diff --git a/404.html b/404.html index a3ba71d0..bc1df3e3 100644 --- a/404.html +++ b/404.html @@ -1,10 +1,10 @@ -Not found

Page not found

Sorry 😔, we couldn’t find what you were looking for.

Go home.

+*/*,:after,:before{border:0 solid}:after,:before{--tw-content:""}html{-webkit-text-size-adjust:100%;font-feature-settings:normal;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;font-variation-settings:normal;line-height:1.5;-moz-tab-size:4;-o-tab-size:4;tab-size:4}body{line-height:inherit;margin:0}hr{border-top-width:1px;color:inherit;height:0}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{border-collapse:collapse;border-color:inherit;text-indent:0}button,input,optgroup,select,textarea{color:inherit;font-family:inherit;font-size:100%;font-weight:inherit;line-height:inherit;margin:0;padding:0}button,select{text-transform:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{color:#9ca3af;opacity:1}input::placeholder,textarea::placeholder{color:#9ca3af;opacity:1}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{height:auto;max-width:100%}[hidden]{display:none}*,:after,:before{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }.container{width:100%}@media (min-width:640px){.container{max-width:640px}}@media (min-width:768px){.container{max-width:768px}}@media (min-width:1024px){.container{max-width:1024px}}@media (min-width:1280px){.container{max-width:1280px}}@media (min-width:1440px){.container{max-width:1440px}}@media (min-width:1900px){.container{max-width:1900px}}@media (min-width:2200px){.container{max-width:2200px}}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.inset-y-0{bottom:0;top:0}.-bottom-2{bottom:-.5rem}.-right-6{right:-1.5rem}.-top-2{top:-.5rem}.bottom-0{bottom:0}.bottom-1{bottom:.25rem}.bottom-\[5\%\]{bottom:5%}.left-0{left:0}.left-1\/2{left:50%}.left-6{left:1.5rem}.right-0{right:0}.right-6{right:1.5rem}.right-\[2\%\]{right:2%}.top-0{top:0}.top-1\/2{top:50%}.top-full{top:100%}.z-10{z-index:10}.z-20{z-index:20}.z-30{z-index:30}.z-50{z-index:50}.z-\[1\]{z-index:1}.m-2{margin:.5rem}.m-4{margin:1rem}.mx-0{margin-left:0;margin-right:0}.mx-12{margin-left:3rem;margin-right:3rem}.mx-2{margin-left:.5rem;margin-right:.5rem}.mx-3{margin-left:.75rem;margin-right:.75rem}.mx-\[-1px\]{margin-left:-1px;margin-right:-1px}.mx-auto{margin-left:auto;margin-right:auto}.my-10{margin-bottom:2.5rem;margin-top:2.5rem}.my-16{margin-bottom:4rem;margin-top:4rem}.my-20{margin-bottom:5rem;margin-top:5rem}.mb-12{margin-bottom:3rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.mr-10{margin-right:2.5rem}.mr-2{margin-right:.5rem}.mr-6{margin-right:1.5rem}.mr-7{margin-right:1.75rem}.mt-16{margin-top:4rem}.inline-block{display:inline-block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.hidden{display:none}.aspect-square{aspect-ratio:1/1}.h-0{height:0}.h-1{height:.25rem}.h-10{height:2.5rem}.h-12{height:3rem}.h-136{height:34rem}.h-14{height:3.5rem}.h-16{height:4rem}.h-160{height:40rem}.h-2\/3{height:66.666667%}.h-20{height:5rem}.h-24{height:6rem}.h-28{height:7rem}.h-32{height:8rem}.h-36{height:9rem}.h-8{height:2rem}.h-96{height:24rem}.h-full{height:100%}.h-min{height:-moz-min-content;height:min-content}.min-h-160{min-height:40rem}.min-h-96{min-height:24rem}.min-h-\[8\.5rem\]{min-height:8.5rem}.w-0{width:0}.w-1{width:.25rem}.w-12{width:3rem}.w-14{width:3.5rem}.w-16{width:4rem}.w-2\/3{width:66.666667%}.w-32{width:8rem}.w-40{width:10rem}.w-56{width:14rem}.w-64{width:16rem}.w-8{width:2rem}.w-\[100\%\]{width:100%}.w-\[352px\]{width:352px}.w-\[85\%\]{width:85%}.w-full{width:100%}.w-max{width:-moz-max-content;width:max-content}.min-w-10{min-width:2.5rem}.max-w-6xl{max-width:72rem}.max-w-7xl{max-width:80rem}.flex-1{flex:1 1 0%}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.flex-grow,.grow{flex-grow:1}.basis-1\/2{flex-basis:50%}.basis-1\/3{flex-basis:33.333333%}.basis-1\/4{flex-basis:25%}.basis-1\/5{flex-basis:20%}.basis-1\/6{flex-basis:16.666667%}.basis-4\/6{flex-basis:66.666667%}.basis-5\/12{flex-basis:41.666667%}.basis-\[48\%\]{flex-basis:48%}.basis-full{flex-basis:100%}.-translate-x-1\/2{--tw-translate-x:-50%}.-translate-x-1\/2,.-translate-y-1\/2{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\/2{--tw-translate-y:-50%}.-translate-y-\[120\%\]{--tw-translate-y:-120%}.-translate-y-\[120\%\],.translate-y-0{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-0{--tw-translate-y:0px}.translate-y-full{--tw-translate-y:100%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes spin{to{transform:rotate(1turn)}}.animate-spin{animation:spin 1s linear infinite}.cursor-pointer{cursor:pointer}.touch-manipulation{touch-action:manipulation}.resize{resize:both}.list-inside{list-style-position:inside}.list-disc{list-style-type:disc}.columns-1{-moz-columns:1;column-count:1}.break-inside-avoid{-moz-column-break-inside:avoid;break-inside:avoid}.flex-row{flex-direction:row}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.flex-nowrap{flex-wrap:nowrap}.content-center{align-content:center}.items-start{align-items:flex-start}.items-center{align-items:center}.items-stretch{align-items:stretch}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.justify-around{justify-content:space-around}.justify-evenly{justify-content:space-evenly}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(.25rem*var(--tw-space-y-reverse));margin-top:calc(.25rem*(1 - var(--tw-space-y-reverse)))}.overflow-hidden{overflow:hidden}.whitespace-nowrap{white-space:nowrap}.rounded-2xl{border-radius:1rem}.rounded-full{border-radius:9999px}.rounded-t-2xl{border-top-left-radius:1rem;border-top-right-radius:1rem}.border{border-width:1px}.border-2{border-width:2px}.border-\[3px\]{border-width:3px}.border-b-2{border-bottom-width:2px}.border-b-4,.border-b-\[4px\]{border-bottom-width:4px}.border-r-8{border-right-width:8px}.border-t-4{border-top-width:4px}.border-solid{border-style:solid}.border-dashed{border-style:dashed}.border-main-10{--tw-border-opacity:1;border-color:rgb(143 143 143/var(--tw-border-opacity))}.border-main-100{--tw-border-opacity:1;border-color:rgb(0 0 0/var(--tw-border-opacity))}.border-secondary-100{--tw-border-opacity:1;border-color:rgb(255 255 255/var(--tw-border-opacity))}.border-secondary-30{--tw-border-opacity:1;border-color:rgb(231 231 231/var(--tw-border-opacity))}.bg-main-100{--tw-bg-opacity:1;background-color:rgb(0 0 0/var(--tw-bg-opacity))}.bg-secondary-10{--tw-bg-opacity:1;background-color:rgb(209 209 209/var(--tw-bg-opacity))}.bg-secondary-100{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity))}.bg-secondary-70{--tw-bg-opacity:1;background-color:rgb(245 245 245/var(--tw-bg-opacity))}.fill-main-100{fill:#000}.object-contain{-o-object-fit:contain;object-fit:contain}.object-cover{-o-object-fit:cover;object-fit:cover}.p-1{padding:.25rem}.p-10{padding:2.5rem}.p-12{padding:3rem}.p-2{padding:.5rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-0{padding-left:0;padding-right:0}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.py-1{padding-bottom:.25rem;padding-top:.25rem}.py-12{padding-bottom:3rem;padding-top:3rem}.py-14{padding-bottom:3.5rem;padding-top:3.5rem}.py-20{padding-bottom:5rem;padding-top:5rem}.py-32{padding-bottom:8rem;padding-top:8rem}.py-48{padding-bottom:12rem;padding-top:12rem}.pb-10{padding-bottom:2.5rem}.pb-24{padding-bottom:6rem}.pb-3{padding-bottom:.75rem}.pb-4{padding-bottom:1rem}.pb-5{padding-bottom:1.25rem}.pb-6{padding-bottom:1.5rem}.pb-9{padding-bottom:2.25rem}.pl-4{padding-left:1rem}.pr-11{padding-right:2.75rem}.pr-16{padding-right:4rem}.pr-8{padding-right:2rem}.pt-14{padding-top:3.5rem}.pt-2{padding-top:.5rem}.pt-6{padding-top:1.5rem}.text-center{text-align:center}.text-end{text-align:end}.font-\[\'Rubik_Glitch\'\]{font-family:Rubik Glitch}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-5xl{font-size:3rem;line-height:1}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.font-black{font-weight:900}.font-bold{font-weight:700}.font-extrabold{font-weight:800}.font-light{font-weight:300}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.italic{font-style:italic}.leading-7{line-height:1.75rem}.leading-\[52px\]{line-height:52px}.text-main-10{--tw-text-opacity:1;color:rgb(143 143 143/var(--tw-text-opacity))}.text-main-100{--tw-text-opacity:1;color:rgb(0 0 0/var(--tw-text-opacity))}.text-main-70{--tw-text-opacity:1;color:rgb(61 61 61/var(--tw-text-opacity))}.text-secondary-10{--tw-text-opacity:1;color:rgb(209 209 209/var(--tw-text-opacity))}.text-secondary-100{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity))}.text-secondary-30{--tw-text-opacity:1;color:rgb(231 231 231/var(--tw-text-opacity))}.underline{text-decoration-line:underline}.opacity-50{opacity:.5}.shadow-lg{--tw-shadow:0 10px 15px -3px rgba(0,0,0,.1),0 4px 6px -4px rgba(0,0,0,.1);--tw-shadow-colored:0 10px 15px -3px var(--tw-shadow-color),0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.shadow-main-100{--tw-shadow-color:#000;--tw-shadow:var(--tw-shadow-colored)}.brightness-0{--tw-brightness:brightness(0)}.brightness-0,.grayscale{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.grayscale{--tw-grayscale:grayscale(100%)}.invert{--tw-invert:invert(100%)}.filter,.invert{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition{transition-duration:.15s;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,-webkit-backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter,-webkit-backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1)}.transition-all{transition-duration:.15s;transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1)}.duration-1000{transition-duration:1s}.duration-300{transition-duration:.3s}.duration-500{transition-duration:.5s}.ease-linear{transition-timing-function:linear}.after\:h-1:after{content:var(--tw-content);height:.25rem}.after\:h-1\.5:after{content:var(--tw-content);height:.375rem}.after\:w-full:after{content:var(--tw-content);width:100%}.after\:bg-main-10:after{--tw-bg-opacity:1;background-color:rgb(143 143 143/var(--tw-bg-opacity));content:var(--tw-content)}.after\:bg-main-100:after{--tw-bg-opacity:1;background-color:rgb(0 0 0/var(--tw-bg-opacity));content:var(--tw-content)}.after\:content-\[\'\'\]:after{--tw-content:"";content:var(--tw-content)}.first\:mt-0:first-child{margin-top:0}.first\:mt-36:first-child{margin-top:9rem}.hover\:bg-main-100:hover{--tw-bg-opacity:1;background-color:rgb(0 0 0/var(--tw-bg-opacity))}.hover\:bg-main-70:hover{--tw-bg-opacity:1;background-color:rgb(61 61 61/var(--tw-bg-opacity))}.hover\:bg-secondary-100:hover{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity))}.hover\:bg-secondary-30:hover{--tw-bg-opacity:1;background-color:rgb(231 231 231/var(--tw-bg-opacity))}.hover\:bg-secondary-70:hover{--tw-bg-opacity:1;background-color:rgb(245 245 245/var(--tw-bg-opacity))}.hover\:text-main-10:hover{--tw-text-opacity:1;color:rgb(143 143 143/var(--tw-text-opacity))}.hover\:text-secondary-10:hover{--tw-text-opacity:1;color:rgb(209 209 209/var(--tw-text-opacity))}.hover\:text-secondary-100:hover{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity))}.hover\:outline-main-100:hover{outline-color:#000}.hover\:outline-secondary-100:hover{outline-color:#fff}.hover\:invert:hover{--tw-invert:invert(100%);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.disabled\:opacity-30:disabled{opacity:.3}@media (prefers-color-scheme:dark){.dark\:text-secondary-10{--tw-text-opacity:1;color:rgb(209 209 209/var(--tw-text-opacity))}}@media (min-width:640px){.sm\:mb-0{margin-bottom:0}.sm\:mt-0{margin-top:0}.sm\:inline{display:inline}.sm\:flex{display:flex}.sm\:hidden{display:none}.sm\:basis-2\/5{flex-basis:40%}.sm\:basis-3\/5{flex-basis:60%}.sm\:basis-5\/6{flex-basis:83.333333%}.sm\:flex-row{flex-direction:row}.sm\:items-stretch{align-items:stretch}.sm\:px-5{padding-left:1.25rem;padding-right:1.25rem}.sm\:pb-10{padding-bottom:2.5rem}.sm\:text-start{text-align:start}.sm\:text-3xl{font-size:1.875rem;line-height:2.25rem}.sm\:text-4xl{font-size:2.25rem;line-height:2.5rem}.sm\:text-5xl{font-size:3rem;line-height:1}.sm\:text-6xl{font-size:3.75rem;line-height:1}.sm\:last\:hidden:last-child{display:none}}@media (min-width:768px){.md\:left-auto{left:auto}.md\:top-auto{top:auto}.md\:z-0{z-index:0}.md\:m-12{margin:3rem}.md\:-my-2{margin-bottom:-.5rem;margin-top:-.5rem}.md\:mx-3{margin-left:.75rem;margin-right:.75rem}.md\:-ms-6{margin-inline-start:-1.5rem}.md\:block{display:block}.md\:flex{display:flex}.md\:w-1\/2{width:50%}.md\:w-\[400px\]{width:400px}.md\:basis-1\/3{flex-basis:33.333333%}.md\:basis-1\/4{flex-basis:25%}.md\:basis-3\/4{flex-basis:75%}.md\:basis-4\/6{flex-basis:66.666667%}.md\:basis-5\/6{flex-basis:83.333333%}.md\:basis-\[31\%\]{flex-basis:31%}.md\:translate-x-full{--tw-translate-x:100%}.md\:translate-x-full,.md\:translate-y-0{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.md\:translate-y-0{--tw-translate-y:0px}.md\:columns-2{-moz-columns:2;column-count:2}.md\:flex-row{flex-direction:row}.md\:p-12{padding:3rem}.md\:px-40{padding-left:10rem;padding-right:10rem}.md\:px-7{padding-left:1.75rem;padding-right:1.75rem}.md\:py-24{padding-bottom:6rem;padding-top:6rem}.md\:pb-0{padding-bottom:0}.md\:pb-10{padding-bottom:2.5rem}.md\:pb-16{padding-bottom:4rem}.md\:pt-10{padding-top:2.5rem}.md\:text-start{text-align:start}.md\:text-3xl{font-size:1.875rem;line-height:2.25rem}.md\:text-5xl{font-size:3rem;line-height:1}.md\:text-6xl{font-size:3.75rem;line-height:1}.md\:leading-10{line-height:2.5rem}.md\:first\:mt-0:first-child{margin-top:0}.md\:last\:mb-0:last-child{margin-bottom:0}.md\:last\:flex:last-child{display:flex}.md\:odd\:ms-6:nth-child(odd){margin-inline-start:1.5rem}.md\:odd\:flex-row-reverse:nth-child(odd){flex-direction:row-reverse}.md\:even\:translate-x-full:nth-child(2n){--tw-translate-x:100%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}}@media (min-width:1024px){.lg\:flex{display:flex}.lg\:hidden{display:none}.lg\:h-full{height:100%}.lg\:w-1\/2{width:50%}.lg\:basis-1\/2{flex-basis:50%}.lg\:basis-2\/5{flex-basis:40%}.lg\:basis-4\/6{flex-basis:66.666667%}.lg\:flex-row{flex-direction:row}.lg\:justify-between{justify-content:space-between}.lg\:py-0{padding-bottom:0;padding-top:0}.lg\:text-start{text-align:start}}@media (min-width:1280px){.xl\:w-\[480px\]{width:480px}.xl\:basis-1\/3{flex-basis:33.333333%}.xl\:basis-2\/3{flex-basis:66.666667%}.xl\:basis-2\/5{flex-basis:40%}}@media (min-width:1900px){.\33xl\:w-\[576px\]{width:576px}.\33xl\:basis-1\/3{flex-basis:33.333333%}}@media (min-width:2200px){.\34xl\:basis-1\/4{flex-basis:25%}}*{border:0;margin:0;padding:0}*,:after,:before{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}:active,:focus,a:active,a:focus{outline:none}aside,footer,header,nav{display:block}body,html{-ms-text-size-adjust:100%;-moz-text-size-adjust:100%;-webkit-text-size-adjust:100%;font-size:100%;font-size:14px;line-height:1;min-height:100vh}button,input,textarea{font-family:inherit}input::-ms-clear{display:none}button{cursor:pointer}button::-moz-focus-inner{border:0;padding:0}a,a:hover,a:visited{text-decoration:none}ul li{list-style:none}img{vertical-align:top}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:400}*{font-family:Urbanist,Helvetica,Arial,sans-serif}div.single-post h3{font-size:1.875rem;font-weight:600;line-height:2.25rem;padding-bottom:2rem}div.single-post p{padding-bottom:3rem;text-align:justify;text-indent:2.5rem}div.single-post h4,div.single-post p{font-size:1.5rem;font-weight:500;line-height:2rem}div.single-post ul{padding-bottom:3rem;padding-left:1rem}div.single-post ul li{list-style-position:inside;list-style-type:disc}div.single-post ol{padding-bottom:.5rem;padding-left:1rem}div.single-post ol li{list-style-position:inside;list-style-type:decimal}div.single-post span.gatsby-resp-image-wrapper{margin:1.5rem!important;width:100%!important}div.single-post span.gatsby-resp-image-wrapper:nth-child(odd){float:left!important;margin-left:0!important}div.single-post span.gatsby-resp-image-wrapper:nth-child(2n){float:right!important;margin-right:0!important}@media (min-width:1024px){div.single-post span.gatsby-resp-image-wrapper{margin:3.5rem!important;width:50%!important}}div.single-post img{border-radius:1rem}div.single-post pre{--tw-bg-opacity:1;background-color:rgb(245 245 245/var(--tw-bg-opacity));font-size:1rem;line-height:1rem;padding:1.5rem;white-space:pre-wrap}div.service-preview{background:linear-gradient(#000 0 0) padding-box,linear-gradient(90deg,#fff 0 0) border-box}div.service-preview:hover{background:#000}div.service-preview p{padding-top:1.75rem}.gradient-border{background:linear-gradient(#fff 0 0) padding-box,linear-gradient(90deg,#fff,#000 50%,#fff) border-box}div.team-member:hover div.line{width:100%}div.applied-tech:hover div.line{height:100%}div.review-body p{padding-top:1.25rem}div.review-body p:first-child{padding-top:0}div.workflow-step:nth-child(odd) div.cover{left:-1.5rem}div.workflow-step:nth-child(2n) p.step-number{z-index:30}@media (min-width:768px){div.workflow-step:nth-child(2n) p.step-number{--tw-translate-x:-100%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}}div.why-us-card p{text-align:justify}div.why-us-card:hover div.line{height:100%}Not found

Page not found

Sorry 😔, we couldn’t find what you were looking for.

Go home.

- \ No newline at end of file + \ No newline at end of file diff --git a/404/index.html b/404/index.html index b28df3c8..35db288c 100644 --- a/404/index.html +++ b/404/index.html @@ -1,10 +1,10 @@ -Not found

Page not found

Sorry 😔, we couldn’t find what you were looking for.

Go home.

+*/*,:after,:before{border:0 solid}:after,:before{--tw-content:""}html{-webkit-text-size-adjust:100%;font-feature-settings:normal;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;font-variation-settings:normal;line-height:1.5;-moz-tab-size:4;-o-tab-size:4;tab-size:4}body{line-height:inherit;margin:0}hr{border-top-width:1px;color:inherit;height:0}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{border-collapse:collapse;border-color:inherit;text-indent:0}button,input,optgroup,select,textarea{color:inherit;font-family:inherit;font-size:100%;font-weight:inherit;line-height:inherit;margin:0;padding:0}button,select{text-transform:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{color:#9ca3af;opacity:1}input::placeholder,textarea::placeholder{color:#9ca3af;opacity:1}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{height:auto;max-width:100%}[hidden]{display:none}*,:after,:before{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }.container{width:100%}@media (min-width:640px){.container{max-width:640px}}@media (min-width:768px){.container{max-width:768px}}@media (min-width:1024px){.container{max-width:1024px}}@media (min-width:1280px){.container{max-width:1280px}}@media (min-width:1440px){.container{max-width:1440px}}@media (min-width:1900px){.container{max-width:1900px}}@media (min-width:2200px){.container{max-width:2200px}}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.inset-y-0{bottom:0;top:0}.-bottom-2{bottom:-.5rem}.-right-6{right:-1.5rem}.-top-2{top:-.5rem}.bottom-0{bottom:0}.bottom-1{bottom:.25rem}.bottom-\[5\%\]{bottom:5%}.left-0{left:0}.left-1\/2{left:50%}.left-6{left:1.5rem}.right-0{right:0}.right-6{right:1.5rem}.right-\[2\%\]{right:2%}.top-0{top:0}.top-1\/2{top:50%}.top-full{top:100%}.z-10{z-index:10}.z-20{z-index:20}.z-30{z-index:30}.z-50{z-index:50}.z-\[1\]{z-index:1}.m-2{margin:.5rem}.m-4{margin:1rem}.mx-0{margin-left:0;margin-right:0}.mx-12{margin-left:3rem;margin-right:3rem}.mx-2{margin-left:.5rem;margin-right:.5rem}.mx-3{margin-left:.75rem;margin-right:.75rem}.mx-\[-1px\]{margin-left:-1px;margin-right:-1px}.mx-auto{margin-left:auto;margin-right:auto}.my-10{margin-bottom:2.5rem;margin-top:2.5rem}.my-16{margin-bottom:4rem;margin-top:4rem}.my-20{margin-bottom:5rem;margin-top:5rem}.mb-12{margin-bottom:3rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.mr-10{margin-right:2.5rem}.mr-2{margin-right:.5rem}.mr-6{margin-right:1.5rem}.mr-7{margin-right:1.75rem}.mt-16{margin-top:4rem}.inline-block{display:inline-block}.inline{display:inline}.flex{display:flex}.inline-flex{display:inline-flex}.hidden{display:none}.aspect-square{aspect-ratio:1/1}.h-0{height:0}.h-1{height:.25rem}.h-10{height:2.5rem}.h-12{height:3rem}.h-136{height:34rem}.h-14{height:3.5rem}.h-16{height:4rem}.h-160{height:40rem}.h-2\/3{height:66.666667%}.h-20{height:5rem}.h-24{height:6rem}.h-28{height:7rem}.h-32{height:8rem}.h-36{height:9rem}.h-8{height:2rem}.h-96{height:24rem}.h-full{height:100%}.h-min{height:-moz-min-content;height:min-content}.min-h-160{min-height:40rem}.min-h-96{min-height:24rem}.min-h-\[8\.5rem\]{min-height:8.5rem}.w-0{width:0}.w-1{width:.25rem}.w-12{width:3rem}.w-14{width:3.5rem}.w-16{width:4rem}.w-2\/3{width:66.666667%}.w-32{width:8rem}.w-40{width:10rem}.w-56{width:14rem}.w-64{width:16rem}.w-8{width:2rem}.w-\[100\%\]{width:100%}.w-\[352px\]{width:352px}.w-\[85\%\]{width:85%}.w-full{width:100%}.w-max{width:-moz-max-content;width:max-content}.min-w-10{min-width:2.5rem}.max-w-6xl{max-width:72rem}.max-w-7xl{max-width:80rem}.flex-1{flex:1 1 0%}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.flex-grow,.grow{flex-grow:1}.basis-1\/2{flex-basis:50%}.basis-1\/3{flex-basis:33.333333%}.basis-1\/4{flex-basis:25%}.basis-1\/5{flex-basis:20%}.basis-1\/6{flex-basis:16.666667%}.basis-4\/6{flex-basis:66.666667%}.basis-5\/12{flex-basis:41.666667%}.basis-\[48\%\]{flex-basis:48%}.basis-full{flex-basis:100%}.-translate-x-1\/2{--tw-translate-x:-50%}.-translate-x-1\/2,.-translate-y-1\/2{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.-translate-y-1\/2{--tw-translate-y:-50%}.-translate-y-\[120\%\]{--tw-translate-y:-120%}.-translate-y-\[120\%\],.translate-y-0{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-0{--tw-translate-y:0px}.translate-y-full{--tw-translate-y:100%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes spin{to{transform:rotate(1turn)}}.animate-spin{animation:spin 1s linear infinite}.cursor-pointer{cursor:pointer}.touch-manipulation{touch-action:manipulation}.resize{resize:both}.list-inside{list-style-position:inside}.list-disc{list-style-type:disc}.columns-1{-moz-columns:1;column-count:1}.break-inside-avoid{-moz-column-break-inside:avoid;break-inside:avoid}.flex-row{flex-direction:row}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.flex-nowrap{flex-wrap:nowrap}.content-center{align-content:center}.items-start{align-items:flex-start}.items-center{align-items:center}.items-stretch{align-items:stretch}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.justify-around{justify-content:space-around}.justify-evenly{justify-content:space-evenly}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(.25rem*var(--tw-space-y-reverse));margin-top:calc(.25rem*(1 - var(--tw-space-y-reverse)))}.overflow-hidden{overflow:hidden}.whitespace-nowrap{white-space:nowrap}.rounded-2xl{border-radius:1rem}.rounded-full{border-radius:9999px}.rounded-t-2xl{border-top-left-radius:1rem;border-top-right-radius:1rem}.border{border-width:1px}.border-2{border-width:2px}.border-\[3px\]{border-width:3px}.border-b-2{border-bottom-width:2px}.border-b-4,.border-b-\[4px\]{border-bottom-width:4px}.border-r-8{border-right-width:8px}.border-t-4{border-top-width:4px}.border-solid{border-style:solid}.border-dashed{border-style:dashed}.border-main-10{--tw-border-opacity:1;border-color:rgb(143 143 143/var(--tw-border-opacity))}.border-main-100{--tw-border-opacity:1;border-color:rgb(0 0 0/var(--tw-border-opacity))}.border-secondary-100{--tw-border-opacity:1;border-color:rgb(255 255 255/var(--tw-border-opacity))}.border-secondary-30{--tw-border-opacity:1;border-color:rgb(231 231 231/var(--tw-border-opacity))}.bg-main-100{--tw-bg-opacity:1;background-color:rgb(0 0 0/var(--tw-bg-opacity))}.bg-secondary-10{--tw-bg-opacity:1;background-color:rgb(209 209 209/var(--tw-bg-opacity))}.bg-secondary-100{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity))}.bg-secondary-70{--tw-bg-opacity:1;background-color:rgb(245 245 245/var(--tw-bg-opacity))}.fill-main-100{fill:#000}.object-contain{-o-object-fit:contain;object-fit:contain}.object-cover{-o-object-fit:cover;object-fit:cover}.p-1{padding:.25rem}.p-10{padding:2.5rem}.p-12{padding:3rem}.p-2{padding:.5rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-0{padding-left:0;padding-right:0}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.py-1{padding-bottom:.25rem;padding-top:.25rem}.py-12{padding-bottom:3rem;padding-top:3rem}.py-14{padding-bottom:3.5rem;padding-top:3.5rem}.py-20{padding-bottom:5rem;padding-top:5rem}.py-32{padding-bottom:8rem;padding-top:8rem}.py-48{padding-bottom:12rem;padding-top:12rem}.pb-10{padding-bottom:2.5rem}.pb-24{padding-bottom:6rem}.pb-3{padding-bottom:.75rem}.pb-4{padding-bottom:1rem}.pb-5{padding-bottom:1.25rem}.pb-6{padding-bottom:1.5rem}.pb-9{padding-bottom:2.25rem}.pl-4{padding-left:1rem}.pr-11{padding-right:2.75rem}.pr-16{padding-right:4rem}.pr-8{padding-right:2rem}.pt-14{padding-top:3.5rem}.pt-2{padding-top:.5rem}.pt-6{padding-top:1.5rem}.text-center{text-align:center}.text-end{text-align:end}.font-\[\'Rubik_Glitch\'\]{font-family:Rubik Glitch}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-5xl{font-size:3rem;line-height:1}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.font-black{font-weight:900}.font-bold{font-weight:700}.font-extrabold{font-weight:800}.font-light{font-weight:300}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.italic{font-style:italic}.leading-7{line-height:1.75rem}.leading-\[52px\]{line-height:52px}.text-main-10{--tw-text-opacity:1;color:rgb(143 143 143/var(--tw-text-opacity))}.text-main-100{--tw-text-opacity:1;color:rgb(0 0 0/var(--tw-text-opacity))}.text-main-70{--tw-text-opacity:1;color:rgb(61 61 61/var(--tw-text-opacity))}.text-secondary-10{--tw-text-opacity:1;color:rgb(209 209 209/var(--tw-text-opacity))}.text-secondary-100{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity))}.text-secondary-30{--tw-text-opacity:1;color:rgb(231 231 231/var(--tw-text-opacity))}.underline{text-decoration-line:underline}.opacity-50{opacity:.5}.shadow-lg{--tw-shadow:0 10px 15px -3px rgba(0,0,0,.1),0 4px 6px -4px rgba(0,0,0,.1);--tw-shadow-colored:0 10px 15px -3px var(--tw-shadow-color),0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.shadow-main-100{--tw-shadow-color:#000;--tw-shadow:var(--tw-shadow-colored)}.brightness-0{--tw-brightness:brightness(0)}.brightness-0,.grayscale{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.grayscale{--tw-grayscale:grayscale(100%)}.invert{--tw-invert:invert(100%)}.filter,.invert{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition{transition-duration:.15s;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,-webkit-backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter,-webkit-backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1)}.transition-all{transition-duration:.15s;transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1)}.duration-1000{transition-duration:1s}.duration-300{transition-duration:.3s}.duration-500{transition-duration:.5s}.ease-linear{transition-timing-function:linear}.after\:h-1:after{content:var(--tw-content);height:.25rem}.after\:h-1\.5:after{content:var(--tw-content);height:.375rem}.after\:w-full:after{content:var(--tw-content);width:100%}.after\:bg-main-10:after{--tw-bg-opacity:1;background-color:rgb(143 143 143/var(--tw-bg-opacity));content:var(--tw-content)}.after\:bg-main-100:after{--tw-bg-opacity:1;background-color:rgb(0 0 0/var(--tw-bg-opacity));content:var(--tw-content)}.after\:content-\[\'\'\]:after{--tw-content:"";content:var(--tw-content)}.first\:mt-0:first-child{margin-top:0}.first\:mt-36:first-child{margin-top:9rem}.hover\:bg-main-100:hover{--tw-bg-opacity:1;background-color:rgb(0 0 0/var(--tw-bg-opacity))}.hover\:bg-main-70:hover{--tw-bg-opacity:1;background-color:rgb(61 61 61/var(--tw-bg-opacity))}.hover\:bg-secondary-100:hover{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity))}.hover\:bg-secondary-30:hover{--tw-bg-opacity:1;background-color:rgb(231 231 231/var(--tw-bg-opacity))}.hover\:bg-secondary-70:hover{--tw-bg-opacity:1;background-color:rgb(245 245 245/var(--tw-bg-opacity))}.hover\:text-main-10:hover{--tw-text-opacity:1;color:rgb(143 143 143/var(--tw-text-opacity))}.hover\:text-secondary-10:hover{--tw-text-opacity:1;color:rgb(209 209 209/var(--tw-text-opacity))}.hover\:text-secondary-100:hover{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity))}.hover\:outline-main-100:hover{outline-color:#000}.hover\:outline-secondary-100:hover{outline-color:#fff}.hover\:invert:hover{--tw-invert:invert(100%);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.disabled\:opacity-30:disabled{opacity:.3}@media (prefers-color-scheme:dark){.dark\:text-secondary-10{--tw-text-opacity:1;color:rgb(209 209 209/var(--tw-text-opacity))}}@media (min-width:640px){.sm\:mb-0{margin-bottom:0}.sm\:mt-0{margin-top:0}.sm\:inline{display:inline}.sm\:flex{display:flex}.sm\:hidden{display:none}.sm\:basis-2\/5{flex-basis:40%}.sm\:basis-3\/5{flex-basis:60%}.sm\:basis-5\/6{flex-basis:83.333333%}.sm\:flex-row{flex-direction:row}.sm\:items-stretch{align-items:stretch}.sm\:px-5{padding-left:1.25rem;padding-right:1.25rem}.sm\:pb-10{padding-bottom:2.5rem}.sm\:text-start{text-align:start}.sm\:text-3xl{font-size:1.875rem;line-height:2.25rem}.sm\:text-4xl{font-size:2.25rem;line-height:2.5rem}.sm\:text-5xl{font-size:3rem;line-height:1}.sm\:text-6xl{font-size:3.75rem;line-height:1}.sm\:last\:hidden:last-child{display:none}}@media (min-width:768px){.md\:left-auto{left:auto}.md\:top-auto{top:auto}.md\:z-0{z-index:0}.md\:m-12{margin:3rem}.md\:-my-2{margin-bottom:-.5rem;margin-top:-.5rem}.md\:mx-3{margin-left:.75rem;margin-right:.75rem}.md\:-ms-6{margin-inline-start:-1.5rem}.md\:block{display:block}.md\:flex{display:flex}.md\:w-1\/2{width:50%}.md\:w-\[400px\]{width:400px}.md\:basis-1\/3{flex-basis:33.333333%}.md\:basis-1\/4{flex-basis:25%}.md\:basis-3\/4{flex-basis:75%}.md\:basis-4\/6{flex-basis:66.666667%}.md\:basis-5\/6{flex-basis:83.333333%}.md\:basis-\[31\%\]{flex-basis:31%}.md\:translate-x-full{--tw-translate-x:100%}.md\:translate-x-full,.md\:translate-y-0{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.md\:translate-y-0{--tw-translate-y:0px}.md\:columns-2{-moz-columns:2;column-count:2}.md\:flex-row{flex-direction:row}.md\:p-12{padding:3rem}.md\:px-40{padding-left:10rem;padding-right:10rem}.md\:px-7{padding-left:1.75rem;padding-right:1.75rem}.md\:py-24{padding-bottom:6rem;padding-top:6rem}.md\:pb-0{padding-bottom:0}.md\:pb-10{padding-bottom:2.5rem}.md\:pb-16{padding-bottom:4rem}.md\:pt-10{padding-top:2.5rem}.md\:text-start{text-align:start}.md\:text-3xl{font-size:1.875rem;line-height:2.25rem}.md\:text-5xl{font-size:3rem;line-height:1}.md\:text-6xl{font-size:3.75rem;line-height:1}.md\:leading-10{line-height:2.5rem}.md\:first\:mt-0:first-child{margin-top:0}.md\:last\:mb-0:last-child{margin-bottom:0}.md\:last\:flex:last-child{display:flex}.md\:odd\:ms-6:nth-child(odd){margin-inline-start:1.5rem}.md\:odd\:flex-row-reverse:nth-child(odd){flex-direction:row-reverse}.md\:even\:translate-x-full:nth-child(2n){--tw-translate-x:100%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}}@media (min-width:1024px){.lg\:flex{display:flex}.lg\:hidden{display:none}.lg\:h-full{height:100%}.lg\:w-1\/2{width:50%}.lg\:basis-1\/2{flex-basis:50%}.lg\:basis-2\/5{flex-basis:40%}.lg\:basis-4\/6{flex-basis:66.666667%}.lg\:flex-row{flex-direction:row}.lg\:justify-between{justify-content:space-between}.lg\:py-0{padding-bottom:0;padding-top:0}.lg\:text-start{text-align:start}}@media (min-width:1280px){.xl\:w-\[480px\]{width:480px}.xl\:basis-1\/3{flex-basis:33.333333%}.xl\:basis-2\/3{flex-basis:66.666667%}.xl\:basis-2\/5{flex-basis:40%}}@media (min-width:1900px){.\33xl\:w-\[576px\]{width:576px}.\33xl\:basis-1\/3{flex-basis:33.333333%}}@media (min-width:2200px){.\34xl\:basis-1\/4{flex-basis:25%}}*{border:0;margin:0;padding:0}*,:after,:before{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}:active,:focus,a:active,a:focus{outline:none}aside,footer,header,nav{display:block}body,html{-ms-text-size-adjust:100%;-moz-text-size-adjust:100%;-webkit-text-size-adjust:100%;font-size:100%;font-size:14px;line-height:1;min-height:100vh}button,input,textarea{font-family:inherit}input::-ms-clear{display:none}button{cursor:pointer}button::-moz-focus-inner{border:0;padding:0}a,a:hover,a:visited{text-decoration:none}ul li{list-style:none}img{vertical-align:top}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:400}*{font-family:Urbanist,Helvetica,Arial,sans-serif}div.single-post h3{font-size:1.875rem;font-weight:600;line-height:2.25rem;padding-bottom:2rem}div.single-post p{padding-bottom:3rem;text-align:justify;text-indent:2.5rem}div.single-post h4,div.single-post p{font-size:1.5rem;font-weight:500;line-height:2rem}div.single-post ul{padding-bottom:3rem;padding-left:1rem}div.single-post ul li{list-style-position:inside;list-style-type:disc}div.single-post ol{padding-bottom:.5rem;padding-left:1rem}div.single-post ol li{list-style-position:inside;list-style-type:decimal}div.single-post span.gatsby-resp-image-wrapper{margin:1.5rem!important;width:100%!important}div.single-post span.gatsby-resp-image-wrapper:nth-child(odd){float:left!important;margin-left:0!important}div.single-post span.gatsby-resp-image-wrapper:nth-child(2n){float:right!important;margin-right:0!important}@media (min-width:1024px){div.single-post span.gatsby-resp-image-wrapper{margin:3.5rem!important;width:50%!important}}div.single-post img{border-radius:1rem}div.single-post pre{--tw-bg-opacity:1;background-color:rgb(245 245 245/var(--tw-bg-opacity));font-size:1rem;line-height:1rem;padding:1.5rem;white-space:pre-wrap}div.service-preview{background:linear-gradient(#000 0 0) padding-box,linear-gradient(90deg,#fff 0 0) border-box}div.service-preview:hover{background:#000}div.service-preview p{padding-top:1.75rem}.gradient-border{background:linear-gradient(#fff 0 0) padding-box,linear-gradient(90deg,#fff,#000 50%,#fff) border-box}div.team-member:hover div.line{width:100%}div.applied-tech:hover div.line{height:100%}div.review-body p{padding-top:1.25rem}div.review-body p:first-child{padding-top:0}div.workflow-step:nth-child(odd) div.cover{left:-1.5rem}div.workflow-step:nth-child(2n) p.step-number{z-index:30}@media (min-width:768px){div.workflow-step:nth-child(2n) p.step-number{--tw-translate-x:-100%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}}div.why-us-card p{text-align:justify}div.why-us-card:hover div.line{height:100%}Not found

Page not found

Sorry 😔, we couldn’t find what you were looking for.

Go home.

- \ No newline at end of file + \ No newline at end of file diff --git a/475-f022f6fdbc411815273f.js b/475-1b51ef15275da40692d5.js similarity index 99% rename from 475-f022f6fdbc411815273f.js rename to 475-1b51ef15275da40692d5.js index 49b6199c..5d8ab00d 100644 --- a/475-f022f6fdbc411815273f.js +++ b/475-1b51ef15275da40692d5.js @@ -1,2 +1,2 @@ -!function(){"use strict";var e,t,i={4201:function(e,t,i){var n=i(8426),s=i(9802),r=i(8139),o=i(5412),a=i(2922),l=i(646);class h{constructor(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new r.y$,e.parameter?(this.trigger=e.trigger,this._triggerParameter=e.parameter):e.trigger?this.trigger=e.trigger:this.trigger=e,this._nextActiveAction=this,this._condition=t}_prepare(){}getTriggerParameter(){return this._triggerParameter}setTriggerParameter(e){this._triggerParameter=e}_evaluateConditionForCurrentFrame(){const e=this._condition;if(!e)return!0;const t=this._actionManager.getScene().getRenderId();return e._evaluationId!==t&&(e._evaluationId=t,e._currentResult=e.isValid()),e._currentResult}_executeCurrent(e){this._evaluateConditionForCurrentFrame()&&(this.onBeforeExecuteObservable.notifyObservers(this),this._nextActiveAction.execute(e),this.skipToNextActiveAction())}execute(e){}skipToNextActiveAction(){this._nextActiveAction._child?(this._nextActiveAction._child._actionManager||(this._nextActiveAction._child._actionManager=this._actionManager),this._nextActiveAction=this._nextActiveAction._child):this._nextActiveAction=this}then(e){return this._child=e,e._actionManager=this._actionManager,e._prepare(),e}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(e){}_serialize(e,t){const i={type:1,children:[],name:e.name,properties:e.properties||[]};if(this._child&&this._child.serialize(i),this._condition){const e=this._condition.serialize();return e.children.push(i),t&&t.children.push(e),e}return t&&t.children.push(i),i}}h._SerializeValueAsString=e=>"number"==typeof e?e.toString():"boolean"==typeof e?e?"true":"false":e instanceof o.FM?e.x+", "+e.y:e instanceof o.P?e.x+", "+e.y+", "+e.z:e instanceof a.Wo?e.r+", "+e.g+", "+e.b:e instanceof a.HE?e.r+", "+e.g+", "+e.b+", "+e.a:e,h._GetTargetProperty=e=>({name:"target",targetType:e._isMesh?"MeshProperties":e._isLight?"LightProperties":e._isCamera?"CameraProperties":e._isMaterial?"MaterialProperties":"SceneProperties",value:e._isScene?"Scene":e.name}),(0,l.H)("BABYLON.Action",h);var c=i(9372);class d{constructor(e){this._actionManager=e}isValid(){return!0}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(){}_serialize(e){return{type:2,children:[],name:e.name,properties:e.properties}}}class u extends d{static get IsEqual(){return u._IsEqual}static get IsDifferent(){return u._IsDifferent}static get IsGreater(){return u._IsGreater}static get IsLesser(){return u._IsLesser}constructor(e,t,i,n,s=u.IsEqual){super(e),this.propertyPath=i,this.value=n,this.operator=s,this._target=t,this._effectiveTarget=this._getEffectiveTarget(t,this.propertyPath),this._property=this._getProperty(this.propertyPath)}isValid(){switch(this.operator){case u.IsGreater:return this._effectiveTarget[this._property]>this.value;case u.IsLesser:return this._effectiveTarget[this._property]-1&&this._scene.actionManagers.splice(e,1)}getScene(){return this._scene}hasSpecificTriggers(e){for(let t=0;t-1)return!0}return!1}hasSpecificTriggers2(e,t){for(let i=0;i=v.OnPickTrigger&&t.trigger<=v.OnPointerOutTrigger)return!0}return!1}get hasPickTriggers(){for(let e=0;e=v.OnPickTrigger&&t.trigger<=v.OnPickUpTrigger)return!0}return!1}registerAction(e){return e.trigger===v.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(p.Y.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,v.Triggers[e.trigger]?v.Triggers[e.trigger]++:v.Triggers[e.trigger]=1,e._actionManager=this,e._prepare(),e)}unregisterAction(e){const t=this.actions.indexOf(e);return-1!==t&&(this.actions.splice(t,1),v.Triggers[e.trigger]-=1,0===v.Triggers[e.trigger]&&delete v.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0)}processTrigger(e,t){for(let i=0;i{if(null===n){const e=parseFloat(t);return"true"===t||"false"===t?"true"===t:isNaN(e)?t:e}const s=n.split("."),r=t.split(",");for(let o=0;o{if(e.detached)return;const c=new Array;let p=null,_=null;const m=e.combine&&e.combine.length>0;if(2===e.type?c.push(n):c.push(t),m){const t=new Array;for(let i=0;i{const i=(0,l.q)("BABYLON."+e);return i&&new i(...t)})(e.name,c);if(g instanceof d&&null!==o){const e=new f(t,o);a?a.then(e):n.registerAction(e),a=e}null===h?g instanceof d?(o=g,g=a):(o=null,a?a.then(g):n.registerAction(g)):h.push(g);for(let i=0;i0){const e=n.properties[0].value,s=null===n.properties[0].targetType?e:i.getMeshByName(e);s._meshId&&(s.mesh=i.getMeshById(s._meshId)),t={trigger:v[n.name],parameter:s}}else t=v[n.name];for(let e=0;e=0?t:0;let a=0;const l=r._keys[0];let h=r._keys.length-1;const c=r._keys[h],d={referenceValue:l.value,referencePosition:o.jp.Vector3[0],referenceQuaternion:o.jp.Quaternion[0],referenceScaling:o.jp.Vector3[1],keyPosition:o.jp.Vector3[2],keyQuaternion:o.jp.Quaternion[1],keyScaling:o.jp.Vector3[3]};let u=!1,p=l.frame,f=c.frame;if(i){const e=r.getRange(i);e&&(p=e.from,f=e.to)}let _=l.frame===p,m=c.frame===f;if(1===r._keys.length){const e=r._getKeyValue(r._keys[0]);d.referenceValue=e.clone?e.clone():e,u=!0}else if(t<=l.frame){const e=r._getKeyValue(l.value);d.referenceValue=e.clone?e.clone():e,u=!0}else if(t>=c.frame){const e=r._getKeyValue(c.value);d.referenceValue=e.clone?e.clone():e,u=!0}let g=0;for(;!u||!_||!m&&g=e.frame&&t<=i.frame){let n;if(t===e.frame)n=r._getKeyValue(e.value);else if(t===i.frame)n=r._getKeyValue(i.value);else{const e={key:g,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT};n=r._interpolate(t,e)}d.referenceValue=n.clone?n.clone():n,u=!0}if(!_&&p>=e.frame&&p<=i.frame){if(p===e.frame)a=g;else if(p===i.frame)a=g+1;else{const e={key:g,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT},t=r._interpolate(p,e),i={frame:p,value:t.clone?t.clone():t};r._keys.splice(g+1,0,i),a=g+1}_=!0}if(!m&&f>=e.frame&&f<=i.frame){if(f===e.frame)h=g;else if(f===i.frame)h=g+1;else{const e={key:g,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT},t=r._interpolate(f,e),i={frame:f,value:t.clone?t.clone():t};r._keys.splice(g+1,0,i),h=g+1}m=!0}g++}for(r.dataType===A.ANIMATIONTYPE_QUATERNION?d.referenceValue.normalize().conjugateInPlace():r.dataType===A.ANIMATIONTYPE_MATRIX&&(d.referenceValue.decompose(d.referenceScaling,d.referenceQuaternion,d.referencePosition),d.referenceQuaternion.normalize().conjugateInPlace()),g=a;g<=h;g++){const e=r._keys[g];if(!g||r.dataType===A.ANIMATIONTYPE_FLOAT||e.value!==l.value)switch(r.dataType){case A.ANIMATIONTYPE_MATRIX:e.value.decompose(d.keyScaling,d.keyQuaternion,d.keyPosition),d.keyPosition.subtractInPlace(d.referencePosition),d.keyScaling.divideInPlace(d.referenceScaling),d.referenceQuaternion.multiplyToRef(d.keyQuaternion,d.keyQuaternion),o.y3.ComposeToRef(d.keyScaling,d.keyQuaternion,d.keyPosition,e.value);break;case A.ANIMATIONTYPE_QUATERNION:d.referenceValue.multiplyToRef(e.value,e.value);break;case A.ANIMATIONTYPE_VECTOR2:case A.ANIMATIONTYPE_VECTOR3:case A.ANIMATIONTYPE_COLOR3:case A.ANIMATIONTYPE_COLOR4:e.value.subtractToRef(d.referenceValue,e.value);break;case A.ANIMATIONTYPE_SIZE:e.value.width-=d.referenceValue.width,e.value.height-=d.referenceValue.height;break;default:e.value-=d.referenceValue}}return r}static TransitionTo(e,t,i,n,s,r,o,a=null){if(o<=0)return i[e]=t,a&&a(),null;const l=s*(o/1e3);r.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(r);const h=n.beginAnimation(i,0,l,!1);return h.onAnimationEnd=a,h}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(const e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,n,s,r){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=n,this.loopMode=s,this.enableBlending=r,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===s?A.ANIMATIONLOOPMODE_CYCLE:s,this.uniqueId=A._UniqueIdGenerator++}toString(e){let t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType],t+=", nKeys: "+(this._keys?this._keys.length:"none"),t+=", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";let e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort(((e,t)=>e.frame-t.frame))}removeEvents(e){for(let t=0;t=0;i--)this._keys[i].frame>=e&&this._keys[i].frame<=t&&this._keys.splice(i,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;const i=this._keys,n=i.length;let s=t.key;for(;s>=0&&e=i[s+1].frame;)++s;if(t.key=s,s<0)return this._getKeyValue(i[0].value);if(s+1>n-1)return this._getKeyValue(i[n-1].value);const r=i[s],o=i[s+1],a=this._getKeyValue(r.value),l=this._getKeyValue(o.value);if(r.interpolation===T.STEP)return o.frame>e?a:l;const h=void 0!==r.outTangent&&void 0!==o.inTangent,c=o.frame-r.frame;let d=(e-r.frame)/c;const u=this.getEasingFunction();switch(null!==u&&(d=u.ease(d)),this.dataType){case A.ANIMATIONTYPE_FLOAT:{const e=h?this.floatInterpolateFunctionWithTangents(a,r.outTangent*c,l,o.inTangent*c,d):this.floatInterpolateFunction(a,l,d);switch(t.loopMode){case A.ANIMATIONLOOPMODE_CYCLE:case A.ANIMATIONLOOPMODE_CONSTANT:case A.ANIMATIONLOOPMODE_YOYO:return e;case A.ANIMATIONLOOPMODE_RELATIVE:return t.offsetValue*t.repeatCount+e}break}case A.ANIMATIONTYPE_QUATERNION:{const e=h?this.quaternionInterpolateFunctionWithTangents(a,r.outTangent.scale(c),l,o.inTangent.scale(c),d):this.quaternionInterpolateFunction(a,l,d);switch(t.loopMode){case A.ANIMATIONLOOPMODE_CYCLE:case A.ANIMATIONLOOPMODE_CONSTANT:case A.ANIMATIONLOOPMODE_YOYO:return e;case A.ANIMATIONLOOPMODE_RELATIVE:return e.addInPlace(t.offsetValue.scale(t.repeatCount))}return e}case A.ANIMATIONTYPE_VECTOR3:{const e=h?this.vector3InterpolateFunctionWithTangents(a,r.outTangent.scale(c),l,o.inTangent.scale(c),d):this.vector3InterpolateFunction(a,l,d);switch(t.loopMode){case A.ANIMATIONLOOPMODE_CYCLE:case A.ANIMATIONLOOPMODE_CONSTANT:case A.ANIMATIONLOOPMODE_YOYO:return e;case A.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case A.ANIMATIONTYPE_VECTOR2:{const e=h?this.vector2InterpolateFunctionWithTangents(a,r.outTangent.scale(c),l,o.inTangent.scale(c),d):this.vector2InterpolateFunction(a,l,d);switch(t.loopMode){case A.ANIMATIONLOOPMODE_CYCLE:case A.ANIMATIONLOOPMODE_CONSTANT:case A.ANIMATIONLOOPMODE_YOYO:return e;case A.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case A.ANIMATIONTYPE_SIZE:switch(t.loopMode){case A.ANIMATIONLOOPMODE_CYCLE:case A.ANIMATIONLOOPMODE_CONSTANT:case A.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(a,l,d);case A.ANIMATIONLOOPMODE_RELATIVE:return this.sizeInterpolateFunction(a,l,d).add(t.offsetValue.scale(t.repeatCount))}break;case A.ANIMATIONTYPE_COLOR3:{const e=h?this.color3InterpolateFunctionWithTangents(a,r.outTangent.scale(c),l,o.inTangent.scale(c),d):this.color3InterpolateFunction(a,l,d);switch(t.loopMode){case A.ANIMATIONLOOPMODE_CYCLE:case A.ANIMATIONLOOPMODE_CONSTANT:case A.ANIMATIONLOOPMODE_YOYO:return e;case A.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case A.ANIMATIONTYPE_COLOR4:{const e=h?this.color4InterpolateFunctionWithTangents(a,r.outTangent.scale(c),l,o.inTangent.scale(c),d):this.color4InterpolateFunction(a,l,d);switch(t.loopMode){case A.ANIMATIONLOOPMODE_CYCLE:case A.ANIMATIONLOOPMODE_CONSTANT:case A.ANIMATIONLOOPMODE_YOYO:return e;case A.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case A.ANIMATIONTYPE_MATRIX:switch(t.loopMode){case A.ANIMATIONLOOPMODE_CYCLE:case A.ANIMATIONLOOPMODE_CONSTANT:case A.ANIMATIONLOOPMODE_YOYO:return A.AllowMatricesInterpolation?this.matrixInterpolateFunction(a,l,d,t.workValue):a;case A.ANIMATIONLOOPMODE_RELATIVE:return a}}return 0}matrixInterpolateFunction(e,t,i,n){return A.AllowMatrixDecomposeForInterpolation?n?(o.y3.DecomposeLerpToRef(e,t,i,n),n):o.y3.DecomposeLerp(e,t,i):n?(o.y3.LerpToRef(e,t,i,n),n):o.y3.Lerp(e,t,i)}clone(){const e=new A(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){this._keys=e.slice(0)}serialize(){const e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed;const t=this.dataType;e.keys=[];const i=this.getKeys();for(let n=0;n=2&&(l=t.values[1]),t.values.length>=3&&(h=t.values[2]),t.values.length>=4&&(c=t.values[3]);break;case A.ANIMATIONTYPE_QUATERNION:if(s=o._f.FromArray(t.values),t.values.length>=8){const e=o._f.FromArray(t.values.slice(4,8));e.equals(o._f.Zero())||(l=e)}if(t.values.length>=12){const e=o._f.FromArray(t.values.slice(8,12));e.equals(o._f.Zero())||(h=e)}t.values.length>=13&&(c=t.values[12]);break;case A.ANIMATIONTYPE_MATRIX:s=o.y3.FromArray(t.values),t.values.length>=17&&(c=t.values[16]);break;case A.ANIMATIONTYPE_COLOR3:s=a.Wo.FromArray(t.values),t.values[3]&&(l=a.Wo.FromArray(t.values[3])),t.values[4]&&(h=a.Wo.FromArray(t.values[4])),t.values[5]&&(c=t.values[5]);break;case A.ANIMATIONTYPE_COLOR4:s=a.HE.FromArray(t.values),t.values[4]&&(l=a.HE.FromArray(t.values[4])),t.values[5]&&(h=a.HE.FromArray(t.values[5])),t.values[6]&&(c=a.HE.FromArray(t.values[6]));break;case A.ANIMATIONTYPE_VECTOR3:default:s=o.P.FromArray(t.values),t.values[3]&&(l=o.P.FromArray(t.values[3])),t.values[4]&&(h=o.P.FromArray(t.values[4])),t.values[5]&&(c=t.values[5])}const d={};d.frame=t.frame,d.value=s,null!=l&&(d.inTangent=l),null!=h&&(d.outTangent=h),null!=c&&(d.interpolation=c),n.push(d)}if(t.setKeys(n),e.ranges)for(r=0;r{const s=new y.g;s.addEventListener("readystatechange",(()=>{if(4==s.readyState)if(200==s.status){let t=JSON.parse(s.responseText);if(t.animations&&(t=t.animations),t.length){const e=new Array;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")})),s.open("GET",t),s.send()}))}static ParseFromSnippetAsync(e){return new Promise(((t,i)=>{const n=new y.g;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),s=new Array;for(const t of n.animations){const i=this.Parse(t);i.snippetId=e,s.push(i)}t(s)}else{const n=JSON.parse(i.animation),s=this.Parse(n);s.snippetId=e,t(s)}}else i("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}A._UniqueIdGenerator=0,A.AllowMatricesInterpolation=!1,A.AllowMatrixDecomposeForInterpolation=!0,A.SnippetUrl="https://snippet.babylonjs.com",A.ANIMATIONTYPE_FLOAT=0,A.ANIMATIONTYPE_VECTOR3=1,A.ANIMATIONTYPE_QUATERNION=2,A.ANIMATIONTYPE_MATRIX=3,A.ANIMATIONTYPE_COLOR3=4,A.ANIMATIONTYPE_COLOR4=7,A.ANIMATIONTYPE_VECTOR2=5,A.ANIMATIONTYPE_SIZE=6,A.ANIMATIONLOOPMODE_RELATIVE=0,A.ANIMATIONLOOPMODE_CYCLE=1,A.ANIMATIONLOOPMODE_CONSTANT=2,A.ANIMATIONLOOPMODE_YOYO=4,A.CreateFromSnippetAsync=A.ParseFromSnippetAsync,(0,l.H)("BABYLON.Animation",A),b.N._AnimationRangeFactory=(e,t,i)=>new x(e,t,i);(0,l.H)("BABYLON.InterpolateValueAction",class extends h{constructor(e,t,i,n,s=1e3,o,a,l){super(e,o),this.duration=1e3,this.onInterpolationDoneObservable=new r.y$,this.propertyPath=i,this.value=n,this.duration=s,this.stopOtherAnimations=a,this.onInterpolationDone=l,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){const e=this._actionManager.getScene(),t=[{frame:0,value:this._effectiveTarget[this._property]},{frame:100,value:this.value}];let i;if("number"==typeof this.value)i=A.ANIMATIONTYPE_FLOAT;else if(this.value instanceof a.Wo)i=A.ANIMATIONTYPE_COLOR3;else if(this.value instanceof o.P)i=A.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof o.y3)i=A.ANIMATIONTYPE_MATRIX;else{if(!(this.value instanceof o._f))return void p.Y.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");i=A.ANIMATIONTYPE_QUATERNION}const n=new A("InterpolateValueAction",this._property,1e3/this.duration*100,i,A.ANIMATIONLOOPMODE_CONSTANT);n.setKeys(t),this.stopOtherAnimations&&e.stopAnimation(this._effectiveTarget);e.beginDirectAnimation(this._effectiveTarget,[n],0,100,!1,1,(()=>{this.onInterpolationDoneObservable.notifyObservers(this),this.onInterpolationDone&&this.onInterpolationDone()}))}serialize(e){return super._serialize({name:"InterpolateValueAction",properties:[h._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:h._SerializeValueAsString(this.value)},{name:"duration",value:h._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:h._SerializeValueAsString(this.stopOtherAnimations)||!1}]},e)}});const R=Object.freeze(new o._f(0,0,0,0)),P=Object.freeze(o.P.Zero()),I=Object.freeze(o.FM.Zero()),M=Object.freeze(C.Zero()),O=Object.freeze(a.Wo.Black());class D{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._ratioOffset=0,this._previousDelay=0,this._previousRatio=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===A.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=o.y3.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 s=t.getEvents();s&&s.length>0&&s.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[i[0]];for(let e=1;e-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray)for(let i=0;it[t.length-1].frame&&(e=t[t.length-1].frame);const i=this._events;if(i.length)for(let s=0;sthis._maxFrame)&&(t=this._minFrame),(ithis._maxFrame)&&(i=this._maxFrame);const h=i-t;let c,d,u=e*(o.framePerSecond*s)/1e3+this._ratioOffset,p=0;if(n&&this._animationState.loopMode===A.ANIMATIONLOOPMODE_YOYO){const e=(u-t)/h;u=Math.abs(Math.sin(e*Math.PI))*h+t}if(this._previousDelay=e,this._previousRatio=u,!n&&i>=t&&u>=h)l=!1,p=o._getKeyValue(this._maxValue);else if(!n&&t>=i&&u<=h)l=!1,p=o._getKeyValue(this._minValue);else if(this._animationState.loopMode!==A.ANIMATIONLOOPMODE_CYCLE){const e=i.toString()+t.toString();if(!this._offsetsCache[e]){this._animationState.repeatCount=0,this._animationState.loopMode=A.ANIMATIONLOOPMODE_CYCLE;const n=o._interpolate(t,this._animationState),s=o._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),o.dataType){case A.ANIMATIONTYPE_FLOAT:this._offsetsCache[e]=s-n;break;case A.ANIMATIONTYPE_QUATERNION:case A.ANIMATIONTYPE_VECTOR3:case A.ANIMATIONTYPE_VECTOR2:case A.ANIMATIONTYPE_SIZE:case A.ANIMATIONTYPE_COLOR3:this._offsetsCache[e]=s.subtract(n)}this._highLimitsCache[e]=s}p=this._highLimitsCache[e],c=this._offsetsCache[e]}if(void 0===c)switch(o.dataType){case A.ANIMATIONTYPE_FLOAT:c=0;break;case A.ANIMATIONTYPE_QUATERNION:c=R;break;case A.ANIMATIONTYPE_VECTOR3:c=P;break;case A.ANIMATIONTYPE_VECTOR2:c=I;break;case A.ANIMATIONTYPE_SIZE:c=M;break;case A.ANIMATIONTYPE_COLOR3:c=O}if(this._host&&this._host.syncRoot){const e=this._host.syncRoot;d=t+(i-t)*((e.masterFrame-e.fromFrame)/(e.toFrame-e.fromFrame))}else d=u>0&&t>i||u<0&&t0&&this.currentFrame>d||s<0&&this.currentFrame0?0:o.getKeys().length-1}this._currentFrame=d,this._animationState.repeatCount=0===h?0:u/h>>0,this._animationState.highLimitValue=p,this._animationState.offsetValue=c;const _=o._interpolate(d,this._animationState);if(this.setValue(_,r),f.length)for(let m=0;m0&&d>=f[m].frame&&f[m].frame>=t||h<0&&d<=f[m].frame&&f[m].frame<=t){const e=f[m];e.isDone||(e.onlyOnce&&(f.splice(m,1),m--),e.isDone=!0,e.action(d))}return l||(this._stopped=!0),l}}var N=i(147),F=i(9665),w=i(2554),L=i(5241);class B extends b.N{get _matrix(){return this._compose(),this._localMatrix}set _matrix(e){this._needToCompose=!1,e.updateFlag!==this._localMatrix.updateFlag&&(this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())}constructor(e,t,i=null,n=null,s=null,r=null,a=null){var l;super(e,t.getScene()),this.name=e,this.children=new Array,this.animations=new Array,this._index=null,this._scalingDeterminant=1,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._skeleton=t,this._localMatrix=null!==(l=null==n?void 0:n.clone())&&void 0!==l?l:o.y3.Identity(),this._restMatrix=null!=s?s:this._localMatrix.clone(),this._bindMatrix=null!=r?r:this._localMatrix.clone(),this._index=a,this._absoluteMatrix=new o.y3,this._absoluteBindMatrix=new o.y3,this._absoluteInverseBindMatrix=new o.y3,this._finalMatrix=new o.y3,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(){var e;if(this._linkedTransformNode){const t=o.jp.Vector3[0],i=o.jp.Quaternion[0],n=o.jp.Vector3[1];this.getRestMatrix().decompose(t,i,n),this._linkedTransformNode.position.copyFrom(n),this._linkedTransformNode.rotationQuaternion=null!==(e=this._linkedTransformNode.rotationQuaternion)&&void 0!==e?e:o._f.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(i),this._linkedTransformNode.scaling.copyFrom(t)}else this._matrix=this._restMatrix}getAbsoluteInverseBindMatrix(){return this._absoluteInverseBindMatrix}getInvertedAbsoluteTransform(){return this.getAbsoluteInverseBindMatrix()}getAbsoluteMatrix(){return this._absoluteMatrix}getAbsoluteTransform(){return this._absoluteMatrix}linkTransformNode(e){this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode--,this._linkedTransformNode=e,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode++}getTransformNode(){return this._linkedTransformNode}get position(){return this._decompose(),this._localPosition}set position(e){this._decompose(),this._localPosition.copyFrom(e),this._markAsDirtyAndCompose()}get rotation(){return this.getRotation()}set rotation(e){this.setRotation(e)}get rotationQuaternion(){return this._decompose(),this._localRotation}set rotationQuaternion(e){this.setRotationQuaternion(e)}get scaling(){return this.getScale()}set scaling(e){this.setScale(e)}get animationPropertiesOverride(){return this._skeleton.animationPropertiesOverride}_decompose(){this._needToDecompose&&(this._needToDecompose=!1,this._localScaling||(this._localScaling=o.P.Zero(),this._localRotation=o._f.Zero(),this._localPosition=o.P.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){this._needToCompose&&(this._localScaling?(this._needToCompose=!1,o.y3.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 i=0;i-1&&(this._scene._activeAnimatables.splice(e,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let i=0;i{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(s)}}getAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let i=0;i-1){const 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(n,1),this._raiseOnAnimationEnd())}}else{const e=this._scene._activeAnimatables.indexOf(this);if(e>-1){i||this._scene._activeAnimatables.splice(e,1);const t=this._runtimeAnimations;for(let e=0;e{this.onAnimationEndObservable.add((()=>{e(this)}),void 0,void 0,this,!0)}))}_animate(e){if(this._paused)return this.animationStarted=!1,null===this._pausedDelay&&(this._pausedDelay=e),!0;if(null===this._localDelayOffset?(this._localDelayOffset=e,this._pausedDelay=null):null!==this._pausedDelay&&(this._localDelayOffset+=e-this._pausedDelay,this._pausedDelay=null),null!==this._manualJumpDelay&&(this._localDelayOffset+=this._manualJumpDelay,this._manualJumpDelay=null,this._frameToSyncFromJump=null),this._goToFrame=null,0===this._weight)return!0;let t=!1;const i=this._runtimeAnimations;let n;for(n=0;n0)return;this._animationTimeLast=e}this.deltaTime=this.useConstantAnimationDeltaTime?16:(e-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=e;const t=this._activeAnimatables;if(0===t.length)return;this._animationTime+=this.deltaTime;const i=this._animationTime;for(let n=0;ni&&s>0&&(s*=-1),a&&this.stopAnimation(e,void 0,l),o||(o=new U(this,e,t,i,n,s,r,void 0,h,c));const d=!l||l(e);if(e.animations&&d&&o.appendAnimations(e,e.animations),e.getAnimatables){const c=e.getAnimatables();for(let e=0;en&&r>0)r*=-1;else if(n>i&&r<0){const e=n;n=i,i=e}return new U(this,e,i,n,s,r,o,t,a,l)},N.x.prototype.beginDirectHierarchyAnimation=function(e,t,i,n,s,r,o,a,l,h=!1){const c=e.getDescendants(t),d=[];d.push(this.beginDirectAnimation(e,i,n,s,r,o,a,l,h));for(const u of c)d.push(this.beginDirectAnimation(u,i,n,s,r,o,a,l,h));return d},N.x.prototype.getAnimatableByTarget=function(e){for(let t=0;t0?h:-h,s),l.scaleAndAddToRef(h,i)}s.normalize()}for(let u=0;u0)s.copyFrom(n);else if(1===e.animations.length){if(o._f.SlerpToRef(n,i.currentValue,Math.min(1,e.totalWeight),s),0===e.totalAdditiveWeight)return s}else if(e.animations.length>1){let i,r,a=1;if(e.totalWeight<1){const t=1-e.totalWeight;i=[],r=[],i.push(n),r.push(t)}else{if(2===e.animations.length&&(o._f.SlerpToRef(e.animations[0].currentValue,e.animations[1].currentValue,e.animations[1].weight/e.totalWeight,t),0===e.totalAdditiveWeight))return t;i=[],r=[],a=e.totalWeight}for(let t=0;t=o&&m.frame<=a&&(n?(v=m.value.clone(),u?(g=v.getTranslation(),v.setTranslation(g.scaleInPlace(p))):f&&s?(g=v.getTranslation(),v.setTranslation(g.multiplyInPlace(s))):v=m.value):v=m.value,_.push({frame:m.frame+i,value:v}));return this.animations[0].createRange(t,o+i,a+i),!0};var V,k=i(4551);!function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"}(V||(V={}));class G{constructor(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}degrees(){return 180*this._radians/Math.PI}radians(){return this._radians}static BetweenTwoPoints(e,t){const i=t.subtract(e),n=Math.atan2(i.y,i.x);return new G(n)}static FromRadians(e){return new G(e)}static FromDegrees(e){return new G(e*Math.PI/180)}}class z{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;const n=Math.pow(t.x,2)+Math.pow(t.y,2),s=(Math.pow(e.x,2)+Math.pow(e.y,2)-n)/2,r=(n-Math.pow(i.x,2)-Math.pow(i.y,2))/2,a=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new o.FM((s*(t.y-i.y)-r*(e.y-t.y))/a,((e.x-t.x)*r-(t.x-i.x)*s)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=G.BetweenTwoPoints(this.centerPoint,this.startPoint);const l=this.startAngle.degrees();let h=G.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),c=G.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();h-l>180&&(h-=360),h-l<-180&&(h+=360),c-h>180&&(c-=360),c-h<-180&&(c+=360),this.orientation=h-l<0?V.CW:V.CCW,this.angle=G.FromDegrees(this.orientation===V.CW?l-c:c-l)}}class W{constructor(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o.FM(e,t))}addLineTo(e,t){if(this.closed)return this;const i=new o.FM(e,t),n=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(n).length(),this}addArcTo(e,t,i,n,s=36){if(this.closed)return this;const r=this._points[this._points.length-1],a=new o.FM(e,t),l=new o.FM(i,n),h=new z(r,a,l);let c=h.angle.radians()/s;h.orientation===V.CW&&(c*=-1);let d=h.startAngle.radians()+c;for(let o=0;o(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*n,o=this._points[this._points.length-1];for(let a=0;a<=s;a++){const l=a/s,h=r(l,o.x,e,i),c=r(l,o.y,t,n);this.addLineTo(h,c)}return this}addBezierCurveTo(e,t,i,n,s,r,o=36){if(this.closed)return this;const a=(e,t,i,n,s)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*n+e*e*e*s,l=this._points[this._points.length-1];for(let h=0;h<=o;h++){const c=h/o,d=a(c,l.x,e,i,s),u=a(c,l.y,t,n,r);this.addLineTo(d,u)}return this}isPointInside(e){let t=!1;const i=this._points.length;for(let n=i-1,s=0;sNumber.EPSILON){if(a<0&&(i=this._points[s],o=-o,r=this._points[n],a=-a),e.yr.y)continue;if(e.y===i.y&&e.x===i.x)return!0;{const n=a*(e.x-i.x)-o*(e.y-i.y);if(0===n)return!0;if(n<0)continue;t=!t}}else{if(e.y!==i.y)continue;if(r.x<=e.x&&e.x<=i.x||i.x<=e.x&&e.x<=r.x)return!0}}return t}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){const t=this._points[this._points.length-1];e+=this._points[0].subtract(t).length()}return e}area(){const e=this._points.length;let t=0;for(let i=e-1,n=0;n1)return o.FM.Zero();const t=e*this.length();let i=0;for(let n=0;n=i&&t<=a){const e=r.normalize(),n=t-i;return new o.FM(s.x+e.x*n,s.y+e.y*n)}i=a}return o.FM.Zero()}static StartingAt(e,t){return new W(e,t)}}class H{constructor(e,t=null,i,n=!1){this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array,this._pointAtData={id:0,point:o.P.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:o.y3.Identity()};for(let s=0;st){const i=e;e=t,t=i}const i=this.getCurve(),n=this.getPointAt(e);let s=this.getPreviousPointIndexAt(e);const r=this.getPointAt(t),o=this.getPreviousPointIndexAt(t)+1,a=[];return 0!==e&&(s++,a.push(n)),a.push(...i.slice(s,o)),1===t&&1!==e||a.push(r),new H(a,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let n=0;nt+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i,n=e.length();if(0===n&&(n=1),null==t){let t;t=S.R.WithinEpsilon(Math.abs(e.y)/n,1,k.kn)?S.R.WithinEpsilon(Math.abs(e.x)/n,1,k.kn)?S.R.WithinEpsilon(Math.abs(e.z)/n,1,k.kn)?o.P.Zero():new o.P(0,0,1):new o.P(1,0,0):new o.P(0,-1,0),i=o.P.Cross(e,t)}else i=o.P.Cross(e,t),o.P.CrossToRef(i,e,i);return i.normalize(),i}_updatePointAtData(e,t=!1){if(this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;const i=this.getPoints();if(e<=0)return this._setPointAtData(0,0,i[0],0,t);if(e>=1)return this._setPointAtData(1,1,i[i.length-1],i.length-1,t);let n,s=i[0],r=0;const a=e*this.length();for(let l=1;la){const i=(r-a)/h,o=s.subtract(n),c=n.add(o.scaleInPlace(i));return this._setPointAtData(e,1-i,c,l-1,t)}s=n}return this._pointAtData}_setPointAtData(e,t,i,n,s){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=n,this._pointAtData.interpolateReady=s,s&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=o.y3.Identity();const e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){const t=e+1,i=this._tangents[e].clone(),n=this._normals[e].clone(),s=this._binormals[e].clone(),r=this._tangents[t].clone(),a=this._normals[t].clone(),l=this._binormals[t].clone(),h=o._f.RotationQuaternionFromAxis(n,s,i),c=o._f.RotationQuaternionFromAxis(a,l,r);o._f.Slerp(h,c,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}class X{static CreateQuadraticBezier(e,t,i,n){n=n>2?n:3;const s=new Array,r=(e,t,i,n)=>(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*n;for(let a=0;a<=n;a++)s.push(new o.P(r(a/n,e.x,t.x,i.x),r(a/n,e.y,t.y,i.y),r(a/n,e.z,t.z,i.z)));return new X(s)}static CreateCubicBezier(e,t,i,n,s){s=s>3?s:4;const r=new Array,a=(e,t,i,n,s)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*n+e*e*e*s;for(let l=0;l<=s;l++)r.push(new o.P(a(l/s,e.x,t.x,i.x,n.x),a(l/s,e.y,t.y,i.y,n.y),a(l/s,e.z,t.z,i.z,n.z)));return new X(r)}static CreateHermiteSpline(e,t,i,n,s){const r=new Array,a=1/s;for(let l=0;l<=s;l++)r.push(o.P.Hermite(e,t,i,n,l*a));return new X(r)}static CreateCatmullRomSpline(e,t,i){const n=new Array,s=1/t;let r=0;if(i){const i=e.length;for(let a=0;a=.5?.5*(1-this.easeInCore(2*(1-e)))+.5:.5*this.easeInCore(2*e)}}Y.EASINGMODE_EASEIN=0,Y.EASINGMODE_EASEOUT=1,Y.EASINGMODE_EASEINOUT=2;class j extends Y{easeInCore(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)}}class K extends Y{easeInCore(e){return e*e}}class q extends Y{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}}class ${constructor(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}_clone(){return new $(this.frame,this.action,this.onlyOnce)}}var Q=i(4104);class Z{getClassName(){return"TargetedAnimation"}serialize(){const e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class J{get from(){return this._from}get to(){return 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;en[0].frame&&(this._from=n[0].frame),this._to-1;t--){this._targetedAnimations[t].animation===e&&this._targetedAnimations.splice(t,1)}}normalize(e=null,t=null){null==e&&(e=this._from),null==t&&(t=this._to);for(let i=0;ie){const t={frame:e,value:s.value,inTangent:s.inTangent,outTangent:s.outTangent,interpolation:s.interpolation};n.splice(0,0,t)}if(r.frame{this.onAnimationLoopObservable.notifyObservers(t),this._animationLoopFlags[i]||(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount===this._targetedAnimations.length&&(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,n,s){if(this._isStarted||0===this._targetedAnimations.length)return this;this._loopAnimation=e,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let r=0;r{this.onAnimationEndObservable.notifyObservers(o),this._checkAnimationGroupEnded(a)},this._processLoop(a,o,r),this._animatables.push(a)}return this._speedRatio=t,this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this}pause(){if(!this._isStarted)return this;this._isPaused=!0;for(let e=0;e0&&(this._scene._activeAnimatables[t++]=e)}return this._scene._activeAnimatables.length=t,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t-1&&this._scene.animationGroups.splice(e,1),this._parentContainer){const 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){const t=this._animatables.indexOf(e);t>-1&&this._animatables.splice(t,1),0===this._animatables.length&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))}clone(e,t,i=!1){const n=new J(e||this.name,this._scene);for(const s of this._targetedAnimations)n.addTargetedAnimation(i?s.animation.clone():s.animation,t?t(s.target):s.target);return n}serialize(){const e={};e.name=this.name,e.from=this.from,e.to=this.to,e.targetedAnimations=[];for(let t=0;t{const i=new re(e,t);if(t.instancedBuffers){i.instancedBuffers={};for(const e in t.instancedBuffers)i.instancedBuffers[e]=t.instancedBuffers[e]}return i};class re extends ie.x{constructor(e,t){super(e,t.getScene()),this._indexInSourceMeshInstanceArray=-1,this._distanceToCamera=0,t.addInstance(this),this._sourceMesh=t,this._unIndexed=t._unIndexed,this.position.copyFrom(t.position),this.rotation.copyFrom(t.rotation),this.scaling.copyFrom(t.scaling),t.rotationQuaternion&&(this.rotationQuaternion=t.rotationQuaternion.clone()),this.animations=t.animations.slice();for(const i of t.getAnimationRanges())null!=i&&this.createAnimationRange(i.name,i.from,i.to);this.infiniteDistance=t.infiniteDistance,this.setPivotMatrix(t.getPivotMatrix()),this.refreshBoundingInfo(!0,!0),this._syncSubMeshes()}getClassName(){return"InstancedMesh"}get lightSources(){return this._sourceMesh._lightSources}_resyncLightSources(){}_resyncLightSource(){}_removeLightSource(){}get receiveShadows(){return this._sourceMesh.receiveShadows}set receiveShadows(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.receiveShadows)!==e&&se.w1.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.material)!==e&&se.w1.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.visibility)!==e&&se.w1.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.skeleton)!==e&&se.w1.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&&p.Y.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")}getTotalVertices(){return this._sourceMesh?this._sourceMesh.getTotalVertices():0}getTotalIndices(){return this._sourceMesh.getTotalIndices()}get sourceMesh(){return this._sourceMesh}createInstance(e){return this._sourceMesh.createInstance(e)}isReady(e=!1){return this._sourceMesh.isReady(e,!0)}getVerticesData(e,t,i){return this._sourceMesh.getVerticesData(e,t,i)}setVerticesData(e,t,i,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;const i=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getPositionData(e,t),i),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||p.Y.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!==te.Y.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new o.y3);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,o.jp.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(o.jp.Vector3[7]),this._currentLOD._masterMesh=e,this._billboardWorldMatrix}return super.getWorldMatrix()}get isAnInstance(){return!0}getLOD(e){if(!e)return this;const t=this.sourceMesh.getLODLevels();if(t&&0!==t.length){const t=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,t.boundingSphere)}else this._currentLOD=this.sourceMesh;return this._currentLOD}_preActivateForIntermediateRendering(e){return this.sourceMesh._preActivateForIntermediateRendering(e)}_syncSubMeshes(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(let e=0;e0&&-1===this.includedOnlyMeshes.indexOf(e))&&(!(this.excludedMeshes&&this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e))&&((0===this.includeOnlyWithLayerMask||0!=(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 i of this.getScene().meshes)i._removeLightSource(this,!0);this._uniformBuffer.dispose(),this.getScene().removeLight(this),super.dispose(e,t)}getTypeID(){return 0}getScaledIntensity(){return this._photometricScale*this.intensity}clone(e,t=null){const i=he.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const n=E.p4.Clone(i,this);return e&&(n.name=e),t&&(n.parent=t),n.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(n),n}serialize(){const e=E.p4.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)}))),E.p4.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){const n=b.N.Construct("Light_Type_"+e,t,i);return n||null}static Parse(e,t){const i=he.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const n=E.p4.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{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 s=i.apply(e,[t,n]);for(const e of s)e._resyncLightSource(this);return s};for(const n of e)n._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 s=i.apply(e,[t,n]);return this._resyncMeshes(),s},this._resyncMeshes()}_resyncMeshes(){for(const e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(const e of this.getScene().meshes)-1!==e.lightSources.indexOf(this)&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0;const t=this.getTypeID();let i=this.intensityMode;switch(i===he.INTENSITYMODE_AUTOMATIC&&(i=t===he.LIGHTTYPEID_DIRECTIONALLIGHT?he.INTENSITYMODE_ILLUMINANCE:he.INTENSITYMODE_LUMINOUSINTENSITY),t){case he.LIGHTTYPEID_POINTLIGHT:case he.LIGHTTYPEID_SPOTLIGHT:switch(i){case he.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case he.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case he.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case he.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case he.INTENSITYMODE_ILLUMINANCE:e=1;break;case he.INTENSITYMODE_LUMINANCE:{let t=this.radius;t=Math.max(t,.001);e=2*Math.PI*(1-Math.cos(t));break}}break;case he.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e}_reorderLightsInScene(){const e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}he.FALLOFF_DEFAULT=le.m.FALLOFF_DEFAULT,he.FALLOFF_PHYSICAL=le.m.FALLOFF_PHYSICAL,he.FALLOFF_GLTF=le.m.FALLOFF_GLTF,he.FALLOFF_STANDARD=le.m.FALLOFF_STANDARD,he.LIGHTMAP_DEFAULT=le.m.LIGHTMAP_DEFAULT,he.LIGHTMAP_SPECULAR=le.m.LIGHTMAP_SPECULAR,he.LIGHTMAP_SHADOWSONLY=le.m.LIGHTMAP_SHADOWSONLY,he.INTENSITYMODE_AUTOMATIC=le.m.INTENSITYMODE_AUTOMATIC,he.INTENSITYMODE_LUMINOUSPOWER=le.m.INTENSITYMODE_LUMINOUSPOWER,he.INTENSITYMODE_LUMINOUSINTENSITY=le.m.INTENSITYMODE_LUMINOUSINTENSITY,he.INTENSITYMODE_ILLUMINANCE=le.m.INTENSITYMODE_ILLUMINANCE,he.INTENSITYMODE_LUMINANCE=le.m.INTENSITYMODE_LUMINANCE,he.LIGHTTYPEID_POINTLIGHT=le.m.LIGHTTYPEID_POINTLIGHT,he.LIGHTTYPEID_DIRECTIONALLIGHT=le.m.LIGHTTYPEID_DIRECTIONALLIGHT,he.LIGHTTYPEID_SPOTLIGHT=le.m.LIGHTTYPEID_SPOTLIGHT,he.LIGHTTYPEID_HEMISPHERICLIGHT=le.m.LIGHTTYPEID_HEMISPHERICLIGHT,(0,oe.gn)([(0,E.n9)()],he.prototype,"diffuse",void 0),(0,oe.gn)([(0,E.n9)()],he.prototype,"specular",void 0),(0,oe.gn)([(0,E.qC)()],he.prototype,"falloffType",void 0),(0,oe.gn)([(0,E.qC)()],he.prototype,"intensity",void 0),(0,oe.gn)([(0,E.qC)()],he.prototype,"range",null),(0,oe.gn)([(0,E.qC)()],he.prototype,"intensityMode",null),(0,oe.gn)([(0,E.qC)()],he.prototype,"radius",null),(0,oe.gn)([(0,E.qC)()],he.prototype,"_renderPriority",void 0),(0,oe.gn)([(0,E.wz)("_reorderLightsInScene")],he.prototype,"renderPriority",void 0),(0,oe.gn)([(0,E.qC)("shadowEnabled")],he.prototype,"_shadowEnabled",void 0),(0,oe.gn)([(0,E.qC)("excludeWithLayerMask")],he.prototype,"_excludeWithLayerMask",void 0),(0,oe.gn)([(0,E.qC)("includeOnlyWithLayerMask")],he.prototype,"_includeOnlyWithLayerMask",void 0),(0,oe.gn)([(0,E.qC)("lightmapMode")],he.prototype,"_lightmapMode",void 0);var ce=i(4515);class de extends n.p{}class ue{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 pe extends n.p{constructor(e){super(),this._wasAddedToScene=!1,(e=e||m.l.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 o of e)t.set(o.uniqueId,o);const i={dependsOn:new Map,dependedBy:new Map};for(const o of e){const e=o.uniqueId;i.dependsOn.set(e,new Set),i.dependedBy.set(e,new Set)}for(const o of e){const e=o.uniqueId,n=i.dependsOn.get(e);if(o instanceof re){const s=o.sourceMesh;t.has(s.uniqueId)&&(n.add(s.uniqueId),i.dependedBy.get(s.uniqueId).add(e))}const s=i.dependedBy.get(e);for(const r of o.getDescendants()){const n=r.uniqueId;if(t.has(n)){s.add(n);i.dependsOn.get(n).add(e)}}}const n=[],s=[];for(const o of e){const e=o.uniqueId;0===i.dependsOn.get(e).size&&(s.push(o),t.delete(e))}const r=s;for(;r.length>0;){const e=r.shift();n.push(e);const s=i.dependedBy.get(e.uniqueId);for(const n of Array.from(s.values())){const s=i.dependsOn.get(n);s.delete(e.uniqueId),0===s.size&&t.get(n)&&(r.push(t.get(n)),t.delete(n))}}return t.size>0&&(console.error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach((e=>console.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 s of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,s,n)}}_isNodeInContainer(e){return e instanceof ee.Kj&&-1!==this.meshes.indexOf(e)||(e instanceof te.Y&&-1!==this.transformNodes.indexOf(e)||(e instanceof he&&-1!==this.lights.indexOf(e)||e instanceof ce.V&&-1!==this.cameras.indexOf(e)))}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return p.Y.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 p.Y.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 p.Y.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 p.Y.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||se.w1.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const n={},s={},r=new ue,o=[],a=[],l=Object.assign({doNotInstantiate:!0},i),h=[],c=new Set;for(const p of this.transformNodes)null===p.parent&&this._addNodeAndDescendantsToList(h,c,p,l.predicate);for(const p of this.meshes)null===p.parent&&this._addNodeAndDescendantsToList(h,c,p,l.predicate);const d=this._topologicalSort(h),u=(i,o)=>{if(((t,i)=>{if(n[t.uniqueId]=i.uniqueId,s[i.uniqueId]=i,e&&(i.name=e(t.name)),i instanceof ee.Kj){const e=i;if(e.morphTargetManager){const i=t.morphTargetManager;e.morphTargetManager=i.clone();for(let t=0;te&&s[n[e.uniqueId]]))}}"InstancedMesh"!==r.getClassName()&&(r.material=s[n[t.uniqueId]])}else"MultiMaterial"===r.material.getClassName()?-1===this.scene.multiMaterials.indexOf(r.material)&&this.scene.addMultiMaterial(r.material):-1===this.scene.materials.indexOf(r.material)&&this.scene.addMaterial(r.material)}null===o.parent&&r.rootNodes.push(o)};return d.forEach((e=>{if("InstancedMesh"===e.getClassName()){const t=e,i=t.sourceMesh,r=n[i.uniqueId],o=("number"==typeof r?s[r]:i).createInstance(t.name);u(t,o)}else{let t=!0;"TransformNode"===e.getClassName()||"Node"===e.getClassName()||e.skeleton||!e.getTotalVertices||0===e.getTotalVertices()?t=!1:l.doNotInstantiate&&(t="function"==typeof l.doNotInstantiate?!l.doNotInstantiate(e):!l.doNotInstantiate);const i=t?e.createInstance(`instance of ${e.name}`):e.clone(`Clone of ${e.name}`,null,!0);if(!i)throw new Error(`Could not clone or instantiate node on Asset Container ${e.name}`);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=s[n[e.uniqueId]];if(!t||t.isAnInstance)continue;if(t.skeleton=i,-1!==o.indexOf(i))continue;o.push(i);for(const e of i.bones)e._linkedTransformNode&&(e._linkedTransformNode=s[n[e._linkedTransformNode.uniqueId]])}r.skeletons.push(i)})),this.animationGroups.forEach((t=>{if(l.predicate&&!l.predicate(t))return;const i=t.clone(e?e(t.name):"Clone of "+t.name,(e=>s[n[e.uniqueId]]||e));r.animationGroups.push(i)})),r}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||se.w1.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){this.cameras.forEach((t=>{e&&!e(t)||this.scene.addCamera(t)})),this.lights.forEach((t=>{e&&!e(t)||this.scene.addLight(t)})),this.meshes.forEach((t=>{e&&!e(t)||this.scene.addMesh(t)})),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((t=>{e&&!e(t)||this.scene.addTransformNode(t)})),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)}))}removeAllFromScene(){this._isValidHierarchy()||se.w1.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)})),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 de);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 ee.Kj("assetContainerRootMesh",this.scene);return this.meshes.forEach((t=>{t.parent||e.addChild(t)})),this.meshes.unshift(e),e}mergeAnimationsTo(e=m.l.LastCreatedScene,t,i=null){if(!e)return p.Y.Error("No scene available to merge animations to"),[];const n=i||(t=>{let i=null;const n=t.animations.length?t.animations[0].targetProperty:"",s=t.name.split(".").join("").split("_primitive")[0];switch(n){case"position":case"rotationQuaternion":i=e.getTransformNodeByName(t.name)||e.getTransformNodeByName(s);break;case"influence":i=e.getMorphTargetByName(t.name)||e.getMorphTargetByName(s);break;default:i=e.getNodeByName(t.name)||e.getNodeByName(s)}return i});this.getNodes().forEach((e=>{const t=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 s=new Array;return this.animationGroups.slice().forEach((e=>{s.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))})),s}}var fe=i(8838);var _e=i(1102);fe.D.AudioEngineFactory=(e,t,i)=>new me(e,t,i);class me{get audioContext(){return this._audioContextInitialized?this.unlocked||this._muteButton||this._displayMuteButton():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=!0,this.useCustomUnlockedButton=!1,this.onAudioUnlockedObservable=new r.y$,this.onAudioLockedObservable=new r.y$,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!(0,_e.CG)())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(s){}try{n&&n.canPlayType&&n.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch(s){}}lock(){this._triggerSuspendedState()}unlock(){this._triggerRunningState()}_resumeAudioContext(){let e;return void 0!==this._audioContext.resume&&(e=this._audioContext.resume()),e||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,p.Y.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._triggerRunningState()}),!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))}}var ge=i(9069);class ve{get loop(){return this._loop}set loop(e){e!==this._loop&&(this._loop=e,this.updateOptions({loop:e}))}get currentTime(){var e;if(this._htmlAudioElement)return this._htmlAudioElement.currentTime;if((null===(e=fe.D.audioEngine)||void 0===e?void 0:e.audioContext)&&(this.isPlaying||this.isPaused)){const e=this.isPaused?0:fe.D.audioEngine.audioContext.currentTime-this._startTime;return this._currentTime+e}return 0}get spatialSound(){return this._spatialSound}set spatialSound(e){var t;this._spatialSound=e,this._spatialSound&&(null===(t=fe.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&fe.D.audioEngine.audioContext&&this._createSpatialParameters()}constructor(e,t,i,n=null,s){var a,l,h,c,d;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 r.y$,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=o.P.Zero(),this._localDirection=new o.P(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||m.l.LastCreatedScene)if(this._scene=i,ve._SceneComponentInitialization(i),this._readyToPlayCallback=n,this._customAttenuationFunction=(e,t,i,n,s)=>t0&&(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{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&&p.Y.Error("XHR "+e.status+" error on: "+t+"."),p.Y.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)):p.Y.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch(u){p.Y.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),fe.D.audioEngine&&!fe.D.audioEngine.WarnedWebAudioUnsupported&&(p.Y.Error("Web Audio is not supported by your browser."),fe.D.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)}dispose(){var e;(null===(e=fe.D.audioEngine)||void 0===e?void 0:e.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))}isReady(){return this._isReadyToPlay}getClassName(){return"Sound"}_audioBufferLoaded(e){var t;(null===(t=fe.D.audioEngine)||void 0===t?void 0:t.audioContext)&&(this._audioBuffer=e,this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback())}_soundLoaded(e){var t;(null===(t=fe.D.audioEngine)||void 0===t?void 0:t.audioContext)&&fe.D.audioEngine.audioContext.decodeAudioData(e,(e=>{this._audioBufferLoaded(e)}),(e=>{p.Y.Error("Error while decoding audio data for: "+this.name+" / Error: "+e)}))}setAudioBuffer(e){var t;(null===(t=fe.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&(this._audioBuffer=e,this._isReadyToPlay=!0)}updateOptions(e){var t,i,n,s,r,o,a,l,h,c;e&&(this.loop=null!==(t=e.loop)&&void 0!==t?t:this.loop,this.maxDistance=null!==(i=e.maxDistance)&&void 0!==i?i:this.maxDistance,this.useCustomAttenuation=null!==(n=e.useCustomAttenuation)&&void 0!==n?n:this.useCustomAttenuation,this.rolloffFactor=null!==(s=e.rolloffFactor)&&void 0!==s?s:this.rolloffFactor,this.refDistance=null!==(r=e.refDistance)&&void 0!==r?r:this.refDistance,this.distanceModel=null!==(o=e.distanceModel)&&void 0!==o?o:this.distanceModel,this._playbackRate=null!==(a=e.playbackRate)&&void 0!==a?a:this._playbackRate,this._length=null!==(l=e.length)&&void 0!==l?l:void 0,this._setOffset(null!==(h=e.offset)&&void 0!==h?h:void 0),this.setVolume(null!==(c=e.volume)&&void 0!==c?c: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(){var e,t;(null===(e=fe.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&fe.D.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=null!==(t=this._soundPanner)&&void 0!==t?t:fe.D.audioEngine.audioContext.createPanner(),this._soundPanner&&this._outputAudioNode&&(this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner))}_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))}switchPanningModelToHRTF(){this._panningModel="HRTF",this._switchPanningModel()}switchPanningModelToEqualPower(){this._panningModel="equalpower",this._switchPanningModel()}_switchPanningModel(){var e;(null===(e=fe.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){var t;(null===(t=fe.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(e),this._isOutputConnected=!0)}setDirectionalCone(e,t,i){t{this._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement){const e=()=>{var t,i;if(null===(t=fe.D.audioEngine)||void 0===t?void 0:t.unlocked){const t=this._htmlAudioElement.play();void 0!==t&&t.catch((()=>{var t,i;null===(t=fe.D.audioEngine)||void 0===t||t.lock(),(this.loop||this.autoplay)&&(null===(i=fe.D.audioEngine)||void 0===i||i.onAudioUnlockedObservable.addOnce((()=>{e()})))}))}else(this.loop||this.autoplay)&&(null===(i=fe.D.audioEngine)||void 0===i||i.onAudioUnlockedObservable.addOnce((()=>{e()})))};e()}}else{const s=()=>{var s,r,o,a;if(null===(s=fe.D.audioEngine)||void 0===s?void 0:s.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=null===(r=fe.D.audioEngine)||void 0===r?void 0:r.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?(null===(o=fe.D.audioEngine)||void 0===o?void 0:o.audioContext.currentTime)+e:fe.D.audioEngine.audioContext.currentTime;const s=((this.isPaused?this.currentTime:0)+(null!==(a=this._offset)&&void 0!==a?a:0))%this._soundSource.buffer.duration;this._soundSource.start(n,s,this.loop?void 0:i)}}};"suspended"===(null===(o=fe.D.audioEngine)||void 0===o?void 0:o.audioContext.state)?setTimeout((()=>{var e;"suspended"===(null===(e=fe.D.audioEngine)||void 0===e?void 0:e.audioContext.state)?(fe.D.audioEngine.lock(),(this.loop||this.autoplay)&&fe.D.audioEngine.onAudioUnlockedObservable.addOnce((()=>{s()}))):s()}),500):s()}this._startTime=n,this.isPlaying=!0,this.isPaused=!1}catch(a){p.Y.Error("Error while trying to play audio: "+this.name+", "+a.message)}}_onended(){this.isPlaying=!1,this._startTime=0,this._currentTime=0,this.onended&&this.onended(),this.onEndedObservable.notifyObservers(this)}stop(e){var t;if(this.isPlaying){if(this._streaming)this._htmlAudioElement?(this._htmlAudioElement.pause(),this._htmlAudioElement.currentTime>0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect(),this.isPlaying=!1;else if((null===(t=fe.D.audioEngine)||void 0===t?void 0:t.audioContext)&&this._soundSource){const t=e?fe.D.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.isPaused&&(this.isPaused=!1,this._startTime=0,this._currentTime=0)}pause(){var e;this.isPlaying&&(this._streaming?(this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect(),this.isPlaying=!1,this.isPaused=!0):(null===(e=fe.D.audioEngine)||void 0===e?void 0:e.audioContext)&&this._soundSource&&(this._soundSource.onended=()=>{},this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=fe.D.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){var i;(null===(i=fe.D.audioEngine)||void 0===i?void 0:i.canUseWebAudio)&&this._soundGain&&(t&&fe.D.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(fe.D.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,fe.D.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,fe.D.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){var t;if(e.getBoundingInfo){const t=e.getBoundingInfo();this.setPosition(t.boundingSphere.centerWorld)}else this.setPosition(e.absolutePosition);(null===(t=fe.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._isDirectional&&this.isPlaying&&this._updateDirection()}clone(){if(this._streaming)return null;{const e=()=>{this._isReadyToPlay?(i._audioBuffer=this.getAudioBuffer(),i._isReadyToPlay=!0,i.autoplay&&i.play(0,this._offset,this._length)):setTimeout(e,300)},t={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},i=new ve(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.name,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId,metadata:this.metadata};return this._spatialSound&&(this._connectedTransformNode&&(e.connectedMeshId=this._connectedTransformNode.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e}static Parse(e,t,i,n){const s=e.name;let r;r=e.url?i+e.url:i+s;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 l;if(n){const e=()=>{n._isReadyToPlay?(l._audioBuffer=n.getAudioBuffer(),l._isReadyToPlay=!0,l.autoplay&&l.play(0,l._offset,l._length)):setTimeout(e,300)};l=new ve(s,new ArrayBuffer(0),t,null,a),e()}else l=new ve(s,r,t,(()=>{t.removePendingData(l)}),a),t.addPendingData(l);if(e.position){const t=o.P.FromArray(e.position);l.setPosition(t)}if(e.isDirectional&&(l.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){const t=o.P.FromArray(e.localDirectionToMesh);l.setLocalDirectionToMesh(t)}if(e.connectedMeshId){const i=t.getMeshById(e.connectedMeshId);i&&l.attachToMesh(i)}return e.metadata&&(l.metadata=e.metadata),l}_setOffset(e){this._offset!==e&&(this.isPaused&&(this.stop(),this.isPaused=!1),this._offset=e)}}ve._SceneComponentInitialization=e=>{throw(0,ge.S)("AudioSceneComponent")};class Te{constructor(e,t={}){this.id=-1,this._isInitialized=!1,(e=e||m.l.LastCreatedScene)&&(this._scene=e,this.soundCollection=new Array,this._options=t,!this._options.mainTrack&&this._scene.soundTracks&&(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1))}_initializeSoundTrackAudioGraph(){var e;(null===(e=fe.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&fe.D.audioEngine.audioContext&&(this._outputAudioNode=fe.D.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(fe.D.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(fe.D.audioEngine&&fe.D.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}}addSound(e){var t;this._isInitialized||this._initializeSoundTrackAudioGraph(),(null===(t=fe.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&e.connectToSoundTrackAudioNode(this._outputAudioNode),e.soundTrackId&&(-1===e.soundTrackId?this._scene.mainSoundTrack.removeSound(e):this._scene.soundTracks&&this._scene.soundTracks[e.soundTrackId].removeSound(e)),this.soundCollection.push(e),e.soundTrackId=this.id}removeSound(e){const t=this.soundCollection.indexOf(e);-1!==t&&this.soundCollection.splice(t,1)}setVolume(e){var t;(null===(t=fe.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)}switchPanningModelToHRTF(){var e;if(null===(e=fe.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)for(let t=0;t{var s;let r,o=[];if(i.sounds=i.sounds||[],void 0!==e.sounds&&null!==e.sounds)for(let a=0,l=e.sounds.length;a{e.play(),e.autoplay=!0,this.scene.mainSoundTrack.addSound(e)}))}removeFromContainer(e,t=!1){e.sounds&&e.sounds.forEach((e=>{e.stop(),e.autoplay=!1,this.scene.mainSoundTrack.removeSound(e),t&&e.dispose()}))}dispose(){const e=this.scene;if(e._mainSoundTrack&&e.mainSoundTrack.dispose(),e.soundTracks)for(let t=0;t0&&(n=t.activeCameras[0]),this.audioListenerPositionProvider){const e=this.audioListenerPositionProvider();i.audioContext.listener.setPosition(e.x||0,e.y||0,e.z||0)}else n?this._cachedCameraPosition.equals(n.globalPosition)||(this._cachedCameraPosition.copyFrom(n.globalPosition),i.audioContext.listener.setPosition(n.globalPosition.x,n.globalPosition.y,n.globalPosition.z)):i.audioContext.listener.setPosition(0,0,0);if(this.audioListenerRotationProvider){const e=this.audioListenerRotationProvider();i.audioContext.listener.setOrientation(e.x||0,e.y||0,e.z||0,0,1,0)}else n?(n.rigCameras&&n.rigCameras.length>0&&(n=n.rigCameras[0]),n.getViewMatrix().invertToRef(this._invertMatrixTemp),o.P.TransformNormalToRef(Ee._CameraDirection,this._invertMatrixTemp,this._cameraDirectionTemp),this._cameraDirectionTemp.normalize(),isNaN(this._cameraDirectionTemp.x)||isNaN(this._cameraDirectionTemp.y)||isNaN(this._cameraDirectionTemp.z)||this._cachedCameraDirection.equals(this._cameraDirectionTemp)||(this._cachedCameraDirection.copyFrom(this._cameraDirectionTemp),i.audioContext.listener.setOrientation(this._cameraDirectionTemp.x,this._cameraDirectionTemp.y,this._cameraDirectionTemp.z,0,1,0))):i.audioContext.listener.setOrientation(0,0,0,0,1,0);for(e=0;e{let t=e._getComponent(Se.l.NAME_AUDIO);t||(t=new Ee(e),e._addComponent(t))};class xe{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 r of i)n+=r;const s=n>0?1/n:0;for(let r=0;r{this._onended()}))}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(e){if(e!==this._coneInnerAngle){if(this._coneOuterAnglee),this)}serialize(){return E.p4.Serialize(this)}parse(e,t,i){E.p4.Parse((()=>this),e,t,i)}}(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markSubMeshesAsAttributesDirty")],be.prototype,"texture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markSubMeshesAsAttributesDirty")],be.prototype,"isEnabled",void 0),(0,oe.gn)([(0,E.qC)()],be.prototype,"animationParameters",void 0),(0,oe.gn)([(0,E.qC)()],be.prototype,"time",void 0);var Ce=i(3706),ye=i(9051);class Ae{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!==(null==e?void 0:e._shareDepth)}constructor(e){this._wrapU=1,this._wrapV=1,this.wrapR=1,this.anisotropicFilteringLevel=4,this.delayLoadState=0,this._texture=null,this._engine=null,this._cachedSize=C.Zero(),this._cachedBaseSize=C.Zero(),this._initialSamplingMode=2,this._texture=Ae._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine())}isReady(){return 4===this.delayLoadState?(this.delayLoad(),!1):!!this._texture&&this._texture.isReady}delayLoad(){}getInternalTexture(){return this._texture}getSize(){if(this._texture){if(this._texture.width)return this._cachedSize.width=this._texture.width,this._cachedSize.height=this._texture.height,this._cachedSize;if(this._texture._size)return this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size,this._cachedSize}return this._cachedSize}getBaseSize(){return this.isReady()&&this._texture?this._texture._size?(this._cachedBaseSize.width=this._texture._size,this._cachedBaseSize.height=this._texture._size,this._cachedBaseSize):(this._cachedBaseSize.width=this._texture.baseWidth,this._cachedBaseSize.height=this._texture.baseHeight,this._cachedBaseSize):(this._cachedBaseSize.width=0,this._cachedBaseSize.height=0,this._cachedBaseSize)}get samplingMode(){return this._texture?this._texture.samplingMode:this._initialSamplingMode}updateSamplingMode(e){this._texture&&this._engine&&this._engine.updateTextureSamplingMode(e,this._texture)}releaseInternalTexture(){this._texture&&(this._texture.dispose(),this._texture=null)}dispose(){this._texture&&(this.releaseInternalTexture(),this._engine=null)}}class Re extends Ae{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get coordinatesMode(){return this._coordinatesMode}get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get isCube(){return this._texture?this._texture.isCube:this._isCube}set isCube(e){this._texture?this._texture.isCube=e:this._isCube=e}get is3D(){return!!this._texture&&this._texture.is3D}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}get gammaSpace(){return this._texture?(null===this._texture._gammaSpace&&(this._texture._gammaSpace=this._gammaSpace),this._texture._gammaSpace&&!this._texture._useSRGBBuffer):this._gammaSpace}set gammaSpace(e){if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}this._markAllSubMeshesAsTexturesDirty()}get isRGBD(){return null!=this._texture&&this._texture._isRGBD}set isRGBD(e){this._texture&&(this._texture._isRGBD=e)}get noMipmap(){return!1}get lodGenerationOffset(){return this._texture?this._texture._lodGenerationOffset:0}set lodGenerationOffset(e){this._texture&&(this._texture._lodGenerationOffset=e)}get lodGenerationScale(){return this._texture?this._texture._lodGenerationScale:0}set lodGenerationScale(e){this._texture&&(this._texture._lodGenerationScale=e)}get linearSpecularLOD(){return!!this._texture&&this._texture._linearSpecularLOD}set linearSpecularLOD(e){this._texture&&(this._texture._linearSpecularLOD=e)}get irradianceTexture(){return this._texture?this._texture._irradianceTexture:null}set irradianceTexture(e){this._texture&&(this._texture._irradianceTexture=e)}get uid(){return this._uid||(this._uid=(0,Ce.f)()),this._uid}toString(){return this.name}getClassName(){return"BaseTexture"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get isBlocking(){return!0}get loadingError(){return this._loadingError}get errorObject(){return this._errorObject}constructor(e,t=null){super(null),this.metadata=null,this.reservedDataStore=null,this._hasAlpha=!1,this._getAlphaFromRGB=!1,this.level=1,this._coordinatesIndex=0,this.optimizeUVAllocation=!0,this._coordinatesMode=0,this.wrapR=1,this.anisotropicFilteringLevel=Re.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=new Array,this.onDisposeObservable=new r.y$,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?Re._IsScene(e)?this._scene=e:this._engine=e:this._scene=m.l.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}checkTransformsAreIdentical(e){return null!==e}getTextureMatrix(){return o.y3.IdentityReadOnly}getReflectionTextureMatrix(){return o.y3.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,n,s,r){const o=this._getEngine();if(!o)return null;const a=o._getUseSRGBBuffer(!!s,t),l=o.getLoadedTexturesCache();for(let h=0;h=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=E.p4.Serialize(this);return E.p4.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(0!==i)for(let n=0;n{0==--i&&t()})):0==--i&&t()}}else t()}static _IsScene(e){return"Scene"===e.getClassName()}}Re.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,(0,oe.gn)([(0,E.qC)()],Re.prototype,"uniqueId",void 0),(0,oe.gn)([(0,E.qC)()],Re.prototype,"name",void 0),(0,oe.gn)([(0,E.qC)()],Re.prototype,"metadata",void 0),(0,oe.gn)([(0,E.qC)("hasAlpha")],Re.prototype,"_hasAlpha",void 0),(0,oe.gn)([(0,E.qC)("getAlphaFromRGB")],Re.prototype,"_getAlphaFromRGB",void 0),(0,oe.gn)([(0,E.qC)()],Re.prototype,"level",void 0),(0,oe.gn)([(0,E.qC)("coordinatesIndex")],Re.prototype,"_coordinatesIndex",void 0),(0,oe.gn)([(0,E.qC)()],Re.prototype,"optimizeUVAllocation",void 0),(0,oe.gn)([(0,E.qC)("coordinatesMode")],Re.prototype,"_coordinatesMode",void 0),(0,oe.gn)([(0,E.qC)()],Re.prototype,"wrapU",null),(0,oe.gn)([(0,E.qC)()],Re.prototype,"wrapV",null),(0,oe.gn)([(0,E.qC)()],Re.prototype,"wrapR",void 0),(0,oe.gn)([(0,E.qC)()],Re.prototype,"anisotropicFilteringLevel",void 0),(0,oe.gn)([(0,E.qC)()],Re.prototype,"isCube",null),(0,oe.gn)([(0,E.qC)()],Re.prototype,"is3D",null),(0,oe.gn)([(0,E.qC)()],Re.prototype,"is2DArray",null),(0,oe.gn)([(0,E.qC)()],Re.prototype,"gammaSpace",null),(0,oe.gn)([(0,E.qC)()],Re.prototype,"invertZ",void 0),(0,oe.gn)([(0,E.qC)()],Re.prototype,"lodLevelInAlpha",void 0),(0,oe.gn)([(0,E.qC)()],Re.prototype,"lodGenerationOffset",null),(0,oe.gn)([(0,E.qC)()],Re.prototype,"lodGenerationScale",null),(0,oe.gn)([(0,E.qC)()],Re.prototype,"linearSpecularLOD",null),(0,oe.gn)([(0,E.oU)()],Re.prototype,"irradianceTexture",null),(0,oe.gn)([(0,E.qC)()],Re.prototype,"isRenderTarget",void 0);var Pe=i(9447),Ie=i(6448),Me=i(6504),Oe=i(8661);function De(e,t,i=!1){const n=t.width,s=t.height;if(e instanceof Float32Array){let t=e.byteLength/e.BYTES_PER_ELEMENT;const i=new Uint8Array(t);for(;--t>=0;){let n=e[t];n<0?n=0:n>1&&(n=1),i[t]=255*n}e=i}const r=document.createElement("canvas");r.width=n,r.height=s;const o=r.getContext("2d");if(!o)return null;const a=o.createImageData(n,s);if(a.data.set(e),o.putImageData(a,0,0),i){const e=document.createElement("canvas");e.width=n,e.height=s;const t=e.getContext("2d");return t?(t.translate(0,s),t.scale(1,-1),t.drawImage(r,0,0),e.toDataURL("image/png")):null}return r.toDataURL("image/png")}function Ne(e,t=0,i=0){const n=e.getInternalTexture();if(!n)return null;const s=e._readPixelsSync(t,i);return s?De(s,e.getSize(),n.invertY):null}async function Fe(e,t=0,i=0){const n=e.getInternalTexture();if(!n)return null;const s=await e.readPixels(t,i);return s?De(s,e.getSize(),n.invertY):null}var we=i(6629);class Le extends Re{get noMipmap(){return this._noMipmap}get mimeType(){return this._mimeType}set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}get invertY(){return this._invertY}constructor(e,t,i,n,s=Le.TRILINEAR_SAMPLINGMODE,o=null,a=null,l=null,h=!1,c,d,u,p,f){var _,m,g,v,T,S,E,x,b;let C;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._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 r.y$,this._isBlocking=!0,this.name=e||"",this.url=e;let y=!1,A=null;"object"==typeof i&&null!==i?(C=null!==(_=i.noMipmap)&&void 0!==_&&_,n=null!==(m=i.invertY)&&void 0!==m?m:!we.e.UseOpenGLOrientationForUV,s=null!==(g=i.samplingMode)&&void 0!==g?g:Le.TRILINEAR_SAMPLINGMODE,o=null!==(v=i.onLoad)&&void 0!==v?v:null,a=null!==(T=i.onError)&&void 0!==T?T:null,l=null!==(S=i.buffer)&&void 0!==S?S:null,h=null!==(E=i.deleteBuffer)&&void 0!==E&&E,c=i.format,d=i.mimeType,u=i.loaderOptions,p=i.creationFlags,y=null!==(x=i.useSRGBBuffer)&&void 0!==x&&x,A=null!==(b=i.internalTexture)&&void 0!==b?b:null):C=!!i,this._noMipmap=C,this._invertY=void 0===n?!we.e.UseOpenGLOrientationForUV:n,this._initialSamplingMode=s,this._buffer=l,this._deleteBuffer=h,this._mimeType=d,this._loaderOptions=u,this._creationFlags=p,this._useSRGBBuffer=y,this._forcedExtension=f,c&&(this._format=c);const R=this.getScene(),P=this._getEngine();if(!P)return;P.onBeforeTextureInitObservable.notifyObservers(this);const I=()=>{this._texture&&(this._texture._invertVScale&&(this.vScale*=-1,this.vOffset+=1),null!==this._texture._cachedWrapU&&(this.wrapU=this._texture._cachedWrapU,this._texture._cachedWrapU=null),null!==this._texture._cachedWrapV&&(this.wrapV=this._texture._cachedWrapV,this._texture._cachedWrapV=null),null!==this._texture._cachedWrapR&&(this.wrapR=this._texture._cachedWrapR,this._texture._cachedWrapR=null)),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),o&&o(),!this.isBlocking&&R&&R.resetCachedMaterial()},M=(e,t)=>{this._loadingError=!0,this._errorObject={message:e,exception:t},a&&a(e,t),Le.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!A)return this._delayedOnLoad=I,void(this._delayedOnError=M);if(this._texture=null!=A?A:this._getFromCache(this.url,C,s,this._invertY,y),this._texture)if(this._texture.isReady)Pe.Q.SetImmediate((()=>I()));else{const e=this._texture.onLoadedObservable.add(I);this._texture.onErrorObservable.add((t=>{var i;M(t.message,t.exception),null===(i=this._texture)||void 0===i||i.onLoadedObservable.remove(e)}))}else if(R&&R.useDelayedTextureLoading)this.delayLoadState=4,this._delayedOnLoad=I,this._delayedOnError=M;else{try{this._texture=P.createTexture(this.url,C,this._invertY,R,s,I,M,this._buffer,void 0,this._format,this._forcedExtension,d,u,p,y)}catch(O){throw M("error loading",O),O}h&&(this._buffer=null)}}updateURL(e,t=null,i,n){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1)),this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=n,this.delayLoadState=4,i&&(this._delayedOnLoad=i),this.delayLoad()}delayLoad(){if(4!==this.delayLoadState)return;const e=this.getScene();e&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer),this._texture?this._delayedOnLoad&&(this._texture.isReady?Pe.Q.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(this.url,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format,this._forcedExtension,this._mimeType,this._loaderOptions,this._creationFlags,this._useSRGBBuffer),this._deleteBuffer&&(this._buffer=null)),this._delayedOnLoad=null,this._delayedOnError=null)}_prepareRowForTextureGeneration(e,t,i,n){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,o.P.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}checkTransformsAreIdentical(e){return null!==e&&this.uOffset===e.uOffset&&this.vOffset===e.vOffset&&this.uScale===e.uScale&&this.vScale===e.vScale&&this.uAng===e.uAng&&this.vAng===e.vAng&&this.wAng===e.wAng}getTextureMatrix(e=1){if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale*e===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng&&this.uRotationCenter===this._cachedURotationCenter&&this.vRotationCenter===this._cachedVRotationCenter&&this.wRotationCenter===this._cachedWRotationCenter&&this.homogeneousRotationInUVTransform===this._cachedHomogeneousRotationInUVTransform)return this._cachedTextureMatrix;this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale*e,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedURotationCenter=this.uRotationCenter,this._cachedVRotationCenter=this.vRotationCenter,this._cachedWRotationCenter=this.wRotationCenter,this._cachedHomogeneousRotationInUVTransform=this.homogeneousRotationInUVTransform,this._cachedTextureMatrix&&this._rowGenerationMatrix||(this._cachedTextureMatrix=o.y3.Zero(),this._rowGenerationMatrix=new o.y3,this._t0=o.P.Zero(),this._t1=o.P.Zero(),this._t2=o.P.Zero()),o.y3.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(o.y3.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,o.jp.Matrix[0]),o.y3.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,o.jp.Matrix[1]),o.y3.ScalingToRef(this._cachedUScale,this._cachedVScale,0,o.jp.Matrix[2]),o.y3.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,o.jp.Matrix[3]),o.jp.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(o.jp.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(o.jp.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(o.jp.Matrix[3],this._cachedTextureMatrix),this._cachedTextureMatrix.setRowFromFloats(2,this._cachedTextureMatrix.m[12],this._cachedTextureMatrix.m[13],this._cachedTextureMatrix.m[14],1)):(this._prepareRowForTextureGeneration(0,0,0,this._t0),this._prepareRowForTextureGeneration(1,0,0,this._t1),this._prepareRowForTextureGeneration(0,1,0,this._t2),this._t1.subtractInPlace(this._t0),this._t2.subtractInPlace(this._t0),o.y3.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();return t?(this.optimizeUVAllocation&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))),this._cachedTextureMatrix):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!==Le.PROJECTION_MODE)return this._cachedReflectionTextureMatrix;if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=o.y3.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=o.y3.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 Le.PLANAR_MODE:o.y3.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 Le.PROJECTION_MODE:{o.y3.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);const t=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=t.updateFlag,t.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:o.y3.IdentityToRef(this._cachedReflectionTextureMatrix)}return t&&e.markAllMaterialsAsDirty(1,(e=>-1!==e.getActiveTextures().indexOf(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 E.p4.Clone((()=>new Le(this._texture?this._texture.url:null,this.getScene(),e)),this)}serialize(){var e,t;const i=this.name;Le.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const n=super.serialize(Le._SerializeInternalTextureUniqueId);return n?((Le.SerializeBuffers||Le.ForceSerializeBuffers)&&("string"==typeof this._buffer&&"data:"===this._buffer.substr(0,5)?(n.base64String=this._buffer,n.name=n.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?n.base64String="data:image/png;base64,"+(0,Oe.Gh)(this._buffer):(Le.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(n.base64String=!this._engine||this._engine._features.supportSyncTextureRead?Ne(this):Fe(this))),n.invertY=this._invertY,n.samplingMode=this.samplingMode,n._creationFlags=this._creationFlags,n._useSRGBBuffer=this._useSRGBBuffer,Le._SerializeInternalTextureUniqueId&&(n.internalTextureUniqueId=null!==(t=null===(e=this._texture)||void 0===e?void 0:e.uniqueId)&&void 0!==t?t:void 0),this.name=i,n):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=Ie.K.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 Le._CubeTextureParser(e,t,i);const n=void 0!==e.internalTextureUniqueId;if(!e.name&&!e.isRenderTarget&&!n)return null;let s;if(n){const i=t.getEngine().getLoadedTexturesCache();for(const t of i)if(t.uniqueId===e.internalTextureUniqueId){s=t;break}}const r=t=>{var i;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 n=0;n{var n,o,a;let l=!0;if(e.noMipmap&&(l=!1),e.mirrorPlane){const i=Le._CreateMirror(e.name,e.renderTargetSize,t,l);return i._waitingRenderList=e.renderList,i.mirrorPlane=Me.J.FromArray(e.mirrorPlane),r(i),i}if(e.isRenderTarget){let i=null;if(e.isCube){if(t.reflectionProbes)for(let n=0;n{r(n)}),null!==(o=e._creationFlags)&&void 0!==o?o:0,null!==(a=e._useSRGBBuffer)&&void 0!==a&&a),n.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:")||Le.UseSerializedUrlIfAny)&&(o=e.url);const a={noMipmap:!l,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{r(n)},internalTexture:s};n=new Le(o,t,a)}return n}}),e,t)}static CreateFromBase64String(e,t,i,n,s,r=Le.TRILINEAR_SAMPLINGMODE,o=null,a=null,l=5,h){return new Le("data:"+t,i,n,s,r,o,a,e,!1,l,void 0,void 0,h)}static LoadFromDataString(e,t,i,n=!1,s,r=!0,o=Le.TRILINEAR_SAMPLINGMODE,a=null,l=null,h=5,c){return"data:"!==e.substr(0,5)&&(e="data:"+e),new Le(e,i,s,r,o,a,l,t,n,h,void 0,void 0,c)}}Le.SerializeBuffers=!0,Le.ForceSerializeBuffers=!1,Le.OnTextureLoadErrorObservable=new r.y$,Le._SerializeInternalTextureUniqueId=!1,Le._CubeTextureParser=(e,t,i)=>{throw(0,ge.S)("CubeTexture")},Le._CreateMirror=(e,t,i,n)=>{throw(0,ge.S)("MirrorTexture")},Le._CreateRenderTargetTexture=(e,t,i,n,s)=>{throw(0,ge.S)("RenderTargetTexture")},Le.NEAREST_SAMPLINGMODE=1,Le.NEAREST_NEAREST_MIPLINEAR=8,Le.BILINEAR_SAMPLINGMODE=2,Le.LINEAR_LINEAR_MIPNEAREST=11,Le.TRILINEAR_SAMPLINGMODE=3,Le.LINEAR_LINEAR_MIPLINEAR=3,Le.NEAREST_NEAREST_MIPNEAREST=4,Le.NEAREST_LINEAR_MIPNEAREST=5,Le.NEAREST_LINEAR_MIPLINEAR=6,Le.NEAREST_LINEAR=7,Le.NEAREST_NEAREST=1,Le.LINEAR_NEAREST_MIPNEAREST=9,Le.LINEAR_NEAREST_MIPLINEAR=10,Le.LINEAR_LINEAR=2,Le.LINEAR_NEAREST=12,Le.EXPLICIT_MODE=0,Le.SPHERICAL_MODE=1,Le.PLANAR_MODE=2,Le.CUBIC_MODE=3,Le.PROJECTION_MODE=4,Le.SKYBOX_MODE=5,Le.INVCUBIC_MODE=6,Le.EQUIRECTANGULAR_MODE=7,Le.FIXED_EQUIRECTANGULAR_MODE=8,Le.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,Le.CLAMP_ADDRESSMODE=0,Le.WRAP_ADDRESSMODE=1,Le.MIRROR_ADDRESSMODE=2,Le.UseSerializedUrlIfAny=!1,(0,oe.gn)([(0,E.qC)()],Le.prototype,"url",void 0),(0,oe.gn)([(0,E.qC)()],Le.prototype,"uOffset",void 0),(0,oe.gn)([(0,E.qC)()],Le.prototype,"vOffset",void 0),(0,oe.gn)([(0,E.qC)()],Le.prototype,"uScale",void 0),(0,oe.gn)([(0,E.qC)()],Le.prototype,"vScale",void 0),(0,oe.gn)([(0,E.qC)()],Le.prototype,"uAng",void 0),(0,oe.gn)([(0,E.qC)()],Le.prototype,"vAng",void 0),(0,oe.gn)([(0,E.qC)()],Le.prototype,"wAng",void 0),(0,oe.gn)([(0,E.qC)()],Le.prototype,"uRotationCenter",void 0),(0,oe.gn)([(0,E.qC)()],Le.prototype,"vRotationCenter",void 0),(0,oe.gn)([(0,E.qC)()],Le.prototype,"wRotationCenter",void 0),(0,oe.gn)([(0,E.qC)()],Le.prototype,"homogeneousRotationInUVTransform",void 0),(0,oe.gn)([(0,E.qC)()],Le.prototype,"isBlocking",null),(0,l.H)("BABYLON.Texture",Le),E.p4._TextureParser=Le.Parse;var Be=i(4679),Ue=i(9271);function Ve(e,t,i,n){let s,r=1;1===n?s=new Float32Array(t*i*4):2===n?(s=new Uint16Array(t*i*4),r=15360):s=7===n?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let o=0;o{const i=p.width,r=o(e);if(r){if(a){const e=this._getWebGLTextureType(s);let t=this._getInternalFormat(n);const o=this._getRGBABufferInternalSizedFormat(s);let l=!1;t===u.RGB&&(t=u.RGBA,l=!0),this._bindTextureDirectly(u.TEXTURE_CUBE_MAP,p,!0),this._unpackFlipY(!1);const h=a(r);for(let n=0;n>n;for(let i=0;i<6;i++){let a=h[n][i];l&&(a=Ve(a,r,r,s)),u.texImage2D(i,n,o,r,r,0,t,e,a)}}this._bindTextureDirectly(u.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(p,r,n,s,d);p.isReady=!0,null==t||t.removePendingData(p),p.onLoadedObservable.notifyObservers(p),p.onLoadedObservable.clear(),l&&l()}};return this._loadFile(e,(e=>{f(e)}),void 0,null==t?void 0:t.offlineProvider,!0,((e,i)=>{null==t||t.removePendingData(p),h&&e&&h(e.status+" "+e.statusText,i)})),p},Ue.B.prototype.createRawTexture2DArray=ke(!1),Ue.B.prototype.createRawTexture3D=ke(!0),Ue.B.prototype.updateRawTexture2DArray=Ge(!1),Ue.B.prototype.updateRawTexture3D=Ge(!0);class ze extends Le{constructor(e,t,i,n,s,r=!0,o=!1,a=3,l=0,h,c){super(null,s,!r,o,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,h),this.format=n,this._engine&&(this._engine._caps.textureFloatLinearFiltering||1!==l||(a=1),this._engine._caps.textureHalfFloatLinearFiltering||2!==l||(a=1),this._texture=this._engine.createRawTexture(e,t,i,n,r,o,a,null,l,null!=h?h:0,null!=c&&c),this.wrapU=Le.CLAMP_ADDRESSMODE,this.wrapV=Le.CLAMP_ADDRESSMODE)}update(e){this._getEngine().updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type,this._texture._useSRGBBuffer)}static CreateLuminanceTexture(e,t,i,n,s=!0,r=!1,o=3){return new ze(e,t,i,1,n,s,r,o)}static CreateLuminanceAlphaTexture(e,t,i,n,s=!0,r=!1,o=3){return new ze(e,t,i,2,n,s,r,o)}static CreateAlphaTexture(e,t,i,n,s=!0,r=!1,o=3){return new ze(e,t,i,0,n,s,r,o)}static CreateRGBTexture(e,t,i,n,s=!0,r=!1,o=3,a=0,l=0,h=!1){return new ze(e,t,i,4,n,s,r,o,a,l,h)}static CreateRGBATexture(e,t,i,n,s=!0,r=!1,o=3,a=0,l=0,h=!1){return new ze(e,t,i,5,n,s,r,o,a,l,h)}static CreateRGBAStorageTexture(e,t,i,n,s=!0,r=!1,o=3,a=0,l=!1){return new ze(e,t,i,5,n,s,r,o,a,1,l)}static CreateRTexture(e,t,i,n,s=!0,r=!1,o=Le.TRILINEAR_SAMPLINGMODE,a=1){return new ze(e,t,i,6,n,s,r,o,a)}static CreateRStorageTexture(e,t,i,n,s=!0,r=!1,o=Le.TRILINEAR_SAMPLINGMODE,a=1){return new ze(e,t,i,6,n,s,r,o,a,1)}}var We=i(27);class He{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!==We.kD.POINTERDOWN?e.type===We.kD.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{if(this._reachTargetAlpha())return;const e=F.F.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=null!=e?e:F.F.Now}_reachTargetAlpha(){return!(!this._attachedCamera||!this.targetAlpha)&&Math.abs(this._attachedCamera.alpha-this.targetAlpha){if(!e)return;e.computeWorldMatrix(!0);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||(Xe.EasingFunction.setEasingMode(Xe.EasingMode),this._radiusBounceTransition=A.CreateAnimation("radius",A.ANIMATIONTYPE_FLOAT,60,Xe.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=A.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()}}Xe.EasingFunction=new class extends Y{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),Xe.EasingMode=Y.EASINGMODE_EASEOUT;class Ye{constructor(){this.onTargetFramingAnimationEndObservable=new r.y$,this._mode=Ye.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();Ye.EasingFunction.setEasingMode(Ye.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==We.kD.POINTERDOWN?e.type===We.kD.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add((e=>{e&&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 o.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new o.P(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let r=0;r{this.stopAllAnimations(),n&&n(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()})),h&&this._animatables.push(h)}_calculateLowerRadiusFromModelBoundingSphere(e,t){const i=t.subtract(e).length(),n=this._getFrustumSlope(),s=.5*i*this._radiusScale,r=s*Math.sqrt(1+1/(n.x*n.x)),o=s*Math.sqrt(1+1/(n.y*n.y));let a=Math.max(r,o);const l=this._attachedCamera;return l?(l.lowerRadiusLimit&&this._mode===Ye.IgnoreBoundsSizeMode&&(a=al.upperRadiusLimit?l.upperRadiusLimit:a),a):0}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=F.F.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=A.CreateAnimation("beta",A.ANIMATIONTYPE_FLOAT,60,Ye.EasingFunction));const e=A.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,(()=>{this._clearAnimationLocks(),this.stopAllAnimations()}));e&&this._animatables.push(e)}}_getFrustumSlope(){const e=this._attachedCamera;if(!e)return o.FM.Zero();const t=e.getScene().getEngine().getAspectRatio(e),i=Math.tan(e.fov/2),n=i*t;return new o.FM(n,i)}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=F.F.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)}}Ye.EasingFunction=new class extends Y{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)}},Ye.EasingMode=Y.EASINGMODE_EASEINOUT,Ye.IgnoreBoundsSizeMode=0,Ye.FitFrustumSidesMode=1;var je=i(318),Ke=i(3573);class qe{constructor(e,t,i=Number.MAX_VALUE){this.origin=e,this.direction=t,this.length=i}clone(){return new qe(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){const n=qe._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),s=qe._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i);let r,o,a,l,h=0,c=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.xs.x)return!1}else if(r=1/this.direction.x,o=(n.x-this.origin.x)*r,a=(s.x-this.origin.x)*r,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.ys.y)return!1}else if(r=1/this.direction.y,o=(n.y-this.origin.y)*r,a=(s.y-this.origin.y)*r,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zs.z)return!1}else if(r=1/this.direction.z,o=(n.z-this.origin.z)*r,a=(s.z-this.origin.z)*r,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;return!0}intersectsBox(e,t=0){return this.intersectsBoxMinMax(e.minimum,e.maximum,t)}intersectsSphere(e,t=0){const i=e.center.x-this.origin.x,n=e.center.y-this.origin.y,s=e.center.z-this.origin.z,r=i*i+n*n+s*s,o=e.radius+t,a=o*o;if(r<=a)return!0;const l=i*this.direction.x+n*this.direction.y+s*this.direction.z;if(l<0)return!1;return r-l*l<=a}intersectsTriangle(e,t,i){const n=qe._TmpVector3[0],s=qe._TmpVector3[1],r=qe._TmpVector3[2],a=qe._TmpVector3[3],l=qe._TmpVector3[4];t.subtractToRef(e,n),i.subtractToRef(e,s),o.P.CrossToRef(this.direction,s,r);const h=o.P.Dot(n,r);if(0===h)return null;const c=1/h;this.origin.subtractToRef(e,a);const d=o.P.Dot(a,r)*c;if(d<0||d>1)return null;o.P.CrossToRef(a,n,l);const u=o.P.Dot(this.direction,l)*c;if(u<0||d+u>1)return null;const p=o.P.Dot(s,l)*c;return p>this.length?null:new Ke.c(1-d-u,d,p)}intersectsPlane(e){let t;const i=o.P.Dot(e.normal,this.direction);if(Math.abs(i)<9.99999997475243e-7)return null;{const n=o.P.Dot(e.normal,this.origin);return t=(-e.d-n)/i,t<0?t<-9.99999997475243e-7?null:0:t}}intersectsAxis(e,t=0){switch(e){case"y":{const e=(this.origin.y-t)/this.direction.y;return e>0?null:new o.P(this.origin.x+this.direction.x*-e,t,this.origin.z+this.direction.z*-e)}case"x":{const e=(this.origin.x-t)/this.direction.x;return e>0?null:new o.P(t,this.origin.y+this.direction.y*-e,this.origin.z+this.direction.z*-e)}case"z":{const e=(this.origin.z-t)/this.direction.z;return e>0?null:new o.P(this.origin.x+this.direction.x*-e,this.origin.y+this.direction.y*-e,t)}default:return null}}intersectsMesh(e,t,i,n=!1,s,r=!1){const a=o.jp.Matrix[0];return e.getWorldMatrix().invertToRef(a),this._tmpRay?qe.TransformToRef(this,a,this._tmpRay):this._tmpRay=qe.Transform(this,a),e.intersects(this._tmpRay,t,i,n,s,r)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let n=0;nt.distance?1:0}intersectionSegment(e,t,i){const n=this.origin,s=o.jp.Vector3[0],r=o.jp.Vector3[1],a=o.jp.Vector3[2],l=o.jp.Vector3[3];t.subtractToRef(e,s),this.direction.scaleToRef(qe._Rayl,a),n.addToRef(a,r),e.subtractToRef(n,l);const h=o.P.Dot(s,s),c=o.P.Dot(s,a),d=o.P.Dot(a,a),u=o.P.Dot(s,l),p=o.P.Dot(a,l),f=h*d-c*c;let _,m,g=f,v=f;fg&&(_=g,m=p+c,v=d)),m<0?(m=0,-u<0?_=0:-u>h?_=g:(_=-u,g=h)):m>v&&(m=v,-u+c<0?_=0:-u+c>h?_=g:(_=-u+c,g=h));const T=Math.abs(_)0&&S<=this.length&&b.lengthSquared()=e.distance?null:h:null},N.x.prototype._internalPick=function(e,t,i,n,s){let r=null;const a=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),l=this.cameraToUseForPointers||this.activeCamera;for(let h=0;h1&&this.cameraToUseForPointers!==this.activeCamera),r=this.cameraToUseForPointers||this.activeCamera;for(let a=0;a(this._tempPickingRay||(this._tempPickingRay=qe.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,s||null),this._tempPickingRay)),i,n,!0);return r&&(r.ray=this.createPickingRay(e,t,o.y3.Identity(),s||null)),r},Object.defineProperty(N.x.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1}),N.x.prototype.pick=function(e,t,i,n,s,r,a=!1){const l=this._internalPick(((i,n)=>(this._tempPickingRay||(this._tempPickingRay=qe.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,s||null,!1,n),this._tempPickingRay)),i,n,!1,r);return l&&(l.ray=this.createPickingRay(e,t,o.y3.Identity(),s||null)),l},N.x.prototype.pickWithRay=function(e,t,i,n){const s=this._internalPick((t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=o.y3.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=qe.Zero()),qe.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform)),t,i,!1,n);return s&&(s.ray=e),s},N.x.prototype.multiPick=function(e,t,i,n,s){return this._internalMultiPick((i=>this.createPickingRay(e,t,i,n||null)),i,s)},N.x.prototype.multiPickWithRay=function(e,t,i){return this._internalMultiPick((t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=o.y3.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=qe.Zero()),qe.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform)),t,i)},ce.V.prototype.getForwardRay=function(e=100,t,i){return this.getForwardRayToRef(new qe(o.P.Zero(),o.P.Zero(),e),e,t,i)},ce.V.prototype.getForwardRayToRef=function(e,t=100,i,n){return i||(i=this.getWorldMatrix()),e.length=t,n?e.origin.copyFrom(n):e.origin.copyFrom(this.position),o.jp.Vector3[2].set(0,0,this._scene.useRightHandedSystem?-1:1),o.P.TransformNormalToRef(o.jp.Vector3[2],i,o.jp.Vector3[3]),o.P.NormalizeToRef(o.jp.Vector3[3],e.direction),e};class $e{static _RemoveAndStorePivotPoint(e){e&&0===$e._PivotCached&&(e.getPivotPointToRef($e._OldPivotPoint),$e._PivotPostMultiplyPivotMatrix=e._postMultiplyPivotMatrix,$e._OldPivotPoint.equalsToFloats(0,0,0)||(e.setPivotMatrix(o.y3.IdentityReadOnly),$e._OldPivotPoint.subtractToRef(e.getPivotPoint(),$e._PivotTranslation),$e._PivotTmpVector.copyFromFloats(1,1,1),$e._PivotTmpVector.subtractInPlace(e.scaling),$e._PivotTmpVector.multiplyInPlace($e._PivotTranslation),e.position.addInPlace($e._PivotTmpVector))),$e._PivotCached++}static _RestorePivotPoint(e){e&&!$e._OldPivotPoint.equalsToFloats(0,0,0)&&1===$e._PivotCached&&(e.setPivotPoint($e._OldPivotPoint),e._postMultiplyPivotMatrix=$e._PivotPostMultiplyPivotMatrix,$e._PivotTmpVector.copyFromFloats(1,1,1),$e._PivotTmpVector.subtractInPlace(e.scaling),$e._PivotTmpVector.multiplyInPlace($e._PivotTranslation),e.position.subtractInPlace($e._PivotTmpVector)),this._PivotCached--}}$e._PivotCached=0,$e._OldPivotPoint=new o.P,$e._PivotTranslation=new o.P,$e._PivotTmpVector=new o.P,$e._PivotPostMultiplyPivotMatrix=!1;var Qe=i(2341);function Ze(e){const t=[],i=[],n=[],s=[],r=e.width||e.size||1,o=e.height||e.size||1,a=0===e.sideOrientation?0:e.sideOrientation||Qe.x.DEFAULTSIDE,l=r/2,h=o/2;i.push(-l,-h,0),n.push(0,0,-1),s.push(0,we.e.UseOpenGLOrientationForUV?1:0),i.push(l,-h,0),n.push(0,0,-1),s.push(1,we.e.UseOpenGLOrientationForUV?1:0),i.push(l,h,0),n.push(0,0,-1),s.push(1,we.e.UseOpenGLOrientationForUV?0:1),i.push(-l,h,0),n.push(0,0,-1),s.push(0,we.e.UseOpenGLOrientationForUV?0:1),t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),Qe.x._ComputeSides(a,i,t,n,s,e.frontUVs,e.backUVs);const c=new Qe.x;return c.indices=t,c.positions=i,c.normals=n,c.uvs=s,c}function Je(e,t={},i=null){const n=new ee.Kj(e,i);t.sideOrientation=ee.Kj._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation;return Ze(t).applyToMesh(n,t.updatable),t.sourcePlane&&(n.translate(t.sourcePlane.normal,-t.sourcePlane.d),n.setDirection(t.sourcePlane.normal.scale(-1))),n}Qe.x.CreatePlane=Ze,ee.Kj.CreatePlane=(e,t,i,n,s)=>Je(e,{size:t,width:t,height:t,sideOrientation:s,updatable:n},i);class et{get currentDraggingPointerID(){return this.currentDraggingPointerId}set currentDraggingPointerID(e){this.currentDraggingPointerId=e}set enabled(e){e!=this._enabled&&this.onEnabledObservable.notifyObservers(e),this._enabled=e}get enabled(){return this._enabled}get options(){return this._options}set options(e){this._options=e}constructor(e){this._useAlternatePickedPointAboveMaxDragAngleDragSpeed=-1.1,this._activeDragButton=-1,this.maxDragAngle=0,this.dragButtons=[0,1,2],this._useAlternatePickedPointAboveMaxDragAngle=!1,this.currentDraggingPointerId=-1,this.dragging=!1,this.dragDeltaRatio=.2,this.updateDragPlane=!0,this._debugMode=!1,this._moving=!1,this.onDragObservable=new r.y$,this.onDragStartObservable=new r.y$,this.onDragEndObservable=new r.y$,this.onEnabledObservable=new r.y$,this.moveAttached=!0,this._enabled=!0,this.startAndReleaseDragOnPointerEvents=!0,this.detachCameraControls=!0,this.useObjectOrientationForDragging=!0,this.validateDrag=e=>!0,this._tmpVector=new o.P(0,0,0),this._alternatePickedPoint=new o.P(0,0,0),this._worldDragAxis=new o.P(0,0,0),this._targetPosition=new o.P(0,0,0),this._attachedToElement=!1,this._startDragRay=new qe(new o.P,new o.P),this._lastPointerRay={},this._dragDelta=new o.P,this._pointA=new o.P(0,0,0),this._pointC=new o.P(0,0,0),this._localAxis=new o.P(0,0,0),this._lookAt=new o.P(0,0,0),this._options=e||{};let t=0;if(this._options.dragAxis&&t++,this._options.dragPlaneNormal&&t++,t>1)throw"Multiple drag modes specified in dragBehavior options. Only one expected"}get name(){return"PointerDrag"}init(){}attach(e,t){this._scene=e.getScene(),e.isNearGrabbable=!0,this.attachedNode=e,et._PlaneScene||(this._debugMode?et._PlaneScene=this._scene:(et._PlaneScene=new N.x(this._scene.getEngine(),{virtual:!0}),et._PlaneScene.detachControl(),this._scene.onDisposeObservable.addOnce((()=>{et._PlaneScene.dispose(),et._PlaneScene=null})))),this._dragPlane=Je("pointerDragPlane",{size:this._debugMode?1:1e4,updatable:!1,sideOrientation:ee.Kj.DOUBLESIDE},et._PlaneScene),this.lastDragPosition=new o.P(0,0,0);const i=t||(e=>this.attachedNode==e||e.isDescendantOf(this.attachedNode));this._pointerObserver=this._scene.onPointerObservable.add((e=>{if(this.enabled){if(e.type==We.kD.POINTERDOWN)this.startAndReleaseDragOnPointerEvents&&!this.dragging&&e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh&&e.pickInfo.pickedPoint&&e.pickInfo.ray&&i(e.pickInfo.pickedMesh)&&-1===this._activeDragButton&&-1!==this.dragButtons.indexOf(e.event.button)&&(this._activeDragButton=e.event.button,this._activePointerInfo=e,this._startDrag(e.event.pointerId,e.pickInfo.ray,e.pickInfo.pickedPoint));else if(e.type==We.kD.POINTERUP)!this.startAndReleaseDragOnPointerEvents||this.currentDraggingPointerId!=e.event.pointerId||this._activeDragButton!==e.event.button&&-1!==this._activeDragButton||this.releaseDrag();else if(e.type==We.kD.POINTERMOVE){const t=e.event.pointerId;if(this.currentDraggingPointerId===et._AnyMouseId&&t!==et._AnyMouseId){const i=e.event;("mouse"===i.pointerType||!this._scene.getEngine().hostInformation.isMobile&&i instanceof MouseEvent)&&(this._lastPointerRay[this.currentDraggingPointerId]&&(this._lastPointerRay[t]=this._lastPointerRay[this.currentDraggingPointerId],delete this._lastPointerRay[this.currentDraggingPointerId]),this.currentDraggingPointerId=t)}this._lastPointerRay[t]||(this._lastPointerRay[t]=new qe(new o.P,new o.P)),e.pickInfo&&e.pickInfo.ray&&(this._lastPointerRay[t].origin.copyFrom(e.pickInfo.ray.origin),this._lastPointerRay[t].direction.copyFrom(e.pickInfo.ray.direction),this.currentDraggingPointerId==t&&this.dragging&&this._moveDrag(e.pickInfo.ray))}}else this._attachedToElement&&this.releaseDrag()})),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add((()=>{if(this._moving&&this.moveAttached){let e=!1;$e._RemoveAndStorePivotPoint(this.attachedNode),this._targetPosition.subtractToRef(this.attachedNode.absolutePosition,this._tmpVector),this._tmpVector.scaleInPlace(this.dragDeltaRatio),this.attachedNode.getAbsolutePosition().addToRef(this._tmpVector,this._tmpVector),this.validateDrag(this._tmpVector)&&(this.attachedNode.setAbsolutePosition(this._tmpVector),e=!0),$e._RestorePivotPoint(this.attachedNode),e&&this.attachedNode.computeWorldMatrix()}}))}releaseDrag(){if(this.dragging&&(this.dragging=!1,this.onDragEndObservable.notifyObservers({dragPlanePoint:this.lastDragPosition,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo})),this.currentDraggingPointerId=-1,this._activeDragButton=-1,this._activePointerInfo=null,this._moving=!1,this.detachCameraControls&&this._attachedToElement&&this._scene.activeCamera&&!this._scene.activeCamera.leftCamera){if("ArcRotateCamera"===this._scene.activeCamera.getClassName()){const e=this._scene.activeCamera;e.attachControl(!e.inputs||e.inputs.noPreventDefault,e._useCtrlForPanning,e._panningMouseButton)}else this._scene.activeCamera.attachControl(!this._scene.activeCamera.inputs||this._scene.activeCamera.inputs.noPreventDefault);this._attachedToElement=!1}}startDrag(e=et._AnyMouseId,t,i){this._startDrag(e,t,i);let n=this._lastPointerRay[e];e===et._AnyMouseId&&(n=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),n&&this._moveDrag(n)}_startDrag(e,t,i){if(!this._scene.activeCamera||this.dragging||!this.attachedNode)return;$e._RemoveAndStorePivotPoint(this.attachedNode),t?(this._startDragRay.direction.copyFrom(t.direction),this._startDragRay.origin.copyFrom(t.origin)):(this._startDragRay.origin.copyFrom(this._scene.activeCamera.position),this.attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector),this._tmpVector.subtractToRef(this._scene.activeCamera.position,this._startDragRay.direction)),this._updateDragPlanePosition(this._startDragRay,i||this._tmpVector);const n=this._pickWithRayOnDragPlane(this._startDragRay);n?(this.dragging=!0,this.currentDraggingPointerId=e,this.lastDragPosition.copyFrom(n),this.onDragStartObservable.notifyObservers({dragPlanePoint:n,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition()),this.detachCameraControls&&this._scene.activeCamera&&this._scene.activeCamera.inputs&&!this._scene.activeCamera.leftCamera&&(this._scene.activeCamera.inputs.attachedToElement?(this._scene.activeCamera.detachControl(),this._attachedToElement=!0):this._attachedToElement=!1)):this.releaseDrag(),$e._RestorePivotPoint(this.attachedNode)}_moveDrag(e){this._moving=!0;const t=this._pickWithRayOnDragPlane(e);if(t){$e._RemoveAndStorePivotPoint(this.attachedNode),this.updateDragPlane&&this._updateDragPlanePosition(e,t);let i=0;this._options.dragAxis?(this.useObjectOrientationForDragging?o.P.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis):this._worldDragAxis.copyFrom(this._options.dragAxis),t.subtractToRef(this.lastDragPosition,this._tmpVector),i=o.P.Dot(this._tmpVector,this._worldDragAxis),this._worldDragAxis.scaleToRef(i,this._dragDelta)):(i=this._dragDelta.length(),t.subtractToRef(this.lastDragPosition,this._dragDelta)),this._targetPosition.addInPlace(this._dragDelta),this.onDragObservable.notifyObservers({dragDistance:i,delta:this._dragDelta,dragPlanePoint:t,dragPlaneNormal:this._dragPlane.forward,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this.lastDragPosition.copyFrom(t),$e._RestorePivotPoint(this.attachedNode)}}_pickWithRayOnDragPlane(e){if(!e)return null;let t=Math.acos(o.P.Dot(this._dragPlane.forward,e.direction));if(t>Math.PI/2&&(t=Math.PI-t),this.maxDragAngle>0&&t>this.maxDragAngle){if(this._useAlternatePickedPointAboveMaxDragAngle){this._tmpVector.copyFrom(e.direction),this.attachedNode.absolutePosition.subtractToRef(e.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed*o.P.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);const t=o.P.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-t,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition),this._alternatePickedPoint}return null}const i=et._PlaneScene.pickWithRay(e,(e=>e==this._dragPlane));return i&&i.hit&&i.pickedMesh&&i.pickedPoint?i.pickedPoint:null}_updateDragPlanePosition(e,t){this._pointA.copyFrom(t),this._options.dragAxis?(this.useObjectOrientationForDragging?o.P.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragAxis),e.origin.subtractToRef(this._pointA,this._pointC),this._pointC.normalize(),Math.abs(o.P.Dot(this._localAxis,this._pointC))>.999?Math.abs(o.P.Dot(o.P.UpReadOnly,this._pointC))>.999?this._lookAt.copyFrom(o.P.Right()):this._lookAt.copyFrom(o.P.UpReadOnly):(o.P.CrossToRef(this._localAxis,this._pointC,this._lookAt),o.P.CrossToRef(this._localAxis,this._lookAt,this._lookAt),this._lookAt.normalize()),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._lookAt,this._lookAt),this._dragPlane.lookAt(this._lookAt)):this._options.dragPlaneNormal?(this.useObjectOrientationForDragging?o.P.TransformCoordinatesToRef(this._options.dragPlaneNormal,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragPlaneNormal),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._localAxis,this._lookAt),this._dragPlane.lookAt(this._lookAt)):(this._dragPlane.position.copyFrom(this._pointA),this._dragPlane.lookAt(e.origin)),this._dragPlane.position.copyFrom(this.attachedNode.getAbsolutePosition()),this._dragPlane.computeWorldMatrix(!0)}detach(){this._lastPointerRay={},this.attachedNode&&(this.attachedNode.isNearGrabbable=!1),this._pointerObserver&&this._scene.onPointerObservable.remove(this._pointerObserver),this._beforeRenderObserver&&this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver),this._dragPlane&&this._dragPlane.dispose(),this.releaseDrag()}}et._AnyMouseId=-2;class tt{}tt.ANCHOR_SYSTEM="xr-anchor-system",tt.BACKGROUND_REMOVER="xr-background-remover",tt.HIT_TEST="xr-hit-test",tt.MESH_DETECTION="xr-mesh-detection",tt.PHYSICS_CONTROLLERS="xr-physics-controller",tt.PLANE_DETECTION="xr-plane-detection",tt.POINTER_SELECTION="xr-controller-pointer-selection",tt.TELEPORTATION="xr-controller-teleportation",tt.FEATURE_POINTS="xr-feature-points",tt.HAND_TRACKING="xr-hand-tracking",tt.IMAGE_TRACKING="xr-image-tracking",tt.NEAR_INTERACTION="xr-near-interaction",tt.DOM_OVERLAY="xr-dom-overlay",tt.MOVEMENT="xr-controller-movement",tt.LIGHT_ESTIMATION="xr-light-estimation",tt.EYE_TRACKING="xr-eye-tracking",tt.WALKING_LOCOMOTION="xr-walking-locomotion",tt.LAYERS="xr-layers",tt.DEPTH_SENSING="xr-depth-sensing",tt.SPACE_WARP="xr-space-warp";class it{constructor(e){this._xrSessionManager=e,this._features={},this._xrSessionManager.onXRSessionInit.add((()=>{this.getEnabledFeatures().forEach((e=>{const t=this._features[e];!t.enabled||t.featureImplementation.attached||t.featureImplementation.disableAutoAttach||this.attachFeature(e)}))})),this._xrSessionManager.onXRSessionEnded.add((()=>{this.getEnabledFeatures().forEach((e=>{const t=this._features[e];t.enabled&&t.featureImplementation.attached&&this.detachFeature(e)}))}))}static AddWebXRFeature(e,t,i=1,n=!1){this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),n&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t}static ConstructFeature(e,t=1,i,n){const s=this._AvailableFeatures[e][t];if(!s)throw new Error("feature not found");return s(i,n)}static GetAvailableFeatures(){return Object.keys(this._AvailableFeatures)}static GetAvailableVersions(e){return Object.keys(this._AvailableFeatures[e])}static GetLatestVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].latest||-1}static GetStableVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].stable||-1}attachFeature(e){const t=this._features[e];t&&t.enabled&&!t.featureImplementation.attached&&t.featureImplementation.attach()}detachFeature(e){const t=this._features[e];t&&t.featureImplementation.attached&&t.featureImplementation.detach()}disableFeature(e){const t="string"==typeof e?e:e.Name,i=this._features[t];return!(!i||!i.enabled)&&(i.enabled=!1,this.detachFeature(t),i.featureImplementation.dispose(),delete this._features[t],!0)}dispose(){this.getEnabledFeatures().forEach((e=>{this.disableFeature(e)}))}enableFeature(e,t="latest",i={},n=!0,s=!0){const r="string"==typeof e?e:e.Name;let o=0;if("string"==typeof t){if(!t)throw new Error(`Error in provided version - ${r} (${t})`);if(o="stable"===t?it.GetStableVersionOfFeature(r):"latest"===t?it.GetLatestVersionOfFeature(r):+t,-1===o||isNaN(o))throw new Error(`feature not found - ${r} (${t})`)}else o=t;const a=it._ConflictingFeatures[r];if(void 0!==a&&-1!==this.getEnabledFeatures().indexOf(a))throw new Error(`Feature ${r} cannot be enabled while ${a} is enabled.`);const l=this._features[r],h=it.ConstructFeature(r,o,this._xrSessionManager,i);if(!h)throw new Error(`feature not found - ${r}`);l&&this.disableFeature(r);const c=h();if(c.dependsOn){const e=c.dependsOn.every((e=>!!this._features[e]));if(!e)throw new Error(`Dependant features missing. Make sure the following features are enabled - ${c.dependsOn.join(", ")}`)}if(c.isCompatible())return this._features[r]={featureImplementation:c,enabled:!0,version:o,required:s},n?this._xrSessionManager.session&&!this._features[r].featureImplementation.attached&&this.attachFeature(r):this._features[r].featureImplementation.disableAutoAttach=!0,this._features[r].featureImplementation;if(s)throw new Error("required feature not compatible");return se.w1.Warn(`Feature ${r} not compatible with the current environment/browser and was not enabled.`),c}getEnabledFeature(e){return this._features[e]&&this._features[e].featureImplementation}getEnabledFeatures(){return Object.keys(this._features)}async _extendXRSessionInitObject(e){const t=this.getEnabledFeatures();for(const i of t){const t=this._features[i],n=t.featureImplementation.xrNativeFeatureName;if(n&&(t.required?(e.requiredFeatures=e.requiredFeatures||[],-1===e.requiredFeatures.indexOf(n)&&e.requiredFeatures.push(n)):(e.optionalFeatures=e.optionalFeatures||[],-1===e.optionalFeatures.indexOf(n)&&e.optionalFeatures.push(n))),t.featureImplementation.getXRSessionInitExtension){const i=await t.featureImplementation.getXRSessionInitExtension();e=Object.assign(Object.assign({},e),i)}}return e}}it._AvailableFeatures={},it._ConflictingFeatures={[tt.TELEPORTATION]:tt.MOVEMENT,[tt.MOVEMENT]:tt.TELEPORTATION};class nt{constructor(e){this._xrSessionManager=e,this._attached=!1,this._removeOnDetach=[],this.isDisposed=!1,this.disableAutoAttach=!1,this.xrNativeFeatureName=""}get attached(){return this._attached}attach(e){if(this.isDisposed)return!1;if(e)this.attached&&this.detach();else if(this.attached)return!1;return this._attached=!0,this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable,(e=>this._onXRFrame(e))),!0}detach(){return this._attached?(this._attached=!1,this._removeOnDetach.forEach((e=>{e.observable.remove(e.observer)})),!0):(this.disableAutoAttach=!0,!1)}dispose(){this.detach(),this.isDisposed=!0}isCompatible(){return!0}_addNewAttachObserver(e,t){this._removeOnDetach.push({observable:e,observer:e.add(t)})}}class st{constructor(e,t){this.type=e,this.jointData=t,t.nativeParams=t.nativeParams||{}}get physicsJoint(){return this._physicsJoint}set physicsJoint(e){this._physicsJoint,this._physicsJoint=e}set physicsPlugin(e){this._physicsPlugin=e}executeNativeFunction(e){e(this._physicsPlugin.world,this._physicsJoint)}}st.DistanceJoint=0,st.HingeJoint=1,st.BallAndSocketJoint=2,st.WheelJoint=3,st.SliderJoint=4,st.PrismaticJoint=5,st.UniversalJoint=6,st.Hinge2Joint=st.WheelJoint,st.PointToPointJoint=8,st.SpringJoint=9,st.LockJoint=10;ee.Kj._PhysicsImpostorParser=function(e,t,i){return new rt(t,i.physicsImpostor,{mass:i.physicsMass,friction:i.physicsFriction,restitution:i.physicsRestitution},e)};class rt{get isDisposed(){return this._isDisposed}get mass(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyMass(this):0}set mass(e){this.setMass(e)}get friction(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyFriction(this):0}set friction(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyFriction(this,e)}get restitution(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this):0}set restitution(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this,e)}get pressure(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.setBodyPressure?e.getBodyPressure(this):0}set pressure(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyPressure&&t.setBodyPressure(this,e)}get stiffness(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyStiffness?e.getBodyStiffness(this):0}set stiffness(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyStiffness&&t.setBodyStiffness(this,e)}get velocityIterations(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyVelocityIterations?e.getBodyVelocityIterations(this):0}set velocityIterations(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyVelocityIterations&&t.setBodyVelocityIterations(this,e)}get positionIterations(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyPositionIterations?e.getBodyPositionIterations(this):0}set positionIterations(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyPositionIterations&&t.setBodyPositionIterations(this,e)}constructor(e,t,i={mass:0},n){this.object=e,this.type=t,this._options=i,this._scene=n,this._pluginData={},this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=new Array,this._onAfterPhysicsStepCallbacks=new Array,this._onPhysicsCollideCallbacks=[],this._deltaPosition=o.P.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new o._f,this._tmpQuat2=new o._f,this.beforeStep=()=>{this._physicsEngine&&(this.object.translate(this._deltaPosition,-1),this._deltaRotationConjugated&&this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotationConjugated,this.object.rotationQuaternion),this.object.computeWorldMatrix(!1),this.object.parent&&this.object.rotationQuaternion?(this.getParentsRotation(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this._tmpQuat)):this._tmpQuat.copyFrom(this.object.rotationQuaternion||new o._f),this._options.disableBidirectionalTransformation||this.object.rotationQuaternion&&this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this,this.object.getAbsolutePosition(),this._tmpQuat),this._onBeforePhysicsStepCallbacks.forEach((e=>{e(this)})))},this.afterStep=()=>{this._physicsEngine&&(this._onAfterPhysicsStepCallbacks.forEach((e=>{e(this)})),this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(this),this.object.parent&&this.object.rotationQuaternion&&(this.getParentsRotation(),this._tmpQuat.conjugateInPlace(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this.object.rotationQuaternion)),this.object.setAbsolutePosition(this.object.position),this._deltaRotation?(this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotation,this.object.rotationQuaternion),this._deltaPosition.applyRotationQuaternionToRef(this._deltaRotation,rt._TmpVecs[0]),this.object.translate(rt._TmpVecs[0],1)):this.object.translate(this._deltaPosition,1),this.object.computeWorldMatrix(!0))},this.onCollideEvent=null,this.onCollide=e=>{if(!this._onPhysicsCollideCallbacks.length&&!this.onCollideEvent)return;if(!this._physicsEngine)return;const t=this._physicsEngine.getImpostorWithPhysicsBody(e.body);t&&(this.onCollideEvent&&this.onCollideEvent(this,t),this._onPhysicsCollideCallbacks.filter((e=>-1!==e.otherImpostors.indexOf(t))).forEach((i=>{i.callback(this,t,e.point,e.distance,e.impulse,e.normal)})))},this.object?(this.object.parent&&0!==i.mass&&p.Y.Warn("A physics impostor has been created for an object which has a parent. Babylon physics currently works in local space so unexpected issues may occur."),!this._scene&&e.getScene&&(this._scene=e.getScene()),this._scene&&(this.type>100&&(this.soft=!0),this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine?(this.object.rotationQuaternion||(this.object.rotation?this.object.rotationQuaternion=o._f.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new o._f),this._options.mass=void 0===i.mass?0:i.mass,this._options.friction=void 0===i.friction?.2:i.friction,this._options.restitution=void 0===i.restitution?.2:i.restitution,this.soft&&(this._options.mass=this._options.mass>0?this._options.mass:1,this._options.pressure=void 0===i.pressure?200:i.pressure,this._options.stiffness=void 0===i.stiffness?1:i.stiffness,this._options.velocityIterations=void 0===i.velocityIterations?20:i.velocityIterations,this._options.positionIterations=void 0===i.positionIterations?20:i.positionIterations,this._options.fixedPoints=void 0===i.fixedPoints?0:i.fixedPoints,this._options.margin=void 0===i.margin?0:i.margin,this._options.damping=void 0===i.damping?0:i.damping,this._options.path=void 0===i.path?null:i.path,this._options.shape=void 0===i.shape?null:i.shape),this._joints=[],!this.object.parent||this._options.ignoreParent?this._init():this.object.parent.physicsImpostor&&p.Y.Warn("You must affect impostors to children before affecting impostor to parent.")):p.Y.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."))):p.Y.Error("No object was provided. A physics object is obligatory")}_init(){this._physicsEngine&&(this._physicsEngine.removeImpostor(this),this.physicsBody=null,this._parent=this._parent||this._getPhysicsParent(),this._isDisposed||this.parent&&!this._options.ignoreParent||this._physicsEngine.addImpostor(this))}_getPhysicsParent(){if(this.object.parent instanceof ie.x){return this.object.parent.physicsImpostor}return null}isBodyInitRequired(){return this._bodyUpdateRequired||!this._physicsBody&&(!this._parent||!!this._options.ignoreParent)}setScalingUpdated(){this.forceUpdate()}forceUpdate(){this._init(),this.parent&&!this._options.ignoreParent&&this.parent.forceUpdate()}get physicsBody(){return this._parent&&!this._options.ignoreParent?this._parent.physicsBody:this._physicsBody}get parent(){return!this._options.ignoreParent&&this._parent?this._parent:null}set parent(e){this._parent=e}set physicsBody(e){this._physicsBody&&this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this),this._physicsBody=e,this.resetUpdateFlags()}resetUpdateFlags(){this._bodyUpdateRequired=!1}getObjectExtents(){if(this.object.getBoundingInfo){const e=this.object.rotationQuaternion,t=this.object.scaling.clone();this.object.rotationQuaternion=rt.IDENTITY_QUATERNION;const i=this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);i&&i.decompose(t,void 0,void 0);const n=this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiplyInPlace(t);return n.x=Math.abs(n.x),n.y=Math.abs(n.y),n.z=Math.abs(n.z),this.object.rotationQuaternion=e,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),n}return rt.DEFAULT_OBJECT_SIZE}getObjectCenter(){if(this.object.getBoundingInfo){return this.object.getBoundingInfo().boundingBox.centerWorld}return this.object.position}getParam(e){return this._options[e]}setParam(e,t){this._options[e]=t,this._bodyUpdateRequired=!0}setMass(e){this.getParam("mass")!==e&&this.setParam("mass",e),this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyMass(this,e)}getLinearVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this):o.P.Zero()}setLinearVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)}getAngularVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):o.P.Zero()}setAngularVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this,e)}executeNativeFunction(e){this._physicsEngine&&e(this._physicsEngine.getPhysicsPlugin().world,this.physicsBody)}registerBeforePhysicsStep(e){this._onBeforePhysicsStepCallbacks.push(e)}unregisterBeforePhysicsStep(e){const t=this._onBeforePhysicsStepCallbacks.indexOf(e);t>-1?this._onBeforePhysicsStepCallbacks.splice(t,1):p.Y.Warn("Function to remove was not found")}registerAfterPhysicsStep(e){this._onAfterPhysicsStepCallbacks.push(e)}unregisterAfterPhysicsStep(e){const t=this._onAfterPhysicsStepCallbacks.indexOf(e);t>-1?this._onAfterPhysicsStepCallbacks.splice(t,1):p.Y.Warn("Function to remove was not found")}registerOnPhysicsCollide(e,t){const i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})}unregisterOnPhysicsCollide(e,t){const i=e instanceof Array?e:[e];let n=-1;this._onPhysicsCollideCallbacks.some(((e,s)=>{if(e.callback===t&&e.otherImpostors.length===i.length){const t=e.otherImpostors.every((e=>i.indexOf(e)>-1));return t&&(n=s),t}return!1}))?this._onPhysicsCollideCallbacks.splice(n,1):p.Y.Warn("Function to remove was not found")}getParentsRotation(){let e=this.object.parent;for(this._tmpQuat.copyFromFloats(0,0,0,1);e;)e.rotationQuaternion?this._tmpQuat2.copyFrom(e.rotationQuaternion):o._f.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,this._tmpQuat2),this._tmpQuat.multiplyToRef(this._tmpQuat2,this._tmpQuat),e=e.parent;return this._tmpQuat}applyForce(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t),this}applyImpulse(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t),this}createJoint(e,t,i){const n=new st(t,i);return this.addJoint(e,n),this}addJoint(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this}addAnchor(e,t,i,n,s){if(!this._physicsEngine)return this;const r=this._physicsEngine.getPhysicsPlugin();return r.appendAnchor?(this._physicsEngine&&r.appendAnchor(this,e,t,i,n,s),this):this}addHook(e,t,i,n){if(!this._physicsEngine)return this;const s=this._physicsEngine.getPhysicsPlugin();return s.appendAnchor?(this._physicsEngine&&s.appendHook(this,e,t,i,n),this):this}sleep(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().sleepBody(this),this}wakeUp(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),this}clone(e){return e?new rt(e,this.type,this._options,this._scene):null}dispose(){this._physicsEngine&&(this._joints.forEach((e=>{this._physicsEngine&&this._physicsEngine.removeJoint(this,e.otherImpostor,e.joint)})),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate(),this._isDisposed=!0)}setDeltaPosition(e){this._deltaPosition.copyFrom(e)}setDeltaRotation(e){this._deltaRotation||(this._deltaRotation=new o._f),this._deltaRotation.copyFrom(e),this._deltaRotationConjugated=this._deltaRotation.conjugate()}getBoxSizeToRef(e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,e),this}getRadius(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0}syncBoneWithImpostor(e,t,i,n,s){const r=rt._TmpVecs[0],o=this.object;if(o.rotationQuaternion)if(s){const i=rt._TmpQuat;o.rotationQuaternion.multiplyToRef(s,i),e.setRotationQuaternion(i,L.T.WORLD,t)}else e.setRotationQuaternion(o.rotationQuaternion,L.T.WORLD,t);r.x=0,r.y=0,r.z=0,i&&(r.x=i.x,r.y=i.y,r.z=i.z,e.getDirectionToRef(r,t,r),null==n&&(n=i.length()),r.x*=n,r.y*=n,r.z*=n),e.getParent()?(r.addInPlace(o.getAbsolutePosition()),e.setAbsolutePosition(r,t)):(t.setAbsolutePosition(o.getAbsolutePosition()),t.position.x-=r.x,t.position.y-=r.y,t.position.z-=r.z)}syncImpostorWithBone(e,t,i,n,s,r){const o=this.object;if(o.rotationQuaternion)if(s){const i=rt._TmpQuat;e.getRotationQuaternionToRef(L.T.WORLD,t,i),i.multiplyToRef(s,o.rotationQuaternion)}else e.getRotationQuaternionToRef(L.T.WORLD,t,o.rotationQuaternion);const a=rt._TmpVecs[0],l=rt._TmpVecs[1];r||((r=rt._TmpVecs[2]).x=0,r.y=1,r.z=0),e.getDirectionToRef(r,t,l),e.getAbsolutePositionToRef(t,a),null==n&&i&&(n=i.length()),null!=n&&(a.x+=l.x*n,a.y+=l.y*n,a.z+=l.z*n),o.setAbsolutePosition(a)}}rt.DEFAULT_OBJECT_SIZE=new o.P(1,1,1),rt.IDENTITY_QUATERNION=o._f.Identity(),rt._TmpVecs=w.B.BuildArray(3,o.P.Zero),rt._TmpQuat=o._f.Identity(),rt.NoImpostor=0,rt.SphereImpostor=1,rt.BoxImpostor=2,rt.PlaneImpostor=3,rt.MeshImpostor=4,rt.CapsuleImpostor=6,rt.CylinderImpostor=7,rt.ParticleImpostor=8,rt.HeightmapImpostor=9,rt.ConvexHullImpostor=10,rt.CustomImpostor=100,rt.RopeImpostor=101,rt.ClothImpostor=102,rt.SoftbodyImpostor=103;var ot,at=i(5458),lt=i(9714);!function(e){e[e.Clean=0]="Clean",e[e.Stop=1]="Stop",e[e.Sync=2]="Sync",e[e.NoSync=3]="NoSync"}(ot||(ot={}));class ht{static get ForceFullSceneLoadingForIncremental(){return at.Z.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){at.Z.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return at.Z.ShowLoadingScreen}static set ShowLoadingScreen(e){at.Z.ShowLoadingScreen=e}static get loggingLevel(){return at.Z.loggingLevel}static set loggingLevel(e){at.Z.loggingLevel=e}static get CleanBoneMatrixWeights(){return at.Z.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){at.Z.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return ht._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){const t=ht._RegisteredPlugins[e];return t||(p.Y.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"),ht.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(const t in ht._RegisteredPlugins){const i=ht._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return ht._RegisteredPlugins[t]}return ht.GetDefaultPlugin()}static _GetPluginForFilename(e){const t=e.indexOf("?");-1!==t&&(e=e.substring(0,t));const i=e.lastIndexOf("."),n=e.substring(i,e.length).toLowerCase();return ht._GetPluginForExtension(n)}static _GetDirectLoad(e){return"data:"===e.substr(0,5)?e.substr(5):null}static _FormatErrorMessage(e,t,i){let n="Unable to load from "+(e.rawData?"binary data":e.url);return t?n+=`: ${t}`:i&&(n+=`: ${i}`),n}static _LoadData(e,t,i,n,s,r,o,a){const l=ht._GetDirectLoad(e.url);if(e.rawData&&!o)throw"When using ArrayBufferView to load data the file extension must be provided.";const h=o?ht._GetPluginForExtension(o):l?ht._GetPluginForDirectLoad(e.url):ht._GetPluginForFilename(e.url);if(e.rawData&&!h.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";let c;if(c=void 0!==h.plugin.createPlugin?h.plugin.createPlugin():h.plugin,!c)throw"The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.";if(ht.OnPluginActivatedObservable.notifyObservers(c),l&&(c.canDirectLoad&&c.canDirectLoad(e.url)||!(0,ye.VL)(e.url))){if(c.directLoad){const e=c.directLoad(t,l);e.then?e.then((e=>{i(c,e)})).catch((e=>{s("Error in directLoad of _loadData: "+e,e)})):i(c,e)}else i(c,l);return c}const d=h.isBinary,u=(e,n)=>{t.isDisposed?s("Scene has been disposed"):i(c,e,n)};let p=null,f=!1;const _=c.onDisposeObservable;_&&_.add((()=>{f=!0,p&&(p.abort(),p=null),r()}));const m=()=>{if(f)return;const i=(e,t)=>{s(null==e?void 0:e.statusText,t)};if(!c.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";p=c.loadFile?c.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,u,n,d,i,a):t._loadFile(e.file||e.url,u,n,!0,d,i)},g=t.getEngine();let v=g.enableOfflineSupport;if(v){let i=!1;for(const n of t.disableOfflineSupportExceptionRules)if(n.test(e.url)){i=!0;break}v=!i}return v&&fe.D.OfflineProviderFactory?t.offlineProvider=fe.D.OfflineProviderFactory(e.url,m,g.disableManifestCheck):m(),c}static _GetFileInfo(e,t){let i,n,s=null,r=null;if(t)if(t.name){const e=t;i=`file:${e.name}`,n=e.name,s=e}else if(ArrayBuffer.isView(t))i="",n="arrayBuffer",r=t;else if("string"==typeof t&&t.startsWith("data:"))i=t,n="";else{const s=t;if("/"===s.substr(0,1))return se.w1.Error("Wrong sceneFilename parameter"),null;i=e+s,n=s}else i=e,n=se.w1.GetFilename(e),e=se.w1.GetFolderPath(e);return{url:i,rootUrl:e,name:n,file:s,rawData:r}}static GetPluginForExtension(e){return ht._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!ht._RegisteredPlugins[e]}static RegisterPlugin(e){if("string"==typeof e.extensions){const t=e.extensions;ht._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{const t=e.extensions;Object.keys(t).forEach((i=>{ht._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}}))}}static ImportMesh(e,t,i="",n=m.l.LastCreatedScene,s=null,r=null,o=null,a=null,l=""){if(!n)return p.Y.Error("No scene available to import mesh to"),null;const h=ht._GetFileInfo(t,i);if(!h)return null;const c={};n.addPendingData(c);const d=()=>{n.removePendingData(c)},u=(e,t)=>{const i=ht._FormatErrorMessage(h,e,t);o?o(n,i,new lt.LH(i,lt.SM.SceneLoaderError,t)):p.Y.Error(i),d()},f=r?e=>{try{r(e)}catch(t){u("Error in onProgress callback: "+t,t)}}:void 0,_=(e,t,i,r,o,a,l)=>{if(n.importedMeshesFiles.push(h.url),s)try{s(e,t,i,r,o,a,l)}catch(d){u("Error in onSuccess callback: "+d,d)}n.removePendingData(c)};return ht._LoadData(h,n,((t,i,s)=>{if(t.rewriteRootURL&&(h.rootUrl=t.rewriteRootURL(h.rootUrl,s)),t.importMesh){const s=t,r=new Array,o=new Array,a=new Array;if(!s.importMesh(e,n,i,h.rootUrl,r,o,a,u))return;n.loadingPluginName=t.name,_(r,o,a,[],[],[],[])}else{t.importMeshAsync(e,n,i,h.rootUrl,f,h.name).then((e=>{n.loadingPluginName=t.name,_(e.meshes,e.particleSystems,e.skeletons,e.animationGroups,e.transformNodes,e.geometries,e.lights)})).catch((e=>{u(e.message,e)}))}}),f,u,d,a,l)}static ImportMeshAsync(e,t,i="",n=m.l.LastCreatedScene,s=null,r=null,o=""){return new Promise(((a,l)=>{ht.ImportMesh(e,t,i,n,((e,t,i,n,s,r,o)=>{a({meshes:e,particleSystems:t,skeletons:i,animationGroups:n,transformNodes:s,geometries:r,lights:o})}),s,((e,t,i)=>{l(i||new Error(t))}),r,o)}))}static Load(e,t="",i=m.l.LastCreatedEngine,n=null,s=null,r=null,o=null,a=""){return i?ht.Append(e,t,new N.x(i),n,s,r,o,a):(se.w1.Error("No engine available"),null)}static LoadAsync(e,t="",i=m.l.LastCreatedEngine,n=null,s=null,r=""){return new Promise(((o,a)=>{ht.Load(e,t,i,(e=>{o(e)}),n,((e,t,i)=>{a(i||new Error(t))}),s,r)}))}static Append(e,t="",i=m.l.LastCreatedScene,n=null,s=null,r=null,o=null,a=""){if(!i)return p.Y.Error("No scene available to append to"),null;const l=ht._GetFileInfo(e,t);if(!l)return null;const h={};i.addPendingData(h);const c=()=>{i.removePendingData(h)};ht.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady((()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1})));const d=(e,t)=>{const n=ht._FormatErrorMessage(l,e,t);r?r(i,n,new lt.LH(n,lt.SM.SceneLoaderError,t)):p.Y.Error(n),c()},u=s?e=>{try{s(e)}catch(t){d("Error in onProgress callback",t)}}:void 0,f=()=>{if(n)try{n(i)}catch(e){d("Error in onSuccess callback",e)}i.removePendingData(h)};return ht._LoadData(l,i,((e,t)=>{if(e.load){if(!e.load(i,t,l.rootUrl,d))return;i.loadingPluginName=e.name,f()}else{e.loadAsync(i,t,l.rootUrl,u,l.name).then((()=>{i.loadingPluginName=e.name,f()})).catch((e=>{d(e.message,e)}))}}),u,d,c,o,a)}static AppendAsync(e,t="",i=m.l.LastCreatedScene,n=null,s=null,r=""){return new Promise(((o,a)=>{ht.Append(e,t,i,(e=>{o(e)}),n,((e,t,i)=>{a(i||new Error(t))}),s,r)}))}static LoadAssetContainer(e,t="",i=m.l.LastCreatedScene,n=null,s=null,r=null,o=null,a=""){if(!i)return p.Y.Error("No scene available to load asset container to"),null;const l=ht._GetFileInfo(e,t);if(!l)return null;const h={};i.addPendingData(h);const c=()=>{i.removePendingData(h)},d=(e,t)=>{const n=ht._FormatErrorMessage(l,e,t);r?r(i,n,new lt.LH(n,lt.SM.SceneLoaderError,t)):p.Y.Error(n),c()},u=s?e=>{try{s(e)}catch(t){d("Error in onProgress callback",t)}}:void 0,f=e=>{if(n)try{n(e)}catch(t){d("Error in onSuccess callback",t)}i.removePendingData(h)};return ht._LoadData(l,i,((e,t)=>{if(e.loadAssetContainer){const n=e.loadAssetContainer(i,t,l.rootUrl,d);if(!n)return;i.loadingPluginName=e.name,f(n)}else if(e.loadAssetContainerAsync){e.loadAssetContainerAsync(i,t,l.rootUrl,u,l.name).then((t=>{i.loadingPluginName=e.name,f(t)})).catch((e=>{d(e.message,e)}))}else d("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")}),u,d,c,o,a)}static LoadAssetContainerAsync(e,t="",i=m.l.LastCreatedScene,n=null,s=null){return new Promise(((r,o)=>{ht.LoadAssetContainer(e,t,i,(e=>{r(e)}),n,((e,t,i)=>{o(i||new Error(t))}),s)}))}static ImportAnimations(e,t="",i=m.l.LastCreatedScene,n=!0,s=ot.Clean,r=null,o=null,a=null,l=null,h=null){if(!i)return void p.Y.Error("No scene available to load animations to");if(n){for(const e of i.animatables)e.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach((e=>{e.dispose()}));i.getNodes().forEach((e=>{e.animations&&(e.animations=[])}))}else switch(s){case ot.Clean:i.animationGroups.slice().forEach((e=>{e.dispose()}));break;case ot.Stop:i.animationGroups.forEach((e=>{e.stop()}));break;case ot.Sync:i.animationGroups.forEach((e=>{e.reset(),e.restart()}));break;case ot.NoSync:break;default:return void p.Y.Error("Unknown animation group loading mode value '"+s+"'")}const c=i.animatables.length;this.LoadAssetContainer(e,t,i,(e=>{e.mergeAnimationsTo(i,i.animatables.slice(c),r),e.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),o&&o(i)}),a,l,h)}static ImportAnimationsAsync(e,t="",i=m.l.LastCreatedScene,n=!0,s=ot.Clean,r=null,o=null,a=null,l=null,h=null){return new Promise(((o,l)=>{ht.ImportAnimations(e,t,i,n,s,r,(e=>{o(e)}),a,((e,t,i)=>{l(i||new Error(t))}),h)}))}}ht.NO_LOGGING=0,ht.MINIMAL_LOGGING=1,ht.SUMMARY_LOGGING=2,ht.DETAILED_LOGGING=3,ht.OnPluginActivatedObservable=new r.y$,ht._RegisteredPlugins={},ht._ShowingLoadingScreen=!1;var ct,dt,ut=i(2067);class pt extends ut.F{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new o.y3,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){super._afterBind(e,t),this.getScene()._cachedEffect=t,t&&(t._forceRebindOnNextCall=!1)}_mustRebind(e,t,i=1){return e.isCachedMaterialInvalid(this,t,i)}dispose(e,t,i){this._activeEffect=void 0,super.dispose(e,t,i)}}!function(e){e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=4]="Vector2",e[e.Vector3=8]="Vector3",e[e.Vector4=16]="Vector4",e[e.Color3=32]="Color3",e[e.Color4=64]="Color4",e[e.Matrix=128]="Matrix",e[e.Object=256]="Object",e[e.AutoDetect=1024]="AutoDetect",e[e.BasedOnInput=2048]="BasedOnInput",e[e.All=4095]="All"}(ct||(ct={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Neutral=4]="Neutral",e[e.VertexAndFragment=3]="VertexAndFragment"}(dt||(dt={}));var ft=i(4442);class _t{constructor(){this.supportUniformBuffers=!1,this.attributes=new Array,this.uniforms=new Array,this.constants=new Array,this.samplers=new Array,this.functions={},this.extensions={},this.counters={},this._attributeDeclaration="",this._uniformDeclaration="",this._constantDeclaration="",this._samplerDeclaration="",this._varyingTransfer="",this._injectAtEnd="",this._repeatableContentAnchorIndex=0,this._builtCompilationString="",this.compilationString=""}finalize(e){const t=e.sharedData.emitComments,i=this.target===dt.Fragment;this.compilationString=`\r\n${t?"//Entry point\r\n":""}void main(void) {\r\n${this.compilationString}`,this._constantDeclaration&&(this.compilationString=`\r\n${t?"//Constants\r\n":""}${this._constantDeclaration}\r\n${this.compilationString}`);let n="";for(const s in this.functions)n+=this.functions[s]+"\r\n";this.compilationString=`\r\n${n}\r\n${this.compilationString}`,!i&&this._varyingTransfer&&(this.compilationString=`${this.compilationString}\r\n${this._varyingTransfer}`),this._injectAtEnd&&(this.compilationString=`${this.compilationString}\r\n${this._injectAtEnd}`),this.compilationString=`${this.compilationString}\r\n}`,this.sharedData.varyingDeclaration&&(this.compilationString=`\r\n${t?"//Varyings\r\n":""}${this.sharedData.varyingDeclaration}\r\n${this.compilationString}`),this._samplerDeclaration&&(this.compilationString=`\r\n${t?"//Samplers\r\n":""}${this._samplerDeclaration}\r\n${this.compilationString}`),this._uniformDeclaration&&(this.compilationString=`\r\n${t?"//Uniforms\r\n":""}${this._uniformDeclaration}\r\n${this.compilationString}`),this._attributeDeclaration&&!i&&(this.compilationString=`\r\n${t?"//Attributes\r\n":""}${this._attributeDeclaration}\r\n${this.compilationString}`),this.compilationString="precision highp float;\r\n"+this.compilationString,this.compilationString="#if defined(WEBGL2) || defines(WEBGPU)\r\nprecision highp sampler2DArray;\r\n#endif\r\n"+this.compilationString;for(const s in this.extensions){const e=this.extensions[s];this.compilationString=`\r\n${e}\r\n${this.compilationString}`}this._builtCompilationString=this.compilationString}get _repeatableContentAnchor(){return`###___ANCHOR${this._repeatableContentAnchorIndex++}___###`}_getFreeVariableName(e){return e=e.replace(/[^a-zA-Z_]+/g,""),void 0===this.sharedData.variableNames[e]?(this.sharedData.variableNames[e]=0,"output"===e||"texture"===e?e+this.sharedData.variableNames[e]:e):(this.sharedData.variableNames[e]++,e+this.sharedData.variableNames[e])}_getFreeDefineName(e){return void 0===this.sharedData.defineNames[e]?this.sharedData.defineNames[e]=0:this.sharedData.defineNames[e]++,e+this.sharedData.defineNames[e]}_excludeVariableName(e){this.sharedData.variableNames[e]=0}_emit2DSampler(e){this.samplers.indexOf(e)<0&&(this._samplerDeclaration+=`uniform sampler2D ${e};\r\n`,this.samplers.push(e))}_emit2DArraySampler(e){this.samplers.indexOf(e)<0&&(this._samplerDeclaration+=`uniform sampler2DArray ${e};\r\n`,this.samplers.push(e))}_getGLType(e){switch(e){case ct.Float:return"float";case ct.Int:return"int";case ct.Vector2:return"vec2";case ct.Color3:case ct.Vector3:return"vec3";case ct.Color4:case ct.Vector4:return"vec4";case ct.Matrix:return"mat4"}return""}_emitExtension(e,t,i=""){this.extensions[e]||(i&&(t=`#if ${i}\r\n${t}\r\n#endif`),this.extensions[e]=t)}_emitFunction(e,t,i){this.functions[e]||(this.sharedData.emitComments&&(t=i+"\r\n"+t),this.functions[e]=t)}_emitCodeFromInclude(e,t,i){if(i&&i.repeatKey)return`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}]\r\n`;let n=ft.Q.IncludesShadersStore[e]+"\r\n";if(this.sharedData.emitComments&&(n=t+"\r\n"+n),!i)return n;if(i.replaceStrings)for(let s=0;s${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}]\r\n`:this.functions[s]=`#include<${e}>${(null==i?void 0:i.substitutionVars)?"("+(null==i?void 0:i.substitutionVars)+")":""}\r\n`,void(this.sharedData.emitComments&&(this.functions[s]=t+"\r\n"+this.functions[s]));if(this.functions[s]=ft.Q.IncludesShadersStore[e],this.sharedData.emitComments&&(this.functions[s]=t+"\r\n"+this.functions[s]),i.removeIfDef&&(this.functions[s]=this.functions[s].replace(/^\s*?#ifdef.+$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#endif.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#else.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[s]=this.functions[s].replace(/^\s*?attribute.+$/gm,"")),i.removeUniforms&&(this.functions[s]=this.functions[s].replace(/^\s*?uniform.+$/gm,"")),i.removeVaryings&&(this.functions[s]=this.functions[s].replace(/^\s*?varying.+$/gm,"")),i.replaceStrings)for(let e=0;ee.ownerBlock))}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get isDirectlyConnectedToVertexOutput(){if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===dt.Vertex)return!0;if((e.ownerBlock.target===dt.Neutral||e.ownerBlock.target===dt.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isDirectlyConnectedToVertexOutput)))return!0}return!1}get isConnectedInVertexShader(){if(this.target===dt.Vertex)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===dt.Vertex)return!0;if(e.target===dt.Vertex)return!0;if((e.ownerBlock.target===dt.Neutral||e.ownerBlock.target===dt.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isConnectedInVertexShader)))return!0}return!1}get isConnectedInFragmentShader(){if(this.target===dt.Fragment)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===dt.Fragment)return!0;if((e.ownerBlock.target===dt.Neutral||e.ownerBlock.target===dt.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isConnectedInFragmentShader)))return!0}return!1}createCustomInputBlock(){return null}constructor(e,t,i){this._connectedPoint=null,this._endpoints=new Array,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this._linkedConnectionSource=null,this._acceptedConnectionPointType=null,this._type=ct.Float,this._enforceAssociatedVariableName=!1,this.needDualDirectionValidation=!1,this.acceptedConnectionPointTypes=new Array,this.excludedConnectionPointTypes=new Array,this.onConnectionObservable=new r.y$,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._prioritizeVertex=!1,this._target=dt.VertexAndFragment,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeMaterialConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===gt.Compatible}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(t.target===dt.Fragment){if(i.target===dt.Vertex)return gt.TargetIncompatible;for(const e of i.outputs)if(e.ownerBlock.target!=dt.Neutral&&e.isConnectedInVertexShader)return gt.TargetIncompatible}if(this.type!==e.type&&e.innerType!==ct.AutoDetect)return St.AreEquivalentTypes(this.type,e.type)||e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)||e._acceptedConnectionPointType&&St.AreEquivalentTypes(e._acceptedConnectionPointType.type,this.type)?gt.Compatible:gt.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return gt.TypeIncompatible;let n=i,s=t;return this.direction===vt.Input&&(n=t,s=i),n.isAnAncestorOf(s)?gt.HierarchyIssue:gt.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this._enforceAssociatedVariableName=!1,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return-1===t||(this._endpoints.splice(t,1),e._connectedPoint=null,this._enforceAssociatedVariableName=!1,e._enforceAssociatedVariableName=!1),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear()}}var Et,xt=i(8501);class bt{get name(){return this._name}set name(e){this.validateBlockName(e)&&(this._name=e)}get isUnique(){return this._isUnique}get isFinalMerger(){return this._isFinalMerger}get isInput(){return this._isInput}get buildId(){return this._buildId}set buildId(e){this._buildId=e}get target(){return this._target}set target(e){0==(this._target&e)&&(this._target=e)}get inputs(){return this._inputs}get outputs(){return this._outputs}getInputByName(e){const t=this._inputs.filter((t=>t.name===e));return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter((t=>t.name===e));return t.length?t[0]:null}constructor(e,t=dt.Vertex,i=!1,n=!1){this._isFinalMerger=!1,this._isInput=!1,this._name="",this._isUnique=!1,this.inputsAreExclusive=!1,this._codeVariableName="",this._inputs=new Array,this._outputs=new Array,this.comments="",this.visibleInInspector=!1,this.visibleOnFrame=!1,this._target=t,this._originalTargetIsNeutral=t===dt.Neutral,this._isFinalMerger=i,this._isInput=n,this._name=e,this.uniqueId=xt.K.UniqueId}_setInitialTarget(e){this._target=e,this._originalTargetIsNeutral=e===dt.Neutral}initialize(e){}bind(e,t,i,n){}_declareOutput(e,t){return`${t._getGLType(e.type)} ${e.associatedVariableName}`}_writeVariable(e){return e.connectedPoint?`${e.associatedVariableName}`:"0."}_writeFloat(e){let t=e.toString();return-1===t.indexOf(".")&&(t+=".0"),`${t}`}getClassName(){return"NodeMaterialBlock"}registerInput(e,t,i=!1,n,s){return(s=null!=s?s:new St(e,this,vt.Input)).type=t,s.isOptional=i,n&&(s.target=n),this._inputs.push(s),this}registerOutput(e,t,i,n){return(n=null!=n?n:new St(e,this,vt.Output)).type=t,i&&(n.target=i),this._outputs.push(n),this}getFirstAvailableInput(e=null){for(const t of this._inputs)if(!(t.connectedPoint||e&&e.type!==t.type&&t.type!==ct.AutoDetect))return t;return null}getFirstAvailableOutput(e=null){for(const t of this._outputs)if(!e||!e.target||e.target===dt.Neutral||0!=(e.target&t.target))return t;return null}getSiblingOutput(e){const t=this._outputs.indexOf(e);return-1===t||t>=this._outputs.length?null:this._outputs[t+1]}isAnAncestorOf(e){for(const t of this._outputs)if(t.hasEndpoints)for(const i of t.endpoints){if(i.ownerBlock===e)return!0;if(i.ownerBlock.isAnAncestorOf(e))return!0}return!1}connectTo(e,t){if(0===this._outputs.length)return;let i=t&&t.output?this.getOutputByName(t.output):this.getFirstAvailableOutput(e),n=!0;for(;n;){const s=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&s&&i.canConnectTo(s))i.connectTo(s),n=!1;else{if(!i)throw"Unable to find a compatible match";i=this.getSiblingOutput(i)}}return this}_buildBlock(e){}updateUniformsAndSamples(e,t,i,n){}provideFallbacks(e,t){}initializeDefines(e,t,i,n=!1){}prepareDefines(e,t,i,n=!1,s){}autoConfigure(e){}replaceRepeatableContent(e,t,i,n){}get willBeGeneratedIntoVertexShaderFromFragmentShader(){return!this.isInput&&!this.isFinalMerger&&(!this._outputs.some((e=>e.isDirectlyConnectedToVertexOutput))&&(this.target!==dt.Vertex&&!(this.target!==dt.VertexAndFragment&&this.target!==dt.Neutral||!this._outputs.some((e=>e.isConnectedInVertexShader)))))}isReady(e,t,i,n=!1){return!0}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}_processBuild(e,t,i,n){e.build(t,n);const s=null!=t._vertexState,r=e._buildTarget===dt.Vertex&&e.target!==dt.VertexAndFragment;if(s&&(0==(e.target&e._buildTarget)||0==(e.target&i.target)||this.target!==dt.VertexAndFragment&&r)&&(!e.isInput&&t.target!==e._buildTarget||e.isInput&&e.isAttribute&&!e._noContextSwitch)){const e=i.connectedPoint;t._vertexState._emitVaryingFromString("v_"+e.associatedVariableName,t._getGLType(e.type))&&(t._vertexState.compilationString+=`${"v_"+e.associatedVariableName} = ${e.associatedVariableName};\r\n`),i.associatedVariableName="v_"+e.associatedVariableName,i._enforceAssociatedVariableName=!0}}validateBlockName(e){const t=["position","normal","tangent","particle_positionw","uv","uv2","uv3","uv4","uv5","uv6","position2d","particle_uv","matricesIndices","matricesWeights","world0","world1","world2","world3","particle_color","particle_texturemask"];for(const i of t)if(e===i)return!1;return!0}build(e,t){if(this._buildId===e.sharedData.buildId)return!0;if(!this.isInput)for(const i of this._outputs)i.associatedVariableName||(i.associatedVariableName=e._getFreeVariableName(i.name));for(const i of this._inputs){if(!i.connectedPoint){i.isOptional||e.sharedData.checks.notConnectedNonOptionalInputs.push(i);continue}if(this.target!==dt.Neutral){if(0==(i.target&this.target))continue;if(0==(i.target&e.target))continue}const n=i.connectedPoint.ownerBlock;n&&n!==this&&this._processBuild(n,e,i,t)}if(this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&console.log(`${e.target===dt.Vertex?"Vertex shader":"Fragment shader"}: Building ${this.name} [${this.getClassName()}]`),this.isFinalMerger)switch(e.target){case dt.Vertex:e.sharedData.checks.emitVertex=!0;break;case dt.Fragment:e.sharedData.checks.emitFragment=!0}!this.isInput&&e.sharedData.emitComments&&(e.compilationString+=`\r\n//${this.name}\r\n`),this._buildBlock(e),this._buildId=e.sharedData.buildId,this._buildTarget=e.target;for(const i of this._outputs)if(0!=(i.target&e.target))for(const n of i.endpoints){const i=n.ownerBlock;i&&0!=(i.target&e.target)&&-1!==t.indexOf(i)&&this._processBuild(i,e,n,t)}return!1}_inputRename(e){return e}_outputRename(e){return e}_dumpPropertiesCode(){const e=this._codeVariableName;return`${e}.visibleInInspector = ${this.visibleInInspector};\r\n${e}.visibleOnFrame = ${this.visibleOnFrame};\r\n${e}.target = ${this.target};\r\n`}_dumpCode(e,t){let i;t.push(this);const n=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=n||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do{t++,this._codeVariableName=n+t}while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName),i=`\r\n// ${this.getClassName()}\r\n`,this.comments&&(i+=`// ${this.comments}\r\n`),i+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}");\r\n`,i+=this._dumpPropertiesCode();for(const s of this.inputs){if(!s.isConnected)continue;const n=s.connectedPoint.ownerBlock;-1===t.indexOf(n)&&(i+=n._dumpCode(e,t))}for(const s of this.outputs)if(s.hasEndpoints)for(const n of s.endpoints){const s=n.ownerBlock;s&&-1===t.indexOf(s)&&(i+=s._dumpCode(e,t))}return i}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const n=i.connectedPoint,s=n.ownerBlock;t+=s._dumpCodeForOutputConnections(e),t+=`${s._codeVariableName}.${s._outputRename(n.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)});\r\n`}return t}clone(e,t=""){const i=this.serialize(),n=(0,l.q)(i.customType);if(n){const s=new n;return s._deserialize(i,e,t),s}return null}serialize(){const e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.comments=this.comments,e.visibleInInspector=this.visibleInInspector,e.visibleOnFrame=this.visibleOnFrame,e.target=this.target,e.inputs=[],e.outputs=[];for(const t of this.inputs)e.inputs.push(t.serialize());for(const t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e,t,i){var n;this.name=e.name,this.comments=e.comments,this.visibleInInspector=!!e.visibleInInspector,this.visibleOnFrame=!!e.visibleOnFrame,this._target=null!==(n=e.target)&&void 0!==n?n:this.target,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach(((e,t)=>{e.displayName&&(this.inputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.inputs[t].isExposedOnFrame=e.isExposedOnFrame,this.inputs[t].exposedPortPosition=e.exposedPortPosition)})),i&&i.forEach(((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)}))}dispose(){for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose()}}class Ct extends bt{constructor(e){super(e,dt.Neutral),this.complementW=1,this.complementZ=0,this.target=dt.Vertex,this.registerInput("vector",ct.AutoDetect),this.registerInput("transform",ct.Matrix),this.registerOutput("output",ct.Vector4),this.registerOutput("xyz",ct.Vector3),this._inputs[0].onConnectionObservable.add((e=>{if(e.ownerBlock.isInput){const t=e.ownerBlock;"normal"!==t.name&&"tangent"!==t.name||(this.complementW=0)}}))}getClassName(){return"TransformBlock"}get vector(){return this._inputs[0]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}get transform(){return this._inputs[1]}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.transform;if(t.connectedPoint){if(0===this.complementW){const n=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",n),e.sharedData.blocksWithDefines.push(this);const s=e._getFreeVariableName(`${i.associatedVariableName}_NUS`);switch(e.compilationString+=`mat3 ${s} = mat3(${i.associatedVariableName});\r\n`,e.compilationString+="#ifdef NONUNIFORMSCALING\r\n",e.compilationString+=`${s} = transposeMat3(inverseMat3(${s}));\r\n`,e.compilationString+="#endif\r\n",t.connectedPoint.type){case ct.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * vec3(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)});\r\n`;break;case ct.Vector3:case ct.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * ${t.associatedVariableName}, ${this._writeFloat(this.complementW)});\r\n`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * ${t.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)});\r\n`}}else{const n=i.associatedVariableName;switch(t.connectedPoint.type){case ct.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = ${n} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)});\r\n`;break;case ct.Vector3:case ct.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = ${n} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementW)});\r\n`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = ${n} * ${t.associatedVariableName};\r\n`}}this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz;\r\n`)}return this}prepareDefines(e,t,i){e.nonUniformScaling&&i.setValue("NONUNIFORMSCALING",!0)}serialize(){const e=super.serialize();return e.complementZ=this.complementZ,e.complementW=this.complementW,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.complementZ=void 0!==e.complementZ?e.complementZ:0,this.complementW=void 0!==e.complementW?e.complementW:1}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.complementZ = ${this.complementZ};\r\n`;return e+=`${this._codeVariableName}.complementW = ${this.complementW};\r\n`,e}}(0,l.H)("BABYLON.TransformBlock",Ct);class yt extends bt{constructor(e){super(e,dt.Vertex,!0),this.registerInput("vector",ct.Vector4)}getClassName(){return"VertexOutputBlock"}get vector(){return this._inputs[0]}_isLogarithmicDepthEnabled(e){for(const t of e)if(t.useLogarithmicDepth)return!0;return!1}_buildBlock(e){super._buildBlock(e);const t=this.vector;return e.compilationString+=`gl_Position = ${t.associatedVariableName};\r\n`,this._isLogarithmicDepthEnabled(e.sharedData.fragmentOutputNodes)&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.compilationString+="vFragmentDepth = 1.0 + gl_Position.w;\r\n",e.compilationString+="gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\r\n"),this}}function At(e,t=Et.Boolean,i="PROPERTIES",n){return(s,r)=>{let o=s._propStore;o||(o=[],s._propStore=o),o.push({propertyName:r,displayName:e,type:t,groupName:i,options:null!=n?n:{}})}}(0,l.H)("BABYLON.VertexOutputBlock",yt),function(e){e[e.Boolean=0]="Boolean",e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=3]="Vector2",e[e.List=4]="List"}(Et||(Et={}));var Rt,Pt,It=i(2108);class Mt extends bt{constructor(e){super(e,dt.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",ct.Color4,!0),this.registerInput("rgb",ct.AutoDetect,!0),this.registerInput("a",ct.Float,!0),this.rgb.addExcludedConnectionPointFromAllowedTypes(ct.Color3|ct.Vector3|ct.Float)}getClassName(){return"FragmentOutputBlock"}initialize(e){e._excludeVariableName("logarithmicDepthConstant"),e._excludeVariableName("vFragmentDepth")}get rgba(){return this._inputs[0]}get rgb(){return this._inputs[1]}get a(){return this._inputs[2]}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToLinearSpace,!0),i.setValue(this._gammaDefineName,this.convertToGammaSpace,!0)}bind(e,t,i){this.useLogarithmicDepth&&i&&It.G.BindLogDepth(void 0,e,i.getScene())}_buildBlock(e){super._buildBlock(e);const t=this.rgba,i=this.rgb,n=this.a;e.sharedData.hints.needAlphaBlending=t.isConnected||n.isConnected,e.sharedData.blocksWithDefines.push(this),this.useLogarithmicDepth&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.sharedData.bindableBlocks.push(this)),this._linearDefineName=e._getFreeDefineName("CONVERTTOLINEAR"),this._gammaDefineName=e._getFreeDefineName("CONVERTTOGAMMA");const s=`//${this.name}`;if(e._emitFunctionFromInclude("helperFunctions",s),t.connectedPoint)n.isConnected?e.compilationString+=`gl_FragColor = vec4(${t.associatedVariableName}.rgb, ${n.associatedVariableName});\r\n`:e.compilationString+=`gl_FragColor = ${t.associatedVariableName};\r\n`;else if(i.connectedPoint){let t="1.0";n.connectedPoint&&(t=n.associatedVariableName),i.connectedPoint.type===ct.Float?e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${i.associatedVariableName}, ${i.associatedVariableName}, ${t});\r\n`:e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${t});\r\n`}else e.sharedData.checks.notConnectedNonOptionalInputs.push(t);return e.compilationString+=`#ifdef ${this._linearDefineName}\r\n`,e.compilationString+="gl_FragColor = toLinearSpace(gl_FragColor);\r\n",e.compilationString+="#endif\r\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\r\n`,e.compilationString+="gl_FragColor = toGammaSpace(gl_FragColor);\r\n",e.compilationString+="#endif\r\n",this.useLogarithmicDepth&&(e.compilationString+="gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\r\n"),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\r\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\r\n`,e+=`${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth};\r\n`,e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.useLogarithmicDepth=this.useLogarithmicDepth,e}_deserialize(e,t,i){var n;super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=e.convertToLinearSpace,this.useLogarithmicDepth=null!==(n=e.useLogarithmicDepth)&&void 0!==n&&n}}(0,oe.gn)([At("Convert to gamma space",Et.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Mt.prototype,"convertToGammaSpace",void 0),(0,oe.gn)([At("Convert to linear space",Et.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Mt.prototype,"convertToLinearSpace",void 0),(0,oe.gn)([At("Use logarithmic depth",Et.Boolean,"PROPERTIES")],Mt.prototype,"useLogarithmicDepth",void 0),(0,l.H)("BABYLON.FragmentOutputBlock",Mt),function(e){e[e.Uniform=0]="Uniform",e[e.Attribute=1]="Attribute",e[e.Varying=2]="Varying",e[e.Undefined=3]="Undefined"}(Rt||(Rt={})),function(e){e[e.World=1]="World",e[e.View=2]="View",e[e.Projection=3]="Projection",e[e.ViewProjection=4]="ViewProjection",e[e.WorldView=5]="WorldView",e[e.WorldViewProjection=6]="WorldViewProjection",e[e.CameraPosition=7]="CameraPosition",e[e.FogColor=8]="FogColor",e[e.DeltaTime=9]="DeltaTime",e[e.CameraParameters=10]="CameraParameters",e[e.MaterialAlpha=11]="MaterialAlpha"}(Pt||(Pt={}));var Ot=i(8952);var Dt,Nt=i(470);!function(e){e[e.None=0]="None",e[e.Time=1]="Time",e[e.RealTime=2]="RealTime"}(Dt||(Dt={}));const Ft={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},wt={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},Lt={particle_texturemask:!0};class Bt extends bt{get type(){if(this._type===ct.AutoDetect){if(this.isUniform&&null!=this.value){if(!isNaN(this.value))return this._type=ct.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=ct.Vector2,this._type;case"Vector3":return this._type=ct.Vector3,this._type;case"Vector4":return this._type=ct.Vector4,this._type;case"Color3":return this._type=ct.Color3,this._type;case"Color4":return this._type=ct.Color4,this._type;case"Matrix":return this._type=ct.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"particle_positionw":return this._type=ct.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=ct.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=ct.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":return this._type=ct.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case Pt.World:case Pt.WorldView:case Pt.WorldViewProjection:case Pt.View:case Pt.ViewProjection:case Pt.Projection:return this._type=ct.Matrix,this._type;case Pt.CameraPosition:return this._type=ct.Vector3,this._type;case Pt.FogColor:return this._type=ct.Color3,this._type;case Pt.DeltaTime:case Pt.MaterialAlpha:return this._type=ct.Float,this._type;case Pt.CameraParameters:return this._type=ct.Vector4,this._type}}return this._type}constructor(e,t=dt.Vertex,i=ct.AutoDetect){super(e,t,!1,!0),this._mode=Rt.Undefined,this._animationType=Dt.None,this.min=0,this.max=0,this.isBoolean=!1,this.matrixMode=0,this._systemValue=null,this.isConstant=!1,this.groupInInspector="",this.onValueChangedObservable=new r.y$,this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._type=i,this.setDefaultValue(),this.registerOutput("output",i)}validateBlockName(e){return!!this.isAttribute||super.validateBlockName(e)}get output(){return this._outputs[0]}setAsAttribute(e){return this._mode=Rt.Attribute,e&&(this.name=e),this}setAsSystemValue(e){return this.systemValue=e,this}get value(){return this._storedValue}set value(e){this.type===ct.Float&&(this.isBoolean?e=e?1:0:this.min!==this.max&&(e=Math.max(this.min,e),e=Math.min(this.max,e))),this._storedValue=e,this._mode=Rt.Uniform,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e,this._mode=Rt.Uniform}get associatedVariableName(){return this._associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get animationType(){return this._animationType}set animationType(e){this._animationType=e}get isUndefined(){return this._mode===Rt.Undefined}get isUniform(){return this._mode===Rt.Uniform}set isUniform(e){this._mode=e?Rt.Uniform:Rt.Undefined,this.associatedVariableName=""}get isAttribute(){return this._mode===Rt.Attribute}set isAttribute(e){this._mode=e?Rt.Attribute:Rt.Undefined,this.associatedVariableName=""}get isVarying(){return this._mode===Rt.Varying}set isVarying(e){this._mode=e?Rt.Varying:Rt.Undefined,this.associatedVariableName=""}get isSystemValue(){return null!=this._systemValue}get systemValue(){return this._systemValue}set systemValue(e){this._mode=Rt.Uniform,this.associatedVariableName="",this._systemValue=e}getClassName(){return"InputBlock"}animate(e){switch(this._animationType){case Dt.Time:this.type===ct.Float&&(this.value+=.01*e.getAnimationRatio());break;case Dt.RealTime:this.type===ct.Float&&(this.value=(F.F.Now-e.getEngine().startTime)/1e3)}}_emitDefine(e){return"!"===e[0]?`#ifndef ${e.substring(1)}\r\n`:`#ifdef ${e}\r\n`}initialize(){this.associatedVariableName=""}setDefaultValue(){switch(this.type){case ct.Float:this.value=0;break;case ct.Vector2:this.value=o.FM.Zero();break;case ct.Vector3:this.value=o.P.Zero();break;case ct.Vector4:this.value=o.Lt.Zero();break;case ct.Color3:this.value=a.Wo.White();break;case ct.Color4:this.value=new a.HE(1,1,1,1);break;case ct.Matrix:this.value=o.y3.Identity()}}_emitConstant(e){switch(this.type){case ct.Float:return`${e._emitFloat(this.value)}`;case ct.Vector2:return`vec2(${this.value.x}, ${this.value.y})`;case ct.Vector3:return`vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;case ct.Vector4:return`vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;case ct.Color3:return a.zZ.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&a.zZ.Color3[0].toGammaSpaceToRef(a.zZ.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&a.zZ.Color3[0].toLinearSpaceToRef(a.zZ.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec3(${a.zZ.Color3[0].r}, ${a.zZ.Color3[0].g}, ${a.zZ.Color3[0].b})`;case ct.Color4:return a.zZ.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&a.zZ.Color4[0].toGammaSpaceToRef(a.zZ.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&a.zZ.Color4[0].toLinearSpaceToRef(a.zZ.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec4(${a.zZ.Color4[0].r}, ${a.zZ.Color4[0].g}, ${a.zZ.Color4[0].b}, ${a.zZ.Color4[0].a})`}return""}get _noContextSwitch(){return wt[this.name]}_emit(e,t){var i;if(this.isUniform){if(this.associatedVariableName||(this.associatedVariableName=e._getFreeVariableName("u_"+this.name)),this.isConstant){if(-1!==e.constants.indexOf(this.associatedVariableName))return;return e.constants.push(this.associatedVariableName),void(e._constantDeclaration+=this._declareOutput(this.output,e)+` = ${this._emitConstant(e)};\r\n`)}if(-1!==e.uniforms.indexOf(this.associatedVariableName))return;e.uniforms.push(this.associatedVariableName),t&&(e._uniformDeclaration+=this._emitDefine(t)),e._uniformDeclaration+=`uniform ${e._getGLType(this.type)} ${this.associatedVariableName};\r\n`,t&&(e._uniformDeclaration+="#endif\r\n");const i=e.sharedData.hints;if(null!==this._systemValue&&void 0!==this._systemValue)switch(this._systemValue){case Pt.WorldView:i.needWorldViewMatrix=!0;break;case Pt.WorldViewProjection:i.needWorldViewProjectionMatrix=!0}else this._animationType!==Dt.None&&e.sharedData.animatedInputs.push(this)}else if(this.isAttribute){if(this.associatedVariableName=null!==(i=Ft[this.name])&&void 0!==i?i:this.name,this.target===dt.Vertex&&e._vertexState)return void(wt[this.name]?Lt[this.name]?e._emitUniformFromString(this.associatedVariableName,e._getGLType(this.type),t):e._emitVaryingFromString(this.associatedVariableName,e._getGLType(this.type),t):this._emit(e._vertexState,t));if(-1!==e.attributes.indexOf(this.associatedVariableName))return;e.attributes.push(this.associatedVariableName),wt[this.name]?Lt[this.name]?e._emitUniformFromString(this.associatedVariableName,e._getGLType(this.type),t):e._emitVaryingFromString(this.associatedVariableName,e._getGLType(this.type),t):(t&&(e._attributeDeclaration+=this._emitDefine(t)),e._attributeDeclaration+=`attribute ${e._getGLType(this.type)} ${this.associatedVariableName};\r\n`,t&&(e._attributeDeclaration+="#endif\r\n"))}}_transmitWorld(e,t,i,n){if(!this._systemValue)return;const s=this.associatedVariableName;switch(this._systemValue){case Pt.World:e.setMatrix(s,t);break;case Pt.WorldView:e.setMatrix(s,i);break;case Pt.WorldViewProjection:e.setMatrix(s,n)}}_transmit(e,t,i){if(this.isAttribute)return;const n=this.associatedVariableName;if(this._systemValue){switch(this._systemValue){case Pt.World:case Pt.WorldView:case Pt.WorldViewProjection:return;case Pt.View:e.setMatrix(n,t.getViewMatrix());break;case Pt.Projection:e.setMatrix(n,t.getProjectionMatrix());break;case Pt.ViewProjection:e.setMatrix(n,t.getTransformMatrix());break;case Pt.CameraPosition:t.bindEyePosition(e,n,!0);break;case Pt.FogColor:e.setColor3(n,t.fogColor);break;case Pt.DeltaTime:e.setFloat(n,t.deltaTime/1e3);break;case Pt.CameraParameters:t.activeCamera&&e.setFloat4(n,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case Pt.MaterialAlpha:e.setFloat(n,i.alpha)}return}const s=this._valueCallback?this._valueCallback():this._storedValue;if(null!==s)switch(this.type){case ct.Float:e.setFloat(n,s);break;case ct.Int:e.setInt(n,s);break;case ct.Color3:a.zZ.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&a.zZ.Color3[0].toGammaSpaceToRef(a.zZ.Color3[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&a.zZ.Color3[0].toLinearSpaceToRef(a.zZ.Color3[0],t.getEngine().useExactSrgbConversions),e.setColor3(n,a.zZ.Color3[0]);break;case ct.Color4:a.zZ.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&a.zZ.Color4[0].toGammaSpaceToRef(a.zZ.Color4[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&a.zZ.Color4[0].toLinearSpaceToRef(a.zZ.Color4[0],t.getEngine().useExactSrgbConversions),e.setDirectColor4(n,a.zZ.Color4[0]);break;case ct.Vector2:e.setVector2(n,s);break;case ct.Vector3:e.setVector3(n,s);break;case ct.Vector4:e.setVector4(n,s);break;case ct.Matrix:e.setMatrix(n,s)}}_buildBlock(e){super._buildBlock(e),(this.isUniform||this.isSystemValue)&&e.sharedData.inputBlocks.push(this),this._emit(e)}_dumpPropertiesCode(){const e=this._codeVariableName;if(this.isAttribute)return super._dumpPropertiesCode()+`${e}.setAsAttribute("${this.name}");\r\n`;if(this.isSystemValue)return super._dumpPropertiesCode()+`${e}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${Pt[this._systemValue]});\r\n`;if(this.isUniform){const t=[];let i="";switch(this.type){case ct.Float:i=`${this.value}`;break;case ct.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case ct.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case ct.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break;case ct.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case ct.Color4:i=`new BABYLON.Color4(${this.value.r}, ${this.value.g}, ${this.value.b}, ${this.value.a})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case ct.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`}return t.push(`${e}.value = ${i}`),this.type===ct.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${Dt[this.animationType]}`),t.push(`${e}.isConstant = ${this.isConstant}`),t.push(""),super._dumpPropertiesCode()+t.join(";\r\n")}return super._dumpPropertiesCode()}dispose(){this.onValueChangedObservable.clear(),super.dispose()}serialize(){const e=super.serialize();return e.type=this.type,e.mode=this._mode,e.systemValue=this._systemValue,e.animationType=this._animationType,e.min=this.min,e.max=this.max,e.isBoolean=this.isBoolean,e.matrixMode=this.matrixMode,e.isConstant=this.isConstant,e.groupInInspector=this.groupInInspector,e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,null!=this._storedValue&&this._mode===Rt.Uniform&&(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e,t,i){if(this._mode=e.mode,super._deserialize(e,t,i),this._type=e.type,this._systemValue=e.systemValue||e.wellKnownValue,this._animationType=e.animationType,this.min=e.min||0,this.max=e.max||0,this.isBoolean=!!e.isBoolean,this.matrixMode=e.matrixMode||0,this.isConstant=!!e.isConstant,this.groupInInspector=e.groupInInspector||"",this.convertToGammaSpace=!!e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,"tangent"===e.name&&e.mode===Rt.Attribute&&e.type===ct.Vector3&&(this._type=ct.Vector4),e.valueType)if("number"===e.valueType)this._storedValue=e.value;else{const t=(0,l.q)(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}(0,l.H)("BABYLON.InputBlock",Bt);class Ut extends bt{constructor(e){super(e,dt.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",ct.AutoDetect,!1,dt.VertexAndFragment),this.registerOutput("rgba",ct.Color4,dt.Neutral),this.registerOutput("rgb",ct.Color3,dt.Neutral),this.registerOutput("r",ct.Float,dt.Neutral),this.registerOutput("g",ct.Float,dt.Neutral),this.registerOutput("b",ct.Float,dt.Neutral),this.registerOutput("a",ct.Float,dt.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ct.Vector2|ct.Vector3|ct.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"CurrentScreenBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return this.uv.isConnected?this.uv.sourceBlock.isInput?dt.VertexAndFragment:dt.Fragment:dt.VertexAndFragment}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}_injectVertexCode(e){const t=this.uv;if(t.connectedPoint.ownerBlock.isInput){t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,"vec2")}if(this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\r\n`,this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name,!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===dt.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName});\r\n`}else this.uv.ownerBlock.target!==dt.Fragment?e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\r\n`:e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName});\r\n`}_writeOutput(e,t,i,n=!1){if(n){if(e.target===dt.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`}else this.uv.ownerBlock.target!==dt.Fragment?(e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`,e.compilationString+=`#ifdef ${this._linearDefineName}\r\n`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\r\n`,e.compilationString+="#endif\r\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\r\n`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\r\n`,e.compilationString+="#endif\r\n"):e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`}_buildBlock(e){if(super._buildBlock(e),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e.sharedData.blockingBlocks.indexOf(this)<0&&e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.indexOf(this)<0&&e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.indexOf(this)<0&&e.sharedData.blocksWithDefines.push(this),e.target!==dt.Fragment)return e._emit2DSampler(this._samplerName),void this._injectVertexCode(e);if(!this._outputs.some((e=>e.isConnectedInFragmentShader)))return;e._emit2DSampler(this._samplerName),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),this._writeTextureRead(e);for(const i of this._outputs)i.hasEndpoints&&this._writeOutput(e,i,i.name);return this}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Le.Parse(e.texture,t,i))}}(0,l.H)("BABYLON.CurrentScreenBlock",Ut);class Vt extends bt{constructor(e){super(e,dt.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",ct.AutoDetect,!1,dt.VertexAndFragment),this.registerOutput("rgba",ct.Color4,dt.Neutral),this.registerOutput("rgb",ct.Color3,dt.Neutral),this.registerOutput("r",ct.Float,dt.Neutral),this.registerOutput("g",ct.Float,dt.Neutral),this.registerOutput("b",ct.Float,dt.Neutral),this.registerOutput("a",ct.Float,dt.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ct.Vector2|ct.Vector3|ct.Vector4)}getClassName(){return"ParticleTextureBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("diffuseSampler")}autoConfigure(e){if(!this.uv.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"particle_uv"===e.name));t||(t=new Bt("uv"),t.setAsAttribute("particle_uv")),t.output.connectTo(this.uv)}}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}_writeOutput(e,t,i){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`,e.compilationString+=`#ifdef ${this._linearDefineName}\r\n`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\r\n`,e.compilationString+="#endif\r\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\r\n`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\r\n`,e.compilationString+="#endif\r\n"}_buildBlock(e){if(super._buildBlock(e),e.target===dt.Vertex)return;this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e._emit2DSampler(this._samplerName),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this.uv.associatedVariableName});\r\n`;for(const i of this._outputs)i.hasEndpoints&&this._writeOutput(e,i,i.name);return this}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Le.Parse(e.texture,t,i))}}(0,l.H)("BABYLON.ParticleTextureBlock",Vt);class kt extends bt{constructor(e){super(e,dt.Fragment),this._isUnique=!0,this.registerInput("color",ct.Color4,!1,dt.Fragment),this.registerOutput("rampColor",ct.Color4,dt.Fragment)}getClassName(){return"ParticleRampGradientBlock"}get color(){return this._inputs[0]}get rampColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("remapRanges"),e._excludeVariableName("rampSampler"),e._excludeVariableName("baseColor"),e._excludeVariableName("alpha"),e._excludeVariableName("remappedColorIndex"),e._excludeVariableName("rampColor"),e._excludeVariableName("finalAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==dt.Vertex)return e._emit2DSampler("rampSampler"),e._emitVaryingFromString("remapRanges","vec4","RAMPGRADIENT"),e.compilationString+=`\n #ifdef RAMPGRADIENT\n vec4 baseColor = ${this.color.associatedVariableName};\n float alpha = ${this.color.associatedVariableName}.a;\n\n float remappedColorIndex = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0);\n\n vec4 rampColor = texture2D(rampSampler, vec2(1.0 - remappedColorIndex, 0.));\n baseColor.rgb *= rampColor.rgb;\n\n // Remapped alpha\n float finalAlpha = baseColor.a;\n baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0);\n\n ${this._declareOutput(this.rampColor,e)} = baseColor;\n #else\n ${this._declareOutput(this.rampColor,e)} = ${this.color.associatedVariableName};\n #endif\n `,this}}(0,l.H)("BABYLON.ParticleRampGradientBlock",kt);class Gt extends bt{constructor(e){super(e,dt.Fragment),this._isUnique=!0,this.registerInput("color",ct.Color4,!1,dt.Fragment),this.registerInput("alphaTexture",ct.Float,!1,dt.Fragment),this.registerInput("alphaColor",ct.Float,!1,dt.Fragment),this.registerOutput("blendColor",ct.Color4,dt.Fragment)}getClassName(){return"ParticleBlendMultiplyBlock"}get color(){return this._inputs[0]}get alphaTexture(){return this._inputs[1]}get alphaColor(){return this._inputs[2]}get blendColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("sourceAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==dt.Vertex)return e.compilationString+=`\n #ifdef BLENDMULTIPLYMODE\n ${this._declareOutput(this.blendColor,e)};\n float sourceAlpha = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName};\n ${this.blendColor.associatedVariableName}.rgb = ${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha);\n ${this.blendColor.associatedVariableName}.a = ${this.color.associatedVariableName}.a;\n #else\n ${this._declareOutput(this.blendColor,e)} = ${this.color.associatedVariableName};\n #endif\n `,this}}(0,l.H)("BABYLON.ParticleBlendMultiplyBlock",Gt);class zt{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(ethis._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,ethis._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;const i=this._mesh.getScene();for(let e=0;e0&&(n.computeBonesUsingShaders=!1)}}else{const t=this._defines[this._currentRank];if(t)for(let i=0;i0}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 texture(){var e,t;return null!==(t=null===(e=this._textures)||void 0===e?void 0:e[0])&&void 0!==t?t: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){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}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]&&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,s=14,r){var o;return null===(o=this._depthStencilTexture)||void 0===o||o.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:n,depthTextureFormat:s,label:r},this),this._depthStencilTexture}_shareDepth(e){this._depthStencilTexture&&(e._depthStencilTexture&&e._depthStencilTexture.dispose(),e._depthStencilTexture=this._depthStencilTexture,this._depthStencilTexture.incrementReferences())}_swapAndDie(e){this.texture&&this.texture._swapAndDie(e),this._textures=null,this.dispose(!0)}_cloneRenderTargetWrapper(){var e,t,i,n,s,r,o,a;let l=null;if(this._isMulti){const i=this.textures;if(i&&i.length>0){let n=!1,s=i.length;const r=i[i.length-1]._source;r!==Be.S.Depth&&r!==Be.S.DepthStencil||(n=!0,s--);const o=[],a=[],h=[],c=[],d=[],u=[],p=[],f={};for(let l=0;l1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){var e,t;if(this._textures)for(let i=0;null!==(t=i<(null===(e=this._textures)||void 0===e?void 0:e.length))&&void 0!==t&&t;++i)this._textures[i].dispose();this._textures=null}dispose(e=!1){var t;e||(null===(t=this._depthStencilTexture)||void 0===t||t.dispose(),this._depthStencilTexture=null,this.releaseTextures()),this._engine._releaseRenderTargetWrapper(this)}}class Kt extends jt{constructor(e,t,i,n,s){super(e,t,i,n),this._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._disposeOnlyFramebuffers=!1,this._context=s}_cloneRenderTargetWrapper(){let e=null;return this._colorTextureArray&&this._depthStencilTextureArray?(e=this._engine.createMultiviewRenderTargetTexture(this.width,this.height),e.texture.isReady=!0):e=super._cloneRenderTargetWrapper(),e}_swapRenderTargetWrapper(e){super._swapRenderTargetWrapper(e),e._framebuffer=this._framebuffer,e._depthStencilBuffer=this._depthStencilBuffer,e._MSAAFramebuffer=this._MSAAFramebuffer,e._colorTextureArray=this._colorTextureArray,e._depthStencilTextureArray=this._depthStencilTextureArray,this._framebuffer=this._depthStencilBuffer=this._MSAAFramebuffer=this._colorTextureArray=this._depthStencilTextureArray=null}_shareDepth(e){super._shareDepth(e);const t=this._context,i=this._depthStencilBuffer,n=e._MSAAFramebuffer||e._framebuffer;e._depthStencilBuffer&&t.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=this._depthStencilBuffer,this._engine._bindUnboundFramebuffer(n),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.RENDERBUFFER,i),this._engine._bindUnboundFramebuffer(null)}_bindTextureRenderTarget(e,t=0,i,n=0){var s,r,o,a;if(!e._hardwareTexture)return;const l=this._framebuffer,h=this._engine._currentFramebuffer;if(this._engine._bindUnboundFramebuffer(l),this._engine.webGLVersion>1){const l=this._context,h=l["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=null!==(r=null!=i?i:null===(s=this.layerIndices)||void 0===s?void 0:s[t])&&void 0!==r?r:0,l.framebufferTextureLayer(l.FRAMEBUFFER,h,e._hardwareTexture.underlyingResource,n,i)):e.isCube?(i=null!==(a=null!=i?i:null===(o=this.faceIndices)||void 0===o?void 0:o[t])&&void 0!==a?a:0,l.framebufferTexture2D(l.FRAMEBUFFER,h,l.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,n)):l.framebufferTexture2D(l.FRAMEBUFFER,h,l.TEXTURE_2D,e._hardwareTexture.underlyingResource,n)}else{const s=this._context,r=s["COLOR_ATTACHMENT"+t+"_WEBGL"],o=void 0!==i?s.TEXTURE_CUBE_MAP_POSITIVE_X+i:s.TEXTURE_2D;s.framebufferTexture2D(s.FRAMEBUFFER,r,o,e._hardwareTexture.underlyingResource,n)}this._engine._bindUnboundFramebuffer(h)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){var i,n;if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;const s=null!==(n=null===(i=this._attachments)||void 0===i?void 0:i.length)&&void 0!==n?n:this.textures.length;for(let r=0;r1&&(15===o.format?d=n.DEPTH_COMPONENT16:16===o.format?d=n.DEPTH_COMPONENT24:17===o.format||13===o.format?d=n.DEPTH24_STENCIL8:14===o.format?d=n.DEPTH_COMPONENT32F:18===o.format&&(d=n.DEPTH32F_STENCIL8)),o.is2DArray?n.texImage3D(r,0,d,o.width,o.height,s,0,c,h,null):n.texImage2D(r,0,d,o.width,o.height,0,c,h,null),this._bindTextureDirectly(r,null),this._internalTexturesCache.push(o);const u=i;if(u._depthStencilBuffer){const e=this._currentFramebuffer;this._bindUnboundFramebuffer(u._framebuffer),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_STENCIL_ATTACHMENT,n.RENDERBUFFER,null),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_ATTACHMENT,n.RENDERBUFFER,null),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.STENCIL_ATTACHMENT,n.RENDERBUFFER,null),this._bindUnboundFramebuffer(e),n.deleteRenderbuffer(u._depthStencilBuffer),u._depthStencilBuffer=null}return o},Ue.B.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 s=i.createFramebuffer();if(!s)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=s,this._bindUnboundFramebuffer(e._MSAAFramebuffer);const r=this._createRenderBuffer(e.texture.width,e.texture.height,t,-1,this._getRGBAMultiSampleBufferFormat(e.texture.type),i.COLOR_ATTACHMENT0,!1);if(!r)throw new Error("Unable to create multi sampled framebuffer");n.addMSAARenderBuffer(r)}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};var qt,$t=i(7050),Qt=i(475);class Zt{static RegisterShaderCodeProcessing(e,t){t?Zt._CustomShaderCodeProcessing[null!=e?e:""]=t:delete Zt._CustomShaderCodeProcessing[null!=e?e:""]}static _GetShaderCodeProcessing(e){var t;return null!==(t=Zt._CustomShaderCodeProcessing[e])&&void 0!==t?t:Zt._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)}))}getEffectName(){return this._fragmentUrl}set onActivate(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),e&&(this._onActivateObserver=this.onActivateObservable.add(e))}set onSizeChanged(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)}set onApply(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}get inputTexture(){return this._textures.data[this._currentRenderTextureInd]}set inputTexture(e){this._forcedOutputTexture=e}restoreDefaultInputTexture(){this._forcedOutputTexture&&(this._forcedOutputTexture=null,this.markTextureDirty())}getCamera(){return this._camera}get texelSize(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)}constructor(e,t,i,n,s,a,l=1,h,c,d=null,u=0,p="postprocess",f,_=!1,m=5,g=Qt.x.GLSL){this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.alphaMode=0,this.animations=new Array,this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new Wt.t(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new o.FM(1,1),this._texelSize=o.FM.Zero(),this.onActivateObservable=new r.y$,this.onSizeChangedObservable=new r.y$,this.onApplyObservable=new r.y$,this.onBeforeRenderObservable=new r.y$,this.onAfterRenderObservable=new r.y$,this.name=e,null!=a?(this._camera=a,this._scene=a.getScene(),a.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):h&&(this._engine=h,this._engine.postProcesses.push(this)),this._options=s,this.renderTargetSamplingMode=l||1,this._reusable=c||!1,this._textureType=u,this._textureFormat=m,this._shaderLanguage=g,this._samplers=n||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=p,this._parameters=i||[],this._parameters.push("scale"),this._indexParameters=f,this._drawWrapper=new $t.q(this._engine),_||this.updateEffect(d)}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 Wt.t(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,n,s,r,o,a){var l,h;const c=Zt._GetShaderCodeProcessing(this.name);if(null==c?void 0:c.defineCustomBindings){const n=null!==(l=null==t?void 0:t.slice())&&void 0!==l?l:[];n.push(...this._parameters);const s=null!==(h=null==i?void 0:i.slice())&&void 0!==h?h:[];s.push(...this._samplers),e=c.defineCustomBindings(this.name,e,n,s),t=n,i=s}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:null!=o?o:this._vertexUrl,fragment:null!=a?a:this._fragmentUrl},{attributes:["position"],uniformsNames:t||this._parameters,uniformBuffersNames:[],samplers:i||this._samplers,defines:null!==e?e:"",fallbacks:null,onCompiled:null!=s?s:null,onError:null!=r?r:null,indexParameters:n||this._indexParameters,processCodeAfterIncludes:(null==c?void 0:c.processCodeAfterIncludes)?(e,t)=>c.processCodeAfterIncludes(this.name,e,t):null,processFinalCode:(null==c?void 0:c.processFinalCode)?(e,t)=>c.processFinalCode(this.name,e,t):null,shaderLanguage:this._shaderLanguage},this._engine)}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let s=0;s=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let e=!1;for(let i=0;i0&&this._textures.reset(),this.width=e,this.height=t;let r=null;for(let l=0;l{e.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(e,this.samples)})),this._flushTextureCache(),this._renderId++}let f;if(this._shareOutputWithPostProcess)f=this._shareOutputWithPostProcess.inputTexture;else if(this._forcedOutputTexture)f=this._forcedOutputTexture,this.width=this._forcedOutputTexture.width,this.height=this._forcedOutputTexture.height;else{let e;f=this.inputTexture;for(let t=0;t=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()}}serialize(){const e=E.p4.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=Zt.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=(0,l.q)(e.customType);if(!n||!n._Parse)return null;const s=t?t.getCameraById(e.cameraId):null;return n._Parse(e,s,t,i)}static _Parse(e,t,i,n){return E.p4.Parse((()=>new Zt(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)}}Zt._CustomShaderCodeProcessing={},(0,oe.gn)([(0,E.qC)()],Zt.prototype,"uniqueId",void 0),(0,oe.gn)([(0,E.qC)()],Zt.prototype,"name",void 0),(0,oe.gn)([(0,E.qC)()],Zt.prototype,"width",void 0),(0,oe.gn)([(0,E.qC)()],Zt.prototype,"height",void 0),(0,oe.gn)([(0,E.qC)()],Zt.prototype,"renderTargetSamplingMode",void 0),(0,oe.gn)([(0,E.XX)()],Zt.prototype,"clearColor",void 0),(0,oe.gn)([(0,E.qC)()],Zt.prototype,"autoClear",void 0),(0,oe.gn)([(0,E.qC)()],Zt.prototype,"forceAutoClearInAlphaMode",void 0),(0,oe.gn)([(0,E.qC)()],Zt.prototype,"alphaMode",void 0),(0,oe.gn)([(0,E.qC)()],Zt.prototype,"alphaConstants",void 0),(0,oe.gn)([(0,E.qC)()],Zt.prototype,"enablePixelPerfectMode",void 0),(0,oe.gn)([(0,E.qC)()],Zt.prototype,"forceFullscreenViewport",void 0),(0,oe.gn)([(0,E.qC)()],Zt.prototype,"scaleMode",void 0),(0,oe.gn)([(0,E.qC)()],Zt.prototype,"alwaysForcePOT",void 0),(0,oe.gn)([(0,E.qC)("samples")],Zt.prototype,"_samples",void 0),(0,oe.gn)([(0,E.qC)()],Zt.prototype,"adaptScaleToCurrentViewport",void 0),(0,l.H)("BABYLON.PostProcess",Zt);class Jt extends bt{constructor(e){super(e,dt.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",this.registerInput("xyzw ",ct.Vector4,!0),this.registerInput("xyz ",ct.Vector3,!0),this.registerInput("xy ",ct.Vector2,!0),this.registerInput("zw ",ct.Vector2,!0),this.registerInput("x",ct.Float,!0),this.registerInput("y",ct.Float,!0),this.registerInput("z",ct.Float,!0),this.registerInput("w",ct.Float,!0),this.registerOutput("xyzw",ct.Vector4),this.registerOutput("xyz",ct.Vector3),this.registerOutput("xy",ct.Vector2),this.registerOutput("zw",ct.Vector2)}getClassName(){return"VectorMergerBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get x(){return this._inputs[4]}get y(){return this._inputs[5]}get z(){return this._inputs[6]}get w(){return this._inputs[7]}get xyzw(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xy(){return this.xyOut}get xyz(){return this.xyzOut}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":e}_buildSwizzle(e){return"."+(this.xSwizzle+this.ySwizzle+this.zSwizzle+this.wSwizzle).substr(0,e)}_buildBlock(e){super._buildBlock(e);const t=this.x,i=this.y,n=this.z,s=this.w,r=this.xyIn,o=this.zwIn,a=this.xyzIn,l=this.xyzwIn,h=this._outputs[0],c=this._outputs[1],d=this._outputs[2],u=this._outputs[3];return l.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = ${l.associatedVariableName}${this._buildSwizzle(4)};\r\n`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${l.associatedVariableName}${this._buildSwizzle(3)};\r\n`),d.hasEndpoints&&(e.compilationString+=this._declareOutput(d,e)+` = ${l.associatedVariableName}${this._buildSwizzle(2)};\r\n`)):a.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = vec4(${a.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)};\r\n`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${a.associatedVariableName}${this._buildSwizzle(3)};\r\n`),d.hasEndpoints&&(e.compilationString+=this._declareOutput(d,e)+` = ${a.associatedVariableName}${this._buildSwizzle(2)};\r\n`)):r.isConnected?(h.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${r.associatedVariableName}, ${o.associatedVariableName})${this._buildSwizzle(4)};\r\n`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${r.associatedVariableName}, ${n.isConnected?this._writeVariable(n):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)};\r\n`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = vec3(${r.associatedVariableName}, ${n.isConnected?this._writeVariable(n):"0.0"})${this._buildSwizzle(3)};\r\n`),d.hasEndpoints&&(e.compilationString+=this._declareOutput(d,e)+` = ${r.associatedVariableName}${this._buildSwizzle(2)};\r\n`),u.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(u,e)+` = ${o.associatedVariableName}${this._buildSwizzle(2)};\r\n`:e.compilationString+=this._declareOutput(u,e)+` = vec2(${n.isConnected?this._writeVariable(n):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(2)};\r\n`)):(h.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${o.associatedVariableName})${this._buildSwizzle(4)};\r\n`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${n.isConnected?this._writeVariable(n):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)};\r\n`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = vec3(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${n.isConnected?this._writeVariable(n):"0.0"})${this._buildSwizzle(3)};\r\n`),d.hasEndpoints&&(e.compilationString+=this._declareOutput(d,e)+` = vec2(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"})${this._buildSwizzle(2)};\r\n`),u.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(u,e)+` = ${o.associatedVariableName}${this._buildSwizzle(2)};\r\n`:e.compilationString+=this._declareOutput(u,e)+` = vec2(${n.isConnected?this._writeVariable(n):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(2)};\r\n`)),this}serialize(){const e=super.serialize();return e.xSwizzle=this.xSwizzle,e.ySwizzle=this.ySwizzle,e.zSwizzle=this.zSwizzle,e.wSwizzle=this.wSwizzle,e}_deserialize(e,t,i){var n,s,r,o;super._deserialize(e,t,i),this.xSwizzle=null!==(n=e.xSwizzle)&&void 0!==n?n:"x",this.ySwizzle=null!==(s=e.ySwizzle)&&void 0!==s?s:"y",this.zSwizzle=null!==(r=e.zSwizzle)&&void 0!==r?r:"z",this.wSwizzle=null!==(o=e.wSwizzle)&&void 0!==o?o:"w"}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.xSwizzle = "${this.xSwizzle}";\r\n`,e+=`${this._codeVariableName}.ySwizzle = "${this.ySwizzle}";\r\n`,e+=`${this._codeVariableName}.zSwizzle = "${this.zSwizzle}";\r\n`,e+=`${this._codeVariableName}.wSwizzle = "${this.wSwizzle}";\r\n`,e}}(0,l.H)("BABYLON.VectorMergerBlock",Jt);class ei extends bt{constructor(e){super(e,dt.Neutral),this.sourceRange=new o.FM(-1,1),this.targetRange=new o.FM(0,1),this.registerInput("input",ct.AutoDetect),this.registerInput("sourceMin",ct.Float,!0),this.registerInput("sourceMax",ct.Float,!0),this.registerInput("targetMin",ct.Float,!0),this.registerInput("targetMax",ct.Float,!0),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"RemapBlock"}get input(){return this._inputs[0]}get sourceMin(){return this._inputs[1]}get sourceMax(){return this._inputs[2]}get targetMin(){return this._inputs[3]}get targetMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.sourceMin.isConnected?this.sourceMin.associatedVariableName:this._writeFloat(this.sourceRange.x),n=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),s=this.targetMin.isConnected?this.targetMin.associatedVariableName:this._writeFloat(this.targetRange.x),r=this.targetMax.isConnected?this.targetMax.associatedVariableName:this._writeFloat(this.targetRange.y);return e.compilationString+=this._declareOutput(t,e)+` = ${s} + (${this._inputs[0].associatedVariableName} - ${i}) * (${r} - ${s}) / (${n} - ${i});\r\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y});\r\n`;return e+=`${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y});\r\n`,e}serialize(){const e=super.serialize();return e.sourceRange=this.sourceRange.asArray(),e.targetRange=this.targetRange.asArray(),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.sourceRange=o.FM.FromArray(e.sourceRange),this.targetRange=o.FM.FromArray(e.targetRange)}}(0,oe.gn)([At("From",Et.Vector2)],ei.prototype,"sourceRange",void 0),(0,oe.gn)([At("To",Et.Vector2)],ei.prototype,"targetRange",void 0),(0,l.H)("BABYLON.RemapBlock",ei);class ti extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("left",ct.AutoDetect),this.registerInput("right",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].acceptedConnectionPointTypes.push(ct.Float),this._inputs[1].acceptedConnectionPointTypes.push(ct.Float)}getClassName(){return"MultiplyBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} * ${this.right.associatedVariableName};\r\n`,this}}(0,l.H)("BABYLON.MultiplyBlock",ti),function(e){e[e.Material=0]="Material",e[e.PostProcess=1]="PostProcess",e[e.Particle=2]="Particle",e[e.ProceduralTexture=3]="ProceduralTexture"}(qt||(qt={}));var ii=i(9096);class ni{constructor(){this.direction1=new o.P(0,1,0),this.direction2=new o.P(0,1,0),this.minEmitBox=new o.P(-.5,-.5,-.5),this.maxEmitBox=new o.P(.5,.5,.5)}startDirectionFunction(e,t,i,n){const s=S.R.RandomRange(this.direction1.x,this.direction2.x),r=S.R.RandomRange(this.direction1.y,this.direction2.y),a=S.R.RandomRange(this.direction1.z,this.direction2.z);if(n)return t.x=s,t.y=r,void(t.z=a);o.P.TransformNormalFromFloatsToRef(s,r,a,e,t)}startPositionFunction(e,t,i,n){const s=S.R.RandomRange(this.minEmitBox.x,this.maxEmitBox.x),r=S.R.RandomRange(this.minEmitBox.y,this.maxEmitBox.y),a=S.R.RandomRange(this.minEmitBox.z,this.maxEmitBox.z);if(n)return t.x=s,t.y=r,void(t.z=a);o.P.TransformCoordinatesFromFloatsToRef(s,r,a,e,t)}clone(){const e=new ni;return g.j.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2),e.setVector3("minEmitBox",this.minEmitBox),e.setVector3("maxEmitBox",this.maxEmitBox)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3),e.addUniform("minEmitBox",3),e.addUniform("maxEmitBox",3)}getEffectDefines(){return"#define BOXEMITTER"}getClassName(){return"BoxParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.minEmitBox=this.minEmitBox.asArray(),e.maxEmitBox=this.maxEmitBox.asArray(),e}parse(e){o.P.FromArrayToRef(e.direction1,0,this.direction1),o.P.FromArrayToRef(e.direction2,0,this.direction2),o.P.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),o.P.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}}class si{get radius(){return this._radius}set radius(e){this._radius=e,this._buildHeight()}get angle(){return this._angle}set angle(e){this._angle=e,this._buildHeight()}_buildHeight(){0!==this._angle?this._height=this._radius/Math.tan(this._angle/2):this._height=1}constructor(e=1,t=Math.PI,i=0){this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}startDirectionFunction(e,t,i,n){n?o.jp.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),o.jp.Vector3[0]).normalize();const s=S.R.RandomRange(0,this.directionRandomizer),r=S.R.RandomRange(0,this.directionRandomizer),a=S.R.RandomRange(0,this.directionRandomizer);t.x=o.jp.Vector3[0].x+s,t.y=o.jp.Vector3[0].y+r,t.z=o.jp.Vector3[0].z+a,t.normalize()}startPositionFunction(e,t,i,n){const s=S.R.RandomRange(0,2*Math.PI);let r;this.emitFromSpawnPointOnly?r=1e-4:(r=S.R.RandomRange(0,this.heightRange),r=1-r*r);let a=this._radius-S.R.RandomRange(0,this._radius*this.radiusRange);a*=r;const l=a*Math.sin(s),h=a*Math.cos(s),c=r*this._height;if(n)return t.x=l,t.y=c,void(t.z=h);o.P.TransformCoordinatesFromFloatsToRef(l,c,h,e,t)}clone(){const e=new si(this._radius,this._angle,this.directionRandomizer);return g.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat2("radius",this._radius,this.radiusRange),e.setFloat("coneAngle",this._angle),e.setFloat2("height",this._height,this.heightRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",2),e.addUniform("coneAngle",1),e.addUniform("height",2),e.addUniform("directionRandomizer",1)}getEffectDefines(){let e="#define CONEEMITTER";return this.emitFromSpawnPointOnly&&(e+="\n#define CONEEMITTERSPAWNPOINT"),e}getClassName(){return"ConeParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this._radius,e.angle=this._angle,e.directionRandomizer=this.directionRandomizer,e.radiusRange=this.radiusRange,e.heightRange=this.heightRange,e.emitFromSpawnPointOnly=this.emitFromSpawnPointOnly,e}parse(e){this.radius=e.radius,this.angle=e.angle,this.directionRandomizer=e.directionRandomizer,this.radiusRange=void 0!==e.radiusRange?e.radiusRange:1,this.heightRange=void 0!==e.radiusRange?e.heightRange:1,this.emitFromSpawnPointOnly=void 0!==e.emitFromSpawnPointOnly&&e.emitFromSpawnPointOnly}}class ri{constructor(e=1,t=1,i=1,n=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=n,this._tempVector=o.P.Zero()}startDirectionFunction(e,t,i,n,s){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),o.P.TransformNormalToRef(this._tempVector,s,this._tempVector);const r=S.R.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2);let a=Math.atan2(this._tempVector.x,this._tempVector.z);a+=S.R.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,this._tempVector.y=r,this._tempVector.x=Math.sin(a),this._tempVector.z=Math.cos(a),this._tempVector.normalize(),n?t.copyFrom(this._tempVector):o.P.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,n){const s=S.R.RandomRange(-this.height/2,this.height/2),r=S.R.RandomRange(0,2*Math.PI),a=S.R.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1),l=Math.sqrt(a)*this.radius,h=l*Math.cos(r),c=l*Math.sin(r);n?t.copyFromFloats(h,s,c):o.P.TransformCoordinatesFromFloatsToRef(h,s,c,e,t)}clone(){const e=new ri(this.radius,this.directionRandomizer);return g.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define CYLINDEREMITTER"}getClassName(){return"CylinderParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.height=this.height,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.height=e.height,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class oi extends ri{constructor(e=1,t=1,i=1,n=new o.P(0,1,0),s=new o.P(0,1,0)){super(e,t,i),this.direction1=n,this.direction2=s}startDirectionFunction(e,t){const i=S.R.RandomRange(this.direction1.x,this.direction2.x),n=S.R.RandomRange(this.direction1.y,this.direction2.y),s=S.R.RandomRange(this.direction1.z,this.direction2.z);o.P.TransformNormalFromFloatsToRef(i,n,s,e,t)}clone(){const e=new oi(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return g.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER"}getClassName(){return"CylinderDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}class ai{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,n){const s=i.position.subtract(e.getTranslation()).normalize(),r=S.R.RandomRange(0,this.directionRandomizer),a=S.R.RandomRange(0,this.directionRandomizer),l=S.R.RandomRange(0,this.directionRandomizer);s.x+=r,s.y+=a,s.z+=l,s.normalize(),n?t.copyFrom(s):o.P.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,n){const s=this.radius-S.R.RandomRange(0,this.radius*this.radiusRange),r=S.R.RandomRange(0,1),a=S.R.RandomRange(0,2*Math.PI),l=Math.acos(2*r-1),h=s*Math.cos(a)*Math.sin(l),c=s*Math.cos(l),d=s*Math.sin(a)*Math.sin(l);n?t.copyFromFloats(h,Math.abs(c),d):o.P.TransformCoordinatesFromFloatsToRef(h,Math.abs(c),d,e,t)}clone(){const e=new ai(this.radius,this.directionRandomizer);return g.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define HEMISPHERICEMITTER"}getClassName(){return"HemisphericParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class li{constructor(){this.direction1=new o.P(0,1,0),this.direction2=new o.P(0,1,0)}startDirectionFunction(e,t,i,n){const s=S.R.RandomRange(this.direction1.x,this.direction2.x),r=S.R.RandomRange(this.direction1.y,this.direction2.y),a=S.R.RandomRange(this.direction1.z,this.direction2.z);n?t.copyFromFloats(s,r,a):o.P.TransformNormalFromFloatsToRef(s,r,a,e,t)}startPositionFunction(e,t,i,n){n?t.copyFromFloats(0,0,0):o.P.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){const e=new li;return g.j.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define POINTEMITTER"}getClassName(){return"PointParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){o.P.FromArrayToRef(e.direction1,0,this.direction1),o.P.FromArrayToRef(e.direction2,0,this.direction2)}}class hi{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,n){const s=i.position.subtract(e.getTranslation()).normalize(),r=S.R.RandomRange(0,this.directionRandomizer),a=S.R.RandomRange(0,this.directionRandomizer),l=S.R.RandomRange(0,this.directionRandomizer);s.x+=r,s.y+=a,s.z+=l,s.normalize(),n?t.copyFrom(s):o.P.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,n){const s=this.radius-S.R.RandomRange(0,this.radius*this.radiusRange),r=S.R.RandomRange(0,1),a=S.R.RandomRange(0,2*Math.PI),l=Math.acos(2*r-1),h=s*Math.cos(a)*Math.sin(l),c=s*Math.cos(l),d=s*Math.sin(a)*Math.sin(l);n?t.copyFromFloats(h,c,d):o.P.TransformCoordinatesFromFloatsToRef(h,c,d,e,t)}clone(){const e=new hi(this.radius,this.directionRandomizer);return g.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define SPHEREEMITTER"}getClassName(){return"SphereParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class ci extends hi{constructor(e=1,t=new o.P(0,1,0),i=new o.P(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){const i=S.R.RandomRange(this.direction1.x,this.direction2.x),n=S.R.RandomRange(this.direction1.y,this.direction2.y),s=S.R.RandomRange(this.direction1.z,this.direction2.z);o.P.TransformNormalFromFloatsToRef(i,n,s,e,t)}clone(){const e=new ci(this.radius,this.direction1,this.direction2);return g.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER"}getClassName(){return"SphereDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}class di{constructor(){this.particlePositionGenerator=()=>{},this.particleDestinationGenerator=()=>{}}startDirectionFunction(e,t,i,n){const s=o.jp.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,s);const e=o.jp.Vector3[1];s.subtractToRef(i.position,e),e.scaleToRef(1/i.lifeTime,s)}else s.set(0,0,0);n?t.copyFrom(s):o.P.TransformNormalToRef(s,e,t)}startPositionFunction(e,t,i,n){const s=o.jp.Vector3[0];this.particlePositionGenerator?this.particlePositionGenerator(-1,i,s):s.set(0,0,0),n?t.copyFrom(s):o.P.TransformCoordinatesToRef(s,e,t)}clone(){const e=new di;return g.j.DeepCopy(this,e),e}applyToShader(e){}buildUniformLayout(e){}getEffectDefines(){return"#define CUSTOMEMITTER"}getClassName(){return"CustomParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e}parse(e){}}class ui{get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(ne.o.PositionKind),this._normals=e.getVerticesData(ne.o.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))}constructor(e=null){this._indices=null,this._positions=null,this._normals=null,this._storedNormal=o.P.Zero(),this._mesh=null,this.direction1=new o.P(0,1,0),this.direction2=new o.P(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,n){if(this.useMeshNormalsForDirection&&this._normals)return void o.P.TransformNormalToRef(this._storedNormal,e,t);const s=S.R.RandomRange(this.direction1.x,this.direction2.x),r=S.R.RandomRange(this.direction1.y,this.direction2.y),a=S.R.RandomRange(this.direction1.z,this.direction2.z);n?t.copyFromFloats(s,r,a):o.P.TransformNormalFromFloatsToRef(s,r,a,e,t)}startPositionFunction(e,t,i,n){if(!this._indices||!this._positions)return;const s=3*Math.random()*(this._indices.length/3)|0,r=Math.random(),a=Math.random()*(1-r),l=1-r-a,h=this._indices[s],c=this._indices[s+1],d=this._indices[s+2],u=o.jp.Vector3[0],p=o.jp.Vector3[1],f=o.jp.Vector3[2],_=o.jp.Vector3[3];o.P.FromArrayToRef(this._positions,3*h,u),o.P.FromArrayToRef(this._positions,3*c,p),o.P.FromArrayToRef(this._positions,3*d,f),_.x=r*u.x+a*p.x+l*f.x,_.y=r*u.y+a*p.y+l*f.y,_.z=r*u.z+a*p.z+l*f.z,n?t.copyFromFloats(_.x,_.y,_.z):o.P.TransformCoordinatesFromFloatsToRef(_.x,_.y,_.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(o.P.FromArrayToRef(this._normals,3*h,u),o.P.FromArrayToRef(this._normals,3*c,p),o.P.FromArrayToRef(this._normals,3*d,f),this._storedNormal.x=r*u.x+a*p.x+l*f.x,this._storedNormal.y=r*u.y+a*p.y+l*f.y,this._storedNormal.z=r*u.z+a*p.z+l*f.z)}clone(){const e=new ui(this.mesh);return g.j.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return""}getClassName(){return"MeshParticleEmitter"}serialize(){var e;const t={};return t.type=this.getClassName(),t.direction1=this.direction1.asArray(),t.direction2=this.direction2.asArray(),t.meshId=null===(e=this.mesh)||void 0===e?void 0:e.id,t.useMeshNormalsForDirection=this.useMeshNormalsForDirection,t}parse(e,t){o.P.FromArrayToRef(e.direction1,0,this.direction1),o.P.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}}i(6430);class pi{get noiseTexture(){return this._noiseTexture}set noiseTexture(e){this._noiseTexture!==e&&(this._noiseTexture=e,this._reset())}get isAnimationSheetEnabled(){return this._isAnimationSheetEnabled}set isAnimationSheetEnabled(e){this._isAnimationSheetEnabled!=e&&(this._isAnimationSheetEnabled=e,this._reset())}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported}getScene(){return this._scene}_hasTargetStopDurationDependantGradient(){return this._startSizeGradients&&this._startSizeGradients.length>0||this._emitRateGradients&&this._emitRateGradients.length>0||this._lifeTimeGradients&&this._lifeTimeGradients.length>0}getDragGradients(){return this._dragGradients}getLimitVelocityGradients(){return this._limitVelocityGradients}getColorGradients(){return this._colorGradients}getSizeGradients(){return this._sizeGradients}getColorRemapGradients(){return this._colorRemapGradients}getAlphaRemapGradients(){return this._alphaRemapGradients}getLifeTimeGradients(){return this._lifeTimeGradients}getAngularSpeedGradients(){return this._angularSpeedGradients}getVelocityGradients(){return this._velocityGradients}getStartSizeGradients(){return this._startSizeGradients}getEmitRateGradients(){return this._emitRateGradients}get direction1(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:o.P.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:o.P.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:o.P.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:o.P.Zero()}set maxEmitBox(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)}get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._reset())}get isBillboardBased(){return this._isBillboardBased}set isBillboardBased(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._reset())}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(!e&&this._scene?this._imageProcessingConfiguration=this._scene.imageProcessingConfiguration:this._imageProcessingConfiguration=e)}_reset(){}_removeGradientAndTexture(e,t,i){if(!t)return this;let n=0;for(const s of t){if(s.gradient===e){t.splice(n,1);break}n++}return i&&i.dispose(),this}constructor(e){this.animations=[],this.renderingGroupId=0,this.emitter=o.P.Zero(),this.emitRate=10,this.manualEmitCount=-1,this.updateSpeed=.01,this.targetStopDuration=0,this.disposeOnStop=!1,this.minEmitPower=1,this.maxEmitPower=1,this.minLifeTime=1,this.maxLifeTime=1,this.minSize=1,this.maxSize=1,this.minScaleX=1,this.maxScaleX=1,this.minScaleY=1,this.maxScaleY=1,this.minInitialRotation=0,this.maxInitialRotation=0,this.minAngularSpeed=0,this.maxAngularSpeed=0,this.layerMask=268435455,this.customShader=null,this.preventAutoStart=!1,this._wasDispatched=!1,this._rootUrl="",this.noiseStrength=new o.P(10,10,10),this.onAnimationEnd=null,this.blendMode=pi.BLENDMODE_ONEONE,this.forceDepthWrite=!1,this.preWarmCycles=0,this.preWarmStepOffset=1,this.spriteCellChangeSpeed=1,this.startSpriteCellID=0,this.endSpriteCellID=0,this.spriteCellWidth=0,this.spriteCellHeight=0,this.spriteCellLoop=!0,this.spriteRandomStartCell=!1,this.translationPivot=new o.FM(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new o.P(0,0,0),this._useLogarithmicDepth=!1,this.gravity=o.P.Zero(),this._colorGradients=null,this._sizeGradients=null,this._lifeTimeGradients=null,this._angularSpeedGradients=null,this._velocityGradients=null,this._limitVelocityGradients=null,this._dragGradients=null,this._emitRateGradients=null,this._startSizeGradients=null,this._rampGradients=null,this._colorRemapGradients=null,this._alphaRemapGradients=null,this.startDelay=0,this.limitVelocityDamping=.4,this.color1=new a.HE(1,1,1,1),this.color2=new a.HE(1,1,1,1),this.colorDead=new a.HE(0,0,0,1),this.textureMask=new a.HE(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new ii.b,this.id=e,this.name=e}createPointEmitter(e,t){const i=new li;return i.direction1=e,i.direction2=t,this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=new ai(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=new hi(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new o.P(0,1,0),i=new o.P(0,1,0)){const n=new ci(e,t,i);return this.particleEmitterType=n,n}createCylinderEmitter(e=1,t=1,i=1,n=0){const s=new ri(e,t,i,n);return this.particleEmitterType=s,s}createDirectedCylinderEmitter(e=1,t=1,i=1,n=new o.P(0,1,0),s=new o.P(0,1,0)){const r=new oi(e,t,i,n,s);return this.particleEmitterType=r,r}createConeEmitter(e=1,t=Math.PI/4){const i=new si(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,n){const s=new ni;return this.particleEmitterType=s,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=n,s}}pi.BLENDMODE_ONEONE=0,pi.BLENDMODE_STANDARD=1,pi.BLENDMODE_ADD=2,pi.BLENDMODE_MULTIPLY=3,pi.BLENDMODE_MULTIPLYADD=4;class fi extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("rgba",ct.Color4,!0),this.registerInput("rgb ",ct.Color3,!0),this.registerOutput("rgb",ct.Color3),this.registerOutput("r",ct.Float),this.registerOutput("g",ct.Float),this.registerOutput("b",ct.Float),this.registerOutput("a",ct.Float),this.inputsAreExclusive=!0}getClassName(){return"ColorSplitterBlock"}get rgba(){return this._inputs[0]}get rgbIn(){return this._inputs[1]}get rgbOut(){return this._outputs[0]}get r(){return this._outputs[1]}get g(){return this._outputs[2]}get b(){return this._outputs[3]}get a(){return this._outputs[4]}_inputRename(e){return"rgb "===e?"rgbIn":e}_outputRename(e){return"rgb"===e?"rgbOut":e}_buildBlock(e){super._buildBlock(e);const t=this.rgba.isConnected?this.rgba:this.rgbIn;if(!t.isConnected)return;const i=this._outputs[0],n=this._outputs[1],s=this._outputs[2],r=this._outputs[3],o=this._outputs[4];return i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = ${t.associatedVariableName}.rgb;\r\n`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${t.associatedVariableName}.r;\r\n`),s.hasEndpoints&&(e.compilationString+=this._declareOutput(s,e)+` = ${t.associatedVariableName}.g;\r\n`),r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = ${t.associatedVariableName}.b;\r\n`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = ${t.associatedVariableName}.a;\r\n`),this}}(0,l.H)("BABYLON.ColorSplitterBlock",fi);var _i=i(9093),mi=i(5567);Ue.B.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),n=Object.assign({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5},t);n.generateStencilBuffer=n.generateDepthBuffer&&n.generateStencilBuffer,(1!==n.type||this._caps.textureFloatLinearFiltering)&&(2!==n.type||this._caps.textureHalfFloatLinearFiltering)||(n.samplingMode=1);const s=this._gl,r=new Be.l(this,Be.S.RenderTarget);this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,r,!0);const o=this._getSamplingParameters(n.samplingMode,n.generateMipMaps);1!==n.type||this._caps.textureFloat||(n.type=0,p.Y.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAG_FILTER,o.mag),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,o.min),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE);for(let l=0;l<6;l++)s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+l,0,this._getRGBABufferInternalSizedFormat(n.type,n.format),e,e,0,this._getInternalFormat(n.format),this._getWebGLTextureType(n.type),null);const a=s.createFramebuffer();return this._bindUnboundFramebuffer(a),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(n.generateStencilBuffer,n.generateDepthBuffer,e,e),n.generateMipMaps&&s.generateMipmap(s.TEXTURE_CUBE_MAP),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),i._framebuffer=a,i._generateDepthBuffer=n.generateDepthBuffer,i._generateStencilBuffer=n.generateStencilBuffer,r.width=e,r.height=e,r.isReady=!0,r.isCube=!0,r.samples=1,r.generateMipMaps=n.generateMipMaps,r.samplingMode=n.samplingMode,r.type=n.type,r.format=n.format,this._internalTexturesCache.push(r),i.setTextures(r),i};const gi={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class vi{constructor(e,t=gi){var i,n;this._fullscreenViewport=new Nt.l(0,0,1,1);const s=null!==(i=t.positions)&&void 0!==i?i:gi.positions,r=null!==(n=t.indices)&&void 0!==n?n:gi.indices;this.engine=e,this._vertexBuffers={[ne.o.PositionKind]:new ne.o(e,s,ne.o.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(r),this._onContextRestoredObserver=e.onContextRestoredObservable.add((()=>{this._indexBuffer=e.createIndexBuffer(r);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({})}restoreStates(){this.engine.depthCullingState.depthTest=!0,this.engine.stencilState.stencilTest=!0}draw(){this.engine.drawElementsType(0,0,6)}_isRenderTargetTexture(e){return void 0!==e.renderTarget}render(e,t=null){if(!e.effect.isReady())return;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[ne.o.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[ne.o.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class Ti{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){let t;this.onApplyObservable=new r.y$;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 $t.q(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 ft.Q(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._wasPreviouslyReady=!1,this.effect._prepareEffect()})))}dispose(){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()}}const Si="passPixelShader",Ei="varying vec2 vUV;\nuniform sampler2D textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}";Ht.v.ShadersStore[Si]=Ei;const xi={name:Si,shader:Ei};class bi{static _CreateDumpRenderer(){if(!bi._DumpToolsEngine){const e=new OffscreenCanvas(100,100),t=new Ue.B(e,!1,{preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1});t.getCaps().parallelShaderCompile=void 0;const i=new vi(t),n=new Ti({engine:t,name:xi.name,fragmentShader:xi.shader,samplerNames:["textureSampler"]});bi._DumpToolsEngine={canvas:e,engine:t,renderer:i,wrapper:n}}return bi._DumpToolsEngine}static async DumpFramebuffer(e,t,i,n,s="image/png",r,o){const a=await i.readPixels(0,0,e,t),l=new Uint8Array(a.buffer);bi.DumpData(e,t,l,n,s,r,!0,void 0,o)}static DumpDataAsync(e,t,i,n="image/png",s,r=!1,o=!1,a){return new Promise((l=>{bi.DumpData(e,t,i,(e=>l(e)),n,s,r,o,a)}))}static DumpData(e,t,i,n,s="image/png",r,o=!1,a=!1,l){const h=bi._CreateDumpRenderer();if(h.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*S.R.Clamp(n))}i=e}const c=h.engine.createRawTexture(i,e,t,5,!1,!o,1);h.renderer.setViewport(),h.renderer.applyEffectWrapper(h.wrapper),h.wrapper.effect._bindTexture("textureSampler",c),h.renderer.draw(),a?se.w1.ToBlob(h.canvas,(e=>{const t=new FileReader;t.onload=e=>{const t=e.target.result;n&&n(t)},t.readAsArrayBuffer(e)}),s,l):se.w1.EncodeScreenshotCanvasData(h.canvas,n,s,r,l),c.dispose()}static Dispose(){bi._DumpToolsEngine&&(bi._DumpToolsEngine.wrapper.dispose(),bi._DumpToolsEngine.renderer.dispose(),bi._DumpToolsEngine.engine.dispose()),bi._DumpToolsEngine=null}}se.w1.DumpData=bi.DumpData,se.w1.DumpDataAsync=bi.DumpDataAsync,se.w1.DumpFramebuffer=bi.DumpFramebuffer;class Ci extends Le{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=(0,w.M)(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 n=0;n{var i;const n=this._renderList?this._renderList.length:0;(0===t&&n>0||0===n)&&(null===(i=this.getScene())||void 0===i||i.meshes.forEach((e=>{e._markSubMeshesAsLightDirty()})))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new r.y$,this.onAfterUnbindObservable=new r.y$,this.onBeforeRenderObservable=new r.y$,this.onAfterRenderObservable=new r.y$,this.onClearObservable=new r.y$,this.onResizeObservable=new r.y$,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=o.P.Zero(),!(i=this.getScene()))return;const A=this.getScene().getEngine();this._coordinatesMode=Le.PROJECTION_MODE,this.renderList=new Array,this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._renderPassIds=[],this._isCubeData=l,this._processSizeParameter(t),this.renderPassId=this._renderPassIds[0],this._resizeObserver=A.onResizeObservable.add((()=>{})),this._generateMipMaps=!!n,this._doNotChangeAspectRatio=s,this._renderingManager=new mi.$(i),this._renderingManager._useSceneAutoClearSetup=!0,u||(this._renderTargetOptions={generateMipMaps:n,type:a,format:null!==(C=this._format)&&void 0!==C?C:void 0,samplingMode:this.samplingMode,generateDepthBuffer:c,generateStencilBuffer:d,samples:_,creationFlags:m,noColorAttachment:g,useSRGBBuffer:v,colorAttachment:y,label:this.name},this.samplingMode===Le.NEAREST_SAMPLINGMODE&&(this.wrapU=Le.CLAMP_ADDRESSMODE,this.wrapV=Le.CLAMP_ADDRESSMODE),f||(l?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=Le.INVCUBIC_MODE,this._textureMatrix=o.y3.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==_&&(this.samples=_)))}createDepthStencilTexture(e=0,t=!0,i=!1,n=1,s=14){var r;null===(r=this._renderTarget)||void 0===r||r.createDepthStencilTexture(e,t,i,n,s)}_releaseRenderPassId(){if(this._scene){const e=this._scene.getEngine();for(let t=0;t0&&(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;return e||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){const t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){var t;const i=this.isCube;null===(t=this._renderTarget)||void 0===t||t.dispose(),this._renderTarget=null;const n=this.getScene();n&&(this._processSizeParameter(e,!1),this._renderTarget=i?n.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):n.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){var n;const s=this.getScene();if(!s)return i;const r=s.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){this.renderList=[];for(let e=0;e1||this.activeCamera&&this.activeCamera!==s.activeCamera)&&s.setTransformMatrix(s.activeCamera.getViewMatrix(),s.activeCamera.getProjectionMatrix(!0)),r.setViewport(s.activeCamera.viewport)),s.resetCachedMaterial(),h}_bestReflectionRenderTargetDimension(e,t){const i=e*t,n=fe.D.NearestPOT(i+16384/(128+i));return Math.min(fe.D.FloorPOT(e),n)}_prepareRenderingManager(e,t,i,n){const s=this.getScene();if(!s)return;this._renderingManager.reset();const r=s.getRenderId();for(let o=0;o{this.onAfterRenderObservable.notifyObservers(t)}))}_prepareFrame(e,t,i,n){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):n&&e.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,n=0,s=null){var r,o,a,l,h,c;const d=this.getScene();if(!d)return;const u=d.getEngine();null===(r=u._debugPushGroup)||void 0===r||r.call(u,`render to face #${e} layer #${n}`,1),this._prepareFrame(d,e,n,t),this.is2DArray?(u.currentRenderPassId=this._renderPassIds[n],this.onBeforeRenderObservable.notifyObservers(n)):(u.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e));if(u.snapshotRendering&&1===u.snapshotRenderingMode)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(u):this.skipInitialClear||u.clear(this.clearColor||d.clearColor,!0,!0,!0);else{let r=null;const c=this.renderList?this.renderList:d.getActiveMeshes().data,p=this.renderList?this.renderList.length:d.getActiveMeshes().length;this.getCustomRenderList&&(r=this.getCustomRenderList(this.is2DArray?n:e,c,p)),r?this._prepareRenderingManager(r,r.length,s,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(c,p,s,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),r=c);for(const t of d._beforeRenderTargetClearStage)t.action(this,e,n);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(u):this.skipInitialClear||u.clear(this.clearColor||d.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||d.updateTransformMatrix(!0);for(const t of d._beforeRenderTargetDrawStage)t.action(this,e,n);this._renderingManager.render(this.customRenderFunction,r,this.renderParticles,this.renderSprites);for(const t of d._afterRenderTargetDrawStage)t.action(this,e,n);const f=null!==(a=null===(o=this._texture)||void 0===o?void 0:o.generateMipMaps)&&void 0!==a&&a;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,null!==(l=this._renderTarget)&&void 0!==l?l:void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&d.postProcessManager._finalizeFrame(!1,null!==(h=this._renderTarget)&&void 0!==h?h:void 0,e);for(const t of d._afterRenderTargetPostProcessStage)t.action(this,e,n);this._texture&&(this._texture.generateMipMaps=f),this._doNotChangeAspectRatio||d.updateTransformMatrix(!0),i&&bi.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),u)}this._unbindFrameBuffer(u,e),this._texture&&this.isCube&&5===e&&u.generateMipMapsForCubemap(this._texture),null===(c=u._debugPopGroup)||void 0===c||c.call(u,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 Ci(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer,void 0,this._renderTargetOptions.format,void 0,this._renderTargetOptions.samples);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,this.renderList&&(t.renderList=this.renderList.slice(0)),t}serialize(){if(!this.name)return null;const e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t=0&&t.customRenderTargets.splice(i,1);for(const n of t.cameras)i=n.customRenderTargets.indexOf(this),i>=0&&n.customRenderTargets.splice(i,1);null===(e=this._renderTarget)||void 0===e||e.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===Ci.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=Ci.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}Ci.REFRESHRATE_RENDER_ONCE=0,Ci.REFRESHRATE_RENDER_ONEVERYFRAME=1,Ci.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,Le._CreateRenderTargetTexture=(e,t,i,n,s)=>new Ci(e,t,i,n);class yi{constructor(e){this.name=Se.l.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=new Array}register(){this.scene._beforeClearStage.registerStep(Se.l.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){se.w1.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e0)}}}const Ai="proceduralVertexShader",Ri="attribute vec2 position;\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";Ht.v.ShadersStore[Ai]=Ri;class Pi extends Le{constructor(e,t,i,n,s=null,o=!0,a=!1,l=0){super(null,n,!o),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new r.y$,this.onBeforeGenerationObservable=new r.y$,this.nodeMaterialSource=null,this._textures={},this._currentRefreshId=-1,this._frameId=-1,this._refreshRate=1,this._vertexBuffers={},this._uniforms=new Array,this._samplers=new Array,this._floats={},this._ints={},this._floatsArrays={},this._colors3={},this._colors4={},this._vectors2={},this._vectors3={},this._matrices={},this._fallbackTextureUsed=!1,this._cachedDefines=null,this._contentUpdateId=-1,this._rtWrapper=null;let h=(n=this.getScene()||m.l.LastCreatedScene)._getComponent(Se.l.NAME_PROCEDURALTEXTURE);h||(h=new yi(n),n._addComponent(h)),n.proceduralTextures.push(this),this._fullEngine=n.getEngine(),this.name=e,this.isRenderTarget=!0,this._size=t,this._textureType=l,this._generateMipMaps=o,this._drawWrapper=new $t.q(this._fullEngine),this.setFragment(i),this._fallbackTexture=s;const c=this._createRtWrapper(a,t,o,l);this._texture=c.texture;const d=[];d.push(1,1),d.push(-1,1),d.push(-1,-1),d.push(1,-1),this._vertexBuffers[ne.o.PositionKind]=new ne.o(this._fullEngine,d,ne.o.PositionKind,!1,!1,2),this._createIndexBuffer()}_createRtWrapper(e,t,i,n){return e?(this._rtWrapper=this._fullEngine.createRenderTargetCubeTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:n}),this.setFloat("face",0)):this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:n}),this._rtWrapper}getEffect(){return this._drawWrapper.effect}_setEffect(e){this._drawWrapper.effect=e}getContent(){return this._contentData&&this._frameId===this._contentUpdateId||(this._contentData?this._contentData.then((e=>{this._contentData=this.readPixels(0,0,e),this._contentUpdateId=this._frameId})):(this._contentData=this.readPixels(0,0),this._contentUpdateId=this._frameId)),this._contentData}_createIndexBuffer(){const e=this._fullEngine,t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){const e=this._vertexBuffers[ne.o.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===Ci.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=Ci.REFRESHRATE_RENDER_ONCE)}reset(){var e;null===(e=this._drawWrapper.effect)||void 0===e||e.dispose()}_getDefines(){return""}isReady(){const e=this._fullEngine;let t;if(this.nodeMaterialSource)return this._drawWrapper.effect.isReady();if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;if(!this._texture)return!1;const i=this._getDefines();return!(!this._drawWrapper.effect||i!==this._cachedDefines||!this._drawWrapper.effect.isReady())||(t=void 0!==this._fragment.fragmentElement?{vertex:"procedural",fragmentElement:this._fragment.fragmentElement}:{vertex:"procedural",fragment:this._fragment},this._cachedDefines!==i&&(this._cachedDefines=i,this._drawWrapper.effect=e.createEffect(t,[ne.o.PositionKind],this._uniforms,this._samplers,i,void 0,void 0,(()=>{var e;null===(e=this._rtWrapper)||void 0===e||e.dispose(),this._rtWrapper=this._texture=null,this._fallbackTexture&&(this._texture=this._fallbackTexture._texture,this._texture&&this._texture.incrementReferences()),this._fallbackTextureUsed=!0}))),this._drawWrapper.effect.isReady())}resetRefreshCounter(){this._currentRefreshId=-1}setFragment(e){this._fragment=e}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}_shouldRender(){return this.isEnabled&&this.isReady()&&this._texture?!this._fallbackTextureUsed&&(-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,this._frameId++,!0):(this._currentRefreshId++,!1)):(this._texture&&(this._texture.isReady=!1),!1)}getRenderSize(){return this._size}resize(e,t){if(this._fallbackTextureUsed||!this._rtWrapper||!this._texture)return;const i=this._texture.isCube;this._rtWrapper.dispose();const n=this._createRtWrapper(i,e,t,this._textureType);this._texture=n.texture,this._size=e,this._generateMipMaps=t}_checkUniform(e){-1===this._uniforms.indexOf(e)&&this._uniforms.push(e)}setTexture(e,t){return-1===this._samplers.indexOf(e)&&this._samplers.push(e),this._textures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}render(e){var t,i;const n=this.getScene();if(!n)return;const s=this._fullEngine;if(s.enableEffect(this._drawWrapper),this.onBeforeGenerationObservable.notifyObservers(this),s.setState(!1),!this.nodeMaterialSource){for(const e in this._textures)this._drawWrapper.effect.setTexture(e,this._textures[e]);for(const e in this._ints)this._drawWrapper.effect.setInt(e,this._ints[e]);for(const e in this._floats)this._drawWrapper.effect.setFloat(e,this._floats[e]);for(const e in this._floatsArrays)this._drawWrapper.effect.setArray(e,this._floatsArrays[e]);for(const e in this._colors3)this._drawWrapper.effect.setColor3(e,this._colors3[e]);for(const e in this._colors4){const t=this._colors4[e];this._drawWrapper.effect.setFloat4(e,t.r,t.g,t.b,t.a)}for(const e in this._vectors2)this._drawWrapper.effect.setVector2(e,this._vectors2[e]);for(const e in this._vectors3)this._drawWrapper.effect.setVector3(e,this._vectors3[e]);for(const e in this._matrices)this._drawWrapper.effect.setMatrix(e,this._matrices[e])}if(!this._texture||!this._rtWrapper)return;null===(t=s._debugPushGroup)||void 0===t||t.call(s,`procedural texture generation for ${this.name}`,1);const r=s.currentViewport;if(this.isCube)for(let o=0;o<6;o++)s.bindFramebuffer(this._rtWrapper,o,void 0,void 0,!0),s.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",o),this.autoClear&&s.clear(n.clearColor,!0,!1,!1),s.drawElementsType(ut.F.TriangleFillMode,0,6);else s.bindFramebuffer(this._rtWrapper,0,void 0,void 0,!0),s.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this.autoClear&&s.clear(n.clearColor,!0,!1,!1),s.drawElementsType(ut.F.TriangleFillMode,0,6);s.unBindFramebuffer(this._rtWrapper,this.isCube),r&&s.setViewport(r),this.isCube&&s.generateMipMapsForCubemap(this._texture),null===(i=s._debugPopGroup)||void 0===i||i.call(s,1),this.onGenerated&&this.onGenerated(),this.onGeneratedObservable.notifyObservers(this)}clone(){const e=this.getSize(),t=new Pi(this.name,e.width,this._fragment,this.getScene(),this._fallbackTexture,this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,t}dispose(){const e=this.getScene();if(!e)return;const t=e.proceduralTextures.indexOf(this);t>=0&&e.proceduralTextures.splice(t,1);const i=this._vertexBuffers[ne.o.PositionKind];i&&(i.dispose(),this._vertexBuffers[ne.o.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}}var Ii;(0,oe.gn)([(0,E.qC)()],Pi.prototype,"isEnabled",void 0),(0,oe.gn)([(0,E.qC)()],Pi.prototype,"autoClear",void 0),(0,oe.gn)([(0,E.qC)()],Pi.prototype,"_generateMipMaps",void 0),(0,oe.gn)([(0,E.qC)()],Pi.prototype,"_size",void 0),(0,oe.gn)([(0,E.qC)()],Pi.prototype,"refreshRate",null),(0,l.H)("BABYLON.ProceduralTexture",Pi),function(e){e[e.Cos=0]="Cos",e[e.Sin=1]="Sin",e[e.Abs=2]="Abs",e[e.Exp=3]="Exp",e[e.Exp2=4]="Exp2",e[e.Round=5]="Round",e[e.Floor=6]="Floor",e[e.Ceiling=7]="Ceiling",e[e.Sqrt=8]="Sqrt",e[e.Log=9]="Log",e[e.Tan=10]="Tan",e[e.ArcTan=11]="ArcTan",e[e.ArcCos=12]="ArcCos",e[e.ArcSin=13]="ArcSin",e[e.Fract=14]="Fract",e[e.Sign=15]="Sign",e[e.Radians=16]="Radians",e[e.Degrees=17]="Degrees"}(Ii||(Ii={}));class Mi extends bt{constructor(e){super(e,dt.Neutral),this.operation=Ii.Cos,this.registerInput("input",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"TrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="";switch(this.operation){case Ii.Cos:i="cos";break;case Ii.Sin:i="sin";break;case Ii.Abs:i="abs";break;case Ii.Exp:i="exp";break;case Ii.Exp2:i="exp2";break;case Ii.Round:i="round";break;case Ii.Floor:i="floor";break;case Ii.Ceiling:i="ceil";break;case Ii.Sqrt:i="sqrt";break;case Ii.Log:i="log";break;case Ii.Tan:i="tan";break;case Ii.ArcTan:i="atan";break;case Ii.ArcCos:i="acos";break;case Ii.ArcSin:i="asin";break;case Ii.Fract:i="fract";break;case Ii.Sign:i="sign";break;case Ii.Radians:i="radians";break;case Ii.Degrees:i="degrees"}return e.compilationString+=this._declareOutput(t,e)+` = ${i}(${this.input.associatedVariableName});\r\n`,this}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.operation=e.operation}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.TrigonometryBlockOperations.${Ii[this.operation]};\r\n`}}(0,l.H)("BABYLON.TrigonometryBlock",Mi);const Oi={effect:null,subMesh:null};class Di extends Tt.H{constructor(){super(),this.NORMAL=!1,this.TANGENT=!1,this.VERTEXCOLOR_NME=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.EXPOSURE=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.BUMPDIRECTUV=0,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.rebuild()}setValue(e,t,i=!1){void 0===this[e]&&this._keys.push(e),i&&this[e]!==t&&this.markAsUnprocessed(),this[e]=t}}class Ni extends pt{static _BlockIsTextureBlock(e){return"TextureBlock"===e.getClassName()||"ReflectionTextureBaseBlock"===e.getClassName()||"RefractionBlock"===e.getClassName()||"CurrentScreenBlock"===e.getClassName()||"ParticleTextureBlock"===e.getClassName()||"ImageSourceBlock"===e.getClassName()||"TriPlanarBlock"===e.getClassName()||"BiPlanarBlock"===e.getClassName()}_getGlobalNodeMaterialEditor(){return"undefined"!=typeof NODEEDITOR?NODEEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeEditor?BABYLON:void 0}get options(){return this._options}set options(e){this._options=e}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get mode(){return this._mode}set mode(e){this._mode=e}get buildId(){return this._buildId}set buildId(e){this._buildId=e}constructor(e,t,i={}){super(e,t||m.l.LastCreatedScene),this._buildId=Ni._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new o.y3,this._cachedWorldViewProjectionMatrix=new o.y3,this._optimizers=new Array,this._animationFrame=-1,this.BJSNODEMATERIALEDITOR=this._getGlobalNodeMaterialEditor(),this.editorData=null,this.ignoreAlpha=!1,this.maxSimultaneousLights=4,this.onBuildObservable=new r.y$,this._vertexOutputNodes=new Array,this._fragmentOutputNodes=new Array,this.attachedBlocks=new Array,this._mode=qt.Material,this.forceAlphaBlending=!1,this._options=Object.assign({emitComments:!1},i),this._attachImageProcessingConfiguration(null)}getClassName(){return"NodeMaterial"}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e){if(t)return se.w1.Warn("More than one block was found with the name `"+e+"`"),t;t=i}return t}getBlockByPredicate(e){for(const t of this.attachedBlocks)if(e(t))return t;return null}getInputBlockByPredicate(e){for(const t of this.attachedBlocks)if(t.isInput&&e(t))return t;return null}getInputBlocks(){const e=[];for(const t of this.attachedBlocks)t.isInput&&e.push(t);return e}registerOptimizer(e){if(!(this._optimizers.indexOf(e)>-1))return this._optimizers.push(e),this}unregisterOptimizer(e){const t=this._optimizers.indexOf(e);if(-1!==t)return this._optimizers.splice(t,1),this}addOutputNode(e){if(null===e.target)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return 0!=(e.target&dt.Vertex)&&this._addVertexOutputNode(e),0!=(e.target&dt.Fragment)&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return null===e.target||(0!=(e.target&dt.Vertex)&&this._removeVertexOutputNode(e),0!=(e.target&dt.Fragment)&&this._removeFragmentOutputNode(e)),this}_addVertexOutputNode(e){if(-1===this._vertexOutputNodes.indexOf(e))return e.target=dt.Vertex,this._vertexOutputNodes.push(e),this}_removeVertexOutputNode(e){const t=this._vertexOutputNodes.indexOf(e);if(-1!==t)return this._vertexOutputNodes.splice(t,1),this}_addFragmentOutputNode(e){if(-1===this._fragmentOutputNodes.indexOf(e))return e.target=dt.Fragment,this._fragmentOutputNodes.push(e),this}_removeFragmentOutputNode(e){const t=this._fragmentOutputNodes.indexOf(e);if(-1!==t)return this._fragmentOutputNodes.splice(t,1),this}needAlphaBlending(){return!this.ignoreAlpha&&(this.forceAlphaBlending||this.alpha<1||this._sharedData&&this._sharedData.hints.needAlphaBlending)}needAlphaTesting(){return this._sharedData&&this._sharedData.hints.needAlphaTesting}_initializeBlock(e,t,i,n=!0){if(e.initialize(t),n&&e.autoConfigure(this),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)){if(e.isUnique){const t=e.getClassName();for(const e of this.attachedBlocks)if(e.getClassName()===t)throw`Cannot have multiple blocks of type ${t} in the same NodeMaterial`}this.attachedBlocks.push(e)}for(const s of e.inputs){s.associatedVariableName="";const r=s.connectedPoint;if(r){const s=r.ownerBlock;s!==e&&((s.target===dt.VertexAndFragment||t.target===dt.Fragment&&s.target===dt.Vertex&&s._preparationId!==this._buildId)&&i.push(s),this._initializeBlock(s,t,i,n))}}for(const s of e.outputs)s.associatedVariableName=""}_resetDualBlocks(e,t){e.target===dt.VertexAndFragment&&(e.buildId=t);for(const i of e.inputs){const n=i.connectedPoint;if(n){const i=n.ownerBlock;i!==e&&this._resetDualBlocks(i,t)}}}removeBlock(e){const t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e.isFinalMerger&&this.removeOutputNode(e)}build(e=!1,t=!0,i=!0){this._buildWasSuccessful=!1;const n=this.getScene().getEngine(),s=this._mode===qt.Particle;if(0===this._vertexOutputNodes.length&&!s)throw"You must define at least one vertexOutputNode";if(0===this._fragmentOutputNodes.length)throw"You must define at least one fragmentOutputNode";this._vertexCompilationState=new _t,this._vertexCompilationState.supportUniformBuffers=n.supportsUniformBuffers,this._vertexCompilationState.target=dt.Vertex,this._fragmentCompilationState=new _t,this._fragmentCompilationState.supportUniformBuffers=n.supportsUniformBuffers,this._fragmentCompilationState.target=dt.Fragment,this._sharedData=new mt,this._sharedData.fragmentOutputNodes=this._fragmentOutputNodes,this._vertexCompilationState.sharedData=this._sharedData,this._fragmentCompilationState.sharedData=this._sharedData,this._sharedData.buildId=this._buildId,this._sharedData.emitComments=this._options.emitComments,this._sharedData.verbose=e,this._sharedData.scene=this.getScene(),this._sharedData.allowEmptyVertexProgram=s;const r=[],o=[];for(const l of this._vertexOutputNodes)r.push(l),this._initializeBlock(l,this._vertexCompilationState,o,i);for(const l of this._fragmentOutputNodes)o.push(l),this._initializeBlock(l,this._fragmentCompilationState,r,i);this.optimize();for(const l of r)l.build(this._vertexCompilationState,r);this._fragmentCompilationState.uniforms=this._vertexCompilationState.uniforms.slice(0),this._fragmentCompilationState._uniformDeclaration=this._vertexCompilationState._uniformDeclaration,this._fragmentCompilationState._constantDeclaration=this._vertexCompilationState._constantDeclaration,this._fragmentCompilationState._vertexState=this._vertexCompilationState;for(const l of o)this._resetDualBlocks(l,this._buildId-1);for(const l of o)l.build(this._fragmentCompilationState,o);this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),t&&(this._buildId=Ni._BuildIdGenerator++),this._sharedData.emitErrors(),e&&(console.log("Vertex shader:"),console.log(this._vertexCompilationState.compilationString),console.log("Fragment shader:"),console.log(this._fragmentCompilationState.compilationString)),this._buildWasSuccessful=!0,this.onBuildObservable.notifyObservers(this);const a=this.getScene().meshes;for(const l of a)if(l.subMeshes)for(const e of l.subMeshes){if(e.getMaterial()!==this)continue;if(!e.materialDefines)continue;const t=e.materialDefines;t.markAllAsDirty(),t.reset()}}optimize(){for(const e of this._optimizers)e.optimize(this._vertexOutputNodes,this._fragmentOutputNodes)}_prepareDefinesForAttributes(e,t){const i=t.NORMAL,n=t.TANGENT,s=t.VERTEXCOLOR_NME;t.NORMAL=e.isVerticesDataPresent(ne.o.NormalKind),t.TANGENT=e.isVerticesDataPresent(ne.o.TangentKind);const r=e.useVertexColors&&e.isVerticesDataPresent(ne.o.ColorKind);t.VERTEXCOLOR_NME=r;let o=!1;for(let a=1;a<=6;++a){const i=t["UV"+a];t["UV"+a]=e.isVerticesDataPresent(`uv${1===a?"":a}`),o=o||t["UV"+a]!==i}(i!==t.NORMAL||n!==t.TANGENT||s!==t.VERTEXCOLOR_NME||o)&&t.markAsAttributesDirty()}createPostProcess(e,t=1,i=1,n,s,r=0,o=5){return this.mode!==qt.PostProcess?(console.log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,n,s,r,o)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,n=1,s,r,o=0,a=5){let l=this.name+this._buildId;const h=new Di,c=new ie.x(l+"PostProcess",this.getScene());let d=this._buildId;return this._processDefines(c,h),ft.Q.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),e?e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l):e=new Zt(this.name+"PostProcess",l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,n,s,r,h.toString(),o,l,{maxSimultaneousLights:this.maxSimultaneousLights},!1,a),e.nodeMaterialSource=this,e.onApplyObservable.add((t=>{d!==this._buildId&&(delete ft.Q.ShadersStore[l+"VertexShader"],delete ft.Q.ShadersStore[l+"PixelShader"],l=this.name+this._buildId,h.markAllAsDirty(),d=this._buildId);this._processDefines(c,h)&&(ft.Q.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),Pe.Q.SetImmediate((()=>e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l)))),this._checkInternals(t)})),e}createProceduralTexture(e,t){if(this.mode!==qt.ProceduralTexture)return console.log("Incompatible material mode"),null;let i=this.name+this._buildId;const n=new Pi(i,e,null,t),s=new ie.x(i+"Procedural",this.getScene());s.reservedDataStore={hidden:!0};const r=new Di,o=this._processDefines(s,r);ft.Q.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString);let a=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[ne.o.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,r.toString(),null==o?void 0:o.fallbacks,void 0);n.nodeMaterialSource=this,n._setEffect(a);let l=this._buildId;return n.onBeforeGenerationObservable.add((()=>{l!==this._buildId&&(delete ft.Q.ShadersStore[i+"VertexShader"],delete ft.Q.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,r.markAllAsDirty(),l=this._buildId);const e=this._processDefines(s,r);e&&(ft.Q.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),Pe.Q.SetImmediate((()=>{a=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[ne.o.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,r.toString(),null==e?void 0:e.fallbacks,void 0),n._setEffect(a)}))),this._checkInternals(a)})),n}_createEffectForParticles(e,t,i,n,s,r,o,a=""){let l=this.name+this._buildId+"_"+t;r||(r=new Di),o||(o=this.getScene().getMeshByName(this.name+"Particle"))||((o=new ie.x(this.name+"Particle",this.getScene())).reservedDataStore={hidden:!0});let h=this._buildId;const c=[];let d=a;if(!s){const a=this._processDefines(o,r);ft.Q.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),e.fillDefines(c,t),d=c.join("\n"),s=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,r.toString()+"\n"+d,null==a?void 0:a.fallbacks,i,n,e),e.setCustomEffect(s,t)}s.onBindObservable.add((s=>{h!==this._buildId&&(delete ft.Q.ShadersStore[l+"PixelShader"],l=this.name+this._buildId+"_"+t,r.markAllAsDirty(),h=this._buildId),c.length=0,e.fillDefines(c,t);const u=c.join("\n");u!==d&&(r.markAllAsDirty(),d=u);const p=this._processDefines(o,r);if(p)return ft.Q.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),s=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,r.toString()+"\n"+d,null==p?void 0:p.fallbacks,i,n,e),e.setCustomEffect(s,t),void this._createEffectForParticles(e,t,i,n,s,r,o,a);this._checkInternals(s)}))}_checkInternals(e){if(this._sharedData.animatedInputs){const e=this.getScene(),t=e.getFrameId();if(this._animationFrame!==t){for(const t of this._sharedData.animatedInputs)t.animate(e);this._animationFrame=t}}for(const t of this._sharedData.bindableBlocks)t.bind(e,this);for(const t of this._sharedData.inputBlocks)t._transmit(e,this.getScene(),this)}createEffectForParticles(e,t,i){this.mode===qt.Particle?(this._createEffectForParticles(e,pi.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,pi.BLENDMODE_MULTIPLY,t,i)):console.log("Incompatible material mode")}createAsShadowDepthWrapper(e){this.mode===qt.Material?e.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(this,this.getScene()):console.log("Incompatible material mode")}_processDefines(e,t,i=!1,n){let s=null;const r=this.getScene();if(It.G.PrepareDefinesForCamera(r,t)&&t.markAsMiscDirty(),this._sharedData.blocksWithDefines.forEach((n=>{n.initializeDefines(e,this,t,i)})),this._sharedData.blocksWithDefines.forEach((s=>{s.prepareDefines(e,this,t,i,n)})),t.isDirty){const i=t._areLightsDisposed;t.markAsProcessed(),this._vertexCompilationState.compilationString=this._vertexCompilationState._builtCompilationString,this._fragmentCompilationState.compilationString=this._fragmentCompilationState._builtCompilationString,this._sharedData.repeatableContentBlocks.forEach((i=>{i.replaceRepeatableContent(this._vertexCompilationState,this._fragmentCompilationState,e,t)}));const n=[];this._sharedData.dynamicUniformBlocks.forEach((e=>{e.updateUniformsAndSamples(this._vertexCompilationState,this,t,n)}));const r=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach((e=>{-1===r.indexOf(e)&&r.push(e)}));const o=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach((e=>{-1===o.indexOf(e)&&o.push(e)}));const a=new zt;this._sharedData.blocksWithFallbacks.forEach((t=>{t.provideFallbacks(e,a)})),s={lightDisposed:i,uniformBuffers:n,mergedUniforms:r,mergedSamplers:o,fallbacks:a}}return s}isReadyForSubMesh(e,t,i=!1){if(!this._buildWasSuccessful)return!1;const n=this.getScene();if(this._sharedData.animatedInputs){const e=n.getFrameId();if(this._animationFrame!==e){for(const e of this._sharedData.animatedInputs)e.animate(n);this._animationFrame=e}}if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new Di);const s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const r=n.getEngine();if(this._prepareDefinesForAttributes(e,s),this._sharedData.blockingBlocks.some((t=>!t.isReady(e,this,s,i))))return!1;const o=this._processDefines(e,s,i,t);if(o){const e=t.effect,i=s.toString();let a=r.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:o.mergedUniforms,uniformBuffersNames:o.uniformBuffers,samplers:o.mergedSamplers,defines:i,fallbacks:o.fallbacks,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:s.NUM_MORPH_INFLUENCERS}},r);if(a)if(this._onEffectCreatedObservable&&(Oi.effect=a,Oi.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Oi)),this.allowShaderHotSwapping&&e&&!a.isReady()){if(a=e,s.markAsUnprocessed(),o.lightDisposed)return s._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(a,s,this._materialContext)}return!(!t.effect||!t.effect.isReady())&&(s._renderId=n.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}get compiledShaders(){return`// Vertex shader\r\n${this._vertexCompilationState.compilationString}\r\n\r\n// Fragment shader\r\n${this._fragmentCompilationState.compilationString}`}bindOnlyWorldMatrix(e){const t=this.getScene();if(!this._activeEffect)return;const i=this._sharedData.hints;i.needWorldViewMatrix&&e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),i.needWorldViewProjectionMatrix&&e.multiplyToRef(t.getTransformMatrix(),this._cachedWorldViewProjectionMatrix);for(const n of this._sharedData.inputBlocks)n._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}bindForSubMesh(e,t,i){const n=this.getScene(),s=i.effect;if(!s)return;this._activeEffect=s,this.bindOnlyWorldMatrix(e);const r=this._mustRebind(n,s,t.visibility),o=this._sharedData;if(r){for(const e of o.bindableBlocks)e.bind(s,this,t,i);for(const e of o.forcedBindableBlocks)e.bind(s,this,t,i);for(const e of o.inputBlocks)e._transmit(s,n,this)}else if(!this.isFrozen)for(const a of o.forcedBindableBlocks)a.bind(s,this,t,i);this._afterBind(t,this._activeEffect)}getActiveTextures(){const e=super.getActiveTextures();return this._sharedData&&e.push(...this._sharedData.textureBlocks.filter((e=>e.texture)).map((e=>e.texture))),e}getTextureBlocks(){return this._sharedData?this._sharedData.textureBlocks:[]}getAllTextureBlocks(){const e=[];for(const t of this.attachedBlocks)Ni._BlockIsTextureBlock(t)&&e.push(t);return e}hasTexture(e){if(super.hasTexture(e))return!0;if(!this._sharedData)return!1;for(const t of this._sharedData.textureBlocks)if(t.texture===e)return!0;return!1}dispose(e,t,i){if(t)for(const n of this.getTextureBlocks().filter((e=>e.texture)).map((e=>e.texture)))n.dispose();for(const n of this.attachedBlocks)n.dispose();this.attachedBlocks.length=0,this._sharedData=null,this._vertexCompilationState=null,this._fragmentCompilationState=null,this.onBuildObservable.clear(),this._imageProcessingObserver&&(this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingObserver=null),super.dispose(e,t,i)}_createNodeEditor(e){const t=Object.assign({nodeMaterial:this},e);this.BJSNODEMATERIALEDITOR.NodeEditor.Show(t)}edit(e){return new Promise((t=>{if(this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),void 0===this.BJSNODEMATERIALEDITOR){const i=e&&e.editorURL?e.editorURL:Ni.EditorURL;se.w1.LoadScript(i,(()=>{this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),this._createNodeEditor(null==e?void 0:e.nodeEditorConfig),t()}))}else this._createNodeEditor(null==e?void 0:e.nodeEditorConfig),t()}))}clear(){this._vertexOutputNodes.length=0,this._fragmentOutputNodes.length=0,this.attachedBlocks.length=0}setToDefault(){this.clear(),this.editorData=null;const e=new Bt("Position");e.setAsAttribute("position");const t=new Bt("World");t.setAsSystemValue(Pt.World);const i=new Ct("WorldPos");e.connectTo(i),t.connectTo(i);const n=new Bt("ViewProjection");n.setAsSystemValue(Pt.ViewProjection);const s=new Ct("WorldPos * ViewProjectionTransform");i.connectTo(s),n.connectTo(s);const r=new yt("VertexOutput");s.connectTo(r);const o=new Bt("color");o.value=new a.HE(.8,.8,.8,1);const l=new Mt("FragmentOutput");o.connectTo(l),this.addOutputNode(r),this.addOutputNode(l),this._mode=qt.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;const e=new Bt("Position");e.setAsAttribute("position2d");const t=new Bt("Constant1");t.isConstant=!0,t.value=1;const i=new Jt("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const n=new yt("VertexOutput");i.connectTo(n);const s=new Bt("Scale");s.visibleInInspector=!0,s.value=new o.FM(1,1);const r=new ei("uv0");e.connectTo(r);const a=new ti("UV scale");r.connectTo(a),s.connectTo(a);const l=new Ut("CurrentScreen");a.connectTo(l),l.texture=new Le("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());const h=new Mt("FragmentOutput");l.connectTo(h,{output:"rgba"}),this.addOutputNode(n),this.addOutputNode(h),this._mode=qt.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;const e=new Bt("Position");e.setAsAttribute("position2d");const t=new Bt("Constant1");t.isConstant=!0,t.value=1;const i=new Jt("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const n=new yt("VertexOutput");i.connectTo(n);const s=new Bt("Time");s.value=0,s.min=0,s.max=0,s.isBoolean=!1,s.matrixMode=0,s.animationType=Dt.Time,s.isConstant=!1;const r=new Bt("Color3");r.value=new a.Wo(1,1,1),r.isConstant=!1;const o=new Mt("FragmentOutput"),l=new Jt("VectorMerger");l.visibleInInspector=!1;const h=new Mi("Cos");h.operation=Ii.Cos,e.connectTo(l),s.output.connectTo(h.input),h.output.connectTo(l.z),l.xyzOut.connectTo(o.rgb),this.addOutputNode(n),this.addOutputNode(o),this._mode=qt.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;const e=new Bt("uv");e.setAsAttribute("particle_uv");const t=new Vt("ParticleTexture");e.connectTo(t);const i=new Bt("Color");i.setAsAttribute("particle_color");const n=new ti("Texture * Color");t.connectTo(n),i.connectTo(n);const s=new kt("ParticleRampGradient");n.connectTo(s);const r=new fi("ColorSplitter");i.connectTo(r);const o=new Gt("ParticleBlendMultiply");s.connectTo(o),t.connectTo(o,{output:"a"}),r.connectTo(o,{output:"a"});const a=new Mt("FragmentOutput");o.connectTo(a),this.addOutputNode(a),this._mode=qt.Particle}async loadAsync(e,t=""){return Ni.ParseFromFileAsync("",e,this.getScene(),t,!0,this)}_gatherBlocks(e,t){if(-1===t.indexOf(e)){t.push(e);for(const i of e.inputs){const n=i.connectedPoint;if(n){const i=n.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}}}generateCode(){let e=[];const t=[],i=["const","var","let"];for(const r of this._vertexOutputNodes)this._gatherBlocks(r,t);const n=[];for(const r of this._fragmentOutputNodes)this._gatherBlocks(r,n);let s=`var nodeMaterial = new BABYLON.NodeMaterial("${this.name||"node material"}");\r\n`;for(const r of t)r.isInput&&-1===e.indexOf(r)&&(s+=r._dumpCode(i,e));for(const r of n)r.isInput&&-1===e.indexOf(r)&&(s+=r._dumpCode(i,e));e=[],s+="\r\n// Connections\r\n";for(const r of this._vertexOutputNodes)s+=r._dumpCodeForOutputConnections(e);for(const r of this._fragmentOutputNodes)s+=r._dumpCodeForOutputConnections(e);s+="\r\n// Output nodes\r\n";for(const r of this._vertexOutputNodes)s+=`nodeMaterial.addOutputNode(${r._codeVariableName});\r\n`;for(const r of this._fragmentOutputNodes)s+=`nodeMaterial.addOutputNode(${r._codeVariableName});\r\n`;return s+="nodeMaterial.build();\r\n",s}serialize(e){const t=e?{}:E.p4.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];if(e)i=e;else{t.customType="BABYLON.NodeMaterial",t.outputNodes=[];for(const e of this._vertexOutputNodes)this._gatherBlocks(e,i),t.outputNodes.push(e.uniqueId);for(const e of this._fragmentOutputNodes)this._gatherBlocks(e,i),-1===t.outputNodes.indexOf(e.uniqueId)&&t.outputNodes.push(e.uniqueId)}t.blocks=[];for(const n of i)t.blocks.push(n.serialize());if(!e)for(const n of this.attachedBlocks)-1===i.indexOf(n)&&t.blocks.push(n.serialize());return t}_restoreConnections(e,t,i){for(const n of e.outputs)for(const s of t.blocks){const r=i[s.id];if(r)for(const o of s.inputs)if(i[o.targetBlockId]!==e||o.targetConnectionName!==n.name);else{const e=r.getInputByName(o.inputName);if(!e||e.isConnected)continue;n.connectTo(e,!0),this._restoreConnections(r,t,i)}}}parseSerializedObject(e,t="",i=!1){var n;i||this.clear();const s={};for(const r of e.blocks){const e=(0,l.q)(r.customType);if(e){const i=new e;i._deserialize(r,this.getScene(),t),s[r.id]=i,this.attachedBlocks.push(i)}}for(let r=0;rnew Ni(e,this.getScene(),this.options)),this);return n.id=e,n.name=e,n.parseSerializedObject(i),n._buildId=this._buildId,n.build(!1,!t),n}static Parse(e,t,i=""){const n=E.p4.Parse((()=>new Ni(e.name,t)),e,t,i);return n.parseSerializedObject(e,i),n.build(),n}static async ParseFromFileAsync(e,t,i,n="",s=!1,r){const o=null!=r?r:new Ni(e,i),a=await i._loadFileAsync(t),l=JSON.parse(a);return o.parseSerializedObject(l,n),s||o.build(),o}static ParseFromSnippetAsync(e,t=m.l.LastCreatedScene,i="",n,s=!1){return"_BLANK"===e?Promise.resolve(Ni.CreateDefault("blank",t)):new Promise(((r,o)=>{const a=new y.g;a.addEventListener("readystatechange",(()=>{if(4==a.readyState)if(200==a.status){const h=JSON.parse(JSON.parse(a.responseText).jsonPayload),c=JSON.parse(h.nodeMaterial);n||((n=E.p4.Parse((()=>new Ni(e,t)),c,t,i)).uniqueId=t.getUniqueId()),n.parseSerializedObject(c),n.snippetId=e;try{s||n.build(),r(n)}catch(l){o(l)}}else o("Unable to load the snippet "+e)})),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()}))}static CreateDefault(e,t){const i=new Ni(e,t);return i.setToDefault(),i.build(),i}}function Fi(e){const t=e.sideOrientation||Qe.x.DEFAULTSIDE,i=e.radius||1,n=void 0===e.flat||e.flat,s=e.subdivisions||4,r=e.radiusX||i,a=e.radiusY||i,l=e.radiusZ||i,h=(1+Math.sqrt(5))/2,c=[-1,h,-0,1,h,0,-1,-h,0,1,-h,0,0,-1,-h,0,1,-h,0,-1,h,0,1,h,h,0,1,h,0,-1,-h,0,1,-h,0,-1],d=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],u=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],p=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],f=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],_=new Array,m=new Array,g=new Array,v=new Array;let T=0;const S=new Array(3),E=new Array(3);let x;for(x=0;x<3;x++)S[x]=o.P.Zero(),E[x]=o.FM.Zero();for(let C=0;C<20;C++){for(x=0;x<3;x++){const e=d[3*C+x];S[x].copyFromFloats(c[3*u[e]],c[3*u[e]+1],c[3*u[e]+2]),S[x].normalize(),E[x].copyFromFloats(.134765625*p[2*e]+.05859375+-.0390625*f[C],.2333984375*p[2*e+1]+.025390625+.01953125*f[C])}const e=(e,t,i,h)=>{const c=o.P.Lerp(S[0],S[2],t/s),d=o.P.Lerp(S[1],S[2],t/s),u=s===t?S[2]:o.P.Lerp(c,d,e/(s-t));let p;if(u.normalize(),n){const e=o.P.Lerp(S[0],S[2],h/s),t=o.P.Lerp(S[1],S[2],h/s);p=o.P.Lerp(e,t,i/(s-h))}else p=new o.P(u.x,u.y,u.z);p.x/=r,p.y/=a,p.z/=l,p.normalize();const f=o.FM.Lerp(E[0],E[2],t/s),x=o.FM.Lerp(E[1],E[2],t/s),b=s===t?E[2]:o.FM.Lerp(f,x,e/(s-t));m.push(u.x*r,u.y*a,u.z*l),g.push(p.x,p.y,p.z),v.push(b.x,we.e.UseOpenGLOrientationForUV?1-b.y:b.y),_.push(T),T++};for(let t=0;twi(e,t,i),function(e){e.WRIST="wrist",e.THUMB="thumb",e.INDEX="index",e.MIDDLE="middle",e.RING="ring",e.LITTLE="little"}(Li||(Li={})),function(e){e.WRIST="wrist",e.THUMB_METACARPAL="thumb-metacarpal",e.THUMB_PHALANX_PROXIMAL="thumb-phalanx-proximal",e.THUMB_PHALANX_DISTAL="thumb-phalanx-distal",e.THUMB_TIP="thumb-tip",e.INDEX_FINGER_METACARPAL="index-finger-metacarpal",e.INDEX_FINGER_PHALANX_PROXIMAL="index-finger-phalanx-proximal",e.INDEX_FINGER_PHALANX_INTERMEDIATE="index-finger-phalanx-intermediate",e.INDEX_FINGER_PHALANX_DISTAL="index-finger-phalanx-distal",e.INDEX_FINGER_TIP="index-finger-tip",e.MIDDLE_FINGER_METACARPAL="middle-finger-metacarpal",e.MIDDLE_FINGER_PHALANX_PROXIMAL="middle-finger-phalanx-proximal",e.MIDDLE_FINGER_PHALANX_INTERMEDIATE="middle-finger-phalanx-intermediate",e.MIDDLE_FINGER_PHALANX_DISTAL="middle-finger-phalanx-distal",e.MIDDLE_FINGER_TIP="middle-finger-tip",e.RING_FINGER_METACARPAL="ring-finger-metacarpal",e.RING_FINGER_PHALANX_PROXIMAL="ring-finger-phalanx-proximal",e.RING_FINGER_PHALANX_INTERMEDIATE="ring-finger-phalanx-intermediate",e.RING_FINGER_PHALANX_DISTAL="ring-finger-phalanx-distal",e.RING_FINGER_TIP="ring-finger-tip",e.PINKY_FINGER_METACARPAL="pinky-finger-metacarpal",e.PINKY_FINGER_PHALANX_PROXIMAL="pinky-finger-phalanx-proximal",e.PINKY_FINGER_PHALANX_INTERMEDIATE="pinky-finger-phalanx-intermediate",e.PINKY_FINGER_PHALANX_DISTAL="pinky-finger-phalanx-distal",e.PINKY_FINGER_TIP="pinky-finger-tip"}(Bi||(Bi={}));const Ui=[Bi.WRIST,Bi.THUMB_METACARPAL,Bi.THUMB_PHALANX_PROXIMAL,Bi.THUMB_PHALANX_DISTAL,Bi.THUMB_TIP,Bi.INDEX_FINGER_METACARPAL,Bi.INDEX_FINGER_PHALANX_PROXIMAL,Bi.INDEX_FINGER_PHALANX_INTERMEDIATE,Bi.INDEX_FINGER_PHALANX_DISTAL,Bi.INDEX_FINGER_TIP,Bi.MIDDLE_FINGER_METACARPAL,Bi.MIDDLE_FINGER_PHALANX_PROXIMAL,Bi.MIDDLE_FINGER_PHALANX_INTERMEDIATE,Bi.MIDDLE_FINGER_PHALANX_DISTAL,Bi.MIDDLE_FINGER_TIP,Bi.RING_FINGER_METACARPAL,Bi.RING_FINGER_PHALANX_PROXIMAL,Bi.RING_FINGER_PHALANX_INTERMEDIATE,Bi.RING_FINGER_PHALANX_DISTAL,Bi.RING_FINGER_TIP,Bi.PINKY_FINGER_METACARPAL,Bi.PINKY_FINGER_PHALANX_PROXIMAL,Bi.PINKY_FINGER_PHALANX_INTERMEDIATE,Bi.PINKY_FINGER_PHALANX_DISTAL,Bi.PINKY_FINGER_TIP],Vi={[Li.WRIST]:[Bi.WRIST],[Li.THUMB]:[Bi.THUMB_METACARPAL,Bi.THUMB_PHALANX_PROXIMAL,Bi.THUMB_PHALANX_DISTAL,Bi.THUMB_TIP],[Li.INDEX]:[Bi.INDEX_FINGER_METACARPAL,Bi.INDEX_FINGER_PHALANX_PROXIMAL,Bi.INDEX_FINGER_PHALANX_INTERMEDIATE,Bi.INDEX_FINGER_PHALANX_DISTAL,Bi.INDEX_FINGER_TIP],[Li.MIDDLE]:[Bi.MIDDLE_FINGER_METACARPAL,Bi.MIDDLE_FINGER_PHALANX_PROXIMAL,Bi.MIDDLE_FINGER_PHALANX_INTERMEDIATE,Bi.MIDDLE_FINGER_PHALANX_DISTAL,Bi.MIDDLE_FINGER_TIP],[Li.RING]:[Bi.RING_FINGER_METACARPAL,Bi.RING_FINGER_PHALANX_PROXIMAL,Bi.RING_FINGER_PHALANX_INTERMEDIATE,Bi.RING_FINGER_PHALANX_DISTAL,Bi.RING_FINGER_TIP],[Li.LITTLE]:[Bi.PINKY_FINGER_METACARPAL,Bi.PINKY_FINGER_PHALANX_PROXIMAL,Bi.PINKY_FINGER_PHALANX_INTERMEDIATE,Bi.PINKY_FINGER_PHALANX_DISTAL,Bi.PINKY_FINGER_TIP]};class ki{get handMesh(){return this._handMesh}getHandPartMeshes(e){return Vi[e].map((e=>this._jointMeshes[Ui.indexOf(e)]))}getJointMesh(e){return this._jointMeshes[Ui.indexOf(e)]}constructor(e,t,i,n,s=!1,r=!1,a=1){this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=n,this._leftHandedMeshes=s,this._jointsInvisible=r,this._jointScaleFactor=a,this._jointTransforms=new Array(Ui.length),this._jointTransformMatrices=new Float32Array(16*Ui.length),this._tempJointMatrix=new o.y3,this._jointRadii=new Float32Array(Ui.length),this._scene=t[0].getScene();for(let l=0;l{e.rootMesh&&e.rootMesh.setEnabled(!1)}))),this.xrController.onMotionControllerInitObservable.add((e=>{e.onModelLoadedObservable.add((e=>{e.rootMesh&&e.rootMesh.setEnabled(!1)})),e.rootMesh&&e.rootMesh.setEnabled(!1)}))}setHandMesh(e,t){if(this._handMesh=e,e.alwaysSelectAsActiveMesh=!0,e.getChildMeshes().forEach((e=>e.alwaysSelectAsActiveMesh=!0)),this._handMesh.skeleton){const e=this._handMesh.skeleton;Ui.forEach(((i,n)=>{const s=e.getBoneIndexByName(t?t[i]:i);-1!==s&&e.bones[s].linkTransformNode(this._jointTransforms[n])}))}}updateFromXRFrame(e,t){const i=this.xrController.inputSource.hand;if(!i)return;const n=i,s=Ui.map((e=>n[e]||i.get(e)));let r=!1;if(e.fillPoses&&e.fillJointRadii)r=e.fillPoses(s,t,this._jointTransformMatrices)&&e.fillJointRadii(s,this._jointRadii);else if(e.getJointPose){r=!0;for(let i=0;i{const i=this._jointTransforms[t];o.y3.FromArrayToRef(this._jointTransformMatrices,16*t,this._tempJointMatrix),this._tempJointMatrix.decompose(void 0,i.rotationQuaternion,i.position);const n=this._jointRadii[t]*this._jointScaleFactor,s=this._jointMeshes[t];s.isVisible=!this._handMesh&&!this._jointsInvisible,s.position.copyFrom(i.position),s.rotationQuaternion.copyFrom(i.rotationQuaternion),s.scaling.setAll(n),this._scene.useRightHandedSystem||(s.position.z*=-1,s.rotationQuaternion.z*=-1,s.rotationQuaternion.w*=-1,this._leftHandedMeshes&&this._handMesh&&(i.position.z*=-1,i.rotationQuaternion.z*=-1,i.rotationQuaternion.w*=-1))})),this._handMesh&&(this._handMesh.isVisible=!0))}dispose(){this._handMesh&&(this._handMesh.isVisible=!1)}}class Gi extends nt{static _GenerateTrackedJointMeshes(e){const t={};return["left","right"].map((i=>{var n,s,r,a,l;const h=[],c=(null===(n=e.jointMeshes)||void 0===n?void 0:n.sourceMesh)||wi("jointParent",Gi._ICOSPHERE_PARAMS);c.isVisible=!!(null===(s=e.jointMeshes)||void 0===s?void 0:s.keepOriginalVisible);for(let t=0;t{var n,s,r,o,l;const h={};(null===(s=null===(n=Gi._RightHandGLB)||void 0===n?void 0:n.meshes[1])||void 0===s?void 0:s.isDisposed())&&(Gi._RightHandGLB=null),(null===(o=null===(r=Gi._LeftHandGLB)||void 0===r?void 0:r.meshes[1])||void 0===o?void 0:o.isDisposed())&&(Gi._LeftHandGLB=null);const c=!(!Gi._RightHandGLB||!Gi._LeftHandGLB),d=await Promise.all([Gi._RightHandGLB||ht.ImportMeshAsync("",Gi.DEFAULT_HAND_MODEL_BASE_URL,Gi.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),Gi._LeftHandGLB||ht.ImportMeshAsync("",Gi.DEFAULT_HAND_MODEL_BASE_URL,Gi.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)]);Gi._RightHandGLB=d[0],Gi._LeftHandGLB=d[1];const u=new Ni("handShader",e,{emitComments:!1});await u.loadAsync(Gi.DEFAULT_HAND_MODEL_SHADER_URL),u.needDepthPrePass=!0,u.transparencyMode=ut.F.MATERIAL_ALPHABLEND,u.alphaMode=2,u.build(!1);const p=Object.assign({base:a.Wo.FromInts(116,63,203),fresnel:a.Wo.FromInts(149,102,229),fingerColor:a.Wo.FromInts(177,130,255),tipFresnel:a.Wo.FromInts(220,200,255)},null===(l=null==t?void 0:t.handMeshes)||void 0===l?void 0:l.customColors),f={base:u.getBlockByName("baseColor"),fresnel:u.getBlockByName("fresnelColor"),fingerColor:u.getBlockByName("fingerColor"),tipFresnel:u.getBlockByName("tipFresnelColor")};f.base.value=p.base,f.fresnel.value=p.fresnel,f.fingerColor.value=p.fingerColor,f.tipFresnel.value=p.tipFresnel,["left","right"].forEach((t=>{const i="left"==t?Gi._LeftHandGLB:Gi._RightHandGLB;if(!i)throw new Error("Could not load hand model");const n=i.meshes[1];n._internalAbstractMeshDataInfo._computeBonesUsingShaders=!0,n.material=u.clone(`${t}HandShaderClone`,!0),n.isVisible=!1,h[t]=n,c||e.useRightHandedSystem||i.meshes[1].rotate(L.RD.Y,Math.PI)})),u.dispose(),i({left:h.left,right:h.right})}))}static _GenerateDefaultHandMeshRigMapping(e){const t="right"==e?"R":"L";return{[Bi.WRIST]:`wrist_${t}`,[Bi.THUMB_METACARPAL]:`thumb_metacarpal_${t}`,[Bi.THUMB_PHALANX_PROXIMAL]:`thumb_proxPhalanx_${t}`,[Bi.THUMB_PHALANX_DISTAL]:`thumb_distPhalanx_${t}`,[Bi.THUMB_TIP]:`thumb_tip_${t}`,[Bi.INDEX_FINGER_METACARPAL]:`index_metacarpal_${t}`,[Bi.INDEX_FINGER_PHALANX_PROXIMAL]:`index_proxPhalanx_${t}`,[Bi.INDEX_FINGER_PHALANX_INTERMEDIATE]:`index_intPhalanx_${t}`,[Bi.INDEX_FINGER_PHALANX_DISTAL]:`index_distPhalanx_${t}`,[Bi.INDEX_FINGER_TIP]:`index_tip_${t}`,[Bi.MIDDLE_FINGER_METACARPAL]:`middle_metacarpal_${t}`,[Bi.MIDDLE_FINGER_PHALANX_PROXIMAL]:`middle_proxPhalanx_${t}`,[Bi.MIDDLE_FINGER_PHALANX_INTERMEDIATE]:`middle_intPhalanx_${t}`,[Bi.MIDDLE_FINGER_PHALANX_DISTAL]:`middle_distPhalanx_${t}`,[Bi.MIDDLE_FINGER_TIP]:`middle_tip_${t}`,[Bi.RING_FINGER_METACARPAL]:`ring_metacarpal_${t}`,[Bi.RING_FINGER_PHALANX_PROXIMAL]:`ring_proxPhalanx_${t}`,[Bi.RING_FINGER_PHALANX_INTERMEDIATE]:`ring_intPhalanx_${t}`,[Bi.RING_FINGER_PHALANX_DISTAL]:`ring_distPhalanx_${t}`,[Bi.RING_FINGER_TIP]:`ring_tip_${t}`,[Bi.PINKY_FINGER_METACARPAL]:`little_metacarpal_${t}`,[Bi.PINKY_FINGER_PHALANX_PROXIMAL]:`little_proxPhalanx_${t}`,[Bi.PINKY_FINGER_PHALANX_INTERMEDIATE]:`little_intPhalanx_${t}`,[Bi.PINKY_FINGER_PHALANX_DISTAL]:`little_distPhalanx_${t}`,[Bi.PINKY_FINGER_TIP]:`little_tip_${t}`}}isCompatible(){return"undefined"!=typeof XRHand}getHandByControllerId(e){return this._attachedHands[e]}getHandByHandedness(e){return"none"==e?null:this._trackingHands[e]}constructor(e,t){super(e),this.options=t,this._attachedHands={},this._trackingHands={left:null,right:null},this._handResources={jointMeshes:null,handMeshes:null,rigMappings:null},this.onHandAddedObservable=new r.y$,this.onHandRemovedObservable=new r.y$,this._attachHand=e=>{var t,i,n;if(!e.inputSource.hand||"none"==e.inputSource.handedness||!this._handResources.jointMeshes)return;const s=e.inputSource.handedness,r=new ki(e,this._handResources.jointMeshes[s],this._handResources.handMeshes&&this._handResources.handMeshes[s],this._handResources.rigMappings&&this._handResources.rigMappings[s],null===(t=this.options.handMeshes)||void 0===t?void 0:t.meshesUseLeftHandedCoordinates,null===(i=this.options.jointMeshes)||void 0===i?void 0:i.invisible,null===(n=this.options.jointMeshes)||void 0===n?void 0:n.scaleFactor);this._attachedHands[e.uniqueId]=r,this._trackingHands[s]=r,this.onHandAddedObservable.notifyObservers(r)},this._detachHand=e=>{this._detachHandById(e.uniqueId)},this.xrNativeFeatureName="hand-tracking";const i=t.jointMeshes;if(i&&(void 0!==i.disableDefaultHandMesh&&(t.handMeshes=t.handMeshes||{},t.handMeshes.disableDefaultMeshes=i.disableDefaultHandMesh),void 0!==i.handMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.customMeshes=i.handMeshes),void 0!==i.leftHandedSystemMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.meshesUseLeftHandedCoordinates=i.leftHandedSystemMeshes),void 0!==i.rigMapping)){t.handMeshes=t.handMeshes||{};const e={},n={};[[i.rigMapping.left,e],[i.rigMapping.right,n]].forEach((e=>{const t=e[0],i=e[1];t.forEach(((e,t)=>{i[Ui[t]]=e}))})),t.handMeshes.customRigMappings={left:e,right:n}}}attach(){var e,t,i,n;return!!super.attach()&&(this._handResources={jointMeshes:Gi._GenerateTrackedJointMeshes(this.options),handMeshes:(null===(e=this.options.handMeshes)||void 0===e?void 0:e.customMeshes)||null,rigMappings:(null===(t=this.options.handMeshes)||void 0===t?void 0:t.customRigMappings)||null},(null===(i=this.options.handMeshes)||void 0===i?void 0:i.customMeshes)||(null===(n=this.options.handMeshes)||void 0===n?void 0:n.disableDefaultMeshes)||Gi._GenerateDefaultHandMeshesAsync(m.l.LastCreatedScene,this.options).then((e=>{var t,i;this._handResources.handMeshes=e,this._handResources.rigMappings={left:Gi._GenerateDefaultHandMeshRigMapping("left"),right:Gi._GenerateDefaultHandMeshRigMapping("right")},null===(t=this._trackingHands.left)||void 0===t||t.setHandMesh(this._handResources.handMeshes.left,this._handResources.rigMappings.left),null===(i=this._trackingHands.right)||void 0===i||i.setHandMesh(this._handResources.handMeshes.right,this._handResources.rigMappings.right)})),this.options.xrInput.controllers.forEach(this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerAddedObservable,this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerRemovedObservable,this._detachHand),!0)}_onXRFrame(e){var t,i;null===(t=this._trackingHands.left)||void 0===t||t.updateFromXRFrame(e,this._xrSessionManager.referenceSpace),null===(i=this._trackingHands.right)||void 0===i||i.updateFromXRFrame(e,this._xrSessionManager.referenceSpace)}_detachHandById(e){var t;const i=this.getHandByControllerId(e);if(i){const n="left"==i.xrController.inputSource.handedness?"left":"right";(null===(t=this._trackingHands[n])||void 0===t?void 0:t.xrController.uniqueId)===e&&(this._trackingHands[n]=null),this.onHandRemovedObservable.notifyObservers(i),i.dispose(),delete this._attachedHands[e]}}detach(){return!!super.detach()&&(Object.keys(this._attachedHands).forEach((e=>this._detachHandById(e))),!0)}dispose(){var e;super.dispose(),this.onHandAddedObservable.clear(),this.onHandRemovedObservable.clear(),this._handResources.handMeshes&&!(null===(e=this.options.handMeshes)||void 0===e?void 0:e.customMeshes)&&(this._handResources.handMeshes.left.dispose(),this._handResources.handMeshes.right.dispose(),Gi._RightHandGLB=null,Gi._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach((e=>e.dispose())),this._handResources.jointMeshes.right.forEach((e=>e.dispose())))}}var zi,Wi,Hi;Gi.Name=tt.HAND_TRACKING,Gi.Version=1,Gi.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/",Gi.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb",Gi.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb",Gi.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json",Gi._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2},Gi._RightHandGLB=null,Gi._LeftHandGLB=null,it.AddWebXRFeature(Gi.Name,((e,t)=>()=>new Gi(e,t)),Gi.Version,!1),function(e){e[e.ABOVE_FINGER_TIPS=0]="ABOVE_FINGER_TIPS",e[e.RADIAL_SIDE=1]="RADIAL_SIDE",e[e.ULNAR_SIDE=2]="ULNAR_SIDE",e[e.BELOW_WRIST=3]="BELOW_WRIST"}(zi||(zi={})),function(e){e[e.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",e[e.HAND_ROTATION=1]="HAND_ROTATION"}(Wi||(Wi={})),function(e){e[e.ALWAYS_VISIBLE=0]="ALWAYS_VISIBLE",e[e.PALM_UP=1]="PALM_UP",e[e.GAZE_FOCUS=2]="GAZE_FOCUS",e[e.PALM_AND_GAZE=3]="PALM_AND_GAZE"}(Hi||(Hi={}));class Xi{get maxAngle(){return this._maxAngle}set maxAngle(e){this._setMaxAngle(e)}constructor(e,t,i){this.targetPosition=o.P.Zero(),this.poleTargetPosition=o.P.Zero(),this.poleTargetLocalOffset=o.P.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=o._f.Identity(),this._bone1Mat=o.y3.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._rightHandedSystem=!1,this._bendAxis=o.P.Right(),this._slerping=!1,this._adjustRoll=0,this._notEnoughInformation=!1,this._bone2=t;const n=t.getParent();if(!n)return this._notEnoughInformation=!0,void p.Y.Error("BoneIKController: bone must have a parent for IK to work.");if(this._bone1=n,0===this._bone2.children.length&&!this._bone2.length)return this._notEnoughInformation=!0,void p.Y.Error("BoneIKController: bone must not be a leaf or it should have a length for IK to work.");this.mesh=e;const s=t.getPosition();if(t.getAbsoluteMatrix().determinant()>0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,s.x>s.y&&s.x>s.z&&(this._adjustRoll=.5*Math.PI,this._bendAxis.z=1)),this._bone1.length&&this._bone2.length){const e=this._bone1.getScale(),t=this._bone2.getScale();this._bone1Length=this._bone1.length*e.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y}else if(this._bone2.children[0]){e.computeWorldMatrix(!0);const t=this._bone2.children[0].getAbsolutePosition(e),i=this._bone2.getAbsolutePosition(e),n=this._bone1.getAbsolutePosition(e);this._bone2Length=o.P.Distance(t,i),this._bone1Length=o.P.Distance(i,n)}else{e.computeWorldMatrix(!0);const t=this._bone2.getScale();this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y;const i=this._bone2.getAbsolutePosition(e),n=this._bone1.getAbsolutePosition(e);this._bone1Length=o.P.Distance(i,n)}this._bone1.getRotationMatrixToRef(L.T.WORLD,e,this._bone1Mat),this.maxAngle=Math.PI,i&&(i.targetMesh&&(this.targetMesh=i.targetMesh,this.targetMesh.computeWorldMatrix(!0)),i.poleTargetMesh?(this.poleTargetMesh=i.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):i.poleTargetBone?this.poleTargetBone=i.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),i.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(i.poleTargetLocalOffset),i.poleAngle&&(this.poleAngle=i.poleAngle),i.bendAxis&&this._bendAxis.copyFrom(i.bendAxis),i.maxAngle&&(this.maxAngle=i.maxAngle),i.slerpAmount&&(this.slerpAmount=i.slerpAmount))}_setMaxAngle(e){e<0&&(e=0),(e>Math.PI||null==e)&&(e=Math.PI),this._maxAngle=e;const t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))}update(){if(this._notEnoughInformation)return;const e=this.targetPosition,t=this.poleTargetPosition,i=Xi._TmpMats[0],n=Xi._TmpMats[1];this.targetMesh&&e.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,t):this.poleTargetMesh&&o.P.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),t);const s=Xi._TmpVecs[0],r=Xi._TmpVecs[1],a=Xi._TmpVecs[2],l=Xi._TmpVecs[3],h=Xi._TmpVecs[4],c=Xi._TmpQuat;this._bone1.getAbsolutePositionToRef(this.mesh,s),t.subtractToRef(s,h),0==h.x&&0==h.y&&0==h.z?h.y=1:h.normalize(),e.subtractToRef(s,l),l.normalize(),o.P.CrossToRef(l,h,r),r.normalize(),o.P.CrossToRef(l,r,a),a.normalize(),o.y3.FromXYZAxesToRef(a,l,r,i);const d=this._bone1Length,u=this._bone2Length;let p=o.P.Distance(s,e);this._maxReach>0&&(p=Math.min(this._maxReach,p));let f=(u*u+p*p-d*d)/(2*u*p),_=(p*p+d*d-u*u)/(2*p*d);f>1&&(f=1),_>1&&(_=1),f<-1&&(f=-1),_<-1&&(_=-1);const m=Math.acos(f),g=Math.acos(_);let v=-m-g;if(this._rightHandedSystem)o.y3.RotationYawPitchRollToRef(0,0,this._adjustRoll,n),n.multiplyToRef(i,i),o.y3.RotationAxisToRef(this._bendAxis,g,n),n.multiplyToRef(i,i);else{const e=Xi._TmpVecs[5];e.copyFrom(this._bendAxis),e.x*=-1,o.y3.RotationAxisToRef(e,-g,n),n.multiplyToRef(i,i)}this.poleAngle&&(o.y3.RotationAxisToRef(l,this.poleAngle,n),i.multiplyToRef(n,i)),this._bone1&&(this.slerpAmount<1?(this._slerping||o._f.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),o._f.FromRotationMatrixToRef(i,c),o._f.SlerpToRef(this._bone1Quat,c,this.slerpAmount,this._bone1Quat),v=this._bone2Ang*(1-this.slerpAmount)+v*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,L.T.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(i,L.T.WORLD,this.mesh),this._bone1Mat.copyFrom(i),this._slerping=!1),this._updateLinkedTransformRotation(this._bone1)),this._bone2.setAxisAngle(this._bendAxis,v,L.T.LOCAL),this._updateLinkedTransformRotation(this._bone2),this._bone2Ang=v}_updateLinkedTransformRotation(e){e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new o._f),e.getRotationQuaternionToRef(L.T.LOCAL,null,e._linkedTransformNode.rotationQuaternion))}}Xi._TmpVecs=[o.P.Zero(),o.P.Zero(),o.P.Zero(),o.P.Zero(),o.P.Zero(),o.P.Zero()],Xi._TmpQuat=o._f.Identity(),Xi._TmpMats=[o.y3.Identity(),o.y3.Identity()];class Yi{get minYaw(){return this._minYaw}set minYaw(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),null!=this._maxYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get maxYaw(){return this._maxYaw}set maxYaw(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),null!=this._minYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get minPitch(){return this._minPitch}set minPitch(e){this._minPitch=e,this._minPitchTan=Math.tan(e)}get maxPitch(){return this._maxPitch}set maxPitch(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)}constructor(e,t,i,n){if(this.upAxis=o.P.Up(),this.upAxisSpace=L.T.LOCAL,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=o._f.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=o.P.Forward(),this.useAbsoluteValueForYaw=!1,this.mesh=e,this.bone=t,this.target=i,n){if(n.adjustYaw&&(this.adjustYaw=n.adjustYaw),n.adjustPitch&&(this.adjustPitch=n.adjustPitch),n.adjustRoll&&(this.adjustRoll=n.adjustRoll),null!=n.maxYaw?this.maxYaw=n.maxYaw:this.maxYaw=Math.PI,null!=n.minYaw?this.minYaw=n.minYaw:this.minYaw=-Math.PI,null!=n.maxPitch?this.maxPitch=n.maxPitch:this.maxPitch=Math.PI,null!=n.minPitch?this.minPitch=n.minPitch:this.minPitch=-Math.PI,null!=n.slerpAmount&&(this.slerpAmount=n.slerpAmount),null!=n.upAxis&&(this.upAxis=n.upAxis),null!=n.upAxisSpace&&(this.upAxisSpace=n.upAxisSpace),null!=n.yawAxis||null!=n.pitchAxis){let e=L.RD.Y,t=L.RD.X;null!=n.yawAxis&&(e=n.yawAxis.clone(),e.normalize()),null!=n.pitchAxis&&(t=n.pitchAxis.clone(),t.normalize());const i=o.P.Cross(t,e);this._transformYawPitch=o.y3.Identity(),o.y3.FromXYZAxesToRef(t,e,i,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}void 0!==n.useAbsoluteValueForYaw&&(this.useAbsoluteValueForYaw=n.useAbsoluteValueForYaw)}t.getParent()||this.upAxisSpace!=L.T.BONE||(this.upAxisSpace=L.T.LOCAL)}update(){if(this.slerpAmount<1&&!this._firstFrameSkipped)return void(this._firstFrameSkipped=!0);const e=this.bone,t=Yi._TmpVecs[0];e.getAbsolutePositionToRef(this.mesh,t);let i=this.target;const n=Yi._TmpMats[0],s=Yi._TmpMats[1],r=this.mesh,a=e.getParent(),l=Yi._TmpVecs[1];l.copyFrom(this.upAxis),this.upAxisSpace==L.T.BONE&&a?(this._transformYawPitch&&o.P.TransformCoordinatesToRef(l,this._transformYawPitchInv,l),a.getDirectionToRef(l,this.mesh,l)):this.upAxisSpace==L.T.LOCAL&&(r.getDirectionToRef(l,l),1==r.scaling.x&&1==r.scaling.y&&1==r.scaling.z||l.normalize());let h=!1,c=!1;if(this._maxYaw==Math.PI&&this._minYaw==-Math.PI||(h=!0),this._maxPitch==Math.PI&&this._minPitch==-Math.PI||(c=!0),h||c){const e=Yi._TmpMats[2],n=Yi._TmpMats[3];if(this.upAxisSpace==L.T.BONE&&1==l.y&&a)a.getRotationMatrixToRef(L.T.WORLD,this.mesh,e);else if(this.upAxisSpace!=L.T.LOCAL||1!=l.y||a){let t=Yi._TmpVecs[2];t.copyFrom(this._fowardAxis),this._transformYawPitch&&o.P.TransformCoordinatesToRef(t,this._transformYawPitchInv,t),a?a.getDirectionToRef(t,this.mesh,t):r.getDirectionToRef(t,t);const i=o.P.Cross(l,t);i.normalize(),t=o.P.Cross(i,l),o.y3.FromXYZAxesToRef(i,l,t,e)}else e.copyFrom(r.getWorldMatrix());e.invertToRef(n);let s=null;if(c){const r=Yi._TmpVecs[3];i.subtractToRef(t,r),o.P.TransformCoordinatesToRef(r,n,r),s=Math.sqrt(r.x*r.x+r.z*r.z);const a=Math.atan2(r.y,s);let l=a;a>this._maxPitch?(r.y=this._maxPitchTan*s,l=this._maxPitch):athis._maxYaw||lMath.PI?this._isAngleBetween(a,this._maxYaw,this._midYawConstraint)?(r.z=this._maxYawCos*s,r.x=this._maxYawSin*s,h=this._maxYaw):this._isAngleBetween(a,this._midYawConstraint,this._minYaw)&&(r.z=this._minYawCos*s,r.x=this._minYawSin*s,h=this._minYaw):l>this._maxYaw?(r.z=this._maxYawCos*s,r.x=this._maxYawSin*s,a<0&&this.useAbsoluteValueForYaw&&(r.x*=-1),h=this._maxYaw):lMath.PI){const e=Yi._TmpVecs[8];e.copyFrom(L.RD.Z),this._transformYawPitch&&o.P.TransformCoordinatesToRef(e,this._transformYawPitchInv,e);const t=Yi._TmpMats[4];this._boneQuat.toRotationMatrix(t),this.mesh.getWorldMatrix().multiplyToRef(t,t),o.P.TransformCoordinatesToRef(e,t,e),o.P.TransformCoordinatesToRef(e,n,e);const i=Math.atan2(e.x,e.z);if(this._getAngleBetween(i,a)>this._getAngleBetween(i,this._midYawConstraint)){null==s&&(s=Math.sqrt(r.x*r.x+r.z*r.z));const e=this._getAngleBetween(i,this._maxYaw);this._getAngleBetween(i,this._minYaw)Math.PI?i-=2*Math.PI:i<-Math.PI&&(i+=2*Math.PI),i}_getAngleBetween(e,t){let i=0;return i=(e=(e%=2*Math.PI)<0?e+2*Math.PI:e)<(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)?t-e:e-t,i>Math.PI&&(i=2*Math.PI-i),i}_isAngleBetween(e,t,i){if(e=(e%=2*Math.PI)<0?e+2*Math.PI:e,(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)<(i=(i%=2*Math.PI)<0?i+2*Math.PI:i)){if(e>t&&ei&&e0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter((e=>!e.getParent()))}getTransformMatrices(e){return this.needInitialSkinMatrix?(e._bonesTransformMatrices||this.prepare(),e._bonesTransformMatrices):(this._transformMatrices&&!this._isDirty||this.prepare(),this._transformMatrices)}getTransformMatrixTexture(e){return this.needInitialSkinMatrix&&e._transformMatrixTexture?e._transformMatrixTexture:this._transformMatrixTexture}getScene(){return this._scene}toString(e){let t=`Name: ${this.name}, nBones: ${this.bones.length}`;if(t+=`, nAnimationRanges: ${this._ranges?Object.keys(this._ranges).length:"none"}`,e){t+=", Ranges: {";let e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}getBoneIndexByName(e){for(let t=0,i=this.bones.length;t-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i0)for(const e of this.bones)if(e._linkedTransformNode){const t=e._linkedTransformNode;e.position=t.position,t.rotationQuaternion?e.rotationQuaternion=t.rotationQuaternion:e.rotation=t.rotation,e.scaling=t.scaling}if(this.needInitialSkinMatrix)for(const e of this._meshesWithPoseMatrix){const t=e.getPoseMatrix();let i=this._isDirty;if(e._bonesTransformMatrices&&e._bonesTransformMatrices.length===16*(this.bones.length+1)||(e._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)),i=!0),i){if(this._synchronizedWithMesh!==e){this._synchronizedWithMesh=e;for(const e of this.bones)if(!e.getParent()){e.getBindMatrix().multiplyToRef(t,o.jp.Matrix[1]),e._updateAbsoluteBindMatrices(o.jp.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=ze.CreateRGBATexture(e._bonesTransformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,1,1))}}this._computeTransformMatrices(e._bonesTransformMatrices,t),this.isUsingTextureForMatrices&&e._transformMatrixTexture&&e._transformMatrixTexture.update(e._bonesTransformMatrices)}}else{if(!this._isDirty)return;this._transformMatrices&&this._transformMatrices.length===16*(this.bones.length+1)||(this._transformMatrices=new Float32Array(16*(this.bones.length+1)),this.isUsingTextureForMatrices&&(this._transformMatrixTexture&&this._transformMatrixTexture.dispose(),this._transformMatrixTexture=ze.CreateRGBATexture(this._transformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,1,1))),this._computeTransformMatrices(this._transformMatrices,null),this.isUsingTextureForMatrices&&this._transformMatrixTexture&&this._transformMatrixTexture.update(this._transformMatrices)}this._isDirty=!1}getAnimatables(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(let e=0;e{t.animations.forEach((t=>{t.enableBlending=!0,t.blendingSpeed=e}))}))}dispose(){if(this._meshesWithPoseMatrix.length=0,this.getScene().stopAnimation(this),this.getScene().removeSkeleton(this),this._parentContainer){const e=this._parentContainer.skeletons.indexOf(this);e>-1&&this._parentContainer.skeletons.splice(e,1),this._parentContainer=null}this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null)}serialize(){var e;const t={};t.name=this.name,t.id=this.id,this.dimensionsAtRest&&(t.dimensionsAtRest=this.dimensionsAtRest.asArray()),t.bones=[],t.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let i=0;i0&&(r.animation=n.animations[0].serialize()),t.ranges=[];for(const e in this._ranges){const i=this._ranges[e];if(!i)continue;const n={};n.name=e,n.from=i.from,n.to=i.to,t.ranges.push(n)}}return t}static Parse(e,t){const i=new ji(e.name,e.id,t);let n;for(e.dimensionsAtRest&&(i.dimensionsAtRest=o.P.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix,n=0;n-1&&(r=i.bones[t.parentBoneIndex]);const a=t.rest?o.y3.FromArray(t.rest):null,l=new B(t.name,i,r,o.y3.FromArray(t.matrix),a,null,s);void 0!==t.id&&null!==t.id&&(l.id=t.id),t.length&&(l.length=t.length),t.metadata&&(l.metadata=t.metadata),t.animation&&l.animations.push(A.Parse(t.animation)),void 0!==t.linkedTransformNodeId&&null!==t.linkedTransformNodeId&&(i._hasWaitingData=!0,l._waitingTransformNodeId=t.linkedTransformNodeId)}if(e.ranges)for(n=0;n0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){const e=new Array,t=new Array(this.bones.length);for(let i=0;i{e.setCurrentPoseAsRest()}))}}var Ki=i(1545);class qi{constructor(e,t,i=3){this._engine=e,this._engine._storageBuffers.push(this),this._create(t,i)}_create(e,t){this._bufferSize=e,this._creationFlags=t,this._buffer=this._engine.createStorageBuffer(e,t)}_rebuild(){this._create(this._bufferSize,this._creationFlags)}getBuffer(){return this._buffer}update(e,t,i){this._buffer&&this._engine.updateStorageBuffer(this._buffer,e,t,i)}read(e,t,i){return this._engine.readFromStorageBuffer(this._buffer,e,t,i)}dispose(){const e=this._engine._storageBuffers,t=e.indexOf(this);-1!==t&&(e[t]=e[e.length-1],e.pop()),this._engine._releaseBuffer(this._buffer),this._buffer=null}}var $i=i(1318);class Qi{constructor(){this.wheelPrecisionX=3,this.wheelPrecisionY=3,this.wheelPrecisionZ=3,this.onChangedObservable=new r.y$,this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0,this._ffMultiplier=12,this._normalize=120}attachControl(e){e=se.w1.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==We.kD.POINTERWHEEL)return;const i=t.event,n=i.deltaMode===$i.G.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,We.kD.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null),this.onChangedObservable&&this.onChangedObservable.clear()}checkInputs(){this.onChangedObservable.notifyObservers({wheelDeltaX:this._wheelDeltaX,wheelDeltaY:this._wheelDeltaY,wheelDeltaZ:this._wheelDeltaZ}),this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0}getClassName(){return"BaseCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}(0,oe.gn)([(0,E.qC)()],Qi.prototype,"wheelPrecisionX",void 0),(0,oe.gn)([(0,E.qC)()],Qi.prototype,"wheelPrecisionY",void 0),(0,oe.gn)([(0,E.qC)()],Qi.prototype,"wheelPrecisionZ",void 0);class Zi{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=se.w1.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();let n=0,s=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=r=>{var o,a;const l=r.event,h="touch"===l.pointerType;if(t.isInVRExclusivePointerMode)return;if(r.type!==We.kD.POINTERMOVE&&-1===this.buttons.indexOf(l.button))return;const c=l.target;if(this._altKey=l.altKey,this._ctrlKey=l.ctrlKey,this._metaKey=l.metaKey,this._shiftKey=l.shiftKey,this._buttonsPressed=l.buttons,t.isPointerLock){const e=l.movementX,t=l.movementY;this.onTouch(null,e,t),this._pointA=null,this._pointB=null}else{if(r.type!==We.kD.POINTERDOWN&&h&&(null===(o=this._pointA)||void 0===o?void 0:o.pointerId)!==l.pointerId&&(null===(a=this._pointB)||void 0===a?void 0:a.pointerId)!==l.pointerId)return;if(r.type!==We.kD.POINTERDOWN||-1!==this._currentActiveButton&&!h)if(r.type===We.kD.POINTERDOUBLETAP)this.onDoubleTap(l.pointerType);else if(r.type!==We.kD.POINTERUP||this._currentActiveButton!==l.button&&!h){if(r.type===We.kD.POINTERMOVE)if(e||l.preventDefault(),this._pointA&&null===this._pointB){const e=l.clientX-this._pointA.x,t=l.clientY-this._pointA.y;this.onTouch(this._pointA,e,t),this._pointA.x=l.clientX,this._pointA.y=l.clientY}else if(this._pointA&&this._pointB){const e=this._pointA.pointerId===l.pointerId?this._pointA:this._pointB;e.x=l.clientX,e.y=l.clientY;const t=this._pointA.x-this._pointB.x,i=this._pointA.y-this._pointB.y,o=t*t+i*i,a={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:l.pointerId,type:r.type};this.onMultiTouch(this._pointA,this._pointB,n,o,s,a),s=a,n=o}}else{try{null==c||c.releasePointerCapture(l.pointerId)}catch(d){}h||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==l.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==l.pointerId?this._pointB=null:this._pointA=this._pointB=null,(0!==n||s)&&(this.onMultiTouch(this._pointA,this._pointB,n,0,s,null),n=0,s=null),this._currentActiveButton=-1,this.onButtonUp(l),e||l.preventDefault()}else{try{null==c||c.setPointerCapture(l.pointerId)}catch(d){}if(null===this._pointA)this._pointA={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType};else{if(null!==this._pointB)return;this._pointB={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType}}-1!==this._currentActiveButton||h||(this._currentActiveButton=l.button),this.onButtonDown(l),e||(l.preventDefault(),i&&i.focus())}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,We.kD.POINTERDOWN|We.kD.POINTERUP|We.kD.POINTERMOVE|We.kD.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,n=0,s=null,this.onLostFocus()},this._contextMenuBind=this.onContextMenu.bind(this),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const r=this.camera.getScene().getEngine().getHostWindow();r&&se.w1.RegisterTopRootEvents(r,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&se.w1.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){const e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentActiveButton=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,i){}onMultiTouch(e,t,i,n,s,r){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}(0,oe.gn)([(0,E.qC)()],Zi.prototype,"buttons",void 0);var Ji={};class en{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){const t=e.getSimpleName();this.attached[t]?p.Y.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=!ce.V.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 i in this.attached){const e=this.attached[i],n=E.p4.Serialize(e);t[e.getClassName()]=n}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const e in t){const i=Ji[e];if(i){const n=t[e],s=E.p4.Parse((()=>new i),n,null);this.add(s)}}}else for(const i in this.attached){const t=Ji[this.attached[i].getClassName()];if(t){const n=E.p4.Parse((()=>new t),e,null);this.remove(this.attached[i]),this.add(n)}}}}class tn{get isConnected(){return this._isConnected}constructor(e,t,i,n=0,s=1,r=2,o=3){this.id=e,this.index=t,this.browserGamepad=i,this._leftStick={x:0,y:0},this._rightStick={x:0,y:0},this._isConnected=!0,this._invertLeftStickY=!1,this.type=tn.GAMEPAD,this._leftStickAxisX=n,this._leftStickAxisY=s,this._rightStickAxisX=r,this._rightStickAxisY=o,this.browserGamepad.axes.length>=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}onleftstickchanged(e){this._onleftstickchanged=e}onrightstickchanged(e){this._onrightstickchanged=e}get leftStick(){return this._leftStick}set leftStick(e){!this._onleftstickchanged||this._leftStick.x===e.x&&this._leftStick.y===e.y||this._onleftstickchanged(e),this._leftStick=e}get rightStick(){return this._rightStick}set rightStick(e){!this._onrightstickchanged||this._rightStick.x===e.x&&this._rightStick.y===e.y||this._onrightstickchanged(e),this._rightStick=e}update(){this._leftStick&&(this.leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]},this._invertLeftStickY&&(this.leftStick.y*=-1)),this._rightStick&&(this.rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}dispose(){}}tn.GAMEPAD=0,tn.GENERIC=1,tn.XBOX=2,tn.POSE_ENABLED=3,tn.DUALSHOCK=4;class nn extends tn{onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new r.y$,this.onButtonUpObservable=new r.y$,this.type=tn.GENERIC,this._buttons=new Array(i.buttons.length)}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}update(){super.update();for(let e=0;e{e.type!==tn.POSE_ENABLED&&(this.gamepad&&e.type!==tn.XBOX||(this.gamepad=e))})),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{this.gamepad===e&&(this.gamepad=null)})),this.gamepad=e.getGamepadByType(tn.XBOX)}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad){const e=this.camera,t=this.gamepad.rightStick;if(t){if(0!=t.x){const i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){const i=t.y/this.gamepadRotationSensibility*this._yAxisScale;0!=i&&Math.abs(i)>.005&&(e.inertialBetaOffset+=i)}}const i=this.gamepad.leftStick;if(i&&0!=i.y){const e=i.y/this.gamepadMoveSensibility;0!=e&&Math.abs(e)>.005&&(this.camera.inertialRadiusOffset-=e)}}}getClassName(){return"ArcRotateCameraGamepadInput"}getSimpleName(){return"gamepad"}}(0,oe.gn)([(0,E.qC)()],sn.prototype,"gamepadRotationSensibility",void 0),(0,oe.gn)([(0,E.qC)()],sn.prototype,"gamepadMoveSensibility",void 0),Ji.ArcRotateCameraGamepadInput=sn;var rn=i(6081);class on{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=se.w1.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===rn.OG.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;t0?n/(1+this.wheelDeltaPercentage):n*(1+this.wheelDeltaPercentage),i}attachControl(e){e=se.w1.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==We.kD.POINTERWHEEL)return;const i=t.event;let n=0;const s=i.deltaMode===$i.G.DOM_DELTA_LINE?40:1,r=-i.deltaY*s;if(this.customComputeDeltaFromMouseWheel)n=this.customComputeDeltaFromMouseWheel(r,this,i);else if(this.wheelDeltaPercentage){if(n=this._computeDeltaFromMouseWheelLegacyEvent(r,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=S.R.Clamp(e,0,Number.MAX_VALUE),n=this._computeDeltaFromMouseWheelLegacyEvent(r,e)}}else n=r/(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,We.kD.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=Me.J.FromPositionAndNormal(e.target,t)}_getPosition(){var e;const t=this.camera,i=t.getScene(),n=i.createPickingRay(i.pointerX,i.pointerY,o.y3.Identity(),t,!1);n.origin.x-=t.targetScreenOffset.x,n.origin.y-=t.targetScreenOffset.y;let s=0;return this._hitPlane&&(s=null!==(e=n.intersectsPlane(this._hitPlane))&&void 0!==e?e:0),n.origin.addInPlace(n.direction.scaleInPlace(s))}_zoomToMouse(e){var t,i;const n=this.camera,s=1-n.inertia;if(n.lowerRadiusLimit){const i=null!==(t=n.lowerRadiusLimit)&&void 0!==t?t:0;n.radius-(n.inertialRadiusOffset+e)/st&&(e=(n.radius-t)*s-n.inertialRadiusOffset)}const r=e/s/n.radius,a=this._getPosition(),l=o.jp.Vector3[6];a.subtractToRef(n.target,l),l.scaleInPlace(r),l.scaleInPlace(s),this._inertialPanning.addInPlace(l),n.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,n),this._isPinching=!0):this._computeMultiTouchPanning(s,r)):this.multiTouchPanning?this._computeMultiTouchPanning(s,r):this.pinchZoom&&this._computePinchZoom(i,n))}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton}onButtonUp(){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}}ln.MinimumRadiusForPinch=.001,(0,oe.gn)([(0,E.qC)()],ln.prototype,"buttons",void 0),(0,oe.gn)([(0,E.qC)()],ln.prototype,"angularSensibilityX",void 0),(0,oe.gn)([(0,E.qC)()],ln.prototype,"angularSensibilityY",void 0),(0,oe.gn)([(0,E.qC)()],ln.prototype,"pinchPrecision",void 0),(0,oe.gn)([(0,E.qC)()],ln.prototype,"pinchDeltaPercentage",void 0),(0,oe.gn)([(0,E.qC)()],ln.prototype,"useNaturalPinchZoom",void 0),(0,oe.gn)([(0,E.qC)()],ln.prototype,"pinchZoom",void 0),(0,oe.gn)([(0,E.qC)()],ln.prototype,"panningSensibility",void 0),(0,oe.gn)([(0,E.qC)()],ln.prototype,"multiTouchPanning",void 0),(0,oe.gn)([(0,E.qC)()],ln.prototype,"multiTouchPanAndZoom",void 0),Ji.ArcRotateCameraPointersInput=ln;class hn extends en{constructor(e){super(e)}addMouseWheel(){return this.add(new an),this}addPointers(){return this.add(new ln),this}addKeyboard(){return this.add(new on),this}}hn.prototype.addVRDeviceOrientation=function(){return this.add(new cn),this};class cn{constructor(){this.alphaCorrection=1,this.gammaCorrection=1,this._alpha=0,this._gamma=0,this._dirty=!1,this._deviceOrientationHandler=this._onOrientationEvent.bind(this)}attachControl(e){e=se.w1.BackCompatCameraNoPreventDefault(arguments),this.camera.attachControl(e);const t=this.camera.getScene().getEngine().getHostWindow();t&&("undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"===e?t.addEventListener("deviceorientation",this._deviceOrientationHandler):se.w1.Warn("Permission not granted.")})).catch((e=>{se.w1.Error(e)})):t.addEventListener("deviceorientation",this._deviceOrientationHandler))}_onOrientationEvent(e){null!==e.alpha&&(this._alpha=(0|+e.alpha)*this.alphaCorrection),null!==e.gamma&&(this._gamma=(0|+e.gamma)*this.gammaCorrection),this._dirty=!0}checkInputs(){this._dirty&&(this._dirty=!1,this._gamma<0&&(this._gamma=180+this._gamma),this.camera.alpha=-this._alpha/180*Math.PI%Math.PI*2,this.camera.beta=this._gamma/180*Math.PI)}detachControl(){window.removeEventListener("deviceorientation",this._deviceOrientationHandler)}getClassName(){return"ArcRotateCameraVRDeviceOrientationInput"}getSimpleName(){return"VRDeviceOrientation"}}Ji.ArcRotateCameraVRDeviceOrientationInput=cn;class dn{constructor(){this.keysForward=[87],this.keysBackward=[83],this.keysUp=[69],this.keysDown=[81],this.keysRight=[68],this.keysLeft=[65],this._keys=new Array}attachControl(e){e=se.w1.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(t.type===rn.OG.KEYDOWN){if(-1!==this.keysForward.indexOf(i.keyCode)||-1!==this.keysBackward.indexOf(i.keyCode)||-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)){-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),e||i.preventDefault()}}else if(-1!==this.keysForward.indexOf(i.keyCode)||-1!==this.keysBackward.indexOf(i.keyCode)||-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.preventDefault()}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}getClassName(){return"FlyCameraKeyboardInput"}_onLostFocus(){this._keys.length=0}getSimpleName(){return"keyboard"}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t{this._pointerInput(e)}),We.kD.POINTERDOWN|We.kD.POINTERUP|We.kD.POINTERMOVE),this._rollObserver=this.camera.getScene().onBeforeRenderObservable.add((()=>{this.camera.rollCorrect&&this.camera.restoreRoll(this.camera.rollCorrect)}))}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver),this._observer=null,this._rollObserver=null,this._previousPosition=null,this._noPreventDefault=void 0)}getClassName(){return"FlyCameraMouseInput"}getSimpleName(){return"mouse"}_pointerInput(e){const t=e.event,i=this.camera.getEngine();if(i.isInVRExclusivePointerMode)return;if(!this.touchEnabled&&"touch"===t.pointerType)return;if(e.type!==We.kD.POINTERMOVE&&-1===this.buttons.indexOf(t.button))return;const n=t.target;if(e.type===We.kD.POINTERDOWN){try{null==n||n.setPointerCapture(t.pointerId)}catch(t){}this._previousPosition={x:t.clientX,y:t.clientY},this.activeButton=t.button,this._noPreventDefault||(t.preventDefault(),this._element.focus()),i.isPointerLock&&this._onMouseMove(e.event)}else if(e.type===We.kD.POINTERUP){try{null==n||n.releasePointerCapture(t.pointerId)}catch(t){}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===We.kD.POINTERMOVE){if(!this._previousPosition)return void(i.isPointerLock&&this._onMouseMove(e.event));const n=t.clientX-this._previousPosition.x,s=t.clientY-this._previousPosition.y;this._rotateCamera(n,s),this._previousPosition={x:t.clientX,y:t.clientY},this._noPreventDefault||t.preventDefault()}}_onMouseMove(e){const t=this.camera.getEngine();if(!t.isPointerLock||t.isInVRExclusivePointerMode)return;const i=e.movementX,n=e.movementY;this._rotateCamera(i,n),this._previousPosition=null,this._noPreventDefault||e.preventDefault()}_rotateCamera(e,t){const i=this.camera;this.camera.getScene().useRightHandedSystem&&(e*=-1),i.parent&&i.parent._getWorldMatrixDeterminant()<0&&(e*=-1);const n=e/this.angularSensibility,s=t/this.angularSensibility,r=o._f.RotationYawPitchRoll(i.rotation.y,i.rotation.x,i.rotation.z);let a;if(this.buttonsPitch.some((e=>e===this.activeButton))&&(a=o._f.RotationAxis(L.RD.X,s),r.multiplyInPlace(a)),this.buttonsYaw.some((e=>e===this.activeButton))){a=o._f.RotationAxis(L.RD.Y,n),r.multiplyInPlace(a);const e=i.bankedTurnLimit+i._trackRoll;if(i.bankedTurn&&-ee===this.activeButton))&&(a=o._f.RotationAxis(L.RD.Z,-n),i._trackRoll-=n,r.multiplyInPlace(a)),r.toEulerAnglesToRef(i.rotation)}}(0,oe.gn)([(0,E.qC)()],un.prototype,"buttons",void 0),(0,oe.gn)([(0,E.qC)()],un.prototype,"angularSensibility",void 0),Ji.FlyCameraMouseInput=un;class pn{constructor(){this.keysHeightOffsetIncr=[38],this.keysHeightOffsetDecr=[40],this.keysHeightOffsetModifierAlt=!1,this.keysHeightOffsetModifierCtrl=!1,this.keysHeightOffsetModifierShift=!1,this.keysRotationOffsetIncr=[37],this.keysRotationOffsetDecr=[39],this.keysRotationOffsetModifierAlt=!1,this.keysRotationOffsetModifierCtrl=!1,this.keysRotationOffsetModifierShift=!1,this.keysRadiusIncr=[40],this.keysRadiusDecr=[38],this.keysRadiusModifierAlt=!0,this.keysRadiusModifierCtrl=!1,this.keysRadiusModifierShift=!1,this.heightSensibility=1,this.rotationSensibility=1,this.radiusSensibility=1,this._keys=new Array}attachControl(e){e=se.w1.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===rn.OG.KEYDOWN){if(this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,this._shiftPressed=i.shiftKey,-1!==this.keysHeightOffsetIncr.indexOf(i.keyCode)||-1!==this.keysHeightOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetIncr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRadiusIncr.indexOf(i.keyCode)||-1!==this.keysRadiusDecr.indexOf(i.keyCode)){-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault())}}else if(-1!==this.keysHeightOffsetIncr.indexOf(i.keyCode)||-1!==this.keysHeightOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetIncr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRadiusIncr.indexOf(i.keyCode)||-1!==this.keysRadiusDecr.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),i.preventDefault&&(e||i.preventDefault())}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){this._onKeyboardObserver&&this._keys.forEach((e=>{-1!==this.keysHeightOffsetIncr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset+=this.heightSensibility:-1!==this.keysHeightOffsetDecr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset-=this.heightSensibility:-1!==this.keysRotationOffsetIncr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset+=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRotationOffsetDecr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset-=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRadiusIncr.indexOf(e)&&this._modifierRadius()?this.camera.radius+=this.radiusSensibility:-1!==this.keysRadiusDecr.indexOf(e)&&this._modifierRadius()&&(this.camera.radius-=this.radiusSensibility)}))}getClassName(){return"FollowCameraKeyboardMoveInput"}getSimpleName(){return"keyboard"}_modifierHeightOffset(){return this.keysHeightOffsetModifierAlt===this._altPressed&&this.keysHeightOffsetModifierCtrl===this._ctrlPressed&&this.keysHeightOffsetModifierShift===this._shiftPressed}_modifierRotationOffset(){return this.keysRotationOffsetModifierAlt===this._altPressed&&this.keysRotationOffsetModifierCtrl===this._ctrlPressed&&this.keysRotationOffsetModifierShift===this._shiftPressed}_modifierRadius(){return this.keysRadiusModifierAlt===this._altPressed&&this.keysRadiusModifierCtrl===this._ctrlPressed&&this.keysRadiusModifierShift===this._shiftPressed}}(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysHeightOffsetIncr",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysHeightOffsetDecr",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysHeightOffsetModifierAlt",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysHeightOffsetModifierCtrl",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysHeightOffsetModifierShift",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysRotationOffsetIncr",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysRotationOffsetDecr",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysRotationOffsetModifierAlt",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysRotationOffsetModifierCtrl",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysRotationOffsetModifierShift",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysRadiusIncr",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysRadiusDecr",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysRadiusModifierAlt",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysRadiusModifierCtrl",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysRadiusModifierShift",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"heightSensibility",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"rotationSensibility",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"radiusSensibility",void 0),Ji.FollowCameraKeyboardMoveInput=pn;class fn{constructor(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}attachControl(e){e=se.w1.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==We.kD.POINTERWHEEL)return;const i=t.event;let n=0;const s=Math.max(-1,Math.min(1,i.deltaY));this.wheelDeltaPercentage?(console.assert(this.axisControlRadius+this.axisControlHeight+this.axisControlRotation<=1,"wheelDeltaPercentage only usable when mouse wheel controls ONE axis. Currently enabled: axisControlRadius: "+this.axisControlRadius+", axisControlHeightOffset: "+this.axisControlHeight+", axisControlRotationOffset: "+this.axisControlRotation),this.axisControlRadius?n=.01*s*this.wheelDeltaPercentage*this.camera.radius:this.axisControlHeight?n=.01*s*this.wheelDeltaPercentage*this.camera.heightOffset:this.axisControlRotation&&(n=.01*s*this.wheelDeltaPercentage*this.camera.rotationOffset)):n=s*this.wheelPrecision,n&&(this.axisControlRadius?this.camera.radius+=n:this.axisControlHeight?this.camera.heightOffset-=n:this.axisControlRotation&&(this.camera.rotationOffset-=n)),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,We.kD.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}(0,oe.gn)([(0,E.qC)()],fn.prototype,"axisControlRadius",void 0),(0,oe.gn)([(0,E.qC)()],fn.prototype,"axisControlHeight",void 0),(0,oe.gn)([(0,E.qC)()],fn.prototype,"axisControlRotation",void 0),(0,oe.gn)([(0,E.qC)()],fn.prototype,"wheelPrecision",void 0),(0,oe.gn)([(0,E.qC)()],fn.prototype,"wheelDeltaPercentage",void 0),Ji.FollowCameraMouseWheelInput=fn;class _n extends Zi{constructor(){super(...arguments),this.angularSensibilityX=1,this.angularSensibilityY=1,this.pinchPrecision=1e4,this.pinchDeltaPercentage=0,this.axisXControlRadius=!1,this.axisXControlHeight=!1,this.axisXControlRotation=!0,this.axisYControlRadius=!1,this.axisYControlHeight=!0,this.axisYControlRotation=!1,this.axisPinchControlRadius=!0,this.axisPinchControlHeight=!1,this.axisPinchControlRotation=!1,this.warningEnable=!0,this._warningCounter=0}getClassName(){return"FollowCameraPointersInput"}onTouch(e,t,i){this._warning(),this.axisXControlRotation?this.camera.rotationOffset+=t/this.angularSensibilityX:this.axisYControlRotation&&(this.camera.rotationOffset+=i/this.angularSensibilityX),this.axisXControlHeight?this.camera.heightOffset+=t/this.angularSensibilityY:this.axisYControlHeight&&(this.camera.heightOffset+=i/this.angularSensibilityY),this.axisXControlRadius?this.camera.radius-=t/this.angularSensibilityY:this.axisYControlRadius&&(this.camera.radius-=i/this.angularSensibilityY)}onMultiTouch(e,t,i,n,s,r){if(0===i&&null===s)return;if(0===n&&null===r)return;let o=(n-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(o*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=o*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=o*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=o*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=o),this.axisPinchControlHeight&&(this.camera.heightOffset+=o),this.axisPinchControlRadius&&(this.camera.radius-=o))}_warning(){if(!this.warningEnable||this._warningCounter++%100!=0)return;const e="It probably only makes sense to control ONE camera property with each pointer axis. Set 'warningEnable = false' if you are sure. Currently enabled: ";console.assert(this.axisXControlRotation+this.axisXControlHeight+this.axisXControlRadius<=1,e+"axisXControlRotation: "+this.axisXControlRotation+", axisXControlHeight: "+this.axisXControlHeight+", axisXControlRadius: "+this.axisXControlRadius),console.assert(this.axisYControlRotation+this.axisYControlHeight+this.axisYControlRadius<=1,e+"axisYControlRotation: "+this.axisYControlRotation+", axisYControlHeight: "+this.axisYControlHeight+", axisYControlRadius: "+this.axisYControlRadius),console.assert(this.axisPinchControlRotation+this.axisPinchControlHeight+this.axisPinchControlRadius<=1,e+"axisPinchControlRotation: "+this.axisPinchControlRotation+", axisPinchControlHeight: "+this.axisPinchControlHeight+", axisPinchControlRadius: "+this.axisPinchControlRadius)}}(0,oe.gn)([(0,E.qC)()],_n.prototype,"angularSensibilityX",void 0),(0,oe.gn)([(0,E.qC)()],_n.prototype,"angularSensibilityY",void 0),(0,oe.gn)([(0,E.qC)()],_n.prototype,"pinchPrecision",void 0),(0,oe.gn)([(0,E.qC)()],_n.prototype,"pinchDeltaPercentage",void 0),(0,oe.gn)([(0,E.qC)()],_n.prototype,"axisXControlRadius",void 0),(0,oe.gn)([(0,E.qC)()],_n.prototype,"axisXControlHeight",void 0),(0,oe.gn)([(0,E.qC)()],_n.prototype,"axisXControlRotation",void 0),(0,oe.gn)([(0,E.qC)()],_n.prototype,"axisYControlRadius",void 0),(0,oe.gn)([(0,E.qC)()],_n.prototype,"axisYControlHeight",void 0),(0,oe.gn)([(0,E.qC)()],_n.prototype,"axisYControlRotation",void 0),(0,oe.gn)([(0,E.qC)()],_n.prototype,"axisPinchControlRadius",void 0),(0,oe.gn)([(0,E.qC)()],_n.prototype,"axisPinchControlHeight",void 0),(0,oe.gn)([(0,E.qC)()],_n.prototype,"axisPinchControlRotation",void 0),Ji.FollowCameraPointersInput=_n;class mn{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=se.w1.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===rn.OG.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{const s=n.event,r="touch"===s.pointerType;if(t.isInVRExclusivePointerMode)return;if(!this.touchEnabled&&r)return;if(n.type!==We.kD.POINTERMOVE&&-1===this.buttons.indexOf(s.button))return;const o=s.target;if(n.type===We.kD.POINTERDOWN){if(r&&-1!==this._activePointerId||!r&&-1!==this._currentActiveButton)return;this._activePointerId=s.pointerId;try{null==o||o.setPointerCapture(s.pointerId)}catch(a){}-1===this._currentActiveButton&&(this._currentActiveButton=s.button),this._previousPosition={x:s.clientX,y:s.clientY},e||(s.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(n.event)}else if(n.type===We.kD.POINTERUP){if(r&&this._activePointerId!==s.pointerId||!r&&this._currentActiveButton!==s.button)return;try{null==o||o.releasePointerCapture(s.pointerId)}catch(a){}this._currentActiveButton=-1,this._previousPosition=null,e||s.preventDefault(),this._activePointerId=-1}else if(n.type===We.kD.POINTERMOVE&&(this._activePointerId===s.pointerId||!r))if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(n.event);else if(this._previousPosition){let t=s.clientX-this._previousPosition.x;const i=s.clientY-this._previousPosition.y;this.camera.getScene().useRightHandedSystem&&(t*=-1),this.camera.parent&&this.camera.parent._getWorldMatrixDeterminant()<0&&(t*=-1),this._allowCameraRotation&&(this.camera.cameraRotation.y+=t/this.angularSensibility,this.camera.cameraRotation.x+=i/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:t,offsetY:i}),this._previousPosition={x:s.clientX,y:s.clientY},e||s.preventDefault()}}),this._onMouseMove=i=>{if(!t.isPointerLock)return;if(t.isInVRExclusivePointerMode)return;let n=i.movementX;this.camera.getScene().useRightHandedSystem&&(n*=-1),this.camera.parent&&this.camera.parent._getWorldMatrixDeterminant()<0&&(n*=-1),this.camera.cameraRotation.y+=n/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,We.kD.POINTERDOWN|We.kD.POINTERUP|We.kD.POINTERMOVE),i&&(this._contextMenuBind=this.onContextMenu.bind(this),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._currentActiveButton=-1}getClassName(){return"FreeCameraMouseInput"}getSimpleName(){return"mouse"}}var vn;(0,oe.gn)([(0,E.qC)()],gn.prototype,"buttons",void 0),(0,oe.gn)([(0,E.qC)()],gn.prototype,"angularSensibility",void 0),Ji.FreeCameraMouseInput=gn,function(e){e[e.MoveRelative=0]="MoveRelative",e[e.RotateRelative=1]="RotateRelative",e[e.MoveScene=2]="MoveScene"}(vn||(vn={}));class Tn extends Qi{constructor(){super(...arguments),this._moveRelative=o.P.Zero(),this._rotateRelative=o.P.Zero(),this._moveScene=o.P.Zero(),this._wheelXAction=vn.MoveRelative,this._wheelXActionCoordinate=L.c7.X,this._wheelYAction=vn.MoveRelative,this._wheelYActionCoordinate=L.c7.Z,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){null===e&&this._wheelXAction!==vn.MoveRelative||(this._wheelXAction=vn.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==vn.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){null===e&&this._wheelYAction!==vn.MoveRelative||(this._wheelYAction=vn.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==vn.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){null===e&&this._wheelZAction!==vn.MoveRelative||(this._wheelZAction=vn.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==vn.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){null===e&&this._wheelXAction!==vn.RotateRelative||(this._wheelXAction=vn.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==vn.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){null===e&&this._wheelYAction!==vn.RotateRelative||(this._wheelYAction=vn.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==vn.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){null===e&&this._wheelZAction!==vn.RotateRelative||(this._wheelZAction=vn.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==vn.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){null===e&&this._wheelXAction!==vn.MoveScene||(this._wheelXAction=vn.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==vn.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){null===e&&this._wheelYAction!==vn.MoveScene||(this._wheelYAction=vn.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==vn.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){null===e&&this._wheelZAction!==vn.MoveScene||(this._wheelZAction=vn.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==vn.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=o.y3.Zero();this.camera.getViewMatrix().invertToRef(e);const t=o.P.Zero();o.P.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 vn.MoveRelative:n=this._moveRelative;break;case vn.RotateRelative:n=this._rotateRelative;break;case vn.MoveScene:n=this._moveScene}switch(i){case L.c7.X:n.set(e,0,0);break;case L.c7.Y:n.set(0,e,0);break;case L.c7.Z:n.set(0,0,e)}}}(0,oe.gn)([(0,E.qC)()],Tn.prototype,"wheelXMoveRelative",null),(0,oe.gn)([(0,E.qC)()],Tn.prototype,"wheelYMoveRelative",null),(0,oe.gn)([(0,E.qC)()],Tn.prototype,"wheelZMoveRelative",null),(0,oe.gn)([(0,E.qC)()],Tn.prototype,"wheelXRotateRelative",null),(0,oe.gn)([(0,E.qC)()],Tn.prototype,"wheelYRotateRelative",null),(0,oe.gn)([(0,E.qC)()],Tn.prototype,"wheelZRotateRelative",null),(0,oe.gn)([(0,E.qC)()],Tn.prototype,"wheelXMoveScene",null),(0,oe.gn)([(0,E.qC)()],Tn.prototype,"wheelYMoveScene",null),(0,oe.gn)([(0,E.qC)()],Tn.prototype,"wheelZMoveScene",null),Ji.FreeCameraMouseWheelInput=Tn;class Sn{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=se.w1.IsSafari()}attachControl(e){e=se.w1.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,s="mouse"===n.pointerType||this._isSafari&&void 0===n.pointerType;if(this.allowMouse||!s)if(i.type===We.kD.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===We.kD.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===We.kD.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,We.kD.POINTERDOWN|We.kD.POINTERUP|We.kD.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;e.cameraRotation.y=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 o.P(0,0,0!==this.touchMoveSensibility?t*this._offsetY/this.touchMoveSensibility:0);o.y3.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(o.P.TransformCoordinates(i,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}(0,oe.gn)([(0,E.qC)()],Sn.prototype,"touchAngularSensibility",void 0),(0,oe.gn)([(0,E.qC)()],Sn.prototype,"touchMoveSensibility",void 0),Ji.FreeCameraTouchInput=Sn;class En extends en{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new mn),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new gn(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new Tn,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new Sn),this}clear(){super.clear(),this._mouseInput=null}}En.prototype.addDeviceOrientation=function(e){return this._deviceOrientationInput||(this._deviceOrientationInput=new xn,e&&(this._deviceOrientationInput.smoothFactor=e),this.add(this._deviceOrientationInput)),this};class xn{static WaitForOrientationChangeAsync(e){return new Promise(((t,i)=>{let n=!1;const s=()=>{window.removeEventListener("deviceorientation",s),n=!0,t()};e&&setTimeout((()=>{n||(window.removeEventListener("deviceorientation",s),i("WaitForOrientationChangeAsync timed out"))}),e),"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"==e?window.addEventListener("deviceorientation",s):se.w1.Warn("Permission not granted.")})).catch((e=>{se.w1.Error(e)})):window.addEventListener("deviceorientation",s)}))}constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new o._f,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new r.y$,this._orientationChanged=()=>{this._screenOrientationAngle=void 0!==window.orientation?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,this._screenOrientationAngle=-se.w1.ToRadians(this._screenOrientationAngle/2),this._screenQuaternion.copyFromFloats(0,Math.sin(this._screenOrientationAngle),0,Math.cos(this._screenOrientationAngle))},this._deviceOrientation=e=>{this.smoothFactor?(this._alpha=null!==e.alpha?se.w1.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=null!==e.beta?se.w1.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=null!==e.gamma?se.w1.SmoothAngleChange(this._gamma,e.gamma,this.smoothFactor):0):(this._alpha=null!==e.alpha?e.alpha:0,this._beta=null!==e.beta?e.beta:0,this._gamma=null!==e.gamma?e.gamma:0),null!==e.alpha&&this._onDeviceOrientationChangedObservable.notifyObservers()},this._constantTranform=new o._f(-Math.sqrt(.5),0,0,Math.sqrt(.5)),this._orientationChanged()}get camera(){return this._camera}set camera(e){this._camera=e,null==this._camera||this._camera.rotationQuaternion||(this._camera.rotationQuaternion=new o._f),this._camera&&this._camera.onDisposeObservable.add((()=>{this._onDeviceOrientationChangedObservable.clear()}))}attachControl(){const e=this.camera.getScene().getEngine().getHostWindow();if(e){const t=()=>{e.addEventListener("orientationchange",this._orientationChanged),e.addEventListener("deviceorientation",this._deviceOrientation),this._orientationChanged()};"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"===e?t():se.w1.Warn("Permission not granted.")})).catch((e=>{se.w1.Error(e)})):t()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){this._alpha&&(o._f.RotationYawPitchRollToRef(se.w1.ToRadians(this._alpha),se.w1.ToRadians(this._beta),-se.w1.ToRadians(this._gamma),this.camera.rotationQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform),this._camera.rotationQuaternion.z*=-1,this._camera.rotationQuaternion.w*=-1)}getClassName(){return"FreeCameraDeviceOrientationInput"}getSimpleName(){return"deviceOrientation"}}Ji.FreeCameraDeviceOrientationInput=xn;class bn{constructor(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=o.y3.Identity(),this._deltaTransform=o.P.Zero(),this._vector3=o.P.Zero(),this._vector2=o.FM.Zero()}get invertYAxis(){return 1!==this._yAxisScale}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){const e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add((e=>{e.type!==tn.POSE_ENABLED&&(this.gamepad&&e.type!==tn.XBOX||(this.gamepad=e))})),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{this.gamepad===e&&(this.gamepad=null)})),this.gamepad=e.getGamepadByType(tn.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad&&this.gamepad.leftStick){const e=this.camera,t=this.gamepad.leftStick;0!==this.gamepadMoveSensibility&&(t.x=Math.abs(t.x)>this.deadzoneDelta?t.x/this.gamepadMoveSensibility:0,t.y=Math.abs(t.y)>this.deadzoneDelta?t.y/this.gamepadMoveSensibility:0);let i=this.gamepad.rightStick;i&&0!==this.gamepadAngularSensibility?(i.x=Math.abs(i.x)>this.deadzoneDelta?i.x/this.gamepadAngularSensibility:0,i.y=(Math.abs(i.y)>this.deadzoneDelta?i.y/this.gamepadAngularSensibility:0)*this._yAxisScale):i={x:0,y:0},e.rotationQuaternion?e.rotationQuaternion.toRotationMatrix(this._cameraTransform):o.y3.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);const n=50*e._computeLocalCameraSpeed();this._vector3.copyFromFloats(t.x*n,0,-t.y*n),o.P.TransformCoordinatesToRef(this._vector3,this._cameraTransform,this._deltaTransform),e.cameraDirection.addInPlace(this._deltaTransform),this._vector2.copyFromFloats(i.y,i.x),e.cameraRotation.addInPlace(this._vector2)}}getClassName(){return"FreeCameraGamepadInput"}getSimpleName(){return"gamepad"}}(0,oe.gn)([(0,E.qC)()],bn.prototype,"gamepadAngularSensibility",void 0),(0,oe.gn)([(0,E.qC)()],bn.prototype,"gamepadMoveSensibility",void 0),Ji.FreeCameraGamepadInput=bn;var Cn,yn,An,Rn,Pn,In,Mn=i(5500);!function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(Cn||(Cn={}));class On{static _GetDefaultOptions(){return{puckSize:40,containerSize:60,color:"cyan",puckImage:void 0,containerImage:void 0,position:void 0,alwaysVisible:!1,limitToContainer:!1}}constructor(e,t){this._released=!1;const i=Object.assign(Object.assign({},On._GetDefaultOptions()),t);if(this._leftJoystick=!!e,On._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=Cn.X,this._axisTargetedByUpAndDown=Cn.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new Mn.x,this.deltaPosition=o.P.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{On._VJCanvasWidth=window.innerWidth,On._VJCanvasHeight=window.innerHeight,On.Canvas&&(On.Canvas.width=On._VJCanvasWidth,On.Canvas.height=On._VJCanvasHeight),On._HalfWidth=On._VJCanvasWidth/2},!On.Canvas){window.addEventListener("resize",this._onResize,!1),On.Canvas=document.createElement("canvas"),On._VJCanvasWidth=window.innerWidth,On._VJCanvasHeight=window.innerHeight,On.Canvas.width=window.innerWidth,On.Canvas.height=window.innerHeight,On.Canvas.style.width="100%",On.Canvas.style.height="100%",On.Canvas.style.position="absolute",On.Canvas.style.backgroundColor="transparent",On.Canvas.style.top="0px",On.Canvas.style.left="0px",On.Canvas.style.zIndex="5",On.Canvas.style.touchAction="none",On.Canvas.setAttribute("touch-action","none");const e=On.Canvas.getContext("2d");if(!e)throw new Error("Unable to create canvas for virtual joystick");On._VJCanvasContext=e,On._VJCanvasContext.strokeStyle="#ffffff",On._VJCanvasContext.lineWidth=2,document.body.appendChild(On.Canvas)}On._HalfWidth=On.Canvas.width/2,this.pressed=!1,this.limitToContainer=i.limitToContainer,this._joystickColor=i.color,this.containerSize=i.containerSize,this.puckSize=i.puckSize,i.position&&this.setPosition(i.position.x,i.position.y),i.puckImage&&this.setPuckImage(i.puckImage),i.containerImage&&this.setContainerImage(i.containerImage),i.alwaysVisible&&On._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new o.FM(0,0),this._joystickPreviousPointerPos=new o.FM(0,0),this._joystickPointerStartPos=new o.FM(0,0),this._deltaJoystickVector=new o.FM(0,0),this._onPointerDownHandlerRef=e=>{this._onPointerDown(e)},this._onPointerMoveHandlerRef=e=>{this._onPointerMove(e)},this._onPointerUpHandlerRef=e=>{this._onPointerUp(e)},On.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),On.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),On.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),On.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),On.Canvas.addEventListener("contextmenu",(e=>{e.preventDefault()}),!1),requestAnimationFrame((()=>{this._drawVirtualJoystick()}))}setJoystickSensibility(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)}_onPointerDown(e){let t;e.preventDefault(),t=!0===this._leftJoystick?e.clientXOn._HalfWidth,t&&this._joystickPointerId<0?(this._joystickPointerId=e.pointerId,this._joystickPosition?(this._joystickPointerStartPos=this._joystickPosition.clone(),this._joystickPointerPos=this._joystickPosition.clone(),this._joystickPreviousPointerPos=this._joystickPosition.clone(),this._onPointerMove(e)):(this._joystickPointerStartPos.x=e.clientX,this._joystickPointerStartPos.y=e.clientY,this._joystickPointerPos=this._joystickPointerStartPos.clone(),this._joystickPreviousPointerPos=this._joystickPointerStartPos.clone()),this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this.pressed=!0,this._touches.add(e.pointerId.toString(),e)):On._GlobalJoystickIndex<2&&this._action&&(this._action(),this._touches.add(e.pointerId.toString(),{x:e.clientX,y:e.clientY,prevX:e.clientX,prevY:e.clientY}))}_onPointerMove(e){if(this._joystickPointerId==e.pointerId){if(this.limitToContainer){const t=new o.FM(e.clientX-this._joystickPointerStartPos.x,e.clientY-this._joystickPointerStartPos.y),i=t.length();i>this.containerSize&&t.scaleInPlace(this.containerSize/i),this._joystickPointerPos.x=this._joystickPointerStartPos.x+t.x,this._joystickPointerPos.y=this._joystickPointerStartPos.y+t.y}else this._joystickPointerPos.x=e.clientX,this._joystickPointerPos.y=e.clientY;this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos),0this._containerImage=t}setPuckImage(e){const t=new Image;t.src=e,t.onload=()=>this._puckImage=t}_drawContainer(){const e=this._joystickPosition||this._joystickPointerStartPos;this._clearPreviousDraw(),this._containerImage?On._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,2*this.containerSize,2*this.containerSize):(On._VJCanvasContext.beginPath(),On._VJCanvasContext.strokeStyle=this._joystickColor,On._VJCanvasContext.lineWidth=2,On._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,2*Math.PI,!0),On._VJCanvasContext.stroke(),On._VJCanvasContext.closePath(),On._VJCanvasContext.beginPath(),On._VJCanvasContext.lineWidth=6,On._VJCanvasContext.strokeStyle=this._joystickColor,On._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,2*Math.PI,!0),On._VJCanvasContext.stroke(),On._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?On._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,2*this.puckSize,2*this.puckSize):(On._VJCanvasContext.beginPath(),On._VJCanvasContext.strokeStyle=this._joystickColor,On._VJCanvasContext.lineWidth=2,On._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,2*Math.PI,!0),On._VJCanvasContext.stroke(),On._VJCanvasContext.closePath())}_drawVirtualJoystick(){this._released||(this.alwaysVisible&&this._drawContainer(),this.pressed&&this._touches.forEach(((e,t)=>{t.pointerId===this._joystickPointerId?(this.alwaysVisible||this._drawContainer(),this._drawPuck(),this._joystickPreviousPointerPos=this._joystickPointerPos.clone()):(On._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),On._VJCanvasContext.beginPath(),On._VJCanvasContext.fillStyle="white",On._VJCanvasContext.beginPath(),On._VJCanvasContext.strokeStyle="red",On._VJCanvasContext.lineWidth=6,On._VJCanvasContext.arc(t.x,t.y,40,0,2*Math.PI,!0),On._VJCanvasContext.stroke(),On._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)})),requestAnimationFrame((()=>{this._drawVirtualJoystick()})))}releaseCanvas(){On.Canvas&&(On.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),On.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),On.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),On.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(On.Canvas),On.Canvas=null),this._released=!0}}On._GlobalJoystickIndex=0,On._AlwaysVisibleSticks=0,En.prototype.addVirtualJoystick=function(){return this.add(new Dn),this};class Dn{getLeftJoystick(){return this._leftjoystick}getRightJoystick(){return this._rightjoystick}checkInputs(){if(this._leftjoystick){const e=this.camera,t=50*e._computeLocalCameraSpeed(),i=o.y3.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),n=o.P.TransformCoordinates(new o.P(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(n),e.cameraRotation=e.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}}attachControl(){this._leftjoystick=new On(!0),this._leftjoystick.setAxisForUpDown(Cn.Z),this._leftjoystick.setAxisForLeftRight(Cn.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new On(!1),this._rightjoystick.setAxisForUpDown(Cn.X),this._rightjoystick.setAxisForLeftRight(Cn.Y),this._rightjoystick.reverseUpDown=!0,this._rightjoystick.setJoystickSensibility(.05),this._rightjoystick.setJoystickColor("yellow")}detachControl(){this._leftjoystick.releaseCanvas(),this._rightjoystick.releaseCanvas()}getClassName(){return"FreeCameraVirtualJoystickInput"}getSimpleName(){return"virtualJoystick"}}Ji.FreeCameraVirtualJoystickInput=Dn;class Nn extends ce.V{constructor(e,t,i,n=!0){super(e,t,i,n),this._tmpUpVector=o.P.Zero(),this._tmpTargetVector=o.P.Zero(),this.cameraDirection=new o.P(0,0,0),this.cameraRotation=new o.FM(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new o._f,this.rotation=new o.P(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=o.P.Zero(),this._initialFocalDistance=1,this._viewMatrix=o.y3.Zero(),this._camMatrix=o.y3.Zero(),this._cameraTransformMatrix=o.y3.Zero(),this._cameraRotationMatrix=o.y3.Zero(),this._referencePoint=new o.P(0,0,1),this._transformedReferencePoint=o.P.Zero(),this._defaultUp=o.P.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 o.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new o.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new o._f(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+=k.kn),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),o.y3.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&&o._f.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(o.jp.Matrix[0]),o.P.TransformNormalToRef(this.cameraDirection,o.jp.Matrix[0],o.jp.Vector3[0]),void this.position.addInPlace(o.jp.Vector3[0]);this.position.addInPlace(this.cameraDirection)}_checkInputs(){const e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=Math.abs(this.cameraRotation.x)>0||Math.abs(this.cameraRotation.y)>0;if(t&&this._updatePosition(),i){if(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this.rotation),this.rotation.x+=this.cameraRotation.x*e,this.rotation.y+=this.cameraRotation.y*e,!this.noRotationConstraint){const e=1.570796;this.rotation.x>e&&(this.rotation.x=e),this.rotation.x<-e&&(this.rotation.x=-e)}if(this.rotationQuaternion){this.rotation.lengthSquared()&&o._f.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)}}t&&(Math.abs(this.cameraDirection.x){(e=>{this._newPosition.copyFrom(e),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>fe.D.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&i&&this.onCollide(i))})(t)},this.inputs=new En(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=se.w1.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new o.P(0,0,0),this.cameraRotation=new o.FM(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?o.P.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=o.P.Zero(),this._transformedDirection=o.P.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FreeCamera"}}(0,oe.gn)([(0,E.hd)()],Fn.prototype,"ellipsoid",void 0),(0,oe.gn)([(0,E.hd)()],Fn.prototype,"ellipsoidOffset",void 0),(0,oe.gn)([(0,E.qC)()],Fn.prototype,"checkCollisions",void 0),(0,oe.gn)([(0,E.qC)()],Fn.prototype,"applyGravity",void 0),b.N.AddNodeConstructor("TouchCamera",((e,t)=>()=>new wn(e,o.P.Zero(),t)));class wn extends Fn{get touchAngularSensibility(){const e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0}set touchAngularSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)}get touchMoveSensibility(){const e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0}set touchMoveSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addTouch(),this._setupInputs()}getClassName(){return"TouchCamera"}_setupInputs(){const e=this.inputs.attached.touch,t=this.inputs.attached.mouse;t?t.touchEnabled=!1:e.allowMouse=!0}}b.N.AddNodeConstructor("ArcRotateCamera",((e,t)=>()=>new Ln(e,0,0,1,o.P.Zero(),t)));class Ln extends Nn{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 o.y3,this._upToYMatrix=new o.y3,this._upVector=o.P.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){o.y3.RotationAlignToRef(o.P.UpReadOnly,this._upVector,this._yToUpMatrix),o.y3.RotationAlignToRef(this._upVector,o.P.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 Xe,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 Ye,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 He,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,n,s,a,l=!0){super(e,o.P.Zero(),a,l),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.lowerAlphaLimit=null,this.upperAlphaLimit=null,this.lowerBetaLimit=.01,this.upperBetaLimit=Math.PI-.01,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.inertialPanningX=0,this.inertialPanningY=0,this.pinchToPanMaxDistance=20,this.panningDistanceLimit=null,this.panningOriginTarget=o.P.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=o.FM.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new o.y3,this.panningAxis=new o.P(1,1,0),this._transformedDirection=new o.P,this.mapPanning=!1,this.onMeshTargetChangedObservable=new r.y$,this.checkCollisions=!1,this.collisionRadius=new o.P(.5,.5,.5),this._previousPosition=o.P.Zero(),this._collisionVelocity=o.P.Zero(),this._newPosition=o.P.Zero(),this._computationVector=o.P.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),s=Math.sin(this.alpha),r=Math.cos(this.beta);let o=Math.sin(this.beta);0===o&&(o=1e-4);const a=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*n*o,this.radius*r,this.radius*s*o),a.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let l=this.upVector;this.allowUpsideDown&&this.beta<0&&(l=l.clone(),l=l.negate()),this._computeViewMatrix(this._position,a,l),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=o.P.Zero(),s&&this.setTarget(s),this.alpha=t,this.beta=i,this.radius=n,this.getViewMatrix(),this.inputs=new hn(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new o.P(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=o.FM.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!!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 s=arguments;t=se.w1.BackCompatCameraNoPreventDefault(s),this._useCtrlForPanning=i,this._panningMouseButton=n,"boolean"==typeof s[0]&&(s.length>1&&(this._useCtrlForPanning=s[1]),s.length>2&&(this._panningMouseButton=s[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){const e=this.invertRotation?-1:1;let t=this.inertialAlphaOffset;this.beta<=0&&(t*=-1),this.getScene().useRightHandedSystem&&(t*=-1),this.parent&&this.parent._getWorldMatrixDeterminant()<0&&(t*=-1),this.alpha+=t*e,this.beta+=this.inertialBetaOffset*e,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||o.P.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){var s;if(n=null!==(s=this.overrideCloneAlphaBetaRadius)&&void 0!==s?s:n,e.getBoundingInfo)this._targetBoundingCenter=t?e.getBoundingInfo().boundingBox.centerWorld.clone():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 s=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||o.P.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),s.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){const e=this.getScene().collisionCoordinator;this._collider||(this._collider=e.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,e.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let e=this.upVector;this.allowUpsideDown&&n<0&&(e=e.negate()),this._computeViewMatrix(this._position,s,e),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=s,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;const i=ee.Kj.MinMax(e),n=o.P.Distance(i.min,i.max);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=ee.Kj.MinMax(t),n=o.P.Distance(i.min,i.max)}else{i=e,n=e.distance}this._target=ee.Kj.Center(i),t||(this.maxZ=2*n)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case ce.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ce.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ce.V.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ce.V.RIG_MODE_STEREOSCOPIC_INTERLACED:case ce.V.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(0===t?1:-1);break;case ce.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(0===t?-1:1)}const n=new Ln(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 ce.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ce.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ce.V.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ce.V.RIG_MODE_STEREOSCOPIC_INTERLACED:case ce.V.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case ce.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}super._updateRigCameras()}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}(0,oe.gn)([(0,E.qC)()],Ln.prototype,"alpha",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"beta",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"radius",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"overrideCloneAlphaBetaRadius",void 0),(0,oe.gn)([(0,E.hd)("target")],Ln.prototype,"_target",void 0),(0,oe.gn)([(0,E.RR)("targetHost")],Ln.prototype,"_targetHost",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"inertialAlphaOffset",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"inertialBetaOffset",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"inertialRadiusOffset",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"lowerAlphaLimit",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"upperAlphaLimit",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"lowerBetaLimit",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"upperBetaLimit",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"lowerRadiusLimit",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"upperRadiusLimit",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"inertialPanningX",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"inertialPanningY",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"pinchToPanMaxDistance",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"panningDistanceLimit",void 0),(0,oe.gn)([(0,E.hd)()],Ln.prototype,"panningOriginTarget",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"panningInertia",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"zoomToMouseLocation",null),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"zoomOnFactor",void 0),(0,oe.gn)([(0,E.QC)()],Ln.prototype,"targetScreenOffset",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"allowUpsideDown",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"useInputToRestoreState",void 0),b.N.AddNodeConstructor("DeviceOrientationCamera",((e,t)=>()=>new Bn(e,o.P.Zero(),t)));class Bn extends Fn{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new o._f,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new o._f,this.inputs.addDeviceOrientation(),this.inputs._deviceOrientationInput&&this.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce((()=>{this._disablePointerInputWhenUsingDeviceOrientation&&this.inputs._mouseInput&&(this.inputs._mouseInput._allowCameraRotation=!1,this.inputs._mouseInput.onPointerMovedObservable.add((e=>{0!=this._dragFactor&&(this._initialQuaternion||(this._initialQuaternion=new o._f),o._f.FromEulerAnglesToRef(0,e.offsetX*this._dragFactor,0,this._tmpDragQuaternion),this._initialQuaternion.multiplyToRef(this._tmpDragQuaternion,this._initialQuaternion))})))}))}get disablePointerInputWhenUsingDeviceOrientation(){return this._disablePointerInputWhenUsingDeviceOrientation}set disablePointerInputWhenUsingDeviceOrientation(e){this._disablePointerInputWhenUsingDeviceOrientation=e}enableHorizontalDragging(e=1/300){this._dragFactor=e}getClassName(){return"DeviceOrientationCamera"}_checkInputs(){super._checkInputs(),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}resetToCurrentRotation(e=L.RD.Y){this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new o._f),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach((t=>{e[t]?this._initialQuaternion[t]*=-1:this._initialQuaternion[t]=0})),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))}}class Un extends en{constructor(e){super(e)}addKeyboard(){return this.add(new dn),this}addMouse(){return this.add(new un),this}}class Vn extends Nn{get angularSensibility(){const e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){const t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysForward(){const e=this.inputs.attached.keyboard;return e?e.keysForward:[]}set keysForward(e){const t=this.inputs.attached.keyboard;t&&(t.keysForward=e)}get keysBackward(){const e=this.inputs.attached.keyboard;return e?e.keysBackward:[]}set keysBackward(e){const t=this.inputs.attached.keyboard;t&&(t.keysBackward=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}constructor(e,t,i,n=!0){super(e,t,i,n),this.ellipsoid=new o.P(1,1,1),this.ellipsoidOffset=new o.P(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this.cameraDirection=o.P.Zero(),this._trackRoll=0,this.rollCorrect=100,this.bankedTurn=!1,this.bankedTurnLimit=Math.PI/2,this.bankedTurnMultiplier=1,this._needMoveForGravity=!1,this._oldPosition=o.P.Zero(),this._diffPosition=o.P.Zero(),this._newPosition=o.P.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(e,t,i=null)=>{(e=>{this._newPosition.copyFrom(e),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>fe.D.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&i&&this.onCollide(i))})(t)},this.inputs=new Un(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=se.w1.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new o.P(0,0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?o.P.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=o.P.Zero(),this._transformedDirection=o.P.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}restoreRoll(e){const t=this._trackRoll,i=t-this.rotation.z;Math.abs(i)>=.001&&(this.rotation.z+=i/e,Math.abs(t-this.rotation.z)<=.001&&(this.rotation.z=t))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FlyCamera"}}(0,oe.gn)([(0,E.hd)()],Vn.prototype,"ellipsoid",void 0),(0,oe.gn)([(0,E.hd)()],Vn.prototype,"ellipsoidOffset",void 0),(0,oe.gn)([(0,E.qC)()],Vn.prototype,"checkCollisions",void 0),(0,oe.gn)([(0,E.qC)()],Vn.prototype,"applyGravity",void 0);class kn extends en{constructor(e){super(e)}addKeyboard(){return this.add(new pn),this}addMouseWheel(){return this.add(new fn),this}addPointers(){return this.add(new _n),this}addVRDeviceOrientation(){return console.warn("DeviceOrientation support not yet implemented for FollowCamera."),this}}b.N.AddNodeConstructor("FollowCamera",((e,t)=>()=>new Gn(e,o.P.Zero(),t))),b.N.AddNodeConstructor("ArcFollowCamera",((e,t)=>()=>new zn(e,0,0,1,null,t)));class Gn extends Nn{constructor(e,t,i,n=null){super(e,t,i),this.radius=12,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.rotationOffset=0,this.lowerRotationOffsetLimit=null,this.upperRotationOffsetLimit=null,this.heightOffset=4,this.lowerHeightOffsetLimit=null,this.upperHeightOffsetLimit=null,this.cameraAcceleration=.05,this.maxCameraSpeed=20,this.lockedTarget=n,this.inputs=new kn(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_follow(e){if(!e)return;const t=o.jp.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);const i=Math.atan2(t.m[8],t.m[10]),n=se.w1.ToRadians(this.rotationOffset)+i,s=e.getAbsolutePosition(),r=s.x+Math.sin(n)*this.radius,a=s.z+Math.cos(n)*this.radius,l=r-this.position.x,h=s.y+this.heightOffset-this.position.y,c=a-this.position.z;let d=l*this.cameraAcceleration*2,u=h*this.cameraAcceleration,p=c*this.cameraAcceleration*2;(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),(u>this.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<1?-this.maxCameraSpeed:this.maxCameraSpeed),(p>this.maxCameraSpeed||p<-this.maxCameraSpeed)&&(p=p<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new o.P(this.position.x+d,this.position.y+u,this.position.z+p),this.setTarget(s)}attachControl(e,t){t=se.w1.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t),this._reset=()=>{}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){this.inputs.checkInputs(),this._checkLimits(),super._checkInputs(),this.lockedTarget&&this._follow(this.lockedTarget)}_checkLimits(){null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),null!==this.lowerHeightOffsetLimit&&this.heightOffsetthis.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),null!==this.lowerRotationOffsetLimit&&this.rotationOffsetthis.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)}getClassName(){return"FollowCamera"}}(0,oe.gn)([(0,E.qC)()],Gn.prototype,"radius",void 0),(0,oe.gn)([(0,E.qC)()],Gn.prototype,"lowerRadiusLimit",void 0),(0,oe.gn)([(0,E.qC)()],Gn.prototype,"upperRadiusLimit",void 0),(0,oe.gn)([(0,E.qC)()],Gn.prototype,"rotationOffset",void 0),(0,oe.gn)([(0,E.qC)()],Gn.prototype,"lowerRotationOffsetLimit",void 0),(0,oe.gn)([(0,E.qC)()],Gn.prototype,"upperRotationOffsetLimit",void 0),(0,oe.gn)([(0,E.qC)()],Gn.prototype,"heightOffset",void 0),(0,oe.gn)([(0,E.qC)()],Gn.prototype,"lowerHeightOffsetLimit",void 0),(0,oe.gn)([(0,E.qC)()],Gn.prototype,"upperHeightOffsetLimit",void 0),(0,oe.gn)([(0,E.qC)()],Gn.prototype,"cameraAcceleration",void 0),(0,oe.gn)([(0,E.qC)()],Gn.prototype,"maxCameraSpeed",void 0),(0,oe.gn)([(0,E.RR)("lockedTargetId")],Gn.prototype,"lockedTarget",void 0);class zn extends Nn{constructor(e,t,i,n,s,r){super(e,o.P.Zero(),r),this.alpha=t,this.beta=i,this.radius=n,this._cartesianCoordinates=o.P.Zero(),this.setMeshTarget(s)}setMeshTarget(e){this._meshTarget=e,this._follow()}_follow(){if(!this._meshTarget)return;this._cartesianCoordinates.x=this.radius*Math.cos(this.alpha)*Math.cos(this.beta),this._cartesianCoordinates.y=this.radius*Math.sin(this.beta),this._cartesianCoordinates.z=this.radius*Math.sin(this.alpha)*Math.cos(this.beta);const e=this._meshTarget.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}_checkInputs(){super._checkInputs(),this._follow()}getClassName(){return"ArcFollowCamera"}}!function(e){e[e.VIVE=0]="VIVE",e[e.OCULUS=1]="OCULUS",e[e.WINDOWS=2]="WINDOWS",e[e.GEAR_VR=3]="GEAR_VR",e[e.DAYDREAM=4]="DAYDREAM",e[e.GENERIC=5]="GENERIC"}(yn||(yn={}));class Wn{static InitiateController(e){for(const t of this._ControllerFactories)if(t.canCreate(e))return t.create(e);if(this._DefaultControllerFactory)return this._DefaultControllerFactory(e);throw"The type of gamepad you are trying to load needs to be imported first or is not supported."}}Wn._ControllerFactories=[],Wn._DefaultControllerFactory=null;class Hn extends tn{_disableTrackPosition(e){this._trackPosition&&(this._calculatedPosition.copyFrom(e),this._trackPosition=!1)}constructor(e){super(e.id,e.index,e),this.isXR=!1,this._deviceRoomPosition=o.P.Zero(),this._deviceRoomRotationQuaternion=new o._f,this.devicePosition=o.P.Zero(),this.deviceRotationQuaternion=new o._f,this.deviceScaleFactor=1,this._trackPosition=!0,this._maxRotationDistFromHeadset=Math.PI/5,this._draggedRoomRotation=0,this._leftHandSystemQuaternion=new o._f,this._deviceToWorld=o.y3.Identity(),this._pointingPoseNode=null,this._workingMatrix=o.y3.Identity(),this._meshAttachedObservable=new r.y$,this.type=tn.POSE_ENABLED,this.controllerType=yn.GENERIC,this.position=o.P.Zero(),this.rotationQuaternion=new o._f,this._calculatedPosition=o.P.Zero(),this._calculatedRotation=new o._f,o._f.RotationYawPitchRollToRef(Math.PI,0,0,this._leftHandSystemQuaternion)}update(){super.update(),this._updatePoseAndMesh()}_updatePoseAndMesh(){if(this.isXR)return;const e=this.browserGamepad.pose;if(this.updateFromDevice(e),!this._trackPosition&&m.l.LastCreatedScene&&m.l.LastCreatedScene.activeCamera&&m.l.LastCreatedScene.activeCamera.devicePosition){const e=m.l.LastCreatedScene.activeCamera;if(e._computeDevicePosition(),this._deviceToWorld.setTranslation(e.devicePosition),e.deviceRotationQuaternion){e._deviceRoomRotationQuaternion.toEulerAnglesToRef(o.jp.Vector3[0]);const t=Math.atan2(Math.sin(o.jp.Vector3[0].y-this._draggedRoomRotation),Math.cos(o.jp.Vector3[0].y-this._draggedRoomRotation));if(Math.abs(t)>this._maxRotationDistFromHeadset){const e=t-(t<0?-this._maxRotationDistFromHeadset:this._maxRotationDistFromHeadset);this._draggedRoomRotation+=e;const i=Math.sin(-e),n=Math.cos(-e);this._calculatedPosition.x=this._calculatedPosition.x*n-this._calculatedPosition.z*i,this._calculatedPosition.z=this._calculatedPosition.x*i+this._calculatedPosition.z*n}}}o.P.TransformCoordinatesToRef(this._calculatedPosition,this._deviceToWorld,this.devicePosition),this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix),o._f.FromRotationMatrixToRef(this._workingMatrix,this.deviceRotationQuaternion),this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation),this._mesh&&(this._mesh.position.copyFrom(this.devicePosition),this._mesh.rotationQuaternion&&this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion))}updateFromDevice(e){if(!this.isXR&&e){this.rawPose=e,e.position&&(this._deviceRoomPosition.copyFromFloats(e.position[0],e.position[1],-e.position[2]),this._mesh&&this._mesh.getScene().useRightHandedSystem&&(this._deviceRoomPosition.z*=-1),this._trackPosition&&this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor,this._calculatedPosition),this._calculatedPosition.addInPlace(this.position));const t=this.rawPose;e.orientation&&t.orientation&&4===t.orientation.length&&(this._deviceRoomRotationQuaternion.copyFromFloats(t.orientation[0],t.orientation[1],-t.orientation[2],-t.orientation[3]),this._mesh&&(this._mesh.getScene().useRightHandedSystem?(this._deviceRoomRotationQuaternion.z*=-1,this._deviceRoomRotationQuaternion.w*=-1):this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion,this._deviceRoomRotationQuaternion)),this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion,this._calculatedRotation))}}attachToMesh(e){if(this._mesh&&(this._mesh.parent=null),this._mesh=e,this._poseControlledCamera&&(this._mesh.parent=this._poseControlledCamera),this._mesh.rotationQuaternion||(this._mesh.rotationQuaternion=new o._f),!this.isXR&&(this._updatePoseAndMesh(),this._pointingPoseNode)){const e=[];let t=this._pointingPoseNode;for(;t.parent;)e.push(t.parent),t=t.parent;e.reverse().forEach((e=>{e.computeWorldMatrix(!0)}))}this._meshAttachedObservable.notifyObservers(e)}attachToPoseControlledCamera(e){this._poseControlledCamera=e,this._mesh&&(this._mesh.parent=this._poseControlledCamera)}dispose(){this._mesh&&this._mesh.dispose(),this._mesh=null,super.dispose()}get mesh(){return this._mesh}getForwardRay(e=100){if(!this.mesh)return new qe(o.P.Zero(),new o.P(0,0,1),e);const t=this._pointingPoseNode?this._pointingPoseNode.getWorldMatrix():this.mesh.getWorldMatrix(),i=t.getTranslation(),n=new o.P(0,0,-1),s=o.P.TransformNormal(n,t),r=o.P.Normalize(s);return new qe(i,r,e)}}Hn.POINTING_POSE="POINTING_POSE",function(e){e[e.A=0]="A",e[e.B=1]="B",e[e.X=2]="X",e[e.Y=3]="Y",e[e.LB=4]="LB",e[e.RB=5]="RB",e[e.Back=8]="Back",e[e.Start=9]="Start",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(An||(An={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(Rn||(Rn={}));class Xn extends tn{constructor(e,t,i,n=!1){super(e,t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new r.y$,this.onButtonUpObservable=new r.y$,this.onPadDownObservable=new r.y$,this.onPadUpObservable=new r.y$,this._buttonA=0,this._buttonB=0,this._buttonX=0,this._buttonY=0,this._buttonBack=0,this._buttonStart=0,this._buttonLB=0,this._buttonRB=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this._isXboxOnePad=!1,this.type=tn.XBOX,this._isXboxOnePad=n}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonA(){return this._buttonA}set buttonA(e){this._buttonA=this._setButtonValue(e,this._buttonA,An.A)}get buttonB(){return this._buttonB}set buttonB(e){this._buttonB=this._setButtonValue(e,this._buttonB,An.B)}get buttonX(){return this._buttonX}set buttonX(e){this._buttonX=this._setButtonValue(e,this._buttonX,An.X)}get buttonY(){return this._buttonY}set buttonY(e){this._buttonY=this._setButtonValue(e,this._buttonY,An.Y)}get buttonStart(){return this._buttonStart}set buttonStart(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,An.Start)}get buttonBack(){return this._buttonBack}set buttonBack(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,An.Back)}get buttonLB(){return this._buttonLB}set buttonLB(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,An.LB)}get buttonRB(){return this._buttonRB}set buttonRB(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,An.RB)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,An.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,An.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Rn.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Rn.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Rn.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Rn.Right)}update(){super.update(),this._isXboxOnePad,this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonBack=this.browserGamepad.buttons[8].value,this.buttonStart=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}!function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.Share=8]="Share",e[e.Options=9]="Options",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(Pn||(Pn={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(In||(In={}));class Yn extends tn{constructor(e,t,i){super(e.replace("STANDARD GAMEPAD","SONY PLAYSTATION DUALSHOCK"),t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new r.y$,this.onButtonUpObservable=new r.y$,this.onPadDownObservable=new r.y$,this.onPadUpObservable=new r.y$,this._buttonCross=0,this._buttonCircle=0,this._buttonSquare=0,this._buttonTriangle=0,this._buttonShare=0,this._buttonOptions=0,this._buttonL1=0,this._buttonR1=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this.type=tn.DUALSHOCK}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonCross(){return this._buttonCross}set buttonCross(e){this._buttonCross=this._setButtonValue(e,this._buttonCross,Pn.Cross)}get buttonCircle(){return this._buttonCircle}set buttonCircle(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,Pn.Circle)}get buttonSquare(){return this._buttonSquare}set buttonSquare(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,Pn.Square)}get buttonTriangle(){return this._buttonTriangle}set buttonTriangle(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,Pn.Triangle)}get buttonOptions(){return this._buttonOptions}set buttonOptions(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,Pn.Options)}get buttonShare(){return this._buttonShare}set buttonShare(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,Pn.Share)}get buttonL1(){return this._buttonL1}set buttonL1(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,Pn.L1)}get buttonR1(){return this._buttonR1}set buttonR1(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,Pn.R1)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,Pn.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,Pn.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,In.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,In.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,In.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,In.Right)}update(){super.update(),this.buttonCross=this.browserGamepad.buttons[0].value,this.buttonCircle=this.browserGamepad.buttons[1].value,this.buttonSquare=this.browserGamepad.buttons[2].value,this.buttonTriangle=this.browserGamepad.buttons[3].value,this.buttonL1=this.browserGamepad.buttons[4].value,this.buttonR1=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonShare=this.browserGamepad.buttons[8].value,this.buttonOptions=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}class jn{constructor(e){if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new r.y$,(0,_e.CG)()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new r.y$((e=>{for(const t in this._babylonGamepads){const i=this._babylonGamepads[t];i&&i._isConnected&&this.onGamepadConnectedObservable.notifyObserver(e,i)}})),this._onGamepadConnectedEvent=e=>{const t=e.gamepad;if(t.index in this._babylonGamepads&&this._babylonGamepads[t.index].isConnected)return;let i;this._babylonGamepads[t.index]?(i=this._babylonGamepads[t.index],i.browserGamepad=t,i._isConnected=!0):i=this._addNewGamepad(t),this.onGamepadConnectedObservable.notifyObservers(i),this._startMonitoringGamepads()},this._onGamepadDisconnectedEvent=e=>{const t=e.gamepad;for(const i in this._babylonGamepads)if(this._babylonGamepads[i].index===t.index){const e=this._babylonGamepads[i];e._isConnected=!1,this.onGamepadDisconnectedObservable.notifyObservers(e),e.dispose&&e.dispose();break}},this._gamepadSupport)if(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported){const e=this._scene?this._scene.getEngine().getHostWindow():window;e&&(e.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),e.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1))}else this._startMonitoringGamepads()}get gamepads(){return this._babylonGamepads}getGamepadByType(e=tn.XBOX){for(const t of this._babylonGamepads)if(t&&t.type===e)return t;return null}dispose(){this._gamepadEventSupported&&(this._onGamepadConnectedEvent&&window.removeEventListener("gamepadconnected",this._onGamepadConnectedEvent),this._onGamepadDisconnectedEvent&&window.removeEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent),this._onGamepadConnectedEvent=null,this._onGamepadDisconnectedEvent=null),this._babylonGamepads.forEach((e=>{e.dispose()})),this.onGamepadConnectedObservable.clear(),this.onGamepadDisconnectedObservable.clear(),this._oneGamepadConnected=!1,this._stopMonitoringGamepads(),this._babylonGamepads=[]}_addNewGamepad(e){let t;this._oneGamepadConnected||(this._oneGamepadConnected=!0);const i=-1!==e.id.search("054c")&&-1===e.id.search("0ce6"),n=-1!==e.id.search("Xbox One");return t=n||-1!==e.id.search("Xbox 360")||-1!==e.id.search("xinput")||-1!==e.id.search("045e")&&-1===e.id.search("Surface Dock")?new Xn(e.id,e.index,e,n):i?new Yn(e.id,e.index,e):e.pose?Wn.InitiateController(e):new nn(e.id,e.index,e),this._babylonGamepads[t.index]=t,t}_startMonitoringGamepads(){this._isMonitoring||(this._isMonitoring=!0,this._checkGamepadsStatus())}_stopMonitoringGamepads(){this._isMonitoring=!1}_checkGamepadsStatus(){this._updateGamepadObjects();for(const t in this._babylonGamepads){const i=this._babylonGamepads[t];if(i&&i.isConnected)try{i.update()}catch(e){-1===this._loggedErrors.indexOf(i.index)&&(se.w1.Warn(`Error updating gamepad ${i.id}`),this._loggedErrors.push(i.index))}}this._isMonitoring&&fe.D.QueueNewFrame((()=>{this._checkGamepadsStatus()}))}_updateGamepadObjects(){const e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t()=>new qn(e,o.P.Zero(),t)));class qn extends wn{get gamepadAngularSensibility(){const e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0}set gamepadAngularSensibility(e){const t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)}get gamepadMoveSensibility(){const e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0}set gamepadMoveSensibility(e){const t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addGamepad()}getClassName(){return"UniversalCamera"}}ce.V._CreateDefaultParsedCamera=(e,t)=>new qn(e,o.P.Zero(),t),b.N.AddNodeConstructor("GamepadCamera",((e,t)=>()=>new $n(e,o.P.Zero(),t)));class $n extends qn{constructor(e,t,i){super(e,t,i)}getClassName(){return"GamepadCamera"}}const Qn="passCubePixelShader",Zn="varying vec2 vUV;\nuniform samplerCube textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\nvec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x));\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x));\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x));\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x));\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001));\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001));\n#endif\n}";Ht.v.ShadersStore[Qn]=Zn;class Jn extends Zt{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,n,s,r,o=0,a=!1){super(e,"pass",null,null,t,i,n,s,r,void 0,o,void 0,null,a)}static _Parse(e,t,i,n){return E.p4.Parse((()=>new Jn(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable)),e,i,n)}}(0,l.H)("BABYLON.PassPostProcess",Jn);fe.D._RescalePostProcessFactory=e=>new Jn("rescale",1,null,2,e,!1,0);const es="anaglyphPixelShader",ts="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}";Ht.v.ShadersStore[es]=ts;class is extends Zt{getClassName(){return"AnaglyphPostProcess"}constructor(e,t,i,n,s,r){super(e,"anaglyph",null,["leftSampler"],t,i[1],n,s,r),this._passedProcess=i[0]._rigPostProcess,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("leftSampler",this._passedProcess)}))}}function ns(e){e._rigCameras[0]._rigPostProcess=new Jn(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new is(e.name+"_anaglyph",1,e._rigCameras)}(0,l.H)("BABYLON.AnaglyphPostProcess",is),b.N.AddNodeConstructor("AnaglyphArcRotateCamera",((e,t,i)=>()=>new ss(e,0,0,1,o.P.Zero(),i.interaxial_distance,t)));class ss extends Ln{constructor(e,t,i,n,s,r,o){super(e,t,i,n,s,o),this._setRigMode=ns.bind(null,this),this.interaxialDistance=r,this.setCameraRigMode(ce.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:r})}getClassName(){return"AnaglyphArcRotateCamera"}}b.N.AddNodeConstructor("AnaglyphFreeCamera",((e,t,i)=>()=>new rs(e,o.P.Zero(),i.interaxial_distance,t)));class rs extends Fn{constructor(e,t,i,n){super(e,t,n),this._setRigMode=ns.bind(null,this),this.interaxialDistance=i,this.setCameraRigMode(ce.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphFreeCamera"}}b.N.AddNodeConstructor("AnaglyphGamepadCamera",((e,t,i)=>()=>new os(e,o.P.Zero(),i.interaxial_distance,t)));class os extends $n{constructor(e,t,i,n){super(e,t,n),this._setRigMode=ns.bind(null,this),this.interaxialDistance=i,this.setCameraRigMode(ce.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphGamepadCamera"}}b.N.AddNodeConstructor("AnaglyphUniversalCamera",((e,t,i)=>()=>new as(e,o.P.Zero(),i.interaxial_distance,t)));class as extends qn{constructor(e,t,i,n){super(e,t,n),this._setRigMode=ns.bind(null,this),this.interaxialDistance=i,this.setCameraRigMode(ce.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphUniversalCamera"}}const ls="stereoscopicInterlacePixelShader",hs="const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nbool useCamA;\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\nuseCamA=!useCamB;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\n#ifdef IS_STEREOSCOPIC_INTERLACED\nfloat rowNum=floor(vUV.y/stepSize.y);\nuseCamA=mod(rowNum,2.0)==1.0;\nuseCamB=mod(rowNum,2.0)==0.0;\ntexCoord1=vec2(vUV.x,vUV.y);\ntexCoord2=vec2(vUV.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\nuseCamA=!useCamB;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n#endif\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else if (useCamA){\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}else {\ndiscard;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}\n";Ht.v.ShadersStore[ls]=hs;class cs extends Zt{getClassName(){return"StereoscopicInterlacePostProcessI"}constructor(e,t,i,n,s,r,a){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],s,r,a,n?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new o.FM(1/this.width,1/this.height),this.onSizeChangedObservable.add((()=>{this._stepSize=new o.FM(1/this.width,1/this.height)})),this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("camASampler",this._passedProcess),e.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)}))}}function ds(e){const t=e.cameraRigMode===ce.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||e.cameraRigMode===ce.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,i=e.cameraRigMode===ce.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;e.cameraRigMode===ce.V.RIG_MODE_STEREOSCOPIC_INTERLACED?(e._rigCameras[0]._rigPostProcess=new Jn(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new cs(e.name+"_stereoInterlace",e._rigCameras,!1,!0)):(e._rigCameras[i?1:0].viewport=new Nt.l(0,0,t?.5:1,t?1:.5),e._rigCameras[i?0:1].viewport=new Nt.l(t?.5:0,t?0:.5,t?.5:1,t?1:.5))}b.N.AddNodeConstructor("StereoscopicArcRotateCamera",((e,t,i)=>()=>new us(e,0,0,1,o.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class us extends Ln{constructor(e,t,i,n,s,r,o,a){super(e,t,i,n,s,a),this._setRigMode=ds.bind(null,this),this.interaxialDistance=r,this.isStereoscopicSideBySide=o,this.setCameraRigMode(o?ce.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:ce.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:r})}getClassName(){return"StereoscopicArcRotateCamera"}}b.N.AddNodeConstructor("StereoscopicFreeCamera",((e,t,i)=>()=>new ps(e,o.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class ps extends Fn{constructor(e,t,i,n,s){super(e,t,s),this._setRigMode=ds.bind(null,this),this.interaxialDistance=i,this.isStereoscopicSideBySide=n,this.setCameraRigMode(n?ce.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:ce.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicFreeCamera"}}b.N.AddNodeConstructor("StereoscopicGamepadCamera",((e,t,i)=>()=>new fs(e,o.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class fs extends $n{constructor(e,t,i,n,s){super(e,t,s),this._setRigMode=ds.bind(null,this),this.interaxialDistance=i,this.isStereoscopicSideBySide=n,this.setCameraRigMode(n?ce.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:ce.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicGamepadCamera"}}b.N.AddNodeConstructor("StereoscopicFreeCamera",((e,t,i)=>()=>new _s(e,o.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class _s extends qn{constructor(e,t,i,n,s){super(e,t,s),this._setRigMode=ds.bind(null,this),this.interaxialDistance=i,this.isStereoscopicSideBySide=n,this.setCameraRigMode(n?ce.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:ce.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicUniversalCamera"}}b.N.AddNodeConstructor("VirtualJoysticksCamera",((e,t)=>()=>new ms(e,o.P.Zero(),t)));class ms extends Fn{constructor(e,t,i){super(e,t,i),this.inputs.addVirtualJoystick()}getClassName(){return"VirtualJoysticksCamera"}}class gs{constructor(){this.compensateDistortion=!0,this.multiviewEnabled=!1}get aspectRatio(){return this.hResolution/(2*this.vResolution)}get aspectRatioFov(){return 2*Math.atan(this.postProcessScaleFactor*this.vScreenSize/(2*this.eyeToScreenDistance))}get leftHMatrix(){const e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return o.y3.Translation(e,0,0)}get rightHMatrix(){const e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return o.y3.Translation(-e,0,0)}get leftPreViewMatrix(){return o.y3.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return o.y3.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){const e=new gs;return e.hResolution=1280,e.vResolution=800,e.hScreenSize=.149759993,e.vScreenSize=.0935999975,e.vScreenCenter=.0467999987,e.eyeToScreenDistance=.0410000011,e.lensSeparationDistance=.063500002,e.interpupillaryDistance=.064000003,e.distortionK=[1,.219999999,.239999995,0],e.chromaAbCorrection=[.995999992,-.00400000019,1.01400006,0],e.postProcessScaleFactor=1.714605507808412,e.lensCenterOffset=.151976421,e}}const vs="vrDistortionCorrectionPixelShader",Ts="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}";Ht.v.ShadersStore[vs]=Ts;class Ss extends Zt{getClassName(){return"VRDistortionCorrectionPostProcess"}constructor(e,t,i,n){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,n.postProcessScaleFactor,t,Le.BILINEAR_SAMPLINGMODE),this._isRightEye=i,this._distortionFactors=n.distortionK,this._postProcessScaleFactor=n.postProcessScaleFactor,this._lensCenterOffset=n.lensCenterOffset,this.adaptScaleToCurrentViewport=!0,this.onSizeChangedObservable.add((()=>{this._scaleIn=new o.FM(2,2/this.aspectRatio),this._scaleFactor=new o.FM(1/this._postProcessScaleFactor*.5,1/this._postProcessScaleFactor*.5*this.aspectRatio),this._lensCenter=new o.FM(this._isRightEye?.5-.5*this._lensCenterOffset:.5+.5*this._lensCenterOffset,.5)})),this.onApplyObservable.add((e=>{e.setFloat2("LensCenter",this._lensCenter.x,this._lensCenter.y),e.setFloat2("Scale",this._scaleFactor.x,this._scaleFactor.y),e.setFloat2("ScaleIn",this._scaleIn.x,this._scaleIn.y),e.setFloat4("HmdWarpParam",this._distortionFactors[0],this._distortionFactors[1],this._distortionFactors[2],this._distortionFactors[3])}))}}const Es="vrMultiviewToSingleviewPixelShader",xs="precision mediump sampler2DArray;\nvarying vec2 vUV;\nuniform sampler2DArray multiviewSampler;\nuniform int imageIndex;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\ngl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));\n}";Ht.v.ShadersStore[Es]=xs;class bs extends Ci{set samples(e){this._samples=e}get samples(){return this._samples}constructor(e,t=512){super("multiview rtt",t,e,!1,!0,0,!1,void 0,!1,!1,!0,void 0,!0),this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight()),this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,this.samples=this._getEngine().getCaps().maxSamples||this.samples,this._texture.samples=this._samples}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindMultiviewFramebuffer(this._renderTarget)}getViewCount(){return 2}}function Cs(e,t){const i=new ae.M(e,void 0,!0,t);return i.addUniform("viewProjection",16),i.addUniform("viewProjectionR",16),i.addUniform("view",16),i.addUniform("projection",16),i.addUniform("vEyePosition",4),i}fe.D.prototype.createMultiviewRenderTargetTexture=function(e,t,i,n){const s=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";const r=this._createHardwareRenderTargetWrapper(!1,!1,{width:e,height:t});r._framebuffer=s.createFramebuffer();const o=new Be.l(this,Be.S.Unknown,!0);return o.width=e,o.height=t,o.isMultiview=!0,i||(i=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,i),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.RGBA8,e,t,2)),r._colorTextureArray=i,n||(n=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,n),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.DEPTH24_STENCIL8,e,t,2)),r._depthStencilTextureArray=n,o.isReady=!0,r.setTextures(o),r._depthStencilTexture=o,r},fe.D.prototype.bindMultiviewFramebuffer=function(e){const t=e,i=this._gl,n=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(t,void 0,void 0,void 0,!0),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),!t._colorTextureArray||!t._depthStencilTextureArray)throw"Invalid multiview frame buffer";this.getCaps().oculusMultiview?(n.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,t.samples,0,2),n.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,t._depthStencilTextureArray,0,t.samples,0,2)):(n.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,0,2),n.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,t._depthStencilTextureArray,0,0,2))},fe.D.prototype.bindSpaceWarpFramebuffer=function(e){const t=e,i=this._gl,n=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(t,void 0,void 0,void 0,!0),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),!t._colorTextureArray||!t._depthStencilTextureArray)throw new Error("Invalid Space Warp framebuffer");n.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,0,2),n.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_ATTACHMENT,t._depthStencilTextureArray,0,0,2)},ce.V.prototype._useMultiviewToSingleView=!1,ce.V.prototype._multiviewTexture=null,ce.V.prototype._resizeOrCreateMultiviewTexture=function(e,t){this._multiviewTexture?this._multiviewTexture.getRenderWidth()==e&&this._multiviewTexture.getRenderHeight()==t||(this._multiviewTexture.dispose(),this._multiviewTexture=new bs(this.getScene(),{width:e,height:t})):this._multiviewTexture=new bs(this.getScene(),{width:e,height:t})};const ys=N.x.prototype.createSceneUniformBuffer;N.x.prototype._transformMatrixR=o.y3.Zero(),N.x.prototype._multiviewSceneUbo=null,N.x.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=Cs(this.getEngine(),"scene_multiview")},N.x.prototype.createSceneUniformBuffer=function(e){return this._multiviewSceneUbo?Cs(this.getEngine(),e):ys.bind(this)(e)},N.x.prototype._updateMultiviewUbo=function(e,t){e&&t&&e.multiplyToRef(t,this._transformMatrixR),e&&t&&(e.multiplyToRef(t,o.jp.Matrix[0]),Ot.i.GetRightPlaneToRef(o.jp.Matrix[0],this._frustumPlanes[3])),this._multiviewSceneUbo&&(this._multiviewSceneUbo.updateMatrix("viewProjection",this.getTransformMatrix()),this._multiviewSceneUbo.updateMatrix("viewProjectionR",this._transformMatrixR),this._multiviewSceneUbo.updateMatrix("view",this._viewMatrix),this._multiviewSceneUbo.updateMatrix("projection",this._projectionMatrix))},N.x.prototype._renderMultiviewToSingleView=function(e){e._resizeOrCreateMultiviewTexture(e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.width>0?e._rigPostProcess.width:this.getEngine().getRenderWidth(!0),e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.height>0?e._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),e.outputRenderTarget=e._multiviewTexture,this._renderForCamera(e),e.outputRenderTarget=null;for(let t=0;t{})),this.onApplyObservable.add((e=>{n._scene.activeCamera&&n._scene.activeCamera.isLeftCamera?e.setInt("imageIndex",0):e.setInt("imageIndex",1),e.setTexture("multiviewSampler",n._multiviewTexture)}))}}function Rs(e,t){const i=t.vrCameraMetrics||gs.GetDefault();e._rigCameras[0]._cameraRigParams.vrMetrics=i,e._rigCameras[0].viewport=new Nt.l(0,0,.5,1),e._rigCameras[0]._cameraRigParams.vrWorkMatrix=new o.y3,e._rigCameras[0]._cameraRigParams.vrHMatrix=i.leftHMatrix,e._rigCameras[0]._cameraRigParams.vrPreViewMatrix=i.leftPreViewMatrix,e._rigCameras[0].getProjectionMatrix=e._rigCameras[0]._getVRProjectionMatrix,e._rigCameras[1]._cameraRigParams.vrMetrics=i,e._rigCameras[1].viewport=new Nt.l(.5,0,.5,1),e._rigCameras[1]._cameraRigParams.vrWorkMatrix=new o.y3,e._rigCameras[1]._cameraRigParams.vrHMatrix=i.rightHMatrix,e._rigCameras[1]._cameraRigParams.vrPreViewMatrix=i.rightPreViewMatrix,e._rigCameras[1].getProjectionMatrix=e._rigCameras[1]._getVRProjectionMatrix,i.multiviewEnabled&&(e.getScene().getEngine().getCaps().multiview?(e._useMultiviewToSingleView=!0,e._rigPostProcess=new As("VRMultiviewToSingleview",e,i.postProcessScaleFactor)):(p.Y.Warn("Multiview is not supported, falling back to standard rendering"),i.multiviewEnabled=!1)),i.compensateDistortion&&(e._rigCameras[0]._rigPostProcess=new Ss("VR_Distort_Compensation_Left",e._rigCameras[0],!1,i),e._rigCameras[1]._rigPostProcess=new Ss("VR_Distort_Compensation_Right",e._rigCameras[1],!0,i))}b.N.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",((e,t)=>()=>new Ps(e,0,0,1,o.P.Zero(),t)));class Ps extends Ln{constructor(e,t,i,n,s,r,o=!0,a=gs.GetDefault()){super(e,t,i,n,s,r),this._setRigMode=Rs.bind(null,this),a.compensateDistortion=o,this.setCameraRigMode(ce.V.RIG_MODE_VR,{vrCameraMetrics:a}),this.inputs.addVRDeviceOrientation()}getClassName(){return"VRDeviceOrientationArcRotateCamera"}}b.N.AddNodeConstructor("VRDeviceOrientationFreeCamera",((e,t)=>()=>new Is(e,o.P.Zero(),t)));class Is extends Bn{constructor(e,t,i,n=!0,s=gs.GetDefault()){super(e,t,i),this._setRigMode=Rs.bind(null,this),s.compensateDistortion=n,this.setCameraRigMode(ce.V.RIG_MODE_VR,{vrCameraMetrics:s})}getClassName(){return"VRDeviceOrientationFreeCamera"}}b.N.AddNodeConstructor("VRDeviceOrientationGamepadCamera",((e,t)=>()=>new Ms(e,o.P.Zero(),t)));class Ms extends Is{constructor(e,t,i,n=!0,s=gs.GetDefault()){super(e,t,i,n,s),this._setRigMode=Rs.bind(null,this),this.inputs.addGamepad()}getClassName(){return"VRDeviceOrientationGamepadCamera"}}b.N.AddNodeConstructor("Light_Type_3",((e,t)=>()=>new Os(e,o.P.Zero(),t)));class Os extends he{constructor(e,t,i){super(e,i),this.groundColor=new a.Wo(0,0,0),this.direction=t||o.P.Up()}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightGround",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}getClassName(){return"HemisphericLight"}setDirectionToTarget(e){return this.direction=o.P.Normalize(e.subtract(o.P.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=o.P.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",i.x,i.y,i.z,0,t),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),t),this}transferToNodeMaterialEffect(e,t){const i=o.P.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=o.y3.Identity()),this._worldMatrix}getTypeID(){return he.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}function Ds(e,t){if(t.vrDisplay){const i=t.vrDisplay.getEyeParameters("left"),n=t.vrDisplay.getEyeParameters("right");e._rigCameras[0].viewport=new Nt.l(0,0,.5,1),e._rigCameras[0].setCameraRigParameter("left",!0),e._rigCameras[0].setCameraRigParameter("specs",t.specs),e._rigCameras[0].setCameraRigParameter("eyeParameters",i),e._rigCameras[0].setCameraRigParameter("frameData",t.frameData),e._rigCameras[0].setCameraRigParameter("parentCamera",t.parentCamera),e._rigCameras[0]._cameraRigParams.vrWorkMatrix=new o.y3,e._rigCameras[0].getProjectionMatrix=e._getWebVRProjectionMatrix,e._rigCameras[0].parent=e,e._rigCameras[0]._getViewMatrix=e._getWebVRViewMatrix,e._rigCameras[1].viewport=new Nt.l(.5,0,.5,1),e._rigCameras[1].setCameraRigParameter("eyeParameters",n),e._rigCameras[1].setCameraRigParameter("specs",t.specs),e._rigCameras[1].setCameraRigParameter("frameData",t.frameData),e._rigCameras[1].setCameraRigParameter("parentCamera",t.parentCamera),e._rigCameras[1]._cameraRigParams.vrWorkMatrix=new o.y3,e._rigCameras[1].getProjectionMatrix=e._getWebVRProjectionMatrix,e._rigCameras[1].parent=e,e._rigCameras[1]._getViewMatrix=e._getWebVRViewMatrix}}(0,oe.gn)([(0,E.n9)()],Os.prototype,"groundColor",void 0),(0,oe.gn)([(0,E.hd)()],Os.prototype,"direction",void 0),Object.defineProperty(fe.D.prototype,"isInVRExclusivePointerMode",{get:function(){return this._vrExclusivePointerMode},enumerable:!0,configurable:!0}),fe.D.prototype._prepareVRComponent=function(){this._vrSupported=!1,this._vrExclusivePointerMode=!1,this.onVRDisplayChangedObservable=new r.y$,this.onVRRequestPresentComplete=new r.y$,this.onVRRequestPresentStart=new r.y$},fe.D.prototype.isVRDevicePresent=function(){return!!this._vrDisplay},fe.D.prototype.getVRDevice=function(){return this._vrDisplay},fe.D.prototype.initWebVR=function(){return this.initWebVRAsync(),this.onVRDisplayChangedObservable},fe.D.prototype.initWebVRAsync=function(){const e=()=>{const e={vrDisplay:this._vrDisplay,vrSupported:this._vrSupported};this.onVRDisplayChangedObservable.notifyObservers(e),this._webVRInitPromise=new Promise((t=>{t(e)}))};if(!this._onVrDisplayConnect){this._onVrDisplayConnect=t=>{this._vrDisplay=t.display,e()},this._onVrDisplayDisconnect=()=>{this._vrDisplay.cancelAnimationFrame(this._frameHandler),this._vrDisplay=void 0,this._frameHandler=fe.D.QueueNewFrame(this._boundRenderFunction),e()},this._onVrDisplayPresentChange=()=>{this._vrExclusivePointerMode=this._vrDisplay&&this._vrDisplay.isPresenting};const t=this.getHostWindow();t&&(t.addEventListener("vrdisplayconnect",this._onVrDisplayConnect),t.addEventListener("vrdisplaydisconnect",this._onVrDisplayDisconnect),t.addEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange))}return this._webVRInitPromise=this._webVRInitPromise||this._getVRDisplaysAsync(),this._webVRInitPromise.then(e),this._webVRInitPromise},fe.D.prototype._getVRDisplaysAsync=function(){return new Promise((e=>{navigator.getVRDisplays?navigator.getVRDisplays().then((t=>{this._vrSupported=!0,this._vrDisplay=t[0],e({vrDisplay:this._vrDisplay,vrSupported:this._vrSupported})})):(this._vrDisplay=void 0,this._vrSupported=!1,e({vrDisplay:this._vrDisplay,vrSupported:this._vrSupported}))}))},fe.D.prototype.enableVR=function(e){if(this._vrDisplay&&!this._vrDisplay.isPresenting){const t=()=>{this.onVRRequestPresentComplete.notifyObservers(!0),this._onVRFullScreenTriggered()},i=()=>{this.onVRRequestPresentComplete.notifyObservers(!1)};this.onVRRequestPresentStart.notifyObservers(this);const n={highRefreshRate:!!this.vrPresentationAttributes&&this.vrPresentationAttributes.highRefreshRate,foveationLevel:this.vrPresentationAttributes?this.vrPresentationAttributes.foveationLevel:1,multiview:(this.getCaps().multiview||this.getCaps().oculusMultiview)&&e.useMultiview};this._vrDisplay.requestPresent([Object.assign({source:this.getRenderingCanvas(),attributes:n},n)]).then(t).catch(i)}},fe.D.prototype._onVRFullScreenTriggered=function(){if(this._vrDisplay&&this._vrDisplay.isPresenting){this._oldSize=new C(this.getRenderWidth(),this.getRenderHeight()),this._oldHardwareScaleFactor=this.getHardwareScalingLevel();const e=this._vrDisplay.getEyeParameters("left");this.setHardwareScalingLevel(1),this.setSize(2*e.renderWidth,e.renderHeight)}else this.setHardwareScalingLevel(this._oldHardwareScaleFactor),this.setSize(this._oldSize.width,this._oldSize.height)},fe.D.prototype.disableVR=function(){this._vrDisplay&&this._vrDisplay.isPresenting&&this._vrDisplay.exitPresent().then((()=>this._onVRFullScreenTriggered())).catch((()=>this._onVRFullScreenTriggered())),(0,_e.CG)()&&(window.removeEventListener("vrdisplaypointerrestricted",this._onVRDisplayPointerRestricted),window.removeEventListener("vrdisplaypointerunrestricted",this._onVRDisplayPointerUnrestricted),this._onVrDisplayConnect&&(window.removeEventListener("vrdisplayconnect",this._onVrDisplayConnect),this._onVrDisplayDisconnect&&window.removeEventListener("vrdisplaydisconnect",this._onVrDisplayDisconnect),this._onVrDisplayPresentChange&&window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange),this._onVrDisplayConnect=null,this._onVrDisplayDisconnect=null))},fe.D.prototype._connectVREvents=function(e,t){if(this._onVRDisplayPointerRestricted=()=>{e&&e.requestPointerLock()},this._onVRDisplayPointerUnrestricted=()=>{if(t)t.exitPointerLock&&t.exitPointerLock();else{const e=this.getHostWindow();e.document&&e.document.exitPointerLock&&e.document.exitPointerLock()}},(0,_e.CG)()){const e=this.getHostWindow();e.addEventListener("vrdisplaypointerrestricted",this._onVRDisplayPointerRestricted,!1),e.addEventListener("vrdisplaypointerunrestricted",this._onVRDisplayPointerUnrestricted,!1)}},fe.D.prototype._submitVRFrame=function(){if(this._vrDisplay&&this._vrDisplay.isPresenting)try{this._vrDisplay.submitFrame()}catch(e){se.w1.Warn("webVR submitFrame has had an unexpected failure: "+e)}},fe.D.prototype.isVRPresenting=function(){return this._vrDisplay&&this._vrDisplay.isPresenting},fe.D.prototype._requestVRFrame=function(){this._frameHandler=fe.D.QueueNewFrame(this._boundRenderFunction,this._vrDisplay)},b.N.AddNodeConstructor("WebVRFreeCamera",((e,t)=>()=>new Ns(e,o.P.Zero(),t))),b.N.AddNodeConstructor("WebVRGamepadCamera",((e,t)=>()=>new Ns(e,o.P.Zero(),t)));class Ns extends Fn{constructor(e,t,i,n={}){super(e,t,i),this._webVROptions=n,this._vrDevice=null,this.rawPose=null,this._specsVersion="1.1",this._attached=!1,this._descendants=[],this._deviceRoomPosition=o.P.Zero(),this._deviceRoomRotationQuaternion=o._f.Identity(),this._standingMatrix=null,this.devicePosition=o.P.Zero(),this.deviceRotationQuaternion=o._f.Identity(),this.deviceScaleFactor=1,this._deviceToWorld=o.y3.Identity(),this._worldToDevice=o.y3.Identity(),this.controllers=[],this.onControllersAttachedObservable=new r.y$,this.onControllerMeshLoadedObservable=new r.y$,this.onPoseUpdatedFromDeviceObservable=new r.y$,this._poseSet=!1,this.rigParenting=!0,this._defaultHeight=void 0,this._setRigMode=Ds.bind(null,this),this._detachIfAttached=()=>{const e=this.getEngine().getVRDevice();e&&!e.isPresenting&&this.detachControl()},this._workingVector=o.P.Zero(),this._oneVector=o.P.One(),this._workingMatrix=o.y3.Identity(),this._tmpMatrix=new o.y3,this._cache.position=o.P.Zero(),n.defaultHeight&&(this._defaultHeight=n.defaultHeight,this.position.y=this._defaultHeight),this.minZ=.1,5===arguments.length&&(this._webVROptions=arguments[4]),null==this._webVROptions.trackPosition&&(this._webVROptions.trackPosition=!0),null==this._webVROptions.controllerMeshes&&(this._webVROptions.controllerMeshes=!0),null==this._webVROptions.defaultLightingOnControllers&&(this._webVROptions.defaultLightingOnControllers=!0),this.rotationQuaternion=new o._f,this._webVROptions&&this._webVROptions.positionScale&&(this.deviceScaleFactor=this._webVROptions.positionScale);const s=this.getEngine();this._onVREnabled=e=>{e&&this.initControllers()},s.onVRRequestPresentComplete.add(this._onVREnabled),s.initWebVR().add((e=>{e.vrDisplay&&this._vrDevice!==e.vrDisplay&&(this._vrDevice=e.vrDisplay,this.setCameraRigMode(ce.V.RIG_MODE_WEBVR,{parentCamera:this,vrDisplay:this._vrDevice,frameData:this._frameData,specs:this._specsVersion}),this._attached&&this.getEngine().enableVR(this._webVROptions))})),"undefined"!=typeof VRFrameData&&(this._frameData=new VRFrameData),n.useMultiview&&(this.getScene().getEngine().getCaps().multiview?(this._useMultiviewToSingleView=!0,this._rigPostProcess=new As("VRMultiviewToSingleview",this,1)):(p.Y.Warn("Multiview is not supported, falling back to standard rendering"),this._useMultiviewToSingleView=!1)),this.getScene().onBeforeCameraRenderObservable.add((e=>{e.parent===this&&this.rigParenting&&(this._descendants=this.getDescendants(!0,(e=>{const t=this.controllers.some((t=>t._mesh===e)),i=-1!==this._rigCameras.indexOf(e);return!t&&!i})),this._descendants.forEach((t=>{t.parent=e})))})),this.getScene().onAfterCameraRenderObservable.add((e=>{e.parent===this&&this.rigParenting&&this._descendants.forEach((e=>{e.parent=this}))}))}deviceDistanceToRoomGround(){return this._standingMatrix?(this._standingMatrix.getTranslationToRef(this._workingVector),this._deviceRoomPosition.y+this._workingVector.y):this._defaultHeight||0}useStandingMatrix(e=(e=>{})){this.getEngine().initWebVRAsync().then((t=>{t.vrDisplay&&t.vrDisplay.stageParameters&&t.vrDisplay.stageParameters.sittingToStandingTransform&&this._webVROptions.trackPosition?(this._standingMatrix=new o.y3,o.y3.FromFloat32ArrayToRefScaled(t.vrDisplay.stageParameters.sittingToStandingTransform,0,1,this._standingMatrix),this.getScene().useRightHandedSystem||this._standingMatrix&&this._standingMatrix.toggleModelMatrixHandInPlace(),e(!0)):e(!1)}))}useStandingMatrixAsync(){return new Promise((e=>{this.useStandingMatrix((t=>{e(t)}))}))}dispose(){this._detachIfAttached(),this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled),this._updateCacheWhenTrackingDisabledObserver&&this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver),super.dispose()}getControllerByName(e){for(const t of this.controllers)if(t.hand===e)return t;return null}get leftController(){return this._leftController||(this._leftController=this.getControllerByName("left")),this._leftController}get rightController(){return this._rightController||(this._rightController=this.getControllerByName("right")),this._rightController}getForwardRay(e=100){return this.leftCamera?super.getForwardRay(e,this.leftCamera.getWorldMatrix(),this.leftCamera.globalPosition):super.getForwardRay(e)}_checkInputs(){this._vrDevice&&this._vrDevice.isPresenting&&(this._vrDevice.getFrameData(this._frameData),this.updateFromDevice(this._frameData.pose)),super._checkInputs()}updateFromDevice(e){e&&e.orientation&&4===e.orientation.length&&(this.rawPose=e,this._deviceRoomRotationQuaternion.copyFromFloats(e.orientation[0],e.orientation[1],-e.orientation[2],-e.orientation[3]),this.getScene().useRightHandedSystem&&(this._deviceRoomRotationQuaternion.z*=-1,this._deviceRoomRotationQuaternion.w*=-1),this._webVROptions.trackPosition&&this.rawPose.position&&(this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0],this.rawPose.position[1],-this.rawPose.position[2]),this.getScene().useRightHandedSystem&&(this._deviceRoomPosition.z*=-1)),this._poseSet=!0)}attachControl(e){e=se.w1.BackCompatCameraNoPreventDefault(arguments),super.attachControl(e),this._attached=!0,e=!ce.V.ForceAttachControlToAlwaysPreventDefault&&e,this._vrDevice&&this.getEngine().enableVR(this._webVROptions);const t=this._scene.getEngine().getHostWindow();t&&t.addEventListener("vrdisplaypresentchange",this._detachIfAttached)}detachControl(){this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),super.detachControl(),this._attached=!1,this.getEngine().disableVR(),window.removeEventListener("vrdisplaypresentchange",this._detachIfAttached)}getClassName(){return"WebVRFreeCamera"}resetToCurrentRotation(){this._vrDevice.resetPose()}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];e.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion),t.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion),e.position.copyFrom(this._deviceRoomPosition),t.position.copyFrom(this._deviceRoomPosition)}_correctPositionIfNotTrackPosition(e,t=!1){this.rawPose&&this.rawPose.position&&!this._webVROptions.trackPosition&&(o.y3.TranslationToRef(this.rawPose.position[0],this.rawPose.position[1],-this.rawPose.position[2],this._tmpMatrix),t||this._tmpMatrix.invert(),this._tmpMatrix.multiplyToRef(e,e))}_updateCache(e){this.rotationQuaternion.equals(this._cache.rotationQuaternion)&&this.position.equals(this._cache.position)||(this._updateCacheCalled||(this._updateCacheCalled=!0,this.update()),this.rotationQuaternion.toRotationMatrix(this._workingMatrix),o.P.TransformCoordinatesToRef(this._deviceRoomPosition,this._workingMatrix,this._workingVector),this.devicePosition.subtractToRef(this._workingVector,this._workingVector),o.y3.ComposeToRef(this._oneVector,this.rotationQuaternion,this._workingVector,this._deviceToWorld),this._deviceToWorld.getTranslationToRef(this._workingVector),this._workingVector.addInPlace(this.position),this._workingVector.subtractInPlace(this._cache.position),this._deviceToWorld.setTranslation(this._workingVector),this._deviceToWorld.invertToRef(this._worldToDevice),this.controllers.forEach((e=>{e._deviceToWorld.copyFrom(this._deviceToWorld),this._correctPositionIfNotTrackPosition(e._deviceToWorld),e.update()}))),e||super._updateCache(),this._updateCacheCalled=!1}_computeDevicePosition(){o.P.TransformCoordinatesToRef(this._deviceRoomPosition,this._deviceToWorld,this.devicePosition)}update(){this._computeDevicePosition(),o.y3.FromQuaternionToRef(this._deviceRoomRotationQuaternion,this._workingMatrix),this._workingMatrix.multiplyToRef(this._deviceToWorld,this._workingMatrix),o._f.FromRotationMatrixToRef(this._workingMatrix,this.deviceRotationQuaternion),this._poseSet&&this.onPoseUpdatedFromDeviceObservable.notifyObservers(null),super.update()}_getViewMatrix(){return o.y3.Identity()}_getWebVRViewMatrix(){const e=this._cameraRigParams.parentCamera;e._updateCache();const t=this._cameraRigParams.left?this._cameraRigParams.frameData.leftViewMatrix:this._cameraRigParams.frameData.rightViewMatrix;return o.y3.FromArrayToRef(t,0,this._webvrViewMatrix),this.getScene().useRightHandedSystem||this._webvrViewMatrix.toggleModelMatrixHandInPlace(),this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix),o.P.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint),this.position.addToRef(this._transformedReferencePoint,this._currentTarget),1!==e.deviceScaleFactor&&(this._webvrViewMatrix.invert(),e.deviceScaleFactor&&(this._webvrViewMatrix.multiplyAtIndex(12,e.deviceScaleFactor),this._webvrViewMatrix.multiplyAtIndex(13,e.deviceScaleFactor),this._webvrViewMatrix.multiplyAtIndex(14,e.deviceScaleFactor)),this._webvrViewMatrix.invert()),e._correctPositionIfNotTrackPosition(this._webvrViewMatrix,!0),e._worldToDevice.multiplyToRef(this._webvrViewMatrix,this._webvrViewMatrix),this._workingMatrix=this._workingMatrix||o.y3.Identity(),this._webvrViewMatrix.invertToRef(this._workingMatrix),this._workingMatrix.multiplyToRef(e.getWorldMatrix(),this._workingMatrix),this._workingMatrix.getTranslationToRef(this._globalPosition),this._markSyncedWithParent(),this._webvrViewMatrix}_getWebVRProjectionMatrix(){const e=this.parent;e._vrDevice.depthNear=e.minZ,e._vrDevice.depthFar=e.maxZ;const t=this._cameraRigParams.left?this._cameraRigParams.frameData.leftProjectionMatrix:this._cameraRigParams.frameData.rightProjectionMatrix;return o.y3.FromArrayToRef(t,0,this._projectionMatrix),this.getScene().useRightHandedSystem||this._projectionMatrix.toggleProjectionMatrixHandInPlace(),this._projectionMatrix}initControllers(){this.controllers.length=0;const e=this.getScene().gamepadManager;this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{if(e.type===tn.POSE_ENABLED){const t=e;t.defaultModel&&t.defaultModel.setEnabled(!1),"right"===t.hand&&(this._rightController=null),"left"===t.hand&&(this._leftController=null);const i=this.controllers.indexOf(t);-1!==i&&this.controllers.splice(i,1)}})),this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add((e=>{if(e.type===tn.POSE_ENABLED){const t=e;if(this._webVROptions.trackPosition||(t._disableTrackPosition(new o.P("left"==t.hand?-.15:.15,-.5,.25)),this._updateCacheWhenTrackingDisabledObserver||(this._updateCacheWhenTrackingDisabledObserver=this._scene.onBeforeRenderObservable.add((()=>{this._updateCache()})))),t.deviceScaleFactor=this.deviceScaleFactor,t._deviceToWorld.copyFrom(this._deviceToWorld),this._correctPositionIfNotTrackPosition(t._deviceToWorld),this._webVROptions.controllerMeshes&&(t.defaultModel?t.defaultModel.setEnabled(!0):t.initControllerMesh(this.getScene(),(e=>{if(e.scaling.scaleInPlace(this.deviceScaleFactor),this.onControllerMeshLoadedObservable.notifyObservers(t),this._webVROptions.defaultLightingOnControllers){this._lightOnControllers||(this._lightOnControllers=new Os("vrControllersLight",new o.P(0,1,0),this.getScene()));const t=function(e,i){const n=e.getChildren();n&&0!==n.length&&n.forEach((e=>{i.includedOnlyMeshes.push(e),t(e,i)}))};this._lightOnControllers.includedOnlyMeshes.push(e),t(e,this._lightOnControllers)}}))),t.attachToPoseControlledCamera(this),-1===this.controllers.indexOf(t)){this.controllers.push(t);let e=!1;for(let t=0;t=2&&this.onControllersAttachedObservable.notifyObservers(this.controllers)}}}))}}class Fs extends Hn{onButtonStateChange(e){this._onButtonStateChange=e}get defaultModel(){return this._defaultModel}constructor(e){super(e),this.onTriggerStateChangedObservable=new r.y$,this.onMainButtonStateChangedObservable=new r.y$,this.onSecondaryButtonStateChangedObservable=new r.y$,this.onPadStateChangedObservable=new r.y$,this.onPadValuesChangedObservable=new r.y$,this.pad={x:0,y:0},this._changes={pressChanged:!1,touchChanged:!1,valueChanged:!1,changed:!1},this._buttons=new Array(e.buttons.length),this.hand=e.hand}update(){super.update();for(let e=0;ee.priority-t.priority)),this._codeInjectionPoints={};const i={};i[sa._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(const n of this._plugins)n.collectDefines(i),this._collectPointNames("vertex",n.getCustomCode("vertex")),this._collectPointNames("fragment",n.getCustomCode("fragment"));return this._defineNamesFromPlugins=i,!0}_activatePlugin(e){-1===this._activePlugins.indexOf(e)&&(this._activePlugins.push(e),this._activePlugins.sort(((e,t)=>e.priority-t.priority)),this._material._callbackPluginEventIsReadyForSubMesh=this._handlePluginEventIsReadyForSubMesh.bind(this),this._material._callbackPluginEventPrepareDefinesBeforeAttributes=this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this),this._material._callbackPluginEventPrepareDefines=this._handlePluginEventPrepareDefines.bind(this),this._material._callbackPluginEventBindForSubMesh=this._handlePluginEventBindForSubMesh.bind(this),e.registerForExtraEvents&&(this._activePluginsForExtraEvents.push(e),this._activePluginsForExtraEvents.sort(((e,t)=>e.priority-t.priority)),this._material._callbackPluginEventHasRenderTargetTextures=this._handlePluginEventHasRenderTargetTextures.bind(this),this._material._callbackPluginEventFillRenderTargetTextures=this._handlePluginEventFillRenderTargetTextures.bind(this),this._material._callbackPluginEventHardBindForSubMesh=this._handlePluginEventHardBindForSubMesh.bind(this)))}getPlugin(e){for(let t=0;t0&&e.uniforms.push(...this._uniformList),this._samplerList.length>0&&e.samplers.push(...this._samplerList),this._uboList.length>0&&e.uniformBuffersNames.push(...this._uboList),e.customCode=this._injectCustomCode(e.customCode);break}case Ls.S.PrepareUniformBuffer:{const e=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];for(const t of this._plugins){const n=t.getUniforms();if(n){if(n.ubo)for(const t of n.ubo){if(t.size&&t.type){const n=null!==(i=t.arraySize)&&void 0!==i?i:0;e.ubo.addUniform(t.name,t.size,n),this._uboDeclaration+=`${t.type} ${t.name}${n>0?`[${n}]`:""};\r\n`}this._uniformList.push(t.name)}n.vertex&&(this._vertexDeclaration+=n.vertex+"\r\n"),n.fragment&&(this._fragmentDeclaration+=n.fragment+"\r\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){return(t,i)=>{var n;e&&(i=e(t,i)),this._uboDeclaration&&(i=i.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(i=i.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(i=i.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));const s=null===(n=this._codeInjectionPoints)||void 0===n?void 0:n[t];if(!s)return i;for(let e in s){let n="";for(const i of this._activePlugins){const s=i.getCustomCode(t);(null==s?void 0:s[e])&&(n+=s[e]+"\r\n")}if(n.length>0)if("!"===e.charAt(0)){e=e.substring(1);let t="g";if("!"===e.charAt(0))t="",e=e.substring(1);else{const i=na.exec(e);i&&i.length>=2&&(t=i[1],e=e.substring(t.length+1))}t.indexOf("g")<0&&(t+="g");const s=i,r=new RegExp(e,t);let o=r.exec(s);for(;null!==o;){let e=n;for(let t=0;t{la()}));const ra=[];let oa=!1,aa=null;function la(){ra.length=0,oa=!1,ut.F.OnEventObservable.remove(aa),aa=null}class ha{_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,n,s=!0,r=!1){this.priority=500,this.registerForExtraEvents=!1,this._material=e,this.name=t,this.priority=i,e.pluginManager||(e.pluginManager=new sa(e),e.onDisposeObservable.add((()=>{e.pluginManager=void 0}))),this._pluginDefineNames=n,this._pluginManager=e.pluginManager,s&&this._pluginManager._addPlugin(this),r&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,n){return!0}hardBindForSubMesh(e,t,i,n){}bindForSubMesh(e,t,i,n){}dispose(e){}getCustomCode(e){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(){return{}}copyTo(e){E.p4.Clone((()=>e),this)}serialize(){return E.p4.Serialize(this)}parse(e,t,i){E.p4.Parse((()=>this),e,t,i)}}(0,oe.gn)([(0,E.qC)()],ha.prototype,"name",void 0),(0,oe.gn)([(0,E.qC)()],ha.prototype,"priority",void 0),(0,oe.gn)([(0,E.qC)()],ha.prototype,"registerForExtraEvents",void 0);class ca extends Tt.H{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class da extends ha{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new ca,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=ut.F.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&i.getCaps().standardDerivatives&&this._texture&&Bs.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&&Bs.DetailTextureEnabled&&this._isEnabled?(It.G.PrepareDefinesForMergedUV(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&&Bs.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),It.G.BindTextureMatrix(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&Bs.DetailTextureEnabled&&e.setTexture("detailSampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){var t;e&&(null===(t=this._texture)||void 0===t||t.dispose())}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}}(0,oe.gn)([(0,E.oU)("detailTexture"),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],da.prototype,"texture",void 0),(0,oe.gn)([(0,E.qC)()],da.prototype,"diffuseBlendLevel",void 0),(0,oe.gn)([(0,E.qC)()],da.prototype,"roughnessBlendLevel",void 0),(0,oe.gn)([(0,E.qC)()],da.prototype,"bumpLevel",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],da.prototype,"normalBlendMethod",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],da.prototype,"isEnabled",void 0);var ua=i(6181);const pa={effect:null,subMesh:null};class fa extends Tt.H{constructor(e){super(e),this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.OPACITY=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.SPECULAR=!1,this.SPECULARDIRECTUV=0,this.BUMP=!1,this.BUMPDIRECTUV=0,this.PARALLAX=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.IS_REFLECTION_LINEAR=!1,this.IS_REFRACTION_LINEAR=!1,this.EXPOSURE=!1,this.rebuild()}setReflectionMode(e){const t=["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"];for(const i of t)this[i]=i===e}}class _a extends pt{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}get isPrePassCapable(){return!this.disableDepthWrite}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}get canRenderToMRT(){return!0}constructor(e,t){super(e,t),this._diffuseTexture=null,this._ambientTexture=null,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._specularTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._refractionTexture=null,this.ambientColor=new a.Wo(0,0,0),this.diffuseColor=new a.Wo(1,1,1),this.specularColor=new a.Wo(1,1,1),this.emissiveColor=new a.Wo(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._renderTargets=new Wt.t(16),this._worldViewProjectionMatrix=o.y3.Zero(),this._globalAmbientColor=new a.Wo(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new da(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new ws,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),_a.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),_a.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._renderTargets.push(this._refractionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets)}get hasRenderTargetTextures(){return!!(_a.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||(!!(_a.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures)}getClassName(){return"StandardMaterial"}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported,this._markAllSubMeshesAsMiscDirty()}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled)}needAlphaTesting(){return!!this._forceAlphaTest||this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===ut.F.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==ut.F.MATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){if(this._uniformBufferLayoutBuilt||this.buildUniformLayout(),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(Ls.S.GetDefineNames,this._eventInfo),t.materialDefines=new fa(this._eventInfo.defineNames));const n=this.getScene(),s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const r=n.getEngine();s._needNormals=It.G.PrepareDefinesForLights(n,e,s,!0,this._maxSimultaneousLights,this._disableLighting),It.G.PrepareDefinesForMultiview(n,s);const o=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(It.G.PrepareDefinesForPrePass(n,s,this.canRenderToMRT&&!o),It.G.PrepareDefinesForOIT(n,s,o),s._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,s._needUVs=!1;for(let e=1;e<=6;++e)s["MAINUV"+e]=!1;if(n.texturesEnabled){if(s.DIFFUSEDIRECTUV=0,s.BUMPDIRECTUV=0,s.AMBIENTDIRECTUV=0,s.OPACITYDIRECTUV=0,s.EMISSIVEDIRECTUV=0,s.SPECULARDIRECTUV=0,s.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&_a.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;It.G.PrepareDefinesForMergedUV(this._diffuseTexture,s,"DIFFUSE")}else s.DIFFUSE=!1;if(this._ambientTexture&&_a.AmbientTextureEnabled){if(!this._ambientTexture.isReadyOrNotBlocking())return!1;It.G.PrepareDefinesForMergedUV(this._ambientTexture,s,"AMBIENT")}else s.AMBIENT=!1;if(this._opacityTexture&&_a.OpacityTextureEnabled){if(!this._opacityTexture.isReadyOrNotBlocking())return!1;It.G.PrepareDefinesForMergedUV(this._opacityTexture,s,"OPACITY"),s.OPACITYRGB=this._opacityTexture.getAlphaFromRGB}else s.OPACITY=!1;if(this._reflectionTexture&&_a.ReflectionTextureEnabled){if(!this._reflectionTexture.isReadyOrNotBlocking())return!1;switch(s._needNormals=!0,s.REFLECTION=!0,s.ROUGHNESS=this._roughness>0,s.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,s.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===Le.INVCUBIC_MODE,s.REFLECTIONMAP_3D=this._reflectionTexture.isCube,s.REFLECTIONMAP_OPPOSITEZ=s.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,s.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case Le.EXPLICIT_MODE:s.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case Le.PLANAR_MODE:s.setReflectionMode("REFLECTIONMAP_PLANAR");break;case Le.PROJECTION_MODE:s.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case Le.SKYBOX_MODE:s.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case Le.SPHERICAL_MODE:s.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case Le.EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case Le.FIXED_EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case Le.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:s.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case Le.CUBIC_MODE:case Le.INVCUBIC_MODE:default:s.setReflectionMode("REFLECTIONMAP_CUBIC")}s.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else s.REFLECTION=!1,s.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&_a.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;It.G.PrepareDefinesForMergedUV(this._emissiveTexture,s,"EMISSIVE")}else s.EMISSIVE=!1;if(this._lightmapTexture&&_a.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;It.G.PrepareDefinesForMergedUV(this._lightmapTexture,s,"LIGHTMAP"),s.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,s.RGBDLIGHTMAP=this._lightmapTexture.isRGBD}else s.LIGHTMAP=!1;if(this._specularTexture&&_a.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;It.G.PrepareDefinesForMergedUV(this._specularTexture,s,"SPECULAR"),s.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else s.SPECULAR=!1;if(n.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&_a.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;It.G.PrepareDefinesForMergedUV(this._bumpTexture,s,"BUMP"),s.PARALLAX=this._useParallax,s.PARALLAXOCCLUSION=this._useParallaxOcclusion,s.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else s.BUMP=!1,s.PARALLAX=!1,s.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&_a.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.REFRACTION=!0,s.REFRACTIONMAP_3D=this._refractionTexture.isCube,s.RGBDREFRACTION=this._refractionTexture.isRGBD,s.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize}else s.REFRACTION=!1;s.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else s.DIFFUSE=!1,s.AMBIENT=!1,s.OPACITY=!1,s.REFLECTION=!1,s.EMISSIVE=!1,s.LIGHTMAP=!1,s.BUMP=!1,s.REFRACTION=!1;s.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),s.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,s.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,s.SPECULAROVERALPHA=this._useSpecularOverAlpha,s.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,s.ALPHATEST_AFTERALLALPHACOMPUTATIONS=null!==this.transparencyMode,s.ALPHABLEND=null===this.transparencyMode||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(s._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(s),s.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,s.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}s._areFresnelDirty&&(_a.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(s.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,s.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,s.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,s.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,s.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,s.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,s._needNormals=!0,s.FRESNEL=!0):s.FRESNEL=!1),It.G.PrepareDefinesForMisc(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,s),It.G.PrepareDefinesForFrameBoundValues(n,r,this,s,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=s,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),It.G.PrepareDefinesForAttributes(e,s,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let a=!1;if(s.isDirty){const i=s._areLightsDisposed;s.markAsProcessed();const o=new zt;s.REFLECTION&&o.addFallback(0,"REFLECTION"),s.SPECULAR&&o.addFallback(0,"SPECULAR"),s.BUMP&&o.addFallback(0,"BUMP"),s.PARALLAX&&o.addFallback(1,"PARALLAX"),s.PARALLAXOCCLUSION&&o.addFallback(0,"PARALLAXOCCLUSION"),s.SPECULAROVERALPHA&&o.addFallback(0,"SPECULAROVERALPHA"),s.FOG&&o.addFallback(1,"FOG"),s.POINTSIZE&&o.addFallback(0,"POINTSIZE"),s.LOGARITHMICDEPTH&&o.addFallback(0,"LOGARITHMICDEPTH"),It.G.HandleFallbacksForShadows(s,o,this._maxSimultaneousLights),s.SPECULARTERM&&o.addFallback(0,"SPECULARTERM"),s.DIFFUSEFRESNEL&&o.addFallback(1,"DIFFUSEFRESNEL"),s.OPACITYFRESNEL&&o.addFallback(2,"OPACITYFRESNEL"),s.REFLECTIONFRESNEL&&o.addFallback(3,"REFLECTIONFRESNEL"),s.EMISSIVEFRESNEL&&o.addFallback(4,"EMISSIVEFRESNEL"),s.FRESNEL&&o.addFallback(4,"FRESNEL"),s.MULTIVIEW&&o.addFallback(0,"MULTIVIEW");const l=[ne.o.PositionKind];s.NORMAL&&l.push(ne.o.NormalKind),s.TANGENT&&l.push(ne.o.TangentKind);for(let e=1;e<=6;++e)s["UV"+e]&&l.push(`uv${1===e?"":e}`);s.VERTEXCOLOR&&l.push(ne.o.ColorKind),It.G.PrepareAttributesForBones(l,e,s,o),It.G.PrepareAttributesForInstances(l,s),It.G.PrepareAttributesForMorphTargets(l,e,s),It.G.PrepareAttributesForBakedVertexAnimation(l,e,s);let h="default";const c=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","visibility","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vReflectionPosition","vReflectionSize","vRefractionPosition","vRefractionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff","boneTextureWidth","morphTargetTextureInfo","morphTargetTextureIndices"],d=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],u=["Material","Scene","Mesh"];this._eventInfo.fallbacks=o,this._eventInfo.fallbackRank=0,this._eventInfo.defines=s,this._eventInfo.uniforms=c,this._eventInfo.attributes=l,this._eventInfo.samplers=d,this._eventInfo.uniformBuffersNames=u,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._callbackPluginEventGeneric(Ls.S.PrepareEffect,this._eventInfo),ws.AddUniforms(c),ws.AddSamplers(d),ii.$&&(ii.$.PrepareUniforms(c,s),ii.$.PrepareSamplers(d,s)),It.G.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:u,samplers:d,defines:s,maxSimultaneousLights:this._maxSimultaneousLights}),(0,ua.qx)(c);const p={};this.customShaderNameResolve&&(h=this.customShaderNameResolve(h,c,u,d,s,l,p));const f=s.toString(),_=t.effect;let m=n.getEngine().createEffect(h,{attributes:l,uniformsNames:c,uniformBuffersNames:u,samplers:d,defines:f,fallbacks:o,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:s.NUM_MORPH_INFLUENCERS},processFinalCode:p.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:s.PREPASS},r);if(this._eventInfo.customCode=void 0,m)if(this._onEffectCreatedObservable&&(pa.effect=m,pa.subMesh=t,this._onEffectCreatedObservable.notifyObservers(pa)),this.allowShaderHotSwapping&&_&&!m.isReady()){if(m=_,s.markAsUnprocessed(),a=this.isFrozen,i)return s._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(m,s,this._materialContext)}return!(!t.effect||!t.effect.isReady())&&(s._renderId=n.getRenderId(),t.effect._wasPreviouslyReady=!a,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("reflectionMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("alphaCutOff",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vRefractionPosition",3),e.addUniform("vRefractionSize",3),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vDiffuseColor",4),e.addUniform("vAmbientColor",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){var n;const s=this.getScene(),r=i.materialDefines;if(!r)return;const o=i.effect;if(!o)return;this._activeEffect=o,t.getMeshUniformBuffer().bindToEffect(o,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(o,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),r.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const l=o._forceRebindOnNextCall||this._mustRebind(s,o,t.visibility);It.G.BindBonesParameters(t,o);const h=this._uniformBuffer;if(l){if(this.bindViewProjection(o),!h.useUbo||!this.isFrozen||!h.isSync||o._forceRebindOnNextCall){if(_a.FresnelEnabled&&r.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(h.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),h.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&h.updateColor4("opacityParts",new a.Wo(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(h.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),h.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(h.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),h.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(h.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),h.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),s.texturesEnabled){if(this._diffuseTexture&&_a.DiffuseTextureEnabled&&(h.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),It.G.BindTextureMatrix(this._diffuseTexture,h,"diffuse")),this._ambientTexture&&_a.AmbientTextureEnabled&&(h.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),It.G.BindTextureMatrix(this._ambientTexture,h,"ambient")),this._opacityTexture&&_a.OpacityTextureEnabled&&(h.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),It.G.BindTextureMatrix(this._opacityTexture,h,"opacity")),this._hasAlphaChannel()&&h.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&_a.ReflectionTextureEnabled&&(h.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),h.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){const e=this._reflectionTexture;h.updateVector3("vReflectionPosition",e.boundingBoxPosition),h.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this._emissiveTexture&&_a.EmissiveTextureEnabled&&(h.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),It.G.BindTextureMatrix(this._emissiveTexture,h,"emissive")),this._lightmapTexture&&_a.LightmapTextureEnabled&&(h.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),It.G.BindTextureMatrix(this._lightmapTexture,h,"lightmap")),this._specularTexture&&_a.SpecularTextureEnabled&&(h.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),It.G.BindTextureMatrix(this._specularTexture,h,"specular")),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&_a.BumpTextureEnabled&&(h.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),It.G.BindTextureMatrix(this._bumpTexture,h,"bump"),s._mirroredCameraPosition?h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&_a.RefractionTextureEnabled){let e=1;if(this._refractionTexture.isCube||(h.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(e=this._refractionTexture.depth)),h.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,e,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){const e=this._refractionTexture;h.updateVector3("vRefractionPosition",e.boundingBoxPosition),h.updateVector3("vRefractionSize",e.boundingBoxSize)}}}this.pointsCloud&&h.updateFloat("pointSize",this.pointSize),r.SPECULARTERM&&h.updateColor4("vSpecularColor",this.specularColor,this.specularPower),h.updateColor3("vEmissiveColor",_a.EmissiveTextureEnabled?this.emissiveColor:a.Wo.BlackReadOnly),h.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),s.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),h.updateColor3("vAmbientColor",this._globalAmbientColor)}s.texturesEnabled&&(this._diffuseTexture&&_a.DiffuseTextureEnabled&&o.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&_a.AmbientTextureEnabled&&o.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&_a.OpacityTextureEnabled&&o.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&_a.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?o.setTexture("reflectionCubeSampler",this._reflectionTexture):o.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&_a.EmissiveTextureEnabled&&o.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&_a.LightmapTextureEnabled&&o.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&_a.SpecularTextureEnabled&&o.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&_a.BumpTextureEnabled&&o.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&_a.RefractionTextureEnabled&&(this._refractionTexture.isCube?o.setTexture("refractionCubeSampler",this._refractionTexture):o.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(o),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),(0,ua.an)(o,this,s),this.bindEyePosition(o)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!l&&this.isFrozen||(s.lightsEnabled&&!this._disableLighting&&It.G.BindLights(s,t,o,r,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==N.x.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||r.PREPASS)&&this.bindView(o),It.G.BindFogParameters(s,t,o),r.NUM_MORPH_INFLUENCERS&&It.G.BindMorphTargetParameters(t,o),r.BAKED_VERTEX_ANIMATION_TEXTURE&&(null===(n=t.bakedVertexAnimationManager)||void 0===n||n.bind(o,r.INSTANCES)),this.useLogarithmicDepth&&It.G.BindLogDepth(r,o,s),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),h.update()}getAnimatables(){const e=super.getAnimatables();return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e}hasTexture(e){return!!super.hasTexture(e)||(this._diffuseTexture===e||(this._ambientTexture===e||(this._opacityTexture===e||(this._reflectionTexture===e||(this._emissiveTexture===e||(this._specularTexture===e||(this._bumpTexture===e||(this._lightmapTexture===e||this._refractionTexture===e))))))))}dispose(e,t){var i,n,s,r,o,a,l,h,c;t&&(null===(i=this._diffuseTexture)||void 0===i||i.dispose(),null===(n=this._ambientTexture)||void 0===n||n.dispose(),null===(s=this._opacityTexture)||void 0===s||s.dispose(),null===(r=this._reflectionTexture)||void 0===r||r.dispose(),null===(o=this._emissiveTexture)||void 0===o||o.dispose(),null===(a=this._specularTexture)||void 0===a||a.dispose(),null===(l=this._bumpTexture)||void 0===l||l.dispose(),null===(h=this._lightmapTexture)||void 0===h||h.dispose(),null===(c=this._refractionTexture)||void 0===c||c.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){const n=E.p4.Clone((()=>new _a(e,this.getScene())),this,{cloneTexturesOnlyOnce:t});return n.name=e,n.id=e,this.stencil.copyTo(n.stencil),this._clonePlugins(n,i),n}static Parse(e,t,i){const n=E.p4.Parse((()=>new _a(e.name,t)),e,t,i);return e.stencil&&n.stencil.parse(e.stencil,t,i),ut.F._parsePlugins(e,n,t,i),n}static get DiffuseTextureEnabled(){return Bs.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){Bs.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return Bs.DetailTextureEnabled}static set DetailTextureEnabled(e){Bs.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return Bs.AmbientTextureEnabled}static set AmbientTextureEnabled(e){Bs.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return Bs.OpacityTextureEnabled}static set OpacityTextureEnabled(e){Bs.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return Bs.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){Bs.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return Bs.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){Bs.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return Bs.SpecularTextureEnabled}static set SpecularTextureEnabled(e){Bs.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return Bs.BumpTextureEnabled}static set BumpTextureEnabled(e){Bs.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return Bs.LightmapTextureEnabled}static set LightmapTextureEnabled(e){Bs.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return Bs.RefractionTextureEnabled}static set RefractionTextureEnabled(e){Bs.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return Bs.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){Bs.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return Bs.FresnelEnabled}static set FresnelEnabled(e){Bs.FresnelEnabled=e}}(0,oe.gn)([(0,E.oU)("diffuseTexture")],_a.prototype,"_diffuseTexture",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],_a.prototype,"diffuseTexture",void 0),(0,oe.gn)([(0,E.oU)("ambientTexture")],_a.prototype,"_ambientTexture",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"ambientTexture",void 0),(0,oe.gn)([(0,E.oU)("opacityTexture")],_a.prototype,"_opacityTexture",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],_a.prototype,"opacityTexture",void 0),(0,oe.gn)([(0,E.oU)("reflectionTexture")],_a.prototype,"_reflectionTexture",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"reflectionTexture",void 0),(0,oe.gn)([(0,E.oU)("emissiveTexture")],_a.prototype,"_emissiveTexture",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"emissiveTexture",void 0),(0,oe.gn)([(0,E.oU)("specularTexture")],_a.prototype,"_specularTexture",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"specularTexture",void 0),(0,oe.gn)([(0,E.oU)("bumpTexture")],_a.prototype,"_bumpTexture",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"bumpTexture",void 0),(0,oe.gn)([(0,E.oU)("lightmapTexture")],_a.prototype,"_lightmapTexture",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"lightmapTexture",void 0),(0,oe.gn)([(0,E.oU)("refractionTexture")],_a.prototype,"_refractionTexture",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"refractionTexture",void 0),(0,oe.gn)([(0,E.n9)("ambient")],_a.prototype,"ambientColor",void 0),(0,oe.gn)([(0,E.n9)("diffuse")],_a.prototype,"diffuseColor",void 0),(0,oe.gn)([(0,E.n9)("specular")],_a.prototype,"specularColor",void 0),(0,oe.gn)([(0,E.n9)("emissive")],_a.prototype,"emissiveColor",void 0),(0,oe.gn)([(0,E.qC)()],_a.prototype,"specularPower",void 0),(0,oe.gn)([(0,E.qC)("useAlphaFromDiffuseTexture")],_a.prototype,"_useAlphaFromDiffuseTexture",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],_a.prototype,"useAlphaFromDiffuseTexture",void 0),(0,oe.gn)([(0,E.qC)("useEmissiveAsIllumination")],_a.prototype,"_useEmissiveAsIllumination",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"useEmissiveAsIllumination",void 0),(0,oe.gn)([(0,E.qC)("linkEmissiveWithDiffuse")],_a.prototype,"_linkEmissiveWithDiffuse",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"linkEmissiveWithDiffuse",void 0),(0,oe.gn)([(0,E.qC)("useSpecularOverAlpha")],_a.prototype,"_useSpecularOverAlpha",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"useSpecularOverAlpha",void 0),(0,oe.gn)([(0,E.qC)("useReflectionOverAlpha")],_a.prototype,"_useReflectionOverAlpha",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"useReflectionOverAlpha",void 0),(0,oe.gn)([(0,E.qC)("disableLighting")],_a.prototype,"_disableLighting",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsLightsDirty")],_a.prototype,"disableLighting",void 0),(0,oe.gn)([(0,E.qC)("useObjectSpaceNormalMap")],_a.prototype,"_useObjectSpaceNormalMap",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"useObjectSpaceNormalMap",void 0),(0,oe.gn)([(0,E.qC)("useParallax")],_a.prototype,"_useParallax",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"useParallax",void 0),(0,oe.gn)([(0,E.qC)("useParallaxOcclusion")],_a.prototype,"_useParallaxOcclusion",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"useParallaxOcclusion",void 0),(0,oe.gn)([(0,E.qC)()],_a.prototype,"parallaxScaleBias",void 0),(0,oe.gn)([(0,E.qC)("roughness")],_a.prototype,"_roughness",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"roughness",void 0),(0,oe.gn)([(0,E.qC)()],_a.prototype,"indexOfRefraction",void 0),(0,oe.gn)([(0,E.qC)()],_a.prototype,"invertRefractionY",void 0),(0,oe.gn)([(0,E.qC)()],_a.prototype,"alphaCutOff",void 0),(0,oe.gn)([(0,E.qC)("useLightmapAsShadowmap")],_a.prototype,"_useLightmapAsShadowmap",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"useLightmapAsShadowmap",void 0),(0,oe.gn)([(0,E.qQ)("diffuseFresnelParameters")],_a.prototype,"_diffuseFresnelParameters",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsFresnelDirty")],_a.prototype,"diffuseFresnelParameters",void 0),(0,oe.gn)([(0,E.qQ)("opacityFresnelParameters")],_a.prototype,"_opacityFresnelParameters",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsFresnelAndMiscDirty")],_a.prototype,"opacityFresnelParameters",void 0),(0,oe.gn)([(0,E.qQ)("reflectionFresnelParameters")],_a.prototype,"_reflectionFresnelParameters",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsFresnelDirty")],_a.prototype,"reflectionFresnelParameters",void 0),(0,oe.gn)([(0,E.qQ)("refractionFresnelParameters")],_a.prototype,"_refractionFresnelParameters",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsFresnelDirty")],_a.prototype,"refractionFresnelParameters",void 0),(0,oe.gn)([(0,E.qQ)("emissiveFresnelParameters")],_a.prototype,"_emissiveFresnelParameters",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsFresnelDirty")],_a.prototype,"emissiveFresnelParameters",void 0),(0,oe.gn)([(0,E.qC)("useReflectionFresnelFromSpecular")],_a.prototype,"_useReflectionFresnelFromSpecular",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsFresnelDirty")],_a.prototype,"useReflectionFresnelFromSpecular",void 0),(0,oe.gn)([(0,E.qC)("useGlossinessFromSpecularMapAlpha")],_a.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"useGlossinessFromSpecularMapAlpha",void 0),(0,oe.gn)([(0,E.qC)("maxSimultaneousLights")],_a.prototype,"_maxSimultaneousLights",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsLightsDirty")],_a.prototype,"maxSimultaneousLights",void 0),(0,oe.gn)([(0,E.qC)("invertNormalMapX")],_a.prototype,"_invertNormalMapX",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"invertNormalMapX",void 0),(0,oe.gn)([(0,E.qC)("invertNormalMapY")],_a.prototype,"_invertNormalMapY",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"invertNormalMapY",void 0),(0,oe.gn)([(0,E.qC)("twoSidedLighting")],_a.prototype,"_twoSidedLighting",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"twoSidedLighting",void 0),(0,oe.gn)([(0,E.qC)()],_a.prototype,"useLogarithmicDepth",null),(0,l.H)("BABYLON.StandardMaterial",_a),N.x.DefaultMaterialFactory=e=>new _a("default material",e),Ue.B.prototype.createDynamicTexture=function(e,t,i,n){const s=new Be.l(this,Be.S.Dynamic);return s.baseWidth=e,s.baseHeight=t,i&&(e=this.needPOTTextures?Ue.B.GetExponentOfTwo(e,this._caps.maxTextureSize):e,t=this.needPOTTextures?Ue.B.GetExponentOfTwo(t,this._caps.maxTextureSize):t),s.width=e,s.height=t,s.isReady=!1,s.generateMipMaps=i,s.samplingMode=n,this.updateTextureSamplingMode(n,s),this._internalTexturesCache.push(s),s},Ue.B.prototype.updateDynamicTexture=function(e,t,i,n=!1,s,r=!1,o=!1){if(!e)return;const a=this._gl,l=a.TEXTURE_2D,h=this._bindTextureDirectly(l,e,!0,r);this._unpackFlipY(void 0===i?e.invertY:i),n&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);const c=this._getWebGLTextureType(e.type),d=this._getInternalFormat(s||e.format),u=this._getRGBABufferInternalSizedFormat(e.type,d);a.texImage2D(l,0,u,d,c,t),e.generateMipMaps&&a.generateMipmap(l),h||this._bindTextureDirectly(l,null),n&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.isReady=!0};class ma extends Le{constructor(e,t,i=null,n=!1,s=3,r=5,o){super(null,i,!n,o,s,void 0,void 0,void 0,void 0,r),this.name=e,this.wrapU=Le.CLAMP_ADDRESSMODE,this.wrapV=Le.CLAMP_ADDRESSMODE,this._generateMipMaps=n;const a=this._getEngine();if(!a)return;t.getContext?(this._canvas=t,this._texture=a.createDynamicTexture(t.width,t.height,n,s)):(this._canvas=a.createCanvas(1,1),t.width||0===t.width?this._texture=a.createDynamicTexture(t.width,t.height,n,s):this._texture=a.createDynamicTexture(t,t,n,s));const l=this.getSize();this._canvas.width!==l.width&&(this._canvas.width=l.width),this._canvas.height!==l.height&&(this._canvas.height=l.height),this._context=this._canvas.getContext("2d")}getClassName(){return"DynamicTexture"}get canRescale(){return!0}_recreate(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._getEngine().createDynamicTexture(e.width,e.height,this._generateMipMaps,this.samplingMode)}scale(e){const t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)}scaleTo(e,t){const i=this.getSize();i.width=e,i.height=t,this._recreate(i)}getContext(){return this._context}clear(){const e=this.getSize();this._context.fillRect(0,0,e.width,e.height)}update(e,t=!1,i=!1){this._getEngine().updateDynamicTexture(this._texture,this._canvas,void 0===e||e,t,this._format||void 0,void 0,i)}drawText(e,t,i,n,s,r,o,a=!0){const l=this.getSize();if(r&&(this._context.fillStyle=r,this._context.fillRect(0,0,l.width,l.height)),this._context.font=n,null==t){const i=this._context.measureText(e);t=(l.width-i.width)/2}if(null==i){const e=parseInt(n.replace(/\D/g,""));i=l.height/2+e/3.65}this._context.fillStyle=s||"",this._context.fillText(e,t,i),a&&this.update(o)}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new ma(this.name,t,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.wrapU=this.wrapU,i.wrapV=this.wrapV,i}serialize(){const e=this.getScene();e&&!e.isReady()&&p.Y.Warn("The scene must be ready before serializing the dynamic texture");const t=super.serialize();return ma._IsCanvasElement(this._canvas)&&(t.base64String=this._canvas.toDataURL()),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t}static _IsCanvasElement(e){return void 0!==e.toDataURL}_rebuild(){this.update()}}const ga="imageProcessingPixelShader",va="varying vec2 vUV;\nuniform sampler2D textureSampler;\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}";Ht.v.ShadersStore[ga]=va;class Ta extends Zt{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){e.applyByPostProcess=!0,this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e,t=!1){if(e!==this._imageProcessingConfiguration){if(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e)this._imageProcessingConfiguration=e;else{let e=null;const t=this.getEngine(),i=this.getCamera();if(i)e=i.getScene();else if(t&&t.scenes){const i=t.scenes;e=i[i.length-1]}else e=m.l.LastCreatedScene;this._imageProcessingConfiguration=e?e.imageProcessingConfiguration:new ii.$}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._updateParameters()}))),t||this._updateParameters()}}get isSupported(){const e=this.getEffect();return!e||e.isSupported}get colorCurves(){return this.imageProcessingConfiguration.colorCurves}set colorCurves(e){this.imageProcessingConfiguration.colorCurves=e}get colorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set colorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get colorGradingTexture(){return this.imageProcessingConfiguration.colorGradingTexture}set colorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get colorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set colorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get exposure(){return this.imageProcessingConfiguration.exposure}set exposure(e){this.imageProcessingConfiguration.exposure=e}get toneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set toneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get toneMappingType(){return this._imageProcessingConfiguration.toneMappingType}set toneMappingType(e){this._imageProcessingConfiguration.toneMappingType=e}get contrast(){return this.imageProcessingConfiguration.contrast}set contrast(e){this.imageProcessingConfiguration.contrast=e}get vignetteStretch(){return this.imageProcessingConfiguration.vignetteStretch}set vignetteStretch(e){this.imageProcessingConfiguration.vignetteStretch=e}get vignetteCentreX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCentreX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteCentreY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCentreY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCenterY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCenterX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteWeight(){return this.imageProcessingConfiguration.vignetteWeight}set vignetteWeight(e){this.imageProcessingConfiguration.vignetteWeight=e}get vignetteColor(){return this.imageProcessingConfiguration.vignetteColor}set vignetteColor(e){this.imageProcessingConfiguration.vignetteColor=e}get vignetteCameraFov(){return this.imageProcessingConfiguration.vignetteCameraFov}set vignetteCameraFov(e){this.imageProcessingConfiguration.vignetteCameraFov=e}get vignetteBlendMode(){return this.imageProcessingConfiguration.vignetteBlendMode}set vignetteBlendMode(e){this.imageProcessingConfiguration.vignetteBlendMode=e}get vignetteEnabled(){return this.imageProcessingConfiguration.vignetteEnabled}set vignetteEnabled(e){this.imageProcessingConfiguration.vignetteEnabled=e}get ditheringIntensity(){return this.imageProcessingConfiguration.ditheringIntensity}set ditheringIntensity(e){this.imageProcessingConfiguration.ditheringIntensity=e}get ditheringEnabled(){return this.imageProcessingConfiguration.ditheringEnabled}set ditheringEnabled(e){this.imageProcessingConfiguration.ditheringEnabled=e}get fromLinearSpace(){return this._fromLinearSpace}set fromLinearSpace(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())}constructor(e,t,i=null,n,s,r,o=0,a){super(e,"imageProcessing",[],[],t,i,n,s,r,null,o,"postprocess",null,!0),this._fromLinearSpace=!0,this._defines={IMAGEPROCESSING:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:!1,TONEMAPPING_ACES:!1,CONTRAST:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,FROMLINEARSPACE:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,EXPOSURE:!1,SKIPFINALCOLORCLAMP:!1},a?(a.applyByPostProcess=!0,this._attachImageProcessingConfiguration(a,!0),this._updateParameters()):(this._attachImageProcessingConfiguration(null,!0),this.imageProcessingConfiguration.applyByPostProcess=!0),this.onApply=e=>{this.imageProcessingConfiguration.bind(e,this.aspectRatio)}}getClassName(){return"ImageProcessingPostProcess"}_updateParameters(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);let e="";for(const n in this._defines)this._defines[n]&&(e+=`#define ${n};\r\n`);const t=["textureSampler"],i=["scale"];ii.$&&(ii.$.PrepareSamplers(t,this._defines),ii.$.PrepareUniforms(i,this._defines)),this.updateEffect(e,i,t)}dispose(e){super.dispose(e),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration&&(this.imageProcessingConfiguration.applyByPostProcess=!1)}}(0,oe.gn)([(0,E.qC)()],Ta.prototype,"_fromLinearSpace",void 0);class Sa{get isFixedFoveationSupported(){return"XRWebGLLayer"==this.layerType&&"number"==typeof this.layer.fixedFoveation}get fixedFoveation(){return this.isFixedFoveationSupported?this.layer.fixedFoveation:null}set fixedFoveation(e){if(this.isFixedFoveationSupported){const t=Math.max(0,Math.min(1,e||0));this.layer.fixedFoveation=t}}constructor(e,t,i,n,s){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=n,this.createRenderTargetTextureProvider=s}}var Ea,xa,ba=i(8449);class Ca{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=new Array,this._engine=e.getEngine()}_createInternalTexture(e,t){const i=new Be.l(this._engine,Be.S.Unknown,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new ba.B(t,this._engine._gl),i.isReady=!0,i}_createRenderTargetTexture(e,t,i,n,s,r){if(!this._engine)throw new Error("Engine is disposed");const o={width:e,height:t},a=r?new bs(this._scene,o):new Ci("XR renderTargetTexture",o,this._scene),l=a.renderTarget;if(l._samples=a.samples,!i&&n||(l._framebuffer=i),n)if(r)l._colorTextureArray=n;else{const e=this._createInternalTexture(o,n);l.setTexture(e,0),a._texture=e}return s&&(r?l._depthStencilTextureArray=s:l._depthStencilTexture=this._createInternalTexture(o,s)),a.disableRescaling(),"undefined"!=typeof XRWebGLBinding&&(a.skipInitialClear=!0),this._renderTargetTextures.push(a),a}_destroyRenderTargetTexture(e){this._renderTargetTextures.splice(this._renderTargetTextures.indexOf(e),1),e.dispose()}getFramebufferDimensions(){return this._framebufferDimensions}dispose(){this._renderTargetTextures.forEach((e=>e.dispose())),this._renderTargetTextures.length=0}}class ya extends Sa{constructor(e){super((()=>e.framebufferWidth),(()=>e.framebufferHeight),e,"XRWebGLLayer",(e=>new Aa(e.scene,this))),this.layer=e}}class Aa extends Ca{constructor(e,t){super(e,t),this.layerWrapper=t,this._layer=t.layer,this._framebufferDimensions={framebufferWidth:this._layer.framebufferWidth,framebufferHeight:this._layer.framebufferHeight}}trySetViewportForView(e,t){const i=this._layer.getViewport(t);if(!i)return!1;const n=this._framebufferDimensions.framebufferWidth,s=this._framebufferDimensions.framebufferHeight;return e.x=i.x/n,e.y=i.y/s,e.width=i.width/n,e.height=i.height/s,!0}getRenderTargetTextureForEye(e){const t=this._layer.framebufferWidth,i=this._layer.framebufferHeight,n=this._layer.framebuffer;return this._rtt&&t===this._framebufferDimensions.framebufferWidth&&i===this._framebufferDimensions.framebufferHeight&&n===this._framebuffer||(this._rtt=this._createRenderTargetTexture(t,i,n),this._framebufferDimensions.framebufferWidth=t,this._framebufferDimensions.framebufferHeight=i,this._framebuffer=n),this._rtt}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}}class Ra{static GetDefaults(e){const t=new Ra;return t.canvasOptions={antialias:!0,depth:!0,stencil:!e||e.isStencilEnable,alpha:!0,framebufferScaleFactor:1},t.newCanvasCssStyle="position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;",t}}class Pa{constructor(e,t=Ra.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new r.y$,this._engine=e.scene.getEngine(),this._engine.onDisposeObservable.addOnce((()=>{this._engine=null})),t.canvasElement)this._setManagedOutputCanvas(t.canvasElement);else{const e=document.createElement("canvas");e.style.cssText=this._options.newCanvasCssStyle||"position:absolute; bottom:0px;right:0px;",this._setManagedOutputCanvas(e)}e.onXRSessionInit.add((()=>{this._addCanvas()})),e.onXRSessionEnded.add((()=>{this._removeCanvas()}))}dispose(){this._removeCanvas(),this._setManagedOutputCanvas(null)}async initializeXRLayerAsync(e){const t=()=>(this.xrLayer=new XRWebGLLayer(e,this.canvasContext,this._options.canvasOptions),this._xrLayerWrapper=new ya(this.xrLayer),this.onXRLayerInitObservable.notifyObservers(this.xrLayer),this.xrLayer);return this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then((()=>{}),(()=>{se.w1.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly.")})).then((()=>t())):Promise.resolve(t())}_addCanvas(){this._canvas&&this._engine&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.appendChild(this._canvas),this.xrLayer?this._setCanvasSize(!0):this.onXRLayerInitObservable.addOnce((()=>{this._setCanvasSize(!0)}))}_removeCanvas(){this._canvas&&this._engine&&document.body.contains(this._canvas)&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.removeChild(this._canvas),this._setCanvasSize(!1)}_setCanvasSize(e=!0,t=this._xrLayerWrapper){this._canvas&&this._engine&&(e?t&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=t.getWidth()+"px",this._canvas.style.height=t.getHeight()+"px"):this._engine.setSize(t.getWidth(),t.getHeight())):this._originalCanvasSize&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=this._originalCanvasSize.width+"px",this._canvas.style.height=this._originalCanvasSize.height+"px"):this._engine.setSize(this._originalCanvasSize.width,this._originalCanvasSize.height)))}_setManagedOutputCanvas(e){this._removeCanvas(),e?(this._originalCanvasSize={width:e.offsetWidth,height:e.offsetHeight},this._canvas=e,this.canvasContext=this._canvas.getContext("webgl2"),this.canvasContext||(this.canvasContext=this._canvas.getContext("webgl"))):(this._canvas=null,this.canvasContext=null)}}class Ia extends Sa{constructor(e){super((()=>e.framebufferWidth),(()=>e.framebufferHeight),e,"XRWebGLLayer",(e=>new Ma(e,this))),this.layer=e}}class Ma extends Ca{constructor(e,t){super(e.scene,t),this.layerWrapper=t,this._nativeRTTProvider=navigator.xr.getNativeRenderTargetProvider(e.session,this._createRenderTargetTexture.bind(this),this._destroyRenderTargetTexture.bind(this)),this._nativeLayer=t.layer}trySetViewportForView(e){return e.x=0,e.y=0,e.width=1,e.height=1,!0}getRenderTargetTextureForEye(e){return this._nativeRTTProvider.getRenderTargetForEye(e)}getRenderTargetTextureForView(e){return this._nativeRTTProvider.getRenderTargetForEye(e.eye)}getFramebufferDimensions(){return{framebufferWidth:this._nativeLayer.framebufferWidth,framebufferHeight:this._nativeLayer.framebufferHeight}}}class Oa{constructor(e){this._nativeRenderTarget=navigator.xr.getWebXRRenderTarget(e.scene.getEngine())}async initializeXRLayerAsync(e){return await this._nativeRenderTarget.initializeXRLayerAsync(e),this.xrLayer=this._nativeRenderTarget.xrLayer,this.xrLayer}dispose(){}}class Da{constructor(e){this.scene=e,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new r.y$,this.onXRReferenceSpaceChanged=new r.y$,this.onXRSessionEnded=new r.y$,this.onXRSessionInit=new r.y$,this.inXRFrameLoop=!1,this.inXRSession=!1,this._engine=e.getEngine(),this._onEngineDisposedObserver=this._engine.onDisposeObservable.addOnce((()=>{this._engine=null})),e.onDisposeObservable.addOnce((()=>{this.dispose()}))}get referenceSpace(){return this._referenceSpace}set referenceSpace(e){this._referenceSpace=e,this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace)}get sessionMode(){return this._sessionMode}dispose(){var e;this.inXRSession&&this.exitXRAsync(),this.onXRFrameObservable.clear(),this.onXRSessionEnded.clear(),this.onXRReferenceSpaceChanged.clear(),this.onXRSessionInit.clear(),null===(e=this._engine)||void 0===e||e.onDisposeObservable.remove(this._onEngineDisposedObserver),this._engine=null}exitXRAsync(){return this.session&&this.inXRSession?(this.inXRSession=!1,this.session.end().catch((()=>{p.Y.Warn("Could not end XR session.")}))):Promise.resolve()}trySetViewportForView(e,t){var i;return(null===(i=this._baseLayerRTTProvider)||void 0===i?void 0:i.trySetViewportForView(e,t))||!1}getRenderTargetTextureForEye(e){var t;return(null===(t=this._baseLayerRTTProvider)||void 0===t?void 0:t.getRenderTargetTextureForEye(e))||null}getRenderTargetTextureForView(e){var t;return(null===(t=this._baseLayerRTTProvider)||void 0===t?void 0:t.getRenderTargetTextureForView(e))||null}getWebXRRenderTarget(e){const t=this.scene.getEngine();return this._xrNavigator.xr.native?new Oa(this):((e=e||Ra.GetDefaults(t)).canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new Pa(this,e))}initializeAsync(){return this._xrNavigator=navigator,this._xrNavigator.xr?Promise.resolve():Promise.reject("WebXR not available")}initializeSessionAsync(e="immersive-vr",t={}){return this._xrNavigator.xr.requestSession(e,t).then((t=>(this.session=t,this._sessionMode=e,this.onXRSessionInit.notifyObservers(t),this.inXRSession=!0,this.session.addEventListener("end",(()=>{var e;this.inXRSession=!1,this.onXRSessionEnded.notifyObservers(null),this._engine&&(this._engine.framebufferDimensionsObject=null,this._engine.restoreDefaultFramebuffer(),this._engine.customAnimationFrameRequester=null,this._engine._renderLoop()),this.isNative&&(null===(e=this._baseLayerRTTProvider)||void 0===e||e.dispose()),this._baseLayerRTTProvider=null,this._baseLayerWrapper=null}),{once:!0}),this.session)))}isSessionSupportedAsync(e){return Da.IsSessionSupportedAsync(e)}resetReferenceSpace(){this.referenceSpace=this.baseReferenceSpace}runXRRenderLoop(){var e;this.inXRSession&&this._engine&&(this._engine.customAnimationFrameRequester={requestAnimationFrame:this.session.requestAnimationFrame.bind(this.session),renderFunction:(e,t)=>{var i;this.inXRSession&&this._engine&&(this.currentFrame=t,this.currentTimestamp=e,t&&(this.inXRFrameLoop=!0,this._engine.framebufferDimensionsObject=(null===(i=this._baseLayerRTTProvider)||void 0===i?void 0:i.getFramebufferDimensions())||null,this.onXRFrameObservable.notifyObservers(t),this._engine._renderLoop(),this._engine.framebufferDimensionsObject=null,this.inXRFrameLoop=!1))}},this._engine.framebufferDimensionsObject=(null===(e=this._baseLayerRTTProvider)||void 0===e?void 0:e.getFramebufferDimensions())||null,"undefined"!=typeof window&&window.cancelAnimationFrame&&window.cancelAnimationFrame(this._engine._frameHandler),this._engine._renderLoop())}setReferenceSpaceTypeAsync(e="local-floor"){return this.session.requestReferenceSpace(e).then((e=>e),(e=>(p.Y.Error("XR.requestReferenceSpace failed for the following reason: "),p.Y.Error(e),p.Y.Log('Defaulting to universally-supported "viewer" reference space type.'),this.session.requestReferenceSpace("viewer").then((e=>{const t=new XRRigidTransform({x:0,y:-this.defaultHeightCompensation,z:0});return e.getOffsetReferenceSpace(t)}),(e=>{throw p.Y.Error(e),'XR initialization failed: required "viewer" reference space type not supported.'}))))).then((e=>this.session.requestReferenceSpace("viewer").then((t=>(this.viewerReferenceSpace=t,e))))).then((e=>(this.referenceSpace=this.baseReferenceSpace=e,this.referenceSpace)))}updateRenderStateAsync(e){return Promise.resolve(this.session.updateRenderState(e))}_setBaseLayerWrapper(e){var t,i;this.isNative&&(null===(t=this._baseLayerRTTProvider)||void 0===t||t.dispose()),this._baseLayerWrapper=e,this._baseLayerRTTProvider=(null===(i=this._baseLayerWrapper)||void 0===i?void 0:i.createRenderTargetTextureProvider(this))||null}_getBaseLayerWrapper(){return this._baseLayerWrapper}updateRenderState(e){e.baseLayer&&this._setBaseLayerWrapper(this.isNative?new Ia(e.baseLayer):new ya(e.baseLayer)),this.session.updateRenderState(e)}static IsSessionSupportedAsync(e){if(!navigator.xr)return Promise.resolve(!1);const t=navigator.xr.isSessionSupported||navigator.xr.supportsSession;return t?t.call(navigator.xr,e).then((e=>{const t=void 0===e||e;return Promise.resolve(t)})).catch((e=>(p.Y.Warn(e),Promise.resolve(!1)))):Promise.resolve(!1)}get isNative(){var e;return null!==(e=this._xrNavigator.xr.native)&&void 0!==e&&e}get currentFrameRate(){var e;return null===(e=this.session)||void 0===e?void 0:e.frameRate}get supportedFrameRates(){var e;return null===(e=this.session)||void 0===e?void 0:e.supportedFrameRates}updateTargetFrameRate(e){return this.session.updateTargetFrameRate(e)}runInXRFrame(e,t=!0){this.inXRFrameLoop?e():!this.inXRSession&&t||this.onXRFrameObservable.addOnce(e)}get isFixedFoveationSupported(){var e;return(null===(e=this._baseLayerWrapper)||void 0===e?void 0:e.isFixedFoveationSupported)||!1}get fixedFoveation(){var e;return(null===(e=this._baseLayerWrapper)||void 0===e?void 0:e.fixedFoveation)||null}set fixedFoveation(e){const t=Math.max(0,Math.min(1,e||0));this._baseLayerWrapper&&(this._baseLayerWrapper.fixedFoveation=t)}get enabledFeatures(){var e,t;return null!==(t=null===(e=this.session)||void 0===e?void 0:e.enabledFeatures)&&void 0!==t?t:null}}function Na(e){const t=e.height||2;let i=0===e.diameterTop?0:e.diameterTop||e.diameter||1,n=0===e.diameterBottom?0:e.diameterBottom||e.diameter||1;i=i||1e-5,n=n||1e-5;const s=e.tessellation||24,r=e.subdivisions||1,l=!!e.hasRings,h=!!e.enclose,c=0===e.cap?0:e.cap||ee.Kj.CAP_ALL,d=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,u=0===e.sideOrientation?0:e.sideOrientation||Qe.x.DEFAULTSIDE,p=e.faceUV||new Array(3),f=e.faceColors,_=2+(1+(1!==d&&h?2:0))*(l?r:1);let m;for(m=0;m<_;m++)f&&void 0===f[m]&&(f[m]=new a.HE(1,1,1,1));for(m=0;m<_;m++)p&&void 0===p[m]&&(p[m]=new o.Lt(0,0,1,1));const g=new Array,v=new Array,T=new Array,S=new Array,E=new Array,x=2*Math.PI*d/s;let b,C,y;const A=(n-i)/2/t,R=o.P.Zero(),P=o.P.Zero(),I=o.P.Zero(),M=o.P.Zero(),O=o.P.Zero(),D=L.RD.Y;let N,F,w,B=1,U=1,V=0,k=0;for(N=0;N<=r;N++)for(C=N/r,y=(C*(i-n)+n)/2,B=l&&0!==N&&N!==r?2:1,w=0;w{const r=e?i/2:n/2;if(0===r)return;let a,l,h;const c=e?p[_-1]:p[0];let u=null;f&&(u=e?f[_-1]:f[0]);const m=v.length/3,x=e?t/2:-t/2,b=new o.P(0,x,0);v.push(b.x,b.y,b.z),T.push(0,e?1:-1,0);const C=c.y+.5*(c.w-c.y);S.push(c.x+.5*(c.z-c.x),we.e.UseOpenGLOrientationForUV?1-C:C),u&&E.push(u.r,u.g,u.b,u.a);const y=new o.FM(.5,.5);for(h=0;h<=s;h++){a=2*Math.PI*h*d/s;const t=Math.cos(-a),i=Math.sin(-a);l=new o.P(t*r,x,i*r);const n=new o.FM(t*y.x+.5,i*y.y+.5);v.push(l.x,l.y,l.z),T.push(0,e?1:-1,0);const p=c.y+(c.w-c.y)*n.y;S.push(c.x+(c.z-c.x)*n.x,we.e.UseOpenGLOrientationForUV?1-p:p),u&&E.push(u.r,u.g,u.b,u.a)}for(h=0;h{void 0!==o&&o instanceof N.x||(void 0!==o&&(l=a||ee.Kj.DEFAULTSIDE,a=o),o=r,r=1);return Fa(e,{height:t,diameterTop:i,diameterBottom:n,tessellation:s,subdivisions:r,sideOrientation:l,updatable:a},o)};Qe.x.CreateTorus=wa,ee.Kj.CreateTorus=(e,t,i,n,s,r,o)=>La(e,{diameter:t,thickness:i,tessellation:n,sideOrientation:o,updatable:r},s),ee.Kj._GroundMeshParser=(e,t)=>Ba.Parse(e,t);class Ba extends ee.Kj{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=o.jp.Matrix[5];i.invertToRef(n);const s=o.jp.Vector3[8];if(o.P.TransformCoordinatesFromFloatsToRef(e,0,t,n,s),e=s.x,t=s.z,e=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const r=this._getFacetAt(e,t),a=-(r.x*e+r.z*t+r.w)/r.y;return o.P.TransformCoordinatesFromFloatsToRef(0,a,0,i,s),s.y}getNormalAtCoordinates(e,t){const i=new o.P(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const n=this.getWorldMatrix(),s=o.jp.Matrix[5];n.invertToRef(s);const r=o.jp.Vector3[8];if(o.P.TransformCoordinatesFromFloatsToRef(e,0,t,s,r),e=r.x,t=r.z,ethis._maxX||tthis._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const a=this._getFacetAt(e,t);return o.P.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),s=this._heightQuads[n*this._subdivisionsX+i];let r;return r=te.maxHeight){d=!0;const t=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=t}for(r=0;r<=e.subdivisions;r++)for(l=0;l<=e.subdivisions;l++){const t=new o.P(l*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-r)*e.height/e.subdivisions-e.height/2),a=4*(((t.x+e.width/2)/e.width*(e.bufferWidth-1)|0)+((1-(t.z+e.height/2)/e.height)*(e.bufferHeight-1)|0)*e.bufferWidth);let u=e.buffer[a]/255,p=e.buffer[a+1]/255,f=e.buffer[a+2]/255;const _=e.buffer[a+3]/255;d&&(u=1-u,p=1-p,f=1-f);const m=u*h.r+p*h.g+f*h.b;t.y=_>=c?e.minHeight+(e.maxHeight-e.minHeight)*m:e.minHeight-k.kn,i.push(t.x,t.y,t.z),n.push(0,0,0),s.push(l/e.subdivisions,1-r/e.subdivisions)}for(r=0;r=e.minHeight,c=i[3*s+1]>=e.minHeight,d=i[3*o+1]>=e.minHeight;h&&c&&d&&(t.push(n),t.push(s),t.push(o));i[3*a+1]>=e.minHeight&&h&&d&&(t.push(a),t.push(n),t.push(o))}Qe.x.ComputeNormals(i,t,n);const u=new Qe.x;return u.indices=t,u.positions=i,u.normals=n,u.uvs=s,u}function Ga(e,t={},i){const n=new Ba(e,i);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;return Ua(t).applyToMesh(n,t.updatable),n._setReady(!0),n}function za(e,t,i=null){const n=new ee.Kj(e,i);return Va(t).applyToMesh(n,t.updatable),n}function Wa(e,t,i={},n=null){const s=i.width||10,r=i.height||10,o=i.subdivisions||1,l=i.minHeight||0,h=i.maxHeight||1,c=i.colorFilter||new a.Wo(.3,.59,.11),d=i.alphaFilter||0,u=i.updatable,p=i.onReady;n=n||m.l.LastCreatedScene;const f=new Ba(e,n);f._subdivisionsX=o,f._subdivisionsY=o,f._width=s,f._height=r,f._maxX=f._width/2,f._maxZ=f._height/2,f._minX=-f._maxX,f._minZ=-f._maxZ,f._setReady(!1);return se.w1.LoadImage(t,(e=>{const t=e.width,i=e.height;if(n.isDisposed)return;const a=null==n?void 0:n.getEngine().resizeImageBitmap(e,t,i);ka({width:s,height:r,subdivisions:o,minHeight:l,maxHeight:h,colorFilter:c,buffer:a,bufferWidth:t,bufferHeight:i,alphaFilter:d}).applyToMesh(f,u),p&&p(f),f._setReady(!0)}),(()=>{}),n.offlineProvider),f}Qe.x.CreateGround=Ua,Qe.x.CreateTiledGround=Va,Qe.x.CreateGroundFromHeightMap=ka,ee.Kj.CreateGround=(e,t,i,n,s,r)=>Ga(e,{width:t,height:i,subdivisions:n,updatable:r},s),ee.Kj.CreateTiledGround=(e,t,i,n,s,r,o,a,l)=>za(e,{xmin:t,zmin:i,xmax:n,zmax:s,subdivisions:r,precision:o,updatable:l},a),ee.Kj.CreateGroundFromHeightMap=(e,t,i,n,s,r,o,a,l,h,c)=>Wa(e,t,{width:i,height:n,subdivisions:s,minHeight:r,maxHeight:o,updatable:l,onReady:h,alphaFilter:c},a);class Ha{constructor(e,t=null){if(this.scene=e,this._pointerDownOnMeshAsked=!1,this._isActionableMesh=!1,this._teleportationRequestInitiated=!1,this._teleportationBackRequestInitiated=!1,this._rotationRightAsked=!1,this._rotationLeftAsked=!1,this._dpadPressed=!0,this._activePointer=!1,this._id=Ha._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=La("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},e),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;const t=new _a("targetMat",e);t.specularColor=a.Wo.Black(),t.emissiveColor=new a.Wo(.7,.7,.7),t.backFaceCulling=!1,this._gazeTracker.material=t}}_getForwardRay(e){return new qe(o.P.Zero(),new o.P(0,0,e))}_selectionPointerDown(){this._pointerDownOnMeshAsked=!0,this._currentHit&&this.scene.simulatePointerDown(this._currentHit,{pointerId:this._id})}_selectionPointerUp(){this._currentHit&&this.scene.simulatePointerUp(this._currentHit,{pointerId:this._id}),this._pointerDownOnMeshAsked=!1}_activatePointer(){this._activePointer=!0}_deactivatePointer(){this._activePointer=!1}_updatePointerDistance(e=100){}dispose(){this._interactionsEnabled=!1,this._teleportationEnabled=!1,this._gazeTracker&&this._gazeTracker.dispose()}}Ha._IdCounter=0;class Xa extends Ha{constructor(e,t,i){super(t,i),this.webVRController=e,this._laserPointer=Fa("laserPointer",{updatable:!1,height:1,diameterTop:.004,diameterBottom:2e-4,tessellation:20,subdivisions:1},t);const n=new _a("laserPointerMat",t);if(n.emissiveColor=new a.Wo(.7,.7,.7),n.alpha=.6,this._laserPointer.material=n,this._laserPointer.rotation.x=Math.PI/2,this._laserPointer.position.z=-.5,this._laserPointer.isVisible=!1,this._laserPointer.isPickable=!1,!e.mesh){const i=new ee.Kj("preloadControllerMesh",t),n=new ee.Kj(Hn.POINTING_POSE,t);n.rotation.x=-.7,i.addChild(n),e.attachToMesh(i)}this._setLaserPointerParent(e.mesh),this._meshAttachedObserver=e._meshAttachedObservable.add((e=>{this._setLaserPointerParent(e)}))}_getForwardRay(e){return this.webVRController.getForwardRay(e)}_activatePointer(){super._activatePointer(),this._laserPointer.isVisible=!0}_deactivatePointer(){super._deactivatePointer(),this._laserPointer.isVisible=!1}_setLaserPointerColor(e){this._laserPointer.material.emissiveColor=e}_setLaserPointerLightingDisabled(e){this._laserPointer.material.disableLighting=e}_setLaserPointerParent(e){const t=e=>{e.isPickable=!1,e.getChildMeshes().forEach((e=>{t(e)}))};t(e);const i=e.getChildren(void 0,!1);let n=e;this.webVRController._pointingPoseNode=null;for(let s=0;s=0){n=i[s],this.webVRController._pointingPoseNode=n;break}this._laserPointer.parent=n}_updatePointerDistance(e=100){this._laserPointer.scaling.y=e,this._laserPointer.position.z=-e/2}dispose(){super.dispose(),this._laserPointer.dispose(),this._meshAttachedObserver&&this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver)}}class Ya extends Ha{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){const t=this._getCamera();return t?t.getForwardRay(e):new qe(o.P.Zero(),o.P.Forward())}}class ja{get onEnteringVR(){return this.onEnteringVRObservable}get onExitingVR(){return this.onExitingVRObservable}get onControllerMeshLoaded(){return this.onControllerMeshLoadedObservable}get teleportationTarget(){return this._teleportationTarget}set teleportationTarget(e){e&&(e.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=e)}get gazeTrackerMesh(){return this._cameraGazer._gazeTracker}set gazeTrackerMesh(e){e&&(this._cameraGazer._gazeTracker&&this._cameraGazer._gazeTracker.dispose(),this._leftController&&this._leftController._gazeTracker&&this._leftController._gazeTracker.dispose(),this._rightController&&this._rightController._gazeTracker&&this._rightController._gazeTracker.dispose(),this._cameraGazer._gazeTracker=e,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker",this._leftController&&(this._leftController._gazeTracker=this._cameraGazer._gazeTracker.clone("gazeTracker")),this._rightController&&(this._rightController._gazeTracker=this._cameraGazer._gazeTracker.clone("gazeTracker")))}get leftControllerGazeTrackerMesh(){return this._leftController?this._leftController._gazeTracker:null}get rightControllerGazeTrackerMesh(){return this._rightController?this._rightController._gazeTracker:null}get displayGaze(){return this._displayGaze}set displayGaze(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1,this._leftController&&(this._leftController._gazeTracker.isVisible=!1),this._rightController&&(this._rightController._gazeTracker.isVisible=!1))}get displayLaserPointer(){return this._displayLaserPointer}set displayLaserPointer(e){this._displayLaserPointer=e,e?(this._rightController&&this._rightController._activatePointer(),this._leftController&&this._leftController._activatePointer()):(this._rightController&&(this._rightController._deactivatePointer(),this._rightController._gazeTracker.isVisible=!1),this._leftController&&(this._leftController._deactivatePointer(),this._leftController._gazeTracker.isVisible=!1))}get deviceOrientationCamera(){return this._deviceOrientationCamera}get currentVRCamera(){return this._webVRready?this._webVRCamera:this._scene.activeCamera}get webVRCamera(){return this._webVRCamera}get vrDeviceOrientationCamera(){return this._vrDeviceOrientationCamera}get vrButton(){return this._btnVR}get _teleportationRequestInitiated(){return this._cameraGazer._teleportationRequestInitiated||null!==this._leftController&&this._leftController._teleportationRequestInitiated||null!==this._rightController&&this._rightController._teleportationRequestInitiated}constructor(e,t={}){this.webVROptions=t,this._webVRsupported=!1,this._webVRready=!1,this._webVRrequesting=!1,this._webVRpresenting=!1,this._fullscreenVRpresenting=!1,this.enableGazeEvenWhenNoPointerLock=!1,this.exitVROnDoubleTap=!0,this.onEnteringVRObservable=new r.y$,this.onAfterEnteringVRObservable=new r.y$,this.onExitingVRObservable=new r.y$,this.onControllerMeshLoadedObservable=new r.y$,this._useCustomVRButton=!1,this._teleportationRequested=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=ja.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new o.P(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new o.P(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._leftController=null,this._rightController=null,this._gazeColor=new a.Wo(.7,.7,.7),this._laserColor=new a.Wo(.7,.7,.7),this._pickedLaserColor=new a.Wo(.2,.2,1),this._pickedGazeColor=new a.Wo(0,0,1),this.onNewMeshSelected=new r.y$,this.onMeshSelectedWithController=new r.y$,this.onNewMeshPicked=new r.y$,this.onBeforeCameraTeleport=new r.y$,this.onAfterCameraTeleport=new r.y$,this.onSelectedMeshUnselected=new r.y$,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._interactionsRequested=!1,this._displayGaze=!0,this._displayLaserPointer=!0,this.updateGazeTrackerScale=!0,this.updateGazeTrackerColor=!0,this.updateControllerLaserColor=!0,this.requestPointerLockOnFullScreen=!0,this.xrTestDone=!1,this._onResize=()=>{this._moveButtonToBottomRight(),this._fullscreenVRpresenting&&this._webVRready&&this.exitVR()},this._onFullscreenChange=()=>{this._fullscreenVRpresenting=!!document.fullscreenElement,!this._fullscreenVRpresenting&&this._inputElement&&(this.exitVR(),!this._useCustomVRButton&&this._btnVR&&(this._btnVR.style.top=this._inputElement.offsetTop+this._inputElement.offsetHeight-70+"px",this._btnVR.style.left=this._inputElement.offsetLeft+this._inputElement.offsetWidth-100+"px",this._updateButtonVisibility()))},this._cachedAngularSensibility={angularSensibilityX:null,angularSensibilityY:null,angularSensibility:null},this._beforeRender=()=>{this._leftController&&this._leftController._activePointer&&this._castRayAndSelectObject(this._leftController),this._rightController&&this._rightController._activePointer&&this._castRayAndSelectObject(this._rightController),this._noControllerIsActive&&(this._scene.getEngine().isPointerLock||this.enableGazeEvenWhenNoPointerLock)?this._castRayAndSelectObject(this._cameraGazer):this._cameraGazer._gazeTracker.isVisible=!1},this._onNewGamepadConnected=e=>{if(e.type!==tn.POSE_ENABLED)e.leftStick&&e.onleftstickchanged((e=>{this._teleportationInitialized&&this.teleportationEnabled&&(!this._leftController&&!this._rightController||this._leftController&&!this._leftController._activePointer&&this._rightController&&!this._rightController._activePointer)&&(this._checkTeleportWithRay(e,this._cameraGazer),this._checkTeleportBackwards(e,this._cameraGazer))})),e.rightStick&&e.onrightstickchanged((e=>{this._teleportationInitialized&&this._checkRotate(e,this._cameraGazer)})),e.type===tn.XBOX&&(e.onbuttondown((e=>{this._interactionsEnabled&&e===An.A&&this._cameraGazer._selectionPointerDown()})),e.onbuttonup((e=>{this._interactionsEnabled&&e===An.A&&this._cameraGazer._selectionPointerUp()})));else{const t=e,i=new Xa(t,this._scene,this._cameraGazer._gazeTracker);"right"===t.hand||this._leftController&&this._leftController.webVRController!=t?this._rightController=i:this._leftController=i,this._tryEnableInteractionOnController(i)}},this._tryEnableInteractionOnController=e=>{this._interactionsRequested&&!e._interactionsEnabled&&this._enableInteractionOnController(e),this._teleportationRequested&&!e._teleportationEnabled&&this._enableTeleportationOnController(e)},this._onNewGamepadDisconnected=e=>{e instanceof Fs&&("left"===e.hand&&null!=this._leftController&&(this._leftController.dispose(),this._leftController=null),"right"===e.hand&&null!=this._rightController&&(this._rightController.dispose(),this._rightController=null))},this._workingVector=o.P.Zero(),this._workingQuaternion=o._f.Identity(),this._workingMatrix=o.y3.Identity(),p.Y.Warn("WebVR is deprecated. Please avoid using this experience helper and use the WebXR experience helper instead"),this._scene=e,this._inputElement=e.getEngine().getInputElement();if("getVRDisplays"in navigator||void 0!==t.useXR||(t.useXR=!0),void 0===t.createFallbackVRDeviceOrientationFreeCamera&&(t.createFallbackVRDeviceOrientationFreeCamera=!0),void 0===t.createDeviceOrientationCamera&&(t.createDeviceOrientationCamera=!0),void 0===t.laserToggle&&(t.laserToggle=!0),void 0===t.defaultHeight&&(t.defaultHeight=1.7),t.useCustomVRButton&&(this._useCustomVRButton=!0,t.customVRButton&&(this._btnVR=t.customVRButton)),t.rayLength&&(this._rayLength=t.rayLength),this._defaultHeight=t.defaultHeight,t.positionScale&&(this._rayLength*=t.positionScale,this._defaultHeight*=t.positionScale),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new o.P(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new Bn("deviceOrientationVRHelper",this._position.clone(),e),this._scene.activeCamera&&(this._deviceOrientationCamera.minZ=this._scene.activeCamera.minZ,this._deviceOrientationCamera.maxZ=this._scene.activeCamera.maxZ,this._scene.activeCamera instanceof Nn&&this._scene.activeCamera.rotation)){const e=this._scene.activeCamera;e.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(e.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(o._f.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z)),this._deviceOrientationCamera.rotation=e.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._inputElement&&this._scene.activeCamera.attachControl()}else this._existingCamera=this._scene.activeCamera;this.webVROptions.useXR&&navigator.xr?Da.IsSessionSupportedAsync("immersive-vr").then((i=>{i?(p.Y.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),e.createDefaultXRExperienceAsync({floorMeshes:t.floorMeshes||[]}).then((t=>{this.xr=t,this.xrTestDone=!0,this._cameraGazer=new Ya((()=>this.xr.baseExperience.camera),e),this.xr.baseExperience.onStateChangedObservable.add((e=>{switch(e){case Ea.ENTERING_XR:this.onEnteringVRObservable.notifyObservers(this),this._interactionsEnabled||this.xr.pointerSelection.detach(),this.xr.pointerSelection.displayLaserPointer=this._displayLaserPointer;break;case Ea.EXITING_XR:this.onExitingVRObservable.notifyObservers(this),this._scene.getEngine().resize();break;case Ea.IN_XR:this._hasEnteredVR=!0;break;case Ea.NOT_IN_XR:this._hasEnteredVR=!1}}))}))):this._completeVRInit(e,t)})):this._completeVRInit(e,t)}_completeVRInit(e,t){if(this.xrTestDone=!0,t.createFallbackVRDeviceOrientationFreeCamera&&(t.useMultiview&&(t.vrDeviceOrientationCameraMetrics||(t.vrDeviceOrientationCameraMetrics=gs.GetDefault()),t.vrDeviceOrientationCameraMetrics.multiviewEnabled=!0),this._vrDeviceOrientationCamera=new Is("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._webVRCamera=new Ns("WebVRHelper",this._position,this._scene,t),this._webVRCamera.useStandingMatrix(),this._cameraGazer=new Ya((()=>this.currentVRCamera),e),!this._useCustomVRButton){this._btnVR=document.createElement("BUTTON"),this._btnVR.className="babylonVRicon",this._btnVR.id="babylonVRiconbtn",this._btnVR.title="Click to switch to VR";let e=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A":"https://cdn.babylonjs.com/Assets/vrButton.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";e+=".babylonVRicon.vrdisplaypresenting { display: none; }";const t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),this._moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",(()=>{this.isInVRMode?this._scene.getEngine().disableVR():this.enterVR()}));const i=this._scene.getEngine().getHostWindow();i&&(i.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),t.createFallbackVRDeviceOrientationFreeCamera?this._displayVRButton():this._scene.getEngine().onVRDisplayChangedObservable.add((e=>{e.vrDisplay&&this._displayVRButton()})),this._onKeyDown=e=>{27===e.keyCode&&this.isInVRMode&&this.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add((()=>{this._hasEnteredVR&&this.exitVROnDoubleTap&&(this.exitVR(),this._fullscreenVRpresenting&&this._scene.getEngine().exitFullscreen())}),We.kD.POINTERDOUBLETAP,!1),this._onVRDisplayChangedBind=e=>this._onVRDisplayChanged(e),this._onVrDisplayPresentChangeBind=()=>this._onVrDisplayPresentChange(),this._onVRRequestPresentStart=()=>{this._webVRrequesting=!0,this._updateButtonVisibility()},this._onVRRequestPresentComplete=()=>{this._webVRrequesting=!1,this._updateButtonVisibility()},e.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChangedBind),e.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart),e.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete),i.addEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChangeBind),e.onDisposeObservable.add((()=>{this.dispose()})),this._webVRCamera.onControllerMeshLoadedObservable.add((e=>this._onDefaultMeshLoaded(e))),this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected),this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected),this._updateButtonVisibility(),this._circleEase=new j,this._circleEase.setEasingMode(Y.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add((t=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&"mouse"===t.event.pointerType&&(t.type===We.kD.POINTERDOWN?this._cameraGazer._selectionPointerDown():t.type===We.kD.POINTERUP&&this._cameraGazer._selectionPointerUp())})),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes}))}_onDefaultMeshLoaded(e){this._leftController&&this._leftController.webVRController==e&&e.mesh&&this._leftController._setLaserPointerParent(e.mesh),this._rightController&&this._rightController.webVRController==e&&e.mesh&&this._rightController._setLaserPointerParent(e.mesh);try{this.onControllerMeshLoadedObservable.notifyObservers(e)}catch(t){p.Y.Warn("Error in your custom logic onControllerMeshLoaded: "+t)}}get isInVRMode(){return this.xr&&this.webVROptions.useXR&&this.xr.baseExperience.state===Ea.IN_XR||this._webVRpresenting||this._fullscreenVRpresenting}_onVrDisplayPresentChange(){const e=this._scene.getEngine().getVRDevice();if(e){const t=this._webVRpresenting;this._webVRpresenting=e.isPresenting,t&&!this._webVRpresenting&&this.exitVR()}else p.Y.Warn("Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?");this._updateButtonVisibility()}_onVRDisplayChanged(e){this._webVRsupported=e.vrSupported,this._webVRready=!!e.vrDisplay,this._webVRpresenting=e.vrDisplay&&e.vrDisplay.isPresenting,this._updateButtonVisibility()}_moveButtonToBottomRight(){if(this._inputElement&&!this._useCustomVRButton&&this._btnVR){const e=this._inputElement.getBoundingClientRect();this._btnVR.style.top=e.top+e.height-70+"px",this._btnVR.style.left=e.left+e.width-100+"px"}}_displayVRButton(){this._useCustomVRButton||this._btnVRDisplayed||!this._btnVR||(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)}_updateButtonVisibility(){this._btnVR&&!this._useCustomVRButton&&(this._btnVR.className="babylonVRicon",this.isInVRMode?this._btnVR.className+=" vrdisplaypresenting":(this._webVRready&&(this._btnVR.className+=" vrdisplayready"),this._webVRsupported&&(this._btnVR.className+=" vrdisplaysupported"),this._webVRrequesting&&(this._btnVR.className+=" vrdisplayrequesting")))}enterVR(){if(this.xr)this.xr.baseExperience.enterXRAsync("immersive-vr","local-floor",this.xr.renderTarget);else{if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(e){p.Y.Warn("Error in your custom logic onEnteringVR: "+e)}if(this._scene.activeCamera){if(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=o._f.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),this.vrDeviceOrientationCamera.angularSensibility=2e3),this.webVRCamera){const e=this.webVRCamera.deviceRotationQuaternion.toEulerAngles().y,t=o._f.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles().y-e,i=this.webVRCamera.rotationQuaternion.toEulerAngles().y;this.webVRCamera.rotationQuaternion=o._f.FromEulerAngles(0,i+t,0)}this._existingCamera=this._scene.activeCamera,this._existingCamera.angularSensibilityX&&(this._cachedAngularSensibility.angularSensibilityX=this._existingCamera.angularSensibilityX,this._existingCamera.angularSensibilityX=Number.MAX_VALUE),this._existingCamera.angularSensibilityY&&(this._cachedAngularSensibility.angularSensibilityY=this._existingCamera.angularSensibilityY,this._existingCamera.angularSensibilityY=Number.MAX_VALUE),this._existingCamera.angularSensibility&&(this._cachedAngularSensibility.angularSensibility=this._existingCamera.angularSensibility,this._existingCamera.angularSensibility=Number.MAX_VALUE)}this._webVRrequesting||(this._webVRready?this._webVRpresenting||(this._scene.getEngine().onVRRequestPresentComplete.addOnce((e=>{this.onAfterEnteringVRObservable.notifyObservers({success:e})})),this._webVRCamera.position=this._position,this._scene.activeCamera=this._webVRCamera):this._vrDeviceOrientationCamera&&(this._vrDeviceOrientationCamera.position=this._position,this._scene.activeCamera&&(this._vrDeviceOrientationCamera.minZ=this._scene.activeCamera.minZ),this._scene.activeCamera=this._vrDeviceOrientationCamera,this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen),this._updateButtonVisibility(),this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce((()=>{this.onAfterEnteringVRObservable.notifyObservers({success:!0})}))),this._scene.activeCamera&&this._inputElement&&this._scene.activeCamera.attachControl(),this._interactionsEnabled&&this._scene.registerBeforeRender(this._beforeRender),this._displayLaserPointer&&[this._leftController,this._rightController].forEach((e=>{e&&e._activatePointer()})),this._hasEnteredVR=!0)}}exitVR(){if(this.xr)this.xr.baseExperience.exitXRAsync();else if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){p.Y.Warn("Error in your custom logic onExitingVR: "+e)}this._webVRpresenting&&this._scene.getEngine().disableVR(),this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone()),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._deviceOrientationCamera?(this._deviceOrientationCamera.position=this._position,this._scene.activeCamera=this._deviceOrientationCamera,this._cachedAngularSensibility.angularSensibilityX&&(this._deviceOrientationCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._deviceOrientationCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._deviceOrientationCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)):this._existingCamera&&(this._existingCamera.position=this._position,this._scene.activeCamera=this._existingCamera,this._inputElement&&this._scene.activeCamera.attachControl(),this._cachedAngularSensibility.angularSensibilityX&&(this._existingCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._existingCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._existingCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)),this._updateButtonVisibility(),this._interactionsEnabled&&(this._scene.unregisterBeforeRender(this._beforeRender),this._cameraGazer._gazeTracker.isVisible=!1,this._leftController&&(this._leftController._gazeTracker.isVisible=!1),this._rightController&&(this._rightController._gazeTracker.isVisible=!1)),this._scene.getEngine().resize(),[this._leftController,this._rightController].forEach((e=>{e&&e._deactivatePointer()})),this._hasEnteredVR=!1;const t=this._scene.getEngine();t._onVrDisplayPresentChange&&t._onVrDisplayPresentChange()}}get position(){return this._position}set position(e){this._position=e,this._scene.activeCamera&&(this._scene.activeCamera.position=e)}enableInteractions(){if(!this._interactionsEnabled){if(this._interactionsRequested=!0,this.xr)return void(this.xr.baseExperience.state===Ea.IN_XR&&this.xr.pointerSelection.attach());this._leftController&&this._enableInteractionOnController(this._leftController),this._rightController&&this._enableInteractionOnController(this._rightController),this.raySelectionPredicate=e=>e.isVisible&&(e.isPickable||e.name===this._floorMeshName),this.meshSelectionPredicate=()=>!0,this._raySelectionPredicate=e=>!!(this._isTeleportationFloor(e)||-1===e.name.indexOf("gazeTracker")&&-1===e.name.indexOf("teleportationTarget")&&-1===e.name.indexOf("torusTeleportation"))&&this.raySelectionPredicate(e),this._interactionsEnabled=!0}}get _noControllerIsActive(){return!(this._leftController&&this._leftController._activePointer||this._rightController&&this._rightController._activePointer)}_isTeleportationFloor(e){for(let t=0;t-1||this._floorMeshesCollection.push(e))}removeFloorMesh(e){if(!this._floorMeshesCollection)return;const t=this._floorMeshesCollection.indexOf(e);-1!==t&&this._floorMeshesCollection.splice(t,1)}enableTeleportation(e={}){if(!this._teleportationInitialized){if(this._teleportationRequested=!0,this.enableInteractions(),this.webVROptions.useXR&&(e.floorMeshes||e.floorMeshName)){const t=e.floorMeshes||[];if(!t.length){const i=this._scene.getMeshByName(e.floorMeshName);i&&t.push(i)}if(this.xr)return t.forEach((e=>{this.xr.teleportation.addFloorMesh(e)})),void(this.xr.teleportation.attached||this.xr.teleportation.attach());if(!this.xrTestDone){const t=()=>{this.xrTestDone&&(this._scene.unregisterBeforeRender(t),this.xr?this.xr.teleportation.attached||this.xr.teleportation.attach():this.enableTeleportation(e))};return void this._scene.registerBeforeRender(t)}}e.floorMeshName&&(this._floorMeshName=e.floorMeshName),e.floorMeshes&&(this._floorMeshesCollection=e.floorMeshes),e.teleportationMode&&(this._teleportationMode=e.teleportationMode),e.teleportationTime&&e.teleportationTime>0&&(this._teleportationTime=e.teleportationTime),e.teleportationSpeed&&e.teleportationSpeed>0&&(this._teleportationSpeed=e.teleportationSpeed),void 0!==e.easingFunction&&(this._teleportationEasing=e.easingFunction),null!=this._leftController&&this._enableTeleportationOnController(this._leftController),null!=this._rightController&&this._enableTeleportationOnController(this._rightController);const t=new ii.$;t.vignetteColor=new a.HE(0,0,0,0),t.vignetteEnabled=!0,this._postProcessMove=new Ta("postProcessMove",1,this._webVRCamera,void 0,void 0,void 0,void 0,t),this._webVRCamera.detachPostProcess(this._postProcessMove),this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&(this._createTeleportationCircles(),this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor))}}_enableInteractionOnController(e){e.webVRController.mesh&&(e._interactionsEnabled=!0,this.isInVRMode&&this._displayLaserPointer&&e._activatePointer(),this.webVROptions.laserToggle&&e.webVRController.onMainButtonStateChangedObservable.add((t=>{this._displayLaserPointer&&1===t.value&&(e._activePointer?e._deactivatePointer():e._activatePointer(),this.displayGaze&&(e._gazeTracker.isVisible=e._activePointer))})),e.webVRController.onTriggerStateChangedObservable.add((t=>{let i=e;this._noControllerIsActive&&(i=this._cameraGazer),i._pointerDownOnMeshAsked?t.valuethis._padSensibilityUp&&i._selectionPointerDown()})))}_checkTeleportWithRay(e,t){this._teleportationRequestInitiated&&!t._teleportationRequestInitiated||(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.xthis._padSensibilityUp&&t._dpadPressed&&(t._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))}_checkTeleportBackwards(e,t){if(!t._teleportationRequestInitiated)if(e.y>this._padSensibilityUp&&t._dpadPressed){if(!t._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;let e=o._f.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),i=this.currentVRCamera.position;this.currentVRCamera.devicePosition&&this.currentVRCamera.deviceRotationQuaternion&&(e=this.currentVRCamera.deviceRotationQuaternion,i=this.currentVRCamera.devicePosition),e.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,o._f.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),o.P.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);const n=new qe(i,this._workingVector),s=this._scene.pickWithRay(n,this._raySelectionPredicate);s&&s.pickedPoint&&s.pickedMesh&&this._isTeleportationFloor(s.pickedMesh)&&s.distance<5&&this.teleportCamera(s.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1}_enableTeleportationOnController(e){e.webVRController.mesh&&(e._interactionsEnabled||this._enableInteractionOnController(e),e._interactionsEnabled=!0,e._teleportationEnabled=!0,e.webVRController.controllerType===yn.VIVE&&(e._dpadPressed=!1,e.webVRController.onPadStateChangedObservable.add((t=>{e._dpadPressed=t.pressed,e._dpadPressed||(e._rotationLeftAsked=!1,e._rotationRightAsked=!1,e._teleportationBackRequestInitiated=!1)}))),e.webVRController.onPadValuesChangedObservable.add((t=>{this.teleportationEnabled&&(this._checkTeleportBackwards(t,e),this._checkTeleportWithRay(t,e)),this._checkRotate(t,e)})))}_createTeleportationCircles(){this._teleportationTarget=Ga("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;const e=new ma("DynamicTexture",512,this._scene,!0);e.hasAlpha=!0;const t=e.getContext();t.beginPath(),t.arc(256,256,200,0,2*Math.PI,!1),t.fillStyle=this._teleportationFillColor,t.fill(),t.lineWidth=10,t.strokeStyle=this._teleportationBorderColor,t.stroke(),t.closePath(),e.update();const i=new _a("TextPlaneMaterial",this._scene);i.diffuseTexture=e,this._teleportationTarget.material=i;const n=La("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);n.isPickable=!1,n.parent=this._teleportationTarget;const s=new A("animationInnerCircle","position.y",30,A.ANIMATIONTYPE_FLOAT,A.ANIMATIONLOOPMODE_CYCLE),r=[];r.push({frame:0,value:0}),r.push({frame:30,value:.4}),r.push({frame:60,value:0}),s.setKeys(r);const o=new q;o.setEasingMode(Y.EASINGMODE_EASEINOUT),s.setEasingFunction(o),n.animations=[],n.animations.push(s),this._scene.beginAnimation(n,0,60,!0),this._hideTeleportationTarget()}_displayTeleportationTarget(){this._teleportActive=!0,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!0,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!0))}_hideTeleportationTarget(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))}_rotateCamera(e){if(!(this.currentVRCamera instanceof Fn))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];const t=o._f.FromRotationMatrix(o.y3.RotationY(Math.PI/4*this._rotationAngle)),i=new A("animationRotation","rotationQuaternion",90,A.ANIMATIONTYPE_QUATERNION,A.ANIMATIONLOOPMODE_CONSTANT),n=[];n.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),n.push({frame:6,value:t}),i.setKeys(n),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];const s=new A("animationPP","vignetteWeight",90,A.ANIMATIONTYPE_FLOAT,A.ANIMATIONLOOPMODE_CONSTANT),r=[];r.push({frame:0,value:0}),r.push({frame:3,value:4}),r.push({frame:6,value:0}),s.setKeys(r),s.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(s);const a=new A("animationPP2","vignetteStretch",90,A.ANIMATIONTYPE_FLOAT,A.ANIMATIONLOOPMODE_CONSTANT),l=[];l.push({frame:0,value:0}),l.push({frame:3,value:10}),l.push({frame:6,value:0}),a.setKeys(l),a.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(a),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._postProcessMove.samples=4,this._webVRCamera.attachPostProcess(this._postProcessMove),this._scene.beginAnimation(this._postProcessMove,0,6,!1,1,(()=>{this._webVRCamera.detachPostProcess(this._postProcessMove)})),this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}_moveTeleportationSelectorTo(e,t,i){if(e.pickedPoint){t._teleportationRequestInitiated&&(this._displayTeleportationTarget(),this._haloCenter.copyFrom(e.pickedPoint),this._teleportationTarget.position.copyFrom(e.pickedPoint));const n=this._convertNormalToDirectionOfRay(e.getNormal(!0,!1),i);if(n){const e=o.P.Cross(L.RD.Y,n),t=o.P.Cross(n,e);o.P.RotationFromAxisToRef(t,n,e,this._teleportationTarget.rotation)}this._teleportationTarget.position.y+=.1}}teleportCamera(e){if(!(this.currentVRCamera instanceof Fn))return;this.webVRCamera.leftCamera?(this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition),this._workingVector.subtractInPlace(this.webVRCamera.position),e.subtractToRef(this._workingVector,this._workingVector)):this._workingVector.copyFrom(e),this.isInVRMode?this._workingVector.y+=this.webVRCamera.deviceDistanceToRoomGround()*this._webVRCamera.deviceScaleFactor:this._workingVector.y+=this._defaultHeight,this.onBeforeCameraTeleport.notifyObservers(this._workingVector);let t,i;if(this._teleportationMode==ja.TELEPORTATIONMODE_CONSTANTSPEED){i=90;const e=o.P.Distance(this.currentVRCamera.position,this._workingVector);t=this._teleportationSpeed/e}else i=Math.round(90*this._teleportationTime/1e3),t=1;this.currentVRCamera.animations=[];const n=new A("animationCameraTeleportation","position",90,A.ANIMATIONTYPE_VECTOR3,A.ANIMATIONLOOPMODE_CONSTANT),s=[{frame:0,value:this.currentVRCamera.position},{frame:i,value:this._workingVector}];n.setKeys(s),n.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(n),this._postProcessMove.animations=[];const r=Math.round(i/2),a=new A("animationPP","vignetteWeight",90,A.ANIMATIONTYPE_FLOAT,A.ANIMATIONLOOPMODE_CONSTANT),l=[];l.push({frame:0,value:0}),l.push({frame:r,value:8}),l.push({frame:i,value:0}),a.setKeys(l),this._postProcessMove.animations.push(a);const h=new A("animationPP2","vignetteStretch",90,A.ANIMATIONTYPE_FLOAT,A.ANIMATIONLOOPMODE_CONSTANT),c=[];c.push({frame:0,value:0}),c.push({frame:r,value:10}),c.push({frame:i,value:0}),h.setKeys(c),this._postProcessMove.animations.push(h),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._webVRCamera.attachPostProcess(this._postProcessMove),this._scene.beginAnimation(this._postProcessMove,0,i,!1,t,(()=>{this._webVRCamera.detachPostProcess(this._postProcessMove)})),this._scene.beginAnimation(this.currentVRCamera,0,i,!1,t,(()=>{this.onAfterCameraTeleport.notifyObservers(this._workingVector)})),this._hideTeleportationTarget()}_convertNormalToDirectionOfRay(e,t){if(e){Math.acos(o.P.Dot(e,t.direction))l){const e=l;l=a,a=e}return a>0&&a0&&l=0))}_canDoCollision(e,t,i,n){const s=o.P.Distance(this._basePointWorld,e),r=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(s>this._velocityWorldLength+r+t)&&!!((e,t,i,n)=>!(e.x>i.x+n||i.x-n>t.x||e.y>i.y+n||i.y-n>t.y||e.z>i.z+n||i.z-n>t.z))(i,n,this._basePointWorld,this._velocityWorldLength+r)}_testTriangle(e,t,i,n,s,r,a){let l,h=!1;t||(t=[]),t[e]||(t[e]=new Me.J(0,0,0,0),t[e].copyFromPoints(i,n,s));const c=t[e];if(!r&&!c.isFrontFacingTo(this._normalizedVelocity,0))return;const d=c.signedDistanceTo(this._basePoint),u=o.P.Dot(c.normal,this._velocity);if(qa.DoubleSidedCheck&&u>1e-4)return;if(0==u){if(Math.abs(d)>=1)return;h=!0,l=0}else{l=(-1-d)/u;let e=(1-d)/u;if(l>e){const t=e;e=l,l=t}if(l>1||e<0)return;l<0&&(l=0),l>1&&(l=1)}this._collisionPoint.copyFromFloats(0,0,0);let p=!1,f=1;if(h||(this._basePoint.subtractToRef(c.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(l,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,i,n,s,c.normal)&&(p=!0,f=l,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!p){let e=this._velocitySquaredLength;this._basePoint.subtractToRef(i,this._tempVector);let t=2*o.P.Dot(this._velocity,this._tempVector),r=this._tempVector.lengthSquared()-1,a=Ka(e,t,r,f);a.found&&(f=a.root,p=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(n,this._tempVector),t=2*o.P.Dot(this._velocity,this._tempVector),r=this._tempVector.lengthSquared()-1,a=Ka(e,t,r,f),a.found&&(f=a.root,p=!0,this._collisionPoint.copyFrom(n)),this._basePoint.subtractToRef(s,this._tempVector),t=2*o.P.Dot(this._velocity,this._tempVector),r=this._tempVector.lengthSquared()-1,a=Ka(e,t,r,f),a.found&&(f=a.root,p=!0,this._collisionPoint.copyFrom(s)),n.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);let l=this._edge.lengthSquared(),h=o.P.Dot(this._edge,this._velocity),c=o.P.Dot(this._edge,this._baseToVertex);if(e=l*-this._velocitySquaredLength+h*h,t=2*(l*o.P.Dot(this._velocity,this._baseToVertex)-h*c),r=l*(1-this._baseToVertex.lengthSquared())+c*c,a=Ka(e,t,r,f),a.found){const e=(h*a.root-c)/l;e>=0&&e<=1&&(f=a.root,p=!0,this._edge.scaleInPlace(e),i.addToRef(this._edge,this._collisionPoint))}if(s.subtractToRef(n,this._edge),n.subtractToRef(this._basePoint,this._baseToVertex),l=this._edge.lengthSquared(),h=o.P.Dot(this._edge,this._velocity),c=o.P.Dot(this._edge,this._baseToVertex),e=l*-this._velocitySquaredLength+h*h,t=2*(l*o.P.Dot(this._velocity,this._baseToVertex)-h*c),r=l*(1-this._baseToVertex.lengthSquared())+c*c,a=Ka(e,t,r,f),a.found){const e=(h*a.root-c)/l;e>=0&&e<=1&&(f=a.root,p=!0,this._edge.scaleInPlace(e),n.addToRef(this._edge,this._collisionPoint))}if(i.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),l=this._edge.lengthSquared(),h=o.P.Dot(this._edge,this._velocity),c=o.P.Dot(this._edge,this._baseToVertex),e=l*-this._velocitySquaredLength+h*h,t=2*(l*o.P.Dot(this._velocity,this._baseToVertex)-h*c),r=l*(1-this._baseToVertex.lengthSquared())+c*c,a=Ka(e,t,r,f),a.found){const e=(h*a.root-c)/l;e>=0&&e<=1&&(f=a.root,p=!0,this._edge.scaleInPlace(e),s.addToRef(this._edge,this._collisionPoint))}}if(p){const e=f*f*this._velocitySquaredLength;(!this.collisionFound||e=n)return void s.copyFrom(e);const a=r?r.collisionMask:i.collisionMask;i._initialize(e,t,o);const l=r&&r.surroundingMeshes||this._scene.meshes;for(let h=0;hnew $a;i(7901);var Qa,Za=i(3525);class Ja{constructor(e,t,i,n=""){var s,o;let a;this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new r.y$,this.onErrorObservable=new r.y$,this.onBindObservable=new r.y$,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=Qt.x.WGSL,this.name=e,this._key=n,this._engine=i,this.uniqueId=Ja._UniqueIdSeed++,this.defines=null!==(s=t.defines)&&void 0!==s?s:"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=null!==(o=t.entryPoint)&&void 0!==o?o:"main",this._shaderStore=Ht.v.GetShadersStore(this._shaderLanguage),this._shaderRepository=Ht.v.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=Ht.v.GetIncludesShadersStore(this._shaderLanguage);const l=(0,_e.CG)()?this._engine.getHostDocument():null;e.computeSource?a="source:"+e.computeSource:e.computeElement?(a=l?l.getElementById(e.computeElement):null,a||(a=e.computeElement)):a=e.compute||e;const h={defines:this.defines.split("\n"),indexParameters:void 0,isFragment:!1,shouldUseHighPrecisionShader:!1,processor:null,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:this._shaderRepository,includesShadersStore:this._includeShaderStore,version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:null,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer};this._loadShader(a,"Compute","",(i=>{Za.L.Initialize(h),Za.L.PreProcess(i,h,(n=>{this._rawComputeSourceCode=i,t.processFinalCode&&(n=t.processFinalCode(n));const s=Za.L.Finalize(n,"",h);this._useFinalCode(s.vertexCode,e)}),this._engine)}))}_useFinalCode(e,t){if(t){const i=t.computeElement||t.compute||t.spectorName||t;this._computeSourceCode="//#define SHADER_NAME compute:"+i+"\n"+e}else this._computeSourceCode=e;this._prepareEffect()}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch(e){return!1}}_isReadyInternal(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getCompilationError(){return this._compilationError}executeWhenCompiled(e){this.isReady()?e(this):(this.onCompileObservable.add((t=>{e(t)})),this._pipelineContext&&!this._pipelineContext.isAsync||setTimeout((()=>{this._checkIsReady(null)}),16))}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){return void this._processCompilationErrors(t,e)}setTimeout((()=>{this._checkIsReady(e)}),16)}_loadShader(e,t,i,n){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement){return void n((0,_e.v)(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)))}if(this._shaderStore[e+t+"Shader"])return void n(this._shaderStore[e+t+"Shader"]);if(i&&this._shaderStore[e+i+"Shader"])return void n(this._shaderStore[e+i+"Shader"]);let s;s="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:this._shaderRepository+e,this._engine._loadFile(s+"."+t.toLowerCase()+".fx",n)}get computeSourceCode(){var e,t;return this._computeSourceCodeOverride?this._computeSourceCodeOverride:null!==(t=null===(e=this._pipelineContext)||void 0===e?void 0:e._getComputeShaderCode())&&void 0!==t?t:this._computeSourceCode}get rawComputeSourceCode(){return this._rawComputeSourceCode}_prepareEffect(){const e=this.defines,t=this._pipelineContext;this._isReady=!1;try{const i=this._engine;this._pipelineContext=i.createComputePipelineContext(),this._pipelineContext._name=this._key,i._prepareComputePipelineContext(this._pipelineContext,this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._computeSourceCode,this._rawComputeSourceCode,this._computeSourceCodeOverride?null:e,this._entryPoint),i._executeWhenComputeStateIsCompiled(this._pipelineContext,(()=>{this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),t&&this.getEngine()._deleteComputePipelineContext(t)})),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(i){this._processCompilationErrors(i,t)}}_getShaderCodeAndErrorLine(e,t){const i=/COMPUTE SHADER ERROR: 0:(\d+?):/;let n=null;if(t&&e){const s=t.match(i);if(s&&2===s.length){const t=parseInt(s[1]),i=e.split("\n",-1);i.length>=t&&(n=`Offending line [${t}] in compute code: ${i[t-1]}`)}}return[e,n]}_processCompilationErrors(e,t=null){var i;if(this._compilationError=e.message,p.Y.Error("Unable to compile compute effect:"),p.Y.Error("Defines:\r\n"+this.defines),Ja.LogShaderCodeOnCompilationError){let e=null,t=null;(null===(i=this._pipelineContext)||void 0===i?void 0:i._getComputeShaderCode())&&([t,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getComputeShaderCode(),this._compilationError),t&&(p.Y.Error("Compute code:"),p.Y.Error(t))),e&&p.Y.Error(e)}p.Y.Error("Error: "+this._compilationError),t&&(this._pipelineContext=t,this._isReady=!0,this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this))}dispose(){this._pipelineContext&&this._pipelineContext.dispose(),this._engine._releaseComputeEffect(this)}static RegisterShader(e,t){Ht.v.GetShadersStore(Qt.x.WGSL)[`${e}ComputeShader`]=t}}Ja._UniqueIdSeed=0,Ja.LogShaderCodeOnCompilationError=!0,function(e){e[e.Texture=0]="Texture",e[e.StorageTexture=1]="StorageTexture",e[e.UniformBuffer=2]="UniformBuffer",e[e.StorageBuffer=3]="StorageBuffer",e[e.TextureWithoutSampler=4]="TextureWithoutSampler",e[e.Sampler=5]="Sampler"}(Qa||(Qa={})),Ue.B.prototype.createComputeEffect=function(e,t){throw new Error("createComputeEffect: This engine does not support compute shaders!")},Ue.B.prototype.createComputePipelineContext=function(){throw new Error("createComputePipelineContext: This engine does not support compute shaders!")},Ue.B.prototype.createComputeContext=function(){},Ue.B.prototype.computeDispatch=function(e,t,i,n,s,r,o){throw new Error("computeDispatch: This engine does not support compute shaders!")},Ue.B.prototype.areAllComputeEffectsReady=function(){return!0},Ue.B.prototype.releaseComputeEffects=function(){},Ue.B.prototype._prepareComputePipelineContext=function(e,t,i,n,s){},Ue.B.prototype._rebuildComputeEffects=function(){},Ue.B.prototype._executeWhenComputeStateIsCompiled=function(e,t){t()},Ue.B.prototype._releaseComputeEffect=function(e){},Ue.B.prototype._deleteComputePipelineContext=function(e){};var el=i(2931);class tl{get options(){return this._options}get shaderPath(){return this._shaderPath}constructor(e,t,i,n={}){this._bindings={},this._samplers={},this._contextIsDirty=!1,this.onCompiled=null,this.onError=null,this.name=e,this._engine=t,this.uniqueId=xt.K.UniqueId,this._engine.getCaps().supportComputeShaders?n.bindingsMapping?(this._context=t.createComputeContext(),this._shaderPath=i,this._options=Object.assign({bindingsMapping:{},defines:[]},n)):p.Y.Error("You must provide the binding mappings as browsers don't support reflection for wgsl shaders yet!"):p.Y.Error("This engine does not support compute shaders!")}getClassName(){return"ComputeShader"}setTexture(e,t,i=!0){const n=this._bindings[e];this._bindings[e]={type:i?Qa.Texture:Qa.TextureWithoutSampler,object:t,indexInGroupEntries:null==n?void 0:n.indexInGroupEntries},this._contextIsDirty||(this._contextIsDirty=!n||n.object!==t||n.type!==this._bindings[e].type)}setStorageTexture(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:Qa.StorageTexture,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setUniformBuffer(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:Qa.UniformBuffer,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setStorageBuffer(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:Qa.StorageBuffer,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setTextureSampler(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||!t.compareSampler(i.object)),this._bindings[e]={type:Qa.Sampler,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}isReady(){let e=this._effect;for(const s in this._bindings){const e=this._bindings[s],t=e.type,i=e.object;switch(t){case Qa.Texture:case Qa.TextureWithoutSampler:case Qa.StorageTexture:if(!i.isReady())return!1;break}}const t=[],i=this._shaderPath;if(this._options.defines)for(let s=0;s{const r=()=>{this.dispatch(e,t,i)?s():setTimeout(r,n)};r()}))}serialize(){const e=E.p4.Serialize(this);e.options=this._options,e.shaderPath=this._shaderPath,e.bindings={},e.textures={};for(const t in this._bindings){const i=this._bindings[t],n=i.object;switch(i.type){case Qa.Texture:case Qa.TextureWithoutSampler:case Qa.StorageTexture:{const s=n.serialize();s&&(e.textures[t]=s,e.bindings[t]={type:i.type});break}case Qa.UniformBuffer:}}return e}static Parse(e,t,i){const n=E.p4.Parse((()=>new tl(e.name,t.getEngine(),e.shaderPath,e.options)),e,t,i);for(const s in e.textures){const r=e.bindings[s],o=Le.Parse(e.textures[s],t,i);r.type===Qa.Texture?n.setTexture(s,o):r.type===Qa.TextureWithoutSampler?n.setTexture(s,o,!1):n.setStorageTexture(s,o)}return n}}(0,oe.gn)([(0,E.qC)()],tl.prototype,"name",void 0),(0,l.H)("BABYLON.ComputeShader",tl);var il,nl,sl,rl=i(3773),ol=i(2789),al=i(2897);class ll{constructor(e,t,i,n,s,r){this.entries=new Array,this._boundingVectors=new Array,this._capacity=i,this._depth=n,this._maxDepth=s,this._creationFunc=r,this._minPoint=e,this._maxPoint=t,this._boundingVectors.push(e.clone()),this._boundingVectors.push(t.clone()),this._boundingVectors.push(e.clone()),this._boundingVectors[2].x=t.x,this._boundingVectors.push(e.clone()),this._boundingVectors[3].y=t.y,this._boundingVectors.push(e.clone()),this._boundingVectors[4].z=t.z,this._boundingVectors.push(t.clone()),this._boundingVectors[5].z=e.z,this._boundingVectors.push(t.clone()),this._boundingVectors[6].x=e.x,this._boundingVectors.push(t.clone()),this._boundingVectors[7].y=e.y}get capacity(){return this._capacity}get minPoint(){return this._minPoint}get maxPoint(){return this._maxPoint}addEntry(e){if(this.blocks)for(let t=0;tthis.capacity&&this._depth-1&&this.entries.splice(t,1)}addEntries(e){for(let t=0;t{const i=e.getBoundingInfo();!e.isBlocked&&i.boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},hl.CreationFuncForSubMeshes=(e,t)=>{e.getBoundingInfo().boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},N.x.prototype.createOrUpdateSelectionOctree=function(e=64,t=2){let i=this._getComponent(Se.l.NAME_OCTREE);i||(i=new cl(this),this._addComponent(i)),this._selectionOctree||(this._selectionOctree=new hl(hl.CreationFuncForMeshes,e,t));const n=this.getWorldExtends();return this._selectionOctree.update(n.min,n.max,this.meshes),this._selectionOctree},Object.defineProperty(N.x.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0}),ie.x.prototype.createOrUpdateSubmeshesOctree=function(e=64,t=2){const i=this.getScene();let n=i._getComponent(Se.l.NAME_OCTREE);n||(n=new cl(i),i._addComponent(n)),this._submeshesOctree||(this._submeshesOctree=new hl(hl.CreationFuncForSubMeshes,e,t)),this.computeWorldMatrix(!0);const s=this.getBoundingInfo().boundingBox;return this._submeshesOctree.update(s.minimumWorld,s.maximumWorld,this.subMeshes),this._submeshesOctree};class cl{constructor(e){this.name=Se.l.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new qe(o.P.Zero(),new o.P(1,1,1)),(e=e||m.l.LastCreatedScene)&&(this.scene=e,this.scene.getActiveMeshCandidates=this.getActiveMeshCandidates.bind(this),this.scene.getActiveSubMeshCandidates=this.getActiveSubMeshCandidates.bind(this),this.scene.getCollidingSubMeshCandidates=this.getCollidingSubMeshCandidates.bind(this),this.scene.getIntersectingSubMeshCandidates=this.getIntersectingSubMeshCandidates.bind(this))}register(){this.scene.onMeshRemovedObservable.add((e=>{const t=this.scene.selectionOctree;if(null!=t){const i=t.dynamicContent.indexOf(e);-1!==i&&t.dynamicContent.splice(i,1)}})),this.scene.onMeshImportedObservable.add((e=>{const t=this.scene.selectionOctree;null!=t&&t.addMesh(e)}))}getActiveMeshCandidates(){var e;return(null===(e=this.scene._selectionOctree)||void 0===e?void 0:e.select(this.scene.frustumPlanes))||this.scene._getDefaultMeshCandidates()}getActiveSubMeshCandidates(e){if(e._submeshesOctree&&e.useOctreeForRenderingSelection){return e._submeshesOctree.select(this.scene.frustumPlanes)}return this.scene._getDefaultSubMeshCandidates(e)}getIntersectingSubMeshCandidates(e,t){if(e._submeshesOctree&&e.useOctreeForPicking){qe.TransformToRef(t,e.getWorldMatrix(),this._tempRay);return e._submeshesOctree.intersectsRay(this._tempRay)}return this.scene._getDefaultSubMeshCandidates(e)}getCollidingSubMeshCandidates(e,t){if(e._submeshesOctree&&e.useOctreeForCollisions){const i=t._velocityWorldLength+Math.max(t._radius.x,t._radius.y,t._radius.z);return e._submeshesOctree.intersects(t._basePointWorld,i)}return this.scene._getDefaultSubMeshCandidates(e)}rebuild(){}dispose(){}}class dl{getRenderCamera(e){if(this._renderCamera)return this._renderCamera;{let t;return t=this.originalScene.activeCameras&&this.originalScene.activeCameras.length>1?this.originalScene.activeCameras[this.originalScene.activeCameras.length-1]:this.originalScene.activeCamera,e&&t&&t.isRigCamera?t.rigParent:t}}setRenderCamera(e){this._renderCamera=e}_getSharedGizmoLight(){return this._sharedGizmoLight||(this._sharedGizmoLight=new Os("shared gizmo light",new o.P(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=a.Wo.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return null==dl._DefaultUtilityLayer?dl._CreateDefaultUtilityLayerFromScene(m.l.LastCreatedScene):dl._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return dl._DefaultUtilityLayer=new dl(e),dl._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce((()=>{dl._DefaultUtilityLayer=null})),dl._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return null==dl._DefaultKeepDepthUtilityLayer&&(dl._DefaultKeepDepthUtilityLayer=new dl(m.l.LastCreatedScene),dl._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,dl._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce((()=>{dl._DefaultKeepDepthUtilityLayer=null}))),dl._DefaultKeepDepthUtilityLayer}constructor(e,t=!0){this.originalScene=e,this._pointerCaptures={},this._lastPointerEvents={},this._sharedGizmoLight=null,this._renderCamera=null,this.pickUtilitySceneFirst=!0,this.shouldRender=!0,this.onlyCheckPointerDownEvents=!0,this.processAllEvents=!1,this.pickingEnabled=!0,this.onPointerOutObservable=new r.y$,this.utilityLayerScene=new N.x(e.getEngine(),{virtual:!0}),this.utilityLayerScene.useRightHandedSystem=e.useRightHandedSystem,this.utilityLayerScene._allowPostProcessClearColor=!1,this.utilityLayerScene.postProcessesEnabled=!1,this.utilityLayerScene.detachControl(),t&&(this._originalPointerObserver=e.onPrePointerObservable.add((t=>{if(!this.utilityLayerScene.activeCamera)return;if(!this.pickingEnabled)return;if(!this.processAllEvents&&t.type!==We.kD.POINTERMOVE&&t.type!==We.kD.POINTERUP&&t.type!==We.kD.POINTERDOWN&&t.type!==We.kD.POINTERDOUBLETAP)return;this.utilityLayerScene.pointerX=e.pointerX,this.utilityLayerScene.pointerY=e.pointerY;const i=t.event;if(e.isPointerCaptured(i.pointerId))return void(this._pointerCaptures[i.pointerId]=!1);const n=i=>{let n=null;if(t.nearInteractionPickingInfo)n=t.nearInteractionPickingInfo.pickedMesh.getScene()==i?t.nearInteractionPickingInfo:new je.p;else if(i!==this.utilityLayerScene&&t.originalPickingInfo)n=t.originalPickingInfo;else{let s=null;this._renderCamera&&(s=i._activeCamera,i._activeCamera=this._renderCamera,t.ray=null),n=t.ray?i.pickWithRay(t.ray):i.pick(e.pointerX,e.pointerY),s&&(i._activeCamera=s)}return n},s=n(this.utilityLayerScene);if(!t.ray&&s&&(t.ray=s.ray),this.utilityLayerScene.onPrePointerObservable.notifyObservers(t),this.onlyCheckPointerDownEvents&&t.type!=We.kD.POINTERDOWN)return t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new We.R5(t.type,t.event,s),t.type),void(t.type===We.kD.POINTERUP&&this._pointerCaptures[i.pointerId]&&(this._pointerCaptures[i.pointerId]=!1));if(this.utilityLayerScene.autoClearDepthAndStencil||this.pickUtilitySceneFirst)s&&s.hit&&(t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new We.R5(t.type,t.event,s),t.type),t.skipOnPointerObservable=!0);else{const i=n(e),r=t.event;i&&s&&(0===s.distance&&i.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,r),t.skipOnPointerObservable=!0):t.type===We.kD.POINTERDOWN?this._pointerCaptures[r.pointerId]=!0:t.type!==We.kD.POINTERMOVE&&t.type!==We.kD.POINTERUP||(this._lastPointerEvents[r.pointerId]&&(this.onPointerOutObservable.notifyObservers(r.pointerId),delete this._lastPointerEvents[r.pointerId]),this._notifyObservers(t,i,r)):!this._pointerCaptures[r.pointerId]&&(s.distance0)):!this._pointerCaptures[r.pointerId]&&s.distance>=i.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,r),t.skipOnPointerObservable=!0):(t.type!==We.kD.POINTERMOVE&&t.type!==We.kD.POINTERUP||this._lastPointerEvents[r.pointerId]&&(this.onPointerOutObservable.notifyObservers(r.pointerId),delete this._lastPointerEvents[r.pointerId]),this._notifyObservers(t,s,r))),t.type===We.kD.POINTERUP&&this._pointerCaptures[r.pointerId]&&(this._pointerCaptures[r.pointerId]=!1))}})),this._originalPointerObserver&&e.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterRenderCameraObservable.add((e=>{this.shouldRender&&e==this.getRenderCamera()&&this.render()})),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add((()=>{this.dispose()})),this._updateCamera()}_notifyObservers(e,t,i){e.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new We.R5(e.type,e.event,t),e.type),this._lastPointerEvents[i.pointerId]=!0)}render(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){const e=this.utilityLayerScene.activeCamera.getScene(),t=this.utilityLayerScene.activeCamera;t._scene=this.utilityLayerScene,t.leftCamera&&(t.leftCamera._scene=this.utilityLayerScene),t.rightCamera&&(t.rightCamera._scene=this.utilityLayerScene),this.utilityLayerScene.render(!1),t._scene=e,t.leftCamera&&(t.leftCamera._scene=e),t.rightCamera&&(t.rightCamera._scene=e)}}dispose(){this.onPointerOutObservable.clear(),this._afterRenderObserver&&this.originalScene.onAfterCameraRenderObservable.remove(this._afterRenderObserver),this._sceneDisposeObserver&&this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver),this._originalPointerObserver&&this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver),this.utilityLayerScene.dispose()}_updateCamera(){this.utilityLayerScene.cameraToUseForPointers=this.getRenderCamera(),this.utilityLayerScene.activeCamera=this.getRenderCamera()}}dl._DefaultUtilityLayer=null,dl._DefaultKeepDepthUtilityLayer=null,function(e){e[e.Origin=0]="Origin",e[e.Pivot=1]="Pivot"}(il||(il={})),function(e){e[e.World=0]="World",e[e.Local=1]="Local"}(nl||(nl={}));class ul{set scaleRatio(e){this._scaleRatio=e}get scaleRatio(){return this._scaleRatio}get isHovered(){return this._isHovered}get attachedMesh(){return this._attachedMesh}set attachedMesh(e){this._attachedMesh=e,e&&(this._attachedNode=e),this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}get attachedNode(){return this._attachedNode}set attachedNode(e){this._attachedNode=e,this._attachedMesh=null,this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}setCustomMesh(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._rootMesh.getChildMeshes().forEach((e=>{e.dispose()})),e.parent=this._rootMesh,this._customMeshSet=!0}set updateGizmoRotationToMatchAttachedMesh(e){this._updateGizmoRotationToMatchAttachedMesh=e}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this._updateGizmoPositionToMatchAttachedMesh=e}get updateGizmoPositionToMatchAttachedMesh(){return this._updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){this._coordinatesMode=e;const t=e==nl.Local;this.updateGizmoRotationToMatchAttachedMesh=t,this.updateGizmoPositionToMatchAttachedMesh=t}get coordinatesMode(){return this._coordinatesMode}set updateScale(e){this._updateScale=e}get updateScale(){return this._updateScale}_attachedNodeChanged(e){}constructor(e=dl.DefaultUtilityLayer){this.gizmoLayer=e,this._attachedMesh=null,this._attachedNode=null,this._customRotationQuaternion=null,this._scaleRatio=1,this._isHovered=!1,this._customMeshSet=!1,this._updateGizmoRotationToMatchAttachedMesh=!0,this._updateGizmoPositionToMatchAttachedMesh=!0,this._anchorPoint=il.Origin,this._updateScale=!0,this._coordinatesMode=nl.Local,this._interactionsEnabled=!0,this._rightHandtoLeftHandMatrix=o.y3.RotationY(Math.PI),this._rootMesh=new ee.Kj("gizmoRootNode",e.utilityLayerScene),this._rootMesh.rotationQuaternion=o._f.Identity(),this._beforeRenderObserver=this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add((()=>{this._update()}))}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e}_update(){if(this.attachedNode){let e=this.attachedNode;if(this.attachedMesh&&(e=this.attachedMesh||this.attachedNode),this.updateGizmoPositionToMatchAttachedMesh)if(this.anchorPoint==il.Pivot&&e.getAbsolutePivotPoint){const t=e.getAbsolutePivotPoint();this._rootMesh.position.copyFrom(t)}else{const t=e.getWorldMatrix().getRow(3),i=t?t.toVector3():new o.P(0,0,0);this._rootMesh.position.copyFrom(i)}if(this.updateGizmoRotationToMatchAttachedMesh){const t=e._isMesh||"AbstractMesh"===e.getClassName()||"TransformNode"===e.getClassName()||"InstancedMesh"===e.getClassName()?e:void 0;e.getWorldMatrix().decompose(void 0,this._rootMesh.rotationQuaternion,void 0,ul.PreserveScaling?t:void 0)}else this._customRotationQuaternion?this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion):this._rootMesh.rotationQuaternion.set(0,0,0,1);if(this.updateScale){const t=this.gizmoLayer.utilityLayerScene.activeCamera;let i=t.globalPosition;t.devicePosition&&(i=t.devicePosition),this._rootMesh.position.subtractToRef(i,o.jp.Vector3[0]);let n=this.scaleRatio;if(t.mode==ce.V.ORTHOGRAPHIC_CAMERA){if(t.orthoTop&&t.orthoBottom){n*=t.orthoTop-t.orthoBottom}}else{const e=t.getScene().useRightHandedSystem?o.P.RightHandedForwardReadOnly:o.P.LeftHandedForwardReadOnly,i=t.getDirection(e);n*=o.P.Dot(o.jp.Vector3[0],i)}this._rootMesh.scaling.setAll(n),e._getWorldMatrixDeterminant()<0&&!ul.PreserveScaling&&(this._rootMesh.scaling.y*=-1)}else this._rootMesh.scaling.setAll(this.scaleRatio)}}_handlePivot(){const e=this._attachedNode;e.isUsingPivotMatrix&&e.isUsingPivotMatrix()&&e.position&&e.getWorldMatrix().setTranslation(e.position)}_matrixChanged(){if(this._attachedNode)if(this._attachedNode._isCamera){const e=this._attachedNode;let t,i;if(e.parent){const i=o.jp.Matrix[1];e.parent._worldMatrix.invertToRef(i),this._attachedNode._worldMatrix.multiplyToRef(i,o.jp.Matrix[0]),t=o.jp.Matrix[0]}else t=this._attachedNode._worldMatrix;e.getScene().useRightHandedSystem?(this._rightHandtoLeftHandMatrix.multiplyToRef(t,o.jp.Matrix[1]),i=o.jp.Matrix[1]):i=t,i.decompose(o.jp.Vector3[1],o.jp.Quaternion[0],o.jp.Vector3[0]);if("FreeCamera"===this._attachedNode.getClassName()||"FlyCamera"===this._attachedNode.getClassName()||"ArcFollowCamera"===this._attachedNode.getClassName()||"TargetCamera"===this._attachedNode.getClassName()||"TouchCamera"===this._attachedNode.getClassName()||"UniversalCamera"===this._attachedNode.getClassName()){const e=this._attachedNode;e.rotation=o.jp.Quaternion[0].toEulerAngles(),e.rotationQuaternion&&(e.rotationQuaternion.copyFrom(o.jp.Quaternion[0]),e.rotationQuaternion.normalize())}e.position.copyFrom(o.jp.Vector3[0])}else if(this._attachedNode._isMesh||"AbstractMesh"===this._attachedNode.getClassName()||"TransformNode"===this._attachedNode.getClassName()||"InstancedMesh"===this._attachedNode.getClassName()){const e=this._attachedNode;if(e.parent){const t=o.jp.Matrix[0],i=o.jp.Matrix[1];e.parent.getWorldMatrix().invertToRef(t),this._attachedNode.getWorldMatrix().multiplyToRef(t,i),i.decompose(o.jp.Vector3[0],o.jp.Quaternion[0],e.position,ul.PreserveScaling?e:void 0)}else this._attachedNode._worldMatrix.decompose(o.jp.Vector3[0],o.jp.Quaternion[0],e.position,ul.PreserveScaling?e:void 0);o.jp.Vector3[0].scaleInPlace(1/e.scalingDeterminant),e.scaling.copyFrom(o.jp.Vector3[0]),e.billboardMode||(e.rotationQuaternion?(e.rotationQuaternion.copyFrom(o.jp.Quaternion[0]),e.rotationQuaternion.normalize()):e.rotation=o.jp.Quaternion[0].toEulerAngles())}else if("Bone"===this._attachedNode.getClassName()){const e=this._attachedNode,t=e.getParent();if(t){const i=o.jp.Matrix[0],n=o.jp.Matrix[1];t.getFinalMatrix().invertToRef(i),e.getFinalMatrix().multiplyToRef(i,n);e.getLocalMatrix().copyFrom(n)}else{e.getLocalMatrix().copyFrom(e.getFinalMatrix())}e.markAsDirty()}else{const e=this._attachedNode;if(e.getTypeID){const t=e.getTypeID();if(t===he.LIGHTTYPEID_DIRECTIONALLIGHT||t===he.LIGHTTYPEID_SPOTLIGHT||t===he.LIGHTTYPEID_POINTLIGHT){const t=e.parent;if(t){const i=o.jp.Matrix[0],n=o.jp.Matrix[1];t.getWorldMatrix().invertToRef(i),e.getWorldMatrix().multiplyToRef(i,n),n.decompose(void 0,o.jp.Quaternion[0],o.jp.Vector3[0])}else this._attachedNode._worldMatrix.decompose(void 0,o.jp.Quaternion[0],o.jp.Vector3[0]);e.position=new o.P(o.jp.Vector3[0].x,o.jp.Vector3[0].y,o.jp.Vector3[0].z),e.direction&&(e.direction=new o.P(e.direction.x,e.direction.y,e.direction.z))}}}}_setGizmoMeshMaterial(e,t){e&&e.forEach((e=>{e.material=t,e.color&&(e.color=t.diffuseColor)}))}static GizmoAxisPointerObserver(e,t){let i=!1;return e.utilityLayerScene.onPointerObservable.add((e=>{var n,s;if(e.pickInfo){if(e.type===We.kD.POINTERMOVE){if(i)return;t.forEach((t=>{var i,n;if(t.colliderMeshes&&t.gizmoMeshes){const s=-1!=(null===(i=t.colliderMeshes)||void 0===i?void 0:i.indexOf(null===(n=null==e?void 0:e.pickInfo)||void 0===n?void 0:n.pickedMesh)),r=t.dragBehavior.enabled?s||t.active?t.hoverMaterial:t.material:t.disableMaterial;t.gizmoMeshes.forEach((e=>{e.material=r,e.color&&(e.color=r.diffuseColor)}))}}))}if(e.type===We.kD.POINTERDOWN&&t.has(null===(n=e.pickInfo.pickedMesh)||void 0===n?void 0:n.parent)){i=!0;t.get(null===(s=e.pickInfo.pickedMesh)||void 0===s?void 0:s.parent).active=!0,t.forEach((t=>{var i,n;const s=(-1!=(null===(i=t.colliderMeshes)||void 0===i?void 0:i.indexOf(null===(n=null==e?void 0:e.pickInfo)||void 0===n?void 0:n.pickedMesh))||t.active)&&t.dragBehavior.enabled?t.hoverMaterial:t.disableMaterial;t.gizmoMeshes.forEach((e=>{e.material=s,e.color&&(e.color=s.diffuseColor)}))}))}e.type===We.kD.POINTERUP&&t.forEach((e=>{e.active=!1,i=!1,e.gizmoMeshes.forEach((t=>{t.material=e.dragBehavior.enabled?e.material:e.disableMaterial,t.color&&(t.color=e.material.diffuseColor)}))}))}}))}dispose(){this._rootMesh.dispose(),this._beforeRenderObserver&&this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver)}}ul.PreserveScaling=!1;Object.defineProperty(N.x.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new pl(this)),this._debugLayer},enumerable:!0,configurable:!0}),function(e){e[e.Properties=0]="Properties",e[e.Debug=1]="Debug",e[e.Statistics=2]="Statistics",e[e.Tools=3]="Tools",e[e.Settings=4]="Settings"}(sl||(sl={}));class pl{get onPropertyChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new r.y$),this._onPropertyChangedObservable)}get onSelectionChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new r.y$),this._onSelectionChangedObservable)}constructor(e){this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||m.l.LastCreatedScene,this._scene&&this._scene.onDisposeObservable.add((()=>{this._scene._debugLayer&&this._scene._debugLayer.hide()}))}_createInspector(e){if(this.isVisible())return;if(this._onPropertyChangedObservable){for(const e of this._onPropertyChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(e);this._onPropertyChangedObservable.clear(),this._onPropertyChangedObservable=void 0}if(this._onSelectionChangedObservable){for(const e of this._onSelectionChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(e);this._onSelectionChangedObservable.clear(),this._onSelectionChangedObservable=void 0}const t=Object.assign({overlay:!1,showExplorer:!0,showInspector:!0,embedMode:!1,handleResize:!0,enablePopup:!0},e);this.BJSINSPECTOR=this.BJSINSPECTOR||this._getGlobalInspector(),this.BJSINSPECTOR.Inspector.Show(this._scene,t)}select(e,t){this.BJSINSPECTOR&&(t&&("[object String]"==Object.prototype.toString.call(t)?this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(t):this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(t)),this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(e))}_getGlobalInspector(){return"undefined"!=typeof INSPECTOR?INSPECTOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.Inspector?BABYLON:void 0}isVisible(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.IsVisible}hide(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.Hide()}setAsActiveScene(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector._SetNewScene(this._scene)}show(e){return new Promise((t=>{if(void 0===this.BJSINSPECTOR){const i=e&&e.inspectorURL?e.inspectorURL:pl.InspectorURL;se.w1.LoadScript(i,(()=>{this._createInspector(e),t(this)}))}else this._createInspector(e),t(this)}))}}function fl(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 s=[];const r=e.width||e.size||1,l=e.height||e.size||1,h=e.depth||e.size||1,c=e.wrap||!1;let d=void 0===e.topBaseAt?1:e.topBaseAt,u=void 0===e.bottomBaseAt?0:e.bottomBaseAt;d=(d+4)%4,u=(u+4)%4;let p=[2,0,3,1][d],f=[2,0,1,3][u],_=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,1];if(c){t=[2,3,0,2,0,1,4,5,6,4,6,7,9,10,11,9,11,8,12,14,15,12,13,14],_=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,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],s=[22,23,20,21];for(;p>0;)e.unshift(e.pop()),n.unshift(n.pop()),p--;for(;f>0;)i.unshift(i.pop()),s.unshift(s.pop()),f--;e=e.flat(),i=i.flat(),_=_.concat(e).concat(i),t.push(n[0],n[2],n[3],n[0],n[1],n[2]),t.push(s[0],s[2],s[3],s[0],s[1],s[2])}const m=[r/2,l/2,h/2];s=_.reduce(((e,t,i)=>e.concat(t*m[i%3])),[]);const g=0===e.sideOrientation?0:e.sideOrientation||Qe.x.DEFAULTSIDE,v=e.faceUV||new Array(6),T=e.faceColors,S=[];for(let x=0;x<6;x++)void 0===v[x]&&(v[x]=new o.Lt(0,0,1,1)),T&&void 0===T[x]&&(T[x]=new a.HE(1,1,1,1));for(let o=0;o<6;o++)if(n.push(v[o].z,we.e.UseOpenGLOrientationForUV?1-v[o].w:v[o].w),n.push(v[o].x,we.e.UseOpenGLOrientationForUV?1-v[o].w:v[o].w),n.push(v[o].x,we.e.UseOpenGLOrientationForUV?1-v[o].y:v[o].y),n.push(v[o].z,we.e.UseOpenGLOrientationForUV?1-v[o].y:v[o].y),T)for(let e=0;e<4;e++)S.push(T[o].r,T[o].g,T[o].b,T[o].a);Qe.x._ComputeSides(g,s,t,i,n,e.frontUVs,e.backUVs);const E=new Qe.x;if(E.indices=t,E.positions=s,E.normals=i,E.uvs=n,T){const e=g===Qe.x.DOUBLESIDE?S.concat(S):S;E.colors=e}return E}function _l(e,t={},i=null){const n=new ee.Kj(e,i);t.sideOrientation=ee.Kj._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation;return fl(t).applyToMesh(n,t.updatable),n}pl.InspectorURL=`https://unpkg.com/babylonjs-inspector@${fe.D.Version}/babylon.inspector.bundle.js`;function ml(e){const t=e.segments||32,i=e.diameterX||e.diameter||1,n=e.diameterY||e.diameter||1,s=e.diameterZ||e.diameter||1,r=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,a=e.slice&&e.slice<=0?1:e.slice||1,l=0===e.sideOrientation?0:e.sideOrientation||Qe.x.DEFAULTSIDE,h=!!e.dedupTopBottomIndices,c=new o.P(i/2,n/2,s/2),d=2+t,u=2*d,p=[],f=[],_=[],m=[];for(let v=0;v<=d;v++){const e=v/d,t=e*Math.PI*a;for(let i=0;i<=u;i++){const n=i/u,s=n*Math.PI*2*r,a=o.y3.RotationZ(-t),l=o.y3.RotationY(s),h=o.P.TransformCoordinates(o.P.Up(),a),d=o.P.TransformCoordinates(h,l),p=d.multiply(c),g=d.divide(c).normalize();f.push(p.x,p.y,p.z),_.push(g.x,g.y,g.z),m.push(n,we.e.UseOpenGLOrientationForUV?1-e:e)}if(v>0){const e=f.length/3;for(let t=e-2*(u+1);t+u+21&&(p.push(t),p.push(t+1),p.push(t+u+1)),(v_l(e,{size:t,sideOrientation:s,updatable:n},i);function vl(e={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){const t=Math.max(e.subdivisions?e.subdivisions:2,1),i=Math.max(e.tessellation?e.tessellation:16,3),n=Math.max(e.height?e.height:1,0),s=Math.max(e.radius?e.radius:.25,0),r=Math.max(e.capSubdivisions?e.capSubdivisions:6,1),a=i,l=t,h=Math.max(e.radiusTop?e.radiusTop:s,0),c=Math.max(e.radiusBottom?e.radiusBottom:s,0),d=n-(h+c),u=2*Math.PI,p=Math.max(e.topCapSubdivisions?e.topCapSubdivisions:r,1),f=Math.max(e.bottomCapSubdivisions?e.bottomCapSubdivisions:r,1),_=Math.acos((c-h)/n);let m=[];const g=[],v=[],T=[];let S=0;const E=[],x=.5*d,b=.5*Math.PI;let C,y;const A=o.P.Zero(),R=o.P.Zero(),P=Math.cos(_),I=Math.sin(_),M=new o.FM(h*I,x+h*P).subtract(new o.FM(c*I,c*P-x)).length(),O=h*_+M+c*(b-_);let D=0;for(y=0;y<=p;y++){const e=[],t=b-_*(y/p);D+=h*_/p;const i=Math.cos(t),n=Math.sin(t),s=i*h;for(C=0;C<=a;C++){const t=C/a,r=t*u+0,o=Math.sin(r),l=Math.cos(r);R.x=s*o,R.y=x+n*h,R.z=s*l,g.push(R.x,R.y,R.z),A.set(i*o,n,i*l),v.push(A.x,A.y,A.z),T.push(t,we.e.UseOpenGLOrientationForUV?D/O:1-D/O),e.push(S),S++}E.push(e)}const N=n-h-c+P*h-P*c,F=I*(c-h)/N;for(y=1;y<=l;y++){const e=[];D+=M/l;const t=I*(y*(c-h)/l+h);for(C=0;C<=a;C++){const i=C/a,n=i*u+0,s=Math.sin(n),r=Math.cos(n);R.x=t*s,R.y=x+P*h-y*N/l,R.z=t*r,g.push(R.x,R.y,R.z),A.set(s,F,r).normalize(),v.push(A.x,A.y,A.z),T.push(i,we.e.UseOpenGLOrientationForUV?D/O:1-D/O),e.push(S),S++}E.push(e)}for(y=1;y<=f;y++){const e=[],t=b-_-(Math.PI-_)*(y/f);D+=c*_/f;const i=Math.cos(t),n=Math.sin(t),s=i*c;for(C=0;C<=a;C++){const t=C/a,r=t*u+0,o=Math.sin(r),l=Math.cos(r);R.x=s*o,R.y=n*c-x,R.z=s*l,g.push(R.x,R.y,R.z),A.set(i*o,n,i*l),v.push(A.x,A.y,A.z),T.push(t,we.e.UseOpenGLOrientationForUV?D/O:1-D/O),e.push(S),S++}E.push(e)}for(C=0;Cgl(e,{segments:t,diameterX:i,diameterY:i,diameterZ:i,sideOrientation:r,updatable:s},n);function Sl(e){let t=e.pathArray;const i=e.closeArray||!1,n=e.closePath||!1,s=e.invertUV||!1,r=Math.floor(t[0].length/2);let o=e.offset||r;o=o>r?r:Math.floor(o);const a=0===e.sideOrientation?0:e.sideOrientation||Qe.x.DEFAULTSIDE,l=e.uvs,h=e.colors,c=[],d=[],u=[],p=[],f=[],_=[],m=[],g=[];let v;const T=[],S=[];let E,x,b;if(t.length<2){const e=[],i=[];for(x=0;x0&&(P=A[b].subtract(A[b-1]).length(),I=P+m[E],f[E].push(I),m[E]=I),b++;n&&(b--,c.push(A[0].x,A[0].y,A[0].z),P=A[b].subtract(A[0]).length(),I=P+m[E],f[E].push(I),m[E]=I),T[E]=R+y,S[E]=C,C+=R+y}let D,N,F=null,w=null;for(x=0;x{let s=n[0].length;const r=l;let o=0;const a=r._originalBuilderSideOrientation===ee.Kj.DOUBLESIDE?2:1;for(let l=1;l<=a;++l)for(let a=0;aTl(e,t,i),Qe.x.CreateCapsule=vl;function xl(e){const t=new Array,i=new Array,n=new Array,s=new Array,r=e.radius||.5,o=e.tessellation||64,a=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,l=0===e.sideOrientation?0:e.sideOrientation||Qe.x.DEFAULTSIDE;t.push(0,0,0),s.push(.5,.5);const h=2*Math.PI*a,c=1===a?h/o:h/(o-1);let d=0;for(let f=0;fEl(e,{pathArray:t,closeArray:i,closePath:n,offset:s,updatable:o,sideOrientation:a,instance:l},r);function Cl(e){const t=e.pattern||ee.Kj.NO_FLIP,i=e.tileWidth||e.tileSize||1,n=e.tileHeight||e.tileSize||1,s=e.alignHorizontal||0,r=e.alignVertical||0,o=e.width||e.size||1,a=Math.floor(o/i);let l=o-a*i;const h=e.height||e.size||1,c=Math.floor(h/n);let d=h-c*n;const u=i*a/2,p=n*c/2;let f=0,_=0,m=0,g=0,v=0,T=0;if(l>0||d>0){switch(m=-u,g=-p,v=u,T=p,s){case ee.Kj.CENTER:l/=2,m-=l,v+=l;break;case ee.Kj.LEFT:v+=l,f=-l/2;break;case ee.Kj.RIGHT:m-=l,f=l/2}switch(r){case ee.Kj.CENTER:d/=2,g-=d,T+=d;break;case ee.Kj.BOTTOM:T+=d,_=-d/2;break;case ee.Kj.TOP:g-=d,_=d/2}}const S=[],E=[],x=[];x[0]=[0,0,1,0,1,1,0,1],x[1]=[0,0,1,0,1,1,0,1],t!==ee.Kj.ROTATE_TILE&&t!==ee.Kj.ROTATE_ROW||(x[1]=[1,1,0,1,0,0,1,0]),t!==ee.Kj.FLIP_TILE&&t!==ee.Kj.FLIP_ROW||(x[1]=[1,0,0,0,0,1,1,1]),t!==ee.Kj.FLIP_N_ROTATE_TILE&&t!==ee.Kj.FLIP_N_ROTATE_ROW||(x[1]=[0,1,1,1,1,0,0,0]);let b=[];const C=[],y=[];let A=0;for(let M=0;M0||d>0){const e=d>0&&(r===ee.Kj.CENTER||r===ee.Kj.TOP),o=d>0&&(r===ee.Kj.CENTER||r===ee.Kj.BOTTOM),h=l>0&&(s===ee.Kj.CENTER||s===ee.Kj.RIGHT),x=l>0&&(s===ee.Kj.CENTER||s===ee.Kj.LEFT);let R,P,I,M,O=[];if(e&&h&&(S.push(m+f,g+_,0),S.push(-u+f,g+_,0),S.push(-u+f,g+d+_,0),S.push(m+f,g+d+_,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,R=1-l/i,P=1-d/n,I=1,M=1,O=[R,P,I,P,I,M,R,M],t===ee.Kj.ROTATE_ROW&&(O=[1-R,1-P,1-I,1-P,1-I,1-M,1-R,1-M]),t===ee.Kj.FLIP_ROW&&(O=[1-R,P,1-I,P,1-I,M,1-R,M]),t===ee.Kj.FLIP_N_ROTATE_ROW&&(O=[R,1-P,I,1-P,I,1-M,R,1-M]),b=b.concat(O),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),E.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),e&&x&&(S.push(u+f,g+_,0),S.push(v+f,g+_,0),S.push(v+f,g+d+_,0),S.push(u+f,g+d+_,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,R=0,P=1-d/n,I=l/i,M=1,O=[R,P,I,P,I,M,R,M],(t===ee.Kj.ROTATE_ROW||t===ee.Kj.ROTATE_TILE&&a%2==0)&&(O=[1-R,1-P,1-I,1-P,1-I,1-M,1-R,1-M]),(t===ee.Kj.FLIP_ROW||t===ee.Kj.FLIP_TILE&&a%2==0)&&(O=[1-R,P,1-I,P,1-I,M,1-R,M]),(t===ee.Kj.FLIP_N_ROTATE_ROW||t===ee.Kj.FLIP_N_ROTATE_TILE&&a%2==0)&&(O=[R,1-P,I,1-P,I,1-M,R,1-M]),b=b.concat(O),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),E.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),o&&h&&(S.push(m+f,p+_,0),S.push(-u+f,p+_,0),S.push(-u+f,T+_,0),S.push(m+f,T+_,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,R=1-l/i,P=0,I=1,M=d/n,O=[R,P,I,P,I,M,R,M],(t===ee.Kj.ROTATE_ROW&&c%2==1||t===ee.Kj.ROTATE_TILE&&c%1==0)&&(O=[1-R,1-P,1-I,1-P,1-I,1-M,1-R,1-M]),(t===ee.Kj.FLIP_ROW&&c%2==1||t===ee.Kj.FLIP_TILE&&c%2==0)&&(O=[1-R,P,1-I,P,1-I,M,1-R,M]),(t===ee.Kj.FLIP_N_ROTATE_ROW&&c%2==1||t===ee.Kj.FLIP_N_ROTATE_TILE&&c%2==0)&&(O=[R,1-P,I,1-P,I,1-M,R,1-M]),b=b.concat(O),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),E.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),o&&x&&(S.push(u+f,p+_,0),S.push(v+f,p+_,0),S.push(v+f,T+_,0),S.push(u+f,T+_,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,R=0,P=0,I=l/i,M=d/n,O=[R,P,I,P,I,M,R,M],(t===ee.Kj.ROTATE_ROW&&c%2==1||t===ee.Kj.ROTATE_TILE&&(c+a)%2==1)&&(O=[1-R,1-P,1-I,1-P,1-I,1-M,1-R,1-M]),(t===ee.Kj.FLIP_ROW&&c%2==1||t===ee.Kj.FLIP_TILE&&(c+a)%2==1)&&(O=[1-R,P,1-I,P,1-I,M,1-R,M]),(t===ee.Kj.FLIP_N_ROTATE_ROW&&c%2==1||t===ee.Kj.FLIP_N_ROTATE_TILE&&(c+a)%2==1)&&(O=[R,1-P,I,1-P,I,1-M,R,1-M]),b=b.concat(O),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),E.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),e){const e=[];R=0,P=1-d/n,I=1,M=1,e[0]=[R,P,I,P,I,M,R,M],e[1]=[R,P,I,P,I,M,R,M],t!==ee.Kj.ROTATE_TILE&&t!==ee.Kj.ROTATE_ROW||(e[1]=[1-R,1-P,1-I,1-P,1-I,1-M,1-R,1-M]),t!==ee.Kj.FLIP_TILE&&t!==ee.Kj.FLIP_ROW||(e[1]=[1-R,P,1-I,P,1-I,M,1-R,M]),t!==ee.Kj.FLIP_N_ROTATE_TILE&&t!==ee.Kj.FLIP_N_ROTATE_ROW||(e[1]=[R,1-P,I,1-P,I,1-M,R,1-M]);for(let n=0;nbl(e,{radius:t,tessellation:i,sideOrientation:r,updatable:s},n);function yl(e){const t=e.faceUV||new Array(6),i=e.faceColors,n=e.pattern||ee.Kj.NO_FLIP,s=e.width||e.size||1,r=e.height||e.size||1,l=e.depth||e.size||1,h=e.tileWidth||e.tileSize||1,c=e.tileHeight||e.tileSize||1,d=e.alignHorizontal||0,u=e.alignVertical||0,p=0===e.sideOrientation?0:e.sideOrientation||Qe.x.DEFAULTSIDE;for(let U=0;U<6;U++)void 0===t[U]&&(t[U]=new o.Lt(0,0,1,1)),i&&void 0===i[U]&&(i[U]=new a.HE(1,1,1,1));const f=s/2,_=r/2,m=l/2,g=[];for(let o=0;o<2;o++)g[o]=Cl({pattern:n,tileWidth:h,tileHeight:c,width:s,height:r,alignVertical:u,alignHorizontal:d,sideOrientation:p});for(let o=2;o<4;o++)g[o]=Cl({pattern:n,tileWidth:h,tileHeight:c,width:l,height:r,alignVertical:u,alignHorizontal:d,sideOrientation:p});let v=u;u===ee.Kj.BOTTOM?v=ee.Kj.TOP:u===ee.Kj.TOP&&(v=ee.Kj.BOTTOM);for(let o=4;o<6;o++)g[o]=Cl({pattern:n,tileWidth:h,tileHeight:c,width:s,height:l,alignVertical:v,alignHorizontal:d,sideOrientation:p});let T=[],S=[],E=[],x=[];const b=[],C=[],y=[],A=[];let R=0,P=0;for(let a=0;a<6;a++){const e=g[a].positions.length;C[a]=[],y[a]=[];for(let t=0;te+P))),P+=C[a].length,i)for(let t=0;t<4;t++)b.push(i[a].r,i[a].g,i[a].b,i[a].a)}const I=new o.P(0,0,m),M=o.y3.RotationY(Math.PI);T=C[0].map((e=>o.P.TransformNormal(e,M).add(I))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]),S=y[0].map((e=>o.P.TransformNormal(e,M))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]),T=T.concat(C[1].map((e=>e.subtract(I))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),S=S.concat(y[1].map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const O=new o.P(f,0,0),D=o.y3.RotationY(-Math.PI/2);T=T.concat(C[2].map((e=>o.P.TransformNormal(e,D).add(O))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),S=S.concat(y[2].map((e=>o.P.TransformNormal(e,D))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const N=o.y3.RotationY(Math.PI/2);T=T.concat(C[3].map((e=>o.P.TransformNormal(e,N).subtract(O))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),S=S.concat(y[3].map((e=>o.P.TransformNormal(e,N))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const F=new o.P(0,_,0),w=o.y3.RotationX(Math.PI/2);T=T.concat(C[4].map((e=>o.P.TransformNormal(e,w).add(F))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),S=S.concat(y[4].map((e=>o.P.TransformNormal(e,w))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const L=o.y3.RotationX(-Math.PI/2);T=T.concat(C[5].map((e=>o.P.TransformNormal(e,L).subtract(F))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),S=S.concat(y[5].map((e=>o.P.TransformNormal(e,L))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),Qe.x._ComputeSides(p,T,x,S,E);const B=new Qe.x;if(B.indices=x,B.positions=T,B.normals=S,B.uvs=E,i){const e=p===Qe.x.DOUBLESIDE?b.concat(b):b;B.colors=e}return B}Qe.x.CreateTiledPlane=Cl;function Al(e){const t=new Array,i=new Array,n=new Array,s=new Array,r=e.radius||2,a=e.tube||.5,l=e.radialSegments||32,h=e.tubularSegments||32,c=e.p||2,d=e.q||3,u=0===e.sideOrientation?0:e.sideOrientation||Qe.x.DEFAULTSIDE,p=e=>{const t=Math.cos(e),i=Math.sin(e),n=d/c*e,s=Math.cos(n),a=r*(2+s)*.5*t,l=r*(2+s)*i*.5,h=r*Math.sin(n)*.5;return new o.P(a,l,h)};let f,_;for(f=0;f<=l;f++){const e=f%l/l*2*c*Math.PI,t=p(e),n=p(e+.01),r=n.subtract(t);let d=n.add(t);const u=o.P.Cross(r,d);for(d=o.P.Cross(u,r),u.normalize(),d.normalize(),_=0;_Rl(e,{radius:t,tube:i,radialSegments:n,tubularSegments:s,p:r,q:o,sideOrientation:h,updatable:l},a);const Pl={effect:null,subMesh:null};class Il extends pt{constructor(e,t,i,n={},s=!0){super(e,t,s),this._textures={},this._textureArrays={},this._externalTextures={},this._floats={},this._ints={},this._uints={},this._floatsArrays={},this._colors3={},this._colors3Arrays={},this._colors4={},this._colors4Arrays={},this._vectors2={},this._vectors3={},this._vectors4={},this._quaternions={},this._quaternionsArrays={},this._matrices={},this._matrixArrays={},this._matrices3x3={},this._matrices2x2={},this._vectors2Arrays={},this._vectors3Arrays={},this._vectors4Arrays={},this._uniformBuffers={},this._textureSamplers={},this._storageBuffers={},this._cachedWorldViewMatrix=new o.y3,this._cachedWorldViewProjectionMatrix=new o.y3,this._multiview=!1,this._materialHelperNeedsPreviousMatrices=!1,this._shaderPath=i,this._options=Object.assign({needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1},n)}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){-1===this._options.uniforms.indexOf(e)&&this._options.uniforms.push(e)}setTexture(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._textures[e]=t,this}setTextureArray(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this}setExternalTexture(e,t){return-1===this._options.externalTextures.indexOf(e)&&this._options.externalTextures.push(e),this._externalTextures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setUInt(e,t){return this._checkUniform(e),this._uints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor3Array(e,t){return this._checkUniform(e),this._colors3Arrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setColor4Array(e,t){return this._checkUniform(e),this._colors4Arrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setQuaternion(e,t){return this._checkUniform(e),this._quaternions[e]=t,this}setQuaternionArray(e,t){return this._checkUniform(e),this._quaternionsArrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);const i=new Float32Array(16*t.length);for(let n=0;nt===e||t.startsWith(i)));return n>=0&&this.options.defines.splice(n,1),("boolean"!=typeof t||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){var n,s,r,o;const a=i&&this._storeEffectOnSubMeshes;if(this.isFrozen)if(a){if(i.effect&&i.effect._wasPreviouslyReady)return!0}else{const e=this._drawWrapper.effect;if(e&&e._wasPreviouslyReady&&e._wasPreviouslyUsingInstances===t)return!0}const l=this.getScene(),h=l.getEngine(),c=[],d=[],u=new zt;let p=this._shaderPath,f=this._options.uniforms,_=this._options.uniformBuffers,m=this._options.samplers;h.getCaps().multiview&&l.activeCamera&&l.activeCamera.outputRenderTarget&&l.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,c.push("#define MULTIVIEW"),-1!==this._options.uniforms.indexOf("viewProjection")&&-1===this._options.uniforms.indexOf("viewProjectionR")&&this._options.uniforms.push("viewProjectionR"));for(let C=0;C4&&(d.push(ne.o.MatricesIndicesExtraKind),d.push(ne.o.MatricesWeightsExtraKind));const t=e.skeleton;c.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),u.addCPUSkinningFallback(0,e),t.isUsingTextureForMatrices?(c.push("#define BONETEXTURE"),-1===this._options.uniforms.indexOf("boneTextureWidth")&&this._options.uniforms.push("boneTextureWidth"),-1===this._options.samplers.indexOf("boneSampler")&&this._options.samplers.push("boneSampler")):(c.push("#define BonesPerMesh "+(t.bones.length+1)),-1===this._options.uniforms.indexOf("mBones")&&this._options.uniforms.push("mBones"))}else c.push("#define NUM_BONE_INFLUENCERS 0");let g=0;const v=e?e.morphTargetManager:null;if(v){const e=v.supportsUVs&&-1!==c.indexOf("#define UV1"),t=v.supportsTangents&&-1!==c.indexOf("#define TANGENT"),i=v.supportsNormals&&-1!==c.indexOf("#define NORMAL");g=v.numInfluencers,e&&c.push("#define MORPHTARGETS_UV"),t&&c.push("#define MORPHTARGETS_TANGENT"),i&&c.push("#define MORPHTARGETS_NORMAL"),g>0&&c.push("#define MORPHTARGETS"),v.isUsingTextureForTargets&&(c.push("#define MORPHTARGETS_TEXTURE"),-1===this._options.uniforms.indexOf("morphTargetTextureIndices")&&this._options.uniforms.push("morphTargetTextureIndices"),-1===this._options.samplers.indexOf("morphTargets")&&this._options.samplers.push("morphTargets")),c.push("#define NUM_MORPH_INFLUENCERS "+g);for(let n=0;n0&&(f=f.slice(),f.push("morphTargetInfluences"),f.push("morphTargetTextureInfo"),f.push("morphTargetTextureIndices"))}else c.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const t=e.bakedVertexAnimationManager;t&&t.isEnabled&&(c.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),-1===this._options.uniforms.indexOf("bakedVertexAnimationSettings")&&this._options.uniforms.push("bakedVertexAnimationSettings"),-1===this._options.uniforms.indexOf("bakedVertexAnimationTextureSizeInverted")&&this._options.uniforms.push("bakedVertexAnimationTextureSizeInverted"),-1===this._options.uniforms.indexOf("bakedVertexAnimationTime")&&this._options.uniforms.push("bakedVertexAnimationTime"),-1===this._options.samplers.indexOf("bakedVertexAnimationTexture")&&this._options.samplers.push("bakedVertexAnimationTexture")),It.G.PrepareAttributesForBakedVertexAnimation(d,e,c)}for(const C in this._textures)if(!this._textures[C].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&c.push("#define ALPHATEST"),!1!==this._options.useClipPlane&&((0,ua.qx)(f),(0,ua.lK)(this,l,c)),this.customShaderNameResolve&&(f=f.slice(),_=_.slice(),m=m.slice(),p=this.customShaderNameResolve(p,f,_,m,c,d));const T=a?i._getDrawWrapper():this._drawWrapper,S=null!==(n=null==T?void 0:T.effect)&&void 0!==n?n:null,E=null!==(s=null==T?void 0:T.defines)&&void 0!==s?s:null,x=c.join("\n");let b=S;return E!==x&&(b=h.createEffect(p,{attributes:d,uniformsNames:f,uniformBuffersNames:_,samplers:m,defines:x,fallbacks:u,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:g},shaderLanguage:this._options.shaderLanguage},h),a?i.setEffect(b,x,this._materialContext):T&&T.setEffect(b,x),this._onEffectCreatedObservable&&(Pl.effect=b,Pl.subMesh=null!==(r=null!=i?i:null==e?void 0:e.subMeshes[0])&&void 0!==r?r:null,this._onEffectCreatedObservable.notifyObservers(Pl))),b._wasPreviouslyUsingInstances=!!t,null!==(o=!(null==b?void 0:b.isReady()))&&void 0!==o&&!o&&(S!==b&&l.resetCachedMaterial(),b._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){const i=this.getScene(),n=null!=t?t:this.getEffect();n&&(-1!==this._options.uniforms.indexOf("world")&&n.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),n.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),n.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)))}bindForSubMesh(e,t,i){var n;this.bind(e,t,null===(n=i._drawWrapperOverride)||void 0===n?void 0:n.effect,i)}bind(e,t,i,n){var s;const r=n&&this._storeEffectOnSubMeshes,o=null!=i?i:r?n.effect:this.getEffect();if(!o)return;this._activeEffect=o,this.bindOnlyWorldMatrix(e,i);const a=this._options.uniformBuffers;let l=!1;if(o&&a&&a.length>0&&this.getScene().getEngine().supportsUniformBuffers)for(let c=0;c0&&It.G.BindMorphTargetParameters(t,o);const i=t.bakedVertexAnimationManager;i&&i.isEnabled&&(null===(s=t.bakedVertexAnimationManager)||void 0===s||s.bind(o,!!o._wasPreviouslyUsingInstances))}this._afterBind(t,o)}getActiveTextures(){const e=super.getActiveTextures();for(const t in this._textures)e.push(this._textures[t]);for(const t in this._textureArrays){const i=this._textureArrays[t];for(let t=0;tnew Il(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes)),this);t.name=e,t.id=e,"object"==typeof t._shaderPath&&(t._shaderPath=Object.assign({},t._shaderPath)),this._options=Object.assign({},this._options),Object.keys(this._options).forEach((e=>{const t=this._options[e];Array.isArray(t)&&(this._options[e]=t.slice(0))})),this.stencil.copyTo(t.stencil);for(const i in this._textures)t.setTexture(i,this._textures[i]);for(const i in this._textureArrays)t.setTextureArray(i,this._textureArrays[i]);for(const i in this._externalTextures)t.setExternalTexture(i,this._externalTextures[i]);for(const i in this._ints)t.setInt(i,this._ints[i]);for(const i in this._uints)t.setUInt(i,this._uints[i]);for(const i in this._floats)t.setFloat(i,this._floats[i]);for(const i in this._floatsArrays)t.setFloats(i,this._floatsArrays[i]);for(const i in this._colors3)t.setColor3(i,this._colors3[i]);for(const i in this._colors3Arrays)t._colors3Arrays[i]=this._colors3Arrays[i];for(const i in this._colors4)t.setColor4(i,this._colors4[i]);for(const i in this._colors4Arrays)t._colors4Arrays[i]=this._colors4Arrays[i];for(const i in this._vectors2)t.setVector2(i,this._vectors2[i]);for(const i in this._vectors3)t.setVector3(i,this._vectors3[i]);for(const i in this._vectors4)t.setVector4(i,this._vectors4[i]);for(const i in this._quaternions)t.setQuaternion(i,this._quaternions[i]);for(const i in this._quaternionsArrays)t._quaternionsArrays[i]=this._quaternionsArrays[i];for(const i in this._matrices)t.setMatrix(i,this._matrices[i]);for(const i in this._matrixArrays)t._matrixArrays[i]=this._matrixArrays[i].slice();for(const i in this._matrices3x3)t.setMatrix3x3(i,this._matrices3x3[i]);for(const i in this._matrices2x2)t.setMatrix2x2(i,this._matrices2x2[i]);for(const i in this._vectors2Arrays)t.setArray2(i,this._vectors2Arrays[i]);for(const i in this._vectors3Arrays)t.setArray3(i,this._vectors3Arrays[i]);for(const i in this._vectors4Arrays)t.setArray4(i,this._vectors4Arrays[i]);for(const i in this._uniformBuffers)t.setUniformBuffer(i,this._uniformBuffers[i]);for(const i in this._textureSamplers)t.setTextureSampler(i,this._textureSamplers[i]);for(const i in this._storageBuffers)t.setStorageBuffer(i,this._storageBuffers[i]);return t}dispose(e,t,i){if(t){let e;for(e in this._textures)this._textures[e].dispose();for(e in this._textureArrays){const t=this._textureArrays[e];for(let e=0;enew Il(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes)),e,t,i);let s;for(s in e.stencil&&n.stencil.parse(e.stencil,t,i),e.textures)n.setTexture(s,Le.Parse(e.textures[s],t,i));for(s in e.textureArrays){const r=e.textureArrays[s],o=new Array;for(let e=0;e(i%3==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>a.Wo.FromArray(e)));n.setColor3Array(s,t)}for(s in e.colors4)n.setColor4(s,a.HE.FromArray(e.colors4[s]));for(s in e.colors4Arrays){const t=e.colors4Arrays[s].reduce(((e,t,i)=>(i%4==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>a.HE.FromArray(e)));n.setColor4Array(s,t)}for(s in e.vectors2)n.setVector2(s,o.FM.FromArray(e.vectors2[s]));for(s in e.vectors3)n.setVector3(s,o.P.FromArray(e.vectors3[s]));for(s in e.vectors4)n.setVector4(s,o.Lt.FromArray(e.vectors4[s]));for(s in e.quaternions)n.setQuaternion(s,o._f.FromArray(e.quaternions[s]));for(s in e.matrices)n.setMatrix(s,o.y3.FromArray(e.matrices[s]));for(s in e.matrixArray)n._matrixArrays[s]=new Float32Array(e.matrixArray[s]);for(s in e.matrices3x3)n.setMatrix3x3(s,e.matrices3x3[s]);for(s in e.matrices2x2)n.setMatrix2x2(s,e.matrices2x2[s]);for(s in e.vectors2Arrays)n.setArray2(s,e.vectors2Arrays[s]);for(s in e.vectors3Arrays)n.setArray3(s,e.vectors3Arrays[s]);for(s in e.vectors4Arrays)n.setArray4(s,e.vectors4Arrays[s]);for(s in e.quaternionsArrays)n.setArray4(s,e.quaternionsArrays[s]);return n}static ParseFromFileAsync(e,t,i,n=""){return new Promise(((s,r)=>{const o=new y.g;o.addEventListener("readystatechange",(()=>{if(4==o.readyState)if(200==o.status){const t=JSON.parse(o.responseText),r=this.Parse(t,i||m.l.LastCreatedScene,n);e&&(r.name=e),s(r)}else r("Unable to load the ShaderMaterial")})),o.open("GET",t),o.send()}))}static ParseFromSnippetAsync(e,t,i=""){return new Promise(((n,s)=>{const r=new y.g;r.addEventListener("readystatechange",(()=>{if(4==r.readyState)if(200==r.status){const s=JSON.parse(JSON.parse(r.responseText).jsonPayload),o=JSON.parse(s.shaderMaterial),a=this.Parse(o,t||m.l.LastCreatedScene,i);a.snippetId=e,n(a)}else s("Unable to load the snippet "+e)})),r.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),r.send()}))}}Il.SnippetUrl="https://snippet.babylonjs.com",Il.CreateFromSnippetAsync=Il.ParseFromSnippetAsync,(0,l.H)("BABYLON.ShaderMaterial",Il);const Ml="colorPixelShader",Ol="#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\n#define VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ht.v.ShadersStore[Ml]=Ol;const Dl="colorVertexShader",Nl="attribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\n#include\nuniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {\ngl_Position=viewProjection*worldPos;\n} else {\ngl_Position=viewProjectionR*worldPos;\n}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";Ht.v.ShadersStore[Dl]=Nl;ee.Kj._LinesMeshParser=(e,t)=>Fl.Parse(e,t);class Fl extends ee.Kj{_isShaderMaterial(e){return"ShaderMaterial"===e.getClassName()}constructor(e,t=null,i=null,n=null,s,r,o,l){super(e,t,i,n,s),this.useVertexColor=r,this.useVertexAlpha=o,this.color=new a.Wo(1,1,1),this.alpha=1,n&&(this.color=n.color.clone(),this.alpha=n.alpha,this.useVertexColor=n.useVertexColor,this.useVertexAlpha=n.useVertexAlpha),this.intersectionThreshold=.1;const h={attributes:[ne.o.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:[],useClipPlane:null};!1===o?h.needAlphaBlending=!1:h.defines.push("#define VERTEXALPHA"),r?(h.defines.push("#define VERTEXCOLOR"),h.attributes.push(ne.o.ColorKind)):(h.uniforms.push("color"),this._color4=new a.HE),l?this.material=l:(this.material=new Il("colorShader",this.getScene(),"color",h,!1),this.material.doNotSerialize=!0)}isReady(){return!!this._lineMaterial.isReady(this,!!this._userInstancedBuffersStorage)&&super.isReady()}getClassName(){return"LinesMesh"}get material(){return this._lineMaterial}set material(e){this._lineMaterial=e,this._lineMaterial.fillMode=ut.F.LineListDrawMode}get checkCollisions(){return!1}set checkCollisions(e){}_bind(e,t){if(!this._geometry)return this;const i=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(this._userInstancedBuffersStorage?this._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(t,i),!this.useVertexColor&&this._isShaderMaterial(this._lineMaterial)){const{r:e,g:t,b:i}=this.color;this._color4.set(e,t,i,this.alpha),this._lineMaterial.setColor4("color",this._color4)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const n=this.getScene().getEngine();return this._unIndexed?n.drawArraysType(ut.F.LineListDrawMode,e.verticesStart,e.verticesCount,i):n.drawElementsType(ut.F.LineListDrawMode,e.indexStart,e.indexCount,i),this}dispose(e,t=!1,i){i||this._lineMaterial.dispose(!1,!1,!0),super.dispose(e)}clone(e,t=null,i){return new Fl(e,this.getScene(),t,this,i)}createInstance(e){const t=new wl(e,this);if(this.instancedBuffers){t.instancedBuffers={};for(const e in this.instancedBuffers)t.instancedBuffers[e]=this.instancedBuffers[e]}return t}serialize(e){super.serialize(e),e.color=this.color.asArray(),e.alpha=this.alpha}static Parse(e,t){const i=new Fl(e.name,t);return i.color=a.Wo.FromArray(e.color),i.alpha=e.alpha,i}}class wl extends re{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}function Ll(e){const t=[],i=[],n=e.lines,s=e.colors,r=[];let o=0;for(let l=0;l0&&(t.push(o-1),t.push(o)),o++}}const a=new Qe.x;return a.indices=t,a.positions=i,s&&(a.colors=r),a}function Bl(e){const t=e.dashSize||3,i=e.gapSize||1,n=e.dashNb||200,s=e.points,r=new Array,a=new Array,l=o.P.Zero();let h=0,c=0,d=0,u=0,p=0,f=0,_=0;for(_=0;_{const t=o.P.Zero(),i=e.length/6;let r=0,a=0,l=0,h=0,c=0,d=0,u=0,p=0;for(u=0;uVl(e,{points:t,updatable:n,instance:s},i),ee.Kj.CreateDashedLines=(e,t,i,n,s,r=null,o,a)=>kl(e,{points:t,dashSize:i,gapSize:n,dashNb:s,updatable:o,instance:a},r);class Gl extends o.FM{constructor(e,t){super(e.x,e.y),this.index=t}}class zl{constructor(){this.elements=new Array}add(e){const t=new Array;return e.forEach((e=>{const i=new Gl(e,this.elements.length);t.push(i),this.elements.push(i)})),t}computeBounds(){const e=new o.FM(this.elements[0].x,this.elements[0].y),t=new o.FM(this.elements[0].x,this.elements[0].y);return this.elements.forEach((i=>{i.xt.x&&(t.x=i.x),i.yt.y&&(t.y=i.y)})),{min:e,max:t,width:t.x-e.x,height:t.y-e.y}}}class Wl{_addToepoint(e){for(const t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,n=earcut){let s;this._points=new zl,this._outlinepoints=new zl,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=n,this._name=e,this._scene=i||m.l.LastCreatedScene,s=t instanceof W?t.getPoints():t,this._addToepoint(s),this._points.add(s),this._outlinepoints.add(s),void 0===this.bjsEarcut&&p.Y.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);const t=new zl;return t.add(e),this._holes.push(t),this._eholes.push(this._epoints.length/2),this._addToepoint(e),this}build(e=!1,t=0,i=2){const n=new ee.Kj(this._name,this._scene),s=this.buildVertexData(t,i);return n.setVerticesData(ne.o.PositionKind,s.positions,e),n.setVerticesData(ne.o.NormalKind,s.normals,e),n.setVerticesData(ne.o.UVKind,s.uvs,e),n.setIndices(s.indices),n}buildVertexData(e=0,t=2){const i=new Qe.x,n=new Array,s=new Array,r=new Array,o=this._points.computeBounds();this._points.elements.forEach((e=>{n.push(0,1,0),s.push(e.x,0,e.y),r.push((e.x-o.min.x)/o.width,(e.y-o.min.y)/o.height)}));const a=new Array,l=this.bjsEarcut(this._epoints,this._eholes,2);for(let h=0;h0){const i=s.length/3;this._points.elements.forEach((t=>{n.push(0,-1,0),s.push(t.x,-e,t.y),r.push(1-(t.x-o.min.x)/o.width,1-(t.y-o.min.y)/o.height)}));const l=a.length;for(let e=0;e{this._addSide(s,n,r,a,o,i,e,!0,t)}))}return i.indices=a,i.positions=s,i.normals=n,i.uvs=r,i}_addSide(e,t,i,n,s,r,a,l,h){let c=e.length/3,d=0;for(let u=0;uh?bh?C1),o=t.rotationFunction||(()=>0),a=t.closePath||t.ribbonCloseArray||!1,l=t.closeShape||t.ribbonClosePath||!1,h=0===t.cap?0:t.cap||ee.Kj.NO_CAP,c=t.updatable,d=t.firstNormal||null,u=t.adjustFrame||!1;return ql(e,s,n,null,null,r,o,a,l,h,!0,i,!!c,ee.Kj._GetDefaultSideOrientation(t.sideOrientation),t.instance||null,t.invertUV||!1,t.frontUVs||null,t.backUVs||null,d,u)}function ql(e,t,i,n,s,r,a,l,h,c,d,u,p,f,_,m,g,v,T,S){const E=(e,t,i,n,s,r,a,l,h,c,d)=>{const u=i.getTangents(),p=i.getNormals(),f=i.getBinormals(),_=i.getDistances();if(d)for(let x=0;x0){let e=u[x-1];o.P.Dot(e,u[x])<0&&u[x].scaleInPlace(-1),e=p[x-1],o.P.Dot(e,p[x])<0&&p[x].scaleInPlace(-1),e=f[x-1],o.P.Dot(e,f[x])<0&&f[x].scaleInPlace(-1)}let m=0;const g=c&&l?l:()=>null!==r?r:0,v=c&&a?a:()=>null!==s?s:1;let T=h===ee.Kj.NO_CAP||h===ee.Kj.CAP_END?0:2;const S=o.jp.Matrix[0];for(let x=0;x{const t=Array(),i=o.P.Zero();let n;for(n=0;n3?0:c,d,S);const C=El(e,{pathArray:b,closeArray:l,closePath:h,updatable:p,sideOrientation:f,invertUV:m,frontUVs:g||void 0,backUVs:v||void 0},u);return C._creationDataStorage.pathArray=b,C._creationDataStorage.path3D=x,C._creationDataStorage.cap=c,C}Qe.x.CreatePolygon=Hl,ee.Kj.CreatePolygon=(e,t,i,n,s,r,o=earcut)=>Xl(e,{shape:t,holes:n,updatable:s,sideOrientation:r},i,o),ee.Kj.ExtrudePolygon=(e,t,i,n,s,r,o,a=earcut)=>Yl(e,{shape:t,holes:s,depth:i,updatable:r,sideOrientation:o},n,a);function $l(e,t,i=null){const n=t.arc?t.arc<=0||t.arc>1?1:t.arc:1,s=void 0===t.closed||t.closed,r=t.shape,a=t.radius||1,l=t.tessellation||64,h=t.clip||0,c=t.updatable,d=ee.Kj._GetDefaultSideOrientation(t.sideOrientation),u=t.cap||ee.Kj.NO_CAP,p=2*Math.PI,f=new Array,_=t.invertUV||!1;let m=0,g=0;const v=p/l*n;let T,S;for(m=0;m<=l-h;m++){for(S=[],u!=ee.Kj.CAP_START&&u!=ee.Kj.CAP_ALL||(S.push(new o.P(0,r[0].y,0)),S.push(new o.P(Math.cos(m*v)*r[0].x*a,r[0].y,Math.sin(m*v)*r[0].x*a))),g=0;gjl(e,{shape:t,path:i,scale:n,rotation:s,cap:0===r?0:r||ee.Kj.NO_CAP,sideOrientation:l,instance:h,updatable:a},o),ee.Kj.ExtrudeShapeCustom=(e,t,i,n,s,r,o,a,l,h,c,d)=>Kl(e,{shape:t,path:i,scaleFunction:n,rotationFunction:s,ribbonCloseArray:r,ribbonClosePath:o,cap:0===a?0:a||ee.Kj.NO_CAP,sideOrientation:c,instance:d,updatable:h},l);function Ql(e,t,i=null){const n=t.path;let s=t.instance,r=1;void 0!==t.radius?r=t.radius:s&&(r=s._creationDataStorage.radius);const a=t.tessellation||64,l=t.radiusFunction||null;let h=t.cap||ee.Kj.NO_CAP;const c=t.invertUV||!1,d=t.updatable,u=ee.Kj._GetDefaultSideOrientation(t.sideOrientation);t.arc=t.arc&&(t.arc<=0||t.arc>1)?1:t.arc||1;const p=(e,t,i,n,s,r,a,l)=>{const h=t.getTangents(),c=t.getNormals(),d=t.getDistances(),u=2*Math.PI/s*l,p=r||(()=>n);let f,_,m,g;const v=o.jp.Matrix[0];let T=a===ee.Kj.NO_CAP||a===ee.Kj.CAP_END?0:2;for(let E=0;E{const n=Array();for(let s=0;s3?0:h,_=p(n,f,new Array,r,a,l,h,t.arc);const m=El(e,{pathArray:_,closePath:!0,closeArray:!1,updatable:d,sideOrientation:u,invertUV:c,frontUVs:t.frontUVs,backUVs:t.backUVs},i);return m._creationDataStorage.pathArray=_,m._creationDataStorage.path3D=f,m._creationDataStorage.tessellation=a,m._creationDataStorage.cap=h,m._creationDataStorage.arc=t.arc,m._creationDataStorage.radius=r,m}ee.Kj.CreateLathe=(e,t,i,n,s,r,o)=>$l(e,{shape:t,radius:i,tessellation:n,sideOrientation:o,updatable:r},s);function Zl(e){const t=[];t[0]={vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},t[1]={vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},t[2]={vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},t[3]={vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},t[4]={vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},t[5]={vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},t[6]={vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},t[7]={vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},t[8]={vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},t[9]={vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},t[10]={vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},t[11]={vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},t[12]={vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},t[13]={vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},t[14]={vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]};const i=e.type&&(e.type<0||e.type>=t.length)?0:e.type||0,n=e.size,s=e.sizeX||n||1,r=e.sizeY||n||1,l=e.sizeZ||n||1,h=e.custom||t[i],c=h.face.length,d=e.faceUV||new Array(c),u=e.faceColors,p=void 0===e.flat||e.flat,f=0===e.sideOrientation?0:e.sideOrientation||Qe.x.DEFAULTSIDE,_=new Array,m=new Array,g=new Array,v=new Array,T=new Array;let S=0,E=0;const x=new Array;let b,C,y,A,R,P,I=0,M=0;if(p)for(M=0;MQl(e,{path:t,radius:i,tessellation:n,radiusFunction:s,arc:1,cap:r,updatable:a,sideOrientation:l,instance:h},o);Qe.x.CreatePolyhedron=Zl,ee.Kj.CreatePolyhedron=(e,t,i)=>Jl(e,t,i);const eh=new o.P(1,0,0),th=new o.P(-1,0,0),ih=new o.P(0,1,0),nh=new o.P(0,-1,0),sh=new o.P(0,0,1),rh=new o.P(0,0,-1);class oh{constructor(e=o.P.Zero(),t=o.P.Up(),i=o.FM.Zero(),n=0,s=0,r=null,a=null,l=null,h=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=n,this.vertexIdxForBones=s,this.localPositionOverride=r,this.localNormalOverride=a,this.matrixIndicesOverride=l,this.matrixWeightsOverride=h}clone(){var e,t,i,n;return new oh(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,null===(e=this.localPositionOverride)||void 0===e?void 0:e.slice(),null===(t=this.localNormalOverride)||void 0===t?void 0:t.slice(),null===(i=this.matrixIndicesOverride)||void 0===i?void 0:i.slice(),null===(n=this.matrixWeightsOverride)||void 0===n?void 0:n.slice())}}function ah(e,t,i){var n,s,r,a;const l=!!t.skeleton,h=i.localMode||l,c=null!==t.overrideMaterialSideOrientation&&void 0!==t.overrideMaterialSideOrientation,d=t.getIndices(),u=l?t.getPositionData(!0,!0):t.getVerticesData(ne.o.PositionKind),p=l?t.getNormalsData(!0,!0):t.getVerticesData(ne.o.NormalKind),f=h?l?t.getVerticesData(ne.o.PositionKind):u:null,_=h?l?t.getVerticesData(ne.o.NormalKind):p:null,m=t.getVerticesData(ne.o.UVKind),g=l?t.getVerticesData(ne.o.MatricesIndicesKind):null,v=l?t.getVerticesData(ne.o.MatricesWeightsKind):null,T=l?t.getVerticesData(ne.o.MatricesIndicesExtraKind):null,E=l?t.getVerticesData(ne.o.MatricesWeightsExtraKind):null,x=i.position||o.P.Zero();let b=i.normal||o.P.Up();const C=i.size||o.P.One(),y=i.angle||0;if(!b){const e=new o.P(0,0,1),i=t.getScene().activeCamera,n=o.P.TransformCoordinates(e,i.getWorldMatrix());b=i.globalPosition.subtract(n)}const A=-Math.atan2(b.z,b.x)-Math.PI/2,R=Math.sqrt(b.x*b.x+b.z*b.z),P=Math.atan2(b.y,R),I=new Qe.x;I.indices=[],I.positions=[],I.normals=[],I.uvs=[],I.matricesIndices=l?[]:null,I.matricesWeights=l?[]:null,I.matricesIndicesExtra=T?[]:null,I.matricesWeightsExtra=E?[]:null;let M=0;const O=(e,t)=>{const n=new oh;if(!d||!u||!p)return n;const s=d[e];if(n.vertexIdx=3*s,n.vertexIdxForBones=4*s,n.position=new o.P(u[3*s],u[3*s+1],u[3*s+2]),o.P.TransformCoordinatesToRef(n.position,t,n.position),n.normal=new o.P(p[3*s],p[3*s+1],p[3*s+2]),o.P.TransformNormalToRef(n.normal,t,n.normal),i.captureUVS&&m){const e=m[2*s+1];n.uv=new o.FM(m[2*s],we.e.UseOpenGLOrientationForUV?1-e:e)}return n},D=[0,0,0,0],N=(e,t)=>{if(0===e.length)return e;const i=.5*Math.abs(o.P.Dot(C,t)),n=(e,t,i,n)=>{for(let s=0;s{var r,a,l,h,c,d,u,p,m,T,E,x,b,C,y,A;const R=o.P.GetClipFactor(e.position,s.position,t,i);let P=D,I=D;if(g&&v){const t=e.matrixIndicesOverride?0:e.vertexIdxForBones,i=null!==(r=e.matrixIndicesOverride)&&void 0!==r?r:g,o=null!==(a=e.matrixWeightsOverride)&&void 0!==a?a:v,c=s.matrixIndicesOverride?0:s.vertexIdxForBones,d=null!==(l=s.matrixIndicesOverride)&&void 0!==l?l:g,u=null!==(h=s.matrixWeightsOverride)&&void 0!==h?h:v;P=[0,0,0,0],I=[0,0,0,0];let p=0;for(let e=0;e<4;++e)if(o[t+e]>0){const s=n(d,i[t+e],c,4);P[p]=i[t+e],I[p]=S.R.Lerp(o[t+e],s>=0?u[s]:0,R),p++}for(let e=0;e<4&&p<4;++e){const s=d[c+e];-1===n(i,s,t,4)&&(P[p]=s,I[p]=S.R.Lerp(0,u[c+e],R),p++)}const f=I[0]+I[1]+I[2]+I[3];I[0]/=f,I[1]/=f,I[2]/=f,I[3]/=f}const M=e.localPositionOverride?e.localPositionOverride[0]:null!==(c=null==f?void 0:f[e.vertexIdx])&&void 0!==c?c:0,O=e.localPositionOverride?e.localPositionOverride[1]:null!==(d=null==f?void 0:f[e.vertexIdx+1])&&void 0!==d?d:0,N=e.localPositionOverride?e.localPositionOverride[2]:null!==(u=null==f?void 0:f[e.vertexIdx+2])&&void 0!==u?u:0,F=s.localPositionOverride?s.localPositionOverride[0]:null!==(p=null==f?void 0:f[s.vertexIdx])&&void 0!==p?p:0,w=s.localPositionOverride?s.localPositionOverride[1]:null!==(m=null==f?void 0:f[s.vertexIdx+1])&&void 0!==m?m:0,L=s.localPositionOverride?s.localPositionOverride[2]:null!==(T=null==f?void 0:f[s.vertexIdx+2])&&void 0!==T?T:0,B=e.localNormalOverride?e.localNormalOverride[0]:null!==(E=null==_?void 0:_[e.vertexIdx])&&void 0!==E?E:0,U=e.localNormalOverride?e.localNormalOverride[1]:null!==(x=null==_?void 0:_[e.vertexIdx+1])&&void 0!==x?x:0,V=e.localNormalOverride?e.localNormalOverride[2]:null!==(b=null==_?void 0:_[e.vertexIdx+2])&&void 0!==b?b:0,k=B+((s.localNormalOverride?s.localNormalOverride[0]:null!==(C=null==_?void 0:_[s.vertexIdx])&&void 0!==C?C:0)-B)*R,G=U+((s.localNormalOverride?s.localNormalOverride[1]:null!==(y=null==_?void 0:_[s.vertexIdx+1])&&void 0!==y?y:0)-U)*R,z=V+((s.localNormalOverride?s.localNormalOverride[2]:null!==(A=null==_?void 0:_[s.vertexIdx+2])&&void 0!==A?A:0)-V)*R,W=Math.sqrt(k*k+G*G+z*z);return new oh(o.P.Lerp(e.position,s.position,R),o.P.Lerp(e.normal,s.normal,R).normalize(),o.FM.Lerp(e.uv,s.uv,R),-1,-1,f?[M+(F-M)*R,O+(w-O)*R,N+(L-N)*R]:null,_?[k/W,G/W,z/W]:null,P,I)};let r=null;e.length>3&&(r=new Array);for(let a=0;a0,p=o.P.Dot(e[a+1].position,t)-i>0,f=o.P.Dot(e[a+2].position,t)-i>0;switch(n=(u?1:0)+(p?1:0)+(f?1:0),n){case 0:e.length>3?(r.push(e[a]),r.push(e[a+1]),r.push(e[a+2])):r=e;break;case 1:if(r=null!=r?r:new Array,u&&(l=e[a+1],h=e[a+2],c=s(e[a],l),d=s(e[a],h)),p){l=e[a],h=e[a+2],c=s(e[a+1],l),d=s(e[a+1],h),r.push(c),r.push(h.clone()),r.push(l.clone()),r.push(h.clone()),r.push(c.clone()),r.push(d);break}f&&(l=e[a],h=e[a+1],c=s(e[a+2],l),d=s(e[a+2],h)),l&&h&&c&&d&&(r.push(l.clone()),r.push(h.clone()),r.push(c),r.push(d),r.push(c.clone()),r.push(h.clone()));break;case 2:r=null!=r?r:new Array,u||(l=e[a].clone(),h=s(l,e[a+1]),c=s(l,e[a+2]),r.push(l),r.push(h),r.push(c)),p||(l=e[a+1].clone(),h=s(l,e[a+2]),c=s(l,e[a]),r.push(l),r.push(h),r.push(c)),f||(l=e[a+2].clone(),h=s(l,e[a]),c=s(l,e[a+1]),r.push(l),r.push(h),r.push(c))}}return r},F=t instanceof ee.Kj?t:null,w=null==F?void 0:F._thinInstanceDataStorage.matrixData,L=(null==F?void 0:F.thinInstanceCount)||1,B=o.jp.Matrix[0];B.copyFrom(o.y3.IdentityReadOnly);for(let S=0;Sah(e,t,{position:i,normal:n,size:s,angle:r});class lh{constructor(e=0,t=0){this.x=e,this.y=t,e!==Math.floor(e)&&(Math.floor(e),p.Y.Warn("x is not an integer, floor(x) used")),t!==Math.floor(t)&&(Math.floor(t),p.Y.Warn("y is not an integer, floor(y) used"))}clone(){return new lh(this.x,this.y)}rotate60About(e){const t=this.x;return this.x=e.x+e.y-this.y,this.y=t+this.y-e.x,this}rotateNeg60About(e){const t=this.x;return this.x=t+this.y-e.y,this.y=e.x+e.y-t,this}rotate120(e,t){e!==Math.floor(e)&&(Math.floor(e),p.Y.Warn("m not an integer only floor(m) used")),t!==Math.floor(t)&&(Math.floor(t),p.Y.Warn("n not an integer only floor(n) used"));const i=this.x;return this.x=e-i-this.y,this.y=t+i,this}rotateNeg120(e,t){e!==Math.floor(e)&&(Math.floor(e),p.Y.Warn("m is not an integer, floor(m) used")),t!==Math.floor(t)&&(Math.floor(t),p.Y.Warn("n is not an integer, floor(n) used"));const i=this.x;return this.x=this.y-t,this.y=e+t-i-this.y,this}toCartesianOrigin(e,t){const i=o.P.Zero();return i.x=e.x+2*this.x*t+this.y*t,i.y=e.y+Math.sqrt(3)*this.y*t,i}static Zero(){return new lh(0,0)}}class hh{constructor(){this.cartesian=[],this.vertices=[],this.max=[],this.min=[],this.closestTo=[],this.innerFacets=[],this.isoVecsABOB=[],this.isoVecsOBOA=[],this.isoVecsBAOA=[],this.vertexTypes=[],this.IDATA=new ch("icosahedron","Regular",[[0,k.Q_,-1],[-k.Q_,1,0],[-1,0,-k.Q_],[1,0,-k.Q_],[k.Q_,1,0],[0,k.Q_,1],[-1,0,k.Q_],[-k.Q_,-1,0],[0,-k.Q_,-1],[k.Q_,-1,0],[1,0,k.Q_],[0,-k.Q_,1]],[[0,2,1],[0,3,2],[0,4,3],[0,5,4],[0,1,5],[7,6,1],[8,7,2],[9,8,3],[10,9,4],[6,10,5],[2,7,1],[3,8,2],[4,9,3],[5,10,4],[1,6,5],[11,6,7],[11,7,8],[11,8,9],[11,9,10],[11,10,6]])}setIndices(){let e=12;const t={},i=this.m,n=this.n;let s,r,o,a,l,h=i,c=1,d=0;0!==n&&(h=S.R.HCF(i,n)),c=i/h,d=n/h;const u=lh.Zero(),p=new lh(i,n),f=new lh(-n,i+n),_=lh.Zero(),m=lh.Zero(),g=lh.Zero();let v,T,E,x,b=[];const C=[],y=this.vertByDist,A=(i,n,s,r)=>{v=i+"|"+s,T=n+"|"+r,v in t||T in t?v in t&&!(T in t)?t[T]=t[v]:T in t&&!(v in t)&&(t[v]=t[T]):(t[v]=e,t[T]=e,e++),y[s][0]>2?C[t[v]]=[-y[s][0],y[s][1],t[v]]:C[t[v]]=[b[y[s][0]],y[s][1],t[v]]};this.IDATA.edgematch=[[1,"B"],[2,"B"],[3,"B"],[4,"B"],[0,"B"],[10,"O",14,"A"],[11,"O",10,"A"],[12,"O",11,"A"],[13,"O",12,"A"],[14,"O",13,"A"],[0,"O"],[1,"O"],[2,"O"],[3,"O"],[4,"O"],[19,"B",5,"A"],[15,"B",6,"A"],[16,"B",7,"A"],[17,"B",8,"A"],[18,"B",9,"A"]];for(let S=0;S<20;S++){if(b=this.IDATA.face[S],o=b[2],a=b[1],l=b[0],E=u.x+"|"+u.y,v=S+"|"+E,v in t||(t[v]=o,C[o]=[b[y[E][0]],y[E][1]]),E=p.x+"|"+p.y,v=S+"|"+E,v in t||(t[v]=a,C[a]=[b[y[E][0]],y[E][1]]),E=f.x+"|"+f.y,v=S+"|"+E,v in t||(t[v]=l,C[l]=[b[y[E][0]],y[E][1]]),s=this.IDATA.edgematch[S][0],r=this.IDATA.edgematch[S][1],"B"===r)for(let e=1;e2?C[t[v]]=[-y[E][0],y[E][1],t[v]]:C[t[v]]=[b[y[E][0]],y[E][1],t[v]])}this.closestTo=C,this.vecToidx=t}calcCoeffs(){const e=this.m,t=this.n,i=Math.sqrt(3)/3,n=e*e+t*t+e*t;this.coau=(e+t)/n,this.cobu=-t/n,this.coav=-i*(e-t)/n,this.cobv=i*(2*e+t)/n}createInnerFacets(){const e=this.m,t=this.n;for(let i=0;i0&&e0){const n=S.R.HCF(e,t),s=e/n,r=t/n;for(let a=1;ae.x-t.x)),i.sort(((e,t)=>e.y-t.y));const o=new Array(e+t+1),a=new Array(e+t+1);for(let S=0;S{const s=i.clone();return"A"===n&&s.rotateNeg120(e,t),"B"===n&&s.rotate120(e,t),s.x<0?s.y:s.x+s.y},u=[],p=[],f=[],_=[],m={},g=[];let v=-1,T=-1;for(let S=0;Se[2]-t[2])),g.sort(((e,t)=>e[3]-t[3])),g.sort(((e,t)=>e[1]-t[1])),g.sort(((e,t)=>e[0]-t[0]));for(let S=0;St.vecToidx[e+i])))}mapABOBtoDATA(e,t){const i=t.IDATA.edgematch[e][0];for(let n=0;n-1?i[r][1]>0&&t[i[r][0]].push([r,i[r][1]]):t[12].push([r,i[r][0]]);const n=[];for(let r=0;r<12;r++)n[r]=r;let s=12;for(let r=0;r<12;r++){t[r].sort(((e,t)=>e[1]-t[1]));for(let e=0;ee[3]-t[3]));for(let r=0;r0;)s=t[a],this.face[s].indexOf(o)>-1?(r=(this.face[s].indexOf(o)+1)%3,o=this.face[s][r],i.push(o),n.push(s),t.splice(a,1),a=0):a++;return this.adjacentFaces.push(i),n}toGoldbergPolyhedronData(){const e=new ch("GeoDual","Goldberg",[],[]);e.name="GD dual";const t=this.vertex.length,i=new Array(t);for(let l=0;l{n=0,s=0,r=0,o=this.face[t];for(let e=0;e<3;e++)a=this.vertex[o[e]],n+=a[0],s+=a[1],r+=a[2];e.vertex[t]=[n/3,s/3,r/3]}));return e}static BuildGeodesicData(e){const t=new dh("Geodesic-m-n","Geodesic",[[0,k.Q_,-1],[-k.Q_,1,0],[-1,0,-k.Q_],[1,0,-k.Q_],[k.Q_,1,0],[0,k.Q_,1],[-1,0,k.Q_],[-k.Q_,-1,0],[0,-k.Q_,-1],[k.Q_,-1,0],[1,0,k.Q_],[0,-k.Q_,1]],[]);e.setIndices(),e.calcCoeffs(),e.createInnerFacets(),e.edgeVecsABOB(),e.mapABOBtoOBOA(),e.mapABOBtoBAOA();for(let i=0;iuh.Parse(e,t);class uh extends ee.Kj{constructor(){super(...arguments),this.goldbergData={faceColors:[],faceCenters:[],faceZaxis:[],faceXaxis:[],faceYaxis:[],nbSharedFaces:0,nbUnsharedFaces:0,nbFaces:0,nbFacesAtPole:0,adjacentFaces:[]}}relatedGoldbergFace(e,t){return void 0===t?(e>this.goldbergData.nbUnsharedFaces-1&&(p.Y.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(p.Y.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(p.Y.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let i=0;i1&&(c=1),l.push(c,d);for(let e=0;e<6;e++)c=r.x+o*Math.cos(a+e*Math.PI/3),d=r.y+o*Math.sin(a+e*Math.PI/3),c<0&&(c=0),c>1&&(c=1),h.push(c,d);for(let e=n;ea.HE.FromArray(e))),i.faceCenters=i.faceCenters.map((e=>o.P.FromArray(e))),i.faceZaxis=i.faceZaxis.map((e=>o.P.FromArray(e))),i.faceXaxis=i.faceXaxis.map((e=>o.P.FromArray(e))),i.faceYaxis=i.faceYaxis.map((e=>o.P.FromArray(e)));const n=new uh(e.name,t);return n.goldbergData=i,n}}function ph(e,t,i=null){const n=t.size,s=t.sizeX||n||1,r=t.sizeY||n||1,l=t.sizeZ||n||1;let h=t.m||1;h!==Math.floor(h)&&(Math.floor(h),p.Y.Warn("m not an integer only floor(m) used"));let c=t.n||0;if(c!==Math.floor(c)&&(Math.floor(c),p.Y.Warn("n not an integer only floor(n) used")),c>h){const e=c;c=h,h=e,p.Y.Warn("n > m therefore m and n swapped")}const d=new hh;d.build(h,c);const u=dh.BuildGeodesicData(d),f=u.toGoldbergPolyhedronData(),_=new uh(e,i);t.sideOrientation=ee.Kj._GetDefaultSideOrientation(t.sideOrientation),_._originalBuilderSideOrientation=t.sideOrientation;const m=function(e,t){const i=e.size,n=e.sizeX||i||1,s=e.sizeY||i||1,r=e.sizeZ||i||1,a=0===e.sideOrientation?0:e.sideOrientation||Qe.x.DEFAULTSIDE,l=new Array,h=new Array,c=new Array,d=new Array;let u=1/0,p=-1/0,f=1/0,_=-1/0;for(let o=0;o0?this._holes.push(e):this._paths.push(e);if(!this._paths.length&&this._holes.length){const e=this._holes;this._holes=this._paths,this._paths=e}this._tempPaths.length=0}get paths(){return this._paths}get holes(){return this._holes}}function _h(e,t,i,n,s,r){const o=r.glyphs[e]||r.glyphs["?"];if(!o)return null;const a=new fh(s);if(o.o){const e=o.o.split(" ");for(let s=0,r=e.length;s\n #if NUM_BONE_INFLUENCERS == 0\n attribute vec4 matricesIndices;\n attribute vec4 matricesWeights;\n #endif\n #include\n\n #include\n\n varying vec3 vColor;\n\n uniform vec3 colorBase;\n uniform vec3 colorZero;\n uniform vec3 colorQuarter;\n uniform vec3 colorHalf;\n uniform vec3 colorFull;\n\n uniform float targetBoneIndex;\n\n void main() {\n vec3 positionUpdated = position;\n\n #include\n #include\n #include\n\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\n\n vec3 color = colorBase;\n float totalWeight = 0.;\n if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){\n totalWeight += matricesWeights[0];\n }\n if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){\n totalWeight += matricesWeights[1];\n }\n if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){\n totalWeight += matricesWeights[2];\n }\n if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){\n totalWeight += matricesWeights[3];\n }\n\n color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight));\n color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight));\n color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight));\n color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight));\n vColor = color;\n\n gl_Position = projection * view * worldPos;\n }",ft.Q.ShadersStore["boneWeights:"+h.name+"FragmentShader"]="\n precision highp float;\n varying vec3 vPosition;\n\n varying vec3 vColor;\n\n void main() {\n vec4 color = vec4(vColor, 1.0);\n gl_FragColor = color;\n }\n ";const m=new Il("boneWeight:"+h.name,t,{vertex:"boneWeights:"+h.name,fragment:"boneWeights:"+h.name},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorBase","colorZero","colorQuarter","colorHalf","colorFull","targetBoneIndex"]});return m.setColor3("colorBase",c),m.setColor3("colorZero",d),m.setColor3("colorQuarter",u),m.setColor3("colorHalf",p),m.setColor3("colorFull",f),m.setFloat("targetBoneIndex",_),m.getClassName=()=>"BoneWeightShader",m.transparencyMode=ut.F.MATERIAL_OPAQUE,m}static CreateSkeletonMapShader(e,t){var i;const n=e.skeleton,s=null!==(i=e.colorMap)&&void 0!==i?i:[{color:new a.Wo(1,.38,.18),location:0},{color:new a.Wo(.59,.18,1),location:.2},{color:new a.Wo(.59,1,.18),location:.4},{color:new a.Wo(1,.87,.17),location:.6},{color:new a.Wo(1,.17,.42),location:.8},{color:new a.Wo(.17,.68,1),location:1}],r=n.bones.length+1,o=gh._CreateBoneMapColorBuffer(r,s,t),l=new Il("boneWeights:"+n.name,t,{vertexSource:"precision highp float;\n\n attribute vec3 position;\n attribute vec2 uv;\n\n uniform mat4 view;\n uniform mat4 projection;\n uniform mat4 worldViewProjection;\n uniform float colorMap["+4*n.bones.length+"];\n\n #include\n #if NUM_BONE_INFLUENCERS == 0\n attribute vec4 matricesIndices;\n attribute vec4 matricesWeights;\n #endif\n #include\n #include\n\n varying vec3 vColor;\n\n void main() {\n vec3 positionUpdated = position;\n\n #include\n #include\n #include\n\n vec3 color = vec3(0.);\n bool first = true;\n\n for (int i = 0; i < 4; i++) {\n int boneIdx = int(matricesIndices[i]);\n float boneWgt = matricesWeights[i];\n\n vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]);\n\n if (boneWgt > 0.) {\n if (first) {\n first = false;\n color = c;\n } else {\n color = mix(color, c, boneWgt);\n }\n }\n }\n\n vColor = color;\n\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\n\n gl_Position = projection * view * worldPos;\n }",fragmentSource:"\n precision highp float;\n varying vec3 vColor;\n\n void main() {\n vec4 color = vec4( vColor, 1.0 );\n gl_FragColor = color;\n }\n "},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorMap"]});return l.setFloats("colorMap",o),l.getClassName=()=>"SkeletonMapShader",l.transparencyMode=ut.F.MATERIAL_OPAQUE,l}static _CreateBoneMapColorBuffer(e,t,i){const n=new ma("temp",{width:e,height:1},i,!1),s=n.getContext(),r=s.createLinearGradient(0,0,e,0);t.forEach((e=>{r.addColorStop(e.location,e.color.toHexString())})),s.fillStyle=r,s.fillRect(0,0,e,1),n.update();const o=[],a=s.getImageData(0,0,e,1).data;for(let l=0;lgh.DISPLAY_SPHERE_AND_SPURS&&(e=gh.DISPLAY_LINES),this.options.displayMode=e}constructor(e,t,i,n=!0,s=3,r={}){var o,l,h,c,d,u,p,f,_,m,g,v,T,S;this.skeleton=e,this.mesh=t,this.autoUpdateBonesMatrices=n,this.renderingGroupId=s,this.options=r,this.color=a.Wo.White(),this._debugLines=new Array,this._localAxes=null,this._isEnabled=!0,this._obs=null,this._scene=i,this._ready=!1,r.pauseAnimations=null===(o=r.pauseAnimations)||void 0===o||o,r.returnToRest=null!==(l=r.returnToRest)&&void 0!==l&&l,r.displayMode=null!==(h=r.displayMode)&&void 0!==h?h:gh.DISPLAY_LINES,r.displayOptions=null!==(c=r.displayOptions)&&void 0!==c?c:{},r.displayOptions.midStep=null!==(d=r.displayOptions.midStep)&&void 0!==d?d:.235,r.displayOptions.midStepFactor=null!==(u=r.displayOptions.midStepFactor)&&void 0!==u?u:.155,r.displayOptions.sphereBaseSize=null!==(p=r.displayOptions.sphereBaseSize)&&void 0!==p?p:.15,r.displayOptions.sphereScaleUnit=null!==(f=r.displayOptions.sphereScaleUnit)&&void 0!==f?f:2,r.displayOptions.sphereFactor=null!==(_=r.displayOptions.sphereFactor)&&void 0!==_?_:.865,r.displayOptions.spurFollowsChild=null!==(m=r.displayOptions.spurFollowsChild)&&void 0!==m&&m,r.displayOptions.showLocalAxes=null!==(g=r.displayOptions.showLocalAxes)&&void 0!==g&&g,r.displayOptions.localAxesSize=null!==(v=r.displayOptions.localAxesSize)&&void 0!==v?v:.075,r.computeBonesUsingShaders=null===(T=r.computeBonesUsingShaders)||void 0===T||T,r.useAllBones=null===(S=r.useAllBones)||void 0===S||S;const E=t.getVerticesData(ne.o.MatricesIndicesKind),x=t.getVerticesData(ne.o.MatricesWeightsKind);if(this._boneIndices=new Set,!r.useAllBones&&E&&x)for(let a=0;agh.DISPLAY_SPHERE_AND_SPURS&&(b=gh.DISPLAY_LINES),this.displayMode=b,this.update(),this._bindObs()}_bindObs(){if(this.displayMode===gh.DISPLAY_LINES)this._obs=this.scene.onBeforeRenderObservable.add((()=>{this._displayLinesUpdate()}))}update(){switch(this.displayMode){case gh.DISPLAY_LINES:this._displayLinesUpdate();break;case gh.DISPLAY_SPHERES:this._buildSpheresAndSpurs(!0);break;case gh.DISPLAY_SPHERE_AND_SPURS:this._buildSpheresAndSpurs(!1)}this._buildLocalAxes()}set isEnabled(e){this.isEnabled!==e&&(this._isEnabled=e,this.debugMesh&&this.debugMesh.setEnabled(e),e&&!this._obs?this._bindObs():!e&&this._obs&&(this.scene.onBeforeRenderObservable.remove(this._obs),this._obs=null))}get isEnabled(){return this._isEnabled}_getBonePosition(e,t,i,n=0,s=0,r=0){const a=o.jp.Matrix[0],l=t.getParent();if(a.copyFrom(t.getLocalMatrix()),0!==n||0!==s||0!==r){const e=o.jp.Matrix[1];o.y3.IdentityToRef(e),e.setTranslationFromFloats(n,s,r),e.multiplyToRef(a,a)}l&&a.multiplyToRef(l.getAbsoluteMatrix(),a),a.multiplyToRef(i,a),e.x=a.m[12],e.y=a.m[13],e.z=a.m[14]}_getLinesForBonesWithLength(e,t){const i=e.length,n=this.mesh.position;let s=0;for(let r=0;r=0;r--){const t=e[r],a=t.getParent();if(!a||!this._boneIndices.has(t.getIndex())&&!this.options.useAllBones)continue;let l=this._debugLines[i];l||(l=[o.P.Zero(),o.P.Zero()],this._debugLines[i]=l),t.getAbsolutePositionToRef(n,l[0]),a.getAbsolutePositionToRef(n,l[1]),l[0].subtractInPlace(s),l[1].subtractInPlace(s),i++}}_revert(e){this.options.pauseAnimations&&(this.scene.animationsEnabled=e,this.utilityLayer.utilityLayerScene.animationsEnabled=e)}_getAbsoluteBindPoseToRef(e,t){null!==e&&-1!==e._index?(this._getAbsoluteBindPoseToRef(e.getParent(),t),e.getBaseMatrix().multiplyToRef(t,t)):t.copyFrom(o.y3.Identity())}_buildSpheresAndSpurs(e=!0){var t,i;this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this._ready=!1;const n=null===(t=this.utilityLayer)||void 0===t?void 0:t.utilityLayerScene,s=this.skeleton.bones,r=[],a=[],l=this.scene.animationsEnabled;try{this.options.pauseAnimations&&(this.scene.animationsEnabled=!1,n.animationsEnabled=!1),this.options.returnToRest&&this.skeleton.returnToRest(),this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteMatrices();let t=Number.NEGATIVE_INFINITY;const h=this.options.displayOptions||{};for(let i=0;i{const s=new o.y3;i.getBaseMatrix().multiplyToRef(c,s);const r=new o.P;s.decompose(void 0,void 0,r);const u=o.P.Distance(d,r);if(u>t&&(t=u),e)return;const p=r.clone().subtract(d.clone()),f=p.length(),_=p.normalize().scale(f),m=h.midStep||.165,g=h.midStepFactor||.215,v=_.scale(m),T=Kl("skeletonViewer",{shape:[new o.P(1,-1,0),new o.P(1,1,0),new o.P(-1,1,0),new o.P(-1,-1,0),new o.P(1,-1,0)],path:[o.P.Zero(),v,_],scaleFunction:e=>{switch(e){case 0:case 2:return 0;case 1:return f*g}return 0},sideOrientation:ee.Kj.DEFAULTSIDE,updatable:!1},n),S=T.getTotalVertices(),E=[],x=[];for(let e=0;e9?x.push(i.getIndex(),0,0,0):x.push(l.getIndex(),0,0,0);T.position=d.clone(),T.setVerticesData(ne.o.MatricesWeightsKind,E,!1),T.setVerticesData(ne.o.MatricesIndicesKind,x,!1),T.convertToFlatShadedMesh(),a.push(T)}));const u=gl("skeletonViewer",{segments:6,diameter:h.sphereBaseSize||.2,updatable:!0},n),p=u.getTotalVertices(),f=[],_=[];for(let e=0;e{this._gpuFrameTimeToken||(this._gpuFrameTimeToken=this.startTimeQuery())})),this._onEndFrameObserver=this.onEndFrameObservable.add((()=>{if(!this._gpuFrameTimeToken)return;const e=this.endTimeQuery(this._gpuFrameTimeToken);e>-1&&(this._gpuFrameTimeToken=null,this._gpuFrameTime.fetchNewFrame(),this._gpuFrameTime.addCount(e,!0))}))):(this.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null))},fe.D.prototype._getGlAlgorithmType=function(e){return e===ie.x.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED},Object.defineProperty(ie.x.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(e){this._occlusionDataStorage.isOcclusionQueryInProgress=e},enumerable:!1,configurable:!0}),Object.defineProperty(ie.x.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new Eh),this.__occlusionDataStorage},enumerable:!1,configurable:!0}),Object.defineProperty(ie.x.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(e){this._occlusionDataStorage.isOccluded=e},enumerable:!0,configurable:!0}),Object.defineProperty(ie.x.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(e){this._occlusionDataStorage.occlusionQueryAlgorithmType=e},enumerable:!0,configurable:!0}),Object.defineProperty(ie.x.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(e){this._occlusionDataStorage.occlusionType=e},enumerable:!0,configurable:!0}),Object.defineProperty(ie.x.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(e){this._occlusionDataStorage.occlusionRetryCount=e},enumerable:!0,configurable:!0}),Object.defineProperty(ie.x.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(e){this._occlusionDataStorage.forceRenderingWhenOccluded=e},enumerable:!0,configurable:!0}),ie.x.prototype._checkOcclusionQuery=function(){const e=this._occlusionDataStorage;if(e.occlusionType===ie.x.OCCLUSION_TYPE_NONE)return e.isOccluded=!1,!1;const t=this.getEngine();if(!t.getCaps().supportOcclusionQuery)return e.isOccluded=!1,!1;if(!t.isQueryResultAvailable)return e.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&this._occlusionQuery){if(t.isQueryResultAvailable(this._occlusionQuery)){const i=t.getQueryResult(this._occlusionQuery);e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=!(i>0)}else{if(e.occlusionInternalRetryCounter++,!(-1!==e.occlusionRetryCount&&e.occlusionInternalRetryCounter>e.occlusionRetryCount))return e.occlusionType!==ie.x.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded;e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=e.occlusionType!==ie.x.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded}}const i=this.getScene();if(i.getBoundingBoxRenderer){const n=i.getBoundingBoxRenderer();null===this._occlusionQuery&&(this._occlusionQuery=t.createQuery()),t.beginOcclusionQuery(e.occlusionQueryAlgorithmType,this._occlusionQuery)&&(n.renderOcclusionBoundingBox(this),t.endOcclusionQuery(e.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return e.isOccluded};fe.D.prototype.createTransformFeedback=function(){const e=this._gl.createTransformFeedback();if(!e)throw new Error("Unable to create Transform Feedback");return e},fe.D.prototype.deleteTransformFeedback=function(e){this._gl.deleteTransformFeedback(e)},fe.D.prototype.bindTransformFeedback=function(e){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,e)},fe.D.prototype.beginTransformFeedback=function(e=!0){this._gl.beginTransformFeedback(e?this._gl.POINTS:this._gl.TRIANGLES)},fe.D.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()},fe.D.prototype.setTranformFeedbackVaryings=function(e,t){this._gl.transformFeedbackVaryings(e,t,this._gl.INTERLEAVED_ATTRIBS)},fe.D.prototype.bindTransformFeedbackBuffer=function(e){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,e?e.underlyingResource:null)},Ue.B.prototype.createExternalTexture=function(e){return null},Ue.B.prototype.setExternalTexture=function(e,t){throw new Error("setExternalTexture: This engine does not support external textures!")},Ue.B.prototype.updateVideoTexture=function(e,t,i){if(!e||e._isDisabled)return;const n=this._getInternalFormat(e.format),s=this._getRGBABufferInternalSizedFormat(0,e.format),r=this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0);this._unpackFlipY(!i);try{if(void 0===this._videoTextureSupported&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,n,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,n,this._gl.UNSIGNED_BYTE,t);else{if(!e._workingCanvas){e._workingCanvas=this.createCanvas(e.width,e.height);const t=e._workingCanvas.getContext("2d");if(!t)throw new Error("Unable to get 2d context");e._workingContext=t,e._workingCanvas.width=e.width,e._workingCanvas.height=e.height}e._workingContext.clearRect(0,0,e.width,e.height),e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e.width,e.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,n,this._gl.UNSIGNED_BYTE,e._workingCanvas)}e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),r||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}catch(o){e._isDisabled=!0}},Ue.B.prototype.restoreSingleAttachment=function(){const e=this._gl;this.bindAttachments([e.BACK])},Ue.B.prototype.restoreSingleAttachmentForRenderTarget=function(){const e=this._gl;this.bindAttachments([e.COLOR_ATTACHMENT0])},Ue.B.prototype.buildTextureLayout=function(e){const t=this._gl,i=[];for(let n=0;n1?"COLOR_ATTACHMENT"+t:"COLOR_ATTACHMENT"+t+"_WEBGL"],n.readBuffer(s[t]),n.drawBuffers(s),n.blitFramebuffer(0,0,i.width,i.height,0,0,i.width,i.height,n.COLOR_BUFFER_BIT,n.NEAREST)}for(let e=0;e1?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];n.drawBuffers(s)}for(let o=0;o1&&(13===t.depthTextureFormat||17===t.depthTextureFormat||16===t.depthTextureFormat||14===t.depthTextureFormat||18===t.depthTextureFormat)&&(l=t.depthTextureFormat));const S=this._gl,E=S.createFramebuffer();this._bindUnboundFramebuffer(E);const x=e.width||e,b=e.height||e,C=[],y=[],A=this.webGLVersion>1&&a&&(13===t.depthTextureFormat||17===t.depthTextureFormat||18===t.depthTextureFormat),R=this._setupFramebufferDepthAttachments(!A&&o,!a&&r,x,b);T._framebuffer=E,T._depthStencilBuffer=R,T._generateDepthBuffer=!a&&r,T._generateStencilBuffer=!A&&o,T._attachments=y;for(let P=0;P1||this.isWebGPU);const h=this.webGLVersion>1,m=S[h?"COLOR_ATTACHMENT"+P:"COLOR_ATTACHMENT"+P+"_WEBGL"];if(y.push(m),-1===o)continue;const g=new Be.l(this,Be.S.MultiRenderTarget);C[P]=g,S.activeTexture(S["TEXTURE"+P]),S.bindTexture(o,g._hardwareTexture.underlyingResource),S.texParameteri(o,S.TEXTURE_MAG_FILTER,l.mag),S.texParameteri(o,S.TEXTURE_MIN_FILTER,l.min),S.texParameteri(o,S.TEXTURE_WRAP_S,S.CLAMP_TO_EDGE),S.texParameteri(o,S.TEXTURE_WRAP_T,S.CLAMP_TO_EDGE);const T=this._getRGBABufferInternalSizedFormat(t,r,i),E=this._getInternalFormat(r),A=this._getWebGLTextureType(t);if(!h||35866!==o&&32879!==o)if(34067===o){for(let e=0;e<6;e++)S.texImage2D(S.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,T,x,b,0,E,A,null);g.isCube=!0}else S.texImage2D(S.TEXTURE_2D,0,T,x,b,0,E,A,null);else 35866===o?g.is2DArray=!0:g.is3D=!0,g.baseDepth=g.depth=a,S.texImage3D(o,0,T,x,b,a,0,E,A,null);s&&S.generateMipmap(o),this._bindTextureDirectly(o,null),g.baseWidth=x,g.baseHeight=b,g.width=x,g.height=b,g.isReady=!0,g.samples=1,g.generateMipMaps=s,g.samplingMode=e,g.type=t,g._useSRGBBuffer=i,g.format=r,this._internalTexturesCache.push(g)}if(a&&this._caps.depthTextureExtension){const e=new Be.l(this,Be.S.Depth);let t=5,i=S.DEPTH_COMPONENT16,n=S.DEPTH_COMPONENT,r=S.UNSIGNED_SHORT,o=S.DEPTH_ATTACHMENT;this.webGLVersion<2?i=S.DEPTH_COMPONENT:14===l?(t=1,r=S.FLOAT,i=S.DEPTH_COMPONENT32F):18===l?(t=0,r=S.FLOAT_32_UNSIGNED_INT_24_8_REV,i=S.DEPTH32F_STENCIL8,n=S.DEPTH_STENCIL,o=S.DEPTH_STENCIL_ATTACHMENT):16===l?(t=0,r=S.UNSIGNED_INT,i=S.DEPTH_COMPONENT24,o=S.DEPTH_ATTACHMENT):13!==l&&17!==l||(t=12,r=S.UNSIGNED_INT_24_8,i=S.DEPTH24_STENCIL8,n=S.DEPTH_STENCIL,o=S.DEPTH_STENCIL_ATTACHMENT),S.activeTexture(S.TEXTURE0),S.bindTexture(S.TEXTURE_2D,e._hardwareTexture.underlyingResource),S.texParameteri(S.TEXTURE_2D,S.TEXTURE_MAG_FILTER,S.NEAREST),S.texParameteri(S.TEXTURE_2D,S.TEXTURE_MIN_FILTER,S.NEAREST),S.texParameteri(S.TEXTURE_2D,S.TEXTURE_WRAP_S,S.CLAMP_TO_EDGE),S.texParameteri(S.TEXTURE_2D,S.TEXTURE_WRAP_T,S.CLAMP_TO_EDGE),S.texImage2D(S.TEXTURE_2D,0,i,x,b,0,n,r,null),S.framebufferTexture2D(S.FRAMEBUFFER,o,S.TEXTURE_2D,e._hardwareTexture.underlyingResource,0),e.baseWidth=x,e.baseHeight=b,e.width=x,e.height=b,e.isReady=!0,e.samples=1,e.generateMipMaps=s,e.samplingMode=1,e.format=l,e.type=t,C[h]=e,this._internalTexturesCache.push(e)}return T.setTextures(C),i&&S.drawBuffers(y),this._bindUnboundFramebuffer(null),T.setLayerAndFaceIndices(g,m),this.resetTextureCache(),T},Ue.B.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t,i=!0){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;const n=e._attachments.length;if(0===n)return 1;const s=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples);const r=!!e._depthStencilBuffer;if(r&&(s.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(s.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null),t>1&&"function"==typeof s.renderbufferStorageMultisample){const r=s.createFramebuffer();if(!r)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=r,this._bindUnboundFramebuffer(r);const o=[];for(let t=0;t1?"COLOR_ATTACHMENT"+i:"COLOR_ATTACHMENT"+i+"_WEBGL"],l=this._createRenderBuffer(n.width,n.height,t,-1,this._getRGBAMultiSampleBufferFormat(n.type,n.format),a);if(!l)throw new Error("Unable to create multi sampled framebuffer");r.addMSAARenderBuffer(l),n.samples=t,o.push(a)}i&&s.drawBuffers(o)}else this._bindUnboundFramebuffer(e._framebuffer);return r&&(e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t)),this._bindUnboundFramebuffer(null),t},Ue.B.prototype._createDepthStencilCubeTexture=function(e,t,i){const n=new Be.l(this,Be.S.DepthStencil);if(n.isCube=!0,1===this.webGLVersion)return p.Y.Error("Depth cube texture is not supported by WebGL 1."),n;const s=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},t),r=this._gl;this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,n,!0),this._setupDepthStencilTexture(n,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction),i._depthStencilTexture=n,i._depthStencilTextureWithStencil=s.generateStencil;for(let o=0;o<6;o++)s.generateStencil?r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+o,0,r.DEPTH24_STENCIL8,e,e,0,r.DEPTH_STENCIL,r.UNSIGNED_INT_24_8,null):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+o,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(n),n},Ue.B.prototype._partialLoadFile=function(e,t,i,n,s=null){this._loadFile(e,(e=>{i[t]=e,i._internalCount++,6===i._internalCount&&n(i)}),void 0,void 0,!0,((e,t)=>{s&&e&&s(e.status+" "+e.statusText,t)}))},Ue.B.prototype._cascadeLoadFiles=function(e,t,i,n=null){const s=[];s._internalCount=0;for(let r=0;r<6;r++)this._partialLoadFile(i[r],r,s,t,n)},Ue.B.prototype._cascadeLoadImgs=function(e,t,i,n,s=null,r){const o=[];o._internalCount=0;for(let a=0;a<6;a++)this._partialLoadImg(n[a],a,o,e,t,i,s,r)},Ue.B.prototype._partialLoadImg=function(e,t,i,n,s,r,o=null,a){const l=(0,Ce.f)();(0,ye.r6)(e,(e=>{i[t]=e,i._internalCount++,n&&n.removePendingData(l),6===i._internalCount&&r&&r(s,i)}),((e,t)=>{n&&n.removePendingData(l),o&&o(e,t)}),n?n.offlineProvider:null,a),n&&n.addPendingData(l)},Ue.B.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?3:2,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)},Ue.B.prototype.createCubeTextureBase=function(e,t,i,n,s=null,r=null,o,a=null,l=!1,h=0,c=0,d=null,u=null,f=null,_=!1){const m=d||new Be.l(this,Be.S.Cube);m.isCube=!0,m.url=e,m.generateMipMaps=!n,m._lodGenerationScale=h,m._lodGenerationOffset=c,m._useSRGBBuffer=!!_&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||!!n),m!==d&&(m.label=e.substring(0,60)),this._doNotHandleContextLost||(m._extension=a,m._files=i);const g=e;this._transformTextureUrl&&!d&&(e=this._transformTextureUrl(e));const v=e.split("?")[0],T=v.lastIndexOf("."),S=a||(T>-1?v.substring(T).toLowerCase():"");let E=null;for(const p of Ue.B._TextureLoaders)if(p.canLoad(S)){E=p;break}const x=(d,v)=>{e===g?r&&d&&r(d.status+" "+d.statusText,v):(p.Y.Warn(`Failed to load ${e}, falling back to the ${g}`),this.createCubeTextureBase(g,t,i,!!n,s,r,o,a,l,h,c,m,u,f,_))};if(E){const n=e=>{u&&u(m,e),E.loadCubeData(e,m,l,s,r)};i&&6===i.length?E.supportCascades?this._cascadeLoadFiles(t,(e=>n(e.map((e=>new Uint8Array(e))))),i,r):r?r("Textures type does not support cascades."):p.Y.Warn("Texture loader does not support cascades."):this._loadFile(e,(e=>n(new Uint8Array(e))),void 0,void 0,!0,x)}else{if(!i)throw new Error("Cannot load cubemap because files were not defined");this._cascadeLoadImgs(t,m,((e,t)=>{f&&f(e,t)}),i,r)}return this._internalTexturesCache.push(m),m},Ue.B.prototype.createCubeTexture=function(e,t,i,n,s=null,r=null,o,a=null,l=!1,h=0,c=0,d=null,u,f=!1){const _=this._gl;return this.createCubeTextureBase(e,t,i,!!n,s,r,o,a,l,h,c,d,(e=>this._bindTextureDirectly(_.TEXTURE_CUBE_MAP,e,!0)),((e,t)=>{const i=this.needPOTTextures?Ue.B.GetExponentOfTwo(t[0].width,this._caps.maxCubemapTextureSize):t[0].width,r=i,a=[_.TEXTURE_CUBE_MAP_POSITIVE_X,_.TEXTURE_CUBE_MAP_POSITIVE_Y,_.TEXTURE_CUBE_MAP_POSITIVE_Z,_.TEXTURE_CUBE_MAP_NEGATIVE_X,_.TEXTURE_CUBE_MAP_NEGATIVE_Y,_.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(_.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(!1);const l=o?this._getInternalFormat(o,e._useSRGBBuffer):e._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:_.RGBA;let h=o?this._getInternalFormat(o):_.RGBA;e._useSRGBBuffer&&1===this.webGLVersion&&(h=l);for(let n=0;n{this.unRegisterView(e)})),s},fe.D.prototype.unRegisterView=function(e){if(!this.views||0===this.views.length)return this;for(const t of this.views)if(t.target===e){const e=this.views.indexOf(t);-1!==e&&this.views.splice(e,1);break}return this},fe.D.prototype._renderViewStep=function(e){const t=e.target,i=t.getContext("2d");if(!i)return!0;const n=this.getRenderingCanvas();xh.notifyObservers(e);const s=e.camera;let r=null,o=null;if(s){if(o=s.getScene(),!o||o.activeCameras&&o.activeCameras.length)return!0;this.activeView=e,r=o.activeCamera,o.activeCamera=s}if(e.customResize)e.customResize(t);else{const e=Math.floor(t.clientWidth/this._hardwareScalingLevel),i=Math.floor(t.clientHeight/this._hardwareScalingLevel),s=e!==t.width||n.width!==t.width||i!==t.height||n.height!==t.height;t.clientWidth&&t.clientHeight&&s&&(t.width=e,t.height=i,this.setSize(e,i))}return!(!n.width||!n.height)&&(this._renderFrame(),this.flushFramebuffer(),e.clearBeforeCopy&&i.clearRect(0,0,n.width,n.height),i.drawImage(n,0,0),r&&o&&(o.activeCamera=r),bh.notifyObservers(e),!0)},fe.D.prototype._renderViews=function(){if(!this.views||0===this.views.length)return!1;if(!this.getRenderingCanvas())return!1;let e;for(const t of this.views){if(!t.enabled)continue;if(t.target!==this.inputElement){if(!this._renderViewStep(t))return!1}else e=t}return!(e&&!this._renderViewStep(e))&&(this.activeView=null,!0)};var Ch=i(9834);function yh(e){if(this._excludedCompressedTextures&&this._excludedCompressedTextures.some((t=>{const i="\\b"+t+"\\b";return e&&(e===t||e.match(new RegExp(i,"g")))})))return e;const t=e.lastIndexOf("."),i=e.lastIndexOf("?"),n=i>-1?e.substring(i,e.length):"";return(t>-1?e.substring(0,t):e)+this._textureFormatInUse+n}Ue.B.prototype.createStorageBuffer=function(e,t){throw new Error("createStorageBuffer: Unsupported method in this engine!")},Ue.B.prototype.updateStorageBuffer=function(e,t,i,n){},Ue.B.prototype.readFromStorageBuffer=function(e,t,i,n){throw new Error("readFromStorageBuffer: Unsupported method in this engine!")},Ue.B.prototype.setStorageBuffer=function(e,t){throw new Error("setStorageBuffer: Unsupported method in this engine!")},Object.defineProperty(fe.D.prototype,"texturesSupported",{get:function(){const e=new Array;return this._caps.astc&&e.push("-astc.ktx"),this._caps.s3tc&&e.push("-dxt.ktx"),this._caps.pvrtc&&e.push("-pvrtc.ktx"),this._caps.etc2&&e.push("-etc2.ktx"),this._caps.etc1&&e.push("-etc1.ktx"),e},enumerable:!0,configurable:!0}),Object.defineProperty(fe.D.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0}),fe.D.prototype.setCompressedTextureExclusions=function(e){this._excludedCompressedTextures=e},fe.D.prototype.setTextureFormatToUse=function(e){const t=this.texturesSupported;for(let i=0,n=t.length;i{this._flush()}))}writeUint32(e){this._flushIfNecessary(1),this._uint32s[this._position++]=e}writeInt32(e){this._flushIfNecessary(1),this._int32s[this._position++]=e}writeFloat32(e){this._flushIfNecessary(1),this._float32s[this._position++]=e}writeUint32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._uint32s.set(e,this._position),this._position+=e.length}writeInt32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._int32s.set(e,this._position),this._position+=e.length}writeFloat32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._float32s.set(e,this._position),this._position+=e.length}writeNativeData(e){this._flushIfNecessary(e.length),this._uint32s.set(e,this._position),this._position+=e.length}writeBoolean(e){this.writeUint32(e?1:0)}_flushIfNecessary(e){this._position+e>this._length&&this._flush()}_flush(){this._nativeDataStream.writeBuffer(this._uint32s.buffer,this._position),this._position=0}}Ah.DEFAULT_BUFFER_SIZE=65536;const Rh=[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))],Ph=[()=>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],Ih=(e,t)=>Rh[e]*Ph[e](t),Mh=[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 Oh{constructor(){this.preScaled=!1,this.l00=o.P.Zero(),this.l1_1=o.P.Zero(),this.l10=o.P.Zero(),this.l11=o.P.Zero(),this.l2_2=o.P.Zero(),this.l2_1=o.P.Zero(),this.l20=o.P.Zero(),this.l21=o.P.Zero(),this.l22=o.P.Zero()}addLight(e,t,i){o.jp.Vector3[0].set(t.r,t.g,t.b);const n=o.jp.Vector3[0],s=o.jp.Vector3[1];n.scaleToRef(i,s),s.scaleToRef(Ih(0,e),o.jp.Vector3[2]),this.l00.addInPlace(o.jp.Vector3[2]),s.scaleToRef(Ih(1,e),o.jp.Vector3[2]),this.l1_1.addInPlace(o.jp.Vector3[2]),s.scaleToRef(Ih(2,e),o.jp.Vector3[2]),this.l10.addInPlace(o.jp.Vector3[2]),s.scaleToRef(Ih(3,e),o.jp.Vector3[2]),this.l11.addInPlace(o.jp.Vector3[2]),s.scaleToRef(Ih(4,e),o.jp.Vector3[2]),this.l2_2.addInPlace(o.jp.Vector3[2]),s.scaleToRef(Ih(5,e),o.jp.Vector3[2]),this.l2_1.addInPlace(o.jp.Vector3[2]),s.scaleToRef(Ih(6,e),o.jp.Vector3[2]),this.l20.addInPlace(o.jp.Vector3[2]),s.scaleToRef(Ih(7,e),o.jp.Vector3[2]),this.l21.addInPlace(o.jp.Vector3[2]),s.scaleToRef(Ih(8,e),o.jp.Vector3[2]),this.l22.addInPlace(o.jp.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(Mh[0]),this.l1_1.scaleInPlace(Mh[1]),this.l10.scaleInPlace(Mh[2]),this.l11.scaleInPlace(Mh[3]),this.l2_2.scaleInPlace(Mh[4]),this.l2_1.scaleInPlace(Mh[5]),this.l20.scaleInPlace(Mh[6]),this.l21.scaleInPlace(Mh[7]),this.l22.scaleInPlace(Mh[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(Rh[0]),this.l1_1.scaleInPlace(Rh[1]),this.l10.scaleInPlace(Rh[2]),this.l11.scaleInPlace(Rh[3]),this.l2_2.scaleInPlace(Rh[4]),this.l2_1.scaleInPlace(Rh[5]),this.l20.scaleInPlace(Rh[6]),this.l21.scaleInPlace(Rh[7]),this.l22.scaleInPlace(Rh[8])}updateFromArray(e){return o.P.FromArrayToRef(e[0],0,this.l00),o.P.FromArrayToRef(e[1],0,this.l1_1),o.P.FromArrayToRef(e[2],0,this.l10),o.P.FromArrayToRef(e[3],0,this.l11),o.P.FromArrayToRef(e[4],0,this.l2_2),o.P.FromArrayToRef(e[5],0,this.l2_1),o.P.FromArrayToRef(e[6],0,this.l20),o.P.FromArrayToRef(e[7],0,this.l21),o.P.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return o.P.FromFloatsToRef(e[0],e[1],e[2],this.l00),o.P.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),o.P.FromFloatsToRef(e[6],e[7],e[8],this.l10),o.P.FromFloatsToRef(e[9],e[10],e[11],this.l11),o.P.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),o.P.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),o.P.FromFloatsToRef(e[18],e[19],e[20],this.l20),o.P.FromFloatsToRef(e[21],e[22],e[23],this.l21),o.P.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return(new Oh).updateFromArray(e)}static FromPolynomial(e){const t=new Oh;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 Dh{constructor(){this.x=o.P.Zero(),this.y=o.P.Zero(),this.z=o.P.Zero(),this.xx=o.P.Zero(),this.yy=o.P.Zero(),this.zz=o.P.Zero(),this.xy=o.P.Zero(),this.yz=o.P.Zero(),this.zx=o.P.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=Oh.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){o.jp.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=o.jp.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),o.jp.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),o.jp.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(o.jp.Vector3[0]).addInPlace(o.jp.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(o.jp.Vector3[0]).subtractInPlace(o.jp.Vector3[1]),this.zz.copyFrom(e.l00),o.jp.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(o.jp.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 Dh).updateFromHarmonics(e)}static FromArray(e){const t=new Dh;return o.P.FromArrayToRef(e[0],0,t.x),o.P.FromArrayToRef(e[1],0,t.y),o.P.FromArrayToRef(e[2],0,t.z),o.P.FromArrayToRef(e[3],0,t.xx),o.P.FromArrayToRef(e[4],0,t.yy),o.P.FromArrayToRef(e[5],0,t.zz),o.P.FromArrayToRef(e[6],0,t.yz),o.P.FromArrayToRef(e[7],0,t.zx),o.P.FromArrayToRef(e[8],0,t.xy),t}}const Nh="rgbdDecodePixelShader",Fh="varying vec2 vUV;\nuniform sampler2D textureSampler;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}";Ht.v.ShadersStore[Nh]=Fh;function wh(e,t,i,n,s,r,o,a){const l=t.getEngine();return t.isReady=!1,s=null!=s?s:t.samplingMode,n=null!=n?n:t.type,r=null!=r?r:t.format,o=null!=o?o:t.width,a=null!=a?a:t.height,-1===n&&(n=0),new Promise((h=>{const c=new Zt("postprocess",e,null,null,1,null,s,l,!1,void 0,n,void 0,null,!1,r);c.externalTextureSamplerBinding=!0;const d=l.createRenderTargetTexture({width:o,height:a},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:s,type:n,format:r});c.getEffect().executeWhenCompiled((()=>{c.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},i.postProcessManager.directRender([c],d,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(t),c&&c.dispose(),d._swapAndDie(t),t.type=n,t.format=5,t.isReady=!0,h(t)}))}))}let Lh,Bh;function Uh(e){Lh||(Lh=new Float32Array(1),Bh=new Int32Array(Lh.buffer)),Lh[0]=e;const t=Bh[0];let i=t>>16&32768,n=t>>12&2047;const s=t>>23&255;return s<103?i:s>142?(i|=31744,i|=(255==s?0:1)&&8388607&t,i):s<113?(n|=2048,i|=(n>>114-s)+(n>>113-s&1),i):(i|=s-112<<10|n>>1,i+=1&n,i)}function Vh(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))}class kh{static ExpandRGBDTexture(e){const t=e._texture;if(!t||!e.isRGBD)return;const i=t.getEngine(),n=i.getCaps(),s=t.isReady;let r=!1;n.textureHalfFloatRender&&n.textureHalfFloatLinearFiltering?(r=!0,t.type=2):n.textureFloatRender&&n.textureFloatLinearFiltering&&(r=!0,t.type=1),r&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);const o=()=>{if(r){const n=new Zt("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1);n.externalTextureSamplerBinding=!0;const s=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});n.getEffect().executeWhenCompiled((()=>{n.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([n],s,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),n&&n.dispose(),s._swapAndDie(t),t.isReady=!0}))}};s?o():e.onLoadObservable.addOnce(o)}static EncodeTextureToRGBD(e,t,i=0){return wh("rgbdEncode",e,t,i,1,5)}}class Gh{constructor(e,t,i,n){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=n}}class zh{static ConvertCubeMapTextureToSphericalPolynomial(e){var t;if(!e.isCube)return null;null===(t=e.getScene())||void 0===t||t.getEngine().flushFramebuffer();const i=e.getSize().width,n=e.readPixels(0,void 0,void 0,!1),s=e.readPixels(1,void 0,void 0,!1);let r,o;e.isRenderTarget?(r=e.readPixels(3,void 0,void 0,!1),o=e.readPixels(2,void 0,void 0,!1)):(r=e.readPixels(2,void 0,void 0,!1),o=e.readPixels(3,void 0,void 0,!1));const a=e.readPixels(4,void 0,void 0,!1),l=e.readPixels(5,void 0,void 0,!1),h=e.gammaSpace;let c=0;return 1!=e.textureType&&2!=e.textureType||(c=1),new Promise((e=>{Promise.all([s,n,r,o,a,l]).then((([t,n,s,r,o,a])=>{const l={size:i,right:n,left:t,up:s,down:r,front:o,back:a,format:5,type:c,gammaSpace:h};e(this.ConvertCubeMapToSphericalPolynomial(l))}))}))}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){const t=new Oh;let i=0;const n=2/e.size,s=n,r=.5*n,o=r-1;for(let h=0;h<6;h++){const l=this._FileFaces[h],c=e[l.name];let d=o;const u=5===e.format?4:3;for(let h=0;hv){const t=v/e;_*=t,m*=t,g*=t}}else _=S.R.Clamp(_,0,v),m=S.R.Clamp(m,0,v),g=S.R.Clamp(g,0,v);const T=new a.Wo(_,m,g);t.addLight(o,T,f),i+=f,p+=n}d+=s}}const l=6*(4*Math.PI)/6/i;return t.scaleInPlace(l),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),Dh.FromHarmonics(t)}}zh._FileFaces=[new Gh("right",new o.P(1,0,0),new o.P(0,0,-1),new o.P(0,-1,0)),new Gh("left",new o.P(-1,0,0),new o.P(0,0,1),new o.P(0,-1,0)),new Gh("up",new o.P(0,1,0),new o.P(1,0,0),new o.P(0,0,1)),new Gh("down",new o.P(0,-1,0),new o.P(1,0,0),new o.P(0,0,-1)),new Gh("front",new o.P(0,0,1),new o.P(1,0,0),new o.P(0,-1,0)),new Gh("back",new o.P(0,0,-1),new o.P(-1,0,0),new o.P(0,-1,0))],zh.MAX_HDRI_VALUE=4096,zh.PRESERVE_CLAMPED_COLORS=!1,Re.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)},Object.defineProperty(Re.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=zh.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});const Wh="rgbdEncodePixelShader",Hh="varying vec2 vUV;\nuniform sampler2D textureSampler;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}";Ht.v.ShadersStore[Wh]=Hh;const Xh="image/png",Yh=2,jh=[134,22,135,150,246,214,150,54];function Kh(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);let i=0;for(let o=0;oYh)throw new Error(`Unsupported babylon environment map version "${e.version}". Latest supported version is "${Yh}".`);return 2===e.version?e:e=Object.assign(Object.assign({},e),{version:2,imageType:Xh})}function $h(e,t){const i=(t=qh(t)).specular;let n=S.R.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 s=new Array(n);for(let r=0;r{if(i){const i=t.createTexture(null,!0,!0,null,1,null,(e=>{u(e)}),e);n.getEffect().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],h,!0,r,o),t.restoreDefaultFramebuffer(),i.dispose(),URL.revokeObjectURL(s),d())}))}else{if(t._uploadImageToTexture(c,e,r,o),a){const i=l[o];i&&t._uploadImageToTexture(i._texture,e,r,0)}d()}}))}function Jh(e,t,i=Xh){if(!se.w1.IsExponentOfTwo(e.width))throw new Error("Texture size must be a power of two");const n=S.R.ILog2(e.width)+1,s=e.getEngine();let r=!1,o=!1,a=null,l=null,h=null;const c=s.getCaps();if(e.format=5,e.type=0,e.generateMipMaps=!0,e._cachedAnisotropicFilteringLevel=null,s.updateTextureSamplingMode(3,e),c.textureLOD?s._features.supportRenderAndCopyToLodForFloatTextures?c.textureHalfFloatRender&&c.textureHalfFloatLinearFiltering?(r=!0,e.type=2):c.textureFloatRender&&c.textureFloatLinearFiltering&&(r=!0,e.type=1):r=!1:(r=!1,o=!0,h={}),r)a=new Zt("rgbdDecode","rgbdDecode",null,null,1,null,3,s,!1,void 0,e.type,void 0,null,!1),e._isRGBD=!1,e.invertY=!1,l=s.createRenderTargetCubeTexture(e.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:e.type,format:5});else if(e._isRGBD=!0,e.invertY=!0,o){const t=3,i=e._lodGenerationScale,r=e._lodGenerationOffset;for(let o=0;oZh(t,s,r,a,f,n,u,o,h,l,e)));else{const t=new Image;t.src=f,_=new Promise(((i,c)=>{t.onload=()=>{Zh(t,s,r,a,f,n,u,o,h,l,e).then((()=>i())).catch((e=>{c(e)}))},t.onerror=e=>{c(e)}}))}d.push(_)}if(t.length{l&&(s._releaseTexture(e),l._swapAndDie(e)),a&&a.dispose(),o&&(e._lodTextureHigh&&e._lodTextureHigh._texture&&(e._lodTextureHigh._texture.isReady=!0),e._lodTextureMid&&e._lodTextureMid._texture&&(e._lodTextureMid._texture.isReady=!0),e._lodTextureLow&&e._lodTextureLow._texture&&(e._lodTextureLow._texture.isReady=!0))}))}function ec(e,t){const i=(t=qh(t)).irradiance;if(!i)return;const n=new Dh;o.P.FromArrayToRef(i.x,0,n.x),o.P.FromArrayToRef(i.y,0,n.y),o.P.FromArrayToRef(i.z,0,n.z),o.P.FromArrayToRef(i.xx,0,n.xx),o.P.FromArrayToRef(i.yy,0,n.yy),o.P.FromArrayToRef(i.zz,0,n.zz),o.P.FromArrayToRef(i.yz,0,n.yz),o.P.FromArrayToRef(i.zx,0,n.zx),o.P.FromArrayToRef(i.xy,0,n.xy),e._sphericalPolynomial=n}function tc(e,t,i,n){let s=n,r=0,o="";for(;s=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||95==t}function sc(e){let t=0,i="",n=!1;const s=[];for(;t=0&&e.charAt(t)!==i;)t--;return t}class oc{get code(){return this._sourceCode}constructor(e,t=20){this.debug=!1,this._sourceCode=e,this._numMaxIterations=t,this._functionDescr=[],this.inlineToken="#define inline"}processCode(){this.debug&&console.log(`Start inlining process (code size=${this._sourceCode.length})...`),this._collectFunctions(),this._processInlining(this._numMaxIterations),this.debug&&console.log("End of inlining process.")}_collectFunctions(){let e=0;for(;e=0&&u.push(t.substring(i+1))}"void"!==s&&u.push("return"),this._functionDescr.push({name:r,type:s,parameters:u,body:c,callIndex:0}),e=h+1;const p=t>0?this._sourceCode.substring(0,t):"",f=h+1=0&&this._replaceFunctionCallsByCode(););return this.debug&&console.log(`numMaxIterations is ${e} after inlining process`),e>=0}_replaceFunctionCallsByCode(){let e=!1;for(const t of this._functionDescr){const{name:i,type:n,parameters:s,body:r}=t;let o=0;for(;o{const t=[];let i=0,n=0;for(;i0?this._sourceCode.substring(0,a):"";const g=h+1{const a=s[0];return nc(e.charAt(a-1))||nc(e.charAt(a+r))?t[n]:o}))}return e}}oc._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;var ac=i(3156);class lc{get isAsync(){return this.isParallelCompiled}get isReady(){if(this.compilationError){const e=this.compilationError.message;throw new Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}return this.isCompiled}_getVertexShaderCode(){return null}_getFragmentShaderCode(){return null}_handlesSpectorRebuildCallback(e){throw new Error("Not implemented")}constructor(e){this.isParallelCompiled=!0,this.isCompiled=!1,this._valueCache={},this._engine=e}_fillEffectInformation(e,t,i,n,s,r,o,a){const l=this._engine;if(l.supportsUniformBuffers)for(const c in t)e.bindUniformBlock(c,t[c]);let h;for(this._engine.getUniforms(this,i).forEach(((e,t)=>{n[i[t]]=e})),this._uniforms=n,h=0;h{r[e]=t})),a.push(...l.getAttributes(this,o))}dispose(){this._uniforms={}}_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)return n=[t,i],this._valueCache[e]=n,!0;let s=!1;return n[0]!==t&&(n[0]=t,s=!0),n[1]!==i&&(n[1]=i,s=!0),s}_cacheFloat3(e,t,i,n){let s=this._valueCache[e];if(!s)return s=[t,i,n],this._valueCache[e]=s,!0;let r=!1;return s[0]!==t&&(s[0]=t,r=!0),s[1]!==i&&(s[1]=i,r=!0),s[2]!==n&&(s[2]=n,r=!0),r}_cacheFloat4(e,t,i,n,s){let r=this._valueCache[e];if(!r)return r=[t,i,n,s],this._valueCache[e]=r,!0;let o=!1;return r[0]!==t&&(r[0]=t,o=!0),r[1]!==i&&(r[1]=i,o=!0),r[2]!==n&&(r[2]=n,o=!0),r[3]!==s&&(r[3]=s,o=!0),o}setInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,n){this._cacheFloat3(e,t,i,n)&&(this._engine.setInt3(this._uniforms[e],t,i,n)||(this._valueCache[e]=null))}setInt4(e,t,i,n,s){this._cacheFloat4(e,t,i,n,s)&&(this._engine.setInt4(this._uniforms[e],t,i,n,s)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this._engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this._engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this._engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this._engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];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,s){this._cacheFloat4(e,t,i,n,s)&&(this._engine.setUInt4(this._uniforms[e],t,i,n,s)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this._engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this._engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this._engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this._engine.setUIntArray4(this._uniforms[e],t)}setFloatArray(e,t){this._valueCache[e]=null,this._engine.setFloatArray(this._uniforms[e],t)}setFloatArray2(e,t){this._valueCache[e]=null,this._engine.setFloatArray2(this._uniforms[e],t)}setFloatArray3(e,t){this._valueCache[e]=null,this._engine.setFloatArray3(this._uniforms[e],t)}setFloatArray4(e,t){this._valueCache[e]=null,this._engine.setFloatArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this._engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this._engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this._engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this._engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this._engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this._engine.setMatrices(this._uniforms[e],t.toArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this._engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this._engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setBool(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setInt(this._uniforms[e],t?1:0)&&(this._valueCache[e]=t?1:0)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this._engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this._engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,n){this._cacheFloat3(e,t,i,n)&&(this._engine.setFloat3(this._uniforms[e],t,i,n)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,n,s){this._cacheFloat4(e,t,i,n,s)&&(this._engine.setFloat4(this._uniforms[e],t,i,n,s)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this._engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}}class hc extends jt{get _framebuffer(){return this.__framebuffer}set _framebuffer(e){this.__framebuffer&&this._engine._releaseFramebufferObjects(this.__framebuffer),this.__framebuffer=e}get _framebufferDepthStencil(){return this.__framebufferDepthStencil}set _framebufferDepthStencil(e){this.__framebufferDepthStencil&&this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil),this.__framebufferDepthStencil=e}constructor(e,t,i,n){super(e,t,i,n),this.__framebuffer=null,this.__framebufferDepthStencil=null,this._engine=n}dispose(e=!1){this._framebuffer=null,this._framebufferDepthStencil=null,super.dispose(e)}}class cc{get underlyingResource(){return this._nativeTexture}constructor(e,t){this._engine=t,this.set(e)}setUsage(){}set(e){this._nativeTexture=e}reset(){this._nativeTexture=null}release(){this._nativeTexture&&this._engine.deleteTexture(this._nativeTexture),this.reset()}}const dc=new r.y$;if("undefined"!=typeof self&&!Object.prototype.hasOwnProperty.call(self,"_native")){let e;Object.defineProperty(self,"_native",{get:()=>e,set:t=>{e=t,e&&dc.notifyObservers(e)}})}class uc extends Ki.h{}class pc{constructor(e){this._engine=e,this._pending=new Array,this._isCommandBufferScopeActive=!1,this._commandStream=fc._createNativeDataStream(),this._engine.setCommandDataStream(this._commandStream)}beginCommandScope(){if(this._isCommandBufferScopeActive)throw new Error("Command scope already active.");this._isCommandBufferScopeActive=!0}endCommandScope(){if(!this._isCommandBufferScopeActive)throw new Error("Command scope is not active.");this._isCommandBufferScopeActive=!1,this._submit()}startEncodingCommand(e){this._commandStream.writeNativeData(e)}encodeCommandArgAsUInt32(e){this._commandStream.writeUint32(e)}encodeCommandArgAsUInt32s(e){this._commandStream.writeUint32Array(e)}encodeCommandArgAsInt32(e){this._commandStream.writeInt32(e)}encodeCommandArgAsInt32s(e){this._commandStream.writeInt32Array(e)}encodeCommandArgAsFloat32(e){this._commandStream.writeFloat32(e)}encodeCommandArgAsFloat32s(e){this._commandStream.writeFloat32Array(e)}encodeCommandArgAsNativeData(e){this._commandStream.writeNativeData(e),this._pending.push(e)}finishEncodingCommand(){this._isCommandBufferScopeActive||this._submit()}_submit(){this._engine.submitCommands(),this._pending.length=0}}class fc extends fe.D{setHardwareScalingLevel(e){super.setHardwareScalingLevel(e),this._engine.setHardwareScalingLevel(e)}constructor(e={}){if(super(null,!1,void 0,e.adaptToDeviceRatio),this._engine=new _native.Engine,this._camera=_native.Camera?new _native.Camera:null,this._commandBufferEncoder=new pc(this._engine),this._boundBuffersVertexArray=null,this._currentDepthTest=_native.Engine.DEPTH_TEST_LEQUAL,this._stencilTest=!1,this._stencilMask=255,this._stencilFunc=519,this._stencilFuncRef=0,this._stencilFuncMask=255,this._stencilOpStencilFail=7680,this._stencilOpDepthFail=7680,this._stencilOpStencilDepthPass=7681,this._zOffset=0,this._zOffsetUnits=0,this._depthWrite=!0,_native.Engine.PROTOCOL_VERSION!==fc.PROTOCOL_VERSION)throw new Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${fc.PROTOCOL_VERSION} (JS)`);this._webGLVersion=2,this.disableUniformBuffers=!0,this._shaderPlatformName="NATIVE",this._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_SIZE,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!0,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,textureFloat:!0,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloat:!1,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!1,textureLOD:!0,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!0,instancedArrays:!0,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,blendMinMax:!1,maxMSAASamples:1,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!1,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!1,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!1,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,_collectUbosUpdatedInFrame:!1},se.w1.Log("Babylon Native (v"+fe.D.Version+") launched"),se.w1.LoadScript=function(e,t,i,n){se.w1.LoadFile(e,(e=>{Function(e).apply(null),t&&t()}),void 0,void 0,!1,((e,t)=>{i&&i("LoadScript Error",t)}))},"undefined"==typeof URL&&(window.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(window.Blob=function(e){return e}),Array.prototype.flat||Object.defineProperty(Array.prototype,"flat",{configurable:!0,value:function e(){const t=isNaN(arguments[0])?1:Number(arguments[0]);return t?Array.prototype.reduce.call(this,(function(i,n){return Array.isArray(n)?i.push.apply(i,e.call(n,t-1)):i.push(n),i}),[]):Array.prototype.slice.call(this)},writable:!0});const t=window&&window.devicePixelRatio||1;this._hardwareScalingLevel=e.adaptToDeviceRatio?1/t:1,this._engine.setHardwareScalingLevel(this._hardwareScalingLevel),this._lastDevicePixelRatio=t,this.resize();const i=this.getDepthFunction();i&&this.setDepthFunction(i),this._shaderProcessor=new ac.C,this.onNewSceneAddedObservable.add((e=>{const t=e.render;e.render=(...i)=>{this._commandBufferEncoder.beginCommandScope(),t.apply(e,i),this._commandBufferEncoder.endCommandScope()}}))}dispose(){super.dispose(),this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._engine.dispose()}static _createNativeDataStream(){return new Ah}_queueNewFrame(e,t){return t.requestAnimationFrame&&t!==window?t.requestAnimationFrame(e):this._engine.requestAnimationFrame(e),0}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._currentFramebuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer),this._commandBufferEncoder.finishEncodingCommand()),e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()),this._currentFramebuffer=e)}getHostDocument(){return null}clear(e,t,i,n=!1){if(this.useReverseDepthBuffer)throw new Error("reverse depth buffer is not currently implemented");this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR),this._commandBufferEncoder.encodeCommandArgAsUInt32(t&&e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.r:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.g:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.b:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.a:1),this._commandBufferEncoder.encodeCommandArgAsUInt32(i?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(1),this._commandBufferEncoder.encodeCommandArgAsUInt32(n?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(0),this._commandBufferEncoder.finishEncodingCommand()}createIndexBuffer(e,t){const i=this._normalizeIndexData(e),n=new uc;return n.references=1,n.is32Bits=4===i.BYTES_PER_ELEMENT,i.byteLength&&(n.nativeIndexBuffer=this._engine.createIndexBuffer(i.buffer,i.byteOffset,i.byteLength,n.is32Bits,null!=t&&t)),n}createVertexBuffer(e,t){const i=ArrayBuffer.isView(e)?e:new Float32Array(e),n=new uc;return n.references=1,i.byteLength&&(n.nativeVertexBuffer=this._engine.createVertexBuffer(i.buffer,i.byteOffset,i.byteLength,null!=t&&t)),n}_recordVertexArrayObject(e,t,i,n,s){i&&this._engine.recordIndexBuffer(e,i.nativeIndexBuffer);const r=n.getAttributesNames();for(let o=0;o=0){const n=r[o];let a=null;if(s&&(a=s[n]),a||(a=t[n]),a){const t=a.getBuffer();t&&t.nativeVertexBuffer&&this._engine.recordVertexBuffer(e,t.nativeVertexBuffer,i,a.byteOffset,a.byteStride,a.getSize(),this._getNativeAttribType(a.type),a.normalized,a.getInstanceDivisor())}}}}bindBuffers(e,t,i){this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._boundBuffersVertexArray=this._engine.createVertexArray(),this._recordVertexArrayObject(this._boundBuffersVertexArray,e,t,i),this.bindVertexArrayObject(this._boundBuffersVertexArray)}recordVertexArrayObject(e,t,i,n){const s=this._engine.createVertexArray();return this._recordVertexArrayObject(s,e,t,i,n),s}_deleteVertexArray(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}bindVertexArrayObject(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}releaseVertexArrayObject(e){this._deleteVertexArray(e)}getAttributes(e,t){const i=e;return this._engine.getAttributes(i.nativeProgram,t)}drawElementsType(e,t,i,n){this._drawCalls.addCount(1,!1),this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand()}drawArraysType(e,t,i,n){this._drawCalls.addCount(1,!1),this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAW),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand()}createPipelineContext(){return new lc(this)}createMaterialContext(){}createDrawContext(){}_preparePipelineContext(e,t,i,n,s,r,o,a){const l=e;l.nativeProgram=n?this.createRawShaderProgram():this.createShaderProgram(e,t,i,a)}isAsync(e){return!(!e.isAsync||!this._engine.createProgramAsync)}_executeWhenRenderingStateIsCompiled(e,t){const i=e;if(!this.isAsync(e))return void t();const n=i.onCompiled;i.onCompiled=n?()=>{n(),t()}:t}createRawShaderProgram(){throw new Error("Not Supported")}createShaderProgram(e,t,i,n){const s=e;if(s.nativeProgram)throw new Error("Tried to create a second program in the same NativePipelineContext");this.onBeforeShaderCompilationObservable.notifyObservers(this);const r=new oc(t);r.processCode(),t=r.code;const o=new oc(i);o.processCode(),i=o.code,t=Ue.B._ConcatenateShader(t,n),i=Ue.B._ConcatenateShader(i,n);const a=()=>{var e;s.isCompiled=!0,null===(e=s.onCompiled)||void 0===e||e.call(s),this.onAfterShaderCompilationObservable.notifyObservers(this)};if(this.isAsync(e))return this._engine.createProgramAsync(t,i,a,(e=>{s.compilationError=e}));try{const e=s.nativeProgram=this._engine.createProgram(t,i);return a(),e}catch(l){const e=null==l?void 0:l.message;throw new Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}}inlineShaderCode(e){const t=new oc(e);return t.debug=!1,t.processCode(),t.code}_setProgram(e){this._currentProgram!==e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand(),this._currentProgram=e)}_deletePipelineContext(e){const t=e;t&&t.nativeProgram&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(t.nativeProgram),this._commandBufferEncoder.finishEncodingCommand())}getUniforms(e,t){const i=e;return this._engine.getUniforms(i.nativeProgram,t)}bindUniformBlock(e,t,i){throw new Error("Not Implemented")}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.nativeProgram);const i=e.getSamplers();for(let n=0;n{}}}setZOffset(e){e!==this._zOffset&&(this._zOffset=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSET),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffset(){return this._zOffset}setZOffsetUnits(e){e!==this._zOffsetUnits&&(this._zOffsetUnits=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSETUNITS),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffsetUnits(){return this._zOffsetUnits}setDepthBuffer(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(e?this._currentDepthTest:_native.Engine.DEPTH_TEST_ALWAYS),this._commandBufferEncoder.finishEncodingCommand()}getDepthWrite(){return this._depthWrite}getDepthFunction(){switch(this._currentDepthTest){case _native.Engine.DEPTH_TEST_NEVER:return 512;case _native.Engine.DEPTH_TEST_ALWAYS:return 519;case _native.Engine.DEPTH_TEST_GREATER:return 516;case _native.Engine.DEPTH_TEST_GEQUAL:return 518;case _native.Engine.DEPTH_TEST_NOTEQUAL:return 517;case _native.Engine.DEPTH_TEST_EQUAL:return 514;case _native.Engine.DEPTH_TEST_LESS:return 513;case _native.Engine.DEPTH_TEST_LEQUAL:return 515}return null}setDepthFunction(e){let t=0;switch(e){case 512:t=_native.Engine.DEPTH_TEST_NEVER;break;case 519:t=_native.Engine.DEPTH_TEST_ALWAYS;break;case 516:t=_native.Engine.DEPTH_TEST_GREATER;break;case 518:t=_native.Engine.DEPTH_TEST_GEQUAL;break;case 517:t=_native.Engine.DEPTH_TEST_NOTEQUAL;break;case 514:t=_native.Engine.DEPTH_TEST_EQUAL;break;case 513:t=_native.Engine.DEPTH_TEST_LESS;break;case 515:t=_native.Engine.DEPTH_TEST_LEQUAL}this._currentDepthTest=t,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(this._currentDepthTest),this._commandBufferEncoder.finishEncodingCommand()}setDepthWrite(e){this._depthWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}setColorWrite(e){this._colorWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETCOLORWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}getColorWrite(){return this._colorWrite}applyStencil(){this._setStencil(this._stencilMask,this._getStencilOpFail(this._stencilOpStencilFail),this._getStencilDepthFail(this._stencilOpDepthFail),this._getStencilDepthPass(this._stencilOpStencilDepthPass),this._getStencilFunc(this._stencilFunc),this._stencilFuncRef)}_setStencil(e,t,i,n,s,r){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(n),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.finishEncodingCommand()}setStencilBuffer(e){this._stencilTest=e,e?this.applyStencil():this._setStencil(255,_native.Engine.STENCIL_OP_FAIL_S_KEEP,_native.Engine.STENCIL_OP_FAIL_Z_KEEP,_native.Engine.STENCIL_OP_PASS_Z_KEEP,_native.Engine.STENCIL_TEST_ALWAYS,0)}getStencilBuffer(){return this._stencilTest}getStencilOperationPass(){return this._stencilOpStencilDepthPass}setStencilOperationPass(e){this._stencilOpStencilDepthPass=e,this.applyStencil()}setStencilMask(e){this._stencilMask=e,this.applyStencil()}setStencilFunction(e){this._stencilFunc=e,this.applyStencil()}setStencilFunctionReference(e){this._stencilFuncRef=e,this.applyStencil()}setStencilFunctionMask(e){this._stencilFuncMask=e}setStencilOperationFail(e){this._stencilOpStencilFail=e,this.applyStencil()}setStencilOperationDepthFail(e){this._stencilOpDepthFail=e,this.applyStencil()}getStencilMask(){return this._stencilMask}getStencilFunction(){return this._stencilFunc}getStencilFunctionReference(){return this._stencilFuncRef}getStencilFunctionMask(){return this._stencilFuncMask}getStencilOperationFail(){return this._stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilOpDepthFail}setAlphaConstants(e,t,i,n){throw new Error("Setting alpha blend constant color not yet implemented.")}setAlphaMode(e,t=!1){if(this._alphaMode===e)return;const i=this._getNativeAlphaMode(e);this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t||this.setDepthWrite(0===e),this._alphaMode=e}getAlphaMode(){return this._alphaMode}setInt(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setArray(e,t){return!!e&&this.setFloatArray(e,new Float32Array(t))}setArray2(e,t){return!!e&&this.setFloatArray2(e,new Float32Array(t))}setArray3(e,t){return!!e&&this.setFloatArray3(e,new Float32Array(t))}setArray4(e,t){return!!e&&this.setFloatArray4(e,new Float32Array(t))}setMatrices(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix3x3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix2x2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat2(e,t,i){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat3(e,t,i,n){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(n),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat4(e,t,i,n,s){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(n),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.finishEncodingCommand(),!0)}setColor3(e,t){return!!e&&(this.setFloat3(e,t.r,t.g,t.b),!0)}setColor4(e,t,i){return!!e&&(this.setFloat4(e,t.r,t.g,t.b,i),!0)}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}_createTexture(){return this._engine.createTexture()}_deleteTexture(e){e&&this._engine.deleteTexture(e)}updateDynamicTexture(e,t,i,n=!1,s){if(void 0===n&&(n=!1),e&&e._hardwareTexture){const i=t.getCanvasTexture(),n=e._hardwareTexture.underlyingResource;this._engine.copyTexture(n,i),e.isReady=!0}}createDynamicTexture(e,t,i,n){return e=Math.max(e,1),t=Math.max(t,1),this.createRawTexture(new Uint8Array(e*t*4),e,t,5,!1,!1,n)}createVideoElement(e){return this._camera?this._camera.createVideo(e):null}updateVideoTexture(e,t,i){if(e&&e._hardwareTexture&&this._camera){const n=e._hardwareTexture.underlyingResource;this._camera.updateVideoTexture(n,t,i)}}createRawTexture(e,t,i,n,s,r,o,a=null,l=0,h=0,c=!1){const d=new Be.l(this,Be.S.Raw);if(d.format=n,d.generateMipMaps=s,d.samplingMode=o,d.invertY=r,d.baseWidth=t,d.baseHeight=i,d.width=d.baseWidth,d.height=d.baseHeight,d._compression=a,d.type=l,d._useSRGBBuffer=this._getUseSRGBBuffer(c,!s),this.updateRawTexture(d,e,n,r,a,l,d._useSRGBBuffer),d._hardwareTexture){const e=d._hardwareTexture.underlyingResource,t=this._getNativeSamplingMode(o);this._setTextureSampling(e,t)}return this._internalTexturesCache.push(d),d}createRawTexture2DArray(e,t,i,n,s,r,o,a,l=null,h=0){const c=new Be.l(this,Be.S.Raw2DArray);if(c.baseWidth=t,c.baseHeight=i,c.baseDepth=n,c.width=t,c.height=i,c.depth=n,c.format=s,c.type=h,c.generateMipMaps=r,c.samplingMode=a,c.is2DArray=!0,c._hardwareTexture){const l=c._hardwareTexture.underlyingResource;this._engine.loadRawTexture2DArray(l,e,t,i,n,this._getNativeTextureFormat(s,h),r,o);const d=this._getNativeSamplingMode(a);this._setTextureSampling(l,d)}return c.isReady=!0,this._internalTexturesCache.push(c),c}updateRawTexture(e,t,i,n,s=null,r=0,o=!1){if(e){if(t&&e._hardwareTexture){const n=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(n,t,e.width,e.height,this._getNativeTextureFormat(i,r),e.generateMipMaps,e.invertY)}e.isReady=!0}}createTexture(e,t,i,n,s=3,r=null,o=null,a=null,l=null,h=null,c=null,d,u,f,_=!1){const g="data:"===(e=e||"").substr(0,5),v=g&&-1!==e.indexOf(";base64,"),T=l||new Be.l(this,Be.S.Url),S=e;!this._transformTextureUrl||v||l||a||(e=this._transformTextureUrl(e));const E=e.lastIndexOf("."),x=c||(E>-1?e.substring(E).toLowerCase():"");let b=null;for(const p of fe.D._TextureLoaders)if(p.canLoad(x)){b=p;break}n&&n.addPendingData(T),T.url=e,T.generateMipMaps=!t,T.samplingMode=s,T.invertY=i,T._useSRGBBuffer=this._getUseSRGBBuffer(_,t),this.doNotHandleContextLost||(T._buffer=a);let C=null;r&&!l&&(C=T.onLoadedObservable.add(r)),l||this._internalTexturesCache.push(T);const y=(i,l)=>{n&&n.removePendingData(T),e===S?(C&&T.onLoadedObservable.remove(C),m.l.UseFallbackTexture&&this.createTexture(m.l.FallbackTexture,t,T.invertY,n,s,null,o,a,T),o&&o((i||"Unknown error")+(m.l.UseFallbackTexture?" - Fallback texture was used":""),l)):(p.Y.Warn(`Failed to load ${e}, falling back to ${S}`),this.createTexture(S,t,T.invertY,n,s,r,o,a,T,h,c,d,u))};if(b)throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");{const r=e=>{if(!T._hardwareTexture)return void(n&&n.removePendingData(T));const r=T._hardwareTexture.underlyingResource;this._engine.loadTexture(r,e,!t,i,_,(()=>{T.baseWidth=this._engine.getTextureWidth(r),T.baseHeight=this._engine.getTextureHeight(r),T.width=T.baseWidth,T.height=T.baseHeight,T.isReady=!0;const e=this._getNativeSamplingMode(s);this._setTextureSampling(r,e),n&&n.removePendingData(T),T.onLoadedObservable.notifyObservers(T),T.onLoadedObservable.clear()}),(()=>{throw new Error("Could not load a native texture.")}))};if(g&&a)if(a instanceof ArrayBuffer)r(new Uint8Array(a));else if(ArrayBuffer.isView(a))r(a);else{if("string"!=typeof a)throw new Error("Unsupported buffer type");r(new Uint8Array(se.w1.DecodeBase64(a)))}else v?r(new Uint8Array(se.w1.DecodeBase64(e))):this._loadFile(e,(e=>r(new Uint8Array(e))),void 0,void 0,!0,((e,t)=>{y("Unable to load "+(e&&e.responseURL,t))}))}return T}wrapNativeTexture(e,t=!1,i=3){const n=new cc(e,this._engine),s=new Be.l(this,Be.S.Unknown,!0);return s._hardwareTexture=n,s.isReady=!0,s.useMipMaps=t,this.updateTextureSamplingMode(i,s),s}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.")}_createDepthStencilTexture(e,t,i){const n=i,s=new Be.l(this,Be.S.DepthStencil),r=e.width||e,o=e.height||e,a=this._engine.createFrameBuffer(s._hardwareTexture.underlyingResource,r,o,!0,!0);return n._framebufferDepthStencil=a,s}_releaseFramebufferObjects(e){e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_createImageBitmapFromSource(e,t){const i=new Promise(((t,i)=>{const n=this.createCanvasImage();n.onload=()=>{try{const e=this._engine.createImageBitmap(n);t(e)}catch(lt){i(`Error loading image ${n.src} with exception: ${lt}`)}},n.onerror=e=>{i(`Error loading image ${n.src} with exception: ${e}`)},n.src=e}));return i}createImageBitmap(e,t){return new Promise(((t,i)=>{if(Array.isArray(e)){const i=e;if(i.length){const e=this._engine.createImageBitmap(i[0]);if(e)return void t(e)}}i("Unsupported data for createImageBitmap.")}))}resizeImageBitmap(e,t,i){return this._engine.resizeImageBitmap(e,t,i)}createCubeTexture(e,t,i,n,s=null,r=null,o,a=null,l=!1,h=0,c=0,d=null,u,p=!1){const f=d||new Be.l(this,Be.S.Cube);f.isCube=!0,f.url=e,f.generateMipMaps=!n,f._lodGenerationScale=h,f._lodGenerationOffset=c,this._doNotHandleContextLost||(f._extension=a,f._files=i);const _=e.lastIndexOf(".");if(".env"===(a||(_>-1?e.substring(_).toLowerCase():""))){const t=e=>{const t=Kh(e);f.width=t.width,f.height=t.width,ec(f,t);const i=t.specular;if(!i)throw new Error("Nothing else parsed so far");f._lodGenerationScale=i.lodGenerationScale;const n=$h(e,t);f.format=5,f.type=0,f.generateMipMaps=!0,f.getEngine().updateTextureSamplingMode(Le.TRILINEAR_SAMPLINGMODE,f),f._isRGBD=!0,f.invertY=!0,this._engine.loadCubeTextureWithMips(f._hardwareTexture.underlyingResource,n,!1,p,(()=>{f.isReady=!0,s&&s()}),(()=>{throw new Error("Could not load a native cube texture.")}))};if(i&&6===i.length)throw new Error("Multi-file loading not allowed on env files.");{const i=(e,t)=>{r&&e&&r(e.status+" "+e.statusText,t)};this._loadFile(e,(e=>t(new Uint8Array(e))),void 0,void 0,!0,i)}}else{if(!i||6!==i.length)throw new Error("Cannot load cubemap because 6 files were not defined");const e=[i[0],i[3],i[1],i[4],i[2],i[5]];Promise.all(e.map((e=>se.w1.LoadFileAsync(e).then((e=>new Uint8Array(e)))))).then((e=>new Promise(((t,i)=>{this._engine.loadCubeTexture(f._hardwareTexture.underlyingResource,e,!n,!0,p,t,i)})))).then((()=>{f.isReady=!0,s&&s()}),(e=>{r&&r(`Failed to load cubemap: ${e.message}`,e)}))}return this._internalTexturesCache.push(f),f}_createHardwareTexture(){return new cc(this._createTexture(),this._engine)}_createHardwareRenderTargetWrapper(e,t,i){const n=new hc(e,t,i,this);return this._renderTargetWrapperCache.push(n),n}_createInternalTexture(e,t,i=!0,n=Be.S.Unknown){var s;let r,o=!1,a=0,l=3,h=5,c=!1,d=1;void 0!==t&&"object"==typeof t?(o=!!t.generateMipMaps,a=void 0===t.type?0:t.type,l=void 0===t.samplingMode?3:t.samplingMode,h=void 0===t.format?5:t.format,c=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,d=null!==(s=t.samples)&&void 0!==s?s:1,r=t.label):o=!!t,c&&(c=this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU)),(1!==a||this._caps.textureFloatLinearFiltering)&&(2!==a||this._caps.textureHalfFloatLinearFiltering)||(l=1),1!==a||this._caps.textureFloat||(a=0,p.Y.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const u=new Be.l(this,n),f=e.width||e,_=e.height||e,m=e.layers||0;if(0!==m)throw new Error("Texture layers are not supported in Babylon Native");const g=u._hardwareTexture.underlyingResource,v=this._getNativeTextureFormat(h,a);return this._engine.initializeTexture(g,f,_,o,v,!0,c),this._setTextureSampling(g,this._getNativeSamplingMode(l)),u._useSRGBBuffer=c,u.baseWidth=f,u.baseHeight=_,u.width=f,u.height=_,u.depth=m,u.isReady=!0,u.samples=d,u.generateMipMaps=o,u.samplingMode=l,u.type=a,u.format=h,u.label=r,this._internalTexturesCache.push(u),u}createRenderTargetTexture(e,t){var i,n;const s=this._createHardwareRenderTargetWrapper(!1,!1,e);let r,o=!0,a=!1,l=!1,h=1;void 0!==t&&"object"==typeof t&&(o=null===(i=t.generateDepthBuffer)||void 0===i||i,a=!!t.generateStencilBuffer,l=!!t.noColorAttachment,r=t.colorAttachment,h=null!==(n=t.samples)&&void 0!==n?n:1);const c=r||(l?null:this._createInternalTexture(e,t,!0,Be.S.RenderTarget)),d=e.width||e,u=e.height||e,p=this._engine.createFrameBuffer(c?c._hardwareTexture.underlyingResource:null,d,u,a,o);return s._framebuffer=p,s._generateDepthBuffer=o,s._generateStencilBuffer=a,s.setTextures(c),this.updateRenderTargetTextureSampleCount(s,h),s}updateRenderTargetTextureSampleCount(e,t){return 1}updateTextureSamplingMode(e,t){if(t._hardwareTexture){const i=this._getNativeSamplingMode(e);this._setTextureSampling(t._hardwareTexture.underlyingResource,i)}t.samplingMode=e}bindFramebuffer(e,t,i,n,s){const r=e;if(this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,t)throw new Error("Cuboid frame buffers are not yet supported in NativeEngine.");if(i||n)throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");r._framebufferDepthStencil?this._bindUnboundFramebuffer(r._framebufferDepthStencil):this._bindUnboundFramebuffer(r._framebuffer)}unBindFramebuffer(e,t=!1,i){this._currentRenderTarget=null,i&&i(),this._bindUnboundFramebuffer(null)}createDynamicVertexBuffer(e){return this.createVertexBuffer(e,!0)}updateDynamicIndexBuffer(e,t,i=0){const n=e,s=this._normalizeIndexData(t);n.is32Bits=4===s.BYTES_PER_ELEMENT,this._engine.updateDynamicIndexBuffer(n.nativeIndexBuffer,s.buffer,s.byteOffset,s.byteLength,i)}updateDynamicVertexBuffer(e,t,i,n){const s=e,r=ArrayBuffer.isView(t)?t:new Float32Array(t);this._engine.updateDynamicVertexBuffer(s.nativeVertexBuffer,r.buffer,r.byteOffset+(null!=i?i:0),null!=n?n:r.byteLength)}_setTexture(e,t,i=!1,n=!1){const s=this._boundUniforms[e];if(!s)return!1;if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._boundTexturesCache[e]=null),!1;if(t.video)this._activeChannel=e,t.update();else if(4===t.delayLoadState)return t.delayLoad(),!1;let r;return r=n?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,this._activeChannel=e,!(!r||!r._hardwareTexture)&&(this._setTextureWrapMode(r._hardwareTexture.underlyingResource,this._getAddressMode(t.wrapU),this._getAddressMode(t.wrapV),this._getAddressMode(t.wrapR)),this._updateAnisotropicLevel(t),this._setTextureCore(s,r._hardwareTexture.underlyingResource),!0)}_setTextureSampling(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.finishEncodingCommand()}_setTextureWrapMode(e,t,i,n){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(n),this._commandBufferEncoder.finishEncodingCommand()}_setTextureCore(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsNativeData(t),this._commandBufferEncoder.finishEncodingCommand()}_updateAnisotropicLevel(e){const t=e.getInternalTexture(),i=e.anisotropicFilteringLevel;t&&t._hardwareTexture&&t._cachedAnisotropicFilteringLevel!==i&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL),this._commandBufferEncoder.encodeCommandArgAsNativeData(t._hardwareTexture.underlyingResource),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t._cachedAnisotropicFilteringLevel=i)}_getAddressMode(e){switch(e){case 1:return _native.Engine.ADDRESS_MODE_WRAP;case 0:return _native.Engine.ADDRESS_MODE_CLAMP;case 2:return _native.Engine.ADDRESS_MODE_MIRROR;default:throw new Error("Unexpected wrap mode: "+e+".")}}_bindTexture(e,t){const i=this._boundUniforms[e];if(i&&t&&t._hardwareTexture){const e=t._hardwareTexture.underlyingResource;this._setTextureCore(i,e)}}_deleteBuffer(e){e.nativeIndexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeIndexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeIndexBuffer),e.nativeVertexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeVertexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeVertexBuffer)}createCanvas(e,t){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");const i=new _native.Canvas;return i.width=e,i.height=t,i}createCanvasImage(){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");return new _native.Image}updateTextureData(e,t,i,n,s,r,o=0,a=0,l=!1){throw new Error("updateTextureData not implemented.")}_uploadCompressedDataToTextureDirectly(e,t,i,n,s,r=0,o=0){throw new Error("_uploadCompressedDataToTextureDirectly not implemented.")}_uploadDataToTextureDirectly(e,t,i=0,n=0){throw new Error("_uploadDataToTextureDirectly not implemented.")}_uploadArrayBufferViewToTexture(e,t,i=0,n=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}_uploadImageToTexture(e,t,i=0,n=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}_getNativeSamplingMode(e){switch(e){case 1:return _native.Engine.TEXTURE_NEAREST_NEAREST;case 2:return _native.Engine.TEXTURE_LINEAR_LINEAR;case 3:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR;case 4:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;case 5:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;case 6:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;case 7:return _native.Engine.TEXTURE_NEAREST_LINEAR;case 8:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR;case 9:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;case 10:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;case 11:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST;case 12:return _native.Engine.TEXTURE_LINEAR_NEAREST;default:throw new Error(`Unsupported sampling mode: ${e}.`)}}_getStencilFunc(e){switch(e){case 513:return _native.Engine.STENCIL_TEST_LESS;case 515:return _native.Engine.STENCIL_TEST_LEQUAL;case 514:return _native.Engine.STENCIL_TEST_EQUAL;case 518:return _native.Engine.STENCIL_TEST_GEQUAL;case 516:return _native.Engine.STENCIL_TEST_GREATER;case 517:return _native.Engine.STENCIL_TEST_NOTEQUAL;case 512:return _native.Engine.STENCIL_TEST_NEVER;case 519:return _native.Engine.STENCIL_TEST_ALWAYS;default:throw new Error(`Unsupported stencil func mode: ${e}.`)}}_getStencilOpFail(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_FAIL_S_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_S_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_S_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_S_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_S_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_S_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_S_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_S_DECRSAT;default:throw new Error(`Unsupported stencil OpFail mode: ${e}.`)}}_getStencilDepthFail(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_FAIL_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_Z_DECRSAT;default:throw new Error(`Unsupported stencil depthFail mode: ${e}.`)}}_getStencilDepthPass(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_PASS_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_PASS_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_PASS_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_PASS_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_PASS_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_PASS_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_PASS_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_PASS_Z_DECRSAT;default:throw new Error(`Unsupported stencil opPass mode: ${e}.`)}}_getNativeTextureFormat(e,t){if(4==e&&0==t)return _native.Engine.TEXTURE_FORMAT_RGB8;if(5==e&&0==t)return _native.Engine.TEXTURE_FORMAT_RGBA8;if(5==e&&2==t)return _native.Engine.TEXTURE_FORMAT_RGBA16F;if(5==e&&1==t)return _native.Engine.TEXTURE_FORMAT_RGBA32F;throw new lt.LH(`Unsupported texture format or type: format ${e}, type ${t}.`,lt.SM.UnsupportedTextureError)}_getNativeAlphaMode(e){switch(e){case 0:return _native.Engine.ALPHA_DISABLE;case 1:return _native.Engine.ALPHA_ADD;case 2:return _native.Engine.ALPHA_COMBINE;case 3:return _native.Engine.ALPHA_SUBTRACT;case 4:return _native.Engine.ALPHA_MULTIPLY;case 5:return _native.Engine.ALPHA_MAXIMIZED;case 6:return _native.Engine.ALPHA_ONEONE;case 7:return _native.Engine.ALPHA_PREMULTIPLIED;case 8:return _native.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;case 9:return _native.Engine.ALPHA_INTERPOLATE;case 10:return _native.Engine.ALPHA_SCREENMODE;default:throw new Error(`Unsupported alpha mode: ${e}.`)}}_getNativeAttribType(e){switch(e){case ne.o.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case ne.o.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case ne.o.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case ne.o.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case ne.o.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw new Error(`Unsupported attribute type: ${e}.`)}}getFontOffset(e){return{ascent:0,height:0,descent:0}}_readTexturePixels(e,t,i,n,s,r,o,a,l,h){var c,d,u,p;if(void 0!==n&&-1!==n)throw new Error(`Reading cubemap faces is not supported, but faceIndex is ${n}.`);return this._engine.readTexture(null===(c=e._hardwareTexture)||void 0===c?void 0:c.underlyingResource,null!=s?s:0,null!=l?l:0,null!=h?h:0,t,i,null!==(d=null==r?void 0:r.buffer)&&void 0!==d?d:null,null!==(u=null==r?void 0:r.byteOffset)&&void 0!==u?u:0,null!==(p=null==r?void 0:r.byteLength)&&void 0!==p?p:0).then((e=>(r||(r=new Uint8Array(e)),r)))}}fc.PROTOCOL_VERSION=8,fc._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new _c:new Ah};class _c extends Ah{constructor(){super()}writeUint32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32),super.writeUint32(e)}writeInt32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32),super.writeInt32(e)}writeFloat32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32),super.writeFloat32(e)}writeUint32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32_ARRAY),super.writeUint32Array(e)}writeInt32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32_ARRAY),super.writeInt32Array(e)}writeFloat32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32_ARRAY),super.writeFloat32Array(e)}writeNativeData(e){super.writeUint32(_native.NativeDataStream.VALIDATION_NATIVE_DATA),super.writeNativeData(e)}writeBoolean(e){super.writeUint32(_native.NativeDataStream.VALIDATION_BOOLEAN),super.writeBoolean(e)}}var mc,gc,vc,Tc,Sc,Ec,xc,bc,Cc,yc,Ac,Rc,Pc,Ic,Mc,Oc,Dc,Nc,Fc,wc,Lc,Bc,Uc,Vc,kc,Gc,zc,Wc,Hc,Xc,Yc,jc,Kc,qc,$c,Qc,Zc,Jc,ed,td;!function(e){e.LowPower="low-power",e.HighPerformance="high-performance"}(mc||(mc={})),function(e){e.DepthClipControl="depth-clip-control",e.Depth32FloatStencil8="depth32float-stencil8",e.TextureCompressionBC="texture-compression-bc",e.TextureCompressionETC2="texture-compression-etc2",e.TextureCompressionASTC="texture-compression-astc",e.TimestampQuery="timestamp-query",e.IndirectFirstInstance="indirect-first-instance",e.ShaderF16="shader-f16",e.RG11B10UFloatRenderable="rg11b10ufloat-renderable",e.BGRA8UnormStorage="bgra8unorm-storage",e.Float32Filterable="float32-filterable"}(gc||(gc={})),function(e){e.Unmapped="unmapped",e.Pending="pending",e.Mapped="mapped"}(vc||(vc={})),function(e){e[e.MapRead=1]="MapRead",e[e.MapWrite=2]="MapWrite",e[e.CopySrc=4]="CopySrc",e[e.CopyDst=8]="CopyDst",e[e.Index=16]="Index",e[e.Vertex=32]="Vertex",e[e.Uniform=64]="Uniform",e[e.Storage=128]="Storage",e[e.Indirect=256]="Indirect",e[e.QueryResolve=512]="QueryResolve"}(Tc||(Tc={})),function(e){e[e.Read=1]="Read",e[e.Write=2]="Write"}(Sc||(Sc={})),function(e){e.E1d="1d",e.E2d="2d",e.E3d="3d"}(Ec||(Ec={})),function(e){e[e.CopySrc=1]="CopySrc",e[e.CopyDst=2]="CopyDst",e[e.TextureBinding=4]="TextureBinding",e[e.StorageBinding=8]="StorageBinding",e[e.RenderAttachment=16]="RenderAttachment"}(xc||(xc={})),function(e){e.E1d="1d",e.E2d="2d",e.E2dArray="2d-array",e.Cube="cube",e.CubeArray="cube-array",e.E3d="3d"}(bc||(bc={})),function(e){e.All="all",e.StencilOnly="stencil-only",e.DepthOnly="depth-only"}(Cc||(Cc={})),function(e){e.R8Unorm="r8unorm",e.R8Snorm="r8snorm",e.R8Uint="r8uint",e.R8Sint="r8sint",e.R16Uint="r16uint",e.R16Sint="r16sint",e.R16Float="r16float",e.RG8Unorm="rg8unorm",e.RG8Snorm="rg8snorm",e.RG8Uint="rg8uint",e.RG8Sint="rg8sint",e.R32Uint="r32uint",e.R32Sint="r32sint",e.R32Float="r32float",e.RG16Uint="rg16uint",e.RG16Sint="rg16sint",e.RG16Float="rg16float",e.RGBA8Unorm="rgba8unorm",e.RGBA8UnormSRGB="rgba8unorm-srgb",e.RGBA8Snorm="rgba8snorm",e.RGBA8Uint="rgba8uint",e.RGBA8Sint="rgba8sint",e.BGRA8Unorm="bgra8unorm",e.BGRA8UnormSRGB="bgra8unorm-srgb",e.RGB9E5UFloat="rgb9e5ufloat",e.RGB10A2Unorm="rgb10a2unorm",e.RG11B10UFloat="rg11b10ufloat",e.RG32Uint="rg32uint",e.RG32Sint="rg32sint",e.RG32Float="rg32float",e.RGBA16Uint="rgba16uint",e.RGBA16Sint="rgba16sint",e.RGBA16Float="rgba16float",e.RGBA32Uint="rgba32uint",e.RGBA32Sint="rgba32sint",e.RGBA32Float="rgba32float",e.Stencil8="stencil8",e.Depth16Unorm="depth16unorm",e.Depth24Plus="depth24plus",e.Depth24PlusStencil8="depth24plus-stencil8",e.Depth32Float="depth32float",e.BC1RGBAUnorm="bc1-rgba-unorm",e.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",e.BC2RGBAUnorm="bc2-rgba-unorm",e.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",e.BC3RGBAUnorm="bc3-rgba-unorm",e.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",e.BC4RUnorm="bc4-r-unorm",e.BC4RSnorm="bc4-r-snorm",e.BC5RGUnorm="bc5-rg-unorm",e.BC5RGSnorm="bc5-rg-snorm",e.BC6HRGBUFloat="bc6h-rgb-ufloat",e.BC6HRGBFloat="bc6h-rgb-float",e.BC7RGBAUnorm="bc7-rgba-unorm",e.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",e.ETC2RGB8Unorm="etc2-rgb8unorm",e.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",e.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",e.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",e.ETC2RGBA8Unorm="etc2-rgba8unorm",e.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",e.EACR11Unorm="eac-r11unorm",e.EACR11Snorm="eac-r11snorm",e.EACRG11Unorm="eac-rg11unorm",e.EACRG11Snorm="eac-rg11snorm",e.ASTC4x4Unorm="astc-4x4-unorm",e.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",e.ASTC5x4Unorm="astc-5x4-unorm",e.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",e.ASTC5x5Unorm="astc-5x5-unorm",e.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",e.ASTC6x5Unorm="astc-6x5-unorm",e.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",e.ASTC6x6Unorm="astc-6x6-unorm",e.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",e.ASTC8x5Unorm="astc-8x5-unorm",e.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",e.ASTC8x6Unorm="astc-8x6-unorm",e.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",e.ASTC8x8Unorm="astc-8x8-unorm",e.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",e.ASTC10x5Unorm="astc-10x5-unorm",e.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",e.ASTC10x6Unorm="astc-10x6-unorm",e.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",e.ASTC10x8Unorm="astc-10x8-unorm",e.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",e.ASTC10x10Unorm="astc-10x10-unorm",e.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",e.ASTC12x10Unorm="astc-12x10-unorm",e.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",e.ASTC12x12Unorm="astc-12x12-unorm",e.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",e.Depth24UnormStencil8="depth24unorm-stencil8",e.Depth32FloatStencil8="depth32float-stencil8"}(yc||(yc={})),function(e){e.ClampToEdge="clamp-to-edge",e.Repeat="repeat",e.MirrorRepeat="mirror-repeat"}(Ac||(Ac={})),function(e){e.Nearest="nearest",e.Linear="linear"}(Rc||(Rc={})),function(e){e.Nearest="nearest",e.Linear="linear"}(Pc||(Pc={})),function(e){e.Never="never",e.Less="less",e.Equal="equal",e.LessEqual="less-equal",e.Greater="greater",e.NotEqual="not-equal",e.GreaterEqual="greater-equal",e.Always="always"}(Ic||(Ic={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Compute=4]="Compute"}(Mc||(Mc={})),function(e){e.Uniform="uniform",e.Storage="storage",e.ReadOnlyStorage="read-only-storage"}(Oc||(Oc={})),function(e){e.Filtering="filtering",e.NonFiltering="non-filtering",e.Comparison="comparison"}(Dc||(Dc={})),function(e){e.Float="float",e.UnfilterableFloat="unfilterable-float",e.Depth="depth",e.Sint="sint",e.Uint="uint"}(Nc||(Nc={})),function(e){e.WriteOnly="write-only"}(Fc||(Fc={})),function(e){e.Error="error",e.Warning="warning",e.Info="info"}(wc||(wc={})),function(e){e.Validation="validation",e.Internal="internal"}(Lc||(Lc={})),function(e){e.Auto="auto"}(Bc||(Bc={})),function(e){e.PointList="point-list",e.LineList="line-list",e.LineStrip="line-strip",e.TriangleList="triangle-list",e.TriangleStrip="triangle-strip"}(Uc||(Uc={})),function(e){e.CCW="ccw",e.CW="cw"}(Vc||(Vc={})),function(e){e.None="none",e.Front="front",e.Back="back"}(kc||(kc={})),function(e){e[e.Red=1]="Red",e[e.Green=2]="Green",e[e.Blue=4]="Blue",e[e.Alpha=8]="Alpha",e[e.All=15]="All"}(Gc||(Gc={})),function(e){e.Zero="zero",e.One="one",e.Src="src",e.OneMinusSrc="one-minus-src",e.SrcAlpha="src-alpha",e.OneMinusSrcAlpha="one-minus-src-alpha",e.Dst="dst",e.OneMinusDst="one-minus-dst",e.DstAlpha="dst-alpha",e.OneMinusDstAlpha="one-minus-dst-alpha",e.SrcAlphaSaturated="src-alpha-saturated",e.Constant="constant",e.OneMinusConstant="one-minus-constant"}(zc||(zc={})),function(e){e.Add="add",e.Subtract="subtract",e.ReverseSubtract="reverse-subtract",e.Min="min",e.Max="max"}(Wc||(Wc={})),function(e){e.Keep="keep",e.Zero="zero",e.Replace="replace",e.Invert="invert",e.IncrementClamp="increment-clamp",e.DecrementClamp="decrement-clamp",e.IncrementWrap="increment-wrap",e.DecrementWrap="decrement-wrap"}(Hc||(Hc={})),function(e){e.Uint16="uint16",e.Uint32="uint32"}(Xc||(Xc={})),function(e){e.Uint8x2="uint8x2",e.Uint8x4="uint8x4",e.Sint8x2="sint8x2",e.Sint8x4="sint8x4",e.Unorm8x2="unorm8x2",e.Unorm8x4="unorm8x4",e.Snorm8x2="snorm8x2",e.Snorm8x4="snorm8x4",e.Uint16x2="uint16x2",e.Uint16x4="uint16x4",e.Sint16x2="sint16x2",e.Sint16x4="sint16x4",e.Unorm16x2="unorm16x2",e.Unorm16x4="unorm16x4",e.Snorm16x2="snorm16x2",e.Snorm16x4="snorm16x4",e.Float16x2="float16x2",e.Float16x4="float16x4",e.Float32="float32",e.Float32x2="float32x2",e.Float32x3="float32x3",e.Float32x4="float32x4",e.Uint32="uint32",e.Uint32x2="uint32x2",e.Uint32x3="uint32x3",e.Uint32x4="uint32x4",e.Sint32="sint32",e.Sint32x2="sint32x2",e.Sint32x3="sint32x3",e.Sint32x4="sint32x4"}(Yc||(Yc={})),function(e){e.Vertex="vertex",e.Instance="instance"}(jc||(jc={})),function(e){e.Beginning="beginning",e.End="end"}(Kc||(Kc={})),function(e){e.Beginning="beginning",e.End="end"}(qc||(qc={})),function(e){e.Load="load",e.Clear="clear"}($c||($c={})),function(e){e.Store="store",e.Discard="discard"}(Qc||(Qc={})),function(e){e.Occlusion="occlusion",e.Timestamp="timestamp"}(Zc||(Zc={})),function(e){e.Opaque="opaque",e.Premultiplied="premultiplied"}(Jc||(Jc={})),function(e){e.Unknown="unknown",e.Destroyed="destroyed"}(ed||(ed={})),function(e){e.Validation="validation",e.OutOfMemory="out-of-memory",e.Internal="internal"}(td||(td={}));class id{constructor(){this.shaderLanguage=Qt.x.GLSL}_addUniformToLeftOverUBO(e,t,i){let n=0;[e,t,n]=this._getArraySize(e,t,i);for(let s=0;s=0&&(d.push(o[c]),u.push(e))}this.shaderProcessingContext.attributeNamesFromEffect=d,this.shaderProcessingContext.attributeLocationsFromEffect=u}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){this.uniformBuffer=new ae.M(this.engine,void 0,void 0,"leftOver-"+this._name);for(const e of this.shaderProcessingContext.leftOverUniforms){const t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=id.UniformSizes[t];this.uniformBuffer.addUniform(e.name,i,e.length),this._leftOverUniformsByName[e.name]=e.type}this.uniformBuffer.create()}}dispose(){this.uniformBuffer&&this.uniformBuffer.dispose()}setInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt(e,t)}setInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt2(e,t,i)}setInt3(e,t,i,n){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt3(e,t,i,n)}setInt4(e,t,i,n,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt4(e,t,i,n,s)}setIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateIntArray(e,t)}setIntArray2(e,t){this.setIntArray(e,t)}setIntArray3(e,t){this.setIntArray(e,t)}setIntArray4(e,t){this.setIntArray(e,t)}setUInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt(e,t)}setUInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt2(e,t,i)}setUInt3(e,t,i,n){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt3(e,t,i,n)}setUInt4(e,t,i,n,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt4(e,t,i,n,s)}setUIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUIntArray(e,t)}setUIntArray2(e,t){this.setUIntArray(e,t)}setUIntArray3(e,t){this.setUIntArray(e,t)}setUIntArray4(e,t){this.setUIntArray(e,t)}setArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateArray(e,t)}setArray2(e,t){this.setArray(e,t)}setArray3(e,t){this.setArray(e,t)}setArray4(e,t){this.setArray(e,t)}setMatrices(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrices(e,t)}setMatrix(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix(e,t)}setMatrix3x3(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix3x3(e,t)}setMatrix2x2(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix2x2(e,t)}setFloat(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat(e,t)}setVector2(e,t){this.setFloat2(e,t.x,t.y)}setFloat2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat2(e,t,i)}setVector3(e,t){this.setFloat3(e,t.x,t.y,t.z)}setFloat3(e,t,i,n){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat3(e,t,i,n)}setVector4(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setQuaternion(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setFloat4(e,t,i,n,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat4(e,t,i,n,s)}setColor3(e,t){this.setFloat3(e,t.r,t.g,t.b)}setColor4(e,t,i){this.setFloat4(e,t.r,t.g,t.b,i)}setDirectColor4(e,t){this.setFloat4(e,t.r,t.g,t.b,t.a)}_getVertexShaderCode(){var e;return null===(e=this.sources)||void 0===e?void 0:e.vertex}_getFragmentShaderCode(){var e;return null===(e=this.sources)||void 0===e?void 0:e.fragment}}const sd={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};class rd{static get KnownUBOs(){return rd._SimplifiedKnownBindings?rd._SimplifiedKnownUBOs:rd._KnownUBOs}constructor(e){this.shaderLanguage=e,this._attributeNextLocation=0,this._varyingNextLocation=0,this.freeGroupIndex=0,this.freeBindingIndex=0,this.availableVaryings={},this.availableAttributes={},this.availableBuffers={},this.availableTextures={},this.availableSamplers={},this.orderedAttributes=[],this.bindGroupLayoutEntries=[],this.bindGroupLayoutEntryInfo=[],this.bindGroupEntries=[],this.bufferNames=[],this.textureNames=[],this.samplerNames=[],this.leftOverUniforms=[],this._findStartingGroupBinding()}_findStartingGroupBinding(){const e=rd.KnownUBOs,t=[];for(const i in e){const n=e[i].binding;-1!==n.groupIndex&&(void 0===t[n.groupIndex]?t[n.groupIndex]=n.bindingIndex:t[n.groupIndex]=Math.max(t[n.groupIndex],n.bindingIndex))}this.freeGroupIndex=t.length-1,0===this.freeGroupIndex?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=t[t.length-1]+1}getAttributeNextLocation(e,t=0){var i;const n=this._attributeNextLocation;return this._attributeNextLocation+=(null!==(i=sd[e])&&void 0!==i?i:1)*(t||1),n}getVaryingNextLocation(e,t=0){var i;const n=this._varyingNextLocation;return this._varyingNextLocation+=(null!==(i=sd[e])&&void 0!==i?i:1)*(t||1),n}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>65536-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),4===this.freeGroupIndex)throw"Too many textures or UBOs have been declared and it is not supported in WebGPU.";const t={groupIndex:this.freeGroupIndex,bindingIndex:this.freeBindingIndex};return this.freeBindingIndex+=e,t}}rd._SimplifiedKnownBindings=!0,rd._SimplifiedKnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:-1,bindingIndex:-1}},Light1:{binding:{groupIndex:-1,bindingIndex:-1}},Light2:{binding:{groupIndex:-1,bindingIndex:-1}},Light3:{binding:{groupIndex:-1,bindingIndex:-1}},Light4:{binding:{groupIndex:-1,bindingIndex:-1}},Light5:{binding:{groupIndex:-1,bindingIndex:-1}},Light6:{binding:{groupIndex:-1,bindingIndex:-1}},Light7:{binding:{groupIndex:-1,bindingIndex:-1}},Light8:{binding:{groupIndex:-1,bindingIndex:-1}},Light9:{binding:{groupIndex:-1,bindingIndex:-1}},Light10:{binding:{groupIndex:-1,bindingIndex:-1}},Light11:{binding:{groupIndex:-1,bindingIndex:-1}},Light12:{binding:{groupIndex:-1,bindingIndex:-1}},Light13:{binding:{groupIndex:-1,bindingIndex:-1}},Light14:{binding:{groupIndex:-1,bindingIndex:-1}},Light15:{binding:{groupIndex:-1,bindingIndex:-1}},Light16:{binding:{groupIndex:-1,bindingIndex:-1}},Light17:{binding:{groupIndex:-1,bindingIndex:-1}},Light18:{binding:{groupIndex:-1,bindingIndex:-1}},Light19:{binding:{groupIndex:-1,bindingIndex:-1}},Light20:{binding:{groupIndex:-1,bindingIndex:-1}},Light21:{binding:{groupIndex:-1,bindingIndex:-1}},Light22:{binding:{groupIndex:-1,bindingIndex:-1}},Light23:{binding:{groupIndex:-1,bindingIndex:-1}},Light24:{binding:{groupIndex:-1,bindingIndex:-1}},Light25:{binding:{groupIndex:-1,bindingIndex:-1}},Light26:{binding:{groupIndex:-1,bindingIndex:-1}},Light27:{binding:{groupIndex:-1,bindingIndex:-1}},Light28:{binding:{groupIndex:-1,bindingIndex:-1}},Light29:{binding:{groupIndex:-1,bindingIndex:-1}},Light30:{binding:{groupIndex:-1,bindingIndex:-1}},Light31:{binding:{groupIndex:-1,bindingIndex:-1}},Material:{binding:{groupIndex:-1,bindingIndex:-1}},Mesh:{binding:{groupIndex:-1,bindingIndex:-1}},Internals:{binding:{groupIndex:-1,bindingIndex:-1}}},rd._KnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:1,bindingIndex:0}},Light1:{binding:{groupIndex:1,bindingIndex:1}},Light2:{binding:{groupIndex:1,bindingIndex:2}},Light3:{binding:{groupIndex:1,bindingIndex:3}},Light4:{binding:{groupIndex:1,bindingIndex:4}},Light5:{binding:{groupIndex:1,bindingIndex:5}},Light6:{binding:{groupIndex:1,bindingIndex:6}},Light7:{binding:{groupIndex:1,bindingIndex:7}},Light8:{binding:{groupIndex:1,bindingIndex:8}},Light9:{binding:{groupIndex:1,bindingIndex:9}},Light10:{binding:{groupIndex:1,bindingIndex:10}},Light11:{binding:{groupIndex:1,bindingIndex:11}},Light12:{binding:{groupIndex:1,bindingIndex:12}},Light13:{binding:{groupIndex:1,bindingIndex:13}},Light14:{binding:{groupIndex:1,bindingIndex:14}},Light15:{binding:{groupIndex:1,bindingIndex:15}},Light16:{binding:{groupIndex:1,bindingIndex:16}},Light17:{binding:{groupIndex:1,bindingIndex:17}},Light18:{binding:{groupIndex:1,bindingIndex:18}},Light19:{binding:{groupIndex:1,bindingIndex:19}},Light20:{binding:{groupIndex:1,bindingIndex:20}},Light21:{binding:{groupIndex:1,bindingIndex:21}},Light22:{binding:{groupIndex:1,bindingIndex:22}},Light23:{binding:{groupIndex:1,bindingIndex:23}},Light24:{binding:{groupIndex:1,bindingIndex:24}},Light25:{binding:{groupIndex:1,bindingIndex:25}},Light26:{binding:{groupIndex:1,bindingIndex:26}},Light27:{binding:{groupIndex:1,bindingIndex:27}},Light28:{binding:{groupIndex:1,bindingIndex:28}},Light29:{binding:{groupIndex:1,bindingIndex:29}},Light30:{binding:{groupIndex:1,bindingIndex:30}},Light31:{binding:{groupIndex:1,bindingIndex:31}},Material:{binding:{groupIndex:2,bindingIndex:0}},Mesh:{binding:{groupIndex:2,bindingIndex:1}},Internals:{binding:{groupIndex:2,bindingIndex:2}}};class od extends id{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=Qt.x.GLSL,this.parseGLES3=!0}_getArraySize(e,t,i){let n=0;const s=e.indexOf("["),r=e.indexOf("]");if(s>0&&r>0){const t=e.substring(s+1,r);n=+t,isNaN(n)&&(n=+i[t.trim()]),e=e.substr(0,s)}return[e,t,n]}initializeShaders(e){this._webgpuProcessingContext=e,this._missingVaryings.length=0,this._textureArrayProcessing.length=0,this.attributeKeywordName=void 0,this.varyingVertexKeywordName=void 0,this.varyingFragmentKeywordName=void 0}preProcessShaderCode(e,t){const i=`// Internals UBO\r\nuniform ${id.InternalsUBOName} {\nfloat yFactor_;\nfloat textureOutputHeight_;\n};\n`,n=-1!==e.indexOf("// Internals UBO");return t?(this._fragmentIsGLES3=-1!==e.indexOf("#version 3"),this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),n?e:i+"##INJECTCODE##\n"+e):(this._vertexIsGLES3=-1!==e.indexOf("#version 3"),this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),n?e:i+e)}varyingCheck(e,t){return(t&&this._fragmentIsGLES3?/(flat\s)?\s*in/:!t&&this._vertexIsGLES3?/(flat\s)?\s*out/:/(flat\s)?\s*varying/).test(e)}varyingProcessor(e,t,i){var n;this._preProcessors=i;const s=(t&&this._fragmentIsGLES3?/\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:!t&&this._vertexIsGLES3?/\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:/\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==s){const r=null!==(n=s[1])&&void 0!==n?n:"",o=s[2],a=s[3];let l;t?(l=this._webgpuProcessingContext.availableVaryings[a],this._missingVaryings[l]="",void 0===l&&p.Y.Warn(`Invalid fragment shader: The varying named "${a}" is not declared in the vertex shader! This declaration will be ignored.`)):(l=this._webgpuProcessingContext.getVaryingNextLocation(o,this._getArraySize(a,o,i)[2]),this._webgpuProcessingContext.availableVaryings[a]=l,this._missingVaryings[l]=`layout(location = ${l}) ${r} in ${o} ${a};`),e=e.replace(s[0],void 0===l?"":`layout(location = ${l}) ${r} ${t?"in":"out"} ${o} ${a};`)}return e}attributeProcessor(e,t){this._preProcessors=t;const i=(this._vertexIsGLES3?/\s*in\s+(\S+)\s+(\S+)\s*;/gm:/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==i){const n=i[1],s=i[2],r=this._webgpuProcessingContext.getAttributeNextLocation(n,this._getArraySize(s,n,t)[2]);this._webgpuProcessingContext.availableAttributes[s]=r,this._webgpuProcessingContext.orderedAttributes[r]=s,e=e.replace(i[0],`layout(location = ${r}) in ${n} ${s};`)}return e}uniformProcessor(e,t,i){var n;this._preProcessors=i;const s=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(null!==s){let r=s[1],o=s[2];if(0===r.indexOf("sampler")||1===r.indexOf("sampler")){let s=0;[o,r,s]=this._getArraySize(o,r,i);let a=this._webgpuProcessingContext.availableTextures[o];if(!a){a={autoBindSampler:!0,isTextureArray:s>0,isStorageTexture:!1,textures:[],sampleType:Nc.Float};for(let e=0;e<(s||1);++e)a.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}const l=null!==(n=id._SamplerTypeByWebGLSamplerType[r])&&void 0!==n?n:"sampler",h=!!id._IsComparisonSamplerByWebGPUSamplerType[l],c=h?Dc.Comparison:Dc.Filtering,d=o+id.AutoSamplerSuffix;let u=this._webgpuProcessingContext.availableSamplers[d];u||(u={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:c});const p="u"===r.charAt(0)?"u":"i"===r.charAt(0)?"i":"";p&&(r=r.substr(1));const f=h?Nc.Depth:"u"===p?Nc.Uint:"i"===p?Nc.Sint:Nc.Float;a.sampleType=f;const _=s>0,m=u.binding.groupIndex,g=u.binding.bindingIndex,v=id._SamplerFunctionByWebGLSamplerType[r],T=id._TextureTypeByWebGLSamplerType[r],S=id._GpuTextureViewDimensionByWebGPUTextureType[T];if(_){const t=[];t.push(`layout(set = ${m}, binding = ${g}) uniform ${p}${l} ${d};`),e="\r\n";for(let i=0;i0?"\r\n":""}#define ${o}${i} ${p}${v}(${o}Texture${i}, ${d})`}e=t.join("\r\n")+e,this._textureArrayProcessing.push(o)}else s=1,e=`layout(set = ${m}, binding = ${g}) uniform ${p}${l} ${d};\n layout(set = ${a.textures[0].groupIndex}, binding = ${a.textures[0].bindingIndex}) uniform ${T} ${o}Texture;\n #define ${o} ${p}${v}(${o}Texture, ${d})`;this._webgpuProcessingContext.availableTextures[o]=a,this._webgpuProcessingContext.availableSamplers[d]=u,this._addSamplerBindingDescription(d,u,!t);for(let e=0;e=0,i="\n glFragCoord_ = gl_FragCoord;\n if (yFactor_ == 1.) {\n glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y;\n }\n ",n=t?"vec4 glFragCoord_;\n":"";if(e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/gl_FragCoord/g,"glFragCoord_"),this._fragmentIsGLES3){const t=/^\s*out\s+\S+\s+\S+\s*;/gm.exec(e);null!==t&&(e=e.substring(0,t.index)+"layout(location = 0) "+e.substring(t.index))}else e=e.replace(/void\s+?main\s*\(/g,(r?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(");e=(e=e.replace(/dFdy/g,"(-yFactor_)*dFdy")).replace("##INJECTCODE##",n),t&&(e=this._injectStartingAndEndingCode(e,"void main",i))}else{e=(e=e.replace(/gl_InstanceID/g,"gl_InstanceIndex")).replace(/gl_VertexID/g,"gl_VertexIndex");if(-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e}if(!i){const t=e.lastIndexOf("}");e=e.substring(0,t),e+="gl_Position.y *= yFactor_;\n",s.isNDCHalfZRange||(e+="gl_Position.z = (gl_Position.z + gl_Position.w) / 2.0;\n"),e+="}"}return e}_applyTextureArrayProcessing(e,t){const i=new RegExp(t+"\\s*\\[(.+)?\\]","gm");let n=i.exec(e);for(;null!==n;){const s=n[1];let r=+s;this._preProcessors&&isNaN(r)&&(r=+this._preProcessors[s.trim()]),e=e.replace(n[0],t+r),n=i.exec(e)}return e}_generateLeftOverUBOCode(e,t){let i=`layout(set = ${t.binding.groupIndex}, binding = ${t.binding.bindingIndex}) uniform ${e} {\n `;for(const n of this._webgpuProcessingContext.leftOverUniforms)n.length>0?i+=` ${n.type} ${n.name}[${n.length}];\n`:i+=` ${n.type} ${n.name};\n`;return i+="};\n\n",i}finalizeShaders(e,t){for(let n=0;n0&&(t=e+"\n"+t)}const i=this._buildLeftOverUBO();return e=i+e,t=i+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,{vertexCode:e,fragmentCode:t}}}const ad="bonesDeclaration",ld="#if NUM_BONE_INFLUENCERS>0\nattribute matricesIndices : vec4;\nattribute matricesWeights : vec4;\n#if NUM_BONE_INFLUENCERS>4\nattribute matricesIndicesExtra : vec4;\nattribute matricesWeightsExtra : vec4;\n#endif\n#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#ifdef BONETEXTURE\nvar boneSampler : texture_2d;\nuniform boneTextureWidth : f32;\n#else\nuniform mBones : array;\n#ifdef BONES_VELOCITY_ENABLED\nuniform mPreviousBones : array;\n#endif\n#endif\n#ifdef BONETEXTURE\nfn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4\n{\nlet offset=i32(index) *4; \nlet m0=textureLoad(smp,vec2(offset+0,0),0);\nlet m1=textureLoad(smp,vec2(offset+1,0),0);\nlet m2=textureLoad(smp,vec2(offset+2,0),0);\nlet m3=textureLoad(smp,vec2(offset+3,0),0);\nreturn mat4x4(m0,m1,m2,m3);\n}\n#endif\n#endif\n#endif\n";Ht.v.IncludesShadersStoreWGSL[ad]=ld;const hd="bonesVertex",cd="#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#if NUM_BONE_INFLUENCERS>0\nvar influence : mat4x4;\n#ifdef BONETEXTURE\ninfluence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3];\n#endif \n#else \ninfluence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3];\n#endif \n#endif\nfinalWorld=finalWorld*influence;\n#endif\n#endif\n";Ht.v.IncludesShadersStoreWGSL[hd]=cd;const dd="bakedVertexAnimationDeclaration",ud="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\nuniform bakedVertexAnimationTime: f32;\nuniform bakedVertexAnimationTextureSizeInverted: vec2;\nuniform bakedVertexAnimationSettings: vec4;\nvar bakedVertexAnimationTexture : texture_2d;\n#ifdef INSTANCES\nattribute bakedVertexAnimationSettingsInstanced : vec4;\n#endif\nfn readMatrixFromRawSamplerVAT(smp : texture_2d,index : f32,frame : f32)->mat4x4\n{\nlet offset=i32(index)*4;\nlet frameUV=i32(frame);\nlet m0=textureLoad(smp,vec2(offset+0,frameUV),0);\nlet m1=textureLoad(smp,vec2(offset+1,frameUV),0);\nlet m2=textureLoad(smp,vec2(offset+2,frameUV),0);\nlet m3=textureLoad(smp,vec2(offset+3,frameUV),0);\nreturn mat4x4(m0,m1,m2,m3);\n}\n#endif\n";Ht.v.IncludesShadersStoreWGSL[dd]=ud;const pd="bakedVertexAnimation",fd="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\n{\n#ifdef INSTANCES\nlet VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;\nlet VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;\nlet VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;\nlet VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w;\n#else\nlet VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;\nlet VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;\nlet VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;\nlet VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w;\n#endif\nlet totalFrames: f32=VATEndFrame-VATStartFrame+1.0;\nlet time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;\nlet frameCorrection: f32=select(1.0,0.0,time<1.0);\nlet numOfFrames: f32=totalFrames-frameCorrection;\nvar VATFrameNum: f32=fract(time)*numOfFrames;\nVATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;\nVATFrameNum=floor(VATFrameNum);\nVATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;\nvar VATInfluence : mat4x4;\nVATInfluence=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}\n#endif\n";Ht.v.IncludesShadersStoreWGSL[pd]=fd;const _d="clipPlaneFragment",md="#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{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE2\nelse if (fragmentInputs.fClipDistance2>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE3\nelse if (fragmentInputs.fClipDistance3>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE4\nelse if (fragmentInputs.fClipDistance4>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE5\nelse if (fragmentInputs.fClipDistance5>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE6\nelse if (fragmentInputs.fClipDistance6>0.0)\n{\ndiscard;\n}\n#endif\n";Ht.v.IncludesShadersStoreWGSL[_d]=md;const gd="clipPlaneFragmentDeclaration",vd="#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";Ht.v.IncludesShadersStoreWGSL[gd]=vd;const Td="clipPlaneVertex",Sd="#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";Ht.v.IncludesShadersStoreWGSL[Td]=Sd;const Ed="clipPlaneVertexDeclaration",xd="#ifdef CLIPPLANE\nuniform vClipPlane: vec4;\nvarying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nuniform vClipPlane2: vec4;\nvarying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nuniform vClipPlane3: vec4;\nvarying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nuniform vClipPlane4: vec4;\nvarying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nuniform vClipPlane5: vec4;\nvarying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nuniform vClipPlane6: vec4;\nvarying fClipDistance6: f32;\n#endif\n";Ht.v.IncludesShadersStoreWGSL[Ed]=xd;const bd="instancesDeclaration",Cd="#ifdef INSTANCES\nattribute world0 : vec4;\nattribute world1 : vec4;\nattribute world2 : vec4;\nattribute world3 : vec4;\n#ifdef INSTANCESCOLOR\nattribute instanceColor : vec4;\n#endif\n#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)\nuniform world : mat4x4;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nattribute previousWorld0 : vec4;\nattribute previousWorld1 : vec4;\nattribute previousWorld2 : vec4;\nattribute previousWorld3 : vec4;\n#ifdef THIN_INSTANCES\nuniform previousWorld : mat4x4;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nuniform world : mat4x4;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nuniform previousWorld : mat4x4;\n#endif\n#endif\n";Ht.v.IncludesShadersStoreWGSL[bd]=Cd;const yd="instancesVertex",Ad="#ifdef INSTANCES\nvar finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3);\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=mat4x4(previousWorld0,previousWorld1,previousWorld2,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=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=previousWorld;\n#endif\n#endif\n";Ht.v.IncludesShadersStoreWGSL[yd]=Ad;const Rd="meshUboDeclaration",Pd="struct Mesh {\nworld : mat4x4,\nvisibility : f32,\n};\nvar mesh : Mesh;\n#define WORLD_UBO\n";Ht.v.IncludesShadersStoreWGSL[Rd]=Pd;const Id="morphTargetsVertex",Md="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE \nvertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;\npositionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];\nvertexID=vertexID+1.0;\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];\nvertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];\nvertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\n#endif\n#else\npositionUpdated=positionUpdated+(position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];\n#endif\n#endif\n#endif\n";Ht.v.IncludesShadersStoreWGSL[Id]=Md;const Od="morphTargetsVertexDeclaration",Dd="#ifdef MORPHTARGETS\n#ifndef MORPHTARGETS_TEXTURE\nattribute position{X} : vec3;\n#ifdef MORPHTARGETS_NORMAL\nattribute normal{X} : vec3;\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute tangent{X} : vec3;\n#endif\n#ifdef MORPHTARGETS_UV\nattribute uv_{X} : vec2;\n#endif\n#endif\n#endif\n";Ht.v.IncludesShadersStoreWGSL[Od]=Dd;const Nd="morphTargetsVertexGlobal",Fd="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\nvar vertexID : f32;\n#endif\n#endif\n";Ht.v.IncludesShadersStoreWGSL[Nd]=Fd;const wd="morphTargetsVertexGlobalDeclaration",Ld="#ifdef MORPHTARGETS\nuniform morphTargetInfluences : array;\n#ifdef MORPHTARGETS_TEXTURE \nuniform morphTargetTextureIndices : array;\nuniform morphTargetTextureInfo : vec3;\nvar morphTargets : texture_2d_array;\nvar morphTargetsSampler : sampler;\nfn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3\n{ \nlet y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);\nlet x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;\nlet textureUV=vec2((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);\nreturn textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;\n}\n#endif\n#endif\n";Ht.v.IncludesShadersStoreWGSL[wd]=Ld;const Bd="sceneUboDeclaration",Ud="struct Scene {\nviewProjection : mat4x4,\n#ifdef MULTIVIEW\nviewProjectionR : mat4x4,\n#endif \nview : mat4x4,\nprojection : mat4x4,\nvEyePosition : vec4,\n};\nvar scene : Scene;\n";Ht.v.IncludesShadersStoreWGSL[Bd]=Ud;const Vd="fragmentOutputs.fragDepth",kd={texture_1d:bc.E1d,texture_2d:bc.E2d,texture_2d_array:bc.E2dArray,texture_3d:bc.E3d,texture_cube:bc.Cube,texture_cube_array:bc.CubeArray,texture_multisampled_2d:bc.E2d,texture_depth_2d:bc.E2d,texture_depth_2d_array:bc.E2dArray,texture_depth_cube:bc.Cube,texture_depth_cube_array:bc.CubeArray,texture_depth_multisampled_2d:bc.E2d,texture_storage_1d:bc.E1d,texture_storage_2d:bc.E2d,texture_storage_2d_array:bc.E2dArray,texture_storage_3d:bc.E3d,texture_external:null};class Gd extends id{constructor(){super(...arguments),this.shaderLanguage=Qt.x.WGSL,this.uniformRegexp=/uniform\s+(\w+)\s*:\s*(.+)\s*;/,this.textureRegexp=/var\s+(\w+)\s*:\s*((array<\s*)?(texture_\w+)\s*(<\s*(.+)\s*>)?\s*(,\s*\w+\s*>\s*)?);/,this.noPrecision=!0}_getArraySize(e,t,i){let n=0;const s=t.lastIndexOf(">");if(t.indexOf("array")>=0&&s>0){let e=s;for(;e>0&&" "!==t.charAt(e)&&","!==t.charAt(e);)e--;const r=t.substring(e+1,s);for(n=+r,isNaN(n)&&(n=+i[r.trim()]);e>0&&(" "===t.charAt(e)||","===t.charAt(e));)e--;t=t.substring(t.indexOf("<")+1,e+1)}return[e,t,n]}initializeShaders(e){this._webgpuProcessingContext=e,this._attributesWGSL=[],this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){return`struct ${id.InternalsUBOName} {\n yFactor_: f32,\n textureOutputHeight_: f32,\n};\nvar internals : ${id.InternalsUBOName};\n`+sc(e)}varyingProcessor(e,t,i){const n=/\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==n){const s=n[2],r=n[1];let o;t?(o=this._webgpuProcessingContext.availableVaryings[r],void 0===o&&p.Y.Warn(`Invalid fragment shader: The varying named "${r}" is not declared in the vertex shader! This declaration will be ignored.`)):(o=this._webgpuProcessingContext.getVaryingNextLocation(s,this._getArraySize(r,s,i)[2]),this._webgpuProcessingContext.availableVaryings[r]=o,this._varyingsWGSL.push(` @location(${o}) ${r} : ${s},`),this._varyingNamesWGSL.push(r)),e=""}return e}attributeProcessor(e,t){const i=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==i){const n=i[2],s=i[1],r=this._webgpuProcessingContext.getAttributeNextLocation(n,this._getArraySize(s,n,t)[2]);this._webgpuProcessingContext.availableAttributes[s]=r,this._webgpuProcessingContext.orderedAttributes[r]=s,this._attributesWGSL.push(`@location(${r}) ${s} : ${n},`),e=""}return e}uniformProcessor(e,t,i){const n=this.uniformRegexp.exec(e);if(null!==n){const t=n[2],s=n[1];this._addUniformToLeftOverUBO(s,t,i),e=""}return e}textureProcessor(e,t,i){const n=this.textureRegexp.exec(e);if(null!==n){const s=n[1],r=n[2],o=!!n[3],a=n[4],l=a.indexOf("storage")>0,h=n[6],c=l?h.substring(0,h.indexOf(",")).trim():null;let d=o?this._getArraySize(s,r,i)[2]:0,u=this._webgpuProcessingContext.availableTextures[s];if(u)d=u.textures.length;else{u={isTextureArray:d>0,isStorageTexture:l,textures:[],sampleType:Nc.Float},d=d||1;for(let e=0;e0,f=kd[a],_=p?Nc.Depth:"u32"===h?Nc.Uint:"i32"===h?Nc.Sint:Nc.Float;if(u.sampleType=_,void 0===f)throw`Can't get the texture dimension corresponding to the texture function "${a}"!`;for(let i=0;i=0?"\n if (internals.yFactor_ == 1.) {\n fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y;\n }\n ":"";e=this._processSamplers(e,!0),t=this._processSamplers(t,!1),e=this._processCustomBuffers(e,!0),t=this._processCustomBuffers(t,!1);const n=this._buildLeftOverUBO();t=n+t,e=(e=n+e).replace(/#define /g,"//#define "),e=this._processStridedUniformArrays(e);let s="struct VertexInputs {\n @builtin(vertex_index) vertexIndex : u32,\n @builtin(instance_index) instanceIndex : u32,\n";this._attributesWGSL.length>0&&(s+=this._attributesWGSL.join("\n")),s+="\n};\nvar vertexInputs : VertexInputs;\n";let r="struct FragmentInputs {\n @builtin(position) position : vec4,\n";this._varyingsWGSL.length>0&&(r+=this._varyingsWGSL.join("\n")),r+="\n};\nvar vertexOutputs : FragmentInputs;\n",e=s+r+e;e=this._injectStartingAndEndingCode(e,"fn main","\n vertexInputs = input;\n"," vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_;\n return vertexOutputs;"),t=t.replace(/#define /g,"//#define "),t=(t=this._processStridedUniformArrays(t)).replace(/dpdy/g,"(-internals.yFactor_)*dpdy");let o="struct FragmentInputs {\n @builtin(position) position : vec4,\n @builtin(front_facing) frontFacing : bool,\n";this._varyingsWGSL.length>0&&(o+=this._varyingsWGSL.join("\n")),o+="\n};\nvar fragmentInputs : FragmentInputs;\n";let a="struct FragmentOutputs {\n @location(0) color : vec4,\n",l=!1,h=0;for(;!(l||(h=t.indexOf(Vd,h),h<0));){const e=h;for(l=!0;h>1&&"\n"!==t.charAt(h);){if("/"===t.charAt(h)&&"/"===t.charAt(h-1)){l=!1;break}h--}h=e+25}l&&(a+=" @builtin(frag_depth) fragDepth: f32,\n"),a+="};\nvar fragmentOutputs : FragmentOutputs;\n",t=o+a+t;const c=" fragmentInputs = input;\n "+i;return t=this._injectStartingAndEndingCode(t,"fn main",c," return fragmentOutputs;"),this._collectBindingNames(),this._preCreateBindGroupEntries(),{vertexCode:e,fragmentCode:t}}_generateLeftOverUBOCode(e,t){let i="",n=`struct ${e} {\n`;for(const s of this._webgpuProcessingContext.leftOverUniforms){const t=s.type.replace(/^(.*?)(<.*>)?$/,"$1"),r=id.UniformSizes[t];if(s.length>0)if(r<=2){const r=`${e}_${this._stridedUniformArrays.length}_strided_arr`;i+=`struct ${r} {\n @size(16)\n el: ${t},\n }`,this._stridedUniformArrays.push(s.name),n+=` @align(16) ${s.name} : array<${r}, ${s.length}>,\n`}else n+=` ${s.name} : array<${s.type}, ${s.length}>,\n`;else n+=` ${s.name} : ${s.type},\n`}return n+="};\n",n=`${i}\n${n}`,n+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var uniforms : ${e};\n`,n}_processSamplers(e,t){const i=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;for(;;){const n=i.exec(e);if(null===n)break;const s=n[1],r=n[2],o=s.indexOf(id.AutoSamplerSuffix)===s.length-id.AutoSamplerSuffix.length?s.substring(0,s.indexOf(id.AutoSamplerSuffix)):null,a="sampler_comparison"===r?Dc.Comparison:Dc.Filtering;if(o){const e=this._webgpuProcessingContext.availableTextures[o];e&&(e.autoBindSampler=!0)}let l=this._webgpuProcessingContext.availableSamplers[s];l||(l={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:a},this._webgpuProcessingContext.availableSamplers[s]=l),this._addSamplerBindingDescription(s,l,t);const h=e.substring(0,n.index),c=`@group(${l.binding.groupIndex}) @binding(${l.binding.bindingIndex}) `,d=e.substring(n.index);e=h+c+d,i.lastIndex+=c.length}return e}_processCustomBuffers(e,t){const i=/var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;for(;;){const n=i.exec(e);if(null===n)break;const s=n[1],r=n[3];let o=n[4];const a=n[5];let l=this._webgpuProcessingContext.availableBuffers[o];if(!l){const e="uniform"===s?rd.KnownUBOs[a]:null;let t;e?(o=a,t=e.binding,-1===t.groupIndex&&(t=this._webgpuProcessingContext.getNextFreeUBOBinding())):t=this._webgpuProcessingContext.getNextFreeUBOBinding(),l={binding:t},this._webgpuProcessingContext.availableBuffers[o]=l}this._addBufferBindingDescription(o,this._webgpuProcessingContext.availableBuffers[o],"read_write"===r?Oc.Storage:"storage"===s?Oc.ReadOnlyStorage:Oc.Uniform,t);const h=l.binding.groupIndex,c=l.binding.bindingIndex,d=e.substring(0,n.index),u=`@group(${h}) @binding(${c}) `,p=e.substring(n.index);e=d+u+p,i.lastIndex+=u.length}return e}_processStridedUniformArrays(e){for(const t of this._stridedUniformArrays)e=e.replace(new RegExp(`${t}\\s*\\[(.*)\\]`,"g"),`${t}[$1].el`);return e}}class zd{get underlyingResource(){return this._webgpuTexture}getMSAATexture(e=0){var t,i;return null!==(i=null===(t=this._webgpuMSAATexture)||void 0===t?void 0:t[e])&&void 0!==i?i:null}setMSAATexture(e,t=-1){this._webgpuMSAATexture||(this._webgpuMSAATexture=[]),-1===t&&(t=this._webgpuMSAATexture.length),this._webgpuMSAATexture[t]=e}releaseMSAATexture(){if(this._webgpuMSAATexture){for(const e of this._webgpuMSAATexture)null==e||e.destroy();this._webgpuMSAATexture=null}}constructor(e=null){this.format=yc.RGBA8Unorm,this.textureUsages=0,this.textureAdditionalUsages=0,this._webgpuTexture=e,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}set(e){this._webgpuTexture=e}setUsage(e,t,i,n,s){this.createView({format:this.format,dimension:i?bc.Cube:bc.E2d,mipLevelCount:t?S.R.ILog2(Math.max(n,s))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:i?6:1,aspect:Cc.All})}createView(e,t=!1){if(this.view=this._webgpuTexture.createView(e),t&&e){const t=e.mipLevelCount;e.mipLevelCount=1,this.viewForWriting=this._webgpuTexture.createView(e),e.mipLevelCount=t}}reset(){this._webgpuTexture=null,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}release(){var e,t;null===(e=this._webgpuTexture)||void 0===e||e.destroy(),this.releaseMSAATexture(),null===(t=this._copyInvertYTempTexture)||void 0===t||t.destroy(),this.reset()}}const Wd="\n #extension GL_EXT_samplerless_texture_functions : enable\n\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));\n\n layout(set = 0, binding = 0) uniform texture2D img;\n\n #ifdef INVERTY\n layout(location = 0) out flat ivec2 vTextureSize;\n #endif\n\n void main() {\n #ifdef INVERTY\n vTextureSize = textureSize(img, 0);\n #endif\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",Hd=Wd;var Xd,Yd;!function(e){e[e.MipMap=0]="MipMap",e[e.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",e[e.Clear=2]="Clear",e[e.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst"}(Xd||(Xd={})),function(e){e[e.DontInvertY=0]="DontInvertY",e[e.InvertY=1]="InvertY"}(Yd||(Yd={}));const jd=[{vertex:"\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));\n\n layout(location = 0) out vec2 vTex;\n\n void main() {\n vTex = tex[gl_VertexIndex];\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n layout(set = 0, binding = 0) uniform sampler imgSampler;\n layout(set = 0, binding = 1) uniform texture2D img;\n\n layout(location = 0) in vec2 vTex;\n layout(location = 0) out vec4 outColor;\n\n void main() {\n outColor = texture(sampler2D(img, imgSampler), vTex);\n }\n "},{vertex:Wd,fragment:"\n #extension GL_EXT_samplerless_texture_functions : enable\n\n layout(set = 0, binding = 0) uniform texture2D img;\n\n #ifdef INVERTY\n layout(location = 0) in flat ivec2 vTextureSize;\n #endif\n layout(location = 0) out vec4 outColor;\n\n void main() {\n #ifdef INVERTY\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0);\n #else\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color.rgb *= color.a;\n #endif\n outColor = color;\n }\n "},{vertex:"\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n\n void main() {\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n layout(set = 0, binding = 0) uniform Uniforms {\n uniform vec4 color;\n };\n\n layout(location = 0) out vec4 outColor;\n\n void main() {\n outColor = color;\n }\n "},{vertex:Hd,fragment:"\n #extension GL_EXT_samplerless_texture_functions : enable\n\n layout(set = 0, binding = 0) uniform texture2D img;\n layout(set = 0, binding = 1) uniform Params {\n float ofstX;\n float ofstY;\n float width;\n float height;\n };\n\n #ifdef INVERTY\n layout(location = 0) in flat ivec2 vTextureSize;\n #endif\n layout(location = 0) out vec4 outColor;\n\n void main() {\n if (gl_FragCoord.x < ofstX || gl_FragCoord.x >= ofstX + width) {\n discard;\n }\n if (gl_FragCoord.y < ofstY || gl_FragCoord.y >= ofstY + height) {\n discard;\n }\n #ifdef INVERTY\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, ofstY + height - (gl_FragCoord.y - ofstY)), 0);\n #else\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color.rgb *= color.a;\n #endif\n outColor = color;\n }\n "}],Kd={"":0,r8unorm:1,r8uint:2,r8sint:3,r16uint:4,r16sint:5,r16float:6,rg8unorm:7,rg8uint:8,rg8sint:9,r32uint:10,r32sint:11,r32float:12,rg16uint:13,rg16sint:14,rg16float:15,rgba8unorm:16,"rgba8unorm-srgb":17,rgba8uint:18,rgba8sint:19,bgra8unorm:20,"bgra8unorm-srgb":21,rgb10a2unorm:22,rg32uint:23,rg32sint:24,rg32float:25,rgba16uint:26,rgba16sint:27,rgba16float:28,rgba32uint:29,rgba32sint:30,rgba32float:31,stencil8:32,depth16unorm:33,depth24plus:34,"depth24plus-stencil8":35,depth32float:36,"depth32float-stencil8":37};class qd{static ComputeNumMipmapLevels(e,t){return S.R.ILog2(Math.max(e,t))+1}constructor(e,t,i,n,s){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._device=e,this._glslang=t,this._tintWASM=i,this._bufferManager=n,-1!==s.indexOf(gc.RG11B10UFloatRenderable)){const e=Object.keys(Kd);Kd[yc.RG11B10UFloat]=Kd[e[e.length-1]]+1}this._mipmapSampler=e.createSampler({minFilter:Rc.Linear}),this._videoSampler=e.createSampler({minFilter:Rc.Linear}),this._ubCopyWithOfst=this._bufferManager.createBuffer(16,Tc.Uniform|Tc.CopyDst).underlyingResource,this._getPipeline(yc.RGBA8Unorm),this._getVideoPipeline(yc.RGBA8Unorm)}_getPipeline(e,t=Xd.MipMap,i){const n=t===Xd.MipMap?1:t===Xd.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===Xd.Clear?8:t===Xd.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);let s=this._pipelines[e][n];if(!s){let r="#version 450\r\n";t!==Xd.InvertYPremultiplyAlpha&&t!==Xd.InvertYPremultiplyAlphaWithOfst||(i.invertY&&(r+="#define INVERTY\r\n"),i.premultiplyAlpha&&(r+="#define PREMULTIPLYALPHA\r\n"));let o=this._compiledShaders[n];if(!o){let e=this._glslang.compileGLSL(r+jd[t].vertex,"vertex"),i=this._glslang.compileGLSL(r+jd[t].fragment,"fragment");this._tintWASM&&(e=this._tintWASM.convertSpirV2WGSL(e),i=this._tintWASM.convertSpirV2WGSL(i));const s=this._device.createShaderModule({code:e}),a=this._device.createShaderModule({code:i});o=this._compiledShaders[n]=[s,a]}const a=this._device.createRenderPipeline({layout:Bc.Auto,vertex:{module:o[0],entryPoint:"main"},fragment:{module:o[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:Uc.TriangleStrip,stripIndexFormat:Xc.Uint16}});s=this._pipelines[e][n]=[a,a.getBindGroupLayout(0)]}return s}_getVideoPipeline(e,t=Yd.DontInvertY){const i=t===Yd.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let n=this._videoPipelines[e][i];if(!n){let t=this._videoCompiledShaders[i];if(!t){const e=this._device.createShaderModule({code:"\n struct VertexOutput {\n @builtin(position) Position : vec4,\n @location(0) fragUV : vec2\n }\n \n @vertex\n fn main(\n @builtin(vertex_index) VertexIndex : u32\n ) -> VertexOutput {\n var pos = array, 4>(\n vec2(-1.0, 1.0),\n vec2( 1.0, 1.0),\n vec2(-1.0, -1.0),\n vec2( 1.0, -1.0)\n );\n var tex = array, 4>(\n vec2(0.0, 0.0),\n vec2(1.0, 0.0),\n vec2(0.0, 1.0),\n vec2(1.0, 1.0)\n );\n\n var output: VertexOutput;\n\n output.Position = vec4(pos[VertexIndex], 0.0, 1.0);\n output.fragUV = tex[VertexIndex];\n\n return output;\n }\n "}),n=this._device.createShaderModule({code:0===i?"\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2\n ) -> @location(0) vec4 {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV);\n }\n ":"\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2\n ) -> @location(0) vec4 {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2(fragUV.x, 1.0 - fragUV.y));\n }\n "});t=this._videoCompiledShaders[i]=[e,n]}const s=this._device.createRenderPipeline({label:`CopyVideoToTexture_${e}_${0===i?"DontInvertY":"InvertY"}`,layout:Bc.Auto,vertex:{module:t[0],entryPoint:"main"},fragment:{module:t[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:Uc.TriangleStrip,stripIndexFormat:Xc.Uint16}});n=this._videoPipelines[e][i]=[s,s.getBindGroupLayout(0)]}return n}static _GetTextureTypeFromFormat(e){switch(e){case yc.R8Unorm:case yc.R8Snorm:case yc.R8Uint:case yc.R8Sint:case yc.RG8Unorm:case yc.RG8Snorm:case yc.RG8Uint:case yc.RG8Sint:case yc.RGBA8Unorm:case yc.RGBA8UnormSRGB:case yc.RGBA8Snorm:case yc.RGBA8Uint:case yc.RGBA8Sint:case yc.BGRA8Unorm:case yc.BGRA8UnormSRGB:case yc.RGB10A2Unorm:case yc.RGB9E5UFloat:case yc.RG11B10UFloat:case yc.Depth24UnormStencil8:case yc.Depth32FloatStencil8:case yc.BC7RGBAUnorm:case yc.BC7RGBAUnormSRGB:case yc.BC6HRGBUFloat:case yc.BC6HRGBFloat:case yc.BC5RGUnorm:case yc.BC5RGSnorm:case yc.BC3RGBAUnorm:case yc.BC3RGBAUnormSRGB:case yc.BC2RGBAUnorm:case yc.BC2RGBAUnormSRGB:case yc.BC4RUnorm:case yc.BC4RSnorm:case yc.BC1RGBAUnorm:case yc.BC1RGBAUnormSRGB:case yc.ETC2RGB8Unorm:case yc.ETC2RGB8UnormSRGB:case yc.ETC2RGB8A1Unorm:case yc.ETC2RGB8A1UnormSRGB:case yc.ETC2RGBA8Unorm:case yc.ETC2RGBA8UnormSRGB:case yc.EACR11Unorm:case yc.EACR11Snorm:case yc.EACRG11Unorm:case yc.EACRG11Snorm:case yc.ASTC4x4Unorm:case yc.ASTC4x4UnormSRGB:case yc.ASTC5x4Unorm:case yc.ASTC5x4UnormSRGB:case yc.ASTC5x5Unorm:case yc.ASTC5x5UnormSRGB:case yc.ASTC6x5Unorm:case yc.ASTC6x5UnormSRGB:case yc.ASTC6x6Unorm:case yc.ASTC6x6UnormSRGB:case yc.ASTC8x5Unorm:case yc.ASTC8x5UnormSRGB:case yc.ASTC8x6Unorm:case yc.ASTC8x6UnormSRGB:case yc.ASTC8x8Unorm:case yc.ASTC8x8UnormSRGB:case yc.ASTC10x5Unorm:case yc.ASTC10x5UnormSRGB:case yc.ASTC10x6Unorm:case yc.ASTC10x6UnormSRGB:case yc.ASTC10x8Unorm:case yc.ASTC10x8UnormSRGB:case yc.ASTC10x10Unorm:case yc.ASTC10x10UnormSRGB:case yc.ASTC12x10Unorm:case yc.ASTC12x10UnormSRGB:case yc.ASTC12x12Unorm:case yc.ASTC12x12UnormSRGB:return 0;case yc.R16Uint:case yc.R16Sint:case yc.RG16Uint:case yc.RG16Sint:case yc.RGBA16Uint:case yc.RGBA16Sint:case yc.Depth16Unorm:return 5;case yc.R16Float:case yc.RG16Float:case yc.RGBA16Float:return 2;case yc.R32Uint:case yc.R32Sint:case yc.RG32Uint:case yc.RG32Sint:case yc.RGBA32Uint:case yc.RGBA32Sint:return 7;case yc.R32Float:case yc.RG32Float:case yc.RGBA32Float:case yc.Depth32Float:return 1;case yc.Stencil8:throw"No fixed size for Stencil8 format!";case yc.Depth24Plus:throw"No fixed size for Depth24Plus format!";case yc.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!"}return 0}static _GetBlockInformationFromFormat(e){switch(e){case yc.R8Unorm:case yc.R8Snorm:case yc.R8Uint:case yc.R8Sint:return{width:1,height:1,length:1};case yc.R16Uint:case yc.R16Sint:case yc.R16Float:case yc.RG8Unorm:case yc.RG8Snorm:case yc.RG8Uint:case yc.RG8Sint:return{width:1,height:1,length:2};case yc.R32Uint:case yc.R32Sint:case yc.R32Float:case yc.RG16Uint:case yc.RG16Sint:case yc.RG16Float:case yc.RGBA8Unorm:case yc.RGBA8UnormSRGB:case yc.RGBA8Snorm:case yc.RGBA8Uint:case yc.RGBA8Sint:case yc.BGRA8Unorm:case yc.BGRA8UnormSRGB:case yc.RGB9E5UFloat:case yc.RGB10A2Unorm:case yc.RG11B10UFloat:return{width:1,height:1,length:4};case yc.RG32Uint:case yc.RG32Sint:case yc.RG32Float:case yc.RGBA16Uint:case yc.RGBA16Sint:case yc.RGBA16Float:return{width:1,height:1,length:8};case yc.RGBA32Uint:case yc.RGBA32Sint:case yc.RGBA32Float:return{width:1,height:1,length:16};case yc.Stencil8:throw"No fixed size for Stencil8 format!";case yc.Depth16Unorm:return{width:1,height:1,length:2};case yc.Depth24Plus:throw"No fixed size for Depth24Plus format!";case yc.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!";case yc.Depth32Float:case yc.Depth24UnormStencil8:return{width:1,height:1,length:4};case yc.Depth32FloatStencil8:return{width:1,height:1,length:5};case yc.BC7RGBAUnorm:case yc.BC7RGBAUnormSRGB:case yc.BC6HRGBUFloat:case yc.BC6HRGBFloat:case yc.BC5RGUnorm:case yc.BC5RGSnorm:case yc.BC3RGBAUnorm:case yc.BC3RGBAUnormSRGB:case yc.BC2RGBAUnorm:case yc.BC2RGBAUnormSRGB:return{width:4,height:4,length:16};case yc.BC4RUnorm:case yc.BC4RSnorm:case yc.BC1RGBAUnorm:case yc.BC1RGBAUnormSRGB:case yc.ETC2RGB8Unorm:case yc.ETC2RGB8UnormSRGB:case yc.ETC2RGB8A1Unorm:case yc.ETC2RGB8A1UnormSRGB:case yc.EACR11Unorm:case yc.EACR11Snorm:return{width:4,height:4,length:8};case yc.ETC2RGBA8Unorm:case yc.ETC2RGBA8UnormSRGB:case yc.EACRG11Unorm:case yc.EACRG11Snorm:case yc.ASTC4x4Unorm:case yc.ASTC4x4UnormSRGB:return{width:4,height:4,length:16};case yc.ASTC5x4Unorm:case yc.ASTC5x4UnormSRGB:return{width:5,height:4,length:16};case yc.ASTC5x5Unorm:case yc.ASTC5x5UnormSRGB:return{width:5,height:5,length:16};case yc.ASTC6x5Unorm:case yc.ASTC6x5UnormSRGB:return{width:6,height:5,length:16};case yc.ASTC6x6Unorm:case yc.ASTC6x6UnormSRGB:return{width:6,height:6,length:16};case yc.ASTC8x5Unorm:case yc.ASTC8x5UnormSRGB:return{width:8,height:5,length:16};case yc.ASTC8x6Unorm:case yc.ASTC8x6UnormSRGB:return{width:8,height:6,length:16};case yc.ASTC8x8Unorm:case yc.ASTC8x8UnormSRGB:return{width:8,height:8,length:16};case yc.ASTC10x5Unorm:case yc.ASTC10x5UnormSRGB:return{width:10,height:5,length:16};case yc.ASTC10x6Unorm:case yc.ASTC10x6UnormSRGB:return{width:10,height:6,length:16};case yc.ASTC10x8Unorm:case yc.ASTC10x8UnormSRGB:return{width:10,height:8,length:16};case yc.ASTC10x10Unorm:case yc.ASTC10x10UnormSRGB:return{width:10,height:10,length:16};case yc.ASTC12x10Unorm:case yc.ASTC12x10UnormSRGB:return{width:12,height:10,length:16};case yc.ASTC12x12Unorm:case yc.ASTC12x12UnormSRGB:return{width:12,height:12,length:16}}return{width:1,height:1,length:4}}static _IsHardwareTexture(e){return!!e.release}static _IsInternalTexture(e){return!!e.dispose}static IsImageBitmap(e){return void 0!==e.close}static IsImageBitmapArray(e){return Array.isArray(e)&&void 0!==e[0].close}setCommandEncoder(e){this._commandEncoderForCreation=e}static IsCompressedFormat(e){switch(e){case yc.BC7RGBAUnormSRGB:case yc.BC7RGBAUnorm:case yc.BC6HRGBFloat:case yc.BC6HRGBUFloat:case yc.BC5RGSnorm:case yc.BC5RGUnorm:case yc.BC4RSnorm:case yc.BC4RUnorm:case yc.BC3RGBAUnormSRGB:case yc.BC3RGBAUnorm:case yc.BC2RGBAUnormSRGB:case yc.BC2RGBAUnorm:case yc.BC1RGBAUnormSRGB:case yc.BC1RGBAUnorm:case yc.ETC2RGB8Unorm:case yc.ETC2RGB8UnormSRGB:case yc.ETC2RGB8A1Unorm:case yc.ETC2RGB8A1UnormSRGB:case yc.ETC2RGBA8Unorm:case yc.ETC2RGBA8UnormSRGB:case yc.EACR11Unorm:case yc.EACR11Snorm:case yc.EACRG11Unorm:case yc.EACRG11Snorm:case yc.ASTC4x4Unorm:case yc.ASTC4x4UnormSRGB:case yc.ASTC5x4Unorm:case yc.ASTC5x4UnormSRGB:case yc.ASTC5x5Unorm:case yc.ASTC5x5UnormSRGB:case yc.ASTC6x5Unorm:case yc.ASTC6x5UnormSRGB:case yc.ASTC6x6Unorm:case yc.ASTC6x6UnormSRGB:case yc.ASTC8x5Unorm:case yc.ASTC8x5UnormSRGB:case yc.ASTC8x6Unorm:case yc.ASTC8x6UnormSRGB:case yc.ASTC8x8Unorm:case yc.ASTC8x8UnormSRGB:case yc.ASTC10x5Unorm:case yc.ASTC10x5UnormSRGB:case yc.ASTC10x6Unorm:case yc.ASTC10x6UnormSRGB:case yc.ASTC10x8Unorm:case yc.ASTC10x8UnormSRGB:case yc.ASTC10x10Unorm:case yc.ASTC10x10UnormSRGB:case yc.ASTC12x10Unorm:case yc.ASTC12x10UnormSRGB:case yc.ASTC12x12Unorm:case yc.ASTC12x12UnormSRGB:return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return yc.Depth16Unorm;case 16:return yc.Depth24Plus;case 13:return yc.Depth24PlusStencil8;case 14:return yc.Depth32Float;case 17:return yc.Depth24UnormStencil8;case 18:return yc.Depth32FloatStencil8;case 19:return yc.Stencil8;case 36492:return i?yc.BC7RGBAUnormSRGB:yc.BC7RGBAUnorm;case 36495:return yc.BC6HRGBUFloat;case 36494:return yc.BC6HRGBFloat;case 33779:return i?yc.BC3RGBAUnormSRGB:yc.BC3RGBAUnorm;case 33778:return i?yc.BC2RGBAUnormSRGB:yc.BC2RGBAUnorm;case 33777:case 33776:return i?yc.BC1RGBAUnormSRGB:yc.BC1RGBAUnorm;case 37808:return i?yc.ASTC4x4UnormSRGB:yc.ASTC4x4Unorm;case 36196:case 37492:return i?yc.ETC2RGB8UnormSRGB:yc.ETC2RGB8Unorm;case 37496:return i?yc.ETC2RGBA8UnormSRGB:yc.ETC2RGBA8Unorm}switch(e){case 3:switch(t){case 6:return yc.R8Snorm;case 7:return yc.RG8Snorm;case 4:throw"RGB format not supported in WebGPU";case 8:return yc.R8Sint;case 9:return yc.RG8Sint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return yc.RGBA8Sint;default:return yc.RGBA8Snorm}case 0:switch(t){case 6:return yc.R8Unorm;case 7:return yc.RG8Unorm;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?yc.RGBA8UnormSRGB:yc.RGBA8Unorm;case 12:return i?yc.BGRA8UnormSRGB:yc.BGRA8Unorm;case 8:return yc.R8Uint;case 9:return yc.RG8Uint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return yc.RGBA8Uint;case 0:throw"TEXTUREFORMAT_ALPHA format not supported in WebGPU";case 1:throw"TEXTUREFORMAT_LUMINANCE format not supported in WebGPU";case 2:throw"TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU";default:return yc.RGBA8Unorm}case 4:switch(t){case 8:return yc.R16Sint;case 9:return yc.RG16Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return yc.RGBA16Sint}case 5:switch(t){case 8:return yc.R16Uint;case 9:return yc.RG16Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return yc.RGBA16Uint}case 6:switch(t){case 8:return yc.R32Sint;case 9:return yc.RG32Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return yc.RGBA32Sint}case 7:switch(t){case 8:return yc.R32Uint;case 9:return yc.RG32Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return yc.RGBA32Uint}case 1:switch(t){case 6:return yc.R32Float;case 7:return yc.RG32Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return yc.RGBA32Float}case 2:switch(t){case 6:return yc.R16Float;case 7:return yc.RG16Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return yc.RGBA16Float}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:switch(t){case 5:default:return yc.RG11B10UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV"}case 14:switch(t){case 5:default:return yc.RGB9E5UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV"}case 8:throw"TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU";case 9:throw"TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU";case 11:switch(t){case 5:default:return yc.RGB10A2Unorm;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV"}}return i?yc.RGBA8UnormSRGB:yc.RGBA8Unorm}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case yc.R8Unorm:case yc.R8Snorm:case yc.R8Uint:case yc.R8Sint:case yc.BC4RUnorm:case yc.BC4RSnorm:case yc.R16Uint:case yc.R16Sint:case yc.Depth16Unorm:case yc.R16Float:case yc.R32Uint:case yc.R32Sint:case yc.R32Float:case yc.Depth32Float:case yc.Stencil8:case yc.Depth24Plus:case yc.EACR11Unorm:case yc.EACR11Snorm:return 1;case yc.RG8Unorm:case yc.RG8Snorm:case yc.RG8Uint:case yc.RG8Sint:case yc.Depth24UnormStencil8:case yc.Depth32FloatStencil8:case yc.BC5RGUnorm:case yc.BC5RGSnorm:case yc.RG16Uint:case yc.RG16Sint:case yc.RG16Float:case yc.RG32Uint:case yc.RG32Sint:case yc.RG32Float:case yc.Depth24PlusStencil8:case yc.EACRG11Unorm:case yc.EACRG11Snorm:return 2;case yc.RGB9E5UFloat:case yc.RG11B10UFloat:case yc.BC6HRGBUFloat:case yc.BC6HRGBFloat:case yc.ETC2RGB8Unorm:case yc.ETC2RGB8UnormSRGB:return 3;case yc.RGBA8Unorm:case yc.RGBA8UnormSRGB:case yc.RGBA8Snorm:case yc.RGBA8Uint:case yc.RGBA8Sint:case yc.BGRA8Unorm:case yc.BGRA8UnormSRGB:case yc.RGB10A2Unorm:case yc.BC7RGBAUnorm:case yc.BC7RGBAUnormSRGB:case yc.BC3RGBAUnorm:case yc.BC3RGBAUnormSRGB:case yc.BC2RGBAUnorm:case yc.BC2RGBAUnormSRGB:case yc.BC1RGBAUnorm:case yc.BC1RGBAUnormSRGB:case yc.RGBA16Uint:case yc.RGBA16Sint:case yc.RGBA16Float:case yc.RGBA32Uint:case yc.RGBA32Sint:case yc.RGBA32Float:case yc.ETC2RGB8A1Unorm:case yc.ETC2RGB8A1UnormSRGB:case yc.ETC2RGBA8Unorm:case yc.ETC2RGBA8UnormSRGB:case yc.ASTC4x4Unorm:case yc.ASTC4x4UnormSRGB:case yc.ASTC5x4Unorm:case yc.ASTC5x4UnormSRGB:case yc.ASTC5x5Unorm:case yc.ASTC5x5UnormSRGB:case yc.ASTC6x5Unorm:case yc.ASTC6x5UnormSRGB:case yc.ASTC6x6Unorm:case yc.ASTC6x6UnormSRGB:case yc.ASTC8x5Unorm:case yc.ASTC8x5UnormSRGB:case yc.ASTC8x6Unorm:case yc.ASTC8x6UnormSRGB:case yc.ASTC8x8Unorm:case yc.ASTC8x8UnormSRGB:case yc.ASTC10x5Unorm:case yc.ASTC10x5UnormSRGB:case yc.ASTC10x6Unorm:case yc.ASTC10x6UnormSRGB:case yc.ASTC10x8Unorm:case yc.ASTC10x8UnormSRGB:case yc.ASTC10x10Unorm:case yc.ASTC10x10UnormSRGB:case yc.ASTC12x10Unorm:case yc.ASTC12x10UnormSRGB:case yc.ASTC12x12Unorm:case yc.ASTC12x12UnormSRGB:return 4}throw`Unknown format ${e}!`}static HasStencilAspect(e){switch(e){case yc.Stencil8:case yc.Depth24UnormStencil8:case yc.Depth32FloatStencil8:case yc.Depth24PlusStencil8:return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case yc.Depth24UnormStencil8:case yc.Depth32FloatStencil8:case yc.Depth24PlusStencil8:return!0}return!1}static GetDepthFormatOnly(e){switch(e){case yc.Depth16Unorm:return yc.Depth16Unorm;case yc.Depth24Plus:case yc.Depth24PlusStencil8:case yc.Depth24UnormStencil8:return yc.Depth24Plus;case yc.Depth32Float:case yc.Depth32FloatStencil8:return yc.Depth32Float}return e}copyVideoToTexture(e,t,i,n=!1,s){var r,o,a,l;const h=void 0===s,[c,d]=this._getVideoPipeline(i,n?Yd.InvertY:Yd.DontInvertY);h&&(s=this._device.createCommandEncoder({})),null===(o=(r=s).pushDebugGroup)||void 0===o||o.call(r,`copy video to texture - invertY=${n}`);const u={colorAttachments:[{view:t._hardwareTexture.underlyingResource.createView({format:i,dimension:bc.E2d,mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:Cc.All}),loadOp:$c.Load,storeOp:Qc.Store}]},p=s.beginRenderPass(u),f={layout:d,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},_=this._device.createBindGroup(f);p.setPipeline(c),p.setBindGroup(0,_),p.draw(4,1,0,0),p.end(),null===(l=(a=s).popDebugGroup)||void 0===l||l.call(a),h&&(this._device.queue.submit([s.finish()]),s=null)}invertYPreMultiplyAlpha(e,t,i,n,s=!1,r=!1,o=0,a=0,l=1,h=0,c=0,d=0,u=0,p,f){var _,m,g,v,T,S;const E=0!==d,x=void 0===p,[b,C]=this._getPipeline(n,E?Xd.InvertYPremultiplyAlphaWithOfst:Xd.InvertYPremultiplyAlpha,{invertY:s,premultiplyAlpha:r});let y;if(o=Math.max(o,0),x&&(p=this._device.createCommandEncoder({})),null===(m=(_=p).pushDebugGroup)||void 0===m||m.call(_,`internal process texture - invertY=${s} premultiplyAlpha=${r}`),qd._IsHardwareTexture(e)?(y=e.underlyingResource,s&&!r&&1===l&&0===o||(e=void 0)):(y=e,e=void 0),!y)return;E&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([h,c,d,u]),0,16);const A=e,R=null!==(g=null==A?void 0:A._copyInvertYTempTexture)&&void 0!==g?g:this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,n,1,p,xc.CopySrc|xc.RenderAttachment|xc.TextureBinding,void 0,"TempTextureForCopyWithInvertY"),P=null!==(v=null==A?void 0:A._copyInvertYRenderPassDescr)&&void 0!==v?v:{colorAttachments:[{view:R.createView({format:n,dimension:bc.E2d,baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:$c.Load,storeOp:Qc.Store}]},I=p.beginRenderPass(P);let M=E?null==A?void 0:A._copyInvertYBindGroupWithOfst:null==A?void 0:A._copyInvertYBindGroup;if(!M){const e={layout:C,entries:[{binding:0,resource:y.createView({format:n,dimension:bc.E2d,baseMipLevel:a,mipLevelCount:1,arrayLayerCount:l,baseArrayLayer:o})}]};E&&e.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),M=this._device.createBindGroup(e)}I.setPipeline(b),I.setBindGroup(0,M),I.draw(4,1,0,0),I.end(),p.copyTextureToTexture({texture:R},{texture:y,mipLevel:a,origin:{x:0,y:0,z:o}},{width:t,height:i,depthOrArrayLayers:1}),A?(A._copyInvertYTempTexture=R,A._copyInvertYRenderPassDescr=P,E?A._copyInvertYBindGroupWithOfst=M:A._copyInvertYBindGroup=M):this._deferredReleaseTextures.push([R,null]),null===(S=(T=p).popDebugGroup)||void 0===S||S.call(T),x&&(this._device.queue.submit([p.finish()]),p=null)}copyWithInvertY(e,t,i,n){var s,r,o,a;const l=void 0===n,[h,c]=this._getPipeline(t,Xd.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});l&&(n=this._device.createCommandEncoder({})),null===(r=(s=n).pushDebugGroup)||void 0===r||r.call(s,"internal copy texture with invertY");const d=n.beginRenderPass(i),u=this._device.createBindGroup({layout:c,entries:[{binding:0,resource:e}]});d.setPipeline(h),d.setBindGroup(0,u),d.draw(4,1,0,0),d.end(),null===(a=(o=n).popDebugGroup)||void 0===a||a.call(o),l&&(this._device.queue.submit([n.finish()]),n=null)}createTexture(e,t=!1,i=!1,n=!1,s=!1,r=!1,o=yc.RGBA8Unorm,a=1,l,h=-1,c=0,d){a>1&&(a=4);const u=e.layers||1,p={width:e.width,height:e.height,depthOrArrayLayers:u},f=Kd[o]?xc.RenderAttachment:0,_=qd.IsCompressedFormat(o),m=t?qd.ComputeNumMipmapLevels(e.width,e.height):1,g=h>=0?h:xc.CopySrc|xc.CopyDst|xc.TextureBinding;c|=t&&!_?xc.CopySrc|f:0,_||r||(c|=f|xc.CopyDst);const v=this._device.createTexture({label:`Texture${r?"3D":"2D"}_${d?d+"_":""}${p.width}x${p.height}x${p.depthOrArrayLayers}_${t?"wmips":"womips"}_${o}_samples${a}`,size:p,dimension:r?Ec.E3d:Ec.E2d,format:o,usage:g|c,sampleCount:a,mipLevelCount:m});return qd.IsImageBitmap(e)&&(this.updateTexture(e,v,e.width,e.height,u,o,0,0,n,s,0,0),t&&i&&this.generateMipmaps(v,o,m,0,l)),v}createCubeTexture(e,t=!1,i=!1,n=!1,s=!1,r=yc.RGBA8Unorm,o=1,a,l=-1,h=0,c){o>1&&(o=4);const d=qd.IsImageBitmapArray(e)?e[0].width:e.width,u=qd.IsImageBitmapArray(e)?e[0].height:e.height,p=Kd[r]?xc.RenderAttachment:0,f=qd.IsCompressedFormat(r),_=t?qd.ComputeNumMipmapLevels(d,u):1,m=l>=0?l:xc.CopySrc|xc.CopyDst|xc.TextureBinding;h|=t&&!f?xc.CopySrc|p:0,f||(h|=p|xc.CopyDst);const g=this._device.createTexture({label:`TextureCube_${c?c+"_":""}${d}x${u}x6_${t?"wmips":"womips"}_${r}_samples${o}`,size:{width:d,height:u,depthOrArrayLayers:6},dimension:Ec.E2d,format:r,usage:m|h,sampleCount:o,mipLevelCount:_});return qd.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,g,d,u,r,n,s,0,0),t&&i&&this.generateCubeMipmaps(g,r,_,a)),g}generateCubeMipmaps(e,t,i,n){var s,r,o,a;const l=void 0===n;l&&(n=this._device.createCommandEncoder({})),null===(r=(s=n).pushDebugGroup)||void 0===r||r.call(s,`create cube mipmaps - ${i} levels`);for(let h=0;h<6;++h)this.generateMipmaps(e,t,i,h,n);null===(a=(o=n).popDebugGroup)||void 0===a||a.call(o),l&&(this._device.queue.submit([n.finish()]),n=null)}generateMipmaps(e,t,i,n=0,s){var r,o,a,l,h,c,d,u;const p=void 0===s,[f,_]=this._getPipeline(t);let m;if(n=Math.max(n,0),p&&(s=this._device.createCommandEncoder({})),null===(o=(r=s).pushDebugGroup)||void 0===o||o.call(r,`create mipmaps for face #${n} - ${i} levels`),qd._IsHardwareTexture(e)?(m=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(m=e,e=void 0),!m)return;const g=e;for(let v=1;vh;)this._device.queue.writeBuffer(r,t+c,i.buffer,o+c,h),c+=h;this._device.queue.writeBuffer(r,t+c,i.buffer,o+c,s-c)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));const n=new Uint16Array(t);for(;e--;)i[e]=Vh(n[e]);return i}readDataFromBuffer(e,t,i,n,s,r,o=0,a=0,l=null,h=!0,c=!1){const d=1===o?2:2===o?1:0;return new Promise(((i,u)=>{e.mapAsync(Sc.Read,a,t).then((()=>{const u=e.getMappedRange(a,t);let p=l;if(c)p=null===p?(0,Ch.A)(o,t,!0,u):(0,Ch.A)(o,p.buffer,void 0,u);else if(null===p)switch(d){case 0:p=new Uint8Array(t),p.set(new Uint8Array(u));break;case 1:p=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,u);break;case 2:p=new Float32Array(t/4),p.set(new Float32Array(u))}else switch(d){case 0:p=new Uint8Array(p.buffer),p.set(new Uint8Array(u));break;case 1:p=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,u,l);break;case 2:p=new Float32Array(p.buffer),p.set(new Float32Array(u))}if(s!==r){1!==d||c||(s*=2,r*=2);const e=new Uint8Array(p.buffer);let t=s,i=0;for(let o=1;ou(e)))}))}releaseBuffer(e){return Qd._IsGPUBuffer(e)?(this._deferredReleaseBuffers.push(e),!0):(e.references--,0===e.references&&(this._deferredReleaseBuffers.push(e.underlyingResource),!0))}destroyDeferredBuffers(){for(let e=0;e1?4:1;return Jd[e.samplingMode]+eu[(e._comparisonFunction||514)-512+1]+tu[e.samplingMode]+((null!==(t=e._cachedWrapU)&&void 0!==t?t:1)<<8)+((null!==(i=e._cachedWrapV)&&void 0!==i?i:1)<<10)+((null!==(n=e._cachedWrapR)&&void 0!==n?n:1)<<12)+((e.useMipMaps?1:0)<<14)+(s<<15)}static _GetSamplerFilterDescriptor(e,t){let i,n,s,r,o;const a=e.useMipMaps;switch(e.samplingMode){case 11:i=Rc.Linear,n=Rc.Linear,s=Rc.Nearest,a||(r=o=0);break;case 3:case 3:i=Rc.Linear,n=Rc.Linear,a?s=Rc.Linear:(s=Rc.Nearest,r=o=0);break;case 8:i=Rc.Nearest,n=Rc.Nearest,a?s=Rc.Linear:(s=Rc.Nearest,r=o=0);break;case 4:i=Rc.Nearest,n=Rc.Nearest,s=Rc.Nearest,a||(r=o=0);break;case 5:i=Rc.Nearest,n=Rc.Linear,s=Rc.Nearest,a||(r=o=0);break;case 6:i=Rc.Nearest,n=Rc.Linear,a?s=Rc.Linear:(s=Rc.Nearest,r=o=0);break;case 7:i=Rc.Nearest,n=Rc.Linear,s=Rc.Nearest,r=o=0;break;case 1:case 1:default:i=Rc.Nearest,n=Rc.Nearest,s=Rc.Nearest,r=o=0;break;case 9:i=Rc.Linear,n=Rc.Nearest,s=Rc.Nearest,a||(r=o=0);break;case 10:i=Rc.Linear,n=Rc.Nearest,a?s=Rc.Linear:(s=Rc.Nearest,r=o=0);break;case 2:case 2:i=Rc.Linear,n=Rc.Linear,s=Rc.Nearest,r=o=0;break;case 12:i=Rc.Linear,n=Rc.Nearest,s=Rc.Nearest,r=o=0}return t>1&&(0!==r||0!==o)?{magFilter:Rc.Linear,minFilter:Rc.Linear,mipmapFilter:Rc.Linear,anisotropyEnabled:!0}:{magFilter:i,minFilter:n,mipmapFilter:s,lodMinClamp:r,lodMaxClamp:o}}static _GetWrappingMode(e){switch(e){case 1:return Ac.Repeat;case 0:return Ac.ClampToEdge;case 2:return Ac.MirrorRepeat}return Ac.Repeat}static _GetSamplerWrappingDescriptor(e){return{addressModeU:this._GetWrappingMode(e._cachedWrapU),addressModeV:this._GetWrappingMode(e._cachedWrapV),addressModeW:this._GetWrappingMode(e._cachedWrapR)}}static _GetSamplerDescriptor(e){const t=e.useMipMaps&&e._cachedAnisotropicFilteringLevel&&e._cachedAnisotropicFilteringLevel>1?4:1,i=this._GetSamplerFilterDescriptor(e,t);return Object.assign(Object.assign(Object.assign({},i),this._GetSamplerWrappingDescriptor(e)),{compare:e._comparisonFunction?iu.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:i.anisotropyEnabled?t:1})}static GetCompareFunction(e){switch(e){case 519:return Ic.Always;case 514:return Ic.Equal;case 516:return Ic.Greater;case 518:return Ic.GreaterEqual;case 513:default:return Ic.Less;case 515:return Ic.LessEqual;case 512:return Ic.Never;case 517:return Ic.NotEqual}}getSampler(e,t=!1,i=0){if(this.disabled)return this._device.createSampler(iu._GetSamplerDescriptor(e));t?i=0:0===i&&(i=iu.GetSamplerHashCode(e));let n=t?void 0:this._samplers[i];return n||(n=this._device.createSampler(iu._GetSamplerDescriptor(e)),t||(this._samplers[i]=n)),n}}var nu;!function(e){e[e.StencilReadMask=0]="StencilReadMask",e[e.StencilWriteMask=1]="StencilWriteMask",e[e.DepthBias=2]="DepthBias",e[e.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",e[e.DepthStencilState=4]="DepthStencilState",e[e.MRTAttachments1=5]="MRTAttachments1",e[e.MRTAttachments2=6]="MRTAttachments2",e[e.RasterizationState=7]="RasterizationState",e[e.ColorStates=8]="ColorStates",e[e.ShaderStage=9]="ShaderStage",e[e.TextureStage=10]="TextureStage",e[e.VertexState=11]="VertexState",e[e.NumStates=12]="NumStates"}(nu||(nu={}));const su={0:1,1:2,768:3,769:4,770:5,771:6,772:7,773:8,774:9,775:10,776:11,32769:12,32770:13,32771:12,32772:13},ru={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7};class ou{constructor(e,t,i){this.mrtTextureCount=0,this._device=e,this._useTextureStage=i,this._states=new Array(30),this._statesLength=0,this._stateDirtyLowestIndex=0,this._emptyVertexBuffer=t,this._mrtFormats=[],this._parameter={token:void 0,pipeline:null},this.disabled=!1,this.vertexBuffers=[],this._kMaxVertexBufferStride=e.limits.maxVertexBufferArrayStride||2048,this.reset()}reset(){this._isDirty=!0,this.vertexBuffers.length=0,this.setAlphaToCoverage(!1),this.resetDepthCullingState(),this.setClampDepth(!1),this.setDepthBias(0),this._webgpuColorFormat=[yc.BGRA8Unorm],this.setColorFormat(yc.BGRA8Unorm),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat(yc.Depth24PlusStencil8),this.setStencilEnabled(!1),this.resetStencilState(),this.setBuffers(null,null,null),this._setTextureState(0)}get colorFormats(){return this._mrtAttachments1>0?this._mrtFormats:this._webgpuColorFormat}getRenderPipeline(e,t,i,n=0){if(i>1&&(i=4),this.disabled){const s=ou._GetTopology(e);return this._setVertexState(t),this._setTextureState(n),this._parameter.pipeline=this._createRenderPipeline(t,s,i),ou.NumCacheMiss++,ou._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(t.uniqueId),this._setRasterizationState(e,i),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(t),this._setTextureState(n),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,ou.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return ou.NumCacheHitWithHash++,this._parameter.pipeline;const s=ou._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,s,i),this._setRenderPipeline(this._parameter),ou.NumCacheMiss++,ou._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){ou.NumPipelineCreationLastFrame=ou._NumPipelineCreationCurrentFrame,ou._NumPipelineCreationCurrentFrame=0}setAlphaToCoverage(e){this._alphaToCoverageEnabled=e}setFrontFace(e){this._frontFace=e}setCullEnabled(e){this._cullEnabled=e}setCullFace(e){this._cullFace=e}setClampDepth(e){this._clampDepth=e}resetDepthCullingState(){this.setDepthCullingState(!1,2,1,0,0,!0,!0,519)}setDepthCullingState(e,t,i,n,s,r,o,a){this._depthWriteEnabled=o,this._depthTestEnabled=r,this._depthCompare=(null!=a?a:519)-512,this._cullFace=i,this._cullEnabled=e,this._frontFace=t,this.setDepthBiasSlopeScale(n),this.setDepthBias(s)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[nu.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,nu.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[nu.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,nu.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=Kd[null!=e?e:""]}setMRTAttachments(e){this.mrtAttachments=e;let t=0;for(let i=0;i10)throw"Can't handle more than 10 attachments for a MRT in cache render pipeline!";this.mrtTextureArray=e,this.mrtTextureCount=t,this._mrtEnabledMask=65535;const s=[0,0];let r=0,o=0,a=0;for(let l=0;l=32&&(o=0,r++)}this._mrtFormats.length=a,this._mrtAttachments1===s[0]&&this._mrtAttachments2===s[1]||(this._mrtAttachments1=s[0],this._mrtAttachments2=s[1],this._states[nu.MRTAttachments1]=s[0],this._states[nu.MRTAttachments2]=s[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,nu.MRTAttachments1))}setAlphaBlendEnabled(e){this._alphaBlendEnabled=e}setAlphaBlendFactors(e,t){this._alphaBlendFuncParams=e,this._alphaBlendEqParams=t}setWriteMask(e){this._writeMask=e}setDepthStencilFormat(e){this._webgpuDepthStencilFormat=e,this._depthStencilFormat=void 0===e?0:Kd[e]}setDepthTestEnabled(e){this._depthTestEnabled=e}setDepthWriteEnabled(e){this._depthWriteEnabled=e}setDepthCompare(e){this._depthCompare=(null!=e?e:519)-512}setStencilEnabled(e){this._stencilEnabled=e}setStencilCompare(e){this._stencilFrontCompare=(null!=e?e:519)-512}setStencilDepthFailOp(e){this._stencilFrontDepthFailOp=null===e?1:ru[e]}setStencilPassOp(e){this._stencilFrontPassOp=null===e?2:ru[e]}setStencilFailOp(e){this._stencilFrontFailOp=null===e?1:ru[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[nu.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,nu.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[nu.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,nu.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,n,s,r,o){this._stencilEnabled=e,this._stencilFrontCompare=(null!=t?t:519)-512,this._stencilFrontDepthFailOp=null===i?1:ru[i],this._stencilFrontPassOp=null===n?2:ru[n],this._stencilFrontFailOp=null===s?1:ru[s],this.setStencilReadMask(r),this.setStencilWriteMask(o)}setBuffers(e,t,i){this._vertexBuffers=e,this._overrideVertexBuffers=i,this._indexBuffer=t}static _GetTopology(e){switch(e){case 0:default:return Uc.TriangleList;case 2:case 3:return Uc.PointList;case 1:case 4:return Uc.LineList;case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return Uc.LineStrip;case 7:return Uc.TriangleStrip;case 8:throw"TriangleFan is an unsupported fillmode in WebGPU"}}static _GetAphaBlendOperation(e){switch(e){case 32774:default:return Wc.Add;case 32778:return Wc.Subtract;case 32779:return Wc.ReverseSubtract;case 32775:return Wc.Min;case 32776:return Wc.Max}}static _GetAphaBlendFactor(e){switch(e){case 0:return zc.Zero;case 1:default:return zc.One;case 768:return zc.Src;case 769:return zc.OneMinusSrc;case 770:return zc.SrcAlpha;case 771:return zc.OneMinusSrcAlpha;case 772:return zc.DstAlpha;case 773:return zc.OneMinusDstAlpha;case 774:return zc.Dst;case 775:return zc.OneMinusDst;case 776:return zc.SrcAlphaSaturated;case 32769:case 32771:return zc.Constant;case 32770:case 32772:return zc.OneMinusConstant}}static _GetCompareFunction(e){switch(e){case 0:return Ic.Never;case 1:return Ic.Less;case 2:return Ic.Equal;case 3:return Ic.LessEqual;case 4:return Ic.Greater;case 5:return Ic.NotEqual;case 6:return Ic.GreaterEqual;case 7:return Ic.Always}return Ic.Never}static _GetStencilOpFunction(e){switch(e){case 0:return Hc.Zero;case 1:return Hc.Keep;case 2:return Hc.Replace;case 3:return Hc.IncrementClamp;case 4:return Hc.DecrementClamp;case 5:return Hc.Invert;case 6:return Hc.IncrementWrap;case 7:return Hc.DecrementWrap}return Hc.Keep}static _GetVertexInputDescriptorFormat(e){const t=e.type,i=e.normalized,n=e.getSize();switch(t){case ne.o.BYTE:switch(n){case 1:case 2:return i?Yc.Snorm8x2:Yc.Sint8x2;case 3:case 4:return i?Yc.Snorm8x4:Yc.Sint8x4}break;case ne.o.UNSIGNED_BYTE:switch(n){case 1:case 2:return i?Yc.Unorm8x2:Yc.Uint8x2;case 3:case 4:return i?Yc.Unorm8x4:Yc.Uint8x4}break;case ne.o.SHORT:switch(n){case 1:case 2:return i?Yc.Snorm16x2:Yc.Sint16x2;case 3:case 4:return i?Yc.Snorm16x4:Yc.Sint16x4}break;case ne.o.UNSIGNED_SHORT:switch(n){case 1:case 2:return i?Yc.Unorm16x2:Yc.Uint16x2;case 3:case 4:return i?Yc.Unorm16x4:Yc.Uint16x4}break;case ne.o.INT:switch(n){case 1:return Yc.Sint32;case 2:return Yc.Sint32x2;case 3:return Yc.Sint32x3;case 4:return Yc.Sint32x4}break;case ne.o.UNSIGNED_INT:switch(n){case 1:return Yc.Uint32;case 2:return Yc.Uint32x2;case 3:return Yc.Uint32x3;case 4:return Yc.Uint32x4}break;case ne.o.FLOAT:switch(n){case 1:return Yc.Float32;case 2:return Yc.Float32x2;case 3:return Yc.Float32x3;case 4:return Yc.Float32x4}}throw new Error(`Invalid Format '${e.getKind()}' - type=${t}, normalized=${i}, size=${n}`)}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:ou._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:ou._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:ou._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:ou._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:ou._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:ou._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[nu.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,nu.ShaderStage))}_setRasterizationState(e,t){const i=this._frontFace-1+((this._cullEnabled?this._cullFace:0)<<1)+((this._clampDepth?1:0)<<3)+((this._alphaToCoverageEnabled?1:0)<<4)+(e<<5)+(t<<8);this._rasterizationState!==i&&(this._rasterizationState=i,this._states[nu.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,nu.RasterizationState))}_setColorStates(){let e=((this._writeMask?1:0)<<22)+(this._colorFormat<<23)+((this._depthWriteEnabled?1:0)<<29);this._alphaBlendEnabled&&(e+=((null===this._alphaBlendFuncParams[0]?2:su[this._alphaBlendFuncParams[0]])<<0)+((null===this._alphaBlendFuncParams[1]?2:su[this._alphaBlendFuncParams[1]])<<4)+((null===this._alphaBlendFuncParams[2]?2:su[this._alphaBlendFuncParams[2]])<<8)+((null===this._alphaBlendFuncParams[3]?2:su[this._alphaBlendFuncParams[3]])<<12)+((null===this._alphaBlendEqParams[0]?1:this._alphaBlendEqParams[0]-32773)<<16)+((null===this._alphaBlendEqParams[1]?1:this._alphaBlendEqParams[1]-32773)<<19)),e!==this._colorStates&&(this._colorStates=e,this._states[nu.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,nu.ColorStates))}_setDepthStencilState(){const e=this._stencilEnabled?this._stencilFrontCompare+(this._stencilFrontDepthFailOp<<3)+(this._stencilFrontPassOp<<6)+(this._stencilFrontFailOp<<9):591,t=this._depthStencilFormat+((this._depthTestEnabled?this._depthCompare:7)<<6)+(e<<10);this._depthStencilState!==t&&(this._depthStencilState=t,this._states[nu.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,nu.DepthStencilState))}_setVertexState(e){var t,i;const n=this._statesLength;let s=nu.VertexState;const r=e._pipelineContext,o=r.shaderProcessingContext.attributeNamesFromEffect,a=r.shaderProcessingContext.attributeLocationsFromEffect;let l,h=0;for(let c=0;c0)for(let _=0;_=this._video.HAVE_CURRENT_DATA}dispose(){}}class fu{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatTextures(){return this._numFloatTextures>0}constructor(){this.uniqueId=fu._Counter++,this.updateId=0,this.textureState=0,this.reset()}reset(){this.samplers={},this.textures={},this.isDirty=!0,this._numFloatTextures=0,this._numExternalTextures=0}setSampler(e,t){let i=this.samplers[e],n=-1;i?n=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?iu.GetSamplerHashCode(t):0;const s=n!==i.hashCode;s&&this.updateId++,this.isDirty||(this.isDirty=s)}setTexture(e,t){var i,n,s;let r=this.textures[e],o=-1;r?o=null!==(n=null===(i=r.texture)||void 0===i?void 0:i.uniqueId)&&void 0!==n?n:-1:this.textures[e]=r={texture:t,isFloatTexture:!1,isExternalTexture:!1},r.isExternalTexture&&this._numExternalTextures--,r.isFloatTexture&&this._numFloatTextures--,t?(r.isFloatTexture=1===t.type,r.isExternalTexture=pu.IsExternalTexture(t),r.isFloatTexture&&this._numFloatTextures++,r.isExternalTexture&&this._numExternalTextures++):(r.isFloatTexture=!1,r.isExternalTexture=!1),r.texture=t;const a=o!==(null!==(s=null==t?void 0:t.uniqueId)&&void 0!==s?s:-1);a&&this.updateId++,this.isDirty||(this.isDirty=a)}}fu._Counter=0;class _u{isDirty(e){return this._isDirty||this._materialContextUpdateId!==e}resetIsDirty(e){this._isDirty=!1,this._materialContextUpdateId=e}get useInstancing(){return this._useInstancing}set useInstancing(e){this._useInstancing!==e&&(e?(this.indirectDrawBuffer=this._bufferManager.createRawBuffer(20,Tc.CopyDst|Tc.Indirect|Tc.Storage),this._indirectDrawData=new Uint32Array(5),this._indirectDrawData[3]=0,this._indirectDrawData[4]=0):(this.indirectDrawBuffer&&this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this._useInstancing=e,this._currentInstanceCount=-1)}constructor(e){this._bufferManager=e,this.uniqueId=_u._Counter++,this._useInstancing=!1,this._currentInstanceCount=0,this.reset()}reset(){this.buffers={},this._isDirty=!0,this._materialContextUpdateId=0,this.fastBundle=void 0,this.bindGroups=void 0}setBuffer(e,t){var i;this._isDirty||(this._isDirty=(null==t?void 0:t.uniqueId)!==(null===(i=this.buffers[e])||void 0===i?void 0:i.uniqueId)),this.buffers[e]=t}setIndirectData(e,t,i){t!==this._currentInstanceCount&&this.indirectDrawBuffer&&this._indirectDrawData&&(this._currentInstanceCount=t,this._indirectDrawData[0]=e,this._indirectDrawData[1]=t,this._indirectDrawData[2]=i,this._bufferManager.setRawData(this.indirectDrawBuffer,0,this._indirectDrawData,0,20))}dispose(){this.indirectDrawBuffer&&(this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this.fastBundle=void 0,this.bindGroups=void 0,this.buffers=void 0}}_u._Counter=0;class mu{constructor(){this.values={}}}class gu{static get Statistics(){return{totalCreated:gu.NumBindGroupsCreatedTotal,lastFrameCreated:gu.NumBindGroupsCreatedLastFrame,lookupLastFrame:gu.NumBindGroupsLookupLastFrame,noLookupLastFrame:gu.NumBindGroupsNoLookupLastFrame}}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){gu.NumBindGroupsCreatedLastFrame=gu._NumBindGroupsCreatedCurrentFrame,gu.NumBindGroupsLookupLastFrame=gu._NumBindGroupsLookupCurrentFrame,gu.NumBindGroupsNoLookupLastFrame=gu._NumBindGroupsNoLookupCurrentFrame,gu._NumBindGroupsCreatedCurrentFrame=0,gu._NumBindGroupsLookupCurrentFrame=0,gu._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){var n,s,r,o,a,l,h,c,d,u;let f,_=gu._Cache;const m=this.disabled||i.forceBindGroupCreation;if(!m){if(!t.isDirty(i.updateId)&&!i.isDirty)return gu._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(const i of e.shaderProcessingContext.bufferNames){const e=null!==(s=null===(n=t.buffers[i])||void 0===n?void 0:n.uniqueId)&&void 0!==s?s:0;let r=_.values[e];r||(r=new mu,_.values[e]=r),_=r}for(const t of e.shaderProcessingContext.samplerNames){const e=null!==(o=null===(r=i.samplers[t])||void 0===r?void 0:r.hashCode)&&void 0!==o?o:0;let n=_.values[e];n||(n=new mu,_.values[e]=n),_=n}for(const t of e.shaderProcessingContext.textureNames){const e=null!==(h=null===(l=null===(a=i.textures[t])||void 0===a?void 0:a.texture)||void 0===l?void 0:l.uniqueId)&&void 0!==h?h:0;let n=_.values[e];n||(n=new mu,_.values[e]=n),_=n}f=_.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,f)return t.bindGroups=f,gu._NumBindGroupsLookupCurrentFrame++,f;f=[],t.bindGroups=f,m||(_.bindGroups=f),gu.NumBindGroupsCreatedTotal++,gu._NumBindGroupsCreatedCurrentFrame++;const g=e.bindGroupLayouts[i.textureState];for(let v=0;v"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}s[o].resource=this._cacheSampler.getSampler(t,!1,e.hashCode)}else p.Y.Error(`Sampler "${a}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.texture||n.storageTexture){const e=i.textures[a];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){p.Y.Error(`Trying to bind a null texture! entry=${JSON.stringify(n)}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const t=e.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!t||n.texture&&!t.view||n.storageTexture&&!t.viewForWriting)){p.Y.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(n)}, name=${a}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, isReady=${null===(d=e.texture)||void 0===d?void 0:d.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}s[o].resource=n.storageTexture?t.viewForWriting:t.view}else p.Y.Error(`Texture "${a}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.externalTexture){const e=i.textures[a];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){p.Y.Error(`Trying to bind a null external texture! entry=${JSON.stringify(n)}, name=${a}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const t=e.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!t){p.Y.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(n)}, name=${a}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, isReady=${null===(u=e.texture)||void 0===u?void 0:u.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}s[o].resource=this._device.importExternalTexture({source:t})}else p.Y.Error(`Texture "${a}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.buffer){const e=t.buffers[a];if(e){const t=e.underlyingResource;s[o].resource.buffer=t,s[o].resource.size=e.capacity}else p.Y.Error(`Can't find buffer "${a}". entry=${JSON.stringify(n)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}const r=g[v];f[v]=this._device.createBindGroup({layout:r,entries:s})}return f}}gu.NumBindGroupsCreatedTotal=0,gu.NumBindGroupsCreatedLastFrame=0,gu.NumBindGroupsLookupLastFrame=0,gu.NumBindGroupsNoLookupLastFrame=0,gu._Cache=new mu,gu._NumBindGroupsCreatedCurrentFrame=0,gu._NumBindGroupsLookupCurrentFrame=0,gu._NumBindGroupsNoLookupCurrentFrame=0;const vu="clearQuadVertexShader",Tu="uniform float depthValue;\nconst vec2 pos[4]={\nvec2(-1.0,1.0),\nvec2(1.0,1.0),\nvec2(-1.0,-1.0),\nvec2(1.0,-1.0)\n};\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\ngl_Position=vec4(pos[gl_VertexID],depthValue,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}\n";Ht.v.ShadersStore[vu]=Tu;const Su="clearQuadPixelShader",Eu="uniform vec4 color;\nvoid main() {\ngl_FragColor=color;\n}\n";Ht.v.ShadersStore[Su]=Eu;class xu{setDepthStencilFormat(e){this._depthTextureFormat=e,this._cacheRenderPipeline.setDepthStencilFormat(e)}setColorFormat(e){this._cacheRenderPipeline.setColorFormat(e)}setMRTAttachments(e,t,i){this._cacheRenderPipeline.setMRT(t,i),this._cacheRenderPipeline.setMRTAttachments(e)}constructor(e,t,i){this._bindGroups={},this._bundleCache={},this._keyTemp=[],this._device=e,this._engine=t,this._cacheRenderPipeline=new lu(this._device,i,!t._caps.textureFloatLinearFiltering),this._cacheRenderPipeline.setDepthTestEnabled(!1),this._cacheRenderPipeline.setStencilReadMask(255),this._effect=t.createEffect("clearQuad",[],["color","depthValue"])}clear(e,t,i,n,s=1){var r,o;let a,l,h=null;const c=!!this._engine._currentRenderTarget;if(e)a=e;else{let e=0;this._keyTemp.length=0;for(let t=0;t1?2**36:0)+d*2**37,l=this._keyTemp.join("_"),h=this._bundleCache[l],h)return h;a=this._device.createRenderBundleEncoder({colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:s})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!n&&!!this._depthTextureFormat&&qd.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(n?255:0),this._cacheRenderPipeline.setStencilCompare(n?519:512),this._cacheRenderPipeline.setStencilPassOp(n?7681:7680),this._cacheRenderPipeline.setWriteMask(t?15:0);const d=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,s),u=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),u.uniformBuffer.update();const p=c?this._engine._ubInvertY:this._engine._ubDontInvertY,f=u.uniformBuffer.getBuffer(),_=f.uniqueId+"-"+p.uniqueId;let m=this._bindGroups[_];if(!m){const e=u.bindGroupLayouts[0];m=this._bindGroups[_]=[],m.push(this._device.createBindGroup({layout:e[0],entries:[]})),rd._SimplifiedKnownBindings||m.push(this._device.createBindGroup({layout:e[1],entries:[]})),m.push(this._device.createBindGroup({layout:e[rd._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:p.underlyingResource,size:p.capacity}},{binding:1,resource:{buffer:f.underlyingResource,size:f.capacity}}]}))}a.setPipeline(d);for(let g=0;g{null!==e&&e>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(e,!0)),this._measureDurationState=0})))}}class Nu{constructor(e,t){this._querySet=new Ou(2,Zc.Timestamp,e,t)}start(e){e.writeTimestamp(this._querySet.querySet,0)}async stop(e){return e.writeTimestamp(this._querySet.querySet,1),this._querySet.readTwoValuesAndSubtract(0)}dispose(){this._querySet.dispose()}}class Fu{get querySet(){return this._querySet.querySet}get hasQueries(){return this._currentTotalIndices!==this._availableIndices.length}get canBeginQuery(){switch(this._engine._getCurrentRenderPassIndex()){case 0:return void 0!==this._engine._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet;case 1:return void 0!==this._engine._rttRenderPassWrapper.renderPassDescriptor.occlusionQuerySet}return!1}constructor(e,t,i,n=50,s=100){this._availableIndices=[],this._engine=e,this._device=t,this._bufferManager=i,this._frameLastBuffer=-1,this._currentTotalIndices=0,this._countIncrement=s,this._allocateNewIndices(n)}createQuery(){0===this._availableIndices.length&&this._allocateNewIndices();const e=this._availableIndices[this._availableIndices.length-1];return this._availableIndices.length--,e}deleteQuery(e){this._availableIndices[this._availableIndices.length-1]=e}isQueryResultAvailable(e){return this._retrieveQueryBuffer(),!!this._lastBuffer&&e{this._lastBuffer=e})))}_allocateNewIndices(e){e=null!=e?e:this._countIncrement,this._delayQuerySetDispose();for(let t=0;te.dispose),1e3)}dispose(){var e;null===(e=this._querySet)||void 0===e||e.dispose(),this._availableIndices.length=0}}class wu{async initTwgsl(e){if(!wu._twgsl)return e=e||{},(e=Object.assign(Object.assign({},wu._TWgslDefaultOptions),e)).twgsl?(wu._twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&((0,_e.CG)()?await se.w1.LoadScriptAsync(e.jsPath):importScripts(e.jsPath)),self.twgsl?(wu._twgsl=await self.twgsl(e.wasmPath),Promise.resolve()):Promise.reject("twgsl is not available."))}convertSpirV2WGSL(e,t=!1){const i=wu._twgsl.convertSpirV2WGSL(e);return wu.ShowWGSLShaderCode&&(console.log(i),console.log("***********************************************")),wu.DisableUniformityAnalysis||t?"diagnostic(off, derivative_uniformity);\n"+i:i}}wu._TWgslDefaultOptions={jsPath:"https://preview.babylonjs.com/twgsl/twgsl.js",wasmPath:"https://preview.babylonjs.com/twgsl/twgsl.wasm"},wu.ShowWGSLShaderCode=!1,wu.DisableUniformityAnalysis=!1,wu._twgsl=null;class Lu{constructor(e,t,i,n){this._record=!1,this._play=!1,this._mainPassBundleList=[],this._enabled=!1,this._engine=e,this._mode=t,this._bundleList=i,this._bundleListRenderTarget=n}get enabled(){return this._enabled}get play(){return this._play}get record(){return this._record}set enabled(e){this._mainPassBundleList.length=0,this._record=this._enabled=e,this._play=!1,e&&(this._modeSaved=this._mode,this._mode=0)}get mode(){return this._mode}set mode(e){this._record?this._modeSaved=e:this._mode=e}endMainRenderPass(){this._record&&this._mainPassBundleList.push(this._bundleList.clone())}endRenderTargetPass(e,t){var i,n,s,r;if(this._play)null===(n=null===(i=t._bundleLists)||void 0===i?void 0:i[t._currentLayer])||void 0===n||n.run(e),1===this._mode&&this._engine._reportDrawCall(null===(r=null===(s=t._bundleLists)||void 0===s?void 0:s[t._currentLayer])||void 0===r?void 0:r.numDrawCalls);else{if(!this._record)return!1;t._bundleLists||(t._bundleLists=[]),t._bundleLists[t._currentLayer]=this._bundleListRenderTarget.clone(),t._bundleLists[t._currentLayer].run(e),this._bundleListRenderTarget.reset()}return!0}endFrame(e){if(this._record&&(this._mainPassBundleList.push(this._bundleList.clone()),this._record=!1,this._play=!0,this._mode=this._modeSaved),null!==e&&this._play)for(let t=0;t!!e),(()=>!1)).catch((()=>!1)):Promise.resolve(!1)}static get IsSupported(){return p.Y.Warn("You must call IsSupportedAsync for WebGPU!"),!1}get supportsUniformBuffers(){return!0}get supportedExtensions(){return this._adapterSupportedExtensions}get enabledExtensions(){return this._deviceEnabledExtensions}get supportedLimits(){return this._adapterSupportedLimits}get currentLimits(){return this._deviceLimits}get description(){return this.name+this.version}get version(){return 1}getInfo(){return{vendor:this._adapterInfo.vendor||"unknown vendor",renderer:this._adapterInfo.architecture||"unknown renderer",version:this._adapterInfo.description||"unknown version"}}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=e}get currentSampleCount(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount}static CreateAsync(e,t={}){const i=new zu(e,t);return new Promise((e=>{i.initAsync(t.glslangOptions,t.twgslOptions).then((()=>e(i)))}))}constructor(e,t={}){var i,n;super(null,null===(i=t.antialias)||void 0===i||i,t),this._uploadEncoderDescriptor={label:"upload"},this._renderEncoderDescriptor={label:"render"},this._renderTargetEncoderDescriptor={label:"renderTarget"},this._clearDepthValue=1,this._clearReverseDepthValue=0,this._clearStencilValue=0,this._defaultSampleCount=4,this._glslang=null,this._tintWASM=null,this._adapterInfo={vendor:"",architecture:"",device:"",description:""},this._compiledComputeEffects={},this._counters={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.countersLastFrame={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.numMaxUncapturedErrors=20,this._commandBuffers=[null,null,null],this._currentRenderPass=null,this._mainRenderPassWrapper=new Zd,this._rttRenderPassWrapper=new Zd,this._pendingDebugCommands=[],this._onAfterUnbindFrameBufferObservable=new r.y$,this._currentOverrideVertexBuffers=null,this._currentIndexBuffer=null,this._colorWriteLocal=!0,this._forceEnableEffect=!1,this.dbgShowShaderCode=!1,this.dbgSanityChecks=!0,this.dbgVerboseLogsForFirstFrames=!1,this.dbgVerboseLogsNumFrames=10,this.dbgLogIfNotDrawWrapper=!0,this.dbgShowEmptyEnableEffectCalls=!0,this.isNDCHalfZRange=!0,this.hasOriginBottomLeft=!1,this._viewportsCurrent=[{x:0,y:0,w:0,h:0},{x:0,y:0,w:0,h:0}],this._scissorsCurrent=[{x:0,y:0,w:0,h:0},{x:0,y:0,w:0,h:0}],this._scissorCached={x:0,y:0,z:0,w:0},this._stencilRefsCurrent=[-1,-1],this._blendColorsCurrent=[[null,null,null,null],[null,null,null,null]],this._name="WebGPU",t.deviceDescriptor=t.deviceDescriptor||{},t.enableGPUDebugMarkers=null!==(n=t.enableGPUDebugMarkers)&&void 0!==n&&n,p.Y.Log(`Babylon.js v${fe.D.Version} - ${this.description} engine`),navigator.gpu?(t.swapChainFormat=t.swapChainFormat||navigator.gpu.getPreferredCanvasFormat(),this._isWebGPU=!0,this._shaderPlatformName="WEBGPU",this._renderingCanvas=e,this._options=t,this._mainPassSampleCount=t.antialias?this._defaultSampleCount:1,this._setupMobileChecks(),this._sharedInit(e),this._shaderProcessor=new od,this._shaderProcessorWGSL=new Gd):p.Y.Error("WebGPU is not supported by your browser.")}initAsync(e,t){var i;return this._initGlslang(null!=e?e:null===(i=this._options)||void 0===i?void 0:i.glslangOptions).then((e=>{var i;return this._glslang=e,this._tintWASM=zu.UseTWGSL?new wu:null,this._tintWASM?this._tintWASM.initTwgsl(null!=t?t:null===(i=this._options)||void 0===i?void 0:i.twgslOptions).then((()=>navigator.gpu.requestAdapter(this._options)),(e=>{throw p.Y.Error("Can not initialize twgsl!"),p.Y.Error(e),Error("WebGPU initializations stopped.")})):navigator.gpu.requestAdapter(this._options)}),(e=>{throw p.Y.Error("Can not initialize glslang!"),p.Y.Error(e),Error("WebGPU initializations stopped.")})).then((e=>{var t,i,n;if(e){this._adapter=e,this._adapterSupportedExtensions=[],null===(t=this._adapter.features)||void 0===t||t.forEach((e=>this._adapterSupportedExtensions.push(e))),this._adapterSupportedLimits=this._adapter.limits,this._adapter.requestAdapterInfo().then((e=>{this._adapterInfo=e}));const s=null!==(i=this._options.deviceDescriptor)&&void 0!==i?i:{},r=null!==(n=null==s?void 0:s.requiredFeatures)&&void 0!==n?n:this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0;if(r){const e=r,t=[];for(const i of e)-1!==this._adapterSupportedExtensions.indexOf(i)&&t.push(i);s.requiredFeatures=t}if(this._options.setMaximumLimits&&!s.requiredLimits){s.requiredLimits={};for(const e in this._adapterSupportedLimits)s.requiredLimits[e]=this._adapterSupportedLimits[e]}return this._adapter.requestDevice(s)}throw"Could not retrieve a WebGPU adapter (adapter is null)."})).then((e=>{var t,i;this._device=e,this._deviceEnabledExtensions=[],null===(t=this._device.features)||void 0===t||t.forEach((e=>this._deviceEnabledExtensions.push(e))),this._deviceLimits=e.limits;let n=-1;this._device.addEventListener("uncapturederror",(e=>{++n{this._isDisposed||(this._contextWasLost=!0,p.Y.Warn("WebGPU context lost. "+e),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost(this.initAsync.bind(this)))}))}),(e=>{p.Y.Error("Could not retrieve a WebGPU device."),p.Y.Error(e)})).then((()=>{this._bufferManager=new Qd(this._device),this._textureHelper=new qd(this._device,this._glslang,this._tintWASM,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new iu(this._device),this._cacheBindGroups=new gu(this._device,this._cacheSampler,this),this._timestampQuery=new Du(this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new Fu(this,this._device,this._bufferManager):void 0,this._bundleList=new Mu(this._device),this._bundleListRenderTarget=new Mu(this._device),this._snapshotRendering=new Lu(this,this._snapshotRenderingMode,this._bundleList,this._bundleListRenderTarget),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),Tc.Uniform|Tc.CopyDst),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),Tc.Uniform|Tc.CopyDst),this.dbgVerboseLogsForFirstFrames&&void 0===this._count&&(this._count=0,console.log("%c frame #"+this._count+" - begin","background: #ffff00")),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._renderTargetEncoder=this._device.createCommandEncoder(this._renderTargetEncoderDescriptor),this._emptyVertexBuffer=new ne.o(this,[0],"",!1,!1,1,!1,0,1),this._initializeLimits(),this._cacheRenderPipeline=new lu(this._device,this._emptyVertexBuffer,!this._caps.textureFloatLinearFiltering),this._depthCullingState=new uu(this._cacheRenderPipeline),this._stencilStateComposer=new cu(this._cacheRenderPipeline),this._stencilStateComposer.stencilGlobal=this._stencilState,this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=515,this._depthCullingState.depthMask=!0,this._textureHelper.setCommandEncoder(this._uploadEncoder),this._clearQuad=new xu(this._device,this,this._emptyVertexBuffer),this._defaultDrawContext=this.createDrawContext(),this._currentDrawContext=this._defaultDrawContext,this._defaultMaterialContext=this.createMaterialContext(),this._currentMaterialContext=this._defaultMaterialContext,this._initializeContextAndSwapChain(),this._initializeMainAttachments(),this.resize()})).catch((e=>{p.Y.Error("Can not create WebGPU Device and/or context."),p.Y.Error(e),console.trace&&console.trace()}))}_initGlslang(e){return e=e||{},(e=Object.assign(Object.assign({},zu._GLSLslangDefaultOptions),e)).glslang?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?(0,_e.CG)()?se.w1.LoadScriptAsync(e.jsPath).then((()=>self.glslang(e.wasmPath))):(importScripts(e.jsPath),self.glslang(e.wasmPath)):Promise.reject("gslang is not available.")}_initializeLimits(){this._caps={maxTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxVertexTextureImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxCombinedTexturesImageUnits:2*this._deviceLimits.maxSampledTexturesPerShaderStage,maxTextureSize:this._deviceLimits.maxTextureDimension2D,maxCubemapTextureSize:this._deviceLimits.maxTextureDimension2D,maxRenderTextureSize:this._deviceLimits.maxTextureDimension2D,maxVertexAttribs:this._deviceLimits.maxVertexAttributes,maxVaryingVectors:this._deviceLimits.maxInterStageShaderVariables,maxFragmentUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),maxVertexUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),standardDerivatives:!0,astc:this._deviceEnabledExtensions.indexOf(gc.TextureCompressionASTC)>=0||void 0,s3tc:this._deviceEnabledExtensions.indexOf(gc.TextureCompressionBC)>=0||void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf(gc.TextureCompressionETC2)>=0||void 0,bptc:this._deviceEnabledExtensions.indexOf(gc.TextureCompressionBC)>=0||void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf(gc.Float32Filterable)>=0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!0,drawBuffersExtension:!0,depthTextureExtension:!0,vertexArrayObject:!1,instancedArrays:!0,timerQuery:"undefined"!=typeof BigUint64Array&&-1!==this._deviceEnabledExtensions.indexOf(gc.TimestampQuery)||void 0,supportOcclusionQuery:"undefined"!=typeof BigUint64Array,canUseTimestampForTimerQuery:!0,multiview:!1,oculusMultiview:!1,parallelShaderCompile:void 0,blendMinMax:!0,maxMSAASamples:4,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!0,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!0,texture2DArrayMaxLayerCount:this._deviceLimits.maxTextureArrayLayers,disableMorphTargetTexture:!1},this._caps.parallelShaderCompile=null,this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!0,supportDepthStencilTexture:!0,supportShadowSamplers:!0,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!0,trackUbosInFrame:!0,checkUbosContentBeforeUpload:!0,supportCSM:!0,basisNeedsPOT:!1,support3DTextures:!0,needTypeSuffixInShaderConstants:!0,supportMSAA:!0,supportSSAO2:!0,supportExtendedTextureFormats:!0,supportSwitchCaseInShader:!0,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!0,supportRenderPasses:!0,supportSpriteInstancing:!0,_collectUbosUpdatedInFrame:!1}}_initializeContextAndSwapChain(){if(!this._renderingCanvas)throw"The rendering canvas has not been set!";this._context=this._renderingCanvas.getContext("webgpu"),this._configureContext(),this._colorFormat=this._options.swapChainFormat,this._mainRenderPassWrapper.colorAttachmentGPUTextures=[new zd],this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format=this._colorFormat}_initializeMainAttachments(){if(!this._bufferManager)return;this.flushFramebuffer(!1),this._mainTextureExtends={width:this.getRenderWidth(!0),height:this.getRenderHeight(!0),depthOrArrayLayers:1};const e=new Float32Array([this.getRenderHeight(!0)]);let t;if(this._bufferManager.setSubData(this._ubInvertY,4,e),this._bufferManager.setSubData(this._ubDontInvertY,4,e),this._options.antialias){const e={label:`Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:Ec.E2d,format:this._options.swapChainFormat,usage:xc.RenderAttachment};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(e),t=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:Ec.E2d,format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new a.HE(0,0,0,1),loadOp:$c.Clear,storeOp:Qc.Store}]}else t=[{view:void 0,clearValue:new a.HE(0,0,0,1),loadOp:$c.Clear,storeOp:Qc.Store}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?yc.Depth24PlusStencil8:yc.Depth32Float,this._setDepthTextureFormat(this._mainRenderPassWrapper);const i={label:`Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:Ec.E2d,format:this._mainRenderPassWrapper.depthTextureFormat,usage:xc.RenderAttachment};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(i);const n={view:this._depthTexture.createView({label:`TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,dimension:Ec.E2d,format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:$c.Clear,depthStoreOp:Qc.Store,stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?$c.Clear:void 0,stencilStoreOp:this.isStencilEnable?Qc.Store:void 0};this._mainRenderPassWrapper.renderPassDescriptor={colorAttachments:t,depthStencilAttachment:n}}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:xc.RenderAttachment|xc.CopySrc,alphaMode:this.premultipliedAlpha?Jc.Premultiplied:Jc.Opaque})}setSize(e,t,i=!1){return!!super.setSize(e,t,i)&&(this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count=0,s=t.indexOf(Gu)>=0,r=i===Qt.x.GLSL?this._compileRawShaderToSpirV(e,"vertex"):e,o=i===Qt.x.GLSL?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(r,o,i,n,s)}_compilePipelineStageDescriptor(e,t,i,n){this.onBeforeShaderCompilationObservable.notifyObservers(this);const s=e.indexOf(Gu)>=0,r=t.indexOf(Gu)>=0,o="#version 450\n",a=n===Qt.x.GLSL?this._compileShaderToSpirV(e,"vertex",i,o):this._getWGSLShader(e,"vertex",i),l=n===Qt.x.GLSL?this._compileShaderToSpirV(t,"fragment",i,o):this._getWGSLShader(t,"fragment",i),h=this._createPipelineStageDescriptor(a,l,n,s,r);return this.onAfterShaderCompilationObservable.notifyObservers(this),h}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){const t=new oc(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new nd(e,this)}createMaterialContext(){return new fu}createDrawContext(){return new _u(this._bufferManager)}_preparePipelineContext(e,t,i,n,s,r,o,a){const l=e,h=l.shaderProcessingContext.shaderLanguage;this.dbgShowShaderCode&&(console.log(a),console.log(t),console.log(i),console.log("***********************************************")),l.sources={fragment:i,vertex:t,rawVertex:s,rawFragment:r},l.stages=n?this._compileRawPipelineStageDescriptor(t,i,h):this._compilePipelineStageDescriptor(t,i,a,h)}getAttributes(e,t){const i=new Array(t.length),n=e;for(let s=0;s0,l._cachedWrapU=0,l._cachedWrapV=0,l._useSRGBBuffer=a.useSRGBBuffer,l.label=a.label,this._internalTexturesCache.push(l),i||this._textureHelper.createGPUTextureForInternalTexture(l,h,c,d||1,a.creationFlags),l}createTexture(e,t,i,n,s=3,r=null,o=null,a=null,l=null,h=null,c=null,d,u,p,f){return this._createTextureBase(e,t,i,n,s,r,o,((e,t,i,n,s,r,o,a)=>{var l;const c=n;if(e.baseWidth=c.width,e.baseHeight=c.height,e.width=c.width,e.height=c.height,e.format=null!=h?h:-1,a(e.width,e.height,c,t,e,(()=>{})),null===(l=e._hardwareTexture)||void 0===l?void 0:l.underlyingResource)r||o||this._generateMipmaps(e,this._uploadEncoder);else{const t=this._textureHelper.createGPUTextureForInternalTexture(e,c.width,c.height,void 0,p);qd.IsImageBitmap(c)&&(this._textureHelper.updateTexture(c,e,c.width,c.height,e.depth,t.format,0,0,s,!1,0,0),r||o||this._generateMipmaps(e,this._uploadEncoder))}i&&i.removePendingData(e),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}),(()=>!1),a,l,h,c,d,u,f)}wrapWebGPUTexture(e){const t=new zd(e),i=new Be.l(this,Be.S.Unknown,!0);return i._hardwareTexture=t,i.isReady=!0,i}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.")}generateMipMapsForCubemap(e){var t;if(e.generateMipMaps){(null===(t=e._hardwareTexture)||void 0===t?void 0:t.underlyingResource)||this._textureHelper.createGPUTextureForInternalTexture(e),this._generateMipmaps(e,e.source===Be.S.RenderTarget||e.source===Be.S.MultiRenderTarget?this._renderTargetEncoder:void 0)}}updateTextureSamplingMode(e,t,i=!1){i&&(t.generateMipMaps=!0,this._generateMipmaps(t)),t.samplingMode=e}updateTextureWrappingMode(e,t,i=null,n=null){null!==t&&(e._cachedWrapU=t),null!==i&&(e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==n&&(e._cachedWrapR=n)}updateTextureDimensions(e,t,i,n=1){if(!e._hardwareTexture)return;if(e.width===t&&e.height===i&&e.depth===n)return;const s=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,n,s)}_setInternalTexture(e,t,i){if(i=null!=i?i:e,this._currentEffect){const n=this._currentEffect._pipelineContext.shaderProcessingContext.availableTextures[i];if(this._currentMaterialContext.setTexture(e,t),n&&n.autoBindSampler){const e=i+id.AutoSamplerSuffix;this._currentMaterialContext.setSampler(e,t)}}}setTexture(e,t,i,n){this._setTexture(e,i,!1,!1,n,n)}setTextureArray(e,t,i,n){for(let s=0;s0;for(const t in e){const s=e[t],r=i[t],o=r.group,a=r.binding,l=s.type,h=s.object;let c=s.indexInGroupEntries,d=this._bindGroupEntries[o];switch(d||(d=this._bindGroupEntries[o]=[]),l){case Qa.Sampler:{const e=h;void 0!==c&&n?d[c].resource=this._cacheSampler.getSampler(e):(s.indexInGroupEntries=d.length,d.push({binding:a,resource:this._cacheSampler.getSampler(e)}));break}case Qa.Texture:case Qa.TextureWithoutSampler:{const e=h,t=e._texture._hardwareTexture;void 0!==c&&n?(l===Qa.Texture&&(d[c++].resource=this._cacheSampler.getSampler(e._texture)),d[c].resource=t.view):(s.indexInGroupEntries=d.length,l===Qa.Texture&&d.push({binding:a-1,resource:this._cacheSampler.getSampler(e._texture)}),d.push({binding:a,resource:t.view}));break}case Qa.StorageTexture:{const e=h,t=e._texture._hardwareTexture;0==(t.textureAdditionalUsages&xc.StorageBinding)&&p.Y.Error(`computeDispatch: The texture (name=${e.name}, uniqueId=${e.uniqueId}) is not a storage texture!`,50),void 0!==c&&n?d[c].resource=t.viewForWriting:(s.indexInGroupEntries=d.length,d.push({binding:a,resource:t.viewForWriting}));break}case Qa.UniformBuffer:case Qa.StorageBuffer:{const e=(Qa.UniformBuffer,h).getBuffer(),t=e.underlyingResource;void 0!==c&&n?(d[c].resource.buffer=t,d[c].resource.size=e.capacity):(s.indexInGroupEntries=d.length,d.push({binding:a,resource:{buffer:t,offset:0,size:e.capacity}}));break}}}for(let e=0;e{this.computeDispatch(e,t,i,n,s,r,o)}));const a=e._pipelineContext,l=t;a.computePipeline||(a.computePipeline=this._device.createComputePipeline({layout:Bc.Auto,compute:a.stage}));const h=this._renderTargetEncoder.beginComputePass();h.setPipeline(a.computePipeline);const c=l.getBindGroups(i,a.computePipeline,o);for(let d=0;d{const i=t,r=i[0].width,a=r;this._setCubeMapTextureParams(e,!n),e.format=null!=o?o:-1;const l=this._textureHelper.createGPUTextureForInternalTexture(e,r,a);this._textureHelper.updateCubeTextures(i,l.underlyingResource,r,a,l.format,!1,!1,0,0),n||this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),s&&s()}),!!u)},zu.prototype._setCubeMapTextureParams=function(e,t,i){e.samplingMode=t?3:2,e._cachedWrapU=0,e._cachedWrapV=0,i&&(e._maxLodLevel=i)},zu.prototype._debugPushGroup=function(e,t){if(this._options.enableGPUDebugMarkers)if(0===t||1===t){(0===t?this._renderEncoder:this._renderTargetEncoder).pushDebugGroup(e)}else this._currentRenderPass?this._currentRenderPass.pushDebugGroup(e):this._pendingDebugCommands.push(["push",e])},zu.prototype._debugPopGroup=function(e){if(this._options.enableGPUDebugMarkers)if(0===e||1===e){(0===e?this._renderEncoder:this._renderTargetEncoder).popDebugGroup()}else this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null])},zu.prototype._debugInsertMarker=function(e,t){if(this._options.enableGPUDebugMarkers)if(0===t||1===t){(0===t?this._renderEncoder:this._renderTargetEncoder).insertDebugMarker(e)}else this._currentRenderPass?this._currentRenderPass.insertDebugMarker(e):this._pendingDebugCommands.push(["insert",e])},zu.prototype._debugFlushPendingCommands=function(){for(let e=0;e{const i=u.width,r=o(e);if(!r)return;const h=[0,2,4,1,3,5];if(a){const e=4===n,t=a(r),o=u._hardwareTexture,l=[0,1,2,3,4,5];for(let n=0;n>n,a=[];for(let i=0;i<6;i++){let o=t[n][l[i]];e&&(o=Yu(o,r,r,s)),a.push(new Uint8Array(o.buffer,o.byteOffset,o.byteLength))}this._textureHelper.updateCubeTextures(a,o.underlyingResource,r,r,o.format,d,!1,0,0)}}else{const e=[];for(let t=0;t<6;t++)e.push(r[h[t]]);this.updateRawCubeTexture(u,e,n,s,d)}u.isReady=!0,null==t||t.removePendingData(u),l&&l()};return this._loadFile(e,(e=>{p(e)}),void 0,null==t?void 0:t.offlineProvider,!0,((e,i)=>{null==t||t.removePendingData(u),h&&e&&h(e.status+" "+e.statusText,i)})),u},zu.prototype.createRawTexture3D=function(e,t,i,n,s,r,o,a,l=null,h=0,c=0){const d=Be.S.Raw3D,u=new Be.l(this,d);return u.baseWidth=t,u.baseHeight=i,u.baseDepth=n,u.width=t,u.height=i,u.depth=n,u.format=s,u.type=h,u.generateMipMaps=r,u.samplingMode=a,u.is3D=!0,this._doNotHandleContextLost||(u._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(u,t,i,void 0,c),this.updateRawTexture3D(u,e,s,o,l,h),this._internalTexturesCache.push(u),u},zu.prototype.updateRawTexture3D=function(e,t,i,n,s=null,r=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=n,e._compression=s),t){const s=e._hardwareTexture;4===i&&(t=Yu(t,e.width,e.height,r));const o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,s.format,0,0,n,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},zu.prototype.createRawTexture2DArray=function(e,t,i,n,s,r,o,a,l=null,h=0,c=0){const d=Be.S.Raw2DArray,u=new Be.l(this,d);return u.baseWidth=t,u.baseHeight=i,u.baseDepth=n,u.width=t,u.height=i,u.depth=n,u.format=s,u.type=h,u.generateMipMaps=r,u.samplingMode=a,u.is2DArray=!0,this._doNotHandleContextLost||(u._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(u,t,i,n,c),this.updateRawTexture2DArray(u,e,s,o,l,h),this._internalTexturesCache.push(u),u},zu.prototype.updateRawTexture2DArray=function(e,t,i,n,s=null,r=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=n,e._compression=s),t){const s=e._hardwareTexture;4===i&&(t=Yu(t,e.width,e.height,r));const o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,s.format,0,0,n,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},zu.prototype._readTexturePixels=function(e,t,i,n=-1,s=0,r=null,o=!0,a=!1,l=0,h=0){const c=e._hardwareTexture;return o&&this.flushFramebuffer(),this._textureHelper.readPixels(c.underlyingResource,l,h,t,i,c.format,n,s,r,a)},zu.prototype._readTexturePixelsSync=function(){throw"_readTexturePixelsSync is unsupported in WebGPU!"};class ju extends jt{}zu.prototype._createHardwareRenderTargetWrapper=function(e,t,i){const n=new ju(e,t,i,this);return this._renderTargetWrapperCache.push(n),n},zu.prototype.createRenderTargetTexture=function(e,t){var i,n;const s=this._createHardwareRenderTargetWrapper(!1,!1,e),r={};void 0!==t&&"object"==typeof t?(r.generateMipMaps=t.generateMipMaps,r.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,r.generateStencilBuffer=r.generateDepthBuffer&&t.generateStencilBuffer,r.samplingMode=void 0===t.samplingMode?3:t.samplingMode,r.creationFlags=null!==(i=t.creationFlags)&&void 0!==i?i:0,r.noColorAttachment=!!t.noColorAttachment,r.samples=t.samples,r.label=t.label):(r.generateMipMaps=t,r.generateDepthBuffer=!0,r.generateStencilBuffer=!1,r.samplingMode=3,r.creationFlags=0,r.noColorAttachment=!1);const o=r.noColorAttachment?null:this._createInternalTexture(e,t,!0,Be.S.RenderTarget);return s._samples=null!==(n=r.samples)&&void 0!==n?n:1,s._generateDepthBuffer=r.generateDepthBuffer,s._generateStencilBuffer=!!r.generateStencilBuffer,s.setTextures(o),(s._generateDepthBuffer||s._generateStencilBuffer)&&s.createDepthStencilTexture(0,this._caps.textureFloatLinearFiltering&&(void 0===r.samplingMode||2===r.samplingMode||2===r.samplingMode||3===r.samplingMode||3===r.samplingMode||5===r.samplingMode||6===r.samplingMode||7===r.samplingMode||11===r.samplingMode),s._generateStencilBuffer,s.samples,r.generateStencilBuffer?13:14,r.label?r.label+"-DepthStencil":void 0),o&&(void 0!==t&&"object"==typeof t&&t.createMipMaps&&!r.generateMipMaps&&(o.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(o,void 0,void 0,void 0,r.creationFlags),void 0!==t&&"object"==typeof t&&t.createMipMaps&&!r.generateMipMaps&&(o.generateMipMaps=!1)),s},zu.prototype._createDepthStencilTexture=function(e,t){const i=new Be.l(this,Be.S.DepthStencil);i.label=t.label;const n=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?13:14},t);return i.format=n.depthTextureFormat,this._setupDepthStencilTexture(i,e,n.generateStencil,n.bilinearFiltering,n.comparisonFunction,n.samples),this._textureHelper.createGPUTextureForInternalTexture(i),this._internalTexturesCache.push(i),i},zu.prototype._setupDepthStencilTexture=function(e,t,i,n,s,r=1){const o=t.width||t,a=t.height||t,l=t.layers||0;e.baseWidth=o,e.baseHeight=a,e.width=o,e.height=a,e.is2DArray=l>0,e.depth=l,e.isReady=!0,e.samples=r,e.generateMipMaps=!1,e.samplingMode=n?2:1,e.type=1,e._comparisonFunction=s,e._cachedWrapU=0,e._cachedWrapV=0},zu.prototype.updateRenderTargetTextureSampleCount=function(e,t){return e&&e.texture&&e.samples!==t?(t=Math.min(t,this.getCaps().maxMSAASamples),this._textureHelper.createMSAATexture(e.texture,t),e._depthStencilTexture&&(this._textureHelper.createMSAATexture(e._depthStencilTexture,t),e._depthStencilTexture.samples=t),e._samples=t,e.texture.samples=t,t):t},zu.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),n=Object.assign({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1},t);n.generateStencilBuffer=n.generateDepthBuffer&&n.generateStencilBuffer,i._generateDepthBuffer=n.generateDepthBuffer,i._generateStencilBuffer=n.generateStencilBuffer;const s=new Be.l(this,Be.S.RenderTarget);return s.width=e,s.height=e,s.depth=0,s.isReady=!0,s.isCube=!0,s.samples=n.samples,s.generateMipMaps=n.generateMipMaps,s.samplingMode=n.samplingMode,s.type=n.type,s.format=n.format,this._internalTexturesCache.push(s),i.setTextures(s),(i._generateDepthBuffer||i._generateStencilBuffer)&&i.createDepthStencilTexture(0,void 0===n.samplingMode||2===n.samplingMode||2===n.samplingMode||3===n.samplingMode||3===n.samplingMode||5===n.samplingMode||6===n.samplingMode||7===n.samplingMode||11===n.samplingMode,i._generateStencilBuffer,i.samples),t&&t.createMipMaps&&!n.generateMipMaps&&(s.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(s),t&&t.createMipMaps&&!n.generateMipMaps&&(s.generateMipMaps=!1),i},ft.Q.prototype.setTextureSampler=function(e,t){this._engine.setTextureSampler(e,t)},zu.prototype.setTextureSampler=function(e,t){var i;null===(i=this._currentMaterialContext)||void 0===i||i.setSampler(e,t)},ft.Q.prototype.setStorageBuffer=function(e,t){this._engine.setStorageBuffer(e,t)},zu.prototype.createStorageBuffer=function(e,t){return this._createBuffer(e,32|t)},zu.prototype.updateStorageBuffer=function(e,t,i,n){const s=e;let r;void 0===i&&(i=0),void 0===n?(r=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,n=r.byteLength):r=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,this._bufferManager.setSubData(s,i,r,0,n)},zu.prototype.readFromStorageBuffer=function(e,t,i,n){i=i||e.capacity;const s=this._bufferManager.createRawBuffer(i,Tc.MapRead|Tc.CopyDst);return this._renderTargetEncoder.copyBufferToBuffer(e.underlyingResource,null!=t?t:0,s,0,i),new Promise(((e,t)=>{this.onEndFrameObservable.addOnce((()=>{s.mapAsync(Sc.Read,0,i).then((()=>{const t=s.getMappedRange(0,i);let r=n;if(void 0===r)r=new Uint8Array(i),r.set(new Uint8Array(t));else{const e=r.constructor;r=new e(r.buffer),r.set(new e(t))}s.unmap(),this._bufferManager.releaseBuffer(s),e(r)}),(e=>t(e)))}))}))},zu.prototype.setStorageBuffer=function(e,t){var i,n;null===(i=this._currentDrawContext)||void 0===i||i.setBuffer(e,null!==(n=null==t?void 0:t.getBuffer())&&void 0!==n?n:null)},zu.prototype.createUniformBuffer=function(e){let t;t=e instanceof Array?new Float32Array(e):e;return this._bufferManager.createBuffer(t,Tc.Uniform|Tc.CopyDst)},zu.prototype.createDynamicUniformBuffer=function(e){return this.createUniformBuffer(e)},zu.prototype.updateUniformBuffer=function(e,t,i,n){void 0===i&&(i=0);const s=e;let r;void 0===n?(r=t instanceof Float32Array?t:new Float32Array(t),n=r.byteLength):r=t instanceof Float32Array?t:new Float32Array(t),this._bufferManager.setSubData(s,i,r,0,n)},zu.prototype.bindUniformBufferBase=function(e,t,i){this._currentDrawContext.setBuffer(i,e)},zu.prototype.bindUniformBlock=function(){},zu.prototype.updateVideoTexture=function(e,t,i){var n;if(!e||e._isDisabled)return;void 0===this._videoTextureSupported&&(this._videoTextureSupported=!0);let s=e._hardwareTexture;(null===(n=e._hardwareTexture)||void 0===n?void 0:n.underlyingResource)||(s=this._textureHelper.createGPUTextureForInternalTexture(e)),!function(e){return!(!e||void 0===e.underlyingResource)}(t)?t&&this.createImageBitmap(t).then((t=>{this._textureHelper.updateTexture(t,e,e.width,e.height,e.depth,s.format,0,0,!i,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0})).catch((()=>{e.isReady=!0})):(this._textureHelper.copyVideoToTexture(t,e,s.format,!i),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0)};i(1917);class Ku{}Ku.COPY=1,Ku.CUT=2,Ku.PASTE=3;class qu extends Fs{constructor(e){super(e),this.controllerType=yn.DAYDREAM}initControllerMesh(e,t){ht.ImportMesh("",qu.MODEL_BASE_URL,qu.MODEL_FILENAME,e,(e=>{this._defaultModel=e[1],this.attachToMesh(this._defaultModel),t&&t(this._defaultModel)}))}_handleButtonChange(e,t){if(0===e){const e=this.onTriggerStateChangedObservable;e&&e.notifyObservers(t)}else p.Y.Warn(`Unrecognized Daydream button index: ${e}`)}}qu.MODEL_BASE_URL="https://controllers.babylonjs.com/generic/",qu.MODEL_FILENAME="generic.babylon",qu.GAMEPAD_ID_PREFIX="Daydream",Wn._ControllerFactories.push({canCreate:e=>0===e.id.indexOf(qu.GAMEPAD_ID_PREFIX),create:e=>new qu(e)});class $u extends Fs{constructor(e){super(e),this._buttonIndexToObservableNameMap=["onPadStateChangedObservable","onTriggerStateChangedObservable"],this.controllerType=yn.GEAR_VR,this._calculatedPosition=new o.P("left"==this.hand?-.15:.15,-.5,.25),this._disableTrackPosition(this._calculatedPosition)}initControllerMesh(e,t){ht.ImportMesh("",$u.MODEL_BASE_URL,$u.MODEL_FILENAME,e,(i=>{const n=new ee.Kj("",e);i[1].parent=n,i[1].position.z=-.15,this._defaultModel=n,this.attachToMesh(this._defaultModel),t&&t(this._defaultModel)}))}_handleButtonChange(e,t){if(e0===e.id.indexOf($u.GAMEPAD_ID_PREFIX)||-1!==e.id.indexOf("Oculus Go")||-1!==e.id.indexOf("Vive Focus"),create:e=>new $u(e)});class Qu extends Fs{constructor(e){super(e)}initControllerMesh(e,t){ht.ImportMesh("",Qu.MODEL_BASE_URL,Qu.MODEL_FILENAME,e,(e=>{this._defaultModel=e[1],this.attachToMesh(this._defaultModel),t&&t(this._defaultModel)}))}_handleButtonChange(e,t){console.log("Button id: "+e+"state: "),console.dir(t)}}Qu.MODEL_BASE_URL="https://controllers.babylonjs.com/generic/",Qu.MODEL_FILENAME="generic.babylon",Wn._DefaultControllerFactory=e=>new Qu(e);class Zu extends Fs{constructor(e){super(e),this.onSecondaryTriggerStateChangedObservable=new r.y$,this.onThumbRestChangedObservable=new r.y$,this.controllerType=yn.OCULUS}initControllerMesh(e,t){let i;i="left"===this.hand?Zu.MODEL_LEFT_FILENAME:Zu.MODEL_RIGHT_FILENAME,ht.ImportMesh("",Zu._IsQuest?Zu.QUEST_MODEL_BASE_URL:Zu.MODEL_BASE_URL,i,e,(e=>{this._defaultModel=Zu._IsQuest?e[0]:e[1],this.attachToMesh(this._defaultModel),t&&t(this._defaultModel)}))}get onAButtonStateChangedObservable(){if("right"===this.hand)return this.onMainButtonStateChangedObservable;throw new Error("No A button on left hand")}get onBButtonStateChangedObservable(){if("right"===this.hand)return this.onSecondaryButtonStateChangedObservable;throw new Error("No B button on left hand")}get onXButtonStateChangedObservable(){if("left"===this.hand)return this.onMainButtonStateChangedObservable;throw new Error("No X button on right hand")}get onYButtonStateChangedObservable(){if("left"===this.hand)return this.onSecondaryButtonStateChangedObservable;throw new Error("No Y button on right hand")}_handleButtonChange(e,t){const i=t,n="right"===this.hand?-1:1;switch(e){case 0:return void this.onPadStateChangedObservable.notifyObservers(i);case 1:return!Zu._IsQuest&&this._defaultModel&&(this._defaultModel.getChildren()[3].rotation.x=.2*-i.value,this._defaultModel.getChildren()[3].position.y=.005*-i.value,this._defaultModel.getChildren()[3].position.z=.005*-i.value),void this.onTriggerStateChangedObservable.notifyObservers(i);case 2:return!Zu._IsQuest&&this._defaultModel&&(this._defaultModel.getChildren()[4].position.x=n*i.value*.0035),void this.onSecondaryTriggerStateChangedObservable.notifyObservers(i);case 3:return!Zu._IsQuest&&this._defaultModel&&(i.pressed?this._defaultModel.getChildren()[1].position.y=-.001:this._defaultModel.getChildren()[1].position.y=0),void this.onMainButtonStateChangedObservable.notifyObservers(i);case 4:return!Zu._IsQuest&&this._defaultModel&&(i.pressed?this._defaultModel.getChildren()[2].position.y=-.001:this._defaultModel.getChildren()[2].position.y=0),void this.onSecondaryButtonStateChangedObservable.notifyObservers(i);case 5:return void this.onThumbRestChangedObservable.notifyObservers(i)}}}Zu.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/",Zu.MODEL_LEFT_FILENAME="left.babylon",Zu.MODEL_RIGHT_FILENAME="right.babylon",Zu.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/",Zu._IsQuest=!1,Wn._ControllerFactories.push({canCreate:e=>(m.l.LastCreatedEngine&&m.l.LastCreatedEngine._vrDisplay&&"Oculus Quest"===m.l.LastCreatedEngine._vrDisplay.displayName&&(Zu._IsQuest=!0),-1!==e.id.indexOf("Oculus Touch")),create:e=>new Zu(e)});class Ju extends Fs{constructor(e){super(e),this.controllerType=yn.VIVE,this._invertLeftStickY=!0}initControllerMesh(e,t){ht.ImportMesh("",Ju.MODEL_BASE_URL,Ju.MODEL_FILENAME,e,(e=>{this._defaultModel=e[1],this.attachToMesh(this._defaultModel),t&&t(this._defaultModel)}))}get onLeftButtonStateChangedObservable(){return this.onMainButtonStateChangedObservable}get onRightButtonStateChangedObservable(){return this.onMainButtonStateChangedObservable}get onMenuButtonStateChangedObservable(){return this.onSecondaryButtonStateChangedObservable}_handleButtonChange(e,t){const i=t;switch(e){case 0:return void this.onPadStateChangedObservable.notifyObservers(i);case 1:return this._defaultModel&&(this._defaultModel.getChildren()[6].rotation.x=.15*-i.value),void this.onTriggerStateChangedObservable.notifyObservers(i);case 2:return void this.onMainButtonStateChangedObservable.notifyObservers(i);case 3:return this._defaultModel&&(i.pressed?this._defaultModel.getChildren()[2].position.y=-.001:this._defaultModel.getChildren()[2].position.y=0),void this.onSecondaryButtonStateChangedObservable.notifyObservers(i)}}}Ju.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/",Ju.MODEL_FILENAME="wand.babylon",Wn._ControllerFactories.push({canCreate:e=>-1!==e.id.toLowerCase().indexOf("openvr"),create:e=>new Ju(e)});class ep{constructor(){this.buttonMeshes={},this.axisMeshes={}}}class tp extends Fs{constructor(e){super(e),this._mapping={buttons:["thumbstick","trigger","grip","menu","trackpad"],buttonMeshNames:{trigger:"SELECT",menu:"MENU",grip:"GRASP",thumbstick:"THUMBSTICK_PRESS",trackpad:"TOUCHPAD_PRESS"},buttonObservableNames:{trigger:"onTriggerStateChangedObservable",menu:"onSecondaryButtonStateChangedObservable",grip:"onMainButtonStateChangedObservable",thumbstick:"onPadStateChangedObservable",trackpad:"onTrackpadChangedObservable"},axisMeshNames:["THUMBSTICK_X","THUMBSTICK_Y","TOUCHPAD_TOUCH_X","TOUCHPAD_TOUCH_Y"],pointingPoseMeshName:Hn.POINTING_POSE},this.onTrackpadChangedObservable=new r.y$,this.onTrackpadValuesChangedObservable=new r.y$,this.trackpad={x:0,y:0},this.controllerType=yn.WINDOWS,this._loadedMeshInfo=null}get onTriggerButtonStateChangedObservable(){return this.onTriggerStateChangedObservable}get onMenuButtonStateChangedObservable(){return this.onSecondaryButtonStateChangedObservable}get onGripButtonStateChangedObservable(){return this.onMainButtonStateChangedObservable}get onThumbstickButtonStateChangedObservable(){return this.onPadStateChangedObservable}get onTouchpadButtonStateChangedObservable(){return this.onTrackpadChangedObservable}get onTouchpadValuesChangedObservable(){return this.onTrackpadValuesChangedObservable}_updateTrackpad(){!this.browserGamepad.axes||this.browserGamepad.axes[2]==this.trackpad.x&&this.browserGamepad.axes[3]==this.trackpad.y||(this.trackpad.x=this.browserGamepad.axes[this._mapping.axisMeshNames.indexOf("TOUCHPAD_TOUCH_X")],this.trackpad.y=this.browserGamepad.axes[this._mapping.axisMeshNames.indexOf("TOUCHPAD_TOUCH_Y")],this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad))}update(){if(super.update(),this.browserGamepad.axes&&(this._updateTrackpad(),this._loadedMeshInfo))for(let e=0;e{this._loadedMeshInfo=this._processModel(e,i),this._loadedMeshInfo&&(this._defaultModel=this._loadedMeshInfo.rootNode,this.attachToMesh(this._defaultModel),t&&t(this._defaultModel))}),null,((e,r)=>{p.Y.Log(r),p.Y.Warn("Failed to retrieve controller model from the remote server: "+n+s),i||this.initControllerMesh(e,t,!0)}))}_processModel(e,t){let i=null;const n=new ee.Kj(this.id+" "+this.hand,e);let s=null;for(let r=0;re.name===t),!1)[0]}function s(e,t){return e.getChildren((e=>e.name==t),!0)[0]}}getForwardRay(e=100){if(!this._loadedMeshInfo||!this._loadedMeshInfo.pointingPoseNode)return super.getForwardRay(e);const t=this._loadedMeshInfo.pointingPoseNode.getWorldMatrix(),i=t.getTranslation(),n=new o.P(0,0,-1),s=o.P.TransformNormal(n,t),r=o.P.Normalize(s);return new qe(i,r,e)}dispose(){super.dispose(),this.onTrackpadChangedObservable.clear(),this.onTrackpadValuesChangedObservable.clear()}}tp.MODEL_BASE_URL="https://controllers.babylonjs.com/microsoft/",tp.MODEL_LEFT_FILENAME="left.glb",tp.MODEL_RIGHT_FILENAME="right.glb",tp.GAMEPAD_ID_PREFIX="Spatial Controller (Spatial Interaction Source) ",tp.GAMEPAD_ID_PATTERN=/([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;Wn._ControllerFactories.push({canCreate:e=>0===e.id.indexOf(tp.GAMEPAD_ID_PREFIX),create:e=>new tp(e)});class ip extends ul{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}constructor(e,t=a.Wo.Gray(),i=dl.DefaultUtilityLayer,n=32,s=null,l=!1,h=1){var c;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new r.y$,this.angle=0,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._angles=new o.P,this._parent=s,this._coloredMaterial=new _a("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new a.Wo(.1,.1,.1)),this._hoverMaterial=new _a("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=a.Wo.Yellow(),this._disableMaterial=new _a("",i.utilityLayerScene),this._disableMaterial.diffuseColor=a.Wo.Gray(),this._disableMaterial.alpha=.4,this._gizmoMesh=new ee.Kj("",i.utilityLayerScene);const{rotationMesh:d,collider:u}=this._createGizmoMesh(this._gizmoMesh,h,n);this._rotationDisplayPlane=Je("rotationDisplay",{size:.6,updatable:!1},this.gizmoLayer.utilityLayerScene),this._rotationDisplayPlane.rotation.z=.5*Math.PI,this._rotationDisplayPlane.parent=this._gizmoMesh,this._rotationDisplayPlane.setEnabled(!1),ft.Q.ShadersStore.rotationGizmoVertexShader=ip._RotationGizmoVertexShader,ft.Q.ShadersStore.rotationGizmoFragmentShader=ip._RotationGizmoFragmentShader,this._rotationShaderMaterial=new Il("shader",this.gizmoLayer.utilityLayerScene,{vertex:"rotationGizmo",fragment:"rotationGizmo"},{attributes:["position","uv"],uniforms:["worldViewProjection","angles"]}),this._rotationShaderMaterial.backFaceCulling=!1,this._rotationDisplayPlane.material=this._rotationShaderMaterial,this._rotationDisplayPlane.visibility=.999,this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,ul.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3),this.dragBehavior=new et({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.maxDragAngle=ip.MaxDragAngle,this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,this._rootMesh.addBehavior(this.dragBehavior);const f=new o.P,_=new o.y3,m=new o.P;let g=new o.P;this.dragBehavior.onDragStartObservable.add((e=>{this.attachedNode&&(f.copyFrom(e.dragPlanePoint),this._rotationDisplayPlane.setEnabled(!0),this._rotationDisplayPlane.getWorldMatrix().invertToRef(_),o.P.TransformCoordinatesToRef(e.dragPlanePoint,_,f),this._angles.x=Math.atan2(f.y,f.x)+Math.PI,this._angles.y=0,this._angles.z=this.updateGizmoRotationToMatchAttachedMesh?1:0,this._dragging=!0,f.copyFrom(e.dragPlanePoint),this._rotationShaderMaterial.setVector3("angles",this._angles),this.angle=0)})),this.dragBehavior.onDragEndObservable.add((()=>{this._dragging=!1,this._rotationDisplayPlane.setEnabled(!1)}));const v={snapDistance:0};let T=0;const S=new o.y3,E=new o._f;this.dragBehavior.onDragObservable.add((t=>{if(this.attachedNode){const n=new o.P(1,1,1),s=new o._f(0,0,0,1),r=new o.P(0,0,0);this._handlePivot(),this.attachedNode.getWorldMatrix().decompose(n,s,r);if(!(Math.abs(Math.abs(n.x)-Math.abs(n.y))<=k.kn&&Math.abs(Math.abs(n.x)-Math.abs(n.z))<=k.kn)&&this.updateGizmoRotationToMatchAttachedMesh)return void p.Y.Warn("Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false.");s.normalize();const a=this.updateGizmoPositionToMatchAttachedMesh?r:this._rootMesh.absolutePosition,l=t.dragPlanePoint.subtract(a).normalize(),h=f.subtract(a).normalize(),c=o.P.Cross(l,h),d=o.P.Dot(l,h);let u=Math.atan2(c.length(),d);m.copyFrom(e),g.copyFrom(e),this.updateGizmoRotationToMatchAttachedMesh&&(s.toRotationMatrix(_),g=o.P.TransformCoordinates(m,_));let x=!1;if(i.utilityLayerScene.activeCamera){const e=i.utilityLayerScene.activeCamera.position.subtract(a).normalize();o.P.Dot(e,g)>0&&(m.scaleInPlace(-1),g.scaleInPlace(-1),x=!0)}o.P.Dot(g,c)>0&&(u=-u);let b=!1;if(0!=this.snapDistance)if(T+=u,Math.abs(T)>this.snapDistance){let e=Math.floor(Math.abs(T)/this.snapDistance);T<0&&(e*=-1),T%=this.snapDistance,u=this.snapDistance*e,b=!0}else u=0;const C=Math.sin(u/2);if(E.set(m.x*C,m.y*C,m.z*C,Math.cos(u/2)),S.determinant()>0){const e=new o.P;E.toEulerAnglesToRef(e),o._f.RotationYawPitchRollToRef(e.y,-e.x,-e.z,E)}if(this.updateGizmoRotationToMatchAttachedMesh)s.multiplyToRef(E,s),o.y3.ComposeToRef(n,s,r,this.attachedNode.getWorldMatrix());else{E.toRotationMatrix(o.jp.Matrix[0]);const e=this.attachedNode.getWorldMatrix().getTranslation();this.attachedNode.getWorldMatrix().multiplyToRef(o.jp.Matrix[0],this.attachedNode.getWorldMatrix()),this.attachedNode.getWorldMatrix().setTranslation(e)}f.copyFrom(t.dragPlanePoint),b&&(v.snapDistance=u,this.onSnapObservable.notifyObservers(v)),this._angles.y+=u,this.angle+=x?-u:u,this._rotationShaderMaterial.setVector3("angles",this._angles),this._matrixChanged()}}));const x=i._getSharedGizmoLight();x.includedOnlyMeshes=x.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const b={colliderMeshes:[u],gizmoMeshes:[d],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};null===(c=this._parent)||void 0===c||c.addToAxisCache(this._gizmoMesh,b),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{var t;if(!this._customMeshSet&&(this.dragBehavior.maxDragAngle=ip.MaxDragAngle,this._isHovered=!(-1==b.colliderMeshes.indexOf(null===(t=null==e?void 0:e.pickInfo)||void 0===t?void 0:t.pickedMesh)),!this._parent)){const e=b.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(b.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(b.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}))}_createGizmoMesh(e,t,i){const n=La("ignore",{diameter:.6,thickness:.03*t,tessellation:i},this.gizmoLayer.utilityLayerScene);n.visibility=0;const s=La("",{diameter:.6,thickness:.005*t,tessellation:i},this.gizmoLayer.utilityLayerScene);return s.material=this._coloredMaterial,s.rotation.x=Math.PI/2,n.rotation.x=Math.PI/2,e.addChild(s,ul.PreserveScaling),e.addChild(n,ul.PreserveScaling),{rotationMesh:s,collider:n}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),this._rotationDisplayPlane&&this._rotationDisplayPlane.dispose(),this._rotationShaderMaterial&&this._rotationShaderMaterial.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}}ip.MaxDragAngle=9*Math.PI/20,ip._RotationGizmoVertexShader="\n precision highp float;\n attribute vec3 position;\n attribute vec2 uv;\n uniform mat4 worldViewProjection;\n varying vec3 vPosition;\n varying vec2 vUV;\n void main(void) {\n gl_Position = worldViewProjection * vec4(position, 1.0);\n vUV = uv;\n }",ip._RotationGizmoFragmentShader="\n precision highp float;\n varying vec2 vUV;\n varying vec3 vPosition;\n uniform vec3 angles;\n #define twopi 6.283185307\n void main(void) {\n vec2 uv = vUV - vec2(0.5);\n float angle = atan(uv.y, uv.x) + 3.141592;\n float delta = gl_FrontFacing ? angles.y : -angles.y;\n float begin = angles.x - delta * angles.z;\n float start = (begin < (begin + delta)) ? begin : (begin + delta);\n float end = (begin > (begin + delta)) ? begin : (begin + delta);\n float len = sqrt(dot(uv,uv));\n float opacity = 1. - step(0.5, len);\n\n float base = abs(floor(start / twopi)) * twopi;\n start += base;\n end += base;\n\n float intensity = 0.;\n for (int i = 0; i < 5; i++)\n {\n intensity += max(step(start, angle) - step(end, angle), 0.);\n angle += twopi;\n }\n gl_FragColor = vec4(1.,1.,0., min(intensity * 0.25, 0.8)) * opacity;\n }";class np extends he{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0}_setPosition(e){this._position=e}get position(){return this._position}set position(e){this._setPosition(e)}_setDirection(e){this._direction=e}get direction(){return this._direction}set direction(e){this._setDirection(e)}get shadowMinZ(){return this._shadowMinZ}set shadowMinZ(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()}get shadowMaxZ(){return this._shadowMaxZ}set shadowMaxZ(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()}computeTransformedInformation(){return!(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition||(this.transformedPosition=o.P.Zero()),o.P.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=o.P.Zero()),o.P.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=o.P.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=o.P.Cross(this.direction,L.RD.Y),t=o.P.Cross(e,this.direction);return o.P.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=o.P.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=o.y3.Identity()),o.y3.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)}}(0,oe.gn)([(0,E.hd)()],np.prototype,"position",null),(0,oe.gn)([(0,E.hd)()],np.prototype,"direction",null),(0,oe.gn)([(0,E.qC)()],np.prototype,"shadowMinZ",null),(0,oe.gn)([(0,E.qC)()],np.prototype,"shadowMaxZ",null),b.N.AddNodeConstructor("Light_Type_1",((e,t)=>()=>new sp(e,o.P.Zero(),t)));class sp extends np{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 he.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&&o.y3.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=o.P.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE;let n=Number.MAX_VALUE,s=Number.MIN_VALUE;for(let r=0;rthis._orthoRight&&(this._orthoRight=e.x),e.y>this._orthoTop&&(this._orthoTop=e.y),this.autoCalcShadowZBounds&&(e.zs&&(s=e.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=n,this._shadowMaxZ=s)}const s=this._orthoRight-this._orthoLeft,r=this._orthoTop-this._orthoBottom,a=void 0!==this.shadowMinZ?this.shadowMinZ:n.minZ,l=void 0!==this.shadowMaxZ?this.shadowMaxZ:n.maxZ,h=this.getScene().getEngine().useReverseDepthBuffer;o.y3.OrthoOffCenterLHToRef(this._orthoLeft-s*this.shadowOrthoScale,this._orthoRight+s*this.shadowOrthoScale,this._orthoBottom-r*this.shadowOrthoScale,this._orthoTop+r*this.shadowOrthoScale,h?l:a,h?a:l,e,this.getScene().getEngine().isNDCHalfZRange)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?(e.setFloat3(t,this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z),this):(e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this)}getDepthMinZ(e){const t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){const t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}}function rp(e,t={},i){t.diameter||(t.diameter=1),t.segments||(t.segments=16);const n=gl("",{slice:.5,diameter:t.diameter,segments:t.segments},i),s=bl("",{radius:t.diameter/2,tessellation:3*t.segments+(4-t.segments)},i);s.rotation.x=-Math.PI/2,s.parent=n;const r=ee.Kj.MergeMeshes([s,n],!0);return r.name=e,r}(0,oe.gn)([(0,E.qC)()],sp.prototype,"shadowFrustumSize",null),(0,oe.gn)([(0,E.qC)()],sp.prototype,"shadowOrthoScale",null),(0,oe.gn)([(0,E.qC)()],sp.prototype,"autoUpdateExtends",void 0),(0,oe.gn)([(0,E.qC)()],sp.prototype,"autoCalcShadowZBounds",void 0),(0,oe.gn)([(0,E.qC)("orthoLeft")],sp.prototype,"_orthoLeft",void 0),(0,oe.gn)([(0,E.qC)("orthoRight")],sp.prototype,"_orthoRight",void 0),(0,oe.gn)([(0,E.qC)("orthoTop")],sp.prototype,"_orthoTop",void 0),(0,oe.gn)([(0,E.qC)("orthoBottom")],sp.prototype,"_orthoBottom",void 0);ee.Kj.CreateHemisphere=(e,t,i,n)=>rp(e,{segments:t,diameter:i},n),b.N.AddNodeConstructor("Light_Type_2",((e,t)=>()=>new op(e,o.P.Zero(),o.P.Zero(),0,0,t)));class op extends np{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()&&(op._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled((()=>{this._markMeshesAsLightDirty()})):op._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,s,r){super(e,r),this._innerAngle=0,this._projectionTextureMatrix=o.y3.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=o.P.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=o.P.Zero(),this._projectionTextureViewLightMatrix=o.y3.Zero(),this._projectionTextureProjectionLightMatrix=o.y3.Zero(),this._projectionTextureScalingMatrix=o.y3.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),this.position=t,this.direction=i,this.angle=n,this.exponent=s}getClassName(){return"SpotLight"}getTypeID(){return he.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){const n=this.getScene().activeCamera;if(!n)return;this._shadowAngleScale=this._shadowAngleScale||1;const s=this._shadowAngleScale*this._angle,r=void 0!==this.shadowMinZ?this.shadowMinZ:n.minZ,a=void 0!==this.shadowMaxZ?this.shadowMaxZ:n.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;o.y3.PerspectiveFovLHToRef(s,1,l?a:r,l?r:a,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,l)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.position.addToRef(this.direction,this._projectionTextureViewTargetVector),o.y3.LookAtLHToRef(this.position,this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;const e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),n=-i*t,s=1/Math.tan(this._angle/2);o.y3.FromValuesToRef(s/1,0,0,0,0,s,0,0,0,0,i,1,0,0,n,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof Le){const e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;o.y3.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("projectionLightSampler"+t,this.projectionTexture)),this}transferToEffect(e,t){let i;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,t),i=o.P.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=o.P.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()?o.P.Normalize(this.transformedDirection):o.P.Normalize(this.direction),this.getScene().useRightHandedSystem?e.setFloat3(t,-i.x,-i.y,-i.z):e.setFloat3(t,i.x,i.y,i.z),this}dispose(){super.dispose(),this._projectionTexture&&this._projectionTexture.dispose()}getDepthMinZ(e){const t=this._scene.getEngine(),i=void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?i:this._scene.getEngine().isNDCHalfZRange?0:i}getDepthMaxZ(e){const t=this._scene.getEngine(),i=void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:i}prepareLightSpecificDefines(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!(!this.projectionTexture||!this.projectionTexture.isReady())}}(0,oe.gn)([(0,E.qC)()],op.prototype,"angle",null),(0,oe.gn)([(0,E.qC)()],op.prototype,"innerAngle",null),(0,oe.gn)([(0,E.qC)()],op.prototype,"shadowAngleScale",null),(0,oe.gn)([(0,E.qC)()],op.prototype,"exponent",void 0),(0,oe.gn)([(0,E.qC)()],op.prototype,"projectionTextureLightNear",null),(0,oe.gn)([(0,E.qC)()],op.prototype,"projectionTextureLightFar",null),(0,oe.gn)([(0,E.qC)()],op.prototype,"projectionTextureUpDirection",null),(0,oe.gn)([(0,E.oU)("projectedLightTexture")],op.prototype,"_projectionTexture",void 0);class ap extends ul{constructor(e=dl.DefaultUtilityLayer){super(e),this._cachedPosition=new o.P,this._cachedForward=new o.P(0,0,1),this._pointerObserver=null,this.onClickedObservable=new r.y$,this._light=null,this.attachedMesh=new ie.x("",this.gizmoLayer.utilityLayerScene),this._attachedMeshParent=new te.Y("parent",this.gizmoLayer.utilityLayerScene),this.attachedMesh.parent=this._attachedMeshParent,this._material=new _a("light",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new a.Wo(.5,.5,.5),this._material.specularColor=new a.Wo(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add((e=>{this._light&&(this._isHovered=!(!e.pickInfo||-1==this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._light))}),We.kD.POINTERDOWN)}get attachedNode(){return this.attachedMesh}set attachedNode(e){console.warn("Nodes cannot be attached to LightGizmo. Attach to a mesh instead.")}set light(e){if(this._light=e,e){this._lightMesh&&this._lightMesh.dispose(),this._lightMesh=e instanceof Os?ap._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof sp?ap._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof op?ap._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene):ap._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene),this._lightMesh.getChildMeshes(!1).forEach((e=>{e.material=this._material})),this._lightMesh.parent=this._rootMesh;const t=this.gizmoLayer._getSharedGizmoLight();t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(!1)),this._lightMesh.rotationQuaternion=new o._f,this.attachedMesh.reservedDataStore||(this.attachedMesh.reservedDataStore={}),this.attachedMesh.reservedDataStore.lightGizmo=this,e.parent&&this._attachedMeshParent.freezeWorldMatrix(e.parent.getWorldMatrix()),e.position&&(this.attachedMesh.position.copyFrom(e.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position)),e.direction&&(this.attachedMesh.setDirection(e.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(this.attachedMesh.forward)),this._update()}}get light(){return this._light}get material(){return this._material}_update(){if(super._update(),this._light){if(this._light.parent&&this._attachedMeshParent.freezeWorldMatrix(this._light.parent.getWorldMatrix()),this._light.position)if(this.attachedMesh.position.equals(this._cachedPosition))this.attachedMesh.position.copyFrom(this._light.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position);else{const e=this.attachedMesh.position;this._light.position=new o.P(e.x,e.y,e.z),this._cachedPosition.copyFrom(this.attachedMesh.position)}if(this._light.direction)if(o.P.DistanceSquared(this.attachedMesh.forward,this._cachedForward)>1e-4){const e=this.attachedMesh.forward;this._light.direction=new o.P(e.x,e.y,e.z),this._cachedForward.copyFrom(this.attachedMesh.forward)}else o.P.DistanceSquared(this.attachedMesh.forward,this._light.direction)>1e-4&&(this.attachedMesh.setDirection(this._light.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(this.attachedMesh.forward))}}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._material.dispose(),super.dispose(),this._attachedMeshParent.dispose()}static _CreateHemisphericLightMesh(e){const t=new ee.Kj("hemisphereLight",e),i=rp(t.name,{segments:10,diameter:1},e);i.position.z=-.15,i.rotation.x=Math.PI/2,i.parent=t;return this._CreateLightLines(3,e).parent=t,t.scaling.scaleInPlace(ap._Scale),t.rotation.x=Math.PI/2,t}static _CreatePointLightMesh(e){const t=new ee.Kj("pointLight",e),i=gl(t.name,{segments:10,diameter:1},e);i.rotation.x=Math.PI/2,i.parent=t;return this._CreateLightLines(5,e).parent=t,t.scaling.scaleInPlace(ap._Scale),t.rotation.x=Math.PI/2,t}static _CreateSpotLightMesh(e){const t=new ee.Kj("spotLight",e);gl(t.name,{segments:10,diameter:1},e).parent=t;const i=rp(t.name,{segments:10,diameter:2},e);i.parent=t,i.rotation.x=-Math.PI/2;return this._CreateLightLines(2,e).parent=t,t.scaling.scaleInPlace(ap._Scale),t.rotation.x=Math.PI/2,t}static _CreateDirectionalLightMesh(e){const t=new ee.Kj("directionalLight",e),i=new ee.Kj(t.name,e);i.parent=t;gl(t.name,{diameter:1.2,segments:10},e).parent=i;const n=Fa(t.name,{updatable:!1,height:6,diameterTop:.3,diameterBottom:.3,tessellation:6,subdivisions:1},e);n.parent=i;let s=n.clone(t.name);s.scaling.y=.5,s.position.x+=1.25;let r=n.clone(t.name);r.scaling.y=.5,r.position.x+=-1.25;const o=Fa(t.name,{updatable:!1,height:1,diameterTop:0,diameterBottom:.6,tessellation:6,subdivisions:1},e);return o.position.y+=3,o.parent=i,s=o.clone(t.name),s.position.y=1.5,s.position.x+=1.25,r=o.clone(t.name),r.position.y=1.5,r.position.x+=-1.25,i.scaling.scaleInPlace(ap._Scale),i.rotation.z=Math.PI/2,i.rotation.y=Math.PI/2,t}}ap._Scale=.007,ap._CreateLightLines=(e,t)=>{const i=new ee.Kj("root",t);i.rotation.x=Math.PI/2;const n=new ee.Kj("linePivot",t);n.parent=i;const s=Fa("line",{updatable:!1,height:2,diameterTop:.2,diameterBottom:.3,tessellation:6,subdivisions:1},t);if(s.position.y=s.scaling.y/2+1.2,s.parent=n,e<2)return n;for(let r=0;r<4;r++){const e=n.clone("lineParentClone");e.rotation.z=Math.PI/4,e.rotation.y=Math.PI/2+Math.PI/2*r,e.getChildMeshes()[0].scaling.y=.5,e.getChildMeshes()[0].scaling.x=e.getChildMeshes()[0].scaling.z=.8,e.getChildMeshes()[0].position.y=e.getChildMeshes()[0].scaling.y/2+1.2}if(e<3)return i;for(let r=0;r<4;r++){const e=n.clone("linePivotClone");e.rotation.z=Math.PI/2,e.rotation.y=Math.PI/2*r}if(e<4)return i;for(let r=0;r<4;r++){const e=n.clone("linePivotClone");e.rotation.z=Math.PI+Math.PI/4,e.rotation.y=Math.PI/2+Math.PI/2*r,e.getChildMeshes()[0].scaling.y=.5,e.getChildMeshes()[0].scaling.x=e.getChildMeshes()[0].scaling.z=.8,e.getChildMeshes()[0].position.y=e.getChildMeshes()[0].scaling.y/2+1.2}if(e<5)return i;return n.clone("linePivotClone").rotation.z=Math.PI,i};class lp extends ul{constructor(e=dl.DefaultUtilityLayer){super(e),this._pointerObserver=null,this.onClickedObservable=new r.y$,this._camera=null,this._invProjection=new o.y3,this._material=new _a("cameraGizmoMaterial",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new a.Wo(.5,.5,.5),this._material.specularColor=new a.Wo(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add((e=>{this._camera&&(this._isHovered=!(!e.pickInfo||-1==this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._camera))}),We.kD.POINTERDOWN)}get displayFrustum(){return this._cameraLinesMesh.isEnabled()}set displayFrustum(e){this._cameraLinesMesh.setEnabled(e)}set camera(e){if(this._camera=e,this.attachedNode=e,e){this._cameraMesh&&this._cameraMesh.dispose(),this._cameraLinesMesh&&this._cameraLinesMesh.dispose(),this._cameraMesh=lp._CreateCameraMesh(this.gizmoLayer.utilityLayerScene),this._cameraLinesMesh=lp._CreateCameraFrustum(this.gizmoLayer.utilityLayerScene),this._cameraMesh.getChildMeshes(!1).forEach((e=>{e.material=this._material})),this._cameraMesh.parent=this._rootMesh,this._cameraLinesMesh.parent=this._rootMesh,this.gizmoLayer.utilityLayerScene.activeCamera&&this.gizmoLayer.utilityLayerScene.activeCamera.maxZ<1.5*e.maxZ&&(this.gizmoLayer.utilityLayerScene.activeCamera.maxZ=1.5*e.maxZ),this.attachedNode.reservedDataStore||(this.attachedNode.reservedDataStore={}),this.attachedNode.reservedDataStore.cameraGizmo=this;const t=this.gizmoLayer._getSharedGizmoLight();t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._cameraMesh.getChildMeshes(!1)),this._update()}}get camera(){return this._camera}get material(){return this._material}_update(){super._update(),this._camera&&(this._camera.getProjectionMatrix().invertToRef(this._invProjection),this._cameraLinesMesh.setPivotMatrix(this._invProjection,!1),this._cameraLinesMesh.scaling.x=1/this._rootMesh.scaling.x,this._cameraLinesMesh.scaling.y=1/this._rootMesh.scaling.y,this._cameraLinesMesh.scaling.z=1/this._rootMesh.scaling.z,this._cameraMesh.parent=null,this._cameraMesh.rotation.y=.5*Math.PI*(this._camera.getScene().useRightHandedSystem?1:-1),this._cameraMesh.parent=this._rootMesh)}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._cameraMesh&&this._cameraMesh.dispose(),this._cameraLinesMesh&&this._cameraLinesMesh.dispose(),this._material.dispose(),super.dispose()}static _CreateCameraMesh(e){const t=new ee.Kj("rootCameraGizmo",e),i=new ee.Kj(t.name,e);i.parent=t;_l(t.name,{width:1,height:.8,depth:.5},e).parent=i;const n=Fa(t.name,{height:.5,diameterTop:.8,diameterBottom:.8},e);n.parent=i,n.position.y=.3,n.position.x=-.6,n.rotation.x=.5*Math.PI;const s=Fa(t.name,{height:.5,diameterTop:.6,diameterBottom:.6},e);s.parent=i,s.position.y=.5,s.position.x=.4,s.rotation.x=.5*Math.PI;const r=Fa(t.name,{height:.5,diameterTop:.5,diameterBottom:.5},e);return r.parent=i,r.position.y=0,r.position.x=.6,r.rotation.z=.5*Math.PI,t.scaling.scaleInPlace(lp._Scale),i.position.x=-.9,t}static _CreateCameraFrustum(e){const t=new ee.Kj("rootCameraGizmo",e),i=new ee.Kj(t.name,e);i.parent=t;for(let n=0;n<4;n+=2)for(let t=0;t<4;t+=2){let s=Vl("lines",{points:[new o.P(-1+t,-1+n,-1),new o.P(-1+t,-1+n,1)]},e);s.parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1,s=Vl("lines",{points:[new o.P(-1,-1+t,-1+n),new o.P(1,-1+t,-1+n)]},e),s.parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1,s=Vl("lines",{points:[new o.P(-1+t,-1,-1+n),new o.P(-1+t,1,-1+n)]},e),s.parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1}return t}}lp._Scale=.05;const hp="kernelBlurVaryingDeclaration",cp="varying vec2 sampleCoord{X};";Ht.v.IncludesShadersStore[hp]=cp;const dp="packingFunctions",up="vec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}";Ht.v.IncludesShadersStore[dp]=up;const pp="kernelBlurFragment",fp="#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif\n";Ht.v.IncludesShadersStore[pp]=fp;const _p="kernelBlurFragment2",mp="#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif\n";Ht.v.IncludesShadersStore[_p]=mp;const gp="kernelBlurPixelShader",vp="uniform sampler2D textureSampler;\nuniform vec2 delta;\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nfloat sampleCoC(in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r;\nreturn coc; \n}\n#endif\n#include[0..varyingCount]\n#ifdef PACKEDFLOAT\n#include\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT\nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include[0..varyingCount]\n#include[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}";Ht.v.ShadersStore[gp]=vp;const Tp="kernelBlurVertex",Sp="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";Ht.v.IncludesShadersStore[Tp]=Sp;const Ep="kernelBlurVertexShader",xp="attribute vec2 position;\nuniform vec2 delta;\nvarying vec2 sampleCenter;\n#include[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nsampleCenter=(position*madd+madd);\n#include[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";Ht.v.ShadersStore[Ep]=xp;class bp extends Zt{set kernel(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this._blockCompilation||this._updateParameters())}get kernel(){return this._idealKernel}set packedFloat(e){this._packedFloat!==e&&(this._packedFloat=e,this._blockCompilation||this._updateParameters())}get packedFloat(){return this._packedFloat}getClassName(){return"BlurPostProcess"}constructor(e,t,i,n,s,r=Le.BILINEAR_SAMPLINGMODE,o,a,l=0,h="",c=!1,d=5){super(e,"kernelBlur",["delta","direction"],["circleOfConfusionSampler"],n,s,r,o,a,null,l,"kernelBlur",{varyingCount:0,depCount:0},!0,d),this._blockCompilation=c,this._packedFloat=!1,this._staticDefines="",this._staticDefines=h,this.direction=t,this.onApplyObservable.add((e=>{this._outputTexture?e.setFloat2("delta",1/this._outputTexture.width*this.direction.x,1/this._outputTexture.height*this.direction.y):e.setFloat2("delta",1/this.width*this.direction.x,1/this.height*this.direction.y)})),this.kernel=i}updateEffect(e=null,t=null,i=null,n,s,r){this._updateParameters(s,r)}_updateParameters(e,t){const i=this._kernel,n=(i-1)/2;let s=[],r=[],o=0;for(let _=0;_0)return Math.max(i,3);return Math.max(t,3)}_gaussianWeight(e){const t=1/3,i=-e*e/(2*t*t);return 1/(Math.sqrt(2*Math.PI)*t)*Math.exp(i)}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}static _Parse(e,t,i,n){return E.p4.Parse((()=>new bp(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1)),e,i,n)}}(0,oe.gn)([(0,E.qC)("kernel")],bp.prototype,"_kernel",void 0),(0,oe.gn)([(0,E.qC)("packedFloat")],bp.prototype,"_packedFloat",void 0),(0,oe.gn)([(0,E.QC)()],bp.prototype,"direction",void 0),(0,l.H)("BABYLON.BlurPostProcess",bp);class Cp extends Ci{set blurRatio(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())}get blurRatio(){return this._blurRatio}set adaptiveBlurKernel(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()}set blurKernel(e){this.blurKernelX=e,this.blurKernelY=e}set blurKernelX(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())}get blurKernelX(){return this._blurKernelX}set blurKernelY(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())}get blurKernelY(){return this._blurKernelY}_autoComputeBlurKernel(){const e=this.getScene().getEngine(),t=this.getRenderWidth()/e.getRenderWidth(),i=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*t,this.blurKernelY=this._adaptiveBlurKernel*i}_onRatioRescale(){this._sizeRatio&&(this.resize(this._initialSizeParameter),this._adaptiveBlurKernel||this._preparePostProcesses()),this._adaptiveBlurKernel&&this._autoComputeBlurKernel()}_updateGammaSpace(){const e=this.getScene();e&&(this.gammaSpace=!e.imageProcessingConfiguration.isEnabled||!e.imageProcessingConfiguration.applyByPostProcess)}constructor(e,t,i,n,s=0,r=Le.BILINEAR_SAMPLINGMODE,a=!0){if(super(e,t,i,n,!0,s,!1,r,a),this.mirrorPlane=new Me.J(0,1,0,1),this._transformMatrix=o.y3.Zero(),this._mirrorMatrix=o.y3.Zero(),this._adaptiveBlurKernel=0,this._blurKernelX=0,this._blurKernelY=0,this._blurRatio=1,!(i=this.getScene()))return this;this.ignoreCameraViewport=!0,this._updateGammaSpace(),this._imageProcessingConfigChangeObserver=i.imageProcessingConfiguration.onUpdateParameters.add((()=>{this._updateGammaSpace()}));const l=i.getEngine();let h;l.supportsUniformBuffers&&(this._sceneUBO=i.createSceneUniformBuffer(`Scene for Mirror Texture (name "${e}")`)),this.onBeforeBindObservable.add((()=>{var t;null===(t=l._debugPushGroup)||void 0===t||t.call(l,`mirror generation for ${e}`,1)})),this.onAfterUnbindObservable.add((()=>{var e;null===(e=l._debugPopGroup)||void 0===e||e.call(l,1)})),this.onBeforeRenderObservable.add((()=>{this._sceneUBO&&(this._currentSceneUBO=i.getSceneUniformBuffer(),i.setSceneUniformBuffer(this._sceneUBO),i.getSceneUniformBuffer().unbindEffect()),o.y3.ReflectionToRef(this.mirrorPlane,this._mirrorMatrix),this._mirrorMatrix.multiplyToRef(i.getViewMatrix(),this._transformMatrix),i.setTransformMatrix(this._transformMatrix,i.getProjectionMatrix()),h=i.clipPlane,i.clipPlane=this.mirrorPlane,i._mirroredCameraPosition=o.P.TransformCoordinates(i.activeCamera.globalPosition,this._mirrorMatrix)})),this.onAfterRenderObservable.add((()=>{this._sceneUBO&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(),i._mirroredCameraPosition=null,i.clipPlane=h}))}_preparePostProcesses(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){const e=this.getScene().getEngine(),t=e.getCaps().textureFloatRender&&e.getCaps().textureFloatLinearFiltering?1:2;this._blurX=new bp("horizontal blur",new o.FM(1,0),this._blurKernelX,this._blurRatio,null,Le.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurX.autoClear=!1,1===this._blurRatio&&this.samples<2&&this._texture?this._blurX.inputTexture=this._renderTarget:this._blurX.alwaysForcePOT=!0,this._blurY=new bp("vertical blur",new o.FM(0,1),this._blurKernelY,this._blurRatio,null,Le.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=1!==this._blurRatio,this.addPostProcess(this._blurX),this.addPostProcess(this._blurY)}else this._blurY&&(this.removePostProcess(this._blurY),this._blurY.dispose(),this._blurY=null),this._blurX&&(this.removePostProcess(this._blurX),this._blurX.dispose(),this._blurX=null)}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new Cp(this.name,t.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i}serialize(){if(!this.name)return null;const e=super.serialize();return e.mirrorPlane=this.mirrorPlane.asArray(),e}dispose(){var e;super.dispose();const t=this.getScene();t&&t.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),null===(e=this._sceneUBO)||void 0===e||e.dispose()}}Le._CreateMirror=(e,t,i,n)=>new Cp(e,t,i,n);class yp extends Re{set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(o.y3.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 yp(n,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,n=!0){const s=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;const r=new yp(e,t,null,!1,null,null,null,void 0,!0,i,n);return t.useDelayedTextureLoading=s,r}constructor(e,t,i=null,n=!1,s=null,a=null,l=null,h=5,c=!1,d=null,u=!1,p=.8,f=0,_,m){var g;super(t),this._lodScale=.8,this._lodOffset=0,this.onLoadObservable=new r.y$,this.boundingBoxPosition=o.P.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new o.y3,this.name=e,this.url=e,this._noMipmap=n,this.hasAlpha=!1,this._format=h,this.isCube=!0,this._textureMatrix=o.y3.Identity(),this._createPolynomials=u,this.coordinatesMode=Le.CUBIC_MODE,this._extensions=i,this._files=s,this._forcedExtension=d,this._loaderOptions=_,this._useSRGBBuffer=m,this._lodScale=p,this._lodOffset=f,(e||s)&&this.updateURL(e,d,a,c,l,i,null===(g=this.getScene())||void 0===g?void 0:g.useDelayedTextureLoading,s)}getClassName(){return"CubeTexture"}updateURL(e,t,i=null,n=!1,s=null,r=null,o=!1,a=null){this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,t&&(this._forcedExtension=t);const l=e.lastIndexOf("."),h=t||(l>-1?e.substring(l).toLowerCase():""),c=0===h.indexOf(".dds"),d=0===h.indexOf(".env"),u=0===h.indexOf(".basis");if(d?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=n,n&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),a)this._files=a;else if(u||d||c||r||(r=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),this._files=this._files||[],this._files.length=0,r){for(let t=0;t-1!==e.getActiveTextures().indexOf(this)))),this._textureMatrix=e,!(null===(i=this.getScene())||void 0===i?void 0:i.useRightHandedSystem))return;const n=o.jp.Vector3[0],s=o.jp.Quaternion[0],r=o.jp.Vector3[1];this._textureMatrix.decompose(n,s,r),s.z*=-1,s.w*=-1,o.y3.ComposeToRef(n,s,r,this._textureMatrixRefraction)}getRefractionTextureMatrix(){var e;return(null===(e=this.getScene())||void 0===e?void 0:e.useRightHandedSystem)?this._textureMatrixRefraction:this._textureMatrix}_loadTexture(e=null,t=null){var i;const n=this.getScene(),s=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);const r=()=>{var t;this.onLoadObservable.notifyObservers(this),s&&(s.dispose(),null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1)),e&&e()},o=(e,i)=>{this._loadingError=!0,this._errorObject={message:e,exception:i},t&&t(e,i),Le.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?se.w1.SetImmediate((()=>r())):this._texture.onLoadedObservable.add((()=>r())):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,n,this._lodScale,this._lodOffset,e,o,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,n,this._files,this._noMipmap,e,o,this._format,this._forcedExtension,!1,this._lodScale,this._lodOffset,null,this._loaderOptions,!!this._useSRGBBuffer),null===(i=this._texture)||void 0===i||i.onLoadedObservable.add((()=>this.onLoadObservable.notifyObservers(this))))}static Parse(e,t,i){const n=E.p4.Parse((()=>{var n;let s=!1;return e.prefiltered&&(s=e.prefiltered),new yp(i+(null!==(n=e.url)&&void 0!==n?n:e.name),t,e.extensions,!1,e.files||null,null,null,void 0,s,e.forcedExtension)}),e,t);if(e.boundingBoxPosition&&(n.boundingBoxPosition=o.P.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(n.boundingBoxSize=o.P.FromArray(e.boundingBoxSize)),e.animations)for(let s=0;s{const t=new yp(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=t.uniqueId,t}),this);return t.uniqueId=e,t}}(0,oe.gn)([(0,E.qC)()],yp.prototype,"url",void 0),(0,oe.gn)([(0,E.hd)()],yp.prototype,"boundingBoxPosition",void 0),(0,oe.gn)([(0,E.hd)()],yp.prototype,"boundingBoxSize",null),(0,oe.gn)([(0,E.qC)("rotationY")],yp.prototype,"rotationY",null),(0,oe.gn)([(0,E.qC)("files")],yp.prototype,"_files",void 0),(0,oe.gn)([(0,E.qC)("forcedExtension")],yp.prototype,"_forcedExtension",void 0),(0,oe.gn)([(0,E.qC)("extensions")],yp.prototype,"_extensions",void 0),(0,oe.gn)([(0,E.oQ)("textureMatrix")],yp.prototype,"_textureMatrix",void 0),(0,oe.gn)([(0,E.oQ)("textureMatrixRefraction")],yp.prototype,"_textureMatrixRefraction",void 0),Le._CubeTextureParser=yp.Parse,(0,l.H)("BABYLON.CubeTexture",yp);const Ap="backgroundFragmentDeclaration",Rp="uniform vec4 vEyePosition;\nuniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n";Ht.v.IncludesShadersStore[Ap]=Rp;const Pp="backgroundUboDeclaration",Ip="layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\n#include\n";Ht.v.IncludesShadersStore[Pp]=Ip;const Mp="backgroundPixelShader",Op="#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#include\n#define RECIPROCAL_PI2 0.15915494\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV==1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV==2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include\n#include\n#include\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));\n}\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n#ifndef BACKMAT_SHADOWONLY\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=saturate(reflectionLOD);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition.xyz),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));\nconst float startAngle=0.1;\nfloat fadeFactor=saturate(viewAngleToFloor/startAngle);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\nvec4 color=vec4(finalColor,finalAlpha);\n#else\nvec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha);\n#endif\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n#if !defined(SKIPFINALCOLORCLAMP)\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#endif\n#else\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Ht.v.ShadersStore[Mp]=Op;const Dp="backgroundVertexDeclaration",Np="uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n";Ht.v.IncludesShadersStore[Dp]=Np;const Fp="backgroundVertexShader",wp="precision highp float;\n#include<__decl__backgroundVertex>\n#include\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nvarying vec2 vDiffuseUV;\n#endif\n#include\n#include\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif\n#include\n#include\n#include\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n} else {\ngl_Position=viewProjectionR*finalWorld*vec4(position,1.0);\n}\n#else\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#endif\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nif (vDiffuseInfos.x==0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";Ht.v.ShadersStore[Fp]=wp;class Lp extends Tt.H{constructor(){super(),this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.GAMMADIFFUSE=!1,this.DIFFUSEHASALPHA=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONBLUR=!1,this.REFLECTIONFRESNEL=!1,this.REFLECTIONFALLOFF=!1,this.TEXTURELODSUPPORT=!1,this.PREMULTIPLYALPHA=!1,this.USERGBCOLOR=!1,this.USEHIGHLIGHTANDSHADOWCOLORS=!1,this.BACKMAT_SHADOWONLY=!1,this.NOISE=!1,this.REFLECTIONBGR=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1,this.MULTIVIEW=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.EQUIRECTANGULAR_RELFECTION_FOV=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.UV1=!1,this.UV2=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.SHADOWFLOAT=!1,this.LOGARITHMICDEPTH=!1,this.NONUNIFORMSCALING=!1,this.ALPHATEST=!1,this.rebuild()}}class Bp extends pt{get _perceptualColor(){return this.__perceptualColor}set _perceptualColor(e){this.__perceptualColor=e,this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsLightsDirty()}get primaryColorShadowLevel(){return this._primaryColorShadowLevel}set primaryColorShadowLevel(e){this._primaryColorShadowLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}get primaryColorHighlightLevel(){return this._primaryColorHighlightLevel}set primaryColorHighlightLevel(e){this._primaryColorHighlightLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}set reflectionStandardFresnelWeight(e){let t=e;t<.5?(t*=2,this.reflectionReflectance0=Bp.StandardReflectance0*t,this.reflectionReflectance90=Bp.StandardReflectance90*t):(t=2*t-1,this.reflectionReflectance0=Bp.StandardReflectance0+(1-Bp.StandardReflectance0)*t,this.reflectionReflectance90=Bp.StandardReflectance90+(1-Bp.StandardReflectance90)*t)}get fovMultiplier(){return this._fovMultiplier}set fovMultiplier(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsImageProcessingDirty()}))))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this.imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this.imageProcessingConfiguration.colorCurves=e}constructor(e,t){super(e,t),this.primaryColor=a.Wo.White(),this._primaryColorShadowLevel=0,this._primaryColorHighlightLevel=0,this.reflectionTexture=null,this.reflectionBlur=0,this.diffuseTexture=null,this._shadowLights=null,this.shadowLights=null,this.shadowLevel=0,this.sceneCenter=o.P.Zero(),this.opacityFresnel=!0,this.reflectionFresnel=!1,this.reflectionFalloffDistance=0,this.reflectionAmount=1,this.reflectionReflectance0=.05,this.reflectionReflectance90=.5,this.useRGBColor=!0,this.enableNoise=!1,this._fovMultiplier=1,this.useEquirectangularFOV=!1,this._maxSimultaneousLights=4,this.maxSimultaneousLights=4,this._shadowOnly=!1,this.shadowOnly=!1,this._imageProcessingObserver=null,this.switchToBGR=!1,this._renderTargets=new Wt.t(16),this._reflectionControls=o.Lt.Zero(),this._white=a.Wo.White(),this._primaryShadowColor=a.Wo.Black(),this._primaryHighlightColor=a.Wo.Black(),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._renderTargets.push(this._diffuseTexture),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._renderTargets)}get hasRenderTargetTextures(){return!(!this._diffuseTexture||!this._diffuseTexture.isRenderTarget)||!(!this._reflectionTexture||!this._reflectionTexture.isRenderTarget)}needAlphaTesting(){return!0}needAlphaBlending(){return this.alpha<1||null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||this._shadowOnly}isReadyForSubMesh(e,t,i=!1){if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new Lp);const n=this.getScene(),s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const r=n.getEngine();if(It.G.PrepareDefinesForLights(n,e,s,!1,this._maxSimultaneousLights),s._needNormals=!0,It.G.PrepareDefinesForMultiview(n,s),s._areTexturesDirty){if(s._needUVs=!1,n.texturesEnabled){if(n.getEngine().getCaps().textureLOD&&(s.TEXTURELODSUPPORT=!0),this._diffuseTexture&&Bs.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;It.G.PrepareDefinesForMergedUV(this._diffuseTexture,s,"DIFFUSE"),s.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,s.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,s.OPACITYFRESNEL=this._opacityFresnel}else s.DIFFUSE=!1,s.DIFFUSEDIRECTUV=0,s.DIFFUSEHASALPHA=!1,s.GAMMADIFFUSE=!1,s.OPACITYFRESNEL=!1;const e=this._reflectionTexture;if(e&&Bs.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;switch(s.REFLECTION=!0,s.GAMMAREFLECTION=e.gammaSpace,s.RGBDREFLECTION=e.isRGBD,s.REFLECTIONBLUR=this._reflectionBlur>0,s.LODINREFLECTIONALPHA=e.lodLevelInAlpha,s.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,s.REFLECTIONBGR=this.switchToBGR,e.coordinatesMode===Le.INVCUBIC_MODE&&(s.INVERTCUBICMAP=!0),s.REFLECTIONMAP_3D=e.isCube,s.REFLECTIONMAP_OPPOSITEZ=s.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.invertZ,e.coordinatesMode){case Le.EXPLICIT_MODE:s.REFLECTIONMAP_EXPLICIT=!0;break;case Le.PLANAR_MODE:s.REFLECTIONMAP_PLANAR=!0;break;case Le.PROJECTION_MODE:s.REFLECTIONMAP_PROJECTION=!0;break;case Le.SKYBOX_MODE:s.REFLECTIONMAP_SKYBOX=!0;break;case Le.SPHERICAL_MODE:s.REFLECTIONMAP_SPHERICAL=!0;break;case Le.EQUIRECTANGULAR_MODE:s.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Le.FIXED_EQUIRECTANGULAR_MODE:s.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Le.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:s.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Le.CUBIC_MODE:case Le.INVCUBIC_MODE:default:s.REFLECTIONMAP_CUBIC=!0}this.reflectionFresnel?(s.REFLECTIONFRESNEL=!0,s.REFLECTIONFALLOFF=this.reflectionFalloffDistance>0,this._reflectionControls.x=this.reflectionAmount,this._reflectionControls.y=this.reflectionReflectance0,this._reflectionControls.z=this.reflectionReflectance90,this._reflectionControls.w=1/this.reflectionFalloffDistance):(s.REFLECTIONFRESNEL=!1,s.REFLECTIONFALLOFF=!1)}else s.REFLECTION=!1,s.REFLECTIONFRESNEL=!1,s.REFLECTIONFALLOFF=!1,s.REFLECTIONBLUR=!1,s.REFLECTIONMAP_3D=!1,s.REFLECTIONMAP_SPHERICAL=!1,s.REFLECTIONMAP_PLANAR=!1,s.REFLECTIONMAP_CUBIC=!1,s.REFLECTIONMAP_PROJECTION=!1,s.REFLECTIONMAP_SKYBOX=!1,s.REFLECTIONMAP_EXPLICIT=!1,s.REFLECTIONMAP_EQUIRECTANGULAR=!1,s.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,s.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,s.INVERTCUBICMAP=!1,s.REFLECTIONMAP_OPPOSITEZ=!1,s.LODINREFLECTIONALPHA=!1,s.GAMMAREFLECTION=!1,s.RGBDREFLECTION=!1}s.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,s.USERGBCOLOR=this._useRGBColor,s.NOISE=this._enableNoise}if(s._areLightsDirty&&(s.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel),s.BACKMAT_SHADOWONLY=this._shadowOnly),s._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(s)}if(It.G.PrepareDefinesForMisc(e,n,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),It.G.PrepareDefinesForFrameBoundValues(n,r,this,s,i,null,t.getRenderingMesh().hasThinInstances),It.G.PrepareDefinesForAttributes(e,s,!1,!0,!1)&&e&&(n.getEngine().getCaps().standardDerivatives||e.isVerticesDataPresent(ne.o.NormalKind)||(e.createNormals(!0),p.Y.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name))),s.isDirty){s.markAsProcessed(),n.resetCachedMaterial();const i=new zt;s.FOG&&i.addFallback(0,"FOG"),s.POINTSIZE&&i.addFallback(1,"POINTSIZE"),s.MULTIVIEW&&i.addFallback(0,"MULTIVIEW"),It.G.HandleFallbacksForShadows(s,i,this._maxSimultaneousLights);const o=[ne.o.PositionKind];s.NORMAL&&o.push(ne.o.NormalKind),s.UV1&&o.push(ne.o.UVKind),s.UV2&&o.push(ne.o.UV2Kind),It.G.PrepareAttributesForBones(o,e,s,i),It.G.PrepareAttributesForInstances(o,s);const a=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix"];(0,ua.qx)(a);const l=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],h=["Material","Scene"];ii.$&&(ii.$.PrepareUniforms(a,s),ii.$.PrepareSamplers(l,s)),It.G.PrepareUniformsAndSamplersList({uniformsNames:a,uniformBuffersNames:h,samplers:l,defines:s,maxSimultaneousLights:this._maxSimultaneousLights});const c=s.toString(),d=n.getEngine().createEffect("background",{attributes:o,uniformsNames:a,uniformBuffersNames:h,samplers:l,defines:c,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},r);t.setEffect(d,s,this._materialContext),this.buildUniformLayout()}return!(!t.effect||!t.effect.isReady())&&(s._renderId=n.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}_computePrimaryColorFromPerceptualColor(){this.__perceptualColor&&(this._primaryColor.copyFrom(this.__perceptualColor),this._primaryColor.toLinearSpaceToRef(this._primaryColor,this.getScene().getEngine().useExactSrgbConversions),this._imageProcessingConfiguration&&this._primaryColor.scaleToRef(1/this._imageProcessingConfiguration.exposure,this._primaryColor),this._computePrimaryColors())}_computePrimaryColors(){0===this._primaryColorShadowLevel&&0===this._primaryColorHighlightLevel||(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))}buildUniformLayout(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.create()}unbind(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),super.unbind()}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindForSubMesh(e,t,i){const n=this.getScene(),s=i.materialDefines;if(!s)return;const r=i.effect;if(!r)return;this._activeEffect=r,this.bindOnlyWorldMatrix(e),It.G.BindBonesParameters(t,this._activeEffect);const o=this._mustRebind(n,r,t.visibility);if(o){this._uniformBuffer.bindToEffect(r,"Material"),this.bindViewProjection(r);const e=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync||(n.texturesEnabled&&(this._diffuseTexture&&Bs.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),It.G.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse")),e&&Bs.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",e.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",e.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",e.getSize().width,e.lodGenerationScale,e.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),s.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),n.texturesEnabled&&(this._diffuseTexture&&Bs.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),e&&Bs.ReflectionTextureEnabled&&(s.REFLECTIONBLUR&&s.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",e):s.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",e._lodTextureMid||e),this._uniformBuffer.setTexture("reflectionSamplerLow",e._lodTextureLow||e),this._uniformBuffer.setTexture("reflectionSamplerHigh",e._lodTextureHigh||e)):this._uniformBuffer.setTexture("reflectionSampler",e),s.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w)))),(0,ua.an)(this._activeEffect,this,n),n.bindEyePosition(r)}else n.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(r,"Material"),this._needToBindSceneUbo=!0);!o&&this.isFrozen||(n.lightsEnabled&&It.G.BindLights(n,t,this._activeEffect,s,this._maxSimultaneousLights),this.bindView(r),It.G.BindFogParameters(n,t,this._activeEffect,!0),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),this._uniformBuffer.update()}hasTexture(e){return!!super.hasTexture(e)||(this._reflectionTexture===e||this._diffuseTexture===e)}dispose(e=!1,t=!1){t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return E.p4.Clone((()=>new Bp(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return E.p4.Parse((()=>new Bp(e.name,t)),e,t,i)}}Bp.StandardReflectance0=.05,Bp.StandardReflectance90=.5,(0,oe.gn)([(0,E.n9)()],Bp.prototype,"_primaryColor",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsLightsDirty")],Bp.prototype,"primaryColor",void 0),(0,oe.gn)([(0,E.n9)()],Bp.prototype,"__perceptualColor",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_primaryColorShadowLevel",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_primaryColorHighlightLevel",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsLightsDirty")],Bp.prototype,"primaryColorHighlightLevel",null),(0,oe.gn)([(0,E.oU)()],Bp.prototype,"_reflectionTexture",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"reflectionTexture",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_reflectionBlur",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"reflectionBlur",void 0),(0,oe.gn)([(0,E.oU)()],Bp.prototype,"_diffuseTexture",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"diffuseTexture",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"shadowLights",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_shadowLevel",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"shadowLevel",void 0),(0,oe.gn)([(0,E.hd)()],Bp.prototype,"_sceneCenter",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"sceneCenter",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_opacityFresnel",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"opacityFresnel",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_reflectionFresnel",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"reflectionFresnel",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_reflectionFalloffDistance",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"reflectionFalloffDistance",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_reflectionAmount",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"reflectionAmount",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_reflectionReflectance0",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"reflectionReflectance0",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_reflectionReflectance90",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"reflectionReflectance90",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_useRGBColor",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"useRGBColor",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_enableNoise",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"enableNoise",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_maxSimultaneousLights",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"maxSimultaneousLights",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_shadowOnly",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsLightsDirty")],Bp.prototype,"shadowOnly",void 0),(0,oe.gn)([(0,E.rX)()],Bp.prototype,"_imageProcessingConfiguration",void 0),(0,l.H)("BABYLON.BackgroundMaterial",Bp);class Up{static _GetDefaultOptions(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new a.Wo(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),groundOpacity:.9,enableGroundShadow:!0,groundShadowLevel:.5,enableGroundMirror:!1,groundMirrorSizeRatio:.3,groundMirrorBlurKernel:64,groundMirrorAmount:1,groundMirrorFresnelWeight:1,groundMirrorFallOffDistance:0,groundMirrorTextureType:0,groundYBias:1e-5,createSkybox:!0,skyboxSize:20,skyboxTexture:this._SkyboxTextureCDNUrl,skyboxColor:new a.Wo(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:o.P.Zero(),setupImageProcessing:!0,environmentTexture:this._EnvironmentTextureCDNUrl,cameraExposure:.8,cameraContrast:1.2,toneMappingEnabled:!0}}get rootMesh(){return this._rootMesh}get skybox(){return this._skybox}get skyboxTexture(){return this._skyboxTexture}get skyboxMaterial(){return this._skyboxMaterial}get ground(){return this._ground}get groundTexture(){return this._groundTexture}get groundMirror(){return this._groundMirror}get groundMirrorRenderList(){return this._groundMirror?this._groundMirror.renderList:null}get groundMaterial(){return this._groundMaterial}constructor(e,t){this._errorHandler=(e,t)=>{this.onErrorObservable.notifyObservers({message:e,exception:t})},this._options=Object.assign(Object.assign({},Up._GetDefaultOptions(t)),e),this._scene=t,this.onErrorObservable=new r.y$,this._setupBackground(),this._setupImageProcessing()}updateOptions(e){const t=Object.assign(Object.assign({},this._options),e);this._ground&&!t.createGround&&(this._ground.dispose(),this._ground=null),this._groundMaterial&&!t.createGround&&(this._groundMaterial.dispose(),this._groundMaterial=null),this._groundTexture&&this._options.groundTexture!=t.groundTexture&&(this._groundTexture.dispose(),this._groundTexture=null),this._skybox&&!t.createSkybox&&(this._skybox.dispose(),this._skybox=null),this._skyboxMaterial&&!t.createSkybox&&(this._skyboxMaterial.dispose(),this._skyboxMaterial=null),this._skyboxTexture&&this._options.skyboxTexture!=t.skyboxTexture&&(this._skyboxTexture.dispose(),this._skyboxTexture=null),this._groundMirror&&!t.enableGroundMirror&&(this._groundMirror.dispose(),this._groundMirror=null),this._scene.environmentTexture&&this._options.environmentTexture!=t.environmentTexture&&this._scene.environmentTexture.dispose(),this._options=t,this._setupBackground(),this._setupImageProcessing()}setMainColor(e){this.groundMaterial&&(this.groundMaterial.primaryColor=e),this.skyboxMaterial&&(this.skyboxMaterial.primaryColor=e),this.groundMirror&&(this.groundMirror.clearColor=new a.HE(e.r,e.g,e.b,1))}_setupImageProcessing(){this._options.setupImageProcessing&&(this._scene.imageProcessingConfiguration.contrast=this._options.cameraContrast,this._scene.imageProcessingConfiguration.exposure=this._options.cameraExposure,this._scene.imageProcessingConfiguration.toneMappingEnabled=this._options.toneMappingEnabled,this._setupEnvironmentTexture())}_setupEnvironmentTexture(){if(this._scene.environmentTexture)return;if(this._options.environmentTexture instanceof Re)return void(this._scene.environmentTexture=this._options.environmentTexture);const e=yp.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new ee.Kj("BackgroundHelper",this._scene)),this._rootMesh.rotation.y=this._options.backgroundYRotation;const e=this._getSceneSize();this._options.createGround&&(this._setupGround(e),this._setupGroundMaterial(),this._setupGroundDiffuseTexture(),this._options.enableGroundMirror&&this._setupGroundMirrorTexture(e),this._setupMirrorInGroundMaterial()),this._options.createSkybox&&(this._setupSkybox(e),this._setupSkyboxMaterial(),this._setupSkyboxReflectionTexture()),this._rootMesh.position.x=e.rootPosition.x,this._rootMesh.position.z=e.rootPosition.z,this._rootMesh.position.y=e.rootPosition.y}_getSceneSize(){let e=this._options.groundSize,t=this._options.skyboxSize,i=this._options.rootPosition;if(!this._scene.meshes||1===this._scene.meshes.length)return{groundSize:e,skyboxSize:t,rootPosition:i};const n=this._scene.getWorldExtends((e=>e!==this._ground&&e!==this._rootMesh&&e!==this._skybox)),s=n.max.subtract(n.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof Ln&&this._scene.activeCamera.upperRadiusLimit&&(e=2*this._scene.activeCamera.upperRadiusLimit,t=e);const r=s.length();r>e&&(e=2*r,t=e),e*=1.1,t*=1.5,i=n.min.add(s.scale(.5)),i.y=n.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:t,rootPosition:i}}_setupGround(e){this._ground&&!this._ground.isDisposed()||(this._ground=Je("BackgroundPlane",{size:e.groundSize},this._scene),this._ground.rotation.x=Math.PI/2,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add((()=>{this._ground=null}))),this._ground.receiveShadows=this._options.enableGroundShadow}_setupGroundMaterial(){this._groundMaterial||(this._groundMaterial=new Bp("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=8,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)}_setupGroundDiffuseTexture(){this._groundMaterial&&(this._groundTexture||(this._options.groundTexture instanceof Re?this._groundMaterial.diffuseTexture=this._options.groundTexture:(this._groundTexture=new Le(this._options.groundTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._groundTexture.gammaSpace=!1,this._groundTexture.hasAlpha=!0,this._groundMaterial.diffuseTexture=this._groundTexture)))}_setupGroundMirrorTexture(e){const t=Le.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new Cp("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,Le.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new Me.J(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.renderList))for(let n=0;n{this._skybox=null}))),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new Bp("BackgroundSkyboxMaterial",this._scene)),this._skyboxMaterial.useRGBColor=!1,this._skyboxMaterial.primaryColor=this._options.skyboxColor,this._skyboxMaterial.enableNoise=!0,this._skybox.material=this._skyboxMaterial)}_setupSkyboxReflectionTexture(){this._skyboxMaterial&&(this._skyboxTexture||(this._options.skyboxTexture instanceof Re?this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture:(this._skyboxTexture=new yp(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=Le.SKYBOX_MODE,this._skyboxTexture.gammaSpace=!1,this._skyboxMaterial.reflectionTexture=this._skyboxTexture)))}dispose(){this._groundMaterial&&this._groundMaterial.dispose(!0,!0),this._skyboxMaterial&&this._skyboxMaterial.dispose(!0,!0),this._rootMesh.dispose(!1)}}Up._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png",Up._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds",Up._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";class Vp extends te.Y{get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=Le.CLAMP_ADDRESSMODE,this._texture.wrapV=Le.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=Le.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=Le.CLAMP_ADDRESSMODE,this._material.reflectionTexture=this._texture),this._changeTextureMode(this._textureMode))}get mesh(){return this._mesh}get fovMultiplier(){return this._material.fovMultiplier}set fovMultiplier(e){this._material.fovMultiplier=e}get textureMode(){return this._textureMode}set textureMode(e){this._textureMode!==e&&this._changeTextureMode(e)}get halfDome(){return this._halfDome}set halfDome(e){this._halfDome=e,this._halfDomeMask.setEnabled(e),this._changeTextureMode(this._textureMode)}set crossEye(e){this._crossEye=e,this._changeTextureMode(this._textureMode)}get crossEye(){return this._crossEye}get material(){return this._material}constructor(e,t,i,n,s=null){super(e,n),this.onError=s,this._halfDome=!1,this._crossEye=!1,this._useDirectMapping=!1,this._textureMode=Vp.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new r.y$,this.onLoadObservable=new r.y$,n=this.getScene(),e=e||"textureDome",i.resolution=0|Math.abs(i.resolution)||32,i.clickToPlay=Boolean(i.clickToPlay),i.autoPlay=void 0===i.autoPlay||Boolean(i.autoPlay),i.loop=void 0===i.loop||Boolean(i.loop),i.size=Math.abs(i.size)||(n.activeCamera?.48*n.activeCamera.maxZ:1e3),void 0===i.useDirectMapping?this._useDirectMapping=!0:this._useDirectMapping=i.useDirectMapping,void 0===i.faceForward&&(i.faceForward=!0),this._setReady(!1),i.mesh?this._mesh=i.mesh:this._mesh=gl(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:ee.Kj.BACKSIDE},n);const a=this._material=new Bp(e+"_material",n);a.useEquirectangularFOV=!0,a.fovMultiplier=1,a.opacityFresnel=!1;const l=this._initTexture(t,n,i);if(this.texture=l,this._mesh.material=a,this._mesh.parent=this,this._halfDomeMask=gl("",{slice:.5,diameter:.98*i.size,segments:2*i.resolution,sideOrientation:ee.Kj.BACKSIDE},n),this._halfDomeMask.rotate(L.RD.X,-Math.PI/2),this._halfDomeMask.parent=this._mesh,this._halfDome=!!i.halfDomeMode,this._halfDomeMask.setEnabled(this._halfDome),this._crossEye=!!i.crossEyeMode,this._texture.anisotropicFilteringLevel=1,this._texture.onLoadObservable.addOnce((()=>{this._setReady(!0)})),i.faceForward&&n.activeCamera){const e=n.activeCamera,t=o.P.Forward(),i=o.P.TransformNormal(t,e.getViewMatrix());i.normalize(),this.rotation.y=Math.acos(o.P.Dot(t,i))}this._changeTextureMode(this._textureMode)}_changeTextureMode(e){switch(this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._textureMode=e,this._texture.uScale=1,this._texture.vScale=1,this._texture.uOffset=0,this._texture.vOffset=0,this._texture.vAng=0,e){case Vp.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case Vp.MODE_SIDEBYSIDE:{this._texture.uScale=this._halfDome?.99999:.5;const e=this._halfDome?0:.5,t=this._halfDome?-.5:0;this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add((i=>{let n=i.isRightCamera;this._crossEye&&(n=!n),this._texture.uOffset=n?e:t}));break}case Vp.MODE_TOPBOTTOM:this._texture.vScale=this._halfDome?.99999:.5,this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add((e=>{let t=e.isRightCamera;this._crossEye&&(t=!t),this._texture.vOffset=t?.5:0}))}}dispose(e,t=!1){this._texture.dispose(),this._mesh.dispose(),this._material.dispose(),this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this.onLoadErrorObservable.clear(),this.onLoadObservable.clear(),super.dispose(e,t)}}Vp.MODE_MONOSCOPIC=0,Vp.MODE_TOPBOTTOM=1,Vp.MODE_SIDEBYSIDE=2;class kp extends Vp{get photoTexture(){return this.texture}set photoTexture(e){this.texture=e}get imageMode(){return this.textureMode}set imageMode(e){this.textureMode=e}_initTexture(e,t,i){return new Le(e,t,!i.generateMipMaps,!this._useDirectMapping,void 0,(()=>{this.onLoadObservable.notifyObservers()}),((e,t)=>{this.onLoadErrorObservable.notifyObservers(e||"Unknown error occured"),this.onError&&this.onError(e,t)}))}}kp.MODE_MONOSCOPIC=Vp.MODE_MONOSCOPIC,kp.MODE_TOPBOTTOM=Vp.MODE_TOPBOTTOM,kp.MODE_SIDEBYSIDE=Vp.MODE_SIDEBYSIDE;let Gp=0;const zp=e=>{if(!e.environmentBRDFTexture){const t=e.useDelayedTextureLoading;e.useDelayedTextureLoading=!1;const i=e._blockEntityCollection;e._blockEntityCollection=!1;const n=Le.CreateFromBase64String("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR42u29yY5tWXIlZnbuiSaTbZFUkZRKrCKhElASQA0EoQABgn6hJvoXzfUP+gP9hWb6Bg00IgRoQJaKqUxmZmTEe8/v0uB2u7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!1,Le.BILINEAR_SAMPLINGMODE);e._blockEntityCollection=i;const s=e.getEngine().getLoadedTexturesCache(),r=s.indexOf(n.getInternalTexture());-1!==r&&s.splice(r,1),n.isRGBD=!0,n.wrapU=Le.CLAMP_ADDRESSMODE,n.wrapV=Le.CLAMP_ADDRESSMODE,e.environmentBRDFTexture=n,e.useDelayedTextureLoading=t,kh.ExpandRGBDTexture(n);const o=e.getEngine().onContextRestoredObservable.add((()=>{n.isRGBD=!0;const e=()=>{n.isReady()?kh.ExpandRGBDTexture(n):se.w1.SetImmediate(e)};e()}));e.onDisposeObservable.add((()=>{e.getEngine().onContextRestoredObservable.remove(o)}))}return e.environmentBRDFTexture};class Wp extends Tt.H{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 Hp extends ha{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRBRDF",90,new Wp,t),this._useEnergyConservation=Hp.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=Hp.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=Hp.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=Hp.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=Hp.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=Hp.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=Hp.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=Hp.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16],this._enable(!0)}prepareDefines(e){e.BRDF_V_HEIGHT_CORRELATED=this._useSmithVisibilityHeightCorrelated,e.MS_BRDF_ENERGY_CONSERVATION=this._useEnergyConservation&&this._useSmithVisibilityHeightCorrelated,e.SPHERICAL_HARMONICS=this._useSphericalHarmonics,e.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=this._useSpecularGlossinessInputEnergyConservation}getClassName(){return"PBRBRDFConfiguration"}}Hp.DEFAULT_USE_ENERGY_CONSERVATION=!0,Hp.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,Hp.DEFAULT_USE_SPHERICAL_HARMONICS=!0,Hp.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0,(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsMiscDirty")],Hp.prototype,"useEnergyConservation",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsMiscDirty")],Hp.prototype,"useSmithVisibilityHeightCorrelated",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsMiscDirty")],Hp.prototype,"useSphericalHarmonics",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsMiscDirty")],Hp.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);const Xp="pbrFragmentDeclaration",Yp="uniform vec4 vEyePosition;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec4 vMetallicReflectanceFactors;\nuniform vec3 vEmissiveColor;\nuniform float visibility;\nuniform vec3 vAmbientColor;\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform 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;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC)\nuniform vec3 vRefractionPosition;\nuniform vec3 vRefractionSize; \n#endif\n#ifdef CLEARCOAT\nuniform vec2 vClearCoatParams;\nuniform 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;\nuniform vec2 vClearCoatTangentSpaceParams;\nuniform mat4 clearCoatBumpMatrix;\n#endif\n#ifdef CLEARCOAT_TINT\nuniform vec4 vClearCoatTintParams;\nuniform float clearCoatColorAtDistance;\n#ifdef CLEARCOAT_TINT_TEXTURE\nuniform vec2 vClearCoatTintInfos;\nuniform 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;\nuniform 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;\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\n#ifdef REALTIME_FILTERING\nuniform vec2 vRefractionFilteringInfo;\n#endif\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nuniform vec2 vThicknessInfos;\nuniform mat4 thicknessMatrix;\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nuniform vec2 vRefractionIntensityInfos;\nuniform mat4 refractionIntensityMatrix;\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nuniform vec2 vTranslucencyIntensityInfos;\nuniform mat4 translucencyIntensityMatrix;\n#endif\nuniform vec2 vThicknessParam;\nuniform vec3 vDiffusionDistance;\nuniform vec4 vTintColor;\nuniform vec3 vSubSurfaceIntensity;\n#endif\n#ifdef PREPASS\n#ifdef SS_SCATTERING\nuniform float scatteringDiffusionProfile;\n#endif\n#endif\n#if DEBUGMODE>0\nuniform vec2 vDebugMode;\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\n#endif\n#include\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nuniform vec3 vSphericalL00;\nuniform vec3 vSphericalL1_1;\nuniform vec3 vSphericalL10;\nuniform vec3 vSphericalL11;\nuniform vec3 vSphericalL2_2;\nuniform vec3 vSphericalL2_1;\nuniform vec3 vSphericalL20;\nuniform vec3 vSphericalL21;\nuniform vec3 vSphericalL22;\n#else\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\n#endif\n#endif\n#define ADDITIONAL_FRAGMENT_DECLARATION\n";Ht.v.IncludesShadersStore[Xp]=Yp;const jp="pbrUboDeclaration",Kp="layout(std140,column_major) uniform;\nuniform Material {\nvec2 vAlbedoInfos;\nvec4 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec3 vReflectivityInfos;\nvec2 vMicroSurfaceSamplerInfos;\nvec2 vReflectionInfos;\nvec2 vReflectionFilteringInfo;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec3 vBumpInfos;\nmat4 albedoMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 reflectivityMatrix;\nmat4 microSurfaceSamplerMatrix;\nmat4 bumpMatrix;\nvec2 vTangentSpaceParams;\nmat4 reflectionMatrix;\nvec3 vReflectionColor;\nvec4 vAlbedoColor;\nvec4 vLightingIntensity;\nvec3 vReflectionMicrosurfaceInfos;\nfloat pointSize;\nvec4 vReflectivityColor;\nvec3 vEmissiveColor;\nvec3 vAmbientColor;\nvec2 vDebugMode;\nvec4 vMetallicReflectanceFactors;\nvec2 vMetallicReflectanceInfos;\nmat4 metallicReflectanceMatrix;\nvec2 vReflectanceInfos;\nmat4 reflectanceMatrix;\nvec3 vSphericalL00;\nvec3 vSphericalL1_1;\nvec3 vSphericalL10;\nvec3 vSphericalL11;\nvec3 vSphericalL2_2;\nvec3 vSphericalL2_1;\nvec3 vSphericalL20;\nvec3 vSphericalL21;\nvec3 vSphericalL22;\nvec3 vSphericalX;\nvec3 vSphericalY;\nvec3 vSphericalZ;\nvec3 vSphericalXX_ZZ;\nvec3 vSphericalYY_ZZ;\nvec3 vSphericalZZ;\nvec3 vSphericalXY;\nvec3 vSphericalYZ;\nvec3 vSphericalZX;\n#define ADDITIONAL_UBO_DECLARATION\n};\n#include\n#include\n";Ht.v.IncludesShadersStore[jp]=Kp;const qp="pbrFragmentExtraDeclaration",$p="varying vec3 vPositionW;\n#if DEBUGMODE>0\nvarying vec4 vClipSpacePosition;\n#endif\n#include[1..7]\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n";Ht.v.IncludesShadersStore[qp]=$p;const Qp="samplerFragmentAlternateDeclaration",Zp="#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";Ht.v.IncludesShadersStore[Qp]=Zp;const Jp="pbrFragmentSamplersDeclaration",ef="#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL)\nuniform sampler2D clearCoatRoughnessSampler;\n#endif\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL)\nuniform sampler2D sheenRoughnessSampler;\n#endif\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy)\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform 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;\nuniform 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;\nuniform 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;\nuniform sampler2D refractionSamplerHigh;\n#endif\n#endif\n#endif\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)\n#endif\n";Ht.v.IncludesShadersStore[Jp]=ef;const tf="subSurfaceScatteringFunctions",nf="bool testLightingForSSS(float diffusionProfile)\n{\nreturn diffusionProfile<1.;\n}";Ht.v.IncludesShadersStore[tf]=nf;const sf="importanceSampling",rf="vec3 hemisphereCosSample(vec2 u) {\nfloat phi=2.*PI*u.x;\nfloat cosTheta2=1.-u.y;\nfloat cosTheta=sqrt(cosTheta2);\nfloat sinTheta=sqrt(1.-cosTheta2);\nreturn vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);\n}\nvec3 hemisphereImportanceSampleDggx(vec2 u,float a) {\nfloat phi=2.*PI*u.x;\nfloat cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));\nfloat cosTheta=sqrt(cosTheta2);\nfloat sinTheta=sqrt(1.-cosTheta2);\nreturn vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);\n}\nvec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { \nfloat phi=2.*PI*u.x;\nfloat sinTheta=pow(u.y,a/(2.*a+1.));\nfloat cosTheta=sqrt(1.-sinTheta*sinTheta);\nreturn vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);\n}";Ht.v.IncludesShadersStore[sf]=rf;const of="pbrHelperFunctions",af="#define RECIPROCAL_PI2 0.15915494\n#define RECIPROCAL_PI 0.31830988618\n#define MINIMUMVARIANCE 0.0005\nfloat convertRoughnessToAverageSlope(float roughness)\n{\nreturn square(roughness)+MINIMUMVARIANCE;\n}\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=saturate(reflectance0*25.0);\nreturn reflectance90;\n}\nvec2 getAARoughnessFactors(vec3 normalVector) {\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalVector.xyz);\nvec3 nDfdy=dFdy(normalVector.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\nfloat geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\ngeometricAlphaGFactor*=0.75;\nreturn vec2(geometricRoughnessFactor,geometricAlphaGFactor);\n#else\nreturn vec2(0.);\n#endif\n}\n#ifdef ANISOTROPIC\n#ifdef ANISOTROPIC_LEGACY\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {\nfloat alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);\nfloat alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);\nreturn vec2(alphaT,alphaB);\n}\nvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {\nvec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;\nvec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);\nvec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);\nvec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));\nreturn anisotropicNormal;\n}\n#else\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {\nfloat alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);\nfloat alphaB=max(alphaG,MINIMUMVARIANCE);\nreturn vec2(alphaT,alphaB);\n}\nvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {\nvec3 bentNormal=cross(B,V);\nbentNormal=normalize(cross(bentNormal,B));\nfloat a=square(square(1.0-anisotropy*(1.0-roughness)));\nbentNormal=normalize(mix(bentNormal,N,a));\nreturn bentNormal;\n}\n#endif\n#endif\n#if defined(CLEARCOAT) || defined(SS_REFRACTION)\nvec3 cocaLambert(vec3 alpha,float distance) {\nreturn exp(-alpha*distance);\n}\nvec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {\nreturn cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));\n}\nvec3 computeColorAtDistanceInMedia(vec3 color,float distance) {\nreturn -log(color)/distance;\n}\nvec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {\nvec3 clearCoatAbsorption=mix(vec3(1.0),\ncocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),\nclearCoatIntensity);\nreturn clearCoatAbsorption;\n}\n#endif\n#ifdef MICROSURFACEAUTOMATIC\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n#endif\n";Ht.v.IncludesShadersStore[of]=af;const lf="harmonicsFunctions",hf="#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nvec3 computeEnvironmentIrradiance(vec3 normal) {\nreturn 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}\n#else\nvec3 computeEnvironmentIrradiance(vec3 normal) {\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz *Nz+C1;\nvec3 t2=a2 *Ny+t1;\nvec3 t3=b3 *Nx+t2;\nreturn t3;\n}\n#endif\n#endif\n";Ht.v.IncludesShadersStore[lf]=hf;const cf="pbrDirectLightingSetupFunctions",df="struct preLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nfloat lightDistance;\nfloat attenuation;\nvec3 L;\nvec3 H;\nfloat NdotV;\nfloat NdotLUnclamped;\nfloat NdotL;\nfloat VdotH;\nfloat roughness;\n#ifdef IRIDESCENCE\nfloat iridescenceIntensity;\n#endif\n};\npreLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {\npreLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nresult.lightDistance=sqrt(result.lightDistanceSquared);\nresult.L=normalize(result.lightOffset);\nresult.H=normalize(V+result.L);\nresult.VdotH=saturate(dot(V,result.H));\nresult.NdotLUnclamped=dot(N,result.L);\nresult.NdotL=saturateEps(result.NdotLUnclamped);\nreturn result;\n}\npreLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {\npreLightingInfo result;\nresult.lightDistance=length(-lightData.xyz);\nresult.L=normalize(-lightData.xyz);\nresult.H=normalize(V+result.L);\nresult.VdotH=saturate(dot(V,result.H));\nresult.NdotLUnclamped=dot(N,result.L);\nresult.NdotL=saturateEps(result.NdotLUnclamped);\nreturn result;\n}\npreLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {\npreLightingInfo result;\nresult.NdotL=dot(N,lightData.xyz)*0.5+0.5;\nresult.NdotL=saturateEps(result.NdotL);\nresult.NdotLUnclamped=result.NdotL;\n#ifdef SPECULARTERM\nresult.L=normalize(lightData.xyz);\nresult.H=normalize(V+result.L);\nresult.VdotH=saturate(dot(V,result.H));\n#endif\nreturn result;\n}";Ht.v.IncludesShadersStore[cf]=df;const uf="pbrDirectLightingFalloffFunctions",pf="float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{\nreturn max(0.,1.0-length(lightOffset)/range);\n}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{\nreturn 1.0/maxEps(lightDistanceSquared);\n}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{\nfloat lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);\nfloat factor=lightDistanceSquared*inverseSquaredRange;\nfloat attenuation=saturate(1.0-factor*factor);\nattenuation*=attenuation;\nlightDistanceFalloff*=attenuation;\nreturn lightDistanceFalloff;\n}\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{\nfloat falloff=0.0;\nfloat cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfloat falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{\nfloat cd=dot(-lightDirection,directionToLightCenterW);\nfloat falloff=saturate(cd*lightAngleScale+lightAngleOffset);\nfalloff*=falloff;\nreturn falloff;\n}\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}";Ht.v.IncludesShadersStore[uf]=pf;const ff="pbrBRDFFunctions",_f="#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n#ifdef MS_BRDF_ENERGY_CONSERVATION\nvec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {\nreturn 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);\n}\n#endif\n#ifdef ENVIRONMENTBRDF\nvec3 getBRDFLookup(float NdotV,float perceptualRoughness) {\nvec2 UV=vec2(NdotV,perceptualRoughness);\nvec4 brdfLookup=texture2D(environmentBrdfSampler,UV);\n#ifdef ENVIRONMENTBRDF_RGBD\nbrdfLookup.rgb=fromRGBD(brdfLookup.rgba);\n#endif\nreturn brdfLookup.rgb;\n}\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;\n}\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}\n#endif\n/* NOT USED\n#if defined(SHEEN) && defined(SHEEN_SOFTER)\nfloat getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness)\n{\nfloat c=1.0-NdotV;\nfloat c3=c*c*c;\nreturn 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));\n}\n#endif\n*/\n#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL)\nvec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));\n}\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) {\nvec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;\nreturn sheenEnvironmentReflectance;\n}\n#endif\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);\n}\nfloat fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);\n}\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);\nvec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);\nreturn 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);\nvec3 getIORTfromAirToSurfaceR0(vec3 f0) {\nvec3 sqrtF0=sqrt(f0);\nreturn (1.+sqrtF0)/(1.-sqrtF0);\n}\nvec3 getR0fromIORs(vec3 iorT,float iorI) {\nreturn square((iorT-vec3(iorI))/(iorT+vec3(iorI)));\n}\nfloat getR0fromIORs(float iorT,float iorI) {\nreturn square((iorT-iorI)/(iorT+iorI));\n}\nvec3 evalSensitivity(float opd,vec3 shift) {\nfloat phase=2.0*PI*opd*1.0e-9;\nconst vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);\nconst vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);\nconst vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);\nvec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);\nxyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));\nxyz/=1.0685e-7;\nvec3 srgb=XYZ_TO_REC709*xyz;\nreturn srgb;\n}\nvec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {\nvec3 I=vec3(1.0);\nfloat iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));\nfloat sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));\nfloat cosTheta2Sq=1.0-sinTheta2Sq;\nif (cosTheta2Sq<0.0) {\nreturn I;\n}\nfloat cosTheta2=sqrt(cosTheta2Sq);\nfloat R0=getR0fromIORs(iridescenceIOR,outsideIOR);\nfloat R12=fresnelSchlickGGX(cosTheta1,R0,1.);\nfloat R21=R12;\nfloat T121=1.0-R12;\nfloat phi12=0.0;\nif (iridescenceIOR0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._tintTexture&&this._tintTexture.animations&&this._tintTexture.animations.length>0&&e.push(this._tintTexture)}dispose(e){var t,i,n,s;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._textureRoughness)||void 0===i||i.dispose(),null===(n=this._bumpTexture)||void 0===n||n.dispose(),null===(s=this._tintTexture)||void 0===s||s.dispose())}getClassName(){return"PBRClearCoatConfiguration"}addFallbacks(e,t,i){return e.CLEARCOAT_BUMP&&t.addFallback(i++,"CLEARCOAT_BUMP"),e.CLEARCOAT_TINT&&t.addFallback(i++,"CLEARCOAT_TINT"),e.CLEARCOAT&&t.addFallback(i++,"CLEARCOAT"),i}getSamplers(e){e.push("clearCoatSampler","clearCoatRoughnessSampler","clearCoatBumpSampler","clearCoatTintSampler")}getUniforms(){return{ubo:[{name:"vClearCoatParams",size:2,type:"vec2"},{name:"vClearCoatRefractionParams",size:4,type:"vec4"},{name:"vClearCoatInfos",size:4,type:"vec4"},{name:"clearCoatMatrix",size:16,type:"mat4"},{name:"clearCoatRoughnessMatrix",size:16,type:"mat4"},{name:"vClearCoatBumpInfos",size:2,type:"vec2"},{name:"vClearCoatTangentSpaceParams",size:2,type:"vec2"},{name:"clearCoatBumpMatrix",size:16,type:"mat4"},{name:"vClearCoatTintParams",size:4,type:"vec4"},{name:"clearCoatColorAtDistance",size:1,type:"float"},{name:"vClearCoatTintInfos",size:2,type:"vec2"},{name:"clearCoatTintMatrix",size:16,type:"mat4"}]}}}T_._DefaultIndexOfRefraction=1.5,(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],T_.prototype,"isEnabled",void 0),(0,oe.gn)([(0,E.qC)()],T_.prototype,"intensity",void 0),(0,oe.gn)([(0,E.qC)()],T_.prototype,"roughness",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],T_.prototype,"indexOfRefraction",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],T_.prototype,"texture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],T_.prototype,"useRoughnessFromMainTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],T_.prototype,"textureRoughness",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],T_.prototype,"remapF0OnInterfaceChange",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],T_.prototype,"bumpTexture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],T_.prototype,"isTintEnabled",void 0),(0,oe.gn)([(0,E.n9)()],T_.prototype,"tintColor",void 0),(0,oe.gn)([(0,E.qC)()],T_.prototype,"tintColorAtDistance",void 0),(0,oe.gn)([(0,E.qC)()],T_.prototype,"tintThickness",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],T_.prototype,"tintTexture",void 0);class S_ extends Tt.H{constructor(){super(...arguments),this.IRIDESCENCE=!1,this.IRIDESCENCE_TEXTURE=!1,this.IRIDESCENCE_TEXTUREDIRECTUV=0,this.IRIDESCENCE_THICKNESS_TEXTURE=!1,this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0,this.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE=!1}}class E_ extends ha{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRIridescence",110,new S_,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=E_._DefaultMinimumThickness,this.maximumThickness=E_._DefaultMaximumThickness,this.indexOfRefraction=E_._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&Bs.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._thicknessTexture&&Bs.IridescenceTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){var i;this._isEnabled?(e.IRIDESCENCE=!0,e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE=null!==this._texture&&this._texture._texture===(null===(i=this._thicknessTexture)||void 0===i?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._thicknessTexture),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Bs.IridescenceTextureEnabled?It.G.PrepareDefinesForMergedUV(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,!e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&this._thicknessTexture&&Bs.IridescenceTextureEnabled?It.G.PrepareDefinesForMergedUV(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_USE_THICKNESS_FROM_MAINTEXTURE=!1,e.IRIDESCENCE_TEXTUREDIRECTUV=0,e.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0)}bindForSubMesh(e,t,i,n){var s,r,o,a,l,h,c,d;if(!this._isEnabled)return;const u=n.materialDefines,p=this._material.isFrozen,f=u.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE;e.useUbo&&p&&e.isSync||(f&&Bs.IridescenceTextureEnabled?(e.updateFloat4("vIridescenceInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),It.G.BindTextureMatrix(this._texture,e,"iridescence")):(this._texture||this._thicknessTexture)&&Bs.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",null!==(r=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==r?r:0,null!==(a=null===(o=this._texture)||void 0===o?void 0:o.level)&&void 0!==a?a:0,null!==(h=null===(l=this._thicknessTexture)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(d=null===(c=this._thicknessTexture)||void 0===c?void 0:c.level)&&void 0!==d?d:0),this._texture&&It.G.BindTextureMatrix(this._texture,e,"iridescence"),!this._thicknessTexture||f||u.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE||It.G.BindTextureMatrix(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&Bs.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&!f&&!u.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&Bs.IridescenceTextureEnabled&&e.setTexture("iridescenceThicknessSampler",this._thicknessTexture))}hasTexture(e){return this._texture===e||this._thicknessTexture===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._thicknessTexture&&e.push(this._thicknessTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture)}dispose(e){var t,i;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._thicknessTexture)||void 0===i||i.dispose())}getClassName(){return"PBRIridescenceConfiguration"}addFallbacks(e,t,i){return e.IRIDESCENCE&&t.addFallback(i++,"IRIDESCENCE"),i}getSamplers(e){e.push("iridescenceSampler","iridescenceThicknessSampler")}getUniforms(){return{ubo:[{name:"vIridescenceParams",size:4,type:"vec4"},{name:"vIridescenceInfos",size:4,type:"vec4"},{name:"iridescenceMatrix",size:16,type:"mat4"},{name:"iridescenceThicknessMatrix",size:16,type:"mat4"}]}}}E_._DefaultMinimumThickness=100,E_._DefaultMaximumThickness=400,E_._DefaultIndexOfRefraction=1.3,(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],E_.prototype,"isEnabled",void 0),(0,oe.gn)([(0,E.qC)()],E_.prototype,"intensity",void 0),(0,oe.gn)([(0,E.qC)()],E_.prototype,"minimumThickness",void 0),(0,oe.gn)([(0,E.qC)()],E_.prototype,"maximumThickness",void 0),(0,oe.gn)([(0,E.qC)()],E_.prototype,"indexOfRefraction",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],E_.prototype,"texture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],E_.prototype,"thicknessTexture",void 0);class x_ extends Tt.H{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}}class b_ extends ha{set angle(e){this.direction.x=Math.cos(e),this.direction.y=Math.sin(e)}get angle(){return Math.atan2(this.direction.y,this.direction.x)}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markAllSubMeshesAsMiscDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRAnisotropic",110,new x_,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new o.FM(1,0),this._texture=null,this.texture=null,this._legacy=!1,this.legacy=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16]}isReadyForSubMesh(e,t){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&this._texture&&Bs.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(ne.o.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Bs.AnisotropicTextureEnabled?It.G.PrepareDefinesForMergedUV(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&&Bs.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),It.G.BindTextureMatrix(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&Bs.AnisotropicTextureEnabled&&e.setTexture("anisotropySampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){e&&this._texture&&this._texture.dispose()}getClassName(){return"PBRAnisotropicConfiguration"}addFallbacks(e,t,i){return e.ANISOTROPIC&&t.addFallback(i++,"ANISOTROPIC"),i}getSamplers(e){e.push("anisotropySampler")}getUniforms(){return{ubo:[{name:"vAnisotropy",size:3,type:"vec3"},{name:"vAnisotropyInfos",size:2,type:"vec2"},{name:"anisotropyMatrix",size:16,type:"mat4"}]}}parse(e,t,i){super.parse(e,t,i),void 0===e.legacy&&(this.legacy=!0)}}(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],b_.prototype,"isEnabled",void 0),(0,oe.gn)([(0,E.qC)()],b_.prototype,"intensity",void 0),(0,oe.gn)([(0,E.QC)()],b_.prototype,"direction",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],b_.prototype,"texture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsMiscDirty")],b_.prototype,"legacy",void 0);class C_ extends Tt.H{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,this.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=!1}}class y_ extends ha{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"Sheen",120,new C_,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=a.Wo.White(),this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._roughness=null,this.roughness=null,this._textureRoughness=null,this.textureRoughness=null,this._albedoScaling=!1,this.albedoScaling=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&Bs.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._textureRoughness&&Bs.SheenTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){var i;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.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=null!==this._texture&&this._texture._texture===(null===(i=this._textureRoughness)||void 0===i?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._textureRoughness),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Bs.SheenTextureEnabled?(It.G.PrepareDefinesForMergedUV(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&Bs.SheenTextureEnabled?It.G.PrepareDefinesForMergedUV(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_TEXTURE_ROUGHNESS_IDENTICAL=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,i,n){var s,r,o,a,l,h,c,d;if(!this._isEnabled)return;const u=n.materialDefines,p=this._material.isFrozen,f=u.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL;e.useUbo&&p&&e.isSync||(f&&Bs.SheenTextureEnabled?(e.updateFloat4("vSheenInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),It.G.BindTextureMatrix(this._texture,e,"sheen")):(this._texture||this._textureRoughness)&&Bs.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",null!==(r=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==r?r:0,null!==(a=null===(o=this._texture)||void 0===o?void 0:o.level)&&void 0!==a?a:0,null!==(h=null===(l=this._textureRoughness)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(d=null===(c=this._textureRoughness)||void 0===c?void 0:c.level)&&void 0!==d?d:0),this._texture&&It.G.BindTextureMatrix(this._texture,e,"sheen"),!this._textureRoughness||f||u.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE||It.G.BindTextureMatrix(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&&Bs.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!f&&!u.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&Bs.SheenTextureEnabled&&e.setTexture("sheenRoughnessSampler",this._textureRoughness))}hasTexture(e){return this._texture===e||this._textureRoughness===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness)}dispose(e){var t,i;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._textureRoughness)||void 0===i||i.dispose())}getClassName(){return"PBRSheenConfiguration"}addFallbacks(e,t,i){return e.SHEEN&&t.addFallback(i++,"SHEEN"),i}getSamplers(e){e.push("sheenSampler","sheenRoughnessSampler")}getUniforms(){return{ubo:[{name:"vSheenColor",size:4,type:"vec4"},{name:"vSheenRoughness",size:1,type:"float"},{name:"vSheenInfos",size:4,type:"vec4"},{name:"sheenMatrix",size:16,type:"mat4"},{name:"sheenRoughnessMatrix",size:16,type:"mat4"}]}}}(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],y_.prototype,"isEnabled",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],y_.prototype,"linkSheenWithAlbedo",void 0),(0,oe.gn)([(0,E.qC)()],y_.prototype,"intensity",void 0),(0,oe.gn)([(0,E.n9)()],y_.prototype,"color",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],y_.prototype,"texture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],y_.prototype,"useRoughnessFromMainTexture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],y_.prototype,"roughness",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],y_.prototype,"textureRoughness",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],y_.prototype,"albedoScaling",void 0);class A_ extends Tt.H{constructor(){super(...arguments),this.SUBSURFACE=!1,this.SS_REFRACTION=!1,this.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,this.SS_TRANSLUCENCY=!1,this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!1,this.SS_SCATTERING=!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_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_MASK_FROM_THICKNESS_TEXTURE=!1,this.SS_USE_GLTF_TEXTURES=!1}}class R_ extends ha{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()}constructor(e,t=!0){super(e,"PBRSubSurface",130,new A_,t),this._isRefractionEnabled=!1,this.isRefractionEnabled=!1,this._isTranslucencyEnabled=!1,this.isTranslucencyEnabled=!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=a.Wo.White(),this.tintColorAtDistance=1,this.diffusionDistance=a.Wo.White(),this._useMaskFromThicknessTexture=!1,this.useMaskFromThicknessTexture=!1,this._refractionIntensityTexture=null,this.refractionIntensityTexture=null,this._translucencyIntensityTexture=null,this.translucencyIntensityTexture=null,this._useGltfStyleTextures=!1,this.useGltfStyleTextures=!1,this._scene=e.getScene(),this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkScenePrePassDirty=e._dirtyCallbacks[32]}isReadyForSubMesh(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&Bs.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;const e=this._getRefractionTexture(t);if(e&&Bs.RefractionTextureEnabled&&!e.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return e.SUBSURFACE=!1,e.SS_TRANSLUCENCY=!1,e.SS_SCATTERING=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!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_MASK_FROM_THICKNESS_TEXTURE=!1,void(e.SS_USE_GLTF_TEXTURES=!1);if(e._areTexturesDirty){e.SUBSURFACE=!0,e.SS_TRANSLUCENCY=this._isTranslucencyEnabled,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!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_MASK_FROM_THICKNESS_TEXTURE=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!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;const i=!!this._thicknessTexture&&!!this._refractionIntensityTexture&&this._refractionIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._refractionIntensityTexture._texture===this._thicknessTexture._texture,n=!!this._thicknessTexture&&!!this._translucencyIntensityTexture&&this._translucencyIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._translucencyIntensityTexture._texture===this._thicknessTexture._texture,s=(i||!this._refractionIntensityTexture)&&(n||!this._translucencyIntensityTexture);if(e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&Bs.ThicknessTextureEnabled&&It.G.PrepareDefinesForMergedUV(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&Bs.RefractionIntensityTextureEnabled&&!s&&It.G.PrepareDefinesForMergedUV(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&Bs.TranslucencyIntensityTextureEnabled&&!s&&It.G.PrepareDefinesForMergedUV(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE")),e.SS_HAS_THICKNESS=this.maximumThickness-this.minimumThickness!=0,e.SS_MASK_FROM_THICKNESS_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture||!!this._translucencyIntensityTexture)&&s,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture)&&s,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._translucencyIntensityTexture)&&s,this._isRefractionEnabled&&t.texturesEnabled){const i=this._getRefractionTexture(t);i&&Bs.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)return;n.getRenderingMesh().getWorldMatrix().decompose(o.jp.Vector3[0]);const s=Math.max(Math.abs(o.jp.Vector3[0].x),Math.abs(o.jp.Vector3[0].y),Math.abs(o.jp.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*s,(this.maximumThickness-this.minimumThickness)*s)}bindForSubMesh(e,t,i,n){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;const s=n.materialDefines,r=this._material.isFrozen,o=this._material.realTimeFiltering,a=s.LODBASEDMICROSFURACE,l=this._getRefractionTexture(t);if(!e.useUbo||!r||!e.isSync){if(this._thicknessTexture&&Bs.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),It.G.BindTextureMatrix(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&Bs.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),It.G.BindTextureMatrix(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyIntensityTexture&&Bs.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),It.G.BindTextureMatrix(this._translucencyIntensityTexture,e,"translucencyIntensity")),l&&Bs.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),o&&e.updateFloat2("vRefractionFilteringInfo",i,S.R.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.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,0)}t.texturesEnabled&&(this._thicknessTexture&&Bs.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&Bs.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&Bs.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),l&&Bs.RefractionTextureEnabled&&(a?e.setTexture("refractionSampler",l):(e.setTexture("refractionSampler",l._lodTextureMid||l),e.setTexture("refractionSamplerLow",l._lodTextureLow||l),e.setTexture("refractionSamplerHigh",l._lodTextureHigh||l))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){Bs.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e}hasRenderTargetTextures(){return!!(Bs.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)}getActiveTextures(e){this._thicknessTexture&&e.push(this._thicknessTexture),this._refractionTexture&&e.push(this._refractionTexture)}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)}dispose(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.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")}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"}]}}}(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],R_.prototype,"isRefractionEnabled",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],R_.prototype,"isTranslucencyEnabled",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markScenePrePassDirty")],R_.prototype,"isScatteringEnabled",void 0),(0,oe.gn)([(0,E.qC)()],R_.prototype,"_scatteringDiffusionProfileIndex",void 0),(0,oe.gn)([(0,E.qC)()],R_.prototype,"refractionIntensity",void 0),(0,oe.gn)([(0,E.qC)()],R_.prototype,"translucencyIntensity",void 0),(0,oe.gn)([(0,E.qC)()],R_.prototype,"useAlbedoToTintRefraction",void 0),(0,oe.gn)([(0,E.qC)()],R_.prototype,"useAlbedoToTintTranslucency",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],R_.prototype,"thicknessTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],R_.prototype,"refractionTexture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],R_.prototype,"indexOfRefraction",void 0),(0,oe.gn)([(0,E.qC)()],R_.prototype,"_volumeIndexOfRefraction",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],R_.prototype,"volumeIndexOfRefraction",null),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],R_.prototype,"invertRefractionY",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],R_.prototype,"linkRefractionWithTransparency",void 0),(0,oe.gn)([(0,E.qC)()],R_.prototype,"minimumThickness",void 0),(0,oe.gn)([(0,E.qC)()],R_.prototype,"maximumThickness",void 0),(0,oe.gn)([(0,E.qC)()],R_.prototype,"useThicknessAsDepth",void 0),(0,oe.gn)([(0,E.n9)()],R_.prototype,"tintColor",void 0),(0,oe.gn)([(0,E.qC)()],R_.prototype,"tintColorAtDistance",void 0),(0,oe.gn)([(0,E.n9)()],R_.prototype,"diffusionDistance",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],R_.prototype,"useMaskFromThicknessTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],R_.prototype,"refractionIntensityTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],R_.prototype,"translucencyIntensityTexture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],R_.prototype,"useGltfStyleTextures",void 0);const P_={effect:null,subMesh:null};class I_ extends Tt.H{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.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_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=!1,this.TONEMAPPING_ACES=!1,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.DEBUGMODE=0,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0}}class M_ extends pt{get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(1)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)}get canRenderToMRT(){return!0}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}constructor(e,t){super(e,t),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new o.Lt(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=M_.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=a.Wo.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new a.Wo(0,0,0),this._albedoColor=new a.Wo(1,1,1),this._reflectivityColor=new a.Wo(1,1,1),this._reflectionColor=new a.Wo(1,1,1),this._emissiveColor=new a.Wo(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=M_.LIGHTFALLOFF_PHYSICAL,this._useRadianceOverAlpha=!0,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this._parallaxScaleBias=.05,this._disableLighting=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._alphaCutOff=.4,this._forceAlphaTest=!1,this._useAlphaFresnel=!1,this._useLinearAlphaFresnel=!1,this._environmentBRDFTexture=null,this._forceIrradianceInFragment=!1,this._realTimeFiltering=!1,this._realTimeFilteringQuality=8,this._forceNormalForward=!1,this._enableSpecularAntiAliasing=!1,this._imageProcessingObserver=null,this._renderTargets=new Wt.t(16),this._globalAmbientColor=new a.Wo(0,0,0),this._useLogarithmicDepth=!1,this._unlit=!1,this._debugMode=0,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new Hp(this),this.clearCoat=new T_(this),this.iridescence=new E_(this),this.anisotropy=new b_(this),this.sheen=new y_(this),this.subSurface=new R_(this),this.detailMap=new da(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),Bs.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=zp(this.getScene()),this.prePassConfiguration=new ws}get hasRenderTargetTextures(){return!!(Bs.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported}get _disableAlphaBlending(){var e;return this._transparencyMode===M_.PBRMATERIAL_OPAQUE||this._transparencyMode===M_.PBRMATERIAL_ALPHATEST||(null===(e=this.subSurface)||void 0===e?void 0:e.disableAlphaBlending)}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromAlbedoTexture())}needAlphaTesting(){var e;return!!this._forceAlphaTest||!(null===(e=this.subSurface)||void 0===e?void 0:e.disableAlphaBlending)&&(this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===M_.PBRMATERIAL_ALPHATEST))}_shouldUseAlphaFromAlbedoTexture(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==M_.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){var n;if(this._uniformBufferLayoutBuilt||this.buildUniformLayout(),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(Ls.S.GetDefineNames,this._eventInfo),t.materialDefines=new I_(this._eventInfo.defineNames));const s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const r=this.getScene(),o=r.getEngine();if(s._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,r.texturesEnabled)){if(this._albedoTexture&&Bs.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking())return!1;if(this._ambientTexture&&Bs.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking())return!1;if(this._opacityTexture&&Bs.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;const e=this._getReflectionTexture();if(e&&Bs.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;if(e.irradianceTexture){if(!e.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!e.sphericalPolynomial&&(null===(n=e.getInternalTexture())||void 0===n?void 0:n._sphericalPolynomialPromise))return!1}if(this._lightmapTexture&&Bs.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking())return!1;if(this._emissiveTexture&&Bs.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(Bs.SpecularTextureEnabled){if(this._metallicTexture){if(!this._metallicTexture.isReadyOrNotBlocking())return!1}else if(this._reflectivityTexture&&!this._reflectivityTexture.isReadyOrNotBlocking())return!1;if(this._metallicReflectanceTexture&&!this._metallicReflectanceTexture.isReadyOrNotBlocking())return!1;if(this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking())return!1;if(this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(o.getCaps().standardDerivatives&&this._bumpTexture&&Bs.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady())return!1;if(this._environmentBRDFTexture&&Bs.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(s._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;o.getCaps().standardDerivatives||e.isVerticesDataPresent(ne.o.NormalKind)||(e.createNormals(!0),p.Y.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));const a=t.effect,l=s._areLightsDisposed;let h=this._prepareEffect(e,s,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),c=!1;if(h)if(this._onEffectCreatedObservable&&(P_.effect=h,P_.subMesh=t,this._onEffectCreatedObservable.notifyObservers(P_)),this.allowShaderHotSwapping&&a&&!h.isReady()){if(h=a,s.markAsUnprocessed(),c=this.isFrozen,l)return s._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(h,s,this._materialContext);return!(!t.effect||!t.effect.isReady())&&(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!c,t.effect._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),!0)}isMetallicWorkflow(){return!(null==this._metallic&&null==this._roughness&&!this._metallicTexture)}_prepareEffect(e,t,i=null,n=null,s=null,r=null,o){if(this._prepareDefines(e,t,s,r,o),!t.isDirty)return null;t.markAsProcessed();const a=this.getScene().getEngine(),l=new zt;let h=0;t.USESPHERICALINVERTEX&&l.addFallback(h++,"USESPHERICALINVERTEX"),t.FOG&&l.addFallback(h,"FOG"),t.SPECULARAA&&l.addFallback(h,"SPECULARAA"),t.POINTSIZE&&l.addFallback(h,"POINTSIZE"),t.LOGARITHMICDEPTH&&l.addFallback(h,"LOGARITHMICDEPTH"),t.PARALLAX&&l.addFallback(h,"PARALLAX"),t.PARALLAXOCCLUSION&&l.addFallback(h++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&l.addFallback(h++,"ENVIRONMENTBRDF"),t.TANGENT&&l.addFallback(h++,"TANGENT"),t.BUMP&&l.addFallback(h++,"BUMP"),h=It.G.HandleFallbacksForShadows(t,l,this._maxSimultaneousLights,h++),t.SPECULARTERM&&l.addFallback(h++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&l.addFallback(h++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&l.addFallback(h++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&l.addFallback(h++,"LIGHTMAP"),t.NORMAL&&l.addFallback(h++,"NORMAL"),t.AMBIENT&&l.addFallback(h++,"AMBIENT"),t.EMISSIVE&&l.addFallback(h++,"EMISSIVE"),t.VERTEXCOLOR&&l.addFallback(h++,"VERTEXCOLOR"),t.MORPHTARGETS&&l.addFallback(h++,"MORPHTARGETS"),t.MULTIVIEW&&l.addFallback(0,"MULTIVIEW");const c=[ne.o.PositionKind];t.NORMAL&&c.push(ne.o.NormalKind),t.TANGENT&&c.push(ne.o.TangentKind);for(let v=1;v<=6;++v)t["UV"+v]&&c.push(`uv${1===v?"":v}`);t.VERTEXCOLOR&&c.push(ne.o.ColorKind),t.INSTANCESCOLOR&&c.push(ne.o.ColorInstanceKind),It.G.PrepareAttributesForBones(c,e,t,l),It.G.PrepareAttributesForInstances(c,t),It.G.PrepareAttributesForMorphTargets(c,e,t),It.G.PrepareAttributesForBakedVertexAnimation(c,e,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"],p=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],f=["Material","Scene","Mesh"];this._eventInfo.fallbacks=l,this._eventInfo.fallbackRank=h,this._eventInfo.defines=t,this._eventInfo.uniforms=u,this._eventInfo.attributes=c,this._eventInfo.samplers=p,this._eventInfo.uniformBuffersNames=f,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._callbackPluginEventGeneric(Ls.S.PrepareEffect,this._eventInfo),ws.AddUniforms(u),ws.AddSamplers(p),(0,ua.qx)(u),ii.$&&(ii.$.PrepareUniforms(u,t),ii.$.PrepareSamplers(p,t)),It.G.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:f,samplers:p,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});const _={};this.customShaderNameResolve&&(d=this.customShaderNameResolve(d,u,f,p,t,c,_));const m=t.toString(),g=a.createEffect(d,{attributes:c,uniformsNames:u,uniformBuffersNames:f,samplers:p,defines:m,fallbacks:l,onCompiled:i,onError:n,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS},processFinalCode:_.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS},a);return this._eventInfo.customCode=void 0,g}_prepareDefines(e,t,i=null,n=null,s=!1){var r;const o=this.getScene(),a=o.getEngine();It.G.PrepareDefinesForLights(o,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,It.G.PrepareDefinesForMultiview(o,t);const l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(It.G.PrepareDefinesForPrePass(o,t,this.canRenderToMRT&&!l),It.G.PrepareDefinesForOIT(o,t,l),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let e=1;e<=6;++e)t["MAINUV"+e]=!1;if(o.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&&Bs.DiffuseTextureEnabled?(It.G.PrepareDefinesForMergedUV(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&Bs.AmbientTextureEnabled?(It.G.PrepareDefinesForMergedUV(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&Bs.OpacityTextureEnabled?(It.G.PrepareDefinesForMergedUV(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;const e=this._getReflectionTexture();if(e&&Bs.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===Le.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 Le.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case Le.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case Le.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case Le.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case Le.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case Le.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Le.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Le.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Le.CUBIC_MODE:case Le.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize}e.coordinatesMode!==Le.SKYBOX_MODE&&(e.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):e.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||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;if(this._lightmapTexture&&Bs.LightmapTextureEnabled?(It.G.PrepareDefinesForMergedUV(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&Bs.EmissiveTextureEnabled?(It.G.PrepareDefinesForMergedUV(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,Bs.SpecularTextureEnabled){if(this._metallicTexture?(It.G.PrepareDefinesForMergedUV(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?(It.G.PrepareDefinesForMergedUV(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){const e=null!==this._metallicReflectanceTexture&&this._metallicReflectanceTexture._texture===(null===(r=this._reflectanceTexture)||void 0===r?void 0:r._texture)&&this._metallicReflectanceTexture.checkTransformsAreIdentical(this._reflectanceTexture);t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture&&!e,this._metallicReflectanceTexture?(It.G.PrepareDefinesForMergedUV(this._metallicReflectanceTexture,t,"METALLIC_REFLECTANCE"),t.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):t.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&!e&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(It.G.PrepareDefinesForMergedUV(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1}else t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1;this._microSurfaceTexture?It.G.PrepareDefinesForMergedUV(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1}else t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1;a.getCaps().standardDerivatives&&this._bumpTexture&&Bs.BumpTextureEnabled&&!this._disableBumpMap?(It.G.PrepareDefinesForMergedUV(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&Bs.DiffuseTextureEnabled?(t.PARALLAX=!0,t.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):t.PARALLAX=!1,t.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):(t.BUMP=!1,t.PARALLAX=!1,t.PARALLAXOCCLUSION=!1,t.OBJECTSPACE_NORMALMAP=!1),this._environmentBRDFTexture&&Bs.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===M_.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===M_.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=7===this.alphaMode||8===this.alphaMode,t.ALPHABLEND=this.needAlphaBlendingForMesh(e),t.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,t.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel),t._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(t),t.FORCENORMALFORWARD=this._forceNormalForward,t.RADIANCEOCCLUSION=this._useRadianceOcclusion,t.HORIZONOCCLUSION=this._useHorizonOcclusion,t._areMiscDirty&&(It.G.PrepareDefinesForMisc(e,o,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,t),t.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(ne.o.NormalKind),t.DEBUGMODE=this._debugMode),It.G.PrepareDefinesForFrameBoundValues(o,a,this,t,!!i,n,s),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),It.G.PrepareDefinesForAttributes(e,t,!0,!0,!0,this._transparencyMode!==M_.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){const n=Object.assign({clipPlane:!1,useInstances:!1},i);this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(Ls.S.GetDefineNames,this._eventInfo);const s=new I_(this._eventInfo.defineNames),r=this._prepareEffect(e,s,void 0,void 0,n.useInstances,n.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(P_.effect=r,P_.subMesh=null,this._onEffectCreatedObservable.notifyObservers(P_)),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){var n,s,r,o;const l=this.getScene(),h=i.materialDefines;if(!h)return;const c=i.effect;if(!c)return;this._activeEffect=c,t.getMeshUniformBuffer().bindToEffect(c,"Mesh"),t.transferToEffect(e);const d=l.getEngine();this._uniformBuffer.bindToEffect(c,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,l,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),h.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const u=c._forceRebindOnNextCall||this._mustRebind(l,c,t.visibility);It.G.BindBonesParameters(t,this._activeEffect,this.prePassConfiguration);let p=null;const f=this._uniformBuffer;if(u){if(this.bindViewProjection(c),p=this._getReflectionTexture(),!f.useUbo||!this.isFrozen||!f.isSync||c._forceRebindOnNextCall){if(l.texturesEnabled){if(this._albedoTexture&&Bs.DiffuseTextureEnabled&&(f.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),It.G.BindTextureMatrix(this._albedoTexture,f,"albedo")),this._ambientTexture&&Bs.AmbientTextureEnabled&&(f.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),It.G.BindTextureMatrix(this._ambientTexture,f,"ambient")),this._opacityTexture&&Bs.OpacityTextureEnabled&&(f.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),It.G.BindTextureMatrix(this._opacityTexture,f,"opacity")),p&&Bs.ReflectionTextureEnabled){if(f.updateMatrix("reflectionMatrix",p.getReflectionTextureMatrix()),f.updateFloat2("vReflectionInfos",p.level,0),p.boundingBoxSize){const e=p;f.updateVector3("vReflectionPosition",e.boundingBoxPosition),f.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this.realTimeFiltering){const e=p.getSize().width;f.updateFloat2("vReflectionFilteringInfo",e,S.R.Log2(e))}if(!h.USEIRRADIANCEMAP){const e=p.sphericalPolynomial;if(h.USESPHERICALFROMREFLECTIONMAP&&e)if(h.SPHERICAL_HARMONICS){const t=e.preScaledHarmonics;f.updateVector3("vSphericalL00",t.l00),f.updateVector3("vSphericalL1_1",t.l1_1),f.updateVector3("vSphericalL10",t.l10),f.updateVector3("vSphericalL11",t.l11),f.updateVector3("vSphericalL2_2",t.l2_2),f.updateVector3("vSphericalL2_1",t.l2_1),f.updateVector3("vSphericalL20",t.l20),f.updateVector3("vSphericalL21",t.l21),f.updateVector3("vSphericalL22",t.l22)}else f.updateFloat3("vSphericalX",e.x.x,e.x.y,e.x.z),f.updateFloat3("vSphericalY",e.y.x,e.y.y,e.y.z),f.updateFloat3("vSphericalZ",e.z.x,e.z.y,e.z.z),f.updateFloat3("vSphericalXX_ZZ",e.xx.x-e.zz.x,e.xx.y-e.zz.y,e.xx.z-e.zz.z),f.updateFloat3("vSphericalYY_ZZ",e.yy.x-e.zz.x,e.yy.y-e.zz.y,e.yy.z-e.zz.z),f.updateFloat3("vSphericalZZ",e.zz.x,e.zz.y,e.zz.z),f.updateFloat3("vSphericalXY",e.xy.x,e.xy.y,e.xy.z),f.updateFloat3("vSphericalYZ",e.yz.x,e.yz.y,e.yz.z),f.updateFloat3("vSphericalZX",e.zx.x,e.zx.y,e.zx.z)}f.updateFloat3("vReflectionMicrosurfaceInfos",p.getSize().width,p.lodGenerationScale,p.lodGenerationOffset)}this._emissiveTexture&&Bs.EmissiveTextureEnabled&&(f.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),It.G.BindTextureMatrix(this._emissiveTexture,f,"emissive")),this._lightmapTexture&&Bs.LightmapTextureEnabled&&(f.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),It.G.BindTextureMatrix(this._lightmapTexture,f,"lightmap")),Bs.SpecularTextureEnabled&&(this._metallicTexture?(f.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),It.G.BindTextureMatrix(this._metallicTexture,f,"reflectivity")):this._reflectivityTexture&&(f.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),It.G.BindTextureMatrix(this._reflectivityTexture,f,"reflectivity")),this._metallicReflectanceTexture&&(f.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),It.G.BindTextureMatrix(this._metallicReflectanceTexture,f,"metallicReflectance")),this._reflectanceTexture&&h.REFLECTANCE&&(f.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),It.G.BindTextureMatrix(this._reflectanceTexture,f,"reflectance")),this._microSurfaceTexture&&(f.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),It.G.BindTextureMatrix(this._microSurfaceTexture,f,"microSurfaceSampler"))),this._bumpTexture&&d.getCaps().standardDerivatives&&Bs.BumpTextureEnabled&&!this._disableBumpMap&&(f.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),It.G.BindTextureMatrix(this._bumpTexture,f,"bump"),l._mirroredCameraPosition?f.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):f.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&f.updateFloat("pointSize",this.pointSize),h.METALLICWORKFLOW){a.zZ.Color3[0].r=void 0===this._metallic||null===this._metallic?1:this._metallic,a.zZ.Color3[0].g=void 0===this._roughness||null===this._roughness?1:this._roughness,f.updateColor4("vReflectivityColor",a.zZ.Color3[0],1);const e=null!==(s=null===(n=this.subSurface)||void 0===n?void 0:n._indexOfRefraction)&&void 0!==s?s:1.5,t=1,i=Math.pow((e-t)/(e+t),2);this._metallicReflectanceColor.scaleToRef(i*this._metallicF0Factor,a.zZ.Color3[0]);const r=this._metallicF0Factor;f.updateColor4("vMetallicReflectanceFactors",a.zZ.Color3[0],r)}else f.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);f.updateColor3("vEmissiveColor",Bs.EmissiveTextureEnabled?this._emissiveColor:a.Wo.BlackReadOnly),f.updateColor3("vReflectionColor",this._reflectionColor),!h.SS_REFRACTION&&(null===(r=this.subSurface)||void 0===r?void 0:r._linkRefractionWithTransparency)?f.updateColor4("vAlbedoColor",this._albedoColor,1):f.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*l.environmentIntensity,this._lightingInfos.w=this._specularIntensity,f.updateVector4("vLightingIntensity",this._lightingInfos),l.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),f.updateColor3("vAmbientColor",this._globalAmbientColor),f.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}l.texturesEnabled&&(this._albedoTexture&&Bs.DiffuseTextureEnabled&&f.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&Bs.AmbientTextureEnabled&&f.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&Bs.OpacityTextureEnabled&&f.setTexture("opacitySampler",this._opacityTexture),p&&Bs.ReflectionTextureEnabled&&(h.LODBASEDMICROSFURACE?f.setTexture("reflectionSampler",p):(f.setTexture("reflectionSampler",p._lodTextureMid||p),f.setTexture("reflectionSamplerLow",p._lodTextureLow||p),f.setTexture("reflectionSamplerHigh",p._lodTextureHigh||p)),h.USEIRRADIANCEMAP&&f.setTexture("irradianceSampler",p.irradianceTexture)),h.ENVIRONMENTBRDF&&f.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&Bs.EmissiveTextureEnabled&&f.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&Bs.LightmapTextureEnabled&&f.setTexture("lightmapSampler",this._lightmapTexture),Bs.SpecularTextureEnabled&&(this._metallicTexture?f.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&f.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&f.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&h.REFLECTANCE&&f.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&f.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&d.getCaps().standardDerivatives&&Bs.BumpTextureEnabled&&!this._disableBumpMap&&f.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(c),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),(0,ua.an)(this._activeEffect,this,l),this.bindEyePosition(c)}else l.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!u&&this.isFrozen||(l.lightsEnabled&&!this._disableLighting&&It.G.BindLights(l,t,this._activeEffect,h,this._maxSimultaneousLights),(l.fogEnabled&&t.applyFog&&l.fogMode!==N.x.FOGMODE_NONE||p||t.receiveShadows||h.PREPASS)&&this.bindView(c),It.G.BindFogParameters(l,t,this._activeEffect,!0),h.NUM_MORPH_INFLUENCERS&&It.G.BindMorphTargetParameters(t,this._activeEffect),h.BAKED_VERTEX_ANIMATION_TEXTURE&&(null===(o=t.bakedVertexAnimationManager)||void 0===o||o.bind(c,h.INSTANCES)),this._imageProcessingConfiguration.bind(this._activeEffect),It.G.BindLogDepth(h,this._activeEffect,l)),this._afterBind(t,this._activeEffect),f.update()}getAnimatables(){const e=super.getAnimatables();return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&e.push(this._albedoTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?e.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&e.push(this._reflectivityTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._metallicReflectanceTexture&&this._metallicReflectanceTexture.animations&&this._metallicReflectanceTexture.animations.length>0&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&this._reflectanceTexture.animations&&this._reflectanceTexture.animations.length>0&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&this._microSurfaceTexture.animations&&this._microSurfaceTexture.animations.length>0&&e.push(this._microSurfaceTexture),e}_getReflectionTexture(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture}getActiveTextures(){const e=super.getActiveTextures();return this._albedoTexture&&e.push(this._albedoTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._reflectivityTexture&&e.push(this._reflectivityTexture),this._metallicTexture&&e.push(this._metallicTexture),this._metallicReflectanceTexture&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&e.push(this._microSurfaceTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),e}hasTexture(e){return!!super.hasTexture(e)||(this._albedoTexture===e||(this._ambientTexture===e||(this._opacityTexture===e||(this._reflectionTexture===e||(this._emissiveTexture===e||(this._reflectivityTexture===e||(this._metallicTexture===e||(this._metallicReflectanceTexture===e||(this._reflectanceTexture===e||(this._microSurfaceTexture===e||(this._bumpTexture===e||this._lightmapTexture===e)))))))))))}setPrePassRenderer(){var e;if(!(null===(e=this.subSurface)||void 0===e?void 0:e.isScatteringEnabled))return!1;const t=this.getScene().enableSubSurfaceForPrePass();return t&&(t.enabled=!0),!0}dispose(e,t){var i,n,s,r,o,a,l,h,c,d,u,p;t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),null===(i=this._albedoTexture)||void 0===i||i.dispose(),null===(n=this._ambientTexture)||void 0===n||n.dispose(),null===(s=this._opacityTexture)||void 0===s||s.dispose(),null===(r=this._reflectionTexture)||void 0===r||r.dispose(),null===(o=this._emissiveTexture)||void 0===o||o.dispose(),null===(a=this._metallicTexture)||void 0===a||a.dispose(),null===(l=this._reflectivityTexture)||void 0===l||l.dispose(),null===(h=this._bumpTexture)||void 0===h||h.dispose(),null===(c=this._lightmapTexture)||void 0===c||c.dispose(),null===(d=this._metallicReflectanceTexture)||void 0===d||d.dispose(),null===(u=this._reflectanceTexture)||void 0===u||u.dispose(),null===(p=this._microSurfaceTexture)||void 0===p||p.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}}M_.PBRMATERIAL_OPAQUE=ut.F.MATERIAL_OPAQUE,M_.PBRMATERIAL_ALPHATEST=ut.F.MATERIAL_ALPHATEST,M_.PBRMATERIAL_ALPHABLEND=ut.F.MATERIAL_ALPHABLEND,M_.PBRMATERIAL_ALPHATESTANDBLEND=ut.F.MATERIAL_ALPHATESTANDBLEND,M_.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,M_.LIGHTFALLOFF_PHYSICAL=0,M_.LIGHTFALLOFF_GLTF=1,M_.LIGHTFALLOFF_STANDARD=2,(0,oe.gn)([(0,E.rX)()],M_.prototype,"_imageProcessingConfiguration",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsMiscDirty")],M_.prototype,"debugMode",void 0),(0,oe.gn)([(0,E.qC)()],M_.prototype,"useLogarithmicDepth",null);class O_ extends M_{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===M_.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?M_.LIGHTFALLOFF_PHYSICAL:M_.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===M_.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?M_.LIGHTFALLOFF_GLTF:M_.LIGHTFALLOFF_STANDARD)}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}constructor(e,t){super(e,t),this.directIntensity=1,this.emissiveIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.disableBumpMap=!1,this.ambientTextureStrength=1,this.ambientTextureImpactOnAnalyticalLights=O_.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=a.Wo.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new a.Wo(0,0,0),this.albedoColor=new a.Wo(1,1,1),this.reflectivityColor=new a.Wo(1,1,1),this.reflectionColor=new a.Wo(1,1,1),this.emissiveColor=new a.Wo(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._environmentBRDFTexture=zp(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){const n=E.p4.Clone((()=>new O_(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=E.p4.Parse((()=>new O_(e.name,t)),e,t,i);return e.stencil&&n.stencil.parse(e.stencil,t,i),ut.F._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}}O_.PBRMATERIAL_OPAQUE=M_.PBRMATERIAL_OPAQUE,O_.PBRMATERIAL_ALPHATEST=M_.PBRMATERIAL_ALPHATEST,O_.PBRMATERIAL_ALPHABLEND=M_.PBRMATERIAL_ALPHABLEND,O_.PBRMATERIAL_ALPHATESTANDBLEND=M_.PBRMATERIAL_ALPHATESTANDBLEND,O_.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=M_.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"directIntensity",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"emissiveIntensity",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"environmentIntensity",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"specularIntensity",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"disableBumpMap",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"albedoTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"ambientTexture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"ambientTextureStrength",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],O_.prototype,"opacityTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"reflectionTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"emissiveTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"reflectivityTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"metallicTexture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"metallic",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"roughness",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"metallicF0Factor",void 0),(0,oe.gn)([(0,E.n9)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"metallicReflectanceColor",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"metallicReflectanceTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"reflectanceTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"microSurfaceTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"bumpTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty",null)],O_.prototype,"lightmapTexture",void 0),(0,oe.gn)([(0,E.n9)("ambient"),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"ambientColor",void 0),(0,oe.gn)([(0,E.n9)("albedo"),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"albedoColor",void 0),(0,oe.gn)([(0,E.n9)("reflectivity"),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"reflectivityColor",void 0),(0,oe.gn)([(0,E.n9)("reflection"),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"reflectionColor",void 0),(0,oe.gn)([(0,E.n9)("emissive"),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"emissiveColor",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"microSurface",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useLightmapAsShadowmap",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],O_.prototype,"useAlphaFromAlbedoTexture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],O_.prototype,"forceAlphaTest",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],O_.prototype,"alphaCutOff",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useSpecularOverAlpha",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useRoughnessFromMetallicTextureGreen",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useMetallnessFromMetallicTextureBlue",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useAmbientInGrayScale",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),(0,oe.gn)([(0,E.qC)()],O_.prototype,"usePhysicalLightFalloff",null),(0,oe.gn)([(0,E.qC)()],O_.prototype,"useGLTFLightFalloff",null),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useRadianceOverAlpha",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useObjectSpaceNormalMap",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useParallax",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useParallaxOcclusion",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"parallaxScaleBias",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsLightsDirty")],O_.prototype,"disableLighting",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"forceIrradianceInFragment",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsLightsDirty")],O_.prototype,"maxSimultaneousLights",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"invertNormalMapX",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"invertNormalMapY",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"twoSidedLighting",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useAlphaFresnel",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useLinearAlphaFresnel",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"environmentBRDFTexture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"forceNormalForward",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"enableSpecularAntiAliasing",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useHorizonOcclusion",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useRadianceOcclusion",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsMiscDirty")],O_.prototype,"unlit",void 0),(0,l.H)("BABYLON.PBRMaterial",O_);const D_=131072,N_=131072;function F_(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}const w_=F_("DXT1"),L_=F_("DXT3"),B_=F_("DXT5"),U_=F_("DX10");class V_{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]&D_&&(n=Math.max(1,t[7]));const s=t[21],r=s===U_?i[32]:0;let o=0;switch(s){case 113:o=2;break;case 116:o=1;break;case U_:if(10===r){o=2;break}if(2===r){o=1;break}}return{width:t[4],height:t[3],mipmapCount:n,isFourCC:4==(4&t[20]),isRGB:64==(64&t[20]),isLuminance:(t[20]&N_)===N_,isCube:512==(512&t[28]),isCompressed:s===w_||s===L_||s===B_,dxgiFormat:r,textureType:o}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,n,s,r){const o=new Float32Array(n),a=new Uint16Array(s,i);let l=0;for(let h=0;h>8)}static _GetRGBArrayBuffer(e,t,i,n,s,r,o,a){const l=new Uint8Array(n),h=new Uint8Array(s,i);let c=0;for(let d=0;d>8&255,y>>16&255,y>>24&255)))}var y;const A=V_._ExtractLongWordOrder(d[23]),R=V_._ExtractLongWordOrder(d[24]),P=V_._ExtractLongWordOrder(d[25]),I=V_._ExtractLongWordOrder(d[26]);C&&(E=e._getRGBABufferInternalSizedFormat(n.textureType)),v=1,d[2]&D_&&!1!==s&&(v=Math.max(1,d[7]));const M=a||0,O=e.getCaps();for(let p=M;p0?n.sphericalPolynomial=zh.ConvertCubeMapToSphericalPolynomial({size:d[4],right:h[0],left:h[1],up:h[2],down:h[3],front:h[4],back:h[5],format:5,type:1,gammaSpace:!1}):n.sphericalPolynomial=void 0}}V_.StoreLODInAlphaChannel=!1,Ue.B.prototype.createPrefilteredCubeTexture=function(e,t,i,n,s=null,r=null,o,a=null,l=!0){return this.createCubeTexture(e,t,null,!1,(e=>{if(!e)return void(s&&s(null));const r=e.texture;if(l?e.info.sphericalPolynomial&&(r._sphericalPolynomial=e.info.sphericalPolynomial):r._sphericalPolynomial=new Dh,r._source=Be.S.CubePrefiltered,this.getCaps().textureLOD)return void(s&&s(r));const o=this._gl,a=e.width;if(!a)return;const h=[];for(let s=0;s<3;s++){const l=1-s/2,c=n,d=S.R.Log2(a)*i+n,u=c+(d-c)*l,f=Math.round(Math.min(Math.max(u,0),d)),_=new Be.l(this,Be.S.Temp);if(_.type=r.type,_.format=r.format,_.width=Math.pow(2,Math.max(S.R.Log2(a)-f,0)),_.height=_.width,_.isCube=!0,_._cachedWrapU=0,_._cachedWrapV=0,this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,_,!0),_.samplingMode=2,o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),e.isDDS){const t=e.info,i=e.data;this._unpackFlipY(t.isCompressed),V_.UploadDDSLevels(this,_,i,t,!0,6,f)}else p.Y.Warn("DDS is the only prefiltered cube map supported so far.");this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,null);const m=new Re(t);m._isCube=!0,m._texture=_,_.isReady=!0,h.push(m)}r._lodTextureHigh=h[2],r._lodTextureMid=h[1],r._lodTextureLow=h[0],s&&s(r)}),r,o,a,l,i,n)};fe.D._TextureLoaders.push(new class{constructor(){this.supportCascades=!0}canLoad(e){return e.endsWith(".dds")}loadCubeData(e,t,i,n){const s=t.getEngine();let r,o=!1,a=1e3;if(Array.isArray(e))for(let l=0;l1)&&t.generateMipMaps,s._unpackFlipY(r.isCompressed),V_.UploadDDSLevels(s,t,i,r,o,6,-1,l),r.isFourCC||1!==r.mipmapCount?a=r.mipmapCount-1:s.generateMipMapsForCubemap(t)}else{const n=e;r=V_.GetDDSInfo(n),t.width=r.width,t.height=r.height,i&&(r.sphericalPolynomial=new Dh),o=(r.isRGB||r.isLuminance||r.mipmapCount>1)&&t.generateMipMaps,s._unpackFlipY(r.isCompressed),V_.UploadDDSLevels(s,t,n,r,o,6),r.isFourCC||1!==r.mipmapCount?a=r.mipmapCount-1:s.generateMipMapsForCubemap(t,!1)}s._setCubeMapTextureParams(t,o,a),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n({isDDS:!0,width:t.width,info:r,data:e,texture:t})}loadData(e,t,i){const n=V_.GetDDSInfo(e),s=(n.isRGB||n.isLuminance||n.mipmapCount>1)&&t.generateMipMaps&&n.width>>n.mipmapCount-1==1;i(n.width,n.height,s,n.isFourCC,(()=>{V_.UploadDDSLevels(t.getEngine(),t,e,n,s,1)}))}});fe.D._TextureLoaders.push(new class{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".env")}loadCubeData(e,t,i,n,s){if(Array.isArray(e))return;const r=Kh(e);if(r){t.width=r.width,t.height=r.width;try{ec(t,r),Qh(t,e,r).then((()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n()}),(e=>{null==s||s("Can not upload environment levels",e)}))}catch(o){null==s||s("Can not upload environment file",o)}}else s&&s("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}});class k_{constructor(e,t){if(this.data=e,this.isInvalid=!1,!k_.IsValid(e))return this.isInvalid=!0,void p.Y.Error("texture missing KTX identifier");const i=Uint32Array.BYTES_PER_ELEMENT,n=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),s=67305985===n.getUint32(0,!0);return this.glType=n.getUint32(1*i,s),this.glTypeSize=n.getUint32(2*i,s),this.glFormat=n.getUint32(3*i,s),this.glInternalFormat=n.getUint32(4*i,s),this.glBaseInternalFormat=n.getUint32(5*i,s),this.pixelWidth=n.getUint32(6*i,s),this.pixelHeight=n.getUint32(7*i,s),this.pixelDepth=n.getUint32(8*i,s),this.numberOfArrayElements=n.getUint32(9*i,s),this.numberOfFaces=n.getUint32(10*i,s),this.numberOfMipmapLevels=n.getUint32(11*i,s),this.bytesOfKeyValueData=n.getUint32(12*i,s),0!==this.glType?(p.Y.Error("only compressed formats currently supported"),void(this.isInvalid=!0)):(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0===this.pixelHeight||0!==this.pixelDepth?(p.Y.Error("only 2D textures currently supported"),void(this.isInvalid=!0)):0!==this.numberOfArrayElements?(p.Y.Error("texture arrays not currently supported"),void(this.isInvalid=!0)):this.numberOfFaces!==t?(p.Y.Error("number of faces expected"+t+", but found "+this.numberOfFaces),void(this.isInvalid=!0)):void(this.loadType=k_.COMPRESSED_2D))}uploadLevels(e,t){switch(this.loadType){case k_.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);case k_.TEX_2D:case k_.COMPRESSED_3D:case k_.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=k_.HEADER_LEN+this.bytesOfKeyValueData,n=this.pixelWidth,s=this.pixelHeight;const r=t?this.numberOfMipmapLevels:1;for(let o=0;o=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}}k_.HEADER_LEN=64,k_.COMPRESSED_2D=0,k_.COMPRESSED_3D=1,k_.TEX_2D=2,k_.TEX_3D=3;class G_{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 z_ extends G_{constructor(e,t,i=z_.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length{t(i,(()=>{n(),e.idle&&(e.timeoutId=setTimeout((()=>{e.workerPromise.then((e=>{e.terminate()}));const t=this._workerInfos.indexOf(e);-1!==t&&this._workerInfos.splice(t,1)}),this._options.idleTimeElapsedBeforeRelease))}))}))}}var W_,H_,X_;function Y_(e){return e?se.w1.GetAbsoluteUrl(e):null}function j_(e){null!==e.wasmUASTCToASTC&&(KTX2DECODER.LiteTranscoder_UASTC_ASTC.WasmModuleURL=e.wasmUASTCToASTC),null!==e.wasmUASTCToBC7&&(KTX2DECODER.LiteTranscoder_UASTC_BC7.WasmModuleURL=e.wasmUASTCToBC7),null!==e.wasmUASTCToRGBA_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=e.wasmUASTCToRGBA_UNORM),null!==e.wasmUASTCToRGBA_SRGB&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=e.wasmUASTCToRGBA_SRGB),null!==e.wasmUASTCToR8_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=e.wasmUASTCToR8_UNORM),null!==e.wasmUASTCToRG8_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=e.wasmUASTCToRG8_UNORM),null!==e.jsMSCTranscoder&&(KTX2DECODER.MSCTranscoder.JSModuleURL=e.jsMSCTranscoder),null!==e.wasmMSCTranscoder&&(KTX2DECODER.MSCTranscoder.WasmModuleURL=e.wasmMSCTranscoder),null!==e.wasmZSTDDecoder&&(KTX2DECODER.ZSTDDecoder.WasmModuleURL=e.wasmZSTDDecoder)}z_.DefaultOptions={idleTimeElapsedBeforeRelease:1e3},function(e){e[e.ETC1S=0]="ETC1S",e[e.UASTC4x4=1]="UASTC4x4"}(W_||(W_={})),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"}(H_||(H_={})),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"}(X_||(X_={}));class K_{static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static _Initialize(e){if(K_._WorkerPoolPromise||K_._DecoderModulePromise)return;const t={jsDecoderModule:se.w1.GetAbsoluteUrl(this.URLConfig.jsDecoderModule),wasmUASTCToASTC:Y_(this.URLConfig.wasmUASTCToASTC),wasmUASTCToBC7:Y_(this.URLConfig.wasmUASTCToBC7),wasmUASTCToRGBA_UNORM:Y_(this.URLConfig.wasmUASTCToRGBA_UNORM),wasmUASTCToRGBA_SRGB:Y_(this.URLConfig.wasmUASTCToRGBA_SRGB),wasmUASTCToR8_UNORM:Y_(this.URLConfig.wasmUASTCToR8_UNORM),wasmUASTCToRG8_UNORM:Y_(this.URLConfig.wasmUASTCToRG8_UNORM),jsMSCTranscoder:Y_(this.URLConfig.jsMSCTranscoder),wasmMSCTranscoder:Y_(this.URLConfig.wasmMSCTranscoder),wasmZSTDDecoder:Y_(this.URLConfig.wasmZSTDDecoder)};e&&"function"==typeof Worker&&"undefined"!=typeof URL?K_._WorkerPoolPromise=new Promise((i=>{const n=`${j_}(${q_})()`,s=URL.createObjectURL(new Blob([n],{type:"application/javascript"}));i(new z_(e,(()=>new Promise(((e,i)=>{const n=new Worker(s),r=e=>{n.removeEventListener("error",r),n.removeEventListener("message",o),i(e)},o=t=>{"init"===t.data.action&&(n.removeEventListener("error",r),n.removeEventListener("message",o),e(n))};n.addEventListener("error",r),n.addEventListener("message",o),n.postMessage({action:"init",urls:t})})))))})):"undefined"==typeof KTX2DECODER?K_._DecoderModulePromise=se.w1.LoadScriptAsync(t.jsDecoderModule).then((()=>(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,j_(t),new KTX2DECODER.KTX2Decoder))):(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,K_._DecoderModulePromise=Promise.resolve(new KTX2DECODER.KTX2Decoder))}constructor(e,t=K_.DefaultNumWorkers){this._engine=e,K_._Initialize(t)}uploadAsync(e,t,i){const n=this._engine.getCaps(),s={astc:!!n.astc,bptc:!!n.bptc,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,etc1:!!n.etc1};if(K_._WorkerPoolPromise)return K_._WorkerPoolPromise.then((n=>new Promise(((r,o)=>{n.push(((n,a)=>{const l=e=>{n.removeEventListener("error",l),n.removeEventListener("message",h),o(e),a()},h=e=>{if("decoded"===e.data.action){if(n.removeEventListener("error",l),n.removeEventListener("message",h),e.data.success)try{this._createTexture(e.data.decodedData,t,i),r()}catch(s){o({message:s})}else o({message:e.data.msg});a()}};n.addEventListener("error",l),n.addEventListener("message",h),n.postMessage({action:"setDefaultDecoderOptions",options:K_.DefaultDecoderOptions._getKTX2DecoderOptions()});const c=new Uint8Array(e.byteLength);c.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),n.postMessage({action:"decode",data:c,caps:s,options:i},[c.buffer])}))}))));if(K_._DecoderModulePromise)return K_._DecoderModulePromise.then((i=>(K_.DefaultDecoderOptions.isDirty&&(KTX2DECODER.KTX2Decoder.DefaultDecoderOptions=K_.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise(((s,r)=>{i.decode(e,n).then((e=>{this._createTexture(e,t),s()})).catch((e=>{r({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=0,t.format=5;break;case 33321:t.type=0,t.format=6;break;case 33323:t.type=0,t.format=7;break;default:t.format=e.transcodedFormat,n=!1}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 s=0;s=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}}function q_(){let e;onmessage=t=>{if(t.data)switch(t.data.action){case"init":{const i=t.data.urls;importScripts(i.jsDecoderModule),j_(i),e=new KTX2DECODER.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":KTX2DECODER.KTX2Decoder.DefaultDecoderOptions=t.data.options;break;case"decode":e.decode(t.data.data,t.data.caps,t.data.options).then((e=>{const t=[];for(let i=0;i{postMessage({action:"decoded",success:!1,msg:e})}))}}}K_.URLConfig={jsDecoderModule:"https://preview.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},K_.DefaultNumWorkers=K_.GetDefaultNumWorkers(),K_.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:[H_.BC1_RGB,H_.BC3_RGBA],yes:{transcodeFormat:H_.RGBA32,engineFormat:X_.RGBA8Format,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}};fe.D._TextureLoaders.unshift(new class{constructor(){this.supportCascades=!1}canLoad(e,t){return e.endsWith(".ktx")||e.endsWith(".ktx2")||"image/ktx"===t||"image/ktx2"===t}loadCubeData(e,t,i,n){if(Array.isArray(e))return;t._invertVScale=!t.invertY;const s=t.getEngine(),r=new k_(e,6),o=r.numberOfMipmapLevels>1&&t.generateMipMaps;s._unpackFlipY(!0),r.uploadLevels(t,t.generateMipMaps),t.width=r.pixelWidth,t.height=r.pixelHeight,s._setCubeMapTextureParams(t,o,r.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n()}loadData(e,t,i,n){if(k_.IsValid(e)){t._invertVScale=!t.invertY;const n=new k_(e,1),s=function(e){switch(e){case 35916:return 33776;case 35918:return 33778;case 35919:return 33779;case 37493:return 37492;case 37497:return 37496;case 37495:return 37494;case 37840:return 37808;case 36493:return 36492}return null}(n.glInternalFormat);s?(t.format=s,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(K_.IsValid(e)){new K_(t.getEngine()).uploadAsync(e,t,n).then((()=>{i(t.width,t.height,t.generateMipMaps,!0,(()=>{}),!1)}),(e=>{p.Y.Warn(`Failed to load KTX2 texture data: ${e.message}`),i(0,0,!1,!1,(()=>{}),!0)}))}else p.Y.Error("texture missing KTX identifier"),i(0,0,!1,!1,(()=>{}),!0)}});class $_ extends Fn{constructor(e,t,i){super(e,o.P.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=o._f.Identity(),this._referencedPosition=new o.P,this._trackingState=xa.NOT_TRACKING,this.onBeforeCameraTeleport=new r.y$,this.onAfterCameraTeleport=new r.y$,this.onTrackingStateChanged=new r.y$,this.compensateOnFirstFrame=!0,this._rotate180=new o._f(0,1,0,0),this.minZ=.1,this.rotationQuaternion=new o._f,this.cameraRigMode=ce.V.RIG_MODE_CUSTOM,this.updateUpVectorFromRotation=!0,this._updateNumberOfRigCameras(1),this.freezeProjectionMatrix(),this._xrSessionManager.onXRSessionInit.add((()=>{this._referencedPosition.copyFromFloats(0,0,0),this._referenceQuaternion.copyFromFloats(0,0,0,1),this._firstFrame=this.compensateOnFirstFrame})),this._xrSessionManager.onXRFrameObservable.add((()=>{this._firstFrame&&this._updateFromXRSession(),this._updateReferenceSpace(),this._updateFromXRSession()}),void 0,!0)}get trackingState(){return this._trackingState}_setTrackingState(e){this._trackingState!==e&&(this._trackingState=e,this.onTrackingStateChanged.notifyObservers(e))}get realWorldHeight(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace);return e&&e.transform?e.transform.position.y:0}_updateForDualEyeDebugging(){this._updateNumberOfRigCameras(2),this.rigCameras[0].viewport=new Nt.l(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new Nt.l(.5,0,.5,1),this.rigCameras[1].outputRenderTarget=null}setTransformationFromNonVRCamera(e=this.getScene().activeCamera,t=!0){if(!e||e===this)return;e.computeWorldMatrix().decompose(void 0,this.rotationQuaternion,this.position),this.position.y=0,o._f.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace()}getClassName(){return"WebXRCamera"}setTarget(e){const t=o.jp.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();const i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),o._f.FromEulerAnglesToRef(t.x,i,t.z,this.rotationQuaternion)}dispose(){super.dispose(),this._lastXRViewerPose=void 0}_updateFromXRSession(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);if(this._lastXRViewerPose=e||void 0,!e)return void this._setTrackingState(xa.NOT_TRACKING);const t=e.emulatedPosition?xa.TRACKING_LOST:xa.TRACKING;if(this._setTrackingState(t),this.minZ!==this._cache.minZ||this.maxZ!==this._cache.maxZ){const e={depthFar:this.maxZ||1e4,depthNear:this.minZ};this._xrSessionManager.updateRenderState(e),this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ}if(e.transform){const t=e.transform.orientation;if(void 0===e.transform.orientation.x)return;const i=e.transform.position;this._referencedPosition.set(i.x,i.y,i.z),this._referenceQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this._referencedPosition.z*=-1,this._referenceQuaternion.z*=-1,this._referenceQuaternion.w*=-1),this._firstFrame?(this._firstFrame=!1,this.position.y+=this._referencedPosition.y,this._referenceQuaternion.copyFromFloats(0,0,0,1)):(this.rotationQuaternion.copyFrom(this._referenceQuaternion),this.position.copyFrom(this._referencedPosition))}this.rigCameras.length!==e.views.length&&this._updateNumberOfRigCameras(e.views.length),e.views.forEach(((e,t)=>{var i;const n=this.rigCameras[t];n.isLeftCamera||n.isRightCamera||("right"===e.eye?n._isRightCamera=!0:"left"===e.eye&&(n._isLeftCamera=!0));const s=e.transform.position,r=e.transform.orientation;n.parent=this.parent,n.position.set(s.x,s.y,s.z),n.rotationQuaternion.set(r.x,r.y,r.z,r.w),this._scene.useRightHandedSystem?n.rotationQuaternion.multiplyInPlace(this._rotate180):(n.position.z*=-1,n.rotationQuaternion.z*=-1,n.rotationQuaternion.w*=-1),o.y3.FromFloat32ArrayToRefScaled(e.projectionMatrix,0,1,n._projectionMatrix),this._scene.useRightHandedSystem||n._projectionMatrix.toggleProjectionMatrixHandInPlace(),0===t&&this._projectionMatrix.copyFrom(n._projectionMatrix);const a=this._xrSessionManager.getRenderTargetTextureForView(e);this._renderingMultiview=(null===(i=null==a?void 0:a._texture)||void 0===i?void 0:i.isMultiview)||!1,this._renderingMultiview?0==t&&(this._xrSessionManager.trySetViewportForView(this.viewport,e),this.outputRenderTarget=a):(this._xrSessionManager.trySetViewportForView(n.viewport,e),n.outputRenderTarget=a||this._xrSessionManager.getRenderTargetTextureForView(e)),n.layerMask=this.layerMask}))}_updateNumberOfRigCameras(e=1){for(;this.rigCameras.lengthe;){const e=this.rigCameras.pop();e&&e.dispose()}}_updateReferenceSpace(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){const e=o.jp.Matrix[0],t=o.jp.Matrix[1],i=o.jp.Matrix[2];o.y3.ComposeToRef($_._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),o.y3.ComposeToRef($_._ScaleReadOnly,this.rotationQuaternion,this.position,t),e.invert().multiplyToRef(t,i),i.invert(),this._scene.useRightHandedSystem||i.toggleModelMatrixHandInPlace(),i.decompose(void 0,this._referenceQuaternion,this._referencedPosition);const n=new XRRigidTransform({x:this._referencedPosition.x,y:this._referencedPosition.y,z:this._referencedPosition.z},{x:this._referenceQuaternion.x,y:this._referenceQuaternion.y,z:this._referenceQuaternion.z,w:this._referenceQuaternion.w});this._xrSessionManager.referenceSpace=this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(n)}}}$_._ScaleReadOnly=o.P.One();class Q_{constructor(e){this._scene=e,this._nonVRCamera=null,this._attachedToElement=!1,this._spectatorCamera=null,this._originalSceneAutoClear=!0,this._supported=!1,this._spectatorMode=!1,this._lastTimestamp=0,this.onInitialXRPoseSetObservable=new r.y$,this.onStateChangedObservable=new r.y$,this.state=Ea.NOT_IN_XR,this.sessionManager=new Da(e),this.camera=new $_("webxr",e,this.sessionManager),this.featuresManager=new it(this.sessionManager),e.onDisposeObservable.addOnce((()=>{this.dispose()}))}static CreateAsync(e){const t=new Q_(e);return t.sessionManager.initializeAsync().then((()=>(t._supported=!0,t))).catch((e=>{throw t._setState(Ea.NOT_IN_XR),t.dispose(),e}))}dispose(){var e;this.exitXRAsync(),this.camera.dispose(),this.onStateChangedObservable.clear(),this.onInitialXRPoseSetObservable.clear(),this.sessionManager.dispose(),null===(e=this._spectatorCamera)||void 0===e||e.dispose(),this._nonVRCamera&&(this._scene.activeCamera=this._nonVRCamera)}async enterXRAsync(e,t,i=this.sessionManager.getWebXRRenderTarget(),n={}){var s,r,o;if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(Ea.ENTERING_XR),"viewer"!==t&&"local"!==t&&(n.optionalFeatures=n.optionalFeatures||[],n.optionalFeatures.push(t)),n=await this.featuresManager._extendXRSessionInitObject(n),"immersive-ar"===e&&"unbounded"!==t&&p.Y.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode");try{await this.sessionManager.initializeSessionAsync(e,n),await this.sessionManager.setReferenceSpaceTypeAsync(t);const a=await i.initializeXRLayerAsync(this.sessionManager.session),l={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};return this.featuresManager.getEnabledFeature(tt.LAYERS)||(l.baseLayer=a),this.sessionManager.updateRenderState(l),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!(null===(r=null===(s=this._nonVRCamera)||void 0===s?void 0:s.inputs)||void 0===r?void 0:r.attachedToElement),null===(o=this._nonVRCamera)||void 0===o||o.detachControl(),this._scene.activeCamera=this.camera,"immersive-ar"!==e?this._nonXRToXRCamera():(this._scene.autoClear=!1,this.camera.compensateOnFirstFrame=!1,this.camera.position.set(0,0,0),this.camera.rotationQuaternion.set(0,0,0,1),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)),this.sessionManager.onXRSessionEnded.addOnce((()=>{this.state!==Ea.EXITING_XR&&this._setState(Ea.EXITING_XR),this.camera.rigCameras.forEach((e=>{e.outputRenderTarget=null})),this._scene.autoClear=this._originalSceneAutoClear,this._scene.activeCamera=this._nonVRCamera,this._attachedToElement&&this._nonVRCamera&&this._nonVRCamera.attachControl(!!this._nonVRCamera.inputs.noPreventDefault),"immersive-ar"!==e&&this.camera.compensateOnFirstFrame&&(this._nonVRCamera.setPosition?this._nonVRCamera.setPosition(this.camera.position):this._nonVRCamera.position.copyFrom(this.camera.position)),this._setState(Ea.NOT_IN_XR)})),this.sessionManager.onXRFrameObservable.addOnce((()=>{this._setState(Ea.IN_XR)})),this.sessionManager}catch(a){throw console.log(a),console.log(a.message),this._setState(Ea.NOT_IN_XR),a}}exitXRAsync(){return this.state!==Ea.IN_XR?Promise.resolve():(this._setState(Ea.EXITING_XR),this.sessionManager.exitXRAsync())}enableSpectatorMode(e){this._spectatorMode||(this._spectatorMode=!0,this._switchSpectatorMode(e))}disableSpecatatorMode(){this._spectatorMode&&(this._spectatorMode=!1,this._switchSpectatorMode())}_switchSpectatorMode(e){const t=1/((null==e?void 0:e.fps)?e.fps:1e3)*1e3,i=(null==e?void 0:e.preferredCameraIndex)?null==e?void 0:e.preferredCameraIndex:0,n=()=>{if(this._spectatorCamera){this.sessionManager.currentTimestamp-this._lastTimestamp>=t&&(this._lastTimestamp=this.sessionManager.currentTimestamp,this._spectatorCamera.position.copyFrom(this.camera.rigCameras[i].globalPosition),this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[i].absoluteRotation))}};if(this._spectatorMode){if(i>=this.camera.rigCameras.length)throw new Error("the preferred camera index is beyond the length of rig camera array.");const e=()=>{this.state===Ea.IN_XR?(this._spectatorCamera=new qn("webxr-spectator",o.P.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new o._f,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(n),this._scene.onAfterRenderCameraObservable.add((e=>{e===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)}))):this.state===Ea.EXITING_XR&&(this.sessionManager.onXRFrameObservable.removeCallback(n),this._scene.activeCameras=null)};this.onStateChangedObservable.add(e),e()}else this.sessionManager.onXRFrameObservable.removeCallback(n),this._scene.activeCameras=[this.camera]}_nonXRToXRCamera(){this.camera.setTransformationFromNonVRCamera(this._nonVRCamera),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)}_setState(e){this.state!==e&&(this.state=e,this.onStateChangedObservable.notifyObservers(this.state))}}class Z_{constructor(e,t,i=-1,n=[]){this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=n,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new r.y$,this.onButtonStateChangedObservable=new r.y$}get axes(){return this._axes}get changes(){return this._changes}get hasChanges(){return this._hasChanges}get pressed(){return this._pressed}get touched(){return this._touched}get value(){return this._currentValue}dispose(){this.onAxisValueChangedObservable.clear(),this.onButtonStateChangedObservable.clear()}isAxes(){return 0!==this._axesIndices.length}isButton(){return-1!==this._buttonIndex}update(e){let t=!1,i=!1;if(this._hasChanges=!1,this._changes={},this.isButton()){const i=e.buttons[this._buttonIndex];if(!i)return;this._currentValue!==i.value&&(this.changes.value={current:i.value,previous:this._currentValue},t=!0,this._currentValue=i.value),this._touched!==i.touched&&(this.changes.touched={current:i.touched,previous:this._touched},t=!0,this._touched=i.touched),this._pressed!==i.pressed&&(this.changes.pressed={current:i.pressed,previous:this._pressed},t=!0,this._pressed=i.pressed)}this.isAxes()&&(this._axes.x!==e.axes[this._axesIndices[0]]&&(this.changes.axes={current:{x:e.axes[this._axesIndices[0]],y:this._axes.y},previous:{x:this._axes.x,y:this._axes.y}},this._axes.x=e.axes[this._axesIndices[0]],i=!0),this._axes.y!==e.axes[this._axesIndices[1]]&&(this.changes.axes?this.changes.axes.current.y=e.axes[this._axesIndices[1]]:this.changes.axes={current:{x:this._axes.x,y:e.axes[this._axesIndices[1]]},previous:{x:this._axes.x,y:this._axes.y}},this._axes.y=e.axes[this._axesIndices[1]],i=!0)),t&&(this._hasChanges=!0,this.onButtonStateChangedObservable.notifyObservers(this)),i&&(this._hasChanges=!0,this.onAxisValueChangedObservable.notifyObservers(this._axes))}}Z_.BUTTON_TYPE="button",Z_.SQUEEZE_TYPE="squeeze",Z_.THUMBSTICK_TYPE="thumbstick",Z_.TOUCHPAD_TYPE="touchpad",Z_.TRIGGER_TYPE="trigger";class J_{constructor(e,t,i,n,s=!1,o){this.scene=e,this.layout=t,this.gamepadObject=i,this.handedness=n,this._doNotLoadControllerMesh=s,this._controllerCache=o,this._initComponent=e=>{if(!e)return;const t=this.layout.components[e],i=t.type,n=t.gamepadIndices.button,s=[];void 0!==t.gamepadIndices.xAxis&&void 0!==t.gamepadIndices.yAxis&&s.push(t.gamepadIndices.xAxis,t.gamepadIndices.yAxis),this.components[e]=new Z_(e,i,n,s)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new r.y$,t.components&&Object.keys(t.components).forEach(this._initComponent)}dispose(){this.getComponentIds().forEach((e=>this.getComponent(e).dispose())),this.rootMesh&&(this.rootMesh.getChildren(void 0,!0).forEach((e=>{e.setEnabled(!1)})),this.rootMesh.dispose(!!this._controllerCache,!this._controllerCache))}getAllComponentsOfType(e){return this.getComponentIds().map((e=>this.components[e])).filter((t=>t.type===e))}getComponent(e){return this.components[e]}getComponentIds(){return Object.keys(this.components)}getComponentOfType(e){return this.getAllComponentsOfType(e)[0]||null}getMainComponent(){return this.getComponent(this.layout.selectComponentId)}async loadModel(){const e=!this._getModelLoadingConstraints();let t=this._getGenericFilenameAndPath();return e?p.Y.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),new Promise(((i,n)=>{const s=t=>{e?this._getGenericParentMesh(t):this._setRootMesh(t),this._processLoadedModel(t),this._modelReady=!0,this.onModelLoadedObservable.notifyObservers(this),i(!0)};if(this._controllerCache){const e=this._controllerCache.filter((e=>e.filename===t.filename&&e.path===t.path));if(e[0])return e[0].meshes.forEach((e=>e.setEnabled(!0))),void s(e[0].meshes)}ht.ImportMesh("",t.path,t.filename,this.scene,(e=>{this._controllerCache&&this._controllerCache.push(Object.assign(Object.assign({},t),{meshes:e})),s(e)}),null,((e,i)=>{p.Y.Log(i),p.Y.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),n(i)}))}))}updateFromXRFrame(e){this.getComponentIds().forEach((e=>this.getComponent(e).update(this.gamepadObject))),this.updateModel(e)}get handness(){return this.handedness}pulse(e,t,i=0){return this.gamepadObject.hapticActuators&&this.gamepadObject.hapticActuators[i]?this.gamepadObject.hapticActuators[i].pulse(e,t):Promise.resolve(!1)}_getChildByName(e,t){return e.getChildren((e=>e.name===t),!1)[0]}_getImmediateChildByName(e,t){return e.getChildren((e=>e.name==t),!0)[0]}_lerpTransform(e,t,i){if(!e.minMesh||!e.maxMesh||!e.valueMesh)return;if(!e.minMesh.rotationQuaternion||!e.maxMesh.rotationQuaternion||!e.valueMesh.rotationQuaternion)return;const n=i?.5*t+.5:t;o._f.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,n,e.valueMesh.rotationQuaternion),o.P.LerpToRef(e.minMesh.position,e.maxMesh.position,n,e.valueMesh.position)}updateModel(e){this._modelReady&&this._updateModel(e)}_getGenericFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getGenericParentMesh(e){this.rootMesh=new ee.Kj(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.parent||(e.isPickable=!1,e.setParent(this.rootMesh))})),this.rootMesh.rotationQuaternion=o._f.FromEulerAngles(0,Math.PI,0)}}class em extends J_{constructor(e,t,i){super(e,tm[i],t,i),this.profileId=em.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new ee.Kj(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.isPickable=!1,e.parent||e.setParent(this.rootMesh)})),this.rootMesh.rotationQuaternion=o._f.FromEulerAngles(0,Math.PI,0)}_updateModel(){}}em.ProfileId="generic-trigger";const tm={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-none",assetPath:"none.glb"}};class im extends J_{constructor(e,t,i,n,s){super(e,i.layouts[t.handedness||"none"],t.gamepad,t.handedness,void 0,s),this._repositoryUrl=n,this.controllerCache=s,this._buttonMeshMapping={},this._touchDots={},this.profileId=i.profileId}dispose(){super.dispose(),this.controllerCache||Object.keys(this._touchDots).forEach((e=>{this._touchDots[e].dispose()}))}_getFilenameAndPath(){return{filename:this.layout.assetPath,path:`${this._repositoryUrl}/profiles/${this.profileId}/`}}_getModelLoadingConstraints(){const e=ht.IsPluginForExtensionAvailable(".glb");return e||p.Y.Warn("glTF / glb loader was not registered, using generic controller instead"),e}_processLoadedModel(e){this.getComponentIds().forEach((e=>{const t=this.layout.components[e];this._buttonMeshMapping[e]={mainMesh:this._getChildByName(this.rootMesh,t.rootNodeName),states:{}},Object.keys(t.visualResponses).forEach((i=>{const n=t.visualResponses[i];if("transform"===n.valueNodeProperty)this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,n.valueNodeName),minMesh:this._getChildByName(this.rootMesh,n.minNodeName),maxMesh:this._getChildByName(this.rootMesh,n.maxNodeName)};else{const s=t.type===Z_.TOUCHPAD_TYPE&&t.touchPointNodeName?t.touchPointNodeName:n.valueNodeName;if(this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,s)},t.type===Z_.TOUCHPAD_TYPE&&!this._touchDots[i]){const t=gl(i+"dot",{diameter:.0015,segments:8},this.scene);t.material=new _a(i+"mat",this.scene),t.material.diffuseColor=a.Wo.Red(),t.parent=this._buttonMeshMapping[e].states[i].valueMesh||null,t.isVisible=!1,this._touchDots[i]=t}}}))}))}_setRootMesh(e){let t;this.rootMesh=new ee.Kj(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;i{const t=this.getComponent(e);if(!t.hasChanges)return;const i=this._buttonMeshMapping[e],n=this.layout.components[e];Object.keys(n.visualResponses).forEach((e=>{const s=n.visualResponses[e];let r=t.value;if("xAxis"===s.componentProperty?r=t.axes.x:"yAxis"===s.componentProperty&&(r=t.axes.y),"transform"===s.valueNodeProperty)this._lerpTransform(i.states[e],r,"button"!==s.componentProperty);else{const n=i.states[e].valueMesh;n&&(n.isVisible=t.touched||t.pressed),this._touchDots[e]&&(this._touchDots[e].isVisible=t.touched||t.pressed)}}))}))}}const nm=[];class sm{static ClearProfilesCache(){this._ProfilesList=null,this._ProfileLoadingPromises={}}static DefaultFallbacks(){this.RegisterFallbacksForProfileId("google-daydream",["generic-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive-focus",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("magicleap-one",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("windows-mixed-reality",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("microsoft-mixed-reality",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-go",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("oculus-touch-v2",["oculus-touch","generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-touch",["generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-gearvr",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-odyssey",["generic-touchpad"]),this.RegisterFallbacksForProfileId("valve-index",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("generic-hand-select",["generic-trigger"])}static FindFallbackWithProfileId(e){const t=this._Fallbacks[e]||[];return t.unshift(e),t}static GetMotionControllerWithXRInput(e,t,i){const n=[];if(i&&n.push(i),n.push(...e.profiles||[]),n.length&&!n[0]&&n.pop(),e.gamepad&&e.gamepad.id&&e.gamepad.id===(e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0))n.push("oculus-touch-v2");const s=n.indexOf("windows-mixed-reality");if(-1!==s&&n.splice(s,0,"microsoft-mixed-reality"),n.length||n.push("generic-trigger"),this.UseOnlineRepository){const i=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,s=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return i.call(this,n,e,t).catch((()=>s.call(this,n,e,t)))}return this._LoadProfilesFromAvailableControllers(n,e,t)}static RegisterController(e,t){this._AvailableControllers[e]=t}static RegisterFallbacksForProfileId(e,t){this._Fallbacks[e]?this._Fallbacks[e].push(...t):this._Fallbacks[e]=t}static UpdateProfilesList(){return this._ProfilesList=se.w1.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then((e=>JSON.parse(e.toString()))),this._ProfilesList}static ClearControllerCache(){nm.forEach((e=>{e.meshes.forEach((e=>{e.dispose(!1,!0)}))})),nm.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then((()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList())).then((t=>{for(let i=0;i(this._ProfileLoadingPromises[e]||(this._ProfileLoadingPromises[e]=se.w1.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${e}/profile.json`,!1).then((e=>JSON.parse(e)))),this._ProfileLoadingPromises[e]))).then((e=>new im(i,t,e,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:nm)))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let n=0;nnew em(t,e.gamepad,e.handedness))),sm.DefaultFallbacks();let rm=0;class om{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new o.P,this._disposed=!1,this.onDisposeObservable=new r.y$,this.onMeshLoadedObservable=new r.y$,this.onMotionControllerInitObservable=new r.y$,this._uniqueId=`controller-${rm++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new ie.x(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new o._f,this.inputSource.gripSpace&&(this.grip=new ie.x(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new o._f),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&"tracked-pointer"===this.inputSource.targetRayMode&&sm.GetMotionControllerWithXRInput(t,e,this._options.forceControllerProfile).then((e=>{this.motionController=e,this.onMotionControllerInitObservable.notifyObservers(e),this._options.doNotLoadControllerMesh||this.motionController._doNotLoadControllerMesh||this.motionController.loadModel().then((e=>{var t;e&&this.motionController&&this.motionController.rootMesh&&(this._options.renderingGroupId&&(this.motionController.rootMesh.renderingGroupId=this._options.renderingGroupId,this.motionController.rootMesh.getChildMeshes(!1).forEach((e=>e.renderingGroupId=this._options.renderingGroupId))),this.onMeshLoadedObservable.notifyObservers(this.motionController.rootMesh),this.motionController.rootMesh.parent=this.grip||this.pointer,this.motionController.disableAnimation=!!this._options.disableMotionControllerAnimation),this._disposed&&(null===(t=this.motionController)||void 0===t||t.dispose())}))}),(()=>{se.w1.Warn("Could not find a matching motion controller for the registered input source")}))}get uniqueId(){return this._uniqueId}dispose(){this.grip&&this.grip.dispose(!0),this.motionController&&this.motionController.dispose(),this.pointer.dispose(!0),this.onMotionControllerInitObservable.clear(),this.onMeshLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._disposed=!0}getWorldPointerRayToRef(e,t=!1){const i=t&&this.grip?this.grip:this.pointer;o.P.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i){const n=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=n,n){const e=n.transform.position;this.pointer.position.set(e.x,e.y,e.z);const t=n.transform.orientation;this.pointer.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.pointer.position.z*=-1,this.pointer.rotationQuaternion.z*=-1,this.pointer.rotationQuaternion.w*=-1),this.pointer.parent=i.parent}if(this.inputSource.gripSpace&&this.grip){const n=e.getPose(this.inputSource.gripSpace,t);if(n){const e=n.transform.position,t=n.transform.orientation;this.grip.position.set(e.x,e.y,e.z),this.grip.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.grip.position.z*=-1,this.grip.rotationQuaternion.z*=-1,this.grip.rotationQuaternion.w*=-1)}this.grip.parent=i.parent}this.motionController&&this.motionController.updateFromXRFrame(e)}}class am{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new r.y$,this.onControllerRemovedObservable=new r.y$,this._onInputSourcesChange=e=>{this._addAndRemoveControllers(e.added,e.removed)},this._sessionEndedObserver=this.xrSessionManager.onXRSessionEnded.add((()=>{this._addAndRemoveControllers([],this.controllers.map((e=>e.inputSource)))})),this._sessionInitObserver=this.xrSessionManager.onXRSessionInit.add((e=>{e.addEventListener("inputsourceschange",this._onInputSourcesChange)})),this._frameObserver=this.xrSessionManager.onXRFrameObservable.add((e=>{this.controllers.forEach((t=>{t.updateFromXRFrame(e,this.xrSessionManager.referenceSpace,this.xrCamera)}))})),this._options.customControllersRepositoryURL&&(sm.BaseRepositoryUrl=this._options.customControllersRepositoryURL),sm.UseOnlineRepository=!this._options.disableOnlineControllerRepository,sm.UseOnlineRepository)try{sm.UpdateProfilesList().catch((()=>{sm.UseOnlineRepository=!1}))}catch(n){sm.UseOnlineRepository=!1}}_addAndRemoveControllers(e,t){const i=this.controllers.map((e=>e.inputSource));for(const r of e)if(-1===i.indexOf(r)){const e=new om(this.xrSessionManager.scene,r,Object.assign(Object.assign({},this._options.controllerOptions||{}),{forceControllerProfile:this._options.forceInputProfile,doNotLoadControllerMesh:this._options.doNotLoadControllerMeshes,disableMotionControllerAnimation:this._options.disableControllerAnimation}));this.controllers.push(e),this.onControllerAddedObservable.notifyObservers(e)}const n=[],s=[];this.controllers.forEach((e=>{-1===t.indexOf(e.inputSource)?n.push(e):s.push(e)})),this.controllers=n,s.forEach((e=>{this.onControllerRemovedObservable.notifyObservers(e),e.dispose()}))}dispose(){this.controllers.forEach((e=>{e.dispose()})),this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver),this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver),this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver),this.onControllerAddedObservable.clear(),this.onControllerRemovedObservable.clear(),sm.ClearControllerCache()}}class lm extends nt{constructor(e,t){super(e),this._options=t,this._attachController=e=>{if(this._controllers[e.uniqueId])return;const{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(e.pointer);switch(this._controllers[e.uniqueId]={xrController:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new qe(new o.P,new o.P),disabledByNearInteraction:!1,id:lm._IdCounter++},this._attachedController?!this._options.enablePointerSelectionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enablePointerSelectionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachTrackedPointerRayMode(e);case"gaze":return this._attachGazeMode(e);case"screen":return this._attachScreenRayMode(e)}},this._controllers={},this._tmpVectorForPickCompare=new o.P,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new a.Wo(.9,.9,.9),this.laserPointerDefaultColor=new a.Wo(.7,.7,.7),this.selectionMeshDefaultColor=new a.Wo(.8,.8,.8),this.selectionMeshPickedColor=new a.Wo(.3,.3,1),this._identityMatrix=o.y3.Identity(),this._screenCoordinatesRef=o.P.Zero(),this._viewportRef=new Nt.l(0,0,0,0),this._scene=this._xrSessionManager.scene}attach(){if(!super.attach())return!1;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),this._scene.constantlyUpdateMeshUnderPointer=!0,this._options.gazeCamera){const e=this._options.gazeCamera,{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(e);this._controllers.camera={webXRCamera:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new qe(new o.P,new o.P),disabledByNearInteraction:!1,id:lm._IdCounter++},this._attachGazeMode()}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;i{const t=this._controllers[e];if(!this._options.enablePointerSelectionOnAllControllers&&e!==this._attachedController||t.disabledByNearInteraction)return t.selectionMesh.isVisible=!1,t.laserPointer.isVisible=!1,void(t.pick=null);let i;if(t.laserPointer.isVisible=this.displayLaserPointer,t.xrController)i=t.xrController.pointer.position,t.xrController.getWorldPointerRayToRef(t.tmpRay);else{if(!t.webXRCamera)return;i=t.webXRCamera.position,t.webXRCamera.getForwardRayToRef(t.tmpRay)}if(this._options.maxPointerDistance&&(t.tmpRay.length=this._options.maxPointerDistance),!this._options.disableScenePointerVectorUpdate&&i){const e=this._xrSessionManager.scene,n=this._options.xrInput.xrCamera;n&&(n.viewport.toGlobalToRef(e.getEngine().getRenderWidth(),e.getEngine().getRenderHeight(),this._viewportRef),o.P.ProjectToRef(i,this._identityMatrix,e.getTransformMatrix(),this._viewportRef,this._screenCoordinatesRef),"number"!=typeof this._screenCoordinatesRef.x||"number"!=typeof this._screenCoordinatesRef.y||isNaN(this._screenCoordinatesRef.x)||isNaN(this._screenCoordinatesRef.y)||(e.pointerX=this._screenCoordinatesRef.x,e.pointerY=this._screenCoordinatesRef.y,t.screenCoordinates={x:this._screenCoordinatesRef.x,y:this._screenCoordinatesRef.y}))}let n=null;this._utilityLayerScene&&(n=this._utilityLayerScene.pickWithRay(t.tmpRay,this._utilityLayerScene.pointerMovePredicate||this.raySelectionPredicate));const s=this._scene.pickWithRay(t.tmpRay,this._scene.pointerMovePredicate||this.raySelectionPredicate);n&&n.hit?s&&s.hit?n.distance{if(t.pick){if(this._augmentPointerInit(l,t.id,t.screenCoordinates),t.laserPointer.material.alpha=0,r.isVisible=!1,t.pick.hit)if(this._pickingMoved(s,t.pick))a&&(this._options.disablePointerUpOnTouchOut||this._scene.simulatePointerUp(t.pick,l)),a=!1,o=0;else if(o>i/10&&(r.isVisible=!0),o+=this._scene.getEngine().getDeltaTime(),o>=i)this._scene.simulatePointerDown(t.pick,l),a=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),r.isVisible=!1;else{const e=1-o/i;r.scaling.set(e,e,e)}else a=!1,o=0;this._scene.simulatePointerMove(t.pick,l),s=t.pick}})),void 0!==this._options.renderingGroupId&&(r.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce((()=>{t.pick&&!this._options.disablePointerUpOnTouchOut&&a&&(this._scene.simulatePointerUp(t.pick,l),t.finalPointerUpTriggered=!0),r.dispose()}))}_attachScreenRayMode(e){const t=this._controllers[e.uniqueId];let i=!1;const n={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{this._augmentPointerInit(n,t.id,t.screenCoordinates),!t.pick||this._options.disablePointerUpOnTouchOut&&i||(i?this._scene.simulatePointerMove(t.pick,n):(this._scene.simulatePointerDown(t.pick,n),t.pointerDownTriggered=!0,i=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,n)))})),e.onDisposeObservable.addOnce((()=>{this._augmentPointerInit(n,t.id,t.screenCoordinates),this._xrSessionManager.runInXRFrame((()=>{t.pick&&!t.finalPointerUpTriggered&&i&&!this._options.disablePointerUpOnTouchOut&&(this._scene.simulatePointerUp(t.pick,n),t.finalPointerUpTriggered=!0)}))}))}_attachTrackedPointerRayMode(e){const t=this._controllers[e.uniqueId];if(this._options.forceGazeMode)return this._attachGazeMode(e);const i={pointerId:t.id,pointerType:"xr"};if(t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{t.laserPointer.material.disableLighting=this.disablePointerLighting,t.selectionMesh.material.disableLighting=this.disableSelectionMeshLighting,t.pick&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerMove(t.pick,i))})),e.inputSource.gamepad){const n=n=>{this._options.overrideButtonId&&(t.selectionComponent=n.getComponent(this._options.overrideButtonId)),t.selectionComponent||(t.selectionComponent=n.getMainComponent()),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add((n=>{if(n.changes.pressed){const s=n.changes.pressed.current;t.pick?(this._options.enablePointerSelectionOnAllControllers||e.uniqueId===this._attachedController)&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),s?(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor):(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor)):!s||this._options.enablePointerSelectionOnAllControllers||this._options.disableSwitchOnClick||(this._attachedController=e.uniqueId)}}))};e.motionController?n(e.motionController):e.onMotionControllerInitObservable.add(n)}else{const e=e=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor)},n=e=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor)};t.eventListeners={selectend:n,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",n)}}_convertNormalToDirectionOfRay(e,t){if(e){Math.acos(o.P.Dot(e,t.direction)){const i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)})),!t.finalPointerUpTriggered&&t.pointerDownTriggered){const e={pointerId:t.id,pointerType:"xr"};this._xrSessionManager.runInXRFrame((()=>{this._augmentPointerInit(e,t.id,t.screenCoordinates),this._scene.simulatePointerUp(t.pick||new je.p,e),t.finalPointerUpTriggered=!0}))}this._xrSessionManager.scene.onBeforeRenderObservable.addOnce((()=>{try{if(t.selectionMesh.dispose(),t.laserPointer.dispose(),delete this._controllers[e],this._attachedController===e){const e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}catch(i){se.w1.Warn("controller already detached.")}}))}}_generateNewMeshPair(e){const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||dl.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():Fa("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;const n=new _a("laserPointerMat",t);n.emissiveColor=this.laserPointerDefaultColor,n.alpha=.7,i.material=n,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1,i.isVisible=!1;const s=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():La("gazeTracker",{diameter:.0105,thickness:.0075,tessellation:20},t);s.bakeCurrentTransformIntoVertices(),s.isPickable=!1,s.isVisible=!1;const r=new _a("targetMat",t);return r.specularColor=a.Wo.Black(),r.emissiveColor=this.selectionMeshDefaultColor,r.backFaceCulling=!1,s.material=r,void 0!==this._options.renderingGroupId&&(i.renderingGroupId=this._options.renderingGroupId,s.renderingGroupId=this._options.renderingGroupId),{laserPointer:i,selectionMesh:s}}_pickingMoved(e,t){var i;if(!e.hit||!t.hit)return!0;if(!(e.pickedMesh&&e.pickedPoint&&t.pickedMesh&&t.pickedPoint))return!0;if(e.pickedMesh!==t.pickedMesh)return!0;null===(i=e.pickedPoint)||void 0===i||i.subtractToRef(t.pickedPoint,this._tmpVectorForPickCompare),this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x),Math.abs(this._tmpVectorForPickCompare.y),Math.abs(this._tmpVectorForPickCompare.z));const n=.01*(this._options.gazeModePointerMovedFactor||1)*t.distance;return this._tmpVectorForPickCompare.length()>n}_updatePointerDistance(e,t=100){e.scaling.y=t,this._scene.useRightHandedSystem&&(t*=-1),e.position.z=t/2+.05}_augmentPointerInit(e,t,i){e.pointerId=t,e.pointerType="xr",i&&(e.screenX=i.x,e.screenY=i.y)}get lasterPointerDefaultColor(){return this.laserPointerDefaultColor}}lm._IdCounter=200,lm.Name=tt.POINTER_SELECTION,lm.Version=1,it.AddWebXRFeature(lm.Name,((e,t)=>()=>new lm(e,t)),lm.Version,!0);var hm,cm,dm,um=i(4735);um.P.prototype._projectOnTrianglesToRef=function(e,t,i,n,s,r){const a=o.jp.Vector3[0],l=o.jp.Vector3[1];let h=1/0;for(let c=this.indexStart;c{if(this._controllers[e.uniqueId])return;const{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:n}=this._generateNewTouchPointMesh(),s=this._generateVisualCue();switch(this._controllers[e.uniqueId]={xrController:e,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:n,currentAnimationState:hm.DEHYDRATED,grabRay:new qe(new o.P,new o.P),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,id:pm._IdCounter++,pickedPointVisualCue:s},this._attachedController?!this._options.enableNearInteractionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enableNearInteractionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachNearInteractionMode(e);case"gaze":case"screen":return null}},this._controllers={},this._farInteractionFeature=null,this.selectionMeshDefaultColor=new a.Wo(.8,.8,.8),this.selectionMeshPickedColor=new a.Wo(.3,.3,1),this._hoverRadius=.1,this._pickRadius=.02,this._controllerPickRadius=.03,this._nearGrabLengthScale=5,this._scene=this._xrSessionManager.scene,void 0===this._options.nearInteractionControllerMode&&(this._options.nearInteractionControllerMode=cm.CENTERED_IN_FRONT),this._options.farInteractionFeature&&(this._farInteractionFeature=this._options.farInteractionFeature)}attach(){return!!super.attach()&&(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),this._scene.constantlyUpdateMeshUnderPointer=!0,!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;ie.currentAnimationState)switch(e.currentAnimationState){case hm.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===hm.HOVER)break;case hm.HOVER:if(e.touchCollisionMeshFunction(!0),t===hm.TOUCH)break}else switch(e.currentAnimationState){case hm.TOUCH:if(e.touchCollisionMeshFunction(!1),t===hm.HOVER)break;case hm.HOVER:if(e.hydrateCollisionMeshFunction(!1),t===hm.DEHYDRATED)break}e.currentAnimationState=t}}_processTouchPoint(e,t,i){var n;const s=this._controllers[e];s.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(o.jp.Vector3[0]),s.grabRay.direction.copyFrom(o.jp.Vector3[0]),this._options.nearInteractionControllerMode!==cm.CENTERED_IN_FRONT||(null===(n=s.xrController)||void 0===n?void 0:n.inputSource.hand)||(s.xrController.getWorldPointerRayToRef(this._tmpRay),s.grabRay.origin.addInPlace(this._tmpRay.direction.scale(.05))),s.grabRay.length=this._nearGrabLengthScale*this._hoverRadius,s.touchCollisionMesh.position.copyFrom(s.grabRay.origin)}_onXRFrame(e){Object.keys(this._controllers).forEach((t=>{var i;const n=this._controllers[t],s=null===(i=n.xrController)||void 0===i?void 0:i.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!n.xrController||!s&&(!this._options.nearInteractionControllerMode||!n.xrController.inputSource.gamepad))return void(n.pick=null);if(n.hoverInteraction=!1,n.nearInteraction=!1,!n.xrController)return;if(s){const i=s.get("index-finger-tip");if(i){const n=e.getJointPose(i,this._xrSessionManager.referenceSpace);if(n&&n.transform){const e=this._scene.useRightHandedSystem?1:-1;o.jp.Vector3[0].set(n.transform.position.x,n.transform.position.y,n.transform.position.z*e),o.jp.Quaternion[0].set(n.transform.orientation.x,n.transform.orientation.y,n.transform.orientation.z*e,n.transform.orientation.w*e),this._processTouchPoint(t,o.jp.Vector3[0],o.jp.Quaternion[0])}}}else if(n.xrController.inputSource.gamepad&&this._options.nearInteractionControllerMode!==cm.DISABLED){let e=n.xrController.pointer;n.xrController.grip&&this._options.nearInteractionControllerMode===cm.CENTERED_ON_CONTROLLER&&(e=n.xrController.grip),this._processTouchPoint(t,e.position,e.rotationQuaternion)}const r=(e,t)=>{let i=null;return i=t&&t.hit?e&&e.hit?t.distance{let t=new je.p,i=!1;const n=e&&e.pickedPoint&&e.hit;return(null==e?void 0:e.pickedPoint)&&(i=0===e.pickedPoint.x&&0===e.pickedPoint.y&&0===e.pickedPoint.z),n&&!i&&(t=e),t};if(!n.grabInteraction){let e=null,t=null;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(n,this._hoverRadius,this._utilityLayerScene,(e=>this._nearInteractionPredicate(e))));const i=r(this._pickWithSphere(n,this._hoverRadius,this._scene,(e=>this._nearInteractionPredicate(e))),t);if(i&&i.hit&&(e=a(i),e.hit&&(n.hoverInteraction=!0)),n.hoverInteraction){let t=null;const i=s?this._pickRadius:this._controllerPickRadius;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(n,i,this._utilityLayerScene,(e=>this._nearPickPredicate(e))));const o=a(r(this._pickWithSphere(n,i,this._scene,(e=>this._nearPickPredicate(e))),t));o.hit&&(e=o,n.nearInteraction=!0)}n.stalePick=n.pick,n.pick=e,n.pick&&n.pick.pickedPoint&&n.pick.hit?(n.meshUnderPointer=n.pick.pickedMesh,n.pickedPointVisualCue.position.copyFrom(n.pick.pickedPoint),n.pickedPointVisualCue.isVisible=!0,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(n.id,!0)):(n.meshUnderPointer=null,n.pickedPointVisualCue.isVisible=!1,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(n.id,!1))}let l=hm.DEHYDRATED;n.grabInteraction||n.nearInteraction?l=hm.TOUCH:n.hoverInteraction&&(l=hm.HOVER),this._handleTransitionAnimation(n,l)}))}get _utilityLayerScene(){return this._options.customUtilityLayerScene||dl.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||dl.DefaultUtilityLayer.utilityLayerScene:this._scene,t=gl("nearInteraction",{diameter:.0105},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=o._f.Identity();const i=new _a("targetMat",e);return i.specularColor=a.Wo.Black(),i.emissiveColor=this.selectionMeshDefaultColor,i.backFaceCulling=!1,t.material=i,t}_isControllerReadyForNearInteraction(e){return!this._farInteractionFeature||this._farInteractionFeature._getPointerSelectionDisabledByPointerId(e)}_attachNearInteractionMode(e){const t=this._controllers[e.uniqueId],i={pointerId:t.id,pointerType:"xr-near"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{(this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController)&&t.xrController&&(t.xrController.inputSource.hand||this._options.nearInteractionControllerMode&&t.xrController.inputSource.gamepad)&&(t.pick&&(t.pick.ray=t.grabRay),t.pick&&this._isControllerReadyForNearInteraction(t.id)&&this._scene.simulatePointerMove(t.pick,i),t.nearInteraction&&t.pick&&t.pick.hit?t.nearInteractionTargetMesh||(this._scene.simulatePointerDown(t.pick,i),t.nearInteractionTargetMesh=t.meshUnderPointer):t.nearInteractionTargetMesh&&t.stalePick&&(this._scene.simulatePointerUp(t.stalePick,i),t.nearInteractionTargetMesh=null))}));const n=n=>{this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController&&this._isControllerReadyForNearInteraction(t.id)?(t.pick&&(t.pick.ray=t.grabRay),n&&t.pick&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)?(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i)):!n&&t.pick&&t.grabInteraction&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)):!n||this._options.enableNearInteractionOnAllControllers||this._options.disableSwitchOnClick||(this._attachedController=e.uniqueId)};if(e.inputSource.gamepad){const i=e=>{t.squeezeComponent=e.getComponent("grasp"),t.squeezeComponent?t.onSqueezeButtonChangedObserver=t.squeezeComponent.onButtonStateChangedObservable.add((e=>{if(e.changes.pressed){const t=e.changes.pressed.current;n(t)}})):(t.selectionComponent=e.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add((e=>{if(e.changes.pressed){const t=e.changes.pressed.current;n(t)}})))};e.motionController?i(e.motionController):e.onMotionControllerInitObservable.add(i)}else{const e=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)&&(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i))},n=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)};t.eventListeners={selectend:n,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",n)}}_detachController(e){const t=this._controllers[e];if(t&&(t.squeezeComponent&&t.onSqueezeButtonChangedObserver&&t.squeezeComponent.onButtonStateChangedObservable.remove(t.onSqueezeButtonChangedObserver),t.selectionComponent&&t.onButtonChangedObserver&&t.selectionComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver),t.onFrameObserver&&this._xrSessionManager.onXRFrameObservable.remove(t.onFrameObserver),t.eventListeners&&Object.keys(t.eventListeners).forEach((e=>{const i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)})),t.touchCollisionMesh.dispose(),t.pickedPointVisualCue.dispose(),this._xrSessionManager.runInXRFrame((()=>{const e={pointerId:t.id,pointerType:"xr-near"};this._scene.simulatePointerUp(new je.p,e)})),delete this._controllers[e],this._attachedController===e)){const e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}_generateNewTouchPointMesh(){const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||dl.DefaultUtilityLayer.utilityLayerScene:this._scene,t=gl("PickSphere",{diameter:1},e);t.isVisible=!1,this._options.motionControllerOrbMaterial?t.material=this._options.motionControllerOrbMaterial:Ni.ParseFromSnippetAsync("8RUNKL#3",e).then((e=>{t.material=e}));const i=new K;i.setEasingMode(Y.EASINGMODE_EASEINOUT);const n=new o.P(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius),s=this._controllerPickRadius*(4/3),r=new o.P(s,s,s),a=this._controllerPickRadius*(7/6),l=new o.P(a,a,a),h=.8*this._controllerPickRadius,c=new o.P(h,h,h),d=1.5*this._controllerPickRadius,u=[{frame:0,value:n},{frame:10,value:new o.P(d,d,d)},{frame:18,value:r}],p=[{frame:0,value:r},{frame:10,value:c},{frame:18,value:n}],f=[{frame:0,value:o.P.ZeroReadOnly},{frame:12,value:l},{frame:15,value:n}],_=[{frame:0,value:n},{frame:10,value:o.P.ZeroReadOnly},{frame:15,value:o.P.ZeroReadOnly}],m=new A("touch","scaling",60,A.ANIMATIONTYPE_VECTOR3,A.ANIMATIONLOOPMODE_CONSTANT),g=new A("release","scaling",60,A.ANIMATIONTYPE_VECTOR3,A.ANIMATIONLOOPMODE_CONSTANT),v=new A("hydrate","scaling",60,A.ANIMATIONTYPE_VECTOR3,A.ANIMATIONLOOPMODE_CONSTANT),T=new A("dehydrate","scaling",60,A.ANIMATIONTYPE_VECTOR3,A.ANIMATIONLOOPMODE_CONSTANT);m.setEasingFunction(i),g.setEasingFunction(i),v.setEasingFunction(i),T.setEasingFunction(i),m.setKeys(u),g.setKeys(p),v.setKeys(f),T.setKeys(_);return{touchCollisionMesh:t,touchCollisionMeshFunction:i=>{const n=i?m:g;e.beginDirectAnimation(t,[n],0,18,!1,1)},hydrateCollisionMeshFunction:i=>{const n=i?v:T;i&&(t.isVisible=!0),e.beginDirectAnimation(t,[n],0,15,!1,1,(()=>{i||(t.isVisible=!1)}))}}}_pickWithSphere(e,t,i,n){const s=new je.p;if(s.distance=1/0,e.touchCollisionMesh&&e.xrController){const r=e.touchCollisionMesh.position,o=al.K.CreateFromCenterAndRadius(r,t);for(let t=0;tc&&(h=0,l.copyFrom(t.center)),-1!==h&&h()=>new pm(e,t)),pm.Version,!0);class fm{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}}class _m{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new r.y$,this._onSessionGranted=e=>{this._helper&&this._enterXRWithButtonIndex(0)},this.overlay=document.createElement("div"),this.overlay.classList.add("xr-button-overlay"),!t.ignoreSessionGrantedEvent&&navigator.xr&&navigator.xr.addEventListener("sessiongranted",this._onSessionGranted),"undefined"!=typeof window&&window.location&&"http:"===window.location.protocol&&"localhost"!==window.location.hostname)throw se.w1.Warn("WebXR can only be served over HTTPS"),new Error("WebXR can only be served over HTTPS");if(t.customButtons)this._buttons=t.customButtons;else{this.overlay.style.cssText="z-index:11;position: absolute; right: 20px;bottom: 50px;";const e=t.sessionMode||"immersive-vr",i=t.referenceSpaceType||"local-floor";let n=".babylonVRicon { color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+("undefined"==typeof SVGSVGElement?"https://cdn.babylonjs.com/Assets/vrButton.png":"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";n+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';const s=document.createElement("style");s.appendChild(document.createTextNode(n)),document.getElementsByTagName("head")[0].appendChild(s);const r=document.createElement("button");r.className="babylonVRicon",r.title=`${e} - ${i}`,this._buttons.push(new fm(r,e,i)),this._buttons[this._buttons.length-1].update=function(e){this.element.style.display=null===e||e===this?"":"none",r.className="babylonVRicon"+(e===this?" vrdisplaypresenting":"")},this._updateButtons(null)}const i=e.getEngine().getInputElement();i&&i.parentNode&&(i.parentNode.appendChild(this.overlay),e.onDisposeObservable.addOnce((()=>{this.dispose()})))}async setHelperAsync(e,t){this._helper=e,this._renderTarget=t;const i=this._buttons.map((t=>e.sessionManager.isSessionSupportedAsync(t.sessionMode)));e.onStateChangedObservable.add((e=>{e==Ea.NOT_IN_XR&&this._updateButtons(null)}));(await Promise.all(i)).forEach(((e,t)=>{e?(this.overlay.appendChild(this._buttons[t].element),this._buttons[t].element.onclick=this._enterXRWithButtonIndex.bind(this,t)):se.w1.Warn(`Session mode "${this._buttons[t].sessionMode}" not supported in browser`)}))}static async CreateAsync(e,t,i){const n=new _m(e,i);return await n.setHelperAsync(t,i.renderTarget||void 0),n}async _enterXRWithButtonIndex(e=0){if(this._helper.state==Ea.IN_XR)await this._helper.exitXRAsync(),this._updateButtons(null);else if(this._helper.state==Ea.NOT_IN_XR)try{await this._helper.enterXRAsync(this._buttons[e].sessionMode,this._buttons[e].referenceSpaceType,this._renderTarget,{optionalFeatures:this.options.optionalFeatures,requiredFeatures:this.options.requiredFeatures}),this._updateButtons(this._buttons[e])}catch(t){this._updateButtons(null);const i=this._buttons[e].element,n=i.title;i.title="Error entering XR session : "+n,i.classList.add("xr-error"),this.options.onError&&this.options.onError(t)}}dispose(){const e=this._scene.getEngine().getInputElement();e&&e.parentNode&&e.parentNode.contains(this.overlay)&&e.parentNode.removeChild(this.overlay),this.activeButtonChangedObservable.clear(),navigator.xr.removeEventListener("sessiongranted",this._onSessionGranted)}_updateButtons(e){this._activeButton=e,this._buttons.forEach((e=>{e.update(this._activeButton)})),this.activeButtonChangedObservable.notifyObservers(this._activeButton)}}function mm(e){var t;let i=0;const n=Date.now();e.observableParameters=null!==(t=e.observableParameters)&&void 0!==t?t:{};const s=e.contextObservable.add((t=>{const r=Date.now();i=r-n;const o={startTime:n,currentTime:r,deltaTime:i,completeRate:i/e.timeout,payload:t};e.onTick&&e.onTick(o),e.breakCondition&&e.breakCondition()&&(e.contextObservable.remove(s),e.onAborted&&e.onAborted(o)),i>=e.timeout&&(e.contextObservable.remove(s),e.onEnded&&e.onEnded(o))}),e.observableParameters.mask,e.observableParameters.insertFirst,e.observableParameters.scope);return s}!function(e){e[e.INIT=0]="INIT",e[e.STARTED=1]="STARTED",e[e.ENDED=2]="ENDED"}(dm||(dm={}));class gm extends nt{get rotationEnabled(){return this._rotationEnabled}set rotationEnabled(e){if(this._rotationEnabled=e,this._options.teleportationTargetMesh){const t=this._options.teleportationTargetMesh.getChildMeshes(!1,(e=>"rotationCone"===e.name));t[0]&&t[0].setEnabled(e)}}get teleportationTargetMesh(){return this._options.teleportationTargetMesh||null}constructor(e,t){super(e),this._options=t,this._controllers={},this._snappedToPoint=!1,this._cachedColor4White=new a.HE(1,1,1,1),this._tmpRay=new qe(new o.P,new o.P),this._tmpVector=new o.P,this._tmpQuaternion=new o._f,this.skipNextTeleportation=!1,this.backwardsMovementEnabled=!0,this.backwardsTeleportationDistance=.7,this.parabolicCheckRadius=5,this.parabolicRayEnabled=!0,this.straightRayEnabled=!0,this.rotationAngle=Math.PI/8,this.onTargetMeshPositionUpdatedObservable=new r.y$,this.teleportationEnabled=!0,this._rotationEnabled=!0,this._attachController=e=>{if(this._controllers[e.uniqueId]||this._options.forceHandedness&&e.inputSource.handedness!==this._options.forceHandedness)return;this._controllers[e.uniqueId]={xrController:e,teleportationState:{forward:!1,backwards:!1,rotating:!1,currentRotation:0,baseRotation:0,blocked:!1}};const t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){const i=()=>{if(e.motionController){const i=e.motionController.getComponentOfType(Z_.THUMBSTICK_TYPE)||e.motionController.getComponentOfType(Z_.TOUCHPAD_TYPE);if(!i||this._options.useMainComponentOnly){const i=e.motionController.getMainComponent();if(!i)return;t.teleportationComponent=i,t.onButtonChangedObserver=i.onButtonStateChangedObservable.add((()=>{if(this.teleportationEnabled&&i.changes.pressed)if(i.changes.pressed.current){t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0;mm({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,breakCondition:()=>!i.pressed,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})}else t.teleportationState.forward=!1,this._currentTeleportationControllerId=""}))}else t.teleportationComponent=i,t.onAxisChangedObserver=i.onAxisValueChangedObservable.add((i=>{if(i.y<=.7&&t.teleportationState.backwards&&(t.teleportationState.backwards=!1),i.y>.7&&!t.teleportationState.forward&&this.backwardsMovementEnabled&&!this.snapPointsOnly&&!t.teleportationState.backwards){t.teleportationState.backwards=!0,this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion),this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector),this._tmpVector.x=0,this._tmpVector.z=0,o._f.FromEulerVectorToRef(this._tmpVector,this._tmpQuaternion),this._tmpVector.set(0,0,this.backwardsTeleportationDistance*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),this._tmpVector.rotateByQuaternionToRef(this._tmpQuaternion,this._tmpVector),this._tmpVector.addInPlace(this._options.xrInput.xrCamera.position),this._tmpRay.origin.copyFrom(this._tmpVector),this._tmpRay.length=this._options.xrInput.xrCamera.realWorldHeight+.1,this._tmpRay.direction.set(0,-1,0);const e=this._xrSessionManager.scene.pickWithRay(this._tmpRay,(e=>-1!==this._floorMeshes.indexOf(e)));e&&e.pickedPoint&&(this._options.xrInput.xrCamera.position.x=e.pickedPoint.x,this._options.xrInput.xrCamera.position.z=e.pickedPoint.z)}if(i.y<-.7&&!this._currentTeleportationControllerId&&!t.teleportationState.rotating&&this.teleportationEnabled&&(t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),i.x){if(t.teleportationState.forward)this._currentTeleportationControllerId===t.xrController.uniqueId&&(this.rotationEnabled?setTimeout((()=>{t.teleportationState.currentRotation=Math.atan2(i.x,i.y*(this._xrSessionManager.scene.useRightHandedSystem?1:-1))})):t.teleportationState.currentRotation=0);else if(!t.teleportationState.rotating&&Math.abs(i.x)>.7){t.teleportationState.rotating=!0;const e=this.rotationAngle*(i.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);o._f.FromEulerAngles(0,e,0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion)}}else t.teleportationState.rotating=!1;0===i.x&&0===i.y&&(t.teleportationState.blocked&&(t.teleportationState.blocked=!1,this._setTargetMeshVisibility(!1)),t.teleportationState.forward&&this._teleportForward(e.uniqueId))}))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce((()=>{i()}))}else this._xrSessionManager.scene.onPointerObservable.add((i=>{if(i.type===We.kD.POINTERDOWN){t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0;mm({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})}else i.type===We.kD.POINTERUP&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="")}))},this._options.teleportationTargetMesh||this._createDefaultTargetMesh(),this._floorMeshes=this._options.floorMeshes||[],this._snapToPositions=this._options.snapPositions||[],this._blockedRayColor=this._options.blockedRayColor||new a.HE(1,0,0,.75),this._setTargetMeshVisibility(!1)}get snapPointsOnly(){return!!this._options.snapPointsOnly}set snapPointsOnly(e){this._options.snapPointsOnly=e}addFloorMesh(e){this._floorMeshes.push(e)}addBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[],this._options.pickBlockerMeshes.push(e)}addSnapPoint(e){this._snapToPositions.push(e)}attach(){return!!super.attach()&&(this._currentTeleportationControllerId="",this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._setTargetMeshVisibility(!1),this._currentTeleportationControllerId="",this._controllers={},!0)}dispose(){super.dispose(),this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.dispose(!1,!0)}removeFloorMesh(e){const t=this._floorMeshes.indexOf(e);-1!==t&&this._floorMeshes.splice(t,1)}removeBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[];const t=this._options.pickBlockerMeshes.indexOf(e);-1!==t&&this._options.pickBlockerMeshes.splice(t,1)}removeFloorMeshByName(e){const t=this._xrSessionManager.scene.getMeshByName(e);t&&this.removeFloorMesh(t)}removeSnapPoint(e){let t=this._snapToPositions.indexOf(e);if(-1===t)for(let i=0;i{if(this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(e))return!0;const t=this._floorMeshes.indexOf(e);return-1!==t&&this._floorMeshes[t].absolutePosition.y!(!this._options.pickBlockerMeshes||-1===this._options.pickBlockerMeshes.indexOf(e))||-1!==this._floorMeshes.indexOf(e)));if(o&&o.pickedMesh&&this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(o.pickedMesh))return e.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1),void this._showParabolicPath(o);o&&o.pickedPoint&&(e.teleportationState.blocked=!1,t=!0,this._setTargetMeshPosition(o),this._setTargetMeshVisibility(!0),this._showParabolicPath(o))}this._setTargetMeshVisibility(t)}else this._setTargetMeshVisibility(!1)}else this._disposeBezierCurve(),this._setTargetMeshVisibility(!1)}_createDefaultTargetMesh(){this._options.defaultTargetMeshOptions=this._options.defaultTargetMeshOptions||{};const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||dl.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=Ga("teleportationTarget",{width:2,height:2,subdivisions:2},e);if(t.isPickable=!1,this._options.defaultTargetMeshOptions.teleportationCircleMaterial)t.material=this._options.defaultTargetMeshOptions.teleportationCircleMaterial;else{const i=512,n=new ma("teleportationPlaneDynamicTexture",i,e,!0);n.hasAlpha=!0;const s=n.getContext(),r=i/2,o=i/2,a=200;s.beginPath(),s.arc(r,o,a,0,2*Math.PI,!1),s.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",s.fill(),s.lineWidth=10,s.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",s.stroke(),s.closePath(),n.update();const l=new _a("teleportationPlaneMaterial",e);l.diffuseTexture=n,t.material=l}const i=La("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){const t=new A("animationInnerCircle","position.y",30,A.ANIMATIONTYPE_FLOAT,A.ANIMATIONLOOPMODE_CYCLE),n=[];n.push({frame:0,value:0}),n.push({frame:30,value:.4}),n.push({frame:60,value:0}),t.setKeys(n);const s=new q;s.setEasingMode(Y.EASINGMODE_EASEINOUT),t.setEasingFunction(s),i.animations=[],i.animations.push(t),e.beginAnimation(i,0,60,!0)}const n=Fa("rotationCone",{diameterTop:0,tessellation:4},e);if(n.isPickable=!1,n.scaling.set(.5,.12,.2),n.rotate(L.RD.X,Math.PI/2),n.position.z=.6,n.parent=i,this._options.defaultTargetMeshOptions.torusArrowMaterial)i.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,n.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{const t=new _a("torusConsMat",e);t.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,t.disableLighting?t.emissiveColor=new a.Wo(.3,.3,1):t.diffuseColor=new a.Wo(.3,.3,1),t.alpha=.9,i.material=t,n.material=t,this._teleportationRingMaterial=t}void 0!==this._options.renderingGroupId&&(t.renderingGroupId=this._options.renderingGroupId,i.renderingGroupId=this._options.renderingGroupId,n.renderingGroupId=this._options.renderingGroupId),this._options.teleportationTargetMesh=t,this._setTargetMeshVisibility(!1)}_detachController(e){const t=this._controllers[e];t&&(t.teleportationComponent&&(t.onAxisChangedObserver&&t.teleportationComponent.onAxisValueChangedObservable.remove(t.onAxisChangedObserver),t.onButtonChangedObserver&&t.teleportationComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver)),delete this._controllers[e])}_findClosestSnapPointWithRadius(e,t=this._options.snapToPositionRadius||.8){let i=null,n=Number.MAX_VALUE;if(this._snapToPositions.length){const s=t*t;this._snapToPositions.forEach((t=>{const r=o.P.DistanceSquared(t,e);r<=s&&r{t.isVisible=e})),e?this._selectionFeature&&this._selectionFeature.detach():(this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null),this._selectionFeature&&this._selectionFeature.attach()))}_disposeBezierCurve(){this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null)}_showParabolicPath(e){if(!e.pickedPoint||!this._currentTeleportationControllerId)return;const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||dl.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],n=X.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),s=i.teleportationState.blocked?this._blockedRayColor:void 0,r=new Array(26).fill(s||this._cachedColor4White);this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(n.getPoints(),e):this._quadraticBezierCurve=Vl("teleportation path line",{points:n.getPoints(),instance:this._quadraticBezierCurve,updatable:!0,colors:r},t),this._quadraticBezierCurve.isPickable=!1,void 0!==this._options.renderingGroupId&&(this._quadraticBezierCurve.renderingGroupId=this._options.renderingGroupId)}_teleportForward(e){const t=this._controllers[e];if(t&&t.teleportationState.forward&&this.teleportationEnabled&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="",!this.snapPointsOnly||this._snappedToPoint))if(this.skipNextTeleportation)this.skipNextTeleportation=!1;else if(this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.isVisible){const e=this._options.xrInput.xrCamera.realWorldHeight;this._options.xrInput.xrCamera.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position),this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position),this._options.xrInput.xrCamera.position.y+=e,o._f.FromEulerAngles(0,t.teleportationState.currentRotation-(this._xrSessionManager.scene.useRightHandedSystem?Math.PI:0),0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this._options.xrInput.xrCamera.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position)}}}gm.Name=tt.TELEPORTATION,gm.Version=1,it.AddWebXRFeature(gm.Name,((e,t)=>()=>new gm(e,t)),gm.Version,!0);class vm{constructor(){}static CreateAsync(e,t={}){const i=new vm;if(e.onDisposeObservable.addOnce((()=>{i.dispose()})),!t.disableDefaultUI){const n=Object.assign({renderTarget:i.renderTarget},t.uiOptions||{});t.optionalFeatures&&("boolean"==typeof t.optionalFeatures?n.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:n.optionalFeatures=t.optionalFeatures),i.enterExitUI=new _m(e,n)}return Q_.CreateAsync(e).then((e=>{if(i.baseExperience=e,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new am(e.sessionManager,e.camera,Object.assign({controllerOptions:{renderingGroupId:t.renderingGroupId}},t.inputOptions||{})),!t.disablePointerSelection){const e=Object.assign(Object.assign({},t.pointerSelectionOptions),{xrInput:i.input,renderingGroupId:t.renderingGroupId});i.pointerSelection=i.baseExperience.featuresManager.enableFeature(lm.Name,t.useStablePlugins?"stable":"latest",e),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(gm.Name,t.useStablePlugins?"stable":"latest",Object.assign({floorMeshes:t.floorMeshes,xrInput:i.input,renderingGroupId:t.renderingGroupId},t.teleportationOptions)),i.teleportation.setSelectionFeature(i.pointerSelection))}return t.disableNearInteraction||(i.nearInteraction=i.baseExperience.featuresManager.enableFeature(pm.Name,t.useStablePlugins?"stable":"latest",Object.assign({xrInput:i.input,farInteractionFeature:i.pointerSelection,renderingGroupId:t.renderingGroupId,useUtilityLayer:!0,enableNearInteractionOnAllControllers:!0},t.nearInteractionOptions))),i.renderTarget=i.baseExperience.sessionManager.getWebXRRenderTarget(t.outputCanvasOptions),t.disableDefaultUI?void 0:i.enterExitUI.setHelperAsync(i.baseExperience,i.renderTarget)})).then((()=>i)).catch((e=>(p.Y.Error("Error initializing XR"),p.Y.Error(e),i)))}dispose(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()}}function Tm(e){for(;e.firstChild;)e.removeChild(e.firstChild);e.srcObject=null,e.src="",e.removeAttribute("src")}N.x.prototype.createDefaultLight=function(e=!1){if(e&&this.lights)for(let t=0;te.isVisible&&e.isEnabled())),n=t.max.subtract(t.min),s=t.min.add(n.scale(.5));let r,a=1.5*n.length();if(isFinite(a)||(a=1,s.copyFromFloats(0,0,0)),e){const e=new Ln("default camera",-Math.PI/2,Math.PI/2,a,s,this);e.lowerRadiusLimit=.01*a,e.wheelPrecision=100/a,r=e}else{const e=new Fn("default camera",new o.P(s.x,s.y,-a),this);e.setTarget(s),r=e}r.minZ=.01*a,r.maxZ=1e3*a,r.speed=.2*a,this.activeCamera=r,i&&r.attachControl()}},N.x.prototype.createDefaultCameraOrLight=function(e=!1,t=!1,i=!1){this.createDefaultLight(t),this.createDefaultCamera(e,t,i)},N.x.prototype.createDefaultSkybox=function(e,t=!1,i=1e3,n=0,s=!0){if(!e)return p.Y.Warn("Can not create default skybox without environment texture."),null;s&&e&&(this.environmentTexture=e);const r=_l("hdrSkyBox",{size:i},this);if(t){const t=new O_("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=Le.SKYBOX_MODE),t.microSurface=1-n,t.disableLighting=!0,t.twoSidedLighting=!0,r.material=t}else{const t=new _a("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=Le.SKYBOX_MODE),t.disableLighting=!0,r.material=t}return r.isPickable=!1,r.infiniteDistance=!0,r.ignoreCameraMaxZ=!0,r},N.x.prototype.createDefaultEnvironment=function(e){return Up?new Up(e,this):null},N.x.prototype.createDefaultVRExperience=function(e={}){return new ja(this,e)},N.x.prototype.createDefaultXRExperienceAsync=function(e={}){return vm.CreateAsync(this,e).then((e=>e))};class Sm extends Le{get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new r.y$),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(null==e?void 0:e.message):p.Y.Error(null==e?void 0:e.message)}_handlePlay(){this._errorFound=!1,this.video.play().catch((e=>{if("NotAllowedError"===(null==e?void 0:e.name)){if(this._onUserActionRequestedObservable&&this._onUserActionRequestedObservable.hasObservers())return void this._onUserActionRequestedObservable.notifyObservers(this);if(!this.video.muted)return p.Y.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"),this.video.muted=!0,this._errorFound=!1,void this.video.play().catch((e=>{this._processError(e)}))}this._processError(e)}))}constructor(e,t,i,n=!1,s=!1,r=Le.TRILINEAR_SAMPLINGMODE,o={},a,l=5){var h,c;super(null,i,!n,s),this._onUserActionRequestedObservable=null,this._stillImageCaptured=!1,this._displayingPosterTexture=!1,this._frameId=-1,this._currentSrc=null,this._errorFound=!1,this._resizeInternalTexture=()=>{var e;null!=this._texture&&this._texture.dispose(),!this._getEngine().needPOTTextures||se.w1.IsExponentOfTwo(this.video.videoWidth)&&se.w1.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=Le.WRAP_ADDRESSMODE,this.wrapV=Le.WRAP_ADDRESSMODE):(this.wrapU=Le.CLAMP_ADDRESSMODE,this.wrapV=Le.CLAMP_ADDRESSMODE,this._generateMipMaps=!1),this._texture=this._getEngine().createDynamicTexture(this.video.videoWidth,this.video.videoHeight,this._generateMipMaps,this.samplingMode),this._texture.format=null!==(e=this._format)&&void 0!==e?e:5,this._frameId=-1,this._updateInternalTexture()},this._createInternalTexture=()=>{if(null!=this._texture){if(!this._displayingPosterTexture)return;this._displayingPosterTexture=!1}if(this.video.addEventListener("resize",this._resizeInternalTexture),this._resizeInternalTexture(),this.video.autoplay||this._settings.poster||this._settings.independentVideoSource)this._updateInternalTexture(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this);else{const e=this.video.onplaying,t=this.video.muted;this.video.muted=!0,this.video.onplaying=()=>{this.video.muted=t,this.video.onplaying=e,this._updateInternalTexture(),this._errorFound||this.video.pause(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this)},this._handlePlay()}},this._reset=()=>{null!=this._texture&&(this._displayingPosterTexture||(this._texture.dispose(),this._texture=null))},this._updateInternalTexture=()=>{if(null==this._texture)return;if(this.video.readyState=this.video.HAVE_CURRENT_DATA;!this._settings.poster||this._settings.autoPlay&&d?d&&this._createInternalTexture():(this._texture=this._getEngine().createTexture(this._settings.poster,!1,!this.invertY,i),this._displayingPosterTexture=!0)}getClassName(){return"VideoTexture"}_getName(e){return e instanceof HTMLVideoElement?e.currentSrc:"object"==typeof e?e.toString():e}_getVideo(e){if(e.isNative)return e;if(e instanceof HTMLVideoElement)return se.w1.SetCorsBehavior(e.currentSrc,e),e;const t=document.createElement("video");return"string"==typeof e?(se.w1.SetCorsBehavior(e,t),t.src=e):(se.w1.SetCorsBehavior(e[0],t),e.forEach((e=>{const i=document.createElement("source");i.src=e,t.appendChild(i)}))),this.onDisposeObservable.addOnce((()=>{Tm(t)})),t}_rebuild(){this.update()}update(){this.autoUpdateTexture&&this.updateTexture(!0)}updateTexture(e){e&&(this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture()))}updateURL(e){this.video.src=e,this._currentSrc=e}clone(){return new Sm(this.name,this._currentSrc,this.getScene(),this._generateMipMaps,this.invertY,this.samplingMode,this._settings)}dispose(){var e;super.dispose(),this._currentSrc=null,this._onUserActionRequestedObservable&&(this._onUserActionRequestedObservable.clear(),this._onUserActionRequestedObservable=null),this.video.removeEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this._settings.independentVideoSource||(this.video.removeEventListener("paused",this._updateInternalTexture),this.video.removeEventListener("seeked",this._updateInternalTexture),this.video.removeEventListener("emptied",this._reset),this.video.removeEventListener("resize",this._resizeInternalTexture),this.video.pause()),null===(e=this._externalTexture)||void 0===e||e.dispose()}static CreateFromStreamAsync(e,t,i,n=!0){const s=e.getEngine().createVideoElement(i);return e.getEngine()._badOS&&(document.body.appendChild(s),s.style.transform="scale(0.0001, 0.0001)",s.style.opacity="0",s.style.position="fixed",s.style.bottom="0px",s.style.right="0px"),s.setAttribute("autoplay",""),s.setAttribute("muted","true"),s.setAttribute("playsinline",""),s.muted=!0,s.isNative||(void 0!==s.mozSrcObject?s.mozSrcObject=t:"object"==typeof s.srcObject?s.srcObject=t:s.src=window.URL&&window.URL.createObjectURL(t)),new Promise((t=>{const i=()=>{const r=new Sm("video",s,e,!0,n,void 0,void 0,void 0,4);e.getEngine()._badOS&&r.onDisposeObservable.addOnce((()=>{s.remove()})),r.onDisposeObservable.addOnce((()=>{Tm(s)})),t(r),s.removeEventListener("playing",i)};s.addEventListener("playing",i),s.play()}))}static async CreateFromWebCamAsync(e,t,i=!1,n=!0){if(navigator.mediaDevices){const s=await navigator.mediaDevices.getUserMedia({video:t,audio:i}),r=await this.CreateFromStreamAsync(e,s,t,n);return r.onDisposeObservable.addOnce((()=>{s.getTracks().forEach((e=>{e.stop()}))})),r}return Promise.reject("No support for userMedia on this device")}static CreateFromWebCam(e,t,i,n=!1,s=!0){this.CreateFromWebCamAsync(e,i,n,s).then((function(e){t&&t(e)})).catch((function(e){p.Y.Error(e.name)}))}}class Em extends Vp{get videoTexture(){return this._texture}get videoMode(){return this.textureMode}set videoMode(e){this.textureMode=e}_initTexture(e,t,i){const n={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},s=new Sm((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,Le.TRILINEAR_SAMPLINGMODE,n);return i.clickToPlay&&(this._pointerObserver=t.onPointerObservable.add((e=>{var t;(null===(t=e.pickInfo)||void 0===t?void 0:t.pickedMesh)===this.mesh&&this._texture.video.play()}),We.kD.POINTERDOWN)),this._textureObserver=s.onLoadObservable.add((()=>{this.onLoadObservable.notifyObservers()})),s}dispose(e,t=!1){this._texture.onLoadObservable.remove(this._textureObserver),this._scene.onPointerObservable.remove(this._pointerObserver),super.dispose(e,t)}}Em.MODE_MONOSCOPIC=Vp.MODE_MONOSCOPIC,Em.MODE_TOPBOTTOM=Vp.MODE_TOPBOTTOM,Em.MODE_SIDEBYSIDE=Vp.MODE_SIDEBYSIDE;const xm="glowMapGenerationPixelShader",bm="#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)\n#include\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;\nuniform sampler2D opacitySampler;\nuniform float opacityIntensity;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef VERTEXALPHA\nvarying vec4 vColor;\n#endif\nuniform vec4 glowColor;\nuniform float glowIntensity;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\nvec4 finalColor=glowColor;\n#ifdef DIFFUSE\nvec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse);\n#ifdef DIFFUSE_ISLINEAR\nalbedoTexture=toGammaSpace(albedoTexture);\n#endif\n#ifdef GLOW\nfinalColor.a*=albedoTexture.a;\n#endif\n#ifdef HIGHLIGHT\nfinalColor.a=albedoTexture.a;\n#endif\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vUVOpacity);\n#ifdef OPACITYRGB\nfinalColor.a*=getLuminance(opacityMap.rgb);\n#else\nfinalColor.a*=opacityMap.a;\n#endif\nfinalColor.a*=opacityIntensity;\n#endif\n#ifdef VERTEXALPHA\nfinalColor.a*=vColor.a;\n#endif\n#ifdef ALPHATEST\nif (finalColor.a{if((i||0===t)&&e.subMeshes)for(let n=0;n{let s;this.onBeforeRenderMainTextureObservable.notifyObservers(this);const r=this._scene.getEngine();if(n.length){for(r.setColorWrite(!1),s=0;s{e.clear(this.neutralColor,!0,!0,!0)})),this._scene.getBoundingBoxRenderer){const e=this._scene.getBoundingBoxRenderer().enabled;this._mainTexture.onBeforeBindObservable.add((()=>{this._scene.getBoundingBoxRenderer().enabled=!this.disableBoundingBoxesFromEffectLayer&&e})),this._mainTexture.onAfterUnbindObservable.add((()=>{this._scene.getBoundingBoxRenderer().enabled=e}))}}_addCustomEffectDefines(e){}_isReady(e,t,i){var n;const s=this._scene.getEngine(),r=e.getMesh(),o=null===(n=r._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===n?void 0:n[s.currentRenderPassId];if(o)return o.isReadyForSubMesh(r,e,t);const a=e.getMaterial();if(!a)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return a.isReadyForSubMesh(e.getMesh(),e,t);const l=[],h=[ne.o.PositionKind];let c=!1,d=!1;if(a){const e=a.needAlphaTesting(),t=a.getAlphaTestTexture(),i=t&&t.hasAlpha&&(a.useAlphaFromDiffuseTexture||a._useAlphaFromAlbedoTexture);t&&(e||i)&&(l.push("#define DIFFUSE"),r.isVerticesDataPresent(ne.o.UV2Kind)&&1===t.coordinatesIndex?(l.push("#define DIFFUSEUV2"),d=!0):r.isVerticesDataPresent(ne.o.UVKind)&&(l.push("#define DIFFUSEUV1"),c=!0),e&&(l.push("#define ALPHATEST"),l.push("#define ALPHATESTVALUE 0.4")),t.gammaSpace||l.push("#define DIFFUSE_ISLINEAR"));const n=a.opacityTexture;n&&(l.push("#define OPACITY"),r.isVerticesDataPresent(ne.o.UV2Kind)&&1===n.coordinatesIndex?(l.push("#define OPACITYUV2"),d=!0):r.isVerticesDataPresent(ne.o.UVKind)&&(l.push("#define OPACITYUV1"),c=!0))}i&&(l.push("#define EMISSIVE"),r.isVerticesDataPresent(ne.o.UV2Kind)&&1===i.coordinatesIndex?(l.push("#define EMISSIVEUV2"),d=!0):r.isVerticesDataPresent(ne.o.UVKind)&&(l.push("#define EMISSIVEUV1"),c=!0),i.gammaSpace||l.push("#define EMISSIVE_ISLINEAR")),r.useVertexColors&&r.isVerticesDataPresent(ne.o.ColorKind)&&r.hasVertexAlpha&&a.transparencyMode!==ut.F.MATERIAL_OPAQUE&&(h.push(ne.o.ColorKind),l.push("#define VERTEXALPHA")),c&&(h.push(ne.o.UVKind),l.push("#define UV1")),d&&(h.push(ne.o.UV2Kind),l.push("#define UV2"));const u=new zt;if(r.useBones&&r.computeBonesUsingShaders){h.push(ne.o.MatricesIndicesKind),h.push(ne.o.MatricesWeightsKind),r.numBoneInfluencers>4&&(h.push(ne.o.MatricesIndicesExtraKind),h.push(ne.o.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers);const e=r.skeleton;e&&e.isUsingTextureForMatrices?l.push("#define BONETEXTURE"):l.push("#define BonesPerMesh "+(e?e.bones.length+1:0)),r.numBoneInfluencers>0&&u.addCPUSkinningFallback(0,r)}else l.push("#define NUM_BONE_INFLUENCERS 0");const p=r.morphTargetManager;let f=0;p&&p.numInfluencers>0&&(l.push("#define MORPHTARGETS"),f=p.numInfluencers,l.push("#define NUM_MORPH_INFLUENCERS "+f),p.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),It.G.PrepareAttributesForMorphTargetsInfluencers(h,r,f)),t&&(l.push("#define INSTANCES"),It.G.PushAttributesForInstances(h),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),(0,ua.lK)(a,this._scene,l),this._addCustomEffectDefines(l);const _=e._getDrawWrapper(void 0,!0),m=_.defines,g=l.join("\n");if(m!==g){const e=["world","mBones","viewProjection","glowColor","morphTargetInfluences","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];(0,ua.qx)(e),_.setEffect(this._engine.createEffect("glowMapGeneration",h,e,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],g,u,void 0,void 0,{maxSimultaneousMorphTargets:f}),g)}return _.effect.isReady()}render(){for(let r=0;ro.setMatrix("world",t)))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(r)}_useMeshMaterial(e){return!1}_rebuild(){const e=this._vertexBuffers[ne.o.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()}_disposeTextureAndPostProcesses(){this._mainTexture.dispose();for(let e=0;e-1&&this._scene.effectLayers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()}getClassName(){return"EffectLayer"}static Parse(e,t,i){return se.w1.Instantiate(e.customType).Parse(e,t,i)}}Am._SceneComponentInitialization=e=>{throw(0,ge.S)("EffectLayerSceneComponent")},(0,oe.gn)([(0,E.qC)()],Am.prototype,"name",void 0),(0,oe.gn)([(0,E.XX)()],Am.prototype,"neutralColor",void 0),(0,oe.gn)([(0,E.qC)()],Am.prototype,"isEnabled",void 0),(0,oe.gn)([(0,E.VE)()],Am.prototype,"camera",null),(0,oe.gn)([(0,E.qC)()],Am.prototype,"renderingGroupId",null),(0,oe.gn)([(0,E.qC)()],Am.prototype,"disableBoundingBoxesFromEffectLayer",void 0),n.p.AddParser(Se.l.NAME_EFFECTLAYER,((e,t,i,n)=>{if(e.effectLayers){i.effectLayers||(i.effectLayers=new Array);for(let s=0;s{this.scene.addEffectLayer(e)}))}removeFromContainer(e,t){e.effectLayers&&e.effectLayers.forEach((e=>{this.scene.removeEffectLayer(e),t&&e.dispose()}))}dispose(){const e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){const i=this._engine.currentRenderPassId,n=this.scene.effectLayers;for(const s of n){if(!s.hasMesh(e))continue;const n=s._mainTexture;this._engine.currentRenderPassId=n.renderPassId;for(const r of e.subMeshes)if(!s.isReady(r,t))return this._engine.currentRenderPassId=i,!1}return this._engine.currentRenderPassId=i,!0}_renderMainTexture(e){this._renderEffects=!1,this._needStencil=!1;let t=!1;const i=this.scene.effectLayers;if(i&&i.length>0){this._previousStencilState=this._engine.getStencilBuffer();for(const n of i)if(n.shouldRender()&&(!n.camera||n.camera.cameraRigMode===ce.V.RIG_MODE_NONE&&e===n.camera||n.camera.cameraRigMode!==ce.V.RIG_MODE_NONE&&n.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||n.needStencil();const e=n._mainTexture;e._shouldRender()&&(this.scene.incrementRenderId(),e.render(!1,!1),t=!0)}this.scene.incrementRenderId()}return t}_setStencil(){this._needStencil&&this._engine.setStencilBuffer(!0)}_setStencilBack(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)}_draw(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);const t=this.scene.effectLayers;for(let i=0;i{let t=e._getComponent(Se.l.NAME_EFFECTLAYER);t||(t=new Rm(e),e._addComponent(t))};const Pm="glowMapMergePixelShader",Im="varying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\nuniform float offset;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\n#if LDR\nbaseColor=clamp(baseColor,0.,1.0);\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ht.v.ShadersStore[Pm]=Im;const Mm="glowMapMergeVertexShader",Om="attribute vec2 position;\nvarying vec2 vUV;\nconst 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;\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";Ht.v.ShadersStore[Mm]=Om;n.p.prototype.getGlowLayerByName=function(e){var t;for(let i=0;i<(null===(t=this.effectLayers)||void 0===t?void 0:t.length);i++)if(this.effectLayers[i].name===e&&this.effectLayers[i].getEffectName()===Dm.EffectName)return this.effectLayers[i];return null};class Dm extends Am{set blurKernelSize(e){if(e===this._options.blurKernelSize)return;this._options.blurKernelSize=e;const t=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1.kernel=t,this._verticalBlurPostprocess1.kernel=t,this._horizontalBlurPostprocess2.kernel=t,this._verticalBlurPostprocess2.kernel=t}get blurKernelSize(){return this._options.blurKernelSize}set intensity(e){this._intensity=e}get intensity(){return this._intensity}constructor(e,t,i){super(e,t),this._intensity=1,this._includedOnlyMeshes=[],this._excludedMeshes=[],this._meshesUsingTheirOwnMaterials=[],this.neutralColor=new a.HE(0,0,0,1),this._options=Object.assign({mainTextureRatio:Dm.DefaultTextureRatio,blurKernelSize:32,mainTextureFixedSize:void 0,camera:null,mainTextureSamples:1,renderingGroupId:-1,ldrMerge:!1,alphaBlendingMode:1,mainTextureType:0},i),this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType})}getEffectName(){return Dm.EffectName}_createMergeEffect(){let e="#define EMISSIVE \n";return this._options.ldrMerge&&(e+="#define LDR \n"),this._engine.createEffect("glowMapMerge",[ne.o.PositionKind],["offset"],["textureSampler","textureSampler2"],e)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width,t=this._mainTextureDesiredSize.height;e=this._engine.needPOTTextures?fe.D.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?fe.D.GetExponentOfTwo(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture1=new Ci("GlowLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture1.wrapU=Le.CLAMP_ADDRESSMODE,this._blurTexture1.wrapV=Le.CLAMP_ADDRESSMODE,this._blurTexture1.updateSamplingMode(Le.BILINEAR_SAMPLINGMODE),this._blurTexture1.renderParticles=!1,this._blurTexture1.ignoreCameraViewport=!0;const n=Math.floor(e/2),s=Math.floor(t/2);this._blurTexture2=new Ci("GlowLayerBlurRTT2",{width:n,height:s},this._scene,!1,!0,i),this._blurTexture2.wrapU=Le.CLAMP_ADDRESSMODE,this._blurTexture2.wrapV=Le.CLAMP_ADDRESSMODE,this._blurTexture2.updateSamplingMode(Le.BILINEAR_SAMPLINGMODE),this._blurTexture2.renderParticles=!1,this._blurTexture2.ignoreCameraViewport=!0,this._textures=[this._blurTexture1,this._blurTexture2];const r=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1=new bp("GlowLayerHBP1",new o.FM(1,0),r,{width:e,height:t},null,Le.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess1.width=e,this._horizontalBlurPostprocess1.height=t,this._horizontalBlurPostprocess1.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess1.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._verticalBlurPostprocess1=new bp("GlowLayerVBP1",new o.FM(0,1),r,{width:e,height:t},null,Le.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new bp("GlowLayerHBP2",new o.FM(1,0),r,{width:n,height:s},null,Le.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=n,this._horizontalBlurPostprocess2.height=s,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._blurTexture1)})),this._verticalBlurPostprocess2=new bp("GlowLayerVBP2",new o.FM(0,1),r,{width:n,height:s},null,Le.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1,this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._postProcesses1=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1],this._postProcesses2=[this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._mainTexture.samples=this._options.mainTextureSamples,this._mainTexture.onAfterUnbindObservable.add((()=>{const e=this._blurTexture1.renderTarget;if(e){this._scene.postProcessManager.directRender(this._postProcesses1,e,!0);const t=this._blurTexture2.renderTarget;t&&this._scene.postProcessManager.directRender(this._postProcesses2,t,!0),this._engine.unBindFramebuffer(null!=t?t:e,!0)}})),this._postProcesses.map((e=>{e.autoClear=!1}))}_getEffectiveBlurKernelSize(){return this._options.blurKernelSize/2}isReady(e,t){const i=e.getMaterial(),n=e.getRenderingMesh();if(!i||!n)return!1;const s=i.emissiveTexture;return super._isReady(e,t,s)}needStencil(){return!1}_canRenderMesh(e,t){return!0}_internalRender(e){e.setTexture("textureSampler",this._blurTexture1),e.setTexture("textureSampler2",this._blurTexture2),e.setFloat("offset",this._intensity);const t=this._engine,i=t.getStencilBuffer();t.setStencilBuffer(!1),t.drawElementsType(ut.F.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){var n;let s=1;if(this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(s=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector)this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color);else if(i.emissiveColor){s*=null!==(n=i.emissiveIntensity)&&void 0!==n?n:1,this._emissiveTextureAndColor.color.set(i.emissiveColor.r*s,i.emissiveColor.g*s,i.emissiveColor.b*s,i.alpha)}else this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a)}_shouldRenderMesh(e){return this.hasMesh(e)}_addCustomEffectDefines(e){e.push("#define GLOW")}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}addIncludedOnlyMesh(e){-1===this._includedOnlyMeshes.indexOf(e.uniqueId)&&this._includedOnlyMeshes.push(e.uniqueId)}removeIncludedOnlyMesh(e){const t=this._includedOnlyMeshes.indexOf(e.uniqueId);-1!==t&&this._includedOnlyMeshes.splice(t,1)}hasMesh(e){return!!super.hasMesh(e)&&(this._includedOnlyMeshes.length?-1!==this._includedOnlyMeshes.indexOf(e.uniqueId):!this._excludedMeshes.length||-1===this._excludedMeshes.indexOf(e.uniqueId))}_useMeshMaterial(e){return 0!=this._meshesUsingTheirOwnMaterials.length&&this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId)>-1}referenceMeshToUseItsOwnMaterial(e){e.resetDrawCache(this._mainTexture.renderPassId),this._meshesUsingTheirOwnMaterials.push(e.uniqueId),e.onDisposeObservable.add((()=>{this._disposeMesh(e)}))}unReferenceMeshFromUsingItsOwnMaterial(e){let t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);for(;t>=0;)this._meshesUsingTheirOwnMaterials.splice(t,1),t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);e.resetDrawCache(this._mainTexture.renderPassId)}_disposeMesh(e){this.removeIncludedOnlyMesh(e),this.removeExcludedMesh(e)}getClassName(){return"GlowLayer"}serialize(){const e=E.p4.Serialize(this);let t;if(e.customType="BABYLON.GlowLayer",e.includedMeshes=[],this._includedOnlyMeshes.length)for(t=0;tnew Dm(e.name,t,e.options)),e,t,i);let s;for(s=0;s{e.setFloat2("screenSize",this.width,this.height),e.setVector2("direction",this.direction),e.setFloat("blurWidth",this.kernel)}))}}class Lm extends Am{set blurHorizontalSize(e){this._horizontalBlurPostprocess.kernel=e,this._options.blurHorizontalSize=e}set blurVerticalSize(e){this._verticalBlurPostprocess.kernel=e,this._options.blurVerticalSize=e}get blurHorizontalSize(){return this._horizontalBlurPostprocess.kernel}get blurVerticalSize(){return this._verticalBlurPostprocess.kernel}constructor(e,t,i){super(e,t),this.name=e,this.innerGlow=!0,this.outerGlow=!0,this.onBeforeBlurObservable=new r.y$,this.onAfterBlurObservable=new r.y$,this._instanceGlowingMeshStencilReference=Lm.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=Lm.NeutralColor,this._engine.isStencilEnable||p.Y.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),this._options=Object.assign({mainTextureRatio:.5,blurTextureSizeRatio:.5,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0},i),this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType}),this._shouldRender=!1}getEffectName(){return Lm.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[ne.o.PositionKind],["offset"],["textureSampler"],this._options.isStroke?"#define STROKE \n":void 0)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,t=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;e=this._engine.needPOTTextures?fe.D.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?fe.D.GetExponentOfTwo(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture=new Ci("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=Le.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=Le.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(Le.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],2===this._options.alphaBlendingMode?(this._downSamplePostprocess=new Jn("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,Le.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._horizontalBlurPostprocess=new wm("HighlightLayerHBP",new o.FM(1,0),this._options.blurHorizontalSize,1,null,Le.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add((i=>{i.setFloat2("screenSize",e,t)})),this._verticalBlurPostprocess=new wm("HighlightLayerVBP",new o.FM(0,1),this._options.blurVerticalSize,1,null,Le.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add((i=>{i.setFloat2("screenSize",e,t)})),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new bp("HighlightLayerHBP",new o.FM(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,Le.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess.width=e,this._horizontalBlurPostprocess.height=t,this._horizontalBlurPostprocess.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._verticalBlurPostprocess=new bp("HighlightLayerVBP",new o.FM(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,Le.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add((()=>{this.onBeforeBlurObservable.notifyObservers(this);const e=this._blurTexture.renderTarget;e&&(this._scene.postProcessManager.directRender(this._postProcesses,e,!0),this._engine.unBindFramebuffer(e,!0)),this.onAfterBlurObservable.notifyObservers(this)})),this._postProcesses.map((e=>{e.autoClear=!1}))}needStencil(){return!0}isReady(e,t){const i=e.getMaterial(),n=e.getRenderingMesh();if(!i||!n||!this._meshes)return!1;let s=null;const r=this._meshes[n.uniqueId];return r&&r.glowEmissiveOnly&&i&&(s=i.emissiveTexture),super._isReady(e,t,s)}_internalRender(e,t){e.setTexture("textureSampler",this._blurTexture);const i=this._engine;i.cacheStencilState(),i.setStencilOperationPass(7681),i.setStencilOperationFail(7680),i.setStencilOperationDepthFail(7680),i.setStencilMask(0),i.setStencilBuffer(!0),i.setStencilFunctionReference(this._instanceGlowingMeshStencilReference),this.outerGlow&&0===t&&(e.setFloat("offset",0),i.setStencilFunction(517),i.drawElementsType(ut.F.TriangleFillMode,0,6)),this.innerGlow&&1===t&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(ut.F.TriangleFillMode,0,6)),i.restoreStencilState()}shouldRender(){return!!super.shouldRender()&&!!this._meshes}_shouldRenderMesh(e){return(!this._excludedMeshes||!this._excludedMeshes[e.uniqueId])&&!!super.hasMesh(e)}_canRenderMesh(e,t){return!0}_addCustomEffectDefines(e){e.push("#define HIGHLIGHT")}_setEmissiveTextureAndColor(e,t,i){const n=this._meshes[e.uniqueId];n?this._emissiveTextureAndColor.color.set(n.color.r,n.color.g,n.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),n&&n.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null}addExcludedMesh(e){if(!this._excludedMeshes)return;if(!this._excludedMeshes[e.uniqueId]){const t={mesh:e,beforeBind:null,afterRender:null,stencilState:!1};t.beforeBind=e.onBeforeBindObservable.add((e=>{t.stencilState=e.getEngine().getStencilBuffer(),e.getEngine().setStencilBuffer(!1)})),t.afterRender=e.onAfterRenderObservable.add((e=>{e.getEngine().setStencilBuffer(t.stencilState)})),this._excludedMeshes[e.uniqueId]=t}}removeExcludedMesh(e){if(!this._excludedMeshes)return;const t=this._excludedMeshes[e.uniqueId];t&&(t.beforeBind&&e.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&e.onAfterRenderObservable.remove(t.afterRender)),this._excludedMeshes[e.uniqueId]=null}hasMesh(e){return!!this._meshes&&(!!super.hasMesh(e)&&(void 0!==this._meshes[e.uniqueId]&&null!==this._meshes[e.uniqueId]))}addMesh(e,t,i=!1){if(!this._meshes)return;const n=this._meshes[e.uniqueId];n?n.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add((e=>{this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]?this._defaultStencilReference(e):e.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference))})),observerDefault:e.onAfterRenderObservable.add((e=>{this.isEnabled&&this._defaultStencilReference(e)})),glowEmissiveOnly:i},e.onDisposeObservable.add((()=>{this._disposeMesh(e)}))),this._shouldRender=!0}removeMesh(e){if(!this._meshes)return;const t=this._meshes[e.uniqueId];t&&(t.observerHighlight&&e.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&e.onAfterRenderObservable.remove(t.observerDefault),delete this._meshes[e.uniqueId]),this._shouldRender=!1;for(const i in this._meshes)if(this._meshes[i]){this._shouldRender=!0;break}}removeAllMeshes(){if(this._meshes)for(const e in this._meshes)if(Object.prototype.hasOwnProperty.call(this._meshes,e)){const t=this._meshes[e];t&&this.removeMesh(t.mesh)}}_defaultStencilReference(e){e.getScene().getEngine().setStencilFunctionReference(Lm.NormalMeshStencilReference)}_disposeMesh(e){this.removeMesh(e),this.removeExcludedMesh(e)}dispose(){if(this._meshes){for(const e in this._meshes){const t=this._meshes[e];t&&t.mesh&&(t.observerHighlight&&t.mesh.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&t.mesh.onAfterRenderObservable.remove(t.observerDefault))}this._meshes=null}if(this._excludedMeshes){for(const e in this._excludedMeshes){const t=this._excludedMeshes[e];t&&(t.beforeBind&&t.mesh.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&t.mesh.onAfterRenderObservable.remove(t.afterRender))}this._excludedMeshes=null}super.dispose()}getClassName(){return"HighlightLayer"}serialize(){const e=E.p4.Serialize(this);if(e.customType="BABYLON.HighlightLayer",e.meshes=[],this._meshes)for(const t in this._meshes){const i=this._meshes[t];i&&e.meshes.push({glowEmissiveOnly:i.glowEmissiveOnly,color:i.color.asArray(),meshId:i.mesh.id})}if(e.excludedMeshes=[],this._excludedMeshes)for(const t in this._excludedMeshes){const i=this._excludedMeshes[t];i&&e.excludedMeshes.push(i.mesh.id)}return e}static Parse(e,t,i){const n=E.p4.Parse((()=>new Lm(e.name,t,e.options)),e,t,i);let s;for(s=0;si.activeCamera&&e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&0!=(e.layerMask&i.activeCamera.layerMask);const n=i.getEngine(),s=[];s.push(1,1),s.push(-1,1),s.push(-1,-1),s.push(1,-1),this._vertexBuffers[ne.o.PositionKind]=new ne.o(n,s,ne.o.PositionKind,!1,!1,2),this._createIndexBuffer()}_createIndexBuffer(){const e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled=e}getScene(){return this._scene}getEmitter(){return this._emitter}setEmitter(e){this._emitter=e}getEmitterPosition(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position}computeEffectivePosition(e){let t=this.getEmitterPosition();t=o.P.Project(t,o.y3.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=o.P.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(e.x-=this.viewportBorder,e.y-=this.viewportBorder,e.width+=2*this.viewportBorder,e.height+=2*this.viewportBorder,t.x+=this.viewportBorder,t.y+=this.viewportBorder,this._positionX+=this.viewportBorder,this._positionY+=this.viewportBorder);const i=this._scene.useRightHandedSystem;return!!(t.z>0&&!i||t.z<0&&i)&&(this._positionX>e.x&&this._positionXe.y&&(this._positionY,e.y,e.height),!0)}_isVisible(){if(!this._isEnabled||!this._scene.activeCamera)return!1;const e=this.getEmitterPosition().subtract(this._scene.activeCamera.globalPosition),t=e.length();e.normalize();const i=new qe(this._scene.activeCamera.globalPosition,e),n=this._scene.pickWithRay(i,this.meshesSelectionPredicate,!0);return!n||!n.hit||n.distance>t}render(){if(!this._scene.activeCamera)return!1;const e=this._scene.getEngine(),t=this._scene.activeCamera.viewport.toGlobal(e.getRenderWidth(!0),e.getRenderHeight(!0));if(!this.computeEffectivePosition(t))return!1;if(!this._isVisible())return!1;let i,n;i=this._positionXt.x+t.width-this.borderLimit?this._positionX-t.x-t.width+this.borderLimit:0,n=this._positionYt.y+t.height-this.borderLimit?this._positionY-t.y-t.height+this.borderLimit:0;let s=i>n?i:n;s-=this.viewportBorder,s>this.borderLimit&&(s=this.borderLimit);let r=1-S.R.Clamp(s/this.borderLimit,0,1);if(r<0)return!1;r>1&&(r=1),this.viewportBorder>0&&(t.x+=this.viewportBorder,t.y+=this.viewportBorder,t.width-=2*this.viewportBorder,t.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);const a=t.x+t.width/2,l=t.y+t.height/2,h=a-this._positionX,c=l-this._positionY;e.setState(!1),e.setDepthBuffer(!1);for(let d=0;d{throw(0,ge.S)("LensFlareSystemSceneComponent")},n.p.AddParser(Se.l.NAME_LENSFLARESYSTEM,((e,t,i,n)=>{if(void 0!==e.lensFlareSystems&&null!==e.lensFlareSystems){i.lensFlareSystems||(i.lensFlareSystems=new Array);for(let s=0,r=e.lensFlareSystems.length;s{this.scene.addLensFlareSystem(e)}))}removeFromContainer(e,t){e.lensFlareSystems&&e.lensFlareSystems.forEach((e=>{this.scene.removeLensFlareSystem(e),t&&e.dispose()}))}serialize(e){e.lensFlareSystems=[];const t=this.scene.lensFlareSystems;for(const i of t)e.lensFlareSystems.push(i.serialize())}dispose(){const e=this.scene.lensFlareSystems;for(;e.length;)e[0].dispose()}_draw(e){if(this.scene.lensFlaresEnabled){const t=this.scene.lensFlareSystems;se.w1.StartPerformanceCounter("Lens flares",t.length>0);for(const i of t)0!=(e.layerMask&i.layerMask)&&i.render();se.w1.EndPerformanceCounter("Lens flares",t.length>0)}}}Ym._SceneComponentInitialization=e=>{let t=e._getComponent(Se.l.NAME_LENSFLARESYSTEM);t||(t=new jm(e),e._addComponent(t))};const Km="bayerDitherFunctions",qm="float bayerDither2(vec2 _P) {\nreturn mod(2.0*_P.y+_P.x+1.0,4.0);\n}\nfloat bayerDither4(vec2 _P) {\nvec2 P1=mod(_P,2.0); \nvec2 P2=floor(0.5*mod(_P,4.0)); \nreturn 4.0*bayerDither2(P1)+bayerDither2(P2);\n}\nfloat bayerDither8(vec2 _P) {\nvec2 P1=mod(_P,2.0); \nvec2 P2=floor(0.5 *mod(_P,4.0)); \nvec2 P4=floor(0.25*mod(_P,8.0)); \nreturn 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);\n}\n";Ht.v.IncludesShadersStore[Km]=qm;const $m="shadowMapFragmentExtraDeclaration",Qm="#if SM_FLOAT==0\n#include\n#endif\n#if SM_SOFTTRANSPARENTSHADOW==1\n#include\nuniform float softTransparentShadowSM;\n#endif\nvarying float vDepthMetricSM;\n#if SM_USEDISTANCE==1\nuniform vec3 lightDataSM;\nvarying vec3 vPositionWSM;\n#endif\nuniform vec3 biasAndScaleSM;\nuniform vec2 depthValuesSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\n#endif\n";Ht.v.IncludesShadersStore[$m]=Qm;const Zm="shadowMapFragment",Jm="float depthSM=vDepthMetricSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\n#if SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\ndepthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\ndepthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_FragDepth=clamp(1.0-depthSM,0.0,1.0);\n#else\ngl_FragDepth=clamp(depthSM,0.0,1.0); \n#endif\n#elif SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#if SM_ESM==1\ndepthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.);\n#endif\n#if SM_FLOAT==1\ngl_FragColor=vec4(depthSM,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depthSM);\n#endif\nreturn;";Ht.v.IncludesShadersStore[Zm]=Jm;const eg="shadowMapPixelShader",tg="#include\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\n#ifdef ALPHATEXTURE\nfloat alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a;\n#ifdef ALPHATESTVALUE\nif (alphaFromAlphaTexture=softTransparentShadowSM*alphaFromAlphaTexture) discard;\n#else\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM) discard;\n#endif\n#endif\n#include\n}";Ht.v.ShadersStore[eg]=tg;const ig="sceneVertexDeclaration",ng="uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec4 vEyePosition;\n";Ht.v.IncludesShadersStore[ig]=ng;const sg="meshVertexDeclaration",rg="uniform mat4 world;\nuniform float visibility;\n";Ht.v.IncludesShadersStore[sg]=rg;const og="shadowMapVertexDeclaration",ag="#include\n#include\n";Ht.v.IncludesShadersStore[og]=ag;const lg="shadowMapUboDeclaration",hg="layout(std140,column_major) uniform;\n#include\n#include\n";Ht.v.IncludesShadersStore[lg]=hg;const cg="shadowMapVertexExtraDeclaration",dg="#if SM_NORMALBIAS==1\nuniform vec3 lightDataSM;\n#endif\nuniform vec3 biasAndScaleSM;\nuniform vec2 depthValuesSM;\nvarying float vDepthMetricSM;\n#if SM_USEDISTANCE==1\nvarying vec3 vPositionWSM;\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\n#endif\n";Ht.v.IncludesShadersStore[cg]=dg;const ug="shadowMapVertexNormalBias",pg="#if SM_NORMALBIAS==1\n#if SM_DIRECTIONINLIGHTDATA==1\nvec3 worldLightDirSM=normalize(-lightDataSM.xyz);\n#else\nvec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;\nvec3 worldLightDirSM=normalize(directionToLightSM);\n#endif\nfloat ndlSM=dot(vNormalW,worldLightDirSM);\nfloat sinNLSM=sqrt(1.0-ndlSM*ndlSM);\nfloat normalBiasSM=biasAndScaleSM.y*sinNLSM;\nworldPos.xyz-=vNormalW*normalBiasSM;\n#endif\n";Ht.v.IncludesShadersStore[ug]=pg;const fg="shadowMapVertexMetric",_g="#if SM_USEDISTANCE==1\nvPositionWSM=worldPos.xyz;\n#endif\n#if SM_DEPTHTEXTURE==1\n#ifdef IS_NDC_HALF_ZRANGE\n#define BIASFACTOR 0.5\n#else\n#define BIASFACTOR 1.0\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\n#else\ngl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\n#endif\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nzSM=gl_Position.z;\ngl_Position.z=0.0;\n#elif SM_USEDISTANCE==0\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\nvDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#endif\n";Ht.v.IncludesShadersStore[fg]=_g;const mg="shadowMapVertexShader",gg="attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#endif\n#include\n#include<__decl__shadowMapVertex>\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef NORMAL\nmat3 normWorldSM=mat3(finalWorld);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));\nvNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvec3 vNormalW=normalize(normWorldSM*normalUpdated);\n#endif\n#endif\n#include\ngl_Position=viewProjection*worldPos;\n#include\n#ifdef ALPHATEXTURE\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n}";Ht.v.ShadersStore[mg]=gg;const vg="depthBoxBlurPixelShader",Tg="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}";Ht.v.ShadersStore[vg]=Tg;const Sg="shadowMapFragmentSoftTransparentShadow",Eg="#if SM_SOFTTRANSPARENTSHADOW==1\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard;\n#endif\n";Ht.v.IncludesShadersStore[Sg]=Eg;class xg{get bias(){return this._bias}set bias(e){this._bias=e}get normalBias(){return this._normalBias}set normalBias(e){this._normalBias=e}get blurBoxOffset(){return this._blurBoxOffset}set blurBoxOffset(e){this._blurBoxOffset!==e&&(this._blurBoxOffset=e,this._disposeBlurPostProcesses())}get blurScale(){return this._blurScale}set blurScale(e){this._blurScale!==e&&(this._blurScale=e,this._disposeBlurPostProcesses())}get blurKernel(){return this._blurKernel}set blurKernel(e){this._blurKernel!==e&&(this._blurKernel=e,this._disposeBlurPostProcesses())}get useKernelBlur(){return this._useKernelBlur}set useKernelBlur(e){this._useKernelBlur!==e&&(this._useKernelBlur=e,this._disposeBlurPostProcesses())}get depthScale(){return void 0!==this._depthScale?this._depthScale:this._light.getDepthScale()}set depthScale(e){this._depthScale=e}_validateFilter(e){return e}get filter(){return this._filter}set filter(e){if(e=this._validateFilter(e),this._light.needCube()){if(e===xg.FILTER_BLUREXPONENTIALSHADOWMAP)return void(this.useExponentialShadowMap=!0);if(e===xg.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)return void(this.useCloseExponentialShadowMap=!0);if(e===xg.FILTER_PCF||e===xg.FILTER_PCSS)return void(this.usePoissonSampling=!0)}e!==xg.FILTER_PCF&&e!==xg.FILTER_PCSS||this._scene.getEngine()._features.supportShadowSamplers?this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty()):this.usePoissonSampling=!0}get usePoissonSampling(){return this.filter===xg.FILTER_POISSONSAMPLING}set usePoissonSampling(e){const t=this._validateFilter(xg.FILTER_POISSONSAMPLING);(e||this.filter===xg.FILTER_POISSONSAMPLING)&&(this.filter=e?t:xg.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===xg.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){const t=this._validateFilter(xg.FILTER_EXPONENTIALSHADOWMAP);(e||this.filter===xg.FILTER_EXPONENTIALSHADOWMAP)&&(this.filter=e?t:xg.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===xg.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){const t=this._validateFilter(xg.FILTER_BLUREXPONENTIALSHADOWMAP);(e||this.filter===xg.FILTER_BLUREXPONENTIALSHADOWMAP)&&(this.filter=e?t:xg.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===xg.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){const t=this._validateFilter(xg.FILTER_CLOSEEXPONENTIALSHADOWMAP);(e||this.filter===xg.FILTER_CLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:xg.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===xg.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){const t=this._validateFilter(xg.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);(e||this.filter===xg.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:xg.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===xg.FILTER_PCF}set usePercentageCloserFiltering(e){const t=this._validateFilter(xg.FILTER_PCF);(e||this.filter===xg.FILTER_PCF)&&(this.filter=e?t:xg.FILTER_NONE)}get filteringQuality(){return this._filteringQuality}set filteringQuality(e){this._filteringQuality!==e&&(this._filteringQuality=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get useContactHardeningShadow(){return this.filter===xg.FILTER_PCSS}set useContactHardeningShadow(e){const t=this._validateFilter(xg.FILTER_PCSS);(e||this.filter===xg.FILTER_PCSS)&&(this.filter=e?t:xg.FILTER_NONE)}get contactHardeningLightSizeUVRatio(){return this._contactHardeningLightSizeUVRatio}set contactHardeningLightSizeUVRatio(e){this._contactHardeningLightSizeUVRatio=e}get darkness(){return this._darkness}set darkness(e){this.setDarkness(e)}getDarkness(){return this._darkness}setDarkness(e){return this._darkness=e>=1?1:e<=0?0:e,this}get transparencyShadow(){return this._transparencyShadow}set transparencyShadow(e){this.setTransparencyShadow(e)}setTransparencyShadow(e){return this._transparencyShadow=e,this}getShadowMap(){return this._shadowMap}getShadowMapForRendering(){return this._shadowMap2?this._shadowMap2:this._shadowMap}getClassName(){return xg.CLASSNAME}addShadowCaster(e,t=!0){if(!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),-1===this._shadowMap.renderList.indexOf(e)&&this._shadowMap.renderList.push(e),t)for(const i of e.getChildMeshes())-1===this._shadowMap.renderList.indexOf(i)&&this._shadowMap.renderList.push(i);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;const i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(const n of e.getChildren())this.removeShadowCaster(n);return this}getLight(){return this._light}_getCamera(){var e;return null!==(e=this._camera)&&void 0!==e?e:this._scene.activeCamera}get mapSize(){return this._mapSize}set mapSize(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}constructor(e,t,i,n){this.onBeforeShadowMapRenderObservable=new r.y$,this.onAfterShadowMapRenderObservable=new r.y$,this.onBeforeShadowMapRenderMeshObservable=new r.y$,this.onAfterShadowMapRenderMeshObservable=new r.y$,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=xg.FILTER_NONE,this._filteringQuality=xg.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.useOpacityTextureForTransparentShadow=!1,this.frustumEdgeFalloff=0,this.forceBackFacesOnly=!1,this._lightDirection=o.P.Zero(),this._viewMatrix=o.y3.Zero(),this._projectionMatrix=o.y3.Zero(),this._transformMatrix=o.y3.Zero(),this._cachedPosition=new o.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new o.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=o.y3.Identity(),this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=null!=n?n:null;let s=t._shadowGenerators;s||(s=t._shadowGenerators=new Map),s.set(this._camera,this),this.id=t.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[],this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`))),xg._SceneComponentInitialization(this._scene);const a=this._scene.getEngine().getCaps();i?a.textureFloatRender&&a.textureFloatLinearFiltering?this._textureType=1:a.textureHalfFloatRender&&a.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:a.textureHalfFloatRender&&a.textureHalfFloatLinearFiltering?this._textureType=2:a.textureFloatRender&&a.textureFloatLinearFiltering?this._textureType=1:this._textureType=0,this._initializeGenerator(),this._applyFilterValues()}_initializeGenerator(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()}_createTargetRenderTexture(){const e=this._scene.getEngine();e._features.supportDepthStencilTexture?(this._shadowMap=new Ci(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0)):this._shadowMap=new Ci(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(this._createTargetRenderTexture(),null===this._shadowMap)return;this._shadowMap.wrapU=Le.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=Le.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(Le.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=this._renderForShadowMap.bind(this),this._shadowMap.customIsReadyFunction=()=>!0;const e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add((()=>{var t;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),null===(t=e._debugPushGroup)||void 0===t||t.call(e,`shadow map generation for pass id ${e.currentRenderPassId}`,1)})),this._shadowMap.onBeforeRenderObservable.add((t=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=t,this._filter===xg.FILTER_PCF&&e.setColorWrite(!1),this.getTransformMatrix(),this._scene.setTransformMatrix(this._viewMatrix,this._projectionMatrix),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._shadowMap.onAfterUnbindObservable.add((()=>{var t,i;if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._scene.updateTransformMatrix(),this._filter===xg.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap)return void(null===(t=e._debugPopGroup)||void 0===t||t.call(e,1));const n=this.getShadowMapForRendering();n&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,n.renderTarget,!0),e.unBindFramebuffer(n.renderTarget,!0),null===(i=e._debugPopGroup)||void 0===i||i.call(e,1))}));const t=new a.HE(0,0,0,0),i=new a.HE(1,1,1,1);this._shadowMap.onClearObservable.add((e=>{this._filter===xg.FILTER_PCF?e.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e.clear(t,!0,!0,!1):e.clear(i,!0,!0,!1)})),this._shadowMap.onResizeObservable.add((e=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=e.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}));for(let n=mi.$.MIN_RENDERINGGROUPS;n{e.setTexture("textureSampler",this._shadowMap)})),this._kernelBlurYPostprocess=new bp(this._light.name+"KernelBlurY",new o.FM(0,1),this.blurKernel,1,null,Le.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,0===this._textureType&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new Zt(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,Le.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add((e=>{e.setFloat2("screenSize",t,t),e.setTexture("textureSampler",this._shadowMap)})),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])}_renderForShadowMap(e,t,i,n){let s;if(n.length)for(s=0;s{r===s||e?(r.getMeshUniformBuffer().bindToEffect(c,"Mesh"),r.transferToEffect(e?t:f)):(s.getMeshUniformBuffer().bindToEffect(c,"Mesh"),s.transferToEffect(t))})),this.forceBackFacesOnly&&a.setState(!0,0,!1,!1,l.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(c),this.onAfterShadowMapRenderMeshObservable.notifyObservers(s)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}_applyFilterValues(){this._shadowMap&&(this.filter===xg.FILTER_NONE||this.filter===xg.FILTER_PCSS?this._shadowMap.updateSamplingMode(Le.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(Le.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){const i=Object.assign({useInstances:!1},t),n=this.getShadowMap();if(!n)return void(e&&e(this));const s=n.renderList;if(!s)return void(e&&e(this));const r=new Array;for(const l of s)r.push(...l.subMeshes);if(0===r.length)return void(e&&e(this));let o=0;const a=()=>{var t,n;if(this._scene&&this._scene.getEngine()){for(;this.isReady(r[o],i.useInstances,null!==(n=null===(t=r[o].getMaterial())||void 0===t?void 0:t.needAlphaBlendingForMesh(r[o].getMesh()))&&void 0!==n&&n);)if(o++,o>=r.length)return void(e&&e(this));setTimeout(a,16)}};a()}forceCompilationAsync(e){return new Promise((t=>{this.forceCompilation((()=>{t()}),e)}))}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,n){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(0!==this._textureType?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));const s=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&s.isVerticesDataPresent(ne.o.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===he.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&n?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){var n;const s=e.getMaterial(),r=null==s?void 0:s.shadowDepthWrapper;if(this._opacityTexture=null,!s)return!1;const o=[];if(this._prepareShadowDefines(e,t,o,i),r){if(!r.isReadyForSubMesh(e,o,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{const i=e._getDrawWrapper(void 0,!0);let r=i.effect,a=i.defines;const l=[ne.o.PositionKind],h=e.getMesh();this.normalBias&&h.isVerticesDataPresent(ne.o.NormalKind)&&(l.push(ne.o.NormalKind),o.push("#define NORMAL"),h.nonUniformScaling&&o.push("#define NONUNIFORMSCALING"));const c=s.needAlphaTesting();if((c||s.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=s.opacityTexture:this._opacityTexture=s.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;const e=null!==(n=s.alphaCutOff)&&void 0!==n?n:xg.DEFAULT_ALPHA_CUTOFF;o.push("#define ALPHATEXTURE"),c&&o.push(`#define ALPHATESTVALUE ${e}${e%1==0?".":""}`),h.isVerticesDataPresent(ne.o.UVKind)&&(l.push(ne.o.UVKind),o.push("#define UV1")),h.isVerticesDataPresent(ne.o.UV2Kind)&&1===this._opacityTexture.coordinatesIndex&&(l.push(ne.o.UV2Kind),o.push("#define UV2"))}const d=new zt;if(h.useBones&&h.computeBonesUsingShaders&&h.skeleton){l.push(ne.o.MatricesIndicesKind),l.push(ne.o.MatricesWeightsKind),h.numBoneInfluencers>4&&(l.push(ne.o.MatricesIndicesExtraKind),l.push(ne.o.MatricesWeightsExtraKind));const e=h.skeleton;o.push("#define NUM_BONE_INFLUENCERS "+h.numBoneInfluencers),h.numBoneInfluencers>0&&d.addCPUSkinningFallback(0,h),e.isUsingTextureForMatrices?o.push("#define BONETEXTURE"):o.push("#define BonesPerMesh "+(e.bones.length+1))}else o.push("#define NUM_BONE_INFLUENCERS 0");const u=h.morphTargetManager;let p=0;if(u&&u.numInfluencers>0&&(o.push("#define MORPHTARGETS"),p=u.numInfluencers,o.push("#define NUM_MORPH_INFLUENCERS "+p),u.isUsingTextureForTargets&&o.push("#define MORPHTARGETS_TEXTURE"),It.G.PrepareAttributesForMorphTargetsInfluencers(l,h,p)),(0,ua.lK)(s,this._scene,o),t&&(o.push("#define INSTANCES"),It.G.PushAttributesForInstances(l),e.getRenderingMesh().hasThinInstances&&o.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(const e of this.customShaderOptions.defines)-1===o.indexOf(e)&&o.push(e);const f=o.join("\n");if(a!==f){a=f;let e="shadowMap";const t=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices"],n=["diffuseSampler","boneSampler","morphTargets"],s=["Scene","Mesh"];if((0,ua.qx)(t),this.customShaderOptions){if(e=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(const e of this.customShaderOptions.attributes)-1===l.indexOf(e)&&l.push(e);if(this.customShaderOptions.uniforms)for(const e of this.customShaderOptions.uniforms)-1===t.indexOf(e)&&t.push(e);if(this.customShaderOptions.samplers)for(const e of this.customShaderOptions.samplers)-1===n.indexOf(e)&&n.push(e)}const o=this._scene.getEngine();r=o.createEffect(e,{attributes:l,uniformsNames:t,uniformBuffersNames:s,samplers:n,defines:f,fallbacks:d,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:p}},o),i.setEffect(r,a)}if(!r.isReady())return!1}return(this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(this._blurPostProcesses&&this._blurPostProcesses.length||this._initializeBlurRTTAndPostProcesses()),!(this._kernelBlurXPostprocess&&!this._kernelBlurXPostprocess.isReady())&&(!(this._kernelBlurYPostprocess&&!this._kernelBlurYPostprocess.isReady())&&!(this._boxBlurPostprocess&&!this._boxBlurPostprocess.isReady()))}prepareDefines(e,t){const i=this._scene,n=this._light;i.shadowsEnabled&&n.shadowEnabled&&(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===xg.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===xg.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===xg.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===xg.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),n.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const n=this._getCamera();if(!n)return;const s=this.getShadowMap();s&&(i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix()),this._filter===xg.FILTER_PCF?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),s.getSize().width,1/s.getSize().width,this.frustumEdgeFalloff,e)):this._filter===xg.FILTER_PCSS?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),t.setTexture("depthSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/s.getSize().width,this._contactHardeningLightSizeUVRatio*s.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/s.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(n),this.getLight().getDepthMinZ(n)+this.getLight().getDepthMaxZ(n),e))}getTransformMatrix(){const e=this._scene;if(this._currentRenderId===e.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderId=e.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;let t=this._light.position;if(this._light.computeTransformedInformation()&&(t=this._light.transformedPosition),o.P.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(o.P.Dot(this._lightDirection,o.P.Up()))&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!t.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(t),this._cachedDirection.copyFrom(this._lightDirection),o.y3.LookAtLHToRef(t,t.add(this._lightDirection),o.P.Up(),this._viewMatrix);const e=this.getShadowMap();if(e){const t=e.renderList;t&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,t)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix}recreateShadowMap(){const e=this._shadowMap;if(!e)return;const t=e.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this._filter,this._applyFilterValues(),t){this._shadowMap.renderList||(this._shadowMap.renderList=[]);for(const e of t)this._shadowMap.renderList.push(e)}else this._shadowMap.renderList=null}_disposeBlurPostProcesses(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]}_disposeRTTandPostProcesses(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()}_disposeSceneUBOs(){if(this._sceneUBOs){for(const e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}dispose(){if(this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light){if(this._light._shadowGenerators){const e=this._light._shadowGenerators.entries();for(let t=e.next();!0!==t.done;t=e.next()){const[e,i]=t.value;i===this&&this._light._shadowGenerators.delete(e)}0===this._light._shadowGenerators.size&&(this._light._shadowGenerators=null)}this._light._markMeshesAsLightDirty()}this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear()}serialize(){var e;const t={},i=this.getShadowMap();if(!i)return t;if(t.className=this.getClassName(),t.lightId=this._light.id,t.cameraId=null===(e=this._camera)||void 0===e?void 0:e.id,t.id=this.id,t.mapSize=i.getRenderSize(),t.forceBackFacesOnly=this.forceBackFacesOnly,t.darkness=this.getDarkness(),t.transparencyShadow=this._transparencyShadow,t.frustumEdgeFalloff=this.frustumEdgeFalloff,t.bias=this.bias,t.normalBias=this.normalBias,t.usePercentageCloserFiltering=this.usePercentageCloserFiltering,t.useContactHardeningShadow=this.useContactHardeningShadow,t.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,t.filteringQuality=this.filteringQuality,t.useExponentialShadowMap=this.useExponentialShadowMap,t.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,t.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,t.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,t.usePoissonSampling=this.usePoissonSampling,t.depthScale=this.depthScale,t.blurBoxOffset=this.blurBoxOffset,t.blurKernel=this.blurKernel,t.blurScale=this.blurScale,t.useKernelBlur=this.useKernelBlur,t.renderList=[],i.renderList)for(let n=0;n{throw(0,ge.S)("ShadowGeneratorSceneComponent")};const bg="depthPixelShader",Cg="#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include\nvarying float vDepthMetric;\n#ifdef PACKED\n#include\n#endif\n#ifdef STORE_CAMERASPACE_Z\nvarying vec4 vViewPos;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef STORE_CAMERASPACE_Z\n#ifdef PACKED\ngl_FragColor=pack(vViewPos.z);\n#else\ngl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0);\n#endif\n#else\n#ifdef NONLINEARDEPTH\n#ifdef PACKED\ngl_FragColor=pack(gl_FragCoord.z);\n#else\ngl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0);\n#endif\n#else\n#ifdef PACKED\ngl_FragColor=pack(vDepthMetric);\n#else\ngl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0);\n#endif\n#endif\n#endif\n}";Ht.v.ShadersStore[bg]=Cg;const yg="depthVertexShader",Ag="attribute vec3 position;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef STORE_CAMERASPACE_Z\nuniform mat4 view;\nvarying vec4 vViewPos;\n#endif\nvarying float vDepthMetric;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#include\ngl_Position=viewProjection*worldPos;\n#ifdef STORE_CAMERASPACE_Z\nvViewPos=view*worldPos;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y));\n#else\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#endif\n#endif\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n";Ht.v.ShadersStore[yg]=Ag;class Rg{setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,n=!1,s=Le.TRILINEAR_SAMPLINGMODE,r=!1,o){this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._scene=e,this._storeNonLinearDepth=n,this._storeCameraSpaceZ=r,this.isPacked=0===t,this.isPacked?this.clearColor=new a.HE(1,1,1,1):this.clearColor=new a.HE(r?1e8:1,0,0,1),Rg._SceneComponentInitialization(this._scene);const l=e.getEngine();this._camera=i,s!==Le.NEAREST_SAMPLINGMODE&&(1!==t||l._caps.textureFloatLinearFiltering||(s=Le.NEAREST_SAMPLINGMODE),2!==t||l._caps.textureHalfFloatLinearFiltering||(s=Le.NEAREST_SAMPLINGMODE));const h=this.isPacked||!l._features.supportExtendedTextureFormats?5:6;this._depthMap=new Ci(null!=o?o:"DepthRenderer",{width:l.getRenderWidth(),height:l.getRenderHeight()},this._scene,!1,!0,t,!1,s,void 0,void 0,void 0,h),this._depthMap.wrapU=Le.CLAMP_ADDRESSMODE,this._depthMap.wrapV=Le.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.noPrePassRenderer=!0,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add((e=>{e.clear(this.clearColor,!0,!0,!0)})),this._depthMap.onBeforeBindObservable.add((()=>{var e;null===(e=l._debugPushGroup)||void 0===e||e.call(l,"depth renderer",1)})),this._depthMap.onAfterUnbindObservable.add((()=>{var e;null===(e=l._debugPopGroup)||void 0===e||e.call(l,1)})),this._depthMap.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let n=0;n{var t,i;const n=e.getRenderingMesh(),s=e.getEffectiveMesh(),r=this._scene,o=r.getEngine(),a=e.getMaterial();if(s._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!a||s.infiniteDistance||a.disableDepthWrite||0===e.verticesCount||e._renderId===r.getRenderId())return;const l=s._getWorldMatrixDeterminant()<0;let h=null!==(t=n.overrideMaterialSideOrientation)&&void 0!==t?t:a.sideOrientation;l&&(h=0===h?1:0);const c=0===h;o.setState(a.backFaceCulling,0,!1,c,this.reverseCulling?!a.cullBackFaces:a.cullBackFaces);const d=n._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(d.mustReturn)return;const u=o.getCaps().instancedArrays&&(null!==d.visibleInstances[e._id]&&void 0!==d.visibleInstances[e._id]||n.hasThinInstances),p=this._camera||r.activeCamera;if(this.isReady(e,u)&&p){e._renderId=r.getRenderId();const t=null===(i=s._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[o.currentRenderPassId];let l=e._getDrawWrapper();!l&&t&&(l=t._getDrawWrapper());const h=p.mode===ce.V.ORTHOGRAPHIC_CAMERA;if(!l)return;const c=l.effect;let f,_;if(o.enableEffect(l),u||n._bind(e,c,a.fillMode),t?t.bindForSubMesh(s.getWorldMatrix(),s,e):(c.setMatrix("viewProjection",r.getTransformMatrix()),c.setMatrix("world",s.getWorldMatrix()),this._storeCameraSpaceZ&&c.setMatrix("view",r.getViewMatrix())),h?(f=!o.useReverseDepthBuffer&&o.isNDCHalfZRange?0:1,_=o.useReverseDepthBuffer&&o.isNDCHalfZRange?0:1):(f=o.useReverseDepthBuffer&&o.isNDCHalfZRange?p.minZ:o.isNDCHalfZRange?0:p.minZ,_=o.useReverseDepthBuffer&&o.isNDCHalfZRange?0:p.maxZ),c.setFloat2("depthValues",f,f+_),!t){if(a.needAlphaTesting()){const e=a.getAlphaTestTexture();e&&(c.setTexture("diffuseSampler",e),c.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(n.useBones&&n.computeBonesUsingShaders&&n.skeleton){const e=n.skeleton;if(e.isUsingTextureForMatrices){const t=e.getTransformMatrixTexture(n);if(!t)return;c.setTexture("boneSampler",t),c.setFloat("boneTextureWidth",4*(e.bones.length+1))}else c.setMatrices("mBones",e.getTransformMatrices(n))}(0,ua.an)(c,a,r),It.G.BindMorphTargetParameters(n,c),n.morphTargetManager&&n.morphTargetManager.isUsingTextureForTargets&&n.morphTargetManager._bind(c)}n._processRendering(s,e,c,a.fillMode,d,u,((e,t)=>c.setMatrix("world",t)))}};this._depthMap.customRenderFunction=(e,t,i,n)=>{let s;if(n.length)for(s=0;s4&&(h.push(ne.o.MatricesIndicesExtraKind),h.push(ne.o.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),l.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0));const t=e.getRenderingMesh().skeleton;(null==t?void 0:t.isUsingTextureForMatrices)&&l.push("#define BONETEXTURE")}else l.push("#define NUM_BONE_INFLUENCERS 0");const c=s.morphTargetManager;let d=0;c&&c.numInfluencers>0&&(d=c.numInfluencers,l.push("#define MORPHTARGETS"),l.push("#define NUM_MORPH_INFLUENCERS "+d),c.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),It.G.PrepareAttributesForMorphTargetsInfluencers(h,s,d)),t&&(l.push("#define INSTANCES"),It.G.PushAttributesForInstances(h),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),this._storeNonLinearDepth&&l.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&l.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&l.push("#define PACKED"),(0,ua.lK)(a,r,l);const u=e._getDrawWrapper(void 0,!0),p=u.defines,f=l.join("\n");if(p!==f){const e=["world","mBones","boneTextureWidth","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];(0,ua.qx)(e),u.setEffect(n.createEffect("depth",h,e,["diffuseSampler","morphTargets","boneSampler"],f,void 0,void 0,void 0,{maxSimultaneousMorphTargets:d}),f)}return u.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){const e=[];for(const t in this._scene._depthRenderer){this._scene._depthRenderer[t]===this&&e.push(t)}if(e.length>0){this._depthMap.dispose();for(const t of e)delete this._scene._depthRenderer[t]}}}Rg._SceneComponentInitialization=e=>{throw(0,ge.S)("DepthRendererSceneComponent")};const Pg="minmaxReduxPixelShader",Ig="varying vec2 vUV;\nuniform sampler2D textureSampler;\n#if defined(INITIAL)\nuniform sampler2D sourceTexture;\nuniform vec2 texSize;\nvoid main(void)\n{\nivec2 coord=ivec2(vUV*(texSize-1.0));\nfloat f1=texelFetch(sourceTexture,coord,0).r;\nfloat f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;\nfloat f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;\nfloat f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;\nfloat minz=min(min(min(f1,f2),f3),f4);\n#ifdef DEPTH_REDUX\nfloat maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);\n#else\nfloat maxz=max(max(max(f1,f2),f3),f4);\n#endif\nglFragColor=vec4(minz,maxz,0.,0.);\n}\n#elif defined(MAIN)\nuniform vec2 texSize;\nvoid main(void)\n{\nivec2 coord=ivec2(vUV*(texSize-1.0));\nvec2 f1=texelFetch(textureSampler,coord,0).rg;\nvec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;\nvec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;\nvec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;\nfloat minz=min(min(min(f1.x,f2.x),f3.x),f4.x);\nfloat maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);\nglFragColor=vec4(minz,maxz,0.,0.);\n}\n#elif defined(ONEBEFORELAST)\nuniform ivec2 texSize;\nvoid main(void)\n{\nivec2 coord=ivec2(vUV*vec2(texSize-1));\nvec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;\nvec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;\nvec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;\nvec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;\nfloat minz=min(f1.x,f2.x);\nfloat maxz=max(f1.y,f2.y);\nglFragColor=vec4(minz,maxz,0.,0.);\n}\n#elif defined(LAST)\nvoid main(void)\n{\nglFragColor=vec4(0.);\nif (true) { \ndiscard;\n}\n}\n#endif\n";Ht.v.ShadersStore[Pg]=Ig;class Mg{constructor(e){this.onAfterReductionPerformed=new r.y$,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new _i.O(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((()=>{this._postProcessManager._rebuild()}))}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,n=!0){if(e===this._sourceTexture)return;this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=n;const s=this._camera.getScene(),r=new Zt("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,s.getEngine(),!1,"#define INITIAL"+(t?"\n#define DEPTH_REDUX":""),i,void 0,void 0,void 0,7);r.autoClear=!1,r.forceFullscreenViewport=n;let o=this._sourceTexture.getRenderWidth(),a=this._sourceTexture.getRenderHeight();r.onApply=((e,t)=>i=>{i.setTexture("sourceTexture",this._sourceTexture),i.setFloat2("texSize",e,t)})(o,a),this._reductionSteps.push(r);let l=1;for(;o>1||a>1;){o=Math.max(Math.round(o/2),1),a=Math.max(Math.round(a/2),1);const e=new Zt("Reduction phase "+l,"minmaxRedux",["texSize"],null,{width:o,height:a},null,1,s.getEngine(),!1,"#define "+(1==o&&1==a?"LAST":1==o||1==a?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,7);if(e.autoClear=!1,e.forceFullscreenViewport=n,e.onApply=((e,t)=>i=>{1==e||1==t?i.setInt2("texSize",e,t):i.setFloat2("texSize",e,t)})(o,a),this._reductionSteps.push(e),l++,1==o&&1==a){const t=(e,t,i)=>{const n=new Float32Array(4*e*t),r={min:0,max:0};return()=>{s.getEngine()._readTexturePixels(i.inputTexture.texture,e,t,-1,0,n,!1),r.min=n[0],r.max=n[1],this.onAfterReductionPerformed.notifyObservers(r)}};e.onAfterRenderObservable.add(t(o,a,e))}}}get refreshRate(){return this._sourceTexture?this._sourceTexture.refreshRate:-1}set refreshRate(e){this._sourceTexture&&(this._sourceTexture.refreshRate=e)}get activated(){return this._activated}activate(){!this._onAfterUnbindObserver&&this._sourceTexture&&(this._onAfterUnbindObserver=this._sourceTexture.onAfterUnbindObservable.add((()=>{var e,t;const i=this._camera.getScene().getEngine();null===(e=i._debugPushGroup)||void 0===e||e.call(i,"min max reduction",1),this._reductionSteps[0].activate(this._camera),this._postProcessManager.directRender(this._reductionSteps,this._reductionSteps[0].inputTexture,this._forceFullscreenViewport),i.unBindFramebuffer(this._reductionSteps[0].inputTexture,!1),null===(t=i._debugPopGroup)||void 0===t||t.call(i,1)})),this._activated=!0)}deactivate(){this._onAfterUnbindObserver&&this._sourceTexture&&(this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=null,this._activated=!1)}dispose(e=!0){if(e&&(this.onAfterReductionPerformed.clear(),this._onContextRestoredObserver&&(this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)),this.deactivate(),this._reductionSteps){for(let e=0;et&&(e=0,t=1),e<0&&(e=0),t>1&&(t=1),this._minDistance=e,this._maxDistance=t,this._breaksAreDirty=!0)}get minDistance(){return this._minDistance}get maxDistance(){return this._maxDistance}getClassName(){return Bg.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e=0&&et.maxZ||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0):this._shadowMaxZ=e}get debug(){return this._debug}set debug(e){this._debug=e,this._light._markMeshesAsLightDirty()}get depthClamp(){return this._depthClamp}set depthClamp(e){this._depthClamp=e}get cascadeBlendPercentage(){return this._cascadeBlendPercentage}set cascadeBlendPercentage(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()}get lambda(){return this._lambda}set lambda(e){const t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)}getCascadeViewMatrix(e){return e>=0&&e=0&&e=0&&e{let t=e.min,i=e.max;t>=i&&(t=0,i=1),t==this._minDistance&&i==this._maxDistance||this.setMinMaxDistance(t,i)})),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}}get autoCalcDepthBoundsRefreshRate(){var e,t,i;return null!==(i=null===(t=null===(e=this._depthReducer)||void 0===e?void 0:e.depthRenderer)||void 0===t?void 0:t.getDepthMap().refreshRate)&&void 0!==i?i:-1}set autoCalcDepthBoundsRefreshRate(e){var t;(null===(t=this._depthReducer)||void 0===t?void 0:t.depthRenderer)&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)}splitFrustum(){this._breaksAreDirty=!0}_splitFrustum(){const e=this._getCamera();if(!e)return;const t=e.minZ,i=e.maxZ||this._shadowMaxZ,n=i-t,s=this._minDistance,r=t+s*n,o=t+(this._shadowMaxZ=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance)*n,a=o-r,l=o/r;for(let h=0;h{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===xg.FILTER_PCF&&e.setColorWrite(!1),this._scene.setTransformMatrix(this.getCascadeViewMatrix(t),this.getCascadeProjectionMatrix(t)),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._shadowMap.onBeforeBindObservable.add((()=>{var t;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),null===(t=e._debugPushGroup)||void 0===t||t.call(e,`cascaded shadow map generation for pass id ${e.currentRenderPassId}`,1),this._breaksAreDirty&&this._splitFrustum(),this._computeMatrices()})),this._splitFrustum()}_bindCustomEffectForRenderSubMeshForShadowMap(e,t){t.setMatrix("viewProjection",this.getCascadeTransformMatrix(this._currentLayer))}_isReadyCustomDefines(e){e.push("#define SM_DEPTHCLAMP "+(this._depthClamp&&this._filter!==xg.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);const i=this._scene,n=this._light;if(!i.shadowsEnabled||!n.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;const s=this._getCamera();s&&this._shadowMaxZ<=(s.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),0===this.cascadeBlendPercentage&&(e["SHADOWCSMNOBLEND"+t]=!0)}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const n=this._getCamera();if(!n)return;const s=this.getShadowMap();if(!s)return;const r=s.getSize().width;if(t.setMatrices("lightMatrix"+e,this._transformMatricesAsArray),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,0===this.cascadeBlendPercentage?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===xg.FILTER_PCF)t.setDepthStencilTexture("shadowSampler"+e,s),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),r,1/r,this.frustumEdgeFalloff,e);else if(this._filter===xg.FILTER_PCSS){for(let e=0;enew Bg(e,t,void 0,i)));return void 0!==e.numCascades&&(i.numCascades=e.numCascades),void 0!==e.debug&&(i.debug=e.debug),void 0!==e.stabilizeCascades&&(i.stabilizeCascades=e.stabilizeCascades),void 0!==e.lambda&&(i.lambda=e.lambda),void 0!==e.cascadeBlendPercentage&&(i.cascadeBlendPercentage=e.cascadeBlendPercentage),void 0!==e.depthClamp&&(i.depthClamp=e.depthClamp),void 0!==e.autoCalcDepthBounds&&(i.autoCalcDepthBounds=e.autoCalcDepthBounds),void 0!==e.shadowMaxZ&&(i.shadowMaxZ=e.shadowMaxZ),void 0!==e.penumbraDarkness&&(i.penumbraDarkness=e.penumbraDarkness),void 0!==e.freezeShadowCastersBoundingInfo&&(i.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),void 0!==e.minDistance&&void 0!==e.maxDistance&&i.setMinMaxDistance(e.minDistance,e.maxDistance),i}}Bg._FrustumCornersNDCSpace=[new o.P(-1,1,-1),new o.P(1,1,-1),new o.P(1,-1,-1),new o.P(-1,-1,-1),new o.P(-1,1,1),new o.P(1,1,1),new o.P(1,-1,1),new o.P(-1,-1,1)],Bg.CLASSNAME="CascadedShadowGenerator",Bg.DEFAULT_CASCADES_COUNT=4,Bg.MIN_CASCADES_COUNT=2,Bg.MAX_CASCADES_COUNT=4,Bg._SceneComponentInitialization=e=>{throw(0,ge.S)("ShadowGeneratorSceneComponent")},n.p.AddParser(Se.l.NAME_SHADOWGENERATOR,((e,t)=>{if(void 0!==e.shadowGenerators&&null!==e.shadowGenerators)for(let i=0,n=e.shadowGenerators.length;i{let t=e._getComponent(Se.l.NAME_SHADOWGENERATOR);t||(t=new Ug(e),e._addComponent(t))},b.N.AddNodeConstructor("Light_Type_0",((e,t)=>()=>new Vg(e,o.P.Zero(),t)));class Vg extends np{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 he.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new o.P(1,0,0);case 1:return new o.P(-1,0,0);case 2:return new o.P(0,-1,0);case 3:return new o.P(0,1,0);case 4:return new o.P(0,0,1);case 5:return new o.P(0,0,-1)}return o.P.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){const n=this.getScene().activeCamera;if(!n)return;const s=void 0!==this.shadowMinZ?this.shadowMinZ:n.minZ,r=void 0!==this.shadowMaxZ?this.shadowMaxZ:n.maxZ,a=this.getScene().getEngine().useReverseDepthBuffer;o.y3.PerspectiveFovLHToRef(this.shadowAngle,1,a?r:s,a?s:r,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}}(0,oe.gn)([(0,E.qC)()],Vg.prototype,"shadowAngle",null);class kg{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{const e=this._renderingCanvas.getBoundingClientRect(),t=window.getComputedStyle(this._renderingCanvas).position;this._loadingDiv&&(this._loadingDiv.style.position="fixed"===t?"fixed":"absolute",this._loadingDiv.style.left=e.left+"px",this._loadingDiv.style.top=e.top+"px",this._loadingDiv.style.width=e.width+"px",this._loadingDiv.style.height=e.height+"px")}}displayLoadingUI(){if(this._loadingDiv)return;this._loadingDiv=document.createElement("div"),this._loadingDiv.id="babylonjsLoadingDiv",this._loadingDiv.style.opacity="0",this._loadingDiv.style.transition="opacity 1.5s ease",this._loadingDiv.style.pointerEvents="none",this._loadingDiv.style.display="grid",this._loadingDiv.style.gridTemplateRows="100%",this._loadingDiv.style.gridTemplateColumns="100%",this._loadingDiv.style.justifyItems="center",this._loadingDiv.style.alignItems="center",this._loadingTextDiv=document.createElement("div"),this._loadingTextDiv.style.position="absolute",this._loadingTextDiv.style.left="0",this._loadingTextDiv.style.top="50%",this._loadingTextDiv.style.marginTop="80px",this._loadingTextDiv.style.width="100%",this._loadingTextDiv.style.height="20px",this._loadingTextDiv.style.fontFamily="Arial",this._loadingTextDiv.style.fontSize="14px",this._loadingTextDiv.style.color="white",this._loadingTextDiv.style.textAlign="center",this._loadingTextDiv.style.zIndex="1",this._loadingTextDiv.innerHTML="Loading",this._loadingDiv.appendChild(this._loadingTextDiv),this._loadingTextDiv.innerHTML=this._loadingText,this._style=document.createElement("style"),this._style.type="text/css";this._style.innerHTML="@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }",document.getElementsByTagName("head")[0].appendChild(this._style);const e=!!window.SVGSVGElement,t=new Image;kg.DefaultLogoUrl?t.src=kg.DefaultLogoUrl:t.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC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1",t.style.gridRow="1",t.style.top="50%",t.style.left="50%",t.style.transform="translate(-50%, -50%)",t.style.position="absolute";const i=document.createElement("div");i.style.width="300px",i.style.gridColumn="1",i.style.gridRow="1",i.style.top="50%",i.style.left="50%",i.style.transform="translate(-50%, -50%)",i.style.position="absolute";const n=new Image;if(kg.DefaultSpinnerUrl?n.src=kg.DefaultSpinnerUrl:n.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",n.style.animation="spin1 0.75s infinite linear",n.style.webkitAnimation="spin1 0.75s infinite linear",n.style.transformOrigin="50% 50%",n.style.webkitTransformOrigin="50% 50%",!e){const e={w:16,h:18.5},i={w:30,h:30};t.style.width=`${e.w}vh`,t.style.height=`${e.h}vh`,t.style.left=`calc(50% - ${e.w/2}vh)`,t.style.top=`calc(50% - ${e.h/2}vh)`,n.style.width=`${i.w}vh`,n.style.height=`${i.h}vh`,n.style.left=`calc(50% - ${i.w/2}vh)`,n.style.top=`calc(50% - ${i.h/2}vh)`}i.appendChild(n),this._loadingDiv.appendChild(t),this._loadingDiv.appendChild(i),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}hideLoadingUI(){if(!this._loadingDiv)return;this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",(()=>{this._loadingTextDiv&&(this._loadingTextDiv.remove(),this._loadingTextDiv=null),this._loadingDiv&&(this._loadingDiv.remove(),this._loadingDiv=null),this._style&&(this._style.remove(),this._style=null),window.removeEventListener("resize",this._resizeLoadingUI)}))}set loadingUIText(e){this._loadingText=e,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)}get loadingUIText(){return this._loadingText}get loadingUIBackgroundColor(){return this._loadingDivBackgroundColor}set loadingUIBackgroundColor(e){this._loadingDivBackgroundColor=e,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)}}kg.DefaultLogoUrl="",kg.DefaultSpinnerUrl="",fe.D.DefaultLoadingScreenFactory=e=>new kg(e);var Gg=i(4106),zg=i(8058);class Wg{static ConvertPanoramaToCubemap(e,t,i,n,s=!1){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";return{front:this.CreateCubemapTexture(n,this.FACE_FRONT,e,t,i,s),back:this.CreateCubemapTexture(n,this.FACE_BACK,e,t,i,s),left:this.CreateCubemapTexture(n,this.FACE_LEFT,e,t,i,s),right:this.CreateCubemapTexture(n,this.FACE_RIGHT,e,t,i,s),up:this.CreateCubemapTexture(n,this.FACE_UP,e,t,i,s),down:this.CreateCubemapTexture(n,this.FACE_DOWN,e,t,i,s),size:n,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,n,s,r=!1){const o=new ArrayBuffer(e*e*4*3),a=new Float32Array(o),l=r?Math.max(1,Math.round(n/4/e)):1,h=1/l,c=h*h,d=t[1].subtract(t[0]).scale(h/e),u=t[3].subtract(t[2]).scale(h/e),p=1/e;let f=0;for(let _=0;_Math.PI;)s-=2*Math.PI;let o=s/Math.PI;const a=r/Math.PI;o=.5*o+.5;let l=Math.round(o*i);l<0?l=0:l>=i&&(l=i-1);let h=Math.round(a*n);h<0?h=0:h>=n&&(h=n-1);const c=n-h-1;return{r:t[c*i*3+3*l+0],g:t[c*i*3+3*l+1],b:t[c*i*3+3*l+2]}}}Wg.FACE_LEFT=[new o.P(-1,-1,-1),new o.P(1,-1,-1),new o.P(-1,1,-1),new o.P(1,1,-1)],Wg.FACE_RIGHT=[new o.P(1,-1,1),new o.P(-1,-1,1),new o.P(1,1,1),new o.P(-1,1,1)],Wg.FACE_FRONT=[new o.P(1,-1,-1),new o.P(1,-1,1),new o.P(1,1,-1),new o.P(1,1,1)],Wg.FACE_BACK=[new o.P(-1,-1,1),new o.P(-1,-1,-1),new o.P(-1,1,1),new o.P(-1,1,-1)],Wg.FACE_DOWN=[new o.P(1,1,-1),new o.P(1,1,1),new o.P(-1,1,-1),new o.P(-1,1,1)],Wg.FACE_UP=[new o.P(-1,-1,-1),new o.P(-1,-1,1),new o.P(1,-1,-1),new o.P(1,-1,1)];class Hg{static _Ldexp(e,t){return t>1023?e*Math.pow(2,1023)*Math.pow(2,t-1023):t<-1074?e*Math.pow(2,-1074)*Math.pow(2,t+1074):e*Math.pow(2,t)}static _Rgbe2float(e,t,i,n,s,r){s>0?(s=this._Ldexp(1,s-136),e[r+0]=t*s,e[r+1]=i*s,e[r+2]=n*s):(e[r+0]=0,e[r+1]=0,e[r+2]=0)}static _ReadStringLine(e,t){let i="",n="";for(let s=t;s32767)throw"HDR Bad header format, unsupported size";return o+=n.length+1,{height:t,width:i,dataPosition:o}}static GetCubeMapTextureData(e,t,i=!1){const n=new Uint8Array(e),s=this.RGBE_ReadHeader(n),r=this.RGBE_ReadPixels(n,s);return Wg.ConvertPanoramaToCubemap(r,s.width,s.height,t,i)}static RGBE_ReadPixels(e,t){return this._RGBEReadPixelsRLE(e,t)}static _RGBEReadPixelsRLE(e,t){let i=t.height;const n=t.width;let s,r,o,a,l,h=t.dataPosition,c=0,d=0,u=0;const p=new ArrayBuffer(4*n),f=new Uint8Array(p),_=new ArrayBuffer(t.width*t.height*4*3),m=new Float32Array(_);for(;i>0;){if(s=e[h++],r=e[h++],o=e[h++],a=e[h++],2!=s||2!=r||128&o||t.width<8||t.width>32767)return this._RGBEReadPixelsNOTRLE(e,t);if((o<<8|a)!=n)throw"HDR Bad header format, wrong scan line width";for(c=0,u=0;u<4;u++)for(d=(u+1)*n;c128){if(l=s-128,0==l||l>d-c)throw"HDR Bad Format, bad scanline data (run)";for(;l-- >0;)f[c++]=r}else{if(l=s,0==l||l>d-c)throw"HDR Bad Format, bad scanline data (non-run)";if(f[c++]=r,--l>0)for(let t=0;t0;){for(l=0;l{this._effectRenderer=new vi(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled((()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()}))})):(p.Y.Warn("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."),Promise.reject("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."))}}class $g extends Re{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(o.y3.RotationY(this._rotationY))}get rotationY(){return this._rotationY}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}constructor(e,t,i,n=!1,s=!0,a=!1,l=!1,h=null,c=null,d=!1){var u;super(t),this._generateHarmonics=!0,this._onError=null,this._isBlocking=!0,this._rotationY=0,this.boundingBoxPosition=o.P.Zero(),this.onLoadObservable=new r.y$,e&&(this._coordinatesMode=Le.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=o.y3.Identity(),this._prefilterOnLoad=l,this._onLoad=()=>{this.onLoadObservable.notifyObservers(this),h&&h()},this._onError=c,this.gammaSpace=a,this._noMipmap=n,this._size=i,this._supersample=d,this._generateHarmonics=s,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?this._texture.isReady?se.w1.SetImmediate((()=>this._onLoad())):this._texture.onLoadedObservable.add(this._onLoad):(null===(u=this.getScene())||void 0===u?void 0:u.useDelayedTextureLoading)?this.delayLoadState=4:this._loadTexture())}getClassName(){return"HDRCubeTexture"}_loadTexture(){const e=this._getEngine(),t=e.getCaps();let i=0;t.textureFloat&&t.textureFloatLinearFiltering?i=1:t.textureHalfFloat&&t.textureHalfFloatLinearFiltering&&(i=2);if(e._features.allowTexturePrefiltering&&this._prefilterOnLoad){const t=this._onLoad,i=new qg(e);this._onLoad=()=>{i.prefilter(this,t)}}this._texture=e.createRawCubeTextureFromUrl(this.url,this.getScene(),this._size,4,i,this._noMipmap,(e=>{this.lodGenerationOffset=0,this.lodGenerationScale=.8;const t=Hg.GetCubeMapTextureData(e,this._size,this._supersample);if(this._generateHarmonics){const e=zh.ConvertCubeMapToSphericalPolynomial(t);this.sphericalPolynomial=e}const n=[];let s=null,r=null;for(let o=0;o<6;o++){2===i?r=new Uint16Array(this._size*this._size*3):0===i&&(s=new Uint8Array(this._size*this._size*3));const e=t[$g._FacesMapping[o]];if(this.gammaSpace||r||s)for(let t=0;t255){const e=255/o;i*=e,n*=e,r*=e}s[3*t+0]=i,s[3*t+1]=n,s[3*t+2]=r}r?n.push(r):s?n.push(s):n.push(e)}return n}),null,this._onLoad,this._onError)}clone(){const e=new $g(this.url,this.getScene()||this._getEngine(),this._size,this._noMipmap,this._generateHarmonics,this.gammaSpace);return e.level=this.level,e.wrapU=this.wrapU,e.wrapV=this.wrapV,e.coordinatesIndex=this.coordinatesIndex,e.coordinatesMode=this.coordinatesMode,e}delayLoad(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this._loadTexture())}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){var t;this._textureMatrix=e,e.updateFlag!==this._textureMatrix.updateFlag&&e.isIdentity()!==this._textureMatrix.isIdentity()&&(null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1,(e=>-1!==e.getActiveTextures().indexOf(this))))}dispose(){this.onLoadObservable.clear(),super.dispose()}static Parse(e,t,i){let n=null;return e.name&&!e.isRenderTarget&&(n=new $g(i+e.name,t,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace),n.name=e.name,n.hasAlpha=e.hasAlpha,n.level=e.level,n.coordinatesMode=e.coordinatesMode,n.isBlocking=e.isBlocking),n&&(e.boundingBoxPosition&&(n.boundingBoxPosition=o.P.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(n.boundingBoxSize=o.P.FromArray(e.boundingBoxSize)),e.rotationY&&(n.rotationY=e.rotationY)),n}serialize(){if(!this.name)return null;const e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this.gammaSpace,e.generateHarmonics=this._generateHarmonics,e.customType="BABYLON.HDRCubeTexture",e.noMipmap=this._noMipmap,e.isBlocking=this._isBlocking,e.rotationY=this._rotationY,e}}$g._FacesMapping=["right","left","up","down","front","back"],(0,l.H)("BABYLON.HDRCubeTexture",$g);class Qg{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=new Array,this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new r.y$,this._onDataLayoutChanged=new r.y$,this._animationPropertiesOverride=null,this._scene=i||m.l.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=E.p4.Clone((()=>new Qg(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())),E.p4.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){const i=new Qg(e.name,e.influence);if(i.setPositions(e.positions),null!=e.id&&(i.id=e.id),e.normals&&i.setNormals(e.normals),e.tangents&&i.setTangents(e.tangents),e.uvs&&i.setUVs(e.uvs),e.animations){for(let t=0;t0}constructor(e=null){if(this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new Wt.t(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._uniqueId=0,this._tempInfluences=new Array,this._canUseTextureForTargets=!1,this._blockCounter=0,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this._useTextureToStoreTargets=!0,e||(e=m.l.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 uniqueId(){return this._uniqueId}get vertexCount(){return this._vertexCount}get supportsNormals(){return this._supportsNormals&&this.enableNormalMorphing}get supportsTangents(){return this._supportsTangents&&this.enableTangentMorphing}get supportsUVs(){return this._supportsUVs&&this.enableUVMorphing}get numTargets(){return this._targets.length}get numInfluencers(){return this._activeTargets.length}get influences(){return this._influences}get useTextureToStoreTargets(){return this._useTextureToStoreTargets}set useTextureToStoreTargets(e){this._useTextureToStoreTargets=e}get isUsingTextureForTargets(){var e;return Jg.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!(null===(e=this._scene)||void 0===e?void 0:e.getEngine().getCaps().disableMorphTargetTexture)}getActiveTarget(e){return this._activeTargets.data[e]}getTarget(e){return this._targets[e]}addTarget(e){this._targets.push(e),this._targetInfluenceChangedObservers.push(e.onInfluenceChanged.add((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)}clone(){const e=new Jg(this._scene);for(const t of this._targets)e.addTarget(t.clone());return e.enableNormalMorphing=this.enableNormalMorphing,e.enableTangentMorphing=this.enableTangentMorphing,e.enableUVMorphing=this.enableUVMorphing,e}serialize(){const e={};e.id=this.uniqueId,e.targets=[];for(const t of this._targets)e.targets.push(t.serialize());return e}_syncActiveTargets(e){if(this.areUpdatesFrozen)return;let t=0;this._activeTargets.reset(),this._supportsNormals=!0,this._supportsTangents=!0,this._supportsUVs=!0,this._vertexCount=0,this._scene&&this._targets.length>this._scene.getEngine().getCaps().texture2DArrayMaxLayerCount&&(this.useTextureToStoreTargets=!1),this._morphTargetTextureIndices&&this._morphTargetTextureIndices.length===this._targets.length||(this._morphTargetTextureIndices=new Float32Array(this._targets.length));let i=-1;for(const n of this._targets){if(i++,0===n.influence&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=Jg.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(n),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=n.influence,this._supportsNormals=this._supportsNormals&&n.hasNormals,this._supportsTangents=this._supportsTangents&&n.hasTangents,this._supportsUVs=this._supportsUVs&&n.hasUVs;const e=n.getPositions();if(e){const t=e.length/3;if(0===this._vertexCount)this._vertexCount=t;else if(this._vertexCount!==t)return void p.Y.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 n=0;ne&&(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-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 Jg(t);i._uniqueId=e.id;for(const n of e.targets)i.addTarget(Qg.Parse(n,t));return i}}Jg.EnableTextureStorage=!0,Jg.MaxActiveMorphTargetsInVertexAttributeMode=8;class ev{constructor(){this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld=o.P.Zero(),this._hitPointWorld=o.P.Zero(),this._rayFromWorld=o.P.Zero(),this._rayToWorld=o.P.Zero(),this._triangleIndex=-1}get hasHit(){return this._hasHit}get hitDistance(){return this._hitDistance}get hitNormalWorld(){return this._hitNormalWorld}get hitPointWorld(){return this._hitPointWorld}get rayFromWorld(){return this._rayFromWorld}get rayToWorld(){return this._rayToWorld}get triangleIndex(){return this._triangleIndex}setHitData(e,t,i){this._hasHit=!0,this._hitNormalWorld.set(e.x,e.y,e.z),this._hitPointWorld.set(t.x,t.y,t.z),this._triangleIndex=null!=i?i:-1}setHitDistance(e){this._hitDistance=e}calculateHitDistance(){this._hitDistance=o.P.Distance(this._rayFromWorld,this._hitPointWorld)}reset(e=o.P.Zero(),t=o.P.Zero()){this._rayFromWorld.copyFrom(e),this._rayToWorld.copyFrom(t),this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld.setAll(0),this._hitPointWorld.setAll(0),this._triangleIndex=-1}}class tv{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw(0,ge.S)("CannonJSPlugin")}constructor(e,t=tv.DefaultPluginFactory()){if(this._physicsPlugin=t,this._impostors=[],this._joints=[],this._subTimeStep=0,this._uniqueIdCounter=0,!this._physicsPlugin.isSupported())throw new Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");e=e||new o.P(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._impostors.forEach((function(e){e.dispose()})),this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}addImpostor(e){this._impostors.push(e),e.uniqueId=this._uniqueIdCounter++,e.parent||this._physicsPlugin.generatePhysicsBody(e)}removeImpostor(e){const t=this._impostors.indexOf(e);if(t>-1){this._impostors.splice(t,1).length&&this.getPhysicsPlugin().removePhysicsBody(e)}}addJoint(e,t,i){const n={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(n),this._physicsPlugin.generateJoint(n)}removeJoint(e,t,i){const n=this._joints.filter((function(n){return n.connectedImpostor===t&&n.joint===i&&n.mainImpostor===e}));n.length&&this._physicsPlugin.removeJoint(n[0])}_step(e){this._impostors.forEach((e=>{e.isBodyInitRequired()&&this._physicsPlugin.generatePhysicsBody(e)})),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)}getPhysicsPlugin(){return this._physicsPlugin}getImpostors(){return this._impostors}getImpostorForPhysicsObject(e){for(let t=0;t0&&(this._physicsBodiesToRemoveAfterStep.forEach((e=>{"function"==typeof this.world.removeBody?this.world.removeBody(e):this.world.remove(e)})),this._physicsBodiesToRemoveAfterStep.length=0)}applyImpulse(e,t,i){const n=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(s,n)}applyForce(e,t,i){const n=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(s,n)}generatePhysicsBody(e){if(this._removeMarkedPhysicsBodiesFromWorld(),e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else{if(e.isBodyInitRequired()){const t=this._createShape(e);if(!t)return void p.Y.Warn("It was not possible to create a physics body for this object.");const i=e.physicsBody;i&&this.removePhysicsBody(e);const n=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),s={mass:e.getParam("mass"),material:n},r=e.getParam("nativeOptions");for(const e in r)Object.prototype.hasOwnProperty.call(r,e)&&(s[e]=r[e]);e.physicsBody=new this.BJSCANNON.Body(s),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),"function"==typeof this.world.addBody?this.world.addBody(e.physicsBody):this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach((function(t){const n=i[t];e.physicsBody[t].set(n.x,n.y,n.z)})),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)}}_processChildMeshes(e){const t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[],i=e.object.rotationQuaternion;if(i?i.conjugateToRef(this._tmpQuaternion):this._tmpQuaternion.set(0,0,0,1),t.length){const i=t=>{if(!t.rotationQuaternion)return;const n=t.getPhysicsImpostor();if(n){if(n.parent!==e&&t.parent){const i=t.getAbsolutePosition().subtract(t.parent.getAbsolutePosition()),s=t.rotationQuaternion.multiply(this._tmpQuaternion);n.physicsBody&&(this.removePhysicsBody(n),n.physicsBody=null),n.parent=e,n.resetUpdateFlags(),e.physicsBody.addShape(this._createShape(n),new this.BJSCANNON.Vec3(i.x,i.y,i.z),new this.BJSCANNON.Quaternion(s.x,s.y,s.z,s.w)),e.physicsBody.mass+=n.getParam("mass")}}t.getChildMeshes(!0).filter((e=>!!e.physicsImpostor)).forEach(i)};t.filter((e=>!!e.physicsImpostor)).forEach(i)}}removePhysicsBody(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),-1===this._physicsBodiesToRemoveAfterStep.indexOf(e.physicsBody)&&this._physicsBodiesToRemoveAfterStep.push(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;let n;const s=e.joint.jointData,r={pivotA:s.mainPivot?(new this.BJSCANNON.Vec3).set(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z):null,pivotB:s.connectedPivot?(new this.BJSCANNON.Vec3).set(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z):null,axisA:s.mainAxis?(new this.BJSCANNON.Vec3).set(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z):null,axisB:s.connectedAxis?(new this.BJSCANNON.Vec3).set(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z):null,maxForce:s.nativeParams.maxForce,collideConnected:!!s.collision};switch(e.joint.type){case st.HingeJoint:case st.Hinge2Joint:n=new this.BJSCANNON.HingeConstraint(t,i,r);break;case st.DistanceJoint:n=new this.BJSCANNON.DistanceConstraint(t,i,s.maxDistance||2);break;case st.SpringJoint:{const e=s;n=new this.BJSCANNON.Spring(t,i,{restLength:e.length,stiffness:e.stiffness,damping:e.damping,localAnchorA:r.pivotA,localAnchorB:r.pivotB});break}case st.LockJoint:n=new this.BJSCANNON.LockConstraint(t,i,r);break;case st.PointToPointJoint:case st.BallAndSocketJoint:default:n=new this.BJSCANNON.PointToPointConstraint(t,r.pivotA,i,r.pivotB,r.maxForce)}n.collideConnected=!!s.collision,e.joint.physicsJoint=n,e.joint.type!==st.SpringJoint?this.world.addConstraint(n):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){n.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}removeJoint(e){e.joint.type!==st.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}_addMaterial(e,t,i){let n,s;for(n=0;n1e3*i));e++);this.time+=n;const a=this.time%i/i,l=e,h=this.bodies;for(let e=0;e!==h.length;e++){const i=h[e];i.type!==t.Body.STATIC&&i.sleepState!==t.Body.SLEEPING?(i.position.vsub(i.previousPosition,l),l.scale(a,l),i.position.vadd(l,i.interpolatedPosition)):(i.interpolatedPosition.set(i.position.x,i.position.y,i.position.z),i.interpolatedQuaternion.set(i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w))}}}}raycast(e,t){return this._raycastResult.reset(e,t),this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._cannonRaycastResult.reset(),this.world.raycastClosest(e,t,{},this._cannonRaycastResult),i.reset(e,t),this._cannonRaycastResult.hasHit&&(i.setHitData({x:this._cannonRaycastResult.hitNormalWorld.x,y:this._cannonRaycastResult.hitNormalWorld.y,z:this._cannonRaycastResult.hitNormalWorld.z},{x:this._cannonRaycastResult.hitPointWorld.x,y:this._cannonRaycastResult.hitPointWorld.y,z:this._cannonRaycastResult.hitPointWorld.z}),i.setHitDistance(this._cannonRaycastResult.distance))}}tv.DefaultPluginFactory=()=>new iv;class nv{constructor(e=!0,t,i=OIMO){this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=o.P.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new ev}getPluginVersion(){return 1}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}setTimeStep(e){this.world.timeStep=e}getTimeStep(){return this.world.timeStep}executeStep(e,t){t.forEach((function(e){e.beforeStep()})),this.world.timeStep=this._useDeltaForWorldStep?e:this._fixedTimeStep,this.world.step(),t.forEach((e=>{e.afterStep(),this._tmpImpostorsArray[e.uniqueId]=e}));let i=this.world.contacts;for(;null!==i;){if(i.touching&&!i.body1.sleeping&&!i.body2.sleeping){i=i.next;continue}const e=this._tmpImpostorsArray[+i.body1.name],t=this._tmpImpostorsArray[+i.body2.name];e&&t?(e.onCollide({body:t.physicsBody,point:null,distance:0,impulse:0,normal:null}),t.onCollide({body:e.physicsBody,point:null,distance:0,impulse:0,normal:null}),i=i.next):i=i.next}}applyImpulse(e,t,i){const n=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*n))}applyForce(e,t,i){p.Y.Warn("Oimo doesn't support applying force. Using impulse instead."),this.applyImpulse(e,t,i)}generatePhysicsBody(e){if(e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else{if(e.isBodyInitRequired()){const t={name:e.uniqueId,config:[e.getParam("mass")||.001,e.getParam("friction"),e.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:0!==e.getParam("mass"),density:e.getParam("mass"),friction:e.getParam("friction"),restitution:e.getParam("restitution"),world:this.world},i=[e];(e=>{e.getChildMeshes&&e.getChildMeshes().forEach((function(e){e.physicsImpostor&&i.push(e.physicsImpostor)}))})(e.object);const n=e=>Math.max(e,k.kn),s=new o._f;i.forEach((i=>{if(!i.object.rotationQuaternion)return;const r=i.object.rotationQuaternion;s.copyFrom(r),i.object.rotationQuaternion.set(0,0,0,1),i.object.computeWorldMatrix(!0);const o=s.toEulerAngles(),a=i.getObjectExtents(),l=57.29577951308232;if(i===e){const i=e.getObjectCenter();e.object.getAbsolutePivotPoint().subtractToRef(i,this._tmpPositionVector),this._tmpPositionVector.divideInPlace(e.object.scaling),t.pos.push(i.x),t.pos.push(i.y),t.pos.push(i.z),t.posShape.push(0,0,0),t.rotShape.push(0,0,0)}else{const e=i.object.position.clone();t.posShape.push(e.x),t.posShape.push(e.y),t.posShape.push(e.z),t.rotShape.push(o.x*l,o.y*l,o.z*l)}switch(i.object.rotationQuaternion.copyFrom(s),i.type){case rt.ParticleImpostor:p.Y.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case rt.SphereImpostor:{const e=a.x,i=a.y,s=a.z,r=Math.max(n(e),n(i),n(s))/2;t.type.push("sphere"),t.size.push(r),t.size.push(r),t.size.push(r);break}case rt.CylinderImpostor:{const e=n(a.x)/2,i=n(a.y);t.type.push("cylinder"),t.size.push(e),t.size.push(i),t.size.push(i);break}case rt.PlaneImpostor:case rt.BoxImpostor:default:{const e=n(a.x),i=n(a.y),s=n(a.z);t.type.push("box"),t.size.push(e),t.size.push(i),t.size.push(s);break}}i.object.rotationQuaternion=r})),e.physicsBody=this.world.add(t),e.physicsBody.resetQuaternion(s),e.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpPositionVector)}}removePhysicsBody(e){this.world.removeRigidBody(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;const n=e.joint.jointData,s=n.nativeParams||{};let r;const o={body1:t,body2:i,axe1:s.axe1||(n.mainAxis?n.mainAxis.asArray():null),axe2:s.axe2||(n.connectedAxis?n.connectedAxis.asArray():null),pos1:s.pos1||(n.mainPivot?n.mainPivot.asArray():null),pos2:s.pos2||(n.connectedPivot?n.connectedPivot.asArray():null),min:s.min,max:s.max,collision:s.collision||n.collision,spring:s.spring,world:this.world};switch(e.joint.type){case st.BallAndSocketJoint:r="jointBall";break;case st.SpringJoint:{p.Y.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");const e=n;o.min=e.length||o.min,o.max=Math.max(o.min,o.max)}case st.DistanceJoint:r="jointDistance",o.max=n.maxDistance;break;case st.PrismaticJoint:r="jointPrisme";break;case st.SliderJoint:r="jointSlide";break;case st.WheelJoint:r="jointWheel";break;case st.HingeJoint:default:r="jointHinge"}o.type=r,e.joint.physicsJoint=this.world.add(o)}removeJoint(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(t){p.Y.Warn(t)}}isSupported(){return void 0!==this.BJSOIMO}setTransformationFromPhysicsBody(e){if(!e.physicsBody.sleeping){if(e.physicsBody.shapes.next){let t=e.physicsBody.shapes;for(;t.next;)t=t.next;e.object.position.set(t.position.x,t.position.y,t.position.z)}else{const t=e.physicsBody.getPosition();e.object.position.set(t.x,t.y,t.z)}if(e.object.rotationQuaternion){const t=e.physicsBody.getQuaternion();e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}}}setPhysicsBodyTransformation(e,t,i){const n=e.physicsBody;e.physicsBody.shapes.next||(n.position.set(t.x,t.y,t.z),n.orientation.set(i.x,i.y,i.z,i.w),n.syncShapes(),n.awake())}setLinearVelocity(e,t){e.physicsBody.linearVelocity.set(t.x,t.y,t.z)}setAngularVelocity(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)}getLinearVelocity(e){const t=e.physicsBody.linearVelocity;return t?new o.P(t.x,t.y,t.z):null}getAngularVelocity(e){const t=e.physicsBody.angularVelocity;return t?new o.P(t.x,t.y,t.z):null}setBodyMass(e,t){const i=0===t;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)}getBodyMass(e){return e.physicsBody.shapes.density}getBodyFriction(e){return e.physicsBody.shapes.friction}setBodyFriction(e,t){e.physicsBody.shapes.friction=t}getBodyRestitution(e){return e.physicsBody.shapes.restitution}setBodyRestitution(e,t){e.physicsBody.shapes.restitution=t}sleepBody(e){e.physicsBody.sleep()}wakeUpBody(e){e.physicsBody.awake()}updateDistanceJoint(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)}setMotor(e,t,i,n){void 0!==i?p.Y.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;const s=n?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setMotor(t,i)}setLimit(e,t,i,n){const s=n?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setLimit(t,void 0===i?-t:i)}syncMeshWithImpostor(e,t){const i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.orientation.x,e.rotationQuaternion.y=i.orientation.y,e.rotationQuaternion.z=i.orientation.z,e.rotationQuaternion.w=i.orientation.w)}getRadius(e){return e.physicsBody.shapes.radius}getBoxSizeToRef(e,t){const i=e.physicsBody.shapes;t.x=2*i.halfWidth,t.y=2*i.halfHeight,t.z=2*i.halfDepth}dispose(){this.world.clear()}raycast(e,t){return p.Y.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult}raycastToRef(e,t,i){p.Y.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)}}class sv{constructor(e=!0,t=Ammo,i=null){this._useDeltaForWorldStep=e,this.bjsAMMO={},this.name="AmmoJSPlugin",this._timeStep=1/60,this._fixedTimeStep=1/60,this._maxSteps=5,this._tmpQuaternion=new o._f,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new o.P,this._tmpContactNormal=new o.P,this._tmpVec3=new o.P,this._tmpMatrix=new o.y3,"function"!=typeof t?(this.bjsAMMO=t,this.isSupported()?(this._collisionConfiguration=new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration,this._dispatcher=new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration),this._overlappingPairCache=i||new this.bjsAMMO.btDbvtBroadphase,this._solver=new this.bjsAMMO.btSequentialImpulseConstraintSolver,this._softBodySolver=new this.bjsAMMO.btDefaultSoftBodySolver,this.world=new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher,this._overlappingPairCache,this._solver,this._collisionConfiguration,this._softBodySolver),this._tmpAmmoConcreteContactResultCallback=new this.bjsAMMO.ConcreteContactResultCallback,this._tmpAmmoConcreteContactResultCallback.addSingleResult=e=>{const t=(e=this.bjsAMMO.wrapPointer(e,this.bjsAMMO.btManifoldPoint)).getPositionWorldOnA(),i=e.m_normalWorldOnB;this._tmpContactPoint.x=t.x(),this._tmpContactPoint.y=t.y(),this._tmpContactPoint.z=t.z(),this._tmpContactNormal.x=i.x(),this._tmpContactNormal.y=i.y(),this._tmpContactNormal.z=i.z(),this._tmpContactImpulse=e.getAppliedImpulse(),this._tmpContactDistance=e.getDistance(),this._tmpContactCallbackResult=!0},this._raycastResult=new ev,this._tmpAmmoTransform=new this.bjsAMMO.btTransform,this._tmpAmmoTransform.setIdentity(),this._tmpAmmoQuaternion=new this.bjsAMMO.btQuaternion(0,0,0,1),this._tmpAmmoVectorA=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorB=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorC=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorD=new this.bjsAMMO.btVector3(0,0,0)):p.Y.Error("AmmoJS is not available. Please make sure you included the js file.")):p.Y.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.")}getPluginVersion(){return 1}setGravity(e){this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),this.world.setGravity(this._tmpAmmoVectorA),this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA)}setTimeStep(e){this._timeStep=e}setFixedTimeStep(e){this._fixedTimeStep=e}setMaxSteps(e){this._maxSteps=e}getTimeStep(){return this._timeStep}_isImpostorInContact(e){return this._tmpContactCallbackResult=!1,this.world.contactTest(e.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_isImpostorPairInContact(e,t){return this._tmpContactCallbackResult=!1,this.world.contactPairTest(e.physicsBody,t.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_stepSimulation(e=1/60,t=10,i=1/60){if(0==t)this.world.stepSimulation(e,0);else for(;t>0&&e>0;)e-i0&&this._isImpostorInContact(i))for(const e of i._onPhysicsCollideCallbacks)for(const t of e.otherImpostors)(i.physicsBody.isActive()||t.physicsBody.isActive())&&this._isImpostorPairInContact(i,t)&&(i.onCollide({body:t.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}),t.onCollide({body:i.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}))}_afterSoftStep(e){e.type===rt.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)}_ropeStep(e){const t=e.physicsBody.get_m_nodes(),i=t.size();let n,s,r,a,l;const h=new Array;for(let u=0;u{this.bjsAMMO.destroy(e)})),e._pluginData.toDispose=[]))}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;const n=e.joint.jointData;let s;switch(n.mainPivot||(n.mainPivot=new o.P(0,0,0)),n.connectedPivot||(n.connectedPivot=new o.P(0,0,0)),e.joint.type){case st.DistanceJoint:{const e=n.maxDistance;e&&(n.mainPivot=new o.P(0,-e/2,0),n.connectedPivot=new o.P(0,e/2,0)),s=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(n.mainPivot.x,n.mainPivot.y,n.mainPivot.z),new this.bjsAMMO.btVector3(n.connectedPivot.x,n.connectedPivot.y,n.connectedPivot.z));break}case st.HingeJoint:{n.mainAxis||(n.mainAxis=new o.P(0,0,0)),n.connectedAxis||(n.connectedAxis=new o.P(0,0,0));const e=new this.bjsAMMO.btVector3(n.mainAxis.x,n.mainAxis.y,n.mainAxis.z),r=new this.bjsAMMO.btVector3(n.connectedAxis.x,n.connectedAxis.y,n.connectedAxis.z);s=new this.bjsAMMO.btHingeConstraint(t,i,new this.bjsAMMO.btVector3(n.mainPivot.x,n.mainPivot.y,n.mainPivot.z),new this.bjsAMMO.btVector3(n.connectedPivot.x,n.connectedPivot.y,n.connectedPivot.z),e,r);break}case st.BallAndSocketJoint:s=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(n.mainPivot.x,n.mainPivot.y,n.mainPivot.z),new this.bjsAMMO.btVector3(n.connectedPivot.x,n.connectedPivot.y,n.connectedPivot.z));break;default:p.Y.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint"),s=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(n.mainPivot.x,n.mainPivot.y,n.mainPivot.z),new this.bjsAMMO.btVector3(n.connectedPivot.x,n.connectedPivot.y,n.connectedPivot.z))}this.world.addConstraint(s,!e.joint.jointData.collision),e.joint.physicsJoint=s}removeJoint(e){this.world&&this.world.removeConstraint(e.joint.physicsJoint)}_addMeshVerts(e,t,i){let n=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s=i.getIndices();s||(s=[]);let r,a=i.getVerticesData(ne.o.PositionKind);if(a||(a=[]),t&&t!==i){let e;e=t.rotationQuaternion?t.rotationQuaternion:t.rotation?o._f.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):o._f.Identity();o.y3.Compose(o.P.One(),e,t.position).invertToRef(this._tmpMatrix);r=i.computeWorldMatrix(!1).multiply(this._tmpMatrix)}else o.y3.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),r=this._tmpMatrix;const l=s.length/3;for(let t=0;t{n+=this._addMeshVerts(e,t,i)}))}return n}_softVertexData(e){const t=e.object;if(t&&t.getIndices&&t.getWorldMatrix&&t.getChildMeshes){let e=t.getIndices();e||(e=[]);let i=t.getVerticesData(ne.o.PositionKind);i||(i=[]);let n=t.getVerticesData(ne.o.NormalKind);n||(n=[]),t.computeWorldMatrix(!1);const s=[],r=[];for(let l=0;le*e)).reduce(((e,t)=>e+t)))t=s.length,i=t/3-1,this._tmpAmmoVectorA.setValue(s[0],s[1],s[2]),this._tmpAmmoVectorB.setValue(s[t-3],s[t-2],s[t-1]);else{e._isFromLine=!1;const n=e.getParam("path");if(null===e.getParam("shape"))return p.Y.Warn("No shape available for extruded mesh"),new this.bjsAMMO.btCompoundShape;t=n.length,i=t-1,this._tmpAmmoVectorA.setValue(n[0].x,n[0].y,n[0].z),this._tmpAmmoVectorB.setValue(n[t-1].x,n[t-1].y,n[t-1].z)}e.segments=i;let o=e.getParam("fixedPoints");o=o>3?3:o;const a=(new this.bjsAMMO.btSoftBodyHelpers).CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,i-1,o);return a.get_m_cfg().set_collisions(17),a}_createCustom(e){let t=null;return this.onCreateCustomShape&&(t=this.onCreateCustomShape(e)),null==t&&(t=new this.bjsAMMO.btCompoundShape),t}_addHullVerts(e,t,i){let n=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s=i.getIndices();s||(s=[]);let r=i.getVerticesData(ne.o.PositionKind);r||(r=[]),i.computeWorldMatrix(!1);const a=s.length/3;for(let t=0;t{n+=this._addHullVerts(e,t,i)}))}return n}_createShape(e,t=!1){const i=e.object;let n;const s=e.getObjectExtents();if(!t){const t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[];n=new this.bjsAMMO.btCompoundShape;let i=0;if(t.forEach((e=>{const t=e.getPhysicsImpostor();if(t){if(t.type==rt.MeshImpostor)throw"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";const s=this._createShape(t),r=e.parent.getWorldMatrix().clone(),a=new o.P;r.decompose(a),this._tmpAmmoTransform.getOrigin().setValue(e.position.x*a.x,e.position.y*a.y,e.position.z*a.z),this._tmpAmmoQuaternion.setValue(e.rotationQuaternion.x,e.rotationQuaternion.y,e.rotationQuaternion.z,e.rotationQuaternion.w),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),n.addChildShape(this._tmpAmmoTransform,s),t.dispose(),i++}})),i>0){if(e.type!=rt.NoImpostor){const t=this._createShape(e,!0);t&&(this._tmpAmmoTransform.getOrigin().setValue(0,0,0),this._tmpAmmoQuaternion.setValue(0,0,0,1),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),n.addChildShape(this._tmpAmmoTransform,t))}return n}this.bjsAMMO.destroy(n),n=null}switch(e.type){case rt.SphereImpostor:if(S.R.WithinEpsilon(s.x,s.y,1e-4)&&S.R.WithinEpsilon(s.x,s.z,1e-4))n=new this.bjsAMMO.btSphereShape(s.x/2);else{const e=[new this.bjsAMMO.btVector3(0,0,0)],t=[1];n=new this.bjsAMMO.btMultiSphereShape(e,t,1),n.setLocalScaling(new this.bjsAMMO.btVector3(s.x/2,s.y/2,s.z/2))}break;case rt.CapsuleImpostor:{const e=s.x/2;n=new this.bjsAMMO.btCapsuleShape(e,s.y-2*e)}break;case rt.CylinderImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),n=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case rt.PlaneImpostor:case rt.BoxImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),n=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case rt.MeshImpostor:if(0==e.getParam("mass")){if(this.onCreateCustomMeshImpostor)n=this.onCreateCustomMeshImpostor(e);else{const t=new this.bjsAMMO.btTriangleMesh;e._pluginData.toDispose.push(t);const s=this._addMeshVerts(t,i,i);n=0==s?new this.bjsAMMO.btCompoundShape:new this.bjsAMMO.btBvhTriangleMeshShape(t)}break}case rt.ConvexHullImpostor:if(this.onCreateCustomConvexHullImpostor)n=this.onCreateCustomConvexHullImpostor(e);else{const t=new this.bjsAMMO.btConvexHullShape;0==this._addHullVerts(t,i,i)?(e._pluginData.toDispose.push(t),n=new this.bjsAMMO.btCompoundShape):n=t}break;case rt.NoImpostor:n=new this.bjsAMMO.btSphereShape(s.x/2);break;case rt.CustomImpostor:n=this._createCustom(e);break;case rt.SoftbodyImpostor:n=this._createSoftbody(e);break;case rt.ClothImpostor:n=this._createCloth(e);break;case rt.RopeImpostor:n=this._createRope(e);break;default:p.Y.Warn("The impostor type is not currently supported by the ammo plugin.")}return n}setTransformationFromPhysicsBody(e){e.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.object.position.set(this._tmpAmmoTransform.getOrigin().x(),this._tmpAmmoTransform.getOrigin().y(),this._tmpAmmoTransform.getOrigin().z()),e.object.rotationQuaternion?e.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()):e.object.rotation&&(this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()),this._tmpQuaternion.toEulerAnglesToRef(e.object.rotation))}setPhysicsBodyTransformation(e,t,i){const n=e.physicsBody.getWorldTransform();if(Math.abs(n.getOrigin().x()-t.x)>k.kn||Math.abs(n.getOrigin().y()-t.y)>k.kn||Math.abs(n.getOrigin().z()-t.z)>k.kn||Math.abs(n.getRotation().x()-i.x)>k.kn||Math.abs(n.getRotation().y()-i.y)>k.kn||Math.abs(n.getRotation().z()-i.z)>k.kn||Math.abs(n.getRotation().w()-i.w)>k.kn)if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),n.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),n.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(n),0==e.mass){const t=e.physicsBody.getMotionState();t&&t.setWorldTransform(n)}else e.physicsBody.activate()}isSupported(){return void 0!==this.bjsAMMO}setLinearVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.linearVelocity(this._tmpAmmoVectorA):e.physicsBody.setLinearVelocity(this._tmpAmmoVectorA)}setAngularVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.angularVelocity(this._tmpAmmoVectorA):e.physicsBody.setAngularVelocity(this._tmpAmmoVectorA)}getLinearVelocity(e){let t;if(t=e.soft?e.physicsBody.linearVelocity():e.physicsBody.getLinearVelocity(),!t)return null;const i=new o.P(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}getAngularVelocity(e){let t;if(t=e.soft?e.physicsBody.angularVelocity():e.physicsBody.getAngularVelocity(),!t)return null;const i=new o.P(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}setBodyMass(e,t){e.soft?e.physicsBody.setTotalMass(t,!1):e.physicsBody.setMassProps(t),e._pluginData.mass=t}getBodyMass(e){return e._pluginData.mass||0}getBodyFriction(e){return e._pluginData.friction||0}setBodyFriction(e,t){e.soft?e.physicsBody.get_m_cfg().set_kDF(t):e.physicsBody.setFriction(t),e._pluginData.friction=t}getBodyRestitution(e){return e._pluginData.restitution||0}setBodyRestitution(e,t){e.physicsBody.setRestitution(t),e._pluginData.restitution=t}getBodyPressure(e){return e.soft?e._pluginData.pressure||0:(p.Y.Warn("Pressure is not a property of a rigid body"),0)}setBodyPressure(e,t){e.soft?e.type===rt.SoftbodyImpostor?(e.physicsBody.get_m_cfg().set_kPR(t),e._pluginData.pressure=t):(e.physicsBody.get_m_cfg().set_kPR(0),e._pluginData.pressure=0):p.Y.Warn("Pressure can only be applied to a softbody")}getBodyStiffness(e){return e.soft?e._pluginData.stiffness||0:(p.Y.Warn("Stiffness is not a property of a rigid body"),0)}setBodyStiffness(e,t){e.soft?(t=(t=t<0?0:t)>1?1:t,e.physicsBody.get_m_materials().at(0).set_m_kLST(t),e._pluginData.stiffness=t):p.Y.Warn("Stiffness cannot be applied to a rigid body")}getBodyVelocityIterations(e){return e.soft?e._pluginData.velocityIterations||0:(p.Y.Warn("Velocity iterations is not a property of a rigid body"),0)}setBodyVelocityIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_viterations(t),e._pluginData.velocityIterations=t):p.Y.Warn("Velocity iterations cannot be applied to a rigid body")}getBodyPositionIterations(e){return e.soft?e._pluginData.positionIterations||0:(p.Y.Warn("Position iterations is not a property of a rigid body"),0)}setBodyPositionIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_piterations(t),e._pluginData.positionIterations=t):p.Y.Warn("Position iterations cannot be applied to a rigid body")}appendAnchor(e,t,i,n,s=1,r=!1){const o=e.segments,a=Math.round((o-1)*i)+o*(o-1-Math.round((o-1)*n));e.physicsBody.appendAnchor(a,t.physicsBody,r,s)}appendHook(e,t,i,n=1,s=!1){const r=Math.round(e.segments*i);e.physicsBody.appendAnchor(r,t.physicsBody,s,n)}sleepBody(e){e.physicsBody.forceActivationState(0)}wakeUpBody(e){e.physicsBody.activate()}updateDistanceJoint(){p.Y.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")}setMotor(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)}setLimit(){p.Y.Warn("setLimit is not currently supported by the Ammo physics plugin")}syncMeshWithImpostor(e,t){t.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.position.x=this._tmpAmmoTransform.getOrigin().x(),e.position.y=this._tmpAmmoTransform.getOrigin().y(),e.position.z=this._tmpAmmoTransform.getOrigin().z(),e.rotationQuaternion&&(e.rotationQuaternion.x=this._tmpAmmoTransform.getRotation().x(),e.rotationQuaternion.y=this._tmpAmmoTransform.getRotation().y(),e.rotationQuaternion.z=this._tmpAmmoTransform.getRotation().z(),e.rotationQuaternion.w=this._tmpAmmoTransform.getRotation().w())}getRadius(e){return e.getObjectExtents().x/2}getBoxSizeToRef(e,t){const i=e.getObjectExtents();t.x=i.x,t.y=i.y,t.z=i.z}dispose(){this.bjsAMMO.destroy(this.world),this.bjsAMMO.destroy(this._solver),this.bjsAMMO.destroy(this._overlappingPairCache),this.bjsAMMO.destroy(this._dispatcher),this.bjsAMMO.destroy(this._collisionConfiguration),this.bjsAMMO.destroy(this._tmpAmmoVectorA),this.bjsAMMO.destroy(this._tmpAmmoVectorB),this.bjsAMMO.destroy(this._tmpAmmoVectorC),this.bjsAMMO.destroy(this._tmpAmmoTransform),this.bjsAMMO.destroy(this._tmpAmmoQuaternion),this.bjsAMMO.destroy(this._tmpAmmoConcreteContactResultCallback),this.world=null}raycast(e,t){return this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._tmpAmmoVectorRCA=new this.bjsAMMO.btVector3(e.x,e.y,e.z),this._tmpAmmoVectorRCB=new this.bjsAMMO.btVector3(t.x,t.y,t.z);const n=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,n),i.reset(e,t),n.hasHit()&&(i.setHitData({x:n.get_m_hitNormalWorld().x(),y:n.get_m_hitNormalWorld().y(),z:n.get_m_hitNormalWorld().z()},{x:n.get_m_hitPointWorld().x(),y:n.get_m_hitPointWorld().y(),z:n.get_m_hitPointWorld().z()}),i.calculateHitDistance()),this.bjsAMMO.destroy(n),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB)}}sv._DISABLE_COLLISION_FLAG=4,sv._KINEMATIC_FLAG=2,sv._DISABLE_DEACTIVATION_FLAG=4,n.p.prototype.removeReflectionProbe=function(e){if(!this.reflectionProbes)return-1;const t=this.reflectionProbes.indexOf(e);return-1!==t&&this.reflectionProbes.splice(t,1),t},n.p.prototype.addReflectionProbe=function(e){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(e)};class rv{constructor(e,t,i,n=!0,s=!1,r=!1){if(this.name=e,this._viewMatrix=o.y3.Identity(),this._target=o.P.Zero(),this._add=o.P.Zero(),this._invertYAxis=!1,this.position=o.P.Zero(),this.metadata=null,this._parentContainer=null,this._scene=i,i.getEngine().supportsUniformBuffers){this._sceneUBOs=[];for(let t=0;t<6;++t)this._sceneUBOs.push(i.createSceneUniformBuffer(`Scene for Reflection Probe (name "${e}") face #${t}`))}this._scene.reflectionProbes||(this._scene.reflectionProbes=new Array),this._scene.reflectionProbes.push(this);let a=0;if(s){const e=this._scene.getEngine().getCaps();e.textureHalfFloatRender?a=2:e.textureFloatRender&&(a=1)}this._renderTargetTexture=new Ci(e,t,i,n,!0,a,!0),this._renderTargetTexture.gammaSpace=!r,this._renderTargetTexture.invertZ=i.useRightHandedSystem;const l=i.getEngine().useReverseDepthBuffer;let h;this._renderTargetTexture.onBeforeRenderObservable.add((e=>{switch(this._sceneUBOs&&(i.setSceneUniformBuffer(this._sceneUBOs[e]),i.getSceneUniformBuffer().unbindEffect()),e){case 0:this._add.copyFromFloats(1,0,0);break;case 1:this._add.copyFromFloats(-1,0,0);break;case 2:this._add.copyFromFloats(0,this._invertYAxis?1:-1,0);break;case 3:this._add.copyFromFloats(0,this._invertYAxis?-1:1,0);break;case 4:this._add.copyFromFloats(0,0,i.useRightHandedSystem?-1:1);break;case 5:this._add.copyFromFloats(0,0,i.useRightHandedSystem?1:-1)}this._attachedMesh&&this.position.copyFrom(this._attachedMesh.getAbsolutePosition()),this.position.addToRef(this._add,this._target);const t=i.useRightHandedSystem?o.y3.LookAtRHToRef:o.y3.LookAtLHToRef,n=i.useRightHandedSystem?o.y3.PerspectiveFovRH:o.y3.PerspectiveFovLH;t(this.position,this._target,o.P.Up(),this._viewMatrix),i.activeCamera&&(this._projectionMatrix=n(Math.PI/2,1,l?i.activeCamera.maxZ:i.activeCamera.minZ,l?i.activeCamera.minZ:i.activeCamera.maxZ,this._scene.getEngine().isNDCHalfZRange),i.setTransformMatrix(this._viewMatrix,this._projectionMatrix),i.activeCamera.isRigCamera&&!this._renderTargetTexture.activeCamera&&(this._renderTargetTexture.activeCamera=i.activeCamera.rigParent||null)),i._forcedViewPosition=this.position})),this._renderTargetTexture.onBeforeBindObservable.add((()=>{var t,n;this._currentSceneUBO=i.getSceneUniformBuffer(),null===(n=(t=i.getEngine())._debugPushGroup)||void 0===n||n.call(t,`reflection probe generation for ${e}`,1),h=this._scene.imageProcessingConfiguration.applyByPostProcess,r&&(i.imageProcessingConfiguration.applyByPostProcess=!0)})),this._renderTargetTexture.onAfterUnbindObservable.add((()=>{var e,t;i.imageProcessingConfiguration.applyByPostProcess=h,i._forcedViewPosition=null,this._sceneUBOs&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(!0),null===(t=(e=i.getEngine())._debugPopGroup)||void 0===t||t.call(e,1)}))}get samples(){return this._renderTargetTexture.samples}set samples(e){this._renderTargetTexture.samples=e}get refreshRate(){return this._renderTargetTexture.refreshRate}set refreshRate(e){this._renderTargetTexture.refreshRate=e}getScene(){return this._scene}get cubeTexture(){return this._renderTargetTexture}get renderList(){return this._renderTargetTexture.renderList}attachToMesh(e){this._attachedMesh=e}setRenderingAutoClearDepthStencil(e,t){this._renderTargetTexture.setRenderingAutoClearDepthStencil(e,t)}dispose(){const e=this._scene.reflectionProbes.indexOf(this);if(-1!==e&&this._scene.reflectionProbes.splice(e,1),this._parentContainer){const e=this._parentContainer.reflectionProbes.indexOf(this);e>-1&&this._parentContainer.reflectionProbes.splice(e,1),this._parentContainer=null}if(this._renderTargetTexture&&(this._renderTargetTexture.dispose(),this._renderTargetTexture=null),this._sceneUBOs){for(const e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}toString(e){let t="Name: "+this.name;return e&&(t+=", position: "+this.position.toString(),this._attachedMesh&&(t+=", attached mesh: "+this._attachedMesh.name)),t}getClassName(){return"ReflectionProbe"}serialize(){const e=E.p4.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e.metadata=this.metadata,e}static Parse(e,t,i){let n=null;if(t.reflectionProbes)for(let s=0;sn||new rv(e.name,e.renderTargetSize,t,e._generateMipMaps)),e,t,i),n.cubeTexture._waitingRenderList=e.renderList,e._attachedMesh&&n.attachToMesh(t.getMeshById(e._attachedMesh)),e.metadata&&(n.metadata=e.metadata),n}}(0,oe.gn)([(0,E.RR)()],rv.prototype,"_attachedMesh",void 0),(0,oe.gn)([(0,E.hd)()],rv.prototype,"position",void 0);class ov{}ov.LoaderInjectedPhysicsEngine=void 0;let av={},lv={};const hv=(e,t,i,n)=>{if(!t.materials)return null;for(let s=0,r=t.materials.length;s{for(const n in t)if(e.name===t[n])return i.push(e.id),!0;return void 0!==e.parentId&&-1!==i.indexOf(e.parentId)&&(i.push(e.id),!0)},dv=(e,t)=>e+" of "+(t?t.file+" from "+t.name+" version: "+t.version+", exporter version: "+t.exporter_version:"unknown"),uv=(e,t)=>{const i=t;if(t._waitingData.lods){if(t._waitingData.lods.ids&&t._waitingData.lods.ids.length>0){const n=t._waitingData.lods.ids,s=i.isEnabled(!1);if(t._waitingData.lods.distances){const r=t._waitingData.lods.distances;if(r.length>=n.length){const t=r.length>n.length?r[r.length-1]:0;i.setEnabled(!1);for(let s=0;s0&&i.addLODLevel(t,null),!0===s&&i.setEnabled(!0)}else se.w1.Warn("Invalid level of detail distances for "+t.name)}}t._waitingData.lods=null}},pv=(e,t,i)=>{if("number"!=typeof e){const n=i.getLastEntryById(e);if(n&&null!=t){return n.instances[parseInt(t)]}return n}const n=av[e];if(n&&null!=t){return n.instances[parseInt(t)]}return n},fv=(e,t)=>"number"!=typeof e?t.getLastMaterialById(e,!0):lv[e],_v=(e,t,i,s,r=!1)=>{const o=new pe(e);let a="importScene has failed JSON parse";try{var h=JSON.parse(t);a="";const s=ht.loggingLevel===ht.DETAILED_LOGGING;let r,c;if(void 0!==h.environmentTexture&&null!==h.environmentTexture){const t=void 0===h.isPBR||h.isPBR;if(h.environmentTextureType&&"BABYLON.HDRCubeTexture"===h.environmentTextureType){const n=h.environmentTextureSize?h.environmentTextureSize:128,s=new $g((h.environmentTexture.match(/https?:\/\//g)?"":i)+h.environmentTexture,e,n,!0,!t,void 0,h.environmentTexturePrefilterOnLoad);h.environmentTextureRotationY&&(s.rotationY=h.environmentTextureRotationY),e.environmentTexture=s}else if("object"==typeof h.environmentTexture){const t=yp.Parse(h.environmentTexture,e,i);e.environmentTexture=t}else if(h.environmentTexture.endsWith(".env")){const t=new yp((h.environmentTexture.match(/https?:\/\//g)?"":i)+h.environmentTexture,e,h.environmentTextureForcedExtension);h.environmentTextureRotationY&&(t.rotationY=h.environmentTextureRotationY),e.environmentTexture=t}else{const t=yp.CreateFromPrefilteredData((h.environmentTexture.match(/https?:\/\//g)?"":i)+h.environmentTexture,e,h.environmentTextureForcedExtension);h.environmentTextureRotationY&&(t.rotationY=h.environmentTextureRotationY),e.environmentTexture=t}if(!0===h.createDefaultSkybox){const i=void 0!==e.activeCamera&&null!==e.activeCamera?(e.activeCamera.maxZ-e.activeCamera.minZ)/2:1e3,n=h.skyboxBlurLevel||0;e.createDefaultSkybox(e.environmentTexture,t,i,n)}o.environmentTexture=e.environmentTexture}if(void 0!==h.environmentIntensity&&null!==h.environmentIntensity&&(e.environmentIntensity=h.environmentIntensity),void 0!==h.lights&&null!==h.lights)for(r=0,c=h.lights.length;r{-1==o.textures.indexOf(e)&&(o.textures.push(e),e._parentContainer=o)}))}}if(void 0!==h.multiMaterials&&null!==h.multiMaterials)for(r=0,c=h.multiMaterials.length;r{-1==o.textures.indexOf(e)&&(o.textures.push(e),e._parentContainer=o)}))}if(void 0!==h.morphTargetManagers&&null!==h.morphTargetManagers)for(const t of h.morphTargetManagers){const i=Jg.Parse(t,e);o.morphTargetManagers.push(i),i._parentContainer=o}if(void 0!==h.skeletons&&null!==h.skeletons)for(r=0,c=h.skeletons.length;r{e&&(o.geometries.push(e),e._parentContainer=o)}))}if(void 0!==h.transformNodes&&null!==h.transformNodes)for(r=0,c=h.transformNodes.length;r{t._waitingSubMaterialsUniqueIds.forEach((i=>{t.subMaterials.push(fv(i,e))})),t._waitingSubMaterialsUniqueIds=[]})),e.meshes.forEach((t=>{null!==t._waitingMaterialId&&(t.material=fv(t._waitingMaterialId,e),t._waitingMaterialId=null)})),r=0,c=e.skeletons.length;r{if(t._waitingTransformNodeId){const i=e.getLastEntryById(t._waitingTransformNodeId);i&&t.linkTransformNode(i),t._waitingTransformNodeId=null}})),t._hasWaitingData=null)}for(r=0,c=e.meshes.length;r0){for(let i=0;i0){for(let i=0;i{e._loadedUniqueId=""})),n.p.Parse(h,e,o,i),r=0,c=e.meshes.length;r-1!==e.indexOf("babylon"),importMesh:(e,t,i,s,r,o,a,l)=>{var h;let c="importMesh has failed JSON parse";try{var d=JSON.parse(i);c="";const l=ht.loggingLevel===ht.DETAILED_LOGGING;e?Array.isArray(e)||(e=[e]):e=null;const u=new Array,f=new Map,_=[];if(void 0!==d.transformNodes&&null!==d.transformNodes)for(let e=0,i=d.transformNodes.length;e{!0!==e&&d.geometries[i]&&Array.isArray(d.geometries[i])&&d.geometries[i].forEach((n=>{if(n.id===_.geometryId){if("vertexData"===i)Gg.Z.Parse(n,t,s);e=!0}}))})),!1===e&&p.Y.Warn("Geometry not found for mesh "+_.id)}if(_.materialUniqueId||_.materialId){const e=_.materialUniqueId?o:n;let i=-1!==e.indexOf(_.materialUniqueId||_.materialId);if(!1===i&&void 0!==d.multiMaterials&&null!==d.multiMaterials){const n=(i,n)=>{e.push(i);const r=hv(n,d,t,s);r&&r.material&&(lv[r.parsedMaterial.uniqueId||r.parsedMaterial.id]=r.material,c+="\n\tMaterial "+r.material.toString(l))};for(let s=0,r=d.multiMaterials.length;sn(e,(t=>t.uniqueId===e)))):r.materials.forEach((e=>n(e,(t=>t.id===e)))),e.push(r.uniqueId||r.id);const s=zg.G.ParseMultiMaterial(r,t);lv[r.uniqueId||r.id]=s,s&&(i=!0,c+="\n\tMulti-Material "+s.toString(l));break}}}if(!1===i){e.push(_.materialUniqueId||_.materialId);const i=hv((e=>_.materialUniqueId&&e.uniqueId===_.materialUniqueId||e.id===_.materialId),d,t,s);i&&i.material?(lv[i.parsedMaterial.uniqueId||i.parsedMaterial.id]=i.material,c+="\n\tMaterial "+i.material.toString(l)):p.Y.Warn("Material not found for mesh "+_.id)}}if(_.skeletonId>-1&&void 0!==d.skeletons&&null!==d.skeletons){if(!(i.indexOf(_.skeletonId)>-1))for(let e=0,n=d.skeletons.length;e-1&&void 0!==d.morphTargetManagers&&null!==d.morphTargetManagers){if(!(m.indexOf(_.morphTargetManagerId)>-1))for(let e=0,i=d.morphTargetManagers.length;e{e._waitingSubMaterialsUniqueIds.forEach((i=>{e.subMaterials.push(fv(i,t))})),e._waitingSubMaterialsUniqueIds=[]})),t.meshes.forEach((e=>{null!==e._waitingMaterialId&&(e.material=fv(e._waitingMaterialId,t),e._waitingMaterialId=null)}));for(let e=0,s=t.transformNodes.length;e-1&&_.splice(e,1)}g._waitingParentId=null}g._waitingData.lods&&uv(t,g)}for(const e of _)e.dispose();for(let e=0,s=t.skeletons.length;e{if(e._waitingTransformNodeId){const i=t.getLastEntryById(e._waitingTransformNodeId);i&&e.linkTransformNode(i),e._waitingTransformNodeId=null}})),i._hasWaitingData=null)}for(let e=0,s=t.meshes.length;e{e._loadedUniqueId=""})),!0}catch(u){const e=dv("importMesh",d?d.producer:"Unknown")+c;if(!l)throw p.Y.Log(e),u;l(e,u)}finally{null!==c&&ht.loggingLevel!==ht.NO_LOGGING&&p.Y.Log(dv("importMesh",d?d.producer:"Unknown")+(ht.loggingLevel!==ht.MINIMAL_LOGGING?c:"")),lv={}}return!1},load:(e,t,i,n)=>{let s="importScene has failed JSON parse";try{var r=JSON.parse(t);if(s="",void 0!==r.useDelayedTextureLoading&&null!==r.useDelayedTextureLoading&&(e.useDelayedTextureLoading=r.useDelayedTextureLoading&&!ht.ForceFullSceneLoadingForIncremental),void 0!==r.autoClear&&null!==r.autoClear&&(e.autoClear=r.autoClear),void 0!==r.clearColor&&null!==r.clearColor&&(e.clearColor=a.HE.FromArray(r.clearColor)),void 0!==r.ambientColor&&null!==r.ambientColor&&(e.ambientColor=a.Wo.FromArray(r.ambientColor)),void 0!==r.gravity&&null!==r.gravity&&(e.gravity=o.P.FromArray(r.gravity)),void 0!==r.useRightHandedSystem&&(e.useRightHandedSystem=!!r.useRightHandedSystem),r.fogMode&&0!==r.fogMode)switch(e.fogMode=r.fogMode,e.fogColor=a.Wo.FromArray(r.fogColor),e.fogStart=r.fogStart,e.fogEnd=r.fogEnd,e.fogDensity=r.fogDensity,s+="\tFog mode for scene: ",e.fogMode){case 1:s+="exp\n";break;case 2:s+="exp2\n";break;case 3:s+="linear\n"}if(r.physicsEnabled){let t;"cannon"===r.physicsEngine||r.physicsEngine===iv.name?t=new iv(void 0,void 0,ov.LoaderInjectedPhysicsEngine):"oimo"===r.physicsEngine||r.physicsEngine===nv.name?t=new nv(void 0,ov.LoaderInjectedPhysicsEngine):"ammo"!==r.physicsEngine&&r.physicsEngine!==sv.name||(t=new sv(void 0,ov.LoaderInjectedPhysicsEngine,void 0)),s="\tPhysics engine "+(r.physicsEngine?r.physicsEngine:"oimo")+" enabled\n";const i=r.physicsGravity?o.P.FromArray(r.physicsGravity):null;e.enablePhysics(i,t)}void 0!==r.metadata&&null!==r.metadata&&(e.metadata=r.metadata),void 0!==r.collisionsEnabled&&null!==r.collisionsEnabled&&(e.collisionsEnabled=r.collisionsEnabled);return!!_v(e,t,i,n,!0)&&(r.autoAnimate&&e.beginAnimation(e,r.autoAnimateFrom,r.autoAnimateTo,r.autoAnimateLoop,r.autoAnimateSpeed||1),void 0!==r.activeCameraID&&null!==r.activeCameraID&&e.setActiveCameraById(r.activeCameraID),!0)}catch(l){const e=dv("importScene",r?r.producer:"Unknown")+s;if(!n)throw p.Y.Log(e),l;n(e,l)}finally{null!==s&&ht.loggingLevel!==ht.NO_LOGGING&&p.Y.Log(dv("importScene",r?r.producer:"Unknown")+(ht.loggingLevel!==ht.MINIMAL_LOGGING?s:""))}return!1},loadAssetContainer:(e,t,i,n)=>_v(e,t,i,n)});i(4839);class mv{get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,fe.D.MarkAllMaterialsAsDirty(20))}constructor(e={}){this._isEnabled=!0,this.bias=void 0===e.bias?0:e.bias,this.power=void 0===e.power?1:e.power,this.leftColor=e.leftColor||a.Wo.White(),this.rightColor=e.rightColor||a.Wo.Black(),!1===e.isEnabled&&(this.isEnabled=!1)}clone(){const e=new mv;return g.j.DeepCopy(this,e),e}equals(e){return e&&this.bias===e.bias&&this.power===e.power&&this.leftColor.equals(e.leftColor)&&this.rightColor.equals(e.rightColor)&&this.isEnabled===e.isEnabled}serialize(){return{isEnabled:this.isEnabled,leftColor:this.leftColor.asArray(),rightColor:this.rightColor.asArray(),bias:this.bias,power:this.power}}static Parse(e){return new mv({isEnabled:e.isEnabled,leftColor:a.Wo.FromArray(e.leftColor),rightColor:a.Wo.FromArray(e.rightColor),bias:e.bias,power:e.power||1})}}E.p4._FresnelParametersParser=mv.Parse;class gv extends M_{get doubleSided(){return this._twoSidedLighting}set doubleSided(e){this._twoSidedLighting!==e&&(this._twoSidedLighting=e,this.backFaceCulling=!e,this._markAllSubMeshesAsTexturesDirty())}constructor(e,t){super(e,t),this.maxSimultaneousLights=4,this.disableLighting=!1,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.emissiveColor=new a.Wo(0,0,0),this.occlusionStrength=1,this.useLightmapAsShadowmap=!1,this._useAlphaFromAlbedoTexture=!0,this._useAmbientInGrayScale=!0}getClassName(){return"PBRBaseSimpleMaterial"}}(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsLightsDirty")],gv.prototype,"maxSimultaneousLights",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsLightsDirty")],gv.prototype,"disableLighting",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],gv.prototype,"environmentTexture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],gv.prototype,"invertNormalMapX",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],gv.prototype,"invertNormalMapY",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],gv.prototype,"normalTexture",void 0),(0,oe.gn)([(0,E.n9)("emissive"),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],gv.prototype,"emissiveColor",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],gv.prototype,"emissiveTexture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],gv.prototype,"occlusionStrength",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],gv.prototype,"occlusionTexture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],gv.prototype,"alphaCutOff",void 0),(0,oe.gn)([(0,E.qC)()],gv.prototype,"doubleSided",null),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty",null)],gv.prototype,"lightmapTexture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],gv.prototype,"useLightmapAsShadowmap",void 0);class vv extends gv{constructor(e,t){super(e,t),this._useRoughnessFromMetallicTextureAlpha=!1,this._useRoughnessFromMetallicTextureGreen=!0,this._useMetallnessFromMetallicTextureBlue=!0,this.metallic=1,this.roughness=1}getClassName(){return"PBRMetallicRoughnessMaterial"}clone(e){const t=E.p4.Clone((()=>new vv(e,this.getScene())),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){const e=E.p4.Serialize(this);return e.customType="BABYLON.PBRMetallicRoughnessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const n=E.p4.Parse((()=>new vv(e.name,t)),e,t,i);return e.clearCoat&&n.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&n.anisotropy.parse(e.anisotropy,t,i),e.brdf&&n.brdf.parse(e.brdf,t,i),e.sheen&&n.sheen.parse(e.sheen,t,i),e.subSurface&&n.subSurface.parse(e.subSurface,t,i),e.iridescence&&n.iridescence.parse(e.iridescence,t,i),n}}(0,oe.gn)([(0,E.n9)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty","_albedoColor")],vv.prototype,"baseColor",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],vv.prototype,"baseTexture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],vv.prototype,"metallic",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],vv.prototype,"roughness",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],vv.prototype,"metallicRoughnessTexture",void 0),(0,l.H)("BABYLON.PBRMetallicRoughnessMaterial",vv);class Tv extends gv{get useMicroSurfaceFromReflectivityMapAlpha(){return this._useMicroSurfaceFromReflectivityMapAlpha}constructor(e,t){super(e,t),this._useMicroSurfaceFromReflectivityMapAlpha=!0}getClassName(){return"PBRSpecularGlossinessMaterial"}clone(e){const t=E.p4.Clone((()=>new Tv(e,this.getScene())),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){const e=E.p4.Serialize(this);return e.customType="BABYLON.PBRSpecularGlossinessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const n=E.p4.Parse((()=>new Tv(e.name,t)),e,t,i);return e.clearCoat&&n.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&n.anisotropy.parse(e.anisotropy,t,i),e.brdf&&n.brdf.parse(e.brdf,t,i),e.sheen&&n.sheen.parse(e.sheen,t,i),e.subSurface&&n.subSurface.parse(e.subSurface,t,i),e.iridescence&&n.iridescence.parse(e.iridescence,t,i),n}}(0,oe.gn)([(0,E.n9)("diffuse"),(0,E.wz)("_markAllSubMeshesAsTexturesDirty","_albedoColor")],Tv.prototype,"diffuseColor",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],Tv.prototype,"diffuseTexture",void 0),(0,oe.gn)([(0,E.n9)("specular"),(0,E.wz)("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],Tv.prototype,"specularColor",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty","_microSurface")],Tv.prototype,"glossiness",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],Tv.prototype,"specularGlossinessTexture",void 0),(0,l.H)("BABYLON.PBRSpecularGlossinessMaterial",Tv);class Sv extends Re{constructor(e,t,i=null){if(super(t),e)if(this._textureMatrix=o.y3.Identity(),this.name=e,this.url=e,this._onLoad=i,this._texture=this._getFromCache(e,!0),this._texture)this._triggerOnLoad();else{const e=this.getScene();e&&e.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture()}}_triggerOnLoad(){this._onLoad&&this._onLoad()}getTextureMatrix(){return this._textureMatrix}_load3dlTexture(){const e=this._getEngine();let t;t=e._features.support3DTextures?e.createRawTexture3D(null,1,1,1,5,!1,!1,2,null,0):e.createRawTexture(null,1,1,5,!1,!1,2,null,0),this._texture=t,this._texture.isReady=!1,this.isCube=!1,this.is3D=e._features.support3DTextures,this.wrapU=0,this.wrapV=0,this.wrapR=0,this.anisotropicFilteringLevel=1;const i=i=>{if("string"!=typeof i)return;let n,s=null,r=null;const o=i.split("\n");let a=0,l=0,h=0,c=0,d=0;for(let e=0;e0&&(e+1)%4==0)s[e]=255;else{const t=r[e];s[e]=t/d*255}t.is3D?(t.updateSize(a,a,a),e.updateRawTexture3D(t,s,5,!1)):(t.updateSize(a*a,a),e.updateRawTexture(t,s,5,!1)),t.isReady=!0,this._triggerOnLoad()},n=this.getScene();return n?n._loadFile(this.url,i):e._loadFile(this.url,i),this._texture}_loadTexture(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this._load3dlTexture()}clone(){const e=new Sv(this.url,this.getScene()||this._getEngine());return e.level=this.level,e}delayLoad(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,!0),this._texture||this._loadTexture())}static Parse(e,t){let i=null;return e.name&&!e.isRenderTarget&&(i=new Sv(e.name,t),i.name=e.name,i.level=e.level),i}serialize(){if(!this.name)return null;const e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e}}Sv._NoneEmptyLineRegex=/\S+/,(0,l.H)("BABYLON.ColorGradingTexture",Sv);class Ev extends Re{constructor(e,t,i,n=!1,s=!0,r=null,o=null,a=!1){if(super(t),this._onLoad=null,this._onError=null,!e)throw new Error("Image url is not set");this._coordinatesMode=Le.CUBIC_MODE,this.name=e,this.url=e,this._size=i,this._supersample=a,this._noMipmap=n,this.gammaSpace=s,this._onLoad=r,this._onError=o,this.hasAlpha=!1,this.isCube=!0,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?r&&(this._texture.isReady?se.w1.SetImmediate((()=>r())):this._texture.onLoadedObservable.add(r)):t.useDelayedTextureLoading?this.delayLoadState=4:this._loadImage(this._loadTexture.bind(this),this._onError)}_loadImage(e,t){const i=document.createElement("canvas");(0,ye.r6)(this.url,(t=>{this._width=t.width,this._height=t.height,i.width=this._width,i.height=this._height;const n=i.getContext("2d");n.drawImage(t,0,0);const s=n.getImageData(0,0,t.width,t.height);this._buffer=s.data.buffer,i.remove(),e()}),((e,i)=>{t&&t(`${this.getClassName()} could not be loaded`,i)}),null)}_loadTexture(){const e=this.getScene();e&&(this._texture=e.getEngine().createRawCubeTextureFromUrl(this.url,e,this._size,4,e.getEngine().getCaps().textureFloat?1:7,this._noMipmap,(()=>{const e=this._getFloat32ArrayFromArrayBuffer(this._buffer),t=Wg.ConvertPanoramaToCubemap(e,this._width,this._height,this._size,this._supersample),i=[];for(let n=0;n<6;n++){const e=t[Ev._FacesMapping[n]];i.push(e)}return i}),null,this._onLoad,this._onError))}_getFloat32ArrayFromArrayBuffer(e){const t=new DataView(e),i=new Float32Array(3*e.byteLength/4);let n=0;for(let s=0;st.length)return void p.Y.Error("Unable to load TGA file - Not enough data");i+=n.id_length;let s,r=!1,o=!1,a=!1;switch(n.image_type){case 9:r=!0;case 1:o=!0;break;case 10:r=!0;case 2:break;case 11:r=!0;case 3:a=!0}const l=n.pixel_size>>3,h=n.width*n.height*l;let c,d,u,f,_,m,g;if(o&&(c=t.subarray(i,i+=n.colormap_length*(n.colormap_size>>3))),r){let e,n,r;s=new Uint8Array(h);let o=0;const a=new Uint8Array(l);for(;i>4){default:case 2:d=0,f=1,g=n.width,u=0,_=1,m=n.height;break;case 0:d=0,f=1,g=n.width,u=n.height-1,_=-1,m=-1;break;case 3:d=n.width-1,f=-1,g=-1,u=0,_=1,m=n.height;break;case 1:d=n.width-1,f=-1,g=-1,u=n.height-1,_=-1,m=-1}const v="_getImageData"+(a?"Grey":"")+n.pixel_size+"bits",T=yv[v](n,c,s,u,_,m,d,f,g);e.getEngine()._uploadDataToTextureDirectly(e,T)}const yv={GetTGAHeader:bv,UploadContent:Cv,_getImageData8bits:function(e,t,i,n,s,r,o,a,l){const h=i,c=t,d=e.width,u=e.height;let p,f,_,m=0;const g=new Uint8Array(d*u*4);for(_=n;_!==r;_+=s)for(f=o;f!==l;f+=a,m++)p=h[m],g[4*(f+d*_)+3]=255,g[4*(f+d*_)+2]=c[3*p+0],g[4*(f+d*_)+1]=c[3*p+1],g[4*(f+d*_)+0]=c[3*p+2];return g},_getImageData16bits:function(e,t,i,n,s,r,o,a,l){const h=i,c=e.width,d=e.height;let u,p,f,_=0;const m=new Uint8Array(c*d*4);for(f=n;f!==r;f+=s)for(p=o;p!==l;p+=a,_+=2){u=h[_+0]+(h[_+1]<<8);const e=255*((31744&u)>>10)/31|0,t=255*((992&u)>>5)/31|0,i=255*(31&u)/31|0;m[4*(p+c*f)+0]=e,m[4*(p+c*f)+1]=t,m[4*(p+c*f)+2]=i,m[4*(p+c*f)+3]=32768&u?0:255}return m},_getImageData24bits:function(e,t,i,n,s,r,o,a,l){const h=i,c=e.width,d=e.height;let u,p,f=0;const _=new Uint8Array(c*d*4);for(p=n;p!==r;p+=s)for(u=o;u!==l;u+=a,f+=3)_[4*(u+c*p)+3]=255,_[4*(u+c*p)+2]=h[f+0],_[4*(u+c*p)+1]=h[f+1],_[4*(u+c*p)+0]=h[f+2];return _},_getImageData32bits:function(e,t,i,n,s,r,o,a,l){const h=i,c=e.width,d=e.height;let u,p,f=0;const _=new Uint8Array(c*d*4);for(p=n;p!==r;p+=s)for(u=o;u!==l;u+=a,f+=4)_[4*(u+c*p)+2]=h[f+0],_[4*(u+c*p)+1]=h[f+1],_[4*(u+c*p)+0]=h[f+2],_[4*(u+c*p)+3]=h[f+3];return _},_getImageDataGrey8bits:function(e,t,i,n,s,r,o,a,l){const h=i,c=e.width,d=e.height;let u,p,f,_=0;const m=new Uint8Array(c*d*4);for(f=n;f!==r;f+=s)for(p=o;p!==l;p+=a,_++)u=h[_],m[4*(p+c*f)+0]=u,m[4*(p+c*f)+1]=u,m[4*(p+c*f)+2]=u,m[4*(p+c*f)+3]=255;return m},_getImageDataGrey16bits:function(e,t,i,n,s,r,o,a,l){const h=i,c=e.width,d=e.height;let u,p,f=0;const _=new Uint8Array(c*d*4);for(p=n;p!==r;p+=s)for(u=o;u!==l;u+=a,f+=2)_[4*(u+c*p)+0]=h[f+0],_[4*(u+c*p)+1]=h[f+0],_[4*(u+c*p)+2]=h[f+0],_[4*(u+c*p)+3]=h[f+1];return _}};fe.D._TextureLoaders.push(new class{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".tga")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=bv(n);i(s.width,s.height,t.generateMipMaps,!1,(()=>{Cv(t,n)}))}});fe.D._TextureLoaders.push(new class{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".hdr")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=Hg.RGBE_ReadHeader(n),r=Hg.RGBE_ReadPixels(n,s),o=s.width*s.height,a=new Float32Array(4*o);for(let l=0;l{const e=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,e._uploadDataToTextureDirectly(t,a)}))}});var Av;!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"}(Av||(Av={}));const Rv={JSModuleURL:"https://cdn.babylonjs.com/basisTranscoder/1/basis_transcoder.js",WasmModuleURL:"https://cdn.babylonjs.com/basisTranscoder/1/basis_transcoder.wasm"};let Pv=null,Iv=null,Mv=0;const Ov=(e,t)=>{const i=e instanceof ArrayBuffer?new Uint8Array(e):e;return new Promise(((e,n)=>{(Pv||(Pv=new Promise(((e,t)=>{Iv?e(Iv):se.w1.LoadFileAsync(Rv.WasmModuleURL).then((i=>{if("function"!=typeof URL)return t("Basis transcoder requires an environment with a URL constructor");const n=URL.createObjectURL(new Blob([`(${wv})()`],{type:"application/javascript"}));Iv=new Worker(n);const s=i=>{"init"===i.data.action?(Iv.removeEventListener("message",s),e(Iv)):"error"===i.data.action&&t(i.data.error||"error initializing worker")};Iv.addEventListener("message",s),Iv.postMessage({action:"init",url:Rv.JSModuleURL,wasmBinary:i})})).catch(t)}))),Pv).then((()=>{const s=Mv++,r=t=>{"transcode"===t.data.action&&t.data.id===s&&(Iv.removeEventListener("message",r),t.data.success?e(t.data):n("Transcode is not supported on this device"))};Iv.addEventListener("message",r);const o=new Uint8Array(i.byteLength);o.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),Iv.postMessage({action:"transcode",id:s,imageData:o,config:t,ignoreSupportedFormats:false},[o.buffer])}),(e=>{n(e)}))}))},Dv=(e,t)=>{var i,n;let s=null===(i=t._gl)||void 0===i?void 0:i.TEXTURE_2D;e.isCube&&(s=null===(n=t._gl)||void 0===n?void 0:n.TEXTURE_CUBE_MAP),t._bindTextureDirectly(s,e,!0)},Nv=(e,t)=>{const i=e.getEngine();for(let n=0;n{i._releaseTexture(t),Dv(e,i)}))}else{e.width=s.width,e.height=s.height,e.generateMipMaps=t.fileInfo.images[n].levels.length>1;const r=Fv.GetInternalFormatFromBasisFormat(t.format,i);e.format=r,Dv(e,i),t.fileInfo.images[n].levels.forEach(((t,s)=>{i._uploadCompressedDataToTextureDirectly(e,r,t.width,t.height,t.transcodedPixels,n,s)})),!i._features.basisNeedsPOT||S.R.Log2(e.width)%1==0&&S.R.Log2(e.height)%1==0||(se.w1.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=Le.CLAMP_ADDRESSMODE,e._cachedWrapV=Le.CLAMP_ADDRESSMODE)}}},Fv={JSModuleURL:Rv.JSModuleURL,WasmModuleURL:Rv.WasmModuleURL,GetInternalFormatFromBasisFormat:(e,t)=>{let i;switch(e){case Av.cTFETC1:i=36196;break;case Av.cTFBC1:i=33776;break;case Av.cTFBC4:i=33779;break;case Av.cTFASTC_4x4:i=37808;break;case Av.cTFETC2:i=37496;break;case Av.cTFBC7:i=36492}if(void 0===i)throw"The chosen Basis transcoder format is not currently supported";return i},TranscodeAsync:Ov,LoadTextureFromTranscodeResult:Nv};function wv(){const e=0,t=1,i=2,n=3,s=6,r=8,o=9,a=10,l=14;let h=null;function c(e,t,i,n,s){const r=e.getImageTranscodedSizeInBytes(t,i,n);let o=new Uint8Array(r);if(!e.transcodeImage(o,t,i,n,1,0))return null;if(s){o=function(e,t,i,n){const s=new Uint16Array(4),r=new Uint16Array(i*n),o=i/4,a=n/4;for(let l=0;l>2&3],r[h++]=s[o>>4&3],r[h++]=s[o>>6&3]}}return r}(o,0,e.getImageWidth(t,i)+3&-4,e.getImageHeight(t,i)+3&-4)}return o}onmessage=d=>{if("init"===d.data.action){if(!h){try{importScripts(d.data.url)}catch(u){postMessage({action:"error",error:u})}h=BASIS({wasmBinary:d.data.wasmBinary})}null!==h&&h.then((e=>{BASIS=e,e.initializeBasis(),postMessage({action:"init"})}))}else if("transcode"===d.data.action){const h=d.data.config,u=d.data.imageData,p=new BASIS.BasisFile(u),f=function(e){const t=e.getHasAlpha(),i=e.getNumImages(),n=[];for(let s=0;s{const i=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;Nv(t,e),t.getEngine()._setCubeMapTextureParams(t,i),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n()})).catch((e=>{se.w1.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),t.isReady=!0,s&&s(e)}))}loadData(e,t,i){const n=t.getEngine().getCaps(),s={supportedCompressionFormats:{etc1:!!n.etc1,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,astc:!!n.astc,bc7:!!n.bptc}};Ov(e,s).then((e=>{const n=e.fileInfo.images[0].levels[0],s=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(n.width,n.height,s,-1!==e.format,(()=>{Nv(t,e)}))})).catch((e=>{se.w1.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),se.w1.Warn(`Failed to transcode Basis file: ${e}`),i(0,0,!1,!1,(()=>{}),!0)}))}});class Lv extends Ci{get isSupported(){var e,t;return null!==(t=null===(e=this._engine)||void 0===e?void 0:e.getCaps().drawBuffersExtension)&&void 0!==t&&t}get textures(){return this._textures}get count(){return this._count}get depthTexture(){return this._textures[this._textures.length-1]}set wrapU(e){if(this._textures)for(let t=0;t0&&(this._createInternalTextures(),this._createTextures(r))}_initTypes(e,t,i,n,s,r,o,a,l,h){for(let c=0;c{this.onAfterRenderObservable.notifyObservers(t)}))}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){var e,t;const i=null===(e=this._renderTarget)||void 0===e?void 0:e.textures;if(i){for(let e=i.length-1;e>=0;e--)this._textures[e]._texture=null;null===(t=this._renderTarget)||void 0===t||t.dispose(),this._renderTarget=null}}}class Bv{constructor(e,t,i){this.id=e,this.scale=t,this.offset=i}}class Uv{constructor(e,t,i,n){var s,r,o,l,h,c,d,u,p,f,_,m,g;return this.name=e,this.meshes=t,this.scene=n,this.options=i,this.options.map=null!==(s=this.options.map)&&void 0!==s?s:["ambientTexture","bumpTexture","diffuseTexture","emissiveTexture","lightmapTexture","opacityTexture","reflectionTexture","refractionTexture","specularTexture"],this.options.uvsIn=null!==(r=this.options.uvsIn)&&void 0!==r?r:ne.o.UVKind,this.options.uvsOut=null!==(o=this.options.uvsOut)&&void 0!==o?o:ne.o.UVKind,this.options.layout=null!==(l=this.options.layout)&&void 0!==l?l:Uv.LAYOUT_STRIP,this.options.layout===Uv.LAYOUT_COLNUM&&(this.options.colnum=null!==(h=this.options.colnum)&&void 0!==h?h:8),this.options.updateInputMeshes=null===(c=this.options.updateInputMeshes)||void 0===c||c,this.options.disposeSources=null===(d=this.options.disposeSources)||void 0===d||d,this._expecting=0,this.options.fillBlanks=null===(u=this.options.fillBlanks)||void 0===u||u,!0===this.options.fillBlanks&&(this.options.customFillColor=null!==(p=this.options.customFillColor)&&void 0!==p?p:"black"),this.options.frameSize=null!==(f=this.options.frameSize)&&void 0!==f?f:256,this.options.paddingRatio=null!==(_=this.options.paddingRatio)&&void 0!==_?_:.0115,this._paddingValue=Math.ceil(this.options.frameSize*this.options.paddingRatio),this._paddingValue%2!=0&&this._paddingValue++,this.options.paddingMode=null!==(m=this.options.paddingMode)&&void 0!==m?m:Uv.SUBUV_WRAP,this.options.paddingMode===Uv.SUBUV_COLOR&&(this.options.paddingColor=null!==(g=this.options.paddingColor)&&void 0!==g?g:new a.HE(0,0,0,1)),this.sets={},this.frames=[],this}_createFrames(e){const t=this._calculateSize(),i=new o.FM(1,1).divide(t);let n=0;const s=this._expecting,r=this.meshes.length,l=Object.keys(this.sets);for(let o=0;o{this._calculateMeshUVFrames(h,c,t,i,this.options.updateInputMeshes||!1)};for(let o=0;o{n++,p.update(!1);const i=f.getImageData(0,0,d,d),r=this.sets[g];if(r.getContext().putImageData(i,t.x*_.x,t.y*_.y),p.dispose(),r.update(!1),n==s)return u(),void e()},g=l[r]||"_blank";if(i&&null!==i[g]){const e=i[g],t=new Image;t.src=e instanceof ma?e.getContext().canvas.toDataURL("image/png"):e.url,se.w1.SetCorsBehavior(t.src,t),t.onload=()=>{f.fillStyle="rgba(0,0,0,0)",f.fillRect(0,0,d,d),p.update(!1),f.setTransform(1,0,0,-1,0,0);const e=[0,0,1,0,1,1,0,1,-1,1,-1,0,-2,0,-1,1,-1];switch(this.options.paddingMode){case 0:for(let i=0;i<9;i++)f.drawImage(t,0,0,t.width,t.height,c+h*e[i],c+h*e[i+1]-d,h,h);break;case 1:for(let i=0;i{e.dispose&&e.dispose()};for(let r=0;r{try{if(0===this.meshes.length)return void e();let t=0;const i=i=>{if(t++,this.options.map){for(let e=0;e{i(r)}));else if(t++,t===this.meshes.length)return this._createFrames(e)}}catch(i){return t(i)}}))}dispose(){const e=Object.keys(this.sets);for(let t=0;t{const i={name:this.name,sets:{},options:{},frames:[]},n=Object.keys(this.sets),s=Object.keys(this.options);try{for(let s=0;se));return e.onRebuildCallback=e=>({proxy:r,isReady:!0,isAsync:!0}),e._source=Be.S.CubeRawRGBD,e._bufferViewArrayArray=t,e._lodGenerationScale=n,e._lodGenerationOffset=s,e._sphericalPolynomial=i,Jh(e,t).then((()=>(e.isReady=!0,e)))}(this._texture,e,t,i,n).then((()=>{}))}clone(){return E.p4.Clone((()=>{const e=this.getScene(),t=this._texture,i=new zv(e,t._bufferViewArray,t.width,t.format,t.type,t.generateMipMaps,t.invertY,t.samplingMode,t._compression);return t.source===Be.S.CubeRawRGBD&&i.updateRGBDAsync(t._bufferViewArrayArray,t._sphericalPolynomial,t._lodGenerationScale,t._lodGenerationOffset),i}),this)}}class Wv extends St{constructor(e,t,i,n,s){super(e,t,i),this._blockType=n,this._blockName=s,this.needDualDirectionValidation=!0}checkCompatibilityState(e){return e instanceof Wv&&e._blockName===this._blockName?gt.Compatible:gt.TypeIncompatible}createCustomInputBlock(){return[new this._blockType(this._blockName),this.name]}}(0,l.H)("BABYLON.BonesBlock",class extends bt{constructor(e){super(e,dt.Vertex),this.registerInput("matricesIndices",ct.Vector4),this.registerInput("matricesWeights",ct.Vector4),this.registerInput("matricesIndicesExtra",ct.Vector4,!0),this.registerInput("matricesWeightsExtra",ct.Vector4,!0),this.registerInput("world",ct.Matrix),this.registerOutput("output",ct.Matrix)}initialize(e){e._excludeVariableName("boneSampler"),e._excludeVariableName("boneTextureWidth"),e._excludeVariableName("mBones"),e._excludeVariableName("BonesPerMesh")}getClassName(){return"BonesBlock"}get matricesIndices(){return this._inputs[0]}get matricesWeights(){return this._inputs[1]}get matricesIndicesExtra(){return this._inputs[2]}get matricesWeightsExtra(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}autoConfigure(e){if(!this.matricesIndices.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"matricesIndices"===e.name));t||(t=new Bt("matricesIndices"),t.setAsAttribute("matricesIndices")),t.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"matricesWeights"===e.name));t||(t=new Bt("matricesWeights"),t.setAsAttribute("matricesWeights")),t.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===Pt.World));t||(t=new Bt("world"),t.setAsSystemValue(Pt.World)),t.output.connectTo(this.world)}}provideFallbacks(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)}bind(e,t,i){It.G.BindBonesParameters(i,e)}prepareDefines(e,t,i){i._areAttributesDirty&&It.G.PrepareDefinesForBones(e,i)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithFallbacks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.uniforms.push("boneTextureWidth"),e.uniforms.push("mBones"),e.samplers.push("boneSampler");const t=`//${this.name}`;e._emitFunctionFromInclude("bonesDeclaration",t,{removeAttributes:!0,removeUniforms:!1,removeVaryings:!0,removeIfDef:!1});const i=e._getFreeVariableName("influence");e.compilationString+=e._emitCodeFromInclude("bonesVertex",t,{replaceStrings:[{search:/finalWorld=finalWorld\*influence;/,replace:""},{search:/influence/gm,replace:i}]});const n=this._outputs[0],s=this.world;return e.compilationString+="#if NUM_BONE_INFLUENCERS>0\r\n",e.compilationString+=this._declareOutput(n,e)+` = ${s.associatedVariableName} * ${i};\r\n`,e.compilationString+="#else\r\n",e.compilationString+=this._declareOutput(n,e)+` = ${s.associatedVariableName};\r\n`,e.compilationString+="#endif\r\n",this}});(0,l.H)("BABYLON.InstancesBlock",class extends bt{constructor(e){super(e,dt.Vertex),this.registerInput("world0",ct.Vector4),this.registerInput("world1",ct.Vector4),this.registerInput("world2",ct.Vector4),this.registerInput("world3",ct.Vector4),this.registerInput("world",ct.Matrix,!0),this.registerOutput("output",ct.Matrix),this.registerOutput("instanceID",ct.Float)}getClassName(){return"InstancesBlock"}get world0(){return this._inputs[0]}get world1(){return this._inputs[1]}get world2(){return this._inputs[2]}get world3(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}get instanceID(){return this._outputs[1]}autoConfigure(e){if(!this.world0.connectedPoint){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"world0"===e.name));t||(t=new Bt("world0"),t.setAsAttribute("world0")),t.output.connectTo(this.world0)}if(!this.world1.connectedPoint){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"world1"===e.name));t||(t=new Bt("world1"),t.setAsAttribute("world1")),t.output.connectTo(this.world1)}if(!this.world2.connectedPoint){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"world2"===e.name));t||(t=new Bt("world2"),t.setAsAttribute("world2")),t.output.connectTo(this.world2)}if(!this.world3.connectedPoint){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"world3"===e.name));t||(t=new Bt("world3"),t.setAsAttribute("world3")),t.output.connectTo(this.world3)}if(!this.world.connectedPoint){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"world"===e.name));t||(t=new Bt("world"),t.setAsSystemValue(Pt.World)),t.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"}prepareDefines(e,t,i,n=!1,s){let r=!1;i.INSTANCES!==n&&(i.setValue("INSTANCES",n),r=!0),s&&i.THIN_INSTANCES!==!!(null==s?void 0:s.getRenderingMesh().hasThinInstances)&&(i.setValue("THIN_INSTANCES",!!(null==s?void 0:s.getRenderingMesh().hasThinInstances)),r=!0),r&&i.markAsUnprocessed()}_buildBlock(e){super._buildBlock(e);const t=e.sharedData.scene.getEngine();e.sharedData.blocksWithDefines.push(this);const i=this._outputs[0],n=this._outputs[1],s=this.world0,r=this.world1,o=this.world2,a=this.world3;return e.compilationString+="#ifdef INSTANCES\r\n",e.compilationString+=this._declareOutput(i,e)+` = mat4(${s.associatedVariableName}, ${r.associatedVariableName}, ${o.associatedVariableName}, ${a.associatedVariableName});\r\n`,e.compilationString+="#ifdef THIN_INSTANCES\r\n",e.compilationString+=`${i.associatedVariableName} = ${this.world.associatedVariableName} * ${i.associatedVariableName};\r\n`,e.compilationString+="#endif\r\n",t._caps.canUseGLInstanceID?e.compilationString+=this._declareOutput(n,e)+" = float(gl_InstanceID);\r\n":e.compilationString+=this._declareOutput(n,e)+" = 0.0;\r\n",e.compilationString+="#else\r\n",e.compilationString+=this._declareOutput(i,e)+` = ${this.world.associatedVariableName};\r\n`,e.compilationString+=this._declareOutput(n,e)+" = 0.0;\r\n",e.compilationString+="#endif\r\n",this}});class Hv extends bt{constructor(e){super(e,dt.Vertex),this.registerInput("position",ct.Vector3),this.registerInput("normal",ct.Vector3),this.registerInput("tangent",ct.AutoDetect),this.tangent.addExcludedConnectionPointFromAllowedTypes(ct.Color4|ct.Vector4|ct.Vector3),this.registerInput("uv",ct.Vector2),this.registerOutput("positionOutput",ct.Vector3),this.registerOutput("normalOutput",ct.Vector3),this.registerOutput("tangentOutput",ct.Vector4),this.registerOutput("uvOutput",ct.Vector2)}getClassName(){return"MorphTargetsBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get tangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get positionOutput(){return this._outputs[0]}get normalOutput(){return this._outputs[1]}get tangentOutput(){return this._outputs[2]}get uvOutput(){return this._outputs[3]}initialize(e){e._excludeVariableName("morphTargetInfluences")}autoConfigure(e){if(!this.position.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"position"===e.name));t||(t=new Bt("position"),t.setAsAttribute()),t.output.connectTo(this.position)}if(!this.normal.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"normal"===e.name));t||(t=new Bt("normal"),t.setAsAttribute("normal")),t.output.connectTo(this.normal)}if(!this.tangent.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"tangent"===e.name));t||(t=new Bt("tangent"),t.setAsAttribute("tangent")),t.output.connectTo(this.tangent)}if(!this.uv.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"uv"===e.name));t||(t=new Bt("uv"),t.setAsAttribute("uv")),t.output.connectTo(this.uv)}}prepareDefines(e,t,i){if(e.morphTargetManager){const t=e.morphTargetManager;(null==t?void 0:t.isUsingTextureForTargets)&&t.numInfluencers!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}i._areAttributesDirty&&It.G.PrepareDefinesForMorphTargets(e,i)}bind(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&(It.G.BindMorphTargetParameters(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))}replaceRepeatableContent(e,t,i,n){const s=this.position,r=this.normal,o=this.tangent,a=this.uv,l=this.positionOutput,h=this.normalOutput,c=this.tangentOutput,d=this.uvOutput,u=e,p=n.NUM_MORPH_INFLUENCERS,f=i.morphTargetManager,_=f&&f.supportsNormals&&n.NORMAL,m=f&&f.supportsTangents&&n.TANGENT,g=f&&f.supportsUVs&&n.UV1;let v="";(null==f?void 0:f.isUsingTextureForTargets)&&p>0&&(v+="float vertexID;\r\n");for(let T=0;T0)for(let T=0;Te.isSystemValue&&e.systemValue===Pt.World));t||(t=new Bt("world"),t.setAsSystemValue(Pt.World)),t.output.connectTo(this.world)}if(!this.normal.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"normal"===e.name));t||(t=new Bt("normal"),t.setAsAttribute("normal")),t.output.connectTo(this.normal)}if(!this.tangent.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"tangent"===e.name&&e.type===ct.Vector4));t||(t=new Bt("tangent"),t.setAsAttribute("tangent")),t.output.connectTo(this.tangent)}}prepareDefines(e,t,i){var n,s,r,o;const a=this.normal,l=this.tangent;let h=a.isConnected;(null===(n=a.connectInputBlock)||void 0===n?void 0:n.isAttribute)&&!e.isVerticesDataPresent(null===(s=a.connectInputBlock)||void 0===s?void 0:s.name)&&(h=!1);let c=l.isConnected;(null===(r=l.connectInputBlock)||void 0===r?void 0:r.isAttribute)&&!e.isVerticesDataPresent(null===(o=l.connectInputBlock)||void 0===o?void 0:o.name)&&(c=!1);const d=h&&c;i.setValue("TBNBLOCK",d,!0)}_buildBlock(e){super._buildBlock(e);const t=this.normal,i=this.tangent,n=this.world,s=this.TBN,r=this.row0,o=this.row1,a=this.row2;return e.target===dt.Fragment&&(e.compilationString+=`\n // ${this.name}\n vec3 tbnNormal = normalize(${t.associatedVariableName}).xyz;\n vec3 tbnTangent = normalize(${i.associatedVariableName}.xyz);\n vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${i.associatedVariableName}.w;\n mat3 ${s.associatedVariableName} = mat3(${n.associatedVariableName}) * mat3(tbnTangent, tbnBitangent, tbnNormal);\n `,r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = vec3(${s.associatedVariableName}[0][0], ${s.associatedVariableName}[0][1], ${s.associatedVariableName}[0][2]);\r\n`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = vec3(${s.associatedVariableName}[1[0], ${s.associatedVariableName}[1][1], ${s.associatedVariableName}[1][2]);\r\n`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = vec3(${s.associatedVariableName}[2][0], ${s.associatedVariableName}[2][1], ${s.associatedVariableName}[2][2]);\r\n`),e.sharedData.blocksWithDefines.push(this)),this}}(0,l.H)("BABYLON.TBNBlock",Yv);class jv extends bt{constructor(e){super(e,dt.Fragment),this._tangentSpaceParameterName="",this._tangentCorrectionFactorName="",this._worldMatrixName="",this.invertX=!1,this.invertY=!1,this.useParallaxOcclusion=!1,this.useObjectSpaceNormalMap=!1,this._isUnique=!0,this.registerInput("worldPosition",ct.Vector4,!1),this.registerInput("worldNormal",ct.Vector4,!1),this.registerInput("worldTangent",ct.Vector4,!0),this.registerInput("uv",ct.Vector2,!1),this.registerInput("normalMapColor",ct.Color3,!1),this.registerInput("strength",ct.Float,!1),this.registerInput("viewDirection",ct.Vector3,!0),this.registerInput("parallaxScale",ct.Float,!0),this.registerInput("parallaxHeight",ct.Float,!0),this.registerInput("TBN",ct.Object,!0,dt.VertexAndFragment,new Wv("TBN",this,vt.Input,Yv,"TBNBlock")),this.registerInput("world",ct.Matrix,!0),this.registerOutput("output",ct.Vector4),this.registerOutput("uvOffset",ct.Vector2)}getClassName(){return"PerturbNormalBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get worldTangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get normalMapColor(){return this._inputs[4]}get strength(){return this._inputs[5]}get viewDirection(){return this._inputs[6]}get parallaxScale(){return this._inputs[7]}get parallaxHeight(){return this._inputs[8]}get TBN(){return this._inputs[9]}get world(){return this._inputs[10]}get output(){return this._outputs[0]}get uvOffset(){return this._outputs[1]}prepareDefines(e,t,i){const n=this.normalMapColor.connectedPoint._ownerBlock.samplerName,s=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&n||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected);i.setValue("BUMP",!0),i.setValue("PARALLAX",s,!0),i.setValue("PARALLAXOCCLUSION",this.useParallaxOcclusion,!0),i.setValue("OBJECTSPACE_NORMALMAP",this.useObjectSpaceNormalMap,!0)}bind(e,t,i){t.getScene()._mirroredCameraPosition?e.setFloat2(this._tangentSpaceParameterName,this.invertX?1:-1,this.invertY?1:-1):e.setFloat2(this._tangentSpaceParameterName,this.invertX?-1:1,this.invertY?-1:1),i&&(e.setFloat(this._tangentCorrectionFactorName,i.getWorldMatrix().determinant()<0?-1:1),this.useObjectSpaceNormalMap&&!this.world.isConnected&&e.setMatrix(this._worldMatrixName,i.getWorldMatrix()))}autoConfigure(e){if(!this.uv.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"uv"===e.name));t||(t=new Bt("uv"),t.setAsAttribute()),t.output.connectTo(this.uv)}if(!this.strength.isConnected){const e=new Bt("strength");e.value=1,e.output.connectTo(this.strength)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`,i=this.uv,n=this.worldPosition,s=this.worldNormal,r=this.worldTangent;e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentSpaceParameterName=e._getFreeDefineName("tangentSpaceParameter"),e._emitUniformFromString(this._tangentSpaceParameterName,"vec2"),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float"),this._worldMatrixName=e._getFreeDefineName("perturbNormalWorldMatrix"),e._emitUniformFromString(this._worldMatrixName,"mat4");let o=null;this.normalMapColor.connectedPoint&&(o=this.normalMapColor.connectedPoint._ownerBlock.samplerName);const a=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&o||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected),l=this.parallaxScale.isConnectedToInputBlock?this.parallaxScale.connectInputBlock.isConstant?e._emitFloat(this.parallaxScale.connectInputBlock.value):this.parallaxScale.associatedVariableName:"0.05",h=this.strength.isConnectedToInputBlock&&this.strength.connectInputBlock.isConstant?`\r\n#if !defined(NORMALXYSCALE)\r\n1.0/\r\n#endif\r\n${e._emitFloat(this.strength.connectInputBlock.value)}`:`\r\n#if !defined(NORMALXYSCALE)\r\n1.0/\r\n#endif\r\n${this.strength.associatedVariableName}`;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");const c={search:/defined\(TANGENT\)/g,replace:r.isConnected?"defined(TANGENT)":"defined(IGNORE)"},d=this.TBN;d.isConnected?e.compilationString+=`\n #ifdef TBNBLOCK\n mat3 vTBN = ${d.associatedVariableName};\n #endif\n `:r.isConnected&&(e.compilationString+=`vec3 tbnNormal = normalize(${s.associatedVariableName}.xyz);\r\n`,e.compilationString+=`vec3 tbnTangent = normalize(${r.associatedVariableName}.xyz);\r\n`,e.compilationString+=`vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};\r\n`,e.compilationString+="mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\r\n"),e._emitFunctionFromInclude("bumpFragmentMainFunctions",t,{replaceStrings:[c,{search:/varying mat3 vTBN/g,replace:""},{search:/uniform mat4 normalMatrix;/g,replace:""}]}),e._emitFunctionFromInclude("bumpFragmentFunctions",t,{replaceStrings:[{search:/#include\(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump\)/g,replace:""},{search:/uniform sampler2D bumpSampler;/g,replace:""},{search:/vec2 parallaxOcclusion\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\)/g,replace:"#define inline\r\nvec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale, sampler2D bumpSampler)"},{search:/vec2 parallaxOffset\(vec3 viewDir,float heightScale\)/g,replace:"vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)"},{search:/texture2D\(bumpSampler,vBumpUV\)\.w/g,replace:"height_"}]});const u=a&&o?`texture2D(${o}, ${i.associatedVariableName} + uvOffset).xyz`:this.normalMapColor.associatedVariableName;return e.compilationString+=this._declareOutput(this.output,e)+" = vec4(0.);\r\n",e.compilationString+=e._emitCodeFromInclude("bumpFragment",t,{replaceStrings:[{search:/texture2D\(bumpSampler,vBumpUV\)/g,replace:`${u}`},{search:/#define CUSTOM_FRAGMENT_BUMP_FRAGMENT/g,replace:`mat4 normalMatrix = toNormalMatrix(${this.world.isConnected?this.world.associatedVariableName:this._worldMatrixName});`},{search:/perturbNormal\(TBN,texture2D\(bumpSampler,vBumpUV\+uvOffset\).xyz,vBumpInfos.y\)/g,replace:`perturbNormal(TBN, ${u}, vBumpInfos.y)`},{search:/parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,replace:`parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ${a&&this.useParallaxOcclusion?o:"bumpSampler"})`},{search:/parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,replace:`parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ${a?this.parallaxHeight.associatedVariableName:"0."})`},{search:/vTangentSpaceParams/g,replace:this._tangentSpaceParameterName},{search:/vBumpInfos.y/g,replace:h},{search:/vBumpInfos.z/g,replace:l},{search:/vBumpUV/g,replace:i.associatedVariableName},{search:/vPositionW/g,replace:n.associatedVariableName+".xyz"},{search:/normalW=/g,replace:this.output.associatedVariableName+".xyz = "},{search:/mat3\(normalMatrix\)\*normalW/g,replace:"mat3(normalMatrix) * "+this.output.associatedVariableName+".xyz"},{search:/normalW/g,replace:s.associatedVariableName+".xyz"},{search:/viewDirectionW/g,replace:a?this.viewDirection.associatedVariableName:"vec3(0.)"},c]}),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.invertX = ${this.invertX};\r\n`;return e+=`${this._codeVariableName}.invertY = ${this.invertY};\r\n`,e+=`${this._codeVariableName}.useParallaxOcclusion = ${this.useParallaxOcclusion};\r\n`,e+=`${this._codeVariableName}.useObjectSpaceNormalMap = ${this.useObjectSpaceNormalMap};\r\n`,e}serialize(){const e=super.serialize();return e.invertX=this.invertX,e.invertY=this.invertY,e.useParallaxOcclusion=this.useParallaxOcclusion,e.useObjectSpaceNormalMap=this.useObjectSpaceNormalMap,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.invertX=e.invertX,this.invertY=e.invertY,this.useParallaxOcclusion=!!e.useParallaxOcclusion,this.useObjectSpaceNormalMap=!!e.useObjectSpaceNormalMap}}(0,oe.gn)([At("Invert X axis",Et.Boolean,"PROPERTIES",{notifiers:{update:!1}})],jv.prototype,"invertX",void 0),(0,oe.gn)([At("Invert Y axis",Et.Boolean,"PROPERTIES",{notifiers:{update:!1}})],jv.prototype,"invertY",void 0),(0,oe.gn)([At("Use parallax occlusion",Et.Boolean)],jv.prototype,"useParallaxOcclusion",void 0),(0,oe.gn)([At("Object Space Mode",Et.Boolean,"PROPERTIES",{notifiers:{update:!1}})],jv.prototype,"useObjectSpaceNormalMap",void 0),(0,l.H)("BABYLON.PerturbNormalBlock",jv);(0,l.H)("BABYLON.DiscardBlock",class extends bt{constructor(e){super(e,dt.Fragment,!0),this.registerInput("value",ct.Float,!0),this.registerInput("cutoff",ct.Float,!0)}getClassName(){return"DiscardBlock"}get value(){return this._inputs[0]}get cutoff(){return this._inputs[1]}_buildBlock(e){if(super._buildBlock(e),e.sharedData.hints.needAlphaTesting=!0,this.cutoff.isConnected&&this.value.isConnected)return e.compilationString+=`if (${this.value.associatedVariableName} < ${this.cutoff.associatedVariableName}) discard;\r\n`,this}});(0,l.H)("BABYLON.FrontFacingBlock",class extends bt{constructor(e){super(e,dt.Fragment),this.registerOutput("output",ct.Float,dt.Fragment)}getClassName(){return"FrontFacingBlock"}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),e.target===dt.Vertex)throw"FrontFacingBlock must only be used in a fragment shader";const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+" = gl_FrontFacing ? 1.0 : 0.0;\r\n",this}});(0,l.H)("BABYLON.DerivativeBlock",class extends bt{constructor(e){super(e,dt.Fragment),this.registerInput("input",ct.AutoDetect,!1),this.registerOutput("dx",ct.BasedOnInput),this.registerOutput("dy",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._outputs[1]._typeConnectionSource=this._inputs[0]}getClassName(){return"DerivativeBlock"}get input(){return this._inputs[0]}get dx(){return this._outputs[0]}get dy(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._outputs[1];return e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),t.hasEndpoints&&(e.compilationString+=this._declareOutput(t,e)+` = dFdx(${this.input.associatedVariableName});\r\n`),i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = dFdy(${this.input.associatedVariableName});\r\n`),this}});(0,l.H)("BABYLON.FragCoordBlock",class extends bt{constructor(e){super(e,dt.Fragment),this.registerOutput("xy",ct.Vector2,dt.Fragment),this.registerOutput("xyz",ct.Vector3,dt.Fragment),this.registerOutput("xyzw",ct.Vector4,dt.Fragment),this.registerOutput("x",ct.Float,dt.Fragment),this.registerOutput("y",ct.Float,dt.Fragment),this.registerOutput("z",ct.Float,dt.Fragment),this.registerOutput("w",ct.Float,dt.Fragment)}getClassName(){return"FragCoordBlock"}get xy(){return this._outputs[0]}get xyz(){return this._outputs[1]}get xyzw(){return this._outputs[2]}get x(){return this._outputs[3]}get y(){return this._outputs[4]}get z(){return this._outputs[5]}get output(){return this._outputs[6]}writeOutputs(e){let t="";for(const i of this._outputs)i.hasEndpoints&&(t+=`${this._declareOutput(i,e)} = gl_FragCoord.${i.name};\r\n`);return t}_buildBlock(e){if(super._buildBlock(e),e.target===dt.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this}});(0,l.H)("BABYLON.ScreenSizeBlock",class extends bt{constructor(e){super(e,dt.Fragment),this.registerOutput("xy",ct.Vector2,dt.Fragment),this.registerOutput("x",ct.Float,dt.Fragment),this.registerOutput("y",ct.Float,dt.Fragment)}getClassName(){return"ScreenSizeBlock"}get xy(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}bind(e){const t=this._scene.getEngine();e.setFloat2(this._varName,t.getRenderWidth(),t.getRenderHeight())}writeOutputs(e,t){let i="";for(const n of this._outputs)n.hasEndpoints&&(i+=`${this._declareOutput(n,e)} = ${t}.${n.name};\r\n`);return i}_buildBlock(e){if(super._buildBlock(e),this._scene=e.sharedData.scene,e.target===dt.Vertex)throw"ScreenSizeBlock must only be used in a fragment shader";return e.sharedData.bindableBlocks.push(this),this._varName=e._getFreeVariableName("screenSize"),e._emitUniformFromString(this._varName,"vec2"),e.compilationString+=this.writeOutputs(e,this._varName),this}});(0,l.H)("BABYLON.ScreenSpaceBlock",class extends bt{constructor(e){super(e,dt.Fragment),this.registerInput("vector",ct.AutoDetect),this.registerInput("worldViewProjection",ct.Matrix),this.registerOutput("output",ct.Vector2),this.registerOutput("x",ct.Float),this.registerOutput("y",ct.Float),this.inputs[0].addExcludedConnectionPointFromAllowedTypes(ct.Color3|ct.Vector3|ct.Vector4)}getClassName(){return"ScreenSpaceBlock"}get vector(){return this._inputs[0]}get worldViewProjection(){return this._inputs[1]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(e){if(!this.worldViewProjection.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===Pt.WorldViewProjection));t||(t=new Bt("worldViewProjection"),t.setAsSystemValue(Pt.WorldViewProjection)),t.output.connectTo(this.worldViewProjection)}}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.worldViewProjection;if(!t.connectedPoint)return;const n=i.associatedVariableName,s=e._getFreeVariableName("screenSpaceTemp");switch(t.connectedPoint.type){case ct.Vector3:e.compilationString+=`vec4 ${s} = ${n} * vec4(${t.associatedVariableName}, 1.0);\r\n`;break;case ct.Vector4:e.compilationString+=`vec4 ${s} = ${n} * ${t.associatedVariableName};\r\n`}return e.compilationString+=`${s}.xy /= ${s}.w;`,e.compilationString+=`${s}.xy = ${s}.xy * 0.5 + vec2(0.5, 0.5);`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${s}.xy;\r\n`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${s}.x;\r\n`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${s}.y;\r\n`),this}});(0,l.H)("BABYLON.TwirlBlock",class extends bt{constructor(e){super(e,dt.Fragment),this.registerInput("input",ct.Vector2),this.registerInput("strength",ct.Float),this.registerInput("center",ct.Vector2),this.registerInput("offset",ct.Vector2),this.registerOutput("output",ct.Vector2),this.registerOutput("x",ct.Float),this.registerOutput("y",ct.Float)}getClassName(){return"TwirlBlock"}get input(){return this._inputs[0]}get strength(){return this._inputs[1]}get center(){return this._inputs[2]}get offset(){return this._inputs[3]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(){if(!this.center.isConnected){const e=new Bt("center");e.value=new o.FM(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){const e=new Bt("strength");e.value=1,e.output.connectTo(this.strength)}if(!this.offset.isConnected){const e=new Bt("offset");e.value=new o.FM(0,0),e.output.connectTo(this.offset)}}_buildBlock(e){super._buildBlock(e);const t=e._getFreeVariableName("delta"),i=e._getFreeVariableName("angle"),n=e._getFreeVariableName("x"),s=e._getFreeVariableName("y"),r=e._getFreeVariableName("result");return e.compilationString+=`\n vec2 ${t} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName};\n float ${i} = ${this.strength.associatedVariableName} * length(${t});\n float ${n} = cos(${i}) * ${t}.x - sin(${i}) * ${t}.y;\n float ${s} = sin(${i}) * ${t}.x + cos(${i}) * ${t}.y;\n vec2 ${r} = vec2(${n} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${s} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y);\n `,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${r};\r\n`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${r}.x;\r\n`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${r}.y;\r\n`),this}});class Kv extends bt{constructor(e){super(e,dt.Fragment),this.generateInWorldSpace=!1,this.automaticNormalizationNormal=!0,this.automaticNormalizationTangent=!0,this.registerInput("input",ct.Float),this.registerInput("worldPosition",ct.Vector3),this.registerInput("worldNormal",ct.Vector3),this.registerInput("worldTangent",ct.AutoDetect,!0),this.registerOutput("output",ct.Vector4),this.registerOutput("xyz",ct.Vector3),this._inputs[3].addExcludedConnectionPointFromAllowedTypes(ct.Color3|ct.Vector3|ct.Vector4)}getClassName(){return"HeightToNormalBlock"}get input(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get worldTangent(){return this._inputs[3]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];this.generateInWorldSpace||this.worldTangent.isConnected||console.error(`You must connect the 'worldTangent' input of the ${this.name} block!`);const i=this.generateInWorldSpace?"":"\n vec3 biTangent = cross(normal, tangent);\n mat3 TBN = mat3(tangent, biTangent, normal);\n ",n=this.generateInWorldSpace?"":"\n result = TBN * result;\n result = result * vec3(0.5) + vec3(0.5);\n ",s=`\n vec4 heightToNormal(in float height, in vec3 position, in vec3 tangent, in vec3 normal) {\n ${i}\n ${this.automaticNormalizationTangent?"tangent = normalize(tangent);":""}\n ${this.automaticNormalizationNormal?"normal = normalize(normal);":""}\n vec3 worlddX = dFdx(position);\n vec3 worlddY = dFdy(position);\n vec3 crossX = cross(normal, worlddX);\n vec3 crossY = cross(normal, worlddY);\n float d = abs(dot(crossY, worlddX));\n vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d));\n inToNormal.y *= -1.0;\n vec3 result = normalize((d * normal) - inToNormal);\n ${n}\n return vec4(result, 0.);\n }`;return e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitFunction("heightToNormal",s,"// heightToNormal"),e.compilationString+=this._declareOutput(t,e)+` = heightToNormal(${this.input.associatedVariableName}, ${this.worldPosition.associatedVariableName}, ${this.worldTangent.isConnected?this.worldTangent.associatedVariableName:"vec3(0.)"}.xyz, ${this.worldNormal.associatedVariableName});\r\n`,this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz;\r\n`),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.generateInWorldSpace = ${this.generateInWorldSpace};\r\n`,e+=`${this._codeVariableName}.automaticNormalizationNormal = ${this.automaticNormalizationNormal};\r\n`,e+=`${this._codeVariableName}.automaticNormalizationTangent = ${this.automaticNormalizationTangent};\r\n`,e}serialize(){const e=super.serialize();return e.generateInWorldSpace=this.generateInWorldSpace,e.automaticNormalizationNormal=this.automaticNormalizationNormal,e.automaticNormalizationTangent=this.automaticNormalizationTangent,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.generateInWorldSpace=e.generateInWorldSpace,this.automaticNormalizationNormal=e.automaticNormalizationNormal,this.automaticNormalizationTangent=e.automaticNormalizationTangent}}(0,oe.gn)([At("Generate in world space instead of tangent space",Et.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Kv.prototype,"generateInWorldSpace",void 0),(0,oe.gn)([At("Force normalization for the worldNormal input",Et.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Kv.prototype,"automaticNormalizationNormal",void 0),(0,oe.gn)([At("Force normalization for the worldTangent input",Et.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Kv.prototype,"automaticNormalizationTangent",void 0),(0,l.H)("BABYLON.HeightToNormalBlock",Kv);(0,l.H)("BABYLON.FragDepthBlock",class extends bt{constructor(e){super(e,dt.Fragment,!0),this.registerInput("depth",ct.Float,!0),this.registerInput("worldPos",ct.Vector4,!0),this.registerInput("viewProjection",ct.Matrix,!0)}getClassName(){return"FragDepthBlock"}get depth(){return this._inputs[0]}get worldPos(){return this._inputs[1]}get viewProjection(){return this._inputs[2]}_buildBlock(e){return super._buildBlock(e),this.depth.isConnected?e.compilationString+=`gl_FragDepth = ${this.depth.associatedVariableName};\r\n`:this.worldPos.isConnected&&this.viewProjection.isConnected?e.compilationString+=`\n vec4 p = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName};\n float v = p.z / p.w;\n #ifndef IS_NDC_HALF_ZRANGE\n v = v * 0.5 + 0.5;\n #endif\n gl_FragDepth = v;\n \n `:console.warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this}});(0,l.H)("BABYLON.ShadowMapBlock",class extends bt{constructor(e){super(e,dt.Fragment),this.registerInput("worldPosition",ct.Vector4,!1),this.registerInput("viewProjection",ct.Matrix,!1),this.registerInput("worldNormal",ct.AutoDetect,!0),this.registerOutput("depth",ct.Vector3),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(ct.Color3|ct.Vector3|ct.Vector4)}getClassName(){return"ShadowMapBlock"}initialize(e){e._excludeVariableName("vPositionWSM"),e._excludeVariableName("lightDataSM"),e._excludeVariableName("biasAndScaleSM"),e._excludeVariableName("depthValuesSM"),e._excludeVariableName("clipPos"),e._excludeVariableName("worldPos"),e._excludeVariableName("zSM")}get worldPosition(){return this._inputs[0]}get viewProjection(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get depth(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;return e._emitUniformFromString("biasAndScaleSM","vec3"),e._emitUniformFromString("lightDataSM","vec3"),e._emitUniformFromString("depthValuesSM","vec2"),e._emitFunctionFromInclude("packingFunctions",t),e.compilationString+=`vec4 worldPos = ${this.worldPosition.associatedVariableName};\r\n`,e.compilationString+="vec3 vPositionWSM;\r\n",e.compilationString+="float vDepthMetricSM = 0.0;\r\n",e.compilationString+="float zSM;\r\n",this.worldNormal.isConnected&&(e.compilationString+=`vec3 vNormalW = ${this.worldNormal.associatedVariableName}.xyz;\r\n`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexNormalBias",t)),e.compilationString+=`vec4 clipPos = ${this.viewProjection.associatedVariableName} * worldPos;\r\n`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexMetric",t,{replaceStrings:[{search:/gl_Position/g,replace:"clipPos"}]}),e.compilationString+=e._emitCodeFromInclude("shadowMapFragment",t,{replaceStrings:[{search:/return;/g,replace:""}]}),e.compilationString+="\n #if SM_DEPTHTEXTURE == 1\n #ifdef IS_NDC_HALF_ZRANGE\n gl_FragDepth = (clipPos.z / clipPos.w);\n #else\n gl_FragDepth = (clipPos.z / clipPos.w) * 0.5 + 0.5;\n #endif\n #endif\n ",e.compilationString+=`${this._declareOutput(this.depth,e)} = vec3(depthSM, 1., 1.);\r\n`,this}});(0,l.H)("BABYLON.FogBlock",class extends bt{constructor(e){super(e,dt.VertexAndFragment,!1),this.registerInput("worldPosition",ct.Vector4,!1,dt.Vertex),this.registerInput("view",ct.Matrix,!1,dt.Vertex),this.registerInput("input",ct.AutoDetect,!1,dt.Fragment),this.registerInput("fogColor",ct.AutoDetect,!1,dt.Fragment),this.registerOutput("output",ct.Color3,dt.Fragment),this.input.addExcludedConnectionPointFromAllowedTypes(ct.Color3|ct.Vector3|ct.Color4),this.fogColor.addExcludedConnectionPointFromAllowedTypes(ct.Color3|ct.Vector3|ct.Color4)}getClassName(){return"FogBlock"}get worldPosition(){return this._inputs[0]}get view(){return this._inputs[1]}get input(){return this._inputs[2]}get fogColor(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(e){if(!this.view.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===Pt.View));t||(t=new Bt("view"),t.setAsSystemValue(Pt.View)),t.output.connectTo(this.view)}if(!this.fogColor.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===Pt.FogColor));t||(t=new Bt("fogColor",void 0,ct.Color3),t.setAsSystemValue(Pt.FogColor)),t.output.connectTo(this.fogColor)}}prepareDefines(e,t,i){const n=e.getScene();i.setValue("FOG",t.fogEnabled&&It.G.GetFogState(e,n))}bind(e,t,i){if(!i)return;const n=i.getScene();e.setFloat4(this._fogParameters,n.fogMode,n.fogStart,n.fogEnd,n.fogDensity)}_buildBlock(e){if(super._buildBlock(e),e.target===dt.Fragment){e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),e._emitFunctionFromInclude("fogFragmentDeclaration",`//${this.name}`,{removeUniforms:!0,removeVaryings:!0,removeIfDef:!1,replaceStrings:[{search:/float CalcFogFactor\(\)/,replace:"float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)"}]});const t=e._getFreeVariableName("fog"),i=this.input,n=this.fogColor;this._fogParameters=e._getFreeVariableName("fogParameters");const s=this._outputs[0];e._emitUniformFromString(this._fogParameters,"vec4"),e.compilationString+="#ifdef FOG\r\n",e.compilationString+=`float ${t} = CalcFogFactor(${this._fogDistanceName}, ${this._fogParameters});\r\n`,e.compilationString+=this._declareOutput(s,e)+` = ${t} * ${i.associatedVariableName}.rgb + (1.0 - ${t}) * ${n.associatedVariableName}.rgb;\r\n`,e.compilationString+=`#else\r\n${this._declareOutput(s,e)} = ${i.associatedVariableName}.rgb;\r\n`,e.compilationString+="#endif\r\n"}else{const t=this.worldPosition,i=this.view;this._fogDistanceName=e._getFreeVariableName("vFogDistance"),e._emitVaryingFromString(this._fogDistanceName,"vec3"),e.compilationString+=`${this._fogDistanceName} = (${i.associatedVariableName} * ${t.associatedVariableName}).xyz;\r\n`}return this}});class qv extends bt{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,console.error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?dt.Fragment:dt.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?dt.Fragment:dt.Vertex}constructor(e){super(e,dt.VertexAndFragment),this._lightId=0,this.generateOnlyFragmentCode=!1,this._isUnique=!0,this.registerInput("worldPosition",ct.Vector4,!1,dt.Vertex),this.registerInput("worldNormal",ct.Vector4,!1,dt.Fragment),this.registerInput("cameraPosition",ct.Vector3,!1,dt.Fragment),this.registerInput("glossiness",ct.Float,!0,dt.Fragment),this.registerInput("glossPower",ct.Float,!0,dt.Fragment),this.registerInput("diffuseColor",ct.Color3,!0,dt.Fragment),this.registerInput("specularColor",ct.Color3,!0,dt.Fragment),this.registerInput("view",ct.Matrix,!0),this.registerOutput("diffuseOutput",ct.Color3,dt.Fragment),this.registerOutput("specularOutput",ct.Color3,dt.Fragment),this.registerOutput("shadow",ct.Float,dt.Fragment)}getClassName(){return"LightBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get cameraPosition(){return this._inputs[2]}get glossiness(){return this._inputs[3]}get glossPower(){return this._inputs[4]}get diffuseColor(){return this._inputs[5]}get specularColor(){return this._inputs[6]}get view(){return this._inputs[7]}get diffuseOutput(){return this._outputs[0]}get specularOutput(){return this._outputs[1]}get shadow(){return this._outputs[2]}autoConfigure(e){if(!this.cameraPosition.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===Pt.CameraPosition));t||(t=new Bt("cameraPosition"),t.setAsSystemValue(Pt.CameraPosition)),t.output.connectTo(this.cameraPosition)}}prepareDefines(e,t,i){if(!i._areLightsDirty)return;const n=e.getScene();if(this.light){const t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};It.G.PrepareDefinesForLight(n,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else It.G.PrepareDefinesForLights(n,e,i,!0,t.maxSimultaneousLights)}updateUniformsAndSamples(e,t,i,n){for(let s=0;s=0;It.G.PrepareUniformsAndSamplersForLight(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],n,t)}}bind(e,t,i){if(!i)return;const n=i.getScene();this.light?It.G.BindLight(this.light,this._lightId,n,e,!0):It.G.BindLights(n,i,e,!0,t.maxSimultaneousLights)}_injectVertexCode(e){const t=this.worldPosition,i=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const n="v_"+t.associatedVariableName;e._emitVaryingFromString(n,"vec4")&&(e.compilationString+=`${n} = ${t.associatedVariableName};\r\n`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${t.associatedVariableName};\r\n`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName};\r\n`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_buildBlock(e){if(super._buildBlock(e),e.target!==dt.Fragment)return void this._injectVertexCode(e);this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);const t=`//${this.name}`,i=this.worldPosition;let n=i.associatedVariableName;this.generateOnlyFragmentCode?(n=e._getFreeVariableName("globalWorldPos"),e._emitFunction("light_globalworldpos",`vec3 ${n};\r\n`,t),e.compilationString+=`${n} = ${i.associatedVariableName}.xyz;\r\n`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${i.associatedVariableName}`:void 0})):n="v_"+n+".xyz",e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("lightsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:n}]}),e._emitFunctionFromInclude("shadowsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:n}]}),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),0===this._lightId&&(e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${n});\r\n`),e.compilationString+="lightingInfo info;\r\n",e.compilationString+="float shadow = 1.;\r\n",e.compilationString+=`float glossiness = ${this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0"} * ${this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0"};\r\n`,e.compilationString+="vec3 diffuseBase = vec3(0., 0., 0.);\r\n",e.compilationString+="vec3 specularBase = vec3(0., 0., 0.);\r\n",e.compilationString+=`vec3 normalW = ${this.worldNormal.associatedVariableName}.xyz;\r\n`),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{repeatKey:"maxSimultaneousLights"});const s=this.diffuseOutput,r=this.specularOutput;return e.compilationString+=this._declareOutput(s,e)+` = diffuseBase${this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:""};\r\n`,r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = specularBase${this.specularColor.isConnected?" * "+this.specularColor.associatedVariableName:""};\r\n`),this.shadow.hasEndpoints&&(e.compilationString+=this._declareOutput(this.shadow,e)+" = shadow;\r\n"),this}serialize(){const e=super.serialize();return e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,this.light&&(e.lightId=this.light.id),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}(0,oe.gn)([At("Generate only fragment code",Et.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:qv._OnGenerateOnlyFragmentCodeChanged}})],qv.prototype,"generateOnlyFragmentCode",void 0),(0,l.H)("BABYLON.LightBlock",qv);class $v extends bt{get texture(){return this._texture}set texture(e){var t;if(this._texture===e)return;const i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:m.l.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}get samplerName(){return this._samplerName}constructor(e){super(e,dt.VertexAndFragment),this.registerOutput("source",ct.Object,dt.VertexAndFragment,new Wv("source",this,vt.Output,$v,"ImageSourceBlock"))}bind(e){this.texture&&e.setTexture(this._samplerName,this.texture)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}getClassName(){return"ImageSourceBlock"}get source(){return this._outputs[0]}_buildBlock(e){return super._buildBlock(e),e.target===dt.Vertex&&(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this)),e._emit2DSampler(this._samplerName),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\r\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\r\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\r\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\r\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\r\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\r\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\r\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\r\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\r\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\r\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\r\n`,e):e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&"VideoTexture"!==this.texture.getClassName()&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!Ni.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Le.Parse(e.texture,t,i))}}(0,l.H)("BABYLON.ImageSourceBlock",$v);(0,l.H)("BABYLON.TextureBlock",class extends bt{get texture(){var e;return this.source.isConnected?(null===(e=this.source.connectedPoint)||void 0===e?void 0:e.ownerBlock).texture:this._texture}set texture(e){var t;if(this._texture===e)return;const i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:m.l.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}get samplerName(){return this._imageSource?this._imageSource.samplerName:this._samplerName}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){var t;if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const e=null!==(t=this.texture.getScene())&&void 0!==t?t:m.l.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){var t;if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const e=null!==(t=this.texture.getScene())&&void 0!==t?t:m.l.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,t?dt.Fragment:dt.VertexAndFragment),this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this._fragmentOnly=t,this.registerInput("uv",ct.AutoDetect,!1,dt.VertexAndFragment),this.registerInput("source",ct.Object,!0,dt.VertexAndFragment,new Wv("source",this,vt.Input,$v,"ImageSourceBlock")),this.registerInput("layer",ct.Float,!0),this.registerInput("lod",ct.Float,!0),this.registerOutput("rgba",ct.Color4,dt.Neutral),this.registerOutput("rgb",ct.Color3,dt.Neutral),this.registerOutput("r",ct.Float,dt.Neutral),this.registerOutput("g",ct.Float,dt.Neutral),this.registerOutput("b",ct.Float,dt.Neutral),this.registerOutput("a",ct.Float,dt.Neutral),this.registerOutput("level",ct.Float,dt.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ct.Vector2|ct.Vector3|ct.Vector4),this._inputs[0]._prioritizeVertex=!t}getClassName(){return"TextureBlock"}get uv(){return this._inputs[0]}get source(){return this._inputs[1]}get layer(){return this._inputs[2]}get lod(){return this._inputs[3]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}get target(){if(this._fragmentOnly)return dt.Fragment;if(!this.uv.isConnected)return dt.VertexAndFragment;if(this.uv.sourceBlock.isInput)return dt.VertexAndFragment;let e=this.uv.connectedPoint;for(;e;){if(e.target===dt.Fragment)return dt.Fragment;if(e.target===dt.Vertex)return dt.VertexAndFragment;if(e.target===dt.Neutral||e.target===dt.VertexAndFragment){const t=e.ownerBlock;if(t.target===dt.Fragment)return dt.Fragment;e=null;for(const i of t.inputs)if(i.connectedPoint){e=i.connectedPoint;break}}}return dt.VertexAndFragment}set target(e){}autoConfigure(e){if(!this.uv.isConnected)if(e.mode===qt.PostProcess){const t=e.getBlockByPredicate((e=>"uv"===e.name));t&&t.connectTo(this)}else{const t=e.mode===qt.Particle?"particle_uv":"uv";let i=e.getInputBlockByPredicate((e=>e.isAttribute&&e.name===t));i||(i=new Bt("uv"),i.setAsAttribute(t)),i.output.connectTo(this.uv)}}initializeDefines(e,t,i){i._areTexturesDirty&&void 0!==this._mainUVDefineName&&i.setValue(this._mainUVDefineName,!1,!0)}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;if(!this.texture||!this.texture.getTextureMatrix)return void(this._isMixed&&(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)));const n=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,n,!0),i.setValue(this._gammaDefineName,s,!0),this._isMixed&&(this.texture.getTextureMatrix().isIdentityAs3x2()?(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)):(i.setValue(this._defineName,!0),null==i[this._mainUVDefineName]&&i.setValue(this._mainUVDefineName,!1,!0)))}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){this.texture&&(this._isMixed&&(e.setFloat(this._textureInfoName,this.texture.level),e.setMatrix(this._textureTransformName,this.texture.getTextureMatrix())),this._imageSource||e.setTexture(this._samplerName,this.texture))}get _isMixed(){return this.target!==dt.Fragment}_injectVertexCode(e){const t=this.uv;if(this._defineName=e._getFreeDefineName("UVTRANSFORM"),this._mainUVDefineName="VMAIN"+t.associatedVariableName.toUpperCase(),this._mainUVName="vMain"+t.associatedVariableName,this._transformedUVName=e._getFreeVariableName("transformedUV"),this._textureTransformName=e._getFreeVariableName("textureTransform"),this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,e._emitVaryingFromString(this._transformedUVName,"vec2",this._defineName),e._emitVaryingFromString(this._mainUVName,"vec2",this._mainUVDefineName),e._emitUniformFromString(this._textureTransformName,"mat4",this._defineName),e.compilationString+=`#ifdef ${this._defineName}\r\n`,e.compilationString+=`${this._transformedUVName} = vec2(${this._textureTransformName} * vec4(${t.associatedVariableName}.xy, 1.0, 0.0));\r\n`,e.compilationString+=`#elif defined(${this._mainUVDefineName})\r\n`,e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\r\n`,e.compilationString+="#endif\r\n",this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name,!0)}}_getUVW(e){var t,i,n;let s=e;if(null!==(n=null===(i=null===(t=this._texture)||void 0===t?void 0:t._texture)||void 0===i?void 0:i.is2DArray)&&void 0!==n&&n){s=`vec3(${e}, ${this.layer.isConnected?this.layer.associatedVariableName:"0"})`}return s}get _samplerFunc(){return this.lod.isConnected?"texture2DLodEXT":"texture2D"}get _samplerLodSuffix(){return this.lod.isConnected?`, ${this.lod.associatedVariableName}`:""}_generateTextureLookup(e){const t=this.samplerName;e.compilationString+=`#ifdef ${this._defineName}\r\n`,e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${t}, ${this._getUVW(this._transformedUVName)}${this._samplerLodSuffix});\r\n`,e.compilationString+=`#elif defined(${this._mainUVDefineName})\r\n`,e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${t}, ${this._getUVW(this._mainUVName?this._mainUVName:this.uv.associatedVariableName)}${this._samplerLodSuffix});\r\n`,e.compilationString+="#endif\r\n"}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===dt.Fragment)return;this._generateTextureLookup(e)}else this.uv.ownerBlock.target!==dt.Fragment?this._generateTextureLookup(e):e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${this.samplerName}, ${this._getUVW(i.associatedVariableName)}${this._samplerLodSuffix});\r\n`}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName}\n ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n #endif\n `),e.compilationString+=`#ifdef ${this._gammaDefineName}\n ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n #endif\n `)}_writeOutput(e,t,i,n=!1){if(n){if(e.target===dt.Fragment)return;return e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`,void this._generateConversionCode(e,t,i)}if(this.uv.ownerBlock.target===dt.Fragment)return e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`,void this._generateConversionCode(e,t,i);let s="";this.disableLevelMultiplication||(s=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${s};\r\n`,this._generateConversionCode(e,t,i)}_buildBlock(e){var t,i,n,s;if(super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,(e.target===dt.Vertex||this._fragmentOnly||e.target===dt.Fragment)&&(this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA")),(!this._isMixed&&e.target===dt.Fragment||this._isMixed&&e.target===dt.Vertex)&&(this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),(null===(i=null===(t=this._texture)||void 0===t?void 0:t._texture)||void 0===i?void 0:i.is2DArray)?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this)),e.target!==dt.Fragment)return void this._injectVertexCode(e);if(!this._outputs.some((e=>e.isConnectedInFragmentShader)))return;this._isMixed&&!this._imageSource&&((null===(s=null===(n=this._texture)||void 0===n?void 0:n._texture)||void 0===s?void 0:s.is2DArray)?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName));const r=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",r),this._isMixed&&e._emitUniformFromString(this._textureInfoName,"float"),this._writeTextureRead(e);for(const o of this._outputs)o.hasEndpoints&&"level"!==o.name&&this._writeOutput(e,o,o.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\r\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\r\n`,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\r\n`,this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\r\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\r\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\r\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\r\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\r\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\r\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\r\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\r\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\r\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\r\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\r\n`,e):e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.fragmentOnly=this._fragmentOnly,e.disableLevelMultiplication=this.disableLevelMultiplication,this.hasImageSource||!this.texture||this.texture.isRenderTarget||"VideoTexture"===this.texture.getClassName()||(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this._fragmentOnly=!!e.fragmentOnly,this.disableLevelMultiplication=!!e.disableLevelMultiplication,e.texture&&!Ni.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Le.Parse(e.texture,t,i))}});class Qv extends bt{get texture(){return this._texture}set texture(e){var t;if(this._texture===e)return;const i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:m.l.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}static _OnGenerateOnlyFragmentCodeChanged(e,t){return e._onGenerateOnlyFragmentCodeChanged()}_onGenerateOnlyFragmentCodeChanged(){return this._setTarget(),!0}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?dt.Fragment:dt.VertexAndFragment)}constructor(e){super(e,dt.VertexAndFragment),this.generateOnlyFragmentCode=!1}getClassName(){return"ReflectionTextureBaseBlock"}_getTexture(){return this.texture}autoConfigure(e){if(!this.position.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"position"===e.name));t||(t=new Bt("position"),t.setAsAttribute()),t.output.connectTo(this.position)}if(!this.world.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===Pt.World));t||(t=new Bt("world"),t.setAsSystemValue(Pt.World)),t.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===Pt.View));t||(t=new Bt("view"),t.setAsSystemValue(Pt.View)),t.output.connectTo(this.view)}}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const n=this._getTexture();n&&n.getTextureMatrix&&(i.setValue(this._define3DName,n.isCube,!0),i.setValue(this._defineLocalCubicName,!!n.boundingBoxSize,!0),i.setValue(this._defineExplicitName,0===n.coordinatesMode,!0),i.setValue(this._defineSkyboxName,5===n.coordinatesMode,!0),i.setValue(this._defineCubicName,3===n.coordinatesMode||6===n.coordinatesMode,!0),i.setValue("INVERTCUBICMAP",6===n.coordinatesMode,!0),i.setValue(this._defineSphericalName,1===n.coordinatesMode,!0),i.setValue(this._definePlanarName,2===n.coordinatesMode,!0),i.setValue(this._defineProjectionName,4===n.coordinatesMode,!0),i.setValue(this._defineEquirectangularName,7===n.coordinatesMode,!0),i.setValue(this._defineEquirectangularFixedName,8===n.coordinatesMode,!0),i.setValue(this._defineMirroredEquirectangularFixedName,9===n.coordinatesMode,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i){const n=this._getTexture();if(i&&n&&(e.setMatrix(this._reflectionMatrixName,n.getReflectionTextureMatrix()),n.isCube?e.setTexture(this._cubeSamplerName,n):e.setTexture(this._2DSamplerName,n),n.boundingBoxSize)){const t=n;e.setVector3(this._reflectionPositionName,t.boundingBoxPosition),e.setVector3(this._reflectionSizeName,t.boundingBoxSize)}}handleVertexSide(e){if(this.generateOnlyFragmentCode&&e.target===dt.Vertex)return"";this._define3DName=e._getFreeDefineName("REFLECTIONMAP_3D"),this._defineCubicName=e._getFreeDefineName("REFLECTIONMAP_CUBIC"),this._defineSphericalName=e._getFreeDefineName("REFLECTIONMAP_SPHERICAL"),this._definePlanarName=e._getFreeDefineName("REFLECTIONMAP_PLANAR"),this._defineProjectionName=e._getFreeDefineName("REFLECTIONMAP_PROJECTION"),this._defineExplicitName=e._getFreeDefineName("REFLECTIONMAP_EXPLICIT"),this._defineEquirectangularName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR"),this._defineLocalCubicName=e._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC"),this._defineMirroredEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"),this._defineEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED"),this._defineSkyboxName=e._getFreeDefineName("REFLECTIONMAP_SKYBOX"),this._defineOppositeZ=e._getFreeDefineName("REFLECTIONMAP_OPPOSITEZ"),this._reflectionMatrixName=e._getFreeVariableName("reflectionMatrix"),e._emitUniformFromString(this._reflectionMatrixName,"mat4");let t="";this._worldPositionNameInFragmentOnlyMode=e._getFreeVariableName("worldPosition");const i=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName;return(this.generateOnlyFragmentCode||e._emitVaryingFromString(i,"vec4"))&&(t+=`${this.generateOnlyFragmentCode?"vec4 ":""}${i} = ${this.worldPosition.associatedVariableName};\r\n`),this._positionUVWName=e._getFreeVariableName("positionUVW"),this._directionWName=e._getFreeVariableName("directionW"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._positionUVWName,"vec3",this._defineSkyboxName))&&(t+=`#ifdef ${this._defineSkyboxName}\r\n`,t+=`${this.generateOnlyFragmentCode?"vec3 ":""}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz;\r\n`,t+="#endif\r\n"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._directionWName,"vec3",`defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`))&&(t+=`#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})\r\n`,t+=`${this.generateOnlyFragmentCode?"vec3 ":""}${this._directionWName} = normalize(vec3(${this.world.associatedVariableName} * vec4(${this.position.associatedVariableName}.xyz, 0.0)));\r\n`,t+="#endif\r\n"),t}handleFragmentSideInits(e){e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),e._samplerDeclaration+=`#ifdef ${this._define3DName}\r\n`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName};\r\n`,e._samplerDeclaration+="#else\r\n",e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName};\r\n`,e._samplerDeclaration+="#endif\r\n",e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunction("ReciprocalPI","#define RECIPROCAL_PI2 0.15915494",""),e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("reflectionFunction",t,{replaceStrings:[{search:/vec3 computeReflectionCoords/g,replace:"void DUMMYFUNC"}]}),this._reflectionColorName=e._getFreeVariableName("reflectionColor"),this._reflectionVectorName=e._getFreeVariableName("reflectionUVW"),this._reflectionCoordsName=e._getFreeVariableName("reflectionCoords"),this._reflectionPositionName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionPositionName,"vec3"),this._reflectionSizeName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionSizeName,"vec3")}handleFragmentSideCodeReflectionCoords(e,t,i=!1,n=!1){t||(t=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:`v_${this.worldPosition.associatedVariableName}`);const s=this._reflectionMatrixName,r=`normalize(${this._directionWName})`,o=`${this._positionUVWName}`,a=`${this.cameraPosition.associatedVariableName}`,l=`${this.view.associatedVariableName}`;e+=".xyz";let h=`\n #ifdef ${this._defineMirroredEquirectangularFixedName}\n vec3 ${this._reflectionVectorName} = computeMirroredFixedEquirectangularCoords(${t}, ${e}, ${r});\n #endif\n\n #ifdef ${this._defineEquirectangularFixedName}\n vec3 ${this._reflectionVectorName} = computeFixedEquirectangularCoords(${t}, ${e}, ${r});\n #endif\n\n #ifdef ${this._defineEquirectangularName}\n vec3 ${this._reflectionVectorName} = computeEquirectangularCoords(${t}, ${e}, ${a}.xyz, ${s});\n #endif\n\n #ifdef ${this._defineSphericalName}\n vec3 ${this._reflectionVectorName} = computeSphericalCoords(${t}, ${e}, ${l}, ${s});\n #endif\n\n #ifdef ${this._definePlanarName}\n vec3 ${this._reflectionVectorName} = computePlanarCoords(${t}, ${e}, ${a}.xyz, ${s});\n #endif\n\n #ifdef ${this._defineCubicName}\n #ifdef ${this._defineLocalCubicName}\n vec3 ${this._reflectionVectorName} = computeCubicLocalCoords(${t}, ${e}, ${a}.xyz, ${s}, ${this._reflectionSizeName}, ${this._reflectionPositionName});\n #else\n vec3 ${this._reflectionVectorName} = computeCubicCoords(${t}, ${e}, ${a}.xyz, ${s});\n #endif\n #endif\n\n #ifdef ${this._defineProjectionName}\n vec3 ${this._reflectionVectorName} = computeProjectionCoords(${t}, ${l}, ${s});\n #endif\n\n #ifdef ${this._defineSkyboxName}\n vec3 ${this._reflectionVectorName} = computeSkyBoxCoords(${o}, ${s});\n #endif\n\n #ifdef ${this._defineExplicitName}\n vec3 ${this._reflectionVectorName} = vec3(0, 0, 0);\n #endif\r\n`;return n||(h+=`#ifdef ${this._defineOppositeZ}\n ${this._reflectionVectorName}.z *= -1.0;\n #endif\r\n`),i||(h+=`\n #ifdef ${this._define3DName}\n vec3 ${this._reflectionCoordsName} = ${this._reflectionVectorName};\n #else\n vec2 ${this._reflectionCoordsName} = ${this._reflectionVectorName}.xy;\n #ifdef ${this._defineProjectionName}\n ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z;\n #endif\n ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y;\n #endif\r\n`),h}handleFragmentSideCodeReflectionColor(e,t=".rgb"){let i=`${"vec"+(0===t.length?"4":t.length-1)} ${this._reflectionColorName};\n #ifdef ${this._define3DName}\r\n`;return i+=e?`${this._reflectionColorName} = textureCubeLodEXT(${this._cubeSamplerName}, ${this._reflectionVectorName}, ${e})${t};\r\n`:`${this._reflectionColorName} = textureCube(${this._cubeSamplerName}, ${this._reflectionVectorName})${t};\r\n`,i+="\n #else\r\n",i+=e?`${this._reflectionColorName} = texture2DLodEXT(${this._2DSamplerName}, ${this._reflectionCoordsName}, ${e})${t};\r\n`:`${this._reflectionColorName} = texture2D(${this._2DSamplerName}, ${this._reflectionCoordsName})${t};\r\n`,i+="#endif\r\n",i}writeOutputs(e,t){let i="";if(e.target===dt.Fragment)for(const n of this._outputs)n.hasEndpoints&&(i+=`${this._declareOutput(n,e)} = ${t}.${n.name};\r\n`);return i}_buildBlock(e){return super._buildBlock(e),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();if(!this.texture)return e;if(this.texture.isCube){const t=this.texture.forcedExtension;e+=`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}", undefined, undefined, ${this.texture.noMipmap}, null, undefined, undefined, undefined, ${this.texture._prefiltered}, ${t?'"'+t+'"':"null"});\r\n`}else e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null);\r\n`;return e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\r\n`,e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!Ni.IgnoreTexturesAtLoadTime&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=yp.Parse(e.texture,t,i):this.texture=Le.Parse(e.texture,t,i)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}(0,oe.gn)([At("Generate only fragment code",Et.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:Qv._OnGenerateOnlyFragmentCodeChanged}})],Qv.prototype,"generateOnlyFragmentCode",void 0),(0,l.H)("BABYLON.ReflectionTextureBaseBlock",Qv);(0,l.H)("BABYLON.ReflectionTextureBlock",class extends Qv{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,console.error("The position input must not be connected to be able to switch!"),!1):this.worldPosition.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,console.error("The worldPosition input must not be connected to be able to switch!"),!1):(this._setTarget(),!0)}_setTarget(){super._setTarget(),this.getInputByName("position").target=this.generateOnlyFragmentCode?dt.Fragment:dt.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?dt.Fragment:dt.Vertex}constructor(e){super(e),this.registerInput("position",ct.AutoDetect,!1,dt.Vertex),this.registerInput("worldPosition",ct.Vector4,!1,dt.Vertex),this.registerInput("worldNormal",ct.Vector4,!1,dt.Fragment),this.registerInput("world",ct.Matrix,!1,dt.Vertex),this.registerInput("cameraPosition",ct.Vector3,!1,dt.Fragment),this.registerInput("view",ct.Matrix,!1,dt.Fragment),this.registerOutput("rgb",ct.Color3,dt.Fragment),this.registerOutput("rgba",ct.Color4,dt.Fragment),this.registerOutput("r",ct.Float,dt.Fragment),this.registerOutput("g",ct.Float,dt.Fragment),this.registerOutput("b",ct.Float,dt.Fragment),this.registerOutput("a",ct.Float,dt.Fragment),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ct.Color3|ct.Vector3|ct.Vector4)}getClassName(){return"ReflectionTextureBlock"}get position(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get world(){return this._inputs[3]}get cameraPosition(){return this._inputs[4]}get view(){return this._inputs[5]}get rgb(){return this._outputs[0]}get rgba(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}autoConfigure(e){if(super.autoConfigure(e),!this.cameraPosition.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===Pt.CameraPosition));t||(t=new Bt("cameraPosition"),t.setAsSystemValue(Pt.CameraPosition)),t.output.connectTo(this.cameraPosition)}}_buildBlock(e){if(super._buildBlock(e),!this.texture)return e.compilationString+=this.writeOutputs(e,"vec4(0.)"),this;if(e.target!==dt.Fragment)return e.compilationString+=this.handleVertexSide(e),this;this.generateOnlyFragmentCode&&(e.compilationString+=this.handleVertexSide(e)),this.handleFragmentSideInits(e);const t=e._getFreeVariableName("normalWUnit");return e.compilationString+=`vec4 ${t} = normalize(${this.worldNormal.associatedVariableName});\r\n`,e.compilationString+=this.handleFragmentSideCodeReflectionCoords(t),e.compilationString+=this.handleFragmentSideCodeReflectionColor(void 0,""),e.compilationString+=this.writeOutputs(e,this._reflectionColorName),this}});class Zv extends bt{constructor(e){super(e,dt.VertexAndFragment),this.useNonLinearDepth=!1,this.storeCameraSpaceZ=!1,this.force32itsFloat=!1,this._isUnique=!0,this.registerInput("uv",ct.AutoDetect,!1,dt.VertexAndFragment),this.registerOutput("depth",ct.Float,dt.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ct.Vector2|ct.Vector3|ct.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"SceneDepthBlock"}get uv(){return this._inputs[0]}get depth(){return this._outputs[0]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return this.uv.isConnected?this.uv.sourceBlock.isInput?dt.VertexAndFragment:dt.Fragment:dt.VertexAndFragment}_getTexture(e){return e.enableDepthRenderer(void 0,this.useNonLinearDepth,this.force32itsFloat,void 0,this.storeCameraSpaceZ).getDepthMap()}bind(e,t){const i=this._getTexture(t.getScene());e.setTexture(this._samplerName,i)}_injectVertexCode(e){const t=this.uv;if(t.connectedPoint.ownerBlock.isInput){t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,"vec"+(t.type===ct.Vector3?"3":t.type===ct.Vector4?"4":"2"))}if(this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\r\n`,this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,"r",!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===dt.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy);\r\n`}else this.uv.ownerBlock.target!==dt.Fragment?e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\r\n`:e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy);\r\n`}_writeOutput(e,t,i,n=!1){if(n){if(e.target===dt.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`}else this.uv.ownerBlock.target,dt.Fragment,e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`}_buildBlock(e){if(super._buildBlock(e),this._samplerName=e._getFreeVariableName(this.name+"Sampler"),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e.sharedData.bindableBlocks.indexOf(this)<0&&e.sharedData.bindableBlocks.push(this),e.target!==dt.Fragment)return e._emit2DSampler(this._samplerName),void this._injectVertexCode(e);if(this._outputs.some((e=>e.isConnectedInFragmentShader))){e._emit2DSampler(this._samplerName),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,"r");return this}}serialize(){const e=super.serialize();return e.useNonLinearDepth=this.useNonLinearDepth,e.storeCameraSpaceZ=this.storeCameraSpaceZ,e.force32itsFloat=this.force32itsFloat,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.useNonLinearDepth=e.useNonLinearDepth,this.storeCameraSpaceZ=!!e.storeCameraSpaceZ,this.force32itsFloat=e.force32itsFloat}}(0,oe.gn)([At("Use non linear depth",Et.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{const i=t;let n=!1;return i.useNonLinearDepth&&(i.storeCameraSpaceZ=!1,n=!0),e.disableDepthRenderer(),n}}})],Zv.prototype,"useNonLinearDepth",void 0),(0,oe.gn)([At("Store Camera space Z",Et.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{const i=t;let n=!1;return i.storeCameraSpaceZ&&(i.useNonLinearDepth=!1,n=!0),e.disableDepthRenderer(),n}}})],Zv.prototype,"storeCameraSpaceZ",void 0),(0,oe.gn)([At("Force 32 bits float",Et.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:e=>e.disableDepthRenderer()}})],Zv.prototype,"force32itsFloat",void 0),(0,l.H)("BABYLON.SceneDepthBlock",Zv);(0,l.H)("BABYLON.ClipPlanesBlock",class extends bt{constructor(e){super(e,dt.VertexAndFragment,!0),this.registerInput("worldPosition",ct.Vector4,!1)}getClassName(){return"ClipPlanesBlock"}initialize(e){e._excludeVariableName("vClipPlane"),e._excludeVariableName("fClipDistance"),e._excludeVariableName("vClipPlane2"),e._excludeVariableName("fClipDistance2"),e._excludeVariableName("vClipPlane3"),e._excludeVariableName("fClipDistance3"),e._excludeVariableName("vClipPlane4"),e._excludeVariableName("fClipDistance4"),e._excludeVariableName("vClipPlane5"),e._excludeVariableName("fClipDistance5"),e._excludeVariableName("vClipPlane6"),e._excludeVariableName("fClipDistance6")}get worldPosition(){return this._inputs[0]}get target(){return dt.VertexAndFragment}set target(e){}prepareDefines(e,t,i){var n,s,r,o,a,l;const h=e.getScene(),c=!!(null!==(n=t.clipPlane)&&void 0!==n?n:h.clipPlane),d=!!(null!==(s=t.clipPlane2)&&void 0!==s?s:h.clipPlane2),u=!!(null!==(r=t.clipPlane3)&&void 0!==r?r:h.clipPlane3),p=!!(null!==(o=t.clipPlane4)&&void 0!==o?o:h.clipPlane4),f=!!(null!==(a=t.clipPlane5)&&void 0!==a?a:h.clipPlane5),_=!!(null!==(l=t.clipPlane6)&&void 0!==l?l:h.clipPlane6);i.setValue("CLIPPLANE",c,!0),i.setValue("CLIPPLANE2",d,!0),i.setValue("CLIPPLANE3",u,!0),i.setValue("CLIPPLANE4",p,!0),i.setValue("CLIPPLANE5",f,!0),i.setValue("CLIPPLANE6",_,!0)}bind(e,t,i){if(!i)return;const n=i.getScene();(0,ua.an)(e,t,n)}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;if(e.target!==dt.Fragment){const i=this.worldPosition;return e._emitFunctionFromInclude("clipPlaneVertexDeclaration",t,{replaceStrings:[{search:/uniform vec4 vClipPlane\d*;/g,replace:""}]}),e.compilationString+=e._emitCodeFromInclude("clipPlaneVertex",t,{replaceStrings:[{search:/worldPos/g,replace:i.associatedVariableName}]}),e._emitUniformFromString("vClipPlane","vec4"),e._emitUniformFromString("vClipPlane2","vec4"),e._emitUniformFromString("vClipPlane3","vec4"),e._emitUniformFromString("vClipPlane4","vec4"),e._emitUniformFromString("vClipPlane5","vec4"),void e._emitUniformFromString("vClipPlane6","vec4")}return e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e._emitFunctionFromInclude("clipPlaneFragmentDeclaration",t),e.compilationString+=e._emitCodeFromInclude("clipPlaneFragment",t),this}});(0,l.H)("BABYLON.AddBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("left",ct.AutoDetect),this.registerInput("right",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].acceptedConnectionPointTypes.push(ct.Float),this._inputs[1].acceptedConnectionPointTypes.push(ct.Float)}getClassName(){return"AddBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} + ${this.right.associatedVariableName};\r\n`,this}});(0,l.H)("BABYLON.ScaleBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("input",ct.AutoDetect),this.registerInput("factor",ct.Float),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ScaleBlock"}get input(){return this._inputs[0]}get factor(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} * ${this.factor.associatedVariableName};\r\n`,this}});class Jv extends bt{constructor(e){super(e,dt.Neutral),this.minimum=0,this.maximum=1,this.registerInput("value",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ClampBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = clamp(${this.value.associatedVariableName}, ${this._writeFloat(this.minimum)}, ${this._writeFloat(this.maximum)});\r\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum};\r\n`;return e+=`${this._codeVariableName}.maximum = ${this.maximum};\r\n`,e}serialize(){const e=super.serialize();return e.minimum=this.minimum,e.maximum=this.maximum,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.minimum=e.minimum,this.maximum=e.maximum}}(0,oe.gn)([At("Minimum",Et.Float)],Jv.prototype,"minimum",void 0),(0,oe.gn)([At("Maximum",Et.Float)],Jv.prototype,"maximum",void 0),(0,l.H)("BABYLON.ClampBlock",Jv);(0,l.H)("BABYLON.CrossBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("left",ct.AutoDetect),this.registerInput("right",ct.AutoDetect),this.registerOutput("output",ct.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(ct.Float),this._inputs[0].excludedConnectionPointTypes.push(ct.Matrix),this._inputs[0].excludedConnectionPointTypes.push(ct.Vector2),this._inputs[1].excludedConnectionPointTypes.push(ct.Float),this._inputs[1].excludedConnectionPointTypes.push(ct.Matrix),this._inputs[1].excludedConnectionPointTypes.push(ct.Vector2)}getClassName(){return"CrossBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = cross(${this.left.associatedVariableName}.xyz, ${this.right.associatedVariableName}.xyz);\r\n`,this}});(0,l.H)("BABYLON.CustomBlock",class extends bt{get options(){return this._options}set options(e){this._deserializeOptions(e)}constructor(e){super(e)}getClassName(){return"CustomBlock"}_buildBlock(e){super._buildBlock(e);let t=this._code,i=this._options.functionName;this._inputs.forEach((n=>{const s=new RegExp("\\{TYPE_"+n.name+"\\}","gm"),r=e._getGLType(n.type);t=t.replace(s,r),i=i.replace(s,r)})),this._outputs.forEach((n=>{const s=new RegExp("\\{TYPE_"+n.name+"\\}","gm"),r=e._getGLType(n.type);t=t.replace(s,r),i=i.replace(s,r)})),e._emitFunction(i,t,""),this._outputs.forEach((t=>{e.compilationString+=this._declareOutput(t,e)+";\r\n"})),e.compilationString+=i+"(";let n=!1;return this._inputs.forEach(((t,i)=>{var s,r,o;i>0&&(e.compilationString+=", "),this._inputSamplers&&-1!==this._inputSamplers.indexOf(t.name)?e.compilationString+=null!==(o=null===(r=null===(s=t.connectedPoint)||void 0===s?void 0:s.ownerBlock)||void 0===r?void 0:r.samplerName)&&void 0!==o?o:t.associatedVariableName:e.compilationString+=t.associatedVariableName,n=!0})),this._outputs.forEach(((t,i)=>{(i>0||n)&&(e.compilationString+=", "),e.compilationString+=t.associatedVariableName})),e.compilationString+=");\r\n",this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.options = ${JSON.stringify(this._options)};\r\n`,e}serialize(){const e=super.serialize();return e.options=this._options,e}_deserialize(e,t,i){this._deserializeOptions(e.options),super._deserialize(e,t,i)}_deserializeOptions(e){var t,i,n;this._options=e,this._code=e.code.join("\r\n")+"\r\n",this.name=this.name||e.name,this.target=dt[e.target],null===(t=e.inParameters)||void 0===t||t.forEach(((e,t)=>{const i=ct[e.type];"sampler2D"===e.type||"samplerCube"===e.type?(this._inputSamplers=this._inputSamplers||[],this._inputSamplers.push(e.name),this.registerInput(e.name,ct.Object,!0,dt.VertexAndFragment,new Wv(e.name,this,vt.Input,$v,"ImageSourceBlock"))):this.registerInput(e.name,i),Object.defineProperty(this,e.name,{get:function(){return this._inputs[t]},enumerable:!0,configurable:!0})})),null===(i=e.outParameters)||void 0===i||i.forEach(((e,t)=>{this.registerOutput(e.name,ct[e.type]),Object.defineProperty(this,e.name,{get:function(){return this._outputs[t]},enumerable:!0,configurable:!0}),"BasedOnInput"===e.type&&(this._outputs[t]._typeConnectionSource=this._findInputByName(e.typeFromInput)[0])})),null===(n=e.inLinkedConnectionTypes)||void 0===n||n.forEach((e=>{this._linkConnectionTypes(this._findInputByName(e.input1)[1],this._findInputByName(e.input2)[1])}))}_findInputByName(e){if(!e)return null;for(let t=0;te.systemValue===Pt.CameraPosition));t||(t=new Bt("cameraPosition"),t.setAsSystemValue(Pt.CameraPosition)),t.output.connectTo(this.cameraPosition)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = normalize(${this.cameraPosition.associatedVariableName} - ${this.worldPosition.associatedVariableName}.xyz);\r\n`,this}}(0,l.H)("BABYLON.ViewDirectionBlock",tT);(0,l.H)("BABYLON.FresnelBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("worldNormal",ct.Vector4),this.registerInput("viewDirection",ct.Vector3),this.registerInput("bias",ct.Float),this.registerInput("power",ct.Float),this.registerOutput("fresnel",ct.Float)}getClassName(){return"FresnelBlock"}get worldNormal(){return this._inputs[0]}get viewDirection(){return this._inputs[1]}get bias(){return this._inputs[2]}get power(){return this._inputs[3]}get fresnel(){return this._outputs[0]}autoConfigure(e){if(!this.viewDirection.isConnected){const t=new tT("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){const e=new Bt("bias");e.value=0,e.output.connectTo(this.bias)}if(!this.power.isConnected){const e=new Bt("power");e.value=1,e.output.connectTo(this.power)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;return e._emitFunctionFromInclude("fresnelFunction",t,{removeIfDef:!0}),e.compilationString+=this._declareOutput(this.fresnel,e)+` = computeFresnelTerm(${this.viewDirection.associatedVariableName}.xyz, ${this.worldNormal.associatedVariableName}.xyz, ${this.bias.associatedVariableName}, ${this.power.associatedVariableName});\r\n`,this}});(0,l.H)("BABYLON.MaxBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("left",ct.AutoDetect),this.registerInput("right",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MaxBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = max(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\r\n`,this}});(0,l.H)("BABYLON.MinBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("left",ct.AutoDetect),this.registerInput("right",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MinBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = min(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\r\n`,this}});(0,l.H)("BABYLON.DistanceBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("left",ct.AutoDetect),this.registerInput("right",ct.AutoDetect),this.registerOutput("output",ct.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(ct.Float),this._inputs[0].excludedConnectionPointTypes.push(ct.Matrix),this._inputs[1].excludedConnectionPointTypes.push(ct.Float),this._inputs[1].excludedConnectionPointTypes.push(ct.Matrix)}getClassName(){return"DistanceBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = length(${this.left.associatedVariableName} - ${this.right.associatedVariableName});\r\n`,this}});(0,l.H)("BABYLON.LengthBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("value",ct.AutoDetect),this.registerOutput("output",ct.Float),this._inputs[0].excludedConnectionPointTypes.push(ct.Float),this._inputs[0].excludedConnectionPointTypes.push(ct.Matrix)}getClassName(){return"LengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = length(${this.value.associatedVariableName});\r\n`,this}});(0,l.H)("BABYLON.NegateBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("value",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NegateBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = -1.0 * ${this.value.associatedVariableName};\r\n`,this}});(0,l.H)("BABYLON.PowBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("value",ct.AutoDetect),this.registerInput("power",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"PowBlock"}get value(){return this._inputs[0]}get power(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = pow(${this.value.associatedVariableName}, ${this.power.associatedVariableName});\r\n`,this}});(0,l.H)("BABYLON.RandomNumberBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("seed",ct.AutoDetect),this.registerOutput("output",ct.Float),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ct.Vector2|ct.Vector3|ct.Vector4|ct.Color3|ct.Color4)}getClassName(){return"RandomNumberBlock"}get seed(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",i),e.compilationString+=this._declareOutput(t,e)+` = getRand(${this.seed.associatedVariableName}.xy);\r\n`,this}});(0,l.H)("BABYLON.ArcTan2Block",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("x",ct.Float),this.registerInput("y",ct.Float),this.registerOutput("output",ct.Float)}getClassName(){return"ArcTan2Block"}get x(){return this._inputs[0]}get y(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = atan(${this.x.associatedVariableName}, ${this.y.associatedVariableName});\r\n`,this}});(0,l.H)("BABYLON.SmoothStepBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("value",ct.AutoDetect),this.registerInput("edge0",ct.Float),this.registerInput("edge1",ct.Float),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"SmoothStepBlock"}get value(){return this._inputs[0]}get edge0(){return this._inputs[1]}get edge1(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = smoothstep(${this.edge0.associatedVariableName}, ${this.edge1.associatedVariableName}, ${this.value.associatedVariableName});\r\n`,this}});(0,l.H)("BABYLON.ReciprocalBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("input",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ReciprocalBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return this.input.type===ct.Matrix?e.compilationString+=this._declareOutput(t,e)+` = inverse(${this.input.associatedVariableName});\r\n`:e.compilationString+=this._declareOutput(t,e)+` = 1. / ${this.input.associatedVariableName};\r\n`,this}});(0,l.H)("BABYLON.ReplaceColorBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("value",ct.AutoDetect),this.registerInput("reference",ct.AutoDetect),this.registerInput("distance",ct.Float),this.registerInput("replacement",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(ct.Float),this._inputs[0].excludedConnectionPointTypes.push(ct.Matrix),this._inputs[1].excludedConnectionPointTypes.push(ct.Float),this._inputs[1].excludedConnectionPointTypes.push(ct.Matrix),this._inputs[3].excludedConnectionPointTypes.push(ct.Float),this._inputs[3].excludedConnectionPointTypes.push(ct.Matrix)}getClassName(){return"ReplaceColorBlock"}get value(){return this._inputs[0]}get reference(){return this._inputs[1]}get distance(){return this._inputs[2]}get replacement(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+";\r\n",e.compilationString+=`if (length(${this.value.associatedVariableName} - ${this.reference.associatedVariableName}) < ${this.distance.associatedVariableName}) {\r\n`,e.compilationString+=`${t.associatedVariableName} = ${this.replacement.associatedVariableName};\r\n`,e.compilationString+="} else {\r\n",e.compilationString+=`${t.associatedVariableName} = ${this.value.associatedVariableName};\r\n`,e.compilationString+="}\r\n",this}});var iT;(0,l.H)("BABYLON.PosterizeBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("value",ct.AutoDetect),this.registerInput("steps",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(ct.Matrix),this._inputs[1].excludedConnectionPointTypes.push(ct.Matrix)}getClassName(){return"PosterizeBlock"}get value(){return this._inputs[0]}get steps(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = floor(${this.value.associatedVariableName} / (1.0 / ${this.steps.associatedVariableName})) * (1.0 / ${this.steps.associatedVariableName});\r\n`,this}}),function(e){e[e.SawTooth=0]="SawTooth",e[e.Square=1]="Square",e[e.Triangle=2]="Triangle"}(iT||(iT={}));(0,l.H)("BABYLON.WaveBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.kind=iT.SawTooth,this.registerInput("input",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(ct.Matrix)}getClassName(){return"WaveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];switch(this.kind){case iT.SawTooth:e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName});\r\n`;break;case iT.Square:e.compilationString+=this._declareOutput(t,e)+` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName}));\r\n`;break;case iT.Triangle:e.compilationString+=this._declareOutput(t,e)+` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0;\r\n`}return this}serialize(){const e=super.serialize();return e.kind=this.kind,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.kind=e.kind}});class nT{get step(){return this._step}set step(e){this._step=e}get color(){return this._color}set color(e){this._color=e}constructor(e,t){this.step=e,this.color=t}}(0,l.H)("BABYLON.GradientBlock",class extends bt{colorStepsUpdated(){this.onValueChangedObservable.notifyObservers(this)}constructor(e){super(e,dt.Neutral),this.colorSteps=[new nT(0,a.Wo.Black()),new nT(1,a.Wo.White())],this.onValueChangedObservable=new r.y$,this.registerInput("gradient",ct.AutoDetect),this.registerOutput("output",ct.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ct.Float|ct.Vector2|ct.Vector3|ct.Vector4|ct.Color3|ct.Color4)}getClassName(){return"GradientBlock"}get gradient(){return this._inputs[0]}get output(){return this._outputs[0]}_writeColorConstant(e){const t=this.colorSteps[e];return`vec3(${t.color.r}, ${t.color.g}, ${t.color.b})`}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];if(!this.colorSteps.length||!this.gradient.connectedPoint)return void(e.compilationString+=this._declareOutput(t,e)+" = vec3(0., 0., 0.);\r\n");const i=e._getFreeVariableName("gradientTempColor"),n=e._getFreeVariableName("gradientTempPosition");e.compilationString+=`vec3 ${i} = ${this._writeColorConstant(0)};\r\n`,e.compilationString+=`float ${n};\r\n`;let s=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==ct.Float&&(s+=".x");for(let r=1;re.systemValue===Pt.View));t||(t=new Bt("view"),t.setAsSystemValue(Pt.View)),t.output.connectTo(this.view)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const n=this._getTexture(),s=n&&n.getTextureMatrix;i.setValue("SS_REFRACTION",s,!0),s&&(i.setValue(this._define3DName,n.isCube,!0),i.setValue(this._defineLODRefractionAlpha,n.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularRefraction,n.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem&&n.isCube?!n.invertZ:n.invertZ,!0),i.setValue("SS_LINKREFRACTIONTOTRANSPARENCY",this.linkRefractionWithTransparency,!0),i.setValue("SS_GAMMAREFRACTION",n.gammaSpace,!0),i.setValue("SS_RGBDREFRACTION",n.isRGBD,!0),i.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC",!!n.boundingBoxSize,!0),i.setValue("SS_USE_THICKNESS_AS_DEPTH",this.useThicknessAsDepth,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i){var n,s,r,o;super.bind(e,t,i);const a=this._getTexture();if(!a)return;a.isCube?e.setTexture(this._cubeSamplerName,a):e.setTexture(this._2DSamplerName,a),e.setMatrix(this._refractionMatrixName,a.getRefractionTextureMatrix());let l=1;a.isCube||a.depth&&(l=a.depth);const h=null!==(o=null!==(s=null===(n=this.volumeIndexOfRefraction.connectInputBlock)||void 0===n?void 0:n.value)&&void 0!==s?s:null===(r=this.indexOfRefractionConnectionPoint.connectInputBlock)||void 0===r?void 0:r.value)&&void 0!==o?o:1.5;e.setFloat4(this._vRefractionInfosName,a.level,1/h,l,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,a.getSize().width,a.lodGenerationScale,a.lodGenerationOffset,1/h);const c=a.getSize().width;if(e.setFloat2(this._vRefractionFilteringInfoName,c,S.R.Log2(c)),a.boundingBoxSize){const t=a;e.setVector3("vRefractionPosition",t.boundingBoxPosition),e.setVector3("vRefractionSize",t.boundingBoxSize)}}getCode(e){return e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),this._define3DName=e._getFreeDefineName("SS_REFRACTIONMAP_3D"),e._samplerDeclaration+=`#ifdef ${this._define3DName}\r\n`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName};\r\n`,e._samplerDeclaration+="#else\r\n",e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName};\r\n`,e._samplerDeclaration+="#endif\r\n",e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._defineLODRefractionAlpha=e._getFreeDefineName("SS_LODINREFRACTIONALPHA"),this._defineLinearSpecularRefraction=e._getFreeDefineName("SS_LINEARSPECULARREFRACTION"),this._defineOppositeZ=e._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ"),this._refractionMatrixName=e._getFreeVariableName("refractionMatrix"),e._emitUniformFromString(this._refractionMatrixName,"mat4"),e._emitFunction("sampleRefraction",`\n #ifdef ${this._define3DName}\n #define sampleRefraction(s, c) textureCube(s, c)\n #else\n #define sampleRefraction(s, c) texture2D(s, c)\n #endif\r\n`,`//${this.name}`),e._emitFunction("sampleRefractionLod",`\n #ifdef ${this._define3DName}\n #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l)\n #else\n #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l)\n #endif\r\n`,`//${this.name}`),this._vRefractionMicrosurfaceInfosName=e._getFreeVariableName("vRefractionMicrosurfaceInfos"),e._emitUniformFromString(this._vRefractionMicrosurfaceInfosName,"vec4"),this._vRefractionInfosName=e._getFreeVariableName("vRefractionInfos"),e._emitUniformFromString(this._vRefractionInfosName,"vec4"),this._vRefractionFilteringInfoName=e._getFreeVariableName("vRefractionFilteringInfo"),e._emitUniformFromString(this._vRefractionFilteringInfoName,"vec2"),e._emitUniformFromString("vRefractionPosition","vec3"),e._emitUniformFromString("vRefractionSize","vec3"),""}_buildBlock(e){return this._scene=e.sharedData.scene,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e=this.texture.isCube?`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}");\r\n`:`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}");\r\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\r\n`),e+=`${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency};\r\n`,e+=`${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY};\r\n`,e+=`${this._codeVariableName}.useThicknessAsDepth = ${this.useThicknessAsDepth};\r\n`,e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.linkRefractionWithTransparency=this.linkRefractionWithTransparency,e.invertRefractionY=this.invertRefractionY,e.useThicknessAsDepth=this.useThicknessAsDepth,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=yp.Parse(e.texture,t,i):this.texture=Le.Parse(e.texture,t,i)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth}}(0,oe.gn)([At("Link refraction to transparency",Et.Boolean,"ADVANCED",{notifiers:{update:!0}})],cT.prototype,"linkRefractionWithTransparency",void 0),(0,oe.gn)([At("Invert refraction Y",Et.Boolean,"ADVANCED",{notifiers:{update:!0}})],cT.prototype,"invertRefractionY",void 0),(0,oe.gn)([At("Use thickness as depth",Et.Boolean,"ADVANCED",{notifiers:{update:!0}})],cT.prototype,"useThicknessAsDepth",void 0),(0,l.H)("BABYLON.RefractionBlock",cT);class dT extends bt{constructor(e){super(e,dt.Fragment),this._isUnique=!0,this.registerInput("thickness",ct.Float,!1,dt.Fragment),this.registerInput("tintColor",ct.Color3,!0,dt.Fragment),this.registerInput("translucencyIntensity",ct.Float,!0,dt.Fragment),this.registerInput("translucencyDiffusionDist",ct.Color3,!0,dt.Fragment),this.registerInput("refraction",ct.Object,!0,dt.Fragment,new Wv("refraction",this,vt.Input,cT,"RefractionBlock")),this.registerOutput("subsurface",ct.Object,dt.Fragment,new Wv("subsurface",this,vt.Output,dT,"SubSurfaceBlock"))}initialize(e){e._excludeVariableName("subSurfaceOut"),e._excludeVariableName("vThicknessParam"),e._excludeVariableName("vTintColor"),e._excludeVariableName("vSubSurfaceIntensity")}getClassName(){return"SubSurfaceBlock"}get thickness(){return this._inputs[0]}get tintColor(){return this._inputs[1]}get translucencyIntensity(){return this._inputs[2]}get translucencyDiffusionDist(){return this._inputs[3]}get refraction(){return this._inputs[4]}get subsurface(){return this._outputs[0]}autoConfigure(){if(!this.thickness.isConnected){const e=new Bt("SubSurface thickness",dt.Fragment,ct.Float);e.value=0,e.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const n=this.translucencyDiffusionDist.isConnected||this.translucencyIntensity.isConnected;i.setValue("SUBSURFACE",n||this.refraction.isConnected,!0),i.setValue("SS_TRANSLUCENCY",n,!0),i.setValue("SS_THICKNESSANDMASK_TEXTURE",!1,!0),i.setValue("SS_REFRACTIONINTENSITY_TEXTURE",!1,!0),i.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE",!1,!0),i.setValue("SS_MASK_FROM_THICKNESS_TEXTURE",!1,!0),i.setValue("SS_USE_GLTF_TEXTURES",!1,!0)}static GetCode(e,t,i,n){var s,r,o,a,l,h,c,d,u,p,f,_,m,g,v,T;let S="";const E=(null==t?void 0:t.thickness.isConnected)?t.thickness.associatedVariableName:"0.",x=(null==t?void 0:t.tintColor.isConnected)?t.tintColor.associatedVariableName:"vec3(1.)",b=(null==t?void 0:t.translucencyIntensity.isConnected)?null==t?void 0:t.translucencyIntensity.associatedVariableName:"1.",C=(null==t?void 0:t.translucencyDiffusionDist.isConnected)?null==t?void 0:t.translucencyDiffusionDist.associatedVariableName:"vec3(1.)",y=(null==t?void 0:t.refraction.isConnected)?null===(s=null==t?void 0:t.refraction.connectedPoint)||void 0===s?void 0:s.ownerBlock:null,A=(null==y?void 0:y.tintAtDistance.isConnected)?y.tintAtDistance.associatedVariableName:"1.",R=(null==y?void 0:y.intensity.isConnected)?y.intensity.associatedVariableName:"1.",P=(null==y?void 0:y.view.isConnected)?y.view.associatedVariableName:"";return S+=null!==(r=null==y?void 0:y.getCode(e))&&void 0!==r?r:"",S+=`subSurfaceOutParams subSurfaceOut;\n\n #ifdef SUBSURFACE\n vec2 vThicknessParam = vec2(0., ${E});\n vec4 vTintColor = vec4(${x}, ${A});\n vec3 vSubSurfaceIntensity = vec3(${R}, ${b}, 0.);\n\n subSurfaceBlock(\n vSubSurfaceIntensity,\n vThicknessParam,\n vTintColor,\n normalW,\n specularEnvironmentReflectance,\n #ifdef SS_THICKNESSANDMASK_TEXTURE\n vec4(0.),\n #endif\n #ifdef REFLECTION\n #ifdef SS_TRANSLUCENCY\n ${null==i?void 0:i._reflectionMatrixName},\n #ifdef USESPHERICALFROMREFLECTIONMAP\n #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n reflectionOut.irradianceVector,\n #endif\n #if defined(REALTIME_FILTERING)\n ${null==i?void 0:i._cubeSamplerName},\n ${null==i?void 0:i._vReflectionFilteringInfoName},\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 ${n}.xyz,\n viewDirectionW,\n ${P},\n ${null!==(o=null==y?void 0:y._vRefractionInfosName)&&void 0!==o?o:""},\n ${null!==(a=null==y?void 0:y._refractionMatrixName)&&void 0!==a?a:""},\n ${null!==(l=null==y?void 0:y._vRefractionMicrosurfaceInfosName)&&void 0!==l?l:""},\n vLightingIntensity,\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n alpha,\n #endif\n #ifdef ${null!==(h=null==y?void 0:y._defineLODRefractionAlpha)&&void 0!==h?h:"IGNORE"}\n NdotVUnclamped,\n #endif\n #ifdef ${null!==(c=null==y?void 0:y._defineLinearSpecularRefraction)&&void 0!==c?c:"IGNORE"}\n roughness,\n #endif\n alphaG,\n #ifdef ${null!==(d=null==y?void 0:y._define3DName)&&void 0!==d?d:"IGNORE"}\n ${null!==(u=null==y?void 0:y._cubeSamplerName)&&void 0!==u?u:""},\n #else\n ${null!==(p=null==y?void 0:y._2DSamplerName)&&void 0!==p?p:""},\n #endif\n #ifndef LODBASEDMICROSFURACE\n #ifdef ${null!==(f=null==y?void 0:y._define3DName)&&void 0!==f?f:"IGNORE"}\n ${null!==(_=null==y?void 0:y._cubeSamplerName)&&void 0!==_?_:""},\n ${null!==(m=null==y?void 0:y._cubeSamplerName)&&void 0!==m?m:""},\n #else\n ${null!==(g=null==y?void 0:y._2DSamplerName)&&void 0!==g?g:""},\n ${null!==(v=null==y?void 0:y._2DSamplerName)&&void 0!==v?v:""},\n #endif\n #endif\n #ifdef ANISOTROPIC\n anisotropicOut,\n #endif\n #ifdef REALTIME_FILTERING\n ${null!==(T=null==y?void 0:y._vRefractionFilteringInfoName)&&void 0!==T?T:""},\n #endif\n #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\n vRefractionPosition,\n vRefractionSize,\n #endif\n #endif\n #ifdef SS_TRANSLUCENCY\n ${C},\n #endif\n subSurfaceOut\n );\n\n #ifdef SS_REFRACTION\n surfaceAlbedo = subSurfaceOut.surfaceAlbedo;\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n alpha = subSurfaceOut.alpha;\n #endif\n #endif\n #else\n subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance;\n #endif\r\n`,S}_buildBlock(e){return e.target===dt.Fragment&&e.sharedData.blocksWithDefines.push(this),this}}(0,l.H)("BABYLON.SubSurfaceBlock",dT);const uT={ambientClr:["finalAmbient",""],diffuseDir:["finalDiffuse",""],specularDir:["finalSpecularScaled","!defined(UNLIT) && defined(SPECULARTERM)"],clearcoatDir:["finalClearCoatScaled","!defined(UNLIT) && defined(CLEARCOAT)"],sheenDir:["finalSheenScaled","!defined(UNLIT) && defined(SHEEN)"],diffuseInd:["finalIrradiance","!defined(UNLIT) && defined(REFLECTION)"],specularInd:["finalRadianceScaled","!defined(UNLIT) && defined(REFLECTION)"],clearcoatInd:["clearcoatOut.finalClearCoatRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(CLEARCOAT)"],sheenInd:["sheenOut.finalSheenRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(SHEEN) && defined(ENVIRONMENTBRDF)"],refraction:["subSurfaceOut.finalRefraction","!defined(UNLIT) && defined(SS_REFRACTION)"],lighting:["finalColor.rgb",""],shadow:["shadow",""],alpha:["alpha",""]};class pT extends bt{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,console.error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?dt.Fragment:dt.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?dt.Fragment:dt.Vertex}constructor(e){super(e,dt.VertexAndFragment),this._environmentBRDFTexture=null,this._metallicReflectanceColor=a.Wo.White(),this._metallicF0Factor=1,this.directIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.lightFalloff=0,this.useAlphaTest=!1,this.alphaTestCutoff=.5,this.useAlphaBlending=!1,this.useRadianceOverAlpha=!0,this.useSpecularOverAlpha=!0,this.enableSpecularAntiAliasing=!1,this.realTimeFiltering=!1,this.realTimeFilteringQuality=8,this.useEnergyConservation=!0,this.useRadianceOcclusion=!0,this.useHorizonOcclusion=!0,this.unlit=!1,this.forceNormalForward=!1,this.generateOnlyFragmentCode=!1,this.debugMode=0,this.debugLimit=0,this.debugFactor=1,this._isUnique=!0,this.registerInput("worldPosition",ct.Vector4,!1,dt.Vertex),this.registerInput("worldNormal",ct.Vector4,!1,dt.Fragment),this.registerInput("view",ct.Matrix,!1),this.registerInput("cameraPosition",ct.Vector3,!1,dt.Fragment),this.registerInput("perturbedNormal",ct.Vector4,!0,dt.Fragment),this.registerInput("baseColor",ct.Color3,!0,dt.Fragment),this.registerInput("metallic",ct.Float,!1,dt.Fragment),this.registerInput("roughness",ct.Float,!1,dt.Fragment),this.registerInput("ambientOcc",ct.Float,!0,dt.Fragment),this.registerInput("opacity",ct.Float,!0,dt.Fragment),this.registerInput("indexOfRefraction",ct.Float,!0,dt.Fragment),this.registerInput("ambientColor",ct.Color3,!0,dt.Fragment),this.registerInput("reflection",ct.Object,!0,dt.Fragment,new Wv("reflection",this,vt.Input,aT,"ReflectionBlock")),this.registerInput("clearcoat",ct.Object,!0,dt.Fragment,new Wv("clearcoat",this,vt.Input,lT,"ClearCoatBlock")),this.registerInput("sheen",ct.Object,!0,dt.Fragment,new Wv("sheen",this,vt.Input,rT,"SheenBlock")),this.registerInput("subsurface",ct.Object,!0,dt.Fragment,new Wv("subsurface",this,vt.Input,dT,"SubSurfaceBlock")),this.registerInput("anisotropy",ct.Object,!0,dt.Fragment,new Wv("anisotropy",this,vt.Input,oT,"AnisotropyBlock")),this.registerInput("iridescence",ct.Object,!0,dt.Fragment,new Wv("iridescence",this,vt.Input,hT,"IridescenceBlock")),this.registerOutput("ambientClr",ct.Color3,dt.Fragment),this.registerOutput("diffuseDir",ct.Color3,dt.Fragment),this.registerOutput("specularDir",ct.Color3,dt.Fragment),this.registerOutput("clearcoatDir",ct.Color3,dt.Fragment),this.registerOutput("sheenDir",ct.Color3,dt.Fragment),this.registerOutput("diffuseInd",ct.Color3,dt.Fragment),this.registerOutput("specularInd",ct.Color3,dt.Fragment),this.registerOutput("clearcoatInd",ct.Color3,dt.Fragment),this.registerOutput("sheenInd",ct.Color3,dt.Fragment),this.registerOutput("refraction",ct.Color3,dt.Fragment),this.registerOutput("lighting",ct.Color3,dt.Fragment),this.registerOutput("shadow",ct.Float,dt.Fragment),this.registerOutput("alpha",ct.Float,dt.Fragment)}initialize(e){e._excludeVariableName("vLightingIntensity"),e._excludeVariableName("geometricNormalW"),e._excludeVariableName("normalW"),e._excludeVariableName("faceNormal"),e._excludeVariableName("albedoOpacityOut"),e._excludeVariableName("surfaceAlbedo"),e._excludeVariableName("alpha"),e._excludeVariableName("aoOut"),e._excludeVariableName("baseColor"),e._excludeVariableName("reflectivityOut"),e._excludeVariableName("microSurface"),e._excludeVariableName("roughness"),e._excludeVariableName("NdotVUnclamped"),e._excludeVariableName("NdotV"),e._excludeVariableName("alphaG"),e._excludeVariableName("AARoughnessFactors"),e._excludeVariableName("environmentBrdf"),e._excludeVariableName("ambientMonochrome"),e._excludeVariableName("seo"),e._excludeVariableName("eho"),e._excludeVariableName("environmentRadiance"),e._excludeVariableName("irradianceVector"),e._excludeVariableName("environmentIrradiance"),e._excludeVariableName("diffuseBase"),e._excludeVariableName("specularBase"),e._excludeVariableName("preInfo"),e._excludeVariableName("info"),e._excludeVariableName("shadow"),e._excludeVariableName("finalDiffuse"),e._excludeVariableName("finalAmbient"),e._excludeVariableName("ambientOcclusionForDirectDiffuse"),e._excludeVariableName("finalColor"),e._excludeVariableName("vClipSpacePosition"),e._excludeVariableName("vDebugMode")}getClassName(){return"PBRMetallicRoughnessBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get view(){return this._inputs[2]}get cameraPosition(){return this._inputs[3]}get perturbedNormal(){return this._inputs[4]}get baseColor(){return this._inputs[5]}get metallic(){return this._inputs[6]}get roughness(){return this._inputs[7]}get ambientOcc(){return this._inputs[8]}get opacity(){return this._inputs[9]}get indexOfRefraction(){return this._inputs[10]}get ambientColor(){return this._inputs[11]}get reflection(){return this._inputs[12]}get clearcoat(){return this._inputs[13]}get sheen(){return this._inputs[14]}get subsurface(){return this._inputs[15]}get anisotropy(){return this._inputs[16]}get iridescence(){return this._inputs[17]}get ambientClr(){return this._outputs[0]}get diffuseDir(){return this._outputs[1]}get specularDir(){return this._outputs[2]}get clearcoatDir(){return this._outputs[3]}get sheenDir(){return this._outputs[4]}get diffuseInd(){return this._outputs[5]}get specularInd(){return this._outputs[6]}get clearcoatInd(){return this._outputs[7]}get sheenInd(){return this._outputs[8]}get refraction(){return this._outputs[9]}get lighting(){return this._outputs[10]}get shadow(){return this._outputs[11]}get alpha(){return this._outputs[12]}autoConfigure(e){if(!this.cameraPosition.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===Pt.CameraPosition));t||(t=new Bt("cameraPosition"),t.setAsSystemValue(Pt.CameraPosition)),t.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===Pt.View));t||(t=new Bt("view"),t.setAsSystemValue(Pt.View)),t.output.connectTo(this.view)}}prepareDefines(e,t,i){i.setValue("PBR",!0),i.setValue("METALLICWORKFLOW",!0),i.setValue("DEBUGMODE",this.debugMode,!0),i.setValue("NORMALXYSCALE",!0),i.setValue("BUMP",this.perturbedNormal.isConnected,!0),i.setValue("LODBASEDMICROSFURACE",this._scene.getEngine().getCaps().textureLOD),i.setValue("ALBEDO",!1,!0),i.setValue("OPACITY",this.opacity.isConnected,!0),i.setValue("AMBIENT",!0,!0),i.setValue("AMBIENTINGRAYSCALE",!1,!0),i.setValue("REFLECTIVITY",!1,!0),i.setValue("AOSTOREINMETALMAPRED",!1,!0),i.setValue("METALLNESSSTOREINMETALMAPBLUE",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPALPHA",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPGREEN",!1,!0),this.lightFalloff===M_.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===M_.LIGHTFALLOFF_GLTF?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!0)):(i.setValue("USEPHYSICALLIGHTFALLOFF",!0),i.setValue("USEGLTFLIGHTFALLOFF",!1));const n=this.alphaTestCutoff.toString();i.setValue("ALPHABLEND",this.useAlphaBlending,!0),i.setValue("ALPHAFROMALBEDO",!1,!0),i.setValue("ALPHATEST",this.useAlphaTest,!0),i.setValue("ALPHATESTVALUE",n.indexOf(".")<0?n+".":n,!0),i.setValue("OPACITYRGB",!1,!0),i.setValue("RADIANCEOVERALPHA",this.useRadianceOverAlpha,!0),i.setValue("SPECULAROVERALPHA",this.useSpecularOverAlpha,!0),i.setValue("SPECULARAA",this._scene.getEngine().getCaps().standardDerivatives&&this.enableSpecularAntiAliasing,!0),i.setValue("REALTIME_FILTERING",this.realTimeFiltering,!0);const s=e.getScene();if(s.getEngine()._features.needTypeSuffixInShaderConstants?i.setValue("NUM_SAMPLES",this.realTimeFilteringQuality+"u",!0):i.setValue("NUM_SAMPLES",""+this.realTimeFilteringQuality,!0),i.setValue("BRDF_V_HEIGHT_CORRELATED",!0),i.setValue("MS_BRDF_ENERGY_CONSERVATION",this.useEnergyConservation,!0),i.setValue("RADIANCEOCCLUSION",this.useRadianceOcclusion,!0),i.setValue("HORIZONOCCLUSION",this.useHorizonOcclusion,!0),i.setValue("UNLIT",this.unlit,!0),i.setValue("FORCENORMALFORWARD",this.forceNormalForward,!0),this._environmentBRDFTexture&&Bs.ReflectionTextureEnabled?(i.setValue("ENVIRONMENTBRDF",!0),i.setValue("ENVIRONMENTBRDF_RGBD",this._environmentBRDFTexture.isRGBD,!0)):(i.setValue("ENVIRONMENTBRDF",!1),i.setValue("ENVIRONMENTBRDF_RGBD",!1)),i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i),i._areLightsDirty)if(this.light){const t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};It.G.PrepareDefinesForLight(s,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else It.G.PrepareDefinesForLights(s,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,It.G.PrepareDefinesForMultiview(s,i)}updateUniformsAndSamples(e,t,i,n){for(let s=0;s=0;It.G.PrepareUniformsAndSamplersForLight(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],n,t)}}isReady(e,t,i){return!(this._environmentBRDFTexture&&!this._environmentBRDFTexture.isReady())&&!(i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())}bind(e,t,i){var n,s;if(!i)return;const r=i.getScene();this.light?It.G.BindLight(this.light,this._lightId,r,e,!0):It.G.BindLights(r,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);const o=this._scene.ambientColor;o&&e.setColor3("ambientFromScene",o);const l=r.useRightHandedSystem===(null!=r._mirroredCameraPosition);e.setFloat(this._invertNormalName,l?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);const h=null!==(s=null===(n=this.indexOfRefraction.connectInputBlock)||void 0===n?void 0:n.value)&&void 0!==s?s:1.5,c=Math.pow((h-1)/(h+1),2);this._metallicReflectanceColor.scaleToRef(c*this._metallicF0Factor,a.zZ.Color3[0]);const d=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,a.zZ.Color3[0],d),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_injectVertexCode(e){var t,i;const n=this.worldPosition,s=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",s,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",s,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const r="v_"+n.associatedVariableName;e._emitVaryingFromString(r,"vec4")&&(e.compilationString+=`${r} = ${n.associatedVariableName};\r\n`);const o=this.reflection.isConnected?null===(t=this.reflection.connectedPoint)||void 0===t?void 0:t.ownerBlock:null;o&&(o.viewConnectionPoint=this.view),e.compilationString+=null!==(i=null==o?void 0:o.handleVertexSide(e))&&void 0!==i?i:"",e._emitVaryingFromString("vClipSpacePosition","vec4","defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+="#if DEBUGMODE > 0\r\n",e._injectAtEnd+="vClipSpacePosition = gl_Position;\r\n",e._injectAtEnd+="#endif\r\n"),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",s,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:n.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${n.associatedVariableName};\r\n`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName};\r\n`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",s,{repeatKey:"maxSimultaneousLights"}))}_getAlbedoOpacityCode(){let e="albedoOpacityOutParams albedoOpacityOut;\r\n";return e+=`albedoOpacityBlock(\n vec4(${this.baseColor.isConnected?this.baseColor.associatedVariableName:"vec3(1.)"}, 1.),\n #ifdef ALBEDO\n vec4(1.),\n vec2(1., 1.),\n #endif\n #ifdef OPACITY\n vec4(${this.opacity.isConnected?this.opacity.associatedVariableName:"1."}),\n vec2(1., 1.),\n #endif\n albedoOpacityOut\n );\n\n vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo;\n float alpha = albedoOpacityOut.alpha;\r\n`,e}_getAmbientOcclusionCode(){let e="ambientOcclusionOutParams aoOut;\r\n";return e+=`ambientOcclusionBlock(\n #ifdef AMBIENT\n vec3(${this.ambientOcc.isConnected?this.ambientOcc.associatedVariableName:"1."}),\n vec4(0., 1.0, 1.0, 0.),\n #endif\n aoOut\n );\r\n`,e}_getReflectivityCode(e){let t="reflectivityOutParams reflectivityOut;\r\n";return this._vMetallicReflectanceFactorsName=e._getFreeVariableName("vMetallicReflectanceFactors"),e._emitUniformFromString(this._vMetallicReflectanceFactorsName,"vec4"),t+=`vec3 baseColor = surfaceAlbedo;\n\n reflectivityBlock(\n vec4(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.),\n #ifdef METALLICWORKFLOW\n surfaceAlbedo,\n ${this._vMetallicReflectanceFactorsName},\n #endif\n #ifdef REFLECTIVITY\n vec3(0., 0., 1.),\n vec4(1.),\n #endif\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n aoOut.ambientOcclusionColor,\n #endif\n #ifdef MICROSURFACEMAP\n microSurfaceTexel, <== not handled!\n #endif\n reflectivityOut\n );\n\n float microSurface = reflectivityOut.microSurface;\n float roughness = reflectivityOut.roughness;\n\n #ifdef METALLICWORKFLOW\n surfaceAlbedo = reflectivityOut.surfaceAlbedo;\n #endif\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor;\n #endif\r\n`,t}_buildBlock(e){var t,i,n,s,r,o,a,l,h,c,d,u,p,f,_,m,g,v,T,S,E,x,b,C,y,A,R,P,I,M,O,D,N,F,w,L,B,U,V,k,G;super._buildBlock(e),this._scene=e.sharedData.scene,this._environmentBRDFTexture||(this._environmentBRDFTexture=zp(this._scene));const z=this.reflection.isConnected?null===(t=this.reflection.connectedPoint)||void 0===t?void 0:t.ownerBlock:null;if(z&&(z.worldPositionConnectionPoint=this.worldPosition,z.cameraPositionConnectionPoint=this.cameraPosition,z.worldNormalConnectionPoint=this.worldNormal,z.viewConnectionPoint=this.view),e.target!==dt.Fragment)return this._injectVertexCode(e),this;e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this);const W=`//${this.name}`,H=this.perturbedNormal;let X=this.worldPosition.associatedVariableName;this.generateOnlyFragmentCode?(X=e._getFreeVariableName("globalWorldPos"),e._emitFunction("pbr_globalworldpos",`vec3 ${X};\r\n`,W),e.compilationString+=`${X} = ${this.worldPosition.associatedVariableName}.xyz;\r\n`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",W,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${this.worldPosition.associatedVariableName}`:void 0}),e.compilationString+="#if DEBUGMODE > 0\r\n",e.compilationString+="vec4 vClipSpacePosition = vec4((vec2(gl_FragCoord.xy) / vec2(1.0)) * 2.0 - 1.0, 0.0, 1.0);\r\n",e.compilationString+="#endif\r\n"):X="v_"+X,this._environmentBrdfSamplerName=e._getFreeVariableName("environmentBrdfSampler"),e._emit2DSampler(this._environmentBrdfSamplerName),e.sharedData.hints.needAlphaBlending=e.sharedData.hints.needAlphaBlending||this.useAlphaBlending,e.sharedData.hints.needAlphaTesting=e.sharedData.hints.needAlphaTesting||this.useAlphaTest,e._emitExtension("lod","#extension GL_EXT_shader_texture_lod : enable","defined(LODBASEDMICROSFURACE)"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitUniformFromString("vDebugMode","vec2","defined(IGNORE) || DEBUGMODE > 0"),e._emitUniformFromString("ambientFromScene","vec3"),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity"),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",W,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",W,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),e._emitFunctionFromInclude("helperFunctions",W),e._emitFunctionFromInclude("importanceSampling",W),e._emitFunctionFromInclude("pbrHelperFunctions",W),e._emitFunctionFromInclude("imageProcessingDeclaration",W),e._emitFunctionFromInclude("imageProcessingFunctions",W),e._emitFunctionFromInclude("shadowsFragmentFunctions",W,{replaceStrings:[{search:/vPositionW/g,replace:X+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingSetupFunctions",W,{replaceStrings:[{search:/vPositionW/g,replace:X+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions",W),e._emitFunctionFromInclude("pbrBRDFFunctions",W,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(i=null==z?void 0:z._defineSkyboxName)&&void 0!==i?i:"REFLECTIONMAP_SKYBOX"}]}),e._emitFunctionFromInclude("hdrFilteringFunctions",W),e._emitFunctionFromInclude("pbrDirectLightingFunctions",W,{replaceStrings:[{search:/vPositionW/g,replace:X+".xyz"}]}),e._emitFunctionFromInclude("pbrIBLFunctions",W),e._emitFunctionFromInclude("pbrBlockAlbedoOpacity",W),e._emitFunctionFromInclude("pbrBlockReflectivity",W),e._emitFunctionFromInclude("pbrBlockAmbientOcclusion",W),e._emitFunctionFromInclude("pbrBlockAlphaFresnel",W),e._emitFunctionFromInclude("pbrBlockAnisotropic",W),e._emitUniformFromString("vLightingIntensity","vec4"),(null==z?void 0:z.generateOnlyFragmentCode)&&(e.compilationString+=z.handleVertexSide(e)),this._vNormalWName=e._getFreeVariableName("vNormalW"),e.compilationString+=`vec4 ${this._vNormalWName} = normalize(${this.worldNormal.associatedVariableName});\r\n`,e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${X}.xyz);\r\n`),e.compilationString+=`vec3 geometricNormalW = ${this._vNormalWName}.xyz;\r\n`,e.compilationString+=`vec3 normalW = ${H.isConnected?"normalize("+H.associatedVariableName+".xyz)":"geometricNormalW"};\r\n`,this._invertNormalName=e._getFreeVariableName("invertNormal"),e._emitUniformFromString(this._invertNormalName,"float"),e.compilationString+=e._emitCodeFromInclude("pbrBlockNormalFinal",W,{replaceStrings:[{search:/vPositionW/g,replace:X+".xyz"},{search:/vEyePosition.w/g,replace:this._invertNormalName}]}),e.compilationString+=this._getAlbedoOpacityCode(),e.compilationString+=e._emitCodeFromInclude("depthPrePass",W),e.compilationString+=this._getAmbientOcclusionCode(),e.compilationString+=e._emitCodeFromInclude("pbrBlockLightmapInit",W),e.compilationString+="#ifdef UNLIT\n vec3 diffuseBase = vec3(1., 1., 1.);\n #else\r\n",e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",W,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(n=null==z?void 0:z._defineSkyboxName)&&void 0!==n?n:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:null!==(s=null==z?void 0:z._define3DName)&&void 0!==s?s:"REFLECTIONMAP_3D"}]});const Y=this.anisotropy.isConnected?null===(r=this.anisotropy.connectedPoint)||void 0===r?void 0:r.ownerBlock:null;Y&&(Y.worldPositionConnectionPoint=this.worldPosition,Y.worldNormalConnectionPoint=this.worldNormal,e.compilationString+=Y.getCode(e,!this.perturbedNormal.isConnected)),z&&z.hasTexture&&(e.compilationString+=z.getCode(e,Y?"anisotropicOut.anisotropicNormal":"normalW")),e._emitFunctionFromInclude("pbrBlockReflection",W,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:null!==(o=null==z?void 0:z._define3DName)&&void 0!==o?o:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(a=null==z?void 0:z._defineOppositeZ)&&void 0!==a?a:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:null!==(l=null==z?void 0:z._defineProjectionName)&&void 0!==l?l:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(h=null==z?void 0:z._defineSkyboxName)&&void 0!==h?h:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:null!==(c=null==z?void 0:z._defineLODReflectionAlpha)&&void 0!==c?c:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(d=null==z?void 0:z._defineLinearSpecularReflection)&&void 0!==d?d:"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:null!==(u=null==z?void 0:z._vReflectionFilteringInfoName)&&void 0!==u?u:"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",W,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:this._vMetallicReflectanceFactorsName}]});const j=this.sheen.isConnected?null===(p=this.sheen.connectedPoint)||void 0===p?void 0:p.ownerBlock:null;j&&(e.compilationString+=j.getCode(z)),e._emitFunctionFromInclude("pbrBlockSheen",W,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:null!==(f=null==z?void 0:z._define3DName)&&void 0!==f?f:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(_=null==z?void 0:z._defineSkyboxName)&&void 0!==_?_:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:null!==(m=null==z?void 0:z._defineLODReflectionAlpha)&&void 0!==m?m:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(g=null==z?void 0:z._defineLinearSpecularReflection)&&void 0!==g?g:"LINEARSPECULARREFLECTION"}]});const K=this.iridescence.isConnected?null===(v=this.iridescence.connectedPoint)||void 0===v?void 0:v.ownerBlock:null;e.compilationString+=hT.GetCode(K),e._emitFunctionFromInclude("pbrBlockIridescence",W,{replaceStrings:[]});const q=this.clearcoat.isConnected?null===(T=this.clearcoat.connectedPoint)||void 0===T?void 0:T.ownerBlock:null,$=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,Q=this.perturbedNormal.isConnected&&(null===(E=(null===(S=this.perturbedNormal.connectedPoint)||void 0===S?void 0:S.ownerBlock).worldTangent)||void 0===E?void 0:E.isConnected),Z=this.anisotropy.isConnected&&(null===(x=this.anisotropy.connectedPoint)||void 0===x?void 0:x.ownerBlock).worldTangent.isConnected;let J=Q||!this.perturbedNormal.isConnected&&Z;e.compilationString+=lT.GetCode(e,q,z,X,$,J,this.worldNormal.associatedVariableName),$&&(J=null!==(b=null==q?void 0:q.worldTangent.isConnected)&&void 0!==b&&b),e._emitFunctionFromInclude("pbrBlockClearcoat",W,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:null!==(C=null==z?void 0:z._define3DName)&&void 0!==C?C:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(y=null==z?void 0:z._defineOppositeZ)&&void 0!==y?y:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:null!==(A=null==z?void 0:z._defineProjectionName)&&void 0!==A?A:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(R=null==z?void 0:z._defineSkyboxName)&&void 0!==R?R:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:null!==(P=null==z?void 0:z._defineLODReflectionAlpha)&&void 0!==P?P:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(I=null==z?void 0:z._defineLinearSpecularReflection)&&void 0!==I?I:"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:J?"defined(TANGENT)":"defined(IGNORE)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance",W,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(M=null==z?void 0:z._defineSkyboxName)&&void 0!==M?M:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:null!==(O=null==z?void 0:z._define3DName)&&void 0!==O?O:"REFLECTIONMAP_3D"}]});const ee=this.subsurface.isConnected?null===(D=this.subsurface.connectedPoint)||void 0===D?void 0:D.ownerBlock:null,te=this.subsurface.isConnected?null===(F=(null===(N=this.subsurface.connectedPoint)||void 0===N?void 0:N.ownerBlock).refraction.connectedPoint)||void 0===F?void 0:F.ownerBlock:null;te&&(te.viewConnectionPoint=this.view,te.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=dT.GetCode(e,ee,z,X),e._emitFunctionFromInclude("pbrBlockSubSurface",W,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:null!==(w=null==z?void 0:z._define3DName)&&void 0!==w?w:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(L=null==z?void 0:z._defineOppositeZ)&&void 0!==L?L:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:null!==(B=null==z?void 0:z._defineProjectionName)&&void 0!==B?B:"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:null!==(U=null==te?void 0:te._define3DName)&&void 0!==U?U:"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:null!==(V=null==te?void 0:te._defineLODRefractionAlpha)&&void 0!==V?V:"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:null!==(k=null==te?void 0:te._defineLinearSpecularRefraction)&&void 0!==k?k:"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:null!==(G=null==te?void 0:te._defineOppositeZ)&&void 0!==G?G:"SS_REFRACTIONMAP_OPPOSITEZ"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockDirectLighting",W),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",W,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",W,{repeatKey:"maxSimultaneousLights"}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",W),e.compilationString+="#endif\r\n";const ie=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:"vec3(0., 0., 0.)";let ne=M_.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();-1===ne.indexOf(".")&&(ne+="."),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",W,{replaceStrings:[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:/vAmbientColor/g,replace:ie+" * ambientFromScene"},{search:/vAmbientInfos\.w/g,replace:ne}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalColorComposition",W,{replaceStrings:[{search:/finalEmissive/g,replace:"vec3(0.)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockImageProcessing",W,{replaceStrings:[{search:/visibility/g,replace:"1."}]}),e.compilationString+=e._emitCodeFromInclude("pbrDebug",W,{replaceStrings:[{search:/vNormalW/g,replace:this._vNormalWName},{search:/vPositionW/g,replace:X},{search:/albedoTexture\.rgb;/g,replace:"vec3(1.);\r\ngl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb);\r\n"}]});for(const se of this._outputs)if(se.hasEndpoints){const t=uT[se.name];if(t){const[i,n]=t;n&&(e.compilationString+=`#if ${n}\r\n`),e.compilationString+=`${this._declareOutput(se,e)} = ${i};\r\n`,n&&(e.compilationString+="#else\r\n",e.compilationString+=`${this._declareOutput(se,e)} = vec3(0.);\r\n`,e.compilationString+="#endif\r\n")}else console.error(`There's no remapping for the ${se.name} end point! No code generated`)}return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.lightFalloff = ${this.lightFalloff};\r\n`,e+=`${this._codeVariableName}.useAlphaTest = ${this.useAlphaTest};\r\n`,e+=`${this._codeVariableName}.alphaTestCutoff = ${this.alphaTestCutoff};\r\n`,e+=`${this._codeVariableName}.useAlphaBlending = ${this.useAlphaBlending};\r\n`,e+=`${this._codeVariableName}.useRadianceOverAlpha = ${this.useRadianceOverAlpha};\r\n`,e+=`${this._codeVariableName}.useSpecularOverAlpha = ${this.useSpecularOverAlpha};\r\n`,e+=`${this._codeVariableName}.enableSpecularAntiAliasing = ${this.enableSpecularAntiAliasing};\r\n`,e+=`${this._codeVariableName}.realTimeFiltering = ${this.realTimeFiltering};\r\n`,e+=`${this._codeVariableName}.realTimeFilteringQuality = ${this.realTimeFilteringQuality};\r\n`,e+=`${this._codeVariableName}.useEnergyConservation = ${this.useEnergyConservation};\r\n`,e+=`${this._codeVariableName}.useRadianceOcclusion = ${this.useRadianceOcclusion};\r\n`,e+=`${this._codeVariableName}.useHorizonOcclusion = ${this.useHorizonOcclusion};\r\n`,e+=`${this._codeVariableName}.unlit = ${this.unlit};\r\n`,e+=`${this._codeVariableName}.forceNormalForward = ${this.forceNormalForward};\r\n`,e+=`${this._codeVariableName}.debugMode = ${this.debugMode};\r\n`,e+=`${this._codeVariableName}.debugLimit = ${this.debugLimit};\r\n`,e+=`${this._codeVariableName}.debugFactor = ${this.debugFactor};\r\n`,e}serialize(){const e=super.serialize();return this.light&&(e.lightId=this.light.id),e.lightFalloff=this.lightFalloff,e.useAlphaTest=this.useAlphaTest,e.alphaTestCutoff=this.alphaTestCutoff,e.useAlphaBlending=this.useAlphaBlending,e.useRadianceOverAlpha=this.useRadianceOverAlpha,e.useSpecularOverAlpha=this.useSpecularOverAlpha,e.enableSpecularAntiAliasing=this.enableSpecularAntiAliasing,e.realTimeFiltering=this.realTimeFiltering,e.realTimeFilteringQuality=this.realTimeFilteringQuality,e.useEnergyConservation=this.useEnergyConservation,e.useRadianceOcclusion=this.useRadianceOcclusion,e.useHorizonOcclusion=this.useHorizonOcclusion,e.unlit=this.unlit,e.forceNormalForward=this.forceNormalForward,e.debugMode=this.debugMode,e.debugLimit=this.debugLimit,e.debugFactor=this.debugFactor,e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){var n,s;super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.lightFalloff=null!==(n=e.lightFalloff)&&void 0!==n?n:0,this.useAlphaTest=e.useAlphaTest,this.alphaTestCutoff=e.alphaTestCutoff,this.useAlphaBlending=e.useAlphaBlending,this.useRadianceOverAlpha=e.useRadianceOverAlpha,this.useSpecularOverAlpha=e.useSpecularOverAlpha,this.enableSpecularAntiAliasing=e.enableSpecularAntiAliasing,this.realTimeFiltering=!!e.realTimeFiltering,this.realTimeFilteringQuality=null!==(s=e.realTimeFilteringQuality)&&void 0!==s?s:8,this.useEnergyConservation=e.useEnergyConservation,this.useRadianceOcclusion=e.useRadianceOcclusion,this.useHorizonOcclusion=e.useHorizonOcclusion,this.unlit=e.unlit,this.forceNormalForward=!!e.forceNormalForward,this.debugMode=e.debugMode,this.debugLimit=e.debugLimit,this.debugFactor=e.debugFactor,this.generateOnlyFragmentCode=!!e.generateOnlyFragmentCode,this._setTarget()}}(0,oe.gn)([At("Direct lights",Et.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],pT.prototype,"directIntensity",void 0),(0,oe.gn)([At("Environment lights",Et.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],pT.prototype,"environmentIntensity",void 0),(0,oe.gn)([At("Specular highlights",Et.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],pT.prototype,"specularIntensity",void 0),(0,oe.gn)([At("Light falloff",Et.List,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:M_.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:M_.LIGHTFALLOFF_GLTF},{label:"Standard",value:M_.LIGHTFALLOFF_STANDARD}]})],pT.prototype,"lightFalloff",void 0),(0,oe.gn)([At("Alpha Testing",Et.Boolean,"OPACITY")],pT.prototype,"useAlphaTest",void 0),(0,oe.gn)([At("Alpha CutOff",Et.Float,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],pT.prototype,"alphaTestCutoff",void 0),(0,oe.gn)([At("Alpha blending",Et.Boolean,"OPACITY")],pT.prototype,"useAlphaBlending",void 0),(0,oe.gn)([At("Radiance over alpha",Et.Boolean,"RENDERING",{notifiers:{update:!0}})],pT.prototype,"useRadianceOverAlpha",void 0),(0,oe.gn)([At("Specular over alpha",Et.Boolean,"RENDERING",{notifiers:{update:!0}})],pT.prototype,"useSpecularOverAlpha",void 0),(0,oe.gn)([At("Specular anti-aliasing",Et.Boolean,"RENDERING",{notifiers:{update:!0}})],pT.prototype,"enableSpecularAntiAliasing",void 0),(0,oe.gn)([At("Realtime filtering",Et.Boolean,"RENDERING",{notifiers:{update:!0}})],pT.prototype,"realTimeFiltering",void 0),(0,oe.gn)([At("Realtime filtering quality",Et.List,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],pT.prototype,"realTimeFilteringQuality",void 0),(0,oe.gn)([At("Energy Conservation",Et.Boolean,"ADVANCED",{notifiers:{update:!0}})],pT.prototype,"useEnergyConservation",void 0),(0,oe.gn)([At("Radiance occlusion",Et.Boolean,"ADVANCED",{notifiers:{update:!0}})],pT.prototype,"useRadianceOcclusion",void 0),(0,oe.gn)([At("Horizon occlusion",Et.Boolean,"ADVANCED",{notifiers:{update:!0}})],pT.prototype,"useHorizonOcclusion",void 0),(0,oe.gn)([At("Unlit",Et.Boolean,"ADVANCED",{notifiers:{update:!0}})],pT.prototype,"unlit",void 0),(0,oe.gn)([At("Force normal forward",Et.Boolean,"ADVANCED",{notifiers:{update:!0}})],pT.prototype,"forceNormalForward",void 0),(0,oe.gn)([At("Generate only fragment code",Et.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:pT._OnGenerateOnlyFragmentCodeChanged}})],pT.prototype,"generateOnlyFragmentCode",void 0),(0,oe.gn)([At("Debug mode",Et.List,"DEBUG",{notifiers:{update:!0},options:[{label:"None",value:0},{label:"Normalized position",value:1},{label:"Normals",value:2},{label:"Tangents",value:3},{label:"Bitangents",value:4},{label:"Bump Normals",value:5},{label:"ClearCoat Normals",value:8},{label:"ClearCoat Tangents",value:9},{label:"ClearCoat Bitangents",value:10},{label:"Anisotropic Normals",value:11},{label:"Anisotropic Tangents",value:12},{label:"Anisotropic Bitangents",value:13},{label:"Env Refraction",value:40},{label:"Env Reflection",value:41},{label:"Env Clear Coat",value:42},{label:"Direct Diffuse",value:50},{label:"Direct Specular",value:51},{label:"Direct Clear Coat",value:52},{label:"Direct Sheen",value:53},{label:"Env Irradiance",value:54},{label:"Surface Albedo",value:60},{label:"Reflectance 0",value:61},{label:"Metallic",value:62},{label:"Metallic F0",value:71},{label:"Roughness",value:63},{label:"AlphaG",value:64},{label:"NdotV",value:65},{label:"ClearCoat Color",value:66},{label:"ClearCoat Roughness",value:67},{label:"ClearCoat NdotV",value:68},{label:"Transmittance",value:69},{label:"Refraction Transmittance",value:70},{label:"SEO",value:80},{label:"EHO",value:81},{label:"Energy Factor",value:82},{label:"Specular Reflectance",value:83},{label:"Clear Coat Reflectance",value:84},{label:"Sheen Reflectance",value:85},{label:"Luminance Over Alpha",value:86},{label:"Alpha",value:87}]})],pT.prototype,"debugMode",void 0),(0,oe.gn)([At("Split position",Et.Float,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],pT.prototype,"debugLimit",void 0),(0,oe.gn)([At("Output factor",Et.Float,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],pT.prototype,"debugFactor",void 0),(0,l.H)("BABYLON.PBRMetallicRoughnessBlock",pT);(0,l.H)("BABYLON.ModBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("left",ct.AutoDetect),this.registerInput("right",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"ModBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = mod(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\r\n`,this}});var fT,_T,mT,gT,vT,TT;(0,l.H)("BABYLON.MatrixBuilder",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("row0",ct.Vector4),this.registerInput("row1",ct.Vector4),this.registerInput("row2",ct.Vector4),this.registerInput("row3",ct.Vector4),this.registerOutput("output",ct.Matrix)}getClassName(){return"MatrixBuilder"}get row0(){return this._inputs[0]}get row1(){return this._inputs[1]}get row2(){return this._inputs[2]}get row3(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(){if(!this.row0.isConnected){const e=new Bt("row0");e.value=new o.Lt(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){const e=new Bt("row1");e.value=new o.Lt(0,1,0,0),e.output.connectTo(this.row1)}if(!this.row2.isConnected){const e=new Bt("row2");e.value=new o.Lt(0,0,1,0),e.output.connectTo(this.row2)}if(!this.row3.isConnected){const e=new Bt("row3");e.value=new o.Lt(0,0,0,1),e.output.connectTo(this.row3)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.row0,n=this.row1,s=this.row2,r=this.row3;return e.compilationString+=this._declareOutput(t,e)+` = mat4(${i.associatedVariableName}, ${n.associatedVariableName}, ${s.associatedVariableName}, ${r.associatedVariableName});\r\n`,this}}),function(e){e[e.Equal=0]="Equal",e[e.NotEqual=1]="NotEqual",e[e.LessThan=2]="LessThan",e[e.GreaterThan=3]="GreaterThan",e[e.LessOrEqual=4]="LessOrEqual",e[e.GreaterOrEqual=5]="GreaterOrEqual",e[e.Xor=6]="Xor",e[e.Or=7]="Or",e[e.And=8]="And"}(fT||(fT={}));(0,l.H)("BABYLON.ConditionalBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.condition=fT.LessThan,this.registerInput("a",ct.Float),this.registerInput("b",ct.Float),this.registerInput("true",ct.AutoDetect,!0),this.registerInput("false",ct.AutoDetect,!0),this.registerOutput("output",ct.BasedOnInput),this._linkConnectionTypes(2,3),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=ct.Float}getClassName(){return"ConditionalBlock"}get a(){return this._inputs[0]}get b(){return this._inputs[1]}get true(){return this._inputs[2]}get false(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.true.isConnected?this.true.associatedVariableName:"1.0",n=this.false.isConnected?this.false.associatedVariableName:"0.0";switch(this.condition){case fT.Equal:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} == ${this.b.associatedVariableName} ? ${i} : ${n};\r\n`;break;case fT.NotEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} != ${this.b.associatedVariableName} ? ${i} : ${n};\r\n`;break;case fT.LessThan:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} < ${this.b.associatedVariableName} ? ${i} : ${n};\r\n`;break;case fT.LessOrEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} <= ${this.b.associatedVariableName} ? ${i} : ${n};\r\n`;break;case fT.GreaterThan:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} > ${this.b.associatedVariableName} ? ${i} : ${n};\r\n`;break;case fT.GreaterOrEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} >= ${this.b.associatedVariableName} ? ${i} : ${n};\r\n`;break;case fT.Xor:e.compilationString+=this._declareOutput(t,e)+` = (mod(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 2.0) > 0.0) ? ${i} : ${n};\r\n`;break;case fT.Or:e.compilationString+=this._declareOutput(t,e)+` = (min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0) ? ${i} : ${n};\r\n`;break;case fT.And:e.compilationString+=this._declareOutput(t,e)+` = (${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0) ? ${i} : ${n};\r\n`}return this}serialize(){const e=super.serialize();return e.condition=this.condition,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.condition=e.condition}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.condition = BABYLON.ConditionalBlockConditions.${fT[this.condition]};\r\n`}});class ST extends bt{constructor(e){super(e,dt.Neutral),this.octaves=6,this.registerInput("seed",ct.AutoDetect),this.registerInput("chaos",ct.AutoDetect,!0),this.registerInput("offsetX",ct.Float,!0),this.registerInput("offsetY",ct.Float,!0),this.registerInput("offsetZ",ct.Float,!0),this.registerOutput("output",ct.Float),this._inputs[0].acceptedConnectionPointTypes.push(ct.Vector2),this._inputs[0].acceptedConnectionPointTypes.push(ct.Vector3),this._linkConnectionTypes(0,1)}getClassName(){return"CloudBlock"}get seed(){return this._inputs[0]}get chaos(){return this._inputs[1]}get offsetX(){return this._inputs[2]}get offsetY(){return this._inputs[3]}get offsetZ(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){var t,i;if(super._buildBlock(e),!this.seed.isConnected)return;if(!this._outputs[0].hasEndpoints)return;const n="\n float fbm(in vec2 st, in vec2 chaos) {\n // Initial values\n float value = 0.0;\n float amplitude = .5;\n float frequency = 0.;\n\n // Loop of octaves\n for (int i = 0; i < OCTAVES; i++) {\n value += amplitude * cloudNoise(st, chaos);\n st *= 2.0;\n amplitude *= 0.5;\n }\n return value;\n }\n\n float fbm(in vec3 x, in vec3 chaos) {\n // Initial values\n float value = 0.0;\n float amplitude = 0.5;\n for (int i = 0; i < OCTAVES; ++i) {\n value += amplitude * cloudNoise(x, chaos);\n x = x * 2.0;\n amplitude *= 0.5;\n }\n return value;\n }",s=`fbm${this.octaves}`;e._emitFunction("CloudBlockCode","\n\n float cloudRandom(in float p) { p = fract(p * 0.011); p *= p + 7.5; p *= p + p; return fract(p); }\n\n // Based on Morgan McGuire @morgan3d\n // https://www.shadertoy.com/view/4dS3Wd\n float cloudNoise(in vec2 x, in vec2 chaos) {\n vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.);\n\n vec2 i = floor(x);\n vec2 f = fract(x);\n\n float n = dot(i, step);\n\n vec2 u = f * f * (3.0 - 2.0 * f);\n return mix(\n mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x),\n mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x),\n u.y\n );\n }\n\n float cloudNoise(in vec3 x, in vec3 chaos) {\n vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.);\n\n vec3 i = floor(x);\n vec3 f = fract(x);\n\n float n = dot(i, step);\n\n vec3 u = f * f * (3.0 - 2.0 * f);\n return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x),\n mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y),\n mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x),\n mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z);\n }","// CloudBlockCode"),e._emitFunction("CloudBlockCodeFBM"+this.octaves,n.replace(/fbm/gi,s).replace(/OCTAVES/gi,(0|this.octaves).toString()),"// CloudBlockCode FBM");const r=e._getFreeVariableName("st"),o=(null===(t=this.seed.connectedPoint)||void 0===t?void 0:t.type)===ct.Vector2?"vec2":"vec3";e.compilationString+=`${o} ${r} = ${this.seed.associatedVariableName};\r\n`,this.offsetX.isConnected&&(e.compilationString+=`${r}.x += 0.1 * ${this.offsetX.associatedVariableName};\r\n`),this.offsetY.isConnected&&(e.compilationString+=`${r}.y += 0.1 * ${this.offsetY.associatedVariableName};\r\n`),this.offsetZ.isConnected&&"vec3"===o&&(e.compilationString+=`${r}.z += 0.1 * ${this.offsetZ.associatedVariableName};\r\n`);let a="";return a=this.chaos.isConnected?this.chaos.associatedVariableName:(null===(i=this.seed.connectedPoint)||void 0===i?void 0:i.type)===ct.Vector2?"vec2(0., 0.)":"vec3(0., 0., 0.)",e.compilationString+=this._declareOutput(this._outputs[0],e)+` = ${s}(${r}, ${a});\r\n`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.octaves = ${this.octaves};\r\n`}serialize(){const e=super.serialize();return e.octaves=this.octaves,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.octaves=e.octaves}}(0,oe.gn)([At("Octaves",Et.Int)],ST.prototype,"octaves",void 0),(0,l.H)("BABYLON.CloudBlock",ST);(0,l.H)("BABYLON.VoronoiNoiseBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("seed",ct.Vector2),this.registerInput("offset",ct.Float),this.registerInput("density",ct.Float),this.registerOutput("output",ct.Float),this.registerOutput("cells",ct.Float)}getClassName(){return"VoronoiNoiseBlock"}get seed(){return this._inputs[0]}get offset(){return this._inputs[1]}get density(){return this._inputs[2]}get output(){return this._outputs[0]}get cells(){return this._outputs[1]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;let t="vec2 voronoiRandom(vec2 seed, float offset){\n mat2 m = mat2(15.27, 47.63, 99.41, 89.98);\n vec2 uv = fract(sin(m * seed) * 46839.32);\n return vec2(sin(uv.y * offset) * 0.5 + 0.5, cos(uv.x * offset) * 0.5 + 0.5);\n }\n ";e._emitFunction("voronoiRandom",t,"// Voronoi random generator"),t="void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){\n vec2 g = floor(seed * density);\n vec2 f = fract(seed * density);\n float t = 8.0;\n vec3 res = vec3(8.0, 0.0, 0.0);\n\n for(int y=-1; y<=1; y++)\n {\n for(int x=-1; x<=1; x++)\n {\n vec2 lattice = vec2(x,y);\n vec2 randomOffset = voronoiRandom(lattice + g, offset);\n float d = distance(lattice + randomOffset, f);\n if(d < res.x)\n {\n res = vec3(d, randomOffset.x, randomOffset.y);\n outValue = res.x;\n cells = res.y;\n }\n }\n }\n }\n ",e._emitFunction("voronoi",t,"// Voronoi");const i=e._getFreeVariableName("tempOutput"),n=e._getFreeVariableName("tempCells");return e.compilationString+=`float ${i} = 0.0;\r\n`,e.compilationString+=`float ${n} = 0.0;\r\n`,e.compilationString+=`voronoi(${this.seed.associatedVariableName}, ${this.offset.associatedVariableName}, ${this.density.associatedVariableName}, ${i}, ${n});\r\n`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${i};\r\n`),this.cells.hasEndpoints&&(e.compilationString+=this._declareOutput(this.cells,e)+` = ${n};\r\n`),this}});(0,l.H)("BABYLON.ElbowBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("input",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}get target(){const e=this._inputs[0];if(e.isConnected){const t=e.connectedPoint.ownerBlock;if(t.target!==dt.VertexAndFragment)return t.target;if(e.connectedPoint.target!==dt.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){0==(this._target&e)&&(this._target=e)}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._inputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${i.associatedVariableName};\r\n`,this}});class ET extends bt{get texture(){var e;return this.source.isConnected?(null===(e=this.source.connectedPoint)||void 0===e?void 0:e.ownerBlock).texture:this._texture}set texture(e){var t;if(this._texture===e)return;const i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:m.l.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}get textureY(){var e;return this.sourceY.isConnected?(null===(e=this.sourceY.connectedPoint)||void 0===e?void 0:e.ownerBlock).texture:null}get textureZ(){var e,t;return(null===(e=this.sourceZ)||void 0===e?void 0:e.isConnected)?(null===(t=this.sourceY.connectedPoint)||void 0===t?void 0:t.ownerBlock).texture:null}_getImageSourceBlock(e){return(null==e?void 0:e.isConnected)?e.connectedPoint.ownerBlock:null}get samplerName(){const e=this._getImageSourceBlock(this.source);return e?e.samplerName:this._samplerName}get samplerYName(){var e,t;return null!==(t=null===(e=this._getImageSourceBlock(this.sourceY))||void 0===e?void 0:e.samplerName)&&void 0!==t?t:null}get samplerZName(){var e,t;return null!==(t=null===(e=this._getImageSourceBlock(this.sourceZ))||void 0===e?void 0:e.samplerName)&&void 0!==t?t:null}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){var t;if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const e=null!==(t=this.texture.getScene())&&void 0!==t?t:m.l.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){var t;if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const e=null!==(t=this.texture.getScene())&&void 0!==t?t:m.l.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,dt.Neutral),this.projectAsCube=!1,this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this.registerInput("position",ct.AutoDetect,!1),this.registerInput("normal",ct.AutoDetect,!1),this.registerInput("sharpness",ct.Float,!0),this.registerInput("source",ct.Object,!0,dt.VertexAndFragment,new Wv("source",this,vt.Input,$v,"ImageSourceBlock")),this.registerInput("sourceY",ct.Object,!0,dt.VertexAndFragment,new Wv("sourceY",this,vt.Input,$v,"ImageSourceBlock")),t||this.registerInput("sourceZ",ct.Object,!0,dt.VertexAndFragment,new Wv("sourceZ",this,vt.Input,$v,"ImageSourceBlock")),this.registerOutput("rgba",ct.Color4,dt.Neutral),this.registerOutput("rgb",ct.Color3,dt.Neutral),this.registerOutput("r",ct.Float,dt.Neutral),this.registerOutput("g",ct.Float,dt.Neutral),this.registerOutput("b",ct.Float,dt.Neutral),this.registerOutput("a",ct.Float,dt.Neutral),this.registerOutput("level",ct.Float,dt.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ct.Color3|ct.Vector3|ct.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(ct.Color3|ct.Vector3|ct.Vector4)}getClassName(){return"TriPlanarBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get sharpness(){return this._inputs[2]}get source(){return this._inputs[3]}get sourceY(){return this._inputs[4]}get sourceZ(){return this._inputs[5]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const n=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,n,!0),i.setValue(this._gammaDefineName,s,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){this.texture&&(e.setFloat(this._textureInfoName,this.texture.level),this._imageSource||e.setTexture(this._samplerName,this.texture))}_generateTextureLookup(e){var t,i;const n=this.samplerName,s=null!==(t=this.samplerYName)&&void 0!==t?t:n,r=null!==(i=this.samplerZName)&&void 0!==i?i:n,o=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",a=e._getFreeVariableName("x"),l=e._getFreeVariableName("y"),h=e._getFreeVariableName("z"),c=e._getFreeVariableName("w"),d=e._getFreeVariableName("n"),u=e._getFreeVariableName("uvx"),p=e._getFreeVariableName("uvy"),f=e._getFreeVariableName("uvz");e.compilationString+=`\n vec3 ${d} = ${this.normal.associatedVariableName}.xyz;\n\n vec2 ${u} = ${this.position.associatedVariableName}.yz;\n vec2 ${p} = ${this.position.associatedVariableName}.zx;\n vec2 ${f} = ${this.position.associatedVariableName}.xy;\n `,this.projectAsCube&&(e.compilationString+=`\n ${u}.xy = ${u}.yx;\n\n if (${d}.x >= 0.0) {\n ${u}.x = -${u}.x;\n }\n if (${d}.y < 0.0) {\n ${p}.y = -${p}.y;\n }\n if (${d}.z < 0.0) {\n ${f}.x = -${f}.x;\n }\n `),e.compilationString+=`\n vec4 ${a} = texture2D(${n}, ${u});\n vec4 ${l} = texture2D(${s}, ${p});\n vec4 ${h} = texture2D(${r}, ${f});\n \n // blend weights\n vec3 ${c} = pow(abs(${d}), vec3(${o}));\n\n // blend and return\n vec4 ${this._tempTextureRead} = (${a}*${c}.x + ${l}*${c}.y + ${h}*${c}.z) / (${c}.x + ${c}.y + ${c}.z); \n `}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName}\n ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n #endif\n `),e.compilationString+=`#ifdef ${this._gammaDefineName}\n ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n #endif\n `)}_writeOutput(e,t,i){let n="";this.disableLevelMultiplication||(n=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${n};\r\n`,this._generateConversionCode(e,t,i)}_buildBlock(e){super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA"),this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitUniformFromString(this._textureInfoName,"float"),this._generateTextureLookup(e);for(const i of this._outputs)i.hasEndpoints&&"level"!==i.name&&this._writeOutput(e,i,i.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\r\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\r\n`,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\r\n`,e+=`${this._codeVariableName}.projectAsCube = ${this.projectAsCube};\r\n`,this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\r\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\r\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\r\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\r\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\r\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\r\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\r\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\r\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\r\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\r\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\r\n`,e):e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.disableLevelMultiplication=this.disableLevelMultiplication,e.projectAsCube=this.projectAsCube,this.hasImageSource||!this.texture||this.texture.isRenderTarget||"VideoTexture"===this.texture.getClassName()||(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this.disableLevelMultiplication=!!e.disableLevelMultiplication,this.projectAsCube=!!e.projectAsCube,e.texture&&!Ni.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Le.Parse(e.texture,t,i))}}(0,oe.gn)([At("Project as cube",Et.Boolean,"ADVANCED",{notifiers:{update:!0}})],ET.prototype,"projectAsCube",void 0),(0,l.H)("BABYLON.TriPlanarBlock",ET);(0,l.H)("BABYLON.BiPlanarBlock",class extends ET{constructor(e){super(e,!0)}getClassName(){return"BiPlanarBlock"}_generateTextureLookup(e){var t;const i=this.samplerName,n=null!==(t=this.samplerYName)&&void 0!==t?t:this.samplerName,s=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",r=e._getFreeVariableName("dpdx"),o=e._getFreeVariableName("dpdy"),a=e._getFreeVariableName("n"),l=e._getFreeVariableName("ma"),h=e._getFreeVariableName("mi"),c=e._getFreeVariableName("me"),d=e._getFreeVariableName("x"),u=e._getFreeVariableName("y"),p=e._getFreeVariableName("y");e.compilationString+=`\n // grab coord derivatives for texturing\n vec3 ${r} = dFdx(${this.position.associatedVariableName}.xyz);\n vec3 ${o} = dFdy(${this.position.associatedVariableName}.xyz);\n vec3 ${a} = abs(${this.normal.associatedVariableName}.xyz);\n \n // determine major axis (in x; yz are following axis)\n ivec3 ${l} = (${a}.x>${a}.y && ${a}.x>${a}.z) ? ivec3(0,1,2) :\n (${a}.y>${a}.z) ? ivec3(1,2,0) :\n ivec3(2,0,1) ;\n // determine minor axis (in x; yz are following axis)\n ivec3 ${h} = (${a}.x<${a}.y && ${a}.x<${a}.z) ? ivec3(0,1,2) :\n (${a}.y<${a}.z) ? ivec3(1,2,0) :\n ivec3(2,0,1) ;\n // determine median axis (in x; yz are following axis)\n ivec3 ${c} = ivec3(3) - ${h} - ${l};\n \n // project+fetch\n vec4 ${d} = textureGrad( ${i}, vec2( ${this.position.associatedVariableName}[${l}.y], ${this.position.associatedVariableName}[${l}.z]), \n vec2(${r}[${l}.y],${r}[${l}.z]), \n vec2(${o}[${l}.y],${o}[${l}.z]) );\n vec4 ${u} = textureGrad( ${n}, vec2( ${this.position.associatedVariableName}[${c}.y], ${this.position.associatedVariableName}[${c}.z]), \n vec2(${r}[${c}.y],${r}[${c}.z]),\n vec2(${o}[${c}.y],${o}[${c}.z]) );\n \n // blend factors\n vec2 ${p} = vec2(${a}[${l}.x],${a}[${c}.x]);\n // make local support\n ${p} = clamp( (${p}-0.5773)/(1.0-0.5773), 0.0, 1.0 );\n // shape transition\n ${p} = pow( ${p}, vec2(${s}/8.0) );\n // blend and return\n vec4 ${this._tempTextureRead} = (${d}*${p}.x + ${u}*${p}.y) / (${p}.x + ${p}.y);\n `}});(0,l.H)("BABYLON.MatrixDeterminantBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("input",ct.Matrix),this.registerOutput("output",ct.Float)}getClassName(){return"MatrixDeterminantBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this.output,i=this.input;return e.compilationString+=this._declareOutput(t,e)+`${t.associatedVariableName} = determinant(${i.associatedVariableName});\r\n`,this}});(0,l.H)("BABYLON.MatrixTransposeBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("input",ct.Matrix),this.registerOutput("output",ct.Matrix)}getClassName(){return"MatrixTransposeBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this.output,i=this.input;return e.compilationString+=this._declareOutput(t,e)+`${t.associatedVariableName} = transpose(${i.associatedVariableName});\r\n`,this}}),function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Tangent=2]="Tangent",e[e.VertexColor=3]="VertexColor",e[e.UV1=4]="UV1",e[e.UV2=5]="UV2",e[e.UV3=6]="UV3",e[e.UV4=7]="UV4",e[e.UV5=8]="UV5",e[e.UV6=9]="UV6"}(_T||(_T={}));class xT extends bt{constructor(e){super(e,dt.Neutral),this.attributeType=_T.None,this.registerInput("input",ct.AutoDetect),this.registerInput("fallback",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].onConnectionObservable.add((e=>{var t;if(this.attributeType)return;const i=e.ownerBlock;if(i instanceof Bt&&i.isAttribute)switch(i.name){case"color":this.attributeType=_T.VertexColor;break;case"normal":this.attributeType=_T.Normal;break;case"tangent":this.attributeType=_T.Tangent;break;case"uv":this.attributeType=_T.UV1;break;case"uv2":this.attributeType=_T.UV2;break;case"uv3":this.attributeType=_T.UV3;break;case"uv4":this.attributeType=_T.UV4;break;case"uv5":this.attributeType=_T.UV5;break;case"uv6":this.attributeType=_T.UV6}else if(i instanceof Hv)switch(null===(t=this.input.connectedPoint)||void 0===t?void 0:t.name){case"normalOutput":this.attributeType=_T.Normal;break;case"tangentOutput":this.attributeType=_T.Tangent;break;case"uvOutput":this.attributeType=_T.UV1}}))}getClassName(){return"MeshAttributeExistsBlock"}get input(){return this._inputs[0]}get fallback(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.attributeType){case _T.VertexColor:t="VERTEXCOLOR_NME";break;case _T.Normal:t="NORMAL";break;case _T.Tangent:t="TANGENT";break;case _T.UV1:t="UV1";break;case _T.UV2:t="UV2";break;case _T.UV3:t="UV3";break;case _T.UV4:t="UV4";break;case _T.UV5:t="UV5";break;case _T.UV6:t="UV6"}const i=this._declareOutput(this.output,e);return t&&(e.compilationString+=`#ifdef ${t}\r\n`),e.compilationString+=`${i} = ${this.input.associatedVariableName};\r\n`,t&&(e.compilationString+="#else\r\n",e.compilationString+=`${i} = ${this.fallback.associatedVariableName};\r\n`,e.compilationString+="#endif\r\n"),this}serialize(){const e=super.serialize();return e.attributeType=this.attributeType,e}_deserialize(e,t,i){var n;super._deserialize(e,t,i),this.attributeType=null!==(n=e.attributeType)&&void 0!==n?n:_T.None}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.attributeType = ${this.attributeType};\r\n`,e}}(0,oe.gn)([At("Attribute lookup",Et.List,void 0,{notifiers:{update:!0},options:[{label:"(None)",value:_T.None},{label:"Normal",value:_T.Normal},{label:"Tangent",value:_T.Tangent},{label:"Vertex Color",value:_T.VertexColor},{label:"UV1",value:_T.UV1},{label:"UV2",value:_T.UV2},{label:"UV3",value:_T.UV3},{label:"UV4",value:_T.UV4},{label:"UV5",value:_T.UV5},{label:"UV6",value:_T.UV6}]})],xT.prototype,"attributeType",void 0),(0,l.H)("BABYLON.MeshAttributeExistsBlock",xT),function(e){e[e.EaseInSine=0]="EaseInSine",e[e.EaseOutSine=1]="EaseOutSine",e[e.EaseInOutSine=2]="EaseInOutSine",e[e.EaseInQuad=3]="EaseInQuad",e[e.EaseOutQuad=4]="EaseOutQuad",e[e.EaseInOutQuad=5]="EaseInOutQuad",e[e.EaseInCubic=6]="EaseInCubic",e[e.EaseOutCubic=7]="EaseOutCubic",e[e.EaseInOutCubic=8]="EaseInOutCubic",e[e.EaseInQuart=9]="EaseInQuart",e[e.EaseOutQuart=10]="EaseOutQuart",e[e.EaseInOutQuart=11]="EaseInOutQuart",e[e.EaseInQuint=12]="EaseInQuint",e[e.EaseOutQuint=13]="EaseOutQuint",e[e.EaseInOutQuint=14]="EaseInOutQuint",e[e.EaseInExpo=15]="EaseInExpo",e[e.EaseOutExpo=16]="EaseOutExpo",e[e.EaseInOutExpo=17]="EaseInOutExpo",e[e.EaseInCirc=18]="EaseInCirc",e[e.EaseOutCirc=19]="EaseOutCirc",e[e.EaseInOutCirc=20]="EaseInOutCirc",e[e.EaseInBack=21]="EaseInBack",e[e.EaseOutBack=22]="EaseOutBack",e[e.EaseInOutBack=23]="EaseInOutBack",e[e.EaseInElastic=24]="EaseInElastic",e[e.EaseOutElastic=25]="EaseOutElastic",e[e.EaseInOutElastic=26]="EaseInOutElastic"}(mT||(mT={}));(0,l.H)("BABYLON.CurveBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.type=mT.EaseInOutSine,this.registerInput("input",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(ct.Matrix),this._inputs[0].excludedConnectionPointTypes.push(ct.Object),this._inputs[0].excludedConnectionPointTypes.push(ct.Int)}getClassName(){return"CurveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_duplicateEntry(e,t){return`ret.${t} = ${e.replace(/VAL/g,"v."+t)}`}_duplicateEntryDirect(e){return`return ${e.replace(/VAL/g,"v")}`}_duplicateVector(e,t){if("float"===t)return this._duplicateEntryDirect(e);const i=parseInt(t.replace("vec",""));let n=`\n vec${i} ret = vec${i}(0.0);\n `;for(let s=1;s<=i;s++)n+=this._duplicateEntry(e,1===s?"x":2===s?"y":3===s?"z":"w")+";\r\n";return n+="return ret;\r\n",n}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="",n="",s="";switch(this.input.type){case ct.Float:s="float";break;case ct.Vector2:s="vec2";break;case ct.Vector3:case ct.Color3:s="vec3";break;case ct.Vector4:case ct.Color4:s="vec4"}switch(n=mT[this.type]+"_"+s,this.type){case mT.EaseInSine:i="return 1.0 - cos((v * 3.1415) / 2.0)";break;case mT.EaseOutSine:i="return sin((v * 3.1415) / 2.0)";break;case mT.EaseInOutSine:i="return -(cos(v * 3.1415) - 1.0) / 2.0";break;case mT.EaseInQuad:i="return v * v";break;case mT.EaseOutQuad:i="return (1.0 - v) * (1.0 - v)";break;case mT.EaseInOutQuad:{const e="VAL < 0.5 ? 2.0 * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0";i=this._duplicateVector(e,s);break}case mT.EaseInCubic:i="return v * v * v";break;case mT.EaseOutCubic:{const e="1.0 - pow(1.0 - VAL, 3.0)";i=this._duplicateVector(e,s);break}case mT.EaseInOutCubic:{const e="VAL < 0.5 ? 4.0 * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0";i=this._duplicateVector(e,s);break}case mT.EaseInQuart:i="return v * v * v * v";break;case mT.EaseOutQuart:{const e="1.0 - pow(1.0 - VAL, 4.0)";i=this._duplicateVector(e,s);break}case mT.EaseInOutQuart:{const e="VAL < 0.5 ? 8.0 * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0";i=this._duplicateVector(e,s);break}case mT.EaseInQuint:i="return v * v * v * v * v";break;case mT.EaseOutQuint:{const e="1.0 - pow(1.0 - VAL, 5.0)";i=this._duplicateVector(e,s);break}case mT.EaseInOutQuint:{const e="VAL < 0.5 ? 16.0 * VAL * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0";i=this._duplicateVector(e,s);break}case mT.EaseInExpo:{const e="VAL == 0.0 ? 0.0 : pow(2.0, 10.0 * VAL - 10.0)";i=this._duplicateVector(e,s);break}case mT.EaseOutExpo:{const e="VAL == 1.0 ? 1.0 : 1.0 - pow(2.0, -10.0 * VAL)";i=this._duplicateVector(e,s);break}case mT.EaseInOutExpo:{const e="VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : VAL < 0.5 ? pow(2.0, 20.0 * VAL - 10.0) / 2.0 : (2.0 - pow(2.0, -20.0 * VAL + 10.0)) / 2.0";i=this._duplicateVector(e,s);break}case mT.EaseInCirc:{const e="1.0 - sqrt(1.0 - pow(VAL, 2.0))";i=this._duplicateVector(e,s);break}case mT.EaseOutCirc:{const e="sqrt(1.0 - pow(VAL - 1.0, 2.0))";i=this._duplicateVector(e,s);break}case mT.EaseInOutCirc:{const e="VAL < 0.5 ? (1.0 - sqrt(1.0 - pow(2.0 * VAL, 2.0))) / 2.0 : (sqrt(1.0 - pow(-2.0 * VAL + 2.0, 2.0)) + 1.0) / 2.0";i=this._duplicateVector(e,s);break}case mT.EaseInBack:i="return 2.70158 * v * v * v - 1.70158 * v * v";break;case mT.EaseOutBack:{const e="2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)";i=this._duplicateVector(e,s);break}case mT.EaseInOutBack:{const e="VAL < 0.5 ? (pow(2.0 * VAL, 2.0) * ((3.5949095) * 2.0 * VAL - 2.5949095)) / 2.0 : (pow(2.0 * VAL - 2.0, 2.0) * (3.5949095 * (VAL * 2.0 - 2.0) + 3.5949095) + 2.0) / 2.0";i=this._duplicateVector(e,s);break}case mT.EaseInElastic:{const e="VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : -pow(2.0, 10.0 * VAL - 10.0) * sin((VAL * 10.0 - 10.75) * ((2.0 * 3.1415) / 3.0))";i=this._duplicateVector(e,s);break}case mT.EaseOutElastic:{const e="VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : pow(2.0, -10.0 * VAL) * sin((VAL * 10.0 - 0.75) * ((2.0 * 3.1415) / 3.0)) + 1.0";i=this._duplicateVector(e,s);break}case mT.EaseInOutElastic:{const e="VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : VAL < 0.5 ? -(pow(2.0, 20.0 * VAL - 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 : (pow(2.0, -20.0 * VAL + 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 + 1.0";i=this._duplicateVector(e,s);break}}return e._emitFunction(n,`${s} ${n}(${s} v) {${i};}\r\n`,""),e.compilationString+=this._declareOutput(t,e)+` = ${n}(${this.input.associatedVariableName});\r\n`,this}serialize(){const e=super.serialize();return e.curveType=this.type,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.type=e.curveType}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.CurveBlockTypes.${mT[this.type]};\r\n`}});class bT extends Tt.H{constructor(){super(...arguments),this.DECAL=!1,this.DECALDIRECTUV=0,this.DECAL_SMOOTHALPHA=!1,this.GAMMADECAL=!1}}class CT extends ha{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DecalMap",150,new bT,t),this._isEnabled=!1,this.isEnabled=!1,this._smoothAlpha=!1,this.smoothAlpha=!1,this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i,n){const s=n.getMesh().decalMap;return!(this._isEnabled&&(null==s?void 0:s.texture)&&Bs.DecalMapEnabled&&t.texturesEnabled)||s.isReady()}prepareDefines(e,t,i){const n=i.decalMap;if(this._isEnabled&&(null==n?void 0:n.texture)&&Bs.DecalMapEnabled&&t.texturesEnabled){(!e.DECAL||e.GAMMADECAL!==n.texture.gammaSpace)&&e.markAsTexturesDirty(),e.DECAL=!0,e.GAMMADECAL=n.texture.gammaSpace,e.DECAL_SMOOTHALPHA=this._smoothAlpha,It.G.PrepareDefinesForMergedUV(n.texture,e,"DECAL")}else{e.DECAL&&e.markAsTexturesDirty(),e.DECAL=!1}}hardBindForSubMesh(e,t,i,n){const s=n.getMesh().decalMap;if(!(this._isEnabled&&(null==s?void 0:s.texture)&&Bs.DecalMapEnabled&&t.texturesEnabled))return;const r=this._material.isFrozen,o=s.texture;e.useUbo&&r&&e.isSync||(e.updateFloat4("vDecalInfos",o.coordinatesIndex,0,0,0),It.G.BindTextureMatrix(o,e,"decal")),e.setTexture("decalSampler",o)}getClassName(){return"DecalMapConfiguration"}getSamplers(e){e.push("decalSampler")}getUniforms(){return{ubo:[{name:"vDecalInfos",size:4,type:"vec4"},{name:"decalMatrix",size:16,type:"mat4"}]}}}(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],CT.prototype,"isEnabled",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],CT.prototype,"smoothAlpha",void 0),function(e){e[e.MATERIAL_TYPE_STANDARD=0]="MATERIAL_TYPE_STANDARD",e[e.MATERIAL_TYPE_PBR=1]="MATERIAL_TYPE_PBR"}(gT||(gT={})),function(e){e[e.COLOR_MODE_SET=0]="COLOR_MODE_SET",e[e.COLOR_MODE_ADD=1]="COLOR_MODE_ADD",e[e.COLOR_MODE_MULTIPLY=2]="COLOR_MODE_MULTIPLY"}(vT||(vT={})),function(e){e[e.COLOR_DISTRIBUTION_TYPE_SEGMENT=0]="COLOR_DISTRIBUTION_TYPE_SEGMENT",e[e.COLOR_DISTRIBUTION_TYPE_LINE=1]="COLOR_DISTRIBUTION_TYPE_LINE"}(TT||(TT={}));class yT extends Tt.H{constructor(){super(...arguments),this.GREASED_LINE_HAS_COLOR=!1,this.GREASED_LINE_SIZE_ATTENUATION=!1,this.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=!1}}class AT extends ha{constructor(e,t,i){var n,s,r;i=null!=i?i:{};const o=new yT;o.GREASED_LINE_HAS_COLOR=!!i.color,o.GREASED_LINE_SIZE_ATTENUATION=null!==(n=i.sizeAttenuation)&&void 0!==n&&n,o.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=i.colorDistributionType===TT.COLOR_DISTRIBUTION_TYPE_LINE,super(e,AT.GREASED_LINE_MATERIAL_NAME,200,o),this._scene=t,this._dashArray=0,this._options=i,this._scene=null!==(s=this._scene)&&void 0!==s?s:e.getScene(),this._engine=this._scene.getEngine(),i.colors?this._createColorsTexture(`${e.name}-colors-texture`,i.colors):AT._PrepareEmptyColorsTexture(t),this.setDashCount(null!==(r=i.dashCount)&&void 0!==r?r:1),this._enable(!0)}getAttributes(e){e.push("grl_offsets"),e.push("grl_previousAndSide"),e.push("grl_nextAndCounters"),e.push("grl_widths"),e.push("grl_colorPointers")}getSamplers(e){e.push("grl_colors")}getActiveTextures(e){this._colorsTexture&&e.push(this._colorsTexture)}getUniforms(){return{ubo:[{name:"grl_projection",size:16,type:"mat4"},{name:"grl_singleColor",size:3,type:"vec3"},{name:"grl_resolution_lineWidth",size:3,type:"vec3"},{name:"grl_dashOptions",size:4,type:"vec4"},{name:"grl_colorMode_visibility_colorsWidth_useColors",size:4,type:"vec4"}],vertex:"\n uniform vec3 grl_resolution_lineWidth;\n uniform mat4 grl_projection;\n ",fragment:"\n uniform vec4 grl_dashOptions;\n uniform vec4 grl_colorMode_visibility_colorsWidth_useColors;\n uniform vec3 grl_singleColor;\n "}}get isEnabled(){return!0}bindForSubMesh(e){var t,i,n,s,r,l,h;const c=this._scene.activeCamera;if(!c)throw Error("GreasedLinePluginMaterial requires an active camera.");{const t=c.getProjectionMatrix();e.updateMatrix("grl_projection",t)}const d=o.jp.Vector3[0];this._options.resolution?(d.x=this._options.resolution.x,d.y=this._options.resolution.y):(d.x=this._engine.getRenderWidth(),d.y=this._engine.getRenderHeight()),d.z=this._options.width?this._options.width:this._options.sizeAttenuation?1:.1,e.updateVector3("grl_resolution_lineWidth",d);const u=o.jp.Vector4[0];u.x=AT._BooleanToNumber(this._options.useDash),u.y=null!==(t=this._dashArray)&&void 0!==t?t:0,u.z=null!==(i=this._options.dashOffset)&&void 0!==i?i:0,u.w=null!==(n=this._options.dashRatio)&&void 0!==n?n:.5,e.updateVector4("grl_dashOptions",u);const p=o.jp.Vector4[1];p.x=null!==(s=this._options.colorMode)&&void 0!==s?s:vT.COLOR_MODE_SET,p.y=null!==(r=this._options.visibility)&&void 0!==r?r:1,p.z=this._colorsTexture?this._colorsTexture.getSize().width:0,p.w=AT._BooleanToNumber(this._options.useColors),e.updateVector4("grl_colorMode_visibility_colorsWidth_useColors",p),this._options.color&&e.updateColor3("grl_singleColor",null!==(l=this._options.color)&&void 0!==l?l:a.Wo.White()),e.setTexture("grl_colors",null!==(h=this._colorsTexture)&&void 0!==h?h:AT._EmptyColorsTexture)}prepareDefines(e,t,i){var n;const s=this._options;e.GREASED_LINE_HAS_COLOR=!!s.color,e.GREASED_LINE_SIZE_ATTENUATION=null!==(n=s.sizeAttenuation)&&void 0!==n&&n,e.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=s.colorDistributionType===TT.COLOR_DISTRIBUTION_TYPE_LINE}getClassName(){return AT.GREASED_LINE_MATERIAL_NAME}getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_DEFINITIONS:"\n attribute vec4 grl_previousAndSide;\n attribute vec4 grl_nextAndCounters;\n attribute float grl_widths;\n attribute vec3 grl_offsets;\n attribute float grl_colorPointers;\n\n varying float grlCounters;\n varying float grlColorPointer;\n\n vec2 grlFix( vec4 i, float aspect ) {\n vec2 res = i.xy / i.w;\n res.x *= aspect;\n return res;\n }\n ",CUSTOM_VERTEX_UPDATE_POSITION:"\n vec3 grlPositionOffset = grl_offsets;\n positionUpdated += grlPositionOffset;\n ",CUSTOM_VERTEX_MAIN_END:"\n vec2 grlResolution = grl_resolution_lineWidth.xy;\n float grlBaseWidth = grl_resolution_lineWidth.z;\n\n grlColorPointer = grl_colorPointers;\n\n vec3 grlPrevious = grl_previousAndSide.xyz;\n float grlSide = grl_previousAndSide.w;\n\n vec3 grlNext = grl_nextAndCounters.xyz;\n grlCounters = grl_nextAndCounters.w;\n\n float grlAspect = grlResolution.x / grlResolution.y;\n\n mat4 grlMatrix = viewProjection * world;\n vec4 grlFinalPosition = grlMatrix * vec4( positionUpdated , 1.0 );\n vec4 grlPrevPos = grlMatrix * vec4( grlPrevious + grlPositionOffset, 1.0 );\n vec4 grlNextPos = grlMatrix * vec4( grlNext + grlPositionOffset, 1.0 );\n\n vec2 grlCurrentP = grlFix( grlFinalPosition, grlAspect );\n vec2 grlPrevP = grlFix( grlPrevPos, grlAspect );\n vec2 grlNextP = grlFix( grlNextPos, grlAspect );\n\n float grlWidth = grlBaseWidth * grl_widths;\n\n vec2 grlDir;\n if( grlNextP == grlCurrentP ) grlDir = normalize( grlCurrentP - grlPrevP );\n else if( grlPrevP == grlCurrentP ) grlDir = normalize( grlNextP - grlCurrentP );\n else {\n vec2 grlDir1 = normalize( grlCurrentP - grlPrevP );\n vec2 grlDir2 = normalize( grlNextP - grlCurrentP );\n grlDir = normalize( grlDir1 + grlDir2 );\n }\n vec4 grlNormal = vec4( -grlDir.y, grlDir.x, 0., 1. );\n grlNormal.xy *= .5 * grlWidth;\n grlNormal *= grl_projection;\n #ifdef GREASED_LINE_SIZE_ATTENUATION\n grlNormal.xy *= grlFinalPosition.w;\n grlNormal.xy /= ( vec4( grlResolution, 0., 1. ) * grl_projection ).xy;\n #endif\n grlFinalPosition.xy += grlNormal.xy * grlSide;\n gl_Position = grlFinalPosition;\n\n vPositionW = vec3(grlFinalPosition);\n\n ","!gl_Position\\=viewProjection\\*worldPos;":"//"}:"fragment"===e?{CUSTOM_FRAGMENT_DEFINITIONS:"\n varying float grlCounters;\n varying float grlColorPointer;\n uniform sampler2D grl_colors;\n ",CUSTOM_FRAGMENT_MAIN_END:`\n float grlColorMode = grl_colorMode_visibility_colorsWidth_useColors.x;\n float grlVisibility = grl_colorMode_visibility_colorsWidth_useColors.y;\n float grlColorsWidth = grl_colorMode_visibility_colorsWidth_useColors.z;\n float grlUseColors = grl_colorMode_visibility_colorsWidth_useColors.w;\n\n float grlUseDash = grl_dashOptions.x;\n float grlDashArray = grl_dashOptions.y;\n float grlDashOffset = grl_dashOptions.z;\n float grlDashRatio = grl_dashOptions.w;\n\n gl_FragColor.a *= step(grlCounters, grlVisibility);\n if( gl_FragColor.a == 0. ) discard;\n\n if(grlUseDash == 1.){\n gl_FragColor.a *= ceil(mod(grlCounters + grlDashOffset, grlDashArray) - (grlDashArray * grlDashRatio));\n if (gl_FragColor.a == 0.) discard;\n }\n\n #ifdef GREASED_LINE_HAS_COLOR\n if (grlColorMode == ${vT.COLOR_MODE_SET}.) {\n gl_FragColor.rgb = grl_singleColor;\n } else if (grlColorMode == ${vT.COLOR_MODE_ADD}.) {\n gl_FragColor.rgb += grl_singleColor;\n } else if (grlColorMode == ${vT.COLOR_MODE_MULTIPLY}.) {\n gl_FragColor.rgb *= grl_singleColor;\n }\n #else\n if (grlUseColors == 1.) {\n #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE\n vec4 grlColor = texture2D(grl_colors, vec2(grlCounters, 0.), 0.);\n #else\n vec4 grlColor = texture2D(grl_colors, vec2(grlColorPointer/grlColorsWidth, 0.), 0.);\n #endif\n if (grlColorMode == ${vT.COLOR_MODE_SET}.) {\n gl_FragColor = grlColor;\n } else if (grlColorMode == ${vT.COLOR_MODE_ADD}.) {\n gl_FragColor += grlColor;\n } else if (grlColorMode == ${vT.COLOR_MODE_MULTIPLY}.) {\n gl_FragColor *= grlColor;\n }\n }\n #endif\n `}:null}static _BooleanToNumber(e){return e?1:0}static _Color3toRGBAUint8(e){const t=new Uint8Array(4*e.length);for(let i=0,n=0;i{const r=i.num_components(),o=l.num_points(),h=o*r,c=h*Float32Array.BYTES_PER_ELEMENT,d=e._malloc(c);try{a.GetAttributeDataArrayForAllPoints(l,i,e.DT_FLOAT32,c,d);const u=new Float32Array(e.HEAPF32.buffer,d,h);if("color"===t&&3===r){const e=new Float32Array(4*o);for(let t=0,i=0;t{const i=t.data;switch(i.id){case"init":{const t=i.decoder;t.url&&(importScripts(t.url),e=DracoDecoderModule({wasmBinary:t.wasmBinary})),postMessage("done");break}case"decodeMesh":if(!e)throw new Error("Draco decoder module is not available");e.then((e=>{RT(e,i.dataView,i.attributes,(e=>{postMessage({id:"indices",value:e},[e.buffer])}),((e,t)=>{postMessage({id:e,value:t},[t.buffer])})),postMessage("done")}))}}}class IT{static get DecoderAvailable(){const e=IT.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 IT._Default||(IT._Default=new IT),IT._Default}constructor(e=IT.DefaultNumWorkers){const t=IT.Configuration.decoder,i=t.wasmUrl&&t.wasmBinaryUrl&&"object"==typeof WebAssembly?{url:se.w1.GetAbsoluteUrl(t.wasmUrl),wasmBinaryPromise:se.w1.LoadFileAsync(se.w1.GetAbsoluteUrl(t.wasmBinaryUrl))}:{url:se.w1.GetAbsoluteUrl(t.fallbackUrl),wasmBinaryPromise:Promise.resolve(void 0)};e&&"function"==typeof Worker&&"function"==typeof URL?this._workerPoolPromise=i.wasmBinaryPromise.then((t=>{const n=`${RT}(${PT})()`,s=URL.createObjectURL(new Blob([n],{type:"application/javascript"}));return new z_(e,(()=>new Promise(((e,n)=>{const r=new Worker(s),o=e=>{r.removeEventListener("error",o),r.removeEventListener("message",a),n(e)},a=t=>{"done"===t.data&&(r.removeEventListener("error",o),r.removeEventListener("message",a),e(r))};r.addEventListener("error",o),r.addEventListener("message",a),r.postMessage({id:"init",decoder:{url:i.url,wasmBinary:t}})}))))})):this._decoderModulePromise=i.wasmBinaryPromise.then((e=>{if(!i.url)throw new Error("Draco decoder module is not available");return se.w1.LoadScriptAsync(i.url).then((()=>{return t=e,new Promise((e=>{DracoDecoderModule({wasmBinary:t}).then((t=>{e({module:t})}))}));var t}))}))}dispose(){this._workerPoolPromise&&this._workerPoolPromise.then((e=>{e.dispose()})),delete this._workerPoolPromise,delete this._decoderModulePromise}whenReadyAsync(){return this._workerPoolPromise?this._workerPoolPromise.then((()=>{})):this._decoderModulePromise?this._decoderModulePromise.then((()=>{})):Promise.resolve()}decodeMeshAsync(e,t,i){const n=e instanceof ArrayBuffer?new Uint8Array(e):e;if(this._workerPoolPromise)return this._workerPoolPromise.then((e=>new Promise(((s,r)=>{e.push(((e,o)=>{const a=new Qe.x,l=t=>{e.removeEventListener("error",l),e.removeEventListener("message",h),r(t),o()},h=t=>{if("done"===t.data)e.removeEventListener("error",l),e.removeEventListener("message",h),s(a),o();else if("indices"===t.data.id)a.indices=t.data.value;else{const e=i&&i[t.data.id]?i[t.data.id]:1;if(1!==e)for(let i=0;i{const s=new Qe.x;return RT(e.module,n,t,(e=>{s.indices=e}),((e,t)=>{s.set(t,e)}),i),s}));throw new Error("Draco decoder module is not available")}}IT.Configuration={decoder:{wasmUrl:"https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",wasmBinaryUrl:"https://preview.babylonjs.com/draco_decoder_gltf.wasm",fallbackUrl:"https://preview.babylonjs.com/draco_decoder_gltf.js"}},IT.DefaultNumWorkers=IT.GetDefaultNumWorkers(),IT._Default=null;class MT{static get Default(){return MT._Default||(MT._Default=new MT),MT._Default}constructor(){const e=MT.Configuration.decoder;this._decoderModulePromise=se.w1.LoadScriptAsync(se.w1.GetAbsoluteUrl(e.url)).then((()=>MeshoptDecoder.ready))}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,n,s){return this._decoderModulePromise.then((()=>{const r=new Uint8Array(t*i);return MeshoptDecoder.decodeGltfBuffer(r,t,i,e,n,s),r}))}}MT.Configuration={decoder:{url:"https://preview.babylonjs.com/meshopt_decoder.js"}},MT._Default=null;class OT{constructor(e,t){this.normal=e,this.w=t}static FromPoints(e,t,i){const n=i.subtract(e),s=t.subtract(e);if(0===n.lengthSquared()||0===s.lengthSquared())return null;const r=o.P.Normalize(o.P.Cross(n,s));return new OT(r,o.P.Dot(r,e))}clone(){return new OT(this.normal.clone(),this.w)}flip(){this.normal.scaleInPlace(-1),this.w=-this.w}splitPolygon(e,t,i,n,s){let r=0;const a=[];let l,h;for(l=0;lOT.EPSILON?1:0;r|=t,a.push(t)}switch(r){case 0:(o.P.Dot(this.normal,e.plane.normal)>0?t:i).push(e);break;case 1:n.push(e);break;case 2:s.push(e);break;case 3:{const t=[],i=[];for(l=0;l=3&&(r=new DT(t,e.shared),r.plane&&n.push(r)),i.length>=3&&(r=new DT(i,e.shared),r.plane&&s.push(r));break}}}}OT.EPSILON=1e-5;class DT{constructor(e,t){this.vertices=e,this.shared=t,this.plane=OT.FromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){const e=this.vertices.map((e=>e.clone()));return new DT(e,this.shared)}flip(){this.vertices.reverse().map((e=>{e.flip()})),this.plane.flip()}}const NT="meshUVSpaceRendererVertexShader",FT="precision highp float;\nattribute vec3 position;\nattribute vec3 normal;\nattribute vec2 uv;\nuniform mat4 projMatrix;\nvarying vec2 vDecalTC;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nvoid main(void) {\nvec3 positionUpdated=position;\nvec3 normalUpdated=normal;\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nmat3 normWorldSM=mat3(finalWorld);\nvec3 vNormalW;\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));\nvNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvNormalW=normalize(normWorldSM*normalUpdated);\n#endif\nvec3 normalView=normalize((projMatrix*vec4(vNormalW,0.0)).xyz);\nvec3 decalTC=(projMatrix*worldPos).xyz;\nvDecalTC=decalTC.xy;\ngl_Position=vec4(uv*2.0-1.0,normalView.z>0.0 ? 2. : decalTC.z,1.0);\n}\n";Ht.v.ShadersStore[NT]=FT;const wT="meshUVSpaceRendererPixelShader",LT="precision highp float;\nvarying vec2 vDecalTC;\nuniform sampler2D textureSampler;\nvoid main(void) {\nif (vDecalTC.x<0. || vDecalTC.x>1. || vDecalTC.y<0. || vDecalTC.y>1.) {\ndiscard;\n}\ngl_FragColor=texture2D(textureSampler,vDecalTC);\n}\n";Ht.v.ShadersStore[wT]=LT;class BT{constructor(){this.running=!1,this._simplificationArray=[]}addTask(e){this._simplificationArray.push(e)}executeNext(){const e=this._simplificationArray.pop();e?(this.running=!0,this.runSimplification(e)):this.running=!1}runSimplification(e){if(e.parallelProcessing)e.settings.forEach((t=>{this._getSimplifier(e).simplify(t,(i=>{void 0!==t.distance&&e.mesh.addLODLevel(t.distance,i),i.isVisible=!0,t.quality===e.settings[e.settings.length-1].quality&&e.successCallback&&e.successCallback(),this.executeNext()}))}));else{const t=this._getSimplifier(e),i=(i,n)=>{t.simplify(i,(t=>{void 0!==i.distance&&e.mesh.addLODLevel(i.distance,t),t.isVisible=!0,n()}))};se.$g.Run(e.settings.length,(t=>{i(e.settings[t.index],(()=>{t.executeNext()}))}),(()=>{e.successCallback&&e.successCallback(),this.executeNext()}))}}_getSimplifier(e){return e.simplificationType,UT.QUADRATIC,new WT(e.mesh)}}var UT;!function(e){e[e.QUADRATIC=0]="QUADRATIC"}(UT||(UT={}));class VT{constructor(e){this._vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}}class kT{constructor(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new GT,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}updatePosition(e){this.position.copyFrom(e)}}class GT{constructor(e){this.data=new Array(10);for(let t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}det(e,t,i,n,s,r,o,a,l){return this.data[e]*this.data[s]*this.data[l]+this.data[i]*this.data[n]*this.data[a]+this.data[t]*this.data[r]*this.data[o]-this.data[i]*this.data[s]*this.data[o]-this.data[e]*this.data[r]*this.data[a]-this.data[t]*this.data[n]*this.data[l]}addInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e.data[t]}addArrayInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e[t]}add(e){const t=new GT;for(let i=0;i<10;++i)t.data[i]=this.data[i]+e.data[i];return t}static FromData(e,t,i,n){return new GT(GT.DataFromNumbers(e,t,i,n))}static DataFromNumbers(e,t,i,n){return[e*e,e*t,e*i,e*n,t*t,t*i,t*n,i*i,i*n,n*n]}}class zT{constructor(e,t){this.vertexId=e,this.triangleId=t}}class WT{constructor(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=k.kn}simplify(e,t){this._initDecimatedMesh(),se.$g.Run(this._mesh.subMeshes.length,(t=>{this._initWithMesh(t.index,(()=>{this._runDecimation(e,t.index,(()=>{t.executeNext()}))}),e.optimizeMesh)}),(()=>{setTimeout((()=>{t(this._reconstructedMesh)}),0)}))}_runDecimation(e,t,i){const n=~~(this._triangles.length*e.quality);let s=0;const r=this._triangles.length,a=(e,t)=>{setTimeout((()=>{e%5==0&&this._updateMesh(0===e);for(let e=0;e{const t=~~((this._triangles.length/2+e)%this._triangles.length),n=this._triangles[t];if(n&&!(n.error[3]>i||n.deleted||n.isDirty))for(let r=0;r<3;++r)if(n.error[r]{-1===c.indexOf(e)&&(e.deletePending=!0,c.push(e))})),c.length%2!=0)continue;i.q=a.q.add(i.q),i.updatePosition(l);const d=this._references.length;s=this._updateTriangles(i,i,e,s),s=this._updateTriangles(i,a,t,s);const u=this._references.length-d;if(u<=i.triangleCount){if(u)for(let n=0;nr-s<=n))}),0)};se.$g.Run(this.decimationIterations,(e=>{r-s<=n?e.breakLoop():a(e.index,(()=>{e.executeNext()}))}),(()=>{setTimeout((()=>{this._reconstructMesh(t),i()}),0)}))}_initWithMesh(e,t,i){this._vertices=[],this._triangles=[];const n=this._mesh.getVerticesData(ne.o.PositionKind),s=this._mesh.getIndices(),r=this._mesh.subMeshes[e],a=e=>{if(i)for(let t=0;t>0,(e=>{if(!n)return;const t=e+r.verticesStart,i=o.P.FromArray(n,3*t),s=a(i)||new kT(i,this._vertices.length);s.originalOffsets.push(t),s.id===this._vertices.length&&this._vertices.push(s),l.push(s.id)}),(()=>{se.$g.SyncAsyncForLoop(r.indexCount/3,this.syncIterations,(e=>{if(!s)return;const t=3*(r.indexStart/3+e),i=s[t+0],n=s[t+1],o=s[t+2],a=this._vertices[l[i-r.verticesStart]],h=this._vertices[l[n-r.verticesStart]],c=this._vertices[l[o-r.verticesStart]],d=new VT([a,h,c]);d.originalOffset=t,this._triangles.push(d)}),(()=>{this._init(t)}))}))}_init(e){se.$g.SyncAsyncForLoop(this._triangles.length,this.syncIterations,(e=>{const t=this._triangles[e];t.normal=o.P.Cross(t._vertices[1].position.subtract(t._vertices[0].position),t._vertices[2].position.subtract(t._vertices[0].position)).normalize();for(let i=0;i<3;i++)t._vertices[i].q.addArrayInPlace(GT.DataFromNumbers(t.normal.x,t.normal.y,t.normal.z,-o.P.Dot(t.normal,t._vertices[0].position)))}),(()=>{se.$g.SyncAsyncForLoop(this._triangles.length,this.syncIterations,(e=>{const t=this._triangles[e];for(let i=0;i<3;++i)t.error[i]=this._calculateError(t._vertices[i],t._vertices[(i+1)%3]);t.error[3]=Math.min(t.error[0],t.error[1],t.error[2])}),(()=>{e()}))}))}_reconstructMesh(e){const t=[];let i,n,s;for(i=0;i{r.push(e.position.x),r.push(e.position.y),r.push(e.position.z),h&&h.length&&(o.push(h[3*t]),o.push(h[3*t+1]),o.push(h[3*t+2])),c&&c.length&&(a.push(c[2*t]),a.push(c[2*t+1])),d&&d.length&&(l.push(d[4*t]),l.push(d[4*t+1]),l.push(d[4*t+2]),l.push(d[4*t+3])),++u}))}const p=this._reconstructedMesh.getTotalIndices(),f=this._reconstructedMesh.getTotalVertices(),_=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];const m=this._reconstructedMesh.getIndices(),g=this._mesh.getIndices();for(i=0;i{const t=g[n.originalOffset+e];let i=n._vertices[e].originalOffsets.indexOf(t);i<0&&(i=0),m.push(n._vertices[e].id+i+f)}));this._reconstructedMesh.setIndices(m),this._reconstructedMesh.setVerticesData(ne.o.PositionKind,r),o.length>0&&this._reconstructedMesh.setVerticesData(ne.o.NormalKind,o),a.length>0&&this._reconstructedMesh.setVerticesData(ne.o.UVKind,a),l.length>0&&this._reconstructedMesh.setVerticesData(ne.o.ColorKind,l);const v=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],_.forEach((e=>{um.P.AddToMesh(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,e.getMesh())})),um.P.AddToMesh(v.materialIndex,f,u,p,3*t.length,this._reconstructedMesh))}_initDecimatedMesh(){this._reconstructedMesh=new ee.Kj(this._mesh.name+"Decimated",this._mesh.getScene()),this._reconstructedMesh.material=this._mesh.material,this._reconstructedMesh.parent=this._mesh.parent,this._reconstructedMesh.isVisible=!1,this._reconstructedMesh.renderingGroupId=this._mesh.renderingGroupId}_isFlipped(e,t,i,n,s){for(let r=0;r.999)return!0;const p=o.P.Cross(d,u).normalize();if(n[r]=!1,o.P.Dot(p,a.normal)<.2)return!0}return!1}_updateTriangles(e,t,i,n){let s=n;for(let r=0;r{const n=e.getVerticesData(ne.o.PositionKind),s=e.getIndices();if(n&&s)for(let r=0,a=0;r[e.x,e.y,e.z]))}static GetPointsCountInfo(e){const t=new Array(e.length);let i=0;for(let n=e.length;n--;)t[n]=e[n].length/3,i+=t[n];return{total:i,counts:t}}static GetLineLength(e){if(0===e.length)return 0;let t;t="number"==typeof e[0]?jT.ToVector3Array(e):e;const i=o.jp.Vector3[0];let n=0;for(let s=0;s{if(e.length>t){jT.SegmentizeSegmentByCount(e.point1,e.point2,Math.ceil(e.length/t)).forEach((e=>{n.push(e)}))}else n.push(e.point1),n.push(e.point2)})),n}static SegmentizeLineBySegmentCount(e,t){const i=jT.GetLineLength(e)/t;return jT.SegmentizeLineBySegmentLength(e,i)}static GetLineSegments(e){const t=[];for(let i=0;ie.length));return{min:t[0].length,max:t[t.length-1].length}}static GetPositionOnLineByVisibility(e,t,i,n=!1){const s=t*i;let r=0,a=0;const l=e.length;for(let o=0;o[e.x,e.y,e.z]))}static GetArrowCap(e,t,i,n,s,r=0,o=0){return{points:[e.clone(),e.add(t.multiplyByFloats(i,i,i))],widths:[n,s,r,o]}}static GetPointsFromText(e,t,i,n,s=0,r=!0){const o=[],a=mh(e,t,i,n);for(const l of a){for(const e of l.paths){const t=[],i=e.getPoints();for(const e of i)t.push(e.x,e.y,s);o.push(t)}if(r)for(const e of l.holes){const t=[],i=e.getPoints();for(const e of i)t.push(e.x,e.y,s);o.push(t)}}return o}}ee.Kj._GreasedLineMeshParser=(e,t)=>KT.Parse(e,t);class KT extends ee.Kj{constructor(e,t,i){var n,s,r,o;super(e,t,null,null,!1,!1),this.name=e,this._options=i,this._lazy=!1,this._updatable=!1,this.intersectionThreshold=.1,this._lazy=null!==(n=i.lazy)&&void 0!==n&&n,this._updatable=null!==(s=i.updatable)&&void 0!==s&&s,this._vertexPositions=[],this._indices=[],this._uvs=[],this._points=[],this._colorPointers=null!==(r=i.colorPointers)&&void 0!==r?r:[],this._previousAndSide=[],this._nextAndCounters=[],i.widths=null!==(o=i.widths)&&void 0!==o?o:new Array(i.points.length).fill(1),i.points&&this.addPoints(KT.ConvertPoints(i.points))}getClassName(){return"GreasedLineMesh"}static ConvertPoints(e){if(e.length&&Array.isArray(e)&&"number"==typeof e[0])return[e];if(e.length&&Array.isArray(e[0])&&"number"==typeof e[0][0])return e;if(e.length&&!Array.isArray(e[0])&&e[0]instanceof o.P){const t=[];for(let i=0;i0&&Array.isArray(e[0])&&e[0].length>0&&e[0][0]instanceof o.P){const t=[];return e.forEach((e=>{t.push(e.flatMap((e=>[e.x,e.y,e.z])))})),t}if(e instanceof Float32Array)return[Array.from(e)];if(e.length&&e[0]instanceof Float32Array){const t=[];return e.forEach((e=>{t.push(Array.from(e))})),t}return[]}updateLazy(){var e;this.setPoints(this._points),this._options.colorPointers||this._updateColorPointers(),this._createVertexBuffers(),this.refreshBoundingInfo(),null===(e=this.greasedLineMaterial)||void 0===e||e.updateLazy()}dispose(){super.dispose()}isLazy(){return this._lazy}get options(){return this._options}setOffsets(e){this._offsetsBuffer?this._offsetsBuffer&&this._offsetsBuffer.update(e):this._createOffsetsBuffer(e)}setSegmentWidths(e){this._options.widths=e,this._lazy||this._widthsBuffer&&this._widthsBuffer.update(e)}setColorPointers(e){this._lazy||this._colorPointersBuffer&&this._colorPointersBuffer.update(e)}get greasedLineMaterial(){var e,t;return null===(t=null===(e=this.material)||void 0===e?void 0:e.pluginManager)||void 0===t?void 0:t.getPlugin(AT.GREASED_LINE_MATERIAL_NAME)}addPoints(e){const t=e;this._points.push(...t),this._lazy||this.setPoints(this._points)}_updateColorPointers(){let e=0;this._colorPointers=[],this._points.forEach((t=>{for(let i=0;i{var i;const n=[],s=[],r=[],o=jT.GetLineLength(e);for(let d=0,u=0;u0&&(o=KT._CopyV3(a,e),i.push(o[0],o[1],o[2]),i.push(o[0],o[1],o[2]));return o=KT._CompareV3(r-1,0,e)?KT._CopyV3(1,e):KT._CopyV3(r-1,e),i.push(o[0],o[1],o[2]),i.push(o[0],o[1],o[2]),{previous:t,next:i,uvs:s,side:n}}_createVertexBuffers(){const e=new Qe.x;e.positions=this._vertexPositions,e.indices=this._indices,e.uvs=this._uvs,e.applyToMesh(this,this._options.updatable);const t=this._scene.getEngine(),i=new ne.l(t,this._previousAndSide,!1,4);this.setVerticesBuffer(i.createVertexBuffer("grl_previousAndSide",0,4));const n=new ne.l(t,this._nextAndCounters,!1,4);this.setVerticesBuffer(n.createVertexBuffer("grl_nextAndCounters",0,4));const s=new ne.l(t,this._options.widths,this._updatable,1);this.setVerticesBuffer(s.createVertexBuffer("grl_widths",0,1)),this._widthsBuffer=s;const r=new ne.l(t,this._colorPointers,this._updatable,1);this.setVerticesBuffer(r.createVertexBuffer("grl_colorPointers",0,1)),this._colorPointersBuffer=r}_createOffsetsBuffer(e){const t=this._scene.getEngine(),i=new ne.l(t,e,this._updatable,3);this.setVerticesBuffer(i.createVertexBuffer("grl_offsets",0,3)),this._offsetsBuffer=i}}KT._V_START=new o.P,KT._V_END=new o.P,KT._V_OFFSET_START=new o.P,KT._V_OFFSET_END=new o.P,function(e){e[e.COLOR_DISTRIBUTION_NONE=0]="COLOR_DISTRIBUTION_NONE",e[e.COLOR_DISTRIBUTION_REPEAT=1]="COLOR_DISTRIBUTION_REPEAT",e[e.COLOR_DISTRIBUTION_EVEN=2]="COLOR_DISTRIBUTION_EVEN",e[e.COLOR_DISTRIBUTION_START=3]="COLOR_DISTRIBUTION_START",e[e.COLOR_DISTRIBUTION_END=4]="COLOR_DISTRIBUTION_END",e[e.COLOR_DISTRIBUTION_START_END=5]="COLOR_DISTRIBUTION_START_END"}(XT||(XT={})),function(e){e[e.WIDTH_DISTRIBUTION_NONE=0]="WIDTH_DISTRIBUTION_NONE",e[e.WIDTH_DISTRIBUTION_REPEAT=1]="WIDTH_DISTRIBUTION_REPEAT",e[e.WIDTH_DISTRIBUTION_EVEN=2]="WIDTH_DISTRIBUTION_EVEN",e[e.WIDTH_DISTRIBUTION_START=3]="WIDTH_DISTRIBUTION_START",e[e.WIDTH_DISTRIBUTION_END=4]="WIDTH_DISTRIBUTION_END",e[e.WIDTH_DISTRIBUTION_START_END=5]="WIDTH_DISTRIBUTION_START_END"}(YT||(YT={}));i(4081);ee.Kj.prototype.thinInstanceAdd=function(e,t=!0){if(!this.getScene().getEngine().getCaps().instancedArrays)return p.Y.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 n=0;n=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},ee.Kj.prototype.thinInstanceSetAttributeAt=function(e,t,i,n=!0){return e===ne.o.ColorKind&&(e=ne.o.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(ee.Kj.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(e){var t,i;const n=null!==(t=this._thinInstanceDataStorage.matrixData)&&void 0!==t?t:null===(i=this.source)||void 0===i?void 0:i._thinInstanceDataStorage.matrixData;e<=(n?n.length/16:0)&&(this._thinInstanceDataStorage.instancesCount=e)},enumerable:!0,configurable:!0}),ee.Kj.prototype._thinInstanceCreateMatrixBuffer=function(e,t,i=!1){e===ne.o.ColorKind&&(e=ne.o.ColorInstanceKind);const n=new ne.l(this.getEngine(),t,!i,16,!1,!0);for(let s=0;s<4;s++)this.setVerticesBuffer(n.createVertexBuffer(e+s,4*s,4));return n},ee.Kj.prototype.thinInstanceSetBuffer=function(e,t,i=0,n=!1){var s,r,o;i=i||16,"matrix"===e?(null===(s=this._thinInstanceDataStorage.matrixBuffer)||void 0===s||s.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?(null===(r=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===r||r.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=t,null!==t&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",t,n))):(e===ne.o.ColorKind&&(e=ne.o.ColorInstanceKind),null===t?(null===(o=this._userThinInstanceBuffersStorage)||void 0===o?void 0:o.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 ne.o(this.getEngine(),t,e,!n,!1,i,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])))},ee.Kj.prototype.thinInstanceBufferUpdated=function(e){var t,i,n;"matrix"===e?null===(t=this._thinInstanceDataStorage.matrixBuffer)||void 0===t||t.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount):"previousMatrix"===e?null===(i=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===i||i.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount):(e===ne.o.ColorKind&&(e=ne.o.ColorInstanceKind),(null===(n=this._userThinInstanceBuffersStorage)||void 0===n?void 0:n.vertexBuffers[e])&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(this._userThinInstanceBuffersStorage.data[e],0))},ee.Kj.prototype.thinInstancePartialBufferUpdate=function(e,t,i){var n;"matrix"===e?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(t,i):(e===ne.o.ColorKind&&(e=ne.o.ColorInstanceKind),(null===(n=this._userThinInstanceBuffersStorage)||void 0===n?void 0:n.vertexBuffers[e])&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(t,i))},ee.Kj.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];const e=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=new Array;for(let t=0;tnew qT(e,t,i);class qT{get enableSceneOffline(){return this._enableSceneOffline}get enableTexturesOffline(){return this._enableTexturesOffline}constructor(e,t,i=!1){this._idbFactory="undefined"!=typeof indexedDB?indexedDB:void 0,this._currentSceneUrl=qT._ReturnFullUrlLocation(e),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,qT.IDBStorageEnabled?i?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,se.w1.SetImmediate((()=>{t(!0)}))):this._checkManifestFile(t):t(!0)}_checkManifestFile(e){const t=()=>{this._enableSceneOffline=!1,this._enableTexturesOffline=!1,e(!1)},i=()=>{try{if("function"==typeof URL&&0===this._currentSceneUrl.indexOf("http")){const e=new URL(this._currentSceneUrl);return e.pathname+=".manifest",e.toString()}}catch(e){}return`${this._currentSceneUrl}.manifest`};let n=!1,s=i();const r=new y.g;navigator.onLine&&(n=!0,s=s+(null==s.match(/\?/)?"?":"&")+Date.now()),r.open("GET",s),r.addEventListener("load",(()=>{if(200===r.status||qT._ValidateXHRData(r,1))try{const t=JSON.parse(r.response);this._enableSceneOffline=t.enableSceneOffline,this._enableTexturesOffline=t.enableTexturesOffline&&qT._IsUASupportingBlobStorage,t.version&&!isNaN(parseInt(t.version))&&(this._manifestVersionFound=t.version),e(!0)}catch(i){t()}else t()}),!1),r.addEventListener("error",(()=>{if(n){n=!1;const e=i();r.open("GET",e),r.send()}else t()}),!1);try{r.send()}catch(o){p.Y.Error("Error on XHR send request."),e(!1)}}open(e,t){const i=()=>{this._isSupported=!1,t&&t()};if(this._idbFactory&&(this._enableSceneOffline||this._enableTexturesOffline))if(this._db)e&&e();else{this._hasReachedQuota=!1,this._isSupported=!0;const t=this._idbFactory.open("babylonjs",1);t.onerror=()=>{i()},t.onblocked=()=>{p.Y.Error("IDB request blocked. Please reload the page."),i()},t.onsuccess=()=>{this._db=t.result,e()},t.onupgradeneeded=e=>{if(this._db=e.target.result,this._db)try{this._db.createObjectStore("scenes",{keyPath:"sceneUrl"}),this._db.createObjectStore("versions",{keyPath:"sceneUrl"}),this._db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(t){p.Y.Error("Error while creating object stores. Exception: "+t.message),i()}}}else this._isSupported=!1,t&&t()}loadImage(e,t){const i=qT._ReturnFullUrlLocation(e),n=()=>{this._hasReachedQuota||null===this._db?t.src=e:this._saveImageIntoDBAsync(i,t)};this._mustUpdateRessources?n():this._loadImageFromDBAsync(i,t,n)}_loadImageFromDBAsync(e,t,i){if(this._isSupported&&null!==this._db){let n;const s=this._db.transaction(["textures"]);s.onabort=()=>{t.src=e},s.oncomplete=()=>{let s;n&&"function"==typeof URL?(s=URL.createObjectURL(n.data),t.onerror=()=>{p.Y.Error("Error loading image from blob URL: "+s+" switching back to web url: "+e),t.src=e},t.src=s):i()};const r=s.objectStore("textures").get(e);r.onsuccess=e=>{n=e.target.result},r.onerror=()=>{p.Y.Error("Error loading texture "+e+" from DB."),t.src=e}}else p.Y.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t.src=e}_saveImageIntoDBAsync(e,t){let i;if(this._isSupported){const n=()=>{let e;if(i&&"function"==typeof URL)try{e=URL.createObjectURL(i)}catch(n){e=URL.createObjectURL(i)}e&&(t.src=e)};if(qT._IsUASupportingBlobStorage){const s=new y.g;s.open("GET",e),s.responseType="blob",s.addEventListener("load",(()=>{if(200===s.status&&this._db){i=s.response;const o=this._db.transaction(["textures"],"readwrite");o.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(t){}n()},o.oncomplete=()=>{n()};const a={textureUrl:e,data:i};try{const e=o.objectStore("textures").put(a);e.onsuccess=()=>{},e.onerror=()=>{n()}}catch(r){25===r.code&&(qT._IsUASupportingBlobStorage=!1,this._enableTexturesOffline=!1),t.src=e}}else t.src=e}),!1),s.addEventListener("error",(()=>{p.Y.Error("Error in XHR request in BABYLON.Database."),t.src=e}),!1),s.send()}else t.src=e}else p.Y.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t.src=e}_checkVersionFromDB(e,t){this._loadVersionFromDBAsync(e,t,(()=>{this._saveVersionIntoDBAsync(e,t)}))}_loadVersionFromDBAsync(e,t,i){if(this._isSupported&&this._db){let s;try{const n=this._db.transaction(["versions"]);n.oncomplete=()=>{s?this._manifestVersionFound!==s.data?(this._mustUpdateRessources=!0,i()):t(s.data):(this._mustUpdateRessources=!0,i())},n.onabort=()=>{t(-1)};const r=n.objectStore("versions").get(e);r.onsuccess=e=>{s=e.target.result},r.onerror=()=>{p.Y.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(n){p.Y.Error("Error while accessing 'versions' object store (READ OP). Exception: "+n.message),t(-1)}}else p.Y.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t(-1)}_saveVersionIntoDBAsync(e,t){if(this._isSupported&&!this._hasReachedQuota&&this._db)try{const i=this._db.transaction(["versions"],"readwrite");i.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(i){}t(-1)},i.oncomplete=()=>{t(this._manifestVersionFound)};const n={sceneUrl:e,data:this._manifestVersionFound},s=i.objectStore("versions").put(n);s.onsuccess=()=>{},s.onerror=()=>{p.Y.Error("Error in DB add version request in BABYLON.Database.")}}catch(i){p.Y.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+i.message),t(-1)}else t(-1)}loadFile(e,t,i,n,s){const r=qT._ReturnFullUrlLocation(e),o=()=>{this._saveFileAsync(r,t,i,s,n)};this._checkVersionFromDB(r,(e=>{-1!==e?this._mustUpdateRessources?this._saveFileAsync(r,t,i,s,n):this._loadFileAsync(r,t,o):n&&n()}))}_loadFileAsync(e,t,i){if(this._isSupported&&this._db){let n,s;n=-1!==e.indexOf(".babylon")?"scenes":"textures";const r=this._db.transaction([n]);r.oncomplete=()=>{s?t(s.data):i()},r.onabort=()=>{i()};const o=r.objectStore(n).get(e);o.onsuccess=e=>{s=e.target.result},o.onerror=()=>{p.Y.Error("Error loading file "+e+" from DB."),i()}}else p.Y.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t()}_saveFileAsync(e,t,i,n,s){if(this._isSupported){let r;r=-1!==e.indexOf(".babylon")?"scenes":"textures";const o=new y.g;let a;o.open("GET",e+(null==e.match(/\?/)?"?":"&")+Date.now()),n&&(o.responseType="arraybuffer"),i&&(o.onprogress=i),o.addEventListener("load",(()=>{if(200===o.status||o.status<400&&qT._ValidateXHRData(o,n?6:1))if(a=n?o.response:o.responseText,!this._hasReachedQuota&&this._db){const n=this._db.transaction([r],"readwrite");let s;n.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(i){}t(a)},n.oncomplete=()=>{t(a)},s="scenes"===r?{sceneUrl:e,data:a,version:this._manifestVersionFound}:{textureUrl:e,data:a};try{const e=n.objectStore(r).put(s);e.onsuccess=()=>{},e.onerror=()=>{p.Y.Error("Error in DB add file request in BABYLON.Database.")}}catch(i){t(a)}}else t(a);else o.status>=400&&s?s(o):t()}),!1),o.addEventListener("error",(()=>{p.Y.Error("error on XHR request."),s&&s()}),!1),o.send()}else p.Y.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),s&&s()}static _ValidateXHRData(e,t=7){try{if(1&t){if(e.responseText&&e.responseText.length>0)return!0;if(1===t)return!1}if(2&t){const i=bv(e.response);if(i.width&&i.height&&i.width>0&&i.height>0)return!0;if(2===t)return!1}if(4&t){const t=new Uint8Array(e.response,0,3);return 68===t[0]&&68===t[1]&&83===t[2]}}catch(i){}return!1}}qT._IsUASupportingBlobStorage=!0,qT.IDBStorageEnabled=!1,qT._ParseURL=e=>{document.createElement("a").href=e;const t=e.substring(0,e.lastIndexOf("#")),i=e.substring(t.lastIndexOf("/")+1,e.length);return e.substring(0,e.indexOf(i,0))},qT._ReturnFullUrlLocation=e=>-1===e.indexOf("http:/")&&-1===e.indexOf("https:/")&&"undefined"!=typeof window?qT._ParseURL(window.location.href)+e:e;class $T{_isUbo(e){return void 0!==e.addUniform}constructor(e){this._isUbo(e)?(this.setMatrix3x3=e.updateMatrix3x3.bind(e),this.setMatrix2x2=e.updateMatrix2x2.bind(e),this.setFloat=e.updateFloat.bind(e),this.setFloat2=e.updateFloat2.bind(e),this.setFloat3=e.updateFloat3.bind(e),this.setFloat4=e.updateFloat4.bind(e),this.setFloatArray=e.updateFloatArray.bind(e),this.setArray=e.updateArray.bind(e),this.setIntArray=e.updateIntArray.bind(e),this.setMatrix=e.updateMatrix.bind(e),this.setMatrices=e.updateMatrices.bind(e),this.setVector3=e.updateVector3.bind(e),this.setVector4=e.updateVector4.bind(e),this.setColor3=e.updateColor3.bind(e),this.setColor4=e.updateColor4.bind(e),this.setDirectColor4=e.updateDirectColor4.bind(e),this.setInt=e.updateInt.bind(e),this.setInt2=e.updateInt2.bind(e),this.setInt3=e.updateInt3.bind(e),this.setInt4=e.updateInt4.bind(e)):(this.setMatrix3x3=e.setMatrix3x3.bind(e),this.setMatrix2x2=e.setMatrix2x2.bind(e),this.setFloat=e.setFloat.bind(e),this.setFloat2=e.setFloat2.bind(e),this.setFloat3=e.setFloat3.bind(e),this.setFloat4=e.setFloat4.bind(e),this.setFloatArray=e.setFloatArray.bind(e),this.setArray=e.setArray.bind(e),this.setIntArray=e.setIntArray.bind(e),this.setMatrix=e.setMatrix.bind(e),this.setMatrices=e.setMatrices.bind(e),this.setVector3=e.setVector3.bind(e),this.setVector4=e.setVector4.bind(e),this.setColor3=e.setColor3.bind(e),this.setColor4=e.setColor4.bind(e),this.setDirectColor4=e.setDirectColor4.bind(e),this.setInt=e.setInt.bind(e),this.setInt2=e.setInt2.bind(e),this.setInt3=e.setInt3.bind(e),this.setInt4=e.setInt4.bind(e))}}const QT="gpuUpdateParticlesPixelShader",ZT="#version 300 es\nvoid main() {\ndiscard;\n}\n";Ht.v.ShadersStore[QT]=ZT;const JT="gpuUpdateParticlesVertexShader",eS="#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\n#ifndef LOCAL\nuniform mat4 emitterWM;\n#endif\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\nin vec3 position;\n#ifdef CUSTOMEMITTER\nin vec3 initialPosition;\n#endif\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;\nin vec3 noiseCoordinates2;\n#endif\nout vec3 outPosition;\n#ifdef CUSTOMEMITTER\nout vec3 outInitialPosition;\n#endif\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;\nout vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec4 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nfloat newAge=age+timeDelta; \nif (newAge>=life && stopFactor != 0.) {\nvec3 newPosition;\nvec3 newDirection;\nvec4 randoms=getRandomVec4(seed.x);\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=newAge-life;\noutSeed=seed;\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nnewPosition=vec3(0,0,0);\nnewDirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nnewPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\nnewDirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nnewPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\nnewDirection=newPosition+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nnewPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\nnewDirection=normalize(direction1+(direction2-direction1)*randoms3);\n#else\nnewDirection=normalize(newPosition+directionRandomizer*randoms3);\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nnewPosition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\nnewDirection=direction1+(direction2-direction1)*randoms3;\n#else\nangle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;\nnewDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));\nnewDirection=normalize(newDirection);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.0001;\n#else\nfloat h=randoms2.y*height.y;\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h *height.x;\nnewPosition=vec3(randX,randY,randZ); \nif (abs(cos(coneAngle))==1.0) {\nnewDirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\nnewDirection=normalize(newPosition+directionRandomizer*randoms3); \n}\n#elif defined(CUSTOMEMITTER)\nnewPosition=initialPosition;\noutInitialPosition=initialPosition;\n#else \nnewPosition=vec3(0.,0.,0.);\nnewDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\n#ifdef LOCAL\noutPosition=newPosition;\n#else\noutPosition=(emitterWM*vec4(newPosition,1.)).xyz;\n#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\n#ifndef BILLBOARD \noutInitialDirection=direction;\n#endif\n#else\n#ifdef LOCAL\nvec3 initial=newDirection;\n#else \nvec3 initial=(emitterWM*vec4(newDirection,0.)).xyz;\n#endif\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#if defined(CUSTOMEMITTER)\noutPosition=position+(direction-position)*ageGradient; \noutInitialPosition=initialPosition;\n#else\noutPosition=position+direction*directionScale;\n#endif\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\n#else\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif \n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#else\nfloat cellStartOffset=0.;\n#endif \nfloat ratio=0.;\nif (cellInfos.w==1.0) {\nratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);\n}\nelse {\nratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);\n}\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}";Ht.v.ShadersStore[JT]=eS;(0,l.H)("BABYLON.WebGL2ParticleSystem",class{constructor(e,t){this._renderVAO=[],this._updateVAO=[],this.alignDataInBuffer=!1,this._parent=e,this._engine=t,this._updateEffectOptions={attributes:["position","initialPosition","age","life","seed","size","color","direction","initialDirection","angle","cellIndex","cellStartOffset","noiseCoordinates1","noiseCoordinates2"],uniformsNames:["currentCount","timeDelta","emitterWM","lifeTime","color1","color2","sizeRange","scaleRange","gravity","emitPower","direction1","direction2","minEmitBox","maxEmitBox","radius","directionRandomizer","height","coneAngle","stopFactor","angleRange","radiusRange","cellInfos","noiseStrength","limitVelocityDamping"],uniformBuffersNames:[],samplers:["randomSampler","randomSampler2","sizeGradientSampler","angularSpeedGradientSampler","velocityGradientSampler","limitVelocityGradientSampler","noiseSampler","dragGradientSampler"],defines:"",fallbacks:null,onCompiled:null,onError:null,indexParameters:null,maxSimultaneousLights:0,transformFeedbackVaryings:[]}}isUpdateBufferCreated(){return!!this._updateEffect}isUpdateBufferReady(){var e,t;return null!==(t=null===(e=this._updateEffect)||void 0===e?void 0:e.isReady())&&void 0!==t&&t}createUpdateBuffer(e){return this._updateEffectOptions.transformFeedbackVaryings=["outPosition"],this._updateEffectOptions.transformFeedbackVaryings.push("outAge"),this._updateEffectOptions.transformFeedbackVaryings.push("outSize"),this._updateEffectOptions.transformFeedbackVaryings.push("outLife"),this._updateEffectOptions.transformFeedbackVaryings.push("outSeed"),this._updateEffectOptions.transformFeedbackVaryings.push("outDirection"),this._parent.particleEmitterType instanceof di&&this._updateEffectOptions.transformFeedbackVaryings.push("outInitialPosition"),this._parent._colorGradientsTexture||this._updateEffectOptions.transformFeedbackVaryings.push("outColor"),this._parent._isBillboardBased||this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection"),this._parent.noiseTexture&&(this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1"),this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2")),this._updateEffectOptions.transformFeedbackVaryings.push("outAngle"),this._parent.isAnimationSheetEnabled&&(this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex"),this._parent.spriteRandomStartCell&&this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset")),this._updateEffectOptions.defines=e,this._updateEffect=new ft.Q("gpuUpdateParticles",this._updateEffectOptions,this._engine),new $T(this._updateEffect)}createVertexBuffers(e,t){this._updateVAO.push(this._createUpdateVAO(e)),this._renderVAO.push(this._engine.recordVertexArrayObject(t,null,this._parent._getWrapper(this._parent.blendMode).effect)),this._engine.bindArrayBuffer(null)}createParticleBuffer(e){return e}bindDrawBuffers(e){this._engine.bindVertexArrayObject(this._renderVAO[e],null)}preUpdateParticleBuffer(){const e=this._engine;if(this._engine.enableEffect(this._updateEffect),!e.setState)throw new Error("GPU particles cannot work without a full Engine. ThinEngine is not supported")}updateParticleBuffer(e,t,i){this._updateEffect.setTexture("randomSampler",this._parent._randomTexture),this._updateEffect.setTexture("randomSampler2",this._parent._randomTexture2),this._parent._sizeGradientsTexture&&this._updateEffect.setTexture("sizeGradientSampler",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateEffect.setTexture("angularSpeedGradientSampler",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateEffect.setTexture("velocityGradientSampler",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateEffect.setTexture("limitVelocityGradientSampler",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateEffect.setTexture("dragGradientSampler",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateEffect.setTexture("noiseSampler",this._parent.noiseTexture),this._engine.bindVertexArrayObject(this._updateVAO[e],null);const n=this._engine;n.bindTransformFeedbackBuffer(t.getBuffer()),n.setRasterizerState(!1),n.beginTransformFeedback(!0),n.drawArraysType(3,0,i),n.endTransformFeedback(),n.setRasterizerState(!0),n.bindTransformFeedbackBuffer(null)}releaseBuffers(){}releaseVertexBuffers(){for(let e=0;ee)return void i(t[0],t[0],1);for(let s=0;s=n.gradient&&e<=r.gradient){return void i(n,r,(e-n.gradient)/(r.gradient-n.gradient))}}const n=t.length-1;i(t[n],t[n],1)}}class aS{constructor(e){this.particleSystem=e,this.position=o.P.Zero(),this.direction=o.P.Zero(),this.color=new a.HE(0,0,0,0),this.colorStep=new a.HE(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new o.FM(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new a.HE(0,0,0,0),this._currentColor2=new a.HE(0,0,0,0),this._currentSize1=0,this._currentSize2=0,this._currentAngularSpeed1=0,this._currentAngularSpeed2=0,this._currentVelocity1=0,this._currentVelocity2=0,this._currentLimitVelocity1=0,this._currentLimitVelocity2=0,this._currentDrag1=0,this._currentDrag2=0,this.id=aS._Count++,this.particleSystem.isAnimationSheetEnabled&&this._updateCellInfoFromSystem()}_updateCellInfoFromSystem(){this.cellIndex=this.particleSystem.startSpriteCellID}updateCellIndex(){let e=this.age,t=this.particleSystem.spriteCellChangeSpeed;this.particleSystem.spriteRandomStartCell&&(void 0===this._randomCellOffset&&(this._randomCellOffset=Math.random()*this.lifeTime),0===t?(t=1,e=this._randomCellOffset):e+=this._randomCellOffset);const i=this._initialEndSpriteCellID-this._initialStartSpriteCellID;let n;n=this._initialSpriteCellLoop?S.R.Clamp(e*t%this.lifeTime/this.lifeTime):S.R.Clamp(e*t/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+n*i|0}_inheritParticleInfoToSubEmitter(e){if(e.particleSystem.emitter.position){const t=e.particleSystem.emitter;if(t.position.copyFrom(this.position),e.inheritDirection){const e=o.jp.Vector3[0];this.direction.normalizeToRef(e),t.setDirection(e,0,Math.PI/2)}}else{e.particleSystem.emitter.copyFrom(this.position)}this.direction.scaleToRef(e.inheritedVelocityAmount/2,o.jp.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(o.jp.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach((e=>{this._inheritParticleInfoToSubEmitter(e)}))}_reset(){this.age=0,this.id=aS._Count++,this._currentColorGradient=null,this._currentSizeGradient=null,this._currentAngularSpeedGradient=null,this._currentVelocityGradient=null,this._currentLimitVelocityGradient=null,this._currentDragGradient=null,this.cellIndex=this.particleSystem.startSpriteCellID,this._randomCellOffset=void 0}copyTo(e){e.position.copyFrom(this.position),this._initialDirection?e._initialDirection?e._initialDirection.copyFrom(this._initialDirection):e._initialDirection=this._initialDirection.clone():e._initialDirection=null,e.direction.copyFrom(this.direction),this._localPosition&&(e._localPosition?e._localPosition.copyFrom(this._localPosition):e._localPosition=this._localPosition.clone()),e.color.copyFrom(this.color),e.colorStep.copyFrom(this.colorStep),e.lifeTime=this.lifeTime,e.age=this.age,e._randomCellOffset=this._randomCellOffset,e.size=this.size,e.scale.copyFrom(this.scale),e.angle=this.angle,e.angularSpeed=this.angularSpeed,e.particleSystem=this.particleSystem,e.cellIndex=this.cellIndex,e.id=this.id,e._attachedSubEmitters=this._attachedSubEmitters,this._currentColorGradient&&(e._currentColorGradient=this._currentColorGradient,e._currentColor1.copyFrom(this._currentColor1),e._currentColor2.copyFrom(this._currentColor2)),this._currentSizeGradient&&(e._currentSizeGradient=this._currentSizeGradient,e._currentSize1=this._currentSize1,e._currentSize2=this._currentSize2),this._currentAngularSpeedGradient&&(e._currentAngularSpeedGradient=this._currentAngularSpeedGradient,e._currentAngularSpeed1=this._currentAngularSpeed1,e._currentAngularSpeed2=this._currentAngularSpeed2),this._currentVelocityGradient&&(e._currentVelocityGradient=this._currentVelocityGradient,e._currentVelocity1=this._currentVelocity1,e._currentVelocity2=this._currentVelocity2),this._currentLimitVelocityGradient&&(e._currentLimitVelocityGradient=this._currentLimitVelocityGradient,e._currentLimitVelocity1=this._currentLimitVelocity1,e._currentLimitVelocity2=this._currentLimitVelocity2),this._currentDragGradient&&(e._currentDragGradient=this._currentDragGradient,e._currentDrag1=this._currentDrag1,e._currentDrag2=this._currentDrag2),this.particleSystem.isAnimationSheetEnabled&&(e._initialStartSpriteCellID=this._initialStartSpriteCellID,e._initialEndSpriteCellID=this._initialEndSpriteCellID,e._initialSpriteCellLoop=this._initialSpriteCellLoop),this.particleSystem.useRampGradients&&(e.remapData&&this.remapData?e.remapData.copyFrom(this.remapData):e.remapData=new o.Lt(0,0,0,0)),this._randomNoiseCoordinates1&&(e._randomNoiseCoordinates1?(e._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1),e._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2)):(e._randomNoiseCoordinates1=this._randomNoiseCoordinates1.clone(),e._randomNoiseCoordinates2=this._randomNoiseCoordinates2.clone()))}}var lS;aS._Count=0,function(e){e[e.ATTACHED=0]="ATTACHED",e[e.END=1]="END"}(lS||(lS={}));class hS{constructor(e){if(this.particleSystem=e,this.type=lS.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){const t=(0,l.q)("BABYLON.AbstractMesh");e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;if(e){if(e instanceof o.P)e=e.clone();else if(-1!==e.getClassName().indexOf("Mesh")){e=new((0,l.q)("BABYLON.Mesh"))("",e.getScene()),e.isVisible=!1}}else e=new o.P;const t=new hS(this.particleSystem.clone(this.particleSystem.name,e));return t.particleSystem.name+="Clone",t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem._disposeEmitterOnDispose=!0,t.particleSystem.disposeOnStop=!0,t}serialize(e=!1){const t={};return t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem=this.particleSystem.serialize(e),t}static _ParseParticleSystem(e,t,i,n=!1){throw(0,ge.S)("ParseParticle")}static Parse(e,t,i){const n=e.particleSystem,s=new hS(hS._ParseParticleSystem(n,t,i,!0));return s.type=e.type,s.inheritDirection=e.inheritDirection,s.inheritedVelocityAmount=e.inheritedVelocityAmount,s.particleSystem._isSubEmitter=!0,s}dispose(){this.particleSystem.dispose()}}const cS="particlesPixelShader",dS="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include\n#include\n#include\n#include\n#include\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ht.v.ShadersStore[cS]=dS;const uS="particlesVertexShader",pS="attribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET\nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD\nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction;\n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET\nuniform vec3 particlesInfos; \n#endif\nvarying vec2 vUV;\nvarying vec4 vColor;\nvarying vec3 vPositionW;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)\nuniform mat4 invView;\n#endif\n#include\n#include\n#ifdef BILLBOARD\nuniform vec3 eyePosition;\n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix= mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\n#ifdef BILLBOARDSTRETCHED_LOCAL\nvec3 row1=direction;\n#else\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\n#endif\nmat3 rotMatrix= mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD\nvec3 rotatedCorner;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvPositionW=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition;\nvPositionW=rotateAlign(toCamera,rotatedCorner);\nvec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;\n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;\nvPositionW=(invView*vec4(viewPos,1)).xyz;\n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\ngl_Position=projection*vec4(viewPos,1.0);\n#else\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvPositionW=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(vPositionW,1.0);\n#endif\nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex*particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset/particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nvec4 worldPos=vec4(vPositionW,1.0);\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";Ht.v.ShadersStore[uS]=pS;class fS extends pi{set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get useRampGradients(){return this._useRampGradients}set useRampGradients(e){this._useRampGradients!==e&&(this._useRampGradients=e,this._resetEffect())}get particles(){return this._particles}getActiveCount(){return this._particles.length}getClassName(){return"ParticleSystem"}isStopping(){return this._stopped&&this.isAlive()}getCustomEffect(e=0){var t,i;return null!==(i=null===(t=this._customWrappers[e])||void 0===t?void 0:t.effect)&&void 0!==i?i:this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){var t;return null!==(t=this._customWrappers[e])&&void 0!==t?t:this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new $t.q(this._engine),this._customWrappers[t].effect=e,this._customWrappers[t].drawContext&&(this._customWrappers[t].drawContext.useInstancing=this._useInstancing)}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new r.y$),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"particles"}get vertexBuffers(){return this._vertexBuffers}get indexBuffer(){return this._indexBuffer}constructor(e,t,i,n=null,s=!1,l=.01){super(e),this._emitterInverseWorldMatrix=o.y3.Identity(),this._inheritedVelocityOffset=new o.P,this.onDisposeObservable=new r.y$,this.onStoppedObservable=new r.y$,this._particles=new Array,this._stockParticles=new Array,this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new a.HE(0,0,0,0),this._colorDiff=new a.HE(0,0,0,0),this._scaledDirection=o.P.Zero(),this._scaledGravity=o.P.Zero(),this._currentRenderId=-1,this._useInstancing=!1,this._started=!1,this._stopped=!1,this._actualFrame=0,this._currentEmitRate1=0,this._currentEmitRate2=0,this._currentStartSize1=0,this._currentStartSize2=0,this.updateInAnimate=!0,this._rawTextureWidth=256,this._useRampGradients=!1,this._disposeEmitterOnDispose=!1,this.isLocal=!1,this.isGPU=!1,this._onBeforeDrawParticlesObservable=null,this.recycleParticle=e=>{const t=this._particles.pop();t!==e&&t.copyTo(e),this._stockParticles.push(t)},this._createParticle=()=>{let e;if(0!==this._stockParticles.length?(e=this._stockParticles.pop(),e._reset()):e=new aS(this),this._subEmitters&&this._subEmitters.length>0){const t=this._subEmitters[Math.floor(Math.random()*this._subEmitters.length)];e._attachedSubEmitters=[],t.forEach((t=>{if(t.type===lS.ATTACHED){const i=t.clone();e._attachedSubEmitters.push(i),i.particleSystem.start()}}))}return e},this._emitFromParticle=e=>{if(!this._subEmitters||0===this._subEmitters.length)return;const t=Math.floor(Math.random()*this._subEmitters.length);this._subEmitters[t].forEach((t=>{if(t.type===lS.END){const i=t.clone();e._inheritParticleInfoToSubEmitter(i),i.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(i.particleSystem),i.particleSystem.start()}}))},this._capacity=t,this._epsilon=l,this._isAnimationSheetEnabled=s,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=o.y3.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||m.l.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._attachImageProcessingConfiguration(null),this._customWrappers={0:new $t.q(this._engine)},this._customWrappers[0].effect=n,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new ni;let h=null;this.updateFunction=e=>{var t;let i=null;this.noiseTexture&&(i=this.noiseTexture.getSize(),null===(t=this.noiseTexture.getContent())||void 0===t||t.then((e=>{h=e})));for(let n=0;nt.lifeTime){const e=t.age-r;s=(t.lifeTime-r)*s/e,t.age=t.lifeTime}const l=t.age/t.lifeTime;this._colorGradients&&this._colorGradients.length>0?oS.GetCurrentGradient(l,this._colorGradients,((e,i,n)=>{e!==t._currentColorGradient&&(t._currentColor1.copyFrom(t._currentColor2),i.getColorToRef(t._currentColor2),t._currentColorGradient=e),a.HE.LerpToRef(t._currentColor1,t._currentColor2,n,t.color)})):(t.colorStep.scaleToRef(s,this._scaledColorStep),t.color.addInPlace(this._scaledColorStep),t.color.a<0&&(t.color.a=0)),this._angularSpeedGradients&&this._angularSpeedGradients.length>0&&oS.GetCurrentGradient(l,this._angularSpeedGradients,((e,i,n)=>{e!==t._currentAngularSpeedGradient&&(t._currentAngularSpeed1=t._currentAngularSpeed2,t._currentAngularSpeed2=i.getFactor(),t._currentAngularSpeedGradient=e),t.angularSpeed=S.R.Lerp(t._currentAngularSpeed1,t._currentAngularSpeed2,n)})),t.angle+=t.angularSpeed*s;let c=s;if(this._velocityGradients&&this._velocityGradients.length>0&&oS.GetCurrentGradient(l,this._velocityGradients,((e,i,n)=>{e!==t._currentVelocityGradient&&(t._currentVelocity1=t._currentVelocity2,t._currentVelocity2=i.getFactor(),t._currentVelocityGradient=e),c*=S.R.Lerp(t._currentVelocity1,t._currentVelocity2,n)})),t.direction.scaleToRef(c,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&oS.GetCurrentGradient(l,this._limitVelocityGradients,((e,i,n)=>{e!==t._currentLimitVelocityGradient&&(t._currentLimitVelocity1=t._currentLimitVelocity2,t._currentLimitVelocity2=i.getFactor(),t._currentLimitVelocityGradient=e);const s=S.R.Lerp(t._currentLimitVelocity1,t._currentLimitVelocity2,n);t.direction.length()>s&&t.direction.scaleInPlace(this.limitVelocityDamping)})),this._dragGradients&&this._dragGradients.length>0&&oS.GetCurrentGradient(l,this._dragGradients,((e,i,n)=>{e!==t._currentDragGradient&&(t._currentDrag1=t._currentDrag2,t._currentDrag2=i.getFactor(),t._currentDragGradient=e);const s=S.R.Lerp(t._currentDrag1,t._currentDrag2,n);this._scaledDirection.scaleInPlace(1-s)})),this.isLocal&&t._localPosition?(t._localPosition.addInPlace(this._scaledDirection),o.P.TransformCoordinatesToRef(t._localPosition,this._emitterWorldMatrix,t.position)):t.position.addInPlace(this._scaledDirection),h&&i&&t._randomNoiseCoordinates1){const e=this._fetchR(t._randomNoiseCoordinates1.x,t._randomNoiseCoordinates1.y,i.width,i.height,h),n=this._fetchR(t._randomNoiseCoordinates1.z,t._randomNoiseCoordinates2.x,i.width,i.height,h),r=this._fetchR(t._randomNoiseCoordinates2.y,t._randomNoiseCoordinates2.z,i.width,i.height,h),a=o.jp.Vector3[0],l=o.jp.Vector3[1];a.copyFromFloats((2*e-1)*this.noiseStrength.x,(2*n-1)*this.noiseStrength.y,(2*r-1)*this.noiseStrength.z),a.scaleToRef(s,l),t.direction.addInPlace(l)}this.gravity.scaleToRef(s,this._scaledGravity),t.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&oS.GetCurrentGradient(l,this._sizeGradients,((e,i,n)=>{e!==t._currentSizeGradient&&(t._currentSize1=t._currentSize2,t._currentSize2=i.getFactor(),t._currentSizeGradient=e),t.size=S.R.Lerp(t._currentSize1,t._currentSize2,n)})),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&oS.GetCurrentGradient(l,this._colorRemapGradients,((e,i,n)=>{const s=S.R.Lerp(e.factor1,i.factor1,n),r=S.R.Lerp(e.factor2,i.factor2,n);t.remapData.x=s,t.remapData.y=r-s})),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&oS.GetCurrentGradient(l,this._alphaRemapGradients,((e,i,n)=>{const s=S.R.Lerp(e.factor1,i.factor1,n),r=S.R.Lerp(e.factor2,i.factor2,n);t.remapData.z=s,t.remapData.w=r-s}))),this._isAnimationSheetEnabled&&t.updateCellIndex(),t._inheritParticleInfoToSubEmitters(),t.age>=t.lifeTime&&(this._emitFromParticle(t),t._attachedSubEmitters&&(t._attachedSubEmitters.forEach((e=>{e.particleSystem.disposeOnStop=!0,e.particleSystem.stop()})),t._attachedSubEmitters=null),this.recycleParticle(t),n--)}}}_addFactorGradient(e,t,i,n){const s=new rS(t,i,n);e.push(s),e.sort(((e,t)=>e.gradientt.gradient?1:0))}_removeFactorGradient(e,t){if(!e)return;let i=0;for(const n of e){if(n.gradient===t){e.splice(i,1);break}i++}}addLifeTimeGradient(e,t,i){return this._lifeTimeGradients||(this._lifeTimeGradients=[]),this._addFactorGradient(this._lifeTimeGradients,e,t,i),this}removeLifeTimeGradient(e){return this._removeFactorGradient(this._lifeTimeGradients,e),this}addSizeGradient(e,t,i){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t,i),this}removeSizeGradient(e){return this._removeFactorGradient(this._sizeGradients,e),this}addColorRemapGradient(e,t,i){return this._colorRemapGradients||(this._colorRemapGradients=[]),this._addFactorGradient(this._colorRemapGradients,e,t,i),this}removeColorRemapGradient(e){return this._removeFactorGradient(this._colorRemapGradients,e),this}addAlphaRemapGradient(e,t,i){return this._alphaRemapGradients||(this._alphaRemapGradients=[]),this._addFactorGradient(this._alphaRemapGradients,e,t,i),this}removeAlphaRemapGradient(e){return this._removeFactorGradient(this._alphaRemapGradients,e),this}addAngularSpeedGradient(e,t,i){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t,i),this}removeAngularSpeedGradient(e){return this._removeFactorGradient(this._angularSpeedGradients,e),this}addVelocityGradient(e,t,i){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t,i),this}removeVelocityGradient(e){return this._removeFactorGradient(this._velocityGradients,e),this}addLimitVelocityGradient(e,t,i){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t,i),this}removeLimitVelocityGradient(e){return this._removeFactorGradient(this._limitVelocityGradients,e),this}addDragGradient(e,t,i){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t,i),this}removeDragGradient(e){return this._removeFactorGradient(this._dragGradients,e),this}addEmitRateGradient(e,t,i){return this._emitRateGradients||(this._emitRateGradients=[]),this._addFactorGradient(this._emitRateGradients,e,t,i),this}removeEmitRateGradient(e){return this._removeFactorGradient(this._emitRateGradients,e),this}addStartSizeGradient(e,t,i){return this._startSizeGradients||(this._startSizeGradients=[]),this._addFactorGradient(this._startSizeGradients,e,t,i),this}removeStartSizeGradient(e){return this._removeFactorGradient(this._startSizeGradients,e),this}_createRampGradientTexture(){if(!this._rampGradients||!this._rampGradients.length||this._rampGradientsTexture||!this._scene)return;const e=new Uint8Array(4*this._rawTextureWidth),t=a.zZ.Color3[0];for(let i=0;i{a.Wo.LerpToRef(n.color,s.color,r,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255}))}this._rampGradientsTexture=ze.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1)}getRampGradients(){return this._rampGradients}forceRefreshGradients(){this._syncRampGradientTexture()}_syncRampGradientTexture(){this._rampGradients&&(this._rampGradients.sort(((e,t)=>e.gradientt.gradient?1:0)),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture())}addRampGradient(e,t){this._rampGradients||(this._rampGradients=[]);const i=new sS(e,t);return this._rampGradients.push(i),this._syncRampGradientTexture(),this}removeRampGradient(e){return this._removeGradientAndTexture(e,this._rampGradients,this._rampGradientsTexture),this._rampGradientsTexture=null,this._rampGradients&&this._rampGradients.length>0&&this._createRampGradientTexture(),this}addColorGradient(e,t,i){this._colorGradients||(this._colorGradients=[]);const n=new nS(e,t,i);return this._colorGradients.push(n),this._colorGradients.sort(((e,t)=>e.gradientt.gradient?1:0)),this}removeColorGradient(e){if(!this._colorGradients)return this;let t=0;for(const i of this._colorGradients){if(i.gradient===e){this._colorGradients.splice(t,1);break}t++}return this}resetDrawCache(){for(const e of this._drawWrappers)if(e)for(const t of e)null==t||t.dispose();this._drawWrappers=[]}_fetchR(e,t,i,n,s){return s[4*(((e=.5*Math.abs(e)+.5)*i%i|0)+((t=.5*Math.abs(t)+.5)*n%n|0)*i)]/255}_reset(){this._resetEffect()}_resetEffect(){this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),this._createVertexBuffers()}_createVertexBuffers(){this._vertexBufferSize=this._useInstancing?10:12,this._isAnimationSheetEnabled&&(this._vertexBufferSize+=1),this._isBillboardBased&&this.billboardMode!==fS.BILLBOARDMODE_STRETCHED&&this.billboardMode!==fS.BILLBOARDMODE_STRETCHED_LOCAL||(this._vertexBufferSize+=3),this._useRampGradients&&(this._vertexBufferSize+=4);const e=this._engine,t=this._vertexBufferSize*(this._useInstancing?1:4);this._vertexData=new Float32Array(this._capacity*t),this._vertexBuffer=new ne.l(e,this._vertexData,!0,t);let i=0;const n=this._vertexBuffer.createVertexBuffer(ne.o.PositionKind,i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[ne.o.PositionKind]=n,i+=3;const s=this._vertexBuffer.createVertexBuffer(ne.o.ColorKind,i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[ne.o.ColorKind]=s,i+=4;const r=this._vertexBuffer.createVertexBuffer("angle",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=r,i+=1;const o=this._vertexBuffer.createVertexBuffer("size",i,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=o,i+=2,this._isAnimationSheetEnabled){const e=this._vertexBuffer.createVertexBuffer("cellIndex",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=e,i+=1}if(!this._isBillboardBased||this.billboardMode===fS.BILLBOARDMODE_STRETCHED||this.billboardMode===fS.BILLBOARDMODE_STRETCHED_LOCAL){const e=this._vertexBuffer.createVertexBuffer("direction",i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=e,i+=3}if(this._useRampGradients){const e=this._vertexBuffer.createVertexBuffer("remapData",i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=e,i+=4}let a;if(this._useInstancing){const t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new ne.l(e,t,!1,2),a=this._spriteBuffer.createVertexBuffer("offset",0,2)}else a=this._vertexBuffer.createVertexBuffer("offset",i,2,this._vertexBufferSize,this._useInstancing),i+=2;this._vertexBuffers.offset=a,this.resetDrawCache()}_createIndexBuffer(){if(this._useInstancing)return;const e=[];let t=0;for(let i=0;i{e instanceof fS?this._subEmitters.push([new hS(e)]):e instanceof hS?this._subEmitters.push([e]):e instanceof Array&&this._subEmitters.push(e)}))}start(e=this.startDelay){var t;if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";if(e)setTimeout((()=>{this.start(0)}),e);else{if(this._prepareSubEmitterInternalArray(),this._started=!0,this._stopped=!1,this._actualFrame=0,this._subEmitters&&0!=this._subEmitters.length&&(this.activeSubSystems=new Array),this._emitRateGradients&&(this._emitRateGradients.length>0&&(this._currentEmitRateGradient=this._emitRateGradients[0],this._currentEmitRate1=this._currentEmitRateGradient.getFactor(),this._currentEmitRate2=this._currentEmitRate1),this._emitRateGradients.length>1&&(this._currentEmitRate2=this._emitRateGradients[1].getFactor())),this._startSizeGradients&&(this._startSizeGradients.length>0&&(this._currentStartSizeGradient=this._startSizeGradients[0],this._currentStartSize1=this._currentStartSizeGradient.getFactor(),this._currentStartSize2=this._currentStartSize1),this._startSizeGradients.length>1&&(this._currentStartSize2=this._startSizeGradients[1].getFactor())),this.preWarmCycles){-1!==(null===(t=this.emitter)||void 0===t?void 0:t.getClassName().indexOf("Mesh"))&&this.emitter.computeWorldMatrix(!0);const e=this.noiseTexture;if(e&&e.onGeneratedObservable)e.onGeneratedObservable.addOnce((()=>{setTimeout((()=>{for(let t=0;t0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}}stop(e=!0){this._stopped||(this.onStoppedObservable.notifyObservers(this),this._stopped=!0,e&&this._stopSubEmitters())}reset(){this._stockParticles.length=0,this._particles.length=0}_appendParticleVertex(e,t,i,n){let s=e*this._vertexBufferSize;if(this._vertexData[s++]=t.position.x+this.worldOffset.x,this._vertexData[s++]=t.position.y+this.worldOffset.y,this._vertexData[s++]=t.position.z+this.worldOffset.z,this._vertexData[s++]=t.color.r,this._vertexData[s++]=t.color.g,this._vertexData[s++]=t.color.b,this._vertexData[s++]=t.color.a,this._vertexData[s++]=t.angle,this._vertexData[s++]=t.scale.x*t.size,this._vertexData[s++]=t.scale.y*t.size,this._isAnimationSheetEnabled&&(this._vertexData[s++]=t.cellIndex),this._isBillboardBased)this.billboardMode!==fS.BILLBOARDMODE_STRETCHED&&this.billboardMode!==fS.BILLBOARDMODE_STRETCHED_LOCAL||(this._vertexData[s++]=t.direction.x,this._vertexData[s++]=t.direction.y,this._vertexData[s++]=t.direction.z);else if(t._initialDirection){let e=t._initialDirection;this.isLocal&&(o.P.TransformNormalToRef(e,this._emitterWorldMatrix,o.jp.Vector3[0]),e=o.jp.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[s++]=e.x,this._vertexData[s++]=e.y,this._vertexData[s++]=e.z}else{let e=t.direction;this.isLocal&&(o.P.TransformNormalToRef(e,this._emitterWorldMatrix,o.jp.Vector3[0]),e=o.jp.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[s++]=e.x,this._vertexData[s++]=e.y,this._vertexData[s++]=e.z}this._useRampGradients&&t.remapData&&(this._vertexData[s++]=t.remapData.x,this._vertexData[s++]=t.remapData.y,this._vertexData[s++]=t.remapData.z,this._vertexData[s++]=t.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===n?n=this._epsilon:1===n&&(n=1-this._epsilon)),this._vertexData[s++]=i,this._vertexData[s++]=n)}_stopSubEmitters(){this.activeSubSystems&&(this.activeSubSystems.forEach((e=>{e.stop(!0)})),this.activeSubSystems=new Array)}_removeFromRoot(){if(!this._rootParticleSystem)return;const e=this._rootParticleSystem.activeSubSystems.indexOf(this);-1!==e&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}_update(e){if(this._alive=this._particles.length>0,this.emitter.position){const e=this.emitter;this._emitterWorldMatrix=e.getWorldMatrix()}else{const e=this.emitter;this._emitterWorldMatrix=o.y3.Translation(e.x,e.y,e.z)}let t;this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);for(let i=0;i0){const e=S.R.Clamp(this._actualFrame/this.targetStopDuration);oS.GetCurrentGradient(e,this._lifeTimeGradients,((i,n)=>{const s=i,r=n,o=s.getFactor(),a=r.getFactor(),l=(e-s.gradient)/(r.gradient-s.gradient);t.lifeTime=S.R.Lerp(o,a,l)}))}else t.lifeTime=S.R.RandomRange(this.minLifeTime,this.maxLifeTime);const e=S.R.RandomRange(this.minEmitPower,this.maxEmitPower);if(this.startPositionFunction?this.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal):this.particleEmitterType.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal),this.isLocal&&(t._localPosition?t._localPosition.copyFrom(t.position):t._localPosition=t.position.clone(),o.P.TransformCoordinatesToRef(t._localPosition,this._emitterWorldMatrix,t.position)),this.startDirectionFunction?this.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal):this.particleEmitterType.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal,this._emitterInverseWorldMatrix),0===e?t._initialDirection?t._initialDirection.copyFrom(t.direction):t._initialDirection=t.direction.clone():t._initialDirection=null,t.direction.scaleInPlace(e),this._sizeGradients&&0!==this._sizeGradients.length?(t._currentSizeGradient=this._sizeGradients[0],t._currentSize1=t._currentSizeGradient.getFactor(),t.size=t._currentSize1,this._sizeGradients.length>1?t._currentSize2=this._sizeGradients[1].getFactor():t._currentSize2=t._currentSize1):t.size=S.R.RandomRange(this.minSize,this.maxSize),t.scale.copyFromFloats(S.R.RandomRange(this.minScaleX,this.maxScaleX),S.R.RandomRange(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){const e=this._actualFrame/this.targetStopDuration;oS.GetCurrentGradient(e,this._startSizeGradients,((e,i,n)=>{e!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=i.getFactor(),this._currentStartSizeGradient=e);const s=S.R.Lerp(this._currentStartSize1,this._currentStartSize2,n);t.scale.scaleInPlace(s)}))}if(this._angularSpeedGradients&&0!==this._angularSpeedGradients.length?(t._currentAngularSpeedGradient=this._angularSpeedGradients[0],t.angularSpeed=t._currentAngularSpeedGradient.getFactor(),t._currentAngularSpeed1=t.angularSpeed,this._angularSpeedGradients.length>1?t._currentAngularSpeed2=this._angularSpeedGradients[1].getFactor():t._currentAngularSpeed2=t._currentAngularSpeed1):t.angularSpeed=S.R.RandomRange(this.minAngularSpeed,this.maxAngularSpeed),t.angle=S.R.RandomRange(this.minInitialRotation,this.maxInitialRotation),this._velocityGradients&&this._velocityGradients.length>0&&(t._currentVelocityGradient=this._velocityGradients[0],t._currentVelocity1=t._currentVelocityGradient.getFactor(),this._velocityGradients.length>1?t._currentVelocity2=this._velocityGradients[1].getFactor():t._currentVelocity2=t._currentVelocity1),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&(t._currentLimitVelocityGradient=this._limitVelocityGradients[0],t._currentLimitVelocity1=t._currentLimitVelocityGradient.getFactor(),this._limitVelocityGradients.length>1?t._currentLimitVelocity2=this._limitVelocityGradients[1].getFactor():t._currentLimitVelocity2=t._currentLimitVelocity1),this._dragGradients&&this._dragGradients.length>0&&(t._currentDragGradient=this._dragGradients[0],t._currentDrag1=t._currentDragGradient.getFactor(),this._dragGradients.length>1?t._currentDrag2=this._dragGradients[1].getFactor():t._currentDrag2=t._currentDrag1),this._colorGradients&&0!==this._colorGradients.length)t._currentColorGradient=this._colorGradients[0],t._currentColorGradient.getColorToRef(t.color),t._currentColor1.copyFrom(t.color),this._colorGradients.length>1?this._colorGradients[1].getColorToRef(t._currentColor2):t._currentColor2.copyFrom(t.color);else{const e=S.R.RandomRange(0,1);a.HE.LerpToRef(this.color1,this.color2,e,t.color),this.colorDead.subtractToRef(t.color,this._colorDiff),this._colorDiff.scaleToRef(1/t.lifeTime,t.colorStep)}this._isAnimationSheetEnabled&&(t._initialStartSpriteCellID=this.startSpriteCellID,t._initialEndSpriteCellID=this.endSpriteCellID,t._initialSpriteCellLoop=this.spriteCellLoop),t.direction.addInPlace(this._inheritedVelocityOffset),this._useRampGradients&&(t.remapData=new o.Lt(0,1,0,1)),this.noiseTexture&&(t._randomNoiseCoordinates1?(t._randomNoiseCoordinates1.copyFromFloats(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2.copyFromFloats(Math.random(),Math.random(),Math.random())):(t._randomNoiseCoordinates1=new o.P(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new o.P(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){const n=[ne.o.PositionKind,ne.o.ColorKind,"angle","offset","size"];return e&&n.push("cellIndex"),t||n.push("direction"),i&&n.push("remapData"),n}static _GetEffectCreationOptions(e=!1,t=!1){const i=["invView","view","projection","textureMask","translationPivot","eyePosition"];return(0,ua.qx)(i),e&&i.push("particlesInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t){if(this._scene&&(0,ua.lK)(this,this._scene,e),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),t===fS.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this._useRampGradients&&e.push("#define RAMPGRADIENT"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case fS.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case fS.BILLBOARDMODE_STRETCHED:case fS.BILLBOARDMODE_STRETCHED_LOCAL:e.push("#define BILLBOARDSTRETCHED"),this.billboardMode===fS.BILLBOARDMODE_STRETCHED_LOCAL&&e.push("#define BILLBOARDSTRETCHED_LOCAL");break;case fS.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL")}this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...fS._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&this.billboardMode!==fS.BILLBOARDMODE_STRETCHED&&this.billboardMode!==fS.BILLBOARDMODE_STRETCHED_LOCAL,this._useRampGradients)),e.push(...fS._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(ii.$.PrepareUniforms(e,this._imageProcessingConfigurationDefines),ii.$.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(null==t?void 0:t.effect)return t;const i=[];this.fillDefines(i,e);const n=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:0;let s=this._drawWrappers[n];s||(s=this._drawWrappers[n]=[]);let r=s[e];r||(r=new $t.q(this._engine),r.drawContext&&(r.drawContext.useInstancing=this._useInstancing),s[e]=r);const o=i.join("\n");if(r.defines!==o){const e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),r.setEffect(this._engine.createEffect("particles",e,t,i,o),o)}return r}animate(e=!1){var t;if(!this._started)return;if(!e&&this._scene){if(!this.isReady())return;if(this._currentRenderId===this._scene.getFrameId())return;this._currentRenderId=this._scene.getFrameId()}let i;if(this._scaledUpdateSpeed=this.updateSpeed*(e?this.preWarmStepOffset:(null===(t=this._scene)||void 0===t?void 0:t.getAnimationRatio())||1),this.manualEmitCount>-1)i=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0;else{let e=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){const t=this._actualFrame/this.targetStopDuration;oS.GetCurrentGradient(t,this._emitRateGradients,((t,i,n)=>{t!==this._currentEmitRateGradient&&(this._currentEmitRate1=this._currentEmitRate2,this._currentEmitRate2=i.getFactor(),this._currentEmitRateGradient=t),e=S.R.Lerp(this._currentEmitRate1,this._currentEmitRate2,n)}))}i=e*this._scaledUpdateSpeed>>0,this._newPartsExcess+=e*this._scaledUpdateSpeed-i}if(this._newPartsExcess>1&&(i+=this._newPartsExcess>>0,this._newPartsExcess-=this._newPartsExcess>>0),this._alive=!1,this._stopped?i=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(i),this._stopped&&(this._alive||(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene&&this._scene._toBeDisposed.push(this))),!e){let e=0;for(let t=0;t=0&&(a.invertToRef(o.jp.Matrix[0]),s.setMatrix("invView",o.jp.Matrix[0])),void 0!==this._vertexArrayObject?(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,this._indexBuffer,s)),this._engine.bindVertexArrayObject(this._vertexArrayObject,this._indexBuffer)):r.bindBuffers(this._vertexBuffers,this._indexBuffer,s),this.useLogarithmicDepth&&this._scene&&It.G.BindLogDepth(l,s,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(s),e){case fS.BLENDMODE_ADD:r.setAlphaMode(1);break;case fS.BLENDMODE_ONEONE:r.setAlphaMode(6);break;case fS.BLENDMODE_STANDARD:r.setAlphaMode(2);break;case fS.BLENDMODE_MULTIPLY:r.setAlphaMode(4)}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(s),this._useInstancing?r.drawArraysType(7,0,4,this._particles.length):r.drawElementsType(0,0,6*this._particles.length),this._particles.length}render(){if(!this.isReady()||!this._particles.length)return 0;const e=this._engine;e.setState&&(e.setState(!1),this.forceDepthWrite&&e.setDepthWrite(!0));let t=0;return t=this.blendMode===fS.BLENDMODE_MULTIPLYADD?this._render(fS.BLENDMODE_MULTIPLY)+this._render(fS.BLENDMODE_ADD):this._render(this.blendMode),this._engine.unbindInstanceAttributes(),this._engine.setAlphaMode(0),t}dispose(e=!0){if(this.resetDrawCache(),this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._indexBuffer&&(this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._removeFromRoot(),this.subEmitters&&!this._subEmitters&&this._prepareSubEmitterInternalArray(),this._subEmitters&&this._subEmitters.length){for(let e=0;e-1&&this._scene.particleSystems.splice(e,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()}clone(e,t,i=!1){const n=Object.assign({},this._customWrappers);let s=null;const r=this._engine;if(r.createEffectForParticles&&null!=this.customShader){s=this.customShader;const e=s.shaderOptions.defines.length>0?s.shaderOptions.defines.join("\n"):"",t=r.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,e);n[0]?n[0].effect=t:this.setCustomEffect(t,0)}const o=this.serialize(i),a=fS.Parse(o,this._scene||this._engine,this._rootUrl);return a.name=e,a.customShader=s,a._customWrappers=n,void 0===t&&(t=this.emitter),this.noiseTexture&&(a.noiseTexture=this.noiseTexture.clone()),a.emitter=t,this.preventAutoStart||a.start(),a}serialize(e=!1){const t={};if(fS._Serialize(t,this,e),t.textureMask=this.textureMask.asArray(),t.customShader=this.customShader,t.preventAutoStart=this.preventAutoStart,this.subEmitters){t.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray();for(const i of this._subEmitters){const n=[];for(const t of i)n.push(t.serialize(e));t.subEmitters.push(n)}}return t}static _Serialize(e,t,i){if(e.name=t.name,e.id=t.id,e.capacity=t.getCapacity(),e.disposeOnStop=t.disposeOnStop,e.manualEmitCount=t.manualEmitCount,t.emitter.position){const i=t.emitter;e.emitterId=i.id}else{const i=t.emitter;e.emitter=i.asArray()}t.particleEmitterType&&(e.particleEmitterType=t.particleEmitterType.serialize()),t.particleTexture&&(i?e.texture=t.particleTexture.serialize():(e.textureName=t.particleTexture.name,e.invertY=!!t.particleTexture._invertY)),e.isLocal=t.isLocal,E.p4.AppendSerializedAnimations(t,e),e.beginAnimationOnStart=t.beginAnimationOnStart,e.beginAnimationFrom=t.beginAnimationFrom,e.beginAnimationTo=t.beginAnimationTo,e.beginAnimationLoop=t.beginAnimationLoop,e.startDelay=t.startDelay,e.renderingGroupId=t.renderingGroupId,e.isBillboardBased=t.isBillboardBased,e.billboardMode=t.billboardMode,e.minAngularSpeed=t.minAngularSpeed,e.maxAngularSpeed=t.maxAngularSpeed,e.minSize=t.minSize,e.maxSize=t.maxSize,e.minScaleX=t.minScaleX,e.maxScaleX=t.maxScaleX,e.minScaleY=t.minScaleY,e.maxScaleY=t.maxScaleY,e.minEmitPower=t.minEmitPower,e.maxEmitPower=t.maxEmitPower,e.minLifeTime=t.minLifeTime,e.maxLifeTime=t.maxLifeTime,e.emitRate=t.emitRate,e.gravity=t.gravity.asArray(),e.noiseStrength=t.noiseStrength.asArray(),e.color1=t.color1.asArray(),e.color2=t.color2.asArray(),e.colorDead=t.colorDead.asArray(),e.updateSpeed=t.updateSpeed,e.targetStopDuration=t.targetStopDuration,e.blendMode=t.blendMode,e.preWarmCycles=t.preWarmCycles,e.preWarmStepOffset=t.preWarmStepOffset,e.minInitialRotation=t.minInitialRotation,e.maxInitialRotation=t.maxInitialRotation,e.startSpriteCellID=t.startSpriteCellID,e.spriteCellLoop=t.spriteCellLoop,e.endSpriteCellID=t.endSpriteCellID,e.spriteCellChangeSpeed=t.spriteCellChangeSpeed,e.spriteCellWidth=t.spriteCellWidth,e.spriteCellHeight=t.spriteCellHeight,e.spriteRandomStartCell=t.spriteRandomStartCell,e.isAnimationSheetEnabled=t.isAnimationSheetEnabled,e.useLogarithmicDepth=t.useLogarithmicDepth;const n=t.getColorGradients();if(n){e.colorGradients=[];for(const t of n){const i={gradient:t.gradient,color1:t.color1.asArray()};t.color2?i.color2=t.color2.asArray():i.color2=t.color1.asArray(),e.colorGradients.push(i)}}const s=t.getRampGradients();if(s){e.rampGradients=[];for(const t of s){const i={gradient:t.gradient,color:t.color.asArray()};e.rampGradients.push(i)}e.useRampGradients=t.useRampGradients}const r=t.getColorRemapGradients();if(r){e.colorRemapGradients=[];for(const t of r){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.colorRemapGradients.push(i)}}const o=t.getAlphaRemapGradients();if(o){e.alphaRemapGradients=[];for(const t of o){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.alphaRemapGradients.push(i)}}const a=t.getSizeGradients();if(a){e.sizeGradients=[];for(const t of a){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.sizeGradients.push(i)}}const l=t.getAngularSpeedGradients();if(l){e.angularSpeedGradients=[];for(const t of l){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.angularSpeedGradients.push(i)}}const h=t.getVelocityGradients();if(h){e.velocityGradients=[];for(const t of h){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.velocityGradients.push(i)}}const c=t.getDragGradients();if(c){e.dragGradients=[];for(const t of c){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.dragGradients.push(i)}}const d=t.getEmitRateGradients();if(d){e.emitRateGradients=[];for(const t of d){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.emitRateGradients.push(i)}}const u=t.getStartSizeGradients();if(u){e.startSizeGradients=[];for(const t of u){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.startSizeGradients.push(i)}}const p=t.getLifeTimeGradients();if(p){e.lifeTimeGradients=[];for(const t of p){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.lifeTimeGradients.push(i)}}const f=t.getLimitVelocityGradients();if(f){e.limitVelocityGradients=[];for(const t of f){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.limitVelocityGradients.push(i)}e.limitVelocityDamping=t.limitVelocityDamping}t.noiseTexture&&(e.noiseTexture=t.noiseTexture.serialize())}static _Parse(e,t,i,n){var s,r,h;let c;c=i instanceof Ue.B?null:i;const d=(0,l.q)("BABYLON.Texture");if(d&&c&&(e.texture?t.particleTexture=d.Parse(e.texture,c,n):e.textureName&&(t.particleTexture=new d(n+e.textureName,c,!1,void 0===e.invertY||e.invertY),t.particleTexture.name=e.textureName)),e.emitterId||0===e.emitterId||void 0!==e.emitter?e.emitterId&&c?t.emitter=c.getLastMeshById(e.emitterId):t.emitter=o.P.FromArray(e.emitter):t.emitter=o.P.Zero(),t.isLocal=!!e.isLocal,void 0!==e.renderingGroupId&&(t.renderingGroupId=e.renderingGroupId),void 0!==e.isBillboardBased&&(t.isBillboardBased=e.isBillboardBased),void 0!==e.billboardMode&&(t.billboardMode=e.billboardMode),void 0!==e.useLogarithmicDepth&&(t.useLogarithmicDepth=e.useLogarithmicDepth),e.animations){for(let i=0;i0?c.shaderOptions.defines.join("\n"):"";h=o.createEffectForParticles(c.shaderPath.fragmentElement,c.shaderOptions.uniforms,c.shaderOptions.samplers,t)}const d=new fS(r,s||e.capacity,t,h,e.isAnimationSheetEnabled);if(d.customShader=c,d._rootUrl=i,e.id&&(d.id=e.id),e.subEmitters){d.subEmitters=[];for(const n of e.subEmitters){const e=[];for(const s of n)e.push(hS.Parse(s,t,i));d.subEmitters.push(e)}}return fS._Parse(e,d,t,i),e.textureMask&&(d.textureMask=a.HE.FromArray(e.textureMask)),e.preventAutoStart&&(d.preventAutoStart=e.preventAutoStart),n||d.preventAutoStart||d.start(),d}}fS.BILLBOARDMODE_Y=2,fS.BILLBOARDMODE_ALL=7,fS.BILLBOARDMODE_STRETCHED=8,fS.BILLBOARDMODE_STRETCHED_LOCAL=9,hS._ParseParticleSystem=fS.Parse;const _S="clipPlaneFragmentDeclaration2",mS="#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nin float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nin float fClipDistance6;\n#endif\n";Ht.v.IncludesShadersStore[_S]=mS;const gS="gpuRenderParticlesPixelShader",vS="precision highp float;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform sampler2D diffuseSampler;\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include \n#include\n#include\n#include\n#include\nvoid main() {\n#include \nvec4 textureColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\ngl_FragColor.rgb=gl_FragColor.rgb*alpha+vec3(1.0)*(1.0-alpha);\n#endif \n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ngl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\ngl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);\ngl_FragColor=applyImageProcessing(gl_FragColor);\n#endif\n#endif\n}\n";Ht.v.ShadersStore[gS]=vS;const TS="clipPlaneVertexDeclaration2",SS="#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nout float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nout float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nout float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nout float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nuniform vec4 vClipPlane5;\nout float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nuniform vec4 vClipPlane6;\nout float fClipDistance6;\n#endif\n";Ht.v.IncludesShadersStore[TS]=SS;const ES="gpuRenderParticlesVertexShader",xS="precision highp float;\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\nuniform vec3 worldOffset;\n#ifdef LOCAL\nuniform mat4 emitterWM;\n#endif\nattribute vec3 position;\nattribute float age;\nattribute float life;\nattribute vec3 size;\n#ifndef BILLBOARD\nattribute vec3 initialDirection;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction;\n#endif\nattribute float angle;\n#ifdef ANIMATESHEET\nattribute float cellIndex;\n#endif\nattribute vec2 offset;\nattribute vec2 uv;\nvarying vec2 vUV;\nvarying vec4 vColor;\nvarying vec3 vPositionW;\n#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)\nuniform mat4 invView;\n#endif\n#include\n#include\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nattribute vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition;\n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix= mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\n#ifdef LOCAL\nreturn ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;\n#else\nreturn (position+worldOffset)+alignedCorner;\n#endif\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix= mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\n#ifdef LOCAL\nreturn ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;\n#else\nreturn (position+worldOffset)+alignedCorner;\n#endif\n}\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture2D(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=(position+worldOffset)-eyePosition;\nyaxis.y=0.;\nvPositionW=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(vPositionW,1.0));\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=(position+worldOffset)-eyePosition;\nvPositionW=rotateAlign(toCamera,rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(vPositionW,1.0));\n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n#ifdef LOCAL\nvec4 viewPosition=view*vec4(((emitterWM*vec4(position,1.0)).xyz+worldOffset),1.0)+rotatedCorner;\n#else\nvec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner;\n#endif\nvPositionW=(invView*viewPosition).xyz;\n#endif\n#else\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvPositionW=rotate(yaxis,rotatedCorner);\nvec4 viewPosition=view*vec4(vPositionW,1.0);\n#endif\ngl_Position=projection*viewPosition;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nvec4 worldPos=vec4(vPositionW,1.0);\n#endif\n#include\n#include\n}";Ht.v.ShadersStore[ES]=xS;class bS extends pi{static get IsSupported(){if(!m.l.LastCreatedEngine)return!1;const e=m.l.LastCreatedEngine.getCaps();return e.supportTransformFeedbacks||e.supportComputeShaders}getCapacity(){return this._capacity}get activeParticleCount(){return this._activeCount}set activeParticleCount(e){this._activeCount=Math.min(e,this._capacity)}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady())return!1;if(this.blendMode!==fS.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else{if(!this._getWrapper(fS.BLENDMODE_MULTIPLY).effect.isReady())return!1;if(!this._getWrapper(fS.BLENDMODE_ADD).effect.isReady())return!1}return this._platform.isUpdateBufferCreated()?this._platform.isUpdateBufferReady():(this._recreateUpdateEffect(),!1)}isStarted(){return this._started}isStopped(){return this._stopped}isStopping(){return!1}getActiveCount(){return this._currentActiveCount}start(e=this.startDelay){if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";e?setTimeout((()=>{this.start(0)}),e):(this._started=!0,this._stopped=!1,this._preWarmDone=!1,this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop))}stop(){this._stopped||(this._stopped=!0)}reset(){this._releaseBuffers(),this._platform.releaseVertexBuffers(),this._currentActiveCount=0,this._targetIndex=0}getClassName(){return"GPUParticleSystem"}getCustomEffect(e=0){var t,i;return null!==(i=null===(t=this._customWrappers[e])||void 0===t?void 0:t.effect)&&void 0!==i?i:this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){var t;return null!==(t=this._customWrappers[e])&&void 0!==t?t:this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new $t.q(this._engine),this._customWrappers[t].effect=e}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new r.y$),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"gpuRenderParticles"}get vertexBuffers(){return this._renderVertexBuffers[1^this._targetIndex]}get indexBuffer(){return null}_removeGradientAndTexture(e,t,i){return super._removeGradientAndTexture(e,t,i),this._releaseBuffers(),this}addColorGradient(e,t){this._colorGradients||(this._colorGradients=[]);const i=new nS(e,t);return this._colorGradients.push(i),this._refreshColorGradient(!0),this._releaseBuffers(),this}_refreshColorGradient(e=!1){this._colorGradients&&(e&&this._colorGradients.sort(((e,t)=>e.gradientt.gradient?1:0)),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null))}forceRefreshGradients(){this._refreshColorGradient(),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture"),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture"),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture"),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture"),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture"),this.reset()}removeColorGradient(e){return this._removeGradientAndTexture(e,this._colorGradients,this._colorGradientsTexture),this._colorGradientsTexture=null,this}resetDrawCache(){var e;for(const t in this._drawWrappers){null===(e=this._drawWrappers[t].drawContext)||void 0===e||e.reset()}}_addFactorGradient(e,t,i){const n=new rS(t,i);e.push(n),this._releaseBuffers()}addSizeGradient(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture",!0),this._releaseBuffers(),this}removeSizeGradient(e){return this._removeGradientAndTexture(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this}_refreshFactorGradient(e,t,i=!1){if(!e)return;i&&e.sort(((e,t)=>e.gradientt.gradient?1:0));const n=this;n[t]&&(n[t].dispose(),n[t]=null)}addAngularSpeedGradient(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture",!0),this._releaseBuffers(),this}removeAngularSpeedGradient(e){return this._removeGradientAndTexture(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this}addVelocityGradient(e,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture",!0),this._releaseBuffers(),this}removeVelocityGradient(e){return this._removeGradientAndTexture(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this}addLimitVelocityGradient(e,t){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture",!0),this._releaseBuffers(),this}removeLimitVelocityGradient(e){return this._removeGradientAndTexture(e,this._limitVelocityGradients,this._limitVelocityGradientsTexture),this._limitVelocityGradientsTexture=null,this}addDragGradient(e,t){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture",!0),this._releaseBuffers(),this}removeDragGradient(e){return this._removeGradientAndTexture(e,this._dragGradients,this._dragGradientsTexture),this._dragGradientsTexture=null,this}addEmitRateGradient(){return this}removeEmitRateGradient(){return this}addStartSizeGradient(){return this}removeStartSizeGradient(){return this}addColorRemapGradient(){return this}removeColorRemapGradient(){return this}addAlphaRemapGradient(){return this}removeAlphaRemapGradient(){return this}addRampGradient(){return this}removeRampGradient(){return this}getRampGradients(){return null}get useRampGradients(){return!1}set useRampGradients(e){}addLifeTimeGradient(){return this}removeLifeTimeGradient(){return this}constructor(e,t,i,n=null,s=!1){if(super(e),this.layerMask=268435455,this._accumulatedCount=0,this._renderVertexBuffers=[],this._targetIndex=0,this._currentRenderId=-1,this._currentRenderingCameraUniqueId=-1,this._started=!1,this._stopped=!1,this._timeDelta=0,this.updateInAnimate=!1,this._actualFrame=0,this._rawTextureWidth=256,this.onDisposeObservable=new r.y$,this.onStoppedObservable=new r.y$,this.forceDepthWrite=!1,this._preWarmDone=!1,this.isLocal=!1,this.isGPU=!0,this._onBeforeDrawParticlesObservable=null,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=o.y3.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||m.l.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().supportComputeShaders){if(!(0,l.q)("BABYLON.ComputeShaderParticleSystem"))throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");this._platform=new((0,l.q)("BABYLON.ComputeShaderParticleSystem"))(this,this._engine)}else{if(!(0,l.q)("BABYLON.WebGL2ParticleSystem"))throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");this._platform=new((0,l.q)("BABYLON.WebGL2ParticleSystem"))(this,this._engine)}this._customWrappers={0:new $t.q(this._engine)},this._customWrappers[0].effect=n,this._drawWrappers={0:new $t.q(this._engine)},this._drawWrappers[0].drawContext&&(this._drawWrappers[0].drawContext.useInstancing=!0),this._attachImageProcessingConfiguration(null),(t=null!=t?t:{}).randomTextureSize||delete t.randomTextureSize;const a=Object.assign({capacity:5e4,randomTextureSize:this._engine.getCaps().maxTextureSize},t),h=t;isFinite(h)&&(a.capacity=h),this._capacity=a.capacity,this._activeCount=a.capacity,this._currentActiveCount=0,this._isAnimationSheetEnabled=s,this.particleEmitterType=new ni;const c=Math.min(this._engine.getCaps().maxTextureSize,a.randomTextureSize);let d=[];for(let r=0;r0;)i.push(0)}const a=new Float32Array([.5,.5,1,1,-.5,.5,0,1,.5,-.5,1,0,-.5,-.5,0,0]),l=this._platform.createParticleBuffer(i),h=this._platform.createParticleBuffer(i);this._buffer0=new ne.l(t,l,!1,this._attributesStrideSize),this._buffer1=new ne.l(t,h,!1,this._attributesStrideSize),this._spriteBuffer=new ne.l(t,a,!1,4),this._renderVertexBuffers=[],this._createVertexBuffers(this._buffer0,this._buffer1,this._spriteBuffer),this._createVertexBuffers(this._buffer1,this._buffer0,this._spriteBuffer),this._sourceBuffer=this._buffer0,this._targetBuffer=this._buffer1}_recreateUpdateEffect(){this._createColorGradientTexture(),this._createSizeGradientTexture(),this._createAngularSpeedGradientTexture(),this._createVelocityGradientTexture(),this._createLimitVelocityGradientTexture(),this._createDragGradientTexture();let e=this.particleEmitterType?this.particleEmitterType.getEffectDefines():"";return this._isBillboardBased&&(e+="\n#define BILLBOARD"),this._colorGradientsTexture&&(e+="\n#define COLORGRADIENTS"),this._sizeGradientsTexture&&(e+="\n#define SIZEGRADIENTS"),this._angularSpeedGradientsTexture&&(e+="\n#define ANGULARSPEEDGRADIENTS"),this._velocityGradientsTexture&&(e+="\n#define VELOCITYGRADIENTS"),this._limitVelocityGradientsTexture&&(e+="\n#define LIMITVELOCITYGRADIENTS"),this._dragGradientsTexture&&(e+="\n#define DRAGGRADIENTS"),this.isAnimationSheetEnabled&&(e+="\n#define ANIMATESHEET",this.spriteRandomStartCell&&(e+="\n#define ANIMATESHEETRANDOMSTART")),this.noiseTexture&&(e+="\n#define NOISE"),this.isLocal&&(e+="\n#define LOCAL"),!(!this._platform.isUpdateBufferCreated()||this._cachedUpdateDefines!==e)||(this._cachedUpdateDefines=e,this._updateBuffer=this._platform.createUpdateBuffer(e),this._platform.isUpdateBufferReady())}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(null==t?void 0:t.effect)return t;const i=[];this.fillDefines(i,e);let n=this._drawWrappers[e];n||(n=new $t.q(this._engine),n.drawContext&&(n.drawContext.useInstancing=!0),this._drawWrappers[e]=n);const s=i.join("\n");if(n.defines!==s){const e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),n.setEffect(this._engine.createEffect("gpuRenderParticles",e,t,i,s),s)}return n}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1,n=!1){const s=[ne.o.PositionKind,"age","life","size","angle"];return e||s.push(ne.o.ColorKind),t&&s.push("cellIndex"),i||s.push("initialDirection"),n||s.push("direction"),s.push("offset",ne.o.UVKind),s}static _GetEffectCreationOptions(e=!1,t=!1){const i=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return(0,ua.qx)(i),e&&i.push("sheetInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t=0){if(this._scene&&(0,ua.lK)(this,this._scene,e),t===fS.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this.isLocal&&e.push("#define LOCAL"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case fS.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case fS.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case fS.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL")}this._colorGradientsTexture&&e.push("#define COLORGRADIENTS"),this.isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(""+this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...bS._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===fS.BILLBOARDMODE_STRETCHED)),e.push(...bS._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(ii.$.PrepareUniforms(e,this._imageProcessingConfigurationDefines),ii.$.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}animate(e=!1){var t;this._timeDelta=this.updateSpeed*(e?this.preWarmStepOffset:(null===(t=this._scene)||void 0===t?void 0:t.getAnimationRatio())||1),this._actualFrame+=this._timeDelta,this._stopped||this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop(),this.updateInAnimate&&this._update()}_createFactorGradientTexture(e,t){const i=this[t];if(!e||!e.length||i)return;const n=new Float32Array(this._rawTextureWidth);for(let s=0;s{n[s]=S.R.Lerp(e.factor1,t.factor1,i)}))}this[t]=ze.CreateRTexture(n,this._rawTextureWidth,1,this._scene||this._engine,!1,!1,1),this[t].name=t.substring(1)}_createSizeGradientTexture(){this._createFactorGradientTexture(this._sizeGradients,"_sizeGradientsTexture")}_createAngularSpeedGradientTexture(){this._createFactorGradientTexture(this._angularSpeedGradients,"_angularSpeedGradientsTexture")}_createVelocityGradientTexture(){this._createFactorGradientTexture(this._velocityGradients,"_velocityGradientsTexture")}_createLimitVelocityGradientTexture(){this._createFactorGradientTexture(this._limitVelocityGradients,"_limitVelocityGradientsTexture")}_createDragGradientTexture(){this._createFactorGradientTexture(this._dragGradients,"_dragGradientsTexture")}_createColorGradientTexture(){if(!this._colorGradients||!this._colorGradients.length||this._colorGradientsTexture)return;const e=new Uint8Array(4*this._rawTextureWidth),t=a.zZ.Color4[0];for(let i=0;i{a.HE.LerpToRef(n.color1,s.color1,r,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255*t.a}))}this._colorGradientsTexture=ze.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1),this._colorGradientsTexture.name="colorGradients"}_render(e,t){var i,n;const s=this._getWrapper(e),r=s.effect;this._engine.enableEffect(s);const a=(null===(i=this._scene)||void 0===i?void 0:i.getViewMatrix())||o.y3.IdentityReadOnly;if(r.setMatrix("view",a),r.setMatrix("projection",null!==(n=this.defaultProjectionMatrix)&&void 0!==n?n:this._scene.getProjectionMatrix()),r.setTexture("diffuseSampler",this.particleTexture),r.setVector2("translationPivot",this.translationPivot),r.setVector3("worldOffset",this.worldOffset),this.isLocal&&r.setMatrix("emitterWM",t),this._colorGradientsTexture?r.setTexture("colorGradientSampler",this._colorGradientsTexture):r.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){const e=this.particleTexture.getBaseSize();r.setFloat3("sheetInfos",this.spriteCellWidth/e.width,this.spriteCellHeight/e.height,e.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){const e=this._scene.activeCamera;r.setVector3("eyePosition",e.globalPosition)}const l=r.defines;if(this._scene&&(0,ua.an)(r,this,this._scene),l.indexOf("#define BILLBOARDMODE_ALL")>=0){const e=a.clone();e.invert(),r.setMatrix("invView",e)}switch(this.useLogarithmicDepth&&this._scene&&It.G.BindLogDepth(l,r,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(r),e){case fS.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case fS.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case fS.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case fS.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4)}return this._platform.bindDrawBuffers(this._targetIndex,r),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(r),this._engine.drawArraysType(7,0,4,this._currentActiveCount),this._engine.setAlphaMode(0),this._currentActiveCount}_update(e){if(!this.emitter||!this._targetBuffer)return;if(!this._recreateUpdateEffect())return;if(!e)if(this.emitter.position){e=this.emitter.getWorldMatrix()}else{const t=this.emitter;e=o.jp.Matrix[0],o.y3.TranslationToRef(t.x,t.y,t.z,e)}this._platform.preUpdateParticleBuffer(),this._updateBuffer.setFloat("currentCount",this._currentActiveCount),this._updateBuffer.setFloat("timeDelta",this._timeDelta),this._updateBuffer.setFloat("stopFactor",this._stopped?0:1),this._updateBuffer.setInt("randomTextureSize",this._randomTextureSize),this._updateBuffer.setFloat2("lifeTime",this.minLifeTime,this.maxLifeTime),this._updateBuffer.setFloat2("emitPower",this.minEmitPower,this.maxEmitPower),this._colorGradientsTexture||(this._updateBuffer.setDirectColor4("color1",this.color1),this._updateBuffer.setDirectColor4("color2",this.color2)),this._updateBuffer.setFloat2("sizeRange",this.minSize,this.maxSize),this._updateBuffer.setFloat4("scaleRange",this.minScaleX,this.maxScaleX,this.minScaleY,this.maxScaleY),this._updateBuffer.setFloat4("angleRange",this.minAngularSpeed,this.maxAngularSpeed,this.minInitialRotation,this.maxInitialRotation),this._updateBuffer.setVector3("gravity",this.gravity),this._limitVelocityGradientsTexture&&this._updateBuffer.setFloat("limitVelocityDamping",this.limitVelocityDamping),this.particleEmitterType&&this.particleEmitterType.applyToShader(this._updateBuffer),this._isAnimationSheetEnabled&&this._updateBuffer.setFloat4("cellInfos",this.startSpriteCellID,this.endSpriteCellID,this.spriteCellChangeSpeed,this.spriteCellLoop?1:0),this.noiseTexture&&this._updateBuffer.setVector3("noiseStrength",this.noiseStrength),this.isLocal||this._updateBuffer.setMatrix("emitterWM",e),this._platform.updateParticleBuffer(this._targetIndex,this._targetBuffer,this._currentActiveCount),this._targetIndex++,2===this._targetIndex&&(this._targetIndex=0);const t=this._sourceBuffer;this._sourceBuffer=this._targetBuffer,this._targetBuffer=t}render(e=!1,t=!1){if(!this._started)return 0;if(!this.isReady())return 0;if(!e&&this._scene){if(!this._preWarmDone&&this.preWarmCycles){for(let e=0;e1){const e=0|this._accumulatedCount;this._accumulatedCount-=e,this._currentActiveCount=Math.min(this._activeCount,this._currentActiveCount+e)}if(!this._currentActiveCount)return 0;let i;if(this.emitter.position){i=this.emitter.getWorldMatrix()}else{const e=this.emitter;i=o.jp.Matrix[0],o.y3.TranslationToRef(e.x,e.y,e.z,i)}const n=this._engine;this.updateInAnimate||this._update(i);let s=0;return e||t||(n.setState(!1),this.forceDepthWrite&&n.setDepthWrite(!0),s=this.blendMode===fS.BLENDMODE_MULTIPLYADD?this._render(fS.BLENDMODE_MULTIPLY,i)+this._render(fS.BLENDMODE_ADD,i):this._render(this.blendMode,i),this._engine.setAlphaMode(0)),s}rebuild(){this._initialize(!0)}_releaseBuffers(){this._buffer0&&(this._buffer0.dispose(),this._buffer0=null),this._buffer1&&(this._buffer1.dispose(),this._buffer1=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._platform.releaseBuffers()}dispose(e=!0){for(const t in this._drawWrappers){this._drawWrappers[t].dispose()}if(this._drawWrappers={},this._scene){const e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1)}this._releaseBuffers(),this._platform.releaseVertexBuffers();for(let t=0;t0?s.shaderOptions.defines.join("\n"):"";n[0]=r.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,e,void 0,void 0,void 0,this)}const o=this.serialize(i),a=bS.Parse(o,this._scene||this._engine,this._rootUrl);return a.name=e,a.customShader=s,a._customWrappers=n,void 0===t&&(t=this.emitter),this.noiseTexture&&(a.noiseTexture=this.noiseTexture.clone()),a.emitter=t,a}serialize(e=!1){const t={};return fS._Serialize(t,this,e),t.activeParticleCount=this.activeParticleCount,t.randomTextureSize=this._randomTextureSize,t.customShader=this.customShader,t}static Parse(e,t,i,n=!1,s){const r=e.name;let o,a;t instanceof Ue.B?o=t:(a=t,o=a.getEngine());const l=new bS(r,{capacity:s||e.capacity,randomTextureSize:e.randomTextureSize},t,null,e.isAnimationSheetEnabled);if(l._rootUrl=i,e.customShader&&o.createEffectForParticles){const t=e.customShader,i=t.shaderOptions.defines.length>0?t.shaderOptions.defines.join("\n"):"",n=o.createEffectForParticles(t.shaderPath.fragmentElement,t.shaderOptions.uniforms,t.shaderOptions.samplers,i,void 0,void 0,void 0,l);l.setCustomEffect(n,0),l.customShader=t}return e.id&&(l.id=e.id),e.activeParticleCount&&(l.activeParticleCount=e.activeParticleCount),fS._Parse(e,l,t,i),e.preventAutoStart&&(l.preventAutoStart=e.preventAutoStart),n||l.preventAutoStart||l.start(),l}}class CS{constructor(){this._emitterNodeIsOwned=!0,this.systems=new Array}get emitterNode(){return this._emitterNode}set emitterNode(e){this._emitterNodeIsOwned&&this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!1);for(const t of this.systems)t.emitter=e;this._emitterNode=e}setEmitterAsSphere(e,t,i){this._emitterNodeIsOwned&&this._emitterNode&&this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!0,this._emitterCreationOptions={kind:"Sphere",options:e,renderingGroupId:t};const n=gl("emitterSphere",{diameter:e.diameter,segments:e.segments},i);n.renderingGroupId=t;const s=new _a("emitterSphereMaterial",i);s.emissiveColor=e.color,n.material=s;for(const r of this.systems)r.emitter=n;this._emitterNode=n}start(e){for(const t of this.systems)e&&(t.emitter=e),t.start()}dispose(){for(const e of this.systems)e.dispose();this.systems.length=0,this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNode=null)}serialize(e=!1){const t={systems:[]};for(const i of this.systems)t.systems.push(i.serialize(e));return this._emitterNode&&(t.emitter=this._emitterCreationOptions),t}static Parse(e,t,i=!1,n){const s=new CS,r=this.BaseAssetsUrl+"/textures/";t=t||m.l.LastCreatedScene;for(const o of e.systems)s.systems.push(i?bS.Parse(o,t,r,!0,n):fS.Parse(o,t,r,!0,n));if(e.emitter){const i=e.emitter.options;if("Sphere"===e.emitter.kind)s.setEmitterAsSphere({diameter:i.diameter,segments:i.segments,color:a.Wo.FromArray(i.color)},e.emitter.renderingGroupId,t)}return s}}CS.BaseAssetsUrl="https://assets.babylonjs.com/particles";class yS{static CreateDefault(e,t=500,i,n=!1){let s;return s=n?new bS("default system",{capacity:t},i):new fS("default system",t,i),s.emitter=e,s.particleTexture=new Le("https://assets.babylonjs.com/textures/flare.png",s.getScene()),s.createConeEmitter(.1,Math.PI/4),s.color1=new a.HE(1,1,1,1),s.color2=new a.HE(1,1,1,1),s.colorDead=new a.HE(1,1,1,0),s.minSize=.1,s.maxSize=.1,s.minEmitPower=2,s.maxEmitPower=2,s.updateSpeed=1/60,s.emitRate=30,s}static CreateAsync(e,t,i=!1,n){t||(t=m.l.LastCreatedScene);const s={};return t.addPendingData(s),new Promise(((r,o)=>{if(i&&!bS.IsSupported)return t.removePendingData(s),o("Particle system with GPU is not supported.");se.w1.LoadFile(`${yS.BaseAssetsUrl}/systems/${e}.json`,(e=>{t.removePendingData(s);const o=JSON.parse(e.toString());return r(CS.Parse(o,t,i,n))}),void 0,void 0,void 0,(()=>(t.removePendingData(s),o(`An error occurred with the creation of your particle system. Check if your type '${e}' exists.`))))}))}static ExportSet(e){const t=new CS;for(const i of e)t.systems.push(i);return t}static ParseFromFileAsync(e,t,i,n=!1,s="",r){return new Promise(((o,a)=>{const l=new y.g;l.addEventListener("readystatechange",(()=>{if(4==l.readyState)if(200==l.status){const t=JSON.parse(l.responseText);let a;a=n?bS.Parse(t,i,s,!1,r):fS.Parse(t,i,s,!1,r),e&&(a.name=e),o(a)}else a("Unable to load the particle system")})),l.open("GET",t),l.send()}))}static ParseFromSnippetAsync(e,t,i=!1,n="",s){if("_BLANK"===e){const e=this.CreateDefault(null);return e.start(),Promise.resolve(e)}return new Promise(((r,o)=>{const a=new y.g;a.addEventListener("readystatechange",(()=>{if(4==a.readyState)if(200==a.status){const o=JSON.parse(JSON.parse(a.responseText).jsonPayload),l=JSON.parse(o.particleSystem);let h;h=i?bS.Parse(l,t,n,!1,s):fS.Parse(l,t,n,!1,s),h.snippetId=e,r(h)}else o("Unable to load the snippet "+e)})),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()}))}}yS.BaseAssetsUrl=CS.BaseAssetsUrl,yS.SnippetUrl="https://snippet.babylonjs.com",yS.CreateFromSnippetAsync=yS.ParseFromSnippetAsync,n.p.AddParser(Se.l.NAME_PARTICLESYSTEM,((e,t,i,s)=>{const r=n.p.GetIndividualParser(Se.l.NAME_PARTICLESYSTEM);if(r&&void 0!==e.particleSystems&&null!==e.particleSystems)for(let n=0,o=e.particleSystems.length;n{if(e.activeParticleCount){return bS.Parse(e,t,i)}return fS.Parse(e,t,i)})),fe.D.prototype.createEffectForParticles=function(e,t=[],i=[],n="",s,r,o,a){var l;let h=[],c=[];const d=[];return a?a.fillUniformsAttributesAndSamplerNames(c,h,d):(h=fS._GetAttributeNamesOrOptions(),c=fS._GetEffectCreationOptions()),-1===n.indexOf(" BILLBOARD")&&(n+="\n#define BILLBOARD\n"),(null==a?void 0:a.isAnimationSheetEnabled)&&-1===n.indexOf(" ANIMATESHEET")&&(n+="\n#define ANIMATESHEET\n"),-1===i.indexOf("diffuseSampler")&&i.push("diffuseSampler"),this.createEffect({vertex:null!==(l=null==a?void 0:a.vertexShaderName)&&void 0!==l?l:"particles",fragmentElement:e},h,c.concat(t),d.concat(i),n,s,r,o)},ee.Kj.prototype.getEmittedParticleSystems=function(){const e=new Array;for(let t=0;t{this.physicsImpostor&&(this.physicsImpostor.dispose(),this.physicsImpostor=null)}))))},enumerable:!0,configurable:!0}),ie.x.prototype.getPhysicsImpostor=function(){return this.physicsImpostor},ie.x.prototype.applyImpulse=function(e,t){return this.physicsImpostor?(this.physicsImpostor.applyImpulse(e,t),this):this},ie.x.prototype.setPhysicsLinkWith=function(e,t,i,n){return this.physicsImpostor&&e.physicsImpostor?(this.physicsImpostor.createJoint(e.physicsImpostor,st.HingeJoint,{mainPivot:t,connectedPivot:i,nativeParams:n}),this):this};class LS{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw(0,ge.S)("")}constructor(e,t=LS.DefaultPluginFactory()){this._physicsPlugin=t,this._physicsBodies=[],this._subTimeStep=0,e=e||new o.P(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}_step(e){e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._physicsBodies)}addBody(e){this._physicsBodies.push(e)}removeBody(e){const t=this._physicsBodies.indexOf(e);t>-1&&this._physicsBodies.splice(t,1)}getBodies(){return this._physicsBodies}getPhysicsPlugin(){return this._physicsPlugin}raycastToRef(e,t,i,n){this._physicsPlugin.raycast(e,t,i,n)}raycast(e,t,i){const n=new ev;return this._physicsPlugin.raycast(e,t,n,i),n}}!function(e){e[e.FREE=0]="FREE",e[e.LIMITED=1]="LIMITED",e[e.LOCKED=2]="LOCKED"}(RS||(RS={})),function(e){e[e.LINEAR_X=0]="LINEAR_X",e[e.LINEAR_Y=1]="LINEAR_Y",e[e.LINEAR_Z=2]="LINEAR_Z",e[e.ANGULAR_X=3]="ANGULAR_X",e[e.ANGULAR_Y=4]="ANGULAR_Y",e[e.ANGULAR_Z=5]="ANGULAR_Z",e[e.LINEAR_DISTANCE=6]="LINEAR_DISTANCE"}(PS||(PS={})),function(e){e[e.BALL_AND_SOCKET=1]="BALL_AND_SOCKET",e[e.DISTANCE=2]="DISTANCE",e[e.HINGE=3]="HINGE",e[e.SLIDER=4]="SLIDER",e[e.LOCK=5]="LOCK",e[e.PRISMATIC=6]="PRISMATIC",e[e.SIX_DOF=7]="SIX_DOF"}(IS||(IS={})),function(e){e[e.SPHERE=0]="SPHERE",e[e.CAPSULE=1]="CAPSULE",e[e.CYLINDER=2]="CYLINDER",e[e.BOX=3]="BOX",e[e.CONVEX_HULL=4]="CONVEX_HULL",e[e.CONTAINER=5]="CONTAINER",e[e.MESH=6]="MESH",e[e.HEIGHTFIELD=7]="HEIGHTFIELD"}(MS||(MS={})),function(e){e[e.NONE=0]="NONE",e[e.VELOCITY=1]="VELOCITY",e[e.POSITION=2]="POSITION"}(OS||(OS={})),function(e){e[e.STATIC=0]="STATIC",e[e.ANIMATED=1]="ANIMATED",e[e.DYNAMIC=2]="DYNAMIC"}(DS||(DS={}));!function(e){e[e.GEOMETRIC_MEAN=0]="GEOMETRIC_MEAN",e[e.MINIMUM=1]="MINIMUM",e[e.MAXIMUM=2]="MAXIMUM",e[e.ARITHMETIC_MEAN=3]="ARITHMETIC_MEAN",e[e.MULTIPLY=4]="MULTIPLY"}(NS||(NS={}));N.x.prototype.getPhysicsEngine=function(){return this._physicsEngine},N.x.prototype.enablePhysics=function(e=null,t){if(this._physicsEngine)return!0;let i=this._getComponent(Se.l.NAME_PHYSICSENGINE);i||(i=new BS(this),this._addComponent(i));try{if(t&&1!==(null==t?void 0:t.getPluginVersion())){if(2!==(null==t?void 0:t.getPluginVersion()))throw new Error("Unsupported Physics plugin version.");this._physicsEngine=new LS(e,t)}else this._physicsEngine=new tv(e,t);return this._physicsTimeAccumulator=0,!0}catch(n){return p.Y.Error(n.message),!1}},N.x.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)},N.x.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},N.x.prototype.deleteCompoundImpostor=function(e){const t=e.parts[0].mesh;t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)},N.x.prototype._advancePhysicsEngineStep=function(e){if(this._physicsEngine){const t=this._physicsEngine.getSubTimeStep();if(t>0)for(this._physicsTimeAccumulator+=e;this._physicsTimeAccumulator>t;)this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(t/1e3),this.onAfterPhysicsObservable.notifyObservers(this),this._physicsTimeAccumulator-=t;else this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(e/1e3),this.onAfterPhysicsObservable.notifyObservers(this)}};class BS{constructor(e){this.name=Se.l.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new r.y$,this.scene.onAfterPhysicsObservable=new r.y$,this.scene.getDeterministicFrameTime=()=>this.scene._physicsEngine?1e3*this.scene._physicsEngine.getTimeStep():1e3/60}register(){}rebuild(){}dispose(){this.scene.onBeforePhysicsObservable.clear(),this.scene.onAfterPhysicsObservable.clear(),this.scene._physicsEngine&&this.scene.disablePhysicsEngine()}}Object.defineProperty(te.Y.prototype,"physicsBody",{get:function(){return this._physicsBody},set:function(e){this._physicsBody!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsBody=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add((()=>{this.physicsBody&&(this.physicsBody.dispose(),this.physicsBody=null)}))))},enumerable:!0,configurable:!0}),te.Y.prototype.getPhysicsBody=function(){return this.physicsBody},te.Y.prototype.applyImpulse=function(e,t){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(e,t),this};class US{static GetContactPointToRef(e,t,i,n,s){const r=e.getScene().getPhysicsEngine(),o=null==r?void 0:r.getPluginVersion();if(1===o){const s=new qe(t,i).intersectsMesh(e);if(s.hit&&s.pickedPoint)return n.copyFrom(s.pickedPoint),!0}else if(2===o)return e.physicsBody.getObjectCenterWorldToRef(n,s),!0;return!1}static HasAppliedForces(e,t){var i,n,s;return e.getMotionType(t)===DS.STATIC||0===(null!==(n=null===(i=e.getMassProperties(t))||void 0===i?void 0:i.mass)&&void 0!==n?n:0)||0===(null===(s=e.transformNode)||void 0===s?void 0:s.getTotalVertices())}static IsInsideCylinder(e,t,i,n){const s=o.jp.Vector3[0];return e.subtractToRef(t,s),Math.abs(s.x)<=i&&Math.abs(s.z)<=i&&s.y>=0&&s.y<=n}}class VS{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=o.P.Zero(),this._originDirection=o.P.Zero(),this._cylinderPosition=o.P.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=Object.assign(Object.assign({},new GS),this._options),this._origin.addToRef(new o.P(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new o.P(0,this._options.height,0),this._originTop),this._options.updraftMode===wS.Perpendicular&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=this._tick.bind(this),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?(this._cylinder.dispose(),this._cylinder=void 0):setTimeout((()=>{!this._dataFetched&&this._cylinder&&(this._cylinder.dispose(),this._cylinder=void 0)}),0))}_getHitData(e,t){let i;i=this._options.updraftMode===wS.Perpendicular?this._originDirection:e.subtract(this._originTop);const n=o.P.Distance(this._origin,e),s=-1*this._options.strength,r=i.multiplyByFloats(s,s,s);t.force.copyFrom(r),t.contactPoint.copyFrom(e),t.distanceFromOrigin=n}_getBodyHitData(e,t,i){if(US.HasAppliedForces(e))return!1;const n=e.getObjectCenterWorld(i);return!!US.IsInsideCylinder(n,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(n,t),!0)}_getImpostorHitData(e,t){if(0===e.mass)return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const n=e.getObjectCenter();return this._getHitData(n,t),!0}_tick(){const e=VS._HitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach((t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)})):this._physicsEngine.getBodies().forEach((t=>{t.iterateOverAllInstances(((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)}))}))}_prepareCylinder(){this._cylinder||(this._cylinder=Fa("updraftEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return!!this._cylinder&&(this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0))}}VS._HitData={force:new o.P,contactPoint:new o.P,distanceFromOrigin:0};class kS{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=o.P.Zero(),this._cylinderPosition=o.P.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=Object.assign(Object.assign({},new zS),this._options),this._origin.addToRef(new o.P(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new o.P(0,this._options.height,0),this._originTop),this._tickCallback=this._tick.bind(this),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?this._cylinder.dispose():setTimeout((()=>{this._dataFetched||this._cylinder.dispose()}),0))}_getHitData(e,t,i){const n=kS.originOnPlane;n.set(this._origin.x,t.y,this._origin.z);const s=o.jp.Vector3[0];t.subtractToRef(n,s);const r=o.jp.Vector3[1];if(!US.GetContactPointToRef(e,n,s,r,i.instanceIndex))return!1;const a=o.P.Distance(r,n)/this._options.radius,l=o.jp.Vector3[2];let h,c,d;if(r.normalizeToRef(l),a>this._options.centripetalForceThreshold&&l.negateInPlace(),a>this._options.centripetalForceThreshold)h=l.x*this._options.centripetalForceMultiplier,c=l.y*this._options.updraftForceMultiplier,d=l.z*this._options.centripetalForceMultiplier;else{const e=o.P.Cross(n,t).normalize();h=(e.x+l.x)*this._options.centrifugalForceMultiplier,c=this._originTop.y*this._options.updraftForceMultiplier,d=(e.z+l.z)*this._options.centrifugalForceMultiplier}const u=o.jp.Vector3[3];return u.set(h,c,d),u.scaleInPlace(this._options.strength),i.force.copyFrom(u),i.contactPoint.copyFrom(t),i.distanceFromOrigin=a,!0}_getBodyHitData(e,t,i){if(US.HasAppliedForces(e,i))return!1;const n=e.transformNode,s=e.getObjectCenterWorld(i);return!!US.IsInsideCylinder(s,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(n,s,t))}_getImpostorHitData(e,t){if(0===e.mass)return!1;if("Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const n=e.getObjectCenter();return this._getHitData(i,n,t),!0}_tick(){const e=kS.hitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach((t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)})):this._physicsEngine.getBodies().forEach((t=>{t.iterateOverAllInstances(((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)}))}))}_prepareCylinder(){this._cylinder||(this._cylinder=Fa("vortexEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0)}}kS.originOnPlane=o.P.Zero(),kS.hitData={force:new o.P,contactPoint:new o.P,distanceFromOrigin:0};class GS{constructor(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=wS.Center}}class zS{constructor(){this.radius=5,this.strength=10,this.height=10,this.centripetalForceThreshold=.7,this.centripetalForceMultiplier=5,this.centrifugalForceMultiplier=.5,this.updraftForceMultiplier=.02}}!function(e){e[e.Constant=0]="Constant",e[e.Linear=1]="Linear"}(FS||(FS={})),function(e){e[e.Center=0]="Center",e[e.Perpendicular=1]="Perpendicular"}(wS||(wS={}));const WS="blackAndWhitePixelShader",HS="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}";Ht.v.ShadersStore[WS]=HS;class XS extends Zt{getClassName(){return"BlackAndWhitePostProcess"}constructor(e,t,i,n,s,r){super(e,"blackAndWhite",["degree"],null,t,i,n,s,r),this.degree=1,this.onApplyObservable.add((e=>{e.setFloat("degree",this.degree)}))}static _Parse(e,t,i,n){return E.p4.Parse((()=>new XS(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,n)}}(0,oe.gn)([(0,E.qC)()],XS.prototype,"degree",void 0),(0,l.H)("BABYLON.BlackAndWhitePostProcess",XS);class YS{constructor(e,t,i,n){this._name=t,this._singleInstance=n||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}get isSupported(){for(const e in this._postProcesses)if(Object.prototype.hasOwnProperty.call(this._postProcesses,e)){const t=this._postProcesses[e];for(let e=0;e{const i=e.attachPostProcess(t);this._indicesForCamera[s].push(i)})),this._cameras[s]||(this._cameras[s]=e)}}_detachCameras(e){const t=se.w1.MakeArray(e||this._cameras);if(t)for(let i=0;i{e.detachPostProcess(t)})),this._cameras[n]&&(this._cameras[n]=null)}}_enable(e){const t=se.w1.MakeArray(e||this._cameras);if(t)for(let i=0;i{t[i].attachPostProcess(e,this._indicesForCamera[n][s])}))}}_disable(e){const t=se.w1.MakeArray(e||this._cameras);if(t)for(let i=0;i{e.detachPostProcess(t)}))}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}}const jS="extractHighlightsPixelShader",KS="#include\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}";Ht.v.ShadersStore[jS]=KS;class qS extends Zt{getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i,n,s,r,o=0,a=!1){super(e,"extractHighlights",["threshold","exposure"],null,t,i,n,s,r,null,o,void 0,null,a),this.threshold=.9,this._exposure=1,this._inputPostProcess=null,this.onApplyObservable.add((e=>{this.externalTextureSamplerBinding=!!this._inputPostProcess,this._inputPostProcess&&e.setTextureFromPostProcess("textureSampler",this._inputPostProcess),e.setFloat("threshold",Math.pow(this.threshold,k.zp)),e.setFloat("exposure",this._exposure)}))}}(0,oe.gn)([(0,E.qC)()],qS.prototype,"threshold",void 0),(0,l.H)("BABYLON.ExtractHighlightsPostProcess",qS);const $S="bloomMergePixelShader",QS="uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n";Ht.v.ShadersStore[$S]=QS;class ZS extends Zt{getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,n,s,r,o,a,l,h=0,c=!1){super(e,"bloomMerge",["bloomWeight"],["bloomBlur"],s,r,o,a,l,null,h,void 0,null,!0),this.weight=1,this.weight=n,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("bloomBlur",i),e.setFloat("bloomWeight",this.weight)})),c||this.updateEffect()}}(0,oe.gn)([(0,E.qC)()],ZS.prototype,"weight",void 0),(0,l.H)("BABYLON.BloomMergePostProcess",ZS);class JS extends YS{get threshold(){return this._downscale.threshold}set threshold(e){this._downscale.threshold=e}get weight(){return this._merge.weight}set weight(e){this._merge.weight=e}get kernel(){return this._blurX.kernel/this._bloomScale}set kernel(e){this._blurX.kernel=e*this._bloomScale,this._blurY.kernel=e*this._bloomScale}constructor(e,t,i,n,s=0,r=!1){super(e.getEngine(),"bloom",(()=>this._effects),!0),this._bloomScale=t,this._effects=[],this._downscale=new qS("highlights",1,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,r),this._blurX=new bp("horizontal blur",new o.FM(1,0),10,t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,void 0,r),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new bp("vertical blur",new o.FM(0,1),10,t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,void 0,r),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=n,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new ZS("bloomMerge",this._downscale,this._blurY,i,t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,r),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;t{e.setFloat("chromatic_aberration",this.aberrationAmount),e.setFloat("screen_width",t),e.setFloat("screen_height",i),e.setFloat("radialIntensity",this.radialIntensity),e.setFloat2("direction",this.direction.x,this.direction.y),e.setFloat2("centerPosition",this.centerPosition.x,this.centerPosition.y)}))}static _Parse(e,t,i,n){return E.p4.Parse((()=>new iE(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1)),e,i,n)}}(0,oe.gn)([(0,E.qC)()],iE.prototype,"aberrationAmount",void 0),(0,oe.gn)([(0,E.qC)()],iE.prototype,"radialIntensity",void 0),(0,oe.gn)([(0,E.qC)()],iE.prototype,"direction",void 0),(0,oe.gn)([(0,E.qC)()],iE.prototype,"centerPosition",void 0),(0,oe.gn)([(0,E.qC)()],iE.prototype,"screenWidth",void 0),(0,oe.gn)([(0,E.qC)()],iE.prototype,"screenHeight",void 0),(0,l.H)("BABYLON.ChromaticAberrationPostProcess",iE);const nE="circleOfConfusionPixelShader",sE="uniform sampler2D depthSampler;\nvarying vec2 vUV;\nuniform vec2 cameraMinMaxZ;\nuniform float focusDistance;\nuniform float cocPrecalculation;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\n#define CUSTOM_COC_DEPTH\nfloat pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; \n#define CUSTOM_COC_PIXELDISTANCE\nfloat coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,coc,coc,1.0);\n}\n";Ht.v.ShadersStore[nE]=sE;class rE extends Zt{getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,n,s,r,o,a=0,l=!1){super(e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],i,n,s,r,o,null,a,void 0,null,l),this.lensSize=50,this.fStop=1.4,this.focusDistance=2e3,this.focalLength=50,this._depthTexture=null,this._depthTexture=t,this.onApplyObservable.add((e=>{if(!this._depthTexture)return void p.Y.Warn("No depth texture set on CircleOfConfusionPostProcess");e.setTexture("depthSampler",this._depthTexture);const t=this.lensSize/this.fStop*this.focalLength/(this.focusDistance-this.focalLength);e.setFloat("focusDistance",this.focusDistance),e.setFloat("cocPrecalculation",t);const i=this._depthTexture.activeCamera;e.setFloat2("cameraMinMaxZ",i.minZ,i.maxZ-i.minZ)}))}set depthTexture(e){this._depthTexture=e}}(0,oe.gn)([(0,E.qC)()],rE.prototype,"lensSize",void 0),(0,oe.gn)([(0,E.qC)()],rE.prototype,"fStop",void 0),(0,oe.gn)([(0,E.qC)()],rE.prototype,"focusDistance",void 0),(0,oe.gn)([(0,E.qC)()],rE.prototype,"focalLength",void 0),(0,l.H)("BABYLON.CircleOfConfusionPostProcess",rE);const oE="colorCorrectionPixelShader",aE="uniform sampler2D textureSampler; \nuniform sampler2D colorTable; \nvarying vec2 vUV;\nconst float SLICE_COUNT=16.0; \nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}";Ht.v.ShadersStore[oE]=aE;class lE extends Zt{getClassName(){return"ColorCorrectionPostProcess"}constructor(e,t,i,n,s,r,o){super(e,"colorCorrection",null,["colorTable"],i,n,s,r,o);const a=(null==n?void 0:n.getScene())||null;this._colorTableTexture=new Le(t,a,!0,!1,Le.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=Le.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=Le.CLAMP_ADDRESSMODE,this.colorTableUrl=t,this.onApply=e=>{e.setTexture("colorTable",this._colorTableTexture)}}static _Parse(e,t,i,n){return E.p4.Parse((()=>new lE(e.name,e.colorTableUrl,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,n)}}(0,oe.gn)([(0,E.qC)()],lE.prototype,"colorTableUrl",void 0),(0,l.H)("BABYLON.ColorCorrectionPostProcess",lE);const hE="convolutionPixelShader",cE="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}";Ht.v.ShadersStore[hE]=cE;class dE extends Zt{getClassName(){return"ConvolutionPostProcess"}constructor(e,t,i,n,s,r,o,a=0){super(e,"convolution",["kernel","screenSize"],null,i,n,s,r,o,null,a),this.kernel=t,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setArray("kernel",this.kernel)}}static _Parse(e,t,i,n){return E.p4.Parse((()=>new dE(e.name,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType)),e,i,n)}}dE.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1],dE.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0],dE.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1],dE.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0],dE.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2],dE.GaussianKernel=[0,1,0,1,1,1,0,1,0],(0,oe.gn)([(0,E.qC)()],dE.prototype,"kernel",void 0),(0,l.H)("BABYLON.ConvolutionPostProcess",dE);class uE extends bp{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,n,s,r,o,a=null,l=Le.BILINEAR_SAMPLINGMODE,h,c,d=0,u=!1,p=5){super(e,i,n,s,r,2,h,c,d,"#define DOF 1\r\n",u,p),this.direction=i,this.externalTextureSamplerBinding=!!a,this.onApplyObservable.add((e=>{null!=a&&e.setTextureFromPostProcess("textureSampler",a),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",o)}))}}(0,oe.gn)([(0,E.qC)()],uE.prototype,"direction",void 0),(0,l.H)("BABYLON.DepthOfFieldBlurPostProcess",uE);const pE="depthOfFieldMergePixelShader",fE="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#endif\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nfloat coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r;\n#if BLUR_LEVEL==0\nvec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);\nvec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL==1\nif(coc<0.5){\nvec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);\nvec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);\nvec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL==2\nif(coc<0.33){\nvec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);\nvec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);\nvec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);\nvec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n";Ht.v.ShadersStore[pE]=fE;class _E extends Zt{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,n,s,r,o,a,l,h=0,c=!1){super(e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],s,r,o,a,l,null,h,void 0,null,!0),this._blurSteps=n,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),n.forEach(((t,i)=>{e.setTextureFromPostProcessOutput("blurStep"+(n.length-i-1),t)}))})),c||this.updateEffect()}updateEffect(e=null,t=null,i=null,n,s,r){e||(e="",e+="#define BLUR_LEVEL "+(this._blurSteps.length-1)+"\n"),super.updateEffect(e,t,i,n,s,r)}}var mE;!function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High"}(mE||(mE={}));class gE extends YS{set focalLength(e){this._circleOfConfusion.focalLength=e}get focalLength(){return this._circleOfConfusion.focalLength}set fStop(e){this._circleOfConfusion.fStop=e}get fStop(){return this._circleOfConfusion.fStop}set focusDistance(e){this._circleOfConfusion.focusDistance=e}get focusDistance(){return this._circleOfConfusion.focusDistance}set lensSize(e){this._circleOfConfusion.lensSize=e}get lensSize(){return this._circleOfConfusion.lensSize}constructor(e,t,i=mE.Low,n=0,s=!1){super(e.getEngine(),"depth of field",(()=>this._effects),!0),this._effects=[];const r=e.getEngine(),a=r.isWebGPU||r.webGLVersion>1?6:5;this._circleOfConfusion=new rE("circleOfConfusion",t,1,null,Le.BILINEAR_SAMPLINGMODE,r,!1,n,s),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];let l=1,h=15;switch(i){case mE.High:l=3,h=51;break;case mE.Medium:l=2,h=31;break;default:h=15,l=1}const c=h/Math.pow(2,l-1);let d=1;for(let u=0;unew SE(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,n)}}(0,l.H)("BABYLON.DisplayPassPostProcess",SE);const EE="filterPixelShader",xE="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}";Ht.v.ShadersStore[EE]=xE;class bE extends Zt{getClassName(){return"FilterPostProcess"}constructor(e,t,i,n,s,r,o){super(e,"filter",["kernelMatrix"],null,i,n,s,r,o),this.kernelMatrix=t,this.onApply=e=>{e.setMatrix("kernelMatrix",this.kernelMatrix)}}static _Parse(e,t,i,n){return E.p4.Parse((()=>new bE(e.name,e.kernelMatrix,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,n)}}(0,oe.gn)([(0,E.oQ)()],bE.prototype,"kernelMatrix",void 0),(0,l.H)("BABYLON.FilterPostProcess",bE);const CE="fxaaPixelShader",yE="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN{const t=this.texelSize;e.setFloat2("texelSize",t.x,t.y)}))}_getDefines(){const e=this.getEngine();if(!e)return null;const t=e.getGlInfo();return t&&t.renderer&&t.renderer.toLowerCase().indexOf("mali")>-1?"#define MALI 1\n":null}static _Parse(e,t,i,n){return E.p4.Parse((()=>new PE(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,n)}}(0,l.H)("BABYLON.FxaaPostProcess",PE);const IE="grainPixelShader",ME="#include\nuniform sampler2D textureSampler; \nuniform float intensity;\nuniform float animatedSeed;\nvarying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}";Ht.v.ShadersStore[IE]=ME;class OE extends Zt{getClassName(){return"GrainPostProcess"}constructor(e,t,i,n,s,r,o=0,a=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,n,s,r,null,o,void 0,null,a),this.intensity=30,this.animated=!1,this.onApplyObservable.add((e=>{e.setFloat("intensity",this.intensity),e.setFloat("animatedSeed",this.animated?Math.random()+1:1)}))}static _Parse(e,t,i,n){return E.p4.Parse((()=>new OE(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,n)}}(0,oe.gn)([(0,E.qC)()],OE.prototype,"intensity",void 0),(0,oe.gn)([(0,E.qC)()],OE.prototype,"animated",void 0),(0,l.H)("BABYLON.GrainPostProcess",OE);const DE="highlightsPixelShader",NE="varying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}";Ht.v.ShadersStore[DE]=NE;const FE="mrtFragmentDeclaration",wE="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n";Ht.v.IncludesShadersStore[FE]=wE;const LE="geometryPixelShader",BE="#extension GL_EXT_draw_buffers : require\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\nprecision highp float;\n#ifdef BUMP\nvarying mat4 vWorldView;\nvarying vec3 vNormalW;\n#else\nvarying vec3 vNormalV;\n#endif\nvarying vec4 vViewPos;\n#if defined(POSITION) || defined(BUMP)\nvarying vec3 vPositionW;\n#endif\n#ifdef VELOCITY\nvarying vec4 vCurrentPosition;\nvarying vec4 vPreviousPosition;\n#endif\n#ifdef NEED_UV\nvarying vec2 vUV;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIVITY)\n#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nuniform sampler2D reflectivitySampler;\nvarying vec2 vReflectivityUV;\n#endif\n#ifdef ALBEDOTEXTURE\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\n#endif\n#ifdef REFLECTIVITYCOLOR\nuniform vec3 reflectivityColor;\n#endif\n#ifdef ALBEDOCOLOR\nuniform vec3 albedoColor;\n#endif\n#ifdef METALLIC\nuniform float metallic;\n#endif\n#if defined(ROUGHNESS) || defined(GLOSSINESS)\nuniform float glossiness;\n#endif\n#endif\n#if defined(ALPHATEST) && defined(NEED_UV)\nuniform sampler2D diffuseSampler;\n#endif\n#include\n#include[RENDER_TARGET_COUNT]\n#include\n#include\n#include\nvoid main() {\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nvec3 normalOutput;\n#ifdef BUMP\nvec3 normalW=normalize(vNormalW);\n#include\nnormalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0)));\n#else\nnormalOutput=normalize(vNormalV);\n#endif\n#ifdef PREPASS\n#ifdef PREPASS_DEPTH\ngl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n#endif\n#ifdef PREPASS_NORMAL\ngl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0);\n#endif\n#else\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\ngl_FragData[1]=vec4(normalOutput,1.0);\n#endif\n#ifdef POSITION\ngl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0);\n#endif\n#ifdef VELOCITY\nvec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;\nvec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;\nvec2 velocity=abs(a-b);\nvelocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;\ngl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0);\n#endif\n#ifdef REFLECTIVITY\nvec4 reflectivity=vec4(0.0,0.0,0.0,1.0);\n#ifdef METALLICWORKFLOW\nfloat metal=1.0;\nfloat roughness=1.0;\n#ifdef ORMTEXTURE\nmetal*=texture2D(reflectivitySampler,vReflectivityUV).b;\nroughness*=texture2D(reflectivitySampler,vReflectivityUV).g;\n#endif\n#ifdef METALLIC\nmetal*=metallic;\n#endif\n#ifdef ROUGHNESS\nroughness*=(1.0-glossiness); \n#endif\nreflectivity.a-=roughness;\nvec3 color=vec3(1.0);\n#ifdef ALBEDOTEXTURE\ncolor=texture2D(albedoSampler,vAlbedoUV).rgb;\n#ifdef GAMMAALBEDO\ncolor=toLinearSpace(color);\n#endif\n#endif\n#ifdef ALBEDOCOLOR\ncolor*=albedoColor.xyz;\n#endif\nreflectivity.rgb=mix(vec3(0.04),color,metal);\n#else\n#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nreflectivity=texture2D(reflectivitySampler,vReflectivityUV);\n#ifdef GAMMAREFLECTIVITYTEXTURE\nreflectivity.rgb=toLinearSpace(reflectivity.rgb);\n#endif\n#else \n#ifdef REFLECTIVITYCOLOR\nreflectivity.rgb=toLinearSpace(reflectivityColor.xyz);\nreflectivity.a=1.0;\n#endif\n#endif\n#ifdef GLOSSINESSS\nreflectivity.a*=glossiness; \n#endif\n#endif\ngl_FragData[REFLECTIVITY_INDEX]=reflectivity;\n#endif\n}\n";Ht.v.ShadersStore[LE]=BE;const UE="geometryVertexDeclaration",VE="uniform mat4 viewProjection;\nuniform mat4 view;";Ht.v.IncludesShadersStore[UE]=VE;const kE="geometryUboDeclaration",GE="#include\n";Ht.v.IncludesShadersStore[kE]=GE;const zE="geometryVertexShader",WE="precision highp float;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include<__decl__geometryVertex>\n#include\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef NEED_UV\nvarying vec2 vUV;\n#ifdef ALPHATEST\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef BUMP\nuniform mat4 bumpMatrix;\nvarying vec2 vBumpUV;\n#endif\n#ifdef REFLECTIVITY\nuniform mat4 reflectivityMatrix;\nuniform mat4 albedoMatrix;\nvarying vec2 vReflectivityUV;\nvarying vec2 vAlbedoUV;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef BUMP\nvarying mat4 vWorldView;\n#endif\n#ifdef BUMP\nvarying vec3 vNormalW;\n#else\nvarying vec3 vNormalV;\n#endif\nvarying vec4 vViewPos;\n#if defined(POSITION) || defined(BUMP)\nvarying vec3 vPositionW;\n#endif\n#ifdef VELOCITY\nuniform mat4 previousViewProjection;\nvarying vec4 vCurrentPosition;\nvarying vec4 vPreviousPosition;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{\nvec3 positionUpdated=position;\nvec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#if defined(VELOCITY) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#include\n#include\nvec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0));\n#ifdef BUMP\nvWorldView=view*finalWorld;\nvNormalW=normalUpdated;\n#else\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0)));\n#endif\nvViewPos=view*worldPos;\n#if defined(VELOCITY) && defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#if NUM_BONE_INFLUENCERS>0\nmat4 previousInfluence;\npreviousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\npreviousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\npreviousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\npreviousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\nvPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0);\n#else\nvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#endif\n#if defined(POSITION) || defined(BUMP)\nvPositionW=worldPos.xyz/worldPos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#include\n#ifdef NEED_UV\n#ifdef UV1\n#if defined(ALPHATEST) && defined(ALPHATEST_UV1)\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#else\nvUV=uv;\n#endif\n#ifdef BUMP_UV1\nvBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef REFLECTIVITY_UV1\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef ALBEDO_UV1\nvAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#endif\n#ifdef UV2\n#if defined(ALPHATEST) && defined(ALPHATEST_UV2)\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#else\nvUV=uv2;\n#endif\n#ifdef BUMP_UV2\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n#endif\n#ifdef REFLECTIVITY_UV2\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n#endif\n#ifdef ALBEDO_UV2\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#endif\n#include\n}\n";Ht.v.ShadersStore[zE]=WE;const HE=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];(0,ua.qx)(HE);class XE{_linkPrePassRenderer(e){this._linkedWithPrePass=!0,this._prePassRenderer=e,this._multiRenderTarget&&(this._multiRenderTarget.onClearObservable.clear(),this._multiRenderTarget.onClearObservable.add((()=>{})))}_unlinkPrePassRenderer(){this._linkedWithPrePass=!1,this._createRenderTargets()}_resetLayout(){this._enablePosition=!1,this._enableReflectivity=!1,this._enableVelocity=!1,this._attachmentsFromPrePass=[]}_forceTextureType(e,t){e===XE.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===XE.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===XE.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===XE.DEPTH_TEXTURE_TYPE?this._depthIndex=t:e===XE.NORMAL_TEXTURE_TYPE&&(this._normalIndex=t)}_setAttachments(e){this._attachmentsFromPrePass=e}_linkInternalTexture(e){this._multiRenderTarget.setInternalTexture(e,0,!1)}get renderList(){return this._multiRenderTarget.renderList}set renderList(e){this._multiRenderTarget.renderList=e}get isSupported(){return this._multiRenderTarget.isSupported}getTextureIndex(e){switch(e){case XE.POSITION_TEXTURE_TYPE:return this._positionIndex;case XE.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case XE.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;default:return-1}}get enablePosition(){return this._enablePosition}set enablePosition(e){this._enablePosition=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableVelocity(){return this._enableVelocity}set enableVelocity(e){this._enableVelocity=e,e||(this._previousTransformationMatrices={}),this._linkedWithPrePass||(this.dispose(),this._createRenderTargets()),this._scene.needsPreviousWorldMatrices=e}get enableReflectivity(){return this._enableReflectivity}set enableReflectivity(e){this._enableReflectivity=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get scene(){return this._scene}get ratio(){return this._ratio}constructor(e,t=1,i=15){this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this._resizeObserver=null,this._enablePosition=!1,this._enableVelocity=!1,this._enableReflectivity=!1,this._clearColor=new a.HE(0,0,0,0),this._clearDepthColor=new a.HE(1e8,0,0,1),this._positionIndex=-1,this._velocityIndex=-1,this._reflectivityIndex=-1,this._depthIndex=-1,this._normalIndex=-1,this._linkedWithPrePass=!1,this.useSpecificClearForDepthTexture=!1,this._scene=e,this._ratio=t,this._useUbo=e.getEngine().supportsUniformBuffers,this._depthFormat=i,XE._SceneComponentInitialization(this._scene),this._createRenderTargets()}isReady(e,t){const i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;const n=[],s=[ne.o.PositionKind,ne.o.NormalKind],r=e.getMesh();if(i){let e=!1;if(i.needAlphaTesting()&&i.getAlphaTestTexture()&&(n.push("#define ALPHATEST"),n.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),e=!0),i.bumpTexture&&Bs.BumpTextureEnabled&&(n.push("#define BUMP"),n.push(`#define BUMP_UV${i.bumpTexture.coordinatesIndex+1}`),e=!0),this._enableReflectivity){let t=!1;"PBRMetallicRoughnessMaterial"===i.getClassName()?(null!==i.metallicRoughnessTexture&&(n.push("#define ORMTEXTURE"),n.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),n.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!==i.metallic&&(n.push("#define METALLIC"),n.push("#define METALLICWORKFLOW"),t=!0),null!==i.roughness&&(n.push("#define ROUGHNESS"),n.push("#define METALLICWORKFLOW"),t=!0),t&&(null!==i.baseTexture&&(n.push("#define ALBEDOTEXTURE"),n.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&n.push("#define GAMMAALBEDO"),e=!0),null!==i.baseColor&&n.push("#define ALBEDOCOLOR"))):"PBRSpecularGlossinessMaterial"===i.getClassName()?(null!==i.specularGlossinessTexture?(n.push("#define SPECULARGLOSSINESSTEXTURE"),n.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),e=!0,i.specularGlossinessTexture.gammaSpace&&n.push("#define GAMMAREFLECTIVITYTEXTURE")):null!==i.specularColor&&n.push("#define REFLECTIVITYCOLOR"),null!==i.glossiness&&n.push("#define GLOSSINESS")):"PBRMaterial"===i.getClassName()?(null!==i.metallicTexture&&(n.push("#define ORMTEXTURE"),n.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),n.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!==i.metallic&&(n.push("#define METALLIC"),n.push("#define METALLICWORKFLOW"),t=!0),null!==i.roughness&&(n.push("#define ROUGHNESS"),n.push("#define METALLICWORKFLOW"),t=!0),t?(null!==i.albedoTexture&&(n.push("#define ALBEDOTEXTURE"),n.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&n.push("#define GAMMAALBEDO"),e=!0),null!==i.albedoColor&&n.push("#define ALBEDOCOLOR")):(null!==i.reflectivityTexture?(n.push("#define SPECULARGLOSSINESSTEXTURE"),n.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&n.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0):null!==i.reflectivityColor&&n.push("#define REFLECTIVITYCOLOR"),null!==i.microSurface&&n.push("#define GLOSSINESS"))):"StandardMaterial"===i.getClassName()&&(null!==i.specularTexture&&(n.push("#define REFLECTIVITYTEXTURE"),n.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&n.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0),null!==i.specularColor&&n.push("#define REFLECTIVITYCOLOR"))}e&&(n.push("#define NEED_UV"),r.isVerticesDataPresent(ne.o.UVKind)&&(s.push(ne.o.UVKind),n.push("#define UV1")),r.isVerticesDataPresent(ne.o.UV2Kind)&&(s.push(ne.o.UV2Kind),n.push("#define UV2")))}this._linkedWithPrePass&&(n.push("#define PREPASS"),-1!==this._depthIndex&&(n.push("#define DEPTH_INDEX "+this._depthIndex),n.push("#define PREPASS_DEPTH")),-1!==this._normalIndex&&(n.push("#define NORMAL_INDEX "+this._normalIndex),n.push("#define PREPASS_NORMAL"))),this._enablePosition&&(n.push("#define POSITION"),n.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(n.push("#define VELOCITY"),n.push("#define VELOCITY_INDEX "+this._velocityIndex),-1===this.excludedSkinnedMeshesFromVelocity.indexOf(r)&&n.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(n.push("#define REFLECTIVITY"),n.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),r.useBones&&r.computeBonesUsingShaders?(s.push(ne.o.MatricesIndicesKind),s.push(ne.o.MatricesWeightsKind),r.numBoneInfluencers>4&&(s.push(ne.o.MatricesIndicesExtraKind),s.push(ne.o.MatricesWeightsExtraKind)),n.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),n.push("#define BonesPerMesh "+(r.skeleton?r.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0");const o=r.morphTargetManager;let a=0;o&&o.numInfluencers>0&&(a=o.numInfluencers,n.push("#define MORPHTARGETS"),n.push("#define NUM_MORPH_INFLUENCERS "+a),o.isUsingTextureForTargets&&n.push("#define MORPHTARGETS_TEXTURE"),It.G.PrepareAttributesForMorphTargetsInfluencers(s,r,a)),t&&(n.push("#define INSTANCES"),It.G.PushAttributesForInstances(s,this._enableVelocity),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES")),this._linkedWithPrePass?n.push("#define RENDER_TARGET_COUNT "+this._attachmentsFromPrePass.length):n.push("#define RENDER_TARGET_COUNT "+this._multiRenderTarget.textures.length),(0,ua.lK)(i,this._scene,n);const l=this._scene.getEngine(),h=e._getDrawWrapper(void 0,!0),c=h.defines,d=n.join("\n");return c!==d&&h.setEffect(l.createEffect("geometry",{attributes:s,uniformsNames:HE,samplers:["diffuseSampler","bumpSampler","reflectivitySampler","albedoSampler","morphTargets"],defines:d,onCompiled:null,fallbacks:null,onError:null,uniformBuffersNames:["Scene"],indexParameters:{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:a}},l),d),h.effect.isReady()}getGBuffer(){return this._multiRenderTarget}get samples(){return this._multiRenderTarget.samples}set samples(e){this._multiRenderTarget.samples=e}dispose(){if(this._resizeObserver){this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null}this.getGBuffer().dispose()}_assignRenderTargetIndices(){const e=[];let t=2;return e.push("gBuffer_Depth","gBuffer_Normal"),this._enablePosition&&(this._positionIndex=t,t++,e.push("gBuffer_Position")),this._enableVelocity&&(this._velocityIndex=t,t++,e.push("gBuffer_Velocity")),this._enableReflectivity&&(this._reflectivityIndex=t,t++,e.push("gBuffer_Reflectivity")),[t,e]}_createRenderTargets(){const e=this._scene.getEngine(),[t,i]=this._assignRenderTargetIndices();let n=0;if(e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?n=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(n=2),this._multiRenderTarget=new Lv("gBuffer",{width:e.getRenderWidth()*this._ratio,height:e.getRenderHeight()*this._ratio},t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,defaultType:n,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=Le.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=Le.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;const s=[!0],r=[!1],a=[!0];for(let o=1;o{e.bindAttachments(this.useSpecificClearForDepthTexture?h:l),e.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(e.bindAttachments(c),e.clear(this._clearDepthColor,!0,!0,!0)),e.bindAttachments(l)})),this._resizeObserver=e.onResizeObservable.add((()=>{this._multiRenderTarget&&this._multiRenderTarget.resize({width:e.getRenderWidth()*this._ratio,height:e.getRenderHeight()*this._ratio})}));const d=e=>{const t=e.getRenderingMesh(),i=e.getEffectiveMesh(),n=this._scene,s=n.getEngine(),r=e.getMaterial();if(!r)return;if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,this._enableVelocity&&!this._previousTransformationMatrices[i.uniqueId]&&(this._previousTransformationMatrices[i.uniqueId]={world:o.y3.Identity(),viewProjection:n.getTransformMatrix()},t.skeleton)){const e=t.skeleton.getTransformMatrices(t);this._previousBonesTransformationMatrices[t.uniqueId]=this._copyBonesTransformationMatrices(e,new Float32Array(e.length))}const a=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(a.mustReturn)return;const l=s.getCaps().instancedArrays&&(null!==a.visibleInstances[e._id]||t.hasThinInstances),h=i.getWorldMatrix();if(this.isReady(e,l)){const o=e._getDrawWrapper();if(!o)return;const c=o.effect;let d;s.enableEffect(o),l||t._bind(e,c,r.fillMode),this._useUbo?(It.G.BindSceneUniformBuffer(c,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(c.setMatrix("viewProjection",n.getTransformMatrix()),c.setMatrix("view",n.getViewMatrix()));const u=t._instanceDataStorage;if(u.isFrozen||!r.backFaceCulling&&null===t.overrideMaterialSideOrientation)d=u.sideOrientation;else{const e=i._getWorldMatrixDeterminant();d=t.overrideMaterialSideOrientation,null===d&&(d=r.sideOrientation),e<0&&(d=d===ut.F.ClockWiseSideOrientation?ut.F.CounterClockWiseSideOrientation:ut.F.ClockWiseSideOrientation)}if(r._preBind(o,d),r.needAlphaTesting()){const e=r.getAlphaTestTexture();e&&(c.setTexture("diffuseSampler",e),c.setMatrix("diffuseMatrix",e.getTextureMatrix()))}r.bumpTexture&&n.getEngine().getCaps().standardDerivatives&&Bs.BumpTextureEnabled&&(c.setFloat3("vBumpInfos",r.bumpTexture.coordinatesIndex,1/r.bumpTexture.level,r.parallaxScaleBias),c.setMatrix("bumpMatrix",r.bumpTexture.getTextureMatrix()),c.setTexture("bumpSampler",r.bumpTexture),c.setFloat2("vTangentSpaceParams",r.invertNormalMapX?-1:1,r.invertNormalMapY?-1:1)),this._enableReflectivity&&("PBRMetallicRoughnessMaterial"===r.getClassName()?(null!==r.metallicRoughnessTexture&&(c.setTexture("reflectivitySampler",r.metallicRoughnessTexture),c.setMatrix("reflectivityMatrix",r.metallicRoughnessTexture.getTextureMatrix())),null!==r.metallic&&c.setFloat("metallic",r.metallic),null!==r.roughness&&c.setFloat("glossiness",1-r.roughness),null!==r.baseTexture&&(c.setTexture("albedoSampler",r.baseTexture),c.setMatrix("albedoMatrix",r.baseTexture.getTextureMatrix())),null!==r.baseColor&&c.setColor3("albedoColor",r.baseColor)):"PBRSpecularGlossinessMaterial"===r.getClassName()?(null!==r.specularGlossinessTexture?(c.setTexture("reflectivitySampler",r.specularGlossinessTexture),c.setMatrix("reflectivityMatrix",r.specularGlossinessTexture.getTextureMatrix())):null!==r.specularColor&&c.setColor3("reflectivityColor",r.specularColor),null!==r.glossiness&&c.setFloat("glossiness",r.glossiness)):"PBRMaterial"===r.getClassName()?(null!==r.metallicTexture&&(c.setTexture("reflectivitySampler",r.metallicTexture),c.setMatrix("reflectivityMatrix",r.metallicTexture.getTextureMatrix())),null!==r.metallic&&c.setFloat("metallic",r.metallic),null!==r.roughness&&c.setFloat("glossiness",1-r.roughness),null!==r.roughness||null!==r.metallic||null!==r.metallicTexture?(null!==r.albedoTexture&&(c.setTexture("albedoSampler",r.albedoTexture),c.setMatrix("albedoMatrix",r.albedoTexture.getTextureMatrix())),null!==r.albedoColor&&c.setColor3("albedoColor",r.albedoColor)):(null!==r.reflectivityTexture?(c.setTexture("reflectivitySampler",r.reflectivityTexture),c.setMatrix("reflectivityMatrix",r.reflectivityTexture.getTextureMatrix())):null!==r.reflectivityColor&&c.setColor3("reflectivityColor",r.reflectivityColor),null!==r.microSurface&&c.setFloat("glossiness",r.microSurface))):"StandardMaterial"===r.getClassName()&&(null!==r.specularTexture&&(c.setTexture("reflectivitySampler",r.specularTexture),c.setMatrix("reflectivityMatrix",r.specularTexture.getTextureMatrix())),null!==r.specularColor&&c.setColor3("reflectivityColor",r.specularColor))),(0,ua.an)(c,r,this._scene),t.useBones&&t.computeBonesUsingShaders&&t.skeleton&&(c.setMatrices("mBones",t.skeleton.getTransformMatrices(t)),this._enableVelocity&&c.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[t.uniqueId])),It.G.BindMorphTargetParameters(t,c),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(c),this._enableVelocity&&(c.setMatrix("previousWorld",this._previousTransformationMatrices[i.uniqueId].world),c.setMatrix("previousViewProjection",this._previousTransformationMatrices[i.uniqueId].viewProjection)),l&&t.hasThinInstances&&c.setMatrix("world",h),t._processRendering(i,e,c,r.fillMode,a,l,((e,t)=>{e||c.setMatrix("world",t)}))}this._enableVelocity&&(this._previousTransformationMatrices[i.uniqueId].world=h.clone(),this._previousTransformationMatrices[i.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),t.skeleton&&this._copyBonesTransformationMatrices(t.skeleton.getTransformMatrices(t),this._previousBonesTransformationMatrices[i.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(t,i,n)=>{if((n||0===i)&&t.subMeshes)for(let s=0;s{let r;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(s.length){for(e.setColorWrite(!1),r=0;r{throw(0,ge.S)("GeometryBufferRendererSceneComponent")};class YE{constructor(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[2]}}Object.defineProperty(N.x.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(e){e&&e.isSupported&&(this._geometryBufferRenderer=e)},enumerable:!0,configurable:!0}),N.x.prototype.enableGeometryBufferRenderer=function(e=1,t=15){return this._geometryBufferRenderer||(this._geometryBufferRenderer=new XE(this,e,t),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null)),this._geometryBufferRenderer},N.x.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};class jE{constructor(e){this.name=Se.l.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(Se.l.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)}rebuild(){}dispose(){}_gatherRenderTargets(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())}}XE._SceneComponentInitialization=e=>{let t=e._getComponent(Se.l.NAME_GEOMETRYBUFFERRENDERER);t||(t=new jE(e),e._addComponent(t))};const KE="motionBlurPixelShader",qE="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float motionStrength;\nuniform float motionScale;\nuniform vec2 screenSize;\n#ifdef OBJECT_BASED\nuniform sampler2D velocitySampler;\n#else\nuniform sampler2D depthSampler;\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform mat4 projection;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#ifdef GEOMETRY_SUPPORTED\n#ifdef OBJECT_BASED\nvec2 texelSize=1.0/screenSize;\nvec4 velocityColor=texture2D(velocitySampler,vUV);\nvelocityColor.rg=velocityColor.rg*2.0-vec2(1.0);\nvec2 velocity=vec2(pow(velocityColor.r,3.0),pow(velocityColor.g,3.0))*velocityColor.a;\nvelocity*=motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint samplesCount=int(clamp(speed,1.0,SAMPLES));\nvelocity=normalize(velocity)*texelSize;\nfloat hlim=float(-samplesCount)*0.5+0.5;\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i=samplesCount)\nbreak;\nvec2 offset=vUV+velocity*(hlim+float(i));\n#if defined(WEBGPU)\nresult+=texture2DLodEXT(textureSampler,offset,0.0);\n#else\nresult+=texture2D(textureSampler,offset);\n#endif\n}\ngl_FragColor=result/float(samplesCount);\ngl_FragColor.a=1.0;\n#else\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\ndepth=projection[2].z+projection[3].z/depth; \nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=inverseViewProjection*cpos;\ncpos/=cpos.w;\nvec4 ppos=prevViewProjection*cpos;\nppos/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\n#if defined(WEBGPU)\nresult+=texture2DLodEXT(textureSampler,offset1,0.0);\n#else\nresult+=texture2D(textureSampler,offset1);\n#endif\n}\ngl_FragColor=result/float(nSamples);\n#endif\n#else\ngl_FragColor=texture2D(textureSampler,vUV);\n#endif\n}\n";Ht.v.ShadersStore[KE]=qE;class $E extends Zt{get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this._motionBlurSamples=e,this._updateEffect()}get isObjectBased(){return this._isObjectBased}set isObjectBased(e){this._isObjectBased!==e&&(this._isObjectBased=e,this._applyMode())}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}getClassName(){return"MotionBlurPostProcess"}constructor(e,t,i,n,s,r,o,a=0,l=!1,h=!1){super(e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],i,n,s,r,o,"#define GEOMETRY_SUPPORTED\n#define SAMPLES 64.0\n#define OBJECT_BASED",a,void 0,null,l),this.motionStrength=1,this._motionBlurSamples=32,this._isObjectBased=!0,this._forceGeometryBuffer=!1,this._invViewProjection=null,this._previousViewProjection=null,this._forceGeometryBuffer=h,this._forceGeometryBuffer?(t.enableGeometryBufferRenderer(),this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=!0)):(t.enablePrePassRenderer(),this._prePassRenderer&&(this._prePassRenderer.markAsDirty(),this._prePassEffectConfiguration=new YE)),this._applyMode()}excludeSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}t.push(e)}}removeExcludedSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}const i=t.indexOf(e);-1!==i&&t.splice(i,1)}}dispose(e){this._geometryBufferRenderer&&(this._geometryBufferRenderer._previousTransformationMatrices={},this._geometryBufferRenderer._previousBonesTransformationMatrices={},this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity=[]),super.dispose(e)}_applyMode(){if(!this._geometryBufferRenderer&&!this._prePassRenderer)return p.Y.Warn("Multiple Render Target support needed to compute object based motion blur"),this.updateEffect();this._updateEffect(),this._invViewProjection=null,this._previousViewProjection=null,this.isObjectBased?(this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=2),this.onApply=e=>this._onApplyObjectBased(e)):(this._invViewProjection=o.y3.Identity(),this._previousViewProjection=this._scene.getTransformMatrix().clone(),this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=5),this.onApply=e=>this._onApplyScreenBased(e))}_onApplyObjectBased(e){if(e.setVector2("screenSize",new o.FM(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(XE.VELOCITY_TEXTURE_TYPE);e.setTexture("velocitySampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){const t=this._prePassRenderer.getIndex(2);e.setTexture("velocitySampler",this._prePassRenderer.getRenderTarget().textures[t])}}_onApplyScreenBased(e){const t=o.jp.Matrix[0];if(t.copyFrom(this._scene.getTransformMatrix()),t.invertToRef(this._invViewProjection),e.setMatrix("inverseViewProjection",this._invViewProjection),e.setMatrix("prevViewProjection",this._previousViewProjection),this._previousViewProjection.copyFrom(t),e.setMatrix("projection",this._scene.getProjectionMatrix()),e.setVector2("screenSize",new o.FM(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(XE.DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){const t=this._prePassRenderer.getIndex(5);e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[t])}}_updateEffect(){if(this._geometryBufferRenderer||this._prePassRenderer){const e=["#define GEOMETRY_SUPPORTED","#define SAMPLES "+this._motionBlurSamples.toFixed(1),this._isObjectBased?"#define OBJECT_BASED":"#define SCREEN_BASED"];this.updateEffect(e.join("\n"))}}static _Parse(e,t,i,n){return E.p4.Parse((()=>new $E(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1)),e,i,n)}}(0,oe.gn)([(0,E.qC)()],$E.prototype,"motionStrength",void 0),(0,oe.gn)([(0,E.qC)()],$E.prototype,"motionBlurSamples",null),(0,oe.gn)([(0,E.qC)()],$E.prototype,"isObjectBased",null),(0,l.H)("BABYLON.MotionBlurPostProcess",$E);const QE="refractionPixelShader",ZE="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}";Ht.v.ShadersStore[QE]=ZE;class JE extends Zt{get refractionTexture(){return this._refTexture}set refractionTexture(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1}getClassName(){return"RefractionPostProcess"}constructor(e,t,i,n,s,r,o,a,l,h){super(e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],r,o,a,l,h),this._ownRefractionTexture=!0,this.color=i,this.depth=n,this.colorLevel=s,this.refractionTextureUrl=t,this.onActivateObservable.add((e=>{this._refTexture=this._refTexture||new Le(t,e.getScene())})),this.onApplyObservable.add((e=>{e.setColor3("baseColor",this.color),e.setFloat("depth",this.depth),e.setFloat("colorLevel",this.colorLevel),e.setTexture("refractionSampler",this._refTexture)}))}dispose(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),super.dispose(e)}static _Parse(e,t,i,n){return E.p4.Parse((()=>new JE(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,n)}}(0,oe.gn)([(0,E.qC)()],JE.prototype,"color",void 0),(0,oe.gn)([(0,E.qC)()],JE.prototype,"depth",void 0),(0,oe.gn)([(0,E.qC)()],JE.prototype,"colorLevel",void 0),(0,oe.gn)([(0,E.qC)()],JE.prototype,"refractionTextureUrl",void 0),(0,l.H)("BABYLON.RefractionPostProcess",JE);const ex="sharpenPixelShader",tx="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}";Ht.v.ShadersStore[ex]=tx;class ix extends Zt{getClassName(){return"SharpenPostProcess"}constructor(e,t,i,n,s,r,o=0,a=!1){super(e,"sharpen",["sharpnessAmounts","screenSize"],null,t,i,n,s,r,null,o,void 0,null,a),this.colorAmount=1,this.edgeAmount=.3,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setFloat2("sharpnessAmounts",this.edgeAmount,this.colorAmount)}}static _Parse(e,t,i,n){return E.p4.Parse((()=>new ix(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,n)}}(0,oe.gn)([(0,E.qC)()],ix.prototype,"colorAmount",void 0),(0,oe.gn)([(0,E.qC)()],ix.prototype,"edgeAmount",void 0),(0,l.H)("BABYLON.SharpenPostProcess",ix);class nx{get name(){return this._name}get cameras(){return this._cameras}constructor(e,t){this._engine=e,this._name=t,this._renderEffects={},this._renderEffectsForIsolatedPass=new Array,this._cameras=[]}getClassName(){return"PostProcessRenderPipeline"}get isSupported(){for(const e in this._renderEffects)if(Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&!this._renderEffects[e].isSupported)return!1;return!0}addEffect(e){this._renderEffects[e._name]=e}_rebuild(){}_enableEffect(e,t){const i=this._renderEffects[e];i&&i._enable(se.w1.MakeArray(t||this._cameras))}_disableEffect(e,t){const i=this._renderEffects[e];i&&i._disable(se.w1.MakeArray(t||this._cameras))}_attachCameras(e,t){const i=se.w1.MakeArray(e||this._cameras);if(!i)return;const n=[];let s;for(s=0;s0){const i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0}setPrePassRenderer(e){return!1}dispose(){}}(0,oe.gn)([(0,E.qC)()],nx.prototype,"_name",void 0);class sx{constructor(){this._renderPipelines={}}get supportedPipelines(){const e=[];for(const t in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,t)){const i=this._renderPipelines[t];i.isSupported&&e.push(i)}return e}addPipeline(e){this._renderPipelines[e._name]=e}removePipeline(e){delete this._renderPipelines[e]}attachCamerasToRenderPipeline(e,t,i=!1){const n=this._renderPipelines[e];n&&n._attachCameras(t,i)}detachCamerasFromRenderPipeline(e,t){const i=this._renderPipelines[e];i&&i._detachCameras(t)}enableEffectInPipeline(e,t,i){const n=this._renderPipelines[e];n&&n._enableEffect(t,i)}disableEffectInPipeline(e,t,i){const n=this._renderPipelines[e];n&&n._disableEffect(t,i)}update(){for(const e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){const t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}}_rebuild(){for(const e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){this._renderPipelines[e]._rebuild()}}dispose(){for(const e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){this._renderPipelines[e].dispose()}}}Object.defineProperty(N.x.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let e=this._getComponent(Se.l.NAME_POSTPROCESSRENDERPIPELINEMANAGER);e||(e=new rx(this),this._addComponent(e)),this._postProcessRenderPipelineManager=new sx}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});class rx{constructor(e){this.name=Se.l.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(Se.l.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER,this,this._gatherRenderTargets)}rebuild(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager._rebuild()}dispose(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.dispose()}_gatherRenderTargets(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.update()}}class ox extends nx{get automaticBuild(){return this._buildAllowed}set automaticBuild(e){this._buildAllowed=e}get scene(){return this._scene}set sharpenEnabled(e){this._sharpenEnabled!==e&&(this._sharpenEnabled=e,this._buildPipeline())}get sharpenEnabled(){return this._sharpenEnabled}get bloomKernel(){return this._bloomKernel}set bloomKernel(e){this._bloomKernel=e,this.bloom.kernel=e/this._hardwareScaleLevel}set bloomWeight(e){this._bloomWeight!==e&&(this.bloom.weight=e,this._bloomWeight=e)}get bloomWeight(){return this._bloomWeight}set bloomThreshold(e){this._bloomThreshold!==e&&(this.bloom.threshold=e,this._bloomThreshold=e)}get bloomThreshold(){return this._bloomThreshold}set bloomScale(e){this._bloomScale!==e&&(this._bloomScale=e,this._rebuildBloom(),this._buildPipeline())}get bloomScale(){return this._bloomScale}set bloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get bloomEnabled(){return this._bloomEnabled}_rebuildBloom(){const e=this.bloom;this.bloom=new JS(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(let t=0;tthis.sharpen),!0),this.depthOfField=new gE(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!0),this._hardwareScaleLevel=a.getHardwareScalingLevel(),this._resizeObserver=a.onResizeObservable.add((()=>{this._hardwareScaleLevel=a.getHardwareScalingLevel(),this.bloomKernel=this._bloomKernel})),this.bloom=new JS(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new iE("ChromaticAberration",a.getRenderWidth(),a.getRenderHeight(),1,null,Le.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new YS(a,this.ChromaticAberrationPostProcessId,(()=>this.chromaticAberration),!0),this.grain=new OE("Grain",1,null,Le.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new YS(a,this.GrainPostProcessId,(()=>this.grain),!0),this._imageProcessingConfigurationObserver=this._scene.imageProcessingConfiguration.onUpdateParameters.add((()=>{this.bloom._downscale._exposure=this._scene.imageProcessingConfiguration.exposure,this.imageProcessingEnabled!==this._scene.imageProcessingConfiguration.isEnabled&&(this._imageProcessingEnabled=this._scene.imageProcessingConfiguration.isEnabled,se.w1.SetImmediate((()=>{this._buildPipeline()})))})),this._buildPipeline()}getClassName(){return"DefaultRenderingPipeline"}prepare(){const e=this._buildAllowed;this._buildAllowed=!0,this._buildPipeline(),this._buildAllowed=e}_setAutoClearAndTextureSharing(e,t=!1){this._hasCleared?e.autoClear=!1:(e.autoClear=!0,this._scene.autoClear=!1,this._hasCleared=!0),t||(this._prevPrevPostProcess?e.shareOutputWith(this._prevPrevPostProcess):e.useOwnOutput(),this._prevPostProcess&&(this._prevPrevPostProcess=this._prevPostProcess),this._prevPostProcess=e)}_buildPipeline(){if(!this._buildAllowed)return;this._scene.autoClear=!0;const e=this._scene.getEngine();if(this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._prevPostProcess=null,this._prevPrevPostProcess=null,this._hasCleared=!1,this.depthOfFieldEnabled){if(this._cameras.length>1){for(const e of this._cameras){this._scene.enableDepthRenderer(e).useOnlyInActiveCamera=!0}this._depthOfFieldSceneObserver=this._scene.onAfterRenderTargetsRenderObservable.add((e=>{this._cameras.indexOf(e.activeCamera)>-1&&(this.depthOfField.depthTexture=e.enableDepthRenderer(e.activeCamera).getDepthMap())}))}else{this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);const e=this._scene.enableDepthRenderer(this._cameras[0]);this.depthOfField.depthTexture=e.getDepthMap()}this.depthOfField._isReady()||this.depthOfField._updateEffects(),this.addEffect(this.depthOfField),this._setAutoClearAndTextureSharing(this.depthOfField._effects[0],!0)}else this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);this.bloomEnabled&&(this.bloom._isReady()||this.bloom._updateEffects(),this.addEffect(this.bloom),this._setAutoClearAndTextureSharing(this.bloom._effects[0],!0)),this._imageProcessingEnabled&&(this.imageProcessing=new Ta("imageProcessing",1,null,Le.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new YS(e,this.ImageProcessingPostProcessId,(()=>this.imageProcessing),!0)),this._setAutoClearAndTextureSharing(this.imageProcessing)):this._scene.imageProcessingConfiguration.applyByPostProcess=!1,this._cameras&&0!==this._cameras.length||(this._scene.imageProcessingConfiguration.applyByPostProcess=!1),this.imageProcessing.getEffect()||this.imageProcessing._updateParameters()),this.sharpenEnabled&&(this.sharpen.isReady()||this.sharpen.updateEffect(),this.addEffect(this._sharpenEffect),this._setAutoClearAndTextureSharing(this.sharpen)),this.grainEnabled&&(this.grain.isReady()||this.grain.updateEffect(),this.addEffect(this._grainEffect),this._setAutoClearAndTextureSharing(this.grain)),this.chromaticAberrationEnabled&&(this.chromaticAberration.isReady()||this.chromaticAberration.updateEffect(),this.addEffect(this._chromaticAberrationEffect),this._setAutoClearAndTextureSharing(this.chromaticAberration)),this.fxaaEnabled&&(this.fxaa=new PE("fxaa",1,null,Le.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new YS(e,this.FxaaPostProcessId,(()=>this.fxaa),!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),(this._scene.activeCameras&&this._scene.activeCameras.length>1||this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera))&&(this._scene.autoClear=!0),this._activeCameraChangedObserver||(this._activeCameraChangedObserver=this._scene.onActiveCameraChanged.add((()=>{this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera)&&(this._scene.autoClear=!0)}))),this._activeCamerasChangedObserver||(this._activeCamerasChangedObserver=this._scene.onActiveCamerasChanged.add((()=>{this._scene.activeCameras&&this._scene.activeCameras.length>1&&(this._scene.autoClear=!0)}))),!this._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&p.Y.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"),this.onBuildObservable.notifyObservers(this)}_disposePostProcesses(e=!1){for(let t=0;tnew ox(e._name,e._name._hdr,t)),e,t,i)}}(0,oe.gn)([(0,E.qC)()],ox.prototype,"sharpenEnabled",null),(0,oe.gn)([(0,E.qC)()],ox.prototype,"bloomKernel",null),(0,oe.gn)([(0,E.qC)()],ox.prototype,"_bloomWeight",void 0),(0,oe.gn)([(0,E.qC)()],ox.prototype,"_bloomThreshold",void 0),(0,oe.gn)([(0,E.qC)()],ox.prototype,"_hdr",void 0),(0,oe.gn)([(0,E.qC)()],ox.prototype,"bloomWeight",null),(0,oe.gn)([(0,E.qC)()],ox.prototype,"bloomThreshold",null),(0,oe.gn)([(0,E.qC)()],ox.prototype,"bloomScale",null),(0,oe.gn)([(0,E.qC)()],ox.prototype,"bloomEnabled",null),(0,oe.gn)([(0,E.qC)()],ox.prototype,"depthOfFieldEnabled",null),(0,oe.gn)([(0,E.qC)()],ox.prototype,"depthOfFieldBlurLevel",null),(0,oe.gn)([(0,E.qC)()],ox.prototype,"fxaaEnabled",null),(0,oe.gn)([(0,E.qC)()],ox.prototype,"samples",null),(0,oe.gn)([(0,E.qC)()],ox.prototype,"imageProcessingEnabled",null),(0,oe.gn)([(0,E.qC)()],ox.prototype,"glowLayerEnabled",null),(0,oe.gn)([(0,E.qC)()],ox.prototype,"chromaticAberrationEnabled",null),(0,oe.gn)([(0,E.qC)()],ox.prototype,"grainEnabled",null),(0,l.H)("BABYLON.DefaultRenderingPipeline",ox);const ax="lensHighlightsPixelShader",lx="uniform sampler2D textureSampler; \nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\nvarying vec2 vUV;\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\nif (gain==-1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n}";Ht.v.ShadersStore[ax]=lx;const hx="depthOfFieldPixelShader",cx="uniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\nuniform float near;\nuniform float far;\nvarying vec2 vUV;\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion==0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\nfloat sampleScreen(inout vec4 color,in vec2 offset,in float weight) {\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\nreturn col;\n}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\nif (dof_enabled==false || coc<0.07) { coc=0.0; }\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\nfloat blur_amount=max(edge_blur_amount,coc);\nif (blur_amount==0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\ngl_FragColor=getBlurColor(blur_amount*1.7);\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n";Ht.v.ShadersStore[hx]=cx;class dx{constructor(){this.enabled=!1,this.name="ssao2",this.texturesRequired=[6,5]}}const ux="ssao2PixelShader",px="precision highp float;\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\nuniform float near;\nuniform float radius;\nuniform sampler2D depthSampler;\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform mat3 depthProjection;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=textureLod(randomSampler,vUV*randTextureTiles,0.0).rgb;\nfloat depth=textureLod(depthSampler,vUV,0.0).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=textureLod(normalSampler,vUV,0.0).rgb;\nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 vDepthFactor=depthProjection*vec3(1.0,1.0,depth);\nvec3 origin=vViewRay*vDepthFactor;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i1.0 || offset.y>1.0) {\ncontinue;\n}\nfloat sampleDepth=abs(textureLod(depthSampler,offset.xy,0.0).r);\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=step(EPSILON,difference)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BLUR\nuniform float outSize;\nuniform float soften;\nuniform float tolerance;\nuniform int samples;\n#ifndef BLUR_BYPASS\nuniform sampler2D depthSampler;\n#ifdef BLUR_LEGACY\n#define inline\nfloat blur13Bilateral(sampler2D image,vec2 uv,vec2 step) {\nfloat result=0.0;\nvec2 off1=vec2(1.411764705882353)*step;\nvec2 off2=vec2(3.2941176470588234)*step;\nvec2 off3=vec2(5.176470588235294)*step;\nfloat compareDepth=abs(textureLod(depthSampler,uv,0.0).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\nresult+=textureLod(image,uv,0.0).r*30.0;\nsampleDepth=abs(textureLod(depthSampler,uv+off1,0.0).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+= weight;\nresult+=textureLod(image,uv+off1,0.0).r*weight;\nsampleDepth=abs(textureLod(depthSampler,uv-off1,0.0).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+= weight;\nresult+=textureLod(image,uv-off1,0.0).r*weight;\nsampleDepth=abs(textureLod(depthSampler,uv+off2,0.0).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\nresult+=textureLod(image,uv+off2,0.0).r*weight;\nsampleDepth=abs(textureLod(depthSampler,uv-off2,0.0).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\nresult+=textureLod(image,uv-off2,0.0).r*weight;\nsampleDepth=abs(textureLod(depthSampler,uv+off3,0.0).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\nresult+=textureLod(image,uv+off3,0.0).r*weight;\nsampleDepth=abs(textureLod(depthSampler,uv-off3,0.0).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\nresult+=textureLod(image,uv-off3,0.0).r*weight;\nreturn result/weightSum;\n}\n#endif\n#endif\nvoid main()\n{\nfloat result=0.0;\n#ifdef BLUR_BYPASS\nresult=textureLod(textureSampler,vUV,0.0).r;\n#else\n#ifdef BLUR_H\nvec2 step=vec2(1.0/outSize,0.0);\n#else\nvec2 step=vec2(0.0,1.0/outSize);\n#endif\n#ifdef BLUR_LEGACY\nresult=blur13Bilateral(textureSampler,vUV,step);\n#else\nfloat compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);\nfloat weightSum=0.0;\nfor (int i=-samples; ithis._originalColorPostProcess),!0)),this.addEffect(new YS(t.getEngine(),this.SSAORenderEffect,(()=>this._ssaoPostProcess),!0)),this.addEffect(new YS(t.getEngine(),this.SSAOBlurHRenderEffect,(()=>this._blurHPostProcess),!0)),this.addEffect(new YS(t.getEngine(),this.SSAOBlurVRenderEffect,(()=>this._blurVPostProcess),!0)),this.addEffect(new YS(t.getEngine(),this.SSAOCombineRenderEffect,(()=>this._ssaoCombinePostProcess),!0)),t.postProcessRenderPipelineManager.addPipeline(this),n&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,n)}getClassName(){return"SSAO2RenderingPipeline"}dispose(e=!1){for(let t=0;t{if(!this._scene.activeCamera)return;const t=r?this._ssaoCombinePostProcess.width:this._ssaoCombinePostProcess.height,i=r?this._originalColorPostProcess.width:this._originalColorPostProcess.height;e.setFloat("outSize",t>0?t:i),e.setInt("samples",this.bilateralSamples),e.setFloat("soften",this.bilateralSoften),e.setFloat("tolerance",this.bilateralTolerance),this._geometryBufferRenderer?e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]):this._prePassRenderer&&e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)])},o.samples=this.textureSamples,o}_radicalInverse_VdC(e){return this._bits[0]=e,this._bits[0]=(this._bits[0]<<16|this._bits[0]>>16)>>>0,this._bits[0]=(1431655765&this._bits[0])<<1|(2863311530&this._bits[0])>>>1>>>0,this._bits[0]=(858993459&this._bits[0])<<2|(3435973836&this._bits[0])>>>2>>>0,this._bits[0]=(252645135&this._bits[0])<<4|(4042322160&this._bits[0])>>>4>>>0,this._bits[0]=(16711935&this._bits[0])<<8|(4278255360&this._bits[0])>>>8>>>0,2.3283064365386963e-10*this._bits[0]}_hammersley(e,t){return[e/t,this._radicalInverse_VdC(e)]}_hemisphereSample_uniform(e,t){const i=2*t*Math.PI,n=1-.85*e,s=Math.sqrt(1-n*n);return new o.P(Math.cos(i)*s,Math.sin(i)*s,n)}_generateHemisphere(){const e=this.samples,t=[];let i,n=0;for(;n{var t,i,n,s;if(this._scene.activeCamera){if(e.setArray3("sampleSphere",this._sampleSphere),e.setFloat("randTextureTiles",32),e.setFloat("samplesFactor",1/this.samples),e.setFloat("totalStrength",this.totalStrength),e.setFloat2("texelSize",1/this._ssaoPostProcess.width,1/this._ssaoPostProcess.height),e.setFloat("radius",this.radius),e.setFloat("maxZ",this.maxZ),e.setFloat("minZAspect",this.minZAspect),e.setFloat("base",this.base),e.setFloat("near",this._scene.activeCamera.minZ),this._scene.activeCamera.mode===ce.V.PERSPECTIVE_CAMERA)e.setMatrix3x3("depthProjection",mx.PERSPECTIVE_DEPTH_PROJECTION),e.setFloat("xViewport",Math.tan(this._scene.activeCamera.fov/2)*this._scene.getEngine().getAspectRatio(this._scene.activeCamera,!0)),e.setFloat("yViewport",Math.tan(this._scene.activeCamera.fov/2));else{const r=this._scene.getEngine().getRenderWidth()/2,o=this._scene.getEngine().getRenderHeight()/2,a=null!==(t=this._scene.activeCamera.orthoLeft)&&void 0!==t?t:-r,l=null!==(i=this._scene.activeCamera.orthoRight)&&void 0!==i?i:r,h=null!==(n=this._scene.activeCamera.orthoBottom)&&void 0!==n?n:-o,c=null!==(s=this._scene.activeCamera.orthoTop)&&void 0!==s?s:o;e.setMatrix3x3("depthProjection",mx.ORTHO_DEPTH_PROJECTION),e.setFloat("xViewport",.5*(l-a)),e.setFloat("yViewport",.5*(c-h))}e.setMatrix("projection",this._scene.getProjectionMatrix()),this._geometryBufferRenderer?(e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]),e.setTexture("normalSampler",this._geometryBufferRenderer.getGBuffer().textures[1])):this._prePassRenderer&&(e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]),e.setTexture("normalSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)])),e.setTexture("randomSampler",this._randomTexture)}},this._ssaoPostProcess.samples=this.textureSamples,this._forceGeometryBuffer||(this._ssaoPostProcess._prePassEffectConfiguration=new dx)}_createSSAOCombinePostProcess(e,t){this._ssaoCombinePostProcess=new Zt("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,Le.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t),this._ssaoCombinePostProcess.onApply=e=>{const t=this._scene.activeCamera.viewport;e.setVector4("viewport",o.jp.Vector4[0].copyFromFloats(t.x,t.y,t.width,t.height)),e.setTextureFromPostProcessOutput("originalColor",this._originalColorPostProcess)},this._ssaoCombinePostProcess.samples=this.textureSamples}_createRandomTexture(){this._randomTexture=new ma("SSAORandomTexture",128,this._scene,!1,Le.BILINEAR_SAMPLINGMODE),this._randomTexture.wrapU=Le.WRAP_ADDRESSMODE,this._randomTexture.wrapV=Le.WRAP_ADDRESSMODE;const e=this._randomTexture.getContext(),t=(e,t)=>Math.random()*(t-e)+e,i=o.P.Zero();for(let n=0;n<128;n++)for(let s=0;s<128;s++)i.x=t(0,1),i.y=t(0,1),i.z=0,i.normalize(),i.scaleInPlace(255),i.x=Math.floor(i.x),i.y=Math.floor(i.y),e.fillStyle="rgb("+i.x+", "+i.y+", "+i.z+")",e.fillRect(n,s,1,1);this._randomTexture.update(!1)}serialize(){const e=E.p4.Serialize(this);return e.customType="SSAO2RenderingPipeline",e}static Parse(e,t,i){return E.p4.Parse((()=>new mx(e._name,t,e._ratio,void 0,e._forceGeometryBuffer,e._textureType)),e,t,i)}}mx.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1],mx.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1],(0,oe.gn)([(0,E.qC)()],mx.prototype,"totalStrength",void 0),(0,oe.gn)([(0,E.qC)()],mx.prototype,"maxZ",void 0),(0,oe.gn)([(0,E.qC)()],mx.prototype,"minZAspect",void 0),(0,oe.gn)([(0,E.qC)("epsilon")],mx.prototype,"_epsilon",void 0),(0,oe.gn)([(0,E.qC)("samples")],mx.prototype,"_samples",void 0),(0,oe.gn)([(0,E.qC)("textureSamples")],mx.prototype,"_textureSamples",void 0),(0,oe.gn)([(0,E.qC)()],mx.prototype,"_forceGeometryBuffer",void 0),(0,oe.gn)([(0,E.qC)()],mx.prototype,"_ratio",void 0),(0,oe.gn)([(0,E.qC)()],mx.prototype,"_textureType",void 0),(0,oe.gn)([(0,E.qC)()],mx.prototype,"radius",void 0),(0,oe.gn)([(0,E.qC)()],mx.prototype,"base",void 0),(0,oe.gn)([(0,E.qC)("bypassBlur")],mx.prototype,"_bypassBlur",void 0),(0,oe.gn)([(0,E.qC)("expensiveBlur")],mx.prototype,"_expensiveBlur",void 0),(0,oe.gn)([(0,E.qC)()],mx.prototype,"bilateralSamples",void 0),(0,oe.gn)([(0,E.qC)()],mx.prototype,"bilateralSoften",void 0),(0,oe.gn)([(0,E.qC)()],mx.prototype,"bilateralTolerance",void 0),(0,l.H)("BABYLON.SSAO2RenderingPipeline",mx);const gx="ssaoPixelShader",vx="uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; ithis._originalColorPostProcess),!0)),this.addEffect(new YS(t.getEngine(),this.SSAORenderEffect,(()=>this._ssaoPostProcess),!0)),this.addEffect(new YS(t.getEngine(),this.SSAOBlurHRenderEffect,(()=>this._blurHPostProcess),!0)),this.addEffect(new YS(t.getEngine(),this.SSAOBlurVRenderEffect,(()=>this._blurVPostProcess),!0)),this.addEffect(new YS(t.getEngine(),this.SSAOCombineRenderEffect,(()=>this._ssaoCombinePostProcess),!0)),t.postProcessRenderPipelineManager.addPipeline(this),n&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,n)}_attachCameras(e,t){super._attachCameras(e,t);for(const i of this._cameras)this._scene.enableDepthRenderer(i).getDepthMap()}getClassName(){return"SSAORenderingPipeline"}dispose(e=!1){for(let t=0;t{const e=this._blurHPostProcess.width/this._scene.getEngine().getRenderWidth();this._blurHPostProcess.kernel=16*e})),this._blurVPostProcess.onActivateObservable.add((()=>{const e=this._blurVPostProcess.height/this._scene.getEngine().getRenderHeight();this._blurVPostProcess.kernel=16*e}))}_rebuild(){this._firstUpdate=!0,super._rebuild()}_createSSAOPostProcess(e){const t=[.5381,.1856,-.4319,.1379,.2486,.443,.3371,.5679,-.0057,-.6999,-.0451,-.0019,.0689,-.1598,-.8547,.056,.0069,-.1843,-.0146,.1402,.0762,.01,-.1924,-.0344,-.3577,-.5301,-.4358,-.3169,.1063,.0158,.0103,-.5869,.0046,-.0897,-.494,.3287,.7119,-.0154,-.0918,-.0533,.0596,-.5411,.0352,-.0631,.546,-.4776,.2847,-.0271];this._ssaoPostProcess=new Zt("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,Le.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,"#define SAMPLES 16\n#define SSAO"),this._ssaoPostProcess.externalTextureSamplerBinding=!0,this._ssaoPostProcess.onApply=e=>{this._firstUpdate&&(e.setArray3("sampleSphere",t),e.setFloat("samplesFactor",.0625),e.setFloat("randTextureTiles",4)),e.setFloat("totalStrength",this.totalStrength),e.setFloat("radius",this.radius),e.setFloat("area",this.area),e.setFloat("fallOff",this.fallOff),e.setFloat("base",this.base),e.setTexture("textureSampler",this._scene.enableDepthRenderer(this._scene.activeCamera).getDepthMap()),e.setTexture("randomSampler",this._randomTexture)}}_createSSAOCombinePostProcess(e){this._ssaoCombinePostProcess=new Zt("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,Le.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=e=>{e.setVector4("viewport",o.jp.Vector4[0].copyFromFloats(0,0,1,1)),e.setTextureFromPostProcess("originalColor",this._originalColorPostProcess)}}_createRandomTexture(){this._randomTexture=new ma("SSAORandomTexture",512,this._scene,!1,Le.TRILINEAR_SAMPLINGMODE),this._randomTexture.wrapU=Le.WRAP_ADDRESSMODE,this._randomTexture.wrapV=Le.WRAP_ADDRESSMODE;const e=this._randomTexture.getContext(),t=(e,t)=>Math.random()*(t-e)+e,i=o.P.Zero();for(let n=0;n<512;n++)for(let s=0;s<512;s++)i.x=Math.floor(255*Math.max(0,t(-1,1))),i.y=Math.floor(255*Math.max(0,t(-1,1))),i.z=Math.floor(255*Math.max(0,t(-1,1))),e.fillStyle="rgb("+i.x+", "+i.y+", "+i.z+")",e.fillRect(n,s,1,1);this._randomTexture.update(!1)}}(0,oe.gn)([(0,E.qC)()],Tx.prototype,"totalStrength",void 0),(0,oe.gn)([(0,E.qC)()],Tx.prototype,"radius",void 0),(0,oe.gn)([(0,E.qC)()],Tx.prototype,"area",void 0),(0,oe.gn)([(0,E.qC)()],Tx.prototype,"fallOff",void 0),(0,oe.gn)([(0,E.qC)()],Tx.prototype,"base",void 0);class Sx{constructor(){this.enabled=!1,this.name="screenSpaceReflections",this.texturesRequired=[6,3,1]}}const Ex="screenSpaceReflectionPixelShader",xx="uniform sampler2D textureSampler;\n#ifdef SSR_SUPPORTED\nuniform sampler2D reflectivitySampler;\nuniform sampler2D normalSampler;\nuniform sampler2D positionSampler;\n#endif\nuniform mat4 view;\nuniform mat4 projection;\nuniform float stepSize;\nuniform float strength;\nuniform float threshold;\nuniform float roughnessFactor;\nuniform float reflectionSpecularFalloffExponent;\nvarying vec2 vUV;\n#ifdef SSR_SUPPORTED\nstruct ReflectionInfo {\nvec3 color;\nvec4 coords;\n};\n/**\n* According to specular,see https:\n*/\nvec3 fresnelSchlick(float cosTheta,vec3 F0)\n{\nreturn F0+(1.0-F0)*pow(1.0-cosTheta,5.0);\n}\n/**\n* Once the pixel's coordinates has been found,let's adjust (smooth) a little bit\n* by sampling multiple reflection pixels.\n*/\nReflectionInfo smoothReflectionInfo(vec3 dir,vec3 hitCoord)\n{\nReflectionInfo info;\ninfo.color=vec3(0.0);\nvec4 projectedCoord;\nfloat sampledDepth;\nfor(int i=0; i0.0)\nhitCoord-=dir;\nelse\nhitCoord+=dir;\ninfo.color+=texture2D(textureSampler,projectedCoord.xy).rgb;\n}\nprojectedCoord=projection*vec4(hitCoord,1.0);\nprojectedCoord.xy/=projectedCoord.w;\nprojectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);\ninfo.coords=vec4(projectedCoord.xy,sampledDepth,1.0);\ninfo.color+=texture2D(textureSampler,projectedCoord.xy).rgb;\ninfo.color/=float(SMOOTH_STEPS+1);\nreturn info;\n}\n/**\n* Tests the given world position (hitCoord) according to the given reflection vector (dir)\n* until it finds a collision (means that depth is enough close to say \"it's the pixel to sample!\").\n*/\nReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord)\n{\nReflectionInfo info;\nvec4 projectedCoord;\nfloat sampledDepth;\ndir*=stepSize;\nfor(int i=0; i{const i=this._geometryBufferRenderer,n=this._prePassRenderer;if(!n&&!i)return;if(i){const t=i.getTextureIndex(XE.POSITION_TEXTURE_TYPE),n=i.getTextureIndex(XE.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",i.getGBuffer().textures[1]),e.setTexture("positionSampler",i.getGBuffer().textures[t]),e.setTexture("reflectivitySampler",i.getGBuffer().textures[n])}else if(n){const t=n.getIndex(1),i=n.getIndex(3),s=n.getIndex(6);e.setTexture("normalSampler",n.getRenderTarget().textures[s]),e.setTexture("positionSampler",n.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",n.getRenderTarget().textures[i])}const s=t.activeCamera;if(!s)return;const r=s.getViewMatrix(!0),o=s.getProjectionMatrix(!0);e.setMatrix("projection",o),e.setMatrix("view",r),e.setFloat("threshold",this.threshold),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("roughnessFactor",this.roughnessFactor)},this._isSceneRightHanded=t.useRightHandedSystem}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get reflectionSamples(){return this._reflectionSamples}set reflectionSamples(e){e!==this._reflectionSamples&&(this._reflectionSamples=e,this._updateEffectDefines())}get smoothSteps(){return this._smoothSteps}set smoothSteps(e){e!==this._smoothSteps&&(this._smoothSteps=e,this._updateEffectDefines())}_updateEffectDefines(){const e=[];(this._geometryBufferRenderer||this._prePassRenderer)&&e.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&e.push("#define ENABLE_SMOOTH_REFLECTIONS"),this._isSceneRightHanded&&e.push("#define RIGHT_HANDED_SCENE"),e.push("#define REFLECTION_SAMPLES "+(this._reflectionSamples>>0)),e.push("#define SMOOTH_STEPS "+(this._smoothSteps>>0)),this.updateEffect(e.join("\n"))}static _Parse(e,t,i,n){return E.p4.Parse((()=>new bx(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,n)}}(0,oe.gn)([(0,E.qC)()],bx.prototype,"threshold",void 0),(0,oe.gn)([(0,E.qC)()],bx.prototype,"strength",void 0),(0,oe.gn)([(0,E.qC)()],bx.prototype,"reflectionSpecularFalloffExponent",void 0),(0,oe.gn)([(0,E.qC)()],bx.prototype,"step",void 0),(0,oe.gn)([(0,E.qC)()],bx.prototype,"roughnessFactor",void 0),(0,oe.gn)([(0,E.qC)()],bx.prototype,"enableSmoothReflections",null),(0,oe.gn)([(0,E.qC)()],bx.prototype,"reflectionSamples",null),(0,oe.gn)([(0,E.qC)()],bx.prototype,"smoothSteps",null),(0,l.H)("BABYLON.ScreenSpaceReflectionPostProcess",bx);const Cx="standardPixelShader",yx="uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminanceshadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\n#include\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\n#ifndef AUTO_EXPOSURE\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\n#endif\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n";Ht.v.ShadersStore[Cx]=yx;class Ax extends nx{get exposure(){return this._fixedExposure}set exposure(e){this._fixedExposure=e,this._currentExposure=e}get hdrAutoExposure(){return this._hdrAutoExposure}set hdrAutoExposure(e){if(this._hdrAutoExposure=e,this.hdrPostProcess){const t=["#define HDR"];e&&t.push("#define AUTO_EXPOSURE"),this.hdrPostProcess.updateEffect(t.join("\n"))}}get motionStrength(){return this._motionStrength}set motionStrength(e){this._motionStrength=e,this._isObjectBasedMotionBlur&&this.motionBlurPostProcess&&(this.motionBlurPostProcess.motionStrength=e)}get objectBasedMotionBlur(){return this._isObjectBasedMotionBlur}set objectBasedMotionBlur(e){const t=this._isObjectBasedMotionBlur!==e;this._isObjectBasedMotionBlur=e,t&&this._buildPipeline()}get BloomEnabled(){return this._bloomEnabled}set BloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get DepthOfFieldEnabled(){return this._depthOfFieldEnabled}set DepthOfFieldEnabled(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())}get LensFlareEnabled(){return this._lensFlareEnabled}set LensFlareEnabled(e){this._lensFlareEnabled!==e&&(this._lensFlareEnabled=e,this._buildPipeline())}get HDREnabled(){return this._hdrEnabled}set HDREnabled(e){this._hdrEnabled!==e&&(this._hdrEnabled=e,this._buildPipeline())}get VLSEnabled(){return this._vlsEnabled}set VLSEnabled(e){if(this._vlsEnabled!==e){if(e){if(!this._scene.enableGeometryBufferRenderer())return void p.Y.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline")}this._vlsEnabled=e,this._buildPipeline()}}get MotionBlurEnabled(){return this._motionBlurEnabled}set MotionBlurEnabled(e){this._motionBlurEnabled!==e&&(this._motionBlurEnabled=e,this._buildPipeline())}get fxaaEnabled(){return this._fxaaEnabled}set fxaaEnabled(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())}get screenSpaceReflectionsEnabled(){return this._screenSpaceReflectionsEnabled}set screenSpaceReflectionsEnabled(e){this._screenSpaceReflectionsEnabled!==e&&(this._screenSpaceReflectionsEnabled=e,this._buildPipeline())}get volumetricLightStepsCount(){return this._volumetricLightStepsCount}set volumetricLightStepsCount(e){this.volumetricLightPostProcess&&this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS "+e.toFixed(1)),this._volumetricLightStepsCount=e}get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this.motionBlurPostProcess&&(this._isObjectBasedMotionBlur?this.motionBlurPostProcess.motionBlurSamples=e:this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+e.toFixed(1))),this._motionBlurSamples=e}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}constructor(e,t,i,n=null,s){super(t.getEngine(),e),this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.blurHPostProcesses=[],this.blurVPostProcesses=[],this.textureAdderPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.luminancePostProcess=null,this.luminanceDownSamplePostProcesses=[],this.hdrPostProcess=null,this.textureAdderFinalPostProcess=null,this.lensFlareFinalPostProcess=null,this.hdrFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.motionBlurPostProcess=null,this.depthOfFieldPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.brightThreshold=1,this.blurWidth=512,this.horizontalBlur=!1,this.lensTexture=null,this.volumetricLightCoefficient=.2,this.volumetricLightPower=4,this.volumetricLightBlurScale=64,this.sourceLight=null,this.hdrMinimumLuminance=1,this.hdrDecreaseRate=.5,this.hdrIncreaseRate=.5,this.lensColorTexture=null,this.lensFlareStrength=20,this.lensFlareGhostDispersal=1.4,this.lensFlareHaloWidth=.7,this.lensFlareDistortionStrength=16,this.lensFlareBlurWidth=512,this.lensStarTexture=null,this.lensFlareDirtTexture=null,this.depthOfFieldDistance=10,this.depthOfFieldBlurWidth=64,this.animations=[],this._currentDepthOfFieldSource=null,this._fixedExposure=1,this._currentExposure=1,this._hdrAutoExposure=!1,this._hdrCurrentLuminance=1,this._motionStrength=1,this._isObjectBasedMotionBlur=!1,this._camerasToBeAttached=[],this._bloomEnabled=!1,this._depthOfFieldEnabled=!1,this._vlsEnabled=!1,this._lensFlareEnabled=!1,this._hdrEnabled=!1,this._motionBlurEnabled=!1,this._fxaaEnabled=!1,this._screenSpaceReflectionsEnabled=!1,this._motionBlurSamples=64,this._volumetricLightStepsCount=50,this._samples=1,this._cameras=s||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._basePostProcess=n,this._ratio=i,this._floatTextureType=t.getEngine().getCaps().textureFloatRender?1:2,t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline()}_buildPipeline(){const e=this._ratio,t=this._scene;this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._screenSpaceReflectionsEnabled&&(this.screenSpaceReflectionPostProcess=new bx("HDRPass",t,e,null,Le.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add((()=>{this._currentDepthOfFieldSource=this.screenSpaceReflectionPostProcess})),this.addEffect(new YS(t.getEngine(),"HDRScreenSpaceReflections",(()=>this.screenSpaceReflectionPostProcess),!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new Zt("HDRPass","standard",[],[],e,null,Le.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",this._floatTextureType),this.originalPostProcess.autoClear=!this.screenSpaceReflectionPostProcess,this.originalPostProcess.onApplyObservable.add((()=>{this._currentDepthOfFieldSource=this.originalPostProcess})),this.addEffect(new YS(t.getEngine(),"HDRPassPostProcess",(()=>this.originalPostProcess),!0)),this._bloomEnabled&&(this._createDownSampleX4PostProcess(t,e/4),this._createBrightPassPostProcess(t,e/4),this._createBlurPostProcesses(t,e/4,1),this._createTextureAdderPostProcess(t,e),this.textureAdderFinalPostProcess=new Zt("HDRDepthOfFieldSource","standard",[],[],e,null,Le.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new YS(t.getEngine(),"HDRBaseDepthOfFieldSource",(()=>this.textureAdderFinalPostProcess),!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(t,e),this.volumetricLightFinalPostProcess=new Zt("HDRVLSFinal","standard",[],[],e,null,Le.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new YS(t.getEngine(),"HDRVLSFinal",(()=>this.volumetricLightFinalPostProcess),!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(t,e),this.lensFlareFinalPostProcess=new Zt("HDRPostLensFlareDepthOfFieldSource","standard",[],[],e,null,Le.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new YS(t.getEngine(),"HDRPostLensFlareDepthOfFieldSource",(()=>this.lensFlareFinalPostProcess),!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(t,this._floatTextureType),this._createHdrPostProcess(t,e),this.hdrFinalPostProcess=new Zt("HDRPostHDReDepthOfFieldSource","standard",[],[],e,null,Le.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new YS(t.getEngine(),"HDRPostHDReDepthOfFieldSource",(()=>this.hdrFinalPostProcess),!0))),this._depthOfFieldEnabled&&(this._createBlurPostProcesses(t,e/2,3,"depthOfFieldBlurWidth"),this._createDepthOfFieldPostProcess(t,e)),this._motionBlurEnabled&&this._createMotionBlurPostProcess(t,e),this._fxaaEnabled&&(this.fxaaPostProcess=new PE("fxaa",1,null,Le.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,0),this.addEffect(new YS(t.getEngine(),"HDRFxaa",(()=>this.fxaaPostProcess),!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&p.Y.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")}_createDownSampleX4PostProcess(e,t){const i=new Array(32);this.downSampleX4PostProcess=new Zt("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=e=>{let t=0;const n=this.downSampleX4PostProcess.width,s=this.downSampleX4PostProcess.height;for(let r=-2;r<2;r++)for(let e=-2;e<2;e++)i[t]=(r+.5)*(1/n),i[t+1]=(e+.5)*(1/s),t+=2;e.setArray2("dsOffsets",i)},this.addEffect(new YS(e.getEngine(),"HDRDownSampleX4",(()=>this.downSampleX4PostProcess),!0))}_createBrightPassPostProcess(e,t){const i=new Array(8);this.brightPassPostProcess=new Zt("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=e=>{const t=1/this.brightPassPostProcess.width,n=1/this.brightPassPostProcess.height;i[0]=-.5*t,i[1]=.5*n,i[2]=.5*t,i[3]=.5*n,i[4]=-.5*t,i[5]=-.5*n,i[6]=.5*t,i[7]=-.5*n,e.setArray2("dsOffsets",i),e.setFloat("brightThreshold",this.brightThreshold)},this.addEffect(new YS(e.getEngine(),"HDRBrightPass",(()=>this.brightPassPostProcess),!0))}_createBlurPostProcesses(e,t,i,n="blurWidth"){const s=e.getEngine(),r=new bp("HDRBlurH_"+i,new o.FM(1,0),this[n],t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),a=new bp("HDRBlurV_"+i,new o.FM(0,1),this[n],t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);r.onActivateObservable.add((()=>{const e=r.width/s.getRenderWidth();r.kernel=this[n]*e})),a.onActivateObservable.add((()=>{const e=a.height/s.getRenderHeight();a.kernel=this.horizontalBlur?64*e:this[n]*e})),this.addEffect(new YS(e.getEngine(),"HDRBlurH"+i,(()=>r),!0)),this.addEffect(new YS(e.getEngine(),"HDRBlurV"+i,(()=>a),!0)),this.blurHPostProcesses.push(r),this.blurVPostProcesses.push(a)}_createTextureAdderPostProcess(e,t){this.textureAdderPostProcess=new Zt("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define TEXTURE_ADDER",this._floatTextureType),this.textureAdderPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._vlsEnabled?this._currentDepthOfFieldSource:this.originalPostProcess),e.setTexture("lensSampler",this.lensTexture),e.setFloat("exposure",this._currentExposure),this._currentDepthOfFieldSource=this.textureAdderFinalPostProcess},this.addEffect(new YS(e.getEngine(),"HDRTextureAdder",(()=>this.textureAdderPostProcess),!0))}_createVolumetricLightPostProcess(e,t){const i=e.enableGeometryBufferRenderer();i.enablePosition=!0;const n=i.getGBuffer();this.volumetricLightPostProcess=new Zt("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLS\n#define NB_STEPS "+this._volumetricLightStepsCount.toFixed(1));const s=o.FM.Zero();this.volumetricLightPostProcess.onApply=e=>{if(this.sourceLight&&this.sourceLight.getShadowGenerator()&&this._scene.activeCamera){const t=this.sourceLight.getShadowGenerator();e.setTexture("shadowMapSampler",t.getShadowMap()),e.setTexture("positionSampler",n.textures[2]),e.setColor3("sunColor",this.sourceLight.diffuse),e.setVector3("sunDirection",this.sourceLight.getShadowDirection()),e.setVector3("cameraPosition",this._scene.activeCamera.globalPosition),e.setMatrix("shadowViewProjection",t.getTransformMatrix()),e.setFloat("scatteringCoefficient",this.volumetricLightCoefficient),e.setFloat("scatteringPower",this.volumetricLightPower),s.x=this.sourceLight.getDepthMinZ(this._scene.activeCamera),s.y=this.sourceLight.getDepthMaxZ(this._scene.activeCamera),e.setVector2("depthValues",s)}},this.addEffect(new YS(e.getEngine(),"HDRVLS",(()=>this.volumetricLightPostProcess),!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new Zt("HDRVLSMerge","standard",[],["originalSampler"],t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLSMERGE"),this.volumetricLightMergePostProces.onApply=e=>{e.setTextureFromPostProcess("originalSampler",this._bloomEnabled?this.textureAdderFinalPostProcess:this.originalPostProcess),this._currentDepthOfFieldSource=this.volumetricLightFinalPostProcess},this.addEffect(new YS(e.getEngine(),"HDRVLSMerge",(()=>this.volumetricLightMergePostProces),!0))}_createLuminancePostProcesses(e,t){let i=Math.pow(3,Ax.LuminanceSteps);this.luminancePostProcess=new Zt("HDRLuminance","standard",["lumOffsets"],[],{width:i,height:i},null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",t);const n=[];this.luminancePostProcess.onApply=e=>{const t=1/this.luminancePostProcess.width,i=1/this.luminancePostProcess.height;n[0]=-.5*t,n[1]=.5*i,n[2]=.5*t,n[3]=.5*i,n[4]=-.5*t,n[5]=-.5*i,n[6]=.5*t,n[7]=-.5*i,e.setArray2("lumOffsets",n)},this.addEffect(new YS(e.getEngine(),"HDRLuminance",(()=>this.luminancePostProcess),!0));for(let r=Ax.LuminanceSteps-1;r>=0;r--){i=Math.pow(3,r);let n="#define LUMINANCE_DOWN_SAMPLE\n";0===r&&(n+="#define FINAL_DOWN_SAMPLER");const s=new Zt("HDRLuminanceDownSample"+r,"standard",["dsOffsets","halfDestPixelSize"],[],{width:i,height:i},null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,n,t);this.luminanceDownSamplePostProcesses.push(s)}let s=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach(((t,i)=>{const n=new Array(18);t.onApply=e=>{if(!s)return;let r=0;for(let t=-1;t<2;t++)for(let e=-1;e<2;e++)n[r]=t/s.width,n[r+1]=e/s.height,r+=2;e.setArray2("dsOffsets",n),e.setFloat("halfDestPixelSize",.5/s.width),s=i===this.luminanceDownSamplePostProcesses.length-1?this.luminancePostProcess:t},i===this.luminanceDownSamplePostProcesses.length-1&&(t.onAfterRender=()=>{const t=e.getEngine().readPixels(0,0,1,1),i=new o.Lt(1/16581375,1/65025,1/255,1);t.then((e=>{const t=new Uint8Array(e.buffer);this._hdrCurrentLuminance=(t[0]*i.x+t[1]*i.y+t[2]*i.z+t[3]*i.w)/100}))}),this.addEffect(new YS(e.getEngine(),"HDRLuminanceDownSample"+i,(()=>t),!0))}))}_createHdrPostProcess(e,t){const i=["#define HDR"];this._hdrAutoExposure&&i.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new Zt("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,i.join("\n"),0);let n=1,s=0,r=0;this.hdrPostProcess.onApply=t=>{if(t.setTextureFromPostProcess("textureAdderSampler",this._currentDepthOfFieldSource),s+=e.getEngine().getDeltaTime(),n<0)n=this._hdrCurrentLuminance;else{const e=(r-s)/1e3;this._hdrCurrentLuminancen-this.hdrIncreaseRate*e?n-=this.hdrIncreaseRate*e:n=this._hdrCurrentLuminance}this.hdrAutoExposure?this._currentExposure=this._fixedExposure/n:(n=S.R.Clamp(n,this.hdrMinimumLuminance,1e20),t.setFloat("averageLuminance",n)),r=s,this._currentDepthOfFieldSource=this.hdrFinalPostProcess},this.addEffect(new YS(e.getEngine(),"HDR",(()=>this.hdrPostProcess),!0))}_createLensFlarePostProcess(e,t){this.lensFlarePostProcess=new Zt("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",0),this.addEffect(new YS(e.getEngine(),"HDRLensFlare",(()=>this.lensFlarePostProcess),!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new Zt("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",0),this.addEffect(new YS(e.getEngine(),"HDRLensFlareCompose",(()=>this.lensFlareComposePostProcess),!0));const i=new o.FM(0,0);this.lensFlarePostProcess.externalTextureSamplerBinding=!0,this.lensFlarePostProcess.onApply=e=>{e.setTextureFromPostProcess("textureSampler",this._bloomEnabled?this.blurHPostProcesses[0]:this.originalPostProcess),e.setTexture("lensColorSampler",this.lensColorTexture),e.setFloat("strength",this.lensFlareStrength),e.setFloat("ghostDispersal",this.lensFlareGhostDispersal),e.setFloat("haloWidth",this.lensFlareHaloWidth),i.x=this.lensFlarePostProcess.width,i.y=this.lensFlarePostProcess.height,e.setVector2("resolution",i),e.setFloat("distortionStrength",this.lensFlareDistortionStrength)};const n=o.y3.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),s=o.y3.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=e=>{if(!this._scene.activeCamera)return;e.setTextureFromPostProcess("otherSampler",this.lensFlarePostProcess),e.setTexture("lensDirtSampler",this.lensFlareDirtTexture),e.setTexture("lensStarSampler",this.lensStarTexture);const t=this._scene.activeCamera.getViewMatrix().getRow(0),i=this._scene.activeCamera.getViewMatrix().getRow(2);let r=o.P.Dot(t.toVector3(),new o.P(1,0,0))+o.P.Dot(i.toVector3(),new o.P(0,0,1));r*=4;const a=o.y3.FromValues(.5*Math.cos(r),-Math.sin(r),0,0,Math.sin(r),.5*Math.cos(r),0,0,0,0,1,0,0,0,0,1),l=s.multiply(a).multiply(n);e.setMatrix("lensStarMatrix",l),this._currentDepthOfFieldSource=this.lensFlareFinalPostProcess}}_createDepthOfFieldPostProcess(e,t){this.depthOfFieldPostProcess=new Zt("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DEPTH_OF_FIELD",0),this.depthOfFieldPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._currentDepthOfFieldSource),e.setTexture("depthSampler",this._getDepthTexture()),e.setFloat("distance",this.depthOfFieldDistance)},this.addEffect(new YS(e.getEngine(),"HDRDepthOfField",(()=>this.depthOfFieldPostProcess),!0))}_createMotionBlurPostProcess(e,t){if(this._isObjectBasedMotionBlur){const i=new $E("HDRMotionBlur",e,t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,0);i.motionStrength=this.motionStrength,i.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=i}else{this.motionBlurPostProcess=new Zt("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+this.motionBlurSamples.toFixed(1),0);let i=0,n=o.y3.Identity();const s=o.y3.Identity();let r=o.y3.Identity();const a=o.FM.Zero();this.motionBlurPostProcess.onApply=t=>{r=e.getProjectionMatrix().multiply(e.getViewMatrix()),r.invertToRef(s),t.setMatrix("inverseViewProjection",s),t.setMatrix("prevViewProjection",n),n=r,a.x=this.motionBlurPostProcess.width,a.y=this.motionBlurPostProcess.height,t.setVector2("screenSize",a),i=e.getEngine().getFps()/60,t.setFloat("motionScale",i),t.setFloat("motionStrength",this.motionStrength),t.setTexture("depthSampler",this._getDepthTexture())}}this.addEffect(new YS(e.getEngine(),"HDRMotionBlur",(()=>this.motionBlurPostProcess),!0))}_getDepthTexture(){if(this._scene.getEngine().getCaps().drawBuffersExtension){return this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0]}return this._scene.enableDepthRenderer().getDepthMap()}_disposePostProcesses(){for(let e=0;enew Ax(e._name,t,e._ratio)),e,t,i);return e.sourceLightId&&(n.sourceLight=t.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&E.p4.Parse((()=>n.screenSpaceReflectionPostProcess),e.screenSpaceReflectionPostProcess,t,i),n}}Ax.LuminanceSteps=6,(0,oe.gn)([(0,E.qC)()],Ax.prototype,"brightThreshold",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"blurWidth",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"horizontalBlur",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"exposure",null),(0,oe.gn)([(0,E.oU)("lensTexture")],Ax.prototype,"lensTexture",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"volumetricLightCoefficient",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"volumetricLightPower",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"volumetricLightBlurScale",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"hdrMinimumLuminance",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"hdrDecreaseRate",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"hdrIncreaseRate",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"hdrAutoExposure",null),(0,oe.gn)([(0,E.oU)("lensColorTexture")],Ax.prototype,"lensColorTexture",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"lensFlareStrength",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"lensFlareGhostDispersal",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"lensFlareHaloWidth",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"lensFlareDistortionStrength",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"lensFlareBlurWidth",void 0),(0,oe.gn)([(0,E.oU)("lensStarTexture")],Ax.prototype,"lensStarTexture",void 0),(0,oe.gn)([(0,E.oU)("lensFlareDirtTexture")],Ax.prototype,"lensFlareDirtTexture",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"depthOfFieldDistance",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"depthOfFieldBlurWidth",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"motionStrength",null),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"objectBasedMotionBlur",null),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"_ratio",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"BloomEnabled",null),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"DepthOfFieldEnabled",null),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"LensFlareEnabled",null),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"HDREnabled",null),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"VLSEnabled",null),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"MotionBlurEnabled",null),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"fxaaEnabled",null),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"screenSpaceReflectionsEnabled",null),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"volumetricLightStepsCount",null),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"motionBlurSamples",null),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"samples",null),(0,l.H)("BABYLON.StandardRenderingPipeline",Ax);class Rx{constructor(){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[6,3,5]}}const Px="screenSpaceRayTrace",Ix="float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); }\n/**\nparam csOrigin Camera-space ray origin,which must be \nwithin the view volume and must have z>0.01 and project within the valid screen rectangle\nparam csDirection Unit length camera-space ray direction\nparam projectToPixelMatrix A projection matrix that maps to **pixel** coordinates \n(**not** [-1,+1] normalized device coordinates).\nparam csZBuffer The camera-space Z buffer\nparam csZBufferSize Dimensions of csZBuffer\nparam csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer\nparam nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value\nfor clipping rays headed towards the camera\nparam stride Step in horizontal or vertical pixels between samples. This is a float\nbecause integer math is slow on GPUs,but should be set to an integer>=1\nparam jitterFraction Number between 0 and 1 for how far to bump the ray in stride units\nto conceal banding artifacts,plus the stride ray offset.\nparam maxSteps Maximum number of iterations. Higher gives better images but may be slow\nparam maxRayTraceDistance Maximum camera-space distance to trace before returning a miss\nparam selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions.\n1 is a reasonable value,depending on the scene you may need to set this value to 2\nparam hitPixel Pixel coordinates of the first intersection with the scene\nparam numIterations number of iterations performed\nparam csHitPoint Camera space location of the ray hit\n*/\n#define inline\nbool traceScreenSpaceRay1(\nvec3 csOrigin,\nvec3 csDirection,\nmat4 projectToPixelMatrix,\nsampler2D csZBuffer,\nvec2 csZBufferSize,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nsampler2D csZBackBuffer,\nfloat csZBackSizeFactor,\n#endif\nfloat csZThickness,\nfloat nearPlaneZ,\nfloat stride,\nfloat jitterFraction,\nfloat maxSteps,\nfloat maxRayTraceDistance,\nfloat selfCollisionNumSkip,\nout vec2 startPixel,\nout vec2 hitPixel,\nout vec3 csHitPoint,\nout float numIterations\n#ifdef SSRAYTRACE_DEBUG\n,out vec3 debugColor\n#endif\n)\n{\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance;\n#else\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)yMax) || (P1.yyMax) ? yMax : yMin))/(P1.y-P0.y);\n}\nif ((P1.x>xMax) || (P1.xxMax) ? xMax : xMin))/(P1.x-P0.x));\n}\nP1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha);\n#endif\nP1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);\nvec2 delta=P1-P0;\nbool permute=false;\nif (abs(delta.x)rayZMax) { \nfloat t=rayZMin; rayZMin=rayZMax; rayZMax=t;\n}\nsceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r;\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;\nhit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax);\n#else\nhit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax);\n#endif\n#else\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;\nhit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0);\n#else\nhit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax);\n#endif\n#endif\n}\npqk-=dPQK;\nstepCount-=1.0;\nif (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {\nhit=false;\n}\n#ifdef SSRAYTRACE_ENABLE_REFINEMENT\nif (stride>1.0 && hit) {\npqk-=dPQK;\nstepCount-=1.0;\nfloat invStride=1.0/stride;\ndPQK*=invStride;\nfloat refinementStepCount=0.0;\nprevZMaxEstimate=pqk.z/pqk.w;\nrayZMax=prevZMaxEstimate;\nsceneZMax=rayZMax+1e7;\nfor (;\nrefinementStepCount<=1.0 ||\n(refinementStepCount<=stride*1.4) &&\n(rayZMaxend) {\ndebugColor=vec3(0,0,1);\n} else if ((stepCount+1.0)>=maxSteps) {\ndebugColor=vec3(1,0,0);\n} else if (sceneZMax==0.0) {\ndebugColor=vec3(1,1,0);\n} else {\ndebugColor=vec3(0,stepCount/maxSteps,0);\n}\n#endif\nreturn hit;\n}\n/**\ntexCoord: in the [0,1] range\ndepth: depth in view space (range [znear,zfar]])\n*/\nvec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {\nvec4 ndc;\nndc.xy=texCoord*2.0-1.0;\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nndc.z=-projection[2].z-projection[3].z/depth;\n#else\nndc.z=projection[2].z+projection[3].z/depth;\n#endif\nndc.w=1.0;\nvec4 eyePos=invProjectionMatrix*ndc;\neyePos.xyz/=eyePos.w;\nreturn eyePos.xyz;\n}\n";Ht.v.IncludesShadersStore[Px]=Ix;const Mx="screenSpaceReflection2PixelShader",Ox="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#define TEXTURECUBEFUNC(s,c,lod) textureLod(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#define TEXTURECUBEFUNC(s,c,bias) textureCube(s,c,bias)\n#endif\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSR_SUPPORTED\nuniform sampler2D reflectivitySampler;\nuniform sampler2D normalSampler;\nuniform sampler2D depthSampler;\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nuniform sampler2D backDepthSampler;\nuniform float backSizeFactor;\n#endif\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nuniform samplerCube envCubeSampler;\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize;\n#endif\n#endif\nuniform mat4 view;\nuniform mat4 invView;\nuniform mat4 projection;\nuniform mat4 invProjectionMatrix;\nuniform mat4 projectionPixel;\nuniform float nearPlaneZ;\nuniform float stepSize;\nuniform float maxSteps;\nuniform float strength;\nuniform float thickness;\nuniform float roughnessFactor;\nuniform float reflectionSpecularFalloffExponent;\nuniform float maxDistance;\nuniform float selfCollisionNumSkip;\nuniform float reflectivityThreshold;\n#include\n#include\n#include\nvec3 hash(vec3 a)\n{\na=fract(a*0.8);\na+=dot(a,a.yxz+19.19);\nreturn fract((a.xxy+a.yxx)*a.zyx);\n}\nfloat computeAttenuationForIntersection(ivec2 hitPixel,vec2 hitUV,vec3 vsRayOrigin,vec3 vsHitPoint,vec3 reflectionVector,float maxRayDistance,float numIterations) {\nfloat attenuation=1.0;\n#ifdef SSR_ATTENUATE_SCREEN_BORDERS\nvec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-hitUV.xy));\nattenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0);\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE\nattenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0);\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS\nattenuation*=1.0-(numIterations/maxSteps);\n#endif\n#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION\nvec3 reflectionNormal=texelFetch(normalSampler,hitPixel,0).xyz;\nfloat directionBasedAttenuation=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));\nattenuation*=directionBasedAttenuation;\n#endif\nreturn attenuation;\n}\n#endif\nvoid main()\n{\n#ifdef SSR_SUPPORTED\nvec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);\nvec3 color=colorFull.rgb;\nvec4 reflectivity=TEXTUREFUNC(reflectivitySampler,vUV,0.0);\n#ifndef SSR_DISABLE_REFLECTIVITY_TEST\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {\n#ifdef SSR_USE_BLUR\ngl_FragColor=vec4(0.);\n#else\ngl_FragColor=colorFull;\n#endif\nreturn;\n}\n#endif\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpace(color);\n#endif\nvec2 texSize=vec2(textureSize(depthSampler,0));\nvec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; \nfloat depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;\nvec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);\nvec3 csViewDirection=normalize(csPosition);\nvec3 csReflectedVector=reflect(csViewDirection,csNormal);\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nvec3 wReflectedVector=vec3(invView*vec4(csReflectedVector,0.0));\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nvec4 worldPos=invView*vec4(csPosition,1.0);\nwReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),vReflectionSize,vReflectionPosition);\n#endif\n#ifdef SSR_INVERTCUBICMAP\nwReflectedVector.y*=-1.0;\n#endif\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nwReflectedVector.z*=-1.0;\n#endif\nvec3 envColor=TEXTURECUBEFUNC(envCubeSampler,wReflectedVector,0.0).xyz;\n#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE\nenvColor=toLinearSpace(envColor);\n#endif\n#else\nvec3 envColor=color;\n#endif\nfloat reflectionAttenuation=1.0;\nbool rayHasHit=false;\nvec2 startPixel;\nvec2 hitPixel;\nvec3 hitPoint;\nfloat numIterations;\n#ifdef SSRAYTRACE_DEBUG\nvec3 debugColor;\n#endif\n#ifdef SSR_ATTENUATE_FACING_CAMERA\nreflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector));\n#endif\nif (reflectionAttenuation>0.0) {\n#ifdef SSR_USE_BLUR\nvec3 jitt=vec3(0.);\n#else\nfloat roughness=1.0-reflectivity.a;\nvec3 jitt=mix(vec3(0.0),hash(csPosition)-vec3(0.5),roughness)*roughnessFactor; \n#endif\nvec2 uv2=vUV*texSize;\nfloat c=(uv2.x+uv2.y)*0.25;\nfloat jitter=mod(c,1.0); \nrayHasHit=traceScreenSpaceRay1(\ncsPosition,\nnormalize(csReflectedVector+jitt),\nprojectionPixel,\ndepthSampler,\ntexSize,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nbackDepthSampler,\nbackSizeFactor,\n#endif\nthickness,\nnearPlaneZ,\nstepSize,\njitter,\nmaxSteps,\nmaxDistance,\nselfCollisionNumSkip,\nstartPixel,\nhitPixel,\nhitPoint,\nnumIterations\n#ifdef SSRAYTRACE_DEBUG\n,debugColor\n#endif\n);\n}\n#ifdef SSRAYTRACE_DEBUG\ngl_FragColor=vec4(debugColor,1.);\nreturn;\n#endif\nvec3 F0=reflectivity.rgb;\nvec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));\nvec3 SSR=envColor;\nif (rayHasHit) {\nvec3 reflectedColor=texelFetch(textureSampler,ivec2(hitPixel),0).rgb;\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\nreflectedColor=toLinearSpace(reflectedColor);\n#endif\nreflectionAttenuation*=computeAttenuationForIntersection(ivec2(hitPixel),hitPixel/texSize,csPosition,hitPoint,csReflectedVector,maxDistance,numIterations);\nSSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;\n}\n#ifndef SSR_BLEND_WITH_FRESNEL\nSSR*=fresnel;\n#endif\n#ifdef SSR_USE_BLUR\nfloat blur_radius=0.0;\nfloat roughness=1.0-reflectivity.a*(1.0-roughnessFactor);\nif (roughness>0.001) {\nfloat cone_angle=min(roughness,0.999)*3.14159265*0.5;\nfloat cone_len=distance(startPixel,hitPixel);\nfloat op_len=2.0*tan(cone_angle)*cone_len; \nfloat a=op_len;\nfloat h=cone_len;\nfloat a2=a*a;\nfloat fh2=4.0f*h*h;\nblur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);\n}\ngl_FragColor=vec4(SSR,blur_radius/255.0); \n#else\n#ifdef SSR_BLEND_WITH_FRESNEL\nvec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#else\nvec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#endif\nvec3 colorMultiplier=1.0-reflectionMultiplier;\nvec3 finalColor=(color*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpace(finalColor);\n#endif\ngl_FragColor=vec4(finalColor,colorFull.a);\n#endif\n#else\ngl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0);\n#endif\n}\n";Ht.v.ShadersStore[Mx]=Ox;const Dx="screenSpaceReflection2BlurPixelShader",Nx="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#endif\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform vec2 texelOffsetScale;\nconst float weights[8]=float[8] (0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);\nvoid processSample(vec2 uv,float i,vec2 stepSize,inout vec4 accumulator,inout float denominator)\n{\nvec2 offsetUV=stepSize*i+uv;\nfloat coefficient=weights[int(2.0-abs(i))];\naccumulator+=TEXTUREFUNC(textureSampler,offsetUV,0.0)*coefficient;\ndenominator+=coefficient;\n}\nvoid main()\n{\nvec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);\nif (dot(colorFull,vec4(1.0))==0.0) {\ngl_FragColor=colorFull;\nreturn;\n}\nfloat blurRadius=colorFull.a*255.0; \nvec2 stepSize=texelOffsetScale.xy*blurRadius;\nvec4 accumulator=TEXTUREFUNC(textureSampler,vUV,0.0)*0.214607;\nfloat denominator=0.214607;\nprocessSample(vUV,1.0,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*0.2,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*0.4,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*0.6,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*0.8,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*1.2,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*1.4,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*1.6,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*1.8,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*2.0,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*0.2,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*0.4,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*0.6,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*0.8,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*1.2,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*1.4,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*1.6,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*1.8,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*2.0,stepSize,accumulator,denominator);\ngl_FragColor=vec4(accumulator.rgb/denominator,colorFull.a);\n}\n";Ht.v.ShadersStore[Dx]=Nx;const Fx="screenSpaceReflection2BlurCombinerPixelShader",wx="uniform sampler2D textureSampler; \nuniform sampler2D mainSampler;\nuniform sampler2D reflectivitySampler;\nuniform float strength;\nuniform float reflectionSpecularFalloffExponent;\nuniform float reflectivityThreshold;\nvarying vec2 vUV;\n#include\n#ifdef SSR_BLEND_WITH_FRESNEL\n#include\n#include\nuniform mat4 projection;\nuniform mat4 invProjectionMatrix;\nuniform sampler2D normalSampler;\nuniform sampler2D depthSampler;\n#endif\nvoid main()\n{\n#ifdef SSRAYTRACE_DEBUG\ngl_FragColor=texture2D(textureSampler,vUV);\n#else\nvec3 SSR=texture2D(textureSampler,vUV).rgb;\nvec4 color=texture2D(mainSampler,vUV);\nvec4 reflectivity=texture2D(reflectivitySampler,vUV);\n#ifndef SSR_DISABLE_REFLECTIVITY_TEST\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {\ngl_FragColor=color;\nreturn;\n}\n#endif\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpace(color);\n#endif\n#ifdef SSR_BLEND_WITH_FRESNEL\nvec2 texSize=vec2(textureSize(depthSampler,0));\nvec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz;\nfloat depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;\nvec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);\nvec3 csViewDirection=normalize(csPosition);\nvec3 F0=reflectivity.rgb;\nvec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));\nvec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#else\nvec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#endif\nvec3 colorMultiplier=1.0-reflectionMultiplier;\nvec3 finalColor=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpace(finalColor);\n#endif\ngl_FragColor=vec4(finalColor,color.a);\n#endif\n}\n";Ht.v.ShadersStore[Fx]=wx;const Lx=o.y3.Compose(new o.P(.5,.5,.5),o._f.Identity(),new o.P(.5,.5,.5)),Bx=o.y3.Compose(new o.P(.5,.5,1),o._f.Identity(),new o.P(.5,.5,0));class Ux extends nx{set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}get samples(){return this._samples}get reflectivityThreshold(){return this._reflectivityThreshold}set reflectivityThreshold(e){e!==this._reflectivityThreshold&&(0===e&&0!==this._reflectivityThreshold||0!==e&&0===this._reflectivityThreshold?(this._reflectivityThreshold=e,this._buildPipeline()):this._reflectivityThreshold=e)}get ssrDownsample(){return this._ssrDownsample}set ssrDownsample(e){e!==this._ssrDownsample&&(this._ssrDownsample=e,this._buildPipeline())}get blurDispersionStrength(){return this._blurDispersionStrength}set blurDispersionStrength(e){if(e===this._blurDispersionStrength)return;const t=0===e&&0!==this._blurDispersionStrength||0!==e&&0===this._blurDispersionStrength;this._blurDispersionStrength=e,t&&this._buildPipeline()}_useBlur(){return this._blurDispersionStrength>0}get blurDownsample(){return this._blurDownsample}set blurDownsample(e){e!==this._blurDownsample&&(this._blurDownsample=e,this._buildPipeline())}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e,this._updateEffectDefines()}get environmentTextureIsProbe(){return this._environmentTextureIsProbe}set environmentTextureIsProbe(e){this._environmentTextureIsProbe=e,this._updateEffectDefines()}get attenuateScreenBorders(){return this._attenuateScreenBorders}set attenuateScreenBorders(e){this._attenuateScreenBorders!==e&&(this._attenuateScreenBorders=e,this._updateEffectDefines())}get attenuateIntersectionDistance(){return this._attenuateIntersectionDistance}set attenuateIntersectionDistance(e){this._attenuateIntersectionDistance!==e&&(this._attenuateIntersectionDistance=e,this._updateEffectDefines())}get attenuateIntersectionIterations(){return this._attenuateIntersectionIterations}set attenuateIntersectionIterations(e){this._attenuateIntersectionIterations!==e&&(this._attenuateIntersectionIterations=e,this._updateEffectDefines())}get attenuateFacingCamera(){return this._attenuateFacingCamera}set attenuateFacingCamera(e){this._attenuateFacingCamera!==e&&(this._attenuateFacingCamera=e,this._updateEffectDefines())}get attenuateBackfaceReflection(){return this._attenuateBackfaceReflection}set attenuateBackfaceReflection(e){this._attenuateBackfaceReflection!==e&&(this._attenuateBackfaceReflection=e,this._updateEffectDefines())}get clipToFrustum(){return this._clipToFrustum}set clipToFrustum(e){this._clipToFrustum!==e&&(this._clipToFrustum=e,this._updateEffectDefines())}get useFresnel(){return this._useFresnel}set useFresnel(e){this._useFresnel!==e&&(this._useFresnel=e,this._buildPipeline())}get enableAutomaticThicknessComputation(){return this._enableAutomaticThicknessComputation}set enableAutomaticThicknessComputation(e){this._enableAutomaticThicknessComputation!==e&&(this._enableAutomaticThicknessComputation=e,this._buildPipeline())}get backfaceDepthRenderer(){return this._depthRenderer}get backfaceDepthTextureDownsample(){return this._backfaceDepthTextureDownsample}set backfaceDepthTextureDownsample(e){this._backfaceDepthTextureDownsample!==e&&(this._backfaceDepthTextureDownsample=e,this._resizeDepthRenderer())}get backfaceForceDepthWriteTransparentMeshes(){return this._backfaceForceDepthWriteTransparentMeshes}set backfaceForceDepthWriteTransparentMeshes(e){this._backfaceForceDepthWriteTransparentMeshes!==e&&(this._backfaceForceDepthWriteTransparentMeshes=e,this._depthRenderer&&(this._depthRenderer.forceDepthWriteTransparentMeshes=e))}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)):null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get inputTextureColorIsInGammaSpace(){return this._inputTextureColorIsInGammaSpace}set inputTextureColorIsInGammaSpace(e){this._inputTextureColorIsInGammaSpace!==e&&(this._inputTextureColorIsInGammaSpace=e,this._buildPipeline())}get generateOutputInGammaSpace(){return this._generateOutputInGammaSpace}set generateOutputInGammaSpace(e){this._generateOutputInGammaSpace!==e&&(this._generateOutputInGammaSpace=e,this._buildPipeline())}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._buildPipeline())}getScene(){return this._scene}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}get scene(){return this._scene}get isSupported(){const e=this._scene.getEngine().getCaps();return e.drawBuffersExtension&&e.texelFetch}constructor(e,t,i,n=!1,s=0){if(super(t.getEngine(),e),this.SSRRenderEffect="SSRRenderEffect",this.SSRBlurRenderEffect="SSRBlurRenderEffect",this.SSRCombineRenderEffect="SSRCombineRenderEffect",this._samples=1,this.maxDistance=1e3,this.step=1,this.thickness=.5,this.strength=1,this.reflectionSpecularFalloffExponent=1,this.maxSteps=1e3,this.roughnessFactor=.2,this.selfCollisionNumSkip=1,this._reflectivityThreshold=.04,this._ssrDownsample=0,this._blurDispersionStrength=.03,this._blurDownsample=0,this._enableSmoothReflections=!1,this._environmentTextureIsProbe=!1,this._attenuateScreenBorders=!0,this._attenuateIntersectionDistance=!0,this._attenuateIntersectionIterations=!0,this._attenuateFacingCamera=!1,this._attenuateBackfaceReflection=!1,this._clipToFrustum=!0,this._useFresnel=!1,this._enableAutomaticThicknessComputation=!1,this._backfaceDepthTextureDownsample=0,this._backfaceForceDepthWriteTransparentMeshes=!0,this._isEnabled=!0,this._inputTextureColorIsInGammaSpace=!0,this._generateOutputInGammaSpace=!0,this._debug=!1,this._forceGeometryBuffer=!1,this._isDirty=!1,this._camerasToBeAttached=[],this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=s,this._forceGeometryBuffer=n,this.isSupported){if(t.postProcessRenderPipelineManager.addPipeline(this),this._forceGeometryBuffer){const e=t.enableGeometryBufferRenderer();e&&(e.enableReflectivity=!0,e.useSpecificClearForDepthTexture=!0)}else{const e=t.enablePrePassRenderer();e&&(e.useSpecificClearForDepthTexture=!0,e.markAsDirty())}this._buildPipeline()}}getClassName(){return"SSRRenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){const t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(e=!1){this._disposeDepthRenderer(),this._disposePostProcesses(),e&&this._scene.disableGeometryBufferRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),super.dispose()}_getTextureSize(){var e,t;const i=this._scene.getEngine(),n=this._prePassRenderer;let s={width:i.getRenderWidth(),height:i.getRenderHeight()};if(n&&(null===(e=this._scene.activeCamera)||void 0===e?void 0:e._getFirstPostProcess())===this._ssrPostProcess){const e=n.getRenderTarget();e&&e.textures&&(s=e.textures[n.getIndex(4)].getSize())}else(null===(t=this._ssrPostProcess)||void 0===t?void 0:t.inputTexture)&&(s.width=this._ssrPostProcess.inputTexture.width,s.height=this._ssrPostProcess.inputTexture.height);return s}_updateEffectDefines(){var e;const t=[];(this._geometryBufferRenderer||this._prePassRenderer)&&t.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&t.push("#define SSRAYTRACE_ENABLE_REFINEMENT"),this._scene.useRightHandedSystem&&t.push("#define SSRAYTRACE_RIGHT_HANDED_SCENE"),this._environmentTexture&&(t.push("#define SSR_USE_ENVIRONMENT_CUBE"),this._environmentTexture.boundingBoxSize&&t.push("#define SSR_USE_LOCAL_REFLECTIONMAP_CUBIC"),this._environmentTexture.gammaSpace&&t.push("#define SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE")),this._environmentTextureIsProbe&&t.push("#define SSR_INVERTCUBICMAP"),this._enableAutomaticThicknessComputation&&t.push("#define SSRAYTRACE_USE_BACK_DEPTHBUFFER"),this._attenuateScreenBorders&&t.push("#define SSR_ATTENUATE_SCREEN_BORDERS"),this._attenuateIntersectionDistance&&t.push("#define SSR_ATTENUATE_INTERSECTION_DISTANCE"),this._attenuateIntersectionIterations&&t.push("#define SSR_ATTENUATE_INTERSECTION_NUMITERATIONS"),this._attenuateFacingCamera&&t.push("#define SSR_ATTENUATE_FACING_CAMERA"),this._attenuateBackfaceReflection&&t.push("#define SSR_ATTENUATE_BACKFACE_REFLECTION"),this._clipToFrustum&&t.push("#define SSRAYTRACE_CLIP_TO_FRUSTUM"),this._useBlur()&&t.push("#define SSR_USE_BLUR"),this._debug&&t.push("#define SSRAYTRACE_DEBUG"),this._inputTextureColorIsInGammaSpace&&t.push("#define SSR_INPUT_IS_GAMMA_SPACE"),this._generateOutputInGammaSpace&&t.push("#define SSR_OUTPUT_IS_GAMMA_SPACE"),this._useFresnel&&t.push("#define SSR_BLEND_WITH_FRESNEL"),0===this._reflectivityThreshold&&t.push("#define SSR_DISABLE_REFLECTIVITY_TEST"),null===(e=this._ssrPostProcess)||void 0===e||e.updateEffect(t.join("\n"))}_buildPipeline(){var e;if(!this.isSupported)return;if(!this._isEnabled)return void(this._isDirty=!0);this._isDirty=!1;const t=this._scene.getEngine();if(this._disposeDepthRenderer(),this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._enableAutomaticThicknessComputation){const t=null===(e=this._cameras)||void 0===e?void 0:e[0];t&&(this._depthRendererCamera=t,this._depthRenderer=new Rg(this._scene,void 0,void 0,void 0,1,!0,"SSRBackDepth"),this._depthRenderer.clearColor.r=1e8,this._depthRenderer.reverseCulling=!0,this._depthRenderer.forceDepthWriteTransparentMeshes=this._backfaceForceDepthWriteTransparentMeshes,this._resizeDepthRenderer(),t.customRenderTargets.push(this._depthRenderer.getDepthMap()))}this._createSSRPostProcess(),this.addEffect(new YS(t,this.SSRRenderEffect,(()=>this._ssrPostProcess),!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new YS(t,this.SSRBlurRenderEffect,(()=>[this._blurPostProcessX,this._blurPostProcessY]),!0)),this.addEffect(new YS(t,this.SSRCombineRenderEffect,(()=>this._blurCombinerPostProcess),!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_resizeDepthRenderer(){if(!this._depthRenderer)return;const e=this._getTextureSize(),t=this._depthRenderer.getDepthMap().getSize(),i=Math.floor(e.width/(this._backfaceDepthTextureDownsample+1)),n=Math.floor(e.height/(this._backfaceDepthTextureDownsample+1));t.width===i&&t.height===n||this._depthRenderer.getDepthMap().resize({width:i,height:n})}_disposeDepthRenderer(){var e;if(this._depthRenderer){if(this._depthRendererCamera){const t=null!==(e=this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap()))&&void 0!==e?e:-1;-1!==t&&this._depthRendererCamera.customRenderTargets.splice(t,1)}this._depthRendererCamera=null,this._depthRenderer.getDepthMap().dispose()}this._depthRenderer=null}_disposePostProcesses(){var e,t,i,n;for(let s=0;s{this._resizeDepthRenderer();const t=this._geometryBufferRenderer,i=this._prePassRenderer;if(!i&&!t)return;if(t){const i=t.getTextureIndex(XE.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",t.getGBuffer().textures[1]),e.setTexture("reflectivitySampler",t.getGBuffer().textures[i]),e.setTexture("depthSampler",t.getGBuffer().textures[0])}else if(i){const t=i.getIndex(5),n=i.getIndex(3),s=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[s]),e.setTexture("depthSampler",i.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",i.getRenderTarget().textures[n])}this._enableAutomaticThicknessComputation&&this._depthRenderer&&(e.setTexture("backDepthSampler",this._depthRenderer.getDepthMap()),e.setFloat("backSizeFactor",this._backfaceDepthTextureDownsample+1));const n=this._scene.activeCamera;if(!n)return;const s=n.getViewMatrix(!0),r=n.getProjectionMatrix(!0);r.invertToRef(o.jp.Matrix[0]),s.invertToRef(o.jp.Matrix[1]),e.setMatrix("projection",r),e.setMatrix("view",s),e.setMatrix("invView",o.jp.Matrix[1]),e.setMatrix("invProjectionMatrix",o.jp.Matrix[0]),e.setFloat("thickness",this.thickness),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("maxSteps",this.maxSteps),e.setFloat("roughnessFactor",this.roughnessFactor),e.setFloat("nearPlaneZ",n.minZ),e.setFloat("maxDistance",this.maxDistance),e.setFloat("selfCollisionNumSkip",this.selfCollisionNumSkip),e.setFloat("reflectivityThreshold",this._reflectivityThreshold);const a=this._getTextureSize();o.y3.ScalingToRef(a.width,a.height,1,o.jp.Matrix[2]),r.multiplyToRef(this._scene.getEngine().isWebGPU?Bx:Lx,o.jp.Matrix[3]),o.jp.Matrix[3].multiplyToRef(o.jp.Matrix[2],o.jp.Matrix[4]),e.setMatrix("projectionPixel",o.jp.Matrix[4]),this._environmentTexture&&(e.setTexture("envCubeSampler",this._environmentTexture),this._environmentTexture.boundingBoxSize&&(e.setVector3("vReflectionPosition",this._environmentTexture.boundingBoxPosition),e.setVector3("vReflectionSize",this._environmentTexture.boundingBoxSize)))},this._ssrPostProcess.samples=this.samples,this._forceGeometryBuffer||(this._ssrPostProcess._prePassEffectConfiguration=new Rx)}_createBlurAndCombinerPostProcesses(){const e=this._scene.getEngine();this._blurPostProcessX=new Zt("SSRblurX","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._ssrDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessX.autoClear=!1,this._blurPostProcessX.onApplyObservable.add((e=>{var t,i;const n=null!==(i=null===(t=this._blurPostProcessX)||void 0===t?void 0:t.inputTexture.width)&&void 0!==i?i:this._scene.getEngine().getRenderWidth();e.setFloat2("texelOffsetScale",this._blurDispersionStrength/n,0)})),this._blurPostProcessY=new Zt("SSRblurY","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._blurDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessY.autoClear=!1,this._blurPostProcessY.onApplyObservable.add((e=>{var t,i;const n=null!==(i=null===(t=this._blurPostProcessY)||void 0===t?void 0:t.inputTexture.height)&&void 0!==i?i:this._scene.getEngine().getRenderHeight();e.setFloat2("texelOffsetScale",0,this._blurDispersionStrength/n)}));const t=["strength","reflectionSpecularFalloffExponent","reflectivityThreshold"],i=["textureSampler","mainSampler","reflectivitySampler"];let n="";this._debug&&(n+="#define SSRAYTRACE_DEBUG\n"),this._inputTextureColorIsInGammaSpace&&(n+="#define SSR_INPUT_IS_GAMMA_SPACE\n"),this._generateOutputInGammaSpace&&(n+="#define SSR_OUTPUT_IS_GAMMA_SPACE\n"),this.useFresnel&&(n+="#define SSR_BLEND_WITH_FRESNEL\n",t.push("projection","invProjectionMatrix"),i.push("depthSampler","normalSampler")),0===this._reflectivityThreshold&&(n+="#define SSR_DISABLE_REFLECTIVITY_TEST"),this._blurCombinerPostProcess=new Zt("SSRblurCombiner","screenSpaceReflection2BlurCombiner",t,i,this._useBlur()?1/(this._blurDownsample+1):1,null,1,e,!1,n,this._textureType),this._blurCombinerPostProcess.autoClear=!1,this._blurCombinerPostProcess.onApplyObservable.add((e=>{var t;const i=this._geometryBufferRenderer,n=this._prePassRenderer;if(n||i){if(n&&(null===(t=this._scene.activeCamera)||void 0===t?void 0:t._getFirstPostProcess())===this._ssrPostProcess){const t=n.getRenderTarget();t&&t.textures&&e.setTexture("mainSampler",t.textures[n.getIndex(4)])}else e.setTextureFromPostProcess("mainSampler",this._ssrPostProcess);if(i){const t=i.getTextureIndex(XE.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("reflectivitySampler",i.getGBuffer().textures[t]),this.useFresnel&&(e.setTexture("normalSampler",i.getGBuffer().textures[1]),e.setTexture("depthSampler",i.getGBuffer().textures[0]))}else if(n){const t=n.getIndex(3);if(e.setTexture("reflectivitySampler",n.getRenderTarget().textures[t]),this.useFresnel){const t=n.getIndex(5),i=n.getIndex(6);e.setTexture("normalSampler",n.getRenderTarget().textures[i]),e.setTexture("depthSampler",n.getRenderTarget().textures[t])}}if(e.setFloat("strength",this.strength),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("reflectivityThreshold",this._reflectivityThreshold),this.useFresnel){const t=this._scene.activeCamera;if(t){const i=t.getProjectionMatrix();i.invertToRef(o.jp.Matrix[0]),e.setMatrix("projection",i),e.setMatrix("invProjectionMatrix",o.jp.Matrix[0])}}}}))}serialize(){const e=E.p4.Serialize(this);return e.customType="SSRRenderingPipeline",e}static Parse(e,t,i){return E.p4.Parse((()=>new Ux(e._name,t,e._ratio)),e,t,i)}}(0,oe.gn)([(0,E.qC)()],Ux.prototype,"samples",null),(0,oe.gn)([(0,E.qC)()],Ux.prototype,"maxDistance",void 0),(0,oe.gn)([(0,E.qC)()],Ux.prototype,"step",void 0),(0,oe.gn)([(0,E.qC)()],Ux.prototype,"thickness",void 0),(0,oe.gn)([(0,E.qC)()],Ux.prototype,"strength",void 0),(0,oe.gn)([(0,E.qC)()],Ux.prototype,"reflectionSpecularFalloffExponent",void 0),(0,oe.gn)([(0,E.qC)()],Ux.prototype,"maxSteps",void 0),(0,oe.gn)([(0,E.qC)()],Ux.prototype,"roughnessFactor",void 0),(0,oe.gn)([(0,E.qC)()],Ux.prototype,"selfCollisionNumSkip",void 0),(0,oe.gn)([(0,E.qC)()],Ux.prototype,"_reflectivityThreshold",void 0),(0,oe.gn)([(0,E.qC)("_ssrDownsample")],Ux.prototype,"_ssrDownsample",void 0),(0,oe.gn)([(0,E.qC)()],Ux.prototype,"ssrDownsample",null),(0,oe.gn)([(0,E.qC)("blurDispersionStrength")],Ux.prototype,"_blurDispersionStrength",void 0),(0,oe.gn)([(0,E.qC)("blurDownsample")],Ux.prototype,"_blurDownsample",void 0),(0,oe.gn)([(0,E.qC)("enableSmoothReflections")],Ux.prototype,"_enableSmoothReflections",void 0),(0,oe.gn)([(0,E.qC)("environmentTexture")],Ux.prototype,"_environmentTexture",void 0),(0,oe.gn)([(0,E.qC)("environmentTextureIsProbe")],Ux.prototype,"_environmentTextureIsProbe",void 0),(0,oe.gn)([(0,E.qC)("attenuateScreenBorders")],Ux.prototype,"_attenuateScreenBorders",void 0),(0,oe.gn)([(0,E.qC)("attenuateIntersectionDistance")],Ux.prototype,"_attenuateIntersectionDistance",void 0),(0,oe.gn)([(0,E.qC)("attenuateIntersectionIterations")],Ux.prototype,"_attenuateIntersectionIterations",void 0),(0,oe.gn)([(0,E.qC)("attenuateFacingCamera")],Ux.prototype,"_attenuateFacingCamera",void 0),(0,oe.gn)([(0,E.qC)("attenuateBackfaceReflection")],Ux.prototype,"_attenuateBackfaceReflection",void 0),(0,oe.gn)([(0,E.qC)("clipToFrustum")],Ux.prototype,"_clipToFrustum",void 0),(0,oe.gn)([(0,E.qC)("useFresnel")],Ux.prototype,"_useFresnel",void 0),(0,oe.gn)([(0,E.qC)("enableAutomaticThicknessComputation")],Ux.prototype,"_enableAutomaticThicknessComputation",void 0),(0,oe.gn)([(0,E.qC)("backfaceDepthTextureDownsample")],Ux.prototype,"_backfaceDepthTextureDownsample",void 0),(0,oe.gn)([(0,E.qC)("backfaceForceDepthWriteTransparentMeshes")],Ux.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0),(0,oe.gn)([(0,E.qC)("isEnabled")],Ux.prototype,"_isEnabled",void 0),(0,oe.gn)([(0,E.qC)("inputTextureColorIsInGammaSpace")],Ux.prototype,"_inputTextureColorIsInGammaSpace",void 0),(0,oe.gn)([(0,E.qC)("generateOutputInGammaSpace")],Ux.prototype,"_generateOutputInGammaSpace",void 0),(0,oe.gn)([(0,E.qC)("debug")],Ux.prototype,"_debug",void 0),(0,l.H)("BABYLON.SSRRenderingPipeline",Ux);const Vx="tonemapPixelShader",kx="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}";Ht.v.ShadersStore[Vx]=kx;var Gx;!function(e){e[e.Hable=0]="Hable",e[e.Reinhard=1]="Reinhard",e[e.HejiDawson=2]="HejiDawson",e[e.Photographic=3]="Photographic"}(Gx||(Gx={}));const zx="volumetricLightScatteringPixelShader",Wx="uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i{this.isSupported||this.dispose(e),this.onActivate=null},this.onApplyObservable.add((e=>{this._updateMeshScreenCoordinates(h),e.setTexture("lightScatteringSampler",this._volumetricLightScatteringRTT),e.setFloat("exposure",this.exposure),e.setFloat("decay",this.decay),e.setFloat("weight",this.weight),e.setFloat("density",this.density),e.setVector2("meshPositionOnScreen",this._screenCoordinates)}))}getClassName(){return"VolumetricLightScatteringPostProcess"}_isReady(e,t){var i;const n=e.getMesh();if(n===this.mesh&&n.material)return n.material.isReady(n);const s=null===(i=n._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[this._scene.getEngine().currentRenderPassId];if(s)return s.isReadyForSubMesh(n,e,t);const r=[],o=[ne.o.PositionKind],a=e.getMaterial();a&&(a.needAlphaTesting()&&r.push("#define ALPHATEST"),n.isVerticesDataPresent(ne.o.UVKind)&&(o.push(ne.o.UVKind),r.push("#define UV1")),n.isVerticesDataPresent(ne.o.UV2Kind)&&(o.push(ne.o.UV2Kind),r.push("#define UV2"))),n.useBones&&n.computeBonesUsingShaders?(o.push(ne.o.MatricesIndicesKind),o.push(ne.o.MatricesWeightsKind),r.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),r.push("#define BonesPerMesh "+(n.skeleton?n.skeleton.bones.length+1:0))):r.push("#define NUM_BONE_INFLUENCERS 0"),t&&(r.push("#define INSTANCES"),It.G.PushAttributesForInstances(o),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES"));const l=e._getDrawWrapper(void 0,!0),h=l.defines,c=r.join("\n");return h!==c&&l.setEffect(n.getScene().getEngine().createEffect("volumetricLightScatteringPass",o,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],c,void 0,void 0,void 0,{maxSimultaneousMorphTargets:n.numBoneInfluencers}),c),l.effect.isReady()}setCustomMeshPosition(e){this.customMeshPosition=e}getCustomMeshPosition(){return this.customMeshPosition}dispose(e){const t=e.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);-1!==t&&e.getScene().customRenderTargets.splice(t,1),this._volumetricLightScatteringRTT.dispose(),super.dispose(e)}getPass(){return this._volumetricLightScatteringRTT}_meshExcluded(e){return this.includedMeshes.length>0&&-1===this.includedMeshes.indexOf(e)||this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)}_createPass(e,t){const i=e.getEngine();this._volumetricLightScatteringRTT=new Ci("volumetricLightScatteringMap",{width:i.getRenderWidth()*t,height:i.getRenderHeight()*t},e,!1,!0,0),this._volumetricLightScatteringRTT.wrapU=Le.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=Le.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;const n=this.getCamera();n?n.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);const s=e=>{var t;const i=e.getRenderingMesh(),n=e.getEffectiveMesh();if(this._meshExcluded(i))return;n._internalAbstractMeshDataInfo._isActiveIntermediate=!1;const s=e.getMaterial();if(!s)return;const r=i.getScene(),o=r.getEngine();o.setState(s.backFaceCulling,void 0,void 0,void 0,s.cullBackFaces);const a=i._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(a.mustReturn)return;const l=o.getCaps().instancedArrays&&(null!==a.visibleInstances[e._id]||i.hasThinInstances);if(this._isReady(e,l)){const h=null===(t=n._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===t?void 0:t[o.currentRenderPassId];let c=e._getDrawWrapper();if(i!==this.mesh||c||(c=s._getDrawWrapper()),!c)return;const d=c.effect;if(o.enableEffect(c),l||i._bind(e,d,s.fillMode),i===this.mesh)s.bind(n.getWorldMatrix(),i);else if(h)h.bindForSubMesh(n.getWorldMatrix(),n,e);else{if(d.setMatrix("viewProjection",r.getTransformMatrix()),s&&s.needAlphaTesting()){const e=s.getAlphaTestTexture();d.setTexture("diffuseSampler",e),e&&d.setMatrix("diffuseMatrix",e.getTextureMatrix())}i.useBones&&i.computeBonesUsingShaders&&i.skeleton&&d.setMatrices("mBones",i.skeleton.getTransformMatrices(i))}l&&i.hasThinInstances&&d.setMatrix("world",n.getWorldMatrix()),i._processRendering(n,e,d,ut.F.TriangleFillMode,a,l,((e,t)=>{e||d.setMatrix("world",t)}))}};let r;const o=new a.HE(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add((()=>{r=e.clearColor,e.clearColor=o})),this._volumetricLightScatteringRTT.onAfterRenderObservable.add((()=>{e.clearColor=r})),this._volumetricLightScatteringRTT.customIsReadyFunction=(e,t,n)=>{if((n||0===t)&&e.subMeshes)for(let s=0;s{const o=e.getEngine();let a;if(r.length){for(o.setColorWrite(!1),a=0;ae._alphaIndex>t._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0)),o.setAlphaMode(2),a=0;a{e.setFloat("curvature_ridge",.5/Math.max(this.ridge*this.ridge,1e-4)),e.setFloat("curvature_valley",.7/Math.max(this.valley*this.valley,1e-4));const t=this._geometryBufferRenderer.getGBuffer().textures[1];e.setTexture("normalSampler",t)}:p.Y.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.")}static get IsSupported(){const e=m.l.LastCreatedEngine;return!!e&&e.getCaps().drawBuffersExtension}static _Parse(e,t,i,n){return E.p4.Parse((()=>new Qx(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,n)}}(0,oe.gn)([(0,E.qC)()],Qx.prototype,"ridge",void 0),(0,oe.gn)([(0,E.qC)()],Qx.prototype,"valley",void 0),(0,l.H)("BABYLON.ScreenSpaceCurvaturePostProcess",Qx);const Zx="boundingBoxRendererFragmentDeclaration",Jx="uniform vec4 color;\n";Ht.v.IncludesShadersStore[Zx]=Jx;const eb="boundingBoxRendererUboDeclaration",tb="#ifdef WEBGL2\nuniform vec4 color;\nuniform mat4 world;\nuniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n#else\nlayout(std140,column_major) uniform;\nuniform BoundingBoxRenderer {\nvec4 color;\nmat4 world;\nmat4 viewProjection;\nmat4 viewProjectionR;\n};\n#endif\n";Ht.v.IncludesShadersStore[eb]=tb;const ib="boundingBoxRendererPixelShader",nb="#include<__decl__boundingBoxRendererFragment>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ht.v.ShadersStore[ib]=nb;const sb="boundingBoxRendererVertexDeclaration",rb="uniform mat4 world;\nuniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n";Ht.v.IncludesShadersStore[sb]=rb;const ob="boundingBoxRendererVertexShader",ab="attribute vec3 position;\n#include<__decl__boundingBoxRendererVertex>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec4 worldPos=world*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {\ngl_Position=viewProjection*worldPos;\n} else {\ngl_Position=viewProjectionR*worldPos;\n}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";Ht.v.ShadersStore[ob]=ab;Object.defineProperty(N.x.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(e){this._forceShowBoundingBoxes=e,e&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0}),N.x.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new lb(this)),this._boundingBoxRenderer},Object.defineProperty(ie.x.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(e){this._showBoundingBox=e,e&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});class lb{constructor(e){this.name=Se.l.NAME_BOUNDINGBOXRENDERER,this.frontColor=new a.Wo(1,1,1),this.backColor=new a.Wo(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new r.y$,this.onAfterBoxRenderingObservable=new r.y$,this.onResourcesReadyObservable=new r.y$,this.enabled=!0,this.renderList=new Wt.t(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,e._addComponent(this),this._uniformBufferFront=new ae.M(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new ae.M(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererBack",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferBack)}_buildUniformLayout(e){e.addUniform("color",4),e.addUniform("world",16),e.addUniform("viewProjection",16),e.addUniform("viewProjectionR",16),e.create()}register(){this.scene._beforeEvaluateActiveMeshStage.registerStep(Se.l.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(Se.l.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(Se.l.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(Se.l.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)}_evaluateSubMesh(e,t){if(e.showSubMeshesBoundingBox){const i=t.getBoundingInfo();null!=i&&(i.boundingBox._tag=e.renderingGroupId,this.renderList.push(i.boundingBox))}}_preActiveMesh(e){if(e.showBoundingBox||this.scene.forceShowBoundingBoxes){const t=e.getBoundingInfo();t.boundingBox._tag=e.renderingGroupId,this.renderList.push(t.boundingBox)}}_prepareResources(){if(this._colorShader)return;this._colorShader=new Il("colorShader",this.scene,"boundingBoxRenderer",{attributes:[ne.o.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new Il("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[ne.o.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};const e=this.scene.getEngine(),t=fl({size:1});this._vertexBuffers[ne.o.PositionKind]=new ne.o(e,t.positions,ne.o.PositionKind,!1),this._createIndexBuffer(),this._fillIndexData=t.indices,this.onResourcesReadyObservable.notifyObservers(this)}_createIndexBuffer(){const e=this.scene.getEngine();this._indexBuffer=e.createIndexBuffer([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,7,1,6,2,5,3,4])}rebuild(){const e=this._vertexBuffers[ne.o.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}reset(){this.renderList.reset()}render(e){var t,i;if(0===this.renderList.length||!this.enabled)return;if(this._prepareResources(),!this._colorShader.isReady())return;const n=this.scene.getEngine();n.setDepthWrite(!1);const s=this.scene.getTransformMatrix();for(let r=0;r{let t=e._getComponent(Se.l.NAME_DEPTHRENDERER);t||(t=new hb(e),e._addComponent(t))};const cb="oitFinalPixelShader",db="precision highp float;\nuniform sampler2D uFrontColor;\nuniform sampler2D uBackColor;\nvoid main() {\nivec2 fragCoord=ivec2(gl_FragCoord.xy);\nvec4 frontColor=texelFetch(uFrontColor,fragCoord,0);\nvec4 backColor=texelFetch(uBackColor,fragCoord,0);\nfloat alphaMultiplier=1.0-frontColor.a;\nglFragColor=vec4(\nfrontColor.rgb+alphaMultiplier*backColor.rgb,\nfrontColor.a+backColor.a\n);\n}";Ht.v.ShadersStore[cb]=db;const ub="oitBackBlendPixelShader",pb="precision highp float;\nuniform sampler2D uBackColor;\nvoid main() {\nglFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);\nif (glFragColor.a==0.0) { \ndiscard;\n}\n}";Ht.v.ShadersStore[ub]=pb;class fb{constructor(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[4]}}class _b{get passCount(){return this._passCount}set passCount(e){this._passCount!==e&&(this._passCount=e,this._createRenderPassIds())}get useRenderPasses(){return this._useRenderPasses}set useRenderPasses(e){this._useRenderPasses!==e&&(this._useRenderPasses=e,this._createRenderPassIds())}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}constructor(e,t=5){if(this._thinTextures=[],this._currentPingPongState=0,this._layoutCacheFormat=[[!0],[!0,!0],[!0,!0,!0]],this._layoutCache=[],this._candidateSubMeshes=new Wt.t(10),this._excludedSubMeshes=new Wt.t(10),this._excludedMeshes=[],this._colorCache=[new a.HE(_b._DEPTH_CLEAR_VALUE,_b._DEPTH_CLEAR_VALUE,0,0),new a.HE(-_b._MIN_DEPTH,_b._MAX_DEPTH,0,0),new a.HE(0,0,0,0)],this._scene=e,this._engine=e.getEngine(),this._passCount=t,e.enablePrePassRenderer()){for(let e=0;e{this._rebuild()})),this._meshDisposeObserver=this._source.onDisposeObservable.add((()=>{this.dispose()}))}_prepareRessources(){this._lineShader||(this._lineShader=xb._GetShader(this._source.getScene()))}_rebuild(){let e=this._buffers[ne.o.PositionKind];e&&e._rebuild(),e=this._buffers[ne.o.NormalKind],e&&e._rebuild();const t=this._source.getScene().getEngine();this._ib=t.createIndexBuffer(this._linesIndices)}dispose(){var e;this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);let t=this._buffers[ne.o.PositionKind];t&&(t.dispose(),this._buffers[ne.o.PositionKind]=null),t=this._buffers[ne.o.NormalKind],t&&(t.dispose(),this._buffers[ne.o.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose(),null===(e=this._drawWrapper)||void 0===e||e.dispose()}_processEdgeForAdjacencies(e,t,i,n,s){return e===i&&t===n||e===n&&t===i?0:e===n&&t===s||e===s&&t===n?1:e===s&&t===i||e===i&&t===s?2:-1}_processEdgeForAdjacenciesWithVertices(e,t,i,n,s){const r=1e-10;return e.equalsWithEpsilon(i,r)&&t.equalsWithEpsilon(n,r)||e.equalsWithEpsilon(n,r)&&t.equalsWithEpsilon(i,r)?0:e.equalsWithEpsilon(n,r)&&t.equalsWithEpsilon(s,r)||e.equalsWithEpsilon(s,r)&&t.equalsWithEpsilon(n,r)?1:e.equalsWithEpsilon(s,r)&&t.equalsWithEpsilon(i,r)||e.equalsWithEpsilon(i,r)&&t.equalsWithEpsilon(s,r)?2:-1}_checkEdge(e,t,i,n,s){let r;if(void 0===t)r=!0;else{r=o.P.Dot(i[e],i[t]){i>=0&&t.push(i);for(let n=0;n=e[0].length&&e[1].length>=e[2].length?r=1:e[2].length>=e[0].length&&e[2].length>=e[1].length&&(r=2);for(let E=0;E<3;++E)E===r?e[E].sort(((e,t)=>e[1]t[1]?1:0)):e[E].sort(((e,t)=>e[1]>t[1]?-1:e[1]=r+1;--E)s(e[E%3],a,E!==r+2?n[i[t+(E+1)%3]]:-1);const h=a.length;i.push(n[i[t+r]],o[0],a[0]),i.push(n[i[t+(r+1)%3]],a[h-1],o[l-1]);const c=l<=h,d=c?l:h,u=c?h:l,p=c?l-1:h-1,f=c?0:1;let _=l+h-2,m=0,g=0;const v=c?o:a,T=c?a:o;let S=0;for(;_-- >0;){let e;f?i.push(v[m],T[g]):i.push(T[g],v[m]),S+=d,S>=u&&mn){const e=i;i=n,n=e}const r=i+"_"+n,a=g[r];if(a){if(!a.done){o.P.Dot(e,a.normal)0||this._source.hasThinInstances)}render(){const e=this._source.getScene(),t=this._lineShader._getDrawWrapper();if(this._drawWrapper&&this._lineShader._setDrawWrapper(this._drawWrapper),!this.isReady()||!e.activeCamera)return void this._lineShader._setDrawWrapper(t);const i=this._source.hasInstances&&this.customInstances.length>0,n=i||this._source.hasThinInstances;let s=0;if(n)if(this._buffersForInstances.world0=this._source.getVertexBuffer("world0"),this._buffersForInstances.world1=this._source.getVertexBuffer("world1"),this._buffersForInstances.world2=this._source.getVertexBuffer("world2"),this._buffersForInstances.world3=this._source.getVertexBuffer("world3"),i){const e=this._source._instanceDataStorage;if(s=this.customInstances.length,!e.instancesData)return void(this._source.getScene()._activeMeshesFrozen||this.customInstances.reset());if(!e.isFrozen){let t=0;for(let i=0;i0&&(this._useSpecificClearForDepthTexture&&5===this._mrtLayout[s]?(t.push(!1),i.push(!0)):(t.push(!0),i.push(!1)),n.push(!1));this._multiRenderAttachments=this._engine.buildTextureLayout(e),this._clearAttachments=this._engine.buildTextureLayout(t),this._clearDepthAttachments=this._engine.buildTextureLayout(i),this._defaultAttachments=this._engine.buildTextureLayout(n)}_resetLayout(){for(let e=0;enull!=e)),this._scene.autoClear=!0;const n=this._hasImageProcessing(this._postProcessesSourceForThisPass);this._needsCompositionForThisPass=!n&&!this.disableGammaTransform&&this._needsImageProcessing()&&!i;const s=this._getFirstPostProcess(this._postProcessesSourceForThisPass),r=e._beforeCompositionPostProcesses&&e._beforeCompositionPostProcesses[0];let o=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||n,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),r?o=r:this._needsCompositionForThisPass?o=e.imageProcessingPostProcess:s&&(o=s),this._bindFrameBuffer(e),this._linkInternalTexture(e,o)}_linkInternalTexture(e,t){t&&(t.autoClear=!1,t.inputTexture=e.renderTarget),e._outputPostProcess!==t&&(e._outputPostProcess&&this._unlinkInternalTexture(e),e._outputPostProcess=t),e._internalTextureDirty&&(this._updateGeometryBufferLayout(),e._internalTextureDirty=!1)}_unlinkInternalTexture(e){e._outputPostProcess&&(e._outputPostProcess.autoClear=!0,e._outputPostProcess.restoreDefaultInputTexture(),e._outputPostProcess=null)}_needsImageProcessing(){for(let e=0;enull!=e)),e)){for(let n=0;n=0;e--)this.renderTargets[e].dispose();for(let e=0;e{throw(0,ge.S)("PrePassRendererSceneComponent")},yb.TextureFormats=[{purpose:0,type:2,format:5,name:"prePass_Irradiance"},{purpose:1,type:2,format:5,name:"prePass_Position"},{purpose:2,type:0,format:5,name:"prePass_Velocity"},{purpose:3,type:0,format:5,name:"prePass_Reflectivity"},{purpose:4,type:2,format:5,name:"prePass_Color"},{purpose:5,type:1,format:6,name:"prePass_Depth"},{purpose:6,type:2,format:5,name:"prePass_Normal"},{purpose:7,type:0,format:5,name:"prePass_Albedo"}],Object.defineProperty(N.x.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(e){e&&e.isSupported&&(this._prePassRenderer=e)},enumerable:!0,configurable:!0}),N.x.prototype.enablePrePassRenderer=function(){return this._prePassRenderer||(this._prePassRenderer=new yb(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,p.Y.Error("PrePassRenderer needs WebGL 2 support.\nMaybe you tried to use the following features that need the PrePassRenderer :\n + Subsurface Scattering"))),this._prePassRenderer},N.x.prototype.disablePrePassRenderer=function(){this._prePassRenderer&&(this._prePassRenderer.dispose(),this._prePassRenderer=null)};class Ab{constructor(e){this.name=Se.l.NAME_PREPASSRENDERER,this.scene=e}register(){this.scene._beforeCameraDrawStage.registerStep(Se.l.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(Se.l.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(Se.l.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(Se.l.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(Se.l.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(Se.l.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(Se.l.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(Se.l.STEP_AFTERRENDERINGMESH_PREPASS,this,this._afterRenderingMeshStage)}_beforeRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._beforeDraw(void 0,t,i))}_afterRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&this.scene.prePassRenderer._afterDraw(t,i)}_beforeRenderTargetClearStage(e){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(e._prePassRenderTarget||(e._prePassRenderTarget=this.scene.prePassRenderer._createRenderTarget(e.name+"_prePassRTT",e)),this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._clear())}_beforeCameraDraw(e){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._beforeDraw(e))}_afterCameraDraw(){this.scene.prePassRenderer&&this.scene.prePassRenderer._afterDraw()}_beforeClearStage(){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._clear())}_beforeRenderingMeshStage(e,t,i,n){if(!n)return;const s=e.getScene();s.prePassRenderer&&s.prePassRenderer.bindAttachmentsForEffect(n,t)}_afterRenderingMeshStage(e){const t=e.getScene();t.prePassRenderer&&t.prePassRenderer.restoreAttachments()}rebuild(){this.scene.disablePrePassRenderer(),this.scene.enablePrePassRenderer()}dispose(){this.scene.disablePrePassRenderer()}}yb._SceneComponentInitialization=e=>{let t=e._getComponent(Se.l.NAME_PREPASSRENDERER);t||(t=new Ab(e),e._addComponent(t))};const Rb="fibonacci",Pb="#define rcp(x) 1./x\n#define GOLDEN_RATIO 1.618033988749895\n#define TWO_PI 6.2831855\nvec2 Golden2dSeq(int i,float n)\n{\nreturn vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));\n}\nvec2 SampleDiskGolden(int i,int sampleCount)\n{\nvec2 f=Golden2dSeq(i,float(sampleCount));\nreturn vec2(sqrt(f.x),TWO_PI*f.y);\n}";Ht.v.IncludesShadersStore[Rb]=Pb;const Ib="diffusionProfile",Mb="uniform vec3 diffusionS[5];\nuniform float diffusionD[5];\nuniform float filterRadii[5];";Ht.v.IncludesShadersStore[Ib]=Mb;const Ob="subSurfaceScatteringPixelShader",Db="#include\n#include\n#include\n#include\nvarying vec2 vUV;\nuniform vec2 texelSize;\nuniform sampler2D textureSampler;\nuniform sampler2D irradianceSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D albedoSampler;\nuniform vec2 viewportSize;\nuniform float metersPerUnit;\nconst float LOG2_E=1.4426950408889634;\nconst float SSS_PIXELS_PER_SAMPLE=4.;\nconst int _SssSampleBudget=40;\n#define rcp(x) 1./x\n#define Sq(x) x*x\n#define SSS_BILATERAL_FILTER true\nvec3 EvalBurleyDiffusionProfile(float r,vec3 S)\n{\nvec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); \nvec3 expSum=exp_13*(1.+exp_13*exp_13); \nreturn (S*rcp(8.*PI))*expSum; \n}\nvec2 SampleBurleyDiffusionProfile(float u,float rcpS)\n{\nu=1.-u; \nfloat g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));\nfloat n=exp2(log2(g)*(-1.0/3.0)); \nfloat p=(g*n)*n; \nfloat c=1.+p+n; \nfloat d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); \nfloat x=(3./LOG2_E)*log2(c)-d; \nfloat rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));\nfloat r=x*rcpS;\nfloat rcpPdf=(8.*PI*rcpS)*rcpExp; \nreturn vec2(r,rcpPdf);\n}\nvec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf)\n{\n#ifndef SSS_BILATERAL_FILTER\nz=0.;\n#endif\nfloat r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));\nfloat area=rcpPdf;\n#if SSS_CLAMP_ARTIFACT\nreturn clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0);\n#else\nreturn EvalBurleyDiffusionProfile(r,S)*area;\n#endif\n}\nvoid EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm,\nfloat phase,inout vec3 totalIrradiance,inout vec3 totalWeight)\n{\nfloat scale =rcp(float(n));\nfloat offset=rcp(float(n))*0.5;\nfloat sinPhase,cosPhase;\nsinPhase=sin(phase);\ncosPhase=cos(phase);\nvec2 bdp=SampleBurleyDiffusionProfile(float(i)*scale+offset,d);\nfloat r=bdp.x;\nfloat rcpPdf=bdp.y;\nfloat phi=SampleDiskGolden(i,n).y;\nfloat sinPhi,cosPhi;\nsinPhi=sin(phi);\ncosPhi=cos(phi);\nfloat sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; \nfloat cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; \nvec2 vec=r*vec2(cosPsi,sinPsi);\nvec2 position; \nfloat xy2;\nposition=vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*texelSize;\nxy2 =r*r;\nvec4 textureSample=texture2D(irradianceSampler,position);\nfloat viewZ=texture2D(depthSampler,position).r;\nvec3 irradiance =textureSample.rgb;\nif (testLightingForSSS(textureSample.a))\n{\nfloat relZ=viewZ-centerPosVS.z;\nvec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);\ntotalIrradiance+=weight*irradiance;\ntotalWeight +=weight;\n}\nelse\n{\n}\n}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\nvec4 irradianceAndDiffusionProfile =texture2D(irradianceSampler,vUV);\nvec3 centerIrradiance=irradianceAndDiffusionProfile.rgb;\nint diffusionProfileIndex=int(round(irradianceAndDiffusionProfile.a*255.));\nfloat centerDepth =0.;\nvec4 inputColor=texture2D(textureSampler,vUV);\nbool passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);\nif (passedStencilTest)\n{\ncenterDepth=texture2D(depthSampler,vUV).r;\n}\nif (!passedStencilTest) { \ngl_FragColor=inputColor;\nreturn;\n}\nfloat distScale =1.;\nvec3 S =diffusionS[diffusionProfileIndex];\nfloat d =diffusionD[diffusionProfileIndex];\nfloat filterRadius=filterRadii[diffusionProfileIndex];\nvec2 centerPosNDC=vUV;\nvec2 cornerPosNDC=vUV+0.5*texelSize;\nvec3 centerPosVS =vec3(centerPosNDC*viewportSize,1.0)*centerDepth; \nvec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; \nfloat mmPerUnit =1000.*(metersPerUnit*rcp(distScale));\nfloat unitsPerMm=rcp(mmPerUnit);\nfloat unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);\nfloat pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;\nfloat filterArea =PI*Sq(filterRadius*pixelsPerMm);\nint sampleCount =int(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));\nint sampleBudget=_SssSampleBudget;\nint texturingMode=0;\nvec3 albedo =texture2D(albedoSampler,vUV).rgb;\nif (distScale==0. || sampleCount<1)\n{\n#ifdef DEBUG_SSS_SAMPLES\nvec3 green=vec3(0.,1.,0.);\ngl_FragColor=vec4(green,1.0);\nreturn;\n#endif\ngl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);\nreturn;\n}\n#ifdef DEBUG_SSS_SAMPLES\nvec3 red =vec3(1.,0.,0.);\nvec3 blue=vec3(0.,0.,1.);\ngl_FragColor=vec4(mix(blue,red,clamp(float(sampleCount)/float(sampleBudget),0.0,1.0)),1.0);\nreturn;\n#endif\nfloat phase=0.;\nint n=min(sampleCount,sampleBudget);\nvec3 centerWeight =vec3(0.); \nvec3 totalIrradiance=vec3(0.);\nvec3 totalWeight =vec3(0.);\nfor (int i=0; i{if(!t.prePassRenderer||!t.subSurfaceConfiguration)return void p.Y.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering.");const i=this.texelSize;e.setFloat("metersPerUnit",t.subSurfaceConfiguration.metersPerUnit),e.setFloat2("texelSize",i.x,i.y),e.setTexture("irradianceSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(0)]),e.setTexture("depthSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(5)]),e.setTexture("albedoSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(7)]),e.setFloat2("viewportSize",Math.tan(t.activeCamera.fov/2)*t.getEngine().getAspectRatio(t.activeCamera,!0),Math.tan(t.activeCamera.fov/2)),e.setArray3("diffusionS",t.subSurfaceConfiguration.ssDiffusionS),e.setArray("diffusionD",t.subSurfaceConfiguration.ssDiffusionD),e.setArray("filterRadii",t.subSurfaceConfiguration.ssFilterRadii)}))}}class Fb{get ssDiffusionS(){return this._ssDiffusionS}get ssDiffusionD(){return this._ssDiffusionD}get ssFilterRadii(){return this._ssFilterRadii}constructor(e){this._ssDiffusionS=[],this._ssFilterRadii=[],this._ssDiffusionD=[],this.enabled=!1,this.needsImageProcessing=!0,this.name=Se.l.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[5,7,4,0],this.addDiffusionProfile(new a.Wo(1,1,1)),this._scene=e,Fb._SceneComponentInitialization(this._scene)}addDiffusionProfile(e){if(this.ssDiffusionD.length>=5)return p.Y.Error("You already reached the maximum number of diffusion profiles."),0;for(let t=0;t{throw(0,ge.S)("SubSurfaceSceneComponent")},n.p.AddParser(Se.l.NAME_SUBSURFACE,((e,t)=>{if(void 0!==e.ssDiffusionProfileColors&&null!==e.ssDiffusionProfileColors&&(t.enableSubSurfaceForPrePass(),t.subSurfaceConfiguration))for(let i=0,n=e.ssDiffusionProfileColors.length;i{let t=e._getComponent(Se.l.NAME_SUBSURFACE);t||(t=new wb(e),e._addComponent(t))};const Lb="outlinePixelShader",Bb="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ht.v.ShadersStore[Lb]=Bb;const Ub="outlineVertexShader",Vb="attribute vec3 position;\nattribute vec3 normal;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nuniform float offset;\n#include\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{\nvec3 positionUpdated=position;\nvec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\nvec3 offsetPosition=positionUpdated+(normalUpdated*offset);\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(offsetPosition,1.0);\ngl_Position=viewProjection*worldPos;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n#include\n}\n";Ht.v.ShadersStore[Ub]=Vb;N.x.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new kb(this)),this._outlineRenderer},Object.defineProperty(ee.Kj.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOutline=e},enumerable:!0,configurable:!0}),Object.defineProperty(ee.Kj.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOverlay=e},enumerable:!0,configurable:!0});class kb{constructor(e){this.name=Se.l.NAME_OUTLINERENDERER,this.zOffset=1,this.zOffsetUnits=4,this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this),this._passIdForDrawWrapper=[];for(let t=0;t<4;++t)this._passIdForDrawWrapper[t]=this._engine.createRenderPassId(`Outline Renderer (${t})`)}register(){this.scene._beforeRenderingMeshStage.registerStep(Se.l.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(Se.l.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){for(let e=0;e{p.setMatrix("world",t)})),r.setZOffset(0),r.setZOffsetUnits(0)}isReady(e,t,i){i=null!=i?i:this._passIdForDrawWrapper[0];const n=[],s=[ne.o.PositionKind,ne.o.NormalKind],r=e.getMesh(),o=e.getMaterial();if(!o)return!1;const a=r.getScene();o.needAlphaTesting()&&(n.push("#define ALPHATEST"),r.isVerticesDataPresent(ne.o.UVKind)&&(s.push(ne.o.UVKind),n.push("#define UV1")),r.isVerticesDataPresent(ne.o.UV2Kind)&&(s.push(ne.o.UV2Kind),n.push("#define UV2"))),o.useLogarithmicDepth&&n.push("#define LOGARITHMICDEPTH"),(0,ua.lK)(o,a,n),r.useBones&&r.computeBonesUsingShaders?(s.push(ne.o.MatricesIndicesKind),s.push(ne.o.MatricesWeightsKind),r.numBoneInfluencers>4&&(s.push(ne.o.MatricesIndicesExtraKind),s.push(ne.o.MatricesWeightsExtraKind)),n.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),n.push("#define BonesPerMesh "+(r.skeleton?r.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0");const l=r.morphTargetManager;let h=0;l&&l.numInfluencers>0&&(h=l.numInfluencers,n.push("#define MORPHTARGETS"),n.push("#define NUM_MORPH_INFLUENCERS "+h),l.isUsingTextureForTargets&&n.push("#define MORPHTARGETS_TEXTURE"),It.G.PrepareAttributesForMorphTargetsInfluencers(s,r,h)),t&&(n.push("#define INSTANCES"),It.G.PushAttributesForInstances(s),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES"));const c=e._getDrawWrapper(i,!0),d=c.defines,u=n.join("\n");if(d!==u){const e=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];(0,ua.qx)(e),c.setEffect(this.scene.getEngine().createEffect("outline",s,e,["diffuseSampler","morphTargets"],u,void 0,void 0,void 0,{maxSimultaneousMorphTargets:h}),u)}return c.effect.isReady()}_beforeRenderingMesh(e,t,i){if(this._savedDepthWrite=this._engine.getDepthWrite(),e.renderOutline){const n=t.getMaterial();n&&n.needAlphaBlendingForMesh(e)&&(this._engine.cacheStencilState(),this._engine.setDepthWrite(!1),this._engine.setColorWrite(!1),this._engine.setStencilBuffer(!0),this._engine.setStencilOperationPass(7681),this._engine.setStencilFunction(519),this._engine.setStencilMask(kb._StencilReference),this._engine.setStencilFunctionReference(kb._StencilReference),this._engine.stencilStateComposer.useStencilGlobalOnly=!0,this.render(t,i,!0,this._passIdForDrawWrapper[1]),this._engine.setColorWrite(!0),this._engine.setStencilFunction(517)),this._engine.setDepthWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[0]),this._engine.setDepthWrite(this._savedDepthWrite),n&&n.needAlphaBlendingForMesh(e)&&(this._engine.stencilStateComposer.useStencilGlobalOnly=!1,this._engine.restoreStencilState())}}_afterRenderingMesh(e,t,i){if(e.renderOverlay){const e=this._engine.getAlphaMode(),n=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(2),this.render(t,i,!0,this._passIdForDrawWrapper[3]),this._engine.setAlphaMode(e),this._engine.setDepthWrite(this._savedDepthWrite),this._engine.alphaState.alphaBlend=n}e.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[2]),this._engine.setColorWrite(!0))}}kb._StencilReference=4;var Gb;i(4511);class zb{get particleSize(){return this._particleSize}set particleSize(e){e!==this._particleSize&&(this._particleSize=e,this.onParticleSizeChanged.notifyObservers(this))}get useInstancing(){return!this.indexBuffer}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&this._hasVelocity()&&(this._useVelocity=e,this._effectsAreDirty=!0)}_hasVelocity(){var e;return!!(null===(e=this.vertexBuffers)||void 0===e?void 0:e.velocity)}get indexBuffer(){return null}getClassName(){return"FluidRenderingObject"}constructor(e){this.priority=0,this._particleSize=.1,this.onParticleSizeChanged=new r.y$,this.particleThicknessAlpha=.05,this._useVelocity=!1,this._scene=e,this._engine=e.getEngine(),this._effectsAreDirty=!0,this._depthEffectWrapper=null,this._thicknessEffectWrapper=null}_createEffects(){const e=["view","projection","particleRadius","size"],t=["position","offset"],i=[];this._effectsAreDirty=!1,this.useVelocity&&(t.push("velocity"),i.push("#define FLUIDRENDERING_VELOCITY")),this._scene.useRightHandedSystem&&i.push("#define FLUIDRENDERING_RHS"),this._depthEffectWrapper=new Ti({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:i}),e.push("particleAlpha"),this._thicknessEffectWrapper=new Ti({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleThickness",fragmentShader:"fluidRenderingParticleThickness",attributeNames:["position","offset"],uniformNames:e,samplerNames:[]})}isReady(){if(this._effectsAreDirty&&this._createEffects(),!this._depthEffectWrapper||!this._thicknessEffectWrapper)return!1;const e=this._depthEffectWrapper._drawWrapper.effect,t=this._thicknessEffectWrapper._drawWrapper.effect;return e.isReady()&&t.isReady()}renderDepthTexture(){const e=this.numParticles;if(!this._depthEffectWrapper||0===e)return;const t=this._depthEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat2("size",this._particleSize,this._particleSize),i.setFloat("particleRadius",this._particleSize/2),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}renderThicknessTexture(){const e=this.numParticles;if(!this._thicknessEffectWrapper||0===e)return;const t=this._thicknessEffectWrapper._drawWrapper,i=t.effect;this._engine.setAlphaMode(6),this._engine.setDepthWrite(!1),this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat("particleAlpha",this.particleThicknessAlpha),i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0)}renderDiffuseTexture(){}dispose(){var e,t;null===(e=this._depthEffectWrapper)||void 0===e||e.dispose(),null===(t=this._thicknessEffectWrapper)||void 0===t||t.dispose()}}class Wb extends zb{get particleSystem(){return this._particleSystem}getClassName(){return"FluidRenderingObjectParticleSystem"}get useTrueRenderingForDiffuseTexture(){return this._useTrueRenderingForDiffuseTexture}set useTrueRenderingForDiffuseTexture(e){this._useTrueRenderingForDiffuseTexture!==e&&(this._useTrueRenderingForDiffuseTexture=e,e?(this._particleSystem.blendMode=this._blendMode,this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null):(this._particleSystem.blendMode=-1,this._onBeforeDrawParticleObserver=this._particleSystem.onBeforeDrawParticlesObservable.add((()=>{this._engine.setAlphaMode(2)}))))}get vertexBuffers(){return this._particleSystem.vertexBuffers}get indexBuffer(){return this._particleSystem.indexBuffer}constructor(e,t){super(e),this._useTrueRenderingForDiffuseTexture=!0,this._particleSystem=t,this._originalRender=t.render.bind(t),this._blendMode=t.blendMode,this._onBeforeDrawParticleObserver=null,this._updateInAnimate=this._particleSystem.updateInAnimate,this._particleSystem.updateInAnimate=!0,this._particleSystem.render=()=>0,this.particleSize=(t.minSize+t.maxSize)/2,this.useTrueRenderingForDiffuseTexture=!1}isReady(){return super.isReady()&&this._particleSystem.isReady()}get numParticles(){return this._particleSystem.getActiveCount()}renderDiffuseTexture(){this._originalRender()}dispose(){super.dispose(),this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null,this._particleSystem.render=this._originalRender,this._particleSystem.blendMode=this._blendMode,this._particleSystem.updateInAnimate=this._updateInAnimate}}class Hb{get blurNumIterations(){return this._blurNumIterations}set blurNumIterations(e){if(this._blurNumIterations!==e&&(this._blurNumIterations=e,null!==this._blurPostProcesses)){const e=this._blurPostProcesses[0],t=this._blurPostProcesses[1];this._blurPostProcesses=[];for(let i=0;i<2*this._blurNumIterations;++i)this._blurPostProcesses[i]=1&i?t:e}}get renderTarget(){return this._rt}get renderTargetBlur(){return this._rtBlur}get texture(){return this._texture}get textureBlur(){return this._textureBlurred}constructor(e,t,i,n,s,o,a=1,l=6,h=1,c=6,d=!1,u=null,p=!0,f=1){this.enableBlur=!0,this.blurSizeDivisor=1,this.blurFilterSize=7,this._blurNumIterations=3,this.blurMaxFilterSize=100,this.blurDepthScale=10,this.particleSize=.02,this.onDisposeObservable=new r.y$,this._name=e,this._scene=t,this._camera=u,this._engine=t.getEngine(),this._width=i,this._height=n,this._blurTextureSizeX=s,this._blurTextureSizeY=o,this._textureType=a,this._textureFormat=l,this._blurTextureType=h,this._blurTextureFormat=c,this._useStandardBlur=d,this._generateDepthBuffer=p,this._samples=f,this._postProcessRunningIndex=0,this.enableBlur=0!==s&&0!==o,this._rt=null,this._texture=null,this._rtBlur=null,this._textureBlurred=null,this._blurPostProcesses=null}initialize(){if(this.dispose(),this._createRenderTarget(),this.enableBlur&&this._texture){const[e,t,i]=this._createBlurPostProcesses(this._texture,this._blurTextureType,this._blurTextureFormat,this.blurSizeDivisor,this._name,this._useStandardBlur);this._rtBlur=e,this._textureBlurred=t,this._blurPostProcesses=i}}applyBlurPostProcesses(){this.enableBlur&&this._blurPostProcesses&&(this._postProcessRunningIndex=0,this._scene.postProcessManager.directRender(this._blurPostProcesses,this._rtBlur,!0),this._engine.unBindFramebuffer(this._rtBlur))}_createRenderTarget(){this._rt=this._engine.createRenderTargetTexture({width:this._width,height:this._height},{generateMipMaps:!1,type:this._textureType,format:this._textureFormat,samplingMode:1,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTT-${this._name}`});const e=this._rt.texture;e.incrementReferences(),this._texture=new Le(null,this._scene),this._texture.name="rtt"+this._name,this._texture._texture=e,this._texture.wrapU=Le.CLAMP_ADDRESSMODE,this._texture.wrapV=Le.CLAMP_ADDRESSMODE,this._texture.anisotropicFilteringLevel=1}_createBlurPostProcesses(e,t,i,n,s,r=!1){const a=this._scene.getEngine(),l=new o.FM(Math.floor(this._blurTextureSizeX/n),Math.floor(this._blurTextureSizeY/n)),h=1===t&&a.getCaps().textureFloatLinearFiltering||2===t&&a.getCaps().textureHalfFloatLinearFiltering,c=this._engine.createRenderTargetTexture({width:l.x,height:l.y},{generateMipMaps:!1,type:t,format:i,samplingMode:h?2:1,generateDepthBuffer:!1,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTTBlur-${s}`}),d=c.texture;d.incrementReferences();const u=new Le(null,this._scene);if(u.name="rttBlurred"+s,u._texture=d,u.wrapU=Le.CLAMP_ADDRESSMODE,u.wrapV=Le.CLAMP_ADDRESSMODE,u.anisotropicFilteringLevel=1,r){const n=new Zt("BilateralBlurX","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);n.samples=this._samples,n.externalTextureSamplerBinding=!0,n.onApplyObservable.add((t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",n.inputTexture.texture),t.setInt("filterSize",this.blurFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),this._postProcessRunningIndex++})),n.onSizeChangedObservable.add((()=>{n._textures.forEach((e=>{e.texture.wrapU=Le.CLAMP_ADDRESSMODE,e.texture.wrapV=Le.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(n);const s=new Zt("BilateralBlurY","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);s.samples=this._samples,s.onApplyObservable.add((e=>{e.setInt("filterSize",this.blurFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),this._postProcessRunningIndex++})),s.onSizeChangedObservable.add((()=>{s._textures.forEach((e=>{e.texture.wrapU=Le.CLAMP_ADDRESSMODE,e.texture.wrapV=Le.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(s),n.autoClear=!1,s.autoClear=!1;const r=[];for(let e=0;e<2*this._blurNumIterations;++e)r[e]=1&e?s:n;return[c,u,r]}{const n=["maxFilterSize","blurDir","projectedParticleConstant","depthThreshold"],s=new Zt("BilateralBlurX","fluidRenderingBilateralBlur",n,null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);s.samples=this._samples,s.externalTextureSamplerBinding=!0,s.onApplyObservable.add((t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",s.inputTexture.texture),t.setInt("maxFilterSize",this.blurMaxFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),t.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),t.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++})),s.onSizeChangedObservable.add((()=>{s._textures.forEach((e=>{e.texture.wrapU=Le.CLAMP_ADDRESSMODE,e.texture.wrapV=Le.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(s);const r=new Zt("BilateralBlurY","fluidRenderingBilateralBlur",n,null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);r.samples=this._samples,r.onApplyObservable.add((e=>{e.setInt("maxFilterSize",this.blurMaxFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),e.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),e.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++})),r.onSizeChangedObservable.add((()=>{r._textures.forEach((e=>{e.texture.wrapU=Le.CLAMP_ADDRESSMODE,e.texture.wrapV=Le.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(r),s.autoClear=!1,r.autoClear=!1;const o=[];for(let e=0;e<2*this._blurNumIterations;++e)o[e]=1&e?r:s;return[c,u,o]}}_fixReusablePostProcess(e){e.isReusable()&&(e.onActivateObservable.add((()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2})),e.onApplyObservable.add((()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2})))}_getProjectedParticleConstant(){var e,t;return this.blurFilterSize*this.particleSize*.05*(this._height/2)/Math.tan((null!==(t=null===(e=this._camera)||void 0===e?void 0:e.fov)&&void 0!==t?t:45*Math.PI/180)/2)}_getDepthThreshold(){return this.particleSize/2*this.blurDepthScale}dispose(){var e,t,i,n;this.onDisposeObservable.hasObservers()&&this.onDisposeObservable.notifyObservers(this),null===(e=this._rt)||void 0===e||e.dispose(),this._rt=null,null===(t=this._texture)||void 0===t||t.dispose(),this._texture=null,null===(i=this._rtBlur)||void 0===i||i.dispose(),this._rtBlur=null,null===(n=this._textureBlurred)||void 0===n||n.dispose(),this._textureBlurred=null,this._blurPostProcesses&&(this._blurPostProcesses[0].dispose(),this._blurPostProcesses[1].dispose()),this._blurPostProcesses=null}}!function(e){e[e.DepthTexture=0]="DepthTexture",e[e.DepthBlurredTexture=1]="DepthBlurredTexture",e[e.ThicknessTexture=2]="ThicknessTexture",e[e.ThicknessBlurredTexture=3]="ThicknessBlurredTexture",e[e.DiffuseTexture=4]="DiffuseTexture",e[e.Normals=5]="Normals",e[e.DiffuseRendering=6]="DiffuseRendering"}(Gb||(Gb={}));class Xb{get needInitialization(){return this._needInitialization}get generateDiffuseTexture(){return this._generateDiffuseTexture}set generateDiffuseTexture(e){this._generateDiffuseTexture!==e&&(this._generateDiffuseTexture=e,this._needInitialization=!0)}get debugFeature(){return this._debugFeature}set debugFeature(e){this._debugFeature!==e&&(this._needInitialization=!0,this._debugFeature=e)}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._needInitialization=!0)}get environmentMap(){return this._environmentMap}set environmentMap(e){this._environmentMap!==e&&(this._needInitialization=!0,this._environmentMap=e)}get enableBlurDepth(){return this._enableBlurDepth}set enableBlurDepth(e){this._enableBlurDepth!==e&&(this._enableBlurDepth=e,this._needInitialization=!0)}get blurDepthSizeDivisor(){return this._blurDepthSizeDivisor}set blurDepthSizeDivisor(e){this._blurDepthSizeDivisor!==e&&(this._blurDepthSizeDivisor=e,this._needInitialization=!0)}get blurDepthFilterSize(){return this._blurDepthFilterSize}set blurDepthFilterSize(e){this._blurDepthFilterSize!==e&&(this._blurDepthFilterSize=e,this._setBlurParameters())}get blurDepthNumIterations(){return this._blurDepthNumIterations}set blurDepthNumIterations(e){this._blurDepthNumIterations!==e&&(this._blurDepthNumIterations=e,this._setBlurParameters())}get blurDepthMaxFilterSize(){return this._blurDepthMaxFilterSize}set blurDepthMaxFilterSize(e){this._blurDepthMaxFilterSize!==e&&(this._blurDepthMaxFilterSize=e,this._setBlurParameters())}get blurDepthDepthScale(){return this._blurDepthDepthScale}set blurDepthDepthScale(e){this._blurDepthDepthScale!==e&&(this._blurDepthDepthScale=e,this._setBlurParameters())}get enableBlurThickness(){return this._enableBlurThickness}set enableBlurThickness(e){this._enableBlurThickness!==e&&(this._enableBlurThickness=e,this._needInitialization=!0)}get blurThicknessSizeDivisor(){return this._blurThicknessSizeDivisor}set blurThicknessSizeDivisor(e){this._blurThicknessSizeDivisor!==e&&(this._blurThicknessSizeDivisor=e,this._needInitialization=!0)}get blurThicknessFilterSize(){return this._blurThicknessFilterSize}set blurThicknessFilterSize(e){this._blurThicknessFilterSize!==e&&(this._blurThicknessFilterSize=e,this._setBlurParameters())}get blurThicknessNumIterations(){return this._blurThicknessNumIterations}set blurThicknessNumIterations(e){this._blurThicknessNumIterations!==e&&(this._blurThicknessNumIterations=e,this._setBlurParameters())}get useFixedThickness(){return this._useFixedThickness}set useFixedThickness(e){this._useFixedThickness!==e&&(this._useFixedThickness=e,this._needInitialization=!0)}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&(this._useVelocity=e,this._needInitialization=!0,this._onUseVelocityChanged.notifyObservers(this))}get depthMapSize(){return this._depthMapSize}set depthMapSize(e){this._depthMapSize!==e&&(this._depthMapSize=e,this._needInitialization=!0)}get thicknessMapSize(){return this._thicknessMapSize}set thicknessMapSize(e){this._thicknessMapSize!==e&&(this._thicknessMapSize=e,this._needInitialization=!0)}get diffuseMapSize(){return this._diffuseMapSize}set diffuseMapSize(e){this._diffuseMapSize!==e&&(this._diffuseMapSize=e,this._needInitialization=!0)}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._needInitialization=!0)}get camera(){return this._camera}constructor(e,t){this._generateDiffuseTexture=!1,this.fluidColor=new a.Wo(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new o.P(-2,-1,1).normalize(),this._debugFeature=Gb.DepthBlurredTexture,this._debug=!1,this._enableBlurDepth=!0,this._blurDepthSizeDivisor=1,this._blurDepthFilterSize=7,this._blurDepthNumIterations=3,this._blurDepthMaxFilterSize=100,this._blurDepthDepthScale=10,this._enableBlurThickness=!0,this._blurThicknessSizeDivisor=1,this._blurThicknessFilterSize=5,this._blurThicknessNumIterations=1,this._useFixedThickness=!1,this._onUseVelocityChanged=new r.y$,this._useVelocity=!1,this._depthMapSize=null,this._thicknessMapSize=null,this._diffuseMapSize=null,this._samples=1,this._scene=e,this._engine=e.getEngine(),this._camera=null!=t?t:e.activeCamera,this._needInitialization=!0,this._bgDepthTexture=null,this._invProjectionMatrix=new o.y3,this._depthClearColor=new a.HE(1e6,1e6,1e6,1),this._thicknessClearColor=new a.HE(0,0,0,1),this._depthRenderTarget=null,this._diffuseRenderTarget=null,this._thicknessRenderTarget=null,this._renderPostProcess=null}_initialize(){var e,t,i;this.dispose(),this._needInitialization=!1;const n=null!==(e=this._depthMapSize)&&void 0!==e?e:this._engine.getRenderWidth(),s=null!==this._depthMapSize?Math.round(this._depthMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();if(this._depthRenderTarget=new Hb("Depth",this._scene,n,s,n,s,1,7,1,7,!1,this._camera,!0,this._samples),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){const e=null!==(t=this._diffuseMapSize)&&void 0!==t?t:this._engine.getRenderWidth(),i=null!==this._diffuseMapSize?Math.round(this._diffuseMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._diffuseRenderTarget=new Hb("Diffuse",this._scene,e,i,0,0,0,5,0,5,!0,this._camera,!0,this._samples),this._initializeRenderTarget(this._diffuseRenderTarget)}const r=null!==(i=this._thicknessMapSize)&&void 0!==i?i:this._engine.getRenderWidth(),o=null!==this._thicknessMapSize?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new Hb("Thickness",this._scene,r,o,r,o,2,6,2,6,!0,this._camera,!1,this._samples),this._initializeRenderTarget(this._thicknessRenderTarget)),this._createLiquidRenderingPostProcess()}_setBlurParameters(e=null){null!==e&&e!==this._depthRenderTarget||this._setBlurDepthParameters(),null!==e&&e!==this._thicknessRenderTarget||this._setBlurThicknessParameters()}_setBlurDepthParameters(){this._depthRenderTarget&&(this._depthRenderTarget.blurFilterSize=this.blurDepthFilterSize,this._depthRenderTarget.blurMaxFilterSize=this.blurDepthMaxFilterSize,this._depthRenderTarget.blurNumIterations=this.blurDepthNumIterations,this._depthRenderTarget.blurDepthScale=this.blurDepthDepthScale)}_setBlurThicknessParameters(){this._thicknessRenderTarget&&(this._thicknessRenderTarget.blurFilterSize=this.blurThicknessFilterSize,this._thicknessRenderTarget.blurNumIterations=this.blurThicknessNumIterations)}_initializeRenderTarget(e){e!==this._diffuseRenderTarget&&(e.enableBlur=e===this._depthRenderTarget?this.enableBlurDepth:this.enableBlurThickness,e.blurSizeDivisor=e===this._depthRenderTarget?this.blurDepthSizeDivisor:this.blurThicknessSizeDivisor),this._setBlurParameters(e),e.initialize()}_createLiquidRenderingPostProcess(){var e;const t=this._scene.getEngine(),i=["viewMatrix","projectionMatrix","invProjectionMatrix","texelSize","dirLight","cameraFar","density","refractionStrength","fresnelClamp","specularPower"],n=["depthSampler"],s=[];if(this.dispose(!0),!this._camera)return;const r=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,a=new o.FM(1/r.getSize().width,1/r.getSize().height);if(this._scene.useRightHandedSystem&&s.push("#define FLUIDRENDERING_RHS"),null!==this._environmentMap){(null!==(e=this._environmentMap)&&void 0!==e?e:this._scene.environmentTexture)&&(n.push("reflectionSampler"),s.push("#define FLUIDRENDERING_ENVIRONMENT"))}this._diffuseRenderTarget?(n.push("diffuseSampler"),s.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):i.push("diffuseColor"),this._useVelocity&&(n.push("velocitySampler"),s.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(i.push("thickness"),n.push("bgDepthSampler"),s.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(i.push("minimumThickness"),n.push("thicknessSampler")),this._debug&&(s.push("#define FLUIDRENDERING_DEBUG"),this._debugFeature===Gb.Normals?s.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):this._debugFeature===Gb.DiffuseRendering?s.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(s.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),n.push("debugSampler"),this._debugFeature!==Gb.DepthTexture&&this._debugFeature!==Gb.DepthBlurredTexture||s.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new Zt("FluidRendering","fluidRenderingRender",i,n,1,null,2,t,!1,null,0,void 0,void 0,!0,void 0),this._renderPostProcess.updateEffect(s.join("\n")),this._renderPostProcess.samples=this._samples,this._renderPostProcess.onApplyObservable.add((e=>{var i,n,s,r,o,l,h,c,d,u,p,f,_,m,g,v,T,S,E,x,b,C,y;if(this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix()),this._invProjectionMatrix.invert(),t.isWebGPU&&e.setTextureSampler("textureSamplerSampler",this._renderPostProcess.inputTexture.texture),this._depthRenderTarget.enableBlur?(e.setTexture("depthSampler",this._depthRenderTarget.textureBlur),t.isWebGPU&&e.setTextureSampler("depthSamplerSampler",null!==(r=null===(s=this._depthRenderTarget.textureBlur)||void 0===s?void 0:s.getInternalTexture())&&void 0!==r?r:null)):(e.setTexture("depthSampler",this._depthRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("depthSamplerSampler",null!==(n=null===(i=this._depthRenderTarget.texture)||void 0===i?void 0:i.getInternalTexture())&&void 0!==n?n:null)),this._diffuseRenderTarget?this._diffuseRenderTarget.enableBlur?(e.setTexture("diffuseSampler",this._diffuseRenderTarget.textureBlur),t.isWebGPU&&e.setTextureSampler("diffuseSamplerSampler",null!==(c=null===(h=this._diffuseRenderTarget.textureBlur)||void 0===h?void 0:h.getInternalTexture())&&void 0!==c?c:null)):(e.setTexture("diffuseSampler",this._diffuseRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("diffuseSamplerSampler",null!==(l=null===(o=this._diffuseRenderTarget.texture)||void 0===o?void 0:o.getInternalTexture())&&void 0!==l?l:null)):e.setColor3("diffuseColor",this.fluidColor),this._useFixedThickness?(e.setFloat("thickness",this.minimumThickness),e._bindTexture("bgDepthSampler",this._bgDepthTexture),t.isWebGPU&&e.setTextureSampler("bgDepthSamplerSampler",null!==(d=this._bgDepthTexture)&&void 0!==d?d:null)):(this._thicknessRenderTarget.enableBlur?(e.setTexture("thicknessSampler",this._thicknessRenderTarget.textureBlur),t.isWebGPU&&e.setTextureSampler("thicknessSamplerSampler",null!==(_=null===(f=this._thicknessRenderTarget.textureBlur)||void 0===f?void 0:f.getInternalTexture())&&void 0!==_?_:null)):(e.setTexture("thicknessSampler",this._thicknessRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("thicknessSamplerSampler",null!==(p=null===(u=this._thicknessRenderTarget.texture)||void 0===u?void 0:u.getInternalTexture())&&void 0!==p?p:null)),e.setFloat("minimumThickness",this.minimumThickness)),null!==this._environmentMap){const i=null!==(m=this._environmentMap)&&void 0!==m?m:this._scene.environmentTexture;i&&(e.setTexture("reflectionSampler",i),t.isWebGPU&&e.setTextureSampler("reflectionSamplerSampler",null!==(g=null==i?void 0:i.getInternalTexture())&&void 0!==g?g:null))}if(e.setMatrix("viewMatrix",this._scene.getViewMatrix()),e.setMatrix("invProjectionMatrix",this._invProjectionMatrix),e.setMatrix("projectionMatrix",this._scene.getProjectionMatrix()),e.setVector2("texelSize",a),e.setFloat("density",this.density),e.setFloat("refractionStrength",this.refractionStrength),e.setFloat("fresnelClamp",this.fresnelClamp),e.setFloat("specularPower",this.specularPower),e.setVector3("dirLight",this.dirLight),e.setFloat("cameraFar",this._camera.maxZ),this._debug){let i=null;switch(this._debugFeature){case Gb.DepthTexture:i=this._depthRenderTarget.texture;break;case Gb.DepthBlurredTexture:i=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture;break;case Gb.ThicknessTexture:i=null!==(T=null===(v=this._thicknessRenderTarget)||void 0===v?void 0:v.texture)&&void 0!==T?T:null;break;case Gb.ThicknessBlurredTexture:i=(null===(S=this._thicknessRenderTarget)||void 0===S?void 0:S.enableBlur)?null!==(x=null===(E=this._thicknessRenderTarget)||void 0===E?void 0:E.textureBlur)&&void 0!==x?x:null:null!==(C=null===(b=this._thicknessRenderTarget)||void 0===b?void 0:b.texture)&&void 0!==C?C:null;break;case Gb.DiffuseTexture:this._diffuseRenderTarget&&(i=this._diffuseRenderTarget.texture)}this._debugFeature!==Gb.Normals&&(e.setTexture("debugSampler",i),t.isWebGPU&&e.setTextureSampler("debugSamplerSampler",null!==(y=null==i?void 0:i.getInternalTexture())&&void 0!==y?y:null))}}))}_clearTargets(){var e,t,i;(null===(e=this._depthRenderTarget)||void 0===e?void 0:e.renderTarget)&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),this._engine.clear(this._depthClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),(null===(t=this._diffuseRenderTarget)||void 0===t?void 0:t.renderTarget)&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),(null===(i=this._thicknessRenderTarget)||void 0===i?void 0:i.renderTarget)&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!1,!1),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget))}_render(e){var t,i,n,s,r,o;if(this._needInitialization||!e.isReady())return;const a=this._engine._currentRenderTarget;this._engine.setState(!1,void 0,void 0,void 0,!0),this._engine.setDepthBuffer(!0),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0),(null===(t=this._depthRenderTarget)||void 0===t?void 0:t.renderTarget)&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),e.renderDepthTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),(null===(i=this._diffuseRenderTarget)||void 0===i?void 0:i.renderTarget)&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),e.renderDiffuseTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),(null===(n=this._thicknessRenderTarget)||void 0===n?void 0:n.renderTarget)&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),e.renderThicknessTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget)),null===(s=this._depthRenderTarget)||void 0===s||s.applyBlurPostProcesses(),null===(r=this._diffuseRenderTarget)||void 0===r||r.applyBlurPostProcesses(),null===(o=this._thicknessRenderTarget)||void 0===o||o.applyBlurPostProcesses(),a&&this._engine.bindFramebuffer(a)}dispose(e=!1){var t,i,n,s;e||(null===(t=this._depthRenderTarget)||void 0===t||t.dispose(),this._depthRenderTarget=null,null===(i=this._diffuseRenderTarget)||void 0===i||i.dispose(),this._diffuseRenderTarget=null,null===(n=this._thicknessRenderTarget)||void 0===n||n.dispose(),this._thicknessRenderTarget=null),this._renderPostProcess&&this._camera&&this._camera.detachPostProcess(this._renderPostProcess),null===(s=this._renderPostProcess)||void 0===s||s.dispose(),this._renderPostProcess=null,this._needInitialization=!1}}class Yb extends zb{getClassName(){return"FluidRenderingObjectCustomParticles"}get vertexBuffers(){return this._vertexBuffers}constructor(e,t,i){super(e),this._numParticles=i,this._diffuseEffectWrapper=null,this._vertexBuffers={},this.addBuffers(t)}addBuffers(e){for(const t in e){let i,n=!0;switch(t){case"velocity":i=3;break;case"offset":n=!1}this._vertexBuffers[t]=new ne.o(this._engine,e[t],t,!0,!1,i,n)}}_createEffects(){super._createEffects();this._diffuseEffectWrapper=new Ti({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDiffuse",fragmentShader:"fluidRenderingParticleDiffuse",attributeNames:["position","offset","color"],uniformNames:["view","projection","size"],samplerNames:[]})}isReady(){var e,t;return this._vertexBuffers.offset||(this._vertexBuffers.offset=new ne.o(this._engine,[0,0,1,0,0,1,1,1],"offset",!1,!1,2)),super.isReady()&&null!==(t=null===(e=this._diffuseEffectWrapper)||void 0===e?void 0:e.effect.isReady())&&void 0!==t&&t}get numParticles(){return this._numParticles}setNumParticles(e){this._numParticles=e}renderDiffuseTexture(){const e=this.numParticles;if(!this._diffuseEffectWrapper||0===e)return;const t=this._diffuseEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),null!==this._particleSize&&i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}dispose(){var e;super.dispose(),null===(e=this._diffuseEffectWrapper)||void 0===e||e.dispose();for(const t in this._vertexBuffers)this._vertexBuffers[t].dispose();this._vertexBuffers={}}}const jb="copyTextureToTexturePixelShader",Kb="uniform float conversion;\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#include\nvoid main(void) \n{\nvec4 color=texture2D(textureSampler,vUV);\n#ifdef DEPTH_TEXTURE\ngl_FragDepth=color.r;\n#else\nif (conversion==1.) {\ncolor=toLinearSpace(color);\n} else if (conversion==2.) {\ncolor=toGammaSpace(color);\n}\ngl_FragColor=color;\n#endif\n}\n";Ht.v.ShadersStore[jb]=Kb;var qb;!function(e){e[e.None=0]="None",e[e.ToLinearSpace=1]="ToLinearSpace",e[e.ToGammaSpace=2]="ToGammaSpace"}(qb||(qb={}));class $b{_textureIsInternal(e){return void 0===e.getInternalTexture}constructor(e,t=!1){this._engine=e,this._isDepthTexture=t,this._renderer=new vi(e),this._effectWrapper=new Ti({engine:e,name:"CopyTextureToTexture",fragmentShader:"copyTextureToTexture",useShaderStore:!0,uniformNames:["conversion"],samplerNames:["textureSampler"],defines:t?["#define DEPTH_TEXTURE"]:[]}),this._effectWrapper.onApplyObservable.add((()=>{t&&(e.setState(!1),e.setDepthBuffer(!0),e.depthCullingState.depthMask=!0,e.depthCullingState.depthFunc=519),this._textureIsInternal(this._source)?this._effectWrapper.effect._bindTexture("textureSampler",this._source):this._effectWrapper.effect.setTexture("textureSampler",this._source),this._effectWrapper.effect.setFloat("conversion",this._conversion)}))}isReady(){return this._effectWrapper.effect.isReady()}copy(e,t,i=qb.None){if(!this.isReady())return!1;this._source=e,this._conversion=i;const n=this._engine.depthCullingState.depthFunc;return this._renderer.render(this._effectWrapper,t),this._isDepthTexture&&n&&(this._engine.depthCullingState.depthFunc=n),!0}dispose(){this._effectWrapper.dispose(),this._renderer.dispose()}}class Qb{get depthRTWrapper(){return this._depthRTWrapper}constructor(e,t,i,n=1){this._engine=e,this._copyTextureToTexture=new $b(e,!0),this._depthRTWrapper=this._engine.createRenderTargetTexture({width:t,height:i},{generateMipMaps:!1,type:0,format:6,samplingMode:1,generateDepthBuffer:!0,generateStencilBuffer:!1,samples:n,noColorAttachment:!0,label:"FluidRenderingDepthTextureCopyRTT"}),this._depthRTWrapper.createDepthStencilTexture(0,!1,!1,1,void 0,"FluidRenderingDepthTextureCopyRTTDepthStencil")}copy(e){return this._copyTextureToTexture.copy(e,this._depthRTWrapper)}dispose(){this._depthRTWrapper.dispose(),this._copyTextureToTexture.dispose()}}const Zb="fluidRenderingParticleDepthVertexShader",Jb="attribute vec3 position;\nattribute vec2 offset;\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 size;\nvarying vec2 uv;\nvarying vec3 viewPos;\nvarying float sphereRadius;\n#ifdef FLUIDRENDERING_VELOCITY\nattribute vec3 velocity;\nvarying float velocityNorm;\n#endif\nvoid main(void) {\nvec3 cornerPos;\ncornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;\ncornerPos.z=0.0;\nviewPos=(view*vec4(position,1.0)).xyz;\ngl_Position=projection*vec4(viewPos+cornerPos,1.0);\nuv=offset;\nsphereRadius=size.x/2.0;\n#ifdef FLUIDRENDERING_VELOCITY\nvelocityNorm=length(velocity);\n#endif\n}\n";Ht.v.ShadersStore[Zb]=Jb;const eC="fluidRenderingParticleDepthPixelShader",tC="uniform mat4 projection;\nvarying vec2 uv;\nvarying vec3 viewPos;\nvarying float sphereRadius;\n#ifdef FLUIDRENDERING_VELOCITY\nvarying float velocityNorm;\n#endif\nvoid main(void) {\nvec3 normal;\nnormal.xy=uv*2.0-1.0;\nfloat r2=dot(normal.xy,normal.xy);\nif (r2>1.0) discard;\nnormal.z=sqrt(1.0-r2);\n#ifndef FLUIDRENDERING_RHS\nnormal.z=-normal.z;\n#endif\nvec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);\nvec4 clipSpacePos=projection*realViewPos;\n#ifdef WEBGPU\ngl_FragDepth=clipSpacePos.z/clipSpacePos.w;\n#else\ngl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5;\n#endif\n#ifdef FLUIDRENDERING_RHS\nrealViewPos.z=-realViewPos.z;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nglFragColor=vec4(realViewPos.z,velocityNorm,0.,1.);\n#else\nglFragColor=vec4(realViewPos.z,0.,0.,1.);\n#endif\n}\n";Ht.v.ShadersStore[eC]=tC;const iC="fluidRenderingParticleThicknessVertexShader",nC="attribute vec3 position;\nattribute vec2 offset;\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 size;\nvarying vec2 uv;\nvoid main(void) {\nvec3 cornerPos;\ncornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;\ncornerPos.z=0.0;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;\ngl_Position=projection*vec4(viewPos,1.0);\nuv=offset;\n}\n";Ht.v.ShadersStore[iC]=nC;const sC="fluidRenderingParticleThicknessPixelShader",rC="uniform float particleAlpha;\nvarying vec2 uv;\nvoid main(void) {\nvec3 normal;\nnormal.xy=uv*2.0-1.0;\nfloat r2=dot(normal.xy,normal.xy);\nif (r2>1.0) discard;\nfloat thickness=sqrt(1.0-r2);\nglFragColor=vec4(vec3(particleAlpha*thickness),1.0);\n}\n";Ht.v.ShadersStore[sC]=rC;const oC="fluidRenderingParticleDiffuseVertexShader",aC="attribute vec3 position;\nattribute vec2 offset;\nattribute vec4 color;\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 size;\nvarying vec2 uv;\nvarying vec3 diffuseColor;\nvoid main(void) {\nvec3 cornerPos;\ncornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;\ncornerPos.z=0.0;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;\ngl_Position=projection*vec4(viewPos,1.0);\nuv=offset;\ndiffuseColor=color.rgb;\n}\n";Ht.v.ShadersStore[oC]=aC;const lC="fluidRenderingParticleDiffusePixelShader",hC="uniform float particleAlpha;\nvarying vec2 uv;\nvarying vec3 diffuseColor;\nvoid main(void) {\nvec3 normal;\nnormal.xy=uv*2.0-1.0;\nfloat r2=dot(normal.xy,normal.xy);\nif (r2>1.0) discard;\nglFragColor=vec4(diffuseColor,1.0);\n}\n";Ht.v.ShadersStore[lC]=hC;const cC="fluidRenderingBilateralBlurPixelShader",dC="uniform sampler2D textureSampler;\nuniform int maxFilterSize;\nuniform vec2 blurDir;\nuniform float projectedParticleConstant;\nuniform float depthThreshold;\nvarying vec2 vUV;\nvoid main(void) {\nfloat depth=textureLod(textureSampler,vUV,0.).x;\nif (depth>=1e6 || depth<=0.) {\nglFragColor=vec4(vec3(depth),1.);\nreturn;\n}\nint filterSize=min(maxFilterSize,int(ceil(projectedParticleConstant/depth)));\nfloat sigma=float(filterSize)/3.0;\nfloat two_sigma2=2.0*sigma*sigma;\nfloat sigmaDepth=depthThreshold/3.0;\nfloat two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;\nfloat sum=0.;\nfloat wsum=0.;\nfloat sumVel=0.;\nfor (int x=-filterSize; x<=filterSize; ++x) {\nvec2 coords=vec2(x);\nvec2 sampleDepthVel=textureLod(textureSampler,vUV+coords*blurDir,0.).rg;\nfloat r=dot(coords,coords);\nfloat w=exp(-r/two_sigma2);\nfloat rDepth=sampleDepthVel.r-depth;\nfloat wd=exp(-rDepth*rDepth/two_sigmaDepth2);\nsum+=sampleDepthVel.r*w*wd;\nsumVel+=sampleDepthVel.g*w*wd;\nwsum+=w*wd;\n}\nglFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);\n}\n";Ht.v.ShadersStore[cC]=dC;const uC="fluidRenderingStandardBlurPixelShader",pC="uniform sampler2D textureSampler;\nuniform int filterSize;\nuniform vec2 blurDir;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 s=textureLod(textureSampler,vUV,0.);\nif (s.r==0.) {\nglFragColor=vec4(0.,0.,0.,1.);\nreturn;\n}\nfloat sigma=float(filterSize)/3.0;\nfloat twoSigma2=2.0*sigma*sigma;\nvec4 sum=vec4(0.);\nfloat wsum=0.;\nfor (int x=-filterSize; x<=filterSize; ++x) {\nvec2 coords=vec2(x);\nvec4 sampl=textureLod(textureSampler,vUV+coords*blurDir,0.);\nfloat w=exp(-coords.x*coords.x/twoSigma2);\nsum+=sampl*w;\nwsum+=w;\n}\nsum/=wsum;\nglFragColor=vec4(sum.rgb,1.);\n}\n";Ht.v.ShadersStore[uC]=pC;const fC="fluidRenderingRenderPixelShader",_C="/* disable_uniformity_analysis */\n#define IOR 1.333\n#define ETA 1.0/IOR\n#define F0 0.02\nuniform sampler2D textureSampler;\nuniform sampler2D depthSampler;\n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nuniform sampler2D diffuseSampler;\n#else\nuniform vec3 diffuseColor;\n#endif\n#ifdef FLUIDRENDERING_FIXED_THICKNESS\nuniform float thickness;\nuniform sampler2D bgDepthSampler;\n#else\nuniform float minimumThickness;\nuniform sampler2D thicknessSampler;\n#endif\n#ifdef FLUIDRENDERING_ENVIRONMENT\nuniform samplerCube reflectionSampler;\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nuniform sampler2D debugSampler;\n#endif\nuniform mat4 viewMatrix;\nuniform mat4 projectionMatrix;\nuniform mat4 invProjectionMatrix;\nuniform vec2 texelSize;\nuniform vec3 dirLight;\nuniform float cameraFar;\nuniform float density;\nuniform float refractionStrength;\nuniform float fresnelClamp;\nuniform float specularPower;\nvarying vec2 vUV;\nvec3 computeViewPosFromUVDepth(vec2 texCoord,float depth) {\nvec4 ndc;\nndc.xy=texCoord*2.0-1.0;\n#ifdef FLUIDRENDERING_RHS\nndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth;\n#else\nndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth;\n#endif\nndc.w=1.0;\nvec4 eyePos=invProjectionMatrix*ndc;\neyePos.xyz/=eyePos.w;\nreturn eyePos.xyz;\n}\nvec3 getViewPosFromTexCoord(vec2 texCoord) {\nfloat depth=textureLod(depthSampler,texCoord,0.).x;\nreturn computeViewPosFromUVDepth(texCoord,depth);\n}\nvoid main(void) {\nvec2 texCoord=vUV;\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nvec4 color=texture2D(debugSampler,texCoord);\n#ifdef FLUIDRENDERING_DEBUG_DEPTH\nglFragColor=vec4(color.rgb/vec3(2.0),1.);\nif (color.r>0.999 && color.g>0.999) {\nglFragColor=texture2D(textureSampler,texCoord);\n}\n#else\nglFragColor=vec4(color.rgb,1.);\nif (color.r<0.001 && color.g<0.001 && color.b<0.001) {\nglFragColor=texture2D(textureSampler,texCoord);\n}\n#endif\nreturn;\n#endif\nvec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;\nfloat depth=depthVel.r;\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nfloat thickness=texture2D(thicknessSampler,texCoord).x;\n#else\nfloat bgDepth=texture2D(bgDepthSampler,texCoord).x;\nfloat depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;\ndepthNonLinear=depthNonLinear*0.5+0.5;\n#endif\nvec4 backColor=texture2D(textureSampler,texCoord);\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nif (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) {\n#else\nif (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) {\n#endif\nglFragColor=backColor;\nreturn;\n}\nvec3 viewPos=computeViewPosFromUVDepth(texCoord,depth);\nvec3 ddx=getViewPosFromTexCoord(texCoord+vec2(texelSize.x,0.))-viewPos;\nvec3 ddy=getViewPosFromTexCoord(texCoord+vec2(0.,texelSize.y))-viewPos;\nvec3 ddx2=viewPos-getViewPosFromTexCoord(texCoord+vec2(-texelSize.x,0.));\nif (abs(ddx.z)>abs(ddx2.z)) {\nddx=ddx2;\n}\nvec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));\nif (abs(ddy.z)>abs(ddy2.z)) {\nddy=ddy2;\n}\nvec3 normal=normalize(cross(ddy,ddx));\n#ifdef FLUIDRENDERING_RHS\nnormal=-normal;\n#endif\n#ifndef WEBGPU\nif(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {\nnormal=vec3(0.,0.,-1.);\n}\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL)\nglFragColor=vec4(normal*0.5+0.5,1.0);\nreturn;\n#endif\nvec3 rayDir=normalize(viewPos); \n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nvec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb;\n#endif\nvec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));\nvec3 H =normalize(lightDir-rayDir);\nfloat specular=pow(max(0.0,dot(H,normal)),specularPower);\n#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING\nfloat diffuse =max(0.0,dot(lightDir,normal))*1.0;\nglFragColor=vec4(vec3(0.1) /*ambient*/+vec3(0.42,0.50,1.00)*diffuse+vec3(0,0,0.2)+specular,1.);\nreturn;\n#endif\nvec3 refractionDir=refract(rayDir,normal,ETA);\nvec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0);\nvec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); \nvec3 refractionColor=transmitted.rgb*transmittance;\n#ifdef FLUIDRENDERING_ENVIRONMENT\nvec3 reflectionDir=reflect(rayDir,normal);\nvec3 reflectionColor=(textureCube(reflectionSampler,reflectionDir).rgb);\nfloat fresnel=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,fresnelClamp);\nvec3 finalColor=mix(refractionColor,reflectionColor,fresnel)+specular;\n#else\nvec3 finalColor=refractionColor+specular;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nfloat velocity=depthVel.g;\nfinalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0));\n#endif\nglFragColor=vec4(finalColor,transmitted.a);\n}\n";Ht.v.ShadersStore[fC]=_C;function mC(e){return!!e.particleSystem}Object.defineProperty(N.x.prototype,"fluidRenderer",{get:function(){return this._fluidRenderer},set:function(e){this._fluidRenderer=e},enumerable:!0,configurable:!0}),N.x.prototype.enableFluidRenderer=function(){return this._fluidRenderer||(this._fluidRenderer=new vC(this)),this._fluidRenderer},N.x.prototype.disableFluidRenderer=function(){var e;null===(e=this._fluidRenderer)||void 0===e||e.dispose(),this._fluidRenderer=null};class gC{constructor(e){this.name=Se.l.NAME_FLUIDRENDERER,this.scene=e}register(){this.scene._gatherActiveCameraRenderTargetsStage.registerStep(Se.l.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER,this,this._gatherActiveCameraRenderTargets),this.scene._afterCameraDrawStage.registerStep(Se.l.STEP_AFTERCAMERADRAW_FLUIDRENDERER,this,this._afterCameraDraw)}_gatherActiveCameraRenderTargets(e){var t;null===(t=this.scene.fluidRenderer)||void 0===t||t._prepareRendering()}_afterCameraDraw(e){var t;null===(t=this.scene.fluidRenderer)||void 0===t||t._render(e)}rebuild(){this.scene._fluidRenderer&&(this.scene.disableFluidRenderer(),this.scene.enableFluidRenderer())}dispose(){this.scene.disableFluidRenderer()}}class vC{static _SceneComponentInitialization(e){let t=e._getComponent(Se.l.NAME_FLUIDRENDERER);t||(t=new gC(e),e._addComponent(t))}constructor(e){this._scene=e,this._engine=e.getEngine(),this._onEngineResizeObserver=null,this.renderObjects=[],this.targetRenderers=[],this._cameras=new Map,vC._SceneComponentInitialization(this._scene),this._onEngineResizeObserver=this._engine.onResizeObservable.add((()=>{this._initialize()}))}recreate(){this._sortRenderingObjects(),this._initialize()}getRenderObjectFromParticleSystem(e){const t=this._getParticleSystemIndex(e);return-1!==t?this.renderObjects[t]:null}addParticleSystem(e,t,i,n){const s=new Wb(this._scene,e);s.onParticleSizeChanged.add(this._setParticleSizeForRenderTargets.bind(this)),i||(i=new Xb(this._scene,n),this.targetRenderers.push(i)),i._onUseVelocityChanged.hasObservers()||i._onUseVelocityChanged.add(this._setUseVelocityForRenderObject.bind(this)),void 0!==t&&(i.generateDiffuseTexture=t);const r={object:s,targetRenderer:i};return this.renderObjects.push(r),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),r}addCustomParticles(e,t,i,n,s){const r=new Yb(this._scene,e,t);r.onParticleSizeChanged.add(this._setParticleSizeForRenderTargets.bind(this)),n||(n=new Xb(this._scene,s),this.targetRenderers.push(n)),n._onUseVelocityChanged.hasObservers()||n._onUseVelocityChanged.add(this._setUseVelocityForRenderObject.bind(this)),void 0!==i&&(n.generateDiffuseTexture=i);const o={object:r,targetRenderer:n};return this.renderObjects.push(o),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),o}removeRenderObject(e,t=!0){const i=this.renderObjects.indexOf(e);return-1!==i&&(e.object.dispose(),this.renderObjects.splice(i,1),t&&this._removeUnusedTargetRenderers()?this._initialize():this._setParticleSizeForRenderTargets(),!0)}_sortRenderingObjects(){this.renderObjects.sort(((e,t)=>e.object.priorityt.object.priority?1:0))}_removeUnusedTargetRenderers(){const e={};for(let n=0;n{var e;s.inputTexture.depthStencilTexture||s.inputTexture.createDepthStencilTexture(0,!0,this._engine.isStencilEnable,r[0].samples,this._engine.isStencilEnable?13:14,`PostProcessRTTDepthStencil-${s.name}`);for(const t of r){const i=null===(e=t._thicknessRenderTarget)||void 0===e?void 0:e.renderTarget,n=null==i?void 0:i.texture;if(i&&n){const e=n.width+"_"+n.height;let t=o[e];t||(t=o[e]=new Qb(this._engine,n.width,n.height)),t.depthRTWrapper._shareDepth(i)}}}))}t=this._cameras.keys();for(let i=t.next();!0!==i.done;i=t.next()){const t=i.value,n=this._cameras.get(t)[1],s=e.get(t);if(s)for(const e in n)s[1][e]||n[e].dispose();else for(const e in n)n[e].dispose()}this._cameras.clear(),this._cameras=e,this._setParticleSizeForRenderTargets()}_setParticleSizeForRenderTargets(){const e=new Map;for(let t=0;t{t._depthRenderTarget&&(t._depthRenderTarget.particleSize=e)}))}_setUseVelocityForRenderObject(){for(const e of this.renderObjects)e.object.useVelocity=e.targetRenderer.useVelocity}_prepareRendering(){for(const e of this.targetRenderers)if(e.needInitialization)return void this._initialize()}_render(e){var t;for(let n=0;n{const t=e[1];for(const i in t)t[i].dispose()})),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()}}class TC{get animationStarted(){return this._animationStarted}get fromIndex(){return this._fromIndex}get toIndex(){return this._toIndex}get loopAnimation(){return this._loopAnimation}get delay(){return Math.max(this._delay,1)}constructor(){this.width=1,this.height=1,this.angle=0,this.invertU=!1,this.invertV=!1,this.isVisible=!0,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._time=0,this._onBaseAnimationEnd=null,this.position={x:1,y:1,z:1},this.color={r:1,g:1,b:1,a:1}}playAnimation(e,t,i,n,s){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=n||1,this._animationStarted=!0,this._onBaseAnimationEnd=s,ethis._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,(this._direction>0&&this.cellIndex>this._toIndex||this._direction<0&&this.cellIndex0?this._fromIndex:this._toIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onBaseAnimationEnd&&this._onBaseAnimationEnd()))))}}class SC extends TC{get size(){return this.width}set size(e){this.width=e,this.height=e}get manager(){return this._manager}constructor(e,t){super(),this.name=e,this.animations=new Array,this.isPickable=!1,this.useAlphaForPicking=!1,this.onDisposeObservable=new r.y$,this._onAnimationEnd=null,this._endAnimation=()=>{this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()},this.color=new a.HE(1,1,1,1),this.position=o.P.Zero(),this._manager=t,this._manager.sprites.push(this),this.uniqueId=this._manager.scene.getUniqueId()}getClassName(){return"Sprite"}get fromIndex(){return this._fromIndex}set fromIndex(e){this.playAnimation(e,this._toIndex,this._loopAnimation,this._delay,this._onAnimationEnd)}get toIndex(){return this._toIndex}set toIndex(e){this.playAnimation(this._fromIndex,e,this._loopAnimation,this._delay,this._onAnimationEnd)}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){this.playAnimation(this._fromIndex,this._toIndex,e,this._delay,this._onAnimationEnd)}get delay(){return Math.max(this._delay,1)}set delay(e){this.playAnimation(this._fromIndex,this._toIndex,this._loopAnimation,e,this._onAnimationEnd)}playAnimation(e,t,i,n,s=null){this._onAnimationEnd=s,super.playAnimation(e,t,i,n,this._endAnimation)}dispose(){for(let e=0;e0)for(let r=0;r=s.distance))&&(s=a,i)))break}return s||new je.p},N.x.prototype._internalMultiPickSprites=function(e,t,i){if(!je.p)return null;let n=new Array;if(!i){if(!this.activeCamera)return null;i=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let s=0;s!!e.actionManager&&(e.isPickable&&e.actionManager.hasPointerTriggers)}register(){this.scene._pointerMoveStage.registerStep(Se.l.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(Se.l.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(Se.l.STEP_POINTERUP_SPRITE,this,this._pointerUp)}rebuild(){}dispose(){this.scene.onBeforeSpritesRenderingObservable.clear(),this.scene.onAfterSpritesRenderingObservable.clear();const e=this.scene.spriteManagers;if(e)for(;e.length;)e[0].dispose()}_pickSpriteButKeepRay(e,t,i,n,s){const r=this.scene.pickSprite(t,i,this._spritePredicate,n,s);return r&&(r.ray=e?e.ray:null),r}_pointerMove(e,t,i,n,s){const r=this.scene;return n?r.setPointerOverSprite(null):(i=this._pickSpriteButKeepRay(i,e,t,!1,r.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite?(r.setPointerOverSprite(i.pickedSprite),!r.doNotHandleCursors&&s&&(r._pointerOverSprite&&r._pointerOverSprite.actionManager&&r._pointerOverSprite.actionManager.hoverCursor?s.style.cursor=r._pointerOverSprite.actionManager.hoverCursor:s.style.cursor=r.hoverCursor)):r.setPointerOverSprite(null),i}_pointerDown(e,t,i,n){const s=this.scene;if(s._pickedDownSprite=null,s.spriteManagers&&s.spriteManagers.length>0&&(i=s.pickSprite(e,t,this._spritePredicate,!1,s.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager){switch(s._pickedDownSprite=i.pickedSprite,n.button){case 0:i.pickedSprite.actionManager.processTrigger(2,c.V.CreateNewFromSprite(i.pickedSprite,s,n));break;case 1:i.pickedSprite.actionManager.processTrigger(4,c.V.CreateNewFromSprite(i.pickedSprite,s,n));break;case 2:i.pickedSprite.actionManager.processTrigger(3,c.V.CreateNewFromSprite(i.pickedSprite,s,n))}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(5,c.V.CreateNewFromSprite(i.pickedSprite,s,n))}return i}_pointerUp(e,t,i,n,s){const r=this.scene;if(r.spriteManagers&&r.spriteManagers.length>0){const i=r.pickSprite(e,t,this._spritePredicate,!1,r.cameraToUseForPointers||void 0);i&&(i.hit&&i.pickedSprite&&i.pickedSprite.actionManager&&(i.pickedSprite.actionManager.processTrigger(7,c.V.CreateNewFromSprite(i.pickedSprite,r,n)),i.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||i.pickedSprite.actionManager.processTrigger(1,c.V.CreateNewFromSprite(i.pickedSprite,r,n)),s&&i.pickedSprite.actionManager.processTrigger(6,c.V.CreateNewFromSprite(i.pickedSprite,r,n)))),r._pickedDownSprite&&r._pickedDownSprite.actionManager&&r._pickedDownSprite!==i.pickedSprite&&r._pickedDownSprite.actionManager.processTrigger(16,c.V.CreateNewFromSprite(r._pickedDownSprite,r,n)))}return i}}const xC="imageProcessingCompatibility",bC="#ifdef IMAGEPROCESSINGPOSTPROCESS\ngl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2));\n#endif\n";Ht.v.IncludesShadersStore[xC]=bC;const CC="spritesPixelShader",yC="uniform bool alphaTest;\nvarying vec4 vColor;\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#ifdef PIXEL_PERFECT\nvec2 uvPixelPerfect(vec2 uv) {\nvec2 res=vec2(textureSize(diffuseSampler,0));\nuv=uv*res;\nvec2 seam=floor(uv+0.5);\nuv=seam+clamp((uv-seam)/fwidth(uv),-0.5,0.5);\nreturn uv/res;\n}\n#endif\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#ifdef PIXEL_PERFECT\nvec2 uv=uvPixelPerfect(vUV);\n#else\nvec2 uv=vUV;\n#endif\nvec4 color=texture2D(diffuseSampler,uv);\nfloat fAlphaTest=float(alphaTest);\nif (fAlphaTest != 0.)\n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ht.v.ShadersStore[CC]=yC;const AC="spritesVertexShader",RC="attribute vec4 position;\nattribute vec2 options;\nattribute vec2 offsets;\nattribute vec2 inverts;\nattribute vec4 cellInfo;\nattribute vec4 color;\nuniform mat4 view;\nuniform mat4 projection;\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=offsets.xy;\ncornerPos=vec2(offset.x-0.5,offset.y -0.5)*size;\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));\nvec2 uvPlace=cellInfo.xy;\nvec2 uvSize=cellInfo.zw;\nvUV.x=uvPlace.x+uvSize.x*uvOffset.x;\nvUV.y=uvPlace.y+uvSize.y*uvOffset.y;\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}";Ht.v.ShadersStore[AC]=RC;class PC{get capacity(){return this._capacity}get pixelPerfect(){return this._pixelPerfect}set pixelPerfect(e){this._pixelPerfect!==e&&(this._pixelPerfect=e,this._createEffects())}constructor(e,t,i=.01,n=null){this.blendMode=2,this.autoResetAlpha=!0,this.disableDepthWrite=!1,this.fogEnabled=!0,this._pixelPerfect=!1,this._useVAO=!1,this._useInstancing=!1,this._vertexBuffers={},this._capacity=t,this._epsilon=i,this._engine=e,this._useInstancing=e.getCaps().instancedArrays&&e._features.supportSpriteInstancing,this._useVAO=e.getCaps().vertexArrayObject&&!e.disableVertexArrayObjects,this._scene=n,this._useInstancing||this._buildIndexBuffer(),this._vertexBufferSize=this._useInstancing?16:18,this._vertexData=new Float32Array(t*this._vertexBufferSize*(this._useInstancing?1:4)),this._buffer=new ne.l(e,this._vertexData,!0,this._vertexBufferSize);const s=this._buffer.createVertexBuffer(ne.o.PositionKind,0,4,this._vertexBufferSize,this._useInstancing),r=this._buffer.createVertexBuffer("options",4,2,this._vertexBufferSize,this._useInstancing);let o,a=6;if(this._useInstancing){const t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new ne.l(e,t,!1,2),o=this._spriteBuffer.createVertexBuffer("offsets",0,2)}else o=this._buffer.createVertexBuffer("offsets",a,2,this._vertexBufferSize,this._useInstancing),a+=2;const l=this._buffer.createVertexBuffer("inverts",a,2,this._vertexBufferSize,this._useInstancing),h=this._buffer.createVertexBuffer("cellInfo",a+2,4,this._vertexBufferSize,this._useInstancing),c=this._buffer.createVertexBuffer(ne.o.ColorKind,a+6,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[ne.o.PositionKind]=s,this._vertexBuffers.options=r,this._vertexBuffers.offsets=o,this._vertexBuffers.inverts=l,this._vertexBuffers.cellInfo=h,this._vertexBuffers[ne.o.ColorKind]=c,this._createEffects()}_createEffects(){var e,t,i,n;null===(e=this._drawWrapperBase)||void 0===e||e.dispose(),null===(t=this._drawWrapperFog)||void 0===t||t.dispose(),null===(i=this._drawWrapperDepth)||void 0===i||i.dispose(),null===(n=this._drawWrapperFogDepth)||void 0===n||n.dispose(),this._drawWrapperBase=new $t.q(this._engine),this._drawWrapperFog=new $t.q(this._engine),this._drawWrapperDepth=new $t.q(this._engine,!1),this._drawWrapperFogDepth=new $t.q(this._engine,!1),this._drawWrapperBase.drawContext&&(this._drawWrapperBase.drawContext.useInstancing=this._useInstancing),this._drawWrapperFog.drawContext&&(this._drawWrapperFog.drawContext.useInstancing=this._useInstancing),this._drawWrapperDepth.drawContext&&(this._drawWrapperDepth.drawContext.useInstancing=this._useInstancing),this._drawWrapperFogDepth.drawContext&&(this._drawWrapperFogDepth.drawContext.useInstancing=this._useInstancing);const s=this._pixelPerfect?"#define PIXEL_PERFECT\n":"";this._drawWrapperBase.effect=this._engine.createEffect("sprites",[ne.o.PositionKind,"options","offsets","inverts","cellInfo",ne.o.ColorKind],["view","projection","textureInfos","alphaTest"],["diffuseSampler"],s),this._drawWrapperDepth.effect=this._drawWrapperBase.effect,this._drawWrapperDepth.materialContext=this._drawWrapperBase.materialContext,this._scene&&(this._drawWrapperFog.effect=this._scene.getEngine().createEffect("sprites",[ne.o.PositionKind,"options","offsets","inverts","cellInfo",ne.o.ColorKind],["view","projection","textureInfos","alphaTest","vFogInfos","vFogColor"],["diffuseSampler"],s+"#define FOG"),this._drawWrapperFogDepth.effect=this._drawWrapperFog.effect,this._drawWrapperFogDepth.materialContext=this._drawWrapperFog.materialContext)}render(e,t,i,n,s=null){if(!this.texture||!this.texture.isReady()||!e.length)return;let r=this._drawWrapperBase,o=this._drawWrapperDepth,a=!1;this.fogEnabled&&this._scene&&this._scene.fogEnabled&&0!==this._scene.fogMode&&(r=this._drawWrapperFog,o=this._drawWrapperFogDepth,a=!0);const l=r.effect;if(!l.isReady())return;const h=this._engine,c=!(!this._scene||!this._scene.useRightHandedSystem),d=this.texture.getBaseSize(),u=Math.min(this._capacity,e.length);let p=0,f=!0;for(let v=0;v>0;t._xOffset=(t.cellIndex-i*e)*this.cellWidth/s.width,t._yOffset=i*this.cellHeight/s.height,t._xSize=this.cellWidth,t._ySize=this.cellHeight}this._vertexData[a]=t.position.x,this._vertexData[a+1]=t.position.y,this._vertexData[a+2]=t.position.z,this._vertexData[a+3]=t.angle,this._vertexData[a+4]=t.width,this._vertexData[a+5]=t.height,this._useInstancing?a-=2:(this._vertexData[a+6]=i,this._vertexData[a+7]=n),this._vertexData[a+8]=r?t.invertU?0:1:t.invertU?1:0,this._vertexData[a+9]=t.invertV?1:0,this._vertexData[a+10]=t._xOffset,this._vertexData[a+11]=t._yOffset,this._vertexData[a+12]=t._xSize/s.width,this._vertexData[a+13]=t._ySize/s.height,this._vertexData[a+14]=t.color.r,this._vertexData[a+15]=t.color.g,this._vertexData[a+16]=t.color.b,this._vertexData[a+17]=t.color.a}_buildIndexBuffer(){const e=[];let t=0;for(let i=0;i{e.cellRef||(e.cellIndex=0);const i=e.cellIndex;"number"==typeof i&&isFinite(i)&&Math.floor(i)===i&&(e.cellRef=this._spriteMap[e.cellIndex]),e._xOffset=this._cellData[e.cellRef].frame.x/t.width,e._yOffset=this._cellData[e.cellRef].frame.y/t.height,e._xSize=this._cellData[e.cellRef].frame.w,e._ySize=this._cellData[e.cellRef].frame.h},s||(s=m.l.LastCreatedScene),s._getComponent(Se.l.NAME_SPRITE)||s._addComponent(new EC(s)),this._fromPacked=l,this._scene=s;const c=this._scene.getEngine();if(this._spriteRenderer=new PC(c,i,o,s),n.width&&n.height)this.cellWidth=n.width,this.cellHeight=n.height;else{if(void 0===n)return void(this._spriteRenderer=null);this.cellWidth=n,this.cellHeight=n}this._scene.spriteManagers&&this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),t&&(this.texture=new Le(t,s,!0,!1,a)),this._fromPacked&&this._makePacked(t,h)}getClassName(){return"SpriteManager"}_makePacked(e,t){if(null!==t)try{let e;if(e="string"==typeof t?JSON.parse(t):t,e.frames.length){const t={};for(let i=0;i0);const s=e.substring(0,n-1)+".json",r=()=>{p.Y.Error("JSON ERROR: Unable to load JSON file."),this._fromPacked=!1,this._packedAndReady=!1},o=e=>{try{const t=JSON.parse(e),i=Reflect.ownKeys(t.frames);this._spriteMap=i,this._packedAndReady=!0,this._cellData=t.frames}catch(i){throw this._fromPacked=!1,this._packedAndReady=!1,new Error("Invalid JSON format. Please check documentation for format specifications.")}};se.w1.LoadFile(s,o,void 0,void 0,!1,r)}}_checkTextureAlpha(e,t,i,n,s){if(!e.useAlphaForPicking||!this.texture)return!0;const r=this.texture.getSize();this._textureContent||(this._textureContent=new Uint8Array(r.width*r.height*4),this.texture.readPixels(0,0,this._textureContent));const a=o.jp.Vector3[0];a.copyFrom(t.direction),a.normalize(),a.scaleInPlace(i),a.addInPlace(t.origin);const l=(a.x-n.x)/(s.x-n.x),h=1-(a.y-n.y)/(s.y-n.y),c=e._xOffset*r.width+l*e._xSize|0,d=e._yOffset*r.height+h*e._ySize|0;return this._textureContent[4*(c+d*r.width)+3]>.5}intersects(e,t,i,n){const s=Math.min(this.capacity,this.sprites.length),r=o.P.Zero(),a=o.P.Zero();let l=Number.MAX_VALUE,h=null;const c=o.jp.Vector3[0],d=o.jp.Vector3[1],u=t.getViewMatrix();let p=e,f=e;for(let _=0;_e){if(!this._checkTextureAlpha(t,p,e,r,a))continue;if(f=p,l=e,h=t,n)break}}}}if(h){const e=new je.p;u.invertToRef(o.jp.Matrix[0]),e.hit=!0,e.pickedSprite=h,e.distance=l;const t=o.jp.Vector3[2];return t.copyFrom(f.direction),t.normalize(),t.scaleInPlace(l),f.origin.addToRef(t,c),e.pickedPoint=o.P.TransformCoordinates(c,o.jp.Matrix[0]),e}return null}multiIntersects(e,t,i){const n=Math.min(this.capacity,this.sprites.length),s=o.P.Zero(),r=o.P.Zero();let a;const l=[],h=o.jp.Vector3[0].copyFromFloats(0,0,0),c=o.jp.Vector3[1].copyFromFloats(0,0,0),d=t.getViewMatrix();for(let u=0;u{const o=new y.g;o.addEventListener("readystatechange",(()=>{if(4==o.readyState)if(200==o.status){const t=JSON.parse(o.responseText),r=IC.Parse(t,i||m.l.LastCreatedScene,n);e&&(r.name=e),s(r)}else r("Unable to load the sprite manager")})),o.open("GET",t),o.send()}))}static ParseFromSnippetAsync(e,t,i=""){return"_BLANK"===e?Promise.resolve(new IC("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,t)):new Promise(((n,s)=>{const r=new y.g;r.addEventListener("readystatechange",(()=>{if(4==r.readyState)if(200==r.status){const s=JSON.parse(JSON.parse(r.responseText).jsonPayload),o=JSON.parse(s.spriteManager),a=IC.Parse(o,t||m.l.LastCreatedScene,i);a.snippetId=e,n(a)}else s("Unable to load the snippet "+e)})),r.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),r.send()}))}}IC.SnippetUrl="https://snippet.babylonjs.com",IC.CreateFromSnippetAsync=IC.ParseFromSnippetAsync;const MC="spriteMapPixelShader",OC="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nprecision highp float;\nvarying vec3 vPosition;\nvarying vec2 vUV;\nvarying vec2 tUV;\nuniform float time;\nuniform float spriteCount;\nuniform sampler2D spriteSheet;\nuniform vec2 spriteMapSize;\nuniform vec2 outputSize;\nuniform vec2 stageSize;\nuniform sampler2D frameMap;\nuniform sampler2D tileMaps[LAYERS];\nuniform sampler2D animationMap;\nuniform vec3 colorMul;\nfloat mt;\nconst float fdStep=1./4.;\nconst float aFrameSteps=1./MAX_ANIMATION_FRAMES;\nmat4 getFrameData(float frameID){\nfloat fX=frameID/spriteCount;\nreturn mat4(\ntexture2D(frameMap,vec2(fX,0.),0.),\ntexture2D(frameMap,vec2(fX,fdStep*1.),0.),\ntexture2D(frameMap,vec2(fX,fdStep*2.),0.),\nvec4(0.)\n);\n}\nvoid main(){\nvec4 color=vec4(0.);\nvec2 tileUV=fract(tUV);\n#ifdef FLIPU\ntileUV.y=1.0-tileUV.y;\n#endif\nvec2 tileID=floor(tUV);\nvec2 sheetUnits=1./spriteMapSize;\nfloat spriteUnits=1./spriteCount;\nvec2 stageUnits=1./stageSize;\nfor(int i=0; i0.) {\nmt=mod(time*animationData.z,1.0);\nfor(float f=0.; fmt){\nframeID=animationData.x;\nbreak;\n}\nanimationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.);\n}\n}\nmat4 frameData=getFrameData(frameID+0.5);\nvec2 frameSize=(frameData[0].zw)/spriteMapSize;\nvec2 offset=frameData[0].xy*sheetUnits;\nvec2 ratio=frameData[2].xy/frameData[0].zw;\nif (frameData[2].z==1.){\ntileUV.xy=tileUV.yx;\n}\nvec4 nc=texture2D(spriteSheet,tileUV*frameSize+offset);\nif (i==0){\ncolor=nc;\n} else {\nfloat alpha=min(color.a+nc.a,1.0);\nvec3 mixed=mix(color.xyz,nc.xyz,nc.a);\ncolor=vec4(mixed,alpha);\n}\n}\ncolor.xyz*=colorMul;\ngl_FragColor=color;\n}";Ht.v.ShadersStore[MC]=OC;const DC="spriteMapVertexShader",NC="precision highp float;\nattribute vec3 position;\nattribute vec3 normal;\nattribute vec2 uv;\nvarying vec3 vPosition;\nvarying vec2 vUV;\nvarying vec2 tUV;\nvarying vec2 stageUnits;\nvarying vec2 levelUnits;\nvarying vec2 tileID;\nuniform float time;\nuniform mat4 worldViewProjection;\nuniform vec2 outputSize;\nuniform vec2 stageSize;\nuniform vec2 spriteMapSize;\nuniform float stageScale;\nvoid main() {\nvec4 p=vec4( position,1. );\nvPosition=p.xyz;\nvUV=uv;\ntUV=uv*stageSize; \ngl_Position=worldViewProjection*p;\n}";Ht.v.ShadersStore[DC]=NC;var FC;i(6184),i(2320),i(5776);!function(e){e[e.INIT=0]="INIT",e[e.RUNNING=1]="RUNNING",e[e.DONE=2]="DONE",e[e.ERROR=3]="ERROR"}(FC||(FC={}));class wC{get resolve(){return this._resolve}get reject(){return this._reject}constructor(){this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}}i(3392);r.y$.prototype.notifyObserversWithPromise=async function(e,t=-1,i,n,s){let r=Promise.resolve(e);if(!this.observers.length)return r;const o=this._eventState;return o.mask=t,o.target=i,o.currentTarget=n,o.skipNextObservers=!1,o.userInfo=s,this.observers.forEach((i=>{o.skipNextObservers||i._willBeUnregistered||i.mask&t&&(r=i.scope?r.then((t=>(o.lastReturnValue=t,i.callback.apply(i.scope,[e,o])))):r.then((t=>(o.lastReturnValue=t,i.callback(e,o)))),i.unregisterOnNextCall&&this._deferUnregister(i))})),await r,e};i(4441);class LC{getDescription(){return""}apply(e,t){return!0}constructor(e=0){this.priority=e}}class BC extends LC{constructor(){super(...arguments),this._canBeMerged=e=>{if(!(e instanceof ee.Kj))return!1;const t=e;return!t.isDisposed()&&(!(!t.isVisible||!t.isEnabled())&&(!(t.instances.length>0)&&(!t.skeleton&&!t.hasLODLevels&&0!==t.getTotalVertices())))}}static get UpdateSelectionTree(){return BC._UpdateSelectionTree}static set UpdateSelectionTree(e){BC._UpdateSelectionTree=e}getDescription(){return"Merging similar meshes together"}apply(e,t,i){const n=e.meshes.slice(0);let s=n.length;for(let o=0;o{e.doNotSerialize||(t.vertexData.push(e.serializeVerticeData()),UC[e.id]=!0)},kC=(e,t)=>{const i={},n=e._geometry;return n&&(e.getScene().getGeometryById(n.id)||VC(n,t.geometries)),e.serialize&&e.serialize(i),i};class GC{static ClearCache(){UC=[]}static Serialize(e){return GC._Serialize(e)}static _Serialize(e,t=!0){const i={};if(t&&!e.getEngine()._features.supportSyncTextureRead&&Le.ForceSerializeBuffers&&console.warn("The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead."),GC.ClearCache(),i.useDelayedTextureLoading=e.useDelayedTextureLoading,i.autoClear=e.autoClear,i.clearColor=e.clearColor.asArray(),i.ambientColor=e.ambientColor.asArray(),i.gravity=e.gravity.asArray(),i.collisionsEnabled=e.collisionsEnabled,i.useRightHandedSystem=e.useRightHandedSystem,e.fogMode&&0!==e.fogMode&&(i.fogMode=e.fogMode,i.fogColor=e.fogColor.asArray(),i.fogStart=e.fogStart,i.fogEnd=e.fogEnd,i.fogDensity=e.fogDensity),e.isPhysicsEnabled()){const t=e.getPhysicsEngine();t&&(i.physicsEnabled=!0,i.physicsGravity=t.gravity.asArray(),i.physicsEngine=t.getPhysicsPluginName())}e.metadata&&(i.metadata=e.metadata),i.morphTargetManagers=[];for(const a of e.meshes){const e=a.morphTargetManager;e&&i.morphTargetManagers.push(e.serialize())}let n,s,r;for(i.lights=[],n=0;n0){i.animationGroups=[];for(let t=0;t0)for(i.reflectionProbes=[],n=0;nt))}static _CollectPromises(e,t){if(Array.isArray(e))for(let i=0;ie[i]=t))):(n instanceof Object||Array.isArray(n))&&this._CollectPromises(n,t)}else if(e instanceof Object)for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)){const n=e[i];n instanceof Promise?t.push(n.then((t=>e[i]=t))):(n instanceof Object||Array.isArray(n))&&this._CollectPromises(n,t)}}static SerializeMesh(e,t=!1,i=!1){const n={};if(GC.ClearCache(),e=e instanceof Array?e:[e],t||i)for(let s=0;s{t instanceof ee.Kj&&e.indexOf(t)<0&&!t.doNotSerialize&&e.push(t)})),t&&e[s].parent&&e.indexOf(e[s].parent)<0&&!e[s].parent.doNotSerialize&&e.push(e[s].parent);return e.forEach((e=>{((e,t)=>{if(1===e.delayLoadState||0===e.delayLoadState){const i=i=>{t.materials=t.materials||[],e.material&&!t.materials.some((t=>t.id===e.material.id))&&t.materials.push(i.serialize())};if(e.material&&!e.material.doNotSerialize)if(e.material instanceof zg.G){if(t.multiMaterials=t.multiMaterials||[],!t.multiMaterials.some((t=>t.id===e.material.id))){t.multiMaterials.push(e.material.serialize());for(const t of e.material.subMaterials)t&&i(t)}}else i(e.material);else e.material||i(e.getScene().defaultMaterial);const n=e._geometry;n&&(t.geometries||(t.geometries={},t.geometries.boxes=[],t.geometries.spheres=[],t.geometries.cylinders=[],t.geometries.toruses=[],t.geometries.grounds=[],t.geometries.planes=[],t.geometries.torusKnots=[],t.geometries.vertexData=[]),VC(n,t.geometries)),e.skeleton&&!e.skeleton.doNotSerialize&&(t.skeletons=t.skeletons||[],t.skeletons.push(e.skeleton.serialize())),t.meshes=t.meshes||[],t.meshes.push(kC(e,t))}})(e,n)})),n}}class zC{static IsSupported(e){const t=e.getRenderingCanvas();return!!t&&"function"==typeof t.captureStream}get isRecording(){return!!this._canvas&&this._canvas.isRecording}constructor(e,t={}){if(!zC.IsSupported(e))throw"Your browser does not support recording so far.";const i=e.getRenderingCanvas();if(!i)throw"The babylon engine must have a canvas to be recorded";this._canvas=i,this._canvas.isRecording=!1,this._options=Object.assign(Object.assign({},zC._DefaultOptions),t);const n=this._canvas.captureStream(this._options.fps);if(this._options.audioTracks)for(const s of this._options.audioTracks)n.addTrack(s);this._mediaRecorder=new MediaRecorder(n,{mimeType:this._options.mimeType}),this._mediaRecorder.ondataavailable=this._handleDataAvailable.bind(this),this._mediaRecorder.onerror=this._handleError.bind(this),this._mediaRecorder.onstop=this._handleStop.bind(this)}stopRecording(){this._canvas&&this._mediaRecorder&&this.isRecording&&(this._canvas.isRecording=!1,this._mediaRecorder.stop())}startRecording(e="babylonjs.webm",t=7){if(!this._canvas||!this._mediaRecorder)throw"Recorder has already been disposed";if(this.isRecording)throw"Recording already in progress";return t>0&&setTimeout((()=>{this.stopRecording()}),1e3*t),this._fileName=e,this._recordedChunks=[],this._resolve=null,this._reject=null,this._canvas.isRecording=!0,this._mediaRecorder.start(this._options.recordChunckSize),new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}dispose(){this._canvas=null,this._mediaRecorder=null,this._recordedChunks=[],this._fileName=null,this._resolve=null,this._reject=null}_handleDataAvailable(e){e.data.size>0&&this._recordedChunks.push(e.data)}_handleError(e){if(this.stopRecording(),!this._reject)throw new e.error;this._reject(e.error)}_handleStop(){this.stopRecording();const e=new Blob(this._recordedChunks);this._resolve&&this._resolve(e),window.URL.createObjectURL(e),this._fileName&&se.w1.Download(e,this._fileName)}}zC._DefaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3};let WC=null;function HC(e,t,i,n,s="image/png",r=!1,o){const{height:a,width:l}=KC(e,t,i);if(!a||!l)return void p.Y.Error("Invalid 'size' parameter !");WC||(WC=document.createElement("canvas")),WC.width=l,WC.height=a;const h=WC.getContext("2d"),c=e.getRenderWidth()/e.getRenderHeight();let d=l,u=d/c;u>a&&(u=a,d=u*c);const f=Math.max(0,l-d)/2,_=Math.max(0,a-u)/2;t.getScene().activeCamera!==t?YC(e,t,i,(e=>{if(r){const t=new Blob([e]);se.w1.DownloadBlob(t),n&&n("")}else n&&n(e)}),s,1,e.getCreationOptions().antialias,void 0,void 0,void 0,void 0,o):e.onEndFrameObservable.addOnce((()=>{const t=e.getRenderingCanvas();h&&t&&h.drawImage(t,f,_,d,u),WC&&(r?(se.w1.EncodeScreenshotCanvasData(WC,void 0,s,void 0,o),n&&n("")):se.w1.EncodeScreenshotCanvasData(WC,n,s,void 0,o))}))}function XC(e,t,i,n="image/png",s){return new Promise(((r,o)=>{HC(e,t,i,(e=>{void 0!==e?r(e):o(new Error("Data is undefined"))}),n,void 0,s)}))}function YC(e,t,i,n,s="image/png",r=1,o=!1,a,l=!1,h=!1,c=!0,d){const{height:u,width:f,finalWidth:_,finalHeight:m}=KC(e,t,i),g={width:f,height:u};if(!u||!f)return void p.Y.Error("Invalid 'size' parameter !");const v={width:e.getRenderWidth(),height:e.getRenderHeight()};e.setSize(f,u);const T=t.getScene(),S=new Ci("screenShot",g,T,!1,!1,0,!1,Le.BILINEAR_SAMPLINGMODE,void 0,h,void 0,void 0,void 0,r);S.renderList=T.meshes.slice(),S.samples=r,S.renderSprites=l,S.activeCamera=t,S.forceLayerMaskCheck=c;const E=()=>{e.onEndFrameObservable.addOnce((()=>{_===f&&m===u?S.readPixels(void 0,void 0,void 0,!1).then((e=>{bi.DumpData(f,u,e,n,s,a,!0,void 0,d),S.dispose()})):wh("pass",S.getInternalTexture(),T,void 0,void 0,void 0,_,m).then((t=>{e._readTexturePixels(t,_,m,-1,0,null,!0,!1,0,0).then((e=>{bi.DumpData(_,m,e,n,s,a,!0,void 0,d),t.dispose()}))}))})),T.incrementRenderId(),T.resetCachedMaterial(),S.render(!0),T.incrementRenderId(),T.resetCachedMaterial(),e.setSize(v.width,v.height),t.getProjectionMatrix(!0),T.render()};if(o){const e=new PE("antialiasing",1,T.activeCamera);S.addPostProcess(e),e.getEffect().isReady()?E():e.getEffect().onCompiled=()=>{E()}}else E()}function jC(e,t,i,n="image/png",s=1,r=!1,o,a=!1,l=!1,h=!0,c){return new Promise(((d,u)=>{YC(e,t,i,(e=>{void 0!==e?d(e):u(new Error("Data is undefined"))}),n,s,r,o,a,l,h,c)}))}function KC(e,t,i){let n=0,s=0,r=0,o=0;if("object"==typeof i){const a=i.precision?Math.abs(i.precision):1;i.width&&i.height?(n=i.height*a,s=i.width*a):i.width&&!i.height?(s=i.width*a,n=Math.round(s/e.getAspectRatio(t))):i.height&&!i.width?(n=i.height*a,s=Math.round(n*e.getAspectRatio(t))):(s=Math.round(e.getRenderWidth()*a),n=Math.round(s/e.getAspectRatio(t))),i.finalWidth&&i.finalHeight?(o=i.finalHeight,r=i.finalWidth):i.finalWidth&&!i.finalHeight?(r=i.finalWidth,o=Math.round(r/e.getAspectRatio(t))):i.finalHeight&&!i.finalWidth?(o=i.finalHeight,r=Math.round(o*e.getAspectRatio(t))):(r=s,o=n)}else isNaN(i)||(n=i,s=i,r=i,o=i);return s&&(s=Math.floor(s)),n&&(n=Math.floor(n)),r&&(r=Math.floor(r)),o&&(o=Math.floor(o)),{height:0|n,width:0|s,finalWidth:0|r,finalHeight:0|o}}var qC;se.w1.CreateScreenshot=HC,se.w1.CreateScreenshotAsync=XC,se.w1.CreateScreenshotUsingRenderTarget=YC,se.w1.CreateScreenshotUsingRenderTargetAsync=jC,function(e){e[e.Checkbox=0]="Checkbox",e[e.Slider=1]="Slider",e[e.Vector3=2]="Vector3",e[e.Quaternion=3]="Quaternion",e[e.Color3=4]="Color3",e[e.String=5]="String",e[e.Button=6]="Button",e[e.Options=7]="Options",e[e.Tab=8]="Tab",e[e.FileButton=9]="FileButton",e[e.Vector2=10]="Vector2"}(qC||(qC={}));var $C;i(5077);class QC{constructor(e){this.byteOffset=0,this.buffer=e}loadAsync(e){return this.buffer.readAsync(this.byteOffset,e).then((e=>{this._dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),this._dataByteOffset=0}))}readUint32(){const e=this._dataView.getUint32(this._dataByteOffset,!0);return this._dataByteOffset+=4,this.byteOffset+=4,e}readUint8Array(e){const t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._dataByteOffset,e);return this._dataByteOffset+=e,this.byteOffset+=e,t}readString(e){return(0,Oe.fJ)(this.readUint8Array(e))}skipBytes(e){this._dataByteOffset+=e,this.byteOffset+=e}}class ZC{static _GetStorage(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch(e){const t={};return{getItem:e=>{const i=t[e];return void 0===i?null:i},setItem:(e,i)=>{t[e]=i}}}}static ReadString(e,t){const i=this._Storage.getItem(e);return null!==i?i:t}static WriteString(e,t){this._Storage.setItem(e,t)}static ReadBoolean(e,t){const i=this._Storage.getItem(e);return null!==i?"true"===i:t}static WriteBoolean(e,t){this._Storage.setItem(e,t?"true":"false")}static ReadNumber(e,t){const i=this._Storage.getItem(e);return null!==i?parseFloat(i):t}static WriteNumber(e,t){this._Storage.setItem(e,t.toString())}}ZC._Storage=ZC._GetStorage();!function(e){class t{serialize(){const e={},t=new Array(this._characterToIdx.size);return this._characterToIdx.forEach(((e,i)=>{t[e]=i})),e.characters=t,e.insertionCosts=this._insertionCosts,e.deletionCosts=this._deletionCosts,e.substitutionCosts=this._substitutionCosts,JSON.stringify(e)}static Deserialize(e){const i=JSON.parse(e),n=new t(i.characters);return n._insertionCosts=i.insertionCosts,n._deletionCosts=i.deletionCosts,n._substitutionCosts=i.substitutionCosts,n}constructor(e,t=null,i=null,n=null){let s;t=null!=t?t:()=>1,i=null!=i?i:()=>1,n=null!=n?n:(e,t)=>e===t?0:1,this._characterToIdx=new Map,this._insertionCosts=new Array(e.length),this._deletionCosts=new Array(e.length),this._substitutionCosts=new Array(e.length);for(let r=0;ri._MAX_SEQUENCE_LENGTH)throw new Error("Sequences longer than "+i._MAX_SEQUENCE_LENGTH+" not supported.");this._alphabet=t,this._characters=e.map((e=>this._alphabet.getCharacterIdx(e)))}distance(e){return i._Distance(this,e)}static _Distance(e,t){const n=e._alphabet;if(n!==t._alphabet)throw new Error("Cannot Levenshtein compare Sequences built from different alphabets.");const s=e._characters,r=t._characters,o=s.length,a=r.length,l=i._CostMatrix;l[0][0]=0;for(let i=0;inew Array(i._MAX_SEQUENCE_LENGTH+1))),e.Sequence=i}($C||($C={}));class JC{serialize(){return JSON.stringify(this)}static Deserialize(e){const t=JSON.parse(e),i=new JC(t._segmentLength);return i._points=t._points.map((e=>new o.P(e._x,e._y,e._z))),i}constructor(e=.01){this._points=[],this._segmentLength=e}getLength(){return this._points.length*this._segmentLength}add(e){let t=this._points.length;if(0===t)this._points.push(e.clone());else{const i=()=>this._segmentLength/o.P.Distance(this._points[t-1],e);for(let n=i();n<=1;n=i()){const i=this._points[t-1].scale(1-n);e.scaleAndAddToRef(n,i),this._points.push(i),++t}}}resampleAtTargetResolution(e){const t=new JC(this.getLength()/e);return this._points.forEach((e=>{t.add(e)})),t}tokenize(e){const t=[],i=new o.P;for(let n=2;n.98)&&(o.P.CrossToRef(JC._ForwardDir,JC._InverseFromVec,JC._UpDir),JC._UpDir.normalize(),o.y3.LookAtLHToRef(e,t,JC._UpDir,JC._LookMatrix),i.subtractToRef(t,JC._FromToVec),JC._FromToVec.normalize(),o.P.TransformNormalToRef(JC._FromToVec,JC._LookMatrix,n),!0)}static _TokenizeSegment(e,t){JC._BestMatch=0,JC._Score=o.P.Dot(e,t[0]),JC._BestScore=JC._Score;for(let i=1;iJC._BestScore&&(JC._BestMatch=i,JC._BestScore=JC._Score);return JC._BestMatch}}JC._ForwardDir=new o.P,JC._InverseFromVec=new o.P,JC._UpDir=new o.P,JC._FromToVec=new o.P,JC._LookMatrix=new o.y3;class ey{serialize(){return JSON.stringify(this._sequences.map((e=>e.serialize())))}static Deserialize(e,t){const i=new ey;return i._sequences=JSON.parse(e).map((e=>$C.Sequence.Deserialize(e,t))),i}static CreateFromTrajectory(e,t,i){return ey.CreateFromTokenizationPyramid(ey._GetTokenizationPyramid(e,t),i)}static CreateFromTokenizationPyramid(e,t){const i=new ey;return i._sequences=e.map((e=>new $C.Sequence(e,t))),i}constructor(){this._sequences=[]}static _GetTokenizationPyramid(e,t,i=ey._FINEST_DESCRIPTOR_RESOLUTION){const n=[];for(let s=i;s>4;s=Math.floor(s/2))n.push(e.resampleAtTargetResolution(s).tokenize(t.chars));return n}distance(e){let t,i=0;for(let n=0;ne.serialize())),e.centroidIdx=this._centroidIdx,e.averageDistance=this._averageDistance,JSON.stringify(e)}static Deserialize(e,t){const i=JSON.parse(e),n=new ty;return n._descriptors=i.descriptors.map((e=>ey.Deserialize(e,t))),n._centroidIdx=i.centroidIdx,n._averageDistance=i.averageDistance,n}constructor(e=[]){this._descriptors=e,this._centroidIdx=-1,this._averageDistance=0,this._refreshDescription()}add(e){this._descriptors.push(e),this._refreshDescription()}getMatchCost(e){return e.distance(this._descriptors[this._centroidIdx])/this._averageDistance}getMatchMinimumDistance(e){return Math.min(...this._descriptors.map((t=>t.distance(e))))}_refreshDescription(){let e;this._centroidIdx=-1;const t=this._descriptors.map((t=>(e=0,this._descriptors.forEach((i=>{e+=t.distance(i)})),e)));for(let i=0;i{this._averageDistance+=e.distance(this._descriptors[this._centroidIdx])})),this._descriptors.length>0&&(this._averageDistance=Math.max(this._averageDistance/this._descriptors.length,ty._MIN_AVERAGE_DISTANCE))}}ty._MIN_AVERAGE_DISTANCE=1;class iy{constructor(e,t,i){this._scene=e,p.Y.Log(`[Reflector] Connecting to ws://${t}:${i}`),this._webSocket=new WebSocket(`ws://${t}:${i}`),this._webSocket.onmessage=e=>{const t=e.data;if(t.startsWith(iy._SERVER_PREFIX)){const e=t.substr(iy._SERVER_PREFIX.length);return p.Y.Log(`[Reflector] Received server message: ${e.substr(0,64)}`),void this._handleServerMessage(e)}p.Y.Log(`[Reflector] Received client message: ${t.substr(0,64)}`),this._handleClientMessage()},this._webSocket.onclose=e=>{p.Y.Log(`[Reflector] Disconnected ${e.code} ${e.reason}`)}}close(){this._webSocket.close()}_handleServerMessage(e){if("connected"===e)GC.SerializeAsync(this._scene).then((e=>{this._webSocket.send(`load|${JSON.stringify(e)}`)}))}_handleClientMessage(){}}iy._SERVER_PREFIX="$$";class ny{constructor(e){this._view=new Float32Array(e),this._itemLength=0}get itemLength(){return this._itemLength}at(e){return e<0||e>=this._itemLength?NaN:this._view[e]}subarray(e,t){return e>=t||e<0?new Float32Array(0):(t>this._itemLength&&(t=this._itemLength),this._view.subarray(e,t))}push(e){this._view[this._itemLength]=e,this._itemLength++,this._itemLength>=this._view.length&&this._growArray()}_growArray(){const e=Math.floor(1.5*this._view.length),t=new Float32Array(e);t.set(this._view),this._view=t}}const sy=1800,ry="timestamp",oy="numPoints",ay=/\r/g;class ly{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{const e=F.F.Now-this._startingTimestamp,t=this.datasets.ids.length,i=this.datasets.startingIndices.itemLength;let n=0;if(i>0){const e=this.datasets.startingIndices.at(i-1);n=e+this.datasets.data.at(e+ly.NumberOfPointsOffset)+ly.SliceDataOffset}if(this.datasets.startingIndices.push(n),this.datasets.data.push(e),this.datasets.data.push(t),this.datasets.ids.forEach((e=>{const t=this._strategies.get(e);t&&this.datasets.data.push(t.getData())})),this.datasetObservable.hasObservers()){const i=[e,t];for(let e=0;ee.callback(this._datasetMeta,new r.he(0)))),t&&this.addCollectionStrategies(...t)}registerEvent(e,t,i){var n;if(this._strategies.has(e)&&!t)return;this._strategies.has(e)&&t&&(null===(n=this._strategies.get(e))||void 0===n||n.dispose(),this._strategies.delete(e));const s={name:e};return this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:t=>{let i=0,n=0;const s=t.onAfterRenderObservable.add((()=>{n=i,i=0})),r=this._customEventObservable.add((t=>{e===t.name&&(void 0!==t.value?i=t.value:i++)}));return{id:e,getData:()=>n,dispose:()=>{t.onAfterRenderObservable.remove(s),this._customEventObservable.remove(r)}}},category:i}),s}sendEvent(e){this._customEventObservable.notifyObservers(e)}_restoreStringEvents(){this._eventRestoreSet.size!==this._customEventObservable.observers.length&&this._eventRestoreSet.forEach((e=>{this.registerEvent(e,!0)}))}addCollectionStrategies(...e){for(let{strategyCallback:t,category:i,hidden:n}of e){const e=t(this._scene);this._strategies.has(e.id)?e.dispose():(this.datasets.ids.push(e.id),i&&(i=i.replace(new RegExp("@","g"),"")),this._datasetMeta.set(e.id,{color:this._getHexColorFromId(e.id),category:i,hidden:n}),this._strategies.set(e.id,e))}this.metadataObservable.notifyObservers(this._datasetMeta)}_getHexColorFromId(e){let t=0;for(let n=0;n>n&255).toString(16)).substr(-2)}return i}getCurrentSlice(){const e=[F.F.Now-this._startingTimestamp,this.datasets.ids.length];this.datasets.ids.forEach((t=>{const i=this._strategies.get(t);i&&this.datasetObservable.hasObservers()&&e.push(i.getData())})),this.datasetObservable.hasObservers()&&this.datasetObservable.notifyObservers(e)}updateMetadata(e,t,i){const n=this._datasetMeta.get(e);n&&(n[t]=i,this.metadataObservable.notifyObservers(this._datasetMeta))}clear(e){this.datasets.data=new ny(sy),this.datasets.ids.length=0,this.datasets.startingIndices=new ny(sy),this._datasetMeta.clear(),this._strategies.forEach((e=>e.dispose())),this._strategies.clear(),e||this._eventRestoreSet.clear(),this._hasLoadedData=!1}get hasLoadedData(){return this._hasLoadedData}loadFromFileData(e,t){const i=e.replace(ay,"").split("\n").map((e=>e.split(",").filter((e=>e.length>0)))).filter((e=>e.length>0)),n=ly.NumberOfPointsOffset;if(i.length<2)return!1;const s={ids:[],data:new ny(sy),startingIndices:new ny(sy)},[r,...o]=i;if(r.length<2||r[0]!==ry||r[n]!==oy)return!1;const a=new Map;for(let h=ly.SliceDataOffset;he.dispose())),this._strategies.clear(),!t)for(const h of this.datasets.ids){const e=a.get(h);this._datasetMeta.set(h,{category:e,color:this._getHexColorFromId(h)})}return this.metadataObservable.notifyObservers(this._datasetMeta),this._hasLoadedData=!0,!0}exportDataToCsv(){let e="";e+=`${ry},${oy}`;for(let i=0;i{e.dispose()})),this.datasetObservable.clear(),this.metadataObservable.clear(),this._isStarted=!1,this.datasets=null}}N.x.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new ly(this)),this._perfCollector};var hy=i(140);r.y$.prototype.runCoroutineAsync=function(e){if(!this._coroutineScheduler){const e=function(e){const t=new Array,i=new Array,n=new Array,s=e.add((()=>{const e=t.length;for(let s=0;s{t.push(e),i.push(s),n.push(r)},dispose:()=>{e.remove(s)}}}(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return(0,hy.sM)(e,this._coroutineScheduler)},r.y$.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};class cy extends nt{constructor(e,t={}){super(e),this.options=t,this._direction=new o.P(0,0,-1),this._mat=new o.y3,this._onSelectEnabled=!1,this._origin=new o.P(0,0,0),this.lastNativeXRHitResults=[],this.onHitTestResultObservable=new r.y$,this._onHitTestResults=e=>{const t=e.map((e=>{const t=o.y3.FromArray(e.hitMatrix);return this._xrSessionManager.scene.useRightHandedSystem||t.toggleModelMatrixHandInPlace(),this.options.worldParentNode&&t.multiplyToRef(this.options.worldParentNode.getWorldMatrix(),t),{xrHitResult:e,transformationMatrix:t}}));this.lastNativeXRHitResults=e,this.onHitTestResultObservable.notifyObservers(t)},this._onSelect=e=>{this._onSelectEnabled&&cy.XRHitTestWithSelectEvent(e,this._xrSessionManager.referenceSpace)},this.xrNativeFeatureName="hit-test",se.w1.Warn("A newer version of this plugin is available")}static XRHitTestWithRay(e,t,i,n){return e.requestHitTest(t,i).then((e=>{const t=n||(e=>!!e.hitMatrix);return e.filter(t)}))}static XRHitTestWithSelectEvent(e,t){const i=e.frame.getPose(e.inputSource.targetRaySpace,t);if(!i)return Promise.resolve([]);const n=new XRRay(i.transform);return this.XRHitTestWithRay(e.frame.session,n,t)}attach(){return!!super.attach()&&(this.options.testOnPointerDownOnly&&this._xrSessionManager.session.addEventListener("select",this._onSelect,!1),!0)}detach(){return!!super.detach()&&(this._onSelectEnabled=!1,this._xrSessionManager.session.removeEventListener("select",this._onSelect),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(!this.attached||this.options.testOnPointerDownOnly)return;const t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;o.y3.FromArrayToRef(t.transform.matrix,0,this._mat),o.P.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),o.P.TransformCoordinatesFromFloatsToRef(0,0,-1,this._mat,this._direction),this._direction.subtractInPlace(this._origin),this._direction.normalize();const i=new XRRay({x:this._origin.x,y:this._origin.y,z:this._origin.z,w:0},{x:this._direction.x,y:this._direction.y,z:this._direction.z,w:0});cy.XRHitTestWithRay(this._xrSessionManager.session,i,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}}cy.Name=tt.HIT_TEST,cy.Version=1,it.AddWebXRFeature(cy.Name,((e,t)=>()=>new cy(e,t)),cy.Version,!1);let dy=0;class uy extends nt{set referenceSpaceForFrameAnchors(e){this._referenceSpaceForFrameAnchors=e}constructor(e,t={}){super(e),this._options=t,this._lastFrameDetected=new Set,this._trackedAnchors=[],this._futureAnchors=[],this.onAnchorAddedObservable=new r.y$,this.onAnchorRemovedObservable=new r.y$,this.onAnchorUpdatedObservable=new r.y$,this._tmpVector=new o.P,this._tmpQuaternion=new o._f,this.xrNativeFeatureName="anchors"}_populateTmpTransformation(e,t){return this._tmpVector.copyFrom(e),this._tmpQuaternion.copyFrom(t),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpVector.z*=-1,this._tmpQuaternion.z*=-1,this._tmpQuaternion.w*=-1),{position:this._tmpVector,rotationQuaternion:this._tmpQuaternion}}async addAnchorPointUsingHitTestResultAsync(e,t=new o.P,i=new o._f){this._populateTmpTransformation(t,i);const n=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w});if(!e.xrHitResult.createAnchor)throw this.detach(),new Error("Anchors not enabled in this environment/browser");try{const t=await e.xrHitResult.createAnchor(n);return new Promise(((e,i)=>{this._futureAnchors.push({nativeAnchor:t,resolved:!1,submitted:!0,xrTransformation:n,resolve:e,reject:i})}))}catch(lt){throw new Error(lt)}}async addAnchorAtPositionAndRotationAsync(e,t=new o._f,i=!1){this._populateTmpTransformation(e,t);const n=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w}),s=i&&this.attached&&this._xrSessionManager.currentFrame?await this._createAnchorAtTransformation(n,this._xrSessionManager.currentFrame):void 0;return new Promise(((e,t)=>{this._futureAnchors.push({nativeAnchor:s,resolved:!1,submitted:!1,xrTransformation:n,resolve:e,reject:t})}))}get anchors(){return this._trackedAnchors}detach(){if(!super.detach())return!1;if(!this._options.doNotRemoveAnchorsOnSessionEnded)for(;this._trackedAnchors.length;){const t=this._trackedAnchors.pop();if(t){try{t.remove()}catch(e){}this.onAnchorRemovedObservable.notifyObservers(t)}}return!0}dispose(){this._futureAnchors.length=0,super.dispose(),this.onAnchorAddedObservable.clear(),this.onAnchorRemovedObservable.clear(),this.onAnchorUpdatedObservable.clear()}_onXRFrame(e){if(!this.attached||!e)return;const t=e.trackedAnchors;if(t){const i=this._trackedAnchors.filter((e=>!t.has(e.xrAnchor))).map((e=>this._trackedAnchors.indexOf(e)));let n=0;i.forEach((e=>{const t=this._trackedAnchors.splice(e-n,1)[0];this.onAnchorRemovedObservable.notifyObservers(t),n++})),t.forEach((t=>{if(this._lastFrameDetected.has(t)){const n=this._findIndexInAnchorArray(t),s=this._trackedAnchors[n];try{this._updateAnchorWithXRFrame(t,s,e),s.attachedNode&&(s.attachedNode.rotationQuaternion=s.attachedNode.rotationQuaternion||new o._f,s.transformationMatrix.decompose(s.attachedNode.scaling,s.attachedNode.rotationQuaternion,s.attachedNode.position)),this.onAnchorUpdatedObservable.notifyObservers(s)}catch(i){se.w1.Warn("Anchor could not be updated")}}else{const i={id:dy++,xrAnchor:t,remove:()=>t.delete()},n=this._updateAnchorWithXRFrame(t,i,e);this._trackedAnchors.push(n),this.onAnchorAddedObservable.notifyObservers(n);const s=this._futureAnchors.filter((e=>e.nativeAnchor===t))[0];s&&(s.resolve(n),s.resolved=!0)}})),this._lastFrameDetected=t}this._futureAnchors.forEach((t=>{t.resolved||t.submitted||(this._createAnchorAtTransformation(t.xrTransformation,e).then((e=>{t.nativeAnchor=e}),(e=>{t.resolved=!0,t.reject(e)})),t.submitted=!0)}))}_findIndexInAnchorArray(e){for(let t=0;t()=>new uy(e,t)),uy.Version);let py=0;class fy extends nt{constructor(e,t={}){super(e),this._options=t,this._detectedPlanes=[],this._enabled=!1,this._lastFrameDetected=new Set,this.onPlaneAddedObservable=new r.y$,this.onPlaneRemovedObservable=new r.y$,this.onPlaneUpdatedObservable=new r.y$,this.xrNativeFeatureName="plane-detection",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){if(!super.detach())return!1;if(!this._options.doNotRemovePlanesOnSessionEnded)for(;this._detectedPlanes.length;){const e=this._detectedPlanes.pop();e&&this.onPlaneRemovedObservable.notifyObservers(e)}return!0}dispose(){super.dispose(),this.onPlaneAddedObservable.clear(),this.onPlaneRemovedObservable.clear(),this.onPlaneUpdatedObservable.clear()}isCompatible(){return"undefined"!=typeof XRPlane}_onXRFrame(e){var t;if(!this.attached||!this._enabled||!e)return;const i=e.detectedPlanes||(null===(t=e.worldInformation)||void 0===t?void 0:t.detectedPlanes);if(i){for(let e=0;e{if(this._lastFrameDetected.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){const i=this._findIndexInPlaneArray(t),n=this._detectedPlanes[i];this._updatePlaneWithXRPlane(t,n,e),this.onPlaneUpdatedObservable.notifyObservers(n)}}else{const i={id:py++,xrPlane:t,polygonDefinition:[]},n=this._updatePlaneWithXRPlane(t,i,e);this._detectedPlanes.push(n),this.onPlaneAddedObservable.notifyObservers(n)}})),this._lastFrameDetected=i}}_init(){const e=()=>{this._enabled=!0,this._detectedPlanes.length&&(this._detectedPlanes.length=0)};this._xrSessionManager.isNative&&this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions),this._xrSessionManager.session.updateWorldTrackingState?(this._xrSessionManager.session.updateWorldTrackingState({planeDetectionState:{enabled:!0}}),e()):e()}_updatePlaneWithXRPlane(e,t,i){t.polygonDefinition=e.polygon.map((e=>{const t=this._xrSessionManager.scene.useRightHandedSystem?1:-1;return new o.P(e.x,e.y,e.z*t)}));const n=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(n){const e=t.transformationMatrix||new o.y3;o.y3.FromArrayToRef(n.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t.transformationMatrix=e,this._options.worldParentNode&&e.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),e)}return t}_findIndexInPlaneArray(e){for(let t=0;t()=>new fy(e,t)),fy.Version);class _y extends nt{constructor(e,t={}){super(e),this.options=t,this.onBackgroundStateChangedObservable=new r.y$}attach(){return this._setBackgroundState(!1),super.attach()}detach(){return this._setBackgroundState(!0),super.detach()}dispose(){super.dispose(),this.onBackgroundStateChangedObservable.clear()}_onXRFrame(e){}_setBackgroundState(e){const t=this._xrSessionManager.scene;if(!this.options.ignoreEnvironmentHelper)if(this.options.environmentHelperRemovalFlags){if(this.options.environmentHelperRemovalFlags.skyBox){const i=t.getMeshByName("BackgroundSkybox");i&&i.setEnabled(e)}if(this.options.environmentHelperRemovalFlags.ground){const i=t.getMeshByName("BackgroundPlane");i&&i.setEnabled(e)}}else{const i=t.getMeshByName("BackgroundHelper");i&&i.setEnabled(e)}this.options.backgroundMeshes&&this.options.backgroundMeshes.forEach((t=>t.setEnabled(e))),this.onBackgroundStateChangedObservable.notifyObservers(e)}}_y.Name=tt.BACKGROUND_REMOVER,_y.Version=1,it.AddWebXRFeature(_y.Name,((e,t)=>()=>new _y(e,t)),_y.Version,!0);class my extends nt{_createPhysicsImpostor(e){const t=this._options.physicsProperties.impostorType||rt.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,n=gl("impostor-mesh-"+e.uniqueId,{diameterX:"number"==typeof i?i:i.width,diameterY:"number"==typeof i?i:i.height,diameterZ:"number"==typeof i?i:i.depth});n.isVisible=this._debugMode,n.isPickable=!1,n.rotationQuaternion=new o._f;const s=e.grip||e.pointer;n.position.copyFrom(s.position),n.rotationQuaternion.copyFrom(s.rotationQuaternion);const r=new rt(n,t,Object.assign({mass:0},this._options.physicsProperties));this._controllers[e.uniqueId]={xrController:e,impostor:r,impostorMesh:n}}constructor(e,t){super(e),this._options=t,this._attachController=e=>{this._controllers[e.uniqueId]||(this._xrSessionManager.scene.isPhysicsEnabled()||p.Y.Warn("physics engine not enabled, skipped. Please add this controller manually."),this._options.physicsProperties.useControllerMesh&&e.inputSource.gamepad?e.onMotionControllerInitObservable.addOnce((t=>{t._doNotLoadControllerMesh?this._createPhysicsImpostor(e):t.onModelLoadedObservable.addOnce((()=>{const i=new rt(t.rootMesh,rt.MeshImpostor,Object.assign({mass:0},this._options.physicsProperties)),n=e.grip||e.pointer;this._controllers[e.uniqueId]={xrController:e,impostor:i,oldPos:n.position.clone(),oldRotation:n.rotationQuaternion.clone()}}))})):this._createPhysicsImpostor(e))},this._controllers={},this._debugMode=!1,this._delta=0,this._lastTimestamp=0,this._tmpQuaternion=new o._f,this._tmpVector=new o.P,this._options.physicsProperties||(this._options.physicsProperties={})}_enablePhysicsDebug(){this._debugMode=!0,Object.keys(this._controllers).forEach((e=>{const t=this._controllers[e];t.impostorMesh&&(t.impostorMesh.isVisible=!0)}))}addController(e){this._attachController(e)}attach(){if(!super.attach())return!1;if(!this._options.xrInput)return!0;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),this._options.enableHeadsetImpostor){const e=this._options.headsetImpostorParams||{impostorType:rt.SphereImpostor,restitution:.8,impostorSize:.3},t=e.impostorSize||.3;this._headsetMesh=gl("headset-mesh",{diameterX:"number"==typeof t?t:t.width,diameterY:"number"==typeof t?t:t.height,diameterZ:"number"==typeof t?t:t.depth}),this._headsetMesh.rotationQuaternion=new o._f,this._headsetMesh.isVisible=!1,this._headsetImpostor=new rt(this._headsetMesh,e.impostorType,Object.assign({mass:0},e))}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._headsetMesh&&this._headsetMesh.dispose(),!0)}getHeadsetImpostor(){return this._headsetImpostor}getImpostorForController(e){const t="string"==typeof e?e:e.uniqueId;return this._controllers[t]?this._controllers[t].impostor:null}setPhysicsProperties(e){this._options.physicsProperties=Object.assign(Object.assign({},this._options.physicsProperties),e)}_onXRFrame(e){var t,i;if(this._delta=this._xrSessionManager.currentTimestamp-this._lastTimestamp,this._lastTimestamp=this._xrSessionManager.currentTimestamp,this._headsetMesh&&this._headsetImpostor){if(this._headsetMesh.position.copyFrom(this._options.xrInput.xrCamera.globalPosition),this._headsetMesh.rotationQuaternion.copyFrom(this._options.xrInput.xrCamera.absoluteRotation),null===(t=this._options.xrInput.xrCamera._lastXRViewerPose)||void 0===t?void 0:t.linearVelocity){const e=this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setLinearVelocity(this._tmpVector)}if(null===(i=this._options.xrInput.xrCamera._lastXRViewerPose)||void 0===i?void 0:i.angularVelocity){const e=this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setAngularVelocity(this._tmpVector)}}Object.keys(this._controllers).forEach((e=>{var t,i;const n=this._controllers[e],s=n.xrController.grip||n.xrController.pointer,r=n.oldPos||n.impostorMesh.position;if(null===(t=n.xrController._lastXRPose)||void 0===t?void 0:t.linearVelocity){const e=n.xrController._lastXRPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),n.impostor.setLinearVelocity(this._tmpVector)}else s.position.subtractToRef(r,this._tmpVector),this._tmpVector.scaleInPlace(1e3/this._delta),n.impostor.setLinearVelocity(this._tmpVector);r.copyFrom(s.position),this._debugMode&&console.log(this._tmpVector,"linear");const o=n.oldRotation||n.impostorMesh.rotationQuaternion;if(null===(i=n.xrController._lastXRPose)||void 0===i?void 0:i.angularVelocity){const e=n.xrController._lastXRPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),n.impostor.setAngularVelocity(this._tmpVector)}else if(!o.equalsWithEpsilon(s.rotationQuaternion)){o.conjugateInPlace().multiplyToRef(s.rotationQuaternion,this._tmpQuaternion);const e=Math.sqrt(this._tmpQuaternion.x*this._tmpQuaternion.x+this._tmpQuaternion.y*this._tmpQuaternion.y+this._tmpQuaternion.z*this._tmpQuaternion.z);if(this._tmpVector.set(this._tmpQuaternion.x,this._tmpQuaternion.y,this._tmpQuaternion.z),e<.001)this._tmpVector.scaleInPlace(2);else{const t=2*Math.atan2(e,this._tmpQuaternion.w);this._tmpVector.scaleInPlace(t/(e*(this._delta/1e3)))}n.impostor.setAngularVelocity(this._tmpVector)}o.copyFrom(s.rotationQuaternion),this._debugMode&&console.log(this._tmpVector,this._tmpQuaternion,"angular")}))}_detachController(e){const t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])}}my.Name=tt.PHYSICS_CONTROLLERS,my.Version=1,it.AddWebXRFeature(my.Name,((e,t)=>()=>new my(e,t)),my.Version,!0);class gy extends nt{constructor(e,t={}){super(e),this.options=t,this._tmpMat=new o.y3,this._tmpPos=new o.P,this._tmpQuat=new o._f,this._initHitTestSource=e=>{if(!e)return;const t=new XRRay(this.options.offsetRay||{}),i={space:this.options.useReferenceSpace?e:this._xrSessionManager.viewerReferenceSpace,offsetRay:t};this.options.entityTypes&&(i.entityTypes=this.options.entityTypes),i.space?this._xrSessionManager.session.requestHitTestSource(i).then((e=>{this._xrHitTestSource&&this._xrHitTestSource.cancel(),this._xrHitTestSource=e})):se.w1.Warn("waiting for viewer reference space to initialize")},this.autoCloneTransformation=!1,this.onHitTestResultObservable=new r.y$,this.paused=!1,this.xrNativeFeatureName="hit-test",se.w1.Warn("Hit test is an experimental and unstable feature.")}attach(){if(!super.attach())return!1;if(!this._xrSessionManager.session.requestHitTestSource)return!1;if(this.options.disablePermanentHitTest||(this._xrSessionManager.referenceSpace&&this._initHitTestSource(this._xrSessionManager.referenceSpace),this._xrSessionManager.onXRReferenceSpaceChanged.add(this._initHitTestSource)),this.options.enableTransientHitTest){const e=new XRRay(this.options.transientOffsetRay||{});this._xrSessionManager.session.requestHitTestSourceForTransientInput({profile:this.options.transientHitTestProfile||"generic-touchscreen",offsetRay:e,entityTypes:this.options.entityTypes}).then((e=>{this._transientXrHitTestSource=e}))}return!0}detach(){return!!super.detach()&&(this._xrHitTestSource&&(this._xrHitTestSource.cancel(),this._xrHitTestSource=null),this._xrSessionManager.onXRReferenceSpaceChanged.removeCallback(this._initHitTestSource),this._transientXrHitTestSource&&(this._transientXrHitTestSource.cancel(),this._transientXrHitTestSource=null),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(this.attached&&!this.paused){if(this._xrHitTestSource){const t=e.getHitTestResults(this._xrHitTestSource);this._processWebXRHitTestResult(t)}if(this._transientXrHitTestSource){e.getHitTestResultsForTransientInput(this._transientXrHitTestSource).forEach((e=>{this._processWebXRHitTestResult(e.results,e.inputSource)}))}}}_processWebXRHitTestResult(e,t){const i=[];e.forEach((e=>{const n=e.getPose(this._xrSessionManager.referenceSpace);if(!n)return;const s=n.transform.position,r=n.transform.orientation;this._tmpPos.set(s.x,s.y,s.z),this._tmpQuat.set(r.x,r.y,r.z,r.w),o.y3.FromFloat32ArrayToRefScaled(n.transform.matrix,0,1,this._tmpMat),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpPos.z*=-1,this._tmpQuat.z*=-1,this._tmpQuat.w*=-1,this._tmpMat.toggleModelMatrixHandInPlace());const a={position:this.autoCloneTransformation?this._tmpPos.clone():this._tmpPos,rotationQuaternion:this.autoCloneTransformation?this._tmpQuat.clone():this._tmpQuat,transformationMatrix:this.autoCloneTransformation?this._tmpMat.clone():this._tmpMat,inputSource:t,isTransient:!!t,xrHitResult:e};i.push(a)})),this.onHitTestResultObservable.notifyObservers(i)}}gy.Name=tt.HIT_TEST,gy.Version=2,it.AddWebXRFeature(gy.Name,((e,t)=>()=>new gy(e,t)),gy.Version,!1);class vy extends nt{get featurePointCloud(){return this._featurePointCloud}constructor(e){super(e),this._enabled=!1,this._featurePointCloud=[],this.onFeaturePointsAddedObservable=new r.y$,this.onFeaturePointsUpdatedObservable=new r.y$,this.xrNativeFeatureName="bjsfeature-points",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){return!!super.detach()&&(this.featurePointCloud.length=0,!0)}dispose(){super.dispose(),this._featurePointCloud.length=0,this.onFeaturePointsUpdatedObservable.clear(),this.onFeaturePointsAddedObservable.clear()}_onXRFrame(e){if(!this.attached||!this._enabled||!e)return;const t=e.featurePointCloud;if(t&&0!==t.length){if(t.length%5!=0)throw new Error("Received malformed feature point cloud of length: "+t.length);const e=t.length/5,i=new Array,n=new Array;for(let s=0;s0&&this.onFeaturePointsAddedObservable.notifyObservers(n),i.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(i)}}_init(){this._xrSessionManager.session.trySetFeaturePointCloudEnabled&&this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)&&(this._enabled=!0)}}vy.Name=tt.FEATURE_POINTS,vy.Version=1,it.AddWebXRFeature(vy.Name,(e=>()=>new vy(e)),vy.Version);let Ty=0;class Sy extends nt{constructor(e,t={}){super(e),this._options=t,this._detectedMeshes=new Map,this.onMeshAddedObservable=new r.y$,this.onMeshRemovedObservable=new r.y$,this.onMeshUpdatedObservable=new r.y$,this.xrNativeFeatureName="mesh-detection",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){return!!super.detach()&&(this._xrSessionManager.isNative&&this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!1),this._options.doNotRemoveMeshesOnSessionEnded||(this._detectedMeshes.forEach((e=>{this.onMeshRemovedObservable.notifyObservers(e)})),this._detectedMeshes.clear()),!0)}dispose(){super.dispose(),this.onMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onMeshUpdatedObservable.clear()}_onXRFrame(e){var t;try{if(!this.attached||!e)return;const i=null===(t=e.worldInformation)||void 0===t?void 0:t.detectedMeshes;if(i){const t=new Set;this._detectedMeshes.forEach(((e,n)=>{i.has(n)||t.add(n)})),t.forEach((e=>{const t=this._detectedMeshes.get(e);t&&(this.onMeshRemovedObservable.notifyObservers(t),this._detectedMeshes.delete(e))})),i.forEach((t=>{if(this._detectedMeshes.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){const i=this._detectedMeshes.get(t);i&&(this._updateVertexDataWithXRMesh(t,i,e),this.onMeshUpdatedObservable.notifyObservers(i))}}else{const i={id:Ty++,xrMesh:t},n=this._updateVertexDataWithXRMesh(t,i,e);this._detectedMeshes.set(t,n),this.onMeshAddedObservable.notifyObservers(n)}}))}}catch(lt){console.log(lt.stack)}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!0),this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions(this._options.preferredDetectorOptions))}_updateVertexDataWithXRMesh(e,t,i){if(t.xrMesh=e,t.worldParentNode=this._options.worldParentNode,this._options.convertCoordinateSystems){if(this._xrSessionManager.scene.useRightHandedSystem)t.positions=e.positions,t.normals=e.normals;else{t.positions=new Float32Array(e.positions.length);for(let i=0;i()=>new Sy(e,t)),Sy.Version,!1),function(e){e[e.NotReceived=0]="NotReceived",e[e.Waiting=1]="Waiting",e[e.Received=2]="Received"}(Ey||(Ey={}));class xy extends nt{constructor(e,t){super(e),this.options=t,this.onUntrackableImageFoundObservable=new r.y$,this.onTrackableImageFoundObservable=new r.y$,this.onTrackedImageUpdatedObservable=new r.y$,this._trackableScoreStatus=Ey.NotReceived,this._trackedImages=[],this.xrNativeFeatureName="image-tracking"}attach(){return super.attach()}detach(){return super.detach()}getTrackedImageById(e){return this._trackedImages[e]||null}dispose(){super.dispose(),this._trackedImages.forEach((e=>{e.originalBitmap.close()})),this._trackedImages.length=0,this.onTrackableImageFoundObservable.clear(),this.onUntrackableImageFoundObservable.clear(),this.onTrackedImageUpdatedObservable.clear()}async getXRSessionInitExtension(){if(!this.options.images||!this.options.images.length)return{};const e=this.options.images.map((e=>"string"==typeof e.src?this._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(e.src):Promise.resolve(e.src)));try{const t=await Promise.all(e);return this._originalTrackingRequest=t.map(((e,t)=>({image:e,widthInMeters:this.options.images[t].estimatedRealWorldWidth}))),{trackedImages:this._originalTrackingRequest}}catch(t){return se.w1.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),{}}}_onXRFrame(e){if(!e.getImageTrackingResults||this._trackableScoreStatus===Ey.Waiting)return;if(this._trackableScoreStatus===Ey.NotReceived)return void this._checkScoresAsync();const t=e.getImageTrackingResults();for(const i of t){let t=!1;const n=i.index,s=this._trackedImages[n];if(!s)continue;s.xrTrackingResult=i,s.realWorldWidth!==i.measuredWidthInMeters&&(s.realWorldWidth=i.measuredWidthInMeters,t=!0);const r=e.getPose(i.imageSpace,this._xrSessionManager.referenceSpace);if(r){const e=s.transformationMatrix;o.y3.FromArrayToRef(r.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t=!0}const a="emulated"===i.trackingState;s.emulated!==a&&(s.emulated=a,t=!0),t&&this.onTrackedImageUpdatedObservable.notifyObservers(s)}}async _checkScoresAsync(){if(!this._xrSessionManager.session.getTrackedImageScores||this._trackableScoreStatus!==Ey.NotReceived)return;this._trackableScoreStatus=Ey.Waiting;const e=await this._xrSessionManager.session.getTrackedImageScores();if(e&&0!==e.length){for(let t=0;t0?Ey.Received:Ey.NotReceived}else this._trackableScoreStatus=Ey.NotReceived}}xy.Name=tt.IMAGE_TRACKING,xy.Version=1,it.AddWebXRFeature(xy.Name,((e,t)=>()=>new xy(e,t)),xy.Version,!1);class by extends nt{constructor(e,t){super(e),this.options=t,this._domOverlayType=null,this._beforeXRSelectListener=null,this._element=null,this.xrNativeFeatureName="dom-overlay",se.w1.Warn("dom-overlay is an experimental and unstable feature.")}attach(){return!!super.attach()&&(!(!this._xrSessionManager.session.domOverlayState||null===this._xrSessionManager.session.domOverlayState.type)&&(this._domOverlayType=this._xrSessionManager.session.domOverlayState.type,null!==this._element&&!0===this.options.supressXRSelectEvents&&(this._beforeXRSelectListener=e=>{e.preventDefault()},this._element.addEventListener("beforexrselect",this._beforeXRSelectListener)),!0))}get domOverlayType(){return this._domOverlayType}dispose(){super.dispose(),null!==this._element&&this._beforeXRSelectListener&&this._element.removeEventListener("beforexrselect",this._beforeXRSelectListener)}_onXRFrame(e){}async getXRSessionInitExtension(){if(void 0===this.options.element)return se.w1.Warn('"element" option must be provided to attach xr-dom-overlay feature.'),{};if("string"==typeof this.options.element){const e=document.querySelector(this.options.element);if(null===e)return se.w1.Warn(`element not found '${this.options.element}' (not requesting xr-dom-overlay)`),{};this._element=e}else this._element=this.options.element;return{domOverlay:{root:this._element}}}}by.Name=tt.DOM_OVERLAY,by.Version=1,it.AddWebXRFeature(by.Name,((e,t)=>()=>new by(e,t)),by.Version,!1);class Cy extends nt{get movementDirection(){return this._movementDirection}get movementEnabled(){return this._featureContext.movementEnabled}set movementEnabled(e){this._featureContext.movementEnabled=e}get movementOrientationFollowsViewerPose(){return this._featureContext.movementOrientationFollowsViewerPose}set movementOrientationFollowsViewerPose(e){this._featureContext.movementOrientationFollowsViewerPose=e}get movementSpeed(){return this._featureContext.movementSpeed}set movementSpeed(e){this._featureContext.movementSpeed=e}get movementThreshold(){return this._featureContext.movementThreshold}set movementThreshold(e){this._featureContext.movementThreshold=e}get rotationEnabled(){return this._featureContext.rotationEnabled}set rotationEnabled(e){this._featureContext.rotationEnabled=e}get rotationSpeed(){return this._featureContext.rotationSpeed}set rotationSpeed(e){this._featureContext.rotationSpeed=e}get rotationThreshold(){return this._featureContext.rotationThreshold}set rotationThreshold(e){this._featureContext.rotationThreshold=e}constructor(e,t){var i,n,s,r,a,l;super(e),this._controllers={},this._currentRegistrationConfigurations=[],this._movementDirection=null,this._tmpRotationMatrix=o.y3.Identity(),this._tmpTranslationDirection=new o.P,this._tmpMovementTranslation=new o.P,this._attachController=e=>{if(this._controllers[e.uniqueId])return;this._controllers[e.uniqueId]={xrController:e,registeredComponents:[]};const t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){const i=()=>{if(e.motionController)for(const i of this._currentRegistrationConfigurations){let n=null;if(i.allowedComponentTypes)for(const t of i.allowedComponentTypes){const i=e.motionController.getComponentOfType(t);if(null!==i){n=i;break}}if(i.mainComponentOnly){const t=e.motionController.getMainComponent();if(null===t)continue;n=t}if("function"==typeof i.componentSelectionPredicate&&(n=i.componentSelectionPredicate(e)),n&&i.forceHandedness&&e.inputSource.handedness!==i.forceHandedness)continue;if(null===n)continue;const s={registrationConfiguration:i,component:n};t.registeredComponents.push(s),"axisChangedHandler"in i&&(s.onAxisChangedObserver=n.onAxisValueChangedObservable.add((e=>{i.axisChangedHandler(e,this._movementState,this._featureContext,this._xrInput)}))),"buttonChangedhandler"in i&&(s.onButtonChangedObserver=n.onButtonStateChangedObservable.add((()=>{n.changes.pressed&&i.buttonChangedhandler(n.changes.pressed,this._movementState,this._featureContext,this._xrInput)})))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce((()=>{i()}))}},t&&void 0!==t.xrInput?(Array.isArray(t.customRegistrationConfigurations)?this._currentRegistrationConfigurations=t.customRegistrationConfigurations:this._currentRegistrationConfigurations=Cy.REGISTRATIONS.default,this._featureContext={movementEnabled:t.movementEnabled||!0,movementOrientationFollowsViewerPose:null===(i=t.movementOrientationFollowsViewerPose)||void 0===i||i,movementSpeed:null!==(n=t.movementSpeed)&&void 0!==n?n:1,movementThreshold:null!==(s=t.movementThreshold)&&void 0!==s?s:.25,rotationEnabled:null===(r=t.rotationEnabled)||void 0===r||r,rotationSpeed:null!==(a=t.rotationSpeed)&&void 0!==a?a:1,rotationThreshold:null!==(l=t.rotationThreshold)&&void 0!==l?l:.25},this._movementState={moveX:0,moveY:0,rotateX:0,rotateY:0},this._xrInput=t.xrInput):se.w1.Error('WebXRControllerMovement feature requires "xrInput" option.')}attach(){return!!super.attach()&&(this._xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._controllers={},!0)}_onXRFrame(e){if(this.attach){if(null===this._movementDirection&&(this._movementDirection=this._xrInput.xrCamera.rotationQuaternion.clone()),0!==this._movementState.rotateX&&this._featureContext.rotationEnabled){const e=.001*this._xrSessionManager.scene.getEngine().getDeltaTime()*this._featureContext.rotationSpeed*this._movementState.rotateX*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);!0===this._featureContext.movementOrientationFollowsViewerPose?(this._xrInput.xrCamera.cameraRotation.y+=e,this._movementDirection=this._xrInput.xrCamera.rotationQuaternion.multiply(o._f.RotationYawPitchRoll(e,0,0))):this._movementDirection.multiplyInPlace(o._f.RotationYawPitchRoll(3*e,0,0))}else!0===this._featureContext.movementOrientationFollowsViewerPose&&this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion);0===this._movementState.moveX&&0===this._movementState.moveY||!this._featureContext.movementEnabled||(o.y3.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),o.P.TransformCoordinatesToRef(this._tmpTranslationDirection,this._tmpRotationMatrix,this._tmpMovementTranslation),this._tmpMovementTranslation.scaleInPlace(this._xrInput.xrCamera._computeLocalCameraSpeed()*this._featureContext.movementSpeed),this._xrInput.xrCamera.cameraDirection.addInPlace(this._tmpMovementTranslation))}}_detachController(e){const t=this._controllers[e];if(t){for(const e of t.registeredComponents)e.onAxisChangedObserver&&e.component.onAxisValueChangedObservable.remove(e.onAxisChangedObserver),e.onButtonChangedObserver&&e.component.onButtonStateChangedObservable.remove(e.onButtonChangedObserver);delete this._controllers[e]}}}Cy.Name=tt.MOVEMENT,Cy.REGISTRATIONS={default:[{allowedComponentTypes:[Z_.THUMBSTICK_TYPE,Z_.TOUCHPAD_TYPE],forceHandedness:"left",axisChangedHandler:(e,t,i)=>{t.rotateX=Math.abs(e.x)>i.rotationThreshold?e.x:0,t.rotateY=Math.abs(e.y)>i.rotationThreshold?e.y:0}},{allowedComponentTypes:[Z_.THUMBSTICK_TYPE,Z_.TOUCHPAD_TYPE],forceHandedness:"right",axisChangedHandler:(e,t,i)=>{t.moveX=Math.abs(e.x)>i.movementThreshold?e.x:0,t.moveY=Math.abs(e.y)>i.movementThreshold?e.y:0}}]},Cy.Version=1,it.AddWebXRFeature(Cy.Name,((e,t)=>()=>new Cy(e,t)),Cy.Version,!0);class yy extends nt{constructor(e,t){super(e),this.options=t,this._canvasContext=null,this._reflectionCubeMap=null,this._xrLightEstimate=null,this._xrLightProbe=null,this._xrWebGLBinding=null,this._lightDirection=o.P.Up().negateInPlace(),this._lightColor=a.Wo.White(),this._intensity=1,this._sphericalHarmonics=new Oh,this._cubeMapPollTime=Date.now(),this._lightEstimationPollTime=Date.now(),this._reflectionCubeMapTextureSize=16,this.directionalLight=null,this.onReflectionCubeMapUpdatedObservable=new r.y$,this._updateReflectionCubeMap=()=>{var e;if(!this._xrLightProbe)return;if(this.options.cubeMapPollInterval){const e=Date.now();if(e-this._cubeMapPollTime{this._xrLightProbe=e,this.options.disableCubeMapReflection||(this._reflectionCubeMap||(this._reflectionCubeMap=new Re(this._xrSessionManager.scene),this._reflectionCubeMap._isCube=!0,this._reflectionCubeMap.coordinatesMode=3,this.options.setSceneEnvironmentTexture&&(this._xrSessionManager.scene.environmentTexture=this._reflectionCubeMap)),this._xrLightProbe.addEventListener("reflectionchange",this._updateReflectionCubeMap))})),!0}detach(){const e=super.detach();return null===this._xrLightProbe||this.options.disableCubeMapReflection||(this._xrLightProbe.removeEventListener("reflectionchange",this._updateReflectionCubeMap),this._xrLightProbe=null),this._canvasContext=null,this._xrLightEstimate=null,this._xrWebGLBinding=null,e}dispose(){super.dispose(),this.onReflectionCubeMapUpdatedObservable.clear(),this.directionalLight&&(this.directionalLight.dispose(),this.directionalLight=null),null!==this._reflectionCubeMap&&(this._reflectionCubeMap._texture&&this._reflectionCubeMap._texture.dispose(),this._reflectionCubeMap.dispose(),this._reflectionCubeMap=null)}_onXRFrame(e){var t;if(null!==this._xrLightProbe){if(this.options.lightEstimationPollInterval){const e=Date.now();if(e-this._lightEstimationPollTime()=>new yy(e,t)),yy.Version,!1);class Ay extends nt{constructor(e){super(e),this.onEyeTrackingStartedObservable=new r.y$,this.onEyeTrackingEndedObservable=new r.y$,this.onEyeTrackingFrameUpdateObservable=new r.y$,this._eyeTrackingStartListener=e=>{this._latestEyeSpace=e.gazeSpace,this._gazeRay=new qe(o.P.Zero(),o.P.Forward()),this.onEyeTrackingStartedObservable.notifyObservers(this._gazeRay)},this._eyeTrackingEndListener=()=>{this._latestEyeSpace=null,this._gazeRay=null,this.onEyeTrackingEndedObservable.notifyObservers()},this.xrNativeFeatureName="eye-tracking",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}dispose(){super.dispose(),this._xrSessionManager.session.removeEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.removeEventListener("eyetrackingend",this._eyeTrackingEndListener),this.onEyeTrackingStartedObservable.clear(),this.onEyeTrackingEndedObservable.clear(),this.onEyeTrackingFrameUpdateObservable.clear()}get isEyeGazeValid(){return!!this._gazeRay}getEyeGaze(){return this._gazeRay}_onXRFrame(e){if(this.attached&&e&&this._latestEyeSpace&&this._gazeRay){const t=e.getPose(this._latestEyeSpace,this._xrSessionManager.referenceSpace);if(t){this._gazeRay.origin.set(t.transform.position.x,t.transform.position.y,t.transform.position.z);const e=t.transform.orientation;o.jp.Quaternion[0].set(e.x,e.y,e.z,e.w),this._xrSessionManager.scene.useRightHandedSystem?o.P.RightHandedForwardReadOnly.rotateByQuaternionToRef(o.jp.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,o.jp.Quaternion[0].z*=-1,o.jp.Quaternion[0].w*=-1,o.P.LeftHandedForwardReadOnly.rotateByQuaternionToRef(o.jp.Quaternion[0],this._gazeRay.direction)),this.onEyeTrackingFrameUpdateObservable.notifyObservers(this._gazeRay)}}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.addEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.addEventListener("eyetrackingend",this._eyeTrackingEndListener))}}Ay.Name=tt.EYE_TRACKING,Ay.Version=1,it.AddWebXRFeature(Ay.Name,(e=>()=>new Ay(e)),Ay.Version,!1);class Ry{constructor(e,t){this._samples=[],this._idx=0;for(let i=0;i=this._samples.length)throw new Error("Index out of bounds");return this._samples[(this._idx+e)%this._samples.length]}}class Py{constructor(){this._samples=new Ry(20),this._entropy=0,this.onFirstStepDetected=new r.y$}update(e,t,i,n){this._samples.push(e,t);const s=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=o.FM.Distance(s,this._samples.at(1)),this._entropy>this._entropyThreshold)return;let r;for(r=this._samePointCheckStartIdx;ra&&(l=E,a=S);if(ar*this._squaredProjectionDistanceThreshold)return;const _=o.jp.Vector3[0];_.set(i,n,0);const m=o.jp.Vector3[1];m.set(c.x,c.y,0);const g=o.P.Cross(_,m).z>0,v=s.clone(),T=s.clone();h.subtractToRef(s,c),g?(c.scaleAndAddToRef(this._axisToApexShrinkFactor,v),c.scaleAndAddToRef(this._axisToApexExtendFactor,T)):(c.scaleAndAddToRef(this._axisToApexExtendFactor,v),c.scaleAndAddToRef(this._axisToApexShrinkFactor,T)),this.onFirstStepDetected.notifyObservers({leftApex:v,rightApex:T,currentPosition:s,currentStepDirection:g?"right":"left"})}reset(){for(let e=0;ethis._maxT&&(this._maxT=this._t,this._maxTPosition.copyFromFloats(e,t)),!(this._vitalityi&&(this.onMovement.notifyObservers({deltaT:this._t-i}),i<.5&&this._t>=.5&&this.onFootfall.notifyObservers({foot:this._steppingLeft?"left":"right"})),this._t<.95*this._maxT&&(this._currentPosition.copyFromFloats(e,t),this._steppingLeft?this._leftApex.copyFrom(this._maxTPosition):this._rightApex.copyFrom(this._maxTPosition),this._reset(this._leftApex,this._rightApex,this._currentPosition,!this._steppingLeft)),!(this._axisLength<.03))}get _vitalityThreshold(){return.1}get forward(){return this._forward}}class My{static get _MillisecondsPerUpdate(){return 1e3/15}constructor(e){this._detector=new Py,this._walker=null,this._movement=new o.FM,this._millisecondsSinceLastUpdate=My._MillisecondsPerUpdate,this.movementThisFrame=o.P.Zero(),this._engine=e,this._detector.onFirstStepDetected.add((e=>{this._walker||(this._walker=new Iy(e.leftApex,e.rightApex,e.currentPosition,e.currentStepDirection),this._walker.onFootfall.add((()=>{console.log("Footfall!")})),this._walker.onMovement.add((e=>{this._walker.forward.scaleAndAddToRef(.024*e.deltaT,this._movement)})))}))}update(e,t){if(t.y=0,t.normalize(),this._millisecondsSinceLastUpdate+=this._engine.getDeltaTime(),this._millisecondsSinceLastUpdate>=My._MillisecondsPerUpdate){if(this._millisecondsSinceLastUpdate-=My._MillisecondsPerUpdate,this._detector.update(e.x,e.z,t.x,t.z),this._walker){this._walker.update(e.x,e.z)||(this._walker=null)}this._movement.scaleInPlace(.85)}this.movementThisFrame.set(this._movement.x,0,this._movement.y)}}class Oy extends nt{static get Name(){return tt.WALKING_LOCOMOTION}static get Version(){return 1}get locomotionTarget(){return this._locomotionTarget}set locomotionTarget(e){this._locomotionTarget=e,this._isLocomotionTargetWebXRCamera="WebXRCamera"===this._locomotionTarget.getClassName()}constructor(e,t){super(e),this._up=new o.P,this._forward=new o.P,this._position=new o.P,this._movement=new o.P,this._sessionManager=e,this.locomotionTarget=t.locomotionTarget,this._isLocomotionTargetWebXRCamera&&p.Y.Warn("Using walking locomotion directly on a WebXRCamera may have unintended interactions with other XR techniques. Using an XR space parent is highly recommended")}isCompatible(){return void 0===this._sessionManager.sessionMode||"immersive-vr"===this._sessionManager.sessionMode}attach(){return!(!this.isCompatible||!super.attach())&&(this._walker=new My(this._sessionManager.scene.getEngine()),!0)}detach(){return!!super.detach()&&(this._walker=null,!0)}_onXRFrame(e){const t=e.getViewerPose(this._sessionManager.baseReferenceSpace);if(!t)return;const i=this.locomotionTarget.getScene().useRightHandedSystem?1:-1,n=t.transform.matrix;this._up.copyFromFloats(n[4],n[5],i*n[6]),this._forward.copyFromFloats(n[8],n[9],i*n[10]),this._position.copyFromFloats(n[12],n[13],i*n[14]),this._forward.scaleAndAddToRef(.05,this._position),this._up.scaleAndAddToRef(-.05,this._position),this._walker.update(this._position,this._forward),this._movement.copyFrom(this._walker.movementThisFrame),this._isLocomotionTargetWebXRCamera||o.P.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}}it.AddWebXRFeature(Oy.Name,((e,t)=>()=>new Oy(e,t)),Oy.Version,!1);class Dy extends Sa{constructor(e,t,i,n,s,r){super(e,t,i,n,r),this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=n,this.isMultiview=s,this.createRTTProvider=r}}class Ny extends Ca{constructor(e,t,i){super(e.scene,i),this._xrSessionManager=e,this._xrWebGLBinding=t,this.layerWrapper=i,this._lastSubImages=new Map,this._compositionLayer=i.layer}_getRenderTargetForSubImage(e,t){var i,n,s,r;const o=this._lastSubImages.get(t),a="left"==t?0:1,l=null!==(i=e.colorTextureWidth)&&void 0!==i?i:e.textureWidth,h=null!==(n=e.colorTextureHeight)&&void 0!==n?n:e.textureHeight;if(!this._renderTargetTextures[a]||(null==o?void 0:o.textureWidth)!==l||(null==o?void 0:o.textureHeight)!==h){let t;const i=null!==(s=e.depthStencilTextureWidth)&&void 0!==s?s:l,n=null!==(r=e.depthStencilTextureHeight)&&void 0!==r?r:h;l!==i&&h!==n||(t=e.depthStencilTexture),this._renderTargetTextures[a]=this._createRenderTargetTexture(l,h,null,e.colorTexture,t,this.layerWrapper.isMultiview),this._framebufferDimensions={framebufferWidth:l,framebufferHeight:h}}return this._lastSubImages.set(t,e),this._renderTargetTextures[a]}_getSubImageForEye(e){const t=this._xrSessionManager.currentFrame;return t?this._xrWebGLBinding.getSubImage(this._compositionLayer,t,e):null}getRenderTargetTextureForEye(e){const t=this._getSubImageForEye(e);return t?this._getRenderTargetForSubImage(t,e):null}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}_setViewportForSubImage(e,t){var i,n;const s=null!==(i=t.colorTextureWidth)&&void 0!==i?i:t.textureWidth,r=null!==(n=t.colorTextureWidth)&&void 0!==n?n:t.textureHeight,o=t.viewport;e.x=o.x/s,e.y=o.y/r,e.width=o.width/s,e.height=o.height/r}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return!!i&&(this._setViewportForSubImage(e,i),!0)}}class Fy extends Dy{constructor(e,t,i){super((()=>e.textureWidth),(()=>e.textureHeight),e,"XRProjectionLayer",t,(e=>new wy(e,i,this))),this.layer=e}}class wy extends Ny{constructor(e,t,i){super(e,t,i),this.layerWrapper=i,this._projectionLayer=i.layer}_getSubImageForView(e){return this._xrWebGLBinding.getViewSubImage(this._projectionLayer,e)}getRenderTargetTextureForView(e){return this._getRenderTargetForSubImage(this._getSubImageForView(e),e.eye)}getRenderTargetTextureForEye(e){const t=this._lastSubImages.get(e);return t?this._getRenderTargetForSubImage(t,e):null}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}}const Ly={},By={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1};class Uy extends nt{constructor(e,t={}){super(e),this._options=t,this._existingLayers=[],this.xrNativeFeatureName="layers"}attach(){if(!super.attach())return!1;const e=this._xrSessionManager.scene.getEngine();this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this._existingLayers.length=0;const t=Object.assign({},By),i=this._options.preferMultiviewOnInit&&e.getCaps().multiview;return i&&(t.textureType="texture-array"),this.addXRSessionLayer(this.createProjectionLayer(t,i)),!0}detach(){return!!super.detach()&&(this._existingLayers.length=0,!0)}createXRWebGLLayer(e=Ly){const t=new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e);return new ya(t)}createProjectionLayer(e=By,t=!1){if(t&&"texture-array"!==e.textureType)throw new Error("Projection layers can only be made multiview if they use texture arrays. Set the textureType parameter to 'texture-array'.");if(!t&&"texture-array"===e.textureType)throw new Error("We currently only support multiview rendering when the textureType parameter is set to 'texture-array'.");const i=this._xrWebGLBinding.createProjectionLayer(e);return new Fy(i,t,this._xrWebGLBinding)}addXRSessionLayer(e){this.setXRSessionLayers([...this._existingLayers,e])}setXRSessionLayers(e){this._existingLayers=e;const t=Object.assign({},this._xrSessionManager.session.renderState);t.baseLayer=void 0,t.layers=e.map((e=>e.layer)),this._xrSessionManager.updateRenderState(t),this._xrSessionManager._setBaseLayerWrapper(e.length>0?e[0]:null)}isCompatible(){return!this._xrSessionManager.isNative&&"undefined"!=typeof XRWebGLBinding&&!!XRWebGLBinding.prototype.createProjectionLayer}dispose(){super.dispose()}_onXRFrame(e){}}Uy.Name=tt.LAYERS,Uy.Version=1,it.AddWebXRFeature(Uy.Name,((e,t)=>()=>new Uy(e,t)),Uy.Version,!1);class Vy extends nt{get width(){return this._width}get height(){return this._height}get rawValueToMeters(){return this._rawValueToMeters}get normDepthBufferFromNormView(){return this._normDepthBufferFromNormView}get depthUsage(){switch(this._xrSessionManager.session.depthUsage){case"cpu-optimized":return"cpu";case"gpu-optimized":return"gpu"}}get depthDataFormat(){switch(this._xrSessionManager.session.depthDataFormat){case"luminance-alpha":return"ushort";case"float32":return"float"}}get latestInternalTexture(){var e,t;if(!this._cachedWebGLTexture)return null;const i=this._xrSessionManager.scene.getEngine(),n=new Be.l(i,Be.S.Unknown);return n.isCube=!1,n.invertY=!1,n._useSRGBBuffer=!1,n.format="ushort"===this.depthDataFormat?2:5,n.generateMipMaps=!1,n.type="ushort"===this.depthDataFormat?5:1,n.samplingMode=7,n.width=null!==(e=this.width)&&void 0!==e?e:0,n.height=null!==(t=this.height)&&void 0!==t?t:0,n._cachedWrapU=1,n._cachedWrapV=1,n._hardwareTexture=new ba.B(this._cachedWebGLTexture,i._gl),n}get latestDepthBuffer(){return this._cachedDepthBuffer?"ushort"===this.depthDataFormat?new Uint16Array(this._cachedDepthBuffer):new Float32Array(this._cachedDepthBuffer):null}get latestDepthImageTexture(){return this._cachedDepthImageTexture}constructor(e,t){super(e),this.options=t,this._width=null,this._height=null,this._rawValueToMeters=null,this._normDepthBufferFromNormView=null,this._cachedDepthBuffer=null,this._cachedWebGLTexture=null,this._cachedDepthImageTexture=null,this.onGetDepthInMetersAvailable=new r.y$,this.xrNativeFeatureName="depth-sensing",se.w1.Warn("depth-sensing is an experimental and unstable feature.")}attach(e){if(!super.attach(e))return!1;return null!=this._xrSessionManager.session.depthDataFormat&&null!=this._xrSessionManager.session.depthUsage&&(this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._xrSessionManager.scene.getEngine()._gl),!0)}dispose(){var e;null===(e=this._cachedDepthImageTexture)||void 0===e||e.dispose()}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(null!=i)for(const n of i.views)switch(this.depthUsage){case"cpu":this._updateDepthInformationAndTextureCPUDepthUsage(e,n,this.depthDataFormat);break;case"gpu":if(!this._glBinding)break;this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding,n,this.depthDataFormat);break;default:se.w1.Error("Unknown depth usage"),this.detach()}}_updateDepthInformationAndTextureCPUDepthUsage(e,t,i){const n=e.getDepthInformation(t);if(null===n)return;const{data:s,width:r,height:o,rawValueToMeters:a,getDepthInMeters:l}=n;switch(this._width=r,this._height=o,this._rawValueToMeters=a,this._cachedDepthBuffer=s,this.onGetDepthInMetersAvailable.notifyObservers(l.bind(n)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=ze.CreateRTexture(null,r,o,this._xrSessionManager.scene,!1,!0,Le.NEAREST_SAMPLINGMODE,fe.D.TEXTURETYPE_FLOAT)),i){case"ushort":this._cachedDepthImageTexture.update(Float32Array.from(new Uint16Array(s)).map((e=>e*a)));break;case"float":this._cachedDepthImageTexture.update(new Float32Array(s).map((e=>e*a)))}}_updateDepthInformationAndTextureWebGLDepthUsage(e,t,i){const n=e.getDepthInformation(t);if(null===n)return;const{texture:s,width:r,height:o}=n;this._width=r,this._height=o,this._cachedWebGLTexture=s;const a=this._xrSessionManager.scene,l=a.getEngine().wrapWebGLTexture(s);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=ze.CreateRTexture(null,r,o,a,!1,!0,Le.NEAREST_SAMPLINGMODE,"ushort"===i?fe.D.TEXTURETYPE_UNSIGNED_BYTE:fe.D.TEXTURETYPE_FLOAT)),this._cachedDepthImageTexture._texture=l}getXRSessionInitExtension(){const e=null!=this.options.usagePreference&&0!==this.options.usagePreference.length,t=null!=this.options.dataFormatPreference&&0!==this.options.dataFormatPreference.length;return new Promise((i=>{if(e&&t){i({depthSensing:{usagePreference:this.options.usagePreference.map((e=>{switch(e){case"cpu":return"cpu-optimized";case"gpu":return"gpu-optimized"}})),dataFormatPreference:this.options.dataFormatPreference.map((e=>{switch(e){case"ushort":return"luminance-alpha";case"float":return"float32"}}))}})}else i({})}))}}Vy.Name=tt.DEPTH_SENSING,Vy.Version=1,it.AddWebXRFeature(Vy.Name,((e,t)=>()=>new Vy(e,t)),Vy.Version,!1);const ky="velocityPixelShader",Gy="precision highp float;\n#define CUSTOM_FRAGMENT_BEGIN\nvarying vec4 clipPos;\nvarying vec4 previousClipPos;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nhighp vec4 motionVector=( clipPos/clipPos.w-previousClipPos/previousClipPos.w );\ngl_FragColor=motionVector;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ht.v.ShadersStore[ky]=Gy;const zy="velocityVertexShader",Wy="#define CUSTOM_VERTEX_BEGIN\n#define VELOCITY\nattribute vec3 position;\n#include\nuniform mat4 viewProjection;\nuniform mat4 previousViewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\nuniform mat4 previousViewProjectionR;\n#endif\nvarying vec4 clipPos;\nvarying vec4 previousClipPos;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvec4 previousWorldPos=finalPreviousWorld*vec4(positionUpdated,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {\nclipPos=viewProjection*worldPos;\npreviousClipPos=previousViewProjection*previousWorldPos;\ngl_Position=clipPos;\n} else {\nclipPos=viewProjectionR*worldPos;\npreviousClipPos=previousViewProjectionR*previousWorldPos;\ngl_Position=clipPos;\n}\n#elif\nclipPos=viewProjection*worldPos;\npreviousClipPos=previousViewProjection*previousWorldPos;\ngl_Position=clipPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}";Ht.v.ShadersStore[zy]=Wy;class Hy extends Ci{constructor(e,t,i,n=512){super("spacewarp rtt",n,i,!1,!0,2,!1,void 0,!1,!1,!0,void 0,!0),this._originalPairing=[],this._previousWorldMatrices=[],this._previousTransforms=[o.y3.Identity(),o.y3.Identity()],this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight(),e,t),this._renderTarget._disposeOnlyFramebuffers=!0,this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,i&&(this._velocityMaterial=new Il("velocity shader material",i,{vertex:"velocity",fragment:"velocity"},{uniforms:["world","previousWorld","viewProjection","viewProjectionR","previousViewProjection","previousViewProjectionR"]}),this._velocityMaterial._materialHelperNeedsPreviousMatrices=!0,this._velocityMaterial.onBindObservable.add((e=>{this._previousWorldMatrices[e.uniqueId]=this._previousWorldMatrices[e.uniqueId]||e.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousWorld",this._previousWorldMatrices[e.uniqueId]),this._previousWorldMatrices[e.uniqueId]=e.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousViewProjection",this._previousTransforms[0]),this._velocityMaterial.getEffect().setMatrix("previousViewProjectionR",this._previousTransforms[1]),this._previousTransforms[0].copyFrom(i.getTransformMatrix()),this._previousTransforms[1].copyFrom(i._transformMatrixR)})),this._velocityMaterial.freeze())}render(e=!1,t=!1){this._originalPairing.length=0;const i=this.getScene();i&&this._velocityMaterial&&i.getActiveMeshes().forEach((e=>{this._originalPairing.push([e,e.material]),e.material=this._velocityMaterial})),super.render(e,t),this._originalPairing.forEach((e=>{e[0].material=e[1]}))}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindSpaceWarpFramebuffer(this._renderTarget)}getViewCount(){return 2}dispose(){super.dispose(),this._velocityMaterial.dispose(),this._previousTransforms.length=0,this._previousWorldMatrices.length=0,this._originalPairing.length=0}}class Xy{constructor(e,t,i){this._scene=e,this._xrSessionManager=t,this._xrWebGLBinding=i,this._lastSubImages=new Map,this._renderTargetTextures=new Map,this._engine=e.getEngine()}_getSubImageForView(e){const t=this._xrSessionManager._getBaseLayerWrapper();if(!t)throw new Error("For Space Warp, the base layer should be a WebXR Projection Layer.");if("XRProjectionLayer"!==t.layerType)throw new Error('For Space Warp, the base layer type should "XRProjectionLayer".');const i=t.layer;return this._xrWebGLBinding.getViewSubImage(i,e)}_setViewportForSubImage(e,t){e.x=0,e.y=0,e.width=t.motionVectorTextureWidth,e.height=t.motionVectorTextureHeight}_createRenderTargetTexture(e,t,i,n,s){if(!this._engine)throw new Error("Engine is disposed");const r={width:e,height:t},o=new Hy(n,s,this._scene,r),a=o.renderTarget;return i&&(a._framebuffer=i),a._colorTextureArray=n,a._depthStencilTextureArray=s,o.disableRescaling(),o.renderListPredicate=()=>!0,o}_getRenderTargetForSubImage(e,t){const i=this._lastSubImages.get(t);let n=this._renderTargetTextures.get(t.eye);const s=e.motionVectorTextureWidth,r=e.motionVectorTextureHeight;return n&&(null==i?void 0:i.textureWidth)===s&&(null==i?void 0:i.textureHeight)==r||(n=this._createRenderTargetTexture(s,r,null,e.motionVectorTexture,e.depthStencilTexture),this._renderTargetTextures.set(t.eye,n),this._framebufferDimensions={framebufferWidth:s,framebufferHeight:r}),this._lastSubImages.set(t,e),n}trySetViewportForView(e,t){const i=this._lastSubImages.get(t)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}accessMotionVector(e){const t=this._getSubImageForView(e);t&&(t.motionVectorTexture,t.depthStencilTexture)}getRenderTargetTextureForEye(e){return null}getRenderTargetTextureForView(e){const t=this._getSubImageForView(e);return t?this._getRenderTargetForSubImage(t,e):null}dispose(){this._renderTargetTextures.forEach((e=>e.dispose())),this._renderTargetTextures.clear()}}class Yy extends nt{constructor(e){super(e),this.dependsOn=[tt.LAYERS],this.xrNativeFeatureName="space-warp",this._xrSessionManager.scene.needsPreviousWorldMatrices=!0}attach(){if(!super.attach())return!1;const e=this._xrSessionManager.scene.getEngine();return this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this.spaceWarpRTTProvider=new Xy(this._xrSessionManager.scene,this._xrSessionManager,this._xrWebGLBinding),this._xrSessionManager.scene.onAfterRenderObservable.add(this._onAfterRender.bind(this)),!0}_onAfterRender(){this.attached&&this._renderTargetTexture&&this._renderTargetTexture.render(!1,!1)}isCompatible(){return this._xrSessionManager.scene.getEngine().getCaps().colorBufferHalfFloat||!1}dispose(){super.dispose()}_onXRFrame(e){const t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;const i=t.views[0];this._renderTargetTexture=this._renderTargetTexture||this.spaceWarpRTTProvider.getRenderTargetTextureForView(i),this.spaceWarpRTTProvider.accessMotionVector(i)}}Yy.Name=tt.SPACE_WARP,Yy.Version=1,it.AddWebXRFeature(Yy.Name,(e=>()=>new Yy(e)),Yy.Version,!1);class jy extends J_{constructor(e,t,i){super(e,Ky[i],t,i,!0),this.profileId="generic-hand-select-grasp"}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){}_updateModel(){}}sm.RegisterController("generic-hand-select-grasp",((e,t)=>new jy(t,e.gamepad,e.handedness)));const Ky={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-none",assetPath:"none.glb"}};class qy extends J_{constructor(e,t,i){super(e,$y["left-right"],t,i),this._mapping={defaultButton:{valueNodeName:"VALUE",unpressedNodeName:"UNPRESSED",pressedNodeName:"PRESSED"},defaultAxis:{valueNodeName:"VALUE",minNodeName:"MIN",maxNodeName:"MAX"},buttons:{"xr-standard-trigger":{rootNodeName:"SELECT",componentProperty:"button",states:["default","touched","pressed"]},"xr-standard-squeeze":{rootNodeName:"GRASP",componentProperty:"state",states:["pressed"]},"xr-standard-touchpad":{rootNodeName:"TOUCHPAD_PRESS",labelAnchorNodeName:"squeeze-label",touchPointNodeName:"TOUCH"},"xr-standard-thumbstick":{rootNodeName:"THUMBSTICK_PRESS",componentProperty:"state",states:["pressed"]}},axes:{"xr-standard-touchpad":{"x-axis":{rootNodeName:"TOUCHPAD_TOUCH_X"},"y-axis":{rootNodeName:"TOUCHPAD_TOUCH_Y"}},"xr-standard-thumbstick":{"x-axis":{rootNodeName:"THUMBSTICK_X"},"y-axis":{rootNodeName:"THUMBSTICK_Y"}}}},this.profileId="microsoft-mixed-reality"}_getFilenameAndPath(){let e="";e="left"===this.handedness?qy.MODEL_LEFT_FILENAME:qy.MODEL_RIGHT_FILENAME;return{filename:e,path:qy.MODEL_BASE_URL+"default/"}}_getModelLoadingConstraints(){const e=ht.IsPluginForExtensionAvailable(".glb");return e||p.Y.Warn("glTF / glb loaded was not registered, using generic controller instead"),e}_processLoadedModel(e){this.rootMesh&&(this.getComponentIds().forEach(((e,t)=>{if(!this.disableAnimation&&e&&this.rootMesh){const i=this._mapping.buttons[e],n=i.rootNodeName;if(!n)return void p.Y.Log("Skipping unknown button at index: "+t+" with mapped name: "+e);const s=this._getChildByName(this.rootMesh,n);if(!s)return void p.Y.Warn("Missing button mesh with name: "+n);if(i.valueMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.valueNodeName),i.pressedMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.pressedNodeName),i.unpressedMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.unpressedNodeName),i.valueMesh&&i.pressedMesh&&i.unpressedMesh){const t=this.getComponent(e);t&&t.onButtonStateChangedObservable.add((e=>{this._lerpTransform(i,e.value)}),void 0,!0)}else p.Y.Warn("Missing button submesh under mesh with name: "+n)}})),this.getComponentIds().forEach((e=>{const t=this.getComponent(e);t.isAxes()&&["x-axis","y-axis"].forEach((i=>{if(!this.rootMesh)return;const n=this._mapping.axes[e][i],s=this._getChildByName(this.rootMesh,n.rootNodeName);s?(n.valueMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.valueNodeName),n.minMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.minNodeName),n.maxMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.maxNodeName),n.valueMesh&&n.minMesh&&n.maxMesh?t&&t.onAxisValueChangedObservable.add((e=>{const t="x-axis"===i?e.x:e.y;this._lerpTransform(n,t,!0)}),void 0,!0):p.Y.Warn("Missing axis submesh under mesh with name: "+n.rootNodeName)):p.Y.Warn("Missing axis mesh with name: "+n.rootNodeName)}))})))}_setRootMesh(e){let t;this.rootMesh=new ee.Kj(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;inew qy(t,e.gamepad,e.handedness)));const $y={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-right",assetPath:"right.glb"}};class Qy extends J_{constructor(e,t,i,n=!1,s=!1){super(e,Zy[i],t,i),this._forceLegacyControllers=s,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";e="left"===this.handedness?Qy.MODEL_LEFT_FILENAME:Qy.MODEL_RIGHT_FILENAME;return{filename:e,path:this._isQuest()?Qy.QUEST_MODEL_BASE_URL:Qy.MODEL_BASE_URL}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){const t=this._isQuest(),i="right"===this.handedness?-1:1;this.getComponentIds().forEach((e=>{const n=e&&this.getComponent(e);n&&n.onButtonStateChangedObservable.add((n=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":return void(t||(this._modelRootNode.getChildren()[3].rotation.x=.2*-n.value,this._modelRootNode.getChildren()[3].position.y=.005*-n.value,this._modelRootNode.getChildren()[3].position.z=.005*-n.value));case"xr-standard-squeeze":return void(t||(this._modelRootNode.getChildren()[4].position.x=i*n.value*.0035));case"xr-standard-thumbstick":return;case"a-button":case"x-button":return void(t||(n.pressed?this._modelRootNode.getChildren()[1].position.y=-.001:this._modelRootNode.getChildren()[1].position.y=0));case"b-button":case"y-button":return void(t||(n.pressed?this._modelRootNode.getChildren()[2].position.y=-.001:this._modelRootNode.getChildren()[2].position.y=0))}}),void 0,!0)}))}_setRootMesh(e){this.rootMesh=new ee.Kj(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=o._f.FromEulerAngles(0,Math.PI,0)),e.forEach((e=>{e.isPickable=!1})),this._isQuest()?this._modelRootNode=e[0]:(this._modelRootNode=e[1],this.rootMesh.position.y=.034,this.rootMesh.position.z=.052),this._modelRootNode.parent=this.rootMesh}_updateModel(){}_isQuest(){return!!navigator.userAgent.match(/Quest/gi)&&!this._forceLegacyControllers}}Qy.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/",Qy.MODEL_LEFT_FILENAME="left.babylon",Qy.MODEL_RIGHT_FILENAME="right.babylon",Qy.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/",sm.RegisterController("oculus-touch",((e,t)=>new Qy(t,e.gamepad,e.handedness))),sm.RegisterController("oculus-touch-legacy",((e,t)=>new Qy(t,e.gamepad,e.handedness,!0)));const Zy={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"x-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"x_button",visualResponses:{}},"y-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"y_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"a-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"a_button",visualResponses:{}},"b-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"b_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-right",assetPath:"right.glb"}};class Jy extends J_{constructor(e,t,i){super(e,eA[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){return{filename:Jy.MODEL_FILENAME,path:Jy.MODEL_BASE_URL}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){this.getComponentIds().forEach((e=>{const t=e&&this.getComponent(e);t&&t.onButtonStateChangedObservable.add((t=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":return void(this._modelRootNode.getChildren()[6].rotation.x=.15*-t.value);case"xr-standard-touchpad":case"xr-standard-squeeze":return}}),void 0,!0)}))}_setRootMesh(e){this.rootMesh=new ee.Kj(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.isPickable=!1})),this._modelRootNode=e[1],this._modelRootNode.parent=this.rootMesh,this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=o._f.FromEulerAngles(0,Math.PI,0))}_updateModel(){}}Jy.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/",Jy.MODEL_FILENAME="wand.babylon",sm.RegisterController("htc-vive",((e,t)=>new Jy(t,e.gamepad,e.handedness)));const eA={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc-vive-none",assetPath:"none.glb"}};function tA(e,t,i,n){const s={externalResourceFunction:e=>n(e).then((e=>new Uint8Array(e)))};return i&&(s.uri="file:"===t?i:t+i),e instanceof ArrayBuffer?GLTFValidator.validateBytes(new Uint8Array(e),s):GLTFValidator.validateString(e,s)}function iA(){const e=[];onmessage=t=>{const i=t.data;switch(i.id){case"init":importScripts(i.url);break;case"validate":tA(i.data,i.rootUrl,i.fileName,(t=>new Promise(((i,n)=>{const s=e.length;e.push({resolve:i,reject:n}),postMessage({id:"getExternalResource",index:s,uri:t})})))).then((e=>{postMessage({id:"validate.resolve",value:e})}),(e=>{postMessage({id:"validate.reject",reason:e})}));break;case"getExternalResource.resolve":e[i.index].resolve(i.value);break;case"getExternalResource.reject":e[i.index].reject(i.reason)}}}!async function(e,t){(await new Promise((e=>{"undefined"==typeof _native?dc.addOnce((t=>e(t))):e(_native)})))[e]=t}("NativeXRFrame",class{get session(){return this._nativeImpl.session}constructor(e){this._nativeImpl=e,this._xrTransform=new XRRigidTransform,this._xrPose={transform:this._xrTransform,emulatedPosition:!1},this._xrPoseVectorData=new Float32Array(8),this.fillPoses=this._nativeImpl.fillPoses.bind(this._nativeImpl),this.getViewerPose=this._nativeImpl.getViewerPose.bind(this._nativeImpl),this.getHitTestResults=this._nativeImpl.getHitTestResults.bind(this._nativeImpl),this.getHitTestResultsForTransientInput=()=>{throw new Error("XRFrame.getHitTestResultsForTransientInput not supported on native.")},this.createAnchor=this._nativeImpl.createAnchor.bind(this._nativeImpl),this.getJointPose=this._nativeImpl.getJointPose.bind(this._nativeImpl),this.fillJointRadii=this._nativeImpl.fillJointRadii.bind(this._nativeImpl),this.getLightEstimate=()=>{throw new Error("XRFrame.getLightEstimate not supported on native.")},this.getImageTrackingResults=()=>{var e;return null!==(e=this._nativeImpl._imageTrackingResults)&&void 0!==e?e:[]}}getPose(e,t){if(!this._nativeImpl.getPoseData(e,t,this._xrPoseVectorData.buffer,this._xrTransform.matrix.buffer))return;const i=this._xrTransform.position;i.x=this._xrPoseVectorData[0],i.y=this._xrPoseVectorData[1],i.z=this._xrPoseVectorData[2],i.w=this._xrPoseVectorData[3];const n=this._xrTransform.orientation;return n.x=this._xrPoseVectorData[4],n.y=this._xrPoseVectorData[5],n.z=this._xrPoseVectorData[6],n.w=this._xrPoseVectorData[7],this._xrPose}get trackedAnchors(){return this._nativeImpl.trackedAnchors}get worldInformation(){return this._nativeImpl.worldInformation}get detectedPlanes(){return this._nativeImpl.detectedPlanes}get featurePointCloud(){return this._nativeImpl.featurePointCloud}getDepthInformation(e){throw new Error("This function is not available in Babylon Native")}});class nA{static ValidateAsync(e,t,i,n){const s=ArrayBuffer.isView(e)?e.slice().buffer:e;return"function"==typeof Worker?new Promise(((e,r)=>{const o=`${tA}(${iA})()`,a=URL.createObjectURL(new Blob([o],{type:"application/javascript"})),l=new Worker(a),h=e=>{l.removeEventListener("error",h),l.removeEventListener("message",c),r(e)},c=t=>{const i=t.data;switch(i.id){case"getExternalResource":n(i.uri).then((e=>{l.postMessage({id:"getExternalResource.resolve",index:i.index,value:e},[e])}),(e=>{l.postMessage({id:"getExternalResource.reject",index:i.index,reason:e})}));break;case"validate.resolve":l.removeEventListener("error",h),l.removeEventListener("message",c),e(i.value),l.terminate();break;case"validate.reject":l.removeEventListener("error",h),l.removeEventListener("message",c),r(i.reason),l.terminate()}};l.addEventListener("error",h),l.addEventListener("message",c),l.postMessage({id:"init",url:this.Configuration.url}),l.postMessage({id:"validate",data:s,rootUrl:t,fileName:i})})):(this._LoadScriptPromise||(this._LoadScriptPromise=se.w1.LoadScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then((()=>tA(s,t,i,n))))}}function sA(e,t,i){try{return Promise.resolve(new Uint8Array(e,t,i))}catch(n){return Promise.reject(n)}}var rA,oA,aA,lA,hA,cA,dA,uA,pA,fA,_A,mA;nA.Configuration={url:"https://preview.babylonjs.com/gltf_validator.js"},function(e){e[e.AUTO=0]="AUTO",e[e.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED"}(rA||(rA={})),function(e){e[e.NONE=0]="NONE",e[e.FIRST=1]="FIRST",e[e.ALL=2]="ALL"}(oA||(oA={})),function(e){e[e.LOADING=0]="LOADING",e[e.READY=1]="READY",e[e.COMPLETE=2]="COMPLETE"}(aA||(aA={}));class gA{constructor(){this.onParsedObservable=new r.y$,this.coordinateSystemMode=rA.AUTO,this.animationStartMode=oA.FIRST,this.compileMaterials=!1,this.useClipPlane=!1,this.compileShadowGenerators=!1,this.transparencyAsCoverage=!1,this.useRangeRequests=!1,this.createInstances=!0,this.alwaysComputeBoundingBox=!1,this.loadAllMaterials=!1,this.loadOnlyMaterials=!1,this.skipMaterials=!1,this.useSRGBBuffers=!0,this.targetFps=60,this.alwaysComputeSkeletonRootNode=!1,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable=new r.y$,this.onSkinLoadedObservable=new r.y$,this.onTextureLoadedObservable=new r.y$,this.onMaterialLoadedObservable=new r.y$,this.onCameraLoadedObservable=new r.y$,this.onCompleteObservable=new r.y$,this.onErrorObservable=new r.y$,this.onDisposeObservable=new r.y$,this.onExtensionLoadedObservable=new r.y$,this.validate=!1,this.onValidatedObservable=new r.y$,this._loader=null,this._state=null,this._requests=new Array,this.name="gltf",this.extensions={".gltf":{isBinary:!1},".glb":{isBinary:!0}},this.onLoaderStateChangedObservable=new r.y$,this._logIndentLevel=0,this._loggingEnabled=!1,this._log=this._logDisabled,this._capturePerformanceCounters=!1,this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled}set onParsed(e){this._onParsedObserver&&this.onParsedObservable.remove(this._onParsedObserver),this._onParsedObserver=this.onParsedObservable.add(e)}set onMeshLoaded(e){this._onMeshLoadedObserver&&this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver),this._onMeshLoadedObserver=this.onMeshLoadedObservable.add(e)}set onTextureLoaded(e){this._onTextureLoadedObserver&&this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver),this._onTextureLoadedObserver=this.onTextureLoadedObservable.add(e)}set onMaterialLoaded(e){this._onMaterialLoadedObserver&&this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver),this._onMaterialLoadedObserver=this.onMaterialLoadedObservable.add(e)}set onCameraLoaded(e){this._onCameraLoadedObserver&&this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver),this._onCameraLoadedObserver=this.onCameraLoadedObservable.add(e)}set onComplete(e){this._onCompleteObserver&&this.onCompleteObservable.remove(this._onCompleteObserver),this._onCompleteObserver=this.onCompleteObservable.add(e)}set onError(e){this._onErrorObserver&&this.onErrorObservable.remove(this._onErrorObserver),this._onErrorObserver=this.onErrorObservable.add(e)}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onExtensionLoaded(e){this._onExtensionLoadedObserver&&this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver),this._onExtensionLoadedObserver=this.onExtensionLoadedObservable.add(e)}get loggingEnabled(){return this._loggingEnabled}set loggingEnabled(e){this._loggingEnabled!==e&&(this._loggingEnabled=e,this._loggingEnabled?this._log=this._logEnabled:this._log=this._logDisabled)}get capturePerformanceCounters(){return this._capturePerformanceCounters}set capturePerformanceCounters(e){this._capturePerformanceCounters!==e&&(this._capturePerformanceCounters=e,this._capturePerformanceCounters?(this._startPerformanceCounter=this._startPerformanceCounterEnabled,this._endPerformanceCounter=this._endPerformanceCounterEnabled):(this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled))}set onValidated(e){this._onValidatedObserver&&this.onValidatedObservable.remove(this._onValidatedObserver),this._onValidatedObserver=this.onValidatedObservable.add(e)}dispose(){this._loader&&(this._loader.dispose(),this._loader=null);for(const e of this._requests)e.abort();this._requests.length=0,delete this._progressCallback,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable.clear(),this.onSkinLoadedObservable.clear(),this.onTextureLoadedObservable.clear(),this.onMaterialLoadedObservable.clear(),this.onCameraLoadedObservable.clear(),this.onCompleteObservable.clear(),this.onExtensionLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(void 0),this.onDisposeObservable.clear()}loadFile(e,t,i,n,s,o,a,l){if(ArrayBuffer.isView(t))return this._loadBinary(e,t,i,n,a,l),null;this._progressCallback=s;const h=t.name||se.w1.GetFilename(t);if(o){if(this.useRangeRequests){this.validate&&p.Y.Warn("glTF validation is not supported when range requests are enabled");const i={abort:()=>{},onCompleteObservable:new r.y$},s={readAsync:(i,n)=>new Promise(((s,r)=>{this._loadFile(e,t,(e=>{s(new Uint8Array(e))}),!0,(e=>{r(e)}),(e=>{e.setRequestHeader("Range",`bytes=${i}-${i+n-1}`)}))})),byteLength:0};return this._unpackBinaryAsync(new QC(s)).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),i,h),this._unpackBinaryAsync(new QC({readAsync:(e,i)=>sA(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=>{this._validate(e,new Uint8Array(t),i,h),n({json:this._parseJson(t)})}),o,a)}_loadBinary(e,t,i,n,s,r){this._validate(e,t,i,r),this._unpackBinaryAsync(new QC({readAsync:(e,i)=>function(e,t,i){try{if(e.byteOffset+i>e.byteLength)throw new Error("Array length out of bounds.");return Promise.resolve(new Uint8Array(e.buffer,e.byteOffset+t,i))}catch(n){return Promise.reject(n)}}(t,e,i),byteLength:t.byteLength})).then((e=>{n(e)}),s?e=>s(void 0,e):void 0)}importMeshAsync(e,t,i,n,s,r){return Promise.resolve().then((()=>(this.onParsedObservable.notifyObservers(i),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(i),this._loader.importMeshAsync(e,t,null,i,n,s,r))))}loadAsync(e,t,i,n,s){return Promise.resolve().then((()=>(this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${s||""}`),this._loader=this._getLoader(t),this._loader.loadAsync(e,t,i,n,s))))}loadAssetContainerAsync(e,t,i,n,s){return Promise.resolve().then((()=>{this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${s||""}`),this._loader=this._getLoader(t);const r=new pe(e),o=[];this.onMaterialLoadedObservable.add((e=>{o.push(e)}));const a=[];this.onTextureLoadedObservable.add((e=>{a.push(e)}));const l=[];this.onCameraLoadedObservable.add((e=>{l.push(e)}));const h=[];return this.onMeshLoadedObservable.add((e=>{e.morphTargetManager&&h.push(e.morphTargetManager)})),this._loader.importMeshAsync(null,e,r,t,i,n,s).then((e=>(Array.prototype.push.apply(r.geometries,e.geometries),Array.prototype.push.apply(r.meshes,e.meshes),Array.prototype.push.apply(r.particleSystems,e.particleSystems),Array.prototype.push.apply(r.skeletons,e.skeletons),Array.prototype.push.apply(r.animationGroups,e.animationGroups),Array.prototype.push.apply(r.materials,o),Array.prototype.push.apply(r.textures,a),Array.prototype.push.apply(r.lights,e.lights),Array.prototype.push.apply(r.transformNodes,e.transformNodes),Array.prototype.push.apply(r.cameras,l),Array.prototype.push.apply(r.morphTargetManagers,h),r)))}))}canDirectLoad(e){return-1!==e.indexOf("asset")&&-1!==e.indexOf("version")||e.startsWith("data:base64,"+gA._MagicBase64Encoded)||e.startsWith("data:;base64,"+gA._MagicBase64Encoded)||e.startsWith("data:application/octet-stream;base64,"+gA._MagicBase64Encoded)||e.startsWith("data:model/gltf-binary;base64,"+gA._MagicBase64Encoded)}directLoad(e,t){if(t.startsWith("base64,"+gA._MagicBase64Encoded)||t.startsWith(";base64,"+gA._MagicBase64Encoded)||t.startsWith("application/octet-stream;base64,"+gA._MagicBase64Encoded)||t.startsWith("model/gltf-binary;base64,"+gA._MagicBase64Encoded)){const i=(0,ye.$K)(t);return this._validate(e,new Uint8Array(i)),this._unpackBinaryAsync(new QC({readAsync:(e,t)=>sA(i,e,t),byteLength:i.byteLength}))}return this._validate(e,t),Promise.resolve({json:this._parseJson(t)})}createPlugin(){return new gA}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(aA[this._state]))}_loadFile(e,t,i,n,s,r){const o=e._loadFile(t,i,(e=>{this._onProgress(e,o)}),!0,n,s,r);return o.onCompleteObservable.add((e=>{this._requests.splice(this._requests.indexOf(e),1)})),this._requests.push(o),o}_onProgress(e,t){if(!this._progressCallback)return;t._lengthComputable=e.lengthComputable,t._loaded=e.loaded,t._total=e.total;let i=!0,n=0,s=0;for(const r of this._requests){if(void 0===r._lengthComputable||void 0===r._loaded||void 0===r._total)return;i=i&&r._lengthComputable,n+=r._loaded,s+=r._total}this._progressCallback({lengthComputable:i,loaded:n,total:i?s:0})}_validate(e,t,i="",n=""){this.validate&&(this._startPerformanceCounter("Validate JSON"),nA.ValidateAsync(t,i,n,(t=>this.preprocessUrlAsync(i+t).then((t=>e._loadFileAsync(t,void 0,!0,!0))))).then((e=>{this._endPerformanceCounter("Validate JSON"),this.onValidatedObservable.notifyObservers(e),this.onValidatedObservable.clear()}),(e=>{this._endPerformanceCounter("Validate JSON"),se.w1.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=gA._parseVersion(t.version);if(!i)throw new Error("Invalid version: "+t.version);if(void 0!==t.minVersion){const e=gA._parseVersion(t.minVersion);if(!e)throw new Error("Invalid minimum version: "+t.minVersion);if(gA._compareVersion(e,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}const n={1:gA._CreateGLTF1Loader,2:gA._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 lt.LH("Unexpected magic: "+t,lt.SM.GLTFLoaderUnexpectedMagicError);const i=e.readUint32();this.loggingEnabled&&this._log(`Binary version: ${i}`);const n=e.readUint32();let s;switch(this.useRangeRequests||n===e.buffer.byteLength||p.Y.Warn(`Length in header does not match actual data length: ${n} != ${e.buffer.byteLength}`),i){case 1:s=this._unpackBinaryV1Async(e,n);break;case 2:s=this._unpackBinaryV2Async(e,n);break;default:throw new Error("Unsupported version: "+i)}return this._endPerformanceCounter("Unpack Binary"),s}))}_unpackBinaryV1Async(e,t){const i=e.readUint32(),n=e.readUint32();if(0!==n)throw new Error(`Unexpected content format: ${n}`);const s=t-e.byteOffset,r={json:this._parseJson(e.readString(i)),bin:null};if(0!==s){const t=e.byteOffset;r.bin={readAsync:(i,n)=>e.buffer.readAsync(t+i,n),byteLength:s}}return Promise.resolve(r)}_unpackBinaryV2Async(e,t){const i=1313821514,n=5130562,s=e.readUint32();if(e.readUint32()!==i)throw new Error("First chunk format is not JSON");return e.byteOffset+s===t?e.loadAsync(s).then((()=>({json:this._parseJson(e.readString(s)),bin:null}))):e.loadAsync(s+8).then((()=>{const r={json:this._parseJson(e.readString(s)),bin:null},o=()=>{const s=e.readUint32();switch(e.readUint32()){case i:throw new Error("Unexpected JSON chunk");case n:{const t=e.byteOffset;r.bin={readAsync:(i,n)=>e.buffer.readAsync(t+i,n),byteLength:s},e.skipBytes(s);break}default:e.skipBytes(s)}return e.byteOffset!==t?e.loadAsync(8).then(o):Promise.resolve(r)};return o()}))}static _parseVersion(e){if("1.0"===e||"1.0.1"===e)return{major:1,minor:0};const t=(e+"").match(/^(\d+)\.(\d+)/);return t?{major:parseInt(t[1]),minor:parseInt(t[2])}:null}static _compareVersion(e,t){return e.major>t.major?1:e.majort.minor?1:e.minorr.byteLength)throw new Error("Buffer access is out of range");const o=r.buffer;switch(i+=r.byteOffset,s){case lA.BYTE:return new Int8Array(o,i,n);case lA.UNSIGNED_BYTE:return new Uint8Array(o,i,n);case lA.SHORT:return new Int16Array(o,i,n);case lA.UNSIGNED_SHORT:return new Uint16Array(o,i,n);default:return new Float32Array(o,i,n)}}static GetBufferFromAccessor(e,t){const i=e.bufferViews[t.bufferView],n=t.count*vA.GetByteStrideFromType(t);return vA.GetBufferFromBufferView(e,i,t.byteOffset,n,t.componentType)}static DecodeBufferToText(e){let t="";const i=e.byteLength;for(let n=0;n=this._maxPos}}const SA=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],EA=["world","view","projection","worldView","worldViewProjection","mBones"],xA=["translation","rotation","scale"],bA=["position","rotationQuaternion","scaling"],CA=(e,t,i)=>{for(const n in e){const s=e[n];i[t][n]=s}},yA=e=>{if(e)for(let t=0;t{if("NORMAL"===e.semantic)return"normal";if("POSITION"===e.semantic)return"position";if("JOINT"===e.semantic)return"matricesIndices";if("WEIGHT"===e.semantic)return"matricesWeights";if("COLOR"===e.semantic)return"color";if(e.semantic&&-1!==e.semantic.indexOf("TEXCOORD_")){const t=Number(e.semantic.split("_")[1]);return"uv"+(0===t?"":t+1)}return null},RA=e=>{let t=null;if(e.translation||e.rotation||e.scale){const i=o.P.FromArray(e.scale||[1,1,1]),n=o._f.FromArray(e.rotation||[0,0,0,1]),s=o.P.FromArray(e.translation||[0,0,0]);t=o.y3.Compose(i,n,s)}else t=o.y3.FromArray(e.matrix);return t},PA=(e,t,i,n)=>{for(let r=0;r{for(let i=0;i{const i=e.nodes;let n=i[t];if(n)return{node:n,id:t};for(const s in i)if(n=i[s],n.jointName===t)return{node:n,id:s};return null},OA=(e,t)=>{for(let i=0;i{if(n||(n=new ji(t.name||"","",e.scene)),!t.babylonSkeleton)return n;const s=[],r=[];((e,t,i,n)=>{for(const s in e.nodes){const r=e.nodes[s],o=s;if(!r.jointName||OA(i,r.jointName))continue;const a=RA(r),l=new B(r.name||"",t,null,a);l.id=o,n.push({bone:l,node:r,id:o})}for(let s=0;s0&&(d=IA(s,l),d&&-1===r.indexOf(d)&&r.push(d));new B(o.jointName||"",n,d,u).id=l}const o=n.bones;n.bones=[];for(let a=0;a{if(s||(e.scene._blockEntityCollection=!!e.assetContainer,(s=new ee.Kj(t.name||"",e.scene))._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,s.id=n),!t.babylonNode)return s;const r=[];let o=null;const a=new Array,l=new Array,h=new Array,c=new Array;for(let p=0;p1?(d=new zg.G("multimat"+n,e.scene),d.subMaterials=r):d=new _a("multimat"+n,e.scene),1===r.length&&(d=r[0]),d._parentContainer=e.assetContainer,s.material||(s.material=d),new Gg.Z(n,e.scene,o,!1,s),s.computeWorldMatrix(!0),e.scene._blockEntityCollection=!1,s.subMeshes=[];let u=0;for(let p=0;p{e.position&&(e.position=t),(e.rotationQuaternion||e.rotation)&&(e.rotationQuaternion=i),e.scaling&&(e.scaling=n)},wA=(e,t,i)=>{let n=null;if(e.importOnlyMeshes&&(t.skin||t.meshes)&&e.importMeshesNames&&e.importMeshesNames.length>0&&-1===e.importMeshesNames.indexOf(t.name||""))return null;if(t.skin){if(t.meshes){const s=e.skins[t.skin],r=NA(e,t,t.meshes,i,t.babylonNode);r.skeleton=e.scene.getLastSkeletonById(t.skin),null===r.skeleton&&(r.skeleton=DA(e,s,0,s.babylonSkeleton),s.babylonSkeleton||(s.babylonSkeleton=r.skeleton)),n=r}}else if(t.meshes){n=NA(e,t,t.mesh?[t.mesh]:t.meshes,i,t.babylonNode)}else if(!t.light||t.babylonNode||e.importOnlyMeshes){if(t.camera&&!t.babylonNode&&!e.importOnlyMeshes){const i=e.cameras[t.camera];if(i){if(e.scene._blockEntityCollection=!!e.assetContainer,"orthographic"===i.type){const i=new Fn(t.camera,o.P.Zero(),e.scene,!1);i.name=t.name||"",i.mode=ce.V.ORTHOGRAPHIC_CAMERA,i.attachControl(),n=i,i._parentContainer=e.assetContainer}else if("perspective"===i.type){const s=i[i.type],r=new Fn(t.camera,o.P.Zero(),e.scene,!1);r.name=t.name||"",r.attachControl(),s.aspectRatio||(s.aspectRatio=e.scene.getEngine().getRenderWidth()/e.scene.getEngine().getRenderHeight()),s.znear&&s.zfar&&(r.maxZ=s.zfar,r.minZ=s.znear),n=r,r._parentContainer=e.assetContainer}e.scene._blockEntityCollection=!1}}}else{const i=e.lights[t.light];if(i)if("ambient"===i.type){const s=i[i.type],r=new Os(t.light,o.P.Zero(),e.scene);r.name=t.name||"",s.color&&(r.diffuse=a.Wo.FromArray(s.color)),n=r}else if("directional"===i.type){const s=i[i.type],r=new sp(t.light,o.P.Zero(),e.scene);r.name=t.name||"",s.color&&(r.diffuse=a.Wo.FromArray(s.color)),n=r}else if("point"===i.type){const s=i[i.type],r=new Vg(t.light,o.P.Zero(),e.scene);r.name=t.name||"",s.color&&(r.diffuse=a.Wo.FromArray(s.color)),n=r}else if("spot"===i.type){const s=i[i.type],r=new op(t.light,o.P.Zero(),o.P.Zero(),0,0,e.scene);r.name=t.name||"",s.color&&(r.diffuse=a.Wo.FromArray(s.color)),s.fallOfAngle&&(r.angle=s.fallOfAngle),s.fallOffExponent&&(r.exponent=s.fallOffExponent),n=r}}if(!t.jointName){if(t.babylonNode)return t.babylonNode;if(null===n){e.scene._blockEntityCollection=!!e.assetContainer;const i=new ee.Kj(t.name||"",e.scene);i._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,t.babylonNode=i,n=i}}if(null!==n){if(t.matrix&&n instanceof ee.Kj)((e,t)=>{if(t.matrix){const i=new o.P(0,0,0),n=new o._f,s=new o.P(0,0,0);o.y3.FromArray(t.matrix).decompose(s,n,i),FA(e,i,n,s)}else t.translation&&t.rotation&&t.scale&&FA(e,o.P.FromArray(t.translation),o._f.FromArray(t.rotation),o.P.FromArray(t.scale));e.computeWorldMatrix(!0)})(n,t);else{const e=t.translation||[0,0,0],i=t.rotation||[0,0,0,1],s=t.scale||[1,1,1];FA(n,o.P.FromArray(e),o._f.FromArray(i),o.P.FromArray(s))}n.updateCache(!0),t.babylonNode=n}return n},LA=(e,t,i,n=!1)=>{const s=e.nodes[t];let r=null;if(n=!(e.importOnlyMeshes&&!n&&e.importMeshesNames)||(-1!==e.importMeshesNames.indexOf(s.name||"")||0===e.importMeshesNames.length),!s.jointName&&n&&(r=wA(e,s,t),null!==r&&(r.id=t,r.parent=i)),s.children)for(let o=0;o{let t=e.currentScene;if(t)for(let i=0;i{for(const t in e.animations){const i=e.animations[t];if(!i.channels||!i.samplers)continue;let n=null;for(let s=0;so=>{((e,t,i,n,s)=>{const r=n.values||i.parameters,o=i.uniforms;for(const a in s){const i=s[a],l=i.type;let h=r[o[a]];if(void 0===h&&(h=i.value),!h)continue;const c=e=>n=>{i.value&&e&&(t.setTexture(e,n),delete s[e])};l===cA.SAMPLER_2D?WA.LoadTextureAsync(e,n.values?h:i.value,c(a),(()=>c(null))):i.value&&vA.SetUniform(t,a,n.values?h:i.value,l)&&delete s[a]}})(e,t,i,n,s),t.onBind=o=>{((e,t,i,n,s,r,o)=>{const a=r.values||s.parameters;for(const l in i){const o=i[l],h=o.type;if(h===cA.FLOAT_MAT2||h===cA.FLOAT_MAT3||h===cA.FLOAT_MAT4)if(!o.semantic||o.source||o.node){if(o.semantic&&(o.source||o.node)){let e=t.scene.getNodeByName(o.source||o.node||"");if(null===e&&(e=t.scene.getNodeById(o.source||o.node||"")),null===e)continue;vA.SetMatrix(t.scene,e,o,l,n.getEffect())}}else vA.SetMatrix(t.scene,e,o,l,n.getEffect());else{const e=a[s.uniforms[l]];if(!e)continue;if(h===cA.SAMPLER_2D){const i=t.textures[r.values?e:o.value].babylonTexture;if(null==i)continue;n.getEffect().setTexture(l,i)}else vA.SetUniform(n.getEffect(),l,e,h)}}o(n)})(o,e,s,t,i,n,r)}},VA=(e,t,i)=>{for(const n in t.uniforms){const s=t.uniforms[n],r=t.parameters[s];if(e.currentIdentifier===n&&r.semantic&&!r.source&&!r.node){const e=SA.indexOf(r.semantic);if(-1!==e)return delete i[n],EA[e]}}return e.currentIdentifier},kA=e=>{for(const t in e.materials)WA.LoadMaterialAsync(e,t,(()=>{}),(()=>{}))};class GA{static CreateRuntime(e,t,i){const n={extensions:{},accessors:{},buffers:{},bufferViews:{},meshes:{},lights:{},cameras:{},nodes:{},images:{},textures:{},shaders:{},programs:{},samplers:{},techniques:{},materials:{},animations:{},skins:{},extensionsUsed:[],scenes:{},buffersCount:0,shaderscount:0,scene:t,rootUrl:i,loadedBufferCount:0,loadedBufferViews:{},loadedShaderCount:0,importOnlyMeshes:!1,dummyNodes:[],assetContainer:null};return e.extensions&&CA(e.extensions,"extensions",n),e.extensionsUsed&&CA(e.extensionsUsed,"extensionsUsed",n),e.buffers&&((e,t)=>{for(const i in e){const n=e[i];t.buffers[i]=n,t.buffersCount++}})(e.buffers,n),e.bufferViews&&CA(e.bufferViews,"bufferViews",n),e.accessors&&CA(e.accessors,"accessors",n),e.meshes&&CA(e.meshes,"meshes",n),e.lights&&CA(e.lights,"lights",n),e.cameras&&CA(e.cameras,"cameras",n),e.nodes&&CA(e.nodes,"nodes",n),e.images&&CA(e.images,"images",n),e.textures&&CA(e.textures,"textures",n),e.shaders&&((e,t)=>{for(const i in e){const n=e[i];t.shaders[i]=n,t.shaderscount++}})(e.shaders,n),e.programs&&CA(e.programs,"programs",n),e.samplers&&CA(e.samplers,"samplers",n),e.techniques&&CA(e.techniques,"techniques",n),e.materials&&CA(e.materials,"materials",n),e.animations&&CA(e.animations,"animations",n),e.skins&&CA(e.skins,"skins",n),e.scenes&&(n.scenes=e.scenes),e.scene&&e.scenes&&(n.currentScene=e.scenes[e.scene]),n}static LoadBufferAsync(e,t,i,n,s){const r=e.buffers[t];se.w1.IsBase64(r.uri)?setTimeout((()=>i(new Uint8Array(se.w1.DecodeBase64(r.uri))))):se.w1.LoadFile(e.rootUrl+r.uri,(e=>i(new Uint8Array(e))),s,void 0,!0,(e=>{e&&n(e.status+" "+e.statusText)}))}static LoadTextureBufferAsync(e,t,i,n){const s=e.textures[t];if(!s||!s.source)return void n("");if(s.babylonTexture)return void i(null);const r=e.images[s.source];se.w1.IsBase64(r.uri)?setTimeout((()=>i(new Uint8Array(se.w1.DecodeBase64(r.uri))))):se.w1.LoadFile(e.rootUrl+r.uri,(e=>i(new Uint8Array(e))),void 0,void 0,!0,(e=>{e&&n(e.status+" "+e.statusText)}))}static CreateTextureAsync(e,t,i,n){const s=e.textures[t];if(s.babylonTexture)return void n(s.babylonTexture);const r=e.samplers[s.sampler],o=r.minFilter===uA.NEAREST_MIPMAP_NEAREST||r.minFilter===uA.NEAREST_MIPMAP_LINEAR||r.minFilter===uA.LINEAR_MIPMAP_NEAREST||r.minFilter===uA.LINEAR_MIPMAP_LINEAR,a=Le.BILINEAR_SAMPLINGMODE,l=null==i?new Blob:new Blob([i]),h=URL.createObjectURL(l),c=()=>URL.revokeObjectURL(h),d=new Le(h,e.scene,!o,!0,a,c,c);void 0!==r.wrapS&&(d.wrapU=vA.GetWrapMode(r.wrapS)),void 0!==r.wrapT&&(d.wrapV=vA.GetWrapMode(r.wrapT)),d.name=t,s.babylonTexture=d,n(d)}static LoadShaderStringAsync(e,t,i,n){const s=e.shaders[t];if(se.w1.IsBase64(s.uri)){const e=atob(s.uri.split(",")[1]);i&&i(e)}else se.w1.LoadFile(e.rootUrl+s.uri,i,void 0,void 0,!1,(e=>{e&&n&&n(e.status+" "+e.statusText)}))}static LoadMaterialAsync(e,t,i,n){const s=e.materials[t];if(!s.technique)return void(n&&n("No technique found."));const r=e.techniques[s.technique];if(!r){e.scene._blockEntityCollection=!!e.assetContainer;const n=new _a(t,e.scene);return n._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,n.diffuseColor=new a.Wo(.5,.5,.5),n.sideOrientation=ut.F.CounterClockWiseSideOrientation,void i(n)}const o=e.programs[r.program],l=r.states,h=ft.Q.ShadersStore[o.vertexShader+"VertexShader"],c=ft.Q.ShadersStore[o.fragmentShader+"PixelShader"];let d="",u="";const p=new TA(h),f=new TA(c),_={},m=[],g=[],v=[];for(const a in r.uniforms){const e=r.uniforms[a],t=r.parameters[e];if(_[a]=t,!t.semantic||t.node||t.source)t.type===cA.SAMPLER_2D?v.push(a):m.push(a);else{const e=SA.indexOf(t.semantic);-1!==e?(m.push(EA[e]),delete _[a]):m.push(a)}}for(const a in r.attributes){const e=r.attributes[a],t=r.parameters[e];if(t.semantic){const e=AA(t);e&&g.push(e)}}for(;!p.isEnd()&&p.getNextToken();){if(p.currentToken!==mA.IDENTIFIER){d+=p.currentString;continue}let e=!1;for(const t in r.attributes){const i=r.attributes[t],n=r.parameters[i];if(p.currentIdentifier===t&&n.semantic){d+=AA(n),e=!0;break}}e||(d+=VA(p,r,_))}for(;!f.isEnd()&&f.getNextToken();){f.currentToken===mA.IDENTIFIER?u+=VA(f,r,_):u+=f.currentString}const T={vertex:o.vertexShader+t,fragment:o.fragmentShader+t},S={attributes:g,uniforms:m,samplers:v,needAlphaBlending:l&&l.enable&&-1!==l.enable.indexOf(3042)};ft.Q.ShadersStore[o.vertexShader+t+"VertexShader"]=d,ft.Q.ShadersStore[o.fragmentShader+t+"PixelShader"]=u;const E=new Il(t,e.scene,T,S);if(E.onError=((e,t,i)=>(n,s)=>{t.dispose(!0),i("Cannot compile program named "+e.name+". Error: "+s+". Default material will be applied")})(o,E,n),E.onCompiled=UA(e,E,r,s,_,i),E.sideOrientation=ut.F.CounterClockWiseSideOrientation,l&&l.functions){const e=l.functions;e.cullFace&&e.cullFace[0]!==fA.BACK&&(E.backFaceCulling=!1);const t=e.blendFuncSeparate;t&&(t[0]===_A.SRC_ALPHA&&t[1]===_A.ONE_MINUS_SRC_ALPHA&&t[2]===_A.ONE&&t[3]===_A.ONE?E.alphaMode=vh.ALPHA_COMBINE:t[0]===_A.ONE&&t[1]===_A.ONE&&t[2]===_A.ZERO&&t[3]===_A.ONE?E.alphaMode=vh.ALPHA_ONEONE:t[0]===_A.SRC_ALPHA&&t[1]===_A.ONE&&t[2]===_A.ZERO&&t[3]===_A.ONE?E.alphaMode=vh.ALPHA_ADD:t[0]===_A.ZERO&&t[1]===_A.ONE_MINUS_SRC_COLOR&&t[2]===_A.ONE&&t[3]===_A.ONE?E.alphaMode=vh.ALPHA_SUBTRACT:t[0]===_A.DST_COLOR&&t[1]===_A.ZERO&&t[2]===_A.ONE&&t[3]===_A.ONE?E.alphaMode=vh.ALPHA_MULTIPLY:t[0]===_A.SRC_ALPHA&&t[1]===_A.ONE_MINUS_SRC_COLOR&&t[2]===_A.ONE&&t[3]===_A.ONE&&(E.alphaMode=vh.ALPHA_MAXIMIZED))}}}class zA{static RegisterExtension(e){zA.Extensions[e.name]?se.w1.Error('Tool with the same name "'+e.name+'" already exists'):zA.Extensions[e.name]=e}dispose(){}_importMeshAsync(e,t,i,n,s,r,o,a){return t.useRightHandedSystem=!0,WA.LoadRuntimeAsync(t,i,n,(t=>{t.assetContainer=s,t.importOnlyMeshes=!0,""===e?t.importMeshesNames=[]:"string"==typeof e?t.importMeshesNames=[e]:!e||e instanceof Array?(t.importMeshesNames=[],se.w1.Warn("Argument meshesNames must be of type string or string[]")):t.importMeshesNames=[e],this._createNodes(t);const i=new Array,n=new Array;for(const e in t.nodes){const n=t.nodes[e];n.babylonNode instanceof ie.x&&i.push(n.babylonNode)}for(const e in t.skins){const i=t.skins[e];i.babylonSkeleton instanceof ji&&n.push(i.babylonSkeleton)}this._loadBuffersAsync(t,(()=>{this._loadShadersAsync(t,(()=>{kA(t),BA(t),!gA.IncrementalLoading&&r&&r(i,n)}))})),gA.IncrementalLoading&&r&&r(i,n)}),a),!0}importMeshAsync(e,t,i,n,s,r){return new Promise(((o,a)=>{this._importMeshAsync(e,t,n,s,i,((e,t)=>{o({meshes:e,particleSystems:[],skeletons:t,animationGroups:[],lights:[],transformNodes:[],geometries:[]})}),r,(e=>{a(new Error(e))}))}))}_loadAsync(e,t,i,n,s,r){e.useRightHandedSystem=!0,WA.LoadRuntimeAsync(e,t,i,(e=>{WA.LoadRuntimeExtensionsAsync(e,(()=>{this._createNodes(e),this._loadBuffersAsync(e,(()=>{this._loadShadersAsync(e,(()=>{kA(e),BA(e),gA.IncrementalLoading||n()}))})),gA.IncrementalLoading&&n()}),r)}),r)}loadAsync(e,t,i,n){return new Promise(((s,r)=>{this._loadAsync(e,t,i,(()=>{s()}),n,(e=>{r(new Error(e))}))}))}_loadShadersAsync(e,t){let i=!1;const n=(i,n)=>{WA.LoadShaderStringAsync(e,i,(s=>{s instanceof ArrayBuffer||(e.loadedShaderCount++,s&&(ft.Q.ShadersStore[i+(n.type===hA.VERTEX?"VertexShader":"PixelShader")]=s),e.loadedShaderCount===e.shaderscount&&t())}),(()=>{se.w1.Error("Error when loading shader program named "+i+" located at "+n.uri)}))};for(const s in e.shaders){i=!0;const t=e.shaders[s];t?n.bind(this,s,t)():se.w1.Error("No shader named: "+s)}i||t()}_loadBuffersAsync(e,t){let i=!1;const n=(i,n)=>{WA.LoadBufferAsync(e,i,(s=>{e.loadedBufferCount++,s&&(s.byteLength!=e.buffers[i].byteLength&&se.w1.Error("Buffer named "+i+" is length "+s.byteLength+". Expected: "+n.byteLength),e.loadedBufferViews[i]=s),e.loadedBufferCount===e.buffersCount&&t()}),(()=>{se.w1.Error("Error when loading buffer named "+i+" located at "+n.uri)}))};for(const s in e.buffers){i=!0;const t=e.buffers[s];t?n.bind(this,s,t)():se.w1.Error("No buffer named: "+s)}i||t()}_createNodes(e){let t=e.currentScene;if(t)for(let i=0;ir.loadRuntimeAsync(e,t,i,n,s)),(()=>{setTimeout((()=>{n&&n(GA.CreateRuntime(t.json,e,i))}))}))}static LoadRuntimeExtensionsAsync(e,t,i){WA._ApplyExtensions((n=>n.loadRuntimeExtensionsAsync(e,t,i)),(()=>{setTimeout((()=>{t()}))}))}static LoadBufferAsync(e,t,i,n,s){WA._ApplyExtensions((r=>r.loadBufferAsync(e,t,i,n,s)),(()=>{GA.LoadBufferAsync(e,t,i,n,s)}))}static LoadTextureAsync(e,t,i,n){WA._LoadTextureBufferAsync(e,t,(s=>{s&&WA._CreateTextureAsync(e,t,s,i,n)}),n)}static LoadShaderStringAsync(e,t,i,n){WA._ApplyExtensions((s=>s.loadShaderStringAsync(e,t,i,n)),(()=>{GA.LoadShaderStringAsync(e,t,i,n)}))}static LoadMaterialAsync(e,t,i,n){WA._ApplyExtensions((s=>s.loadMaterialAsync(e,t,i,n)),(()=>{GA.LoadMaterialAsync(e,t,i,n)}))}static _LoadTextureBufferAsync(e,t,i,n){WA._ApplyExtensions((s=>s.loadTextureBufferAsync(e,t,i,n)),(()=>{GA.LoadTextureBufferAsync(e,t,i,n)}))}static _CreateTextureAsync(e,t,i,n,s){WA._ApplyExtensions((r=>r.createTextureAsync(e,t,i,n,s)),(()=>{GA.CreateTextureAsync(e,t,i,n)}))}static _ApplyExtensions(e,t){for(const i in zA.Extensions){if(e(zA.Extensions[i]))return}t()}}gA._CreateGLTF1Loader=()=>new zA;zA.RegisterExtension(new class extends WA{constructor(){super("KHR_binary_glTF")}loadRuntimeAsync(e,t,i,n){const s=t.json.extensionsUsed;return!(!s||-1===s.indexOf(this.name)||!t.bin)&&(this._bin=t.bin,n(GA.CreateRuntime(t.json,e,i)),!0)}loadBufferAsync(e,t,i,n){return-1!==e.extensionsUsed.indexOf(this.name)&&("binary_glTF"===t&&(this._bin.readAsync(0,this._bin.byteLength).then(i,(e=>n(e.message))),!0))}loadTextureBufferAsync(e,t,i){const n=e.textures[t],s=e.images[n.source];if(!s.extensions||!(this.name in s.extensions))return!1;const r=s.extensions[this.name],o=e.bufferViews[r.bufferView];return i(vA.GetBufferFromBufferView(e,o,0,o.byteLength,lA.UNSIGNED_BYTE)),!0}loadShaderStringAsync(e,t,i){const n=e.shaders[t];if(!n.extensions||!(this.name in n.extensions))return!1;const s=n.extensions[this.name],r=e.bufferViews[s.bufferView],o=vA.GetBufferFromBufferView(e,r,0,r.byteLength,lA.UNSIGNED_BYTE);return setTimeout((()=>{const e=vA.DecodeBufferToText(o);i(e)})),!0}});function HA(e,t,i,n){return o.P.FromArray(t,i).scaleInPlace(n)}zA.RegisterExtension(new class extends WA{constructor(){super("KHR_materials_common")}loadRuntimeExtensionsAsync(e){if(!e.extensions)return!1;const t=e.extensions[this.name];if(!t)return!1;const i=t.lights;if(i)for(const n in i){const t=i[n];switch(t.type){case"ambient":{const i=new Os(t.name,new o.P(0,1,0),e.scene),n=t.ambient;n&&(i.diffuse=a.Wo.FromArray(n.color||[1,1,1]));break}case"point":{const i=new Vg(t.name,new o.P(10,10,10),e.scene),n=t.point;n&&(i.diffuse=a.Wo.FromArray(n.color||[1,1,1]));break}case"directional":{const i=new sp(t.name,new o.P(0,-1,0),e.scene),n=t.directional;n&&(i.diffuse=a.Wo.FromArray(n.color||[1,1,1]));break}case"spot":{const i=t.spot;if(i){new op(t.name,new o.P(0,10,0),new o.P(0,-1,0),i.fallOffAngle||Math.PI,i.fallOffExponent||0,e.scene).diffuse=a.Wo.FromArray(i.color||[1,1,1])}break}default:se.w1.Warn('GLTF Material Common extension: light type "'+t.type+"” not supported")}}return!1}loadMaterialAsync(e,t,i,n){const s=e.materials[t];if(!s||!s.extensions)return!1;const r=s.extensions[this.name];if(!r)return!1;const o=new _a(t,e.scene);return o.sideOrientation=ut.F.CounterClockWiseSideOrientation,"CONSTANT"===r.technique&&(o.disableLighting=!0),o.backFaceCulling=void 0!==r.doubleSided&&!r.doubleSided,o.alpha=void 0===r.values.transparency?1:r.values.transparency,o.specularPower=void 0===r.values.shininess?0:r.values.shininess,"string"==typeof r.values.ambient?this._loadTexture(e,r.values.ambient,o,"ambientTexture",n):o.ambientColor=a.Wo.FromArray(r.values.ambient||[0,0,0]),"string"==typeof r.values.diffuse?this._loadTexture(e,r.values.diffuse,o,"diffuseTexture",n):o.diffuseColor=a.Wo.FromArray(r.values.diffuse||[0,0,0]),"string"==typeof r.values.emission?this._loadTexture(e,r.values.emission,o,"emissiveTexture",n):o.emissiveColor=a.Wo.FromArray(r.values.emission||[0,0,0]),"string"==typeof r.values.specular?this._loadTexture(e,r.values.specular,o,"specularTexture",n):o.specularColor=a.Wo.FromArray(r.values.specular||[0,0,0]),!0}_loadTexture(e,t,i,n,s){GA.LoadTextureBufferAsync(e,t,(s=>{GA.CreateTextureAsync(e,t,s,(e=>i[n]=e))}),s)}});class XA{constructor(e,t,i,n){this.type=e,this.name=t,this.getValue=i,this.getStride=n}_buildAnimation(e,t,i){const n=new A(e,this.name,t,this.type);return n.setKeys(i),n}}class YA extends XA{buildAnimations(e,t,i,n,s){s(e._babylonTransformNode,this._buildAnimation(t,i,n))}}const jA={translation:[new YA(A.ANIMATIONTYPE_VECTOR3,"position",HA,(()=>3))],rotation:[new YA(A.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",(function(e,t,i,n){return o._f.FromArray(t,i).scaleInPlace(n)}),(()=>4))],scale:[new YA(A.ANIMATIONTYPE_VECTOR3,"scaling",HA,(()=>3))],weights:[new class extends XA{buildAnimations(e,t,i,n,s){if(e._numMorphTargets)for(let r=0;r({frame:e.frame,inTangent:e.inTangent?e.inTangent[r]:void 0,value:e.value[r],outTangent:e.outTangent?e.outTangent[r]:void 0,interpolation:e.interpolation})))),e._primitiveBabylonMeshes)for(const t of e._primitiveBabylonMeshes)if(t.morphTargetManager){const e=t.morphTargetManager.getTarget(r),i=o.clone();e.animations.push(i),s(e,i)}}}}(A.ANIMATIONTYPE_FLOAT,"influence",(function(e,t,i,n){const s=new Array(e._numMorphTargets);for(let r=0;re._numMorphTargets))]};function KA(...e){const t=e=>e&&"object"==typeof e;return e.reduce(((e,i)=>(Object.keys(i).forEach((n=>{const s=e[n],r=i[n];Array.isArray(s)&&Array.isArray(r)?e[n]=s.concat(...r):t(s)&&t(r)?e[n]=KA(s,r):e[n]=r})),e)),{})}class qA{static Get(e,t,i){if(!t||null==i||!t[i])throw new Error(`${e}: Failed to find index (${i})`);return t[i]}static Assign(e){if(e)for(let t=0;te.dispose&&e.dispose())),this._extensions.length=0,this._gltf=null,this._bin=null,this._babylonScene=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions.length=0,this._parent.dispose())}importMeshAsync(e,t,i,n,s,r,o=""){return Promise.resolve().then((()=>{this._babylonScene=t,this._assetContainer=i,this._loadData(n);let r=null;if(e){const t={};if(this._gltf.nodes)for(const e of this._gltf.nodes)e.name&&(t[e.name]=e.index);r=(e instanceof Array?e:[e]).map((e=>{const i=t[e];if(void 0===i)throw new Error(`Failed to find node '${e}'`);return i}))}return this._loadAsync(s,o,r,(()=>({meshes:this._getMeshes(),particleSystems:[],skeletons:this._getSkeletons(),animationGroups:this._getAnimationGroups(),lights:this._babylonLights,transformNodes:this._getTransformNodes(),geometries:this._getGeometries()})))}))}loadAsync(e,t,i,n,s=""){return Promise.resolve().then((()=>(this._babylonScene=e,this._loadData(t),this._loadAsync(i,s,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._loadExtensions(),this._checkExtensions();const s=`${aA[aA.LOADING]} => ${aA[aA.READY]}`,r=`${aA[aA.LOADING]} => ${aA[aA.COMPLETE]}`;this._parent._startPerformanceCounter(s),this._parent._startPerformanceCounter(r),this._parent._setState(aA.LOADING),this._extensionsOnLoading();const o=new Array,a=this._babylonScene.blockMaterialDirtyMechanism;if(this._babylonScene.blockMaterialDirtyMechanism=!0,!this.parent.loadOnlyMaterials)if(i)o.push(this.loadSceneAsync("/nodes",{nodes:i,index:-1}));else if(null!=this._gltf.scene||this._gltf.scenes&&this._gltf.scenes[0]){const e=qA.Get("/scene",this._gltf.scenes,this._gltf.scene||0);o.push(this.loadSceneAsync(`/scenes/${e.index}`,e))}if(!this.parent.skipMaterials&&this.parent.loadAllMaterials&&this._gltf.materials)for(let e=0;e{})))}this._babylonScene.blockMaterialDirtyMechanism=a,this._parent.compileMaterials&&o.push(this._compileMaterialsAsync()),this._parent.compileShadowGenerators&&o.push(this._compileShadowGeneratorsAsync());return Promise.all(o).then((()=>(this._rootBabylonMesh&&this._rootBabylonMesh.setEnabled(!0),this._extensionsOnReady(),this._parent._setState(aA.READY),this._startAnimations(),n()))).then((e=>(this._parent._endPerformanceCounter(s),se.w1.SetImmediate((()=>{this._disposed||Promise.all(this._completePromises).then((()=>{this._parent._endPerformanceCounter(r),this._parent._setState(aA.COMPLETE),this._parent.onCompleteObservable.notifyObservers(void 0),this._parent.onCompleteObservable.clear(),this.dispose()}),(e=>{this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()}))})),e)))})).catch((e=>{throw this._disposed||(this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()),e}))}_loadData(e){if(this._gltf=e.json,this._setupData(),e.bin){const t=this._gltf.buffers;if(t&&t[0]&&!t[0].uri){const i=t[0];(i.byteLengthe.bin.byteLength)&&p.Y.Warn(`Binary buffer length (${i.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else p.Y.Warn("Unexpected BIN chunk")}}_setupData(){if(qA.Assign(this._gltf.accessors),qA.Assign(this._gltf.animations),qA.Assign(this._gltf.buffers),qA.Assign(this._gltf.bufferViews),qA.Assign(this._gltf.cameras),qA.Assign(this._gltf.images),qA.Assign(this._gltf.materials),qA.Assign(this._gltf.meshes),qA.Assign(this._gltf.nodes),qA.Assign(this._gltf.samplers),qA.Assign(this._gltf.scenes),qA.Assign(this._gltf.skins),qA.Assign(this._gltf.textures),this._gltf.nodes){const e={};for(const i of this._gltf.nodes)if(i.children)for(const t of i.children)e[t]=i.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 $A._RegisteredExtensions){const t=$A._RegisteredExtensions[e].factory(this);t.name!==e&&p.Y.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)))throw new Error(`Require extension ${e} is not available`)}}_createRootNode(){this._babylonScene._blockEntityCollection=!!this._assetContainer,this._rootBabylonMesh=new ee.Kj("__root__",this._babylonScene),this._rootBabylonMesh._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._rootBabylonMesh.setEnabled(!1);const e={_babylonTransformNode:this._rootBabylonMesh,index:-1};switch(this._parent.coordinateSystemMode){case rA.AUTO:this._babylonScene.useRightHandedSystem||(e.rotation=[0,1,0,0],e.scale=[1,1,-1],$A._LoadTransform(e,this._rootBabylonMesh));break;case rA.FORCE_RIGHT_HANDED:this._babylonScene.useRightHandedSystem=!0;break;default:throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`)}return this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh),e}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 s of t.nodes){const t=qA.Get(`${e}/nodes/${s}`,this._gltf.nodes,s);n.push(this.loadNodeAsync(`/nodes/${t.index}`,t,(e=>{e.parent=this._rootBabylonMesh})))}for(const s of this._postSceneLoadActions)s();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=new Array,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=new Array;this._rootBabylonMesh&&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=new Array,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=new Array,t=this._gltf.skins;if(t)for(const i of t)i._data&&e.push(i._data.babylonSkeleton);return e}_getAnimationGroups(){const e=new Array,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 oA.NONE:break;case oA.FIRST:{const e=this._getAnimationGroups();0!==e.length&&e[0].start(!0);break}case oA.ALL:{const e=this._getAnimationGroups();for(const t of e)t.start(!0);break}default:return void p.Y.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 s=new Array;this.logOpen(`${e} ${t.name||""}`);const r=n=>{if($A.AddPointerMetadata(n,e),$A._LoadTransform(t,n),null!=t.camera){const i=qA.Get(`${e}/camera`,this._gltf.cameras,t.camera);s.push(this.loadCameraAsync(`/cameras/${i.index}`,i,(e=>{e.parent=n})))}if(t.children)for(const i of t.children){const t=qA.Get(`${e}/children/${i}`,this._gltf.nodes,i);s.push(this.loadNodeAsync(`/nodes/${t.index}`,t,(e=>{e.parent=n})))}i(n)};if(null==t.mesh||null!=t.skin){const e=t.name||`node${t.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new te.Y(e,this._babylonScene);i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,null==t.mesh?t._babylonTransformNode=i:t._babylonTransformNodeForSkin=i,r(i)}if(null!=t.mesh)if(null==t.skin){const i=qA.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);s.push(this._loadMeshAsync(`/meshes/${i.index}`,t,i,r))}else{const i=qA.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);s.push(this._loadMeshAsync(`/meshes/${i.index}`,t,i,(i=>{const n=t._babylonTransformNodeForSkin;i.metadata=KA(n.metadata,i.metadata||{});const r=qA.Get(`${e}/skin`,this._gltf.skins,t.skin);s.push(this._loadSkinAsync(`/skins/${r.index}`,t,r,(e=>{this._forEachPrimitive(t,(t=>{t.skeleton=e})),this._postSceneLoadActions.push((()=>{if(null!=r.skeleton){const e=qA.Get(`/skins/${r.index}/skeleton`,this._gltf.nodes,r.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})}))})))})))}return this.logClose(),Promise.all(s).then((()=>(this._forEachPrimitive(t,(e=>{e.geometry&&e.geometry.useBoundingInfoFromGeometry?e._updateBoundingInfo():e.refreshBoundingInfo(!0)})),t._babylonTransformNode)))}_loadMeshAsync(e,t,i,n){const s=i.primitives;if(!s||!s.length)throw new Error(`${e}: Primitives are missing`);null==s[0].index&&qA.Assign(s);const r=new Array;this.logOpen(`${e} ${i.name||""}`);const o=t.name||`node${t.index}`;if(1===s.length){const n=i.primitives[0];r.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${n.index}`,o,t,i,n,(e=>{t._babylonTransformNode=e,t._primitiveBabylonMeshes=[e]})))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,t._babylonTransformNode=new te.Y(o,this._babylonScene),t._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._primitiveBabylonMeshes=[];for(const n of s)r.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${n.index}`,`${o}_primitive${n.index}`,t,i,n,(e=>{e.parent=t._babylonTransformNode,t._primitiveBabylonMeshes.push(e)})))}return n(t._babylonTransformNode),this.logClose(),Promise.all(r).then((()=>t._babylonTransformNode))}_loadMeshPrimitiveAsync(e,t,i,n,s,r){const o=this._extensionsLoadMeshPrimitiveAsync(e,t,i,n,s,r);if(o)return o;this.logOpen(`${e}`);const a=0===this._disableInstancedMesh&&this._parent.createInstances&&null==i.skin&&!n.primitives[0].targets;let l,h;if(a&&s._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,l=s._instanceData.babylonSourceMesh.createInstance(t),l._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,h=s._instanceData.promise;else{const r=new Array;this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new ee.Kj(t,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,o.overrideMaterialSideOrientation=this._babylonScene.useRightHandedSystem?ut.F.CounterClockWiseSideOrientation:ut.F.ClockWiseSideOrientation,this._createMorphTargets(e,i,n,s,o),r.push(this._loadVertexDataAsync(e,s,o).then((t=>this._loadMorphTargetsAsync(e,s,o,t).then((()=>{this._disposed||(this._babylonScene._blockEntityCollection=!!this._assetContainer,t.applyToMesh(o),t._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1)})))));const c=$A._GetDrawMode(e,s.mode);if(null==s.material){let e=this._defaultBabylonMaterialData[c];e||(e=this._createDefaultMaterial("__GLTFLoader._default",c),this._parent.onMaterialLoadedObservable.notifyObservers(e),this._defaultBabylonMaterialData[c]=e),o.material=e}else if(!this.parent.skipMaterials){const t=qA.Get(`${e}/material`,this._gltf.materials,s.material);r.push(this._loadMaterialAsync(`/materials/${t.index}`,t,o,c,(e=>{o.material=e})))}h=Promise.all(r),a&&(s._instanceData={babylonSourceMesh:o,promise:h}),l=o}return $A.AddPointerMetadata(l,e),this._parent.onMeshLoadedObservable.notifyObservers(l),r(l),this.logClose(),h.then((()=>l))}_loadVertexDataAsync(e,t,i){const n=this._extensionsLoadVertexDataAsync(e,t,i);if(n)return n;const s=t.attributes;if(!s)throw new Error(`${e}: Attributes are missing`);const r=new Array,a=new Gg.Z(i.name,this._babylonScene);if(null==t.indices)i.isUnIndexed=!0;else{const i=qA.Get(`${e}/indices`,this._gltf.accessors,t.indices);r.push(this._loadIndicesAccessorAsync(`/accessors/${i.index}`,i).then((e=>{a.setIndices(e)})))}const l=(t,n,l)=>{if(null==s[t])return;i._delayInfo=i._delayInfo||[],-1===i._delayInfo.indexOf(n)&&i._delayInfo.push(n);const h=qA.Get(`${e}/attributes/${t}`,this._gltf.accessors,s[t]);r.push(this._loadVertexAccessorAsync(`/accessors/${h.index}`,h,n).then((e=>{if(e.getKind()===ne.o.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!i.skeleton&&h.min&&h.max){const e=o.jp.Vector3[0].copyFromFloats(...h.min),t=o.jp.Vector3[1].copyFromFloats(...h.max);if(h.normalized&&5126!==h.componentType){let i=1;switch(h.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 ol.j(e,t),a.useBoundingInfoFromGeometry=!0}a.setVerticesBuffer(e,h.count)}))),n==ne.o.MatricesIndicesExtraKind&&(i.numBoneInfluencers=8),l&&l(h)};return l("POSITION",ne.o.PositionKind),l("NORMAL",ne.o.NormalKind),l("TANGENT",ne.o.TangentKind),l("TEXCOORD_0",ne.o.UVKind),l("TEXCOORD_1",ne.o.UV2Kind),l("TEXCOORD_2",ne.o.UV3Kind),l("TEXCOORD_3",ne.o.UV4Kind),l("TEXCOORD_4",ne.o.UV5Kind),l("TEXCOORD_5",ne.o.UV6Kind),l("JOINTS_0",ne.o.MatricesIndicesKind),l("WEIGHTS_0",ne.o.MatricesWeightsKind),l("JOINTS_1",ne.o.MatricesIndicesExtraKind),l("WEIGHTS_1",ne.o.MatricesWeightsExtraKind),l("COLOR_0",ne.o.ColorKind,(e=>{"VEC4"===e.type&&(i.hasVertexAlpha=!0)})),Promise.all(r).then((()=>a))}_createMorphTargets(e,t,i,n,s){if(!n.targets)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 r=i.extras?i.extras.targetNames:null;this._babylonScene._blockEntityCollection=!!this._assetContainer,s.morphTargetManager=new Jg(this._babylonScene),s.morphTargetManager._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,s.morphTargetManager.areUpdatesFrozen=!0;for(let o=0;o{r.areUpdatesFrozen=!1}))}_loadMorphTargetVertexDataAsync(e,t,i,n){const s=new Array,r=(n,r,o)=>{if(null==i[n])return;const a=t.getVertexBuffer(r);if(!a)return;const l=qA.Get(`${e}/${n}`,this._gltf.accessors,i[n]);s.push(this._loadFloatAccessorAsync(`/accessors/${l.index}`,l).then((e=>{o(a,e)})))};return r("POSITION",ne.o.PositionKind,((e,t)=>{const i=new Float32Array(t.length);e.forEach(t.length,((e,n)=>{i[n]=t[n]+e})),n.setPositions(i)})),r("NORMAL",ne.o.NormalKind,((e,t)=>{const i=new Float32Array(t.length);e.forEach(i.length,((e,n)=>{i[n]=t[n]+e})),n.setNormals(i)})),r("TANGENT",ne.o.TangentKind,((e,t)=>{const i=new Float32Array(t.length/3*4);let s=0;e.forEach(t.length/3*4,((e,n)=>{(n+1)%4!=0&&(i[s]=t[s]+e,s++)})),n.setTangents(i)})),Promise.all(s).then((()=>{}))}static _LoadTransform(e,t){if(null!=e.skin)return;let i=o.P.Zero(),n=o._f.Identity(),s=o.P.One();if(e.matrix){o.y3.FromArray(e.matrix).decompose(s,n,i)}else e.translation&&(i=o.P.FromArray(e.translation)),e.rotation&&(n=o._f.FromArray(e.rotation)),e.scale&&(s=o.P.FromArray(e.scale));t.position=i,t.rotationQuaternion=n,t.scaling=s}_loadSkinAsync(e,t,i,n){const s=this._extensionsLoadSkinAsync(e,t,i);if(s)return s;if(i._data)return n(i._data.babylonSkeleton),i._data.promise;const r=`skeleton${i.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new ji(i.name||r,r,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._loadBones(e,i,o);const a=this._loadSkinInverseBindMatricesDataAsync(e,i).then((e=>{this._updateBoneMatrices(o,e)}));return i._data={babylonSkeleton:o,promise:a},n(o),a}_loadBones(e,t,i){if(null==t.skeleton||this._parent.alwaysComputeSkeletonRootNode){const i=this._findSkeletonRootNode(`${e}/joints`,t.joints);if(i)if(void 0===t.skeleton)t.skeleton=i.index;else{const n=(e,t)=>{for(;t.parent;t=t.parent)if(t.parent===e)return!0;return!1},s=qA.Get(`${e}/skeleton`,this._gltf.nodes,t.skeleton);s===i||n(s,i)||(p.Y.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),t.skeleton=i.index)}else p.Y.Warn(`${e}: Failed to find common root`)}const n={};for(const s of t.joints){const r=qA.Get(`${e}/joints/${s}`,this._gltf.nodes,s);this._loadBone(r,t,i,n)}}_findSkeletonRootNode(e,t){if(0===t.length)return null;const i={};for(const s of t){const t=new Array;let n=qA.Get(`${e}/${s}`,this._gltf.nodes,s);for(;-1!==n.index;)t.unshift(n),n=n.parent;i[s]=t}let n=null;for(let s=0;;++s){let e=i[t[0]];if(s>=e.length)return n;const r=e[s];for(let o=1;o=e.length||r!==e[s])return n;n=r}}_loadBone(e,t,i,n){let s=n[e.index];if(s)return s;let r=null;e.index!==t.skeleton&&(e.parent&&-1!==e.parent.index?r=this._loadBone(e.parent,t,i,n):void 0!==t.skeleton&&p.Y.Warn(`/skins/${t.index}/skeleton: Skeleton node is not a common root`));const o=t.joints.indexOf(e.index);return s=new B(e.name||`joint${e.index}`,i,r,this._getNodeMatrix(e),null,null,o),n[e.index]=s,this._postSceneLoadActions.push((()=>{s.linkTransformNode(e._babylonTransformNode)})),s}_loadSkinInverseBindMatricesDataAsync(e,t){if(null==t.inverseBindMatrices)return Promise.resolve(null);const i=qA.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=o.y3.Identity(),n=i._index;t&&-1!==n&&(o.y3.FromArrayToRef(t,16*n,e),e.invertToRef(e));const s=i.getParent();s&&e.multiplyToRef(s.getAbsoluteInverseBindMatrix(),e),i.updateMatrix(e,!1,!1),i._updateAbsoluteBindMatrices(void 0,!1)}}_getNodeMatrix(e){return e.matrix?o.y3.FromArray(e.matrix):o.y3.Compose(e.scale?o.P.FromArray(e.scale):o.P.One(),e.rotation?o._f.FromArray(e.rotation):o._f.Identity(),e.translation?o.P.FromArray(e.translation):o.P.Zero())}loadCameraAsync(e,t,i=(()=>{})){const n=this._extensionsLoadCameraAsync(e,t,i);if(n)return n;const s=new Array;this.logOpen(`${e} ${t.name||""}`),this._babylonScene._blockEntityCollection=!!this._assetContainer;const r=new Fn(t.name||`camera${t.index}`,o.P.Zero(),this._babylonScene,!1);switch(r._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,r.ignoreParentScaling=!0,t._babylonCamera=r,r.rotation=new o.P(0,Math.PI,0),t.type){case"perspective":{const i=t.perspective;if(!i)throw new Error(`${e}: Camera perspective properties are missing`);r.fov=i.yfov,r.minZ=i.znear,r.maxZ=i.zfar||0;break}case"orthographic":if(!t.orthographic)throw new Error(`${e}: Camera orthographic properties are missing`);r.mode=ce.V.ORTHOGRAPHIC_CAMERA,r.orthoLeft=-t.orthographic.xmag,r.orthoRight=t.orthographic.xmag,r.orthoBottom=-t.orthographic.ymag,r.orthoTop=t.orthographic.ymag,r.minZ=t.orthographic.znear,r.maxZ=t.orthographic.zfar;break;default:throw new Error(`${e}: Invalid camera type (${t.type})`)}return $A.AddPointerMetadata(r,e),this._parent.onCameraLoadedObservable.notifyObservers(r),i(r),this.logClose(),Promise.all(s).then((()=>r))}_loadAnimationsAsync(){const e=this._gltf.animations;if(!e)return Promise.resolve();const t=new Array;for(let i=0;i{0===e.targetedAnimations.length&&e.dispose()})))}return Promise.all(t).then((()=>{}))}loadAnimationAsync(e,t){const i=this._extensionsLoadAnimationAsync(e,t);if(i)return i;this._babylonScene._blockEntityCollection=!!this._assetContainer;const n=new J(t.name||`animation${t.index}`,this._babylonScene);n._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=n;const s=new Array;qA.Assign(t.channels),qA.Assign(t.samplers);for(const r of t.channels)s.push(this._loadAnimationChannelAsync(`${e}/channels/${r.index}`,e,t,r,((e,t)=>{e.animations=e.animations||[],e.animations.push(t),n.addTargetedAnimation(t,e)})));return Promise.all(s).then((()=>(n.normalize(0),n)))}_loadAnimationChannelAsync(e,t,i,n,s){const r=this._extensionsLoadAnimationChannelAsync(e,t,i,n,s);if(r)return r;if(null==n.target.node)return Promise.resolve();const o=qA.Get(`${e}/target/node`,this._gltf.nodes,n.target.node);if("weights"===n.target.path&&!o._numMorphTargets||"weights"!==n.target.path&&!o._babylonTransformNode)return Promise.resolve();let a;switch(n.target.path){case"translation":a=jA.translation;break;case"rotation":a=jA.rotation;break;case"scale":a=jA.scale;break;case"weights":a=jA.weights;break;default:throw new Error(`${e}/target/path: Invalid value (${n.target.path})`)}const l={target:o,properties:a};return this._loadAnimationChannelFromTargetInfoAsync(e,t,i,n,l,s)}_loadAnimationChannelFromTargetInfoAsync(e,t,i,n,s,r){const o=this.parent.targetFps,a=1/o,l=qA.Get(`${e}/sampler`,i.samplers,n.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${n.sampler}`,l).then((e=>{let t=0;for(const l of s.properties){const h=l.getStride(s.target),c=e.input,d=e.output,u=new Array(c.length);let p=0;switch(e.interpolation){case"STEP":for(let e=0;e0){const e=`${i.name||`animation${i.index}`}_channel${n.index}_${t}`;l.buildAnimations(s.target,e,o,u,((e,i)=>{++t,r(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=qA.Get(`${e}/input`,this._gltf.accessors,t.input),s=qA.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${n.index}`,n),this._loadFloatAccessorAsync(`/accessors/${s.index}`,s)]).then((([e,t])=>({input:e,interpolation:i,output:t}))),t._data}loadBufferAsync(e,t,i,n){const s=this._extensionsLoadBufferAsync(e,t,i,n);if(s)return s;if(!t._data)if(t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{if(!this._bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);t._data=this._bin.readAsync(0,t.byteLength)}return t._data.then((t=>{try{return new Uint8Array(t.buffer,t.byteOffset+i,n)}catch(s){throw new Error(`${e}: ${s.message}`)}}))}loadBufferViewAsync(e,t){const i=this._extensionsLoadBufferViewAsync(e,t);if(i)return i;if(t._data)return t._data;const n=qA.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=$A._GetNumComponents(e,t.type),s=n*ne.o.GetTypeByteLength(t.componentType),r=n*t.count;if(null==t.bufferView)t._data=Promise.resolve(new i(r));else{const o=qA.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${o.index}`,o).then((a=>{if(5126!==t.componentType||t.normalized||o.byteStride&&o.byteStride!==s){const e=new i(r);return ne.o.ForEach(a,t.byteOffset||0,o.byteStride||s,n,t.componentType,e.length,t.normalized||!1,((t,i)=>{e[i]=t})),e}return $A._GetTypedArray(e,t.componentType,a,t.byteOffset,r)}))}if(t.sparse){const r=t.sparse;t._data=t._data.then((o=>{const a=o,l=qA.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,r.indices.bufferView),h=qA.Get(`${e}/sparse/values/bufferView`,this._gltf.bufferViews,r.values.bufferView);return Promise.all([this.loadBufferViewAsync(`/bufferViews/${l.index}`,l),this.loadBufferViewAsync(`/bufferViews/${h.index}`,h)]).then((([o,l])=>{const h=$A._GetTypedArray(`${e}/sparse/indices`,r.indices.componentType,o,r.indices.byteOffset,r.count),c=n*r.count;let d;if(5126!==t.componentType||t.normalized){const o=$A._GetTypedArray(`${e}/sparse/values`,t.componentType,l,r.values.byteOffset,c);d=new i(c),ne.o.ForEach(o,0,s,n,t.componentType,d.length,t.normalized||!1,((e,t)=>{d[t]=e}))}else d=$A._GetTypedArray(`${e}/sparse/values`,t.componentType,l,r.values.byteOffset,c);let u=0;for(let e=0;e$A._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 ne.l(t,e,!1))),e._babylonBuffer}_loadVertexAccessorAsync(e,t,i){var n;if(null===(n=t._babylonVertexBuffer)||void 0===n?void 0:n[i])return t._babylonVertexBuffer[i];t._babylonVertexBuffer||(t._babylonVertexBuffer={});const s=this._babylonScene.getEngine();if(t.sparse)t._babylonVertexBuffer[i]=this._loadFloatAccessorAsync(e,t).then((e=>new ne.o(s,e,i,!1)));else if(i===ne.o.MatricesIndicesKind||i===ne.o.MatricesIndicesExtraKind)t._babylonVertexBuffer[i]=this._loadFloatAccessorAsync(e,t).then((e=>new ne.o(s,e,i,!1)));else{const n=qA.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._babylonVertexBuffer[i]=this._loadVertexBufferViewAsync(n).then((r=>{const o=$A._GetNumComponents(e,t.type);return new ne.o(s,r,i,!1,!1,n.byteStride,!1,t.byteOffset,o,t.componentType,t.normalized,!0,1,!0)}))}return t._babylonVertexBuffer[i]}_loadMaterialMetallicRoughnessPropertiesAsync(e,t,i){if(!(i instanceof O_))throw new Error(`${e}: Material type not supported`);const n=new Array;return t&&(t.baseColorFactor?(i.albedoColor=a.Wo.FromArray(t.baseColorFactor),i.alpha=t.baseColorFactor[3]):i.albedoColor=a.Wo.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,s=(()=>{})){const r=this._extensionsLoadMaterialAsync(e,t,i,n,s);if(r)return r;t._data=t._data||{};let o=t._data[n];if(!o){this.logOpen(`${e} ${t.name||""}`);const i=this.createMaterial(e,t,n);o={babylonMaterial:i,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(e,t,i)},t._data[n]=o,$A.AddPointerMetadata(i,e),this._parent.onMaterialLoadedObservable.notifyObservers(i),this.logClose()}return i&&(o.babylonMeshes.push(i),i.onDisposeObservable.addOnce((()=>{const e=o.babylonMeshes.indexOf(i);-1!==e&&o.babylonMeshes.splice(e,1)}))),s(o.babylonMaterial),o.promise.then((()=>o.babylonMaterial))}_createDefaultMaterial(e,t){this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new O_(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=O_.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 s=t.name||`material${t.index}`;return this._createDefaultMaterial(s,i)}loadMaterialPropertiesAsync(e,t,i){const n=this._extensionsLoadMaterialPropertiesAsync(e,t,i);if(n)return n;const s=new Array;return s.push(this.loadMaterialBasePropertiesAsync(e,t,i)),t.pbrMetallicRoughness&&s.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,i)),this.loadMaterialAlphaProperties(e,t,i),Promise.all(s).then((()=>{}))}loadMaterialBasePropertiesAsync(e,t,i){if(!(i instanceof O_))throw new Error(`${e}: Material type not supported`);const n=new Array;return i.emissiveColor=t.emissiveFactor?a.Wo.FromArray(t.emissiveFactor):new a.Wo(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 O_))throw new Error(`${e}: Material type not supported`);switch(t.alphaMode||"OPAQUE"){case"OPAQUE":i.transparencyMode=O_.PBRMATERIAL_OPAQUE;break;case"MASK":i.transparencyMode=O_.PBRMATERIAL_ALPHATEST,i.alphaCutOff=null==t.alphaCutoff?.5:t.alphaCutoff,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0);break;case"BLEND":i.transparencyMode=O_.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 s=qA.Get(`${e}/index`,this._gltf.textures,t.index);s._textureInfo=t;const r=this._loadTextureAsync(`/textures/${t.index}`,s,(n=>{n.coordinatesIndex=t.texCoord||0,$A.AddPointerMetadata(n,e),this._parent.onTextureLoadedObservable.notifyObservers(n),i(n)}));return this.logClose(),r}_loadTextureAsync(e,t,i=(()=>{})){const n=this._extensionsLoadTextureAsync(e,t,i);if(n)return n;this.logOpen(`${e} ${t.name||""}`);const s=null==t.sampler?$A.DefaultSampler:qA.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),r=qA.Get(`${e}/source`,this._gltf.images,t.source),o=this._createTextureAsync(e,s,r,i,void 0,!t._textureInfo.nonColorData);return this.logClose(),o}_createTextureAsync(e,t,i,n=(()=>{}),s,r){const o=this._loadSampler(`/samplers/${t.index}`,t),a=new Array,l=new wC;this._babylonScene._blockEntityCollection=!!this._assetContainer;const h={noMipmap:o.noMipMaps,invertY:!1,samplingMode:o.samplingMode,onLoad:()=>{this._disposed||l.resolve()},onError:(t,i)=>{this._disposed||l.reject(new Error(`${e}: ${i&&i.message?i.message:t||"Failed to load texture"}`))},mimeType:i.mimeType,loaderOptions:s,useSRGBBuffer:!!r&&this._parent.useSRGBBuffers},c=new Le(null,this._babylonScene,h);return c._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,a.push(l.promise),a.push(this.loadImageAsync(`/images/${i.index}`,i).then((e=>{const t=i.uri||`${this._fileName}#image${i.index}`,n=`data:${this._uniqueRootUrl}${t}`;c.updateURL(n,e)}))),c.wrapU=o.wrapU,c.wrapV=o.wrapV,n(c),Promise.all(a).then((()=>c))}_loadSampler(e,t){return t._data||(t._data={noMipMaps:9728===t.minFilter||9729===t.minFilter,samplingMode:$A._GetTextureSamplingMode(e,t),wrapU:$A._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:$A._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=qA.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(!$A._ValidateUri(i))throw new Error(`${e}: '${i}' is invalid`);if((0,ye.VL)(i)){const t=new Uint8Array((0,ye.$K)(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,s)=>{this._parent._loadFile(this._babylonScene,t,(t=>{this._disposed||(this.log(`${e}: Loaded ${i} (${t.byteLength} bytes)`),n(new Uint8Array(t)))}),!0,(t=>{s(new ye.eh(`${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 Le.CLAMP_ADDRESSMODE;case 33648:return Le.MIRROR_ADDRESSMODE;case 10497:return Le.WRAP_ADDRESSMODE;default:return p.Y.Warn(`${e}: Invalid value (${t})`),Le.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 Le.LINEAR_NEAREST;case 9729:return Le.LINEAR_LINEAR;case 9984:return Le.LINEAR_NEAREST_MIPNEAREST;case 9985:return Le.LINEAR_LINEAR_MIPNEAREST;case 9986:return Le.LINEAR_NEAREST_MIPLINEAR;case 9987:return Le.LINEAR_LINEAR_MIPLINEAR;default:return p.Y.Warn(`${e}/minFilter: Invalid value (${n})`),Le.LINEAR_LINEAR_MIPLINEAR}else switch(9728!==i&&p.Y.Warn(`${e}/magFilter: Invalid value (${i})`),n){case 9728:return Le.NEAREST_NEAREST;case 9729:return Le.NEAREST_LINEAR;case 9984:return Le.NEAREST_NEAREST_MIPNEAREST;case 9985:return Le.NEAREST_LINEAR_MIPNEAREST;case 9986:return Le.NEAREST_NEAREST_MIPLINEAR;case 9987:return Le.NEAREST_LINEAR_MIPLINEAR;default:return p.Y.Warn(`${e}/minFilter: Invalid value (${n})`),Le.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,s){const r=i.buffer;n=i.byteOffset+(n||0);const o=$A._GetTypedArrayConstructor(`${e}/componentType`,t),a=ne.o.GetTypeByteLength(t);return n%a!=0?(p.Y.Warn(`${e}: Copying buffer as byte offset (${n}) is not a multiple of component type byte length (${a})`),new o(r.slice(n,n+s*a),0)):new o(r,n,s)}static _GetNumComponents(e,t){switch(t){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}throw new Error(`${e}: Invalid type (${t})`)}static _ValidateUri(e){return se.w1.IsBase64(e)||-1===e.indexOf("..")}static _GetDrawMode(e,t){switch(null==t&&(t=4),t){case 0:return ut.F.PointListDrawMode;case 1:return ut.F.LineListDrawMode;case 2:return ut.F.LineLoopDrawMode;case 3:return ut.F.LineStripDrawMode;case 4:return ut.F.TriangleFillMode;case 5:return ut.F.TriangleStripDrawMode;case 6:return ut.F.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 s=`${n.name}.${t}`,r=e;r._activeLoaderExtensionFunctions=r._activeLoaderExtensionFunctions||{};const o=r._activeLoaderExtensionFunctions;if(!o[s]){o[s]=!0;try{const e=i(n);if(e)return e}finally{delete o[s]}}}return null}_extensionsOnLoading(){this._forEachExtensions((e=>e.onLoading&&e.onLoading()))}_extensionsOnReady(){this._forEachExtensions((e=>e.onReady&&e.onReady()))}_extensionsLoadSceneAsync(e,t){return this._applyExtensions(t,"loadScene",(i=>i.loadSceneAsync&&i.loadSceneAsync(e,t)))}_extensionsLoadNodeAsync(e,t,i){return this._applyExtensions(t,"loadNode",(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,s,r){return this._applyExtensions(s,"loadMeshPrimitive",(o=>o._loadMeshPrimitiveAsync&&o._loadMeshPrimitiveAsync(e,t,i,n,s,r)))}_extensionsLoadMaterialAsync(e,t,i,n,s){return this._applyExtensions(t,"loadMaterial",(r=>r._loadMaterialAsync&&r._loadMaterialAsync(e,t,i,n,s)))}_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,s){return this._applyExtensions(i,"loadAnimationChannel",(r=>r._loadAnimationChannelAsync&&r._loadAnimationChannelAsync(e,t,i,n,s)))}_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",(s=>s.loadBufferAsync&&s.loadBufferAsync(e,t,i,n)))}static LoadExtensionAsync(e,t,i,n){if(!t.extensions)return null;const s=t.extensions[i];return s?n(`${e}/extensions/${i}`,s):null}static LoadExtraAsync(e,t,i,n){if(!t.extras)return null;const s=t.extras[i];return s?n(`${e}/extras/${i}`,s):null}isExtensionUsed(e){return!!this._gltf.extensionsUsed&&-1!==this._gltf.extensionsUsed.indexOf(e)}logOpen(e){this._parent._logOpen(e)}logClose(){this._parent._logClose()}log(e){this._parent._log(e)}startPerformanceCounter(e){this._parent._startPerformanceCounter(e)}endPerformanceCounter(e){this._parent._endPerformanceCounter(e)}}$A._RegisteredExtensions={},$A.DefaultSampler={index:-1},gA._CreateGLTF2Loader=e=>new $A(e);const QA="EXT_lights_image_based";class ZA{constructor(e){this.name=QA,this._loader=e,this.enabled=this._loader.isExtensionUsed(QA)}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 $A.LoadExtensionAsync(e,t,this.name,((i,n)=>{const s=new Array;s.push(this._loader.loadSceneAsync(e,t)),this._loader.logOpen(`${i}`);const r=qA.Get(`${i}/light`,this._lights,n.light);return s.push(this._loadLightAsync(`/extensions/${this.name}/lights/${n.light}`,r).then((e=>{this._loader.babylonScene.environmentTexture=e}))),this._loader.logClose(),Promise.all(s).then((()=>{}))}))}_loadLightAsync(e,t){if(!t._loaded){const i=new Array;this._loader.logOpen(`${e}`);const n=new Array(t.specularImages.length);for(let s=0;s{n[s][t]=e}))),this._loader.logClose()}}this._loader.logClose(),t._loaded=Promise.all(i).then((()=>{const i=new zv(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=o._f.FromArray(t.rotation);this._loader.babylonScene.useRightHandedSystem||(e=o._f.Inverse(e)),o.y3.FromQuaternionToRef(e,i.getReflectionTextureMatrix())}if(!t.irradianceCoefficients)throw new Error(`${e}: Irradiance coefficients are missing`);const s=Oh.FromArray(t.irradianceCoefficients);s.scaleInPlace(t.intensity),s.convertIrradianceToLambertianRadiance();const r=Dh.FromHarmonics(s),a=(n.length-1)/S.R.Log2(t.specularImageSize);return i.updateRGBDAsync(n,r,a)}))}return t._loaded.then((()=>t._babylonTexture))}}$A.RegisterExtension(QA,(e=>new ZA(e)));const JA="EXT_mesh_gpu_instancing";class eR{constructor(e){this.name=JA,this._loader=e,this.enabled=this._loader.isExtensionUsed(JA)}dispose(){this._loader=null}loadNodeAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((e,n)=>{this._loader._disableInstancedMesh++;const s=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,i);if(this._loader._disableInstancedMesh--,!t._primitiveBabylonMeshes)return s;const r=new Array;let a=0;const l=t=>{if(null==n.attributes[t])return void r.push(Promise.resolve(null));const i=qA.Get(`${e}/attributes/${t}`,this._loader.gltf.accessors,n.attributes[t]);if(r.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 l("TRANSLATION"),l("ROTATION"),l("SCALE"),s.then((e=>Promise.all(r).then((([i,n,s])=>{const r=new Float32Array(16*a);o.jp.Vector3[0].copyFromFloats(0,0,0),o.jp.Quaternion[0].copyFromFloats(0,0,0,1),o.jp.Vector3[1].copyFromFloats(1,1,1);for(let e=0;enew eR(e)));const tR="EXT_meshopt_compression";class iR{constructor(e){this.name=tR,this.enabled=e.isExtensionUsed(tR),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,t){return $A.LoadExtensionAsync(e,t,this.name,((i,n)=>{const s=t;if(s._meshOptData)return s._meshOptData;const r=qA.Get(`${e}/buffer`,this._loader.gltf.buffers,n.buffer);return s._meshOptData=this._loader.loadBufferAsync(`/buffers/${r.index}`,r,n.byteOffset||0,n.byteLength).then((e=>MT.Default.decodeGltfBufferAsync(e,n.count,n.byteStride,n.mode,n.filter))),s._meshOptData}))}}$A.RegisterExtension(tR,(e=>new iR(e)));const nR="EXT_texture_webp";class sR{constructor(e){this.name=nR,this._loader=e,this.enabled=e.isExtensionUsed(nR)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=null==t.sampler?$A.DefaultSampler:qA.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=qA.Get(`${n}/source`,this._loader.gltf.images,s.source);return this._loader._createTextureAsync(e,r,o,(e=>{i(e)}),void 0,!t._textureInfo.nonColorData)}))}}$A.RegisterExtension(nR,(e=>new sR(e)));const rR="KHR_draco_mesh_compression";class oR{constructor(e){this.name=rR,this._loader=e,this.enabled=IT.DecoderAvailable&&this._loader.isExtensionUsed(rR)}dispose(){delete this.dracoCompression,this._loader=null}_loadVertexDataAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>{if(null!=t.mode){if(5!==t.mode&&4!==t.mode)throw new Error(`${e}: Unsupported mode ${t.mode}`);if(5===t.mode)throw new Error(`${e}: Mode ${t.mode} is not currently supported`)}const r={},o={},a=(n,a)=>{const l=s.attributes[n];if(void 0===l||void 0===t.attributes[n])return;r[a]=l;const h=qA.Get(`${e}/attributes/${n}`,this._loader.gltf.accessors,t.attributes[n]);if(h.normalized&&5126!==h.componentType){let e=1;switch(h.componentType){case 5120:e=127;break;case 5121:e=255;break;case 5122:e=32767;break;case 5123:e=65535}o[a]=e}i._delayInfo=i._delayInfo||[],-1===i._delayInfo.indexOf(a)&&i._delayInfo.push(a)};a("POSITION",ne.o.PositionKind),a("NORMAL",ne.o.NormalKind),a("TANGENT",ne.o.TangentKind),a("TEXCOORD_0",ne.o.UVKind),a("TEXCOORD_1",ne.o.UV2Kind),a("TEXCOORD_2",ne.o.UV3Kind),a("TEXCOORD_3",ne.o.UV4Kind),a("TEXCOORD_4",ne.o.UV5Kind),a("TEXCOORD_5",ne.o.UV6Kind),a("JOINTS_0",ne.o.MatricesIndicesKind),a("WEIGHTS_0",ne.o.MatricesWeightsKind),a("COLOR_0",ne.o.ColorKind);const l=qA.Get(n,this._loader.gltf.bufferViews,s.bufferView);return l._dracoBabylonGeometry||(l._dracoBabylonGeometry=this._loader.loadBufferViewAsync(`/bufferViews/${l.index}`,l).then((t=>(this.dracoCompression||IT.Default).decodeMeshAsync(t,r,o).then((e=>{const t=new Gg.Z(i.name,this._loader.babylonScene);return e.applyToGeometry(t),t})).catch((t=>{throw new Error(`${e}: ${t.message}`)}))))),l._dracoBabylonGeometry}))}}$A.RegisterExtension(rR,(e=>new oR(e)));const aR="KHR_lights_punctual";class lR{constructor(e){this.name=aR,this._loader=e,this.enabled=this._loader.isExtensionUsed(aR)}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,qA.Assign(this._lights)}}loadNodeAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>this._loader.loadNodeAsync(e,t,(e=>{let t;const r=qA.Get(n,this._lights,s.light),l=r.name||e.name;switch(this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,r.type){case"directional":{const e=new sp(l,o.P.Backward(),this._loader.babylonScene);e.position.setAll(0),t=e;break}case"point":t=new Vg(l,o.P.Zero(),this._loader.babylonScene);break;case"spot":{const e=new op(l,o.P.Zero(),o.P.Backward(),0,1,this._loader.babylonScene);e.angle=2*(r.spot&&r.spot.outerConeAngle||Math.PI/4),e.innerAngle=2*(r.spot&&r.spot.innerConeAngle||0),t=e;break}default:throw this._loader.babylonScene._blockEntityCollection=!1,new Error(`${n}: Invalid light type (${r.type})`)}t._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,r._babylonLight=t,t.falloffType=he.FALLOFF_GLTF,t.diffuse=r.color?a.Wo.FromArray(r.color):a.Wo.White(),t.intensity=null==r.intensity?1:r.intensity,t.range=null==r.range?Number.MAX_VALUE:r.range,t.parent=e,this._loader._babylonLights.push(t),$A.AddPointerMetadata(t,n),i(e)}))))}}$A.RegisterExtension(aR,(e=>new lR(e)));const hR="KHR_materials_pbrSpecularGlossiness";class cR{constructor(e){this.name=hR,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(hR)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),r.push(this._loadSpecularGlossinessPropertiesAsync(n,t,s,i)),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(r).then((()=>{}))}))}_loadSpecularGlossinessPropertiesAsync(e,t,i,n){if(!(n instanceof O_))throw new Error(`${e}: Material type not supported`);const s=new Array;return n.metallic=null,n.roughness=null,i.diffuseFactor?(n.albedoColor=a.Wo.FromArray(i.diffuseFactor),n.alpha=i.diffuseFactor[3]):n.albedoColor=a.Wo.White(),n.reflectivityColor=i.specularFactor?a.Wo.FromArray(i.specularFactor):a.Wo.White(),n.microSurface=null==i.glossinessFactor?1:i.glossinessFactor,i.diffuseTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTexture`,i.diffuseTexture,(e=>{e.name=`${n.name} (Diffuse)`,n.albedoTexture=e}))),i.specularGlossinessTexture&&(s.push(this._loader.loadTextureInfoAsync(`${e}/specularGlossinessTexture`,i.specularGlossinessTexture,(e=>{e.name=`${n.name} (Specular Glossiness)`,n.reflectivityTexture=e,n.reflectivityTexture.hasAlpha=!0}))),n.useMicroSurfaceFromReflectivityMapAlpha=!0),Promise.all(s).then((()=>{}))}}$A.RegisterExtension(hR,(e=>new cR(e)));const dR="KHR_materials_unlit";class uR{constructor(e){this.name=dR,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(dR)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,(()=>this._loadUnlitPropertiesAsync(e,t,i)))}_loadUnlitPropertiesAsync(e,t,i){if(!(i instanceof O_))throw new Error(`${e}: Material type not supported`);const n=new Array;i.unlit=!0;const s=t.pbrMetallicRoughness;return s&&(s.baseColorFactor?(i.albedoColor=a.Wo.FromArray(s.baseColorFactor),i.alpha=s.baseColorFactor[3]):i.albedoColor=a.Wo.White(),s.baseColorTexture&&n.push(this._loader.loadTextureInfoAsync(`${e}/baseColorTexture`,s.baseColorTexture,(e=>{e.name=`${i.name} (Base Color)`,i.albedoTexture=e})))),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(n).then((()=>{}))}}$A.RegisterExtension(dR,(e=>new uR(e)));const pR="KHR_materials_clearcoat";class fR{constructor(e){this.name=pR,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(pR)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadClearCoatPropertiesAsync(n,s,i)),Promise.all(r).then((()=>{}))}))}_loadClearCoatPropertiesAsync(e,t,i){if(!(i instanceof O_))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((()=>{}))}}$A.RegisterExtension(pR,(e=>new fR(e)));const _R="KHR_materials_iridescence";class mR{constructor(e){this.name=_R,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(_R)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadIridescencePropertiesAsync(n,s,i)),Promise.all(r).then((()=>{}))}))}_loadIridescencePropertiesAsync(e,t,i){var n,s,r,o,a;if(!(i instanceof O_))throw new Error(`${e}: Material type not supported`);const l=new Array;return i.iridescence.isEnabled=!0,i.iridescence.intensity=null!==(n=t.iridescenceFactor)&&void 0!==n?n:0,i.iridescence.indexOfRefraction=null!==(r=null!==(s=t.iridescenceIor)&&void 0!==s?s:t.iridescenceIOR)&&void 0!==r?r:1.3,i.iridescence.minimumThickness=null!==(o=t.iridescenceThicknessMinimum)&&void 0!==o?o:100,i.iridescence.maximumThickness=null!==(a=t.iridescenceThicknessMaximum)&&void 0!==a?a:400,t.iridescenceTexture&&l.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceTexture`,t.iridescenceTexture,(e=>{e.name=`${i.name} (Iridescence Intensity)`,i.iridescence.texture=e}))),t.iridescenceThicknessTexture&&l.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceThicknessTexture`,t.iridescenceThicknessTexture,(e=>{e.name=`${i.name} (Iridescence Thickness)`,i.iridescence.thicknessTexture=e}))),Promise.all(l).then((()=>{}))}}$A.RegisterExtension(_R,(e=>new mR(e)));const gR="KHR_materials_anisotropy";class vR{constructor(e){this.name=gR,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(gR)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadIridescencePropertiesAsync(n,s,i)),Promise.all(r).then((()=>{}))}))}_loadIridescencePropertiesAsync(e,t,i){var n,s;if(!(i instanceof O_))throw new Error(`${e}: Material type not supported`);const r=new Array;return i.anisotropy.isEnabled=!0,i.anisotropy.intensity=null!==(n=t.anisotropyStrength)&&void 0!==n?n:0,i.anisotropy.angle=null!==(s=t.anisotropyRotation)&&void 0!==s?s:0,t.anisotropyTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/anisotropyTexture`,t.anisotropyTexture,(e=>{e.name=`${i.name} (Anisotropy Intensity)`,i.anisotropy.texture=e}))),Promise.all(r).then((()=>{}))}}$A.RegisterExtension(gR,(e=>new vR(e)));const TR="KHR_materials_emissive_strength";class SR{constructor(e){this.name=TR,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(TR)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>this._loader.loadMaterialPropertiesAsync(e,t,i).then((()=>{this._loadEmissiveProperties(n,s,i)}))))}_loadEmissiveProperties(e,t,i){if(!(i instanceof O_))throw new Error(`${e}: Material type not supported`);void 0!==t.emissiveStrength&&i.emissiveColor.scaleToRef(t.emissiveStrength,i.emissiveColor)}}$A.RegisterExtension(TR,(e=>new SR(e)));const ER="KHR_materials_sheen";class xR{constructor(e){this.name=ER,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(ER)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadSheenPropertiesAsync(n,s,i)),Promise.all(r).then((()=>{}))}))}_loadSheenPropertiesAsync(e,t,i){if(!(i instanceof O_))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=a.Wo.FromArray(t.sheenColorFactor):i.sheen.color=a.Wo.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((()=>{}))}}$A.RegisterExtension(ER,(e=>new xR(e)));const bR="KHR_materials_specular";class CR{constructor(e){this.name=bR,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(bR)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadSpecularPropertiesAsync(n,s,i)),Promise.all(r).then((()=>{}))}))}_loadSpecularPropertiesAsync(e,t,i){if(!(i instanceof O_))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=a.Wo.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((()=>{}))}}$A.RegisterExtension(bR,(e=>new CR(e)));const yR="KHR_materials_ior";class AR{constructor(e){this.name=yR,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(yR)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadIorPropertiesAsync(n,s,i)),Promise.all(r).then((()=>{}))}))}_loadIorPropertiesAsync(e,t,i){if(!(i instanceof O_))throw new Error(`${e}: Material type not supported`);return void 0!==t.ior?i.indexOfRefraction=t.ior:i.indexOfRefraction=AR._DEFAULT_IOR,Promise.resolve()}}AR._DEFAULT_IOR=1.5,$A.RegisterExtension(yR,(e=>new AR(e)));const RR="KHR_materials_variants";class PR{constructor(e){this.name=RR,this._loader=e,this.enabled=this._loader.isExtensionUsed(RR)}dispose(){this._loader=null}static GetAvailableVariants(e){const t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(e){return PR.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 ${RR} extension`);const n=e=>{const t=i.variants[e];if(t)for(const i of t)i.mesh.material=i.material};if(t instanceof Array)for(const s of t)n(s);else n(t);i.lastSelected=t}selectVariant(e,t){return PR.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 ${RR} extension`);for(const i of t.original)i.mesh.material=i.material;t.lastSelected=null}reset(e){return PR.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 ${RR} extension`);return t.lastSelected}getLastSelectedVariant(e){return PR.GetLastSelectedVariant(e)}static _GetExtensionMetadata(e){var t,i;return(null===(i=null===(t=null==e?void 0:e._internalMetadata)||void 0===t?void 0:t.gltf)||void 0===i?void 0:i[RR])||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,s,r){return $A.LoadExtensionAsync(e,s,this.name,((o,a)=>{const l=new Array;return l.push(this._loader._loadMeshPrimitiveAsync(e,t,i,n,s,(t=>{if(r(t),t instanceof ee.Kj){const i=$A._GetDrawMode(e,s.mode),n=this._loader.rootBabylonMesh,r=n?n._internalMetadata=n._internalMetadata||{}:{},h=r.gltf=r.gltf||{},c=h[RR]=h[RR]||{lastSelected:null,original:[],variants:{}};c.original.push({mesh:t,material:t.material});for(let e=0;e{for(let i=0;i{const i=e;let s=null,r=i;do{if(r=r.parent,!r)return;s=PR._GetExtensionMetadata(r)}while(null===s);if(n&&s===PR._GetExtensionMetadata(n)){r._internalMetadata={};for(const e in n._internalMetadata)r._internalMetadata[e]=n._internalMetadata[e];r._internalMetadata.gltf=[];for(const e in n._internalMetadata.gltf)r._internalMetadata.gltf[e]=n._internalMetadata.gltf[e];r._internalMetadata.gltf[RR]={lastSelected:null,original:[],variants:{}};for(const e of s.original)r._internalMetadata.gltf[RR].original.push({mesh:e.mesh,material:e.material});for(const e in s.variants)if(Object.prototype.hasOwnProperty.call(s.variants,e)){r._internalMetadata.gltf[RR].variants[e]=[];for(const t of s.variants[e])r._internalMetadata.gltf[RR].variants[e].push({mesh:t.mesh,material:t.material})}s=r._internalMetadata.gltf[RR]}for(const n of s.original)n.mesh===t&&(n.mesh=i);for(const n of s.variants[o.name])n.mesh===t&&(n.mesh=i)}))}})))}}}))),Promise.all(l).then((([e])=>e))}))}}$A.RegisterExtension(RR,(e=>new PR(e)));class IR{static _GetDefaultOptions(){return{renderSize:1024,samples:4,lodGenerationScale:1,lodGenerationOffset:-4,renderTargetTextureType:vh.TEXTURETYPE_HALF_FLOAT,generateMipmaps:!0}}constructor(e,t){this._opaqueRenderTarget=null,this._opaqueMeshesCache=[],this._transparentMeshesCache=[],this._materialObservers={},this._options={...IR._GetDefaultOptions(),...e},this._scene=t,this._scene._transmissionHelper=this,this.onErrorObservable=new r.y$,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 O_&&e.subSurface.isRefractionEnabled)}_addMesh(e){this._materialObservers[e.uniqueId]=e.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this)),se.w1.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 O_&&(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)}_setupRenderTargets(){var e,t;let i,n;this._opaqueRenderTarget&&this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=new Ci("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=null!==(t=null===(e=this._options.clearColor)||void 0===e?void 0:e.clone())&&void 0!==t?t: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.onBeforeBindObservable.add((e=>{n=this._scene.environmentIntensity,this._scene.environmentIntensity=1,i=this._scene.imageProcessingConfiguration.applyByPostProcess,this._options.clearColor?e.clearColor.copyFrom(this._options.clearColor):this._scene.clearColor.toLinearSpaceToRef(e.clearColor,this._scene.getEngine().useExactSrgbConversions),this._scene.imageProcessingConfiguration._applyByPostProcess=!0})),this._opaqueRenderTarget.onAfterUnbindObservable.add((()=>{this._scene.environmentIntensity=n,this._scene.imageProcessingConfiguration._applyByPostProcess=i})),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 MR="KHR_materials_transmission";class OR{constructor(e){this.name=MR,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed(MR),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadTransparentPropertiesAsync(n,t,i,s)),Promise.all(r).then((()=>{}))}))}_loadTransparentPropertiesAsync(e,t,i,n){if(!(i instanceof O_))throw new Error(`${e}: Material type not supported`);const s=i;if(s.subSurface.isRefractionEnabled=!0,s.subSurface.volumeIndexOfRefraction=1,s.subSurface.useAlbedoToTintRefraction=!0,void 0===n.transmissionFactor)return s.subSurface.refractionIntensity=0,s.subSurface.isRefractionEnabled=!1,Promise.resolve();{s.subSurface.refractionIntensity=n.transmissionFactor;const e=s.getScene();s.subSurface.refractionIntensity&&!e._transmissionHelper&&new IR({},s.getScene())}return s.subSurface.minimumThickness=0,s.subSurface.maximumThickness=0,n.transmissionTexture?(n.transmissionTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/transmissionTexture`,n.transmissionTexture,void 0).then((e=>{s.subSurface.refractionIntensityTexture=e,s.subSurface.useGltfStyleTextures=!0}))):Promise.resolve()}}$A.RegisterExtension(MR,(e=>new OR(e)));const DR="KHR_materials_translucency";class NR{constructor(e){this.name=DR,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(DR),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadTranslucentPropertiesAsync(n,t,i,s)),Promise.all(r).then((()=>{}))}))}_loadTranslucentPropertiesAsync(e,t,i,n){if(!(i instanceof O_))throw new Error(`${e}: Material type not supported`);const s=i;return s.subSurface.isTranslucencyEnabled=!0,s.subSurface.volumeIndexOfRefraction=1,s.subSurface.minimumThickness=0,s.subSurface.maximumThickness=0,s.subSurface.useAlbedoToTintTranslucency=!0,void 0===n.translucencyFactor?(s.subSurface.translucencyIntensity=0,s.subSurface.isTranslucencyEnabled=!1,Promise.resolve()):(s.subSurface.translucencyIntensity=n.translucencyFactor,n.translucencyTexture?(n.translucencyTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/translucencyTexture`,n.translucencyTexture).then((e=>{s.subSurface.translucencyIntensityTexture=e}))):Promise.resolve())}}$A.RegisterExtension(DR,(e=>new NR(e)));const FR="KHR_materials_volume";class wR{constructor(e){this.name=FR,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(FR),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadVolumePropertiesAsync(n,t,i,s)),Promise.all(r).then((()=>{}))}))}_loadVolumePropertiesAsync(e,t,i,n){if(!(i instanceof O_))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 s=void 0!==n.attenuationDistance?n.attenuationDistance:Number.MAX_VALUE;return i.subSurface.tintColorAtDistance=s,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()}}$A.RegisterExtension(FR,(e=>new wR(e)));const LR="KHR_mesh_quantization";class BR{constructor(e){this.name=LR,this.enabled=e.isExtensionUsed(LR)}dispose(){}}$A.RegisterExtension(LR,(e=>new BR(e)));const UR="KHR_texture_basisu";class VR{constructor(e){this.name=UR,this._loader=e,this.enabled=e.isExtensionUsed(UR)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=null==t.sampler?$A.DefaultSampler:qA.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=qA.Get(`${n}/source`,this._loader.gltf.images,s.source);return this._loader._createTextureAsync(e,r,o,(e=>{i(e)}),t._textureInfo.nonColorData?{useRGBAIfASTCBC7NotAvailableWhenUASTC:!0}:void 0,!t._textureInfo.nonColorData)}))}}$A.RegisterExtension(UR,(e=>new VR(e)));const kR="KHR_texture_transform";class GR{constructor(e){this.name=kR,this._loader=e,this.enabled=this._loader.isExtensionUsed(kR)}dispose(){this._loader=null}loadTextureInfoAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>this._loader.loadTextureInfoAsync(e,t,(e=>{if(!(e instanceof Le))throw new Error(`${n}: Texture type not supported`);s.offset&&(e.uOffset=s.offset[0],e.vOffset=s.offset[1]),e.uRotationCenter=0,e.vRotationCenter=0,s.rotation&&(e.wAng=-s.rotation),s.scale&&(e.uScale=s.scale[0],e.vScale=s.scale[1]),null!=s.texCoord&&(e.coordinatesIndex=s.texCoord),i(e)}))))}}$A.RegisterExtension(kR,(e=>new GR(e)));const zR="KHR_xmp_json_ld";class WR{constructor(e){this.name=zR,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed(zR)}dispose(){this._loader=null}onLoading(){var e,t,i;if(null===this._loader.rootBabylonMesh)return;const n=null===(e=this._loader.gltf.extensions)||void 0===e?void 0:e.KHR_xmp_json_ld,s=null===(i=null===(t=this._loader.gltf.asset)||void 0===t?void 0:t.extensions)||void 0===i?void 0:i.KHR_xmp_json_ld;if(n&&s){const e=+s.packet;n.packets&&e2)),new QR(A.ANIMATIONTYPE_FLOAT,`${e}.vScale`,jR,(()=>2))],offset:[new QR(A.ANIMATIONTYPE_FLOAT,`${e}.uOffset`,XR,(()=>2)),new QR(A.ANIMATIONTYPE_FLOAT,`${e}.vOffset`,jR,(()=>2))],rotation:[new QR(A.ANIMATIONTYPE_FLOAT,`${e}.wAng`,YR,(()=>1))]}}$A.RegisterExtension(zR,(e=>new WR(e)));class $R extends XA{buildAnimations(e,t,i,n,s){s(e._babylonCamera,this._buildAnimation(t,i,n))}}class QR extends XA{buildAnimations(e,t,i,n,s){for(const r in e._data)s(e._data[r].babylonMaterial,this._buildAnimation(t,i,n))}}class ZR extends XA{buildAnimations(e,t,i,n,s){s(e._babylonLight,this._buildAnimation(t,i,n))}}const JR={__array__:{__target__:!0,...jA}},eP={__array__:{__target__:!0,orthographic:{xmag:[new $R(A.ANIMATIONTYPE_FLOAT,"orthoLeft",YR,(()=>1)),new $R(A.ANIMATIONTYPE_FLOAT,"orthoRight",jR,(()=>1))],ymag:[new $R(A.ANIMATIONTYPE_FLOAT,"orthoBottom",YR,(()=>1)),new $R(A.ANIMATIONTYPE_FLOAT,"orthoTop",jR,(()=>1))],zfar:[new $R(A.ANIMATIONTYPE_FLOAT,"maxZ",XR,(()=>1))],znear:[new $R(A.ANIMATIONTYPE_FLOAT,"minZ",XR,(()=>1))]},perspective:{yfov:[new $R(A.ANIMATIONTYPE_FLOAT,"fov",XR,(()=>1))],zfar:[new $R(A.ANIMATIONTYPE_FLOAT,"maxZ",XR,(()=>1))],znear:[new $R(A.ANIMATIONTYPE_FLOAT,"minZ",XR,(()=>1))]}}},tP={nodes:JR,materials:{__array__:{__target__:!0,pbrMetallicRoughness:{baseColorFactor:[new QR(A.ANIMATIONTYPE_COLOR3,"albedoColor",HR,(()=>4)),new QR(A.ANIMATIONTYPE_FLOAT,"alpha",(function(e,t,i,n){return t[i+3]*n}),(()=>4))],metallicFactor:[new QR(A.ANIMATIONTYPE_FLOAT,"metallic",XR,(()=>1))],roughnessFactor:[new QR(A.ANIMATIONTYPE_FLOAT,"roughness",XR,(()=>1))],baseColorTexture:{extensions:{KHR_texture_transform:qR("albedoTexture")}}},emissiveFactor:[new QR(A.ANIMATIONTYPE_COLOR3,"emissiveColor",HR,(()=>3))],normalTexture:{scale:[new QR(A.ANIMATIONTYPE_FLOAT,"bumpTexture.level",XR,(()=>1))]},occlusionTexture:{strength:[new QR(A.ANIMATIONTYPE_FLOAT,"ambientTextureStrength",XR,(()=>1))],extensions:{KHR_texture_transform:qR("ambientTexture")}},emissiveTexture:{extensions:{KHR_texture_transform:qR("emissiveTexture")}},extensions:{KHR_materials_ior:{ior:[new QR(A.ANIMATIONTYPE_FLOAT,"indexOfRefraction",XR,(()=>1))]},KHR_materials_clearcoat:{clearcoatFactor:[new QR(A.ANIMATIONTYPE_FLOAT,"clearCoat.intensity",XR,(()=>1))],clearcoatRoughnessFactor:[new QR(A.ANIMATIONTYPE_FLOAT,"clearCoat.roughness",XR,(()=>1))]},KHR_materials_sheen:{sheenColorFactor:[new QR(A.ANIMATIONTYPE_COLOR3,"sheen.color",HR,(()=>3))],sheenRoughnessFactor:[new QR(A.ANIMATIONTYPE_FLOAT,"sheen.roughness",XR,(()=>1))]},KHR_materials_specular:{specularFactor:[new QR(A.ANIMATIONTYPE_FLOAT,"metallicF0Factor",XR,(()=>1))],specularColorFactor:[new QR(A.ANIMATIONTYPE_COLOR3,"metallicReflectanceColor",HR,(()=>3))]},KHR_materials_emissive_strength:{emissiveStrength:[new QR(A.ANIMATIONTYPE_FLOAT,"emissiveIntensity",XR,(()=>1))]},KHR_materials_transmission:{transmissionFactor:[new QR(A.ANIMATIONTYPE_FLOAT,"subSurface.refractionIntensity",XR,(()=>1))]},KHR_materials_volume:{attenuationColor:[new QR(A.ANIMATIONTYPE_COLOR3,"subSurface.tintColor",HR,(()=>3))],attenuationDistance:[new QR(A.ANIMATIONTYPE_FLOAT,"subSurface.tintColorAtDistance",XR,(()=>1))],thicknessFactor:[new QR(A.ANIMATIONTYPE_FLOAT,"subSurface.maximumThickness",XR,(()=>1))]},KHR_materials_iridescence:{iridescenceFactor:[new QR(A.ANIMATIONTYPE_FLOAT,"iridescence.intensity",XR,(()=>1))],iridescenceIor:[new QR(A.ANIMATIONTYPE_FLOAT,"iridescence.indexOfRefraction",XR,(()=>1))],iridescenceThicknessMinimum:[new QR(A.ANIMATIONTYPE_FLOAT,"iridescence.minimumThickness",XR,(()=>1))],iridescenceThicknessMaximum:[new QR(A.ANIMATIONTYPE_FLOAT,"iridescence.maximumThickness",XR,(()=>1))]},KHR_materials_anisotropy:{anisotropyStrength:[new QR(A.ANIMATIONTYPE_FLOAT,"anisotropy.intensity",XR,(()=>1))],anisotropyRotation:[new QR(A.ANIMATIONTYPE_FLOAT,"anisotropy.angle",XR,(()=>1))]}}}},cameras:eP,extensions:{KHR_lights_punctual:{lights:{__array__:{__target__:!0,color:[new ZR(A.ANIMATIONTYPE_COLOR3,"diffuse",HR,(()=>3))],intensity:[new ZR(A.ANIMATIONTYPE_FLOAT,"intensity",XR,(()=>1))],range:[new ZR(A.ANIMATIONTYPE_FLOAT,"range",XR,(()=>1))],spot:{innerConeAngle:[new ZR(A.ANIMATIONTYPE_FLOAT,"innerAngle",KR,(()=>1))],outerConeAngle:[new ZR(A.ANIMATIONTYPE_FLOAT,"angle",KR,(()=>1))]}}}}}},iP="KHR_animation_pointer";class nP{constructor(e){this.name=iP,this._loader=e}get enabled(){return this._loader.isExtensionUsed(iP)}dispose(){this._loader=null}_loadAnimationChannelAsync(e,t,i,n,s){var r;const o=null===(r=n.target.extensions)||void 0===r?void 0:r.KHR_animation_pointer;if(!o)return null;"pointer"!==n.target.path&&p.Y.Warn(`${e}/target/path: Value (${n.target.path}) must be (pointer) when using the ${this.name} extension`),null!=n.target.node&&p.Y.Warn(`${e}/target/node: Value (${n.target.node}) must not be present when using the ${this.name} extension`);const a=`${e}/extensions/${this.name}`,l=o.pointer;if(!l)throw new Error(`${a}: Pointer is missing`);const h=this._parseAnimationPointer(`${a}/pointer`,l);return h?this._loader._loadAnimationChannelFromTargetInfoAsync(e,t,i,n,h,s):(p.Y.Warn(`${a}/pointer: Invalid pointer (${l}) skipped`),null)}_parseAnimationPointer(e,t){if(!t.startsWith("/"))return p.Y.Warn(`${e}: Value (${t}) must start with a slash`),null;const i=t.split("/");i.shift();let n,s=tP,r=this._loader.gltf;for(const o of i){if(s.__array__)s=s.__array__;else if(s=s[o],!s)return null;r=r&&r[o],s.__target__&&(n=r)}return n&&Array.isArray(s)?{target:n,properties:s}:null}}$A.RegisterExtension(iP,(e=>new nP(e)));const sP="MSFT_audio_emitter";class rP{constructor(e){this.name=sP,this._loader=e,this.enabled=this._loader.isExtensionUsed(sP)}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,qA.Assign(this._clips),qA.Assign(this._emitters)}}loadSceneAsync(e,t){return $A.LoadExtensionAsync(e,t,this.name,((i,n)=>{const s=new Array;s.push(this._loader.loadSceneAsync(e,t));for(const e of n.emitters){const t=qA.Get(`${i}/emitters`,this._emitters,e);if(null!=t.refDistance||null!=t.maxDistance||null!=t.rolloffFactor||null!=t.distanceModel||null!=t.innerAngle||null!=t.outerAngle)throw new Error(`${i}: Direction or Distance properties are not allowed on emitters attached to a scene`);s.push(this._loadEmitterAsync(`${i}/emitters/${t.index}`,t))}return Promise.all(s).then((()=>{}))}))}loadNodeAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((e,n)=>{const s=new Array;return this._loader.loadNodeAsync(e,t,(t=>{for(const i of n.emitters){const n=qA.Get(`${e}/emitters`,this._emitters,i);s.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(o.P.Forward()),e.setDirectionalCone(2*se.w1.ToDegrees(null==n.innerAngle?Math.PI:n.innerAngle),2*se.w1.ToDegrees(null==n.outerAngle?Math.PI:n.outerAngle),0))})))}i(t)})).then((e=>Promise.all(s).then((()=>e))))}))}loadAnimationAsync(e,t){return $A.LoadExtensionAsync(e,t,this.name,((i,n)=>this._loader.loadAnimationAsync(e,t).then((s=>{const r=new Array;qA.Assign(n.events);for(const o of n.events)r.push(this._loadAnimationEventAsync(`${i}/events/${o.index}`,e,t,o,s));return Promise.all(r).then((()=>s))}))))}_loadClipAsync(e,t){if(t._objectURL)return t._objectURL;let i;if(t.uri)i=this._loader.loadUriAsync(e,t,t.uri);else{const n=qA.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{const s=t._babylonSounds[r]=new ve(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 s=Promise.all(e).then((()=>{const e=t.clips.map((e=>e.weight||1)),i=new xe(t.loop||!1,t._babylonSounds,e);t.innerAngle&&(i.directionalConeInnerAngle=2*se.w1.ToDegrees(t.innerAngle)),t.outerAngle&&(i.directionalConeOuterAngle=2*se.w1.ToDegrees(t.outerAngle)),t.volume&&(i.volume=t.volume),t._babylonData.sound=i}));t._babylonData={loaded:s}}return t._babylonData.loaded}_getEventAction(e,t,i,n,s){switch(i){case"play":return e=>{const i=(s||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,s){if(0==s.targetedAnimations.length)return Promise.resolve();const r=s.targetedAnimations[0],o=n.emitter,a=qA.Get(`/extensions/${this.name}/emitters`,this._emitters,o);return this._loadEmitterAsync(e,a).then((()=>{const t=a._babylonData.sound;if(t){const i=new $(n.time,this._getEventAction(e,t,n.action,n.time,n.startOffset));r.animation.addEvent(i),s.onAnimationGroupEndObservable.add((()=>{t.stop()})),s.onAnimationGroupPauseObservable.add((()=>{t.pause()}))}}))}}$A.RegisterExtension(sP,(e=>new rP(e)));const oP="MSFT_lod";class aP{constructor(e){this.name=oP,this.order=100,this.maxLODsToLoad=10,this.onNodeLODsLoadedObservable=new r.y$,this.onMaterialLODsLoadedObservable=new r.y$,this._bufferLODs=new Array,this._nodeIndexLOD=null,this._nodeSignalLODs=new Array,this._nodePromiseLODs=new Array,this._nodeBufferLODs=new Array,this._materialIndexLOD=null,this._materialSignalLODs=new Array,this._materialPromiseLODs=new Array,this._materialBufferLODs=new Array,this._loader=e,this.enabled=this._loader.isExtensionUsed(oP)}dispose(){this._loader=null,this._nodeIndexLOD=null,this._nodeSignalLODs.length=0,this._nodePromiseLODs.length=0,this._nodeBufferLODs.length=0,this._materialIndexLOD=null,this._materialSignalLODs.length=0,this._materialPromiseLODs.length=0,this._materialBufferLODs.length=0,this.onMaterialLODsLoadedObservable.clear(),this.onNodeLODsLoadedObservable.clear()}onReady(){for(let e=0;e{0!==e&&(this._loader.endPerformanceCounter(`Node LOD ${e}`),this._loader.log(`Loaded node LOD ${e}`)),this.onNodeLODsLoadedObservable.notifyObservers(e),e!==this._nodePromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Node LOD ${e+1}`),this._loadBufferLOD(this._nodeBufferLODs,e+1),this._nodeSignalLODs[e]&&this._nodeSignalLODs[e].resolve())}));this._loader._completePromises.push(t)}for(let e=0;e{0!==e&&(this._loader.endPerformanceCounter(`Material LOD ${e}`),this._loader.log(`Loaded material LOD ${e}`)),this.onMaterialLODsLoadedObservable.notifyObservers(e),e!==this._materialPromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Material LOD ${e+1}`),this._loadBufferLOD(this._materialBufferLODs,e+1),this._materialSignalLODs[e]&&this._materialSignalLODs[e].resolve())}));this._loader._completePromises.push(t)}}loadSceneAsync(e,t){const i=this._loader.loadSceneAsync(e,t);return this._loadBufferLOD(this._bufferLODs,0),i}loadNodeAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((e,n)=>{let s;const r=this._getLODs(e,t,this._loader.gltf.nodes,n.ids);this._loader.logOpen(`${e}`);for(let t=0;t{i(e),e.setEnabled(!1)},o=this._loader.loadNodeAsync(`/nodes/${e.index}`,e,n).then((e=>{if(0!==t){const e=r[t-1];e._babylonTransformNode&&(this._disposeTransformNode(e._babylonTransformNode),delete e._babylonTransformNode)}return e.setEnabled(!0),e}));this._nodePromiseLODs[t]=this._nodePromiseLODs[t]||[],0===t?s=o:(this._nodeIndexLOD=null,this._nodePromiseLODs[t].push(o))}return this._loader.logClose(),s}))}_loadMaterialAsync(e,t,i,n,s){return this._nodeIndexLOD?null:$A.LoadExtensionAsync(e,t,this.name,((e,r)=>{let o;const a=this._getLODs(e,t,this._loader.gltf.materials,r.ids);this._loader.logOpen(`${e}`);for(let t=0;t{0===t&&s(e)})).then((e=>{if(0!==t){s(e);const i=a[t-1]._data;i[n]&&(this._disposeMaterials([i[n].babylonMaterial]),delete i[n])}return e}));this._materialPromiseLODs[t]=this._materialPromiseLODs[t]||[],0===t?o=r:(this._materialIndexLOD=null,this._materialPromiseLODs[t].push(r))}return this._loader.logClose(),o}))}_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 wC,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 wC,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 s=i,r=s+n-1;let o=e[t];return o?(o.start=Math.min(o.start,s),o.end=Math.max(o.end,r)):(o={start:s,end:r,loaded:new wC},e[t]=o),o.loaded.promise.then((e=>new Uint8Array(e.buffer,e.byteOffset+i-o.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 s=new Array;for(let r=n.length-1;r>=0;r--)if(s.push(qA.Get(`${e}/ids/${n[r]}`,i,n[r])),s.length===this.maxLODsToLoad)return s;return s.push(t),s}_disposeTransformNode(e){const t=new Array,i=e.material;i&&t.push(i);for(const s of e.getChildMeshes())s.material&&t.push(s.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 i in t)for(const e of this._loader.babylonScene.materials)e.hasTexture(t[i])&&delete t[i];for(const i in t)t[i].dispose()}}$A.RegisterExtension(oP,(e=>new aP(e)));const lP="MSFT_minecraftMesh";class hP{constructor(e){this.name=lP,this._loader=e,this.enabled=this._loader.isExtensionUsed(lP)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtraAsync(e,t,this.name,((n,s)=>{if(s){if(!(i instanceof O_))throw new Error(`${n}: Material type not supported`);const s=this._loader.loadMaterialPropertiesAsync(e,t,i);return i.needAlphaBlending()&&(i.forceDepthWrite=!0,i.separateCullingPass=!0),i.backFaceCulling=i.forceDepthWrite,i.twoSidedLighting=!0,s}return null}))}}$A.RegisterExtension(lP,(e=>new hP(e)));const cP="MSFT_sRGBFactors";class dP{constructor(e){this.name=cP,this._loader=e,this.enabled=this._loader.isExtensionUsed(cP)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtraAsync(e,t,this.name,((n,s)=>{if(s){if(!(i instanceof O_))throw new Error(`${n}: Material type not supported`);const s=this._loader.loadMaterialPropertiesAsync(e,t,i),r=i.getScene().getEngine().useExactSrgbConversions;return i.albedoTexture||i.albedoColor.toLinearSpaceToRef(i.albedoColor,r),i.reflectivityTexture||i.reflectivityColor.toLinearSpaceToRef(i.reflectivityColor,r),s}return null}))}}$A.RegisterExtension(cP,(e=>new dP(e)));const uP="ExtrasAsMetadata";class pP{_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=uP,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}}let fP,_P,mP,gP;$A.RegisterExtension(uP,(e=>new pP(e)));const vP=async e=>{e.clearColor=a.HE.FromHexString("#000"),mP=new Ln("camera1",se.w1.ToRadians(0),se.w1.ToRadians(0),15,o.P.Zero(),e);const{meshes:t}=await ht.ImportMeshAsync("","buster_drone/","drone.gltf",e);gP=t[0],gP.scaling=new o.P(3,3,3),gP.alwaysSelectAsActiveMesh=!0,gP.enablePointerMoveEvents=!0,gP.isNearPickable=!0;const i=e.getEngine().getRenderingCanvas();mP.allowUpsideDown,mP.wheelDeltaPercentage=.01,mP.lowerRadiusLimit=8,mP.upperRadiusLimit=70,mP.setTarget(gP),mP.attachControl(i,!1);const n=new Os("light",new o.P(0,10,10),e),s=new Os("light2",new o.P(0,-10,10),e);n.intensity=2.5,s.intensity=1.5;const{animation:r,lastFrame:l}=(e=>{const t=20*e,i=new A("zoom","position",20,A.ANIMATIONTYPE_VECTOR3,A.ANIMATIONLOOPMODE_CONSTANT);return i.setKeys([{frame:0,value:new o.P(0,70,0)},{frame:t,value:new o.P(3,7,-15)}]),{animation:[i],lastFrame:t}})(4);e.beginDirectAnimation(mP,r,0,l,!1)};self.onmessage=async e=>{let{data:{canvas:t,width:i,height:n,dispose:s,wheel:r,x:o,y:a}}=e;if(t){const e=(e=>{let{antialias:t,engineOptions:i,adaptToDeviceRatio:n,sceneOptions:s,onRender:r,onSceneReady:o,canvas:a}=e;const l=new fe.D(a,t,i,n),h=new N.x(l,s);return h.isReady()?o(h):h.onReadyObservable.addOnce((e=>o(e))),l.runRenderLoop((()=>{"function"==typeof r&&r(h),h.render()})),{scene:h,canvas:a}})({antialias:!0,onSceneReady:vP,canvas:t});fP=e.scene,_P=e.canvas,self.postMessage("ready")}fP&&_P&&!t&&i&&n&&(_P.width=i,_P.height=n,fP.getEngine().resize(!0)),s&&fP&&fP.getEngine().dispose(),mP&&r&&(mP.radius=mP.radius+r*mP.wheelDeltaPercentage),fP&&void 0!==o&&void 0!==a&&(mP.alpha-=o/100,mP.beta-=a/100)}},9802:function(e,t,i){i.d(t,{O:function(){return n}});class n{constructor(){this.hoverCursor="",this.actions=new Array,this.isRecursive=!1}static get HasTriggers(){for(const e in n.Triggers)if(Object.prototype.hasOwnProperty.call(n.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(const e in n.Triggers)if(Object.prototype.hasOwnProperty.call(n.Triggers,e)){const t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(const t in n.Triggers)if(Object.prototype.hasOwnProperty.call(n.Triggers,t)){if(parseInt(t)===e)return!0}return!1}}n.Triggers={}},9372:function(e,t,i){i.d(t,{V:function(){return n}});class n{constructor(e,t,i,n,s,r){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=n,this.sourceEvent=s,this.additionalData=r}static CreateNew(e,t,i){const s=e.getScene();return new n(e,s.pointerX,s.pointerY,s.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,s){return new n(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,s)}static CreateNewFromScene(e,t){return new n(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,s){return new n(e,t.x,t.y,null,i,s)}}},2186:function(e,t,i){i.d(t,{l:function(){return s},o:function(){return r}});var n=i(1545);class s{constructor(e,t,i,s=0,r=!1,o=!1,a=!1,l){this._isAlreadyOwned=!1,e.getScene?this._engine=e.getScene().getEngine():this._engine=e,this._updatable=i,this._instanced=o,this._divisor=l||1,t instanceof n.h?(this._data=null,this._buffer=t):(this._data=t,this._buffer=null),this.byteStride=a?s:s*Float32Array.BYTES_PER_ELEMENT,r||this.create()}createVertexBuffer(e,t,i,n,s,o=!1,a){const l=o?t:t*Float32Array.BYTES_PER_ELEMENT,h=n?o?n:n*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new r(this._engine,this,e,this._updatable,!0,h,void 0===s?this._instanced:s,l,i,void 0,void 0,!0,this._divisor||a)}isUpdatable(){return this._updatable}getData(){return this._data}getBuffer(){return this._buffer}getStrideSize(){return this.byteStride/Float32Array.BYTES_PER_ELEMENT}create(e=null){!e&&this._buffer||(e=e||this._data)&&(this._buffer?this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e),this._data=e):this._updatable?(this._buffer=this._engine.createDynamicVertexBuffer(e),this._data=e):this._buffer=this._engine.createVertexBuffer(e))}_rebuild(){this._buffer=null,this.create(this._data)}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._buffer=null,this._data=null)}}class r{get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){const t=0!=e;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}constructor(e,t,i,n,o,a,l,h,c,d,u=!1,p=!1,f=1,_=!1){if(t instanceof s?(this._buffer=t,this._ownsBuffer=_):(this._buffer=new s(e,t,n,a,o,l,p),this._ownsBuffer=!0),this.uniqueId=r._Counter++,this._kind=i,null==d){const e=this.getData();this.type=r.FLOAT,e instanceof Int8Array?this.type=r.BYTE:e instanceof Uint8Array?this.type=r.UNSIGNED_BYTE:e instanceof Int16Array?this.type=r.SHORT:e instanceof Uint16Array?this.type=r.UNSIGNED_SHORT:e instanceof Int32Array?this.type=r.INT:e instanceof Uint32Array&&(this.type=r.UNSIGNED_INT)}else this.type=d;const m=r.GetTypeByteLength(this.type);p?(this._size=c||(a?a/m:r.DeduceStride(i)),this.byteStride=a||this._buffer.byteStride||this._size*m,this.byteOffset=h||0):(this._size=c||a||r.DeduceStride(i),this.byteStride=a?a*m:this._buffer.byteStride||this._size*m,this.byteOffset=(h||0)*m),this.normalized=u,this._instanced=void 0!==l&&l,this._instanceDivisor=l?f:0,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&&this._buffer._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){const i=this.getData();if(!i)return null;const n=this.getSize()*r.GetTypeByteLength(this.type),s=e*this.getSize();if(this.type!==r.FLOAT||this.byteStride!==n){const e=new Float32Array(s);return this.forEach(s,((t,i)=>e[i]=t)),e}if(!(i instanceof Array||i instanceof Float32Array)||0!==this.byteOffset||i.length!==s){if(i instanceof Array){const e=this.byteOffset/4;return i.slice(e,e+s)}if(i instanceof ArrayBuffer)return new Float32Array(i,this.byteOffset,s);{let e=i.byteOffset+this.byteOffset;if(t){const t=new Float32Array(s),n=new Float32Array(i.buffer,e,s);return t.set(n),t}const n=e%4;return n&&(e=Math.max(0,e-n)),new Float32Array(i.buffer,e,s)}}return t?i.slice():i}getBuffer(){return this._buffer.getBuffer()}getStrideSize(){return this.byteStride/r.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/r.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*r.GetTypeByteLength(this.type):this._size}getIsInstanced(){return this._instanced}getInstanceDivisor(){return this._instanceDivisor}create(e){this._buffer.create(e)}update(e){this._buffer.update(e)}updateDirectly(e,t,i=!1){this._buffer.updateDirectly(e,t,void 0,i)}dispose(){this._ownsBuffer&&this._buffer.dispose()}forEach(e,t){r.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}static DeduceStride(e){switch(e){case r.UVKind:case r.UV2Kind:case r.UV3Kind:case r.UV4Kind:case r.UV5Kind:case r.UV6Kind:return 2;case r.NormalKind:case r.PositionKind:return 3;case r.ColorKind:case r.MatricesIndicesKind:case r.MatricesIndicesExtraKind:case r.MatricesWeightsKind:case r.MatricesWeightsExtraKind:case r.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetTypeByteLength(e){switch(e){case r.BYTE:case r.UNSIGNED_BYTE:return 1;case r.SHORT:case r.UNSIGNED_SHORT:return 2;case r.INT:case r.UNSIGNED_INT:case r.FLOAT:return 4;default:throw new Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,n,s,o,a,l){if(e instanceof Array){let s=t/4;const r=i/4;for(let t=0;t-1?(c.Y.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 l.y3.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()||(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){var t,i,n,s,r,o,a,h;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 c=this.getEngine(),d=this.getScene(),u=c.useReverseDepthBuffer;if(this.mode===_.PERSPECTIVE_CAMERA){let e;this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=c.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1),e=d.useRightHandedSystem?l.y3.PerspectiveFovRHToRef:l.y3.PerspectiveFovLHToRef,e(this.fov,c.getAspectRatio(this),u?this.maxZ:this.minZ,u?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===_.FOVMODE_VERTICAL_FIXED,c.isNDCHalfZRange,this.projectionPlaneTilt,u)}else{const e=c.getRenderWidth()/2,p=c.getRenderHeight()/2;d.useRightHandedSystem?l.y3.OrthoOffCenterRHToRef(null!==(t=this.orthoLeft)&&void 0!==t?t:-e,null!==(i=this.orthoRight)&&void 0!==i?i:e,null!==(n=this.orthoBottom)&&void 0!==n?n:-p,null!==(s=this.orthoTop)&&void 0!==s?s:p,u?this.maxZ:this.minZ,u?this.minZ:this.maxZ,this._projectionMatrix,c.isNDCHalfZRange):l.y3.OrthoOffCenterLHToRef(null!==(r=this.orthoLeft)&&void 0!==r?r:-e,null!==(o=this.orthoRight)&&void 0!==o?o:e,null!==(a=this.orthoBottom)&&void 0!==a?a:-p,null!==(h=this.orthoTop)&&void 0!==h?h:p,u?this.maxZ:this.minZ,u?this.minZ:this.maxZ,this._projectionMatrix,c.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.renderWidth=c.getRenderWidth(),this._cache.renderHeight=c.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix}getTransformationMatrix(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?f.i.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=f.i.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),t&&this.rigCameras.length>0){let t=!1;return this.rigCameras.forEach((i=>{i._updateFrustumPlanes(),t=t||e.isInFrustum(i._frustumPlanes)})),t}return e.isInFrustum(this._frustumPlanes)}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw(0,u.S)("Ray")}getForwardRayToRef(e,t=100,i,n){throw(0,u.S)("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!==_.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=o.w1.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==_.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 l.y3.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}_updateCameraRotationMatrix(){}_updateWebVRCameraRotationMatrix(){}_getWebVRProjectionMatrix(){return l.y3.Identity()}_getWebVRViewMatrix(){return l.y3.Identity()}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,"interaxialDistance"===e&&(this._cameraRigParams.stereoHalfAngle=o.w1.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;e_._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,n=_.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),r=s.p4.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=l.P.FromArray(e.upVector)),r.setPosition&&(r.position.copyFromFloats(0,0,0),r.setPosition(l.P.FromArray(e.position))),e.target&&r.setTarget&&r.setTarget(l.P.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{throw(0,u.S)("UniversalCamera")},_.PERSPECTIVE_CAMERA=0,_.ORTHOGRAPHIC_CAMERA=1,_.FOVMODE_VERTICAL_FIXED=0,_.FOVMODE_HORIZONTAL_FIXED=1,_.RIG_MODE_NONE=0,_.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,_.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,_.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,_.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,_.RIG_MODE_STEREOSCOPIC_INTERLACED=14,_.RIG_MODE_VR=20,_.RIG_MODE_WEBVR=21,_.RIG_MODE_CUSTOM=22,_.ForceAttachControlToAlwaysPreventDefault=!1,(0,n.gn)([(0,s.hd)("position")],_.prototype,"_position",void 0),(0,n.gn)([(0,s.hd)("upVector")],_.prototype,"_upVector",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"orthoLeft",null),(0,n.gn)([(0,s.qC)()],_.prototype,"orthoRight",null),(0,n.gn)([(0,s.qC)()],_.prototype,"orthoBottom",null),(0,n.gn)([(0,s.qC)()],_.prototype,"orthoTop",null),(0,n.gn)([(0,s.qC)()],_.prototype,"fov",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"projectionPlaneTilt",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"minZ",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"maxZ",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"inertia",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"mode",null),(0,n.gn)([(0,s.qC)()],_.prototype,"layerMask",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"fovMode",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"cameraRigMode",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"interaxialDistance",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"isStereoscopicSideBySide",void 0)},3573:function(e,t,i){i.d(t,{c:function(){return n}});class n{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}},7901:function(e,t,i){i.d(t,{a:function(){return s}});var n=i(5412);class s{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new n.P(0,0,0),this._diffPositionForCollisions=new n.P(0,0,0),this._collisionResponse=!0}}},318:function(e,t,i){i.d(t,{p:function(){return r}});var n=i(5412),s=i(2186);class r{constructor(){this.hit=!1,this.distance=0,this.pickedPoint=null,this.pickedMesh=null,this.bu=0,this.bv=0,this.faceId=-1,this.subMeshFaceId=-1,this.subMeshId=0,this.pickedSprite=null,this.thinInstanceIndex=-1,this.ray=null,this.originMesh=null,this.aimTransform=null,this.gripTransform=null}getNormal(e=!1,t=!0){if(!this.pickedMesh||t&&!this.pickedMesh.isVerticesDataPresent(s.o.NormalKind))return null;let i,r=this.pickedMesh.getIndices();0===(null==r?void 0:r.length)&&(r=null);const o=n.jp.Vector3[0],a=n.jp.Vector3[1],l=n.jp.Vector3[2];if(t){const e=this.pickedMesh.getVerticesData(s.o.NormalKind);let t=r?n.P.FromArrayToRef(e,3*r[3*this.faceId],o):o.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),h=r?n.P.FromArrayToRef(e,3*r[3*this.faceId+1],a):a.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),c=r?n.P.FromArrayToRef(e,3*r[3*this.faceId+2],l):l.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]);t=t.scale(this.bu),h=h.scale(this.bv),c=c.scale(1-this.bu-this.bv),i=new n.P(t.x+h.x+c.x,t.y+h.y+c.y,t.z+h.z+c.z)}else{const e=this.pickedMesh.getVerticesData(s.o.PositionKind),t=r?n.P.FromArrayToRef(e,3*r[3*this.faceId],o):o.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),h=r?n.P.FromArrayToRef(e,3*r[3*this.faceId+1],a):a.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),c=r?n.P.FromArrayToRef(e,3*r[3*this.faceId+2],l):l.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]),d=t.subtract(h),u=c.subtract(h);i=n.P.Cross(d,u)}const h=(e,t)=>{let i=e.getWorldMatrix();e.nonUniformScaling&&(n.jp.Matrix[0].copyFrom(i),i=n.jp.Matrix[0],i.setTranslationFromFloats(0,0,0),i.invert(),i.transposeToRef(n.jp.Matrix[1]),i=n.jp.Matrix[1]),n.P.TransformNormalToRef(t,i,t)};if(e&&h(this.pickedMesh,i),this.ray){const t=n.jp.Vector3[0].copyFrom(i);e||h(this.pickedMesh,t),n.P.Dot(t,this.ray.direction)>0&&i.negateInPlace()}return i.normalize(),i}getTextureCoordinates(e=s.o.UVKind){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e))return null;const t=this.pickedMesh.getIndices();if(!t)return null;const i=this.pickedMesh.getVerticesData(e);if(!i)return null;let r=n.FM.FromArray(i,2*t[3*this.faceId]),o=n.FM.FromArray(i,2*t[3*this.faceId+1]),a=n.FM.FromArray(i,2*t[3*this.faceId+2]);return r=r.scale(this.bu),o=o.scale(this.bv),a=a.scale(1-this.bu-this.bv),new n.FM(r.x+o.x+a.x,r.y+o.y+a.y)}}},6629:function(e,t,i){i.d(t,{e:function(){return n}});class n{}n.UseOpenGLOrientationForUV=!1},3773:function(e,t,i){i.d(t,{k:function(){return o}});var n=i(2554),s=i(5412),r=i(4551);class o{constructor(e,t,i){this.vectors=n.B.BuildArray(8,s.P.Zero),this.center=s.P.Zero(),this.centerWorld=s.P.Zero(),this.extendSize=s.P.Zero(),this.extendSizeWorld=s.P.Zero(),this.directions=n.B.BuildArray(3,s.P.Zero),this.vectorsWorld=n.B.BuildArray(8,s.P.Zero),this.minimumWorld=s.P.Zero(),this.maximumWorld=s.P.Zero(),this.minimum=s.P.Zero(),this.maximum=s.P.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const n=e.x,r=e.y,o=e.z,a=t.x,l=t.y,h=t.z,c=this.vectors;this.minimum.copyFromFloats(n,r,o),this.maximum.copyFromFloats(a,l,h),c[0].copyFromFloats(n,r,o),c[1].copyFromFloats(a,l,h),c[2].copyFromFloats(a,r,o),c[3].copyFromFloats(n,l,o),c[4].copyFromFloats(n,r,h),c[5].copyFromFloats(a,l,o),c[6].copyFromFloats(n,l,h),c[7].copyFromFloats(a,r,h),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||s.y3.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=o._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),n=i.length();i.normalizeFromLength(n);const s=n*e,r=i.scaleInPlace(.5*s),a=this.center.subtractToRef(r,t[1]),l=this.center.addToRef(r,t[2]);return this.reConstruct(a,l,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){const t=this.minimumWorld,i=this.maximumWorld,n=this.directions,r=this.vectorsWorld,o=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let e=0;e<8;++e)r[e].copyFrom(o[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];s.P.TransformCoordinatesToRef(o[n],e,a),t.minimizeInPlace(a),i.maximizeInPlace(a)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}s.P.FromArrayToRef(e.m,0,n[0]),s.P.FromArrayToRef(e.m,4,n[1]),s.P.FromArrayToRef(e.m,8,n[2]),this._worldMatrix=e}isInFrustum(e){return o.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return o.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,n=t.x,s=t.y,o=t.z,a=i.x,l=i.y,h=i.z,c=e.x,d=e.y,u=e.z,p=-r.kn;return!(a-cc-n)&&(!(l-dd-s)&&!(h-uu-o))}intersectsSphere(e){return o.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,n=this.maximumWorld,s=i.x,r=i.y,o=i.z,a=n.x,l=n.y,h=n.z,c=e.x,d=e.y,u=e.z,p=t.x,f=t.y,_=t.z;return!(ap)&&(!(lf)&&!(h_))}dispose(){var e,t;null===(e=this._drawWrapperFront)||void 0===e||e.dispose(),null===(t=this._drawWrapperBack)||void 0===t||t.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,n){const r=o._TmpVector3[0];s.P.ClampToRef(i,e,t,r);return s.P.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 s=t[i];for(let t=0;t<8;++t)if(s.dotCoordinate(e[t])>=0){n=!1;break}if(n)return!1}return!0}}o._TmpVector3=n.B.BuildArray(3,s.P.Zero)},2789:function(e,t,i){i.d(t,{j:function(){return d}});var n=i(2554),s=i(5412),r=i(3773),o=i(2897);const a={min:0,max:0},l={min:0,max:0},h=(e,t,i)=>{const n=s.P.Dot(t.centerWorld,e),r=Math.abs(s.P.Dot(t.directions[0],e))*t.extendSize.x+Math.abs(s.P.Dot(t.directions[1],e))*t.extendSize.y+Math.abs(s.P.Dot(t.directions[2],e))*t.extendSize.z;i.min=n-r,i.max=n+r},c=(e,t,i)=>(h(e,t,a),h(e,i,l),!(a.min>l.max||l.min>a.max));class d{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new r.k(e,t,i),this.boundingSphere=new o.K(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=d._TmpVector3[0].copyFrom(e).subtractInPlace(t),n=d._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=s.P.Minimize(this.minimum,e),i=s.P.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=s.jp.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=s.jp.Vector3[0];return s.P.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),s.P.TransformCoordinatesToRef(e.boundingBox.maximumWorld,t,i),this.encapsulate(i),this}scale(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this}isInFrustum(e,t=0){if((2===t||3===t)&&this.boundingSphere.isCenterInFrustum(e))return!0;if(!this.boundingSphere.isInFrustum(e))return!1;return!(1!==t&&3!==t)||this.boundingBox.isInFrustum(e)}get diagonalLength(){const e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,d._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(!o.K.Intersects(this.boundingSphere,e.boundingSphere))return!1;if(!r.k.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,n=e.boundingBox;return!!c(i.directions[0],i,n)&&(!!c(i.directions[1],i,n)&&(!!c(i.directions[2],i,n)&&(!!c(n.directions[0],i,n)&&(!!c(n.directions[1],i,n)&&(!!c(n.directions[2],i,n)&&(!!c(s.P.Cross(i.directions[0],n.directions[0]),i,n)&&(!!c(s.P.Cross(i.directions[0],n.directions[1]),i,n)&&(!!c(s.P.Cross(i.directions[0],n.directions[2]),i,n)&&(!!c(s.P.Cross(i.directions[1],n.directions[0]),i,n)&&(!!c(s.P.Cross(i.directions[1],n.directions[1]),i,n)&&(!!c(s.P.Cross(i.directions[1],n.directions[2]),i,n)&&(!!c(s.P.Cross(i.directions[2],n.directions[0]),i,n)&&(!!c(s.P.Cross(i.directions[2],n.directions[1]),i,n)&&!!c(s.P.Cross(i.directions[2],n.directions[2]),i,n))))))))))))))}}d._TmpVector3=n.B.BuildArray(2,s.P.Zero)},2897:function(e,t,i){i.d(t,{K:function(){return r}});var n=i(2554),s=i(5412);class r{constructor(e,t,i){this.center=s.P.Zero(),this.centerWorld=s.P.Zero(),this.minimum=s.P.Zero(),this.maximum=s.P.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const n=s.P.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*n,this._update(i||s.y3.IdentityReadOnly)}scale(e){const t=this.radius*e,i=r._TmpVector3,n=i[0].setAll(t),s=this.center.subtractToRef(n,i[1]),o=this.center.addToRef(n,i[2]);return this.reConstruct(s,o,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{s.P.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=r._TmpVector3[0];s.P.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=s.P.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld=n.Fz.LeftClick&&i<=n.Fz.RightClick&&(l.type=1===s?"pointerdown":"pointerup",l.button=i-2),l}static _CreateWheelEvent(e,t,i,s,o,a){const l=this._CreateMouseEvent(e,t,i,s,o,a);switch(l.pointerId=1,l.type="wheel",l.deltaMode=r.G.DOM_DELTA_PIXEL,l.deltaX=0,l.deltaY=0,l.deltaZ=0,i){case n.Fz.MouseWheelX:l.deltaX=s;break;case n.Fz.MouseWheelY:l.deltaY=s;break;case n.Fz.MouseWheelZ:l.deltaZ=s}return l}static _CreateMouseEvent(e,t,i,s,r,o){const a=this._CreateEvent(o),l=r.pollInput(e,t,n.Fz.Horizontal),h=r.pollInput(e,t,n.Fz.Vertical);return o?(a.movementX=0,a.movementY=0,a.offsetX=a.movementX-o.getBoundingClientRect().x,a.offsetY=a.movementY-o.getBoundingClientRect().y):(a.movementX=r.pollInput(e,t,n.FP.DeltaHorizontal),a.movementY=r.pollInput(e,t,n.FP.DeltaVertical),a.offsetX=0,a.offsetY=0),this._CheckNonCharacterKeys(a,r),a.clientX=l,a.clientY=h,a.x=l,a.y=h,a.deviceType=e,a.deviceSlot=t,a.inputIndex=i,a}static _CreateKeyboardEvent(e,t,i,s){const r=this._CreateEvent(s);return this._CheckNonCharacterKeys(r,i),r.deviceType=n.Yi.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(n.Yi.Keyboard),s=i&&1===t.pollInput(n.Yi.Keyboard,0,18),r=i&&1===t.pollInput(n.Yi.Keyboard,0,17),o=i&&(1===t.pollInput(n.Yi.Keyboard,0,91)||1===t.pollInput(n.Yi.Keyboard,0,92)||1===t.pollInput(n.Yi.Keyboard,0,93)),a=i&&1===t.pollInput(n.Yi.Keyboard,0,16);e.altKey=s,e.ctrlKey=r,e.metaKey=o,e.shiftKey=a}static _CreateEvent(e){const t={preventDefault:()=>{}};return t.target=e,t}}class a{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,((e,t,n,s)=>{const r=o.CreateDeviceEvent(e,t,n,s,this);i(e,t,r)})):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===n.Yi.Mouse||e===n.Yi.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}var l=i(1102),h=i(8658);const c=Object.keys(n.Fz).length/2;class d{constructor(e,t,i,n){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=h.w1.IsSafari(),this._usingMacOS=(0,l.up)()&&/(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._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=l.MZ.IsNavigatorAvailable()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Firefox"),this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=e=>{},this._gamepadDisconnectedEvent=e=>{},this._eventPrefix=h.w1.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 s=this._inputs[e][t];if(!s)throw`Unable to find device ${n.Yi[e]}`;e>=n.Yi.DualShock&&e<=n.Yi.DualSense&&this._updateDevice(e,t,i);const r=s[i];if(void 0===r)throw`Unable to find input ${i} for device ${n.Yi[e]} in slot ${t}`;return i===n.Fz.Move&&h.w1.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=null==this?void 0:this._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs)for(const e of this._inputs)if(e)for(const t in e){const i=e[+t];if(i)for(let e=0;e{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(n.Yi.Keyboard,0,255));const t=this._inputs[n.Yi.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(n.Yi.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(n.Yi.Keyboard,0,255));const t=this._inputs[n.Yi.Keyboard][0];if(t){t[e.keyCode]=0;const i=e;if(i.inputIndex=e.keyCode,this._usingMacOS&&"Meta"===e.key&&this._metaKeys.length>0){for(const e of this._metaKeys){const i=o.CreateDeviceEvent(n.Yi.Keyboard,0,e,0,this,this._elementToAttachTo);t[e]=0,this._onInputChanged(n.Yi.Keyboard,0,i)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(n.Yi.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[n.Yi.Keyboard][0];for(let t=0;t{const t=this._getPointerType(e),i=t===n.Yi.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]||this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const r=e;r.inputIndex=n.Fz.Move,s[n.Fz.Horizontal]=e.clientX,s[n.Fz.Vertical]=e.clientY,void 0===e.pointerId&&(e.pointerId=this._mouseId),this._onInputChanged(t,i,r),this._usingSafari||-1===e.button||(r.inputIndex=e.button+2,s[e.button+2]=s[e.button+2]?0:1,this._onInputChanged(t,i,r))}},this._pointerDownEvent=e=>{const t=this._getPointerType(e);let i=t===n.Yi.Mouse?0:e.pointerId;if(t===n.Yi.Touch){const t=this._activeTouchIds.indexOf(-1);if(!(t>=0))return void h.w1.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===n.Yi.Touch&&this._onDeviceConnected(t,i):this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const o=s[n.Fz.Horizontal],a=s[n.Fz.Vertical];if(t===n.Yi.Mouse){if(void 0===e.pointerId&&(e.pointerId=this._mouseId),!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(this._mouseId)}catch(r){}}else if(e.pointerId&&!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(e.pointerId)}catch(r){}s[n.Fz.Horizontal]=e.clientX,s[n.Fz.Vertical]=e.clientY,s[e.button+2]=1;const l=e;l.inputIndex=e.button+2,this._onInputChanged(t,i,l),o===e.clientX&&a===e.clientY||(l.inputIndex=n.Fz.Move,this._onInputChanged(t,i,l))}},this._pointerUpEvent=e=>{var t,i,s,r,o;const a=this._getPointerType(e),l=a===n.Yi.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(a===n.Yi.Touch){if(-1===l)return;this._activeTouchIds[l]=-1}const h=null===(t=this._inputs[a])||void 0===t?void 0:t[l];if(h&&0!==h[e.button+2]){const t=h[n.Fz.Horizontal],c=h[n.Fz.Vertical];h[n.Fz.Horizontal]=e.clientX,h[n.Fz.Vertical]=e.clientY,h[e.button+2]=0;const d=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),t===e.clientX&&c===e.clientY||(d.inputIndex=n.Fz.Move,this._onInputChanged(a,l,d)),d.inputIndex=e.button+2,a===n.Yi.Mouse&&this._mouseId>=0&&(null===(s=(i=this._elementToAttachTo).hasPointerCapture)||void 0===s?void 0:s.call(i,this._mouseId))?this._elementToAttachTo.releasePointerCapture(this._mouseId):e.pointerId&&(null===(o=(r=this._elementToAttachTo).hasPointerCapture)||void 0===o?void 0:o.call(r,e.pointerId))&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._onInputChanged(a,l,d),a===n.Yi.Touch&&this._onDeviceDisconnected(a,l)}},this._pointerCancelEvent=e=>{var t,i,s,r;if("mouse"===e.pointerType){const e=this._inputs[n.Yi.Mouse][0];this._mouseId>=0&&(null===(i=(t=this._elementToAttachTo).hasPointerCapture)||void 0===i?void 0:i.call(t,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=n.Fz.LeftClick;t<=n.Fz.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=o.CreateDeviceEvent(n.Yi.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(n.Yi.Mouse,0,i)}}else{const t=this._activeTouchIds.indexOf(e.pointerId);(null===(r=(s=this._elementToAttachTo).hasPointerCapture)||void 0===r?void 0:r.call(s,e.pointerId))&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._inputs[n.Yi.Touch][t][n.Fz.LeftClick]=0;const i=o.CreateDeviceEvent(n.Yi.Touch,t,n.Fz.LeftClick,0,this,this._elementToAttachTo,e.pointerId);this._onInputChanged(n.Yi.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(n.Yi.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(i){}this._pointerBlurEvent=()=>{var e,t,i,s,r;if(this.isDeviceAvailable(n.Yi.Mouse)){const i=this._inputs[n.Yi.Mouse][0];this._mouseId>=0&&(null===(t=(e=this._elementToAttachTo).hasPointerCapture)||void 0===t?void 0:t.call(e,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let e=n.Fz.LeftClick;e<=n.Fz.BrowserForward;e++)if(1===i[e]){i[e]=0;const t=o.CreateDeviceEvent(n.Yi.Mouse,0,e,0,this,this._elementToAttachTo);this._onInputChanged(n.Yi.Mouse,0,t)}}if(this.isDeviceAvailable(n.Yi.Touch)){const e=this._inputs[n.Yi.Touch];for(let t=0;t{const t=n.Yi.Mouse;this._inputs[t]||(this._inputs[t]=[]),this._inputs[t][0]||(this._pointerActive=!0,this._registerDevice(t,0,c));const i=this._inputs[t][0];if(i){i[n.Fz.MouseWheelX]=e.deltaX||0,i[n.Fz.MouseWheelY]=e.deltaY||e.wheelDelta||0,i[n.Fz.MouseWheelZ]=e.deltaZ||0;const s=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),0!==i[n.Fz.MouseWheelX]&&(s.inputIndex=n.Fz.MouseWheelX,this._onInputChanged(t,0,s)),0!==i[n.Fz.MouseWheelY]&&(s.inputIndex=n.Fz.MouseWheelY,this._onInputChanged(t,0,s)),0!==i[n.Fz.MouseWheelZ]&&(s.inputIndex=n.Fz.MouseWheelZ,this._onInputChanged(t,0,s))}},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(n.Yi.Mouse)){const e=this._inputs[n.Yi.Mouse][0];e[n.Fz.MouseWheelX]=0,e[n.Fz.MouseWheelY]=0,e[n.Fz.MouseWheelZ]=0}}))}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){const t=this._getGamepadDeviceType(e.gamepad.id),i=e.gamepad.index;this._unregisterDevice(t,i),delete this._gamepads[i]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,i){const n=navigator.getGamepads()[t];if(n&&e===this._gamepads[t]){const s=this._inputs[e][t];i>=n.buttons.length?s[i]=n.axes[i-n.buttons.length].valueOf():s[i]=n.buttons[i].value}}_getGamepadDeviceType(e){return-1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?n.Yi.DualSense:n.Yi.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")?n.Yi.Xbox:-1!==e.indexOf("057e")?n.Yi.Switch:n.Yi.Generic}_getPointerType(e){let t=n.Yi.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=n.Yi.Touch),t}}var u=i(505);class p{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=e=>{for(let t=0;t{const t=this._registeredManagers.indexOf(e);t>-1&&this._registeredManagers.splice(t,1)};const t=Object.keys(n.Yi).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 u.p(this._deviceInputSystem,e,t);i._addDevice(n)}},s=(e,t)=>{var i;(null===(i=this._devices[e])||void 0===i?void 0:i[t])&&delete this._devices[e][t];for(const n of this._registeredManagers)n._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 a(i,s,r):this._deviceInputSystem=new d(e,i,s,r)}dispose(){this._deviceInputSystem.dispose()}}class f{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(n.Yi).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new p(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new s.y$((e=>{for(const t of this._devices)if(t)for(const i of t)i&&this.onDeviceConnectedObservable.notifyObserver(e,i)})),this.onDeviceDisconnectedObservable=new s.y$,this._engine._deviceSourceManager.registerManager(this),this._onDisposeObserver=e.onDisposeObservable.add((()=>{this.dispose()}))}dispose(){this.onDeviceConnectedObservable.clear(),this.onDeviceDisconnectedObservable.clear(),this._engine._deviceSourceManager&&(this._engine._deviceSourceManager.unregisterManager(this),--this._engine._deviceSourceManager._refCount<1&&(this._engine._deviceSourceManager.dispose(),delete this._engine._deviceSourceManager)),this._engine.onDisposeObservable.remove(this._onDisposeObserver)}_addDevice(e){this._devices[e.deviceType]||(this._devices[e.deviceType]=new Array),this._devices[e.deviceType][e.deviceSlot]||(this._devices[e.deviceType][e.deviceSlot]=e,this._updateFirstDevices(e.deviceType)),this.onDeviceConnectedObservable.notifyObservers(e)}_removeDevice(e,t){var i,n;const s=null===(i=this._devices[e])||void 0===i?void 0:i[t];this.onDeviceDisconnectedObservable.notifyObservers(s),(null===(n=this._devices[e])||void 0===n?void 0:n[t])&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){var n,s;null===(s=null===(n=this._devices[e])||void 0===n?void 0:n[t])||void 0===s||s.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case n.Yi.Keyboard:case n.Yi.Mouse:this._firstDevice[e]=0;break;case n.Yi.Touch:case n.Yi.DualSense:case n.Yi.DualShock:case n.Yi.Xbox:case n.Yi.Switch:case n.Yi.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t)for(let i=0;i=s&&0===i?t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,new Float32Array(t)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,t):t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(i,i+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()}},9834:function(e,t,i){i.d(t,{A:function(){return s}});var n=i(9271);function s(e,t,i=!1,n){switch(e){case 3:{const e=(ArrayBuffer,new Int8Array(t));return n&&e.set(new Int8Array(n)),e}case 0:{const e=(ArrayBuffer,new Uint8Array(t));return n&&e.set(new Uint8Array(n)),e}case 4:{const e=t instanceof ArrayBuffer?new Int16Array(t):new Int16Array(i?t/2:t);return n&&e.set(new Int16Array(n)),e}case 5:case 8:case 9:case 10:case 2:{const e=t instanceof ArrayBuffer?new Uint16Array(t):new Uint16Array(i?t/2:t);return n&&e.set(new Uint16Array(n)),e}case 6:{const e=t instanceof ArrayBuffer?new Int32Array(t):new Int32Array(i?t/4:t);return n&&e.set(new Int32Array(n)),e}case 7:case 11:case 12:case 13:case 14:case 15:{const e=t instanceof ArrayBuffer?new Uint32Array(t):new Uint32Array(i?t/4:t);return n&&e.set(new Uint32Array(n)),e}case 1:{const e=t instanceof ArrayBuffer?new Float32Array(t):new Float32Array(i?t/4:t);return n&&e.set(new Float32Array(n)),e}}const s=(ArrayBuffer,new Uint8Array(t));return n&&s.set(new Uint8Array(n)),s}n.B.prototype._readTexturePixelsSync=function(e,t,i,n=-1,r=0,o=null,a=!0,l=!1,h=0,c=0){var d,u;const p=this._gl;if(!p)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const e=p.createFramebuffer();if(!e)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=e}p.bindFramebuffer(p.FRAMEBUFFER,this._dummyFramebuffer),n>-1?p.framebufferTexture2D(p.FRAMEBUFFER,p.COLOR_ATTACHMENT0,p.TEXTURE_CUBE_MAP_POSITIVE_X+n,null===(d=e._hardwareTexture)||void 0===d?void 0:d.underlyingResource,r):p.framebufferTexture2D(p.FRAMEBUFFER,p.COLOR_ATTACHMENT0,p.TEXTURE_2D,null===(u=e._hardwareTexture)||void 0===u?void 0:u.underlyingResource,r);let f=void 0!==e.type?this._getWebGLTextureType(e.type):p.UNSIGNED_BYTE;if(l)o||(o=s(e.type,4*t*i));else if(f===p.UNSIGNED_BYTE)o||(o=new Uint8Array(4*t*i)),f=p.UNSIGNED_BYTE;else o||(o=new Float32Array(4*t*i)),f=p.FLOAT;return a&&this.flushFramebuffer(),p.readPixels(h,c,t,i,p.RGBA,f,o),p.bindFramebuffer(p.FRAMEBUFFER,this._currentFramebuffer),o},n.B.prototype._readTexturePixels=function(e,t,i,n=-1,s=0,r=null,o=!0,a=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(e,t,i,n,s,r,o,a,l,h))}},4507:function(e,t,i){var n=i(9271),s=i(4081);n.B.prototype.createUniformBuffer=function(e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create uniform buffer");const i=new s.M(t);return this.bindUniformBuffer(i),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),i.references=1,i},n.B.prototype.createDynamicUniformBuffer=function(e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create dynamic uniform buffer");const i=new s.M(t);return this.bindUniformBuffer(i),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),i.references=1,i},n.B.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)},n.B.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},n.B.prototype.bindUniformBufferBase=function(e,t,i){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},n.B.prototype.bindUniformBlock=function(e,t,i){const n=e.program,s=this._gl.getUniformBlockIndex(n,t);4294967295!==s&&this._gl.uniformBlockBinding(n,s,i)}},3525:function(e,t,i){i.d(t,{L:function(){return E}});class n{constructor(){this.children=[]}isValid(e){return!0}process(e,t){var i,n,s,r,o,a,l;let h="";if(this.line){let c=this.line;const d=t.processor;if(d){d.lineProcessor&&(c=d.lineProcessor(c,t.isFragment,t.processingContext));const h=null!==(n=null===(i=t.processor)||void 0===i?void 0:i.attributeKeywordName)&&void 0!==n?n:"attribute",u=t.isFragment&&(null===(s=t.processor)||void 0===s?void 0:s.varyingFragmentKeywordName)?null===(r=t.processor)||void 0===r?void 0:r.varyingFragmentKeywordName:!t.isFragment&&(null===(o=t.processor)||void 0===o?void 0:o.varyingVertexKeywordName)?null===(a=t.processor)||void 0===a?void 0:a.varyingVertexKeywordName:"varying";if(!t.isFragment&&d.attributeProcessor&&this.line.startsWith(h))c=d.attributeProcessor(this.line,e,t.processingContext);else if(d.varyingProcessor&&((null===(l=d.varyingCheck)||void 0===l?void 0:l.call(d,this.line,t.isFragment))||!d.varyingCheck&&this.line.startsWith(u)))c=d.varyingProcessor(this.line,t.isFragment,e,t.processingContext);else if(d.uniformProcessor&&d.uniformRegexp&&d.uniformRegexp.test(this.line))t.lookForClosingBracketForUniformBuffer||(c=d.uniformProcessor(this.line,t.isFragment,e,t.processingContext));else if(d.uniformBufferProcessor&&d.uniformBufferRegexp&&d.uniformBufferRegexp.test(this.line))t.lookForClosingBracketForUniformBuffer||(c=d.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0);else if(d.textureProcessor&&d.textureRegexp&&d.textureRegexp.test(this.line))c=d.textureProcessor(this.line,t.isFragment,e,t.processingContext);else if((d.uniformProcessor||d.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer){/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?d.uniformProcessor&&(c=d.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):d.uniformBufferProcessor&&(c=d.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)}t.lookForClosingBracketForUniformBuffer&&-1!==this.line.indexOf("}")&&(t.lookForClosingBracketForUniformBuffer=!1,d.endOfUniformBufferProcessor&&(c=d.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}h+=c+"\r\n"}return this.children.forEach((i=>{h+=i.process(e,t)})),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),h}}class s{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex{c=c.trim(),""!==c&&(i.push(c),c="")},r=e=>{na._Stack[n],l=()=>-1===n?"!!INVALID EXPRESSION!!":a._Stack[n--];let h=0,c="";for(;h1){for(s();-1!==n&&a._OperatorPriority[o()]>=a._OperatorPriority[d];)i.push(l());r(d),h++}else c+=t;h++}for(s();-1!==n;)"("===o()?l():i.push(l());return a._InfixToPostfixCache.size>=a.InfixToPostfixCacheLimitSize&&a.ClearCache(),a._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){const e=Array.from(a._InfixToPostfixCache.entries()).sort(((e,t)=>e[1].accessTime-t[1].accessTime));for(let t=0;t":i=n>s;break;case"<":i=n=":i=n>=s;break;case"==":i=n===s;break;case"!=":i=n!==s}return i}}var u=i(9069),p=i(475);const f=/defined\s*?\((.+?)\)/g,_=/defined\s*?\[(.+?)\]/g,m=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,g=/__decl__/,v=/light\{X\}.(\w*)/g,T=/\{X\}/g,S=[];class E{static Initialize(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}static Process(e,t,i,n){var s;(null===(s=t.processor)||void 0===s?void 0:s.preProcessShaderCode)&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));const s=this._ProcessShaderConversion(e,t,n);i(s,e)}))}static PreProcess(e,t,i,n){var s;(null===(s=t.processor)||void 0===s?void 0:s.preProcessShaderCode)&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));const s=this._ApplyPreProcessing(e,t,n);i(s,e)}))}static Finalize(e,t,i){return i.processor&&i.processor.finalizeShaders?i.processor.finalizeShaders(e,t,i.processingContext):{vertexCode:e,fragmentCode:t}}static _ProcessPrecision(e,t){var i;if(null===(i=t.processor)||void 0===i?void 0:i.noPrecision)return e;const n=t.shouldUseHighPrecisionShader;return-1===e.indexOf("precision highp float")?e=n?"precision highp float;\n"+e:"precision mediump float;\n"+e:n||(e=e.replace("precision highp float","precision mediump float")),e}static _ExtractOperation(e){const t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new l(t[1].trim(),"!"===e[0]);const i=["==","!=",">=","<=","<",">"];let n="",s=0;for(n of i)if(s=e.indexOf(n),s>-1)break;if(-1===s)return new l(e);const r=e.substring(0,s).trim(),o=e.substring(s+n.length).trim();return new d(r,n,o)}static _BuildSubExpression(e){e=e.replace(f,"defined[$1]");const t=a.infixToPostfix(e),i=[];for(const s of t)if("||"!==s&&"&&"!==s)i.push(s);else if(i.length>=2){let e=i[i.length-1],t=i[i.length-2];i.length-=2;const n="&&"==s?new c:new h;"string"==typeof e&&(e=e.replace(_,"defined($1)")),"string"==typeof t&&(t=t.replace(_,"defined($1)")),n.leftOperand="string"==typeof t?this._ExtractOperation(t):t,n.rightOperand="string"==typeof e?this._ExtractOperation(e):e,i.push(n)}let n=i[i.length-1];return"string"==typeof n&&(n=n.replace(_,"defined($1)")),"string"==typeof n?this._ExtractOperation(n):n}static _BuildExpression(e,t){const i=new o,n=e.substring(0,t);let s=e.substring(t);return s=s.substring(0,(s.indexOf("//")+1||s.length+1)-1).trim(),i.testExpression="#ifdef"===n?new l(s):"#ifndef"===n?new l(s,!0):this._BuildSubExpression(s),i}static _MoveCursorWithinIf(e,t,i){let s=e.currentLine;for(;this._MoveCursor(e,i);){s=e.currentLine;const r=s.substring(0,5).toLowerCase();if("#else"===r){const i=new n;return t.children.push(i),void this._MoveCursor(e,i)}if("#elif"===r){const e=this._BuildExpression(s,5);t.children.push(e),i=e}}}static _MoveCursor(e,t){for(;e.canRead;){e.lineIndex++;const i=e.currentLine;if(i.indexOf("#")>=0){const n=E._MoveCursorRegex.exec(i);if(n&&n.length){switch(n[0]){case"#ifdef":{const n=new r;t.children.push(n);const s=this._BuildExpression(i,6);n.children.push(s),this._MoveCursorWithinIf(e,n,s);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const n=new r;t.children.push(n);const s=this._BuildExpression(i,7);n.children.push(s),this._MoveCursorWithinIf(e,n,s);break}case"#if":{const n=new r,s=this._BuildExpression(i,3);t.children.push(n),n.children.push(s),this._MoveCursorWithinIf(e,n,s);break}}continue}}const s=new n;if(s.line=i,t.children.push(s),"#"===i[0]&&"d"===i[1]){const e=i.replace(";","").split(" ");s.additionalDefineKey=e[1],3===e.length&&(s.additionalDefineValue=e[2])}}return!1}static _EvaluatePreProcessors(e,t,i){const r=new n,o=new s;return o.lineIndex=-1,o.lines=e.split("\n"),this._MoveCursor(o,r),r.process(t,i)}static _PreparePreProcessors(e,t){var i;const n=e.defines,s={};for(const r of n){const e=r.replace("#define","").replace(";","").trim().split(" ");s[e[0]]=e.length>1?e[1]:""}return(null===(i=e.processor)||void 0===i?void 0:i.shaderLanguage)===p.x.GLSL&&(s.GL_ES="true"),s.__VERSION__=e.version,s[e.platformName]="true",t._getGlobalDefines(s),s}static _ProcessShaderConversion(e,t,i){let n=this._ProcessPrecision(e,t);if(!t.processor)return n;if(t.processor.shaderLanguage===p.x.GLSL&&-1!==n.indexOf("#version 3")&&(n=n.replace("#version 300 es",""),!t.processor.parseGLES3))return n;const s=t.defines,r=this._PreparePreProcessors(t,i);return t.processor.preProcessor&&(n=t.processor.preProcessor(n,s,t.isFragment,t.processingContext)),n=this._EvaluatePreProcessors(n,r,t),t.processor.postProcessor&&(n=t.processor.postProcessor(n,s,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(n=i.inlineShaderCode(n)),n}static _ApplyPreProcessing(e,t,i){var n,s;let r=e;const o=t.defines,a=this._PreparePreProcessors(t,i);return(null===(n=t.processor)||void 0===n?void 0:n.preProcessor)&&(r=t.processor.preProcessor(r,o,t.isFragment,t.processingContext)),r=this._EvaluatePreProcessors(r,a,t),(null===(s=t.processor)||void 0===s?void 0:s.postProcessor)&&(r=t.processor.postProcessor(r,o,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(r=i.inlineShaderCode(r)),r}static _ProcessIncludes(e,t,i){let n;for(S.length=0;null!==(n=m.exec(e));)S.push(n);let s=String(e),r=[e],o=!1;for(const a of S){let e=a[1];if(-1!==e.indexOf("__decl__")&&(e=e.replace(g,""),t.supportsUniformBuffers&&(e=e.replace("Vertex","Ubo").replace("Fragment","Ubo")),e+="Declaration"),!t.includesShadersStore[e]){const n=t.shadersRepository+"ShadersInclude/"+e+".fx";return void E._FileToolsLoadFile(n,(n=>{t.includesShadersStore[e]=n,this._ProcessIncludes(r.join(""),t,i)}))}{let i=t.includesShadersStore[e];if(a[2]){const e=a[3].split(",");for(let t=0;tt+"{X}"))),i+=o.replace(T,e.toString())+"\n"}else t.supportsUniformBuffers||(i=i.replace(v,((e,t)=>t+"{X}"))),i=i.replace(T,e)}const n=[];for(const e of r){const t=e.split(a[0]);for(let e=0;e=0||i.indexOf("#include <")>=0}}S.length=0,s=r.join(""),o?this._ProcessIncludes(s.toString(),t,i):i(s)}static _FileToolsLoadFile(e,t,i,n,s,r){throw(0,u.S)("FileTools")}}E._MoveCursorRegex=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/},3156:function(e,t,i){i.d(t,{C:function(){return r}});var n=i(475);const s=/(flat\s)?\s*varying\s*.*/;class r{constructor(){this.shaderLanguage=n.x.GLSL}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return s.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)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?"":"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}}},8449:function(e,t,i){i.d(t,{B:function(){return n}});class n{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}}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}},1917:function(e,t,i){i.d(t,{y:function(){return n}});class n{constructor(){this._valueCache={},this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null}get isAsync(){return this.isParallelCompiled}get isReady(){return!!this.program&&(!this.isParallelCompiled||this.engine._isRenderingStateCompiled(this))}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}_fillEffectInformation(e,t,i,n,s,r,o,a){const l=this.engine;if(l.supportsUniformBuffers)for(const c in t)e.bindUniformBlock(c,t[c]);let h;for(this.engine.getUniforms(this,i).forEach(((e,t)=>{n[i[t]]=e})),this._uniforms=n,h=0;h{r[e]=t}));for(const c of l.getAttributes(this,o))a.push(c)}dispose(){this._uniforms={}}_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 s=!1;return n[0]!==t&&(n[0]=t,s=!0),n[1]!==i&&(n[1]=i,s=!0),s}_cacheFloat3(e,t,i,n){let s=this._valueCache[e];if(!s||3!==s.length)return s=[t,i,n],this._valueCache[e]=s,!0;let r=!1;return s[0]!==t&&(s[0]=t,r=!0),s[1]!==i&&(s[1]=i,r=!0),s[2]!==n&&(s[2]=n,r=!0),r}_cacheFloat4(e,t,i,n,s){let r=this._valueCache[e];if(!r||4!==r.length)return r=[t,i,n,s],this._valueCache[e]=r,!0;let o=!1;return r[0]!==t&&(r[0]=t,o=!0),r[1]!==i&&(r[1]=i,o=!0),r[2]!==n&&(r[2]=n,o=!0),r[3]!==s&&(r[3]=s,o=!0),o}setInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,n){this._cacheFloat3(e,t,i,n)&&(this.engine.setInt3(this._uniforms[e],t,i,n)||(this._valueCache[e]=null))}setInt4(e,t,i,n,s){this._cacheFloat4(e,t,i,n,s)&&(this.engine.setInt4(this._uniforms[e],t,i,n,s)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];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,s){this._cacheFloat4(e,t,i,n,s)&&(this.engine.setUInt4(this._uniforms[e],t,i,n,s)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this.engine.setMatrices(this._uniforms[e],t.toArray())||(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,s){this._cacheFloat4(e,t,i,n,s)&&(this.engine.setFloat4(this._uniforms[e],t,i,n,s)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}_getVertexShaderCode(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null}_getFragmentShaderCode(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null}}},2155:function(e,t,i){i.d(t,{f:function(){return s}});var n=i(475);class s{constructor(){this.shaderLanguage=n.x.GLSL}postProcessor(e,t,i,n,s){if(!s.getCaps().drawBuffersExtension){const t=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(t,"")}return e}}},8838:function(e,t,i){i.d(t,{D:function(){return f}});var n=i(8139),s=i(4679),r=i(1102),o=i(5953),a=i(9069),l=i(9271),h=i(4441),c=i(8482),d=i(4081),u=i(658),p=i(8449);i(2094),i(9834),i(6430);class f extends l.B{static get NpmPackage(){return l.B.NpmPackage}static get Version(){return l.B.Version}static get Instances(){return o.l.Instances}static get LastCreatedEngine(){return o.l.LastCreatedEngine}static get LastCreatedScene(){return o.l.LastCreatedScene}_createImageBitmapFromSource(e,t){return new Promise(((i,n)=>{const s=new Image;s.onload=()=>{s.decode().then((()=>{this.createImageBitmap(s,t).then((e=>{i(e)}))}))},s.onerror=()=>{n(`Error loading image ${s.src}`)},s.src=e}))}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){const n=this.createCanvas(t,i).getContext("2d");if(!n)throw new Error("Unable to get 2d context for resizeImageBitmap");n.drawImage(e,0,0);return n.getImageData(0,0,t,i).data}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i{this.onCanvasFocusObservable.notifyObservers(this)},this._onCanvasBlur=()=>{this.onCanvasBlurObservable.notifyObservers(this)},this._onCanvasContextMenu=e=>{this.disableContextMenu&&e.preventDefault()},e.addEventListener("focus",this._onCanvasFocus),e.addEventListener("blur",this._onCanvasBlur),e.addEventListener("contextmenu",this._onCanvasContextMenu),this._onBlur=()=>{this.disablePerformanceMonitorInBackground&&this._performanceMonitor.disable(),this._windowIsBackground=!0},this._onFocus=()=>{this.disablePerformanceMonitorInBackground&&this._performanceMonitor.enable(),this._windowIsBackground=!1},this._onCanvasPointerOut=t=>{document.elementFromPoint(t.clientX,t.clientY)!==e&&this.onCanvasPointerOutObservable.notifyObservers(t)};const t=this.getHostWindow();t&&"function"==typeof t.addEventListener&&(t.addEventListener("blur",this._onBlur),t.addEventListener("focus",this._onFocus)),e.addEventListener("pointerout",this._onCanvasPointerOut),this._creationOptions.doNotHandleTouchAction||this._disableTouchAction(),!f.audioEngine&&this._creationOptions.audioEngine&&f.AudioEngineFactory&&(f.audioEngine=f.AudioEngineFactory(this.getRenderingCanvas(),this.getAudioContext(),this.getAudioDestination())),(0,r.n5)()&&(this._onFullscreenChange=()=>{this.isFullscreen=!!document.fullscreenElement,this.isFullscreen&&this._pointerLockRequested&&e&&f._RequestPointerlock(e)},document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",this._onFullscreenChange,!1),this._onPointerLockChange=()=>{this.isPointerLock=document.pointerLockElement===e},document.addEventListener("pointerlockchange",this._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",this._onPointerLockChange,!1)),this.enableOfflineSupport=void 0!==f.OfflineProviderFactory,this._deterministicLockstep=!!this._creationOptions.deterministicLockstep,this._lockstepMaxSteps=this._creationOptions.lockstepMaxSteps||0,this._timeStep=this._creationOptions.timeStep||1/60}_verifyPointerLock(){var e;null===(e=this._onPointerLockChange)||void 0===e||e.call(this)}getAspectRatio(e,t=!1){const i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)}getScreenAspectRatio(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)}getRenderingCanvasClientRect(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null}getInputElementClientRect(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return 1e3*this._timeStep}generateMipMapsForCubemap(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)}}getDepthWrite(){return this._depthCullingState.depthMask}setDepthWrite(e){this._depthCullingState.depthMask=e}getStencilBuffer(){return this._stencilState.stencilTest}setStencilBuffer(e){this._stencilState.stencilTest=e}getStencilMask(){return this._stencilState.stencilMask}setStencilMask(e){this._stencilState.stencilMask=e}getStencilFunction(){return this._stencilState.stencilFunc}getStencilFunctionReference(){return this._stencilState.stencilFuncRef}getStencilFunctionMask(){return this._stencilState.stencilFuncMask}setStencilFunction(e){this._stencilState.stencilFunc=e}setStencilFunctionReference(e){this._stencilState.stencilFuncRef=e}setStencilFunctionMask(e){this._stencilState.stencilFuncMask=e}getStencilOperationFail(){return this._stencilState.stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilState.stencilOpDepthFail}getStencilOperationPass(){return this._stencilState.stencilOpStencilDepthPass}setStencilOperationFail(e){this._stencilState.stencilOpStencilFail=e}setStencilOperationDepthFail(e){this._stencilState.stencilOpDepthFail=e}setStencilOperationPass(e){this._stencilState.stencilOpStencilDepthPass=e}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)}getDepthFunction(){return this._depthCullingState.depthFunc}setDepthFunction(e){this._depthCullingState.depthFunc=e}setDepthFunctionToGreater(){this.setDepthFunction(516)}setDepthFunctionToGreaterOrEqual(){this.setDepthFunction(518)}setDepthFunctionToLess(){this.setDepthFunction(513)}setDepthFunctionToLessOrEqual(){this.setDepthFunction(515)}cacheStencilState(){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()}restoreStencilState(){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)}setDirectViewport(e,t,i,n){const s=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,n),s}scissorClear(e,t,i,n,s){this.enableScissor(e,t,i,n),this.clear(s,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,n){const s=this._gl;s.enable(s.SCISSOR_TEST),s.scissor(e,t,i,n)}disableScissor(){const e=this._gl;e.disable(e.SCISSOR_TEST)}_reportDrawCall(e=1){this._drawCalls.addCount(e,!1)}initWebVR(){throw(0,a.S)("WebVRCamera")}_prepareVRComponent(){}_connectVREvents(e,t){}_submitVRFrame(){}disableVR(){}isVRPresenting(){return!1}_requestVRFrame(){}_loadFileAsync(e,t,i){return new Promise(((n,s)=>{this._loadFile(e,(e=>{n(e)}),void 0,t,i,((e,t)=>{s(t)}))}))}getVertexShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}setDepthStencilTexture(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))}setTextureFromPostProcess(e,t,i){var n;let s=null;t&&(t._forcedOutputTexture?s=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(s=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,null!==(n=null==s?void 0:s.texture)&&void 0!==n?n:null,i)}setTextureFromPostProcessOutput(e,t,i){var n,s;this._bindTexture(e,null!==(s=null===(n=null==t?void 0:t._outputTexture)||void 0===n?void 0:n.texture)&&void 0!==s?s:null,i)}_rebuildBuffers(){for(const e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries(),e._rebuildTextures();for(const e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries(),e._rebuildTextures();super._rebuildBuffers()}_renderFrame(){for(let e=0;e0?this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this.isVRPresenting()?this._requestVRFrame():this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()):this._renderingQueueLaunched=!1}_renderViews(){return!1}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&f._RequestFullscreen(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&f._ExitFullscreen()}enterPointerlock(){this._renderingCanvas&&f._RequestPointerlock(this._renderingCanvas)}exitPointerlock(){f._ExitPointerlock()}beginFrame(){this._measureFps(),this.onBeginFrameObservable.notifyObservers(this),super.beginFrame()}endFrame(){super.endFrame(),this._submitVRFrame(),this.onEndFrameObservable.notifyObservers(this)}resize(e=!1){this.isVRPresenting()||super.resize(e)}setSize(e,t,i=!1){if(!this._renderingCanvas)return!1;if(!super.setSize(e,t,i))return!1;if(this.scenes){for(let e=0;e1&&s){const t=this.createTransformFeedback();this.bindTransformFeedback(t),this.setTranformFeedbackVaryings(r,s),e.transformFeedback=t}return n.linkProgram(r),this.webGLVersion>1&&s&&this.bindTransformFeedback(null),e.context=n,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),r}_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)}))}))}))}getRenderPassNames(){return this._renderPassNames}getCurrentRenderPassName(){return this._renderPassNames[this.currentRenderPassId]}createRenderPassId(e){const t=++f._RenderPassIdCounter;return this._renderPassNames[t]=null!=e?e:"NONAME",t}releaseRenderPassId(e){this._renderPassNames[e]=void 0;for(let t=0;t{this._rescalePostProcess.onApply=function(t){t._bindTexture("textureSampler",e)};let o=i;o||(o=this.scenes[this.scenes.length-1]),o.postProcessManager.directRender([this._rescalePostProcess],r,!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(r),r.dispose(),s&&s()})))}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}_measureFps(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0}wrapWebGLTexture(e,t=!1,i=3){const n=new p.B(e,this._gl),r=new s.l(this,s.S.Unknown,!0);return r._hardwareTexture=n,r.isReady=!0,r.useMipMaps=t,this.updateTextureSamplingMode(i,r),r}_uploadImageToTexture(e,t,i=0,n=0){const s=this._gl,r=this._getWebGLTextureType(e.type),o=this._getInternalFormat(e.format),a=this._getRGBABufferInternalSizedFormat(e.type,o),l=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);let h=s.TEXTURE_2D;e.isCube&&(h=s.TEXTURE_CUBE_MAP_POSITIVE_X+i),s.texImage2D(h,n,a,o,r,t),this._bindTextureDirectly(l,null,!0)}updateTextureComparisonFunction(e,t){if(1===this.webGLVersion)return void u.Y.Error("WebGL 1 does not support texture comparison.");const i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),0===t?(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),0===t?(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),e._comparisonFunction=t}createInstancesBuffer(e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create instance buffer");const i=new d.M(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}_clientWaitAsync(e,t=0,i=10){const n=this._gl;return new Promise(((s,r)=>{const o=()=>{const a=n.clientWaitSync(e,t,0);a!=n.WAIT_FAILED?a!=n.TIMEOUT_EXPIRED?s():setTimeout(o,i):r()};o()}))}_readPixelsAsync(e,t,i,n,s,r,o){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const a=this._gl,l=a.createBuffer();a.bindBuffer(a.PIXEL_PACK_BUFFER,l),a.bufferData(a.PIXEL_PACK_BUFFER,o.byteLength,a.STREAM_READ),a.readPixels(e,t,i,n,s,r,0),a.bindBuffer(a.PIXEL_PACK_BUFFER,null);const h=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);return h?(a.flush(),this._clientWaitAsync(h,0,10).then((()=>(a.deleteSync(h),a.bindBuffer(a.PIXEL_PACK_BUFFER,l),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,o),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),a.deleteBuffer(l),o)))):null}dispose(){for(this.hideLoadingUI(),this.onNewSceneAddedObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(this._rescalePostProcess&&this._rescalePostProcess.dispose();this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();1===o.l.Instances.length&&f.audioEngine&&(f.audioEngine.dispose(),f.audioEngine=null),this.disableVR();const e=this.getHostWindow();e&&"function"==typeof e.removeEventListener&&(e.removeEventListener("blur",this._onBlur),e.removeEventListener("focus",this._onFocus)),this._renderingCanvas&&(this._renderingCanvas.removeEventListener("focus",this._onCanvasFocus),this._renderingCanvas.removeEventListener("blur",this._onCanvasBlur),this._renderingCanvas.removeEventListener("pointerout",this._onCanvasPointerOut),this._renderingCanvas.removeEventListener("contextmenu",this._onCanvasContextMenu)),(0,r.n5)()&&(document.removeEventListener("fullscreenchange",this._onFullscreenChange),document.removeEventListener("mozfullscreenchange",this._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",this._onFullscreenChange),document.removeEventListener("msfullscreenchange",this._onFullscreenChange),document.removeEventListener("pointerlockchange",this._onPointerLockChange),document.removeEventListener("mspointerlockchange",this._onPointerLockChange),document.removeEventListener("mozpointerlockchange",this._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",this._onPointerLockChange)),super.dispose();const t=o.l.Instances.indexOf(this);t>=0&&o.l.Instances.splice(t,1),f.Instances.length||o.l.OnEnginesDisposedObservable.notifyObservers(this),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}_disableTouchAction(){this._renderingCanvas&&this._renderingCanvas.setAttribute&&(this._renderingCanvas.setAttribute("touch-action","none"),this._renderingCanvas.style.touchAction="none",this._renderingCanvas.style.webkitTapHighlightColor="transparent")}displayLoadingUI(){if(!(0,r.CG)())return;const e=this.loadingScreen;e&&e.displayLoadingUI()}hideLoadingUI(){if(!(0,r.CG)())return;const e=this._loadingScreen;e&&e.hideLoadingUI()}get loadingScreen(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=f.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen}set loadingScreen(e){this._loadingScreen=e}set loadingUIText(e){this.loadingScreen.loadingUIText=e}set loadingUIBackgroundColor(e){this.loadingScreen.loadingUIBackgroundColor=e}createVideoElement(e){return document.createElement("video")}static _RequestPointerlock(e){if(e.requestPointerLock){const t=e.requestPointerLock();t instanceof Promise?t.then((()=>{e.focus()})).catch((()=>{})):e.focus()}}static _ExitPointerlock(){document.exitPointerLock&&document.exitPointerLock()}static _RequestFullscreen(e){const t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}static _ExitFullscreen(){const e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}getFontOffset(e){const t=document.createElement("span");t.innerHTML="Hg",t.setAttribute("style",`font: ${e} !important`);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 s=0,r=0;try{r=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",s=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(n)}return{ascent:s,height:r,descent:r-s}}}f.ALPHA_DISABLE=0,f.ALPHA_ADD=1,f.ALPHA_COMBINE=2,f.ALPHA_SUBTRACT=3,f.ALPHA_MULTIPLY=4,f.ALPHA_MAXIMIZED=5,f.ALPHA_ONEONE=6,f.ALPHA_PREMULTIPLIED=7,f.ALPHA_PREMULTIPLIED_PORTERDUFF=8,f.ALPHA_INTERPOLATE=9,f.ALPHA_SCREENMODE=10,f.DELAYLOADSTATE_NONE=0,f.DELAYLOADSTATE_LOADED=1,f.DELAYLOADSTATE_LOADING=2,f.DELAYLOADSTATE_NOTLOADED=4,f.NEVER=512,f.ALWAYS=519,f.LESS=513,f.EQUAL=514,f.LEQUAL=515,f.GREATER=516,f.GEQUAL=518,f.NOTEQUAL=517,f.KEEP=7680,f.REPLACE=7681,f.INCR=7682,f.DECR=7683,f.INVERT=5386,f.INCR_WRAP=34055,f.DECR_WRAP=34056,f.TEXTURE_CLAMP_ADDRESSMODE=0,f.TEXTURE_WRAP_ADDRESSMODE=1,f.TEXTURE_MIRROR_ADDRESSMODE=2,f.TEXTUREFORMAT_ALPHA=0,f.TEXTUREFORMAT_LUMINANCE=1,f.TEXTUREFORMAT_LUMINANCE_ALPHA=2,f.TEXTUREFORMAT_RGB=4,f.TEXTUREFORMAT_RGBA=5,f.TEXTUREFORMAT_RED=6,f.TEXTUREFORMAT_R=6,f.TEXTUREFORMAT_RG=7,f.TEXTUREFORMAT_RED_INTEGER=8,f.TEXTUREFORMAT_R_INTEGER=8,f.TEXTUREFORMAT_RG_INTEGER=9,f.TEXTUREFORMAT_RGB_INTEGER=10,f.TEXTUREFORMAT_RGBA_INTEGER=11,f.TEXTURETYPE_UNSIGNED_BYTE=0,f.TEXTURETYPE_UNSIGNED_INT=0,f.TEXTURETYPE_FLOAT=1,f.TEXTURETYPE_HALF_FLOAT=2,f.TEXTURETYPE_BYTE=3,f.TEXTURETYPE_SHORT=4,f.TEXTURETYPE_UNSIGNED_SHORT=5,f.TEXTURETYPE_INT=6,f.TEXTURETYPE_UNSIGNED_INTEGER=7,f.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,f.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,f.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,f.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,f.TEXTURETYPE_UNSIGNED_INT_24_8=12,f.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,f.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,f.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,f.TEXTURE_NEAREST_SAMPLINGMODE=1,f.TEXTURE_BILINEAR_SAMPLINGMODE=2,f.TEXTURE_TRILINEAR_SAMPLINGMODE=3,f.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,f.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,f.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,f.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,f.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,f.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,f.TEXTURE_NEAREST_LINEAR=7,f.TEXTURE_NEAREST_NEAREST=1,f.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,f.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,f.TEXTURE_LINEAR_LINEAR=2,f.TEXTURE_LINEAR_NEAREST=12,f.TEXTURE_EXPLICIT_MODE=0,f.TEXTURE_SPHERICAL_MODE=1,f.TEXTURE_PLANAR_MODE=2,f.TEXTURE_CUBIC_MODE=3,f.TEXTURE_PROJECTION_MODE=4,f.TEXTURE_SKYBOX_MODE=5,f.TEXTURE_INVCUBIC_MODE=6,f.TEXTURE_EQUIRECTANGULAR_MODE=7,f.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,f.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,f.SCALEMODE_FLOOR=1,f.SCALEMODE_NEAREST=2,f.SCALEMODE_CEILING=3,f._RescalePostProcessFactory=null,f._RenderPassIdCounter=0},5953:function(e,t,i){i.d(t,{l:function(){return s}});var n=i(8139);class s{static get LastCreatedEngine(){return 0===this.Instances.length?null:this.Instances[this.Instances.length-1]}static get LastCreatedScene(){return this._LastCreatedScene}}s.Instances=new Array,s.OnEnginesDisposedObservable=new n.y$,s._LastCreatedScene=null,s.UseFallbackTexture=!0,s.FallbackTexture=""},1716:function(e,t,i){i.d(t,{Z:function(){return n}});class n{static SetMatrixPrecision(e){if(n.MatrixTrackPrecisionChange=!1,e&&!n.MatrixUse64Bits&&n.MatrixTrackedMatrices)for(let t=0;t=h.Fz.MouseWheelX&&t.inputIndex<=h.Fz.MouseWheelZ?n.kD.POINTERWHEEL:n.kD.POINTERMOVE;let a;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,o)),e?(a=new n.R5(o,t,e),this._setRayOnPointerInfo(e,t)):(a=new n.R5(o,t,null,this),this._movePointerInfo=a),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(a,o)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&i._pickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,o.y3.Identity(),i.activeCamera)))}_addCameraPointerObserver(e,t){return this._cameraObserverCount++,this._scene.onPointerObservable.add(e,t)}_removeCameraPointerObserver(e){return this._cameraObserverCount--,this._scene.onPointerObservable.remove(e)}_checkForPicking(){return!!(this._scene.onPointerObservable.observers.length>this._cameraObserverCount||this._scene.onPointerPick)}_checkPrePointerObservable(e,t,i){const s=this._scene,r=new n.FV(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(r.originalPickingInfo=e,r.ray=e.ray,e.originMesh&&(r.nearInteractionPickingInfo=e)),s.onPrePointerObservable.notifyObservers(r,i),!!r.skipOnPointerObservable}_pickMove(e){const t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){const n=i.getEngine().getInputElement();if(null==e?void 0: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=h.Fz.Move,this._checkPrePointerObservable(e,i,n.kD.POINTERMOVE)||this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,this._checkPrePointerObservable(e,i,n.kD.POINTERDOWN)||this._processPointerDown(e,i)}_processPointerDown(e,t){const i=this._scene;if(null==e?void 0:e.pickedMesh){this._pickedDownMesh=e.pickedMesh;const n=e.pickedMesh._getActionManagerForTrigger();if(n){if(n.hasPickTriggers)switch(n.processTrigger(5,a.V.CreateNew(e.pickedMesh,t)),t.button){case 0:n.processTrigger(2,a.V.CreateNew(e.pickedMesh,t));break;case 1:n.processTrigger(4,a.V.CreateNew(e.pickedMesh,t));break;case 2:n.processTrigger(3,a.V.CreateNew(e.pickedMesh,t))}n.hasSpecificTrigger(8)&&window.setTimeout((()=>{const e=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,(e=>e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(8)&&e===this._pickedDownMesh),!1,i.cameraToUseForPointers);(null==e?void 0:e.pickedMesh)&&n&&0!==this._totalPointersPressed&&Date.now()-this._startingPointerTime>p.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,n.processTrigger(8,a.V.CreateNew(e.pickedMesh,t)))}),p.LongPressDelay)}}else for(const n of i._pointerDownStage)e=n.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let s;const r=n.kD.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,r),s=new n.R5(r,t,e),this._setRayOnPointerInfo(e,t)):s=new n.R5(r,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(s,r)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){const s=new PointerEvent("pointerup",t);s.inputIndex=h.Fz.Move;const r=new u;i?r.doubleClick=!0:r.singleClick=!0,this._checkPrePointerObservable(e,s,n.kD.POINTERUP)||this._processPointerUp(e,s,r)}_processPointerUp(e,t,i){const s=this._scene;if(null==e?void 0:e.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(s.onPointerPick&&s.onPointerPick(t,e),i.singleClick&&!i.ignore&&s.onPointerObservable.observers.length>this._cameraObserverCount)){const i=n.kD.POINTERPICK,r=new n.R5(i,t,e);this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,i)}const r=e.pickedMesh._getActionManagerForTrigger();if(r&&!i.ignore){r.processTrigger(7,a.V.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&r.processTrigger(1,a.V.CreateNew(e.pickedMesh,t,e));const n=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&n&&n.processTrigger(6,a.V.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(const n of s._pointerUpStage)e=n.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const e=this._pickedDownMesh._getActionManagerForTrigger(16);e&&e.processTrigger(16,a.V.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const r=new n.R5(n.kD.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,n.kD.POINTERUP),s.onPointerUp&&s.onPointerUp(t,e,n.kD.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let r=0;if(i.singleClick?r=n.kD.POINTERTAP:i.doubleClick&&(r=n.kD.POINTERDOUBLETAP),r){const i=new n.R5(r,t,e);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(r)&&s.onPointerObservable.notifyObservers(i,r)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,o=null){const d=this._scene,f=d.getEngine();o||(o=f.getInputElement()),this._alreadyAttached&&this.detachControl(),o&&(this._alreadyAttachedTo=o),this._deviceSourceManager=new c.U(f),this._initActionManager=e=>{if(!this._meshPickProceed){const t=d.skipPointerUpPicking||0===d._registeredActions&&!this._checkForPicking()&&!d.onPointerUp?null:d.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,d.pointerUpPredicate,d.pointerUpFastCheck,d.cameraToUseForPointers);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>p.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=n.kD.POINTERTAP,s=new n.R5(i,t,this._currentPickResult);d.onPointerObservable.hasObservers()&&d.onPointerObservable.hasSpecificMask(i)&&d.onPointerObservable.notifyObservers(s,i),this._delayedClicks[e]=null}},this._initClickEvent=(e,t,i,r)=>{var o,a;const l=new u;this._currentPickResult=null;let h=null,c=e.hasSpecificMask(n.kD.POINTERPICK)||t.hasSpecificMask(n.kD.POINTERPICK)||e.hasSpecificMask(n.kD.POINTERTAP)||t.hasSpecificMask(n.kD.POINTERTAP)||e.hasSpecificMask(n.kD.POINTERDOUBLETAP)||t.hasSpecificMask(n.kD.POINTERDOUBLETAP);!c&&s.O&&(h=this._initActionManager(h,l),h&&(c=h.hasPickTriggers));let d=!1;if(c){const c=i.button;if(l.hasSwiped=this._isPointerSwiping(),!l.hasSwiped){let u=!p.ExclusiveDoubleClickMode;if(u||(u=!e.hasSpecificMask(n.kD.POINTERDOUBLETAP)&&!t.hasSpecificMask(n.kD.POINTERDOUBLETAP),u&&!s.O.HasSpecificTrigger(6)&&(h=this._initActionManager(h,l),h&&(u=!h.hasSpecificTrigger(6)))),u)(Date.now()-this._previousStartingPointerTime>p.DoubleClickDelay||c!==this._previousButtonPressed)&&(l.singleClick=!0,r(l,this._currentPickResult),d=!0);else{const e={evt:i,clickInfo:l,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,c,l,r),p.DoubleClickDelay)};this._delayedClicks[c]=e}let f=e.hasSpecificMask(n.kD.POINTERDOUBLETAP)||t.hasSpecificMask(n.kD.POINTERDOUBLETAP);!f&&s.O.HasSpecificTrigger(6)&&(h=this._initActionManager(h,l),h&&(f=h.hasSpecificTrigger(6))),f&&(c===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(this._updatePointerPosition(e),this._isSwiping||-1===this._swipeButtonPressed||(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>p.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>p.DragMovementThreshold),f.isPointerLock&&f._verifyPointerLock(),this._checkPrePointerObservable(null,e,e.inputIndex>=h.Fz.MouseWheelX&&e.inputIndex<=h.Fz.MouseWheelZ?n.kD.POINTERWHEEL:n.kD.POINTERMOVE))return;if(!d.cameraToUseForPointers&&!d.activeCamera)return;if(d.skipPointerMovePicking)return void this._processPointerMove(new r.p,e);d.pointerMovePredicate||(d.pointerMovePredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||d.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!d.cameraToUseForPointers||0!=(d.cameraToUseForPointers.layerMask&e.layerMask)));const t=d._registeredActions>0||d.constantlyUpdateMeshUnderPointer?this._pickMove(e):null;this._processPointerMove(t,e)},this._onPointerDown=e=>{var t;if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,p.ExclusiveDoubleClickMode)for(let s=0;se.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!d.cameraToUseForPointers||0!=(d.cameraToUseForPointers.layerMask&e.layerMask))),this._pickedDownMesh=null,i=d.skipPointerDownPicking||0===d._registeredActions&&!this._checkForPicking()&&!d.onPointerDown?new r.p:d.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,d.pointerDownPredicate,d.pointerDownFastCheck,d.cameraToUseForPointers),this._processPointerDown(i,e)},this._onPointerUp=e=>{0!==this._totalPointersPressed&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(e),d.preventDefaultOnPointerUp&&o&&(e.preventDefault(),o.focus()),this._initClickEvent(d.onPrePointerObservable,d.onPointerObservable,e,((t,i)=>{if(d.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!t.ignore)){if(this._checkPrePointerObservable(null,e,n.kD.POINTERUP))return void(this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1));t.hasSwiped||(t.singleClick&&d.onPrePointerObservable.hasSpecificMask(n.kD.POINTERTAP)&&this._checkPrePointerObservable(null,e,n.kD.POINTERTAP)&&(this._skipPointerTap=!0),t.doubleClick&&d.onPrePointerObservable.hasSpecificMask(n.kD.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,e,n.kD.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}this._pointerCaptures[e.pointerId]?(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1),(d.cameraToUseForPointers||d.activeCamera)&&(d.pointerUpPredicate||(d.pointerUpPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!d.cameraToUseForPointers||0!=(d.cameraToUseForPointers.layerMask&e.layerMask))),!this._meshPickProceed&&(s.O&&s.O.HasTriggers||this._checkForPicking()||d.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=l.OG.KEYDOWN;if(d.onPreKeyboardObservable.hasObservers()){const i=new l.WZ(t,e);if(d.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(d.onKeyboardObservable.hasObservers()){const i=new l.NG(t,e);d.onKeyboardObservable.notifyObservers(i,t)}d.actionManager&&d.actionManager.processTrigger(14,a.V.CreateNewFromScene(d,e))},this._onKeyUp=e=>{const t=l.OG.KEYUP;if(d.onPreKeyboardObservable.hasObservers()){const i=new l.WZ(t,e);if(d.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(d.onKeyboardObservable.hasObservers()){const i=new l.NG(t,e);d.onKeyboardObservable.notifyObservers(i,t)}d.actionManager&&d.actionManager.processTrigger(15,a.V.CreateNewFromScene(d,e))},this._deviceSourceManager.onDeviceConnectedObservable.add((n=>{n.deviceType===h.Yi.Mouse?n.onInputChangedObservable.add((s=>{s.inputIndex===h.Fz.LeftClick||s.inputIndex===h.Fz.MiddleClick||s.inputIndex===h.Fz.RightClick||s.inputIndex===h.Fz.BrowserBack||s.inputIndex===h.Fz.BrowserForward?t&&1===n.getInput(s.inputIndex)?this._onPointerDown(s):e&&0===n.getInput(s.inputIndex)&&this._onPointerUp(s):i&&(s.inputIndex===h.Fz.Move?this._onPointerMove(s):s.inputIndex!==h.Fz.MouseWheelX&&s.inputIndex!==h.Fz.MouseWheelY&&s.inputIndex!==h.Fz.MouseWheelZ||this._onPointerMove(s))})):n.deviceType===h.Yi.Touch?n.onInputChangedObservable.add((s=>{s.inputIndex===h.Fz.LeftClick&&(t&&1===n.getInput(s.inputIndex)?(this._onPointerDown(s),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&0===n.getInput(s.inputIndex)&&(this._onPointerUp(s),0===this._totalPointersPressed&&(this._isMultiTouchGesture=!1))),i&&s.inputIndex===h.Fz.Move&&this._onPointerMove(s)})):n.deviceType===h.Yi.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 s=this._meshUnderPointerId[t];let r;s&&(r=s._getActionManagerForTrigger(10),r&&r.processTrigger(10,a.V.CreateNew(s,n,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,r=e._getActionManagerForTrigger(9),r&&r.processTrigger(9,a.V.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]}}p.DragMovementThreshold=10,p.LongPressDelay=500,p.DoubleClickDelay=300,p.ExclusiveDoubleClickMode=!1},183:function(e,t,i){i.d(t,{m:function(){return n}});class n{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}n.FALLOFF_DEFAULT=0,n.FALLOFF_PHYSICAL=1,n.FALLOFF_GLTF=2,n.FALLOFF_STANDARD=3,n.LIGHTMAP_DEFAULT=0,n.LIGHTMAP_SPECULAR=1,n.LIGHTMAP_SHADOWSONLY=2,n.INTENSITYMODE_AUTOMATIC=0,n.INTENSITYMODE_LUMINOUSPOWER=1,n.INTENSITYMODE_LUMINOUSINTENSITY=2,n.INTENSITYMODE_ILLUMINANCE=3,n.INTENSITYMODE_LUMINANCE=4,n.LIGHTTYPEID_POINTLIGHT=0,n.LIGHTTYPEID_DIRECTIONALLIGHT=1,n.LIGHTTYPEID_SPOTLIGHT=2,n.LIGHTTYPEID_HEMISPHERICLIGHT=3},5458:function(e,t,i){i.d(t,{Z:function(){return n}});class n{static get ForceFullSceneLoadingForIncremental(){return n._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){n._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return n._ShowLoadingScreen}static set ShowLoadingScreen(e){n._ShowLoadingScreen=e}static get loggingLevel(){return n._LoggingLevel}static set loggingLevel(e){n._LoggingLevel=e}static get CleanBoneMatrixWeights(){return n._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){n._CleanBoneMatrixWeights=e}}n._ForceFullSceneLoadingForIncremental=!1,n._ShowLoadingScreen=!0,n._CleanBoneMatrixWeights=!1,n._LoggingLevel=0},4679:function(e,t,i){i.d(t,{S:function(){return n},l:function(){return o}});var n,s=i(8139),r=i(2931);!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"}(n||(n={}));class o extends r.a{get useMipMaps(){return this.generateMipMaps}set useMipMaps(e){this.generateMipMaps=e}get uniqueId(){return this._uniqueId}_setUniqueId(e){this._uniqueId=e}getEngine(){return this._engine}get source(){return this._source}constructor(e,t,i=!1){super(),this.isReady=!1,this.isCube=!1,this.is3D=!1,this.is2DArray=!1,this.isMultiview=!1,this.url="",this.generateMipMaps=!1,this.samples=0,this.type=-1,this.format=-1,this.onLoadedObservable=new s.y$,this.onErrorObservable=new s.y$,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=n.Unknown,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._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._engine=e,this._source=t,this._uniqueId=o._Counter++,i||(this._hardwareTexture=e._createHardwareTexture())}incrementReferences(){this._references++}updateSize(e,t,i=1){this._engine.updateTextureDimensions(this,e,t,i),this.width=e,this.height=t,this.depth=i,this.baseWidth=e,this.baseHeight=t,this.baseDepth=i,this._size=e*t*i}_rebuild(){var e;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 t;switch(this.source){case n.Temp:break;case n.Url:return void(t=this._engine.createTexture(null!==(e=this._originalUrl)&&void 0!==e?e: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 n.Raw:t=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,void 0,this._useSRGBBuffer),t._swapAndDie(this,!1),this.isReady=!0;break;case n.Raw3D:t=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),t._swapAndDie(this,!1),this.isReady=!0;break;case n.Raw2DArray:t=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),t._swapAndDie(this,!1),this.isReady=!0;break;case n.Dynamic:t=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),t._swapAndDie(this,!1),this._engine.updateDynamicTexture(this,this._engine.getRenderingCanvas(),this.invertY,void 0,void 0,!0);break;case n.Cube:return void(t=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,(()=>{t._swapAndDie(this,!1),this.isReady=!0}),null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer));case n.CubeRaw:t=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),t._swapAndDie(this,!1),this.isReady=!0;break;case n.CubeRawRGBD:return;case n.CubePrefiltered:return t=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(t._sphericalPolynomial=this._sphericalPolynomial)}}_swapAndDie(e,t=!0){var i;null===(i=this._hardwareTexture)||void 0===i||i.setUsage(e._source,this.generateMipMaps,this.isCube,this.width,this.height),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 n=this._engine.getLoadedTexturesCache();let s=n.indexOf(this);-1!==s&&n.splice(s,1),s=n.indexOf(e),-1===s&&n.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),0===this._references&&(this._engine._releaseTexture(this),this._hardwareTexture=null)}}o._Counter=0},2931:function(e,t,i){i.d(t,{a:function(){return n}});class n{get wrapU(){return this._cachedWrapU}set wrapU(e){this._cachedWrapU=e}get wrapV(){return this._cachedWrapV}set wrapV(e){this._cachedWrapV=e}get wrapR(){return this._cachedWrapR}set wrapR(e){this._cachedWrapR=e}get anisotropicFilteringLevel(){return this._cachedAnisotropicFilteringLevel}set anisotropicFilteringLevel(e){this._cachedAnisotropicFilteringLevel=e}get comparisonFunction(){return this._comparisonFunction}set comparisonFunction(e){this._comparisonFunction=e}get useMipMaps(){return this._useMipMaps}set useMipMaps(e){this._useMipMaps=e}constructor(){this.samplingMode=-1,this._useMipMaps=!0,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this._comparisonFunction=0}setParameters(e=1,t=1,i=1,n=1,s=2,r=0){return this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=i,this._cachedAnisotropicFilteringLevel=n,this.samplingMode=s,this._comparisonFunction=r,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}}},6181:function(e,t,i){function n(e){-1===e.indexOf("vClipPlane")&&e.push("vClipPlane"),-1===e.indexOf("vClipPlane2")&&e.push("vClipPlane2"),-1===e.indexOf("vClipPlane3")&&e.push("vClipPlane3"),-1===e.indexOf("vClipPlane4")&&e.push("vClipPlane4"),-1===e.indexOf("vClipPlane5")&&e.push("vClipPlane5"),-1===e.indexOf("vClipPlane6")&&e.push("vClipPlane6")}function s(e,t,i){var n,s,r,o,a,l;const h=!!(null!==(n=e.clipPlane)&&void 0!==n?n:t.clipPlane),c=!!(null!==(s=e.clipPlane2)&&void 0!==s?s:t.clipPlane2),d=!!(null!==(r=e.clipPlane3)&&void 0!==r?r:t.clipPlane3),u=!!(null!==(o=e.clipPlane4)&&void 0!==o?o:t.clipPlane4),p=!!(null!==(a=e.clipPlane5)&&void 0!==a?a:t.clipPlane5),f=!!(null!==(l=e.clipPlane6)&&void 0!==l?l:t.clipPlane6);h&&i.push("#define CLIPPLANE"),c&&i.push("#define CLIPPLANE2"),d&&i.push("#define CLIPPLANE3"),u&&i.push("#define CLIPPLANE4"),p&&i.push("#define CLIPPLANE5"),f&&i.push("#define CLIPPLANE6")}function r(e,t,i){var n,s,r,o,a,l;let h=!1;const c=!!(null!==(n=e.clipPlane)&&void 0!==n?n:t.clipPlane),d=!!(null!==(s=e.clipPlane2)&&void 0!==s?s:t.clipPlane2),u=!!(null!==(r=e.clipPlane3)&&void 0!==r?r:t.clipPlane3),p=!!(null!==(o=e.clipPlane4)&&void 0!==o?o:t.clipPlane4),f=!!(null!==(a=e.clipPlane5)&&void 0!==a?a:t.clipPlane5),_=!!(null!==(l=e.clipPlane6)&&void 0!==l?l:t.clipPlane6);return i.CLIPPLANE!==c&&(i.CLIPPLANE=c,h=!0),i.CLIPPLANE2!==d&&(i.CLIPPLANE2=d,h=!0),i.CLIPPLANE3!==u&&(i.CLIPPLANE3=u,h=!0),i.CLIPPLANE4!==p&&(i.CLIPPLANE4=p,h=!0),i.CLIPPLANE5!==f&&(i.CLIPPLANE5=f,h=!0),i.CLIPPLANE6!==_&&(i.CLIPPLANE6=_,h=!0),h}function o(e,t,i){var n,s,r,o,l,h;let c=null!==(n=t.clipPlane)&&void 0!==n?n:i.clipPlane;a(e,"vClipPlane",c),c=null!==(s=t.clipPlane2)&&void 0!==s?s:i.clipPlane2,a(e,"vClipPlane2",c),c=null!==(r=t.clipPlane3)&&void 0!==r?r:i.clipPlane3,a(e,"vClipPlane3",c),c=null!==(o=t.clipPlane4)&&void 0!==o?o:i.clipPlane4,a(e,"vClipPlane4",c),c=null!==(l=t.clipPlane5)&&void 0!==l?l:i.clipPlane5,a(e,"vClipPlane5",c),c=null!==(h=t.clipPlane6)&&void 0!==h?h:i.clipPlane6,a(e,"vClipPlane6",c)}function a(e,t,i){i&&e.setFloat4(t,i.normal.x,i.normal.y,i.normal.z,i.d)}i.d(t,{AN:function(){return r},an:function(){return o},lK:function(){return s},qx:function(){return n}})},4839:function(e,t,i){i.d(t,{U:function(){return o}});var n=i(1069),s=i(8137),r=i(2922);class o{constructor(){this._dirty=!0,this._tempColor=new r.HE(0,0,0,0),this._globalCurve=new r.HE(0,0,0,0),this._highlightsCurve=new r.HE(0,0,0,0),this._midtonesCurve=new r.HE(0,0,0,0),this._shadowsCurve=new r.HE(0,0,0,0),this._positiveCurve=new r.HE(0,0,0,0),this._negativeCurve=new r.HE(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}get globalHue(){return this._globalHue}set globalHue(e){this._globalHue=e,this._dirty=!0}get globalDensity(){return this._globalDensity}set globalDensity(e){this._globalDensity=e,this._dirty=!0}get globalSaturation(){return this._globalSaturation}set globalSaturation(e){this._globalSaturation=e,this._dirty=!0}get globalExposure(){return this._globalExposure}set globalExposure(e){this._globalExposure=e,this._dirty=!0}get highlightsHue(){return this._highlightsHue}set highlightsHue(e){this._highlightsHue=e,this._dirty=!0}get highlightsDensity(){return this._highlightsDensity}set highlightsDensity(e){this._highlightsDensity=e,this._dirty=!0}get highlightsSaturation(){return this._highlightsSaturation}set highlightsSaturation(e){this._highlightsSaturation=e,this._dirty=!0}get highlightsExposure(){return this._highlightsExposure}set highlightsExposure(e){this._highlightsExposure=e,this._dirty=!0}get midtonesHue(){return this._midtonesHue}set midtonesHue(e){this._midtonesHue=e,this._dirty=!0}get midtonesDensity(){return this._midtonesDensity}set midtonesDensity(e){this._midtonesDensity=e,this._dirty=!0}get midtonesSaturation(){return this._midtonesSaturation}set midtonesSaturation(e){this._midtonesSaturation=e,this._dirty=!0}get midtonesExposure(){return this._midtonesExposure}set midtonesExposure(e){this._midtonesExposure=e,this._dirty=!0}get shadowsHue(){return this._shadowsHue}set shadowsHue(e){this._shadowsHue=e,this._dirty=!0}get shadowsDensity(){return this._shadowsDensity}set shadowsDensity(e){this._shadowsDensity=e,this._dirty=!0}get shadowsSaturation(){return this._shadowsSaturation}set shadowsSaturation(e){this._shadowsSaturation=e,this._dirty=!0}get shadowsExposure(){return this._shadowsExposure}set shadowsExposure(e){this._shadowsExposure=e,this._dirty=!0}getClassName(){return"ColorCurves"}static Bind(e,t,i="vCameraColorCurvePositive",n="vCameraColorCurveNeutral",s="vCameraColorCurveNegative"){e._dirty&&(e._dirty=!1,e._getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e._getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e._getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e._getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(n,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(s,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}static PrepareUniforms(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}_getColorGradingDataToRef(e,t,i,n,s){null!=e&&(e=o._Clamp(e,0,360),t=o._Clamp(t,-100,100),i=o._Clamp(i,-100,100),n=o._Clamp(n,-100,100),t=o._ApplyColorGradingSliderNonlinear(t),t*=.5,n=o._ApplyColorGradingSliderNonlinear(n),t<0&&(t*=-1,e=(e+180)%360),o._FromHSBToRef(e,t,50+.25*n,s),s.scaleToRef(2,s),s.a=1+.01*i)}static _ApplyColorGradingSliderNonlinear(e){e/=100;let t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100,t}static _FromHSBToRef(e,t,i,n){let s=o._Clamp(e,0,360);const r=o._Clamp(t/100,0,1),a=o._Clamp(i/100,0,1);if(0===r)n.r=a,n.g=a,n.b=a;else{s/=60;const e=Math.floor(s),t=s-e,i=a*(1-r),o=a*(1-r*t),l=a*(1-r*(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 s.p4.Clone((()=>new o),this)}serialize(){return s.p4.Serialize(this)}static Parse(e){return s.p4.Parse((()=>new o),e,null,null)}}(0,n.gn)([(0,s.qC)()],o.prototype,"_globalHue",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_globalDensity",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_globalSaturation",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_globalExposure",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_highlightsHue",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_highlightsDensity",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_highlightsSaturation",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_highlightsExposure",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_midtonesHue",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_midtonesDensity",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_midtonesSaturation",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_midtonesExposure",void 0),s.p4._ColorCurvesParser=o.Parse},7050:function(e,t,i){i.d(t,{q:function(){return n}});class n{static IsWrapper(e){return void 0===e.getPipelineContext}static GetEffect(e){return void 0===e.getPipelineContext?e.effect:e}constructor(e,t=!0){this.effect=null,this.defines=null,this.drawContext=e.createDrawContext(),t&&(this.materialContext=e.createMaterialContext())}setEffect(e,t,i=!0){var n;this.effect=e,void 0!==t&&(this.defines=t),i&&(null===(n=this.drawContext)||void 0===n||n.reset())}dispose(){var e;null===(e=this.drawContext)||void 0===e||e.dispose()}}},4442:function(e,t,i){i.d(t,{Q:function(){return h}});var n=i(8139),s=i(1102),r=i(658),o=i(3525),a=i(1206),l=i(475);class h{static get ShadersRepository(){return a.v.ShadersRepository}static set ShadersRepository(e){a.v.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new n.y$),this._onBindObservable}constructor(e,t,i,r=null,c,d=null,u=null,p=null,f=null,_,m="",g=l.x.GLSL){var v,T,S;let E;this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new n.y$,this.onErrorObservable=new n.y$,this._onBindObservable=null,this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!1,this._wasPreviouslyUsingInstances=null,this._isDisposed=!1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this.name=e,this._key=m;let x,b,C=null;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=null!==(v=e.shaderLanguage)&&void 0!==v?v:l.x.GLSL,e.uniformBuffersNames){this._uniformBuffersNamesList=e.uniformBuffersNames.slice();for(let t=0;t{if(R[0]&&R[1]){A.isFragment=!0;const[t,i]=R;o.L.Process(i,A,((i,n)=>{this._fragmentSourceCodeBeforeMigration=n,C&&(i=C("fragment",i));const s=o.L.Finalize(t,i,A);A=null,this._useFinalCode(s.vertexCode,s.fragmentCode,e)}),this._engine)}};this._loadShader(x,"Vertex","",(e=>{o.L.Initialize(A),o.L.Process(e,A,((t,i)=>{this._rawVertexSourceCode=e,this._vertexSourceCodeBeforeMigration=i,C&&(t=C("vertex",t)),R[0]=t,P()}),this._engine)})),this._loadShader(b,"Fragment","Pixel",(e=>{this._rawFragmentSourceCode=e,R[1]=e,P()}))}_useFinalCode(e,t,i){if(i){const n=i.vertexElement||i.vertex||i.spectorName||i,s=i.fragmentElement||i.fragment||i.spectorName||i;this._vertexSourceCode=(this._shaderLanguage===l.x.WGSL?"//":"")+"#define SHADER_NAME vertex:"+n+"\n"+e,this._fragmentSourceCode=(this._shaderLanguage===l.x.WGSL?"//":"")+"#define SHADER_NAME fragment:"+s+"\n"+t}else this._vertexSourceCode=e,this._fragmentSourceCode=t;this._prepareEffect()}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch(e){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)}_loadShader(e,t,i,n){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement){return void n((0,s.v)(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 r=a.v.GetShadersStore(this._shaderLanguage);if(r[e+t+"Shader"])return void n(r[e+t+"Shader"]);if(i&&r[e+i+"Shader"])return void n(r[e+i+"Shader"]);let o;o="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:a.v.GetShadersRepository(this._shaderLanguage)+e,this._engine._loadFile(o+"."+t.toLowerCase()+".fx",n)}get vertexSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:null!==(t=null===(e=this._pipelineContext)||void 0===e?void 0:e._getVertexShaderCode())&&void 0!==t?t:this._vertexSourceCode}get fragmentSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:null!==(t=null===(e=this._pipelineContext)||void 0===e?void 0:e._getFragmentShaderCode())&&void 0!==t?t:this._fragmentSourceCode}get vertexSourceCodeBeforeMigration(){return this._vertexSourceCodeBeforeMigration}get fragmentSourceCodeBeforeMigration(){return this._fragmentSourceCodeBeforeMigration}get rawVertexSourceCode(){return this._rawVertexSourceCode}get rawFragmentSourceCode(){return this._rawFragmentSourceCode}_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{if(this._attributes=[],this._pipelineContext._fillEffectInformation(this,this._uniformBuffersNames,this._uniformsNames,this._uniforms,this._samplerList,this._samplers,e,this._attributes),e)for(let t=0;t=t&&(s=`Offending line [${t}] in ${i?"fragment":"vertex"} code: ${n[t-1]}`)}}return[e,s]}_processCompilationErrors(e,t=null){var i,n,s;this._compilationError=e.message;const o=this._attributesNames,a=this._fallbacks;if(r.Y.Error("Unable to compile effect:"),r.Y.Error("Uniforms: "+this._uniformsNames.map((function(e){return" "+e}))),r.Y.Error("Attributes: "+o.map((function(e){return" "+e}))),r.Y.Error("Defines:\r\n"+this.defines),h.LogShaderCodeOnCompilationError){let e=null,t=null,o=null;(null===(i=this._pipelineContext)||void 0===i?void 0:i._getVertexShaderCode())&&([o,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),o&&(r.Y.Error("Vertex code:"),r.Y.Error(o))),(null===(n=this._pipelineContext)||void 0===n?void 0:n._getFragmentShaderCode())&&([o,t]=this._getShaderCodeAndErrorLine(null===(s=this._pipelineContext)||void 0===s?void 0:s._getFragmentShaderCode(),this._compilationError,!0),o&&(r.Y.Error("Fragment code:"),r.Y.Error(o))),e&&r.Y.Error(e),t&&r.Y.Error(t)}r.Y.Error("Error: "+this._compilationError);const l=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,l()),a?(this._pipelineContext=null,a.hasMoreFallbacks?(this._allFallbacksProcessed=!1,r.Y.Error("Trying next fallback."),this.defines=a.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,l(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||l())}get isSupported(){return""===this._compilationError}_bindTexture(e,t){this._engine._bindTexture(this._samplers[e],t,e)}setTexture(e,t){this._engine.setTexture(this._samplers[e],this._uniforms[e],t,e)}setDepthStencilTexture(e,t){this._engine.setDepthStencilTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){const i=e+"Ex";if(-1===this._samplerList.indexOf(i+"0")){const n=this._samplerList.indexOf(e);for(let e=1;enew d),this)}serialize(){return s.p4.Serialize(this)}static Parse(e){const t=s.p4.Parse((()=>new d),e,null,null);return void 0!==e.vignetteCentreX&&(t.vignetteCenterX=e.vignetteCentreX),void 0!==e.vignetteCentreY&&(t.vignetteCenterY=e.vignetteCentreY),t}static get VIGNETTEMODE_MULTIPLY(){return this._VIGNETTEMODE_MULTIPLY}static get VIGNETTEMODE_OPAQUE(){return this._VIGNETTEMODE_OPAQUE}}d.TONEMAPPING_STANDARD=0,d.TONEMAPPING_ACES=1,d._VIGNETTEMODE_MULTIPLY=0,d._VIGNETTEMODE_OPAQUE=1,(0,n.gn)([(0,s.N$)()],d.prototype,"colorCurves",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_colorCurvesEnabled",void 0),(0,n.gn)([(0,s.oU)("colorGradingTexture")],d.prototype,"_colorGradingTexture",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_colorGradingEnabled",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_colorGradingWithGreenDepth",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_colorGradingBGR",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_exposure",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_toneMappingEnabled",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_toneMappingType",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_contrast",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"vignetteStretch",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"vignetteCenterX",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"vignetteCenterY",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"vignetteWeight",void 0),(0,n.gn)([(0,s.XX)()],d.prototype,"vignetteColor",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"vignetteCameraFov",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_vignetteBlendMode",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_vignetteEnabled",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_ditheringEnabled",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_ditheringIntensity",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_skipFinalColorClamp",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_applyByPostProcess",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_isEnabled",void 0),s.p4._ImageProcessingConfigurationParser=d.Parse},2067:function(e,t,i){i.d(t,{F:function(){return g}});var n=i(1069),s=i(8137),r=i(8658),o=i(8139),a=i(5953),l=i(4735),h=i(760),c=i(658),d=i(6504),u=i(2108),p=i(7050);class f{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=519,this.funcRef=1,this.funcMask=255,this.opStencilFail=7680,this.opDepthFail=7680,this.opStencilDepthPass=7681}get func(){return this._func}set func(e){this._func=e}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef=e}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask=e}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail=e}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail=e}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass=e}get mask(){return this._mask}set mask(e){this._mask=e}get enabled(){return this._enabled}set enabled(e){this._enabled=e}getClassName(){return"MaterialStencilState"}copyTo(e){s.p4.Clone((()=>e),this)}serialize(){return s.p4.Serialize(this)}parse(e,t,i){s.p4.Parse((()=>this),e,t,i)}}(0,n.gn)([(0,s.qC)()],f.prototype,"func",null),(0,n.gn)([(0,s.qC)()],f.prototype,"funcRef",null),(0,n.gn)([(0,s.qC)()],f.prototype,"funcMask",null),(0,n.gn)([(0,s.qC)()],f.prototype,"opStencilFail",null),(0,n.gn)([(0,s.qC)()],f.prototype,"opDepthFail",null),(0,n.gn)([(0,s.qC)()],f.prototype,"opStencilDepthPass",null),(0,n.gn)([(0,s.qC)()],f.prototype,"mask",null),(0,n.gn)([(0,s.qC)()],f.prototype,"enabled",null);var _=i(147),m=i(7545);class g{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(g.MiscDirtyFlag+g.PrePassDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(g.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(g.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 o.y$),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 o.y$),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new o.y$),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode!==e&&(this._alphaMode=e,this.markAsDirty(g.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(g.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case g.WireFrameFillMode:case g.LineListDrawMode:case g.LineLoopDrawMode:case g.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?g.WireFrameFillMode:g.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case g.PointFillMode:case g.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?g.PointFillMode:g.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(g.MiscDirtyFlag))}_getDrawWrapper(){return this._drawWrapper}_setDrawWrapper(e){this._drawWrapper=e}constructor(e,t,i){this.shadowDepthWrapper=null,this.allowShaderHotSwapping=!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.onCompiled=null,this.onError=null,this.getRenderTargetTextures=null,this.doNotSerialize=!1,this._storeEffectOnSubMeshes=!1,this.animations=null,this.onDisposeObservable=new o.y$,this._onDisposeObserver=null,this._onUnBindObservable=null,this._onBindObserver=null,this._alphaMode=2,this._needDepthPrePass=!1,this.disableDepthWrite=!1,this.disableColorWrite=!1,this.forceDepthWrite=!1,this.depthFunction=0,this.separateCullingPass=!1,this._fogEnabled=!0,this.pointSize=1,this.zOffset=0,this.zOffsetUnits=0,this.stencil=new f,this._useUBO=!1,this._fillMode=g.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||a.l.LastCreatedScene;n&&(this._scene=n,this._dirtyCallbacks={},this._dirtyCallbacks[1]=this._markAllSubMeshesAsTexturesDirty.bind(this),this._dirtyCallbacks[2]=this._markAllSubMeshesAsLightsDirty.bind(this),this._dirtyCallbacks[4]=this._markAllSubMeshesAsFresnelDirty.bind(this),this._dirtyCallbacks[8]=this._markAllSubMeshesAsAttributesDirty.bind(this),this._dirtyCallbacks[16]=this._markAllSubMeshesAsMiscDirty.bind(this),this._dirtyCallbacks[32]=this._markAllSubMeshesAsPrePassDirty.bind(this),this._dirtyCallbacks[63]=this._markAllSubMeshesAsAllDirty.bind(this),this.id=e||r.w1.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new p.q(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=g.ClockWiseSideOrientation:this.sideOrientation=g.CounterClockWiseSideOrientation,this._uniformBuffer=new h.M(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),g.OnEventObservable.notifyObservers(this,m.S.Created))}toString(e){return"Name: "+this.name}getClassName(){return"Material"}get _isMaterial(){return!0}get isFrozen(){return this.checkReadyOnlyOnce}freeze(){this.markDirty(),this.checkReadyOnlyOnce=!0}unfreeze(){this.markDirty(),this.checkReadyOnlyOnce=!1}isReady(e,t){return!0}isReadyForSubMesh(e,t,i){const 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}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===g.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===g.MATERIAL_OPAQUE||this._transparencyMode===g.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)t.getMaterial()===this&&t.effect&&(t.effect._wasPreviouslyReady=!1,t.effect._wasPreviouslyUsingInstances=null,t.effect._forceRebindOnNextCall=e);e&&this.markAsDirty(g.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),n=(null==t?this.sideOrientation:t)===g.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(m.S.PrepareUniformBuffer,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){const n=i.effect;n&&(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){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,u.G.BindSceneUniformBuffer(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(m.S.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(m.S.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(m.S.HasTexture,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){const i={};if(this._serializePlugins(i),g._parsePlugins(i,e,this._scene,t),this.pluginManager)for(const n of this.pluginManager._plugins){const t=e.pluginManager.getPlugin(n.name);n.copyTo(t)}}getBindedMeshes(){if(this.meshMap){const e=new Array;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 s=Object.assign({clipPlane:!1,useInstances:!1},i),r=this.getScene(),o=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const a=()=>{if(!this._scene||!this._scene.getEngine())return;const i=r.clipPlane;if(s.clipPlane&&(r.clipPlane=new d.J(0,0,0,1)),this._storeEffectOnSubMeshes){let i=!0,r=null;if(e.subMeshes){const t=new l.P(0,0,0,0,0,e,void 0,!1,!1);t.materialDefines&&(t.materialDefines._renderId=-1),this.isReadyForSubMesh(e,t,s.useInstances)||(t.effect&&t.effect.getCompilationError()&&t.effect.allFallbacksProcessed()?r=t.effect.getCompilationError():(i=!1,setTimeout(a,16)))}i&&(this.allowShaderHotSwapping=o,r&&n&&n(r),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=o,t&&t(this)):setTimeout(a,16);s.clipPlane&&(r.clipPlane=i)};a()}forceCompilationAsync(e,t){return new Promise(((i,n)=>{this.forceCompilation(e,(()=>{i()}),t,(e=>{n(e)}))}))}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(g._DirtyCallbackArray.length=0,e&g.TextureDirtyFlag&&g._DirtyCallbackArray.push(g._TextureDirtyCallBack),e&g.LightDirtyFlag&&g._DirtyCallbackArray.push(g._LightsDirtyCallBack),e&g.FresnelDirtyFlag&&g._DirtyCallbackArray.push(g._FresnelDirtyCallBack),e&g.AttributesDirtyFlag&&g._DirtyCallbackArray.push(g._AttributeDirtyCallBack),e&g.MiscDirtyFlag&&g._DirtyCallbackArray.push(g._MiscDirtyCallBack),e&g.PrePassDirtyFlag&&g._DirtyCallbackArray.push(g._PrePassDirtyCallBack),g._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(g._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(g._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(g._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(g._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(g._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(g._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(g._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(g._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(g._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(g._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(g._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==_.a.BackwardCompatible){this.checkReadyOnlyOnce=!0;const e=this._scene.onScenePerformancePriorityChangedObservable.addOnce((()=>{this.checkReadyOnlyOnce=!1}));this.onDisposeObservable.add((()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)}))}}setPrePassRenderer(e){return!1}dispose(e,t,i){const n=this.getScene();if(n.stopAnimation(this),n.freeProcessedMaterials(),n.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(m.S.Disposed,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 s in this.meshMap){const t=this.meshMap[s];t&&(t.material=null,this.releaseVertexArrayObject(t,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){if(e.geometry){const i=e.geometry;if(this._storeEffectOnSubMeshes)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=s.p4.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 c.Y.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=r.w1.Instantiate(e.customType).Parse(e,t,i);return n._loadedUniqueId=e.uniqueId,n}static _parsePlugins(e,t,i,n){var s;if(e.plugins)for(const o in e.plugins){const a=e.plugins[o];let l=null===(s=t.pluginManager)||void 0===s?void 0:s.getPlugin(a.name);if(!l){const e=r.w1.Instantiate("BABYLON."+o);e&&(l=new e(t))}null==l||l.parse(a,i,n)}}}g.TriangleFillMode=0,g.WireFrameFillMode=1,g.PointFillMode=2,g.PointListDrawMode=3,g.LineListDrawMode=4,g.LineLoopDrawMode=5,g.LineStripDrawMode=6,g.TriangleStripDrawMode=7,g.TriangleFanDrawMode=8,g.ClockWiseSideOrientation=0,g.CounterClockWiseSideOrientation=1,g.TextureDirtyFlag=1,g.LightDirtyFlag=2,g.FresnelDirtyFlag=4,g.AttributesDirtyFlag=8,g.MiscDirtyFlag=16,g.PrePassDirtyFlag=32,g.AllDirtyFlag=63,g.MATERIAL_OPAQUE=0,g.MATERIAL_ALPHATEST=1,g.MATERIAL_ALPHABLEND=2,g.MATERIAL_ALPHATESTANDBLEND=3,g.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,g.MATERIAL_NORMALBLENDMETHOD_RNM=1,g.OnEventObservable=new o.y$,g._AllDirtyCallBack=e=>e.markAllAsDirty(),g._ImageProcessingDirtyCallBack=e=>e.markAsImageProcessingDirty(),g._TextureDirtyCallBack=e=>e.markAsTexturesDirty(),g._FresnelDirtyCallBack=e=>e.markAsFresnelDirty(),g._MiscDirtyCallBack=e=>e.markAsMiscDirty(),g._PrePassDirtyCallBack=e=>e.markAsPrePassDirty(),g._LightsDirtyCallBack=e=>e.markAsLightDirty(),g._AttributeDirtyCallBack=e=>e.markAsAttributesDirty(),g._FresnelAndMiscDirtyCallBack=e=>{g._FresnelDirtyCallBack(e),g._MiscDirtyCallBack(e)},g._TextureAndMiscDirtyCallBack=e=>{g._TextureDirtyCallBack(e),g._MiscDirtyCallBack(e)},g._DirtyCallbackArray=[],g._RunDirtyCallBacks=e=>{for(const t of g._DirtyCallbackArray)t(e)},(0,n.gn)([(0,s.qC)()],g.prototype,"id",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"uniqueId",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"name",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"metadata",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"checkReadyOnEveryCall",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"checkReadyOnlyOnce",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"state",void 0),(0,n.gn)([(0,s.qC)("alpha")],g.prototype,"_alpha",void 0),(0,n.gn)([(0,s.qC)("backFaceCulling")],g.prototype,"_backFaceCulling",void 0),(0,n.gn)([(0,s.qC)("cullBackFaces")],g.prototype,"_cullBackFaces",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"sideOrientation",void 0),(0,n.gn)([(0,s.qC)("alphaMode")],g.prototype,"_alphaMode",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"_needDepthPrePass",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"disableDepthWrite",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"disableColorWrite",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"forceDepthWrite",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"depthFunction",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"separateCullingPass",void 0),(0,n.gn)([(0,s.qC)("fogEnabled")],g.prototype,"_fogEnabled",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"pointSize",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"zOffset",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"zOffsetUnits",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"pointsCloud",null),(0,n.gn)([(0,s.qC)()],g.prototype,"fillMode",null),(0,n.gn)([(0,s.qC)()],g.prototype,"transparencyMode",null)},4386:function(e,t,i){i.d(t,{H:function(){return n}});class n{constructor(e){if(this._keys=[],this._isDirty=!0,this._areLightsDirty=!0,this._areLightsDisposed=!1,this._areAttributesDirty=!0,this._areTexturesDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!0,this._areImageProcessingDirty=!0,this._normals=!1,this._uvs=!1,this._needNormals=!1,this._needUVs=!1,this._externalProperties=e,e)for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&this._setDefaultValue(t)}get isDirty(){return this._isDirty}markAsProcessed(){this._isDirty=!1,this._areAttributesDirty=!1,this._areTexturesDirty=!1,this._areFresnelDirty=!1,this._areLightsDirty=!1,this._areLightsDisposed=!1,this._areMiscDirty=!1,this._arePrePassDirty=!1,this._areImageProcessingDirty=!1}markAsUnprocessed(){this._isDirty=!0}markAllAsDirty(){this._areTexturesDirty=!0,this._areAttributesDirty=!0,this._areLightsDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!1,this._areImageProcessingDirty=!0,this._isDirty=!0}markAsImageProcessingDirty(){this._areImageProcessingDirty=!0,this._isDirty=!0}markAsLightDirty(e=!1){this._areLightsDirty=!0,this._areLightsDisposed=this._areLightsDisposed||e,this._isDirty=!0}markAsAttributesDirty(){this._areAttributesDirty=!0,this._isDirty=!0}markAsTexturesDirty(){this._areTexturesDirty=!0,this._isDirty=!0}markAsFresnelDirty(){this._areFresnelDirty=!0,this._isDirty=!0}markAsMiscDirty(){this._areMiscDirty=!0,this._isDirty=!0}markAsPrePassDirty(){this._arePrePassDirty=!0,this._isDirty=!0}rebuild(){this._keys.length=0;for(const e of Object.keys(this))"_"!==e[0]&&this._keys.push(e);if(this._externalProperties)for(const e in this._externalProperties)-1===this._keys.indexOf(e)&&this._keys.push(e)}isEqual(e){if(this._keys.length!==e._keys.length)return!1;for(let t=0;tthis._setDefaultValue(e)))}_setDefaultValue(e){var t,i,n,s,r;const o=null!==(n=null===(i=null===(t=this._externalProperties)||void 0===t?void 0:t[e])||void 0===i?void 0:i.type)&&void 0!==n?n:typeof this[e],a=null===(r=null===(s=this._externalProperties)||void 0===s?void 0:s[e])||void 0===r?void 0:r.default;switch(o){case"number":this[e]=null!=a?a:0;break;case"string":this[e]=null!=a?a:"";break;default:this[e]=null!=a&&a}}toString(){let e="";for(let t=0;t0,t.NUM_MORPH_INFLUENCERS=i.numInfluencers,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)}static PrepareDefinesForBakedVertexAnimation(e,t){const i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!(!i||!i.isEnabled)}static PrepareDefinesForAttributes(e,t,i,n,s=!1,r=!0,o=!0){if(!t._areAttributesDirty&&t._needNormals===t._normals&&t._needUVs===t._uvs)return!1;t._normals=t._needNormals,t._uvs=t._needUVs,t.NORMAL=t._needNormals&&e.isVerticesDataPresent(a.o.NormalKind),t._needNormals&&e.isVerticesDataPresent(a.o.TangentKind)&&(t.TANGENT=!0);for(let a=1;a<=6;++a)t["UV"+a]=!!t._needUVs&&e.isVerticesDataPresent(`uv${1===a?"":a}`);if(i){const i=e.useVertexColors&&e.isVerticesDataPresent(a.o.ColorKind);t.VERTEXCOLOR=i,t.VERTEXALPHA=e.hasVertexAlpha&&i&&r}return e.isVerticesDataPresent(a.o.ColorInstanceKind)&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),n&&this.PrepareDefinesForBones(e,t),s&&this.PrepareDefinesForMorphTargets(e,t),o&&this.PrepareDefinesForBakedVertexAnimation(e,t),!0}static PrepareDefinesForMultiview(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()}}static PrepareDefinesForOIT(e,t,i){const n=t.ORDER_INDEPENDENT_TRANSPARENCY,s=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&i,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,n===t.ORDER_INDEPENDENT_TRANSPARENCY&&s===t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS||t.markAsUnprocessed()}static PrepareDefinesForPrePass(e,t,i){const n=t.PREPASS;if(!t._arePrePassDirty)return;const s=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(e.prePassRenderer&&e.prePassRenderer.enabled&&i){t.PREPASS=!0,t.SCENE_MRT_COUNT=e.prePassRenderer.mrtCount;for(let i=0;i0&&(o.shadowEnabled=!0,t.prepareDefines(s,n))}}i.lightmapMode!=l.m.LIGHTMAP_DEFAULT?(o.lightmapMode=!0,s["LIGHTMAPEXCLUDED"+n]=!0,s["LIGHTMAPNOSPECULAR"+n]=i.lightmapMode==l.m.LIGHTMAP_SHADOWSONLY):(s["LIGHTMAPEXCLUDED"+n]=!1,s["LIGHTMAPNOSPECULAR"+n]=!1)}static PrepareDefinesForLights(e,t,i,n,s=4,r=!1){if(!i._areLightsDirty)return i._needNormals;let o=0;const a={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!r)for(const h of t.lightSources)if(this.PrepareDefinesForLight(e,t,h,o,i,n,a),o++,o===s)break;i.SPECULARTERM=a.specularEnabled,i.SHADOWS=a.shadowEnabled;for(let h=o;h0&&(s=n+r,t.addFallback(s,"LIGHT"+r)),e.SHADOWS||(e["SHADOW"+r]&&t.addFallback(n,"SHADOW"+r),e["SHADOWPCF"+r]&&t.addFallback(n,"SHADOWPCF"+r),e["SHADOWPCSS"+r]&&t.addFallback(n,"SHADOWPCSS"+r),e["SHADOWPOISSON"+r]&&t.addFallback(n,"SHADOWPOISSON"+r),e["SHADOWESM"+r]&&t.addFallback(n,"SHADOWESM"+r),e["SHADOWCLOSEESM"+r]&&t.addFallback(n,"SHADOWCLOSEESM"+r));return s++}static PrepareAttributesForMorphTargetsInfluencers(e,t,i){this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS=i,this.PrepareAttributesForMorphTargets(e,t,this._TmpMorphInfluencers)}static PrepareAttributesForMorphTargets(e,t,i){const s=i.NUM_MORPH_INFLUENCERS;if(s>0&&o.l.LastCreatedEngine){const r=o.l.LastCreatedEngine.getCaps().maxVertexAttribs,l=t.morphTargetManager;if(null==l?void 0:l.isUsingTextureForTargets)return;const h=l&&l.supportsNormals&&i.NORMAL,c=l&&l.supportsTangents&&i.TANGENT,d=l&&l.supportsUVs&&i.UV1;for(let i=0;ir&&n.Y.Error("Cannot add more vertex attributes for mesh "+t.name)}}static PrepareAttributesForBakedVertexAnimation(e,t,i){i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES&&e.push("bakedVertexAnimationSettingsInstanced")}static PrepareAttributesForBones(e,t,i,n){i.NUM_BONE_INFLUENCERS>0&&(n.addCPUSkinningFallback(0,t),e.push(a.o.MatricesIndicesKind),e.push(a.o.MatricesWeightsKind),i.NUM_BONE_INFLUENCERS>4&&(e.push(a.o.MatricesIndicesExtraKind),e.push(a.o.MatricesWeightsExtraKind)))}static PrepareAttributesForInstances(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&this.PushAttributesForInstances(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push(a.o.ColorInstanceKind)}static PushAttributesForInstances(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"))}static BindLightProperties(e,t,i){e.transferToEffect(t,i+"")}static BindLight(e,t,i,n,s,r=!0){e._bindLight(t,i,n,s,r)}static BindLights(e,t,i,n,s=4){const r=Math.min(t.lightSources.length,s);for(let o=0;o-1){const i=n.getTransformMatrixTexture(e);t.setTexture("boneSampler",i),t.setFloat("boneTextureWidth",4*(n.bones.length+1))}else{const s=n.getTransformMatrices(e);s&&(t.setMatrices("mBones",s),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(2)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=s.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),d._CopyBonesTransformationMatrices(s,i.previousBones[e.uniqueId])))}}}static _CopyBonesTransformationMatrices(e,t){return t.set(e),t}static BindMorphTargetParameters(e,t){const i=e.morphTargetManager;e&&i&&t.setFloatArray("morphTargetInfluences",i.influences)}static BindLogDepth(e,t,i){if(!e||e.LOGARITHMICDEPTH||e.indexOf&&e.indexOf("LOGARITHMICDEPTH")>=0){const e=i.activeCamera;e.mode===s.V.ORTHOGRAPHIC_CAMERA&&n.Y.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(e.maxZ+1)/Math.LN2))}}}d._TmpMorphInfluencers={NUM_MORPH_INFLUENCERS:0},d._TempFogColor=h.Wo.Black()},7545:function(e,t,i){var n;i.d(t,{S:function(){return n}}),function(e){e[e.Created=1]="Created",e[e.Disposed=2]="Disposed",e[e.GetDefineNames=4]="GetDefineNames",e[e.PrepareUniformBuffer=8]="PrepareUniformBuffer",e[e.IsReadyForSubMesh=16]="IsReadyForSubMesh",e[e.PrepareDefines=32]="PrepareDefines",e[e.BindForSubMesh=64]="BindForSubMesh",e[e.PrepareEffect=128]="PrepareEffect",e[e.GetAnimatables=256]="GetAnimatables",e[e.GetActiveTextures=512]="GetActiveTextures",e[e.HasTexture=1024]="HasTexture",e[e.FillRenderTargetTextures=2048]="FillRenderTargetTextures",e[e.HasRenderTargetTextures=4096]="HasRenderTargetTextures",e[e.HardBindForSubMesh=8192]="HardBindForSubMesh"}(n||(n={}))},8058:function(e,t,i){i.d(t,{G:function(){return o}});var n=i(2067),s=i(4104),r=i(646);class o extends n.F{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=new Array,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 s=i.apply(e,[t,n]);return this._markAllSubMeshesAsTexturesDirty(),s}}getSubMaterial(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]}getActiveTextures(){return super.getActiveTextures().concat(...this.subMaterials.map((e=>e?e.getActiveTextures():[])))}hasTexture(e){var t;if(super.hasTexture(e))return!0;for(let i=0;i=0&&n.multiMaterials.splice(s,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new o(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,s.$&&s.$.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach((e=>i.subMaterials.push(t.getLastMaterialById(e)))),i}}(0,r.H)("BABYLON.MultiMaterial",o)},475:function(e,t,i){var n;i.d(t,{x:function(){return n}}),function(e){e[e.GLSL=0]="GLSL",e[e.WGSL=1]="WGSL"}(n||(n={}))},760:function(e,t,i){i.d(t,{M:function(){return r}});var n=i(658),s=i(8658);i(4507);class r{constructor(e,t,i,n,s=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||s,this._dynamic=i,this._name=null!=n?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 t=0;t0){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;e1&&this._buffers[this._bufferIndex][1]){if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1]))return this._needSync=!1,void(this._createBufferOnWrite=this._engine._features.trackUbosInFrame);this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1])}this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(r._UpdatedUbosInFrame[this._name]||(r._UpdatedUbosInFrame[this._name]=0),r._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}else this._createBufferOnWrite=this._engine._features.trackUbosInFrame;else this.create()}_createNewBuffer(){this._bufferIndex+10?(this._needSync=0!==this._bufferIndex,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,i){this._checkNewFrame();let r=this._uniformLocations[e];if(void 0===r){if(this._buffer)return void n.Y.Error("Cannot add an uniform after UBO has been created.");this.addUniform(e,i),r=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let n=0;n=0&&r<=1?(a=s,l=o):r>=1&&r<=2?(a=o,l=s):r>=2&&r<=3?(l=s,h=o):r>=3&&r<=4?(l=o,h=s):r>=4&&r<=5?(a=o,h=s):r>=5&&r<=6&&(a=s,h=o);const c=i-s;n.set(a+c,l+c,h+c)}static FromHSV(e,t,i){const n=new d(0,0,0);return d.HSVtoRGBToRef(e,t,i,n),n}static FromHexString(e){if("#"!==e.substring(0,1)||7!==e.length)return new d(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 d.FromInts(t,i,n)}static FromArray(e,t=0){return new d(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 d(e/255,t/255,i/255)}static Lerp(e,t,i){const n=new d(0,0,0);return d.LerpToRef(e,t,i,n),n}static LerpToRef(e,t,i,n){n.r=e.r+(t.r-e.r)*i,n.g=e.g+(t.g-e.g)*i,n.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,n,s){const r=s*s,o=s*r,a=2*o-3*r+1,l=-2*o+3*r,h=o-2*r+s,c=o-r,u=e.r*a+i.r*l+t.r*h+n.r*c,p=e.g*a+i.g*l+t.g*h+n.g*c,f=e.b*a+i.b*l+t.b*h+n.b*c;return new d(u,p,f)}static Hermite1stDerivative(e,t,i,n,s){const r=d.Black();return this.Hermite1stDerivativeToRef(e,t,i,n,s,r),r}static Hermite1stDerivativeToRef(e,t,i,n,s,r){const o=s*s;r.r=6*(o-s)*e.r+(3*o-4*s+1)*t.r+6*(-o+s)*i.r+(3*o-2*s)*n.r,r.g=6*(o-s)*e.g+(3*o-4*s+1)*t.g+6*(-o+s)*i.g+(3*o-2*s)*n.g,r.b=6*(o-s)*e.b+(3*o-4*s+1)*t.b+6*(-o+s)*i.b+(3*o-2*s)*n.b}static Red(){return new d(1,0,0)}static Green(){return new d(0,1,0)}static Blue(){return new d(0,0,1)}static Black(){return new d(0,0,0)}static get BlackReadOnly(){return d._BlackReadOnly}static White(){return new d(1,1,1)}static Purple(){return new d(.5,0,.5)}static Magenta(){return new d(1,0,1)}static Yellow(){return new d(1,1,0)}static Gray(){return new d(.5,.5,.5)}static Teal(){return new d(0,1,1)}static Random(){return new d(Math.random(),Math.random(),Math.random())}}d._BlackReadOnly=d.Black();class u{constructor(e=0,t=0,i=0,n=1){this.r=e,this.g=t,this.b=i,this.a=n}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}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 u.FromArrayToRef(e,t,this),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 u(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}subtract(e){return new u(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,this}scale(e){return new u(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,this}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,this}clampToRef(e=0,t=1,i){return i.r=n.R.Clamp(this.r,e,t),i.g=n.R.Clamp(this.g,e,t),i.b=n.R.Clamp(this.b,e,t),i.a=n.R.Clamp(this.a,e,t),this}multiply(e){return new u(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}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|0),e=397*e^(255*this.b|0),e=397*e^(255*this.a|0),e}clone(){return new u(this.r,this.g,this.b,this.a)}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)}toHexString(e=!1){const t=Math.round(255*this.r),i=Math.round(255*this.g),s=Math.round(255*this.b);if(e)return"#"+n.R.ToHex(t)+n.R.ToHex(i)+n.R.ToHex(s);const r=Math.round(255*this.a);return"#"+n.R.ToHex(t)+n.R.ToHex(i)+n.R.ToHex(s)+n.R.ToHex(r)}toLinearSpace(e=!1){const t=new u;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=l(this.r),e.g=l(this.g),e.b=l(this.b)):(e.r=a(this.r),e.g=a(this.g),e.b=a(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new u;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=c(this.r),e.g=c(this.g),e.b=c(this.b)):(e.r=h(this.r),e.g=h(this.g),e.b=h(this.b)),e.a=this.a,this}static FromHexString(e){if("#"!==e.substring(0,1)||9!==e.length&&7!==e.length)return new u(0,0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),n=parseInt(e.substring(5,7),16),s=9===e.length?parseInt(e.substring(7,9),16):255;return u.FromInts(t,i,n,s)}static Lerp(e,t,i){const n=new u(0,0,0,0);return u.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,n.a=e.a+(t.a-e.a)*i}static Hermite(e,t,i,n,s){const r=s*s,o=s*r,a=2*o-3*r+1,l=-2*o+3*r,h=o-2*r+s,c=o-r,d=e.r*a+i.r*l+t.r*h+n.r*c,p=e.g*a+i.g*l+t.g*h+n.g*c,f=e.b*a+i.b*l+t.b*h+n.b*c,_=e.a*a+i.a*l+t.a*h+n.a*c;return new u(d,p,f,_)}static Hermite1stDerivative(e,t,i,n,s){const r=new u;return this.Hermite1stDerivativeToRef(e,t,i,n,s,r),r}static Hermite1stDerivativeToRef(e,t,i,n,s,r){const o=s*s;r.r=6*(o-s)*e.r+(3*o-4*s+1)*t.r+6*(-o+s)*i.r+(3*o-2*s)*n.r,r.g=6*(o-s)*e.g+(3*o-4*s+1)*t.g+6*(-o+s)*i.g+(3*o-2*s)*n.g,r.b=6*(o-s)*e.b+(3*o-4*s+1)*t.b+6*(-o+s)*i.b+(3*o-2*s)*n.b,r.a=6*(o-s)*e.a+(3*o-4*s+1)*t.a+6*(-o+s)*i.a+(3*o-2*s)*n.a}static FromColor3(e,t=1){return new u(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new u(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 u(e/255,t/255,i/255,n/255)}static CheckColors4(e,t){if(e.length===3*t){const t=[];for(let i=0;inew u(0,0,0,0))),(0,o.H)("BABYLON.Color3",d),(0,o.H)("BABYLON.Color4",u)},4551:function(e,t,i){i.d(t,{Nn:function(){return s},Q_:function(){return r},kn:function(){return o},zp:function(){return n}});const n=1/2.2,s=2.2,r=(1+Math.sqrt(5))/2,o=.001},8952:function(e,t,i){i.d(t,{i:function(){return s}});var n=i(6504);class s{static GetPlanes(e){const t=[];for(let i=0;i<6;i++)t.push(new n.J(0,0,0,0));return s.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[2],t.normal.y=i[7]+i[6],t.normal.z=i[11]+i[10],t.d=i[15]+i[14],t.normalize()}static GetFarPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[2],t.normal.y=i[7]-i[6],t.normal.z=i[11]-i[10],t.d=i[15]-i[14],t.normalize()}static GetLeftPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[0],t.normal.y=i[7]+i[4],t.normal.z=i[11]+i[8],t.d=i[15]+i[12],t.normalize()}static GetRightPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[0],t.normal.y=i[7]-i[4],t.normal.z=i[11]-i[8],t.d=i[15]-i[12],t.normalize()}static GetTopPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[1],t.normal.y=i[7]-i[5],t.normal.z=i[11]-i[9],t.d=i[15]-i[13],t.normalize()}static GetBottomPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[1],t.normal.y=i[7]+i[5],t.normal.z=i[11]+i[9],t.d=i[15]+i[13],t.normalize()}static GetPlanesToRef(e,t){s.GetNearPlaneToRef(e,t[0]),s.GetFarPlaneToRef(e,t[1]),s.GetLeftPlaneToRef(e,t[2]),s.GetRightPlaneToRef(e,t[3]),s.GetTopPlaneToRef(e,t[4]),s.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(t[i].dotCoordinate(e)<0)return!1;return!0}}},7303:function(e,t,i){i.d(t,{k:function(){return l},y:function(){return a}});var n=i(1069),s=i(5412),r=i(8137);class o{static extractMinAndMaxIndexed(e,t,i,n,s,r){for(let o=i;o!Array.isArray(e)&&!Array.isArray(t)))],o,"extractMinAndMaxIndexed",null),(0,n.gn)([r.G6.filter(((...[e])=>!Array.isArray(e)))],o,"extractMinAndMax",null)},6504:function(e,t,i){i.d(t,{J:function(){return s}});var n=i(5412);class s{constructor(e,t,i,s){this.normal=new n.P(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new s(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){let e=this.normal.getHashCode();return e=397*e^(0|this.d),e}normalize(){const e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z);let t=0;return 0!==e&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this}transform(e){const t=s._TmpMatrix;e.invertToRef(t);const i=t.m,n=this.normal.x,r=this.normal.y,o=this.normal.z,a=this.d,l=n*i[0]+r*i[1]+o*i[2]+a*i[3],h=n*i[4]+r*i[5]+o*i[6]+a*i[7],c=n*i[8]+r*i[9]+o*i[10]+a*i[11],d=n*i[12]+r*i[13]+o*i[14]+a*i[15];return new s(l,h,c,d)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){const n=t.x-e.x,s=t.y-e.y,r=t.z-e.z,o=i.x-e.x,a=i.y-e.y,l=i.z-e.z,h=s*l-r*a,c=r*o-n*l,d=n*a-s*o,u=Math.sqrt(h*h+c*c+d*d);let p;return p=0!==u?1/u:0,this.normal.x=h*p,this.normal.y=c*p,this.normal.z=d*p,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return n.P.Dot(this.normal,e)<=t}signedDistanceTo(e){return n.P.Dot(e,this.normal)+this.d}static FromArray(e){return new s(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const n=new s(0,0,0,0);return n.copyFromPoints(e,t,i),n}static FromPositionAndNormal(e,t){const i=new s(0,0,0,0);return t.normalize(),i.normal=t,i.d=-(t.x*e.x+t.y*e.y+t.z*e.z),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){const s=-(t.x*e.x+t.y*e.y+t.z*e.z);return n.P.Dot(i,t)+s}}s._TmpMatrix=n.y3.Identity()},1226:function(e,t,i){i.d(t,{R:function(){return n}});class n{static WithinEpsilon(e,t,i=1401298e-51){return Math.abs(e-t)<=i}static ToHex(e){const t=e.toString(16);return e<=15?("0"+t).toUpperCase():t.toUpperCase()}static Sign(e){return 0===(e=+e)||isNaN(e)?e:e>0?1:-1}static Clamp(e,t=0,i=1){return Math.min(i,Math.max(t,e))}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=n.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){const i=n.Repeat(e,2*t);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let s=n.Clamp(i);return s=-2*s*s*s+3*s*s,t*s+e*(1-s)}static MoveTowards(e,t,i){let s=0;return s=Math.abs(t-e)<=i?t:e+n.Sign(t-e)*i,s}static MoveTowardsAngle(e,t,i){const s=n.DeltaAngle(e,t);let r=0;return-i180&&(s-=360),e+s*n.Clamp(i)}static InverseLerp(e,t,i){let s=0;return s=e!=t?n.Clamp((i-e)/(t-e)):0,s}static Hermite(e,t,i,n,s){const r=s*s,o=s*r;return e*(2*o-3*r+1)+i*(-2*o+3*r)+t*(o-2*r+s)+n*(o-r)}static Hermite1stDerivative(e,t,i,n,s){const r=s*s;return 6*(r-s)*e+(3*r-4*s+1)*t+6*(-r+s)*i+(3*r-2*s)*n}static RandomRange(e,t){return e===t?e:Math.random()*(t-e)+e}static RangeToPercent(e,t,i){return(e-t)/(i-t)}static PercentToRange(e,t,i){return(i-t)*e+t}static NormalizeRadians(e){return e-=n.TwoPi*Math.floor((e+Math.PI)/n.TwoPi)}static HCF(e,t){const i=e%t;return 0===i?t:n.HCF(t,i)}}n.TwoPi=2*Math.PI},470:function(e,t,i){i.d(t,{l:function(){return n}});class n{constructor(e,t,i,n){this.x=e,this.y=t,this.width=i,this.height=n}toGlobal(e,t){return new n(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 n(this.x,this.y,this.width,this.height)}}},4081:function(e,t,i){i.d(t,{M:function(){return s}});var n=i(1545);class s extends n.h{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}},5068:function(e,t,i){i.d(t,{x:function(){return x}});var n=i(8139),s=i(147),r=i(5412),o=i(8838),a=i(2186),l=i(2341),h=i(4179),c=i(318),d=i(2789),u=i(760),p=i(7901),f=i(9069),_=i(7303),m=i(2922),g=i(4551),v=i(5241),T=i(646);class S{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=r.P.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class E{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new S,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 p.a,this._enableDistantPicking=!1,this._rawBoundingInfo=null}}class x extends h.Y{static get BILLBOARDMODE_NONE(){return h.Y.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return h.Y.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return h.Y.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return h.Y.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return h.Y.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return h.Y.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 pointerOverDisableMeshTesting(){return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting}set pointerOverDisableMeshTesting(e){this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting=e}get renderingGroupId(){return this._internalAbstractMeshDataInfo._renderingGroupId}set renderingGroupId(e){this._internalAbstractMeshDataInfo._renderingGroupId=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){this._internalAbstractMeshDataInfo._material!==e&&(this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&(this.resetDrawCache(),this._unBindEffect()))}getMaterialForRenderPass(e){var t;return null===(t=this._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===t?void 0:t[e]}setMaterialForRenderPass(e,t){this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t}get receiveShadows(){return this._internalAbstractMeshDataInfo._receiveShadows}set receiveShadows(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())}get hasVertexAlpha(){return this._internalAbstractMeshDataInfo._hasVertexAlpha}set hasVertexAlpha(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())}get useVertexColors(){return this._internalAbstractMeshDataInfo._useVertexColors}set useVertexColors(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get numBoneInfluencers(){return this._internalAbstractMeshDataInfo._numBoneInfluencers}set numBoneInfluencers(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())}get applyFog(){return this._internalAbstractMeshDataInfo._applyFog}set applyFog(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())}get enableDistantPicking(){return this._internalAbstractMeshDataInfo._enableDistantPicking}set enableDistantPicking(e){this._internalAbstractMeshDataInfo._enableDistantPicking=e}get layerMask(){return this._internalAbstractMeshDataInfo._layerMask}set layerMask(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())}get collisionMask(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask}set collisionMask(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e}get collisionResponse(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse}set collisionResponse(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e}get collisionGroup(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup}set collisionGroup(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e}get surroundingMeshes(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes}set surroundingMeshes(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e}get lightSources(){return this._lightSources}get _positions(){return null}set skeleton(e){const t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()}get skeleton(){return this._internalAbstractMeshDataInfo._skeleton}constructor(e,t=null){switch(super(e,t,!1),this._internalAbstractMeshDataInfo=new E,this._waitingMaterialId=null,this.cullingStrategy=x.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new n.y$,this.onCollisionPositionChangeObservable=new n.y$,this.onMaterialChangedObservable=new n.y$,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=m.Wo.Red(),this.outlineWidth=.02,this.overlayColor=m.Wo.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 r.P(.5,1,.5),this.ellipsoidOffset=new r.P(0,0,0),this.edgesWidth=1,this.edgesColor=new m.HE(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 n.y$,this._onCollisionPositionChange=(e,t,i=null)=>{t.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>o.D.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 u.M(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case s.a.Aggressive:this.doNotSyncBoundingInfo=!0;case s.a.Intermediate: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!==h.Y.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 t of this.subMeshes)t._rebuild()}_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;it.markAsLightDirty(e)))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty((e=>e.markAsAttributesDirty()))}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty((e=>e.markAsMiscDirty()))}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}resetDrawCache(e){if(this.subMeshes)for(const t of this.subMeshes)t.resetDrawCache(e)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,n){return this}updateVerticesData(e,t,i,n){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){var e;return null!==(e=this.rawBoundingInfo)&&void 0!==e?e:this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return null!==this._boundingInfo}buildBoundingInfo(e,t,i){return this._boundingInfo=new d.j(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(a.o.MatricesIndicesKind)&&this.isVerticesDataPresent(a.o.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===h.Y.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 r.y3;(this.rotationQuaternion?this.rotationQuaternion:r._f.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(n);const s=r.P.Zero(),o=this.definedFacingForward?-1:1;return r.P.TransformCoordinatesFromFloatsToRef(e*o,t,i*o,n,s),s}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 r.P(e*n,t,i*n)}refreshBoundingInfo(e=!1,t=!1){return this._boundingInfo&&this._boundingInfo.isLocked||this._refreshBoundingInfo(this._getPositionData(e,t),null),this}_refreshBoundingInfo(e,t){if(e){const i=(0,_.k)(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new d.j(i.minimum,i.maximum)}if(this.subMeshes)for(let i=0;i0){const e=t.getPositions();e&&(i[s]+=(e[s]-i[s])*n)}}if(e++,n===a.o.PositionKind&&this._positions&&3===e){e=0;const n=3*t;this._positions[t++].copyFromFloats(i[n],i[n+1],i[n+2])}}}if(i&&e&&this.skeleton){const e=this.getVerticesData(a.o.MatricesIndicesKind),t=this.getVerticesData(a.o.MatricesWeightsKind);if(t&&e){const s=this.numBoneInfluencers>4,o=s?this.getVerticesData(a.o.MatricesIndicesExtraKind):null,l=s?this.getVerticesData(a.o.MatricesWeightsExtraKind):null,h=this.skeleton.getTransformMatrices(this),c=r.jp.Vector3[0],d=r.jp.Matrix[0],u=r.jp.Matrix[1];let p=0;for(let f=0;f0&&(r.y3.FromFloat32ArrayToRefScaled(h,Math.floor(16*e[p+_]),m,u),d.addToSelf(u));if(s)for(_=0;_<4;_++)m=l[p+_],m>0&&(r.y3.FromFloat32ArrayToRefScaled(h,Math.floor(16*o[p+_]),m,u),d.addToSelf(u));n===a.o.NormalKind?r.P.TransformNormalFromFloatsToRef(i[f],i[f+1],i[f+2],d,c):r.P.TransformCoordinatesFromFloatsToRef(i[f],i[f+1],i[f+2],d,c),c.toArray(i,f),n===a.o.PositionKind&&this._positions&&this._positions[f/3].copyFrom(c)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,a.o.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,a.o.PositionKind)}_getPositionData(e,t){var i;let n=this.getVerticesData(a.o.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),n&&(e&&this.skeleton||t&&this.morphTargetManager)){if(n=n.slice(),this._generatePointsArray(),this._positions){const e=this._positions;this._internalAbstractMeshDataInfo._positions=new Array(e.length);for(let t=0;t1||!n.IsGlobal)&&n.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){const n=this.getBoundingInfo(),s=e.getBoundingInfo();if(n.intersects(s,t))return!0;if(i)for(const r of this.getChildMeshes())if(r.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){var n;if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];const i=e.verticesStart,n=e.verticesStart+e.verticesCount;for(let s=i;s1&&!r._checkCollision(e)||this._collideForSubMesh(r,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=r.jp.Matrix[0],i=r.jp.Matrix[1];return r.y3.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,n=!1,s,o=!1){const a=new c.p,l=this.getClassName(),h="InstancedLinesMesh"===l||"LinesMesh"===l||"GreasedLineMesh"===l?this.intersectionThreshold:0,d=this.getBoundingInfo();if(!this.subMeshes)return a;if(!(o||e.intersectsSphere(d.boundingSphere,h)&&e.intersectsBox(d.boundingBox,h)))return a;if(n)return a.hit=!o,a.pickedMesh=o?null:this,a.distance=o?0:r.P.Distance(e.origin,d.boundingSphere.center),a.subMeshId=0,a;if(!this._generatePointsArray())return a;let u=null;const p=this._scene.getIntersectingSubMeshCandidates(this,e),f=p.length;let _=!1;for(let r=0;r1&&!n.canIntersects(e))continue;const s=n.intersects(e,this._positions,this.getIndices(),t,i);if(s&&(t||!u||s.distance{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 n=this.getScene().getEngine();if(null!==this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,n.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),n.wipeCaches(),this.getScene().removeMesh(this),this._parentContainer){const e=this._parentContainer.meshes.indexOf(this);e>-1&&this._parentContainer.meshes.splice(e,1),this._parentContainer=null}if(t&&this.material&&("MultiMaterial"===this.material.getClassName()?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i65535){t=!0;break}e.depthSortedIndices=t?new Uint32Array(i):new Uint16Array(i)}if(e.facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!e.facetDepthSortFrom){const t=this.getScene().activeCamera;e.facetDepthSortFrom=t?t.position:r.P.Zero()}e.depthSortedFacets=[];for(let t=0;tg.kn?s.maximum.x-s.minimum.x:g.kn,e.bbSize.y=s.maximum.y-s.minimum.y>g.kn?s.maximum.y-s.minimum.y:g.kn,e.bbSize.z=s.maximum.z-s.minimum.z>g.kn?s.maximum.z-s.minimum.z:g.kn;let o=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(o=o>e.bbSize.z?o:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/o),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/o),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/o),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=s,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),r.P.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,n&&l.x.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;ns.subDiv.max||o<0||o>s.subDiv.max||a<0||a>s.subDiv.max?null:s.facetPartitioning[r+s.subDiv.max*o+s.subDiv.max*s.subDiv.max*a]}getClosestFacetAtCoordinates(e,t,i,n,s=!1,o=!0){const a=this.getWorldMatrix(),l=r.jp.Matrix[5];a.invertToRef(l);const h=r.jp.Vector3[8];r.P.TransformCoordinatesFromFloatsToRef(e,t,i,l,h);const c=this.getClosestFacetAtLocalCoordinates(h.x,h.y,h.z,n,s,o);return n&&r.P.TransformCoordinatesFromFloatsToRef(n.x,n.y,n.z,a,n),c}getClosestFacetAtLocalCoordinates(e,t,i,n,s=!1,r=!0){let o=null,a=0,l=0,h=0,c=0,d=0,u=0,p=0,f=0;const _=this.getFacetLocalPositions(),m=this.getFacetLocalNormals(),g=this.getFacetsAtLocalCoordinates(e,t,i);if(!g)return null;let v,T,S,E=Number.MAX_VALUE,x=E;for(let b=0;b=0||s&&!r&&c<=0)&&(c=T.x*S.x+T.y*S.y+T.z*S.z,d=-(T.x*e+T.y*t+T.z*i-c)/(T.x*T.x+T.y*T.y+T.z*T.z),u=e+T.x*d,p=t+T.y*d,f=i+T.z*d,a=u-e,l=p-t,h=f-i,x=a*a+l*l+h*h,xe.emitter===this))}}x.OCCLUSION_TYPE_NONE=0,x.OCCLUSION_TYPE_OPTIMISTIC=1,x.OCCLUSION_TYPE_STRICT=2,x.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,x.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,x.CULLINGSTRATEGY_STANDARD=0,x.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,x.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,x.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,(0,T.H)("BABYLON.AbstractMesh",x)},4106:function(e,t,i){i.d(t,{Z:function(){return _}});var n=i(5412),s=i(2922),r=i(2341),o=i(2186),a=i(4735),l=i(5458),h=i(2789),c=i(8658),d=i(4104),u=i(7303),p=i(5953),f=i(6629);class _{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 _(_.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,n=!1,s=null){this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||p.l.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=n,i?this.setAllVerticesData(i,n):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),s&&(this.applyToMesh(s),s.computeWorldMatrix(!0)))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return 1===this.delayLoadState||0===this.delayLoadState}get doNotSerialize(){for(let e=0;e0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable)),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()}_notifyUpdate(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects();for(const t of this._meshes)t._markSubMeshesAsAttributesDirty()}load(e,t){2!==this.delayLoadState&&(this.isReady()?t&&t():(this.delayLoadState=2,this._queueLoad(e,t)))}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,(i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);const n=this._meshes,s=n.length;for(let e=0;e0){for(let t=0;t0){for(let e=0;e0){for(let e=0;e-1&&this._parentContainer.geometries.splice(e,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new r.x;t.indices=[];const i=this.getIndices();if(i)for(let r=0;r0){const n=new Float32Array(e,i.positionsAttrDesc.offset,i.positionsAttrDesc.count);t.setVerticesData(o.o.PositionKind,n,!1)}if(i.normalsAttrDesc&&i.normalsAttrDesc.count>0){const n=new Float32Array(e,i.normalsAttrDesc.offset,i.normalsAttrDesc.count);t.setVerticesData(o.o.NormalKind,n,!1)}if(i.tangetsAttrDesc&&i.tangetsAttrDesc.count>0){const n=new Float32Array(e,i.tangetsAttrDesc.offset,i.tangetsAttrDesc.count);t.setVerticesData(o.o.TangentKind,n,!1)}if(i.uvsAttrDesc&&i.uvsAttrDesc.count>0){const n=new Float32Array(e,i.uvsAttrDesc.offset,i.uvsAttrDesc.count);if(f.e.UseOpenGLOrientationForUV)for(let e=1;e0){const n=new Float32Array(e,i.uvs2AttrDesc.offset,i.uvs2AttrDesc.count);if(f.e.UseOpenGLOrientationForUV)for(let e=1;e0){const n=new Float32Array(e,i.uvs3AttrDesc.offset,i.uvs3AttrDesc.count);if(f.e.UseOpenGLOrientationForUV)for(let e=1;e0){const n=new Float32Array(e,i.uvs4AttrDesc.offset,i.uvs4AttrDesc.count);if(f.e.UseOpenGLOrientationForUV)for(let e=1;e0){const n=new Float32Array(e,i.uvs5AttrDesc.offset,i.uvs5AttrDesc.count);if(f.e.UseOpenGLOrientationForUV)for(let e=1;e0){const n=new Float32Array(e,i.uvs6AttrDesc.offset,i.uvs6AttrDesc.count);if(f.e.UseOpenGLOrientationForUV)for(let e=1;e0){const n=new Float32Array(e,i.colorsAttrDesc.offset,i.colorsAttrDesc.count);t.setVerticesData(o.o.ColorKind,n,!1,i.colorsAttrDesc.stride)}if(i.matricesIndicesAttrDesc&&i.matricesIndicesAttrDesc.count>0){const n=new Int32Array(e,i.matricesIndicesAttrDesc.offset,i.matricesIndicesAttrDesc.count),s=[];for(let e=0;e>8),s.push((16711680&t)>>16),s.push(t>>24&255)}t.setVerticesData(o.o.MatricesIndicesKind,s,!1)}if(i.matricesIndicesExtraAttrDesc&&i.matricesIndicesExtraAttrDesc.count>0){const n=new Int32Array(e,i.matricesIndicesExtraAttrDesc.offset,i.matricesIndicesExtraAttrDesc.count),s=[];for(let e=0;e>8),s.push((16711680&t)>>16),s.push(t>>24&255)}t.setVerticesData(o.o.MatricesIndicesExtraKind,s,!1)}if(i.matricesWeightsAttrDesc&&i.matricesWeightsAttrDesc.count>0){const n=new Float32Array(e,i.matricesWeightsAttrDesc.offset,i.matricesWeightsAttrDesc.count);t.setVerticesData(o.o.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>8),i.push((16711680&n)>>16),i.push(n>>24&255)}t.setVerticesData(o.o.MatricesIndicesKind,i,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(o.o.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const i=[];for(let t=0;t>8),i.push((16711680&n)>>16),i.push(n>>24&255)}t.setVerticesData(o.o.MatricesIndicesExtraKind,i,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(_._CleanMatricesWeights(e,t),t.setVerticesData(o.o.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(o.o.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let i=0;i-1))return;{const i=t.getScene().getLastSkeletonById(e.skeletonId);if(!i)return;n=i.bones.length}const s=t.getVerticesData(o.o.MatricesIndicesKind),r=t.getVerticesData(o.o.MatricesIndicesExtraKind),a=e.matricesWeights,h=e.matricesWeightsExtra,c=e.numBoneInfluencer,d=a.length;for(let o=0;oc-1)&&(t=c-1),e>i){const t=1/e;for(let e=0;e<4;e++)a[o+e]*=t;if(h)for(let e=0;e<4;e++)h[o+e]*=t}else t>=4?(h[o+t-4]=1-e,r[o+t-4]=n):(a[o+t]=1-e,s[o+t]=n)}t.setVerticesData(o.o.MatricesIndicesKind,s),e.matricesWeightsExtra&&t.setVerticesData(o.o.MatricesIndicesExtraKind,r)}static Parse(e,t,i){const s=new _(e.id,t,void 0,e.updatable);return s._loadedUniqueId=e.uniqueId,d.$&&d.$.AddTagsTo(s,e.tags),e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s._boundingInfo=new h.j(n.P.FromArray(e.boundingBoxMinimum),n.P.FromArray(e.boundingBoxMaximum)),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(o.o.UVKind),e.hasUVs2&&s._delayInfo.push(o.o.UV2Kind),e.hasUVs3&&s._delayInfo.push(o.o.UV3Kind),e.hasUVs4&&s._delayInfo.push(o.o.UV4Kind),e.hasUVs5&&s._delayInfo.push(o.o.UV5Kind),e.hasUVs6&&s._delayInfo.push(o.o.UV6Kind),e.hasColors&&s._delayInfo.push(o.o.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(o.o.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(o.o.MatricesWeightsKind),s._delayLoadingFunction=r.x.ImportVertexData):r.x.ImportVertexData(e,s),t.pushGeometry(s,!0),s}}},2341:function(e,t,i){i.d(t,{x:function(){return u}});var n=i(1069),s=i(5412),r=i(2186),o=i(9069),a=i(2922),l=i(658),h=i(8137),c=i(140),d=i(9714);class u{constructor(){this._applyTo=(0,c.vp)(this._applyToCoroutine.bind(this))}set(e,t){switch(e.length||l.Y.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case r.o.PositionKind:this.positions=e;break;case r.o.NormalKind:this.normals=e;break;case r.o.TangentKind:this.tangents=e;break;case r.o.UVKind:this.uvs=e;break;case r.o.UV2Kind:this.uvs2=e;break;case r.o.UV3Kind:this.uvs3=e;break;case r.o.UV4Kind:this.uvs4=e;break;case r.o.UV5Kind:this.uvs5=e;break;case r.o.UV6Kind:this.uvs6=e;break;case r.o.ColorKind:this.colors=e;break;case r.o.MatricesIndicesKind:this.matricesIndices=e;break;case r.o.MatricesWeightsKind:this.matricesWeights=e;break;case r.o.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case r.o.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){return this.positions&&(e.setVerticesData(r.o.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(r.o.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(r.o.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(r.o.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(r.o.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(r.o.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(r.o.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(r.o.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(r.o.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(r.o.ColorKind,this.colors,t),i&&(yield)),this.matricesIndices&&(e.setVerticesData(r.o.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(r.o.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(r.o.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(r.o.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),this}_update(e,t,i){return this.positions&&e.updateVerticesData(r.o.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(r.o.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(r.o.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(r.o.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(r.o.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(r.o.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(r.o.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(r.o.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(r.o.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(r.o.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(r.o.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(r.o.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(r.o.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(r.o.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,n=e.length){const r=s.jp.Vector3[0],o=s.jp.Vector3[1];for(let a=i;a({vertexData:e}))):[{vertexData:e}];return(0,c.s3)(this._mergeCoroutine(void 0,n,t,!1,i))}*_mergeCoroutine(e,t,i=!1,n,s){var o,a,l,h;this._validate();const c=t.map((e=>e.vertexData));for(const r of c)if(r._validate(),!this.normals!=!r.normals||!this.tangents!=!r.tangents||!this.uvs!=!r.uvs||!this.uvs2!=!r.uvs2||!this.uvs3!=!r.uvs3||!this.uvs4!=!r.uvs4||!this.uvs5!=!r.uvs5||!this.uvs6!=!r.uvs6||!this.colors!=!r.colors||!this.matricesIndices!=!r.matricesIndices||!this.matricesWeights!=!r.matricesWeights||!this.matricesIndicesExtra!=!r.matricesIndicesExtra||!this.matricesWeightsExtra!=!r.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes");const d=c.reduce(((e,t)=>{var i,n;return e+(null!==(n=null===(i=t.indices)||void 0===i?void 0:i.length)&&void 0!==n?n:0)}),null!==(a=null===(o=this.indices)||void 0===o?void 0:o.length)&&void 0!==a?a:0);let p=s||c.some((e=>e.indices===this.indices))?null===(l=this.indices)||void 0===l?void 0:l.slice():this.indices;if(d>0){let s=null!==(h=null==p?void 0:p.length)&&void 0!==h?h:0;if(p||(p=new Array(d)),p.length!==d){if(Array.isArray(p))p.length=d;else{const e=i||p instanceof Uint32Array?new Uint32Array(d):new Uint16Array(d);e.set(p),p=e}e&&e.determinant()<0&&u._FlipFaces(p,0,s)}let r=this.positions?this.positions.length/3:0;for(const{vertexData:e,transform:i}of t)if(e.indices){for(let t=0;t[e.vertexData.positions,e.transform]))),n&&(yield),this.normals=u._MergeElement(r.o.NormalKind,this.normals,e,t.map((e=>[e.vertexData.normals,e.transform]))),n&&(yield),this.tangents=u._MergeElement(r.o.TangentKind,this.tangents,e,t.map((e=>[e.vertexData.tangents,e.transform]))),n&&(yield),this.uvs=u._MergeElement(r.o.UVKind,this.uvs,e,t.map((e=>[e.vertexData.uvs,e.transform]))),n&&(yield),this.uvs2=u._MergeElement(r.o.UV2Kind,this.uvs2,e,t.map((e=>[e.vertexData.uvs2,e.transform]))),n&&(yield),this.uvs3=u._MergeElement(r.o.UV3Kind,this.uvs3,e,t.map((e=>[e.vertexData.uvs3,e.transform]))),n&&(yield),this.uvs4=u._MergeElement(r.o.UV4Kind,this.uvs4,e,t.map((e=>[e.vertexData.uvs4,e.transform]))),n&&(yield),this.uvs5=u._MergeElement(r.o.UV5Kind,this.uvs5,e,t.map((e=>[e.vertexData.uvs5,e.transform]))),n&&(yield),this.uvs6=u._MergeElement(r.o.UV6Kind,this.uvs6,e,t.map((e=>[e.vertexData.uvs6,e.transform]))),n&&(yield),this.colors=u._MergeElement(r.o.ColorKind,this.colors,e,t.map((e=>[e.vertexData.colors,e.transform]))),n&&(yield),this.matricesIndices=u._MergeElement(r.o.MatricesIndicesKind,this.matricesIndices,e,t.map((e=>[e.vertexData.matricesIndices,e.transform]))),n&&(yield),this.matricesWeights=u._MergeElement(r.o.MatricesWeightsKind,this.matricesWeights,e,t.map((e=>[e.vertexData.matricesWeights,e.transform]))),n&&(yield),this.matricesIndicesExtra=u._MergeElement(r.o.MatricesIndicesExtraKind,this.matricesIndicesExtra,e,t.map((e=>[e.vertexData.matricesIndicesExtra,e.transform]))),n&&(yield),this.matricesWeightsExtra=u._MergeElement(r.o.MatricesWeightsExtraKind,this.matricesWeightsExtra,e,t.map((e=>[e.vertexData.matricesWeightsExtra,e.transform]))),this}static _MergeElement(e,t,i,n){const s=n.filter((e=>null!==e[0]&&void 0!==e[0]));if(!t&&0==s.length)return t;if(!t)return this._MergeElement(e,s[0][0],s[0][1],s.slice(1));const o=s.reduce(((e,t)=>e+t[0].length),t.length),a=e===r.o.PositionKind?u._TransformVector3Coordinates:e===r.o.NormalKind?u._TransformVector3Normals:e===r.o.TangentKind?u._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const e=new Float32Array(o);e.set(t),i&&a(e,i,0,t.length);let n=t.length;for(const[t,i]of s)e.set(t,n),i&&a(e,i,n,t.length),n+=t.length;return e}{const e=new Array(o);for(let i=0;i{const i=r.o.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(r.o.PositionKind,this.positions),i=(i,n)=>{const s=e(i,n);if(s!==t)throw new Error("The "+i+"s element count ("+s+") does not match the positions count ("+t+")")};this.normals&&i(r.o.NormalKind,this.normals),this.tangents&&i(r.o.TangentKind,this.tangents),this.uvs&&i(r.o.UVKind,this.uvs),this.uvs2&&i(r.o.UV2Kind,this.uvs2),this.uvs3&&i(r.o.UV3Kind,this.uvs3),this.uvs4&&i(r.o.UV4Kind,this.uvs4),this.uvs5&&i(r.o.UV5Kind,this.uvs5),this.uvs6&&i(r.o.UV6Kind,this.uvs6),this.colors&&i(r.o.ColorKind,this.colors),this.matricesIndices&&i(r.o.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(r.o.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(r.o.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(r.o.MatricesWeightsExtraKind,this.matricesWeightsExtra)}serialize(){const e={};return this.positions&&(e.positions=this.positions),this.normals&&(e.normals=this.normals),this.tangents&&(e.tangents=this.tangents),this.uvs&&(e.uvs=this.uvs),this.uvs2&&(e.uvs2=this.uvs2),this.uvs3&&(e.uvs3=this.uvs3),this.uvs4&&(e.uvs4=this.uvs4),this.uvs5&&(e.uvs5=this.uvs5),this.uvs6&&(e.uvs6=this.uvs6),this.colors&&(e.colors=this.colors),this.matricesIndices&&(e.matricesIndices=this.matricesIndices,e.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=this.matricesWeights),this.matricesIndicesExtra&&(e.matricesIndicesExtra=this.matricesIndicesExtra,e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=this.matricesWeightsExtra),e.indices=this.indices,e}static ExtractFromMesh(e,t,i){return u._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return u._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const n=new u;return e.isVerticesDataPresent(r.o.PositionKind)&&(n.positions=e.getVerticesData(r.o.PositionKind,t,i)),e.isVerticesDataPresent(r.o.NormalKind)&&(n.normals=e.getVerticesData(r.o.NormalKind,t,i)),e.isVerticesDataPresent(r.o.TangentKind)&&(n.tangents=e.getVerticesData(r.o.TangentKind,t,i)),e.isVerticesDataPresent(r.o.UVKind)&&(n.uvs=e.getVerticesData(r.o.UVKind,t,i)),e.isVerticesDataPresent(r.o.UV2Kind)&&(n.uvs2=e.getVerticesData(r.o.UV2Kind,t,i)),e.isVerticesDataPresent(r.o.UV3Kind)&&(n.uvs3=e.getVerticesData(r.o.UV3Kind,t,i)),e.isVerticesDataPresent(r.o.UV4Kind)&&(n.uvs4=e.getVerticesData(r.o.UV4Kind,t,i)),e.isVerticesDataPresent(r.o.UV5Kind)&&(n.uvs5=e.getVerticesData(r.o.UV5Kind,t,i)),e.isVerticesDataPresent(r.o.UV6Kind)&&(n.uvs6=e.getVerticesData(r.o.UV6Kind,t,i)),e.isVerticesDataPresent(r.o.ColorKind)&&(n.colors=e.getVerticesData(r.o.ColorKind,t,i)),e.isVerticesDataPresent(r.o.MatricesIndicesKind)&&(n.matricesIndices=e.getVerticesData(r.o.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(r.o.MatricesWeightsKind)&&(n.matricesWeights=e.getVerticesData(r.o.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(r.o.MatricesIndicesExtraKind)&&(n.matricesIndicesExtra=e.getVerticesData(r.o.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(r.o.MatricesWeightsExtraKind)&&(n.matricesWeightsExtra=e.getVerticesData(r.o.MatricesWeightsExtraKind,t,i)),n.indices=e.getIndices(t,i),n}static CreateRibbon(e){throw(0,o.S)("ribbonBuilder")}static CreateBox(e){throw(0,o.S)("boxBuilder")}static CreateTiledBox(e){throw(0,o.S)("tiledBoxBuilder")}static CreateTiledPlane(e){throw(0,o.S)("tiledPlaneBuilder")}static CreateSphere(e){throw(0,o.S)("sphereBuilder")}static CreateCylinder(e){throw(0,o.S)("cylinderBuilder")}static CreateTorus(e){throw(0,o.S)("torusBuilder")}static CreateLineSystem(e){throw(0,o.S)("linesBuilder")}static CreateDashedLines(e){throw(0,o.S)("linesBuilder")}static CreateGround(e){throw(0,o.S)("groundBuilder")}static CreateTiledGround(e){throw(0,o.S)("groundBuilder")}static CreateGroundFromHeightMap(e){throw(0,o.S)("groundBuilder")}static CreatePlane(e){throw(0,o.S)("planeBuilder")}static CreateDisc(e){throw(0,o.S)("discBuilder")}static CreatePolygon(e,t,i,n,s,r,a){throw(0,o.S)("polygonBuilder")}static CreateIcoSphere(e){throw(0,o.S)("icoSphereBuilder")}static CreatePolyhedron(e){throw(0,o.S)("polyhedronBuilder")}static CreateCapsule(e={orientation:s.P.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw(0,o.S)("capsuleBuilder")}static CreateTorusKnot(e){throw(0,o.S)("torusKnotBuilder")}static ComputeNormals(e,t,i,n){let r=0,o=0,a=0,l=0,h=0,c=0,d=0,u=0,p=0,f=0,_=0,m=0,g=0,v=0,T=0,S=0,E=0,x=0,b=0,C=0,y=!1,A=!1,R=!1,P=!1,I=1,M=0,O=null;n&&(y=!!n.facetNormals,A=!!n.facetPositions,R=!!n.facetPartitioning,I=!0===n.useRightHandedSystem?-1:1,M=n.ratio||0,P=!!n.depthSort,O=n.distanceTo,P&&void 0===O&&(O=s.P.Zero()));let D=0,N=0,F=0,w=0;for(R&&n&&n.bbSize&&(D=n.subDiv.X*M/n.bbSize.x,N=n.subDiv.Y*M/n.bbSize.y,F=n.subDiv.Z*M/n.bbSize.z,w=n.subDiv.max*n.subDiv.max,n.facetPartitioning.length=0),r=0;r!Array.isArray(e)))],u,"_TransformVector3Coordinates",null),(0,n.gn)([h.G6.filter(((...[e])=>!Array.isArray(e)))],u,"_TransformVector3Normals",null),(0,n.gn)([h.G6.filter(((...[e])=>!Array.isArray(e)))],u,"_TransformVector4Normals",null),(0,n.gn)([h.G6.filter(((...[e])=>!Array.isArray(e)))],u,"_FlipFaces",null)},1298:function(e,t,i){i.d(t,{g:function(){return n}});class n{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}},4735:function(e,t,i){i.d(t,{P:function(){return l}});var n=i(2186),s=i(3573),r=i(2789),o=i(7303),a=i(7050);class l{get materialDefines(){var e;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:null===(e=this._getDrawWrapper())||void 0===e?void 0:e.defines}set materialDefines(e){var t;(null!==(t=this._mainDrawWrapperOverride)&&void 0!==t?t:this._getDrawWrapper(void 0,!0)).defines=e}_getDrawWrapper(e,t=!1){e=null!=e?e:this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new a.q(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){var i;t&&(null===(i=this._drawWrappers[e])||void 0===i||i.dispose()),this._drawWrappers[e]=void 0}get effect(){var e,t;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:null!==(t=null===(e=this._getDrawWrapper())||void 0===e?void 0:e.effect)&&void 0!==t?t:null}get _drawWrapper(){var e;return null!==(e=this._mainDrawWrapperOverride)&&void 0!==e?e:this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,n=!0){const s=this._drawWrapper;s.setEffect(e,t,n),void 0!==i&&(s.materialContext=i),e||(s.defines=null,s.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers){if(void 0!==e)return void this._removeDrawWrapper(e);for(const e of this._drawWrappers)null==e||e.dispose()}this._drawWrappers=[]}static AddToMesh(e,t,i,n,s,r,o,a=!0){return new l(e,t,i,n,s,r,o,a)}constructor(e,t,i,n,s,r,o,a=!0,l=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=n,this.indexCount=s,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=r,this._renderingMesh=o||r,l&&r.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=r.subMeshes.length-1,a&&(this.refreshBoundingInfo(),r.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.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){var t;const i=null!==(t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId))&&void 0!==t?t:this._renderingMesh.material;if(!i)return e?this._mesh.getScene().defaultMaterial:null;if(this._isMultiMaterial(i)){const e=i.getSubMaterial(this.materialIndex);return this._currentMaterial!==e&&(this._currentMaterial=e,this.resetDrawCache()),e}return i}_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(n.o.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;const t=this._renderingMesh.getIndices();let i;if(0===this.indexStart&&this.indexCount===t.length){const e=this._renderingMesh.getBoundingInfo();i={minimum:e.minimum.clone(),maximum:e.maximum.clone()}}else i=(0,o.y)(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new r.j(i.minimum,i.maximum),this}_checkCollision(e){return this.getBoundingInfo()._checkCollision(e)}updateBoundingInfo(e){let t=this.getBoundingInfo();return t||(this.refreshBoundingInfo(),t=this.getBoundingInfo()),t&&t.update(e),this}isInFrustum(e){const t=this.getBoundingInfo();return!!t&&t.isInFrustum(e,this._mesh.cullingStrategy)}isCompletelyInFrustum(e){const t=this.getBoundingInfo();return!!t&&t.isCompletelyInFrustum(e)}render(e){return this._renderingMesh.render(this,e,this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:void 0),this}_getLinesIndexBuffer(e,t){if(!this._linesIndexBuffer){const i=[];for(let t=this.indexStart;ta&&(a=e)}return new l(e,o,a-o+1,t,i,n,s,r)}}},4179:function(e,t,i){i.d(t,{Y:function(){return c}});var n=i(1069),s=i(8137),r=i(8139),o=i(5412),a=i(6387),l=i(5241);const h=o.y3.Compose(o.P.One(),o._f.FromEulerAngles(0,Math.PI,0),o.P.Zero());class c extends a.N{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=0!=(this._billboardMode&c.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!==c.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}get infiniteDistance(){return this._infiniteDistance}set infiniteDistance(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)}constructor(e,t=null,i=!0){super(e,t),this._forward=new o.P(0,0,1),this._up=new o.P(0,1,0),this._right=new o.P(1,0,0),this._position=o.P.Zero(),this._rotation=o.P.Zero(),this._rotationQuaternion=null,this._scaling=o.P.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=c.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=o.y3.Zero(),this._usePivotMatrix=!1,this._absolutePosition=o.P.Zero(),this._absoluteScaling=o.P.Zero(),this._absoluteRotationQuaternion=o._f.Identity(),this._pivotMatrix=o.y3.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new r.y$,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}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._isDirty=!0}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._isDirty=!0}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._isDirty=!0}get forward(){return o.P.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return o.P.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return o.P.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=o.y3.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return this._billboardMode===e.billboardMode&&this._billboardMode===c.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=o.y3.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){const n=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);n&&i&&i(this,n);for(const s of this.getChildTransformNodes(!0))s.instantiateHierarchy(n,t,i);return n}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||o._f.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=o.jp.Matrix[0];this.parent.getWorldMatrix().invertToRef(e),o.P.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=o.P.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=o.jp.Matrix[0];return this._localMatrix.invertToRef(e),o.P.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=o.P.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,n=0,s=l.T.LOCAL){const r=c._LookAtVectorCache,a=s===l.T.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(a,r),this.setDirection(r,t,i,n),s===l.T.WORLD&&this.parent)if(this.rotationQuaternion){const e=o.jp.Matrix[0];this.rotationQuaternion.toRotationMatrix(e);const t=o.jp.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.invert(),e.multiplyToRef(t,e),this.rotationQuaternion.fromRotationMatrix(e)}else{const e=o.jp.Quaternion[0];o._f.FromEulerVectorToRef(this.rotation,e);const t=o.jp.Matrix[0];e.toRotationMatrix(t);const i=o.jp.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=o.P.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return o.P.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,n=0){const s=-Math.atan2(e.z,e.x)+Math.PI/2,r=Math.sqrt(e.x*e.x+e.z*e.z),a=-Math.atan2(e.y,r);return this.rotationQuaternion?o._f.RotationYawPitchRollToRef(s+t,a+i,n,this.rotationQuaternion):(this.rotation.x=a+i,this.rotation.y=s+t,this.rotation.z=n),this}setPivotPoint(e,t=l.T.LOCAL){0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(t==l.T.WORLD){const t=o.jp.Matrix[0];i.invertToRef(t),e=o.P.TransformCoordinates(e,t)}return this.setPivotMatrix(o.y3.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=o.P.Zero();return this.getPivotPointToRef(e),e}getPivotPointToRef(e){return e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14],this}getAbsolutePivotPoint(){const e=o.P.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),o.P.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=o.jp.Quaternion[0],s=o.jp.Vector3[0],r=o.jp.Vector3[1],a=o.jp.Matrix[1];o.y3.IdentityToRef(a);const l=o.jp.Matrix[0];this.computeWorldMatrix(!0);let h=this.rotationQuaternion;return h||(h=c._TmpRotation,o._f.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,h)),o.y3.ComposeToRef(this.scaling,h,this.position,l),this.parent&&l.multiplyToRef(this.parent.computeWorldMatrix(!0),l),e&&(e.computeWorldMatrix(!0).invertToRef(a),l.multiplyToRef(a,l)),l.decompose(r,n,s,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(n):n.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(r),this.position.copyFrom(s),this.parent=e,i&&this.setPivotMatrix(o.y3.Identity()),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(),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&&i!==l.T.LOCAL){if(this.parent){const t=o.jp.Matrix[0];this.parent.getWorldMatrix().invertToRef(t),e=o.P.TransformNormal(e,t)}n=o._f.RotationAxisToRef(e,t,c._RotationAxisCache),n.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else n=o._f.RotationAxisToRef(e,t,c._RotationAxisCache),this.rotationQuaternion.multiplyToRef(n,this.rotationQuaternion);return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=o._f.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const n=o.jp.Vector3[0],s=o.jp.Vector3[1],r=o.jp.Vector3[2],a=o.jp.Quaternion[0],l=o.jp.Matrix[0],h=o.jp.Matrix[1],c=o.jp.Matrix[2],d=o.jp.Matrix[3];return e.subtractToRef(this.position,n),o.y3.TranslationToRef(n.x,n.y,n.z,l),o.y3.TranslationToRef(-n.x,-n.y,-n.z,h),o.y3.RotationAxisToRef(t,i,c),h.multiplyToRef(c,d),d.multiplyToRef(l,d),d.decompose(s,a,r),this.position.addInPlace(r),a.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const n=e.scale(t);if(i&&i!==l.T.LOCAL)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=o.jp.Quaternion[1],o._f.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,n));const s=o.jp.Quaternion[0];return o._f.RotationYawPitchRollToRef(t,e,i,s),n.multiplyInPlace(s),this.rotationQuaternion||n.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==c.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}computeWorldMatrix(e=!1,t=null){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;const i=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===i||this.isSynchronized()))return this._currentRenderId=i,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();const n=this._cache;n.pivotMatrixUpdated=!1,n.billboardMode=this.billboardMode,n.infiniteDistance=this.infiniteDistance,n.parent=this._parentNode,this._currentRenderId=i,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;const s=this._getEffectiveParent(),r=c._TmpScaling;let a,l=this._position;if(this._infiniteDistance&&!this.parent&&t){const e=t.getWorldMatrix(),i=new o.P(e.m[12],e.m[13],e.m[14]);l=c._TmpTranslation,l.copyFromFloats(this._position.x+i.x,this._position.y+i.y,this._position.z+i.z)}if(r.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(o._f.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))}}else a=c._TmpRotation,o._f.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,a);if(this._usePivotMatrix){const e=o.jp.Matrix[1];o.y3.ScalingToRef(r.x,r.y,r.z,e);const t=o.jp.Matrix[0];a.toRotationMatrix(t),this._pivotMatrix.multiplyToRef(e,o.jp.Matrix[4]),o.jp.Matrix[4].multiplyToRef(t,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(l.x,l.y,l.z)}else o.y3.ComposeToRef(r,a,l,this._localMatrix);if(s&&s.getWorldMatrix){if(e&&s.computeWorldMatrix(e),n.useBillboardPath){this._transformToBoneReferal?s.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),o.jp.Matrix[7]):o.jp.Matrix[7].copyFrom(s.getWorldMatrix());const e=o.jp.Vector3[5],t=o.jp.Vector3[6],i=o.jp.Quaternion[0];o.jp.Matrix[7].decompose(t,i,e),o.y3.ScalingToRef(t.x,t.y,t.z,o.jp.Matrix[7]),o.jp.Matrix[7].setTranslation(e),c.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(i,e),this._localMatrix.setTranslation(e)),this._localMatrix.multiplyToRef(o.jp.Matrix[7],this._worldMatrix)}else this._transformToBoneReferal?(this._localMatrix.multiplyToRef(s.getWorldMatrix(),o.jp.Matrix[6]),o.jp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)):this._localMatrix.multiplyToRef(s.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(n.useBillboardPath&&t&&this.billboardMode&&!n.useBillboardPosition){const e=o.jp.Vector3[0];if(this._worldMatrix.getTranslationToRef(e),o.jp.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&o.jp.Matrix[1].multiplyToRef(h,o.jp.Matrix[1]),o.jp.Matrix[1].setTranslationFromFloats(0,0,0),o.jp.Matrix[1].invertToRef(o.jp.Matrix[0]),(this.billboardMode&c.BILLBOARDMODE_ALL)!==c.BILLBOARDMODE_ALL){o.jp.Matrix[0].decompose(void 0,o.jp.Quaternion[0],void 0);const e=o.jp.Vector3[1];o.jp.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&c.BILLBOARDMODE_X)!==c.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&c.BILLBOARDMODE_Y)!==c.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&c.BILLBOARDMODE_Z)!==c.BILLBOARDMODE_Z&&(e.z=0),o.y3.RotationYawPitchRollToRef(e.y,e.x,e.z,o.jp.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(o.jp.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(o.jp.Vector3[0])}else if(n.useBillboardPath&&t&&n.useBillboardPosition){const e=o.jp.Vector3[0];this._worldMatrix.getTranslationToRef(e);const i=t.globalPosition;this._worldMatrix.invertToRef(o.jp.Matrix[1]);const n=o.jp.Vector3[1];o.P.TransformCoordinatesToRef(i,o.jp.Matrix[1],n),n.normalize();const s=-Math.atan2(n.z,n.x)+Math.PI/2,r=Math.sqrt(n.x*n.x+n.z*n.z),a=-Math.atan2(n.y,r);if(o._f.RotationYawPitchRollToRef(s,a,0,o.jp.Quaternion[0]),(this.billboardMode&c.BILLBOARDMODE_ALL)!==c.BILLBOARDMODE_ALL){const e=o.jp.Vector3[1];o.jp.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&c.BILLBOARDMODE_X)!==c.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&c.BILLBOARDMODE_Y)!==c.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&c.BILLBOARDMODE_Z)!==c.BILLBOARDMODE_Z&&(e.z=0),o.y3.RotationYawPitchRollToRef(e.y,e.x,e.z,o.jp.Matrix[0])}else o.y3.FromQuaternionToRef(o.jp.Quaternion[0],o.jp.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(o.jp.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(o.jp.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):s&&s._nonUniformScaling?this._updateNonUniformScalingState(s._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._isAbsoluteSynced=!1,this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=o.y3.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const e=this.getChildren();for(let t=0;tnew c(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;inew c(e.name,t)),e,t,i);return e.localMatrix?n.setPreTransformMatrix(o.y3.FromArray(e.localMatrix)):e.pivotMatrix&&n.setPivotMatrix(o.y3.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),n}getChildTransformNodes(e,t){const i=[];return this._getDescendants(i,e,(e=>(!t||t(e))&&e instanceof c)),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,s=null;t&&(this.rotationQuaternion?(s=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(n=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const r=this.getHierarchyBoundingVectors(e,i),o=r.max.subtract(r.min),a=Math.max(o.x,o.y,o.z);if(0===a)return this;const l=1/a;return this.scaling.scaleInPlace(l),t&&(this.rotationQuaternion&&s?this.rotationQuaternion.copyFrom(s):this.rotation&&n&&this.rotation.copyFrom(n)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}c.BILLBOARDMODE_NONE=0,c.BILLBOARDMODE_X=1,c.BILLBOARDMODE_Y=2,c.BILLBOARDMODE_Z=4,c.BILLBOARDMODE_ALL=7,c.BILLBOARDMODE_USE_POSITION=128,c.BillboardUseParentOrientation=!1,c._TmpRotation=o._f.Zero(),c._TmpScaling=o.P.Zero(),c._TmpTranslation=o.P.Zero(),c._LookAtVectorCache=new o.P(0,0,0),c._RotationAxisCache=new o._f,(0,n.gn)([(0,s.hd)("position")],c.prototype,"_position",void 0),(0,n.gn)([(0,s.hd)("rotation")],c.prototype,"_rotation",void 0),(0,n.gn)([(0,s.mv)("rotationQuaternion")],c.prototype,"_rotationQuaternion",void 0),(0,n.gn)([(0,s.hd)("scaling")],c.prototype,"_scaling",void 0),(0,n.gn)([(0,s.qC)("billboardMode")],c.prototype,"_billboardMode",void 0),(0,n.gn)([(0,s.qC)()],c.prototype,"scalingDeterminant",void 0),(0,n.gn)([(0,s.qC)("infiniteDistance")],c.prototype,"_infiniteDistance",void 0),(0,n.gn)([(0,s.qC)()],c.prototype,"ignoreNonUniformScaling",void 0),(0,n.gn)([(0,s.qC)()],c.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0)},5776:function(e,t,i){i.d(t,{q:function(){return n}});class n{static Eval(e,t){return"true"===(e=e.match(/\([^()]*\)/g)?e.replace(/\([^()]*\)/g,(e=>(e=e.slice(1,e.length-1),n._HandleParenthesisContent(e,t)))):n._HandleParenthesisContent(e,t))||"false"!==e&&n.Eval(e,t)}static _HandleParenthesisContent(e,t){let i;t=t||(e=>"true"===e);const s=e.split("||");for(const r in s)if(Object.prototype.hasOwnProperty.call(s,r)){let e=n._SimplifyNegation(s[r].trim());const o=e.split("&&");if(o.length>1)for(let s=0;s(e=e.replace(/[\s]/g,(()=>""))).length%2?"!":""))).trim())?e="false":"!false"===e&&(e="true"),e}}},2554:function(e,t,i){i.d(t,{B:function(){return n},M:function(){return r}});class n{static BuildArray(e,t){const i=[];for(let n=0;nfunction(e,t,i){const n=e[t];if("function"!=typeof n)return null;const s=function(){const n=e.length,r=s.previous.apply(e,arguments);return i(t,n),r};return n.next=s,s.previous=n,e[t]=s,()=>{const i=s.previous;if(!i)return;const n=s.next;n?(i.next=n,n.previous=i):(i.next=void 0,e[t]=i),s.next=void 0,s.previous=void 0}}(e,i,t)));return()=>{i.forEach((e=>{null==e||e()}))}}},140:function(e,t,i){function n(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(n){i(n)}}function s(e=25){let t;return(i,s,r)=>{const o=performance.now();void 0===t||o-t>e?(t=o,setTimeout((()=>{n(i,s,r)}),0)):n(i,s,r)}}function r(e,t,i,n,s){const r=()=>{let o;const a=e=>{e.done?i(e.value):void 0===o?o=!0:r()};do{o=void 0,s&&s.aborted?n(new Error("Aborted")):t(e,a,n),void 0===o&&(o=!1)}while(o)};r()}function o(e,t){let i;return r(e,n,(e=>i=e),(e=>{throw e}),t),i}function a(e,t,i){return new Promise(((n,s)=>{r(e,t,n,s,i)}))}function l(e,t){return(...i)=>o(e(...i),t)}i.d(t,{KO:function(){return s},WP:function(){return n},s3:function(){return o},sM:function(){return a},vp:function(){return l}})},8137:function(e,t,i){i.d(t,{G6:function(){return R},N$:function(){return S},QC:function(){return g},RR:function(){return T},VE:function(){return y},XX:function(){return E},hd:function(){return v},mv:function(){return b},n9:function(){return _},oQ:function(){return C},oU:function(){return f},p4:function(){return A},qC:function(){return p},qQ:function(){return m},rX:function(){return x},wz:function(){return u}});var n=i(4104),s=i(5412),r=i(9069),o=i(2922);const a={},l={},h=function(e,t,i,s={}){const r=e();n.$&&n.$.HasTags(t)&&n.$.AddTagsTo(r,n.$.GetTags(t,!0));const o=c(r),a={};for(const n in o){const e=o[n],l=t[n],h=e.type;if(null!=l&&("uniqueId"!==n||A.AllowLoadingUniqueId))switch(h){case 0:case 6:case 11:r[n]=l;break;case 1:s.cloneTexturesOnlyOnce&&a[l.uniqueId]?r[n]=a[l.uniqueId]:(r[n]=i||l.isRenderTarget?l:l.clone(),a[l.uniqueId]=r[n]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:r[n]=i?l:l.clone()}}return r};function c(e){const t=e.getClassName();if(l[t])return l[t];l[t]={};const i=l[t];let n=e,s=t;for(;s;){const e=a[s];for(const n in e)i[n]=e[n];let t,r=!1;do{if(t=Object.getPrototypeOf(n),!t.getClassName){r=!0;break}if(t.getClassName()!==s)break;n=t}while(t);if(r)break;s=t.getClassName(),n=t}return i}function d(e,t){return(i,n)=>{const s=function(e){const t=e.getClassName();return a[t]||(a[t]={}),a[t]}(i);s[n]||(s[n]={type:e,sourceName:t})}}function u(e,t=null){return function(e,t=null){return(i,n)=>{const s=t||"_"+n;Object.defineProperty(i,n,{get:function(){return this[s]},set:function(t){"function"==typeof this.equals&&this.equals(t)||this[s]!==t&&(this[s]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}(e,t)}function p(e){return d(0,e)}function f(e){return d(1,e)}function _(e){return d(2,e)}function m(e){return d(3,e)}function g(e){return d(4,e)}function v(e){return d(5,e)}function T(e){return d(6,e)}function S(e){return d(7,e)}function E(e){return d(8,e)}function x(e){return d(9,e)}function b(e){return d(10,e)}function C(e){return d(12,e)}function y(e){return d(11,e)}class A{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{let r=s;if("undefined"!=typeof _native&&_native[t]){const e=_native[t];r=n?(...t)=>n(...t)?e(...t):s(...t):e}return e[t]=r,r(...i)}}A.AllowLoadingUniqueId=!1,A._ImageProcessingConfigurationParser=e=>{throw(0,r.S)("ImageProcessingConfiguration")},A._FresnelParametersParser=e=>{throw(0,r.S)("FresnelParameters")},A._ColorCurvesParser=e=>{throw(0,r.S)("ColorCurves")},A._TextureParser=(e,t,i)=>{throw(0,r.S)("Texture")},R.filter=function(e){return(t,i,n)=>R(t,i,n,e)}},2827:function(e,t,i){i.d(t,{j:function(){return r}});var n=i(658);const s=(e,t)=>e?e.getClassName&&"Mesh"===e.getClassName()?null:!e.getClassName||"SubMesh"!==e.getClassName()&&"PhysicsBody"!==e.getClassName()?e.clone?e.clone():Array.isArray(e)?e.slice():null:e.clone(t):null;class r{static DeepCopy(e,t,i,r){const o=function(e){const t=[];do{Object.getOwnPropertyNames(e).forEach((function(e){-1===t.indexOf(e)&&t.push(e)}))}while(e=Object.getPrototypeOf(e));return t}(e);for(const l of o){if("_"===l[0]&&(!r||-1===r.indexOf(l)))continue;if(l.endsWith("Observable"))continue;if(i&&-1!==i.indexOf(l))continue;const o=e[l],h=typeof o;if("function"!==h)try{if("object"===h)if(o instanceof Uint8Array)t[l]=Uint8Array.from(o);else if(o instanceof Array){if(t[l]=[],o.length>0)if("object"==typeof o[0])for(let e=0;e(e.__proto__=t,e));const s={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class r extends n{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",n._setPrototypeOf(this,r.prototype)}}},9051:function(e,t,i){i.d(t,{$K:function(){return I},$M:function(){return E},FV:function(){return y},Ip:function(){return b},VL:function(){return R},eh:function(){return m},r6:function(){return x},rN:function(){return T},vP:function(){return C}});var n=i(4910),s=i(1102),r=i(8139),o=i(3392),a=i(5077),l=i(9714),h=i(8661),c=i(3525),d=i(9271),u=i(5953),p=i(658),f=i(9447);const _=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class m extends l.LH{constructor(e,t){super(e,l.SM.LoadFileError),this.name="LoadFileError",l.GU._setPrototypeOf(this,m.prototype),t instanceof n.g?this.request=t:this.file=t}}class g extends l.LH{constructor(e,t){super(e,l.SM.RequestFileError),this.request=t,this.name="RequestFileError",l.GU._setPrototypeOf(this,g.prototype)}}class v extends l.LH{constructor(e,t){super(e,l.SM.ReadFileError),this.file=t,this.name="ReadFileError",l.GU._setPrototypeOf(this,v.prototype)}}const T={DefaultRetryStrategy:a.b.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:e=>e},S=e=>e=e.replace(/#/gm,"%23"),E=(e,t)=>{if((!e||0!==e.indexOf("data:"))&&T.CorsBehavior)if("string"==typeof T.CorsBehavior||T.CorsBehavior instanceof String)t.crossOrigin=T.CorsBehavior;else{const i=T.CorsBehavior(e);i&&(t.crossOrigin=i)}},x=(e,t,i,n,s="",r)=>{var a;let l,c=!1;e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"undefined"!=typeof Blob&&"undefined"!=typeof URL?(l=URL.createObjectURL(new Blob([e],{type:s})),c=!0):l=`data:${s};base64,`+(0,h.Gh)(e):e instanceof Blob?(l=URL.createObjectURL(e),c=!0):(l=S(e),l=T.PreprocessUrl(e));const d=u.l.LastCreatedEngine,p=t=>{if(i){const n=l||e.toString();i(`Error while trying to load image: ${0===n.indexOf("http")||n.length<=128?n:n.slice(0,128)+"..."}`,t)}};if("undefined"==typeof Image||null!==(a=null==d?void 0:d._features.forceBitmapOverHTMLImageElement)&&void 0!==a&&a)return C(l,(n=>{d.createImageBitmap(new Blob([n],{type:s}),Object.assign({premultiplyAlpha:"none"},r)).then((e=>{t(e),c&&URL.revokeObjectURL(l)})).catch((t=>{i&&i("Error while trying to load image: "+e,t)}))}),void 0,n||void 0,!0,((e,t)=>{p(t)})),null;const f=new Image;E(l,f);const _=[],m=()=>{_.forEach((e=>{e.target.removeEventListener(e.name,e.handler)})),_.length=0};_.push({target:f,name:"load",handler:()=>{m(),t(f),c&&f.src&&URL.revokeObjectURL(f.src)}}),_.push({target:f,name:"error",handler:e=>{m(),p(e),c&&f.src&&URL.revokeObjectURL(f.src)}}),_.push({target:document,name:"securitypolicyviolation",handler:e=>{if(e.blockedURI!==f.src)return;m();const t=new Error(`CSP violation of policy ${e.effectiveDirective} ${e.blockedURI}. Current policy is ${e.originalPolicy}`);u.l.UseFallbackTexture=!1,p(t),c&&f.src&&URL.revokeObjectURL(f.src),f.src=""}}),_.forEach((e=>{e.target.addEventListener(e.name,e.handler)}));const g="blob:"===l.substring(0,5),v="data:"===l.substring(0,5),x=()=>{g||v?f.src=l:C(l,((e,t,i)=>{const n=new Blob([e],{type:!s&&i?i:s}),r=URL.createObjectURL(n);c=!0,f.src=r}),void 0,n||void 0,!0,((e,t)=>{p(t)}))},b=()=>{n&&n.loadImage(l,f)};if(!g&&!v&&n&&n.enableTexturesOffline)n.open(b,x);else{if(-1!==l.indexOf("file:")){const e=decodeURIComponent(l.substring(5).toLowerCase());if(o.X.FilesToLoad[e]&&"undefined"!=typeof URL){try{let t;try{t=URL.createObjectURL(o.X.FilesToLoad[e])}catch(y){t=URL.createObjectURL(o.X.FilesToLoad[e])}f.src=t,c=!0}catch(A){f.src=""}return f}}x()}return f},b=(e,t,i,n,s)=>{const o=new FileReader,a={onCompleteObservable:new r.y$,abort:()=>o.abort()};return o.onloadend=()=>a.onCompleteObservable.notifyObservers(a),s&&(o.onerror=()=>{s(new v(`Unable to read ${e.name}`,e))}),o.onload=e=>{t(e.target.result)},i&&(o.onprogress=i),n?o.readAsArrayBuffer(e):o.readAsText(e),a},C=(e,t,i,n,s,a,l)=>{if(e.name)return b(e,t,i,s,a?e=>{a(void 0,e)}:void 0);const h=e;if(-1!==h.indexOf("file:")){let e=decodeURIComponent(h.substring(5).toLowerCase());0===e.indexOf("./")&&(e=e.substring(2));const n=o.X.FilesToLoad[e];if(n)return b(n,t,i,s,a?e=>a(void 0,new m(e.message,e.file)):void 0)}const{match:c,type:d}=P(h);if(c){const e={onCompleteObservable:new r.y$,abort:()=>()=>{}};try{const e=s?I(h):M(h);t(e,void 0,d)}catch(u){a?a(void 0,u):p.Y.Error(u.message||"Failed to parse the Data URL")}return f.Q.SetImmediate((()=>{e.onCompleteObservable.notifyObservers(e)})),e}return y(h,((e,i)=>{t(e,null==i?void 0:i.responseURL,null==i?void 0:i.getResponseHeader("content-type"))}),i,n,s,a?e=>{a(e.request,new m(e.message,e.request))}:void 0,l)},y=(e,t,i,o,a,l,h)=>{e=S(e),e=T.PreprocessUrl(e);const c=T.BaseUrl+e;let d=!1;const u={onCompleteObservable:new r.y$,abort:()=>d=!0},f=()=>{let e,r=new n.g,o=null;const f=()=>{r&&(i&&r.removeEventListener("progress",i),e&&r.removeEventListener("readystatechange",e),r.removeEventListener("loadend",_))};let _=()=>{f(),u.onCompleteObservable.notifyObservers(u),u.onCompleteObservable.clear(),i=void 0,e=null,_=null,l=void 0,h=void 0,t=void 0};u.abort=()=>{d=!0,_&&_(),r&&r.readyState!==(XMLHttpRequest.DONE||4)&&r.abort(),null!==o&&(clearTimeout(o),o=null),r=null};const m=e=>{const t=e.message||"Unknown error";l&&r?l(new g(t,r)):p.Y.Error(t)},v=u=>{if(r){if(r.open("GET",c),h)try{h(r)}catch(p){return void m(p)}a&&(r.responseType="arraybuffer"),i&&r.addEventListener("progress",i),_&&r.addEventListener("loadend",_),e=()=>{if(!d&&r&&r.readyState===(XMLHttpRequest.DONE||4)){if(e&&r.removeEventListener("readystatechange",e),r.status>=200&&r.status<300||0===r.status&&(!(0,s.CG)()||A())){try{t&&t(a?r.response:r.responseText,r)}catch(p){m(p)}return}const i=T.DefaultRetryStrategy;if(i){const e=i(c,r,u);if(-1!==e)return f(),r=new n.g,void(o=setTimeout((()=>v(u+1)),e))}const h=new g("Error status: "+r.status+" "+r.statusText+" - Unable to load "+c,r);l&&l(h)}},r.addEventListener("readystatechange",e),r.send()}};v(0)};if(o&&o.enableSceneOffline){const n=e=>{e&&e.status>400?l&&l(e):f()},s=()=>{o&&o.loadFile(T.BaseUrl+e,(e=>{!d&&t&&t(e),u.onCompleteObservable.notifyObservers(u)}),i?e=>{!d&&i&&i(e)}:void 0,n,a)};o.open(s,n)}else f();return u},A=()=>"undefined"!=typeof location&&"file:"===location.protocol,R=e=>_.test(e),P=e=>{const t=_.exec(e);if(null===t||0===t.length)return{match:!1,type:""};return{match:!0,type:t[0].replace("data:","").replace("base64,","")}};function I(e){return(0,h.HQ)(e.split(",")[1])}const M=e=>(0,h.rP)(e.split(",")[1]);let O;d.B._FileToolsLoadImage=x,d.B._FileToolsLoadFile=C,c.L._FileToolsLoadFile=C;((e,t,i,n,s,r,o,a,l,h)=>{O={DecodeBase64UrlToBinary:e,DecodeBase64UrlToString:t,DefaultRetryStrategy:i.DefaultRetryStrategy,BaseUrl:i.BaseUrl,CorsBehavior:i.CorsBehavior,PreprocessUrl:i.PreprocessUrl,IsBase64DataUrl:n,IsFileURL:s,LoadFile:r,LoadImage:o,ReadFile:a,RequestFile:l,SetCorsBehavior:h},Object.defineProperty(O,"DefaultRetryStrategy",{get:function(){return i.DefaultRetryStrategy},set:function(e){i.DefaultRetryStrategy=e}}),Object.defineProperty(O,"BaseUrl",{get:function(){return i.BaseUrl},set:function(e){i.BaseUrl=e}}),Object.defineProperty(O,"PreprocessUrl",{get:function(){return i.PreprocessUrl},set:function(e){i.PreprocessUrl=e}}),Object.defineProperty(O,"CorsBehavior",{get:function(){return i.CorsBehavior},set:function(e){i.CorsBehavior=e}})})(I,M,T,R,A,C,x,b,y,E)},3392:function(e,t,i){i.d(t,{X:function(){return n}});class n{}n.FilesToLoad={}},3706:function(e,t,i){function n(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}i.d(t,{f:function(){return n}})},6448:function(e,t,i){i.d(t,{K:function(){return r}});var n=i(658),s=i(646);class r{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=(0,s.q)(e);if(t)return t;n.Y.Warn(e+" not found, you may have missed an import.");const i=e.split(".");let r=window||this;for(let n=0,s=i.length;ne<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){if(void 0!==i&&!n._CheckLimit(t,i))return;const s=n._FormatMessage(t),r=this._Levels[e];r.logFunc&&r.logFunc("BJS - "+s);const o=`
${s}

`;n._AddLogEntry(o),n._GenerateLimitMessage(t,e)}static get LogCache(){return n._LogCache}static ClearLogCache(){n._LogCache="",n._LogLimitOutputs={},n.errorsCount=0}static set LogLevels(e){n.Log=n._LogDisabled,n.Warn=n._LogDisabled,n.Error=n._LogDisabled,[n.MessageLogLevel,n.WarningLogLevel,n.ErrorLogLevel].forEach((t=>{if((e&t)===t){const e=this._Levels[t];n[e.name]=n._LogEnabled.bind(n,t)}}))}}n.NoneLogLevel=0,n.MessageLogLevel=1,n.WarningLogLevel=2,n.ErrorLogLevel=4,n.AllLogLevel=7,n.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",n._LogCache="",n._LogLimitOutputs={},n._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],n.errorsCount=0,n.Log=n._LogEnabled.bind(n,n.MessageLogLevel),n.Warn=n._LogEnabled.bind(n,n.WarningLogLevel),n.Error=n._LogEnabled.bind(n,n.ErrorLogLevel)},8139:function(e,t,i){i.d(t,{he:function(){return n},y$:function(){return r}});class n{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 s{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(){this._remove&&this._remove()}}class r{static FromPromise(e,t){const i=new r;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 n(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,n=null,r=!1){if(!e)return null;const o=new s(e,t,n);return o.unregisterOnNextCall=r,i?this._observers.unshift(o):this._observers.push(o),this._onObserverAdded&&this._onObserverAdded(o),this._hasNotified&&this.notifyIfTriggered&&void 0!==this._lastNotifiedValue&&this.notifyObserver(o,this._lastNotifiedValue),o._remove=()=>{this.remove(o)},o}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._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,s){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;const r=this._eventState;r.mask=t,r.target=i,r.currentTarget=n,r.skipNextObservers=!1,r.lastReturnValue=e,r.userInfo=s;for(const o of this._observers)if(!o._willBeUnregistered&&(o.mask&t&&(o.unregisterOnNextCall&&this._deferUnregister(o),o.scope?r.lastReturnValue=o.callback.apply(o.scope,[e,r]):r.lastReturnValue=o.callback(e,r)),r.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 r;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}}},8482:function(e,t,i){i.d(t,{z:function(){return s}});var n=i(9665);class s{get min(){return this._min}get max(){return this._max}get average(){return this._average}get lastSecAverage(){return this._lastSecAverage}get current(){return this._current}get total(){return this._totalAccumulated}get count(){return this._totalValueCount}constructor(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}fetchNewFrame(){this._totalValueCount++,this._current=0,this._lastSecValueCount++}addCount(e,t){s.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){s.Enabled&&(this._startMonitoringTime=n.F.Now)}endMonitoring(e=!0){if(!s.Enabled)return;e&&this.fetchNewFrame();const t=n.F.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=n.F.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}s.Enabled=!0},4441:function(e,t,i){i.d(t,{A:function(){return s}});var n=i(9665);class s{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new r(e)}sampleFrame(e=n.F.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 r{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}}},9665:function(e,t,i){i.d(t,{F:function(){return s}});var n=i(1102);class s{static get Now(){return n.MZ.IsWindowObjectExist()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}},5077:function(e,t,i){i.d(t,{b:function(){return n}});class n{static ExponentialBackoff(e=3,t=500){return(i,n,s)=>0!==n.status||s>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,s)*t}}},8173:function(e,t,i){i.d(t,{f:function(){return s},t:function(){return n}});class n{constructor(e){this.length=0,this.data=new Array(e),this._id=n._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;tthis.data.length&&(this.data.length=2*(this.length+e.length));for(let t=0;t=this.length?-1:t}contains(e){return-1!==this.indexOf(e)}}n._GlobalId=0;class s extends n{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;tthis.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}}},8661:function(e,t,i){i.d(t,{Gh:function(){return s},HQ:function(){return o},fJ:function(){return n},rP:function(){return r}});const n=e=>{if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let i=0;i{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let i,n,s,r,o,a,l,h="",c=0;const d=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(;c>2,o=(3&i)<<4|n>>4,a=(15&n)<<2|s>>6,l=63&s,isNaN(n)?a=l=64:isNaN(s)&&(l=64),h+=t.charAt(r)+t.charAt(o)+t.charAt(a)+t.charAt(l);return h},r=e=>atob(e),o=e=>{const t=r(e),i=t.length,n=new Uint8Array(new ArrayBuffer(i));for(let s=0;ss.HasTags(e),e.addTags=t=>s.AddTagsTo(e,t),e.removeTags=t=>s.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>s.MatchesQuery(e,t)}static DisableFor(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery}static HasTags(e){if(!e._tags)return!1;const t=e._tags;for(const i in t)if(Object.prototype.hasOwnProperty.call(t,i))return!0;return!1}static GetTags(e,t=!0){if(!e._tags)return null;if(t){const 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){s._AddTagTo(e,t)}))}static _AddTagTo(e,t){""!==(t=t.trim())&&"true"!==t&&"false"!==t&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(s.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!s.HasTags(e))return;const i=t.split(" ");for(const n in i)s._RemoveTagFrom(e,i[n])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return void 0===t||(""===t?s.HasTags(e):n.q.Eval(t,(t=>s.HasTags(e)&&e._tags[t])))}}},9447:function(e,t,i){i.d(t,{Q:function(){return s}});var n=i(1102);class s{static SetImmediate(e){(0,n.CG)()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}},8658:function(e,t,i){i.d(t,{$g:function(){return m},w1:function(){return _}});var n=i(8139),s=i(1102),r=i(658),o=i(2827),a=i(9665),l=i(9069),h=i(4910),c=i(5953),d=i(9051),u=i(9447),p=i(6448),f=i(3706);class _{static get BaseUrl(){return d.rN.BaseUrl}static set BaseUrl(e){d.rN.BaseUrl=e}static get DefaultRetryStrategy(){return d.rN.DefaultRetryStrategy}static set DefaultRetryStrategy(e){d.rN.DefaultRetryStrategy=e}static get CorsBehavior(){return d.rN.CorsBehavior}static set CorsBehavior(e){d.rN.CorsBehavior=e}static get UseFallbackTexture(){return c.l.UseFallbackTexture}static set UseFallbackTexture(e){c.l.UseFallbackTexture=e}static get RegisteredExternalClasses(){return p.K.RegisteredExternalClasses}static set RegisteredExternalClasses(e){p.K.RegisteredExternalClasses=e}static get fallbackTexture(){return c.l.FallbackTexture}static set fallbackTexture(e){c.l.FallbackTexture=e}static FetchToRef(e,t,i,n,s,r){const o=4*((Math.abs(e)*i%i|0)+(Math.abs(t)*n%n|0)*i);r.r=s[o]/255,r.g=s[o+1]/255,r.b=s[o+2]/255,r.a=s[o+3]/255}static Mix(e,t,i){return e*(1-i)+t*i}static Instantiate(e){return p.K.Instantiate(e)}static SetImmediate(e){u.Q.SetImmediate(e)}static IsExponentOfTwo(e){let t=1;do{t*=2}while(t{(0,d.vP)(e,(e=>{i(e)}),void 0,void 0,t,((e,t)=>{n(t)}))}))}static LoadScript(e,t,i,n){if("function"==typeof importScripts){try{importScripts(e),t()}catch(a){null==i||i(`Unable to load script '${e}' in worker`,a)}return}if(!(0,s.CG)())return void(null==i||i(`Cannot load script '${e}' outside of a window or a worker`));const r=document.getElementsByTagName("head")[0],o=document.createElement("script");o.setAttribute("type","text/javascript"),o.setAttribute("src",e),n&&(o.id=n),o.onload=()=>{t&&t()},o.onerror=t=>{i&&i(`Unable to load script '${e}'`,t)},r.appendChild(o)}static LoadScriptAsync(e){return new Promise(((t,i)=>{this.LoadScript(e,(()=>{t()}),((e,t)=>{i(t||new Error(e))}))}))}static ReadFileAsDataURL(e,t,i){const s=new FileReader,r={onCompleteObservable:new n.y$,abort:()=>s.abort()};return s.onloadend=()=>{r.onCompleteObservable.notifyObservers(r)},s.onload=e=>{t(e.target.result)},s.onprogress=i,s.readAsDataURL(e),r}static ReadFile(e,t,i,n,s){return(0,d.Ip)(e,t,i,n,s)}static FileAsURL(e){const t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,n){o.j.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 n=0;n{const n=atob(this.toDataURL(t,i).split(",")[1]),s=n.length,r=new Uint8Array(s);for(let e=0;et(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"}_.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,s){if("string"!=typeof n&&t){if(t){if(_._IsOffScreenCanvas(e))return void e.convertToBlob({type:i,quality:s}).then((e=>{const i=new FileReader;i.readAsDataURL(e),i.onloadend=()=>{const e=i.result;t(e)}}));const n=e.toDataURL(i,s);t(n)}}else this.ToBlob(e,(function(e){e&&_.DownloadBlob(e,n),t&&t("")}),i,s)}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,s="image/png",r=!1,o){throw(0,l.S)("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,n="image/png",s){throw(0,l.S)("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,n,s="image/png",r=1,o=!1,a,h=!1,c=!1,d=!0,u){throw(0,l.S)("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,n="image/png",s=1,r=!1,o,a=!1,h=!1,c=!0,d){throw(0,l.S)("ScreenshotTools")}static RandomId(){return(0,f.f)()}static IsBase64(e){return(0,d.VL)(e)}static DecodeBase64(e){return(0,d.$K)(e)}static get errorsCount(){return r.Y.errorsCount}static Log(e){r.Y.Log(e)}static Warn(e){r.Y.Warn(e)}static Error(e){r.Y.Error(e)}static get LogCache(){return r.Y.LogCache}static ClearLogCache(){r.Y.ClearLogCache()}static set LogLevels(e){r.Y.LogLevels=e}static set PerformanceLogLevel(e){return(e&_.PerformanceUserMarkLogLevel)===_.PerformanceUserMarkLogLevel?(_.StartPerformanceCounter=_._StartUserMark,void(_.EndPerformanceCounter=_._EndUserMark)):(e&_.PerformanceConsoleLogLevel)===_.PerformanceConsoleLogLevel?(_.StartPerformanceCounter=_._StartPerformanceConsole,void(_.EndPerformanceCounter=_._EndPerformanceConsole)):(_.StartPerformanceCounter=_._StartPerformanceCounterDisabled,void(_.EndPerformanceCounter=_._EndPerformanceCounterDisabled))}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!_._Performance){if(!(0,s.CG)())return;_._Performance=window.performance}t&&_._Performance.mark&&_._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){t&&_._Performance.mark&&(_._Performance.mark(e+"-End"),_._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(_._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(_._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return a.F.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 s=t?e:Object.getPrototypeOf(e);i=s.constructor.__bjsclassName__,n=s.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!!(0,s.up)()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}}_.UseCustomRequestHeaders=!1,_.CustomRequestHeaders=h.g.CustomRequestHeaders,_._TmpFloatArray=new Float32Array(1),_.GetDOMTextContent=s.v,_.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.")},_.NoneLogLevel=r.Y.NoneLogLevel,_.MessageLogLevel=r.Y.MessageLogLevel,_.WarningLogLevel=r.Y.WarningLogLevel,_.ErrorLogLevel=r.Y.ErrorLogLevel,_.AllLogLevel=r.Y.AllLogLevel,_.IsWindowObjectExist=s.CG,_.PerformanceNoneLogLevel=0,_.PerformanceUserMarkLogLevel=1,_.PerformanceConsoleLogLevel=2,_.StartPerformanceCounter=_._StartPerformanceCounterDisabled,_.EndPerformanceCounter=_._EndPerformanceCounterDisabled;class m{constructor(e,t,i,n=0){this.iterations=e,this.index=n-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1{s&&s()?n.breakLoop():setTimeout((()=>{for(let r=0;r=e)break;if(i(o),s&&s()){n.breakLoop();break}}n.executeNext()}),r)}),n)}}c.l.FallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhY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+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"},646:function(e,t,i){i.d(t,{H:function(){return s},q:function(){return r}});const n={};function s(e,t){n[e]=t}function r(e){return n[e]}},8501:function(e,t,i){i.d(t,{K:function(){return n}});class n{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}n._UniqueIdCounter=1},4910:function(e,t,i){i.d(t,{g:function(){return n}});class n{constructor(){this._xhr="undefined"!=typeof _native&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest,this._requestURL=""}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(const e in n.CustomRequestHeaders){const t=n.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return n.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){n.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(const i of n.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;i(this._xhr,t)}return 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)}}n.CustomRequestHeaders={},n.CustomRequestModifiers=new Array,n.SkipRequestModificationForBabylonCDN=!0},9093:function(e,t,i){i.d(t,{O:function(){return s}});var n=i(2186);class s{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[n.o.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[n.o.PositionKind]=new n.o(this._scene.getEngine(),e,n.o.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[n.o.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,s=0,r=!1){var o;const a=this._scene.getEngine();for(let l=0;lnull!=e))).length||!this._scene.postProcessesEnabled)return;const a=this._scene.getEngine();for(let l=0,h=n.length;lt._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamerat._distanceToCamera?1:0}static PainterSortCompare(e,t){const i=e.getMesh(),n=t.getMesh();return i.material&&n.material?i.material.uniqueId-n.material.uniqueId:i.uniqueId-n.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,i){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._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;ie=e.concat(t.bones))),e}}n._BabylonFileParsers={},n._IndividualBabylonFileParsers={}},6387:function(e,t,i){i.d(t,{N:function(){return c}});var n=i(1069),s=i(5412),r=i(8137),o=i(8139),a=i(5953),l=i(9069);class h{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new o.y$,this._onClonedObservable=new o.y$}}class c{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,n){const s=this._NodeConstructors[e];return s?s(t,i,n):null}set accessibilityTag(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)}get accessibilityTag(){return this._accessibilityTag}get doNotSerialize(){return!!this._nodeDataStorage._doNotSerialize||!!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._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){this._isDirty=!1,this._nodeDataStorage=new h,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new o.y$,this._parentContainer=null,this.animations=new Array,this._ranges={},this.onReady=null,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._waitingParentInstanceIndex=null,this._waitingParsedUniqueId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=s.y3.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new o.y$,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||a.l.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache()}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={},this._cache.parent=void 0}updateCache(e){!e&&this.isSynchronized()||(this._cache.parent=this.parent,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._cache.parent!==this._parentNode?(this._cache.parent=this._parentNode,!1):!(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(!t||t(e))&&void 0!==e.cullingStrategy)),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){e!==this._nodeDataStorage._isReady&&(e?(this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0):this._nodeDataStorage._isReady=!1)}getAnimationByName(e){for(let t=0;tnew c(e,this.getScene())),this);if(t&&(n.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;i{throw(0,l.S)("AnimationRange")},c._NodeConstructors={},(0,n.gn)([(0,r.qC)()],c.prototype,"name",void 0),(0,n.gn)([(0,r.qC)()],c.prototype,"id",void 0),(0,n.gn)([(0,r.qC)()],c.prototype,"uniqueId",void 0),(0,n.gn)([(0,r.qC)()],c.prototype,"state",void 0),(0,n.gn)([(0,r.qC)()],c.prototype,"metadata",void 0)},4559:function(e,t,i){i.d(t,{H:function(){return s},l:function(){return n}});class n{}n.NAME_EFFECTLAYER="EffectLayer",n.NAME_LAYER="Layer",n.NAME_LENSFLARESYSTEM="LensFlareSystem",n.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer",n.NAME_PARTICLESYSTEM="ParticleSystem",n.NAME_GAMEPAD="Gamepad",n.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue",n.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer",n.NAME_PREPASSRENDERER="PrePassRenderer",n.NAME_DEPTHRENDERER="DepthRenderer",n.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer",n.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager",n.NAME_SPRITE="Sprite",n.NAME_SUBSURFACE="SubSurface",n.NAME_OUTLINERENDERER="Outline",n.NAME_PROCEDURALTEXTURE="ProceduralTexture",n.NAME_SHADOWGENERATOR="ShadowGenerator",n.NAME_OCTREE="Octree",n.NAME_PHYSICSENGINE="PhysicsEngine",n.NAME_AUDIO="Audio",n.NAME_FLUIDRENDERER="FluidRenderer",n.STEP_ISREADYFORMESH_EFFECTLAYER=0,n.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0,n.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0,n.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0,n.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1,n.STEP_BEFORECAMERADRAW_PREPASS=0,n.STEP_BEFORECAMERADRAW_EFFECTLAYER=1,n.STEP_BEFORECAMERADRAW_LAYER=2,n.STEP_BEFORERENDERTARGETDRAW_PREPASS=0,n.STEP_BEFORERENDERTARGETDRAW_LAYER=1,n.STEP_BEFORERENDERINGMESH_PREPASS=0,n.STEP_BEFORERENDERINGMESH_OUTLINE=1,n.STEP_AFTERRENDERINGMESH_PREPASS=0,n.STEP_AFTERRENDERINGMESH_OUTLINE=1,n.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0,n.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1,n.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0,n.STEP_BEFORECAMERAUPDATE_GAMEPAD=1,n.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0,n.STEP_BEFORECLEAR_PREPASS=1,n.STEP_BEFORERENDERTARGETCLEAR_PREPASS=0,n.STEP_AFTERRENDERTARGETDRAW_PREPASS=0,n.STEP_AFTERRENDERTARGETDRAW_LAYER=1,n.STEP_AFTERCAMERADRAW_PREPASS=0,n.STEP_AFTERCAMERADRAW_EFFECTLAYER=1,n.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2,n.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3,n.STEP_AFTERCAMERADRAW_LAYER=4,n.STEP_AFTERCAMERADRAW_FLUIDRENDERER=5,n.STEP_AFTERCAMERAPOSTPROCESS_LAYER=0,n.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER=0,n.STEP_AFTERRENDER_AUDIO=0,n.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0,n.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1,n.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2,n.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3,n.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0,n.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER=1,n.STEP_POINTERMOVE_SPRITE=0,n.STEP_POINTERDOWN_SPRITE=0,n.STEP_POINTERUP_SPRITE=0;class s extends Array{constructor(e){super(...e)}static Create(){return Object.create(s.prototype)}registerStep(e,t,i){let n=0,s=Number.MAX_VALUE;for(;n=0;a--)(s=e[a])&&(o=(r<3?s(o):r>3?s(t,i,o):s(t,i))||o);return r>3&&o&&Object.defineProperty(t,i,o),o}Object.create;Object.create}},n={};function s(e){var t=n[e];if(void 0!==t)return t.exports;var r=n[e]={exports:{}};return i[e](r,r.exports,s),r.exports}s.m=i,s.x=function(){var e=s.O(void 0,[315,568,770,942],(function(){return s(4201)}));return e=s.O(e)},e=[],s.O=function(t,i,n,r){if(!i){var o=1/0;for(c=0;c=r)&&Object.keys(s.O).every((function(e){return s.O[e](i[l])}))?i.splice(l--,1):(a=!1,r0&&e[c-1][2]>r;c--)e[c]=e[c-1];e[c]=[i,n,r]},s.d=function(e,t){for(var i in t)s.o(t,i)&&!s.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},s.f={},s.e=function(e){return Promise.all(Object.keys(s.f).reduce((function(t,i){return s.f[i](e,t),t}),[]))},s.u=function(e){return{315:"c2b82a6e",568:"87a06baf",770:"088d5a4e",942:"256b551e"}[e]+"-"+{315:"1e3631aca5d8280099d6",568:"5d3ac30d48950f0f9b7a",770:"4f2cb64570bdf3425971",942:"1832dd584c826cd29ac8"}[e]+".js"},s.miniCssF=function(e){},s.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},s.p="/www.codecave.pro-new/",function(){var e={475:1};s.f.i=function(t,i){e[t]||importScripts(s.p+s.u(t))};var t=self.webpackChunkcode_cave=self.webpackChunkcode_cave||[],i=t.push.bind(t);t.push=function(t){var n=t[0],r=t[1],o=t[2];for(var a in r)s.o(r,a)&&(s.m[a]=r[a]);for(o&&o(s);n.length;)e[n.pop()]=1;i(t)}}(),t=s.x,s.x=function(){return Promise.all([315,568,770,942].map(s.e,s)).then(t)};s.x()}(); -//# sourceMappingURL=475-f022f6fdbc411815273f.js.map \ No newline at end of file +!function(){"use strict";var e,t,i={4201:function(e,t,i){var n=i(8426),s=i(9802),r=i(8139),o=i(5412),a=i(2922),l=i(646);class h{constructor(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new r.y$,e.parameter?(this.trigger=e.trigger,this._triggerParameter=e.parameter):e.trigger?this.trigger=e.trigger:this.trigger=e,this._nextActiveAction=this,this._condition=t}_prepare(){}getTriggerParameter(){return this._triggerParameter}setTriggerParameter(e){this._triggerParameter=e}_evaluateConditionForCurrentFrame(){const e=this._condition;if(!e)return!0;const t=this._actionManager.getScene().getRenderId();return e._evaluationId!==t&&(e._evaluationId=t,e._currentResult=e.isValid()),e._currentResult}_executeCurrent(e){this._evaluateConditionForCurrentFrame()&&(this.onBeforeExecuteObservable.notifyObservers(this),this._nextActiveAction.execute(e),this.skipToNextActiveAction())}execute(e){}skipToNextActiveAction(){this._nextActiveAction._child?(this._nextActiveAction._child._actionManager||(this._nextActiveAction._child._actionManager=this._actionManager),this._nextActiveAction=this._nextActiveAction._child):this._nextActiveAction=this}then(e){return this._child=e,e._actionManager=this._actionManager,e._prepare(),e}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(e){}_serialize(e,t){const i={type:1,children:[],name:e.name,properties:e.properties||[]};if(this._child&&this._child.serialize(i),this._condition){const e=this._condition.serialize();return e.children.push(i),t&&t.children.push(e),e}return t&&t.children.push(i),i}}h._SerializeValueAsString=e=>"number"==typeof e?e.toString():"boolean"==typeof e?e?"true":"false":e instanceof o.FM?e.x+", "+e.y:e instanceof o.P?e.x+", "+e.y+", "+e.z:e instanceof a.Wo?e.r+", "+e.g+", "+e.b:e instanceof a.HE?e.r+", "+e.g+", "+e.b+", "+e.a:e,h._GetTargetProperty=e=>({name:"target",targetType:e._isMesh?"MeshProperties":e._isLight?"LightProperties":e._isCamera?"CameraProperties":e._isMaterial?"MaterialProperties":"SceneProperties",value:e._isScene?"Scene":e.name}),(0,l.H)("BABYLON.Action",h);var c=i(9372);class d{constructor(e){this._actionManager=e}isValid(){return!0}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(){}_serialize(e){return{type:2,children:[],name:e.name,properties:e.properties}}}class u extends d{static get IsEqual(){return u._IsEqual}static get IsDifferent(){return u._IsDifferent}static get IsGreater(){return u._IsGreater}static get IsLesser(){return u._IsLesser}constructor(e,t,i,n,s=u.IsEqual){super(e),this.propertyPath=i,this.value=n,this.operator=s,this._target=t,this._effectiveTarget=this._getEffectiveTarget(t,this.propertyPath),this._property=this._getProperty(this.propertyPath)}isValid(){switch(this.operator){case u.IsGreater:return this._effectiveTarget[this._property]>this.value;case u.IsLesser:return this._effectiveTarget[this._property]-1&&this._scene.actionManagers.splice(e,1)}getScene(){return this._scene}hasSpecificTriggers(e){for(let t=0;t-1)return!0}return!1}hasSpecificTriggers2(e,t){for(let i=0;i=v.OnPickTrigger&&t.trigger<=v.OnPointerOutTrigger)return!0}return!1}get hasPickTriggers(){for(let e=0;e=v.OnPickTrigger&&t.trigger<=v.OnPickUpTrigger)return!0}return!1}registerAction(e){return e.trigger===v.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(p.Y.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,v.Triggers[e.trigger]?v.Triggers[e.trigger]++:v.Triggers[e.trigger]=1,e._actionManager=this,e._prepare(),e)}unregisterAction(e){const t=this.actions.indexOf(e);return-1!==t&&(this.actions.splice(t,1),v.Triggers[e.trigger]-=1,0===v.Triggers[e.trigger]&&delete v.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0)}processTrigger(e,t){for(let i=0;i{if(null===n){const e=parseFloat(t);return"true"===t||"false"===t?"true"===t:isNaN(e)?t:e}const s=n.split("."),r=t.split(",");for(let o=0;o{if(e.detached)return;const c=new Array;let p=null,_=null;const m=e.combine&&e.combine.length>0;if(2===e.type?c.push(n):c.push(t),m){const t=new Array;for(let i=0;i{const i=(0,l.q)("BABYLON."+e);return i&&new i(...t)})(e.name,c);if(g instanceof d&&null!==o){const e=new f(t,o);a?a.then(e):n.registerAction(e),a=e}null===h?g instanceof d?(o=g,g=a):(o=null,a?a.then(g):n.registerAction(g)):h.push(g);for(let i=0;i0){const e=n.properties[0].value,s=null===n.properties[0].targetType?e:i.getMeshByName(e);s._meshId&&(s.mesh=i.getMeshById(s._meshId)),t={trigger:v[n.name],parameter:s}}else t=v[n.name];for(let e=0;e=0?t:0;let a=0;const l=r._keys[0];let h=r._keys.length-1;const c=r._keys[h],d={referenceValue:l.value,referencePosition:o.jp.Vector3[0],referenceQuaternion:o.jp.Quaternion[0],referenceScaling:o.jp.Vector3[1],keyPosition:o.jp.Vector3[2],keyQuaternion:o.jp.Quaternion[1],keyScaling:o.jp.Vector3[3]};let u=!1,p=l.frame,f=c.frame;if(i){const e=r.getRange(i);e&&(p=e.from,f=e.to)}let _=l.frame===p,m=c.frame===f;if(1===r._keys.length){const e=r._getKeyValue(r._keys[0]);d.referenceValue=e.clone?e.clone():e,u=!0}else if(t<=l.frame){const e=r._getKeyValue(l.value);d.referenceValue=e.clone?e.clone():e,u=!0}else if(t>=c.frame){const e=r._getKeyValue(c.value);d.referenceValue=e.clone?e.clone():e,u=!0}let g=0;for(;!u||!_||!m&&g=e.frame&&t<=i.frame){let n;if(t===e.frame)n=r._getKeyValue(e.value);else if(t===i.frame)n=r._getKeyValue(i.value);else{const e={key:g,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT};n=r._interpolate(t,e)}d.referenceValue=n.clone?n.clone():n,u=!0}if(!_&&p>=e.frame&&p<=i.frame){if(p===e.frame)a=g;else if(p===i.frame)a=g+1;else{const e={key:g,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT},t=r._interpolate(p,e),i={frame:p,value:t.clone?t.clone():t};r._keys.splice(g+1,0,i),a=g+1}_=!0}if(!m&&f>=e.frame&&f<=i.frame){if(f===e.frame)h=g;else if(f===i.frame)h=g+1;else{const e={key:g,repeatCount:0,loopMode:this.ANIMATIONLOOPMODE_CONSTANT},t=r._interpolate(f,e),i={frame:f,value:t.clone?t.clone():t};r._keys.splice(g+1,0,i),h=g+1}m=!0}g++}for(r.dataType===A.ANIMATIONTYPE_QUATERNION?d.referenceValue.normalize().conjugateInPlace():r.dataType===A.ANIMATIONTYPE_MATRIX&&(d.referenceValue.decompose(d.referenceScaling,d.referenceQuaternion,d.referencePosition),d.referenceQuaternion.normalize().conjugateInPlace()),g=a;g<=h;g++){const e=r._keys[g];if(!g||r.dataType===A.ANIMATIONTYPE_FLOAT||e.value!==l.value)switch(r.dataType){case A.ANIMATIONTYPE_MATRIX:e.value.decompose(d.keyScaling,d.keyQuaternion,d.keyPosition),d.keyPosition.subtractInPlace(d.referencePosition),d.keyScaling.divideInPlace(d.referenceScaling),d.referenceQuaternion.multiplyToRef(d.keyQuaternion,d.keyQuaternion),o.y3.ComposeToRef(d.keyScaling,d.keyQuaternion,d.keyPosition,e.value);break;case A.ANIMATIONTYPE_QUATERNION:d.referenceValue.multiplyToRef(e.value,e.value);break;case A.ANIMATIONTYPE_VECTOR2:case A.ANIMATIONTYPE_VECTOR3:case A.ANIMATIONTYPE_COLOR3:case A.ANIMATIONTYPE_COLOR4:e.value.subtractToRef(d.referenceValue,e.value);break;case A.ANIMATIONTYPE_SIZE:e.value.width-=d.referenceValue.width,e.value.height-=d.referenceValue.height;break;default:e.value-=d.referenceValue}}return r}static TransitionTo(e,t,i,n,s,r,o,a=null){if(o<=0)return i[e]=t,a&&a(),null;const l=s*(o/1e3);r.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(r);const h=n.beginAnimation(i,0,l,!1);return h.onAnimationEnd=a,h}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(const e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,n,s,r){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=n,this.loopMode=s,this.enableBlending=r,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===s?A.ANIMATIONLOOPMODE_CYCLE:s,this.uniqueId=A._UniqueIdGenerator++}toString(e){let t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType],t+=", nKeys: "+(this._keys?this._keys.length:"none"),t+=", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";let e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort(((e,t)=>e.frame-t.frame))}removeEvents(e){for(let t=0;t=0;i--)this._keys[i].frame>=e&&this._keys[i].frame<=t&&this._keys.splice(i,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;const i=this._keys,n=i.length;let s=t.key;for(;s>=0&&e=i[s+1].frame;)++s;if(t.key=s,s<0)return this._getKeyValue(i[0].value);if(s+1>n-1)return this._getKeyValue(i[n-1].value);const r=i[s],o=i[s+1],a=this._getKeyValue(r.value),l=this._getKeyValue(o.value);if(r.interpolation===T.STEP)return o.frame>e?a:l;const h=void 0!==r.outTangent&&void 0!==o.inTangent,c=o.frame-r.frame;let d=(e-r.frame)/c;const u=this.getEasingFunction();switch(null!==u&&(d=u.ease(d)),this.dataType){case A.ANIMATIONTYPE_FLOAT:{const e=h?this.floatInterpolateFunctionWithTangents(a,r.outTangent*c,l,o.inTangent*c,d):this.floatInterpolateFunction(a,l,d);switch(t.loopMode){case A.ANIMATIONLOOPMODE_CYCLE:case A.ANIMATIONLOOPMODE_CONSTANT:case A.ANIMATIONLOOPMODE_YOYO:return e;case A.ANIMATIONLOOPMODE_RELATIVE:return t.offsetValue*t.repeatCount+e}break}case A.ANIMATIONTYPE_QUATERNION:{const e=h?this.quaternionInterpolateFunctionWithTangents(a,r.outTangent.scale(c),l,o.inTangent.scale(c),d):this.quaternionInterpolateFunction(a,l,d);switch(t.loopMode){case A.ANIMATIONLOOPMODE_CYCLE:case A.ANIMATIONLOOPMODE_CONSTANT:case A.ANIMATIONLOOPMODE_YOYO:return e;case A.ANIMATIONLOOPMODE_RELATIVE:return e.addInPlace(t.offsetValue.scale(t.repeatCount))}return e}case A.ANIMATIONTYPE_VECTOR3:{const e=h?this.vector3InterpolateFunctionWithTangents(a,r.outTangent.scale(c),l,o.inTangent.scale(c),d):this.vector3InterpolateFunction(a,l,d);switch(t.loopMode){case A.ANIMATIONLOOPMODE_CYCLE:case A.ANIMATIONLOOPMODE_CONSTANT:case A.ANIMATIONLOOPMODE_YOYO:return e;case A.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case A.ANIMATIONTYPE_VECTOR2:{const e=h?this.vector2InterpolateFunctionWithTangents(a,r.outTangent.scale(c),l,o.inTangent.scale(c),d):this.vector2InterpolateFunction(a,l,d);switch(t.loopMode){case A.ANIMATIONLOOPMODE_CYCLE:case A.ANIMATIONLOOPMODE_CONSTANT:case A.ANIMATIONLOOPMODE_YOYO:return e;case A.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case A.ANIMATIONTYPE_SIZE:switch(t.loopMode){case A.ANIMATIONLOOPMODE_CYCLE:case A.ANIMATIONLOOPMODE_CONSTANT:case A.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(a,l,d);case A.ANIMATIONLOOPMODE_RELATIVE:return this.sizeInterpolateFunction(a,l,d).add(t.offsetValue.scale(t.repeatCount))}break;case A.ANIMATIONTYPE_COLOR3:{const e=h?this.color3InterpolateFunctionWithTangents(a,r.outTangent.scale(c),l,o.inTangent.scale(c),d):this.color3InterpolateFunction(a,l,d);switch(t.loopMode){case A.ANIMATIONLOOPMODE_CYCLE:case A.ANIMATIONLOOPMODE_CONSTANT:case A.ANIMATIONLOOPMODE_YOYO:return e;case A.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case A.ANIMATIONTYPE_COLOR4:{const e=h?this.color4InterpolateFunctionWithTangents(a,r.outTangent.scale(c),l,o.inTangent.scale(c),d):this.color4InterpolateFunction(a,l,d);switch(t.loopMode){case A.ANIMATIONLOOPMODE_CYCLE:case A.ANIMATIONLOOPMODE_CONSTANT:case A.ANIMATIONLOOPMODE_YOYO:return e;case A.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case A.ANIMATIONTYPE_MATRIX:switch(t.loopMode){case A.ANIMATIONLOOPMODE_CYCLE:case A.ANIMATIONLOOPMODE_CONSTANT:case A.ANIMATIONLOOPMODE_YOYO:return A.AllowMatricesInterpolation?this.matrixInterpolateFunction(a,l,d,t.workValue):a;case A.ANIMATIONLOOPMODE_RELATIVE:return a}}return 0}matrixInterpolateFunction(e,t,i,n){return A.AllowMatrixDecomposeForInterpolation?n?(o.y3.DecomposeLerpToRef(e,t,i,n),n):o.y3.DecomposeLerp(e,t,i):n?(o.y3.LerpToRef(e,t,i,n),n):o.y3.Lerp(e,t,i)}clone(){const e=new A(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){this._keys=e.slice(0)}serialize(){const e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed;const t=this.dataType;e.keys=[];const i=this.getKeys();for(let n=0;n=2&&(l=t.values[1]),t.values.length>=3&&(h=t.values[2]),t.values.length>=4&&(c=t.values[3]);break;case A.ANIMATIONTYPE_QUATERNION:if(s=o._f.FromArray(t.values),t.values.length>=8){const e=o._f.FromArray(t.values.slice(4,8));e.equals(o._f.Zero())||(l=e)}if(t.values.length>=12){const e=o._f.FromArray(t.values.slice(8,12));e.equals(o._f.Zero())||(h=e)}t.values.length>=13&&(c=t.values[12]);break;case A.ANIMATIONTYPE_MATRIX:s=o.y3.FromArray(t.values),t.values.length>=17&&(c=t.values[16]);break;case A.ANIMATIONTYPE_COLOR3:s=a.Wo.FromArray(t.values),t.values[3]&&(l=a.Wo.FromArray(t.values[3])),t.values[4]&&(h=a.Wo.FromArray(t.values[4])),t.values[5]&&(c=t.values[5]);break;case A.ANIMATIONTYPE_COLOR4:s=a.HE.FromArray(t.values),t.values[4]&&(l=a.HE.FromArray(t.values[4])),t.values[5]&&(h=a.HE.FromArray(t.values[5])),t.values[6]&&(c=a.HE.FromArray(t.values[6]));break;case A.ANIMATIONTYPE_VECTOR3:default:s=o.P.FromArray(t.values),t.values[3]&&(l=o.P.FromArray(t.values[3])),t.values[4]&&(h=o.P.FromArray(t.values[4])),t.values[5]&&(c=t.values[5])}const d={};d.frame=t.frame,d.value=s,null!=l&&(d.inTangent=l),null!=h&&(d.outTangent=h),null!=c&&(d.interpolation=c),n.push(d)}if(t.setKeys(n),e.ranges)for(r=0;r{const s=new y.g;s.addEventListener("readystatechange",(()=>{if(4==s.readyState)if(200==s.status){let t=JSON.parse(s.responseText);if(t.animations&&(t=t.animations),t.length){const e=new Array;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")})),s.open("GET",t),s.send()}))}static ParseFromSnippetAsync(e){return new Promise(((t,i)=>{const n=new y.g;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),s=new Array;for(const t of n.animations){const i=this.Parse(t);i.snippetId=e,s.push(i)}t(s)}else{const n=JSON.parse(i.animation),s=this.Parse(n);s.snippetId=e,t(s)}}else i("Unable to load the snippet "+e)})),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()}))}}A._UniqueIdGenerator=0,A.AllowMatricesInterpolation=!1,A.AllowMatrixDecomposeForInterpolation=!0,A.SnippetUrl="https://snippet.babylonjs.com",A.ANIMATIONTYPE_FLOAT=0,A.ANIMATIONTYPE_VECTOR3=1,A.ANIMATIONTYPE_QUATERNION=2,A.ANIMATIONTYPE_MATRIX=3,A.ANIMATIONTYPE_COLOR3=4,A.ANIMATIONTYPE_COLOR4=7,A.ANIMATIONTYPE_VECTOR2=5,A.ANIMATIONTYPE_SIZE=6,A.ANIMATIONLOOPMODE_RELATIVE=0,A.ANIMATIONLOOPMODE_CYCLE=1,A.ANIMATIONLOOPMODE_CONSTANT=2,A.ANIMATIONLOOPMODE_YOYO=4,A.CreateFromSnippetAsync=A.ParseFromSnippetAsync,(0,l.H)("BABYLON.Animation",A),b.N._AnimationRangeFactory=(e,t,i)=>new x(e,t,i);(0,l.H)("BABYLON.InterpolateValueAction",class extends h{constructor(e,t,i,n,s=1e3,o,a,l){super(e,o),this.duration=1e3,this.onInterpolationDoneObservable=new r.y$,this.propertyPath=i,this.value=n,this.duration=s,this.stopOtherAnimations=a,this.onInterpolationDone=l,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){const e=this._actionManager.getScene(),t=[{frame:0,value:this._effectiveTarget[this._property]},{frame:100,value:this.value}];let i;if("number"==typeof this.value)i=A.ANIMATIONTYPE_FLOAT;else if(this.value instanceof a.Wo)i=A.ANIMATIONTYPE_COLOR3;else if(this.value instanceof o.P)i=A.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof o.y3)i=A.ANIMATIONTYPE_MATRIX;else{if(!(this.value instanceof o._f))return void p.Y.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");i=A.ANIMATIONTYPE_QUATERNION}const n=new A("InterpolateValueAction",this._property,1e3/this.duration*100,i,A.ANIMATIONLOOPMODE_CONSTANT);n.setKeys(t),this.stopOtherAnimations&&e.stopAnimation(this._effectiveTarget);e.beginDirectAnimation(this._effectiveTarget,[n],0,100,!1,1,(()=>{this.onInterpolationDoneObservable.notifyObservers(this),this.onInterpolationDone&&this.onInterpolationDone()}))}serialize(e){return super._serialize({name:"InterpolateValueAction",properties:[h._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:h._SerializeValueAsString(this.value)},{name:"duration",value:h._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:h._SerializeValueAsString(this.stopOtherAnimations)||!1}]},e)}});const R=Object.freeze(new o._f(0,0,0,0)),P=Object.freeze(o.P.Zero()),I=Object.freeze(o.FM.Zero()),M=Object.freeze(C.Zero()),O=Object.freeze(a.Wo.Black());class D{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._ratioOffset=0,this._previousDelay=0,this._previousRatio=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===A.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=o.y3.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 s=t.getEvents();s&&s.length>0&&s.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[i[0]];for(let e=1;e-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray)for(let i=0;it[t.length-1].frame&&(e=t[t.length-1].frame);const i=this._events;if(i.length)for(let s=0;sthis._maxFrame)&&(t=this._minFrame),(ithis._maxFrame)&&(i=this._maxFrame);const h=i-t;let c,d,u=e*(o.framePerSecond*s)/1e3+this._ratioOffset,p=0;if(n&&this._animationState.loopMode===A.ANIMATIONLOOPMODE_YOYO){const e=(u-t)/h;u=Math.abs(Math.sin(e*Math.PI))*h+t}if(this._previousDelay=e,this._previousRatio=u,!n&&i>=t&&u>=h)l=!1,p=o._getKeyValue(this._maxValue);else if(!n&&t>=i&&u<=h)l=!1,p=o._getKeyValue(this._minValue);else if(this._animationState.loopMode!==A.ANIMATIONLOOPMODE_CYCLE){const e=i.toString()+t.toString();if(!this._offsetsCache[e]){this._animationState.repeatCount=0,this._animationState.loopMode=A.ANIMATIONLOOPMODE_CYCLE;const n=o._interpolate(t,this._animationState),s=o._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),o.dataType){case A.ANIMATIONTYPE_FLOAT:this._offsetsCache[e]=s-n;break;case A.ANIMATIONTYPE_QUATERNION:case A.ANIMATIONTYPE_VECTOR3:case A.ANIMATIONTYPE_VECTOR2:case A.ANIMATIONTYPE_SIZE:case A.ANIMATIONTYPE_COLOR3:this._offsetsCache[e]=s.subtract(n)}this._highLimitsCache[e]=s}p=this._highLimitsCache[e],c=this._offsetsCache[e]}if(void 0===c)switch(o.dataType){case A.ANIMATIONTYPE_FLOAT:c=0;break;case A.ANIMATIONTYPE_QUATERNION:c=R;break;case A.ANIMATIONTYPE_VECTOR3:c=P;break;case A.ANIMATIONTYPE_VECTOR2:c=I;break;case A.ANIMATIONTYPE_SIZE:c=M;break;case A.ANIMATIONTYPE_COLOR3:c=O}if(this._host&&this._host.syncRoot){const e=this._host.syncRoot;d=t+(i-t)*((e.masterFrame-e.fromFrame)/(e.toFrame-e.fromFrame))}else d=u>0&&t>i||u<0&&t0&&this.currentFrame>d||s<0&&this.currentFrame0?0:o.getKeys().length-1}this._currentFrame=d,this._animationState.repeatCount=0===h?0:u/h>>0,this._animationState.highLimitValue=p,this._animationState.offsetValue=c;const _=o._interpolate(d,this._animationState);if(this.setValue(_,r),f.length)for(let m=0;m0&&d>=f[m].frame&&f[m].frame>=t||h<0&&d<=f[m].frame&&f[m].frame<=t){const e=f[m];e.isDone||(e.onlyOnce&&(f.splice(m,1),m--),e.isDone=!0,e.action(d))}return l||(this._stopped=!0),l}}var N=i(147),F=i(9665),w=i(2554),L=i(5241);class B extends b.N{get _matrix(){return this._compose(),this._localMatrix}set _matrix(e){this._needToCompose=!1,e.updateFlag!==this._localMatrix.updateFlag&&(this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())}constructor(e,t,i=null,n=null,s=null,r=null,a=null){var l;super(e,t.getScene()),this.name=e,this.children=new Array,this.animations=new Array,this._index=null,this._scalingDeterminant=1,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._skeleton=t,this._localMatrix=null!==(l=null==n?void 0:n.clone())&&void 0!==l?l:o.y3.Identity(),this._restMatrix=null!=s?s:this._localMatrix.clone(),this._bindMatrix=null!=r?r:this._localMatrix.clone(),this._index=a,this._absoluteMatrix=new o.y3,this._absoluteBindMatrix=new o.y3,this._absoluteInverseBindMatrix=new o.y3,this._finalMatrix=new o.y3,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(){var e;if(this._linkedTransformNode){const t=o.jp.Vector3[0],i=o.jp.Quaternion[0],n=o.jp.Vector3[1];this.getRestMatrix().decompose(t,i,n),this._linkedTransformNode.position.copyFrom(n),this._linkedTransformNode.rotationQuaternion=null!==(e=this._linkedTransformNode.rotationQuaternion)&&void 0!==e?e:o._f.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(i),this._linkedTransformNode.scaling.copyFrom(t)}else this._matrix=this._restMatrix}getAbsoluteInverseBindMatrix(){return this._absoluteInverseBindMatrix}getInvertedAbsoluteTransform(){return this.getAbsoluteInverseBindMatrix()}getAbsoluteMatrix(){return this._absoluteMatrix}getAbsoluteTransform(){return this._absoluteMatrix}linkTransformNode(e){this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode--,this._linkedTransformNode=e,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode++}getTransformNode(){return this._linkedTransformNode}get position(){return this._decompose(),this._localPosition}set position(e){this._decompose(),this._localPosition.copyFrom(e),this._markAsDirtyAndCompose()}get rotation(){return this.getRotation()}set rotation(e){this.setRotation(e)}get rotationQuaternion(){return this._decompose(),this._localRotation}set rotationQuaternion(e){this.setRotationQuaternion(e)}get scaling(){return this.getScale()}set scaling(e){this.setScale(e)}get animationPropertiesOverride(){return this._skeleton.animationPropertiesOverride}_decompose(){this._needToDecompose&&(this._needToDecompose=!1,this._localScaling||(this._localScaling=o.P.Zero(),this._localRotation=o._f.Zero(),this._localPosition=o.P.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){this._needToCompose&&(this._localScaling?(this._needToCompose=!1,o.y3.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 i=0;i-1&&(this._scene._activeAnimatables.splice(e,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let i=0;i{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(s)}}getAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let i=0;i-1){const 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(n,1),this._raiseOnAnimationEnd())}}else{const e=this._scene._activeAnimatables.indexOf(this);if(e>-1){i||this._scene._activeAnimatables.splice(e,1);const t=this._runtimeAnimations;for(let e=0;e{this.onAnimationEndObservable.add((()=>{e(this)}),void 0,void 0,this,!0)}))}_animate(e){if(this._paused)return this.animationStarted=!1,null===this._pausedDelay&&(this._pausedDelay=e),!0;if(null===this._localDelayOffset?(this._localDelayOffset=e,this._pausedDelay=null):null!==this._pausedDelay&&(this._localDelayOffset+=e-this._pausedDelay,this._pausedDelay=null),null!==this._manualJumpDelay&&(this._localDelayOffset+=this._manualJumpDelay,this._manualJumpDelay=null,this._frameToSyncFromJump=null),this._goToFrame=null,0===this._weight)return!0;let t=!1;const i=this._runtimeAnimations;let n;for(n=0;n0)return;this._animationTimeLast=e}this.deltaTime=this.useConstantAnimationDeltaTime?16:(e-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=e;const t=this._activeAnimatables;if(0===t.length)return;this._animationTime+=this.deltaTime;const i=this._animationTime;for(let n=0;ni&&s>0&&(s*=-1),a&&this.stopAnimation(e,void 0,l),o||(o=new U(this,e,t,i,n,s,r,void 0,h,c));const d=!l||l(e);if(e.animations&&d&&o.appendAnimations(e,e.animations),e.getAnimatables){const c=e.getAnimatables();for(let e=0;en&&r>0)r*=-1;else if(n>i&&r<0){const e=n;n=i,i=e}return new U(this,e,i,n,s,r,o,t,a,l)},N.x.prototype.beginDirectHierarchyAnimation=function(e,t,i,n,s,r,o,a,l,h=!1){const c=e.getDescendants(t),d=[];d.push(this.beginDirectAnimation(e,i,n,s,r,o,a,l,h));for(const u of c)d.push(this.beginDirectAnimation(u,i,n,s,r,o,a,l,h));return d},N.x.prototype.getAnimatableByTarget=function(e){for(let t=0;t0?h:-h,s),l.scaleAndAddToRef(h,i)}s.normalize()}for(let u=0;u0)s.copyFrom(n);else if(1===e.animations.length){if(o._f.SlerpToRef(n,i.currentValue,Math.min(1,e.totalWeight),s),0===e.totalAdditiveWeight)return s}else if(e.animations.length>1){let i,r,a=1;if(e.totalWeight<1){const t=1-e.totalWeight;i=[],r=[],i.push(n),r.push(t)}else{if(2===e.animations.length&&(o._f.SlerpToRef(e.animations[0].currentValue,e.animations[1].currentValue,e.animations[1].weight/e.totalWeight,t),0===e.totalAdditiveWeight))return t;i=[],r=[],a=e.totalWeight}for(let t=0;t=o&&m.frame<=a&&(n?(v=m.value.clone(),u?(g=v.getTranslation(),v.setTranslation(g.scaleInPlace(p))):f&&s?(g=v.getTranslation(),v.setTranslation(g.multiplyInPlace(s))):v=m.value):v=m.value,_.push({frame:m.frame+i,value:v}));return this.animations[0].createRange(t,o+i,a+i),!0};var V,k=i(4551);!function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"}(V||(V={}));class G{constructor(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}degrees(){return 180*this._radians/Math.PI}radians(){return this._radians}static BetweenTwoPoints(e,t){const i=t.subtract(e),n=Math.atan2(i.y,i.x);return new G(n)}static FromRadians(e){return new G(e)}static FromDegrees(e){return new G(e*Math.PI/180)}}class z{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;const n=Math.pow(t.x,2)+Math.pow(t.y,2),s=(Math.pow(e.x,2)+Math.pow(e.y,2)-n)/2,r=(n-Math.pow(i.x,2)-Math.pow(i.y,2))/2,a=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new o.FM((s*(t.y-i.y)-r*(e.y-t.y))/a,((e.x-t.x)*r-(t.x-i.x)*s)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=G.BetweenTwoPoints(this.centerPoint,this.startPoint);const l=this.startAngle.degrees();let h=G.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),c=G.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();h-l>180&&(h-=360),h-l<-180&&(h+=360),c-h>180&&(c-=360),c-h<-180&&(c+=360),this.orientation=h-l<0?V.CW:V.CCW,this.angle=G.FromDegrees(this.orientation===V.CW?l-c:c-l)}}class W{constructor(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o.FM(e,t))}addLineTo(e,t){if(this.closed)return this;const i=new o.FM(e,t),n=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(n).length(),this}addArcTo(e,t,i,n,s=36){if(this.closed)return this;const r=this._points[this._points.length-1],a=new o.FM(e,t),l=new o.FM(i,n),h=new z(r,a,l);let c=h.angle.radians()/s;h.orientation===V.CW&&(c*=-1);let d=h.startAngle.radians()+c;for(let o=0;o(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*n,o=this._points[this._points.length-1];for(let a=0;a<=s;a++){const l=a/s,h=r(l,o.x,e,i),c=r(l,o.y,t,n);this.addLineTo(h,c)}return this}addBezierCurveTo(e,t,i,n,s,r,o=36){if(this.closed)return this;const a=(e,t,i,n,s)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*n+e*e*e*s,l=this._points[this._points.length-1];for(let h=0;h<=o;h++){const c=h/o,d=a(c,l.x,e,i,s),u=a(c,l.y,t,n,r);this.addLineTo(d,u)}return this}isPointInside(e){let t=!1;const i=this._points.length;for(let n=i-1,s=0;sNumber.EPSILON){if(a<0&&(i=this._points[s],o=-o,r=this._points[n],a=-a),e.yr.y)continue;if(e.y===i.y&&e.x===i.x)return!0;{const n=a*(e.x-i.x)-o*(e.y-i.y);if(0===n)return!0;if(n<0)continue;t=!t}}else{if(e.y!==i.y)continue;if(r.x<=e.x&&e.x<=i.x||i.x<=e.x&&e.x<=r.x)return!0}}return t}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){const t=this._points[this._points.length-1];e+=this._points[0].subtract(t).length()}return e}area(){const e=this._points.length;let t=0;for(let i=e-1,n=0;n1)return o.FM.Zero();const t=e*this.length();let i=0;for(let n=0;n=i&&t<=a){const e=r.normalize(),n=t-i;return new o.FM(s.x+e.x*n,s.y+e.y*n)}i=a}return o.FM.Zero()}static StartingAt(e,t){return new W(e,t)}}class H{constructor(e,t=null,i,n=!1){this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array,this._pointAtData={id:0,point:o.P.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:o.y3.Identity()};for(let s=0;st){const i=e;e=t,t=i}const i=this.getCurve(),n=this.getPointAt(e);let s=this.getPreviousPointIndexAt(e);const r=this.getPointAt(t),o=this.getPreviousPointIndexAt(t)+1,a=[];return 0!==e&&(s++,a.push(n)),a.push(...i.slice(s,o)),1===t&&1!==e||a.push(r),new H(a,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let n=0;nt+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i,n=e.length();if(0===n&&(n=1),null==t){let t;t=S.R.WithinEpsilon(Math.abs(e.y)/n,1,k.kn)?S.R.WithinEpsilon(Math.abs(e.x)/n,1,k.kn)?S.R.WithinEpsilon(Math.abs(e.z)/n,1,k.kn)?o.P.Zero():new o.P(0,0,1):new o.P(1,0,0):new o.P(0,-1,0),i=o.P.Cross(e,t)}else i=o.P.Cross(e,t),o.P.CrossToRef(i,e,i);return i.normalize(),i}_updatePointAtData(e,t=!1){if(this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;const i=this.getPoints();if(e<=0)return this._setPointAtData(0,0,i[0],0,t);if(e>=1)return this._setPointAtData(1,1,i[i.length-1],i.length-1,t);let n,s=i[0],r=0;const a=e*this.length();for(let l=1;la){const i=(r-a)/h,o=s.subtract(n),c=n.add(o.scaleInPlace(i));return this._setPointAtData(e,1-i,c,l-1,t)}s=n}return this._pointAtData}_setPointAtData(e,t,i,n,s){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=n,this._pointAtData.interpolateReady=s,s&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=o.y3.Identity();const e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){const t=e+1,i=this._tangents[e].clone(),n=this._normals[e].clone(),s=this._binormals[e].clone(),r=this._tangents[t].clone(),a=this._normals[t].clone(),l=this._binormals[t].clone(),h=o._f.RotationQuaternionFromAxis(n,s,i),c=o._f.RotationQuaternionFromAxis(a,l,r);o._f.Slerp(h,c,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}class X{static CreateQuadraticBezier(e,t,i,n){n=n>2?n:3;const s=new Array,r=(e,t,i,n)=>(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*n;for(let a=0;a<=n;a++)s.push(new o.P(r(a/n,e.x,t.x,i.x),r(a/n,e.y,t.y,i.y),r(a/n,e.z,t.z,i.z)));return new X(s)}static CreateCubicBezier(e,t,i,n,s){s=s>3?s:4;const r=new Array,a=(e,t,i,n,s)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*n+e*e*e*s;for(let l=0;l<=s;l++)r.push(new o.P(a(l/s,e.x,t.x,i.x,n.x),a(l/s,e.y,t.y,i.y,n.y),a(l/s,e.z,t.z,i.z,n.z)));return new X(r)}static CreateHermiteSpline(e,t,i,n,s){const r=new Array,a=1/s;for(let l=0;l<=s;l++)r.push(o.P.Hermite(e,t,i,n,l*a));return new X(r)}static CreateCatmullRomSpline(e,t,i){const n=new Array,s=1/t;let r=0;if(i){const i=e.length;for(let a=0;a=.5?.5*(1-this.easeInCore(2*(1-e)))+.5:.5*this.easeInCore(2*e)}}Y.EASINGMODE_EASEIN=0,Y.EASINGMODE_EASEOUT=1,Y.EASINGMODE_EASEINOUT=2;class j extends Y{easeInCore(e){return e=Math.max(0,Math.min(1,e)),1-Math.sqrt(1-e*e)}}class K extends Y{easeInCore(e){return e*e}}class q extends Y{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}}class ${constructor(e,t,i){this.frame=e,this.action=t,this.onlyOnce=i,this.isDone=!1}_clone(){return new $(this.frame,this.action,this.onlyOnce)}}var Q=i(4104);class Z{getClassName(){return"TargetedAnimation"}serialize(){const e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class J{get from(){return this._from}get to(){return 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;en[0].frame&&(this._from=n[0].frame),this._to-1;t--){this._targetedAnimations[t].animation===e&&this._targetedAnimations.splice(t,1)}}normalize(e=null,t=null){null==e&&(e=this._from),null==t&&(t=this._to);for(let i=0;ie){const t={frame:e,value:s.value,inTangent:s.inTangent,outTangent:s.outTangent,interpolation:s.interpolation};n.splice(0,0,t)}if(r.frame{this.onAnimationLoopObservable.notifyObservers(t),this._animationLoopFlags[i]||(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount===this._targetedAnimations.length&&(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,n,s){if(this._isStarted||0===this._targetedAnimations.length)return this;this._loopAnimation=e,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let r=0;r{this.onAnimationEndObservable.notifyObservers(o),this._checkAnimationGroupEnded(a)},this._processLoop(a,o,r),this._animatables.push(a)}return this._speedRatio=t,this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this}pause(){if(!this._isStarted)return this;this._isPaused=!0;for(let e=0;e0&&(this._scene._activeAnimatables[t++]=e)}return this._scene._activeAnimatables.length=t,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t-1&&this._scene.animationGroups.splice(e,1),this._parentContainer){const 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){const t=this._animatables.indexOf(e);t>-1&&this._animatables.splice(t,1),0===this._animatables.length&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))}clone(e,t,i=!1){const n=new J(e||this.name,this._scene);for(const s of this._targetedAnimations)n.addTargetedAnimation(i?s.animation.clone():s.animation,t?t(s.target):s.target);return n}serialize(){const e={};e.name=this.name,e.from=this.from,e.to=this.to,e.targetedAnimations=[];for(let t=0;t{const i=new re(e,t);if(t.instancedBuffers){i.instancedBuffers={};for(const e in t.instancedBuffers)i.instancedBuffers[e]=t.instancedBuffers[e]}return i};class re extends ie.x{constructor(e,t){super(e,t.getScene()),this._indexInSourceMeshInstanceArray=-1,this._distanceToCamera=0,t.addInstance(this),this._sourceMesh=t,this._unIndexed=t._unIndexed,this.position.copyFrom(t.position),this.rotation.copyFrom(t.rotation),this.scaling.copyFrom(t.scaling),t.rotationQuaternion&&(this.rotationQuaternion=t.rotationQuaternion.clone()),this.animations=t.animations.slice();for(const i of t.getAnimationRanges())null!=i&&this.createAnimationRange(i.name,i.from,i.to);this.infiniteDistance=t.infiniteDistance,this.setPivotMatrix(t.getPivotMatrix()),this.refreshBoundingInfo(!0,!0),this._syncSubMeshes()}getClassName(){return"InstancedMesh"}get lightSources(){return this._sourceMesh._lightSources}_resyncLightSources(){}_resyncLightSource(){}_removeLightSource(){}get receiveShadows(){return this._sourceMesh.receiveShadows}set receiveShadows(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.receiveShadows)!==e&&se.w1.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.material)!==e&&se.w1.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.visibility)!==e&&se.w1.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.skeleton)!==e&&se.w1.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&&p.Y.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")}getTotalVertices(){return this._sourceMesh?this._sourceMesh.getTotalVertices():0}getTotalIndices(){return this._sourceMesh.getTotalIndices()}get sourceMesh(){return this._sourceMesh}createInstance(e){return this._sourceMesh.createInstance(e)}isReady(e=!1){return this._sourceMesh.isReady(e,!0)}getVerticesData(e,t,i){return this._sourceMesh.getVerticesData(e,t,i)}setVerticesData(e,t,i,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;const i=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getPositionData(e,t),i),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||p.Y.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!==te.Y.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new o.y3);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,o.jp.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(o.jp.Vector3[7]),this._currentLOD._masterMesh=e,this._billboardWorldMatrix}return super.getWorldMatrix()}get isAnInstance(){return!0}getLOD(e){if(!e)return this;const t=this.sourceMesh.getLODLevels();if(t&&0!==t.length){const t=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,t.boundingSphere)}else this._currentLOD=this.sourceMesh;return this._currentLOD}_preActivateForIntermediateRendering(e){return this.sourceMesh._preActivateForIntermediateRendering(e)}_syncSubMeshes(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(let e=0;e0&&-1===this.includedOnlyMeshes.indexOf(e))&&(!(this.excludedMeshes&&this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e))&&((0===this.includeOnlyWithLayerMask||0!=(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 i of this.getScene().meshes)i._removeLightSource(this,!0);this._uniformBuffer.dispose(),this.getScene().removeLight(this),super.dispose(e,t)}getTypeID(){return 0}getScaledIntensity(){return this._photometricScale*this.intensity}clone(e,t=null){const i=he.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;const n=E.p4.Clone(i,this);return e&&(n.name=e),t&&(n.parent=t),n.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(n),n}serialize(){const e=E.p4.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)}))),E.p4.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){const n=b.N.Construct("Light_Type_"+e,t,i);return n||null}static Parse(e,t){const i=he.GetConstructorFromName(e.type,e.name,t);if(!i)return null;const n=E.p4.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{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 s=i.apply(e,[t,n]);for(const e of s)e._resyncLightSource(this);return s};for(const n of e)n._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 s=i.apply(e,[t,n]);return this._resyncMeshes(),s},this._resyncMeshes()}_resyncMeshes(){for(const e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(const e of this.getScene().meshes)-1!==e.lightSources.indexOf(this)&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0;const t=this.getTypeID();let i=this.intensityMode;switch(i===he.INTENSITYMODE_AUTOMATIC&&(i=t===he.LIGHTTYPEID_DIRECTIONALLIGHT?he.INTENSITYMODE_ILLUMINANCE:he.INTENSITYMODE_LUMINOUSINTENSITY),t){case he.LIGHTTYPEID_POINTLIGHT:case he.LIGHTTYPEID_SPOTLIGHT:switch(i){case he.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case he.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case he.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case he.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case he.INTENSITYMODE_ILLUMINANCE:e=1;break;case he.INTENSITYMODE_LUMINANCE:{let t=this.radius;t=Math.max(t,.001);e=2*Math.PI*(1-Math.cos(t));break}}break;case he.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e}_reorderLightsInScene(){const e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}he.FALLOFF_DEFAULT=le.m.FALLOFF_DEFAULT,he.FALLOFF_PHYSICAL=le.m.FALLOFF_PHYSICAL,he.FALLOFF_GLTF=le.m.FALLOFF_GLTF,he.FALLOFF_STANDARD=le.m.FALLOFF_STANDARD,he.LIGHTMAP_DEFAULT=le.m.LIGHTMAP_DEFAULT,he.LIGHTMAP_SPECULAR=le.m.LIGHTMAP_SPECULAR,he.LIGHTMAP_SHADOWSONLY=le.m.LIGHTMAP_SHADOWSONLY,he.INTENSITYMODE_AUTOMATIC=le.m.INTENSITYMODE_AUTOMATIC,he.INTENSITYMODE_LUMINOUSPOWER=le.m.INTENSITYMODE_LUMINOUSPOWER,he.INTENSITYMODE_LUMINOUSINTENSITY=le.m.INTENSITYMODE_LUMINOUSINTENSITY,he.INTENSITYMODE_ILLUMINANCE=le.m.INTENSITYMODE_ILLUMINANCE,he.INTENSITYMODE_LUMINANCE=le.m.INTENSITYMODE_LUMINANCE,he.LIGHTTYPEID_POINTLIGHT=le.m.LIGHTTYPEID_POINTLIGHT,he.LIGHTTYPEID_DIRECTIONALLIGHT=le.m.LIGHTTYPEID_DIRECTIONALLIGHT,he.LIGHTTYPEID_SPOTLIGHT=le.m.LIGHTTYPEID_SPOTLIGHT,he.LIGHTTYPEID_HEMISPHERICLIGHT=le.m.LIGHTTYPEID_HEMISPHERICLIGHT,(0,oe.gn)([(0,E.n9)()],he.prototype,"diffuse",void 0),(0,oe.gn)([(0,E.n9)()],he.prototype,"specular",void 0),(0,oe.gn)([(0,E.qC)()],he.prototype,"falloffType",void 0),(0,oe.gn)([(0,E.qC)()],he.prototype,"intensity",void 0),(0,oe.gn)([(0,E.qC)()],he.prototype,"range",null),(0,oe.gn)([(0,E.qC)()],he.prototype,"intensityMode",null),(0,oe.gn)([(0,E.qC)()],he.prototype,"radius",null),(0,oe.gn)([(0,E.qC)()],he.prototype,"_renderPriority",void 0),(0,oe.gn)([(0,E.wz)("_reorderLightsInScene")],he.prototype,"renderPriority",void 0),(0,oe.gn)([(0,E.qC)("shadowEnabled")],he.prototype,"_shadowEnabled",void 0),(0,oe.gn)([(0,E.qC)("excludeWithLayerMask")],he.prototype,"_excludeWithLayerMask",void 0),(0,oe.gn)([(0,E.qC)("includeOnlyWithLayerMask")],he.prototype,"_includeOnlyWithLayerMask",void 0),(0,oe.gn)([(0,E.qC)("lightmapMode")],he.prototype,"_lightmapMode",void 0);var ce=i(4515);class de extends n.p{}class ue{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 pe extends n.p{constructor(e){super(),this._wasAddedToScene=!1,(e=e||m.l.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 o of e)t.set(o.uniqueId,o);const i={dependsOn:new Map,dependedBy:new Map};for(const o of e){const e=o.uniqueId;i.dependsOn.set(e,new Set),i.dependedBy.set(e,new Set)}for(const o of e){const e=o.uniqueId,n=i.dependsOn.get(e);if(o instanceof re){const s=o.sourceMesh;t.has(s.uniqueId)&&(n.add(s.uniqueId),i.dependedBy.get(s.uniqueId).add(e))}const s=i.dependedBy.get(e);for(const r of o.getDescendants()){const n=r.uniqueId;if(t.has(n)){s.add(n);i.dependsOn.get(n).add(e)}}}const n=[],s=[];for(const o of e){const e=o.uniqueId;0===i.dependsOn.get(e).size&&(s.push(o),t.delete(e))}const r=s;for(;r.length>0;){const e=r.shift();n.push(e);const s=i.dependedBy.get(e.uniqueId);for(const n of Array.from(s.values())){const s=i.dependsOn.get(n);s.delete(e.uniqueId),0===s.size&&t.get(n)&&(r.push(t.get(n)),t.delete(n))}}return t.size>0&&(console.error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach((e=>console.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 s of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,s,n)}}_isNodeInContainer(e){return e instanceof ee.Kj&&-1!==this.meshes.indexOf(e)||(e instanceof te.Y&&-1!==this.transformNodes.indexOf(e)||(e instanceof he&&-1!==this.lights.indexOf(e)||e instanceof ce.V&&-1!==this.cameras.indexOf(e)))}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return p.Y.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 p.Y.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 p.Y.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 p.Y.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||se.w1.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const n={},s={},r=new ue,o=[],a=[],l=Object.assign({doNotInstantiate:!0},i),h=[],c=new Set;for(const p of this.transformNodes)null===p.parent&&this._addNodeAndDescendantsToList(h,c,p,l.predicate);for(const p of this.meshes)null===p.parent&&this._addNodeAndDescendantsToList(h,c,p,l.predicate);const d=this._topologicalSort(h),u=(i,o)=>{if(((t,i)=>{if(n[t.uniqueId]=i.uniqueId,s[i.uniqueId]=i,e&&(i.name=e(t.name)),i instanceof ee.Kj){const e=i;if(e.morphTargetManager){const i=t.morphTargetManager;e.morphTargetManager=i.clone();for(let t=0;te&&s[n[e.uniqueId]]))}}"InstancedMesh"!==r.getClassName()&&(r.material=s[n[t.uniqueId]])}else"MultiMaterial"===r.material.getClassName()?-1===this.scene.multiMaterials.indexOf(r.material)&&this.scene.addMultiMaterial(r.material):-1===this.scene.materials.indexOf(r.material)&&this.scene.addMaterial(r.material)}null===o.parent&&r.rootNodes.push(o)};return d.forEach((e=>{if("InstancedMesh"===e.getClassName()){const t=e,i=t.sourceMesh,r=n[i.uniqueId],o=("number"==typeof r?s[r]:i).createInstance(t.name);u(t,o)}else{let t=!0;"TransformNode"===e.getClassName()||"Node"===e.getClassName()||e.skeleton||!e.getTotalVertices||0===e.getTotalVertices()?t=!1:l.doNotInstantiate&&(t="function"==typeof l.doNotInstantiate?!l.doNotInstantiate(e):!l.doNotInstantiate);const i=t?e.createInstance(`instance of ${e.name}`):e.clone(`Clone of ${e.name}`,null,!0);if(!i)throw new Error(`Could not clone or instantiate node on Asset Container ${e.name}`);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=s[n[e.uniqueId]];if(!t||t.isAnInstance)continue;if(t.skeleton=i,-1!==o.indexOf(i))continue;o.push(i);for(const e of i.bones)e._linkedTransformNode&&(e._linkedTransformNode=s[n[e._linkedTransformNode.uniqueId]])}r.skeletons.push(i)})),this.animationGroups.forEach((t=>{if(l.predicate&&!l.predicate(t))return;const i=t.clone(e?e(t.name):"Clone of "+t.name,(e=>s[n[e.uniqueId]]||e));r.animationGroups.push(i)})),r}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||se.w1.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){this.cameras.forEach((t=>{e&&!e(t)||this.scene.addCamera(t)})),this.lights.forEach((t=>{e&&!e(t)||this.scene.addLight(t)})),this.meshes.forEach((t=>{e&&!e(t)||this.scene.addMesh(t)})),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((t=>{e&&!e(t)||this.scene.addTransformNode(t)})),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)}))}removeAllFromScene(){this._isValidHierarchy()||se.w1.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)})),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 de);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 ee.Kj("assetContainerRootMesh",this.scene);return this.meshes.forEach((t=>{t.parent||e.addChild(t)})),this.meshes.unshift(e),e}mergeAnimationsTo(e=m.l.LastCreatedScene,t,i=null){if(!e)return p.Y.Error("No scene available to merge animations to"),[];const n=i||(t=>{let i=null;const n=t.animations.length?t.animations[0].targetProperty:"",s=t.name.split(".").join("").split("_primitive")[0];switch(n){case"position":case"rotationQuaternion":i=e.getTransformNodeByName(t.name)||e.getTransformNodeByName(s);break;case"influence":i=e.getMorphTargetByName(t.name)||e.getMorphTargetByName(s);break;default:i=e.getNodeByName(t.name)||e.getNodeByName(s)}return i});this.getNodes().forEach((e=>{const t=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 s=new Array;return this.animationGroups.slice().forEach((e=>{s.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))})),s}}var fe=i(8838);var _e=i(1102);fe.D.AudioEngineFactory=(e,t,i)=>new me(e,t,i);class me{get audioContext(){return this._audioContextInitialized?this.unlocked||this._muteButton||this._displayMuteButton():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=!0,this.useCustomUnlockedButton=!1,this.onAudioUnlockedObservable=new r.y$,this.onAudioLockedObservable=new r.y$,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!(0,_e.CG)())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(s){}try{n&&n.canPlayType&&n.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch(s){}}lock(){this._triggerSuspendedState()}unlock(){this._triggerRunningState()}_resumeAudioContext(){let e;return void 0!==this._audioContext.resume&&(e=this._audioContext.resume()),e||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,p.Y.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._triggerRunningState()}),!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))}}var ge=i(9069);class ve{get loop(){return this._loop}set loop(e){e!==this._loop&&(this._loop=e,this.updateOptions({loop:e}))}get currentTime(){var e;if(this._htmlAudioElement)return this._htmlAudioElement.currentTime;if((null===(e=fe.D.audioEngine)||void 0===e?void 0:e.audioContext)&&(this.isPlaying||this.isPaused)){const e=this.isPaused?0:fe.D.audioEngine.audioContext.currentTime-this._startTime;return this._currentTime+e}return 0}get spatialSound(){return this._spatialSound}set spatialSound(e){var t;this._spatialSound=e,this._spatialSound&&(null===(t=fe.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&fe.D.audioEngine.audioContext&&this._createSpatialParameters()}constructor(e,t,i,n=null,s){var a,l,h,c,d;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 r.y$,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=o.P.Zero(),this._localDirection=new o.P(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||m.l.LastCreatedScene)if(this._scene=i,ve._SceneComponentInitialization(i),this._readyToPlayCallback=n,this._customAttenuationFunction=(e,t,i,n,s)=>t0&&(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{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&&p.Y.Error("XHR "+e.status+" error on: "+t+"."),p.Y.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)):p.Y.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch(u){p.Y.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),fe.D.audioEngine&&!fe.D.audioEngine.WarnedWebAudioUnsupported&&(p.Y.Error("Web Audio is not supported by your browser."),fe.D.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)}dispose(){var e;(null===(e=fe.D.audioEngine)||void 0===e?void 0:e.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))}isReady(){return this._isReadyToPlay}getClassName(){return"Sound"}_audioBufferLoaded(e){var t;(null===(t=fe.D.audioEngine)||void 0===t?void 0:t.audioContext)&&(this._audioBuffer=e,this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback())}_soundLoaded(e){var t;(null===(t=fe.D.audioEngine)||void 0===t?void 0:t.audioContext)&&fe.D.audioEngine.audioContext.decodeAudioData(e,(e=>{this._audioBufferLoaded(e)}),(e=>{p.Y.Error("Error while decoding audio data for: "+this.name+" / Error: "+e)}))}setAudioBuffer(e){var t;(null===(t=fe.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&(this._audioBuffer=e,this._isReadyToPlay=!0)}updateOptions(e){var t,i,n,s,r,o,a,l,h,c;e&&(this.loop=null!==(t=e.loop)&&void 0!==t?t:this.loop,this.maxDistance=null!==(i=e.maxDistance)&&void 0!==i?i:this.maxDistance,this.useCustomAttenuation=null!==(n=e.useCustomAttenuation)&&void 0!==n?n:this.useCustomAttenuation,this.rolloffFactor=null!==(s=e.rolloffFactor)&&void 0!==s?s:this.rolloffFactor,this.refDistance=null!==(r=e.refDistance)&&void 0!==r?r:this.refDistance,this.distanceModel=null!==(o=e.distanceModel)&&void 0!==o?o:this.distanceModel,this._playbackRate=null!==(a=e.playbackRate)&&void 0!==a?a:this._playbackRate,this._length=null!==(l=e.length)&&void 0!==l?l:void 0,this._setOffset(null!==(h=e.offset)&&void 0!==h?h:void 0),this.setVolume(null!==(c=e.volume)&&void 0!==c?c: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(){var e,t;(null===(e=fe.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&fe.D.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=null!==(t=this._soundPanner)&&void 0!==t?t:fe.D.audioEngine.audioContext.createPanner(),this._soundPanner&&this._outputAudioNode&&(this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner))}_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))}switchPanningModelToHRTF(){this._panningModel="HRTF",this._switchPanningModel()}switchPanningModelToEqualPower(){this._panningModel="equalpower",this._switchPanningModel()}_switchPanningModel(){var e;(null===(e=fe.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){var t;(null===(t=fe.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(e),this._isOutputConnected=!0)}setDirectionalCone(e,t,i){t{this._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement){const e=()=>{var t,i;if(null===(t=fe.D.audioEngine)||void 0===t?void 0:t.unlocked){const t=this._htmlAudioElement.play();void 0!==t&&t.catch((()=>{var t,i;null===(t=fe.D.audioEngine)||void 0===t||t.lock(),(this.loop||this.autoplay)&&(null===(i=fe.D.audioEngine)||void 0===i||i.onAudioUnlockedObservable.addOnce((()=>{e()})))}))}else(this.loop||this.autoplay)&&(null===(i=fe.D.audioEngine)||void 0===i||i.onAudioUnlockedObservable.addOnce((()=>{e()})))};e()}}else{const s=()=>{var s,r,o,a;if(null===(s=fe.D.audioEngine)||void 0===s?void 0:s.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=null===(r=fe.D.audioEngine)||void 0===r?void 0:r.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?(null===(o=fe.D.audioEngine)||void 0===o?void 0:o.audioContext.currentTime)+e:fe.D.audioEngine.audioContext.currentTime;const s=((this.isPaused?this.currentTime:0)+(null!==(a=this._offset)&&void 0!==a?a:0))%this._soundSource.buffer.duration;this._soundSource.start(n,s,this.loop?void 0:i)}}};"suspended"===(null===(o=fe.D.audioEngine)||void 0===o?void 0:o.audioContext.state)?setTimeout((()=>{var e;"suspended"===(null===(e=fe.D.audioEngine)||void 0===e?void 0:e.audioContext.state)?(fe.D.audioEngine.lock(),(this.loop||this.autoplay)&&fe.D.audioEngine.onAudioUnlockedObservable.addOnce((()=>{s()}))):s()}),500):s()}this._startTime=n,this.isPlaying=!0,this.isPaused=!1}catch(a){p.Y.Error("Error while trying to play audio: "+this.name+", "+a.message)}}_onended(){this.isPlaying=!1,this._startTime=0,this._currentTime=0,this.onended&&this.onended(),this.onEndedObservable.notifyObservers(this)}stop(e){var t;if(this.isPlaying){if(this._streaming)this._htmlAudioElement?(this._htmlAudioElement.pause(),this._htmlAudioElement.currentTime>0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect(),this.isPlaying=!1;else if((null===(t=fe.D.audioEngine)||void 0===t?void 0:t.audioContext)&&this._soundSource){const t=e?fe.D.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.isPaused&&(this.isPaused=!1,this._startTime=0,this._currentTime=0)}pause(){var e;this.isPlaying&&(this._streaming?(this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect(),this.isPlaying=!1,this.isPaused=!0):(null===(e=fe.D.audioEngine)||void 0===e?void 0:e.audioContext)&&this._soundSource&&(this._soundSource.onended=()=>{},this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=fe.D.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){var i;(null===(i=fe.D.audioEngine)||void 0===i?void 0:i.canUseWebAudio)&&this._soundGain&&(t&&fe.D.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(fe.D.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,fe.D.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,fe.D.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){var t;if(e.getBoundingInfo){const t=e.getBoundingInfo();this.setPosition(t.boundingSphere.centerWorld)}else this.setPosition(e.absolutePosition);(null===(t=fe.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._isDirectional&&this.isPlaying&&this._updateDirection()}clone(){if(this._streaming)return null;{const e=()=>{this._isReadyToPlay?(i._audioBuffer=this.getAudioBuffer(),i._isReadyToPlay=!0,i.autoplay&&i.play(0,this._offset,this._length)):setTimeout(e,300)},t={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},i=new ve(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.name,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId,metadata:this.metadata};return this._spatialSound&&(this._connectedTransformNode&&(e.connectedMeshId=this._connectedTransformNode.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e}static Parse(e,t,i,n){const s=e.name;let r;r=e.url?i+e.url:i+s;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 l;if(n){const e=()=>{n._isReadyToPlay?(l._audioBuffer=n.getAudioBuffer(),l._isReadyToPlay=!0,l.autoplay&&l.play(0,l._offset,l._length)):setTimeout(e,300)};l=new ve(s,new ArrayBuffer(0),t,null,a),e()}else l=new ve(s,r,t,(()=>{t.removePendingData(l)}),a),t.addPendingData(l);if(e.position){const t=o.P.FromArray(e.position);l.setPosition(t)}if(e.isDirectional&&(l.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){const t=o.P.FromArray(e.localDirectionToMesh);l.setLocalDirectionToMesh(t)}if(e.connectedMeshId){const i=t.getMeshById(e.connectedMeshId);i&&l.attachToMesh(i)}return e.metadata&&(l.metadata=e.metadata),l}_setOffset(e){this._offset!==e&&(this.isPaused&&(this.stop(),this.isPaused=!1),this._offset=e)}}ve._SceneComponentInitialization=e=>{throw(0,ge.S)("AudioSceneComponent")};class Te{constructor(e,t={}){this.id=-1,this._isInitialized=!1,(e=e||m.l.LastCreatedScene)&&(this._scene=e,this.soundCollection=new Array,this._options=t,!this._options.mainTrack&&this._scene.soundTracks&&(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1))}_initializeSoundTrackAudioGraph(){var e;(null===(e=fe.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&fe.D.audioEngine.audioContext&&(this._outputAudioNode=fe.D.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(fe.D.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(fe.D.audioEngine&&fe.D.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}}addSound(e){var t;this._isInitialized||this._initializeSoundTrackAudioGraph(),(null===(t=fe.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&e.connectToSoundTrackAudioNode(this._outputAudioNode),e.soundTrackId&&(-1===e.soundTrackId?this._scene.mainSoundTrack.removeSound(e):this._scene.soundTracks&&this._scene.soundTracks[e.soundTrackId].removeSound(e)),this.soundCollection.push(e),e.soundTrackId=this.id}removeSound(e){const t=this.soundCollection.indexOf(e);-1!==t&&this.soundCollection.splice(t,1)}setVolume(e){var t;(null===(t=fe.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)}switchPanningModelToHRTF(){var e;if(null===(e=fe.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)for(let t=0;t{var s;let r,o=[];if(i.sounds=i.sounds||[],void 0!==e.sounds&&null!==e.sounds)for(let a=0,l=e.sounds.length;a{e.play(),e.autoplay=!0,this.scene.mainSoundTrack.addSound(e)}))}removeFromContainer(e,t=!1){e.sounds&&e.sounds.forEach((e=>{e.stop(),e.autoplay=!1,this.scene.mainSoundTrack.removeSound(e),t&&e.dispose()}))}dispose(){const e=this.scene;if(e._mainSoundTrack&&e.mainSoundTrack.dispose(),e.soundTracks)for(let t=0;t0&&(n=t.activeCameras[0]),this.audioListenerPositionProvider){const e=this.audioListenerPositionProvider();i.audioContext.listener.setPosition(e.x||0,e.y||0,e.z||0)}else n?this._cachedCameraPosition.equals(n.globalPosition)||(this._cachedCameraPosition.copyFrom(n.globalPosition),i.audioContext.listener.setPosition(n.globalPosition.x,n.globalPosition.y,n.globalPosition.z)):i.audioContext.listener.setPosition(0,0,0);if(this.audioListenerRotationProvider){const e=this.audioListenerRotationProvider();i.audioContext.listener.setOrientation(e.x||0,e.y||0,e.z||0,0,1,0)}else n?(n.rigCameras&&n.rigCameras.length>0&&(n=n.rigCameras[0]),n.getViewMatrix().invertToRef(this._invertMatrixTemp),o.P.TransformNormalToRef(Ee._CameraDirection,this._invertMatrixTemp,this._cameraDirectionTemp),this._cameraDirectionTemp.normalize(),isNaN(this._cameraDirectionTemp.x)||isNaN(this._cameraDirectionTemp.y)||isNaN(this._cameraDirectionTemp.z)||this._cachedCameraDirection.equals(this._cameraDirectionTemp)||(this._cachedCameraDirection.copyFrom(this._cameraDirectionTemp),i.audioContext.listener.setOrientation(this._cameraDirectionTemp.x,this._cameraDirectionTemp.y,this._cameraDirectionTemp.z,0,1,0))):i.audioContext.listener.setOrientation(0,0,0,0,1,0);for(e=0;e{let t=e._getComponent(Se.l.NAME_AUDIO);t||(t=new Ee(e),e._addComponent(t))};class xe{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 r of i)n+=r;const s=n>0?1/n:0;for(let r=0;r{this._onended()}))}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(e){if(e!==this._coneInnerAngle){if(this._coneOuterAnglee),this)}serialize(){return E.p4.Serialize(this)}parse(e,t,i){E.p4.Parse((()=>this),e,t,i)}}(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markSubMeshesAsAttributesDirty")],be.prototype,"texture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markSubMeshesAsAttributesDirty")],be.prototype,"isEnabled",void 0),(0,oe.gn)([(0,E.qC)()],be.prototype,"animationParameters",void 0),(0,oe.gn)([(0,E.qC)()],be.prototype,"time",void 0);var Ce=i(3706),ye=i(9051);class Ae{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!==(null==e?void 0:e._shareDepth)}constructor(e){this._wrapU=1,this._wrapV=1,this.wrapR=1,this.anisotropicFilteringLevel=4,this.delayLoadState=0,this._texture=null,this._engine=null,this._cachedSize=C.Zero(),this._cachedBaseSize=C.Zero(),this._initialSamplingMode=2,this._texture=Ae._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine())}isReady(){return 4===this.delayLoadState?(this.delayLoad(),!1):!!this._texture&&this._texture.isReady}delayLoad(){}getInternalTexture(){return this._texture}getSize(){if(this._texture){if(this._texture.width)return this._cachedSize.width=this._texture.width,this._cachedSize.height=this._texture.height,this._cachedSize;if(this._texture._size)return this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size,this._cachedSize}return this._cachedSize}getBaseSize(){return this.isReady()&&this._texture?this._texture._size?(this._cachedBaseSize.width=this._texture._size,this._cachedBaseSize.height=this._texture._size,this._cachedBaseSize):(this._cachedBaseSize.width=this._texture.baseWidth,this._cachedBaseSize.height=this._texture.baseHeight,this._cachedBaseSize):(this._cachedBaseSize.width=0,this._cachedBaseSize.height=0,this._cachedBaseSize)}get samplingMode(){return this._texture?this._texture.samplingMode:this._initialSamplingMode}updateSamplingMode(e){this._texture&&this._engine&&this._engine.updateTextureSamplingMode(e,this._texture)}releaseInternalTexture(){this._texture&&(this._texture.dispose(),this._texture=null)}dispose(){this._texture&&(this.releaseInternalTexture(),this._engine=null)}}class Re extends Ae{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))))}get coordinatesMode(){return this._coordinatesMode}get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get isCube(){return this._texture?this._texture.isCube:this._isCube}set isCube(e){this._texture?this._texture.isCube=e:this._isCube=e}get is3D(){return!!this._texture&&this._texture.is3D}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}get gammaSpace(){return this._texture?(null===this._texture._gammaSpace&&(this._texture._gammaSpace=this._gammaSpace),this._texture._gammaSpace&&!this._texture._useSRGBBuffer):this._gammaSpace}set gammaSpace(e){if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}this._markAllSubMeshesAsTexturesDirty()}get isRGBD(){return null!=this._texture&&this._texture._isRGBD}set isRGBD(e){this._texture&&(this._texture._isRGBD=e)}get noMipmap(){return!1}get lodGenerationOffset(){return this._texture?this._texture._lodGenerationOffset:0}set lodGenerationOffset(e){this._texture&&(this._texture._lodGenerationOffset=e)}get lodGenerationScale(){return this._texture?this._texture._lodGenerationScale:0}set lodGenerationScale(e){this._texture&&(this._texture._lodGenerationScale=e)}get linearSpecularLOD(){return!!this._texture&&this._texture._linearSpecularLOD}set linearSpecularLOD(e){this._texture&&(this._texture._linearSpecularLOD=e)}get irradianceTexture(){return this._texture?this._texture._irradianceTexture:null}set irradianceTexture(e){this._texture&&(this._texture._irradianceTexture=e)}get uid(){return this._uid||(this._uid=(0,Ce.f)()),this._uid}toString(){return this.name}getClassName(){return"BaseTexture"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get isBlocking(){return!0}get loadingError(){return this._loadingError}get errorObject(){return this._errorObject}constructor(e,t=null){super(null),this.metadata=null,this.reservedDataStore=null,this._hasAlpha=!1,this._getAlphaFromRGB=!1,this.level=1,this._coordinatesIndex=0,this.optimizeUVAllocation=!0,this._coordinatesMode=0,this.wrapR=1,this.anisotropicFilteringLevel=Re.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=new Array,this.onDisposeObservable=new r.y$,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?Re._IsScene(e)?this._scene=e:this._engine=e:this._scene=m.l.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}checkTransformsAreIdentical(e){return null!==e}getTextureMatrix(){return o.y3.IdentityReadOnly}getReflectionTextureMatrix(){return o.y3.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,n,s,r){const o=this._getEngine();if(!o)return null;const a=o._getUseSRGBBuffer(!!s,t),l=o.getLoadedTexturesCache();for(let h=0;h=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=E.p4.Serialize(this);return E.p4.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(0!==i)for(let n=0;n{0==--i&&t()})):0==--i&&t()}}else t()}static _IsScene(e){return"Scene"===e.getClassName()}}Re.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,(0,oe.gn)([(0,E.qC)()],Re.prototype,"uniqueId",void 0),(0,oe.gn)([(0,E.qC)()],Re.prototype,"name",void 0),(0,oe.gn)([(0,E.qC)()],Re.prototype,"metadata",void 0),(0,oe.gn)([(0,E.qC)("hasAlpha")],Re.prototype,"_hasAlpha",void 0),(0,oe.gn)([(0,E.qC)("getAlphaFromRGB")],Re.prototype,"_getAlphaFromRGB",void 0),(0,oe.gn)([(0,E.qC)()],Re.prototype,"level",void 0),(0,oe.gn)([(0,E.qC)("coordinatesIndex")],Re.prototype,"_coordinatesIndex",void 0),(0,oe.gn)([(0,E.qC)()],Re.prototype,"optimizeUVAllocation",void 0),(0,oe.gn)([(0,E.qC)("coordinatesMode")],Re.prototype,"_coordinatesMode",void 0),(0,oe.gn)([(0,E.qC)()],Re.prototype,"wrapU",null),(0,oe.gn)([(0,E.qC)()],Re.prototype,"wrapV",null),(0,oe.gn)([(0,E.qC)()],Re.prototype,"wrapR",void 0),(0,oe.gn)([(0,E.qC)()],Re.prototype,"anisotropicFilteringLevel",void 0),(0,oe.gn)([(0,E.qC)()],Re.prototype,"isCube",null),(0,oe.gn)([(0,E.qC)()],Re.prototype,"is3D",null),(0,oe.gn)([(0,E.qC)()],Re.prototype,"is2DArray",null),(0,oe.gn)([(0,E.qC)()],Re.prototype,"gammaSpace",null),(0,oe.gn)([(0,E.qC)()],Re.prototype,"invertZ",void 0),(0,oe.gn)([(0,E.qC)()],Re.prototype,"lodLevelInAlpha",void 0),(0,oe.gn)([(0,E.qC)()],Re.prototype,"lodGenerationOffset",null),(0,oe.gn)([(0,E.qC)()],Re.prototype,"lodGenerationScale",null),(0,oe.gn)([(0,E.qC)()],Re.prototype,"linearSpecularLOD",null),(0,oe.gn)([(0,E.oU)()],Re.prototype,"irradianceTexture",null),(0,oe.gn)([(0,E.qC)()],Re.prototype,"isRenderTarget",void 0);var Pe=i(9447),Ie=i(6448),Me=i(6504),Oe=i(8661);function De(e,t,i=!1){const n=t.width,s=t.height;if(e instanceof Float32Array){let t=e.byteLength/e.BYTES_PER_ELEMENT;const i=new Uint8Array(t);for(;--t>=0;){let n=e[t];n<0?n=0:n>1&&(n=1),i[t]=255*n}e=i}const r=document.createElement("canvas");r.width=n,r.height=s;const o=r.getContext("2d");if(!o)return null;const a=o.createImageData(n,s);if(a.data.set(e),o.putImageData(a,0,0),i){const e=document.createElement("canvas");e.width=n,e.height=s;const t=e.getContext("2d");return t?(t.translate(0,s),t.scale(1,-1),t.drawImage(r,0,0),e.toDataURL("image/png")):null}return r.toDataURL("image/png")}function Ne(e,t=0,i=0){const n=e.getInternalTexture();if(!n)return null;const s=e._readPixelsSync(t,i);return s?De(s,e.getSize(),n.invertY):null}async function Fe(e,t=0,i=0){const n=e.getInternalTexture();if(!n)return null;const s=await e.readPixels(t,i);return s?De(s,e.getSize(),n.invertY):null}var we=i(6629);class Le extends Re{get noMipmap(){return this._noMipmap}get mimeType(){return this._mimeType}set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}get invertY(){return this._invertY}constructor(e,t,i,n,s=Le.TRILINEAR_SAMPLINGMODE,o=null,a=null,l=null,h=!1,c,d,u,p,f){var _,m,g,v,T,S,E,x,b;let C;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._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 r.y$,this._isBlocking=!0,this.name=e||"",this.url=e;let y=!1,A=null;"object"==typeof i&&null!==i?(C=null!==(_=i.noMipmap)&&void 0!==_&&_,n=null!==(m=i.invertY)&&void 0!==m?m:!we.e.UseOpenGLOrientationForUV,s=null!==(g=i.samplingMode)&&void 0!==g?g:Le.TRILINEAR_SAMPLINGMODE,o=null!==(v=i.onLoad)&&void 0!==v?v:null,a=null!==(T=i.onError)&&void 0!==T?T:null,l=null!==(S=i.buffer)&&void 0!==S?S:null,h=null!==(E=i.deleteBuffer)&&void 0!==E&&E,c=i.format,d=i.mimeType,u=i.loaderOptions,p=i.creationFlags,y=null!==(x=i.useSRGBBuffer)&&void 0!==x&&x,A=null!==(b=i.internalTexture)&&void 0!==b?b:null):C=!!i,this._noMipmap=C,this._invertY=void 0===n?!we.e.UseOpenGLOrientationForUV:n,this._initialSamplingMode=s,this._buffer=l,this._deleteBuffer=h,this._mimeType=d,this._loaderOptions=u,this._creationFlags=p,this._useSRGBBuffer=y,this._forcedExtension=f,c&&(this._format=c);const R=this.getScene(),P=this._getEngine();if(!P)return;P.onBeforeTextureInitObservable.notifyObservers(this);const I=()=>{this._texture&&(this._texture._invertVScale&&(this.vScale*=-1,this.vOffset+=1),null!==this._texture._cachedWrapU&&(this.wrapU=this._texture._cachedWrapU,this._texture._cachedWrapU=null),null!==this._texture._cachedWrapV&&(this.wrapV=this._texture._cachedWrapV,this._texture._cachedWrapV=null),null!==this._texture._cachedWrapR&&(this.wrapR=this._texture._cachedWrapR,this._texture._cachedWrapR=null)),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),o&&o(),!this.isBlocking&&R&&R.resetCachedMaterial()},M=(e,t)=>{this._loadingError=!0,this._errorObject={message:e,exception:t},a&&a(e,t),Le.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!A)return this._delayedOnLoad=I,void(this._delayedOnError=M);if(this._texture=null!=A?A:this._getFromCache(this.url,C,s,this._invertY,y),this._texture)if(this._texture.isReady)Pe.Q.SetImmediate((()=>I()));else{const e=this._texture.onLoadedObservable.add(I);this._texture.onErrorObservable.add((t=>{var i;M(t.message,t.exception),null===(i=this._texture)||void 0===i||i.onLoadedObservable.remove(e)}))}else if(R&&R.useDelayedTextureLoading)this.delayLoadState=4,this._delayedOnLoad=I,this._delayedOnError=M;else{try{this._texture=P.createTexture(this.url,C,this._invertY,R,s,I,M,this._buffer,void 0,this._format,this._forcedExtension,d,u,p,y)}catch(O){throw M("error loading",O),O}h&&(this._buffer=null)}}updateURL(e,t=null,i,n){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1)),this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=n,this.delayLoadState=4,i&&(this._delayedOnLoad=i),this.delayLoad()}delayLoad(){if(4!==this.delayLoadState)return;const e=this.getScene();e&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer),this._texture?this._delayedOnLoad&&(this._texture.isReady?Pe.Q.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(this.url,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format,this._forcedExtension,this._mimeType,this._loaderOptions,this._creationFlags,this._useSRGBBuffer),this._deleteBuffer&&(this._buffer=null)),this._delayedOnLoad=null,this._delayedOnError=null)}_prepareRowForTextureGeneration(e,t,i,n){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,o.P.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}checkTransformsAreIdentical(e){return null!==e&&this.uOffset===e.uOffset&&this.vOffset===e.vOffset&&this.uScale===e.uScale&&this.vScale===e.vScale&&this.uAng===e.uAng&&this.vAng===e.vAng&&this.wAng===e.wAng}getTextureMatrix(e=1){if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale*e===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng&&this.uRotationCenter===this._cachedURotationCenter&&this.vRotationCenter===this._cachedVRotationCenter&&this.wRotationCenter===this._cachedWRotationCenter&&this.homogeneousRotationInUVTransform===this._cachedHomogeneousRotationInUVTransform)return this._cachedTextureMatrix;this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale*e,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedURotationCenter=this.uRotationCenter,this._cachedVRotationCenter=this.vRotationCenter,this._cachedWRotationCenter=this.wRotationCenter,this._cachedHomogeneousRotationInUVTransform=this.homogeneousRotationInUVTransform,this._cachedTextureMatrix&&this._rowGenerationMatrix||(this._cachedTextureMatrix=o.y3.Zero(),this._rowGenerationMatrix=new o.y3,this._t0=o.P.Zero(),this._t1=o.P.Zero(),this._t2=o.P.Zero()),o.y3.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(o.y3.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,o.jp.Matrix[0]),o.y3.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,o.jp.Matrix[1]),o.y3.ScalingToRef(this._cachedUScale,this._cachedVScale,0,o.jp.Matrix[2]),o.y3.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,o.jp.Matrix[3]),o.jp.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(o.jp.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(o.jp.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(o.jp.Matrix[3],this._cachedTextureMatrix),this._cachedTextureMatrix.setRowFromFloats(2,this._cachedTextureMatrix.m[12],this._cachedTextureMatrix.m[13],this._cachedTextureMatrix.m[14],1)):(this._prepareRowForTextureGeneration(0,0,0,this._t0),this._prepareRowForTextureGeneration(1,0,0,this._t1),this._prepareRowForTextureGeneration(0,1,0,this._t2),this._t1.subtractInPlace(this._t0),this._t2.subtractInPlace(this._t0),o.y3.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();return t?(this.optimizeUVAllocation&&t.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this))),this._cachedTextureMatrix):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!==Le.PROJECTION_MODE)return this._cachedReflectionTextureMatrix;if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=o.y3.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=o.y3.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 Le.PLANAR_MODE:o.y3.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 Le.PROJECTION_MODE:{o.y3.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);const t=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=t.updateFlag,t.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:o.y3.IdentityToRef(this._cachedReflectionTextureMatrix)}return t&&e.markAllMaterialsAsDirty(1,(e=>-1!==e.getActiveTextures().indexOf(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 E.p4.Clone((()=>new Le(this._texture?this._texture.url:null,this.getScene(),e)),this)}serialize(){var e,t;const i=this.name;Le.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const n=super.serialize(Le._SerializeInternalTextureUniqueId);return n?((Le.SerializeBuffers||Le.ForceSerializeBuffers)&&("string"==typeof this._buffer&&"data:"===this._buffer.substr(0,5)?(n.base64String=this._buffer,n.name=n.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?n.base64String="data:image/png;base64,"+(0,Oe.Gh)(this._buffer):(Le.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(n.base64String=!this._engine||this._engine._features.supportSyncTextureRead?Ne(this):Fe(this))),n.invertY=this._invertY,n.samplingMode=this.samplingMode,n._creationFlags=this._creationFlags,n._useSRGBBuffer=this._useSRGBBuffer,Le._SerializeInternalTextureUniqueId&&(n.internalTextureUniqueId=null!==(t=null===(e=this._texture)||void 0===e?void 0:e.uniqueId)&&void 0!==t?t:void 0),this.name=i,n):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=Ie.K.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 Le._CubeTextureParser(e,t,i);const n=void 0!==e.internalTextureUniqueId;if(!e.name&&!e.isRenderTarget&&!n)return null;let s;if(n){const i=t.getEngine().getLoadedTexturesCache();for(const t of i)if(t.uniqueId===e.internalTextureUniqueId){s=t;break}}const r=t=>{var i;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 n=0;n{var n,o,a;let l=!0;if(e.noMipmap&&(l=!1),e.mirrorPlane){const i=Le._CreateMirror(e.name,e.renderTargetSize,t,l);return i._waitingRenderList=e.renderList,i.mirrorPlane=Me.J.FromArray(e.mirrorPlane),r(i),i}if(e.isRenderTarget){let i=null;if(e.isCube){if(t.reflectionProbes)for(let n=0;n{r(n)}),null!==(o=e._creationFlags)&&void 0!==o?o:0,null!==(a=e._useSRGBBuffer)&&void 0!==a&&a),n.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:")||Le.UseSerializedUrlIfAny)&&(o=e.url);const a={noMipmap:!l,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{r(n)},internalTexture:s};n=new Le(o,t,a)}return n}}),e,t)}static CreateFromBase64String(e,t,i,n,s,r=Le.TRILINEAR_SAMPLINGMODE,o=null,a=null,l=5,h){return new Le("data:"+t,i,n,s,r,o,a,e,!1,l,void 0,void 0,h)}static LoadFromDataString(e,t,i,n=!1,s,r=!0,o=Le.TRILINEAR_SAMPLINGMODE,a=null,l=null,h=5,c){return"data:"!==e.substr(0,5)&&(e="data:"+e),new Le(e,i,s,r,o,a,l,t,n,h,void 0,void 0,c)}}Le.SerializeBuffers=!0,Le.ForceSerializeBuffers=!1,Le.OnTextureLoadErrorObservable=new r.y$,Le._SerializeInternalTextureUniqueId=!1,Le._CubeTextureParser=(e,t,i)=>{throw(0,ge.S)("CubeTexture")},Le._CreateMirror=(e,t,i,n)=>{throw(0,ge.S)("MirrorTexture")},Le._CreateRenderTargetTexture=(e,t,i,n,s)=>{throw(0,ge.S)("RenderTargetTexture")},Le.NEAREST_SAMPLINGMODE=1,Le.NEAREST_NEAREST_MIPLINEAR=8,Le.BILINEAR_SAMPLINGMODE=2,Le.LINEAR_LINEAR_MIPNEAREST=11,Le.TRILINEAR_SAMPLINGMODE=3,Le.LINEAR_LINEAR_MIPLINEAR=3,Le.NEAREST_NEAREST_MIPNEAREST=4,Le.NEAREST_LINEAR_MIPNEAREST=5,Le.NEAREST_LINEAR_MIPLINEAR=6,Le.NEAREST_LINEAR=7,Le.NEAREST_NEAREST=1,Le.LINEAR_NEAREST_MIPNEAREST=9,Le.LINEAR_NEAREST_MIPLINEAR=10,Le.LINEAR_LINEAR=2,Le.LINEAR_NEAREST=12,Le.EXPLICIT_MODE=0,Le.SPHERICAL_MODE=1,Le.PLANAR_MODE=2,Le.CUBIC_MODE=3,Le.PROJECTION_MODE=4,Le.SKYBOX_MODE=5,Le.INVCUBIC_MODE=6,Le.EQUIRECTANGULAR_MODE=7,Le.FIXED_EQUIRECTANGULAR_MODE=8,Le.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,Le.CLAMP_ADDRESSMODE=0,Le.WRAP_ADDRESSMODE=1,Le.MIRROR_ADDRESSMODE=2,Le.UseSerializedUrlIfAny=!1,(0,oe.gn)([(0,E.qC)()],Le.prototype,"url",void 0),(0,oe.gn)([(0,E.qC)()],Le.prototype,"uOffset",void 0),(0,oe.gn)([(0,E.qC)()],Le.prototype,"vOffset",void 0),(0,oe.gn)([(0,E.qC)()],Le.prototype,"uScale",void 0),(0,oe.gn)([(0,E.qC)()],Le.prototype,"vScale",void 0),(0,oe.gn)([(0,E.qC)()],Le.prototype,"uAng",void 0),(0,oe.gn)([(0,E.qC)()],Le.prototype,"vAng",void 0),(0,oe.gn)([(0,E.qC)()],Le.prototype,"wAng",void 0),(0,oe.gn)([(0,E.qC)()],Le.prototype,"uRotationCenter",void 0),(0,oe.gn)([(0,E.qC)()],Le.prototype,"vRotationCenter",void 0),(0,oe.gn)([(0,E.qC)()],Le.prototype,"wRotationCenter",void 0),(0,oe.gn)([(0,E.qC)()],Le.prototype,"homogeneousRotationInUVTransform",void 0),(0,oe.gn)([(0,E.qC)()],Le.prototype,"isBlocking",null),(0,l.H)("BABYLON.Texture",Le),E.p4._TextureParser=Le.Parse;var Be=i(4679),Ue=i(9271);function Ve(e,t,i,n){let s,r=1;1===n?s=new Float32Array(t*i*4):2===n?(s=new Uint16Array(t*i*4),r=15360):s=7===n?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let o=0;o{const i=p.width,r=o(e);if(r){if(a){const e=this._getWebGLTextureType(s);let t=this._getInternalFormat(n);const o=this._getRGBABufferInternalSizedFormat(s);let l=!1;t===u.RGB&&(t=u.RGBA,l=!0),this._bindTextureDirectly(u.TEXTURE_CUBE_MAP,p,!0),this._unpackFlipY(!1);const h=a(r);for(let n=0;n>n;for(let i=0;i<6;i++){let a=h[n][i];l&&(a=Ve(a,r,r,s)),u.texImage2D(i,n,o,r,r,0,t,e,a)}}this._bindTextureDirectly(u.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(p,r,n,s,d);p.isReady=!0,null==t||t.removePendingData(p),p.onLoadedObservable.notifyObservers(p),p.onLoadedObservable.clear(),l&&l()}};return this._loadFile(e,(e=>{f(e)}),void 0,null==t?void 0:t.offlineProvider,!0,((e,i)=>{null==t||t.removePendingData(p),h&&e&&h(e.status+" "+e.statusText,i)})),p},Ue.B.prototype.createRawTexture2DArray=ke(!1),Ue.B.prototype.createRawTexture3D=ke(!0),Ue.B.prototype.updateRawTexture2DArray=Ge(!1),Ue.B.prototype.updateRawTexture3D=Ge(!0);class ze extends Le{constructor(e,t,i,n,s,r=!0,o=!1,a=3,l=0,h,c){super(null,s,!r,o,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,h),this.format=n,this._engine&&(this._engine._caps.textureFloatLinearFiltering||1!==l||(a=1),this._engine._caps.textureHalfFloatLinearFiltering||2!==l||(a=1),this._texture=this._engine.createRawTexture(e,t,i,n,r,o,a,null,l,null!=h?h:0,null!=c&&c),this.wrapU=Le.CLAMP_ADDRESSMODE,this.wrapV=Le.CLAMP_ADDRESSMODE)}update(e){this._getEngine().updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type,this._texture._useSRGBBuffer)}static CreateLuminanceTexture(e,t,i,n,s=!0,r=!1,o=3){return new ze(e,t,i,1,n,s,r,o)}static CreateLuminanceAlphaTexture(e,t,i,n,s=!0,r=!1,o=3){return new ze(e,t,i,2,n,s,r,o)}static CreateAlphaTexture(e,t,i,n,s=!0,r=!1,o=3){return new ze(e,t,i,0,n,s,r,o)}static CreateRGBTexture(e,t,i,n,s=!0,r=!1,o=3,a=0,l=0,h=!1){return new ze(e,t,i,4,n,s,r,o,a,l,h)}static CreateRGBATexture(e,t,i,n,s=!0,r=!1,o=3,a=0,l=0,h=!1){return new ze(e,t,i,5,n,s,r,o,a,l,h)}static CreateRGBAStorageTexture(e,t,i,n,s=!0,r=!1,o=3,a=0,l=!1){return new ze(e,t,i,5,n,s,r,o,a,1,l)}static CreateRTexture(e,t,i,n,s=!0,r=!1,o=Le.TRILINEAR_SAMPLINGMODE,a=1){return new ze(e,t,i,6,n,s,r,o,a)}static CreateRStorageTexture(e,t,i,n,s=!0,r=!1,o=Le.TRILINEAR_SAMPLINGMODE,a=1){return new ze(e,t,i,6,n,s,r,o,a,1)}}var We=i(27);class He{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!==We.kD.POINTERDOWN?e.type===We.kD.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{if(this._reachTargetAlpha())return;const e=F.F.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=null!=e?e:F.F.Now}_reachTargetAlpha(){return!(!this._attachedCamera||!this.targetAlpha)&&Math.abs(this._attachedCamera.alpha-this.targetAlpha){if(!e)return;e.computeWorldMatrix(!0);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||(Xe.EasingFunction.setEasingMode(Xe.EasingMode),this._radiusBounceTransition=A.CreateAnimation("radius",A.ANIMATIONTYPE_FLOAT,60,Xe.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=A.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()}}Xe.EasingFunction=new class extends Y{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),Xe.EasingMode=Y.EASINGMODE_EASEOUT;class Ye{constructor(){this.onTargetFramingAnimationEndObservable=new r.y$,this._mode=Ye.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();Ye.EasingFunction.setEasingMode(Ye.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==We.kD.POINTERDOWN?e.type===We.kD.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add((e=>{e&&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 o.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new o.P(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let r=0;r{this.stopAllAnimations(),n&&n(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()})),h&&this._animatables.push(h)}_calculateLowerRadiusFromModelBoundingSphere(e,t){const i=t.subtract(e).length(),n=this._getFrustumSlope(),s=.5*i*this._radiusScale,r=s*Math.sqrt(1+1/(n.x*n.x)),o=s*Math.sqrt(1+1/(n.y*n.y));let a=Math.max(r,o);const l=this._attachedCamera;return l?(l.lowerRadiusLimit&&this._mode===Ye.IgnoreBoundsSizeMode&&(a=al.upperRadiusLimit?l.upperRadiusLimit:a),a):0}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=F.F.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=A.CreateAnimation("beta",A.ANIMATIONTYPE_FLOAT,60,Ye.EasingFunction));const e=A.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,(()=>{this._clearAnimationLocks(),this.stopAllAnimations()}));e&&this._animatables.push(e)}}_getFrustumSlope(){const e=this._attachedCamera;if(!e)return o.FM.Zero();const t=e.getScene().getEngine().getAspectRatio(e),i=Math.tan(e.fov/2),n=i*t;return new o.FM(n,i)}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=F.F.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)}}Ye.EasingFunction=new class extends Y{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)}},Ye.EasingMode=Y.EASINGMODE_EASEINOUT,Ye.IgnoreBoundsSizeMode=0,Ye.FitFrustumSidesMode=1;var je=i(318),Ke=i(3573);class qe{constructor(e,t,i=Number.MAX_VALUE){this.origin=e,this.direction=t,this.length=i}clone(){return new qe(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){const n=qe._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),s=qe._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i);let r,o,a,l,h=0,c=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.xs.x)return!1}else if(r=1/this.direction.x,o=(n.x-this.origin.x)*r,a=(s.x-this.origin.x)*r,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.ys.y)return!1}else if(r=1/this.direction.y,o=(n.y-this.origin.y)*r,a=(s.y-this.origin.y)*r,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zs.z)return!1}else if(r=1/this.direction.z,o=(n.z-this.origin.z)*r,a=(s.z-this.origin.z)*r,a===-1/0&&(a=1/0),o>a&&(l=o,o=a,a=l),h=Math.max(o,h),c=Math.min(a,c),h>c)return!1;return!0}intersectsBox(e,t=0){return this.intersectsBoxMinMax(e.minimum,e.maximum,t)}intersectsSphere(e,t=0){const i=e.center.x-this.origin.x,n=e.center.y-this.origin.y,s=e.center.z-this.origin.z,r=i*i+n*n+s*s,o=e.radius+t,a=o*o;if(r<=a)return!0;const l=i*this.direction.x+n*this.direction.y+s*this.direction.z;if(l<0)return!1;return r-l*l<=a}intersectsTriangle(e,t,i){const n=qe._TmpVector3[0],s=qe._TmpVector3[1],r=qe._TmpVector3[2],a=qe._TmpVector3[3],l=qe._TmpVector3[4];t.subtractToRef(e,n),i.subtractToRef(e,s),o.P.CrossToRef(this.direction,s,r);const h=o.P.Dot(n,r);if(0===h)return null;const c=1/h;this.origin.subtractToRef(e,a);const d=o.P.Dot(a,r)*c;if(d<0||d>1)return null;o.P.CrossToRef(a,n,l);const u=o.P.Dot(this.direction,l)*c;if(u<0||d+u>1)return null;const p=o.P.Dot(s,l)*c;return p>this.length?null:new Ke.c(1-d-u,d,p)}intersectsPlane(e){let t;const i=o.P.Dot(e.normal,this.direction);if(Math.abs(i)<9.99999997475243e-7)return null;{const n=o.P.Dot(e.normal,this.origin);return t=(-e.d-n)/i,t<0?t<-9.99999997475243e-7?null:0:t}}intersectsAxis(e,t=0){switch(e){case"y":{const e=(this.origin.y-t)/this.direction.y;return e>0?null:new o.P(this.origin.x+this.direction.x*-e,t,this.origin.z+this.direction.z*-e)}case"x":{const e=(this.origin.x-t)/this.direction.x;return e>0?null:new o.P(t,this.origin.y+this.direction.y*-e,this.origin.z+this.direction.z*-e)}case"z":{const e=(this.origin.z-t)/this.direction.z;return e>0?null:new o.P(this.origin.x+this.direction.x*-e,this.origin.y+this.direction.y*-e,t)}default:return null}}intersectsMesh(e,t,i,n=!1,s,r=!1){const a=o.jp.Matrix[0];return e.getWorldMatrix().invertToRef(a),this._tmpRay?qe.TransformToRef(this,a,this._tmpRay):this._tmpRay=qe.Transform(this,a),e.intersects(this._tmpRay,t,i,n,s,r)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let n=0;nt.distance?1:0}intersectionSegment(e,t,i){const n=this.origin,s=o.jp.Vector3[0],r=o.jp.Vector3[1],a=o.jp.Vector3[2],l=o.jp.Vector3[3];t.subtractToRef(e,s),this.direction.scaleToRef(qe._Rayl,a),n.addToRef(a,r),e.subtractToRef(n,l);const h=o.P.Dot(s,s),c=o.P.Dot(s,a),d=o.P.Dot(a,a),u=o.P.Dot(s,l),p=o.P.Dot(a,l),f=h*d-c*c;let _,m,g=f,v=f;fg&&(_=g,m=p+c,v=d)),m<0?(m=0,-u<0?_=0:-u>h?_=g:(_=-u,g=h)):m>v&&(m=v,-u+c<0?_=0:-u+c>h?_=g:(_=-u+c,g=h));const T=Math.abs(_)0&&S<=this.length&&b.lengthSquared()=e.distance?null:h:null},N.x.prototype._internalPick=function(e,t,i,n,s){let r=null;const a=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),l=this.cameraToUseForPointers||this.activeCamera;for(let h=0;h1&&this.cameraToUseForPointers!==this.activeCamera),r=this.cameraToUseForPointers||this.activeCamera;for(let a=0;a(this._tempPickingRay||(this._tempPickingRay=qe.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,s||null),this._tempPickingRay)),i,n,!0);return r&&(r.ray=this.createPickingRay(e,t,o.y3.Identity(),s||null)),r},Object.defineProperty(N.x.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1}),N.x.prototype.pick=function(e,t,i,n,s,r,a=!1){const l=this._internalPick(((i,n)=>(this._tempPickingRay||(this._tempPickingRay=qe.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,s||null,!1,n),this._tempPickingRay)),i,n,!1,r);return l&&(l.ray=this.createPickingRay(e,t,o.y3.Identity(),s||null)),l},N.x.prototype.pickWithRay=function(e,t,i,n){const s=this._internalPick((t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=o.y3.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=qe.Zero()),qe.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform)),t,i,!1,n);return s&&(s.ray=e),s},N.x.prototype.multiPick=function(e,t,i,n,s){return this._internalMultiPick((i=>this.createPickingRay(e,t,i,n||null)),i,s)},N.x.prototype.multiPickWithRay=function(e,t,i){return this._internalMultiPick((t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=o.y3.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=qe.Zero()),qe.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform)),t,i)},ce.V.prototype.getForwardRay=function(e=100,t,i){return this.getForwardRayToRef(new qe(o.P.Zero(),o.P.Zero(),e),e,t,i)},ce.V.prototype.getForwardRayToRef=function(e,t=100,i,n){return i||(i=this.getWorldMatrix()),e.length=t,n?e.origin.copyFrom(n):e.origin.copyFrom(this.position),o.jp.Vector3[2].set(0,0,this._scene.useRightHandedSystem?-1:1),o.P.TransformNormalToRef(o.jp.Vector3[2],i,o.jp.Vector3[3]),o.P.NormalizeToRef(o.jp.Vector3[3],e.direction),e};class $e{static _RemoveAndStorePivotPoint(e){e&&0===$e._PivotCached&&(e.getPivotPointToRef($e._OldPivotPoint),$e._PivotPostMultiplyPivotMatrix=e._postMultiplyPivotMatrix,$e._OldPivotPoint.equalsToFloats(0,0,0)||(e.setPivotMatrix(o.y3.IdentityReadOnly),$e._OldPivotPoint.subtractToRef(e.getPivotPoint(),$e._PivotTranslation),$e._PivotTmpVector.copyFromFloats(1,1,1),$e._PivotTmpVector.subtractInPlace(e.scaling),$e._PivotTmpVector.multiplyInPlace($e._PivotTranslation),e.position.addInPlace($e._PivotTmpVector))),$e._PivotCached++}static _RestorePivotPoint(e){e&&!$e._OldPivotPoint.equalsToFloats(0,0,0)&&1===$e._PivotCached&&(e.setPivotPoint($e._OldPivotPoint),e._postMultiplyPivotMatrix=$e._PivotPostMultiplyPivotMatrix,$e._PivotTmpVector.copyFromFloats(1,1,1),$e._PivotTmpVector.subtractInPlace(e.scaling),$e._PivotTmpVector.multiplyInPlace($e._PivotTranslation),e.position.subtractInPlace($e._PivotTmpVector)),this._PivotCached--}}$e._PivotCached=0,$e._OldPivotPoint=new o.P,$e._PivotTranslation=new o.P,$e._PivotTmpVector=new o.P,$e._PivotPostMultiplyPivotMatrix=!1;var Qe=i(2341);function Ze(e){const t=[],i=[],n=[],s=[],r=e.width||e.size||1,o=e.height||e.size||1,a=0===e.sideOrientation?0:e.sideOrientation||Qe.x.DEFAULTSIDE,l=r/2,h=o/2;i.push(-l,-h,0),n.push(0,0,-1),s.push(0,we.e.UseOpenGLOrientationForUV?1:0),i.push(l,-h,0),n.push(0,0,-1),s.push(1,we.e.UseOpenGLOrientationForUV?1:0),i.push(l,h,0),n.push(0,0,-1),s.push(1,we.e.UseOpenGLOrientationForUV?0:1),i.push(-l,h,0),n.push(0,0,-1),s.push(0,we.e.UseOpenGLOrientationForUV?0:1),t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),Qe.x._ComputeSides(a,i,t,n,s,e.frontUVs,e.backUVs);const c=new Qe.x;return c.indices=t,c.positions=i,c.normals=n,c.uvs=s,c}function Je(e,t={},i=null){const n=new ee.Kj(e,i);t.sideOrientation=ee.Kj._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation;return Ze(t).applyToMesh(n,t.updatable),t.sourcePlane&&(n.translate(t.sourcePlane.normal,-t.sourcePlane.d),n.setDirection(t.sourcePlane.normal.scale(-1))),n}Qe.x.CreatePlane=Ze,ee.Kj.CreatePlane=(e,t,i,n,s)=>Je(e,{size:t,width:t,height:t,sideOrientation:s,updatable:n},i);class et{get currentDraggingPointerID(){return this.currentDraggingPointerId}set currentDraggingPointerID(e){this.currentDraggingPointerId=e}set enabled(e){e!=this._enabled&&this.onEnabledObservable.notifyObservers(e),this._enabled=e}get enabled(){return this._enabled}get options(){return this._options}set options(e){this._options=e}constructor(e){this._useAlternatePickedPointAboveMaxDragAngleDragSpeed=-1.1,this._activeDragButton=-1,this.maxDragAngle=0,this.dragButtons=[0,1,2],this._useAlternatePickedPointAboveMaxDragAngle=!1,this.currentDraggingPointerId=-1,this.dragging=!1,this.dragDeltaRatio=.2,this.updateDragPlane=!0,this._debugMode=!1,this._moving=!1,this.onDragObservable=new r.y$,this.onDragStartObservable=new r.y$,this.onDragEndObservable=new r.y$,this.onEnabledObservable=new r.y$,this.moveAttached=!0,this._enabled=!0,this.startAndReleaseDragOnPointerEvents=!0,this.detachCameraControls=!0,this.useObjectOrientationForDragging=!0,this.validateDrag=e=>!0,this._tmpVector=new o.P(0,0,0),this._alternatePickedPoint=new o.P(0,0,0),this._worldDragAxis=new o.P(0,0,0),this._targetPosition=new o.P(0,0,0),this._attachedToElement=!1,this._startDragRay=new qe(new o.P,new o.P),this._lastPointerRay={},this._dragDelta=new o.P,this._pointA=new o.P(0,0,0),this._pointC=new o.P(0,0,0),this._localAxis=new o.P(0,0,0),this._lookAt=new o.P(0,0,0),this._options=e||{};let t=0;if(this._options.dragAxis&&t++,this._options.dragPlaneNormal&&t++,t>1)throw"Multiple drag modes specified in dragBehavior options. Only one expected"}get name(){return"PointerDrag"}init(){}attach(e,t){this._scene=e.getScene(),e.isNearGrabbable=!0,this.attachedNode=e,et._PlaneScene||(this._debugMode?et._PlaneScene=this._scene:(et._PlaneScene=new N.x(this._scene.getEngine(),{virtual:!0}),et._PlaneScene.detachControl(),this._scene.onDisposeObservable.addOnce((()=>{et._PlaneScene.dispose(),et._PlaneScene=null})))),this._dragPlane=Je("pointerDragPlane",{size:this._debugMode?1:1e4,updatable:!1,sideOrientation:ee.Kj.DOUBLESIDE},et._PlaneScene),this.lastDragPosition=new o.P(0,0,0);const i=t||(e=>this.attachedNode==e||e.isDescendantOf(this.attachedNode));this._pointerObserver=this._scene.onPointerObservable.add((e=>{if(this.enabled){if(e.type==We.kD.POINTERDOWN)this.startAndReleaseDragOnPointerEvents&&!this.dragging&&e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh&&e.pickInfo.pickedPoint&&e.pickInfo.ray&&i(e.pickInfo.pickedMesh)&&-1===this._activeDragButton&&-1!==this.dragButtons.indexOf(e.event.button)&&(this._activeDragButton=e.event.button,this._activePointerInfo=e,this._startDrag(e.event.pointerId,e.pickInfo.ray,e.pickInfo.pickedPoint));else if(e.type==We.kD.POINTERUP)!this.startAndReleaseDragOnPointerEvents||this.currentDraggingPointerId!=e.event.pointerId||this._activeDragButton!==e.event.button&&-1!==this._activeDragButton||this.releaseDrag();else if(e.type==We.kD.POINTERMOVE){const t=e.event.pointerId;if(this.currentDraggingPointerId===et._AnyMouseId&&t!==et._AnyMouseId){const i=e.event;("mouse"===i.pointerType||!this._scene.getEngine().hostInformation.isMobile&&i instanceof MouseEvent)&&(this._lastPointerRay[this.currentDraggingPointerId]&&(this._lastPointerRay[t]=this._lastPointerRay[this.currentDraggingPointerId],delete this._lastPointerRay[this.currentDraggingPointerId]),this.currentDraggingPointerId=t)}this._lastPointerRay[t]||(this._lastPointerRay[t]=new qe(new o.P,new o.P)),e.pickInfo&&e.pickInfo.ray&&(this._lastPointerRay[t].origin.copyFrom(e.pickInfo.ray.origin),this._lastPointerRay[t].direction.copyFrom(e.pickInfo.ray.direction),this.currentDraggingPointerId==t&&this.dragging&&this._moveDrag(e.pickInfo.ray))}}else this._attachedToElement&&this.releaseDrag()})),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add((()=>{if(this._moving&&this.moveAttached){let e=!1;$e._RemoveAndStorePivotPoint(this.attachedNode),this._targetPosition.subtractToRef(this.attachedNode.absolutePosition,this._tmpVector),this._tmpVector.scaleInPlace(this.dragDeltaRatio),this.attachedNode.getAbsolutePosition().addToRef(this._tmpVector,this._tmpVector),this.validateDrag(this._tmpVector)&&(this.attachedNode.setAbsolutePosition(this._tmpVector),e=!0),$e._RestorePivotPoint(this.attachedNode),e&&this.attachedNode.computeWorldMatrix()}}))}releaseDrag(){if(this.dragging&&(this.dragging=!1,this.onDragEndObservable.notifyObservers({dragPlanePoint:this.lastDragPosition,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo})),this.currentDraggingPointerId=-1,this._activeDragButton=-1,this._activePointerInfo=null,this._moving=!1,this.detachCameraControls&&this._attachedToElement&&this._scene.activeCamera&&!this._scene.activeCamera.leftCamera){if("ArcRotateCamera"===this._scene.activeCamera.getClassName()){const e=this._scene.activeCamera;e.attachControl(!e.inputs||e.inputs.noPreventDefault,e._useCtrlForPanning,e._panningMouseButton)}else this._scene.activeCamera.attachControl(!this._scene.activeCamera.inputs||this._scene.activeCamera.inputs.noPreventDefault);this._attachedToElement=!1}}startDrag(e=et._AnyMouseId,t,i){this._startDrag(e,t,i);let n=this._lastPointerRay[e];e===et._AnyMouseId&&(n=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),n&&this._moveDrag(n)}_startDrag(e,t,i){if(!this._scene.activeCamera||this.dragging||!this.attachedNode)return;$e._RemoveAndStorePivotPoint(this.attachedNode),t?(this._startDragRay.direction.copyFrom(t.direction),this._startDragRay.origin.copyFrom(t.origin)):(this._startDragRay.origin.copyFrom(this._scene.activeCamera.position),this.attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector),this._tmpVector.subtractToRef(this._scene.activeCamera.position,this._startDragRay.direction)),this._updateDragPlanePosition(this._startDragRay,i||this._tmpVector);const n=this._pickWithRayOnDragPlane(this._startDragRay);n?(this.dragging=!0,this.currentDraggingPointerId=e,this.lastDragPosition.copyFrom(n),this.onDragStartObservable.notifyObservers({dragPlanePoint:n,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition()),this.detachCameraControls&&this._scene.activeCamera&&this._scene.activeCamera.inputs&&!this._scene.activeCamera.leftCamera&&(this._scene.activeCamera.inputs.attachedToElement?(this._scene.activeCamera.detachControl(),this._attachedToElement=!0):this._attachedToElement=!1)):this.releaseDrag(),$e._RestorePivotPoint(this.attachedNode)}_moveDrag(e){this._moving=!0;const t=this._pickWithRayOnDragPlane(e);if(t){$e._RemoveAndStorePivotPoint(this.attachedNode),this.updateDragPlane&&this._updateDragPlanePosition(e,t);let i=0;this._options.dragAxis?(this.useObjectOrientationForDragging?o.P.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis):this._worldDragAxis.copyFrom(this._options.dragAxis),t.subtractToRef(this.lastDragPosition,this._tmpVector),i=o.P.Dot(this._tmpVector,this._worldDragAxis),this._worldDragAxis.scaleToRef(i,this._dragDelta)):(i=this._dragDelta.length(),t.subtractToRef(this.lastDragPosition,this._dragDelta)),this._targetPosition.addInPlace(this._dragDelta),this.onDragObservable.notifyObservers({dragDistance:i,delta:this._dragDelta,dragPlanePoint:t,dragPlaneNormal:this._dragPlane.forward,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this.lastDragPosition.copyFrom(t),$e._RestorePivotPoint(this.attachedNode)}}_pickWithRayOnDragPlane(e){if(!e)return null;let t=Math.acos(o.P.Dot(this._dragPlane.forward,e.direction));if(t>Math.PI/2&&(t=Math.PI-t),this.maxDragAngle>0&&t>this.maxDragAngle){if(this._useAlternatePickedPointAboveMaxDragAngle){this._tmpVector.copyFrom(e.direction),this.attachedNode.absolutePosition.subtractToRef(e.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed*o.P.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);const t=o.P.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-t,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition),this._alternatePickedPoint}return null}const i=et._PlaneScene.pickWithRay(e,(e=>e==this._dragPlane));return i&&i.hit&&i.pickedMesh&&i.pickedPoint?i.pickedPoint:null}_updateDragPlanePosition(e,t){this._pointA.copyFrom(t),this._options.dragAxis?(this.useObjectOrientationForDragging?o.P.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragAxis),e.origin.subtractToRef(this._pointA,this._pointC),this._pointC.normalize(),Math.abs(o.P.Dot(this._localAxis,this._pointC))>.999?Math.abs(o.P.Dot(o.P.UpReadOnly,this._pointC))>.999?this._lookAt.copyFrom(o.P.Right()):this._lookAt.copyFrom(o.P.UpReadOnly):(o.P.CrossToRef(this._localAxis,this._pointC,this._lookAt),o.P.CrossToRef(this._localAxis,this._lookAt,this._lookAt),this._lookAt.normalize()),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._lookAt,this._lookAt),this._dragPlane.lookAt(this._lookAt)):this._options.dragPlaneNormal?(this.useObjectOrientationForDragging?o.P.TransformCoordinatesToRef(this._options.dragPlaneNormal,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragPlaneNormal),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._localAxis,this._lookAt),this._dragPlane.lookAt(this._lookAt)):(this._dragPlane.position.copyFrom(this._pointA),this._dragPlane.lookAt(e.origin)),this._dragPlane.position.copyFrom(this.attachedNode.getAbsolutePosition()),this._dragPlane.computeWorldMatrix(!0)}detach(){this._lastPointerRay={},this.attachedNode&&(this.attachedNode.isNearGrabbable=!1),this._pointerObserver&&this._scene.onPointerObservable.remove(this._pointerObserver),this._beforeRenderObserver&&this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver),this._dragPlane&&this._dragPlane.dispose(),this.releaseDrag()}}et._AnyMouseId=-2;class tt{}tt.ANCHOR_SYSTEM="xr-anchor-system",tt.BACKGROUND_REMOVER="xr-background-remover",tt.HIT_TEST="xr-hit-test",tt.MESH_DETECTION="xr-mesh-detection",tt.PHYSICS_CONTROLLERS="xr-physics-controller",tt.PLANE_DETECTION="xr-plane-detection",tt.POINTER_SELECTION="xr-controller-pointer-selection",tt.TELEPORTATION="xr-controller-teleportation",tt.FEATURE_POINTS="xr-feature-points",tt.HAND_TRACKING="xr-hand-tracking",tt.IMAGE_TRACKING="xr-image-tracking",tt.NEAR_INTERACTION="xr-near-interaction",tt.DOM_OVERLAY="xr-dom-overlay",tt.MOVEMENT="xr-controller-movement",tt.LIGHT_ESTIMATION="xr-light-estimation",tt.EYE_TRACKING="xr-eye-tracking",tt.WALKING_LOCOMOTION="xr-walking-locomotion",tt.LAYERS="xr-layers",tt.DEPTH_SENSING="xr-depth-sensing",tt.SPACE_WARP="xr-space-warp";class it{constructor(e){this._xrSessionManager=e,this._features={},this._xrSessionManager.onXRSessionInit.add((()=>{this.getEnabledFeatures().forEach((e=>{const t=this._features[e];!t.enabled||t.featureImplementation.attached||t.featureImplementation.disableAutoAttach||this.attachFeature(e)}))})),this._xrSessionManager.onXRSessionEnded.add((()=>{this.getEnabledFeatures().forEach((e=>{const t=this._features[e];t.enabled&&t.featureImplementation.attached&&this.detachFeature(e)}))}))}static AddWebXRFeature(e,t,i=1,n=!1){this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),n&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t}static ConstructFeature(e,t=1,i,n){const s=this._AvailableFeatures[e][t];if(!s)throw new Error("feature not found");return s(i,n)}static GetAvailableFeatures(){return Object.keys(this._AvailableFeatures)}static GetAvailableVersions(e){return Object.keys(this._AvailableFeatures[e])}static GetLatestVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].latest||-1}static GetStableVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].stable||-1}attachFeature(e){const t=this._features[e];t&&t.enabled&&!t.featureImplementation.attached&&t.featureImplementation.attach()}detachFeature(e){const t=this._features[e];t&&t.featureImplementation.attached&&t.featureImplementation.detach()}disableFeature(e){const t="string"==typeof e?e:e.Name,i=this._features[t];return!(!i||!i.enabled)&&(i.enabled=!1,this.detachFeature(t),i.featureImplementation.dispose(),delete this._features[t],!0)}dispose(){this.getEnabledFeatures().forEach((e=>{this.disableFeature(e)}))}enableFeature(e,t="latest",i={},n=!0,s=!0){const r="string"==typeof e?e:e.Name;let o=0;if("string"==typeof t){if(!t)throw new Error(`Error in provided version - ${r} (${t})`);if(o="stable"===t?it.GetStableVersionOfFeature(r):"latest"===t?it.GetLatestVersionOfFeature(r):+t,-1===o||isNaN(o))throw new Error(`feature not found - ${r} (${t})`)}else o=t;const a=it._ConflictingFeatures[r];if(void 0!==a&&-1!==this.getEnabledFeatures().indexOf(a))throw new Error(`Feature ${r} cannot be enabled while ${a} is enabled.`);const l=this._features[r],h=it.ConstructFeature(r,o,this._xrSessionManager,i);if(!h)throw new Error(`feature not found - ${r}`);l&&this.disableFeature(r);const c=h();if(c.dependsOn){const e=c.dependsOn.every((e=>!!this._features[e]));if(!e)throw new Error(`Dependant features missing. Make sure the following features are enabled - ${c.dependsOn.join(", ")}`)}if(c.isCompatible())return this._features[r]={featureImplementation:c,enabled:!0,version:o,required:s},n?this._xrSessionManager.session&&!this._features[r].featureImplementation.attached&&this.attachFeature(r):this._features[r].featureImplementation.disableAutoAttach=!0,this._features[r].featureImplementation;if(s)throw new Error("required feature not compatible");return se.w1.Warn(`Feature ${r} not compatible with the current environment/browser and was not enabled.`),c}getEnabledFeature(e){return this._features[e]&&this._features[e].featureImplementation}getEnabledFeatures(){return Object.keys(this._features)}async _extendXRSessionInitObject(e){const t=this.getEnabledFeatures();for(const i of t){const t=this._features[i],n=t.featureImplementation.xrNativeFeatureName;if(n&&(t.required?(e.requiredFeatures=e.requiredFeatures||[],-1===e.requiredFeatures.indexOf(n)&&e.requiredFeatures.push(n)):(e.optionalFeatures=e.optionalFeatures||[],-1===e.optionalFeatures.indexOf(n)&&e.optionalFeatures.push(n))),t.featureImplementation.getXRSessionInitExtension){const i=await t.featureImplementation.getXRSessionInitExtension();e=Object.assign(Object.assign({},e),i)}}return e}}it._AvailableFeatures={},it._ConflictingFeatures={[tt.TELEPORTATION]:tt.MOVEMENT,[tt.MOVEMENT]:tt.TELEPORTATION};class nt{constructor(e){this._xrSessionManager=e,this._attached=!1,this._removeOnDetach=[],this.isDisposed=!1,this.disableAutoAttach=!1,this.xrNativeFeatureName=""}get attached(){return this._attached}attach(e){if(this.isDisposed)return!1;if(e)this.attached&&this.detach();else if(this.attached)return!1;return this._attached=!0,this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable,(e=>this._onXRFrame(e))),!0}detach(){return this._attached?(this._attached=!1,this._removeOnDetach.forEach((e=>{e.observable.remove(e.observer)})),!0):(this.disableAutoAttach=!0,!1)}dispose(){this.detach(),this.isDisposed=!0}isCompatible(){return!0}_addNewAttachObserver(e,t){this._removeOnDetach.push({observable:e,observer:e.add(t)})}}class st{constructor(e,t){this.type=e,this.jointData=t,t.nativeParams=t.nativeParams||{}}get physicsJoint(){return this._physicsJoint}set physicsJoint(e){this._physicsJoint,this._physicsJoint=e}set physicsPlugin(e){this._physicsPlugin=e}executeNativeFunction(e){e(this._physicsPlugin.world,this._physicsJoint)}}st.DistanceJoint=0,st.HingeJoint=1,st.BallAndSocketJoint=2,st.WheelJoint=3,st.SliderJoint=4,st.PrismaticJoint=5,st.UniversalJoint=6,st.Hinge2Joint=st.WheelJoint,st.PointToPointJoint=8,st.SpringJoint=9,st.LockJoint=10;ee.Kj._PhysicsImpostorParser=function(e,t,i){return new rt(t,i.physicsImpostor,{mass:i.physicsMass,friction:i.physicsFriction,restitution:i.physicsRestitution},e)};class rt{get isDisposed(){return this._isDisposed}get mass(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyMass(this):0}set mass(e){this.setMass(e)}get friction(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyFriction(this):0}set friction(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyFriction(this,e)}get restitution(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this):0}set restitution(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this,e)}get pressure(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.setBodyPressure?e.getBodyPressure(this):0}set pressure(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyPressure&&t.setBodyPressure(this,e)}get stiffness(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyStiffness?e.getBodyStiffness(this):0}set stiffness(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyStiffness&&t.setBodyStiffness(this,e)}get velocityIterations(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyVelocityIterations?e.getBodyVelocityIterations(this):0}set velocityIterations(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyVelocityIterations&&t.setBodyVelocityIterations(this,e)}get positionIterations(){if(!this._physicsEngine)return 0;const e=this._physicsEngine.getPhysicsPlugin();return e.getBodyPositionIterations?e.getBodyPositionIterations(this):0}set positionIterations(e){if(!this._physicsEngine)return;const t=this._physicsEngine.getPhysicsPlugin();t.setBodyPositionIterations&&t.setBodyPositionIterations(this,e)}constructor(e,t,i={mass:0},n){this.object=e,this.type=t,this._options=i,this._scene=n,this._pluginData={},this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=new Array,this._onAfterPhysicsStepCallbacks=new Array,this._onPhysicsCollideCallbacks=[],this._deltaPosition=o.P.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new o._f,this._tmpQuat2=new o._f,this.beforeStep=()=>{this._physicsEngine&&(this.object.translate(this._deltaPosition,-1),this._deltaRotationConjugated&&this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotationConjugated,this.object.rotationQuaternion),this.object.computeWorldMatrix(!1),this.object.parent&&this.object.rotationQuaternion?(this.getParentsRotation(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this._tmpQuat)):this._tmpQuat.copyFrom(this.object.rotationQuaternion||new o._f),this._options.disableBidirectionalTransformation||this.object.rotationQuaternion&&this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this,this.object.getAbsolutePosition(),this._tmpQuat),this._onBeforePhysicsStepCallbacks.forEach((e=>{e(this)})))},this.afterStep=()=>{this._physicsEngine&&(this._onAfterPhysicsStepCallbacks.forEach((e=>{e(this)})),this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(this),this.object.parent&&this.object.rotationQuaternion&&(this.getParentsRotation(),this._tmpQuat.conjugateInPlace(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this.object.rotationQuaternion)),this.object.setAbsolutePosition(this.object.position),this._deltaRotation?(this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotation,this.object.rotationQuaternion),this._deltaPosition.applyRotationQuaternionToRef(this._deltaRotation,rt._TmpVecs[0]),this.object.translate(rt._TmpVecs[0],1)):this.object.translate(this._deltaPosition,1),this.object.computeWorldMatrix(!0))},this.onCollideEvent=null,this.onCollide=e=>{if(!this._onPhysicsCollideCallbacks.length&&!this.onCollideEvent)return;if(!this._physicsEngine)return;const t=this._physicsEngine.getImpostorWithPhysicsBody(e.body);t&&(this.onCollideEvent&&this.onCollideEvent(this,t),this._onPhysicsCollideCallbacks.filter((e=>-1!==e.otherImpostors.indexOf(t))).forEach((i=>{i.callback(this,t,e.point,e.distance,e.impulse,e.normal)})))},this.object?(this.object.parent&&0!==i.mass&&p.Y.Warn("A physics impostor has been created for an object which has a parent. Babylon physics currently works in local space so unexpected issues may occur."),!this._scene&&e.getScene&&(this._scene=e.getScene()),this._scene&&(this.type>100&&(this.soft=!0),this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine?(this.object.rotationQuaternion||(this.object.rotation?this.object.rotationQuaternion=o._f.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new o._f),this._options.mass=void 0===i.mass?0:i.mass,this._options.friction=void 0===i.friction?.2:i.friction,this._options.restitution=void 0===i.restitution?.2:i.restitution,this.soft&&(this._options.mass=this._options.mass>0?this._options.mass:1,this._options.pressure=void 0===i.pressure?200:i.pressure,this._options.stiffness=void 0===i.stiffness?1:i.stiffness,this._options.velocityIterations=void 0===i.velocityIterations?20:i.velocityIterations,this._options.positionIterations=void 0===i.positionIterations?20:i.positionIterations,this._options.fixedPoints=void 0===i.fixedPoints?0:i.fixedPoints,this._options.margin=void 0===i.margin?0:i.margin,this._options.damping=void 0===i.damping?0:i.damping,this._options.path=void 0===i.path?null:i.path,this._options.shape=void 0===i.shape?null:i.shape),this._joints=[],!this.object.parent||this._options.ignoreParent?this._init():this.object.parent.physicsImpostor&&p.Y.Warn("You must affect impostors to children before affecting impostor to parent.")):p.Y.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors."))):p.Y.Error("No object was provided. A physics object is obligatory")}_init(){this._physicsEngine&&(this._physicsEngine.removeImpostor(this),this.physicsBody=null,this._parent=this._parent||this._getPhysicsParent(),this._isDisposed||this.parent&&!this._options.ignoreParent||this._physicsEngine.addImpostor(this))}_getPhysicsParent(){if(this.object.parent instanceof ie.x){return this.object.parent.physicsImpostor}return null}isBodyInitRequired(){return this._bodyUpdateRequired||!this._physicsBody&&(!this._parent||!!this._options.ignoreParent)}setScalingUpdated(){this.forceUpdate()}forceUpdate(){this._init(),this.parent&&!this._options.ignoreParent&&this.parent.forceUpdate()}get physicsBody(){return this._parent&&!this._options.ignoreParent?this._parent.physicsBody:this._physicsBody}get parent(){return!this._options.ignoreParent&&this._parent?this._parent:null}set parent(e){this._parent=e}set physicsBody(e){this._physicsBody&&this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this),this._physicsBody=e,this.resetUpdateFlags()}resetUpdateFlags(){this._bodyUpdateRequired=!1}getObjectExtents(){if(this.object.getBoundingInfo){const e=this.object.rotationQuaternion,t=this.object.scaling.clone();this.object.rotationQuaternion=rt.IDENTITY_QUATERNION;const i=this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);i&&i.decompose(t,void 0,void 0);const n=this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiplyInPlace(t);return n.x=Math.abs(n.x),n.y=Math.abs(n.y),n.z=Math.abs(n.z),this.object.rotationQuaternion=e,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),n}return rt.DEFAULT_OBJECT_SIZE}getObjectCenter(){if(this.object.getBoundingInfo){return this.object.getBoundingInfo().boundingBox.centerWorld}return this.object.position}getParam(e){return this._options[e]}setParam(e,t){this._options[e]=t,this._bodyUpdateRequired=!0}setMass(e){this.getParam("mass")!==e&&this.setParam("mass",e),this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyMass(this,e)}getLinearVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this):o.P.Zero()}setLinearVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)}getAngularVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):o.P.Zero()}setAngularVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this,e)}executeNativeFunction(e){this._physicsEngine&&e(this._physicsEngine.getPhysicsPlugin().world,this.physicsBody)}registerBeforePhysicsStep(e){this._onBeforePhysicsStepCallbacks.push(e)}unregisterBeforePhysicsStep(e){const t=this._onBeforePhysicsStepCallbacks.indexOf(e);t>-1?this._onBeforePhysicsStepCallbacks.splice(t,1):p.Y.Warn("Function to remove was not found")}registerAfterPhysicsStep(e){this._onAfterPhysicsStepCallbacks.push(e)}unregisterAfterPhysicsStep(e){const t=this._onAfterPhysicsStepCallbacks.indexOf(e);t>-1?this._onAfterPhysicsStepCallbacks.splice(t,1):p.Y.Warn("Function to remove was not found")}registerOnPhysicsCollide(e,t){const i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})}unregisterOnPhysicsCollide(e,t){const i=e instanceof Array?e:[e];let n=-1;this._onPhysicsCollideCallbacks.some(((e,s)=>{if(e.callback===t&&e.otherImpostors.length===i.length){const t=e.otherImpostors.every((e=>i.indexOf(e)>-1));return t&&(n=s),t}return!1}))?this._onPhysicsCollideCallbacks.splice(n,1):p.Y.Warn("Function to remove was not found")}getParentsRotation(){let e=this.object.parent;for(this._tmpQuat.copyFromFloats(0,0,0,1);e;)e.rotationQuaternion?this._tmpQuat2.copyFrom(e.rotationQuaternion):o._f.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,this._tmpQuat2),this._tmpQuat.multiplyToRef(this._tmpQuat2,this._tmpQuat),e=e.parent;return this._tmpQuat}applyForce(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t),this}applyImpulse(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t),this}createJoint(e,t,i){const n=new st(t,i);return this.addJoint(e,n),this}addJoint(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this}addAnchor(e,t,i,n,s){if(!this._physicsEngine)return this;const r=this._physicsEngine.getPhysicsPlugin();return r.appendAnchor?(this._physicsEngine&&r.appendAnchor(this,e,t,i,n,s),this):this}addHook(e,t,i,n){if(!this._physicsEngine)return this;const s=this._physicsEngine.getPhysicsPlugin();return s.appendAnchor?(this._physicsEngine&&s.appendHook(this,e,t,i,n),this):this}sleep(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().sleepBody(this),this}wakeUp(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),this}clone(e){return e?new rt(e,this.type,this._options,this._scene):null}dispose(){this._physicsEngine&&(this._joints.forEach((e=>{this._physicsEngine&&this._physicsEngine.removeJoint(this,e.otherImpostor,e.joint)})),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate(),this._isDisposed=!0)}setDeltaPosition(e){this._deltaPosition.copyFrom(e)}setDeltaRotation(e){this._deltaRotation||(this._deltaRotation=new o._f),this._deltaRotation.copyFrom(e),this._deltaRotationConjugated=this._deltaRotation.conjugate()}getBoxSizeToRef(e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,e),this}getRadius(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0}syncBoneWithImpostor(e,t,i,n,s){const r=rt._TmpVecs[0],o=this.object;if(o.rotationQuaternion)if(s){const i=rt._TmpQuat;o.rotationQuaternion.multiplyToRef(s,i),e.setRotationQuaternion(i,L.T.WORLD,t)}else e.setRotationQuaternion(o.rotationQuaternion,L.T.WORLD,t);r.x=0,r.y=0,r.z=0,i&&(r.x=i.x,r.y=i.y,r.z=i.z,e.getDirectionToRef(r,t,r),null==n&&(n=i.length()),r.x*=n,r.y*=n,r.z*=n),e.getParent()?(r.addInPlace(o.getAbsolutePosition()),e.setAbsolutePosition(r,t)):(t.setAbsolutePosition(o.getAbsolutePosition()),t.position.x-=r.x,t.position.y-=r.y,t.position.z-=r.z)}syncImpostorWithBone(e,t,i,n,s,r){const o=this.object;if(o.rotationQuaternion)if(s){const i=rt._TmpQuat;e.getRotationQuaternionToRef(L.T.WORLD,t,i),i.multiplyToRef(s,o.rotationQuaternion)}else e.getRotationQuaternionToRef(L.T.WORLD,t,o.rotationQuaternion);const a=rt._TmpVecs[0],l=rt._TmpVecs[1];r||((r=rt._TmpVecs[2]).x=0,r.y=1,r.z=0),e.getDirectionToRef(r,t,l),e.getAbsolutePositionToRef(t,a),null==n&&i&&(n=i.length()),null!=n&&(a.x+=l.x*n,a.y+=l.y*n,a.z+=l.z*n),o.setAbsolutePosition(a)}}rt.DEFAULT_OBJECT_SIZE=new o.P(1,1,1),rt.IDENTITY_QUATERNION=o._f.Identity(),rt._TmpVecs=w.B.BuildArray(3,o.P.Zero),rt._TmpQuat=o._f.Identity(),rt.NoImpostor=0,rt.SphereImpostor=1,rt.BoxImpostor=2,rt.PlaneImpostor=3,rt.MeshImpostor=4,rt.CapsuleImpostor=6,rt.CylinderImpostor=7,rt.ParticleImpostor=8,rt.HeightmapImpostor=9,rt.ConvexHullImpostor=10,rt.CustomImpostor=100,rt.RopeImpostor=101,rt.ClothImpostor=102,rt.SoftbodyImpostor=103;var ot,at=i(5458),lt=i(9714);!function(e){e[e.Clean=0]="Clean",e[e.Stop=1]="Stop",e[e.Sync=2]="Sync",e[e.NoSync=3]="NoSync"}(ot||(ot={}));class ht{static get ForceFullSceneLoadingForIncremental(){return at.Z.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){at.Z.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return at.Z.ShowLoadingScreen}static set ShowLoadingScreen(e){at.Z.ShowLoadingScreen=e}static get loggingLevel(){return at.Z.loggingLevel}static set loggingLevel(e){at.Z.loggingLevel=e}static get CleanBoneMatrixWeights(){return at.Z.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){at.Z.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return ht._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){const t=ht._RegisteredPlugins[e];return t||(p.Y.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"),ht.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(const t in ht._RegisteredPlugins){const i=ht._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return ht._RegisteredPlugins[t]}return ht.GetDefaultPlugin()}static _GetPluginForFilename(e){const t=e.indexOf("?");-1!==t&&(e=e.substring(0,t));const i=e.lastIndexOf("."),n=e.substring(i,e.length).toLowerCase();return ht._GetPluginForExtension(n)}static _GetDirectLoad(e){return"data:"===e.substr(0,5)?e.substr(5):null}static _FormatErrorMessage(e,t,i){let n="Unable to load from "+(e.rawData?"binary data":e.url);return t?n+=`: ${t}`:i&&(n+=`: ${i}`),n}static _LoadData(e,t,i,n,s,r,o,a){const l=ht._GetDirectLoad(e.url);if(e.rawData&&!o)throw"When using ArrayBufferView to load data the file extension must be provided.";const h=o?ht._GetPluginForExtension(o):l?ht._GetPluginForDirectLoad(e.url):ht._GetPluginForFilename(e.url);if(e.rawData&&!h.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";let c;if(c=void 0!==h.plugin.createPlugin?h.plugin.createPlugin():h.plugin,!c)throw"The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.";if(ht.OnPluginActivatedObservable.notifyObservers(c),l&&(c.canDirectLoad&&c.canDirectLoad(e.url)||!(0,ye.VL)(e.url))){if(c.directLoad){const e=c.directLoad(t,l);e.then?e.then((e=>{i(c,e)})).catch((e=>{s("Error in directLoad of _loadData: "+e,e)})):i(c,e)}else i(c,l);return c}const d=h.isBinary,u=(e,n)=>{t.isDisposed?s("Scene has been disposed"):i(c,e,n)};let p=null,f=!1;const _=c.onDisposeObservable;_&&_.add((()=>{f=!0,p&&(p.abort(),p=null),r()}));const m=()=>{if(f)return;const i=(e,t)=>{s(null==e?void 0:e.statusText,t)};if(!c.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";p=c.loadFile?c.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,u,n,d,i,a):t._loadFile(e.file||e.url,u,n,!0,d,i)},g=t.getEngine();let v=g.enableOfflineSupport;if(v){let i=!1;for(const n of t.disableOfflineSupportExceptionRules)if(n.test(e.url)){i=!0;break}v=!i}return v&&fe.D.OfflineProviderFactory?t.offlineProvider=fe.D.OfflineProviderFactory(e.url,m,g.disableManifestCheck):m(),c}static _GetFileInfo(e,t){let i,n,s=null,r=null;if(t)if(t.name){const e=t;i=`file:${e.name}`,n=e.name,s=e}else if(ArrayBuffer.isView(t))i="",n="arrayBuffer",r=t;else if("string"==typeof t&&t.startsWith("data:"))i=t,n="";else{const s=t;if("/"===s.substr(0,1))return se.w1.Error("Wrong sceneFilename parameter"),null;i=e+s,n=s}else i=e,n=se.w1.GetFilename(e),e=se.w1.GetFolderPath(e);return{url:i,rootUrl:e,name:n,file:s,rawData:r}}static GetPluginForExtension(e){return ht._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!ht._RegisteredPlugins[e]}static RegisterPlugin(e){if("string"==typeof e.extensions){const t=e.extensions;ht._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{const t=e.extensions;Object.keys(t).forEach((i=>{ht._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}}))}}static ImportMesh(e,t,i="",n=m.l.LastCreatedScene,s=null,r=null,o=null,a=null,l=""){if(!n)return p.Y.Error("No scene available to import mesh to"),null;const h=ht._GetFileInfo(t,i);if(!h)return null;const c={};n.addPendingData(c);const d=()=>{n.removePendingData(c)},u=(e,t)=>{const i=ht._FormatErrorMessage(h,e,t);o?o(n,i,new lt.LH(i,lt.SM.SceneLoaderError,t)):p.Y.Error(i),d()},f=r?e=>{try{r(e)}catch(t){u("Error in onProgress callback: "+t,t)}}:void 0,_=(e,t,i,r,o,a,l)=>{if(n.importedMeshesFiles.push(h.url),s)try{s(e,t,i,r,o,a,l)}catch(d){u("Error in onSuccess callback: "+d,d)}n.removePendingData(c)};return ht._LoadData(h,n,((t,i,s)=>{if(t.rewriteRootURL&&(h.rootUrl=t.rewriteRootURL(h.rootUrl,s)),t.importMesh){const s=t,r=new Array,o=new Array,a=new Array;if(!s.importMesh(e,n,i,h.rootUrl,r,o,a,u))return;n.loadingPluginName=t.name,_(r,o,a,[],[],[],[])}else{t.importMeshAsync(e,n,i,h.rootUrl,f,h.name).then((e=>{n.loadingPluginName=t.name,_(e.meshes,e.particleSystems,e.skeletons,e.animationGroups,e.transformNodes,e.geometries,e.lights)})).catch((e=>{u(e.message,e)}))}}),f,u,d,a,l)}static ImportMeshAsync(e,t,i="",n=m.l.LastCreatedScene,s=null,r=null,o=""){return new Promise(((a,l)=>{ht.ImportMesh(e,t,i,n,((e,t,i,n,s,r,o)=>{a({meshes:e,particleSystems:t,skeletons:i,animationGroups:n,transformNodes:s,geometries:r,lights:o})}),s,((e,t,i)=>{l(i||new Error(t))}),r,o)}))}static Load(e,t="",i=m.l.LastCreatedEngine,n=null,s=null,r=null,o=null,a=""){return i?ht.Append(e,t,new N.x(i),n,s,r,o,a):(se.w1.Error("No engine available"),null)}static LoadAsync(e,t="",i=m.l.LastCreatedEngine,n=null,s=null,r=""){return new Promise(((o,a)=>{ht.Load(e,t,i,(e=>{o(e)}),n,((e,t,i)=>{a(i||new Error(t))}),s,r)}))}static Append(e,t="",i=m.l.LastCreatedScene,n=null,s=null,r=null,o=null,a=""){if(!i)return p.Y.Error("No scene available to append to"),null;const l=ht._GetFileInfo(e,t);if(!l)return null;const h={};i.addPendingData(h);const c=()=>{i.removePendingData(h)};ht.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady((()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1})));const d=(e,t)=>{const n=ht._FormatErrorMessage(l,e,t);r?r(i,n,new lt.LH(n,lt.SM.SceneLoaderError,t)):p.Y.Error(n),c()},u=s?e=>{try{s(e)}catch(t){d("Error in onProgress callback",t)}}:void 0,f=()=>{if(n)try{n(i)}catch(e){d("Error in onSuccess callback",e)}i.removePendingData(h)};return ht._LoadData(l,i,((e,t)=>{if(e.load){if(!e.load(i,t,l.rootUrl,d))return;i.loadingPluginName=e.name,f()}else{e.loadAsync(i,t,l.rootUrl,u,l.name).then((()=>{i.loadingPluginName=e.name,f()})).catch((e=>{d(e.message,e)}))}}),u,d,c,o,a)}static AppendAsync(e,t="",i=m.l.LastCreatedScene,n=null,s=null,r=""){return new Promise(((o,a)=>{ht.Append(e,t,i,(e=>{o(e)}),n,((e,t,i)=>{a(i||new Error(t))}),s,r)}))}static LoadAssetContainer(e,t="",i=m.l.LastCreatedScene,n=null,s=null,r=null,o=null,a=""){if(!i)return p.Y.Error("No scene available to load asset container to"),null;const l=ht._GetFileInfo(e,t);if(!l)return null;const h={};i.addPendingData(h);const c=()=>{i.removePendingData(h)},d=(e,t)=>{const n=ht._FormatErrorMessage(l,e,t);r?r(i,n,new lt.LH(n,lt.SM.SceneLoaderError,t)):p.Y.Error(n),c()},u=s?e=>{try{s(e)}catch(t){d("Error in onProgress callback",t)}}:void 0,f=e=>{if(n)try{n(e)}catch(t){d("Error in onSuccess callback",t)}i.removePendingData(h)};return ht._LoadData(l,i,((e,t)=>{if(e.loadAssetContainer){const n=e.loadAssetContainer(i,t,l.rootUrl,d);if(!n)return;i.loadingPluginName=e.name,f(n)}else if(e.loadAssetContainerAsync){e.loadAssetContainerAsync(i,t,l.rootUrl,u,l.name).then((t=>{i.loadingPluginName=e.name,f(t)})).catch((e=>{d(e.message,e)}))}else d("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")}),u,d,c,o,a)}static LoadAssetContainerAsync(e,t="",i=m.l.LastCreatedScene,n=null,s=null){return new Promise(((r,o)=>{ht.LoadAssetContainer(e,t,i,(e=>{r(e)}),n,((e,t,i)=>{o(i||new Error(t))}),s)}))}static ImportAnimations(e,t="",i=m.l.LastCreatedScene,n=!0,s=ot.Clean,r=null,o=null,a=null,l=null,h=null){if(!i)return void p.Y.Error("No scene available to load animations to");if(n){for(const e of i.animatables)e.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach((e=>{e.dispose()}));i.getNodes().forEach((e=>{e.animations&&(e.animations=[])}))}else switch(s){case ot.Clean:i.animationGroups.slice().forEach((e=>{e.dispose()}));break;case ot.Stop:i.animationGroups.forEach((e=>{e.stop()}));break;case ot.Sync:i.animationGroups.forEach((e=>{e.reset(),e.restart()}));break;case ot.NoSync:break;default:return void p.Y.Error("Unknown animation group loading mode value '"+s+"'")}const c=i.animatables.length;this.LoadAssetContainer(e,t,i,(e=>{e.mergeAnimationsTo(i,i.animatables.slice(c),r),e.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),o&&o(i)}),a,l,h)}static ImportAnimationsAsync(e,t="",i=m.l.LastCreatedScene,n=!0,s=ot.Clean,r=null,o=null,a=null,l=null,h=null){return new Promise(((o,l)=>{ht.ImportAnimations(e,t,i,n,s,r,(e=>{o(e)}),a,((e,t,i)=>{l(i||new Error(t))}),h)}))}}ht.NO_LOGGING=0,ht.MINIMAL_LOGGING=1,ht.SUMMARY_LOGGING=2,ht.DETAILED_LOGGING=3,ht.OnPluginActivatedObservable=new r.y$,ht._RegisteredPlugins={},ht._ShowingLoadingScreen=!1;var ct,dt,ut=i(2067);class pt extends ut.F{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new o.y3,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){super._afterBind(e,t),this.getScene()._cachedEffect=t,t&&(t._forceRebindOnNextCall=!1)}_mustRebind(e,t,i=1){return e.isCachedMaterialInvalid(this,t,i)}dispose(e,t,i){this._activeEffect=void 0,super.dispose(e,t,i)}}!function(e){e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=4]="Vector2",e[e.Vector3=8]="Vector3",e[e.Vector4=16]="Vector4",e[e.Color3=32]="Color3",e[e.Color4=64]="Color4",e[e.Matrix=128]="Matrix",e[e.Object=256]="Object",e[e.AutoDetect=1024]="AutoDetect",e[e.BasedOnInput=2048]="BasedOnInput",e[e.All=4095]="All"}(ct||(ct={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Neutral=4]="Neutral",e[e.VertexAndFragment=3]="VertexAndFragment"}(dt||(dt={}));var ft=i(4442);class _t{constructor(){this.supportUniformBuffers=!1,this.attributes=new Array,this.uniforms=new Array,this.constants=new Array,this.samplers=new Array,this.functions={},this.extensions={},this.counters={},this._attributeDeclaration="",this._uniformDeclaration="",this._constantDeclaration="",this._samplerDeclaration="",this._varyingTransfer="",this._injectAtEnd="",this._repeatableContentAnchorIndex=0,this._builtCompilationString="",this.compilationString=""}finalize(e){const t=e.sharedData.emitComments,i=this.target===dt.Fragment;this.compilationString=`\r\n${t?"//Entry point\r\n":""}void main(void) {\r\n${this.compilationString}`,this._constantDeclaration&&(this.compilationString=`\r\n${t?"//Constants\r\n":""}${this._constantDeclaration}\r\n${this.compilationString}`);let n="";for(const s in this.functions)n+=this.functions[s]+"\r\n";this.compilationString=`\r\n${n}\r\n${this.compilationString}`,!i&&this._varyingTransfer&&(this.compilationString=`${this.compilationString}\r\n${this._varyingTransfer}`),this._injectAtEnd&&(this.compilationString=`${this.compilationString}\r\n${this._injectAtEnd}`),this.compilationString=`${this.compilationString}\r\n}`,this.sharedData.varyingDeclaration&&(this.compilationString=`\r\n${t?"//Varyings\r\n":""}${this.sharedData.varyingDeclaration}\r\n${this.compilationString}`),this._samplerDeclaration&&(this.compilationString=`\r\n${t?"//Samplers\r\n":""}${this._samplerDeclaration}\r\n${this.compilationString}`),this._uniformDeclaration&&(this.compilationString=`\r\n${t?"//Uniforms\r\n":""}${this._uniformDeclaration}\r\n${this.compilationString}`),this._attributeDeclaration&&!i&&(this.compilationString=`\r\n${t?"//Attributes\r\n":""}${this._attributeDeclaration}\r\n${this.compilationString}`),this.compilationString="precision highp float;\r\n"+this.compilationString,this.compilationString="#if defined(WEBGL2) || defines(WEBGPU)\r\nprecision highp sampler2DArray;\r\n#endif\r\n"+this.compilationString;for(const s in this.extensions){const e=this.extensions[s];this.compilationString=`\r\n${e}\r\n${this.compilationString}`}this._builtCompilationString=this.compilationString}get _repeatableContentAnchor(){return`###___ANCHOR${this._repeatableContentAnchorIndex++}___###`}_getFreeVariableName(e){return e=e.replace(/[^a-zA-Z_]+/g,""),void 0===this.sharedData.variableNames[e]?(this.sharedData.variableNames[e]=0,"output"===e||"texture"===e?e+this.sharedData.variableNames[e]:e):(this.sharedData.variableNames[e]++,e+this.sharedData.variableNames[e])}_getFreeDefineName(e){return void 0===this.sharedData.defineNames[e]?this.sharedData.defineNames[e]=0:this.sharedData.defineNames[e]++,e+this.sharedData.defineNames[e]}_excludeVariableName(e){this.sharedData.variableNames[e]=0}_emit2DSampler(e){this.samplers.indexOf(e)<0&&(this._samplerDeclaration+=`uniform sampler2D ${e};\r\n`,this.samplers.push(e))}_emit2DArraySampler(e){this.samplers.indexOf(e)<0&&(this._samplerDeclaration+=`uniform sampler2DArray ${e};\r\n`,this.samplers.push(e))}_getGLType(e){switch(e){case ct.Float:return"float";case ct.Int:return"int";case ct.Vector2:return"vec2";case ct.Color3:case ct.Vector3:return"vec3";case ct.Color4:case ct.Vector4:return"vec4";case ct.Matrix:return"mat4"}return""}_emitExtension(e,t,i=""){this.extensions[e]||(i&&(t=`#if ${i}\r\n${t}\r\n#endif`),this.extensions[e]=t)}_emitFunction(e,t,i){this.functions[e]||(this.sharedData.emitComments&&(t=i+"\r\n"+t),this.functions[e]=t)}_emitCodeFromInclude(e,t,i){if(i&&i.repeatKey)return`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}]\r\n`;let n=ft.Q.IncludesShadersStore[e]+"\r\n";if(this.sharedData.emitComments&&(n=t+"\r\n"+n),!i)return n;if(i.replaceStrings)for(let s=0;s${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}]\r\n`:this.functions[s]=`#include<${e}>${(null==i?void 0:i.substitutionVars)?"("+(null==i?void 0:i.substitutionVars)+")":""}\r\n`,void(this.sharedData.emitComments&&(this.functions[s]=t+"\r\n"+this.functions[s]));if(this.functions[s]=ft.Q.IncludesShadersStore[e],this.sharedData.emitComments&&(this.functions[s]=t+"\r\n"+this.functions[s]),i.removeIfDef&&(this.functions[s]=this.functions[s].replace(/^\s*?#ifdef.+$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#endif.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#else.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[s]=this.functions[s].replace(/^\s*?attribute.+$/gm,"")),i.removeUniforms&&(this.functions[s]=this.functions[s].replace(/^\s*?uniform.+$/gm,"")),i.removeVaryings&&(this.functions[s]=this.functions[s].replace(/^\s*?varying.+$/gm,"")),i.replaceStrings)for(let e=0;ee.ownerBlock))}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get isDirectlyConnectedToVertexOutput(){if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===dt.Vertex)return!0;if((e.ownerBlock.target===dt.Neutral||e.ownerBlock.target===dt.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isDirectlyConnectedToVertexOutput)))return!0}return!1}get isConnectedInVertexShader(){if(this.target===dt.Vertex)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===dt.Vertex)return!0;if(e.target===dt.Vertex)return!0;if((e.ownerBlock.target===dt.Neutral||e.ownerBlock.target===dt.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isConnectedInVertexShader)))return!0}return!1}get isConnectedInFragmentShader(){if(this.target===dt.Fragment)return!0;if(!this.hasEndpoints)return!1;for(const e of this._endpoints){if(e.ownerBlock.target===dt.Fragment)return!0;if((e.ownerBlock.target===dt.Neutral||e.ownerBlock.target===dt.VertexAndFragment)&&e.ownerBlock.outputs.some((e=>e.isConnectedInFragmentShader)))return!0}return!1}createCustomInputBlock(){return null}constructor(e,t,i){this._connectedPoint=null,this._endpoints=new Array,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this._linkedConnectionSource=null,this._acceptedConnectionPointType=null,this._type=ct.Float,this._enforceAssociatedVariableName=!1,this.needDualDirectionValidation=!1,this.acceptedConnectionPointTypes=new Array,this.excludedConnectionPointTypes=new Array,this.onConnectionObservable=new r.y$,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._prioritizeVertex=!1,this._target=dt.VertexAndFragment,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeMaterialConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===gt.Compatible}checkCompatibilityState(e){const t=this._ownerBlock,i=e.ownerBlock;if(t.target===dt.Fragment){if(i.target===dt.Vertex)return gt.TargetIncompatible;for(const e of i.outputs)if(e.ownerBlock.target!=dt.Neutral&&e.isConnectedInVertexShader)return gt.TargetIncompatible}if(this.type!==e.type&&e.innerType!==ct.AutoDetect)return St.AreEquivalentTypes(this.type,e.type)||e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)||e._acceptedConnectionPointType&&St.AreEquivalentTypes(e._acceptedConnectionPointType.type,this.type)?gt.Compatible:gt.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return gt.TypeIncompatible;let n=i,s=t;return this.direction===vt.Input&&(n=t,s=i),n.isAnAncestorOf(s)?gt.HierarchyIssue:gt.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this._enforceAssociatedVariableName=!1,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){const t=this._endpoints.indexOf(e);return-1===t||(this._endpoints.splice(t,1),e._connectedPoint=null,this._enforceAssociatedVariableName=!1,e._enforceAssociatedVariableName=!1),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear()}}var Et,xt=i(8501);class bt{get name(){return this._name}set name(e){this.validateBlockName(e)&&(this._name=e)}get isUnique(){return this._isUnique}get isFinalMerger(){return this._isFinalMerger}get isInput(){return this._isInput}get buildId(){return this._buildId}set buildId(e){this._buildId=e}get target(){return this._target}set target(e){0==(this._target&e)&&(this._target=e)}get inputs(){return this._inputs}get outputs(){return this._outputs}getInputByName(e){const t=this._inputs.filter((t=>t.name===e));return t.length?t[0]:null}getOutputByName(e){const t=this._outputs.filter((t=>t.name===e));return t.length?t[0]:null}constructor(e,t=dt.Vertex,i=!1,n=!1){this._isFinalMerger=!1,this._isInput=!1,this._name="",this._isUnique=!1,this.inputsAreExclusive=!1,this._codeVariableName="",this._inputs=new Array,this._outputs=new Array,this.comments="",this.visibleInInspector=!1,this.visibleOnFrame=!1,this._target=t,this._originalTargetIsNeutral=t===dt.Neutral,this._isFinalMerger=i,this._isInput=n,this._name=e,this.uniqueId=xt.K.UniqueId}_setInitialTarget(e){this._target=e,this._originalTargetIsNeutral=e===dt.Neutral}initialize(e){}bind(e,t,i,n){}_declareOutput(e,t){return`${t._getGLType(e.type)} ${e.associatedVariableName}`}_writeVariable(e){return e.connectedPoint?`${e.associatedVariableName}`:"0."}_writeFloat(e){let t=e.toString();return-1===t.indexOf(".")&&(t+=".0"),`${t}`}getClassName(){return"NodeMaterialBlock"}registerInput(e,t,i=!1,n,s){return(s=null!=s?s:new St(e,this,vt.Input)).type=t,s.isOptional=i,n&&(s.target=n),this._inputs.push(s),this}registerOutput(e,t,i,n){return(n=null!=n?n:new St(e,this,vt.Output)).type=t,i&&(n.target=i),this._outputs.push(n),this}getFirstAvailableInput(e=null){for(const t of this._inputs)if(!(t.connectedPoint||e&&e.type!==t.type&&t.type!==ct.AutoDetect))return t;return null}getFirstAvailableOutput(e=null){for(const t of this._outputs)if(!e||!e.target||e.target===dt.Neutral||0!=(e.target&t.target))return t;return null}getSiblingOutput(e){const t=this._outputs.indexOf(e);return-1===t||t>=this._outputs.length?null:this._outputs[t+1]}isAnAncestorOf(e){for(const t of this._outputs)if(t.hasEndpoints)for(const i of t.endpoints){if(i.ownerBlock===e)return!0;if(i.ownerBlock.isAnAncestorOf(e))return!0}return!1}connectTo(e,t){if(0===this._outputs.length)return;let i=t&&t.output?this.getOutputByName(t.output):this.getFirstAvailableOutput(e),n=!0;for(;n;){const s=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&s&&i.canConnectTo(s))i.connectTo(s),n=!1;else{if(!i)throw"Unable to find a compatible match";i=this.getSiblingOutput(i)}}return this}_buildBlock(e){}updateUniformsAndSamples(e,t,i,n){}provideFallbacks(e,t){}initializeDefines(e,t,i,n=!1){}prepareDefines(e,t,i,n=!1,s){}autoConfigure(e){}replaceRepeatableContent(e,t,i,n){}get willBeGeneratedIntoVertexShaderFromFragmentShader(){return!this.isInput&&!this.isFinalMerger&&(!this._outputs.some((e=>e.isDirectlyConnectedToVertexOutput))&&(this.target!==dt.Vertex&&!(this.target!==dt.VertexAndFragment&&this.target!==dt.Neutral||!this._outputs.some((e=>e.isConnectedInVertexShader)))))}isReady(e,t,i,n=!1){return!0}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}_processBuild(e,t,i,n){e.build(t,n);const s=null!=t._vertexState,r=e._buildTarget===dt.Vertex&&e.target!==dt.VertexAndFragment;if(s&&(0==(e.target&e._buildTarget)||0==(e.target&i.target)||this.target!==dt.VertexAndFragment&&r)&&(!e.isInput&&t.target!==e._buildTarget||e.isInput&&e.isAttribute&&!e._noContextSwitch)){const e=i.connectedPoint;t._vertexState._emitVaryingFromString("v_"+e.associatedVariableName,t._getGLType(e.type))&&(t._vertexState.compilationString+=`${"v_"+e.associatedVariableName} = ${e.associatedVariableName};\r\n`),i.associatedVariableName="v_"+e.associatedVariableName,i._enforceAssociatedVariableName=!0}}validateBlockName(e){const t=["position","normal","tangent","particle_positionw","uv","uv2","uv3","uv4","uv5","uv6","position2d","particle_uv","matricesIndices","matricesWeights","world0","world1","world2","world3","particle_color","particle_texturemask"];for(const i of t)if(e===i)return!1;return!0}build(e,t){if(this._buildId===e.sharedData.buildId)return!0;if(!this.isInput)for(const i of this._outputs)i.associatedVariableName||(i.associatedVariableName=e._getFreeVariableName(i.name));for(const i of this._inputs){if(!i.connectedPoint){i.isOptional||e.sharedData.checks.notConnectedNonOptionalInputs.push(i);continue}if(this.target!==dt.Neutral){if(0==(i.target&this.target))continue;if(0==(i.target&e.target))continue}const n=i.connectedPoint.ownerBlock;n&&n!==this&&this._processBuild(n,e,i,t)}if(this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&console.log(`${e.target===dt.Vertex?"Vertex shader":"Fragment shader"}: Building ${this.name} [${this.getClassName()}]`),this.isFinalMerger)switch(e.target){case dt.Vertex:e.sharedData.checks.emitVertex=!0;break;case dt.Fragment:e.sharedData.checks.emitFragment=!0}!this.isInput&&e.sharedData.emitComments&&(e.compilationString+=`\r\n//${this.name}\r\n`),this._buildBlock(e),this._buildId=e.sharedData.buildId,this._buildTarget=e.target;for(const i of this._outputs)if(0!=(i.target&e.target))for(const n of i.endpoints){const i=n.ownerBlock;i&&0!=(i.target&e.target)&&-1!==t.indexOf(i)&&this._processBuild(i,e,n,t)}return!1}_inputRename(e){return e}_outputRename(e){return e}_dumpPropertiesCode(){const e=this._codeVariableName;return`${e}.visibleInInspector = ${this.visibleInInspector};\r\n${e}.visibleOnFrame = ${this.visibleOnFrame};\r\n${e}.target = ${this.target};\r\n`}_dumpCode(e,t){let i;t.push(this);const n=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=n||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do{t++,this._codeVariableName=n+t}while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName),i=`\r\n// ${this.getClassName()}\r\n`,this.comments&&(i+=`// ${this.comments}\r\n`),i+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}");\r\n`,i+=this._dumpPropertiesCode();for(const s of this.inputs){if(!s.isConnected)continue;const n=s.connectedPoint.ownerBlock;-1===t.indexOf(n)&&(i+=n._dumpCode(e,t))}for(const s of this.outputs)if(s.hasEndpoints)for(const n of s.endpoints){const s=n.ownerBlock;s&&-1===t.indexOf(s)&&(i+=s._dumpCode(e,t))}return i}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;e.push(this);for(const i of this.inputs){if(!i.isConnected)continue;const n=i.connectedPoint,s=n.ownerBlock;t+=s._dumpCodeForOutputConnections(e),t+=`${s._codeVariableName}.${s._outputRename(n.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)});\r\n`}return t}clone(e,t=""){const i=this.serialize(),n=(0,l.q)(i.customType);if(n){const s=new n;return s._deserialize(i,e,t),s}return null}serialize(){const e={};e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.comments=this.comments,e.visibleInInspector=this.visibleInInspector,e.visibleOnFrame=this.visibleOnFrame,e.target=this.target,e.inputs=[],e.outputs=[];for(const t of this.inputs)e.inputs.push(t.serialize());for(const t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e,t,i){var n;this.name=e.name,this.comments=e.comments,this.visibleInInspector=!!e.visibleInInspector,this.visibleOnFrame=!!e.visibleOnFrame,this._target=null!==(n=e.target)&&void 0!==n?n:this.target,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){const t=e.inputs,i=e.outputs;t&&t.forEach(((e,t)=>{e.displayName&&(this.inputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.inputs[t].isExposedOnFrame=e.isExposedOnFrame,this.inputs[t].exposedPortPosition=e.exposedPortPosition)})),i&&i.forEach(((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)}))}dispose(){for(const e of this.inputs)e.dispose();for(const e of this.outputs)e.dispose()}}class Ct extends bt{constructor(e){super(e,dt.Neutral),this.complementW=1,this.complementZ=0,this.target=dt.Vertex,this.registerInput("vector",ct.AutoDetect),this.registerInput("transform",ct.Matrix),this.registerOutput("output",ct.Vector4),this.registerOutput("xyz",ct.Vector3),this._inputs[0].onConnectionObservable.add((e=>{if(e.ownerBlock.isInput){const t=e.ownerBlock;"normal"!==t.name&&"tangent"!==t.name||(this.complementW=0)}}))}getClassName(){return"TransformBlock"}get vector(){return this._inputs[0]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}get transform(){return this._inputs[1]}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.transform;if(t.connectedPoint){if(0===this.complementW){const n=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",n),e.sharedData.blocksWithDefines.push(this);const s=e._getFreeVariableName(`${i.associatedVariableName}_NUS`);switch(e.compilationString+=`mat3 ${s} = mat3(${i.associatedVariableName});\r\n`,e.compilationString+="#ifdef NONUNIFORMSCALING\r\n",e.compilationString+=`${s} = transposeMat3(inverseMat3(${s}));\r\n`,e.compilationString+="#endif\r\n",t.connectedPoint.type){case ct.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * vec3(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)});\r\n`;break;case ct.Vector3:case ct.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * ${t.associatedVariableName}, ${this._writeFloat(this.complementW)});\r\n`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * ${t.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)});\r\n`}}else{const n=i.associatedVariableName;switch(t.connectedPoint.type){case ct.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = ${n} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)});\r\n`;break;case ct.Vector3:case ct.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = ${n} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementW)});\r\n`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = ${n} * ${t.associatedVariableName};\r\n`}}this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz;\r\n`)}return this}prepareDefines(e,t,i){e.nonUniformScaling&&i.setValue("NONUNIFORMSCALING",!0)}serialize(){const e=super.serialize();return e.complementZ=this.complementZ,e.complementW=this.complementW,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.complementZ=void 0!==e.complementZ?e.complementZ:0,this.complementW=void 0!==e.complementW?e.complementW:1}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.complementZ = ${this.complementZ};\r\n`;return e+=`${this._codeVariableName}.complementW = ${this.complementW};\r\n`,e}}(0,l.H)("BABYLON.TransformBlock",Ct);class yt extends bt{constructor(e){super(e,dt.Vertex,!0),this.registerInput("vector",ct.Vector4)}getClassName(){return"VertexOutputBlock"}get vector(){return this._inputs[0]}_isLogarithmicDepthEnabled(e){for(const t of e)if(t.useLogarithmicDepth)return!0;return!1}_buildBlock(e){super._buildBlock(e);const t=this.vector;return e.compilationString+=`gl_Position = ${t.associatedVariableName};\r\n`,this._isLogarithmicDepthEnabled(e.sharedData.fragmentOutputNodes)&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.compilationString+="vFragmentDepth = 1.0 + gl_Position.w;\r\n",e.compilationString+="gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\r\n"),this}}function At(e,t=Et.Boolean,i="PROPERTIES",n){return(s,r)=>{let o=s._propStore;o||(o=[],s._propStore=o),o.push({propertyName:r,displayName:e,type:t,groupName:i,options:null!=n?n:{}})}}(0,l.H)("BABYLON.VertexOutputBlock",yt),function(e){e[e.Boolean=0]="Boolean",e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=3]="Vector2",e[e.List=4]="List"}(Et||(Et={}));var Rt,Pt,It=i(2108);class Mt extends bt{constructor(e){super(e,dt.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",ct.Color4,!0),this.registerInput("rgb",ct.AutoDetect,!0),this.registerInput("a",ct.Float,!0),this.rgb.addExcludedConnectionPointFromAllowedTypes(ct.Color3|ct.Vector3|ct.Float)}getClassName(){return"FragmentOutputBlock"}initialize(e){e._excludeVariableName("logarithmicDepthConstant"),e._excludeVariableName("vFragmentDepth")}get rgba(){return this._inputs[0]}get rgb(){return this._inputs[1]}get a(){return this._inputs[2]}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToLinearSpace,!0),i.setValue(this._gammaDefineName,this.convertToGammaSpace,!0)}bind(e,t,i){this.useLogarithmicDepth&&i&&It.G.BindLogDepth(void 0,e,i.getScene())}_buildBlock(e){super._buildBlock(e);const t=this.rgba,i=this.rgb,n=this.a;e.sharedData.hints.needAlphaBlending=t.isConnected||n.isConnected,e.sharedData.blocksWithDefines.push(this),this.useLogarithmicDepth&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.sharedData.bindableBlocks.push(this)),this._linearDefineName=e._getFreeDefineName("CONVERTTOLINEAR"),this._gammaDefineName=e._getFreeDefineName("CONVERTTOGAMMA");const s=`//${this.name}`;if(e._emitFunctionFromInclude("helperFunctions",s),t.connectedPoint)n.isConnected?e.compilationString+=`gl_FragColor = vec4(${t.associatedVariableName}.rgb, ${n.associatedVariableName});\r\n`:e.compilationString+=`gl_FragColor = ${t.associatedVariableName};\r\n`;else if(i.connectedPoint){let t="1.0";n.connectedPoint&&(t=n.associatedVariableName),i.connectedPoint.type===ct.Float?e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${i.associatedVariableName}, ${i.associatedVariableName}, ${t});\r\n`:e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${t});\r\n`}else e.sharedData.checks.notConnectedNonOptionalInputs.push(t);return e.compilationString+=`#ifdef ${this._linearDefineName}\r\n`,e.compilationString+="gl_FragColor = toLinearSpace(gl_FragColor);\r\n",e.compilationString+="#endif\r\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\r\n`,e.compilationString+="gl_FragColor = toGammaSpace(gl_FragColor);\r\n",e.compilationString+="#endif\r\n",this.useLogarithmicDepth&&(e.compilationString+="gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\r\n"),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\r\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\r\n`,e+=`${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth};\r\n`,e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.useLogarithmicDepth=this.useLogarithmicDepth,e}_deserialize(e,t,i){var n;super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=e.convertToLinearSpace,this.useLogarithmicDepth=null!==(n=e.useLogarithmicDepth)&&void 0!==n&&n}}(0,oe.gn)([At("Convert to gamma space",Et.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Mt.prototype,"convertToGammaSpace",void 0),(0,oe.gn)([At("Convert to linear space",Et.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Mt.prototype,"convertToLinearSpace",void 0),(0,oe.gn)([At("Use logarithmic depth",Et.Boolean,"PROPERTIES")],Mt.prototype,"useLogarithmicDepth",void 0),(0,l.H)("BABYLON.FragmentOutputBlock",Mt),function(e){e[e.Uniform=0]="Uniform",e[e.Attribute=1]="Attribute",e[e.Varying=2]="Varying",e[e.Undefined=3]="Undefined"}(Rt||(Rt={})),function(e){e[e.World=1]="World",e[e.View=2]="View",e[e.Projection=3]="Projection",e[e.ViewProjection=4]="ViewProjection",e[e.WorldView=5]="WorldView",e[e.WorldViewProjection=6]="WorldViewProjection",e[e.CameraPosition=7]="CameraPosition",e[e.FogColor=8]="FogColor",e[e.DeltaTime=9]="DeltaTime",e[e.CameraParameters=10]="CameraParameters",e[e.MaterialAlpha=11]="MaterialAlpha"}(Pt||(Pt={}));var Ot=i(8952);var Dt,Nt=i(470);!function(e){e[e.None=0]="None",e[e.Time=1]="Time",e[e.RealTime=2]="RealTime"}(Dt||(Dt={}));const Ft={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},wt={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},Lt={particle_texturemask:!0};class Bt extends bt{get type(){if(this._type===ct.AutoDetect){if(this.isUniform&&null!=this.value){if(!isNaN(this.value))return this._type=ct.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=ct.Vector2,this._type;case"Vector3":return this._type=ct.Vector3,this._type;case"Vector4":return this._type=ct.Vector4,this._type;case"Color3":return this._type=ct.Color3,this._type;case"Color4":return this._type=ct.Color4,this._type;case"Matrix":return this._type=ct.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"particle_positionw":return this._type=ct.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=ct.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=ct.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":return this._type=ct.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case Pt.World:case Pt.WorldView:case Pt.WorldViewProjection:case Pt.View:case Pt.ViewProjection:case Pt.Projection:return this._type=ct.Matrix,this._type;case Pt.CameraPosition:return this._type=ct.Vector3,this._type;case Pt.FogColor:return this._type=ct.Color3,this._type;case Pt.DeltaTime:case Pt.MaterialAlpha:return this._type=ct.Float,this._type;case Pt.CameraParameters:return this._type=ct.Vector4,this._type}}return this._type}constructor(e,t=dt.Vertex,i=ct.AutoDetect){super(e,t,!1,!0),this._mode=Rt.Undefined,this._animationType=Dt.None,this.min=0,this.max=0,this.isBoolean=!1,this.matrixMode=0,this._systemValue=null,this.isConstant=!1,this.groupInInspector="",this.onValueChangedObservable=new r.y$,this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._type=i,this.setDefaultValue(),this.registerOutput("output",i)}validateBlockName(e){return!!this.isAttribute||super.validateBlockName(e)}get output(){return this._outputs[0]}setAsAttribute(e){return this._mode=Rt.Attribute,e&&(this.name=e),this}setAsSystemValue(e){return this.systemValue=e,this}get value(){return this._storedValue}set value(e){this.type===ct.Float&&(this.isBoolean?e=e?1:0:this.min!==this.max&&(e=Math.max(this.min,e),e=Math.min(this.max,e))),this._storedValue=e,this._mode=Rt.Uniform,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e,this._mode=Rt.Uniform}get associatedVariableName(){return this._associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get animationType(){return this._animationType}set animationType(e){this._animationType=e}get isUndefined(){return this._mode===Rt.Undefined}get isUniform(){return this._mode===Rt.Uniform}set isUniform(e){this._mode=e?Rt.Uniform:Rt.Undefined,this.associatedVariableName=""}get isAttribute(){return this._mode===Rt.Attribute}set isAttribute(e){this._mode=e?Rt.Attribute:Rt.Undefined,this.associatedVariableName=""}get isVarying(){return this._mode===Rt.Varying}set isVarying(e){this._mode=e?Rt.Varying:Rt.Undefined,this.associatedVariableName=""}get isSystemValue(){return null!=this._systemValue}get systemValue(){return this._systemValue}set systemValue(e){this._mode=Rt.Uniform,this.associatedVariableName="",this._systemValue=e}getClassName(){return"InputBlock"}animate(e){switch(this._animationType){case Dt.Time:this.type===ct.Float&&(this.value+=.01*e.getAnimationRatio());break;case Dt.RealTime:this.type===ct.Float&&(this.value=(F.F.Now-e.getEngine().startTime)/1e3)}}_emitDefine(e){return"!"===e[0]?`#ifndef ${e.substring(1)}\r\n`:`#ifdef ${e}\r\n`}initialize(){this.associatedVariableName=""}setDefaultValue(){switch(this.type){case ct.Float:this.value=0;break;case ct.Vector2:this.value=o.FM.Zero();break;case ct.Vector3:this.value=o.P.Zero();break;case ct.Vector4:this.value=o.Lt.Zero();break;case ct.Color3:this.value=a.Wo.White();break;case ct.Color4:this.value=new a.HE(1,1,1,1);break;case ct.Matrix:this.value=o.y3.Identity()}}_emitConstant(e){switch(this.type){case ct.Float:return`${e._emitFloat(this.value)}`;case ct.Vector2:return`vec2(${this.value.x}, ${this.value.y})`;case ct.Vector3:return`vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;case ct.Vector4:return`vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;case ct.Color3:return a.zZ.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&a.zZ.Color3[0].toGammaSpaceToRef(a.zZ.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&a.zZ.Color3[0].toLinearSpaceToRef(a.zZ.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec3(${a.zZ.Color3[0].r}, ${a.zZ.Color3[0].g}, ${a.zZ.Color3[0].b})`;case ct.Color4:return a.zZ.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&a.zZ.Color4[0].toGammaSpaceToRef(a.zZ.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&a.zZ.Color4[0].toLinearSpaceToRef(a.zZ.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec4(${a.zZ.Color4[0].r}, ${a.zZ.Color4[0].g}, ${a.zZ.Color4[0].b}, ${a.zZ.Color4[0].a})`}return""}get _noContextSwitch(){return wt[this.name]}_emit(e,t){var i;if(this.isUniform){if(this.associatedVariableName||(this.associatedVariableName=e._getFreeVariableName("u_"+this.name)),this.isConstant){if(-1!==e.constants.indexOf(this.associatedVariableName))return;return e.constants.push(this.associatedVariableName),void(e._constantDeclaration+=this._declareOutput(this.output,e)+` = ${this._emitConstant(e)};\r\n`)}if(-1!==e.uniforms.indexOf(this.associatedVariableName))return;e.uniforms.push(this.associatedVariableName),t&&(e._uniformDeclaration+=this._emitDefine(t)),e._uniformDeclaration+=`uniform ${e._getGLType(this.type)} ${this.associatedVariableName};\r\n`,t&&(e._uniformDeclaration+="#endif\r\n");const i=e.sharedData.hints;if(null!==this._systemValue&&void 0!==this._systemValue)switch(this._systemValue){case Pt.WorldView:i.needWorldViewMatrix=!0;break;case Pt.WorldViewProjection:i.needWorldViewProjectionMatrix=!0}else this._animationType!==Dt.None&&e.sharedData.animatedInputs.push(this)}else if(this.isAttribute){if(this.associatedVariableName=null!==(i=Ft[this.name])&&void 0!==i?i:this.name,this.target===dt.Vertex&&e._vertexState)return void(wt[this.name]?Lt[this.name]?e._emitUniformFromString(this.associatedVariableName,e._getGLType(this.type),t):e._emitVaryingFromString(this.associatedVariableName,e._getGLType(this.type),t):this._emit(e._vertexState,t));if(-1!==e.attributes.indexOf(this.associatedVariableName))return;e.attributes.push(this.associatedVariableName),wt[this.name]?Lt[this.name]?e._emitUniformFromString(this.associatedVariableName,e._getGLType(this.type),t):e._emitVaryingFromString(this.associatedVariableName,e._getGLType(this.type),t):(t&&(e._attributeDeclaration+=this._emitDefine(t)),e._attributeDeclaration+=`attribute ${e._getGLType(this.type)} ${this.associatedVariableName};\r\n`,t&&(e._attributeDeclaration+="#endif\r\n"))}}_transmitWorld(e,t,i,n){if(!this._systemValue)return;const s=this.associatedVariableName;switch(this._systemValue){case Pt.World:e.setMatrix(s,t);break;case Pt.WorldView:e.setMatrix(s,i);break;case Pt.WorldViewProjection:e.setMatrix(s,n)}}_transmit(e,t,i){if(this.isAttribute)return;const n=this.associatedVariableName;if(this._systemValue){switch(this._systemValue){case Pt.World:case Pt.WorldView:case Pt.WorldViewProjection:return;case Pt.View:e.setMatrix(n,t.getViewMatrix());break;case Pt.Projection:e.setMatrix(n,t.getProjectionMatrix());break;case Pt.ViewProjection:e.setMatrix(n,t.getTransformMatrix());break;case Pt.CameraPosition:t.bindEyePosition(e,n,!0);break;case Pt.FogColor:e.setColor3(n,t.fogColor);break;case Pt.DeltaTime:e.setFloat(n,t.deltaTime/1e3);break;case Pt.CameraParameters:t.activeCamera&&e.setFloat4(n,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case Pt.MaterialAlpha:e.setFloat(n,i.alpha)}return}const s=this._valueCallback?this._valueCallback():this._storedValue;if(null!==s)switch(this.type){case ct.Float:e.setFloat(n,s);break;case ct.Int:e.setInt(n,s);break;case ct.Color3:a.zZ.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&a.zZ.Color3[0].toGammaSpaceToRef(a.zZ.Color3[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&a.zZ.Color3[0].toLinearSpaceToRef(a.zZ.Color3[0],t.getEngine().useExactSrgbConversions),e.setColor3(n,a.zZ.Color3[0]);break;case ct.Color4:a.zZ.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&a.zZ.Color4[0].toGammaSpaceToRef(a.zZ.Color4[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&a.zZ.Color4[0].toLinearSpaceToRef(a.zZ.Color4[0],t.getEngine().useExactSrgbConversions),e.setDirectColor4(n,a.zZ.Color4[0]);break;case ct.Vector2:e.setVector2(n,s);break;case ct.Vector3:e.setVector3(n,s);break;case ct.Vector4:e.setVector4(n,s);break;case ct.Matrix:e.setMatrix(n,s)}}_buildBlock(e){super._buildBlock(e),(this.isUniform||this.isSystemValue)&&e.sharedData.inputBlocks.push(this),this._emit(e)}_dumpPropertiesCode(){const e=this._codeVariableName;if(this.isAttribute)return super._dumpPropertiesCode()+`${e}.setAsAttribute("${this.name}");\r\n`;if(this.isSystemValue)return super._dumpPropertiesCode()+`${e}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${Pt[this._systemValue]});\r\n`;if(this.isUniform){const t=[];let i="";switch(this.type){case ct.Float:i=`${this.value}`;break;case ct.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case ct.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case ct.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break;case ct.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case ct.Color4:i=`new BABYLON.Color4(${this.value.r}, ${this.value.g}, ${this.value.b}, ${this.value.a})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case ct.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`}return t.push(`${e}.value = ${i}`),this.type===ct.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${Dt[this.animationType]}`),t.push(`${e}.isConstant = ${this.isConstant}`),t.push(""),super._dumpPropertiesCode()+t.join(";\r\n")}return super._dumpPropertiesCode()}dispose(){this.onValueChangedObservable.clear(),super.dispose()}serialize(){const e=super.serialize();return e.type=this.type,e.mode=this._mode,e.systemValue=this._systemValue,e.animationType=this._animationType,e.min=this.min,e.max=this.max,e.isBoolean=this.isBoolean,e.matrixMode=this.matrixMode,e.isConstant=this.isConstant,e.groupInInspector=this.groupInInspector,e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,null!=this._storedValue&&this._mode===Rt.Uniform&&(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e,t,i){if(this._mode=e.mode,super._deserialize(e,t,i),this._type=e.type,this._systemValue=e.systemValue||e.wellKnownValue,this._animationType=e.animationType,this.min=e.min||0,this.max=e.max||0,this.isBoolean=!!e.isBoolean,this.matrixMode=e.matrixMode||0,this.isConstant=!!e.isConstant,this.groupInInspector=e.groupInInspector||"",this.convertToGammaSpace=!!e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,"tangent"===e.name&&e.mode===Rt.Attribute&&e.type===ct.Vector3&&(this._type=ct.Vector4),e.valueType)if("number"===e.valueType)this._storedValue=e.value;else{const t=(0,l.q)(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}(0,l.H)("BABYLON.InputBlock",Bt);class Ut extends bt{constructor(e){super(e,dt.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",ct.AutoDetect,!1,dt.VertexAndFragment),this.registerOutput("rgba",ct.Color4,dt.Neutral),this.registerOutput("rgb",ct.Color3,dt.Neutral),this.registerOutput("r",ct.Float,dt.Neutral),this.registerOutput("g",ct.Float,dt.Neutral),this.registerOutput("b",ct.Float,dt.Neutral),this.registerOutput("a",ct.Float,dt.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ct.Vector2|ct.Vector3|ct.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"CurrentScreenBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return this.uv.isConnected?this.uv.sourceBlock.isInput?dt.VertexAndFragment:dt.Fragment:dt.VertexAndFragment}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}_injectVertexCode(e){const t=this.uv;if(t.connectedPoint.ownerBlock.isInput){t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,"vec2")}if(this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\r\n`,this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,t.name,!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===dt.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName});\r\n`}else this.uv.ownerBlock.target!==dt.Fragment?e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\r\n`:e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName});\r\n`}_writeOutput(e,t,i,n=!1){if(n){if(e.target===dt.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`}else this.uv.ownerBlock.target!==dt.Fragment?(e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`,e.compilationString+=`#ifdef ${this._linearDefineName}\r\n`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\r\n`,e.compilationString+="#endif\r\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\r\n`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\r\n`,e.compilationString+="#endif\r\n"):e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`}_buildBlock(e){if(super._buildBlock(e),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e.sharedData.blockingBlocks.indexOf(this)<0&&e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.indexOf(this)<0&&e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.indexOf(this)<0&&e.sharedData.blocksWithDefines.push(this),e.target!==dt.Fragment)return e._emit2DSampler(this._samplerName),void this._injectVertexCode(e);if(!this._outputs.some((e=>e.isConnectedInFragmentShader)))return;e._emit2DSampler(this._samplerName),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),this._writeTextureRead(e);for(const i of this._outputs)i.hasEndpoints&&this._writeOutput(e,i,i.name);return this}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Le.Parse(e.texture,t,i))}}(0,l.H)("BABYLON.CurrentScreenBlock",Ut);class Vt extends bt{constructor(e){super(e,dt.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",ct.AutoDetect,!1,dt.VertexAndFragment),this.registerOutput("rgba",ct.Color4,dt.Neutral),this.registerOutput("rgb",ct.Color3,dt.Neutral),this.registerOutput("r",ct.Float,dt.Neutral),this.registerOutput("g",ct.Float,dt.Neutral),this.registerOutput("b",ct.Float,dt.Neutral),this.registerOutput("a",ct.Float,dt.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ct.Vector2|ct.Vector3|ct.Vector4)}getClassName(){return"ParticleTextureBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("diffuseSampler")}autoConfigure(e){if(!this.uv.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"particle_uv"===e.name));t||(t=new Bt("uv"),t.setAsAttribute("particle_uv")),t.output.connectTo(this.uv)}}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}_writeOutput(e,t,i){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`,e.compilationString+=`#ifdef ${this._linearDefineName}\r\n`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\r\n`,e.compilationString+="#endif\r\n",e.compilationString+=`#ifdef ${this._gammaDefineName}\r\n`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\r\n`,e.compilationString+="#endif\r\n"}_buildBlock(e){if(super._buildBlock(e),e.target===dt.Vertex)return;this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e._emit2DSampler(this._samplerName),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this.uv.associatedVariableName});\r\n`;for(const i of this._outputs)i.hasEndpoints&&this._writeOutput(e,i,i.name);return this}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Le.Parse(e.texture,t,i))}}(0,l.H)("BABYLON.ParticleTextureBlock",Vt);class kt extends bt{constructor(e){super(e,dt.Fragment),this._isUnique=!0,this.registerInput("color",ct.Color4,!1,dt.Fragment),this.registerOutput("rampColor",ct.Color4,dt.Fragment)}getClassName(){return"ParticleRampGradientBlock"}get color(){return this._inputs[0]}get rampColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("remapRanges"),e._excludeVariableName("rampSampler"),e._excludeVariableName("baseColor"),e._excludeVariableName("alpha"),e._excludeVariableName("remappedColorIndex"),e._excludeVariableName("rampColor"),e._excludeVariableName("finalAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==dt.Vertex)return e._emit2DSampler("rampSampler"),e._emitVaryingFromString("remapRanges","vec4","RAMPGRADIENT"),e.compilationString+=`\n #ifdef RAMPGRADIENT\n vec4 baseColor = ${this.color.associatedVariableName};\n float alpha = ${this.color.associatedVariableName}.a;\n\n float remappedColorIndex = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0);\n\n vec4 rampColor = texture2D(rampSampler, vec2(1.0 - remappedColorIndex, 0.));\n baseColor.rgb *= rampColor.rgb;\n\n // Remapped alpha\n float finalAlpha = baseColor.a;\n baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0);\n\n ${this._declareOutput(this.rampColor,e)} = baseColor;\n #else\n ${this._declareOutput(this.rampColor,e)} = ${this.color.associatedVariableName};\n #endif\n `,this}}(0,l.H)("BABYLON.ParticleRampGradientBlock",kt);class Gt extends bt{constructor(e){super(e,dt.Fragment),this._isUnique=!0,this.registerInput("color",ct.Color4,!1,dt.Fragment),this.registerInput("alphaTexture",ct.Float,!1,dt.Fragment),this.registerInput("alphaColor",ct.Float,!1,dt.Fragment),this.registerOutput("blendColor",ct.Color4,dt.Fragment)}getClassName(){return"ParticleBlendMultiplyBlock"}get color(){return this._inputs[0]}get alphaTexture(){return this._inputs[1]}get alphaColor(){return this._inputs[2]}get blendColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("sourceAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==dt.Vertex)return e.compilationString+=`\n #ifdef BLENDMULTIPLYMODE\n ${this._declareOutput(this.blendColor,e)};\n float sourceAlpha = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName};\n ${this.blendColor.associatedVariableName}.rgb = ${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha);\n ${this.blendColor.associatedVariableName}.a = ${this.color.associatedVariableName}.a;\n #else\n ${this._declareOutput(this.blendColor,e)} = ${this.color.associatedVariableName};\n #endif\n `,this}}(0,l.H)("BABYLON.ParticleBlendMultiplyBlock",Gt);class zt{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(ethis._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,ethis._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;const i=this._mesh.getScene();for(let e=0;e0&&(n.computeBonesUsingShaders=!1)}}else{const t=this._defines[this._currentRank];if(t)for(let i=0;i0}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 texture(){var e,t;return null!==(t=null===(e=this._textures)||void 0===e?void 0:e[0])&&void 0!==t?t: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){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}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]&&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,s=14,r){var o;return null===(o=this._depthStencilTexture)||void 0===o||o.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:n,depthTextureFormat:s,label:r},this),this._depthStencilTexture}_shareDepth(e){this._depthStencilTexture&&(e._depthStencilTexture&&e._depthStencilTexture.dispose(),e._depthStencilTexture=this._depthStencilTexture,this._depthStencilTexture.incrementReferences())}_swapAndDie(e){this.texture&&this.texture._swapAndDie(e),this._textures=null,this.dispose(!0)}_cloneRenderTargetWrapper(){var e,t,i,n,s,r,o,a;let l=null;if(this._isMulti){const i=this.textures;if(i&&i.length>0){let n=!1,s=i.length;const r=i[i.length-1]._source;r!==Be.S.Depth&&r!==Be.S.DepthStencil||(n=!0,s--);const o=[],a=[],h=[],c=[],d=[],u=[],p=[],f={};for(let l=0;l1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){var e,t;if(this._textures)for(let i=0;null!==(t=i<(null===(e=this._textures)||void 0===e?void 0:e.length))&&void 0!==t&&t;++i)this._textures[i].dispose();this._textures=null}dispose(e=!1){var t;e||(null===(t=this._depthStencilTexture)||void 0===t||t.dispose(),this._depthStencilTexture=null,this.releaseTextures()),this._engine._releaseRenderTargetWrapper(this)}}class Kt extends jt{constructor(e,t,i,n,s){super(e,t,i,n),this._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._disposeOnlyFramebuffers=!1,this._context=s}_cloneRenderTargetWrapper(){let e=null;return this._colorTextureArray&&this._depthStencilTextureArray?(e=this._engine.createMultiviewRenderTargetTexture(this.width,this.height),e.texture.isReady=!0):e=super._cloneRenderTargetWrapper(),e}_swapRenderTargetWrapper(e){super._swapRenderTargetWrapper(e),e._framebuffer=this._framebuffer,e._depthStencilBuffer=this._depthStencilBuffer,e._MSAAFramebuffer=this._MSAAFramebuffer,e._colorTextureArray=this._colorTextureArray,e._depthStencilTextureArray=this._depthStencilTextureArray,this._framebuffer=this._depthStencilBuffer=this._MSAAFramebuffer=this._colorTextureArray=this._depthStencilTextureArray=null}_shareDepth(e){super._shareDepth(e);const t=this._context,i=this._depthStencilBuffer,n=e._MSAAFramebuffer||e._framebuffer;e._depthStencilBuffer&&t.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=this._depthStencilBuffer,this._engine._bindUnboundFramebuffer(n),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.RENDERBUFFER,i),this._engine._bindUnboundFramebuffer(null)}_bindTextureRenderTarget(e,t=0,i,n=0){var s,r,o,a;if(!e._hardwareTexture)return;const l=this._framebuffer,h=this._engine._currentFramebuffer;if(this._engine._bindUnboundFramebuffer(l),this._engine.webGLVersion>1){const l=this._context,h=l["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=null!==(r=null!=i?i:null===(s=this.layerIndices)||void 0===s?void 0:s[t])&&void 0!==r?r:0,l.framebufferTextureLayer(l.FRAMEBUFFER,h,e._hardwareTexture.underlyingResource,n,i)):e.isCube?(i=null!==(a=null!=i?i:null===(o=this.faceIndices)||void 0===o?void 0:o[t])&&void 0!==a?a:0,l.framebufferTexture2D(l.FRAMEBUFFER,h,l.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,n)):l.framebufferTexture2D(l.FRAMEBUFFER,h,l.TEXTURE_2D,e._hardwareTexture.underlyingResource,n)}else{const s=this._context,r=s["COLOR_ATTACHMENT"+t+"_WEBGL"],o=void 0!==i?s.TEXTURE_CUBE_MAP_POSITIVE_X+i:s.TEXTURE_2D;s.framebufferTexture2D(s.FRAMEBUFFER,r,o,e._hardwareTexture.underlyingResource,n)}this._engine._bindUnboundFramebuffer(h)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){var i,n;if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;const s=null!==(n=null===(i=this._attachments)||void 0===i?void 0:i.length)&&void 0!==n?n:this.textures.length;for(let r=0;r1&&(15===o.format?d=n.DEPTH_COMPONENT16:16===o.format?d=n.DEPTH_COMPONENT24:17===o.format||13===o.format?d=n.DEPTH24_STENCIL8:14===o.format?d=n.DEPTH_COMPONENT32F:18===o.format&&(d=n.DEPTH32F_STENCIL8)),o.is2DArray?n.texImage3D(r,0,d,o.width,o.height,s,0,c,h,null):n.texImage2D(r,0,d,o.width,o.height,0,c,h,null),this._bindTextureDirectly(r,null),this._internalTexturesCache.push(o);const u=i;if(u._depthStencilBuffer){const e=this._currentFramebuffer;this._bindUnboundFramebuffer(u._framebuffer),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_STENCIL_ATTACHMENT,n.RENDERBUFFER,null),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.DEPTH_ATTACHMENT,n.RENDERBUFFER,null),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.STENCIL_ATTACHMENT,n.RENDERBUFFER,null),this._bindUnboundFramebuffer(e),n.deleteRenderbuffer(u._depthStencilBuffer),u._depthStencilBuffer=null}return o},Ue.B.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 s=i.createFramebuffer();if(!s)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=s,this._bindUnboundFramebuffer(e._MSAAFramebuffer);const r=this._createRenderBuffer(e.texture.width,e.texture.height,t,-1,this._getRGBAMultiSampleBufferFormat(e.texture.type),i.COLOR_ATTACHMENT0,!1);if(!r)throw new Error("Unable to create multi sampled framebuffer");n.addMSAARenderBuffer(r)}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};var qt,$t=i(7050),Qt=i(475);class Zt{static RegisterShaderCodeProcessing(e,t){t?Zt._CustomShaderCodeProcessing[null!=e?e:""]=t:delete Zt._CustomShaderCodeProcessing[null!=e?e:""]}static _GetShaderCodeProcessing(e){var t;return null!==(t=Zt._CustomShaderCodeProcessing[e])&&void 0!==t?t:Zt._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)}))}getEffectName(){return this._fragmentUrl}set onActivate(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),e&&(this._onActivateObserver=this.onActivateObservable.add(e))}set onSizeChanged(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)}set onApply(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}get inputTexture(){return this._textures.data[this._currentRenderTextureInd]}set inputTexture(e){this._forcedOutputTexture=e}restoreDefaultInputTexture(){this._forcedOutputTexture&&(this._forcedOutputTexture=null,this.markTextureDirty())}getCamera(){return this._camera}get texelSize(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)}constructor(e,t,i,n,s,a,l=1,h,c,d=null,u=0,p="postprocess",f,_=!1,m=5,g=Qt.x.GLSL){this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.alphaMode=0,this.animations=new Array,this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new Wt.t(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new o.FM(1,1),this._texelSize=o.FM.Zero(),this.onActivateObservable=new r.y$,this.onSizeChangedObservable=new r.y$,this.onApplyObservable=new r.y$,this.onBeforeRenderObservable=new r.y$,this.onAfterRenderObservable=new r.y$,this.name=e,null!=a?(this._camera=a,this._scene=a.getScene(),a.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):h&&(this._engine=h,this._engine.postProcesses.push(this)),this._options=s,this.renderTargetSamplingMode=l||1,this._reusable=c||!1,this._textureType=u,this._textureFormat=m,this._shaderLanguage=g,this._samplers=n||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=p,this._parameters=i||[],this._parameters.push("scale"),this._indexParameters=f,this._drawWrapper=new $t.q(this._engine),_||this.updateEffect(d)}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 Wt.t(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,n,s,r,o,a){var l,h;const c=Zt._GetShaderCodeProcessing(this.name);if(null==c?void 0:c.defineCustomBindings){const n=null!==(l=null==t?void 0:t.slice())&&void 0!==l?l:[];n.push(...this._parameters);const s=null!==(h=null==i?void 0:i.slice())&&void 0!==h?h:[];s.push(...this._samplers),e=c.defineCustomBindings(this.name,e,n,s),t=n,i=s}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:null!=o?o:this._vertexUrl,fragment:null!=a?a:this._fragmentUrl},{attributes:["position"],uniformsNames:t||this._parameters,uniformBuffersNames:[],samplers:i||this._samplers,defines:null!==e?e:"",fallbacks:null,onCompiled:null!=s?s:null,onError:null!=r?r:null,indexParameters:n||this._indexParameters,processCodeAfterIncludes:(null==c?void 0:c.processCodeAfterIncludes)?(e,t)=>c.processCodeAfterIncludes(this.name,e,t):null,processFinalCode:(null==c?void 0:c.processFinalCode)?(e,t)=>c.processFinalCode(this.name,e,t):null,shaderLanguage:this._shaderLanguage},this._engine)}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let s=0;s=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let e=!1;for(let i=0;i0&&this._textures.reset(),this.width=e,this.height=t;let r=null;for(let l=0;l{e.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(e,this.samples)})),this._flushTextureCache(),this._renderId++}let f;if(this._shareOutputWithPostProcess)f=this._shareOutputWithPostProcess.inputTexture;else if(this._forcedOutputTexture)f=this._forcedOutputTexture,this.width=this._forcedOutputTexture.width,this.height=this._forcedOutputTexture.height;else{let e;f=this.inputTexture;for(let t=0;t=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()}}serialize(){const e=E.p4.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=Zt.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=(0,l.q)(e.customType);if(!n||!n._Parse)return null;const s=t?t.getCameraById(e.cameraId):null;return n._Parse(e,s,t,i)}static _Parse(e,t,i,n){return E.p4.Parse((()=>new Zt(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)}}Zt._CustomShaderCodeProcessing={},(0,oe.gn)([(0,E.qC)()],Zt.prototype,"uniqueId",void 0),(0,oe.gn)([(0,E.qC)()],Zt.prototype,"name",void 0),(0,oe.gn)([(0,E.qC)()],Zt.prototype,"width",void 0),(0,oe.gn)([(0,E.qC)()],Zt.prototype,"height",void 0),(0,oe.gn)([(0,E.qC)()],Zt.prototype,"renderTargetSamplingMode",void 0),(0,oe.gn)([(0,E.XX)()],Zt.prototype,"clearColor",void 0),(0,oe.gn)([(0,E.qC)()],Zt.prototype,"autoClear",void 0),(0,oe.gn)([(0,E.qC)()],Zt.prototype,"forceAutoClearInAlphaMode",void 0),(0,oe.gn)([(0,E.qC)()],Zt.prototype,"alphaMode",void 0),(0,oe.gn)([(0,E.qC)()],Zt.prototype,"alphaConstants",void 0),(0,oe.gn)([(0,E.qC)()],Zt.prototype,"enablePixelPerfectMode",void 0),(0,oe.gn)([(0,E.qC)()],Zt.prototype,"forceFullscreenViewport",void 0),(0,oe.gn)([(0,E.qC)()],Zt.prototype,"scaleMode",void 0),(0,oe.gn)([(0,E.qC)()],Zt.prototype,"alwaysForcePOT",void 0),(0,oe.gn)([(0,E.qC)("samples")],Zt.prototype,"_samples",void 0),(0,oe.gn)([(0,E.qC)()],Zt.prototype,"adaptScaleToCurrentViewport",void 0),(0,l.H)("BABYLON.PostProcess",Zt);class Jt extends bt{constructor(e){super(e,dt.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",this.registerInput("xyzw ",ct.Vector4,!0),this.registerInput("xyz ",ct.Vector3,!0),this.registerInput("xy ",ct.Vector2,!0),this.registerInput("zw ",ct.Vector2,!0),this.registerInput("x",ct.Float,!0),this.registerInput("y",ct.Float,!0),this.registerInput("z",ct.Float,!0),this.registerInput("w",ct.Float,!0),this.registerOutput("xyzw",ct.Vector4),this.registerOutput("xyz",ct.Vector3),this.registerOutput("xy",ct.Vector2),this.registerOutput("zw",ct.Vector2)}getClassName(){return"VectorMergerBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get x(){return this._inputs[4]}get y(){return this._inputs[5]}get z(){return this._inputs[6]}get w(){return this._inputs[7]}get xyzw(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xy(){return this.xyOut}get xyz(){return this.xyzOut}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":e}_buildSwizzle(e){return"."+(this.xSwizzle+this.ySwizzle+this.zSwizzle+this.wSwizzle).substr(0,e)}_buildBlock(e){super._buildBlock(e);const t=this.x,i=this.y,n=this.z,s=this.w,r=this.xyIn,o=this.zwIn,a=this.xyzIn,l=this.xyzwIn,h=this._outputs[0],c=this._outputs[1],d=this._outputs[2],u=this._outputs[3];return l.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = ${l.associatedVariableName}${this._buildSwizzle(4)};\r\n`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${l.associatedVariableName}${this._buildSwizzle(3)};\r\n`),d.hasEndpoints&&(e.compilationString+=this._declareOutput(d,e)+` = ${l.associatedVariableName}${this._buildSwizzle(2)};\r\n`)):a.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = vec4(${a.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)};\r\n`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${a.associatedVariableName}${this._buildSwizzle(3)};\r\n`),d.hasEndpoints&&(e.compilationString+=this._declareOutput(d,e)+` = ${a.associatedVariableName}${this._buildSwizzle(2)};\r\n`)):r.isConnected?(h.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${r.associatedVariableName}, ${o.associatedVariableName})${this._buildSwizzle(4)};\r\n`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${r.associatedVariableName}, ${n.isConnected?this._writeVariable(n):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)};\r\n`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = vec3(${r.associatedVariableName}, ${n.isConnected?this._writeVariable(n):"0.0"})${this._buildSwizzle(3)};\r\n`),d.hasEndpoints&&(e.compilationString+=this._declareOutput(d,e)+` = ${r.associatedVariableName}${this._buildSwizzle(2)};\r\n`),u.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(u,e)+` = ${o.associatedVariableName}${this._buildSwizzle(2)};\r\n`:e.compilationString+=this._declareOutput(u,e)+` = vec2(${n.isConnected?this._writeVariable(n):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(2)};\r\n`)):(h.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${o.associatedVariableName})${this._buildSwizzle(4)};\r\n`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${n.isConnected?this._writeVariable(n):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)};\r\n`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = vec3(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${n.isConnected?this._writeVariable(n):"0.0"})${this._buildSwizzle(3)};\r\n`),d.hasEndpoints&&(e.compilationString+=this._declareOutput(d,e)+` = vec2(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"})${this._buildSwizzle(2)};\r\n`),u.hasEndpoints&&(o.isConnected?e.compilationString+=this._declareOutput(u,e)+` = ${o.associatedVariableName}${this._buildSwizzle(2)};\r\n`:e.compilationString+=this._declareOutput(u,e)+` = vec2(${n.isConnected?this._writeVariable(n):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(2)};\r\n`)),this}serialize(){const e=super.serialize();return e.xSwizzle=this.xSwizzle,e.ySwizzle=this.ySwizzle,e.zSwizzle=this.zSwizzle,e.wSwizzle=this.wSwizzle,e}_deserialize(e,t,i){var n,s,r,o;super._deserialize(e,t,i),this.xSwizzle=null!==(n=e.xSwizzle)&&void 0!==n?n:"x",this.ySwizzle=null!==(s=e.ySwizzle)&&void 0!==s?s:"y",this.zSwizzle=null!==(r=e.zSwizzle)&&void 0!==r?r:"z",this.wSwizzle=null!==(o=e.wSwizzle)&&void 0!==o?o:"w"}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.xSwizzle = "${this.xSwizzle}";\r\n`,e+=`${this._codeVariableName}.ySwizzle = "${this.ySwizzle}";\r\n`,e+=`${this._codeVariableName}.zSwizzle = "${this.zSwizzle}";\r\n`,e+=`${this._codeVariableName}.wSwizzle = "${this.wSwizzle}";\r\n`,e}}(0,l.H)("BABYLON.VectorMergerBlock",Jt);class ei extends bt{constructor(e){super(e,dt.Neutral),this.sourceRange=new o.FM(-1,1),this.targetRange=new o.FM(0,1),this.registerInput("input",ct.AutoDetect),this.registerInput("sourceMin",ct.Float,!0),this.registerInput("sourceMax",ct.Float,!0),this.registerInput("targetMin",ct.Float,!0),this.registerInput("targetMax",ct.Float,!0),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"RemapBlock"}get input(){return this._inputs[0]}get sourceMin(){return this._inputs[1]}get sourceMax(){return this._inputs[2]}get targetMin(){return this._inputs[3]}get targetMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.sourceMin.isConnected?this.sourceMin.associatedVariableName:this._writeFloat(this.sourceRange.x),n=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),s=this.targetMin.isConnected?this.targetMin.associatedVariableName:this._writeFloat(this.targetRange.x),r=this.targetMax.isConnected?this.targetMax.associatedVariableName:this._writeFloat(this.targetRange.y);return e.compilationString+=this._declareOutput(t,e)+` = ${s} + (${this._inputs[0].associatedVariableName} - ${i}) * (${r} - ${s}) / (${n} - ${i});\r\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y});\r\n`;return e+=`${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y});\r\n`,e}serialize(){const e=super.serialize();return e.sourceRange=this.sourceRange.asArray(),e.targetRange=this.targetRange.asArray(),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.sourceRange=o.FM.FromArray(e.sourceRange),this.targetRange=o.FM.FromArray(e.targetRange)}}(0,oe.gn)([At("From",Et.Vector2)],ei.prototype,"sourceRange",void 0),(0,oe.gn)([At("To",Et.Vector2)],ei.prototype,"targetRange",void 0),(0,l.H)("BABYLON.RemapBlock",ei);class ti extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("left",ct.AutoDetect),this.registerInput("right",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].acceptedConnectionPointTypes.push(ct.Float),this._inputs[1].acceptedConnectionPointTypes.push(ct.Float)}getClassName(){return"MultiplyBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} * ${this.right.associatedVariableName};\r\n`,this}}(0,l.H)("BABYLON.MultiplyBlock",ti),function(e){e[e.Material=0]="Material",e[e.PostProcess=1]="PostProcess",e[e.Particle=2]="Particle",e[e.ProceduralTexture=3]="ProceduralTexture"}(qt||(qt={}));var ii=i(9096);class ni{constructor(){this.direction1=new o.P(0,1,0),this.direction2=new o.P(0,1,0),this.minEmitBox=new o.P(-.5,-.5,-.5),this.maxEmitBox=new o.P(.5,.5,.5)}startDirectionFunction(e,t,i,n){const s=S.R.RandomRange(this.direction1.x,this.direction2.x),r=S.R.RandomRange(this.direction1.y,this.direction2.y),a=S.R.RandomRange(this.direction1.z,this.direction2.z);if(n)return t.x=s,t.y=r,void(t.z=a);o.P.TransformNormalFromFloatsToRef(s,r,a,e,t)}startPositionFunction(e,t,i,n){const s=S.R.RandomRange(this.minEmitBox.x,this.maxEmitBox.x),r=S.R.RandomRange(this.minEmitBox.y,this.maxEmitBox.y),a=S.R.RandomRange(this.minEmitBox.z,this.maxEmitBox.z);if(n)return t.x=s,t.y=r,void(t.z=a);o.P.TransformCoordinatesFromFloatsToRef(s,r,a,e,t)}clone(){const e=new ni;return g.j.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2),e.setVector3("minEmitBox",this.minEmitBox),e.setVector3("maxEmitBox",this.maxEmitBox)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3),e.addUniform("minEmitBox",3),e.addUniform("maxEmitBox",3)}getEffectDefines(){return"#define BOXEMITTER"}getClassName(){return"BoxParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.minEmitBox=this.minEmitBox.asArray(),e.maxEmitBox=this.maxEmitBox.asArray(),e}parse(e){o.P.FromArrayToRef(e.direction1,0,this.direction1),o.P.FromArrayToRef(e.direction2,0,this.direction2),o.P.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),o.P.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}}class si{get radius(){return this._radius}set radius(e){this._radius=e,this._buildHeight()}get angle(){return this._angle}set angle(e){this._angle=e,this._buildHeight()}_buildHeight(){0!==this._angle?this._height=this._radius/Math.tan(this._angle/2):this._height=1}constructor(e=1,t=Math.PI,i=0){this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}startDirectionFunction(e,t,i,n){n?o.jp.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),o.jp.Vector3[0]).normalize();const s=S.R.RandomRange(0,this.directionRandomizer),r=S.R.RandomRange(0,this.directionRandomizer),a=S.R.RandomRange(0,this.directionRandomizer);t.x=o.jp.Vector3[0].x+s,t.y=o.jp.Vector3[0].y+r,t.z=o.jp.Vector3[0].z+a,t.normalize()}startPositionFunction(e,t,i,n){const s=S.R.RandomRange(0,2*Math.PI);let r;this.emitFromSpawnPointOnly?r=1e-4:(r=S.R.RandomRange(0,this.heightRange),r=1-r*r);let a=this._radius-S.R.RandomRange(0,this._radius*this.radiusRange);a*=r;const l=a*Math.sin(s),h=a*Math.cos(s),c=r*this._height;if(n)return t.x=l,t.y=c,void(t.z=h);o.P.TransformCoordinatesFromFloatsToRef(l,c,h,e,t)}clone(){const e=new si(this._radius,this._angle,this.directionRandomizer);return g.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat2("radius",this._radius,this.radiusRange),e.setFloat("coneAngle",this._angle),e.setFloat2("height",this._height,this.heightRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",2),e.addUniform("coneAngle",1),e.addUniform("height",2),e.addUniform("directionRandomizer",1)}getEffectDefines(){let e="#define CONEEMITTER";return this.emitFromSpawnPointOnly&&(e+="\n#define CONEEMITTERSPAWNPOINT"),e}getClassName(){return"ConeParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this._radius,e.angle=this._angle,e.directionRandomizer=this.directionRandomizer,e.radiusRange=this.radiusRange,e.heightRange=this.heightRange,e.emitFromSpawnPointOnly=this.emitFromSpawnPointOnly,e}parse(e){this.radius=e.radius,this.angle=e.angle,this.directionRandomizer=e.directionRandomizer,this.radiusRange=void 0!==e.radiusRange?e.radiusRange:1,this.heightRange=void 0!==e.radiusRange?e.heightRange:1,this.emitFromSpawnPointOnly=void 0!==e.emitFromSpawnPointOnly&&e.emitFromSpawnPointOnly}}class ri{constructor(e=1,t=1,i=1,n=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=n,this._tempVector=o.P.Zero()}startDirectionFunction(e,t,i,n,s){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),o.P.TransformNormalToRef(this._tempVector,s,this._tempVector);const r=S.R.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2);let a=Math.atan2(this._tempVector.x,this._tempVector.z);a+=S.R.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,this._tempVector.y=r,this._tempVector.x=Math.sin(a),this._tempVector.z=Math.cos(a),this._tempVector.normalize(),n?t.copyFrom(this._tempVector):o.P.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,n){const s=S.R.RandomRange(-this.height/2,this.height/2),r=S.R.RandomRange(0,2*Math.PI),a=S.R.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1),l=Math.sqrt(a)*this.radius,h=l*Math.cos(r),c=l*Math.sin(r);n?t.copyFromFloats(h,s,c):o.P.TransformCoordinatesFromFloatsToRef(h,s,c,e,t)}clone(){const e=new ri(this.radius,this.directionRandomizer);return g.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define CYLINDEREMITTER"}getClassName(){return"CylinderParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.height=this.height,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.height=e.height,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class oi extends ri{constructor(e=1,t=1,i=1,n=new o.P(0,1,0),s=new o.P(0,1,0)){super(e,t,i),this.direction1=n,this.direction2=s}startDirectionFunction(e,t){const i=S.R.RandomRange(this.direction1.x,this.direction2.x),n=S.R.RandomRange(this.direction1.y,this.direction2.y),s=S.R.RandomRange(this.direction1.z,this.direction2.z);o.P.TransformNormalFromFloatsToRef(i,n,s,e,t)}clone(){const e=new oi(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return g.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER"}getClassName(){return"CylinderDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}class ai{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,n){const s=i.position.subtract(e.getTranslation()).normalize(),r=S.R.RandomRange(0,this.directionRandomizer),a=S.R.RandomRange(0,this.directionRandomizer),l=S.R.RandomRange(0,this.directionRandomizer);s.x+=r,s.y+=a,s.z+=l,s.normalize(),n?t.copyFrom(s):o.P.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,n){const s=this.radius-S.R.RandomRange(0,this.radius*this.radiusRange),r=S.R.RandomRange(0,1),a=S.R.RandomRange(0,2*Math.PI),l=Math.acos(2*r-1),h=s*Math.cos(a)*Math.sin(l),c=s*Math.cos(l),d=s*Math.sin(a)*Math.sin(l);n?t.copyFromFloats(h,Math.abs(c),d):o.P.TransformCoordinatesFromFloatsToRef(h,Math.abs(c),d,e,t)}clone(){const e=new ai(this.radius,this.directionRandomizer);return g.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define HEMISPHERICEMITTER"}getClassName(){return"HemisphericParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class li{constructor(){this.direction1=new o.P(0,1,0),this.direction2=new o.P(0,1,0)}startDirectionFunction(e,t,i,n){const s=S.R.RandomRange(this.direction1.x,this.direction2.x),r=S.R.RandomRange(this.direction1.y,this.direction2.y),a=S.R.RandomRange(this.direction1.z,this.direction2.z);n?t.copyFromFloats(s,r,a):o.P.TransformNormalFromFloatsToRef(s,r,a,e,t)}startPositionFunction(e,t,i,n){n?t.copyFromFloats(0,0,0):o.P.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){const e=new li;return g.j.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define POINTEMITTER"}getClassName(){return"PointParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){o.P.FromArrayToRef(e.direction1,0,this.direction1),o.P.FromArrayToRef(e.direction2,0,this.direction2)}}class hi{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,n){const s=i.position.subtract(e.getTranslation()).normalize(),r=S.R.RandomRange(0,this.directionRandomizer),a=S.R.RandomRange(0,this.directionRandomizer),l=S.R.RandomRange(0,this.directionRandomizer);s.x+=r,s.y+=a,s.z+=l,s.normalize(),n?t.copyFrom(s):o.P.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,n){const s=this.radius-S.R.RandomRange(0,this.radius*this.radiusRange),r=S.R.RandomRange(0,1),a=S.R.RandomRange(0,2*Math.PI),l=Math.acos(2*r-1),h=s*Math.cos(a)*Math.sin(l),c=s*Math.cos(l),d=s*Math.sin(a)*Math.sin(l);n?t.copyFromFloats(h,c,d):o.P.TransformCoordinatesFromFloatsToRef(h,c,d,e,t)}clone(){const e=new hi(this.radius,this.directionRandomizer);return g.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define SPHEREEMITTER"}getClassName(){return"SphereParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class ci extends hi{constructor(e=1,t=new o.P(0,1,0),i=new o.P(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){const i=S.R.RandomRange(this.direction1.x,this.direction2.x),n=S.R.RandomRange(this.direction1.y,this.direction2.y),s=S.R.RandomRange(this.direction1.z,this.direction2.z);o.P.TransformNormalFromFloatsToRef(i,n,s,e,t)}clone(){const e=new ci(this.radius,this.direction1,this.direction2);return g.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER"}getClassName(){return"SphereDirectedParticleEmitter"}serialize(){const e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}class di{constructor(){this.particlePositionGenerator=()=>{},this.particleDestinationGenerator=()=>{}}startDirectionFunction(e,t,i,n){const s=o.jp.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,s);const e=o.jp.Vector3[1];s.subtractToRef(i.position,e),e.scaleToRef(1/i.lifeTime,s)}else s.set(0,0,0);n?t.copyFrom(s):o.P.TransformNormalToRef(s,e,t)}startPositionFunction(e,t,i,n){const s=o.jp.Vector3[0];this.particlePositionGenerator?this.particlePositionGenerator(-1,i,s):s.set(0,0,0),n?t.copyFrom(s):o.P.TransformCoordinatesToRef(s,e,t)}clone(){const e=new di;return g.j.DeepCopy(this,e),e}applyToShader(e){}buildUniformLayout(e){}getEffectDefines(){return"#define CUSTOMEMITTER"}getClassName(){return"CustomParticleEmitter"}serialize(){const e={};return e.type=this.getClassName(),e}parse(e){}}class ui{get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(ne.o.PositionKind),this._normals=e.getVerticesData(ne.o.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))}constructor(e=null){this._indices=null,this._positions=null,this._normals=null,this._storedNormal=o.P.Zero(),this._mesh=null,this.direction1=new o.P(0,1,0),this.direction2=new o.P(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,n){if(this.useMeshNormalsForDirection&&this._normals)return void o.P.TransformNormalToRef(this._storedNormal,e,t);const s=S.R.RandomRange(this.direction1.x,this.direction2.x),r=S.R.RandomRange(this.direction1.y,this.direction2.y),a=S.R.RandomRange(this.direction1.z,this.direction2.z);n?t.copyFromFloats(s,r,a):o.P.TransformNormalFromFloatsToRef(s,r,a,e,t)}startPositionFunction(e,t,i,n){if(!this._indices||!this._positions)return;const s=3*Math.random()*(this._indices.length/3)|0,r=Math.random(),a=Math.random()*(1-r),l=1-r-a,h=this._indices[s],c=this._indices[s+1],d=this._indices[s+2],u=o.jp.Vector3[0],p=o.jp.Vector3[1],f=o.jp.Vector3[2],_=o.jp.Vector3[3];o.P.FromArrayToRef(this._positions,3*h,u),o.P.FromArrayToRef(this._positions,3*c,p),o.P.FromArrayToRef(this._positions,3*d,f),_.x=r*u.x+a*p.x+l*f.x,_.y=r*u.y+a*p.y+l*f.y,_.z=r*u.z+a*p.z+l*f.z,n?t.copyFromFloats(_.x,_.y,_.z):o.P.TransformCoordinatesFromFloatsToRef(_.x,_.y,_.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(o.P.FromArrayToRef(this._normals,3*h,u),o.P.FromArrayToRef(this._normals,3*c,p),o.P.FromArrayToRef(this._normals,3*d,f),this._storedNormal.x=r*u.x+a*p.x+l*f.x,this._storedNormal.y=r*u.y+a*p.y+l*f.y,this._storedNormal.z=r*u.z+a*p.z+l*f.z)}clone(){const e=new ui(this.mesh);return g.j.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return""}getClassName(){return"MeshParticleEmitter"}serialize(){var e;const t={};return t.type=this.getClassName(),t.direction1=this.direction1.asArray(),t.direction2=this.direction2.asArray(),t.meshId=null===(e=this.mesh)||void 0===e?void 0:e.id,t.useMeshNormalsForDirection=this.useMeshNormalsForDirection,t}parse(e,t){o.P.FromArrayToRef(e.direction1,0,this.direction1),o.P.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}}i(6430);class pi{get noiseTexture(){return this._noiseTexture}set noiseTexture(e){this._noiseTexture!==e&&(this._noiseTexture=e,this._reset())}get isAnimationSheetEnabled(){return this._isAnimationSheetEnabled}set isAnimationSheetEnabled(e){this._isAnimationSheetEnabled!=e&&(this._isAnimationSheetEnabled=e,this._reset())}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported}getScene(){return this._scene}_hasTargetStopDurationDependantGradient(){return this._startSizeGradients&&this._startSizeGradients.length>0||this._emitRateGradients&&this._emitRateGradients.length>0||this._lifeTimeGradients&&this._lifeTimeGradients.length>0}getDragGradients(){return this._dragGradients}getLimitVelocityGradients(){return this._limitVelocityGradients}getColorGradients(){return this._colorGradients}getSizeGradients(){return this._sizeGradients}getColorRemapGradients(){return this._colorRemapGradients}getAlphaRemapGradients(){return this._alphaRemapGradients}getLifeTimeGradients(){return this._lifeTimeGradients}getAngularSpeedGradients(){return this._angularSpeedGradients}getVelocityGradients(){return this._velocityGradients}getStartSizeGradients(){return this._startSizeGradients}getEmitRateGradients(){return this._emitRateGradients}get direction1(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:o.P.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:o.P.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:o.P.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:o.P.Zero()}set maxEmitBox(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)}get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._reset())}get isBillboardBased(){return this._isBillboardBased}set isBillboardBased(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._reset())}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(!e&&this._scene?this._imageProcessingConfiguration=this._scene.imageProcessingConfiguration:this._imageProcessingConfiguration=e)}_reset(){}_removeGradientAndTexture(e,t,i){if(!t)return this;let n=0;for(const s of t){if(s.gradient===e){t.splice(n,1);break}n++}return i&&i.dispose(),this}constructor(e){this.animations=[],this.renderingGroupId=0,this.emitter=o.P.Zero(),this.emitRate=10,this.manualEmitCount=-1,this.updateSpeed=.01,this.targetStopDuration=0,this.disposeOnStop=!1,this.minEmitPower=1,this.maxEmitPower=1,this.minLifeTime=1,this.maxLifeTime=1,this.minSize=1,this.maxSize=1,this.minScaleX=1,this.maxScaleX=1,this.minScaleY=1,this.maxScaleY=1,this.minInitialRotation=0,this.maxInitialRotation=0,this.minAngularSpeed=0,this.maxAngularSpeed=0,this.layerMask=268435455,this.customShader=null,this.preventAutoStart=!1,this._wasDispatched=!1,this._rootUrl="",this.noiseStrength=new o.P(10,10,10),this.onAnimationEnd=null,this.blendMode=pi.BLENDMODE_ONEONE,this.forceDepthWrite=!1,this.preWarmCycles=0,this.preWarmStepOffset=1,this.spriteCellChangeSpeed=1,this.startSpriteCellID=0,this.endSpriteCellID=0,this.spriteCellWidth=0,this.spriteCellHeight=0,this.spriteCellLoop=!0,this.spriteRandomStartCell=!1,this.translationPivot=new o.FM(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new o.P(0,0,0),this._useLogarithmicDepth=!1,this.gravity=o.P.Zero(),this._colorGradients=null,this._sizeGradients=null,this._lifeTimeGradients=null,this._angularSpeedGradients=null,this._velocityGradients=null,this._limitVelocityGradients=null,this._dragGradients=null,this._emitRateGradients=null,this._startSizeGradients=null,this._rampGradients=null,this._colorRemapGradients=null,this._alphaRemapGradients=null,this.startDelay=0,this.limitVelocityDamping=.4,this.color1=new a.HE(1,1,1,1),this.color2=new a.HE(1,1,1,1),this.colorDead=new a.HE(0,0,0,1),this.textureMask=new a.HE(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new ii.b,this.id=e,this.name=e}createPointEmitter(e,t){const i=new li;return i.direction1=e,i.direction2=t,this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){const i=new ai(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){const i=new hi(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new o.P(0,1,0),i=new o.P(0,1,0)){const n=new ci(e,t,i);return this.particleEmitterType=n,n}createCylinderEmitter(e=1,t=1,i=1,n=0){const s=new ri(e,t,i,n);return this.particleEmitterType=s,s}createDirectedCylinderEmitter(e=1,t=1,i=1,n=new o.P(0,1,0),s=new o.P(0,1,0)){const r=new oi(e,t,i,n,s);return this.particleEmitterType=r,r}createConeEmitter(e=1,t=Math.PI/4){const i=new si(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,n){const s=new ni;return this.particleEmitterType=s,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=n,s}}pi.BLENDMODE_ONEONE=0,pi.BLENDMODE_STANDARD=1,pi.BLENDMODE_ADD=2,pi.BLENDMODE_MULTIPLY=3,pi.BLENDMODE_MULTIPLYADD=4;class fi extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("rgba",ct.Color4,!0),this.registerInput("rgb ",ct.Color3,!0),this.registerOutput("rgb",ct.Color3),this.registerOutput("r",ct.Float),this.registerOutput("g",ct.Float),this.registerOutput("b",ct.Float),this.registerOutput("a",ct.Float),this.inputsAreExclusive=!0}getClassName(){return"ColorSplitterBlock"}get rgba(){return this._inputs[0]}get rgbIn(){return this._inputs[1]}get rgbOut(){return this._outputs[0]}get r(){return this._outputs[1]}get g(){return this._outputs[2]}get b(){return this._outputs[3]}get a(){return this._outputs[4]}_inputRename(e){return"rgb "===e?"rgbIn":e}_outputRename(e){return"rgb"===e?"rgbOut":e}_buildBlock(e){super._buildBlock(e);const t=this.rgba.isConnected?this.rgba:this.rgbIn;if(!t.isConnected)return;const i=this._outputs[0],n=this._outputs[1],s=this._outputs[2],r=this._outputs[3],o=this._outputs[4];return i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = ${t.associatedVariableName}.rgb;\r\n`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${t.associatedVariableName}.r;\r\n`),s.hasEndpoints&&(e.compilationString+=this._declareOutput(s,e)+` = ${t.associatedVariableName}.g;\r\n`),r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = ${t.associatedVariableName}.b;\r\n`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = ${t.associatedVariableName}.a;\r\n`),this}}(0,l.H)("BABYLON.ColorSplitterBlock",fi);var _i=i(9093),mi=i(5567);Ue.B.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),n=Object.assign({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5},t);n.generateStencilBuffer=n.generateDepthBuffer&&n.generateStencilBuffer,(1!==n.type||this._caps.textureFloatLinearFiltering)&&(2!==n.type||this._caps.textureHalfFloatLinearFiltering)||(n.samplingMode=1);const s=this._gl,r=new Be.l(this,Be.S.RenderTarget);this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,r,!0);const o=this._getSamplingParameters(n.samplingMode,n.generateMipMaps);1!==n.type||this._caps.textureFloat||(n.type=0,p.Y.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAG_FILTER,o.mag),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,o.min),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE);for(let l=0;l<6;l++)s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+l,0,this._getRGBABufferInternalSizedFormat(n.type,n.format),e,e,0,this._getInternalFormat(n.format),this._getWebGLTextureType(n.type),null);const a=s.createFramebuffer();return this._bindUnboundFramebuffer(a),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(n.generateStencilBuffer,n.generateDepthBuffer,e,e),n.generateMipMaps&&s.generateMipmap(s.TEXTURE_CUBE_MAP),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),i._framebuffer=a,i._generateDepthBuffer=n.generateDepthBuffer,i._generateStencilBuffer=n.generateStencilBuffer,r.width=e,r.height=e,r.isReady=!0,r.isCube=!0,r.samples=1,r.generateMipMaps=n.generateMipMaps,r.samplingMode=n.samplingMode,r.type=n.type,r.format=n.format,this._internalTexturesCache.push(r),i.setTextures(r),i};const gi={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class vi{constructor(e,t=gi){var i,n;this._fullscreenViewport=new Nt.l(0,0,1,1);const s=null!==(i=t.positions)&&void 0!==i?i:gi.positions,r=null!==(n=t.indices)&&void 0!==n?n:gi.indices;this.engine=e,this._vertexBuffers={[ne.o.PositionKind]:new ne.o(e,s,ne.o.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(r),this._onContextRestoredObserver=e.onContextRestoredObservable.add((()=>{this._indexBuffer=e.createIndexBuffer(r);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({})}restoreStates(){this.engine.depthCullingState.depthTest=!0,this.engine.stencilState.stencilTest=!0}draw(){this.engine.drawElementsType(0,0,6)}_isRenderTargetTexture(e){return void 0!==e.renderTarget}render(e,t=null){if(!e.effect.isReady())return;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[ne.o.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[ne.o.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class Ti{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){let t;this.onApplyObservable=new r.y$;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 $t.q(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 ft.Q(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._wasPreviouslyReady=!1,this.effect._prepareEffect()})))}dispose(){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()}}const Si="passPixelShader",Ei="varying vec2 vUV;\nuniform sampler2D textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}";Ht.v.ShadersStore[Si]=Ei;const xi={name:Si,shader:Ei};class bi{static _CreateDumpRenderer(){if(!bi._DumpToolsEngine){const e=new OffscreenCanvas(100,100),t=new Ue.B(e,!1,{preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1});t.getCaps().parallelShaderCompile=void 0;const i=new vi(t),n=new Ti({engine:t,name:xi.name,fragmentShader:xi.shader,samplerNames:["textureSampler"]});bi._DumpToolsEngine={canvas:e,engine:t,renderer:i,wrapper:n}}return bi._DumpToolsEngine}static async DumpFramebuffer(e,t,i,n,s="image/png",r,o){const a=await i.readPixels(0,0,e,t),l=new Uint8Array(a.buffer);bi.DumpData(e,t,l,n,s,r,!0,void 0,o)}static DumpDataAsync(e,t,i,n="image/png",s,r=!1,o=!1,a){return new Promise((l=>{bi.DumpData(e,t,i,(e=>l(e)),n,s,r,o,a)}))}static DumpData(e,t,i,n,s="image/png",r,o=!1,a=!1,l){const h=bi._CreateDumpRenderer();if(h.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*S.R.Clamp(n))}i=e}const c=h.engine.createRawTexture(i,e,t,5,!1,!o,1);h.renderer.setViewport(),h.renderer.applyEffectWrapper(h.wrapper),h.wrapper.effect._bindTexture("textureSampler",c),h.renderer.draw(),a?se.w1.ToBlob(h.canvas,(e=>{const t=new FileReader;t.onload=e=>{const t=e.target.result;n&&n(t)},t.readAsArrayBuffer(e)}),s,l):se.w1.EncodeScreenshotCanvasData(h.canvas,n,s,r,l),c.dispose()}static Dispose(){bi._DumpToolsEngine&&(bi._DumpToolsEngine.wrapper.dispose(),bi._DumpToolsEngine.renderer.dispose(),bi._DumpToolsEngine.engine.dispose()),bi._DumpToolsEngine=null}}se.w1.DumpData=bi.DumpData,se.w1.DumpDataAsync=bi.DumpDataAsync,se.w1.DumpFramebuffer=bi.DumpFramebuffer;class Ci extends Le{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=(0,w.M)(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 n=0;n{var i;const n=this._renderList?this._renderList.length:0;(0===t&&n>0||0===n)&&(null===(i=this.getScene())||void 0===i||i.meshes.forEach((e=>{e._markSubMeshesAsLightDirty()})))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new r.y$,this.onAfterUnbindObservable=new r.y$,this.onBeforeRenderObservable=new r.y$,this.onAfterRenderObservable=new r.y$,this.onClearObservable=new r.y$,this.onResizeObservable=new r.y$,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=o.P.Zero(),!(i=this.getScene()))return;const A=this.getScene().getEngine();this._coordinatesMode=Le.PROJECTION_MODE,this.renderList=new Array,this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._renderPassIds=[],this._isCubeData=l,this._processSizeParameter(t),this.renderPassId=this._renderPassIds[0],this._resizeObserver=A.onResizeObservable.add((()=>{})),this._generateMipMaps=!!n,this._doNotChangeAspectRatio=s,this._renderingManager=new mi.$(i),this._renderingManager._useSceneAutoClearSetup=!0,u||(this._renderTargetOptions={generateMipMaps:n,type:a,format:null!==(C=this._format)&&void 0!==C?C:void 0,samplingMode:this.samplingMode,generateDepthBuffer:c,generateStencilBuffer:d,samples:_,creationFlags:m,noColorAttachment:g,useSRGBBuffer:v,colorAttachment:y,label:this.name},this.samplingMode===Le.NEAREST_SAMPLINGMODE&&(this.wrapU=Le.CLAMP_ADDRESSMODE,this.wrapV=Le.CLAMP_ADDRESSMODE),f||(l?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=Le.INVCUBIC_MODE,this._textureMatrix=o.y3.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==_&&(this.samples=_)))}createDepthStencilTexture(e=0,t=!0,i=!1,n=1,s=14){var r;null===(r=this._renderTarget)||void 0===r||r.createDepthStencilTexture(e,t,i,n,s)}_releaseRenderPassId(){if(this._scene){const e=this._scene.getEngine();for(let t=0;t0&&(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;return e||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){const t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){var t;const i=this.isCube;null===(t=this._renderTarget)||void 0===t||t.dispose(),this._renderTarget=null;const n=this.getScene();n&&(this._processSizeParameter(e,!1),this._renderTarget=i?n.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):n.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){var n;const s=this.getScene();if(!s)return i;const r=s.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){this.renderList=[];for(let e=0;e1||this.activeCamera&&this.activeCamera!==s.activeCamera)&&s.setTransformMatrix(s.activeCamera.getViewMatrix(),s.activeCamera.getProjectionMatrix(!0)),r.setViewport(s.activeCamera.viewport)),s.resetCachedMaterial(),h}_bestReflectionRenderTargetDimension(e,t){const i=e*t,n=fe.D.NearestPOT(i+16384/(128+i));return Math.min(fe.D.FloorPOT(e),n)}_prepareRenderingManager(e,t,i,n){const s=this.getScene();if(!s)return;this._renderingManager.reset();const r=s.getRenderId();for(let o=0;o{this.onAfterRenderObservable.notifyObservers(t)}))}_prepareFrame(e,t,i,n){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):n&&e.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,n=0,s=null){var r,o,a,l,h,c;const d=this.getScene();if(!d)return;const u=d.getEngine();null===(r=u._debugPushGroup)||void 0===r||r.call(u,`render to face #${e} layer #${n}`,1),this._prepareFrame(d,e,n,t),this.is2DArray?(u.currentRenderPassId=this._renderPassIds[n],this.onBeforeRenderObservable.notifyObservers(n)):(u.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e));if(u.snapshotRendering&&1===u.snapshotRenderingMode)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(u):this.skipInitialClear||u.clear(this.clearColor||d.clearColor,!0,!0,!0);else{let r=null;const c=this.renderList?this.renderList:d.getActiveMeshes().data,p=this.renderList?this.renderList.length:d.getActiveMeshes().length;this.getCustomRenderList&&(r=this.getCustomRenderList(this.is2DArray?n:e,c,p)),r?this._prepareRenderingManager(r,r.length,s,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(c,p,s,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),r=c);for(const t of d._beforeRenderTargetClearStage)t.action(this,e,n);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(u):this.skipInitialClear||u.clear(this.clearColor||d.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||d.updateTransformMatrix(!0);for(const t of d._beforeRenderTargetDrawStage)t.action(this,e,n);this._renderingManager.render(this.customRenderFunction,r,this.renderParticles,this.renderSprites);for(const t of d._afterRenderTargetDrawStage)t.action(this,e,n);const f=null!==(a=null===(o=this._texture)||void 0===o?void 0:o.generateMipMaps)&&void 0!==a&&a;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,null!==(l=this._renderTarget)&&void 0!==l?l:void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&d.postProcessManager._finalizeFrame(!1,null!==(h=this._renderTarget)&&void 0!==h?h:void 0,e);for(const t of d._afterRenderTargetPostProcessStage)t.action(this,e,n);this._texture&&(this._texture.generateMipMaps=f),this._doNotChangeAspectRatio||d.updateTransformMatrix(!0),i&&bi.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),u)}this._unbindFrameBuffer(u,e),this._texture&&this.isCube&&5===e&&u.generateMipMapsForCubemap(this._texture),null===(c=u._debugPopGroup)||void 0===c||c.call(u,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 Ci(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer,void 0,this._renderTargetOptions.format,void 0,this._renderTargetOptions.samples);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,this.renderList&&(t.renderList=this.renderList.slice(0)),t}serialize(){if(!this.name)return null;const e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t=0&&t.customRenderTargets.splice(i,1);for(const n of t.cameras)i=n.customRenderTargets.indexOf(this),i>=0&&n.customRenderTargets.splice(i,1);null===(e=this._renderTarget)||void 0===e||e.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===Ci.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=Ci.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}Ci.REFRESHRATE_RENDER_ONCE=0,Ci.REFRESHRATE_RENDER_ONEVERYFRAME=1,Ci.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,Le._CreateRenderTargetTexture=(e,t,i,n,s)=>new Ci(e,t,i,n);class yi{constructor(e){this.name=Se.l.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=new Array}register(){this.scene._beforeClearStage.registerStep(Se.l.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){se.w1.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e0)}}}const Ai="proceduralVertexShader",Ri="attribute vec2 position;\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";Ht.v.ShadersStore[Ai]=Ri;class Pi extends Le{constructor(e,t,i,n,s=null,o=!0,a=!1,l=0){super(null,n,!o),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new r.y$,this.onBeforeGenerationObservable=new r.y$,this.nodeMaterialSource=null,this._textures={},this._currentRefreshId=-1,this._frameId=-1,this._refreshRate=1,this._vertexBuffers={},this._uniforms=new Array,this._samplers=new Array,this._floats={},this._ints={},this._floatsArrays={},this._colors3={},this._colors4={},this._vectors2={},this._vectors3={},this._matrices={},this._fallbackTextureUsed=!1,this._cachedDefines=null,this._contentUpdateId=-1,this._rtWrapper=null;let h=(n=this.getScene()||m.l.LastCreatedScene)._getComponent(Se.l.NAME_PROCEDURALTEXTURE);h||(h=new yi(n),n._addComponent(h)),n.proceduralTextures.push(this),this._fullEngine=n.getEngine(),this.name=e,this.isRenderTarget=!0,this._size=t,this._textureType=l,this._generateMipMaps=o,this._drawWrapper=new $t.q(this._fullEngine),this.setFragment(i),this._fallbackTexture=s;const c=this._createRtWrapper(a,t,o,l);this._texture=c.texture;const d=[];d.push(1,1),d.push(-1,1),d.push(-1,-1),d.push(1,-1),this._vertexBuffers[ne.o.PositionKind]=new ne.o(this._fullEngine,d,ne.o.PositionKind,!1,!1,2),this._createIndexBuffer()}_createRtWrapper(e,t,i,n){return e?(this._rtWrapper=this._fullEngine.createRenderTargetCubeTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:n}),this.setFloat("face",0)):this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:n}),this._rtWrapper}getEffect(){return this._drawWrapper.effect}_setEffect(e){this._drawWrapper.effect=e}getContent(){return this._contentData&&this._frameId===this._contentUpdateId||(this._contentData?this._contentData.then((e=>{this._contentData=this.readPixels(0,0,e),this._contentUpdateId=this._frameId})):(this._contentData=this.readPixels(0,0),this._contentUpdateId=this._frameId)),this._contentData}_createIndexBuffer(){const e=this._fullEngine,t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){const e=this._vertexBuffers[ne.o.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===Ci.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=Ci.REFRESHRATE_RENDER_ONCE)}reset(){var e;null===(e=this._drawWrapper.effect)||void 0===e||e.dispose()}_getDefines(){return""}isReady(){const e=this._fullEngine;let t;if(this.nodeMaterialSource)return this._drawWrapper.effect.isReady();if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;if(!this._texture)return!1;const i=this._getDefines();return!(!this._drawWrapper.effect||i!==this._cachedDefines||!this._drawWrapper.effect.isReady())||(t=void 0!==this._fragment.fragmentElement?{vertex:"procedural",fragmentElement:this._fragment.fragmentElement}:{vertex:"procedural",fragment:this._fragment},this._cachedDefines!==i&&(this._cachedDefines=i,this._drawWrapper.effect=e.createEffect(t,[ne.o.PositionKind],this._uniforms,this._samplers,i,void 0,void 0,(()=>{var e;null===(e=this._rtWrapper)||void 0===e||e.dispose(),this._rtWrapper=this._texture=null,this._fallbackTexture&&(this._texture=this._fallbackTexture._texture,this._texture&&this._texture.incrementReferences()),this._fallbackTextureUsed=!0}))),this._drawWrapper.effect.isReady())}resetRefreshCounter(){this._currentRefreshId=-1}setFragment(e){this._fragment=e}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}_shouldRender(){return this.isEnabled&&this.isReady()&&this._texture?!this._fallbackTextureUsed&&(-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,this._frameId++,!0):(this._currentRefreshId++,!1)):(this._texture&&(this._texture.isReady=!1),!1)}getRenderSize(){return this._size}resize(e,t){if(this._fallbackTextureUsed||!this._rtWrapper||!this._texture)return;const i=this._texture.isCube;this._rtWrapper.dispose();const n=this._createRtWrapper(i,e,t,this._textureType);this._texture=n.texture,this._size=e,this._generateMipMaps=t}_checkUniform(e){-1===this._uniforms.indexOf(e)&&this._uniforms.push(e)}setTexture(e,t){return-1===this._samplers.indexOf(e)&&this._samplers.push(e),this._textures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}render(e){var t,i;const n=this.getScene();if(!n)return;const s=this._fullEngine;if(s.enableEffect(this._drawWrapper),this.onBeforeGenerationObservable.notifyObservers(this),s.setState(!1),!this.nodeMaterialSource){for(const e in this._textures)this._drawWrapper.effect.setTexture(e,this._textures[e]);for(const e in this._ints)this._drawWrapper.effect.setInt(e,this._ints[e]);for(const e in this._floats)this._drawWrapper.effect.setFloat(e,this._floats[e]);for(const e in this._floatsArrays)this._drawWrapper.effect.setArray(e,this._floatsArrays[e]);for(const e in this._colors3)this._drawWrapper.effect.setColor3(e,this._colors3[e]);for(const e in this._colors4){const t=this._colors4[e];this._drawWrapper.effect.setFloat4(e,t.r,t.g,t.b,t.a)}for(const e in this._vectors2)this._drawWrapper.effect.setVector2(e,this._vectors2[e]);for(const e in this._vectors3)this._drawWrapper.effect.setVector3(e,this._vectors3[e]);for(const e in this._matrices)this._drawWrapper.effect.setMatrix(e,this._matrices[e])}if(!this._texture||!this._rtWrapper)return;null===(t=s._debugPushGroup)||void 0===t||t.call(s,`procedural texture generation for ${this.name}`,1);const r=s.currentViewport;if(this.isCube)for(let o=0;o<6;o++)s.bindFramebuffer(this._rtWrapper,o,void 0,void 0,!0),s.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",o),this.autoClear&&s.clear(n.clearColor,!0,!1,!1),s.drawElementsType(ut.F.TriangleFillMode,0,6);else s.bindFramebuffer(this._rtWrapper,0,void 0,void 0,!0),s.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this.autoClear&&s.clear(n.clearColor,!0,!1,!1),s.drawElementsType(ut.F.TriangleFillMode,0,6);s.unBindFramebuffer(this._rtWrapper,this.isCube),r&&s.setViewport(r),this.isCube&&s.generateMipMapsForCubemap(this._texture),null===(i=s._debugPopGroup)||void 0===i||i.call(s,1),this.onGenerated&&this.onGenerated(),this.onGeneratedObservable.notifyObservers(this)}clone(){const e=this.getSize(),t=new Pi(this.name,e.width,this._fragment,this.getScene(),this._fallbackTexture,this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,t}dispose(){const e=this.getScene();if(!e)return;const t=e.proceduralTextures.indexOf(this);t>=0&&e.proceduralTextures.splice(t,1);const i=this._vertexBuffers[ne.o.PositionKind];i&&(i.dispose(),this._vertexBuffers[ne.o.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}}var Ii;(0,oe.gn)([(0,E.qC)()],Pi.prototype,"isEnabled",void 0),(0,oe.gn)([(0,E.qC)()],Pi.prototype,"autoClear",void 0),(0,oe.gn)([(0,E.qC)()],Pi.prototype,"_generateMipMaps",void 0),(0,oe.gn)([(0,E.qC)()],Pi.prototype,"_size",void 0),(0,oe.gn)([(0,E.qC)()],Pi.prototype,"refreshRate",null),(0,l.H)("BABYLON.ProceduralTexture",Pi),function(e){e[e.Cos=0]="Cos",e[e.Sin=1]="Sin",e[e.Abs=2]="Abs",e[e.Exp=3]="Exp",e[e.Exp2=4]="Exp2",e[e.Round=5]="Round",e[e.Floor=6]="Floor",e[e.Ceiling=7]="Ceiling",e[e.Sqrt=8]="Sqrt",e[e.Log=9]="Log",e[e.Tan=10]="Tan",e[e.ArcTan=11]="ArcTan",e[e.ArcCos=12]="ArcCos",e[e.ArcSin=13]="ArcSin",e[e.Fract=14]="Fract",e[e.Sign=15]="Sign",e[e.Radians=16]="Radians",e[e.Degrees=17]="Degrees"}(Ii||(Ii={}));class Mi extends bt{constructor(e){super(e,dt.Neutral),this.operation=Ii.Cos,this.registerInput("input",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"TrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="";switch(this.operation){case Ii.Cos:i="cos";break;case Ii.Sin:i="sin";break;case Ii.Abs:i="abs";break;case Ii.Exp:i="exp";break;case Ii.Exp2:i="exp2";break;case Ii.Round:i="round";break;case Ii.Floor:i="floor";break;case Ii.Ceiling:i="ceil";break;case Ii.Sqrt:i="sqrt";break;case Ii.Log:i="log";break;case Ii.Tan:i="tan";break;case Ii.ArcTan:i="atan";break;case Ii.ArcCos:i="acos";break;case Ii.ArcSin:i="asin";break;case Ii.Fract:i="fract";break;case Ii.Sign:i="sign";break;case Ii.Radians:i="radians";break;case Ii.Degrees:i="degrees"}return e.compilationString+=this._declareOutput(t,e)+` = ${i}(${this.input.associatedVariableName});\r\n`,this}serialize(){const e=super.serialize();return e.operation=this.operation,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.operation=e.operation}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.TrigonometryBlockOperations.${Ii[this.operation]};\r\n`}}(0,l.H)("BABYLON.TrigonometryBlock",Mi);const Oi={effect:null,subMesh:null};class Di extends Tt.H{constructor(){super(),this.NORMAL=!1,this.TANGENT=!1,this.VERTEXCOLOR_NME=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.EXPOSURE=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.BUMPDIRECTUV=0,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.rebuild()}setValue(e,t,i=!1){void 0===this[e]&&this._keys.push(e),i&&this[e]!==t&&this.markAsUnprocessed(),this[e]=t}}class Ni extends pt{static _BlockIsTextureBlock(e){return"TextureBlock"===e.getClassName()||"ReflectionTextureBaseBlock"===e.getClassName()||"RefractionBlock"===e.getClassName()||"CurrentScreenBlock"===e.getClassName()||"ParticleTextureBlock"===e.getClassName()||"ImageSourceBlock"===e.getClassName()||"TriPlanarBlock"===e.getClassName()||"BiPlanarBlock"===e.getClassName()}_getGlobalNodeMaterialEditor(){return"undefined"!=typeof NODEEDITOR?NODEEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeEditor?BABYLON:void 0}get options(){return this._options}set options(e){this._options=e}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get mode(){return this._mode}set mode(e){this._mode=e}get buildId(){return this._buildId}set buildId(e){this._buildId=e}constructor(e,t,i={}){super(e,t||m.l.LastCreatedScene),this._buildId=Ni._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new o.y3,this._cachedWorldViewProjectionMatrix=new o.y3,this._optimizers=new Array,this._animationFrame=-1,this.BJSNODEMATERIALEDITOR=this._getGlobalNodeMaterialEditor(),this.editorData=null,this.ignoreAlpha=!1,this.maxSimultaneousLights=4,this.onBuildObservable=new r.y$,this._vertexOutputNodes=new Array,this._fragmentOutputNodes=new Array,this.attachedBlocks=new Array,this._mode=qt.Material,this.forceAlphaBlending=!1,this._options=Object.assign({emitComments:!1},i),this._attachImageProcessingConfiguration(null)}getClassName(){return"NodeMaterial"}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}getBlockByName(e){let t=null;for(const i of this.attachedBlocks)if(i.name===e){if(t)return se.w1.Warn("More than one block was found with the name `"+e+"`"),t;t=i}return t}getBlockByPredicate(e){for(const t of this.attachedBlocks)if(e(t))return t;return null}getInputBlockByPredicate(e){for(const t of this.attachedBlocks)if(t.isInput&&e(t))return t;return null}getInputBlocks(){const e=[];for(const t of this.attachedBlocks)t.isInput&&e.push(t);return e}registerOptimizer(e){if(!(this._optimizers.indexOf(e)>-1))return this._optimizers.push(e),this}unregisterOptimizer(e){const t=this._optimizers.indexOf(e);if(-1!==t)return this._optimizers.splice(t,1),this}addOutputNode(e){if(null===e.target)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return 0!=(e.target&dt.Vertex)&&this._addVertexOutputNode(e),0!=(e.target&dt.Fragment)&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return null===e.target||(0!=(e.target&dt.Vertex)&&this._removeVertexOutputNode(e),0!=(e.target&dt.Fragment)&&this._removeFragmentOutputNode(e)),this}_addVertexOutputNode(e){if(-1===this._vertexOutputNodes.indexOf(e))return e.target=dt.Vertex,this._vertexOutputNodes.push(e),this}_removeVertexOutputNode(e){const t=this._vertexOutputNodes.indexOf(e);if(-1!==t)return this._vertexOutputNodes.splice(t,1),this}_addFragmentOutputNode(e){if(-1===this._fragmentOutputNodes.indexOf(e))return e.target=dt.Fragment,this._fragmentOutputNodes.push(e),this}_removeFragmentOutputNode(e){const t=this._fragmentOutputNodes.indexOf(e);if(-1!==t)return this._fragmentOutputNodes.splice(t,1),this}needAlphaBlending(){return!this.ignoreAlpha&&(this.forceAlphaBlending||this.alpha<1||this._sharedData&&this._sharedData.hints.needAlphaBlending)}needAlphaTesting(){return this._sharedData&&this._sharedData.hints.needAlphaTesting}_initializeBlock(e,t,i,n=!0){if(e.initialize(t),n&&e.autoConfigure(this),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)){if(e.isUnique){const t=e.getClassName();for(const e of this.attachedBlocks)if(e.getClassName()===t)throw`Cannot have multiple blocks of type ${t} in the same NodeMaterial`}this.attachedBlocks.push(e)}for(const s of e.inputs){s.associatedVariableName="";const r=s.connectedPoint;if(r){const s=r.ownerBlock;s!==e&&((s.target===dt.VertexAndFragment||t.target===dt.Fragment&&s.target===dt.Vertex&&s._preparationId!==this._buildId)&&i.push(s),this._initializeBlock(s,t,i,n))}}for(const s of e.outputs)s.associatedVariableName=""}_resetDualBlocks(e,t){e.target===dt.VertexAndFragment&&(e.buildId=t);for(const i of e.inputs){const n=i.connectedPoint;if(n){const i=n.ownerBlock;i!==e&&this._resetDualBlocks(i,t)}}}removeBlock(e){const t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e.isFinalMerger&&this.removeOutputNode(e)}build(e=!1,t=!0,i=!0){this._buildWasSuccessful=!1;const n=this.getScene().getEngine(),s=this._mode===qt.Particle;if(0===this._vertexOutputNodes.length&&!s)throw"You must define at least one vertexOutputNode";if(0===this._fragmentOutputNodes.length)throw"You must define at least one fragmentOutputNode";this._vertexCompilationState=new _t,this._vertexCompilationState.supportUniformBuffers=n.supportsUniformBuffers,this._vertexCompilationState.target=dt.Vertex,this._fragmentCompilationState=new _t,this._fragmentCompilationState.supportUniformBuffers=n.supportsUniformBuffers,this._fragmentCompilationState.target=dt.Fragment,this._sharedData=new mt,this._sharedData.fragmentOutputNodes=this._fragmentOutputNodes,this._vertexCompilationState.sharedData=this._sharedData,this._fragmentCompilationState.sharedData=this._sharedData,this._sharedData.buildId=this._buildId,this._sharedData.emitComments=this._options.emitComments,this._sharedData.verbose=e,this._sharedData.scene=this.getScene(),this._sharedData.allowEmptyVertexProgram=s;const r=[],o=[];for(const l of this._vertexOutputNodes)r.push(l),this._initializeBlock(l,this._vertexCompilationState,o,i);for(const l of this._fragmentOutputNodes)o.push(l),this._initializeBlock(l,this._fragmentCompilationState,r,i);this.optimize();for(const l of r)l.build(this._vertexCompilationState,r);this._fragmentCompilationState.uniforms=this._vertexCompilationState.uniforms.slice(0),this._fragmentCompilationState._uniformDeclaration=this._vertexCompilationState._uniformDeclaration,this._fragmentCompilationState._constantDeclaration=this._vertexCompilationState._constantDeclaration,this._fragmentCompilationState._vertexState=this._vertexCompilationState;for(const l of o)this._resetDualBlocks(l,this._buildId-1);for(const l of o)l.build(this._fragmentCompilationState,o);this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),t&&(this._buildId=Ni._BuildIdGenerator++),this._sharedData.emitErrors(),e&&(console.log("Vertex shader:"),console.log(this._vertexCompilationState.compilationString),console.log("Fragment shader:"),console.log(this._fragmentCompilationState.compilationString)),this._buildWasSuccessful=!0,this.onBuildObservable.notifyObservers(this);const a=this.getScene().meshes;for(const l of a)if(l.subMeshes)for(const e of l.subMeshes){if(e.getMaterial()!==this)continue;if(!e.materialDefines)continue;const t=e.materialDefines;t.markAllAsDirty(),t.reset()}}optimize(){for(const e of this._optimizers)e.optimize(this._vertexOutputNodes,this._fragmentOutputNodes)}_prepareDefinesForAttributes(e,t){const i=t.NORMAL,n=t.TANGENT,s=t.VERTEXCOLOR_NME;t.NORMAL=e.isVerticesDataPresent(ne.o.NormalKind),t.TANGENT=e.isVerticesDataPresent(ne.o.TangentKind);const r=e.useVertexColors&&e.isVerticesDataPresent(ne.o.ColorKind);t.VERTEXCOLOR_NME=r;let o=!1;for(let a=1;a<=6;++a){const i=t["UV"+a];t["UV"+a]=e.isVerticesDataPresent(`uv${1===a?"":a}`),o=o||t["UV"+a]!==i}(i!==t.NORMAL||n!==t.TANGENT||s!==t.VERTEXCOLOR_NME||o)&&t.markAsAttributesDirty()}createPostProcess(e,t=1,i=1,n,s,r=0,o=5){return this.mode!==qt.PostProcess?(console.log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,n,s,r,o)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,n=1,s,r,o=0,a=5){let l=this.name+this._buildId;const h=new Di,c=new ie.x(l+"PostProcess",this.getScene());let d=this._buildId;return this._processDefines(c,h),ft.Q.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),e?e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l):e=new Zt(this.name+"PostProcess",l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,n,s,r,h.toString(),o,l,{maxSimultaneousLights:this.maxSimultaneousLights},!1,a),e.nodeMaterialSource=this,e.onApplyObservable.add((t=>{d!==this._buildId&&(delete ft.Q.ShadersStore[l+"VertexShader"],delete ft.Q.ShadersStore[l+"PixelShader"],l=this.name+this._buildId,h.markAllAsDirty(),d=this._buildId);this._processDefines(c,h)&&(ft.Q.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),Pe.Q.SetImmediate((()=>e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l)))),this._checkInternals(t)})),e}createProceduralTexture(e,t){if(this.mode!==qt.ProceduralTexture)return console.log("Incompatible material mode"),null;let i=this.name+this._buildId;const n=new Pi(i,e,null,t),s=new ie.x(i+"Procedural",this.getScene());s.reservedDataStore={hidden:!0};const r=new Di,o=this._processDefines(s,r);ft.Q.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString);let a=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[ne.o.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,r.toString(),null==o?void 0:o.fallbacks,void 0);n.nodeMaterialSource=this,n._setEffect(a);let l=this._buildId;return n.onBeforeGenerationObservable.add((()=>{l!==this._buildId&&(delete ft.Q.ShadersStore[i+"VertexShader"],delete ft.Q.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,r.markAllAsDirty(),l=this._buildId);const e=this._processDefines(s,r);e&&(ft.Q.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),Pe.Q.SetImmediate((()=>{a=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[ne.o.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,r.toString(),null==e?void 0:e.fallbacks,void 0),n._setEffect(a)}))),this._checkInternals(a)})),n}_createEffectForParticles(e,t,i,n,s,r,o,a=""){let l=this.name+this._buildId+"_"+t;r||(r=new Di),o||(o=this.getScene().getMeshByName(this.name+"Particle"))||((o=new ie.x(this.name+"Particle",this.getScene())).reservedDataStore={hidden:!0});let h=this._buildId;const c=[];let d=a;if(!s){const a=this._processDefines(o,r);ft.Q.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),e.fillDefines(c,t),d=c.join("\n"),s=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,r.toString()+"\n"+d,null==a?void 0:a.fallbacks,i,n,e),e.setCustomEffect(s,t)}s.onBindObservable.add((s=>{h!==this._buildId&&(delete ft.Q.ShadersStore[l+"PixelShader"],l=this.name+this._buildId+"_"+t,r.markAllAsDirty(),h=this._buildId),c.length=0,e.fillDefines(c,t);const u=c.join("\n");u!==d&&(r.markAllAsDirty(),d=u);const p=this._processDefines(o,r);if(p)return ft.Q.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),s=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,r.toString()+"\n"+d,null==p?void 0:p.fallbacks,i,n,e),e.setCustomEffect(s,t),void this._createEffectForParticles(e,t,i,n,s,r,o,a);this._checkInternals(s)}))}_checkInternals(e){if(this._sharedData.animatedInputs){const e=this.getScene(),t=e.getFrameId();if(this._animationFrame!==t){for(const t of this._sharedData.animatedInputs)t.animate(e);this._animationFrame=t}}for(const t of this._sharedData.bindableBlocks)t.bind(e,this);for(const t of this._sharedData.inputBlocks)t._transmit(e,this.getScene(),this)}createEffectForParticles(e,t,i){this.mode===qt.Particle?(this._createEffectForParticles(e,pi.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,pi.BLENDMODE_MULTIPLY,t,i)):console.log("Incompatible material mode")}createAsShadowDepthWrapper(e){this.mode===qt.Material?e.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(this,this.getScene()):console.log("Incompatible material mode")}_processDefines(e,t,i=!1,n){let s=null;const r=this.getScene();if(It.G.PrepareDefinesForCamera(r,t)&&t.markAsMiscDirty(),this._sharedData.blocksWithDefines.forEach((n=>{n.initializeDefines(e,this,t,i)})),this._sharedData.blocksWithDefines.forEach((s=>{s.prepareDefines(e,this,t,i,n)})),t.isDirty){const i=t._areLightsDisposed;t.markAsProcessed(),this._vertexCompilationState.compilationString=this._vertexCompilationState._builtCompilationString,this._fragmentCompilationState.compilationString=this._fragmentCompilationState._builtCompilationString,this._sharedData.repeatableContentBlocks.forEach((i=>{i.replaceRepeatableContent(this._vertexCompilationState,this._fragmentCompilationState,e,t)}));const n=[];this._sharedData.dynamicUniformBlocks.forEach((e=>{e.updateUniformsAndSamples(this._vertexCompilationState,this,t,n)}));const r=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach((e=>{-1===r.indexOf(e)&&r.push(e)}));const o=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach((e=>{-1===o.indexOf(e)&&o.push(e)}));const a=new zt;this._sharedData.blocksWithFallbacks.forEach((t=>{t.provideFallbacks(e,a)})),s={lightDisposed:i,uniformBuffers:n,mergedUniforms:r,mergedSamplers:o,fallbacks:a}}return s}isReadyForSubMesh(e,t,i=!1){if(!this._buildWasSuccessful)return!1;const n=this.getScene();if(this._sharedData.animatedInputs){const e=n.getFrameId();if(this._animationFrame!==e){for(const e of this._sharedData.animatedInputs)e.animate(n);this._animationFrame=e}}if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new Di);const s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const r=n.getEngine();if(this._prepareDefinesForAttributes(e,s),this._sharedData.blockingBlocks.some((t=>!t.isReady(e,this,s,i))))return!1;const o=this._processDefines(e,s,i,t);if(o){const e=t.effect,i=s.toString();let a=r.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:o.mergedUniforms,uniformBuffersNames:o.uniformBuffers,samplers:o.mergedSamplers,defines:i,fallbacks:o.fallbacks,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:s.NUM_MORPH_INFLUENCERS}},r);if(a)if(this._onEffectCreatedObservable&&(Oi.effect=a,Oi.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Oi)),this.allowShaderHotSwapping&&e&&!a.isReady()){if(a=e,s.markAsUnprocessed(),o.lightDisposed)return s._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(a,s,this._materialContext)}return!(!t.effect||!t.effect.isReady())&&(s._renderId=n.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}get compiledShaders(){return`// Vertex shader\r\n${this._vertexCompilationState.compilationString}\r\n\r\n// Fragment shader\r\n${this._fragmentCompilationState.compilationString}`}bindOnlyWorldMatrix(e){const t=this.getScene();if(!this._activeEffect)return;const i=this._sharedData.hints;i.needWorldViewMatrix&&e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),i.needWorldViewProjectionMatrix&&e.multiplyToRef(t.getTransformMatrix(),this._cachedWorldViewProjectionMatrix);for(const n of this._sharedData.inputBlocks)n._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}bindForSubMesh(e,t,i){const n=this.getScene(),s=i.effect;if(!s)return;this._activeEffect=s,this.bindOnlyWorldMatrix(e);const r=this._mustRebind(n,s,t.visibility),o=this._sharedData;if(r){for(const e of o.bindableBlocks)e.bind(s,this,t,i);for(const e of o.forcedBindableBlocks)e.bind(s,this,t,i);for(const e of o.inputBlocks)e._transmit(s,n,this)}else if(!this.isFrozen)for(const a of o.forcedBindableBlocks)a.bind(s,this,t,i);this._afterBind(t,this._activeEffect)}getActiveTextures(){const e=super.getActiveTextures();return this._sharedData&&e.push(...this._sharedData.textureBlocks.filter((e=>e.texture)).map((e=>e.texture))),e}getTextureBlocks(){return this._sharedData?this._sharedData.textureBlocks:[]}getAllTextureBlocks(){const e=[];for(const t of this.attachedBlocks)Ni._BlockIsTextureBlock(t)&&e.push(t);return e}hasTexture(e){if(super.hasTexture(e))return!0;if(!this._sharedData)return!1;for(const t of this._sharedData.textureBlocks)if(t.texture===e)return!0;return!1}dispose(e,t,i){if(t)for(const n of this.getTextureBlocks().filter((e=>e.texture)).map((e=>e.texture)))n.dispose();for(const n of this.attachedBlocks)n.dispose();this.attachedBlocks.length=0,this._sharedData=null,this._vertexCompilationState=null,this._fragmentCompilationState=null,this.onBuildObservable.clear(),this._imageProcessingObserver&&(this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingObserver=null),super.dispose(e,t,i)}_createNodeEditor(e){const t=Object.assign({nodeMaterial:this},e);this.BJSNODEMATERIALEDITOR.NodeEditor.Show(t)}edit(e){return new Promise((t=>{if(this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),void 0===this.BJSNODEMATERIALEDITOR){const i=e&&e.editorURL?e.editorURL:Ni.EditorURL;se.w1.LoadScript(i,(()=>{this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),this._createNodeEditor(null==e?void 0:e.nodeEditorConfig),t()}))}else this._createNodeEditor(null==e?void 0:e.nodeEditorConfig),t()}))}clear(){this._vertexOutputNodes.length=0,this._fragmentOutputNodes.length=0,this.attachedBlocks.length=0}setToDefault(){this.clear(),this.editorData=null;const e=new Bt("Position");e.setAsAttribute("position");const t=new Bt("World");t.setAsSystemValue(Pt.World);const i=new Ct("WorldPos");e.connectTo(i),t.connectTo(i);const n=new Bt("ViewProjection");n.setAsSystemValue(Pt.ViewProjection);const s=new Ct("WorldPos * ViewProjectionTransform");i.connectTo(s),n.connectTo(s);const r=new yt("VertexOutput");s.connectTo(r);const o=new Bt("color");o.value=new a.HE(.8,.8,.8,1);const l=new Mt("FragmentOutput");o.connectTo(l),this.addOutputNode(r),this.addOutputNode(l),this._mode=qt.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;const e=new Bt("Position");e.setAsAttribute("position2d");const t=new Bt("Constant1");t.isConstant=!0,t.value=1;const i=new Jt("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const n=new yt("VertexOutput");i.connectTo(n);const s=new Bt("Scale");s.visibleInInspector=!0,s.value=new o.FM(1,1);const r=new ei("uv0");e.connectTo(r);const a=new ti("UV scale");r.connectTo(a),s.connectTo(a);const l=new Ut("CurrentScreen");a.connectTo(l),l.texture=new Le("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());const h=new Mt("FragmentOutput");l.connectTo(h,{output:"rgba"}),this.addOutputNode(n),this.addOutputNode(h),this._mode=qt.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;const e=new Bt("Position");e.setAsAttribute("position2d");const t=new Bt("Constant1");t.isConstant=!0,t.value=1;const i=new Jt("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});const n=new yt("VertexOutput");i.connectTo(n);const s=new Bt("Time");s.value=0,s.min=0,s.max=0,s.isBoolean=!1,s.matrixMode=0,s.animationType=Dt.Time,s.isConstant=!1;const r=new Bt("Color3");r.value=new a.Wo(1,1,1),r.isConstant=!1;const o=new Mt("FragmentOutput"),l=new Jt("VectorMerger");l.visibleInInspector=!1;const h=new Mi("Cos");h.operation=Ii.Cos,e.connectTo(l),s.output.connectTo(h.input),h.output.connectTo(l.z),l.xyzOut.connectTo(o.rgb),this.addOutputNode(n),this.addOutputNode(o),this._mode=qt.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;const e=new Bt("uv");e.setAsAttribute("particle_uv");const t=new Vt("ParticleTexture");e.connectTo(t);const i=new Bt("Color");i.setAsAttribute("particle_color");const n=new ti("Texture * Color");t.connectTo(n),i.connectTo(n);const s=new kt("ParticleRampGradient");n.connectTo(s);const r=new fi("ColorSplitter");i.connectTo(r);const o=new Gt("ParticleBlendMultiply");s.connectTo(o),t.connectTo(o,{output:"a"}),r.connectTo(o,{output:"a"});const a=new Mt("FragmentOutput");o.connectTo(a),this.addOutputNode(a),this._mode=qt.Particle}async loadAsync(e,t=""){return Ni.ParseFromFileAsync("",e,this.getScene(),t,!0,this)}_gatherBlocks(e,t){if(-1===t.indexOf(e)){t.push(e);for(const i of e.inputs){const n=i.connectedPoint;if(n){const i=n.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}}}generateCode(){let e=[];const t=[],i=["const","var","let"];for(const r of this._vertexOutputNodes)this._gatherBlocks(r,t);const n=[];for(const r of this._fragmentOutputNodes)this._gatherBlocks(r,n);let s=`var nodeMaterial = new BABYLON.NodeMaterial("${this.name||"node material"}");\r\n`;for(const r of t)r.isInput&&-1===e.indexOf(r)&&(s+=r._dumpCode(i,e));for(const r of n)r.isInput&&-1===e.indexOf(r)&&(s+=r._dumpCode(i,e));e=[],s+="\r\n// Connections\r\n";for(const r of this._vertexOutputNodes)s+=r._dumpCodeForOutputConnections(e);for(const r of this._fragmentOutputNodes)s+=r._dumpCodeForOutputConnections(e);s+="\r\n// Output nodes\r\n";for(const r of this._vertexOutputNodes)s+=`nodeMaterial.addOutputNode(${r._codeVariableName});\r\n`;for(const r of this._fragmentOutputNodes)s+=`nodeMaterial.addOutputNode(${r._codeVariableName});\r\n`;return s+="nodeMaterial.build();\r\n",s}serialize(e){const t=e?{}:E.p4.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];if(e)i=e;else{t.customType="BABYLON.NodeMaterial",t.outputNodes=[];for(const e of this._vertexOutputNodes)this._gatherBlocks(e,i),t.outputNodes.push(e.uniqueId);for(const e of this._fragmentOutputNodes)this._gatherBlocks(e,i),-1===t.outputNodes.indexOf(e.uniqueId)&&t.outputNodes.push(e.uniqueId)}t.blocks=[];for(const n of i)t.blocks.push(n.serialize());if(!e)for(const n of this.attachedBlocks)-1===i.indexOf(n)&&t.blocks.push(n.serialize());return t}_restoreConnections(e,t,i){for(const n of e.outputs)for(const s of t.blocks){const r=i[s.id];if(r)for(const o of s.inputs)if(i[o.targetBlockId]!==e||o.targetConnectionName!==n.name);else{const e=r.getInputByName(o.inputName);if(!e||e.isConnected)continue;n.connectTo(e,!0),this._restoreConnections(r,t,i)}}}parseSerializedObject(e,t="",i=!1){var n;i||this.clear();const s={};for(const r of e.blocks){const e=(0,l.q)(r.customType);if(e){const i=new e;i._deserialize(r,this.getScene(),t),s[r.id]=i,this.attachedBlocks.push(i)}}for(let r=0;rnew Ni(e,this.getScene(),this.options)),this);return n.id=e,n.name=e,n.parseSerializedObject(i),n._buildId=this._buildId,n.build(!1,!t),n}static Parse(e,t,i=""){const n=E.p4.Parse((()=>new Ni(e.name,t)),e,t,i);return n.parseSerializedObject(e,i),n.build(),n}static async ParseFromFileAsync(e,t,i,n="",s=!1,r){const o=null!=r?r:new Ni(e,i),a=await i._loadFileAsync(t),l=JSON.parse(a);return o.parseSerializedObject(l,n),s||o.build(),o}static ParseFromSnippetAsync(e,t=m.l.LastCreatedScene,i="",n,s=!1){return"_BLANK"===e?Promise.resolve(Ni.CreateDefault("blank",t)):new Promise(((r,o)=>{const a=new y.g;a.addEventListener("readystatechange",(()=>{if(4==a.readyState)if(200==a.status){const h=JSON.parse(JSON.parse(a.responseText).jsonPayload),c=JSON.parse(h.nodeMaterial);n||((n=E.p4.Parse((()=>new Ni(e,t)),c,t,i)).uniqueId=t.getUniqueId()),n.parseSerializedObject(c),n.snippetId=e;try{s||n.build(),r(n)}catch(l){o(l)}}else o("Unable to load the snippet "+e)})),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()}))}static CreateDefault(e,t){const i=new Ni(e,t);return i.setToDefault(),i.build(),i}}function Fi(e){const t=e.sideOrientation||Qe.x.DEFAULTSIDE,i=e.radius||1,n=void 0===e.flat||e.flat,s=e.subdivisions||4,r=e.radiusX||i,a=e.radiusY||i,l=e.radiusZ||i,h=(1+Math.sqrt(5))/2,c=[-1,h,-0,1,h,0,-1,-h,0,1,-h,0,0,-1,-h,0,1,-h,0,-1,h,0,1,h,h,0,1,h,0,-1,-h,0,1,-h,0,-1],d=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],u=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],p=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],f=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],_=new Array,m=new Array,g=new Array,v=new Array;let T=0;const S=new Array(3),E=new Array(3);let x;for(x=0;x<3;x++)S[x]=o.P.Zero(),E[x]=o.FM.Zero();for(let C=0;C<20;C++){for(x=0;x<3;x++){const e=d[3*C+x];S[x].copyFromFloats(c[3*u[e]],c[3*u[e]+1],c[3*u[e]+2]),S[x].normalize(),E[x].copyFromFloats(.134765625*p[2*e]+.05859375+-.0390625*f[C],.2333984375*p[2*e+1]+.025390625+.01953125*f[C])}const e=(e,t,i,h)=>{const c=o.P.Lerp(S[0],S[2],t/s),d=o.P.Lerp(S[1],S[2],t/s),u=s===t?S[2]:o.P.Lerp(c,d,e/(s-t));let p;if(u.normalize(),n){const e=o.P.Lerp(S[0],S[2],h/s),t=o.P.Lerp(S[1],S[2],h/s);p=o.P.Lerp(e,t,i/(s-h))}else p=new o.P(u.x,u.y,u.z);p.x/=r,p.y/=a,p.z/=l,p.normalize();const f=o.FM.Lerp(E[0],E[2],t/s),x=o.FM.Lerp(E[1],E[2],t/s),b=s===t?E[2]:o.FM.Lerp(f,x,e/(s-t));m.push(u.x*r,u.y*a,u.z*l),g.push(p.x,p.y,p.z),v.push(b.x,we.e.UseOpenGLOrientationForUV?1-b.y:b.y),_.push(T),T++};for(let t=0;twi(e,t,i),function(e){e.WRIST="wrist",e.THUMB="thumb",e.INDEX="index",e.MIDDLE="middle",e.RING="ring",e.LITTLE="little"}(Li||(Li={})),function(e){e.WRIST="wrist",e.THUMB_METACARPAL="thumb-metacarpal",e.THUMB_PHALANX_PROXIMAL="thumb-phalanx-proximal",e.THUMB_PHALANX_DISTAL="thumb-phalanx-distal",e.THUMB_TIP="thumb-tip",e.INDEX_FINGER_METACARPAL="index-finger-metacarpal",e.INDEX_FINGER_PHALANX_PROXIMAL="index-finger-phalanx-proximal",e.INDEX_FINGER_PHALANX_INTERMEDIATE="index-finger-phalanx-intermediate",e.INDEX_FINGER_PHALANX_DISTAL="index-finger-phalanx-distal",e.INDEX_FINGER_TIP="index-finger-tip",e.MIDDLE_FINGER_METACARPAL="middle-finger-metacarpal",e.MIDDLE_FINGER_PHALANX_PROXIMAL="middle-finger-phalanx-proximal",e.MIDDLE_FINGER_PHALANX_INTERMEDIATE="middle-finger-phalanx-intermediate",e.MIDDLE_FINGER_PHALANX_DISTAL="middle-finger-phalanx-distal",e.MIDDLE_FINGER_TIP="middle-finger-tip",e.RING_FINGER_METACARPAL="ring-finger-metacarpal",e.RING_FINGER_PHALANX_PROXIMAL="ring-finger-phalanx-proximal",e.RING_FINGER_PHALANX_INTERMEDIATE="ring-finger-phalanx-intermediate",e.RING_FINGER_PHALANX_DISTAL="ring-finger-phalanx-distal",e.RING_FINGER_TIP="ring-finger-tip",e.PINKY_FINGER_METACARPAL="pinky-finger-metacarpal",e.PINKY_FINGER_PHALANX_PROXIMAL="pinky-finger-phalanx-proximal",e.PINKY_FINGER_PHALANX_INTERMEDIATE="pinky-finger-phalanx-intermediate",e.PINKY_FINGER_PHALANX_DISTAL="pinky-finger-phalanx-distal",e.PINKY_FINGER_TIP="pinky-finger-tip"}(Bi||(Bi={}));const Ui=[Bi.WRIST,Bi.THUMB_METACARPAL,Bi.THUMB_PHALANX_PROXIMAL,Bi.THUMB_PHALANX_DISTAL,Bi.THUMB_TIP,Bi.INDEX_FINGER_METACARPAL,Bi.INDEX_FINGER_PHALANX_PROXIMAL,Bi.INDEX_FINGER_PHALANX_INTERMEDIATE,Bi.INDEX_FINGER_PHALANX_DISTAL,Bi.INDEX_FINGER_TIP,Bi.MIDDLE_FINGER_METACARPAL,Bi.MIDDLE_FINGER_PHALANX_PROXIMAL,Bi.MIDDLE_FINGER_PHALANX_INTERMEDIATE,Bi.MIDDLE_FINGER_PHALANX_DISTAL,Bi.MIDDLE_FINGER_TIP,Bi.RING_FINGER_METACARPAL,Bi.RING_FINGER_PHALANX_PROXIMAL,Bi.RING_FINGER_PHALANX_INTERMEDIATE,Bi.RING_FINGER_PHALANX_DISTAL,Bi.RING_FINGER_TIP,Bi.PINKY_FINGER_METACARPAL,Bi.PINKY_FINGER_PHALANX_PROXIMAL,Bi.PINKY_FINGER_PHALANX_INTERMEDIATE,Bi.PINKY_FINGER_PHALANX_DISTAL,Bi.PINKY_FINGER_TIP],Vi={[Li.WRIST]:[Bi.WRIST],[Li.THUMB]:[Bi.THUMB_METACARPAL,Bi.THUMB_PHALANX_PROXIMAL,Bi.THUMB_PHALANX_DISTAL,Bi.THUMB_TIP],[Li.INDEX]:[Bi.INDEX_FINGER_METACARPAL,Bi.INDEX_FINGER_PHALANX_PROXIMAL,Bi.INDEX_FINGER_PHALANX_INTERMEDIATE,Bi.INDEX_FINGER_PHALANX_DISTAL,Bi.INDEX_FINGER_TIP],[Li.MIDDLE]:[Bi.MIDDLE_FINGER_METACARPAL,Bi.MIDDLE_FINGER_PHALANX_PROXIMAL,Bi.MIDDLE_FINGER_PHALANX_INTERMEDIATE,Bi.MIDDLE_FINGER_PHALANX_DISTAL,Bi.MIDDLE_FINGER_TIP],[Li.RING]:[Bi.RING_FINGER_METACARPAL,Bi.RING_FINGER_PHALANX_PROXIMAL,Bi.RING_FINGER_PHALANX_INTERMEDIATE,Bi.RING_FINGER_PHALANX_DISTAL,Bi.RING_FINGER_TIP],[Li.LITTLE]:[Bi.PINKY_FINGER_METACARPAL,Bi.PINKY_FINGER_PHALANX_PROXIMAL,Bi.PINKY_FINGER_PHALANX_INTERMEDIATE,Bi.PINKY_FINGER_PHALANX_DISTAL,Bi.PINKY_FINGER_TIP]};class ki{get handMesh(){return this._handMesh}getHandPartMeshes(e){return Vi[e].map((e=>this._jointMeshes[Ui.indexOf(e)]))}getJointMesh(e){return this._jointMeshes[Ui.indexOf(e)]}constructor(e,t,i,n,s=!1,r=!1,a=1){this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=n,this._leftHandedMeshes=s,this._jointsInvisible=r,this._jointScaleFactor=a,this._jointTransforms=new Array(Ui.length),this._jointTransformMatrices=new Float32Array(16*Ui.length),this._tempJointMatrix=new o.y3,this._jointRadii=new Float32Array(Ui.length),this._scene=t[0].getScene();for(let l=0;l{e.rootMesh&&e.rootMesh.setEnabled(!1)}))),this.xrController.onMotionControllerInitObservable.add((e=>{e.onModelLoadedObservable.add((e=>{e.rootMesh&&e.rootMesh.setEnabled(!1)})),e.rootMesh&&e.rootMesh.setEnabled(!1)}))}setHandMesh(e,t){if(this._handMesh=e,e.alwaysSelectAsActiveMesh=!0,e.getChildMeshes().forEach((e=>e.alwaysSelectAsActiveMesh=!0)),this._handMesh.skeleton){const e=this._handMesh.skeleton;Ui.forEach(((i,n)=>{const s=e.getBoneIndexByName(t?t[i]:i);-1!==s&&e.bones[s].linkTransformNode(this._jointTransforms[n])}))}}updateFromXRFrame(e,t){const i=this.xrController.inputSource.hand;if(!i)return;const n=i,s=Ui.map((e=>n[e]||i.get(e)));let r=!1;if(e.fillPoses&&e.fillJointRadii)r=e.fillPoses(s,t,this._jointTransformMatrices)&&e.fillJointRadii(s,this._jointRadii);else if(e.getJointPose){r=!0;for(let i=0;i{const i=this._jointTransforms[t];o.y3.FromArrayToRef(this._jointTransformMatrices,16*t,this._tempJointMatrix),this._tempJointMatrix.decompose(void 0,i.rotationQuaternion,i.position);const n=this._jointRadii[t]*this._jointScaleFactor,s=this._jointMeshes[t];s.isVisible=!this._handMesh&&!this._jointsInvisible,s.position.copyFrom(i.position),s.rotationQuaternion.copyFrom(i.rotationQuaternion),s.scaling.setAll(n),this._scene.useRightHandedSystem||(s.position.z*=-1,s.rotationQuaternion.z*=-1,s.rotationQuaternion.w*=-1,this._leftHandedMeshes&&this._handMesh&&(i.position.z*=-1,i.rotationQuaternion.z*=-1,i.rotationQuaternion.w*=-1))})),this._handMesh&&(this._handMesh.isVisible=!0))}dispose(){this._handMesh&&(this._handMesh.isVisible=!1)}}class Gi extends nt{static _GenerateTrackedJointMeshes(e){const t={};return["left","right"].map((i=>{var n,s,r,a,l;const h=[],c=(null===(n=e.jointMeshes)||void 0===n?void 0:n.sourceMesh)||wi("jointParent",Gi._ICOSPHERE_PARAMS);c.isVisible=!!(null===(s=e.jointMeshes)||void 0===s?void 0:s.keepOriginalVisible);for(let t=0;t{var n,s,r,o,l;const h={};(null===(s=null===(n=Gi._RightHandGLB)||void 0===n?void 0:n.meshes[1])||void 0===s?void 0:s.isDisposed())&&(Gi._RightHandGLB=null),(null===(o=null===(r=Gi._LeftHandGLB)||void 0===r?void 0:r.meshes[1])||void 0===o?void 0:o.isDisposed())&&(Gi._LeftHandGLB=null);const c=!(!Gi._RightHandGLB||!Gi._LeftHandGLB),d=await Promise.all([Gi._RightHandGLB||ht.ImportMeshAsync("",Gi.DEFAULT_HAND_MODEL_BASE_URL,Gi.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),Gi._LeftHandGLB||ht.ImportMeshAsync("",Gi.DEFAULT_HAND_MODEL_BASE_URL,Gi.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)]);Gi._RightHandGLB=d[0],Gi._LeftHandGLB=d[1];const u=new Ni("handShader",e,{emitComments:!1});await u.loadAsync(Gi.DEFAULT_HAND_MODEL_SHADER_URL),u.needDepthPrePass=!0,u.transparencyMode=ut.F.MATERIAL_ALPHABLEND,u.alphaMode=2,u.build(!1);const p=Object.assign({base:a.Wo.FromInts(116,63,203),fresnel:a.Wo.FromInts(149,102,229),fingerColor:a.Wo.FromInts(177,130,255),tipFresnel:a.Wo.FromInts(220,200,255)},null===(l=null==t?void 0:t.handMeshes)||void 0===l?void 0:l.customColors),f={base:u.getBlockByName("baseColor"),fresnel:u.getBlockByName("fresnelColor"),fingerColor:u.getBlockByName("fingerColor"),tipFresnel:u.getBlockByName("tipFresnelColor")};f.base.value=p.base,f.fresnel.value=p.fresnel,f.fingerColor.value=p.fingerColor,f.tipFresnel.value=p.tipFresnel,["left","right"].forEach((t=>{const i="left"==t?Gi._LeftHandGLB:Gi._RightHandGLB;if(!i)throw new Error("Could not load hand model");const n=i.meshes[1];n._internalAbstractMeshDataInfo._computeBonesUsingShaders=!0,n.material=u.clone(`${t}HandShaderClone`,!0),n.isVisible=!1,h[t]=n,c||e.useRightHandedSystem||i.meshes[1].rotate(L.RD.Y,Math.PI)})),u.dispose(),i({left:h.left,right:h.right})}))}static _GenerateDefaultHandMeshRigMapping(e){const t="right"==e?"R":"L";return{[Bi.WRIST]:`wrist_${t}`,[Bi.THUMB_METACARPAL]:`thumb_metacarpal_${t}`,[Bi.THUMB_PHALANX_PROXIMAL]:`thumb_proxPhalanx_${t}`,[Bi.THUMB_PHALANX_DISTAL]:`thumb_distPhalanx_${t}`,[Bi.THUMB_TIP]:`thumb_tip_${t}`,[Bi.INDEX_FINGER_METACARPAL]:`index_metacarpal_${t}`,[Bi.INDEX_FINGER_PHALANX_PROXIMAL]:`index_proxPhalanx_${t}`,[Bi.INDEX_FINGER_PHALANX_INTERMEDIATE]:`index_intPhalanx_${t}`,[Bi.INDEX_FINGER_PHALANX_DISTAL]:`index_distPhalanx_${t}`,[Bi.INDEX_FINGER_TIP]:`index_tip_${t}`,[Bi.MIDDLE_FINGER_METACARPAL]:`middle_metacarpal_${t}`,[Bi.MIDDLE_FINGER_PHALANX_PROXIMAL]:`middle_proxPhalanx_${t}`,[Bi.MIDDLE_FINGER_PHALANX_INTERMEDIATE]:`middle_intPhalanx_${t}`,[Bi.MIDDLE_FINGER_PHALANX_DISTAL]:`middle_distPhalanx_${t}`,[Bi.MIDDLE_FINGER_TIP]:`middle_tip_${t}`,[Bi.RING_FINGER_METACARPAL]:`ring_metacarpal_${t}`,[Bi.RING_FINGER_PHALANX_PROXIMAL]:`ring_proxPhalanx_${t}`,[Bi.RING_FINGER_PHALANX_INTERMEDIATE]:`ring_intPhalanx_${t}`,[Bi.RING_FINGER_PHALANX_DISTAL]:`ring_distPhalanx_${t}`,[Bi.RING_FINGER_TIP]:`ring_tip_${t}`,[Bi.PINKY_FINGER_METACARPAL]:`little_metacarpal_${t}`,[Bi.PINKY_FINGER_PHALANX_PROXIMAL]:`little_proxPhalanx_${t}`,[Bi.PINKY_FINGER_PHALANX_INTERMEDIATE]:`little_intPhalanx_${t}`,[Bi.PINKY_FINGER_PHALANX_DISTAL]:`little_distPhalanx_${t}`,[Bi.PINKY_FINGER_TIP]:`little_tip_${t}`}}isCompatible(){return"undefined"!=typeof XRHand}getHandByControllerId(e){return this._attachedHands[e]}getHandByHandedness(e){return"none"==e?null:this._trackingHands[e]}constructor(e,t){super(e),this.options=t,this._attachedHands={},this._trackingHands={left:null,right:null},this._handResources={jointMeshes:null,handMeshes:null,rigMappings:null},this.onHandAddedObservable=new r.y$,this.onHandRemovedObservable=new r.y$,this._attachHand=e=>{var t,i,n;if(!e.inputSource.hand||"none"==e.inputSource.handedness||!this._handResources.jointMeshes)return;const s=e.inputSource.handedness,r=new ki(e,this._handResources.jointMeshes[s],this._handResources.handMeshes&&this._handResources.handMeshes[s],this._handResources.rigMappings&&this._handResources.rigMappings[s],null===(t=this.options.handMeshes)||void 0===t?void 0:t.meshesUseLeftHandedCoordinates,null===(i=this.options.jointMeshes)||void 0===i?void 0:i.invisible,null===(n=this.options.jointMeshes)||void 0===n?void 0:n.scaleFactor);this._attachedHands[e.uniqueId]=r,this._trackingHands[s]=r,this.onHandAddedObservable.notifyObservers(r)},this._detachHand=e=>{this._detachHandById(e.uniqueId)},this.xrNativeFeatureName="hand-tracking";const i=t.jointMeshes;if(i&&(void 0!==i.disableDefaultHandMesh&&(t.handMeshes=t.handMeshes||{},t.handMeshes.disableDefaultMeshes=i.disableDefaultHandMesh),void 0!==i.handMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.customMeshes=i.handMeshes),void 0!==i.leftHandedSystemMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.meshesUseLeftHandedCoordinates=i.leftHandedSystemMeshes),void 0!==i.rigMapping)){t.handMeshes=t.handMeshes||{};const e={},n={};[[i.rigMapping.left,e],[i.rigMapping.right,n]].forEach((e=>{const t=e[0],i=e[1];t.forEach(((e,t)=>{i[Ui[t]]=e}))})),t.handMeshes.customRigMappings={left:e,right:n}}}attach(){var e,t,i,n;return!!super.attach()&&(this._handResources={jointMeshes:Gi._GenerateTrackedJointMeshes(this.options),handMeshes:(null===(e=this.options.handMeshes)||void 0===e?void 0:e.customMeshes)||null,rigMappings:(null===(t=this.options.handMeshes)||void 0===t?void 0:t.customRigMappings)||null},(null===(i=this.options.handMeshes)||void 0===i?void 0:i.customMeshes)||(null===(n=this.options.handMeshes)||void 0===n?void 0:n.disableDefaultMeshes)||Gi._GenerateDefaultHandMeshesAsync(m.l.LastCreatedScene,this.options).then((e=>{var t,i;this._handResources.handMeshes=e,this._handResources.rigMappings={left:Gi._GenerateDefaultHandMeshRigMapping("left"),right:Gi._GenerateDefaultHandMeshRigMapping("right")},null===(t=this._trackingHands.left)||void 0===t||t.setHandMesh(this._handResources.handMeshes.left,this._handResources.rigMappings.left),null===(i=this._trackingHands.right)||void 0===i||i.setHandMesh(this._handResources.handMeshes.right,this._handResources.rigMappings.right)})),this.options.xrInput.controllers.forEach(this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerAddedObservable,this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerRemovedObservable,this._detachHand),!0)}_onXRFrame(e){var t,i;null===(t=this._trackingHands.left)||void 0===t||t.updateFromXRFrame(e,this._xrSessionManager.referenceSpace),null===(i=this._trackingHands.right)||void 0===i||i.updateFromXRFrame(e,this._xrSessionManager.referenceSpace)}_detachHandById(e){var t;const i=this.getHandByControllerId(e);if(i){const n="left"==i.xrController.inputSource.handedness?"left":"right";(null===(t=this._trackingHands[n])||void 0===t?void 0:t.xrController.uniqueId)===e&&(this._trackingHands[n]=null),this.onHandRemovedObservable.notifyObservers(i),i.dispose(),delete this._attachedHands[e]}}detach(){return!!super.detach()&&(Object.keys(this._attachedHands).forEach((e=>this._detachHandById(e))),!0)}dispose(){var e;super.dispose(),this.onHandAddedObservable.clear(),this.onHandRemovedObservable.clear(),this._handResources.handMeshes&&!(null===(e=this.options.handMeshes)||void 0===e?void 0:e.customMeshes)&&(this._handResources.handMeshes.left.dispose(),this._handResources.handMeshes.right.dispose(),Gi._RightHandGLB=null,Gi._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach((e=>e.dispose())),this._handResources.jointMeshes.right.forEach((e=>e.dispose())))}}var zi,Wi,Hi;Gi.Name=tt.HAND_TRACKING,Gi.Version=1,Gi.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/",Gi.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb",Gi.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb",Gi.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json",Gi._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2},Gi._RightHandGLB=null,Gi._LeftHandGLB=null,it.AddWebXRFeature(Gi.Name,((e,t)=>()=>new Gi(e,t)),Gi.Version,!1),function(e){e[e.ABOVE_FINGER_TIPS=0]="ABOVE_FINGER_TIPS",e[e.RADIAL_SIDE=1]="RADIAL_SIDE",e[e.ULNAR_SIDE=2]="ULNAR_SIDE",e[e.BELOW_WRIST=3]="BELOW_WRIST"}(zi||(zi={})),function(e){e[e.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",e[e.HAND_ROTATION=1]="HAND_ROTATION"}(Wi||(Wi={})),function(e){e[e.ALWAYS_VISIBLE=0]="ALWAYS_VISIBLE",e[e.PALM_UP=1]="PALM_UP",e[e.GAZE_FOCUS=2]="GAZE_FOCUS",e[e.PALM_AND_GAZE=3]="PALM_AND_GAZE"}(Hi||(Hi={}));class Xi{get maxAngle(){return this._maxAngle}set maxAngle(e){this._setMaxAngle(e)}constructor(e,t,i){this.targetPosition=o.P.Zero(),this.poleTargetPosition=o.P.Zero(),this.poleTargetLocalOffset=o.P.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=o._f.Identity(),this._bone1Mat=o.y3.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._rightHandedSystem=!1,this._bendAxis=o.P.Right(),this._slerping=!1,this._adjustRoll=0,this._notEnoughInformation=!1,this._bone2=t;const n=t.getParent();if(!n)return this._notEnoughInformation=!0,void p.Y.Error("BoneIKController: bone must have a parent for IK to work.");if(this._bone1=n,0===this._bone2.children.length&&!this._bone2.length)return this._notEnoughInformation=!0,void p.Y.Error("BoneIKController: bone must not be a leaf or it should have a length for IK to work.");this.mesh=e;const s=t.getPosition();if(t.getAbsoluteMatrix().determinant()>0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,s.x>s.y&&s.x>s.z&&(this._adjustRoll=.5*Math.PI,this._bendAxis.z=1)),this._bone1.length&&this._bone2.length){const e=this._bone1.getScale(),t=this._bone2.getScale();this._bone1Length=this._bone1.length*e.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y}else if(this._bone2.children[0]){e.computeWorldMatrix(!0);const t=this._bone2.children[0].getAbsolutePosition(e),i=this._bone2.getAbsolutePosition(e),n=this._bone1.getAbsolutePosition(e);this._bone2Length=o.P.Distance(t,i),this._bone1Length=o.P.Distance(i,n)}else{e.computeWorldMatrix(!0);const t=this._bone2.getScale();this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y;const i=this._bone2.getAbsolutePosition(e),n=this._bone1.getAbsolutePosition(e);this._bone1Length=o.P.Distance(i,n)}this._bone1.getRotationMatrixToRef(L.T.WORLD,e,this._bone1Mat),this.maxAngle=Math.PI,i&&(i.targetMesh&&(this.targetMesh=i.targetMesh,this.targetMesh.computeWorldMatrix(!0)),i.poleTargetMesh?(this.poleTargetMesh=i.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):i.poleTargetBone?this.poleTargetBone=i.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),i.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(i.poleTargetLocalOffset),i.poleAngle&&(this.poleAngle=i.poleAngle),i.bendAxis&&this._bendAxis.copyFrom(i.bendAxis),i.maxAngle&&(this.maxAngle=i.maxAngle),i.slerpAmount&&(this.slerpAmount=i.slerpAmount))}_setMaxAngle(e){e<0&&(e=0),(e>Math.PI||null==e)&&(e=Math.PI),this._maxAngle=e;const t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))}update(){if(this._notEnoughInformation)return;const e=this.targetPosition,t=this.poleTargetPosition,i=Xi._TmpMats[0],n=Xi._TmpMats[1];this.targetMesh&&e.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,t):this.poleTargetMesh&&o.P.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),t);const s=Xi._TmpVecs[0],r=Xi._TmpVecs[1],a=Xi._TmpVecs[2],l=Xi._TmpVecs[3],h=Xi._TmpVecs[4],c=Xi._TmpQuat;this._bone1.getAbsolutePositionToRef(this.mesh,s),t.subtractToRef(s,h),0==h.x&&0==h.y&&0==h.z?h.y=1:h.normalize(),e.subtractToRef(s,l),l.normalize(),o.P.CrossToRef(l,h,r),r.normalize(),o.P.CrossToRef(l,r,a),a.normalize(),o.y3.FromXYZAxesToRef(a,l,r,i);const d=this._bone1Length,u=this._bone2Length;let p=o.P.Distance(s,e);this._maxReach>0&&(p=Math.min(this._maxReach,p));let f=(u*u+p*p-d*d)/(2*u*p),_=(p*p+d*d-u*u)/(2*p*d);f>1&&(f=1),_>1&&(_=1),f<-1&&(f=-1),_<-1&&(_=-1);const m=Math.acos(f),g=Math.acos(_);let v=-m-g;if(this._rightHandedSystem)o.y3.RotationYawPitchRollToRef(0,0,this._adjustRoll,n),n.multiplyToRef(i,i),o.y3.RotationAxisToRef(this._bendAxis,g,n),n.multiplyToRef(i,i);else{const e=Xi._TmpVecs[5];e.copyFrom(this._bendAxis),e.x*=-1,o.y3.RotationAxisToRef(e,-g,n),n.multiplyToRef(i,i)}this.poleAngle&&(o.y3.RotationAxisToRef(l,this.poleAngle,n),i.multiplyToRef(n,i)),this._bone1&&(this.slerpAmount<1?(this._slerping||o._f.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),o._f.FromRotationMatrixToRef(i,c),o._f.SlerpToRef(this._bone1Quat,c,this.slerpAmount,this._bone1Quat),v=this._bone2Ang*(1-this.slerpAmount)+v*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,L.T.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(i,L.T.WORLD,this.mesh),this._bone1Mat.copyFrom(i),this._slerping=!1),this._updateLinkedTransformRotation(this._bone1)),this._bone2.setAxisAngle(this._bendAxis,v,L.T.LOCAL),this._updateLinkedTransformRotation(this._bone2),this._bone2Ang=v}_updateLinkedTransformRotation(e){e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new o._f),e.getRotationQuaternionToRef(L.T.LOCAL,null,e._linkedTransformNode.rotationQuaternion))}}Xi._TmpVecs=[o.P.Zero(),o.P.Zero(),o.P.Zero(),o.P.Zero(),o.P.Zero(),o.P.Zero()],Xi._TmpQuat=o._f.Identity(),Xi._TmpMats=[o.y3.Identity(),o.y3.Identity()];class Yi{get minYaw(){return this._minYaw}set minYaw(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),null!=this._maxYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get maxYaw(){return this._maxYaw}set maxYaw(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),null!=this._minYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get minPitch(){return this._minPitch}set minPitch(e){this._minPitch=e,this._minPitchTan=Math.tan(e)}get maxPitch(){return this._maxPitch}set maxPitch(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)}constructor(e,t,i,n){if(this.upAxis=o.P.Up(),this.upAxisSpace=L.T.LOCAL,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=o._f.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=o.P.Forward(),this.useAbsoluteValueForYaw=!1,this.mesh=e,this.bone=t,this.target=i,n){if(n.adjustYaw&&(this.adjustYaw=n.adjustYaw),n.adjustPitch&&(this.adjustPitch=n.adjustPitch),n.adjustRoll&&(this.adjustRoll=n.adjustRoll),null!=n.maxYaw?this.maxYaw=n.maxYaw:this.maxYaw=Math.PI,null!=n.minYaw?this.minYaw=n.minYaw:this.minYaw=-Math.PI,null!=n.maxPitch?this.maxPitch=n.maxPitch:this.maxPitch=Math.PI,null!=n.minPitch?this.minPitch=n.minPitch:this.minPitch=-Math.PI,null!=n.slerpAmount&&(this.slerpAmount=n.slerpAmount),null!=n.upAxis&&(this.upAxis=n.upAxis),null!=n.upAxisSpace&&(this.upAxisSpace=n.upAxisSpace),null!=n.yawAxis||null!=n.pitchAxis){let e=L.RD.Y,t=L.RD.X;null!=n.yawAxis&&(e=n.yawAxis.clone(),e.normalize()),null!=n.pitchAxis&&(t=n.pitchAxis.clone(),t.normalize());const i=o.P.Cross(t,e);this._transformYawPitch=o.y3.Identity(),o.y3.FromXYZAxesToRef(t,e,i,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}void 0!==n.useAbsoluteValueForYaw&&(this.useAbsoluteValueForYaw=n.useAbsoluteValueForYaw)}t.getParent()||this.upAxisSpace!=L.T.BONE||(this.upAxisSpace=L.T.LOCAL)}update(){if(this.slerpAmount<1&&!this._firstFrameSkipped)return void(this._firstFrameSkipped=!0);const e=this.bone,t=Yi._TmpVecs[0];e.getAbsolutePositionToRef(this.mesh,t);let i=this.target;const n=Yi._TmpMats[0],s=Yi._TmpMats[1],r=this.mesh,a=e.getParent(),l=Yi._TmpVecs[1];l.copyFrom(this.upAxis),this.upAxisSpace==L.T.BONE&&a?(this._transformYawPitch&&o.P.TransformCoordinatesToRef(l,this._transformYawPitchInv,l),a.getDirectionToRef(l,this.mesh,l)):this.upAxisSpace==L.T.LOCAL&&(r.getDirectionToRef(l,l),1==r.scaling.x&&1==r.scaling.y&&1==r.scaling.z||l.normalize());let h=!1,c=!1;if(this._maxYaw==Math.PI&&this._minYaw==-Math.PI||(h=!0),this._maxPitch==Math.PI&&this._minPitch==-Math.PI||(c=!0),h||c){const e=Yi._TmpMats[2],n=Yi._TmpMats[3];if(this.upAxisSpace==L.T.BONE&&1==l.y&&a)a.getRotationMatrixToRef(L.T.WORLD,this.mesh,e);else if(this.upAxisSpace!=L.T.LOCAL||1!=l.y||a){let t=Yi._TmpVecs[2];t.copyFrom(this._fowardAxis),this._transformYawPitch&&o.P.TransformCoordinatesToRef(t,this._transformYawPitchInv,t),a?a.getDirectionToRef(t,this.mesh,t):r.getDirectionToRef(t,t);const i=o.P.Cross(l,t);i.normalize(),t=o.P.Cross(i,l),o.y3.FromXYZAxesToRef(i,l,t,e)}else e.copyFrom(r.getWorldMatrix());e.invertToRef(n);let s=null;if(c){const r=Yi._TmpVecs[3];i.subtractToRef(t,r),o.P.TransformCoordinatesToRef(r,n,r),s=Math.sqrt(r.x*r.x+r.z*r.z);const a=Math.atan2(r.y,s);let l=a;a>this._maxPitch?(r.y=this._maxPitchTan*s,l=this._maxPitch):athis._maxYaw||lMath.PI?this._isAngleBetween(a,this._maxYaw,this._midYawConstraint)?(r.z=this._maxYawCos*s,r.x=this._maxYawSin*s,h=this._maxYaw):this._isAngleBetween(a,this._midYawConstraint,this._minYaw)&&(r.z=this._minYawCos*s,r.x=this._minYawSin*s,h=this._minYaw):l>this._maxYaw?(r.z=this._maxYawCos*s,r.x=this._maxYawSin*s,a<0&&this.useAbsoluteValueForYaw&&(r.x*=-1),h=this._maxYaw):lMath.PI){const e=Yi._TmpVecs[8];e.copyFrom(L.RD.Z),this._transformYawPitch&&o.P.TransformCoordinatesToRef(e,this._transformYawPitchInv,e);const t=Yi._TmpMats[4];this._boneQuat.toRotationMatrix(t),this.mesh.getWorldMatrix().multiplyToRef(t,t),o.P.TransformCoordinatesToRef(e,t,e),o.P.TransformCoordinatesToRef(e,n,e);const i=Math.atan2(e.x,e.z);if(this._getAngleBetween(i,a)>this._getAngleBetween(i,this._midYawConstraint)){null==s&&(s=Math.sqrt(r.x*r.x+r.z*r.z));const e=this._getAngleBetween(i,this._maxYaw);this._getAngleBetween(i,this._minYaw)Math.PI?i-=2*Math.PI:i<-Math.PI&&(i+=2*Math.PI),i}_getAngleBetween(e,t){let i=0;return i=(e=(e%=2*Math.PI)<0?e+2*Math.PI:e)<(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)?t-e:e-t,i>Math.PI&&(i=2*Math.PI-i),i}_isAngleBetween(e,t,i){if(e=(e%=2*Math.PI)<0?e+2*Math.PI:e,(t=(t%=2*Math.PI)<0?t+2*Math.PI:t)<(i=(i%=2*Math.PI)<0?i+2*Math.PI:i)){if(e>t&&ei&&e0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter((e=>!e.getParent()))}getTransformMatrices(e){return this.needInitialSkinMatrix?(e._bonesTransformMatrices||this.prepare(),e._bonesTransformMatrices):(this._transformMatrices&&!this._isDirty||this.prepare(),this._transformMatrices)}getTransformMatrixTexture(e){return this.needInitialSkinMatrix&&e._transformMatrixTexture?e._transformMatrixTexture:this._transformMatrixTexture}getScene(){return this._scene}toString(e){let t=`Name: ${this.name}, nBones: ${this.bones.length}`;if(t+=`, nAnimationRanges: ${this._ranges?Object.keys(this._ranges).length:"none"}`,e){t+=", Ranges: {";let e=!0;for(const i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}getBoneIndexByName(e){for(let t=0,i=this.bones.length;t-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i0)for(const e of this.bones)if(e._linkedTransformNode){const t=e._linkedTransformNode;e.position=t.position,t.rotationQuaternion?e.rotationQuaternion=t.rotationQuaternion:e.rotation=t.rotation,e.scaling=t.scaling}if(this.needInitialSkinMatrix)for(const e of this._meshesWithPoseMatrix){const t=e.getPoseMatrix();let i=this._isDirty;if(e._bonesTransformMatrices&&e._bonesTransformMatrices.length===16*(this.bones.length+1)||(e._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)),i=!0),i){if(this._synchronizedWithMesh!==e){this._synchronizedWithMesh=e;for(const e of this.bones)if(!e.getParent()){e.getBindMatrix().multiplyToRef(t,o.jp.Matrix[1]),e._updateAbsoluteBindMatrices(o.jp.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=ze.CreateRGBATexture(e._bonesTransformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,1,1))}}this._computeTransformMatrices(e._bonesTransformMatrices,t),this.isUsingTextureForMatrices&&e._transformMatrixTexture&&e._transformMatrixTexture.update(e._bonesTransformMatrices)}}else{if(!this._isDirty)return;this._transformMatrices&&this._transformMatrices.length===16*(this.bones.length+1)||(this._transformMatrices=new Float32Array(16*(this.bones.length+1)),this.isUsingTextureForMatrices&&(this._transformMatrixTexture&&this._transformMatrixTexture.dispose(),this._transformMatrixTexture=ze.CreateRGBATexture(this._transformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,1,1))),this._computeTransformMatrices(this._transformMatrices,null),this.isUsingTextureForMatrices&&this._transformMatrixTexture&&this._transformMatrixTexture.update(this._transformMatrices)}this._isDirty=!1}getAnimatables(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(let e=0;e{t.animations.forEach((t=>{t.enableBlending=!0,t.blendingSpeed=e}))}))}dispose(){if(this._meshesWithPoseMatrix.length=0,this.getScene().stopAnimation(this),this.getScene().removeSkeleton(this),this._parentContainer){const e=this._parentContainer.skeletons.indexOf(this);e>-1&&this._parentContainer.skeletons.splice(e,1),this._parentContainer=null}this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null)}serialize(){var e;const t={};t.name=this.name,t.id=this.id,this.dimensionsAtRest&&(t.dimensionsAtRest=this.dimensionsAtRest.asArray()),t.bones=[],t.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let i=0;i0&&(r.animation=n.animations[0].serialize()),t.ranges=[];for(const e in this._ranges){const i=this._ranges[e];if(!i)continue;const n={};n.name=e,n.from=i.from,n.to=i.to,t.ranges.push(n)}}return t}static Parse(e,t){const i=new ji(e.name,e.id,t);let n;for(e.dimensionsAtRest&&(i.dimensionsAtRest=o.P.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix,n=0;n-1&&(r=i.bones[t.parentBoneIndex]);const a=t.rest?o.y3.FromArray(t.rest):null,l=new B(t.name,i,r,o.y3.FromArray(t.matrix),a,null,s);void 0!==t.id&&null!==t.id&&(l.id=t.id),t.length&&(l.length=t.length),t.metadata&&(l.metadata=t.metadata),t.animation&&l.animations.push(A.Parse(t.animation)),void 0!==t.linkedTransformNodeId&&null!==t.linkedTransformNodeId&&(i._hasWaitingData=!0,l._waitingTransformNodeId=t.linkedTransformNodeId)}if(e.ranges)for(n=0;n0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){const e=new Array,t=new Array(this.bones.length);for(let i=0;i{e.setCurrentPoseAsRest()}))}}var Ki=i(1545);class qi{constructor(e,t,i=3){this._engine=e,this._engine._storageBuffers.push(this),this._create(t,i)}_create(e,t){this._bufferSize=e,this._creationFlags=t,this._buffer=this._engine.createStorageBuffer(e,t)}_rebuild(){this._create(this._bufferSize,this._creationFlags)}getBuffer(){return this._buffer}update(e,t,i){this._buffer&&this._engine.updateStorageBuffer(this._buffer,e,t,i)}read(e,t,i){return this._engine.readFromStorageBuffer(this._buffer,e,t,i)}dispose(){const e=this._engine._storageBuffers,t=e.indexOf(this);-1!==t&&(e[t]=e[e.length-1],e.pop()),this._engine._releaseBuffer(this._buffer),this._buffer=null}}var $i=i(1318);class Qi{constructor(){this.wheelPrecisionX=3,this.wheelPrecisionY=3,this.wheelPrecisionZ=3,this.onChangedObservable=new r.y$,this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0,this._ffMultiplier=12,this._normalize=120}attachControl(e){e=se.w1.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==We.kD.POINTERWHEEL)return;const i=t.event,n=i.deltaMode===$i.G.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,We.kD.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null),this.onChangedObservable&&this.onChangedObservable.clear()}checkInputs(){this.onChangedObservable.notifyObservers({wheelDeltaX:this._wheelDeltaX,wheelDeltaY:this._wheelDeltaY,wheelDeltaZ:this._wheelDeltaZ}),this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0}getClassName(){return"BaseCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}(0,oe.gn)([(0,E.qC)()],Qi.prototype,"wheelPrecisionX",void 0),(0,oe.gn)([(0,E.qC)()],Qi.prototype,"wheelPrecisionY",void 0),(0,oe.gn)([(0,E.qC)()],Qi.prototype,"wheelPrecisionZ",void 0);class Zi{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=se.w1.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),i=t.getInputElement();let n=0,s=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=r=>{var o,a;const l=r.event,h="touch"===l.pointerType;if(t.isInVRExclusivePointerMode)return;if(r.type!==We.kD.POINTERMOVE&&-1===this.buttons.indexOf(l.button))return;const c=l.target;if(this._altKey=l.altKey,this._ctrlKey=l.ctrlKey,this._metaKey=l.metaKey,this._shiftKey=l.shiftKey,this._buttonsPressed=l.buttons,t.isPointerLock){const e=l.movementX,t=l.movementY;this.onTouch(null,e,t),this._pointA=null,this._pointB=null}else{if(r.type!==We.kD.POINTERDOWN&&h&&(null===(o=this._pointA)||void 0===o?void 0:o.pointerId)!==l.pointerId&&(null===(a=this._pointB)||void 0===a?void 0:a.pointerId)!==l.pointerId)return;if(r.type!==We.kD.POINTERDOWN||-1!==this._currentActiveButton&&!h)if(r.type===We.kD.POINTERDOUBLETAP)this.onDoubleTap(l.pointerType);else if(r.type!==We.kD.POINTERUP||this._currentActiveButton!==l.button&&!h){if(r.type===We.kD.POINTERMOVE)if(e||l.preventDefault(),this._pointA&&null===this._pointB){const e=l.clientX-this._pointA.x,t=l.clientY-this._pointA.y;this.onTouch(this._pointA,e,t),this._pointA.x=l.clientX,this._pointA.y=l.clientY}else if(this._pointA&&this._pointB){const e=this._pointA.pointerId===l.pointerId?this._pointA:this._pointB;e.x=l.clientX,e.y=l.clientY;const t=this._pointA.x-this._pointB.x,i=this._pointA.y-this._pointB.y,o=t*t+i*i,a={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:l.pointerId,type:r.type};this.onMultiTouch(this._pointA,this._pointB,n,o,s,a),s=a,n=o}}else{try{null==c||c.releasePointerCapture(l.pointerId)}catch(d){}h||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==l.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==l.pointerId?this._pointB=null:this._pointA=this._pointB=null,(0!==n||s)&&(this.onMultiTouch(this._pointA,this._pointB,n,0,s,null),n=0,s=null),this._currentActiveButton=-1,this.onButtonUp(l),e||l.preventDefault()}else{try{null==c||c.setPointerCapture(l.pointerId)}catch(d){}if(null===this._pointA)this._pointA={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType};else{if(null!==this._pointB)return;this._pointB={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType}}-1!==this._currentActiveButton||h||(this._currentActiveButton=l.button),this.onButtonDown(l),e||(l.preventDefault(),i&&i.focus())}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,We.kD.POINTERDOWN|We.kD.POINTERUP|We.kD.POINTERMOVE|We.kD.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,n=0,s=null,this.onLostFocus()},this._contextMenuBind=this.onContextMenu.bind(this),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);const r=this.camera.getScene().getEngine().getHostWindow();r&&se.w1.RegisterTopRootEvents(r,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&se.w1.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){const e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentActiveButton=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,i){}onMultiTouch(e,t,i,n,s,r){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}(0,oe.gn)([(0,E.qC)()],Zi.prototype,"buttons",void 0);var Ji={};class en{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){const t=e.getSimpleName();this.attached[t]?p.Y.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=!ce.V.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 i in this.attached){const e=this.attached[i],n=E.p4.Serialize(e);t[e.getClassName()]=n}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const e in t){const i=Ji[e];if(i){const n=t[e],s=E.p4.Parse((()=>new i),n,null);this.add(s)}}}else for(const i in this.attached){const t=Ji[this.attached[i].getClassName()];if(t){const n=E.p4.Parse((()=>new t),e,null);this.remove(this.attached[i]),this.add(n)}}}}class tn{get isConnected(){return this._isConnected}constructor(e,t,i,n=0,s=1,r=2,o=3){this.id=e,this.index=t,this.browserGamepad=i,this._leftStick={x:0,y:0},this._rightStick={x:0,y:0},this._isConnected=!0,this._invertLeftStickY=!1,this.type=tn.GAMEPAD,this._leftStickAxisX=n,this._leftStickAxisY=s,this._rightStickAxisX=r,this._rightStickAxisY=o,this.browserGamepad.axes.length>=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}onleftstickchanged(e){this._onleftstickchanged=e}onrightstickchanged(e){this._onrightstickchanged=e}get leftStick(){return this._leftStick}set leftStick(e){!this._onleftstickchanged||this._leftStick.x===e.x&&this._leftStick.y===e.y||this._onleftstickchanged(e),this._leftStick=e}get rightStick(){return this._rightStick}set rightStick(e){!this._onrightstickchanged||this._rightStick.x===e.x&&this._rightStick.y===e.y||this._onrightstickchanged(e),this._rightStick=e}update(){this._leftStick&&(this.leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]},this._invertLeftStickY&&(this.leftStick.y*=-1)),this._rightStick&&(this.rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}dispose(){}}tn.GAMEPAD=0,tn.GENERIC=1,tn.XBOX=2,tn.POSE_ENABLED=3,tn.DUALSHOCK=4;class nn extends tn{onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new r.y$,this.onButtonUpObservable=new r.y$,this.type=tn.GENERIC,this._buttons=new Array(i.buttons.length)}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}update(){super.update();for(let e=0;e{e.type!==tn.POSE_ENABLED&&(this.gamepad&&e.type!==tn.XBOX||(this.gamepad=e))})),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{this.gamepad===e&&(this.gamepad=null)})),this.gamepad=e.getGamepadByType(tn.XBOX)}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad){const e=this.camera,t=this.gamepad.rightStick;if(t){if(0!=t.x){const i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){const i=t.y/this.gamepadRotationSensibility*this._yAxisScale;0!=i&&Math.abs(i)>.005&&(e.inertialBetaOffset+=i)}}const i=this.gamepad.leftStick;if(i&&0!=i.y){const e=i.y/this.gamepadMoveSensibility;0!=e&&Math.abs(e)>.005&&(this.camera.inertialRadiusOffset-=e)}}}getClassName(){return"ArcRotateCameraGamepadInput"}getSimpleName(){return"gamepad"}}(0,oe.gn)([(0,E.qC)()],sn.prototype,"gamepadRotationSensibility",void 0),(0,oe.gn)([(0,E.qC)()],sn.prototype,"gamepadMoveSensibility",void 0),Ji.ArcRotateCameraGamepadInput=sn;var rn=i(6081);class on{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=se.w1.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===rn.OG.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;t0?n/(1+this.wheelDeltaPercentage):n*(1+this.wheelDeltaPercentage),i}attachControl(e){e=se.w1.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==We.kD.POINTERWHEEL)return;const i=t.event;let n=0;const s=i.deltaMode===$i.G.DOM_DELTA_LINE?40:1,r=-i.deltaY*s;if(this.customComputeDeltaFromMouseWheel)n=this.customComputeDeltaFromMouseWheel(r,this,i);else if(this.wheelDeltaPercentage){if(n=this._computeDeltaFromMouseWheelLegacyEvent(r,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=S.R.Clamp(e,0,Number.MAX_VALUE),n=this._computeDeltaFromMouseWheelLegacyEvent(r,e)}}else n=r/(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,We.kD.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=Me.J.FromPositionAndNormal(e.target,t)}_getPosition(){var e;const t=this.camera,i=t.getScene(),n=i.createPickingRay(i.pointerX,i.pointerY,o.y3.Identity(),t,!1);n.origin.x-=t.targetScreenOffset.x,n.origin.y-=t.targetScreenOffset.y;let s=0;return this._hitPlane&&(s=null!==(e=n.intersectsPlane(this._hitPlane))&&void 0!==e?e:0),n.origin.addInPlace(n.direction.scaleInPlace(s))}_zoomToMouse(e){var t,i;const n=this.camera,s=1-n.inertia;if(n.lowerRadiusLimit){const i=null!==(t=n.lowerRadiusLimit)&&void 0!==t?t:0;n.radius-(n.inertialRadiusOffset+e)/st&&(e=(n.radius-t)*s-n.inertialRadiusOffset)}const r=e/s/n.radius,a=this._getPosition(),l=o.jp.Vector3[6];a.subtractToRef(n.target,l),l.scaleInPlace(r),l.scaleInPlace(s),this._inertialPanning.addInPlace(l),n.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,n),this._isPinching=!0):this._computeMultiTouchPanning(s,r)):this.multiTouchPanning?this._computeMultiTouchPanning(s,r):this.pinchZoom&&this._computePinchZoom(i,n))}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton}onButtonUp(){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}}ln.MinimumRadiusForPinch=.001,(0,oe.gn)([(0,E.qC)()],ln.prototype,"buttons",void 0),(0,oe.gn)([(0,E.qC)()],ln.prototype,"angularSensibilityX",void 0),(0,oe.gn)([(0,E.qC)()],ln.prototype,"angularSensibilityY",void 0),(0,oe.gn)([(0,E.qC)()],ln.prototype,"pinchPrecision",void 0),(0,oe.gn)([(0,E.qC)()],ln.prototype,"pinchDeltaPercentage",void 0),(0,oe.gn)([(0,E.qC)()],ln.prototype,"useNaturalPinchZoom",void 0),(0,oe.gn)([(0,E.qC)()],ln.prototype,"pinchZoom",void 0),(0,oe.gn)([(0,E.qC)()],ln.prototype,"panningSensibility",void 0),(0,oe.gn)([(0,E.qC)()],ln.prototype,"multiTouchPanning",void 0),(0,oe.gn)([(0,E.qC)()],ln.prototype,"multiTouchPanAndZoom",void 0),Ji.ArcRotateCameraPointersInput=ln;class hn extends en{constructor(e){super(e)}addMouseWheel(){return this.add(new an),this}addPointers(){return this.add(new ln),this}addKeyboard(){return this.add(new on),this}}hn.prototype.addVRDeviceOrientation=function(){return this.add(new cn),this};class cn{constructor(){this.alphaCorrection=1,this.gammaCorrection=1,this._alpha=0,this._gamma=0,this._dirty=!1,this._deviceOrientationHandler=this._onOrientationEvent.bind(this)}attachControl(e){e=se.w1.BackCompatCameraNoPreventDefault(arguments),this.camera.attachControl(e);const t=this.camera.getScene().getEngine().getHostWindow();t&&("undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"===e?t.addEventListener("deviceorientation",this._deviceOrientationHandler):se.w1.Warn("Permission not granted.")})).catch((e=>{se.w1.Error(e)})):t.addEventListener("deviceorientation",this._deviceOrientationHandler))}_onOrientationEvent(e){null!==e.alpha&&(this._alpha=(0|+e.alpha)*this.alphaCorrection),null!==e.gamma&&(this._gamma=(0|+e.gamma)*this.gammaCorrection),this._dirty=!0}checkInputs(){this._dirty&&(this._dirty=!1,this._gamma<0&&(this._gamma=180+this._gamma),this.camera.alpha=-this._alpha/180*Math.PI%Math.PI*2,this.camera.beta=this._gamma/180*Math.PI)}detachControl(){window.removeEventListener("deviceorientation",this._deviceOrientationHandler)}getClassName(){return"ArcRotateCameraVRDeviceOrientationInput"}getSimpleName(){return"VRDeviceOrientation"}}Ji.ArcRotateCameraVRDeviceOrientationInput=cn;class dn{constructor(){this.keysForward=[87],this.keysBackward=[83],this.keysUp=[69],this.keysDown=[81],this.keysRight=[68],this.keysLeft=[65],this._keys=new Array}attachControl(e){e=se.w1.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const i=t.event;if(t.type===rn.OG.KEYDOWN){if(-1!==this.keysForward.indexOf(i.keyCode)||-1!==this.keysBackward.indexOf(i.keyCode)||-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)){-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),e||i.preventDefault()}}else if(-1!==this.keysForward.indexOf(i.keyCode)||-1!==this.keysBackward.indexOf(i.keyCode)||-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.preventDefault()}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}getClassName(){return"FlyCameraKeyboardInput"}_onLostFocus(){this._keys.length=0}getSimpleName(){return"keyboard"}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t{this._pointerInput(e)}),We.kD.POINTERDOWN|We.kD.POINTERUP|We.kD.POINTERMOVE),this._rollObserver=this.camera.getScene().onBeforeRenderObservable.add((()=>{this.camera.rollCorrect&&this.camera.restoreRoll(this.camera.rollCorrect)}))}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver),this._observer=null,this._rollObserver=null,this._previousPosition=null,this._noPreventDefault=void 0)}getClassName(){return"FlyCameraMouseInput"}getSimpleName(){return"mouse"}_pointerInput(e){const t=e.event,i=this.camera.getEngine();if(i.isInVRExclusivePointerMode)return;if(!this.touchEnabled&&"touch"===t.pointerType)return;if(e.type!==We.kD.POINTERMOVE&&-1===this.buttons.indexOf(t.button))return;const n=t.target;if(e.type===We.kD.POINTERDOWN){try{null==n||n.setPointerCapture(t.pointerId)}catch(t){}this._previousPosition={x:t.clientX,y:t.clientY},this.activeButton=t.button,this._noPreventDefault||(t.preventDefault(),this._element.focus()),i.isPointerLock&&this._onMouseMove(e.event)}else if(e.type===We.kD.POINTERUP){try{null==n||n.releasePointerCapture(t.pointerId)}catch(t){}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===We.kD.POINTERMOVE){if(!this._previousPosition)return void(i.isPointerLock&&this._onMouseMove(e.event));const n=t.clientX-this._previousPosition.x,s=t.clientY-this._previousPosition.y;this._rotateCamera(n,s),this._previousPosition={x:t.clientX,y:t.clientY},this._noPreventDefault||t.preventDefault()}}_onMouseMove(e){const t=this.camera.getEngine();if(!t.isPointerLock||t.isInVRExclusivePointerMode)return;const i=e.movementX,n=e.movementY;this._rotateCamera(i,n),this._previousPosition=null,this._noPreventDefault||e.preventDefault()}_rotateCamera(e,t){const i=this.camera;this.camera.getScene().useRightHandedSystem&&(e*=-1),i.parent&&i.parent._getWorldMatrixDeterminant()<0&&(e*=-1);const n=e/this.angularSensibility,s=t/this.angularSensibility,r=o._f.RotationYawPitchRoll(i.rotation.y,i.rotation.x,i.rotation.z);let a;if(this.buttonsPitch.some((e=>e===this.activeButton))&&(a=o._f.RotationAxis(L.RD.X,s),r.multiplyInPlace(a)),this.buttonsYaw.some((e=>e===this.activeButton))){a=o._f.RotationAxis(L.RD.Y,n),r.multiplyInPlace(a);const e=i.bankedTurnLimit+i._trackRoll;if(i.bankedTurn&&-ee===this.activeButton))&&(a=o._f.RotationAxis(L.RD.Z,-n),i._trackRoll-=n,r.multiplyInPlace(a)),r.toEulerAnglesToRef(i.rotation)}}(0,oe.gn)([(0,E.qC)()],un.prototype,"buttons",void 0),(0,oe.gn)([(0,E.qC)()],un.prototype,"angularSensibility",void 0),Ji.FlyCameraMouseInput=un;class pn{constructor(){this.keysHeightOffsetIncr=[38],this.keysHeightOffsetDecr=[40],this.keysHeightOffsetModifierAlt=!1,this.keysHeightOffsetModifierCtrl=!1,this.keysHeightOffsetModifierShift=!1,this.keysRotationOffsetIncr=[37],this.keysRotationOffsetDecr=[39],this.keysRotationOffsetModifierAlt=!1,this.keysRotationOffsetModifierCtrl=!1,this.keysRotationOffsetModifierShift=!1,this.keysRadiusIncr=[40],this.keysRadiusDecr=[38],this.keysRadiusModifierAlt=!0,this.keysRadiusModifierCtrl=!1,this.keysRadiusModifierShift=!1,this.heightSensibility=1,this.rotationSensibility=1,this.radiusSensibility=1,this._keys=new Array}attachControl(e){e=se.w1.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===rn.OG.KEYDOWN){if(this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,this._shiftPressed=i.shiftKey,-1!==this.keysHeightOffsetIncr.indexOf(i.keyCode)||-1!==this.keysHeightOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetIncr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRadiusIncr.indexOf(i.keyCode)||-1!==this.keysRadiusDecr.indexOf(i.keyCode)){-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault())}}else if(-1!==this.keysHeightOffsetIncr.indexOf(i.keyCode)||-1!==this.keysHeightOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetIncr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRadiusIncr.indexOf(i.keyCode)||-1!==this.keysRadiusDecr.indexOf(i.keyCode)){const t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),i.preventDefault&&(e||i.preventDefault())}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){this._onKeyboardObserver&&this._keys.forEach((e=>{-1!==this.keysHeightOffsetIncr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset+=this.heightSensibility:-1!==this.keysHeightOffsetDecr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset-=this.heightSensibility:-1!==this.keysRotationOffsetIncr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset+=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRotationOffsetDecr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset-=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRadiusIncr.indexOf(e)&&this._modifierRadius()?this.camera.radius+=this.radiusSensibility:-1!==this.keysRadiusDecr.indexOf(e)&&this._modifierRadius()&&(this.camera.radius-=this.radiusSensibility)}))}getClassName(){return"FollowCameraKeyboardMoveInput"}getSimpleName(){return"keyboard"}_modifierHeightOffset(){return this.keysHeightOffsetModifierAlt===this._altPressed&&this.keysHeightOffsetModifierCtrl===this._ctrlPressed&&this.keysHeightOffsetModifierShift===this._shiftPressed}_modifierRotationOffset(){return this.keysRotationOffsetModifierAlt===this._altPressed&&this.keysRotationOffsetModifierCtrl===this._ctrlPressed&&this.keysRotationOffsetModifierShift===this._shiftPressed}_modifierRadius(){return this.keysRadiusModifierAlt===this._altPressed&&this.keysRadiusModifierCtrl===this._ctrlPressed&&this.keysRadiusModifierShift===this._shiftPressed}}(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysHeightOffsetIncr",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysHeightOffsetDecr",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysHeightOffsetModifierAlt",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysHeightOffsetModifierCtrl",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysHeightOffsetModifierShift",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysRotationOffsetIncr",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysRotationOffsetDecr",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysRotationOffsetModifierAlt",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysRotationOffsetModifierCtrl",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysRotationOffsetModifierShift",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysRadiusIncr",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysRadiusDecr",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysRadiusModifierAlt",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysRadiusModifierCtrl",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"keysRadiusModifierShift",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"heightSensibility",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"rotationSensibility",void 0),(0,oe.gn)([(0,E.qC)()],pn.prototype,"radiusSensibility",void 0),Ji.FollowCameraKeyboardMoveInput=pn;class fn{constructor(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}attachControl(e){e=se.w1.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==We.kD.POINTERWHEEL)return;const i=t.event;let n=0;const s=Math.max(-1,Math.min(1,i.deltaY));this.wheelDeltaPercentage?(console.assert(this.axisControlRadius+this.axisControlHeight+this.axisControlRotation<=1,"wheelDeltaPercentage only usable when mouse wheel controls ONE axis. Currently enabled: axisControlRadius: "+this.axisControlRadius+", axisControlHeightOffset: "+this.axisControlHeight+", axisControlRotationOffset: "+this.axisControlRotation),this.axisControlRadius?n=.01*s*this.wheelDeltaPercentage*this.camera.radius:this.axisControlHeight?n=.01*s*this.wheelDeltaPercentage*this.camera.heightOffset:this.axisControlRotation&&(n=.01*s*this.wheelDeltaPercentage*this.camera.rotationOffset)):n=s*this.wheelPrecision,n&&(this.axisControlRadius?this.camera.radius+=n:this.axisControlHeight?this.camera.heightOffset-=n:this.axisControlRotation&&(this.camera.rotationOffset-=n)),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,We.kD.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}(0,oe.gn)([(0,E.qC)()],fn.prototype,"axisControlRadius",void 0),(0,oe.gn)([(0,E.qC)()],fn.prototype,"axisControlHeight",void 0),(0,oe.gn)([(0,E.qC)()],fn.prototype,"axisControlRotation",void 0),(0,oe.gn)([(0,E.qC)()],fn.prototype,"wheelPrecision",void 0),(0,oe.gn)([(0,E.qC)()],fn.prototype,"wheelDeltaPercentage",void 0),Ji.FollowCameraMouseWheelInput=fn;class _n extends Zi{constructor(){super(...arguments),this.angularSensibilityX=1,this.angularSensibilityY=1,this.pinchPrecision=1e4,this.pinchDeltaPercentage=0,this.axisXControlRadius=!1,this.axisXControlHeight=!1,this.axisXControlRotation=!0,this.axisYControlRadius=!1,this.axisYControlHeight=!0,this.axisYControlRotation=!1,this.axisPinchControlRadius=!0,this.axisPinchControlHeight=!1,this.axisPinchControlRotation=!1,this.warningEnable=!0,this._warningCounter=0}getClassName(){return"FollowCameraPointersInput"}onTouch(e,t,i){this._warning(),this.axisXControlRotation?this.camera.rotationOffset+=t/this.angularSensibilityX:this.axisYControlRotation&&(this.camera.rotationOffset+=i/this.angularSensibilityX),this.axisXControlHeight?this.camera.heightOffset+=t/this.angularSensibilityY:this.axisYControlHeight&&(this.camera.heightOffset+=i/this.angularSensibilityY),this.axisXControlRadius?this.camera.radius-=t/this.angularSensibilityY:this.axisYControlRadius&&(this.camera.radius-=i/this.angularSensibilityY)}onMultiTouch(e,t,i,n,s,r){if(0===i&&null===s)return;if(0===n&&null===r)return;let o=(n-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(o*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=o*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=o*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=o*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=o),this.axisPinchControlHeight&&(this.camera.heightOffset+=o),this.axisPinchControlRadius&&(this.camera.radius-=o))}_warning(){if(!this.warningEnable||this._warningCounter++%100!=0)return;const e="It probably only makes sense to control ONE camera property with each pointer axis. Set 'warningEnable = false' if you are sure. Currently enabled: ";console.assert(this.axisXControlRotation+this.axisXControlHeight+this.axisXControlRadius<=1,e+"axisXControlRotation: "+this.axisXControlRotation+", axisXControlHeight: "+this.axisXControlHeight+", axisXControlRadius: "+this.axisXControlRadius),console.assert(this.axisYControlRotation+this.axisYControlHeight+this.axisYControlRadius<=1,e+"axisYControlRotation: "+this.axisYControlRotation+", axisYControlHeight: "+this.axisYControlHeight+", axisYControlRadius: "+this.axisYControlRadius),console.assert(this.axisPinchControlRotation+this.axisPinchControlHeight+this.axisPinchControlRadius<=1,e+"axisPinchControlRotation: "+this.axisPinchControlRotation+", axisPinchControlHeight: "+this.axisPinchControlHeight+", axisPinchControlRadius: "+this.axisPinchControlRadius)}}(0,oe.gn)([(0,E.qC)()],_n.prototype,"angularSensibilityX",void 0),(0,oe.gn)([(0,E.qC)()],_n.prototype,"angularSensibilityY",void 0),(0,oe.gn)([(0,E.qC)()],_n.prototype,"pinchPrecision",void 0),(0,oe.gn)([(0,E.qC)()],_n.prototype,"pinchDeltaPercentage",void 0),(0,oe.gn)([(0,E.qC)()],_n.prototype,"axisXControlRadius",void 0),(0,oe.gn)([(0,E.qC)()],_n.prototype,"axisXControlHeight",void 0),(0,oe.gn)([(0,E.qC)()],_n.prototype,"axisXControlRotation",void 0),(0,oe.gn)([(0,E.qC)()],_n.prototype,"axisYControlRadius",void 0),(0,oe.gn)([(0,E.qC)()],_n.prototype,"axisYControlHeight",void 0),(0,oe.gn)([(0,E.qC)()],_n.prototype,"axisYControlRotation",void 0),(0,oe.gn)([(0,E.qC)()],_n.prototype,"axisPinchControlRadius",void 0),(0,oe.gn)([(0,E.qC)()],_n.prototype,"axisPinchControlHeight",void 0),(0,oe.gn)([(0,E.qC)()],_n.prototype,"axisPinchControlRotation",void 0),Ji.FollowCameraPointersInput=_n;class mn{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=se.w1.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===rn.OG.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{const s=n.event,r="touch"===s.pointerType;if(t.isInVRExclusivePointerMode)return;if(!this.touchEnabled&&r)return;if(n.type!==We.kD.POINTERMOVE&&-1===this.buttons.indexOf(s.button))return;const o=s.target;if(n.type===We.kD.POINTERDOWN){if(r&&-1!==this._activePointerId||!r&&-1!==this._currentActiveButton)return;this._activePointerId=s.pointerId;try{null==o||o.setPointerCapture(s.pointerId)}catch(a){}-1===this._currentActiveButton&&(this._currentActiveButton=s.button),this._previousPosition={x:s.clientX,y:s.clientY},e||(s.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(n.event)}else if(n.type===We.kD.POINTERUP){if(r&&this._activePointerId!==s.pointerId||!r&&this._currentActiveButton!==s.button)return;try{null==o||o.releasePointerCapture(s.pointerId)}catch(a){}this._currentActiveButton=-1,this._previousPosition=null,e||s.preventDefault(),this._activePointerId=-1}else if(n.type===We.kD.POINTERMOVE&&(this._activePointerId===s.pointerId||!r))if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(n.event);else if(this._previousPosition){let t=s.clientX-this._previousPosition.x;const i=s.clientY-this._previousPosition.y;this.camera.getScene().useRightHandedSystem&&(t*=-1),this.camera.parent&&this.camera.parent._getWorldMatrixDeterminant()<0&&(t*=-1),this._allowCameraRotation&&(this.camera.cameraRotation.y+=t/this.angularSensibility,this.camera.cameraRotation.x+=i/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:t,offsetY:i}),this._previousPosition={x:s.clientX,y:s.clientY},e||s.preventDefault()}}),this._onMouseMove=i=>{if(!t.isPointerLock)return;if(t.isInVRExclusivePointerMode)return;let n=i.movementX;this.camera.getScene().useRightHandedSystem&&(n*=-1),this.camera.parent&&this.camera.parent._getWorldMatrixDeterminant()<0&&(n*=-1),this.camera.cameraRotation.y+=n/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,We.kD.POINTERDOWN|We.kD.POINTERUP|We.kD.POINTERMOVE),i&&(this._contextMenuBind=this.onContextMenu.bind(this),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._currentActiveButton=-1}getClassName(){return"FreeCameraMouseInput"}getSimpleName(){return"mouse"}}var vn;(0,oe.gn)([(0,E.qC)()],gn.prototype,"buttons",void 0),(0,oe.gn)([(0,E.qC)()],gn.prototype,"angularSensibility",void 0),Ji.FreeCameraMouseInput=gn,function(e){e[e.MoveRelative=0]="MoveRelative",e[e.RotateRelative=1]="RotateRelative",e[e.MoveScene=2]="MoveScene"}(vn||(vn={}));class Tn extends Qi{constructor(){super(...arguments),this._moveRelative=o.P.Zero(),this._rotateRelative=o.P.Zero(),this._moveScene=o.P.Zero(),this._wheelXAction=vn.MoveRelative,this._wheelXActionCoordinate=L.c7.X,this._wheelYAction=vn.MoveRelative,this._wheelYActionCoordinate=L.c7.Z,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){null===e&&this._wheelXAction!==vn.MoveRelative||(this._wheelXAction=vn.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==vn.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){null===e&&this._wheelYAction!==vn.MoveRelative||(this._wheelYAction=vn.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==vn.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){null===e&&this._wheelZAction!==vn.MoveRelative||(this._wheelZAction=vn.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==vn.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){null===e&&this._wheelXAction!==vn.RotateRelative||(this._wheelXAction=vn.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==vn.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){null===e&&this._wheelYAction!==vn.RotateRelative||(this._wheelYAction=vn.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==vn.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){null===e&&this._wheelZAction!==vn.RotateRelative||(this._wheelZAction=vn.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==vn.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){null===e&&this._wheelXAction!==vn.MoveScene||(this._wheelXAction=vn.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==vn.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){null===e&&this._wheelYAction!==vn.MoveScene||(this._wheelYAction=vn.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==vn.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){null===e&&this._wheelZAction!==vn.MoveScene||(this._wheelZAction=vn.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==vn.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=o.y3.Zero();this.camera.getViewMatrix().invertToRef(e);const t=o.P.Zero();o.P.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 vn.MoveRelative:n=this._moveRelative;break;case vn.RotateRelative:n=this._rotateRelative;break;case vn.MoveScene:n=this._moveScene}switch(i){case L.c7.X:n.set(e,0,0);break;case L.c7.Y:n.set(0,e,0);break;case L.c7.Z:n.set(0,0,e)}}}(0,oe.gn)([(0,E.qC)()],Tn.prototype,"wheelXMoveRelative",null),(0,oe.gn)([(0,E.qC)()],Tn.prototype,"wheelYMoveRelative",null),(0,oe.gn)([(0,E.qC)()],Tn.prototype,"wheelZMoveRelative",null),(0,oe.gn)([(0,E.qC)()],Tn.prototype,"wheelXRotateRelative",null),(0,oe.gn)([(0,E.qC)()],Tn.prototype,"wheelYRotateRelative",null),(0,oe.gn)([(0,E.qC)()],Tn.prototype,"wheelZRotateRelative",null),(0,oe.gn)([(0,E.qC)()],Tn.prototype,"wheelXMoveScene",null),(0,oe.gn)([(0,E.qC)()],Tn.prototype,"wheelYMoveScene",null),(0,oe.gn)([(0,E.qC)()],Tn.prototype,"wheelZMoveScene",null),Ji.FreeCameraMouseWheelInput=Tn;class Sn{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=se.w1.IsSafari()}attachControl(e){e=se.w1.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,s="mouse"===n.pointerType||this._isSafari&&void 0===n.pointerType;if(this.allowMouse||!s)if(i.type===We.kD.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===We.kD.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===We.kD.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,We.kD.POINTERDOWN|We.kD.POINTERUP|We.kD.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;e.cameraRotation.y=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 o.P(0,0,0!==this.touchMoveSensibility?t*this._offsetY/this.touchMoveSensibility:0);o.y3.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(o.P.TransformCoordinates(i,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}(0,oe.gn)([(0,E.qC)()],Sn.prototype,"touchAngularSensibility",void 0),(0,oe.gn)([(0,E.qC)()],Sn.prototype,"touchMoveSensibility",void 0),Ji.FreeCameraTouchInput=Sn;class En extends en{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new mn),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new gn(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new Tn,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new Sn),this}clear(){super.clear(),this._mouseInput=null}}En.prototype.addDeviceOrientation=function(e){return this._deviceOrientationInput||(this._deviceOrientationInput=new xn,e&&(this._deviceOrientationInput.smoothFactor=e),this.add(this._deviceOrientationInput)),this};class xn{static WaitForOrientationChangeAsync(e){return new Promise(((t,i)=>{let n=!1;const s=()=>{window.removeEventListener("deviceorientation",s),n=!0,t()};e&&setTimeout((()=>{n||(window.removeEventListener("deviceorientation",s),i("WaitForOrientationChangeAsync timed out"))}),e),"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"==e?window.addEventListener("deviceorientation",s):se.w1.Warn("Permission not granted.")})).catch((e=>{se.w1.Error(e)})):window.addEventListener("deviceorientation",s)}))}constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new o._f,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new r.y$,this._orientationChanged=()=>{this._screenOrientationAngle=void 0!==window.orientation?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,this._screenOrientationAngle=-se.w1.ToRadians(this._screenOrientationAngle/2),this._screenQuaternion.copyFromFloats(0,Math.sin(this._screenOrientationAngle),0,Math.cos(this._screenOrientationAngle))},this._deviceOrientation=e=>{this.smoothFactor?(this._alpha=null!==e.alpha?se.w1.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=null!==e.beta?se.w1.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=null!==e.gamma?se.w1.SmoothAngleChange(this._gamma,e.gamma,this.smoothFactor):0):(this._alpha=null!==e.alpha?e.alpha:0,this._beta=null!==e.beta?e.beta:0,this._gamma=null!==e.gamma?e.gamma:0),null!==e.alpha&&this._onDeviceOrientationChangedObservable.notifyObservers()},this._constantTranform=new o._f(-Math.sqrt(.5),0,0,Math.sqrt(.5)),this._orientationChanged()}get camera(){return this._camera}set camera(e){this._camera=e,null==this._camera||this._camera.rotationQuaternion||(this._camera.rotationQuaternion=new o._f),this._camera&&this._camera.onDisposeObservable.add((()=>{this._onDeviceOrientationChangedObservable.clear()}))}attachControl(){const e=this.camera.getScene().getEngine().getHostWindow();if(e){const t=()=>{e.addEventListener("orientationchange",this._orientationChanged),e.addEventListener("deviceorientation",this._deviceOrientation),this._orientationChanged()};"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then((e=>{"granted"===e?t():se.w1.Warn("Permission not granted.")})).catch((e=>{se.w1.Error(e)})):t()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){this._alpha&&(o._f.RotationYawPitchRollToRef(se.w1.ToRadians(this._alpha),se.w1.ToRadians(this._beta),-se.w1.ToRadians(this._gamma),this.camera.rotationQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform),this._camera.rotationQuaternion.z*=-1,this._camera.rotationQuaternion.w*=-1)}getClassName(){return"FreeCameraDeviceOrientationInput"}getSimpleName(){return"deviceOrientation"}}Ji.FreeCameraDeviceOrientationInput=xn;class bn{constructor(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=o.y3.Identity(),this._deltaTransform=o.P.Zero(),this._vector3=o.P.Zero(),this._vector2=o.FM.Zero()}get invertYAxis(){return 1!==this._yAxisScale}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){const e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add((e=>{e.type!==tn.POSE_ENABLED&&(this.gamepad&&e.type!==tn.XBOX||(this.gamepad=e))})),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{this.gamepad===e&&(this.gamepad=null)})),this.gamepad=e.getGamepadByType(tn.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad&&this.gamepad.leftStick){const e=this.camera,t=this.gamepad.leftStick;0!==this.gamepadMoveSensibility&&(t.x=Math.abs(t.x)>this.deadzoneDelta?t.x/this.gamepadMoveSensibility:0,t.y=Math.abs(t.y)>this.deadzoneDelta?t.y/this.gamepadMoveSensibility:0);let i=this.gamepad.rightStick;i&&0!==this.gamepadAngularSensibility?(i.x=Math.abs(i.x)>this.deadzoneDelta?i.x/this.gamepadAngularSensibility:0,i.y=(Math.abs(i.y)>this.deadzoneDelta?i.y/this.gamepadAngularSensibility:0)*this._yAxisScale):i={x:0,y:0},e.rotationQuaternion?e.rotationQuaternion.toRotationMatrix(this._cameraTransform):o.y3.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);const n=50*e._computeLocalCameraSpeed();this._vector3.copyFromFloats(t.x*n,0,-t.y*n),o.P.TransformCoordinatesToRef(this._vector3,this._cameraTransform,this._deltaTransform),e.cameraDirection.addInPlace(this._deltaTransform),this._vector2.copyFromFloats(i.y,i.x),e.cameraRotation.addInPlace(this._vector2)}}getClassName(){return"FreeCameraGamepadInput"}getSimpleName(){return"gamepad"}}(0,oe.gn)([(0,E.qC)()],bn.prototype,"gamepadAngularSensibility",void 0),(0,oe.gn)([(0,E.qC)()],bn.prototype,"gamepadMoveSensibility",void 0),Ji.FreeCameraGamepadInput=bn;var Cn,yn,An,Rn,Pn,In,Mn=i(5500);!function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(Cn||(Cn={}));class On{static _GetDefaultOptions(){return{puckSize:40,containerSize:60,color:"cyan",puckImage:void 0,containerImage:void 0,position:void 0,alwaysVisible:!1,limitToContainer:!1}}constructor(e,t){this._released=!1;const i=Object.assign(Object.assign({},On._GetDefaultOptions()),t);if(this._leftJoystick=!!e,On._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=Cn.X,this._axisTargetedByUpAndDown=Cn.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new Mn.x,this.deltaPosition=o.P.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{On._VJCanvasWidth=window.innerWidth,On._VJCanvasHeight=window.innerHeight,On.Canvas&&(On.Canvas.width=On._VJCanvasWidth,On.Canvas.height=On._VJCanvasHeight),On._HalfWidth=On._VJCanvasWidth/2},!On.Canvas){window.addEventListener("resize",this._onResize,!1),On.Canvas=document.createElement("canvas"),On._VJCanvasWidth=window.innerWidth,On._VJCanvasHeight=window.innerHeight,On.Canvas.width=window.innerWidth,On.Canvas.height=window.innerHeight,On.Canvas.style.width="100%",On.Canvas.style.height="100%",On.Canvas.style.position="absolute",On.Canvas.style.backgroundColor="transparent",On.Canvas.style.top="0px",On.Canvas.style.left="0px",On.Canvas.style.zIndex="5",On.Canvas.style.touchAction="none",On.Canvas.setAttribute("touch-action","none");const e=On.Canvas.getContext("2d");if(!e)throw new Error("Unable to create canvas for virtual joystick");On._VJCanvasContext=e,On._VJCanvasContext.strokeStyle="#ffffff",On._VJCanvasContext.lineWidth=2,document.body.appendChild(On.Canvas)}On._HalfWidth=On.Canvas.width/2,this.pressed=!1,this.limitToContainer=i.limitToContainer,this._joystickColor=i.color,this.containerSize=i.containerSize,this.puckSize=i.puckSize,i.position&&this.setPosition(i.position.x,i.position.y),i.puckImage&&this.setPuckImage(i.puckImage),i.containerImage&&this.setContainerImage(i.containerImage),i.alwaysVisible&&On._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new o.FM(0,0),this._joystickPreviousPointerPos=new o.FM(0,0),this._joystickPointerStartPos=new o.FM(0,0),this._deltaJoystickVector=new o.FM(0,0),this._onPointerDownHandlerRef=e=>{this._onPointerDown(e)},this._onPointerMoveHandlerRef=e=>{this._onPointerMove(e)},this._onPointerUpHandlerRef=e=>{this._onPointerUp(e)},On.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),On.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),On.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),On.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),On.Canvas.addEventListener("contextmenu",(e=>{e.preventDefault()}),!1),requestAnimationFrame((()=>{this._drawVirtualJoystick()}))}setJoystickSensibility(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)}_onPointerDown(e){let t;e.preventDefault(),t=!0===this._leftJoystick?e.clientXOn._HalfWidth,t&&this._joystickPointerId<0?(this._joystickPointerId=e.pointerId,this._joystickPosition?(this._joystickPointerStartPos=this._joystickPosition.clone(),this._joystickPointerPos=this._joystickPosition.clone(),this._joystickPreviousPointerPos=this._joystickPosition.clone(),this._onPointerMove(e)):(this._joystickPointerStartPos.x=e.clientX,this._joystickPointerStartPos.y=e.clientY,this._joystickPointerPos=this._joystickPointerStartPos.clone(),this._joystickPreviousPointerPos=this._joystickPointerStartPos.clone()),this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this.pressed=!0,this._touches.add(e.pointerId.toString(),e)):On._GlobalJoystickIndex<2&&this._action&&(this._action(),this._touches.add(e.pointerId.toString(),{x:e.clientX,y:e.clientY,prevX:e.clientX,prevY:e.clientY}))}_onPointerMove(e){if(this._joystickPointerId==e.pointerId){if(this.limitToContainer){const t=new o.FM(e.clientX-this._joystickPointerStartPos.x,e.clientY-this._joystickPointerStartPos.y),i=t.length();i>this.containerSize&&t.scaleInPlace(this.containerSize/i),this._joystickPointerPos.x=this._joystickPointerStartPos.x+t.x,this._joystickPointerPos.y=this._joystickPointerStartPos.y+t.y}else this._joystickPointerPos.x=e.clientX,this._joystickPointerPos.y=e.clientY;this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos),0this._containerImage=t}setPuckImage(e){const t=new Image;t.src=e,t.onload=()=>this._puckImage=t}_drawContainer(){const e=this._joystickPosition||this._joystickPointerStartPos;this._clearPreviousDraw(),this._containerImage?On._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,2*this.containerSize,2*this.containerSize):(On._VJCanvasContext.beginPath(),On._VJCanvasContext.strokeStyle=this._joystickColor,On._VJCanvasContext.lineWidth=2,On._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,2*Math.PI,!0),On._VJCanvasContext.stroke(),On._VJCanvasContext.closePath(),On._VJCanvasContext.beginPath(),On._VJCanvasContext.lineWidth=6,On._VJCanvasContext.strokeStyle=this._joystickColor,On._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,2*Math.PI,!0),On._VJCanvasContext.stroke(),On._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?On._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,2*this.puckSize,2*this.puckSize):(On._VJCanvasContext.beginPath(),On._VJCanvasContext.strokeStyle=this._joystickColor,On._VJCanvasContext.lineWidth=2,On._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,2*Math.PI,!0),On._VJCanvasContext.stroke(),On._VJCanvasContext.closePath())}_drawVirtualJoystick(){this._released||(this.alwaysVisible&&this._drawContainer(),this.pressed&&this._touches.forEach(((e,t)=>{t.pointerId===this._joystickPointerId?(this.alwaysVisible||this._drawContainer(),this._drawPuck(),this._joystickPreviousPointerPos=this._joystickPointerPos.clone()):(On._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),On._VJCanvasContext.beginPath(),On._VJCanvasContext.fillStyle="white",On._VJCanvasContext.beginPath(),On._VJCanvasContext.strokeStyle="red",On._VJCanvasContext.lineWidth=6,On._VJCanvasContext.arc(t.x,t.y,40,0,2*Math.PI,!0),On._VJCanvasContext.stroke(),On._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)})),requestAnimationFrame((()=>{this._drawVirtualJoystick()})))}releaseCanvas(){On.Canvas&&(On.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),On.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),On.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),On.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(On.Canvas),On.Canvas=null),this._released=!0}}On._GlobalJoystickIndex=0,On._AlwaysVisibleSticks=0,En.prototype.addVirtualJoystick=function(){return this.add(new Dn),this};class Dn{getLeftJoystick(){return this._leftjoystick}getRightJoystick(){return this._rightjoystick}checkInputs(){if(this._leftjoystick){const e=this.camera,t=50*e._computeLocalCameraSpeed(),i=o.y3.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),n=o.P.TransformCoordinates(new o.P(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(n),e.cameraRotation=e.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}}attachControl(){this._leftjoystick=new On(!0),this._leftjoystick.setAxisForUpDown(Cn.Z),this._leftjoystick.setAxisForLeftRight(Cn.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new On(!1),this._rightjoystick.setAxisForUpDown(Cn.X),this._rightjoystick.setAxisForLeftRight(Cn.Y),this._rightjoystick.reverseUpDown=!0,this._rightjoystick.setJoystickSensibility(.05),this._rightjoystick.setJoystickColor("yellow")}detachControl(){this._leftjoystick.releaseCanvas(),this._rightjoystick.releaseCanvas()}getClassName(){return"FreeCameraVirtualJoystickInput"}getSimpleName(){return"virtualJoystick"}}Ji.FreeCameraVirtualJoystickInput=Dn;class Nn extends ce.V{constructor(e,t,i,n=!0){super(e,t,i,n),this._tmpUpVector=o.P.Zero(),this._tmpTargetVector=o.P.Zero(),this.cameraDirection=new o.P(0,0,0),this.cameraRotation=new o.FM(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new o._f,this.rotation=new o.P(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=o.P.Zero(),this._initialFocalDistance=1,this._viewMatrix=o.y3.Zero(),this._camMatrix=o.y3.Zero(),this._cameraTransformMatrix=o.y3.Zero(),this._cameraRotationMatrix=o.y3.Zero(),this._referencePoint=new o.P(0,0,1),this._transformedReferencePoint=o.P.Zero(),this._defaultUp=o.P.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 o.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new o.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new o._f(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+=k.kn),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),o.y3.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&&o._f.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(o.jp.Matrix[0]),o.P.TransformNormalToRef(this.cameraDirection,o.jp.Matrix[0],o.jp.Vector3[0]),void this.position.addInPlace(o.jp.Vector3[0]);this.position.addInPlace(this.cameraDirection)}_checkInputs(){const e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=Math.abs(this.cameraRotation.x)>0||Math.abs(this.cameraRotation.y)>0;if(t&&this._updatePosition(),i){if(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this.rotation),this.rotation.x+=this.cameraRotation.x*e,this.rotation.y+=this.cameraRotation.y*e,!this.noRotationConstraint){const e=1.570796;this.rotation.x>e&&(this.rotation.x=e),this.rotation.x<-e&&(this.rotation.x=-e)}if(this.rotationQuaternion){this.rotation.lengthSquared()&&o._f.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)}}t&&(Math.abs(this.cameraDirection.x){(e=>{this._newPosition.copyFrom(e),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>fe.D.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&i&&this.onCollide(i))})(t)},this.inputs=new En(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=se.w1.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new o.P(0,0,0),this.cameraRotation=new o.FM(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?o.P.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=o.P.Zero(),this._transformedDirection=o.P.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FreeCamera"}}(0,oe.gn)([(0,E.hd)()],Fn.prototype,"ellipsoid",void 0),(0,oe.gn)([(0,E.hd)()],Fn.prototype,"ellipsoidOffset",void 0),(0,oe.gn)([(0,E.qC)()],Fn.prototype,"checkCollisions",void 0),(0,oe.gn)([(0,E.qC)()],Fn.prototype,"applyGravity",void 0),b.N.AddNodeConstructor("TouchCamera",((e,t)=>()=>new wn(e,o.P.Zero(),t)));class wn extends Fn{get touchAngularSensibility(){const e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0}set touchAngularSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)}get touchMoveSensibility(){const e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0}set touchMoveSensibility(e){const t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addTouch(),this._setupInputs()}getClassName(){return"TouchCamera"}_setupInputs(){const e=this.inputs.attached.touch,t=this.inputs.attached.mouse;t?t.touchEnabled=!1:e.allowMouse=!0}}b.N.AddNodeConstructor("ArcRotateCamera",((e,t)=>()=>new Ln(e,0,0,1,o.P.Zero(),t)));class Ln extends Nn{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 o.y3,this._upToYMatrix=new o.y3,this._upVector=o.P.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){o.y3.RotationAlignToRef(o.P.UpReadOnly,this._upVector,this._yToUpMatrix),o.y3.RotationAlignToRef(this._upVector,o.P.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 Xe,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 Ye,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 He,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,n,s,a,l=!0){super(e,o.P.Zero(),a,l),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.lowerAlphaLimit=null,this.upperAlphaLimit=null,this.lowerBetaLimit=.01,this.upperBetaLimit=Math.PI-.01,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.inertialPanningX=0,this.inertialPanningY=0,this.pinchToPanMaxDistance=20,this.panningDistanceLimit=null,this.panningOriginTarget=o.P.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=o.FM.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new o.y3,this.panningAxis=new o.P(1,1,0),this._transformedDirection=new o.P,this.mapPanning=!1,this.onMeshTargetChangedObservable=new r.y$,this.checkCollisions=!1,this.collisionRadius=new o.P(.5,.5,.5),this._previousPosition=o.P.Zero(),this._collisionVelocity=o.P.Zero(),this._newPosition=o.P.Zero(),this._computationVector=o.P.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),s=Math.sin(this.alpha),r=Math.cos(this.beta);let o=Math.sin(this.beta);0===o&&(o=1e-4);const a=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*n*o,this.radius*r,this.radius*s*o),a.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let l=this.upVector;this.allowUpsideDown&&this.beta<0&&(l=l.clone(),l=l.negate()),this._computeViewMatrix(this._position,a,l),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=o.P.Zero(),s&&this.setTarget(s),this.alpha=t,this.beta=i,this.radius=n,this.getViewMatrix(),this.inputs=new hn(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new o.P(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=o.FM.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!!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 s=arguments;t=se.w1.BackCompatCameraNoPreventDefault(s),this._useCtrlForPanning=i,this._panningMouseButton=n,"boolean"==typeof s[0]&&(s.length>1&&(this._useCtrlForPanning=s[1]),s.length>2&&(this._panningMouseButton=s[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){const e=this.invertRotation?-1:1;let t=this.inertialAlphaOffset;this.beta<=0&&(t*=-1),this.getScene().useRightHandedSystem&&(t*=-1),this.parent&&this.parent._getWorldMatrixDeterminant()<0&&(t*=-1),this.alpha+=t*e,this.beta+=this.inertialBetaOffset*e,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||o.P.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){var s;if(n=null!==(s=this.overrideCloneAlphaBetaRadius)&&void 0!==s?s:n,e.getBoundingInfo)this._targetBoundingCenter=t?e.getBoundingInfo().boundingBox.centerWorld.clone():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 s=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||o.P.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),s.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){const e=this.getScene().collisionCoordinator;this._collider||(this._collider=e.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,e.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let e=this.upVector;this.allowUpsideDown&&n<0&&(e=e.negate()),this._computeViewMatrix(this._position,s,e),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=s,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;const i=ee.Kj.MinMax(e),n=o.P.Distance(i.min,i.max);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=ee.Kj.MinMax(t),n=o.P.Distance(i.min,i.max)}else{i=e,n=e.distance}this._target=ee.Kj.Center(i),t||(this.maxZ=2*n)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case ce.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ce.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ce.V.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ce.V.RIG_MODE_STEREOSCOPIC_INTERLACED:case ce.V.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(0===t?1:-1);break;case ce.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(0===t?-1:1)}const n=new Ln(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 ce.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ce.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ce.V.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ce.V.RIG_MODE_STEREOSCOPIC_INTERLACED:case ce.V.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case ce.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}super._updateRigCameras()}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}(0,oe.gn)([(0,E.qC)()],Ln.prototype,"alpha",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"beta",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"radius",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"overrideCloneAlphaBetaRadius",void 0),(0,oe.gn)([(0,E.hd)("target")],Ln.prototype,"_target",void 0),(0,oe.gn)([(0,E.RR)("targetHost")],Ln.prototype,"_targetHost",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"inertialAlphaOffset",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"inertialBetaOffset",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"inertialRadiusOffset",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"lowerAlphaLimit",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"upperAlphaLimit",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"lowerBetaLimit",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"upperBetaLimit",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"lowerRadiusLimit",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"upperRadiusLimit",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"inertialPanningX",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"inertialPanningY",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"pinchToPanMaxDistance",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"panningDistanceLimit",void 0),(0,oe.gn)([(0,E.hd)()],Ln.prototype,"panningOriginTarget",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"panningInertia",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"zoomToMouseLocation",null),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"zoomOnFactor",void 0),(0,oe.gn)([(0,E.QC)()],Ln.prototype,"targetScreenOffset",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"allowUpsideDown",void 0),(0,oe.gn)([(0,E.qC)()],Ln.prototype,"useInputToRestoreState",void 0),b.N.AddNodeConstructor("DeviceOrientationCamera",((e,t)=>()=>new Bn(e,o.P.Zero(),t)));class Bn extends Fn{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new o._f,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new o._f,this.inputs.addDeviceOrientation(),this.inputs._deviceOrientationInput&&this.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce((()=>{this._disablePointerInputWhenUsingDeviceOrientation&&this.inputs._mouseInput&&(this.inputs._mouseInput._allowCameraRotation=!1,this.inputs._mouseInput.onPointerMovedObservable.add((e=>{0!=this._dragFactor&&(this._initialQuaternion||(this._initialQuaternion=new o._f),o._f.FromEulerAnglesToRef(0,e.offsetX*this._dragFactor,0,this._tmpDragQuaternion),this._initialQuaternion.multiplyToRef(this._tmpDragQuaternion,this._initialQuaternion))})))}))}get disablePointerInputWhenUsingDeviceOrientation(){return this._disablePointerInputWhenUsingDeviceOrientation}set disablePointerInputWhenUsingDeviceOrientation(e){this._disablePointerInputWhenUsingDeviceOrientation=e}enableHorizontalDragging(e=1/300){this._dragFactor=e}getClassName(){return"DeviceOrientationCamera"}_checkInputs(){super._checkInputs(),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}resetToCurrentRotation(e=L.RD.Y){this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new o._f),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach((t=>{e[t]?this._initialQuaternion[t]*=-1:this._initialQuaternion[t]=0})),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))}}class Un extends en{constructor(e){super(e)}addKeyboard(){return this.add(new dn),this}addMouse(){return this.add(new un),this}}class Vn extends Nn{get angularSensibility(){const e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){const t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysForward(){const e=this.inputs.attached.keyboard;return e?e.keysForward:[]}set keysForward(e){const t=this.inputs.attached.keyboard;t&&(t.keysForward=e)}get keysBackward(){const e=this.inputs.attached.keyboard;return e?e.keysBackward:[]}set keysBackward(e){const t=this.inputs.attached.keyboard;t&&(t.keysBackward=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}constructor(e,t,i,n=!0){super(e,t,i,n),this.ellipsoid=new o.P(1,1,1),this.ellipsoidOffset=new o.P(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this.cameraDirection=o.P.Zero(),this._trackRoll=0,this.rollCorrect=100,this.bankedTurn=!1,this.bankedTurnLimit=Math.PI/2,this.bankedTurnMultiplier=1,this._needMoveForGravity=!1,this._oldPosition=o.P.Zero(),this._diffPosition=o.P.Zero(),this._newPosition=o.P.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(e,t,i=null)=>{(e=>{this._newPosition.copyFrom(e),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>fe.D.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&i&&this.onCollide(i))})(t)},this.inputs=new Un(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=se.w1.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new o.P(0,0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?o.P.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=o.P.Zero(),this._transformedDirection=o.P.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}restoreRoll(e){const t=this._trackRoll,i=t-this.rotation.z;Math.abs(i)>=.001&&(this.rotation.z+=i/e,Math.abs(t-this.rotation.z)<=.001&&(this.rotation.z=t))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FlyCamera"}}(0,oe.gn)([(0,E.hd)()],Vn.prototype,"ellipsoid",void 0),(0,oe.gn)([(0,E.hd)()],Vn.prototype,"ellipsoidOffset",void 0),(0,oe.gn)([(0,E.qC)()],Vn.prototype,"checkCollisions",void 0),(0,oe.gn)([(0,E.qC)()],Vn.prototype,"applyGravity",void 0);class kn extends en{constructor(e){super(e)}addKeyboard(){return this.add(new pn),this}addMouseWheel(){return this.add(new fn),this}addPointers(){return this.add(new _n),this}addVRDeviceOrientation(){return console.warn("DeviceOrientation support not yet implemented for FollowCamera."),this}}b.N.AddNodeConstructor("FollowCamera",((e,t)=>()=>new Gn(e,o.P.Zero(),t))),b.N.AddNodeConstructor("ArcFollowCamera",((e,t)=>()=>new zn(e,0,0,1,null,t)));class Gn extends Nn{constructor(e,t,i,n=null){super(e,t,i),this.radius=12,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.rotationOffset=0,this.lowerRotationOffsetLimit=null,this.upperRotationOffsetLimit=null,this.heightOffset=4,this.lowerHeightOffsetLimit=null,this.upperHeightOffsetLimit=null,this.cameraAcceleration=.05,this.maxCameraSpeed=20,this.lockedTarget=n,this.inputs=new kn(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_follow(e){if(!e)return;const t=o.jp.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);const i=Math.atan2(t.m[8],t.m[10]),n=se.w1.ToRadians(this.rotationOffset)+i,s=e.getAbsolutePosition(),r=s.x+Math.sin(n)*this.radius,a=s.z+Math.cos(n)*this.radius,l=r-this.position.x,h=s.y+this.heightOffset-this.position.y,c=a-this.position.z;let d=l*this.cameraAcceleration*2,u=h*this.cameraAcceleration,p=c*this.cameraAcceleration*2;(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),(u>this.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<1?-this.maxCameraSpeed:this.maxCameraSpeed),(p>this.maxCameraSpeed||p<-this.maxCameraSpeed)&&(p=p<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new o.P(this.position.x+d,this.position.y+u,this.position.z+p),this.setTarget(s)}attachControl(e,t){t=se.w1.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t),this._reset=()=>{}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){this.inputs.checkInputs(),this._checkLimits(),super._checkInputs(),this.lockedTarget&&this._follow(this.lockedTarget)}_checkLimits(){null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),null!==this.lowerHeightOffsetLimit&&this.heightOffsetthis.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),null!==this.lowerRotationOffsetLimit&&this.rotationOffsetthis.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)}getClassName(){return"FollowCamera"}}(0,oe.gn)([(0,E.qC)()],Gn.prototype,"radius",void 0),(0,oe.gn)([(0,E.qC)()],Gn.prototype,"lowerRadiusLimit",void 0),(0,oe.gn)([(0,E.qC)()],Gn.prototype,"upperRadiusLimit",void 0),(0,oe.gn)([(0,E.qC)()],Gn.prototype,"rotationOffset",void 0),(0,oe.gn)([(0,E.qC)()],Gn.prototype,"lowerRotationOffsetLimit",void 0),(0,oe.gn)([(0,E.qC)()],Gn.prototype,"upperRotationOffsetLimit",void 0),(0,oe.gn)([(0,E.qC)()],Gn.prototype,"heightOffset",void 0),(0,oe.gn)([(0,E.qC)()],Gn.prototype,"lowerHeightOffsetLimit",void 0),(0,oe.gn)([(0,E.qC)()],Gn.prototype,"upperHeightOffsetLimit",void 0),(0,oe.gn)([(0,E.qC)()],Gn.prototype,"cameraAcceleration",void 0),(0,oe.gn)([(0,E.qC)()],Gn.prototype,"maxCameraSpeed",void 0),(0,oe.gn)([(0,E.RR)("lockedTargetId")],Gn.prototype,"lockedTarget",void 0);class zn extends Nn{constructor(e,t,i,n,s,r){super(e,o.P.Zero(),r),this.alpha=t,this.beta=i,this.radius=n,this._cartesianCoordinates=o.P.Zero(),this.setMeshTarget(s)}setMeshTarget(e){this._meshTarget=e,this._follow()}_follow(){if(!this._meshTarget)return;this._cartesianCoordinates.x=this.radius*Math.cos(this.alpha)*Math.cos(this.beta),this._cartesianCoordinates.y=this.radius*Math.sin(this.beta),this._cartesianCoordinates.z=this.radius*Math.sin(this.alpha)*Math.cos(this.beta);const e=this._meshTarget.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}_checkInputs(){super._checkInputs(),this._follow()}getClassName(){return"ArcFollowCamera"}}!function(e){e[e.VIVE=0]="VIVE",e[e.OCULUS=1]="OCULUS",e[e.WINDOWS=2]="WINDOWS",e[e.GEAR_VR=3]="GEAR_VR",e[e.DAYDREAM=4]="DAYDREAM",e[e.GENERIC=5]="GENERIC"}(yn||(yn={}));class Wn{static InitiateController(e){for(const t of this._ControllerFactories)if(t.canCreate(e))return t.create(e);if(this._DefaultControllerFactory)return this._DefaultControllerFactory(e);throw"The type of gamepad you are trying to load needs to be imported first or is not supported."}}Wn._ControllerFactories=[],Wn._DefaultControllerFactory=null;class Hn extends tn{_disableTrackPosition(e){this._trackPosition&&(this._calculatedPosition.copyFrom(e),this._trackPosition=!1)}constructor(e){super(e.id,e.index,e),this.isXR=!1,this._deviceRoomPosition=o.P.Zero(),this._deviceRoomRotationQuaternion=new o._f,this.devicePosition=o.P.Zero(),this.deviceRotationQuaternion=new o._f,this.deviceScaleFactor=1,this._trackPosition=!0,this._maxRotationDistFromHeadset=Math.PI/5,this._draggedRoomRotation=0,this._leftHandSystemQuaternion=new o._f,this._deviceToWorld=o.y3.Identity(),this._pointingPoseNode=null,this._workingMatrix=o.y3.Identity(),this._meshAttachedObservable=new r.y$,this.type=tn.POSE_ENABLED,this.controllerType=yn.GENERIC,this.position=o.P.Zero(),this.rotationQuaternion=new o._f,this._calculatedPosition=o.P.Zero(),this._calculatedRotation=new o._f,o._f.RotationYawPitchRollToRef(Math.PI,0,0,this._leftHandSystemQuaternion)}update(){super.update(),this._updatePoseAndMesh()}_updatePoseAndMesh(){if(this.isXR)return;const e=this.browserGamepad.pose;if(this.updateFromDevice(e),!this._trackPosition&&m.l.LastCreatedScene&&m.l.LastCreatedScene.activeCamera&&m.l.LastCreatedScene.activeCamera.devicePosition){const e=m.l.LastCreatedScene.activeCamera;if(e._computeDevicePosition(),this._deviceToWorld.setTranslation(e.devicePosition),e.deviceRotationQuaternion){e._deviceRoomRotationQuaternion.toEulerAnglesToRef(o.jp.Vector3[0]);const t=Math.atan2(Math.sin(o.jp.Vector3[0].y-this._draggedRoomRotation),Math.cos(o.jp.Vector3[0].y-this._draggedRoomRotation));if(Math.abs(t)>this._maxRotationDistFromHeadset){const e=t-(t<0?-this._maxRotationDistFromHeadset:this._maxRotationDistFromHeadset);this._draggedRoomRotation+=e;const i=Math.sin(-e),n=Math.cos(-e);this._calculatedPosition.x=this._calculatedPosition.x*n-this._calculatedPosition.z*i,this._calculatedPosition.z=this._calculatedPosition.x*i+this._calculatedPosition.z*n}}}o.P.TransformCoordinatesToRef(this._calculatedPosition,this._deviceToWorld,this.devicePosition),this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix),o._f.FromRotationMatrixToRef(this._workingMatrix,this.deviceRotationQuaternion),this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation),this._mesh&&(this._mesh.position.copyFrom(this.devicePosition),this._mesh.rotationQuaternion&&this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion))}updateFromDevice(e){if(!this.isXR&&e){this.rawPose=e,e.position&&(this._deviceRoomPosition.copyFromFloats(e.position[0],e.position[1],-e.position[2]),this._mesh&&this._mesh.getScene().useRightHandedSystem&&(this._deviceRoomPosition.z*=-1),this._trackPosition&&this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor,this._calculatedPosition),this._calculatedPosition.addInPlace(this.position));const t=this.rawPose;e.orientation&&t.orientation&&4===t.orientation.length&&(this._deviceRoomRotationQuaternion.copyFromFloats(t.orientation[0],t.orientation[1],-t.orientation[2],-t.orientation[3]),this._mesh&&(this._mesh.getScene().useRightHandedSystem?(this._deviceRoomRotationQuaternion.z*=-1,this._deviceRoomRotationQuaternion.w*=-1):this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion,this._deviceRoomRotationQuaternion)),this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion,this._calculatedRotation))}}attachToMesh(e){if(this._mesh&&(this._mesh.parent=null),this._mesh=e,this._poseControlledCamera&&(this._mesh.parent=this._poseControlledCamera),this._mesh.rotationQuaternion||(this._mesh.rotationQuaternion=new o._f),!this.isXR&&(this._updatePoseAndMesh(),this._pointingPoseNode)){const e=[];let t=this._pointingPoseNode;for(;t.parent;)e.push(t.parent),t=t.parent;e.reverse().forEach((e=>{e.computeWorldMatrix(!0)}))}this._meshAttachedObservable.notifyObservers(e)}attachToPoseControlledCamera(e){this._poseControlledCamera=e,this._mesh&&(this._mesh.parent=this._poseControlledCamera)}dispose(){this._mesh&&this._mesh.dispose(),this._mesh=null,super.dispose()}get mesh(){return this._mesh}getForwardRay(e=100){if(!this.mesh)return new qe(o.P.Zero(),new o.P(0,0,1),e);const t=this._pointingPoseNode?this._pointingPoseNode.getWorldMatrix():this.mesh.getWorldMatrix(),i=t.getTranslation(),n=new o.P(0,0,-1),s=o.P.TransformNormal(n,t),r=o.P.Normalize(s);return new qe(i,r,e)}}Hn.POINTING_POSE="POINTING_POSE",function(e){e[e.A=0]="A",e[e.B=1]="B",e[e.X=2]="X",e[e.Y=3]="Y",e[e.LB=4]="LB",e[e.RB=5]="RB",e[e.Back=8]="Back",e[e.Start=9]="Start",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(An||(An={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(Rn||(Rn={}));class Xn extends tn{constructor(e,t,i,n=!1){super(e,t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new r.y$,this.onButtonUpObservable=new r.y$,this.onPadDownObservable=new r.y$,this.onPadUpObservable=new r.y$,this._buttonA=0,this._buttonB=0,this._buttonX=0,this._buttonY=0,this._buttonBack=0,this._buttonStart=0,this._buttonLB=0,this._buttonRB=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this._isXboxOnePad=!1,this.type=tn.XBOX,this._isXboxOnePad=n}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonA(){return this._buttonA}set buttonA(e){this._buttonA=this._setButtonValue(e,this._buttonA,An.A)}get buttonB(){return this._buttonB}set buttonB(e){this._buttonB=this._setButtonValue(e,this._buttonB,An.B)}get buttonX(){return this._buttonX}set buttonX(e){this._buttonX=this._setButtonValue(e,this._buttonX,An.X)}get buttonY(){return this._buttonY}set buttonY(e){this._buttonY=this._setButtonValue(e,this._buttonY,An.Y)}get buttonStart(){return this._buttonStart}set buttonStart(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,An.Start)}get buttonBack(){return this._buttonBack}set buttonBack(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,An.Back)}get buttonLB(){return this._buttonLB}set buttonLB(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,An.LB)}get buttonRB(){return this._buttonRB}set buttonRB(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,An.RB)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,An.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,An.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Rn.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Rn.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Rn.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Rn.Right)}update(){super.update(),this._isXboxOnePad,this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonBack=this.browserGamepad.buttons[8].value,this.buttonStart=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}!function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.Share=8]="Share",e[e.Options=9]="Options",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"}(Pn||(Pn={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(In||(In={}));class Yn extends tn{constructor(e,t,i){super(e.replace("STANDARD GAMEPAD","SONY PLAYSTATION DUALSHOCK"),t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new r.y$,this.onButtonUpObservable=new r.y$,this.onPadDownObservable=new r.y$,this.onPadUpObservable=new r.y$,this._buttonCross=0,this._buttonCircle=0,this._buttonSquare=0,this._buttonTriangle=0,this._buttonShare=0,this._buttonOptions=0,this._buttonL1=0,this._buttonR1=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this.type=tn.DUALSHOCK}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonCross(){return this._buttonCross}set buttonCross(e){this._buttonCross=this._setButtonValue(e,this._buttonCross,Pn.Cross)}get buttonCircle(){return this._buttonCircle}set buttonCircle(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,Pn.Circle)}get buttonSquare(){return this._buttonSquare}set buttonSquare(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,Pn.Square)}get buttonTriangle(){return this._buttonTriangle}set buttonTriangle(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,Pn.Triangle)}get buttonOptions(){return this._buttonOptions}set buttonOptions(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,Pn.Options)}get buttonShare(){return this._buttonShare}set buttonShare(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,Pn.Share)}get buttonL1(){return this._buttonL1}set buttonL1(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,Pn.L1)}get buttonR1(){return this._buttonR1}set buttonR1(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,Pn.R1)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,Pn.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,Pn.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,In.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,In.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,In.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,In.Right)}update(){super.update(),this.buttonCross=this.browserGamepad.buttons[0].value,this.buttonCircle=this.browserGamepad.buttons[1].value,this.buttonSquare=this.browserGamepad.buttons[2].value,this.buttonTriangle=this.browserGamepad.buttons[3].value,this.buttonL1=this.browserGamepad.buttons[4].value,this.buttonR1=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonShare=this.browserGamepad.buttons[8].value,this.buttonOptions=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}class jn{constructor(e){if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new r.y$,(0,_e.CG)()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new r.y$((e=>{for(const t in this._babylonGamepads){const i=this._babylonGamepads[t];i&&i._isConnected&&this.onGamepadConnectedObservable.notifyObserver(e,i)}})),this._onGamepadConnectedEvent=e=>{const t=e.gamepad;if(t.index in this._babylonGamepads&&this._babylonGamepads[t.index].isConnected)return;let i;this._babylonGamepads[t.index]?(i=this._babylonGamepads[t.index],i.browserGamepad=t,i._isConnected=!0):i=this._addNewGamepad(t),this.onGamepadConnectedObservable.notifyObservers(i),this._startMonitoringGamepads()},this._onGamepadDisconnectedEvent=e=>{const t=e.gamepad;for(const i in this._babylonGamepads)if(this._babylonGamepads[i].index===t.index){const e=this._babylonGamepads[i];e._isConnected=!1,this.onGamepadDisconnectedObservable.notifyObservers(e),e.dispose&&e.dispose();break}},this._gamepadSupport)if(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported){const e=this._scene?this._scene.getEngine().getHostWindow():window;e&&(e.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),e.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1))}else this._startMonitoringGamepads()}get gamepads(){return this._babylonGamepads}getGamepadByType(e=tn.XBOX){for(const t of this._babylonGamepads)if(t&&t.type===e)return t;return null}dispose(){this._gamepadEventSupported&&(this._onGamepadConnectedEvent&&window.removeEventListener("gamepadconnected",this._onGamepadConnectedEvent),this._onGamepadDisconnectedEvent&&window.removeEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent),this._onGamepadConnectedEvent=null,this._onGamepadDisconnectedEvent=null),this._babylonGamepads.forEach((e=>{e.dispose()})),this.onGamepadConnectedObservable.clear(),this.onGamepadDisconnectedObservable.clear(),this._oneGamepadConnected=!1,this._stopMonitoringGamepads(),this._babylonGamepads=[]}_addNewGamepad(e){let t;this._oneGamepadConnected||(this._oneGamepadConnected=!0);const i=-1!==e.id.search("054c")&&-1===e.id.search("0ce6"),n=-1!==e.id.search("Xbox One");return t=n||-1!==e.id.search("Xbox 360")||-1!==e.id.search("xinput")||-1!==e.id.search("045e")&&-1===e.id.search("Surface Dock")?new Xn(e.id,e.index,e,n):i?new Yn(e.id,e.index,e):e.pose?Wn.InitiateController(e):new nn(e.id,e.index,e),this._babylonGamepads[t.index]=t,t}_startMonitoringGamepads(){this._isMonitoring||(this._isMonitoring=!0,this._checkGamepadsStatus())}_stopMonitoringGamepads(){this._isMonitoring=!1}_checkGamepadsStatus(){this._updateGamepadObjects();for(const t in this._babylonGamepads){const i=this._babylonGamepads[t];if(i&&i.isConnected)try{i.update()}catch(e){-1===this._loggedErrors.indexOf(i.index)&&(se.w1.Warn(`Error updating gamepad ${i.id}`),this._loggedErrors.push(i.index))}}this._isMonitoring&&fe.D.QueueNewFrame((()=>{this._checkGamepadsStatus()}))}_updateGamepadObjects(){const e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t()=>new qn(e,o.P.Zero(),t)));class qn extends wn{get gamepadAngularSensibility(){const e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0}set gamepadAngularSensibility(e){const t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)}get gamepadMoveSensibility(){const e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0}set gamepadMoveSensibility(e){const t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addGamepad()}getClassName(){return"UniversalCamera"}}ce.V._CreateDefaultParsedCamera=(e,t)=>new qn(e,o.P.Zero(),t),b.N.AddNodeConstructor("GamepadCamera",((e,t)=>()=>new $n(e,o.P.Zero(),t)));class $n extends qn{constructor(e,t,i){super(e,t,i)}getClassName(){return"GamepadCamera"}}const Qn="passCubePixelShader",Zn="varying vec2 vUV;\nuniform samplerCube textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\nvec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x));\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x));\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x));\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x));\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001));\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001));\n#endif\n}";Ht.v.ShadersStore[Qn]=Zn;class Jn extends Zt{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,n,s,r,o=0,a=!1){super(e,"pass",null,null,t,i,n,s,r,void 0,o,void 0,null,a)}static _Parse(e,t,i,n){return E.p4.Parse((()=>new Jn(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable)),e,i,n)}}(0,l.H)("BABYLON.PassPostProcess",Jn);fe.D._RescalePostProcessFactory=e=>new Jn("rescale",1,null,2,e,!1,0);const es="anaglyphPixelShader",ts="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}";Ht.v.ShadersStore[es]=ts;class is extends Zt{getClassName(){return"AnaglyphPostProcess"}constructor(e,t,i,n,s,r){super(e,"anaglyph",null,["leftSampler"],t,i[1],n,s,r),this._passedProcess=i[0]._rigPostProcess,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("leftSampler",this._passedProcess)}))}}function ns(e){e._rigCameras[0]._rigPostProcess=new Jn(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new is(e.name+"_anaglyph",1,e._rigCameras)}(0,l.H)("BABYLON.AnaglyphPostProcess",is),b.N.AddNodeConstructor("AnaglyphArcRotateCamera",((e,t,i)=>()=>new ss(e,0,0,1,o.P.Zero(),i.interaxial_distance,t)));class ss extends Ln{constructor(e,t,i,n,s,r,o){super(e,t,i,n,s,o),this._setRigMode=ns.bind(null,this),this.interaxialDistance=r,this.setCameraRigMode(ce.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:r})}getClassName(){return"AnaglyphArcRotateCamera"}}b.N.AddNodeConstructor("AnaglyphFreeCamera",((e,t,i)=>()=>new rs(e,o.P.Zero(),i.interaxial_distance,t)));class rs extends Fn{constructor(e,t,i,n){super(e,t,n),this._setRigMode=ns.bind(null,this),this.interaxialDistance=i,this.setCameraRigMode(ce.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphFreeCamera"}}b.N.AddNodeConstructor("AnaglyphGamepadCamera",((e,t,i)=>()=>new os(e,o.P.Zero(),i.interaxial_distance,t)));class os extends $n{constructor(e,t,i,n){super(e,t,n),this._setRigMode=ns.bind(null,this),this.interaxialDistance=i,this.setCameraRigMode(ce.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphGamepadCamera"}}b.N.AddNodeConstructor("AnaglyphUniversalCamera",((e,t,i)=>()=>new as(e,o.P.Zero(),i.interaxial_distance,t)));class as extends qn{constructor(e,t,i,n){super(e,t,n),this._setRigMode=ns.bind(null,this),this.interaxialDistance=i,this.setCameraRigMode(ce.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphUniversalCamera"}}const ls="stereoscopicInterlacePixelShader",hs="const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nbool useCamA;\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\nuseCamA=!useCamB;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\n#ifdef IS_STEREOSCOPIC_INTERLACED\nfloat rowNum=floor(vUV.y/stepSize.y);\nuseCamA=mod(rowNum,2.0)==1.0;\nuseCamB=mod(rowNum,2.0)==0.0;\ntexCoord1=vec2(vUV.x,vUV.y);\ntexCoord2=vec2(vUV.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\nuseCamA=!useCamB;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n#endif\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else if (useCamA){\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}else {\ndiscard;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}\n";Ht.v.ShadersStore[ls]=hs;class cs extends Zt{getClassName(){return"StereoscopicInterlacePostProcessI"}constructor(e,t,i,n,s,r,a){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],s,r,a,n?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new o.FM(1/this.width,1/this.height),this.onSizeChangedObservable.add((()=>{this._stepSize=new o.FM(1/this.width,1/this.height)})),this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("camASampler",this._passedProcess),e.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)}))}}function ds(e){const t=e.cameraRigMode===ce.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||e.cameraRigMode===ce.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,i=e.cameraRigMode===ce.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;e.cameraRigMode===ce.V.RIG_MODE_STEREOSCOPIC_INTERLACED?(e._rigCameras[0]._rigPostProcess=new Jn(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new cs(e.name+"_stereoInterlace",e._rigCameras,!1,!0)):(e._rigCameras[i?1:0].viewport=new Nt.l(0,0,t?.5:1,t?1:.5),e._rigCameras[i?0:1].viewport=new Nt.l(t?.5:0,t?0:.5,t?.5:1,t?1:.5))}b.N.AddNodeConstructor("StereoscopicArcRotateCamera",((e,t,i)=>()=>new us(e,0,0,1,o.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class us extends Ln{constructor(e,t,i,n,s,r,o,a){super(e,t,i,n,s,a),this._setRigMode=ds.bind(null,this),this.interaxialDistance=r,this.isStereoscopicSideBySide=o,this.setCameraRigMode(o?ce.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:ce.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:r})}getClassName(){return"StereoscopicArcRotateCamera"}}b.N.AddNodeConstructor("StereoscopicFreeCamera",((e,t,i)=>()=>new ps(e,o.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class ps extends Fn{constructor(e,t,i,n,s){super(e,t,s),this._setRigMode=ds.bind(null,this),this.interaxialDistance=i,this.isStereoscopicSideBySide=n,this.setCameraRigMode(n?ce.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:ce.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicFreeCamera"}}b.N.AddNodeConstructor("StereoscopicGamepadCamera",((e,t,i)=>()=>new fs(e,o.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class fs extends $n{constructor(e,t,i,n,s){super(e,t,s),this._setRigMode=ds.bind(null,this),this.interaxialDistance=i,this.isStereoscopicSideBySide=n,this.setCameraRigMode(n?ce.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:ce.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicGamepadCamera"}}b.N.AddNodeConstructor("StereoscopicFreeCamera",((e,t,i)=>()=>new _s(e,o.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t)));class _s extends qn{constructor(e,t,i,n,s){super(e,t,s),this._setRigMode=ds.bind(null,this),this.interaxialDistance=i,this.isStereoscopicSideBySide=n,this.setCameraRigMode(n?ce.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:ce.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicUniversalCamera"}}b.N.AddNodeConstructor("VirtualJoysticksCamera",((e,t)=>()=>new ms(e,o.P.Zero(),t)));class ms extends Fn{constructor(e,t,i){super(e,t,i),this.inputs.addVirtualJoystick()}getClassName(){return"VirtualJoysticksCamera"}}class gs{constructor(){this.compensateDistortion=!0,this.multiviewEnabled=!1}get aspectRatio(){return this.hResolution/(2*this.vResolution)}get aspectRatioFov(){return 2*Math.atan(this.postProcessScaleFactor*this.vScreenSize/(2*this.eyeToScreenDistance))}get leftHMatrix(){const e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return o.y3.Translation(e,0,0)}get rightHMatrix(){const e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return o.y3.Translation(-e,0,0)}get leftPreViewMatrix(){return o.y3.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return o.y3.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){const e=new gs;return e.hResolution=1280,e.vResolution=800,e.hScreenSize=.149759993,e.vScreenSize=.0935999975,e.vScreenCenter=.0467999987,e.eyeToScreenDistance=.0410000011,e.lensSeparationDistance=.063500002,e.interpupillaryDistance=.064000003,e.distortionK=[1,.219999999,.239999995,0],e.chromaAbCorrection=[.995999992,-.00400000019,1.01400006,0],e.postProcessScaleFactor=1.714605507808412,e.lensCenterOffset=.151976421,e}}const vs="vrDistortionCorrectionPixelShader",Ts="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}";Ht.v.ShadersStore[vs]=Ts;class Ss extends Zt{getClassName(){return"VRDistortionCorrectionPostProcess"}constructor(e,t,i,n){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,n.postProcessScaleFactor,t,Le.BILINEAR_SAMPLINGMODE),this._isRightEye=i,this._distortionFactors=n.distortionK,this._postProcessScaleFactor=n.postProcessScaleFactor,this._lensCenterOffset=n.lensCenterOffset,this.adaptScaleToCurrentViewport=!0,this.onSizeChangedObservable.add((()=>{this._scaleIn=new o.FM(2,2/this.aspectRatio),this._scaleFactor=new o.FM(1/this._postProcessScaleFactor*.5,1/this._postProcessScaleFactor*.5*this.aspectRatio),this._lensCenter=new o.FM(this._isRightEye?.5-.5*this._lensCenterOffset:.5+.5*this._lensCenterOffset,.5)})),this.onApplyObservable.add((e=>{e.setFloat2("LensCenter",this._lensCenter.x,this._lensCenter.y),e.setFloat2("Scale",this._scaleFactor.x,this._scaleFactor.y),e.setFloat2("ScaleIn",this._scaleIn.x,this._scaleIn.y),e.setFloat4("HmdWarpParam",this._distortionFactors[0],this._distortionFactors[1],this._distortionFactors[2],this._distortionFactors[3])}))}}const Es="vrMultiviewToSingleviewPixelShader",xs="precision mediump sampler2DArray;\nvarying vec2 vUV;\nuniform sampler2DArray multiviewSampler;\nuniform int imageIndex;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\ngl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));\n}";Ht.v.ShadersStore[Es]=xs;class bs extends Ci{set samples(e){this._samples=e}get samples(){return this._samples}constructor(e,t=512){super("multiview rtt",t,e,!1,!0,0,!1,void 0,!1,!1,!0,void 0,!0),this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight()),this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,this.samples=this._getEngine().getCaps().maxSamples||this.samples,this._texture.samples=this._samples}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindMultiviewFramebuffer(this._renderTarget)}getViewCount(){return 2}}function Cs(e,t){const i=new ae.M(e,void 0,!0,t);return i.addUniform("viewProjection",16),i.addUniform("viewProjectionR",16),i.addUniform("view",16),i.addUniform("projection",16),i.addUniform("vEyePosition",4),i}fe.D.prototype.createMultiviewRenderTargetTexture=function(e,t,i,n){const s=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";const r=this._createHardwareRenderTargetWrapper(!1,!1,{width:e,height:t});r._framebuffer=s.createFramebuffer();const o=new Be.l(this,Be.S.Unknown,!0);return o.width=e,o.height=t,o.isMultiview=!0,i||(i=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,i),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.RGBA8,e,t,2)),r._colorTextureArray=i,n||(n=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,n),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.DEPTH24_STENCIL8,e,t,2)),r._depthStencilTextureArray=n,o.isReady=!0,r.setTextures(o),r._depthStencilTexture=o,r},fe.D.prototype.bindMultiviewFramebuffer=function(e){const t=e,i=this._gl,n=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(t,void 0,void 0,void 0,!0),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),!t._colorTextureArray||!t._depthStencilTextureArray)throw"Invalid multiview frame buffer";this.getCaps().oculusMultiview?(n.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,t.samples,0,2),n.framebufferTextureMultisampleMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,t._depthStencilTextureArray,0,t.samples,0,2)):(n.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,0,2),n.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,t._depthStencilTextureArray,0,0,2))},fe.D.prototype.bindSpaceWarpFramebuffer=function(e){const t=e,i=this._gl,n=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(t,void 0,void 0,void 0,!0),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,t._framebuffer),!t._colorTextureArray||!t._depthStencilTextureArray)throw new Error("Invalid Space Warp framebuffer");n.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,t._colorTextureArray,0,0,2),n.framebufferTextureMultiviewOVR(i.DRAW_FRAMEBUFFER,i.DEPTH_ATTACHMENT,t._depthStencilTextureArray,0,0,2)},ce.V.prototype._useMultiviewToSingleView=!1,ce.V.prototype._multiviewTexture=null,ce.V.prototype._resizeOrCreateMultiviewTexture=function(e,t){this._multiviewTexture?this._multiviewTexture.getRenderWidth()==e&&this._multiviewTexture.getRenderHeight()==t||(this._multiviewTexture.dispose(),this._multiviewTexture=new bs(this.getScene(),{width:e,height:t})):this._multiviewTexture=new bs(this.getScene(),{width:e,height:t})};const ys=N.x.prototype.createSceneUniformBuffer;N.x.prototype._transformMatrixR=o.y3.Zero(),N.x.prototype._multiviewSceneUbo=null,N.x.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=Cs(this.getEngine(),"scene_multiview")},N.x.prototype.createSceneUniformBuffer=function(e){return this._multiviewSceneUbo?Cs(this.getEngine(),e):ys.bind(this)(e)},N.x.prototype._updateMultiviewUbo=function(e,t){e&&t&&e.multiplyToRef(t,this._transformMatrixR),e&&t&&(e.multiplyToRef(t,o.jp.Matrix[0]),Ot.i.GetRightPlaneToRef(o.jp.Matrix[0],this._frustumPlanes[3])),this._multiviewSceneUbo&&(this._multiviewSceneUbo.updateMatrix("viewProjection",this.getTransformMatrix()),this._multiviewSceneUbo.updateMatrix("viewProjectionR",this._transformMatrixR),this._multiviewSceneUbo.updateMatrix("view",this._viewMatrix),this._multiviewSceneUbo.updateMatrix("projection",this._projectionMatrix))},N.x.prototype._renderMultiviewToSingleView=function(e){e._resizeOrCreateMultiviewTexture(e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.width>0?e._rigPostProcess.width:this.getEngine().getRenderWidth(!0),e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.height>0?e._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),e.outputRenderTarget=e._multiviewTexture,this._renderForCamera(e),e.outputRenderTarget=null;for(let t=0;t{})),this.onApplyObservable.add((e=>{n._scene.activeCamera&&n._scene.activeCamera.isLeftCamera?e.setInt("imageIndex",0):e.setInt("imageIndex",1),e.setTexture("multiviewSampler",n._multiviewTexture)}))}}function Rs(e,t){const i=t.vrCameraMetrics||gs.GetDefault();e._rigCameras[0]._cameraRigParams.vrMetrics=i,e._rigCameras[0].viewport=new Nt.l(0,0,.5,1),e._rigCameras[0]._cameraRigParams.vrWorkMatrix=new o.y3,e._rigCameras[0]._cameraRigParams.vrHMatrix=i.leftHMatrix,e._rigCameras[0]._cameraRigParams.vrPreViewMatrix=i.leftPreViewMatrix,e._rigCameras[0].getProjectionMatrix=e._rigCameras[0]._getVRProjectionMatrix,e._rigCameras[1]._cameraRigParams.vrMetrics=i,e._rigCameras[1].viewport=new Nt.l(.5,0,.5,1),e._rigCameras[1]._cameraRigParams.vrWorkMatrix=new o.y3,e._rigCameras[1]._cameraRigParams.vrHMatrix=i.rightHMatrix,e._rigCameras[1]._cameraRigParams.vrPreViewMatrix=i.rightPreViewMatrix,e._rigCameras[1].getProjectionMatrix=e._rigCameras[1]._getVRProjectionMatrix,i.multiviewEnabled&&(e.getScene().getEngine().getCaps().multiview?(e._useMultiviewToSingleView=!0,e._rigPostProcess=new As("VRMultiviewToSingleview",e,i.postProcessScaleFactor)):(p.Y.Warn("Multiview is not supported, falling back to standard rendering"),i.multiviewEnabled=!1)),i.compensateDistortion&&(e._rigCameras[0]._rigPostProcess=new Ss("VR_Distort_Compensation_Left",e._rigCameras[0],!1,i),e._rigCameras[1]._rigPostProcess=new Ss("VR_Distort_Compensation_Right",e._rigCameras[1],!0,i))}b.N.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",((e,t)=>()=>new Ps(e,0,0,1,o.P.Zero(),t)));class Ps extends Ln{constructor(e,t,i,n,s,r,o=!0,a=gs.GetDefault()){super(e,t,i,n,s,r),this._setRigMode=Rs.bind(null,this),a.compensateDistortion=o,this.setCameraRigMode(ce.V.RIG_MODE_VR,{vrCameraMetrics:a}),this.inputs.addVRDeviceOrientation()}getClassName(){return"VRDeviceOrientationArcRotateCamera"}}b.N.AddNodeConstructor("VRDeviceOrientationFreeCamera",((e,t)=>()=>new Is(e,o.P.Zero(),t)));class Is extends Bn{constructor(e,t,i,n=!0,s=gs.GetDefault()){super(e,t,i),this._setRigMode=Rs.bind(null,this),s.compensateDistortion=n,this.setCameraRigMode(ce.V.RIG_MODE_VR,{vrCameraMetrics:s})}getClassName(){return"VRDeviceOrientationFreeCamera"}}b.N.AddNodeConstructor("VRDeviceOrientationGamepadCamera",((e,t)=>()=>new Ms(e,o.P.Zero(),t)));class Ms extends Is{constructor(e,t,i,n=!0,s=gs.GetDefault()){super(e,t,i,n,s),this._setRigMode=Rs.bind(null,this),this.inputs.addGamepad()}getClassName(){return"VRDeviceOrientationGamepadCamera"}}b.N.AddNodeConstructor("Light_Type_3",((e,t)=>()=>new Os(e,o.P.Zero(),t)));class Os extends he{constructor(e,t,i){super(e,i),this.groundColor=new a.Wo(0,0,0),this.direction=t||o.P.Up()}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightGround",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}getClassName(){return"HemisphericLight"}setDirectionToTarget(e){return this.direction=o.P.Normalize(e.subtract(o.P.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const i=o.P.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",i.x,i.y,i.z,0,t),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),t),this}transferToNodeMaterialEffect(e,t){const i=o.P.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=o.y3.Identity()),this._worldMatrix}getTypeID(){return he.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}function Ds(e,t){if(t.vrDisplay){const i=t.vrDisplay.getEyeParameters("left"),n=t.vrDisplay.getEyeParameters("right");e._rigCameras[0].viewport=new Nt.l(0,0,.5,1),e._rigCameras[0].setCameraRigParameter("left",!0),e._rigCameras[0].setCameraRigParameter("specs",t.specs),e._rigCameras[0].setCameraRigParameter("eyeParameters",i),e._rigCameras[0].setCameraRigParameter("frameData",t.frameData),e._rigCameras[0].setCameraRigParameter("parentCamera",t.parentCamera),e._rigCameras[0]._cameraRigParams.vrWorkMatrix=new o.y3,e._rigCameras[0].getProjectionMatrix=e._getWebVRProjectionMatrix,e._rigCameras[0].parent=e,e._rigCameras[0]._getViewMatrix=e._getWebVRViewMatrix,e._rigCameras[1].viewport=new Nt.l(.5,0,.5,1),e._rigCameras[1].setCameraRigParameter("eyeParameters",n),e._rigCameras[1].setCameraRigParameter("specs",t.specs),e._rigCameras[1].setCameraRigParameter("frameData",t.frameData),e._rigCameras[1].setCameraRigParameter("parentCamera",t.parentCamera),e._rigCameras[1]._cameraRigParams.vrWorkMatrix=new o.y3,e._rigCameras[1].getProjectionMatrix=e._getWebVRProjectionMatrix,e._rigCameras[1].parent=e,e._rigCameras[1]._getViewMatrix=e._getWebVRViewMatrix}}(0,oe.gn)([(0,E.n9)()],Os.prototype,"groundColor",void 0),(0,oe.gn)([(0,E.hd)()],Os.prototype,"direction",void 0),Object.defineProperty(fe.D.prototype,"isInVRExclusivePointerMode",{get:function(){return this._vrExclusivePointerMode},enumerable:!0,configurable:!0}),fe.D.prototype._prepareVRComponent=function(){this._vrSupported=!1,this._vrExclusivePointerMode=!1,this.onVRDisplayChangedObservable=new r.y$,this.onVRRequestPresentComplete=new r.y$,this.onVRRequestPresentStart=new r.y$},fe.D.prototype.isVRDevicePresent=function(){return!!this._vrDisplay},fe.D.prototype.getVRDevice=function(){return this._vrDisplay},fe.D.prototype.initWebVR=function(){return this.initWebVRAsync(),this.onVRDisplayChangedObservable},fe.D.prototype.initWebVRAsync=function(){const e=()=>{const e={vrDisplay:this._vrDisplay,vrSupported:this._vrSupported};this.onVRDisplayChangedObservable.notifyObservers(e),this._webVRInitPromise=new Promise((t=>{t(e)}))};if(!this._onVrDisplayConnect){this._onVrDisplayConnect=t=>{this._vrDisplay=t.display,e()},this._onVrDisplayDisconnect=()=>{this._vrDisplay.cancelAnimationFrame(this._frameHandler),this._vrDisplay=void 0,this._frameHandler=fe.D.QueueNewFrame(this._boundRenderFunction),e()},this._onVrDisplayPresentChange=()=>{this._vrExclusivePointerMode=this._vrDisplay&&this._vrDisplay.isPresenting};const t=this.getHostWindow();t&&(t.addEventListener("vrdisplayconnect",this._onVrDisplayConnect),t.addEventListener("vrdisplaydisconnect",this._onVrDisplayDisconnect),t.addEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange))}return this._webVRInitPromise=this._webVRInitPromise||this._getVRDisplaysAsync(),this._webVRInitPromise.then(e),this._webVRInitPromise},fe.D.prototype._getVRDisplaysAsync=function(){return new Promise((e=>{navigator.getVRDisplays?navigator.getVRDisplays().then((t=>{this._vrSupported=!0,this._vrDisplay=t[0],e({vrDisplay:this._vrDisplay,vrSupported:this._vrSupported})})):(this._vrDisplay=void 0,this._vrSupported=!1,e({vrDisplay:this._vrDisplay,vrSupported:this._vrSupported}))}))},fe.D.prototype.enableVR=function(e){if(this._vrDisplay&&!this._vrDisplay.isPresenting){const t=()=>{this.onVRRequestPresentComplete.notifyObservers(!0),this._onVRFullScreenTriggered()},i=()=>{this.onVRRequestPresentComplete.notifyObservers(!1)};this.onVRRequestPresentStart.notifyObservers(this);const n={highRefreshRate:!!this.vrPresentationAttributes&&this.vrPresentationAttributes.highRefreshRate,foveationLevel:this.vrPresentationAttributes?this.vrPresentationAttributes.foveationLevel:1,multiview:(this.getCaps().multiview||this.getCaps().oculusMultiview)&&e.useMultiview};this._vrDisplay.requestPresent([Object.assign({source:this.getRenderingCanvas(),attributes:n},n)]).then(t).catch(i)}},fe.D.prototype._onVRFullScreenTriggered=function(){if(this._vrDisplay&&this._vrDisplay.isPresenting){this._oldSize=new C(this.getRenderWidth(),this.getRenderHeight()),this._oldHardwareScaleFactor=this.getHardwareScalingLevel();const e=this._vrDisplay.getEyeParameters("left");this.setHardwareScalingLevel(1),this.setSize(2*e.renderWidth,e.renderHeight)}else this.setHardwareScalingLevel(this._oldHardwareScaleFactor),this.setSize(this._oldSize.width,this._oldSize.height)},fe.D.prototype.disableVR=function(){this._vrDisplay&&this._vrDisplay.isPresenting&&this._vrDisplay.exitPresent().then((()=>this._onVRFullScreenTriggered())).catch((()=>this._onVRFullScreenTriggered())),(0,_e.CG)()&&(window.removeEventListener("vrdisplaypointerrestricted",this._onVRDisplayPointerRestricted),window.removeEventListener("vrdisplaypointerunrestricted",this._onVRDisplayPointerUnrestricted),this._onVrDisplayConnect&&(window.removeEventListener("vrdisplayconnect",this._onVrDisplayConnect),this._onVrDisplayDisconnect&&window.removeEventListener("vrdisplaydisconnect",this._onVrDisplayDisconnect),this._onVrDisplayPresentChange&&window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChange),this._onVrDisplayConnect=null,this._onVrDisplayDisconnect=null))},fe.D.prototype._connectVREvents=function(e,t){if(this._onVRDisplayPointerRestricted=()=>{e&&e.requestPointerLock()},this._onVRDisplayPointerUnrestricted=()=>{if(t)t.exitPointerLock&&t.exitPointerLock();else{const e=this.getHostWindow();e.document&&e.document.exitPointerLock&&e.document.exitPointerLock()}},(0,_e.CG)()){const e=this.getHostWindow();e.addEventListener("vrdisplaypointerrestricted",this._onVRDisplayPointerRestricted,!1),e.addEventListener("vrdisplaypointerunrestricted",this._onVRDisplayPointerUnrestricted,!1)}},fe.D.prototype._submitVRFrame=function(){if(this._vrDisplay&&this._vrDisplay.isPresenting)try{this._vrDisplay.submitFrame()}catch(e){se.w1.Warn("webVR submitFrame has had an unexpected failure: "+e)}},fe.D.prototype.isVRPresenting=function(){return this._vrDisplay&&this._vrDisplay.isPresenting},fe.D.prototype._requestVRFrame=function(){this._frameHandler=fe.D.QueueNewFrame(this._boundRenderFunction,this._vrDisplay)},b.N.AddNodeConstructor("WebVRFreeCamera",((e,t)=>()=>new Ns(e,o.P.Zero(),t))),b.N.AddNodeConstructor("WebVRGamepadCamera",((e,t)=>()=>new Ns(e,o.P.Zero(),t)));class Ns extends Fn{constructor(e,t,i,n={}){super(e,t,i),this._webVROptions=n,this._vrDevice=null,this.rawPose=null,this._specsVersion="1.1",this._attached=!1,this._descendants=[],this._deviceRoomPosition=o.P.Zero(),this._deviceRoomRotationQuaternion=o._f.Identity(),this._standingMatrix=null,this.devicePosition=o.P.Zero(),this.deviceRotationQuaternion=o._f.Identity(),this.deviceScaleFactor=1,this._deviceToWorld=o.y3.Identity(),this._worldToDevice=o.y3.Identity(),this.controllers=[],this.onControllersAttachedObservable=new r.y$,this.onControllerMeshLoadedObservable=new r.y$,this.onPoseUpdatedFromDeviceObservable=new r.y$,this._poseSet=!1,this.rigParenting=!0,this._defaultHeight=void 0,this._setRigMode=Ds.bind(null,this),this._detachIfAttached=()=>{const e=this.getEngine().getVRDevice();e&&!e.isPresenting&&this.detachControl()},this._workingVector=o.P.Zero(),this._oneVector=o.P.One(),this._workingMatrix=o.y3.Identity(),this._tmpMatrix=new o.y3,this._cache.position=o.P.Zero(),n.defaultHeight&&(this._defaultHeight=n.defaultHeight,this.position.y=this._defaultHeight),this.minZ=.1,5===arguments.length&&(this._webVROptions=arguments[4]),null==this._webVROptions.trackPosition&&(this._webVROptions.trackPosition=!0),null==this._webVROptions.controllerMeshes&&(this._webVROptions.controllerMeshes=!0),null==this._webVROptions.defaultLightingOnControllers&&(this._webVROptions.defaultLightingOnControllers=!0),this.rotationQuaternion=new o._f,this._webVROptions&&this._webVROptions.positionScale&&(this.deviceScaleFactor=this._webVROptions.positionScale);const s=this.getEngine();this._onVREnabled=e=>{e&&this.initControllers()},s.onVRRequestPresentComplete.add(this._onVREnabled),s.initWebVR().add((e=>{e.vrDisplay&&this._vrDevice!==e.vrDisplay&&(this._vrDevice=e.vrDisplay,this.setCameraRigMode(ce.V.RIG_MODE_WEBVR,{parentCamera:this,vrDisplay:this._vrDevice,frameData:this._frameData,specs:this._specsVersion}),this._attached&&this.getEngine().enableVR(this._webVROptions))})),"undefined"!=typeof VRFrameData&&(this._frameData=new VRFrameData),n.useMultiview&&(this.getScene().getEngine().getCaps().multiview?(this._useMultiviewToSingleView=!0,this._rigPostProcess=new As("VRMultiviewToSingleview",this,1)):(p.Y.Warn("Multiview is not supported, falling back to standard rendering"),this._useMultiviewToSingleView=!1)),this.getScene().onBeforeCameraRenderObservable.add((e=>{e.parent===this&&this.rigParenting&&(this._descendants=this.getDescendants(!0,(e=>{const t=this.controllers.some((t=>t._mesh===e)),i=-1!==this._rigCameras.indexOf(e);return!t&&!i})),this._descendants.forEach((t=>{t.parent=e})))})),this.getScene().onAfterCameraRenderObservable.add((e=>{e.parent===this&&this.rigParenting&&this._descendants.forEach((e=>{e.parent=this}))}))}deviceDistanceToRoomGround(){return this._standingMatrix?(this._standingMatrix.getTranslationToRef(this._workingVector),this._deviceRoomPosition.y+this._workingVector.y):this._defaultHeight||0}useStandingMatrix(e=(e=>{})){this.getEngine().initWebVRAsync().then((t=>{t.vrDisplay&&t.vrDisplay.stageParameters&&t.vrDisplay.stageParameters.sittingToStandingTransform&&this._webVROptions.trackPosition?(this._standingMatrix=new o.y3,o.y3.FromFloat32ArrayToRefScaled(t.vrDisplay.stageParameters.sittingToStandingTransform,0,1,this._standingMatrix),this.getScene().useRightHandedSystem||this._standingMatrix&&this._standingMatrix.toggleModelMatrixHandInPlace(),e(!0)):e(!1)}))}useStandingMatrixAsync(){return new Promise((e=>{this.useStandingMatrix((t=>{e(t)}))}))}dispose(){this._detachIfAttached(),this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled),this._updateCacheWhenTrackingDisabledObserver&&this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver),super.dispose()}getControllerByName(e){for(const t of this.controllers)if(t.hand===e)return t;return null}get leftController(){return this._leftController||(this._leftController=this.getControllerByName("left")),this._leftController}get rightController(){return this._rightController||(this._rightController=this.getControllerByName("right")),this._rightController}getForwardRay(e=100){return this.leftCamera?super.getForwardRay(e,this.leftCamera.getWorldMatrix(),this.leftCamera.globalPosition):super.getForwardRay(e)}_checkInputs(){this._vrDevice&&this._vrDevice.isPresenting&&(this._vrDevice.getFrameData(this._frameData),this.updateFromDevice(this._frameData.pose)),super._checkInputs()}updateFromDevice(e){e&&e.orientation&&4===e.orientation.length&&(this.rawPose=e,this._deviceRoomRotationQuaternion.copyFromFloats(e.orientation[0],e.orientation[1],-e.orientation[2],-e.orientation[3]),this.getScene().useRightHandedSystem&&(this._deviceRoomRotationQuaternion.z*=-1,this._deviceRoomRotationQuaternion.w*=-1),this._webVROptions.trackPosition&&this.rawPose.position&&(this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0],this.rawPose.position[1],-this.rawPose.position[2]),this.getScene().useRightHandedSystem&&(this._deviceRoomPosition.z*=-1)),this._poseSet=!0)}attachControl(e){e=se.w1.BackCompatCameraNoPreventDefault(arguments),super.attachControl(e),this._attached=!0,e=!ce.V.ForceAttachControlToAlwaysPreventDefault&&e,this._vrDevice&&this.getEngine().enableVR(this._webVROptions);const t=this._scene.getEngine().getHostWindow();t&&t.addEventListener("vrdisplaypresentchange",this._detachIfAttached)}detachControl(){this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),super.detachControl(),this._attached=!1,this.getEngine().disableVR(),window.removeEventListener("vrdisplaypresentchange",this._detachIfAttached)}getClassName(){return"WebVRFreeCamera"}resetToCurrentRotation(){this._vrDevice.resetPose()}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];e.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion),t.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion),e.position.copyFrom(this._deviceRoomPosition),t.position.copyFrom(this._deviceRoomPosition)}_correctPositionIfNotTrackPosition(e,t=!1){this.rawPose&&this.rawPose.position&&!this._webVROptions.trackPosition&&(o.y3.TranslationToRef(this.rawPose.position[0],this.rawPose.position[1],-this.rawPose.position[2],this._tmpMatrix),t||this._tmpMatrix.invert(),this._tmpMatrix.multiplyToRef(e,e))}_updateCache(e){this.rotationQuaternion.equals(this._cache.rotationQuaternion)&&this.position.equals(this._cache.position)||(this._updateCacheCalled||(this._updateCacheCalled=!0,this.update()),this.rotationQuaternion.toRotationMatrix(this._workingMatrix),o.P.TransformCoordinatesToRef(this._deviceRoomPosition,this._workingMatrix,this._workingVector),this.devicePosition.subtractToRef(this._workingVector,this._workingVector),o.y3.ComposeToRef(this._oneVector,this.rotationQuaternion,this._workingVector,this._deviceToWorld),this._deviceToWorld.getTranslationToRef(this._workingVector),this._workingVector.addInPlace(this.position),this._workingVector.subtractInPlace(this._cache.position),this._deviceToWorld.setTranslation(this._workingVector),this._deviceToWorld.invertToRef(this._worldToDevice),this.controllers.forEach((e=>{e._deviceToWorld.copyFrom(this._deviceToWorld),this._correctPositionIfNotTrackPosition(e._deviceToWorld),e.update()}))),e||super._updateCache(),this._updateCacheCalled=!1}_computeDevicePosition(){o.P.TransformCoordinatesToRef(this._deviceRoomPosition,this._deviceToWorld,this.devicePosition)}update(){this._computeDevicePosition(),o.y3.FromQuaternionToRef(this._deviceRoomRotationQuaternion,this._workingMatrix),this._workingMatrix.multiplyToRef(this._deviceToWorld,this._workingMatrix),o._f.FromRotationMatrixToRef(this._workingMatrix,this.deviceRotationQuaternion),this._poseSet&&this.onPoseUpdatedFromDeviceObservable.notifyObservers(null),super.update()}_getViewMatrix(){return o.y3.Identity()}_getWebVRViewMatrix(){const e=this._cameraRigParams.parentCamera;e._updateCache();const t=this._cameraRigParams.left?this._cameraRigParams.frameData.leftViewMatrix:this._cameraRigParams.frameData.rightViewMatrix;return o.y3.FromArrayToRef(t,0,this._webvrViewMatrix),this.getScene().useRightHandedSystem||this._webvrViewMatrix.toggleModelMatrixHandInPlace(),this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix),o.P.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint),this.position.addToRef(this._transformedReferencePoint,this._currentTarget),1!==e.deviceScaleFactor&&(this._webvrViewMatrix.invert(),e.deviceScaleFactor&&(this._webvrViewMatrix.multiplyAtIndex(12,e.deviceScaleFactor),this._webvrViewMatrix.multiplyAtIndex(13,e.deviceScaleFactor),this._webvrViewMatrix.multiplyAtIndex(14,e.deviceScaleFactor)),this._webvrViewMatrix.invert()),e._correctPositionIfNotTrackPosition(this._webvrViewMatrix,!0),e._worldToDevice.multiplyToRef(this._webvrViewMatrix,this._webvrViewMatrix),this._workingMatrix=this._workingMatrix||o.y3.Identity(),this._webvrViewMatrix.invertToRef(this._workingMatrix),this._workingMatrix.multiplyToRef(e.getWorldMatrix(),this._workingMatrix),this._workingMatrix.getTranslationToRef(this._globalPosition),this._markSyncedWithParent(),this._webvrViewMatrix}_getWebVRProjectionMatrix(){const e=this.parent;e._vrDevice.depthNear=e.minZ,e._vrDevice.depthFar=e.maxZ;const t=this._cameraRigParams.left?this._cameraRigParams.frameData.leftProjectionMatrix:this._cameraRigParams.frameData.rightProjectionMatrix;return o.y3.FromArrayToRef(t,0,this._projectionMatrix),this.getScene().useRightHandedSystem||this._projectionMatrix.toggleProjectionMatrixHandInPlace(),this._projectionMatrix}initControllers(){this.controllers.length=0;const e=this.getScene().gamepadManager;this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add((e=>{if(e.type===tn.POSE_ENABLED){const t=e;t.defaultModel&&t.defaultModel.setEnabled(!1),"right"===t.hand&&(this._rightController=null),"left"===t.hand&&(this._leftController=null);const i=this.controllers.indexOf(t);-1!==i&&this.controllers.splice(i,1)}})),this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add((e=>{if(e.type===tn.POSE_ENABLED){const t=e;if(this._webVROptions.trackPosition||(t._disableTrackPosition(new o.P("left"==t.hand?-.15:.15,-.5,.25)),this._updateCacheWhenTrackingDisabledObserver||(this._updateCacheWhenTrackingDisabledObserver=this._scene.onBeforeRenderObservable.add((()=>{this._updateCache()})))),t.deviceScaleFactor=this.deviceScaleFactor,t._deviceToWorld.copyFrom(this._deviceToWorld),this._correctPositionIfNotTrackPosition(t._deviceToWorld),this._webVROptions.controllerMeshes&&(t.defaultModel?t.defaultModel.setEnabled(!0):t.initControllerMesh(this.getScene(),(e=>{if(e.scaling.scaleInPlace(this.deviceScaleFactor),this.onControllerMeshLoadedObservable.notifyObservers(t),this._webVROptions.defaultLightingOnControllers){this._lightOnControllers||(this._lightOnControllers=new Os("vrControllersLight",new o.P(0,1,0),this.getScene()));const t=function(e,i){const n=e.getChildren();n&&0!==n.length&&n.forEach((e=>{i.includedOnlyMeshes.push(e),t(e,i)}))};this._lightOnControllers.includedOnlyMeshes.push(e),t(e,this._lightOnControllers)}}))),t.attachToPoseControlledCamera(this),-1===this.controllers.indexOf(t)){this.controllers.push(t);let e=!1;for(let t=0;t=2&&this.onControllersAttachedObservable.notifyObservers(this.controllers)}}}))}}class Fs extends Hn{onButtonStateChange(e){this._onButtonStateChange=e}get defaultModel(){return this._defaultModel}constructor(e){super(e),this.onTriggerStateChangedObservable=new r.y$,this.onMainButtonStateChangedObservable=new r.y$,this.onSecondaryButtonStateChangedObservable=new r.y$,this.onPadStateChangedObservable=new r.y$,this.onPadValuesChangedObservable=new r.y$,this.pad={x:0,y:0},this._changes={pressChanged:!1,touchChanged:!1,valueChanged:!1,changed:!1},this._buttons=new Array(e.buttons.length),this.hand=e.hand}update(){super.update();for(let e=0;ee.priority-t.priority)),this._codeInjectionPoints={};const i={};i[sa._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(const n of this._plugins)n.collectDefines(i),this._collectPointNames("vertex",n.getCustomCode("vertex")),this._collectPointNames("fragment",n.getCustomCode("fragment"));return this._defineNamesFromPlugins=i,!0}_activatePlugin(e){-1===this._activePlugins.indexOf(e)&&(this._activePlugins.push(e),this._activePlugins.sort(((e,t)=>e.priority-t.priority)),this._material._callbackPluginEventIsReadyForSubMesh=this._handlePluginEventIsReadyForSubMesh.bind(this),this._material._callbackPluginEventPrepareDefinesBeforeAttributes=this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this),this._material._callbackPluginEventPrepareDefines=this._handlePluginEventPrepareDefines.bind(this),this._material._callbackPluginEventBindForSubMesh=this._handlePluginEventBindForSubMesh.bind(this),e.registerForExtraEvents&&(this._activePluginsForExtraEvents.push(e),this._activePluginsForExtraEvents.sort(((e,t)=>e.priority-t.priority)),this._material._callbackPluginEventHasRenderTargetTextures=this._handlePluginEventHasRenderTargetTextures.bind(this),this._material._callbackPluginEventFillRenderTargetTextures=this._handlePluginEventFillRenderTargetTextures.bind(this),this._material._callbackPluginEventHardBindForSubMesh=this._handlePluginEventHardBindForSubMesh.bind(this)))}getPlugin(e){for(let t=0;t0&&e.uniforms.push(...this._uniformList),this._samplerList.length>0&&e.samplers.push(...this._samplerList),this._uboList.length>0&&e.uniformBuffersNames.push(...this._uboList),e.customCode=this._injectCustomCode(e.customCode);break}case Ls.S.PrepareUniformBuffer:{const e=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];for(const t of this._plugins){const n=t.getUniforms();if(n){if(n.ubo)for(const t of n.ubo){if(t.size&&t.type){const n=null!==(i=t.arraySize)&&void 0!==i?i:0;e.ubo.addUniform(t.name,t.size,n),this._uboDeclaration+=`${t.type} ${t.name}${n>0?`[${n}]`:""};\r\n`}this._uniformList.push(t.name)}n.vertex&&(this._vertexDeclaration+=n.vertex+"\r\n"),n.fragment&&(this._fragmentDeclaration+=n.fragment+"\r\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){return(t,i)=>{var n;e&&(i=e(t,i)),this._uboDeclaration&&(i=i.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(i=i.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(i=i.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));const s=null===(n=this._codeInjectionPoints)||void 0===n?void 0:n[t];if(!s)return i;for(let e in s){let n="";for(const i of this._activePlugins){const s=i.getCustomCode(t);(null==s?void 0:s[e])&&(n+=s[e]+"\r\n")}if(n.length>0)if("!"===e.charAt(0)){e=e.substring(1);let t="g";if("!"===e.charAt(0))t="",e=e.substring(1);else{const i=na.exec(e);i&&i.length>=2&&(t=i[1],e=e.substring(t.length+1))}t.indexOf("g")<0&&(t+="g");const s=i,r=new RegExp(e,t);let o=r.exec(s);for(;null!==o;){let e=n;for(let t=0;t{la()}));const ra=[];let oa=!1,aa=null;function la(){ra.length=0,oa=!1,ut.F.OnEventObservable.remove(aa),aa=null}class ha{_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,n,s=!0,r=!1){this.priority=500,this.registerForExtraEvents=!1,this._material=e,this.name=t,this.priority=i,e.pluginManager||(e.pluginManager=new sa(e),e.onDisposeObservable.add((()=>{e.pluginManager=void 0}))),this._pluginDefineNames=n,this._pluginManager=e.pluginManager,s&&this._pluginManager._addPlugin(this),r&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,n){return!0}hardBindForSubMesh(e,t,i,n){}bindForSubMesh(e,t,i,n){}dispose(e){}getCustomCode(e){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(){return{}}copyTo(e){E.p4.Clone((()=>e),this)}serialize(){return E.p4.Serialize(this)}parse(e,t,i){E.p4.Parse((()=>this),e,t,i)}}(0,oe.gn)([(0,E.qC)()],ha.prototype,"name",void 0),(0,oe.gn)([(0,E.qC)()],ha.prototype,"priority",void 0),(0,oe.gn)([(0,E.qC)()],ha.prototype,"registerForExtraEvents",void 0);class ca extends Tt.H{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class da extends ha{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new ca,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=ut.F.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&i.getCaps().standardDerivatives&&this._texture&&Bs.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&&Bs.DetailTextureEnabled&&this._isEnabled?(It.G.PrepareDefinesForMergedUV(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&&Bs.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),It.G.BindTextureMatrix(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&Bs.DetailTextureEnabled&&e.setTexture("detailSampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){var t;e&&(null===(t=this._texture)||void 0===t||t.dispose())}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}}(0,oe.gn)([(0,E.oU)("detailTexture"),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],da.prototype,"texture",void 0),(0,oe.gn)([(0,E.qC)()],da.prototype,"diffuseBlendLevel",void 0),(0,oe.gn)([(0,E.qC)()],da.prototype,"roughnessBlendLevel",void 0),(0,oe.gn)([(0,E.qC)()],da.prototype,"bumpLevel",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],da.prototype,"normalBlendMethod",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],da.prototype,"isEnabled",void 0);var ua=i(6181);const pa={effect:null,subMesh:null};class fa extends Tt.H{constructor(e){super(e),this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.OPACITY=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.SPECULAR=!1,this.SPECULARDIRECTUV=0,this.BUMP=!1,this.BUMPDIRECTUV=0,this.PARALLAX=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.IS_REFLECTION_LINEAR=!1,this.IS_REFRACTION_LINEAR=!1,this.EXPOSURE=!1,this.rebuild()}setReflectionMode(e){const t=["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"];for(const i of t)this[i]=i===e}}class _a extends pt{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}get isPrePassCapable(){return!this.disableDepthWrite}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}get canRenderToMRT(){return!0}constructor(e,t){super(e,t),this._diffuseTexture=null,this._ambientTexture=null,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._specularTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._refractionTexture=null,this.ambientColor=new a.Wo(0,0,0),this.diffuseColor=new a.Wo(1,1,1),this.specularColor=new a.Wo(1,1,1),this.emissiveColor=new a.Wo(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._renderTargets=new Wt.t(16),this._worldViewProjectionMatrix=o.y3.Zero(),this._globalAmbientColor=new a.Wo(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new da(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new ws,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),_a.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),_a.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._renderTargets.push(this._refractionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets)}get hasRenderTargetTextures(){return!!(_a.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||(!!(_a.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures)}getClassName(){return"StandardMaterial"}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported,this._markAllSubMeshesAsMiscDirty()}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled)}needAlphaTesting(){return!!this._forceAlphaTest||this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===ut.F.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==ut.F.MATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){if(this._uniformBufferLayoutBuilt||this.buildUniformLayout(),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(Ls.S.GetDefineNames,this._eventInfo),t.materialDefines=new fa(this._eventInfo.defineNames));const n=this.getScene(),s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const r=n.getEngine();s._needNormals=It.G.PrepareDefinesForLights(n,e,s,!0,this._maxSimultaneousLights,this._disableLighting),It.G.PrepareDefinesForMultiview(n,s);const o=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(It.G.PrepareDefinesForPrePass(n,s,this.canRenderToMRT&&!o),It.G.PrepareDefinesForOIT(n,s,o),s._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,s._needUVs=!1;for(let e=1;e<=6;++e)s["MAINUV"+e]=!1;if(n.texturesEnabled){if(s.DIFFUSEDIRECTUV=0,s.BUMPDIRECTUV=0,s.AMBIENTDIRECTUV=0,s.OPACITYDIRECTUV=0,s.EMISSIVEDIRECTUV=0,s.SPECULARDIRECTUV=0,s.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&_a.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;It.G.PrepareDefinesForMergedUV(this._diffuseTexture,s,"DIFFUSE")}else s.DIFFUSE=!1;if(this._ambientTexture&&_a.AmbientTextureEnabled){if(!this._ambientTexture.isReadyOrNotBlocking())return!1;It.G.PrepareDefinesForMergedUV(this._ambientTexture,s,"AMBIENT")}else s.AMBIENT=!1;if(this._opacityTexture&&_a.OpacityTextureEnabled){if(!this._opacityTexture.isReadyOrNotBlocking())return!1;It.G.PrepareDefinesForMergedUV(this._opacityTexture,s,"OPACITY"),s.OPACITYRGB=this._opacityTexture.getAlphaFromRGB}else s.OPACITY=!1;if(this._reflectionTexture&&_a.ReflectionTextureEnabled){if(!this._reflectionTexture.isReadyOrNotBlocking())return!1;switch(s._needNormals=!0,s.REFLECTION=!0,s.ROUGHNESS=this._roughness>0,s.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,s.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===Le.INVCUBIC_MODE,s.REFLECTIONMAP_3D=this._reflectionTexture.isCube,s.REFLECTIONMAP_OPPOSITEZ=s.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,s.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case Le.EXPLICIT_MODE:s.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case Le.PLANAR_MODE:s.setReflectionMode("REFLECTIONMAP_PLANAR");break;case Le.PROJECTION_MODE:s.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case Le.SKYBOX_MODE:s.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case Le.SPHERICAL_MODE:s.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case Le.EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case Le.FIXED_EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case Le.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:s.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case Le.CUBIC_MODE:case Le.INVCUBIC_MODE:default:s.setReflectionMode("REFLECTIONMAP_CUBIC")}s.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else s.REFLECTION=!1,s.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&_a.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;It.G.PrepareDefinesForMergedUV(this._emissiveTexture,s,"EMISSIVE")}else s.EMISSIVE=!1;if(this._lightmapTexture&&_a.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;It.G.PrepareDefinesForMergedUV(this._lightmapTexture,s,"LIGHTMAP"),s.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,s.RGBDLIGHTMAP=this._lightmapTexture.isRGBD}else s.LIGHTMAP=!1;if(this._specularTexture&&_a.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;It.G.PrepareDefinesForMergedUV(this._specularTexture,s,"SPECULAR"),s.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else s.SPECULAR=!1;if(n.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&_a.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;It.G.PrepareDefinesForMergedUV(this._bumpTexture,s,"BUMP"),s.PARALLAX=this._useParallax,s.PARALLAXOCCLUSION=this._useParallaxOcclusion,s.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else s.BUMP=!1,s.PARALLAX=!1,s.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&_a.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.REFRACTION=!0,s.REFRACTIONMAP_3D=this._refractionTexture.isCube,s.RGBDREFRACTION=this._refractionTexture.isRGBD,s.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize}else s.REFRACTION=!1;s.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else s.DIFFUSE=!1,s.AMBIENT=!1,s.OPACITY=!1,s.REFLECTION=!1,s.EMISSIVE=!1,s.LIGHTMAP=!1,s.BUMP=!1,s.REFRACTION=!1;s.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),s.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,s.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,s.SPECULAROVERALPHA=this._useSpecularOverAlpha,s.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,s.ALPHATEST_AFTERALLALPHACOMPUTATIONS=null!==this.transparencyMode,s.ALPHABLEND=null===this.transparencyMode||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(s._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(s),s.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,s.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}s._areFresnelDirty&&(_a.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(s.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,s.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,s.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,s.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,s.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,s.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,s._needNormals=!0,s.FRESNEL=!0):s.FRESNEL=!1),It.G.PrepareDefinesForMisc(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,s),It.G.PrepareDefinesForFrameBoundValues(n,r,this,s,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=s,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),It.G.PrepareDefinesForAttributes(e,s,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let a=!1;if(s.isDirty){const i=s._areLightsDisposed;s.markAsProcessed();const o=new zt;s.REFLECTION&&o.addFallback(0,"REFLECTION"),s.SPECULAR&&o.addFallback(0,"SPECULAR"),s.BUMP&&o.addFallback(0,"BUMP"),s.PARALLAX&&o.addFallback(1,"PARALLAX"),s.PARALLAXOCCLUSION&&o.addFallback(0,"PARALLAXOCCLUSION"),s.SPECULAROVERALPHA&&o.addFallback(0,"SPECULAROVERALPHA"),s.FOG&&o.addFallback(1,"FOG"),s.POINTSIZE&&o.addFallback(0,"POINTSIZE"),s.LOGARITHMICDEPTH&&o.addFallback(0,"LOGARITHMICDEPTH"),It.G.HandleFallbacksForShadows(s,o,this._maxSimultaneousLights),s.SPECULARTERM&&o.addFallback(0,"SPECULARTERM"),s.DIFFUSEFRESNEL&&o.addFallback(1,"DIFFUSEFRESNEL"),s.OPACITYFRESNEL&&o.addFallback(2,"OPACITYFRESNEL"),s.REFLECTIONFRESNEL&&o.addFallback(3,"REFLECTIONFRESNEL"),s.EMISSIVEFRESNEL&&o.addFallback(4,"EMISSIVEFRESNEL"),s.FRESNEL&&o.addFallback(4,"FRESNEL"),s.MULTIVIEW&&o.addFallback(0,"MULTIVIEW");const l=[ne.o.PositionKind];s.NORMAL&&l.push(ne.o.NormalKind),s.TANGENT&&l.push(ne.o.TangentKind);for(let e=1;e<=6;++e)s["UV"+e]&&l.push(`uv${1===e?"":e}`);s.VERTEXCOLOR&&l.push(ne.o.ColorKind),It.G.PrepareAttributesForBones(l,e,s,o),It.G.PrepareAttributesForInstances(l,s),It.G.PrepareAttributesForMorphTargets(l,e,s),It.G.PrepareAttributesForBakedVertexAnimation(l,e,s);let h="default";const c=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","visibility","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vReflectionPosition","vReflectionSize","vRefractionPosition","vRefractionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff","boneTextureWidth","morphTargetTextureInfo","morphTargetTextureIndices"],d=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],u=["Material","Scene","Mesh"];this._eventInfo.fallbacks=o,this._eventInfo.fallbackRank=0,this._eventInfo.defines=s,this._eventInfo.uniforms=c,this._eventInfo.attributes=l,this._eventInfo.samplers=d,this._eventInfo.uniformBuffersNames=u,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._callbackPluginEventGeneric(Ls.S.PrepareEffect,this._eventInfo),ws.AddUniforms(c),ws.AddSamplers(d),ii.$&&(ii.$.PrepareUniforms(c,s),ii.$.PrepareSamplers(d,s)),It.G.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:u,samplers:d,defines:s,maxSimultaneousLights:this._maxSimultaneousLights}),(0,ua.qx)(c);const p={};this.customShaderNameResolve&&(h=this.customShaderNameResolve(h,c,u,d,s,l,p));const f=s.toString(),_=t.effect;let m=n.getEngine().createEffect(h,{attributes:l,uniformsNames:c,uniformBuffersNames:u,samplers:d,defines:f,fallbacks:o,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:s.NUM_MORPH_INFLUENCERS},processFinalCode:p.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:s.PREPASS},r);if(this._eventInfo.customCode=void 0,m)if(this._onEffectCreatedObservable&&(pa.effect=m,pa.subMesh=t,this._onEffectCreatedObservable.notifyObservers(pa)),this.allowShaderHotSwapping&&_&&!m.isReady()){if(m=_,s.markAsUnprocessed(),a=this.isFrozen,i)return s._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(m,s,this._materialContext)}return!(!t.effect||!t.effect.isReady())&&(s._renderId=n.getRenderId(),t.effect._wasPreviouslyReady=!a,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("reflectionMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("alphaCutOff",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vRefractionPosition",3),e.addUniform("vRefractionSize",3),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vDiffuseColor",4),e.addUniform("vAmbientColor",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){var n;const s=this.getScene(),r=i.materialDefines;if(!r)return;const o=i.effect;if(!o)return;this._activeEffect=o,t.getMeshUniformBuffer().bindToEffect(o,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(o,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),r.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const l=o._forceRebindOnNextCall||this._mustRebind(s,o,t.visibility);It.G.BindBonesParameters(t,o);const h=this._uniformBuffer;if(l){if(this.bindViewProjection(o),!h.useUbo||!this.isFrozen||!h.isSync||o._forceRebindOnNextCall){if(_a.FresnelEnabled&&r.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(h.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),h.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&h.updateColor4("opacityParts",new a.Wo(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(h.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),h.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(h.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),h.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(h.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),h.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),s.texturesEnabled){if(this._diffuseTexture&&_a.DiffuseTextureEnabled&&(h.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),It.G.BindTextureMatrix(this._diffuseTexture,h,"diffuse")),this._ambientTexture&&_a.AmbientTextureEnabled&&(h.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),It.G.BindTextureMatrix(this._ambientTexture,h,"ambient")),this._opacityTexture&&_a.OpacityTextureEnabled&&(h.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),It.G.BindTextureMatrix(this._opacityTexture,h,"opacity")),this._hasAlphaChannel()&&h.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&_a.ReflectionTextureEnabled&&(h.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),h.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){const e=this._reflectionTexture;h.updateVector3("vReflectionPosition",e.boundingBoxPosition),h.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this._emissiveTexture&&_a.EmissiveTextureEnabled&&(h.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),It.G.BindTextureMatrix(this._emissiveTexture,h,"emissive")),this._lightmapTexture&&_a.LightmapTextureEnabled&&(h.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),It.G.BindTextureMatrix(this._lightmapTexture,h,"lightmap")),this._specularTexture&&_a.SpecularTextureEnabled&&(h.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),It.G.BindTextureMatrix(this._specularTexture,h,"specular")),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&_a.BumpTextureEnabled&&(h.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),It.G.BindTextureMatrix(this._bumpTexture,h,"bump"),s._mirroredCameraPosition?h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&_a.RefractionTextureEnabled){let e=1;if(this._refractionTexture.isCube||(h.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(e=this._refractionTexture.depth)),h.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,e,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){const e=this._refractionTexture;h.updateVector3("vRefractionPosition",e.boundingBoxPosition),h.updateVector3("vRefractionSize",e.boundingBoxSize)}}}this.pointsCloud&&h.updateFloat("pointSize",this.pointSize),r.SPECULARTERM&&h.updateColor4("vSpecularColor",this.specularColor,this.specularPower),h.updateColor3("vEmissiveColor",_a.EmissiveTextureEnabled?this.emissiveColor:a.Wo.BlackReadOnly),h.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),s.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),h.updateColor3("vAmbientColor",this._globalAmbientColor)}s.texturesEnabled&&(this._diffuseTexture&&_a.DiffuseTextureEnabled&&o.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&_a.AmbientTextureEnabled&&o.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&_a.OpacityTextureEnabled&&o.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&_a.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?o.setTexture("reflectionCubeSampler",this._reflectionTexture):o.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&_a.EmissiveTextureEnabled&&o.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&_a.LightmapTextureEnabled&&o.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&_a.SpecularTextureEnabled&&o.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&_a.BumpTextureEnabled&&o.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&_a.RefractionTextureEnabled&&(this._refractionTexture.isCube?o.setTexture("refractionCubeSampler",this._refractionTexture):o.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(o),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),(0,ua.an)(o,this,s),this.bindEyePosition(o)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!l&&this.isFrozen||(s.lightsEnabled&&!this._disableLighting&&It.G.BindLights(s,t,o,r,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==N.x.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||r.PREPASS)&&this.bindView(o),It.G.BindFogParameters(s,t,o),r.NUM_MORPH_INFLUENCERS&&It.G.BindMorphTargetParameters(t,o),r.BAKED_VERTEX_ANIMATION_TEXTURE&&(null===(n=t.bakedVertexAnimationManager)||void 0===n||n.bind(o,r.INSTANCES)),this.useLogarithmicDepth&&It.G.BindLogDepth(r,o,s),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),h.update()}getAnimatables(){const e=super.getAnimatables();return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e}getActiveTextures(){const e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e}hasTexture(e){return!!super.hasTexture(e)||(this._diffuseTexture===e||(this._ambientTexture===e||(this._opacityTexture===e||(this._reflectionTexture===e||(this._emissiveTexture===e||(this._specularTexture===e||(this._bumpTexture===e||(this._lightmapTexture===e||this._refractionTexture===e))))))))}dispose(e,t){var i,n,s,r,o,a,l,h,c;t&&(null===(i=this._diffuseTexture)||void 0===i||i.dispose(),null===(n=this._ambientTexture)||void 0===n||n.dispose(),null===(s=this._opacityTexture)||void 0===s||s.dispose(),null===(r=this._reflectionTexture)||void 0===r||r.dispose(),null===(o=this._emissiveTexture)||void 0===o||o.dispose(),null===(a=this._specularTexture)||void 0===a||a.dispose(),null===(l=this._bumpTexture)||void 0===l||l.dispose(),null===(h=this._lightmapTexture)||void 0===h||h.dispose(),null===(c=this._refractionTexture)||void 0===c||c.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){const n=E.p4.Clone((()=>new _a(e,this.getScene())),this,{cloneTexturesOnlyOnce:t});return n.name=e,n.id=e,this.stencil.copyTo(n.stencil),this._clonePlugins(n,i),n}static Parse(e,t,i){const n=E.p4.Parse((()=>new _a(e.name,t)),e,t,i);return e.stencil&&n.stencil.parse(e.stencil,t,i),ut.F._parsePlugins(e,n,t,i),n}static get DiffuseTextureEnabled(){return Bs.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){Bs.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return Bs.DetailTextureEnabled}static set DetailTextureEnabled(e){Bs.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return Bs.AmbientTextureEnabled}static set AmbientTextureEnabled(e){Bs.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return Bs.OpacityTextureEnabled}static set OpacityTextureEnabled(e){Bs.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return Bs.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){Bs.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return Bs.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){Bs.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return Bs.SpecularTextureEnabled}static set SpecularTextureEnabled(e){Bs.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return Bs.BumpTextureEnabled}static set BumpTextureEnabled(e){Bs.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return Bs.LightmapTextureEnabled}static set LightmapTextureEnabled(e){Bs.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return Bs.RefractionTextureEnabled}static set RefractionTextureEnabled(e){Bs.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return Bs.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){Bs.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return Bs.FresnelEnabled}static set FresnelEnabled(e){Bs.FresnelEnabled=e}}(0,oe.gn)([(0,E.oU)("diffuseTexture")],_a.prototype,"_diffuseTexture",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],_a.prototype,"diffuseTexture",void 0),(0,oe.gn)([(0,E.oU)("ambientTexture")],_a.prototype,"_ambientTexture",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"ambientTexture",void 0),(0,oe.gn)([(0,E.oU)("opacityTexture")],_a.prototype,"_opacityTexture",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],_a.prototype,"opacityTexture",void 0),(0,oe.gn)([(0,E.oU)("reflectionTexture")],_a.prototype,"_reflectionTexture",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"reflectionTexture",void 0),(0,oe.gn)([(0,E.oU)("emissiveTexture")],_a.prototype,"_emissiveTexture",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"emissiveTexture",void 0),(0,oe.gn)([(0,E.oU)("specularTexture")],_a.prototype,"_specularTexture",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"specularTexture",void 0),(0,oe.gn)([(0,E.oU)("bumpTexture")],_a.prototype,"_bumpTexture",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"bumpTexture",void 0),(0,oe.gn)([(0,E.oU)("lightmapTexture")],_a.prototype,"_lightmapTexture",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"lightmapTexture",void 0),(0,oe.gn)([(0,E.oU)("refractionTexture")],_a.prototype,"_refractionTexture",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"refractionTexture",void 0),(0,oe.gn)([(0,E.n9)("ambient")],_a.prototype,"ambientColor",void 0),(0,oe.gn)([(0,E.n9)("diffuse")],_a.prototype,"diffuseColor",void 0),(0,oe.gn)([(0,E.n9)("specular")],_a.prototype,"specularColor",void 0),(0,oe.gn)([(0,E.n9)("emissive")],_a.prototype,"emissiveColor",void 0),(0,oe.gn)([(0,E.qC)()],_a.prototype,"specularPower",void 0),(0,oe.gn)([(0,E.qC)("useAlphaFromDiffuseTexture")],_a.prototype,"_useAlphaFromDiffuseTexture",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],_a.prototype,"useAlphaFromDiffuseTexture",void 0),(0,oe.gn)([(0,E.qC)("useEmissiveAsIllumination")],_a.prototype,"_useEmissiveAsIllumination",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"useEmissiveAsIllumination",void 0),(0,oe.gn)([(0,E.qC)("linkEmissiveWithDiffuse")],_a.prototype,"_linkEmissiveWithDiffuse",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"linkEmissiveWithDiffuse",void 0),(0,oe.gn)([(0,E.qC)("useSpecularOverAlpha")],_a.prototype,"_useSpecularOverAlpha",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"useSpecularOverAlpha",void 0),(0,oe.gn)([(0,E.qC)("useReflectionOverAlpha")],_a.prototype,"_useReflectionOverAlpha",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"useReflectionOverAlpha",void 0),(0,oe.gn)([(0,E.qC)("disableLighting")],_a.prototype,"_disableLighting",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsLightsDirty")],_a.prototype,"disableLighting",void 0),(0,oe.gn)([(0,E.qC)("useObjectSpaceNormalMap")],_a.prototype,"_useObjectSpaceNormalMap",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"useObjectSpaceNormalMap",void 0),(0,oe.gn)([(0,E.qC)("useParallax")],_a.prototype,"_useParallax",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"useParallax",void 0),(0,oe.gn)([(0,E.qC)("useParallaxOcclusion")],_a.prototype,"_useParallaxOcclusion",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"useParallaxOcclusion",void 0),(0,oe.gn)([(0,E.qC)()],_a.prototype,"parallaxScaleBias",void 0),(0,oe.gn)([(0,E.qC)("roughness")],_a.prototype,"_roughness",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"roughness",void 0),(0,oe.gn)([(0,E.qC)()],_a.prototype,"indexOfRefraction",void 0),(0,oe.gn)([(0,E.qC)()],_a.prototype,"invertRefractionY",void 0),(0,oe.gn)([(0,E.qC)()],_a.prototype,"alphaCutOff",void 0),(0,oe.gn)([(0,E.qC)("useLightmapAsShadowmap")],_a.prototype,"_useLightmapAsShadowmap",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"useLightmapAsShadowmap",void 0),(0,oe.gn)([(0,E.qQ)("diffuseFresnelParameters")],_a.prototype,"_diffuseFresnelParameters",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsFresnelDirty")],_a.prototype,"diffuseFresnelParameters",void 0),(0,oe.gn)([(0,E.qQ)("opacityFresnelParameters")],_a.prototype,"_opacityFresnelParameters",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsFresnelAndMiscDirty")],_a.prototype,"opacityFresnelParameters",void 0),(0,oe.gn)([(0,E.qQ)("reflectionFresnelParameters")],_a.prototype,"_reflectionFresnelParameters",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsFresnelDirty")],_a.prototype,"reflectionFresnelParameters",void 0),(0,oe.gn)([(0,E.qQ)("refractionFresnelParameters")],_a.prototype,"_refractionFresnelParameters",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsFresnelDirty")],_a.prototype,"refractionFresnelParameters",void 0),(0,oe.gn)([(0,E.qQ)("emissiveFresnelParameters")],_a.prototype,"_emissiveFresnelParameters",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsFresnelDirty")],_a.prototype,"emissiveFresnelParameters",void 0),(0,oe.gn)([(0,E.qC)("useReflectionFresnelFromSpecular")],_a.prototype,"_useReflectionFresnelFromSpecular",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsFresnelDirty")],_a.prototype,"useReflectionFresnelFromSpecular",void 0),(0,oe.gn)([(0,E.qC)("useGlossinessFromSpecularMapAlpha")],_a.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"useGlossinessFromSpecularMapAlpha",void 0),(0,oe.gn)([(0,E.qC)("maxSimultaneousLights")],_a.prototype,"_maxSimultaneousLights",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsLightsDirty")],_a.prototype,"maxSimultaneousLights",void 0),(0,oe.gn)([(0,E.qC)("invertNormalMapX")],_a.prototype,"_invertNormalMapX",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"invertNormalMapX",void 0),(0,oe.gn)([(0,E.qC)("invertNormalMapY")],_a.prototype,"_invertNormalMapY",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"invertNormalMapY",void 0),(0,oe.gn)([(0,E.qC)("twoSidedLighting")],_a.prototype,"_twoSidedLighting",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],_a.prototype,"twoSidedLighting",void 0),(0,oe.gn)([(0,E.qC)()],_a.prototype,"useLogarithmicDepth",null),(0,l.H)("BABYLON.StandardMaterial",_a),N.x.DefaultMaterialFactory=e=>new _a("default material",e),Ue.B.prototype.createDynamicTexture=function(e,t,i,n){const s=new Be.l(this,Be.S.Dynamic);return s.baseWidth=e,s.baseHeight=t,i&&(e=this.needPOTTextures?Ue.B.GetExponentOfTwo(e,this._caps.maxTextureSize):e,t=this.needPOTTextures?Ue.B.GetExponentOfTwo(t,this._caps.maxTextureSize):t),s.width=e,s.height=t,s.isReady=!1,s.generateMipMaps=i,s.samplingMode=n,this.updateTextureSamplingMode(n,s),this._internalTexturesCache.push(s),s},Ue.B.prototype.updateDynamicTexture=function(e,t,i,n=!1,s,r=!1,o=!1){if(!e)return;const a=this._gl,l=a.TEXTURE_2D,h=this._bindTextureDirectly(l,e,!0,r);this._unpackFlipY(void 0===i?e.invertY:i),n&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);const c=this._getWebGLTextureType(e.type),d=this._getInternalFormat(s||e.format),u=this._getRGBABufferInternalSizedFormat(e.type,d);a.texImage2D(l,0,u,d,c,t),e.generateMipMaps&&a.generateMipmap(l),h||this._bindTextureDirectly(l,null),n&&a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.isReady=!0};class ma extends Le{constructor(e,t,i=null,n=!1,s=3,r=5,o){super(null,i,!n,o,s,void 0,void 0,void 0,void 0,r),this.name=e,this.wrapU=Le.CLAMP_ADDRESSMODE,this.wrapV=Le.CLAMP_ADDRESSMODE,this._generateMipMaps=n;const a=this._getEngine();if(!a)return;t.getContext?(this._canvas=t,this._texture=a.createDynamicTexture(t.width,t.height,n,s)):(this._canvas=a.createCanvas(1,1),t.width||0===t.width?this._texture=a.createDynamicTexture(t.width,t.height,n,s):this._texture=a.createDynamicTexture(t,t,n,s));const l=this.getSize();this._canvas.width!==l.width&&(this._canvas.width=l.width),this._canvas.height!==l.height&&(this._canvas.height=l.height),this._context=this._canvas.getContext("2d")}getClassName(){return"DynamicTexture"}get canRescale(){return!0}_recreate(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._getEngine().createDynamicTexture(e.width,e.height,this._generateMipMaps,this.samplingMode)}scale(e){const t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)}scaleTo(e,t){const i=this.getSize();i.width=e,i.height=t,this._recreate(i)}getContext(){return this._context}clear(){const e=this.getSize();this._context.fillRect(0,0,e.width,e.height)}update(e,t=!1,i=!1){this._getEngine().updateDynamicTexture(this._texture,this._canvas,void 0===e||e,t,this._format||void 0,void 0,i)}drawText(e,t,i,n,s,r,o,a=!0){const l=this.getSize();if(r&&(this._context.fillStyle=r,this._context.fillRect(0,0,l.width,l.height)),this._context.font=n,null==t){const i=this._context.measureText(e);t=(l.width-i.width)/2}if(null==i){const e=parseInt(n.replace(/\D/g,""));i=l.height/2+e/3.65}this._context.fillStyle=s||"",this._context.fillText(e,t,i),a&&this.update(o)}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new ma(this.name,t,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.wrapU=this.wrapU,i.wrapV=this.wrapV,i}serialize(){const e=this.getScene();e&&!e.isReady()&&p.Y.Warn("The scene must be ready before serializing the dynamic texture");const t=super.serialize();return ma._IsCanvasElement(this._canvas)&&(t.base64String=this._canvas.toDataURL()),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t}static _IsCanvasElement(e){return void 0!==e.toDataURL}_rebuild(){this.update()}}const ga="imageProcessingPixelShader",va="varying vec2 vUV;\nuniform sampler2D textureSampler;\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}";Ht.v.ShadersStore[ga]=va;class Ta extends Zt{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){e.applyByPostProcess=!0,this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e,t=!1){if(e!==this._imageProcessingConfiguration){if(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e)this._imageProcessingConfiguration=e;else{let e=null;const t=this.getEngine(),i=this.getCamera();if(i)e=i.getScene();else if(t&&t.scenes){const i=t.scenes;e=i[i.length-1]}else e=m.l.LastCreatedScene;this._imageProcessingConfiguration=e?e.imageProcessingConfiguration:new ii.$}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._updateParameters()}))),t||this._updateParameters()}}get isSupported(){const e=this.getEffect();return!e||e.isSupported}get colorCurves(){return this.imageProcessingConfiguration.colorCurves}set colorCurves(e){this.imageProcessingConfiguration.colorCurves=e}get colorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set colorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get colorGradingTexture(){return this.imageProcessingConfiguration.colorGradingTexture}set colorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get colorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set colorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get exposure(){return this.imageProcessingConfiguration.exposure}set exposure(e){this.imageProcessingConfiguration.exposure=e}get toneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set toneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get toneMappingType(){return this._imageProcessingConfiguration.toneMappingType}set toneMappingType(e){this._imageProcessingConfiguration.toneMappingType=e}get contrast(){return this.imageProcessingConfiguration.contrast}set contrast(e){this.imageProcessingConfiguration.contrast=e}get vignetteStretch(){return this.imageProcessingConfiguration.vignetteStretch}set vignetteStretch(e){this.imageProcessingConfiguration.vignetteStretch=e}get vignetteCentreX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCentreX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteCentreY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCentreY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCenterY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCenterX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteWeight(){return this.imageProcessingConfiguration.vignetteWeight}set vignetteWeight(e){this.imageProcessingConfiguration.vignetteWeight=e}get vignetteColor(){return this.imageProcessingConfiguration.vignetteColor}set vignetteColor(e){this.imageProcessingConfiguration.vignetteColor=e}get vignetteCameraFov(){return this.imageProcessingConfiguration.vignetteCameraFov}set vignetteCameraFov(e){this.imageProcessingConfiguration.vignetteCameraFov=e}get vignetteBlendMode(){return this.imageProcessingConfiguration.vignetteBlendMode}set vignetteBlendMode(e){this.imageProcessingConfiguration.vignetteBlendMode=e}get vignetteEnabled(){return this.imageProcessingConfiguration.vignetteEnabled}set vignetteEnabled(e){this.imageProcessingConfiguration.vignetteEnabled=e}get ditheringIntensity(){return this.imageProcessingConfiguration.ditheringIntensity}set ditheringIntensity(e){this.imageProcessingConfiguration.ditheringIntensity=e}get ditheringEnabled(){return this.imageProcessingConfiguration.ditheringEnabled}set ditheringEnabled(e){this.imageProcessingConfiguration.ditheringEnabled=e}get fromLinearSpace(){return this._fromLinearSpace}set fromLinearSpace(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())}constructor(e,t,i=null,n,s,r,o=0,a){super(e,"imageProcessing",[],[],t,i,n,s,r,null,o,"postprocess",null,!0),this._fromLinearSpace=!0,this._defines={IMAGEPROCESSING:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:!1,TONEMAPPING_ACES:!1,CONTRAST:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,FROMLINEARSPACE:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,EXPOSURE:!1,SKIPFINALCOLORCLAMP:!1},a?(a.applyByPostProcess=!0,this._attachImageProcessingConfiguration(a,!0),this._updateParameters()):(this._attachImageProcessingConfiguration(null,!0),this.imageProcessingConfiguration.applyByPostProcess=!0),this.onApply=e=>{this.imageProcessingConfiguration.bind(e,this.aspectRatio)}}getClassName(){return"ImageProcessingPostProcess"}_updateParameters(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);let e="";for(const n in this._defines)this._defines[n]&&(e+=`#define ${n};\r\n`);const t=["textureSampler"],i=["scale"];ii.$&&(ii.$.PrepareSamplers(t,this._defines),ii.$.PrepareUniforms(i,this._defines)),this.updateEffect(e,i,t)}dispose(e){super.dispose(e),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration&&(this.imageProcessingConfiguration.applyByPostProcess=!1)}}(0,oe.gn)([(0,E.qC)()],Ta.prototype,"_fromLinearSpace",void 0);class Sa{get isFixedFoveationSupported(){return"XRWebGLLayer"==this.layerType&&"number"==typeof this.layer.fixedFoveation}get fixedFoveation(){return this.isFixedFoveationSupported?this.layer.fixedFoveation:null}set fixedFoveation(e){if(this.isFixedFoveationSupported){const t=Math.max(0,Math.min(1,e||0));this.layer.fixedFoveation=t}}constructor(e,t,i,n,s){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=n,this.createRenderTargetTextureProvider=s}}var Ea,xa,ba=i(8449);class Ca{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=new Array,this._engine=e.getEngine()}_createInternalTexture(e,t){const i=new Be.l(this._engine,Be.S.Unknown,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new ba.B(t,this._engine._gl),i.isReady=!0,i}_createRenderTargetTexture(e,t,i,n,s,r){if(!this._engine)throw new Error("Engine is disposed");const o={width:e,height:t},a=r?new bs(this._scene,o):new Ci("XR renderTargetTexture",o,this._scene),l=a.renderTarget;if(l._samples=a.samples,!i&&n||(l._framebuffer=i),n)if(r)l._colorTextureArray=n;else{const e=this._createInternalTexture(o,n);l.setTexture(e,0),a._texture=e}return s&&(r?l._depthStencilTextureArray=s:l._depthStencilTexture=this._createInternalTexture(o,s)),a.disableRescaling(),"undefined"!=typeof XRWebGLBinding&&(a.skipInitialClear=!0),this._renderTargetTextures.push(a),a}_destroyRenderTargetTexture(e){this._renderTargetTextures.splice(this._renderTargetTextures.indexOf(e),1),e.dispose()}getFramebufferDimensions(){return this._framebufferDimensions}dispose(){this._renderTargetTextures.forEach((e=>e.dispose())),this._renderTargetTextures.length=0}}class ya extends Sa{constructor(e){super((()=>e.framebufferWidth),(()=>e.framebufferHeight),e,"XRWebGLLayer",(e=>new Aa(e.scene,this))),this.layer=e}}class Aa extends Ca{constructor(e,t){super(e,t),this.layerWrapper=t,this._layer=t.layer,this._framebufferDimensions={framebufferWidth:this._layer.framebufferWidth,framebufferHeight:this._layer.framebufferHeight}}trySetViewportForView(e,t){const i=this._layer.getViewport(t);if(!i)return!1;const n=this._framebufferDimensions.framebufferWidth,s=this._framebufferDimensions.framebufferHeight;return e.x=i.x/n,e.y=i.y/s,e.width=i.width/n,e.height=i.height/s,!0}getRenderTargetTextureForEye(e){const t=this._layer.framebufferWidth,i=this._layer.framebufferHeight,n=this._layer.framebuffer;return this._rtt&&t===this._framebufferDimensions.framebufferWidth&&i===this._framebufferDimensions.framebufferHeight&&n===this._framebuffer||(this._rtt=this._createRenderTargetTexture(t,i,n),this._framebufferDimensions.framebufferWidth=t,this._framebufferDimensions.framebufferHeight=i,this._framebuffer=n),this._rtt}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}}class Ra{static GetDefaults(e){const t=new Ra;return t.canvasOptions={antialias:!0,depth:!0,stencil:!e||e.isStencilEnable,alpha:!0,framebufferScaleFactor:1},t.newCanvasCssStyle="position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;",t}}class Pa{constructor(e,t=Ra.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new r.y$,this._engine=e.scene.getEngine(),this._engine.onDisposeObservable.addOnce((()=>{this._engine=null})),t.canvasElement)this._setManagedOutputCanvas(t.canvasElement);else{const e=document.createElement("canvas");e.style.cssText=this._options.newCanvasCssStyle||"position:absolute; bottom:0px;right:0px;",this._setManagedOutputCanvas(e)}e.onXRSessionInit.add((()=>{this._addCanvas()})),e.onXRSessionEnded.add((()=>{this._removeCanvas()}))}dispose(){this._removeCanvas(),this._setManagedOutputCanvas(null)}async initializeXRLayerAsync(e){const t=()=>(this.xrLayer=new XRWebGLLayer(e,this.canvasContext,this._options.canvasOptions),this._xrLayerWrapper=new ya(this.xrLayer),this.onXRLayerInitObservable.notifyObservers(this.xrLayer),this.xrLayer);return this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then((()=>{}),(()=>{se.w1.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly.")})).then((()=>t())):Promise.resolve(t())}_addCanvas(){this._canvas&&this._engine&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.appendChild(this._canvas),this.xrLayer?this._setCanvasSize(!0):this.onXRLayerInitObservable.addOnce((()=>{this._setCanvasSize(!0)}))}_removeCanvas(){this._canvas&&this._engine&&document.body.contains(this._canvas)&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.removeChild(this._canvas),this._setCanvasSize(!1)}_setCanvasSize(e=!0,t=this._xrLayerWrapper){this._canvas&&this._engine&&(e?t&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=t.getWidth()+"px",this._canvas.style.height=t.getHeight()+"px"):this._engine.setSize(t.getWidth(),t.getHeight())):this._originalCanvasSize&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=this._originalCanvasSize.width+"px",this._canvas.style.height=this._originalCanvasSize.height+"px"):this._engine.setSize(this._originalCanvasSize.width,this._originalCanvasSize.height)))}_setManagedOutputCanvas(e){this._removeCanvas(),e?(this._originalCanvasSize={width:e.offsetWidth,height:e.offsetHeight},this._canvas=e,this.canvasContext=this._canvas.getContext("webgl2"),this.canvasContext||(this.canvasContext=this._canvas.getContext("webgl"))):(this._canvas=null,this.canvasContext=null)}}class Ia extends Sa{constructor(e){super((()=>e.framebufferWidth),(()=>e.framebufferHeight),e,"XRWebGLLayer",(e=>new Ma(e,this))),this.layer=e}}class Ma extends Ca{constructor(e,t){super(e.scene,t),this.layerWrapper=t,this._nativeRTTProvider=navigator.xr.getNativeRenderTargetProvider(e.session,this._createRenderTargetTexture.bind(this),this._destroyRenderTargetTexture.bind(this)),this._nativeLayer=t.layer}trySetViewportForView(e){return e.x=0,e.y=0,e.width=1,e.height=1,!0}getRenderTargetTextureForEye(e){return this._nativeRTTProvider.getRenderTargetForEye(e)}getRenderTargetTextureForView(e){return this._nativeRTTProvider.getRenderTargetForEye(e.eye)}getFramebufferDimensions(){return{framebufferWidth:this._nativeLayer.framebufferWidth,framebufferHeight:this._nativeLayer.framebufferHeight}}}class Oa{constructor(e){this._nativeRenderTarget=navigator.xr.getWebXRRenderTarget(e.scene.getEngine())}async initializeXRLayerAsync(e){return await this._nativeRenderTarget.initializeXRLayerAsync(e),this.xrLayer=this._nativeRenderTarget.xrLayer,this.xrLayer}dispose(){}}class Da{constructor(e){this.scene=e,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new r.y$,this.onXRReferenceSpaceChanged=new r.y$,this.onXRSessionEnded=new r.y$,this.onXRSessionInit=new r.y$,this.inXRFrameLoop=!1,this.inXRSession=!1,this._engine=e.getEngine(),this._onEngineDisposedObserver=this._engine.onDisposeObservable.addOnce((()=>{this._engine=null})),e.onDisposeObservable.addOnce((()=>{this.dispose()}))}get referenceSpace(){return this._referenceSpace}set referenceSpace(e){this._referenceSpace=e,this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace)}get sessionMode(){return this._sessionMode}dispose(){var e;this.inXRSession&&this.exitXRAsync(),this.onXRFrameObservable.clear(),this.onXRSessionEnded.clear(),this.onXRReferenceSpaceChanged.clear(),this.onXRSessionInit.clear(),null===(e=this._engine)||void 0===e||e.onDisposeObservable.remove(this._onEngineDisposedObserver),this._engine=null}exitXRAsync(){return this.session&&this.inXRSession?(this.inXRSession=!1,this.session.end().catch((()=>{p.Y.Warn("Could not end XR session.")}))):Promise.resolve()}trySetViewportForView(e,t){var i;return(null===(i=this._baseLayerRTTProvider)||void 0===i?void 0:i.trySetViewportForView(e,t))||!1}getRenderTargetTextureForEye(e){var t;return(null===(t=this._baseLayerRTTProvider)||void 0===t?void 0:t.getRenderTargetTextureForEye(e))||null}getRenderTargetTextureForView(e){var t;return(null===(t=this._baseLayerRTTProvider)||void 0===t?void 0:t.getRenderTargetTextureForView(e))||null}getWebXRRenderTarget(e){const t=this.scene.getEngine();return this._xrNavigator.xr.native?new Oa(this):((e=e||Ra.GetDefaults(t)).canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new Pa(this,e))}initializeAsync(){return this._xrNavigator=navigator,this._xrNavigator.xr?Promise.resolve():Promise.reject("WebXR not available")}initializeSessionAsync(e="immersive-vr",t={}){return this._xrNavigator.xr.requestSession(e,t).then((t=>(this.session=t,this._sessionMode=e,this.onXRSessionInit.notifyObservers(t),this.inXRSession=!0,this.session.addEventListener("end",(()=>{var e;this.inXRSession=!1,this.onXRSessionEnded.notifyObservers(null),this._engine&&(this._engine.framebufferDimensionsObject=null,this._engine.restoreDefaultFramebuffer(),this._engine.customAnimationFrameRequester=null,this._engine._renderLoop()),this.isNative&&(null===(e=this._baseLayerRTTProvider)||void 0===e||e.dispose()),this._baseLayerRTTProvider=null,this._baseLayerWrapper=null}),{once:!0}),this.session)))}isSessionSupportedAsync(e){return Da.IsSessionSupportedAsync(e)}resetReferenceSpace(){this.referenceSpace=this.baseReferenceSpace}runXRRenderLoop(){var e;this.inXRSession&&this._engine&&(this._engine.customAnimationFrameRequester={requestAnimationFrame:this.session.requestAnimationFrame.bind(this.session),renderFunction:(e,t)=>{var i;this.inXRSession&&this._engine&&(this.currentFrame=t,this.currentTimestamp=e,t&&(this.inXRFrameLoop=!0,this._engine.framebufferDimensionsObject=(null===(i=this._baseLayerRTTProvider)||void 0===i?void 0:i.getFramebufferDimensions())||null,this.onXRFrameObservable.notifyObservers(t),this._engine._renderLoop(),this._engine.framebufferDimensionsObject=null,this.inXRFrameLoop=!1))}},this._engine.framebufferDimensionsObject=(null===(e=this._baseLayerRTTProvider)||void 0===e?void 0:e.getFramebufferDimensions())||null,"undefined"!=typeof window&&window.cancelAnimationFrame&&window.cancelAnimationFrame(this._engine._frameHandler),this._engine._renderLoop())}setReferenceSpaceTypeAsync(e="local-floor"){return this.session.requestReferenceSpace(e).then((e=>e),(e=>(p.Y.Error("XR.requestReferenceSpace failed for the following reason: "),p.Y.Error(e),p.Y.Log('Defaulting to universally-supported "viewer" reference space type.'),this.session.requestReferenceSpace("viewer").then((e=>{const t=new XRRigidTransform({x:0,y:-this.defaultHeightCompensation,z:0});return e.getOffsetReferenceSpace(t)}),(e=>{throw p.Y.Error(e),'XR initialization failed: required "viewer" reference space type not supported.'}))))).then((e=>this.session.requestReferenceSpace("viewer").then((t=>(this.viewerReferenceSpace=t,e))))).then((e=>(this.referenceSpace=this.baseReferenceSpace=e,this.referenceSpace)))}updateRenderStateAsync(e){return Promise.resolve(this.session.updateRenderState(e))}_setBaseLayerWrapper(e){var t,i;this.isNative&&(null===(t=this._baseLayerRTTProvider)||void 0===t||t.dispose()),this._baseLayerWrapper=e,this._baseLayerRTTProvider=(null===(i=this._baseLayerWrapper)||void 0===i?void 0:i.createRenderTargetTextureProvider(this))||null}_getBaseLayerWrapper(){return this._baseLayerWrapper}updateRenderState(e){e.baseLayer&&this._setBaseLayerWrapper(this.isNative?new Ia(e.baseLayer):new ya(e.baseLayer)),this.session.updateRenderState(e)}static IsSessionSupportedAsync(e){if(!navigator.xr)return Promise.resolve(!1);const t=navigator.xr.isSessionSupported||navigator.xr.supportsSession;return t?t.call(navigator.xr,e).then((e=>{const t=void 0===e||e;return Promise.resolve(t)})).catch((e=>(p.Y.Warn(e),Promise.resolve(!1)))):Promise.resolve(!1)}get isNative(){var e;return null!==(e=this._xrNavigator.xr.native)&&void 0!==e&&e}get currentFrameRate(){var e;return null===(e=this.session)||void 0===e?void 0:e.frameRate}get supportedFrameRates(){var e;return null===(e=this.session)||void 0===e?void 0:e.supportedFrameRates}updateTargetFrameRate(e){return this.session.updateTargetFrameRate(e)}runInXRFrame(e,t=!0){this.inXRFrameLoop?e():!this.inXRSession&&t||this.onXRFrameObservable.addOnce(e)}get isFixedFoveationSupported(){var e;return(null===(e=this._baseLayerWrapper)||void 0===e?void 0:e.isFixedFoveationSupported)||!1}get fixedFoveation(){var e;return(null===(e=this._baseLayerWrapper)||void 0===e?void 0:e.fixedFoveation)||null}set fixedFoveation(e){const t=Math.max(0,Math.min(1,e||0));this._baseLayerWrapper&&(this._baseLayerWrapper.fixedFoveation=t)}get enabledFeatures(){var e,t;return null!==(t=null===(e=this.session)||void 0===e?void 0:e.enabledFeatures)&&void 0!==t?t:null}}function Na(e){const t=e.height||2;let i=0===e.diameterTop?0:e.diameterTop||e.diameter||1,n=0===e.diameterBottom?0:e.diameterBottom||e.diameter||1;i=i||1e-5,n=n||1e-5;const s=e.tessellation||24,r=e.subdivisions||1,l=!!e.hasRings,h=!!e.enclose,c=0===e.cap?0:e.cap||ee.Kj.CAP_ALL,d=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,u=0===e.sideOrientation?0:e.sideOrientation||Qe.x.DEFAULTSIDE,p=e.faceUV||new Array(3),f=e.faceColors,_=2+(1+(1!==d&&h?2:0))*(l?r:1);let m;for(m=0;m<_;m++)f&&void 0===f[m]&&(f[m]=new a.HE(1,1,1,1));for(m=0;m<_;m++)p&&void 0===p[m]&&(p[m]=new o.Lt(0,0,1,1));const g=new Array,v=new Array,T=new Array,S=new Array,E=new Array,x=2*Math.PI*d/s;let b,C,y;const A=(n-i)/2/t,R=o.P.Zero(),P=o.P.Zero(),I=o.P.Zero(),M=o.P.Zero(),O=o.P.Zero(),D=L.RD.Y;let N,F,w,B=1,U=1,V=0,k=0;for(N=0;N<=r;N++)for(C=N/r,y=(C*(i-n)+n)/2,B=l&&0!==N&&N!==r?2:1,w=0;w{const r=e?i/2:n/2;if(0===r)return;let a,l,h;const c=e?p[_-1]:p[0];let u=null;f&&(u=e?f[_-1]:f[0]);const m=v.length/3,x=e?t/2:-t/2,b=new o.P(0,x,0);v.push(b.x,b.y,b.z),T.push(0,e?1:-1,0);const C=c.y+.5*(c.w-c.y);S.push(c.x+.5*(c.z-c.x),we.e.UseOpenGLOrientationForUV?1-C:C),u&&E.push(u.r,u.g,u.b,u.a);const y=new o.FM(.5,.5);for(h=0;h<=s;h++){a=2*Math.PI*h*d/s;const t=Math.cos(-a),i=Math.sin(-a);l=new o.P(t*r,x,i*r);const n=new o.FM(t*y.x+.5,i*y.y+.5);v.push(l.x,l.y,l.z),T.push(0,e?1:-1,0);const p=c.y+(c.w-c.y)*n.y;S.push(c.x+(c.z-c.x)*n.x,we.e.UseOpenGLOrientationForUV?1-p:p),u&&E.push(u.r,u.g,u.b,u.a)}for(h=0;h{void 0!==o&&o instanceof N.x||(void 0!==o&&(l=a||ee.Kj.DEFAULTSIDE,a=o),o=r,r=1);return Fa(e,{height:t,diameterTop:i,diameterBottom:n,tessellation:s,subdivisions:r,sideOrientation:l,updatable:a},o)};Qe.x.CreateTorus=wa,ee.Kj.CreateTorus=(e,t,i,n,s,r,o)=>La(e,{diameter:t,thickness:i,tessellation:n,sideOrientation:o,updatable:r},s),ee.Kj._GroundMeshParser=(e,t)=>Ba.Parse(e,t);class Ba extends ee.Kj{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=o.jp.Matrix[5];i.invertToRef(n);const s=o.jp.Vector3[8];if(o.P.TransformCoordinatesFromFloatsToRef(e,0,t,n,s),e=s.x,t=s.z,e=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const r=this._getFacetAt(e,t),a=-(r.x*e+r.z*t+r.w)/r.y;return o.P.TransformCoordinatesFromFloatsToRef(0,a,0,i,s),s.y}getNormalAtCoordinates(e,t){const i=new o.P(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){const n=this.getWorldMatrix(),s=o.jp.Matrix[5];n.invertToRef(s);const r=o.jp.Vector3[8];if(o.P.TransformCoordinatesFromFloatsToRef(e,0,t,s,r),e=r.x,t=r.z,ethis._maxX||tthis._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const a=this._getFacetAt(e,t);return o.P.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),s=this._heightQuads[n*this._subdivisionsX+i];let r;return r=te.maxHeight){d=!0;const t=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=t}for(r=0;r<=e.subdivisions;r++)for(l=0;l<=e.subdivisions;l++){const t=new o.P(l*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-r)*e.height/e.subdivisions-e.height/2),a=4*(((t.x+e.width/2)/e.width*(e.bufferWidth-1)|0)+((1-(t.z+e.height/2)/e.height)*(e.bufferHeight-1)|0)*e.bufferWidth);let u=e.buffer[a]/255,p=e.buffer[a+1]/255,f=e.buffer[a+2]/255;const _=e.buffer[a+3]/255;d&&(u=1-u,p=1-p,f=1-f);const m=u*h.r+p*h.g+f*h.b;t.y=_>=c?e.minHeight+(e.maxHeight-e.minHeight)*m:e.minHeight-k.kn,i.push(t.x,t.y,t.z),n.push(0,0,0),s.push(l/e.subdivisions,1-r/e.subdivisions)}for(r=0;r=e.minHeight,c=i[3*s+1]>=e.minHeight,d=i[3*o+1]>=e.minHeight;h&&c&&d&&(t.push(n),t.push(s),t.push(o));i[3*a+1]>=e.minHeight&&h&&d&&(t.push(a),t.push(n),t.push(o))}Qe.x.ComputeNormals(i,t,n);const u=new Qe.x;return u.indices=t,u.positions=i,u.normals=n,u.uvs=s,u}function Ga(e,t={},i){const n=new Ba(e,i);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;return Ua(t).applyToMesh(n,t.updatable),n._setReady(!0),n}function za(e,t,i=null){const n=new ee.Kj(e,i);return Va(t).applyToMesh(n,t.updatable),n}function Wa(e,t,i={},n=null){const s=i.width||10,r=i.height||10,o=i.subdivisions||1,l=i.minHeight||0,h=i.maxHeight||1,c=i.colorFilter||new a.Wo(.3,.59,.11),d=i.alphaFilter||0,u=i.updatable,p=i.onReady;n=n||m.l.LastCreatedScene;const f=new Ba(e,n);f._subdivisionsX=o,f._subdivisionsY=o,f._width=s,f._height=r,f._maxX=f._width/2,f._maxZ=f._height/2,f._minX=-f._maxX,f._minZ=-f._maxZ,f._setReady(!1);return se.w1.LoadImage(t,(e=>{const t=e.width,i=e.height;if(n.isDisposed)return;const a=null==n?void 0:n.getEngine().resizeImageBitmap(e,t,i);ka({width:s,height:r,subdivisions:o,minHeight:l,maxHeight:h,colorFilter:c,buffer:a,bufferWidth:t,bufferHeight:i,alphaFilter:d}).applyToMesh(f,u),p&&p(f),f._setReady(!0)}),(()=>{}),n.offlineProvider),f}Qe.x.CreateGround=Ua,Qe.x.CreateTiledGround=Va,Qe.x.CreateGroundFromHeightMap=ka,ee.Kj.CreateGround=(e,t,i,n,s,r)=>Ga(e,{width:t,height:i,subdivisions:n,updatable:r},s),ee.Kj.CreateTiledGround=(e,t,i,n,s,r,o,a,l)=>za(e,{xmin:t,zmin:i,xmax:n,zmax:s,subdivisions:r,precision:o,updatable:l},a),ee.Kj.CreateGroundFromHeightMap=(e,t,i,n,s,r,o,a,l,h,c)=>Wa(e,t,{width:i,height:n,subdivisions:s,minHeight:r,maxHeight:o,updatable:l,onReady:h,alphaFilter:c},a);class Ha{constructor(e,t=null){if(this.scene=e,this._pointerDownOnMeshAsked=!1,this._isActionableMesh=!1,this._teleportationRequestInitiated=!1,this._teleportationBackRequestInitiated=!1,this._rotationRightAsked=!1,this._rotationLeftAsked=!1,this._dpadPressed=!0,this._activePointer=!1,this._id=Ha._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=La("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},e),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;const t=new _a("targetMat",e);t.specularColor=a.Wo.Black(),t.emissiveColor=new a.Wo(.7,.7,.7),t.backFaceCulling=!1,this._gazeTracker.material=t}}_getForwardRay(e){return new qe(o.P.Zero(),new o.P(0,0,e))}_selectionPointerDown(){this._pointerDownOnMeshAsked=!0,this._currentHit&&this.scene.simulatePointerDown(this._currentHit,{pointerId:this._id})}_selectionPointerUp(){this._currentHit&&this.scene.simulatePointerUp(this._currentHit,{pointerId:this._id}),this._pointerDownOnMeshAsked=!1}_activatePointer(){this._activePointer=!0}_deactivatePointer(){this._activePointer=!1}_updatePointerDistance(e=100){}dispose(){this._interactionsEnabled=!1,this._teleportationEnabled=!1,this._gazeTracker&&this._gazeTracker.dispose()}}Ha._IdCounter=0;class Xa extends Ha{constructor(e,t,i){super(t,i),this.webVRController=e,this._laserPointer=Fa("laserPointer",{updatable:!1,height:1,diameterTop:.004,diameterBottom:2e-4,tessellation:20,subdivisions:1},t);const n=new _a("laserPointerMat",t);if(n.emissiveColor=new a.Wo(.7,.7,.7),n.alpha=.6,this._laserPointer.material=n,this._laserPointer.rotation.x=Math.PI/2,this._laserPointer.position.z=-.5,this._laserPointer.isVisible=!1,this._laserPointer.isPickable=!1,!e.mesh){const i=new ee.Kj("preloadControllerMesh",t),n=new ee.Kj(Hn.POINTING_POSE,t);n.rotation.x=-.7,i.addChild(n),e.attachToMesh(i)}this._setLaserPointerParent(e.mesh),this._meshAttachedObserver=e._meshAttachedObservable.add((e=>{this._setLaserPointerParent(e)}))}_getForwardRay(e){return this.webVRController.getForwardRay(e)}_activatePointer(){super._activatePointer(),this._laserPointer.isVisible=!0}_deactivatePointer(){super._deactivatePointer(),this._laserPointer.isVisible=!1}_setLaserPointerColor(e){this._laserPointer.material.emissiveColor=e}_setLaserPointerLightingDisabled(e){this._laserPointer.material.disableLighting=e}_setLaserPointerParent(e){const t=e=>{e.isPickable=!1,e.getChildMeshes().forEach((e=>{t(e)}))};t(e);const i=e.getChildren(void 0,!1);let n=e;this.webVRController._pointingPoseNode=null;for(let s=0;s=0){n=i[s],this.webVRController._pointingPoseNode=n;break}this._laserPointer.parent=n}_updatePointerDistance(e=100){this._laserPointer.scaling.y=e,this._laserPointer.position.z=-e/2}dispose(){super.dispose(),this._laserPointer.dispose(),this._meshAttachedObserver&&this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver)}}class Ya extends Ha{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){const t=this._getCamera();return t?t.getForwardRay(e):new qe(o.P.Zero(),o.P.Forward())}}class ja{get onEnteringVR(){return this.onEnteringVRObservable}get onExitingVR(){return this.onExitingVRObservable}get onControllerMeshLoaded(){return this.onControllerMeshLoadedObservable}get teleportationTarget(){return this._teleportationTarget}set teleportationTarget(e){e&&(e.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=e)}get gazeTrackerMesh(){return this._cameraGazer._gazeTracker}set gazeTrackerMesh(e){e&&(this._cameraGazer._gazeTracker&&this._cameraGazer._gazeTracker.dispose(),this._leftController&&this._leftController._gazeTracker&&this._leftController._gazeTracker.dispose(),this._rightController&&this._rightController._gazeTracker&&this._rightController._gazeTracker.dispose(),this._cameraGazer._gazeTracker=e,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker",this._leftController&&(this._leftController._gazeTracker=this._cameraGazer._gazeTracker.clone("gazeTracker")),this._rightController&&(this._rightController._gazeTracker=this._cameraGazer._gazeTracker.clone("gazeTracker")))}get leftControllerGazeTrackerMesh(){return this._leftController?this._leftController._gazeTracker:null}get rightControllerGazeTrackerMesh(){return this._rightController?this._rightController._gazeTracker:null}get displayGaze(){return this._displayGaze}set displayGaze(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1,this._leftController&&(this._leftController._gazeTracker.isVisible=!1),this._rightController&&(this._rightController._gazeTracker.isVisible=!1))}get displayLaserPointer(){return this._displayLaserPointer}set displayLaserPointer(e){this._displayLaserPointer=e,e?(this._rightController&&this._rightController._activatePointer(),this._leftController&&this._leftController._activatePointer()):(this._rightController&&(this._rightController._deactivatePointer(),this._rightController._gazeTracker.isVisible=!1),this._leftController&&(this._leftController._deactivatePointer(),this._leftController._gazeTracker.isVisible=!1))}get deviceOrientationCamera(){return this._deviceOrientationCamera}get currentVRCamera(){return this._webVRready?this._webVRCamera:this._scene.activeCamera}get webVRCamera(){return this._webVRCamera}get vrDeviceOrientationCamera(){return this._vrDeviceOrientationCamera}get vrButton(){return this._btnVR}get _teleportationRequestInitiated(){return this._cameraGazer._teleportationRequestInitiated||null!==this._leftController&&this._leftController._teleportationRequestInitiated||null!==this._rightController&&this._rightController._teleportationRequestInitiated}constructor(e,t={}){this.webVROptions=t,this._webVRsupported=!1,this._webVRready=!1,this._webVRrequesting=!1,this._webVRpresenting=!1,this._fullscreenVRpresenting=!1,this.enableGazeEvenWhenNoPointerLock=!1,this.exitVROnDoubleTap=!0,this.onEnteringVRObservable=new r.y$,this.onAfterEnteringVRObservable=new r.y$,this.onExitingVRObservable=new r.y$,this.onControllerMeshLoadedObservable=new r.y$,this._useCustomVRButton=!1,this._teleportationRequested=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=ja.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new o.P(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new o.P(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._leftController=null,this._rightController=null,this._gazeColor=new a.Wo(.7,.7,.7),this._laserColor=new a.Wo(.7,.7,.7),this._pickedLaserColor=new a.Wo(.2,.2,1),this._pickedGazeColor=new a.Wo(0,0,1),this.onNewMeshSelected=new r.y$,this.onMeshSelectedWithController=new r.y$,this.onNewMeshPicked=new r.y$,this.onBeforeCameraTeleport=new r.y$,this.onAfterCameraTeleport=new r.y$,this.onSelectedMeshUnselected=new r.y$,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._interactionsRequested=!1,this._displayGaze=!0,this._displayLaserPointer=!0,this.updateGazeTrackerScale=!0,this.updateGazeTrackerColor=!0,this.updateControllerLaserColor=!0,this.requestPointerLockOnFullScreen=!0,this.xrTestDone=!1,this._onResize=()=>{this._moveButtonToBottomRight(),this._fullscreenVRpresenting&&this._webVRready&&this.exitVR()},this._onFullscreenChange=()=>{this._fullscreenVRpresenting=!!document.fullscreenElement,!this._fullscreenVRpresenting&&this._inputElement&&(this.exitVR(),!this._useCustomVRButton&&this._btnVR&&(this._btnVR.style.top=this._inputElement.offsetTop+this._inputElement.offsetHeight-70+"px",this._btnVR.style.left=this._inputElement.offsetLeft+this._inputElement.offsetWidth-100+"px",this._updateButtonVisibility()))},this._cachedAngularSensibility={angularSensibilityX:null,angularSensibilityY:null,angularSensibility:null},this._beforeRender=()=>{this._leftController&&this._leftController._activePointer&&this._castRayAndSelectObject(this._leftController),this._rightController&&this._rightController._activePointer&&this._castRayAndSelectObject(this._rightController),this._noControllerIsActive&&(this._scene.getEngine().isPointerLock||this.enableGazeEvenWhenNoPointerLock)?this._castRayAndSelectObject(this._cameraGazer):this._cameraGazer._gazeTracker.isVisible=!1},this._onNewGamepadConnected=e=>{if(e.type!==tn.POSE_ENABLED)e.leftStick&&e.onleftstickchanged((e=>{this._teleportationInitialized&&this.teleportationEnabled&&(!this._leftController&&!this._rightController||this._leftController&&!this._leftController._activePointer&&this._rightController&&!this._rightController._activePointer)&&(this._checkTeleportWithRay(e,this._cameraGazer),this._checkTeleportBackwards(e,this._cameraGazer))})),e.rightStick&&e.onrightstickchanged((e=>{this._teleportationInitialized&&this._checkRotate(e,this._cameraGazer)})),e.type===tn.XBOX&&(e.onbuttondown((e=>{this._interactionsEnabled&&e===An.A&&this._cameraGazer._selectionPointerDown()})),e.onbuttonup((e=>{this._interactionsEnabled&&e===An.A&&this._cameraGazer._selectionPointerUp()})));else{const t=e,i=new Xa(t,this._scene,this._cameraGazer._gazeTracker);"right"===t.hand||this._leftController&&this._leftController.webVRController!=t?this._rightController=i:this._leftController=i,this._tryEnableInteractionOnController(i)}},this._tryEnableInteractionOnController=e=>{this._interactionsRequested&&!e._interactionsEnabled&&this._enableInteractionOnController(e),this._teleportationRequested&&!e._teleportationEnabled&&this._enableTeleportationOnController(e)},this._onNewGamepadDisconnected=e=>{e instanceof Fs&&("left"===e.hand&&null!=this._leftController&&(this._leftController.dispose(),this._leftController=null),"right"===e.hand&&null!=this._rightController&&(this._rightController.dispose(),this._rightController=null))},this._workingVector=o.P.Zero(),this._workingQuaternion=o._f.Identity(),this._workingMatrix=o.y3.Identity(),p.Y.Warn("WebVR is deprecated. Please avoid using this experience helper and use the WebXR experience helper instead"),this._scene=e,this._inputElement=e.getEngine().getInputElement();if("getVRDisplays"in navigator||void 0!==t.useXR||(t.useXR=!0),void 0===t.createFallbackVRDeviceOrientationFreeCamera&&(t.createFallbackVRDeviceOrientationFreeCamera=!0),void 0===t.createDeviceOrientationCamera&&(t.createDeviceOrientationCamera=!0),void 0===t.laserToggle&&(t.laserToggle=!0),void 0===t.defaultHeight&&(t.defaultHeight=1.7),t.useCustomVRButton&&(this._useCustomVRButton=!0,t.customVRButton&&(this._btnVR=t.customVRButton)),t.rayLength&&(this._rayLength=t.rayLength),this._defaultHeight=t.defaultHeight,t.positionScale&&(this._rayLength*=t.positionScale,this._defaultHeight*=t.positionScale),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new o.P(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new Bn("deviceOrientationVRHelper",this._position.clone(),e),this._scene.activeCamera&&(this._deviceOrientationCamera.minZ=this._scene.activeCamera.minZ,this._deviceOrientationCamera.maxZ=this._scene.activeCamera.maxZ,this._scene.activeCamera instanceof Nn&&this._scene.activeCamera.rotation)){const e=this._scene.activeCamera;e.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(e.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(o._f.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z)),this._deviceOrientationCamera.rotation=e.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._inputElement&&this._scene.activeCamera.attachControl()}else this._existingCamera=this._scene.activeCamera;this.webVROptions.useXR&&navigator.xr?Da.IsSessionSupportedAsync("immersive-vr").then((i=>{i?(p.Y.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),e.createDefaultXRExperienceAsync({floorMeshes:t.floorMeshes||[]}).then((t=>{this.xr=t,this.xrTestDone=!0,this._cameraGazer=new Ya((()=>this.xr.baseExperience.camera),e),this.xr.baseExperience.onStateChangedObservable.add((e=>{switch(e){case Ea.ENTERING_XR:this.onEnteringVRObservable.notifyObservers(this),this._interactionsEnabled||this.xr.pointerSelection.detach(),this.xr.pointerSelection.displayLaserPointer=this._displayLaserPointer;break;case Ea.EXITING_XR:this.onExitingVRObservable.notifyObservers(this),this._scene.getEngine().resize();break;case Ea.IN_XR:this._hasEnteredVR=!0;break;case Ea.NOT_IN_XR:this._hasEnteredVR=!1}}))}))):this._completeVRInit(e,t)})):this._completeVRInit(e,t)}_completeVRInit(e,t){if(this.xrTestDone=!0,t.createFallbackVRDeviceOrientationFreeCamera&&(t.useMultiview&&(t.vrDeviceOrientationCameraMetrics||(t.vrDeviceOrientationCameraMetrics=gs.GetDefault()),t.vrDeviceOrientationCameraMetrics.multiviewEnabled=!0),this._vrDeviceOrientationCamera=new Is("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._webVRCamera=new Ns("WebVRHelper",this._position,this._scene,t),this._webVRCamera.useStandingMatrix(),this._cameraGazer=new Ya((()=>this.currentVRCamera),e),!this._useCustomVRButton){this._btnVR=document.createElement("BUTTON"),this._btnVR.className="babylonVRicon",this._btnVR.id="babylonVRiconbtn",this._btnVR.title="Click to switch to VR";let e=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A":"https://cdn.babylonjs.com/Assets/vrButton.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";e+=".babylonVRicon.vrdisplaypresenting { display: none; }";const t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),this._moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",(()=>{this.isInVRMode?this._scene.getEngine().disableVR():this.enterVR()}));const i=this._scene.getEngine().getHostWindow();i&&(i.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),t.createFallbackVRDeviceOrientationFreeCamera?this._displayVRButton():this._scene.getEngine().onVRDisplayChangedObservable.add((e=>{e.vrDisplay&&this._displayVRButton()})),this._onKeyDown=e=>{27===e.keyCode&&this.isInVRMode&&this.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add((()=>{this._hasEnteredVR&&this.exitVROnDoubleTap&&(this.exitVR(),this._fullscreenVRpresenting&&this._scene.getEngine().exitFullscreen())}),We.kD.POINTERDOUBLETAP,!1),this._onVRDisplayChangedBind=e=>this._onVRDisplayChanged(e),this._onVrDisplayPresentChangeBind=()=>this._onVrDisplayPresentChange(),this._onVRRequestPresentStart=()=>{this._webVRrequesting=!0,this._updateButtonVisibility()},this._onVRRequestPresentComplete=()=>{this._webVRrequesting=!1,this._updateButtonVisibility()},e.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChangedBind),e.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart),e.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete),i.addEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChangeBind),e.onDisposeObservable.add((()=>{this.dispose()})),this._webVRCamera.onControllerMeshLoadedObservable.add((e=>this._onDefaultMeshLoaded(e))),this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected),this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected),this._updateButtonVisibility(),this._circleEase=new j,this._circleEase.setEasingMode(Y.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add((t=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&"mouse"===t.event.pointerType&&(t.type===We.kD.POINTERDOWN?this._cameraGazer._selectionPointerDown():t.type===We.kD.POINTERUP&&this._cameraGazer._selectionPointerUp())})),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes}))}_onDefaultMeshLoaded(e){this._leftController&&this._leftController.webVRController==e&&e.mesh&&this._leftController._setLaserPointerParent(e.mesh),this._rightController&&this._rightController.webVRController==e&&e.mesh&&this._rightController._setLaserPointerParent(e.mesh);try{this.onControllerMeshLoadedObservable.notifyObservers(e)}catch(t){p.Y.Warn("Error in your custom logic onControllerMeshLoaded: "+t)}}get isInVRMode(){return this.xr&&this.webVROptions.useXR&&this.xr.baseExperience.state===Ea.IN_XR||this._webVRpresenting||this._fullscreenVRpresenting}_onVrDisplayPresentChange(){const e=this._scene.getEngine().getVRDevice();if(e){const t=this._webVRpresenting;this._webVRpresenting=e.isPresenting,t&&!this._webVRpresenting&&this.exitVR()}else p.Y.Warn("Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?");this._updateButtonVisibility()}_onVRDisplayChanged(e){this._webVRsupported=e.vrSupported,this._webVRready=!!e.vrDisplay,this._webVRpresenting=e.vrDisplay&&e.vrDisplay.isPresenting,this._updateButtonVisibility()}_moveButtonToBottomRight(){if(this._inputElement&&!this._useCustomVRButton&&this._btnVR){const e=this._inputElement.getBoundingClientRect();this._btnVR.style.top=e.top+e.height-70+"px",this._btnVR.style.left=e.left+e.width-100+"px"}}_displayVRButton(){this._useCustomVRButton||this._btnVRDisplayed||!this._btnVR||(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)}_updateButtonVisibility(){this._btnVR&&!this._useCustomVRButton&&(this._btnVR.className="babylonVRicon",this.isInVRMode?this._btnVR.className+=" vrdisplaypresenting":(this._webVRready&&(this._btnVR.className+=" vrdisplayready"),this._webVRsupported&&(this._btnVR.className+=" vrdisplaysupported"),this._webVRrequesting&&(this._btnVR.className+=" vrdisplayrequesting")))}enterVR(){if(this.xr)this.xr.baseExperience.enterXRAsync("immersive-vr","local-floor",this.xr.renderTarget);else{if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(e){p.Y.Warn("Error in your custom logic onEnteringVR: "+e)}if(this._scene.activeCamera){if(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=o._f.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),this.vrDeviceOrientationCamera.angularSensibility=2e3),this.webVRCamera){const e=this.webVRCamera.deviceRotationQuaternion.toEulerAngles().y,t=o._f.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles().y-e,i=this.webVRCamera.rotationQuaternion.toEulerAngles().y;this.webVRCamera.rotationQuaternion=o._f.FromEulerAngles(0,i+t,0)}this._existingCamera=this._scene.activeCamera,this._existingCamera.angularSensibilityX&&(this._cachedAngularSensibility.angularSensibilityX=this._existingCamera.angularSensibilityX,this._existingCamera.angularSensibilityX=Number.MAX_VALUE),this._existingCamera.angularSensibilityY&&(this._cachedAngularSensibility.angularSensibilityY=this._existingCamera.angularSensibilityY,this._existingCamera.angularSensibilityY=Number.MAX_VALUE),this._existingCamera.angularSensibility&&(this._cachedAngularSensibility.angularSensibility=this._existingCamera.angularSensibility,this._existingCamera.angularSensibility=Number.MAX_VALUE)}this._webVRrequesting||(this._webVRready?this._webVRpresenting||(this._scene.getEngine().onVRRequestPresentComplete.addOnce((e=>{this.onAfterEnteringVRObservable.notifyObservers({success:e})})),this._webVRCamera.position=this._position,this._scene.activeCamera=this._webVRCamera):this._vrDeviceOrientationCamera&&(this._vrDeviceOrientationCamera.position=this._position,this._scene.activeCamera&&(this._vrDeviceOrientationCamera.minZ=this._scene.activeCamera.minZ),this._scene.activeCamera=this._vrDeviceOrientationCamera,this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen),this._updateButtonVisibility(),this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce((()=>{this.onAfterEnteringVRObservable.notifyObservers({success:!0})}))),this._scene.activeCamera&&this._inputElement&&this._scene.activeCamera.attachControl(),this._interactionsEnabled&&this._scene.registerBeforeRender(this._beforeRender),this._displayLaserPointer&&[this._leftController,this._rightController].forEach((e=>{e&&e._activatePointer()})),this._hasEnteredVR=!0)}}exitVR(){if(this.xr)this.xr.baseExperience.exitXRAsync();else if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){p.Y.Warn("Error in your custom logic onExitingVR: "+e)}this._webVRpresenting&&this._scene.getEngine().disableVR(),this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone()),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._deviceOrientationCamera?(this._deviceOrientationCamera.position=this._position,this._scene.activeCamera=this._deviceOrientationCamera,this._cachedAngularSensibility.angularSensibilityX&&(this._deviceOrientationCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._deviceOrientationCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._deviceOrientationCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)):this._existingCamera&&(this._existingCamera.position=this._position,this._scene.activeCamera=this._existingCamera,this._inputElement&&this._scene.activeCamera.attachControl(),this._cachedAngularSensibility.angularSensibilityX&&(this._existingCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._existingCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._existingCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)),this._updateButtonVisibility(),this._interactionsEnabled&&(this._scene.unregisterBeforeRender(this._beforeRender),this._cameraGazer._gazeTracker.isVisible=!1,this._leftController&&(this._leftController._gazeTracker.isVisible=!1),this._rightController&&(this._rightController._gazeTracker.isVisible=!1)),this._scene.getEngine().resize(),[this._leftController,this._rightController].forEach((e=>{e&&e._deactivatePointer()})),this._hasEnteredVR=!1;const t=this._scene.getEngine();t._onVrDisplayPresentChange&&t._onVrDisplayPresentChange()}}get position(){return this._position}set position(e){this._position=e,this._scene.activeCamera&&(this._scene.activeCamera.position=e)}enableInteractions(){if(!this._interactionsEnabled){if(this._interactionsRequested=!0,this.xr)return void(this.xr.baseExperience.state===Ea.IN_XR&&this.xr.pointerSelection.attach());this._leftController&&this._enableInteractionOnController(this._leftController),this._rightController&&this._enableInteractionOnController(this._rightController),this.raySelectionPredicate=e=>e.isVisible&&(e.isPickable||e.name===this._floorMeshName),this.meshSelectionPredicate=()=>!0,this._raySelectionPredicate=e=>!!(this._isTeleportationFloor(e)||-1===e.name.indexOf("gazeTracker")&&-1===e.name.indexOf("teleportationTarget")&&-1===e.name.indexOf("torusTeleportation"))&&this.raySelectionPredicate(e),this._interactionsEnabled=!0}}get _noControllerIsActive(){return!(this._leftController&&this._leftController._activePointer||this._rightController&&this._rightController._activePointer)}_isTeleportationFloor(e){for(let t=0;t-1||this._floorMeshesCollection.push(e))}removeFloorMesh(e){if(!this._floorMeshesCollection)return;const t=this._floorMeshesCollection.indexOf(e);-1!==t&&this._floorMeshesCollection.splice(t,1)}enableTeleportation(e={}){if(!this._teleportationInitialized){if(this._teleportationRequested=!0,this.enableInteractions(),this.webVROptions.useXR&&(e.floorMeshes||e.floorMeshName)){const t=e.floorMeshes||[];if(!t.length){const i=this._scene.getMeshByName(e.floorMeshName);i&&t.push(i)}if(this.xr)return t.forEach((e=>{this.xr.teleportation.addFloorMesh(e)})),void(this.xr.teleportation.attached||this.xr.teleportation.attach());if(!this.xrTestDone){const t=()=>{this.xrTestDone&&(this._scene.unregisterBeforeRender(t),this.xr?this.xr.teleportation.attached||this.xr.teleportation.attach():this.enableTeleportation(e))};return void this._scene.registerBeforeRender(t)}}e.floorMeshName&&(this._floorMeshName=e.floorMeshName),e.floorMeshes&&(this._floorMeshesCollection=e.floorMeshes),e.teleportationMode&&(this._teleportationMode=e.teleportationMode),e.teleportationTime&&e.teleportationTime>0&&(this._teleportationTime=e.teleportationTime),e.teleportationSpeed&&e.teleportationSpeed>0&&(this._teleportationSpeed=e.teleportationSpeed),void 0!==e.easingFunction&&(this._teleportationEasing=e.easingFunction),null!=this._leftController&&this._enableTeleportationOnController(this._leftController),null!=this._rightController&&this._enableTeleportationOnController(this._rightController);const t=new ii.$;t.vignetteColor=new a.HE(0,0,0,0),t.vignetteEnabled=!0,this._postProcessMove=new Ta("postProcessMove",1,this._webVRCamera,void 0,void 0,void 0,void 0,t),this._webVRCamera.detachPostProcess(this._postProcessMove),this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&(this._createTeleportationCircles(),this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor))}}_enableInteractionOnController(e){e.webVRController.mesh&&(e._interactionsEnabled=!0,this.isInVRMode&&this._displayLaserPointer&&e._activatePointer(),this.webVROptions.laserToggle&&e.webVRController.onMainButtonStateChangedObservable.add((t=>{this._displayLaserPointer&&1===t.value&&(e._activePointer?e._deactivatePointer():e._activatePointer(),this.displayGaze&&(e._gazeTracker.isVisible=e._activePointer))})),e.webVRController.onTriggerStateChangedObservable.add((t=>{let i=e;this._noControllerIsActive&&(i=this._cameraGazer),i._pointerDownOnMeshAsked?t.valuethis._padSensibilityUp&&i._selectionPointerDown()})))}_checkTeleportWithRay(e,t){this._teleportationRequestInitiated&&!t._teleportationRequestInitiated||(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.xthis._padSensibilityUp&&t._dpadPressed&&(t._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))}_checkTeleportBackwards(e,t){if(!t._teleportationRequestInitiated)if(e.y>this._padSensibilityUp&&t._dpadPressed){if(!t._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;let e=o._f.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),i=this.currentVRCamera.position;this.currentVRCamera.devicePosition&&this.currentVRCamera.deviceRotationQuaternion&&(e=this.currentVRCamera.deviceRotationQuaternion,i=this.currentVRCamera.devicePosition),e.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,o._f.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),o.P.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);const n=new qe(i,this._workingVector),s=this._scene.pickWithRay(n,this._raySelectionPredicate);s&&s.pickedPoint&&s.pickedMesh&&this._isTeleportationFloor(s.pickedMesh)&&s.distance<5&&this.teleportCamera(s.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1}_enableTeleportationOnController(e){e.webVRController.mesh&&(e._interactionsEnabled||this._enableInteractionOnController(e),e._interactionsEnabled=!0,e._teleportationEnabled=!0,e.webVRController.controllerType===yn.VIVE&&(e._dpadPressed=!1,e.webVRController.onPadStateChangedObservable.add((t=>{e._dpadPressed=t.pressed,e._dpadPressed||(e._rotationLeftAsked=!1,e._rotationRightAsked=!1,e._teleportationBackRequestInitiated=!1)}))),e.webVRController.onPadValuesChangedObservable.add((t=>{this.teleportationEnabled&&(this._checkTeleportBackwards(t,e),this._checkTeleportWithRay(t,e)),this._checkRotate(t,e)})))}_createTeleportationCircles(){this._teleportationTarget=Ga("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;const e=new ma("DynamicTexture",512,this._scene,!0);e.hasAlpha=!0;const t=e.getContext();t.beginPath(),t.arc(256,256,200,0,2*Math.PI,!1),t.fillStyle=this._teleportationFillColor,t.fill(),t.lineWidth=10,t.strokeStyle=this._teleportationBorderColor,t.stroke(),t.closePath(),e.update();const i=new _a("TextPlaneMaterial",this._scene);i.diffuseTexture=e,this._teleportationTarget.material=i;const n=La("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);n.isPickable=!1,n.parent=this._teleportationTarget;const s=new A("animationInnerCircle","position.y",30,A.ANIMATIONTYPE_FLOAT,A.ANIMATIONLOOPMODE_CYCLE),r=[];r.push({frame:0,value:0}),r.push({frame:30,value:.4}),r.push({frame:60,value:0}),s.setKeys(r);const o=new q;o.setEasingMode(Y.EASINGMODE_EASEINOUT),s.setEasingFunction(o),n.animations=[],n.animations.push(s),this._scene.beginAnimation(n,0,60,!0),this._hideTeleportationTarget()}_displayTeleportationTarget(){this._teleportActive=!0,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!0,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!0))}_hideTeleportationTarget(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))}_rotateCamera(e){if(!(this.currentVRCamera instanceof Fn))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];const t=o._f.FromRotationMatrix(o.y3.RotationY(Math.PI/4*this._rotationAngle)),i=new A("animationRotation","rotationQuaternion",90,A.ANIMATIONTYPE_QUATERNION,A.ANIMATIONLOOPMODE_CONSTANT),n=[];n.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),n.push({frame:6,value:t}),i.setKeys(n),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];const s=new A("animationPP","vignetteWeight",90,A.ANIMATIONTYPE_FLOAT,A.ANIMATIONLOOPMODE_CONSTANT),r=[];r.push({frame:0,value:0}),r.push({frame:3,value:4}),r.push({frame:6,value:0}),s.setKeys(r),s.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(s);const a=new A("animationPP2","vignetteStretch",90,A.ANIMATIONTYPE_FLOAT,A.ANIMATIONLOOPMODE_CONSTANT),l=[];l.push({frame:0,value:0}),l.push({frame:3,value:10}),l.push({frame:6,value:0}),a.setKeys(l),a.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(a),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._postProcessMove.samples=4,this._webVRCamera.attachPostProcess(this._postProcessMove),this._scene.beginAnimation(this._postProcessMove,0,6,!1,1,(()=>{this._webVRCamera.detachPostProcess(this._postProcessMove)})),this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}_moveTeleportationSelectorTo(e,t,i){if(e.pickedPoint){t._teleportationRequestInitiated&&(this._displayTeleportationTarget(),this._haloCenter.copyFrom(e.pickedPoint),this._teleportationTarget.position.copyFrom(e.pickedPoint));const n=this._convertNormalToDirectionOfRay(e.getNormal(!0,!1),i);if(n){const e=o.P.Cross(L.RD.Y,n),t=o.P.Cross(n,e);o.P.RotationFromAxisToRef(t,n,e,this._teleportationTarget.rotation)}this._teleportationTarget.position.y+=.1}}teleportCamera(e){if(!(this.currentVRCamera instanceof Fn))return;this.webVRCamera.leftCamera?(this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition),this._workingVector.subtractInPlace(this.webVRCamera.position),e.subtractToRef(this._workingVector,this._workingVector)):this._workingVector.copyFrom(e),this.isInVRMode?this._workingVector.y+=this.webVRCamera.deviceDistanceToRoomGround()*this._webVRCamera.deviceScaleFactor:this._workingVector.y+=this._defaultHeight,this.onBeforeCameraTeleport.notifyObservers(this._workingVector);let t,i;if(this._teleportationMode==ja.TELEPORTATIONMODE_CONSTANTSPEED){i=90;const e=o.P.Distance(this.currentVRCamera.position,this._workingVector);t=this._teleportationSpeed/e}else i=Math.round(90*this._teleportationTime/1e3),t=1;this.currentVRCamera.animations=[];const n=new A("animationCameraTeleportation","position",90,A.ANIMATIONTYPE_VECTOR3,A.ANIMATIONLOOPMODE_CONSTANT),s=[{frame:0,value:this.currentVRCamera.position},{frame:i,value:this._workingVector}];n.setKeys(s),n.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(n),this._postProcessMove.animations=[];const r=Math.round(i/2),a=new A("animationPP","vignetteWeight",90,A.ANIMATIONTYPE_FLOAT,A.ANIMATIONLOOPMODE_CONSTANT),l=[];l.push({frame:0,value:0}),l.push({frame:r,value:8}),l.push({frame:i,value:0}),a.setKeys(l),this._postProcessMove.animations.push(a);const h=new A("animationPP2","vignetteStretch",90,A.ANIMATIONTYPE_FLOAT,A.ANIMATIONLOOPMODE_CONSTANT),c=[];c.push({frame:0,value:0}),c.push({frame:r,value:10}),c.push({frame:i,value:0}),h.setKeys(c),this._postProcessMove.animations.push(h),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._webVRCamera.attachPostProcess(this._postProcessMove),this._scene.beginAnimation(this._postProcessMove,0,i,!1,t,(()=>{this._webVRCamera.detachPostProcess(this._postProcessMove)})),this._scene.beginAnimation(this.currentVRCamera,0,i,!1,t,(()=>{this.onAfterCameraTeleport.notifyObservers(this._workingVector)})),this._hideTeleportationTarget()}_convertNormalToDirectionOfRay(e,t){if(e){Math.acos(o.P.Dot(e,t.direction))l){const e=l;l=a,a=e}return a>0&&a0&&l=0))}_canDoCollision(e,t,i,n){const s=o.P.Distance(this._basePointWorld,e),r=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(s>this._velocityWorldLength+r+t)&&!!((e,t,i,n)=>!(e.x>i.x+n||i.x-n>t.x||e.y>i.y+n||i.y-n>t.y||e.z>i.z+n||i.z-n>t.z))(i,n,this._basePointWorld,this._velocityWorldLength+r)}_testTriangle(e,t,i,n,s,r,a){let l,h=!1;t||(t=[]),t[e]||(t[e]=new Me.J(0,0,0,0),t[e].copyFromPoints(i,n,s));const c=t[e];if(!r&&!c.isFrontFacingTo(this._normalizedVelocity,0))return;const d=c.signedDistanceTo(this._basePoint),u=o.P.Dot(c.normal,this._velocity);if(qa.DoubleSidedCheck&&u>1e-4)return;if(0==u){if(Math.abs(d)>=1)return;h=!0,l=0}else{l=(-1-d)/u;let e=(1-d)/u;if(l>e){const t=e;e=l,l=t}if(l>1||e<0)return;l<0&&(l=0),l>1&&(l=1)}this._collisionPoint.copyFromFloats(0,0,0);let p=!1,f=1;if(h||(this._basePoint.subtractToRef(c.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(l,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,i,n,s,c.normal)&&(p=!0,f=l,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!p){let e=this._velocitySquaredLength;this._basePoint.subtractToRef(i,this._tempVector);let t=2*o.P.Dot(this._velocity,this._tempVector),r=this._tempVector.lengthSquared()-1,a=Ka(e,t,r,f);a.found&&(f=a.root,p=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(n,this._tempVector),t=2*o.P.Dot(this._velocity,this._tempVector),r=this._tempVector.lengthSquared()-1,a=Ka(e,t,r,f),a.found&&(f=a.root,p=!0,this._collisionPoint.copyFrom(n)),this._basePoint.subtractToRef(s,this._tempVector),t=2*o.P.Dot(this._velocity,this._tempVector),r=this._tempVector.lengthSquared()-1,a=Ka(e,t,r,f),a.found&&(f=a.root,p=!0,this._collisionPoint.copyFrom(s)),n.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);let l=this._edge.lengthSquared(),h=o.P.Dot(this._edge,this._velocity),c=o.P.Dot(this._edge,this._baseToVertex);if(e=l*-this._velocitySquaredLength+h*h,t=2*(l*o.P.Dot(this._velocity,this._baseToVertex)-h*c),r=l*(1-this._baseToVertex.lengthSquared())+c*c,a=Ka(e,t,r,f),a.found){const e=(h*a.root-c)/l;e>=0&&e<=1&&(f=a.root,p=!0,this._edge.scaleInPlace(e),i.addToRef(this._edge,this._collisionPoint))}if(s.subtractToRef(n,this._edge),n.subtractToRef(this._basePoint,this._baseToVertex),l=this._edge.lengthSquared(),h=o.P.Dot(this._edge,this._velocity),c=o.P.Dot(this._edge,this._baseToVertex),e=l*-this._velocitySquaredLength+h*h,t=2*(l*o.P.Dot(this._velocity,this._baseToVertex)-h*c),r=l*(1-this._baseToVertex.lengthSquared())+c*c,a=Ka(e,t,r,f),a.found){const e=(h*a.root-c)/l;e>=0&&e<=1&&(f=a.root,p=!0,this._edge.scaleInPlace(e),n.addToRef(this._edge,this._collisionPoint))}if(i.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),l=this._edge.lengthSquared(),h=o.P.Dot(this._edge,this._velocity),c=o.P.Dot(this._edge,this._baseToVertex),e=l*-this._velocitySquaredLength+h*h,t=2*(l*o.P.Dot(this._velocity,this._baseToVertex)-h*c),r=l*(1-this._baseToVertex.lengthSquared())+c*c,a=Ka(e,t,r,f),a.found){const e=(h*a.root-c)/l;e>=0&&e<=1&&(f=a.root,p=!0,this._edge.scaleInPlace(e),s.addToRef(this._edge,this._collisionPoint))}}if(p){const e=f*f*this._velocitySquaredLength;(!this.collisionFound||e=n)return void s.copyFrom(e);const a=r?r.collisionMask:i.collisionMask;i._initialize(e,t,o);const l=r&&r.surroundingMeshes||this._scene.meshes;for(let h=0;hnew $a;i(7901);var Qa,Za=i(3525);class Ja{constructor(e,t,i,n=""){var s,o;let a;this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new r.y$,this.onErrorObservable=new r.y$,this.onBindObservable=new r.y$,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=Qt.x.WGSL,this.name=e,this._key=n,this._engine=i,this.uniqueId=Ja._UniqueIdSeed++,this.defines=null!==(s=t.defines)&&void 0!==s?s:"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=null!==(o=t.entryPoint)&&void 0!==o?o:"main",this._shaderStore=Ht.v.GetShadersStore(this._shaderLanguage),this._shaderRepository=Ht.v.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=Ht.v.GetIncludesShadersStore(this._shaderLanguage);const l=(0,_e.CG)()?this._engine.getHostDocument():null;e.computeSource?a="source:"+e.computeSource:e.computeElement?(a=l?l.getElementById(e.computeElement):null,a||(a=e.computeElement)):a=e.compute||e;const h={defines:this.defines.split("\n"),indexParameters:void 0,isFragment:!1,shouldUseHighPrecisionShader:!1,processor:null,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:this._shaderRepository,includesShadersStore:this._includeShaderStore,version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:null,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer};this._loadShader(a,"Compute","",(i=>{Za.L.Initialize(h),Za.L.PreProcess(i,h,(n=>{this._rawComputeSourceCode=i,t.processFinalCode&&(n=t.processFinalCode(n));const s=Za.L.Finalize(n,"",h);this._useFinalCode(s.vertexCode,e)}),this._engine)}))}_useFinalCode(e,t){if(t){const i=t.computeElement||t.compute||t.spectorName||t;this._computeSourceCode="//#define SHADER_NAME compute:"+i+"\n"+e}else this._computeSourceCode=e;this._prepareEffect()}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch(e){return!1}}_isReadyInternal(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getCompilationError(){return this._compilationError}executeWhenCompiled(e){this.isReady()?e(this):(this.onCompileObservable.add((t=>{e(t)})),this._pipelineContext&&!this._pipelineContext.isAsync||setTimeout((()=>{this._checkIsReady(null)}),16))}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){return void this._processCompilationErrors(t,e)}setTimeout((()=>{this._checkIsReady(e)}),16)}_loadShader(e,t,i,n){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement){return void n((0,_e.v)(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)))}if(this._shaderStore[e+t+"Shader"])return void n(this._shaderStore[e+t+"Shader"]);if(i&&this._shaderStore[e+i+"Shader"])return void n(this._shaderStore[e+i+"Shader"]);let s;s="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:this._shaderRepository+e,this._engine._loadFile(s+"."+t.toLowerCase()+".fx",n)}get computeSourceCode(){var e,t;return this._computeSourceCodeOverride?this._computeSourceCodeOverride:null!==(t=null===(e=this._pipelineContext)||void 0===e?void 0:e._getComputeShaderCode())&&void 0!==t?t:this._computeSourceCode}get rawComputeSourceCode(){return this._rawComputeSourceCode}_prepareEffect(){const e=this.defines,t=this._pipelineContext;this._isReady=!1;try{const i=this._engine;this._pipelineContext=i.createComputePipelineContext(),this._pipelineContext._name=this._key,i._prepareComputePipelineContext(this._pipelineContext,this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._computeSourceCode,this._rawComputeSourceCode,this._computeSourceCodeOverride?null:e,this._entryPoint),i._executeWhenComputeStateIsCompiled(this._pipelineContext,(()=>{this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),t&&this.getEngine()._deleteComputePipelineContext(t)})),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(i){this._processCompilationErrors(i,t)}}_getShaderCodeAndErrorLine(e,t){const i=/COMPUTE SHADER ERROR: 0:(\d+?):/;let n=null;if(t&&e){const s=t.match(i);if(s&&2===s.length){const t=parseInt(s[1]),i=e.split("\n",-1);i.length>=t&&(n=`Offending line [${t}] in compute code: ${i[t-1]}`)}}return[e,n]}_processCompilationErrors(e,t=null){var i;if(this._compilationError=e.message,p.Y.Error("Unable to compile compute effect:"),p.Y.Error("Defines:\r\n"+this.defines),Ja.LogShaderCodeOnCompilationError){let e=null,t=null;(null===(i=this._pipelineContext)||void 0===i?void 0:i._getComputeShaderCode())&&([t,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getComputeShaderCode(),this._compilationError),t&&(p.Y.Error("Compute code:"),p.Y.Error(t))),e&&p.Y.Error(e)}p.Y.Error("Error: "+this._compilationError),t&&(this._pipelineContext=t,this._isReady=!0,this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this))}dispose(){this._pipelineContext&&this._pipelineContext.dispose(),this._engine._releaseComputeEffect(this)}static RegisterShader(e,t){Ht.v.GetShadersStore(Qt.x.WGSL)[`${e}ComputeShader`]=t}}Ja._UniqueIdSeed=0,Ja.LogShaderCodeOnCompilationError=!0,function(e){e[e.Texture=0]="Texture",e[e.StorageTexture=1]="StorageTexture",e[e.UniformBuffer=2]="UniformBuffer",e[e.StorageBuffer=3]="StorageBuffer",e[e.TextureWithoutSampler=4]="TextureWithoutSampler",e[e.Sampler=5]="Sampler"}(Qa||(Qa={})),Ue.B.prototype.createComputeEffect=function(e,t){throw new Error("createComputeEffect: This engine does not support compute shaders!")},Ue.B.prototype.createComputePipelineContext=function(){throw new Error("createComputePipelineContext: This engine does not support compute shaders!")},Ue.B.prototype.createComputeContext=function(){},Ue.B.prototype.computeDispatch=function(e,t,i,n,s,r,o){throw new Error("computeDispatch: This engine does not support compute shaders!")},Ue.B.prototype.areAllComputeEffectsReady=function(){return!0},Ue.B.prototype.releaseComputeEffects=function(){},Ue.B.prototype._prepareComputePipelineContext=function(e,t,i,n,s){},Ue.B.prototype._rebuildComputeEffects=function(){},Ue.B.prototype._executeWhenComputeStateIsCompiled=function(e,t){t()},Ue.B.prototype._releaseComputeEffect=function(e){},Ue.B.prototype._deleteComputePipelineContext=function(e){};var el=i(2931);class tl{get options(){return this._options}get shaderPath(){return this._shaderPath}constructor(e,t,i,n={}){this._bindings={},this._samplers={},this._contextIsDirty=!1,this.onCompiled=null,this.onError=null,this.name=e,this._engine=t,this.uniqueId=xt.K.UniqueId,this._engine.getCaps().supportComputeShaders?n.bindingsMapping?(this._context=t.createComputeContext(),this._shaderPath=i,this._options=Object.assign({bindingsMapping:{},defines:[]},n)):p.Y.Error("You must provide the binding mappings as browsers don't support reflection for wgsl shaders yet!"):p.Y.Error("This engine does not support compute shaders!")}getClassName(){return"ComputeShader"}setTexture(e,t,i=!0){const n=this._bindings[e];this._bindings[e]={type:i?Qa.Texture:Qa.TextureWithoutSampler,object:t,indexInGroupEntries:null==n?void 0:n.indexInGroupEntries},this._contextIsDirty||(this._contextIsDirty=!n||n.object!==t||n.type!==this._bindings[e].type)}setStorageTexture(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:Qa.StorageTexture,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setUniformBuffer(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:Qa.UniformBuffer,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setStorageBuffer(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:Qa.StorageBuffer,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setTextureSampler(e,t){const i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||!t.compareSampler(i.object)),this._bindings[e]={type:Qa.Sampler,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}isReady(){let e=this._effect;for(const s in this._bindings){const e=this._bindings[s],t=e.type,i=e.object;switch(t){case Qa.Texture:case Qa.TextureWithoutSampler:case Qa.StorageTexture:if(!i.isReady())return!1;break}}const t=[],i=this._shaderPath;if(this._options.defines)for(let s=0;s{const r=()=>{this.dispatch(e,t,i)?s():setTimeout(r,n)};r()}))}serialize(){const e=E.p4.Serialize(this);e.options=this._options,e.shaderPath=this._shaderPath,e.bindings={},e.textures={};for(const t in this._bindings){const i=this._bindings[t],n=i.object;switch(i.type){case Qa.Texture:case Qa.TextureWithoutSampler:case Qa.StorageTexture:{const s=n.serialize();s&&(e.textures[t]=s,e.bindings[t]={type:i.type});break}case Qa.UniformBuffer:}}return e}static Parse(e,t,i){const n=E.p4.Parse((()=>new tl(e.name,t.getEngine(),e.shaderPath,e.options)),e,t,i);for(const s in e.textures){const r=e.bindings[s],o=Le.Parse(e.textures[s],t,i);r.type===Qa.Texture?n.setTexture(s,o):r.type===Qa.TextureWithoutSampler?n.setTexture(s,o,!1):n.setStorageTexture(s,o)}return n}}(0,oe.gn)([(0,E.qC)()],tl.prototype,"name",void 0),(0,l.H)("BABYLON.ComputeShader",tl);var il,nl,sl,rl=i(3773),ol=i(2789),al=i(2897);class ll{constructor(e,t,i,n,s,r){this.entries=new Array,this._boundingVectors=new Array,this._capacity=i,this._depth=n,this._maxDepth=s,this._creationFunc=r,this._minPoint=e,this._maxPoint=t,this._boundingVectors.push(e.clone()),this._boundingVectors.push(t.clone()),this._boundingVectors.push(e.clone()),this._boundingVectors[2].x=t.x,this._boundingVectors.push(e.clone()),this._boundingVectors[3].y=t.y,this._boundingVectors.push(e.clone()),this._boundingVectors[4].z=t.z,this._boundingVectors.push(t.clone()),this._boundingVectors[5].z=e.z,this._boundingVectors.push(t.clone()),this._boundingVectors[6].x=e.x,this._boundingVectors.push(t.clone()),this._boundingVectors[7].y=e.y}get capacity(){return this._capacity}get minPoint(){return this._minPoint}get maxPoint(){return this._maxPoint}addEntry(e){if(this.blocks)for(let t=0;tthis.capacity&&this._depth-1&&this.entries.splice(t,1)}addEntries(e){for(let t=0;t{const i=e.getBoundingInfo();!e.isBlocked&&i.boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},hl.CreationFuncForSubMeshes=(e,t)=>{e.getBoundingInfo().boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},N.x.prototype.createOrUpdateSelectionOctree=function(e=64,t=2){let i=this._getComponent(Se.l.NAME_OCTREE);i||(i=new cl(this),this._addComponent(i)),this._selectionOctree||(this._selectionOctree=new hl(hl.CreationFuncForMeshes,e,t));const n=this.getWorldExtends();return this._selectionOctree.update(n.min,n.max,this.meshes),this._selectionOctree},Object.defineProperty(N.x.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0}),ie.x.prototype.createOrUpdateSubmeshesOctree=function(e=64,t=2){const i=this.getScene();let n=i._getComponent(Se.l.NAME_OCTREE);n||(n=new cl(i),i._addComponent(n)),this._submeshesOctree||(this._submeshesOctree=new hl(hl.CreationFuncForSubMeshes,e,t)),this.computeWorldMatrix(!0);const s=this.getBoundingInfo().boundingBox;return this._submeshesOctree.update(s.minimumWorld,s.maximumWorld,this.subMeshes),this._submeshesOctree};class cl{constructor(e){this.name=Se.l.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new qe(o.P.Zero(),new o.P(1,1,1)),(e=e||m.l.LastCreatedScene)&&(this.scene=e,this.scene.getActiveMeshCandidates=this.getActiveMeshCandidates.bind(this),this.scene.getActiveSubMeshCandidates=this.getActiveSubMeshCandidates.bind(this),this.scene.getCollidingSubMeshCandidates=this.getCollidingSubMeshCandidates.bind(this),this.scene.getIntersectingSubMeshCandidates=this.getIntersectingSubMeshCandidates.bind(this))}register(){this.scene.onMeshRemovedObservable.add((e=>{const t=this.scene.selectionOctree;if(null!=t){const i=t.dynamicContent.indexOf(e);-1!==i&&t.dynamicContent.splice(i,1)}})),this.scene.onMeshImportedObservable.add((e=>{const t=this.scene.selectionOctree;null!=t&&t.addMesh(e)}))}getActiveMeshCandidates(){var e;return(null===(e=this.scene._selectionOctree)||void 0===e?void 0:e.select(this.scene.frustumPlanes))||this.scene._getDefaultMeshCandidates()}getActiveSubMeshCandidates(e){if(e._submeshesOctree&&e.useOctreeForRenderingSelection){return e._submeshesOctree.select(this.scene.frustumPlanes)}return this.scene._getDefaultSubMeshCandidates(e)}getIntersectingSubMeshCandidates(e,t){if(e._submeshesOctree&&e.useOctreeForPicking){qe.TransformToRef(t,e.getWorldMatrix(),this._tempRay);return e._submeshesOctree.intersectsRay(this._tempRay)}return this.scene._getDefaultSubMeshCandidates(e)}getCollidingSubMeshCandidates(e,t){if(e._submeshesOctree&&e.useOctreeForCollisions){const i=t._velocityWorldLength+Math.max(t._radius.x,t._radius.y,t._radius.z);return e._submeshesOctree.intersects(t._basePointWorld,i)}return this.scene._getDefaultSubMeshCandidates(e)}rebuild(){}dispose(){}}class dl{getRenderCamera(e){if(this._renderCamera)return this._renderCamera;{let t;return t=this.originalScene.activeCameras&&this.originalScene.activeCameras.length>1?this.originalScene.activeCameras[this.originalScene.activeCameras.length-1]:this.originalScene.activeCamera,e&&t&&t.isRigCamera?t.rigParent:t}}setRenderCamera(e){this._renderCamera=e}_getSharedGizmoLight(){return this._sharedGizmoLight||(this._sharedGizmoLight=new Os("shared gizmo light",new o.P(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=a.Wo.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return null==dl._DefaultUtilityLayer?dl._CreateDefaultUtilityLayerFromScene(m.l.LastCreatedScene):dl._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return dl._DefaultUtilityLayer=new dl(e),dl._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce((()=>{dl._DefaultUtilityLayer=null})),dl._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return null==dl._DefaultKeepDepthUtilityLayer&&(dl._DefaultKeepDepthUtilityLayer=new dl(m.l.LastCreatedScene),dl._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,dl._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce((()=>{dl._DefaultKeepDepthUtilityLayer=null}))),dl._DefaultKeepDepthUtilityLayer}constructor(e,t=!0){this.originalScene=e,this._pointerCaptures={},this._lastPointerEvents={},this._sharedGizmoLight=null,this._renderCamera=null,this.pickUtilitySceneFirst=!0,this.shouldRender=!0,this.onlyCheckPointerDownEvents=!0,this.processAllEvents=!1,this.pickingEnabled=!0,this.onPointerOutObservable=new r.y$,this.utilityLayerScene=new N.x(e.getEngine(),{virtual:!0}),this.utilityLayerScene.useRightHandedSystem=e.useRightHandedSystem,this.utilityLayerScene._allowPostProcessClearColor=!1,this.utilityLayerScene.postProcessesEnabled=!1,this.utilityLayerScene.detachControl(),t&&(this._originalPointerObserver=e.onPrePointerObservable.add((t=>{if(!this.utilityLayerScene.activeCamera)return;if(!this.pickingEnabled)return;if(!this.processAllEvents&&t.type!==We.kD.POINTERMOVE&&t.type!==We.kD.POINTERUP&&t.type!==We.kD.POINTERDOWN&&t.type!==We.kD.POINTERDOUBLETAP)return;this.utilityLayerScene.pointerX=e.pointerX,this.utilityLayerScene.pointerY=e.pointerY;const i=t.event;if(e.isPointerCaptured(i.pointerId))return void(this._pointerCaptures[i.pointerId]=!1);const n=i=>{let n=null;if(t.nearInteractionPickingInfo)n=t.nearInteractionPickingInfo.pickedMesh.getScene()==i?t.nearInteractionPickingInfo:new je.p;else if(i!==this.utilityLayerScene&&t.originalPickingInfo)n=t.originalPickingInfo;else{let s=null;this._renderCamera&&(s=i._activeCamera,i._activeCamera=this._renderCamera,t.ray=null),n=t.ray?i.pickWithRay(t.ray):i.pick(e.pointerX,e.pointerY),s&&(i._activeCamera=s)}return n},s=n(this.utilityLayerScene);if(!t.ray&&s&&(t.ray=s.ray),this.utilityLayerScene.onPrePointerObservable.notifyObservers(t),this.onlyCheckPointerDownEvents&&t.type!=We.kD.POINTERDOWN)return t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new We.R5(t.type,t.event,s),t.type),void(t.type===We.kD.POINTERUP&&this._pointerCaptures[i.pointerId]&&(this._pointerCaptures[i.pointerId]=!1));if(this.utilityLayerScene.autoClearDepthAndStencil||this.pickUtilitySceneFirst)s&&s.hit&&(t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new We.R5(t.type,t.event,s),t.type),t.skipOnPointerObservable=!0);else{const i=n(e),r=t.event;i&&s&&(0===s.distance&&i.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,r),t.skipOnPointerObservable=!0):t.type===We.kD.POINTERDOWN?this._pointerCaptures[r.pointerId]=!0:t.type!==We.kD.POINTERMOVE&&t.type!==We.kD.POINTERUP||(this._lastPointerEvents[r.pointerId]&&(this.onPointerOutObservable.notifyObservers(r.pointerId),delete this._lastPointerEvents[r.pointerId]),this._notifyObservers(t,i,r)):!this._pointerCaptures[r.pointerId]&&(s.distance0)):!this._pointerCaptures[r.pointerId]&&s.distance>=i.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,r),t.skipOnPointerObservable=!0):(t.type!==We.kD.POINTERMOVE&&t.type!==We.kD.POINTERUP||this._lastPointerEvents[r.pointerId]&&(this.onPointerOutObservable.notifyObservers(r.pointerId),delete this._lastPointerEvents[r.pointerId]),this._notifyObservers(t,s,r))),t.type===We.kD.POINTERUP&&this._pointerCaptures[r.pointerId]&&(this._pointerCaptures[r.pointerId]=!1))}})),this._originalPointerObserver&&e.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterRenderCameraObservable.add((e=>{this.shouldRender&&e==this.getRenderCamera()&&this.render()})),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add((()=>{this.dispose()})),this._updateCamera()}_notifyObservers(e,t,i){e.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new We.R5(e.type,e.event,t),e.type),this._lastPointerEvents[i.pointerId]=!0)}render(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){const e=this.utilityLayerScene.activeCamera.getScene(),t=this.utilityLayerScene.activeCamera;t._scene=this.utilityLayerScene,t.leftCamera&&(t.leftCamera._scene=this.utilityLayerScene),t.rightCamera&&(t.rightCamera._scene=this.utilityLayerScene),this.utilityLayerScene.render(!1),t._scene=e,t.leftCamera&&(t.leftCamera._scene=e),t.rightCamera&&(t.rightCamera._scene=e)}}dispose(){this.onPointerOutObservable.clear(),this._afterRenderObserver&&this.originalScene.onAfterCameraRenderObservable.remove(this._afterRenderObserver),this._sceneDisposeObserver&&this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver),this._originalPointerObserver&&this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver),this.utilityLayerScene.dispose()}_updateCamera(){this.utilityLayerScene.cameraToUseForPointers=this.getRenderCamera(),this.utilityLayerScene.activeCamera=this.getRenderCamera()}}dl._DefaultUtilityLayer=null,dl._DefaultKeepDepthUtilityLayer=null,function(e){e[e.Origin=0]="Origin",e[e.Pivot=1]="Pivot"}(il||(il={})),function(e){e[e.World=0]="World",e[e.Local=1]="Local"}(nl||(nl={}));class ul{set scaleRatio(e){this._scaleRatio=e}get scaleRatio(){return this._scaleRatio}get isHovered(){return this._isHovered}get attachedMesh(){return this._attachedMesh}set attachedMesh(e){this._attachedMesh=e,e&&(this._attachedNode=e),this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}get attachedNode(){return this._attachedNode}set attachedNode(e){this._attachedNode=e,this._attachedMesh=null,this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}setCustomMesh(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._rootMesh.getChildMeshes().forEach((e=>{e.dispose()})),e.parent=this._rootMesh,this._customMeshSet=!0}set updateGizmoRotationToMatchAttachedMesh(e){this._updateGizmoRotationToMatchAttachedMesh=e}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this._updateGizmoPositionToMatchAttachedMesh=e}get updateGizmoPositionToMatchAttachedMesh(){return this._updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){this._coordinatesMode=e;const t=e==nl.Local;this.updateGizmoRotationToMatchAttachedMesh=t,this.updateGizmoPositionToMatchAttachedMesh=t}get coordinatesMode(){return this._coordinatesMode}set updateScale(e){this._updateScale=e}get updateScale(){return this._updateScale}_attachedNodeChanged(e){}constructor(e=dl.DefaultUtilityLayer){this.gizmoLayer=e,this._attachedMesh=null,this._attachedNode=null,this._customRotationQuaternion=null,this._scaleRatio=1,this._isHovered=!1,this._customMeshSet=!1,this._updateGizmoRotationToMatchAttachedMesh=!0,this._updateGizmoPositionToMatchAttachedMesh=!0,this._anchorPoint=il.Origin,this._updateScale=!0,this._coordinatesMode=nl.Local,this._interactionsEnabled=!0,this._rightHandtoLeftHandMatrix=o.y3.RotationY(Math.PI),this._rootMesh=new ee.Kj("gizmoRootNode",e.utilityLayerScene),this._rootMesh.rotationQuaternion=o._f.Identity(),this._beforeRenderObserver=this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add((()=>{this._update()}))}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e}_update(){if(this.attachedNode){let e=this.attachedNode;if(this.attachedMesh&&(e=this.attachedMesh||this.attachedNode),this.updateGizmoPositionToMatchAttachedMesh)if(this.anchorPoint==il.Pivot&&e.getAbsolutePivotPoint){const t=e.getAbsolutePivotPoint();this._rootMesh.position.copyFrom(t)}else{const t=e.getWorldMatrix().getRow(3),i=t?t.toVector3():new o.P(0,0,0);this._rootMesh.position.copyFrom(i)}if(this.updateGizmoRotationToMatchAttachedMesh){const t=e._isMesh||"AbstractMesh"===e.getClassName()||"TransformNode"===e.getClassName()||"InstancedMesh"===e.getClassName()?e:void 0;e.getWorldMatrix().decompose(void 0,this._rootMesh.rotationQuaternion,void 0,ul.PreserveScaling?t:void 0)}else this._customRotationQuaternion?this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion):this._rootMesh.rotationQuaternion.set(0,0,0,1);if(this.updateScale){const t=this.gizmoLayer.utilityLayerScene.activeCamera;let i=t.globalPosition;t.devicePosition&&(i=t.devicePosition),this._rootMesh.position.subtractToRef(i,o.jp.Vector3[0]);let n=this.scaleRatio;if(t.mode==ce.V.ORTHOGRAPHIC_CAMERA){if(t.orthoTop&&t.orthoBottom){n*=t.orthoTop-t.orthoBottom}}else{const e=t.getScene().useRightHandedSystem?o.P.RightHandedForwardReadOnly:o.P.LeftHandedForwardReadOnly,i=t.getDirection(e);n*=o.P.Dot(o.jp.Vector3[0],i)}this._rootMesh.scaling.setAll(n),e._getWorldMatrixDeterminant()<0&&!ul.PreserveScaling&&(this._rootMesh.scaling.y*=-1)}else this._rootMesh.scaling.setAll(this.scaleRatio)}}_handlePivot(){const e=this._attachedNode;e.isUsingPivotMatrix&&e.isUsingPivotMatrix()&&e.position&&e.getWorldMatrix().setTranslation(e.position)}_matrixChanged(){if(this._attachedNode)if(this._attachedNode._isCamera){const e=this._attachedNode;let t,i;if(e.parent){const i=o.jp.Matrix[1];e.parent._worldMatrix.invertToRef(i),this._attachedNode._worldMatrix.multiplyToRef(i,o.jp.Matrix[0]),t=o.jp.Matrix[0]}else t=this._attachedNode._worldMatrix;e.getScene().useRightHandedSystem?(this._rightHandtoLeftHandMatrix.multiplyToRef(t,o.jp.Matrix[1]),i=o.jp.Matrix[1]):i=t,i.decompose(o.jp.Vector3[1],o.jp.Quaternion[0],o.jp.Vector3[0]);if("FreeCamera"===this._attachedNode.getClassName()||"FlyCamera"===this._attachedNode.getClassName()||"ArcFollowCamera"===this._attachedNode.getClassName()||"TargetCamera"===this._attachedNode.getClassName()||"TouchCamera"===this._attachedNode.getClassName()||"UniversalCamera"===this._attachedNode.getClassName()){const e=this._attachedNode;e.rotation=o.jp.Quaternion[0].toEulerAngles(),e.rotationQuaternion&&(e.rotationQuaternion.copyFrom(o.jp.Quaternion[0]),e.rotationQuaternion.normalize())}e.position.copyFrom(o.jp.Vector3[0])}else if(this._attachedNode._isMesh||"AbstractMesh"===this._attachedNode.getClassName()||"TransformNode"===this._attachedNode.getClassName()||"InstancedMesh"===this._attachedNode.getClassName()){const e=this._attachedNode;if(e.parent){const t=o.jp.Matrix[0],i=o.jp.Matrix[1];e.parent.getWorldMatrix().invertToRef(t),this._attachedNode.getWorldMatrix().multiplyToRef(t,i),i.decompose(o.jp.Vector3[0],o.jp.Quaternion[0],e.position,ul.PreserveScaling?e:void 0)}else this._attachedNode._worldMatrix.decompose(o.jp.Vector3[0],o.jp.Quaternion[0],e.position,ul.PreserveScaling?e:void 0);o.jp.Vector3[0].scaleInPlace(1/e.scalingDeterminant),e.scaling.copyFrom(o.jp.Vector3[0]),e.billboardMode||(e.rotationQuaternion?(e.rotationQuaternion.copyFrom(o.jp.Quaternion[0]),e.rotationQuaternion.normalize()):e.rotation=o.jp.Quaternion[0].toEulerAngles())}else if("Bone"===this._attachedNode.getClassName()){const e=this._attachedNode,t=e.getParent();if(t){const i=o.jp.Matrix[0],n=o.jp.Matrix[1];t.getFinalMatrix().invertToRef(i),e.getFinalMatrix().multiplyToRef(i,n);e.getLocalMatrix().copyFrom(n)}else{e.getLocalMatrix().copyFrom(e.getFinalMatrix())}e.markAsDirty()}else{const e=this._attachedNode;if(e.getTypeID){const t=e.getTypeID();if(t===he.LIGHTTYPEID_DIRECTIONALLIGHT||t===he.LIGHTTYPEID_SPOTLIGHT||t===he.LIGHTTYPEID_POINTLIGHT){const t=e.parent;if(t){const i=o.jp.Matrix[0],n=o.jp.Matrix[1];t.getWorldMatrix().invertToRef(i),e.getWorldMatrix().multiplyToRef(i,n),n.decompose(void 0,o.jp.Quaternion[0],o.jp.Vector3[0])}else this._attachedNode._worldMatrix.decompose(void 0,o.jp.Quaternion[0],o.jp.Vector3[0]);e.position=new o.P(o.jp.Vector3[0].x,o.jp.Vector3[0].y,o.jp.Vector3[0].z),e.direction&&(e.direction=new o.P(e.direction.x,e.direction.y,e.direction.z))}}}}_setGizmoMeshMaterial(e,t){e&&e.forEach((e=>{e.material=t,e.color&&(e.color=t.diffuseColor)}))}static GizmoAxisPointerObserver(e,t){let i=!1;return e.utilityLayerScene.onPointerObservable.add((e=>{var n,s;if(e.pickInfo){if(e.type===We.kD.POINTERMOVE){if(i)return;t.forEach((t=>{var i,n;if(t.colliderMeshes&&t.gizmoMeshes){const s=-1!=(null===(i=t.colliderMeshes)||void 0===i?void 0:i.indexOf(null===(n=null==e?void 0:e.pickInfo)||void 0===n?void 0:n.pickedMesh)),r=t.dragBehavior.enabled?s||t.active?t.hoverMaterial:t.material:t.disableMaterial;t.gizmoMeshes.forEach((e=>{e.material=r,e.color&&(e.color=r.diffuseColor)}))}}))}if(e.type===We.kD.POINTERDOWN&&t.has(null===(n=e.pickInfo.pickedMesh)||void 0===n?void 0:n.parent)){i=!0;t.get(null===(s=e.pickInfo.pickedMesh)||void 0===s?void 0:s.parent).active=!0,t.forEach((t=>{var i,n;const s=(-1!=(null===(i=t.colliderMeshes)||void 0===i?void 0:i.indexOf(null===(n=null==e?void 0:e.pickInfo)||void 0===n?void 0:n.pickedMesh))||t.active)&&t.dragBehavior.enabled?t.hoverMaterial:t.disableMaterial;t.gizmoMeshes.forEach((e=>{e.material=s,e.color&&(e.color=s.diffuseColor)}))}))}e.type===We.kD.POINTERUP&&t.forEach((e=>{e.active=!1,i=!1,e.gizmoMeshes.forEach((t=>{t.material=e.dragBehavior.enabled?e.material:e.disableMaterial,t.color&&(t.color=e.material.diffuseColor)}))}))}}))}dispose(){this._rootMesh.dispose(),this._beforeRenderObserver&&this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver)}}ul.PreserveScaling=!1;Object.defineProperty(N.x.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new pl(this)),this._debugLayer},enumerable:!0,configurable:!0}),function(e){e[e.Properties=0]="Properties",e[e.Debug=1]="Debug",e[e.Statistics=2]="Statistics",e[e.Tools=3]="Tools",e[e.Settings=4]="Settings"}(sl||(sl={}));class pl{get onPropertyChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new r.y$),this._onPropertyChangedObservable)}get onSelectionChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new r.y$),this._onSelectionChangedObservable)}constructor(e){this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||m.l.LastCreatedScene,this._scene&&this._scene.onDisposeObservable.add((()=>{this._scene._debugLayer&&this._scene._debugLayer.hide()}))}_createInspector(e){if(this.isVisible())return;if(this._onPropertyChangedObservable){for(const e of this._onPropertyChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(e);this._onPropertyChangedObservable.clear(),this._onPropertyChangedObservable=void 0}if(this._onSelectionChangedObservable){for(const e of this._onSelectionChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(e);this._onSelectionChangedObservable.clear(),this._onSelectionChangedObservable=void 0}const t=Object.assign({overlay:!1,showExplorer:!0,showInspector:!0,embedMode:!1,handleResize:!0,enablePopup:!0},e);this.BJSINSPECTOR=this.BJSINSPECTOR||this._getGlobalInspector(),this.BJSINSPECTOR.Inspector.Show(this._scene,t)}select(e,t){this.BJSINSPECTOR&&(t&&("[object String]"==Object.prototype.toString.call(t)?this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(t):this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(t)),this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(e))}_getGlobalInspector(){return"undefined"!=typeof INSPECTOR?INSPECTOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.Inspector?BABYLON:void 0}isVisible(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.IsVisible}hide(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.Hide()}setAsActiveScene(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector._SetNewScene(this._scene)}show(e){return new Promise((t=>{if(void 0===this.BJSINSPECTOR){const i=e&&e.inspectorURL?e.inspectorURL:pl.InspectorURL;se.w1.LoadScript(i,(()=>{this._createInspector(e),t(this)}))}else this._createInspector(e),t(this)}))}}function fl(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 s=[];const r=e.width||e.size||1,l=e.height||e.size||1,h=e.depth||e.size||1,c=e.wrap||!1;let d=void 0===e.topBaseAt?1:e.topBaseAt,u=void 0===e.bottomBaseAt?0:e.bottomBaseAt;d=(d+4)%4,u=(u+4)%4;let p=[2,0,3,1][d],f=[2,0,1,3][u],_=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,1];if(c){t=[2,3,0,2,0,1,4,5,6,4,6,7,9,10,11,9,11,8,12,14,15,12,13,14],_=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,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],s=[22,23,20,21];for(;p>0;)e.unshift(e.pop()),n.unshift(n.pop()),p--;for(;f>0;)i.unshift(i.pop()),s.unshift(s.pop()),f--;e=e.flat(),i=i.flat(),_=_.concat(e).concat(i),t.push(n[0],n[2],n[3],n[0],n[1],n[2]),t.push(s[0],s[2],s[3],s[0],s[1],s[2])}const m=[r/2,l/2,h/2];s=_.reduce(((e,t,i)=>e.concat(t*m[i%3])),[]);const g=0===e.sideOrientation?0:e.sideOrientation||Qe.x.DEFAULTSIDE,v=e.faceUV||new Array(6),T=e.faceColors,S=[];for(let x=0;x<6;x++)void 0===v[x]&&(v[x]=new o.Lt(0,0,1,1)),T&&void 0===T[x]&&(T[x]=new a.HE(1,1,1,1));for(let o=0;o<6;o++)if(n.push(v[o].z,we.e.UseOpenGLOrientationForUV?1-v[o].w:v[o].w),n.push(v[o].x,we.e.UseOpenGLOrientationForUV?1-v[o].w:v[o].w),n.push(v[o].x,we.e.UseOpenGLOrientationForUV?1-v[o].y:v[o].y),n.push(v[o].z,we.e.UseOpenGLOrientationForUV?1-v[o].y:v[o].y),T)for(let e=0;e<4;e++)S.push(T[o].r,T[o].g,T[o].b,T[o].a);Qe.x._ComputeSides(g,s,t,i,n,e.frontUVs,e.backUVs);const E=new Qe.x;if(E.indices=t,E.positions=s,E.normals=i,E.uvs=n,T){const e=g===Qe.x.DOUBLESIDE?S.concat(S):S;E.colors=e}return E}function _l(e,t={},i=null){const n=new ee.Kj(e,i);t.sideOrientation=ee.Kj._GetDefaultSideOrientation(t.sideOrientation),n._originalBuilderSideOrientation=t.sideOrientation;return fl(t).applyToMesh(n,t.updatable),n}pl.InspectorURL=`https://unpkg.com/babylonjs-inspector@${fe.D.Version}/babylon.inspector.bundle.js`;function ml(e){const t=e.segments||32,i=e.diameterX||e.diameter||1,n=e.diameterY||e.diameter||1,s=e.diameterZ||e.diameter||1,r=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,a=e.slice&&e.slice<=0?1:e.slice||1,l=0===e.sideOrientation?0:e.sideOrientation||Qe.x.DEFAULTSIDE,h=!!e.dedupTopBottomIndices,c=new o.P(i/2,n/2,s/2),d=2+t,u=2*d,p=[],f=[],_=[],m=[];for(let v=0;v<=d;v++){const e=v/d,t=e*Math.PI*a;for(let i=0;i<=u;i++){const n=i/u,s=n*Math.PI*2*r,a=o.y3.RotationZ(-t),l=o.y3.RotationY(s),h=o.P.TransformCoordinates(o.P.Up(),a),d=o.P.TransformCoordinates(h,l),p=d.multiply(c),g=d.divide(c).normalize();f.push(p.x,p.y,p.z),_.push(g.x,g.y,g.z),m.push(n,we.e.UseOpenGLOrientationForUV?1-e:e)}if(v>0){const e=f.length/3;for(let t=e-2*(u+1);t+u+21&&(p.push(t),p.push(t+1),p.push(t+u+1)),(v_l(e,{size:t,sideOrientation:s,updatable:n},i);function vl(e={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){const t=Math.max(e.subdivisions?e.subdivisions:2,1),i=Math.max(e.tessellation?e.tessellation:16,3),n=Math.max(e.height?e.height:1,0),s=Math.max(e.radius?e.radius:.25,0),r=Math.max(e.capSubdivisions?e.capSubdivisions:6,1),a=i,l=t,h=Math.max(e.radiusTop?e.radiusTop:s,0),c=Math.max(e.radiusBottom?e.radiusBottom:s,0),d=n-(h+c),u=2*Math.PI,p=Math.max(e.topCapSubdivisions?e.topCapSubdivisions:r,1),f=Math.max(e.bottomCapSubdivisions?e.bottomCapSubdivisions:r,1),_=Math.acos((c-h)/n);let m=[];const g=[],v=[],T=[];let S=0;const E=[],x=.5*d,b=.5*Math.PI;let C,y;const A=o.P.Zero(),R=o.P.Zero(),P=Math.cos(_),I=Math.sin(_),M=new o.FM(h*I,x+h*P).subtract(new o.FM(c*I,c*P-x)).length(),O=h*_+M+c*(b-_);let D=0;for(y=0;y<=p;y++){const e=[],t=b-_*(y/p);D+=h*_/p;const i=Math.cos(t),n=Math.sin(t),s=i*h;for(C=0;C<=a;C++){const t=C/a,r=t*u+0,o=Math.sin(r),l=Math.cos(r);R.x=s*o,R.y=x+n*h,R.z=s*l,g.push(R.x,R.y,R.z),A.set(i*o,n,i*l),v.push(A.x,A.y,A.z),T.push(t,we.e.UseOpenGLOrientationForUV?D/O:1-D/O),e.push(S),S++}E.push(e)}const N=n-h-c+P*h-P*c,F=I*(c-h)/N;for(y=1;y<=l;y++){const e=[];D+=M/l;const t=I*(y*(c-h)/l+h);for(C=0;C<=a;C++){const i=C/a,n=i*u+0,s=Math.sin(n),r=Math.cos(n);R.x=t*s,R.y=x+P*h-y*N/l,R.z=t*r,g.push(R.x,R.y,R.z),A.set(s,F,r).normalize(),v.push(A.x,A.y,A.z),T.push(i,we.e.UseOpenGLOrientationForUV?D/O:1-D/O),e.push(S),S++}E.push(e)}for(y=1;y<=f;y++){const e=[],t=b-_-(Math.PI-_)*(y/f);D+=c*_/f;const i=Math.cos(t),n=Math.sin(t),s=i*c;for(C=0;C<=a;C++){const t=C/a,r=t*u+0,o=Math.sin(r),l=Math.cos(r);R.x=s*o,R.y=n*c-x,R.z=s*l,g.push(R.x,R.y,R.z),A.set(i*o,n,i*l),v.push(A.x,A.y,A.z),T.push(t,we.e.UseOpenGLOrientationForUV?D/O:1-D/O),e.push(S),S++}E.push(e)}for(C=0;Cgl(e,{segments:t,diameterX:i,diameterY:i,diameterZ:i,sideOrientation:r,updatable:s},n);function Sl(e){let t=e.pathArray;const i=e.closeArray||!1,n=e.closePath||!1,s=e.invertUV||!1,r=Math.floor(t[0].length/2);let o=e.offset||r;o=o>r?r:Math.floor(o);const a=0===e.sideOrientation?0:e.sideOrientation||Qe.x.DEFAULTSIDE,l=e.uvs,h=e.colors,c=[],d=[],u=[],p=[],f=[],_=[],m=[],g=[];let v;const T=[],S=[];let E,x,b;if(t.length<2){const e=[],i=[];for(x=0;x0&&(P=A[b].subtract(A[b-1]).length(),I=P+m[E],f[E].push(I),m[E]=I),b++;n&&(b--,c.push(A[0].x,A[0].y,A[0].z),P=A[b].subtract(A[0]).length(),I=P+m[E],f[E].push(I),m[E]=I),T[E]=R+y,S[E]=C,C+=R+y}let D,N,F=null,w=null;for(x=0;x{let s=n[0].length;const r=l;let o=0;const a=r._originalBuilderSideOrientation===ee.Kj.DOUBLESIDE?2:1;for(let l=1;l<=a;++l)for(let a=0;aTl(e,t,i),Qe.x.CreateCapsule=vl;function xl(e){const t=new Array,i=new Array,n=new Array,s=new Array,r=e.radius||.5,o=e.tessellation||64,a=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,l=0===e.sideOrientation?0:e.sideOrientation||Qe.x.DEFAULTSIDE;t.push(0,0,0),s.push(.5,.5);const h=2*Math.PI*a,c=1===a?h/o:h/(o-1);let d=0;for(let f=0;fEl(e,{pathArray:t,closeArray:i,closePath:n,offset:s,updatable:o,sideOrientation:a,instance:l},r);function Cl(e){const t=e.pattern||ee.Kj.NO_FLIP,i=e.tileWidth||e.tileSize||1,n=e.tileHeight||e.tileSize||1,s=e.alignHorizontal||0,r=e.alignVertical||0,o=e.width||e.size||1,a=Math.floor(o/i);let l=o-a*i;const h=e.height||e.size||1,c=Math.floor(h/n);let d=h-c*n;const u=i*a/2,p=n*c/2;let f=0,_=0,m=0,g=0,v=0,T=0;if(l>0||d>0){switch(m=-u,g=-p,v=u,T=p,s){case ee.Kj.CENTER:l/=2,m-=l,v+=l;break;case ee.Kj.LEFT:v+=l,f=-l/2;break;case ee.Kj.RIGHT:m-=l,f=l/2}switch(r){case ee.Kj.CENTER:d/=2,g-=d,T+=d;break;case ee.Kj.BOTTOM:T+=d,_=-d/2;break;case ee.Kj.TOP:g-=d,_=d/2}}const S=[],E=[],x=[];x[0]=[0,0,1,0,1,1,0,1],x[1]=[0,0,1,0,1,1,0,1],t!==ee.Kj.ROTATE_TILE&&t!==ee.Kj.ROTATE_ROW||(x[1]=[1,1,0,1,0,0,1,0]),t!==ee.Kj.FLIP_TILE&&t!==ee.Kj.FLIP_ROW||(x[1]=[1,0,0,0,0,1,1,1]),t!==ee.Kj.FLIP_N_ROTATE_TILE&&t!==ee.Kj.FLIP_N_ROTATE_ROW||(x[1]=[0,1,1,1,1,0,0,0]);let b=[];const C=[],y=[];let A=0;for(let M=0;M0||d>0){const e=d>0&&(r===ee.Kj.CENTER||r===ee.Kj.TOP),o=d>0&&(r===ee.Kj.CENTER||r===ee.Kj.BOTTOM),h=l>0&&(s===ee.Kj.CENTER||s===ee.Kj.RIGHT),x=l>0&&(s===ee.Kj.CENTER||s===ee.Kj.LEFT);let R,P,I,M,O=[];if(e&&h&&(S.push(m+f,g+_,0),S.push(-u+f,g+_,0),S.push(-u+f,g+d+_,0),S.push(m+f,g+d+_,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,R=1-l/i,P=1-d/n,I=1,M=1,O=[R,P,I,P,I,M,R,M],t===ee.Kj.ROTATE_ROW&&(O=[1-R,1-P,1-I,1-P,1-I,1-M,1-R,1-M]),t===ee.Kj.FLIP_ROW&&(O=[1-R,P,1-I,P,1-I,M,1-R,M]),t===ee.Kj.FLIP_N_ROTATE_ROW&&(O=[R,1-P,I,1-P,I,1-M,R,1-M]),b=b.concat(O),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),E.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),e&&x&&(S.push(u+f,g+_,0),S.push(v+f,g+_,0),S.push(v+f,g+d+_,0),S.push(u+f,g+d+_,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,R=0,P=1-d/n,I=l/i,M=1,O=[R,P,I,P,I,M,R,M],(t===ee.Kj.ROTATE_ROW||t===ee.Kj.ROTATE_TILE&&a%2==0)&&(O=[1-R,1-P,1-I,1-P,1-I,1-M,1-R,1-M]),(t===ee.Kj.FLIP_ROW||t===ee.Kj.FLIP_TILE&&a%2==0)&&(O=[1-R,P,1-I,P,1-I,M,1-R,M]),(t===ee.Kj.FLIP_N_ROTATE_ROW||t===ee.Kj.FLIP_N_ROTATE_TILE&&a%2==0)&&(O=[R,1-P,I,1-P,I,1-M,R,1-M]),b=b.concat(O),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),E.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),o&&h&&(S.push(m+f,p+_,0),S.push(-u+f,p+_,0),S.push(-u+f,T+_,0),S.push(m+f,T+_,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,R=1-l/i,P=0,I=1,M=d/n,O=[R,P,I,P,I,M,R,M],(t===ee.Kj.ROTATE_ROW&&c%2==1||t===ee.Kj.ROTATE_TILE&&c%1==0)&&(O=[1-R,1-P,1-I,1-P,1-I,1-M,1-R,1-M]),(t===ee.Kj.FLIP_ROW&&c%2==1||t===ee.Kj.FLIP_TILE&&c%2==0)&&(O=[1-R,P,1-I,P,1-I,M,1-R,M]),(t===ee.Kj.FLIP_N_ROTATE_ROW&&c%2==1||t===ee.Kj.FLIP_N_ROTATE_TILE&&c%2==0)&&(O=[R,1-P,I,1-P,I,1-M,R,1-M]),b=b.concat(O),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),E.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),o&&x&&(S.push(u+f,p+_,0),S.push(v+f,p+_,0),S.push(v+f,T+_,0),S.push(u+f,T+_,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,R=0,P=0,I=l/i,M=d/n,O=[R,P,I,P,I,M,R,M],(t===ee.Kj.ROTATE_ROW&&c%2==1||t===ee.Kj.ROTATE_TILE&&(c+a)%2==1)&&(O=[1-R,1-P,1-I,1-P,1-I,1-M,1-R,1-M]),(t===ee.Kj.FLIP_ROW&&c%2==1||t===ee.Kj.FLIP_TILE&&(c+a)%2==1)&&(O=[1-R,P,1-I,P,1-I,M,1-R,M]),(t===ee.Kj.FLIP_N_ROTATE_ROW&&c%2==1||t===ee.Kj.FLIP_N_ROTATE_TILE&&(c+a)%2==1)&&(O=[R,1-P,I,1-P,I,1-M,R,1-M]),b=b.concat(O),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),E.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),e){const e=[];R=0,P=1-d/n,I=1,M=1,e[0]=[R,P,I,P,I,M,R,M],e[1]=[R,P,I,P,I,M,R,M],t!==ee.Kj.ROTATE_TILE&&t!==ee.Kj.ROTATE_ROW||(e[1]=[1-R,1-P,1-I,1-P,1-I,1-M,1-R,1-M]),t!==ee.Kj.FLIP_TILE&&t!==ee.Kj.FLIP_ROW||(e[1]=[1-R,P,1-I,P,1-I,M,1-R,M]),t!==ee.Kj.FLIP_N_ROTATE_TILE&&t!==ee.Kj.FLIP_N_ROTATE_ROW||(e[1]=[R,1-P,I,1-P,I,1-M,R,1-M]);for(let n=0;nbl(e,{radius:t,tessellation:i,sideOrientation:r,updatable:s},n);function yl(e){const t=e.faceUV||new Array(6),i=e.faceColors,n=e.pattern||ee.Kj.NO_FLIP,s=e.width||e.size||1,r=e.height||e.size||1,l=e.depth||e.size||1,h=e.tileWidth||e.tileSize||1,c=e.tileHeight||e.tileSize||1,d=e.alignHorizontal||0,u=e.alignVertical||0,p=0===e.sideOrientation?0:e.sideOrientation||Qe.x.DEFAULTSIDE;for(let U=0;U<6;U++)void 0===t[U]&&(t[U]=new o.Lt(0,0,1,1)),i&&void 0===i[U]&&(i[U]=new a.HE(1,1,1,1));const f=s/2,_=r/2,m=l/2,g=[];for(let o=0;o<2;o++)g[o]=Cl({pattern:n,tileWidth:h,tileHeight:c,width:s,height:r,alignVertical:u,alignHorizontal:d,sideOrientation:p});for(let o=2;o<4;o++)g[o]=Cl({pattern:n,tileWidth:h,tileHeight:c,width:l,height:r,alignVertical:u,alignHorizontal:d,sideOrientation:p});let v=u;u===ee.Kj.BOTTOM?v=ee.Kj.TOP:u===ee.Kj.TOP&&(v=ee.Kj.BOTTOM);for(let o=4;o<6;o++)g[o]=Cl({pattern:n,tileWidth:h,tileHeight:c,width:s,height:l,alignVertical:v,alignHorizontal:d,sideOrientation:p});let T=[],S=[],E=[],x=[];const b=[],C=[],y=[],A=[];let R=0,P=0;for(let a=0;a<6;a++){const e=g[a].positions.length;C[a]=[],y[a]=[];for(let t=0;te+P))),P+=C[a].length,i)for(let t=0;t<4;t++)b.push(i[a].r,i[a].g,i[a].b,i[a].a)}const I=new o.P(0,0,m),M=o.y3.RotationY(Math.PI);T=C[0].map((e=>o.P.TransformNormal(e,M).add(I))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]),S=y[0].map((e=>o.P.TransformNormal(e,M))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]),T=T.concat(C[1].map((e=>e.subtract(I))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),S=S.concat(y[1].map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const O=new o.P(f,0,0),D=o.y3.RotationY(-Math.PI/2);T=T.concat(C[2].map((e=>o.P.TransformNormal(e,D).add(O))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),S=S.concat(y[2].map((e=>o.P.TransformNormal(e,D))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const N=o.y3.RotationY(Math.PI/2);T=T.concat(C[3].map((e=>o.P.TransformNormal(e,N).subtract(O))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),S=S.concat(y[3].map((e=>o.P.TransformNormal(e,N))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const F=new o.P(0,_,0),w=o.y3.RotationX(Math.PI/2);T=T.concat(C[4].map((e=>o.P.TransformNormal(e,w).add(F))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),S=S.concat(y[4].map((e=>o.P.TransformNormal(e,w))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[]));const L=o.y3.RotationX(-Math.PI/2);T=T.concat(C[5].map((e=>o.P.TransformNormal(e,L).subtract(F))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),S=S.concat(y[5].map((e=>o.P.TransformNormal(e,L))).map((e=>[e.x,e.y,e.z])).reduce(((e,t)=>e.concat(t)),[])),Qe.x._ComputeSides(p,T,x,S,E);const B=new Qe.x;if(B.indices=x,B.positions=T,B.normals=S,B.uvs=E,i){const e=p===Qe.x.DOUBLESIDE?b.concat(b):b;B.colors=e}return B}Qe.x.CreateTiledPlane=Cl;function Al(e){const t=new Array,i=new Array,n=new Array,s=new Array,r=e.radius||2,a=e.tube||.5,l=e.radialSegments||32,h=e.tubularSegments||32,c=e.p||2,d=e.q||3,u=0===e.sideOrientation?0:e.sideOrientation||Qe.x.DEFAULTSIDE,p=e=>{const t=Math.cos(e),i=Math.sin(e),n=d/c*e,s=Math.cos(n),a=r*(2+s)*.5*t,l=r*(2+s)*i*.5,h=r*Math.sin(n)*.5;return new o.P(a,l,h)};let f,_;for(f=0;f<=l;f++){const e=f%l/l*2*c*Math.PI,t=p(e),n=p(e+.01),r=n.subtract(t);let d=n.add(t);const u=o.P.Cross(r,d);for(d=o.P.Cross(u,r),u.normalize(),d.normalize(),_=0;_Rl(e,{radius:t,tube:i,radialSegments:n,tubularSegments:s,p:r,q:o,sideOrientation:h,updatable:l},a);const Pl={effect:null,subMesh:null};class Il extends pt{constructor(e,t,i,n={},s=!0){super(e,t,s),this._textures={},this._textureArrays={},this._externalTextures={},this._floats={},this._ints={},this._uints={},this._floatsArrays={},this._colors3={},this._colors3Arrays={},this._colors4={},this._colors4Arrays={},this._vectors2={},this._vectors3={},this._vectors4={},this._quaternions={},this._quaternionsArrays={},this._matrices={},this._matrixArrays={},this._matrices3x3={},this._matrices2x2={},this._vectors2Arrays={},this._vectors3Arrays={},this._vectors4Arrays={},this._uniformBuffers={},this._textureSamplers={},this._storageBuffers={},this._cachedWorldViewMatrix=new o.y3,this._cachedWorldViewProjectionMatrix=new o.y3,this._multiview=!1,this._materialHelperNeedsPreviousMatrices=!1,this._shaderPath=i,this._options=Object.assign({needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1},n)}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){-1===this._options.uniforms.indexOf(e)&&this._options.uniforms.push(e)}setTexture(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._textures[e]=t,this}setTextureArray(e,t){return-1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this}setExternalTexture(e,t){return-1===this._options.externalTextures.indexOf(e)&&this._options.externalTextures.push(e),this._externalTextures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setUInt(e,t){return this._checkUniform(e),this._uints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor3Array(e,t){return this._checkUniform(e),this._colors3Arrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setColor4Array(e,t){return this._checkUniform(e),this._colors4Arrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setQuaternion(e,t){return this._checkUniform(e),this._quaternions[e]=t,this}setQuaternionArray(e,t){return this._checkUniform(e),this._quaternionsArrays[e]=t.reduce(((e,t)=>(t.toArray(e,e.length),e)),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);const i=new Float32Array(16*t.length);for(let n=0;nt===e||t.startsWith(i)));return n>=0&&this.options.defines.splice(n,1),("boolean"!=typeof t||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){var n,s,r,o;const a=i&&this._storeEffectOnSubMeshes;if(this.isFrozen)if(a){if(i.effect&&i.effect._wasPreviouslyReady)return!0}else{const e=this._drawWrapper.effect;if(e&&e._wasPreviouslyReady&&e._wasPreviouslyUsingInstances===t)return!0}const l=this.getScene(),h=l.getEngine(),c=[],d=[],u=new zt;let p=this._shaderPath,f=this._options.uniforms,_=this._options.uniformBuffers,m=this._options.samplers;h.getCaps().multiview&&l.activeCamera&&l.activeCamera.outputRenderTarget&&l.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,c.push("#define MULTIVIEW"),-1!==this._options.uniforms.indexOf("viewProjection")&&-1===this._options.uniforms.indexOf("viewProjectionR")&&this._options.uniforms.push("viewProjectionR"));for(let C=0;C4&&(d.push(ne.o.MatricesIndicesExtraKind),d.push(ne.o.MatricesWeightsExtraKind));const t=e.skeleton;c.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),u.addCPUSkinningFallback(0,e),t.isUsingTextureForMatrices?(c.push("#define BONETEXTURE"),-1===this._options.uniforms.indexOf("boneTextureWidth")&&this._options.uniforms.push("boneTextureWidth"),-1===this._options.samplers.indexOf("boneSampler")&&this._options.samplers.push("boneSampler")):(c.push("#define BonesPerMesh "+(t.bones.length+1)),-1===this._options.uniforms.indexOf("mBones")&&this._options.uniforms.push("mBones"))}else c.push("#define NUM_BONE_INFLUENCERS 0");let g=0;const v=e?e.morphTargetManager:null;if(v){const e=v.supportsUVs&&-1!==c.indexOf("#define UV1"),t=v.supportsTangents&&-1!==c.indexOf("#define TANGENT"),i=v.supportsNormals&&-1!==c.indexOf("#define NORMAL");g=v.numInfluencers,e&&c.push("#define MORPHTARGETS_UV"),t&&c.push("#define MORPHTARGETS_TANGENT"),i&&c.push("#define MORPHTARGETS_NORMAL"),g>0&&c.push("#define MORPHTARGETS"),v.isUsingTextureForTargets&&(c.push("#define MORPHTARGETS_TEXTURE"),-1===this._options.uniforms.indexOf("morphTargetTextureIndices")&&this._options.uniforms.push("morphTargetTextureIndices"),-1===this._options.samplers.indexOf("morphTargets")&&this._options.samplers.push("morphTargets")),c.push("#define NUM_MORPH_INFLUENCERS "+g);for(let n=0;n0&&(f=f.slice(),f.push("morphTargetInfluences"),f.push("morphTargetTextureInfo"),f.push("morphTargetTextureIndices"))}else c.push("#define NUM_MORPH_INFLUENCERS 0");if(e){const t=e.bakedVertexAnimationManager;t&&t.isEnabled&&(c.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),-1===this._options.uniforms.indexOf("bakedVertexAnimationSettings")&&this._options.uniforms.push("bakedVertexAnimationSettings"),-1===this._options.uniforms.indexOf("bakedVertexAnimationTextureSizeInverted")&&this._options.uniforms.push("bakedVertexAnimationTextureSizeInverted"),-1===this._options.uniforms.indexOf("bakedVertexAnimationTime")&&this._options.uniforms.push("bakedVertexAnimationTime"),-1===this._options.samplers.indexOf("bakedVertexAnimationTexture")&&this._options.samplers.push("bakedVertexAnimationTexture")),It.G.PrepareAttributesForBakedVertexAnimation(d,e,c)}for(const C in this._textures)if(!this._textures[C].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&c.push("#define ALPHATEST"),!1!==this._options.useClipPlane&&((0,ua.qx)(f),(0,ua.lK)(this,l,c)),this.customShaderNameResolve&&(f=f.slice(),_=_.slice(),m=m.slice(),p=this.customShaderNameResolve(p,f,_,m,c,d));const T=a?i._getDrawWrapper():this._drawWrapper,S=null!==(n=null==T?void 0:T.effect)&&void 0!==n?n:null,E=null!==(s=null==T?void 0:T.defines)&&void 0!==s?s:null,x=c.join("\n");let b=S;return E!==x&&(b=h.createEffect(p,{attributes:d,uniformsNames:f,uniformBuffersNames:_,samplers:m,defines:x,fallbacks:u,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:g},shaderLanguage:this._options.shaderLanguage},h),a?i.setEffect(b,x,this._materialContext):T&&T.setEffect(b,x),this._onEffectCreatedObservable&&(Pl.effect=b,Pl.subMesh=null!==(r=null!=i?i:null==e?void 0:e.subMeshes[0])&&void 0!==r?r:null,this._onEffectCreatedObservable.notifyObservers(Pl))),b._wasPreviouslyUsingInstances=!!t,null!==(o=!(null==b?void 0:b.isReady()))&&void 0!==o&&!o&&(S!==b&&l.resetCachedMaterial(),b._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){const i=this.getScene(),n=null!=t?t:this.getEffect();n&&(-1!==this._options.uniforms.indexOf("world")&&n.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),n.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),n.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)))}bindForSubMesh(e,t,i){var n;this.bind(e,t,null===(n=i._drawWrapperOverride)||void 0===n?void 0:n.effect,i)}bind(e,t,i,n){var s;const r=n&&this._storeEffectOnSubMeshes,o=null!=i?i:r?n.effect:this.getEffect();if(!o)return;this._activeEffect=o,this.bindOnlyWorldMatrix(e,i);const a=this._options.uniformBuffers;let l=!1;if(o&&a&&a.length>0&&this.getScene().getEngine().supportsUniformBuffers)for(let c=0;c0&&It.G.BindMorphTargetParameters(t,o);const i=t.bakedVertexAnimationManager;i&&i.isEnabled&&(null===(s=t.bakedVertexAnimationManager)||void 0===s||s.bind(o,!!o._wasPreviouslyUsingInstances))}this._afterBind(t,o)}getActiveTextures(){const e=super.getActiveTextures();for(const t in this._textures)e.push(this._textures[t]);for(const t in this._textureArrays){const i=this._textureArrays[t];for(let t=0;tnew Il(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes)),this);t.name=e,t.id=e,"object"==typeof t._shaderPath&&(t._shaderPath=Object.assign({},t._shaderPath)),this._options=Object.assign({},this._options),Object.keys(this._options).forEach((e=>{const t=this._options[e];Array.isArray(t)&&(this._options[e]=t.slice(0))})),this.stencil.copyTo(t.stencil);for(const i in this._textures)t.setTexture(i,this._textures[i]);for(const i in this._textureArrays)t.setTextureArray(i,this._textureArrays[i]);for(const i in this._externalTextures)t.setExternalTexture(i,this._externalTextures[i]);for(const i in this._ints)t.setInt(i,this._ints[i]);for(const i in this._uints)t.setUInt(i,this._uints[i]);for(const i in this._floats)t.setFloat(i,this._floats[i]);for(const i in this._floatsArrays)t.setFloats(i,this._floatsArrays[i]);for(const i in this._colors3)t.setColor3(i,this._colors3[i]);for(const i in this._colors3Arrays)t._colors3Arrays[i]=this._colors3Arrays[i];for(const i in this._colors4)t.setColor4(i,this._colors4[i]);for(const i in this._colors4Arrays)t._colors4Arrays[i]=this._colors4Arrays[i];for(const i in this._vectors2)t.setVector2(i,this._vectors2[i]);for(const i in this._vectors3)t.setVector3(i,this._vectors3[i]);for(const i in this._vectors4)t.setVector4(i,this._vectors4[i]);for(const i in this._quaternions)t.setQuaternion(i,this._quaternions[i]);for(const i in this._quaternionsArrays)t._quaternionsArrays[i]=this._quaternionsArrays[i];for(const i in this._matrices)t.setMatrix(i,this._matrices[i]);for(const i in this._matrixArrays)t._matrixArrays[i]=this._matrixArrays[i].slice();for(const i in this._matrices3x3)t.setMatrix3x3(i,this._matrices3x3[i]);for(const i in this._matrices2x2)t.setMatrix2x2(i,this._matrices2x2[i]);for(const i in this._vectors2Arrays)t.setArray2(i,this._vectors2Arrays[i]);for(const i in this._vectors3Arrays)t.setArray3(i,this._vectors3Arrays[i]);for(const i in this._vectors4Arrays)t.setArray4(i,this._vectors4Arrays[i]);for(const i in this._uniformBuffers)t.setUniformBuffer(i,this._uniformBuffers[i]);for(const i in this._textureSamplers)t.setTextureSampler(i,this._textureSamplers[i]);for(const i in this._storageBuffers)t.setStorageBuffer(i,this._storageBuffers[i]);return t}dispose(e,t,i){if(t){let e;for(e in this._textures)this._textures[e].dispose();for(e in this._textureArrays){const t=this._textureArrays[e];for(let e=0;enew Il(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes)),e,t,i);let s;for(s in e.stencil&&n.stencil.parse(e.stencil,t,i),e.textures)n.setTexture(s,Le.Parse(e.textures[s],t,i));for(s in e.textureArrays){const r=e.textureArrays[s],o=new Array;for(let e=0;e(i%3==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>a.Wo.FromArray(e)));n.setColor3Array(s,t)}for(s in e.colors4)n.setColor4(s,a.HE.FromArray(e.colors4[s]));for(s in e.colors4Arrays){const t=e.colors4Arrays[s].reduce(((e,t,i)=>(i%4==0?e.push([t]):e[e.length-1].push(t),e)),[]).map((e=>a.HE.FromArray(e)));n.setColor4Array(s,t)}for(s in e.vectors2)n.setVector2(s,o.FM.FromArray(e.vectors2[s]));for(s in e.vectors3)n.setVector3(s,o.P.FromArray(e.vectors3[s]));for(s in e.vectors4)n.setVector4(s,o.Lt.FromArray(e.vectors4[s]));for(s in e.quaternions)n.setQuaternion(s,o._f.FromArray(e.quaternions[s]));for(s in e.matrices)n.setMatrix(s,o.y3.FromArray(e.matrices[s]));for(s in e.matrixArray)n._matrixArrays[s]=new Float32Array(e.matrixArray[s]);for(s in e.matrices3x3)n.setMatrix3x3(s,e.matrices3x3[s]);for(s in e.matrices2x2)n.setMatrix2x2(s,e.matrices2x2[s]);for(s in e.vectors2Arrays)n.setArray2(s,e.vectors2Arrays[s]);for(s in e.vectors3Arrays)n.setArray3(s,e.vectors3Arrays[s]);for(s in e.vectors4Arrays)n.setArray4(s,e.vectors4Arrays[s]);for(s in e.quaternionsArrays)n.setArray4(s,e.quaternionsArrays[s]);return n}static ParseFromFileAsync(e,t,i,n=""){return new Promise(((s,r)=>{const o=new y.g;o.addEventListener("readystatechange",(()=>{if(4==o.readyState)if(200==o.status){const t=JSON.parse(o.responseText),r=this.Parse(t,i||m.l.LastCreatedScene,n);e&&(r.name=e),s(r)}else r("Unable to load the ShaderMaterial")})),o.open("GET",t),o.send()}))}static ParseFromSnippetAsync(e,t,i=""){return new Promise(((n,s)=>{const r=new y.g;r.addEventListener("readystatechange",(()=>{if(4==r.readyState)if(200==r.status){const s=JSON.parse(JSON.parse(r.responseText).jsonPayload),o=JSON.parse(s.shaderMaterial),a=this.Parse(o,t||m.l.LastCreatedScene,i);a.snippetId=e,n(a)}else s("Unable to load the snippet "+e)})),r.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),r.send()}))}}Il.SnippetUrl="https://snippet.babylonjs.com",Il.CreateFromSnippetAsync=Il.ParseFromSnippetAsync,(0,l.H)("BABYLON.ShaderMaterial",Il);const Ml="colorPixelShader",Ol="#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\n#define VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ht.v.ShadersStore[Ml]=Ol;const Dl="colorVertexShader",Nl="attribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n#include\n#include\nuniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {\ngl_Position=viewProjection*worldPos;\n} else {\ngl_Position=viewProjectionR*worldPos;\n}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";Ht.v.ShadersStore[Dl]=Nl;ee.Kj._LinesMeshParser=(e,t)=>Fl.Parse(e,t);class Fl extends ee.Kj{_isShaderMaterial(e){return"ShaderMaterial"===e.getClassName()}constructor(e,t=null,i=null,n=null,s,r,o,l){super(e,t,i,n,s),this.useVertexColor=r,this.useVertexAlpha=o,this.color=new a.Wo(1,1,1),this.alpha=1,n&&(this.color=n.color.clone(),this.alpha=n.alpha,this.useVertexColor=n.useVertexColor,this.useVertexAlpha=n.useVertexAlpha),this.intersectionThreshold=.1;const h={attributes:[ne.o.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:[],useClipPlane:null};!1===o?h.needAlphaBlending=!1:h.defines.push("#define VERTEXALPHA"),r?(h.defines.push("#define VERTEXCOLOR"),h.attributes.push(ne.o.ColorKind)):(h.uniforms.push("color"),this._color4=new a.HE),l?this.material=l:(this.material=new Il("colorShader",this.getScene(),"color",h,!1),this.material.doNotSerialize=!0)}isReady(){return!!this._lineMaterial.isReady(this,!!this._userInstancedBuffersStorage)&&super.isReady()}getClassName(){return"LinesMesh"}get material(){return this._lineMaterial}set material(e){this._lineMaterial=e,this._lineMaterial.fillMode=ut.F.LineListDrawMode}get checkCollisions(){return!1}set checkCollisions(e){}_bind(e,t){if(!this._geometry)return this;const i=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(this._userInstancedBuffersStorage?this._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(t,i),!this.useVertexColor&&this._isShaderMaterial(this._lineMaterial)){const{r:e,g:t,b:i}=this.color;this._color4.set(e,t,i,this.alpha),this._lineMaterial.setColor4("color",this._color4)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const n=this.getScene().getEngine();return this._unIndexed?n.drawArraysType(ut.F.LineListDrawMode,e.verticesStart,e.verticesCount,i):n.drawElementsType(ut.F.LineListDrawMode,e.indexStart,e.indexCount,i),this}dispose(e,t=!1,i){i||this._lineMaterial.dispose(!1,!1,!0),super.dispose(e)}clone(e,t=null,i){return new Fl(e,this.getScene(),t,this,i)}createInstance(e){const t=new wl(e,this);if(this.instancedBuffers){t.instancedBuffers={};for(const e in this.instancedBuffers)t.instancedBuffers[e]=this.instancedBuffers[e]}return t}serialize(e){super.serialize(e),e.color=this.color.asArray(),e.alpha=this.alpha}static Parse(e,t){const i=new Fl(e.name,t);return i.color=a.Wo.FromArray(e.color),i.alpha=e.alpha,i}}class wl extends re{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}function Ll(e){const t=[],i=[],n=e.lines,s=e.colors,r=[];let o=0;for(let l=0;l0&&(t.push(o-1),t.push(o)),o++}}const a=new Qe.x;return a.indices=t,a.positions=i,s&&(a.colors=r),a}function Bl(e){const t=e.dashSize||3,i=e.gapSize||1,n=e.dashNb||200,s=e.points,r=new Array,a=new Array,l=o.P.Zero();let h=0,c=0,d=0,u=0,p=0,f=0,_=0;for(_=0;_{const t=o.P.Zero(),i=e.length/6;let r=0,a=0,l=0,h=0,c=0,d=0,u=0,p=0;for(u=0;uVl(e,{points:t,updatable:n,instance:s},i),ee.Kj.CreateDashedLines=(e,t,i,n,s,r=null,o,a)=>kl(e,{points:t,dashSize:i,gapSize:n,dashNb:s,updatable:o,instance:a},r);class Gl extends o.FM{constructor(e,t){super(e.x,e.y),this.index=t}}class zl{constructor(){this.elements=new Array}add(e){const t=new Array;return e.forEach((e=>{const i=new Gl(e,this.elements.length);t.push(i),this.elements.push(i)})),t}computeBounds(){const e=new o.FM(this.elements[0].x,this.elements[0].y),t=new o.FM(this.elements[0].x,this.elements[0].y);return this.elements.forEach((i=>{i.xt.x&&(t.x=i.x),i.yt.y&&(t.y=i.y)})),{min:e,max:t,width:t.x-e.x,height:t.y-e.y}}}class Wl{_addToepoint(e){for(const t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,n=earcut){let s;this._points=new zl,this._outlinepoints=new zl,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=n,this._name=e,this._scene=i||m.l.LastCreatedScene,s=t instanceof W?t.getPoints():t,this._addToepoint(s),this._points.add(s),this._outlinepoints.add(s),void 0===this.bjsEarcut&&p.Y.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);const t=new zl;return t.add(e),this._holes.push(t),this._eholes.push(this._epoints.length/2),this._addToepoint(e),this}build(e=!1,t=0,i=2){const n=new ee.Kj(this._name,this._scene),s=this.buildVertexData(t,i);return n.setVerticesData(ne.o.PositionKind,s.positions,e),n.setVerticesData(ne.o.NormalKind,s.normals,e),n.setVerticesData(ne.o.UVKind,s.uvs,e),n.setIndices(s.indices),n}buildVertexData(e=0,t=2){const i=new Qe.x,n=new Array,s=new Array,r=new Array,o=this._points.computeBounds();this._points.elements.forEach((e=>{n.push(0,1,0),s.push(e.x,0,e.y),r.push((e.x-o.min.x)/o.width,(e.y-o.min.y)/o.height)}));const a=new Array,l=this.bjsEarcut(this._epoints,this._eholes,2);for(let h=0;h0){const i=s.length/3;this._points.elements.forEach((t=>{n.push(0,-1,0),s.push(t.x,-e,t.y),r.push(1-(t.x-o.min.x)/o.width,1-(t.y-o.min.y)/o.height)}));const l=a.length;for(let e=0;e{this._addSide(s,n,r,a,o,i,e,!0,t)}))}return i.indices=a,i.positions=s,i.normals=n,i.uvs=r,i}_addSide(e,t,i,n,s,r,a,l,h){let c=e.length/3,d=0;for(let u=0;uh?bh?C1),o=t.rotationFunction||(()=>0),a=t.closePath||t.ribbonCloseArray||!1,l=t.closeShape||t.ribbonClosePath||!1,h=0===t.cap?0:t.cap||ee.Kj.NO_CAP,c=t.updatable,d=t.firstNormal||null,u=t.adjustFrame||!1;return ql(e,s,n,null,null,r,o,a,l,h,!0,i,!!c,ee.Kj._GetDefaultSideOrientation(t.sideOrientation),t.instance||null,t.invertUV||!1,t.frontUVs||null,t.backUVs||null,d,u)}function ql(e,t,i,n,s,r,a,l,h,c,d,u,p,f,_,m,g,v,T,S){const E=(e,t,i,n,s,r,a,l,h,c,d)=>{const u=i.getTangents(),p=i.getNormals(),f=i.getBinormals(),_=i.getDistances();if(d)for(let x=0;x0){let e=u[x-1];o.P.Dot(e,u[x])<0&&u[x].scaleInPlace(-1),e=p[x-1],o.P.Dot(e,p[x])<0&&p[x].scaleInPlace(-1),e=f[x-1],o.P.Dot(e,f[x])<0&&f[x].scaleInPlace(-1)}let m=0;const g=c&&l?l:()=>null!==r?r:0,v=c&&a?a:()=>null!==s?s:1;let T=h===ee.Kj.NO_CAP||h===ee.Kj.CAP_END?0:2;const S=o.jp.Matrix[0];for(let x=0;x{const t=Array(),i=o.P.Zero();let n;for(n=0;n3?0:c,d,S);const C=El(e,{pathArray:b,closeArray:l,closePath:h,updatable:p,sideOrientation:f,invertUV:m,frontUVs:g||void 0,backUVs:v||void 0},u);return C._creationDataStorage.pathArray=b,C._creationDataStorage.path3D=x,C._creationDataStorage.cap=c,C}Qe.x.CreatePolygon=Hl,ee.Kj.CreatePolygon=(e,t,i,n,s,r,o=earcut)=>Xl(e,{shape:t,holes:n,updatable:s,sideOrientation:r},i,o),ee.Kj.ExtrudePolygon=(e,t,i,n,s,r,o,a=earcut)=>Yl(e,{shape:t,holes:s,depth:i,updatable:r,sideOrientation:o},n,a);function $l(e,t,i=null){const n=t.arc?t.arc<=0||t.arc>1?1:t.arc:1,s=void 0===t.closed||t.closed,r=t.shape,a=t.radius||1,l=t.tessellation||64,h=t.clip||0,c=t.updatable,d=ee.Kj._GetDefaultSideOrientation(t.sideOrientation),u=t.cap||ee.Kj.NO_CAP,p=2*Math.PI,f=new Array,_=t.invertUV||!1;let m=0,g=0;const v=p/l*n;let T,S;for(m=0;m<=l-h;m++){for(S=[],u!=ee.Kj.CAP_START&&u!=ee.Kj.CAP_ALL||(S.push(new o.P(0,r[0].y,0)),S.push(new o.P(Math.cos(m*v)*r[0].x*a,r[0].y,Math.sin(m*v)*r[0].x*a))),g=0;gjl(e,{shape:t,path:i,scale:n,rotation:s,cap:0===r?0:r||ee.Kj.NO_CAP,sideOrientation:l,instance:h,updatable:a},o),ee.Kj.ExtrudeShapeCustom=(e,t,i,n,s,r,o,a,l,h,c,d)=>Kl(e,{shape:t,path:i,scaleFunction:n,rotationFunction:s,ribbonCloseArray:r,ribbonClosePath:o,cap:0===a?0:a||ee.Kj.NO_CAP,sideOrientation:c,instance:d,updatable:h},l);function Ql(e,t,i=null){const n=t.path;let s=t.instance,r=1;void 0!==t.radius?r=t.radius:s&&(r=s._creationDataStorage.radius);const a=t.tessellation||64,l=t.radiusFunction||null;let h=t.cap||ee.Kj.NO_CAP;const c=t.invertUV||!1,d=t.updatable,u=ee.Kj._GetDefaultSideOrientation(t.sideOrientation);t.arc=t.arc&&(t.arc<=0||t.arc>1)?1:t.arc||1;const p=(e,t,i,n,s,r,a,l)=>{const h=t.getTangents(),c=t.getNormals(),d=t.getDistances(),u=2*Math.PI/s*l,p=r||(()=>n);let f,_,m,g;const v=o.jp.Matrix[0];let T=a===ee.Kj.NO_CAP||a===ee.Kj.CAP_END?0:2;for(let E=0;E{const n=Array();for(let s=0;s3?0:h,_=p(n,f,new Array,r,a,l,h,t.arc);const m=El(e,{pathArray:_,closePath:!0,closeArray:!1,updatable:d,sideOrientation:u,invertUV:c,frontUVs:t.frontUVs,backUVs:t.backUVs},i);return m._creationDataStorage.pathArray=_,m._creationDataStorage.path3D=f,m._creationDataStorage.tessellation=a,m._creationDataStorage.cap=h,m._creationDataStorage.arc=t.arc,m._creationDataStorage.radius=r,m}ee.Kj.CreateLathe=(e,t,i,n,s,r,o)=>$l(e,{shape:t,radius:i,tessellation:n,sideOrientation:o,updatable:r},s);function Zl(e){const t=[];t[0]={vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},t[1]={vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},t[2]={vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},t[3]={vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},t[4]={vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},t[5]={vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},t[6]={vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},t[7]={vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},t[8]={vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},t[9]={vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},t[10]={vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},t[11]={vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},t[12]={vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},t[13]={vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},t[14]={vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]};const i=e.type&&(e.type<0||e.type>=t.length)?0:e.type||0,n=e.size,s=e.sizeX||n||1,r=e.sizeY||n||1,l=e.sizeZ||n||1,h=e.custom||t[i],c=h.face.length,d=e.faceUV||new Array(c),u=e.faceColors,p=void 0===e.flat||e.flat,f=0===e.sideOrientation?0:e.sideOrientation||Qe.x.DEFAULTSIDE,_=new Array,m=new Array,g=new Array,v=new Array,T=new Array;let S=0,E=0;const x=new Array;let b,C,y,A,R,P,I=0,M=0;if(p)for(M=0;MQl(e,{path:t,radius:i,tessellation:n,radiusFunction:s,arc:1,cap:r,updatable:a,sideOrientation:l,instance:h},o);Qe.x.CreatePolyhedron=Zl,ee.Kj.CreatePolyhedron=(e,t,i)=>Jl(e,t,i);const eh=new o.P(1,0,0),th=new o.P(-1,0,0),ih=new o.P(0,1,0),nh=new o.P(0,-1,0),sh=new o.P(0,0,1),rh=new o.P(0,0,-1);class oh{constructor(e=o.P.Zero(),t=o.P.Up(),i=o.FM.Zero(),n=0,s=0,r=null,a=null,l=null,h=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=n,this.vertexIdxForBones=s,this.localPositionOverride=r,this.localNormalOverride=a,this.matrixIndicesOverride=l,this.matrixWeightsOverride=h}clone(){var e,t,i,n;return new oh(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,null===(e=this.localPositionOverride)||void 0===e?void 0:e.slice(),null===(t=this.localNormalOverride)||void 0===t?void 0:t.slice(),null===(i=this.matrixIndicesOverride)||void 0===i?void 0:i.slice(),null===(n=this.matrixWeightsOverride)||void 0===n?void 0:n.slice())}}function ah(e,t,i){var n,s,r,a;const l=!!t.skeleton,h=i.localMode||l,c=null!==t.overrideMaterialSideOrientation&&void 0!==t.overrideMaterialSideOrientation,d=t.getIndices(),u=l?t.getPositionData(!0,!0):t.getVerticesData(ne.o.PositionKind),p=l?t.getNormalsData(!0,!0):t.getVerticesData(ne.o.NormalKind),f=h?l?t.getVerticesData(ne.o.PositionKind):u:null,_=h?l?t.getVerticesData(ne.o.NormalKind):p:null,m=t.getVerticesData(ne.o.UVKind),g=l?t.getVerticesData(ne.o.MatricesIndicesKind):null,v=l?t.getVerticesData(ne.o.MatricesWeightsKind):null,T=l?t.getVerticesData(ne.o.MatricesIndicesExtraKind):null,E=l?t.getVerticesData(ne.o.MatricesWeightsExtraKind):null,x=i.position||o.P.Zero();let b=i.normal||o.P.Up();const C=i.size||o.P.One(),y=i.angle||0;if(!b){const e=new o.P(0,0,1),i=t.getScene().activeCamera,n=o.P.TransformCoordinates(e,i.getWorldMatrix());b=i.globalPosition.subtract(n)}const A=-Math.atan2(b.z,b.x)-Math.PI/2,R=Math.sqrt(b.x*b.x+b.z*b.z),P=Math.atan2(b.y,R),I=new Qe.x;I.indices=[],I.positions=[],I.normals=[],I.uvs=[],I.matricesIndices=l?[]:null,I.matricesWeights=l?[]:null,I.matricesIndicesExtra=T?[]:null,I.matricesWeightsExtra=E?[]:null;let M=0;const O=(e,t)=>{const n=new oh;if(!d||!u||!p)return n;const s=d[e];if(n.vertexIdx=3*s,n.vertexIdxForBones=4*s,n.position=new o.P(u[3*s],u[3*s+1],u[3*s+2]),o.P.TransformCoordinatesToRef(n.position,t,n.position),n.normal=new o.P(p[3*s],p[3*s+1],p[3*s+2]),o.P.TransformNormalToRef(n.normal,t,n.normal),i.captureUVS&&m){const e=m[2*s+1];n.uv=new o.FM(m[2*s],we.e.UseOpenGLOrientationForUV?1-e:e)}return n},D=[0,0,0,0],N=(e,t)=>{if(0===e.length)return e;const i=.5*Math.abs(o.P.Dot(C,t)),n=(e,t,i,n)=>{for(let s=0;s{var r,a,l,h,c,d,u,p,m,T,E,x,b,C,y,A;const R=o.P.GetClipFactor(e.position,s.position,t,i);let P=D,I=D;if(g&&v){const t=e.matrixIndicesOverride?0:e.vertexIdxForBones,i=null!==(r=e.matrixIndicesOverride)&&void 0!==r?r:g,o=null!==(a=e.matrixWeightsOverride)&&void 0!==a?a:v,c=s.matrixIndicesOverride?0:s.vertexIdxForBones,d=null!==(l=s.matrixIndicesOverride)&&void 0!==l?l:g,u=null!==(h=s.matrixWeightsOverride)&&void 0!==h?h:v;P=[0,0,0,0],I=[0,0,0,0];let p=0;for(let e=0;e<4;++e)if(o[t+e]>0){const s=n(d,i[t+e],c,4);P[p]=i[t+e],I[p]=S.R.Lerp(o[t+e],s>=0?u[s]:0,R),p++}for(let e=0;e<4&&p<4;++e){const s=d[c+e];-1===n(i,s,t,4)&&(P[p]=s,I[p]=S.R.Lerp(0,u[c+e],R),p++)}const f=I[0]+I[1]+I[2]+I[3];I[0]/=f,I[1]/=f,I[2]/=f,I[3]/=f}const M=e.localPositionOverride?e.localPositionOverride[0]:null!==(c=null==f?void 0:f[e.vertexIdx])&&void 0!==c?c:0,O=e.localPositionOverride?e.localPositionOverride[1]:null!==(d=null==f?void 0:f[e.vertexIdx+1])&&void 0!==d?d:0,N=e.localPositionOverride?e.localPositionOverride[2]:null!==(u=null==f?void 0:f[e.vertexIdx+2])&&void 0!==u?u:0,F=s.localPositionOverride?s.localPositionOverride[0]:null!==(p=null==f?void 0:f[s.vertexIdx])&&void 0!==p?p:0,w=s.localPositionOverride?s.localPositionOverride[1]:null!==(m=null==f?void 0:f[s.vertexIdx+1])&&void 0!==m?m:0,L=s.localPositionOverride?s.localPositionOverride[2]:null!==(T=null==f?void 0:f[s.vertexIdx+2])&&void 0!==T?T:0,B=e.localNormalOverride?e.localNormalOverride[0]:null!==(E=null==_?void 0:_[e.vertexIdx])&&void 0!==E?E:0,U=e.localNormalOverride?e.localNormalOverride[1]:null!==(x=null==_?void 0:_[e.vertexIdx+1])&&void 0!==x?x:0,V=e.localNormalOverride?e.localNormalOverride[2]:null!==(b=null==_?void 0:_[e.vertexIdx+2])&&void 0!==b?b:0,k=B+((s.localNormalOverride?s.localNormalOverride[0]:null!==(C=null==_?void 0:_[s.vertexIdx])&&void 0!==C?C:0)-B)*R,G=U+((s.localNormalOverride?s.localNormalOverride[1]:null!==(y=null==_?void 0:_[s.vertexIdx+1])&&void 0!==y?y:0)-U)*R,z=V+((s.localNormalOverride?s.localNormalOverride[2]:null!==(A=null==_?void 0:_[s.vertexIdx+2])&&void 0!==A?A:0)-V)*R,W=Math.sqrt(k*k+G*G+z*z);return new oh(o.P.Lerp(e.position,s.position,R),o.P.Lerp(e.normal,s.normal,R).normalize(),o.FM.Lerp(e.uv,s.uv,R),-1,-1,f?[M+(F-M)*R,O+(w-O)*R,N+(L-N)*R]:null,_?[k/W,G/W,z/W]:null,P,I)};let r=null;e.length>3&&(r=new Array);for(let a=0;a0,p=o.P.Dot(e[a+1].position,t)-i>0,f=o.P.Dot(e[a+2].position,t)-i>0;switch(n=(u?1:0)+(p?1:0)+(f?1:0),n){case 0:e.length>3?(r.push(e[a]),r.push(e[a+1]),r.push(e[a+2])):r=e;break;case 1:if(r=null!=r?r:new Array,u&&(l=e[a+1],h=e[a+2],c=s(e[a],l),d=s(e[a],h)),p){l=e[a],h=e[a+2],c=s(e[a+1],l),d=s(e[a+1],h),r.push(c),r.push(h.clone()),r.push(l.clone()),r.push(h.clone()),r.push(c.clone()),r.push(d);break}f&&(l=e[a],h=e[a+1],c=s(e[a+2],l),d=s(e[a+2],h)),l&&h&&c&&d&&(r.push(l.clone()),r.push(h.clone()),r.push(c),r.push(d),r.push(c.clone()),r.push(h.clone()));break;case 2:r=null!=r?r:new Array,u||(l=e[a].clone(),h=s(l,e[a+1]),c=s(l,e[a+2]),r.push(l),r.push(h),r.push(c)),p||(l=e[a+1].clone(),h=s(l,e[a+2]),c=s(l,e[a]),r.push(l),r.push(h),r.push(c)),f||(l=e[a+2].clone(),h=s(l,e[a]),c=s(l,e[a+1]),r.push(l),r.push(h),r.push(c))}}return r},F=t instanceof ee.Kj?t:null,w=null==F?void 0:F._thinInstanceDataStorage.matrixData,L=(null==F?void 0:F.thinInstanceCount)||1,B=o.jp.Matrix[0];B.copyFrom(o.y3.IdentityReadOnly);for(let S=0;Sah(e,t,{position:i,normal:n,size:s,angle:r});class lh{constructor(e=0,t=0){this.x=e,this.y=t,e!==Math.floor(e)&&(Math.floor(e),p.Y.Warn("x is not an integer, floor(x) used")),t!==Math.floor(t)&&(Math.floor(t),p.Y.Warn("y is not an integer, floor(y) used"))}clone(){return new lh(this.x,this.y)}rotate60About(e){const t=this.x;return this.x=e.x+e.y-this.y,this.y=t+this.y-e.x,this}rotateNeg60About(e){const t=this.x;return this.x=t+this.y-e.y,this.y=e.x+e.y-t,this}rotate120(e,t){e!==Math.floor(e)&&(Math.floor(e),p.Y.Warn("m not an integer only floor(m) used")),t!==Math.floor(t)&&(Math.floor(t),p.Y.Warn("n not an integer only floor(n) used"));const i=this.x;return this.x=e-i-this.y,this.y=t+i,this}rotateNeg120(e,t){e!==Math.floor(e)&&(Math.floor(e),p.Y.Warn("m is not an integer, floor(m) used")),t!==Math.floor(t)&&(Math.floor(t),p.Y.Warn("n is not an integer, floor(n) used"));const i=this.x;return this.x=this.y-t,this.y=e+t-i-this.y,this}toCartesianOrigin(e,t){const i=o.P.Zero();return i.x=e.x+2*this.x*t+this.y*t,i.y=e.y+Math.sqrt(3)*this.y*t,i}static Zero(){return new lh(0,0)}}class hh{constructor(){this.cartesian=[],this.vertices=[],this.max=[],this.min=[],this.closestTo=[],this.innerFacets=[],this.isoVecsABOB=[],this.isoVecsOBOA=[],this.isoVecsBAOA=[],this.vertexTypes=[],this.IDATA=new ch("icosahedron","Regular",[[0,k.Q_,-1],[-k.Q_,1,0],[-1,0,-k.Q_],[1,0,-k.Q_],[k.Q_,1,0],[0,k.Q_,1],[-1,0,k.Q_],[-k.Q_,-1,0],[0,-k.Q_,-1],[k.Q_,-1,0],[1,0,k.Q_],[0,-k.Q_,1]],[[0,2,1],[0,3,2],[0,4,3],[0,5,4],[0,1,5],[7,6,1],[8,7,2],[9,8,3],[10,9,4],[6,10,5],[2,7,1],[3,8,2],[4,9,3],[5,10,4],[1,6,5],[11,6,7],[11,7,8],[11,8,9],[11,9,10],[11,10,6]])}setIndices(){let e=12;const t={},i=this.m,n=this.n;let s,r,o,a,l,h=i,c=1,d=0;0!==n&&(h=S.R.HCF(i,n)),c=i/h,d=n/h;const u=lh.Zero(),p=new lh(i,n),f=new lh(-n,i+n),_=lh.Zero(),m=lh.Zero(),g=lh.Zero();let v,T,E,x,b=[];const C=[],y=this.vertByDist,A=(i,n,s,r)=>{v=i+"|"+s,T=n+"|"+r,v in t||T in t?v in t&&!(T in t)?t[T]=t[v]:T in t&&!(v in t)&&(t[v]=t[T]):(t[v]=e,t[T]=e,e++),y[s][0]>2?C[t[v]]=[-y[s][0],y[s][1],t[v]]:C[t[v]]=[b[y[s][0]],y[s][1],t[v]]};this.IDATA.edgematch=[[1,"B"],[2,"B"],[3,"B"],[4,"B"],[0,"B"],[10,"O",14,"A"],[11,"O",10,"A"],[12,"O",11,"A"],[13,"O",12,"A"],[14,"O",13,"A"],[0,"O"],[1,"O"],[2,"O"],[3,"O"],[4,"O"],[19,"B",5,"A"],[15,"B",6,"A"],[16,"B",7,"A"],[17,"B",8,"A"],[18,"B",9,"A"]];for(let S=0;S<20;S++){if(b=this.IDATA.face[S],o=b[2],a=b[1],l=b[0],E=u.x+"|"+u.y,v=S+"|"+E,v in t||(t[v]=o,C[o]=[b[y[E][0]],y[E][1]]),E=p.x+"|"+p.y,v=S+"|"+E,v in t||(t[v]=a,C[a]=[b[y[E][0]],y[E][1]]),E=f.x+"|"+f.y,v=S+"|"+E,v in t||(t[v]=l,C[l]=[b[y[E][0]],y[E][1]]),s=this.IDATA.edgematch[S][0],r=this.IDATA.edgematch[S][1],"B"===r)for(let e=1;e2?C[t[v]]=[-y[E][0],y[E][1],t[v]]:C[t[v]]=[b[y[E][0]],y[E][1],t[v]])}this.closestTo=C,this.vecToidx=t}calcCoeffs(){const e=this.m,t=this.n,i=Math.sqrt(3)/3,n=e*e+t*t+e*t;this.coau=(e+t)/n,this.cobu=-t/n,this.coav=-i*(e-t)/n,this.cobv=i*(2*e+t)/n}createInnerFacets(){const e=this.m,t=this.n;for(let i=0;i0&&e0){const n=S.R.HCF(e,t),s=e/n,r=t/n;for(let a=1;ae.x-t.x)),i.sort(((e,t)=>e.y-t.y));const o=new Array(e+t+1),a=new Array(e+t+1);for(let S=0;S{const s=i.clone();return"A"===n&&s.rotateNeg120(e,t),"B"===n&&s.rotate120(e,t),s.x<0?s.y:s.x+s.y},u=[],p=[],f=[],_=[],m={},g=[];let v=-1,T=-1;for(let S=0;Se[2]-t[2])),g.sort(((e,t)=>e[3]-t[3])),g.sort(((e,t)=>e[1]-t[1])),g.sort(((e,t)=>e[0]-t[0]));for(let S=0;St.vecToidx[e+i])))}mapABOBtoDATA(e,t){const i=t.IDATA.edgematch[e][0];for(let n=0;n-1?i[r][1]>0&&t[i[r][0]].push([r,i[r][1]]):t[12].push([r,i[r][0]]);const n=[];for(let r=0;r<12;r++)n[r]=r;let s=12;for(let r=0;r<12;r++){t[r].sort(((e,t)=>e[1]-t[1]));for(let e=0;ee[3]-t[3]));for(let r=0;r0;)s=t[a],this.face[s].indexOf(o)>-1?(r=(this.face[s].indexOf(o)+1)%3,o=this.face[s][r],i.push(o),n.push(s),t.splice(a,1),a=0):a++;return this.adjacentFaces.push(i),n}toGoldbergPolyhedronData(){const e=new ch("GeoDual","Goldberg",[],[]);e.name="GD dual";const t=this.vertex.length,i=new Array(t);for(let l=0;l{n=0,s=0,r=0,o=this.face[t];for(let e=0;e<3;e++)a=this.vertex[o[e]],n+=a[0],s+=a[1],r+=a[2];e.vertex[t]=[n/3,s/3,r/3]}));return e}static BuildGeodesicData(e){const t=new dh("Geodesic-m-n","Geodesic",[[0,k.Q_,-1],[-k.Q_,1,0],[-1,0,-k.Q_],[1,0,-k.Q_],[k.Q_,1,0],[0,k.Q_,1],[-1,0,k.Q_],[-k.Q_,-1,0],[0,-k.Q_,-1],[k.Q_,-1,0],[1,0,k.Q_],[0,-k.Q_,1]],[]);e.setIndices(),e.calcCoeffs(),e.createInnerFacets(),e.edgeVecsABOB(),e.mapABOBtoOBOA(),e.mapABOBtoBAOA();for(let i=0;iuh.Parse(e,t);class uh extends ee.Kj{constructor(){super(...arguments),this.goldbergData={faceColors:[],faceCenters:[],faceZaxis:[],faceXaxis:[],faceYaxis:[],nbSharedFaces:0,nbUnsharedFaces:0,nbFaces:0,nbFacesAtPole:0,adjacentFaces:[]}}relatedGoldbergFace(e,t){return void 0===t?(e>this.goldbergData.nbUnsharedFaces-1&&(p.Y.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(p.Y.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(p.Y.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let i=0;i1&&(c=1),l.push(c,d);for(let e=0;e<6;e++)c=r.x+o*Math.cos(a+e*Math.PI/3),d=r.y+o*Math.sin(a+e*Math.PI/3),c<0&&(c=0),c>1&&(c=1),h.push(c,d);for(let e=n;ea.HE.FromArray(e))),i.faceCenters=i.faceCenters.map((e=>o.P.FromArray(e))),i.faceZaxis=i.faceZaxis.map((e=>o.P.FromArray(e))),i.faceXaxis=i.faceXaxis.map((e=>o.P.FromArray(e))),i.faceYaxis=i.faceYaxis.map((e=>o.P.FromArray(e)));const n=new uh(e.name,t);return n.goldbergData=i,n}}function ph(e,t,i=null){const n=t.size,s=t.sizeX||n||1,r=t.sizeY||n||1,l=t.sizeZ||n||1;let h=t.m||1;h!==Math.floor(h)&&(Math.floor(h),p.Y.Warn("m not an integer only floor(m) used"));let c=t.n||0;if(c!==Math.floor(c)&&(Math.floor(c),p.Y.Warn("n not an integer only floor(n) used")),c>h){const e=c;c=h,h=e,p.Y.Warn("n > m therefore m and n swapped")}const d=new hh;d.build(h,c);const u=dh.BuildGeodesicData(d),f=u.toGoldbergPolyhedronData(),_=new uh(e,i);t.sideOrientation=ee.Kj._GetDefaultSideOrientation(t.sideOrientation),_._originalBuilderSideOrientation=t.sideOrientation;const m=function(e,t){const i=e.size,n=e.sizeX||i||1,s=e.sizeY||i||1,r=e.sizeZ||i||1,a=0===e.sideOrientation?0:e.sideOrientation||Qe.x.DEFAULTSIDE,l=new Array,h=new Array,c=new Array,d=new Array;let u=1/0,p=-1/0,f=1/0,_=-1/0;for(let o=0;o0?this._holes.push(e):this._paths.push(e);if(!this._paths.length&&this._holes.length){const e=this._holes;this._holes=this._paths,this._paths=e}this._tempPaths.length=0}get paths(){return this._paths}get holes(){return this._holes}}function _h(e,t,i,n,s,r){const o=r.glyphs[e]||r.glyphs["?"];if(!o)return null;const a=new fh(s);if(o.o){const e=o.o.split(" ");for(let s=0,r=e.length;s\n #if NUM_BONE_INFLUENCERS == 0\n attribute vec4 matricesIndices;\n attribute vec4 matricesWeights;\n #endif\n #include\n\n #include\n\n varying vec3 vColor;\n\n uniform vec3 colorBase;\n uniform vec3 colorZero;\n uniform vec3 colorQuarter;\n uniform vec3 colorHalf;\n uniform vec3 colorFull;\n\n uniform float targetBoneIndex;\n\n void main() {\n vec3 positionUpdated = position;\n\n #include\n #include\n #include\n\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\n\n vec3 color = colorBase;\n float totalWeight = 0.;\n if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){\n totalWeight += matricesWeights[0];\n }\n if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){\n totalWeight += matricesWeights[1];\n }\n if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){\n totalWeight += matricesWeights[2];\n }\n if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){\n totalWeight += matricesWeights[3];\n }\n\n color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight));\n color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight));\n color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight));\n color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight));\n vColor = color;\n\n gl_Position = projection * view * worldPos;\n }",ft.Q.ShadersStore["boneWeights:"+h.name+"FragmentShader"]="\n precision highp float;\n varying vec3 vPosition;\n\n varying vec3 vColor;\n\n void main() {\n vec4 color = vec4(vColor, 1.0);\n gl_FragColor = color;\n }\n ";const m=new Il("boneWeight:"+h.name,t,{vertex:"boneWeights:"+h.name,fragment:"boneWeights:"+h.name},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorBase","colorZero","colorQuarter","colorHalf","colorFull","targetBoneIndex"]});return m.setColor3("colorBase",c),m.setColor3("colorZero",d),m.setColor3("colorQuarter",u),m.setColor3("colorHalf",p),m.setColor3("colorFull",f),m.setFloat("targetBoneIndex",_),m.getClassName=()=>"BoneWeightShader",m.transparencyMode=ut.F.MATERIAL_OPAQUE,m}static CreateSkeletonMapShader(e,t){var i;const n=e.skeleton,s=null!==(i=e.colorMap)&&void 0!==i?i:[{color:new a.Wo(1,.38,.18),location:0},{color:new a.Wo(.59,.18,1),location:.2},{color:new a.Wo(.59,1,.18),location:.4},{color:new a.Wo(1,.87,.17),location:.6},{color:new a.Wo(1,.17,.42),location:.8},{color:new a.Wo(.17,.68,1),location:1}],r=n.bones.length+1,o=gh._CreateBoneMapColorBuffer(r,s,t),l=new Il("boneWeights:"+n.name,t,{vertexSource:"precision highp float;\n\n attribute vec3 position;\n attribute vec2 uv;\n\n uniform mat4 view;\n uniform mat4 projection;\n uniform mat4 worldViewProjection;\n uniform float colorMap["+4*n.bones.length+"];\n\n #include\n #if NUM_BONE_INFLUENCERS == 0\n attribute vec4 matricesIndices;\n attribute vec4 matricesWeights;\n #endif\n #include\n #include\n\n varying vec3 vColor;\n\n void main() {\n vec3 positionUpdated = position;\n\n #include\n #include\n #include\n\n vec3 color = vec3(0.);\n bool first = true;\n\n for (int i = 0; i < 4; i++) {\n int boneIdx = int(matricesIndices[i]);\n float boneWgt = matricesWeights[i];\n\n vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]);\n\n if (boneWgt > 0.) {\n if (first) {\n first = false;\n color = c;\n } else {\n color = mix(color, c, boneWgt);\n }\n }\n }\n\n vColor = color;\n\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\n\n gl_Position = projection * view * worldPos;\n }",fragmentSource:"\n precision highp float;\n varying vec3 vColor;\n\n void main() {\n vec4 color = vec4( vColor, 1.0 );\n gl_FragColor = color;\n }\n "},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorMap"]});return l.setFloats("colorMap",o),l.getClassName=()=>"SkeletonMapShader",l.transparencyMode=ut.F.MATERIAL_OPAQUE,l}static _CreateBoneMapColorBuffer(e,t,i){const n=new ma("temp",{width:e,height:1},i,!1),s=n.getContext(),r=s.createLinearGradient(0,0,e,0);t.forEach((e=>{r.addColorStop(e.location,e.color.toHexString())})),s.fillStyle=r,s.fillRect(0,0,e,1),n.update();const o=[],a=s.getImageData(0,0,e,1).data;for(let l=0;lgh.DISPLAY_SPHERE_AND_SPURS&&(e=gh.DISPLAY_LINES),this.options.displayMode=e}constructor(e,t,i,n=!0,s=3,r={}){var o,l,h,c,d,u,p,f,_,m,g,v,T,S;this.skeleton=e,this.mesh=t,this.autoUpdateBonesMatrices=n,this.renderingGroupId=s,this.options=r,this.color=a.Wo.White(),this._debugLines=new Array,this._localAxes=null,this._isEnabled=!0,this._obs=null,this._scene=i,this._ready=!1,r.pauseAnimations=null===(o=r.pauseAnimations)||void 0===o||o,r.returnToRest=null!==(l=r.returnToRest)&&void 0!==l&&l,r.displayMode=null!==(h=r.displayMode)&&void 0!==h?h:gh.DISPLAY_LINES,r.displayOptions=null!==(c=r.displayOptions)&&void 0!==c?c:{},r.displayOptions.midStep=null!==(d=r.displayOptions.midStep)&&void 0!==d?d:.235,r.displayOptions.midStepFactor=null!==(u=r.displayOptions.midStepFactor)&&void 0!==u?u:.155,r.displayOptions.sphereBaseSize=null!==(p=r.displayOptions.sphereBaseSize)&&void 0!==p?p:.15,r.displayOptions.sphereScaleUnit=null!==(f=r.displayOptions.sphereScaleUnit)&&void 0!==f?f:2,r.displayOptions.sphereFactor=null!==(_=r.displayOptions.sphereFactor)&&void 0!==_?_:.865,r.displayOptions.spurFollowsChild=null!==(m=r.displayOptions.spurFollowsChild)&&void 0!==m&&m,r.displayOptions.showLocalAxes=null!==(g=r.displayOptions.showLocalAxes)&&void 0!==g&&g,r.displayOptions.localAxesSize=null!==(v=r.displayOptions.localAxesSize)&&void 0!==v?v:.075,r.computeBonesUsingShaders=null===(T=r.computeBonesUsingShaders)||void 0===T||T,r.useAllBones=null===(S=r.useAllBones)||void 0===S||S;const E=t.getVerticesData(ne.o.MatricesIndicesKind),x=t.getVerticesData(ne.o.MatricesWeightsKind);if(this._boneIndices=new Set,!r.useAllBones&&E&&x)for(let a=0;agh.DISPLAY_SPHERE_AND_SPURS&&(b=gh.DISPLAY_LINES),this.displayMode=b,this.update(),this._bindObs()}_bindObs(){if(this.displayMode===gh.DISPLAY_LINES)this._obs=this.scene.onBeforeRenderObservable.add((()=>{this._displayLinesUpdate()}))}update(){switch(this.displayMode){case gh.DISPLAY_LINES:this._displayLinesUpdate();break;case gh.DISPLAY_SPHERES:this._buildSpheresAndSpurs(!0);break;case gh.DISPLAY_SPHERE_AND_SPURS:this._buildSpheresAndSpurs(!1)}this._buildLocalAxes()}set isEnabled(e){this.isEnabled!==e&&(this._isEnabled=e,this.debugMesh&&this.debugMesh.setEnabled(e),e&&!this._obs?this._bindObs():!e&&this._obs&&(this.scene.onBeforeRenderObservable.remove(this._obs),this._obs=null))}get isEnabled(){return this._isEnabled}_getBonePosition(e,t,i,n=0,s=0,r=0){const a=o.jp.Matrix[0],l=t.getParent();if(a.copyFrom(t.getLocalMatrix()),0!==n||0!==s||0!==r){const e=o.jp.Matrix[1];o.y3.IdentityToRef(e),e.setTranslationFromFloats(n,s,r),e.multiplyToRef(a,a)}l&&a.multiplyToRef(l.getAbsoluteMatrix(),a),a.multiplyToRef(i,a),e.x=a.m[12],e.y=a.m[13],e.z=a.m[14]}_getLinesForBonesWithLength(e,t){const i=e.length,n=this.mesh.position;let s=0;for(let r=0;r=0;r--){const t=e[r],a=t.getParent();if(!a||!this._boneIndices.has(t.getIndex())&&!this.options.useAllBones)continue;let l=this._debugLines[i];l||(l=[o.P.Zero(),o.P.Zero()],this._debugLines[i]=l),t.getAbsolutePositionToRef(n,l[0]),a.getAbsolutePositionToRef(n,l[1]),l[0].subtractInPlace(s),l[1].subtractInPlace(s),i++}}_revert(e){this.options.pauseAnimations&&(this.scene.animationsEnabled=e,this.utilityLayer.utilityLayerScene.animationsEnabled=e)}_getAbsoluteBindPoseToRef(e,t){null!==e&&-1!==e._index?(this._getAbsoluteBindPoseToRef(e.getParent(),t),e.getBaseMatrix().multiplyToRef(t,t)):t.copyFrom(o.y3.Identity())}_buildSpheresAndSpurs(e=!0){var t,i;this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this._ready=!1;const n=null===(t=this.utilityLayer)||void 0===t?void 0:t.utilityLayerScene,s=this.skeleton.bones,r=[],a=[],l=this.scene.animationsEnabled;try{this.options.pauseAnimations&&(this.scene.animationsEnabled=!1,n.animationsEnabled=!1),this.options.returnToRest&&this.skeleton.returnToRest(),this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteMatrices();let t=Number.NEGATIVE_INFINITY;const h=this.options.displayOptions||{};for(let i=0;i{const s=new o.y3;i.getBaseMatrix().multiplyToRef(c,s);const r=new o.P;s.decompose(void 0,void 0,r);const u=o.P.Distance(d,r);if(u>t&&(t=u),e)return;const p=r.clone().subtract(d.clone()),f=p.length(),_=p.normalize().scale(f),m=h.midStep||.165,g=h.midStepFactor||.215,v=_.scale(m),T=Kl("skeletonViewer",{shape:[new o.P(1,-1,0),new o.P(1,1,0),new o.P(-1,1,0),new o.P(-1,-1,0),new o.P(1,-1,0)],path:[o.P.Zero(),v,_],scaleFunction:e=>{switch(e){case 0:case 2:return 0;case 1:return f*g}return 0},sideOrientation:ee.Kj.DEFAULTSIDE,updatable:!1},n),S=T.getTotalVertices(),E=[],x=[];for(let e=0;e9?x.push(i.getIndex(),0,0,0):x.push(l.getIndex(),0,0,0);T.position=d.clone(),T.setVerticesData(ne.o.MatricesWeightsKind,E,!1),T.setVerticesData(ne.o.MatricesIndicesKind,x,!1),T.convertToFlatShadedMesh(),a.push(T)}));const u=gl("skeletonViewer",{segments:6,diameter:h.sphereBaseSize||.2,updatable:!0},n),p=u.getTotalVertices(),f=[],_=[];for(let e=0;e{this._gpuFrameTimeToken||(this._gpuFrameTimeToken=this.startTimeQuery())})),this._onEndFrameObserver=this.onEndFrameObservable.add((()=>{if(!this._gpuFrameTimeToken)return;const e=this.endTimeQuery(this._gpuFrameTimeToken);e>-1&&(this._gpuFrameTimeToken=null,this._gpuFrameTime.fetchNewFrame(),this._gpuFrameTime.addCount(e,!0))}))):(this.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null))},fe.D.prototype._getGlAlgorithmType=function(e){return e===ie.x.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED},Object.defineProperty(ie.x.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(e){this._occlusionDataStorage.isOcclusionQueryInProgress=e},enumerable:!1,configurable:!0}),Object.defineProperty(ie.x.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new Eh),this.__occlusionDataStorage},enumerable:!1,configurable:!0}),Object.defineProperty(ie.x.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(e){this._occlusionDataStorage.isOccluded=e},enumerable:!0,configurable:!0}),Object.defineProperty(ie.x.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(e){this._occlusionDataStorage.occlusionQueryAlgorithmType=e},enumerable:!0,configurable:!0}),Object.defineProperty(ie.x.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(e){this._occlusionDataStorage.occlusionType=e},enumerable:!0,configurable:!0}),Object.defineProperty(ie.x.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(e){this._occlusionDataStorage.occlusionRetryCount=e},enumerable:!0,configurable:!0}),Object.defineProperty(ie.x.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(e){this._occlusionDataStorage.forceRenderingWhenOccluded=e},enumerable:!0,configurable:!0}),ie.x.prototype._checkOcclusionQuery=function(){const e=this._occlusionDataStorage;if(e.occlusionType===ie.x.OCCLUSION_TYPE_NONE)return e.isOccluded=!1,!1;const t=this.getEngine();if(!t.getCaps().supportOcclusionQuery)return e.isOccluded=!1,!1;if(!t.isQueryResultAvailable)return e.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&this._occlusionQuery){if(t.isQueryResultAvailable(this._occlusionQuery)){const i=t.getQueryResult(this._occlusionQuery);e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=!(i>0)}else{if(e.occlusionInternalRetryCounter++,!(-1!==e.occlusionRetryCount&&e.occlusionInternalRetryCounter>e.occlusionRetryCount))return e.occlusionType!==ie.x.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded;e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=e.occlusionType!==ie.x.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded}}const i=this.getScene();if(i.getBoundingBoxRenderer){const n=i.getBoundingBoxRenderer();null===this._occlusionQuery&&(this._occlusionQuery=t.createQuery()),t.beginOcclusionQuery(e.occlusionQueryAlgorithmType,this._occlusionQuery)&&(n.renderOcclusionBoundingBox(this),t.endOcclusionQuery(e.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return e.isOccluded};fe.D.prototype.createTransformFeedback=function(){const e=this._gl.createTransformFeedback();if(!e)throw new Error("Unable to create Transform Feedback");return e},fe.D.prototype.deleteTransformFeedback=function(e){this._gl.deleteTransformFeedback(e)},fe.D.prototype.bindTransformFeedback=function(e){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,e)},fe.D.prototype.beginTransformFeedback=function(e=!0){this._gl.beginTransformFeedback(e?this._gl.POINTS:this._gl.TRIANGLES)},fe.D.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()},fe.D.prototype.setTranformFeedbackVaryings=function(e,t){this._gl.transformFeedbackVaryings(e,t,this._gl.INTERLEAVED_ATTRIBS)},fe.D.prototype.bindTransformFeedbackBuffer=function(e){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,e?e.underlyingResource:null)},Ue.B.prototype.createExternalTexture=function(e){return null},Ue.B.prototype.setExternalTexture=function(e,t){throw new Error("setExternalTexture: This engine does not support external textures!")},Ue.B.prototype.updateVideoTexture=function(e,t,i){if(!e||e._isDisabled)return;const n=this._getInternalFormat(e.format),s=this._getRGBABufferInternalSizedFormat(0,e.format),r=this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0);this._unpackFlipY(!i);try{if(void 0===this._videoTextureSupported&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,n,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,n,this._gl.UNSIGNED_BYTE,t);else{if(!e._workingCanvas){e._workingCanvas=this.createCanvas(e.width,e.height);const t=e._workingCanvas.getContext("2d");if(!t)throw new Error("Unable to get 2d context");e._workingContext=t,e._workingCanvas.width=e.width,e._workingCanvas.height=e.height}e._workingContext.clearRect(0,0,e.width,e.height),e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e.width,e.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,n,this._gl.UNSIGNED_BYTE,e._workingCanvas)}e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),r||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}catch(o){e._isDisabled=!0}},Ue.B.prototype.restoreSingleAttachment=function(){const e=this._gl;this.bindAttachments([e.BACK])},Ue.B.prototype.restoreSingleAttachmentForRenderTarget=function(){const e=this._gl;this.bindAttachments([e.COLOR_ATTACHMENT0])},Ue.B.prototype.buildTextureLayout=function(e){const t=this._gl,i=[];for(let n=0;n1?"COLOR_ATTACHMENT"+t:"COLOR_ATTACHMENT"+t+"_WEBGL"],n.readBuffer(s[t]),n.drawBuffers(s),n.blitFramebuffer(0,0,i.width,i.height,0,0,i.width,i.height,n.COLOR_BUFFER_BIT,n.NEAREST)}for(let e=0;e1?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];n.drawBuffers(s)}for(let o=0;o1&&(13===t.depthTextureFormat||17===t.depthTextureFormat||16===t.depthTextureFormat||14===t.depthTextureFormat||18===t.depthTextureFormat)&&(l=t.depthTextureFormat));const S=this._gl,E=S.createFramebuffer();this._bindUnboundFramebuffer(E);const x=e.width||e,b=e.height||e,C=[],y=[],A=this.webGLVersion>1&&a&&(13===t.depthTextureFormat||17===t.depthTextureFormat||18===t.depthTextureFormat),R=this._setupFramebufferDepthAttachments(!A&&o,!a&&r,x,b);T._framebuffer=E,T._depthStencilBuffer=R,T._generateDepthBuffer=!a&&r,T._generateStencilBuffer=!A&&o,T._attachments=y;for(let P=0;P1||this.isWebGPU);const h=this.webGLVersion>1,m=S[h?"COLOR_ATTACHMENT"+P:"COLOR_ATTACHMENT"+P+"_WEBGL"];if(y.push(m),-1===o)continue;const g=new Be.l(this,Be.S.MultiRenderTarget);C[P]=g,S.activeTexture(S["TEXTURE"+P]),S.bindTexture(o,g._hardwareTexture.underlyingResource),S.texParameteri(o,S.TEXTURE_MAG_FILTER,l.mag),S.texParameteri(o,S.TEXTURE_MIN_FILTER,l.min),S.texParameteri(o,S.TEXTURE_WRAP_S,S.CLAMP_TO_EDGE),S.texParameteri(o,S.TEXTURE_WRAP_T,S.CLAMP_TO_EDGE);const T=this._getRGBABufferInternalSizedFormat(t,r,i),E=this._getInternalFormat(r),A=this._getWebGLTextureType(t);if(!h||35866!==o&&32879!==o)if(34067===o){for(let e=0;e<6;e++)S.texImage2D(S.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,T,x,b,0,E,A,null);g.isCube=!0}else S.texImage2D(S.TEXTURE_2D,0,T,x,b,0,E,A,null);else 35866===o?g.is2DArray=!0:g.is3D=!0,g.baseDepth=g.depth=a,S.texImage3D(o,0,T,x,b,a,0,E,A,null);s&&S.generateMipmap(o),this._bindTextureDirectly(o,null),g.baseWidth=x,g.baseHeight=b,g.width=x,g.height=b,g.isReady=!0,g.samples=1,g.generateMipMaps=s,g.samplingMode=e,g.type=t,g._useSRGBBuffer=i,g.format=r,this._internalTexturesCache.push(g)}if(a&&this._caps.depthTextureExtension){const e=new Be.l(this,Be.S.Depth);let t=5,i=S.DEPTH_COMPONENT16,n=S.DEPTH_COMPONENT,r=S.UNSIGNED_SHORT,o=S.DEPTH_ATTACHMENT;this.webGLVersion<2?i=S.DEPTH_COMPONENT:14===l?(t=1,r=S.FLOAT,i=S.DEPTH_COMPONENT32F):18===l?(t=0,r=S.FLOAT_32_UNSIGNED_INT_24_8_REV,i=S.DEPTH32F_STENCIL8,n=S.DEPTH_STENCIL,o=S.DEPTH_STENCIL_ATTACHMENT):16===l?(t=0,r=S.UNSIGNED_INT,i=S.DEPTH_COMPONENT24,o=S.DEPTH_ATTACHMENT):13!==l&&17!==l||(t=12,r=S.UNSIGNED_INT_24_8,i=S.DEPTH24_STENCIL8,n=S.DEPTH_STENCIL,o=S.DEPTH_STENCIL_ATTACHMENT),S.activeTexture(S.TEXTURE0),S.bindTexture(S.TEXTURE_2D,e._hardwareTexture.underlyingResource),S.texParameteri(S.TEXTURE_2D,S.TEXTURE_MAG_FILTER,S.NEAREST),S.texParameteri(S.TEXTURE_2D,S.TEXTURE_MIN_FILTER,S.NEAREST),S.texParameteri(S.TEXTURE_2D,S.TEXTURE_WRAP_S,S.CLAMP_TO_EDGE),S.texParameteri(S.TEXTURE_2D,S.TEXTURE_WRAP_T,S.CLAMP_TO_EDGE),S.texImage2D(S.TEXTURE_2D,0,i,x,b,0,n,r,null),S.framebufferTexture2D(S.FRAMEBUFFER,o,S.TEXTURE_2D,e._hardwareTexture.underlyingResource,0),e.baseWidth=x,e.baseHeight=b,e.width=x,e.height=b,e.isReady=!0,e.samples=1,e.generateMipMaps=s,e.samplingMode=1,e.format=l,e.type=t,C[h]=e,this._internalTexturesCache.push(e)}return T.setTextures(C),i&&S.drawBuffers(y),this._bindUnboundFramebuffer(null),T.setLayerAndFaceIndices(g,m),this.resetTextureCache(),T},Ue.B.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t,i=!0){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;const n=e._attachments.length;if(0===n)return 1;const s=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples);const r=!!e._depthStencilBuffer;if(r&&(s.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(s.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null),t>1&&"function"==typeof s.renderbufferStorageMultisample){const r=s.createFramebuffer();if(!r)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=r,this._bindUnboundFramebuffer(r);const o=[];for(let t=0;t1?"COLOR_ATTACHMENT"+i:"COLOR_ATTACHMENT"+i+"_WEBGL"],l=this._createRenderBuffer(n.width,n.height,t,-1,this._getRGBAMultiSampleBufferFormat(n.type,n.format),a);if(!l)throw new Error("Unable to create multi sampled framebuffer");r.addMSAARenderBuffer(l),n.samples=t,o.push(a)}i&&s.drawBuffers(o)}else this._bindUnboundFramebuffer(e._framebuffer);return r&&(e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t)),this._bindUnboundFramebuffer(null),t},Ue.B.prototype._createDepthStencilCubeTexture=function(e,t,i){const n=new Be.l(this,Be.S.DepthStencil);if(n.isCube=!0,1===this.webGLVersion)return p.Y.Error("Depth cube texture is not supported by WebGL 1."),n;const s=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},t),r=this._gl;this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,n,!0),this._setupDepthStencilTexture(n,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction),i._depthStencilTexture=n,i._depthStencilTextureWithStencil=s.generateStencil;for(let o=0;o<6;o++)s.generateStencil?r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+o,0,r.DEPTH24_STENCIL8,e,e,0,r.DEPTH_STENCIL,r.UNSIGNED_INT_24_8,null):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+o,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(n),n},Ue.B.prototype._partialLoadFile=function(e,t,i,n,s=null){this._loadFile(e,(e=>{i[t]=e,i._internalCount++,6===i._internalCount&&n(i)}),void 0,void 0,!0,((e,t)=>{s&&e&&s(e.status+" "+e.statusText,t)}))},Ue.B.prototype._cascadeLoadFiles=function(e,t,i,n=null){const s=[];s._internalCount=0;for(let r=0;r<6;r++)this._partialLoadFile(i[r],r,s,t,n)},Ue.B.prototype._cascadeLoadImgs=function(e,t,i,n,s=null,r){const o=[];o._internalCount=0;for(let a=0;a<6;a++)this._partialLoadImg(n[a],a,o,e,t,i,s,r)},Ue.B.prototype._partialLoadImg=function(e,t,i,n,s,r,o=null,a){const l=(0,Ce.f)();(0,ye.r6)(e,(e=>{i[t]=e,i._internalCount++,n&&n.removePendingData(l),6===i._internalCount&&r&&r(s,i)}),((e,t)=>{n&&n.removePendingData(l),o&&o(e,t)}),n?n.offlineProvider:null,a),n&&n.addPendingData(l)},Ue.B.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?3:2,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)},Ue.B.prototype.createCubeTextureBase=function(e,t,i,n,s=null,r=null,o,a=null,l=!1,h=0,c=0,d=null,u=null,f=null,_=!1){const m=d||new Be.l(this,Be.S.Cube);m.isCube=!0,m.url=e,m.generateMipMaps=!n,m._lodGenerationScale=h,m._lodGenerationOffset=c,m._useSRGBBuffer=!!_&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||!!n),m!==d&&(m.label=e.substring(0,60)),this._doNotHandleContextLost||(m._extension=a,m._files=i);const g=e;this._transformTextureUrl&&!d&&(e=this._transformTextureUrl(e));const v=e.split("?")[0],T=v.lastIndexOf("."),S=a||(T>-1?v.substring(T).toLowerCase():"");let E=null;for(const p of Ue.B._TextureLoaders)if(p.canLoad(S)){E=p;break}const x=(d,v)=>{e===g?r&&d&&r(d.status+" "+d.statusText,v):(p.Y.Warn(`Failed to load ${e}, falling back to the ${g}`),this.createCubeTextureBase(g,t,i,!!n,s,r,o,a,l,h,c,m,u,f,_))};if(E){const n=e=>{u&&u(m,e),E.loadCubeData(e,m,l,s,r)};i&&6===i.length?E.supportCascades?this._cascadeLoadFiles(t,(e=>n(e.map((e=>new Uint8Array(e))))),i,r):r?r("Textures type does not support cascades."):p.Y.Warn("Texture loader does not support cascades."):this._loadFile(e,(e=>n(new Uint8Array(e))),void 0,void 0,!0,x)}else{if(!i)throw new Error("Cannot load cubemap because files were not defined");this._cascadeLoadImgs(t,m,((e,t)=>{f&&f(e,t)}),i,r)}return this._internalTexturesCache.push(m),m},Ue.B.prototype.createCubeTexture=function(e,t,i,n,s=null,r=null,o,a=null,l=!1,h=0,c=0,d=null,u,f=!1){const _=this._gl;return this.createCubeTextureBase(e,t,i,!!n,s,r,o,a,l,h,c,d,(e=>this._bindTextureDirectly(_.TEXTURE_CUBE_MAP,e,!0)),((e,t)=>{const i=this.needPOTTextures?Ue.B.GetExponentOfTwo(t[0].width,this._caps.maxCubemapTextureSize):t[0].width,r=i,a=[_.TEXTURE_CUBE_MAP_POSITIVE_X,_.TEXTURE_CUBE_MAP_POSITIVE_Y,_.TEXTURE_CUBE_MAP_POSITIVE_Z,_.TEXTURE_CUBE_MAP_NEGATIVE_X,_.TEXTURE_CUBE_MAP_NEGATIVE_Y,_.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(_.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(!1);const l=o?this._getInternalFormat(o,e._useSRGBBuffer):e._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:_.RGBA;let h=o?this._getInternalFormat(o):_.RGBA;e._useSRGBBuffer&&1===this.webGLVersion&&(h=l);for(let n=0;n{this.unRegisterView(e)})),s},fe.D.prototype.unRegisterView=function(e){if(!this.views||0===this.views.length)return this;for(const t of this.views)if(t.target===e){const e=this.views.indexOf(t);-1!==e&&this.views.splice(e,1);break}return this},fe.D.prototype._renderViewStep=function(e){const t=e.target,i=t.getContext("2d");if(!i)return!0;const n=this.getRenderingCanvas();xh.notifyObservers(e);const s=e.camera;let r=null,o=null;if(s){if(o=s.getScene(),!o||o.activeCameras&&o.activeCameras.length)return!0;this.activeView=e,r=o.activeCamera,o.activeCamera=s}if(e.customResize)e.customResize(t);else{const e=Math.floor(t.clientWidth/this._hardwareScalingLevel),i=Math.floor(t.clientHeight/this._hardwareScalingLevel),s=e!==t.width||n.width!==t.width||i!==t.height||n.height!==t.height;t.clientWidth&&t.clientHeight&&s&&(t.width=e,t.height=i,this.setSize(e,i))}return!(!n.width||!n.height)&&(this._renderFrame(),this.flushFramebuffer(),e.clearBeforeCopy&&i.clearRect(0,0,n.width,n.height),i.drawImage(n,0,0),r&&o&&(o.activeCamera=r),bh.notifyObservers(e),!0)},fe.D.prototype._renderViews=function(){if(!this.views||0===this.views.length)return!1;if(!this.getRenderingCanvas())return!1;let e;for(const t of this.views){if(!t.enabled)continue;if(t.target!==this.inputElement){if(!this._renderViewStep(t))return!1}else e=t}return!(e&&!this._renderViewStep(e))&&(this.activeView=null,!0)};var Ch=i(9834);function yh(e){if(this._excludedCompressedTextures&&this._excludedCompressedTextures.some((t=>{const i="\\b"+t+"\\b";return e&&(e===t||e.match(new RegExp(i,"g")))})))return e;const t=e.lastIndexOf("."),i=e.lastIndexOf("?"),n=i>-1?e.substring(i,e.length):"";return(t>-1?e.substring(0,t):e)+this._textureFormatInUse+n}Ue.B.prototype.createStorageBuffer=function(e,t){throw new Error("createStorageBuffer: Unsupported method in this engine!")},Ue.B.prototype.updateStorageBuffer=function(e,t,i,n){},Ue.B.prototype.readFromStorageBuffer=function(e,t,i,n){throw new Error("readFromStorageBuffer: Unsupported method in this engine!")},Ue.B.prototype.setStorageBuffer=function(e,t){throw new Error("setStorageBuffer: Unsupported method in this engine!")},Object.defineProperty(fe.D.prototype,"texturesSupported",{get:function(){const e=new Array;return this._caps.astc&&e.push("-astc.ktx"),this._caps.s3tc&&e.push("-dxt.ktx"),this._caps.pvrtc&&e.push("-pvrtc.ktx"),this._caps.etc2&&e.push("-etc2.ktx"),this._caps.etc1&&e.push("-etc1.ktx"),e},enumerable:!0,configurable:!0}),Object.defineProperty(fe.D.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0}),fe.D.prototype.setCompressedTextureExclusions=function(e){this._excludedCompressedTextures=e},fe.D.prototype.setTextureFormatToUse=function(e){const t=this.texturesSupported;for(let i=0,n=t.length;i{this._flush()}))}writeUint32(e){this._flushIfNecessary(1),this._uint32s[this._position++]=e}writeInt32(e){this._flushIfNecessary(1),this._int32s[this._position++]=e}writeFloat32(e){this._flushIfNecessary(1),this._float32s[this._position++]=e}writeUint32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._uint32s.set(e,this._position),this._position+=e.length}writeInt32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._int32s.set(e,this._position),this._position+=e.length}writeFloat32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._float32s.set(e,this._position),this._position+=e.length}writeNativeData(e){this._flushIfNecessary(e.length),this._uint32s.set(e,this._position),this._position+=e.length}writeBoolean(e){this.writeUint32(e?1:0)}_flushIfNecessary(e){this._position+e>this._length&&this._flush()}_flush(){this._nativeDataStream.writeBuffer(this._uint32s.buffer,this._position),this._position=0}}Ah.DEFAULT_BUFFER_SIZE=65536;const Rh=[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))],Ph=[()=>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],Ih=(e,t)=>Rh[e]*Ph[e](t),Mh=[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 Oh{constructor(){this.preScaled=!1,this.l00=o.P.Zero(),this.l1_1=o.P.Zero(),this.l10=o.P.Zero(),this.l11=o.P.Zero(),this.l2_2=o.P.Zero(),this.l2_1=o.P.Zero(),this.l20=o.P.Zero(),this.l21=o.P.Zero(),this.l22=o.P.Zero()}addLight(e,t,i){o.jp.Vector3[0].set(t.r,t.g,t.b);const n=o.jp.Vector3[0],s=o.jp.Vector3[1];n.scaleToRef(i,s),s.scaleToRef(Ih(0,e),o.jp.Vector3[2]),this.l00.addInPlace(o.jp.Vector3[2]),s.scaleToRef(Ih(1,e),o.jp.Vector3[2]),this.l1_1.addInPlace(o.jp.Vector3[2]),s.scaleToRef(Ih(2,e),o.jp.Vector3[2]),this.l10.addInPlace(o.jp.Vector3[2]),s.scaleToRef(Ih(3,e),o.jp.Vector3[2]),this.l11.addInPlace(o.jp.Vector3[2]),s.scaleToRef(Ih(4,e),o.jp.Vector3[2]),this.l2_2.addInPlace(o.jp.Vector3[2]),s.scaleToRef(Ih(5,e),o.jp.Vector3[2]),this.l2_1.addInPlace(o.jp.Vector3[2]),s.scaleToRef(Ih(6,e),o.jp.Vector3[2]),this.l20.addInPlace(o.jp.Vector3[2]),s.scaleToRef(Ih(7,e),o.jp.Vector3[2]),this.l21.addInPlace(o.jp.Vector3[2]),s.scaleToRef(Ih(8,e),o.jp.Vector3[2]),this.l22.addInPlace(o.jp.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(Mh[0]),this.l1_1.scaleInPlace(Mh[1]),this.l10.scaleInPlace(Mh[2]),this.l11.scaleInPlace(Mh[3]),this.l2_2.scaleInPlace(Mh[4]),this.l2_1.scaleInPlace(Mh[5]),this.l20.scaleInPlace(Mh[6]),this.l21.scaleInPlace(Mh[7]),this.l22.scaleInPlace(Mh[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(Rh[0]),this.l1_1.scaleInPlace(Rh[1]),this.l10.scaleInPlace(Rh[2]),this.l11.scaleInPlace(Rh[3]),this.l2_2.scaleInPlace(Rh[4]),this.l2_1.scaleInPlace(Rh[5]),this.l20.scaleInPlace(Rh[6]),this.l21.scaleInPlace(Rh[7]),this.l22.scaleInPlace(Rh[8])}updateFromArray(e){return o.P.FromArrayToRef(e[0],0,this.l00),o.P.FromArrayToRef(e[1],0,this.l1_1),o.P.FromArrayToRef(e[2],0,this.l10),o.P.FromArrayToRef(e[3],0,this.l11),o.P.FromArrayToRef(e[4],0,this.l2_2),o.P.FromArrayToRef(e[5],0,this.l2_1),o.P.FromArrayToRef(e[6],0,this.l20),o.P.FromArrayToRef(e[7],0,this.l21),o.P.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return o.P.FromFloatsToRef(e[0],e[1],e[2],this.l00),o.P.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),o.P.FromFloatsToRef(e[6],e[7],e[8],this.l10),o.P.FromFloatsToRef(e[9],e[10],e[11],this.l11),o.P.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),o.P.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),o.P.FromFloatsToRef(e[18],e[19],e[20],this.l20),o.P.FromFloatsToRef(e[21],e[22],e[23],this.l21),o.P.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return(new Oh).updateFromArray(e)}static FromPolynomial(e){const t=new Oh;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 Dh{constructor(){this.x=o.P.Zero(),this.y=o.P.Zero(),this.z=o.P.Zero(),this.xx=o.P.Zero(),this.yy=o.P.Zero(),this.zz=o.P.Zero(),this.xy=o.P.Zero(),this.yz=o.P.Zero(),this.zx=o.P.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=Oh.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){o.jp.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=o.jp.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),o.jp.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),o.jp.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(o.jp.Vector3[0]).addInPlace(o.jp.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(o.jp.Vector3[0]).subtractInPlace(o.jp.Vector3[1]),this.zz.copyFrom(e.l00),o.jp.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(o.jp.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 Dh).updateFromHarmonics(e)}static FromArray(e){const t=new Dh;return o.P.FromArrayToRef(e[0],0,t.x),o.P.FromArrayToRef(e[1],0,t.y),o.P.FromArrayToRef(e[2],0,t.z),o.P.FromArrayToRef(e[3],0,t.xx),o.P.FromArrayToRef(e[4],0,t.yy),o.P.FromArrayToRef(e[5],0,t.zz),o.P.FromArrayToRef(e[6],0,t.yz),o.P.FromArrayToRef(e[7],0,t.zx),o.P.FromArrayToRef(e[8],0,t.xy),t}}const Nh="rgbdDecodePixelShader",Fh="varying vec2 vUV;\nuniform sampler2D textureSampler;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}";Ht.v.ShadersStore[Nh]=Fh;function wh(e,t,i,n,s,r,o,a){const l=t.getEngine();return t.isReady=!1,s=null!=s?s:t.samplingMode,n=null!=n?n:t.type,r=null!=r?r:t.format,o=null!=o?o:t.width,a=null!=a?a:t.height,-1===n&&(n=0),new Promise((h=>{const c=new Zt("postprocess",e,null,null,1,null,s,l,!1,void 0,n,void 0,null,!1,r);c.externalTextureSamplerBinding=!0;const d=l.createRenderTargetTexture({width:o,height:a},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:s,type:n,format:r});c.getEffect().executeWhenCompiled((()=>{c.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},i.postProcessManager.directRender([c],d,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(t),c&&c.dispose(),d._swapAndDie(t),t.type=n,t.format=5,t.isReady=!0,h(t)}))}))}let Lh,Bh;function Uh(e){Lh||(Lh=new Float32Array(1),Bh=new Int32Array(Lh.buffer)),Lh[0]=e;const t=Bh[0];let i=t>>16&32768,n=t>>12&2047;const s=t>>23&255;return s<103?i:s>142?(i|=31744,i|=(255==s?0:1)&&8388607&t,i):s<113?(n|=2048,i|=(n>>114-s)+(n>>113-s&1),i):(i|=s-112<<10|n>>1,i+=1&n,i)}function Vh(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))}class kh{static ExpandRGBDTexture(e){const t=e._texture;if(!t||!e.isRGBD)return;const i=t.getEngine(),n=i.getCaps(),s=t.isReady;let r=!1;n.textureHalfFloatRender&&n.textureHalfFloatLinearFiltering?(r=!0,t.type=2):n.textureFloatRender&&n.textureFloatLinearFiltering&&(r=!0,t.type=1),r&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);const o=()=>{if(r){const n=new Zt("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1);n.externalTextureSamplerBinding=!0;const s=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});n.getEffect().executeWhenCompiled((()=>{n.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([n],s,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),n&&n.dispose(),s._swapAndDie(t),t.isReady=!0}))}};s?o():e.onLoadObservable.addOnce(o)}static EncodeTextureToRGBD(e,t,i=0){return wh("rgbdEncode",e,t,i,1,5)}}class Gh{constructor(e,t,i,n){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=n}}class zh{static ConvertCubeMapTextureToSphericalPolynomial(e){var t;if(!e.isCube)return null;null===(t=e.getScene())||void 0===t||t.getEngine().flushFramebuffer();const i=e.getSize().width,n=e.readPixels(0,void 0,void 0,!1),s=e.readPixels(1,void 0,void 0,!1);let r,o;e.isRenderTarget?(r=e.readPixels(3,void 0,void 0,!1),o=e.readPixels(2,void 0,void 0,!1)):(r=e.readPixels(2,void 0,void 0,!1),o=e.readPixels(3,void 0,void 0,!1));const a=e.readPixels(4,void 0,void 0,!1),l=e.readPixels(5,void 0,void 0,!1),h=e.gammaSpace;let c=0;return 1!=e.textureType&&2!=e.textureType||(c=1),new Promise((e=>{Promise.all([s,n,r,o,a,l]).then((([t,n,s,r,o,a])=>{const l={size:i,right:n,left:t,up:s,down:r,front:o,back:a,format:5,type:c,gammaSpace:h};e(this.ConvertCubeMapToSphericalPolynomial(l))}))}))}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){const t=new Oh;let i=0;const n=2/e.size,s=n,r=.5*n,o=r-1;for(let h=0;h<6;h++){const l=this._FileFaces[h],c=e[l.name];let d=o;const u=5===e.format?4:3;for(let h=0;hv){const t=v/e;_*=t,m*=t,g*=t}}else _=S.R.Clamp(_,0,v),m=S.R.Clamp(m,0,v),g=S.R.Clamp(g,0,v);const T=new a.Wo(_,m,g);t.addLight(o,T,f),i+=f,p+=n}d+=s}}const l=6*(4*Math.PI)/6/i;return t.scaleInPlace(l),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),Dh.FromHarmonics(t)}}zh._FileFaces=[new Gh("right",new o.P(1,0,0),new o.P(0,0,-1),new o.P(0,-1,0)),new Gh("left",new o.P(-1,0,0),new o.P(0,0,1),new o.P(0,-1,0)),new Gh("up",new o.P(0,1,0),new o.P(1,0,0),new o.P(0,0,1)),new Gh("down",new o.P(0,-1,0),new o.P(1,0,0),new o.P(0,0,-1)),new Gh("front",new o.P(0,0,1),new o.P(1,0,0),new o.P(0,-1,0)),new Gh("back",new o.P(0,0,-1),new o.P(-1,0,0),new o.P(0,-1,0))],zh.MAX_HDRI_VALUE=4096,zh.PRESERVE_CLAMPED_COLORS=!1,Re.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)},Object.defineProperty(Re.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=zh.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});const Wh="rgbdEncodePixelShader",Hh="varying vec2 vUV;\nuniform sampler2D textureSampler;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}";Ht.v.ShadersStore[Wh]=Hh;const Xh="image/png",Yh=2,jh=[134,22,135,150,246,214,150,54];function Kh(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);let i=0;for(let o=0;oYh)throw new Error(`Unsupported babylon environment map version "${e.version}". Latest supported version is "${Yh}".`);return 2===e.version?e:e=Object.assign(Object.assign({},e),{version:2,imageType:Xh})}function $h(e,t){const i=(t=qh(t)).specular;let n=S.R.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 s=new Array(n);for(let r=0;r{if(i){const i=t.createTexture(null,!0,!0,null,1,null,(e=>{u(e)}),e);n.getEffect().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],h,!0,r,o),t.restoreDefaultFramebuffer(),i.dispose(),URL.revokeObjectURL(s),d())}))}else{if(t._uploadImageToTexture(c,e,r,o),a){const i=l[o];i&&t._uploadImageToTexture(i._texture,e,r,0)}d()}}))}function Jh(e,t,i=Xh){if(!se.w1.IsExponentOfTwo(e.width))throw new Error("Texture size must be a power of two");const n=S.R.ILog2(e.width)+1,s=e.getEngine();let r=!1,o=!1,a=null,l=null,h=null;const c=s.getCaps();if(e.format=5,e.type=0,e.generateMipMaps=!0,e._cachedAnisotropicFilteringLevel=null,s.updateTextureSamplingMode(3,e),c.textureLOD?s._features.supportRenderAndCopyToLodForFloatTextures?c.textureHalfFloatRender&&c.textureHalfFloatLinearFiltering?(r=!0,e.type=2):c.textureFloatRender&&c.textureFloatLinearFiltering&&(r=!0,e.type=1):r=!1:(r=!1,o=!0,h={}),r)a=new Zt("rgbdDecode","rgbdDecode",null,null,1,null,3,s,!1,void 0,e.type,void 0,null,!1),e._isRGBD=!1,e.invertY=!1,l=s.createRenderTargetCubeTexture(e.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:e.type,format:5});else if(e._isRGBD=!0,e.invertY=!0,o){const t=3,i=e._lodGenerationScale,r=e._lodGenerationOffset;for(let o=0;oZh(t,s,r,a,f,n,u,o,h,l,e)));else{const t=new Image;t.src=f,_=new Promise(((i,c)=>{t.onload=()=>{Zh(t,s,r,a,f,n,u,o,h,l,e).then((()=>i())).catch((e=>{c(e)}))},t.onerror=e=>{c(e)}}))}d.push(_)}if(t.length{l&&(s._releaseTexture(e),l._swapAndDie(e)),a&&a.dispose(),o&&(e._lodTextureHigh&&e._lodTextureHigh._texture&&(e._lodTextureHigh._texture.isReady=!0),e._lodTextureMid&&e._lodTextureMid._texture&&(e._lodTextureMid._texture.isReady=!0),e._lodTextureLow&&e._lodTextureLow._texture&&(e._lodTextureLow._texture.isReady=!0))}))}function ec(e,t){const i=(t=qh(t)).irradiance;if(!i)return;const n=new Dh;o.P.FromArrayToRef(i.x,0,n.x),o.P.FromArrayToRef(i.y,0,n.y),o.P.FromArrayToRef(i.z,0,n.z),o.P.FromArrayToRef(i.xx,0,n.xx),o.P.FromArrayToRef(i.yy,0,n.yy),o.P.FromArrayToRef(i.zz,0,n.zz),o.P.FromArrayToRef(i.yz,0,n.yz),o.P.FromArrayToRef(i.zx,0,n.zx),o.P.FromArrayToRef(i.xy,0,n.xy),e._sphericalPolynomial=n}function tc(e,t,i,n){let s=n,r=0,o="";for(;s=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||95==t}function sc(e){let t=0,i="",n=!1;const s=[];for(;t=0&&e.charAt(t)!==i;)t--;return t}class oc{get code(){return this._sourceCode}constructor(e,t=20){this.debug=!1,this._sourceCode=e,this._numMaxIterations=t,this._functionDescr=[],this.inlineToken="#define inline"}processCode(){this.debug&&console.log(`Start inlining process (code size=${this._sourceCode.length})...`),this._collectFunctions(),this._processInlining(this._numMaxIterations),this.debug&&console.log("End of inlining process.")}_collectFunctions(){let e=0;for(;e=0&&u.push(t.substring(i+1))}"void"!==s&&u.push("return"),this._functionDescr.push({name:r,type:s,parameters:u,body:c,callIndex:0}),e=h+1;const p=t>0?this._sourceCode.substring(0,t):"",f=h+1=0&&this._replaceFunctionCallsByCode(););return this.debug&&console.log(`numMaxIterations is ${e} after inlining process`),e>=0}_replaceFunctionCallsByCode(){let e=!1;for(const t of this._functionDescr){const{name:i,type:n,parameters:s,body:r}=t;let o=0;for(;o{const t=[];let i=0,n=0;for(;i0?this._sourceCode.substring(0,a):"";const g=h+1{const a=s[0];return nc(e.charAt(a-1))||nc(e.charAt(a+r))?t[n]:o}))}return e}}oc._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;var ac=i(3156);class lc{get isAsync(){return this.isParallelCompiled}get isReady(){if(this.compilationError){const e=this.compilationError.message;throw new Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}return this.isCompiled}_getVertexShaderCode(){return null}_getFragmentShaderCode(){return null}_handlesSpectorRebuildCallback(e){throw new Error("Not implemented")}constructor(e){this.isParallelCompiled=!0,this.isCompiled=!1,this._valueCache={},this._engine=e}_fillEffectInformation(e,t,i,n,s,r,o,a){const l=this._engine;if(l.supportsUniformBuffers)for(const c in t)e.bindUniformBlock(c,t[c]);let h;for(this._engine.getUniforms(this,i).forEach(((e,t)=>{n[i[t]]=e})),this._uniforms=n,h=0;h{r[e]=t})),a.push(...l.getAttributes(this,o))}dispose(){this._uniforms={}}_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)return n=[t,i],this._valueCache[e]=n,!0;let s=!1;return n[0]!==t&&(n[0]=t,s=!0),n[1]!==i&&(n[1]=i,s=!0),s}_cacheFloat3(e,t,i,n){let s=this._valueCache[e];if(!s)return s=[t,i,n],this._valueCache[e]=s,!0;let r=!1;return s[0]!==t&&(s[0]=t,r=!0),s[1]!==i&&(s[1]=i,r=!0),s[2]!==n&&(s[2]=n,r=!0),r}_cacheFloat4(e,t,i,n,s){let r=this._valueCache[e];if(!r)return r=[t,i,n,s],this._valueCache[e]=r,!0;let o=!1;return r[0]!==t&&(r[0]=t,o=!0),r[1]!==i&&(r[1]=i,o=!0),r[2]!==n&&(r[2]=n,o=!0),r[3]!==s&&(r[3]=s,o=!0),o}setInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,n){this._cacheFloat3(e,t,i,n)&&(this._engine.setInt3(this._uniforms[e],t,i,n)||(this._valueCache[e]=null))}setInt4(e,t,i,n,s){this._cacheFloat4(e,t,i,n,s)&&(this._engine.setInt4(this._uniforms[e],t,i,n,s)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this._engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this._engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this._engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this._engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];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,s){this._cacheFloat4(e,t,i,n,s)&&(this._engine.setUInt4(this._uniforms[e],t,i,n,s)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this._engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this._engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this._engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this._engine.setUIntArray4(this._uniforms[e],t)}setFloatArray(e,t){this._valueCache[e]=null,this._engine.setFloatArray(this._uniforms[e],t)}setFloatArray2(e,t){this._valueCache[e]=null,this._engine.setFloatArray2(this._uniforms[e],t)}setFloatArray3(e,t){this._valueCache[e]=null,this._engine.setFloatArray3(this._uniforms[e],t)}setFloatArray4(e,t){this._valueCache[e]=null,this._engine.setFloatArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this._engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this._engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this._engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this._engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this._engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this._engine.setMatrices(this._uniforms[e],t.toArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this._engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this._engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setBool(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this._engine.setInt(this._uniforms[e],t?1:0)&&(this._valueCache[e]=t?1:0)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this._engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this._engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this._engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,n){this._cacheFloat3(e,t,i,n)&&(this._engine.setFloat3(this._uniforms[e],t,i,n)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this._engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,n,s){this._cacheFloat4(e,t,i,n,s)&&(this._engine.setFloat4(this._uniforms[e],t,i,n,s)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this._engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}}class hc extends jt{get _framebuffer(){return this.__framebuffer}set _framebuffer(e){this.__framebuffer&&this._engine._releaseFramebufferObjects(this.__framebuffer),this.__framebuffer=e}get _framebufferDepthStencil(){return this.__framebufferDepthStencil}set _framebufferDepthStencil(e){this.__framebufferDepthStencil&&this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil),this.__framebufferDepthStencil=e}constructor(e,t,i,n){super(e,t,i,n),this.__framebuffer=null,this.__framebufferDepthStencil=null,this._engine=n}dispose(e=!1){this._framebuffer=null,this._framebufferDepthStencil=null,super.dispose(e)}}class cc{get underlyingResource(){return this._nativeTexture}constructor(e,t){this._engine=t,this.set(e)}setUsage(){}set(e){this._nativeTexture=e}reset(){this._nativeTexture=null}release(){this._nativeTexture&&this._engine.deleteTexture(this._nativeTexture),this.reset()}}const dc=new r.y$;if("undefined"!=typeof self&&!Object.prototype.hasOwnProperty.call(self,"_native")){let e;Object.defineProperty(self,"_native",{get:()=>e,set:t=>{e=t,e&&dc.notifyObservers(e)}})}class uc extends Ki.h{}class pc{constructor(e){this._engine=e,this._pending=new Array,this._isCommandBufferScopeActive=!1,this._commandStream=fc._createNativeDataStream(),this._engine.setCommandDataStream(this._commandStream)}beginCommandScope(){if(this._isCommandBufferScopeActive)throw new Error("Command scope already active.");this._isCommandBufferScopeActive=!0}endCommandScope(){if(!this._isCommandBufferScopeActive)throw new Error("Command scope is not active.");this._isCommandBufferScopeActive=!1,this._submit()}startEncodingCommand(e){this._commandStream.writeNativeData(e)}encodeCommandArgAsUInt32(e){this._commandStream.writeUint32(e)}encodeCommandArgAsUInt32s(e){this._commandStream.writeUint32Array(e)}encodeCommandArgAsInt32(e){this._commandStream.writeInt32(e)}encodeCommandArgAsInt32s(e){this._commandStream.writeInt32Array(e)}encodeCommandArgAsFloat32(e){this._commandStream.writeFloat32(e)}encodeCommandArgAsFloat32s(e){this._commandStream.writeFloat32Array(e)}encodeCommandArgAsNativeData(e){this._commandStream.writeNativeData(e),this._pending.push(e)}finishEncodingCommand(){this._isCommandBufferScopeActive||this._submit()}_submit(){this._engine.submitCommands(),this._pending.length=0}}class fc extends fe.D{setHardwareScalingLevel(e){super.setHardwareScalingLevel(e),this._engine.setHardwareScalingLevel(e)}constructor(e={}){if(super(null,!1,void 0,e.adaptToDeviceRatio),this._engine=new _native.Engine,this._camera=_native.Camera?new _native.Camera:null,this._commandBufferEncoder=new pc(this._engine),this._boundBuffersVertexArray=null,this._currentDepthTest=_native.Engine.DEPTH_TEST_LEQUAL,this._stencilTest=!1,this._stencilMask=255,this._stencilFunc=519,this._stencilFuncRef=0,this._stencilFuncMask=255,this._stencilOpStencilFail=7680,this._stencilOpDepthFail=7680,this._stencilOpStencilDepthPass=7681,this._zOffset=0,this._zOffsetUnits=0,this._depthWrite=!0,_native.Engine.PROTOCOL_VERSION!==fc.PROTOCOL_VERSION)throw new Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${fc.PROTOCOL_VERSION} (JS)`);this._webGLVersion=2,this.disableUniformBuffers=!0,this._shaderPlatformName="NATIVE",this._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_SIZE,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!0,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,textureFloat:!0,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloat:!1,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!1,textureLOD:!0,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!0,instancedArrays:!0,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,blendMinMax:!1,maxMSAASamples:1,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!1,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!1,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!1,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,_collectUbosUpdatedInFrame:!1},se.w1.Log("Babylon Native (v"+fe.D.Version+") launched"),se.w1.LoadScript=function(e,t,i,n){se.w1.LoadFile(e,(e=>{Function(e).apply(null),t&&t()}),void 0,void 0,!1,((e,t)=>{i&&i("LoadScript Error",t)}))},"undefined"==typeof URL&&(window.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(window.Blob=function(e){return e}),Array.prototype.flat||Object.defineProperty(Array.prototype,"flat",{configurable:!0,value:function e(){const t=isNaN(arguments[0])?1:Number(arguments[0]);return t?Array.prototype.reduce.call(this,(function(i,n){return Array.isArray(n)?i.push.apply(i,e.call(n,t-1)):i.push(n),i}),[]):Array.prototype.slice.call(this)},writable:!0});const t=window&&window.devicePixelRatio||1;this._hardwareScalingLevel=e.adaptToDeviceRatio?1/t:1,this._engine.setHardwareScalingLevel(this._hardwareScalingLevel),this._lastDevicePixelRatio=t,this.resize();const i=this.getDepthFunction();i&&this.setDepthFunction(i),this._shaderProcessor=new ac.C,this.onNewSceneAddedObservable.add((e=>{const t=e.render;e.render=(...i)=>{this._commandBufferEncoder.beginCommandScope(),t.apply(e,i),this._commandBufferEncoder.endCommandScope()}}))}dispose(){super.dispose(),this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._engine.dispose()}static _createNativeDataStream(){return new Ah}_queueNewFrame(e,t){return t.requestAnimationFrame&&t!==window?t.requestAnimationFrame(e):this._engine.requestAnimationFrame(e),0}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._currentFramebuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer),this._commandBufferEncoder.finishEncodingCommand()),e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()),this._currentFramebuffer=e)}getHostDocument(){return null}clear(e,t,i,n=!1){if(this.useReverseDepthBuffer)throw new Error("reverse depth buffer is not currently implemented");this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR),this._commandBufferEncoder.encodeCommandArgAsUInt32(t&&e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.r:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.g:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.b:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.a:1),this._commandBufferEncoder.encodeCommandArgAsUInt32(i?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(1),this._commandBufferEncoder.encodeCommandArgAsUInt32(n?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(0),this._commandBufferEncoder.finishEncodingCommand()}createIndexBuffer(e,t){const i=this._normalizeIndexData(e),n=new uc;return n.references=1,n.is32Bits=4===i.BYTES_PER_ELEMENT,i.byteLength&&(n.nativeIndexBuffer=this._engine.createIndexBuffer(i.buffer,i.byteOffset,i.byteLength,n.is32Bits,null!=t&&t)),n}createVertexBuffer(e,t){const i=ArrayBuffer.isView(e)?e:new Float32Array(e),n=new uc;return n.references=1,i.byteLength&&(n.nativeVertexBuffer=this._engine.createVertexBuffer(i.buffer,i.byteOffset,i.byteLength,null!=t&&t)),n}_recordVertexArrayObject(e,t,i,n,s){i&&this._engine.recordIndexBuffer(e,i.nativeIndexBuffer);const r=n.getAttributesNames();for(let o=0;o=0){const n=r[o];let a=null;if(s&&(a=s[n]),a||(a=t[n]),a){const t=a.getBuffer();t&&t.nativeVertexBuffer&&this._engine.recordVertexBuffer(e,t.nativeVertexBuffer,i,a.byteOffset,a.byteStride,a.getSize(),this._getNativeAttribType(a.type),a.normalized,a.getInstanceDivisor())}}}}bindBuffers(e,t,i){this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._boundBuffersVertexArray=this._engine.createVertexArray(),this._recordVertexArrayObject(this._boundBuffersVertexArray,e,t,i),this.bindVertexArrayObject(this._boundBuffersVertexArray)}recordVertexArrayObject(e,t,i,n){const s=this._engine.createVertexArray();return this._recordVertexArrayObject(s,e,t,i,n),s}_deleteVertexArray(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}bindVertexArrayObject(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}releaseVertexArrayObject(e){this._deleteVertexArray(e)}getAttributes(e,t){const i=e;return this._engine.getAttributes(i.nativeProgram,t)}drawElementsType(e,t,i,n){this._drawCalls.addCount(1,!1),this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand()}drawArraysType(e,t,i,n){this._drawCalls.addCount(1,!1),this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAW),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand()}createPipelineContext(){return new lc(this)}createMaterialContext(){}createDrawContext(){}_preparePipelineContext(e,t,i,n,s,r,o,a){const l=e;l.nativeProgram=n?this.createRawShaderProgram():this.createShaderProgram(e,t,i,a)}isAsync(e){return!(!e.isAsync||!this._engine.createProgramAsync)}_executeWhenRenderingStateIsCompiled(e,t){const i=e;if(!this.isAsync(e))return void t();const n=i.onCompiled;i.onCompiled=n?()=>{n(),t()}:t}createRawShaderProgram(){throw new Error("Not Supported")}createShaderProgram(e,t,i,n){const s=e;if(s.nativeProgram)throw new Error("Tried to create a second program in the same NativePipelineContext");this.onBeforeShaderCompilationObservable.notifyObservers(this);const r=new oc(t);r.processCode(),t=r.code;const o=new oc(i);o.processCode(),i=o.code,t=Ue.B._ConcatenateShader(t,n),i=Ue.B._ConcatenateShader(i,n);const a=()=>{var e;s.isCompiled=!0,null===(e=s.onCompiled)||void 0===e||e.call(s),this.onAfterShaderCompilationObservable.notifyObservers(this)};if(this.isAsync(e))return this._engine.createProgramAsync(t,i,a,(e=>{s.compilationError=e}));try{const e=s.nativeProgram=this._engine.createProgram(t,i);return a(),e}catch(l){const e=null==l?void 0:l.message;throw new Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}}inlineShaderCode(e){const t=new oc(e);return t.debug=!1,t.processCode(),t.code}_setProgram(e){this._currentProgram!==e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand(),this._currentProgram=e)}_deletePipelineContext(e){const t=e;t&&t.nativeProgram&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(t.nativeProgram),this._commandBufferEncoder.finishEncodingCommand())}getUniforms(e,t){const i=e;return this._engine.getUniforms(i.nativeProgram,t)}bindUniformBlock(e,t,i){throw new Error("Not Implemented")}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.nativeProgram);const i=e.getSamplers();for(let n=0;n{}}}setZOffset(e){e!==this._zOffset&&(this._zOffset=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSET),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffset(){return this._zOffset}setZOffsetUnits(e){e!==this._zOffsetUnits&&(this._zOffsetUnits=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSETUNITS),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffsetUnits(){return this._zOffsetUnits}setDepthBuffer(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(e?this._currentDepthTest:_native.Engine.DEPTH_TEST_ALWAYS),this._commandBufferEncoder.finishEncodingCommand()}getDepthWrite(){return this._depthWrite}getDepthFunction(){switch(this._currentDepthTest){case _native.Engine.DEPTH_TEST_NEVER:return 512;case _native.Engine.DEPTH_TEST_ALWAYS:return 519;case _native.Engine.DEPTH_TEST_GREATER:return 516;case _native.Engine.DEPTH_TEST_GEQUAL:return 518;case _native.Engine.DEPTH_TEST_NOTEQUAL:return 517;case _native.Engine.DEPTH_TEST_EQUAL:return 514;case _native.Engine.DEPTH_TEST_LESS:return 513;case _native.Engine.DEPTH_TEST_LEQUAL:return 515}return null}setDepthFunction(e){let t=0;switch(e){case 512:t=_native.Engine.DEPTH_TEST_NEVER;break;case 519:t=_native.Engine.DEPTH_TEST_ALWAYS;break;case 516:t=_native.Engine.DEPTH_TEST_GREATER;break;case 518:t=_native.Engine.DEPTH_TEST_GEQUAL;break;case 517:t=_native.Engine.DEPTH_TEST_NOTEQUAL;break;case 514:t=_native.Engine.DEPTH_TEST_EQUAL;break;case 513:t=_native.Engine.DEPTH_TEST_LESS;break;case 515:t=_native.Engine.DEPTH_TEST_LEQUAL}this._currentDepthTest=t,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(this._currentDepthTest),this._commandBufferEncoder.finishEncodingCommand()}setDepthWrite(e){this._depthWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}setColorWrite(e){this._colorWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETCOLORWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}getColorWrite(){return this._colorWrite}applyStencil(){this._setStencil(this._stencilMask,this._getStencilOpFail(this._stencilOpStencilFail),this._getStencilDepthFail(this._stencilOpDepthFail),this._getStencilDepthPass(this._stencilOpStencilDepthPass),this._getStencilFunc(this._stencilFunc),this._stencilFuncRef)}_setStencil(e,t,i,n,s,r){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(n),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.finishEncodingCommand()}setStencilBuffer(e){this._stencilTest=e,e?this.applyStencil():this._setStencil(255,_native.Engine.STENCIL_OP_FAIL_S_KEEP,_native.Engine.STENCIL_OP_FAIL_Z_KEEP,_native.Engine.STENCIL_OP_PASS_Z_KEEP,_native.Engine.STENCIL_TEST_ALWAYS,0)}getStencilBuffer(){return this._stencilTest}getStencilOperationPass(){return this._stencilOpStencilDepthPass}setStencilOperationPass(e){this._stencilOpStencilDepthPass=e,this.applyStencil()}setStencilMask(e){this._stencilMask=e,this.applyStencil()}setStencilFunction(e){this._stencilFunc=e,this.applyStencil()}setStencilFunctionReference(e){this._stencilFuncRef=e,this.applyStencil()}setStencilFunctionMask(e){this._stencilFuncMask=e}setStencilOperationFail(e){this._stencilOpStencilFail=e,this.applyStencil()}setStencilOperationDepthFail(e){this._stencilOpDepthFail=e,this.applyStencil()}getStencilMask(){return this._stencilMask}getStencilFunction(){return this._stencilFunc}getStencilFunctionReference(){return this._stencilFuncRef}getStencilFunctionMask(){return this._stencilFuncMask}getStencilOperationFail(){return this._stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilOpDepthFail}setAlphaConstants(e,t,i,n){throw new Error("Setting alpha blend constant color not yet implemented.")}setAlphaMode(e,t=!1){if(this._alphaMode===e)return;const i=this._getNativeAlphaMode(e);this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t||this.setDepthWrite(0===e),this._alphaMode=e}getAlphaMode(){return this._alphaMode}setInt(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setArray(e,t){return!!e&&this.setFloatArray(e,new Float32Array(t))}setArray2(e,t){return!!e&&this.setFloatArray2(e,new Float32Array(t))}setArray3(e,t){return!!e&&this.setFloatArray3(e,new Float32Array(t))}setArray4(e,t){return!!e&&this.setFloatArray4(e,new Float32Array(t))}setMatrices(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix3x3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix2x2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat2(e,t,i){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat3(e,t,i,n){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(n),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat4(e,t,i,n,s){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(n),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.finishEncodingCommand(),!0)}setColor3(e,t){return!!e&&(this.setFloat3(e,t.r,t.g,t.b),!0)}setColor4(e,t,i){return!!e&&(this.setFloat4(e,t.r,t.g,t.b,i),!0)}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}_createTexture(){return this._engine.createTexture()}_deleteTexture(e){e&&this._engine.deleteTexture(e)}updateDynamicTexture(e,t,i,n=!1,s){if(void 0===n&&(n=!1),e&&e._hardwareTexture){const i=t.getCanvasTexture(),n=e._hardwareTexture.underlyingResource;this._engine.copyTexture(n,i),e.isReady=!0}}createDynamicTexture(e,t,i,n){return e=Math.max(e,1),t=Math.max(t,1),this.createRawTexture(new Uint8Array(e*t*4),e,t,5,!1,!1,n)}createVideoElement(e){return this._camera?this._camera.createVideo(e):null}updateVideoTexture(e,t,i){if(e&&e._hardwareTexture&&this._camera){const n=e._hardwareTexture.underlyingResource;this._camera.updateVideoTexture(n,t,i)}}createRawTexture(e,t,i,n,s,r,o,a=null,l=0,h=0,c=!1){const d=new Be.l(this,Be.S.Raw);if(d.format=n,d.generateMipMaps=s,d.samplingMode=o,d.invertY=r,d.baseWidth=t,d.baseHeight=i,d.width=d.baseWidth,d.height=d.baseHeight,d._compression=a,d.type=l,d._useSRGBBuffer=this._getUseSRGBBuffer(c,!s),this.updateRawTexture(d,e,n,r,a,l,d._useSRGBBuffer),d._hardwareTexture){const e=d._hardwareTexture.underlyingResource,t=this._getNativeSamplingMode(o);this._setTextureSampling(e,t)}return this._internalTexturesCache.push(d),d}createRawTexture2DArray(e,t,i,n,s,r,o,a,l=null,h=0){const c=new Be.l(this,Be.S.Raw2DArray);if(c.baseWidth=t,c.baseHeight=i,c.baseDepth=n,c.width=t,c.height=i,c.depth=n,c.format=s,c.type=h,c.generateMipMaps=r,c.samplingMode=a,c.is2DArray=!0,c._hardwareTexture){const l=c._hardwareTexture.underlyingResource;this._engine.loadRawTexture2DArray(l,e,t,i,n,this._getNativeTextureFormat(s,h),r,o);const d=this._getNativeSamplingMode(a);this._setTextureSampling(l,d)}return c.isReady=!0,this._internalTexturesCache.push(c),c}updateRawTexture(e,t,i,n,s=null,r=0,o=!1){if(e){if(t&&e._hardwareTexture){const n=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(n,t,e.width,e.height,this._getNativeTextureFormat(i,r),e.generateMipMaps,e.invertY)}e.isReady=!0}}createTexture(e,t,i,n,s=3,r=null,o=null,a=null,l=null,h=null,c=null,d,u,f,_=!1){const g="data:"===(e=e||"").substr(0,5),v=g&&-1!==e.indexOf(";base64,"),T=l||new Be.l(this,Be.S.Url),S=e;!this._transformTextureUrl||v||l||a||(e=this._transformTextureUrl(e));const E=e.lastIndexOf("."),x=c||(E>-1?e.substring(E).toLowerCase():"");let b=null;for(const p of fe.D._TextureLoaders)if(p.canLoad(x)){b=p;break}n&&n.addPendingData(T),T.url=e,T.generateMipMaps=!t,T.samplingMode=s,T.invertY=i,T._useSRGBBuffer=this._getUseSRGBBuffer(_,t),this.doNotHandleContextLost||(T._buffer=a);let C=null;r&&!l&&(C=T.onLoadedObservable.add(r)),l||this._internalTexturesCache.push(T);const y=(i,l)=>{n&&n.removePendingData(T),e===S?(C&&T.onLoadedObservable.remove(C),m.l.UseFallbackTexture&&this.createTexture(m.l.FallbackTexture,t,T.invertY,n,s,null,o,a,T),o&&o((i||"Unknown error")+(m.l.UseFallbackTexture?" - Fallback texture was used":""),l)):(p.Y.Warn(`Failed to load ${e}, falling back to ${S}`),this.createTexture(S,t,T.invertY,n,s,r,o,a,T,h,c,d,u))};if(b)throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");{const r=e=>{if(!T._hardwareTexture)return void(n&&n.removePendingData(T));const r=T._hardwareTexture.underlyingResource;this._engine.loadTexture(r,e,!t,i,_,(()=>{T.baseWidth=this._engine.getTextureWidth(r),T.baseHeight=this._engine.getTextureHeight(r),T.width=T.baseWidth,T.height=T.baseHeight,T.isReady=!0;const e=this._getNativeSamplingMode(s);this._setTextureSampling(r,e),n&&n.removePendingData(T),T.onLoadedObservable.notifyObservers(T),T.onLoadedObservable.clear()}),(()=>{throw new Error("Could not load a native texture.")}))};if(g&&a)if(a instanceof ArrayBuffer)r(new Uint8Array(a));else if(ArrayBuffer.isView(a))r(a);else{if("string"!=typeof a)throw new Error("Unsupported buffer type");r(new Uint8Array(se.w1.DecodeBase64(a)))}else v?r(new Uint8Array(se.w1.DecodeBase64(e))):this._loadFile(e,(e=>r(new Uint8Array(e))),void 0,void 0,!0,((e,t)=>{y("Unable to load "+(e&&e.responseURL,t))}))}return T}wrapNativeTexture(e,t=!1,i=3){const n=new cc(e,this._engine),s=new Be.l(this,Be.S.Unknown,!0);return s._hardwareTexture=n,s.isReady=!0,s.useMipMaps=t,this.updateTextureSamplingMode(i,s),s}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.")}_createDepthStencilTexture(e,t,i){const n=i,s=new Be.l(this,Be.S.DepthStencil),r=e.width||e,o=e.height||e,a=this._engine.createFrameBuffer(s._hardwareTexture.underlyingResource,r,o,!0,!0);return n._framebufferDepthStencil=a,s}_releaseFramebufferObjects(e){e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_createImageBitmapFromSource(e,t){const i=new Promise(((t,i)=>{const n=this.createCanvasImage();n.onload=()=>{try{const e=this._engine.createImageBitmap(n);t(e)}catch(lt){i(`Error loading image ${n.src} with exception: ${lt}`)}},n.onerror=e=>{i(`Error loading image ${n.src} with exception: ${e}`)},n.src=e}));return i}createImageBitmap(e,t){return new Promise(((t,i)=>{if(Array.isArray(e)){const i=e;if(i.length){const e=this._engine.createImageBitmap(i[0]);if(e)return void t(e)}}i("Unsupported data for createImageBitmap.")}))}resizeImageBitmap(e,t,i){return this._engine.resizeImageBitmap(e,t,i)}createCubeTexture(e,t,i,n,s=null,r=null,o,a=null,l=!1,h=0,c=0,d=null,u,p=!1){const f=d||new Be.l(this,Be.S.Cube);f.isCube=!0,f.url=e,f.generateMipMaps=!n,f._lodGenerationScale=h,f._lodGenerationOffset=c,this._doNotHandleContextLost||(f._extension=a,f._files=i);const _=e.lastIndexOf(".");if(".env"===(a||(_>-1?e.substring(_).toLowerCase():""))){const t=e=>{const t=Kh(e);f.width=t.width,f.height=t.width,ec(f,t);const i=t.specular;if(!i)throw new Error("Nothing else parsed so far");f._lodGenerationScale=i.lodGenerationScale;const n=$h(e,t);f.format=5,f.type=0,f.generateMipMaps=!0,f.getEngine().updateTextureSamplingMode(Le.TRILINEAR_SAMPLINGMODE,f),f._isRGBD=!0,f.invertY=!0,this._engine.loadCubeTextureWithMips(f._hardwareTexture.underlyingResource,n,!1,p,(()=>{f.isReady=!0,s&&s()}),(()=>{throw new Error("Could not load a native cube texture.")}))};if(i&&6===i.length)throw new Error("Multi-file loading not allowed on env files.");{const i=(e,t)=>{r&&e&&r(e.status+" "+e.statusText,t)};this._loadFile(e,(e=>t(new Uint8Array(e))),void 0,void 0,!0,i)}}else{if(!i||6!==i.length)throw new Error("Cannot load cubemap because 6 files were not defined");const e=[i[0],i[3],i[1],i[4],i[2],i[5]];Promise.all(e.map((e=>se.w1.LoadFileAsync(e).then((e=>new Uint8Array(e)))))).then((e=>new Promise(((t,i)=>{this._engine.loadCubeTexture(f._hardwareTexture.underlyingResource,e,!n,!0,p,t,i)})))).then((()=>{f.isReady=!0,s&&s()}),(e=>{r&&r(`Failed to load cubemap: ${e.message}`,e)}))}return this._internalTexturesCache.push(f),f}_createHardwareTexture(){return new cc(this._createTexture(),this._engine)}_createHardwareRenderTargetWrapper(e,t,i){const n=new hc(e,t,i,this);return this._renderTargetWrapperCache.push(n),n}_createInternalTexture(e,t,i=!0,n=Be.S.Unknown){var s;let r,o=!1,a=0,l=3,h=5,c=!1,d=1;void 0!==t&&"object"==typeof t?(o=!!t.generateMipMaps,a=void 0===t.type?0:t.type,l=void 0===t.samplingMode?3:t.samplingMode,h=void 0===t.format?5:t.format,c=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,d=null!==(s=t.samples)&&void 0!==s?s:1,r=t.label):o=!!t,c&&(c=this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU)),(1!==a||this._caps.textureFloatLinearFiltering)&&(2!==a||this._caps.textureHalfFloatLinearFiltering)||(l=1),1!==a||this._caps.textureFloat||(a=0,p.Y.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const u=new Be.l(this,n),f=e.width||e,_=e.height||e,m=e.layers||0;if(0!==m)throw new Error("Texture layers are not supported in Babylon Native");const g=u._hardwareTexture.underlyingResource,v=this._getNativeTextureFormat(h,a);return this._engine.initializeTexture(g,f,_,o,v,!0,c),this._setTextureSampling(g,this._getNativeSamplingMode(l)),u._useSRGBBuffer=c,u.baseWidth=f,u.baseHeight=_,u.width=f,u.height=_,u.depth=m,u.isReady=!0,u.samples=d,u.generateMipMaps=o,u.samplingMode=l,u.type=a,u.format=h,u.label=r,this._internalTexturesCache.push(u),u}createRenderTargetTexture(e,t){var i,n;const s=this._createHardwareRenderTargetWrapper(!1,!1,e);let r,o=!0,a=!1,l=!1,h=1;void 0!==t&&"object"==typeof t&&(o=null===(i=t.generateDepthBuffer)||void 0===i||i,a=!!t.generateStencilBuffer,l=!!t.noColorAttachment,r=t.colorAttachment,h=null!==(n=t.samples)&&void 0!==n?n:1);const c=r||(l?null:this._createInternalTexture(e,t,!0,Be.S.RenderTarget)),d=e.width||e,u=e.height||e,p=this._engine.createFrameBuffer(c?c._hardwareTexture.underlyingResource:null,d,u,a,o);return s._framebuffer=p,s._generateDepthBuffer=o,s._generateStencilBuffer=a,s.setTextures(c),this.updateRenderTargetTextureSampleCount(s,h),s}updateRenderTargetTextureSampleCount(e,t){return 1}updateTextureSamplingMode(e,t){if(t._hardwareTexture){const i=this._getNativeSamplingMode(e);this._setTextureSampling(t._hardwareTexture.underlyingResource,i)}t.samplingMode=e}bindFramebuffer(e,t,i,n,s){const r=e;if(this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,t)throw new Error("Cuboid frame buffers are not yet supported in NativeEngine.");if(i||n)throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");r._framebufferDepthStencil?this._bindUnboundFramebuffer(r._framebufferDepthStencil):this._bindUnboundFramebuffer(r._framebuffer)}unBindFramebuffer(e,t=!1,i){this._currentRenderTarget=null,i&&i(),this._bindUnboundFramebuffer(null)}createDynamicVertexBuffer(e){return this.createVertexBuffer(e,!0)}updateDynamicIndexBuffer(e,t,i=0){const n=e,s=this._normalizeIndexData(t);n.is32Bits=4===s.BYTES_PER_ELEMENT,this._engine.updateDynamicIndexBuffer(n.nativeIndexBuffer,s.buffer,s.byteOffset,s.byteLength,i)}updateDynamicVertexBuffer(e,t,i,n){const s=e,r=ArrayBuffer.isView(t)?t:new Float32Array(t);this._engine.updateDynamicVertexBuffer(s.nativeVertexBuffer,r.buffer,r.byteOffset+(null!=i?i:0),null!=n?n:r.byteLength)}_setTexture(e,t,i=!1,n=!1){const s=this._boundUniforms[e];if(!s)return!1;if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._boundTexturesCache[e]=null),!1;if(t.video)this._activeChannel=e,t.update();else if(4===t.delayLoadState)return t.delayLoad(),!1;let r;return r=n?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,this._activeChannel=e,!(!r||!r._hardwareTexture)&&(this._setTextureWrapMode(r._hardwareTexture.underlyingResource,this._getAddressMode(t.wrapU),this._getAddressMode(t.wrapV),this._getAddressMode(t.wrapR)),this._updateAnisotropicLevel(t),this._setTextureCore(s,r._hardwareTexture.underlyingResource),!0)}_setTextureSampling(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.finishEncodingCommand()}_setTextureWrapMode(e,t,i,n){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(n),this._commandBufferEncoder.finishEncodingCommand()}_setTextureCore(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsNativeData(t),this._commandBufferEncoder.finishEncodingCommand()}_updateAnisotropicLevel(e){const t=e.getInternalTexture(),i=e.anisotropicFilteringLevel;t&&t._hardwareTexture&&t._cachedAnisotropicFilteringLevel!==i&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL),this._commandBufferEncoder.encodeCommandArgAsNativeData(t._hardwareTexture.underlyingResource),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t._cachedAnisotropicFilteringLevel=i)}_getAddressMode(e){switch(e){case 1:return _native.Engine.ADDRESS_MODE_WRAP;case 0:return _native.Engine.ADDRESS_MODE_CLAMP;case 2:return _native.Engine.ADDRESS_MODE_MIRROR;default:throw new Error("Unexpected wrap mode: "+e+".")}}_bindTexture(e,t){const i=this._boundUniforms[e];if(i&&t&&t._hardwareTexture){const e=t._hardwareTexture.underlyingResource;this._setTextureCore(i,e)}}_deleteBuffer(e){e.nativeIndexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeIndexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeIndexBuffer),e.nativeVertexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeVertexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeVertexBuffer)}createCanvas(e,t){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");const i=new _native.Canvas;return i.width=e,i.height=t,i}createCanvasImage(){if(!_native.Canvas)throw new Error("Native Canvas plugin not available.");return new _native.Image}updateTextureData(e,t,i,n,s,r,o=0,a=0,l=!1){throw new Error("updateTextureData not implemented.")}_uploadCompressedDataToTextureDirectly(e,t,i,n,s,r=0,o=0){throw new Error("_uploadCompressedDataToTextureDirectly not implemented.")}_uploadDataToTextureDirectly(e,t,i=0,n=0){throw new Error("_uploadDataToTextureDirectly not implemented.")}_uploadArrayBufferViewToTexture(e,t,i=0,n=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}_uploadImageToTexture(e,t,i=0,n=0){throw new Error("_uploadArrayBufferViewToTexture not implemented.")}_getNativeSamplingMode(e){switch(e){case 1:return _native.Engine.TEXTURE_NEAREST_NEAREST;case 2:return _native.Engine.TEXTURE_LINEAR_LINEAR;case 3:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR;case 4:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;case 5:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;case 6:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;case 7:return _native.Engine.TEXTURE_NEAREST_LINEAR;case 8:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR;case 9:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;case 10:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;case 11:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST;case 12:return _native.Engine.TEXTURE_LINEAR_NEAREST;default:throw new Error(`Unsupported sampling mode: ${e}.`)}}_getStencilFunc(e){switch(e){case 513:return _native.Engine.STENCIL_TEST_LESS;case 515:return _native.Engine.STENCIL_TEST_LEQUAL;case 514:return _native.Engine.STENCIL_TEST_EQUAL;case 518:return _native.Engine.STENCIL_TEST_GEQUAL;case 516:return _native.Engine.STENCIL_TEST_GREATER;case 517:return _native.Engine.STENCIL_TEST_NOTEQUAL;case 512:return _native.Engine.STENCIL_TEST_NEVER;case 519:return _native.Engine.STENCIL_TEST_ALWAYS;default:throw new Error(`Unsupported stencil func mode: ${e}.`)}}_getStencilOpFail(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_FAIL_S_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_S_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_S_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_S_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_S_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_S_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_S_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_S_DECRSAT;default:throw new Error(`Unsupported stencil OpFail mode: ${e}.`)}}_getStencilDepthFail(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_FAIL_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_Z_DECRSAT;default:throw new Error(`Unsupported stencil depthFail mode: ${e}.`)}}_getStencilDepthPass(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_PASS_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_PASS_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_PASS_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_PASS_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_PASS_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_PASS_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_PASS_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_PASS_Z_DECRSAT;default:throw new Error(`Unsupported stencil opPass mode: ${e}.`)}}_getNativeTextureFormat(e,t){if(4==e&&0==t)return _native.Engine.TEXTURE_FORMAT_RGB8;if(5==e&&0==t)return _native.Engine.TEXTURE_FORMAT_RGBA8;if(5==e&&2==t)return _native.Engine.TEXTURE_FORMAT_RGBA16F;if(5==e&&1==t)return _native.Engine.TEXTURE_FORMAT_RGBA32F;throw new lt.LH(`Unsupported texture format or type: format ${e}, type ${t}.`,lt.SM.UnsupportedTextureError)}_getNativeAlphaMode(e){switch(e){case 0:return _native.Engine.ALPHA_DISABLE;case 1:return _native.Engine.ALPHA_ADD;case 2:return _native.Engine.ALPHA_COMBINE;case 3:return _native.Engine.ALPHA_SUBTRACT;case 4:return _native.Engine.ALPHA_MULTIPLY;case 5:return _native.Engine.ALPHA_MAXIMIZED;case 6:return _native.Engine.ALPHA_ONEONE;case 7:return _native.Engine.ALPHA_PREMULTIPLIED;case 8:return _native.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;case 9:return _native.Engine.ALPHA_INTERPOLATE;case 10:return _native.Engine.ALPHA_SCREENMODE;default:throw new Error(`Unsupported alpha mode: ${e}.`)}}_getNativeAttribType(e){switch(e){case ne.o.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case ne.o.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case ne.o.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case ne.o.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case ne.o.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw new Error(`Unsupported attribute type: ${e}.`)}}getFontOffset(e){return{ascent:0,height:0,descent:0}}_readTexturePixels(e,t,i,n,s,r,o,a,l,h){var c,d,u,p;if(void 0!==n&&-1!==n)throw new Error(`Reading cubemap faces is not supported, but faceIndex is ${n}.`);return this._engine.readTexture(null===(c=e._hardwareTexture)||void 0===c?void 0:c.underlyingResource,null!=s?s:0,null!=l?l:0,null!=h?h:0,t,i,null!==(d=null==r?void 0:r.buffer)&&void 0!==d?d:null,null!==(u=null==r?void 0:r.byteOffset)&&void 0!==u?u:0,null!==(p=null==r?void 0:r.byteLength)&&void 0!==p?p:0).then((e=>(r||(r=new Uint8Array(e)),r)))}}fc.PROTOCOL_VERSION=8,fc._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new _c:new Ah};class _c extends Ah{constructor(){super()}writeUint32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32),super.writeUint32(e)}writeInt32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32),super.writeInt32(e)}writeFloat32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32),super.writeFloat32(e)}writeUint32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32_ARRAY),super.writeUint32Array(e)}writeInt32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32_ARRAY),super.writeInt32Array(e)}writeFloat32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32_ARRAY),super.writeFloat32Array(e)}writeNativeData(e){super.writeUint32(_native.NativeDataStream.VALIDATION_NATIVE_DATA),super.writeNativeData(e)}writeBoolean(e){super.writeUint32(_native.NativeDataStream.VALIDATION_BOOLEAN),super.writeBoolean(e)}}var mc,gc,vc,Tc,Sc,Ec,xc,bc,Cc,yc,Ac,Rc,Pc,Ic,Mc,Oc,Dc,Nc,Fc,wc,Lc,Bc,Uc,Vc,kc,Gc,zc,Wc,Hc,Xc,Yc,jc,Kc,qc,$c,Qc,Zc,Jc,ed,td;!function(e){e.LowPower="low-power",e.HighPerformance="high-performance"}(mc||(mc={})),function(e){e.DepthClipControl="depth-clip-control",e.Depth32FloatStencil8="depth32float-stencil8",e.TextureCompressionBC="texture-compression-bc",e.TextureCompressionETC2="texture-compression-etc2",e.TextureCompressionASTC="texture-compression-astc",e.TimestampQuery="timestamp-query",e.IndirectFirstInstance="indirect-first-instance",e.ShaderF16="shader-f16",e.RG11B10UFloatRenderable="rg11b10ufloat-renderable",e.BGRA8UnormStorage="bgra8unorm-storage",e.Float32Filterable="float32-filterable"}(gc||(gc={})),function(e){e.Unmapped="unmapped",e.Pending="pending",e.Mapped="mapped"}(vc||(vc={})),function(e){e[e.MapRead=1]="MapRead",e[e.MapWrite=2]="MapWrite",e[e.CopySrc=4]="CopySrc",e[e.CopyDst=8]="CopyDst",e[e.Index=16]="Index",e[e.Vertex=32]="Vertex",e[e.Uniform=64]="Uniform",e[e.Storage=128]="Storage",e[e.Indirect=256]="Indirect",e[e.QueryResolve=512]="QueryResolve"}(Tc||(Tc={})),function(e){e[e.Read=1]="Read",e[e.Write=2]="Write"}(Sc||(Sc={})),function(e){e.E1d="1d",e.E2d="2d",e.E3d="3d"}(Ec||(Ec={})),function(e){e[e.CopySrc=1]="CopySrc",e[e.CopyDst=2]="CopyDst",e[e.TextureBinding=4]="TextureBinding",e[e.StorageBinding=8]="StorageBinding",e[e.RenderAttachment=16]="RenderAttachment"}(xc||(xc={})),function(e){e.E1d="1d",e.E2d="2d",e.E2dArray="2d-array",e.Cube="cube",e.CubeArray="cube-array",e.E3d="3d"}(bc||(bc={})),function(e){e.All="all",e.StencilOnly="stencil-only",e.DepthOnly="depth-only"}(Cc||(Cc={})),function(e){e.R8Unorm="r8unorm",e.R8Snorm="r8snorm",e.R8Uint="r8uint",e.R8Sint="r8sint",e.R16Uint="r16uint",e.R16Sint="r16sint",e.R16Float="r16float",e.RG8Unorm="rg8unorm",e.RG8Snorm="rg8snorm",e.RG8Uint="rg8uint",e.RG8Sint="rg8sint",e.R32Uint="r32uint",e.R32Sint="r32sint",e.R32Float="r32float",e.RG16Uint="rg16uint",e.RG16Sint="rg16sint",e.RG16Float="rg16float",e.RGBA8Unorm="rgba8unorm",e.RGBA8UnormSRGB="rgba8unorm-srgb",e.RGBA8Snorm="rgba8snorm",e.RGBA8Uint="rgba8uint",e.RGBA8Sint="rgba8sint",e.BGRA8Unorm="bgra8unorm",e.BGRA8UnormSRGB="bgra8unorm-srgb",e.RGB9E5UFloat="rgb9e5ufloat",e.RGB10A2Unorm="rgb10a2unorm",e.RG11B10UFloat="rg11b10ufloat",e.RG32Uint="rg32uint",e.RG32Sint="rg32sint",e.RG32Float="rg32float",e.RGBA16Uint="rgba16uint",e.RGBA16Sint="rgba16sint",e.RGBA16Float="rgba16float",e.RGBA32Uint="rgba32uint",e.RGBA32Sint="rgba32sint",e.RGBA32Float="rgba32float",e.Stencil8="stencil8",e.Depth16Unorm="depth16unorm",e.Depth24Plus="depth24plus",e.Depth24PlusStencil8="depth24plus-stencil8",e.Depth32Float="depth32float",e.BC1RGBAUnorm="bc1-rgba-unorm",e.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",e.BC2RGBAUnorm="bc2-rgba-unorm",e.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",e.BC3RGBAUnorm="bc3-rgba-unorm",e.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",e.BC4RUnorm="bc4-r-unorm",e.BC4RSnorm="bc4-r-snorm",e.BC5RGUnorm="bc5-rg-unorm",e.BC5RGSnorm="bc5-rg-snorm",e.BC6HRGBUFloat="bc6h-rgb-ufloat",e.BC6HRGBFloat="bc6h-rgb-float",e.BC7RGBAUnorm="bc7-rgba-unorm",e.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",e.ETC2RGB8Unorm="etc2-rgb8unorm",e.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",e.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",e.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",e.ETC2RGBA8Unorm="etc2-rgba8unorm",e.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",e.EACR11Unorm="eac-r11unorm",e.EACR11Snorm="eac-r11snorm",e.EACRG11Unorm="eac-rg11unorm",e.EACRG11Snorm="eac-rg11snorm",e.ASTC4x4Unorm="astc-4x4-unorm",e.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",e.ASTC5x4Unorm="astc-5x4-unorm",e.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",e.ASTC5x5Unorm="astc-5x5-unorm",e.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",e.ASTC6x5Unorm="astc-6x5-unorm",e.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",e.ASTC6x6Unorm="astc-6x6-unorm",e.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",e.ASTC8x5Unorm="astc-8x5-unorm",e.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",e.ASTC8x6Unorm="astc-8x6-unorm",e.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",e.ASTC8x8Unorm="astc-8x8-unorm",e.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",e.ASTC10x5Unorm="astc-10x5-unorm",e.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",e.ASTC10x6Unorm="astc-10x6-unorm",e.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",e.ASTC10x8Unorm="astc-10x8-unorm",e.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",e.ASTC10x10Unorm="astc-10x10-unorm",e.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",e.ASTC12x10Unorm="astc-12x10-unorm",e.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",e.ASTC12x12Unorm="astc-12x12-unorm",e.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",e.Depth24UnormStencil8="depth24unorm-stencil8",e.Depth32FloatStencil8="depth32float-stencil8"}(yc||(yc={})),function(e){e.ClampToEdge="clamp-to-edge",e.Repeat="repeat",e.MirrorRepeat="mirror-repeat"}(Ac||(Ac={})),function(e){e.Nearest="nearest",e.Linear="linear"}(Rc||(Rc={})),function(e){e.Nearest="nearest",e.Linear="linear"}(Pc||(Pc={})),function(e){e.Never="never",e.Less="less",e.Equal="equal",e.LessEqual="less-equal",e.Greater="greater",e.NotEqual="not-equal",e.GreaterEqual="greater-equal",e.Always="always"}(Ic||(Ic={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Compute=4]="Compute"}(Mc||(Mc={})),function(e){e.Uniform="uniform",e.Storage="storage",e.ReadOnlyStorage="read-only-storage"}(Oc||(Oc={})),function(e){e.Filtering="filtering",e.NonFiltering="non-filtering",e.Comparison="comparison"}(Dc||(Dc={})),function(e){e.Float="float",e.UnfilterableFloat="unfilterable-float",e.Depth="depth",e.Sint="sint",e.Uint="uint"}(Nc||(Nc={})),function(e){e.WriteOnly="write-only"}(Fc||(Fc={})),function(e){e.Error="error",e.Warning="warning",e.Info="info"}(wc||(wc={})),function(e){e.Validation="validation",e.Internal="internal"}(Lc||(Lc={})),function(e){e.Auto="auto"}(Bc||(Bc={})),function(e){e.PointList="point-list",e.LineList="line-list",e.LineStrip="line-strip",e.TriangleList="triangle-list",e.TriangleStrip="triangle-strip"}(Uc||(Uc={})),function(e){e.CCW="ccw",e.CW="cw"}(Vc||(Vc={})),function(e){e.None="none",e.Front="front",e.Back="back"}(kc||(kc={})),function(e){e[e.Red=1]="Red",e[e.Green=2]="Green",e[e.Blue=4]="Blue",e[e.Alpha=8]="Alpha",e[e.All=15]="All"}(Gc||(Gc={})),function(e){e.Zero="zero",e.One="one",e.Src="src",e.OneMinusSrc="one-minus-src",e.SrcAlpha="src-alpha",e.OneMinusSrcAlpha="one-minus-src-alpha",e.Dst="dst",e.OneMinusDst="one-minus-dst",e.DstAlpha="dst-alpha",e.OneMinusDstAlpha="one-minus-dst-alpha",e.SrcAlphaSaturated="src-alpha-saturated",e.Constant="constant",e.OneMinusConstant="one-minus-constant"}(zc||(zc={})),function(e){e.Add="add",e.Subtract="subtract",e.ReverseSubtract="reverse-subtract",e.Min="min",e.Max="max"}(Wc||(Wc={})),function(e){e.Keep="keep",e.Zero="zero",e.Replace="replace",e.Invert="invert",e.IncrementClamp="increment-clamp",e.DecrementClamp="decrement-clamp",e.IncrementWrap="increment-wrap",e.DecrementWrap="decrement-wrap"}(Hc||(Hc={})),function(e){e.Uint16="uint16",e.Uint32="uint32"}(Xc||(Xc={})),function(e){e.Uint8x2="uint8x2",e.Uint8x4="uint8x4",e.Sint8x2="sint8x2",e.Sint8x4="sint8x4",e.Unorm8x2="unorm8x2",e.Unorm8x4="unorm8x4",e.Snorm8x2="snorm8x2",e.Snorm8x4="snorm8x4",e.Uint16x2="uint16x2",e.Uint16x4="uint16x4",e.Sint16x2="sint16x2",e.Sint16x4="sint16x4",e.Unorm16x2="unorm16x2",e.Unorm16x4="unorm16x4",e.Snorm16x2="snorm16x2",e.Snorm16x4="snorm16x4",e.Float16x2="float16x2",e.Float16x4="float16x4",e.Float32="float32",e.Float32x2="float32x2",e.Float32x3="float32x3",e.Float32x4="float32x4",e.Uint32="uint32",e.Uint32x2="uint32x2",e.Uint32x3="uint32x3",e.Uint32x4="uint32x4",e.Sint32="sint32",e.Sint32x2="sint32x2",e.Sint32x3="sint32x3",e.Sint32x4="sint32x4"}(Yc||(Yc={})),function(e){e.Vertex="vertex",e.Instance="instance"}(jc||(jc={})),function(e){e.Beginning="beginning",e.End="end"}(Kc||(Kc={})),function(e){e.Beginning="beginning",e.End="end"}(qc||(qc={})),function(e){e.Load="load",e.Clear="clear"}($c||($c={})),function(e){e.Store="store",e.Discard="discard"}(Qc||(Qc={})),function(e){e.Occlusion="occlusion",e.Timestamp="timestamp"}(Zc||(Zc={})),function(e){e.Opaque="opaque",e.Premultiplied="premultiplied"}(Jc||(Jc={})),function(e){e.Unknown="unknown",e.Destroyed="destroyed"}(ed||(ed={})),function(e){e.Validation="validation",e.OutOfMemory="out-of-memory",e.Internal="internal"}(td||(td={}));class id{constructor(){this.shaderLanguage=Qt.x.GLSL}_addUniformToLeftOverUBO(e,t,i){let n=0;[e,t,n]=this._getArraySize(e,t,i);for(let s=0;s=0&&(d.push(o[c]),u.push(e))}this.shaderProcessingContext.attributeNamesFromEffect=d,this.shaderProcessingContext.attributeLocationsFromEffect=u}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){this.uniformBuffer=new ae.M(this.engine,void 0,void 0,"leftOver-"+this._name);for(const e of this.shaderProcessingContext.leftOverUniforms){const t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=id.UniformSizes[t];this.uniformBuffer.addUniform(e.name,i,e.length),this._leftOverUniformsByName[e.name]=e.type}this.uniformBuffer.create()}}dispose(){this.uniformBuffer&&this.uniformBuffer.dispose()}setInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt(e,t)}setInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt2(e,t,i)}setInt3(e,t,i,n){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt3(e,t,i,n)}setInt4(e,t,i,n,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt4(e,t,i,n,s)}setIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateIntArray(e,t)}setIntArray2(e,t){this.setIntArray(e,t)}setIntArray3(e,t){this.setIntArray(e,t)}setIntArray4(e,t){this.setIntArray(e,t)}setUInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt(e,t)}setUInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt2(e,t,i)}setUInt3(e,t,i,n){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt3(e,t,i,n)}setUInt4(e,t,i,n,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt4(e,t,i,n,s)}setUIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUIntArray(e,t)}setUIntArray2(e,t){this.setUIntArray(e,t)}setUIntArray3(e,t){this.setUIntArray(e,t)}setUIntArray4(e,t){this.setUIntArray(e,t)}setArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateArray(e,t)}setArray2(e,t){this.setArray(e,t)}setArray3(e,t){this.setArray(e,t)}setArray4(e,t){this.setArray(e,t)}setMatrices(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrices(e,t)}setMatrix(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix(e,t)}setMatrix3x3(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix3x3(e,t)}setMatrix2x2(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix2x2(e,t)}setFloat(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat(e,t)}setVector2(e,t){this.setFloat2(e,t.x,t.y)}setFloat2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat2(e,t,i)}setVector3(e,t){this.setFloat3(e,t.x,t.y,t.z)}setFloat3(e,t,i,n){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat3(e,t,i,n)}setVector4(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setQuaternion(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setFloat4(e,t,i,n,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat4(e,t,i,n,s)}setColor3(e,t){this.setFloat3(e,t.r,t.g,t.b)}setColor4(e,t,i){this.setFloat4(e,t.r,t.g,t.b,i)}setDirectColor4(e,t){this.setFloat4(e,t.r,t.g,t.b,t.a)}_getVertexShaderCode(){var e;return null===(e=this.sources)||void 0===e?void 0:e.vertex}_getFragmentShaderCode(){var e;return null===(e=this.sources)||void 0===e?void 0:e.fragment}}const sd={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};class rd{static get KnownUBOs(){return rd._SimplifiedKnownBindings?rd._SimplifiedKnownUBOs:rd._KnownUBOs}constructor(e){this.shaderLanguage=e,this._attributeNextLocation=0,this._varyingNextLocation=0,this.freeGroupIndex=0,this.freeBindingIndex=0,this.availableVaryings={},this.availableAttributes={},this.availableBuffers={},this.availableTextures={},this.availableSamplers={},this.orderedAttributes=[],this.bindGroupLayoutEntries=[],this.bindGroupLayoutEntryInfo=[],this.bindGroupEntries=[],this.bufferNames=[],this.textureNames=[],this.samplerNames=[],this.leftOverUniforms=[],this._findStartingGroupBinding()}_findStartingGroupBinding(){const e=rd.KnownUBOs,t=[];for(const i in e){const n=e[i].binding;-1!==n.groupIndex&&(void 0===t[n.groupIndex]?t[n.groupIndex]=n.bindingIndex:t[n.groupIndex]=Math.max(t[n.groupIndex],n.bindingIndex))}this.freeGroupIndex=t.length-1,0===this.freeGroupIndex?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=t[t.length-1]+1}getAttributeNextLocation(e,t=0){var i;const n=this._attributeNextLocation;return this._attributeNextLocation+=(null!==(i=sd[e])&&void 0!==i?i:1)*(t||1),n}getVaryingNextLocation(e,t=0){var i;const n=this._varyingNextLocation;return this._varyingNextLocation+=(null!==(i=sd[e])&&void 0!==i?i:1)*(t||1),n}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>65536-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),4===this.freeGroupIndex)throw"Too many textures or UBOs have been declared and it is not supported in WebGPU.";const t={groupIndex:this.freeGroupIndex,bindingIndex:this.freeBindingIndex};return this.freeBindingIndex+=e,t}}rd._SimplifiedKnownBindings=!0,rd._SimplifiedKnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:-1,bindingIndex:-1}},Light1:{binding:{groupIndex:-1,bindingIndex:-1}},Light2:{binding:{groupIndex:-1,bindingIndex:-1}},Light3:{binding:{groupIndex:-1,bindingIndex:-1}},Light4:{binding:{groupIndex:-1,bindingIndex:-1}},Light5:{binding:{groupIndex:-1,bindingIndex:-1}},Light6:{binding:{groupIndex:-1,bindingIndex:-1}},Light7:{binding:{groupIndex:-1,bindingIndex:-1}},Light8:{binding:{groupIndex:-1,bindingIndex:-1}},Light9:{binding:{groupIndex:-1,bindingIndex:-1}},Light10:{binding:{groupIndex:-1,bindingIndex:-1}},Light11:{binding:{groupIndex:-1,bindingIndex:-1}},Light12:{binding:{groupIndex:-1,bindingIndex:-1}},Light13:{binding:{groupIndex:-1,bindingIndex:-1}},Light14:{binding:{groupIndex:-1,bindingIndex:-1}},Light15:{binding:{groupIndex:-1,bindingIndex:-1}},Light16:{binding:{groupIndex:-1,bindingIndex:-1}},Light17:{binding:{groupIndex:-1,bindingIndex:-1}},Light18:{binding:{groupIndex:-1,bindingIndex:-1}},Light19:{binding:{groupIndex:-1,bindingIndex:-1}},Light20:{binding:{groupIndex:-1,bindingIndex:-1}},Light21:{binding:{groupIndex:-1,bindingIndex:-1}},Light22:{binding:{groupIndex:-1,bindingIndex:-1}},Light23:{binding:{groupIndex:-1,bindingIndex:-1}},Light24:{binding:{groupIndex:-1,bindingIndex:-1}},Light25:{binding:{groupIndex:-1,bindingIndex:-1}},Light26:{binding:{groupIndex:-1,bindingIndex:-1}},Light27:{binding:{groupIndex:-1,bindingIndex:-1}},Light28:{binding:{groupIndex:-1,bindingIndex:-1}},Light29:{binding:{groupIndex:-1,bindingIndex:-1}},Light30:{binding:{groupIndex:-1,bindingIndex:-1}},Light31:{binding:{groupIndex:-1,bindingIndex:-1}},Material:{binding:{groupIndex:-1,bindingIndex:-1}},Mesh:{binding:{groupIndex:-1,bindingIndex:-1}},Internals:{binding:{groupIndex:-1,bindingIndex:-1}}},rd._KnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:1,bindingIndex:0}},Light1:{binding:{groupIndex:1,bindingIndex:1}},Light2:{binding:{groupIndex:1,bindingIndex:2}},Light3:{binding:{groupIndex:1,bindingIndex:3}},Light4:{binding:{groupIndex:1,bindingIndex:4}},Light5:{binding:{groupIndex:1,bindingIndex:5}},Light6:{binding:{groupIndex:1,bindingIndex:6}},Light7:{binding:{groupIndex:1,bindingIndex:7}},Light8:{binding:{groupIndex:1,bindingIndex:8}},Light9:{binding:{groupIndex:1,bindingIndex:9}},Light10:{binding:{groupIndex:1,bindingIndex:10}},Light11:{binding:{groupIndex:1,bindingIndex:11}},Light12:{binding:{groupIndex:1,bindingIndex:12}},Light13:{binding:{groupIndex:1,bindingIndex:13}},Light14:{binding:{groupIndex:1,bindingIndex:14}},Light15:{binding:{groupIndex:1,bindingIndex:15}},Light16:{binding:{groupIndex:1,bindingIndex:16}},Light17:{binding:{groupIndex:1,bindingIndex:17}},Light18:{binding:{groupIndex:1,bindingIndex:18}},Light19:{binding:{groupIndex:1,bindingIndex:19}},Light20:{binding:{groupIndex:1,bindingIndex:20}},Light21:{binding:{groupIndex:1,bindingIndex:21}},Light22:{binding:{groupIndex:1,bindingIndex:22}},Light23:{binding:{groupIndex:1,bindingIndex:23}},Light24:{binding:{groupIndex:1,bindingIndex:24}},Light25:{binding:{groupIndex:1,bindingIndex:25}},Light26:{binding:{groupIndex:1,bindingIndex:26}},Light27:{binding:{groupIndex:1,bindingIndex:27}},Light28:{binding:{groupIndex:1,bindingIndex:28}},Light29:{binding:{groupIndex:1,bindingIndex:29}},Light30:{binding:{groupIndex:1,bindingIndex:30}},Light31:{binding:{groupIndex:1,bindingIndex:31}},Material:{binding:{groupIndex:2,bindingIndex:0}},Mesh:{binding:{groupIndex:2,bindingIndex:1}},Internals:{binding:{groupIndex:2,bindingIndex:2}}};class od extends id{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=Qt.x.GLSL,this.parseGLES3=!0}_getArraySize(e,t,i){let n=0;const s=e.indexOf("["),r=e.indexOf("]");if(s>0&&r>0){const t=e.substring(s+1,r);n=+t,isNaN(n)&&(n=+i[t.trim()]),e=e.substr(0,s)}return[e,t,n]}initializeShaders(e){this._webgpuProcessingContext=e,this._missingVaryings.length=0,this._textureArrayProcessing.length=0,this.attributeKeywordName=void 0,this.varyingVertexKeywordName=void 0,this.varyingFragmentKeywordName=void 0}preProcessShaderCode(e,t){const i=`// Internals UBO\r\nuniform ${id.InternalsUBOName} {\nfloat yFactor_;\nfloat textureOutputHeight_;\n};\n`,n=-1!==e.indexOf("// Internals UBO");return t?(this._fragmentIsGLES3=-1!==e.indexOf("#version 3"),this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),n?e:i+"##INJECTCODE##\n"+e):(this._vertexIsGLES3=-1!==e.indexOf("#version 3"),this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),n?e:i+e)}varyingCheck(e,t){return(t&&this._fragmentIsGLES3?/(flat\s)?\s*in/:!t&&this._vertexIsGLES3?/(flat\s)?\s*out/:/(flat\s)?\s*varying/).test(e)}varyingProcessor(e,t,i){var n;this._preProcessors=i;const s=(t&&this._fragmentIsGLES3?/\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:!t&&this._vertexIsGLES3?/\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:/\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==s){const r=null!==(n=s[1])&&void 0!==n?n:"",o=s[2],a=s[3];let l;t?(l=this._webgpuProcessingContext.availableVaryings[a],this._missingVaryings[l]="",void 0===l&&p.Y.Warn(`Invalid fragment shader: The varying named "${a}" is not declared in the vertex shader! This declaration will be ignored.`)):(l=this._webgpuProcessingContext.getVaryingNextLocation(o,this._getArraySize(a,o,i)[2]),this._webgpuProcessingContext.availableVaryings[a]=l,this._missingVaryings[l]=`layout(location = ${l}) ${r} in ${o} ${a};`),e=e.replace(s[0],void 0===l?"":`layout(location = ${l}) ${r} ${t?"in":"out"} ${o} ${a};`)}return e}attributeProcessor(e,t){this._preProcessors=t;const i=(this._vertexIsGLES3?/\s*in\s+(\S+)\s+(\S+)\s*;/gm:/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==i){const n=i[1],s=i[2],r=this._webgpuProcessingContext.getAttributeNextLocation(n,this._getArraySize(s,n,t)[2]);this._webgpuProcessingContext.availableAttributes[s]=r,this._webgpuProcessingContext.orderedAttributes[r]=s,e=e.replace(i[0],`layout(location = ${r}) in ${n} ${s};`)}return e}uniformProcessor(e,t,i){var n;this._preProcessors=i;const s=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(null!==s){let r=s[1],o=s[2];if(0===r.indexOf("sampler")||1===r.indexOf("sampler")){let s=0;[o,r,s]=this._getArraySize(o,r,i);let a=this._webgpuProcessingContext.availableTextures[o];if(!a){a={autoBindSampler:!0,isTextureArray:s>0,isStorageTexture:!1,textures:[],sampleType:Nc.Float};for(let e=0;e<(s||1);++e)a.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}const l=null!==(n=id._SamplerTypeByWebGLSamplerType[r])&&void 0!==n?n:"sampler",h=!!id._IsComparisonSamplerByWebGPUSamplerType[l],c=h?Dc.Comparison:Dc.Filtering,d=o+id.AutoSamplerSuffix;let u=this._webgpuProcessingContext.availableSamplers[d];u||(u={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:c});const p="u"===r.charAt(0)?"u":"i"===r.charAt(0)?"i":"";p&&(r=r.substr(1));const f=h?Nc.Depth:"u"===p?Nc.Uint:"i"===p?Nc.Sint:Nc.Float;a.sampleType=f;const _=s>0,m=u.binding.groupIndex,g=u.binding.bindingIndex,v=id._SamplerFunctionByWebGLSamplerType[r],T=id._TextureTypeByWebGLSamplerType[r],S=id._GpuTextureViewDimensionByWebGPUTextureType[T];if(_){const t=[];t.push(`layout(set = ${m}, binding = ${g}) uniform ${p}${l} ${d};`),e="\r\n";for(let i=0;i0?"\r\n":""}#define ${o}${i} ${p}${v}(${o}Texture${i}, ${d})`}e=t.join("\r\n")+e,this._textureArrayProcessing.push(o)}else s=1,e=`layout(set = ${m}, binding = ${g}) uniform ${p}${l} ${d};\n layout(set = ${a.textures[0].groupIndex}, binding = ${a.textures[0].bindingIndex}) uniform ${T} ${o}Texture;\n #define ${o} ${p}${v}(${o}Texture, ${d})`;this._webgpuProcessingContext.availableTextures[o]=a,this._webgpuProcessingContext.availableSamplers[d]=u,this._addSamplerBindingDescription(d,u,!t);for(let e=0;e=0,i="\n glFragCoord_ = gl_FragCoord;\n if (yFactor_ == 1.) {\n glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y;\n }\n ",n=t?"vec4 glFragCoord_;\n":"";if(e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/gl_FragCoord/g,"glFragCoord_"),this._fragmentIsGLES3){const t=/^\s*out\s+\S+\s+\S+\s*;/gm.exec(e);null!==t&&(e=e.substring(0,t.index)+"layout(location = 0) "+e.substring(t.index))}else e=e.replace(/void\s+?main\s*\(/g,(r?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(");e=(e=e.replace(/dFdy/g,"(-yFactor_)*dFdy")).replace("##INJECTCODE##",n),t&&(e=this._injectStartingAndEndingCode(e,"void main",i))}else{e=(e=e.replace(/gl_InstanceID/g,"gl_InstanceIndex")).replace(/gl_VertexID/g,"gl_VertexIndex");if(-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e}if(!i){const t=e.lastIndexOf("}");e=e.substring(0,t),e+="gl_Position.y *= yFactor_;\n",s.isNDCHalfZRange||(e+="gl_Position.z = (gl_Position.z + gl_Position.w) / 2.0;\n"),e+="}"}return e}_applyTextureArrayProcessing(e,t){const i=new RegExp(t+"\\s*\\[(.+)?\\]","gm");let n=i.exec(e);for(;null!==n;){const s=n[1];let r=+s;this._preProcessors&&isNaN(r)&&(r=+this._preProcessors[s.trim()]),e=e.replace(n[0],t+r),n=i.exec(e)}return e}_generateLeftOverUBOCode(e,t){let i=`layout(set = ${t.binding.groupIndex}, binding = ${t.binding.bindingIndex}) uniform ${e} {\n `;for(const n of this._webgpuProcessingContext.leftOverUniforms)n.length>0?i+=` ${n.type} ${n.name}[${n.length}];\n`:i+=` ${n.type} ${n.name};\n`;return i+="};\n\n",i}finalizeShaders(e,t){for(let n=0;n0&&(t=e+"\n"+t)}const i=this._buildLeftOverUBO();return e=i+e,t=i+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,{vertexCode:e,fragmentCode:t}}}const ad="bonesDeclaration",ld="#if NUM_BONE_INFLUENCERS>0\nattribute matricesIndices : vec4;\nattribute matricesWeights : vec4;\n#if NUM_BONE_INFLUENCERS>4\nattribute matricesIndicesExtra : vec4;\nattribute matricesWeightsExtra : vec4;\n#endif\n#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#ifdef BONETEXTURE\nvar boneSampler : texture_2d;\nuniform boneTextureWidth : f32;\n#else\nuniform mBones : array;\n#ifdef BONES_VELOCITY_ENABLED\nuniform mPreviousBones : array;\n#endif\n#endif\n#ifdef BONETEXTURE\nfn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4\n{\nlet offset=i32(index) *4; \nlet m0=textureLoad(smp,vec2(offset+0,0),0);\nlet m1=textureLoad(smp,vec2(offset+1,0),0);\nlet m2=textureLoad(smp,vec2(offset+2,0),0);\nlet m3=textureLoad(smp,vec2(offset+3,0),0);\nreturn mat4x4(m0,m1,m2,m3);\n}\n#endif\n#endif\n#endif\n";Ht.v.IncludesShadersStoreWGSL[ad]=ld;const hd="bonesVertex",cd="#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#if NUM_BONE_INFLUENCERS>0\nvar influence : mat4x4;\n#ifdef BONETEXTURE\ninfluence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3];\n#endif \n#else \ninfluence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3];\n#endif \n#endif\nfinalWorld=finalWorld*influence;\n#endif\n#endif\n";Ht.v.IncludesShadersStoreWGSL[hd]=cd;const dd="bakedVertexAnimationDeclaration",ud="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\nuniform bakedVertexAnimationTime: f32;\nuniform bakedVertexAnimationTextureSizeInverted: vec2;\nuniform bakedVertexAnimationSettings: vec4;\nvar bakedVertexAnimationTexture : texture_2d;\n#ifdef INSTANCES\nattribute bakedVertexAnimationSettingsInstanced : vec4;\n#endif\nfn readMatrixFromRawSamplerVAT(smp : texture_2d,index : f32,frame : f32)->mat4x4\n{\nlet offset=i32(index)*4;\nlet frameUV=i32(frame);\nlet m0=textureLoad(smp,vec2(offset+0,frameUV),0);\nlet m1=textureLoad(smp,vec2(offset+1,frameUV),0);\nlet m2=textureLoad(smp,vec2(offset+2,frameUV),0);\nlet m3=textureLoad(smp,vec2(offset+3,frameUV),0);\nreturn mat4x4(m0,m1,m2,m3);\n}\n#endif\n";Ht.v.IncludesShadersStoreWGSL[dd]=ud;const pd="bakedVertexAnimation",fd="#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\n{\n#ifdef INSTANCES\nlet VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;\nlet VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;\nlet VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;\nlet VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w;\n#else\nlet VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;\nlet VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;\nlet VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;\nlet VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w;\n#endif\nlet totalFrames: f32=VATEndFrame-VATStartFrame+1.0;\nlet time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;\nlet frameCorrection: f32=select(1.0,0.0,time<1.0);\nlet numOfFrames: f32=totalFrames-frameCorrection;\nvar VATFrameNum: f32=fract(time)*numOfFrames;\nVATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;\nVATFrameNum=floor(VATFrameNum);\nVATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;\nvar VATInfluence : mat4x4;\nVATInfluence=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}\n#endif\n";Ht.v.IncludesShadersStoreWGSL[pd]=fd;const _d="clipPlaneFragment",md="#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{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE2\nelse if (fragmentInputs.fClipDistance2>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE3\nelse if (fragmentInputs.fClipDistance3>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE4\nelse if (fragmentInputs.fClipDistance4>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE5\nelse if (fragmentInputs.fClipDistance5>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE6\nelse if (fragmentInputs.fClipDistance6>0.0)\n{\ndiscard;\n}\n#endif\n";Ht.v.IncludesShadersStoreWGSL[_d]=md;const gd="clipPlaneFragmentDeclaration",vd="#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";Ht.v.IncludesShadersStoreWGSL[gd]=vd;const Td="clipPlaneVertex",Sd="#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";Ht.v.IncludesShadersStoreWGSL[Td]=Sd;const Ed="clipPlaneVertexDeclaration",xd="#ifdef CLIPPLANE\nuniform vClipPlane: vec4;\nvarying fClipDistance: f32;\n#endif\n#ifdef CLIPPLANE2\nuniform vClipPlane2: vec4;\nvarying fClipDistance2: f32;\n#endif\n#ifdef CLIPPLANE3\nuniform vClipPlane3: vec4;\nvarying fClipDistance3: f32;\n#endif\n#ifdef CLIPPLANE4\nuniform vClipPlane4: vec4;\nvarying fClipDistance4: f32;\n#endif\n#ifdef CLIPPLANE5\nuniform vClipPlane5: vec4;\nvarying fClipDistance5: f32;\n#endif\n#ifdef CLIPPLANE6\nuniform vClipPlane6: vec4;\nvarying fClipDistance6: f32;\n#endif\n";Ht.v.IncludesShadersStoreWGSL[Ed]=xd;const bd="instancesDeclaration",Cd="#ifdef INSTANCES\nattribute world0 : vec4;\nattribute world1 : vec4;\nattribute world2 : vec4;\nattribute world3 : vec4;\n#ifdef INSTANCESCOLOR\nattribute instanceColor : vec4;\n#endif\n#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)\nuniform world : mat4x4;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nattribute previousWorld0 : vec4;\nattribute previousWorld1 : vec4;\nattribute previousWorld2 : vec4;\nattribute previousWorld3 : vec4;\n#ifdef THIN_INSTANCES\nuniform previousWorld : mat4x4;\n#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nuniform world : mat4x4;\n#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nuniform previousWorld : mat4x4;\n#endif\n#endif\n";Ht.v.IncludesShadersStoreWGSL[bd]=Cd;const yd="instancesVertex",Ad="#ifdef INSTANCES\nvar finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3);\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=mat4x4(previousWorld0,previousWorld1,previousWorld2,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=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=previousWorld;\n#endif\n#endif\n";Ht.v.IncludesShadersStoreWGSL[yd]=Ad;const Rd="meshUboDeclaration",Pd="struct Mesh {\nworld : mat4x4,\nvisibility : f32,\n};\nvar mesh : Mesh;\n#define WORLD_UBO\n";Ht.v.IncludesShadersStoreWGSL[Rd]=Pd;const Id="morphTargetsVertex",Md="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE \nvertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;\npositionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];\nvertexID=vertexID+1.0;\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];\nvertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];\nvertexID=vertexID+1.0;\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\n#endif\n#else\npositionUpdated=positionUpdated+(position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];\n#endif\n#endif\n#endif\n";Ht.v.IncludesShadersStoreWGSL[Id]=Md;const Od="morphTargetsVertexDeclaration",Dd="#ifdef MORPHTARGETS\n#ifndef MORPHTARGETS_TEXTURE\nattribute position{X} : vec3;\n#ifdef MORPHTARGETS_NORMAL\nattribute normal{X} : vec3;\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute tangent{X} : vec3;\n#endif\n#ifdef MORPHTARGETS_UV\nattribute uv_{X} : vec2;\n#endif\n#endif\n#endif\n";Ht.v.IncludesShadersStoreWGSL[Od]=Dd;const Nd="morphTargetsVertexGlobal",Fd="#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\nvar vertexID : f32;\n#endif\n#endif\n";Ht.v.IncludesShadersStoreWGSL[Nd]=Fd;const wd="morphTargetsVertexGlobalDeclaration",Ld="#ifdef MORPHTARGETS\nuniform morphTargetInfluences : array;\n#ifdef MORPHTARGETS_TEXTURE \nuniform morphTargetTextureIndices : array;\nuniform morphTargetTextureInfo : vec3;\nvar morphTargets : texture_2d_array;\nvar morphTargetsSampler : sampler;\nfn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3\n{ \nlet y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);\nlet x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;\nlet textureUV=vec2((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);\nreturn textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;\n}\n#endif\n#endif\n";Ht.v.IncludesShadersStoreWGSL[wd]=Ld;const Bd="sceneUboDeclaration",Ud="struct Scene {\nviewProjection : mat4x4,\n#ifdef MULTIVIEW\nviewProjectionR : mat4x4,\n#endif \nview : mat4x4,\nprojection : mat4x4,\nvEyePosition : vec4,\n};\nvar scene : Scene;\n";Ht.v.IncludesShadersStoreWGSL[Bd]=Ud;const Vd="fragmentOutputs.fragDepth",kd={texture_1d:bc.E1d,texture_2d:bc.E2d,texture_2d_array:bc.E2dArray,texture_3d:bc.E3d,texture_cube:bc.Cube,texture_cube_array:bc.CubeArray,texture_multisampled_2d:bc.E2d,texture_depth_2d:bc.E2d,texture_depth_2d_array:bc.E2dArray,texture_depth_cube:bc.Cube,texture_depth_cube_array:bc.CubeArray,texture_depth_multisampled_2d:bc.E2d,texture_storage_1d:bc.E1d,texture_storage_2d:bc.E2d,texture_storage_2d_array:bc.E2dArray,texture_storage_3d:bc.E3d,texture_external:null};class Gd extends id{constructor(){super(...arguments),this.shaderLanguage=Qt.x.WGSL,this.uniformRegexp=/uniform\s+(\w+)\s*:\s*(.+)\s*;/,this.textureRegexp=/var\s+(\w+)\s*:\s*((array<\s*)?(texture_\w+)\s*(<\s*(.+)\s*>)?\s*(,\s*\w+\s*>\s*)?);/,this.noPrecision=!0}_getArraySize(e,t,i){let n=0;const s=t.lastIndexOf(">");if(t.indexOf("array")>=0&&s>0){let e=s;for(;e>0&&" "!==t.charAt(e)&&","!==t.charAt(e);)e--;const r=t.substring(e+1,s);for(n=+r,isNaN(n)&&(n=+i[r.trim()]);e>0&&(" "===t.charAt(e)||","===t.charAt(e));)e--;t=t.substring(t.indexOf("<")+1,e+1)}return[e,t,n]}initializeShaders(e){this._webgpuProcessingContext=e,this._attributesWGSL=[],this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){return`struct ${id.InternalsUBOName} {\n yFactor_: f32,\n textureOutputHeight_: f32,\n};\nvar internals : ${id.InternalsUBOName};\n`+sc(e)}varyingProcessor(e,t,i){const n=/\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==n){const s=n[2],r=n[1];let o;t?(o=this._webgpuProcessingContext.availableVaryings[r],void 0===o&&p.Y.Warn(`Invalid fragment shader: The varying named "${r}" is not declared in the vertex shader! This declaration will be ignored.`)):(o=this._webgpuProcessingContext.getVaryingNextLocation(s,this._getArraySize(r,s,i)[2]),this._webgpuProcessingContext.availableVaryings[r]=o,this._varyingsWGSL.push(` @location(${o}) ${r} : ${s},`),this._varyingNamesWGSL.push(r)),e=""}return e}attributeProcessor(e,t){const i=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==i){const n=i[2],s=i[1],r=this._webgpuProcessingContext.getAttributeNextLocation(n,this._getArraySize(s,n,t)[2]);this._webgpuProcessingContext.availableAttributes[s]=r,this._webgpuProcessingContext.orderedAttributes[r]=s,this._attributesWGSL.push(`@location(${r}) ${s} : ${n},`),e=""}return e}uniformProcessor(e,t,i){const n=this.uniformRegexp.exec(e);if(null!==n){const t=n[2],s=n[1];this._addUniformToLeftOverUBO(s,t,i),e=""}return e}textureProcessor(e,t,i){const n=this.textureRegexp.exec(e);if(null!==n){const s=n[1],r=n[2],o=!!n[3],a=n[4],l=a.indexOf("storage")>0,h=n[6],c=l?h.substring(0,h.indexOf(",")).trim():null;let d=o?this._getArraySize(s,r,i)[2]:0,u=this._webgpuProcessingContext.availableTextures[s];if(u)d=u.textures.length;else{u={isTextureArray:d>0,isStorageTexture:l,textures:[],sampleType:Nc.Float},d=d||1;for(let e=0;e0,f=kd[a],_=p?Nc.Depth:"u32"===h?Nc.Uint:"i32"===h?Nc.Sint:Nc.Float;if(u.sampleType=_,void 0===f)throw`Can't get the texture dimension corresponding to the texture function "${a}"!`;for(let i=0;i=0?"\n if (internals.yFactor_ == 1.) {\n fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y;\n }\n ":"";e=this._processSamplers(e,!0),t=this._processSamplers(t,!1),e=this._processCustomBuffers(e,!0),t=this._processCustomBuffers(t,!1);const n=this._buildLeftOverUBO();t=n+t,e=(e=n+e).replace(/#define /g,"//#define "),e=this._processStridedUniformArrays(e);let s="struct VertexInputs {\n @builtin(vertex_index) vertexIndex : u32,\n @builtin(instance_index) instanceIndex : u32,\n";this._attributesWGSL.length>0&&(s+=this._attributesWGSL.join("\n")),s+="\n};\nvar vertexInputs : VertexInputs;\n";let r="struct FragmentInputs {\n @builtin(position) position : vec4,\n";this._varyingsWGSL.length>0&&(r+=this._varyingsWGSL.join("\n")),r+="\n};\nvar vertexOutputs : FragmentInputs;\n",e=s+r+e;e=this._injectStartingAndEndingCode(e,"fn main","\n vertexInputs = input;\n"," vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_;\n return vertexOutputs;"),t=t.replace(/#define /g,"//#define "),t=(t=this._processStridedUniformArrays(t)).replace(/dpdy/g,"(-internals.yFactor_)*dpdy");let o="struct FragmentInputs {\n @builtin(position) position : vec4,\n @builtin(front_facing) frontFacing : bool,\n";this._varyingsWGSL.length>0&&(o+=this._varyingsWGSL.join("\n")),o+="\n};\nvar fragmentInputs : FragmentInputs;\n";let a="struct FragmentOutputs {\n @location(0) color : vec4,\n",l=!1,h=0;for(;!(l||(h=t.indexOf(Vd,h),h<0));){const e=h;for(l=!0;h>1&&"\n"!==t.charAt(h);){if("/"===t.charAt(h)&&"/"===t.charAt(h-1)){l=!1;break}h--}h=e+25}l&&(a+=" @builtin(frag_depth) fragDepth: f32,\n"),a+="};\nvar fragmentOutputs : FragmentOutputs;\n",t=o+a+t;const c=" fragmentInputs = input;\n "+i;return t=this._injectStartingAndEndingCode(t,"fn main",c," return fragmentOutputs;"),this._collectBindingNames(),this._preCreateBindGroupEntries(),{vertexCode:e,fragmentCode:t}}_generateLeftOverUBOCode(e,t){let i="",n=`struct ${e} {\n`;for(const s of this._webgpuProcessingContext.leftOverUniforms){const t=s.type.replace(/^(.*?)(<.*>)?$/,"$1"),r=id.UniformSizes[t];if(s.length>0)if(r<=2){const r=`${e}_${this._stridedUniformArrays.length}_strided_arr`;i+=`struct ${r} {\n @size(16)\n el: ${t},\n }`,this._stridedUniformArrays.push(s.name),n+=` @align(16) ${s.name} : array<${r}, ${s.length}>,\n`}else n+=` ${s.name} : array<${s.type}, ${s.length}>,\n`;else n+=` ${s.name} : ${s.type},\n`}return n+="};\n",n=`${i}\n${n}`,n+=`@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var uniforms : ${e};\n`,n}_processSamplers(e,t){const i=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;for(;;){const n=i.exec(e);if(null===n)break;const s=n[1],r=n[2],o=s.indexOf(id.AutoSamplerSuffix)===s.length-id.AutoSamplerSuffix.length?s.substring(0,s.indexOf(id.AutoSamplerSuffix)):null,a="sampler_comparison"===r?Dc.Comparison:Dc.Filtering;if(o){const e=this._webgpuProcessingContext.availableTextures[o];e&&(e.autoBindSampler=!0)}let l=this._webgpuProcessingContext.availableSamplers[s];l||(l={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:a},this._webgpuProcessingContext.availableSamplers[s]=l),this._addSamplerBindingDescription(s,l,t);const h=e.substring(0,n.index),c=`@group(${l.binding.groupIndex}) @binding(${l.binding.bindingIndex}) `,d=e.substring(n.index);e=h+c+d,i.lastIndex+=c.length}return e}_processCustomBuffers(e,t){const i=/var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;for(;;){const n=i.exec(e);if(null===n)break;const s=n[1],r=n[3];let o=n[4];const a=n[5];let l=this._webgpuProcessingContext.availableBuffers[o];if(!l){const e="uniform"===s?rd.KnownUBOs[a]:null;let t;e?(o=a,t=e.binding,-1===t.groupIndex&&(t=this._webgpuProcessingContext.getNextFreeUBOBinding())):t=this._webgpuProcessingContext.getNextFreeUBOBinding(),l={binding:t},this._webgpuProcessingContext.availableBuffers[o]=l}this._addBufferBindingDescription(o,this._webgpuProcessingContext.availableBuffers[o],"read_write"===r?Oc.Storage:"storage"===s?Oc.ReadOnlyStorage:Oc.Uniform,t);const h=l.binding.groupIndex,c=l.binding.bindingIndex,d=e.substring(0,n.index),u=`@group(${h}) @binding(${c}) `,p=e.substring(n.index);e=d+u+p,i.lastIndex+=u.length}return e}_processStridedUniformArrays(e){for(const t of this._stridedUniformArrays)e=e.replace(new RegExp(`${t}\\s*\\[(.*)\\]`,"g"),`${t}[$1].el`);return e}}class zd{get underlyingResource(){return this._webgpuTexture}getMSAATexture(e=0){var t,i;return null!==(i=null===(t=this._webgpuMSAATexture)||void 0===t?void 0:t[e])&&void 0!==i?i:null}setMSAATexture(e,t=-1){this._webgpuMSAATexture||(this._webgpuMSAATexture=[]),-1===t&&(t=this._webgpuMSAATexture.length),this._webgpuMSAATexture[t]=e}releaseMSAATexture(){if(this._webgpuMSAATexture){for(const e of this._webgpuMSAATexture)null==e||e.destroy();this._webgpuMSAATexture=null}}constructor(e=null){this.format=yc.RGBA8Unorm,this.textureUsages=0,this.textureAdditionalUsages=0,this._webgpuTexture=e,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}set(e){this._webgpuTexture=e}setUsage(e,t,i,n,s){this.createView({format:this.format,dimension:i?bc.Cube:bc.E2d,mipLevelCount:t?S.R.ILog2(Math.max(n,s))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:i?6:1,aspect:Cc.All})}createView(e,t=!1){if(this.view=this._webgpuTexture.createView(e),t&&e){const t=e.mipLevelCount;e.mipLevelCount=1,this.viewForWriting=this._webgpuTexture.createView(e),e.mipLevelCount=t}}reset(){this._webgpuTexture=null,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}release(){var e,t;null===(e=this._webgpuTexture)||void 0===e||e.destroy(),this.releaseMSAATexture(),null===(t=this._copyInvertYTempTexture)||void 0===t||t.destroy(),this.reset()}}const Wd="\n #extension GL_EXT_samplerless_texture_functions : enable\n\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));\n\n layout(set = 0, binding = 0) uniform texture2D img;\n\n #ifdef INVERTY\n layout(location = 0) out flat ivec2 vTextureSize;\n #endif\n\n void main() {\n #ifdef INVERTY\n vTextureSize = textureSize(img, 0);\n #endif\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",Hd=Wd;var Xd,Yd;!function(e){e[e.MipMap=0]="MipMap",e[e.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",e[e.Clear=2]="Clear",e[e.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst"}(Xd||(Xd={})),function(e){e[e.DontInvertY=0]="DontInvertY",e[e.InvertY=1]="InvertY"}(Yd||(Yd={}));const jd=[{vertex:"\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));\n\n layout(location = 0) out vec2 vTex;\n\n void main() {\n vTex = tex[gl_VertexIndex];\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n layout(set = 0, binding = 0) uniform sampler imgSampler;\n layout(set = 0, binding = 1) uniform texture2D img;\n\n layout(location = 0) in vec2 vTex;\n layout(location = 0) out vec4 outColor;\n\n void main() {\n outColor = texture(sampler2D(img, imgSampler), vTex);\n }\n "},{vertex:Wd,fragment:"\n #extension GL_EXT_samplerless_texture_functions : enable\n\n layout(set = 0, binding = 0) uniform texture2D img;\n\n #ifdef INVERTY\n layout(location = 0) in flat ivec2 vTextureSize;\n #endif\n layout(location = 0) out vec4 outColor;\n\n void main() {\n #ifdef INVERTY\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0);\n #else\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color.rgb *= color.a;\n #endif\n outColor = color;\n }\n "},{vertex:"\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\n\n void main() {\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\n }\n ",fragment:"\n layout(set = 0, binding = 0) uniform Uniforms {\n uniform vec4 color;\n };\n\n layout(location = 0) out vec4 outColor;\n\n void main() {\n outColor = color;\n }\n "},{vertex:Hd,fragment:"\n #extension GL_EXT_samplerless_texture_functions : enable\n\n layout(set = 0, binding = 0) uniform texture2D img;\n layout(set = 0, binding = 1) uniform Params {\n float ofstX;\n float ofstY;\n float width;\n float height;\n };\n\n #ifdef INVERTY\n layout(location = 0) in flat ivec2 vTextureSize;\n #endif\n layout(location = 0) out vec4 outColor;\n\n void main() {\n if (gl_FragCoord.x < ofstX || gl_FragCoord.x >= ofstX + width) {\n discard;\n }\n if (gl_FragCoord.y < ofstY || gl_FragCoord.y >= ofstY + height) {\n discard;\n }\n #ifdef INVERTY\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, ofstY + height - (gl_FragCoord.y - ofstY)), 0);\n #else\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\n #endif\n #ifdef PREMULTIPLYALPHA\n color.rgb *= color.a;\n #endif\n outColor = color;\n }\n "}],Kd={"":0,r8unorm:1,r8uint:2,r8sint:3,r16uint:4,r16sint:5,r16float:6,rg8unorm:7,rg8uint:8,rg8sint:9,r32uint:10,r32sint:11,r32float:12,rg16uint:13,rg16sint:14,rg16float:15,rgba8unorm:16,"rgba8unorm-srgb":17,rgba8uint:18,rgba8sint:19,bgra8unorm:20,"bgra8unorm-srgb":21,rgb10a2unorm:22,rg32uint:23,rg32sint:24,rg32float:25,rgba16uint:26,rgba16sint:27,rgba16float:28,rgba32uint:29,rgba32sint:30,rgba32float:31,stencil8:32,depth16unorm:33,depth24plus:34,"depth24plus-stencil8":35,depth32float:36,"depth32float-stencil8":37};class qd{static ComputeNumMipmapLevels(e,t){return S.R.ILog2(Math.max(e,t))+1}constructor(e,t,i,n,s){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._device=e,this._glslang=t,this._tintWASM=i,this._bufferManager=n,-1!==s.indexOf(gc.RG11B10UFloatRenderable)){const e=Object.keys(Kd);Kd[yc.RG11B10UFloat]=Kd[e[e.length-1]]+1}this._mipmapSampler=e.createSampler({minFilter:Rc.Linear}),this._videoSampler=e.createSampler({minFilter:Rc.Linear}),this._ubCopyWithOfst=this._bufferManager.createBuffer(16,Tc.Uniform|Tc.CopyDst).underlyingResource,this._getPipeline(yc.RGBA8Unorm),this._getVideoPipeline(yc.RGBA8Unorm)}_getPipeline(e,t=Xd.MipMap,i){const n=t===Xd.MipMap?1:t===Xd.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===Xd.Clear?8:t===Xd.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);let s=this._pipelines[e][n];if(!s){let r="#version 450\r\n";t!==Xd.InvertYPremultiplyAlpha&&t!==Xd.InvertYPremultiplyAlphaWithOfst||(i.invertY&&(r+="#define INVERTY\r\n"),i.premultiplyAlpha&&(r+="#define PREMULTIPLYALPHA\r\n"));let o=this._compiledShaders[n];if(!o){let e=this._glslang.compileGLSL(r+jd[t].vertex,"vertex"),i=this._glslang.compileGLSL(r+jd[t].fragment,"fragment");this._tintWASM&&(e=this._tintWASM.convertSpirV2WGSL(e),i=this._tintWASM.convertSpirV2WGSL(i));const s=this._device.createShaderModule({code:e}),a=this._device.createShaderModule({code:i});o=this._compiledShaders[n]=[s,a]}const a=this._device.createRenderPipeline({layout:Bc.Auto,vertex:{module:o[0],entryPoint:"main"},fragment:{module:o[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:Uc.TriangleStrip,stripIndexFormat:Xc.Uint16}});s=this._pipelines[e][n]=[a,a.getBindGroupLayout(0)]}return s}_getVideoPipeline(e,t=Yd.DontInvertY){const i=t===Yd.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let n=this._videoPipelines[e][i];if(!n){let t=this._videoCompiledShaders[i];if(!t){const e=this._device.createShaderModule({code:"\n struct VertexOutput {\n @builtin(position) Position : vec4,\n @location(0) fragUV : vec2\n }\n \n @vertex\n fn main(\n @builtin(vertex_index) VertexIndex : u32\n ) -> VertexOutput {\n var pos = array, 4>(\n vec2(-1.0, 1.0),\n vec2( 1.0, 1.0),\n vec2(-1.0, -1.0),\n vec2( 1.0, -1.0)\n );\n var tex = array, 4>(\n vec2(0.0, 0.0),\n vec2(1.0, 0.0),\n vec2(0.0, 1.0),\n vec2(1.0, 1.0)\n );\n\n var output: VertexOutput;\n\n output.Position = vec4(pos[VertexIndex], 0.0, 1.0);\n output.fragUV = tex[VertexIndex];\n\n return output;\n }\n "}),n=this._device.createShaderModule({code:0===i?"\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2\n ) -> @location(0) vec4 {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV);\n }\n ":"\n @group(0) @binding(0) var videoSampler: sampler;\n @group(0) @binding(1) var videoTexture: texture_external;\n\n @fragment\n fn main(\n @location(0) fragUV: vec2\n ) -> @location(0) vec4 {\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2(fragUV.x, 1.0 - fragUV.y));\n }\n "});t=this._videoCompiledShaders[i]=[e,n]}const s=this._device.createRenderPipeline({label:`CopyVideoToTexture_${e}_${0===i?"DontInvertY":"InvertY"}`,layout:Bc.Auto,vertex:{module:t[0],entryPoint:"main"},fragment:{module:t[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:Uc.TriangleStrip,stripIndexFormat:Xc.Uint16}});n=this._videoPipelines[e][i]=[s,s.getBindGroupLayout(0)]}return n}static _GetTextureTypeFromFormat(e){switch(e){case yc.R8Unorm:case yc.R8Snorm:case yc.R8Uint:case yc.R8Sint:case yc.RG8Unorm:case yc.RG8Snorm:case yc.RG8Uint:case yc.RG8Sint:case yc.RGBA8Unorm:case yc.RGBA8UnormSRGB:case yc.RGBA8Snorm:case yc.RGBA8Uint:case yc.RGBA8Sint:case yc.BGRA8Unorm:case yc.BGRA8UnormSRGB:case yc.RGB10A2Unorm:case yc.RGB9E5UFloat:case yc.RG11B10UFloat:case yc.Depth24UnormStencil8:case yc.Depth32FloatStencil8:case yc.BC7RGBAUnorm:case yc.BC7RGBAUnormSRGB:case yc.BC6HRGBUFloat:case yc.BC6HRGBFloat:case yc.BC5RGUnorm:case yc.BC5RGSnorm:case yc.BC3RGBAUnorm:case yc.BC3RGBAUnormSRGB:case yc.BC2RGBAUnorm:case yc.BC2RGBAUnormSRGB:case yc.BC4RUnorm:case yc.BC4RSnorm:case yc.BC1RGBAUnorm:case yc.BC1RGBAUnormSRGB:case yc.ETC2RGB8Unorm:case yc.ETC2RGB8UnormSRGB:case yc.ETC2RGB8A1Unorm:case yc.ETC2RGB8A1UnormSRGB:case yc.ETC2RGBA8Unorm:case yc.ETC2RGBA8UnormSRGB:case yc.EACR11Unorm:case yc.EACR11Snorm:case yc.EACRG11Unorm:case yc.EACRG11Snorm:case yc.ASTC4x4Unorm:case yc.ASTC4x4UnormSRGB:case yc.ASTC5x4Unorm:case yc.ASTC5x4UnormSRGB:case yc.ASTC5x5Unorm:case yc.ASTC5x5UnormSRGB:case yc.ASTC6x5Unorm:case yc.ASTC6x5UnormSRGB:case yc.ASTC6x6Unorm:case yc.ASTC6x6UnormSRGB:case yc.ASTC8x5Unorm:case yc.ASTC8x5UnormSRGB:case yc.ASTC8x6Unorm:case yc.ASTC8x6UnormSRGB:case yc.ASTC8x8Unorm:case yc.ASTC8x8UnormSRGB:case yc.ASTC10x5Unorm:case yc.ASTC10x5UnormSRGB:case yc.ASTC10x6Unorm:case yc.ASTC10x6UnormSRGB:case yc.ASTC10x8Unorm:case yc.ASTC10x8UnormSRGB:case yc.ASTC10x10Unorm:case yc.ASTC10x10UnormSRGB:case yc.ASTC12x10Unorm:case yc.ASTC12x10UnormSRGB:case yc.ASTC12x12Unorm:case yc.ASTC12x12UnormSRGB:return 0;case yc.R16Uint:case yc.R16Sint:case yc.RG16Uint:case yc.RG16Sint:case yc.RGBA16Uint:case yc.RGBA16Sint:case yc.Depth16Unorm:return 5;case yc.R16Float:case yc.RG16Float:case yc.RGBA16Float:return 2;case yc.R32Uint:case yc.R32Sint:case yc.RG32Uint:case yc.RG32Sint:case yc.RGBA32Uint:case yc.RGBA32Sint:return 7;case yc.R32Float:case yc.RG32Float:case yc.RGBA32Float:case yc.Depth32Float:return 1;case yc.Stencil8:throw"No fixed size for Stencil8 format!";case yc.Depth24Plus:throw"No fixed size for Depth24Plus format!";case yc.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!"}return 0}static _GetBlockInformationFromFormat(e){switch(e){case yc.R8Unorm:case yc.R8Snorm:case yc.R8Uint:case yc.R8Sint:return{width:1,height:1,length:1};case yc.R16Uint:case yc.R16Sint:case yc.R16Float:case yc.RG8Unorm:case yc.RG8Snorm:case yc.RG8Uint:case yc.RG8Sint:return{width:1,height:1,length:2};case yc.R32Uint:case yc.R32Sint:case yc.R32Float:case yc.RG16Uint:case yc.RG16Sint:case yc.RG16Float:case yc.RGBA8Unorm:case yc.RGBA8UnormSRGB:case yc.RGBA8Snorm:case yc.RGBA8Uint:case yc.RGBA8Sint:case yc.BGRA8Unorm:case yc.BGRA8UnormSRGB:case yc.RGB9E5UFloat:case yc.RGB10A2Unorm:case yc.RG11B10UFloat:return{width:1,height:1,length:4};case yc.RG32Uint:case yc.RG32Sint:case yc.RG32Float:case yc.RGBA16Uint:case yc.RGBA16Sint:case yc.RGBA16Float:return{width:1,height:1,length:8};case yc.RGBA32Uint:case yc.RGBA32Sint:case yc.RGBA32Float:return{width:1,height:1,length:16};case yc.Stencil8:throw"No fixed size for Stencil8 format!";case yc.Depth16Unorm:return{width:1,height:1,length:2};case yc.Depth24Plus:throw"No fixed size for Depth24Plus format!";case yc.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!";case yc.Depth32Float:case yc.Depth24UnormStencil8:return{width:1,height:1,length:4};case yc.Depth32FloatStencil8:return{width:1,height:1,length:5};case yc.BC7RGBAUnorm:case yc.BC7RGBAUnormSRGB:case yc.BC6HRGBUFloat:case yc.BC6HRGBFloat:case yc.BC5RGUnorm:case yc.BC5RGSnorm:case yc.BC3RGBAUnorm:case yc.BC3RGBAUnormSRGB:case yc.BC2RGBAUnorm:case yc.BC2RGBAUnormSRGB:return{width:4,height:4,length:16};case yc.BC4RUnorm:case yc.BC4RSnorm:case yc.BC1RGBAUnorm:case yc.BC1RGBAUnormSRGB:case yc.ETC2RGB8Unorm:case yc.ETC2RGB8UnormSRGB:case yc.ETC2RGB8A1Unorm:case yc.ETC2RGB8A1UnormSRGB:case yc.EACR11Unorm:case yc.EACR11Snorm:return{width:4,height:4,length:8};case yc.ETC2RGBA8Unorm:case yc.ETC2RGBA8UnormSRGB:case yc.EACRG11Unorm:case yc.EACRG11Snorm:case yc.ASTC4x4Unorm:case yc.ASTC4x4UnormSRGB:return{width:4,height:4,length:16};case yc.ASTC5x4Unorm:case yc.ASTC5x4UnormSRGB:return{width:5,height:4,length:16};case yc.ASTC5x5Unorm:case yc.ASTC5x5UnormSRGB:return{width:5,height:5,length:16};case yc.ASTC6x5Unorm:case yc.ASTC6x5UnormSRGB:return{width:6,height:5,length:16};case yc.ASTC6x6Unorm:case yc.ASTC6x6UnormSRGB:return{width:6,height:6,length:16};case yc.ASTC8x5Unorm:case yc.ASTC8x5UnormSRGB:return{width:8,height:5,length:16};case yc.ASTC8x6Unorm:case yc.ASTC8x6UnormSRGB:return{width:8,height:6,length:16};case yc.ASTC8x8Unorm:case yc.ASTC8x8UnormSRGB:return{width:8,height:8,length:16};case yc.ASTC10x5Unorm:case yc.ASTC10x5UnormSRGB:return{width:10,height:5,length:16};case yc.ASTC10x6Unorm:case yc.ASTC10x6UnormSRGB:return{width:10,height:6,length:16};case yc.ASTC10x8Unorm:case yc.ASTC10x8UnormSRGB:return{width:10,height:8,length:16};case yc.ASTC10x10Unorm:case yc.ASTC10x10UnormSRGB:return{width:10,height:10,length:16};case yc.ASTC12x10Unorm:case yc.ASTC12x10UnormSRGB:return{width:12,height:10,length:16};case yc.ASTC12x12Unorm:case yc.ASTC12x12UnormSRGB:return{width:12,height:12,length:16}}return{width:1,height:1,length:4}}static _IsHardwareTexture(e){return!!e.release}static _IsInternalTexture(e){return!!e.dispose}static IsImageBitmap(e){return void 0!==e.close}static IsImageBitmapArray(e){return Array.isArray(e)&&void 0!==e[0].close}setCommandEncoder(e){this._commandEncoderForCreation=e}static IsCompressedFormat(e){switch(e){case yc.BC7RGBAUnormSRGB:case yc.BC7RGBAUnorm:case yc.BC6HRGBFloat:case yc.BC6HRGBUFloat:case yc.BC5RGSnorm:case yc.BC5RGUnorm:case yc.BC4RSnorm:case yc.BC4RUnorm:case yc.BC3RGBAUnormSRGB:case yc.BC3RGBAUnorm:case yc.BC2RGBAUnormSRGB:case yc.BC2RGBAUnorm:case yc.BC1RGBAUnormSRGB:case yc.BC1RGBAUnorm:case yc.ETC2RGB8Unorm:case yc.ETC2RGB8UnormSRGB:case yc.ETC2RGB8A1Unorm:case yc.ETC2RGB8A1UnormSRGB:case yc.ETC2RGBA8Unorm:case yc.ETC2RGBA8UnormSRGB:case yc.EACR11Unorm:case yc.EACR11Snorm:case yc.EACRG11Unorm:case yc.EACRG11Snorm:case yc.ASTC4x4Unorm:case yc.ASTC4x4UnormSRGB:case yc.ASTC5x4Unorm:case yc.ASTC5x4UnormSRGB:case yc.ASTC5x5Unorm:case yc.ASTC5x5UnormSRGB:case yc.ASTC6x5Unorm:case yc.ASTC6x5UnormSRGB:case yc.ASTC6x6Unorm:case yc.ASTC6x6UnormSRGB:case yc.ASTC8x5Unorm:case yc.ASTC8x5UnormSRGB:case yc.ASTC8x6Unorm:case yc.ASTC8x6UnormSRGB:case yc.ASTC8x8Unorm:case yc.ASTC8x8UnormSRGB:case yc.ASTC10x5Unorm:case yc.ASTC10x5UnormSRGB:case yc.ASTC10x6Unorm:case yc.ASTC10x6UnormSRGB:case yc.ASTC10x8Unorm:case yc.ASTC10x8UnormSRGB:case yc.ASTC10x10Unorm:case yc.ASTC10x10UnormSRGB:case yc.ASTC12x10Unorm:case yc.ASTC12x10UnormSRGB:case yc.ASTC12x12Unorm:case yc.ASTC12x12UnormSRGB:return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return yc.Depth16Unorm;case 16:return yc.Depth24Plus;case 13:return yc.Depth24PlusStencil8;case 14:return yc.Depth32Float;case 17:return yc.Depth24UnormStencil8;case 18:return yc.Depth32FloatStencil8;case 19:return yc.Stencil8;case 36492:return i?yc.BC7RGBAUnormSRGB:yc.BC7RGBAUnorm;case 36495:return yc.BC6HRGBUFloat;case 36494:return yc.BC6HRGBFloat;case 33779:return i?yc.BC3RGBAUnormSRGB:yc.BC3RGBAUnorm;case 33778:return i?yc.BC2RGBAUnormSRGB:yc.BC2RGBAUnorm;case 33777:case 33776:return i?yc.BC1RGBAUnormSRGB:yc.BC1RGBAUnorm;case 37808:return i?yc.ASTC4x4UnormSRGB:yc.ASTC4x4Unorm;case 36196:case 37492:return i?yc.ETC2RGB8UnormSRGB:yc.ETC2RGB8Unorm;case 37496:return i?yc.ETC2RGBA8UnormSRGB:yc.ETC2RGBA8Unorm}switch(e){case 3:switch(t){case 6:return yc.R8Snorm;case 7:return yc.RG8Snorm;case 4:throw"RGB format not supported in WebGPU";case 8:return yc.R8Sint;case 9:return yc.RG8Sint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return yc.RGBA8Sint;default:return yc.RGBA8Snorm}case 0:switch(t){case 6:return yc.R8Unorm;case 7:return yc.RG8Unorm;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?yc.RGBA8UnormSRGB:yc.RGBA8Unorm;case 12:return i?yc.BGRA8UnormSRGB:yc.BGRA8Unorm;case 8:return yc.R8Uint;case 9:return yc.RG8Uint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return yc.RGBA8Uint;case 0:throw"TEXTUREFORMAT_ALPHA format not supported in WebGPU";case 1:throw"TEXTUREFORMAT_LUMINANCE format not supported in WebGPU";case 2:throw"TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU";default:return yc.RGBA8Unorm}case 4:switch(t){case 8:return yc.R16Sint;case 9:return yc.RG16Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return yc.RGBA16Sint}case 5:switch(t){case 8:return yc.R16Uint;case 9:return yc.RG16Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return yc.RGBA16Uint}case 6:switch(t){case 8:return yc.R32Sint;case 9:return yc.RG32Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return yc.RGBA32Sint}case 7:switch(t){case 8:return yc.R32Uint;case 9:return yc.RG32Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return yc.RGBA32Uint}case 1:switch(t){case 6:return yc.R32Float;case 7:return yc.RG32Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return yc.RGBA32Float}case 2:switch(t){case 6:return yc.R16Float;case 7:return yc.RG16Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return yc.RGBA16Float}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:switch(t){case 5:default:return yc.RG11B10UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV"}case 14:switch(t){case 5:default:return yc.RGB9E5UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV"}case 8:throw"TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU";case 9:throw"TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU";case 11:switch(t){case 5:default:return yc.RGB10A2Unorm;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV"}}return i?yc.RGBA8UnormSRGB:yc.RGBA8Unorm}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case yc.R8Unorm:case yc.R8Snorm:case yc.R8Uint:case yc.R8Sint:case yc.BC4RUnorm:case yc.BC4RSnorm:case yc.R16Uint:case yc.R16Sint:case yc.Depth16Unorm:case yc.R16Float:case yc.R32Uint:case yc.R32Sint:case yc.R32Float:case yc.Depth32Float:case yc.Stencil8:case yc.Depth24Plus:case yc.EACR11Unorm:case yc.EACR11Snorm:return 1;case yc.RG8Unorm:case yc.RG8Snorm:case yc.RG8Uint:case yc.RG8Sint:case yc.Depth24UnormStencil8:case yc.Depth32FloatStencil8:case yc.BC5RGUnorm:case yc.BC5RGSnorm:case yc.RG16Uint:case yc.RG16Sint:case yc.RG16Float:case yc.RG32Uint:case yc.RG32Sint:case yc.RG32Float:case yc.Depth24PlusStencil8:case yc.EACRG11Unorm:case yc.EACRG11Snorm:return 2;case yc.RGB9E5UFloat:case yc.RG11B10UFloat:case yc.BC6HRGBUFloat:case yc.BC6HRGBFloat:case yc.ETC2RGB8Unorm:case yc.ETC2RGB8UnormSRGB:return 3;case yc.RGBA8Unorm:case yc.RGBA8UnormSRGB:case yc.RGBA8Snorm:case yc.RGBA8Uint:case yc.RGBA8Sint:case yc.BGRA8Unorm:case yc.BGRA8UnormSRGB:case yc.RGB10A2Unorm:case yc.BC7RGBAUnorm:case yc.BC7RGBAUnormSRGB:case yc.BC3RGBAUnorm:case yc.BC3RGBAUnormSRGB:case yc.BC2RGBAUnorm:case yc.BC2RGBAUnormSRGB:case yc.BC1RGBAUnorm:case yc.BC1RGBAUnormSRGB:case yc.RGBA16Uint:case yc.RGBA16Sint:case yc.RGBA16Float:case yc.RGBA32Uint:case yc.RGBA32Sint:case yc.RGBA32Float:case yc.ETC2RGB8A1Unorm:case yc.ETC2RGB8A1UnormSRGB:case yc.ETC2RGBA8Unorm:case yc.ETC2RGBA8UnormSRGB:case yc.ASTC4x4Unorm:case yc.ASTC4x4UnormSRGB:case yc.ASTC5x4Unorm:case yc.ASTC5x4UnormSRGB:case yc.ASTC5x5Unorm:case yc.ASTC5x5UnormSRGB:case yc.ASTC6x5Unorm:case yc.ASTC6x5UnormSRGB:case yc.ASTC6x6Unorm:case yc.ASTC6x6UnormSRGB:case yc.ASTC8x5Unorm:case yc.ASTC8x5UnormSRGB:case yc.ASTC8x6Unorm:case yc.ASTC8x6UnormSRGB:case yc.ASTC8x8Unorm:case yc.ASTC8x8UnormSRGB:case yc.ASTC10x5Unorm:case yc.ASTC10x5UnormSRGB:case yc.ASTC10x6Unorm:case yc.ASTC10x6UnormSRGB:case yc.ASTC10x8Unorm:case yc.ASTC10x8UnormSRGB:case yc.ASTC10x10Unorm:case yc.ASTC10x10UnormSRGB:case yc.ASTC12x10Unorm:case yc.ASTC12x10UnormSRGB:case yc.ASTC12x12Unorm:case yc.ASTC12x12UnormSRGB:return 4}throw`Unknown format ${e}!`}static HasStencilAspect(e){switch(e){case yc.Stencil8:case yc.Depth24UnormStencil8:case yc.Depth32FloatStencil8:case yc.Depth24PlusStencil8:return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case yc.Depth24UnormStencil8:case yc.Depth32FloatStencil8:case yc.Depth24PlusStencil8:return!0}return!1}static GetDepthFormatOnly(e){switch(e){case yc.Depth16Unorm:return yc.Depth16Unorm;case yc.Depth24Plus:case yc.Depth24PlusStencil8:case yc.Depth24UnormStencil8:return yc.Depth24Plus;case yc.Depth32Float:case yc.Depth32FloatStencil8:return yc.Depth32Float}return e}copyVideoToTexture(e,t,i,n=!1,s){var r,o,a,l;const h=void 0===s,[c,d]=this._getVideoPipeline(i,n?Yd.InvertY:Yd.DontInvertY);h&&(s=this._device.createCommandEncoder({})),null===(o=(r=s).pushDebugGroup)||void 0===o||o.call(r,`copy video to texture - invertY=${n}`);const u={colorAttachments:[{view:t._hardwareTexture.underlyingResource.createView({format:i,dimension:bc.E2d,mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:Cc.All}),loadOp:$c.Load,storeOp:Qc.Store}]},p=s.beginRenderPass(u),f={layout:d,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},_=this._device.createBindGroup(f);p.setPipeline(c),p.setBindGroup(0,_),p.draw(4,1,0,0),p.end(),null===(l=(a=s).popDebugGroup)||void 0===l||l.call(a),h&&(this._device.queue.submit([s.finish()]),s=null)}invertYPreMultiplyAlpha(e,t,i,n,s=!1,r=!1,o=0,a=0,l=1,h=0,c=0,d=0,u=0,p,f){var _,m,g,v,T,S;const E=0!==d,x=void 0===p,[b,C]=this._getPipeline(n,E?Xd.InvertYPremultiplyAlphaWithOfst:Xd.InvertYPremultiplyAlpha,{invertY:s,premultiplyAlpha:r});let y;if(o=Math.max(o,0),x&&(p=this._device.createCommandEncoder({})),null===(m=(_=p).pushDebugGroup)||void 0===m||m.call(_,`internal process texture - invertY=${s} premultiplyAlpha=${r}`),qd._IsHardwareTexture(e)?(y=e.underlyingResource,s&&!r&&1===l&&0===o||(e=void 0)):(y=e,e=void 0),!y)return;E&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([h,c,d,u]),0,16);const A=e,R=null!==(g=null==A?void 0:A._copyInvertYTempTexture)&&void 0!==g?g:this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,n,1,p,xc.CopySrc|xc.RenderAttachment|xc.TextureBinding,void 0,"TempTextureForCopyWithInvertY"),P=null!==(v=null==A?void 0:A._copyInvertYRenderPassDescr)&&void 0!==v?v:{colorAttachments:[{view:R.createView({format:n,dimension:bc.E2d,baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:$c.Load,storeOp:Qc.Store}]},I=p.beginRenderPass(P);let M=E?null==A?void 0:A._copyInvertYBindGroupWithOfst:null==A?void 0:A._copyInvertYBindGroup;if(!M){const e={layout:C,entries:[{binding:0,resource:y.createView({format:n,dimension:bc.E2d,baseMipLevel:a,mipLevelCount:1,arrayLayerCount:l,baseArrayLayer:o})}]};E&&e.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),M=this._device.createBindGroup(e)}I.setPipeline(b),I.setBindGroup(0,M),I.draw(4,1,0,0),I.end(),p.copyTextureToTexture({texture:R},{texture:y,mipLevel:a,origin:{x:0,y:0,z:o}},{width:t,height:i,depthOrArrayLayers:1}),A?(A._copyInvertYTempTexture=R,A._copyInvertYRenderPassDescr=P,E?A._copyInvertYBindGroupWithOfst=M:A._copyInvertYBindGroup=M):this._deferredReleaseTextures.push([R,null]),null===(S=(T=p).popDebugGroup)||void 0===S||S.call(T),x&&(this._device.queue.submit([p.finish()]),p=null)}copyWithInvertY(e,t,i,n){var s,r,o,a;const l=void 0===n,[h,c]=this._getPipeline(t,Xd.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});l&&(n=this._device.createCommandEncoder({})),null===(r=(s=n).pushDebugGroup)||void 0===r||r.call(s,"internal copy texture with invertY");const d=n.beginRenderPass(i),u=this._device.createBindGroup({layout:c,entries:[{binding:0,resource:e}]});d.setPipeline(h),d.setBindGroup(0,u),d.draw(4,1,0,0),d.end(),null===(a=(o=n).popDebugGroup)||void 0===a||a.call(o),l&&(this._device.queue.submit([n.finish()]),n=null)}createTexture(e,t=!1,i=!1,n=!1,s=!1,r=!1,o=yc.RGBA8Unorm,a=1,l,h=-1,c=0,d){a>1&&(a=4);const u=e.layers||1,p={width:e.width,height:e.height,depthOrArrayLayers:u},f=Kd[o]?xc.RenderAttachment:0,_=qd.IsCompressedFormat(o),m=t?qd.ComputeNumMipmapLevels(e.width,e.height):1,g=h>=0?h:xc.CopySrc|xc.CopyDst|xc.TextureBinding;c|=t&&!_?xc.CopySrc|f:0,_||r||(c|=f|xc.CopyDst);const v=this._device.createTexture({label:`Texture${r?"3D":"2D"}_${d?d+"_":""}${p.width}x${p.height}x${p.depthOrArrayLayers}_${t?"wmips":"womips"}_${o}_samples${a}`,size:p,dimension:r?Ec.E3d:Ec.E2d,format:o,usage:g|c,sampleCount:a,mipLevelCount:m});return qd.IsImageBitmap(e)&&(this.updateTexture(e,v,e.width,e.height,u,o,0,0,n,s,0,0),t&&i&&this.generateMipmaps(v,o,m,0,l)),v}createCubeTexture(e,t=!1,i=!1,n=!1,s=!1,r=yc.RGBA8Unorm,o=1,a,l=-1,h=0,c){o>1&&(o=4);const d=qd.IsImageBitmapArray(e)?e[0].width:e.width,u=qd.IsImageBitmapArray(e)?e[0].height:e.height,p=Kd[r]?xc.RenderAttachment:0,f=qd.IsCompressedFormat(r),_=t?qd.ComputeNumMipmapLevels(d,u):1,m=l>=0?l:xc.CopySrc|xc.CopyDst|xc.TextureBinding;h|=t&&!f?xc.CopySrc|p:0,f||(h|=p|xc.CopyDst);const g=this._device.createTexture({label:`TextureCube_${c?c+"_":""}${d}x${u}x6_${t?"wmips":"womips"}_${r}_samples${o}`,size:{width:d,height:u,depthOrArrayLayers:6},dimension:Ec.E2d,format:r,usage:m|h,sampleCount:o,mipLevelCount:_});return qd.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,g,d,u,r,n,s,0,0),t&&i&&this.generateCubeMipmaps(g,r,_,a)),g}generateCubeMipmaps(e,t,i,n){var s,r,o,a;const l=void 0===n;l&&(n=this._device.createCommandEncoder({})),null===(r=(s=n).pushDebugGroup)||void 0===r||r.call(s,`create cube mipmaps - ${i} levels`);for(let h=0;h<6;++h)this.generateMipmaps(e,t,i,h,n);null===(a=(o=n).popDebugGroup)||void 0===a||a.call(o),l&&(this._device.queue.submit([n.finish()]),n=null)}generateMipmaps(e,t,i,n=0,s){var r,o,a,l,h,c,d,u;const p=void 0===s,[f,_]=this._getPipeline(t);let m;if(n=Math.max(n,0),p&&(s=this._device.createCommandEncoder({})),null===(o=(r=s).pushDebugGroup)||void 0===o||o.call(r,`create mipmaps for face #${n} - ${i} levels`),qd._IsHardwareTexture(e)?(m=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(m=e,e=void 0),!m)return;const g=e;for(let v=1;vh;)this._device.queue.writeBuffer(r,t+c,i.buffer,o+c,h),c+=h;this._device.queue.writeBuffer(r,t+c,i.buffer,o+c,s-c)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));const n=new Uint16Array(t);for(;e--;)i[e]=Vh(n[e]);return i}readDataFromBuffer(e,t,i,n,s,r,o=0,a=0,l=null,h=!0,c=!1){const d=1===o?2:2===o?1:0;return new Promise(((i,u)=>{e.mapAsync(Sc.Read,a,t).then((()=>{const u=e.getMappedRange(a,t);let p=l;if(c)p=null===p?(0,Ch.A)(o,t,!0,u):(0,Ch.A)(o,p.buffer,void 0,u);else if(null===p)switch(d){case 0:p=new Uint8Array(t),p.set(new Uint8Array(u));break;case 1:p=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,u);break;case 2:p=new Float32Array(t/4),p.set(new Float32Array(u))}else switch(d){case 0:p=new Uint8Array(p.buffer),p.set(new Uint8Array(u));break;case 1:p=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,u,l);break;case 2:p=new Float32Array(p.buffer),p.set(new Float32Array(u))}if(s!==r){1!==d||c||(s*=2,r*=2);const e=new Uint8Array(p.buffer);let t=s,i=0;for(let o=1;ou(e)))}))}releaseBuffer(e){return Qd._IsGPUBuffer(e)?(this._deferredReleaseBuffers.push(e),!0):(e.references--,0===e.references&&(this._deferredReleaseBuffers.push(e.underlyingResource),!0))}destroyDeferredBuffers(){for(let e=0;e1?4:1;return Jd[e.samplingMode]+eu[(e._comparisonFunction||514)-512+1]+tu[e.samplingMode]+((null!==(t=e._cachedWrapU)&&void 0!==t?t:1)<<8)+((null!==(i=e._cachedWrapV)&&void 0!==i?i:1)<<10)+((null!==(n=e._cachedWrapR)&&void 0!==n?n:1)<<12)+((e.useMipMaps?1:0)<<14)+(s<<15)}static _GetSamplerFilterDescriptor(e,t){let i,n,s,r,o;const a=e.useMipMaps;switch(e.samplingMode){case 11:i=Rc.Linear,n=Rc.Linear,s=Rc.Nearest,a||(r=o=0);break;case 3:case 3:i=Rc.Linear,n=Rc.Linear,a?s=Rc.Linear:(s=Rc.Nearest,r=o=0);break;case 8:i=Rc.Nearest,n=Rc.Nearest,a?s=Rc.Linear:(s=Rc.Nearest,r=o=0);break;case 4:i=Rc.Nearest,n=Rc.Nearest,s=Rc.Nearest,a||(r=o=0);break;case 5:i=Rc.Nearest,n=Rc.Linear,s=Rc.Nearest,a||(r=o=0);break;case 6:i=Rc.Nearest,n=Rc.Linear,a?s=Rc.Linear:(s=Rc.Nearest,r=o=0);break;case 7:i=Rc.Nearest,n=Rc.Linear,s=Rc.Nearest,r=o=0;break;case 1:case 1:default:i=Rc.Nearest,n=Rc.Nearest,s=Rc.Nearest,r=o=0;break;case 9:i=Rc.Linear,n=Rc.Nearest,s=Rc.Nearest,a||(r=o=0);break;case 10:i=Rc.Linear,n=Rc.Nearest,a?s=Rc.Linear:(s=Rc.Nearest,r=o=0);break;case 2:case 2:i=Rc.Linear,n=Rc.Linear,s=Rc.Nearest,r=o=0;break;case 12:i=Rc.Linear,n=Rc.Nearest,s=Rc.Nearest,r=o=0}return t>1&&(0!==r||0!==o)?{magFilter:Rc.Linear,minFilter:Rc.Linear,mipmapFilter:Rc.Linear,anisotropyEnabled:!0}:{magFilter:i,minFilter:n,mipmapFilter:s,lodMinClamp:r,lodMaxClamp:o}}static _GetWrappingMode(e){switch(e){case 1:return Ac.Repeat;case 0:return Ac.ClampToEdge;case 2:return Ac.MirrorRepeat}return Ac.Repeat}static _GetSamplerWrappingDescriptor(e){return{addressModeU:this._GetWrappingMode(e._cachedWrapU),addressModeV:this._GetWrappingMode(e._cachedWrapV),addressModeW:this._GetWrappingMode(e._cachedWrapR)}}static _GetSamplerDescriptor(e){const t=e.useMipMaps&&e._cachedAnisotropicFilteringLevel&&e._cachedAnisotropicFilteringLevel>1?4:1,i=this._GetSamplerFilterDescriptor(e,t);return Object.assign(Object.assign(Object.assign({},i),this._GetSamplerWrappingDescriptor(e)),{compare:e._comparisonFunction?iu.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:i.anisotropyEnabled?t:1})}static GetCompareFunction(e){switch(e){case 519:return Ic.Always;case 514:return Ic.Equal;case 516:return Ic.Greater;case 518:return Ic.GreaterEqual;case 513:default:return Ic.Less;case 515:return Ic.LessEqual;case 512:return Ic.Never;case 517:return Ic.NotEqual}}getSampler(e,t=!1,i=0){if(this.disabled)return this._device.createSampler(iu._GetSamplerDescriptor(e));t?i=0:0===i&&(i=iu.GetSamplerHashCode(e));let n=t?void 0:this._samplers[i];return n||(n=this._device.createSampler(iu._GetSamplerDescriptor(e)),t||(this._samplers[i]=n)),n}}var nu;!function(e){e[e.StencilReadMask=0]="StencilReadMask",e[e.StencilWriteMask=1]="StencilWriteMask",e[e.DepthBias=2]="DepthBias",e[e.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",e[e.DepthStencilState=4]="DepthStencilState",e[e.MRTAttachments1=5]="MRTAttachments1",e[e.MRTAttachments2=6]="MRTAttachments2",e[e.RasterizationState=7]="RasterizationState",e[e.ColorStates=8]="ColorStates",e[e.ShaderStage=9]="ShaderStage",e[e.TextureStage=10]="TextureStage",e[e.VertexState=11]="VertexState",e[e.NumStates=12]="NumStates"}(nu||(nu={}));const su={0:1,1:2,768:3,769:4,770:5,771:6,772:7,773:8,774:9,775:10,776:11,32769:12,32770:13,32771:12,32772:13},ru={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7};class ou{constructor(e,t,i){this.mrtTextureCount=0,this._device=e,this._useTextureStage=i,this._states=new Array(30),this._statesLength=0,this._stateDirtyLowestIndex=0,this._emptyVertexBuffer=t,this._mrtFormats=[],this._parameter={token:void 0,pipeline:null},this.disabled=!1,this.vertexBuffers=[],this._kMaxVertexBufferStride=e.limits.maxVertexBufferArrayStride||2048,this.reset()}reset(){this._isDirty=!0,this.vertexBuffers.length=0,this.setAlphaToCoverage(!1),this.resetDepthCullingState(),this.setClampDepth(!1),this.setDepthBias(0),this._webgpuColorFormat=[yc.BGRA8Unorm],this.setColorFormat(yc.BGRA8Unorm),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat(yc.Depth24PlusStencil8),this.setStencilEnabled(!1),this.resetStencilState(),this.setBuffers(null,null,null),this._setTextureState(0)}get colorFormats(){return this._mrtAttachments1>0?this._mrtFormats:this._webgpuColorFormat}getRenderPipeline(e,t,i,n=0){if(i>1&&(i=4),this.disabled){const s=ou._GetTopology(e);return this._setVertexState(t),this._setTextureState(n),this._parameter.pipeline=this._createRenderPipeline(t,s,i),ou.NumCacheMiss++,ou._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(t.uniqueId),this._setRasterizationState(e,i),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(t),this._setTextureState(n),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,ou.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return ou.NumCacheHitWithHash++,this._parameter.pipeline;const s=ou._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,s,i),this._setRenderPipeline(this._parameter),ou.NumCacheMiss++,ou._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){ou.NumPipelineCreationLastFrame=ou._NumPipelineCreationCurrentFrame,ou._NumPipelineCreationCurrentFrame=0}setAlphaToCoverage(e){this._alphaToCoverageEnabled=e}setFrontFace(e){this._frontFace=e}setCullEnabled(e){this._cullEnabled=e}setCullFace(e){this._cullFace=e}setClampDepth(e){this._clampDepth=e}resetDepthCullingState(){this.setDepthCullingState(!1,2,1,0,0,!0,!0,519)}setDepthCullingState(e,t,i,n,s,r,o,a){this._depthWriteEnabled=o,this._depthTestEnabled=r,this._depthCompare=(null!=a?a:519)-512,this._cullFace=i,this._cullEnabled=e,this._frontFace=t,this.setDepthBiasSlopeScale(n),this.setDepthBias(s)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[nu.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,nu.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[nu.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,nu.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=Kd[null!=e?e:""]}setMRTAttachments(e){this.mrtAttachments=e;let t=0;for(let i=0;i10)throw"Can't handle more than 10 attachments for a MRT in cache render pipeline!";this.mrtTextureArray=e,this.mrtTextureCount=t,this._mrtEnabledMask=65535;const s=[0,0];let r=0,o=0,a=0;for(let l=0;l=32&&(o=0,r++)}this._mrtFormats.length=a,this._mrtAttachments1===s[0]&&this._mrtAttachments2===s[1]||(this._mrtAttachments1=s[0],this._mrtAttachments2=s[1],this._states[nu.MRTAttachments1]=s[0],this._states[nu.MRTAttachments2]=s[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,nu.MRTAttachments1))}setAlphaBlendEnabled(e){this._alphaBlendEnabled=e}setAlphaBlendFactors(e,t){this._alphaBlendFuncParams=e,this._alphaBlendEqParams=t}setWriteMask(e){this._writeMask=e}setDepthStencilFormat(e){this._webgpuDepthStencilFormat=e,this._depthStencilFormat=void 0===e?0:Kd[e]}setDepthTestEnabled(e){this._depthTestEnabled=e}setDepthWriteEnabled(e){this._depthWriteEnabled=e}setDepthCompare(e){this._depthCompare=(null!=e?e:519)-512}setStencilEnabled(e){this._stencilEnabled=e}setStencilCompare(e){this._stencilFrontCompare=(null!=e?e:519)-512}setStencilDepthFailOp(e){this._stencilFrontDepthFailOp=null===e?1:ru[e]}setStencilPassOp(e){this._stencilFrontPassOp=null===e?2:ru[e]}setStencilFailOp(e){this._stencilFrontFailOp=null===e?1:ru[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[nu.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,nu.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[nu.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,nu.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,n,s,r,o){this._stencilEnabled=e,this._stencilFrontCompare=(null!=t?t:519)-512,this._stencilFrontDepthFailOp=null===i?1:ru[i],this._stencilFrontPassOp=null===n?2:ru[n],this._stencilFrontFailOp=null===s?1:ru[s],this.setStencilReadMask(r),this.setStencilWriteMask(o)}setBuffers(e,t,i){this._vertexBuffers=e,this._overrideVertexBuffers=i,this._indexBuffer=t}static _GetTopology(e){switch(e){case 0:default:return Uc.TriangleList;case 2:case 3:return Uc.PointList;case 1:case 4:return Uc.LineList;case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return Uc.LineStrip;case 7:return Uc.TriangleStrip;case 8:throw"TriangleFan is an unsupported fillmode in WebGPU"}}static _GetAphaBlendOperation(e){switch(e){case 32774:default:return Wc.Add;case 32778:return Wc.Subtract;case 32779:return Wc.ReverseSubtract;case 32775:return Wc.Min;case 32776:return Wc.Max}}static _GetAphaBlendFactor(e){switch(e){case 0:return zc.Zero;case 1:default:return zc.One;case 768:return zc.Src;case 769:return zc.OneMinusSrc;case 770:return zc.SrcAlpha;case 771:return zc.OneMinusSrcAlpha;case 772:return zc.DstAlpha;case 773:return zc.OneMinusDstAlpha;case 774:return zc.Dst;case 775:return zc.OneMinusDst;case 776:return zc.SrcAlphaSaturated;case 32769:case 32771:return zc.Constant;case 32770:case 32772:return zc.OneMinusConstant}}static _GetCompareFunction(e){switch(e){case 0:return Ic.Never;case 1:return Ic.Less;case 2:return Ic.Equal;case 3:return Ic.LessEqual;case 4:return Ic.Greater;case 5:return Ic.NotEqual;case 6:return Ic.GreaterEqual;case 7:return Ic.Always}return Ic.Never}static _GetStencilOpFunction(e){switch(e){case 0:return Hc.Zero;case 1:return Hc.Keep;case 2:return Hc.Replace;case 3:return Hc.IncrementClamp;case 4:return Hc.DecrementClamp;case 5:return Hc.Invert;case 6:return Hc.IncrementWrap;case 7:return Hc.DecrementWrap}return Hc.Keep}static _GetVertexInputDescriptorFormat(e){const t=e.type,i=e.normalized,n=e.getSize();switch(t){case ne.o.BYTE:switch(n){case 1:case 2:return i?Yc.Snorm8x2:Yc.Sint8x2;case 3:case 4:return i?Yc.Snorm8x4:Yc.Sint8x4}break;case ne.o.UNSIGNED_BYTE:switch(n){case 1:case 2:return i?Yc.Unorm8x2:Yc.Uint8x2;case 3:case 4:return i?Yc.Unorm8x4:Yc.Uint8x4}break;case ne.o.SHORT:switch(n){case 1:case 2:return i?Yc.Snorm16x2:Yc.Sint16x2;case 3:case 4:return i?Yc.Snorm16x4:Yc.Sint16x4}break;case ne.o.UNSIGNED_SHORT:switch(n){case 1:case 2:return i?Yc.Unorm16x2:Yc.Uint16x2;case 3:case 4:return i?Yc.Unorm16x4:Yc.Uint16x4}break;case ne.o.INT:switch(n){case 1:return Yc.Sint32;case 2:return Yc.Sint32x2;case 3:return Yc.Sint32x3;case 4:return Yc.Sint32x4}break;case ne.o.UNSIGNED_INT:switch(n){case 1:return Yc.Uint32;case 2:return Yc.Uint32x2;case 3:return Yc.Uint32x3;case 4:return Yc.Uint32x4}break;case ne.o.FLOAT:switch(n){case 1:return Yc.Float32;case 2:return Yc.Float32x2;case 3:return Yc.Float32x3;case 4:return Yc.Float32x4}}throw new Error(`Invalid Format '${e.getKind()}' - type=${t}, normalized=${i}, size=${n}`)}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:ou._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:ou._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:ou._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:ou._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:ou._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:ou._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[nu.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,nu.ShaderStage))}_setRasterizationState(e,t){const i=this._frontFace-1+((this._cullEnabled?this._cullFace:0)<<1)+((this._clampDepth?1:0)<<3)+((this._alphaToCoverageEnabled?1:0)<<4)+(e<<5)+(t<<8);this._rasterizationState!==i&&(this._rasterizationState=i,this._states[nu.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,nu.RasterizationState))}_setColorStates(){let e=((this._writeMask?1:0)<<22)+(this._colorFormat<<23)+((this._depthWriteEnabled?1:0)<<29);this._alphaBlendEnabled&&(e+=((null===this._alphaBlendFuncParams[0]?2:su[this._alphaBlendFuncParams[0]])<<0)+((null===this._alphaBlendFuncParams[1]?2:su[this._alphaBlendFuncParams[1]])<<4)+((null===this._alphaBlendFuncParams[2]?2:su[this._alphaBlendFuncParams[2]])<<8)+((null===this._alphaBlendFuncParams[3]?2:su[this._alphaBlendFuncParams[3]])<<12)+((null===this._alphaBlendEqParams[0]?1:this._alphaBlendEqParams[0]-32773)<<16)+((null===this._alphaBlendEqParams[1]?1:this._alphaBlendEqParams[1]-32773)<<19)),e!==this._colorStates&&(this._colorStates=e,this._states[nu.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,nu.ColorStates))}_setDepthStencilState(){const e=this._stencilEnabled?this._stencilFrontCompare+(this._stencilFrontDepthFailOp<<3)+(this._stencilFrontPassOp<<6)+(this._stencilFrontFailOp<<9):591,t=this._depthStencilFormat+((this._depthTestEnabled?this._depthCompare:7)<<6)+(e<<10);this._depthStencilState!==t&&(this._depthStencilState=t,this._states[nu.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,nu.DepthStencilState))}_setVertexState(e){var t,i;const n=this._statesLength;let s=nu.VertexState;const r=e._pipelineContext,o=r.shaderProcessingContext.attributeNamesFromEffect,a=r.shaderProcessingContext.attributeLocationsFromEffect;let l,h=0;for(let c=0;c0)for(let _=0;_=this._video.HAVE_CURRENT_DATA}dispose(){}}class fu{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatTextures(){return this._numFloatTextures>0}constructor(){this.uniqueId=fu._Counter++,this.updateId=0,this.textureState=0,this.reset()}reset(){this.samplers={},this.textures={},this.isDirty=!0,this._numFloatTextures=0,this._numExternalTextures=0}setSampler(e,t){let i=this.samplers[e],n=-1;i?n=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?iu.GetSamplerHashCode(t):0;const s=n!==i.hashCode;s&&this.updateId++,this.isDirty||(this.isDirty=s)}setTexture(e,t){var i,n,s;let r=this.textures[e],o=-1;r?o=null!==(n=null===(i=r.texture)||void 0===i?void 0:i.uniqueId)&&void 0!==n?n:-1:this.textures[e]=r={texture:t,isFloatTexture:!1,isExternalTexture:!1},r.isExternalTexture&&this._numExternalTextures--,r.isFloatTexture&&this._numFloatTextures--,t?(r.isFloatTexture=1===t.type,r.isExternalTexture=pu.IsExternalTexture(t),r.isFloatTexture&&this._numFloatTextures++,r.isExternalTexture&&this._numExternalTextures++):(r.isFloatTexture=!1,r.isExternalTexture=!1),r.texture=t;const a=o!==(null!==(s=null==t?void 0:t.uniqueId)&&void 0!==s?s:-1);a&&this.updateId++,this.isDirty||(this.isDirty=a)}}fu._Counter=0;class _u{isDirty(e){return this._isDirty||this._materialContextUpdateId!==e}resetIsDirty(e){this._isDirty=!1,this._materialContextUpdateId=e}get useInstancing(){return this._useInstancing}set useInstancing(e){this._useInstancing!==e&&(e?(this.indirectDrawBuffer=this._bufferManager.createRawBuffer(20,Tc.CopyDst|Tc.Indirect|Tc.Storage),this._indirectDrawData=new Uint32Array(5),this._indirectDrawData[3]=0,this._indirectDrawData[4]=0):(this.indirectDrawBuffer&&this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this._useInstancing=e,this._currentInstanceCount=-1)}constructor(e){this._bufferManager=e,this.uniqueId=_u._Counter++,this._useInstancing=!1,this._currentInstanceCount=0,this.reset()}reset(){this.buffers={},this._isDirty=!0,this._materialContextUpdateId=0,this.fastBundle=void 0,this.bindGroups=void 0}setBuffer(e,t){var i;this._isDirty||(this._isDirty=(null==t?void 0:t.uniqueId)!==(null===(i=this.buffers[e])||void 0===i?void 0:i.uniqueId)),this.buffers[e]=t}setIndirectData(e,t,i){t!==this._currentInstanceCount&&this.indirectDrawBuffer&&this._indirectDrawData&&(this._currentInstanceCount=t,this._indirectDrawData[0]=e,this._indirectDrawData[1]=t,this._indirectDrawData[2]=i,this._bufferManager.setRawData(this.indirectDrawBuffer,0,this._indirectDrawData,0,20))}dispose(){this.indirectDrawBuffer&&(this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this.fastBundle=void 0,this.bindGroups=void 0,this.buffers=void 0}}_u._Counter=0;class mu{constructor(){this.values={}}}class gu{static get Statistics(){return{totalCreated:gu.NumBindGroupsCreatedTotal,lastFrameCreated:gu.NumBindGroupsCreatedLastFrame,lookupLastFrame:gu.NumBindGroupsLookupLastFrame,noLookupLastFrame:gu.NumBindGroupsNoLookupLastFrame}}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){gu.NumBindGroupsCreatedLastFrame=gu._NumBindGroupsCreatedCurrentFrame,gu.NumBindGroupsLookupLastFrame=gu._NumBindGroupsLookupCurrentFrame,gu.NumBindGroupsNoLookupLastFrame=gu._NumBindGroupsNoLookupCurrentFrame,gu._NumBindGroupsCreatedCurrentFrame=0,gu._NumBindGroupsLookupCurrentFrame=0,gu._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){var n,s,r,o,a,l,h,c,d,u;let f,_=gu._Cache;const m=this.disabled||i.forceBindGroupCreation;if(!m){if(!t.isDirty(i.updateId)&&!i.isDirty)return gu._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(const i of e.shaderProcessingContext.bufferNames){const e=null!==(s=null===(n=t.buffers[i])||void 0===n?void 0:n.uniqueId)&&void 0!==s?s:0;let r=_.values[e];r||(r=new mu,_.values[e]=r),_=r}for(const t of e.shaderProcessingContext.samplerNames){const e=null!==(o=null===(r=i.samplers[t])||void 0===r?void 0:r.hashCode)&&void 0!==o?o:0;let n=_.values[e];n||(n=new mu,_.values[e]=n),_=n}for(const t of e.shaderProcessingContext.textureNames){const e=null!==(h=null===(l=null===(a=i.textures[t])||void 0===a?void 0:a.texture)||void 0===l?void 0:l.uniqueId)&&void 0!==h?h:0;let n=_.values[e];n||(n=new mu,_.values[e]=n),_=n}f=_.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,f)return t.bindGroups=f,gu._NumBindGroupsLookupCurrentFrame++,f;f=[],t.bindGroups=f,m||(_.bindGroups=f),gu.NumBindGroupsCreatedTotal++,gu._NumBindGroupsCreatedCurrentFrame++;const g=e.bindGroupLayouts[i.textureState];for(let v=0;v"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}s[o].resource=this._cacheSampler.getSampler(t,!1,e.hashCode)}else p.Y.Error(`Sampler "${a}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.texture||n.storageTexture){const e=i.textures[a];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){p.Y.Error(`Trying to bind a null texture! entry=${JSON.stringify(n)}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const t=e.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!t||n.texture&&!t.view||n.storageTexture&&!t.viewForWriting)){p.Y.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(n)}, name=${a}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, isReady=${null===(d=e.texture)||void 0===d?void 0:d.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}s[o].resource=n.storageTexture?t.viewForWriting:t.view}else p.Y.Error(`Texture "${a}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.externalTexture){const e=i.textures[a];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){p.Y.Error(`Trying to bind a null external texture! entry=${JSON.stringify(n)}, name=${a}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, materialContext.uniqueId=${i.uniqueId}`,50);continue}const t=e.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!t){p.Y.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(n)}, name=${a}, bindingInfo=${JSON.stringify(e,((e,t)=>"texture"===e?"":t))}, isReady=${null===(u=e.texture)||void 0===u?void 0:u.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}s[o].resource=this._device.importExternalTexture({source:t})}else p.Y.Error(`Texture "${a}" could not be bound. entry=${JSON.stringify(n)}, materialContext=${JSON.stringify(i,((e,t)=>"texture"===e||"sampler"===e?"":t))}`,50)}else if(n.buffer){const e=t.buffers[a];if(e){const t=e.underlyingResource;s[o].resource.buffer=t,s[o].resource.size=e.capacity}else p.Y.Error(`Can't find buffer "${a}". entry=${JSON.stringify(n)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}const r=g[v];f[v]=this._device.createBindGroup({layout:r,entries:s})}return f}}gu.NumBindGroupsCreatedTotal=0,gu.NumBindGroupsCreatedLastFrame=0,gu.NumBindGroupsLookupLastFrame=0,gu.NumBindGroupsNoLookupLastFrame=0,gu._Cache=new mu,gu._NumBindGroupsCreatedCurrentFrame=0,gu._NumBindGroupsLookupCurrentFrame=0,gu._NumBindGroupsNoLookupCurrentFrame=0;const vu="clearQuadVertexShader",Tu="uniform float depthValue;\nconst vec2 pos[4]={\nvec2(-1.0,1.0),\nvec2(1.0,1.0),\nvec2(-1.0,-1.0),\nvec2(1.0,-1.0)\n};\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\ngl_Position=vec4(pos[gl_VertexID],depthValue,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}\n";Ht.v.ShadersStore[vu]=Tu;const Su="clearQuadPixelShader",Eu="uniform vec4 color;\nvoid main() {\ngl_FragColor=color;\n}\n";Ht.v.ShadersStore[Su]=Eu;class xu{setDepthStencilFormat(e){this._depthTextureFormat=e,this._cacheRenderPipeline.setDepthStencilFormat(e)}setColorFormat(e){this._cacheRenderPipeline.setColorFormat(e)}setMRTAttachments(e,t,i){this._cacheRenderPipeline.setMRT(t,i),this._cacheRenderPipeline.setMRTAttachments(e)}constructor(e,t,i){this._bindGroups={},this._bundleCache={},this._keyTemp=[],this._device=e,this._engine=t,this._cacheRenderPipeline=new lu(this._device,i,!t._caps.textureFloatLinearFiltering),this._cacheRenderPipeline.setDepthTestEnabled(!1),this._cacheRenderPipeline.setStencilReadMask(255),this._effect=t.createEffect("clearQuad",[],["color","depthValue"])}clear(e,t,i,n,s=1){var r,o;let a,l,h=null;const c=!!this._engine._currentRenderTarget;if(e)a=e;else{let e=0;this._keyTemp.length=0;for(let t=0;t1?2**36:0)+d*2**37,l=this._keyTemp.join("_"),h=this._bundleCache[l],h)return h;a=this._device.createRenderBundleEncoder({colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:s})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!n&&!!this._depthTextureFormat&&qd.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(n?255:0),this._cacheRenderPipeline.setStencilCompare(n?519:512),this._cacheRenderPipeline.setStencilPassOp(n?7681:7680),this._cacheRenderPipeline.setWriteMask(t?15:0);const d=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,s),u=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),u.uniformBuffer.update();const p=c?this._engine._ubInvertY:this._engine._ubDontInvertY,f=u.uniformBuffer.getBuffer(),_=f.uniqueId+"-"+p.uniqueId;let m=this._bindGroups[_];if(!m){const e=u.bindGroupLayouts[0];m=this._bindGroups[_]=[],m.push(this._device.createBindGroup({layout:e[0],entries:[]})),rd._SimplifiedKnownBindings||m.push(this._device.createBindGroup({layout:e[1],entries:[]})),m.push(this._device.createBindGroup({layout:e[rd._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:p.underlyingResource,size:p.capacity}},{binding:1,resource:{buffer:f.underlyingResource,size:f.capacity}}]}))}a.setPipeline(d);for(let g=0;g{null!==e&&e>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(e,!0)),this._measureDurationState=0})))}}class Nu{constructor(e,t){this._querySet=new Ou(2,Zc.Timestamp,e,t)}start(e){e.writeTimestamp(this._querySet.querySet,0)}async stop(e){return e.writeTimestamp(this._querySet.querySet,1),this._querySet.readTwoValuesAndSubtract(0)}dispose(){this._querySet.dispose()}}class Fu{get querySet(){return this._querySet.querySet}get hasQueries(){return this._currentTotalIndices!==this._availableIndices.length}get canBeginQuery(){switch(this._engine._getCurrentRenderPassIndex()){case 0:return void 0!==this._engine._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet;case 1:return void 0!==this._engine._rttRenderPassWrapper.renderPassDescriptor.occlusionQuerySet}return!1}constructor(e,t,i,n=50,s=100){this._availableIndices=[],this._engine=e,this._device=t,this._bufferManager=i,this._frameLastBuffer=-1,this._currentTotalIndices=0,this._countIncrement=s,this._allocateNewIndices(n)}createQuery(){0===this._availableIndices.length&&this._allocateNewIndices();const e=this._availableIndices[this._availableIndices.length-1];return this._availableIndices.length--,e}deleteQuery(e){this._availableIndices[this._availableIndices.length-1]=e}isQueryResultAvailable(e){return this._retrieveQueryBuffer(),!!this._lastBuffer&&e{this._lastBuffer=e})))}_allocateNewIndices(e){e=null!=e?e:this._countIncrement,this._delayQuerySetDispose();for(let t=0;te.dispose),1e3)}dispose(){var e;null===(e=this._querySet)||void 0===e||e.dispose(),this._availableIndices.length=0}}class wu{async initTwgsl(e){if(!wu._twgsl)return e=e||{},(e=Object.assign(Object.assign({},wu._TWgslDefaultOptions),e)).twgsl?(wu._twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&((0,_e.CG)()?await se.w1.LoadScriptAsync(e.jsPath):importScripts(e.jsPath)),self.twgsl?(wu._twgsl=await self.twgsl(e.wasmPath),Promise.resolve()):Promise.reject("twgsl is not available."))}convertSpirV2WGSL(e,t=!1){const i=wu._twgsl.convertSpirV2WGSL(e);return wu.ShowWGSLShaderCode&&(console.log(i),console.log("***********************************************")),wu.DisableUniformityAnalysis||t?"diagnostic(off, derivative_uniformity);\n"+i:i}}wu._TWgslDefaultOptions={jsPath:"https://preview.babylonjs.com/twgsl/twgsl.js",wasmPath:"https://preview.babylonjs.com/twgsl/twgsl.wasm"},wu.ShowWGSLShaderCode=!1,wu.DisableUniformityAnalysis=!1,wu._twgsl=null;class Lu{constructor(e,t,i,n){this._record=!1,this._play=!1,this._mainPassBundleList=[],this._enabled=!1,this._engine=e,this._mode=t,this._bundleList=i,this._bundleListRenderTarget=n}get enabled(){return this._enabled}get play(){return this._play}get record(){return this._record}set enabled(e){this._mainPassBundleList.length=0,this._record=this._enabled=e,this._play=!1,e&&(this._modeSaved=this._mode,this._mode=0)}get mode(){return this._mode}set mode(e){this._record?this._modeSaved=e:this._mode=e}endMainRenderPass(){this._record&&this._mainPassBundleList.push(this._bundleList.clone())}endRenderTargetPass(e,t){var i,n,s,r;if(this._play)null===(n=null===(i=t._bundleLists)||void 0===i?void 0:i[t._currentLayer])||void 0===n||n.run(e),1===this._mode&&this._engine._reportDrawCall(null===(r=null===(s=t._bundleLists)||void 0===s?void 0:s[t._currentLayer])||void 0===r?void 0:r.numDrawCalls);else{if(!this._record)return!1;t._bundleLists||(t._bundleLists=[]),t._bundleLists[t._currentLayer]=this._bundleListRenderTarget.clone(),t._bundleLists[t._currentLayer].run(e),this._bundleListRenderTarget.reset()}return!0}endFrame(e){if(this._record&&(this._mainPassBundleList.push(this._bundleList.clone()),this._record=!1,this._play=!0,this._mode=this._modeSaved),null!==e&&this._play)for(let t=0;t!!e),(()=>!1)).catch((()=>!1)):Promise.resolve(!1)}static get IsSupported(){return p.Y.Warn("You must call IsSupportedAsync for WebGPU!"),!1}get supportsUniformBuffers(){return!0}get supportedExtensions(){return this._adapterSupportedExtensions}get enabledExtensions(){return this._deviceEnabledExtensions}get supportedLimits(){return this._adapterSupportedLimits}get currentLimits(){return this._deviceLimits}get description(){return this.name+this.version}get version(){return 1}getInfo(){return{vendor:this._adapterInfo.vendor||"unknown vendor",renderer:this._adapterInfo.architecture||"unknown renderer",version:this._adapterInfo.description||"unknown version"}}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=e}get currentSampleCount(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount}static CreateAsync(e,t={}){const i=new zu(e,t);return new Promise((e=>{i.initAsync(t.glslangOptions,t.twgslOptions).then((()=>e(i)))}))}constructor(e,t={}){var i,n;super(null,null===(i=t.antialias)||void 0===i||i,t),this._uploadEncoderDescriptor={label:"upload"},this._renderEncoderDescriptor={label:"render"},this._renderTargetEncoderDescriptor={label:"renderTarget"},this._clearDepthValue=1,this._clearReverseDepthValue=0,this._clearStencilValue=0,this._defaultSampleCount=4,this._glslang=null,this._tintWASM=null,this._adapterInfo={vendor:"",architecture:"",device:"",description:""},this._compiledComputeEffects={},this._counters={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.countersLastFrame={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.numMaxUncapturedErrors=20,this._commandBuffers=[null,null,null],this._currentRenderPass=null,this._mainRenderPassWrapper=new Zd,this._rttRenderPassWrapper=new Zd,this._pendingDebugCommands=[],this._onAfterUnbindFrameBufferObservable=new r.y$,this._currentOverrideVertexBuffers=null,this._currentIndexBuffer=null,this._colorWriteLocal=!0,this._forceEnableEffect=!1,this.dbgShowShaderCode=!1,this.dbgSanityChecks=!0,this.dbgVerboseLogsForFirstFrames=!1,this.dbgVerboseLogsNumFrames=10,this.dbgLogIfNotDrawWrapper=!0,this.dbgShowEmptyEnableEffectCalls=!0,this.isNDCHalfZRange=!0,this.hasOriginBottomLeft=!1,this._viewportsCurrent=[{x:0,y:0,w:0,h:0},{x:0,y:0,w:0,h:0}],this._scissorsCurrent=[{x:0,y:0,w:0,h:0},{x:0,y:0,w:0,h:0}],this._scissorCached={x:0,y:0,z:0,w:0},this._stencilRefsCurrent=[-1,-1],this._blendColorsCurrent=[[null,null,null,null],[null,null,null,null]],this._name="WebGPU",t.deviceDescriptor=t.deviceDescriptor||{},t.enableGPUDebugMarkers=null!==(n=t.enableGPUDebugMarkers)&&void 0!==n&&n,p.Y.Log(`Babylon.js v${fe.D.Version} - ${this.description} engine`),navigator.gpu?(t.swapChainFormat=t.swapChainFormat||navigator.gpu.getPreferredCanvasFormat(),this._isWebGPU=!0,this._shaderPlatformName="WEBGPU",this._renderingCanvas=e,this._options=t,this._mainPassSampleCount=t.antialias?this._defaultSampleCount:1,this._setupMobileChecks(),this._sharedInit(e),this._shaderProcessor=new od,this._shaderProcessorWGSL=new Gd):p.Y.Error("WebGPU is not supported by your browser.")}initAsync(e,t){var i;return this._initGlslang(null!=e?e:null===(i=this._options)||void 0===i?void 0:i.glslangOptions).then((e=>{var i;return this._glslang=e,this._tintWASM=zu.UseTWGSL?new wu:null,this._tintWASM?this._tintWASM.initTwgsl(null!=t?t:null===(i=this._options)||void 0===i?void 0:i.twgslOptions).then((()=>navigator.gpu.requestAdapter(this._options)),(e=>{throw p.Y.Error("Can not initialize twgsl!"),p.Y.Error(e),Error("WebGPU initializations stopped.")})):navigator.gpu.requestAdapter(this._options)}),(e=>{throw p.Y.Error("Can not initialize glslang!"),p.Y.Error(e),Error("WebGPU initializations stopped.")})).then((e=>{var t,i,n;if(e){this._adapter=e,this._adapterSupportedExtensions=[],null===(t=this._adapter.features)||void 0===t||t.forEach((e=>this._adapterSupportedExtensions.push(e))),this._adapterSupportedLimits=this._adapter.limits,this._adapter.requestAdapterInfo().then((e=>{this._adapterInfo=e}));const s=null!==(i=this._options.deviceDescriptor)&&void 0!==i?i:{},r=null!==(n=null==s?void 0:s.requiredFeatures)&&void 0!==n?n:this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0;if(r){const e=r,t=[];for(const i of e)-1!==this._adapterSupportedExtensions.indexOf(i)&&t.push(i);s.requiredFeatures=t}if(this._options.setMaximumLimits&&!s.requiredLimits){s.requiredLimits={};for(const e in this._adapterSupportedLimits)s.requiredLimits[e]=this._adapterSupportedLimits[e]}return this._adapter.requestDevice(s)}throw"Could not retrieve a WebGPU adapter (adapter is null)."})).then((e=>{var t,i;this._device=e,this._deviceEnabledExtensions=[],null===(t=this._device.features)||void 0===t||t.forEach((e=>this._deviceEnabledExtensions.push(e))),this._deviceLimits=e.limits;let n=-1;this._device.addEventListener("uncapturederror",(e=>{++n{this._isDisposed||(this._contextWasLost=!0,p.Y.Warn("WebGPU context lost. "+e),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost(this.initAsync.bind(this)))}))}),(e=>{p.Y.Error("Could not retrieve a WebGPU device."),p.Y.Error(e)})).then((()=>{this._bufferManager=new Qd(this._device),this._textureHelper=new qd(this._device,this._glslang,this._tintWASM,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new iu(this._device),this._cacheBindGroups=new gu(this._device,this._cacheSampler,this),this._timestampQuery=new Du(this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new Fu(this,this._device,this._bufferManager):void 0,this._bundleList=new Mu(this._device),this._bundleListRenderTarget=new Mu(this._device),this._snapshotRendering=new Lu(this,this._snapshotRenderingMode,this._bundleList,this._bundleListRenderTarget),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),Tc.Uniform|Tc.CopyDst),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),Tc.Uniform|Tc.CopyDst),this.dbgVerboseLogsForFirstFrames&&void 0===this._count&&(this._count=0,console.log("%c frame #"+this._count+" - begin","background: #ffff00")),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._renderTargetEncoder=this._device.createCommandEncoder(this._renderTargetEncoderDescriptor),this._emptyVertexBuffer=new ne.o(this,[0],"",!1,!1,1,!1,0,1),this._initializeLimits(),this._cacheRenderPipeline=new lu(this._device,this._emptyVertexBuffer,!this._caps.textureFloatLinearFiltering),this._depthCullingState=new uu(this._cacheRenderPipeline),this._stencilStateComposer=new cu(this._cacheRenderPipeline),this._stencilStateComposer.stencilGlobal=this._stencilState,this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=515,this._depthCullingState.depthMask=!0,this._textureHelper.setCommandEncoder(this._uploadEncoder),this._clearQuad=new xu(this._device,this,this._emptyVertexBuffer),this._defaultDrawContext=this.createDrawContext(),this._currentDrawContext=this._defaultDrawContext,this._defaultMaterialContext=this.createMaterialContext(),this._currentMaterialContext=this._defaultMaterialContext,this._initializeContextAndSwapChain(),this._initializeMainAttachments(),this.resize()})).catch((e=>{p.Y.Error("Can not create WebGPU Device and/or context."),p.Y.Error(e),console.trace&&console.trace()}))}_initGlslang(e){return e=e||{},(e=Object.assign(Object.assign({},zu._GLSLslangDefaultOptions),e)).glslang?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?(0,_e.CG)()?se.w1.LoadScriptAsync(e.jsPath).then((()=>self.glslang(e.wasmPath))):(importScripts(e.jsPath),self.glslang(e.wasmPath)):Promise.reject("gslang is not available.")}_initializeLimits(){this._caps={maxTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxVertexTextureImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxCombinedTexturesImageUnits:2*this._deviceLimits.maxSampledTexturesPerShaderStage,maxTextureSize:this._deviceLimits.maxTextureDimension2D,maxCubemapTextureSize:this._deviceLimits.maxTextureDimension2D,maxRenderTextureSize:this._deviceLimits.maxTextureDimension2D,maxVertexAttribs:this._deviceLimits.maxVertexAttributes,maxVaryingVectors:this._deviceLimits.maxInterStageShaderVariables,maxFragmentUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),maxVertexUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),standardDerivatives:!0,astc:this._deviceEnabledExtensions.indexOf(gc.TextureCompressionASTC)>=0||void 0,s3tc:this._deviceEnabledExtensions.indexOf(gc.TextureCompressionBC)>=0||void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf(gc.TextureCompressionETC2)>=0||void 0,bptc:this._deviceEnabledExtensions.indexOf(gc.TextureCompressionBC)>=0||void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf(gc.Float32Filterable)>=0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!0,drawBuffersExtension:!0,depthTextureExtension:!0,vertexArrayObject:!1,instancedArrays:!0,timerQuery:"undefined"!=typeof BigUint64Array&&-1!==this._deviceEnabledExtensions.indexOf(gc.TimestampQuery)||void 0,supportOcclusionQuery:"undefined"!=typeof BigUint64Array,canUseTimestampForTimerQuery:!0,multiview:!1,oculusMultiview:!1,parallelShaderCompile:void 0,blendMinMax:!0,maxMSAASamples:4,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!0,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!0,texture2DArrayMaxLayerCount:this._deviceLimits.maxTextureArrayLayers,disableMorphTargetTexture:!1},this._caps.parallelShaderCompile=null,this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!0,supportDepthStencilTexture:!0,supportShadowSamplers:!0,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!0,trackUbosInFrame:!0,checkUbosContentBeforeUpload:!0,supportCSM:!0,basisNeedsPOT:!1,support3DTextures:!0,needTypeSuffixInShaderConstants:!0,supportMSAA:!0,supportSSAO2:!0,supportExtendedTextureFormats:!0,supportSwitchCaseInShader:!0,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!0,supportRenderPasses:!0,supportSpriteInstancing:!0,_collectUbosUpdatedInFrame:!1}}_initializeContextAndSwapChain(){if(!this._renderingCanvas)throw"The rendering canvas has not been set!";this._context=this._renderingCanvas.getContext("webgpu"),this._configureContext(),this._colorFormat=this._options.swapChainFormat,this._mainRenderPassWrapper.colorAttachmentGPUTextures=[new zd],this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format=this._colorFormat}_initializeMainAttachments(){if(!this._bufferManager)return;this.flushFramebuffer(!1),this._mainTextureExtends={width:this.getRenderWidth(!0),height:this.getRenderHeight(!0),depthOrArrayLayers:1};const e=new Float32Array([this.getRenderHeight(!0)]);let t;if(this._bufferManager.setSubData(this._ubInvertY,4,e),this._bufferManager.setSubData(this._ubDontInvertY,4,e),this._options.antialias){const e={label:`Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:Ec.E2d,format:this._options.swapChainFormat,usage:xc.RenderAttachment};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(e),t=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:Ec.E2d,format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new a.HE(0,0,0,1),loadOp:$c.Clear,storeOp:Qc.Store}]}else t=[{view:void 0,clearValue:new a.HE(0,0,0,1),loadOp:$c.Clear,storeOp:Qc.Store}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?yc.Depth24PlusStencil8:yc.Depth32Float,this._setDepthTextureFormat(this._mainRenderPassWrapper);const i={label:`Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:Ec.E2d,format:this._mainRenderPassWrapper.depthTextureFormat,usage:xc.RenderAttachment};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(i);const n={view:this._depthTexture.createView({label:`TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,dimension:Ec.E2d,format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:$c.Clear,depthStoreOp:Qc.Store,stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?$c.Clear:void 0,stencilStoreOp:this.isStencilEnable?Qc.Store:void 0};this._mainRenderPassWrapper.renderPassDescriptor={colorAttachments:t,depthStencilAttachment:n}}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:xc.RenderAttachment|xc.CopySrc,alphaMode:this.premultipliedAlpha?Jc.Premultiplied:Jc.Opaque})}setSize(e,t,i=!1){return!!super.setSize(e,t,i)&&(this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count=0,s=t.indexOf(Gu)>=0,r=i===Qt.x.GLSL?this._compileRawShaderToSpirV(e,"vertex"):e,o=i===Qt.x.GLSL?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(r,o,i,n,s)}_compilePipelineStageDescriptor(e,t,i,n){this.onBeforeShaderCompilationObservable.notifyObservers(this);const s=e.indexOf(Gu)>=0,r=t.indexOf(Gu)>=0,o="#version 450\n",a=n===Qt.x.GLSL?this._compileShaderToSpirV(e,"vertex",i,o):this._getWGSLShader(e,"vertex",i),l=n===Qt.x.GLSL?this._compileShaderToSpirV(t,"fragment",i,o):this._getWGSLShader(t,"fragment",i),h=this._createPipelineStageDescriptor(a,l,n,s,r);return this.onAfterShaderCompilationObservable.notifyObservers(this),h}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){const t=new oc(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new nd(e,this)}createMaterialContext(){return new fu}createDrawContext(){return new _u(this._bufferManager)}_preparePipelineContext(e,t,i,n,s,r,o,a){const l=e,h=l.shaderProcessingContext.shaderLanguage;this.dbgShowShaderCode&&(console.log(a),console.log(t),console.log(i),console.log("***********************************************")),l.sources={fragment:i,vertex:t,rawVertex:s,rawFragment:r},l.stages=n?this._compileRawPipelineStageDescriptor(t,i,h):this._compilePipelineStageDescriptor(t,i,a,h)}getAttributes(e,t){const i=new Array(t.length),n=e;for(let s=0;s0,l._cachedWrapU=0,l._cachedWrapV=0,l._useSRGBBuffer=a.useSRGBBuffer,l.label=a.label,this._internalTexturesCache.push(l),i||this._textureHelper.createGPUTextureForInternalTexture(l,h,c,d||1,a.creationFlags),l}createTexture(e,t,i,n,s=3,r=null,o=null,a=null,l=null,h=null,c=null,d,u,p,f){return this._createTextureBase(e,t,i,n,s,r,o,((e,t,i,n,s,r,o,a)=>{var l;const c=n;if(e.baseWidth=c.width,e.baseHeight=c.height,e.width=c.width,e.height=c.height,e.format=null!=h?h:-1,a(e.width,e.height,c,t,e,(()=>{})),null===(l=e._hardwareTexture)||void 0===l?void 0:l.underlyingResource)r||o||this._generateMipmaps(e,this._uploadEncoder);else{const t=this._textureHelper.createGPUTextureForInternalTexture(e,c.width,c.height,void 0,p);qd.IsImageBitmap(c)&&(this._textureHelper.updateTexture(c,e,c.width,c.height,e.depth,t.format,0,0,s,!1,0,0),r||o||this._generateMipmaps(e,this._uploadEncoder))}i&&i.removePendingData(e),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}),(()=>!1),a,l,h,c,d,u,f)}wrapWebGPUTexture(e){const t=new zd(e),i=new Be.l(this,Be.S.Unknown,!0);return i._hardwareTexture=t,i.isReady=!0,i}wrapWebGLTexture(){throw new Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.")}generateMipMapsForCubemap(e){var t;if(e.generateMipMaps){(null===(t=e._hardwareTexture)||void 0===t?void 0:t.underlyingResource)||this._textureHelper.createGPUTextureForInternalTexture(e),this._generateMipmaps(e,e.source===Be.S.RenderTarget||e.source===Be.S.MultiRenderTarget?this._renderTargetEncoder:void 0)}}updateTextureSamplingMode(e,t,i=!1){i&&(t.generateMipMaps=!0,this._generateMipmaps(t)),t.samplingMode=e}updateTextureWrappingMode(e,t,i=null,n=null){null!==t&&(e._cachedWrapU=t),null!==i&&(e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==n&&(e._cachedWrapR=n)}updateTextureDimensions(e,t,i,n=1){if(!e._hardwareTexture)return;if(e.width===t&&e.height===i&&e.depth===n)return;const s=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,n,s)}_setInternalTexture(e,t,i){if(i=null!=i?i:e,this._currentEffect){const n=this._currentEffect._pipelineContext.shaderProcessingContext.availableTextures[i];if(this._currentMaterialContext.setTexture(e,t),n&&n.autoBindSampler){const e=i+id.AutoSamplerSuffix;this._currentMaterialContext.setSampler(e,t)}}}setTexture(e,t,i,n){this._setTexture(e,i,!1,!1,n,n)}setTextureArray(e,t,i,n){for(let s=0;s0;for(const t in e){const s=e[t],r=i[t],o=r.group,a=r.binding,l=s.type,h=s.object;let c=s.indexInGroupEntries,d=this._bindGroupEntries[o];switch(d||(d=this._bindGroupEntries[o]=[]),l){case Qa.Sampler:{const e=h;void 0!==c&&n?d[c].resource=this._cacheSampler.getSampler(e):(s.indexInGroupEntries=d.length,d.push({binding:a,resource:this._cacheSampler.getSampler(e)}));break}case Qa.Texture:case Qa.TextureWithoutSampler:{const e=h,t=e._texture._hardwareTexture;void 0!==c&&n?(l===Qa.Texture&&(d[c++].resource=this._cacheSampler.getSampler(e._texture)),d[c].resource=t.view):(s.indexInGroupEntries=d.length,l===Qa.Texture&&d.push({binding:a-1,resource:this._cacheSampler.getSampler(e._texture)}),d.push({binding:a,resource:t.view}));break}case Qa.StorageTexture:{const e=h,t=e._texture._hardwareTexture;0==(t.textureAdditionalUsages&xc.StorageBinding)&&p.Y.Error(`computeDispatch: The texture (name=${e.name}, uniqueId=${e.uniqueId}) is not a storage texture!`,50),void 0!==c&&n?d[c].resource=t.viewForWriting:(s.indexInGroupEntries=d.length,d.push({binding:a,resource:t.viewForWriting}));break}case Qa.UniformBuffer:case Qa.StorageBuffer:{const e=(Qa.UniformBuffer,h).getBuffer(),t=e.underlyingResource;void 0!==c&&n?(d[c].resource.buffer=t,d[c].resource.size=e.capacity):(s.indexInGroupEntries=d.length,d.push({binding:a,resource:{buffer:t,offset:0,size:e.capacity}}));break}}}for(let e=0;e{this.computeDispatch(e,t,i,n,s,r,o)}));const a=e._pipelineContext,l=t;a.computePipeline||(a.computePipeline=this._device.createComputePipeline({layout:Bc.Auto,compute:a.stage}));const h=this._renderTargetEncoder.beginComputePass();h.setPipeline(a.computePipeline);const c=l.getBindGroups(i,a.computePipeline,o);for(let d=0;d{const i=t,r=i[0].width,a=r;this._setCubeMapTextureParams(e,!n),e.format=null!=o?o:-1;const l=this._textureHelper.createGPUTextureForInternalTexture(e,r,a);this._textureHelper.updateCubeTextures(i,l.underlyingResource,r,a,l.format,!1,!1,0,0),n||this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),s&&s()}),!!u)},zu.prototype._setCubeMapTextureParams=function(e,t,i){e.samplingMode=t?3:2,e._cachedWrapU=0,e._cachedWrapV=0,i&&(e._maxLodLevel=i)},zu.prototype._debugPushGroup=function(e,t){if(this._options.enableGPUDebugMarkers)if(0===t||1===t){(0===t?this._renderEncoder:this._renderTargetEncoder).pushDebugGroup(e)}else this._currentRenderPass?this._currentRenderPass.pushDebugGroup(e):this._pendingDebugCommands.push(["push",e])},zu.prototype._debugPopGroup=function(e){if(this._options.enableGPUDebugMarkers)if(0===e||1===e){(0===e?this._renderEncoder:this._renderTargetEncoder).popDebugGroup()}else this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null])},zu.prototype._debugInsertMarker=function(e,t){if(this._options.enableGPUDebugMarkers)if(0===t||1===t){(0===t?this._renderEncoder:this._renderTargetEncoder).insertDebugMarker(e)}else this._currentRenderPass?this._currentRenderPass.insertDebugMarker(e):this._pendingDebugCommands.push(["insert",e])},zu.prototype._debugFlushPendingCommands=function(){for(let e=0;e{const i=u.width,r=o(e);if(!r)return;const h=[0,2,4,1,3,5];if(a){const e=4===n,t=a(r),o=u._hardwareTexture,l=[0,1,2,3,4,5];for(let n=0;n>n,a=[];for(let i=0;i<6;i++){let o=t[n][l[i]];e&&(o=Yu(o,r,r,s)),a.push(new Uint8Array(o.buffer,o.byteOffset,o.byteLength))}this._textureHelper.updateCubeTextures(a,o.underlyingResource,r,r,o.format,d,!1,0,0)}}else{const e=[];for(let t=0;t<6;t++)e.push(r[h[t]]);this.updateRawCubeTexture(u,e,n,s,d)}u.isReady=!0,null==t||t.removePendingData(u),l&&l()};return this._loadFile(e,(e=>{p(e)}),void 0,null==t?void 0:t.offlineProvider,!0,((e,i)=>{null==t||t.removePendingData(u),h&&e&&h(e.status+" "+e.statusText,i)})),u},zu.prototype.createRawTexture3D=function(e,t,i,n,s,r,o,a,l=null,h=0,c=0){const d=Be.S.Raw3D,u=new Be.l(this,d);return u.baseWidth=t,u.baseHeight=i,u.baseDepth=n,u.width=t,u.height=i,u.depth=n,u.format=s,u.type=h,u.generateMipMaps=r,u.samplingMode=a,u.is3D=!0,this._doNotHandleContextLost||(u._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(u,t,i,void 0,c),this.updateRawTexture3D(u,e,s,o,l,h),this._internalTexturesCache.push(u),u},zu.prototype.updateRawTexture3D=function(e,t,i,n,s=null,r=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=n,e._compression=s),t){const s=e._hardwareTexture;4===i&&(t=Yu(t,e.width,e.height,r));const o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,s.format,0,0,n,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},zu.prototype.createRawTexture2DArray=function(e,t,i,n,s,r,o,a,l=null,h=0,c=0){const d=Be.S.Raw2DArray,u=new Be.l(this,d);return u.baseWidth=t,u.baseHeight=i,u.baseDepth=n,u.width=t,u.height=i,u.depth=n,u.format=s,u.type=h,u.generateMipMaps=r,u.samplingMode=a,u.is2DArray=!0,this._doNotHandleContextLost||(u._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(u,t,i,n,c),this.updateRawTexture2DArray(u,e,s,o,l,h),this._internalTexturesCache.push(u),u},zu.prototype.updateRawTexture2DArray=function(e,t,i,n,s=null,r=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=n,e._compression=s),t){const s=e._hardwareTexture;4===i&&(t=Yu(t,e.width,e.height,r));const o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,s.format,0,0,n,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},zu.prototype._readTexturePixels=function(e,t,i,n=-1,s=0,r=null,o=!0,a=!1,l=0,h=0){const c=e._hardwareTexture;return o&&this.flushFramebuffer(),this._textureHelper.readPixels(c.underlyingResource,l,h,t,i,c.format,n,s,r,a)},zu.prototype._readTexturePixelsSync=function(){throw"_readTexturePixelsSync is unsupported in WebGPU!"};class ju extends jt{}zu.prototype._createHardwareRenderTargetWrapper=function(e,t,i){const n=new ju(e,t,i,this);return this._renderTargetWrapperCache.push(n),n},zu.prototype.createRenderTargetTexture=function(e,t){var i,n;const s=this._createHardwareRenderTargetWrapper(!1,!1,e),r={};void 0!==t&&"object"==typeof t?(r.generateMipMaps=t.generateMipMaps,r.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,r.generateStencilBuffer=r.generateDepthBuffer&&t.generateStencilBuffer,r.samplingMode=void 0===t.samplingMode?3:t.samplingMode,r.creationFlags=null!==(i=t.creationFlags)&&void 0!==i?i:0,r.noColorAttachment=!!t.noColorAttachment,r.samples=t.samples,r.label=t.label):(r.generateMipMaps=t,r.generateDepthBuffer=!0,r.generateStencilBuffer=!1,r.samplingMode=3,r.creationFlags=0,r.noColorAttachment=!1);const o=r.noColorAttachment?null:this._createInternalTexture(e,t,!0,Be.S.RenderTarget);return s._samples=null!==(n=r.samples)&&void 0!==n?n:1,s._generateDepthBuffer=r.generateDepthBuffer,s._generateStencilBuffer=!!r.generateStencilBuffer,s.setTextures(o),(s._generateDepthBuffer||s._generateStencilBuffer)&&s.createDepthStencilTexture(0,this._caps.textureFloatLinearFiltering&&(void 0===r.samplingMode||2===r.samplingMode||2===r.samplingMode||3===r.samplingMode||3===r.samplingMode||5===r.samplingMode||6===r.samplingMode||7===r.samplingMode||11===r.samplingMode),s._generateStencilBuffer,s.samples,r.generateStencilBuffer?13:14,r.label?r.label+"-DepthStencil":void 0),o&&(void 0!==t&&"object"==typeof t&&t.createMipMaps&&!r.generateMipMaps&&(o.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(o,void 0,void 0,void 0,r.creationFlags),void 0!==t&&"object"==typeof t&&t.createMipMaps&&!r.generateMipMaps&&(o.generateMipMaps=!1)),s},zu.prototype._createDepthStencilTexture=function(e,t){const i=new Be.l(this,Be.S.DepthStencil);i.label=t.label;const n=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?13:14},t);return i.format=n.depthTextureFormat,this._setupDepthStencilTexture(i,e,n.generateStencil,n.bilinearFiltering,n.comparisonFunction,n.samples),this._textureHelper.createGPUTextureForInternalTexture(i),this._internalTexturesCache.push(i),i},zu.prototype._setupDepthStencilTexture=function(e,t,i,n,s,r=1){const o=t.width||t,a=t.height||t,l=t.layers||0;e.baseWidth=o,e.baseHeight=a,e.width=o,e.height=a,e.is2DArray=l>0,e.depth=l,e.isReady=!0,e.samples=r,e.generateMipMaps=!1,e.samplingMode=n?2:1,e.type=1,e._comparisonFunction=s,e._cachedWrapU=0,e._cachedWrapV=0},zu.prototype.updateRenderTargetTextureSampleCount=function(e,t){return e&&e.texture&&e.samples!==t?(t=Math.min(t,this.getCaps().maxMSAASamples),this._textureHelper.createMSAATexture(e.texture,t),e._depthStencilTexture&&(this._textureHelper.createMSAATexture(e._depthStencilTexture,t),e._depthStencilTexture.samples=t),e._samples=t,e.texture.samples=t,t):t},zu.prototype.createRenderTargetCubeTexture=function(e,t){const i=this._createHardwareRenderTargetWrapper(!1,!0,e),n=Object.assign({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1},t);n.generateStencilBuffer=n.generateDepthBuffer&&n.generateStencilBuffer,i._generateDepthBuffer=n.generateDepthBuffer,i._generateStencilBuffer=n.generateStencilBuffer;const s=new Be.l(this,Be.S.RenderTarget);return s.width=e,s.height=e,s.depth=0,s.isReady=!0,s.isCube=!0,s.samples=n.samples,s.generateMipMaps=n.generateMipMaps,s.samplingMode=n.samplingMode,s.type=n.type,s.format=n.format,this._internalTexturesCache.push(s),i.setTextures(s),(i._generateDepthBuffer||i._generateStencilBuffer)&&i.createDepthStencilTexture(0,void 0===n.samplingMode||2===n.samplingMode||2===n.samplingMode||3===n.samplingMode||3===n.samplingMode||5===n.samplingMode||6===n.samplingMode||7===n.samplingMode||11===n.samplingMode,i._generateStencilBuffer,i.samples),t&&t.createMipMaps&&!n.generateMipMaps&&(s.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(s),t&&t.createMipMaps&&!n.generateMipMaps&&(s.generateMipMaps=!1),i},ft.Q.prototype.setTextureSampler=function(e,t){this._engine.setTextureSampler(e,t)},zu.prototype.setTextureSampler=function(e,t){var i;null===(i=this._currentMaterialContext)||void 0===i||i.setSampler(e,t)},ft.Q.prototype.setStorageBuffer=function(e,t){this._engine.setStorageBuffer(e,t)},zu.prototype.createStorageBuffer=function(e,t){return this._createBuffer(e,32|t)},zu.prototype.updateStorageBuffer=function(e,t,i,n){const s=e;let r;void 0===i&&(i=0),void 0===n?(r=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,n=r.byteLength):r=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,this._bufferManager.setSubData(s,i,r,0,n)},zu.prototype.readFromStorageBuffer=function(e,t,i,n){i=i||e.capacity;const s=this._bufferManager.createRawBuffer(i,Tc.MapRead|Tc.CopyDst);return this._renderTargetEncoder.copyBufferToBuffer(e.underlyingResource,null!=t?t:0,s,0,i),new Promise(((e,t)=>{this.onEndFrameObservable.addOnce((()=>{s.mapAsync(Sc.Read,0,i).then((()=>{const t=s.getMappedRange(0,i);let r=n;if(void 0===r)r=new Uint8Array(i),r.set(new Uint8Array(t));else{const e=r.constructor;r=new e(r.buffer),r.set(new e(t))}s.unmap(),this._bufferManager.releaseBuffer(s),e(r)}),(e=>t(e)))}))}))},zu.prototype.setStorageBuffer=function(e,t){var i,n;null===(i=this._currentDrawContext)||void 0===i||i.setBuffer(e,null!==(n=null==t?void 0:t.getBuffer())&&void 0!==n?n:null)},zu.prototype.createUniformBuffer=function(e){let t;t=e instanceof Array?new Float32Array(e):e;return this._bufferManager.createBuffer(t,Tc.Uniform|Tc.CopyDst)},zu.prototype.createDynamicUniformBuffer=function(e){return this.createUniformBuffer(e)},zu.prototype.updateUniformBuffer=function(e,t,i,n){void 0===i&&(i=0);const s=e;let r;void 0===n?(r=t instanceof Float32Array?t:new Float32Array(t),n=r.byteLength):r=t instanceof Float32Array?t:new Float32Array(t),this._bufferManager.setSubData(s,i,r,0,n)},zu.prototype.bindUniformBufferBase=function(e,t,i){this._currentDrawContext.setBuffer(i,e)},zu.prototype.bindUniformBlock=function(){},zu.prototype.updateVideoTexture=function(e,t,i){var n;if(!e||e._isDisabled)return;void 0===this._videoTextureSupported&&(this._videoTextureSupported=!0);let s=e._hardwareTexture;(null===(n=e._hardwareTexture)||void 0===n?void 0:n.underlyingResource)||(s=this._textureHelper.createGPUTextureForInternalTexture(e)),!function(e){return!(!e||void 0===e.underlyingResource)}(t)?t&&this.createImageBitmap(t).then((t=>{this._textureHelper.updateTexture(t,e,e.width,e.height,e.depth,s.format,0,0,!i,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0})).catch((()=>{e.isReady=!0})):(this._textureHelper.copyVideoToTexture(t,e,s.format,!i),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0)};i(1917);class Ku{}Ku.COPY=1,Ku.CUT=2,Ku.PASTE=3;class qu extends Fs{constructor(e){super(e),this.controllerType=yn.DAYDREAM}initControllerMesh(e,t){ht.ImportMesh("",qu.MODEL_BASE_URL,qu.MODEL_FILENAME,e,(e=>{this._defaultModel=e[1],this.attachToMesh(this._defaultModel),t&&t(this._defaultModel)}))}_handleButtonChange(e,t){if(0===e){const e=this.onTriggerStateChangedObservable;e&&e.notifyObservers(t)}else p.Y.Warn(`Unrecognized Daydream button index: ${e}`)}}qu.MODEL_BASE_URL="https://controllers.babylonjs.com/generic/",qu.MODEL_FILENAME="generic.babylon",qu.GAMEPAD_ID_PREFIX="Daydream",Wn._ControllerFactories.push({canCreate:e=>0===e.id.indexOf(qu.GAMEPAD_ID_PREFIX),create:e=>new qu(e)});class $u extends Fs{constructor(e){super(e),this._buttonIndexToObservableNameMap=["onPadStateChangedObservable","onTriggerStateChangedObservable"],this.controllerType=yn.GEAR_VR,this._calculatedPosition=new o.P("left"==this.hand?-.15:.15,-.5,.25),this._disableTrackPosition(this._calculatedPosition)}initControllerMesh(e,t){ht.ImportMesh("",$u.MODEL_BASE_URL,$u.MODEL_FILENAME,e,(i=>{const n=new ee.Kj("",e);i[1].parent=n,i[1].position.z=-.15,this._defaultModel=n,this.attachToMesh(this._defaultModel),t&&t(this._defaultModel)}))}_handleButtonChange(e,t){if(e0===e.id.indexOf($u.GAMEPAD_ID_PREFIX)||-1!==e.id.indexOf("Oculus Go")||-1!==e.id.indexOf("Vive Focus"),create:e=>new $u(e)});class Qu extends Fs{constructor(e){super(e)}initControllerMesh(e,t){ht.ImportMesh("",Qu.MODEL_BASE_URL,Qu.MODEL_FILENAME,e,(e=>{this._defaultModel=e[1],this.attachToMesh(this._defaultModel),t&&t(this._defaultModel)}))}_handleButtonChange(e,t){console.log("Button id: "+e+"state: "),console.dir(t)}}Qu.MODEL_BASE_URL="https://controllers.babylonjs.com/generic/",Qu.MODEL_FILENAME="generic.babylon",Wn._DefaultControllerFactory=e=>new Qu(e);class Zu extends Fs{constructor(e){super(e),this.onSecondaryTriggerStateChangedObservable=new r.y$,this.onThumbRestChangedObservable=new r.y$,this.controllerType=yn.OCULUS}initControllerMesh(e,t){let i;i="left"===this.hand?Zu.MODEL_LEFT_FILENAME:Zu.MODEL_RIGHT_FILENAME,ht.ImportMesh("",Zu._IsQuest?Zu.QUEST_MODEL_BASE_URL:Zu.MODEL_BASE_URL,i,e,(e=>{this._defaultModel=Zu._IsQuest?e[0]:e[1],this.attachToMesh(this._defaultModel),t&&t(this._defaultModel)}))}get onAButtonStateChangedObservable(){if("right"===this.hand)return this.onMainButtonStateChangedObservable;throw new Error("No A button on left hand")}get onBButtonStateChangedObservable(){if("right"===this.hand)return this.onSecondaryButtonStateChangedObservable;throw new Error("No B button on left hand")}get onXButtonStateChangedObservable(){if("left"===this.hand)return this.onMainButtonStateChangedObservable;throw new Error("No X button on right hand")}get onYButtonStateChangedObservable(){if("left"===this.hand)return this.onSecondaryButtonStateChangedObservable;throw new Error("No Y button on right hand")}_handleButtonChange(e,t){const i=t,n="right"===this.hand?-1:1;switch(e){case 0:return void this.onPadStateChangedObservable.notifyObservers(i);case 1:return!Zu._IsQuest&&this._defaultModel&&(this._defaultModel.getChildren()[3].rotation.x=.2*-i.value,this._defaultModel.getChildren()[3].position.y=.005*-i.value,this._defaultModel.getChildren()[3].position.z=.005*-i.value),void this.onTriggerStateChangedObservable.notifyObservers(i);case 2:return!Zu._IsQuest&&this._defaultModel&&(this._defaultModel.getChildren()[4].position.x=n*i.value*.0035),void this.onSecondaryTriggerStateChangedObservable.notifyObservers(i);case 3:return!Zu._IsQuest&&this._defaultModel&&(i.pressed?this._defaultModel.getChildren()[1].position.y=-.001:this._defaultModel.getChildren()[1].position.y=0),void this.onMainButtonStateChangedObservable.notifyObservers(i);case 4:return!Zu._IsQuest&&this._defaultModel&&(i.pressed?this._defaultModel.getChildren()[2].position.y=-.001:this._defaultModel.getChildren()[2].position.y=0),void this.onSecondaryButtonStateChangedObservable.notifyObservers(i);case 5:return void this.onThumbRestChangedObservable.notifyObservers(i)}}}Zu.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/",Zu.MODEL_LEFT_FILENAME="left.babylon",Zu.MODEL_RIGHT_FILENAME="right.babylon",Zu.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/",Zu._IsQuest=!1,Wn._ControllerFactories.push({canCreate:e=>(m.l.LastCreatedEngine&&m.l.LastCreatedEngine._vrDisplay&&"Oculus Quest"===m.l.LastCreatedEngine._vrDisplay.displayName&&(Zu._IsQuest=!0),-1!==e.id.indexOf("Oculus Touch")),create:e=>new Zu(e)});class Ju extends Fs{constructor(e){super(e),this.controllerType=yn.VIVE,this._invertLeftStickY=!0}initControllerMesh(e,t){ht.ImportMesh("",Ju.MODEL_BASE_URL,Ju.MODEL_FILENAME,e,(e=>{this._defaultModel=e[1],this.attachToMesh(this._defaultModel),t&&t(this._defaultModel)}))}get onLeftButtonStateChangedObservable(){return this.onMainButtonStateChangedObservable}get onRightButtonStateChangedObservable(){return this.onMainButtonStateChangedObservable}get onMenuButtonStateChangedObservable(){return this.onSecondaryButtonStateChangedObservable}_handleButtonChange(e,t){const i=t;switch(e){case 0:return void this.onPadStateChangedObservable.notifyObservers(i);case 1:return this._defaultModel&&(this._defaultModel.getChildren()[6].rotation.x=.15*-i.value),void this.onTriggerStateChangedObservable.notifyObservers(i);case 2:return void this.onMainButtonStateChangedObservable.notifyObservers(i);case 3:return this._defaultModel&&(i.pressed?this._defaultModel.getChildren()[2].position.y=-.001:this._defaultModel.getChildren()[2].position.y=0),void this.onSecondaryButtonStateChangedObservable.notifyObservers(i)}}}Ju.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/",Ju.MODEL_FILENAME="wand.babylon",Wn._ControllerFactories.push({canCreate:e=>-1!==e.id.toLowerCase().indexOf("openvr"),create:e=>new Ju(e)});class ep{constructor(){this.buttonMeshes={},this.axisMeshes={}}}class tp extends Fs{constructor(e){super(e),this._mapping={buttons:["thumbstick","trigger","grip","menu","trackpad"],buttonMeshNames:{trigger:"SELECT",menu:"MENU",grip:"GRASP",thumbstick:"THUMBSTICK_PRESS",trackpad:"TOUCHPAD_PRESS"},buttonObservableNames:{trigger:"onTriggerStateChangedObservable",menu:"onSecondaryButtonStateChangedObservable",grip:"onMainButtonStateChangedObservable",thumbstick:"onPadStateChangedObservable",trackpad:"onTrackpadChangedObservable"},axisMeshNames:["THUMBSTICK_X","THUMBSTICK_Y","TOUCHPAD_TOUCH_X","TOUCHPAD_TOUCH_Y"],pointingPoseMeshName:Hn.POINTING_POSE},this.onTrackpadChangedObservable=new r.y$,this.onTrackpadValuesChangedObservable=new r.y$,this.trackpad={x:0,y:0},this.controllerType=yn.WINDOWS,this._loadedMeshInfo=null}get onTriggerButtonStateChangedObservable(){return this.onTriggerStateChangedObservable}get onMenuButtonStateChangedObservable(){return this.onSecondaryButtonStateChangedObservable}get onGripButtonStateChangedObservable(){return this.onMainButtonStateChangedObservable}get onThumbstickButtonStateChangedObservable(){return this.onPadStateChangedObservable}get onTouchpadButtonStateChangedObservable(){return this.onTrackpadChangedObservable}get onTouchpadValuesChangedObservable(){return this.onTrackpadValuesChangedObservable}_updateTrackpad(){!this.browserGamepad.axes||this.browserGamepad.axes[2]==this.trackpad.x&&this.browserGamepad.axes[3]==this.trackpad.y||(this.trackpad.x=this.browserGamepad.axes[this._mapping.axisMeshNames.indexOf("TOUCHPAD_TOUCH_X")],this.trackpad.y=this.browserGamepad.axes[this._mapping.axisMeshNames.indexOf("TOUCHPAD_TOUCH_Y")],this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad))}update(){if(super.update(),this.browserGamepad.axes&&(this._updateTrackpad(),this._loadedMeshInfo))for(let e=0;e{this._loadedMeshInfo=this._processModel(e,i),this._loadedMeshInfo&&(this._defaultModel=this._loadedMeshInfo.rootNode,this.attachToMesh(this._defaultModel),t&&t(this._defaultModel))}),null,((e,r)=>{p.Y.Log(r),p.Y.Warn("Failed to retrieve controller model from the remote server: "+n+s),i||this.initControllerMesh(e,t,!0)}))}_processModel(e,t){let i=null;const n=new ee.Kj(this.id+" "+this.hand,e);let s=null;for(let r=0;re.name===t),!1)[0]}function s(e,t){return e.getChildren((e=>e.name==t),!0)[0]}}getForwardRay(e=100){if(!this._loadedMeshInfo||!this._loadedMeshInfo.pointingPoseNode)return super.getForwardRay(e);const t=this._loadedMeshInfo.pointingPoseNode.getWorldMatrix(),i=t.getTranslation(),n=new o.P(0,0,-1),s=o.P.TransformNormal(n,t),r=o.P.Normalize(s);return new qe(i,r,e)}dispose(){super.dispose(),this.onTrackpadChangedObservable.clear(),this.onTrackpadValuesChangedObservable.clear()}}tp.MODEL_BASE_URL="https://controllers.babylonjs.com/microsoft/",tp.MODEL_LEFT_FILENAME="left.glb",tp.MODEL_RIGHT_FILENAME="right.glb",tp.GAMEPAD_ID_PREFIX="Spatial Controller (Spatial Interaction Source) ",tp.GAMEPAD_ID_PATTERN=/([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;Wn._ControllerFactories.push({canCreate:e=>0===e.id.indexOf(tp.GAMEPAD_ID_PREFIX),create:e=>new tp(e)});class ip extends ul{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}constructor(e,t=a.Wo.Gray(),i=dl.DefaultUtilityLayer,n=32,s=null,l=!1,h=1){var c;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new r.y$,this.angle=0,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._angles=new o.P,this._parent=s,this._coloredMaterial=new _a("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new a.Wo(.1,.1,.1)),this._hoverMaterial=new _a("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=a.Wo.Yellow(),this._disableMaterial=new _a("",i.utilityLayerScene),this._disableMaterial.diffuseColor=a.Wo.Gray(),this._disableMaterial.alpha=.4,this._gizmoMesh=new ee.Kj("",i.utilityLayerScene);const{rotationMesh:d,collider:u}=this._createGizmoMesh(this._gizmoMesh,h,n);this._rotationDisplayPlane=Je("rotationDisplay",{size:.6,updatable:!1},this.gizmoLayer.utilityLayerScene),this._rotationDisplayPlane.rotation.z=.5*Math.PI,this._rotationDisplayPlane.parent=this._gizmoMesh,this._rotationDisplayPlane.setEnabled(!1),ft.Q.ShadersStore.rotationGizmoVertexShader=ip._RotationGizmoVertexShader,ft.Q.ShadersStore.rotationGizmoFragmentShader=ip._RotationGizmoFragmentShader,this._rotationShaderMaterial=new Il("shader",this.gizmoLayer.utilityLayerScene,{vertex:"rotationGizmo",fragment:"rotationGizmo"},{attributes:["position","uv"],uniforms:["worldViewProjection","angles"]}),this._rotationShaderMaterial.backFaceCulling=!1,this._rotationDisplayPlane.material=this._rotationShaderMaterial,this._rotationDisplayPlane.visibility=.999,this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,ul.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3),this.dragBehavior=new et({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.maxDragAngle=ip.MaxDragAngle,this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,this._rootMesh.addBehavior(this.dragBehavior);const f=new o.P,_=new o.y3,m=new o.P;let g=new o.P;this.dragBehavior.onDragStartObservable.add((e=>{this.attachedNode&&(f.copyFrom(e.dragPlanePoint),this._rotationDisplayPlane.setEnabled(!0),this._rotationDisplayPlane.getWorldMatrix().invertToRef(_),o.P.TransformCoordinatesToRef(e.dragPlanePoint,_,f),this._angles.x=Math.atan2(f.y,f.x)+Math.PI,this._angles.y=0,this._angles.z=this.updateGizmoRotationToMatchAttachedMesh?1:0,this._dragging=!0,f.copyFrom(e.dragPlanePoint),this._rotationShaderMaterial.setVector3("angles",this._angles),this.angle=0)})),this.dragBehavior.onDragEndObservable.add((()=>{this._dragging=!1,this._rotationDisplayPlane.setEnabled(!1)}));const v={snapDistance:0};let T=0;const S=new o.y3,E=new o._f;this.dragBehavior.onDragObservable.add((t=>{if(this.attachedNode){const n=new o.P(1,1,1),s=new o._f(0,0,0,1),r=new o.P(0,0,0);this._handlePivot(),this.attachedNode.getWorldMatrix().decompose(n,s,r);if(!(Math.abs(Math.abs(n.x)-Math.abs(n.y))<=k.kn&&Math.abs(Math.abs(n.x)-Math.abs(n.z))<=k.kn)&&this.updateGizmoRotationToMatchAttachedMesh)return void p.Y.Warn("Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false.");s.normalize();const a=this.updateGizmoPositionToMatchAttachedMesh?r:this._rootMesh.absolutePosition,l=t.dragPlanePoint.subtract(a).normalize(),h=f.subtract(a).normalize(),c=o.P.Cross(l,h),d=o.P.Dot(l,h);let u=Math.atan2(c.length(),d);m.copyFrom(e),g.copyFrom(e),this.updateGizmoRotationToMatchAttachedMesh&&(s.toRotationMatrix(_),g=o.P.TransformCoordinates(m,_));let x=!1;if(i.utilityLayerScene.activeCamera){const e=i.utilityLayerScene.activeCamera.position.subtract(a).normalize();o.P.Dot(e,g)>0&&(m.scaleInPlace(-1),g.scaleInPlace(-1),x=!0)}o.P.Dot(g,c)>0&&(u=-u);let b=!1;if(0!=this.snapDistance)if(T+=u,Math.abs(T)>this.snapDistance){let e=Math.floor(Math.abs(T)/this.snapDistance);T<0&&(e*=-1),T%=this.snapDistance,u=this.snapDistance*e,b=!0}else u=0;const C=Math.sin(u/2);if(E.set(m.x*C,m.y*C,m.z*C,Math.cos(u/2)),S.determinant()>0){const e=new o.P;E.toEulerAnglesToRef(e),o._f.RotationYawPitchRollToRef(e.y,-e.x,-e.z,E)}if(this.updateGizmoRotationToMatchAttachedMesh)s.multiplyToRef(E,s),o.y3.ComposeToRef(n,s,r,this.attachedNode.getWorldMatrix());else{E.toRotationMatrix(o.jp.Matrix[0]);const e=this.attachedNode.getWorldMatrix().getTranslation();this.attachedNode.getWorldMatrix().multiplyToRef(o.jp.Matrix[0],this.attachedNode.getWorldMatrix()),this.attachedNode.getWorldMatrix().setTranslation(e)}f.copyFrom(t.dragPlanePoint),b&&(v.snapDistance=u,this.onSnapObservable.notifyObservers(v)),this._angles.y+=u,this.angle+=x?-u:u,this._rotationShaderMaterial.setVector3("angles",this._angles),this._matrixChanged()}}));const x=i._getSharedGizmoLight();x.includedOnlyMeshes=x.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));const b={colliderMeshes:[u],gizmoMeshes:[d],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};null===(c=this._parent)||void 0===c||c.addToAxisCache(this._gizmoMesh,b),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add((e=>{var t;if(!this._customMeshSet&&(this.dragBehavior.maxDragAngle=ip.MaxDragAngle,this._isHovered=!(-1==b.colliderMeshes.indexOf(null===(t=null==e?void 0:e.pickInfo)||void 0===t?void 0:t.pickedMesh)),!this._parent)){const e=b.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(b.gizmoMeshes,e)}})),this.dragBehavior.onEnabledObservable.add((e=>{this._setGizmoMeshMaterial(b.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)}))}_createGizmoMesh(e,t,i){const n=La("ignore",{diameter:.6,thickness:.03*t,tessellation:i},this.gizmoLayer.utilityLayerScene);n.visibility=0;const s=La("",{diameter:.6,thickness:.005*t,tessellation:i},this.gizmoLayer.utilityLayerScene);return s.material=this._coloredMaterial,s.rotation.x=Math.PI/2,n.rotation.x=Math.PI/2,e.addChild(s,ul.PreserveScaling),e.addChild(n,ul.PreserveScaling),{rotationMesh:s,collider:n}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),this._rotationDisplayPlane&&this._rotationDisplayPlane.dispose(),this._rotationShaderMaterial&&this._rotationShaderMaterial.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach((e=>{e&&e.dispose()})),super.dispose()}}ip.MaxDragAngle=9*Math.PI/20,ip._RotationGizmoVertexShader="\n precision highp float;\n attribute vec3 position;\n attribute vec2 uv;\n uniform mat4 worldViewProjection;\n varying vec3 vPosition;\n varying vec2 vUV;\n void main(void) {\n gl_Position = worldViewProjection * vec4(position, 1.0);\n vUV = uv;\n }",ip._RotationGizmoFragmentShader="\n precision highp float;\n varying vec2 vUV;\n varying vec3 vPosition;\n uniform vec3 angles;\n #define twopi 6.283185307\n void main(void) {\n vec2 uv = vUV - vec2(0.5);\n float angle = atan(uv.y, uv.x) + 3.141592;\n float delta = gl_FrontFacing ? angles.y : -angles.y;\n float begin = angles.x - delta * angles.z;\n float start = (begin < (begin + delta)) ? begin : (begin + delta);\n float end = (begin > (begin + delta)) ? begin : (begin + delta);\n float len = sqrt(dot(uv,uv));\n float opacity = 1. - step(0.5, len);\n\n float base = abs(floor(start / twopi)) * twopi;\n start += base;\n end += base;\n\n float intensity = 0.;\n for (int i = 0; i < 5; i++)\n {\n intensity += max(step(start, angle) - step(end, angle), 0.);\n angle += twopi;\n }\n gl_FragColor = vec4(1.,1.,0., min(intensity * 0.25, 0.8)) * opacity;\n }";class np extends he{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0}_setPosition(e){this._position=e}get position(){return this._position}set position(e){this._setPosition(e)}_setDirection(e){this._direction=e}get direction(){return this._direction}set direction(e){this._setDirection(e)}get shadowMinZ(){return this._shadowMinZ}set shadowMinZ(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()}get shadowMaxZ(){return this._shadowMaxZ}set shadowMaxZ(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()}computeTransformedInformation(){return!(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition||(this.transformedPosition=o.P.Zero()),o.P.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=o.P.Zero()),o.P.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=o.P.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=o.P.Cross(this.direction,L.RD.Y),t=o.P.Cross(e,this.direction);return o.P.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=o.P.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=o.y3.Identity()),o.y3.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)}}(0,oe.gn)([(0,E.hd)()],np.prototype,"position",null),(0,oe.gn)([(0,E.hd)()],np.prototype,"direction",null),(0,oe.gn)([(0,E.qC)()],np.prototype,"shadowMinZ",null),(0,oe.gn)([(0,E.qC)()],np.prototype,"shadowMaxZ",null),b.N.AddNodeConstructor("Light_Type_1",((e,t)=>()=>new sp(e,o.P.Zero(),t)));class sp extends np{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 he.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&&o.y3.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=o.P.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE;let n=Number.MAX_VALUE,s=Number.MIN_VALUE;for(let r=0;rthis._orthoRight&&(this._orthoRight=e.x),e.y>this._orthoTop&&(this._orthoTop=e.y),this.autoCalcShadowZBounds&&(e.zs&&(s=e.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=n,this._shadowMaxZ=s)}const s=this._orthoRight-this._orthoLeft,r=this._orthoTop-this._orthoBottom,a=void 0!==this.shadowMinZ?this.shadowMinZ:n.minZ,l=void 0!==this.shadowMaxZ?this.shadowMaxZ:n.maxZ,h=this.getScene().getEngine().useReverseDepthBuffer;o.y3.OrthoOffCenterLHToRef(this._orthoLeft-s*this.shadowOrthoScale,this._orthoRight+s*this.shadowOrthoScale,this._orthoBottom-r*this.shadowOrthoScale,this._orthoTop+r*this.shadowOrthoScale,h?l:a,h?a:l,e,this.getScene().getEngine().isNDCHalfZRange)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?(e.setFloat3(t,this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z),this):(e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this)}getDepthMinZ(e){const t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){const t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}}function rp(e,t={},i){t.diameter||(t.diameter=1),t.segments||(t.segments=16);const n=gl("",{slice:.5,diameter:t.diameter,segments:t.segments},i),s=bl("",{radius:t.diameter/2,tessellation:3*t.segments+(4-t.segments)},i);s.rotation.x=-Math.PI/2,s.parent=n;const r=ee.Kj.MergeMeshes([s,n],!0);return r.name=e,r}(0,oe.gn)([(0,E.qC)()],sp.prototype,"shadowFrustumSize",null),(0,oe.gn)([(0,E.qC)()],sp.prototype,"shadowOrthoScale",null),(0,oe.gn)([(0,E.qC)()],sp.prototype,"autoUpdateExtends",void 0),(0,oe.gn)([(0,E.qC)()],sp.prototype,"autoCalcShadowZBounds",void 0),(0,oe.gn)([(0,E.qC)("orthoLeft")],sp.prototype,"_orthoLeft",void 0),(0,oe.gn)([(0,E.qC)("orthoRight")],sp.prototype,"_orthoRight",void 0),(0,oe.gn)([(0,E.qC)("orthoTop")],sp.prototype,"_orthoTop",void 0),(0,oe.gn)([(0,E.qC)("orthoBottom")],sp.prototype,"_orthoBottom",void 0);ee.Kj.CreateHemisphere=(e,t,i,n)=>rp(e,{segments:t,diameter:i},n),b.N.AddNodeConstructor("Light_Type_2",((e,t)=>()=>new op(e,o.P.Zero(),o.P.Zero(),0,0,t)));class op extends np{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()&&(op._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled((()=>{this._markMeshesAsLightDirty()})):op._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,s,r){super(e,r),this._innerAngle=0,this._projectionTextureMatrix=o.y3.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=o.P.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=o.P.Zero(),this._projectionTextureViewLightMatrix=o.y3.Zero(),this._projectionTextureProjectionLightMatrix=o.y3.Zero(),this._projectionTextureScalingMatrix=o.y3.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),this.position=t,this.direction=i,this.angle=n,this.exponent=s}getClassName(){return"SpotLight"}getTypeID(){return he.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){const n=this.getScene().activeCamera;if(!n)return;this._shadowAngleScale=this._shadowAngleScale||1;const s=this._shadowAngleScale*this._angle,r=void 0!==this.shadowMinZ?this.shadowMinZ:n.minZ,a=void 0!==this.shadowMaxZ?this.shadowMaxZ:n.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;o.y3.PerspectiveFovLHToRef(s,1,l?a:r,l?r:a,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,l)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.position.addToRef(this.direction,this._projectionTextureViewTargetVector),o.y3.LookAtLHToRef(this.position,this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;const e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),n=-i*t,s=1/Math.tan(this._angle/2);o.y3.FromValuesToRef(s/1,0,0,0,0,s,0,0,0,0,i,1,0,0,n,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof Le){const e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;o.y3.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("projectionLightSampler"+t,this.projectionTexture)),this}transferToEffect(e,t){let i;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,t),i=o.P.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=o.P.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()?o.P.Normalize(this.transformedDirection):o.P.Normalize(this.direction),this.getScene().useRightHandedSystem?e.setFloat3(t,-i.x,-i.y,-i.z):e.setFloat3(t,i.x,i.y,i.z),this}dispose(){super.dispose(),this._projectionTexture&&this._projectionTexture.dispose()}getDepthMinZ(e){const t=this._scene.getEngine(),i=void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?i:this._scene.getEngine().isNDCHalfZRange?0:i}getDepthMaxZ(e){const t=this._scene.getEngine(),i=void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:i}prepareLightSpecificDefines(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!(!this.projectionTexture||!this.projectionTexture.isReady())}}(0,oe.gn)([(0,E.qC)()],op.prototype,"angle",null),(0,oe.gn)([(0,E.qC)()],op.prototype,"innerAngle",null),(0,oe.gn)([(0,E.qC)()],op.prototype,"shadowAngleScale",null),(0,oe.gn)([(0,E.qC)()],op.prototype,"exponent",void 0),(0,oe.gn)([(0,E.qC)()],op.prototype,"projectionTextureLightNear",null),(0,oe.gn)([(0,E.qC)()],op.prototype,"projectionTextureLightFar",null),(0,oe.gn)([(0,E.qC)()],op.prototype,"projectionTextureUpDirection",null),(0,oe.gn)([(0,E.oU)("projectedLightTexture")],op.prototype,"_projectionTexture",void 0);class ap extends ul{constructor(e=dl.DefaultUtilityLayer){super(e),this._cachedPosition=new o.P,this._cachedForward=new o.P(0,0,1),this._pointerObserver=null,this.onClickedObservable=new r.y$,this._light=null,this.attachedMesh=new ie.x("",this.gizmoLayer.utilityLayerScene),this._attachedMeshParent=new te.Y("parent",this.gizmoLayer.utilityLayerScene),this.attachedMesh.parent=this._attachedMeshParent,this._material=new _a("light",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new a.Wo(.5,.5,.5),this._material.specularColor=new a.Wo(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add((e=>{this._light&&(this._isHovered=!(!e.pickInfo||-1==this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._light))}),We.kD.POINTERDOWN)}get attachedNode(){return this.attachedMesh}set attachedNode(e){console.warn("Nodes cannot be attached to LightGizmo. Attach to a mesh instead.")}set light(e){if(this._light=e,e){this._lightMesh&&this._lightMesh.dispose(),this._lightMesh=e instanceof Os?ap._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof sp?ap._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof op?ap._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene):ap._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene),this._lightMesh.getChildMeshes(!1).forEach((e=>{e.material=this._material})),this._lightMesh.parent=this._rootMesh;const t=this.gizmoLayer._getSharedGizmoLight();t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(!1)),this._lightMesh.rotationQuaternion=new o._f,this.attachedMesh.reservedDataStore||(this.attachedMesh.reservedDataStore={}),this.attachedMesh.reservedDataStore.lightGizmo=this,e.parent&&this._attachedMeshParent.freezeWorldMatrix(e.parent.getWorldMatrix()),e.position&&(this.attachedMesh.position.copyFrom(e.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position)),e.direction&&(this.attachedMesh.setDirection(e.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(this.attachedMesh.forward)),this._update()}}get light(){return this._light}get material(){return this._material}_update(){if(super._update(),this._light){if(this._light.parent&&this._attachedMeshParent.freezeWorldMatrix(this._light.parent.getWorldMatrix()),this._light.position)if(this.attachedMesh.position.equals(this._cachedPosition))this.attachedMesh.position.copyFrom(this._light.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position);else{const e=this.attachedMesh.position;this._light.position=new o.P(e.x,e.y,e.z),this._cachedPosition.copyFrom(this.attachedMesh.position)}if(this._light.direction)if(o.P.DistanceSquared(this.attachedMesh.forward,this._cachedForward)>1e-4){const e=this.attachedMesh.forward;this._light.direction=new o.P(e.x,e.y,e.z),this._cachedForward.copyFrom(this.attachedMesh.forward)}else o.P.DistanceSquared(this.attachedMesh.forward,this._light.direction)>1e-4&&(this.attachedMesh.setDirection(this._light.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(this.attachedMesh.forward))}}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._material.dispose(),super.dispose(),this._attachedMeshParent.dispose()}static _CreateHemisphericLightMesh(e){const t=new ee.Kj("hemisphereLight",e),i=rp(t.name,{segments:10,diameter:1},e);i.position.z=-.15,i.rotation.x=Math.PI/2,i.parent=t;return this._CreateLightLines(3,e).parent=t,t.scaling.scaleInPlace(ap._Scale),t.rotation.x=Math.PI/2,t}static _CreatePointLightMesh(e){const t=new ee.Kj("pointLight",e),i=gl(t.name,{segments:10,diameter:1},e);i.rotation.x=Math.PI/2,i.parent=t;return this._CreateLightLines(5,e).parent=t,t.scaling.scaleInPlace(ap._Scale),t.rotation.x=Math.PI/2,t}static _CreateSpotLightMesh(e){const t=new ee.Kj("spotLight",e);gl(t.name,{segments:10,diameter:1},e).parent=t;const i=rp(t.name,{segments:10,diameter:2},e);i.parent=t,i.rotation.x=-Math.PI/2;return this._CreateLightLines(2,e).parent=t,t.scaling.scaleInPlace(ap._Scale),t.rotation.x=Math.PI/2,t}static _CreateDirectionalLightMesh(e){const t=new ee.Kj("directionalLight",e),i=new ee.Kj(t.name,e);i.parent=t;gl(t.name,{diameter:1.2,segments:10},e).parent=i;const n=Fa(t.name,{updatable:!1,height:6,diameterTop:.3,diameterBottom:.3,tessellation:6,subdivisions:1},e);n.parent=i;let s=n.clone(t.name);s.scaling.y=.5,s.position.x+=1.25;let r=n.clone(t.name);r.scaling.y=.5,r.position.x+=-1.25;const o=Fa(t.name,{updatable:!1,height:1,diameterTop:0,diameterBottom:.6,tessellation:6,subdivisions:1},e);return o.position.y+=3,o.parent=i,s=o.clone(t.name),s.position.y=1.5,s.position.x+=1.25,r=o.clone(t.name),r.position.y=1.5,r.position.x+=-1.25,i.scaling.scaleInPlace(ap._Scale),i.rotation.z=Math.PI/2,i.rotation.y=Math.PI/2,t}}ap._Scale=.007,ap._CreateLightLines=(e,t)=>{const i=new ee.Kj("root",t);i.rotation.x=Math.PI/2;const n=new ee.Kj("linePivot",t);n.parent=i;const s=Fa("line",{updatable:!1,height:2,diameterTop:.2,diameterBottom:.3,tessellation:6,subdivisions:1},t);if(s.position.y=s.scaling.y/2+1.2,s.parent=n,e<2)return n;for(let r=0;r<4;r++){const e=n.clone("lineParentClone");e.rotation.z=Math.PI/4,e.rotation.y=Math.PI/2+Math.PI/2*r,e.getChildMeshes()[0].scaling.y=.5,e.getChildMeshes()[0].scaling.x=e.getChildMeshes()[0].scaling.z=.8,e.getChildMeshes()[0].position.y=e.getChildMeshes()[0].scaling.y/2+1.2}if(e<3)return i;for(let r=0;r<4;r++){const e=n.clone("linePivotClone");e.rotation.z=Math.PI/2,e.rotation.y=Math.PI/2*r}if(e<4)return i;for(let r=0;r<4;r++){const e=n.clone("linePivotClone");e.rotation.z=Math.PI+Math.PI/4,e.rotation.y=Math.PI/2+Math.PI/2*r,e.getChildMeshes()[0].scaling.y=.5,e.getChildMeshes()[0].scaling.x=e.getChildMeshes()[0].scaling.z=.8,e.getChildMeshes()[0].position.y=e.getChildMeshes()[0].scaling.y/2+1.2}if(e<5)return i;return n.clone("linePivotClone").rotation.z=Math.PI,i};class lp extends ul{constructor(e=dl.DefaultUtilityLayer){super(e),this._pointerObserver=null,this.onClickedObservable=new r.y$,this._camera=null,this._invProjection=new o.y3,this._material=new _a("cameraGizmoMaterial",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new a.Wo(.5,.5,.5),this._material.specularColor=new a.Wo(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add((e=>{this._camera&&(this._isHovered=!(!e.pickInfo||-1==this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._camera))}),We.kD.POINTERDOWN)}get displayFrustum(){return this._cameraLinesMesh.isEnabled()}set displayFrustum(e){this._cameraLinesMesh.setEnabled(e)}set camera(e){if(this._camera=e,this.attachedNode=e,e){this._cameraMesh&&this._cameraMesh.dispose(),this._cameraLinesMesh&&this._cameraLinesMesh.dispose(),this._cameraMesh=lp._CreateCameraMesh(this.gizmoLayer.utilityLayerScene),this._cameraLinesMesh=lp._CreateCameraFrustum(this.gizmoLayer.utilityLayerScene),this._cameraMesh.getChildMeshes(!1).forEach((e=>{e.material=this._material})),this._cameraMesh.parent=this._rootMesh,this._cameraLinesMesh.parent=this._rootMesh,this.gizmoLayer.utilityLayerScene.activeCamera&&this.gizmoLayer.utilityLayerScene.activeCamera.maxZ<1.5*e.maxZ&&(this.gizmoLayer.utilityLayerScene.activeCamera.maxZ=1.5*e.maxZ),this.attachedNode.reservedDataStore||(this.attachedNode.reservedDataStore={}),this.attachedNode.reservedDataStore.cameraGizmo=this;const t=this.gizmoLayer._getSharedGizmoLight();t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._cameraMesh.getChildMeshes(!1)),this._update()}}get camera(){return this._camera}get material(){return this._material}_update(){super._update(),this._camera&&(this._camera.getProjectionMatrix().invertToRef(this._invProjection),this._cameraLinesMesh.setPivotMatrix(this._invProjection,!1),this._cameraLinesMesh.scaling.x=1/this._rootMesh.scaling.x,this._cameraLinesMesh.scaling.y=1/this._rootMesh.scaling.y,this._cameraLinesMesh.scaling.z=1/this._rootMesh.scaling.z,this._cameraMesh.parent=null,this._cameraMesh.rotation.y=.5*Math.PI*(this._camera.getScene().useRightHandedSystem?1:-1),this._cameraMesh.parent=this._rootMesh)}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._cameraMesh&&this._cameraMesh.dispose(),this._cameraLinesMesh&&this._cameraLinesMesh.dispose(),this._material.dispose(),super.dispose()}static _CreateCameraMesh(e){const t=new ee.Kj("rootCameraGizmo",e),i=new ee.Kj(t.name,e);i.parent=t;_l(t.name,{width:1,height:.8,depth:.5},e).parent=i;const n=Fa(t.name,{height:.5,diameterTop:.8,diameterBottom:.8},e);n.parent=i,n.position.y=.3,n.position.x=-.6,n.rotation.x=.5*Math.PI;const s=Fa(t.name,{height:.5,diameterTop:.6,diameterBottom:.6},e);s.parent=i,s.position.y=.5,s.position.x=.4,s.rotation.x=.5*Math.PI;const r=Fa(t.name,{height:.5,diameterTop:.5,diameterBottom:.5},e);return r.parent=i,r.position.y=0,r.position.x=.6,r.rotation.z=.5*Math.PI,t.scaling.scaleInPlace(lp._Scale),i.position.x=-.9,t}static _CreateCameraFrustum(e){const t=new ee.Kj("rootCameraGizmo",e),i=new ee.Kj(t.name,e);i.parent=t;for(let n=0;n<4;n+=2)for(let t=0;t<4;t+=2){let s=Vl("lines",{points:[new o.P(-1+t,-1+n,-1),new o.P(-1+t,-1+n,1)]},e);s.parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1,s=Vl("lines",{points:[new o.P(-1,-1+t,-1+n),new o.P(1,-1+t,-1+n)]},e),s.parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1,s=Vl("lines",{points:[new o.P(-1+t,-1,-1+n),new o.P(-1+t,1,-1+n)]},e),s.parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1}return t}}lp._Scale=.05;const hp="kernelBlurVaryingDeclaration",cp="varying vec2 sampleCoord{X};";Ht.v.IncludesShadersStore[hp]=cp;const dp="packingFunctions",up="vec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}";Ht.v.IncludesShadersStore[dp]=up;const pp="kernelBlurFragment",fp="#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif\n";Ht.v.IncludesShadersStore[pp]=fp;const _p="kernelBlurFragment2",mp="#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif\n";Ht.v.IncludesShadersStore[_p]=mp;const gp="kernelBlurPixelShader",vp="uniform sampler2D textureSampler;\nuniform vec2 delta;\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nfloat sampleCoC(in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r;\nreturn coc; \n}\n#endif\n#include[0..varyingCount]\n#ifdef PACKEDFLOAT\n#include\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT\nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include[0..varyingCount]\n#include[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}";Ht.v.ShadersStore[gp]=vp;const Tp="kernelBlurVertex",Sp="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";Ht.v.IncludesShadersStore[Tp]=Sp;const Ep="kernelBlurVertexShader",xp="attribute vec2 position;\nuniform vec2 delta;\nvarying vec2 sampleCenter;\n#include[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nsampleCenter=(position*madd+madd);\n#include[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";Ht.v.ShadersStore[Ep]=xp;class bp extends Zt{set kernel(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this._blockCompilation||this._updateParameters())}get kernel(){return this._idealKernel}set packedFloat(e){this._packedFloat!==e&&(this._packedFloat=e,this._blockCompilation||this._updateParameters())}get packedFloat(){return this._packedFloat}getClassName(){return"BlurPostProcess"}constructor(e,t,i,n,s,r=Le.BILINEAR_SAMPLINGMODE,o,a,l=0,h="",c=!1,d=5){super(e,"kernelBlur",["delta","direction"],["circleOfConfusionSampler"],n,s,r,o,a,null,l,"kernelBlur",{varyingCount:0,depCount:0},!0,d),this._blockCompilation=c,this._packedFloat=!1,this._staticDefines="",this._staticDefines=h,this.direction=t,this.onApplyObservable.add((e=>{this._outputTexture?e.setFloat2("delta",1/this._outputTexture.width*this.direction.x,1/this._outputTexture.height*this.direction.y):e.setFloat2("delta",1/this.width*this.direction.x,1/this.height*this.direction.y)})),this.kernel=i}updateEffect(e=null,t=null,i=null,n,s,r){this._updateParameters(s,r)}_updateParameters(e,t){const i=this._kernel,n=(i-1)/2;let s=[],r=[],o=0;for(let _=0;_0)return Math.max(i,3);return Math.max(t,3)}_gaussianWeight(e){const t=1/3,i=-e*e/(2*t*t);return 1/(Math.sqrt(2*Math.PI)*t)*Math.exp(i)}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}static _Parse(e,t,i,n){return E.p4.Parse((()=>new bp(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1)),e,i,n)}}(0,oe.gn)([(0,E.qC)("kernel")],bp.prototype,"_kernel",void 0),(0,oe.gn)([(0,E.qC)("packedFloat")],bp.prototype,"_packedFloat",void 0),(0,oe.gn)([(0,E.QC)()],bp.prototype,"direction",void 0),(0,l.H)("BABYLON.BlurPostProcess",bp);class Cp extends Ci{set blurRatio(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())}get blurRatio(){return this._blurRatio}set adaptiveBlurKernel(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()}set blurKernel(e){this.blurKernelX=e,this.blurKernelY=e}set blurKernelX(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())}get blurKernelX(){return this._blurKernelX}set blurKernelY(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())}get blurKernelY(){return this._blurKernelY}_autoComputeBlurKernel(){const e=this.getScene().getEngine(),t=this.getRenderWidth()/e.getRenderWidth(),i=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*t,this.blurKernelY=this._adaptiveBlurKernel*i}_onRatioRescale(){this._sizeRatio&&(this.resize(this._initialSizeParameter),this._adaptiveBlurKernel||this._preparePostProcesses()),this._adaptiveBlurKernel&&this._autoComputeBlurKernel()}_updateGammaSpace(){const e=this.getScene();e&&(this.gammaSpace=!e.imageProcessingConfiguration.isEnabled||!e.imageProcessingConfiguration.applyByPostProcess)}constructor(e,t,i,n,s=0,r=Le.BILINEAR_SAMPLINGMODE,a=!0){if(super(e,t,i,n,!0,s,!1,r,a),this.mirrorPlane=new Me.J(0,1,0,1),this._transformMatrix=o.y3.Zero(),this._mirrorMatrix=o.y3.Zero(),this._adaptiveBlurKernel=0,this._blurKernelX=0,this._blurKernelY=0,this._blurRatio=1,!(i=this.getScene()))return this;this.ignoreCameraViewport=!0,this._updateGammaSpace(),this._imageProcessingConfigChangeObserver=i.imageProcessingConfiguration.onUpdateParameters.add((()=>{this._updateGammaSpace()}));const l=i.getEngine();let h;l.supportsUniformBuffers&&(this._sceneUBO=i.createSceneUniformBuffer(`Scene for Mirror Texture (name "${e}")`)),this.onBeforeBindObservable.add((()=>{var t;null===(t=l._debugPushGroup)||void 0===t||t.call(l,`mirror generation for ${e}`,1)})),this.onAfterUnbindObservable.add((()=>{var e;null===(e=l._debugPopGroup)||void 0===e||e.call(l,1)})),this.onBeforeRenderObservable.add((()=>{this._sceneUBO&&(this._currentSceneUBO=i.getSceneUniformBuffer(),i.setSceneUniformBuffer(this._sceneUBO),i.getSceneUniformBuffer().unbindEffect()),o.y3.ReflectionToRef(this.mirrorPlane,this._mirrorMatrix),this._mirrorMatrix.multiplyToRef(i.getViewMatrix(),this._transformMatrix),i.setTransformMatrix(this._transformMatrix,i.getProjectionMatrix()),h=i.clipPlane,i.clipPlane=this.mirrorPlane,i._mirroredCameraPosition=o.P.TransformCoordinates(i.activeCamera.globalPosition,this._mirrorMatrix)})),this.onAfterRenderObservable.add((()=>{this._sceneUBO&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(),i._mirroredCameraPosition=null,i.clipPlane=h}))}_preparePostProcesses(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){const e=this.getScene().getEngine(),t=e.getCaps().textureFloatRender&&e.getCaps().textureFloatLinearFiltering?1:2;this._blurX=new bp("horizontal blur",new o.FM(1,0),this._blurKernelX,this._blurRatio,null,Le.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurX.autoClear=!1,1===this._blurRatio&&this.samples<2&&this._texture?this._blurX.inputTexture=this._renderTarget:this._blurX.alwaysForcePOT=!0,this._blurY=new bp("vertical blur",new o.FM(0,1),this._blurKernelY,this._blurRatio,null,Le.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=1!==this._blurRatio,this.addPostProcess(this._blurX),this.addPostProcess(this._blurY)}else this._blurY&&(this.removePostProcess(this._blurY),this._blurY.dispose(),this._blurY=null),this._blurX&&(this.removePostProcess(this._blurX),this._blurX.dispose(),this._blurX=null)}clone(){const e=this.getScene();if(!e)return this;const t=this.getSize(),i=new Cp(this.name,t.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i}serialize(){if(!this.name)return null;const e=super.serialize();return e.mirrorPlane=this.mirrorPlane.asArray(),e}dispose(){var e;super.dispose();const t=this.getScene();t&&t.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),null===(e=this._sceneUBO)||void 0===e||e.dispose()}}Le._CreateMirror=(e,t,i,n)=>new Cp(e,t,i,n);class yp extends Re{set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(o.y3.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 yp(n,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,n=!0){const s=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;const r=new yp(e,t,null,!1,null,null,null,void 0,!0,i,n);return t.useDelayedTextureLoading=s,r}constructor(e,t,i=null,n=!1,s=null,a=null,l=null,h=5,c=!1,d=null,u=!1,p=.8,f=0,_,m){var g;super(t),this._lodScale=.8,this._lodOffset=0,this.onLoadObservable=new r.y$,this.boundingBoxPosition=o.P.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new o.y3,this.name=e,this.url=e,this._noMipmap=n,this.hasAlpha=!1,this._format=h,this.isCube=!0,this._textureMatrix=o.y3.Identity(),this._createPolynomials=u,this.coordinatesMode=Le.CUBIC_MODE,this._extensions=i,this._files=s,this._forcedExtension=d,this._loaderOptions=_,this._useSRGBBuffer=m,this._lodScale=p,this._lodOffset=f,(e||s)&&this.updateURL(e,d,a,c,l,i,null===(g=this.getScene())||void 0===g?void 0:g.useDelayedTextureLoading,s)}getClassName(){return"CubeTexture"}updateURL(e,t,i=null,n=!1,s=null,r=null,o=!1,a=null){this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,t&&(this._forcedExtension=t);const l=e.lastIndexOf("."),h=t||(l>-1?e.substring(l).toLowerCase():""),c=0===h.indexOf(".dds"),d=0===h.indexOf(".env"),u=0===h.indexOf(".basis");if(d?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=n,n&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),a)this._files=a;else if(u||d||c||r||(r=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),this._files=this._files||[],this._files.length=0,r){for(let t=0;t-1!==e.getActiveTextures().indexOf(this)))),this._textureMatrix=e,!(null===(i=this.getScene())||void 0===i?void 0:i.useRightHandedSystem))return;const n=o.jp.Vector3[0],s=o.jp.Quaternion[0],r=o.jp.Vector3[1];this._textureMatrix.decompose(n,s,r),s.z*=-1,s.w*=-1,o.y3.ComposeToRef(n,s,r,this._textureMatrixRefraction)}getRefractionTextureMatrix(){var e;return(null===(e=this.getScene())||void 0===e?void 0:e.useRightHandedSystem)?this._textureMatrixRefraction:this._textureMatrix}_loadTexture(e=null,t=null){var i;const n=this.getScene(),s=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);const r=()=>{var t;this.onLoadObservable.notifyObservers(this),s&&(s.dispose(),null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1)),e&&e()},o=(e,i)=>{this._loadingError=!0,this._errorObject={message:e,exception:i},t&&t(e,i),Le.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?se.w1.SetImmediate((()=>r())):this._texture.onLoadedObservable.add((()=>r())):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,n,this._lodScale,this._lodOffset,e,o,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,n,this._files,this._noMipmap,e,o,this._format,this._forcedExtension,!1,this._lodScale,this._lodOffset,null,this._loaderOptions,!!this._useSRGBBuffer),null===(i=this._texture)||void 0===i||i.onLoadedObservable.add((()=>this.onLoadObservable.notifyObservers(this))))}static Parse(e,t,i){const n=E.p4.Parse((()=>{var n;let s=!1;return e.prefiltered&&(s=e.prefiltered),new yp(i+(null!==(n=e.url)&&void 0!==n?n:e.name),t,e.extensions,!1,e.files||null,null,null,void 0,s,e.forcedExtension)}),e,t);if(e.boundingBoxPosition&&(n.boundingBoxPosition=o.P.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(n.boundingBoxSize=o.P.FromArray(e.boundingBoxSize)),e.animations)for(let s=0;s{const t=new yp(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=t.uniqueId,t}),this);return t.uniqueId=e,t}}(0,oe.gn)([(0,E.qC)()],yp.prototype,"url",void 0),(0,oe.gn)([(0,E.hd)()],yp.prototype,"boundingBoxPosition",void 0),(0,oe.gn)([(0,E.hd)()],yp.prototype,"boundingBoxSize",null),(0,oe.gn)([(0,E.qC)("rotationY")],yp.prototype,"rotationY",null),(0,oe.gn)([(0,E.qC)("files")],yp.prototype,"_files",void 0),(0,oe.gn)([(0,E.qC)("forcedExtension")],yp.prototype,"_forcedExtension",void 0),(0,oe.gn)([(0,E.qC)("extensions")],yp.prototype,"_extensions",void 0),(0,oe.gn)([(0,E.oQ)("textureMatrix")],yp.prototype,"_textureMatrix",void 0),(0,oe.gn)([(0,E.oQ)("textureMatrixRefraction")],yp.prototype,"_textureMatrixRefraction",void 0),Le._CubeTextureParser=yp.Parse,(0,l.H)("BABYLON.CubeTexture",yp);const Ap="backgroundFragmentDeclaration",Rp="uniform vec4 vEyePosition;\nuniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n";Ht.v.IncludesShadersStore[Ap]=Rp;const Pp="backgroundUboDeclaration",Ip="layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\n#include\n";Ht.v.IncludesShadersStore[Pp]=Ip;const Mp="backgroundPixelShader",Op="#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#include\n#define RECIPROCAL_PI2 0.15915494\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV==1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV==2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include\n#include\n#include\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));\n}\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n#ifndef BACKMAT_SHADOWONLY\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=saturate(reflectionLOD);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition.xyz),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));\nconst float startAngle=0.1;\nfloat fadeFactor=saturate(viewAngleToFloor/startAngle);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\nvec4 color=vec4(finalColor,finalAlpha);\n#else\nvec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha);\n#endif\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n#if !defined(SKIPFINALCOLORCLAMP)\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#endif\n#else\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}\n";Ht.v.ShadersStore[Mp]=Op;const Dp="backgroundVertexDeclaration",Np="uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n";Ht.v.IncludesShadersStore[Dp]=Np;const Fp="backgroundVertexShader",wp="precision highp float;\n#include<__decl__backgroundVertex>\n#include\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nvarying vec2 vDiffuseUV;\n#endif\n#include\n#include\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif\n#include\n#include\n#include\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n} else {\ngl_Position=viewProjectionR*finalWorld*vec4(position,1.0);\n}\n#else\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#endif\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nif (vDiffuseInfos.x==0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";Ht.v.ShadersStore[Fp]=wp;class Lp extends Tt.H{constructor(){super(),this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.GAMMADIFFUSE=!1,this.DIFFUSEHASALPHA=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONBLUR=!1,this.REFLECTIONFRESNEL=!1,this.REFLECTIONFALLOFF=!1,this.TEXTURELODSUPPORT=!1,this.PREMULTIPLYALPHA=!1,this.USERGBCOLOR=!1,this.USEHIGHLIGHTANDSHADOWCOLORS=!1,this.BACKMAT_SHADOWONLY=!1,this.NOISE=!1,this.REFLECTIONBGR=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1,this.MULTIVIEW=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.EQUIRECTANGULAR_RELFECTION_FOV=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.UV1=!1,this.UV2=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.SHADOWFLOAT=!1,this.LOGARITHMICDEPTH=!1,this.NONUNIFORMSCALING=!1,this.ALPHATEST=!1,this.rebuild()}}class Bp extends pt{get _perceptualColor(){return this.__perceptualColor}set _perceptualColor(e){this.__perceptualColor=e,this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsLightsDirty()}get primaryColorShadowLevel(){return this._primaryColorShadowLevel}set primaryColorShadowLevel(e){this._primaryColorShadowLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}get primaryColorHighlightLevel(){return this._primaryColorHighlightLevel}set primaryColorHighlightLevel(e){this._primaryColorHighlightLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}set reflectionStandardFresnelWeight(e){let t=e;t<.5?(t*=2,this.reflectionReflectance0=Bp.StandardReflectance0*t,this.reflectionReflectance90=Bp.StandardReflectance90*t):(t=2*t-1,this.reflectionReflectance0=Bp.StandardReflectance0+(1-Bp.StandardReflectance0)*t,this.reflectionReflectance90=Bp.StandardReflectance90+(1-Bp.StandardReflectance90)*t)}get fovMultiplier(){return this._fovMultiplier}set fovMultiplier(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsImageProcessingDirty()}))))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this.imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this.imageProcessingConfiguration.colorCurves=e}constructor(e,t){super(e,t),this.primaryColor=a.Wo.White(),this._primaryColorShadowLevel=0,this._primaryColorHighlightLevel=0,this.reflectionTexture=null,this.reflectionBlur=0,this.diffuseTexture=null,this._shadowLights=null,this.shadowLights=null,this.shadowLevel=0,this.sceneCenter=o.P.Zero(),this.opacityFresnel=!0,this.reflectionFresnel=!1,this.reflectionFalloffDistance=0,this.reflectionAmount=1,this.reflectionReflectance0=.05,this.reflectionReflectance90=.5,this.useRGBColor=!0,this.enableNoise=!1,this._fovMultiplier=1,this.useEquirectangularFOV=!1,this._maxSimultaneousLights=4,this.maxSimultaneousLights=4,this._shadowOnly=!1,this.shadowOnly=!1,this._imageProcessingObserver=null,this.switchToBGR=!1,this._renderTargets=new Wt.t(16),this._reflectionControls=o.Lt.Zero(),this._white=a.Wo.White(),this._primaryShadowColor=a.Wo.Black(),this._primaryHighlightColor=a.Wo.Black(),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._renderTargets.push(this._diffuseTexture),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._renderTargets)}get hasRenderTargetTextures(){return!(!this._diffuseTexture||!this._diffuseTexture.isRenderTarget)||!(!this._reflectionTexture||!this._reflectionTexture.isRenderTarget)}needAlphaTesting(){return!0}needAlphaBlending(){return this.alpha<1||null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||this._shadowOnly}isReadyForSubMesh(e,t,i=!1){if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new Lp);const n=this.getScene(),s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const r=n.getEngine();if(It.G.PrepareDefinesForLights(n,e,s,!1,this._maxSimultaneousLights),s._needNormals=!0,It.G.PrepareDefinesForMultiview(n,s),s._areTexturesDirty){if(s._needUVs=!1,n.texturesEnabled){if(n.getEngine().getCaps().textureLOD&&(s.TEXTURELODSUPPORT=!0),this._diffuseTexture&&Bs.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;It.G.PrepareDefinesForMergedUV(this._diffuseTexture,s,"DIFFUSE"),s.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,s.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,s.OPACITYFRESNEL=this._opacityFresnel}else s.DIFFUSE=!1,s.DIFFUSEDIRECTUV=0,s.DIFFUSEHASALPHA=!1,s.GAMMADIFFUSE=!1,s.OPACITYFRESNEL=!1;const e=this._reflectionTexture;if(e&&Bs.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;switch(s.REFLECTION=!0,s.GAMMAREFLECTION=e.gammaSpace,s.RGBDREFLECTION=e.isRGBD,s.REFLECTIONBLUR=this._reflectionBlur>0,s.LODINREFLECTIONALPHA=e.lodLevelInAlpha,s.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,s.REFLECTIONBGR=this.switchToBGR,e.coordinatesMode===Le.INVCUBIC_MODE&&(s.INVERTCUBICMAP=!0),s.REFLECTIONMAP_3D=e.isCube,s.REFLECTIONMAP_OPPOSITEZ=s.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.invertZ,e.coordinatesMode){case Le.EXPLICIT_MODE:s.REFLECTIONMAP_EXPLICIT=!0;break;case Le.PLANAR_MODE:s.REFLECTIONMAP_PLANAR=!0;break;case Le.PROJECTION_MODE:s.REFLECTIONMAP_PROJECTION=!0;break;case Le.SKYBOX_MODE:s.REFLECTIONMAP_SKYBOX=!0;break;case Le.SPHERICAL_MODE:s.REFLECTIONMAP_SPHERICAL=!0;break;case Le.EQUIRECTANGULAR_MODE:s.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Le.FIXED_EQUIRECTANGULAR_MODE:s.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Le.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:s.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Le.CUBIC_MODE:case Le.INVCUBIC_MODE:default:s.REFLECTIONMAP_CUBIC=!0}this.reflectionFresnel?(s.REFLECTIONFRESNEL=!0,s.REFLECTIONFALLOFF=this.reflectionFalloffDistance>0,this._reflectionControls.x=this.reflectionAmount,this._reflectionControls.y=this.reflectionReflectance0,this._reflectionControls.z=this.reflectionReflectance90,this._reflectionControls.w=1/this.reflectionFalloffDistance):(s.REFLECTIONFRESNEL=!1,s.REFLECTIONFALLOFF=!1)}else s.REFLECTION=!1,s.REFLECTIONFRESNEL=!1,s.REFLECTIONFALLOFF=!1,s.REFLECTIONBLUR=!1,s.REFLECTIONMAP_3D=!1,s.REFLECTIONMAP_SPHERICAL=!1,s.REFLECTIONMAP_PLANAR=!1,s.REFLECTIONMAP_CUBIC=!1,s.REFLECTIONMAP_PROJECTION=!1,s.REFLECTIONMAP_SKYBOX=!1,s.REFLECTIONMAP_EXPLICIT=!1,s.REFLECTIONMAP_EQUIRECTANGULAR=!1,s.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,s.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,s.INVERTCUBICMAP=!1,s.REFLECTIONMAP_OPPOSITEZ=!1,s.LODINREFLECTIONALPHA=!1,s.GAMMAREFLECTION=!1,s.RGBDREFLECTION=!1}s.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,s.USERGBCOLOR=this._useRGBColor,s.NOISE=this._enableNoise}if(s._areLightsDirty&&(s.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel),s.BACKMAT_SHADOWONLY=this._shadowOnly),s._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(s)}if(It.G.PrepareDefinesForMisc(e,n,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),It.G.PrepareDefinesForFrameBoundValues(n,r,this,s,i,null,t.getRenderingMesh().hasThinInstances),It.G.PrepareDefinesForAttributes(e,s,!1,!0,!1)&&e&&(n.getEngine().getCaps().standardDerivatives||e.isVerticesDataPresent(ne.o.NormalKind)||(e.createNormals(!0),p.Y.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name))),s.isDirty){s.markAsProcessed(),n.resetCachedMaterial();const i=new zt;s.FOG&&i.addFallback(0,"FOG"),s.POINTSIZE&&i.addFallback(1,"POINTSIZE"),s.MULTIVIEW&&i.addFallback(0,"MULTIVIEW"),It.G.HandleFallbacksForShadows(s,i,this._maxSimultaneousLights);const o=[ne.o.PositionKind];s.NORMAL&&o.push(ne.o.NormalKind),s.UV1&&o.push(ne.o.UVKind),s.UV2&&o.push(ne.o.UV2Kind),It.G.PrepareAttributesForBones(o,e,s,i),It.G.PrepareAttributesForInstances(o,s);const a=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix"];(0,ua.qx)(a);const l=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],h=["Material","Scene"];ii.$&&(ii.$.PrepareUniforms(a,s),ii.$.PrepareSamplers(l,s)),It.G.PrepareUniformsAndSamplersList({uniformsNames:a,uniformBuffersNames:h,samplers:l,defines:s,maxSimultaneousLights:this._maxSimultaneousLights});const c=s.toString(),d=n.getEngine().createEffect("background",{attributes:o,uniformsNames:a,uniformBuffersNames:h,samplers:l,defines:c,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},r);t.setEffect(d,s,this._materialContext),this.buildUniformLayout()}return!(!t.effect||!t.effect.isReady())&&(s._renderId=n.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}_computePrimaryColorFromPerceptualColor(){this.__perceptualColor&&(this._primaryColor.copyFrom(this.__perceptualColor),this._primaryColor.toLinearSpaceToRef(this._primaryColor,this.getScene().getEngine().useExactSrgbConversions),this._imageProcessingConfiguration&&this._primaryColor.scaleToRef(1/this._imageProcessingConfiguration.exposure,this._primaryColor),this._computePrimaryColors())}_computePrimaryColors(){0===this._primaryColorShadowLevel&&0===this._primaryColorHighlightLevel||(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))}buildUniformLayout(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.create()}unbind(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),super.unbind()}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindForSubMesh(e,t,i){const n=this.getScene(),s=i.materialDefines;if(!s)return;const r=i.effect;if(!r)return;this._activeEffect=r,this.bindOnlyWorldMatrix(e),It.G.BindBonesParameters(t,this._activeEffect);const o=this._mustRebind(n,r,t.visibility);if(o){this._uniformBuffer.bindToEffect(r,"Material"),this.bindViewProjection(r);const e=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync||(n.texturesEnabled&&(this._diffuseTexture&&Bs.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),It.G.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse")),e&&Bs.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",e.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",e.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",e.getSize().width,e.lodGenerationScale,e.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),s.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),n.texturesEnabled&&(this._diffuseTexture&&Bs.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),e&&Bs.ReflectionTextureEnabled&&(s.REFLECTIONBLUR&&s.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",e):s.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",e._lodTextureMid||e),this._uniformBuffer.setTexture("reflectionSamplerLow",e._lodTextureLow||e),this._uniformBuffer.setTexture("reflectionSamplerHigh",e._lodTextureHigh||e)):this._uniformBuffer.setTexture("reflectionSampler",e),s.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w)))),(0,ua.an)(this._activeEffect,this,n),n.bindEyePosition(r)}else n.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(r,"Material"),this._needToBindSceneUbo=!0);!o&&this.isFrozen||(n.lightsEnabled&&It.G.BindLights(n,t,this._activeEffect,s,this._maxSimultaneousLights),this.bindView(r),It.G.BindFogParameters(n,t,this._activeEffect,!0),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),this._uniformBuffer.update()}hasTexture(e){return!!super.hasTexture(e)||(this._reflectionTexture===e||this._diffuseTexture===e)}dispose(e=!1,t=!1){t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return E.p4.Clone((()=>new Bp(e,this.getScene())),this)}serialize(){const e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return E.p4.Parse((()=>new Bp(e.name,t)),e,t,i)}}Bp.StandardReflectance0=.05,Bp.StandardReflectance90=.5,(0,oe.gn)([(0,E.n9)()],Bp.prototype,"_primaryColor",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsLightsDirty")],Bp.prototype,"primaryColor",void 0),(0,oe.gn)([(0,E.n9)()],Bp.prototype,"__perceptualColor",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_primaryColorShadowLevel",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_primaryColorHighlightLevel",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsLightsDirty")],Bp.prototype,"primaryColorHighlightLevel",null),(0,oe.gn)([(0,E.oU)()],Bp.prototype,"_reflectionTexture",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"reflectionTexture",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_reflectionBlur",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"reflectionBlur",void 0),(0,oe.gn)([(0,E.oU)()],Bp.prototype,"_diffuseTexture",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"diffuseTexture",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"shadowLights",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_shadowLevel",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"shadowLevel",void 0),(0,oe.gn)([(0,E.hd)()],Bp.prototype,"_sceneCenter",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"sceneCenter",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_opacityFresnel",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"opacityFresnel",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_reflectionFresnel",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"reflectionFresnel",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_reflectionFalloffDistance",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"reflectionFalloffDistance",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_reflectionAmount",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"reflectionAmount",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_reflectionReflectance0",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"reflectionReflectance0",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_reflectionReflectance90",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"reflectionReflectance90",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_useRGBColor",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"useRGBColor",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_enableNoise",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"enableNoise",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_maxSimultaneousLights",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],Bp.prototype,"maxSimultaneousLights",void 0),(0,oe.gn)([(0,E.qC)()],Bp.prototype,"_shadowOnly",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsLightsDirty")],Bp.prototype,"shadowOnly",void 0),(0,oe.gn)([(0,E.rX)()],Bp.prototype,"_imageProcessingConfiguration",void 0),(0,l.H)("BABYLON.BackgroundMaterial",Bp);class Up{static _GetDefaultOptions(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new a.Wo(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),groundOpacity:.9,enableGroundShadow:!0,groundShadowLevel:.5,enableGroundMirror:!1,groundMirrorSizeRatio:.3,groundMirrorBlurKernel:64,groundMirrorAmount:1,groundMirrorFresnelWeight:1,groundMirrorFallOffDistance:0,groundMirrorTextureType:0,groundYBias:1e-5,createSkybox:!0,skyboxSize:20,skyboxTexture:this._SkyboxTextureCDNUrl,skyboxColor:new a.Wo(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:o.P.Zero(),setupImageProcessing:!0,environmentTexture:this._EnvironmentTextureCDNUrl,cameraExposure:.8,cameraContrast:1.2,toneMappingEnabled:!0}}get rootMesh(){return this._rootMesh}get skybox(){return this._skybox}get skyboxTexture(){return this._skyboxTexture}get skyboxMaterial(){return this._skyboxMaterial}get ground(){return this._ground}get groundTexture(){return this._groundTexture}get groundMirror(){return this._groundMirror}get groundMirrorRenderList(){return this._groundMirror?this._groundMirror.renderList:null}get groundMaterial(){return this._groundMaterial}constructor(e,t){this._errorHandler=(e,t)=>{this.onErrorObservable.notifyObservers({message:e,exception:t})},this._options=Object.assign(Object.assign({},Up._GetDefaultOptions(t)),e),this._scene=t,this.onErrorObservable=new r.y$,this._setupBackground(),this._setupImageProcessing()}updateOptions(e){const t=Object.assign(Object.assign({},this._options),e);this._ground&&!t.createGround&&(this._ground.dispose(),this._ground=null),this._groundMaterial&&!t.createGround&&(this._groundMaterial.dispose(),this._groundMaterial=null),this._groundTexture&&this._options.groundTexture!=t.groundTexture&&(this._groundTexture.dispose(),this._groundTexture=null),this._skybox&&!t.createSkybox&&(this._skybox.dispose(),this._skybox=null),this._skyboxMaterial&&!t.createSkybox&&(this._skyboxMaterial.dispose(),this._skyboxMaterial=null),this._skyboxTexture&&this._options.skyboxTexture!=t.skyboxTexture&&(this._skyboxTexture.dispose(),this._skyboxTexture=null),this._groundMirror&&!t.enableGroundMirror&&(this._groundMirror.dispose(),this._groundMirror=null),this._scene.environmentTexture&&this._options.environmentTexture!=t.environmentTexture&&this._scene.environmentTexture.dispose(),this._options=t,this._setupBackground(),this._setupImageProcessing()}setMainColor(e){this.groundMaterial&&(this.groundMaterial.primaryColor=e),this.skyboxMaterial&&(this.skyboxMaterial.primaryColor=e),this.groundMirror&&(this.groundMirror.clearColor=new a.HE(e.r,e.g,e.b,1))}_setupImageProcessing(){this._options.setupImageProcessing&&(this._scene.imageProcessingConfiguration.contrast=this._options.cameraContrast,this._scene.imageProcessingConfiguration.exposure=this._options.cameraExposure,this._scene.imageProcessingConfiguration.toneMappingEnabled=this._options.toneMappingEnabled,this._setupEnvironmentTexture())}_setupEnvironmentTexture(){if(this._scene.environmentTexture)return;if(this._options.environmentTexture instanceof Re)return void(this._scene.environmentTexture=this._options.environmentTexture);const e=yp.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new ee.Kj("BackgroundHelper",this._scene)),this._rootMesh.rotation.y=this._options.backgroundYRotation;const e=this._getSceneSize();this._options.createGround&&(this._setupGround(e),this._setupGroundMaterial(),this._setupGroundDiffuseTexture(),this._options.enableGroundMirror&&this._setupGroundMirrorTexture(e),this._setupMirrorInGroundMaterial()),this._options.createSkybox&&(this._setupSkybox(e),this._setupSkyboxMaterial(),this._setupSkyboxReflectionTexture()),this._rootMesh.position.x=e.rootPosition.x,this._rootMesh.position.z=e.rootPosition.z,this._rootMesh.position.y=e.rootPosition.y}_getSceneSize(){let e=this._options.groundSize,t=this._options.skyboxSize,i=this._options.rootPosition;if(!this._scene.meshes||1===this._scene.meshes.length)return{groundSize:e,skyboxSize:t,rootPosition:i};const n=this._scene.getWorldExtends((e=>e!==this._ground&&e!==this._rootMesh&&e!==this._skybox)),s=n.max.subtract(n.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof Ln&&this._scene.activeCamera.upperRadiusLimit&&(e=2*this._scene.activeCamera.upperRadiusLimit,t=e);const r=s.length();r>e&&(e=2*r,t=e),e*=1.1,t*=1.5,i=n.min.add(s.scale(.5)),i.y=n.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:t,rootPosition:i}}_setupGround(e){this._ground&&!this._ground.isDisposed()||(this._ground=Je("BackgroundPlane",{size:e.groundSize},this._scene),this._ground.rotation.x=Math.PI/2,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add((()=>{this._ground=null}))),this._ground.receiveShadows=this._options.enableGroundShadow}_setupGroundMaterial(){this._groundMaterial||(this._groundMaterial=new Bp("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=8,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)}_setupGroundDiffuseTexture(){this._groundMaterial&&(this._groundTexture||(this._options.groundTexture instanceof Re?this._groundMaterial.diffuseTexture=this._options.groundTexture:(this._groundTexture=new Le(this._options.groundTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._groundTexture.gammaSpace=!1,this._groundTexture.hasAlpha=!0,this._groundMaterial.diffuseTexture=this._groundTexture)))}_setupGroundMirrorTexture(e){const t=Le.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new Cp("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,Le.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new Me.J(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.renderList))for(let n=0;n{this._skybox=null}))),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new Bp("BackgroundSkyboxMaterial",this._scene)),this._skyboxMaterial.useRGBColor=!1,this._skyboxMaterial.primaryColor=this._options.skyboxColor,this._skyboxMaterial.enableNoise=!0,this._skybox.material=this._skyboxMaterial)}_setupSkyboxReflectionTexture(){this._skyboxMaterial&&(this._skyboxTexture||(this._options.skyboxTexture instanceof Re?this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture:(this._skyboxTexture=new yp(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=Le.SKYBOX_MODE,this._skyboxTexture.gammaSpace=!1,this._skyboxMaterial.reflectionTexture=this._skyboxTexture)))}dispose(){this._groundMaterial&&this._groundMaterial.dispose(!0,!0),this._skyboxMaterial&&this._skyboxMaterial.dispose(!0,!0),this._rootMesh.dispose(!1)}}Up._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png",Up._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds",Up._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";class Vp extends te.Y{get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=Le.CLAMP_ADDRESSMODE,this._texture.wrapV=Le.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=Le.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=Le.CLAMP_ADDRESSMODE,this._material.reflectionTexture=this._texture),this._changeTextureMode(this._textureMode))}get mesh(){return this._mesh}get fovMultiplier(){return this._material.fovMultiplier}set fovMultiplier(e){this._material.fovMultiplier=e}get textureMode(){return this._textureMode}set textureMode(e){this._textureMode!==e&&this._changeTextureMode(e)}get halfDome(){return this._halfDome}set halfDome(e){this._halfDome=e,this._halfDomeMask.setEnabled(e),this._changeTextureMode(this._textureMode)}set crossEye(e){this._crossEye=e,this._changeTextureMode(this._textureMode)}get crossEye(){return this._crossEye}get material(){return this._material}constructor(e,t,i,n,s=null){super(e,n),this.onError=s,this._halfDome=!1,this._crossEye=!1,this._useDirectMapping=!1,this._textureMode=Vp.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new r.y$,this.onLoadObservable=new r.y$,n=this.getScene(),e=e||"textureDome",i.resolution=0|Math.abs(i.resolution)||32,i.clickToPlay=Boolean(i.clickToPlay),i.autoPlay=void 0===i.autoPlay||Boolean(i.autoPlay),i.loop=void 0===i.loop||Boolean(i.loop),i.size=Math.abs(i.size)||(n.activeCamera?.48*n.activeCamera.maxZ:1e3),void 0===i.useDirectMapping?this._useDirectMapping=!0:this._useDirectMapping=i.useDirectMapping,void 0===i.faceForward&&(i.faceForward=!0),this._setReady(!1),i.mesh?this._mesh=i.mesh:this._mesh=gl(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:ee.Kj.BACKSIDE},n);const a=this._material=new Bp(e+"_material",n);a.useEquirectangularFOV=!0,a.fovMultiplier=1,a.opacityFresnel=!1;const l=this._initTexture(t,n,i);if(this.texture=l,this._mesh.material=a,this._mesh.parent=this,this._halfDomeMask=gl("",{slice:.5,diameter:.98*i.size,segments:2*i.resolution,sideOrientation:ee.Kj.BACKSIDE},n),this._halfDomeMask.rotate(L.RD.X,-Math.PI/2),this._halfDomeMask.parent=this._mesh,this._halfDome=!!i.halfDomeMode,this._halfDomeMask.setEnabled(this._halfDome),this._crossEye=!!i.crossEyeMode,this._texture.anisotropicFilteringLevel=1,this._texture.onLoadObservable.addOnce((()=>{this._setReady(!0)})),i.faceForward&&n.activeCamera){const e=n.activeCamera,t=o.P.Forward(),i=o.P.TransformNormal(t,e.getViewMatrix());i.normalize(),this.rotation.y=Math.acos(o.P.Dot(t,i))}this._changeTextureMode(this._textureMode)}_changeTextureMode(e){switch(this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._textureMode=e,this._texture.uScale=1,this._texture.vScale=1,this._texture.uOffset=0,this._texture.vOffset=0,this._texture.vAng=0,e){case Vp.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case Vp.MODE_SIDEBYSIDE:{this._texture.uScale=this._halfDome?.99999:.5;const e=this._halfDome?0:.5,t=this._halfDome?-.5:0;this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add((i=>{let n=i.isRightCamera;this._crossEye&&(n=!n),this._texture.uOffset=n?e:t}));break}case Vp.MODE_TOPBOTTOM:this._texture.vScale=this._halfDome?.99999:.5,this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add((e=>{let t=e.isRightCamera;this._crossEye&&(t=!t),this._texture.vOffset=t?.5:0}))}}dispose(e,t=!1){this._texture.dispose(),this._mesh.dispose(),this._material.dispose(),this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this.onLoadErrorObservable.clear(),this.onLoadObservable.clear(),super.dispose(e,t)}}Vp.MODE_MONOSCOPIC=0,Vp.MODE_TOPBOTTOM=1,Vp.MODE_SIDEBYSIDE=2;class kp extends Vp{get photoTexture(){return this.texture}set photoTexture(e){this.texture=e}get imageMode(){return this.textureMode}set imageMode(e){this.textureMode=e}_initTexture(e,t,i){return new Le(e,t,!i.generateMipMaps,!this._useDirectMapping,void 0,(()=>{this.onLoadObservable.notifyObservers()}),((e,t)=>{this.onLoadErrorObservable.notifyObservers(e||"Unknown error occured"),this.onError&&this.onError(e,t)}))}}kp.MODE_MONOSCOPIC=Vp.MODE_MONOSCOPIC,kp.MODE_TOPBOTTOM=Vp.MODE_TOPBOTTOM,kp.MODE_SIDEBYSIDE=Vp.MODE_SIDEBYSIDE;let Gp=0;const zp=e=>{if(!e.environmentBRDFTexture){const t=e.useDelayedTextureLoading;e.useDelayedTextureLoading=!1;const i=e._blockEntityCollection;e._blockEntityCollection=!1;const n=Le.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/PHUgLY7wh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cqCyu0GcW45Igh6JMJmhA49/U+cEssHNJhtXDC1MOya3j/sAiAGcrEtqtgjBD6wEzSDc7D8o6C8rIqAZyPk+NQoNLAZ1hR64Yl1FBY648smUYKnSg1Xwk/0DyRyArByMUobyByhCcPnOaPyoegREFS4jNfYAw+IHCjdC1J2WDZBke/OyN85J24WiXwDYPoJyYuCD238ulvuzwt6KgHf0shWKsqCFFGjB/w8HU8eeTED9wAAAAABJRU5ErkJggg==","EnvironmentBRDFTexture"+Gp++,e,!0,!1,Le.BILINEAR_SAMPLINGMODE);e._blockEntityCollection=i;const s=e.getEngine().getLoadedTexturesCache(),r=s.indexOf(n.getInternalTexture());-1!==r&&s.splice(r,1),n.isRGBD=!0,n.wrapU=Le.CLAMP_ADDRESSMODE,n.wrapV=Le.CLAMP_ADDRESSMODE,e.environmentBRDFTexture=n,e.useDelayedTextureLoading=t,kh.ExpandRGBDTexture(n);const o=e.getEngine().onContextRestoredObservable.add((()=>{n.isRGBD=!0;const e=()=>{n.isReady()?kh.ExpandRGBDTexture(n):se.w1.SetImmediate(e)};e()}));e.onDisposeObservable.add((()=>{e.getEngine().onContextRestoredObservable.remove(o)}))}return e.environmentBRDFTexture};class Wp extends Tt.H{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 Hp extends ha{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRBRDF",90,new Wp,t),this._useEnergyConservation=Hp.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=Hp.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=Hp.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=Hp.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=Hp.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=Hp.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=Hp.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=Hp.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16],this._enable(!0)}prepareDefines(e){e.BRDF_V_HEIGHT_CORRELATED=this._useSmithVisibilityHeightCorrelated,e.MS_BRDF_ENERGY_CONSERVATION=this._useEnergyConservation&&this._useSmithVisibilityHeightCorrelated,e.SPHERICAL_HARMONICS=this._useSphericalHarmonics,e.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=this._useSpecularGlossinessInputEnergyConservation}getClassName(){return"PBRBRDFConfiguration"}}Hp.DEFAULT_USE_ENERGY_CONSERVATION=!0,Hp.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,Hp.DEFAULT_USE_SPHERICAL_HARMONICS=!0,Hp.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0,(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsMiscDirty")],Hp.prototype,"useEnergyConservation",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsMiscDirty")],Hp.prototype,"useSmithVisibilityHeightCorrelated",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsMiscDirty")],Hp.prototype,"useSphericalHarmonics",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsMiscDirty")],Hp.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);const Xp="pbrFragmentDeclaration",Yp="uniform vec4 vEyePosition;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec4 vMetallicReflectanceFactors;\nuniform vec3 vEmissiveColor;\nuniform float visibility;\nuniform vec3 vAmbientColor;\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform 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;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC)\nuniform vec3 vRefractionPosition;\nuniform vec3 vRefractionSize; \n#endif\n#ifdef CLEARCOAT\nuniform vec2 vClearCoatParams;\nuniform 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;\nuniform vec2 vClearCoatTangentSpaceParams;\nuniform mat4 clearCoatBumpMatrix;\n#endif\n#ifdef CLEARCOAT_TINT\nuniform vec4 vClearCoatTintParams;\nuniform float clearCoatColorAtDistance;\n#ifdef CLEARCOAT_TINT_TEXTURE\nuniform vec2 vClearCoatTintInfos;\nuniform 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;\nuniform 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;\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\n#ifdef REALTIME_FILTERING\nuniform vec2 vRefractionFilteringInfo;\n#endif\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nuniform vec2 vThicknessInfos;\nuniform mat4 thicknessMatrix;\n#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nuniform vec2 vRefractionIntensityInfos;\nuniform mat4 refractionIntensityMatrix;\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nuniform vec2 vTranslucencyIntensityInfos;\nuniform mat4 translucencyIntensityMatrix;\n#endif\nuniform vec2 vThicknessParam;\nuniform vec3 vDiffusionDistance;\nuniform vec4 vTintColor;\nuniform vec3 vSubSurfaceIntensity;\n#endif\n#ifdef PREPASS\n#ifdef SS_SCATTERING\nuniform float scatteringDiffusionProfile;\n#endif\n#endif\n#if DEBUGMODE>0\nuniform vec2 vDebugMode;\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\n#endif\n#include\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nuniform vec3 vSphericalL00;\nuniform vec3 vSphericalL1_1;\nuniform vec3 vSphericalL10;\nuniform vec3 vSphericalL11;\nuniform vec3 vSphericalL2_2;\nuniform vec3 vSphericalL2_1;\nuniform vec3 vSphericalL20;\nuniform vec3 vSphericalL21;\nuniform vec3 vSphericalL22;\n#else\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\n#endif\n#endif\n#define ADDITIONAL_FRAGMENT_DECLARATION\n";Ht.v.IncludesShadersStore[Xp]=Yp;const jp="pbrUboDeclaration",Kp="layout(std140,column_major) uniform;\nuniform Material {\nvec2 vAlbedoInfos;\nvec4 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec3 vReflectivityInfos;\nvec2 vMicroSurfaceSamplerInfos;\nvec2 vReflectionInfos;\nvec2 vReflectionFilteringInfo;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec3 vBumpInfos;\nmat4 albedoMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 reflectivityMatrix;\nmat4 microSurfaceSamplerMatrix;\nmat4 bumpMatrix;\nvec2 vTangentSpaceParams;\nmat4 reflectionMatrix;\nvec3 vReflectionColor;\nvec4 vAlbedoColor;\nvec4 vLightingIntensity;\nvec3 vReflectionMicrosurfaceInfos;\nfloat pointSize;\nvec4 vReflectivityColor;\nvec3 vEmissiveColor;\nvec3 vAmbientColor;\nvec2 vDebugMode;\nvec4 vMetallicReflectanceFactors;\nvec2 vMetallicReflectanceInfos;\nmat4 metallicReflectanceMatrix;\nvec2 vReflectanceInfos;\nmat4 reflectanceMatrix;\nvec3 vSphericalL00;\nvec3 vSphericalL1_1;\nvec3 vSphericalL10;\nvec3 vSphericalL11;\nvec3 vSphericalL2_2;\nvec3 vSphericalL2_1;\nvec3 vSphericalL20;\nvec3 vSphericalL21;\nvec3 vSphericalL22;\nvec3 vSphericalX;\nvec3 vSphericalY;\nvec3 vSphericalZ;\nvec3 vSphericalXX_ZZ;\nvec3 vSphericalYY_ZZ;\nvec3 vSphericalZZ;\nvec3 vSphericalXY;\nvec3 vSphericalYZ;\nvec3 vSphericalZX;\n#define ADDITIONAL_UBO_DECLARATION\n};\n#include\n#include\n";Ht.v.IncludesShadersStore[jp]=Kp;const qp="pbrFragmentExtraDeclaration",$p="varying vec3 vPositionW;\n#if DEBUGMODE>0\nvarying vec4 vClipSpacePosition;\n#endif\n#include[1..7]\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\n#endif\n";Ht.v.IncludesShadersStore[qp]=$p;const Qp="samplerFragmentAlternateDeclaration",Zp="#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";Ht.v.IncludesShadersStore[Qp]=Zp;const Jp="pbrFragmentSamplersDeclaration",ef="#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL)\nuniform sampler2D clearCoatRoughnessSampler;\n#endif\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL)\nuniform sampler2D sheenRoughnessSampler;\n#endif\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy)\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform 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;\nuniform 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;\nuniform 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;\nuniform sampler2D refractionSamplerHigh;\n#endif\n#endif\n#endif\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)\n#endif\n";Ht.v.IncludesShadersStore[Jp]=ef;const tf="subSurfaceScatteringFunctions",nf="bool testLightingForSSS(float diffusionProfile)\n{\nreturn diffusionProfile<1.;\n}";Ht.v.IncludesShadersStore[tf]=nf;const sf="importanceSampling",rf="vec3 hemisphereCosSample(vec2 u) {\nfloat phi=2.*PI*u.x;\nfloat cosTheta2=1.-u.y;\nfloat cosTheta=sqrt(cosTheta2);\nfloat sinTheta=sqrt(1.-cosTheta2);\nreturn vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);\n}\nvec3 hemisphereImportanceSampleDggx(vec2 u,float a) {\nfloat phi=2.*PI*u.x;\nfloat cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));\nfloat cosTheta=sqrt(cosTheta2);\nfloat sinTheta=sqrt(1.-cosTheta2);\nreturn vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);\n}\nvec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { \nfloat phi=2.*PI*u.x;\nfloat sinTheta=pow(u.y,a/(2.*a+1.));\nfloat cosTheta=sqrt(1.-sinTheta*sinTheta);\nreturn vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);\n}";Ht.v.IncludesShadersStore[sf]=rf;const of="pbrHelperFunctions",af="#define RECIPROCAL_PI2 0.15915494\n#define RECIPROCAL_PI 0.31830988618\n#define MINIMUMVARIANCE 0.0005\nfloat convertRoughnessToAverageSlope(float roughness)\n{\nreturn square(roughness)+MINIMUMVARIANCE;\n}\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=saturate(reflectance0*25.0);\nreturn reflectance90;\n}\nvec2 getAARoughnessFactors(vec3 normalVector) {\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalVector.xyz);\nvec3 nDfdy=dFdy(normalVector.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\nfloat geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\ngeometricAlphaGFactor*=0.75;\nreturn vec2(geometricRoughnessFactor,geometricAlphaGFactor);\n#else\nreturn vec2(0.);\n#endif\n}\n#ifdef ANISOTROPIC\n#ifdef ANISOTROPIC_LEGACY\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {\nfloat alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);\nfloat alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);\nreturn vec2(alphaT,alphaB);\n}\nvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {\nvec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;\nvec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);\nvec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);\nvec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));\nreturn anisotropicNormal;\n}\n#else\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {\nfloat alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);\nfloat alphaB=max(alphaG,MINIMUMVARIANCE);\nreturn vec2(alphaT,alphaB);\n}\nvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {\nvec3 bentNormal=cross(B,V);\nbentNormal=normalize(cross(bentNormal,B));\nfloat a=square(square(1.0-anisotropy*(1.0-roughness)));\nbentNormal=normalize(mix(bentNormal,N,a));\nreturn bentNormal;\n}\n#endif\n#endif\n#if defined(CLEARCOAT) || defined(SS_REFRACTION)\nvec3 cocaLambert(vec3 alpha,float distance) {\nreturn exp(-alpha*distance);\n}\nvec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {\nreturn cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));\n}\nvec3 computeColorAtDistanceInMedia(vec3 color,float distance) {\nreturn -log(color)/distance;\n}\nvec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {\nvec3 clearCoatAbsorption=mix(vec3(1.0),\ncocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),\nclearCoatIntensity);\nreturn clearCoatAbsorption;\n}\n#endif\n#ifdef MICROSURFACEAUTOMATIC\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n#endif\n";Ht.v.IncludesShadersStore[of]=af;const lf="harmonicsFunctions",hf="#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nvec3 computeEnvironmentIrradiance(vec3 normal) {\nreturn 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}\n#else\nvec3 computeEnvironmentIrradiance(vec3 normal) {\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz *Nz+C1;\nvec3 t2=a2 *Ny+t1;\nvec3 t3=b3 *Nx+t2;\nreturn t3;\n}\n#endif\n#endif\n";Ht.v.IncludesShadersStore[lf]=hf;const cf="pbrDirectLightingSetupFunctions",df="struct preLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nfloat lightDistance;\nfloat attenuation;\nvec3 L;\nvec3 H;\nfloat NdotV;\nfloat NdotLUnclamped;\nfloat NdotL;\nfloat VdotH;\nfloat roughness;\n#ifdef IRIDESCENCE\nfloat iridescenceIntensity;\n#endif\n};\npreLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {\npreLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nresult.lightDistance=sqrt(result.lightDistanceSquared);\nresult.L=normalize(result.lightOffset);\nresult.H=normalize(V+result.L);\nresult.VdotH=saturate(dot(V,result.H));\nresult.NdotLUnclamped=dot(N,result.L);\nresult.NdotL=saturateEps(result.NdotLUnclamped);\nreturn result;\n}\npreLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {\npreLightingInfo result;\nresult.lightDistance=length(-lightData.xyz);\nresult.L=normalize(-lightData.xyz);\nresult.H=normalize(V+result.L);\nresult.VdotH=saturate(dot(V,result.H));\nresult.NdotLUnclamped=dot(N,result.L);\nresult.NdotL=saturateEps(result.NdotLUnclamped);\nreturn result;\n}\npreLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {\npreLightingInfo result;\nresult.NdotL=dot(N,lightData.xyz)*0.5+0.5;\nresult.NdotL=saturateEps(result.NdotL);\nresult.NdotLUnclamped=result.NdotL;\n#ifdef SPECULARTERM\nresult.L=normalize(lightData.xyz);\nresult.H=normalize(V+result.L);\nresult.VdotH=saturate(dot(V,result.H));\n#endif\nreturn result;\n}";Ht.v.IncludesShadersStore[cf]=df;const uf="pbrDirectLightingFalloffFunctions",pf="float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{\nreturn max(0.,1.0-length(lightOffset)/range);\n}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{\nreturn 1.0/maxEps(lightDistanceSquared);\n}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{\nfloat lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);\nfloat factor=lightDistanceSquared*inverseSquaredRange;\nfloat attenuation=saturate(1.0-factor*factor);\nattenuation*=attenuation;\nlightDistanceFalloff*=attenuation;\nreturn lightDistanceFalloff;\n}\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{\nfloat falloff=0.0;\nfloat cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfloat falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{\nfloat cd=dot(-lightDirection,directionToLightCenterW);\nfloat falloff=saturate(cd*lightAngleScale+lightAngleOffset);\nfalloff*=falloff;\nreturn falloff;\n}\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}";Ht.v.IncludesShadersStore[uf]=pf;const ff="pbrBRDFFunctions",_f="#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n#ifdef MS_BRDF_ENERGY_CONSERVATION\nvec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {\nreturn 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);\n}\n#endif\n#ifdef ENVIRONMENTBRDF\nvec3 getBRDFLookup(float NdotV,float perceptualRoughness) {\nvec2 UV=vec2(NdotV,perceptualRoughness);\nvec4 brdfLookup=texture2D(environmentBrdfSampler,UV);\n#ifdef ENVIRONMENTBRDF_RGBD\nbrdfLookup.rgb=fromRGBD(brdfLookup.rgba);\n#endif\nreturn brdfLookup.rgb;\n}\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;\n}\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}\n#endif\n/* NOT USED\n#if defined(SHEEN) && defined(SHEEN_SOFTER)\nfloat getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness)\n{\nfloat c=1.0-NdotV;\nfloat c3=c*c*c;\nreturn 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));\n}\n#endif\n*/\n#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL)\nvec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));\n}\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) {\nvec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;\nreturn sheenEnvironmentReflectance;\n}\n#endif\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);\n}\nfloat fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);\n}\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);\nvec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);\nreturn 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);\nvec3 getIORTfromAirToSurfaceR0(vec3 f0) {\nvec3 sqrtF0=sqrt(f0);\nreturn (1.+sqrtF0)/(1.-sqrtF0);\n}\nvec3 getR0fromIORs(vec3 iorT,float iorI) {\nreturn square((iorT-vec3(iorI))/(iorT+vec3(iorI)));\n}\nfloat getR0fromIORs(float iorT,float iorI) {\nreturn square((iorT-iorI)/(iorT+iorI));\n}\nvec3 evalSensitivity(float opd,vec3 shift) {\nfloat phase=2.0*PI*opd*1.0e-9;\nconst vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);\nconst vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);\nconst vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);\nvec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);\nxyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));\nxyz/=1.0685e-7;\nvec3 srgb=XYZ_TO_REC709*xyz;\nreturn srgb;\n}\nvec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {\nvec3 I=vec3(1.0);\nfloat iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));\nfloat sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));\nfloat cosTheta2Sq=1.0-sinTheta2Sq;\nif (cosTheta2Sq<0.0) {\nreturn I;\n}\nfloat cosTheta2=sqrt(cosTheta2Sq);\nfloat R0=getR0fromIORs(iridescenceIOR,outsideIOR);\nfloat R12=fresnelSchlickGGX(cosTheta1,R0,1.);\nfloat R21=R12;\nfloat T121=1.0-R12;\nfloat phi12=0.0;\nif (iridescenceIOR0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._tintTexture&&this._tintTexture.animations&&this._tintTexture.animations.length>0&&e.push(this._tintTexture)}dispose(e){var t,i,n,s;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._textureRoughness)||void 0===i||i.dispose(),null===(n=this._bumpTexture)||void 0===n||n.dispose(),null===(s=this._tintTexture)||void 0===s||s.dispose())}getClassName(){return"PBRClearCoatConfiguration"}addFallbacks(e,t,i){return e.CLEARCOAT_BUMP&&t.addFallback(i++,"CLEARCOAT_BUMP"),e.CLEARCOAT_TINT&&t.addFallback(i++,"CLEARCOAT_TINT"),e.CLEARCOAT&&t.addFallback(i++,"CLEARCOAT"),i}getSamplers(e){e.push("clearCoatSampler","clearCoatRoughnessSampler","clearCoatBumpSampler","clearCoatTintSampler")}getUniforms(){return{ubo:[{name:"vClearCoatParams",size:2,type:"vec2"},{name:"vClearCoatRefractionParams",size:4,type:"vec4"},{name:"vClearCoatInfos",size:4,type:"vec4"},{name:"clearCoatMatrix",size:16,type:"mat4"},{name:"clearCoatRoughnessMatrix",size:16,type:"mat4"},{name:"vClearCoatBumpInfos",size:2,type:"vec2"},{name:"vClearCoatTangentSpaceParams",size:2,type:"vec2"},{name:"clearCoatBumpMatrix",size:16,type:"mat4"},{name:"vClearCoatTintParams",size:4,type:"vec4"},{name:"clearCoatColorAtDistance",size:1,type:"float"},{name:"vClearCoatTintInfos",size:2,type:"vec2"},{name:"clearCoatTintMatrix",size:16,type:"mat4"}]}}}T_._DefaultIndexOfRefraction=1.5,(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],T_.prototype,"isEnabled",void 0),(0,oe.gn)([(0,E.qC)()],T_.prototype,"intensity",void 0),(0,oe.gn)([(0,E.qC)()],T_.prototype,"roughness",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],T_.prototype,"indexOfRefraction",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],T_.prototype,"texture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],T_.prototype,"useRoughnessFromMainTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],T_.prototype,"textureRoughness",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],T_.prototype,"remapF0OnInterfaceChange",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],T_.prototype,"bumpTexture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],T_.prototype,"isTintEnabled",void 0),(0,oe.gn)([(0,E.n9)()],T_.prototype,"tintColor",void 0),(0,oe.gn)([(0,E.qC)()],T_.prototype,"tintColorAtDistance",void 0),(0,oe.gn)([(0,E.qC)()],T_.prototype,"tintThickness",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],T_.prototype,"tintTexture",void 0);class S_ extends Tt.H{constructor(){super(...arguments),this.IRIDESCENCE=!1,this.IRIDESCENCE_TEXTURE=!1,this.IRIDESCENCE_TEXTUREDIRECTUV=0,this.IRIDESCENCE_THICKNESS_TEXTURE=!1,this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0,this.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE=!1}}class E_ extends ha{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRIridescence",110,new S_,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=E_._DefaultMinimumThickness,this.maximumThickness=E_._DefaultMaximumThickness,this.indexOfRefraction=E_._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&Bs.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._thicknessTexture&&Bs.IridescenceTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){var i;this._isEnabled?(e.IRIDESCENCE=!0,e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE=null!==this._texture&&this._texture._texture===(null===(i=this._thicknessTexture)||void 0===i?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._thicknessTexture),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Bs.IridescenceTextureEnabled?It.G.PrepareDefinesForMergedUV(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,!e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&this._thicknessTexture&&Bs.IridescenceTextureEnabled?It.G.PrepareDefinesForMergedUV(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_USE_THICKNESS_FROM_MAINTEXTURE=!1,e.IRIDESCENCE_TEXTUREDIRECTUV=0,e.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0)}bindForSubMesh(e,t,i,n){var s,r,o,a,l,h,c,d;if(!this._isEnabled)return;const u=n.materialDefines,p=this._material.isFrozen,f=u.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE;e.useUbo&&p&&e.isSync||(f&&Bs.IridescenceTextureEnabled?(e.updateFloat4("vIridescenceInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),It.G.BindTextureMatrix(this._texture,e,"iridescence")):(this._texture||this._thicknessTexture)&&Bs.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",null!==(r=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==r?r:0,null!==(a=null===(o=this._texture)||void 0===o?void 0:o.level)&&void 0!==a?a:0,null!==(h=null===(l=this._thicknessTexture)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(d=null===(c=this._thicknessTexture)||void 0===c?void 0:c.level)&&void 0!==d?d:0),this._texture&&It.G.BindTextureMatrix(this._texture,e,"iridescence"),!this._thicknessTexture||f||u.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE||It.G.BindTextureMatrix(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&Bs.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&!f&&!u.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&Bs.IridescenceTextureEnabled&&e.setTexture("iridescenceThicknessSampler",this._thicknessTexture))}hasTexture(e){return this._texture===e||this._thicknessTexture===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._thicknessTexture&&e.push(this._thicknessTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture)}dispose(e){var t,i;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._thicknessTexture)||void 0===i||i.dispose())}getClassName(){return"PBRIridescenceConfiguration"}addFallbacks(e,t,i){return e.IRIDESCENCE&&t.addFallback(i++,"IRIDESCENCE"),i}getSamplers(e){e.push("iridescenceSampler","iridescenceThicknessSampler")}getUniforms(){return{ubo:[{name:"vIridescenceParams",size:4,type:"vec4"},{name:"vIridescenceInfos",size:4,type:"vec4"},{name:"iridescenceMatrix",size:16,type:"mat4"},{name:"iridescenceThicknessMatrix",size:16,type:"mat4"}]}}}E_._DefaultMinimumThickness=100,E_._DefaultMaximumThickness=400,E_._DefaultIndexOfRefraction=1.3,(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],E_.prototype,"isEnabled",void 0),(0,oe.gn)([(0,E.qC)()],E_.prototype,"intensity",void 0),(0,oe.gn)([(0,E.qC)()],E_.prototype,"minimumThickness",void 0),(0,oe.gn)([(0,E.qC)()],E_.prototype,"maximumThickness",void 0),(0,oe.gn)([(0,E.qC)()],E_.prototype,"indexOfRefraction",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],E_.prototype,"texture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],E_.prototype,"thicknessTexture",void 0);class x_ extends Tt.H{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}}class b_ extends ha{set angle(e){this.direction.x=Math.cos(e),this.direction.y=Math.sin(e)}get angle(){return Math.atan2(this.direction.y,this.direction.x)}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markAllSubMeshesAsMiscDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRAnisotropic",110,new x_,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new o.FM(1,0),this._texture=null,this.texture=null,this._legacy=!1,this.legacy=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16]}isReadyForSubMesh(e,t){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&this._texture&&Bs.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(ne.o.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Bs.AnisotropicTextureEnabled?It.G.PrepareDefinesForMergedUV(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&&Bs.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),It.G.BindTextureMatrix(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&Bs.AnisotropicTextureEnabled&&e.setTexture("anisotropySampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){e&&this._texture&&this._texture.dispose()}getClassName(){return"PBRAnisotropicConfiguration"}addFallbacks(e,t,i){return e.ANISOTROPIC&&t.addFallback(i++,"ANISOTROPIC"),i}getSamplers(e){e.push("anisotropySampler")}getUniforms(){return{ubo:[{name:"vAnisotropy",size:3,type:"vec3"},{name:"vAnisotropyInfos",size:2,type:"vec2"},{name:"anisotropyMatrix",size:16,type:"mat4"}]}}parse(e,t,i){super.parse(e,t,i),void 0===e.legacy&&(this.legacy=!0)}}(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],b_.prototype,"isEnabled",void 0),(0,oe.gn)([(0,E.qC)()],b_.prototype,"intensity",void 0),(0,oe.gn)([(0,E.QC)()],b_.prototype,"direction",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],b_.prototype,"texture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsMiscDirty")],b_.prototype,"legacy",void 0);class C_ extends Tt.H{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,this.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=!1}}class y_ extends ha{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"Sheen",120,new C_,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=a.Wo.White(),this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._roughness=null,this.roughness=null,this._textureRoughness=null,this.textureRoughness=null,this._albedoScaling=!1,this.albedoScaling=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&Bs.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._textureRoughness&&Bs.SheenTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){var i;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.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=null!==this._texture&&this._texture._texture===(null===(i=this._textureRoughness)||void 0===i?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._textureRoughness),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Bs.SheenTextureEnabled?(It.G.PrepareDefinesForMergedUV(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&Bs.SheenTextureEnabled?It.G.PrepareDefinesForMergedUV(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_TEXTURE_ROUGHNESS_IDENTICAL=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,i,n){var s,r,o,a,l,h,c,d;if(!this._isEnabled)return;const u=n.materialDefines,p=this._material.isFrozen,f=u.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL;e.useUbo&&p&&e.isSync||(f&&Bs.SheenTextureEnabled?(e.updateFloat4("vSheenInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),It.G.BindTextureMatrix(this._texture,e,"sheen")):(this._texture||this._textureRoughness)&&Bs.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",null!==(r=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==r?r:0,null!==(a=null===(o=this._texture)||void 0===o?void 0:o.level)&&void 0!==a?a:0,null!==(h=null===(l=this._textureRoughness)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(d=null===(c=this._textureRoughness)||void 0===c?void 0:c.level)&&void 0!==d?d:0),this._texture&&It.G.BindTextureMatrix(this._texture,e,"sheen"),!this._textureRoughness||f||u.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE||It.G.BindTextureMatrix(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&&Bs.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!f&&!u.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&Bs.SheenTextureEnabled&&e.setTexture("sheenRoughnessSampler",this._textureRoughness))}hasTexture(e){return this._texture===e||this._textureRoughness===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness)}dispose(e){var t,i;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._textureRoughness)||void 0===i||i.dispose())}getClassName(){return"PBRSheenConfiguration"}addFallbacks(e,t,i){return e.SHEEN&&t.addFallback(i++,"SHEEN"),i}getSamplers(e){e.push("sheenSampler","sheenRoughnessSampler")}getUniforms(){return{ubo:[{name:"vSheenColor",size:4,type:"vec4"},{name:"vSheenRoughness",size:1,type:"float"},{name:"vSheenInfos",size:4,type:"vec4"},{name:"sheenMatrix",size:16,type:"mat4"},{name:"sheenRoughnessMatrix",size:16,type:"mat4"}]}}}(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],y_.prototype,"isEnabled",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],y_.prototype,"linkSheenWithAlbedo",void 0),(0,oe.gn)([(0,E.qC)()],y_.prototype,"intensity",void 0),(0,oe.gn)([(0,E.n9)()],y_.prototype,"color",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],y_.prototype,"texture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],y_.prototype,"useRoughnessFromMainTexture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],y_.prototype,"roughness",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],y_.prototype,"textureRoughness",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],y_.prototype,"albedoScaling",void 0);class A_ extends Tt.H{constructor(){super(...arguments),this.SUBSURFACE=!1,this.SS_REFRACTION=!1,this.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,this.SS_TRANSLUCENCY=!1,this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!1,this.SS_SCATTERING=!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_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_MASK_FROM_THICKNESS_TEXTURE=!1,this.SS_USE_GLTF_TEXTURES=!1}}class R_ extends ha{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()}constructor(e,t=!0){super(e,"PBRSubSurface",130,new A_,t),this._isRefractionEnabled=!1,this.isRefractionEnabled=!1,this._isTranslucencyEnabled=!1,this.isTranslucencyEnabled=!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=a.Wo.White(),this.tintColorAtDistance=1,this.diffusionDistance=a.Wo.White(),this._useMaskFromThicknessTexture=!1,this.useMaskFromThicknessTexture=!1,this._refractionIntensityTexture=null,this.refractionIntensityTexture=null,this._translucencyIntensityTexture=null,this.translucencyIntensityTexture=null,this._useGltfStyleTextures=!1,this.useGltfStyleTextures=!1,this._scene=e.getScene(),this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkScenePrePassDirty=e._dirtyCallbacks[32]}isReadyForSubMesh(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&Bs.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;const e=this._getRefractionTexture(t);if(e&&Bs.RefractionTextureEnabled&&!e.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return e.SUBSURFACE=!1,e.SS_TRANSLUCENCY=!1,e.SS_SCATTERING=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!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_MASK_FROM_THICKNESS_TEXTURE=!1,void(e.SS_USE_GLTF_TEXTURES=!1);if(e._areTexturesDirty){e.SUBSURFACE=!0,e.SS_TRANSLUCENCY=this._isTranslucencyEnabled,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!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_MASK_FROM_THICKNESS_TEXTURE=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!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;const i=!!this._thicknessTexture&&!!this._refractionIntensityTexture&&this._refractionIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._refractionIntensityTexture._texture===this._thicknessTexture._texture,n=!!this._thicknessTexture&&!!this._translucencyIntensityTexture&&this._translucencyIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._translucencyIntensityTexture._texture===this._thicknessTexture._texture,s=(i||!this._refractionIntensityTexture)&&(n||!this._translucencyIntensityTexture);if(e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&Bs.ThicknessTextureEnabled&&It.G.PrepareDefinesForMergedUV(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&Bs.RefractionIntensityTextureEnabled&&!s&&It.G.PrepareDefinesForMergedUV(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&Bs.TranslucencyIntensityTextureEnabled&&!s&&It.G.PrepareDefinesForMergedUV(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE")),e.SS_HAS_THICKNESS=this.maximumThickness-this.minimumThickness!=0,e.SS_MASK_FROM_THICKNESS_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture||!!this._translucencyIntensityTexture)&&s,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture)&&s,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._translucencyIntensityTexture)&&s,this._isRefractionEnabled&&t.texturesEnabled){const i=this._getRefractionTexture(t);i&&Bs.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)return;n.getRenderingMesh().getWorldMatrix().decompose(o.jp.Vector3[0]);const s=Math.max(Math.abs(o.jp.Vector3[0].x),Math.abs(o.jp.Vector3[0].y),Math.abs(o.jp.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*s,(this.maximumThickness-this.minimumThickness)*s)}bindForSubMesh(e,t,i,n){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;const s=n.materialDefines,r=this._material.isFrozen,o=this._material.realTimeFiltering,a=s.LODBASEDMICROSFURACE,l=this._getRefractionTexture(t);if(!e.useUbo||!r||!e.isSync){if(this._thicknessTexture&&Bs.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),It.G.BindTextureMatrix(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&Bs.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),It.G.BindTextureMatrix(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyIntensityTexture&&Bs.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),It.G.BindTextureMatrix(this._translucencyIntensityTexture,e,"translucencyIntensity")),l&&Bs.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),o&&e.updateFloat2("vRefractionFilteringInfo",i,S.R.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.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,0)}t.texturesEnabled&&(this._thicknessTexture&&Bs.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&Bs.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&Bs.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),l&&Bs.RefractionTextureEnabled&&(a?e.setTexture("refractionSampler",l):(e.setTexture("refractionSampler",l._lodTextureMid||l),e.setTexture("refractionSamplerLow",l._lodTextureLow||l),e.setTexture("refractionSamplerHigh",l._lodTextureHigh||l))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){Bs.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e}hasRenderTargetTextures(){return!!(Bs.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)}getActiveTextures(e){this._thicknessTexture&&e.push(this._thicknessTexture),this._refractionTexture&&e.push(this._refractionTexture)}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)}dispose(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.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")}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"}]}}}(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],R_.prototype,"isRefractionEnabled",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],R_.prototype,"isTranslucencyEnabled",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markScenePrePassDirty")],R_.prototype,"isScatteringEnabled",void 0),(0,oe.gn)([(0,E.qC)()],R_.prototype,"_scatteringDiffusionProfileIndex",void 0),(0,oe.gn)([(0,E.qC)()],R_.prototype,"refractionIntensity",void 0),(0,oe.gn)([(0,E.qC)()],R_.prototype,"translucencyIntensity",void 0),(0,oe.gn)([(0,E.qC)()],R_.prototype,"useAlbedoToTintRefraction",void 0),(0,oe.gn)([(0,E.qC)()],R_.prototype,"useAlbedoToTintTranslucency",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],R_.prototype,"thicknessTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],R_.prototype,"refractionTexture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],R_.prototype,"indexOfRefraction",void 0),(0,oe.gn)([(0,E.qC)()],R_.prototype,"_volumeIndexOfRefraction",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],R_.prototype,"volumeIndexOfRefraction",null),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],R_.prototype,"invertRefractionY",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],R_.prototype,"linkRefractionWithTransparency",void 0),(0,oe.gn)([(0,E.qC)()],R_.prototype,"minimumThickness",void 0),(0,oe.gn)([(0,E.qC)()],R_.prototype,"maximumThickness",void 0),(0,oe.gn)([(0,E.qC)()],R_.prototype,"useThicknessAsDepth",void 0),(0,oe.gn)([(0,E.n9)()],R_.prototype,"tintColor",void 0),(0,oe.gn)([(0,E.qC)()],R_.prototype,"tintColorAtDistance",void 0),(0,oe.gn)([(0,E.n9)()],R_.prototype,"diffusionDistance",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],R_.prototype,"useMaskFromThicknessTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],R_.prototype,"refractionIntensityTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],R_.prototype,"translucencyIntensityTexture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],R_.prototype,"useGltfStyleTextures",void 0);const P_={effect:null,subMesh:null};class I_ extends Tt.H{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.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_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=!1,this.TONEMAPPING_ACES=!1,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.DEBUGMODE=0,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0}}class M_ extends pt{get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(1)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)}get canRenderToMRT(){return!0}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}constructor(e,t){super(e,t),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new o.Lt(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=M_.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=a.Wo.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new a.Wo(0,0,0),this._albedoColor=new a.Wo(1,1,1),this._reflectivityColor=new a.Wo(1,1,1),this._reflectionColor=new a.Wo(1,1,1),this._emissiveColor=new a.Wo(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=M_.LIGHTFALLOFF_PHYSICAL,this._useRadianceOverAlpha=!0,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this._parallaxScaleBias=.05,this._disableLighting=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._alphaCutOff=.4,this._forceAlphaTest=!1,this._useAlphaFresnel=!1,this._useLinearAlphaFresnel=!1,this._environmentBRDFTexture=null,this._forceIrradianceInFragment=!1,this._realTimeFiltering=!1,this._realTimeFilteringQuality=8,this._forceNormalForward=!1,this._enableSpecularAntiAliasing=!1,this._imageProcessingObserver=null,this._renderTargets=new Wt.t(16),this._globalAmbientColor=new a.Wo(0,0,0),this._useLogarithmicDepth=!1,this._unlit=!1,this._debugMode=0,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new Hp(this),this.clearCoat=new T_(this),this.iridescence=new E_(this),this.anisotropy=new b_(this),this.sheen=new y_(this),this.subSurface=new R_(this),this.detailMap=new da(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),Bs.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=zp(this.getScene()),this.prePassConfiguration=new ws}get hasRenderTargetTextures(){return!!(Bs.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported}get _disableAlphaBlending(){var e;return this._transparencyMode===M_.PBRMATERIAL_OPAQUE||this._transparencyMode===M_.PBRMATERIAL_ALPHATEST||(null===(e=this.subSurface)||void 0===e?void 0:e.disableAlphaBlending)}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromAlbedoTexture())}needAlphaTesting(){var e;return!!this._forceAlphaTest||!(null===(e=this.subSurface)||void 0===e?void 0:e.disableAlphaBlending)&&(this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===M_.PBRMATERIAL_ALPHATEST))}_shouldUseAlphaFromAlbedoTexture(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==M_.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){var n;if(this._uniformBufferLayoutBuilt||this.buildUniformLayout(),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(Ls.S.GetDefineNames,this._eventInfo),t.materialDefines=new I_(this._eventInfo.defineNames));const s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const r=this.getScene(),o=r.getEngine();if(s._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,r.texturesEnabled)){if(this._albedoTexture&&Bs.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking())return!1;if(this._ambientTexture&&Bs.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking())return!1;if(this._opacityTexture&&Bs.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;const e=this._getReflectionTexture();if(e&&Bs.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;if(e.irradianceTexture){if(!e.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!e.sphericalPolynomial&&(null===(n=e.getInternalTexture())||void 0===n?void 0:n._sphericalPolynomialPromise))return!1}if(this._lightmapTexture&&Bs.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking())return!1;if(this._emissiveTexture&&Bs.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(Bs.SpecularTextureEnabled){if(this._metallicTexture){if(!this._metallicTexture.isReadyOrNotBlocking())return!1}else if(this._reflectivityTexture&&!this._reflectivityTexture.isReadyOrNotBlocking())return!1;if(this._metallicReflectanceTexture&&!this._metallicReflectanceTexture.isReadyOrNotBlocking())return!1;if(this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking())return!1;if(this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(o.getCaps().standardDerivatives&&this._bumpTexture&&Bs.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady())return!1;if(this._environmentBRDFTexture&&Bs.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(s._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;o.getCaps().standardDerivatives||e.isVerticesDataPresent(ne.o.NormalKind)||(e.createNormals(!0),p.Y.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));const a=t.effect,l=s._areLightsDisposed;let h=this._prepareEffect(e,s,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),c=!1;if(h)if(this._onEffectCreatedObservable&&(P_.effect=h,P_.subMesh=t,this._onEffectCreatedObservable.notifyObservers(P_)),this.allowShaderHotSwapping&&a&&!h.isReady()){if(h=a,s.markAsUnprocessed(),c=this.isFrozen,l)return s._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(h,s,this._materialContext);return!(!t.effect||!t.effect.isReady())&&(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!c,t.effect._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),!0)}isMetallicWorkflow(){return!(null==this._metallic&&null==this._roughness&&!this._metallicTexture)}_prepareEffect(e,t,i=null,n=null,s=null,r=null,o){if(this._prepareDefines(e,t,s,r,o),!t.isDirty)return null;t.markAsProcessed();const a=this.getScene().getEngine(),l=new zt;let h=0;t.USESPHERICALINVERTEX&&l.addFallback(h++,"USESPHERICALINVERTEX"),t.FOG&&l.addFallback(h,"FOG"),t.SPECULARAA&&l.addFallback(h,"SPECULARAA"),t.POINTSIZE&&l.addFallback(h,"POINTSIZE"),t.LOGARITHMICDEPTH&&l.addFallback(h,"LOGARITHMICDEPTH"),t.PARALLAX&&l.addFallback(h,"PARALLAX"),t.PARALLAXOCCLUSION&&l.addFallback(h++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&l.addFallback(h++,"ENVIRONMENTBRDF"),t.TANGENT&&l.addFallback(h++,"TANGENT"),t.BUMP&&l.addFallback(h++,"BUMP"),h=It.G.HandleFallbacksForShadows(t,l,this._maxSimultaneousLights,h++),t.SPECULARTERM&&l.addFallback(h++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&l.addFallback(h++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&l.addFallback(h++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&l.addFallback(h++,"LIGHTMAP"),t.NORMAL&&l.addFallback(h++,"NORMAL"),t.AMBIENT&&l.addFallback(h++,"AMBIENT"),t.EMISSIVE&&l.addFallback(h++,"EMISSIVE"),t.VERTEXCOLOR&&l.addFallback(h++,"VERTEXCOLOR"),t.MORPHTARGETS&&l.addFallback(h++,"MORPHTARGETS"),t.MULTIVIEW&&l.addFallback(0,"MULTIVIEW");const c=[ne.o.PositionKind];t.NORMAL&&c.push(ne.o.NormalKind),t.TANGENT&&c.push(ne.o.TangentKind);for(let v=1;v<=6;++v)t["UV"+v]&&c.push(`uv${1===v?"":v}`);t.VERTEXCOLOR&&c.push(ne.o.ColorKind),t.INSTANCESCOLOR&&c.push(ne.o.ColorInstanceKind),It.G.PrepareAttributesForBones(c,e,t,l),It.G.PrepareAttributesForInstances(c,t),It.G.PrepareAttributesForMorphTargets(c,e,t),It.G.PrepareAttributesForBakedVertexAnimation(c,e,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"],p=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],f=["Material","Scene","Mesh"];this._eventInfo.fallbacks=l,this._eventInfo.fallbackRank=h,this._eventInfo.defines=t,this._eventInfo.uniforms=u,this._eventInfo.attributes=c,this._eventInfo.samplers=p,this._eventInfo.uniformBuffersNames=f,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._callbackPluginEventGeneric(Ls.S.PrepareEffect,this._eventInfo),ws.AddUniforms(u),ws.AddSamplers(p),(0,ua.qx)(u),ii.$&&(ii.$.PrepareUniforms(u,t),ii.$.PrepareSamplers(p,t)),It.G.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:f,samplers:p,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});const _={};this.customShaderNameResolve&&(d=this.customShaderNameResolve(d,u,f,p,t,c,_));const m=t.toString(),g=a.createEffect(d,{attributes:c,uniformsNames:u,uniformBuffersNames:f,samplers:p,defines:m,fallbacks:l,onCompiled:i,onError:n,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS},processFinalCode:_.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS},a);return this._eventInfo.customCode=void 0,g}_prepareDefines(e,t,i=null,n=null,s=!1){var r;const o=this.getScene(),a=o.getEngine();It.G.PrepareDefinesForLights(o,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,It.G.PrepareDefinesForMultiview(o,t);const l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(It.G.PrepareDefinesForPrePass(o,t,this.canRenderToMRT&&!l),It.G.PrepareDefinesForOIT(o,t,l),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let e=1;e<=6;++e)t["MAINUV"+e]=!1;if(o.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&&Bs.DiffuseTextureEnabled?(It.G.PrepareDefinesForMergedUV(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&Bs.AmbientTextureEnabled?(It.G.PrepareDefinesForMergedUV(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&Bs.OpacityTextureEnabled?(It.G.PrepareDefinesForMergedUV(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;const e=this._getReflectionTexture();if(e&&Bs.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===Le.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 Le.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case Le.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case Le.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case Le.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case Le.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case Le.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Le.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Le.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Le.CUBIC_MODE:case Le.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize}e.coordinatesMode!==Le.SKYBOX_MODE&&(e.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):e.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||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;if(this._lightmapTexture&&Bs.LightmapTextureEnabled?(It.G.PrepareDefinesForMergedUV(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&Bs.EmissiveTextureEnabled?(It.G.PrepareDefinesForMergedUV(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,Bs.SpecularTextureEnabled){if(this._metallicTexture?(It.G.PrepareDefinesForMergedUV(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?(It.G.PrepareDefinesForMergedUV(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){const e=null!==this._metallicReflectanceTexture&&this._metallicReflectanceTexture._texture===(null===(r=this._reflectanceTexture)||void 0===r?void 0:r._texture)&&this._metallicReflectanceTexture.checkTransformsAreIdentical(this._reflectanceTexture);t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture&&!e,this._metallicReflectanceTexture?(It.G.PrepareDefinesForMergedUV(this._metallicReflectanceTexture,t,"METALLIC_REFLECTANCE"),t.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):t.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&!e&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(It.G.PrepareDefinesForMergedUV(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1}else t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1;this._microSurfaceTexture?It.G.PrepareDefinesForMergedUV(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1}else t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1;a.getCaps().standardDerivatives&&this._bumpTexture&&Bs.BumpTextureEnabled&&!this._disableBumpMap?(It.G.PrepareDefinesForMergedUV(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&Bs.DiffuseTextureEnabled?(t.PARALLAX=!0,t.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):t.PARALLAX=!1,t.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):(t.BUMP=!1,t.PARALLAX=!1,t.PARALLAXOCCLUSION=!1,t.OBJECTSPACE_NORMALMAP=!1),this._environmentBRDFTexture&&Bs.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===M_.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===M_.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=7===this.alphaMode||8===this.alphaMode,t.ALPHABLEND=this.needAlphaBlendingForMesh(e),t.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,t.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel),t._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(t),t.FORCENORMALFORWARD=this._forceNormalForward,t.RADIANCEOCCLUSION=this._useRadianceOcclusion,t.HORIZONOCCLUSION=this._useHorizonOcclusion,t._areMiscDirty&&(It.G.PrepareDefinesForMisc(e,o,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,t),t.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(ne.o.NormalKind),t.DEBUGMODE=this._debugMode),It.G.PrepareDefinesForFrameBoundValues(o,a,this,t,!!i,n,s),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),It.G.PrepareDefinesForAttributes(e,t,!0,!0,!0,this._transparencyMode!==M_.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){const n=Object.assign({clipPlane:!1,useInstances:!1},i);this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(Ls.S.GetDefineNames,this._eventInfo);const s=new I_(this._eventInfo.defineNames),r=this._prepareEffect(e,s,void 0,void 0,n.useInstances,n.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(P_.effect=r,P_.subMesh=null,this._onEffectCreatedObservable.notifyObservers(P_)),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){var n,s,r,o;const l=this.getScene(),h=i.materialDefines;if(!h)return;const c=i.effect;if(!c)return;this._activeEffect=c,t.getMeshUniformBuffer().bindToEffect(c,"Mesh"),t.transferToEffect(e);const d=l.getEngine();this._uniformBuffer.bindToEffect(c,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,l,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),h.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const u=c._forceRebindOnNextCall||this._mustRebind(l,c,t.visibility);It.G.BindBonesParameters(t,this._activeEffect,this.prePassConfiguration);let p=null;const f=this._uniformBuffer;if(u){if(this.bindViewProjection(c),p=this._getReflectionTexture(),!f.useUbo||!this.isFrozen||!f.isSync||c._forceRebindOnNextCall){if(l.texturesEnabled){if(this._albedoTexture&&Bs.DiffuseTextureEnabled&&(f.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),It.G.BindTextureMatrix(this._albedoTexture,f,"albedo")),this._ambientTexture&&Bs.AmbientTextureEnabled&&(f.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),It.G.BindTextureMatrix(this._ambientTexture,f,"ambient")),this._opacityTexture&&Bs.OpacityTextureEnabled&&(f.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),It.G.BindTextureMatrix(this._opacityTexture,f,"opacity")),p&&Bs.ReflectionTextureEnabled){if(f.updateMatrix("reflectionMatrix",p.getReflectionTextureMatrix()),f.updateFloat2("vReflectionInfos",p.level,0),p.boundingBoxSize){const e=p;f.updateVector3("vReflectionPosition",e.boundingBoxPosition),f.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this.realTimeFiltering){const e=p.getSize().width;f.updateFloat2("vReflectionFilteringInfo",e,S.R.Log2(e))}if(!h.USEIRRADIANCEMAP){const e=p.sphericalPolynomial;if(h.USESPHERICALFROMREFLECTIONMAP&&e)if(h.SPHERICAL_HARMONICS){const t=e.preScaledHarmonics;f.updateVector3("vSphericalL00",t.l00),f.updateVector3("vSphericalL1_1",t.l1_1),f.updateVector3("vSphericalL10",t.l10),f.updateVector3("vSphericalL11",t.l11),f.updateVector3("vSphericalL2_2",t.l2_2),f.updateVector3("vSphericalL2_1",t.l2_1),f.updateVector3("vSphericalL20",t.l20),f.updateVector3("vSphericalL21",t.l21),f.updateVector3("vSphericalL22",t.l22)}else f.updateFloat3("vSphericalX",e.x.x,e.x.y,e.x.z),f.updateFloat3("vSphericalY",e.y.x,e.y.y,e.y.z),f.updateFloat3("vSphericalZ",e.z.x,e.z.y,e.z.z),f.updateFloat3("vSphericalXX_ZZ",e.xx.x-e.zz.x,e.xx.y-e.zz.y,e.xx.z-e.zz.z),f.updateFloat3("vSphericalYY_ZZ",e.yy.x-e.zz.x,e.yy.y-e.zz.y,e.yy.z-e.zz.z),f.updateFloat3("vSphericalZZ",e.zz.x,e.zz.y,e.zz.z),f.updateFloat3("vSphericalXY",e.xy.x,e.xy.y,e.xy.z),f.updateFloat3("vSphericalYZ",e.yz.x,e.yz.y,e.yz.z),f.updateFloat3("vSphericalZX",e.zx.x,e.zx.y,e.zx.z)}f.updateFloat3("vReflectionMicrosurfaceInfos",p.getSize().width,p.lodGenerationScale,p.lodGenerationOffset)}this._emissiveTexture&&Bs.EmissiveTextureEnabled&&(f.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),It.G.BindTextureMatrix(this._emissiveTexture,f,"emissive")),this._lightmapTexture&&Bs.LightmapTextureEnabled&&(f.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),It.G.BindTextureMatrix(this._lightmapTexture,f,"lightmap")),Bs.SpecularTextureEnabled&&(this._metallicTexture?(f.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),It.G.BindTextureMatrix(this._metallicTexture,f,"reflectivity")):this._reflectivityTexture&&(f.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),It.G.BindTextureMatrix(this._reflectivityTexture,f,"reflectivity")),this._metallicReflectanceTexture&&(f.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),It.G.BindTextureMatrix(this._metallicReflectanceTexture,f,"metallicReflectance")),this._reflectanceTexture&&h.REFLECTANCE&&(f.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),It.G.BindTextureMatrix(this._reflectanceTexture,f,"reflectance")),this._microSurfaceTexture&&(f.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),It.G.BindTextureMatrix(this._microSurfaceTexture,f,"microSurfaceSampler"))),this._bumpTexture&&d.getCaps().standardDerivatives&&Bs.BumpTextureEnabled&&!this._disableBumpMap&&(f.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),It.G.BindTextureMatrix(this._bumpTexture,f,"bump"),l._mirroredCameraPosition?f.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):f.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&f.updateFloat("pointSize",this.pointSize),h.METALLICWORKFLOW){a.zZ.Color3[0].r=void 0===this._metallic||null===this._metallic?1:this._metallic,a.zZ.Color3[0].g=void 0===this._roughness||null===this._roughness?1:this._roughness,f.updateColor4("vReflectivityColor",a.zZ.Color3[0],1);const e=null!==(s=null===(n=this.subSurface)||void 0===n?void 0:n._indexOfRefraction)&&void 0!==s?s:1.5,t=1,i=Math.pow((e-t)/(e+t),2);this._metallicReflectanceColor.scaleToRef(i*this._metallicF0Factor,a.zZ.Color3[0]);const r=this._metallicF0Factor;f.updateColor4("vMetallicReflectanceFactors",a.zZ.Color3[0],r)}else f.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);f.updateColor3("vEmissiveColor",Bs.EmissiveTextureEnabled?this._emissiveColor:a.Wo.BlackReadOnly),f.updateColor3("vReflectionColor",this._reflectionColor),!h.SS_REFRACTION&&(null===(r=this.subSurface)||void 0===r?void 0:r._linkRefractionWithTransparency)?f.updateColor4("vAlbedoColor",this._albedoColor,1):f.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*l.environmentIntensity,this._lightingInfos.w=this._specularIntensity,f.updateVector4("vLightingIntensity",this._lightingInfos),l.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),f.updateColor3("vAmbientColor",this._globalAmbientColor),f.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}l.texturesEnabled&&(this._albedoTexture&&Bs.DiffuseTextureEnabled&&f.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&Bs.AmbientTextureEnabled&&f.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&Bs.OpacityTextureEnabled&&f.setTexture("opacitySampler",this._opacityTexture),p&&Bs.ReflectionTextureEnabled&&(h.LODBASEDMICROSFURACE?f.setTexture("reflectionSampler",p):(f.setTexture("reflectionSampler",p._lodTextureMid||p),f.setTexture("reflectionSamplerLow",p._lodTextureLow||p),f.setTexture("reflectionSamplerHigh",p._lodTextureHigh||p)),h.USEIRRADIANCEMAP&&f.setTexture("irradianceSampler",p.irradianceTexture)),h.ENVIRONMENTBRDF&&f.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&Bs.EmissiveTextureEnabled&&f.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&Bs.LightmapTextureEnabled&&f.setTexture("lightmapSampler",this._lightmapTexture),Bs.SpecularTextureEnabled&&(this._metallicTexture?f.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&f.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&f.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&h.REFLECTANCE&&f.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&f.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&d.getCaps().standardDerivatives&&Bs.BumpTextureEnabled&&!this._disableBumpMap&&f.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(c),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),(0,ua.an)(this._activeEffect,this,l),this.bindEyePosition(c)}else l.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!u&&this.isFrozen||(l.lightsEnabled&&!this._disableLighting&&It.G.BindLights(l,t,this._activeEffect,h,this._maxSimultaneousLights),(l.fogEnabled&&t.applyFog&&l.fogMode!==N.x.FOGMODE_NONE||p||t.receiveShadows||h.PREPASS)&&this.bindView(c),It.G.BindFogParameters(l,t,this._activeEffect,!0),h.NUM_MORPH_INFLUENCERS&&It.G.BindMorphTargetParameters(t,this._activeEffect),h.BAKED_VERTEX_ANIMATION_TEXTURE&&(null===(o=t.bakedVertexAnimationManager)||void 0===o||o.bind(c,h.INSTANCES)),this._imageProcessingConfiguration.bind(this._activeEffect),It.G.BindLogDepth(h,this._activeEffect,l)),this._afterBind(t,this._activeEffect),f.update()}getAnimatables(){const e=super.getAnimatables();return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&e.push(this._albedoTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?e.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&e.push(this._reflectivityTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._metallicReflectanceTexture&&this._metallicReflectanceTexture.animations&&this._metallicReflectanceTexture.animations.length>0&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&this._reflectanceTexture.animations&&this._reflectanceTexture.animations.length>0&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&this._microSurfaceTexture.animations&&this._microSurfaceTexture.animations.length>0&&e.push(this._microSurfaceTexture),e}_getReflectionTexture(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture}getActiveTextures(){const e=super.getActiveTextures();return this._albedoTexture&&e.push(this._albedoTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._reflectivityTexture&&e.push(this._reflectivityTexture),this._metallicTexture&&e.push(this._metallicTexture),this._metallicReflectanceTexture&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&e.push(this._microSurfaceTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),e}hasTexture(e){return!!super.hasTexture(e)||(this._albedoTexture===e||(this._ambientTexture===e||(this._opacityTexture===e||(this._reflectionTexture===e||(this._emissiveTexture===e||(this._reflectivityTexture===e||(this._metallicTexture===e||(this._metallicReflectanceTexture===e||(this._reflectanceTexture===e||(this._microSurfaceTexture===e||(this._bumpTexture===e||this._lightmapTexture===e)))))))))))}setPrePassRenderer(){var e;if(!(null===(e=this.subSurface)||void 0===e?void 0:e.isScatteringEnabled))return!1;const t=this.getScene().enableSubSurfaceForPrePass();return t&&(t.enabled=!0),!0}dispose(e,t){var i,n,s,r,o,a,l,h,c,d,u,p;t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),null===(i=this._albedoTexture)||void 0===i||i.dispose(),null===(n=this._ambientTexture)||void 0===n||n.dispose(),null===(s=this._opacityTexture)||void 0===s||s.dispose(),null===(r=this._reflectionTexture)||void 0===r||r.dispose(),null===(o=this._emissiveTexture)||void 0===o||o.dispose(),null===(a=this._metallicTexture)||void 0===a||a.dispose(),null===(l=this._reflectivityTexture)||void 0===l||l.dispose(),null===(h=this._bumpTexture)||void 0===h||h.dispose(),null===(c=this._lightmapTexture)||void 0===c||c.dispose(),null===(d=this._metallicReflectanceTexture)||void 0===d||d.dispose(),null===(u=this._reflectanceTexture)||void 0===u||u.dispose(),null===(p=this._microSurfaceTexture)||void 0===p||p.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}}M_.PBRMATERIAL_OPAQUE=ut.F.MATERIAL_OPAQUE,M_.PBRMATERIAL_ALPHATEST=ut.F.MATERIAL_ALPHATEST,M_.PBRMATERIAL_ALPHABLEND=ut.F.MATERIAL_ALPHABLEND,M_.PBRMATERIAL_ALPHATESTANDBLEND=ut.F.MATERIAL_ALPHATESTANDBLEND,M_.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,M_.LIGHTFALLOFF_PHYSICAL=0,M_.LIGHTFALLOFF_GLTF=1,M_.LIGHTFALLOFF_STANDARD=2,(0,oe.gn)([(0,E.rX)()],M_.prototype,"_imageProcessingConfiguration",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsMiscDirty")],M_.prototype,"debugMode",void 0),(0,oe.gn)([(0,E.qC)()],M_.prototype,"useLogarithmicDepth",null);class O_ extends M_{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===M_.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?M_.LIGHTFALLOFF_PHYSICAL:M_.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===M_.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?M_.LIGHTFALLOFF_GLTF:M_.LIGHTFALLOFF_STANDARD)}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}constructor(e,t){super(e,t),this.directIntensity=1,this.emissiveIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.disableBumpMap=!1,this.ambientTextureStrength=1,this.ambientTextureImpactOnAnalyticalLights=O_.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=a.Wo.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new a.Wo(0,0,0),this.albedoColor=new a.Wo(1,1,1),this.reflectivityColor=new a.Wo(1,1,1),this.reflectionColor=new a.Wo(1,1,1),this.emissiveColor=new a.Wo(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._environmentBRDFTexture=zp(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){const n=E.p4.Clone((()=>new O_(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=E.p4.Parse((()=>new O_(e.name,t)),e,t,i);return e.stencil&&n.stencil.parse(e.stencil,t,i),ut.F._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}}O_.PBRMATERIAL_OPAQUE=M_.PBRMATERIAL_OPAQUE,O_.PBRMATERIAL_ALPHATEST=M_.PBRMATERIAL_ALPHATEST,O_.PBRMATERIAL_ALPHABLEND=M_.PBRMATERIAL_ALPHABLEND,O_.PBRMATERIAL_ALPHATESTANDBLEND=M_.PBRMATERIAL_ALPHATESTANDBLEND,O_.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=M_.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"directIntensity",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"emissiveIntensity",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"environmentIntensity",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"specularIntensity",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"disableBumpMap",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"albedoTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"ambientTexture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"ambientTextureStrength",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],O_.prototype,"opacityTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"reflectionTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"emissiveTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"reflectivityTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"metallicTexture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"metallic",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"roughness",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"metallicF0Factor",void 0),(0,oe.gn)([(0,E.n9)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"metallicReflectanceColor",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"metallicReflectanceTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"reflectanceTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"microSurfaceTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"bumpTexture",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty",null)],O_.prototype,"lightmapTexture",void 0),(0,oe.gn)([(0,E.n9)("ambient"),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"ambientColor",void 0),(0,oe.gn)([(0,E.n9)("albedo"),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"albedoColor",void 0),(0,oe.gn)([(0,E.n9)("reflectivity"),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"reflectivityColor",void 0),(0,oe.gn)([(0,E.n9)("reflection"),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"reflectionColor",void 0),(0,oe.gn)([(0,E.n9)("emissive"),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"emissiveColor",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"microSurface",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useLightmapAsShadowmap",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],O_.prototype,"useAlphaFromAlbedoTexture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],O_.prototype,"forceAlphaTest",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],O_.prototype,"alphaCutOff",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useSpecularOverAlpha",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useRoughnessFromMetallicTextureGreen",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useMetallnessFromMetallicTextureBlue",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useAmbientInGrayScale",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),(0,oe.gn)([(0,E.qC)()],O_.prototype,"usePhysicalLightFalloff",null),(0,oe.gn)([(0,E.qC)()],O_.prototype,"useGLTFLightFalloff",null),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useRadianceOverAlpha",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useObjectSpaceNormalMap",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useParallax",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useParallaxOcclusion",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"parallaxScaleBias",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsLightsDirty")],O_.prototype,"disableLighting",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"forceIrradianceInFragment",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsLightsDirty")],O_.prototype,"maxSimultaneousLights",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"invertNormalMapX",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"invertNormalMapY",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"twoSidedLighting",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useAlphaFresnel",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useLinearAlphaFresnel",void 0),(0,oe.gn)([(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"environmentBRDFTexture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"forceNormalForward",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"enableSpecularAntiAliasing",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useHorizonOcclusion",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],O_.prototype,"useRadianceOcclusion",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsMiscDirty")],O_.prototype,"unlit",void 0),(0,l.H)("BABYLON.PBRMaterial",O_);const D_=131072,N_=131072;function F_(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}const w_=F_("DXT1"),L_=F_("DXT3"),B_=F_("DXT5"),U_=F_("DX10");class V_{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]&D_&&(n=Math.max(1,t[7]));const s=t[21],r=s===U_?i[32]:0;let o=0;switch(s){case 113:o=2;break;case 116:o=1;break;case U_:if(10===r){o=2;break}if(2===r){o=1;break}}return{width:t[4],height:t[3],mipmapCount:n,isFourCC:4==(4&t[20]),isRGB:64==(64&t[20]),isLuminance:(t[20]&N_)===N_,isCube:512==(512&t[28]),isCompressed:s===w_||s===L_||s===B_,dxgiFormat:r,textureType:o}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,n,s,r){const o=new Float32Array(n),a=new Uint16Array(s,i);let l=0;for(let h=0;h>8)}static _GetRGBArrayBuffer(e,t,i,n,s,r,o,a){const l=new Uint8Array(n),h=new Uint8Array(s,i);let c=0;for(let d=0;d>8&255,y>>16&255,y>>24&255)))}var y;const A=V_._ExtractLongWordOrder(d[23]),R=V_._ExtractLongWordOrder(d[24]),P=V_._ExtractLongWordOrder(d[25]),I=V_._ExtractLongWordOrder(d[26]);C&&(E=e._getRGBABufferInternalSizedFormat(n.textureType)),v=1,d[2]&D_&&!1!==s&&(v=Math.max(1,d[7]));const M=a||0,O=e.getCaps();for(let p=M;p0?n.sphericalPolynomial=zh.ConvertCubeMapToSphericalPolynomial({size:d[4],right:h[0],left:h[1],up:h[2],down:h[3],front:h[4],back:h[5],format:5,type:1,gammaSpace:!1}):n.sphericalPolynomial=void 0}}V_.StoreLODInAlphaChannel=!1,Ue.B.prototype.createPrefilteredCubeTexture=function(e,t,i,n,s=null,r=null,o,a=null,l=!0){return this.createCubeTexture(e,t,null,!1,(e=>{if(!e)return void(s&&s(null));const r=e.texture;if(l?e.info.sphericalPolynomial&&(r._sphericalPolynomial=e.info.sphericalPolynomial):r._sphericalPolynomial=new Dh,r._source=Be.S.CubePrefiltered,this.getCaps().textureLOD)return void(s&&s(r));const o=this._gl,a=e.width;if(!a)return;const h=[];for(let s=0;s<3;s++){const l=1-s/2,c=n,d=S.R.Log2(a)*i+n,u=c+(d-c)*l,f=Math.round(Math.min(Math.max(u,0),d)),_=new Be.l(this,Be.S.Temp);if(_.type=r.type,_.format=r.format,_.width=Math.pow(2,Math.max(S.R.Log2(a)-f,0)),_.height=_.width,_.isCube=!0,_._cachedWrapU=0,_._cachedWrapV=0,this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,_,!0),_.samplingMode=2,o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_CUBE_MAP,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),e.isDDS){const t=e.info,i=e.data;this._unpackFlipY(t.isCompressed),V_.UploadDDSLevels(this,_,i,t,!0,6,f)}else p.Y.Warn("DDS is the only prefiltered cube map supported so far.");this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,null);const m=new Re(t);m._isCube=!0,m._texture=_,_.isReady=!0,h.push(m)}r._lodTextureHigh=h[2],r._lodTextureMid=h[1],r._lodTextureLow=h[0],s&&s(r)}),r,o,a,l,i,n)};fe.D._TextureLoaders.push(new class{constructor(){this.supportCascades=!0}canLoad(e){return e.endsWith(".dds")}loadCubeData(e,t,i,n){const s=t.getEngine();let r,o=!1,a=1e3;if(Array.isArray(e))for(let l=0;l1)&&t.generateMipMaps,s._unpackFlipY(r.isCompressed),V_.UploadDDSLevels(s,t,i,r,o,6,-1,l),r.isFourCC||1!==r.mipmapCount?a=r.mipmapCount-1:s.generateMipMapsForCubemap(t)}else{const n=e;r=V_.GetDDSInfo(n),t.width=r.width,t.height=r.height,i&&(r.sphericalPolynomial=new Dh),o=(r.isRGB||r.isLuminance||r.mipmapCount>1)&&t.generateMipMaps,s._unpackFlipY(r.isCompressed),V_.UploadDDSLevels(s,t,n,r,o,6),r.isFourCC||1!==r.mipmapCount?a=r.mipmapCount-1:s.generateMipMapsForCubemap(t,!1)}s._setCubeMapTextureParams(t,o,a),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n({isDDS:!0,width:t.width,info:r,data:e,texture:t})}loadData(e,t,i){const n=V_.GetDDSInfo(e),s=(n.isRGB||n.isLuminance||n.mipmapCount>1)&&t.generateMipMaps&&n.width>>n.mipmapCount-1==1;i(n.width,n.height,s,n.isFourCC,(()=>{V_.UploadDDSLevels(t.getEngine(),t,e,n,s,1)}))}});fe.D._TextureLoaders.push(new class{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".env")}loadCubeData(e,t,i,n,s){if(Array.isArray(e))return;const r=Kh(e);if(r){t.width=r.width,t.height=r.width;try{ec(t,r),Qh(t,e,r).then((()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n()}),(e=>{null==s||s("Can not upload environment levels",e)}))}catch(o){null==s||s("Can not upload environment file",o)}}else s&&s("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}});class k_{constructor(e,t){if(this.data=e,this.isInvalid=!1,!k_.IsValid(e))return this.isInvalid=!0,void p.Y.Error("texture missing KTX identifier");const i=Uint32Array.BYTES_PER_ELEMENT,n=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),s=67305985===n.getUint32(0,!0);return this.glType=n.getUint32(1*i,s),this.glTypeSize=n.getUint32(2*i,s),this.glFormat=n.getUint32(3*i,s),this.glInternalFormat=n.getUint32(4*i,s),this.glBaseInternalFormat=n.getUint32(5*i,s),this.pixelWidth=n.getUint32(6*i,s),this.pixelHeight=n.getUint32(7*i,s),this.pixelDepth=n.getUint32(8*i,s),this.numberOfArrayElements=n.getUint32(9*i,s),this.numberOfFaces=n.getUint32(10*i,s),this.numberOfMipmapLevels=n.getUint32(11*i,s),this.bytesOfKeyValueData=n.getUint32(12*i,s),0!==this.glType?(p.Y.Error("only compressed formats currently supported"),void(this.isInvalid=!0)):(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0===this.pixelHeight||0!==this.pixelDepth?(p.Y.Error("only 2D textures currently supported"),void(this.isInvalid=!0)):0!==this.numberOfArrayElements?(p.Y.Error("texture arrays not currently supported"),void(this.isInvalid=!0)):this.numberOfFaces!==t?(p.Y.Error("number of faces expected"+t+", but found "+this.numberOfFaces),void(this.isInvalid=!0)):void(this.loadType=k_.COMPRESSED_2D))}uploadLevels(e,t){switch(this.loadType){case k_.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);case k_.TEX_2D:case k_.COMPRESSED_3D:case k_.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=k_.HEADER_LEN+this.bytesOfKeyValueData,n=this.pixelWidth,s=this.pixelHeight;const r=t?this.numberOfMipmapLevels:1;for(let o=0;o=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}}k_.HEADER_LEN=64,k_.COMPRESSED_2D=0,k_.COMPRESSED_3D=1,k_.TEX_2D=2,k_.TEX_3D=3;class G_{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 z_ extends G_{constructor(e,t,i=z_.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length{t(i,(()=>{n(),e.idle&&(e.timeoutId=setTimeout((()=>{e.workerPromise.then((e=>{e.terminate()}));const t=this._workerInfos.indexOf(e);-1!==t&&this._workerInfos.splice(t,1)}),this._options.idleTimeElapsedBeforeRelease))}))}))}}var W_,H_,X_;function Y_(e){return e?se.w1.GetAbsoluteUrl(e):null}function j_(e){null!==e.wasmUASTCToASTC&&(KTX2DECODER.LiteTranscoder_UASTC_ASTC.WasmModuleURL=e.wasmUASTCToASTC),null!==e.wasmUASTCToBC7&&(KTX2DECODER.LiteTranscoder_UASTC_BC7.WasmModuleURL=e.wasmUASTCToBC7),null!==e.wasmUASTCToRGBA_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=e.wasmUASTCToRGBA_UNORM),null!==e.wasmUASTCToRGBA_SRGB&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=e.wasmUASTCToRGBA_SRGB),null!==e.wasmUASTCToR8_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=e.wasmUASTCToR8_UNORM),null!==e.wasmUASTCToRG8_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=e.wasmUASTCToRG8_UNORM),null!==e.jsMSCTranscoder&&(KTX2DECODER.MSCTranscoder.JSModuleURL=e.jsMSCTranscoder),null!==e.wasmMSCTranscoder&&(KTX2DECODER.MSCTranscoder.WasmModuleURL=e.wasmMSCTranscoder),null!==e.wasmZSTDDecoder&&(KTX2DECODER.ZSTDDecoder.WasmModuleURL=e.wasmZSTDDecoder)}z_.DefaultOptions={idleTimeElapsedBeforeRelease:1e3},function(e){e[e.ETC1S=0]="ETC1S",e[e.UASTC4x4=1]="UASTC4x4"}(W_||(W_={})),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"}(H_||(H_={})),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"}(X_||(X_={}));class K_{static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static _Initialize(e){if(K_._WorkerPoolPromise||K_._DecoderModulePromise)return;const t={jsDecoderModule:se.w1.GetAbsoluteUrl(this.URLConfig.jsDecoderModule),wasmUASTCToASTC:Y_(this.URLConfig.wasmUASTCToASTC),wasmUASTCToBC7:Y_(this.URLConfig.wasmUASTCToBC7),wasmUASTCToRGBA_UNORM:Y_(this.URLConfig.wasmUASTCToRGBA_UNORM),wasmUASTCToRGBA_SRGB:Y_(this.URLConfig.wasmUASTCToRGBA_SRGB),wasmUASTCToR8_UNORM:Y_(this.URLConfig.wasmUASTCToR8_UNORM),wasmUASTCToRG8_UNORM:Y_(this.URLConfig.wasmUASTCToRG8_UNORM),jsMSCTranscoder:Y_(this.URLConfig.jsMSCTranscoder),wasmMSCTranscoder:Y_(this.URLConfig.wasmMSCTranscoder),wasmZSTDDecoder:Y_(this.URLConfig.wasmZSTDDecoder)};e&&"function"==typeof Worker&&"undefined"!=typeof URL?K_._WorkerPoolPromise=new Promise((i=>{const n=`${j_}(${q_})()`,s=URL.createObjectURL(new Blob([n],{type:"application/javascript"}));i(new z_(e,(()=>new Promise(((e,i)=>{const n=new Worker(s),r=e=>{n.removeEventListener("error",r),n.removeEventListener("message",o),i(e)},o=t=>{"init"===t.data.action&&(n.removeEventListener("error",r),n.removeEventListener("message",o),e(n))};n.addEventListener("error",r),n.addEventListener("message",o),n.postMessage({action:"init",urls:t})})))))})):"undefined"==typeof KTX2DECODER?K_._DecoderModulePromise=se.w1.LoadScriptAsync(t.jsDecoderModule).then((()=>(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,j_(t),new KTX2DECODER.KTX2Decoder))):(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,K_._DecoderModulePromise=Promise.resolve(new KTX2DECODER.KTX2Decoder))}constructor(e,t=K_.DefaultNumWorkers){this._engine=e,K_._Initialize(t)}uploadAsync(e,t,i){const n=this._engine.getCaps(),s={astc:!!n.astc,bptc:!!n.bptc,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,etc1:!!n.etc1};if(K_._WorkerPoolPromise)return K_._WorkerPoolPromise.then((n=>new Promise(((r,o)=>{n.push(((n,a)=>{const l=e=>{n.removeEventListener("error",l),n.removeEventListener("message",h),o(e),a()},h=e=>{if("decoded"===e.data.action){if(n.removeEventListener("error",l),n.removeEventListener("message",h),e.data.success)try{this._createTexture(e.data.decodedData,t,i),r()}catch(s){o({message:s})}else o({message:e.data.msg});a()}};n.addEventListener("error",l),n.addEventListener("message",h),n.postMessage({action:"setDefaultDecoderOptions",options:K_.DefaultDecoderOptions._getKTX2DecoderOptions()});const c=new Uint8Array(e.byteLength);c.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),n.postMessage({action:"decode",data:c,caps:s,options:i},[c.buffer])}))}))));if(K_._DecoderModulePromise)return K_._DecoderModulePromise.then((i=>(K_.DefaultDecoderOptions.isDirty&&(KTX2DECODER.KTX2Decoder.DefaultDecoderOptions=K_.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise(((s,r)=>{i.decode(e,n).then((e=>{this._createTexture(e,t),s()})).catch((e=>{r({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=0,t.format=5;break;case 33321:t.type=0,t.format=6;break;case 33323:t.type=0,t.format=7;break;default:t.format=e.transcodedFormat,n=!1}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 s=0;s=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}}function q_(){let e;onmessage=t=>{if(t.data)switch(t.data.action){case"init":{const i=t.data.urls;importScripts(i.jsDecoderModule),j_(i),e=new KTX2DECODER.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":KTX2DECODER.KTX2Decoder.DefaultDecoderOptions=t.data.options;break;case"decode":e.decode(t.data.data,t.data.caps,t.data.options).then((e=>{const t=[];for(let i=0;i{postMessage({action:"decoded",success:!1,msg:e})}))}}}K_.URLConfig={jsDecoderModule:"https://preview.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},K_.DefaultNumWorkers=K_.GetDefaultNumWorkers(),K_.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:[H_.BC1_RGB,H_.BC3_RGBA],yes:{transcodeFormat:H_.RGBA32,engineFormat:X_.RGBA8Format,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}};fe.D._TextureLoaders.unshift(new class{constructor(){this.supportCascades=!1}canLoad(e,t){return e.endsWith(".ktx")||e.endsWith(".ktx2")||"image/ktx"===t||"image/ktx2"===t}loadCubeData(e,t,i,n){if(Array.isArray(e))return;t._invertVScale=!t.invertY;const s=t.getEngine(),r=new k_(e,6),o=r.numberOfMipmapLevels>1&&t.generateMipMaps;s._unpackFlipY(!0),r.uploadLevels(t,t.generateMipMaps),t.width=r.pixelWidth,t.height=r.pixelHeight,s._setCubeMapTextureParams(t,o,r.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n()}loadData(e,t,i,n){if(k_.IsValid(e)){t._invertVScale=!t.invertY;const n=new k_(e,1),s=function(e){switch(e){case 35916:return 33776;case 35918:return 33778;case 35919:return 33779;case 37493:return 37492;case 37497:return 37496;case 37495:return 37494;case 37840:return 37808;case 36493:return 36492}return null}(n.glInternalFormat);s?(t.format=s,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(K_.IsValid(e)){new K_(t.getEngine()).uploadAsync(e,t,n).then((()=>{i(t.width,t.height,t.generateMipMaps,!0,(()=>{}),!1)}),(e=>{p.Y.Warn(`Failed to load KTX2 texture data: ${e.message}`),i(0,0,!1,!1,(()=>{}),!0)}))}else p.Y.Error("texture missing KTX identifier"),i(0,0,!1,!1,(()=>{}),!0)}});class $_ extends Fn{constructor(e,t,i){super(e,o.P.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=o._f.Identity(),this._referencedPosition=new o.P,this._trackingState=xa.NOT_TRACKING,this.onBeforeCameraTeleport=new r.y$,this.onAfterCameraTeleport=new r.y$,this.onTrackingStateChanged=new r.y$,this.compensateOnFirstFrame=!0,this._rotate180=new o._f(0,1,0,0),this.minZ=.1,this.rotationQuaternion=new o._f,this.cameraRigMode=ce.V.RIG_MODE_CUSTOM,this.updateUpVectorFromRotation=!0,this._updateNumberOfRigCameras(1),this.freezeProjectionMatrix(),this._xrSessionManager.onXRSessionInit.add((()=>{this._referencedPosition.copyFromFloats(0,0,0),this._referenceQuaternion.copyFromFloats(0,0,0,1),this._firstFrame=this.compensateOnFirstFrame})),this._xrSessionManager.onXRFrameObservable.add((()=>{this._firstFrame&&this._updateFromXRSession(),this._updateReferenceSpace(),this._updateFromXRSession()}),void 0,!0)}get trackingState(){return this._trackingState}_setTrackingState(e){this._trackingState!==e&&(this._trackingState=e,this.onTrackingStateChanged.notifyObservers(e))}get realWorldHeight(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace);return e&&e.transform?e.transform.position.y:0}_updateForDualEyeDebugging(){this._updateNumberOfRigCameras(2),this.rigCameras[0].viewport=new Nt.l(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new Nt.l(.5,0,.5,1),this.rigCameras[1].outputRenderTarget=null}setTransformationFromNonVRCamera(e=this.getScene().activeCamera,t=!0){if(!e||e===this)return;e.computeWorldMatrix().decompose(void 0,this.rotationQuaternion,this.position),this.position.y=0,o._f.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace()}getClassName(){return"WebXRCamera"}setTarget(e){const t=o.jp.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();const i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),o._f.FromEulerAnglesToRef(t.x,i,t.z,this.rotationQuaternion)}dispose(){super.dispose(),this._lastXRViewerPose=void 0}_updateFromXRSession(){const e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);if(this._lastXRViewerPose=e||void 0,!e)return void this._setTrackingState(xa.NOT_TRACKING);const t=e.emulatedPosition?xa.TRACKING_LOST:xa.TRACKING;if(this._setTrackingState(t),this.minZ!==this._cache.minZ||this.maxZ!==this._cache.maxZ){const e={depthFar:this.maxZ||1e4,depthNear:this.minZ};this._xrSessionManager.updateRenderState(e),this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ}if(e.transform){const t=e.transform.orientation;if(void 0===e.transform.orientation.x)return;const i=e.transform.position;this._referencedPosition.set(i.x,i.y,i.z),this._referenceQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this._referencedPosition.z*=-1,this._referenceQuaternion.z*=-1,this._referenceQuaternion.w*=-1),this._firstFrame?(this._firstFrame=!1,this.position.y+=this._referencedPosition.y,this._referenceQuaternion.copyFromFloats(0,0,0,1)):(this.rotationQuaternion.copyFrom(this._referenceQuaternion),this.position.copyFrom(this._referencedPosition))}this.rigCameras.length!==e.views.length&&this._updateNumberOfRigCameras(e.views.length),e.views.forEach(((e,t)=>{var i;const n=this.rigCameras[t];n.isLeftCamera||n.isRightCamera||("right"===e.eye?n._isRightCamera=!0:"left"===e.eye&&(n._isLeftCamera=!0));const s=e.transform.position,r=e.transform.orientation;n.parent=this.parent,n.position.set(s.x,s.y,s.z),n.rotationQuaternion.set(r.x,r.y,r.z,r.w),this._scene.useRightHandedSystem?n.rotationQuaternion.multiplyInPlace(this._rotate180):(n.position.z*=-1,n.rotationQuaternion.z*=-1,n.rotationQuaternion.w*=-1),o.y3.FromFloat32ArrayToRefScaled(e.projectionMatrix,0,1,n._projectionMatrix),this._scene.useRightHandedSystem||n._projectionMatrix.toggleProjectionMatrixHandInPlace(),0===t&&this._projectionMatrix.copyFrom(n._projectionMatrix);const a=this._xrSessionManager.getRenderTargetTextureForView(e);this._renderingMultiview=(null===(i=null==a?void 0:a._texture)||void 0===i?void 0:i.isMultiview)||!1,this._renderingMultiview?0==t&&(this._xrSessionManager.trySetViewportForView(this.viewport,e),this.outputRenderTarget=a):(this._xrSessionManager.trySetViewportForView(n.viewport,e),n.outputRenderTarget=a||this._xrSessionManager.getRenderTargetTextureForView(e)),n.layerMask=this.layerMask}))}_updateNumberOfRigCameras(e=1){for(;this.rigCameras.lengthe;){const e=this.rigCameras.pop();e&&e.dispose()}}_updateReferenceSpace(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){const e=o.jp.Matrix[0],t=o.jp.Matrix[1],i=o.jp.Matrix[2];o.y3.ComposeToRef($_._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),o.y3.ComposeToRef($_._ScaleReadOnly,this.rotationQuaternion,this.position,t),e.invert().multiplyToRef(t,i),i.invert(),this._scene.useRightHandedSystem||i.toggleModelMatrixHandInPlace(),i.decompose(void 0,this._referenceQuaternion,this._referencedPosition);const n=new XRRigidTransform({x:this._referencedPosition.x,y:this._referencedPosition.y,z:this._referencedPosition.z},{x:this._referenceQuaternion.x,y:this._referenceQuaternion.y,z:this._referenceQuaternion.z,w:this._referenceQuaternion.w});this._xrSessionManager.referenceSpace=this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(n)}}}$_._ScaleReadOnly=o.P.One();class Q_{constructor(e){this._scene=e,this._nonVRCamera=null,this._attachedToElement=!1,this._spectatorCamera=null,this._originalSceneAutoClear=!0,this._supported=!1,this._spectatorMode=!1,this._lastTimestamp=0,this.onInitialXRPoseSetObservable=new r.y$,this.onStateChangedObservable=new r.y$,this.state=Ea.NOT_IN_XR,this.sessionManager=new Da(e),this.camera=new $_("webxr",e,this.sessionManager),this.featuresManager=new it(this.sessionManager),e.onDisposeObservable.addOnce((()=>{this.dispose()}))}static CreateAsync(e){const t=new Q_(e);return t.sessionManager.initializeAsync().then((()=>(t._supported=!0,t))).catch((e=>{throw t._setState(Ea.NOT_IN_XR),t.dispose(),e}))}dispose(){var e;this.exitXRAsync(),this.camera.dispose(),this.onStateChangedObservable.clear(),this.onInitialXRPoseSetObservable.clear(),this.sessionManager.dispose(),null===(e=this._spectatorCamera)||void 0===e||e.dispose(),this._nonVRCamera&&(this._scene.activeCamera=this._nonVRCamera)}async enterXRAsync(e,t,i=this.sessionManager.getWebXRRenderTarget(),n={}){var s,r,o;if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(Ea.ENTERING_XR),"viewer"!==t&&"local"!==t&&(n.optionalFeatures=n.optionalFeatures||[],n.optionalFeatures.push(t)),n=await this.featuresManager._extendXRSessionInitObject(n),"immersive-ar"===e&&"unbounded"!==t&&p.Y.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode");try{await this.sessionManager.initializeSessionAsync(e,n),await this.sessionManager.setReferenceSpaceTypeAsync(t);const a=await i.initializeXRLayerAsync(this.sessionManager.session),l={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};return this.featuresManager.getEnabledFeature(tt.LAYERS)||(l.baseLayer=a),this.sessionManager.updateRenderState(l),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!(null===(r=null===(s=this._nonVRCamera)||void 0===s?void 0:s.inputs)||void 0===r?void 0:r.attachedToElement),null===(o=this._nonVRCamera)||void 0===o||o.detachControl(),this._scene.activeCamera=this.camera,"immersive-ar"!==e?this._nonXRToXRCamera():(this._scene.autoClear=!1,this.camera.compensateOnFirstFrame=!1,this.camera.position.set(0,0,0),this.camera.rotationQuaternion.set(0,0,0,1),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)),this.sessionManager.onXRSessionEnded.addOnce((()=>{this.state!==Ea.EXITING_XR&&this._setState(Ea.EXITING_XR),this.camera.rigCameras.forEach((e=>{e.outputRenderTarget=null})),this._scene.autoClear=this._originalSceneAutoClear,this._scene.activeCamera=this._nonVRCamera,this._attachedToElement&&this._nonVRCamera&&this._nonVRCamera.attachControl(!!this._nonVRCamera.inputs.noPreventDefault),"immersive-ar"!==e&&this.camera.compensateOnFirstFrame&&(this._nonVRCamera.setPosition?this._nonVRCamera.setPosition(this.camera.position):this._nonVRCamera.position.copyFrom(this.camera.position)),this._setState(Ea.NOT_IN_XR)})),this.sessionManager.onXRFrameObservable.addOnce((()=>{this._setState(Ea.IN_XR)})),this.sessionManager}catch(a){throw console.log(a),console.log(a.message),this._setState(Ea.NOT_IN_XR),a}}exitXRAsync(){return this.state!==Ea.IN_XR?Promise.resolve():(this._setState(Ea.EXITING_XR),this.sessionManager.exitXRAsync())}enableSpectatorMode(e){this._spectatorMode||(this._spectatorMode=!0,this._switchSpectatorMode(e))}disableSpecatatorMode(){this._spectatorMode&&(this._spectatorMode=!1,this._switchSpectatorMode())}_switchSpectatorMode(e){const t=1/((null==e?void 0:e.fps)?e.fps:1e3)*1e3,i=(null==e?void 0:e.preferredCameraIndex)?null==e?void 0:e.preferredCameraIndex:0,n=()=>{if(this._spectatorCamera){this.sessionManager.currentTimestamp-this._lastTimestamp>=t&&(this._lastTimestamp=this.sessionManager.currentTimestamp,this._spectatorCamera.position.copyFrom(this.camera.rigCameras[i].globalPosition),this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[i].absoluteRotation))}};if(this._spectatorMode){if(i>=this.camera.rigCameras.length)throw new Error("the preferred camera index is beyond the length of rig camera array.");const e=()=>{this.state===Ea.IN_XR?(this._spectatorCamera=new qn("webxr-spectator",o.P.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new o._f,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(n),this._scene.onAfterRenderCameraObservable.add((e=>{e===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)}))):this.state===Ea.EXITING_XR&&(this.sessionManager.onXRFrameObservable.removeCallback(n),this._scene.activeCameras=null)};this.onStateChangedObservable.add(e),e()}else this.sessionManager.onXRFrameObservable.removeCallback(n),this._scene.activeCameras=[this.camera]}_nonXRToXRCamera(){this.camera.setTransformationFromNonVRCamera(this._nonVRCamera),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)}_setState(e){this.state!==e&&(this.state=e,this.onStateChangedObservable.notifyObservers(this.state))}}class Z_{constructor(e,t,i=-1,n=[]){this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=n,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new r.y$,this.onButtonStateChangedObservable=new r.y$}get axes(){return this._axes}get changes(){return this._changes}get hasChanges(){return this._hasChanges}get pressed(){return this._pressed}get touched(){return this._touched}get value(){return this._currentValue}dispose(){this.onAxisValueChangedObservable.clear(),this.onButtonStateChangedObservable.clear()}isAxes(){return 0!==this._axesIndices.length}isButton(){return-1!==this._buttonIndex}update(e){let t=!1,i=!1;if(this._hasChanges=!1,this._changes={},this.isButton()){const i=e.buttons[this._buttonIndex];if(!i)return;this._currentValue!==i.value&&(this.changes.value={current:i.value,previous:this._currentValue},t=!0,this._currentValue=i.value),this._touched!==i.touched&&(this.changes.touched={current:i.touched,previous:this._touched},t=!0,this._touched=i.touched),this._pressed!==i.pressed&&(this.changes.pressed={current:i.pressed,previous:this._pressed},t=!0,this._pressed=i.pressed)}this.isAxes()&&(this._axes.x!==e.axes[this._axesIndices[0]]&&(this.changes.axes={current:{x:e.axes[this._axesIndices[0]],y:this._axes.y},previous:{x:this._axes.x,y:this._axes.y}},this._axes.x=e.axes[this._axesIndices[0]],i=!0),this._axes.y!==e.axes[this._axesIndices[1]]&&(this.changes.axes?this.changes.axes.current.y=e.axes[this._axesIndices[1]]:this.changes.axes={current:{x:this._axes.x,y:e.axes[this._axesIndices[1]]},previous:{x:this._axes.x,y:this._axes.y}},this._axes.y=e.axes[this._axesIndices[1]],i=!0)),t&&(this._hasChanges=!0,this.onButtonStateChangedObservable.notifyObservers(this)),i&&(this._hasChanges=!0,this.onAxisValueChangedObservable.notifyObservers(this._axes))}}Z_.BUTTON_TYPE="button",Z_.SQUEEZE_TYPE="squeeze",Z_.THUMBSTICK_TYPE="thumbstick",Z_.TOUCHPAD_TYPE="touchpad",Z_.TRIGGER_TYPE="trigger";class J_{constructor(e,t,i,n,s=!1,o){this.scene=e,this.layout=t,this.gamepadObject=i,this.handedness=n,this._doNotLoadControllerMesh=s,this._controllerCache=o,this._initComponent=e=>{if(!e)return;const t=this.layout.components[e],i=t.type,n=t.gamepadIndices.button,s=[];void 0!==t.gamepadIndices.xAxis&&void 0!==t.gamepadIndices.yAxis&&s.push(t.gamepadIndices.xAxis,t.gamepadIndices.yAxis),this.components[e]=new Z_(e,i,n,s)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new r.y$,t.components&&Object.keys(t.components).forEach(this._initComponent)}dispose(){this.getComponentIds().forEach((e=>this.getComponent(e).dispose())),this.rootMesh&&(this.rootMesh.getChildren(void 0,!0).forEach((e=>{e.setEnabled(!1)})),this.rootMesh.dispose(!!this._controllerCache,!this._controllerCache))}getAllComponentsOfType(e){return this.getComponentIds().map((e=>this.components[e])).filter((t=>t.type===e))}getComponent(e){return this.components[e]}getComponentIds(){return Object.keys(this.components)}getComponentOfType(e){return this.getAllComponentsOfType(e)[0]||null}getMainComponent(){return this.getComponent(this.layout.selectComponentId)}async loadModel(){const e=!this._getModelLoadingConstraints();let t=this._getGenericFilenameAndPath();return e?p.Y.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),new Promise(((i,n)=>{const s=t=>{e?this._getGenericParentMesh(t):this._setRootMesh(t),this._processLoadedModel(t),this._modelReady=!0,this.onModelLoadedObservable.notifyObservers(this),i(!0)};if(this._controllerCache){const e=this._controllerCache.filter((e=>e.filename===t.filename&&e.path===t.path));if(e[0])return e[0].meshes.forEach((e=>e.setEnabled(!0))),void s(e[0].meshes)}ht.ImportMesh("",t.path,t.filename,this.scene,(e=>{this._controllerCache&&this._controllerCache.push(Object.assign(Object.assign({},t),{meshes:e})),s(e)}),null,((e,i)=>{p.Y.Log(i),p.Y.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),n(i)}))}))}updateFromXRFrame(e){this.getComponentIds().forEach((e=>this.getComponent(e).update(this.gamepadObject))),this.updateModel(e)}get handness(){return this.handedness}pulse(e,t,i=0){return this.gamepadObject.hapticActuators&&this.gamepadObject.hapticActuators[i]?this.gamepadObject.hapticActuators[i].pulse(e,t):Promise.resolve(!1)}_getChildByName(e,t){return e.getChildren((e=>e.name===t),!1)[0]}_getImmediateChildByName(e,t){return e.getChildren((e=>e.name==t),!0)[0]}_lerpTransform(e,t,i){if(!e.minMesh||!e.maxMesh||!e.valueMesh)return;if(!e.minMesh.rotationQuaternion||!e.maxMesh.rotationQuaternion||!e.valueMesh.rotationQuaternion)return;const n=i?.5*t+.5:t;o._f.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,n,e.valueMesh.rotationQuaternion),o.P.LerpToRef(e.minMesh.position,e.maxMesh.position,n,e.valueMesh.position)}updateModel(e){this._modelReady&&this._updateModel(e)}_getGenericFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getGenericParentMesh(e){this.rootMesh=new ee.Kj(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.parent||(e.isPickable=!1,e.setParent(this.rootMesh))})),this.rootMesh.rotationQuaternion=o._f.FromEulerAngles(0,Math.PI,0)}}class em extends J_{constructor(e,t,i){super(e,tm[i],t,i),this.profileId=em.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new ee.Kj(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.isPickable=!1,e.parent||e.setParent(this.rootMesh)})),this.rootMesh.rotationQuaternion=o._f.FromEulerAngles(0,Math.PI,0)}_updateModel(){}}em.ProfileId="generic-trigger";const tm={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-none",assetPath:"none.glb"}};class im extends J_{constructor(e,t,i,n,s){super(e,i.layouts[t.handedness||"none"],t.gamepad,t.handedness,void 0,s),this._repositoryUrl=n,this.controllerCache=s,this._buttonMeshMapping={},this._touchDots={},this.profileId=i.profileId}dispose(){super.dispose(),this.controllerCache||Object.keys(this._touchDots).forEach((e=>{this._touchDots[e].dispose()}))}_getFilenameAndPath(){return{filename:this.layout.assetPath,path:`${this._repositoryUrl}/profiles/${this.profileId}/`}}_getModelLoadingConstraints(){const e=ht.IsPluginForExtensionAvailable(".glb");return e||p.Y.Warn("glTF / glb loader was not registered, using generic controller instead"),e}_processLoadedModel(e){this.getComponentIds().forEach((e=>{const t=this.layout.components[e];this._buttonMeshMapping[e]={mainMesh:this._getChildByName(this.rootMesh,t.rootNodeName),states:{}},Object.keys(t.visualResponses).forEach((i=>{const n=t.visualResponses[i];if("transform"===n.valueNodeProperty)this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,n.valueNodeName),minMesh:this._getChildByName(this.rootMesh,n.minNodeName),maxMesh:this._getChildByName(this.rootMesh,n.maxNodeName)};else{const s=t.type===Z_.TOUCHPAD_TYPE&&t.touchPointNodeName?t.touchPointNodeName:n.valueNodeName;if(this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,s)},t.type===Z_.TOUCHPAD_TYPE&&!this._touchDots[i]){const t=gl(i+"dot",{diameter:.0015,segments:8},this.scene);t.material=new _a(i+"mat",this.scene),t.material.diffuseColor=a.Wo.Red(),t.parent=this._buttonMeshMapping[e].states[i].valueMesh||null,t.isVisible=!1,this._touchDots[i]=t}}}))}))}_setRootMesh(e){let t;this.rootMesh=new ee.Kj(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;i{const t=this.getComponent(e);if(!t.hasChanges)return;const i=this._buttonMeshMapping[e],n=this.layout.components[e];Object.keys(n.visualResponses).forEach((e=>{const s=n.visualResponses[e];let r=t.value;if("xAxis"===s.componentProperty?r=t.axes.x:"yAxis"===s.componentProperty&&(r=t.axes.y),"transform"===s.valueNodeProperty)this._lerpTransform(i.states[e],r,"button"!==s.componentProperty);else{const n=i.states[e].valueMesh;n&&(n.isVisible=t.touched||t.pressed),this._touchDots[e]&&(this._touchDots[e].isVisible=t.touched||t.pressed)}}))}))}}const nm=[];class sm{static ClearProfilesCache(){this._ProfilesList=null,this._ProfileLoadingPromises={}}static DefaultFallbacks(){this.RegisterFallbacksForProfileId("google-daydream",["generic-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive-focus",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("magicleap-one",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("windows-mixed-reality",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("microsoft-mixed-reality",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-go",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("oculus-touch-v2",["oculus-touch","generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-touch",["generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-gearvr",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-odyssey",["generic-touchpad"]),this.RegisterFallbacksForProfileId("valve-index",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("generic-hand-select",["generic-trigger"])}static FindFallbackWithProfileId(e){const t=this._Fallbacks[e]||[];return t.unshift(e),t}static GetMotionControllerWithXRInput(e,t,i){const n=[];if(i&&n.push(i),n.push(...e.profiles||[]),n.length&&!n[0]&&n.pop(),e.gamepad&&e.gamepad.id&&e.gamepad.id===(e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0))n.push("oculus-touch-v2");const s=n.indexOf("windows-mixed-reality");if(-1!==s&&n.splice(s,0,"microsoft-mixed-reality"),n.length||n.push("generic-trigger"),this.UseOnlineRepository){const i=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,s=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return i.call(this,n,e,t).catch((()=>s.call(this,n,e,t)))}return this._LoadProfilesFromAvailableControllers(n,e,t)}static RegisterController(e,t){this._AvailableControllers[e]=t}static RegisterFallbacksForProfileId(e,t){this._Fallbacks[e]?this._Fallbacks[e].push(...t):this._Fallbacks[e]=t}static UpdateProfilesList(){return this._ProfilesList=se.w1.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then((e=>JSON.parse(e.toString()))),this._ProfilesList}static ClearControllerCache(){nm.forEach((e=>{e.meshes.forEach((e=>{e.dispose(!1,!0)}))})),nm.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then((()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList())).then((t=>{for(let i=0;i(this._ProfileLoadingPromises[e]||(this._ProfileLoadingPromises[e]=se.w1.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${e}/profile.json`,!1).then((e=>JSON.parse(e)))),this._ProfileLoadingPromises[e]))).then((e=>new im(i,t,e,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:nm)))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let n=0;nnew em(t,e.gamepad,e.handedness))),sm.DefaultFallbacks();let rm=0;class om{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new o.P,this._disposed=!1,this.onDisposeObservable=new r.y$,this.onMeshLoadedObservable=new r.y$,this.onMotionControllerInitObservable=new r.y$,this._uniqueId=`controller-${rm++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new ie.x(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new o._f,this.inputSource.gripSpace&&(this.grip=new ie.x(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new o._f),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&"tracked-pointer"===this.inputSource.targetRayMode&&sm.GetMotionControllerWithXRInput(t,e,this._options.forceControllerProfile).then((e=>{this.motionController=e,this.onMotionControllerInitObservable.notifyObservers(e),this._options.doNotLoadControllerMesh||this.motionController._doNotLoadControllerMesh||this.motionController.loadModel().then((e=>{var t;e&&this.motionController&&this.motionController.rootMesh&&(this._options.renderingGroupId&&(this.motionController.rootMesh.renderingGroupId=this._options.renderingGroupId,this.motionController.rootMesh.getChildMeshes(!1).forEach((e=>e.renderingGroupId=this._options.renderingGroupId))),this.onMeshLoadedObservable.notifyObservers(this.motionController.rootMesh),this.motionController.rootMesh.parent=this.grip||this.pointer,this.motionController.disableAnimation=!!this._options.disableMotionControllerAnimation),this._disposed&&(null===(t=this.motionController)||void 0===t||t.dispose())}))}),(()=>{se.w1.Warn("Could not find a matching motion controller for the registered input source")}))}get uniqueId(){return this._uniqueId}dispose(){this.grip&&this.grip.dispose(!0),this.motionController&&this.motionController.dispose(),this.pointer.dispose(!0),this.onMotionControllerInitObservable.clear(),this.onMeshLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._disposed=!0}getWorldPointerRayToRef(e,t=!1){const i=t&&this.grip?this.grip:this.pointer;o.P.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i){const n=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=n,n){const e=n.transform.position;this.pointer.position.set(e.x,e.y,e.z);const t=n.transform.orientation;this.pointer.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.pointer.position.z*=-1,this.pointer.rotationQuaternion.z*=-1,this.pointer.rotationQuaternion.w*=-1),this.pointer.parent=i.parent}if(this.inputSource.gripSpace&&this.grip){const n=e.getPose(this.inputSource.gripSpace,t);if(n){const e=n.transform.position,t=n.transform.orientation;this.grip.position.set(e.x,e.y,e.z),this.grip.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.grip.position.z*=-1,this.grip.rotationQuaternion.z*=-1,this.grip.rotationQuaternion.w*=-1)}this.grip.parent=i.parent}this.motionController&&this.motionController.updateFromXRFrame(e)}}class am{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new r.y$,this.onControllerRemovedObservable=new r.y$,this._onInputSourcesChange=e=>{this._addAndRemoveControllers(e.added,e.removed)},this._sessionEndedObserver=this.xrSessionManager.onXRSessionEnded.add((()=>{this._addAndRemoveControllers([],this.controllers.map((e=>e.inputSource)))})),this._sessionInitObserver=this.xrSessionManager.onXRSessionInit.add((e=>{e.addEventListener("inputsourceschange",this._onInputSourcesChange)})),this._frameObserver=this.xrSessionManager.onXRFrameObservable.add((e=>{this.controllers.forEach((t=>{t.updateFromXRFrame(e,this.xrSessionManager.referenceSpace,this.xrCamera)}))})),this._options.customControllersRepositoryURL&&(sm.BaseRepositoryUrl=this._options.customControllersRepositoryURL),sm.UseOnlineRepository=!this._options.disableOnlineControllerRepository,sm.UseOnlineRepository)try{sm.UpdateProfilesList().catch((()=>{sm.UseOnlineRepository=!1}))}catch(n){sm.UseOnlineRepository=!1}}_addAndRemoveControllers(e,t){const i=this.controllers.map((e=>e.inputSource));for(const r of e)if(-1===i.indexOf(r)){const e=new om(this.xrSessionManager.scene,r,Object.assign(Object.assign({},this._options.controllerOptions||{}),{forceControllerProfile:this._options.forceInputProfile,doNotLoadControllerMesh:this._options.doNotLoadControllerMeshes,disableMotionControllerAnimation:this._options.disableControllerAnimation}));this.controllers.push(e),this.onControllerAddedObservable.notifyObservers(e)}const n=[],s=[];this.controllers.forEach((e=>{-1===t.indexOf(e.inputSource)?n.push(e):s.push(e)})),this.controllers=n,s.forEach((e=>{this.onControllerRemovedObservable.notifyObservers(e),e.dispose()}))}dispose(){this.controllers.forEach((e=>{e.dispose()})),this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver),this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver),this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver),this.onControllerAddedObservable.clear(),this.onControllerRemovedObservable.clear(),sm.ClearControllerCache()}}class lm extends nt{constructor(e,t){super(e),this._options=t,this._attachController=e=>{if(this._controllers[e.uniqueId])return;const{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(e.pointer);switch(this._controllers[e.uniqueId]={xrController:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new qe(new o.P,new o.P),disabledByNearInteraction:!1,id:lm._IdCounter++},this._attachedController?!this._options.enablePointerSelectionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enablePointerSelectionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachTrackedPointerRayMode(e);case"gaze":return this._attachGazeMode(e);case"screen":return this._attachScreenRayMode(e)}},this._controllers={},this._tmpVectorForPickCompare=new o.P,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new a.Wo(.9,.9,.9),this.laserPointerDefaultColor=new a.Wo(.7,.7,.7),this.selectionMeshDefaultColor=new a.Wo(.8,.8,.8),this.selectionMeshPickedColor=new a.Wo(.3,.3,1),this._identityMatrix=o.y3.Identity(),this._screenCoordinatesRef=o.P.Zero(),this._viewportRef=new Nt.l(0,0,0,0),this._scene=this._xrSessionManager.scene}attach(){if(!super.attach())return!1;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),this._scene.constantlyUpdateMeshUnderPointer=!0,this._options.gazeCamera){const e=this._options.gazeCamera,{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(e);this._controllers.camera={webXRCamera:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new qe(new o.P,new o.P),disabledByNearInteraction:!1,id:lm._IdCounter++},this._attachGazeMode()}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;i{const t=this._controllers[e];if(!this._options.enablePointerSelectionOnAllControllers&&e!==this._attachedController||t.disabledByNearInteraction)return t.selectionMesh.isVisible=!1,t.laserPointer.isVisible=!1,void(t.pick=null);let i;if(t.laserPointer.isVisible=this.displayLaserPointer,t.xrController)i=t.xrController.pointer.position,t.xrController.getWorldPointerRayToRef(t.tmpRay);else{if(!t.webXRCamera)return;i=t.webXRCamera.position,t.webXRCamera.getForwardRayToRef(t.tmpRay)}if(this._options.maxPointerDistance&&(t.tmpRay.length=this._options.maxPointerDistance),!this._options.disableScenePointerVectorUpdate&&i){const e=this._xrSessionManager.scene,n=this._options.xrInput.xrCamera;n&&(n.viewport.toGlobalToRef(e.getEngine().getRenderWidth(),e.getEngine().getRenderHeight(),this._viewportRef),o.P.ProjectToRef(i,this._identityMatrix,e.getTransformMatrix(),this._viewportRef,this._screenCoordinatesRef),"number"!=typeof this._screenCoordinatesRef.x||"number"!=typeof this._screenCoordinatesRef.y||isNaN(this._screenCoordinatesRef.x)||isNaN(this._screenCoordinatesRef.y)||(e.pointerX=this._screenCoordinatesRef.x,e.pointerY=this._screenCoordinatesRef.y,t.screenCoordinates={x:this._screenCoordinatesRef.x,y:this._screenCoordinatesRef.y}))}let n=null;this._utilityLayerScene&&(n=this._utilityLayerScene.pickWithRay(t.tmpRay,this._utilityLayerScene.pointerMovePredicate||this.raySelectionPredicate));const s=this._scene.pickWithRay(t.tmpRay,this._scene.pointerMovePredicate||this.raySelectionPredicate);n&&n.hit?s&&s.hit?n.distance{if(t.pick){if(this._augmentPointerInit(l,t.id,t.screenCoordinates),t.laserPointer.material.alpha=0,r.isVisible=!1,t.pick.hit)if(this._pickingMoved(s,t.pick))a&&(this._options.disablePointerUpOnTouchOut||this._scene.simulatePointerUp(t.pick,l)),a=!1,o=0;else if(o>i/10&&(r.isVisible=!0),o+=this._scene.getEngine().getDeltaTime(),o>=i)this._scene.simulatePointerDown(t.pick,l),a=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),r.isVisible=!1;else{const e=1-o/i;r.scaling.set(e,e,e)}else a=!1,o=0;this._scene.simulatePointerMove(t.pick,l),s=t.pick}})),void 0!==this._options.renderingGroupId&&(r.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce((()=>{t.pick&&!this._options.disablePointerUpOnTouchOut&&a&&(this._scene.simulatePointerUp(t.pick,l),t.finalPointerUpTriggered=!0),r.dispose()}))}_attachScreenRayMode(e){const t=this._controllers[e.uniqueId];let i=!1;const n={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{this._augmentPointerInit(n,t.id,t.screenCoordinates),!t.pick||this._options.disablePointerUpOnTouchOut&&i||(i?this._scene.simulatePointerMove(t.pick,n):(this._scene.simulatePointerDown(t.pick,n),t.pointerDownTriggered=!0,i=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,n)))})),e.onDisposeObservable.addOnce((()=>{this._augmentPointerInit(n,t.id,t.screenCoordinates),this._xrSessionManager.runInXRFrame((()=>{t.pick&&!t.finalPointerUpTriggered&&i&&!this._options.disablePointerUpOnTouchOut&&(this._scene.simulatePointerUp(t.pick,n),t.finalPointerUpTriggered=!0)}))}))}_attachTrackedPointerRayMode(e){const t=this._controllers[e.uniqueId];if(this._options.forceGazeMode)return this._attachGazeMode(e);const i={pointerId:t.id,pointerType:"xr"};if(t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{t.laserPointer.material.disableLighting=this.disablePointerLighting,t.selectionMesh.material.disableLighting=this.disableSelectionMeshLighting,t.pick&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerMove(t.pick,i))})),e.inputSource.gamepad){const n=n=>{this._options.overrideButtonId&&(t.selectionComponent=n.getComponent(this._options.overrideButtonId)),t.selectionComponent||(t.selectionComponent=n.getMainComponent()),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add((n=>{if(n.changes.pressed){const s=n.changes.pressed.current;t.pick?(this._options.enablePointerSelectionOnAllControllers||e.uniqueId===this._attachedController)&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),s?(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor):(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor)):!s||this._options.enablePointerSelectionOnAllControllers||this._options.disableSwitchOnClick||(this._attachedController=e.uniqueId)}}))};e.motionController?n(e.motionController):e.onMotionControllerInitObservable.add(n)}else{const e=e=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor)},n=e=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor)};t.eventListeners={selectend:n,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",n)}}_convertNormalToDirectionOfRay(e,t){if(e){Math.acos(o.P.Dot(e,t.direction)){const i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)})),!t.finalPointerUpTriggered&&t.pointerDownTriggered){const e={pointerId:t.id,pointerType:"xr"};this._xrSessionManager.runInXRFrame((()=>{this._augmentPointerInit(e,t.id,t.screenCoordinates),this._scene.simulatePointerUp(t.pick||new je.p,e),t.finalPointerUpTriggered=!0}))}this._xrSessionManager.scene.onBeforeRenderObservable.addOnce((()=>{try{if(t.selectionMesh.dispose(),t.laserPointer.dispose(),delete this._controllers[e],this._attachedController===e){const e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}catch(i){se.w1.Warn("controller already detached.")}}))}}_generateNewMeshPair(e){const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||dl.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():Fa("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;const n=new _a("laserPointerMat",t);n.emissiveColor=this.laserPointerDefaultColor,n.alpha=.7,i.material=n,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1,i.isVisible=!1;const s=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():La("gazeTracker",{diameter:.0105,thickness:.0075,tessellation:20},t);s.bakeCurrentTransformIntoVertices(),s.isPickable=!1,s.isVisible=!1;const r=new _a("targetMat",t);return r.specularColor=a.Wo.Black(),r.emissiveColor=this.selectionMeshDefaultColor,r.backFaceCulling=!1,s.material=r,void 0!==this._options.renderingGroupId&&(i.renderingGroupId=this._options.renderingGroupId,s.renderingGroupId=this._options.renderingGroupId),{laserPointer:i,selectionMesh:s}}_pickingMoved(e,t){var i;if(!e.hit||!t.hit)return!0;if(!(e.pickedMesh&&e.pickedPoint&&t.pickedMesh&&t.pickedPoint))return!0;if(e.pickedMesh!==t.pickedMesh)return!0;null===(i=e.pickedPoint)||void 0===i||i.subtractToRef(t.pickedPoint,this._tmpVectorForPickCompare),this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x),Math.abs(this._tmpVectorForPickCompare.y),Math.abs(this._tmpVectorForPickCompare.z));const n=.01*(this._options.gazeModePointerMovedFactor||1)*t.distance;return this._tmpVectorForPickCompare.length()>n}_updatePointerDistance(e,t=100){e.scaling.y=t,this._scene.useRightHandedSystem&&(t*=-1),e.position.z=t/2+.05}_augmentPointerInit(e,t,i){e.pointerId=t,e.pointerType="xr",i&&(e.screenX=i.x,e.screenY=i.y)}get lasterPointerDefaultColor(){return this.laserPointerDefaultColor}}lm._IdCounter=200,lm.Name=tt.POINTER_SELECTION,lm.Version=1,it.AddWebXRFeature(lm.Name,((e,t)=>()=>new lm(e,t)),lm.Version,!0);var hm,cm,dm,um=i(4735);um.P.prototype._projectOnTrianglesToRef=function(e,t,i,n,s,r){const a=o.jp.Vector3[0],l=o.jp.Vector3[1];let h=1/0;for(let c=this.indexStart;c{if(this._controllers[e.uniqueId])return;const{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:n}=this._generateNewTouchPointMesh(),s=this._generateVisualCue();switch(this._controllers[e.uniqueId]={xrController:e,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:n,currentAnimationState:hm.DEHYDRATED,grabRay:new qe(new o.P,new o.P),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,id:pm._IdCounter++,pickedPointVisualCue:s},this._attachedController?!this._options.enableNearInteractionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enableNearInteractionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachNearInteractionMode(e);case"gaze":case"screen":return null}},this._controllers={},this._farInteractionFeature=null,this.selectionMeshDefaultColor=new a.Wo(.8,.8,.8),this.selectionMeshPickedColor=new a.Wo(.3,.3,1),this._hoverRadius=.1,this._pickRadius=.02,this._controllerPickRadius=.03,this._nearGrabLengthScale=5,this._scene=this._xrSessionManager.scene,void 0===this._options.nearInteractionControllerMode&&(this._options.nearInteractionControllerMode=cm.CENTERED_IN_FRONT),this._options.farInteractionFeature&&(this._farInteractionFeature=this._options.farInteractionFeature)}attach(){return!!super.attach()&&(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),this._scene.constantlyUpdateMeshUnderPointer=!0,!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){const t=Object.keys(this._controllers);for(let i=0;ie.currentAnimationState)switch(e.currentAnimationState){case hm.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===hm.HOVER)break;case hm.HOVER:if(e.touchCollisionMeshFunction(!0),t===hm.TOUCH)break}else switch(e.currentAnimationState){case hm.TOUCH:if(e.touchCollisionMeshFunction(!1),t===hm.HOVER)break;case hm.HOVER:if(e.hydrateCollisionMeshFunction(!1),t===hm.DEHYDRATED)break}e.currentAnimationState=t}}_processTouchPoint(e,t,i){var n;const s=this._controllers[e];s.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(o.jp.Vector3[0]),s.grabRay.direction.copyFrom(o.jp.Vector3[0]),this._options.nearInteractionControllerMode!==cm.CENTERED_IN_FRONT||(null===(n=s.xrController)||void 0===n?void 0:n.inputSource.hand)||(s.xrController.getWorldPointerRayToRef(this._tmpRay),s.grabRay.origin.addInPlace(this._tmpRay.direction.scale(.05))),s.grabRay.length=this._nearGrabLengthScale*this._hoverRadius,s.touchCollisionMesh.position.copyFrom(s.grabRay.origin)}_onXRFrame(e){Object.keys(this._controllers).forEach((t=>{var i;const n=this._controllers[t],s=null===(i=n.xrController)||void 0===i?void 0:i.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!n.xrController||!s&&(!this._options.nearInteractionControllerMode||!n.xrController.inputSource.gamepad))return void(n.pick=null);if(n.hoverInteraction=!1,n.nearInteraction=!1,!n.xrController)return;if(s){const i=s.get("index-finger-tip");if(i){const n=e.getJointPose(i,this._xrSessionManager.referenceSpace);if(n&&n.transform){const e=this._scene.useRightHandedSystem?1:-1;o.jp.Vector3[0].set(n.transform.position.x,n.transform.position.y,n.transform.position.z*e),o.jp.Quaternion[0].set(n.transform.orientation.x,n.transform.orientation.y,n.transform.orientation.z*e,n.transform.orientation.w*e),this._processTouchPoint(t,o.jp.Vector3[0],o.jp.Quaternion[0])}}}else if(n.xrController.inputSource.gamepad&&this._options.nearInteractionControllerMode!==cm.DISABLED){let e=n.xrController.pointer;n.xrController.grip&&this._options.nearInteractionControllerMode===cm.CENTERED_ON_CONTROLLER&&(e=n.xrController.grip),this._processTouchPoint(t,e.position,e.rotationQuaternion)}const r=(e,t)=>{let i=null;return i=t&&t.hit?e&&e.hit?t.distance{let t=new je.p,i=!1;const n=e&&e.pickedPoint&&e.hit;return(null==e?void 0:e.pickedPoint)&&(i=0===e.pickedPoint.x&&0===e.pickedPoint.y&&0===e.pickedPoint.z),n&&!i&&(t=e),t};if(!n.grabInteraction){let e=null,t=null;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(n,this._hoverRadius,this._utilityLayerScene,(e=>this._nearInteractionPredicate(e))));const i=r(this._pickWithSphere(n,this._hoverRadius,this._scene,(e=>this._nearInteractionPredicate(e))),t);if(i&&i.hit&&(e=a(i),e.hit&&(n.hoverInteraction=!0)),n.hoverInteraction){let t=null;const i=s?this._pickRadius:this._controllerPickRadius;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(n,i,this._utilityLayerScene,(e=>this._nearPickPredicate(e))));const o=a(r(this._pickWithSphere(n,i,this._scene,(e=>this._nearPickPredicate(e))),t));o.hit&&(e=o,n.nearInteraction=!0)}n.stalePick=n.pick,n.pick=e,n.pick&&n.pick.pickedPoint&&n.pick.hit?(n.meshUnderPointer=n.pick.pickedMesh,n.pickedPointVisualCue.position.copyFrom(n.pick.pickedPoint),n.pickedPointVisualCue.isVisible=!0,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(n.id,!0)):(n.meshUnderPointer=null,n.pickedPointVisualCue.isVisible=!1,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(n.id,!1))}let l=hm.DEHYDRATED;n.grabInteraction||n.nearInteraction?l=hm.TOUCH:n.hoverInteraction&&(l=hm.HOVER),this._handleTransitionAnimation(n,l)}))}get _utilityLayerScene(){return this._options.customUtilityLayerScene||dl.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||dl.DefaultUtilityLayer.utilityLayerScene:this._scene,t=gl("nearInteraction",{diameter:.0105},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=o._f.Identity();const i=new _a("targetMat",e);return i.specularColor=a.Wo.Black(),i.emissiveColor=this.selectionMeshDefaultColor,i.backFaceCulling=!1,t.material=i,t}_isControllerReadyForNearInteraction(e){return!this._farInteractionFeature||this._farInteractionFeature._getPointerSelectionDisabledByPointerId(e)}_attachNearInteractionMode(e){const t=this._controllers[e.uniqueId],i={pointerId:t.id,pointerType:"xr-near"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add((()=>{(this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController)&&t.xrController&&(t.xrController.inputSource.hand||this._options.nearInteractionControllerMode&&t.xrController.inputSource.gamepad)&&(t.pick&&(t.pick.ray=t.grabRay),t.pick&&this._isControllerReadyForNearInteraction(t.id)&&this._scene.simulatePointerMove(t.pick,i),t.nearInteraction&&t.pick&&t.pick.hit?t.nearInteractionTargetMesh||(this._scene.simulatePointerDown(t.pick,i),t.nearInteractionTargetMesh=t.meshUnderPointer):t.nearInteractionTargetMesh&&t.stalePick&&(this._scene.simulatePointerUp(t.stalePick,i),t.nearInteractionTargetMesh=null))}));const n=n=>{this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController&&this._isControllerReadyForNearInteraction(t.id)?(t.pick&&(t.pick.ray=t.grabRay),n&&t.pick&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)?(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i)):!n&&t.pick&&t.grabInteraction&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)):!n||this._options.enableNearInteractionOnAllControllers||this._options.disableSwitchOnClick||(this._attachedController=e.uniqueId)};if(e.inputSource.gamepad){const i=e=>{t.squeezeComponent=e.getComponent("grasp"),t.squeezeComponent?t.onSqueezeButtonChangedObserver=t.squeezeComponent.onButtonStateChangedObservable.add((e=>{if(e.changes.pressed){const t=e.changes.pressed.current;n(t)}})):(t.selectionComponent=e.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add((e=>{if(e.changes.pressed){const t=e.changes.pressed.current;n(t)}})))};e.motionController?i(e.motionController):e.onMotionControllerInitObservable.add(i)}else{const e=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)&&(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i))},n=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)};t.eventListeners={selectend:n,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",n)}}_detachController(e){const t=this._controllers[e];if(t&&(t.squeezeComponent&&t.onSqueezeButtonChangedObserver&&t.squeezeComponent.onButtonStateChangedObservable.remove(t.onSqueezeButtonChangedObserver),t.selectionComponent&&t.onButtonChangedObserver&&t.selectionComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver),t.onFrameObserver&&this._xrSessionManager.onXRFrameObservable.remove(t.onFrameObserver),t.eventListeners&&Object.keys(t.eventListeners).forEach((e=>{const i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)})),t.touchCollisionMesh.dispose(),t.pickedPointVisualCue.dispose(),this._xrSessionManager.runInXRFrame((()=>{const e={pointerId:t.id,pointerType:"xr-near"};this._scene.simulatePointerUp(new je.p,e)})),delete this._controllers[e],this._attachedController===e)){const e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}_generateNewTouchPointMesh(){const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||dl.DefaultUtilityLayer.utilityLayerScene:this._scene,t=gl("PickSphere",{diameter:1},e);t.isVisible=!1,this._options.motionControllerOrbMaterial?t.material=this._options.motionControllerOrbMaterial:Ni.ParseFromSnippetAsync("8RUNKL#3",e).then((e=>{t.material=e}));const i=new K;i.setEasingMode(Y.EASINGMODE_EASEINOUT);const n=new o.P(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius),s=this._controllerPickRadius*(4/3),r=new o.P(s,s,s),a=this._controllerPickRadius*(7/6),l=new o.P(a,a,a),h=.8*this._controllerPickRadius,c=new o.P(h,h,h),d=1.5*this._controllerPickRadius,u=[{frame:0,value:n},{frame:10,value:new o.P(d,d,d)},{frame:18,value:r}],p=[{frame:0,value:r},{frame:10,value:c},{frame:18,value:n}],f=[{frame:0,value:o.P.ZeroReadOnly},{frame:12,value:l},{frame:15,value:n}],_=[{frame:0,value:n},{frame:10,value:o.P.ZeroReadOnly},{frame:15,value:o.P.ZeroReadOnly}],m=new A("touch","scaling",60,A.ANIMATIONTYPE_VECTOR3,A.ANIMATIONLOOPMODE_CONSTANT),g=new A("release","scaling",60,A.ANIMATIONTYPE_VECTOR3,A.ANIMATIONLOOPMODE_CONSTANT),v=new A("hydrate","scaling",60,A.ANIMATIONTYPE_VECTOR3,A.ANIMATIONLOOPMODE_CONSTANT),T=new A("dehydrate","scaling",60,A.ANIMATIONTYPE_VECTOR3,A.ANIMATIONLOOPMODE_CONSTANT);m.setEasingFunction(i),g.setEasingFunction(i),v.setEasingFunction(i),T.setEasingFunction(i),m.setKeys(u),g.setKeys(p),v.setKeys(f),T.setKeys(_);return{touchCollisionMesh:t,touchCollisionMeshFunction:i=>{const n=i?m:g;e.beginDirectAnimation(t,[n],0,18,!1,1)},hydrateCollisionMeshFunction:i=>{const n=i?v:T;i&&(t.isVisible=!0),e.beginDirectAnimation(t,[n],0,15,!1,1,(()=>{i||(t.isVisible=!1)}))}}}_pickWithSphere(e,t,i,n){const s=new je.p;if(s.distance=1/0,e.touchCollisionMesh&&e.xrController){const r=e.touchCollisionMesh.position,o=al.K.CreateFromCenterAndRadius(r,t);for(let t=0;tc&&(h=0,l.copyFrom(t.center)),-1!==h&&h()=>new pm(e,t)),pm.Version,!0);class fm{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}}class _m{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new r.y$,this._onSessionGranted=e=>{this._helper&&this._enterXRWithButtonIndex(0)},this.overlay=document.createElement("div"),this.overlay.classList.add("xr-button-overlay"),!t.ignoreSessionGrantedEvent&&navigator.xr&&navigator.xr.addEventListener("sessiongranted",this._onSessionGranted),"undefined"!=typeof window&&window.location&&"http:"===window.location.protocol&&"localhost"!==window.location.hostname)throw se.w1.Warn("WebXR can only be served over HTTPS"),new Error("WebXR can only be served over HTTPS");if(t.customButtons)this._buttons=t.customButtons;else{this.overlay.style.cssText="z-index:11;position: absolute; right: 20px;bottom: 50px;";const e=t.sessionMode||"immersive-vr",i=t.referenceSpaceType||"local-floor";let n=".babylonVRicon { color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+("undefined"==typeof SVGSVGElement?"https://cdn.babylonjs.com/Assets/vrButton.png":"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";n+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';const s=document.createElement("style");s.appendChild(document.createTextNode(n)),document.getElementsByTagName("head")[0].appendChild(s);const r=document.createElement("button");r.className="babylonVRicon",r.title=`${e} - ${i}`,this._buttons.push(new fm(r,e,i)),this._buttons[this._buttons.length-1].update=function(e){this.element.style.display=null===e||e===this?"":"none",r.className="babylonVRicon"+(e===this?" vrdisplaypresenting":"")},this._updateButtons(null)}const i=e.getEngine().getInputElement();i&&i.parentNode&&(i.parentNode.appendChild(this.overlay),e.onDisposeObservable.addOnce((()=>{this.dispose()})))}async setHelperAsync(e,t){this._helper=e,this._renderTarget=t;const i=this._buttons.map((t=>e.sessionManager.isSessionSupportedAsync(t.sessionMode)));e.onStateChangedObservable.add((e=>{e==Ea.NOT_IN_XR&&this._updateButtons(null)}));(await Promise.all(i)).forEach(((e,t)=>{e?(this.overlay.appendChild(this._buttons[t].element),this._buttons[t].element.onclick=this._enterXRWithButtonIndex.bind(this,t)):se.w1.Warn(`Session mode "${this._buttons[t].sessionMode}" not supported in browser`)}))}static async CreateAsync(e,t,i){const n=new _m(e,i);return await n.setHelperAsync(t,i.renderTarget||void 0),n}async _enterXRWithButtonIndex(e=0){if(this._helper.state==Ea.IN_XR)await this._helper.exitXRAsync(),this._updateButtons(null);else if(this._helper.state==Ea.NOT_IN_XR)try{await this._helper.enterXRAsync(this._buttons[e].sessionMode,this._buttons[e].referenceSpaceType,this._renderTarget,{optionalFeatures:this.options.optionalFeatures,requiredFeatures:this.options.requiredFeatures}),this._updateButtons(this._buttons[e])}catch(t){this._updateButtons(null);const i=this._buttons[e].element,n=i.title;i.title="Error entering XR session : "+n,i.classList.add("xr-error"),this.options.onError&&this.options.onError(t)}}dispose(){const e=this._scene.getEngine().getInputElement();e&&e.parentNode&&e.parentNode.contains(this.overlay)&&e.parentNode.removeChild(this.overlay),this.activeButtonChangedObservable.clear(),navigator.xr.removeEventListener("sessiongranted",this._onSessionGranted)}_updateButtons(e){this._activeButton=e,this._buttons.forEach((e=>{e.update(this._activeButton)})),this.activeButtonChangedObservable.notifyObservers(this._activeButton)}}function mm(e){var t;let i=0;const n=Date.now();e.observableParameters=null!==(t=e.observableParameters)&&void 0!==t?t:{};const s=e.contextObservable.add((t=>{const r=Date.now();i=r-n;const o={startTime:n,currentTime:r,deltaTime:i,completeRate:i/e.timeout,payload:t};e.onTick&&e.onTick(o),e.breakCondition&&e.breakCondition()&&(e.contextObservable.remove(s),e.onAborted&&e.onAborted(o)),i>=e.timeout&&(e.contextObservable.remove(s),e.onEnded&&e.onEnded(o))}),e.observableParameters.mask,e.observableParameters.insertFirst,e.observableParameters.scope);return s}!function(e){e[e.INIT=0]="INIT",e[e.STARTED=1]="STARTED",e[e.ENDED=2]="ENDED"}(dm||(dm={}));class gm extends nt{get rotationEnabled(){return this._rotationEnabled}set rotationEnabled(e){if(this._rotationEnabled=e,this._options.teleportationTargetMesh){const t=this._options.teleportationTargetMesh.getChildMeshes(!1,(e=>"rotationCone"===e.name));t[0]&&t[0].setEnabled(e)}}get teleportationTargetMesh(){return this._options.teleportationTargetMesh||null}constructor(e,t){super(e),this._options=t,this._controllers={},this._snappedToPoint=!1,this._cachedColor4White=new a.HE(1,1,1,1),this._tmpRay=new qe(new o.P,new o.P),this._tmpVector=new o.P,this._tmpQuaternion=new o._f,this.skipNextTeleportation=!1,this.backwardsMovementEnabled=!0,this.backwardsTeleportationDistance=.7,this.parabolicCheckRadius=5,this.parabolicRayEnabled=!0,this.straightRayEnabled=!0,this.rotationAngle=Math.PI/8,this.onTargetMeshPositionUpdatedObservable=new r.y$,this.teleportationEnabled=!0,this._rotationEnabled=!0,this._attachController=e=>{if(this._controllers[e.uniqueId]||this._options.forceHandedness&&e.inputSource.handedness!==this._options.forceHandedness)return;this._controllers[e.uniqueId]={xrController:e,teleportationState:{forward:!1,backwards:!1,rotating:!1,currentRotation:0,baseRotation:0,blocked:!1}};const t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){const i=()=>{if(e.motionController){const i=e.motionController.getComponentOfType(Z_.THUMBSTICK_TYPE)||e.motionController.getComponentOfType(Z_.TOUCHPAD_TYPE);if(!i||this._options.useMainComponentOnly){const i=e.motionController.getMainComponent();if(!i)return;t.teleportationComponent=i,t.onButtonChangedObserver=i.onButtonStateChangedObservable.add((()=>{if(this.teleportationEnabled&&i.changes.pressed)if(i.changes.pressed.current){t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0;mm({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,breakCondition:()=>!i.pressed,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})}else t.teleportationState.forward=!1,this._currentTeleportationControllerId=""}))}else t.teleportationComponent=i,t.onAxisChangedObserver=i.onAxisValueChangedObservable.add((i=>{if(i.y<=.7&&t.teleportationState.backwards&&(t.teleportationState.backwards=!1),i.y>.7&&!t.teleportationState.forward&&this.backwardsMovementEnabled&&!this.snapPointsOnly&&!t.teleportationState.backwards){t.teleportationState.backwards=!0,this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion),this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector),this._tmpVector.x=0,this._tmpVector.z=0,o._f.FromEulerVectorToRef(this._tmpVector,this._tmpQuaternion),this._tmpVector.set(0,0,this.backwardsTeleportationDistance*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),this._tmpVector.rotateByQuaternionToRef(this._tmpQuaternion,this._tmpVector),this._tmpVector.addInPlace(this._options.xrInput.xrCamera.position),this._tmpRay.origin.copyFrom(this._tmpVector),this._tmpRay.length=this._options.xrInput.xrCamera.realWorldHeight+.1,this._tmpRay.direction.set(0,-1,0);const e=this._xrSessionManager.scene.pickWithRay(this._tmpRay,(e=>-1!==this._floorMeshes.indexOf(e)));e&&e.pickedPoint&&(this._options.xrInput.xrCamera.position.x=e.pickedPoint.x,this._options.xrInput.xrCamera.position.z=e.pickedPoint.z)}if(i.y<-.7&&!this._currentTeleportationControllerId&&!t.teleportationState.rotating&&this.teleportationEnabled&&(t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),i.x){if(t.teleportationState.forward)this._currentTeleportationControllerId===t.xrController.uniqueId&&(this.rotationEnabled?setTimeout((()=>{t.teleportationState.currentRotation=Math.atan2(i.x,i.y*(this._xrSessionManager.scene.useRightHandedSystem?1:-1))})):t.teleportationState.currentRotation=0);else if(!t.teleportationState.rotating&&Math.abs(i.x)>.7){t.teleportationState.rotating=!0;const e=this.rotationAngle*(i.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);o._f.FromEulerAngles(0,e,0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion)}}else t.teleportationState.rotating=!1;0===i.x&&0===i.y&&(t.teleportationState.blocked&&(t.teleportationState.blocked=!1,this._setTargetMeshVisibility(!1)),t.teleportationState.forward&&this._teleportForward(e.uniqueId))}))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce((()=>{i()}))}else this._xrSessionManager.scene.onPointerObservable.add((i=>{if(i.type===We.kD.POINTERDOWN){t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0;mm({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})}else i.type===We.kD.POINTERUP&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="")}))},this._options.teleportationTargetMesh||this._createDefaultTargetMesh(),this._floorMeshes=this._options.floorMeshes||[],this._snapToPositions=this._options.snapPositions||[],this._blockedRayColor=this._options.blockedRayColor||new a.HE(1,0,0,.75),this._setTargetMeshVisibility(!1)}get snapPointsOnly(){return!!this._options.snapPointsOnly}set snapPointsOnly(e){this._options.snapPointsOnly=e}addFloorMesh(e){this._floorMeshes.push(e)}addBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[],this._options.pickBlockerMeshes.push(e)}addSnapPoint(e){this._snapToPositions.push(e)}attach(){return!!super.attach()&&(this._currentTeleportationControllerId="",this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._setTargetMeshVisibility(!1),this._currentTeleportationControllerId="",this._controllers={},!0)}dispose(){super.dispose(),this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.dispose(!1,!0)}removeFloorMesh(e){const t=this._floorMeshes.indexOf(e);-1!==t&&this._floorMeshes.splice(t,1)}removeBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[];const t=this._options.pickBlockerMeshes.indexOf(e);-1!==t&&this._options.pickBlockerMeshes.splice(t,1)}removeFloorMeshByName(e){const t=this._xrSessionManager.scene.getMeshByName(e);t&&this.removeFloorMesh(t)}removeSnapPoint(e){let t=this._snapToPositions.indexOf(e);if(-1===t)for(let i=0;i{if(this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(e))return!0;const t=this._floorMeshes.indexOf(e);return-1!==t&&this._floorMeshes[t].absolutePosition.y!(!this._options.pickBlockerMeshes||-1===this._options.pickBlockerMeshes.indexOf(e))||-1!==this._floorMeshes.indexOf(e)));if(o&&o.pickedMesh&&this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(o.pickedMesh))return e.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1),void this._showParabolicPath(o);o&&o.pickedPoint&&(e.teleportationState.blocked=!1,t=!0,this._setTargetMeshPosition(o),this._setTargetMeshVisibility(!0),this._showParabolicPath(o))}this._setTargetMeshVisibility(t)}else this._setTargetMeshVisibility(!1)}else this._disposeBezierCurve(),this._setTargetMeshVisibility(!1)}_createDefaultTargetMesh(){this._options.defaultTargetMeshOptions=this._options.defaultTargetMeshOptions||{};const e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||dl.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=Ga("teleportationTarget",{width:2,height:2,subdivisions:2},e);if(t.isPickable=!1,this._options.defaultTargetMeshOptions.teleportationCircleMaterial)t.material=this._options.defaultTargetMeshOptions.teleportationCircleMaterial;else{const i=512,n=new ma("teleportationPlaneDynamicTexture",i,e,!0);n.hasAlpha=!0;const s=n.getContext(),r=i/2,o=i/2,a=200;s.beginPath(),s.arc(r,o,a,0,2*Math.PI,!1),s.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",s.fill(),s.lineWidth=10,s.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",s.stroke(),s.closePath(),n.update();const l=new _a("teleportationPlaneMaterial",e);l.diffuseTexture=n,t.material=l}const i=La("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){const t=new A("animationInnerCircle","position.y",30,A.ANIMATIONTYPE_FLOAT,A.ANIMATIONLOOPMODE_CYCLE),n=[];n.push({frame:0,value:0}),n.push({frame:30,value:.4}),n.push({frame:60,value:0}),t.setKeys(n);const s=new q;s.setEasingMode(Y.EASINGMODE_EASEINOUT),t.setEasingFunction(s),i.animations=[],i.animations.push(t),e.beginAnimation(i,0,60,!0)}const n=Fa("rotationCone",{diameterTop:0,tessellation:4},e);if(n.isPickable=!1,n.scaling.set(.5,.12,.2),n.rotate(L.RD.X,Math.PI/2),n.position.z=.6,n.parent=i,this._options.defaultTargetMeshOptions.torusArrowMaterial)i.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,n.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{const t=new _a("torusConsMat",e);t.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,t.disableLighting?t.emissiveColor=new a.Wo(.3,.3,1):t.diffuseColor=new a.Wo(.3,.3,1),t.alpha=.9,i.material=t,n.material=t,this._teleportationRingMaterial=t}void 0!==this._options.renderingGroupId&&(t.renderingGroupId=this._options.renderingGroupId,i.renderingGroupId=this._options.renderingGroupId,n.renderingGroupId=this._options.renderingGroupId),this._options.teleportationTargetMesh=t,this._setTargetMeshVisibility(!1)}_detachController(e){const t=this._controllers[e];t&&(t.teleportationComponent&&(t.onAxisChangedObserver&&t.teleportationComponent.onAxisValueChangedObservable.remove(t.onAxisChangedObserver),t.onButtonChangedObserver&&t.teleportationComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver)),delete this._controllers[e])}_findClosestSnapPointWithRadius(e,t=this._options.snapToPositionRadius||.8){let i=null,n=Number.MAX_VALUE;if(this._snapToPositions.length){const s=t*t;this._snapToPositions.forEach((t=>{const r=o.P.DistanceSquared(t,e);r<=s&&r{t.isVisible=e})),e?this._selectionFeature&&this._selectionFeature.detach():(this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null),this._selectionFeature&&this._selectionFeature.attach()))}_disposeBezierCurve(){this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null)}_showParabolicPath(e){if(!e.pickedPoint||!this._currentTeleportationControllerId)return;const t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||dl.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],n=X.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),s=i.teleportationState.blocked?this._blockedRayColor:void 0,r=new Array(26).fill(s||this._cachedColor4White);this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(n.getPoints(),e):this._quadraticBezierCurve=Vl("teleportation path line",{points:n.getPoints(),instance:this._quadraticBezierCurve,updatable:!0,colors:r},t),this._quadraticBezierCurve.isPickable=!1,void 0!==this._options.renderingGroupId&&(this._quadraticBezierCurve.renderingGroupId=this._options.renderingGroupId)}_teleportForward(e){const t=this._controllers[e];if(t&&t.teleportationState.forward&&this.teleportationEnabled&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="",!this.snapPointsOnly||this._snappedToPoint))if(this.skipNextTeleportation)this.skipNextTeleportation=!1;else if(this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.isVisible){const e=this._options.xrInput.xrCamera.realWorldHeight;this._options.xrInput.xrCamera.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position),this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position),this._options.xrInput.xrCamera.position.y+=e,o._f.FromEulerAngles(0,t.teleportationState.currentRotation-(this._xrSessionManager.scene.useRightHandedSystem?Math.PI:0),0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this._options.xrInput.xrCamera.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position)}}}gm.Name=tt.TELEPORTATION,gm.Version=1,it.AddWebXRFeature(gm.Name,((e,t)=>()=>new gm(e,t)),gm.Version,!0);class vm{constructor(){}static CreateAsync(e,t={}){const i=new vm;if(e.onDisposeObservable.addOnce((()=>{i.dispose()})),!t.disableDefaultUI){const n=Object.assign({renderTarget:i.renderTarget},t.uiOptions||{});t.optionalFeatures&&("boolean"==typeof t.optionalFeatures?n.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:n.optionalFeatures=t.optionalFeatures),i.enterExitUI=new _m(e,n)}return Q_.CreateAsync(e).then((e=>{if(i.baseExperience=e,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new am(e.sessionManager,e.camera,Object.assign({controllerOptions:{renderingGroupId:t.renderingGroupId}},t.inputOptions||{})),!t.disablePointerSelection){const e=Object.assign(Object.assign({},t.pointerSelectionOptions),{xrInput:i.input,renderingGroupId:t.renderingGroupId});i.pointerSelection=i.baseExperience.featuresManager.enableFeature(lm.Name,t.useStablePlugins?"stable":"latest",e),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(gm.Name,t.useStablePlugins?"stable":"latest",Object.assign({floorMeshes:t.floorMeshes,xrInput:i.input,renderingGroupId:t.renderingGroupId},t.teleportationOptions)),i.teleportation.setSelectionFeature(i.pointerSelection))}return t.disableNearInteraction||(i.nearInteraction=i.baseExperience.featuresManager.enableFeature(pm.Name,t.useStablePlugins?"stable":"latest",Object.assign({xrInput:i.input,farInteractionFeature:i.pointerSelection,renderingGroupId:t.renderingGroupId,useUtilityLayer:!0,enableNearInteractionOnAllControllers:!0},t.nearInteractionOptions))),i.renderTarget=i.baseExperience.sessionManager.getWebXRRenderTarget(t.outputCanvasOptions),t.disableDefaultUI?void 0:i.enterExitUI.setHelperAsync(i.baseExperience,i.renderTarget)})).then((()=>i)).catch((e=>(p.Y.Error("Error initializing XR"),p.Y.Error(e),i)))}dispose(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()}}function Tm(e){for(;e.firstChild;)e.removeChild(e.firstChild);e.srcObject=null,e.src="",e.removeAttribute("src")}N.x.prototype.createDefaultLight=function(e=!1){if(e&&this.lights)for(let t=0;te.isVisible&&e.isEnabled())),n=t.max.subtract(t.min),s=t.min.add(n.scale(.5));let r,a=1.5*n.length();if(isFinite(a)||(a=1,s.copyFromFloats(0,0,0)),e){const e=new Ln("default camera",-Math.PI/2,Math.PI/2,a,s,this);e.lowerRadiusLimit=.01*a,e.wheelPrecision=100/a,r=e}else{const e=new Fn("default camera",new o.P(s.x,s.y,-a),this);e.setTarget(s),r=e}r.minZ=.01*a,r.maxZ=1e3*a,r.speed=.2*a,this.activeCamera=r,i&&r.attachControl()}},N.x.prototype.createDefaultCameraOrLight=function(e=!1,t=!1,i=!1){this.createDefaultLight(t),this.createDefaultCamera(e,t,i)},N.x.prototype.createDefaultSkybox=function(e,t=!1,i=1e3,n=0,s=!0){if(!e)return p.Y.Warn("Can not create default skybox without environment texture."),null;s&&e&&(this.environmentTexture=e);const r=_l("hdrSkyBox",{size:i},this);if(t){const t=new O_("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=Le.SKYBOX_MODE),t.microSurface=1-n,t.disableLighting=!0,t.twoSidedLighting=!0,r.material=t}else{const t=new _a("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=Le.SKYBOX_MODE),t.disableLighting=!0,r.material=t}return r.isPickable=!1,r.infiniteDistance=!0,r.ignoreCameraMaxZ=!0,r},N.x.prototype.createDefaultEnvironment=function(e){return Up?new Up(e,this):null},N.x.prototype.createDefaultVRExperience=function(e={}){return new ja(this,e)},N.x.prototype.createDefaultXRExperienceAsync=function(e={}){return vm.CreateAsync(this,e).then((e=>e))};class Sm extends Le{get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new r.y$),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(null==e?void 0:e.message):p.Y.Error(null==e?void 0:e.message)}_handlePlay(){this._errorFound=!1,this.video.play().catch((e=>{if("NotAllowedError"===(null==e?void 0:e.name)){if(this._onUserActionRequestedObservable&&this._onUserActionRequestedObservable.hasObservers())return void this._onUserActionRequestedObservable.notifyObservers(this);if(!this.video.muted)return p.Y.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"),this.video.muted=!0,this._errorFound=!1,void this.video.play().catch((e=>{this._processError(e)}))}this._processError(e)}))}constructor(e,t,i,n=!1,s=!1,r=Le.TRILINEAR_SAMPLINGMODE,o={},a,l=5){var h,c;super(null,i,!n,s),this._onUserActionRequestedObservable=null,this._stillImageCaptured=!1,this._displayingPosterTexture=!1,this._frameId=-1,this._currentSrc=null,this._errorFound=!1,this._resizeInternalTexture=()=>{var e;null!=this._texture&&this._texture.dispose(),!this._getEngine().needPOTTextures||se.w1.IsExponentOfTwo(this.video.videoWidth)&&se.w1.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=Le.WRAP_ADDRESSMODE,this.wrapV=Le.WRAP_ADDRESSMODE):(this.wrapU=Le.CLAMP_ADDRESSMODE,this.wrapV=Le.CLAMP_ADDRESSMODE,this._generateMipMaps=!1),this._texture=this._getEngine().createDynamicTexture(this.video.videoWidth,this.video.videoHeight,this._generateMipMaps,this.samplingMode),this._texture.format=null!==(e=this._format)&&void 0!==e?e:5,this._frameId=-1,this._updateInternalTexture()},this._createInternalTexture=()=>{if(null!=this._texture){if(!this._displayingPosterTexture)return;this._displayingPosterTexture=!1}if(this.video.addEventListener("resize",this._resizeInternalTexture),this._resizeInternalTexture(),this.video.autoplay||this._settings.poster||this._settings.independentVideoSource)this._updateInternalTexture(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this);else{const e=this.video.onplaying,t=this.video.muted;this.video.muted=!0,this.video.onplaying=()=>{this.video.muted=t,this.video.onplaying=e,this._updateInternalTexture(),this._errorFound||this.video.pause(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this)},this._handlePlay()}},this._reset=()=>{null!=this._texture&&(this._displayingPosterTexture||(this._texture.dispose(),this._texture=null))},this._updateInternalTexture=()=>{if(null==this._texture)return;if(this.video.readyState=this.video.HAVE_CURRENT_DATA;!this._settings.poster||this._settings.autoPlay&&d?d&&this._createInternalTexture():(this._texture=this._getEngine().createTexture(this._settings.poster,!1,!this.invertY,i),this._displayingPosterTexture=!0)}getClassName(){return"VideoTexture"}_getName(e){return e instanceof HTMLVideoElement?e.currentSrc:"object"==typeof e?e.toString():e}_getVideo(e){if(e.isNative)return e;if(e instanceof HTMLVideoElement)return se.w1.SetCorsBehavior(e.currentSrc,e),e;const t=document.createElement("video");return"string"==typeof e?(se.w1.SetCorsBehavior(e,t),t.src=e):(se.w1.SetCorsBehavior(e[0],t),e.forEach((e=>{const i=document.createElement("source");i.src=e,t.appendChild(i)}))),this.onDisposeObservable.addOnce((()=>{Tm(t)})),t}_rebuild(){this.update()}update(){this.autoUpdateTexture&&this.updateTexture(!0)}updateTexture(e){e&&(this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture()))}updateURL(e){this.video.src=e,this._currentSrc=e}clone(){return new Sm(this.name,this._currentSrc,this.getScene(),this._generateMipMaps,this.invertY,this.samplingMode,this._settings)}dispose(){var e;super.dispose(),this._currentSrc=null,this._onUserActionRequestedObservable&&(this._onUserActionRequestedObservable.clear(),this._onUserActionRequestedObservable=null),this.video.removeEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this._settings.independentVideoSource||(this.video.removeEventListener("paused",this._updateInternalTexture),this.video.removeEventListener("seeked",this._updateInternalTexture),this.video.removeEventListener("emptied",this._reset),this.video.removeEventListener("resize",this._resizeInternalTexture),this.video.pause()),null===(e=this._externalTexture)||void 0===e||e.dispose()}static CreateFromStreamAsync(e,t,i,n=!0){const s=e.getEngine().createVideoElement(i);return e.getEngine()._badOS&&(document.body.appendChild(s),s.style.transform="scale(0.0001, 0.0001)",s.style.opacity="0",s.style.position="fixed",s.style.bottom="0px",s.style.right="0px"),s.setAttribute("autoplay",""),s.setAttribute("muted","true"),s.setAttribute("playsinline",""),s.muted=!0,s.isNative||(void 0!==s.mozSrcObject?s.mozSrcObject=t:"object"==typeof s.srcObject?s.srcObject=t:s.src=window.URL&&window.URL.createObjectURL(t)),new Promise((t=>{const i=()=>{const r=new Sm("video",s,e,!0,n,void 0,void 0,void 0,4);e.getEngine()._badOS&&r.onDisposeObservable.addOnce((()=>{s.remove()})),r.onDisposeObservable.addOnce((()=>{Tm(s)})),t(r),s.removeEventListener("playing",i)};s.addEventListener("playing",i),s.play()}))}static async CreateFromWebCamAsync(e,t,i=!1,n=!0){if(navigator.mediaDevices){const s=await navigator.mediaDevices.getUserMedia({video:t,audio:i}),r=await this.CreateFromStreamAsync(e,s,t,n);return r.onDisposeObservable.addOnce((()=>{s.getTracks().forEach((e=>{e.stop()}))})),r}return Promise.reject("No support for userMedia on this device")}static CreateFromWebCam(e,t,i,n=!1,s=!0){this.CreateFromWebCamAsync(e,i,n,s).then((function(e){t&&t(e)})).catch((function(e){p.Y.Error(e.name)}))}}class Em extends Vp{get videoTexture(){return this._texture}get videoMode(){return this.textureMode}set videoMode(e){this.textureMode=e}_initTexture(e,t,i){const n={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},s=new Sm((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,Le.TRILINEAR_SAMPLINGMODE,n);return i.clickToPlay&&(this._pointerObserver=t.onPointerObservable.add((e=>{var t;(null===(t=e.pickInfo)||void 0===t?void 0:t.pickedMesh)===this.mesh&&this._texture.video.play()}),We.kD.POINTERDOWN)),this._textureObserver=s.onLoadObservable.add((()=>{this.onLoadObservable.notifyObservers()})),s}dispose(e,t=!1){this._texture.onLoadObservable.remove(this._textureObserver),this._scene.onPointerObservable.remove(this._pointerObserver),super.dispose(e,t)}}Em.MODE_MONOSCOPIC=Vp.MODE_MONOSCOPIC,Em.MODE_TOPBOTTOM=Vp.MODE_TOPBOTTOM,Em.MODE_SIDEBYSIDE=Vp.MODE_SIDEBYSIDE;const xm="glowMapGenerationPixelShader",bm="#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)\n#include\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;\nuniform sampler2D opacitySampler;\nuniform float opacityIntensity;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef VERTEXALPHA\nvarying vec4 vColor;\n#endif\nuniform vec4 glowColor;\nuniform float glowIntensity;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\nvec4 finalColor=glowColor;\n#ifdef DIFFUSE\nvec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse);\n#ifdef DIFFUSE_ISLINEAR\nalbedoTexture=toGammaSpace(albedoTexture);\n#endif\n#ifdef GLOW\nfinalColor.a*=albedoTexture.a;\n#endif\n#ifdef HIGHLIGHT\nfinalColor.a=albedoTexture.a;\n#endif\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vUVOpacity);\n#ifdef OPACITYRGB\nfinalColor.a*=getLuminance(opacityMap.rgb);\n#else\nfinalColor.a*=opacityMap.a;\n#endif\nfinalColor.a*=opacityIntensity;\n#endif\n#ifdef VERTEXALPHA\nfinalColor.a*=vColor.a;\n#endif\n#ifdef ALPHATEST\nif (finalColor.a{if((i||0===t)&&e.subMeshes)for(let n=0;n{let s;this.onBeforeRenderMainTextureObservable.notifyObservers(this);const r=this._scene.getEngine();if(n.length){for(r.setColorWrite(!1),s=0;s{e.clear(this.neutralColor,!0,!0,!0)})),this._scene.getBoundingBoxRenderer){const e=this._scene.getBoundingBoxRenderer().enabled;this._mainTexture.onBeforeBindObservable.add((()=>{this._scene.getBoundingBoxRenderer().enabled=!this.disableBoundingBoxesFromEffectLayer&&e})),this._mainTexture.onAfterUnbindObservable.add((()=>{this._scene.getBoundingBoxRenderer().enabled=e}))}}_addCustomEffectDefines(e){}_isReady(e,t,i){var n;const s=this._scene.getEngine(),r=e.getMesh(),o=null===(n=r._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===n?void 0:n[s.currentRenderPassId];if(o)return o.isReadyForSubMesh(r,e,t);const a=e.getMaterial();if(!a)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return a.isReadyForSubMesh(e.getMesh(),e,t);const l=[],h=[ne.o.PositionKind];let c=!1,d=!1;if(a){const e=a.needAlphaTesting(),t=a.getAlphaTestTexture(),i=t&&t.hasAlpha&&(a.useAlphaFromDiffuseTexture||a._useAlphaFromAlbedoTexture);t&&(e||i)&&(l.push("#define DIFFUSE"),r.isVerticesDataPresent(ne.o.UV2Kind)&&1===t.coordinatesIndex?(l.push("#define DIFFUSEUV2"),d=!0):r.isVerticesDataPresent(ne.o.UVKind)&&(l.push("#define DIFFUSEUV1"),c=!0),e&&(l.push("#define ALPHATEST"),l.push("#define ALPHATESTVALUE 0.4")),t.gammaSpace||l.push("#define DIFFUSE_ISLINEAR"));const n=a.opacityTexture;n&&(l.push("#define OPACITY"),r.isVerticesDataPresent(ne.o.UV2Kind)&&1===n.coordinatesIndex?(l.push("#define OPACITYUV2"),d=!0):r.isVerticesDataPresent(ne.o.UVKind)&&(l.push("#define OPACITYUV1"),c=!0))}i&&(l.push("#define EMISSIVE"),r.isVerticesDataPresent(ne.o.UV2Kind)&&1===i.coordinatesIndex?(l.push("#define EMISSIVEUV2"),d=!0):r.isVerticesDataPresent(ne.o.UVKind)&&(l.push("#define EMISSIVEUV1"),c=!0),i.gammaSpace||l.push("#define EMISSIVE_ISLINEAR")),r.useVertexColors&&r.isVerticesDataPresent(ne.o.ColorKind)&&r.hasVertexAlpha&&a.transparencyMode!==ut.F.MATERIAL_OPAQUE&&(h.push(ne.o.ColorKind),l.push("#define VERTEXALPHA")),c&&(h.push(ne.o.UVKind),l.push("#define UV1")),d&&(h.push(ne.o.UV2Kind),l.push("#define UV2"));const u=new zt;if(r.useBones&&r.computeBonesUsingShaders){h.push(ne.o.MatricesIndicesKind),h.push(ne.o.MatricesWeightsKind),r.numBoneInfluencers>4&&(h.push(ne.o.MatricesIndicesExtraKind),h.push(ne.o.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers);const e=r.skeleton;e&&e.isUsingTextureForMatrices?l.push("#define BONETEXTURE"):l.push("#define BonesPerMesh "+(e?e.bones.length+1:0)),r.numBoneInfluencers>0&&u.addCPUSkinningFallback(0,r)}else l.push("#define NUM_BONE_INFLUENCERS 0");const p=r.morphTargetManager;let f=0;p&&p.numInfluencers>0&&(l.push("#define MORPHTARGETS"),f=p.numInfluencers,l.push("#define NUM_MORPH_INFLUENCERS "+f),p.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),It.G.PrepareAttributesForMorphTargetsInfluencers(h,r,f)),t&&(l.push("#define INSTANCES"),It.G.PushAttributesForInstances(h),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),(0,ua.lK)(a,this._scene,l),this._addCustomEffectDefines(l);const _=e._getDrawWrapper(void 0,!0),m=_.defines,g=l.join("\n");if(m!==g){const e=["world","mBones","viewProjection","glowColor","morphTargetInfluences","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];(0,ua.qx)(e),_.setEffect(this._engine.createEffect("glowMapGeneration",h,e,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],g,u,void 0,void 0,{maxSimultaneousMorphTargets:f}),g)}return _.effect.isReady()}render(){for(let r=0;ro.setMatrix("world",t)))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(r)}_useMeshMaterial(e){return!1}_rebuild(){const e=this._vertexBuffers[ne.o.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()}_disposeTextureAndPostProcesses(){this._mainTexture.dispose();for(let e=0;e-1&&this._scene.effectLayers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()}getClassName(){return"EffectLayer"}static Parse(e,t,i){return se.w1.Instantiate(e.customType).Parse(e,t,i)}}Am._SceneComponentInitialization=e=>{throw(0,ge.S)("EffectLayerSceneComponent")},(0,oe.gn)([(0,E.qC)()],Am.prototype,"name",void 0),(0,oe.gn)([(0,E.XX)()],Am.prototype,"neutralColor",void 0),(0,oe.gn)([(0,E.qC)()],Am.prototype,"isEnabled",void 0),(0,oe.gn)([(0,E.VE)()],Am.prototype,"camera",null),(0,oe.gn)([(0,E.qC)()],Am.prototype,"renderingGroupId",null),(0,oe.gn)([(0,E.qC)()],Am.prototype,"disableBoundingBoxesFromEffectLayer",void 0),n.p.AddParser(Se.l.NAME_EFFECTLAYER,((e,t,i,n)=>{if(e.effectLayers){i.effectLayers||(i.effectLayers=new Array);for(let s=0;s{this.scene.addEffectLayer(e)}))}removeFromContainer(e,t){e.effectLayers&&e.effectLayers.forEach((e=>{this.scene.removeEffectLayer(e),t&&e.dispose()}))}dispose(){const e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){const i=this._engine.currentRenderPassId,n=this.scene.effectLayers;for(const s of n){if(!s.hasMesh(e))continue;const n=s._mainTexture;this._engine.currentRenderPassId=n.renderPassId;for(const r of e.subMeshes)if(!s.isReady(r,t))return this._engine.currentRenderPassId=i,!1}return this._engine.currentRenderPassId=i,!0}_renderMainTexture(e){this._renderEffects=!1,this._needStencil=!1;let t=!1;const i=this.scene.effectLayers;if(i&&i.length>0){this._previousStencilState=this._engine.getStencilBuffer();for(const n of i)if(n.shouldRender()&&(!n.camera||n.camera.cameraRigMode===ce.V.RIG_MODE_NONE&&e===n.camera||n.camera.cameraRigMode!==ce.V.RIG_MODE_NONE&&n.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||n.needStencil();const e=n._mainTexture;e._shouldRender()&&(this.scene.incrementRenderId(),e.render(!1,!1),t=!0)}this.scene.incrementRenderId()}return t}_setStencil(){this._needStencil&&this._engine.setStencilBuffer(!0)}_setStencilBack(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)}_draw(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);const t=this.scene.effectLayers;for(let i=0;i{let t=e._getComponent(Se.l.NAME_EFFECTLAYER);t||(t=new Rm(e),e._addComponent(t))};const Pm="glowMapMergePixelShader",Im="varying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\nuniform float offset;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\n#if LDR\nbaseColor=clamp(baseColor,0.,1.0);\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ht.v.ShadersStore[Pm]=Im;const Mm="glowMapMergeVertexShader",Om="attribute vec2 position;\nvarying vec2 vUV;\nconst 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;\ngl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";Ht.v.ShadersStore[Mm]=Om;n.p.prototype.getGlowLayerByName=function(e){var t;for(let i=0;i<(null===(t=this.effectLayers)||void 0===t?void 0:t.length);i++)if(this.effectLayers[i].name===e&&this.effectLayers[i].getEffectName()===Dm.EffectName)return this.effectLayers[i];return null};class Dm extends Am{set blurKernelSize(e){if(e===this._options.blurKernelSize)return;this._options.blurKernelSize=e;const t=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1.kernel=t,this._verticalBlurPostprocess1.kernel=t,this._horizontalBlurPostprocess2.kernel=t,this._verticalBlurPostprocess2.kernel=t}get blurKernelSize(){return this._options.blurKernelSize}set intensity(e){this._intensity=e}get intensity(){return this._intensity}constructor(e,t,i){super(e,t),this._intensity=1,this._includedOnlyMeshes=[],this._excludedMeshes=[],this._meshesUsingTheirOwnMaterials=[],this.neutralColor=new a.HE(0,0,0,1),this._options=Object.assign({mainTextureRatio:Dm.DefaultTextureRatio,blurKernelSize:32,mainTextureFixedSize:void 0,camera:null,mainTextureSamples:1,renderingGroupId:-1,ldrMerge:!1,alphaBlendingMode:1,mainTextureType:0},i),this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType})}getEffectName(){return Dm.EffectName}_createMergeEffect(){let e="#define EMISSIVE \n";return this._options.ldrMerge&&(e+="#define LDR \n"),this._engine.createEffect("glowMapMerge",[ne.o.PositionKind],["offset"],["textureSampler","textureSampler2"],e)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width,t=this._mainTextureDesiredSize.height;e=this._engine.needPOTTextures?fe.D.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?fe.D.GetExponentOfTwo(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture1=new Ci("GlowLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture1.wrapU=Le.CLAMP_ADDRESSMODE,this._blurTexture1.wrapV=Le.CLAMP_ADDRESSMODE,this._blurTexture1.updateSamplingMode(Le.BILINEAR_SAMPLINGMODE),this._blurTexture1.renderParticles=!1,this._blurTexture1.ignoreCameraViewport=!0;const n=Math.floor(e/2),s=Math.floor(t/2);this._blurTexture2=new Ci("GlowLayerBlurRTT2",{width:n,height:s},this._scene,!1,!0,i),this._blurTexture2.wrapU=Le.CLAMP_ADDRESSMODE,this._blurTexture2.wrapV=Le.CLAMP_ADDRESSMODE,this._blurTexture2.updateSamplingMode(Le.BILINEAR_SAMPLINGMODE),this._blurTexture2.renderParticles=!1,this._blurTexture2.ignoreCameraViewport=!0,this._textures=[this._blurTexture1,this._blurTexture2];const r=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1=new bp("GlowLayerHBP1",new o.FM(1,0),r,{width:e,height:t},null,Le.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess1.width=e,this._horizontalBlurPostprocess1.height=t,this._horizontalBlurPostprocess1.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess1.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._verticalBlurPostprocess1=new bp("GlowLayerVBP1",new o.FM(0,1),r,{width:e,height:t},null,Le.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new bp("GlowLayerHBP2",new o.FM(1,0),r,{width:n,height:s},null,Le.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=n,this._horizontalBlurPostprocess2.height=s,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._blurTexture1)})),this._verticalBlurPostprocess2=new bp("GlowLayerVBP2",new o.FM(0,1),r,{width:n,height:s},null,Le.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1,this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._postProcesses1=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1],this._postProcesses2=[this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._mainTexture.samples=this._options.mainTextureSamples,this._mainTexture.onAfterUnbindObservable.add((()=>{const e=this._blurTexture1.renderTarget;if(e){this._scene.postProcessManager.directRender(this._postProcesses1,e,!0);const t=this._blurTexture2.renderTarget;t&&this._scene.postProcessManager.directRender(this._postProcesses2,t,!0),this._engine.unBindFramebuffer(null!=t?t:e,!0)}})),this._postProcesses.map((e=>{e.autoClear=!1}))}_getEffectiveBlurKernelSize(){return this._options.blurKernelSize/2}isReady(e,t){const i=e.getMaterial(),n=e.getRenderingMesh();if(!i||!n)return!1;const s=i.emissiveTexture;return super._isReady(e,t,s)}needStencil(){return!1}_canRenderMesh(e,t){return!0}_internalRender(e){e.setTexture("textureSampler",this._blurTexture1),e.setTexture("textureSampler2",this._blurTexture2),e.setFloat("offset",this._intensity);const t=this._engine,i=t.getStencilBuffer();t.setStencilBuffer(!1),t.drawElementsType(ut.F.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){var n;let s=1;if(this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(s=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector)this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color);else if(i.emissiveColor){s*=null!==(n=i.emissiveIntensity)&&void 0!==n?n:1,this._emissiveTextureAndColor.color.set(i.emissiveColor.r*s,i.emissiveColor.g*s,i.emissiveColor.b*s,i.alpha)}else this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a)}_shouldRenderMesh(e){return this.hasMesh(e)}_addCustomEffectDefines(e){e.push("#define GLOW")}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}addIncludedOnlyMesh(e){-1===this._includedOnlyMeshes.indexOf(e.uniqueId)&&this._includedOnlyMeshes.push(e.uniqueId)}removeIncludedOnlyMesh(e){const t=this._includedOnlyMeshes.indexOf(e.uniqueId);-1!==t&&this._includedOnlyMeshes.splice(t,1)}hasMesh(e){return!!super.hasMesh(e)&&(this._includedOnlyMeshes.length?-1!==this._includedOnlyMeshes.indexOf(e.uniqueId):!this._excludedMeshes.length||-1===this._excludedMeshes.indexOf(e.uniqueId))}_useMeshMaterial(e){return 0!=this._meshesUsingTheirOwnMaterials.length&&this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId)>-1}referenceMeshToUseItsOwnMaterial(e){e.resetDrawCache(this._mainTexture.renderPassId),this._meshesUsingTheirOwnMaterials.push(e.uniqueId),e.onDisposeObservable.add((()=>{this._disposeMesh(e)}))}unReferenceMeshFromUsingItsOwnMaterial(e){let t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);for(;t>=0;)this._meshesUsingTheirOwnMaterials.splice(t,1),t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);e.resetDrawCache(this._mainTexture.renderPassId)}_disposeMesh(e){this.removeIncludedOnlyMesh(e),this.removeExcludedMesh(e)}getClassName(){return"GlowLayer"}serialize(){const e=E.p4.Serialize(this);let t;if(e.customType="BABYLON.GlowLayer",e.includedMeshes=[],this._includedOnlyMeshes.length)for(t=0;tnew Dm(e.name,t,e.options)),e,t,i);let s;for(s=0;s{e.setFloat2("screenSize",this.width,this.height),e.setVector2("direction",this.direction),e.setFloat("blurWidth",this.kernel)}))}}class Lm extends Am{set blurHorizontalSize(e){this._horizontalBlurPostprocess.kernel=e,this._options.blurHorizontalSize=e}set blurVerticalSize(e){this._verticalBlurPostprocess.kernel=e,this._options.blurVerticalSize=e}get blurHorizontalSize(){return this._horizontalBlurPostprocess.kernel}get blurVerticalSize(){return this._verticalBlurPostprocess.kernel}constructor(e,t,i){super(e,t),this.name=e,this.innerGlow=!0,this.outerGlow=!0,this.onBeforeBlurObservable=new r.y$,this.onAfterBlurObservable=new r.y$,this._instanceGlowingMeshStencilReference=Lm.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=Lm.NeutralColor,this._engine.isStencilEnable||p.Y.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),this._options=Object.assign({mainTextureRatio:.5,blurTextureSizeRatio:.5,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0},i),this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType}),this._shouldRender=!1}getEffectName(){return Lm.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[ne.o.PositionKind],["offset"],["textureSampler"],this._options.isStroke?"#define STROKE \n":void 0)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,t=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;e=this._engine.needPOTTextures?fe.D.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?fe.D.GetExponentOfTwo(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture=new Ci("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=Le.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=Le.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(Le.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],2===this._options.alphaBlendingMode?(this._downSamplePostprocess=new Jn("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,Le.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._horizontalBlurPostprocess=new wm("HighlightLayerHBP",new o.FM(1,0),this._options.blurHorizontalSize,1,null,Le.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add((i=>{i.setFloat2("screenSize",e,t)})),this._verticalBlurPostprocess=new wm("HighlightLayerVBP",new o.FM(0,1),this._options.blurVerticalSize,1,null,Le.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add((i=>{i.setFloat2("screenSize",e,t)})),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new bp("HighlightLayerHBP",new o.FM(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,Le.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess.width=e,this._horizontalBlurPostprocess.height=t,this._horizontalBlurPostprocess.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess.onApplyObservable.add((e=>{e.setTexture("textureSampler",this._mainTexture)})),this._verticalBlurPostprocess=new bp("HighlightLayerVBP",new o.FM(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,Le.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add((()=>{this.onBeforeBlurObservable.notifyObservers(this);const e=this._blurTexture.renderTarget;e&&(this._scene.postProcessManager.directRender(this._postProcesses,e,!0),this._engine.unBindFramebuffer(e,!0)),this.onAfterBlurObservable.notifyObservers(this)})),this._postProcesses.map((e=>{e.autoClear=!1}))}needStencil(){return!0}isReady(e,t){const i=e.getMaterial(),n=e.getRenderingMesh();if(!i||!n||!this._meshes)return!1;let s=null;const r=this._meshes[n.uniqueId];return r&&r.glowEmissiveOnly&&i&&(s=i.emissiveTexture),super._isReady(e,t,s)}_internalRender(e,t){e.setTexture("textureSampler",this._blurTexture);const i=this._engine;i.cacheStencilState(),i.setStencilOperationPass(7681),i.setStencilOperationFail(7680),i.setStencilOperationDepthFail(7680),i.setStencilMask(0),i.setStencilBuffer(!0),i.setStencilFunctionReference(this._instanceGlowingMeshStencilReference),this.outerGlow&&0===t&&(e.setFloat("offset",0),i.setStencilFunction(517),i.drawElementsType(ut.F.TriangleFillMode,0,6)),this.innerGlow&&1===t&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(ut.F.TriangleFillMode,0,6)),i.restoreStencilState()}shouldRender(){return!!super.shouldRender()&&!!this._meshes}_shouldRenderMesh(e){return(!this._excludedMeshes||!this._excludedMeshes[e.uniqueId])&&!!super.hasMesh(e)}_canRenderMesh(e,t){return!0}_addCustomEffectDefines(e){e.push("#define HIGHLIGHT")}_setEmissiveTextureAndColor(e,t,i){const n=this._meshes[e.uniqueId];n?this._emissiveTextureAndColor.color.set(n.color.r,n.color.g,n.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),n&&n.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null}addExcludedMesh(e){if(!this._excludedMeshes)return;if(!this._excludedMeshes[e.uniqueId]){const t={mesh:e,beforeBind:null,afterRender:null,stencilState:!1};t.beforeBind=e.onBeforeBindObservable.add((e=>{t.stencilState=e.getEngine().getStencilBuffer(),e.getEngine().setStencilBuffer(!1)})),t.afterRender=e.onAfterRenderObservable.add((e=>{e.getEngine().setStencilBuffer(t.stencilState)})),this._excludedMeshes[e.uniqueId]=t}}removeExcludedMesh(e){if(!this._excludedMeshes)return;const t=this._excludedMeshes[e.uniqueId];t&&(t.beforeBind&&e.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&e.onAfterRenderObservable.remove(t.afterRender)),this._excludedMeshes[e.uniqueId]=null}hasMesh(e){return!!this._meshes&&(!!super.hasMesh(e)&&(void 0!==this._meshes[e.uniqueId]&&null!==this._meshes[e.uniqueId]))}addMesh(e,t,i=!1){if(!this._meshes)return;const n=this._meshes[e.uniqueId];n?n.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add((e=>{this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]?this._defaultStencilReference(e):e.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference))})),observerDefault:e.onAfterRenderObservable.add((e=>{this.isEnabled&&this._defaultStencilReference(e)})),glowEmissiveOnly:i},e.onDisposeObservable.add((()=>{this._disposeMesh(e)}))),this._shouldRender=!0}removeMesh(e){if(!this._meshes)return;const t=this._meshes[e.uniqueId];t&&(t.observerHighlight&&e.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&e.onAfterRenderObservable.remove(t.observerDefault),delete this._meshes[e.uniqueId]),this._shouldRender=!1;for(const i in this._meshes)if(this._meshes[i]){this._shouldRender=!0;break}}removeAllMeshes(){if(this._meshes)for(const e in this._meshes)if(Object.prototype.hasOwnProperty.call(this._meshes,e)){const t=this._meshes[e];t&&this.removeMesh(t.mesh)}}_defaultStencilReference(e){e.getScene().getEngine().setStencilFunctionReference(Lm.NormalMeshStencilReference)}_disposeMesh(e){this.removeMesh(e),this.removeExcludedMesh(e)}dispose(){if(this._meshes){for(const e in this._meshes){const t=this._meshes[e];t&&t.mesh&&(t.observerHighlight&&t.mesh.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&t.mesh.onAfterRenderObservable.remove(t.observerDefault))}this._meshes=null}if(this._excludedMeshes){for(const e in this._excludedMeshes){const t=this._excludedMeshes[e];t&&(t.beforeBind&&t.mesh.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&t.mesh.onAfterRenderObservable.remove(t.afterRender))}this._excludedMeshes=null}super.dispose()}getClassName(){return"HighlightLayer"}serialize(){const e=E.p4.Serialize(this);if(e.customType="BABYLON.HighlightLayer",e.meshes=[],this._meshes)for(const t in this._meshes){const i=this._meshes[t];i&&e.meshes.push({glowEmissiveOnly:i.glowEmissiveOnly,color:i.color.asArray(),meshId:i.mesh.id})}if(e.excludedMeshes=[],this._excludedMeshes)for(const t in this._excludedMeshes){const i=this._excludedMeshes[t];i&&e.excludedMeshes.push(i.mesh.id)}return e}static Parse(e,t,i){const n=E.p4.Parse((()=>new Lm(e.name,t,e.options)),e,t,i);let s;for(s=0;si.activeCamera&&e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&0!=(e.layerMask&i.activeCamera.layerMask);const n=i.getEngine(),s=[];s.push(1,1),s.push(-1,1),s.push(-1,-1),s.push(1,-1),this._vertexBuffers[ne.o.PositionKind]=new ne.o(n,s,ne.o.PositionKind,!1,!1,2),this._createIndexBuffer()}_createIndexBuffer(){const e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled=e}getScene(){return this._scene}getEmitter(){return this._emitter}setEmitter(e){this._emitter=e}getEmitterPosition(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position}computeEffectivePosition(e){let t=this.getEmitterPosition();t=o.P.Project(t,o.y3.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=o.P.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(e.x-=this.viewportBorder,e.y-=this.viewportBorder,e.width+=2*this.viewportBorder,e.height+=2*this.viewportBorder,t.x+=this.viewportBorder,t.y+=this.viewportBorder,this._positionX+=this.viewportBorder,this._positionY+=this.viewportBorder);const i=this._scene.useRightHandedSystem;return!!(t.z>0&&!i||t.z<0&&i)&&(this._positionX>e.x&&this._positionXe.y&&(this._positionY,e.y,e.height),!0)}_isVisible(){if(!this._isEnabled||!this._scene.activeCamera)return!1;const e=this.getEmitterPosition().subtract(this._scene.activeCamera.globalPosition),t=e.length();e.normalize();const i=new qe(this._scene.activeCamera.globalPosition,e),n=this._scene.pickWithRay(i,this.meshesSelectionPredicate,!0);return!n||!n.hit||n.distance>t}render(){if(!this._scene.activeCamera)return!1;const e=this._scene.getEngine(),t=this._scene.activeCamera.viewport.toGlobal(e.getRenderWidth(!0),e.getRenderHeight(!0));if(!this.computeEffectivePosition(t))return!1;if(!this._isVisible())return!1;let i,n;i=this._positionXt.x+t.width-this.borderLimit?this._positionX-t.x-t.width+this.borderLimit:0,n=this._positionYt.y+t.height-this.borderLimit?this._positionY-t.y-t.height+this.borderLimit:0;let s=i>n?i:n;s-=this.viewportBorder,s>this.borderLimit&&(s=this.borderLimit);let r=1-S.R.Clamp(s/this.borderLimit,0,1);if(r<0)return!1;r>1&&(r=1),this.viewportBorder>0&&(t.x+=this.viewportBorder,t.y+=this.viewportBorder,t.width-=2*this.viewportBorder,t.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);const a=t.x+t.width/2,l=t.y+t.height/2,h=a-this._positionX,c=l-this._positionY;e.setState(!1),e.setDepthBuffer(!1);for(let d=0;d{throw(0,ge.S)("LensFlareSystemSceneComponent")},n.p.AddParser(Se.l.NAME_LENSFLARESYSTEM,((e,t,i,n)=>{if(void 0!==e.lensFlareSystems&&null!==e.lensFlareSystems){i.lensFlareSystems||(i.lensFlareSystems=new Array);for(let s=0,r=e.lensFlareSystems.length;s{this.scene.addLensFlareSystem(e)}))}removeFromContainer(e,t){e.lensFlareSystems&&e.lensFlareSystems.forEach((e=>{this.scene.removeLensFlareSystem(e),t&&e.dispose()}))}serialize(e){e.lensFlareSystems=[];const t=this.scene.lensFlareSystems;for(const i of t)e.lensFlareSystems.push(i.serialize())}dispose(){const e=this.scene.lensFlareSystems;for(;e.length;)e[0].dispose()}_draw(e){if(this.scene.lensFlaresEnabled){const t=this.scene.lensFlareSystems;se.w1.StartPerformanceCounter("Lens flares",t.length>0);for(const i of t)0!=(e.layerMask&i.layerMask)&&i.render();se.w1.EndPerformanceCounter("Lens flares",t.length>0)}}}Ym._SceneComponentInitialization=e=>{let t=e._getComponent(Se.l.NAME_LENSFLARESYSTEM);t||(t=new jm(e),e._addComponent(t))};const Km="bayerDitherFunctions",qm="float bayerDither2(vec2 _P) {\nreturn mod(2.0*_P.y+_P.x+1.0,4.0);\n}\nfloat bayerDither4(vec2 _P) {\nvec2 P1=mod(_P,2.0); \nvec2 P2=floor(0.5*mod(_P,4.0)); \nreturn 4.0*bayerDither2(P1)+bayerDither2(P2);\n}\nfloat bayerDither8(vec2 _P) {\nvec2 P1=mod(_P,2.0); \nvec2 P2=floor(0.5 *mod(_P,4.0)); \nvec2 P4=floor(0.25*mod(_P,8.0)); \nreturn 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);\n}\n";Ht.v.IncludesShadersStore[Km]=qm;const $m="shadowMapFragmentExtraDeclaration",Qm="#if SM_FLOAT==0\n#include\n#endif\n#if SM_SOFTTRANSPARENTSHADOW==1\n#include\nuniform float softTransparentShadowSM;\n#endif\nvarying float vDepthMetricSM;\n#if SM_USEDISTANCE==1\nuniform vec3 lightDataSM;\nvarying vec3 vPositionWSM;\n#endif\nuniform vec3 biasAndScaleSM;\nuniform vec2 depthValuesSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\n#endif\n";Ht.v.IncludesShadersStore[$m]=Qm;const Zm="shadowMapFragment",Jm="float depthSM=vDepthMetricSM;\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\n#if SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\ndepthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\ndepthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_FragDepth=clamp(1.0-depthSM,0.0,1.0);\n#else\ngl_FragDepth=clamp(depthSM,0.0,1.0); \n#endif\n#elif SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#if SM_ESM==1\ndepthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.);\n#endif\n#if SM_FLOAT==1\ngl_FragColor=vec4(depthSM,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depthSM);\n#endif\nreturn;";Ht.v.IncludesShadersStore[Zm]=Jm;const eg="shadowMapPixelShader",tg="#include\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\n#ifdef ALPHATEXTURE\nfloat alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a;\n#ifdef ALPHATESTVALUE\nif (alphaFromAlphaTexture=softTransparentShadowSM*alphaFromAlphaTexture) discard;\n#else\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM) discard;\n#endif\n#endif\n#include\n}";Ht.v.ShadersStore[eg]=tg;const ig="sceneVertexDeclaration",ng="uniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec4 vEyePosition;\n";Ht.v.IncludesShadersStore[ig]=ng;const sg="meshVertexDeclaration",rg="uniform mat4 world;\nuniform float visibility;\n";Ht.v.IncludesShadersStore[sg]=rg;const og="shadowMapVertexDeclaration",ag="#include\n#include\n";Ht.v.IncludesShadersStore[og]=ag;const lg="shadowMapUboDeclaration",hg="layout(std140,column_major) uniform;\n#include\n#include\n";Ht.v.IncludesShadersStore[lg]=hg;const cg="shadowMapVertexExtraDeclaration",dg="#if SM_NORMALBIAS==1\nuniform vec3 lightDataSM;\n#endif\nuniform vec3 biasAndScaleSM;\nuniform vec2 depthValuesSM;\nvarying float vDepthMetricSM;\n#if SM_USEDISTANCE==1\nvarying vec3 vPositionWSM;\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\n#endif\n";Ht.v.IncludesShadersStore[cg]=dg;const ug="shadowMapVertexNormalBias",pg="#if SM_NORMALBIAS==1\n#if SM_DIRECTIONINLIGHTDATA==1\nvec3 worldLightDirSM=normalize(-lightDataSM.xyz);\n#else\nvec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;\nvec3 worldLightDirSM=normalize(directionToLightSM);\n#endif\nfloat ndlSM=dot(vNormalW,worldLightDirSM);\nfloat sinNLSM=sqrt(1.0-ndlSM*ndlSM);\nfloat normalBiasSM=biasAndScaleSM.y*sinNLSM;\nworldPos.xyz-=vNormalW*normalBiasSM;\n#endif\n";Ht.v.IncludesShadersStore[ug]=pg;const fg="shadowMapVertexMetric",_g="#if SM_USEDISTANCE==1\nvPositionWSM=worldPos.xyz;\n#endif\n#if SM_DEPTHTEXTURE==1\n#ifdef IS_NDC_HALF_ZRANGE\n#define BIASFACTOR 0.5\n#else\n#define BIASFACTOR 1.0\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\n#else\ngl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\n#endif\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nzSM=gl_Position.z;\ngl_Position.z=0.0;\n#elif SM_USEDISTANCE==0\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#else\nvDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\n#endif\n#endif\n";Ht.v.IncludesShadersStore[fg]=_g;const mg="shadowMapVertexShader",gg="attribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#endif\n#include\n#include<__decl__shadowMapVertex>\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#ifdef NORMAL\nmat3 normWorldSM=mat3(finalWorld);\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));\nvNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvec3 vNormalW=normalize(normWorldSM*normalUpdated);\n#endif\n#endif\n#include\ngl_Position=viewProjection*worldPos;\n#include\n#ifdef ALPHATEXTURE\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n}";Ht.v.ShadersStore[mg]=gg;const vg="depthBoxBlurPixelShader",Tg="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}";Ht.v.ShadersStore[vg]=Tg;const Sg="shadowMapFragmentSoftTransparentShadow",Eg="#if SM_SOFTTRANSPARENTSHADOW==1\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard;\n#endif\n";Ht.v.IncludesShadersStore[Sg]=Eg;class xg{get bias(){return this._bias}set bias(e){this._bias=e}get normalBias(){return this._normalBias}set normalBias(e){this._normalBias=e}get blurBoxOffset(){return this._blurBoxOffset}set blurBoxOffset(e){this._blurBoxOffset!==e&&(this._blurBoxOffset=e,this._disposeBlurPostProcesses())}get blurScale(){return this._blurScale}set blurScale(e){this._blurScale!==e&&(this._blurScale=e,this._disposeBlurPostProcesses())}get blurKernel(){return this._blurKernel}set blurKernel(e){this._blurKernel!==e&&(this._blurKernel=e,this._disposeBlurPostProcesses())}get useKernelBlur(){return this._useKernelBlur}set useKernelBlur(e){this._useKernelBlur!==e&&(this._useKernelBlur=e,this._disposeBlurPostProcesses())}get depthScale(){return void 0!==this._depthScale?this._depthScale:this._light.getDepthScale()}set depthScale(e){this._depthScale=e}_validateFilter(e){return e}get filter(){return this._filter}set filter(e){if(e=this._validateFilter(e),this._light.needCube()){if(e===xg.FILTER_BLUREXPONENTIALSHADOWMAP)return void(this.useExponentialShadowMap=!0);if(e===xg.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)return void(this.useCloseExponentialShadowMap=!0);if(e===xg.FILTER_PCF||e===xg.FILTER_PCSS)return void(this.usePoissonSampling=!0)}e!==xg.FILTER_PCF&&e!==xg.FILTER_PCSS||this._scene.getEngine()._features.supportShadowSamplers?this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty()):this.usePoissonSampling=!0}get usePoissonSampling(){return this.filter===xg.FILTER_POISSONSAMPLING}set usePoissonSampling(e){const t=this._validateFilter(xg.FILTER_POISSONSAMPLING);(e||this.filter===xg.FILTER_POISSONSAMPLING)&&(this.filter=e?t:xg.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===xg.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){const t=this._validateFilter(xg.FILTER_EXPONENTIALSHADOWMAP);(e||this.filter===xg.FILTER_EXPONENTIALSHADOWMAP)&&(this.filter=e?t:xg.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===xg.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){const t=this._validateFilter(xg.FILTER_BLUREXPONENTIALSHADOWMAP);(e||this.filter===xg.FILTER_BLUREXPONENTIALSHADOWMAP)&&(this.filter=e?t:xg.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===xg.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){const t=this._validateFilter(xg.FILTER_CLOSEEXPONENTIALSHADOWMAP);(e||this.filter===xg.FILTER_CLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:xg.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===xg.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){const t=this._validateFilter(xg.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);(e||this.filter===xg.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:xg.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===xg.FILTER_PCF}set usePercentageCloserFiltering(e){const t=this._validateFilter(xg.FILTER_PCF);(e||this.filter===xg.FILTER_PCF)&&(this.filter=e?t:xg.FILTER_NONE)}get filteringQuality(){return this._filteringQuality}set filteringQuality(e){this._filteringQuality!==e&&(this._filteringQuality=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get useContactHardeningShadow(){return this.filter===xg.FILTER_PCSS}set useContactHardeningShadow(e){const t=this._validateFilter(xg.FILTER_PCSS);(e||this.filter===xg.FILTER_PCSS)&&(this.filter=e?t:xg.FILTER_NONE)}get contactHardeningLightSizeUVRatio(){return this._contactHardeningLightSizeUVRatio}set contactHardeningLightSizeUVRatio(e){this._contactHardeningLightSizeUVRatio=e}get darkness(){return this._darkness}set darkness(e){this.setDarkness(e)}getDarkness(){return this._darkness}setDarkness(e){return this._darkness=e>=1?1:e<=0?0:e,this}get transparencyShadow(){return this._transparencyShadow}set transparencyShadow(e){this.setTransparencyShadow(e)}setTransparencyShadow(e){return this._transparencyShadow=e,this}getShadowMap(){return this._shadowMap}getShadowMapForRendering(){return this._shadowMap2?this._shadowMap2:this._shadowMap}getClassName(){return xg.CLASSNAME}addShadowCaster(e,t=!0){if(!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),-1===this._shadowMap.renderList.indexOf(e)&&this._shadowMap.renderList.push(e),t)for(const i of e.getChildMeshes())-1===this._shadowMap.renderList.indexOf(i)&&this._shadowMap.renderList.push(i);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;const i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(const n of e.getChildren())this.removeShadowCaster(n);return this}getLight(){return this._light}_getCamera(){var e;return null!==(e=this._camera)&&void 0!==e?e:this._scene.activeCamera}get mapSize(){return this._mapSize}set mapSize(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}constructor(e,t,i,n){this.onBeforeShadowMapRenderObservable=new r.y$,this.onAfterShadowMapRenderObservable=new r.y$,this.onBeforeShadowMapRenderMeshObservable=new r.y$,this.onAfterShadowMapRenderMeshObservable=new r.y$,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=xg.FILTER_NONE,this._filteringQuality=xg.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.useOpacityTextureForTransparentShadow=!1,this.frustumEdgeFalloff=0,this.forceBackFacesOnly=!1,this._lightDirection=o.P.Zero(),this._viewMatrix=o.y3.Zero(),this._projectionMatrix=o.y3.Zero(),this._transformMatrix=o.y3.Zero(),this._cachedPosition=new o.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new o.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=o.y3.Identity(),this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=null!=n?n:null;let s=t._shadowGenerators;s||(s=t._shadowGenerators=new Map),s.set(this._camera,this),this.id=t.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[],this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`))),xg._SceneComponentInitialization(this._scene);const a=this._scene.getEngine().getCaps();i?a.textureFloatRender&&a.textureFloatLinearFiltering?this._textureType=1:a.textureHalfFloatRender&&a.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:a.textureHalfFloatRender&&a.textureHalfFloatLinearFiltering?this._textureType=2:a.textureFloatRender&&a.textureFloatLinearFiltering?this._textureType=1:this._textureType=0,this._initializeGenerator(),this._applyFilterValues()}_initializeGenerator(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()}_createTargetRenderTexture(){const e=this._scene.getEngine();e._features.supportDepthStencilTexture?(this._shadowMap=new Ci(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0)):this._shadowMap=new Ci(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(this._createTargetRenderTexture(),null===this._shadowMap)return;this._shadowMap.wrapU=Le.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=Le.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(Le.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=this._renderForShadowMap.bind(this),this._shadowMap.customIsReadyFunction=()=>!0;const e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add((()=>{var t;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),null===(t=e._debugPushGroup)||void 0===t||t.call(e,`shadow map generation for pass id ${e.currentRenderPassId}`,1)})),this._shadowMap.onBeforeRenderObservable.add((t=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=t,this._filter===xg.FILTER_PCF&&e.setColorWrite(!1),this.getTransformMatrix(),this._scene.setTransformMatrix(this._viewMatrix,this._projectionMatrix),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._shadowMap.onAfterUnbindObservable.add((()=>{var t,i;if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._scene.updateTransformMatrix(),this._filter===xg.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap)return void(null===(t=e._debugPopGroup)||void 0===t||t.call(e,1));const n=this.getShadowMapForRendering();n&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,n.renderTarget,!0),e.unBindFramebuffer(n.renderTarget,!0),null===(i=e._debugPopGroup)||void 0===i||i.call(e,1))}));const t=new a.HE(0,0,0,0),i=new a.HE(1,1,1,1);this._shadowMap.onClearObservable.add((e=>{this._filter===xg.FILTER_PCF?e.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e.clear(t,!0,!0,!1):e.clear(i,!0,!0,!1)})),this._shadowMap.onResizeObservable.add((e=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=e.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}));for(let n=mi.$.MIN_RENDERINGGROUPS;n{e.setTexture("textureSampler",this._shadowMap)})),this._kernelBlurYPostprocess=new bp(this._light.name+"KernelBlurY",new o.FM(0,1),this.blurKernel,1,null,Le.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,0===this._textureType&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new Zt(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,Le.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add((e=>{e.setFloat2("screenSize",t,t),e.setTexture("textureSampler",this._shadowMap)})),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])}_renderForShadowMap(e,t,i,n){let s;if(n.length)for(s=0;s{r===s||e?(r.getMeshUniformBuffer().bindToEffect(c,"Mesh"),r.transferToEffect(e?t:f)):(s.getMeshUniformBuffer().bindToEffect(c,"Mesh"),s.transferToEffect(t))})),this.forceBackFacesOnly&&a.setState(!0,0,!1,!1,l.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(c),this.onAfterShadowMapRenderMeshObservable.notifyObservers(s)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}_applyFilterValues(){this._shadowMap&&(this.filter===xg.FILTER_NONE||this.filter===xg.FILTER_PCSS?this._shadowMap.updateSamplingMode(Le.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(Le.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){const i=Object.assign({useInstances:!1},t),n=this.getShadowMap();if(!n)return void(e&&e(this));const s=n.renderList;if(!s)return void(e&&e(this));const r=new Array;for(const l of s)r.push(...l.subMeshes);if(0===r.length)return void(e&&e(this));let o=0;const a=()=>{var t,n;if(this._scene&&this._scene.getEngine()){for(;this.isReady(r[o],i.useInstances,null!==(n=null===(t=r[o].getMaterial())||void 0===t?void 0:t.needAlphaBlendingForMesh(r[o].getMesh()))&&void 0!==n&&n);)if(o++,o>=r.length)return void(e&&e(this));setTimeout(a,16)}};a()}forceCompilationAsync(e){return new Promise((t=>{this.forceCompilation((()=>{t()}),e)}))}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,n){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(0!==this._textureType?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));const s=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&s.isVerticesDataPresent(ne.o.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===he.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&n?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){var n;const s=e.getMaterial(),r=null==s?void 0:s.shadowDepthWrapper;if(this._opacityTexture=null,!s)return!1;const o=[];if(this._prepareShadowDefines(e,t,o,i),r){if(!r.isReadyForSubMesh(e,o,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{const i=e._getDrawWrapper(void 0,!0);let r=i.effect,a=i.defines;const l=[ne.o.PositionKind],h=e.getMesh();this.normalBias&&h.isVerticesDataPresent(ne.o.NormalKind)&&(l.push(ne.o.NormalKind),o.push("#define NORMAL"),h.nonUniformScaling&&o.push("#define NONUNIFORMSCALING"));const c=s.needAlphaTesting();if((c||s.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=s.opacityTexture:this._opacityTexture=s.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;const e=null!==(n=s.alphaCutOff)&&void 0!==n?n:xg.DEFAULT_ALPHA_CUTOFF;o.push("#define ALPHATEXTURE"),c&&o.push(`#define ALPHATESTVALUE ${e}${e%1==0?".":""}`),h.isVerticesDataPresent(ne.o.UVKind)&&(l.push(ne.o.UVKind),o.push("#define UV1")),h.isVerticesDataPresent(ne.o.UV2Kind)&&1===this._opacityTexture.coordinatesIndex&&(l.push(ne.o.UV2Kind),o.push("#define UV2"))}const d=new zt;if(h.useBones&&h.computeBonesUsingShaders&&h.skeleton){l.push(ne.o.MatricesIndicesKind),l.push(ne.o.MatricesWeightsKind),h.numBoneInfluencers>4&&(l.push(ne.o.MatricesIndicesExtraKind),l.push(ne.o.MatricesWeightsExtraKind));const e=h.skeleton;o.push("#define NUM_BONE_INFLUENCERS "+h.numBoneInfluencers),h.numBoneInfluencers>0&&d.addCPUSkinningFallback(0,h),e.isUsingTextureForMatrices?o.push("#define BONETEXTURE"):o.push("#define BonesPerMesh "+(e.bones.length+1))}else o.push("#define NUM_BONE_INFLUENCERS 0");const u=h.morphTargetManager;let p=0;if(u&&u.numInfluencers>0&&(o.push("#define MORPHTARGETS"),p=u.numInfluencers,o.push("#define NUM_MORPH_INFLUENCERS "+p),u.isUsingTextureForTargets&&o.push("#define MORPHTARGETS_TEXTURE"),It.G.PrepareAttributesForMorphTargetsInfluencers(l,h,p)),(0,ua.lK)(s,this._scene,o),t&&(o.push("#define INSTANCES"),It.G.PushAttributesForInstances(l),e.getRenderingMesh().hasThinInstances&&o.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(const e of this.customShaderOptions.defines)-1===o.indexOf(e)&&o.push(e);const f=o.join("\n");if(a!==f){a=f;let e="shadowMap";const t=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices"],n=["diffuseSampler","boneSampler","morphTargets"],s=["Scene","Mesh"];if((0,ua.qx)(t),this.customShaderOptions){if(e=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(const e of this.customShaderOptions.attributes)-1===l.indexOf(e)&&l.push(e);if(this.customShaderOptions.uniforms)for(const e of this.customShaderOptions.uniforms)-1===t.indexOf(e)&&t.push(e);if(this.customShaderOptions.samplers)for(const e of this.customShaderOptions.samplers)-1===n.indexOf(e)&&n.push(e)}const o=this._scene.getEngine();r=o.createEffect(e,{attributes:l,uniformsNames:t,uniformBuffersNames:s,samplers:n,defines:f,fallbacks:d,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:p}},o),i.setEffect(r,a)}if(!r.isReady())return!1}return(this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(this._blurPostProcesses&&this._blurPostProcesses.length||this._initializeBlurRTTAndPostProcesses()),!(this._kernelBlurXPostprocess&&!this._kernelBlurXPostprocess.isReady())&&(!(this._kernelBlurYPostprocess&&!this._kernelBlurYPostprocess.isReady())&&!(this._boxBlurPostprocess&&!this._boxBlurPostprocess.isReady()))}prepareDefines(e,t){const i=this._scene,n=this._light;i.shadowsEnabled&&n.shadowEnabled&&(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===xg.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===xg.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===xg.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===xg.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),n.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const n=this._getCamera();if(!n)return;const s=this.getShadowMap();s&&(i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix()),this._filter===xg.FILTER_PCF?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),s.getSize().width,1/s.getSize().width,this.frustumEdgeFalloff,e)):this._filter===xg.FILTER_PCSS?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),t.setTexture("depthSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/s.getSize().width,this._contactHardeningLightSizeUVRatio*s.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/s.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(n),this.getLight().getDepthMinZ(n)+this.getLight().getDepthMaxZ(n),e))}getTransformMatrix(){const e=this._scene;if(this._currentRenderId===e.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderId=e.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;let t=this._light.position;if(this._light.computeTransformedInformation()&&(t=this._light.transformedPosition),o.P.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(o.P.Dot(this._lightDirection,o.P.Up()))&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!t.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(t),this._cachedDirection.copyFrom(this._lightDirection),o.y3.LookAtLHToRef(t,t.add(this._lightDirection),o.P.Up(),this._viewMatrix);const e=this.getShadowMap();if(e){const t=e.renderList;t&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,t)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix}recreateShadowMap(){const e=this._shadowMap;if(!e)return;const t=e.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this._filter,this._applyFilterValues(),t){this._shadowMap.renderList||(this._shadowMap.renderList=[]);for(const e of t)this._shadowMap.renderList.push(e)}else this._shadowMap.renderList=null}_disposeBlurPostProcesses(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]}_disposeRTTandPostProcesses(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()}_disposeSceneUBOs(){if(this._sceneUBOs){for(const e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}dispose(){if(this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light){if(this._light._shadowGenerators){const e=this._light._shadowGenerators.entries();for(let t=e.next();!0!==t.done;t=e.next()){const[e,i]=t.value;i===this&&this._light._shadowGenerators.delete(e)}0===this._light._shadowGenerators.size&&(this._light._shadowGenerators=null)}this._light._markMeshesAsLightDirty()}this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear()}serialize(){var e;const t={},i=this.getShadowMap();if(!i)return t;if(t.className=this.getClassName(),t.lightId=this._light.id,t.cameraId=null===(e=this._camera)||void 0===e?void 0:e.id,t.id=this.id,t.mapSize=i.getRenderSize(),t.forceBackFacesOnly=this.forceBackFacesOnly,t.darkness=this.getDarkness(),t.transparencyShadow=this._transparencyShadow,t.frustumEdgeFalloff=this.frustumEdgeFalloff,t.bias=this.bias,t.normalBias=this.normalBias,t.usePercentageCloserFiltering=this.usePercentageCloserFiltering,t.useContactHardeningShadow=this.useContactHardeningShadow,t.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,t.filteringQuality=this.filteringQuality,t.useExponentialShadowMap=this.useExponentialShadowMap,t.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,t.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,t.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,t.usePoissonSampling=this.usePoissonSampling,t.depthScale=this.depthScale,t.blurBoxOffset=this.blurBoxOffset,t.blurKernel=this.blurKernel,t.blurScale=this.blurScale,t.useKernelBlur=this.useKernelBlur,t.renderList=[],i.renderList)for(let n=0;n{throw(0,ge.S)("ShadowGeneratorSceneComponent")};const bg="depthPixelShader",Cg="#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include\nvarying float vDepthMetric;\n#ifdef PACKED\n#include\n#endif\n#ifdef STORE_CAMERASPACE_Z\nvarying vec4 vViewPos;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef STORE_CAMERASPACE_Z\n#ifdef PACKED\ngl_FragColor=pack(vViewPos.z);\n#else\ngl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0);\n#endif\n#else\n#ifdef NONLINEARDEPTH\n#ifdef PACKED\ngl_FragColor=pack(gl_FragCoord.z);\n#else\ngl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0);\n#endif\n#else\n#ifdef PACKED\ngl_FragColor=pack(vDepthMetric);\n#else\ngl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0);\n#endif\n#endif\n#endif\n}";Ht.v.ShadersStore[bg]=Cg;const yg="depthVertexShader",Ag="attribute vec3 position;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef STORE_CAMERASPACE_Z\nuniform mat4 view;\nvarying vec4 vViewPos;\n#endif\nvarying float vDepthMetric;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n#include\ngl_Position=viewProjection*worldPos;\n#ifdef STORE_CAMERASPACE_Z\nvViewPos=view*worldPos;\n#else\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y));\n#else\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#endif\n#endif\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n";Ht.v.ShadersStore[yg]=Ag;class Rg{setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,n=!1,s=Le.TRILINEAR_SAMPLINGMODE,r=!1,o){this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._scene=e,this._storeNonLinearDepth=n,this._storeCameraSpaceZ=r,this.isPacked=0===t,this.isPacked?this.clearColor=new a.HE(1,1,1,1):this.clearColor=new a.HE(r?1e8:1,0,0,1),Rg._SceneComponentInitialization(this._scene);const l=e.getEngine();this._camera=i,s!==Le.NEAREST_SAMPLINGMODE&&(1!==t||l._caps.textureFloatLinearFiltering||(s=Le.NEAREST_SAMPLINGMODE),2!==t||l._caps.textureHalfFloatLinearFiltering||(s=Le.NEAREST_SAMPLINGMODE));const h=this.isPacked||!l._features.supportExtendedTextureFormats?5:6;this._depthMap=new Ci(null!=o?o:"DepthRenderer",{width:l.getRenderWidth(),height:l.getRenderHeight()},this._scene,!1,!0,t,!1,s,void 0,void 0,void 0,h),this._depthMap.wrapU=Le.CLAMP_ADDRESSMODE,this._depthMap.wrapV=Le.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.noPrePassRenderer=!0,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add((e=>{e.clear(this.clearColor,!0,!0,!0)})),this._depthMap.onBeforeBindObservable.add((()=>{var e;null===(e=l._debugPushGroup)||void 0===e||e.call(l,"depth renderer",1)})),this._depthMap.onAfterUnbindObservable.add((()=>{var e;null===(e=l._debugPopGroup)||void 0===e||e.call(l,1)})),this._depthMap.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let n=0;n{var t,i;const n=e.getRenderingMesh(),s=e.getEffectiveMesh(),r=this._scene,o=r.getEngine(),a=e.getMaterial();if(s._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!a||s.infiniteDistance||a.disableDepthWrite||0===e.verticesCount||e._renderId===r.getRenderId())return;const l=s._getWorldMatrixDeterminant()<0;let h=null!==(t=n.overrideMaterialSideOrientation)&&void 0!==t?t:a.sideOrientation;l&&(h=0===h?1:0);const c=0===h;o.setState(a.backFaceCulling,0,!1,c,this.reverseCulling?!a.cullBackFaces:a.cullBackFaces);const d=n._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(d.mustReturn)return;const u=o.getCaps().instancedArrays&&(null!==d.visibleInstances[e._id]&&void 0!==d.visibleInstances[e._id]||n.hasThinInstances),p=this._camera||r.activeCamera;if(this.isReady(e,u)&&p){e._renderId=r.getRenderId();const t=null===(i=s._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[o.currentRenderPassId];let l=e._getDrawWrapper();!l&&t&&(l=t._getDrawWrapper());const h=p.mode===ce.V.ORTHOGRAPHIC_CAMERA;if(!l)return;const c=l.effect;let f,_;if(o.enableEffect(l),u||n._bind(e,c,a.fillMode),t?t.bindForSubMesh(s.getWorldMatrix(),s,e):(c.setMatrix("viewProjection",r.getTransformMatrix()),c.setMatrix("world",s.getWorldMatrix()),this._storeCameraSpaceZ&&c.setMatrix("view",r.getViewMatrix())),h?(f=!o.useReverseDepthBuffer&&o.isNDCHalfZRange?0:1,_=o.useReverseDepthBuffer&&o.isNDCHalfZRange?0:1):(f=o.useReverseDepthBuffer&&o.isNDCHalfZRange?p.minZ:o.isNDCHalfZRange?0:p.minZ,_=o.useReverseDepthBuffer&&o.isNDCHalfZRange?0:p.maxZ),c.setFloat2("depthValues",f,f+_),!t){if(a.needAlphaTesting()){const e=a.getAlphaTestTexture();e&&(c.setTexture("diffuseSampler",e),c.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(n.useBones&&n.computeBonesUsingShaders&&n.skeleton){const e=n.skeleton;if(e.isUsingTextureForMatrices){const t=e.getTransformMatrixTexture(n);if(!t)return;c.setTexture("boneSampler",t),c.setFloat("boneTextureWidth",4*(e.bones.length+1))}else c.setMatrices("mBones",e.getTransformMatrices(n))}(0,ua.an)(c,a,r),It.G.BindMorphTargetParameters(n,c),n.morphTargetManager&&n.morphTargetManager.isUsingTextureForTargets&&n.morphTargetManager._bind(c)}n._processRendering(s,e,c,a.fillMode,d,u,((e,t)=>c.setMatrix("world",t)))}};this._depthMap.customRenderFunction=(e,t,i,n)=>{let s;if(n.length)for(s=0;s4&&(h.push(ne.o.MatricesIndicesExtraKind),h.push(ne.o.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),l.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0));const t=e.getRenderingMesh().skeleton;(null==t?void 0:t.isUsingTextureForMatrices)&&l.push("#define BONETEXTURE")}else l.push("#define NUM_BONE_INFLUENCERS 0");const c=s.morphTargetManager;let d=0;c&&c.numInfluencers>0&&(d=c.numInfluencers,l.push("#define MORPHTARGETS"),l.push("#define NUM_MORPH_INFLUENCERS "+d),c.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),It.G.PrepareAttributesForMorphTargetsInfluencers(h,s,d)),t&&(l.push("#define INSTANCES"),It.G.PushAttributesForInstances(h),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),this._storeNonLinearDepth&&l.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&l.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&l.push("#define PACKED"),(0,ua.lK)(a,r,l);const u=e._getDrawWrapper(void 0,!0),p=u.defines,f=l.join("\n");if(p!==f){const e=["world","mBones","boneTextureWidth","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];(0,ua.qx)(e),u.setEffect(n.createEffect("depth",h,e,["diffuseSampler","morphTargets","boneSampler"],f,void 0,void 0,void 0,{maxSimultaneousMorphTargets:d}),f)}return u.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){const e=[];for(const t in this._scene._depthRenderer){this._scene._depthRenderer[t]===this&&e.push(t)}if(e.length>0){this._depthMap.dispose();for(const t of e)delete this._scene._depthRenderer[t]}}}Rg._SceneComponentInitialization=e=>{throw(0,ge.S)("DepthRendererSceneComponent")};const Pg="minmaxReduxPixelShader",Ig="varying vec2 vUV;\nuniform sampler2D textureSampler;\n#if defined(INITIAL)\nuniform sampler2D sourceTexture;\nuniform vec2 texSize;\nvoid main(void)\n{\nivec2 coord=ivec2(vUV*(texSize-1.0));\nfloat f1=texelFetch(sourceTexture,coord,0).r;\nfloat f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;\nfloat f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;\nfloat f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;\nfloat minz=min(min(min(f1,f2),f3),f4);\n#ifdef DEPTH_REDUX\nfloat maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);\n#else\nfloat maxz=max(max(max(f1,f2),f3),f4);\n#endif\nglFragColor=vec4(minz,maxz,0.,0.);\n}\n#elif defined(MAIN)\nuniform vec2 texSize;\nvoid main(void)\n{\nivec2 coord=ivec2(vUV*(texSize-1.0));\nvec2 f1=texelFetch(textureSampler,coord,0).rg;\nvec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;\nvec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;\nvec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;\nfloat minz=min(min(min(f1.x,f2.x),f3.x),f4.x);\nfloat maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);\nglFragColor=vec4(minz,maxz,0.,0.);\n}\n#elif defined(ONEBEFORELAST)\nuniform ivec2 texSize;\nvoid main(void)\n{\nivec2 coord=ivec2(vUV*vec2(texSize-1));\nvec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;\nvec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;\nvec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;\nvec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;\nfloat minz=min(f1.x,f2.x);\nfloat maxz=max(f1.y,f2.y);\nglFragColor=vec4(minz,maxz,0.,0.);\n}\n#elif defined(LAST)\nvoid main(void)\n{\nglFragColor=vec4(0.);\nif (true) { \ndiscard;\n}\n}\n#endif\n";Ht.v.ShadersStore[Pg]=Ig;class Mg{constructor(e){this.onAfterReductionPerformed=new r.y$,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new _i.O(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((()=>{this._postProcessManager._rebuild()}))}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,n=!0){if(e===this._sourceTexture)return;this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=n;const s=this._camera.getScene(),r=new Zt("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,s.getEngine(),!1,"#define INITIAL"+(t?"\n#define DEPTH_REDUX":""),i,void 0,void 0,void 0,7);r.autoClear=!1,r.forceFullscreenViewport=n;let o=this._sourceTexture.getRenderWidth(),a=this._sourceTexture.getRenderHeight();r.onApply=((e,t)=>i=>{i.setTexture("sourceTexture",this._sourceTexture),i.setFloat2("texSize",e,t)})(o,a),this._reductionSteps.push(r);let l=1;for(;o>1||a>1;){o=Math.max(Math.round(o/2),1),a=Math.max(Math.round(a/2),1);const e=new Zt("Reduction phase "+l,"minmaxRedux",["texSize"],null,{width:o,height:a},null,1,s.getEngine(),!1,"#define "+(1==o&&1==a?"LAST":1==o||1==a?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,7);if(e.autoClear=!1,e.forceFullscreenViewport=n,e.onApply=((e,t)=>i=>{1==e||1==t?i.setInt2("texSize",e,t):i.setFloat2("texSize",e,t)})(o,a),this._reductionSteps.push(e),l++,1==o&&1==a){const t=(e,t,i)=>{const n=new Float32Array(4*e*t),r={min:0,max:0};return()=>{s.getEngine()._readTexturePixels(i.inputTexture.texture,e,t,-1,0,n,!1),r.min=n[0],r.max=n[1],this.onAfterReductionPerformed.notifyObservers(r)}};e.onAfterRenderObservable.add(t(o,a,e))}}}get refreshRate(){return this._sourceTexture?this._sourceTexture.refreshRate:-1}set refreshRate(e){this._sourceTexture&&(this._sourceTexture.refreshRate=e)}get activated(){return this._activated}activate(){!this._onAfterUnbindObserver&&this._sourceTexture&&(this._onAfterUnbindObserver=this._sourceTexture.onAfterUnbindObservable.add((()=>{var e,t;const i=this._camera.getScene().getEngine();null===(e=i._debugPushGroup)||void 0===e||e.call(i,"min max reduction",1),this._reductionSteps[0].activate(this._camera),this._postProcessManager.directRender(this._reductionSteps,this._reductionSteps[0].inputTexture,this._forceFullscreenViewport),i.unBindFramebuffer(this._reductionSteps[0].inputTexture,!1),null===(t=i._debugPopGroup)||void 0===t||t.call(i,1)})),this._activated=!0)}deactivate(){this._onAfterUnbindObserver&&this._sourceTexture&&(this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=null,this._activated=!1)}dispose(e=!0){if(e&&(this.onAfterReductionPerformed.clear(),this._onContextRestoredObserver&&(this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)),this.deactivate(),this._reductionSteps){for(let e=0;et&&(e=0,t=1),e<0&&(e=0),t>1&&(t=1),this._minDistance=e,this._maxDistance=t,this._breaksAreDirty=!0)}get minDistance(){return this._minDistance}get maxDistance(){return this._maxDistance}getClassName(){return Bg.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e=0&&et.maxZ||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0):this._shadowMaxZ=e}get debug(){return this._debug}set debug(e){this._debug=e,this._light._markMeshesAsLightDirty()}get depthClamp(){return this._depthClamp}set depthClamp(e){this._depthClamp=e}get cascadeBlendPercentage(){return this._cascadeBlendPercentage}set cascadeBlendPercentage(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()}get lambda(){return this._lambda}set lambda(e){const t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)}getCascadeViewMatrix(e){return e>=0&&e=0&&e=0&&e{let t=e.min,i=e.max;t>=i&&(t=0,i=1),t==this._minDistance&&i==this._maxDistance||this.setMinMaxDistance(t,i)})),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}}get autoCalcDepthBoundsRefreshRate(){var e,t,i;return null!==(i=null===(t=null===(e=this._depthReducer)||void 0===e?void 0:e.depthRenderer)||void 0===t?void 0:t.getDepthMap().refreshRate)&&void 0!==i?i:-1}set autoCalcDepthBoundsRefreshRate(e){var t;(null===(t=this._depthReducer)||void 0===t?void 0:t.depthRenderer)&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)}splitFrustum(){this._breaksAreDirty=!0}_splitFrustum(){const e=this._getCamera();if(!e)return;const t=e.minZ,i=e.maxZ||this._shadowMaxZ,n=i-t,s=this._minDistance,r=t+s*n,o=t+(this._shadowMaxZ=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance)*n,a=o-r,l=o/r;for(let h=0;h{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===xg.FILTER_PCF&&e.setColorWrite(!1),this._scene.setTransformMatrix(this.getCascadeViewMatrix(t),this.getCascadeProjectionMatrix(t)),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())})),this._shadowMap.onBeforeBindObservable.add((()=>{var t;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),null===(t=e._debugPushGroup)||void 0===t||t.call(e,`cascaded shadow map generation for pass id ${e.currentRenderPassId}`,1),this._breaksAreDirty&&this._splitFrustum(),this._computeMatrices()})),this._splitFrustum()}_bindCustomEffectForRenderSubMeshForShadowMap(e,t){t.setMatrix("viewProjection",this.getCascadeTransformMatrix(this._currentLayer))}_isReadyCustomDefines(e){e.push("#define SM_DEPTHCLAMP "+(this._depthClamp&&this._filter!==xg.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);const i=this._scene,n=this._light;if(!i.shadowsEnabled||!n.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;const s=this._getCamera();s&&this._shadowMaxZ<=(s.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),0===this.cascadeBlendPercentage&&(e["SHADOWCSMNOBLEND"+t]=!0)}bindShadowLight(e,t){const i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;const n=this._getCamera();if(!n)return;const s=this.getShadowMap();if(!s)return;const r=s.getSize().width;if(t.setMatrices("lightMatrix"+e,this._transformMatricesAsArray),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,0===this.cascadeBlendPercentage?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===xg.FILTER_PCF)t.setDepthStencilTexture("shadowSampler"+e,s),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),r,1/r,this.frustumEdgeFalloff,e);else if(this._filter===xg.FILTER_PCSS){for(let e=0;enew Bg(e,t,void 0,i)));return void 0!==e.numCascades&&(i.numCascades=e.numCascades),void 0!==e.debug&&(i.debug=e.debug),void 0!==e.stabilizeCascades&&(i.stabilizeCascades=e.stabilizeCascades),void 0!==e.lambda&&(i.lambda=e.lambda),void 0!==e.cascadeBlendPercentage&&(i.cascadeBlendPercentage=e.cascadeBlendPercentage),void 0!==e.depthClamp&&(i.depthClamp=e.depthClamp),void 0!==e.autoCalcDepthBounds&&(i.autoCalcDepthBounds=e.autoCalcDepthBounds),void 0!==e.shadowMaxZ&&(i.shadowMaxZ=e.shadowMaxZ),void 0!==e.penumbraDarkness&&(i.penumbraDarkness=e.penumbraDarkness),void 0!==e.freezeShadowCastersBoundingInfo&&(i.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),void 0!==e.minDistance&&void 0!==e.maxDistance&&i.setMinMaxDistance(e.minDistance,e.maxDistance),i}}Bg._FrustumCornersNDCSpace=[new o.P(-1,1,-1),new o.P(1,1,-1),new o.P(1,-1,-1),new o.P(-1,-1,-1),new o.P(-1,1,1),new o.P(1,1,1),new o.P(1,-1,1),new o.P(-1,-1,1)],Bg.CLASSNAME="CascadedShadowGenerator",Bg.DEFAULT_CASCADES_COUNT=4,Bg.MIN_CASCADES_COUNT=2,Bg.MAX_CASCADES_COUNT=4,Bg._SceneComponentInitialization=e=>{throw(0,ge.S)("ShadowGeneratorSceneComponent")},n.p.AddParser(Se.l.NAME_SHADOWGENERATOR,((e,t)=>{if(void 0!==e.shadowGenerators&&null!==e.shadowGenerators)for(let i=0,n=e.shadowGenerators.length;i{let t=e._getComponent(Se.l.NAME_SHADOWGENERATOR);t||(t=new Ug(e),e._addComponent(t))},b.N.AddNodeConstructor("Light_Type_0",((e,t)=>()=>new Vg(e,o.P.Zero(),t)));class Vg extends np{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 he.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new o.P(1,0,0);case 1:return new o.P(-1,0,0);case 2:return new o.P(0,-1,0);case 3:return new o.P(0,1,0);case 4:return new o.P(0,0,1);case 5:return new o.P(0,0,-1)}return o.P.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){const n=this.getScene().activeCamera;if(!n)return;const s=void 0!==this.shadowMinZ?this.shadowMinZ:n.minZ,r=void 0!==this.shadowMaxZ?this.shadowMaxZ:n.maxZ,a=this.getScene().getEngine().useReverseDepthBuffer;o.y3.PerspectiveFovLHToRef(this.shadowAngle,1,a?r:s,a?s:r,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}}(0,oe.gn)([(0,E.qC)()],Vg.prototype,"shadowAngle",null);class kg{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{const e=this._renderingCanvas.getBoundingClientRect(),t=window.getComputedStyle(this._renderingCanvas).position;this._loadingDiv&&(this._loadingDiv.style.position="fixed"===t?"fixed":"absolute",this._loadingDiv.style.left=e.left+"px",this._loadingDiv.style.top=e.top+"px",this._loadingDiv.style.width=e.width+"px",this._loadingDiv.style.height=e.height+"px")}}displayLoadingUI(){if(this._loadingDiv)return;this._loadingDiv=document.createElement("div"),this._loadingDiv.id="babylonjsLoadingDiv",this._loadingDiv.style.opacity="0",this._loadingDiv.style.transition="opacity 1.5s ease",this._loadingDiv.style.pointerEvents="none",this._loadingDiv.style.display="grid",this._loadingDiv.style.gridTemplateRows="100%",this._loadingDiv.style.gridTemplateColumns="100%",this._loadingDiv.style.justifyItems="center",this._loadingDiv.style.alignItems="center",this._loadingTextDiv=document.createElement("div"),this._loadingTextDiv.style.position="absolute",this._loadingTextDiv.style.left="0",this._loadingTextDiv.style.top="50%",this._loadingTextDiv.style.marginTop="80px",this._loadingTextDiv.style.width="100%",this._loadingTextDiv.style.height="20px",this._loadingTextDiv.style.fontFamily="Arial",this._loadingTextDiv.style.fontSize="14px",this._loadingTextDiv.style.color="white",this._loadingTextDiv.style.textAlign="center",this._loadingTextDiv.style.zIndex="1",this._loadingTextDiv.innerHTML="Loading",this._loadingDiv.appendChild(this._loadingTextDiv),this._loadingTextDiv.innerHTML=this._loadingText,this._style=document.createElement("style"),this._style.type="text/css";this._style.innerHTML="@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }",document.getElementsByTagName("head")[0].appendChild(this._style);const e=!!window.SVGSVGElement,t=new Image;kg.DefaultLogoUrl?t.src=kg.DefaultLogoUrl:t.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5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iAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+":"https://cdn.babylonjs.com/Assets/babylonLogo.png",t.style.width="150px",t.style.gridColumn="1",t.style.gridRow="1",t.style.top="50%",t.style.left="50%",t.style.transform="translate(-50%, -50%)",t.style.position="absolute";const i=document.createElement("div");i.style.width="300px",i.style.gridColumn="1",i.style.gridRow="1",i.style.top="50%",i.style.left="50%",i.style.transform="translate(-50%, -50%)",i.style.position="absolute";const n=new Image;if(kg.DefaultSpinnerUrl?n.src=kg.DefaultSpinnerUrl:n.src=e?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",n.style.animation="spin1 0.75s infinite linear",n.style.webkitAnimation="spin1 0.75s infinite linear",n.style.transformOrigin="50% 50%",n.style.webkitTransformOrigin="50% 50%",!e){const e={w:16,h:18.5},i={w:30,h:30};t.style.width=`${e.w}vh`,t.style.height=`${e.h}vh`,t.style.left=`calc(50% - ${e.w/2}vh)`,t.style.top=`calc(50% - ${e.h/2}vh)`,n.style.width=`${i.w}vh`,n.style.height=`${i.h}vh`,n.style.left=`calc(50% - ${i.w/2}vh)`,n.style.top=`calc(50% - ${i.h/2}vh)`}i.appendChild(n),this._loadingDiv.appendChild(t),this._loadingDiv.appendChild(i),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}hideLoadingUI(){if(!this._loadingDiv)return;this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",(()=>{this._loadingTextDiv&&(this._loadingTextDiv.remove(),this._loadingTextDiv=null),this._loadingDiv&&(this._loadingDiv.remove(),this._loadingDiv=null),this._style&&(this._style.remove(),this._style=null),window.removeEventListener("resize",this._resizeLoadingUI)}))}set loadingUIText(e){this._loadingText=e,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)}get loadingUIText(){return this._loadingText}get loadingUIBackgroundColor(){return this._loadingDivBackgroundColor}set loadingUIBackgroundColor(e){this._loadingDivBackgroundColor=e,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)}}kg.DefaultLogoUrl="",kg.DefaultSpinnerUrl="",fe.D.DefaultLoadingScreenFactory=e=>new kg(e);var Gg=i(4106),zg=i(8058);class Wg{static ConvertPanoramaToCubemap(e,t,i,n,s=!1){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";return{front:this.CreateCubemapTexture(n,this.FACE_FRONT,e,t,i,s),back:this.CreateCubemapTexture(n,this.FACE_BACK,e,t,i,s),left:this.CreateCubemapTexture(n,this.FACE_LEFT,e,t,i,s),right:this.CreateCubemapTexture(n,this.FACE_RIGHT,e,t,i,s),up:this.CreateCubemapTexture(n,this.FACE_UP,e,t,i,s),down:this.CreateCubemapTexture(n,this.FACE_DOWN,e,t,i,s),size:n,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,n,s,r=!1){const o=new ArrayBuffer(e*e*4*3),a=new Float32Array(o),l=r?Math.max(1,Math.round(n/4/e)):1,h=1/l,c=h*h,d=t[1].subtract(t[0]).scale(h/e),u=t[3].subtract(t[2]).scale(h/e),p=1/e;let f=0;for(let _=0;_Math.PI;)s-=2*Math.PI;let o=s/Math.PI;const a=r/Math.PI;o=.5*o+.5;let l=Math.round(o*i);l<0?l=0:l>=i&&(l=i-1);let h=Math.round(a*n);h<0?h=0:h>=n&&(h=n-1);const c=n-h-1;return{r:t[c*i*3+3*l+0],g:t[c*i*3+3*l+1],b:t[c*i*3+3*l+2]}}}Wg.FACE_LEFT=[new o.P(-1,-1,-1),new o.P(1,-1,-1),new o.P(-1,1,-1),new o.P(1,1,-1)],Wg.FACE_RIGHT=[new o.P(1,-1,1),new o.P(-1,-1,1),new o.P(1,1,1),new o.P(-1,1,1)],Wg.FACE_FRONT=[new o.P(1,-1,-1),new o.P(1,-1,1),new o.P(1,1,-1),new o.P(1,1,1)],Wg.FACE_BACK=[new o.P(-1,-1,1),new o.P(-1,-1,-1),new o.P(-1,1,1),new o.P(-1,1,-1)],Wg.FACE_DOWN=[new o.P(1,1,-1),new o.P(1,1,1),new o.P(-1,1,-1),new o.P(-1,1,1)],Wg.FACE_UP=[new o.P(-1,-1,-1),new o.P(-1,-1,1),new o.P(1,-1,-1),new o.P(1,-1,1)];class Hg{static _Ldexp(e,t){return t>1023?e*Math.pow(2,1023)*Math.pow(2,t-1023):t<-1074?e*Math.pow(2,-1074)*Math.pow(2,t+1074):e*Math.pow(2,t)}static _Rgbe2float(e,t,i,n,s,r){s>0?(s=this._Ldexp(1,s-136),e[r+0]=t*s,e[r+1]=i*s,e[r+2]=n*s):(e[r+0]=0,e[r+1]=0,e[r+2]=0)}static _ReadStringLine(e,t){let i="",n="";for(let s=t;s32767)throw"HDR Bad header format, unsupported size";return o+=n.length+1,{height:t,width:i,dataPosition:o}}static GetCubeMapTextureData(e,t,i=!1){const n=new Uint8Array(e),s=this.RGBE_ReadHeader(n),r=this.RGBE_ReadPixels(n,s);return Wg.ConvertPanoramaToCubemap(r,s.width,s.height,t,i)}static RGBE_ReadPixels(e,t){return this._RGBEReadPixelsRLE(e,t)}static _RGBEReadPixelsRLE(e,t){let i=t.height;const n=t.width;let s,r,o,a,l,h=t.dataPosition,c=0,d=0,u=0;const p=new ArrayBuffer(4*n),f=new Uint8Array(p),_=new ArrayBuffer(t.width*t.height*4*3),m=new Float32Array(_);for(;i>0;){if(s=e[h++],r=e[h++],o=e[h++],a=e[h++],2!=s||2!=r||128&o||t.width<8||t.width>32767)return this._RGBEReadPixelsNOTRLE(e,t);if((o<<8|a)!=n)throw"HDR Bad header format, wrong scan line width";for(c=0,u=0;u<4;u++)for(d=(u+1)*n;c128){if(l=s-128,0==l||l>d-c)throw"HDR Bad Format, bad scanline data (run)";for(;l-- >0;)f[c++]=r}else{if(l=s,0==l||l>d-c)throw"HDR Bad Format, bad scanline data (non-run)";if(f[c++]=r,--l>0)for(let t=0;t0;){for(l=0;l{this._effectRenderer=new vi(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled((()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()}))})):(p.Y.Warn("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."),Promise.reject("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."))}}class $g extends Re{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(o.y3.RotationY(this._rotationY))}get rotationY(){return this._rotationY}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}constructor(e,t,i,n=!1,s=!0,a=!1,l=!1,h=null,c=null,d=!1){var u;super(t),this._generateHarmonics=!0,this._onError=null,this._isBlocking=!0,this._rotationY=0,this.boundingBoxPosition=o.P.Zero(),this.onLoadObservable=new r.y$,e&&(this._coordinatesMode=Le.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=o.y3.Identity(),this._prefilterOnLoad=l,this._onLoad=()=>{this.onLoadObservable.notifyObservers(this),h&&h()},this._onError=c,this.gammaSpace=a,this._noMipmap=n,this._size=i,this._supersample=d,this._generateHarmonics=s,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?this._texture.isReady?se.w1.SetImmediate((()=>this._onLoad())):this._texture.onLoadedObservable.add(this._onLoad):(null===(u=this.getScene())||void 0===u?void 0:u.useDelayedTextureLoading)?this.delayLoadState=4:this._loadTexture())}getClassName(){return"HDRCubeTexture"}_loadTexture(){const e=this._getEngine(),t=e.getCaps();let i=0;t.textureFloat&&t.textureFloatLinearFiltering?i=1:t.textureHalfFloat&&t.textureHalfFloatLinearFiltering&&(i=2);if(e._features.allowTexturePrefiltering&&this._prefilterOnLoad){const t=this._onLoad,i=new qg(e);this._onLoad=()=>{i.prefilter(this,t)}}this._texture=e.createRawCubeTextureFromUrl(this.url,this.getScene(),this._size,4,i,this._noMipmap,(e=>{this.lodGenerationOffset=0,this.lodGenerationScale=.8;const t=Hg.GetCubeMapTextureData(e,this._size,this._supersample);if(this._generateHarmonics){const e=zh.ConvertCubeMapToSphericalPolynomial(t);this.sphericalPolynomial=e}const n=[];let s=null,r=null;for(let o=0;o<6;o++){2===i?r=new Uint16Array(this._size*this._size*3):0===i&&(s=new Uint8Array(this._size*this._size*3));const e=t[$g._FacesMapping[o]];if(this.gammaSpace||r||s)for(let t=0;t255){const e=255/o;i*=e,n*=e,r*=e}s[3*t+0]=i,s[3*t+1]=n,s[3*t+2]=r}r?n.push(r):s?n.push(s):n.push(e)}return n}),null,this._onLoad,this._onError)}clone(){const e=new $g(this.url,this.getScene()||this._getEngine(),this._size,this._noMipmap,this._generateHarmonics,this.gammaSpace);return e.level=this.level,e.wrapU=this.wrapU,e.wrapV=this.wrapV,e.coordinatesIndex=this.coordinatesIndex,e.coordinatesMode=this.coordinatesMode,e}delayLoad(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this._loadTexture())}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){var t;this._textureMatrix=e,e.updateFlag!==this._textureMatrix.updateFlag&&e.isIdentity()!==this._textureMatrix.isIdentity()&&(null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1,(e=>-1!==e.getActiveTextures().indexOf(this))))}dispose(){this.onLoadObservable.clear(),super.dispose()}static Parse(e,t,i){let n=null;return e.name&&!e.isRenderTarget&&(n=new $g(i+e.name,t,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace),n.name=e.name,n.hasAlpha=e.hasAlpha,n.level=e.level,n.coordinatesMode=e.coordinatesMode,n.isBlocking=e.isBlocking),n&&(e.boundingBoxPosition&&(n.boundingBoxPosition=o.P.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(n.boundingBoxSize=o.P.FromArray(e.boundingBoxSize)),e.rotationY&&(n.rotationY=e.rotationY)),n}serialize(){if(!this.name)return null;const e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this.gammaSpace,e.generateHarmonics=this._generateHarmonics,e.customType="BABYLON.HDRCubeTexture",e.noMipmap=this._noMipmap,e.isBlocking=this._isBlocking,e.rotationY=this._rotationY,e}}$g._FacesMapping=["right","left","up","down","front","back"],(0,l.H)("BABYLON.HDRCubeTexture",$g);class Qg{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=new Array,this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new r.y$,this._onDataLayoutChanged=new r.y$,this._animationPropertiesOverride=null,this._scene=i||m.l.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=E.p4.Clone((()=>new Qg(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())),E.p4.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){const i=new Qg(e.name,e.influence);if(i.setPositions(e.positions),null!=e.id&&(i.id=e.id),e.normals&&i.setNormals(e.normals),e.tangents&&i.setTangents(e.tangents),e.uvs&&i.setUVs(e.uvs),e.animations){for(let t=0;t0}constructor(e=null){if(this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new Wt.t(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._uniqueId=0,this._tempInfluences=new Array,this._canUseTextureForTargets=!1,this._blockCounter=0,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this._useTextureToStoreTargets=!0,e||(e=m.l.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 uniqueId(){return this._uniqueId}get vertexCount(){return this._vertexCount}get supportsNormals(){return this._supportsNormals&&this.enableNormalMorphing}get supportsTangents(){return this._supportsTangents&&this.enableTangentMorphing}get supportsUVs(){return this._supportsUVs&&this.enableUVMorphing}get numTargets(){return this._targets.length}get numInfluencers(){return this._activeTargets.length}get influences(){return this._influences}get useTextureToStoreTargets(){return this._useTextureToStoreTargets}set useTextureToStoreTargets(e){this._useTextureToStoreTargets=e}get isUsingTextureForTargets(){var e;return Jg.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!(null===(e=this._scene)||void 0===e?void 0:e.getEngine().getCaps().disableMorphTargetTexture)}getActiveTarget(e){return this._activeTargets.data[e]}getTarget(e){return this._targets[e]}addTarget(e){this._targets.push(e),this._targetInfluenceChangedObservers.push(e.onInfluenceChanged.add((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)}clone(){const e=new Jg(this._scene);for(const t of this._targets)e.addTarget(t.clone());return e.enableNormalMorphing=this.enableNormalMorphing,e.enableTangentMorphing=this.enableTangentMorphing,e.enableUVMorphing=this.enableUVMorphing,e}serialize(){const e={};e.id=this.uniqueId,e.targets=[];for(const t of this._targets)e.targets.push(t.serialize());return e}_syncActiveTargets(e){if(this.areUpdatesFrozen)return;let t=0;this._activeTargets.reset(),this._supportsNormals=!0,this._supportsTangents=!0,this._supportsUVs=!0,this._vertexCount=0,this._scene&&this._targets.length>this._scene.getEngine().getCaps().texture2DArrayMaxLayerCount&&(this.useTextureToStoreTargets=!1),this._morphTargetTextureIndices&&this._morphTargetTextureIndices.length===this._targets.length||(this._morphTargetTextureIndices=new Float32Array(this._targets.length));let i=-1;for(const n of this._targets){if(i++,0===n.influence&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=Jg.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(n),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=n.influence,this._supportsNormals=this._supportsNormals&&n.hasNormals,this._supportsTangents=this._supportsTangents&&n.hasTangents,this._supportsUVs=this._supportsUVs&&n.hasUVs;const e=n.getPositions();if(e){const t=e.length/3;if(0===this._vertexCount)this._vertexCount=t;else if(this._vertexCount!==t)return void p.Y.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 n=0;ne&&(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-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 Jg(t);i._uniqueId=e.id;for(const n of e.targets)i.addTarget(Qg.Parse(n,t));return i}}Jg.EnableTextureStorage=!0,Jg.MaxActiveMorphTargetsInVertexAttributeMode=8;class ev{constructor(){this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld=o.P.Zero(),this._hitPointWorld=o.P.Zero(),this._rayFromWorld=o.P.Zero(),this._rayToWorld=o.P.Zero(),this._triangleIndex=-1}get hasHit(){return this._hasHit}get hitDistance(){return this._hitDistance}get hitNormalWorld(){return this._hitNormalWorld}get hitPointWorld(){return this._hitPointWorld}get rayFromWorld(){return this._rayFromWorld}get rayToWorld(){return this._rayToWorld}get triangleIndex(){return this._triangleIndex}setHitData(e,t,i){this._hasHit=!0,this._hitNormalWorld.set(e.x,e.y,e.z),this._hitPointWorld.set(t.x,t.y,t.z),this._triangleIndex=null!=i?i:-1}setHitDistance(e){this._hitDistance=e}calculateHitDistance(){this._hitDistance=o.P.Distance(this._rayFromWorld,this._hitPointWorld)}reset(e=o.P.Zero(),t=o.P.Zero()){this._rayFromWorld.copyFrom(e),this._rayToWorld.copyFrom(t),this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld.setAll(0),this._hitPointWorld.setAll(0),this._triangleIndex=-1}}class tv{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw(0,ge.S)("CannonJSPlugin")}constructor(e,t=tv.DefaultPluginFactory()){if(this._physicsPlugin=t,this._impostors=[],this._joints=[],this._subTimeStep=0,this._uniqueIdCounter=0,!this._physicsPlugin.isSupported())throw new Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");e=e||new o.P(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._impostors.forEach((function(e){e.dispose()})),this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}addImpostor(e){this._impostors.push(e),e.uniqueId=this._uniqueIdCounter++,e.parent||this._physicsPlugin.generatePhysicsBody(e)}removeImpostor(e){const t=this._impostors.indexOf(e);if(t>-1){this._impostors.splice(t,1).length&&this.getPhysicsPlugin().removePhysicsBody(e)}}addJoint(e,t,i){const n={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(n),this._physicsPlugin.generateJoint(n)}removeJoint(e,t,i){const n=this._joints.filter((function(n){return n.connectedImpostor===t&&n.joint===i&&n.mainImpostor===e}));n.length&&this._physicsPlugin.removeJoint(n[0])}_step(e){this._impostors.forEach((e=>{e.isBodyInitRequired()&&this._physicsPlugin.generatePhysicsBody(e)})),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)}getPhysicsPlugin(){return this._physicsPlugin}getImpostors(){return this._impostors}getImpostorForPhysicsObject(e){for(let t=0;t0&&(this._physicsBodiesToRemoveAfterStep.forEach((e=>{"function"==typeof this.world.removeBody?this.world.removeBody(e):this.world.remove(e)})),this._physicsBodiesToRemoveAfterStep.length=0)}applyImpulse(e,t,i){const n=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(s,n)}applyForce(e,t,i){const n=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(s,n)}generatePhysicsBody(e){if(this._removeMarkedPhysicsBodiesFromWorld(),e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else{if(e.isBodyInitRequired()){const t=this._createShape(e);if(!t)return void p.Y.Warn("It was not possible to create a physics body for this object.");const i=e.physicsBody;i&&this.removePhysicsBody(e);const n=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),s={mass:e.getParam("mass"),material:n},r=e.getParam("nativeOptions");for(const e in r)Object.prototype.hasOwnProperty.call(r,e)&&(s[e]=r[e]);e.physicsBody=new this.BJSCANNON.Body(s),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),"function"==typeof this.world.addBody?this.world.addBody(e.physicsBody):this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach((function(t){const n=i[t];e.physicsBody[t].set(n.x,n.y,n.z)})),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)}}_processChildMeshes(e){const t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[],i=e.object.rotationQuaternion;if(i?i.conjugateToRef(this._tmpQuaternion):this._tmpQuaternion.set(0,0,0,1),t.length){const i=t=>{if(!t.rotationQuaternion)return;const n=t.getPhysicsImpostor();if(n){if(n.parent!==e&&t.parent){const i=t.getAbsolutePosition().subtract(t.parent.getAbsolutePosition()),s=t.rotationQuaternion.multiply(this._tmpQuaternion);n.physicsBody&&(this.removePhysicsBody(n),n.physicsBody=null),n.parent=e,n.resetUpdateFlags(),e.physicsBody.addShape(this._createShape(n),new this.BJSCANNON.Vec3(i.x,i.y,i.z),new this.BJSCANNON.Quaternion(s.x,s.y,s.z,s.w)),e.physicsBody.mass+=n.getParam("mass")}}t.getChildMeshes(!0).filter((e=>!!e.physicsImpostor)).forEach(i)};t.filter((e=>!!e.physicsImpostor)).forEach(i)}}removePhysicsBody(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),-1===this._physicsBodiesToRemoveAfterStep.indexOf(e.physicsBody)&&this._physicsBodiesToRemoveAfterStep.push(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;let n;const s=e.joint.jointData,r={pivotA:s.mainPivot?(new this.BJSCANNON.Vec3).set(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z):null,pivotB:s.connectedPivot?(new this.BJSCANNON.Vec3).set(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z):null,axisA:s.mainAxis?(new this.BJSCANNON.Vec3).set(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z):null,axisB:s.connectedAxis?(new this.BJSCANNON.Vec3).set(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z):null,maxForce:s.nativeParams.maxForce,collideConnected:!!s.collision};switch(e.joint.type){case st.HingeJoint:case st.Hinge2Joint:n=new this.BJSCANNON.HingeConstraint(t,i,r);break;case st.DistanceJoint:n=new this.BJSCANNON.DistanceConstraint(t,i,s.maxDistance||2);break;case st.SpringJoint:{const e=s;n=new this.BJSCANNON.Spring(t,i,{restLength:e.length,stiffness:e.stiffness,damping:e.damping,localAnchorA:r.pivotA,localAnchorB:r.pivotB});break}case st.LockJoint:n=new this.BJSCANNON.LockConstraint(t,i,r);break;case st.PointToPointJoint:case st.BallAndSocketJoint:default:n=new this.BJSCANNON.PointToPointConstraint(t,r.pivotA,i,r.pivotB,r.maxForce)}n.collideConnected=!!s.collision,e.joint.physicsJoint=n,e.joint.type!==st.SpringJoint?this.world.addConstraint(n):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){n.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}removeJoint(e){e.joint.type!==st.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}_addMaterial(e,t,i){let n,s;for(n=0;n1e3*i));e++);this.time+=n;const a=this.time%i/i,l=e,h=this.bodies;for(let e=0;e!==h.length;e++){const i=h[e];i.type!==t.Body.STATIC&&i.sleepState!==t.Body.SLEEPING?(i.position.vsub(i.previousPosition,l),l.scale(a,l),i.position.vadd(l,i.interpolatedPosition)):(i.interpolatedPosition.set(i.position.x,i.position.y,i.position.z),i.interpolatedQuaternion.set(i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w))}}}}raycast(e,t){return this._raycastResult.reset(e,t),this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._cannonRaycastResult.reset(),this.world.raycastClosest(e,t,{},this._cannonRaycastResult),i.reset(e,t),this._cannonRaycastResult.hasHit&&(i.setHitData({x:this._cannonRaycastResult.hitNormalWorld.x,y:this._cannonRaycastResult.hitNormalWorld.y,z:this._cannonRaycastResult.hitNormalWorld.z},{x:this._cannonRaycastResult.hitPointWorld.x,y:this._cannonRaycastResult.hitPointWorld.y,z:this._cannonRaycastResult.hitPointWorld.z}),i.setHitDistance(this._cannonRaycastResult.distance))}}tv.DefaultPluginFactory=()=>new iv;class nv{constructor(e=!0,t,i=OIMO){this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=o.P.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new ev}getPluginVersion(){return 1}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}setTimeStep(e){this.world.timeStep=e}getTimeStep(){return this.world.timeStep}executeStep(e,t){t.forEach((function(e){e.beforeStep()})),this.world.timeStep=this._useDeltaForWorldStep?e:this._fixedTimeStep,this.world.step(),t.forEach((e=>{e.afterStep(),this._tmpImpostorsArray[e.uniqueId]=e}));let i=this.world.contacts;for(;null!==i;){if(i.touching&&!i.body1.sleeping&&!i.body2.sleeping){i=i.next;continue}const e=this._tmpImpostorsArray[+i.body1.name],t=this._tmpImpostorsArray[+i.body2.name];e&&t?(e.onCollide({body:t.physicsBody,point:null,distance:0,impulse:0,normal:null}),t.onCollide({body:e.physicsBody,point:null,distance:0,impulse:0,normal:null}),i=i.next):i=i.next}}applyImpulse(e,t,i){const n=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*n))}applyForce(e,t,i){p.Y.Warn("Oimo doesn't support applying force. Using impulse instead."),this.applyImpulse(e,t,i)}generatePhysicsBody(e){if(e.parent)e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());else{if(e.isBodyInitRequired()){const t={name:e.uniqueId,config:[e.getParam("mass")||.001,e.getParam("friction"),e.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:0!==e.getParam("mass"),density:e.getParam("mass"),friction:e.getParam("friction"),restitution:e.getParam("restitution"),world:this.world},i=[e];(e=>{e.getChildMeshes&&e.getChildMeshes().forEach((function(e){e.physicsImpostor&&i.push(e.physicsImpostor)}))})(e.object);const n=e=>Math.max(e,k.kn),s=new o._f;i.forEach((i=>{if(!i.object.rotationQuaternion)return;const r=i.object.rotationQuaternion;s.copyFrom(r),i.object.rotationQuaternion.set(0,0,0,1),i.object.computeWorldMatrix(!0);const o=s.toEulerAngles(),a=i.getObjectExtents(),l=57.29577951308232;if(i===e){const i=e.getObjectCenter();e.object.getAbsolutePivotPoint().subtractToRef(i,this._tmpPositionVector),this._tmpPositionVector.divideInPlace(e.object.scaling),t.pos.push(i.x),t.pos.push(i.y),t.pos.push(i.z),t.posShape.push(0,0,0),t.rotShape.push(0,0,0)}else{const e=i.object.position.clone();t.posShape.push(e.x),t.posShape.push(e.y),t.posShape.push(e.z),t.rotShape.push(o.x*l,o.y*l,o.z*l)}switch(i.object.rotationQuaternion.copyFrom(s),i.type){case rt.ParticleImpostor:p.Y.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case rt.SphereImpostor:{const e=a.x,i=a.y,s=a.z,r=Math.max(n(e),n(i),n(s))/2;t.type.push("sphere"),t.size.push(r),t.size.push(r),t.size.push(r);break}case rt.CylinderImpostor:{const e=n(a.x)/2,i=n(a.y);t.type.push("cylinder"),t.size.push(e),t.size.push(i),t.size.push(i);break}case rt.PlaneImpostor:case rt.BoxImpostor:default:{const e=n(a.x),i=n(a.y),s=n(a.z);t.type.push("box"),t.size.push(e),t.size.push(i),t.size.push(s);break}}i.object.rotationQuaternion=r})),e.physicsBody=this.world.add(t),e.physicsBody.resetQuaternion(s),e.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpPositionVector)}}removePhysicsBody(e){this.world.removeRigidBody(e.physicsBody)}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;const n=e.joint.jointData,s=n.nativeParams||{};let r;const o={body1:t,body2:i,axe1:s.axe1||(n.mainAxis?n.mainAxis.asArray():null),axe2:s.axe2||(n.connectedAxis?n.connectedAxis.asArray():null),pos1:s.pos1||(n.mainPivot?n.mainPivot.asArray():null),pos2:s.pos2||(n.connectedPivot?n.connectedPivot.asArray():null),min:s.min,max:s.max,collision:s.collision||n.collision,spring:s.spring,world:this.world};switch(e.joint.type){case st.BallAndSocketJoint:r="jointBall";break;case st.SpringJoint:{p.Y.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");const e=n;o.min=e.length||o.min,o.max=Math.max(o.min,o.max)}case st.DistanceJoint:r="jointDistance",o.max=n.maxDistance;break;case st.PrismaticJoint:r="jointPrisme";break;case st.SliderJoint:r="jointSlide";break;case st.WheelJoint:r="jointWheel";break;case st.HingeJoint:default:r="jointHinge"}o.type=r,e.joint.physicsJoint=this.world.add(o)}removeJoint(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(t){p.Y.Warn(t)}}isSupported(){return void 0!==this.BJSOIMO}setTransformationFromPhysicsBody(e){if(!e.physicsBody.sleeping){if(e.physicsBody.shapes.next){let t=e.physicsBody.shapes;for(;t.next;)t=t.next;e.object.position.set(t.position.x,t.position.y,t.position.z)}else{const t=e.physicsBody.getPosition();e.object.position.set(t.x,t.y,t.z)}if(e.object.rotationQuaternion){const t=e.physicsBody.getQuaternion();e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}}}setPhysicsBodyTransformation(e,t,i){const n=e.physicsBody;e.physicsBody.shapes.next||(n.position.set(t.x,t.y,t.z),n.orientation.set(i.x,i.y,i.z,i.w),n.syncShapes(),n.awake())}setLinearVelocity(e,t){e.physicsBody.linearVelocity.set(t.x,t.y,t.z)}setAngularVelocity(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)}getLinearVelocity(e){const t=e.physicsBody.linearVelocity;return t?new o.P(t.x,t.y,t.z):null}getAngularVelocity(e){const t=e.physicsBody.angularVelocity;return t?new o.P(t.x,t.y,t.z):null}setBodyMass(e,t){const i=0===t;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)}getBodyMass(e){return e.physicsBody.shapes.density}getBodyFriction(e){return e.physicsBody.shapes.friction}setBodyFriction(e,t){e.physicsBody.shapes.friction=t}getBodyRestitution(e){return e.physicsBody.shapes.restitution}setBodyRestitution(e,t){e.physicsBody.shapes.restitution=t}sleepBody(e){e.physicsBody.sleep()}wakeUpBody(e){e.physicsBody.awake()}updateDistanceJoint(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)}setMotor(e,t,i,n){void 0!==i?p.Y.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;const s=n?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setMotor(t,i)}setLimit(e,t,i,n){const s=n?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setLimit(t,void 0===i?-t:i)}syncMeshWithImpostor(e,t){const i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.orientation.x,e.rotationQuaternion.y=i.orientation.y,e.rotationQuaternion.z=i.orientation.z,e.rotationQuaternion.w=i.orientation.w)}getRadius(e){return e.physicsBody.shapes.radius}getBoxSizeToRef(e,t){const i=e.physicsBody.shapes;t.x=2*i.halfWidth,t.y=2*i.halfHeight,t.z=2*i.halfDepth}dispose(){this.world.clear()}raycast(e,t){return p.Y.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult}raycastToRef(e,t,i){p.Y.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)}}class sv{constructor(e=!0,t=Ammo,i=null){this._useDeltaForWorldStep=e,this.bjsAMMO={},this.name="AmmoJSPlugin",this._timeStep=1/60,this._fixedTimeStep=1/60,this._maxSteps=5,this._tmpQuaternion=new o._f,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new o.P,this._tmpContactNormal=new o.P,this._tmpVec3=new o.P,this._tmpMatrix=new o.y3,"function"!=typeof t?(this.bjsAMMO=t,this.isSupported()?(this._collisionConfiguration=new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration,this._dispatcher=new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration),this._overlappingPairCache=i||new this.bjsAMMO.btDbvtBroadphase,this._solver=new this.bjsAMMO.btSequentialImpulseConstraintSolver,this._softBodySolver=new this.bjsAMMO.btDefaultSoftBodySolver,this.world=new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher,this._overlappingPairCache,this._solver,this._collisionConfiguration,this._softBodySolver),this._tmpAmmoConcreteContactResultCallback=new this.bjsAMMO.ConcreteContactResultCallback,this._tmpAmmoConcreteContactResultCallback.addSingleResult=e=>{const t=(e=this.bjsAMMO.wrapPointer(e,this.bjsAMMO.btManifoldPoint)).getPositionWorldOnA(),i=e.m_normalWorldOnB;this._tmpContactPoint.x=t.x(),this._tmpContactPoint.y=t.y(),this._tmpContactPoint.z=t.z(),this._tmpContactNormal.x=i.x(),this._tmpContactNormal.y=i.y(),this._tmpContactNormal.z=i.z(),this._tmpContactImpulse=e.getAppliedImpulse(),this._tmpContactDistance=e.getDistance(),this._tmpContactCallbackResult=!0},this._raycastResult=new ev,this._tmpAmmoTransform=new this.bjsAMMO.btTransform,this._tmpAmmoTransform.setIdentity(),this._tmpAmmoQuaternion=new this.bjsAMMO.btQuaternion(0,0,0,1),this._tmpAmmoVectorA=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorB=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorC=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorD=new this.bjsAMMO.btVector3(0,0,0)):p.Y.Error("AmmoJS is not available. Please make sure you included the js file.")):p.Y.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.")}getPluginVersion(){return 1}setGravity(e){this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),this.world.setGravity(this._tmpAmmoVectorA),this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA)}setTimeStep(e){this._timeStep=e}setFixedTimeStep(e){this._fixedTimeStep=e}setMaxSteps(e){this._maxSteps=e}getTimeStep(){return this._timeStep}_isImpostorInContact(e){return this._tmpContactCallbackResult=!1,this.world.contactTest(e.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_isImpostorPairInContact(e,t){return this._tmpContactCallbackResult=!1,this.world.contactPairTest(e.physicsBody,t.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_stepSimulation(e=1/60,t=10,i=1/60){if(0==t)this.world.stepSimulation(e,0);else for(;t>0&&e>0;)e-i0&&this._isImpostorInContact(i))for(const e of i._onPhysicsCollideCallbacks)for(const t of e.otherImpostors)(i.physicsBody.isActive()||t.physicsBody.isActive())&&this._isImpostorPairInContact(i,t)&&(i.onCollide({body:t.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}),t.onCollide({body:i.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}))}_afterSoftStep(e){e.type===rt.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)}_ropeStep(e){const t=e.physicsBody.get_m_nodes(),i=t.size();let n,s,r,a,l;const h=new Array;for(let u=0;u{this.bjsAMMO.destroy(e)})),e._pluginData.toDispose=[]))}generateJoint(e){const t=e.mainImpostor.physicsBody,i=e.connectedImpostor.physicsBody;if(!t||!i)return;const n=e.joint.jointData;let s;switch(n.mainPivot||(n.mainPivot=new o.P(0,0,0)),n.connectedPivot||(n.connectedPivot=new o.P(0,0,0)),e.joint.type){case st.DistanceJoint:{const e=n.maxDistance;e&&(n.mainPivot=new o.P(0,-e/2,0),n.connectedPivot=new o.P(0,e/2,0)),s=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(n.mainPivot.x,n.mainPivot.y,n.mainPivot.z),new this.bjsAMMO.btVector3(n.connectedPivot.x,n.connectedPivot.y,n.connectedPivot.z));break}case st.HingeJoint:{n.mainAxis||(n.mainAxis=new o.P(0,0,0)),n.connectedAxis||(n.connectedAxis=new o.P(0,0,0));const e=new this.bjsAMMO.btVector3(n.mainAxis.x,n.mainAxis.y,n.mainAxis.z),r=new this.bjsAMMO.btVector3(n.connectedAxis.x,n.connectedAxis.y,n.connectedAxis.z);s=new this.bjsAMMO.btHingeConstraint(t,i,new this.bjsAMMO.btVector3(n.mainPivot.x,n.mainPivot.y,n.mainPivot.z),new this.bjsAMMO.btVector3(n.connectedPivot.x,n.connectedPivot.y,n.connectedPivot.z),e,r);break}case st.BallAndSocketJoint:s=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(n.mainPivot.x,n.mainPivot.y,n.mainPivot.z),new this.bjsAMMO.btVector3(n.connectedPivot.x,n.connectedPivot.y,n.connectedPivot.z));break;default:p.Y.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint"),s=new this.bjsAMMO.btPoint2PointConstraint(t,i,new this.bjsAMMO.btVector3(n.mainPivot.x,n.mainPivot.y,n.mainPivot.z),new this.bjsAMMO.btVector3(n.connectedPivot.x,n.connectedPivot.y,n.connectedPivot.z))}this.world.addConstraint(s,!e.joint.jointData.collision),e.joint.physicsJoint=s}removeJoint(e){this.world&&this.world.removeConstraint(e.joint.physicsJoint)}_addMeshVerts(e,t,i){let n=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s=i.getIndices();s||(s=[]);let r,a=i.getVerticesData(ne.o.PositionKind);if(a||(a=[]),t&&t!==i){let e;e=t.rotationQuaternion?t.rotationQuaternion:t.rotation?o._f.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):o._f.Identity();o.y3.Compose(o.P.One(),e,t.position).invertToRef(this._tmpMatrix);r=i.computeWorldMatrix(!1).multiply(this._tmpMatrix)}else o.y3.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),r=this._tmpMatrix;const l=s.length/3;for(let t=0;t{n+=this._addMeshVerts(e,t,i)}))}return n}_softVertexData(e){const t=e.object;if(t&&t.getIndices&&t.getWorldMatrix&&t.getChildMeshes){let e=t.getIndices();e||(e=[]);let i=t.getVerticesData(ne.o.PositionKind);i||(i=[]);let n=t.getVerticesData(ne.o.NormalKind);n||(n=[]),t.computeWorldMatrix(!1);const s=[],r=[];for(let l=0;le*e)).reduce(((e,t)=>e+t)))t=s.length,i=t/3-1,this._tmpAmmoVectorA.setValue(s[0],s[1],s[2]),this._tmpAmmoVectorB.setValue(s[t-3],s[t-2],s[t-1]);else{e._isFromLine=!1;const n=e.getParam("path");if(null===e.getParam("shape"))return p.Y.Warn("No shape available for extruded mesh"),new this.bjsAMMO.btCompoundShape;t=n.length,i=t-1,this._tmpAmmoVectorA.setValue(n[0].x,n[0].y,n[0].z),this._tmpAmmoVectorB.setValue(n[t-1].x,n[t-1].y,n[t-1].z)}e.segments=i;let o=e.getParam("fixedPoints");o=o>3?3:o;const a=(new this.bjsAMMO.btSoftBodyHelpers).CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,i-1,o);return a.get_m_cfg().set_collisions(17),a}_createCustom(e){let t=null;return this.onCreateCustomShape&&(t=this.onCreateCustomShape(e)),null==t&&(t=new this.bjsAMMO.btCompoundShape),t}_addHullVerts(e,t,i){let n=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s=i.getIndices();s||(s=[]);let r=i.getVerticesData(ne.o.PositionKind);r||(r=[]),i.computeWorldMatrix(!1);const a=s.length/3;for(let t=0;t{n+=this._addHullVerts(e,t,i)}))}return n}_createShape(e,t=!1){const i=e.object;let n;const s=e.getObjectExtents();if(!t){const t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[];n=new this.bjsAMMO.btCompoundShape;let i=0;if(t.forEach((e=>{const t=e.getPhysicsImpostor();if(t){if(t.type==rt.MeshImpostor)throw"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";const s=this._createShape(t),r=e.parent.getWorldMatrix().clone(),a=new o.P;r.decompose(a),this._tmpAmmoTransform.getOrigin().setValue(e.position.x*a.x,e.position.y*a.y,e.position.z*a.z),this._tmpAmmoQuaternion.setValue(e.rotationQuaternion.x,e.rotationQuaternion.y,e.rotationQuaternion.z,e.rotationQuaternion.w),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),n.addChildShape(this._tmpAmmoTransform,s),t.dispose(),i++}})),i>0){if(e.type!=rt.NoImpostor){const t=this._createShape(e,!0);t&&(this._tmpAmmoTransform.getOrigin().setValue(0,0,0),this._tmpAmmoQuaternion.setValue(0,0,0,1),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),n.addChildShape(this._tmpAmmoTransform,t))}return n}this.bjsAMMO.destroy(n),n=null}switch(e.type){case rt.SphereImpostor:if(S.R.WithinEpsilon(s.x,s.y,1e-4)&&S.R.WithinEpsilon(s.x,s.z,1e-4))n=new this.bjsAMMO.btSphereShape(s.x/2);else{const e=[new this.bjsAMMO.btVector3(0,0,0)],t=[1];n=new this.bjsAMMO.btMultiSphereShape(e,t,1),n.setLocalScaling(new this.bjsAMMO.btVector3(s.x/2,s.y/2,s.z/2))}break;case rt.CapsuleImpostor:{const e=s.x/2;n=new this.bjsAMMO.btCapsuleShape(e,s.y-2*e)}break;case rt.CylinderImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),n=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case rt.PlaneImpostor:case rt.BoxImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),n=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case rt.MeshImpostor:if(0==e.getParam("mass")){if(this.onCreateCustomMeshImpostor)n=this.onCreateCustomMeshImpostor(e);else{const t=new this.bjsAMMO.btTriangleMesh;e._pluginData.toDispose.push(t);const s=this._addMeshVerts(t,i,i);n=0==s?new this.bjsAMMO.btCompoundShape:new this.bjsAMMO.btBvhTriangleMeshShape(t)}break}case rt.ConvexHullImpostor:if(this.onCreateCustomConvexHullImpostor)n=this.onCreateCustomConvexHullImpostor(e);else{const t=new this.bjsAMMO.btConvexHullShape;0==this._addHullVerts(t,i,i)?(e._pluginData.toDispose.push(t),n=new this.bjsAMMO.btCompoundShape):n=t}break;case rt.NoImpostor:n=new this.bjsAMMO.btSphereShape(s.x/2);break;case rt.CustomImpostor:n=this._createCustom(e);break;case rt.SoftbodyImpostor:n=this._createSoftbody(e);break;case rt.ClothImpostor:n=this._createCloth(e);break;case rt.RopeImpostor:n=this._createRope(e);break;default:p.Y.Warn("The impostor type is not currently supported by the ammo plugin.")}return n}setTransformationFromPhysicsBody(e){e.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.object.position.set(this._tmpAmmoTransform.getOrigin().x(),this._tmpAmmoTransform.getOrigin().y(),this._tmpAmmoTransform.getOrigin().z()),e.object.rotationQuaternion?e.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()):e.object.rotation&&(this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()),this._tmpQuaternion.toEulerAnglesToRef(e.object.rotation))}setPhysicsBodyTransformation(e,t,i){const n=e.physicsBody.getWorldTransform();if(Math.abs(n.getOrigin().x()-t.x)>k.kn||Math.abs(n.getOrigin().y()-t.y)>k.kn||Math.abs(n.getOrigin().z()-t.z)>k.kn||Math.abs(n.getRotation().x()-i.x)>k.kn||Math.abs(n.getRotation().y()-i.y)>k.kn||Math.abs(n.getRotation().z()-i.z)>k.kn||Math.abs(n.getRotation().w()-i.w)>k.kn)if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),n.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),n.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(n),0==e.mass){const t=e.physicsBody.getMotionState();t&&t.setWorldTransform(n)}else e.physicsBody.activate()}isSupported(){return void 0!==this.bjsAMMO}setLinearVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.linearVelocity(this._tmpAmmoVectorA):e.physicsBody.setLinearVelocity(this._tmpAmmoVectorA)}setAngularVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.angularVelocity(this._tmpAmmoVectorA):e.physicsBody.setAngularVelocity(this._tmpAmmoVectorA)}getLinearVelocity(e){let t;if(t=e.soft?e.physicsBody.linearVelocity():e.physicsBody.getLinearVelocity(),!t)return null;const i=new o.P(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}getAngularVelocity(e){let t;if(t=e.soft?e.physicsBody.angularVelocity():e.physicsBody.getAngularVelocity(),!t)return null;const i=new o.P(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}setBodyMass(e,t){e.soft?e.physicsBody.setTotalMass(t,!1):e.physicsBody.setMassProps(t),e._pluginData.mass=t}getBodyMass(e){return e._pluginData.mass||0}getBodyFriction(e){return e._pluginData.friction||0}setBodyFriction(e,t){e.soft?e.physicsBody.get_m_cfg().set_kDF(t):e.physicsBody.setFriction(t),e._pluginData.friction=t}getBodyRestitution(e){return e._pluginData.restitution||0}setBodyRestitution(e,t){e.physicsBody.setRestitution(t),e._pluginData.restitution=t}getBodyPressure(e){return e.soft?e._pluginData.pressure||0:(p.Y.Warn("Pressure is not a property of a rigid body"),0)}setBodyPressure(e,t){e.soft?e.type===rt.SoftbodyImpostor?(e.physicsBody.get_m_cfg().set_kPR(t),e._pluginData.pressure=t):(e.physicsBody.get_m_cfg().set_kPR(0),e._pluginData.pressure=0):p.Y.Warn("Pressure can only be applied to a softbody")}getBodyStiffness(e){return e.soft?e._pluginData.stiffness||0:(p.Y.Warn("Stiffness is not a property of a rigid body"),0)}setBodyStiffness(e,t){e.soft?(t=(t=t<0?0:t)>1?1:t,e.physicsBody.get_m_materials().at(0).set_m_kLST(t),e._pluginData.stiffness=t):p.Y.Warn("Stiffness cannot be applied to a rigid body")}getBodyVelocityIterations(e){return e.soft?e._pluginData.velocityIterations||0:(p.Y.Warn("Velocity iterations is not a property of a rigid body"),0)}setBodyVelocityIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_viterations(t),e._pluginData.velocityIterations=t):p.Y.Warn("Velocity iterations cannot be applied to a rigid body")}getBodyPositionIterations(e){return e.soft?e._pluginData.positionIterations||0:(p.Y.Warn("Position iterations is not a property of a rigid body"),0)}setBodyPositionIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_piterations(t),e._pluginData.positionIterations=t):p.Y.Warn("Position iterations cannot be applied to a rigid body")}appendAnchor(e,t,i,n,s=1,r=!1){const o=e.segments,a=Math.round((o-1)*i)+o*(o-1-Math.round((o-1)*n));e.physicsBody.appendAnchor(a,t.physicsBody,r,s)}appendHook(e,t,i,n=1,s=!1){const r=Math.round(e.segments*i);e.physicsBody.appendAnchor(r,t.physicsBody,s,n)}sleepBody(e){e.physicsBody.forceActivationState(0)}wakeUpBody(e){e.physicsBody.activate()}updateDistanceJoint(){p.Y.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")}setMotor(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)}setLimit(){p.Y.Warn("setLimit is not currently supported by the Ammo physics plugin")}syncMeshWithImpostor(e,t){t.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.position.x=this._tmpAmmoTransform.getOrigin().x(),e.position.y=this._tmpAmmoTransform.getOrigin().y(),e.position.z=this._tmpAmmoTransform.getOrigin().z(),e.rotationQuaternion&&(e.rotationQuaternion.x=this._tmpAmmoTransform.getRotation().x(),e.rotationQuaternion.y=this._tmpAmmoTransform.getRotation().y(),e.rotationQuaternion.z=this._tmpAmmoTransform.getRotation().z(),e.rotationQuaternion.w=this._tmpAmmoTransform.getRotation().w())}getRadius(e){return e.getObjectExtents().x/2}getBoxSizeToRef(e,t){const i=e.getObjectExtents();t.x=i.x,t.y=i.y,t.z=i.z}dispose(){this.bjsAMMO.destroy(this.world),this.bjsAMMO.destroy(this._solver),this.bjsAMMO.destroy(this._overlappingPairCache),this.bjsAMMO.destroy(this._dispatcher),this.bjsAMMO.destroy(this._collisionConfiguration),this.bjsAMMO.destroy(this._tmpAmmoVectorA),this.bjsAMMO.destroy(this._tmpAmmoVectorB),this.bjsAMMO.destroy(this._tmpAmmoVectorC),this.bjsAMMO.destroy(this._tmpAmmoTransform),this.bjsAMMO.destroy(this._tmpAmmoQuaternion),this.bjsAMMO.destroy(this._tmpAmmoConcreteContactResultCallback),this.world=null}raycast(e,t){return this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._tmpAmmoVectorRCA=new this.bjsAMMO.btVector3(e.x,e.y,e.z),this._tmpAmmoVectorRCB=new this.bjsAMMO.btVector3(t.x,t.y,t.z);const n=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,n),i.reset(e,t),n.hasHit()&&(i.setHitData({x:n.get_m_hitNormalWorld().x(),y:n.get_m_hitNormalWorld().y(),z:n.get_m_hitNormalWorld().z()},{x:n.get_m_hitPointWorld().x(),y:n.get_m_hitPointWorld().y(),z:n.get_m_hitPointWorld().z()}),i.calculateHitDistance()),this.bjsAMMO.destroy(n),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB)}}sv._DISABLE_COLLISION_FLAG=4,sv._KINEMATIC_FLAG=2,sv._DISABLE_DEACTIVATION_FLAG=4,n.p.prototype.removeReflectionProbe=function(e){if(!this.reflectionProbes)return-1;const t=this.reflectionProbes.indexOf(e);return-1!==t&&this.reflectionProbes.splice(t,1),t},n.p.prototype.addReflectionProbe=function(e){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(e)};class rv{constructor(e,t,i,n=!0,s=!1,r=!1){if(this.name=e,this._viewMatrix=o.y3.Identity(),this._target=o.P.Zero(),this._add=o.P.Zero(),this._invertYAxis=!1,this.position=o.P.Zero(),this.metadata=null,this._parentContainer=null,this._scene=i,i.getEngine().supportsUniformBuffers){this._sceneUBOs=[];for(let t=0;t<6;++t)this._sceneUBOs.push(i.createSceneUniformBuffer(`Scene for Reflection Probe (name "${e}") face #${t}`))}this._scene.reflectionProbes||(this._scene.reflectionProbes=new Array),this._scene.reflectionProbes.push(this);let a=0;if(s){const e=this._scene.getEngine().getCaps();e.textureHalfFloatRender?a=2:e.textureFloatRender&&(a=1)}this._renderTargetTexture=new Ci(e,t,i,n,!0,a,!0),this._renderTargetTexture.gammaSpace=!r,this._renderTargetTexture.invertZ=i.useRightHandedSystem;const l=i.getEngine().useReverseDepthBuffer;let h;this._renderTargetTexture.onBeforeRenderObservable.add((e=>{switch(this._sceneUBOs&&(i.setSceneUniformBuffer(this._sceneUBOs[e]),i.getSceneUniformBuffer().unbindEffect()),e){case 0:this._add.copyFromFloats(1,0,0);break;case 1:this._add.copyFromFloats(-1,0,0);break;case 2:this._add.copyFromFloats(0,this._invertYAxis?1:-1,0);break;case 3:this._add.copyFromFloats(0,this._invertYAxis?-1:1,0);break;case 4:this._add.copyFromFloats(0,0,i.useRightHandedSystem?-1:1);break;case 5:this._add.copyFromFloats(0,0,i.useRightHandedSystem?1:-1)}this._attachedMesh&&this.position.copyFrom(this._attachedMesh.getAbsolutePosition()),this.position.addToRef(this._add,this._target);const t=i.useRightHandedSystem?o.y3.LookAtRHToRef:o.y3.LookAtLHToRef,n=i.useRightHandedSystem?o.y3.PerspectiveFovRH:o.y3.PerspectiveFovLH;t(this.position,this._target,o.P.Up(),this._viewMatrix),i.activeCamera&&(this._projectionMatrix=n(Math.PI/2,1,l?i.activeCamera.maxZ:i.activeCamera.minZ,l?i.activeCamera.minZ:i.activeCamera.maxZ,this._scene.getEngine().isNDCHalfZRange),i.setTransformMatrix(this._viewMatrix,this._projectionMatrix),i.activeCamera.isRigCamera&&!this._renderTargetTexture.activeCamera&&(this._renderTargetTexture.activeCamera=i.activeCamera.rigParent||null)),i._forcedViewPosition=this.position})),this._renderTargetTexture.onBeforeBindObservable.add((()=>{var t,n;this._currentSceneUBO=i.getSceneUniformBuffer(),null===(n=(t=i.getEngine())._debugPushGroup)||void 0===n||n.call(t,`reflection probe generation for ${e}`,1),h=this._scene.imageProcessingConfiguration.applyByPostProcess,r&&(i.imageProcessingConfiguration.applyByPostProcess=!0)})),this._renderTargetTexture.onAfterUnbindObservable.add((()=>{var e,t;i.imageProcessingConfiguration.applyByPostProcess=h,i._forcedViewPosition=null,this._sceneUBOs&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(!0),null===(t=(e=i.getEngine())._debugPopGroup)||void 0===t||t.call(e,1)}))}get samples(){return this._renderTargetTexture.samples}set samples(e){this._renderTargetTexture.samples=e}get refreshRate(){return this._renderTargetTexture.refreshRate}set refreshRate(e){this._renderTargetTexture.refreshRate=e}getScene(){return this._scene}get cubeTexture(){return this._renderTargetTexture}get renderList(){return this._renderTargetTexture.renderList}attachToMesh(e){this._attachedMesh=e}setRenderingAutoClearDepthStencil(e,t){this._renderTargetTexture.setRenderingAutoClearDepthStencil(e,t)}dispose(){const e=this._scene.reflectionProbes.indexOf(this);if(-1!==e&&this._scene.reflectionProbes.splice(e,1),this._parentContainer){const e=this._parentContainer.reflectionProbes.indexOf(this);e>-1&&this._parentContainer.reflectionProbes.splice(e,1),this._parentContainer=null}if(this._renderTargetTexture&&(this._renderTargetTexture.dispose(),this._renderTargetTexture=null),this._sceneUBOs){for(const e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}toString(e){let t="Name: "+this.name;return e&&(t+=", position: "+this.position.toString(),this._attachedMesh&&(t+=", attached mesh: "+this._attachedMesh.name)),t}getClassName(){return"ReflectionProbe"}serialize(){const e=E.p4.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e.metadata=this.metadata,e}static Parse(e,t,i){let n=null;if(t.reflectionProbes)for(let s=0;sn||new rv(e.name,e.renderTargetSize,t,e._generateMipMaps)),e,t,i),n.cubeTexture._waitingRenderList=e.renderList,e._attachedMesh&&n.attachToMesh(t.getMeshById(e._attachedMesh)),e.metadata&&(n.metadata=e.metadata),n}}(0,oe.gn)([(0,E.RR)()],rv.prototype,"_attachedMesh",void 0),(0,oe.gn)([(0,E.hd)()],rv.prototype,"position",void 0);class ov{}ov.LoaderInjectedPhysicsEngine=void 0;let av={},lv={};const hv=(e,t,i,n)=>{if(!t.materials)return null;for(let s=0,r=t.materials.length;s{for(const n in t)if(e.name===t[n])return i.push(e.id),!0;return void 0!==e.parentId&&-1!==i.indexOf(e.parentId)&&(i.push(e.id),!0)},dv=(e,t)=>e+" of "+(t?t.file+" from "+t.name+" version: "+t.version+", exporter version: "+t.exporter_version:"unknown"),uv=(e,t)=>{const i=t;if(t._waitingData.lods){if(t._waitingData.lods.ids&&t._waitingData.lods.ids.length>0){const n=t._waitingData.lods.ids,s=i.isEnabled(!1);if(t._waitingData.lods.distances){const r=t._waitingData.lods.distances;if(r.length>=n.length){const t=r.length>n.length?r[r.length-1]:0;i.setEnabled(!1);for(let s=0;s0&&i.addLODLevel(t,null),!0===s&&i.setEnabled(!0)}else se.w1.Warn("Invalid level of detail distances for "+t.name)}}t._waitingData.lods=null}},pv=(e,t,i)=>{if("number"!=typeof e){const n=i.getLastEntryById(e);if(n&&null!=t){return n.instances[parseInt(t)]}return n}const n=av[e];if(n&&null!=t){return n.instances[parseInt(t)]}return n},fv=(e,t)=>"number"!=typeof e?t.getLastMaterialById(e,!0):lv[e],_v=(e,t,i,s,r=!1)=>{const o=new pe(e);let a="importScene has failed JSON parse";try{var h=JSON.parse(t);a="";const s=ht.loggingLevel===ht.DETAILED_LOGGING;let r,c;if(void 0!==h.environmentTexture&&null!==h.environmentTexture){const t=void 0===h.isPBR||h.isPBR;if(h.environmentTextureType&&"BABYLON.HDRCubeTexture"===h.environmentTextureType){const n=h.environmentTextureSize?h.environmentTextureSize:128,s=new $g((h.environmentTexture.match(/https?:\/\//g)?"":i)+h.environmentTexture,e,n,!0,!t,void 0,h.environmentTexturePrefilterOnLoad);h.environmentTextureRotationY&&(s.rotationY=h.environmentTextureRotationY),e.environmentTexture=s}else if("object"==typeof h.environmentTexture){const t=yp.Parse(h.environmentTexture,e,i);e.environmentTexture=t}else if(h.environmentTexture.endsWith(".env")){const t=new yp((h.environmentTexture.match(/https?:\/\//g)?"":i)+h.environmentTexture,e,h.environmentTextureForcedExtension);h.environmentTextureRotationY&&(t.rotationY=h.environmentTextureRotationY),e.environmentTexture=t}else{const t=yp.CreateFromPrefilteredData((h.environmentTexture.match(/https?:\/\//g)?"":i)+h.environmentTexture,e,h.environmentTextureForcedExtension);h.environmentTextureRotationY&&(t.rotationY=h.environmentTextureRotationY),e.environmentTexture=t}if(!0===h.createDefaultSkybox){const i=void 0!==e.activeCamera&&null!==e.activeCamera?(e.activeCamera.maxZ-e.activeCamera.minZ)/2:1e3,n=h.skyboxBlurLevel||0;e.createDefaultSkybox(e.environmentTexture,t,i,n)}o.environmentTexture=e.environmentTexture}if(void 0!==h.environmentIntensity&&null!==h.environmentIntensity&&(e.environmentIntensity=h.environmentIntensity),void 0!==h.lights&&null!==h.lights)for(r=0,c=h.lights.length;r{-1==o.textures.indexOf(e)&&(o.textures.push(e),e._parentContainer=o)}))}}if(void 0!==h.multiMaterials&&null!==h.multiMaterials)for(r=0,c=h.multiMaterials.length;r{-1==o.textures.indexOf(e)&&(o.textures.push(e),e._parentContainer=o)}))}if(void 0!==h.morphTargetManagers&&null!==h.morphTargetManagers)for(const t of h.morphTargetManagers){const i=Jg.Parse(t,e);o.morphTargetManagers.push(i),i._parentContainer=o}if(void 0!==h.skeletons&&null!==h.skeletons)for(r=0,c=h.skeletons.length;r{e&&(o.geometries.push(e),e._parentContainer=o)}))}if(void 0!==h.transformNodes&&null!==h.transformNodes)for(r=0,c=h.transformNodes.length;r{t._waitingSubMaterialsUniqueIds.forEach((i=>{t.subMaterials.push(fv(i,e))})),t._waitingSubMaterialsUniqueIds=[]})),e.meshes.forEach((t=>{null!==t._waitingMaterialId&&(t.material=fv(t._waitingMaterialId,e),t._waitingMaterialId=null)})),r=0,c=e.skeletons.length;r{if(t._waitingTransformNodeId){const i=e.getLastEntryById(t._waitingTransformNodeId);i&&t.linkTransformNode(i),t._waitingTransformNodeId=null}})),t._hasWaitingData=null)}for(r=0,c=e.meshes.length;r0){for(let i=0;i0){for(let i=0;i{e._loadedUniqueId=""})),n.p.Parse(h,e,o,i),r=0,c=e.meshes.length;r-1!==e.indexOf("babylon"),importMesh:(e,t,i,s,r,o,a,l)=>{var h;let c="importMesh has failed JSON parse";try{var d=JSON.parse(i);c="";const l=ht.loggingLevel===ht.DETAILED_LOGGING;e?Array.isArray(e)||(e=[e]):e=null;const u=new Array,f=new Map,_=[];if(void 0!==d.transformNodes&&null!==d.transformNodes)for(let e=0,i=d.transformNodes.length;e{!0!==e&&d.geometries[i]&&Array.isArray(d.geometries[i])&&d.geometries[i].forEach((n=>{if(n.id===_.geometryId){if("vertexData"===i)Gg.Z.Parse(n,t,s);e=!0}}))})),!1===e&&p.Y.Warn("Geometry not found for mesh "+_.id)}if(_.materialUniqueId||_.materialId){const e=_.materialUniqueId?o:n;let i=-1!==e.indexOf(_.materialUniqueId||_.materialId);if(!1===i&&void 0!==d.multiMaterials&&null!==d.multiMaterials){const n=(i,n)=>{e.push(i);const r=hv(n,d,t,s);r&&r.material&&(lv[r.parsedMaterial.uniqueId||r.parsedMaterial.id]=r.material,c+="\n\tMaterial "+r.material.toString(l))};for(let s=0,r=d.multiMaterials.length;sn(e,(t=>t.uniqueId===e)))):r.materials.forEach((e=>n(e,(t=>t.id===e)))),e.push(r.uniqueId||r.id);const s=zg.G.ParseMultiMaterial(r,t);lv[r.uniqueId||r.id]=s,s&&(i=!0,c+="\n\tMulti-Material "+s.toString(l));break}}}if(!1===i){e.push(_.materialUniqueId||_.materialId);const i=hv((e=>_.materialUniqueId&&e.uniqueId===_.materialUniqueId||e.id===_.materialId),d,t,s);i&&i.material?(lv[i.parsedMaterial.uniqueId||i.parsedMaterial.id]=i.material,c+="\n\tMaterial "+i.material.toString(l)):p.Y.Warn("Material not found for mesh "+_.id)}}if(_.skeletonId>-1&&void 0!==d.skeletons&&null!==d.skeletons){if(!(i.indexOf(_.skeletonId)>-1))for(let e=0,n=d.skeletons.length;e-1&&void 0!==d.morphTargetManagers&&null!==d.morphTargetManagers){if(!(m.indexOf(_.morphTargetManagerId)>-1))for(let e=0,i=d.morphTargetManagers.length;e{e._waitingSubMaterialsUniqueIds.forEach((i=>{e.subMaterials.push(fv(i,t))})),e._waitingSubMaterialsUniqueIds=[]})),t.meshes.forEach((e=>{null!==e._waitingMaterialId&&(e.material=fv(e._waitingMaterialId,t),e._waitingMaterialId=null)}));for(let e=0,s=t.transformNodes.length;e-1&&_.splice(e,1)}g._waitingParentId=null}g._waitingData.lods&&uv(t,g)}for(const e of _)e.dispose();for(let e=0,s=t.skeletons.length;e{if(e._waitingTransformNodeId){const i=t.getLastEntryById(e._waitingTransformNodeId);i&&e.linkTransformNode(i),e._waitingTransformNodeId=null}})),i._hasWaitingData=null)}for(let e=0,s=t.meshes.length;e{e._loadedUniqueId=""})),!0}catch(u){const e=dv("importMesh",d?d.producer:"Unknown")+c;if(!l)throw p.Y.Log(e),u;l(e,u)}finally{null!==c&&ht.loggingLevel!==ht.NO_LOGGING&&p.Y.Log(dv("importMesh",d?d.producer:"Unknown")+(ht.loggingLevel!==ht.MINIMAL_LOGGING?c:"")),lv={}}return!1},load:(e,t,i,n)=>{let s="importScene has failed JSON parse";try{var r=JSON.parse(t);if(s="",void 0!==r.useDelayedTextureLoading&&null!==r.useDelayedTextureLoading&&(e.useDelayedTextureLoading=r.useDelayedTextureLoading&&!ht.ForceFullSceneLoadingForIncremental),void 0!==r.autoClear&&null!==r.autoClear&&(e.autoClear=r.autoClear),void 0!==r.clearColor&&null!==r.clearColor&&(e.clearColor=a.HE.FromArray(r.clearColor)),void 0!==r.ambientColor&&null!==r.ambientColor&&(e.ambientColor=a.Wo.FromArray(r.ambientColor)),void 0!==r.gravity&&null!==r.gravity&&(e.gravity=o.P.FromArray(r.gravity)),void 0!==r.useRightHandedSystem&&(e.useRightHandedSystem=!!r.useRightHandedSystem),r.fogMode&&0!==r.fogMode)switch(e.fogMode=r.fogMode,e.fogColor=a.Wo.FromArray(r.fogColor),e.fogStart=r.fogStart,e.fogEnd=r.fogEnd,e.fogDensity=r.fogDensity,s+="\tFog mode for scene: ",e.fogMode){case 1:s+="exp\n";break;case 2:s+="exp2\n";break;case 3:s+="linear\n"}if(r.physicsEnabled){let t;"cannon"===r.physicsEngine||r.physicsEngine===iv.name?t=new iv(void 0,void 0,ov.LoaderInjectedPhysicsEngine):"oimo"===r.physicsEngine||r.physicsEngine===nv.name?t=new nv(void 0,ov.LoaderInjectedPhysicsEngine):"ammo"!==r.physicsEngine&&r.physicsEngine!==sv.name||(t=new sv(void 0,ov.LoaderInjectedPhysicsEngine,void 0)),s="\tPhysics engine "+(r.physicsEngine?r.physicsEngine:"oimo")+" enabled\n";const i=r.physicsGravity?o.P.FromArray(r.physicsGravity):null;e.enablePhysics(i,t)}void 0!==r.metadata&&null!==r.metadata&&(e.metadata=r.metadata),void 0!==r.collisionsEnabled&&null!==r.collisionsEnabled&&(e.collisionsEnabled=r.collisionsEnabled);return!!_v(e,t,i,n,!0)&&(r.autoAnimate&&e.beginAnimation(e,r.autoAnimateFrom,r.autoAnimateTo,r.autoAnimateLoop,r.autoAnimateSpeed||1),void 0!==r.activeCameraID&&null!==r.activeCameraID&&e.setActiveCameraById(r.activeCameraID),!0)}catch(l){const e=dv("importScene",r?r.producer:"Unknown")+s;if(!n)throw p.Y.Log(e),l;n(e,l)}finally{null!==s&&ht.loggingLevel!==ht.NO_LOGGING&&p.Y.Log(dv("importScene",r?r.producer:"Unknown")+(ht.loggingLevel!==ht.MINIMAL_LOGGING?s:""))}return!1},loadAssetContainer:(e,t,i,n)=>_v(e,t,i,n)});i(4839);class mv{get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,fe.D.MarkAllMaterialsAsDirty(20))}constructor(e={}){this._isEnabled=!0,this.bias=void 0===e.bias?0:e.bias,this.power=void 0===e.power?1:e.power,this.leftColor=e.leftColor||a.Wo.White(),this.rightColor=e.rightColor||a.Wo.Black(),!1===e.isEnabled&&(this.isEnabled=!1)}clone(){const e=new mv;return g.j.DeepCopy(this,e),e}equals(e){return e&&this.bias===e.bias&&this.power===e.power&&this.leftColor.equals(e.leftColor)&&this.rightColor.equals(e.rightColor)&&this.isEnabled===e.isEnabled}serialize(){return{isEnabled:this.isEnabled,leftColor:this.leftColor.asArray(),rightColor:this.rightColor.asArray(),bias:this.bias,power:this.power}}static Parse(e){return new mv({isEnabled:e.isEnabled,leftColor:a.Wo.FromArray(e.leftColor),rightColor:a.Wo.FromArray(e.rightColor),bias:e.bias,power:e.power||1})}}E.p4._FresnelParametersParser=mv.Parse;class gv extends M_{get doubleSided(){return this._twoSidedLighting}set doubleSided(e){this._twoSidedLighting!==e&&(this._twoSidedLighting=e,this.backFaceCulling=!e,this._markAllSubMeshesAsTexturesDirty())}constructor(e,t){super(e,t),this.maxSimultaneousLights=4,this.disableLighting=!1,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.emissiveColor=new a.Wo(0,0,0),this.occlusionStrength=1,this.useLightmapAsShadowmap=!1,this._useAlphaFromAlbedoTexture=!0,this._useAmbientInGrayScale=!0}getClassName(){return"PBRBaseSimpleMaterial"}}(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsLightsDirty")],gv.prototype,"maxSimultaneousLights",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsLightsDirty")],gv.prototype,"disableLighting",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],gv.prototype,"environmentTexture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],gv.prototype,"invertNormalMapX",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],gv.prototype,"invertNormalMapY",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],gv.prototype,"normalTexture",void 0),(0,oe.gn)([(0,E.n9)("emissive"),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],gv.prototype,"emissiveColor",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],gv.prototype,"emissiveTexture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],gv.prototype,"occlusionStrength",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],gv.prototype,"occlusionTexture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],gv.prototype,"alphaCutOff",void 0),(0,oe.gn)([(0,E.qC)()],gv.prototype,"doubleSided",null),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty",null)],gv.prototype,"lightmapTexture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],gv.prototype,"useLightmapAsShadowmap",void 0);class vv extends gv{constructor(e,t){super(e,t),this._useRoughnessFromMetallicTextureAlpha=!1,this._useRoughnessFromMetallicTextureGreen=!0,this._useMetallnessFromMetallicTextureBlue=!0,this.metallic=1,this.roughness=1}getClassName(){return"PBRMetallicRoughnessMaterial"}clone(e){const t=E.p4.Clone((()=>new vv(e,this.getScene())),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){const e=E.p4.Serialize(this);return e.customType="BABYLON.PBRMetallicRoughnessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const n=E.p4.Parse((()=>new vv(e.name,t)),e,t,i);return e.clearCoat&&n.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&n.anisotropy.parse(e.anisotropy,t,i),e.brdf&&n.brdf.parse(e.brdf,t,i),e.sheen&&n.sheen.parse(e.sheen,t,i),e.subSurface&&n.subSurface.parse(e.subSurface,t,i),e.iridescence&&n.iridescence.parse(e.iridescence,t,i),n}}(0,oe.gn)([(0,E.n9)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty","_albedoColor")],vv.prototype,"baseColor",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],vv.prototype,"baseTexture",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],vv.prototype,"metallic",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],vv.prototype,"roughness",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],vv.prototype,"metallicRoughnessTexture",void 0),(0,l.H)("BABYLON.PBRMetallicRoughnessMaterial",vv);class Tv extends gv{get useMicroSurfaceFromReflectivityMapAlpha(){return this._useMicroSurfaceFromReflectivityMapAlpha}constructor(e,t){super(e,t),this._useMicroSurfaceFromReflectivityMapAlpha=!0}getClassName(){return"PBRSpecularGlossinessMaterial"}clone(e){const t=E.p4.Clone((()=>new Tv(e,this.getScene())),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){const e=E.p4.Serialize(this);return e.customType="BABYLON.PBRSpecularGlossinessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){const n=E.p4.Parse((()=>new Tv(e.name,t)),e,t,i);return e.clearCoat&&n.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&n.anisotropy.parse(e.anisotropy,t,i),e.brdf&&n.brdf.parse(e.brdf,t,i),e.sheen&&n.sheen.parse(e.sheen,t,i),e.subSurface&&n.subSurface.parse(e.subSurface,t,i),e.iridescence&&n.iridescence.parse(e.iridescence,t,i),n}}(0,oe.gn)([(0,E.n9)("diffuse"),(0,E.wz)("_markAllSubMeshesAsTexturesDirty","_albedoColor")],Tv.prototype,"diffuseColor",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],Tv.prototype,"diffuseTexture",void 0),(0,oe.gn)([(0,E.n9)("specular"),(0,E.wz)("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],Tv.prototype,"specularColor",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty","_microSurface")],Tv.prototype,"glossiness",void 0),(0,oe.gn)([(0,E.oU)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],Tv.prototype,"specularGlossinessTexture",void 0),(0,l.H)("BABYLON.PBRSpecularGlossinessMaterial",Tv);class Sv extends Re{constructor(e,t,i=null){if(super(t),e)if(this._textureMatrix=o.y3.Identity(),this.name=e,this.url=e,this._onLoad=i,this._texture=this._getFromCache(e,!0),this._texture)this._triggerOnLoad();else{const e=this.getScene();e&&e.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture()}}_triggerOnLoad(){this._onLoad&&this._onLoad()}getTextureMatrix(){return this._textureMatrix}_load3dlTexture(){const e=this._getEngine();let t;t=e._features.support3DTextures?e.createRawTexture3D(null,1,1,1,5,!1,!1,2,null,0):e.createRawTexture(null,1,1,5,!1,!1,2,null,0),this._texture=t,this._texture.isReady=!1,this.isCube=!1,this.is3D=e._features.support3DTextures,this.wrapU=0,this.wrapV=0,this.wrapR=0,this.anisotropicFilteringLevel=1;const i=i=>{if("string"!=typeof i)return;let n,s=null,r=null;const o=i.split("\n");let a=0,l=0,h=0,c=0,d=0;for(let e=0;e0&&(e+1)%4==0)s[e]=255;else{const t=r[e];s[e]=t/d*255}t.is3D?(t.updateSize(a,a,a),e.updateRawTexture3D(t,s,5,!1)):(t.updateSize(a*a,a),e.updateRawTexture(t,s,5,!1)),t.isReady=!0,this._triggerOnLoad()},n=this.getScene();return n?n._loadFile(this.url,i):e._loadFile(this.url,i),this._texture}_loadTexture(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this._load3dlTexture()}clone(){const e=new Sv(this.url,this.getScene()||this._getEngine());return e.level=this.level,e}delayLoad(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,!0),this._texture||this._loadTexture())}static Parse(e,t){let i=null;return e.name&&!e.isRenderTarget&&(i=new Sv(e.name,t),i.name=e.name,i.level=e.level),i}serialize(){if(!this.name)return null;const e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e}}Sv._NoneEmptyLineRegex=/\S+/,(0,l.H)("BABYLON.ColorGradingTexture",Sv);class Ev extends Re{constructor(e,t,i,n=!1,s=!0,r=null,o=null,a=!1){if(super(t),this._onLoad=null,this._onError=null,!e)throw new Error("Image url is not set");this._coordinatesMode=Le.CUBIC_MODE,this.name=e,this.url=e,this._size=i,this._supersample=a,this._noMipmap=n,this.gammaSpace=s,this._onLoad=r,this._onError=o,this.hasAlpha=!1,this.isCube=!0,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?r&&(this._texture.isReady?se.w1.SetImmediate((()=>r())):this._texture.onLoadedObservable.add(r)):t.useDelayedTextureLoading?this.delayLoadState=4:this._loadImage(this._loadTexture.bind(this),this._onError)}_loadImage(e,t){const i=document.createElement("canvas");(0,ye.r6)(this.url,(t=>{this._width=t.width,this._height=t.height,i.width=this._width,i.height=this._height;const n=i.getContext("2d");n.drawImage(t,0,0);const s=n.getImageData(0,0,t.width,t.height);this._buffer=s.data.buffer,i.remove(),e()}),((e,i)=>{t&&t(`${this.getClassName()} could not be loaded`,i)}),null)}_loadTexture(){const e=this.getScene();e&&(this._texture=e.getEngine().createRawCubeTextureFromUrl(this.url,e,this._size,4,e.getEngine().getCaps().textureFloat?1:7,this._noMipmap,(()=>{const e=this._getFloat32ArrayFromArrayBuffer(this._buffer),t=Wg.ConvertPanoramaToCubemap(e,this._width,this._height,this._size,this._supersample),i=[];for(let n=0;n<6;n++){const e=t[Ev._FacesMapping[n]];i.push(e)}return i}),null,this._onLoad,this._onError))}_getFloat32ArrayFromArrayBuffer(e){const t=new DataView(e),i=new Float32Array(3*e.byteLength/4);let n=0;for(let s=0;st.length)return void p.Y.Error("Unable to load TGA file - Not enough data");i+=n.id_length;let s,r=!1,o=!1,a=!1;switch(n.image_type){case 9:r=!0;case 1:o=!0;break;case 10:r=!0;case 2:break;case 11:r=!0;case 3:a=!0}const l=n.pixel_size>>3,h=n.width*n.height*l;let c,d,u,f,_,m,g;if(o&&(c=t.subarray(i,i+=n.colormap_length*(n.colormap_size>>3))),r){let e,n,r;s=new Uint8Array(h);let o=0;const a=new Uint8Array(l);for(;i>4){default:case 2:d=0,f=1,g=n.width,u=0,_=1,m=n.height;break;case 0:d=0,f=1,g=n.width,u=n.height-1,_=-1,m=-1;break;case 3:d=n.width-1,f=-1,g=-1,u=0,_=1,m=n.height;break;case 1:d=n.width-1,f=-1,g=-1,u=n.height-1,_=-1,m=-1}const v="_getImageData"+(a?"Grey":"")+n.pixel_size+"bits",T=yv[v](n,c,s,u,_,m,d,f,g);e.getEngine()._uploadDataToTextureDirectly(e,T)}const yv={GetTGAHeader:bv,UploadContent:Cv,_getImageData8bits:function(e,t,i,n,s,r,o,a,l){const h=i,c=t,d=e.width,u=e.height;let p,f,_,m=0;const g=new Uint8Array(d*u*4);for(_=n;_!==r;_+=s)for(f=o;f!==l;f+=a,m++)p=h[m],g[4*(f+d*_)+3]=255,g[4*(f+d*_)+2]=c[3*p+0],g[4*(f+d*_)+1]=c[3*p+1],g[4*(f+d*_)+0]=c[3*p+2];return g},_getImageData16bits:function(e,t,i,n,s,r,o,a,l){const h=i,c=e.width,d=e.height;let u,p,f,_=0;const m=new Uint8Array(c*d*4);for(f=n;f!==r;f+=s)for(p=o;p!==l;p+=a,_+=2){u=h[_+0]+(h[_+1]<<8);const e=255*((31744&u)>>10)/31|0,t=255*((992&u)>>5)/31|0,i=255*(31&u)/31|0;m[4*(p+c*f)+0]=e,m[4*(p+c*f)+1]=t,m[4*(p+c*f)+2]=i,m[4*(p+c*f)+3]=32768&u?0:255}return m},_getImageData24bits:function(e,t,i,n,s,r,o,a,l){const h=i,c=e.width,d=e.height;let u,p,f=0;const _=new Uint8Array(c*d*4);for(p=n;p!==r;p+=s)for(u=o;u!==l;u+=a,f+=3)_[4*(u+c*p)+3]=255,_[4*(u+c*p)+2]=h[f+0],_[4*(u+c*p)+1]=h[f+1],_[4*(u+c*p)+0]=h[f+2];return _},_getImageData32bits:function(e,t,i,n,s,r,o,a,l){const h=i,c=e.width,d=e.height;let u,p,f=0;const _=new Uint8Array(c*d*4);for(p=n;p!==r;p+=s)for(u=o;u!==l;u+=a,f+=4)_[4*(u+c*p)+2]=h[f+0],_[4*(u+c*p)+1]=h[f+1],_[4*(u+c*p)+0]=h[f+2],_[4*(u+c*p)+3]=h[f+3];return _},_getImageDataGrey8bits:function(e,t,i,n,s,r,o,a,l){const h=i,c=e.width,d=e.height;let u,p,f,_=0;const m=new Uint8Array(c*d*4);for(f=n;f!==r;f+=s)for(p=o;p!==l;p+=a,_++)u=h[_],m[4*(p+c*f)+0]=u,m[4*(p+c*f)+1]=u,m[4*(p+c*f)+2]=u,m[4*(p+c*f)+3]=255;return m},_getImageDataGrey16bits:function(e,t,i,n,s,r,o,a,l){const h=i,c=e.width,d=e.height;let u,p,f=0;const _=new Uint8Array(c*d*4);for(p=n;p!==r;p+=s)for(u=o;u!==l;u+=a,f+=2)_[4*(u+c*p)+0]=h[f+0],_[4*(u+c*p)+1]=h[f+0],_[4*(u+c*p)+2]=h[f+0],_[4*(u+c*p)+3]=h[f+1];return _}};fe.D._TextureLoaders.push(new class{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".tga")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=bv(n);i(s.width,s.height,t.generateMipMaps,!1,(()=>{Cv(t,n)}))}});fe.D._TextureLoaders.push(new class{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".hdr")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){const n=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=Hg.RGBE_ReadHeader(n),r=Hg.RGBE_ReadPixels(n,s),o=s.width*s.height,a=new Float32Array(4*o);for(let l=0;l{const e=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,e._uploadDataToTextureDirectly(t,a)}))}});var Av;!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"}(Av||(Av={}));const Rv={JSModuleURL:"https://cdn.babylonjs.com/basisTranscoder/1/basis_transcoder.js",WasmModuleURL:"https://cdn.babylonjs.com/basisTranscoder/1/basis_transcoder.wasm"};let Pv=null,Iv=null,Mv=0;const Ov=(e,t)=>{const i=e instanceof ArrayBuffer?new Uint8Array(e):e;return new Promise(((e,n)=>{(Pv||(Pv=new Promise(((e,t)=>{Iv?e(Iv):se.w1.LoadFileAsync(Rv.WasmModuleURL).then((i=>{if("function"!=typeof URL)return t("Basis transcoder requires an environment with a URL constructor");const n=URL.createObjectURL(new Blob([`(${wv})()`],{type:"application/javascript"}));Iv=new Worker(n);const s=i=>{"init"===i.data.action?(Iv.removeEventListener("message",s),e(Iv)):"error"===i.data.action&&t(i.data.error||"error initializing worker")};Iv.addEventListener("message",s),Iv.postMessage({action:"init",url:Rv.JSModuleURL,wasmBinary:i})})).catch(t)}))),Pv).then((()=>{const s=Mv++,r=t=>{"transcode"===t.data.action&&t.data.id===s&&(Iv.removeEventListener("message",r),t.data.success?e(t.data):n("Transcode is not supported on this device"))};Iv.addEventListener("message",r);const o=new Uint8Array(i.byteLength);o.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),Iv.postMessage({action:"transcode",id:s,imageData:o,config:t,ignoreSupportedFormats:false},[o.buffer])}),(e=>{n(e)}))}))},Dv=(e,t)=>{var i,n;let s=null===(i=t._gl)||void 0===i?void 0:i.TEXTURE_2D;e.isCube&&(s=null===(n=t._gl)||void 0===n?void 0:n.TEXTURE_CUBE_MAP),t._bindTextureDirectly(s,e,!0)},Nv=(e,t)=>{const i=e.getEngine();for(let n=0;n{i._releaseTexture(t),Dv(e,i)}))}else{e.width=s.width,e.height=s.height,e.generateMipMaps=t.fileInfo.images[n].levels.length>1;const r=Fv.GetInternalFormatFromBasisFormat(t.format,i);e.format=r,Dv(e,i),t.fileInfo.images[n].levels.forEach(((t,s)=>{i._uploadCompressedDataToTextureDirectly(e,r,t.width,t.height,t.transcodedPixels,n,s)})),!i._features.basisNeedsPOT||S.R.Log2(e.width)%1==0&&S.R.Log2(e.height)%1==0||(se.w1.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=Le.CLAMP_ADDRESSMODE,e._cachedWrapV=Le.CLAMP_ADDRESSMODE)}}},Fv={JSModuleURL:Rv.JSModuleURL,WasmModuleURL:Rv.WasmModuleURL,GetInternalFormatFromBasisFormat:(e,t)=>{let i;switch(e){case Av.cTFETC1:i=36196;break;case Av.cTFBC1:i=33776;break;case Av.cTFBC4:i=33779;break;case Av.cTFASTC_4x4:i=37808;break;case Av.cTFETC2:i=37496;break;case Av.cTFBC7:i=36492}if(void 0===i)throw"The chosen Basis transcoder format is not currently supported";return i},TranscodeAsync:Ov,LoadTextureFromTranscodeResult:Nv};function wv(){const e=0,t=1,i=2,n=3,s=6,r=8,o=9,a=10,l=14;let h=null;function c(e,t,i,n,s){const r=e.getImageTranscodedSizeInBytes(t,i,n);let o=new Uint8Array(r);if(!e.transcodeImage(o,t,i,n,1,0))return null;if(s){o=function(e,t,i,n){const s=new Uint16Array(4),r=new Uint16Array(i*n),o=i/4,a=n/4;for(let l=0;l>2&3],r[h++]=s[o>>4&3],r[h++]=s[o>>6&3]}}return r}(o,0,e.getImageWidth(t,i)+3&-4,e.getImageHeight(t,i)+3&-4)}return o}onmessage=d=>{if("init"===d.data.action){if(!h){try{importScripts(d.data.url)}catch(u){postMessage({action:"error",error:u})}h=BASIS({wasmBinary:d.data.wasmBinary})}null!==h&&h.then((e=>{BASIS=e,e.initializeBasis(),postMessage({action:"init"})}))}else if("transcode"===d.data.action){const h=d.data.config,u=d.data.imageData,p=new BASIS.BasisFile(u),f=function(e){const t=e.getHasAlpha(),i=e.getNumImages(),n=[];for(let s=0;s{const i=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;Nv(t,e),t.getEngine()._setCubeMapTextureParams(t,i),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),n&&n()})).catch((e=>{se.w1.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),t.isReady=!0,s&&s(e)}))}loadData(e,t,i){const n=t.getEngine().getCaps(),s={supportedCompressionFormats:{etc1:!!n.etc1,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,astc:!!n.astc,bc7:!!n.bptc}};Ov(e,s).then((e=>{const n=e.fileInfo.images[0].levels[0],s=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(n.width,n.height,s,-1!==e.format,(()=>{Nv(t,e)}))})).catch((e=>{se.w1.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),se.w1.Warn(`Failed to transcode Basis file: ${e}`),i(0,0,!1,!1,(()=>{}),!0)}))}});class Lv extends Ci{get isSupported(){var e,t;return null!==(t=null===(e=this._engine)||void 0===e?void 0:e.getCaps().drawBuffersExtension)&&void 0!==t&&t}get textures(){return this._textures}get count(){return this._count}get depthTexture(){return this._textures[this._textures.length-1]}set wrapU(e){if(this._textures)for(let t=0;t0&&(this._createInternalTextures(),this._createTextures(r))}_initTypes(e,t,i,n,s,r,o,a,l,h){for(let c=0;c{this.onAfterRenderObservable.notifyObservers(t)}))}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){var e,t;const i=null===(e=this._renderTarget)||void 0===e?void 0:e.textures;if(i){for(let e=i.length-1;e>=0;e--)this._textures[e]._texture=null;null===(t=this._renderTarget)||void 0===t||t.dispose(),this._renderTarget=null}}}class Bv{constructor(e,t,i){this.id=e,this.scale=t,this.offset=i}}class Uv{constructor(e,t,i,n){var s,r,o,l,h,c,d,u,p,f,_,m,g;return this.name=e,this.meshes=t,this.scene=n,this.options=i,this.options.map=null!==(s=this.options.map)&&void 0!==s?s:["ambientTexture","bumpTexture","diffuseTexture","emissiveTexture","lightmapTexture","opacityTexture","reflectionTexture","refractionTexture","specularTexture"],this.options.uvsIn=null!==(r=this.options.uvsIn)&&void 0!==r?r:ne.o.UVKind,this.options.uvsOut=null!==(o=this.options.uvsOut)&&void 0!==o?o:ne.o.UVKind,this.options.layout=null!==(l=this.options.layout)&&void 0!==l?l:Uv.LAYOUT_STRIP,this.options.layout===Uv.LAYOUT_COLNUM&&(this.options.colnum=null!==(h=this.options.colnum)&&void 0!==h?h:8),this.options.updateInputMeshes=null===(c=this.options.updateInputMeshes)||void 0===c||c,this.options.disposeSources=null===(d=this.options.disposeSources)||void 0===d||d,this._expecting=0,this.options.fillBlanks=null===(u=this.options.fillBlanks)||void 0===u||u,!0===this.options.fillBlanks&&(this.options.customFillColor=null!==(p=this.options.customFillColor)&&void 0!==p?p:"black"),this.options.frameSize=null!==(f=this.options.frameSize)&&void 0!==f?f:256,this.options.paddingRatio=null!==(_=this.options.paddingRatio)&&void 0!==_?_:.0115,this._paddingValue=Math.ceil(this.options.frameSize*this.options.paddingRatio),this._paddingValue%2!=0&&this._paddingValue++,this.options.paddingMode=null!==(m=this.options.paddingMode)&&void 0!==m?m:Uv.SUBUV_WRAP,this.options.paddingMode===Uv.SUBUV_COLOR&&(this.options.paddingColor=null!==(g=this.options.paddingColor)&&void 0!==g?g:new a.HE(0,0,0,1)),this.sets={},this.frames=[],this}_createFrames(e){const t=this._calculateSize(),i=new o.FM(1,1).divide(t);let n=0;const s=this._expecting,r=this.meshes.length,l=Object.keys(this.sets);for(let o=0;o{this._calculateMeshUVFrames(h,c,t,i,this.options.updateInputMeshes||!1)};for(let o=0;o{n++,p.update(!1);const i=f.getImageData(0,0,d,d),r=this.sets[g];if(r.getContext().putImageData(i,t.x*_.x,t.y*_.y),p.dispose(),r.update(!1),n==s)return u(),void e()},g=l[r]||"_blank";if(i&&null!==i[g]){const e=i[g],t=new Image;t.src=e instanceof ma?e.getContext().canvas.toDataURL("image/png"):e.url,se.w1.SetCorsBehavior(t.src,t),t.onload=()=>{f.fillStyle="rgba(0,0,0,0)",f.fillRect(0,0,d,d),p.update(!1),f.setTransform(1,0,0,-1,0,0);const e=[0,0,1,0,1,1,0,1,-1,1,-1,0,-2,0,-1,1,-1];switch(this.options.paddingMode){case 0:for(let i=0;i<9;i++)f.drawImage(t,0,0,t.width,t.height,c+h*e[i],c+h*e[i+1]-d,h,h);break;case 1:for(let i=0;i{e.dispose&&e.dispose()};for(let r=0;r{try{if(0===this.meshes.length)return void e();let t=0;const i=i=>{if(t++,this.options.map){for(let e=0;e{i(r)}));else if(t++,t===this.meshes.length)return this._createFrames(e)}}catch(i){return t(i)}}))}dispose(){const e=Object.keys(this.sets);for(let t=0;t{const i={name:this.name,sets:{},options:{},frames:[]},n=Object.keys(this.sets),s=Object.keys(this.options);try{for(let s=0;se));return e.onRebuildCallback=e=>({proxy:r,isReady:!0,isAsync:!0}),e._source=Be.S.CubeRawRGBD,e._bufferViewArrayArray=t,e._lodGenerationScale=n,e._lodGenerationOffset=s,e._sphericalPolynomial=i,Jh(e,t).then((()=>(e.isReady=!0,e)))}(this._texture,e,t,i,n).then((()=>{}))}clone(){return E.p4.Clone((()=>{const e=this.getScene(),t=this._texture,i=new zv(e,t._bufferViewArray,t.width,t.format,t.type,t.generateMipMaps,t.invertY,t.samplingMode,t._compression);return t.source===Be.S.CubeRawRGBD&&i.updateRGBDAsync(t._bufferViewArrayArray,t._sphericalPolynomial,t._lodGenerationScale,t._lodGenerationOffset),i}),this)}}class Wv extends St{constructor(e,t,i,n,s){super(e,t,i),this._blockType=n,this._blockName=s,this.needDualDirectionValidation=!0}checkCompatibilityState(e){return e instanceof Wv&&e._blockName===this._blockName?gt.Compatible:gt.TypeIncompatible}createCustomInputBlock(){return[new this._blockType(this._blockName),this.name]}}(0,l.H)("BABYLON.BonesBlock",class extends bt{constructor(e){super(e,dt.Vertex),this.registerInput("matricesIndices",ct.Vector4),this.registerInput("matricesWeights",ct.Vector4),this.registerInput("matricesIndicesExtra",ct.Vector4,!0),this.registerInput("matricesWeightsExtra",ct.Vector4,!0),this.registerInput("world",ct.Matrix),this.registerOutput("output",ct.Matrix)}initialize(e){e._excludeVariableName("boneSampler"),e._excludeVariableName("boneTextureWidth"),e._excludeVariableName("mBones"),e._excludeVariableName("BonesPerMesh")}getClassName(){return"BonesBlock"}get matricesIndices(){return this._inputs[0]}get matricesWeights(){return this._inputs[1]}get matricesIndicesExtra(){return this._inputs[2]}get matricesWeightsExtra(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}autoConfigure(e){if(!this.matricesIndices.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"matricesIndices"===e.name));t||(t=new Bt("matricesIndices"),t.setAsAttribute("matricesIndices")),t.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"matricesWeights"===e.name));t||(t=new Bt("matricesWeights"),t.setAsAttribute("matricesWeights")),t.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===Pt.World));t||(t=new Bt("world"),t.setAsSystemValue(Pt.World)),t.output.connectTo(this.world)}}provideFallbacks(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)}bind(e,t,i){It.G.BindBonesParameters(i,e)}prepareDefines(e,t,i){i._areAttributesDirty&&It.G.PrepareDefinesForBones(e,i)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithFallbacks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.uniforms.push("boneTextureWidth"),e.uniforms.push("mBones"),e.samplers.push("boneSampler");const t=`//${this.name}`;e._emitFunctionFromInclude("bonesDeclaration",t,{removeAttributes:!0,removeUniforms:!1,removeVaryings:!0,removeIfDef:!1});const i=e._getFreeVariableName("influence");e.compilationString+=e._emitCodeFromInclude("bonesVertex",t,{replaceStrings:[{search:/finalWorld=finalWorld\*influence;/,replace:""},{search:/influence/gm,replace:i}]});const n=this._outputs[0],s=this.world;return e.compilationString+="#if NUM_BONE_INFLUENCERS>0\r\n",e.compilationString+=this._declareOutput(n,e)+` = ${s.associatedVariableName} * ${i};\r\n`,e.compilationString+="#else\r\n",e.compilationString+=this._declareOutput(n,e)+` = ${s.associatedVariableName};\r\n`,e.compilationString+="#endif\r\n",this}});(0,l.H)("BABYLON.InstancesBlock",class extends bt{constructor(e){super(e,dt.Vertex),this.registerInput("world0",ct.Vector4),this.registerInput("world1",ct.Vector4),this.registerInput("world2",ct.Vector4),this.registerInput("world3",ct.Vector4),this.registerInput("world",ct.Matrix,!0),this.registerOutput("output",ct.Matrix),this.registerOutput("instanceID",ct.Float)}getClassName(){return"InstancesBlock"}get world0(){return this._inputs[0]}get world1(){return this._inputs[1]}get world2(){return this._inputs[2]}get world3(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}get instanceID(){return this._outputs[1]}autoConfigure(e){if(!this.world0.connectedPoint){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"world0"===e.name));t||(t=new Bt("world0"),t.setAsAttribute("world0")),t.output.connectTo(this.world0)}if(!this.world1.connectedPoint){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"world1"===e.name));t||(t=new Bt("world1"),t.setAsAttribute("world1")),t.output.connectTo(this.world1)}if(!this.world2.connectedPoint){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"world2"===e.name));t||(t=new Bt("world2"),t.setAsAttribute("world2")),t.output.connectTo(this.world2)}if(!this.world3.connectedPoint){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"world3"===e.name));t||(t=new Bt("world3"),t.setAsAttribute("world3")),t.output.connectTo(this.world3)}if(!this.world.connectedPoint){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"world"===e.name));t||(t=new Bt("world"),t.setAsSystemValue(Pt.World)),t.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"}prepareDefines(e,t,i,n=!1,s){let r=!1;i.INSTANCES!==n&&(i.setValue("INSTANCES",n),r=!0),s&&i.THIN_INSTANCES!==!!(null==s?void 0:s.getRenderingMesh().hasThinInstances)&&(i.setValue("THIN_INSTANCES",!!(null==s?void 0:s.getRenderingMesh().hasThinInstances)),r=!0),r&&i.markAsUnprocessed()}_buildBlock(e){super._buildBlock(e);const t=e.sharedData.scene.getEngine();e.sharedData.blocksWithDefines.push(this);const i=this._outputs[0],n=this._outputs[1],s=this.world0,r=this.world1,o=this.world2,a=this.world3;return e.compilationString+="#ifdef INSTANCES\r\n",e.compilationString+=this._declareOutput(i,e)+` = mat4(${s.associatedVariableName}, ${r.associatedVariableName}, ${o.associatedVariableName}, ${a.associatedVariableName});\r\n`,e.compilationString+="#ifdef THIN_INSTANCES\r\n",e.compilationString+=`${i.associatedVariableName} = ${this.world.associatedVariableName} * ${i.associatedVariableName};\r\n`,e.compilationString+="#endif\r\n",t._caps.canUseGLInstanceID?e.compilationString+=this._declareOutput(n,e)+" = float(gl_InstanceID);\r\n":e.compilationString+=this._declareOutput(n,e)+" = 0.0;\r\n",e.compilationString+="#else\r\n",e.compilationString+=this._declareOutput(i,e)+` = ${this.world.associatedVariableName};\r\n`,e.compilationString+=this._declareOutput(n,e)+" = 0.0;\r\n",e.compilationString+="#endif\r\n",this}});class Hv extends bt{constructor(e){super(e,dt.Vertex),this.registerInput("position",ct.Vector3),this.registerInput("normal",ct.Vector3),this.registerInput("tangent",ct.AutoDetect),this.tangent.addExcludedConnectionPointFromAllowedTypes(ct.Color4|ct.Vector4|ct.Vector3),this.registerInput("uv",ct.Vector2),this.registerOutput("positionOutput",ct.Vector3),this.registerOutput("normalOutput",ct.Vector3),this.registerOutput("tangentOutput",ct.Vector4),this.registerOutput("uvOutput",ct.Vector2)}getClassName(){return"MorphTargetsBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get tangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get positionOutput(){return this._outputs[0]}get normalOutput(){return this._outputs[1]}get tangentOutput(){return this._outputs[2]}get uvOutput(){return this._outputs[3]}initialize(e){e._excludeVariableName("morphTargetInfluences")}autoConfigure(e){if(!this.position.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"position"===e.name));t||(t=new Bt("position"),t.setAsAttribute()),t.output.connectTo(this.position)}if(!this.normal.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"normal"===e.name));t||(t=new Bt("normal"),t.setAsAttribute("normal")),t.output.connectTo(this.normal)}if(!this.tangent.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"tangent"===e.name));t||(t=new Bt("tangent"),t.setAsAttribute("tangent")),t.output.connectTo(this.tangent)}if(!this.uv.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"uv"===e.name));t||(t=new Bt("uv"),t.setAsAttribute("uv")),t.output.connectTo(this.uv)}}prepareDefines(e,t,i){if(e.morphTargetManager){const t=e.morphTargetManager;(null==t?void 0:t.isUsingTextureForTargets)&&t.numInfluencers!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}i._areAttributesDirty&&It.G.PrepareDefinesForMorphTargets(e,i)}bind(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&(It.G.BindMorphTargetParameters(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))}replaceRepeatableContent(e,t,i,n){const s=this.position,r=this.normal,o=this.tangent,a=this.uv,l=this.positionOutput,h=this.normalOutput,c=this.tangentOutput,d=this.uvOutput,u=e,p=n.NUM_MORPH_INFLUENCERS,f=i.morphTargetManager,_=f&&f.supportsNormals&&n.NORMAL,m=f&&f.supportsTangents&&n.TANGENT,g=f&&f.supportsUVs&&n.UV1;let v="";(null==f?void 0:f.isUsingTextureForTargets)&&p>0&&(v+="float vertexID;\r\n");for(let T=0;T0)for(let T=0;Te.isSystemValue&&e.systemValue===Pt.World));t||(t=new Bt("world"),t.setAsSystemValue(Pt.World)),t.output.connectTo(this.world)}if(!this.normal.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"normal"===e.name));t||(t=new Bt("normal"),t.setAsAttribute("normal")),t.output.connectTo(this.normal)}if(!this.tangent.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"tangent"===e.name&&e.type===ct.Vector4));t||(t=new Bt("tangent"),t.setAsAttribute("tangent")),t.output.connectTo(this.tangent)}}prepareDefines(e,t,i){var n,s,r,o;const a=this.normal,l=this.tangent;let h=a.isConnected;(null===(n=a.connectInputBlock)||void 0===n?void 0:n.isAttribute)&&!e.isVerticesDataPresent(null===(s=a.connectInputBlock)||void 0===s?void 0:s.name)&&(h=!1);let c=l.isConnected;(null===(r=l.connectInputBlock)||void 0===r?void 0:r.isAttribute)&&!e.isVerticesDataPresent(null===(o=l.connectInputBlock)||void 0===o?void 0:o.name)&&(c=!1);const d=h&&c;i.setValue("TBNBLOCK",d,!0)}_buildBlock(e){super._buildBlock(e);const t=this.normal,i=this.tangent,n=this.world,s=this.TBN,r=this.row0,o=this.row1,a=this.row2;return e.target===dt.Fragment&&(e.compilationString+=`\n // ${this.name}\n vec3 tbnNormal = normalize(${t.associatedVariableName}).xyz;\n vec3 tbnTangent = normalize(${i.associatedVariableName}.xyz);\n vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${i.associatedVariableName}.w;\n mat3 ${s.associatedVariableName} = mat3(${n.associatedVariableName}) * mat3(tbnTangent, tbnBitangent, tbnNormal);\n `,r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = vec3(${s.associatedVariableName}[0][0], ${s.associatedVariableName}[0][1], ${s.associatedVariableName}[0][2]);\r\n`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = vec3(${s.associatedVariableName}[1[0], ${s.associatedVariableName}[1][1], ${s.associatedVariableName}[1][2]);\r\n`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = vec3(${s.associatedVariableName}[2][0], ${s.associatedVariableName}[2][1], ${s.associatedVariableName}[2][2]);\r\n`),e.sharedData.blocksWithDefines.push(this)),this}}(0,l.H)("BABYLON.TBNBlock",Yv);class jv extends bt{constructor(e){super(e,dt.Fragment),this._tangentSpaceParameterName="",this._tangentCorrectionFactorName="",this._worldMatrixName="",this.invertX=!1,this.invertY=!1,this.useParallaxOcclusion=!1,this.useObjectSpaceNormalMap=!1,this._isUnique=!0,this.registerInput("worldPosition",ct.Vector4,!1),this.registerInput("worldNormal",ct.Vector4,!1),this.registerInput("worldTangent",ct.Vector4,!0),this.registerInput("uv",ct.Vector2,!1),this.registerInput("normalMapColor",ct.Color3,!1),this.registerInput("strength",ct.Float,!1),this.registerInput("viewDirection",ct.Vector3,!0),this.registerInput("parallaxScale",ct.Float,!0),this.registerInput("parallaxHeight",ct.Float,!0),this.registerInput("TBN",ct.Object,!0,dt.VertexAndFragment,new Wv("TBN",this,vt.Input,Yv,"TBNBlock")),this.registerInput("world",ct.Matrix,!0),this.registerOutput("output",ct.Vector4),this.registerOutput("uvOffset",ct.Vector2)}getClassName(){return"PerturbNormalBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get worldTangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get normalMapColor(){return this._inputs[4]}get strength(){return this._inputs[5]}get viewDirection(){return this._inputs[6]}get parallaxScale(){return this._inputs[7]}get parallaxHeight(){return this._inputs[8]}get TBN(){return this._inputs[9]}get world(){return this._inputs[10]}get output(){return this._outputs[0]}get uvOffset(){return this._outputs[1]}prepareDefines(e,t,i){const n=this.normalMapColor.connectedPoint._ownerBlock.samplerName,s=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&n||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected);i.setValue("BUMP",!0),i.setValue("PARALLAX",s,!0),i.setValue("PARALLAXOCCLUSION",this.useParallaxOcclusion,!0),i.setValue("OBJECTSPACE_NORMALMAP",this.useObjectSpaceNormalMap,!0)}bind(e,t,i){t.getScene()._mirroredCameraPosition?e.setFloat2(this._tangentSpaceParameterName,this.invertX?1:-1,this.invertY?1:-1):e.setFloat2(this._tangentSpaceParameterName,this.invertX?-1:1,this.invertY?-1:1),i&&(e.setFloat(this._tangentCorrectionFactorName,i.getWorldMatrix().determinant()<0?-1:1),this.useObjectSpaceNormalMap&&!this.world.isConnected&&e.setMatrix(this._worldMatrixName,i.getWorldMatrix()))}autoConfigure(e){if(!this.uv.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"uv"===e.name));t||(t=new Bt("uv"),t.setAsAttribute()),t.output.connectTo(this.uv)}if(!this.strength.isConnected){const e=new Bt("strength");e.value=1,e.output.connectTo(this.strength)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`,i=this.uv,n=this.worldPosition,s=this.worldNormal,r=this.worldTangent;e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentSpaceParameterName=e._getFreeDefineName("tangentSpaceParameter"),e._emitUniformFromString(this._tangentSpaceParameterName,"vec2"),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float"),this._worldMatrixName=e._getFreeDefineName("perturbNormalWorldMatrix"),e._emitUniformFromString(this._worldMatrixName,"mat4");let o=null;this.normalMapColor.connectedPoint&&(o=this.normalMapColor.connectedPoint._ownerBlock.samplerName);const a=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&o||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected),l=this.parallaxScale.isConnectedToInputBlock?this.parallaxScale.connectInputBlock.isConstant?e._emitFloat(this.parallaxScale.connectInputBlock.value):this.parallaxScale.associatedVariableName:"0.05",h=this.strength.isConnectedToInputBlock&&this.strength.connectInputBlock.isConstant?`\r\n#if !defined(NORMALXYSCALE)\r\n1.0/\r\n#endif\r\n${e._emitFloat(this.strength.connectInputBlock.value)}`:`\r\n#if !defined(NORMALXYSCALE)\r\n1.0/\r\n#endif\r\n${this.strength.associatedVariableName}`;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");const c={search:/defined\(TANGENT\)/g,replace:r.isConnected?"defined(TANGENT)":"defined(IGNORE)"},d=this.TBN;d.isConnected?e.compilationString+=`\n #ifdef TBNBLOCK\n mat3 vTBN = ${d.associatedVariableName};\n #endif\n `:r.isConnected&&(e.compilationString+=`vec3 tbnNormal = normalize(${s.associatedVariableName}.xyz);\r\n`,e.compilationString+=`vec3 tbnTangent = normalize(${r.associatedVariableName}.xyz);\r\n`,e.compilationString+=`vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};\r\n`,e.compilationString+="mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\r\n"),e._emitFunctionFromInclude("bumpFragmentMainFunctions",t,{replaceStrings:[c,{search:/varying mat3 vTBN/g,replace:""},{search:/uniform mat4 normalMatrix;/g,replace:""}]}),e._emitFunctionFromInclude("bumpFragmentFunctions",t,{replaceStrings:[{search:/#include\(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump\)/g,replace:""},{search:/uniform sampler2D bumpSampler;/g,replace:""},{search:/vec2 parallaxOcclusion\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\)/g,replace:"#define inline\r\nvec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale, sampler2D bumpSampler)"},{search:/vec2 parallaxOffset\(vec3 viewDir,float heightScale\)/g,replace:"vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)"},{search:/texture2D\(bumpSampler,vBumpUV\)\.w/g,replace:"height_"}]});const u=a&&o?`texture2D(${o}, ${i.associatedVariableName} + uvOffset).xyz`:this.normalMapColor.associatedVariableName;return e.compilationString+=this._declareOutput(this.output,e)+" = vec4(0.);\r\n",e.compilationString+=e._emitCodeFromInclude("bumpFragment",t,{replaceStrings:[{search:/texture2D\(bumpSampler,vBumpUV\)/g,replace:`${u}`},{search:/#define CUSTOM_FRAGMENT_BUMP_FRAGMENT/g,replace:`mat4 normalMatrix = toNormalMatrix(${this.world.isConnected?this.world.associatedVariableName:this._worldMatrixName});`},{search:/perturbNormal\(TBN,texture2D\(bumpSampler,vBumpUV\+uvOffset\).xyz,vBumpInfos.y\)/g,replace:`perturbNormal(TBN, ${u}, vBumpInfos.y)`},{search:/parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,replace:`parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ${a&&this.useParallaxOcclusion?o:"bumpSampler"})`},{search:/parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,replace:`parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ${a?this.parallaxHeight.associatedVariableName:"0."})`},{search:/vTangentSpaceParams/g,replace:this._tangentSpaceParameterName},{search:/vBumpInfos.y/g,replace:h},{search:/vBumpInfos.z/g,replace:l},{search:/vBumpUV/g,replace:i.associatedVariableName},{search:/vPositionW/g,replace:n.associatedVariableName+".xyz"},{search:/normalW=/g,replace:this.output.associatedVariableName+".xyz = "},{search:/mat3\(normalMatrix\)\*normalW/g,replace:"mat3(normalMatrix) * "+this.output.associatedVariableName+".xyz"},{search:/normalW/g,replace:s.associatedVariableName+".xyz"},{search:/viewDirectionW/g,replace:a?this.viewDirection.associatedVariableName:"vec3(0.)"},c]}),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.invertX = ${this.invertX};\r\n`;return e+=`${this._codeVariableName}.invertY = ${this.invertY};\r\n`,e+=`${this._codeVariableName}.useParallaxOcclusion = ${this.useParallaxOcclusion};\r\n`,e+=`${this._codeVariableName}.useObjectSpaceNormalMap = ${this.useObjectSpaceNormalMap};\r\n`,e}serialize(){const e=super.serialize();return e.invertX=this.invertX,e.invertY=this.invertY,e.useParallaxOcclusion=this.useParallaxOcclusion,e.useObjectSpaceNormalMap=this.useObjectSpaceNormalMap,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.invertX=e.invertX,this.invertY=e.invertY,this.useParallaxOcclusion=!!e.useParallaxOcclusion,this.useObjectSpaceNormalMap=!!e.useObjectSpaceNormalMap}}(0,oe.gn)([At("Invert X axis",Et.Boolean,"PROPERTIES",{notifiers:{update:!1}})],jv.prototype,"invertX",void 0),(0,oe.gn)([At("Invert Y axis",Et.Boolean,"PROPERTIES",{notifiers:{update:!1}})],jv.prototype,"invertY",void 0),(0,oe.gn)([At("Use parallax occlusion",Et.Boolean)],jv.prototype,"useParallaxOcclusion",void 0),(0,oe.gn)([At("Object Space Mode",Et.Boolean,"PROPERTIES",{notifiers:{update:!1}})],jv.prototype,"useObjectSpaceNormalMap",void 0),(0,l.H)("BABYLON.PerturbNormalBlock",jv);(0,l.H)("BABYLON.DiscardBlock",class extends bt{constructor(e){super(e,dt.Fragment,!0),this.registerInput("value",ct.Float,!0),this.registerInput("cutoff",ct.Float,!0)}getClassName(){return"DiscardBlock"}get value(){return this._inputs[0]}get cutoff(){return this._inputs[1]}_buildBlock(e){if(super._buildBlock(e),e.sharedData.hints.needAlphaTesting=!0,this.cutoff.isConnected&&this.value.isConnected)return e.compilationString+=`if (${this.value.associatedVariableName} < ${this.cutoff.associatedVariableName}) discard;\r\n`,this}});(0,l.H)("BABYLON.FrontFacingBlock",class extends bt{constructor(e){super(e,dt.Fragment),this.registerOutput("output",ct.Float,dt.Fragment)}getClassName(){return"FrontFacingBlock"}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),e.target===dt.Vertex)throw"FrontFacingBlock must only be used in a fragment shader";const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+" = gl_FrontFacing ? 1.0 : 0.0;\r\n",this}});(0,l.H)("BABYLON.DerivativeBlock",class extends bt{constructor(e){super(e,dt.Fragment),this.registerInput("input",ct.AutoDetect,!1),this.registerOutput("dx",ct.BasedOnInput),this.registerOutput("dy",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._outputs[1]._typeConnectionSource=this._inputs[0]}getClassName(){return"DerivativeBlock"}get input(){return this._inputs[0]}get dx(){return this._outputs[0]}get dy(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._outputs[1];return e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),t.hasEndpoints&&(e.compilationString+=this._declareOutput(t,e)+` = dFdx(${this.input.associatedVariableName});\r\n`),i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = dFdy(${this.input.associatedVariableName});\r\n`),this}});(0,l.H)("BABYLON.FragCoordBlock",class extends bt{constructor(e){super(e,dt.Fragment),this.registerOutput("xy",ct.Vector2,dt.Fragment),this.registerOutput("xyz",ct.Vector3,dt.Fragment),this.registerOutput("xyzw",ct.Vector4,dt.Fragment),this.registerOutput("x",ct.Float,dt.Fragment),this.registerOutput("y",ct.Float,dt.Fragment),this.registerOutput("z",ct.Float,dt.Fragment),this.registerOutput("w",ct.Float,dt.Fragment)}getClassName(){return"FragCoordBlock"}get xy(){return this._outputs[0]}get xyz(){return this._outputs[1]}get xyzw(){return this._outputs[2]}get x(){return this._outputs[3]}get y(){return this._outputs[4]}get z(){return this._outputs[5]}get output(){return this._outputs[6]}writeOutputs(e){let t="";for(const i of this._outputs)i.hasEndpoints&&(t+=`${this._declareOutput(i,e)} = gl_FragCoord.${i.name};\r\n`);return t}_buildBlock(e){if(super._buildBlock(e),e.target===dt.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this}});(0,l.H)("BABYLON.ScreenSizeBlock",class extends bt{constructor(e){super(e,dt.Fragment),this.registerOutput("xy",ct.Vector2,dt.Fragment),this.registerOutput("x",ct.Float,dt.Fragment),this.registerOutput("y",ct.Float,dt.Fragment)}getClassName(){return"ScreenSizeBlock"}get xy(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}bind(e){const t=this._scene.getEngine();e.setFloat2(this._varName,t.getRenderWidth(),t.getRenderHeight())}writeOutputs(e,t){let i="";for(const n of this._outputs)n.hasEndpoints&&(i+=`${this._declareOutput(n,e)} = ${t}.${n.name};\r\n`);return i}_buildBlock(e){if(super._buildBlock(e),this._scene=e.sharedData.scene,e.target===dt.Vertex)throw"ScreenSizeBlock must only be used in a fragment shader";return e.sharedData.bindableBlocks.push(this),this._varName=e._getFreeVariableName("screenSize"),e._emitUniformFromString(this._varName,"vec2"),e.compilationString+=this.writeOutputs(e,this._varName),this}});(0,l.H)("BABYLON.ScreenSpaceBlock",class extends bt{constructor(e){super(e,dt.Fragment),this.registerInput("vector",ct.AutoDetect),this.registerInput("worldViewProjection",ct.Matrix),this.registerOutput("output",ct.Vector2),this.registerOutput("x",ct.Float),this.registerOutput("y",ct.Float),this.inputs[0].addExcludedConnectionPointFromAllowedTypes(ct.Color3|ct.Vector3|ct.Vector4)}getClassName(){return"ScreenSpaceBlock"}get vector(){return this._inputs[0]}get worldViewProjection(){return this._inputs[1]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(e){if(!this.worldViewProjection.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===Pt.WorldViewProjection));t||(t=new Bt("worldViewProjection"),t.setAsSystemValue(Pt.WorldViewProjection)),t.output.connectTo(this.worldViewProjection)}}_buildBlock(e){super._buildBlock(e);const t=this.vector,i=this.worldViewProjection;if(!t.connectedPoint)return;const n=i.associatedVariableName,s=e._getFreeVariableName("screenSpaceTemp");switch(t.connectedPoint.type){case ct.Vector3:e.compilationString+=`vec4 ${s} = ${n} * vec4(${t.associatedVariableName}, 1.0);\r\n`;break;case ct.Vector4:e.compilationString+=`vec4 ${s} = ${n} * ${t.associatedVariableName};\r\n`}return e.compilationString+=`${s}.xy /= ${s}.w;`,e.compilationString+=`${s}.xy = ${s}.xy * 0.5 + vec2(0.5, 0.5);`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${s}.xy;\r\n`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${s}.x;\r\n`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${s}.y;\r\n`),this}});(0,l.H)("BABYLON.TwirlBlock",class extends bt{constructor(e){super(e,dt.Fragment),this.registerInput("input",ct.Vector2),this.registerInput("strength",ct.Float),this.registerInput("center",ct.Vector2),this.registerInput("offset",ct.Vector2),this.registerOutput("output",ct.Vector2),this.registerOutput("x",ct.Float),this.registerOutput("y",ct.Float)}getClassName(){return"TwirlBlock"}get input(){return this._inputs[0]}get strength(){return this._inputs[1]}get center(){return this._inputs[2]}get offset(){return this._inputs[3]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(){if(!this.center.isConnected){const e=new Bt("center");e.value=new o.FM(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){const e=new Bt("strength");e.value=1,e.output.connectTo(this.strength)}if(!this.offset.isConnected){const e=new Bt("offset");e.value=new o.FM(0,0),e.output.connectTo(this.offset)}}_buildBlock(e){super._buildBlock(e);const t=e._getFreeVariableName("delta"),i=e._getFreeVariableName("angle"),n=e._getFreeVariableName("x"),s=e._getFreeVariableName("y"),r=e._getFreeVariableName("result");return e.compilationString+=`\n vec2 ${t} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName};\n float ${i} = ${this.strength.associatedVariableName} * length(${t});\n float ${n} = cos(${i}) * ${t}.x - sin(${i}) * ${t}.y;\n float ${s} = sin(${i}) * ${t}.x + cos(${i}) * ${t}.y;\n vec2 ${r} = vec2(${n} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${s} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y);\n `,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${r};\r\n`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${r}.x;\r\n`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${r}.y;\r\n`),this}});class Kv extends bt{constructor(e){super(e,dt.Fragment),this.generateInWorldSpace=!1,this.automaticNormalizationNormal=!0,this.automaticNormalizationTangent=!0,this.registerInput("input",ct.Float),this.registerInput("worldPosition",ct.Vector3),this.registerInput("worldNormal",ct.Vector3),this.registerInput("worldTangent",ct.AutoDetect,!0),this.registerOutput("output",ct.Vector4),this.registerOutput("xyz",ct.Vector3),this._inputs[3].addExcludedConnectionPointFromAllowedTypes(ct.Color3|ct.Vector3|ct.Vector4)}getClassName(){return"HeightToNormalBlock"}get input(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get worldTangent(){return this._inputs[3]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];this.generateInWorldSpace||this.worldTangent.isConnected||console.error(`You must connect the 'worldTangent' input of the ${this.name} block!`);const i=this.generateInWorldSpace?"":"\n vec3 biTangent = cross(normal, tangent);\n mat3 TBN = mat3(tangent, biTangent, normal);\n ",n=this.generateInWorldSpace?"":"\n result = TBN * result;\n result = result * vec3(0.5) + vec3(0.5);\n ",s=`\n vec4 heightToNormal(in float height, in vec3 position, in vec3 tangent, in vec3 normal) {\n ${i}\n ${this.automaticNormalizationTangent?"tangent = normalize(tangent);":""}\n ${this.automaticNormalizationNormal?"normal = normalize(normal);":""}\n vec3 worlddX = dFdx(position);\n vec3 worlddY = dFdy(position);\n vec3 crossX = cross(normal, worlddX);\n vec3 crossY = cross(normal, worlddY);\n float d = abs(dot(crossY, worlddX));\n vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d));\n inToNormal.y *= -1.0;\n vec3 result = normalize((d * normal) - inToNormal);\n ${n}\n return vec4(result, 0.);\n }`;return e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitFunction("heightToNormal",s,"// heightToNormal"),e.compilationString+=this._declareOutput(t,e)+` = heightToNormal(${this.input.associatedVariableName}, ${this.worldPosition.associatedVariableName}, ${this.worldTangent.isConnected?this.worldTangent.associatedVariableName:"vec3(0.)"}.xyz, ${this.worldNormal.associatedVariableName});\r\n`,this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz;\r\n`),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.generateInWorldSpace = ${this.generateInWorldSpace};\r\n`,e+=`${this._codeVariableName}.automaticNormalizationNormal = ${this.automaticNormalizationNormal};\r\n`,e+=`${this._codeVariableName}.automaticNormalizationTangent = ${this.automaticNormalizationTangent};\r\n`,e}serialize(){const e=super.serialize();return e.generateInWorldSpace=this.generateInWorldSpace,e.automaticNormalizationNormal=this.automaticNormalizationNormal,e.automaticNormalizationTangent=this.automaticNormalizationTangent,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.generateInWorldSpace=e.generateInWorldSpace,this.automaticNormalizationNormal=e.automaticNormalizationNormal,this.automaticNormalizationTangent=e.automaticNormalizationTangent}}(0,oe.gn)([At("Generate in world space instead of tangent space",Et.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Kv.prototype,"generateInWorldSpace",void 0),(0,oe.gn)([At("Force normalization for the worldNormal input",Et.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Kv.prototype,"automaticNormalizationNormal",void 0),(0,oe.gn)([At("Force normalization for the worldTangent input",Et.Boolean,"PROPERTIES",{notifiers:{update:!0}})],Kv.prototype,"automaticNormalizationTangent",void 0),(0,l.H)("BABYLON.HeightToNormalBlock",Kv);(0,l.H)("BABYLON.FragDepthBlock",class extends bt{constructor(e){super(e,dt.Fragment,!0),this.registerInput("depth",ct.Float,!0),this.registerInput("worldPos",ct.Vector4,!0),this.registerInput("viewProjection",ct.Matrix,!0)}getClassName(){return"FragDepthBlock"}get depth(){return this._inputs[0]}get worldPos(){return this._inputs[1]}get viewProjection(){return this._inputs[2]}_buildBlock(e){return super._buildBlock(e),this.depth.isConnected?e.compilationString+=`gl_FragDepth = ${this.depth.associatedVariableName};\r\n`:this.worldPos.isConnected&&this.viewProjection.isConnected?e.compilationString+=`\n vec4 p = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName};\n float v = p.z / p.w;\n #ifndef IS_NDC_HALF_ZRANGE\n v = v * 0.5 + 0.5;\n #endif\n gl_FragDepth = v;\n \n `:console.warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this}});(0,l.H)("BABYLON.ShadowMapBlock",class extends bt{constructor(e){super(e,dt.Fragment),this.registerInput("worldPosition",ct.Vector4,!1),this.registerInput("viewProjection",ct.Matrix,!1),this.registerInput("worldNormal",ct.AutoDetect,!0),this.registerOutput("depth",ct.Vector3),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(ct.Color3|ct.Vector3|ct.Vector4)}getClassName(){return"ShadowMapBlock"}initialize(e){e._excludeVariableName("vPositionWSM"),e._excludeVariableName("lightDataSM"),e._excludeVariableName("biasAndScaleSM"),e._excludeVariableName("depthValuesSM"),e._excludeVariableName("clipPos"),e._excludeVariableName("worldPos"),e._excludeVariableName("zSM")}get worldPosition(){return this._inputs[0]}get viewProjection(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get depth(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;return e._emitUniformFromString("biasAndScaleSM","vec3"),e._emitUniformFromString("lightDataSM","vec3"),e._emitUniformFromString("depthValuesSM","vec2"),e._emitFunctionFromInclude("packingFunctions",t),e.compilationString+=`vec4 worldPos = ${this.worldPosition.associatedVariableName};\r\n`,e.compilationString+="vec3 vPositionWSM;\r\n",e.compilationString+="float vDepthMetricSM = 0.0;\r\n",e.compilationString+="float zSM;\r\n",this.worldNormal.isConnected&&(e.compilationString+=`vec3 vNormalW = ${this.worldNormal.associatedVariableName}.xyz;\r\n`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexNormalBias",t)),e.compilationString+=`vec4 clipPos = ${this.viewProjection.associatedVariableName} * worldPos;\r\n`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexMetric",t,{replaceStrings:[{search:/gl_Position/g,replace:"clipPos"}]}),e.compilationString+=e._emitCodeFromInclude("shadowMapFragment",t,{replaceStrings:[{search:/return;/g,replace:""}]}),e.compilationString+="\n #if SM_DEPTHTEXTURE == 1\n #ifdef IS_NDC_HALF_ZRANGE\n gl_FragDepth = (clipPos.z / clipPos.w);\n #else\n gl_FragDepth = (clipPos.z / clipPos.w) * 0.5 + 0.5;\n #endif\n #endif\n ",e.compilationString+=`${this._declareOutput(this.depth,e)} = vec3(depthSM, 1., 1.);\r\n`,this}});(0,l.H)("BABYLON.FogBlock",class extends bt{constructor(e){super(e,dt.VertexAndFragment,!1),this.registerInput("worldPosition",ct.Vector4,!1,dt.Vertex),this.registerInput("view",ct.Matrix,!1,dt.Vertex),this.registerInput("input",ct.AutoDetect,!1,dt.Fragment),this.registerInput("fogColor",ct.AutoDetect,!1,dt.Fragment),this.registerOutput("output",ct.Color3,dt.Fragment),this.input.addExcludedConnectionPointFromAllowedTypes(ct.Color3|ct.Vector3|ct.Color4),this.fogColor.addExcludedConnectionPointFromAllowedTypes(ct.Color3|ct.Vector3|ct.Color4)}getClassName(){return"FogBlock"}get worldPosition(){return this._inputs[0]}get view(){return this._inputs[1]}get input(){return this._inputs[2]}get fogColor(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(e){if(!this.view.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===Pt.View));t||(t=new Bt("view"),t.setAsSystemValue(Pt.View)),t.output.connectTo(this.view)}if(!this.fogColor.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===Pt.FogColor));t||(t=new Bt("fogColor",void 0,ct.Color3),t.setAsSystemValue(Pt.FogColor)),t.output.connectTo(this.fogColor)}}prepareDefines(e,t,i){const n=e.getScene();i.setValue("FOG",t.fogEnabled&&It.G.GetFogState(e,n))}bind(e,t,i){if(!i)return;const n=i.getScene();e.setFloat4(this._fogParameters,n.fogMode,n.fogStart,n.fogEnd,n.fogDensity)}_buildBlock(e){if(super._buildBlock(e),e.target===dt.Fragment){e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),e._emitFunctionFromInclude("fogFragmentDeclaration",`//${this.name}`,{removeUniforms:!0,removeVaryings:!0,removeIfDef:!1,replaceStrings:[{search:/float CalcFogFactor\(\)/,replace:"float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)"}]});const t=e._getFreeVariableName("fog"),i=this.input,n=this.fogColor;this._fogParameters=e._getFreeVariableName("fogParameters");const s=this._outputs[0];e._emitUniformFromString(this._fogParameters,"vec4"),e.compilationString+="#ifdef FOG\r\n",e.compilationString+=`float ${t} = CalcFogFactor(${this._fogDistanceName}, ${this._fogParameters});\r\n`,e.compilationString+=this._declareOutput(s,e)+` = ${t} * ${i.associatedVariableName}.rgb + (1.0 - ${t}) * ${n.associatedVariableName}.rgb;\r\n`,e.compilationString+=`#else\r\n${this._declareOutput(s,e)} = ${i.associatedVariableName}.rgb;\r\n`,e.compilationString+="#endif\r\n"}else{const t=this.worldPosition,i=this.view;this._fogDistanceName=e._getFreeVariableName("vFogDistance"),e._emitVaryingFromString(this._fogDistanceName,"vec3"),e.compilationString+=`${this._fogDistanceName} = (${i.associatedVariableName} * ${t.associatedVariableName}).xyz;\r\n`}return this}});class qv extends bt{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,console.error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?dt.Fragment:dt.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?dt.Fragment:dt.Vertex}constructor(e){super(e,dt.VertexAndFragment),this._lightId=0,this.generateOnlyFragmentCode=!1,this._isUnique=!0,this.registerInput("worldPosition",ct.Vector4,!1,dt.Vertex),this.registerInput("worldNormal",ct.Vector4,!1,dt.Fragment),this.registerInput("cameraPosition",ct.Vector3,!1,dt.Fragment),this.registerInput("glossiness",ct.Float,!0,dt.Fragment),this.registerInput("glossPower",ct.Float,!0,dt.Fragment),this.registerInput("diffuseColor",ct.Color3,!0,dt.Fragment),this.registerInput("specularColor",ct.Color3,!0,dt.Fragment),this.registerInput("view",ct.Matrix,!0),this.registerOutput("diffuseOutput",ct.Color3,dt.Fragment),this.registerOutput("specularOutput",ct.Color3,dt.Fragment),this.registerOutput("shadow",ct.Float,dt.Fragment)}getClassName(){return"LightBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get cameraPosition(){return this._inputs[2]}get glossiness(){return this._inputs[3]}get glossPower(){return this._inputs[4]}get diffuseColor(){return this._inputs[5]}get specularColor(){return this._inputs[6]}get view(){return this._inputs[7]}get diffuseOutput(){return this._outputs[0]}get specularOutput(){return this._outputs[1]}get shadow(){return this._outputs[2]}autoConfigure(e){if(!this.cameraPosition.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===Pt.CameraPosition));t||(t=new Bt("cameraPosition"),t.setAsSystemValue(Pt.CameraPosition)),t.output.connectTo(this.cameraPosition)}}prepareDefines(e,t,i){if(!i._areLightsDirty)return;const n=e.getScene();if(this.light){const t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};It.G.PrepareDefinesForLight(n,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else It.G.PrepareDefinesForLights(n,e,i,!0,t.maxSimultaneousLights)}updateUniformsAndSamples(e,t,i,n){for(let s=0;s=0;It.G.PrepareUniformsAndSamplersForLight(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],n,t)}}bind(e,t,i){if(!i)return;const n=i.getScene();this.light?It.G.BindLight(this.light,this._lightId,n,e,!0):It.G.BindLights(n,i,e,!0,t.maxSimultaneousLights)}_injectVertexCode(e){const t=this.worldPosition,i=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const n="v_"+t.associatedVariableName;e._emitVaryingFromString(n,"vec4")&&(e.compilationString+=`${n} = ${t.associatedVariableName};\r\n`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${t.associatedVariableName};\r\n`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName};\r\n`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_buildBlock(e){if(super._buildBlock(e),e.target!==dt.Fragment)return void this._injectVertexCode(e);this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);const t=`//${this.name}`,i=this.worldPosition;let n=i.associatedVariableName;this.generateOnlyFragmentCode?(n=e._getFreeVariableName("globalWorldPos"),e._emitFunction("light_globalworldpos",`vec3 ${n};\r\n`,t),e.compilationString+=`${n} = ${i.associatedVariableName}.xyz;\r\n`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${i.associatedVariableName}`:void 0})):n="v_"+n+".xyz",e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("lightsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:n}]}),e._emitFunctionFromInclude("shadowsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:n}]}),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),0===this._lightId&&(e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${n});\r\n`),e.compilationString+="lightingInfo info;\r\n",e.compilationString+="float shadow = 1.;\r\n",e.compilationString+=`float glossiness = ${this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0"} * ${this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0"};\r\n`,e.compilationString+="vec3 diffuseBase = vec3(0., 0., 0.);\r\n",e.compilationString+="vec3 specularBase = vec3(0., 0., 0.);\r\n",e.compilationString+=`vec3 normalW = ${this.worldNormal.associatedVariableName}.xyz;\r\n`),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{repeatKey:"maxSimultaneousLights"});const s=this.diffuseOutput,r=this.specularOutput;return e.compilationString+=this._declareOutput(s,e)+` = diffuseBase${this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:""};\r\n`,r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = specularBase${this.specularColor.isConnected?" * "+this.specularColor.associatedVariableName:""};\r\n`),this.shadow.hasEndpoints&&(e.compilationString+=this._declareOutput(this.shadow,e)+" = shadow;\r\n"),this}serialize(){const e=super.serialize();return e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,this.light&&(e.lightId=this.light.id),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}(0,oe.gn)([At("Generate only fragment code",Et.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:qv._OnGenerateOnlyFragmentCodeChanged}})],qv.prototype,"generateOnlyFragmentCode",void 0),(0,l.H)("BABYLON.LightBlock",qv);class $v extends bt{get texture(){return this._texture}set texture(e){var t;if(this._texture===e)return;const i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:m.l.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}get samplerName(){return this._samplerName}constructor(e){super(e,dt.VertexAndFragment),this.registerOutput("source",ct.Object,dt.VertexAndFragment,new Wv("source",this,vt.Output,$v,"ImageSourceBlock"))}bind(e){this.texture&&e.setTexture(this._samplerName,this.texture)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}getClassName(){return"ImageSourceBlock"}get source(){return this._outputs[0]}_buildBlock(e){return super._buildBlock(e),e.target===dt.Vertex&&(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this)),e._emit2DSampler(this._samplerName),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\r\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\r\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\r\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\r\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\r\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\r\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\r\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\r\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\r\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\r\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\r\n`,e):e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&"VideoTexture"!==this.texture.getClassName()&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!Ni.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Le.Parse(e.texture,t,i))}}(0,l.H)("BABYLON.ImageSourceBlock",$v);(0,l.H)("BABYLON.TextureBlock",class extends bt{get texture(){var e;return this.source.isConnected?(null===(e=this.source.connectedPoint)||void 0===e?void 0:e.ownerBlock).texture:this._texture}set texture(e){var t;if(this._texture===e)return;const i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:m.l.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}get samplerName(){return this._imageSource?this._imageSource.samplerName:this._samplerName}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){var t;if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const e=null!==(t=this.texture.getScene())&&void 0!==t?t:m.l.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){var t;if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const e=null!==(t=this.texture.getScene())&&void 0!==t?t:m.l.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,t?dt.Fragment:dt.VertexAndFragment),this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this._fragmentOnly=t,this.registerInput("uv",ct.AutoDetect,!1,dt.VertexAndFragment),this.registerInput("source",ct.Object,!0,dt.VertexAndFragment,new Wv("source",this,vt.Input,$v,"ImageSourceBlock")),this.registerInput("layer",ct.Float,!0),this.registerInput("lod",ct.Float,!0),this.registerOutput("rgba",ct.Color4,dt.Neutral),this.registerOutput("rgb",ct.Color3,dt.Neutral),this.registerOutput("r",ct.Float,dt.Neutral),this.registerOutput("g",ct.Float,dt.Neutral),this.registerOutput("b",ct.Float,dt.Neutral),this.registerOutput("a",ct.Float,dt.Neutral),this.registerOutput("level",ct.Float,dt.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ct.Vector2|ct.Vector3|ct.Vector4),this._inputs[0]._prioritizeVertex=!t}getClassName(){return"TextureBlock"}get uv(){return this._inputs[0]}get source(){return this._inputs[1]}get layer(){return this._inputs[2]}get lod(){return this._inputs[3]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}get target(){if(this._fragmentOnly)return dt.Fragment;if(!this.uv.isConnected)return dt.VertexAndFragment;if(this.uv.sourceBlock.isInput)return dt.VertexAndFragment;let e=this.uv.connectedPoint;for(;e;){if(e.target===dt.Fragment)return dt.Fragment;if(e.target===dt.Vertex)return dt.VertexAndFragment;if(e.target===dt.Neutral||e.target===dt.VertexAndFragment){const t=e.ownerBlock;if(t.target===dt.Fragment)return dt.Fragment;e=null;for(const i of t.inputs)if(i.connectedPoint){e=i.connectedPoint;break}}}return dt.VertexAndFragment}set target(e){}autoConfigure(e){if(!this.uv.isConnected)if(e.mode===qt.PostProcess){const t=e.getBlockByPredicate((e=>"uv"===e.name));t&&t.connectTo(this)}else{const t=e.mode===qt.Particle?"particle_uv":"uv";let i=e.getInputBlockByPredicate((e=>e.isAttribute&&e.name===t));i||(i=new Bt("uv"),i.setAsAttribute(t)),i.output.connectTo(this.uv)}}initializeDefines(e,t,i){i._areTexturesDirty&&void 0!==this._mainUVDefineName&&i.setValue(this._mainUVDefineName,!1,!0)}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;if(!this.texture||!this.texture.getTextureMatrix)return void(this._isMixed&&(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)));const n=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,n,!0),i.setValue(this._gammaDefineName,s,!0),this._isMixed&&(this.texture.getTextureMatrix().isIdentityAs3x2()?(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)):(i.setValue(this._defineName,!0),null==i[this._mainUVDefineName]&&i.setValue(this._mainUVDefineName,!1,!0)))}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){this.texture&&(this._isMixed&&(e.setFloat(this._textureInfoName,this.texture.level),e.setMatrix(this._textureTransformName,this.texture.getTextureMatrix())),this._imageSource||e.setTexture(this._samplerName,this.texture))}get _isMixed(){return this.target!==dt.Fragment}_injectVertexCode(e){const t=this.uv;if(this._defineName=e._getFreeDefineName("UVTRANSFORM"),this._mainUVDefineName="VMAIN"+t.associatedVariableName.toUpperCase(),this._mainUVName="vMain"+t.associatedVariableName,this._transformedUVName=e._getFreeVariableName("transformedUV"),this._textureTransformName=e._getFreeVariableName("textureTransform"),this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,e._emitVaryingFromString(this._transformedUVName,"vec2",this._defineName),e._emitVaryingFromString(this._mainUVName,"vec2",this._mainUVDefineName),e._emitUniformFromString(this._textureTransformName,"mat4",this._defineName),e.compilationString+=`#ifdef ${this._defineName}\r\n`,e.compilationString+=`${this._transformedUVName} = vec2(${this._textureTransformName} * vec4(${t.associatedVariableName}.xy, 1.0, 0.0));\r\n`,e.compilationString+=`#elif defined(${this._mainUVDefineName})\r\n`,e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\r\n`,e.compilationString+="#endif\r\n",this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name,!0)}}_getUVW(e){var t,i,n;let s=e;if(null!==(n=null===(i=null===(t=this._texture)||void 0===t?void 0:t._texture)||void 0===i?void 0:i.is2DArray)&&void 0!==n&&n){s=`vec3(${e}, ${this.layer.isConnected?this.layer.associatedVariableName:"0"})`}return s}get _samplerFunc(){return this.lod.isConnected?"texture2DLodEXT":"texture2D"}get _samplerLodSuffix(){return this.lod.isConnected?`, ${this.lod.associatedVariableName}`:""}_generateTextureLookup(e){const t=this.samplerName;e.compilationString+=`#ifdef ${this._defineName}\r\n`,e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${t}, ${this._getUVW(this._transformedUVName)}${this._samplerLodSuffix});\r\n`,e.compilationString+=`#elif defined(${this._mainUVDefineName})\r\n`,e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${t}, ${this._getUVW(this._mainUVName?this._mainUVName:this.uv.associatedVariableName)}${this._samplerLodSuffix});\r\n`,e.compilationString+="#endif\r\n"}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===dt.Fragment)return;this._generateTextureLookup(e)}else this.uv.ownerBlock.target!==dt.Fragment?this._generateTextureLookup(e):e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${this.samplerName}, ${this._getUVW(i.associatedVariableName)}${this._samplerLodSuffix});\r\n`}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName}\n ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n #endif\n `),e.compilationString+=`#ifdef ${this._gammaDefineName}\n ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n #endif\n `)}_writeOutput(e,t,i,n=!1){if(n){if(e.target===dt.Fragment)return;return e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`,void this._generateConversionCode(e,t,i)}if(this.uv.ownerBlock.target===dt.Fragment)return e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`,void this._generateConversionCode(e,t,i);let s="";this.disableLevelMultiplication||(s=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${s};\r\n`,this._generateConversionCode(e,t,i)}_buildBlock(e){var t,i,n,s;if(super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,(e.target===dt.Vertex||this._fragmentOnly||e.target===dt.Fragment)&&(this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA")),(!this._isMixed&&e.target===dt.Fragment||this._isMixed&&e.target===dt.Vertex)&&(this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),(null===(i=null===(t=this._texture)||void 0===t?void 0:t._texture)||void 0===i?void 0:i.is2DArray)?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this)),e.target!==dt.Fragment)return void this._injectVertexCode(e);if(!this._outputs.some((e=>e.isConnectedInFragmentShader)))return;this._isMixed&&!this._imageSource&&((null===(s=null===(n=this._texture)||void 0===n?void 0:n._texture)||void 0===s?void 0:s.is2DArray)?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName));const r=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",r),this._isMixed&&e._emitUniformFromString(this._textureInfoName,"float"),this._writeTextureRead(e);for(const o of this._outputs)o.hasEndpoints&&"level"!==o.name&&this._writeOutput(e,o,o.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\r\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\r\n`,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\r\n`,this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\r\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\r\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\r\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\r\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\r\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\r\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\r\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\r\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\r\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\r\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\r\n`,e):e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.fragmentOnly=this._fragmentOnly,e.disableLevelMultiplication=this.disableLevelMultiplication,this.hasImageSource||!this.texture||this.texture.isRenderTarget||"VideoTexture"===this.texture.getClassName()||(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this._fragmentOnly=!!e.fragmentOnly,this.disableLevelMultiplication=!!e.disableLevelMultiplication,e.texture&&!Ni.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Le.Parse(e.texture,t,i))}});class Qv extends bt{get texture(){return this._texture}set texture(e){var t;if(this._texture===e)return;const i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:m.l.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}static _OnGenerateOnlyFragmentCodeChanged(e,t){return e._onGenerateOnlyFragmentCodeChanged()}_onGenerateOnlyFragmentCodeChanged(){return this._setTarget(),!0}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?dt.Fragment:dt.VertexAndFragment)}constructor(e){super(e,dt.VertexAndFragment),this.generateOnlyFragmentCode=!1}getClassName(){return"ReflectionTextureBaseBlock"}_getTexture(){return this.texture}autoConfigure(e){if(!this.position.isConnected){let t=e.getInputBlockByPredicate((e=>e.isAttribute&&"position"===e.name));t||(t=new Bt("position"),t.setAsAttribute()),t.output.connectTo(this.position)}if(!this.world.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===Pt.World));t||(t=new Bt("world"),t.setAsSystemValue(Pt.World)),t.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===Pt.View));t||(t=new Bt("view"),t.setAsSystemValue(Pt.View)),t.output.connectTo(this.view)}}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const n=this._getTexture();n&&n.getTextureMatrix&&(i.setValue(this._define3DName,n.isCube,!0),i.setValue(this._defineLocalCubicName,!!n.boundingBoxSize,!0),i.setValue(this._defineExplicitName,0===n.coordinatesMode,!0),i.setValue(this._defineSkyboxName,5===n.coordinatesMode,!0),i.setValue(this._defineCubicName,3===n.coordinatesMode||6===n.coordinatesMode,!0),i.setValue("INVERTCUBICMAP",6===n.coordinatesMode,!0),i.setValue(this._defineSphericalName,1===n.coordinatesMode,!0),i.setValue(this._definePlanarName,2===n.coordinatesMode,!0),i.setValue(this._defineProjectionName,4===n.coordinatesMode,!0),i.setValue(this._defineEquirectangularName,7===n.coordinatesMode,!0),i.setValue(this._defineEquirectangularFixedName,8===n.coordinatesMode,!0),i.setValue(this._defineMirroredEquirectangularFixedName,9===n.coordinatesMode,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i){const n=this._getTexture();if(i&&n&&(e.setMatrix(this._reflectionMatrixName,n.getReflectionTextureMatrix()),n.isCube?e.setTexture(this._cubeSamplerName,n):e.setTexture(this._2DSamplerName,n),n.boundingBoxSize)){const t=n;e.setVector3(this._reflectionPositionName,t.boundingBoxPosition),e.setVector3(this._reflectionSizeName,t.boundingBoxSize)}}handleVertexSide(e){if(this.generateOnlyFragmentCode&&e.target===dt.Vertex)return"";this._define3DName=e._getFreeDefineName("REFLECTIONMAP_3D"),this._defineCubicName=e._getFreeDefineName("REFLECTIONMAP_CUBIC"),this._defineSphericalName=e._getFreeDefineName("REFLECTIONMAP_SPHERICAL"),this._definePlanarName=e._getFreeDefineName("REFLECTIONMAP_PLANAR"),this._defineProjectionName=e._getFreeDefineName("REFLECTIONMAP_PROJECTION"),this._defineExplicitName=e._getFreeDefineName("REFLECTIONMAP_EXPLICIT"),this._defineEquirectangularName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR"),this._defineLocalCubicName=e._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC"),this._defineMirroredEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"),this._defineEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED"),this._defineSkyboxName=e._getFreeDefineName("REFLECTIONMAP_SKYBOX"),this._defineOppositeZ=e._getFreeDefineName("REFLECTIONMAP_OPPOSITEZ"),this._reflectionMatrixName=e._getFreeVariableName("reflectionMatrix"),e._emitUniformFromString(this._reflectionMatrixName,"mat4");let t="";this._worldPositionNameInFragmentOnlyMode=e._getFreeVariableName("worldPosition");const i=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName;return(this.generateOnlyFragmentCode||e._emitVaryingFromString(i,"vec4"))&&(t+=`${this.generateOnlyFragmentCode?"vec4 ":""}${i} = ${this.worldPosition.associatedVariableName};\r\n`),this._positionUVWName=e._getFreeVariableName("positionUVW"),this._directionWName=e._getFreeVariableName("directionW"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._positionUVWName,"vec3",this._defineSkyboxName))&&(t+=`#ifdef ${this._defineSkyboxName}\r\n`,t+=`${this.generateOnlyFragmentCode?"vec3 ":""}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz;\r\n`,t+="#endif\r\n"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._directionWName,"vec3",`defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`))&&(t+=`#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})\r\n`,t+=`${this.generateOnlyFragmentCode?"vec3 ":""}${this._directionWName} = normalize(vec3(${this.world.associatedVariableName} * vec4(${this.position.associatedVariableName}.xyz, 0.0)));\r\n`,t+="#endif\r\n"),t}handleFragmentSideInits(e){e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),e._samplerDeclaration+=`#ifdef ${this._define3DName}\r\n`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName};\r\n`,e._samplerDeclaration+="#else\r\n",e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName};\r\n`,e._samplerDeclaration+="#endif\r\n",e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunction("ReciprocalPI","#define RECIPROCAL_PI2 0.15915494",""),e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("reflectionFunction",t,{replaceStrings:[{search:/vec3 computeReflectionCoords/g,replace:"void DUMMYFUNC"}]}),this._reflectionColorName=e._getFreeVariableName("reflectionColor"),this._reflectionVectorName=e._getFreeVariableName("reflectionUVW"),this._reflectionCoordsName=e._getFreeVariableName("reflectionCoords"),this._reflectionPositionName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionPositionName,"vec3"),this._reflectionSizeName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionSizeName,"vec3")}handleFragmentSideCodeReflectionCoords(e,t,i=!1,n=!1){t||(t=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:`v_${this.worldPosition.associatedVariableName}`);const s=this._reflectionMatrixName,r=`normalize(${this._directionWName})`,o=`${this._positionUVWName}`,a=`${this.cameraPosition.associatedVariableName}`,l=`${this.view.associatedVariableName}`;e+=".xyz";let h=`\n #ifdef ${this._defineMirroredEquirectangularFixedName}\n vec3 ${this._reflectionVectorName} = computeMirroredFixedEquirectangularCoords(${t}, ${e}, ${r});\n #endif\n\n #ifdef ${this._defineEquirectangularFixedName}\n vec3 ${this._reflectionVectorName} = computeFixedEquirectangularCoords(${t}, ${e}, ${r});\n #endif\n\n #ifdef ${this._defineEquirectangularName}\n vec3 ${this._reflectionVectorName} = computeEquirectangularCoords(${t}, ${e}, ${a}.xyz, ${s});\n #endif\n\n #ifdef ${this._defineSphericalName}\n vec3 ${this._reflectionVectorName} = computeSphericalCoords(${t}, ${e}, ${l}, ${s});\n #endif\n\n #ifdef ${this._definePlanarName}\n vec3 ${this._reflectionVectorName} = computePlanarCoords(${t}, ${e}, ${a}.xyz, ${s});\n #endif\n\n #ifdef ${this._defineCubicName}\n #ifdef ${this._defineLocalCubicName}\n vec3 ${this._reflectionVectorName} = computeCubicLocalCoords(${t}, ${e}, ${a}.xyz, ${s}, ${this._reflectionSizeName}, ${this._reflectionPositionName});\n #else\n vec3 ${this._reflectionVectorName} = computeCubicCoords(${t}, ${e}, ${a}.xyz, ${s});\n #endif\n #endif\n\n #ifdef ${this._defineProjectionName}\n vec3 ${this._reflectionVectorName} = computeProjectionCoords(${t}, ${l}, ${s});\n #endif\n\n #ifdef ${this._defineSkyboxName}\n vec3 ${this._reflectionVectorName} = computeSkyBoxCoords(${o}, ${s});\n #endif\n\n #ifdef ${this._defineExplicitName}\n vec3 ${this._reflectionVectorName} = vec3(0, 0, 0);\n #endif\r\n`;return n||(h+=`#ifdef ${this._defineOppositeZ}\n ${this._reflectionVectorName}.z *= -1.0;\n #endif\r\n`),i||(h+=`\n #ifdef ${this._define3DName}\n vec3 ${this._reflectionCoordsName} = ${this._reflectionVectorName};\n #else\n vec2 ${this._reflectionCoordsName} = ${this._reflectionVectorName}.xy;\n #ifdef ${this._defineProjectionName}\n ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z;\n #endif\n ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y;\n #endif\r\n`),h}handleFragmentSideCodeReflectionColor(e,t=".rgb"){let i=`${"vec"+(0===t.length?"4":t.length-1)} ${this._reflectionColorName};\n #ifdef ${this._define3DName}\r\n`;return i+=e?`${this._reflectionColorName} = textureCubeLodEXT(${this._cubeSamplerName}, ${this._reflectionVectorName}, ${e})${t};\r\n`:`${this._reflectionColorName} = textureCube(${this._cubeSamplerName}, ${this._reflectionVectorName})${t};\r\n`,i+="\n #else\r\n",i+=e?`${this._reflectionColorName} = texture2DLodEXT(${this._2DSamplerName}, ${this._reflectionCoordsName}, ${e})${t};\r\n`:`${this._reflectionColorName} = texture2D(${this._2DSamplerName}, ${this._reflectionCoordsName})${t};\r\n`,i+="#endif\r\n",i}writeOutputs(e,t){let i="";if(e.target===dt.Fragment)for(const n of this._outputs)n.hasEndpoints&&(i+=`${this._declareOutput(n,e)} = ${t}.${n.name};\r\n`);return i}_buildBlock(e){return super._buildBlock(e),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();if(!this.texture)return e;if(this.texture.isCube){const t=this.texture.forcedExtension;e+=`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}", undefined, undefined, ${this.texture.noMipmap}, null, undefined, undefined, undefined, ${this.texture._prefiltered}, ${t?'"'+t+'"':"null"});\r\n`}else e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null);\r\n`;return e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\r\n`,e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!Ni.IgnoreTexturesAtLoadTime&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=yp.Parse(e.texture,t,i):this.texture=Le.Parse(e.texture,t,i)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}(0,oe.gn)([At("Generate only fragment code",Et.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:Qv._OnGenerateOnlyFragmentCodeChanged}})],Qv.prototype,"generateOnlyFragmentCode",void 0),(0,l.H)("BABYLON.ReflectionTextureBaseBlock",Qv);(0,l.H)("BABYLON.ReflectionTextureBlock",class extends Qv{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,console.error("The position input must not be connected to be able to switch!"),!1):this.worldPosition.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,console.error("The worldPosition input must not be connected to be able to switch!"),!1):(this._setTarget(),!0)}_setTarget(){super._setTarget(),this.getInputByName("position").target=this.generateOnlyFragmentCode?dt.Fragment:dt.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?dt.Fragment:dt.Vertex}constructor(e){super(e),this.registerInput("position",ct.AutoDetect,!1,dt.Vertex),this.registerInput("worldPosition",ct.Vector4,!1,dt.Vertex),this.registerInput("worldNormal",ct.Vector4,!1,dt.Fragment),this.registerInput("world",ct.Matrix,!1,dt.Vertex),this.registerInput("cameraPosition",ct.Vector3,!1,dt.Fragment),this.registerInput("view",ct.Matrix,!1,dt.Fragment),this.registerOutput("rgb",ct.Color3,dt.Fragment),this.registerOutput("rgba",ct.Color4,dt.Fragment),this.registerOutput("r",ct.Float,dt.Fragment),this.registerOutput("g",ct.Float,dt.Fragment),this.registerOutput("b",ct.Float,dt.Fragment),this.registerOutput("a",ct.Float,dt.Fragment),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ct.Color3|ct.Vector3|ct.Vector4)}getClassName(){return"ReflectionTextureBlock"}get position(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get world(){return this._inputs[3]}get cameraPosition(){return this._inputs[4]}get view(){return this._inputs[5]}get rgb(){return this._outputs[0]}get rgba(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}autoConfigure(e){if(super.autoConfigure(e),!this.cameraPosition.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===Pt.CameraPosition));t||(t=new Bt("cameraPosition"),t.setAsSystemValue(Pt.CameraPosition)),t.output.connectTo(this.cameraPosition)}}_buildBlock(e){if(super._buildBlock(e),!this.texture)return e.compilationString+=this.writeOutputs(e,"vec4(0.)"),this;if(e.target!==dt.Fragment)return e.compilationString+=this.handleVertexSide(e),this;this.generateOnlyFragmentCode&&(e.compilationString+=this.handleVertexSide(e)),this.handleFragmentSideInits(e);const t=e._getFreeVariableName("normalWUnit");return e.compilationString+=`vec4 ${t} = normalize(${this.worldNormal.associatedVariableName});\r\n`,e.compilationString+=this.handleFragmentSideCodeReflectionCoords(t),e.compilationString+=this.handleFragmentSideCodeReflectionColor(void 0,""),e.compilationString+=this.writeOutputs(e,this._reflectionColorName),this}});class Zv extends bt{constructor(e){super(e,dt.VertexAndFragment),this.useNonLinearDepth=!1,this.storeCameraSpaceZ=!1,this.force32itsFloat=!1,this._isUnique=!0,this.registerInput("uv",ct.AutoDetect,!1,dt.VertexAndFragment),this.registerOutput("depth",ct.Float,dt.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ct.Vector2|ct.Vector3|ct.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"SceneDepthBlock"}get uv(){return this._inputs[0]}get depth(){return this._outputs[0]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return this.uv.isConnected?this.uv.sourceBlock.isInput?dt.VertexAndFragment:dt.Fragment:dt.VertexAndFragment}_getTexture(e){return e.enableDepthRenderer(void 0,this.useNonLinearDepth,this.force32itsFloat,void 0,this.storeCameraSpaceZ).getDepthMap()}bind(e,t){const i=this._getTexture(t.getScene());e.setTexture(this._samplerName,i)}_injectVertexCode(e){const t=this.uv;if(t.connectedPoint.ownerBlock.isInput){t.connectedPoint.ownerBlock.isAttribute||e._emitUniformFromString(t.associatedVariableName,"vec"+(t.type===ct.Vector3?"3":t.type===ct.Vector4?"4":"2"))}if(this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy;\r\n`,this._outputs.some((e=>e.isConnectedInVertexShader))){this._writeTextureRead(e,!0);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,"r",!0)}}_writeTextureRead(e,t=!1){const i=this.uv;if(t){if(e.target===dt.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy);\r\n`}else this.uv.ownerBlock.target!==dt.Fragment?e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\r\n`:e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy);\r\n`}_writeOutput(e,t,i,n=!1){if(n){if(e.target===dt.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`}else this.uv.ownerBlock.target,dt.Fragment,e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i};\r\n`}_buildBlock(e){if(super._buildBlock(e),this._samplerName=e._getFreeVariableName(this.name+"Sampler"),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e.sharedData.bindableBlocks.indexOf(this)<0&&e.sharedData.bindableBlocks.push(this),e.target!==dt.Fragment)return e._emit2DSampler(this._samplerName),void this._injectVertexCode(e);if(this._outputs.some((e=>e.isConnectedInFragmentShader))){e._emit2DSampler(this._samplerName),this._writeTextureRead(e);for(const t of this._outputs)t.hasEndpoints&&this._writeOutput(e,t,"r");return this}}serialize(){const e=super.serialize();return e.useNonLinearDepth=this.useNonLinearDepth,e.storeCameraSpaceZ=this.storeCameraSpaceZ,e.force32itsFloat=this.force32itsFloat,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.useNonLinearDepth=e.useNonLinearDepth,this.storeCameraSpaceZ=!!e.storeCameraSpaceZ,this.force32itsFloat=e.force32itsFloat}}(0,oe.gn)([At("Use non linear depth",Et.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{const i=t;let n=!1;return i.useNonLinearDepth&&(i.storeCameraSpaceZ=!1,n=!0),e.disableDepthRenderer(),n}}})],Zv.prototype,"useNonLinearDepth",void 0),(0,oe.gn)([At("Store Camera space Z",Et.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{const i=t;let n=!1;return i.storeCameraSpaceZ&&(i.useNonLinearDepth=!1,n=!0),e.disableDepthRenderer(),n}}})],Zv.prototype,"storeCameraSpaceZ",void 0),(0,oe.gn)([At("Force 32 bits float",Et.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:e=>e.disableDepthRenderer()}})],Zv.prototype,"force32itsFloat",void 0),(0,l.H)("BABYLON.SceneDepthBlock",Zv);(0,l.H)("BABYLON.ClipPlanesBlock",class extends bt{constructor(e){super(e,dt.VertexAndFragment,!0),this.registerInput("worldPosition",ct.Vector4,!1)}getClassName(){return"ClipPlanesBlock"}initialize(e){e._excludeVariableName("vClipPlane"),e._excludeVariableName("fClipDistance"),e._excludeVariableName("vClipPlane2"),e._excludeVariableName("fClipDistance2"),e._excludeVariableName("vClipPlane3"),e._excludeVariableName("fClipDistance3"),e._excludeVariableName("vClipPlane4"),e._excludeVariableName("fClipDistance4"),e._excludeVariableName("vClipPlane5"),e._excludeVariableName("fClipDistance5"),e._excludeVariableName("vClipPlane6"),e._excludeVariableName("fClipDistance6")}get worldPosition(){return this._inputs[0]}get target(){return dt.VertexAndFragment}set target(e){}prepareDefines(e,t,i){var n,s,r,o,a,l;const h=e.getScene(),c=!!(null!==(n=t.clipPlane)&&void 0!==n?n:h.clipPlane),d=!!(null!==(s=t.clipPlane2)&&void 0!==s?s:h.clipPlane2),u=!!(null!==(r=t.clipPlane3)&&void 0!==r?r:h.clipPlane3),p=!!(null!==(o=t.clipPlane4)&&void 0!==o?o:h.clipPlane4),f=!!(null!==(a=t.clipPlane5)&&void 0!==a?a:h.clipPlane5),_=!!(null!==(l=t.clipPlane6)&&void 0!==l?l:h.clipPlane6);i.setValue("CLIPPLANE",c,!0),i.setValue("CLIPPLANE2",d,!0),i.setValue("CLIPPLANE3",u,!0),i.setValue("CLIPPLANE4",p,!0),i.setValue("CLIPPLANE5",f,!0),i.setValue("CLIPPLANE6",_,!0)}bind(e,t,i){if(!i)return;const n=i.getScene();(0,ua.an)(e,t,n)}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;if(e.target!==dt.Fragment){const i=this.worldPosition;return e._emitFunctionFromInclude("clipPlaneVertexDeclaration",t,{replaceStrings:[{search:/uniform vec4 vClipPlane\d*;/g,replace:""}]}),e.compilationString+=e._emitCodeFromInclude("clipPlaneVertex",t,{replaceStrings:[{search:/worldPos/g,replace:i.associatedVariableName}]}),e._emitUniformFromString("vClipPlane","vec4"),e._emitUniformFromString("vClipPlane2","vec4"),e._emitUniformFromString("vClipPlane3","vec4"),e._emitUniformFromString("vClipPlane4","vec4"),e._emitUniformFromString("vClipPlane5","vec4"),void e._emitUniformFromString("vClipPlane6","vec4")}return e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e._emitFunctionFromInclude("clipPlaneFragmentDeclaration",t),e.compilationString+=e._emitCodeFromInclude("clipPlaneFragment",t),this}});(0,l.H)("BABYLON.AddBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("left",ct.AutoDetect),this.registerInput("right",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].acceptedConnectionPointTypes.push(ct.Float),this._inputs[1].acceptedConnectionPointTypes.push(ct.Float)}getClassName(){return"AddBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} + ${this.right.associatedVariableName};\r\n`,this}});(0,l.H)("BABYLON.ScaleBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("input",ct.AutoDetect),this.registerInput("factor",ct.Float),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ScaleBlock"}get input(){return this._inputs[0]}get factor(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} * ${this.factor.associatedVariableName};\r\n`,this}});class Jv extends bt{constructor(e){super(e,dt.Neutral),this.minimum=0,this.maximum=1,this.registerInput("value",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ClampBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = clamp(${this.value.associatedVariableName}, ${this._writeFloat(this.minimum)}, ${this._writeFloat(this.maximum)});\r\n`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum};\r\n`;return e+=`${this._codeVariableName}.maximum = ${this.maximum};\r\n`,e}serialize(){const e=super.serialize();return e.minimum=this.minimum,e.maximum=this.maximum,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.minimum=e.minimum,this.maximum=e.maximum}}(0,oe.gn)([At("Minimum",Et.Float)],Jv.prototype,"minimum",void 0),(0,oe.gn)([At("Maximum",Et.Float)],Jv.prototype,"maximum",void 0),(0,l.H)("BABYLON.ClampBlock",Jv);(0,l.H)("BABYLON.CrossBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("left",ct.AutoDetect),this.registerInput("right",ct.AutoDetect),this.registerOutput("output",ct.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(ct.Float),this._inputs[0].excludedConnectionPointTypes.push(ct.Matrix),this._inputs[0].excludedConnectionPointTypes.push(ct.Vector2),this._inputs[1].excludedConnectionPointTypes.push(ct.Float),this._inputs[1].excludedConnectionPointTypes.push(ct.Matrix),this._inputs[1].excludedConnectionPointTypes.push(ct.Vector2)}getClassName(){return"CrossBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = cross(${this.left.associatedVariableName}.xyz, ${this.right.associatedVariableName}.xyz);\r\n`,this}});(0,l.H)("BABYLON.CustomBlock",class extends bt{get options(){return this._options}set options(e){this._deserializeOptions(e)}constructor(e){super(e)}getClassName(){return"CustomBlock"}_buildBlock(e){super._buildBlock(e);let t=this._code,i=this._options.functionName;this._inputs.forEach((n=>{const s=new RegExp("\\{TYPE_"+n.name+"\\}","gm"),r=e._getGLType(n.type);t=t.replace(s,r),i=i.replace(s,r)})),this._outputs.forEach((n=>{const s=new RegExp("\\{TYPE_"+n.name+"\\}","gm"),r=e._getGLType(n.type);t=t.replace(s,r),i=i.replace(s,r)})),e._emitFunction(i,t,""),this._outputs.forEach((t=>{e.compilationString+=this._declareOutput(t,e)+";\r\n"})),e.compilationString+=i+"(";let n=!1;return this._inputs.forEach(((t,i)=>{var s,r,o;i>0&&(e.compilationString+=", "),this._inputSamplers&&-1!==this._inputSamplers.indexOf(t.name)?e.compilationString+=null!==(o=null===(r=null===(s=t.connectedPoint)||void 0===s?void 0:s.ownerBlock)||void 0===r?void 0:r.samplerName)&&void 0!==o?o:t.associatedVariableName:e.compilationString+=t.associatedVariableName,n=!0})),this._outputs.forEach(((t,i)=>{(i>0||n)&&(e.compilationString+=", "),e.compilationString+=t.associatedVariableName})),e.compilationString+=");\r\n",this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.options = ${JSON.stringify(this._options)};\r\n`,e}serialize(){const e=super.serialize();return e.options=this._options,e}_deserialize(e,t,i){this._deserializeOptions(e.options),super._deserialize(e,t,i)}_deserializeOptions(e){var t,i,n;this._options=e,this._code=e.code.join("\r\n")+"\r\n",this.name=this.name||e.name,this.target=dt[e.target],null===(t=e.inParameters)||void 0===t||t.forEach(((e,t)=>{const i=ct[e.type];"sampler2D"===e.type||"samplerCube"===e.type?(this._inputSamplers=this._inputSamplers||[],this._inputSamplers.push(e.name),this.registerInput(e.name,ct.Object,!0,dt.VertexAndFragment,new Wv(e.name,this,vt.Input,$v,"ImageSourceBlock"))):this.registerInput(e.name,i),Object.defineProperty(this,e.name,{get:function(){return this._inputs[t]},enumerable:!0,configurable:!0})})),null===(i=e.outParameters)||void 0===i||i.forEach(((e,t)=>{this.registerOutput(e.name,ct[e.type]),Object.defineProperty(this,e.name,{get:function(){return this._outputs[t]},enumerable:!0,configurable:!0}),"BasedOnInput"===e.type&&(this._outputs[t]._typeConnectionSource=this._findInputByName(e.typeFromInput)[0])})),null===(n=e.inLinkedConnectionTypes)||void 0===n||n.forEach((e=>{this._linkConnectionTypes(this._findInputByName(e.input1)[1],this._findInputByName(e.input2)[1])}))}_findInputByName(e){if(!e)return null;for(let t=0;te.systemValue===Pt.CameraPosition));t||(t=new Bt("cameraPosition"),t.setAsSystemValue(Pt.CameraPosition)),t.output.connectTo(this.cameraPosition)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = normalize(${this.cameraPosition.associatedVariableName} - ${this.worldPosition.associatedVariableName}.xyz);\r\n`,this}}(0,l.H)("BABYLON.ViewDirectionBlock",tT);(0,l.H)("BABYLON.FresnelBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("worldNormal",ct.Vector4),this.registerInput("viewDirection",ct.Vector3),this.registerInput("bias",ct.Float),this.registerInput("power",ct.Float),this.registerOutput("fresnel",ct.Float)}getClassName(){return"FresnelBlock"}get worldNormal(){return this._inputs[0]}get viewDirection(){return this._inputs[1]}get bias(){return this._inputs[2]}get power(){return this._inputs[3]}get fresnel(){return this._outputs[0]}autoConfigure(e){if(!this.viewDirection.isConnected){const t=new tT("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){const e=new Bt("bias");e.value=0,e.output.connectTo(this.bias)}if(!this.power.isConnected){const e=new Bt("power");e.value=1,e.output.connectTo(this.power)}}_buildBlock(e){super._buildBlock(e);const t=`//${this.name}`;return e._emitFunctionFromInclude("fresnelFunction",t,{removeIfDef:!0}),e.compilationString+=this._declareOutput(this.fresnel,e)+` = computeFresnelTerm(${this.viewDirection.associatedVariableName}.xyz, ${this.worldNormal.associatedVariableName}.xyz, ${this.bias.associatedVariableName}, ${this.power.associatedVariableName});\r\n`,this}});(0,l.H)("BABYLON.MaxBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("left",ct.AutoDetect),this.registerInput("right",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MaxBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = max(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\r\n`,this}});(0,l.H)("BABYLON.MinBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("left",ct.AutoDetect),this.registerInput("right",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MinBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = min(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\r\n`,this}});(0,l.H)("BABYLON.DistanceBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("left",ct.AutoDetect),this.registerInput("right",ct.AutoDetect),this.registerOutput("output",ct.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(ct.Float),this._inputs[0].excludedConnectionPointTypes.push(ct.Matrix),this._inputs[1].excludedConnectionPointTypes.push(ct.Float),this._inputs[1].excludedConnectionPointTypes.push(ct.Matrix)}getClassName(){return"DistanceBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = length(${this.left.associatedVariableName} - ${this.right.associatedVariableName});\r\n`,this}});(0,l.H)("BABYLON.LengthBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("value",ct.AutoDetect),this.registerOutput("output",ct.Float),this._inputs[0].excludedConnectionPointTypes.push(ct.Float),this._inputs[0].excludedConnectionPointTypes.push(ct.Matrix)}getClassName(){return"LengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = length(${this.value.associatedVariableName});\r\n`,this}});(0,l.H)("BABYLON.NegateBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("value",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NegateBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = -1.0 * ${this.value.associatedVariableName};\r\n`,this}});(0,l.H)("BABYLON.PowBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("value",ct.AutoDetect),this.registerInput("power",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"PowBlock"}get value(){return this._inputs[0]}get power(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = pow(${this.value.associatedVariableName}, ${this.power.associatedVariableName});\r\n`,this}});(0,l.H)("BABYLON.RandomNumberBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("seed",ct.AutoDetect),this.registerOutput("output",ct.Float),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ct.Vector2|ct.Vector3|ct.Vector4|ct.Color3|ct.Color4)}getClassName(){return"RandomNumberBlock"}get seed(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",i),e.compilationString+=this._declareOutput(t,e)+` = getRand(${this.seed.associatedVariableName}.xy);\r\n`,this}});(0,l.H)("BABYLON.ArcTan2Block",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("x",ct.Float),this.registerInput("y",ct.Float),this.registerOutput("output",ct.Float)}getClassName(){return"ArcTan2Block"}get x(){return this._inputs[0]}get y(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = atan(${this.x.associatedVariableName}, ${this.y.associatedVariableName});\r\n`,this}});(0,l.H)("BABYLON.SmoothStepBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("value",ct.AutoDetect),this.registerInput("edge0",ct.Float),this.registerInput("edge1",ct.Float),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"SmoothStepBlock"}get value(){return this._inputs[0]}get edge0(){return this._inputs[1]}get edge1(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = smoothstep(${this.edge0.associatedVariableName}, ${this.edge1.associatedVariableName}, ${this.value.associatedVariableName});\r\n`,this}});(0,l.H)("BABYLON.ReciprocalBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("input",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ReciprocalBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return this.input.type===ct.Matrix?e.compilationString+=this._declareOutput(t,e)+` = inverse(${this.input.associatedVariableName});\r\n`:e.compilationString+=this._declareOutput(t,e)+` = 1. / ${this.input.associatedVariableName};\r\n`,this}});(0,l.H)("BABYLON.ReplaceColorBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("value",ct.AutoDetect),this.registerInput("reference",ct.AutoDetect),this.registerInput("distance",ct.Float),this.registerInput("replacement",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(ct.Float),this._inputs[0].excludedConnectionPointTypes.push(ct.Matrix),this._inputs[1].excludedConnectionPointTypes.push(ct.Float),this._inputs[1].excludedConnectionPointTypes.push(ct.Matrix),this._inputs[3].excludedConnectionPointTypes.push(ct.Float),this._inputs[3].excludedConnectionPointTypes.push(ct.Matrix)}getClassName(){return"ReplaceColorBlock"}get value(){return this._inputs[0]}get reference(){return this._inputs[1]}get distance(){return this._inputs[2]}get replacement(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+";\r\n",e.compilationString+=`if (length(${this.value.associatedVariableName} - ${this.reference.associatedVariableName}) < ${this.distance.associatedVariableName}) {\r\n`,e.compilationString+=`${t.associatedVariableName} = ${this.replacement.associatedVariableName};\r\n`,e.compilationString+="} else {\r\n",e.compilationString+=`${t.associatedVariableName} = ${this.value.associatedVariableName};\r\n`,e.compilationString+="}\r\n",this}});var iT;(0,l.H)("BABYLON.PosterizeBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("value",ct.AutoDetect),this.registerInput("steps",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(ct.Matrix),this._inputs[1].excludedConnectionPointTypes.push(ct.Matrix)}getClassName(){return"PosterizeBlock"}get value(){return this._inputs[0]}get steps(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = floor(${this.value.associatedVariableName} / (1.0 / ${this.steps.associatedVariableName})) * (1.0 / ${this.steps.associatedVariableName});\r\n`,this}}),function(e){e[e.SawTooth=0]="SawTooth",e[e.Square=1]="Square",e[e.Triangle=2]="Triangle"}(iT||(iT={}));(0,l.H)("BABYLON.WaveBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.kind=iT.SawTooth,this.registerInput("input",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(ct.Matrix)}getClassName(){return"WaveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];switch(this.kind){case iT.SawTooth:e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName});\r\n`;break;case iT.Square:e.compilationString+=this._declareOutput(t,e)+` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName}));\r\n`;break;case iT.Triangle:e.compilationString+=this._declareOutput(t,e)+` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0;\r\n`}return this}serialize(){const e=super.serialize();return e.kind=this.kind,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.kind=e.kind}});class nT{get step(){return this._step}set step(e){this._step=e}get color(){return this._color}set color(e){this._color=e}constructor(e,t){this.step=e,this.color=t}}(0,l.H)("BABYLON.GradientBlock",class extends bt{colorStepsUpdated(){this.onValueChangedObservable.notifyObservers(this)}constructor(e){super(e,dt.Neutral),this.colorSteps=[new nT(0,a.Wo.Black()),new nT(1,a.Wo.White())],this.onValueChangedObservable=new r.y$,this.registerInput("gradient",ct.AutoDetect),this.registerOutput("output",ct.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ct.Float|ct.Vector2|ct.Vector3|ct.Vector4|ct.Color3|ct.Color4)}getClassName(){return"GradientBlock"}get gradient(){return this._inputs[0]}get output(){return this._outputs[0]}_writeColorConstant(e){const t=this.colorSteps[e];return`vec3(${t.color.r}, ${t.color.g}, ${t.color.b})`}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];if(!this.colorSteps.length||!this.gradient.connectedPoint)return void(e.compilationString+=this._declareOutput(t,e)+" = vec3(0., 0., 0.);\r\n");const i=e._getFreeVariableName("gradientTempColor"),n=e._getFreeVariableName("gradientTempPosition");e.compilationString+=`vec3 ${i} = ${this._writeColorConstant(0)};\r\n`,e.compilationString+=`float ${n};\r\n`;let s=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==ct.Float&&(s+=".x");for(let r=1;re.systemValue===Pt.View));t||(t=new Bt("view"),t.setAsSystemValue(Pt.View)),t.output.connectTo(this.view)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const n=this._getTexture(),s=n&&n.getTextureMatrix;i.setValue("SS_REFRACTION",s,!0),s&&(i.setValue(this._define3DName,n.isCube,!0),i.setValue(this._defineLODRefractionAlpha,n.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularRefraction,n.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem&&n.isCube?!n.invertZ:n.invertZ,!0),i.setValue("SS_LINKREFRACTIONTOTRANSPARENCY",this.linkRefractionWithTransparency,!0),i.setValue("SS_GAMMAREFRACTION",n.gammaSpace,!0),i.setValue("SS_RGBDREFRACTION",n.isRGBD,!0),i.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC",!!n.boundingBoxSize,!0),i.setValue("SS_USE_THICKNESS_AS_DEPTH",this.useThicknessAsDepth,!0))}isReady(){const e=this._getTexture();return!(e&&!e.isReadyOrNotBlocking())}bind(e,t,i){var n,s,r,o;super.bind(e,t,i);const a=this._getTexture();if(!a)return;a.isCube?e.setTexture(this._cubeSamplerName,a):e.setTexture(this._2DSamplerName,a),e.setMatrix(this._refractionMatrixName,a.getRefractionTextureMatrix());let l=1;a.isCube||a.depth&&(l=a.depth);const h=null!==(o=null!==(s=null===(n=this.volumeIndexOfRefraction.connectInputBlock)||void 0===n?void 0:n.value)&&void 0!==s?s:null===(r=this.indexOfRefractionConnectionPoint.connectInputBlock)||void 0===r?void 0:r.value)&&void 0!==o?o:1.5;e.setFloat4(this._vRefractionInfosName,a.level,1/h,l,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,a.getSize().width,a.lodGenerationScale,a.lodGenerationOffset,1/h);const c=a.getSize().width;if(e.setFloat2(this._vRefractionFilteringInfoName,c,S.R.Log2(c)),a.boundingBoxSize){const t=a;e.setVector3("vRefractionPosition",t.boundingBoxPosition),e.setVector3("vRefractionSize",t.boundingBoxSize)}}getCode(e){return e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),this._define3DName=e._getFreeDefineName("SS_REFRACTIONMAP_3D"),e._samplerDeclaration+=`#ifdef ${this._define3DName}\r\n`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName};\r\n`,e._samplerDeclaration+="#else\r\n",e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName};\r\n`,e._samplerDeclaration+="#endif\r\n",e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._defineLODRefractionAlpha=e._getFreeDefineName("SS_LODINREFRACTIONALPHA"),this._defineLinearSpecularRefraction=e._getFreeDefineName("SS_LINEARSPECULARREFRACTION"),this._defineOppositeZ=e._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ"),this._refractionMatrixName=e._getFreeVariableName("refractionMatrix"),e._emitUniformFromString(this._refractionMatrixName,"mat4"),e._emitFunction("sampleRefraction",`\n #ifdef ${this._define3DName}\n #define sampleRefraction(s, c) textureCube(s, c)\n #else\n #define sampleRefraction(s, c) texture2D(s, c)\n #endif\r\n`,`//${this.name}`),e._emitFunction("sampleRefractionLod",`\n #ifdef ${this._define3DName}\n #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l)\n #else\n #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l)\n #endif\r\n`,`//${this.name}`),this._vRefractionMicrosurfaceInfosName=e._getFreeVariableName("vRefractionMicrosurfaceInfos"),e._emitUniformFromString(this._vRefractionMicrosurfaceInfosName,"vec4"),this._vRefractionInfosName=e._getFreeVariableName("vRefractionInfos"),e._emitUniformFromString(this._vRefractionInfosName,"vec4"),this._vRefractionFilteringInfoName=e._getFreeVariableName("vRefractionFilteringInfo"),e._emitUniformFromString(this._vRefractionFilteringInfoName,"vec2"),e._emitUniformFromString("vRefractionPosition","vec3"),e._emitUniformFromString("vRefractionSize","vec3"),""}_buildBlock(e){return this._scene=e.sharedData.scene,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e=this.texture.isCube?`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}");\r\n`:`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}");\r\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\r\n`),e+=`${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency};\r\n`,e+=`${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY};\r\n`,e+=`${this._codeVariableName}.useThicknessAsDepth = ${this.useThicknessAsDepth};\r\n`,e}serialize(){const e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.linkRefractionWithTransparency=this.linkRefractionWithTransparency,e.invertRefractionY=this.invertRefractionY,e.useThicknessAsDepth=this.useThicknessAsDepth,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=yp.Parse(e.texture,t,i):this.texture=Le.Parse(e.texture,t,i)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth}}(0,oe.gn)([At("Link refraction to transparency",Et.Boolean,"ADVANCED",{notifiers:{update:!0}})],cT.prototype,"linkRefractionWithTransparency",void 0),(0,oe.gn)([At("Invert refraction Y",Et.Boolean,"ADVANCED",{notifiers:{update:!0}})],cT.prototype,"invertRefractionY",void 0),(0,oe.gn)([At("Use thickness as depth",Et.Boolean,"ADVANCED",{notifiers:{update:!0}})],cT.prototype,"useThicknessAsDepth",void 0),(0,l.H)("BABYLON.RefractionBlock",cT);class dT extends bt{constructor(e){super(e,dt.Fragment),this._isUnique=!0,this.registerInput("thickness",ct.Float,!1,dt.Fragment),this.registerInput("tintColor",ct.Color3,!0,dt.Fragment),this.registerInput("translucencyIntensity",ct.Float,!0,dt.Fragment),this.registerInput("translucencyDiffusionDist",ct.Color3,!0,dt.Fragment),this.registerInput("refraction",ct.Object,!0,dt.Fragment,new Wv("refraction",this,vt.Input,cT,"RefractionBlock")),this.registerOutput("subsurface",ct.Object,dt.Fragment,new Wv("subsurface",this,vt.Output,dT,"SubSurfaceBlock"))}initialize(e){e._excludeVariableName("subSurfaceOut"),e._excludeVariableName("vThicknessParam"),e._excludeVariableName("vTintColor"),e._excludeVariableName("vSubSurfaceIntensity")}getClassName(){return"SubSurfaceBlock"}get thickness(){return this._inputs[0]}get tintColor(){return this._inputs[1]}get translucencyIntensity(){return this._inputs[2]}get translucencyDiffusionDist(){return this._inputs[3]}get refraction(){return this._inputs[4]}get subsurface(){return this._outputs[0]}autoConfigure(){if(!this.thickness.isConnected){const e=new Bt("SubSurface thickness",dt.Fragment,ct.Float);e.value=0,e.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);const n=this.translucencyDiffusionDist.isConnected||this.translucencyIntensity.isConnected;i.setValue("SUBSURFACE",n||this.refraction.isConnected,!0),i.setValue("SS_TRANSLUCENCY",n,!0),i.setValue("SS_THICKNESSANDMASK_TEXTURE",!1,!0),i.setValue("SS_REFRACTIONINTENSITY_TEXTURE",!1,!0),i.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE",!1,!0),i.setValue("SS_MASK_FROM_THICKNESS_TEXTURE",!1,!0),i.setValue("SS_USE_GLTF_TEXTURES",!1,!0)}static GetCode(e,t,i,n){var s,r,o,a,l,h,c,d,u,p,f,_,m,g,v,T;let S="";const E=(null==t?void 0:t.thickness.isConnected)?t.thickness.associatedVariableName:"0.",x=(null==t?void 0:t.tintColor.isConnected)?t.tintColor.associatedVariableName:"vec3(1.)",b=(null==t?void 0:t.translucencyIntensity.isConnected)?null==t?void 0:t.translucencyIntensity.associatedVariableName:"1.",C=(null==t?void 0:t.translucencyDiffusionDist.isConnected)?null==t?void 0:t.translucencyDiffusionDist.associatedVariableName:"vec3(1.)",y=(null==t?void 0:t.refraction.isConnected)?null===(s=null==t?void 0:t.refraction.connectedPoint)||void 0===s?void 0:s.ownerBlock:null,A=(null==y?void 0:y.tintAtDistance.isConnected)?y.tintAtDistance.associatedVariableName:"1.",R=(null==y?void 0:y.intensity.isConnected)?y.intensity.associatedVariableName:"1.",P=(null==y?void 0:y.view.isConnected)?y.view.associatedVariableName:"";return S+=null!==(r=null==y?void 0:y.getCode(e))&&void 0!==r?r:"",S+=`subSurfaceOutParams subSurfaceOut;\n\n #ifdef SUBSURFACE\n vec2 vThicknessParam = vec2(0., ${E});\n vec4 vTintColor = vec4(${x}, ${A});\n vec3 vSubSurfaceIntensity = vec3(${R}, ${b}, 0.);\n\n subSurfaceBlock(\n vSubSurfaceIntensity,\n vThicknessParam,\n vTintColor,\n normalW,\n specularEnvironmentReflectance,\n #ifdef SS_THICKNESSANDMASK_TEXTURE\n vec4(0.),\n #endif\n #ifdef REFLECTION\n #ifdef SS_TRANSLUCENCY\n ${null==i?void 0:i._reflectionMatrixName},\n #ifdef USESPHERICALFROMREFLECTIONMAP\n #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n reflectionOut.irradianceVector,\n #endif\n #if defined(REALTIME_FILTERING)\n ${null==i?void 0:i._cubeSamplerName},\n ${null==i?void 0:i._vReflectionFilteringInfoName},\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 ${n}.xyz,\n viewDirectionW,\n ${P},\n ${null!==(o=null==y?void 0:y._vRefractionInfosName)&&void 0!==o?o:""},\n ${null!==(a=null==y?void 0:y._refractionMatrixName)&&void 0!==a?a:""},\n ${null!==(l=null==y?void 0:y._vRefractionMicrosurfaceInfosName)&&void 0!==l?l:""},\n vLightingIntensity,\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n alpha,\n #endif\n #ifdef ${null!==(h=null==y?void 0:y._defineLODRefractionAlpha)&&void 0!==h?h:"IGNORE"}\n NdotVUnclamped,\n #endif\n #ifdef ${null!==(c=null==y?void 0:y._defineLinearSpecularRefraction)&&void 0!==c?c:"IGNORE"}\n roughness,\n #endif\n alphaG,\n #ifdef ${null!==(d=null==y?void 0:y._define3DName)&&void 0!==d?d:"IGNORE"}\n ${null!==(u=null==y?void 0:y._cubeSamplerName)&&void 0!==u?u:""},\n #else\n ${null!==(p=null==y?void 0:y._2DSamplerName)&&void 0!==p?p:""},\n #endif\n #ifndef LODBASEDMICROSFURACE\n #ifdef ${null!==(f=null==y?void 0:y._define3DName)&&void 0!==f?f:"IGNORE"}\n ${null!==(_=null==y?void 0:y._cubeSamplerName)&&void 0!==_?_:""},\n ${null!==(m=null==y?void 0:y._cubeSamplerName)&&void 0!==m?m:""},\n #else\n ${null!==(g=null==y?void 0:y._2DSamplerName)&&void 0!==g?g:""},\n ${null!==(v=null==y?void 0:y._2DSamplerName)&&void 0!==v?v:""},\n #endif\n #endif\n #ifdef ANISOTROPIC\n anisotropicOut,\n #endif\n #ifdef REALTIME_FILTERING\n ${null!==(T=null==y?void 0:y._vRefractionFilteringInfoName)&&void 0!==T?T:""},\n #endif\n #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\n vRefractionPosition,\n vRefractionSize,\n #endif\n #endif\n #ifdef SS_TRANSLUCENCY\n ${C},\n #endif\n subSurfaceOut\n );\n\n #ifdef SS_REFRACTION\n surfaceAlbedo = subSurfaceOut.surfaceAlbedo;\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n alpha = subSurfaceOut.alpha;\n #endif\n #endif\n #else\n subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance;\n #endif\r\n`,S}_buildBlock(e){return e.target===dt.Fragment&&e.sharedData.blocksWithDefines.push(this),this}}(0,l.H)("BABYLON.SubSurfaceBlock",dT);const uT={ambientClr:["finalAmbient",""],diffuseDir:["finalDiffuse",""],specularDir:["finalSpecularScaled","!defined(UNLIT) && defined(SPECULARTERM)"],clearcoatDir:["finalClearCoatScaled","!defined(UNLIT) && defined(CLEARCOAT)"],sheenDir:["finalSheenScaled","!defined(UNLIT) && defined(SHEEN)"],diffuseInd:["finalIrradiance","!defined(UNLIT) && defined(REFLECTION)"],specularInd:["finalRadianceScaled","!defined(UNLIT) && defined(REFLECTION)"],clearcoatInd:["clearcoatOut.finalClearCoatRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(CLEARCOAT)"],sheenInd:["sheenOut.finalSheenRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(SHEEN) && defined(ENVIRONMENTBRDF)"],refraction:["subSurfaceOut.finalRefraction","!defined(UNLIT) && defined(SS_REFRACTION)"],lighting:["finalColor.rgb",""],shadow:["shadow",""],alpha:["alpha",""]};class pT extends bt{static _OnGenerateOnlyFragmentCodeChanged(e,t){const i=e;return i.worldPosition.isConnected?(i.generateOnlyFragmentCode=!i.generateOnlyFragmentCode,console.error("The worldPosition input must not be connected to be able to switch!"),!1):(i._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?dt.Fragment:dt.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?dt.Fragment:dt.Vertex}constructor(e){super(e,dt.VertexAndFragment),this._environmentBRDFTexture=null,this._metallicReflectanceColor=a.Wo.White(),this._metallicF0Factor=1,this.directIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.lightFalloff=0,this.useAlphaTest=!1,this.alphaTestCutoff=.5,this.useAlphaBlending=!1,this.useRadianceOverAlpha=!0,this.useSpecularOverAlpha=!0,this.enableSpecularAntiAliasing=!1,this.realTimeFiltering=!1,this.realTimeFilteringQuality=8,this.useEnergyConservation=!0,this.useRadianceOcclusion=!0,this.useHorizonOcclusion=!0,this.unlit=!1,this.forceNormalForward=!1,this.generateOnlyFragmentCode=!1,this.debugMode=0,this.debugLimit=0,this.debugFactor=1,this._isUnique=!0,this.registerInput("worldPosition",ct.Vector4,!1,dt.Vertex),this.registerInput("worldNormal",ct.Vector4,!1,dt.Fragment),this.registerInput("view",ct.Matrix,!1),this.registerInput("cameraPosition",ct.Vector3,!1,dt.Fragment),this.registerInput("perturbedNormal",ct.Vector4,!0,dt.Fragment),this.registerInput("baseColor",ct.Color3,!0,dt.Fragment),this.registerInput("metallic",ct.Float,!1,dt.Fragment),this.registerInput("roughness",ct.Float,!1,dt.Fragment),this.registerInput("ambientOcc",ct.Float,!0,dt.Fragment),this.registerInput("opacity",ct.Float,!0,dt.Fragment),this.registerInput("indexOfRefraction",ct.Float,!0,dt.Fragment),this.registerInput("ambientColor",ct.Color3,!0,dt.Fragment),this.registerInput("reflection",ct.Object,!0,dt.Fragment,new Wv("reflection",this,vt.Input,aT,"ReflectionBlock")),this.registerInput("clearcoat",ct.Object,!0,dt.Fragment,new Wv("clearcoat",this,vt.Input,lT,"ClearCoatBlock")),this.registerInput("sheen",ct.Object,!0,dt.Fragment,new Wv("sheen",this,vt.Input,rT,"SheenBlock")),this.registerInput("subsurface",ct.Object,!0,dt.Fragment,new Wv("subsurface",this,vt.Input,dT,"SubSurfaceBlock")),this.registerInput("anisotropy",ct.Object,!0,dt.Fragment,new Wv("anisotropy",this,vt.Input,oT,"AnisotropyBlock")),this.registerInput("iridescence",ct.Object,!0,dt.Fragment,new Wv("iridescence",this,vt.Input,hT,"IridescenceBlock")),this.registerOutput("ambientClr",ct.Color3,dt.Fragment),this.registerOutput("diffuseDir",ct.Color3,dt.Fragment),this.registerOutput("specularDir",ct.Color3,dt.Fragment),this.registerOutput("clearcoatDir",ct.Color3,dt.Fragment),this.registerOutput("sheenDir",ct.Color3,dt.Fragment),this.registerOutput("diffuseInd",ct.Color3,dt.Fragment),this.registerOutput("specularInd",ct.Color3,dt.Fragment),this.registerOutput("clearcoatInd",ct.Color3,dt.Fragment),this.registerOutput("sheenInd",ct.Color3,dt.Fragment),this.registerOutput("refraction",ct.Color3,dt.Fragment),this.registerOutput("lighting",ct.Color3,dt.Fragment),this.registerOutput("shadow",ct.Float,dt.Fragment),this.registerOutput("alpha",ct.Float,dt.Fragment)}initialize(e){e._excludeVariableName("vLightingIntensity"),e._excludeVariableName("geometricNormalW"),e._excludeVariableName("normalW"),e._excludeVariableName("faceNormal"),e._excludeVariableName("albedoOpacityOut"),e._excludeVariableName("surfaceAlbedo"),e._excludeVariableName("alpha"),e._excludeVariableName("aoOut"),e._excludeVariableName("baseColor"),e._excludeVariableName("reflectivityOut"),e._excludeVariableName("microSurface"),e._excludeVariableName("roughness"),e._excludeVariableName("NdotVUnclamped"),e._excludeVariableName("NdotV"),e._excludeVariableName("alphaG"),e._excludeVariableName("AARoughnessFactors"),e._excludeVariableName("environmentBrdf"),e._excludeVariableName("ambientMonochrome"),e._excludeVariableName("seo"),e._excludeVariableName("eho"),e._excludeVariableName("environmentRadiance"),e._excludeVariableName("irradianceVector"),e._excludeVariableName("environmentIrradiance"),e._excludeVariableName("diffuseBase"),e._excludeVariableName("specularBase"),e._excludeVariableName("preInfo"),e._excludeVariableName("info"),e._excludeVariableName("shadow"),e._excludeVariableName("finalDiffuse"),e._excludeVariableName("finalAmbient"),e._excludeVariableName("ambientOcclusionForDirectDiffuse"),e._excludeVariableName("finalColor"),e._excludeVariableName("vClipSpacePosition"),e._excludeVariableName("vDebugMode")}getClassName(){return"PBRMetallicRoughnessBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get view(){return this._inputs[2]}get cameraPosition(){return this._inputs[3]}get perturbedNormal(){return this._inputs[4]}get baseColor(){return this._inputs[5]}get metallic(){return this._inputs[6]}get roughness(){return this._inputs[7]}get ambientOcc(){return this._inputs[8]}get opacity(){return this._inputs[9]}get indexOfRefraction(){return this._inputs[10]}get ambientColor(){return this._inputs[11]}get reflection(){return this._inputs[12]}get clearcoat(){return this._inputs[13]}get sheen(){return this._inputs[14]}get subsurface(){return this._inputs[15]}get anisotropy(){return this._inputs[16]}get iridescence(){return this._inputs[17]}get ambientClr(){return this._outputs[0]}get diffuseDir(){return this._outputs[1]}get specularDir(){return this._outputs[2]}get clearcoatDir(){return this._outputs[3]}get sheenDir(){return this._outputs[4]}get diffuseInd(){return this._outputs[5]}get specularInd(){return this._outputs[6]}get clearcoatInd(){return this._outputs[7]}get sheenInd(){return this._outputs[8]}get refraction(){return this._outputs[9]}get lighting(){return this._outputs[10]}get shadow(){return this._outputs[11]}get alpha(){return this._outputs[12]}autoConfigure(e){if(!this.cameraPosition.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===Pt.CameraPosition));t||(t=new Bt("cameraPosition"),t.setAsSystemValue(Pt.CameraPosition)),t.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){let t=e.getInputBlockByPredicate((e=>e.systemValue===Pt.View));t||(t=new Bt("view"),t.setAsSystemValue(Pt.View)),t.output.connectTo(this.view)}}prepareDefines(e,t,i){i.setValue("PBR",!0),i.setValue("METALLICWORKFLOW",!0),i.setValue("DEBUGMODE",this.debugMode,!0),i.setValue("NORMALXYSCALE",!0),i.setValue("BUMP",this.perturbedNormal.isConnected,!0),i.setValue("LODBASEDMICROSFURACE",this._scene.getEngine().getCaps().textureLOD),i.setValue("ALBEDO",!1,!0),i.setValue("OPACITY",this.opacity.isConnected,!0),i.setValue("AMBIENT",!0,!0),i.setValue("AMBIENTINGRAYSCALE",!1,!0),i.setValue("REFLECTIVITY",!1,!0),i.setValue("AOSTOREINMETALMAPRED",!1,!0),i.setValue("METALLNESSSTOREINMETALMAPBLUE",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPALPHA",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPGREEN",!1,!0),this.lightFalloff===M_.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===M_.LIGHTFALLOFF_GLTF?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!0)):(i.setValue("USEPHYSICALLIGHTFALLOFF",!0),i.setValue("USEGLTFLIGHTFALLOFF",!1));const n=this.alphaTestCutoff.toString();i.setValue("ALPHABLEND",this.useAlphaBlending,!0),i.setValue("ALPHAFROMALBEDO",!1,!0),i.setValue("ALPHATEST",this.useAlphaTest,!0),i.setValue("ALPHATESTVALUE",n.indexOf(".")<0?n+".":n,!0),i.setValue("OPACITYRGB",!1,!0),i.setValue("RADIANCEOVERALPHA",this.useRadianceOverAlpha,!0),i.setValue("SPECULAROVERALPHA",this.useSpecularOverAlpha,!0),i.setValue("SPECULARAA",this._scene.getEngine().getCaps().standardDerivatives&&this.enableSpecularAntiAliasing,!0),i.setValue("REALTIME_FILTERING",this.realTimeFiltering,!0);const s=e.getScene();if(s.getEngine()._features.needTypeSuffixInShaderConstants?i.setValue("NUM_SAMPLES",this.realTimeFilteringQuality+"u",!0):i.setValue("NUM_SAMPLES",""+this.realTimeFilteringQuality,!0),i.setValue("BRDF_V_HEIGHT_CORRELATED",!0),i.setValue("MS_BRDF_ENERGY_CONSERVATION",this.useEnergyConservation,!0),i.setValue("RADIANCEOCCLUSION",this.useRadianceOcclusion,!0),i.setValue("HORIZONOCCLUSION",this.useHorizonOcclusion,!0),i.setValue("UNLIT",this.unlit,!0),i.setValue("FORCENORMALFORWARD",this.forceNormalForward,!0),this._environmentBRDFTexture&&Bs.ReflectionTextureEnabled?(i.setValue("ENVIRONMENTBRDF",!0),i.setValue("ENVIRONMENTBRDF_RGBD",this._environmentBRDFTexture.isRGBD,!0)):(i.setValue("ENVIRONMENTBRDF",!1),i.setValue("ENVIRONMENTBRDF_RGBD",!1)),i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i),i._areLightsDirty)if(this.light){const t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};It.G.PrepareDefinesForLight(s,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else It.G.PrepareDefinesForLights(s,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,It.G.PrepareDefinesForMultiview(s,i)}updateUniformsAndSamples(e,t,i,n){for(let s=0;s=0;It.G.PrepareUniformsAndSamplersForLight(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],n,t)}}isReady(e,t,i){return!(this._environmentBRDFTexture&&!this._environmentBRDFTexture.isReady())&&!(i._areImageProcessingDirty&&t.imageProcessingConfiguration&&!t.imageProcessingConfiguration.isReady())}bind(e,t,i){var n,s;if(!i)return;const r=i.getScene();this.light?It.G.BindLight(this.light,this._lightId,r,e,!0):It.G.BindLights(r,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);const o=this._scene.ambientColor;o&&e.setColor3("ambientFromScene",o);const l=r.useRightHandedSystem===(null!=r._mirroredCameraPosition);e.setFloat(this._invertNormalName,l?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);const h=null!==(s=null===(n=this.indexOfRefraction.connectInputBlock)||void 0===n?void 0:n.value)&&void 0!==s?s:1.5,c=Math.pow((h-1)/(h+1),2);this._metallicReflectanceColor.scaleToRef(c*this._metallicF0Factor,a.zZ.Color3[0]);const d=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,a.zZ.Color3[0],d),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_injectVertexCode(e){var t,i;const n=this.worldPosition,s=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",s,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",s,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));const r="v_"+n.associatedVariableName;e._emitVaryingFromString(r,"vec4")&&(e.compilationString+=`${r} = ${n.associatedVariableName};\r\n`);const o=this.reflection.isConnected?null===(t=this.reflection.connectedPoint)||void 0===t?void 0:t.ownerBlock:null;o&&(o.viewConnectionPoint=this.view),e.compilationString+=null!==(i=null==o?void 0:o.handleVertexSide(e))&&void 0!==i?i:"",e._emitVaryingFromString("vClipSpacePosition","vec4","defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+="#if DEBUGMODE > 0\r\n",e._injectAtEnd+="vClipSpacePosition = gl_Position;\r\n",e._injectAtEnd+="#endif\r\n"),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",s,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:n.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${n.associatedVariableName};\r\n`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName};\r\n`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",s,{repeatKey:"maxSimultaneousLights"}))}_getAlbedoOpacityCode(){let e="albedoOpacityOutParams albedoOpacityOut;\r\n";return e+=`albedoOpacityBlock(\n vec4(${this.baseColor.isConnected?this.baseColor.associatedVariableName:"vec3(1.)"}, 1.),\n #ifdef ALBEDO\n vec4(1.),\n vec2(1., 1.),\n #endif\n #ifdef OPACITY\n vec4(${this.opacity.isConnected?this.opacity.associatedVariableName:"1."}),\n vec2(1., 1.),\n #endif\n albedoOpacityOut\n );\n\n vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo;\n float alpha = albedoOpacityOut.alpha;\r\n`,e}_getAmbientOcclusionCode(){let e="ambientOcclusionOutParams aoOut;\r\n";return e+=`ambientOcclusionBlock(\n #ifdef AMBIENT\n vec3(${this.ambientOcc.isConnected?this.ambientOcc.associatedVariableName:"1."}),\n vec4(0., 1.0, 1.0, 0.),\n #endif\n aoOut\n );\r\n`,e}_getReflectivityCode(e){let t="reflectivityOutParams reflectivityOut;\r\n";return this._vMetallicReflectanceFactorsName=e._getFreeVariableName("vMetallicReflectanceFactors"),e._emitUniformFromString(this._vMetallicReflectanceFactorsName,"vec4"),t+=`vec3 baseColor = surfaceAlbedo;\n\n reflectivityBlock(\n vec4(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.),\n #ifdef METALLICWORKFLOW\n surfaceAlbedo,\n ${this._vMetallicReflectanceFactorsName},\n #endif\n #ifdef REFLECTIVITY\n vec3(0., 0., 1.),\n vec4(1.),\n #endif\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n aoOut.ambientOcclusionColor,\n #endif\n #ifdef MICROSURFACEMAP\n microSurfaceTexel, <== not handled!\n #endif\n reflectivityOut\n );\n\n float microSurface = reflectivityOut.microSurface;\n float roughness = reflectivityOut.roughness;\n\n #ifdef METALLICWORKFLOW\n surfaceAlbedo = reflectivityOut.surfaceAlbedo;\n #endif\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor;\n #endif\r\n`,t}_buildBlock(e){var t,i,n,s,r,o,a,l,h,c,d,u,p,f,_,m,g,v,T,S,E,x,b,C,y,A,R,P,I,M,O,D,N,F,w,L,B,U,V,k,G;super._buildBlock(e),this._scene=e.sharedData.scene,this._environmentBRDFTexture||(this._environmentBRDFTexture=zp(this._scene));const z=this.reflection.isConnected?null===(t=this.reflection.connectedPoint)||void 0===t?void 0:t.ownerBlock:null;if(z&&(z.worldPositionConnectionPoint=this.worldPosition,z.cameraPositionConnectionPoint=this.cameraPosition,z.worldNormalConnectionPoint=this.worldNormal,z.viewConnectionPoint=this.view),e.target!==dt.Fragment)return this._injectVertexCode(e),this;e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this);const W=`//${this.name}`,H=this.perturbedNormal;let X=this.worldPosition.associatedVariableName;this.generateOnlyFragmentCode?(X=e._getFreeVariableName("globalWorldPos"),e._emitFunction("pbr_globalworldpos",`vec3 ${X};\r\n`,W),e.compilationString+=`${X} = ${this.worldPosition.associatedVariableName}.xyz;\r\n`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",W,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${this.worldPosition.associatedVariableName}`:void 0}),e.compilationString+="#if DEBUGMODE > 0\r\n",e.compilationString+="vec4 vClipSpacePosition = vec4((vec2(gl_FragCoord.xy) / vec2(1.0)) * 2.0 - 1.0, 0.0, 1.0);\r\n",e.compilationString+="#endif\r\n"):X="v_"+X,this._environmentBrdfSamplerName=e._getFreeVariableName("environmentBrdfSampler"),e._emit2DSampler(this._environmentBrdfSamplerName),e.sharedData.hints.needAlphaBlending=e.sharedData.hints.needAlphaBlending||this.useAlphaBlending,e.sharedData.hints.needAlphaTesting=e.sharedData.hints.needAlphaTesting||this.useAlphaTest,e._emitExtension("lod","#extension GL_EXT_shader_texture_lod : enable","defined(LODBASEDMICROSFURACE)"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitUniformFromString("vDebugMode","vec2","defined(IGNORE) || DEBUGMODE > 0"),e._emitUniformFromString("ambientFromScene","vec3"),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity"),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",W,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",W,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),e._emitFunctionFromInclude("helperFunctions",W),e._emitFunctionFromInclude("importanceSampling",W),e._emitFunctionFromInclude("pbrHelperFunctions",W),e._emitFunctionFromInclude("imageProcessingDeclaration",W),e._emitFunctionFromInclude("imageProcessingFunctions",W),e._emitFunctionFromInclude("shadowsFragmentFunctions",W,{replaceStrings:[{search:/vPositionW/g,replace:X+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingSetupFunctions",W,{replaceStrings:[{search:/vPositionW/g,replace:X+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions",W),e._emitFunctionFromInclude("pbrBRDFFunctions",W,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(i=null==z?void 0:z._defineSkyboxName)&&void 0!==i?i:"REFLECTIONMAP_SKYBOX"}]}),e._emitFunctionFromInclude("hdrFilteringFunctions",W),e._emitFunctionFromInclude("pbrDirectLightingFunctions",W,{replaceStrings:[{search:/vPositionW/g,replace:X+".xyz"}]}),e._emitFunctionFromInclude("pbrIBLFunctions",W),e._emitFunctionFromInclude("pbrBlockAlbedoOpacity",W),e._emitFunctionFromInclude("pbrBlockReflectivity",W),e._emitFunctionFromInclude("pbrBlockAmbientOcclusion",W),e._emitFunctionFromInclude("pbrBlockAlphaFresnel",W),e._emitFunctionFromInclude("pbrBlockAnisotropic",W),e._emitUniformFromString("vLightingIntensity","vec4"),(null==z?void 0:z.generateOnlyFragmentCode)&&(e.compilationString+=z.handleVertexSide(e)),this._vNormalWName=e._getFreeVariableName("vNormalW"),e.compilationString+=`vec4 ${this._vNormalWName} = normalize(${this.worldNormal.associatedVariableName});\r\n`,e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${X}.xyz);\r\n`),e.compilationString+=`vec3 geometricNormalW = ${this._vNormalWName}.xyz;\r\n`,e.compilationString+=`vec3 normalW = ${H.isConnected?"normalize("+H.associatedVariableName+".xyz)":"geometricNormalW"};\r\n`,this._invertNormalName=e._getFreeVariableName("invertNormal"),e._emitUniformFromString(this._invertNormalName,"float"),e.compilationString+=e._emitCodeFromInclude("pbrBlockNormalFinal",W,{replaceStrings:[{search:/vPositionW/g,replace:X+".xyz"},{search:/vEyePosition.w/g,replace:this._invertNormalName}]}),e.compilationString+=this._getAlbedoOpacityCode(),e.compilationString+=e._emitCodeFromInclude("depthPrePass",W),e.compilationString+=this._getAmbientOcclusionCode(),e.compilationString+=e._emitCodeFromInclude("pbrBlockLightmapInit",W),e.compilationString+="#ifdef UNLIT\n vec3 diffuseBase = vec3(1., 1., 1.);\n #else\r\n",e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",W,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(n=null==z?void 0:z._defineSkyboxName)&&void 0!==n?n:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:null!==(s=null==z?void 0:z._define3DName)&&void 0!==s?s:"REFLECTIONMAP_3D"}]});const Y=this.anisotropy.isConnected?null===(r=this.anisotropy.connectedPoint)||void 0===r?void 0:r.ownerBlock:null;Y&&(Y.worldPositionConnectionPoint=this.worldPosition,Y.worldNormalConnectionPoint=this.worldNormal,e.compilationString+=Y.getCode(e,!this.perturbedNormal.isConnected)),z&&z.hasTexture&&(e.compilationString+=z.getCode(e,Y?"anisotropicOut.anisotropicNormal":"normalW")),e._emitFunctionFromInclude("pbrBlockReflection",W,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:null!==(o=null==z?void 0:z._define3DName)&&void 0!==o?o:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(a=null==z?void 0:z._defineOppositeZ)&&void 0!==a?a:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:null!==(l=null==z?void 0:z._defineProjectionName)&&void 0!==l?l:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(h=null==z?void 0:z._defineSkyboxName)&&void 0!==h?h:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:null!==(c=null==z?void 0:z._defineLODReflectionAlpha)&&void 0!==c?c:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(d=null==z?void 0:z._defineLinearSpecularReflection)&&void 0!==d?d:"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:null!==(u=null==z?void 0:z._vReflectionFilteringInfoName)&&void 0!==u?u:"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",W,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:this._vMetallicReflectanceFactorsName}]});const j=this.sheen.isConnected?null===(p=this.sheen.connectedPoint)||void 0===p?void 0:p.ownerBlock:null;j&&(e.compilationString+=j.getCode(z)),e._emitFunctionFromInclude("pbrBlockSheen",W,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:null!==(f=null==z?void 0:z._define3DName)&&void 0!==f?f:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(_=null==z?void 0:z._defineSkyboxName)&&void 0!==_?_:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:null!==(m=null==z?void 0:z._defineLODReflectionAlpha)&&void 0!==m?m:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(g=null==z?void 0:z._defineLinearSpecularReflection)&&void 0!==g?g:"LINEARSPECULARREFLECTION"}]});const K=this.iridescence.isConnected?null===(v=this.iridescence.connectedPoint)||void 0===v?void 0:v.ownerBlock:null;e.compilationString+=hT.GetCode(K),e._emitFunctionFromInclude("pbrBlockIridescence",W,{replaceStrings:[]});const q=this.clearcoat.isConnected?null===(T=this.clearcoat.connectedPoint)||void 0===T?void 0:T.ownerBlock:null,$=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,Q=this.perturbedNormal.isConnected&&(null===(E=(null===(S=this.perturbedNormal.connectedPoint)||void 0===S?void 0:S.ownerBlock).worldTangent)||void 0===E?void 0:E.isConnected),Z=this.anisotropy.isConnected&&(null===(x=this.anisotropy.connectedPoint)||void 0===x?void 0:x.ownerBlock).worldTangent.isConnected;let J=Q||!this.perturbedNormal.isConnected&&Z;e.compilationString+=lT.GetCode(e,q,z,X,$,J,this.worldNormal.associatedVariableName),$&&(J=null!==(b=null==q?void 0:q.worldTangent.isConnected)&&void 0!==b&&b),e._emitFunctionFromInclude("pbrBlockClearcoat",W,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:null!==(C=null==z?void 0:z._define3DName)&&void 0!==C?C:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(y=null==z?void 0:z._defineOppositeZ)&&void 0!==y?y:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:null!==(A=null==z?void 0:z._defineProjectionName)&&void 0!==A?A:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(R=null==z?void 0:z._defineSkyboxName)&&void 0!==R?R:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:null!==(P=null==z?void 0:z._defineLODReflectionAlpha)&&void 0!==P?P:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(I=null==z?void 0:z._defineLinearSpecularReflection)&&void 0!==I?I:"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:J?"defined(TANGENT)":"defined(IGNORE)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance",W,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(M=null==z?void 0:z._defineSkyboxName)&&void 0!==M?M:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:null!==(O=null==z?void 0:z._define3DName)&&void 0!==O?O:"REFLECTIONMAP_3D"}]});const ee=this.subsurface.isConnected?null===(D=this.subsurface.connectedPoint)||void 0===D?void 0:D.ownerBlock:null,te=this.subsurface.isConnected?null===(F=(null===(N=this.subsurface.connectedPoint)||void 0===N?void 0:N.ownerBlock).refraction.connectedPoint)||void 0===F?void 0:F.ownerBlock:null;te&&(te.viewConnectionPoint=this.view,te.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=dT.GetCode(e,ee,z,X),e._emitFunctionFromInclude("pbrBlockSubSurface",W,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:null!==(w=null==z?void 0:z._define3DName)&&void 0!==w?w:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(L=null==z?void 0:z._defineOppositeZ)&&void 0!==L?L:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:null!==(B=null==z?void 0:z._defineProjectionName)&&void 0!==B?B:"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:null!==(U=null==te?void 0:te._define3DName)&&void 0!==U?U:"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:null!==(V=null==te?void 0:te._defineLODRefractionAlpha)&&void 0!==V?V:"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:null!==(k=null==te?void 0:te._defineLinearSpecularRefraction)&&void 0!==k?k:"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:null!==(G=null==te?void 0:te._defineOppositeZ)&&void 0!==G?G:"SS_REFRACTIONMAP_OPPOSITEZ"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockDirectLighting",W),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",W,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",W,{repeatKey:"maxSimultaneousLights"}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",W),e.compilationString+="#endif\r\n";const ie=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:"vec3(0., 0., 0.)";let ne=M_.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();-1===ne.indexOf(".")&&(ne+="."),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",W,{replaceStrings:[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:/vAmbientColor/g,replace:ie+" * ambientFromScene"},{search:/vAmbientInfos\.w/g,replace:ne}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalColorComposition",W,{replaceStrings:[{search:/finalEmissive/g,replace:"vec3(0.)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockImageProcessing",W,{replaceStrings:[{search:/visibility/g,replace:"1."}]}),e.compilationString+=e._emitCodeFromInclude("pbrDebug",W,{replaceStrings:[{search:/vNormalW/g,replace:this._vNormalWName},{search:/vPositionW/g,replace:X},{search:/albedoTexture\.rgb;/g,replace:"vec3(1.);\r\ngl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb);\r\n"}]});for(const se of this._outputs)if(se.hasEndpoints){const t=uT[se.name];if(t){const[i,n]=t;n&&(e.compilationString+=`#if ${n}\r\n`),e.compilationString+=`${this._declareOutput(se,e)} = ${i};\r\n`,n&&(e.compilationString+="#else\r\n",e.compilationString+=`${this._declareOutput(se,e)} = vec3(0.);\r\n`,e.compilationString+="#endif\r\n")}else console.error(`There's no remapping for the ${se.name} end point! No code generated`)}return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.lightFalloff = ${this.lightFalloff};\r\n`,e+=`${this._codeVariableName}.useAlphaTest = ${this.useAlphaTest};\r\n`,e+=`${this._codeVariableName}.alphaTestCutoff = ${this.alphaTestCutoff};\r\n`,e+=`${this._codeVariableName}.useAlphaBlending = ${this.useAlphaBlending};\r\n`,e+=`${this._codeVariableName}.useRadianceOverAlpha = ${this.useRadianceOverAlpha};\r\n`,e+=`${this._codeVariableName}.useSpecularOverAlpha = ${this.useSpecularOverAlpha};\r\n`,e+=`${this._codeVariableName}.enableSpecularAntiAliasing = ${this.enableSpecularAntiAliasing};\r\n`,e+=`${this._codeVariableName}.realTimeFiltering = ${this.realTimeFiltering};\r\n`,e+=`${this._codeVariableName}.realTimeFilteringQuality = ${this.realTimeFilteringQuality};\r\n`,e+=`${this._codeVariableName}.useEnergyConservation = ${this.useEnergyConservation};\r\n`,e+=`${this._codeVariableName}.useRadianceOcclusion = ${this.useRadianceOcclusion};\r\n`,e+=`${this._codeVariableName}.useHorizonOcclusion = ${this.useHorizonOcclusion};\r\n`,e+=`${this._codeVariableName}.unlit = ${this.unlit};\r\n`,e+=`${this._codeVariableName}.forceNormalForward = ${this.forceNormalForward};\r\n`,e+=`${this._codeVariableName}.debugMode = ${this.debugMode};\r\n`,e+=`${this._codeVariableName}.debugLimit = ${this.debugLimit};\r\n`,e+=`${this._codeVariableName}.debugFactor = ${this.debugFactor};\r\n`,e}serialize(){const e=super.serialize();return this.light&&(e.lightId=this.light.id),e.lightFalloff=this.lightFalloff,e.useAlphaTest=this.useAlphaTest,e.alphaTestCutoff=this.alphaTestCutoff,e.useAlphaBlending=this.useAlphaBlending,e.useRadianceOverAlpha=this.useRadianceOverAlpha,e.useSpecularOverAlpha=this.useSpecularOverAlpha,e.enableSpecularAntiAliasing=this.enableSpecularAntiAliasing,e.realTimeFiltering=this.realTimeFiltering,e.realTimeFilteringQuality=this.realTimeFilteringQuality,e.useEnergyConservation=this.useEnergyConservation,e.useRadianceOcclusion=this.useRadianceOcclusion,e.useHorizonOcclusion=this.useHorizonOcclusion,e.unlit=this.unlit,e.forceNormalForward=this.forceNormalForward,e.debugMode=this.debugMode,e.debugLimit=this.debugLimit,e.debugFactor=this.debugFactor,e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){var n,s;super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.lightFalloff=null!==(n=e.lightFalloff)&&void 0!==n?n:0,this.useAlphaTest=e.useAlphaTest,this.alphaTestCutoff=e.alphaTestCutoff,this.useAlphaBlending=e.useAlphaBlending,this.useRadianceOverAlpha=e.useRadianceOverAlpha,this.useSpecularOverAlpha=e.useSpecularOverAlpha,this.enableSpecularAntiAliasing=e.enableSpecularAntiAliasing,this.realTimeFiltering=!!e.realTimeFiltering,this.realTimeFilteringQuality=null!==(s=e.realTimeFilteringQuality)&&void 0!==s?s:8,this.useEnergyConservation=e.useEnergyConservation,this.useRadianceOcclusion=e.useRadianceOcclusion,this.useHorizonOcclusion=e.useHorizonOcclusion,this.unlit=e.unlit,this.forceNormalForward=!!e.forceNormalForward,this.debugMode=e.debugMode,this.debugLimit=e.debugLimit,this.debugFactor=e.debugFactor,this.generateOnlyFragmentCode=!!e.generateOnlyFragmentCode,this._setTarget()}}(0,oe.gn)([At("Direct lights",Et.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],pT.prototype,"directIntensity",void 0),(0,oe.gn)([At("Environment lights",Et.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],pT.prototype,"environmentIntensity",void 0),(0,oe.gn)([At("Specular highlights",Et.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],pT.prototype,"specularIntensity",void 0),(0,oe.gn)([At("Light falloff",Et.List,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:M_.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:M_.LIGHTFALLOFF_GLTF},{label:"Standard",value:M_.LIGHTFALLOFF_STANDARD}]})],pT.prototype,"lightFalloff",void 0),(0,oe.gn)([At("Alpha Testing",Et.Boolean,"OPACITY")],pT.prototype,"useAlphaTest",void 0),(0,oe.gn)([At("Alpha CutOff",Et.Float,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],pT.prototype,"alphaTestCutoff",void 0),(0,oe.gn)([At("Alpha blending",Et.Boolean,"OPACITY")],pT.prototype,"useAlphaBlending",void 0),(0,oe.gn)([At("Radiance over alpha",Et.Boolean,"RENDERING",{notifiers:{update:!0}})],pT.prototype,"useRadianceOverAlpha",void 0),(0,oe.gn)([At("Specular over alpha",Et.Boolean,"RENDERING",{notifiers:{update:!0}})],pT.prototype,"useSpecularOverAlpha",void 0),(0,oe.gn)([At("Specular anti-aliasing",Et.Boolean,"RENDERING",{notifiers:{update:!0}})],pT.prototype,"enableSpecularAntiAliasing",void 0),(0,oe.gn)([At("Realtime filtering",Et.Boolean,"RENDERING",{notifiers:{update:!0}})],pT.prototype,"realTimeFiltering",void 0),(0,oe.gn)([At("Realtime filtering quality",Et.List,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],pT.prototype,"realTimeFilteringQuality",void 0),(0,oe.gn)([At("Energy Conservation",Et.Boolean,"ADVANCED",{notifiers:{update:!0}})],pT.prototype,"useEnergyConservation",void 0),(0,oe.gn)([At("Radiance occlusion",Et.Boolean,"ADVANCED",{notifiers:{update:!0}})],pT.prototype,"useRadianceOcclusion",void 0),(0,oe.gn)([At("Horizon occlusion",Et.Boolean,"ADVANCED",{notifiers:{update:!0}})],pT.prototype,"useHorizonOcclusion",void 0),(0,oe.gn)([At("Unlit",Et.Boolean,"ADVANCED",{notifiers:{update:!0}})],pT.prototype,"unlit",void 0),(0,oe.gn)([At("Force normal forward",Et.Boolean,"ADVANCED",{notifiers:{update:!0}})],pT.prototype,"forceNormalForward",void 0),(0,oe.gn)([At("Generate only fragment code",Et.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:pT._OnGenerateOnlyFragmentCodeChanged}})],pT.prototype,"generateOnlyFragmentCode",void 0),(0,oe.gn)([At("Debug mode",Et.List,"DEBUG",{notifiers:{update:!0},options:[{label:"None",value:0},{label:"Normalized position",value:1},{label:"Normals",value:2},{label:"Tangents",value:3},{label:"Bitangents",value:4},{label:"Bump Normals",value:5},{label:"ClearCoat Normals",value:8},{label:"ClearCoat Tangents",value:9},{label:"ClearCoat Bitangents",value:10},{label:"Anisotropic Normals",value:11},{label:"Anisotropic Tangents",value:12},{label:"Anisotropic Bitangents",value:13},{label:"Env Refraction",value:40},{label:"Env Reflection",value:41},{label:"Env Clear Coat",value:42},{label:"Direct Diffuse",value:50},{label:"Direct Specular",value:51},{label:"Direct Clear Coat",value:52},{label:"Direct Sheen",value:53},{label:"Env Irradiance",value:54},{label:"Surface Albedo",value:60},{label:"Reflectance 0",value:61},{label:"Metallic",value:62},{label:"Metallic F0",value:71},{label:"Roughness",value:63},{label:"AlphaG",value:64},{label:"NdotV",value:65},{label:"ClearCoat Color",value:66},{label:"ClearCoat Roughness",value:67},{label:"ClearCoat NdotV",value:68},{label:"Transmittance",value:69},{label:"Refraction Transmittance",value:70},{label:"SEO",value:80},{label:"EHO",value:81},{label:"Energy Factor",value:82},{label:"Specular Reflectance",value:83},{label:"Clear Coat Reflectance",value:84},{label:"Sheen Reflectance",value:85},{label:"Luminance Over Alpha",value:86},{label:"Alpha",value:87}]})],pT.prototype,"debugMode",void 0),(0,oe.gn)([At("Split position",Et.Float,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],pT.prototype,"debugLimit",void 0),(0,oe.gn)([At("Output factor",Et.Float,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],pT.prototype,"debugFactor",void 0),(0,l.H)("BABYLON.PBRMetallicRoughnessBlock",pT);(0,l.H)("BABYLON.ModBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("left",ct.AutoDetect),this.registerInput("right",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"ModBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = mod(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\r\n`,this}});var fT,_T,mT,gT,vT,TT;(0,l.H)("BABYLON.MatrixBuilder",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("row0",ct.Vector4),this.registerInput("row1",ct.Vector4),this.registerInput("row2",ct.Vector4),this.registerInput("row3",ct.Vector4),this.registerOutput("output",ct.Matrix)}getClassName(){return"MatrixBuilder"}get row0(){return this._inputs[0]}get row1(){return this._inputs[1]}get row2(){return this._inputs[2]}get row3(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(){if(!this.row0.isConnected){const e=new Bt("row0");e.value=new o.Lt(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){const e=new Bt("row1");e.value=new o.Lt(0,1,0,0),e.output.connectTo(this.row1)}if(!this.row2.isConnected){const e=new Bt("row2");e.value=new o.Lt(0,0,1,0),e.output.connectTo(this.row2)}if(!this.row3.isConnected){const e=new Bt("row3");e.value=new o.Lt(0,0,0,1),e.output.connectTo(this.row3)}}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.row0,n=this.row1,s=this.row2,r=this.row3;return e.compilationString+=this._declareOutput(t,e)+` = mat4(${i.associatedVariableName}, ${n.associatedVariableName}, ${s.associatedVariableName}, ${r.associatedVariableName});\r\n`,this}}),function(e){e[e.Equal=0]="Equal",e[e.NotEqual=1]="NotEqual",e[e.LessThan=2]="LessThan",e[e.GreaterThan=3]="GreaterThan",e[e.LessOrEqual=4]="LessOrEqual",e[e.GreaterOrEqual=5]="GreaterOrEqual",e[e.Xor=6]="Xor",e[e.Or=7]="Or",e[e.And=8]="And"}(fT||(fT={}));(0,l.H)("BABYLON.ConditionalBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.condition=fT.LessThan,this.registerInput("a",ct.Float),this.registerInput("b",ct.Float),this.registerInput("true",ct.AutoDetect,!0),this.registerInput("false",ct.AutoDetect,!0),this.registerOutput("output",ct.BasedOnInput),this._linkConnectionTypes(2,3),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=ct.Float}getClassName(){return"ConditionalBlock"}get a(){return this._inputs[0]}get b(){return this._inputs[1]}get true(){return this._inputs[2]}get false(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this.true.isConnected?this.true.associatedVariableName:"1.0",n=this.false.isConnected?this.false.associatedVariableName:"0.0";switch(this.condition){case fT.Equal:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} == ${this.b.associatedVariableName} ? ${i} : ${n};\r\n`;break;case fT.NotEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} != ${this.b.associatedVariableName} ? ${i} : ${n};\r\n`;break;case fT.LessThan:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} < ${this.b.associatedVariableName} ? ${i} : ${n};\r\n`;break;case fT.LessOrEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} <= ${this.b.associatedVariableName} ? ${i} : ${n};\r\n`;break;case fT.GreaterThan:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} > ${this.b.associatedVariableName} ? ${i} : ${n};\r\n`;break;case fT.GreaterOrEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} >= ${this.b.associatedVariableName} ? ${i} : ${n};\r\n`;break;case fT.Xor:e.compilationString+=this._declareOutput(t,e)+` = (mod(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 2.0) > 0.0) ? ${i} : ${n};\r\n`;break;case fT.Or:e.compilationString+=this._declareOutput(t,e)+` = (min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0) ? ${i} : ${n};\r\n`;break;case fT.And:e.compilationString+=this._declareOutput(t,e)+` = (${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0) ? ${i} : ${n};\r\n`}return this}serialize(){const e=super.serialize();return e.condition=this.condition,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.condition=e.condition}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.condition = BABYLON.ConditionalBlockConditions.${fT[this.condition]};\r\n`}});class ST extends bt{constructor(e){super(e,dt.Neutral),this.octaves=6,this.registerInput("seed",ct.AutoDetect),this.registerInput("chaos",ct.AutoDetect,!0),this.registerInput("offsetX",ct.Float,!0),this.registerInput("offsetY",ct.Float,!0),this.registerInput("offsetZ",ct.Float,!0),this.registerOutput("output",ct.Float),this._inputs[0].acceptedConnectionPointTypes.push(ct.Vector2),this._inputs[0].acceptedConnectionPointTypes.push(ct.Vector3),this._linkConnectionTypes(0,1)}getClassName(){return"CloudBlock"}get seed(){return this._inputs[0]}get chaos(){return this._inputs[1]}get offsetX(){return this._inputs[2]}get offsetY(){return this._inputs[3]}get offsetZ(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){var t,i;if(super._buildBlock(e),!this.seed.isConnected)return;if(!this._outputs[0].hasEndpoints)return;const n="\n float fbm(in vec2 st, in vec2 chaos) {\n // Initial values\n float value = 0.0;\n float amplitude = .5;\n float frequency = 0.;\n\n // Loop of octaves\n for (int i = 0; i < OCTAVES; i++) {\n value += amplitude * cloudNoise(st, chaos);\n st *= 2.0;\n amplitude *= 0.5;\n }\n return value;\n }\n\n float fbm(in vec3 x, in vec3 chaos) {\n // Initial values\n float value = 0.0;\n float amplitude = 0.5;\n for (int i = 0; i < OCTAVES; ++i) {\n value += amplitude * cloudNoise(x, chaos);\n x = x * 2.0;\n amplitude *= 0.5;\n }\n return value;\n }",s=`fbm${this.octaves}`;e._emitFunction("CloudBlockCode","\n\n float cloudRandom(in float p) { p = fract(p * 0.011); p *= p + 7.5; p *= p + p; return fract(p); }\n\n // Based on Morgan McGuire @morgan3d\n // https://www.shadertoy.com/view/4dS3Wd\n float cloudNoise(in vec2 x, in vec2 chaos) {\n vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.);\n\n vec2 i = floor(x);\n vec2 f = fract(x);\n\n float n = dot(i, step);\n\n vec2 u = f * f * (3.0 - 2.0 * f);\n return mix(\n mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x),\n mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x),\n u.y\n );\n }\n\n float cloudNoise(in vec3 x, in vec3 chaos) {\n vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.);\n\n vec3 i = floor(x);\n vec3 f = fract(x);\n\n float n = dot(i, step);\n\n vec3 u = f * f * (3.0 - 2.0 * f);\n return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x),\n mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y),\n mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x),\n mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z);\n }","// CloudBlockCode"),e._emitFunction("CloudBlockCodeFBM"+this.octaves,n.replace(/fbm/gi,s).replace(/OCTAVES/gi,(0|this.octaves).toString()),"// CloudBlockCode FBM");const r=e._getFreeVariableName("st"),o=(null===(t=this.seed.connectedPoint)||void 0===t?void 0:t.type)===ct.Vector2?"vec2":"vec3";e.compilationString+=`${o} ${r} = ${this.seed.associatedVariableName};\r\n`,this.offsetX.isConnected&&(e.compilationString+=`${r}.x += 0.1 * ${this.offsetX.associatedVariableName};\r\n`),this.offsetY.isConnected&&(e.compilationString+=`${r}.y += 0.1 * ${this.offsetY.associatedVariableName};\r\n`),this.offsetZ.isConnected&&"vec3"===o&&(e.compilationString+=`${r}.z += 0.1 * ${this.offsetZ.associatedVariableName};\r\n`);let a="";return a=this.chaos.isConnected?this.chaos.associatedVariableName:(null===(i=this.seed.connectedPoint)||void 0===i?void 0:i.type)===ct.Vector2?"vec2(0., 0.)":"vec3(0., 0., 0.)",e.compilationString+=this._declareOutput(this._outputs[0],e)+` = ${s}(${r}, ${a});\r\n`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.octaves = ${this.octaves};\r\n`}serialize(){const e=super.serialize();return e.octaves=this.octaves,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.octaves=e.octaves}}(0,oe.gn)([At("Octaves",Et.Int)],ST.prototype,"octaves",void 0),(0,l.H)("BABYLON.CloudBlock",ST);(0,l.H)("BABYLON.VoronoiNoiseBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("seed",ct.Vector2),this.registerInput("offset",ct.Float),this.registerInput("density",ct.Float),this.registerOutput("output",ct.Float),this.registerOutput("cells",ct.Float)}getClassName(){return"VoronoiNoiseBlock"}get seed(){return this._inputs[0]}get offset(){return this._inputs[1]}get density(){return this._inputs[2]}get output(){return this._outputs[0]}get cells(){return this._outputs[1]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;let t="vec2 voronoiRandom(vec2 seed, float offset){\n mat2 m = mat2(15.27, 47.63, 99.41, 89.98);\n vec2 uv = fract(sin(m * seed) * 46839.32);\n return vec2(sin(uv.y * offset) * 0.5 + 0.5, cos(uv.x * offset) * 0.5 + 0.5);\n }\n ";e._emitFunction("voronoiRandom",t,"// Voronoi random generator"),t="void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){\n vec2 g = floor(seed * density);\n vec2 f = fract(seed * density);\n float t = 8.0;\n vec3 res = vec3(8.0, 0.0, 0.0);\n\n for(int y=-1; y<=1; y++)\n {\n for(int x=-1; x<=1; x++)\n {\n vec2 lattice = vec2(x,y);\n vec2 randomOffset = voronoiRandom(lattice + g, offset);\n float d = distance(lattice + randomOffset, f);\n if(d < res.x)\n {\n res = vec3(d, randomOffset.x, randomOffset.y);\n outValue = res.x;\n cells = res.y;\n }\n }\n }\n }\n ",e._emitFunction("voronoi",t,"// Voronoi");const i=e._getFreeVariableName("tempOutput"),n=e._getFreeVariableName("tempCells");return e.compilationString+=`float ${i} = 0.0;\r\n`,e.compilationString+=`float ${n} = 0.0;\r\n`,e.compilationString+=`voronoi(${this.seed.associatedVariableName}, ${this.offset.associatedVariableName}, ${this.density.associatedVariableName}, ${i}, ${n});\r\n`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${i};\r\n`),this.cells.hasEndpoints&&(e.compilationString+=this._declareOutput(this.cells,e)+` = ${n};\r\n`),this}});(0,l.H)("BABYLON.ElbowBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("input",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}get target(){const e=this._inputs[0];if(e.isConnected){const t=e.connectedPoint.ownerBlock;if(t.target!==dt.VertexAndFragment)return t.target;if(e.connectedPoint.target!==dt.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){0==(this._target&e)&&(this._target=e)}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0],i=this._inputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${i.associatedVariableName};\r\n`,this}});class ET extends bt{get texture(){var e;return this.source.isConnected?(null===(e=this.source.connectedPoint)||void 0===e?void 0:e.ownerBlock).texture:this._texture}set texture(e){var t;if(this._texture===e)return;const i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:m.l.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this._texture))),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,(t=>t.hasTexture(e)))}get textureY(){var e;return this.sourceY.isConnected?(null===(e=this.sourceY.connectedPoint)||void 0===e?void 0:e.ownerBlock).texture:null}get textureZ(){var e,t;return(null===(e=this.sourceZ)||void 0===e?void 0:e.isConnected)?(null===(t=this.sourceY.connectedPoint)||void 0===t?void 0:t.ownerBlock).texture:null}_getImageSourceBlock(e){return(null==e?void 0:e.isConnected)?e.connectedPoint.ownerBlock:null}get samplerName(){const e=this._getImageSourceBlock(this.source);return e?e.samplerName:this._samplerName}get samplerYName(){var e,t;return null!==(t=null===(e=this._getImageSourceBlock(this.sourceY))||void 0===e?void 0:e.samplerName)&&void 0!==t?t:null}get samplerZName(){var e,t;return null!==(t=null===(e=this._getImageSourceBlock(this.sourceZ))||void 0===e?void 0:e.samplerName)&&void 0!==t?t:null}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){var t;if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){const e=null!==(t=this.texture.getScene())&&void 0!==t?t:m.l.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){var t;if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){const e=null!==(t=this.texture.getScene())&&void 0!==t?t:m.l.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,(e=>e.hasTexture(this.texture)))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,dt.Neutral),this.projectAsCube=!1,this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this.registerInput("position",ct.AutoDetect,!1),this.registerInput("normal",ct.AutoDetect,!1),this.registerInput("sharpness",ct.Float,!0),this.registerInput("source",ct.Object,!0,dt.VertexAndFragment,new Wv("source",this,vt.Input,$v,"ImageSourceBlock")),this.registerInput("sourceY",ct.Object,!0,dt.VertexAndFragment,new Wv("sourceY",this,vt.Input,$v,"ImageSourceBlock")),t||this.registerInput("sourceZ",ct.Object,!0,dt.VertexAndFragment,new Wv("sourceZ",this,vt.Input,$v,"ImageSourceBlock")),this.registerOutput("rgba",ct.Color4,dt.Neutral),this.registerOutput("rgb",ct.Color3,dt.Neutral),this.registerOutput("r",ct.Float,dt.Neutral),this.registerOutput("g",ct.Float,dt.Neutral),this.registerOutput("b",ct.Float,dt.Neutral),this.registerOutput("a",ct.Float,dt.Neutral),this.registerOutput("level",ct.Float,dt.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ct.Color3|ct.Vector3|ct.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(ct.Color3|ct.Vector3|ct.Vector4)}getClassName(){return"TriPlanarBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get sharpness(){return this._inputs[2]}get source(){return this._inputs[3]}get sourceY(){return this._inputs[4]}get sourceZ(){return this._inputs[5]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;const n=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,n,!0),i.setValue(this._gammaDefineName,s,!0)}isReady(){return!(this.texture&&!this.texture.isReadyOrNotBlocking())}bind(e){this.texture&&(e.setFloat(this._textureInfoName,this.texture.level),this._imageSource||e.setTexture(this._samplerName,this.texture))}_generateTextureLookup(e){var t,i;const n=this.samplerName,s=null!==(t=this.samplerYName)&&void 0!==t?t:n,r=null!==(i=this.samplerZName)&&void 0!==i?i:n,o=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",a=e._getFreeVariableName("x"),l=e._getFreeVariableName("y"),h=e._getFreeVariableName("z"),c=e._getFreeVariableName("w"),d=e._getFreeVariableName("n"),u=e._getFreeVariableName("uvx"),p=e._getFreeVariableName("uvy"),f=e._getFreeVariableName("uvz");e.compilationString+=`\n vec3 ${d} = ${this.normal.associatedVariableName}.xyz;\n\n vec2 ${u} = ${this.position.associatedVariableName}.yz;\n vec2 ${p} = ${this.position.associatedVariableName}.zx;\n vec2 ${f} = ${this.position.associatedVariableName}.xy;\n `,this.projectAsCube&&(e.compilationString+=`\n ${u}.xy = ${u}.yx;\n\n if (${d}.x >= 0.0) {\n ${u}.x = -${u}.x;\n }\n if (${d}.y < 0.0) {\n ${p}.y = -${p}.y;\n }\n if (${d}.z < 0.0) {\n ${f}.x = -${f}.x;\n }\n `),e.compilationString+=`\n vec4 ${a} = texture2D(${n}, ${u});\n vec4 ${l} = texture2D(${s}, ${p});\n vec4 ${h} = texture2D(${r}, ${f});\n \n // blend weights\n vec3 ${c} = pow(abs(${d}), vec3(${o}));\n\n // blend and return\n vec4 ${this._tempTextureRead} = (${a}*${c}.x + ${l}*${c}.y + ${h}*${c}.z) / (${c}.x + ${c}.y + ${c}.z); \n `}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName}\n ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName});\n #endif\n `),e.compilationString+=`#ifdef ${this._gammaDefineName}\n ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName});\n #endif\n `)}_writeOutput(e,t,i){let n="";this.disableLevelMultiplication||(n=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${n};\r\n`,this._generateConversionCode(e,t,i)}_buildBlock(e){super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA"),this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);const t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitUniformFromString(this._textureInfoName,"float"),this._generateTextureLookup(e);for(const i of this._outputs)i.hasEndpoints&&"level"!==i.name&&this._writeOutput(e,i,i.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\r\n`,e+=`${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\r\n`,e+=`${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\r\n`,e+=`${this._codeVariableName}.projectAsCube = ${this.projectAsCube};\r\n`,this.texture?(e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\r\n`,e+=`${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\r\n`,e+=`${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\r\n`,e+=`${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\r\n`,e+=`${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\r\n`,e+=`${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\r\n`,e+=`${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\r\n`,e+=`${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\r\n`,e+=`${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\r\n`,e+=`${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\r\n`,e+=`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\r\n`,e):e}serialize(){const e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.disableLevelMultiplication=this.disableLevelMultiplication,e.projectAsCube=this.projectAsCube,this.hasImageSource||!this.texture||this.texture.isRenderTarget||"VideoTexture"===this.texture.getClassName()||(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this.disableLevelMultiplication=!!e.disableLevelMultiplication,this.projectAsCube=!!e.projectAsCube,e.texture&&!Ni.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=Le.Parse(e.texture,t,i))}}(0,oe.gn)([At("Project as cube",Et.Boolean,"ADVANCED",{notifiers:{update:!0}})],ET.prototype,"projectAsCube",void 0),(0,l.H)("BABYLON.TriPlanarBlock",ET);(0,l.H)("BABYLON.BiPlanarBlock",class extends ET{constructor(e){super(e,!0)}getClassName(){return"BiPlanarBlock"}_generateTextureLookup(e){var t;const i=this.samplerName,n=null!==(t=this.samplerYName)&&void 0!==t?t:this.samplerName,s=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",r=e._getFreeVariableName("dpdx"),o=e._getFreeVariableName("dpdy"),a=e._getFreeVariableName("n"),l=e._getFreeVariableName("ma"),h=e._getFreeVariableName("mi"),c=e._getFreeVariableName("me"),d=e._getFreeVariableName("x"),u=e._getFreeVariableName("y"),p=e._getFreeVariableName("y");e.compilationString+=`\n // grab coord derivatives for texturing\n vec3 ${r} = dFdx(${this.position.associatedVariableName}.xyz);\n vec3 ${o} = dFdy(${this.position.associatedVariableName}.xyz);\n vec3 ${a} = abs(${this.normal.associatedVariableName}.xyz);\n \n // determine major axis (in x; yz are following axis)\n ivec3 ${l} = (${a}.x>${a}.y && ${a}.x>${a}.z) ? ivec3(0,1,2) :\n (${a}.y>${a}.z) ? ivec3(1,2,0) :\n ivec3(2,0,1) ;\n // determine minor axis (in x; yz are following axis)\n ivec3 ${h} = (${a}.x<${a}.y && ${a}.x<${a}.z) ? ivec3(0,1,2) :\n (${a}.y<${a}.z) ? ivec3(1,2,0) :\n ivec3(2,0,1) ;\n // determine median axis (in x; yz are following axis)\n ivec3 ${c} = ivec3(3) - ${h} - ${l};\n \n // project+fetch\n vec4 ${d} = textureGrad( ${i}, vec2( ${this.position.associatedVariableName}[${l}.y], ${this.position.associatedVariableName}[${l}.z]), \n vec2(${r}[${l}.y],${r}[${l}.z]), \n vec2(${o}[${l}.y],${o}[${l}.z]) );\n vec4 ${u} = textureGrad( ${n}, vec2( ${this.position.associatedVariableName}[${c}.y], ${this.position.associatedVariableName}[${c}.z]), \n vec2(${r}[${c}.y],${r}[${c}.z]),\n vec2(${o}[${c}.y],${o}[${c}.z]) );\n \n // blend factors\n vec2 ${p} = vec2(${a}[${l}.x],${a}[${c}.x]);\n // make local support\n ${p} = clamp( (${p}-0.5773)/(1.0-0.5773), 0.0, 1.0 );\n // shape transition\n ${p} = pow( ${p}, vec2(${s}/8.0) );\n // blend and return\n vec4 ${this._tempTextureRead} = (${d}*${p}.x + ${u}*${p}.y) / (${p}.x + ${p}.y);\n `}});(0,l.H)("BABYLON.MatrixDeterminantBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("input",ct.Matrix),this.registerOutput("output",ct.Float)}getClassName(){return"MatrixDeterminantBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this.output,i=this.input;return e.compilationString+=this._declareOutput(t,e)+`${t.associatedVariableName} = determinant(${i.associatedVariableName});\r\n`,this}});(0,l.H)("BABYLON.MatrixTransposeBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.registerInput("input",ct.Matrix),this.registerOutput("output",ct.Matrix)}getClassName(){return"MatrixTransposeBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);const t=this.output,i=this.input;return e.compilationString+=this._declareOutput(t,e)+`${t.associatedVariableName} = transpose(${i.associatedVariableName});\r\n`,this}}),function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Tangent=2]="Tangent",e[e.VertexColor=3]="VertexColor",e[e.UV1=4]="UV1",e[e.UV2=5]="UV2",e[e.UV3=6]="UV3",e[e.UV4=7]="UV4",e[e.UV5=8]="UV5",e[e.UV6=9]="UV6"}(_T||(_T={}));class xT extends bt{constructor(e){super(e,dt.Neutral),this.attributeType=_T.None,this.registerInput("input",ct.AutoDetect),this.registerInput("fallback",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].onConnectionObservable.add((e=>{var t;if(this.attributeType)return;const i=e.ownerBlock;if(i instanceof Bt&&i.isAttribute)switch(i.name){case"color":this.attributeType=_T.VertexColor;break;case"normal":this.attributeType=_T.Normal;break;case"tangent":this.attributeType=_T.Tangent;break;case"uv":this.attributeType=_T.UV1;break;case"uv2":this.attributeType=_T.UV2;break;case"uv3":this.attributeType=_T.UV3;break;case"uv4":this.attributeType=_T.UV4;break;case"uv5":this.attributeType=_T.UV5;break;case"uv6":this.attributeType=_T.UV6}else if(i instanceof Hv)switch(null===(t=this.input.connectedPoint)||void 0===t?void 0:t.name){case"normalOutput":this.attributeType=_T.Normal;break;case"tangentOutput":this.attributeType=_T.Tangent;break;case"uvOutput":this.attributeType=_T.UV1}}))}getClassName(){return"MeshAttributeExistsBlock"}get input(){return this._inputs[0]}get fallback(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.attributeType){case _T.VertexColor:t="VERTEXCOLOR_NME";break;case _T.Normal:t="NORMAL";break;case _T.Tangent:t="TANGENT";break;case _T.UV1:t="UV1";break;case _T.UV2:t="UV2";break;case _T.UV3:t="UV3";break;case _T.UV4:t="UV4";break;case _T.UV5:t="UV5";break;case _T.UV6:t="UV6"}const i=this._declareOutput(this.output,e);return t&&(e.compilationString+=`#ifdef ${t}\r\n`),e.compilationString+=`${i} = ${this.input.associatedVariableName};\r\n`,t&&(e.compilationString+="#else\r\n",e.compilationString+=`${i} = ${this.fallback.associatedVariableName};\r\n`,e.compilationString+="#endif\r\n"),this}serialize(){const e=super.serialize();return e.attributeType=this.attributeType,e}_deserialize(e,t,i){var n;super._deserialize(e,t,i),this.attributeType=null!==(n=e.attributeType)&&void 0!==n?n:_T.None}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return e+=`${this._codeVariableName}.attributeType = ${this.attributeType};\r\n`,e}}(0,oe.gn)([At("Attribute lookup",Et.List,void 0,{notifiers:{update:!0},options:[{label:"(None)",value:_T.None},{label:"Normal",value:_T.Normal},{label:"Tangent",value:_T.Tangent},{label:"Vertex Color",value:_T.VertexColor},{label:"UV1",value:_T.UV1},{label:"UV2",value:_T.UV2},{label:"UV3",value:_T.UV3},{label:"UV4",value:_T.UV4},{label:"UV5",value:_T.UV5},{label:"UV6",value:_T.UV6}]})],xT.prototype,"attributeType",void 0),(0,l.H)("BABYLON.MeshAttributeExistsBlock",xT),function(e){e[e.EaseInSine=0]="EaseInSine",e[e.EaseOutSine=1]="EaseOutSine",e[e.EaseInOutSine=2]="EaseInOutSine",e[e.EaseInQuad=3]="EaseInQuad",e[e.EaseOutQuad=4]="EaseOutQuad",e[e.EaseInOutQuad=5]="EaseInOutQuad",e[e.EaseInCubic=6]="EaseInCubic",e[e.EaseOutCubic=7]="EaseOutCubic",e[e.EaseInOutCubic=8]="EaseInOutCubic",e[e.EaseInQuart=9]="EaseInQuart",e[e.EaseOutQuart=10]="EaseOutQuart",e[e.EaseInOutQuart=11]="EaseInOutQuart",e[e.EaseInQuint=12]="EaseInQuint",e[e.EaseOutQuint=13]="EaseOutQuint",e[e.EaseInOutQuint=14]="EaseInOutQuint",e[e.EaseInExpo=15]="EaseInExpo",e[e.EaseOutExpo=16]="EaseOutExpo",e[e.EaseInOutExpo=17]="EaseInOutExpo",e[e.EaseInCirc=18]="EaseInCirc",e[e.EaseOutCirc=19]="EaseOutCirc",e[e.EaseInOutCirc=20]="EaseInOutCirc",e[e.EaseInBack=21]="EaseInBack",e[e.EaseOutBack=22]="EaseOutBack",e[e.EaseInOutBack=23]="EaseInOutBack",e[e.EaseInElastic=24]="EaseInElastic",e[e.EaseOutElastic=25]="EaseOutElastic",e[e.EaseInOutElastic=26]="EaseInOutElastic"}(mT||(mT={}));(0,l.H)("BABYLON.CurveBlock",class extends bt{constructor(e){super(e,dt.Neutral),this.type=mT.EaseInOutSine,this.registerInput("input",ct.AutoDetect),this.registerOutput("output",ct.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(ct.Matrix),this._inputs[0].excludedConnectionPointTypes.push(ct.Object),this._inputs[0].excludedConnectionPointTypes.push(ct.Int)}getClassName(){return"CurveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_duplicateEntry(e,t){return`ret.${t} = ${e.replace(/VAL/g,"v."+t)}`}_duplicateEntryDirect(e){return`return ${e.replace(/VAL/g,"v")}`}_duplicateVector(e,t){if("float"===t)return this._duplicateEntryDirect(e);const i=parseInt(t.replace("vec",""));let n=`\n vec${i} ret = vec${i}(0.0);\n `;for(let s=1;s<=i;s++)n+=this._duplicateEntry(e,1===s?"x":2===s?"y":3===s?"z":"w")+";\r\n";return n+="return ret;\r\n",n}_buildBlock(e){super._buildBlock(e);const t=this._outputs[0];let i="",n="",s="";switch(this.input.type){case ct.Float:s="float";break;case ct.Vector2:s="vec2";break;case ct.Vector3:case ct.Color3:s="vec3";break;case ct.Vector4:case ct.Color4:s="vec4"}switch(n=mT[this.type]+"_"+s,this.type){case mT.EaseInSine:i="return 1.0 - cos((v * 3.1415) / 2.0)";break;case mT.EaseOutSine:i="return sin((v * 3.1415) / 2.0)";break;case mT.EaseInOutSine:i="return -(cos(v * 3.1415) - 1.0) / 2.0";break;case mT.EaseInQuad:i="return v * v";break;case mT.EaseOutQuad:i="return (1.0 - v) * (1.0 - v)";break;case mT.EaseInOutQuad:{const e="VAL < 0.5 ? 2.0 * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0";i=this._duplicateVector(e,s);break}case mT.EaseInCubic:i="return v * v * v";break;case mT.EaseOutCubic:{const e="1.0 - pow(1.0 - VAL, 3.0)";i=this._duplicateVector(e,s);break}case mT.EaseInOutCubic:{const e="VAL < 0.5 ? 4.0 * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0";i=this._duplicateVector(e,s);break}case mT.EaseInQuart:i="return v * v * v * v";break;case mT.EaseOutQuart:{const e="1.0 - pow(1.0 - VAL, 4.0)";i=this._duplicateVector(e,s);break}case mT.EaseInOutQuart:{const e="VAL < 0.5 ? 8.0 * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0";i=this._duplicateVector(e,s);break}case mT.EaseInQuint:i="return v * v * v * v * v";break;case mT.EaseOutQuint:{const e="1.0 - pow(1.0 - VAL, 5.0)";i=this._duplicateVector(e,s);break}case mT.EaseInOutQuint:{const e="VAL < 0.5 ? 16.0 * VAL * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0";i=this._duplicateVector(e,s);break}case mT.EaseInExpo:{const e="VAL == 0.0 ? 0.0 : pow(2.0, 10.0 * VAL - 10.0)";i=this._duplicateVector(e,s);break}case mT.EaseOutExpo:{const e="VAL == 1.0 ? 1.0 : 1.0 - pow(2.0, -10.0 * VAL)";i=this._duplicateVector(e,s);break}case mT.EaseInOutExpo:{const e="VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : VAL < 0.5 ? pow(2.0, 20.0 * VAL - 10.0) / 2.0 : (2.0 - pow(2.0, -20.0 * VAL + 10.0)) / 2.0";i=this._duplicateVector(e,s);break}case mT.EaseInCirc:{const e="1.0 - sqrt(1.0 - pow(VAL, 2.0))";i=this._duplicateVector(e,s);break}case mT.EaseOutCirc:{const e="sqrt(1.0 - pow(VAL - 1.0, 2.0))";i=this._duplicateVector(e,s);break}case mT.EaseInOutCirc:{const e="VAL < 0.5 ? (1.0 - sqrt(1.0 - pow(2.0 * VAL, 2.0))) / 2.0 : (sqrt(1.0 - pow(-2.0 * VAL + 2.0, 2.0)) + 1.0) / 2.0";i=this._duplicateVector(e,s);break}case mT.EaseInBack:i="return 2.70158 * v * v * v - 1.70158 * v * v";break;case mT.EaseOutBack:{const e="2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)";i=this._duplicateVector(e,s);break}case mT.EaseInOutBack:{const e="VAL < 0.5 ? (pow(2.0 * VAL, 2.0) * ((3.5949095) * 2.0 * VAL - 2.5949095)) / 2.0 : (pow(2.0 * VAL - 2.0, 2.0) * (3.5949095 * (VAL * 2.0 - 2.0) + 3.5949095) + 2.0) / 2.0";i=this._duplicateVector(e,s);break}case mT.EaseInElastic:{const e="VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : -pow(2.0, 10.0 * VAL - 10.0) * sin((VAL * 10.0 - 10.75) * ((2.0 * 3.1415) / 3.0))";i=this._duplicateVector(e,s);break}case mT.EaseOutElastic:{const e="VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : pow(2.0, -10.0 * VAL) * sin((VAL * 10.0 - 0.75) * ((2.0 * 3.1415) / 3.0)) + 1.0";i=this._duplicateVector(e,s);break}case mT.EaseInOutElastic:{const e="VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : VAL < 0.5 ? -(pow(2.0, 20.0 * VAL - 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 : (pow(2.0, -20.0 * VAL + 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 + 1.0";i=this._duplicateVector(e,s);break}}return e._emitFunction(n,`${s} ${n}(${s} v) {${i};}\r\n`,""),e.compilationString+=this._declareOutput(t,e)+` = ${n}(${this.input.associatedVariableName});\r\n`,this}serialize(){const e=super.serialize();return e.curveType=this.type,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.type=e.curveType}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.CurveBlockTypes.${mT[this.type]};\r\n`}});class bT extends Tt.H{constructor(){super(...arguments),this.DECAL=!1,this.DECALDIRECTUV=0,this.DECAL_SMOOTHALPHA=!1,this.GAMMADECAL=!1}}class CT extends ha{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DecalMap",150,new bT,t),this._isEnabled=!1,this.isEnabled=!1,this._smoothAlpha=!1,this.smoothAlpha=!1,this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i,n){const s=n.getMesh().decalMap;return!(this._isEnabled&&(null==s?void 0:s.texture)&&Bs.DecalMapEnabled&&t.texturesEnabled)||s.isReady()}prepareDefines(e,t,i){const n=i.decalMap;if(this._isEnabled&&(null==n?void 0:n.texture)&&Bs.DecalMapEnabled&&t.texturesEnabled){(!e.DECAL||e.GAMMADECAL!==n.texture.gammaSpace)&&e.markAsTexturesDirty(),e.DECAL=!0,e.GAMMADECAL=n.texture.gammaSpace,e.DECAL_SMOOTHALPHA=this._smoothAlpha,It.G.PrepareDefinesForMergedUV(n.texture,e,"DECAL")}else{e.DECAL&&e.markAsTexturesDirty(),e.DECAL=!1}}hardBindForSubMesh(e,t,i,n){const s=n.getMesh().decalMap;if(!(this._isEnabled&&(null==s?void 0:s.texture)&&Bs.DecalMapEnabled&&t.texturesEnabled))return;const r=this._material.isFrozen,o=s.texture;e.useUbo&&r&&e.isSync||(e.updateFloat4("vDecalInfos",o.coordinatesIndex,0,0,0),It.G.BindTextureMatrix(o,e,"decal")),e.setTexture("decalSampler",o)}getClassName(){return"DecalMapConfiguration"}getSamplers(e){e.push("decalSampler")}getUniforms(){return{ubo:[{name:"vDecalInfos",size:4,type:"vec4"},{name:"decalMatrix",size:16,type:"mat4"}]}}}(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],CT.prototype,"isEnabled",void 0),(0,oe.gn)([(0,E.qC)(),(0,E.wz)("_markAllSubMeshesAsTexturesDirty")],CT.prototype,"smoothAlpha",void 0),function(e){e[e.MATERIAL_TYPE_STANDARD=0]="MATERIAL_TYPE_STANDARD",e[e.MATERIAL_TYPE_PBR=1]="MATERIAL_TYPE_PBR"}(gT||(gT={})),function(e){e[e.COLOR_MODE_SET=0]="COLOR_MODE_SET",e[e.COLOR_MODE_ADD=1]="COLOR_MODE_ADD",e[e.COLOR_MODE_MULTIPLY=2]="COLOR_MODE_MULTIPLY"}(vT||(vT={})),function(e){e[e.COLOR_DISTRIBUTION_TYPE_SEGMENT=0]="COLOR_DISTRIBUTION_TYPE_SEGMENT",e[e.COLOR_DISTRIBUTION_TYPE_LINE=1]="COLOR_DISTRIBUTION_TYPE_LINE"}(TT||(TT={}));class yT extends Tt.H{constructor(){super(...arguments),this.GREASED_LINE_HAS_COLOR=!1,this.GREASED_LINE_SIZE_ATTENUATION=!1,this.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=!1}}class AT extends ha{constructor(e,t,i){var n,s,r;i=null!=i?i:{};const o=new yT;o.GREASED_LINE_HAS_COLOR=!!i.color,o.GREASED_LINE_SIZE_ATTENUATION=null!==(n=i.sizeAttenuation)&&void 0!==n&&n,o.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=i.colorDistributionType===TT.COLOR_DISTRIBUTION_TYPE_LINE,super(e,AT.GREASED_LINE_MATERIAL_NAME,200,o),this._scene=t,this._dashArray=0,this._options=i,this._scene=null!==(s=this._scene)&&void 0!==s?s:e.getScene(),this._engine=this._scene.getEngine(),i.colors?this._createColorsTexture(`${e.name}-colors-texture`,i.colors):AT._PrepareEmptyColorsTexture(t),this.setDashCount(null!==(r=i.dashCount)&&void 0!==r?r:1),this._enable(!0)}getAttributes(e){e.push("grl_offsets"),e.push("grl_previousAndSide"),e.push("grl_nextAndCounters"),e.push("grl_widths"),e.push("grl_colorPointers")}getSamplers(e){e.push("grl_colors")}getActiveTextures(e){this._colorsTexture&&e.push(this._colorsTexture)}getUniforms(){return{ubo:[{name:"grl_projection",size:16,type:"mat4"},{name:"grl_singleColor",size:3,type:"vec3"},{name:"grl_resolution_lineWidth",size:3,type:"vec3"},{name:"grl_dashOptions",size:4,type:"vec4"},{name:"grl_colorMode_visibility_colorsWidth_useColors",size:4,type:"vec4"}],vertex:"\n uniform vec3 grl_resolution_lineWidth;\n uniform mat4 grl_projection;\n ",fragment:"\n uniform vec4 grl_dashOptions;\n uniform vec4 grl_colorMode_visibility_colorsWidth_useColors;\n uniform vec3 grl_singleColor;\n "}}get isEnabled(){return!0}bindForSubMesh(e){var t,i,n,s,r,l,h;const c=this._scene.activeCamera;if(!c)throw Error("GreasedLinePluginMaterial requires an active camera.");{const t=c.getProjectionMatrix();e.updateMatrix("grl_projection",t)}const d=o.jp.Vector3[0];this._options.resolution?(d.x=this._options.resolution.x,d.y=this._options.resolution.y):(d.x=this._engine.getRenderWidth(),d.y=this._engine.getRenderHeight()),d.z=this._options.width?this._options.width:this._options.sizeAttenuation?1:.1,e.updateVector3("grl_resolution_lineWidth",d);const u=o.jp.Vector4[0];u.x=AT._BooleanToNumber(this._options.useDash),u.y=null!==(t=this._dashArray)&&void 0!==t?t:0,u.z=null!==(i=this._options.dashOffset)&&void 0!==i?i:0,u.w=null!==(n=this._options.dashRatio)&&void 0!==n?n:.5,e.updateVector4("grl_dashOptions",u);const p=o.jp.Vector4[1];p.x=null!==(s=this._options.colorMode)&&void 0!==s?s:vT.COLOR_MODE_SET,p.y=null!==(r=this._options.visibility)&&void 0!==r?r:1,p.z=this._colorsTexture?this._colorsTexture.getSize().width:0,p.w=AT._BooleanToNumber(this._options.useColors),e.updateVector4("grl_colorMode_visibility_colorsWidth_useColors",p),this._options.color&&e.updateColor3("grl_singleColor",null!==(l=this._options.color)&&void 0!==l?l:a.Wo.White()),e.setTexture("grl_colors",null!==(h=this._colorsTexture)&&void 0!==h?h:AT._EmptyColorsTexture)}prepareDefines(e,t,i){var n;const s=this._options;e.GREASED_LINE_HAS_COLOR=!!s.color,e.GREASED_LINE_SIZE_ATTENUATION=null!==(n=s.sizeAttenuation)&&void 0!==n&&n,e.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=s.colorDistributionType===TT.COLOR_DISTRIBUTION_TYPE_LINE}getClassName(){return AT.GREASED_LINE_MATERIAL_NAME}getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_DEFINITIONS:"\n attribute vec4 grl_previousAndSide;\n attribute vec4 grl_nextAndCounters;\n attribute float grl_widths;\n attribute vec3 grl_offsets;\n attribute float grl_colorPointers;\n\n varying float grlCounters;\n varying float grlColorPointer;\n\n vec2 grlFix( vec4 i, float aspect ) {\n vec2 res = i.xy / i.w;\n res.x *= aspect;\n return res;\n }\n ",CUSTOM_VERTEX_UPDATE_POSITION:"\n vec3 grlPositionOffset = grl_offsets;\n positionUpdated += grlPositionOffset;\n ",CUSTOM_VERTEX_MAIN_END:"\n vec2 grlResolution = grl_resolution_lineWidth.xy;\n float grlBaseWidth = grl_resolution_lineWidth.z;\n\n grlColorPointer = grl_colorPointers;\n\n vec3 grlPrevious = grl_previousAndSide.xyz;\n float grlSide = grl_previousAndSide.w;\n\n vec3 grlNext = grl_nextAndCounters.xyz;\n grlCounters = grl_nextAndCounters.w;\n\n float grlAspect = grlResolution.x / grlResolution.y;\n\n mat4 grlMatrix = viewProjection * world;\n vec4 grlFinalPosition = grlMatrix * vec4( positionUpdated , 1.0 );\n vec4 grlPrevPos = grlMatrix * vec4( grlPrevious + grlPositionOffset, 1.0 );\n vec4 grlNextPos = grlMatrix * vec4( grlNext + grlPositionOffset, 1.0 );\n\n vec2 grlCurrentP = grlFix( grlFinalPosition, grlAspect );\n vec2 grlPrevP = grlFix( grlPrevPos, grlAspect );\n vec2 grlNextP = grlFix( grlNextPos, grlAspect );\n\n float grlWidth = grlBaseWidth * grl_widths;\n\n vec2 grlDir;\n if( grlNextP == grlCurrentP ) grlDir = normalize( grlCurrentP - grlPrevP );\n else if( grlPrevP == grlCurrentP ) grlDir = normalize( grlNextP - grlCurrentP );\n else {\n vec2 grlDir1 = normalize( grlCurrentP - grlPrevP );\n vec2 grlDir2 = normalize( grlNextP - grlCurrentP );\n grlDir = normalize( grlDir1 + grlDir2 );\n }\n vec4 grlNormal = vec4( -grlDir.y, grlDir.x, 0., 1. );\n grlNormal.xy *= .5 * grlWidth;\n grlNormal *= grl_projection;\n #ifdef GREASED_LINE_SIZE_ATTENUATION\n grlNormal.xy *= grlFinalPosition.w;\n grlNormal.xy /= ( vec4( grlResolution, 0., 1. ) * grl_projection ).xy;\n #endif\n grlFinalPosition.xy += grlNormal.xy * grlSide;\n gl_Position = grlFinalPosition;\n\n vPositionW = vec3(grlFinalPosition);\n\n ","!gl_Position\\=viewProjection\\*worldPos;":"//"}:"fragment"===e?{CUSTOM_FRAGMENT_DEFINITIONS:"\n varying float grlCounters;\n varying float grlColorPointer;\n uniform sampler2D grl_colors;\n ",CUSTOM_FRAGMENT_MAIN_END:`\n float grlColorMode = grl_colorMode_visibility_colorsWidth_useColors.x;\n float grlVisibility = grl_colorMode_visibility_colorsWidth_useColors.y;\n float grlColorsWidth = grl_colorMode_visibility_colorsWidth_useColors.z;\n float grlUseColors = grl_colorMode_visibility_colorsWidth_useColors.w;\n\n float grlUseDash = grl_dashOptions.x;\n float grlDashArray = grl_dashOptions.y;\n float grlDashOffset = grl_dashOptions.z;\n float grlDashRatio = grl_dashOptions.w;\n\n gl_FragColor.a *= step(grlCounters, grlVisibility);\n if( gl_FragColor.a == 0. ) discard;\n\n if(grlUseDash == 1.){\n gl_FragColor.a *= ceil(mod(grlCounters + grlDashOffset, grlDashArray) - (grlDashArray * grlDashRatio));\n if (gl_FragColor.a == 0.) discard;\n }\n\n #ifdef GREASED_LINE_HAS_COLOR\n if (grlColorMode == ${vT.COLOR_MODE_SET}.) {\n gl_FragColor.rgb = grl_singleColor;\n } else if (grlColorMode == ${vT.COLOR_MODE_ADD}.) {\n gl_FragColor.rgb += grl_singleColor;\n } else if (grlColorMode == ${vT.COLOR_MODE_MULTIPLY}.) {\n gl_FragColor.rgb *= grl_singleColor;\n }\n #else\n if (grlUseColors == 1.) {\n #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE\n vec4 grlColor = texture2D(grl_colors, vec2(grlCounters, 0.), 0.);\n #else\n vec4 grlColor = texture2D(grl_colors, vec2(grlColorPointer/grlColorsWidth, 0.), 0.);\n #endif\n if (grlColorMode == ${vT.COLOR_MODE_SET}.) {\n gl_FragColor = grlColor;\n } else if (grlColorMode == ${vT.COLOR_MODE_ADD}.) {\n gl_FragColor += grlColor;\n } else if (grlColorMode == ${vT.COLOR_MODE_MULTIPLY}.) {\n gl_FragColor *= grlColor;\n }\n }\n #endif\n `}:null}static _BooleanToNumber(e){return e?1:0}static _Color3toRGBAUint8(e){const t=new Uint8Array(4*e.length);for(let i=0,n=0;i{const r=i.num_components(),o=l.num_points(),h=o*r,c=h*Float32Array.BYTES_PER_ELEMENT,d=e._malloc(c);try{a.GetAttributeDataArrayForAllPoints(l,i,e.DT_FLOAT32,c,d);const u=new Float32Array(e.HEAPF32.buffer,d,h);if("color"===t&&3===r){const e=new Float32Array(4*o);for(let t=0,i=0;t{const i=t.data;switch(i.id){case"init":{const t=i.decoder;t.url&&(importScripts(t.url),e=DracoDecoderModule({wasmBinary:t.wasmBinary})),postMessage("done");break}case"decodeMesh":if(!e)throw new Error("Draco decoder module is not available");e.then((e=>{RT(e,i.dataView,i.attributes,(e=>{postMessage({id:"indices",value:e},[e.buffer])}),((e,t)=>{postMessage({id:e,value:t},[t.buffer])})),postMessage("done")}))}}}class IT{static get DecoderAvailable(){const e=IT.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 IT._Default||(IT._Default=new IT),IT._Default}constructor(e=IT.DefaultNumWorkers){const t=IT.Configuration.decoder,i=t.wasmUrl&&t.wasmBinaryUrl&&"object"==typeof WebAssembly?{url:se.w1.GetAbsoluteUrl(t.wasmUrl),wasmBinaryPromise:se.w1.LoadFileAsync(se.w1.GetAbsoluteUrl(t.wasmBinaryUrl))}:{url:se.w1.GetAbsoluteUrl(t.fallbackUrl),wasmBinaryPromise:Promise.resolve(void 0)};e&&"function"==typeof Worker&&"function"==typeof URL?this._workerPoolPromise=i.wasmBinaryPromise.then((t=>{const n=`${RT}(${PT})()`,s=URL.createObjectURL(new Blob([n],{type:"application/javascript"}));return new z_(e,(()=>new Promise(((e,n)=>{const r=new Worker(s),o=e=>{r.removeEventListener("error",o),r.removeEventListener("message",a),n(e)},a=t=>{"done"===t.data&&(r.removeEventListener("error",o),r.removeEventListener("message",a),e(r))};r.addEventListener("error",o),r.addEventListener("message",a),r.postMessage({id:"init",decoder:{url:i.url,wasmBinary:t}})}))))})):this._decoderModulePromise=i.wasmBinaryPromise.then((e=>{if(!i.url)throw new Error("Draco decoder module is not available");return se.w1.LoadScriptAsync(i.url).then((()=>{return t=e,new Promise((e=>{DracoDecoderModule({wasmBinary:t}).then((t=>{e({module:t})}))}));var t}))}))}dispose(){this._workerPoolPromise&&this._workerPoolPromise.then((e=>{e.dispose()})),delete this._workerPoolPromise,delete this._decoderModulePromise}whenReadyAsync(){return this._workerPoolPromise?this._workerPoolPromise.then((()=>{})):this._decoderModulePromise?this._decoderModulePromise.then((()=>{})):Promise.resolve()}decodeMeshAsync(e,t,i){const n=e instanceof ArrayBuffer?new Uint8Array(e):e;if(this._workerPoolPromise)return this._workerPoolPromise.then((e=>new Promise(((s,r)=>{e.push(((e,o)=>{const a=new Qe.x,l=t=>{e.removeEventListener("error",l),e.removeEventListener("message",h),r(t),o()},h=t=>{if("done"===t.data)e.removeEventListener("error",l),e.removeEventListener("message",h),s(a),o();else if("indices"===t.data.id)a.indices=t.data.value;else{const e=i&&i[t.data.id]?i[t.data.id]:1;if(1!==e)for(let i=0;i{const s=new Qe.x;return RT(e.module,n,t,(e=>{s.indices=e}),((e,t)=>{s.set(t,e)}),i),s}));throw new Error("Draco decoder module is not available")}}IT.Configuration={decoder:{wasmUrl:"https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",wasmBinaryUrl:"https://preview.babylonjs.com/draco_decoder_gltf.wasm",fallbackUrl:"https://preview.babylonjs.com/draco_decoder_gltf.js"}},IT.DefaultNumWorkers=IT.GetDefaultNumWorkers(),IT._Default=null;class MT{static get Default(){return MT._Default||(MT._Default=new MT),MT._Default}constructor(){const e=MT.Configuration.decoder;this._decoderModulePromise=se.w1.LoadScriptAsync(se.w1.GetAbsoluteUrl(e.url)).then((()=>MeshoptDecoder.ready))}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,n,s){return this._decoderModulePromise.then((()=>{const r=new Uint8Array(t*i);return MeshoptDecoder.decodeGltfBuffer(r,t,i,e,n,s),r}))}}MT.Configuration={decoder:{url:"https://preview.babylonjs.com/meshopt_decoder.js"}},MT._Default=null;class OT{constructor(e,t){this.normal=e,this.w=t}static FromPoints(e,t,i){const n=i.subtract(e),s=t.subtract(e);if(0===n.lengthSquared()||0===s.lengthSquared())return null;const r=o.P.Normalize(o.P.Cross(n,s));return new OT(r,o.P.Dot(r,e))}clone(){return new OT(this.normal.clone(),this.w)}flip(){this.normal.scaleInPlace(-1),this.w=-this.w}splitPolygon(e,t,i,n,s){let r=0;const a=[];let l,h;for(l=0;lOT.EPSILON?1:0;r|=t,a.push(t)}switch(r){case 0:(o.P.Dot(this.normal,e.plane.normal)>0?t:i).push(e);break;case 1:n.push(e);break;case 2:s.push(e);break;case 3:{const t=[],i=[];for(l=0;l=3&&(r=new DT(t,e.shared),r.plane&&n.push(r)),i.length>=3&&(r=new DT(i,e.shared),r.plane&&s.push(r));break}}}}OT.EPSILON=1e-5;class DT{constructor(e,t){this.vertices=e,this.shared=t,this.plane=OT.FromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){const e=this.vertices.map((e=>e.clone()));return new DT(e,this.shared)}flip(){this.vertices.reverse().map((e=>{e.flip()})),this.plane.flip()}}const NT="meshUVSpaceRendererVertexShader",FT="precision highp float;\nattribute vec3 position;\nattribute vec3 normal;\nattribute vec2 uv;\nuniform mat4 projMatrix;\nvarying vec2 vDecalTC;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nvoid main(void) {\nvec3 positionUpdated=position;\nvec3 normalUpdated=normal;\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nmat3 normWorldSM=mat3(finalWorld);\nvec3 vNormalW;\n#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));\nvNormalW=normalize(normWorldSM*vNormalW);\n#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\n#endif\nvNormalW=normalize(normWorldSM*normalUpdated);\n#endif\nvec3 normalView=normalize((projMatrix*vec4(vNormalW,0.0)).xyz);\nvec3 decalTC=(projMatrix*worldPos).xyz;\nvDecalTC=decalTC.xy;\ngl_Position=vec4(uv*2.0-1.0,normalView.z>0.0 ? 2. : decalTC.z,1.0);\n}\n";Ht.v.ShadersStore[NT]=FT;const wT="meshUVSpaceRendererPixelShader",LT="precision highp float;\nvarying vec2 vDecalTC;\nuniform sampler2D textureSampler;\nvoid main(void) {\nif (vDecalTC.x<0. || vDecalTC.x>1. || vDecalTC.y<0. || vDecalTC.y>1.) {\ndiscard;\n}\ngl_FragColor=texture2D(textureSampler,vDecalTC);\n}\n";Ht.v.ShadersStore[wT]=LT;class BT{constructor(){this.running=!1,this._simplificationArray=[]}addTask(e){this._simplificationArray.push(e)}executeNext(){const e=this._simplificationArray.pop();e?(this.running=!0,this.runSimplification(e)):this.running=!1}runSimplification(e){if(e.parallelProcessing)e.settings.forEach((t=>{this._getSimplifier(e).simplify(t,(i=>{void 0!==t.distance&&e.mesh.addLODLevel(t.distance,i),i.isVisible=!0,t.quality===e.settings[e.settings.length-1].quality&&e.successCallback&&e.successCallback(),this.executeNext()}))}));else{const t=this._getSimplifier(e),i=(i,n)=>{t.simplify(i,(t=>{void 0!==i.distance&&e.mesh.addLODLevel(i.distance,t),t.isVisible=!0,n()}))};se.$g.Run(e.settings.length,(t=>{i(e.settings[t.index],(()=>{t.executeNext()}))}),(()=>{e.successCallback&&e.successCallback(),this.executeNext()}))}}_getSimplifier(e){return e.simplificationType,UT.QUADRATIC,new WT(e.mesh)}}var UT;!function(e){e[e.QUADRATIC=0]="QUADRATIC"}(UT||(UT={}));class VT{constructor(e){this._vertices=e,this.error=new Array(4),this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}}class kT{constructor(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new GT,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}updatePosition(e){this.position.copyFrom(e)}}class GT{constructor(e){this.data=new Array(10);for(let t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}det(e,t,i,n,s,r,o,a,l){return this.data[e]*this.data[s]*this.data[l]+this.data[i]*this.data[n]*this.data[a]+this.data[t]*this.data[r]*this.data[o]-this.data[i]*this.data[s]*this.data[o]-this.data[e]*this.data[r]*this.data[a]-this.data[t]*this.data[n]*this.data[l]}addInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e.data[t]}addArrayInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e[t]}add(e){const t=new GT;for(let i=0;i<10;++i)t.data[i]=this.data[i]+e.data[i];return t}static FromData(e,t,i,n){return new GT(GT.DataFromNumbers(e,t,i,n))}static DataFromNumbers(e,t,i,n){return[e*e,e*t,e*i,e*n,t*t,t*i,t*n,i*i,i*n,n*n]}}class zT{constructor(e,t){this.vertexId=e,this.triangleId=t}}class WT{constructor(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=k.kn}simplify(e,t){this._initDecimatedMesh(),se.$g.Run(this._mesh.subMeshes.length,(t=>{this._initWithMesh(t.index,(()=>{this._runDecimation(e,t.index,(()=>{t.executeNext()}))}),e.optimizeMesh)}),(()=>{setTimeout((()=>{t(this._reconstructedMesh)}),0)}))}_runDecimation(e,t,i){const n=~~(this._triangles.length*e.quality);let s=0;const r=this._triangles.length,a=(e,t)=>{setTimeout((()=>{e%5==0&&this._updateMesh(0===e);for(let e=0;e{const t=~~((this._triangles.length/2+e)%this._triangles.length),n=this._triangles[t];if(n&&!(n.error[3]>i||n.deleted||n.isDirty))for(let r=0;r<3;++r)if(n.error[r]{-1===c.indexOf(e)&&(e.deletePending=!0,c.push(e))})),c.length%2!=0)continue;i.q=a.q.add(i.q),i.updatePosition(l);const d=this._references.length;s=this._updateTriangles(i,i,e,s),s=this._updateTriangles(i,a,t,s);const u=this._references.length-d;if(u<=i.triangleCount){if(u)for(let n=0;nr-s<=n))}),0)};se.$g.Run(this.decimationIterations,(e=>{r-s<=n?e.breakLoop():a(e.index,(()=>{e.executeNext()}))}),(()=>{setTimeout((()=>{this._reconstructMesh(t),i()}),0)}))}_initWithMesh(e,t,i){this._vertices=[],this._triangles=[];const n=this._mesh.getVerticesData(ne.o.PositionKind),s=this._mesh.getIndices(),r=this._mesh.subMeshes[e],a=e=>{if(i)for(let t=0;t>0,(e=>{if(!n)return;const t=e+r.verticesStart,i=o.P.FromArray(n,3*t),s=a(i)||new kT(i,this._vertices.length);s.originalOffsets.push(t),s.id===this._vertices.length&&this._vertices.push(s),l.push(s.id)}),(()=>{se.$g.SyncAsyncForLoop(r.indexCount/3,this.syncIterations,(e=>{if(!s)return;const t=3*(r.indexStart/3+e),i=s[t+0],n=s[t+1],o=s[t+2],a=this._vertices[l[i-r.verticesStart]],h=this._vertices[l[n-r.verticesStart]],c=this._vertices[l[o-r.verticesStart]],d=new VT([a,h,c]);d.originalOffset=t,this._triangles.push(d)}),(()=>{this._init(t)}))}))}_init(e){se.$g.SyncAsyncForLoop(this._triangles.length,this.syncIterations,(e=>{const t=this._triangles[e];t.normal=o.P.Cross(t._vertices[1].position.subtract(t._vertices[0].position),t._vertices[2].position.subtract(t._vertices[0].position)).normalize();for(let i=0;i<3;i++)t._vertices[i].q.addArrayInPlace(GT.DataFromNumbers(t.normal.x,t.normal.y,t.normal.z,-o.P.Dot(t.normal,t._vertices[0].position)))}),(()=>{se.$g.SyncAsyncForLoop(this._triangles.length,this.syncIterations,(e=>{const t=this._triangles[e];for(let i=0;i<3;++i)t.error[i]=this._calculateError(t._vertices[i],t._vertices[(i+1)%3]);t.error[3]=Math.min(t.error[0],t.error[1],t.error[2])}),(()=>{e()}))}))}_reconstructMesh(e){const t=[];let i,n,s;for(i=0;i{r.push(e.position.x),r.push(e.position.y),r.push(e.position.z),h&&h.length&&(o.push(h[3*t]),o.push(h[3*t+1]),o.push(h[3*t+2])),c&&c.length&&(a.push(c[2*t]),a.push(c[2*t+1])),d&&d.length&&(l.push(d[4*t]),l.push(d[4*t+1]),l.push(d[4*t+2]),l.push(d[4*t+3])),++u}))}const p=this._reconstructedMesh.getTotalIndices(),f=this._reconstructedMesh.getTotalVertices(),_=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];const m=this._reconstructedMesh.getIndices(),g=this._mesh.getIndices();for(i=0;i{const t=g[n.originalOffset+e];let i=n._vertices[e].originalOffsets.indexOf(t);i<0&&(i=0),m.push(n._vertices[e].id+i+f)}));this._reconstructedMesh.setIndices(m),this._reconstructedMesh.setVerticesData(ne.o.PositionKind,r),o.length>0&&this._reconstructedMesh.setVerticesData(ne.o.NormalKind,o),a.length>0&&this._reconstructedMesh.setVerticesData(ne.o.UVKind,a),l.length>0&&this._reconstructedMesh.setVerticesData(ne.o.ColorKind,l);const v=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],_.forEach((e=>{um.P.AddToMesh(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,e.getMesh())})),um.P.AddToMesh(v.materialIndex,f,u,p,3*t.length,this._reconstructedMesh))}_initDecimatedMesh(){this._reconstructedMesh=new ee.Kj(this._mesh.name+"Decimated",this._mesh.getScene()),this._reconstructedMesh.material=this._mesh.material,this._reconstructedMesh.parent=this._mesh.parent,this._reconstructedMesh.isVisible=!1,this._reconstructedMesh.renderingGroupId=this._mesh.renderingGroupId}_isFlipped(e,t,i,n,s){for(let r=0;r.999)return!0;const p=o.P.Cross(d,u).normalize();if(n[r]=!1,o.P.Dot(p,a.normal)<.2)return!0}return!1}_updateTriangles(e,t,i,n){let s=n;for(let r=0;r{const n=e.getVerticesData(ne.o.PositionKind),s=e.getIndices();if(n&&s)for(let r=0,a=0;r[e.x,e.y,e.z]))}static GetPointsCountInfo(e){const t=new Array(e.length);let i=0;for(let n=e.length;n--;)t[n]=e[n].length/3,i+=t[n];return{total:i,counts:t}}static GetLineLength(e){if(0===e.length)return 0;let t;t="number"==typeof e[0]?jT.ToVector3Array(e):e;const i=o.jp.Vector3[0];let n=0;for(let s=0;s{if(e.length>t){jT.SegmentizeSegmentByCount(e.point1,e.point2,Math.ceil(e.length/t)).forEach((e=>{n.push(e)}))}else n.push(e.point1),n.push(e.point2)})),n}static SegmentizeLineBySegmentCount(e,t){const i=jT.GetLineLength(e)/t;return jT.SegmentizeLineBySegmentLength(e,i)}static GetLineSegments(e){const t=[];for(let i=0;ie.length));return{min:t[0].length,max:t[t.length-1].length}}static GetPositionOnLineByVisibility(e,t,i,n=!1){const s=t*i;let r=0,a=0;const l=e.length;for(let o=0;o[e.x,e.y,e.z]))}static GetArrowCap(e,t,i,n,s,r=0,o=0){return{points:[e.clone(),e.add(t.multiplyByFloats(i,i,i))],widths:[n,s,r,o]}}static GetPointsFromText(e,t,i,n,s=0,r=!0){const o=[],a=mh(e,t,i,n);for(const l of a){for(const e of l.paths){const t=[],i=e.getPoints();for(const e of i)t.push(e.x,e.y,s);o.push(t)}if(r)for(const e of l.holes){const t=[],i=e.getPoints();for(const e of i)t.push(e.x,e.y,s);o.push(t)}}return o}}ee.Kj._GreasedLineMeshParser=(e,t)=>KT.Parse(e,t);class KT extends ee.Kj{constructor(e,t,i){var n,s,r,o;super(e,t,null,null,!1,!1),this.name=e,this._options=i,this._lazy=!1,this._updatable=!1,this.intersectionThreshold=.1,this._lazy=null!==(n=i.lazy)&&void 0!==n&&n,this._updatable=null!==(s=i.updatable)&&void 0!==s&&s,this._vertexPositions=[],this._indices=[],this._uvs=[],this._points=[],this._colorPointers=null!==(r=i.colorPointers)&&void 0!==r?r:[],this._previousAndSide=[],this._nextAndCounters=[],i.widths=null!==(o=i.widths)&&void 0!==o?o:new Array(i.points.length).fill(1),i.points&&this.addPoints(KT.ConvertPoints(i.points))}getClassName(){return"GreasedLineMesh"}static ConvertPoints(e){if(e.length&&Array.isArray(e)&&"number"==typeof e[0])return[e];if(e.length&&Array.isArray(e[0])&&"number"==typeof e[0][0])return e;if(e.length&&!Array.isArray(e[0])&&e[0]instanceof o.P){const t=[];for(let i=0;i0&&Array.isArray(e[0])&&e[0].length>0&&e[0][0]instanceof o.P){const t=[];return e.forEach((e=>{t.push(e.flatMap((e=>[e.x,e.y,e.z])))})),t}if(e instanceof Float32Array)return[Array.from(e)];if(e.length&&e[0]instanceof Float32Array){const t=[];return e.forEach((e=>{t.push(Array.from(e))})),t}return[]}updateLazy(){var e;this.setPoints(this._points),this._options.colorPointers||this._updateColorPointers(),this._createVertexBuffers(),this.refreshBoundingInfo(),null===(e=this.greasedLineMaterial)||void 0===e||e.updateLazy()}dispose(){super.dispose()}isLazy(){return this._lazy}get options(){return this._options}setOffsets(e){this._offsetsBuffer?this._offsetsBuffer&&this._offsetsBuffer.update(e):this._createOffsetsBuffer(e)}setSegmentWidths(e){this._options.widths=e,this._lazy||this._widthsBuffer&&this._widthsBuffer.update(e)}setColorPointers(e){this._lazy||this._colorPointersBuffer&&this._colorPointersBuffer.update(e)}get greasedLineMaterial(){var e,t;return null===(t=null===(e=this.material)||void 0===e?void 0:e.pluginManager)||void 0===t?void 0:t.getPlugin(AT.GREASED_LINE_MATERIAL_NAME)}addPoints(e){const t=e;this._points.push(...t),this._lazy||this.setPoints(this._points)}_updateColorPointers(){let e=0;this._colorPointers=[],this._points.forEach((t=>{for(let i=0;i{var i;const n=[],s=[],r=[],o=jT.GetLineLength(e);for(let d=0,u=0;u0&&(o=KT._CopyV3(a,e),i.push(o[0],o[1],o[2]),i.push(o[0],o[1],o[2]));return o=KT._CompareV3(r-1,0,e)?KT._CopyV3(1,e):KT._CopyV3(r-1,e),i.push(o[0],o[1],o[2]),i.push(o[0],o[1],o[2]),{previous:t,next:i,uvs:s,side:n}}_createVertexBuffers(){const e=new Qe.x;e.positions=this._vertexPositions,e.indices=this._indices,e.uvs=this._uvs,e.applyToMesh(this,this._options.updatable);const t=this._scene.getEngine(),i=new ne.l(t,this._previousAndSide,!1,4);this.setVerticesBuffer(i.createVertexBuffer("grl_previousAndSide",0,4));const n=new ne.l(t,this._nextAndCounters,!1,4);this.setVerticesBuffer(n.createVertexBuffer("grl_nextAndCounters",0,4));const s=new ne.l(t,this._options.widths,this._updatable,1);this.setVerticesBuffer(s.createVertexBuffer("grl_widths",0,1)),this._widthsBuffer=s;const r=new ne.l(t,this._colorPointers,this._updatable,1);this.setVerticesBuffer(r.createVertexBuffer("grl_colorPointers",0,1)),this._colorPointersBuffer=r}_createOffsetsBuffer(e){const t=this._scene.getEngine(),i=new ne.l(t,e,this._updatable,3);this.setVerticesBuffer(i.createVertexBuffer("grl_offsets",0,3)),this._offsetsBuffer=i}}KT._V_START=new o.P,KT._V_END=new o.P,KT._V_OFFSET_START=new o.P,KT._V_OFFSET_END=new o.P,function(e){e[e.COLOR_DISTRIBUTION_NONE=0]="COLOR_DISTRIBUTION_NONE",e[e.COLOR_DISTRIBUTION_REPEAT=1]="COLOR_DISTRIBUTION_REPEAT",e[e.COLOR_DISTRIBUTION_EVEN=2]="COLOR_DISTRIBUTION_EVEN",e[e.COLOR_DISTRIBUTION_START=3]="COLOR_DISTRIBUTION_START",e[e.COLOR_DISTRIBUTION_END=4]="COLOR_DISTRIBUTION_END",e[e.COLOR_DISTRIBUTION_START_END=5]="COLOR_DISTRIBUTION_START_END"}(XT||(XT={})),function(e){e[e.WIDTH_DISTRIBUTION_NONE=0]="WIDTH_DISTRIBUTION_NONE",e[e.WIDTH_DISTRIBUTION_REPEAT=1]="WIDTH_DISTRIBUTION_REPEAT",e[e.WIDTH_DISTRIBUTION_EVEN=2]="WIDTH_DISTRIBUTION_EVEN",e[e.WIDTH_DISTRIBUTION_START=3]="WIDTH_DISTRIBUTION_START",e[e.WIDTH_DISTRIBUTION_END=4]="WIDTH_DISTRIBUTION_END",e[e.WIDTH_DISTRIBUTION_START_END=5]="WIDTH_DISTRIBUTION_START_END"}(YT||(YT={}));i(4081);ee.Kj.prototype.thinInstanceAdd=function(e,t=!0){if(!this.getScene().getEngine().getCaps().instancedArrays)return p.Y.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 n=0;n=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},ee.Kj.prototype.thinInstanceSetAttributeAt=function(e,t,i,n=!0){return e===ne.o.ColorKind&&(e=ne.o.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(ee.Kj.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(e){var t,i;const n=null!==(t=this._thinInstanceDataStorage.matrixData)&&void 0!==t?t:null===(i=this.source)||void 0===i?void 0:i._thinInstanceDataStorage.matrixData;e<=(n?n.length/16:0)&&(this._thinInstanceDataStorage.instancesCount=e)},enumerable:!0,configurable:!0}),ee.Kj.prototype._thinInstanceCreateMatrixBuffer=function(e,t,i=!1){e===ne.o.ColorKind&&(e=ne.o.ColorInstanceKind);const n=new ne.l(this.getEngine(),t,!i,16,!1,!0);for(let s=0;s<4;s++)this.setVerticesBuffer(n.createVertexBuffer(e+s,4*s,4));return n},ee.Kj.prototype.thinInstanceSetBuffer=function(e,t,i=0,n=!1){var s,r,o;i=i||16,"matrix"===e?(null===(s=this._thinInstanceDataStorage.matrixBuffer)||void 0===s||s.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?(null===(r=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===r||r.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=t,null!==t&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",t,n))):(e===ne.o.ColorKind&&(e=ne.o.ColorInstanceKind),null===t?(null===(o=this._userThinInstanceBuffersStorage)||void 0===o?void 0:o.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 ne.o(this.getEngine(),t,e,!n,!1,i,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])))},ee.Kj.prototype.thinInstanceBufferUpdated=function(e){var t,i,n;"matrix"===e?null===(t=this._thinInstanceDataStorage.matrixBuffer)||void 0===t||t.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount):"previousMatrix"===e?null===(i=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===i||i.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount):(e===ne.o.ColorKind&&(e=ne.o.ColorInstanceKind),(null===(n=this._userThinInstanceBuffersStorage)||void 0===n?void 0:n.vertexBuffers[e])&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(this._userThinInstanceBuffersStorage.data[e],0))},ee.Kj.prototype.thinInstancePartialBufferUpdate=function(e,t,i){var n;"matrix"===e?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(t,i):(e===ne.o.ColorKind&&(e=ne.o.ColorInstanceKind),(null===(n=this._userThinInstanceBuffersStorage)||void 0===n?void 0:n.vertexBuffers[e])&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(t,i))},ee.Kj.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];const e=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=new Array;for(let t=0;tnew qT(e,t,i);class qT{get enableSceneOffline(){return this._enableSceneOffline}get enableTexturesOffline(){return this._enableTexturesOffline}constructor(e,t,i=!1){this._idbFactory="undefined"!=typeof indexedDB?indexedDB:void 0,this._currentSceneUrl=qT._ReturnFullUrlLocation(e),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,qT.IDBStorageEnabled?i?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,se.w1.SetImmediate((()=>{t(!0)}))):this._checkManifestFile(t):t(!0)}_checkManifestFile(e){const t=()=>{this._enableSceneOffline=!1,this._enableTexturesOffline=!1,e(!1)},i=()=>{try{if("function"==typeof URL&&0===this._currentSceneUrl.indexOf("http")){const e=new URL(this._currentSceneUrl);return e.pathname+=".manifest",e.toString()}}catch(e){}return`${this._currentSceneUrl}.manifest`};let n=!1,s=i();const r=new y.g;navigator.onLine&&(n=!0,s=s+(null==s.match(/\?/)?"?":"&")+Date.now()),r.open("GET",s),r.addEventListener("load",(()=>{if(200===r.status||qT._ValidateXHRData(r,1))try{const t=JSON.parse(r.response);this._enableSceneOffline=t.enableSceneOffline,this._enableTexturesOffline=t.enableTexturesOffline&&qT._IsUASupportingBlobStorage,t.version&&!isNaN(parseInt(t.version))&&(this._manifestVersionFound=t.version),e(!0)}catch(i){t()}else t()}),!1),r.addEventListener("error",(()=>{if(n){n=!1;const e=i();r.open("GET",e),r.send()}else t()}),!1);try{r.send()}catch(o){p.Y.Error("Error on XHR send request."),e(!1)}}open(e,t){const i=()=>{this._isSupported=!1,t&&t()};if(this._idbFactory&&(this._enableSceneOffline||this._enableTexturesOffline))if(this._db)e&&e();else{this._hasReachedQuota=!1,this._isSupported=!0;const t=this._idbFactory.open("babylonjs",1);t.onerror=()=>{i()},t.onblocked=()=>{p.Y.Error("IDB request blocked. Please reload the page."),i()},t.onsuccess=()=>{this._db=t.result,e()},t.onupgradeneeded=e=>{if(this._db=e.target.result,this._db)try{this._db.createObjectStore("scenes",{keyPath:"sceneUrl"}),this._db.createObjectStore("versions",{keyPath:"sceneUrl"}),this._db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(t){p.Y.Error("Error while creating object stores. Exception: "+t.message),i()}}}else this._isSupported=!1,t&&t()}loadImage(e,t){const i=qT._ReturnFullUrlLocation(e),n=()=>{this._hasReachedQuota||null===this._db?t.src=e:this._saveImageIntoDBAsync(i,t)};this._mustUpdateRessources?n():this._loadImageFromDBAsync(i,t,n)}_loadImageFromDBAsync(e,t,i){if(this._isSupported&&null!==this._db){let n;const s=this._db.transaction(["textures"]);s.onabort=()=>{t.src=e},s.oncomplete=()=>{let s;n&&"function"==typeof URL?(s=URL.createObjectURL(n.data),t.onerror=()=>{p.Y.Error("Error loading image from blob URL: "+s+" switching back to web url: "+e),t.src=e},t.src=s):i()};const r=s.objectStore("textures").get(e);r.onsuccess=e=>{n=e.target.result},r.onerror=()=>{p.Y.Error("Error loading texture "+e+" from DB."),t.src=e}}else p.Y.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t.src=e}_saveImageIntoDBAsync(e,t){let i;if(this._isSupported){const n=()=>{let e;if(i&&"function"==typeof URL)try{e=URL.createObjectURL(i)}catch(n){e=URL.createObjectURL(i)}e&&(t.src=e)};if(qT._IsUASupportingBlobStorage){const s=new y.g;s.open("GET",e),s.responseType="blob",s.addEventListener("load",(()=>{if(200===s.status&&this._db){i=s.response;const o=this._db.transaction(["textures"],"readwrite");o.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(t){}n()},o.oncomplete=()=>{n()};const a={textureUrl:e,data:i};try{const e=o.objectStore("textures").put(a);e.onsuccess=()=>{},e.onerror=()=>{n()}}catch(r){25===r.code&&(qT._IsUASupportingBlobStorage=!1,this._enableTexturesOffline=!1),t.src=e}}else t.src=e}),!1),s.addEventListener("error",(()=>{p.Y.Error("Error in XHR request in BABYLON.Database."),t.src=e}),!1),s.send()}else t.src=e}else p.Y.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t.src=e}_checkVersionFromDB(e,t){this._loadVersionFromDBAsync(e,t,(()=>{this._saveVersionIntoDBAsync(e,t)}))}_loadVersionFromDBAsync(e,t,i){if(this._isSupported&&this._db){let s;try{const n=this._db.transaction(["versions"]);n.oncomplete=()=>{s?this._manifestVersionFound!==s.data?(this._mustUpdateRessources=!0,i()):t(s.data):(this._mustUpdateRessources=!0,i())},n.onabort=()=>{t(-1)};const r=n.objectStore("versions").get(e);r.onsuccess=e=>{s=e.target.result},r.onerror=()=>{p.Y.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(n){p.Y.Error("Error while accessing 'versions' object store (READ OP). Exception: "+n.message),t(-1)}}else p.Y.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t(-1)}_saveVersionIntoDBAsync(e,t){if(this._isSupported&&!this._hasReachedQuota&&this._db)try{const i=this._db.transaction(["versions"],"readwrite");i.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(i){}t(-1)},i.oncomplete=()=>{t(this._manifestVersionFound)};const n={sceneUrl:e,data:this._manifestVersionFound},s=i.objectStore("versions").put(n);s.onsuccess=()=>{},s.onerror=()=>{p.Y.Error("Error in DB add version request in BABYLON.Database.")}}catch(i){p.Y.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+i.message),t(-1)}else t(-1)}loadFile(e,t,i,n,s){const r=qT._ReturnFullUrlLocation(e),o=()=>{this._saveFileAsync(r,t,i,s,n)};this._checkVersionFromDB(r,(e=>{-1!==e?this._mustUpdateRessources?this._saveFileAsync(r,t,i,s,n):this._loadFileAsync(r,t,o):n&&n()}))}_loadFileAsync(e,t,i){if(this._isSupported&&this._db){let n,s;n=-1!==e.indexOf(".babylon")?"scenes":"textures";const r=this._db.transaction([n]);r.oncomplete=()=>{s?t(s.data):i()},r.onabort=()=>{i()};const o=r.objectStore(n).get(e);o.onsuccess=e=>{s=e.target.result},o.onerror=()=>{p.Y.Error("Error loading file "+e+" from DB."),i()}}else p.Y.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t()}_saveFileAsync(e,t,i,n,s){if(this._isSupported){let r;r=-1!==e.indexOf(".babylon")?"scenes":"textures";const o=new y.g;let a;o.open("GET",e+(null==e.match(/\?/)?"?":"&")+Date.now()),n&&(o.responseType="arraybuffer"),i&&(o.onprogress=i),o.addEventListener("load",(()=>{if(200===o.status||o.status<400&&qT._ValidateXHRData(o,n?6:1))if(a=n?o.response:o.responseText,!this._hasReachedQuota&&this._db){const n=this._db.transaction([r],"readwrite");let s;n.onabort=e=>{try{const t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(i){}t(a)},n.oncomplete=()=>{t(a)},s="scenes"===r?{sceneUrl:e,data:a,version:this._manifestVersionFound}:{textureUrl:e,data:a};try{const e=n.objectStore(r).put(s);e.onsuccess=()=>{},e.onerror=()=>{p.Y.Error("Error in DB add file request in BABYLON.Database.")}}catch(i){t(a)}}else t(a);else o.status>=400&&s?s(o):t()}),!1),o.addEventListener("error",(()=>{p.Y.Error("error on XHR request."),s&&s()}),!1),o.send()}else p.Y.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),s&&s()}static _ValidateXHRData(e,t=7){try{if(1&t){if(e.responseText&&e.responseText.length>0)return!0;if(1===t)return!1}if(2&t){const i=bv(e.response);if(i.width&&i.height&&i.width>0&&i.height>0)return!0;if(2===t)return!1}if(4&t){const t=new Uint8Array(e.response,0,3);return 68===t[0]&&68===t[1]&&83===t[2]}}catch(i){}return!1}}qT._IsUASupportingBlobStorage=!0,qT.IDBStorageEnabled=!1,qT._ParseURL=e=>{document.createElement("a").href=e;const t=e.substring(0,e.lastIndexOf("#")),i=e.substring(t.lastIndexOf("/")+1,e.length);return e.substring(0,e.indexOf(i,0))},qT._ReturnFullUrlLocation=e=>-1===e.indexOf("http:/")&&-1===e.indexOf("https:/")&&"undefined"!=typeof window?qT._ParseURL(window.location.href)+e:e;class $T{_isUbo(e){return void 0!==e.addUniform}constructor(e){this._isUbo(e)?(this.setMatrix3x3=e.updateMatrix3x3.bind(e),this.setMatrix2x2=e.updateMatrix2x2.bind(e),this.setFloat=e.updateFloat.bind(e),this.setFloat2=e.updateFloat2.bind(e),this.setFloat3=e.updateFloat3.bind(e),this.setFloat4=e.updateFloat4.bind(e),this.setFloatArray=e.updateFloatArray.bind(e),this.setArray=e.updateArray.bind(e),this.setIntArray=e.updateIntArray.bind(e),this.setMatrix=e.updateMatrix.bind(e),this.setMatrices=e.updateMatrices.bind(e),this.setVector3=e.updateVector3.bind(e),this.setVector4=e.updateVector4.bind(e),this.setColor3=e.updateColor3.bind(e),this.setColor4=e.updateColor4.bind(e),this.setDirectColor4=e.updateDirectColor4.bind(e),this.setInt=e.updateInt.bind(e),this.setInt2=e.updateInt2.bind(e),this.setInt3=e.updateInt3.bind(e),this.setInt4=e.updateInt4.bind(e)):(this.setMatrix3x3=e.setMatrix3x3.bind(e),this.setMatrix2x2=e.setMatrix2x2.bind(e),this.setFloat=e.setFloat.bind(e),this.setFloat2=e.setFloat2.bind(e),this.setFloat3=e.setFloat3.bind(e),this.setFloat4=e.setFloat4.bind(e),this.setFloatArray=e.setFloatArray.bind(e),this.setArray=e.setArray.bind(e),this.setIntArray=e.setIntArray.bind(e),this.setMatrix=e.setMatrix.bind(e),this.setMatrices=e.setMatrices.bind(e),this.setVector3=e.setVector3.bind(e),this.setVector4=e.setVector4.bind(e),this.setColor3=e.setColor3.bind(e),this.setColor4=e.setColor4.bind(e),this.setDirectColor4=e.setDirectColor4.bind(e),this.setInt=e.setInt.bind(e),this.setInt2=e.setInt2.bind(e),this.setInt3=e.setInt3.bind(e),this.setInt4=e.setInt4.bind(e))}}const QT="gpuUpdateParticlesPixelShader",ZT="#version 300 es\nvoid main() {\ndiscard;\n}\n";Ht.v.ShadersStore[QT]=ZT;const JT="gpuUpdateParticlesVertexShader",eS="#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\n#ifndef LOCAL\nuniform mat4 emitterWM;\n#endif\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\nin vec3 position;\n#ifdef CUSTOMEMITTER\nin vec3 initialPosition;\n#endif\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;\nin vec3 noiseCoordinates2;\n#endif\nout vec3 outPosition;\n#ifdef CUSTOMEMITTER\nout vec3 outInitialPosition;\n#endif\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;\nout vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec4 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nfloat newAge=age+timeDelta; \nif (newAge>=life && stopFactor != 0.) {\nvec3 newPosition;\nvec3 newDirection;\nvec4 randoms=getRandomVec4(seed.x);\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=newAge-life;\noutSeed=seed;\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nnewPosition=vec3(0,0,0);\nnewDirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nnewPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\nnewDirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nnewPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\nnewDirection=newPosition+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nnewPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\nnewDirection=normalize(direction1+(direction2-direction1)*randoms3);\n#else\nnewDirection=normalize(newPosition+directionRandomizer*randoms3);\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nnewPosition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\nnewDirection=direction1+(direction2-direction1)*randoms3;\n#else\nangle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;\nnewDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));\nnewDirection=normalize(newDirection);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.0001;\n#else\nfloat h=randoms2.y*height.y;\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h *height.x;\nnewPosition=vec3(randX,randY,randZ); \nif (abs(cos(coneAngle))==1.0) {\nnewDirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\nnewDirection=normalize(newPosition+directionRandomizer*randoms3); \n}\n#elif defined(CUSTOMEMITTER)\nnewPosition=initialPosition;\noutInitialPosition=initialPosition;\n#else \nnewPosition=vec3(0.,0.,0.);\nnewDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\n#ifdef LOCAL\noutPosition=newPosition;\n#else\noutPosition=(emitterWM*vec4(newPosition,1.)).xyz;\n#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\n#ifndef BILLBOARD \noutInitialDirection=direction;\n#endif\n#else\n#ifdef LOCAL\nvec3 initial=newDirection;\n#else \nvec3 initial=(emitterWM*vec4(newDirection,0.)).xyz;\n#endif\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#if defined(CUSTOMEMITTER)\noutPosition=position+(direction-position)*ageGradient; \noutInitialPosition=initialPosition;\n#else\noutPosition=position+direction*directionScale;\n#endif\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\n#else\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif \n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#else\nfloat cellStartOffset=0.;\n#endif \nfloat ratio=0.;\nif (cellInfos.w==1.0) {\nratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);\n}\nelse {\nratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);\n}\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}";Ht.v.ShadersStore[JT]=eS;(0,l.H)("BABYLON.WebGL2ParticleSystem",class{constructor(e,t){this._renderVAO=[],this._updateVAO=[],this.alignDataInBuffer=!1,this._parent=e,this._engine=t,this._updateEffectOptions={attributes:["position","initialPosition","age","life","seed","size","color","direction","initialDirection","angle","cellIndex","cellStartOffset","noiseCoordinates1","noiseCoordinates2"],uniformsNames:["currentCount","timeDelta","emitterWM","lifeTime","color1","color2","sizeRange","scaleRange","gravity","emitPower","direction1","direction2","minEmitBox","maxEmitBox","radius","directionRandomizer","height","coneAngle","stopFactor","angleRange","radiusRange","cellInfos","noiseStrength","limitVelocityDamping"],uniformBuffersNames:[],samplers:["randomSampler","randomSampler2","sizeGradientSampler","angularSpeedGradientSampler","velocityGradientSampler","limitVelocityGradientSampler","noiseSampler","dragGradientSampler"],defines:"",fallbacks:null,onCompiled:null,onError:null,indexParameters:null,maxSimultaneousLights:0,transformFeedbackVaryings:[]}}isUpdateBufferCreated(){return!!this._updateEffect}isUpdateBufferReady(){var e,t;return null!==(t=null===(e=this._updateEffect)||void 0===e?void 0:e.isReady())&&void 0!==t&&t}createUpdateBuffer(e){return this._updateEffectOptions.transformFeedbackVaryings=["outPosition"],this._updateEffectOptions.transformFeedbackVaryings.push("outAge"),this._updateEffectOptions.transformFeedbackVaryings.push("outSize"),this._updateEffectOptions.transformFeedbackVaryings.push("outLife"),this._updateEffectOptions.transformFeedbackVaryings.push("outSeed"),this._updateEffectOptions.transformFeedbackVaryings.push("outDirection"),this._parent.particleEmitterType instanceof di&&this._updateEffectOptions.transformFeedbackVaryings.push("outInitialPosition"),this._parent._colorGradientsTexture||this._updateEffectOptions.transformFeedbackVaryings.push("outColor"),this._parent._isBillboardBased||this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection"),this._parent.noiseTexture&&(this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1"),this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2")),this._updateEffectOptions.transformFeedbackVaryings.push("outAngle"),this._parent.isAnimationSheetEnabled&&(this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex"),this._parent.spriteRandomStartCell&&this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset")),this._updateEffectOptions.defines=e,this._updateEffect=new ft.Q("gpuUpdateParticles",this._updateEffectOptions,this._engine),new $T(this._updateEffect)}createVertexBuffers(e,t){this._updateVAO.push(this._createUpdateVAO(e)),this._renderVAO.push(this._engine.recordVertexArrayObject(t,null,this._parent._getWrapper(this._parent.blendMode).effect)),this._engine.bindArrayBuffer(null)}createParticleBuffer(e){return e}bindDrawBuffers(e){this._engine.bindVertexArrayObject(this._renderVAO[e],null)}preUpdateParticleBuffer(){const e=this._engine;if(this._engine.enableEffect(this._updateEffect),!e.setState)throw new Error("GPU particles cannot work without a full Engine. ThinEngine is not supported")}updateParticleBuffer(e,t,i){this._updateEffect.setTexture("randomSampler",this._parent._randomTexture),this._updateEffect.setTexture("randomSampler2",this._parent._randomTexture2),this._parent._sizeGradientsTexture&&this._updateEffect.setTexture("sizeGradientSampler",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateEffect.setTexture("angularSpeedGradientSampler",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateEffect.setTexture("velocityGradientSampler",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateEffect.setTexture("limitVelocityGradientSampler",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateEffect.setTexture("dragGradientSampler",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateEffect.setTexture("noiseSampler",this._parent.noiseTexture),this._engine.bindVertexArrayObject(this._updateVAO[e],null);const n=this._engine;n.bindTransformFeedbackBuffer(t.getBuffer()),n.setRasterizerState(!1),n.beginTransformFeedback(!0),n.drawArraysType(3,0,i),n.endTransformFeedback(),n.setRasterizerState(!0),n.bindTransformFeedbackBuffer(null)}releaseBuffers(){}releaseVertexBuffers(){for(let e=0;ee)return void i(t[0],t[0],1);for(let s=0;s=n.gradient&&e<=r.gradient){return void i(n,r,(e-n.gradient)/(r.gradient-n.gradient))}}const n=t.length-1;i(t[n],t[n],1)}}class aS{constructor(e){this.particleSystem=e,this.position=o.P.Zero(),this.direction=o.P.Zero(),this.color=new a.HE(0,0,0,0),this.colorStep=new a.HE(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new o.FM(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new a.HE(0,0,0,0),this._currentColor2=new a.HE(0,0,0,0),this._currentSize1=0,this._currentSize2=0,this._currentAngularSpeed1=0,this._currentAngularSpeed2=0,this._currentVelocity1=0,this._currentVelocity2=0,this._currentLimitVelocity1=0,this._currentLimitVelocity2=0,this._currentDrag1=0,this._currentDrag2=0,this.id=aS._Count++,this.particleSystem.isAnimationSheetEnabled&&this._updateCellInfoFromSystem()}_updateCellInfoFromSystem(){this.cellIndex=this.particleSystem.startSpriteCellID}updateCellIndex(){let e=this.age,t=this.particleSystem.spriteCellChangeSpeed;this.particleSystem.spriteRandomStartCell&&(void 0===this._randomCellOffset&&(this._randomCellOffset=Math.random()*this.lifeTime),0===t?(t=1,e=this._randomCellOffset):e+=this._randomCellOffset);const i=this._initialEndSpriteCellID-this._initialStartSpriteCellID;let n;n=this._initialSpriteCellLoop?S.R.Clamp(e*t%this.lifeTime/this.lifeTime):S.R.Clamp(e*t/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+n*i|0}_inheritParticleInfoToSubEmitter(e){if(e.particleSystem.emitter.position){const t=e.particleSystem.emitter;if(t.position.copyFrom(this.position),e.inheritDirection){const e=o.jp.Vector3[0];this.direction.normalizeToRef(e),t.setDirection(e,0,Math.PI/2)}}else{e.particleSystem.emitter.copyFrom(this.position)}this.direction.scaleToRef(e.inheritedVelocityAmount/2,o.jp.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(o.jp.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach((e=>{this._inheritParticleInfoToSubEmitter(e)}))}_reset(){this.age=0,this.id=aS._Count++,this._currentColorGradient=null,this._currentSizeGradient=null,this._currentAngularSpeedGradient=null,this._currentVelocityGradient=null,this._currentLimitVelocityGradient=null,this._currentDragGradient=null,this.cellIndex=this.particleSystem.startSpriteCellID,this._randomCellOffset=void 0}copyTo(e){e.position.copyFrom(this.position),this._initialDirection?e._initialDirection?e._initialDirection.copyFrom(this._initialDirection):e._initialDirection=this._initialDirection.clone():e._initialDirection=null,e.direction.copyFrom(this.direction),this._localPosition&&(e._localPosition?e._localPosition.copyFrom(this._localPosition):e._localPosition=this._localPosition.clone()),e.color.copyFrom(this.color),e.colorStep.copyFrom(this.colorStep),e.lifeTime=this.lifeTime,e.age=this.age,e._randomCellOffset=this._randomCellOffset,e.size=this.size,e.scale.copyFrom(this.scale),e.angle=this.angle,e.angularSpeed=this.angularSpeed,e.particleSystem=this.particleSystem,e.cellIndex=this.cellIndex,e.id=this.id,e._attachedSubEmitters=this._attachedSubEmitters,this._currentColorGradient&&(e._currentColorGradient=this._currentColorGradient,e._currentColor1.copyFrom(this._currentColor1),e._currentColor2.copyFrom(this._currentColor2)),this._currentSizeGradient&&(e._currentSizeGradient=this._currentSizeGradient,e._currentSize1=this._currentSize1,e._currentSize2=this._currentSize2),this._currentAngularSpeedGradient&&(e._currentAngularSpeedGradient=this._currentAngularSpeedGradient,e._currentAngularSpeed1=this._currentAngularSpeed1,e._currentAngularSpeed2=this._currentAngularSpeed2),this._currentVelocityGradient&&(e._currentVelocityGradient=this._currentVelocityGradient,e._currentVelocity1=this._currentVelocity1,e._currentVelocity2=this._currentVelocity2),this._currentLimitVelocityGradient&&(e._currentLimitVelocityGradient=this._currentLimitVelocityGradient,e._currentLimitVelocity1=this._currentLimitVelocity1,e._currentLimitVelocity2=this._currentLimitVelocity2),this._currentDragGradient&&(e._currentDragGradient=this._currentDragGradient,e._currentDrag1=this._currentDrag1,e._currentDrag2=this._currentDrag2),this.particleSystem.isAnimationSheetEnabled&&(e._initialStartSpriteCellID=this._initialStartSpriteCellID,e._initialEndSpriteCellID=this._initialEndSpriteCellID,e._initialSpriteCellLoop=this._initialSpriteCellLoop),this.particleSystem.useRampGradients&&(e.remapData&&this.remapData?e.remapData.copyFrom(this.remapData):e.remapData=new o.Lt(0,0,0,0)),this._randomNoiseCoordinates1&&(e._randomNoiseCoordinates1?(e._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1),e._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2)):(e._randomNoiseCoordinates1=this._randomNoiseCoordinates1.clone(),e._randomNoiseCoordinates2=this._randomNoiseCoordinates2.clone()))}}var lS;aS._Count=0,function(e){e[e.ATTACHED=0]="ATTACHED",e[e.END=1]="END"}(lS||(lS={}));class hS{constructor(e){if(this.particleSystem=e,this.type=lS.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){const t=(0,l.q)("BABYLON.AbstractMesh");e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;if(e){if(e instanceof o.P)e=e.clone();else if(-1!==e.getClassName().indexOf("Mesh")){e=new((0,l.q)("BABYLON.Mesh"))("",e.getScene()),e.isVisible=!1}}else e=new o.P;const t=new hS(this.particleSystem.clone(this.particleSystem.name,e));return t.particleSystem.name+="Clone",t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem._disposeEmitterOnDispose=!0,t.particleSystem.disposeOnStop=!0,t}serialize(e=!1){const t={};return t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem=this.particleSystem.serialize(e),t}static _ParseParticleSystem(e,t,i,n=!1){throw(0,ge.S)("ParseParticle")}static Parse(e,t,i){const n=e.particleSystem,s=new hS(hS._ParseParticleSystem(n,t,i,!0));return s.type=e.type,s.inheritDirection=e.inheritDirection,s.inheritedVelocityAmount=e.inheritedVelocityAmount,s.particleSystem._isSubEmitter=!0,s}dispose(){this.particleSystem.dispose()}}const cS="particlesPixelShader",dS="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include\n#include\n#include\n#include\n#include\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ht.v.ShadersStore[cS]=dS;const uS="particlesVertexShader",pS="attribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET\nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD\nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction;\n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET\nuniform vec3 particlesInfos; \n#endif\nvarying vec2 vUV;\nvarying vec4 vColor;\nvarying vec3 vPositionW;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)\nuniform mat4 invView;\n#endif\n#include\n#include\n#ifdef BILLBOARD\nuniform vec3 eyePosition;\n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix= mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\n#ifdef BILLBOARDSTRETCHED_LOCAL\nvec3 row1=direction;\n#else\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\n#endif\nmat3 rotMatrix= mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD\nvec3 rotatedCorner;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvPositionW=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition;\nvPositionW=rotateAlign(toCamera,rotatedCorner);\nvec3 viewPos=(view*vec4(vPositionW,1.0)).xyz;\n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;\nvPositionW=(invView*vec4(viewPos,1)).xyz;\n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\ngl_Position=projection*vec4(viewPos,1.0);\n#else\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvPositionW=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(vPositionW,1.0);\n#endif\nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex*particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset/particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nvec4 worldPos=vec4(vPositionW,1.0);\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}";Ht.v.ShadersStore[uS]=pS;class fS extends pi{set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get useRampGradients(){return this._useRampGradients}set useRampGradients(e){this._useRampGradients!==e&&(this._useRampGradients=e,this._resetEffect())}get particles(){return this._particles}getActiveCount(){return this._particles.length}getClassName(){return"ParticleSystem"}isStopping(){return this._stopped&&this.isAlive()}getCustomEffect(e=0){var t,i;return null!==(i=null===(t=this._customWrappers[e])||void 0===t?void 0:t.effect)&&void 0!==i?i:this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){var t;return null!==(t=this._customWrappers[e])&&void 0!==t?t:this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new $t.q(this._engine),this._customWrappers[t].effect=e,this._customWrappers[t].drawContext&&(this._customWrappers[t].drawContext.useInstancing=this._useInstancing)}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new r.y$),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"particles"}get vertexBuffers(){return this._vertexBuffers}get indexBuffer(){return this._indexBuffer}constructor(e,t,i,n=null,s=!1,l=.01){super(e),this._emitterInverseWorldMatrix=o.y3.Identity(),this._inheritedVelocityOffset=new o.P,this.onDisposeObservable=new r.y$,this.onStoppedObservable=new r.y$,this._particles=new Array,this._stockParticles=new Array,this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new a.HE(0,0,0,0),this._colorDiff=new a.HE(0,0,0,0),this._scaledDirection=o.P.Zero(),this._scaledGravity=o.P.Zero(),this._currentRenderId=-1,this._useInstancing=!1,this._started=!1,this._stopped=!1,this._actualFrame=0,this._currentEmitRate1=0,this._currentEmitRate2=0,this._currentStartSize1=0,this._currentStartSize2=0,this.updateInAnimate=!0,this._rawTextureWidth=256,this._useRampGradients=!1,this._disposeEmitterOnDispose=!1,this.isLocal=!1,this.isGPU=!1,this._onBeforeDrawParticlesObservable=null,this.recycleParticle=e=>{const t=this._particles.pop();t!==e&&t.copyTo(e),this._stockParticles.push(t)},this._createParticle=()=>{let e;if(0!==this._stockParticles.length?(e=this._stockParticles.pop(),e._reset()):e=new aS(this),this._subEmitters&&this._subEmitters.length>0){const t=this._subEmitters[Math.floor(Math.random()*this._subEmitters.length)];e._attachedSubEmitters=[],t.forEach((t=>{if(t.type===lS.ATTACHED){const i=t.clone();e._attachedSubEmitters.push(i),i.particleSystem.start()}}))}return e},this._emitFromParticle=e=>{if(!this._subEmitters||0===this._subEmitters.length)return;const t=Math.floor(Math.random()*this._subEmitters.length);this._subEmitters[t].forEach((t=>{if(t.type===lS.END){const i=t.clone();e._inheritParticleInfoToSubEmitter(i),i.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(i.particleSystem),i.particleSystem.start()}}))},this._capacity=t,this._epsilon=l,this._isAnimationSheetEnabled=s,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=o.y3.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||m.l.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._attachImageProcessingConfiguration(null),this._customWrappers={0:new $t.q(this._engine)},this._customWrappers[0].effect=n,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new ni;let h=null;this.updateFunction=e=>{var t;let i=null;this.noiseTexture&&(i=this.noiseTexture.getSize(),null===(t=this.noiseTexture.getContent())||void 0===t||t.then((e=>{h=e})));for(let n=0;nt.lifeTime){const e=t.age-r;s=(t.lifeTime-r)*s/e,t.age=t.lifeTime}const l=t.age/t.lifeTime;this._colorGradients&&this._colorGradients.length>0?oS.GetCurrentGradient(l,this._colorGradients,((e,i,n)=>{e!==t._currentColorGradient&&(t._currentColor1.copyFrom(t._currentColor2),i.getColorToRef(t._currentColor2),t._currentColorGradient=e),a.HE.LerpToRef(t._currentColor1,t._currentColor2,n,t.color)})):(t.colorStep.scaleToRef(s,this._scaledColorStep),t.color.addInPlace(this._scaledColorStep),t.color.a<0&&(t.color.a=0)),this._angularSpeedGradients&&this._angularSpeedGradients.length>0&&oS.GetCurrentGradient(l,this._angularSpeedGradients,((e,i,n)=>{e!==t._currentAngularSpeedGradient&&(t._currentAngularSpeed1=t._currentAngularSpeed2,t._currentAngularSpeed2=i.getFactor(),t._currentAngularSpeedGradient=e),t.angularSpeed=S.R.Lerp(t._currentAngularSpeed1,t._currentAngularSpeed2,n)})),t.angle+=t.angularSpeed*s;let c=s;if(this._velocityGradients&&this._velocityGradients.length>0&&oS.GetCurrentGradient(l,this._velocityGradients,((e,i,n)=>{e!==t._currentVelocityGradient&&(t._currentVelocity1=t._currentVelocity2,t._currentVelocity2=i.getFactor(),t._currentVelocityGradient=e),c*=S.R.Lerp(t._currentVelocity1,t._currentVelocity2,n)})),t.direction.scaleToRef(c,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&oS.GetCurrentGradient(l,this._limitVelocityGradients,((e,i,n)=>{e!==t._currentLimitVelocityGradient&&(t._currentLimitVelocity1=t._currentLimitVelocity2,t._currentLimitVelocity2=i.getFactor(),t._currentLimitVelocityGradient=e);const s=S.R.Lerp(t._currentLimitVelocity1,t._currentLimitVelocity2,n);t.direction.length()>s&&t.direction.scaleInPlace(this.limitVelocityDamping)})),this._dragGradients&&this._dragGradients.length>0&&oS.GetCurrentGradient(l,this._dragGradients,((e,i,n)=>{e!==t._currentDragGradient&&(t._currentDrag1=t._currentDrag2,t._currentDrag2=i.getFactor(),t._currentDragGradient=e);const s=S.R.Lerp(t._currentDrag1,t._currentDrag2,n);this._scaledDirection.scaleInPlace(1-s)})),this.isLocal&&t._localPosition?(t._localPosition.addInPlace(this._scaledDirection),o.P.TransformCoordinatesToRef(t._localPosition,this._emitterWorldMatrix,t.position)):t.position.addInPlace(this._scaledDirection),h&&i&&t._randomNoiseCoordinates1){const e=this._fetchR(t._randomNoiseCoordinates1.x,t._randomNoiseCoordinates1.y,i.width,i.height,h),n=this._fetchR(t._randomNoiseCoordinates1.z,t._randomNoiseCoordinates2.x,i.width,i.height,h),r=this._fetchR(t._randomNoiseCoordinates2.y,t._randomNoiseCoordinates2.z,i.width,i.height,h),a=o.jp.Vector3[0],l=o.jp.Vector3[1];a.copyFromFloats((2*e-1)*this.noiseStrength.x,(2*n-1)*this.noiseStrength.y,(2*r-1)*this.noiseStrength.z),a.scaleToRef(s,l),t.direction.addInPlace(l)}this.gravity.scaleToRef(s,this._scaledGravity),t.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&oS.GetCurrentGradient(l,this._sizeGradients,((e,i,n)=>{e!==t._currentSizeGradient&&(t._currentSize1=t._currentSize2,t._currentSize2=i.getFactor(),t._currentSizeGradient=e),t.size=S.R.Lerp(t._currentSize1,t._currentSize2,n)})),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&oS.GetCurrentGradient(l,this._colorRemapGradients,((e,i,n)=>{const s=S.R.Lerp(e.factor1,i.factor1,n),r=S.R.Lerp(e.factor2,i.factor2,n);t.remapData.x=s,t.remapData.y=r-s})),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&oS.GetCurrentGradient(l,this._alphaRemapGradients,((e,i,n)=>{const s=S.R.Lerp(e.factor1,i.factor1,n),r=S.R.Lerp(e.factor2,i.factor2,n);t.remapData.z=s,t.remapData.w=r-s}))),this._isAnimationSheetEnabled&&t.updateCellIndex(),t._inheritParticleInfoToSubEmitters(),t.age>=t.lifeTime&&(this._emitFromParticle(t),t._attachedSubEmitters&&(t._attachedSubEmitters.forEach((e=>{e.particleSystem.disposeOnStop=!0,e.particleSystem.stop()})),t._attachedSubEmitters=null),this.recycleParticle(t),n--)}}}_addFactorGradient(e,t,i,n){const s=new rS(t,i,n);e.push(s),e.sort(((e,t)=>e.gradientt.gradient?1:0))}_removeFactorGradient(e,t){if(!e)return;let i=0;for(const n of e){if(n.gradient===t){e.splice(i,1);break}i++}}addLifeTimeGradient(e,t,i){return this._lifeTimeGradients||(this._lifeTimeGradients=[]),this._addFactorGradient(this._lifeTimeGradients,e,t,i),this}removeLifeTimeGradient(e){return this._removeFactorGradient(this._lifeTimeGradients,e),this}addSizeGradient(e,t,i){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t,i),this}removeSizeGradient(e){return this._removeFactorGradient(this._sizeGradients,e),this}addColorRemapGradient(e,t,i){return this._colorRemapGradients||(this._colorRemapGradients=[]),this._addFactorGradient(this._colorRemapGradients,e,t,i),this}removeColorRemapGradient(e){return this._removeFactorGradient(this._colorRemapGradients,e),this}addAlphaRemapGradient(e,t,i){return this._alphaRemapGradients||(this._alphaRemapGradients=[]),this._addFactorGradient(this._alphaRemapGradients,e,t,i),this}removeAlphaRemapGradient(e){return this._removeFactorGradient(this._alphaRemapGradients,e),this}addAngularSpeedGradient(e,t,i){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t,i),this}removeAngularSpeedGradient(e){return this._removeFactorGradient(this._angularSpeedGradients,e),this}addVelocityGradient(e,t,i){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t,i),this}removeVelocityGradient(e){return this._removeFactorGradient(this._velocityGradients,e),this}addLimitVelocityGradient(e,t,i){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t,i),this}removeLimitVelocityGradient(e){return this._removeFactorGradient(this._limitVelocityGradients,e),this}addDragGradient(e,t,i){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t,i),this}removeDragGradient(e){return this._removeFactorGradient(this._dragGradients,e),this}addEmitRateGradient(e,t,i){return this._emitRateGradients||(this._emitRateGradients=[]),this._addFactorGradient(this._emitRateGradients,e,t,i),this}removeEmitRateGradient(e){return this._removeFactorGradient(this._emitRateGradients,e),this}addStartSizeGradient(e,t,i){return this._startSizeGradients||(this._startSizeGradients=[]),this._addFactorGradient(this._startSizeGradients,e,t,i),this}removeStartSizeGradient(e){return this._removeFactorGradient(this._startSizeGradients,e),this}_createRampGradientTexture(){if(!this._rampGradients||!this._rampGradients.length||this._rampGradientsTexture||!this._scene)return;const e=new Uint8Array(4*this._rawTextureWidth),t=a.zZ.Color3[0];for(let i=0;i{a.Wo.LerpToRef(n.color,s.color,r,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255}))}this._rampGradientsTexture=ze.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1)}getRampGradients(){return this._rampGradients}forceRefreshGradients(){this._syncRampGradientTexture()}_syncRampGradientTexture(){this._rampGradients&&(this._rampGradients.sort(((e,t)=>e.gradientt.gradient?1:0)),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture())}addRampGradient(e,t){this._rampGradients||(this._rampGradients=[]);const i=new sS(e,t);return this._rampGradients.push(i),this._syncRampGradientTexture(),this}removeRampGradient(e){return this._removeGradientAndTexture(e,this._rampGradients,this._rampGradientsTexture),this._rampGradientsTexture=null,this._rampGradients&&this._rampGradients.length>0&&this._createRampGradientTexture(),this}addColorGradient(e,t,i){this._colorGradients||(this._colorGradients=[]);const n=new nS(e,t,i);return this._colorGradients.push(n),this._colorGradients.sort(((e,t)=>e.gradientt.gradient?1:0)),this}removeColorGradient(e){if(!this._colorGradients)return this;let t=0;for(const i of this._colorGradients){if(i.gradient===e){this._colorGradients.splice(t,1);break}t++}return this}resetDrawCache(){for(const e of this._drawWrappers)if(e)for(const t of e)null==t||t.dispose();this._drawWrappers=[]}_fetchR(e,t,i,n,s){return s[4*(((e=.5*Math.abs(e)+.5)*i%i|0)+((t=.5*Math.abs(t)+.5)*n%n|0)*i)]/255}_reset(){this._resetEffect()}_resetEffect(){this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),this._createVertexBuffers()}_createVertexBuffers(){this._vertexBufferSize=this._useInstancing?10:12,this._isAnimationSheetEnabled&&(this._vertexBufferSize+=1),this._isBillboardBased&&this.billboardMode!==fS.BILLBOARDMODE_STRETCHED&&this.billboardMode!==fS.BILLBOARDMODE_STRETCHED_LOCAL||(this._vertexBufferSize+=3),this._useRampGradients&&(this._vertexBufferSize+=4);const e=this._engine,t=this._vertexBufferSize*(this._useInstancing?1:4);this._vertexData=new Float32Array(this._capacity*t),this._vertexBuffer=new ne.l(e,this._vertexData,!0,t);let i=0;const n=this._vertexBuffer.createVertexBuffer(ne.o.PositionKind,i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[ne.o.PositionKind]=n,i+=3;const s=this._vertexBuffer.createVertexBuffer(ne.o.ColorKind,i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[ne.o.ColorKind]=s,i+=4;const r=this._vertexBuffer.createVertexBuffer("angle",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=r,i+=1;const o=this._vertexBuffer.createVertexBuffer("size",i,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=o,i+=2,this._isAnimationSheetEnabled){const e=this._vertexBuffer.createVertexBuffer("cellIndex",i,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=e,i+=1}if(!this._isBillboardBased||this.billboardMode===fS.BILLBOARDMODE_STRETCHED||this.billboardMode===fS.BILLBOARDMODE_STRETCHED_LOCAL){const e=this._vertexBuffer.createVertexBuffer("direction",i,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=e,i+=3}if(this._useRampGradients){const e=this._vertexBuffer.createVertexBuffer("remapData",i,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=e,i+=4}let a;if(this._useInstancing){const t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new ne.l(e,t,!1,2),a=this._spriteBuffer.createVertexBuffer("offset",0,2)}else a=this._vertexBuffer.createVertexBuffer("offset",i,2,this._vertexBufferSize,this._useInstancing),i+=2;this._vertexBuffers.offset=a,this.resetDrawCache()}_createIndexBuffer(){if(this._useInstancing)return;const e=[];let t=0;for(let i=0;i{e instanceof fS?this._subEmitters.push([new hS(e)]):e instanceof hS?this._subEmitters.push([e]):e instanceof Array&&this._subEmitters.push(e)}))}start(e=this.startDelay){var t;if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";if(e)setTimeout((()=>{this.start(0)}),e);else{if(this._prepareSubEmitterInternalArray(),this._started=!0,this._stopped=!1,this._actualFrame=0,this._subEmitters&&0!=this._subEmitters.length&&(this.activeSubSystems=new Array),this._emitRateGradients&&(this._emitRateGradients.length>0&&(this._currentEmitRateGradient=this._emitRateGradients[0],this._currentEmitRate1=this._currentEmitRateGradient.getFactor(),this._currentEmitRate2=this._currentEmitRate1),this._emitRateGradients.length>1&&(this._currentEmitRate2=this._emitRateGradients[1].getFactor())),this._startSizeGradients&&(this._startSizeGradients.length>0&&(this._currentStartSizeGradient=this._startSizeGradients[0],this._currentStartSize1=this._currentStartSizeGradient.getFactor(),this._currentStartSize2=this._currentStartSize1),this._startSizeGradients.length>1&&(this._currentStartSize2=this._startSizeGradients[1].getFactor())),this.preWarmCycles){-1!==(null===(t=this.emitter)||void 0===t?void 0:t.getClassName().indexOf("Mesh"))&&this.emitter.computeWorldMatrix(!0);const e=this.noiseTexture;if(e&&e.onGeneratedObservable)e.onGeneratedObservable.addOnce((()=>{setTimeout((()=>{for(let t=0;t0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}}stop(e=!0){this._stopped||(this.onStoppedObservable.notifyObservers(this),this._stopped=!0,e&&this._stopSubEmitters())}reset(){this._stockParticles.length=0,this._particles.length=0}_appendParticleVertex(e,t,i,n){let s=e*this._vertexBufferSize;if(this._vertexData[s++]=t.position.x+this.worldOffset.x,this._vertexData[s++]=t.position.y+this.worldOffset.y,this._vertexData[s++]=t.position.z+this.worldOffset.z,this._vertexData[s++]=t.color.r,this._vertexData[s++]=t.color.g,this._vertexData[s++]=t.color.b,this._vertexData[s++]=t.color.a,this._vertexData[s++]=t.angle,this._vertexData[s++]=t.scale.x*t.size,this._vertexData[s++]=t.scale.y*t.size,this._isAnimationSheetEnabled&&(this._vertexData[s++]=t.cellIndex),this._isBillboardBased)this.billboardMode!==fS.BILLBOARDMODE_STRETCHED&&this.billboardMode!==fS.BILLBOARDMODE_STRETCHED_LOCAL||(this._vertexData[s++]=t.direction.x,this._vertexData[s++]=t.direction.y,this._vertexData[s++]=t.direction.z);else if(t._initialDirection){let e=t._initialDirection;this.isLocal&&(o.P.TransformNormalToRef(e,this._emitterWorldMatrix,o.jp.Vector3[0]),e=o.jp.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[s++]=e.x,this._vertexData[s++]=e.y,this._vertexData[s++]=e.z}else{let e=t.direction;this.isLocal&&(o.P.TransformNormalToRef(e,this._emitterWorldMatrix,o.jp.Vector3[0]),e=o.jp.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[s++]=e.x,this._vertexData[s++]=e.y,this._vertexData[s++]=e.z}this._useRampGradients&&t.remapData&&(this._vertexData[s++]=t.remapData.x,this._vertexData[s++]=t.remapData.y,this._vertexData[s++]=t.remapData.z,this._vertexData[s++]=t.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===n?n=this._epsilon:1===n&&(n=1-this._epsilon)),this._vertexData[s++]=i,this._vertexData[s++]=n)}_stopSubEmitters(){this.activeSubSystems&&(this.activeSubSystems.forEach((e=>{e.stop(!0)})),this.activeSubSystems=new Array)}_removeFromRoot(){if(!this._rootParticleSystem)return;const e=this._rootParticleSystem.activeSubSystems.indexOf(this);-1!==e&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}_update(e){if(this._alive=this._particles.length>0,this.emitter.position){const e=this.emitter;this._emitterWorldMatrix=e.getWorldMatrix()}else{const e=this.emitter;this._emitterWorldMatrix=o.y3.Translation(e.x,e.y,e.z)}let t;this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);for(let i=0;i0){const e=S.R.Clamp(this._actualFrame/this.targetStopDuration);oS.GetCurrentGradient(e,this._lifeTimeGradients,((i,n)=>{const s=i,r=n,o=s.getFactor(),a=r.getFactor(),l=(e-s.gradient)/(r.gradient-s.gradient);t.lifeTime=S.R.Lerp(o,a,l)}))}else t.lifeTime=S.R.RandomRange(this.minLifeTime,this.maxLifeTime);const e=S.R.RandomRange(this.minEmitPower,this.maxEmitPower);if(this.startPositionFunction?this.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal):this.particleEmitterType.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal),this.isLocal&&(t._localPosition?t._localPosition.copyFrom(t.position):t._localPosition=t.position.clone(),o.P.TransformCoordinatesToRef(t._localPosition,this._emitterWorldMatrix,t.position)),this.startDirectionFunction?this.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal):this.particleEmitterType.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal,this._emitterInverseWorldMatrix),0===e?t._initialDirection?t._initialDirection.copyFrom(t.direction):t._initialDirection=t.direction.clone():t._initialDirection=null,t.direction.scaleInPlace(e),this._sizeGradients&&0!==this._sizeGradients.length?(t._currentSizeGradient=this._sizeGradients[0],t._currentSize1=t._currentSizeGradient.getFactor(),t.size=t._currentSize1,this._sizeGradients.length>1?t._currentSize2=this._sizeGradients[1].getFactor():t._currentSize2=t._currentSize1):t.size=S.R.RandomRange(this.minSize,this.maxSize),t.scale.copyFromFloats(S.R.RandomRange(this.minScaleX,this.maxScaleX),S.R.RandomRange(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){const e=this._actualFrame/this.targetStopDuration;oS.GetCurrentGradient(e,this._startSizeGradients,((e,i,n)=>{e!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=i.getFactor(),this._currentStartSizeGradient=e);const s=S.R.Lerp(this._currentStartSize1,this._currentStartSize2,n);t.scale.scaleInPlace(s)}))}if(this._angularSpeedGradients&&0!==this._angularSpeedGradients.length?(t._currentAngularSpeedGradient=this._angularSpeedGradients[0],t.angularSpeed=t._currentAngularSpeedGradient.getFactor(),t._currentAngularSpeed1=t.angularSpeed,this._angularSpeedGradients.length>1?t._currentAngularSpeed2=this._angularSpeedGradients[1].getFactor():t._currentAngularSpeed2=t._currentAngularSpeed1):t.angularSpeed=S.R.RandomRange(this.minAngularSpeed,this.maxAngularSpeed),t.angle=S.R.RandomRange(this.minInitialRotation,this.maxInitialRotation),this._velocityGradients&&this._velocityGradients.length>0&&(t._currentVelocityGradient=this._velocityGradients[0],t._currentVelocity1=t._currentVelocityGradient.getFactor(),this._velocityGradients.length>1?t._currentVelocity2=this._velocityGradients[1].getFactor():t._currentVelocity2=t._currentVelocity1),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&(t._currentLimitVelocityGradient=this._limitVelocityGradients[0],t._currentLimitVelocity1=t._currentLimitVelocityGradient.getFactor(),this._limitVelocityGradients.length>1?t._currentLimitVelocity2=this._limitVelocityGradients[1].getFactor():t._currentLimitVelocity2=t._currentLimitVelocity1),this._dragGradients&&this._dragGradients.length>0&&(t._currentDragGradient=this._dragGradients[0],t._currentDrag1=t._currentDragGradient.getFactor(),this._dragGradients.length>1?t._currentDrag2=this._dragGradients[1].getFactor():t._currentDrag2=t._currentDrag1),this._colorGradients&&0!==this._colorGradients.length)t._currentColorGradient=this._colorGradients[0],t._currentColorGradient.getColorToRef(t.color),t._currentColor1.copyFrom(t.color),this._colorGradients.length>1?this._colorGradients[1].getColorToRef(t._currentColor2):t._currentColor2.copyFrom(t.color);else{const e=S.R.RandomRange(0,1);a.HE.LerpToRef(this.color1,this.color2,e,t.color),this.colorDead.subtractToRef(t.color,this._colorDiff),this._colorDiff.scaleToRef(1/t.lifeTime,t.colorStep)}this._isAnimationSheetEnabled&&(t._initialStartSpriteCellID=this.startSpriteCellID,t._initialEndSpriteCellID=this.endSpriteCellID,t._initialSpriteCellLoop=this.spriteCellLoop),t.direction.addInPlace(this._inheritedVelocityOffset),this._useRampGradients&&(t.remapData=new o.Lt(0,1,0,1)),this.noiseTexture&&(t._randomNoiseCoordinates1?(t._randomNoiseCoordinates1.copyFromFloats(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2.copyFromFloats(Math.random(),Math.random(),Math.random())):(t._randomNoiseCoordinates1=new o.P(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new o.P(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){const n=[ne.o.PositionKind,ne.o.ColorKind,"angle","offset","size"];return e&&n.push("cellIndex"),t||n.push("direction"),i&&n.push("remapData"),n}static _GetEffectCreationOptions(e=!1,t=!1){const i=["invView","view","projection","textureMask","translationPivot","eyePosition"];return(0,ua.qx)(i),e&&i.push("particlesInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t){if(this._scene&&(0,ua.lK)(this,this._scene,e),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),t===fS.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this._useRampGradients&&e.push("#define RAMPGRADIENT"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case fS.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case fS.BILLBOARDMODE_STRETCHED:case fS.BILLBOARDMODE_STRETCHED_LOCAL:e.push("#define BILLBOARDSTRETCHED"),this.billboardMode===fS.BILLBOARDMODE_STRETCHED_LOCAL&&e.push("#define BILLBOARDSTRETCHED_LOCAL");break;case fS.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL")}this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...fS._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&this.billboardMode!==fS.BILLBOARDMODE_STRETCHED&&this.billboardMode!==fS.BILLBOARDMODE_STRETCHED_LOCAL,this._useRampGradients)),e.push(...fS._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(ii.$.PrepareUniforms(e,this._imageProcessingConfigurationDefines),ii.$.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(null==t?void 0:t.effect)return t;const i=[];this.fillDefines(i,e);const n=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:0;let s=this._drawWrappers[n];s||(s=this._drawWrappers[n]=[]);let r=s[e];r||(r=new $t.q(this._engine),r.drawContext&&(r.drawContext.useInstancing=this._useInstancing),s[e]=r);const o=i.join("\n");if(r.defines!==o){const e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),r.setEffect(this._engine.createEffect("particles",e,t,i,o),o)}return r}animate(e=!1){var t;if(!this._started)return;if(!e&&this._scene){if(!this.isReady())return;if(this._currentRenderId===this._scene.getFrameId())return;this._currentRenderId=this._scene.getFrameId()}let i;if(this._scaledUpdateSpeed=this.updateSpeed*(e?this.preWarmStepOffset:(null===(t=this._scene)||void 0===t?void 0:t.getAnimationRatio())||1),this.manualEmitCount>-1)i=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0;else{let e=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){const t=this._actualFrame/this.targetStopDuration;oS.GetCurrentGradient(t,this._emitRateGradients,((t,i,n)=>{t!==this._currentEmitRateGradient&&(this._currentEmitRate1=this._currentEmitRate2,this._currentEmitRate2=i.getFactor(),this._currentEmitRateGradient=t),e=S.R.Lerp(this._currentEmitRate1,this._currentEmitRate2,n)}))}i=e*this._scaledUpdateSpeed>>0,this._newPartsExcess+=e*this._scaledUpdateSpeed-i}if(this._newPartsExcess>1&&(i+=this._newPartsExcess>>0,this._newPartsExcess-=this._newPartsExcess>>0),this._alive=!1,this._stopped?i=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(i),this._stopped&&(this._alive||(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene&&this._scene._toBeDisposed.push(this))),!e){let e=0;for(let t=0;t=0&&(a.invertToRef(o.jp.Matrix[0]),s.setMatrix("invView",o.jp.Matrix[0])),void 0!==this._vertexArrayObject?(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,this._indexBuffer,s)),this._engine.bindVertexArrayObject(this._vertexArrayObject,this._indexBuffer)):r.bindBuffers(this._vertexBuffers,this._indexBuffer,s),this.useLogarithmicDepth&&this._scene&&It.G.BindLogDepth(l,s,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(s),e){case fS.BLENDMODE_ADD:r.setAlphaMode(1);break;case fS.BLENDMODE_ONEONE:r.setAlphaMode(6);break;case fS.BLENDMODE_STANDARD:r.setAlphaMode(2);break;case fS.BLENDMODE_MULTIPLY:r.setAlphaMode(4)}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(s),this._useInstancing?r.drawArraysType(7,0,4,this._particles.length):r.drawElementsType(0,0,6*this._particles.length),this._particles.length}render(){if(!this.isReady()||!this._particles.length)return 0;const e=this._engine;e.setState&&(e.setState(!1),this.forceDepthWrite&&e.setDepthWrite(!0));let t=0;return t=this.blendMode===fS.BLENDMODE_MULTIPLYADD?this._render(fS.BLENDMODE_MULTIPLY)+this._render(fS.BLENDMODE_ADD):this._render(this.blendMode),this._engine.unbindInstanceAttributes(),this._engine.setAlphaMode(0),t}dispose(e=!0){if(this.resetDrawCache(),this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._indexBuffer&&(this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._removeFromRoot(),this.subEmitters&&!this._subEmitters&&this._prepareSubEmitterInternalArray(),this._subEmitters&&this._subEmitters.length){for(let e=0;e-1&&this._scene.particleSystems.splice(e,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()}clone(e,t,i=!1){const n=Object.assign({},this._customWrappers);let s=null;const r=this._engine;if(r.createEffectForParticles&&null!=this.customShader){s=this.customShader;const e=s.shaderOptions.defines.length>0?s.shaderOptions.defines.join("\n"):"",t=r.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,e);n[0]?n[0].effect=t:this.setCustomEffect(t,0)}const o=this.serialize(i),a=fS.Parse(o,this._scene||this._engine,this._rootUrl);return a.name=e,a.customShader=s,a._customWrappers=n,void 0===t&&(t=this.emitter),this.noiseTexture&&(a.noiseTexture=this.noiseTexture.clone()),a.emitter=t,this.preventAutoStart||a.start(),a}serialize(e=!1){const t={};if(fS._Serialize(t,this,e),t.textureMask=this.textureMask.asArray(),t.customShader=this.customShader,t.preventAutoStart=this.preventAutoStart,this.subEmitters){t.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray();for(const i of this._subEmitters){const n=[];for(const t of i)n.push(t.serialize(e));t.subEmitters.push(n)}}return t}static _Serialize(e,t,i){if(e.name=t.name,e.id=t.id,e.capacity=t.getCapacity(),e.disposeOnStop=t.disposeOnStop,e.manualEmitCount=t.manualEmitCount,t.emitter.position){const i=t.emitter;e.emitterId=i.id}else{const i=t.emitter;e.emitter=i.asArray()}t.particleEmitterType&&(e.particleEmitterType=t.particleEmitterType.serialize()),t.particleTexture&&(i?e.texture=t.particleTexture.serialize():(e.textureName=t.particleTexture.name,e.invertY=!!t.particleTexture._invertY)),e.isLocal=t.isLocal,E.p4.AppendSerializedAnimations(t,e),e.beginAnimationOnStart=t.beginAnimationOnStart,e.beginAnimationFrom=t.beginAnimationFrom,e.beginAnimationTo=t.beginAnimationTo,e.beginAnimationLoop=t.beginAnimationLoop,e.startDelay=t.startDelay,e.renderingGroupId=t.renderingGroupId,e.isBillboardBased=t.isBillboardBased,e.billboardMode=t.billboardMode,e.minAngularSpeed=t.minAngularSpeed,e.maxAngularSpeed=t.maxAngularSpeed,e.minSize=t.minSize,e.maxSize=t.maxSize,e.minScaleX=t.minScaleX,e.maxScaleX=t.maxScaleX,e.minScaleY=t.minScaleY,e.maxScaleY=t.maxScaleY,e.minEmitPower=t.minEmitPower,e.maxEmitPower=t.maxEmitPower,e.minLifeTime=t.minLifeTime,e.maxLifeTime=t.maxLifeTime,e.emitRate=t.emitRate,e.gravity=t.gravity.asArray(),e.noiseStrength=t.noiseStrength.asArray(),e.color1=t.color1.asArray(),e.color2=t.color2.asArray(),e.colorDead=t.colorDead.asArray(),e.updateSpeed=t.updateSpeed,e.targetStopDuration=t.targetStopDuration,e.blendMode=t.blendMode,e.preWarmCycles=t.preWarmCycles,e.preWarmStepOffset=t.preWarmStepOffset,e.minInitialRotation=t.minInitialRotation,e.maxInitialRotation=t.maxInitialRotation,e.startSpriteCellID=t.startSpriteCellID,e.spriteCellLoop=t.spriteCellLoop,e.endSpriteCellID=t.endSpriteCellID,e.spriteCellChangeSpeed=t.spriteCellChangeSpeed,e.spriteCellWidth=t.spriteCellWidth,e.spriteCellHeight=t.spriteCellHeight,e.spriteRandomStartCell=t.spriteRandomStartCell,e.isAnimationSheetEnabled=t.isAnimationSheetEnabled,e.useLogarithmicDepth=t.useLogarithmicDepth;const n=t.getColorGradients();if(n){e.colorGradients=[];for(const t of n){const i={gradient:t.gradient,color1:t.color1.asArray()};t.color2?i.color2=t.color2.asArray():i.color2=t.color1.asArray(),e.colorGradients.push(i)}}const s=t.getRampGradients();if(s){e.rampGradients=[];for(const t of s){const i={gradient:t.gradient,color:t.color.asArray()};e.rampGradients.push(i)}e.useRampGradients=t.useRampGradients}const r=t.getColorRemapGradients();if(r){e.colorRemapGradients=[];for(const t of r){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.colorRemapGradients.push(i)}}const o=t.getAlphaRemapGradients();if(o){e.alphaRemapGradients=[];for(const t of o){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.alphaRemapGradients.push(i)}}const a=t.getSizeGradients();if(a){e.sizeGradients=[];for(const t of a){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.sizeGradients.push(i)}}const l=t.getAngularSpeedGradients();if(l){e.angularSpeedGradients=[];for(const t of l){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.angularSpeedGradients.push(i)}}const h=t.getVelocityGradients();if(h){e.velocityGradients=[];for(const t of h){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.velocityGradients.push(i)}}const c=t.getDragGradients();if(c){e.dragGradients=[];for(const t of c){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.dragGradients.push(i)}}const d=t.getEmitRateGradients();if(d){e.emitRateGradients=[];for(const t of d){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.emitRateGradients.push(i)}}const u=t.getStartSizeGradients();if(u){e.startSizeGradients=[];for(const t of u){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.startSizeGradients.push(i)}}const p=t.getLifeTimeGradients();if(p){e.lifeTimeGradients=[];for(const t of p){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.lifeTimeGradients.push(i)}}const f=t.getLimitVelocityGradients();if(f){e.limitVelocityGradients=[];for(const t of f){const i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.limitVelocityGradients.push(i)}e.limitVelocityDamping=t.limitVelocityDamping}t.noiseTexture&&(e.noiseTexture=t.noiseTexture.serialize())}static _Parse(e,t,i,n){var s,r,h;let c;c=i instanceof Ue.B?null:i;const d=(0,l.q)("BABYLON.Texture");if(d&&c&&(e.texture?t.particleTexture=d.Parse(e.texture,c,n):e.textureName&&(t.particleTexture=new d(n+e.textureName,c,!1,void 0===e.invertY||e.invertY),t.particleTexture.name=e.textureName)),e.emitterId||0===e.emitterId||void 0!==e.emitter?e.emitterId&&c?t.emitter=c.getLastMeshById(e.emitterId):t.emitter=o.P.FromArray(e.emitter):t.emitter=o.P.Zero(),t.isLocal=!!e.isLocal,void 0!==e.renderingGroupId&&(t.renderingGroupId=e.renderingGroupId),void 0!==e.isBillboardBased&&(t.isBillboardBased=e.isBillboardBased),void 0!==e.billboardMode&&(t.billboardMode=e.billboardMode),void 0!==e.useLogarithmicDepth&&(t.useLogarithmicDepth=e.useLogarithmicDepth),e.animations){for(let i=0;i0?c.shaderOptions.defines.join("\n"):"";h=o.createEffectForParticles(c.shaderPath.fragmentElement,c.shaderOptions.uniforms,c.shaderOptions.samplers,t)}const d=new fS(r,s||e.capacity,t,h,e.isAnimationSheetEnabled);if(d.customShader=c,d._rootUrl=i,e.id&&(d.id=e.id),e.subEmitters){d.subEmitters=[];for(const n of e.subEmitters){const e=[];for(const s of n)e.push(hS.Parse(s,t,i));d.subEmitters.push(e)}}return fS._Parse(e,d,t,i),e.textureMask&&(d.textureMask=a.HE.FromArray(e.textureMask)),e.preventAutoStart&&(d.preventAutoStart=e.preventAutoStart),n||d.preventAutoStart||d.start(),d}}fS.BILLBOARDMODE_Y=2,fS.BILLBOARDMODE_ALL=7,fS.BILLBOARDMODE_STRETCHED=8,fS.BILLBOARDMODE_STRETCHED_LOCAL=9,hS._ParseParticleSystem=fS.Parse;const _S="clipPlaneFragmentDeclaration2",mS="#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nin float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nin float fClipDistance6;\n#endif\n";Ht.v.IncludesShadersStore[_S]=mS;const gS="gpuRenderParticlesPixelShader",vS="precision highp float;\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform sampler2D diffuseSampler;\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include \n#include\n#include\n#include\n#include\nvoid main() {\n#include \nvec4 textureColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\ngl_FragColor.rgb=gl_FragColor.rgb*alpha+vec3(1.0)*(1.0-alpha);\n#endif \n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ngl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\ngl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);\ngl_FragColor=applyImageProcessing(gl_FragColor);\n#endif\n#endif\n}\n";Ht.v.ShadersStore[gS]=vS;const TS="clipPlaneVertexDeclaration2",SS="#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nout float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nout float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nout float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nout float fClipDistance4;\n#endif\n#ifdef CLIPPLANE5\nuniform vec4 vClipPlane5;\nout float fClipDistance5;\n#endif\n#ifdef CLIPPLANE6\nuniform vec4 vClipPlane6;\nout float fClipDistance6;\n#endif\n";Ht.v.IncludesShadersStore[TS]=SS;const ES="gpuRenderParticlesVertexShader",xS="precision highp float;\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\nuniform vec3 worldOffset;\n#ifdef LOCAL\nuniform mat4 emitterWM;\n#endif\nattribute vec3 position;\nattribute float age;\nattribute float life;\nattribute vec3 size;\n#ifndef BILLBOARD\nattribute vec3 initialDirection;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction;\n#endif\nattribute float angle;\n#ifdef ANIMATESHEET\nattribute float cellIndex;\n#endif\nattribute vec2 offset;\nattribute vec2 uv;\nvarying vec2 vUV;\nvarying vec4 vColor;\nvarying vec3 vPositionW;\n#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED)\nuniform mat4 invView;\n#endif\n#include\n#include\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nattribute vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition;\n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix= mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\n#ifdef LOCAL\nreturn ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;\n#else\nreturn (position+worldOffset)+alignedCorner;\n#endif\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix= mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\n#ifdef LOCAL\nreturn ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner;\n#else\nreturn (position+worldOffset)+alignedCorner;\n#endif\n}\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture2D(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=(position+worldOffset)-eyePosition;\nyaxis.y=0.;\nvPositionW=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(vPositionW,1.0));\n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=(position+worldOffset)-eyePosition;\nvPositionW=rotateAlign(toCamera,rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(vPositionW,1.0));\n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n#ifdef LOCAL\nvec4 viewPosition=view*vec4(((emitterWM*vec4(position,1.0)).xyz+worldOffset),1.0)+rotatedCorner;\n#else\nvec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner;\n#endif\nvPositionW=(invView*viewPosition).xyz;\n#endif\n#else\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvPositionW=rotate(yaxis,rotatedCorner);\nvec4 viewPosition=view*vec4(vPositionW,1.0);\n#endif\ngl_Position=projection*viewPosition;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nvec4 worldPos=vec4(vPositionW,1.0);\n#endif\n#include\n#include\n}";Ht.v.ShadersStore[ES]=xS;class bS extends pi{static get IsSupported(){if(!m.l.LastCreatedEngine)return!1;const e=m.l.LastCreatedEngine.getCaps();return e.supportTransformFeedbacks||e.supportComputeShaders}getCapacity(){return this._capacity}get activeParticleCount(){return this._activeCount}set activeParticleCount(e){this._activeCount=Math.min(e,this._capacity)}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady())return!1;if(this.blendMode!==fS.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else{if(!this._getWrapper(fS.BLENDMODE_MULTIPLY).effect.isReady())return!1;if(!this._getWrapper(fS.BLENDMODE_ADD).effect.isReady())return!1}return this._platform.isUpdateBufferCreated()?this._platform.isUpdateBufferReady():(this._recreateUpdateEffect(),!1)}isStarted(){return this._started}isStopped(){return this._stopped}isStopping(){return!1}getActiveCount(){return this._currentActiveCount}start(e=this.startDelay){if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";e?setTimeout((()=>{this.start(0)}),e):(this._started=!0,this._stopped=!1,this._preWarmDone=!1,this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop))}stop(){this._stopped||(this._stopped=!0)}reset(){this._releaseBuffers(),this._platform.releaseVertexBuffers(),this._currentActiveCount=0,this._targetIndex=0}getClassName(){return"GPUParticleSystem"}getCustomEffect(e=0){var t,i;return null!==(i=null===(t=this._customWrappers[e])||void 0===t?void 0:t.effect)&&void 0!==i?i:this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){var t;return null!==(t=this._customWrappers[e])&&void 0!==t?t:this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new $t.q(this._engine),this._customWrappers[t].effect=e}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new r.y$),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"gpuRenderParticles"}get vertexBuffers(){return this._renderVertexBuffers[1^this._targetIndex]}get indexBuffer(){return null}_removeGradientAndTexture(e,t,i){return super._removeGradientAndTexture(e,t,i),this._releaseBuffers(),this}addColorGradient(e,t){this._colorGradients||(this._colorGradients=[]);const i=new nS(e,t);return this._colorGradients.push(i),this._refreshColorGradient(!0),this._releaseBuffers(),this}_refreshColorGradient(e=!1){this._colorGradients&&(e&&this._colorGradients.sort(((e,t)=>e.gradientt.gradient?1:0)),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null))}forceRefreshGradients(){this._refreshColorGradient(),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture"),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture"),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture"),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture"),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture"),this.reset()}removeColorGradient(e){return this._removeGradientAndTexture(e,this._colorGradients,this._colorGradientsTexture),this._colorGradientsTexture=null,this}resetDrawCache(){var e;for(const t in this._drawWrappers){null===(e=this._drawWrappers[t].drawContext)||void 0===e||e.reset()}}_addFactorGradient(e,t,i){const n=new rS(t,i);e.push(n),this._releaseBuffers()}addSizeGradient(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture",!0),this._releaseBuffers(),this}removeSizeGradient(e){return this._removeGradientAndTexture(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this}_refreshFactorGradient(e,t,i=!1){if(!e)return;i&&e.sort(((e,t)=>e.gradientt.gradient?1:0));const n=this;n[t]&&(n[t].dispose(),n[t]=null)}addAngularSpeedGradient(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture",!0),this._releaseBuffers(),this}removeAngularSpeedGradient(e){return this._removeGradientAndTexture(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this}addVelocityGradient(e,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture",!0),this._releaseBuffers(),this}removeVelocityGradient(e){return this._removeGradientAndTexture(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this}addLimitVelocityGradient(e,t){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture",!0),this._releaseBuffers(),this}removeLimitVelocityGradient(e){return this._removeGradientAndTexture(e,this._limitVelocityGradients,this._limitVelocityGradientsTexture),this._limitVelocityGradientsTexture=null,this}addDragGradient(e,t){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture",!0),this._releaseBuffers(),this}removeDragGradient(e){return this._removeGradientAndTexture(e,this._dragGradients,this._dragGradientsTexture),this._dragGradientsTexture=null,this}addEmitRateGradient(){return this}removeEmitRateGradient(){return this}addStartSizeGradient(){return this}removeStartSizeGradient(){return this}addColorRemapGradient(){return this}removeColorRemapGradient(){return this}addAlphaRemapGradient(){return this}removeAlphaRemapGradient(){return this}addRampGradient(){return this}removeRampGradient(){return this}getRampGradients(){return null}get useRampGradients(){return!1}set useRampGradients(e){}addLifeTimeGradient(){return this}removeLifeTimeGradient(){return this}constructor(e,t,i,n=null,s=!1){if(super(e),this.layerMask=268435455,this._accumulatedCount=0,this._renderVertexBuffers=[],this._targetIndex=0,this._currentRenderId=-1,this._currentRenderingCameraUniqueId=-1,this._started=!1,this._stopped=!1,this._timeDelta=0,this.updateInAnimate=!1,this._actualFrame=0,this._rawTextureWidth=256,this.onDisposeObservable=new r.y$,this.onStoppedObservable=new r.y$,this.forceDepthWrite=!1,this._preWarmDone=!1,this.isLocal=!1,this.isGPU=!0,this._onBeforeDrawParticlesObservable=null,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=o.y3.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||m.l.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().supportComputeShaders){if(!(0,l.q)("BABYLON.ComputeShaderParticleSystem"))throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");this._platform=new((0,l.q)("BABYLON.ComputeShaderParticleSystem"))(this,this._engine)}else{if(!(0,l.q)("BABYLON.WebGL2ParticleSystem"))throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");this._platform=new((0,l.q)("BABYLON.WebGL2ParticleSystem"))(this,this._engine)}this._customWrappers={0:new $t.q(this._engine)},this._customWrappers[0].effect=n,this._drawWrappers={0:new $t.q(this._engine)},this._drawWrappers[0].drawContext&&(this._drawWrappers[0].drawContext.useInstancing=!0),this._attachImageProcessingConfiguration(null),(t=null!=t?t:{}).randomTextureSize||delete t.randomTextureSize;const a=Object.assign({capacity:5e4,randomTextureSize:this._engine.getCaps().maxTextureSize},t),h=t;isFinite(h)&&(a.capacity=h),this._capacity=a.capacity,this._activeCount=a.capacity,this._currentActiveCount=0,this._isAnimationSheetEnabled=s,this.particleEmitterType=new ni;const c=Math.min(this._engine.getCaps().maxTextureSize,a.randomTextureSize);let d=[];for(let r=0;r0;)i.push(0)}const a=new Float32Array([.5,.5,1,1,-.5,.5,0,1,.5,-.5,1,0,-.5,-.5,0,0]),l=this._platform.createParticleBuffer(i),h=this._platform.createParticleBuffer(i);this._buffer0=new ne.l(t,l,!1,this._attributesStrideSize),this._buffer1=new ne.l(t,h,!1,this._attributesStrideSize),this._spriteBuffer=new ne.l(t,a,!1,4),this._renderVertexBuffers=[],this._createVertexBuffers(this._buffer0,this._buffer1,this._spriteBuffer),this._createVertexBuffers(this._buffer1,this._buffer0,this._spriteBuffer),this._sourceBuffer=this._buffer0,this._targetBuffer=this._buffer1}_recreateUpdateEffect(){this._createColorGradientTexture(),this._createSizeGradientTexture(),this._createAngularSpeedGradientTexture(),this._createVelocityGradientTexture(),this._createLimitVelocityGradientTexture(),this._createDragGradientTexture();let e=this.particleEmitterType?this.particleEmitterType.getEffectDefines():"";return this._isBillboardBased&&(e+="\n#define BILLBOARD"),this._colorGradientsTexture&&(e+="\n#define COLORGRADIENTS"),this._sizeGradientsTexture&&(e+="\n#define SIZEGRADIENTS"),this._angularSpeedGradientsTexture&&(e+="\n#define ANGULARSPEEDGRADIENTS"),this._velocityGradientsTexture&&(e+="\n#define VELOCITYGRADIENTS"),this._limitVelocityGradientsTexture&&(e+="\n#define LIMITVELOCITYGRADIENTS"),this._dragGradientsTexture&&(e+="\n#define DRAGGRADIENTS"),this.isAnimationSheetEnabled&&(e+="\n#define ANIMATESHEET",this.spriteRandomStartCell&&(e+="\n#define ANIMATESHEETRANDOMSTART")),this.noiseTexture&&(e+="\n#define NOISE"),this.isLocal&&(e+="\n#define LOCAL"),!(!this._platform.isUpdateBufferCreated()||this._cachedUpdateDefines!==e)||(this._cachedUpdateDefines=e,this._updateBuffer=this._platform.createUpdateBuffer(e),this._platform.isUpdateBufferReady())}_getWrapper(e){const t=this._getCustomDrawWrapper(e);if(null==t?void 0:t.effect)return t;const i=[];this.fillDefines(i,e);let n=this._drawWrappers[e];n||(n=new $t.q(this._engine),n.drawContext&&(n.drawContext.useInstancing=!0),this._drawWrappers[e]=n);const s=i.join("\n");if(n.defines!==s){const e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),n.setEffect(this._engine.createEffect("gpuRenderParticles",e,t,i,s),s)}return n}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1,n=!1){const s=[ne.o.PositionKind,"age","life","size","angle"];return e||s.push(ne.o.ColorKind),t&&s.push("cellIndex"),i||s.push("initialDirection"),n||s.push("direction"),s.push("offset",ne.o.UVKind),s}static _GetEffectCreationOptions(e=!1,t=!1){const i=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return(0,ua.qx)(i),e&&i.push("sheetInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t=0){if(this._scene&&(0,ua.lK)(this,this._scene,e),t===fS.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this.isLocal&&e.push("#define LOCAL"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case fS.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case fS.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case fS.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL")}this._colorGradientsTexture&&e.push("#define COLORGRADIENTS"),this.isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(""+this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...bS._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===fS.BILLBOARDMODE_STRETCHED)),e.push(...bS._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(ii.$.PrepareUniforms(e,this._imageProcessingConfigurationDefines),ii.$.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}animate(e=!1){var t;this._timeDelta=this.updateSpeed*(e?this.preWarmStepOffset:(null===(t=this._scene)||void 0===t?void 0:t.getAnimationRatio())||1),this._actualFrame+=this._timeDelta,this._stopped||this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop(),this.updateInAnimate&&this._update()}_createFactorGradientTexture(e,t){const i=this[t];if(!e||!e.length||i)return;const n=new Float32Array(this._rawTextureWidth);for(let s=0;s{n[s]=S.R.Lerp(e.factor1,t.factor1,i)}))}this[t]=ze.CreateRTexture(n,this._rawTextureWidth,1,this._scene||this._engine,!1,!1,1),this[t].name=t.substring(1)}_createSizeGradientTexture(){this._createFactorGradientTexture(this._sizeGradients,"_sizeGradientsTexture")}_createAngularSpeedGradientTexture(){this._createFactorGradientTexture(this._angularSpeedGradients,"_angularSpeedGradientsTexture")}_createVelocityGradientTexture(){this._createFactorGradientTexture(this._velocityGradients,"_velocityGradientsTexture")}_createLimitVelocityGradientTexture(){this._createFactorGradientTexture(this._limitVelocityGradients,"_limitVelocityGradientsTexture")}_createDragGradientTexture(){this._createFactorGradientTexture(this._dragGradients,"_dragGradientsTexture")}_createColorGradientTexture(){if(!this._colorGradients||!this._colorGradients.length||this._colorGradientsTexture)return;const e=new Uint8Array(4*this._rawTextureWidth),t=a.zZ.Color4[0];for(let i=0;i{a.HE.LerpToRef(n.color1,s.color1,r,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255*t.a}))}this._colorGradientsTexture=ze.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1),this._colorGradientsTexture.name="colorGradients"}_render(e,t){var i,n;const s=this._getWrapper(e),r=s.effect;this._engine.enableEffect(s);const a=(null===(i=this._scene)||void 0===i?void 0:i.getViewMatrix())||o.y3.IdentityReadOnly;if(r.setMatrix("view",a),r.setMatrix("projection",null!==(n=this.defaultProjectionMatrix)&&void 0!==n?n:this._scene.getProjectionMatrix()),r.setTexture("diffuseSampler",this.particleTexture),r.setVector2("translationPivot",this.translationPivot),r.setVector3("worldOffset",this.worldOffset),this.isLocal&&r.setMatrix("emitterWM",t),this._colorGradientsTexture?r.setTexture("colorGradientSampler",this._colorGradientsTexture):r.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){const e=this.particleTexture.getBaseSize();r.setFloat3("sheetInfos",this.spriteCellWidth/e.width,this.spriteCellHeight/e.height,e.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){const e=this._scene.activeCamera;r.setVector3("eyePosition",e.globalPosition)}const l=r.defines;if(this._scene&&(0,ua.an)(r,this,this._scene),l.indexOf("#define BILLBOARDMODE_ALL")>=0){const e=a.clone();e.invert(),r.setMatrix("invView",e)}switch(this.useLogarithmicDepth&&this._scene&&It.G.BindLogDepth(l,r,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(r),e){case fS.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case fS.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case fS.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case fS.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4)}return this._platform.bindDrawBuffers(this._targetIndex,r),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(r),this._engine.drawArraysType(7,0,4,this._currentActiveCount),this._engine.setAlphaMode(0),this._currentActiveCount}_update(e){if(!this.emitter||!this._targetBuffer)return;if(!this._recreateUpdateEffect())return;if(!e)if(this.emitter.position){e=this.emitter.getWorldMatrix()}else{const t=this.emitter;e=o.jp.Matrix[0],o.y3.TranslationToRef(t.x,t.y,t.z,e)}this._platform.preUpdateParticleBuffer(),this._updateBuffer.setFloat("currentCount",this._currentActiveCount),this._updateBuffer.setFloat("timeDelta",this._timeDelta),this._updateBuffer.setFloat("stopFactor",this._stopped?0:1),this._updateBuffer.setInt("randomTextureSize",this._randomTextureSize),this._updateBuffer.setFloat2("lifeTime",this.minLifeTime,this.maxLifeTime),this._updateBuffer.setFloat2("emitPower",this.minEmitPower,this.maxEmitPower),this._colorGradientsTexture||(this._updateBuffer.setDirectColor4("color1",this.color1),this._updateBuffer.setDirectColor4("color2",this.color2)),this._updateBuffer.setFloat2("sizeRange",this.minSize,this.maxSize),this._updateBuffer.setFloat4("scaleRange",this.minScaleX,this.maxScaleX,this.minScaleY,this.maxScaleY),this._updateBuffer.setFloat4("angleRange",this.minAngularSpeed,this.maxAngularSpeed,this.minInitialRotation,this.maxInitialRotation),this._updateBuffer.setVector3("gravity",this.gravity),this._limitVelocityGradientsTexture&&this._updateBuffer.setFloat("limitVelocityDamping",this.limitVelocityDamping),this.particleEmitterType&&this.particleEmitterType.applyToShader(this._updateBuffer),this._isAnimationSheetEnabled&&this._updateBuffer.setFloat4("cellInfos",this.startSpriteCellID,this.endSpriteCellID,this.spriteCellChangeSpeed,this.spriteCellLoop?1:0),this.noiseTexture&&this._updateBuffer.setVector3("noiseStrength",this.noiseStrength),this.isLocal||this._updateBuffer.setMatrix("emitterWM",e),this._platform.updateParticleBuffer(this._targetIndex,this._targetBuffer,this._currentActiveCount),this._targetIndex++,2===this._targetIndex&&(this._targetIndex=0);const t=this._sourceBuffer;this._sourceBuffer=this._targetBuffer,this._targetBuffer=t}render(e=!1,t=!1){if(!this._started)return 0;if(!this.isReady())return 0;if(!e&&this._scene){if(!this._preWarmDone&&this.preWarmCycles){for(let e=0;e1){const e=0|this._accumulatedCount;this._accumulatedCount-=e,this._currentActiveCount=Math.min(this._activeCount,this._currentActiveCount+e)}if(!this._currentActiveCount)return 0;let i;if(this.emitter.position){i=this.emitter.getWorldMatrix()}else{const e=this.emitter;i=o.jp.Matrix[0],o.y3.TranslationToRef(e.x,e.y,e.z,i)}const n=this._engine;this.updateInAnimate||this._update(i);let s=0;return e||t||(n.setState(!1),this.forceDepthWrite&&n.setDepthWrite(!0),s=this.blendMode===fS.BLENDMODE_MULTIPLYADD?this._render(fS.BLENDMODE_MULTIPLY,i)+this._render(fS.BLENDMODE_ADD,i):this._render(this.blendMode,i),this._engine.setAlphaMode(0)),s}rebuild(){this._initialize(!0)}_releaseBuffers(){this._buffer0&&(this._buffer0.dispose(),this._buffer0=null),this._buffer1&&(this._buffer1.dispose(),this._buffer1=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._platform.releaseBuffers()}dispose(e=!0){for(const t in this._drawWrappers){this._drawWrappers[t].dispose()}if(this._drawWrappers={},this._scene){const e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1)}this._releaseBuffers(),this._platform.releaseVertexBuffers();for(let t=0;t0?s.shaderOptions.defines.join("\n"):"";n[0]=r.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,e,void 0,void 0,void 0,this)}const o=this.serialize(i),a=bS.Parse(o,this._scene||this._engine,this._rootUrl);return a.name=e,a.customShader=s,a._customWrappers=n,void 0===t&&(t=this.emitter),this.noiseTexture&&(a.noiseTexture=this.noiseTexture.clone()),a.emitter=t,a}serialize(e=!1){const t={};return fS._Serialize(t,this,e),t.activeParticleCount=this.activeParticleCount,t.randomTextureSize=this._randomTextureSize,t.customShader=this.customShader,t}static Parse(e,t,i,n=!1,s){const r=e.name;let o,a;t instanceof Ue.B?o=t:(a=t,o=a.getEngine());const l=new bS(r,{capacity:s||e.capacity,randomTextureSize:e.randomTextureSize},t,null,e.isAnimationSheetEnabled);if(l._rootUrl=i,e.customShader&&o.createEffectForParticles){const t=e.customShader,i=t.shaderOptions.defines.length>0?t.shaderOptions.defines.join("\n"):"",n=o.createEffectForParticles(t.shaderPath.fragmentElement,t.shaderOptions.uniforms,t.shaderOptions.samplers,i,void 0,void 0,void 0,l);l.setCustomEffect(n,0),l.customShader=t}return e.id&&(l.id=e.id),e.activeParticleCount&&(l.activeParticleCount=e.activeParticleCount),fS._Parse(e,l,t,i),e.preventAutoStart&&(l.preventAutoStart=e.preventAutoStart),n||l.preventAutoStart||l.start(),l}}class CS{constructor(){this._emitterNodeIsOwned=!0,this.systems=new Array}get emitterNode(){return this._emitterNode}set emitterNode(e){this._emitterNodeIsOwned&&this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!1);for(const t of this.systems)t.emitter=e;this._emitterNode=e}setEmitterAsSphere(e,t,i){this._emitterNodeIsOwned&&this._emitterNode&&this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!0,this._emitterCreationOptions={kind:"Sphere",options:e,renderingGroupId:t};const n=gl("emitterSphere",{diameter:e.diameter,segments:e.segments},i);n.renderingGroupId=t;const s=new _a("emitterSphereMaterial",i);s.emissiveColor=e.color,n.material=s;for(const r of this.systems)r.emitter=n;this._emitterNode=n}start(e){for(const t of this.systems)e&&(t.emitter=e),t.start()}dispose(){for(const e of this.systems)e.dispose();this.systems.length=0,this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNode=null)}serialize(e=!1){const t={systems:[]};for(const i of this.systems)t.systems.push(i.serialize(e));return this._emitterNode&&(t.emitter=this._emitterCreationOptions),t}static Parse(e,t,i=!1,n){const s=new CS,r=this.BaseAssetsUrl+"/textures/";t=t||m.l.LastCreatedScene;for(const o of e.systems)s.systems.push(i?bS.Parse(o,t,r,!0,n):fS.Parse(o,t,r,!0,n));if(e.emitter){const i=e.emitter.options;if("Sphere"===e.emitter.kind)s.setEmitterAsSphere({diameter:i.diameter,segments:i.segments,color:a.Wo.FromArray(i.color)},e.emitter.renderingGroupId,t)}return s}}CS.BaseAssetsUrl="https://assets.babylonjs.com/particles";class yS{static CreateDefault(e,t=500,i,n=!1){let s;return s=n?new bS("default system",{capacity:t},i):new fS("default system",t,i),s.emitter=e,s.particleTexture=new Le("https://assets.babylonjs.com/textures/flare.png",s.getScene()),s.createConeEmitter(.1,Math.PI/4),s.color1=new a.HE(1,1,1,1),s.color2=new a.HE(1,1,1,1),s.colorDead=new a.HE(1,1,1,0),s.minSize=.1,s.maxSize=.1,s.minEmitPower=2,s.maxEmitPower=2,s.updateSpeed=1/60,s.emitRate=30,s}static CreateAsync(e,t,i=!1,n){t||(t=m.l.LastCreatedScene);const s={};return t.addPendingData(s),new Promise(((r,o)=>{if(i&&!bS.IsSupported)return t.removePendingData(s),o("Particle system with GPU is not supported.");se.w1.LoadFile(`${yS.BaseAssetsUrl}/systems/${e}.json`,(e=>{t.removePendingData(s);const o=JSON.parse(e.toString());return r(CS.Parse(o,t,i,n))}),void 0,void 0,void 0,(()=>(t.removePendingData(s),o(`An error occurred with the creation of your particle system. Check if your type '${e}' exists.`))))}))}static ExportSet(e){const t=new CS;for(const i of e)t.systems.push(i);return t}static ParseFromFileAsync(e,t,i,n=!1,s="",r){return new Promise(((o,a)=>{const l=new y.g;l.addEventListener("readystatechange",(()=>{if(4==l.readyState)if(200==l.status){const t=JSON.parse(l.responseText);let a;a=n?bS.Parse(t,i,s,!1,r):fS.Parse(t,i,s,!1,r),e&&(a.name=e),o(a)}else a("Unable to load the particle system")})),l.open("GET",t),l.send()}))}static ParseFromSnippetAsync(e,t,i=!1,n="",s){if("_BLANK"===e){const e=this.CreateDefault(null);return e.start(),Promise.resolve(e)}return new Promise(((r,o)=>{const a=new y.g;a.addEventListener("readystatechange",(()=>{if(4==a.readyState)if(200==a.status){const o=JSON.parse(JSON.parse(a.responseText).jsonPayload),l=JSON.parse(o.particleSystem);let h;h=i?bS.Parse(l,t,n,!1,s):fS.Parse(l,t,n,!1,s),h.snippetId=e,r(h)}else o("Unable to load the snippet "+e)})),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()}))}}yS.BaseAssetsUrl=CS.BaseAssetsUrl,yS.SnippetUrl="https://snippet.babylonjs.com",yS.CreateFromSnippetAsync=yS.ParseFromSnippetAsync,n.p.AddParser(Se.l.NAME_PARTICLESYSTEM,((e,t,i,s)=>{const r=n.p.GetIndividualParser(Se.l.NAME_PARTICLESYSTEM);if(r&&void 0!==e.particleSystems&&null!==e.particleSystems)for(let n=0,o=e.particleSystems.length;n{if(e.activeParticleCount){return bS.Parse(e,t,i)}return fS.Parse(e,t,i)})),fe.D.prototype.createEffectForParticles=function(e,t=[],i=[],n="",s,r,o,a){var l;let h=[],c=[];const d=[];return a?a.fillUniformsAttributesAndSamplerNames(c,h,d):(h=fS._GetAttributeNamesOrOptions(),c=fS._GetEffectCreationOptions()),-1===n.indexOf(" BILLBOARD")&&(n+="\n#define BILLBOARD\n"),(null==a?void 0:a.isAnimationSheetEnabled)&&-1===n.indexOf(" ANIMATESHEET")&&(n+="\n#define ANIMATESHEET\n"),-1===i.indexOf("diffuseSampler")&&i.push("diffuseSampler"),this.createEffect({vertex:null!==(l=null==a?void 0:a.vertexShaderName)&&void 0!==l?l:"particles",fragmentElement:e},h,c.concat(t),d.concat(i),n,s,r,o)},ee.Kj.prototype.getEmittedParticleSystems=function(){const e=new Array;for(let t=0;t{this.physicsImpostor&&(this.physicsImpostor.dispose(),this.physicsImpostor=null)}))))},enumerable:!0,configurable:!0}),ie.x.prototype.getPhysicsImpostor=function(){return this.physicsImpostor},ie.x.prototype.applyImpulse=function(e,t){return this.physicsImpostor?(this.physicsImpostor.applyImpulse(e,t),this):this},ie.x.prototype.setPhysicsLinkWith=function(e,t,i,n){return this.physicsImpostor&&e.physicsImpostor?(this.physicsImpostor.createJoint(e.physicsImpostor,st.HingeJoint,{mainPivot:t,connectedPivot:i,nativeParams:n}),this):this};class LS{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw(0,ge.S)("")}constructor(e,t=LS.DefaultPluginFactory()){this._physicsPlugin=t,this._physicsBodies=[],this._subTimeStep=0,e=e||new o.P(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}_step(e){e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._physicsBodies)}addBody(e){this._physicsBodies.push(e)}removeBody(e){const t=this._physicsBodies.indexOf(e);t>-1&&this._physicsBodies.splice(t,1)}getBodies(){return this._physicsBodies}getPhysicsPlugin(){return this._physicsPlugin}raycastToRef(e,t,i,n){this._physicsPlugin.raycast(e,t,i,n)}raycast(e,t,i){const n=new ev;return this._physicsPlugin.raycast(e,t,n,i),n}}!function(e){e[e.FREE=0]="FREE",e[e.LIMITED=1]="LIMITED",e[e.LOCKED=2]="LOCKED"}(RS||(RS={})),function(e){e[e.LINEAR_X=0]="LINEAR_X",e[e.LINEAR_Y=1]="LINEAR_Y",e[e.LINEAR_Z=2]="LINEAR_Z",e[e.ANGULAR_X=3]="ANGULAR_X",e[e.ANGULAR_Y=4]="ANGULAR_Y",e[e.ANGULAR_Z=5]="ANGULAR_Z",e[e.LINEAR_DISTANCE=6]="LINEAR_DISTANCE"}(PS||(PS={})),function(e){e[e.BALL_AND_SOCKET=1]="BALL_AND_SOCKET",e[e.DISTANCE=2]="DISTANCE",e[e.HINGE=3]="HINGE",e[e.SLIDER=4]="SLIDER",e[e.LOCK=5]="LOCK",e[e.PRISMATIC=6]="PRISMATIC",e[e.SIX_DOF=7]="SIX_DOF"}(IS||(IS={})),function(e){e[e.SPHERE=0]="SPHERE",e[e.CAPSULE=1]="CAPSULE",e[e.CYLINDER=2]="CYLINDER",e[e.BOX=3]="BOX",e[e.CONVEX_HULL=4]="CONVEX_HULL",e[e.CONTAINER=5]="CONTAINER",e[e.MESH=6]="MESH",e[e.HEIGHTFIELD=7]="HEIGHTFIELD"}(MS||(MS={})),function(e){e[e.NONE=0]="NONE",e[e.VELOCITY=1]="VELOCITY",e[e.POSITION=2]="POSITION"}(OS||(OS={})),function(e){e[e.STATIC=0]="STATIC",e[e.ANIMATED=1]="ANIMATED",e[e.DYNAMIC=2]="DYNAMIC"}(DS||(DS={}));!function(e){e[e.GEOMETRIC_MEAN=0]="GEOMETRIC_MEAN",e[e.MINIMUM=1]="MINIMUM",e[e.MAXIMUM=2]="MAXIMUM",e[e.ARITHMETIC_MEAN=3]="ARITHMETIC_MEAN",e[e.MULTIPLY=4]="MULTIPLY"}(NS||(NS={}));N.x.prototype.getPhysicsEngine=function(){return this._physicsEngine},N.x.prototype.enablePhysics=function(e=null,t){if(this._physicsEngine)return!0;let i=this._getComponent(Se.l.NAME_PHYSICSENGINE);i||(i=new BS(this),this._addComponent(i));try{if(t&&1!==(null==t?void 0:t.getPluginVersion())){if(2!==(null==t?void 0:t.getPluginVersion()))throw new Error("Unsupported Physics plugin version.");this._physicsEngine=new LS(e,t)}else this._physicsEngine=new tv(e,t);return this._physicsTimeAccumulator=0,!0}catch(n){return p.Y.Error(n.message),!1}},N.x.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)},N.x.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},N.x.prototype.deleteCompoundImpostor=function(e){const t=e.parts[0].mesh;t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)},N.x.prototype._advancePhysicsEngineStep=function(e){if(this._physicsEngine){const t=this._physicsEngine.getSubTimeStep();if(t>0)for(this._physicsTimeAccumulator+=e;this._physicsTimeAccumulator>t;)this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(t/1e3),this.onAfterPhysicsObservable.notifyObservers(this),this._physicsTimeAccumulator-=t;else this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(e/1e3),this.onAfterPhysicsObservable.notifyObservers(this)}};class BS{constructor(e){this.name=Se.l.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new r.y$,this.scene.onAfterPhysicsObservable=new r.y$,this.scene.getDeterministicFrameTime=()=>this.scene._physicsEngine?1e3*this.scene._physicsEngine.getTimeStep():1e3/60}register(){}rebuild(){}dispose(){this.scene.onBeforePhysicsObservable.clear(),this.scene.onAfterPhysicsObservable.clear(),this.scene._physicsEngine&&this.scene.disablePhysicsEngine()}}Object.defineProperty(te.Y.prototype,"physicsBody",{get:function(){return this._physicsBody},set:function(e){this._physicsBody!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsBody=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add((()=>{this.physicsBody&&(this.physicsBody.dispose(),this.physicsBody=null)}))))},enumerable:!0,configurable:!0}),te.Y.prototype.getPhysicsBody=function(){return this.physicsBody},te.Y.prototype.applyImpulse=function(e,t){if(!this.physicsBody)throw new Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(e,t),this};class US{static GetContactPointToRef(e,t,i,n,s){const r=e.getScene().getPhysicsEngine(),o=null==r?void 0:r.getPluginVersion();if(1===o){const s=new qe(t,i).intersectsMesh(e);if(s.hit&&s.pickedPoint)return n.copyFrom(s.pickedPoint),!0}else if(2===o)return e.physicsBody.getObjectCenterWorldToRef(n,s),!0;return!1}static HasAppliedForces(e,t){var i,n,s;return e.getMotionType(t)===DS.STATIC||0===(null!==(n=null===(i=e.getMassProperties(t))||void 0===i?void 0:i.mass)&&void 0!==n?n:0)||0===(null===(s=e.transformNode)||void 0===s?void 0:s.getTotalVertices())}static IsInsideCylinder(e,t,i,n){const s=o.jp.Vector3[0];return e.subtractToRef(t,s),Math.abs(s.x)<=i&&Math.abs(s.z)<=i&&s.y>=0&&s.y<=n}}class VS{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=o.P.Zero(),this._originDirection=o.P.Zero(),this._cylinderPosition=o.P.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=Object.assign(Object.assign({},new GS),this._options),this._origin.addToRef(new o.P(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new o.P(0,this._options.height,0),this._originTop),this._options.updraftMode===wS.Perpendicular&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=this._tick.bind(this),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?(this._cylinder.dispose(),this._cylinder=void 0):setTimeout((()=>{!this._dataFetched&&this._cylinder&&(this._cylinder.dispose(),this._cylinder=void 0)}),0))}_getHitData(e,t){let i;i=this._options.updraftMode===wS.Perpendicular?this._originDirection:e.subtract(this._originTop);const n=o.P.Distance(this._origin,e),s=-1*this._options.strength,r=i.multiplyByFloats(s,s,s);t.force.copyFrom(r),t.contactPoint.copyFrom(e),t.distanceFromOrigin=n}_getBodyHitData(e,t,i){if(US.HasAppliedForces(e))return!1;const n=e.getObjectCenterWorld(i);return!!US.IsInsideCylinder(n,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(n,t),!0)}_getImpostorHitData(e,t){if(0===e.mass)return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const n=e.getObjectCenter();return this._getHitData(n,t),!0}_tick(){const e=VS._HitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach((t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)})):this._physicsEngine.getBodies().forEach((t=>{t.iterateOverAllInstances(((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)}))}))}_prepareCylinder(){this._cylinder||(this._cylinder=Fa("updraftEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return!!this._cylinder&&(this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0))}}VS._HitData={force:new o.P,contactPoint:new o.P,distanceFromOrigin:0};class kS{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=o.P.Zero(),this._cylinderPosition=o.P.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=Object.assign(Object.assign({},new zS),this._options),this._origin.addToRef(new o.P(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new o.P(0,this._options.height,0),this._originTop),this._tickCallback=this._tick.bind(this),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?this._cylinder.dispose():setTimeout((()=>{this._dataFetched||this._cylinder.dispose()}),0))}_getHitData(e,t,i){const n=kS.originOnPlane;n.set(this._origin.x,t.y,this._origin.z);const s=o.jp.Vector3[0];t.subtractToRef(n,s);const r=o.jp.Vector3[1];if(!US.GetContactPointToRef(e,n,s,r,i.instanceIndex))return!1;const a=o.P.Distance(r,n)/this._options.radius,l=o.jp.Vector3[2];let h,c,d;if(r.normalizeToRef(l),a>this._options.centripetalForceThreshold&&l.negateInPlace(),a>this._options.centripetalForceThreshold)h=l.x*this._options.centripetalForceMultiplier,c=l.y*this._options.updraftForceMultiplier,d=l.z*this._options.centripetalForceMultiplier;else{const e=o.P.Cross(n,t).normalize();h=(e.x+l.x)*this._options.centrifugalForceMultiplier,c=this._originTop.y*this._options.updraftForceMultiplier,d=(e.z+l.z)*this._options.centrifugalForceMultiplier}const u=o.jp.Vector3[3];return u.set(h,c,d),u.scaleInPlace(this._options.strength),i.force.copyFrom(u),i.contactPoint.copyFrom(t),i.distanceFromOrigin=a,!0}_getBodyHitData(e,t,i){if(US.HasAppliedForces(e,i))return!1;const n=e.transformNode,s=e.getObjectCenterWorld(i);return!!US.IsInsideCylinder(s,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(n,s,t))}_getImpostorHitData(e,t){if(0===e.mass)return!1;if("Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;const i=e.object;if(!this._intersectsWithCylinder(i))return!1;const n=e.getObjectCenter();return this._getHitData(i,n,t),!0}_tick(){const e=kS.hitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach((t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)})):this._physicsEngine.getBodies().forEach((t=>{t.iterateOverAllInstances(((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)}))}))}_prepareCylinder(){this._cylinder||(this._cylinder=Fa("vortexEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0)}}kS.originOnPlane=o.P.Zero(),kS.hitData={force:new o.P,contactPoint:new o.P,distanceFromOrigin:0};class GS{constructor(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=wS.Center}}class zS{constructor(){this.radius=5,this.strength=10,this.height=10,this.centripetalForceThreshold=.7,this.centripetalForceMultiplier=5,this.centrifugalForceMultiplier=.5,this.updraftForceMultiplier=.02}}!function(e){e[e.Constant=0]="Constant",e[e.Linear=1]="Linear"}(FS||(FS={})),function(e){e[e.Center=0]="Center",e[e.Perpendicular=1]="Perpendicular"}(wS||(wS={}));const WS="blackAndWhitePixelShader",HS="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}";Ht.v.ShadersStore[WS]=HS;class XS extends Zt{getClassName(){return"BlackAndWhitePostProcess"}constructor(e,t,i,n,s,r){super(e,"blackAndWhite",["degree"],null,t,i,n,s,r),this.degree=1,this.onApplyObservable.add((e=>{e.setFloat("degree",this.degree)}))}static _Parse(e,t,i,n){return E.p4.Parse((()=>new XS(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,n)}}(0,oe.gn)([(0,E.qC)()],XS.prototype,"degree",void 0),(0,l.H)("BABYLON.BlackAndWhitePostProcess",XS);class YS{constructor(e,t,i,n){this._name=t,this._singleInstance=n||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}get isSupported(){for(const e in this._postProcesses)if(Object.prototype.hasOwnProperty.call(this._postProcesses,e)){const t=this._postProcesses[e];for(let e=0;e{const i=e.attachPostProcess(t);this._indicesForCamera[s].push(i)})),this._cameras[s]||(this._cameras[s]=e)}}_detachCameras(e){const t=se.w1.MakeArray(e||this._cameras);if(t)for(let i=0;i{e.detachPostProcess(t)})),this._cameras[n]&&(this._cameras[n]=null)}}_enable(e){const t=se.w1.MakeArray(e||this._cameras);if(t)for(let i=0;i{t[i].attachPostProcess(e,this._indicesForCamera[n][s])}))}}_disable(e){const t=se.w1.MakeArray(e||this._cameras);if(t)for(let i=0;i{e.detachPostProcess(t)}))}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}}const jS="extractHighlightsPixelShader",KS="#include\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}";Ht.v.ShadersStore[jS]=KS;class qS extends Zt{getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i,n,s,r,o=0,a=!1){super(e,"extractHighlights",["threshold","exposure"],null,t,i,n,s,r,null,o,void 0,null,a),this.threshold=.9,this._exposure=1,this._inputPostProcess=null,this.onApplyObservable.add((e=>{this.externalTextureSamplerBinding=!!this._inputPostProcess,this._inputPostProcess&&e.setTextureFromPostProcess("textureSampler",this._inputPostProcess),e.setFloat("threshold",Math.pow(this.threshold,k.zp)),e.setFloat("exposure",this._exposure)}))}}(0,oe.gn)([(0,E.qC)()],qS.prototype,"threshold",void 0),(0,l.H)("BABYLON.ExtractHighlightsPostProcess",qS);const $S="bloomMergePixelShader",QS="uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n";Ht.v.ShadersStore[$S]=QS;class ZS extends Zt{getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,n,s,r,o,a,l,h=0,c=!1){super(e,"bloomMerge",["bloomWeight"],["bloomBlur"],s,r,o,a,l,null,h,void 0,null,!0),this.weight=1,this.weight=n,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("bloomBlur",i),e.setFloat("bloomWeight",this.weight)})),c||this.updateEffect()}}(0,oe.gn)([(0,E.qC)()],ZS.prototype,"weight",void 0),(0,l.H)("BABYLON.BloomMergePostProcess",ZS);class JS extends YS{get threshold(){return this._downscale.threshold}set threshold(e){this._downscale.threshold=e}get weight(){return this._merge.weight}set weight(e){this._merge.weight=e}get kernel(){return this._blurX.kernel/this._bloomScale}set kernel(e){this._blurX.kernel=e*this._bloomScale,this._blurY.kernel=e*this._bloomScale}constructor(e,t,i,n,s=0,r=!1){super(e.getEngine(),"bloom",(()=>this._effects),!0),this._bloomScale=t,this._effects=[],this._downscale=new qS("highlights",1,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,r),this._blurX=new bp("horizontal blur",new o.FM(1,0),10,t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,void 0,r),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new bp("vertical blur",new o.FM(0,1),10,t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,void 0,r),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=n,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new ZS("bloomMerge",this._downscale,this._blurY,i,t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,r),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;t{e.setFloat("chromatic_aberration",this.aberrationAmount),e.setFloat("screen_width",t),e.setFloat("screen_height",i),e.setFloat("radialIntensity",this.radialIntensity),e.setFloat2("direction",this.direction.x,this.direction.y),e.setFloat2("centerPosition",this.centerPosition.x,this.centerPosition.y)}))}static _Parse(e,t,i,n){return E.p4.Parse((()=>new iE(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1)),e,i,n)}}(0,oe.gn)([(0,E.qC)()],iE.prototype,"aberrationAmount",void 0),(0,oe.gn)([(0,E.qC)()],iE.prototype,"radialIntensity",void 0),(0,oe.gn)([(0,E.qC)()],iE.prototype,"direction",void 0),(0,oe.gn)([(0,E.qC)()],iE.prototype,"centerPosition",void 0),(0,oe.gn)([(0,E.qC)()],iE.prototype,"screenWidth",void 0),(0,oe.gn)([(0,E.qC)()],iE.prototype,"screenHeight",void 0),(0,l.H)("BABYLON.ChromaticAberrationPostProcess",iE);const nE="circleOfConfusionPixelShader",sE="uniform sampler2D depthSampler;\nvarying vec2 vUV;\nuniform vec2 cameraMinMaxZ;\nuniform float focusDistance;\nuniform float cocPrecalculation;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\n#define CUSTOM_COC_DEPTH\nfloat pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; \n#define CUSTOM_COC_PIXELDISTANCE\nfloat coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,coc,coc,1.0);\n}\n";Ht.v.ShadersStore[nE]=sE;class rE extends Zt{getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,n,s,r,o,a=0,l=!1){super(e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],i,n,s,r,o,null,a,void 0,null,l),this.lensSize=50,this.fStop=1.4,this.focusDistance=2e3,this.focalLength=50,this._depthTexture=null,this._depthTexture=t,this.onApplyObservable.add((e=>{if(!this._depthTexture)return void p.Y.Warn("No depth texture set on CircleOfConfusionPostProcess");e.setTexture("depthSampler",this._depthTexture);const t=this.lensSize/this.fStop*this.focalLength/(this.focusDistance-this.focalLength);e.setFloat("focusDistance",this.focusDistance),e.setFloat("cocPrecalculation",t);const i=this._depthTexture.activeCamera;e.setFloat2("cameraMinMaxZ",i.minZ,i.maxZ-i.minZ)}))}set depthTexture(e){this._depthTexture=e}}(0,oe.gn)([(0,E.qC)()],rE.prototype,"lensSize",void 0),(0,oe.gn)([(0,E.qC)()],rE.prototype,"fStop",void 0),(0,oe.gn)([(0,E.qC)()],rE.prototype,"focusDistance",void 0),(0,oe.gn)([(0,E.qC)()],rE.prototype,"focalLength",void 0),(0,l.H)("BABYLON.CircleOfConfusionPostProcess",rE);const oE="colorCorrectionPixelShader",aE="uniform sampler2D textureSampler; \nuniform sampler2D colorTable; \nvarying vec2 vUV;\nconst float SLICE_COUNT=16.0; \nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}";Ht.v.ShadersStore[oE]=aE;class lE extends Zt{getClassName(){return"ColorCorrectionPostProcess"}constructor(e,t,i,n,s,r,o){super(e,"colorCorrection",null,["colorTable"],i,n,s,r,o);const a=(null==n?void 0:n.getScene())||null;this._colorTableTexture=new Le(t,a,!0,!1,Le.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=Le.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=Le.CLAMP_ADDRESSMODE,this.colorTableUrl=t,this.onApply=e=>{e.setTexture("colorTable",this._colorTableTexture)}}static _Parse(e,t,i,n){return E.p4.Parse((()=>new lE(e.name,e.colorTableUrl,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,n)}}(0,oe.gn)([(0,E.qC)()],lE.prototype,"colorTableUrl",void 0),(0,l.H)("BABYLON.ColorCorrectionPostProcess",lE);const hE="convolutionPixelShader",cE="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}";Ht.v.ShadersStore[hE]=cE;class dE extends Zt{getClassName(){return"ConvolutionPostProcess"}constructor(e,t,i,n,s,r,o,a=0){super(e,"convolution",["kernel","screenSize"],null,i,n,s,r,o,null,a),this.kernel=t,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setArray("kernel",this.kernel)}}static _Parse(e,t,i,n){return E.p4.Parse((()=>new dE(e.name,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType)),e,i,n)}}dE.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1],dE.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0],dE.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1],dE.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0],dE.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2],dE.GaussianKernel=[0,1,0,1,1,1,0,1,0],(0,oe.gn)([(0,E.qC)()],dE.prototype,"kernel",void 0),(0,l.H)("BABYLON.ConvolutionPostProcess",dE);class uE extends bp{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,n,s,r,o,a=null,l=Le.BILINEAR_SAMPLINGMODE,h,c,d=0,u=!1,p=5){super(e,i,n,s,r,2,h,c,d,"#define DOF 1\r\n",u,p),this.direction=i,this.externalTextureSamplerBinding=!!a,this.onApplyObservable.add((e=>{null!=a&&e.setTextureFromPostProcess("textureSampler",a),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",o)}))}}(0,oe.gn)([(0,E.qC)()],uE.prototype,"direction",void 0),(0,l.H)("BABYLON.DepthOfFieldBlurPostProcess",uE);const pE="depthOfFieldMergePixelShader",fE="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#endif\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nfloat coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r;\n#if BLUR_LEVEL==0\nvec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);\nvec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL==1\nif(coc<0.5){\nvec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);\nvec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);\nvec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL==2\nif(coc<0.33){\nvec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);\nvec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);\nvec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);\nvec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n";Ht.v.ShadersStore[pE]=fE;class _E extends Zt{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,n,s,r,o,a,l,h=0,c=!1){super(e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],s,r,o,a,l,null,h,void 0,null,!0),this._blurSteps=n,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add((e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),n.forEach(((t,i)=>{e.setTextureFromPostProcessOutput("blurStep"+(n.length-i-1),t)}))})),c||this.updateEffect()}updateEffect(e=null,t=null,i=null,n,s,r){e||(e="",e+="#define BLUR_LEVEL "+(this._blurSteps.length-1)+"\n"),super.updateEffect(e,t,i,n,s,r)}}var mE;!function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High"}(mE||(mE={}));class gE extends YS{set focalLength(e){this._circleOfConfusion.focalLength=e}get focalLength(){return this._circleOfConfusion.focalLength}set fStop(e){this._circleOfConfusion.fStop=e}get fStop(){return this._circleOfConfusion.fStop}set focusDistance(e){this._circleOfConfusion.focusDistance=e}get focusDistance(){return this._circleOfConfusion.focusDistance}set lensSize(e){this._circleOfConfusion.lensSize=e}get lensSize(){return this._circleOfConfusion.lensSize}constructor(e,t,i=mE.Low,n=0,s=!1){super(e.getEngine(),"depth of field",(()=>this._effects),!0),this._effects=[];const r=e.getEngine(),a=r.isWebGPU||r.webGLVersion>1?6:5;this._circleOfConfusion=new rE("circleOfConfusion",t,1,null,Le.BILINEAR_SAMPLINGMODE,r,!1,n,s),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];let l=1,h=15;switch(i){case mE.High:l=3,h=51;break;case mE.Medium:l=2,h=31;break;default:h=15,l=1}const c=h/Math.pow(2,l-1);let d=1;for(let u=0;unew SE(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,n)}}(0,l.H)("BABYLON.DisplayPassPostProcess",SE);const EE="filterPixelShader",xE="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}";Ht.v.ShadersStore[EE]=xE;class bE extends Zt{getClassName(){return"FilterPostProcess"}constructor(e,t,i,n,s,r,o){super(e,"filter",["kernelMatrix"],null,i,n,s,r,o),this.kernelMatrix=t,this.onApply=e=>{e.setMatrix("kernelMatrix",this.kernelMatrix)}}static _Parse(e,t,i,n){return E.p4.Parse((()=>new bE(e.name,e.kernelMatrix,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,n)}}(0,oe.gn)([(0,E.oQ)()],bE.prototype,"kernelMatrix",void 0),(0,l.H)("BABYLON.FilterPostProcess",bE);const CE="fxaaPixelShader",yE="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN{const t=this.texelSize;e.setFloat2("texelSize",t.x,t.y)}))}_getDefines(){const e=this.getEngine();if(!e)return null;const t=e.getGlInfo();return t&&t.renderer&&t.renderer.toLowerCase().indexOf("mali")>-1?"#define MALI 1\n":null}static _Parse(e,t,i,n){return E.p4.Parse((()=>new PE(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,n)}}(0,l.H)("BABYLON.FxaaPostProcess",PE);const IE="grainPixelShader",ME="#include\nuniform sampler2D textureSampler; \nuniform float intensity;\nuniform float animatedSeed;\nvarying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}";Ht.v.ShadersStore[IE]=ME;class OE extends Zt{getClassName(){return"GrainPostProcess"}constructor(e,t,i,n,s,r,o=0,a=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,n,s,r,null,o,void 0,null,a),this.intensity=30,this.animated=!1,this.onApplyObservable.add((e=>{e.setFloat("intensity",this.intensity),e.setFloat("animatedSeed",this.animated?Math.random()+1:1)}))}static _Parse(e,t,i,n){return E.p4.Parse((()=>new OE(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,n)}}(0,oe.gn)([(0,E.qC)()],OE.prototype,"intensity",void 0),(0,oe.gn)([(0,E.qC)()],OE.prototype,"animated",void 0),(0,l.H)("BABYLON.GrainPostProcess",OE);const DE="highlightsPixelShader",NE="varying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}";Ht.v.ShadersStore[DE]=NE;const FE="mrtFragmentDeclaration",wE="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n";Ht.v.IncludesShadersStore[FE]=wE;const LE="geometryPixelShader",BE="#extension GL_EXT_draw_buffers : require\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\nprecision highp float;\n#ifdef BUMP\nvarying mat4 vWorldView;\nvarying vec3 vNormalW;\n#else\nvarying vec3 vNormalV;\n#endif\nvarying vec4 vViewPos;\n#if defined(POSITION) || defined(BUMP)\nvarying vec3 vPositionW;\n#endif\n#ifdef VELOCITY\nvarying vec4 vCurrentPosition;\nvarying vec4 vPreviousPosition;\n#endif\n#ifdef NEED_UV\nvarying vec2 vUV;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIVITY)\n#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nuniform sampler2D reflectivitySampler;\nvarying vec2 vReflectivityUV;\n#endif\n#ifdef ALBEDOTEXTURE\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\n#endif\n#ifdef REFLECTIVITYCOLOR\nuniform vec3 reflectivityColor;\n#endif\n#ifdef ALBEDOCOLOR\nuniform vec3 albedoColor;\n#endif\n#ifdef METALLIC\nuniform float metallic;\n#endif\n#if defined(ROUGHNESS) || defined(GLOSSINESS)\nuniform float glossiness;\n#endif\n#endif\n#if defined(ALPHATEST) && defined(NEED_UV)\nuniform sampler2D diffuseSampler;\n#endif\n#include\n#include[RENDER_TARGET_COUNT]\n#include\n#include\n#include\nvoid main() {\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nvec3 normalOutput;\n#ifdef BUMP\nvec3 normalW=normalize(vNormalW);\n#include\nnormalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0)));\n#else\nnormalOutput=normalize(vNormalV);\n#endif\n#ifdef PREPASS\n#ifdef PREPASS_DEPTH\ngl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n#endif\n#ifdef PREPASS_NORMAL\ngl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0);\n#endif\n#else\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\ngl_FragData[1]=vec4(normalOutput,1.0);\n#endif\n#ifdef POSITION\ngl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0);\n#endif\n#ifdef VELOCITY\nvec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;\nvec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;\nvec2 velocity=abs(a-b);\nvelocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;\ngl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0);\n#endif\n#ifdef REFLECTIVITY\nvec4 reflectivity=vec4(0.0,0.0,0.0,1.0);\n#ifdef METALLICWORKFLOW\nfloat metal=1.0;\nfloat roughness=1.0;\n#ifdef ORMTEXTURE\nmetal*=texture2D(reflectivitySampler,vReflectivityUV).b;\nroughness*=texture2D(reflectivitySampler,vReflectivityUV).g;\n#endif\n#ifdef METALLIC\nmetal*=metallic;\n#endif\n#ifdef ROUGHNESS\nroughness*=(1.0-glossiness); \n#endif\nreflectivity.a-=roughness;\nvec3 color=vec3(1.0);\n#ifdef ALBEDOTEXTURE\ncolor=texture2D(albedoSampler,vAlbedoUV).rgb;\n#ifdef GAMMAALBEDO\ncolor=toLinearSpace(color);\n#endif\n#endif\n#ifdef ALBEDOCOLOR\ncolor*=albedoColor.xyz;\n#endif\nreflectivity.rgb=mix(vec3(0.04),color,metal);\n#else\n#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE)\nreflectivity=texture2D(reflectivitySampler,vReflectivityUV);\n#ifdef GAMMAREFLECTIVITYTEXTURE\nreflectivity.rgb=toLinearSpace(reflectivity.rgb);\n#endif\n#else \n#ifdef REFLECTIVITYCOLOR\nreflectivity.rgb=toLinearSpace(reflectivityColor.xyz);\nreflectivity.a=1.0;\n#endif\n#endif\n#ifdef GLOSSINESSS\nreflectivity.a*=glossiness; \n#endif\n#endif\ngl_FragData[REFLECTIVITY_INDEX]=reflectivity;\n#endif\n}\n";Ht.v.ShadersStore[LE]=BE;const UE="geometryVertexDeclaration",VE="uniform mat4 viewProjection;\nuniform mat4 view;";Ht.v.IncludesShadersStore[UE]=VE;const kE="geometryUboDeclaration",GE="#include\n";Ht.v.IncludesShadersStore[kE]=GE;const zE="geometryVertexShader",WE="precision highp float;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include<__decl__geometryVertex>\n#include\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef NEED_UV\nvarying vec2 vUV;\n#ifdef ALPHATEST\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef BUMP\nuniform mat4 bumpMatrix;\nvarying vec2 vBumpUV;\n#endif\n#ifdef REFLECTIVITY\nuniform mat4 reflectivityMatrix;\nuniform mat4 albedoMatrix;\nvarying vec2 vReflectivityUV;\nvarying vec2 vAlbedoUV;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#ifdef BUMP\nvarying mat4 vWorldView;\n#endif\n#ifdef BUMP\nvarying vec3 vNormalW;\n#else\nvarying vec3 vNormalV;\n#endif\nvarying vec4 vViewPos;\n#if defined(POSITION) || defined(BUMP)\nvarying vec3 vPositionW;\n#endif\n#ifdef VELOCITY\nuniform mat4 previousViewProjection;\nvarying vec4 vCurrentPosition;\nvarying vec4 vPreviousPosition;\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{\nvec3 positionUpdated=position;\nvec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#if defined(VELOCITY) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#include\n#include\nvec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0));\n#ifdef BUMP\nvWorldView=view*finalWorld;\nvNormalW=normalUpdated;\n#else\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0)));\n#endif\nvViewPos=view*worldPos;\n#if defined(VELOCITY) && defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#if NUM_BONE_INFLUENCERS>0\nmat4 previousInfluence;\npreviousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\npreviousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif\n#if NUM_BONE_INFLUENCERS>2\npreviousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif\n#if NUM_BONE_INFLUENCERS>3\npreviousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif\n#if NUM_BONE_INFLUENCERS>4\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif\n#if NUM_BONE_INFLUENCERS>5\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif\n#if NUM_BONE_INFLUENCERS>6\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif\n#if NUM_BONE_INFLUENCERS>7\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif\nvPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0);\n#else\nvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\n#endif\n#endif\n#if defined(POSITION) || defined(BUMP)\nvPositionW=worldPos.xyz/worldPos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\n#include\n#ifdef NEED_UV\n#ifdef UV1\n#if defined(ALPHATEST) && defined(ALPHATEST_UV1)\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#else\nvUV=uv;\n#endif\n#ifdef BUMP_UV1\nvBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef REFLECTIVITY_UV1\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef ALBEDO_UV1\nvAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#endif\n#ifdef UV2\n#if defined(ALPHATEST) && defined(ALPHATEST_UV2)\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#else\nvUV=uv2;\n#endif\n#ifdef BUMP_UV2\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n#endif\n#ifdef REFLECTIVITY_UV2\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n#endif\n#ifdef ALBEDO_UV2\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#endif\n#include\n}\n";Ht.v.ShadersStore[zE]=WE;const HE=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];(0,ua.qx)(HE);class XE{_linkPrePassRenderer(e){this._linkedWithPrePass=!0,this._prePassRenderer=e,this._multiRenderTarget&&(this._multiRenderTarget.onClearObservable.clear(),this._multiRenderTarget.onClearObservable.add((()=>{})))}_unlinkPrePassRenderer(){this._linkedWithPrePass=!1,this._createRenderTargets()}_resetLayout(){this._enablePosition=!1,this._enableReflectivity=!1,this._enableVelocity=!1,this._attachmentsFromPrePass=[]}_forceTextureType(e,t){e===XE.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===XE.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===XE.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===XE.DEPTH_TEXTURE_TYPE?this._depthIndex=t:e===XE.NORMAL_TEXTURE_TYPE&&(this._normalIndex=t)}_setAttachments(e){this._attachmentsFromPrePass=e}_linkInternalTexture(e){this._multiRenderTarget.setInternalTexture(e,0,!1)}get renderList(){return this._multiRenderTarget.renderList}set renderList(e){this._multiRenderTarget.renderList=e}get isSupported(){return this._multiRenderTarget.isSupported}getTextureIndex(e){switch(e){case XE.POSITION_TEXTURE_TYPE:return this._positionIndex;case XE.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case XE.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;default:return-1}}get enablePosition(){return this._enablePosition}set enablePosition(e){this._enablePosition=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableVelocity(){return this._enableVelocity}set enableVelocity(e){this._enableVelocity=e,e||(this._previousTransformationMatrices={}),this._linkedWithPrePass||(this.dispose(),this._createRenderTargets()),this._scene.needsPreviousWorldMatrices=e}get enableReflectivity(){return this._enableReflectivity}set enableReflectivity(e){this._enableReflectivity=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get scene(){return this._scene}get ratio(){return this._ratio}constructor(e,t=1,i=15){this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this._resizeObserver=null,this._enablePosition=!1,this._enableVelocity=!1,this._enableReflectivity=!1,this._clearColor=new a.HE(0,0,0,0),this._clearDepthColor=new a.HE(1e8,0,0,1),this._positionIndex=-1,this._velocityIndex=-1,this._reflectivityIndex=-1,this._depthIndex=-1,this._normalIndex=-1,this._linkedWithPrePass=!1,this.useSpecificClearForDepthTexture=!1,this._scene=e,this._ratio=t,this._useUbo=e.getEngine().supportsUniformBuffers,this._depthFormat=i,XE._SceneComponentInitialization(this._scene),this._createRenderTargets()}isReady(e,t){const i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;const n=[],s=[ne.o.PositionKind,ne.o.NormalKind],r=e.getMesh();if(i){let e=!1;if(i.needAlphaTesting()&&i.getAlphaTestTexture()&&(n.push("#define ALPHATEST"),n.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),e=!0),i.bumpTexture&&Bs.BumpTextureEnabled&&(n.push("#define BUMP"),n.push(`#define BUMP_UV${i.bumpTexture.coordinatesIndex+1}`),e=!0),this._enableReflectivity){let t=!1;"PBRMetallicRoughnessMaterial"===i.getClassName()?(null!==i.metallicRoughnessTexture&&(n.push("#define ORMTEXTURE"),n.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),n.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!==i.metallic&&(n.push("#define METALLIC"),n.push("#define METALLICWORKFLOW"),t=!0),null!==i.roughness&&(n.push("#define ROUGHNESS"),n.push("#define METALLICWORKFLOW"),t=!0),t&&(null!==i.baseTexture&&(n.push("#define ALBEDOTEXTURE"),n.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&n.push("#define GAMMAALBEDO"),e=!0),null!==i.baseColor&&n.push("#define ALBEDOCOLOR"))):"PBRSpecularGlossinessMaterial"===i.getClassName()?(null!==i.specularGlossinessTexture?(n.push("#define SPECULARGLOSSINESSTEXTURE"),n.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),e=!0,i.specularGlossinessTexture.gammaSpace&&n.push("#define GAMMAREFLECTIVITYTEXTURE")):null!==i.specularColor&&n.push("#define REFLECTIVITYCOLOR"),null!==i.glossiness&&n.push("#define GLOSSINESS")):"PBRMaterial"===i.getClassName()?(null!==i.metallicTexture&&(n.push("#define ORMTEXTURE"),n.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),n.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!==i.metallic&&(n.push("#define METALLIC"),n.push("#define METALLICWORKFLOW"),t=!0),null!==i.roughness&&(n.push("#define ROUGHNESS"),n.push("#define METALLICWORKFLOW"),t=!0),t?(null!==i.albedoTexture&&(n.push("#define ALBEDOTEXTURE"),n.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&n.push("#define GAMMAALBEDO"),e=!0),null!==i.albedoColor&&n.push("#define ALBEDOCOLOR")):(null!==i.reflectivityTexture?(n.push("#define SPECULARGLOSSINESSTEXTURE"),n.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&n.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0):null!==i.reflectivityColor&&n.push("#define REFLECTIVITYCOLOR"),null!==i.microSurface&&n.push("#define GLOSSINESS"))):"StandardMaterial"===i.getClassName()&&(null!==i.specularTexture&&(n.push("#define REFLECTIVITYTEXTURE"),n.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&n.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0),null!==i.specularColor&&n.push("#define REFLECTIVITYCOLOR"))}e&&(n.push("#define NEED_UV"),r.isVerticesDataPresent(ne.o.UVKind)&&(s.push(ne.o.UVKind),n.push("#define UV1")),r.isVerticesDataPresent(ne.o.UV2Kind)&&(s.push(ne.o.UV2Kind),n.push("#define UV2")))}this._linkedWithPrePass&&(n.push("#define PREPASS"),-1!==this._depthIndex&&(n.push("#define DEPTH_INDEX "+this._depthIndex),n.push("#define PREPASS_DEPTH")),-1!==this._normalIndex&&(n.push("#define NORMAL_INDEX "+this._normalIndex),n.push("#define PREPASS_NORMAL"))),this._enablePosition&&(n.push("#define POSITION"),n.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(n.push("#define VELOCITY"),n.push("#define VELOCITY_INDEX "+this._velocityIndex),-1===this.excludedSkinnedMeshesFromVelocity.indexOf(r)&&n.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(n.push("#define REFLECTIVITY"),n.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),r.useBones&&r.computeBonesUsingShaders?(s.push(ne.o.MatricesIndicesKind),s.push(ne.o.MatricesWeightsKind),r.numBoneInfluencers>4&&(s.push(ne.o.MatricesIndicesExtraKind),s.push(ne.o.MatricesWeightsExtraKind)),n.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),n.push("#define BonesPerMesh "+(r.skeleton?r.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0");const o=r.morphTargetManager;let a=0;o&&o.numInfluencers>0&&(a=o.numInfluencers,n.push("#define MORPHTARGETS"),n.push("#define NUM_MORPH_INFLUENCERS "+a),o.isUsingTextureForTargets&&n.push("#define MORPHTARGETS_TEXTURE"),It.G.PrepareAttributesForMorphTargetsInfluencers(s,r,a)),t&&(n.push("#define INSTANCES"),It.G.PushAttributesForInstances(s,this._enableVelocity),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES")),this._linkedWithPrePass?n.push("#define RENDER_TARGET_COUNT "+this._attachmentsFromPrePass.length):n.push("#define RENDER_TARGET_COUNT "+this._multiRenderTarget.textures.length),(0,ua.lK)(i,this._scene,n);const l=this._scene.getEngine(),h=e._getDrawWrapper(void 0,!0),c=h.defines,d=n.join("\n");return c!==d&&h.setEffect(l.createEffect("geometry",{attributes:s,uniformsNames:HE,samplers:["diffuseSampler","bumpSampler","reflectivitySampler","albedoSampler","morphTargets"],defines:d,onCompiled:null,fallbacks:null,onError:null,uniformBuffersNames:["Scene"],indexParameters:{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:a}},l),d),h.effect.isReady()}getGBuffer(){return this._multiRenderTarget}get samples(){return this._multiRenderTarget.samples}set samples(e){this._multiRenderTarget.samples=e}dispose(){if(this._resizeObserver){this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null}this.getGBuffer().dispose()}_assignRenderTargetIndices(){const e=[];let t=2;return e.push("gBuffer_Depth","gBuffer_Normal"),this._enablePosition&&(this._positionIndex=t,t++,e.push("gBuffer_Position")),this._enableVelocity&&(this._velocityIndex=t,t++,e.push("gBuffer_Velocity")),this._enableReflectivity&&(this._reflectivityIndex=t,t++,e.push("gBuffer_Reflectivity")),[t,e]}_createRenderTargets(){const e=this._scene.getEngine(),[t,i]=this._assignRenderTargetIndices();let n=0;if(e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?n=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(n=2),this._multiRenderTarget=new Lv("gBuffer",{width:e.getRenderWidth()*this._ratio,height:e.getRenderHeight()*this._ratio},t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,defaultType:n,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=Le.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=Le.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;const s=[!0],r=[!1],a=[!0];for(let o=1;o{e.bindAttachments(this.useSpecificClearForDepthTexture?h:l),e.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(e.bindAttachments(c),e.clear(this._clearDepthColor,!0,!0,!0)),e.bindAttachments(l)})),this._resizeObserver=e.onResizeObservable.add((()=>{this._multiRenderTarget&&this._multiRenderTarget.resize({width:e.getRenderWidth()*this._ratio,height:e.getRenderHeight()*this._ratio})}));const d=e=>{const t=e.getRenderingMesh(),i=e.getEffectiveMesh(),n=this._scene,s=n.getEngine(),r=e.getMaterial();if(!r)return;if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,this._enableVelocity&&!this._previousTransformationMatrices[i.uniqueId]&&(this._previousTransformationMatrices[i.uniqueId]={world:o.y3.Identity(),viewProjection:n.getTransformMatrix()},t.skeleton)){const e=t.skeleton.getTransformMatrices(t);this._previousBonesTransformationMatrices[t.uniqueId]=this._copyBonesTransformationMatrices(e,new Float32Array(e.length))}const a=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(a.mustReturn)return;const l=s.getCaps().instancedArrays&&(null!==a.visibleInstances[e._id]||t.hasThinInstances),h=i.getWorldMatrix();if(this.isReady(e,l)){const o=e._getDrawWrapper();if(!o)return;const c=o.effect;let d;s.enableEffect(o),l||t._bind(e,c,r.fillMode),this._useUbo?(It.G.BindSceneUniformBuffer(c,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(c.setMatrix("viewProjection",n.getTransformMatrix()),c.setMatrix("view",n.getViewMatrix()));const u=t._instanceDataStorage;if(u.isFrozen||!r.backFaceCulling&&null===t.overrideMaterialSideOrientation)d=u.sideOrientation;else{const e=i._getWorldMatrixDeterminant();d=t.overrideMaterialSideOrientation,null===d&&(d=r.sideOrientation),e<0&&(d=d===ut.F.ClockWiseSideOrientation?ut.F.CounterClockWiseSideOrientation:ut.F.ClockWiseSideOrientation)}if(r._preBind(o,d),r.needAlphaTesting()){const e=r.getAlphaTestTexture();e&&(c.setTexture("diffuseSampler",e),c.setMatrix("diffuseMatrix",e.getTextureMatrix()))}r.bumpTexture&&n.getEngine().getCaps().standardDerivatives&&Bs.BumpTextureEnabled&&(c.setFloat3("vBumpInfos",r.bumpTexture.coordinatesIndex,1/r.bumpTexture.level,r.parallaxScaleBias),c.setMatrix("bumpMatrix",r.bumpTexture.getTextureMatrix()),c.setTexture("bumpSampler",r.bumpTexture),c.setFloat2("vTangentSpaceParams",r.invertNormalMapX?-1:1,r.invertNormalMapY?-1:1)),this._enableReflectivity&&("PBRMetallicRoughnessMaterial"===r.getClassName()?(null!==r.metallicRoughnessTexture&&(c.setTexture("reflectivitySampler",r.metallicRoughnessTexture),c.setMatrix("reflectivityMatrix",r.metallicRoughnessTexture.getTextureMatrix())),null!==r.metallic&&c.setFloat("metallic",r.metallic),null!==r.roughness&&c.setFloat("glossiness",1-r.roughness),null!==r.baseTexture&&(c.setTexture("albedoSampler",r.baseTexture),c.setMatrix("albedoMatrix",r.baseTexture.getTextureMatrix())),null!==r.baseColor&&c.setColor3("albedoColor",r.baseColor)):"PBRSpecularGlossinessMaterial"===r.getClassName()?(null!==r.specularGlossinessTexture?(c.setTexture("reflectivitySampler",r.specularGlossinessTexture),c.setMatrix("reflectivityMatrix",r.specularGlossinessTexture.getTextureMatrix())):null!==r.specularColor&&c.setColor3("reflectivityColor",r.specularColor),null!==r.glossiness&&c.setFloat("glossiness",r.glossiness)):"PBRMaterial"===r.getClassName()?(null!==r.metallicTexture&&(c.setTexture("reflectivitySampler",r.metallicTexture),c.setMatrix("reflectivityMatrix",r.metallicTexture.getTextureMatrix())),null!==r.metallic&&c.setFloat("metallic",r.metallic),null!==r.roughness&&c.setFloat("glossiness",1-r.roughness),null!==r.roughness||null!==r.metallic||null!==r.metallicTexture?(null!==r.albedoTexture&&(c.setTexture("albedoSampler",r.albedoTexture),c.setMatrix("albedoMatrix",r.albedoTexture.getTextureMatrix())),null!==r.albedoColor&&c.setColor3("albedoColor",r.albedoColor)):(null!==r.reflectivityTexture?(c.setTexture("reflectivitySampler",r.reflectivityTexture),c.setMatrix("reflectivityMatrix",r.reflectivityTexture.getTextureMatrix())):null!==r.reflectivityColor&&c.setColor3("reflectivityColor",r.reflectivityColor),null!==r.microSurface&&c.setFloat("glossiness",r.microSurface))):"StandardMaterial"===r.getClassName()&&(null!==r.specularTexture&&(c.setTexture("reflectivitySampler",r.specularTexture),c.setMatrix("reflectivityMatrix",r.specularTexture.getTextureMatrix())),null!==r.specularColor&&c.setColor3("reflectivityColor",r.specularColor))),(0,ua.an)(c,r,this._scene),t.useBones&&t.computeBonesUsingShaders&&t.skeleton&&(c.setMatrices("mBones",t.skeleton.getTransformMatrices(t)),this._enableVelocity&&c.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[t.uniqueId])),It.G.BindMorphTargetParameters(t,c),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(c),this._enableVelocity&&(c.setMatrix("previousWorld",this._previousTransformationMatrices[i.uniqueId].world),c.setMatrix("previousViewProjection",this._previousTransformationMatrices[i.uniqueId].viewProjection)),l&&t.hasThinInstances&&c.setMatrix("world",h),t._processRendering(i,e,c,r.fillMode,a,l,((e,t)=>{e||c.setMatrix("world",t)}))}this._enableVelocity&&(this._previousTransformationMatrices[i.uniqueId].world=h.clone(),this._previousTransformationMatrices[i.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),t.skeleton&&this._copyBonesTransformationMatrices(t.skeleton.getTransformMatrices(t),this._previousBonesTransformationMatrices[i.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(t,i,n)=>{if((n||0===i)&&t.subMeshes)for(let s=0;s{let r;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(s.length){for(e.setColorWrite(!1),r=0;r{throw(0,ge.S)("GeometryBufferRendererSceneComponent")};class YE{constructor(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[2]}}Object.defineProperty(N.x.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(e){e&&e.isSupported&&(this._geometryBufferRenderer=e)},enumerable:!0,configurable:!0}),N.x.prototype.enableGeometryBufferRenderer=function(e=1,t=15){return this._geometryBufferRenderer||(this._geometryBufferRenderer=new XE(this,e,t),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null)),this._geometryBufferRenderer},N.x.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};class jE{constructor(e){this.name=Se.l.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(Se.l.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)}rebuild(){}dispose(){}_gatherRenderTargets(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())}}XE._SceneComponentInitialization=e=>{let t=e._getComponent(Se.l.NAME_GEOMETRYBUFFERRENDERER);t||(t=new jE(e),e._addComponent(t))};const KE="motionBlurPixelShader",qE="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float motionStrength;\nuniform float motionScale;\nuniform vec2 screenSize;\n#ifdef OBJECT_BASED\nuniform sampler2D velocitySampler;\n#else\nuniform sampler2D depthSampler;\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform mat4 projection;\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\n#ifdef GEOMETRY_SUPPORTED\n#ifdef OBJECT_BASED\nvec2 texelSize=1.0/screenSize;\nvec4 velocityColor=texture2D(velocitySampler,vUV);\nvelocityColor.rg=velocityColor.rg*2.0-vec2(1.0);\nvec2 velocity=vec2(pow(velocityColor.r,3.0),pow(velocityColor.g,3.0))*velocityColor.a;\nvelocity*=motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint samplesCount=int(clamp(speed,1.0,SAMPLES));\nvelocity=normalize(velocity)*texelSize;\nfloat hlim=float(-samplesCount)*0.5+0.5;\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i=samplesCount)\nbreak;\nvec2 offset=vUV+velocity*(hlim+float(i));\n#if defined(WEBGPU)\nresult+=texture2DLodEXT(textureSampler,offset,0.0);\n#else\nresult+=texture2D(textureSampler,offset);\n#endif\n}\ngl_FragColor=result/float(samplesCount);\ngl_FragColor.a=1.0;\n#else\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\ndepth=projection[2].z+projection[3].z/depth; \nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=inverseViewProjection*cpos;\ncpos/=cpos.w;\nvec4 ppos=prevViewProjection*cpos;\nppos/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\n#if defined(WEBGPU)\nresult+=texture2DLodEXT(textureSampler,offset1,0.0);\n#else\nresult+=texture2D(textureSampler,offset1);\n#endif\n}\ngl_FragColor=result/float(nSamples);\n#endif\n#else\ngl_FragColor=texture2D(textureSampler,vUV);\n#endif\n}\n";Ht.v.ShadersStore[KE]=qE;class $E extends Zt{get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this._motionBlurSamples=e,this._updateEffect()}get isObjectBased(){return this._isObjectBased}set isObjectBased(e){this._isObjectBased!==e&&(this._isObjectBased=e,this._applyMode())}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}getClassName(){return"MotionBlurPostProcess"}constructor(e,t,i,n,s,r,o,a=0,l=!1,h=!1){super(e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],i,n,s,r,o,"#define GEOMETRY_SUPPORTED\n#define SAMPLES 64.0\n#define OBJECT_BASED",a,void 0,null,l),this.motionStrength=1,this._motionBlurSamples=32,this._isObjectBased=!0,this._forceGeometryBuffer=!1,this._invViewProjection=null,this._previousViewProjection=null,this._forceGeometryBuffer=h,this._forceGeometryBuffer?(t.enableGeometryBufferRenderer(),this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=!0)):(t.enablePrePassRenderer(),this._prePassRenderer&&(this._prePassRenderer.markAsDirty(),this._prePassEffectConfiguration=new YE)),this._applyMode()}excludeSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}t.push(e)}}removeExcludedSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}const i=t.indexOf(e);-1!==i&&t.splice(i,1)}}dispose(e){this._geometryBufferRenderer&&(this._geometryBufferRenderer._previousTransformationMatrices={},this._geometryBufferRenderer._previousBonesTransformationMatrices={},this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity=[]),super.dispose(e)}_applyMode(){if(!this._geometryBufferRenderer&&!this._prePassRenderer)return p.Y.Warn("Multiple Render Target support needed to compute object based motion blur"),this.updateEffect();this._updateEffect(),this._invViewProjection=null,this._previousViewProjection=null,this.isObjectBased?(this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=2),this.onApply=e=>this._onApplyObjectBased(e)):(this._invViewProjection=o.y3.Identity(),this._previousViewProjection=this._scene.getTransformMatrix().clone(),this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=5),this.onApply=e=>this._onApplyScreenBased(e))}_onApplyObjectBased(e){if(e.setVector2("screenSize",new o.FM(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(XE.VELOCITY_TEXTURE_TYPE);e.setTexture("velocitySampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){const t=this._prePassRenderer.getIndex(2);e.setTexture("velocitySampler",this._prePassRenderer.getRenderTarget().textures[t])}}_onApplyScreenBased(e){const t=o.jp.Matrix[0];if(t.copyFrom(this._scene.getTransformMatrix()),t.invertToRef(this._invViewProjection),e.setMatrix("inverseViewProjection",this._invViewProjection),e.setMatrix("prevViewProjection",this._previousViewProjection),this._previousViewProjection.copyFrom(t),e.setMatrix("projection",this._scene.getProjectionMatrix()),e.setVector2("screenSize",new o.FM(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){const t=this._geometryBufferRenderer.getTextureIndex(XE.DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){const t=this._prePassRenderer.getIndex(5);e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[t])}}_updateEffect(){if(this._geometryBufferRenderer||this._prePassRenderer){const e=["#define GEOMETRY_SUPPORTED","#define SAMPLES "+this._motionBlurSamples.toFixed(1),this._isObjectBased?"#define OBJECT_BASED":"#define SCREEN_BASED"];this.updateEffect(e.join("\n"))}}static _Parse(e,t,i,n){return E.p4.Parse((()=>new $E(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1)),e,i,n)}}(0,oe.gn)([(0,E.qC)()],$E.prototype,"motionStrength",void 0),(0,oe.gn)([(0,E.qC)()],$E.prototype,"motionBlurSamples",null),(0,oe.gn)([(0,E.qC)()],$E.prototype,"isObjectBased",null),(0,l.H)("BABYLON.MotionBlurPostProcess",$E);const QE="refractionPixelShader",ZE="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}";Ht.v.ShadersStore[QE]=ZE;class JE extends Zt{get refractionTexture(){return this._refTexture}set refractionTexture(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1}getClassName(){return"RefractionPostProcess"}constructor(e,t,i,n,s,r,o,a,l,h){super(e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],r,o,a,l,h),this._ownRefractionTexture=!0,this.color=i,this.depth=n,this.colorLevel=s,this.refractionTextureUrl=t,this.onActivateObservable.add((e=>{this._refTexture=this._refTexture||new Le(t,e.getScene())})),this.onApplyObservable.add((e=>{e.setColor3("baseColor",this.color),e.setFloat("depth",this.depth),e.setFloat("colorLevel",this.colorLevel),e.setTexture("refractionSampler",this._refTexture)}))}dispose(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),super.dispose(e)}static _Parse(e,t,i,n){return E.p4.Parse((()=>new JE(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable)),e,i,n)}}(0,oe.gn)([(0,E.qC)()],JE.prototype,"color",void 0),(0,oe.gn)([(0,E.qC)()],JE.prototype,"depth",void 0),(0,oe.gn)([(0,E.qC)()],JE.prototype,"colorLevel",void 0),(0,oe.gn)([(0,E.qC)()],JE.prototype,"refractionTextureUrl",void 0),(0,l.H)("BABYLON.RefractionPostProcess",JE);const ex="sharpenPixelShader",tx="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}";Ht.v.ShadersStore[ex]=tx;class ix extends Zt{getClassName(){return"SharpenPostProcess"}constructor(e,t,i,n,s,r,o=0,a=!1){super(e,"sharpen",["sharpnessAmounts","screenSize"],null,t,i,n,s,r,null,o,void 0,null,a),this.colorAmount=1,this.edgeAmount=.3,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setFloat2("sharpnessAmounts",this.edgeAmount,this.colorAmount)}}static _Parse(e,t,i,n){return E.p4.Parse((()=>new ix(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,n)}}(0,oe.gn)([(0,E.qC)()],ix.prototype,"colorAmount",void 0),(0,oe.gn)([(0,E.qC)()],ix.prototype,"edgeAmount",void 0),(0,l.H)("BABYLON.SharpenPostProcess",ix);class nx{get name(){return this._name}get cameras(){return this._cameras}constructor(e,t){this._engine=e,this._name=t,this._renderEffects={},this._renderEffectsForIsolatedPass=new Array,this._cameras=[]}getClassName(){return"PostProcessRenderPipeline"}get isSupported(){for(const e in this._renderEffects)if(Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&!this._renderEffects[e].isSupported)return!1;return!0}addEffect(e){this._renderEffects[e._name]=e}_rebuild(){}_enableEffect(e,t){const i=this._renderEffects[e];i&&i._enable(se.w1.MakeArray(t||this._cameras))}_disableEffect(e,t){const i=this._renderEffects[e];i&&i._disable(se.w1.MakeArray(t||this._cameras))}_attachCameras(e,t){const i=se.w1.MakeArray(e||this._cameras);if(!i)return;const n=[];let s;for(s=0;s0){const i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0}setPrePassRenderer(e){return!1}dispose(){}}(0,oe.gn)([(0,E.qC)()],nx.prototype,"_name",void 0);class sx{constructor(){this._renderPipelines={}}get supportedPipelines(){const e=[];for(const t in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,t)){const i=this._renderPipelines[t];i.isSupported&&e.push(i)}return e}addPipeline(e){this._renderPipelines[e._name]=e}removePipeline(e){delete this._renderPipelines[e]}attachCamerasToRenderPipeline(e,t,i=!1){const n=this._renderPipelines[e];n&&n._attachCameras(t,i)}detachCamerasFromRenderPipeline(e,t){const i=this._renderPipelines[e];i&&i._detachCameras(t)}enableEffectInPipeline(e,t,i){const n=this._renderPipelines[e];n&&n._enableEffect(t,i)}disableEffectInPipeline(e,t,i){const n=this._renderPipelines[e];n&&n._disableEffect(t,i)}update(){for(const e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){const t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}}_rebuild(){for(const e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){this._renderPipelines[e]._rebuild()}}dispose(){for(const e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){this._renderPipelines[e].dispose()}}}Object.defineProperty(N.x.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let e=this._getComponent(Se.l.NAME_POSTPROCESSRENDERPIPELINEMANAGER);e||(e=new rx(this),this._addComponent(e)),this._postProcessRenderPipelineManager=new sx}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});class rx{constructor(e){this.name=Se.l.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(Se.l.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER,this,this._gatherRenderTargets)}rebuild(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager._rebuild()}dispose(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.dispose()}_gatherRenderTargets(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.update()}}class ox extends nx{get automaticBuild(){return this._buildAllowed}set automaticBuild(e){this._buildAllowed=e}get scene(){return this._scene}set sharpenEnabled(e){this._sharpenEnabled!==e&&(this._sharpenEnabled=e,this._buildPipeline())}get sharpenEnabled(){return this._sharpenEnabled}get bloomKernel(){return this._bloomKernel}set bloomKernel(e){this._bloomKernel=e,this.bloom.kernel=e/this._hardwareScaleLevel}set bloomWeight(e){this._bloomWeight!==e&&(this.bloom.weight=e,this._bloomWeight=e)}get bloomWeight(){return this._bloomWeight}set bloomThreshold(e){this._bloomThreshold!==e&&(this.bloom.threshold=e,this._bloomThreshold=e)}get bloomThreshold(){return this._bloomThreshold}set bloomScale(e){this._bloomScale!==e&&(this._bloomScale=e,this._rebuildBloom(),this._buildPipeline())}get bloomScale(){return this._bloomScale}set bloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get bloomEnabled(){return this._bloomEnabled}_rebuildBloom(){const e=this.bloom;this.bloom=new JS(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(let t=0;tthis.sharpen),!0),this.depthOfField=new gE(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!0),this._hardwareScaleLevel=a.getHardwareScalingLevel(),this._resizeObserver=a.onResizeObservable.add((()=>{this._hardwareScaleLevel=a.getHardwareScalingLevel(),this.bloomKernel=this._bloomKernel})),this.bloom=new JS(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new iE("ChromaticAberration",a.getRenderWidth(),a.getRenderHeight(),1,null,Le.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new YS(a,this.ChromaticAberrationPostProcessId,(()=>this.chromaticAberration),!0),this.grain=new OE("Grain",1,null,Le.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new YS(a,this.GrainPostProcessId,(()=>this.grain),!0),this._imageProcessingConfigurationObserver=this._scene.imageProcessingConfiguration.onUpdateParameters.add((()=>{this.bloom._downscale._exposure=this._scene.imageProcessingConfiguration.exposure,this.imageProcessingEnabled!==this._scene.imageProcessingConfiguration.isEnabled&&(this._imageProcessingEnabled=this._scene.imageProcessingConfiguration.isEnabled,se.w1.SetImmediate((()=>{this._buildPipeline()})))})),this._buildPipeline()}getClassName(){return"DefaultRenderingPipeline"}prepare(){const e=this._buildAllowed;this._buildAllowed=!0,this._buildPipeline(),this._buildAllowed=e}_setAutoClearAndTextureSharing(e,t=!1){this._hasCleared?e.autoClear=!1:(e.autoClear=!0,this._scene.autoClear=!1,this._hasCleared=!0),t||(this._prevPrevPostProcess?e.shareOutputWith(this._prevPrevPostProcess):e.useOwnOutput(),this._prevPostProcess&&(this._prevPrevPostProcess=this._prevPostProcess),this._prevPostProcess=e)}_buildPipeline(){if(!this._buildAllowed)return;this._scene.autoClear=!0;const e=this._scene.getEngine();if(this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._prevPostProcess=null,this._prevPrevPostProcess=null,this._hasCleared=!1,this.depthOfFieldEnabled){if(this._cameras.length>1){for(const e of this._cameras){this._scene.enableDepthRenderer(e).useOnlyInActiveCamera=!0}this._depthOfFieldSceneObserver=this._scene.onAfterRenderTargetsRenderObservable.add((e=>{this._cameras.indexOf(e.activeCamera)>-1&&(this.depthOfField.depthTexture=e.enableDepthRenderer(e.activeCamera).getDepthMap())}))}else{this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);const e=this._scene.enableDepthRenderer(this._cameras[0]);this.depthOfField.depthTexture=e.getDepthMap()}this.depthOfField._isReady()||this.depthOfField._updateEffects(),this.addEffect(this.depthOfField),this._setAutoClearAndTextureSharing(this.depthOfField._effects[0],!0)}else this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);this.bloomEnabled&&(this.bloom._isReady()||this.bloom._updateEffects(),this.addEffect(this.bloom),this._setAutoClearAndTextureSharing(this.bloom._effects[0],!0)),this._imageProcessingEnabled&&(this.imageProcessing=new Ta("imageProcessing",1,null,Le.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new YS(e,this.ImageProcessingPostProcessId,(()=>this.imageProcessing),!0)),this._setAutoClearAndTextureSharing(this.imageProcessing)):this._scene.imageProcessingConfiguration.applyByPostProcess=!1,this._cameras&&0!==this._cameras.length||(this._scene.imageProcessingConfiguration.applyByPostProcess=!1),this.imageProcessing.getEffect()||this.imageProcessing._updateParameters()),this.sharpenEnabled&&(this.sharpen.isReady()||this.sharpen.updateEffect(),this.addEffect(this._sharpenEffect),this._setAutoClearAndTextureSharing(this.sharpen)),this.grainEnabled&&(this.grain.isReady()||this.grain.updateEffect(),this.addEffect(this._grainEffect),this._setAutoClearAndTextureSharing(this.grain)),this.chromaticAberrationEnabled&&(this.chromaticAberration.isReady()||this.chromaticAberration.updateEffect(),this.addEffect(this._chromaticAberrationEffect),this._setAutoClearAndTextureSharing(this.chromaticAberration)),this.fxaaEnabled&&(this.fxaa=new PE("fxaa",1,null,Le.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new YS(e,this.FxaaPostProcessId,(()=>this.fxaa),!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),(this._scene.activeCameras&&this._scene.activeCameras.length>1||this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera))&&(this._scene.autoClear=!0),this._activeCameraChangedObserver||(this._activeCameraChangedObserver=this._scene.onActiveCameraChanged.add((()=>{this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera)&&(this._scene.autoClear=!0)}))),this._activeCamerasChangedObserver||(this._activeCamerasChangedObserver=this._scene.onActiveCamerasChanged.add((()=>{this._scene.activeCameras&&this._scene.activeCameras.length>1&&(this._scene.autoClear=!0)}))),!this._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&p.Y.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"),this.onBuildObservable.notifyObservers(this)}_disposePostProcesses(e=!1){for(let t=0;tnew ox(e._name,e._name._hdr,t)),e,t,i)}}(0,oe.gn)([(0,E.qC)()],ox.prototype,"sharpenEnabled",null),(0,oe.gn)([(0,E.qC)()],ox.prototype,"bloomKernel",null),(0,oe.gn)([(0,E.qC)()],ox.prototype,"_bloomWeight",void 0),(0,oe.gn)([(0,E.qC)()],ox.prototype,"_bloomThreshold",void 0),(0,oe.gn)([(0,E.qC)()],ox.prototype,"_hdr",void 0),(0,oe.gn)([(0,E.qC)()],ox.prototype,"bloomWeight",null),(0,oe.gn)([(0,E.qC)()],ox.prototype,"bloomThreshold",null),(0,oe.gn)([(0,E.qC)()],ox.prototype,"bloomScale",null),(0,oe.gn)([(0,E.qC)()],ox.prototype,"bloomEnabled",null),(0,oe.gn)([(0,E.qC)()],ox.prototype,"depthOfFieldEnabled",null),(0,oe.gn)([(0,E.qC)()],ox.prototype,"depthOfFieldBlurLevel",null),(0,oe.gn)([(0,E.qC)()],ox.prototype,"fxaaEnabled",null),(0,oe.gn)([(0,E.qC)()],ox.prototype,"samples",null),(0,oe.gn)([(0,E.qC)()],ox.prototype,"imageProcessingEnabled",null),(0,oe.gn)([(0,E.qC)()],ox.prototype,"glowLayerEnabled",null),(0,oe.gn)([(0,E.qC)()],ox.prototype,"chromaticAberrationEnabled",null),(0,oe.gn)([(0,E.qC)()],ox.prototype,"grainEnabled",null),(0,l.H)("BABYLON.DefaultRenderingPipeline",ox);const ax="lensHighlightsPixelShader",lx="uniform sampler2D textureSampler; \nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\nvarying vec2 vUV;\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\nif (gain==-1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n}";Ht.v.ShadersStore[ax]=lx;const hx="depthOfFieldPixelShader",cx="uniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\nuniform float near;\nuniform float far;\nvarying vec2 vUV;\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion==0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\nfloat sampleScreen(inout vec4 color,in vec2 offset,in float weight) {\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\nreturn col;\n}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\n{\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\nif (dof_enabled==false || coc<0.07) { coc=0.0; }\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\nfloat blur_amount=max(edge_blur_amount,coc);\nif (blur_amount==0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\ngl_FragColor=getBlurColor(blur_amount*1.7);\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n";Ht.v.ShadersStore[hx]=cx;class dx{constructor(){this.enabled=!1,this.name="ssao2",this.texturesRequired=[6,5]}}const ux="ssao2PixelShader",px="precision highp float;\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\nuniform float near;\nuniform float radius;\nuniform sampler2D depthSampler;\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform mat3 depthProjection;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=textureLod(randomSampler,vUV*randTextureTiles,0.0).rgb;\nfloat depth=textureLod(depthSampler,vUV,0.0).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=textureLod(normalSampler,vUV,0.0).rgb;\nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 vDepthFactor=depthProjection*vec3(1.0,1.0,depth);\nvec3 origin=vViewRay*vDepthFactor;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i1.0 || offset.y>1.0) {\ncontinue;\n}\nfloat sampleDepth=abs(textureLod(depthSampler,offset.xy,0.0).r);\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=step(EPSILON,difference)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BLUR\nuniform float outSize;\nuniform float soften;\nuniform float tolerance;\nuniform int samples;\n#ifndef BLUR_BYPASS\nuniform sampler2D depthSampler;\n#ifdef BLUR_LEGACY\n#define inline\nfloat blur13Bilateral(sampler2D image,vec2 uv,vec2 step) {\nfloat result=0.0;\nvec2 off1=vec2(1.411764705882353)*step;\nvec2 off2=vec2(3.2941176470588234)*step;\nvec2 off3=vec2(5.176470588235294)*step;\nfloat compareDepth=abs(textureLod(depthSampler,uv,0.0).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\nresult+=textureLod(image,uv,0.0).r*30.0;\nsampleDepth=abs(textureLod(depthSampler,uv+off1,0.0).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+= weight;\nresult+=textureLod(image,uv+off1,0.0).r*weight;\nsampleDepth=abs(textureLod(depthSampler,uv-off1,0.0).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+= weight;\nresult+=textureLod(image,uv-off1,0.0).r*weight;\nsampleDepth=abs(textureLod(depthSampler,uv+off2,0.0).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\nresult+=textureLod(image,uv+off2,0.0).r*weight;\nsampleDepth=abs(textureLod(depthSampler,uv-off2,0.0).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\nresult+=textureLod(image,uv-off2,0.0).r*weight;\nsampleDepth=abs(textureLod(depthSampler,uv+off3,0.0).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\nresult+=textureLod(image,uv+off3,0.0).r*weight;\nsampleDepth=abs(textureLod(depthSampler,uv-off3,0.0).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\nresult+=textureLod(image,uv-off3,0.0).r*weight;\nreturn result/weightSum;\n}\n#endif\n#endif\nvoid main()\n{\nfloat result=0.0;\n#ifdef BLUR_BYPASS\nresult=textureLod(textureSampler,vUV,0.0).r;\n#else\n#ifdef BLUR_H\nvec2 step=vec2(1.0/outSize,0.0);\n#else\nvec2 step=vec2(0.0,1.0/outSize);\n#endif\n#ifdef BLUR_LEGACY\nresult=blur13Bilateral(textureSampler,vUV,step);\n#else\nfloat compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);\nfloat weightSum=0.0;\nfor (int i=-samples; ithis._originalColorPostProcess),!0)),this.addEffect(new YS(t.getEngine(),this.SSAORenderEffect,(()=>this._ssaoPostProcess),!0)),this.addEffect(new YS(t.getEngine(),this.SSAOBlurHRenderEffect,(()=>this._blurHPostProcess),!0)),this.addEffect(new YS(t.getEngine(),this.SSAOBlurVRenderEffect,(()=>this._blurVPostProcess),!0)),this.addEffect(new YS(t.getEngine(),this.SSAOCombineRenderEffect,(()=>this._ssaoCombinePostProcess),!0)),t.postProcessRenderPipelineManager.addPipeline(this),n&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,n)}getClassName(){return"SSAO2RenderingPipeline"}dispose(e=!1){for(let t=0;t{if(!this._scene.activeCamera)return;const t=r?this._ssaoCombinePostProcess.width:this._ssaoCombinePostProcess.height,i=r?this._originalColorPostProcess.width:this._originalColorPostProcess.height;e.setFloat("outSize",t>0?t:i),e.setInt("samples",this.bilateralSamples),e.setFloat("soften",this.bilateralSoften),e.setFloat("tolerance",this.bilateralTolerance),this._geometryBufferRenderer?e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]):this._prePassRenderer&&e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)])},o.samples=this.textureSamples,o}_radicalInverse_VdC(e){return this._bits[0]=e,this._bits[0]=(this._bits[0]<<16|this._bits[0]>>16)>>>0,this._bits[0]=(1431655765&this._bits[0])<<1|(2863311530&this._bits[0])>>>1>>>0,this._bits[0]=(858993459&this._bits[0])<<2|(3435973836&this._bits[0])>>>2>>>0,this._bits[0]=(252645135&this._bits[0])<<4|(4042322160&this._bits[0])>>>4>>>0,this._bits[0]=(16711935&this._bits[0])<<8|(4278255360&this._bits[0])>>>8>>>0,2.3283064365386963e-10*this._bits[0]}_hammersley(e,t){return[e/t,this._radicalInverse_VdC(e)]}_hemisphereSample_uniform(e,t){const i=2*t*Math.PI,n=1-.85*e,s=Math.sqrt(1-n*n);return new o.P(Math.cos(i)*s,Math.sin(i)*s,n)}_generateHemisphere(){const e=this.samples,t=[];let i,n=0;for(;n{var t,i,n,s;if(this._scene.activeCamera){if(e.setArray3("sampleSphere",this._sampleSphere),e.setFloat("randTextureTiles",32),e.setFloat("samplesFactor",1/this.samples),e.setFloat("totalStrength",this.totalStrength),e.setFloat2("texelSize",1/this._ssaoPostProcess.width,1/this._ssaoPostProcess.height),e.setFloat("radius",this.radius),e.setFloat("maxZ",this.maxZ),e.setFloat("minZAspect",this.minZAspect),e.setFloat("base",this.base),e.setFloat("near",this._scene.activeCamera.minZ),this._scene.activeCamera.mode===ce.V.PERSPECTIVE_CAMERA)e.setMatrix3x3("depthProjection",mx.PERSPECTIVE_DEPTH_PROJECTION),e.setFloat("xViewport",Math.tan(this._scene.activeCamera.fov/2)*this._scene.getEngine().getAspectRatio(this._scene.activeCamera,!0)),e.setFloat("yViewport",Math.tan(this._scene.activeCamera.fov/2));else{const r=this._scene.getEngine().getRenderWidth()/2,o=this._scene.getEngine().getRenderHeight()/2,a=null!==(t=this._scene.activeCamera.orthoLeft)&&void 0!==t?t:-r,l=null!==(i=this._scene.activeCamera.orthoRight)&&void 0!==i?i:r,h=null!==(n=this._scene.activeCamera.orthoBottom)&&void 0!==n?n:-o,c=null!==(s=this._scene.activeCamera.orthoTop)&&void 0!==s?s:o;e.setMatrix3x3("depthProjection",mx.ORTHO_DEPTH_PROJECTION),e.setFloat("xViewport",.5*(l-a)),e.setFloat("yViewport",.5*(c-h))}e.setMatrix("projection",this._scene.getProjectionMatrix()),this._geometryBufferRenderer?(e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]),e.setTexture("normalSampler",this._geometryBufferRenderer.getGBuffer().textures[1])):this._prePassRenderer&&(e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]),e.setTexture("normalSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)])),e.setTexture("randomSampler",this._randomTexture)}},this._ssaoPostProcess.samples=this.textureSamples,this._forceGeometryBuffer||(this._ssaoPostProcess._prePassEffectConfiguration=new dx)}_createSSAOCombinePostProcess(e,t){this._ssaoCombinePostProcess=new Zt("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,Le.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t),this._ssaoCombinePostProcess.onApply=e=>{const t=this._scene.activeCamera.viewport;e.setVector4("viewport",o.jp.Vector4[0].copyFromFloats(t.x,t.y,t.width,t.height)),e.setTextureFromPostProcessOutput("originalColor",this._originalColorPostProcess)},this._ssaoCombinePostProcess.samples=this.textureSamples}_createRandomTexture(){this._randomTexture=new ma("SSAORandomTexture",128,this._scene,!1,Le.BILINEAR_SAMPLINGMODE),this._randomTexture.wrapU=Le.WRAP_ADDRESSMODE,this._randomTexture.wrapV=Le.WRAP_ADDRESSMODE;const e=this._randomTexture.getContext(),t=(e,t)=>Math.random()*(t-e)+e,i=o.P.Zero();for(let n=0;n<128;n++)for(let s=0;s<128;s++)i.x=t(0,1),i.y=t(0,1),i.z=0,i.normalize(),i.scaleInPlace(255),i.x=Math.floor(i.x),i.y=Math.floor(i.y),e.fillStyle="rgb("+i.x+", "+i.y+", "+i.z+")",e.fillRect(n,s,1,1);this._randomTexture.update(!1)}serialize(){const e=E.p4.Serialize(this);return e.customType="SSAO2RenderingPipeline",e}static Parse(e,t,i){return E.p4.Parse((()=>new mx(e._name,t,e._ratio,void 0,e._forceGeometryBuffer,e._textureType)),e,t,i)}}mx.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1],mx.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1],(0,oe.gn)([(0,E.qC)()],mx.prototype,"totalStrength",void 0),(0,oe.gn)([(0,E.qC)()],mx.prototype,"maxZ",void 0),(0,oe.gn)([(0,E.qC)()],mx.prototype,"minZAspect",void 0),(0,oe.gn)([(0,E.qC)("epsilon")],mx.prototype,"_epsilon",void 0),(0,oe.gn)([(0,E.qC)("samples")],mx.prototype,"_samples",void 0),(0,oe.gn)([(0,E.qC)("textureSamples")],mx.prototype,"_textureSamples",void 0),(0,oe.gn)([(0,E.qC)()],mx.prototype,"_forceGeometryBuffer",void 0),(0,oe.gn)([(0,E.qC)()],mx.prototype,"_ratio",void 0),(0,oe.gn)([(0,E.qC)()],mx.prototype,"_textureType",void 0),(0,oe.gn)([(0,E.qC)()],mx.prototype,"radius",void 0),(0,oe.gn)([(0,E.qC)()],mx.prototype,"base",void 0),(0,oe.gn)([(0,E.qC)("bypassBlur")],mx.prototype,"_bypassBlur",void 0),(0,oe.gn)([(0,E.qC)("expensiveBlur")],mx.prototype,"_expensiveBlur",void 0),(0,oe.gn)([(0,E.qC)()],mx.prototype,"bilateralSamples",void 0),(0,oe.gn)([(0,E.qC)()],mx.prototype,"bilateralSoften",void 0),(0,oe.gn)([(0,E.qC)()],mx.prototype,"bilateralTolerance",void 0),(0,l.H)("BABYLON.SSAO2RenderingPipeline",mx);const gx="ssaoPixelShader",vx="uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; ithis._originalColorPostProcess),!0)),this.addEffect(new YS(t.getEngine(),this.SSAORenderEffect,(()=>this._ssaoPostProcess),!0)),this.addEffect(new YS(t.getEngine(),this.SSAOBlurHRenderEffect,(()=>this._blurHPostProcess),!0)),this.addEffect(new YS(t.getEngine(),this.SSAOBlurVRenderEffect,(()=>this._blurVPostProcess),!0)),this.addEffect(new YS(t.getEngine(),this.SSAOCombineRenderEffect,(()=>this._ssaoCombinePostProcess),!0)),t.postProcessRenderPipelineManager.addPipeline(this),n&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,n)}_attachCameras(e,t){super._attachCameras(e,t);for(const i of this._cameras)this._scene.enableDepthRenderer(i).getDepthMap()}getClassName(){return"SSAORenderingPipeline"}dispose(e=!1){for(let t=0;t{const e=this._blurHPostProcess.width/this._scene.getEngine().getRenderWidth();this._blurHPostProcess.kernel=16*e})),this._blurVPostProcess.onActivateObservable.add((()=>{const e=this._blurVPostProcess.height/this._scene.getEngine().getRenderHeight();this._blurVPostProcess.kernel=16*e}))}_rebuild(){this._firstUpdate=!0,super._rebuild()}_createSSAOPostProcess(e){const t=[.5381,.1856,-.4319,.1379,.2486,.443,.3371,.5679,-.0057,-.6999,-.0451,-.0019,.0689,-.1598,-.8547,.056,.0069,-.1843,-.0146,.1402,.0762,.01,-.1924,-.0344,-.3577,-.5301,-.4358,-.3169,.1063,.0158,.0103,-.5869,.0046,-.0897,-.494,.3287,.7119,-.0154,-.0918,-.0533,.0596,-.5411,.0352,-.0631,.546,-.4776,.2847,-.0271];this._ssaoPostProcess=new Zt("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,Le.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,"#define SAMPLES 16\n#define SSAO"),this._ssaoPostProcess.externalTextureSamplerBinding=!0,this._ssaoPostProcess.onApply=e=>{this._firstUpdate&&(e.setArray3("sampleSphere",t),e.setFloat("samplesFactor",.0625),e.setFloat("randTextureTiles",4)),e.setFloat("totalStrength",this.totalStrength),e.setFloat("radius",this.radius),e.setFloat("area",this.area),e.setFloat("fallOff",this.fallOff),e.setFloat("base",this.base),e.setTexture("textureSampler",this._scene.enableDepthRenderer(this._scene.activeCamera).getDepthMap()),e.setTexture("randomSampler",this._randomTexture)}}_createSSAOCombinePostProcess(e){this._ssaoCombinePostProcess=new Zt("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,Le.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=e=>{e.setVector4("viewport",o.jp.Vector4[0].copyFromFloats(0,0,1,1)),e.setTextureFromPostProcess("originalColor",this._originalColorPostProcess)}}_createRandomTexture(){this._randomTexture=new ma("SSAORandomTexture",512,this._scene,!1,Le.TRILINEAR_SAMPLINGMODE),this._randomTexture.wrapU=Le.WRAP_ADDRESSMODE,this._randomTexture.wrapV=Le.WRAP_ADDRESSMODE;const e=this._randomTexture.getContext(),t=(e,t)=>Math.random()*(t-e)+e,i=o.P.Zero();for(let n=0;n<512;n++)for(let s=0;s<512;s++)i.x=Math.floor(255*Math.max(0,t(-1,1))),i.y=Math.floor(255*Math.max(0,t(-1,1))),i.z=Math.floor(255*Math.max(0,t(-1,1))),e.fillStyle="rgb("+i.x+", "+i.y+", "+i.z+")",e.fillRect(n,s,1,1);this._randomTexture.update(!1)}}(0,oe.gn)([(0,E.qC)()],Tx.prototype,"totalStrength",void 0),(0,oe.gn)([(0,E.qC)()],Tx.prototype,"radius",void 0),(0,oe.gn)([(0,E.qC)()],Tx.prototype,"area",void 0),(0,oe.gn)([(0,E.qC)()],Tx.prototype,"fallOff",void 0),(0,oe.gn)([(0,E.qC)()],Tx.prototype,"base",void 0);class Sx{constructor(){this.enabled=!1,this.name="screenSpaceReflections",this.texturesRequired=[6,3,1]}}const Ex="screenSpaceReflectionPixelShader",xx="uniform sampler2D textureSampler;\n#ifdef SSR_SUPPORTED\nuniform sampler2D reflectivitySampler;\nuniform sampler2D normalSampler;\nuniform sampler2D positionSampler;\n#endif\nuniform mat4 view;\nuniform mat4 projection;\nuniform float stepSize;\nuniform float strength;\nuniform float threshold;\nuniform float roughnessFactor;\nuniform float reflectionSpecularFalloffExponent;\nvarying vec2 vUV;\n#ifdef SSR_SUPPORTED\nstruct ReflectionInfo {\nvec3 color;\nvec4 coords;\n};\n/**\n* According to specular,see https:\n*/\nvec3 fresnelSchlick(float cosTheta,vec3 F0)\n{\nreturn F0+(1.0-F0)*pow(1.0-cosTheta,5.0);\n}\n/**\n* Once the pixel's coordinates has been found,let's adjust (smooth) a little bit\n* by sampling multiple reflection pixels.\n*/\nReflectionInfo smoothReflectionInfo(vec3 dir,vec3 hitCoord)\n{\nReflectionInfo info;\ninfo.color=vec3(0.0);\nvec4 projectedCoord;\nfloat sampledDepth;\nfor(int i=0; i0.0)\nhitCoord-=dir;\nelse\nhitCoord+=dir;\ninfo.color+=texture2D(textureSampler,projectedCoord.xy).rgb;\n}\nprojectedCoord=projection*vec4(hitCoord,1.0);\nprojectedCoord.xy/=projectedCoord.w;\nprojectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);\ninfo.coords=vec4(projectedCoord.xy,sampledDepth,1.0);\ninfo.color+=texture2D(textureSampler,projectedCoord.xy).rgb;\ninfo.color/=float(SMOOTH_STEPS+1);\nreturn info;\n}\n/**\n* Tests the given world position (hitCoord) according to the given reflection vector (dir)\n* until it finds a collision (means that depth is enough close to say \"it's the pixel to sample!\").\n*/\nReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord)\n{\nReflectionInfo info;\nvec4 projectedCoord;\nfloat sampledDepth;\ndir*=stepSize;\nfor(int i=0; i{const i=this._geometryBufferRenderer,n=this._prePassRenderer;if(!n&&!i)return;if(i){const t=i.getTextureIndex(XE.POSITION_TEXTURE_TYPE),n=i.getTextureIndex(XE.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",i.getGBuffer().textures[1]),e.setTexture("positionSampler",i.getGBuffer().textures[t]),e.setTexture("reflectivitySampler",i.getGBuffer().textures[n])}else if(n){const t=n.getIndex(1),i=n.getIndex(3),s=n.getIndex(6);e.setTexture("normalSampler",n.getRenderTarget().textures[s]),e.setTexture("positionSampler",n.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",n.getRenderTarget().textures[i])}const s=t.activeCamera;if(!s)return;const r=s.getViewMatrix(!0),o=s.getProjectionMatrix(!0);e.setMatrix("projection",o),e.setMatrix("view",r),e.setFloat("threshold",this.threshold),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("roughnessFactor",this.roughnessFactor)},this._isSceneRightHanded=t.useRightHandedSystem}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get reflectionSamples(){return this._reflectionSamples}set reflectionSamples(e){e!==this._reflectionSamples&&(this._reflectionSamples=e,this._updateEffectDefines())}get smoothSteps(){return this._smoothSteps}set smoothSteps(e){e!==this._smoothSteps&&(this._smoothSteps=e,this._updateEffectDefines())}_updateEffectDefines(){const e=[];(this._geometryBufferRenderer||this._prePassRenderer)&&e.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&e.push("#define ENABLE_SMOOTH_REFLECTIONS"),this._isSceneRightHanded&&e.push("#define RIGHT_HANDED_SCENE"),e.push("#define REFLECTION_SAMPLES "+(this._reflectionSamples>>0)),e.push("#define SMOOTH_STEPS "+(this._smoothSteps>>0)),this.updateEffect(e.join("\n"))}static _Parse(e,t,i,n){return E.p4.Parse((()=>new bx(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,n)}}(0,oe.gn)([(0,E.qC)()],bx.prototype,"threshold",void 0),(0,oe.gn)([(0,E.qC)()],bx.prototype,"strength",void 0),(0,oe.gn)([(0,E.qC)()],bx.prototype,"reflectionSpecularFalloffExponent",void 0),(0,oe.gn)([(0,E.qC)()],bx.prototype,"step",void 0),(0,oe.gn)([(0,E.qC)()],bx.prototype,"roughnessFactor",void 0),(0,oe.gn)([(0,E.qC)()],bx.prototype,"enableSmoothReflections",null),(0,oe.gn)([(0,E.qC)()],bx.prototype,"reflectionSamples",null),(0,oe.gn)([(0,E.qC)()],bx.prototype,"smoothSteps",null),(0,l.H)("BABYLON.ScreenSpaceReflectionPostProcess",bx);const Cx="standardPixelShader",yx="uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminanceshadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\n#include\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\n#ifndef AUTO_EXPOSURE\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\n#endif\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n";Ht.v.ShadersStore[Cx]=yx;class Ax extends nx{get exposure(){return this._fixedExposure}set exposure(e){this._fixedExposure=e,this._currentExposure=e}get hdrAutoExposure(){return this._hdrAutoExposure}set hdrAutoExposure(e){if(this._hdrAutoExposure=e,this.hdrPostProcess){const t=["#define HDR"];e&&t.push("#define AUTO_EXPOSURE"),this.hdrPostProcess.updateEffect(t.join("\n"))}}get motionStrength(){return this._motionStrength}set motionStrength(e){this._motionStrength=e,this._isObjectBasedMotionBlur&&this.motionBlurPostProcess&&(this.motionBlurPostProcess.motionStrength=e)}get objectBasedMotionBlur(){return this._isObjectBasedMotionBlur}set objectBasedMotionBlur(e){const t=this._isObjectBasedMotionBlur!==e;this._isObjectBasedMotionBlur=e,t&&this._buildPipeline()}get BloomEnabled(){return this._bloomEnabled}set BloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get DepthOfFieldEnabled(){return this._depthOfFieldEnabled}set DepthOfFieldEnabled(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())}get LensFlareEnabled(){return this._lensFlareEnabled}set LensFlareEnabled(e){this._lensFlareEnabled!==e&&(this._lensFlareEnabled=e,this._buildPipeline())}get HDREnabled(){return this._hdrEnabled}set HDREnabled(e){this._hdrEnabled!==e&&(this._hdrEnabled=e,this._buildPipeline())}get VLSEnabled(){return this._vlsEnabled}set VLSEnabled(e){if(this._vlsEnabled!==e){if(e){if(!this._scene.enableGeometryBufferRenderer())return void p.Y.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline")}this._vlsEnabled=e,this._buildPipeline()}}get MotionBlurEnabled(){return this._motionBlurEnabled}set MotionBlurEnabled(e){this._motionBlurEnabled!==e&&(this._motionBlurEnabled=e,this._buildPipeline())}get fxaaEnabled(){return this._fxaaEnabled}set fxaaEnabled(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())}get screenSpaceReflectionsEnabled(){return this._screenSpaceReflectionsEnabled}set screenSpaceReflectionsEnabled(e){this._screenSpaceReflectionsEnabled!==e&&(this._screenSpaceReflectionsEnabled=e,this._buildPipeline())}get volumetricLightStepsCount(){return this._volumetricLightStepsCount}set volumetricLightStepsCount(e){this.volumetricLightPostProcess&&this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS "+e.toFixed(1)),this._volumetricLightStepsCount=e}get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this.motionBlurPostProcess&&(this._isObjectBasedMotionBlur?this.motionBlurPostProcess.motionBlurSamples=e:this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+e.toFixed(1))),this._motionBlurSamples=e}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}constructor(e,t,i,n=null,s){super(t.getEngine(),e),this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.blurHPostProcesses=[],this.blurVPostProcesses=[],this.textureAdderPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.luminancePostProcess=null,this.luminanceDownSamplePostProcesses=[],this.hdrPostProcess=null,this.textureAdderFinalPostProcess=null,this.lensFlareFinalPostProcess=null,this.hdrFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.motionBlurPostProcess=null,this.depthOfFieldPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.brightThreshold=1,this.blurWidth=512,this.horizontalBlur=!1,this.lensTexture=null,this.volumetricLightCoefficient=.2,this.volumetricLightPower=4,this.volumetricLightBlurScale=64,this.sourceLight=null,this.hdrMinimumLuminance=1,this.hdrDecreaseRate=.5,this.hdrIncreaseRate=.5,this.lensColorTexture=null,this.lensFlareStrength=20,this.lensFlareGhostDispersal=1.4,this.lensFlareHaloWidth=.7,this.lensFlareDistortionStrength=16,this.lensFlareBlurWidth=512,this.lensStarTexture=null,this.lensFlareDirtTexture=null,this.depthOfFieldDistance=10,this.depthOfFieldBlurWidth=64,this.animations=[],this._currentDepthOfFieldSource=null,this._fixedExposure=1,this._currentExposure=1,this._hdrAutoExposure=!1,this._hdrCurrentLuminance=1,this._motionStrength=1,this._isObjectBasedMotionBlur=!1,this._camerasToBeAttached=[],this._bloomEnabled=!1,this._depthOfFieldEnabled=!1,this._vlsEnabled=!1,this._lensFlareEnabled=!1,this._hdrEnabled=!1,this._motionBlurEnabled=!1,this._fxaaEnabled=!1,this._screenSpaceReflectionsEnabled=!1,this._motionBlurSamples=64,this._volumetricLightStepsCount=50,this._samples=1,this._cameras=s||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._basePostProcess=n,this._ratio=i,this._floatTextureType=t.getEngine().getCaps().textureFloatRender?1:2,t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline()}_buildPipeline(){const e=this._ratio,t=this._scene;this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._screenSpaceReflectionsEnabled&&(this.screenSpaceReflectionPostProcess=new bx("HDRPass",t,e,null,Le.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add((()=>{this._currentDepthOfFieldSource=this.screenSpaceReflectionPostProcess})),this.addEffect(new YS(t.getEngine(),"HDRScreenSpaceReflections",(()=>this.screenSpaceReflectionPostProcess),!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new Zt("HDRPass","standard",[],[],e,null,Le.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",this._floatTextureType),this.originalPostProcess.autoClear=!this.screenSpaceReflectionPostProcess,this.originalPostProcess.onApplyObservable.add((()=>{this._currentDepthOfFieldSource=this.originalPostProcess})),this.addEffect(new YS(t.getEngine(),"HDRPassPostProcess",(()=>this.originalPostProcess),!0)),this._bloomEnabled&&(this._createDownSampleX4PostProcess(t,e/4),this._createBrightPassPostProcess(t,e/4),this._createBlurPostProcesses(t,e/4,1),this._createTextureAdderPostProcess(t,e),this.textureAdderFinalPostProcess=new Zt("HDRDepthOfFieldSource","standard",[],[],e,null,Le.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new YS(t.getEngine(),"HDRBaseDepthOfFieldSource",(()=>this.textureAdderFinalPostProcess),!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(t,e),this.volumetricLightFinalPostProcess=new Zt("HDRVLSFinal","standard",[],[],e,null,Le.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new YS(t.getEngine(),"HDRVLSFinal",(()=>this.volumetricLightFinalPostProcess),!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(t,e),this.lensFlareFinalPostProcess=new Zt("HDRPostLensFlareDepthOfFieldSource","standard",[],[],e,null,Le.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new YS(t.getEngine(),"HDRPostLensFlareDepthOfFieldSource",(()=>this.lensFlareFinalPostProcess),!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(t,this._floatTextureType),this._createHdrPostProcess(t,e),this.hdrFinalPostProcess=new Zt("HDRPostHDReDepthOfFieldSource","standard",[],[],e,null,Le.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new YS(t.getEngine(),"HDRPostHDReDepthOfFieldSource",(()=>this.hdrFinalPostProcess),!0))),this._depthOfFieldEnabled&&(this._createBlurPostProcesses(t,e/2,3,"depthOfFieldBlurWidth"),this._createDepthOfFieldPostProcess(t,e)),this._motionBlurEnabled&&this._createMotionBlurPostProcess(t,e),this._fxaaEnabled&&(this.fxaaPostProcess=new PE("fxaa",1,null,Le.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,0),this.addEffect(new YS(t.getEngine(),"HDRFxaa",(()=>this.fxaaPostProcess),!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&p.Y.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")}_createDownSampleX4PostProcess(e,t){const i=new Array(32);this.downSampleX4PostProcess=new Zt("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=e=>{let t=0;const n=this.downSampleX4PostProcess.width,s=this.downSampleX4PostProcess.height;for(let r=-2;r<2;r++)for(let e=-2;e<2;e++)i[t]=(r+.5)*(1/n),i[t+1]=(e+.5)*(1/s),t+=2;e.setArray2("dsOffsets",i)},this.addEffect(new YS(e.getEngine(),"HDRDownSampleX4",(()=>this.downSampleX4PostProcess),!0))}_createBrightPassPostProcess(e,t){const i=new Array(8);this.brightPassPostProcess=new Zt("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=e=>{const t=1/this.brightPassPostProcess.width,n=1/this.brightPassPostProcess.height;i[0]=-.5*t,i[1]=.5*n,i[2]=.5*t,i[3]=.5*n,i[4]=-.5*t,i[5]=-.5*n,i[6]=.5*t,i[7]=-.5*n,e.setArray2("dsOffsets",i),e.setFloat("brightThreshold",this.brightThreshold)},this.addEffect(new YS(e.getEngine(),"HDRBrightPass",(()=>this.brightPassPostProcess),!0))}_createBlurPostProcesses(e,t,i,n="blurWidth"){const s=e.getEngine(),r=new bp("HDRBlurH_"+i,new o.FM(1,0),this[n],t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),a=new bp("HDRBlurV_"+i,new o.FM(0,1),this[n],t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);r.onActivateObservable.add((()=>{const e=r.width/s.getRenderWidth();r.kernel=this[n]*e})),a.onActivateObservable.add((()=>{const e=a.height/s.getRenderHeight();a.kernel=this.horizontalBlur?64*e:this[n]*e})),this.addEffect(new YS(e.getEngine(),"HDRBlurH"+i,(()=>r),!0)),this.addEffect(new YS(e.getEngine(),"HDRBlurV"+i,(()=>a),!0)),this.blurHPostProcesses.push(r),this.blurVPostProcesses.push(a)}_createTextureAdderPostProcess(e,t){this.textureAdderPostProcess=new Zt("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define TEXTURE_ADDER",this._floatTextureType),this.textureAdderPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._vlsEnabled?this._currentDepthOfFieldSource:this.originalPostProcess),e.setTexture("lensSampler",this.lensTexture),e.setFloat("exposure",this._currentExposure),this._currentDepthOfFieldSource=this.textureAdderFinalPostProcess},this.addEffect(new YS(e.getEngine(),"HDRTextureAdder",(()=>this.textureAdderPostProcess),!0))}_createVolumetricLightPostProcess(e,t){const i=e.enableGeometryBufferRenderer();i.enablePosition=!0;const n=i.getGBuffer();this.volumetricLightPostProcess=new Zt("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLS\n#define NB_STEPS "+this._volumetricLightStepsCount.toFixed(1));const s=o.FM.Zero();this.volumetricLightPostProcess.onApply=e=>{if(this.sourceLight&&this.sourceLight.getShadowGenerator()&&this._scene.activeCamera){const t=this.sourceLight.getShadowGenerator();e.setTexture("shadowMapSampler",t.getShadowMap()),e.setTexture("positionSampler",n.textures[2]),e.setColor3("sunColor",this.sourceLight.diffuse),e.setVector3("sunDirection",this.sourceLight.getShadowDirection()),e.setVector3("cameraPosition",this._scene.activeCamera.globalPosition),e.setMatrix("shadowViewProjection",t.getTransformMatrix()),e.setFloat("scatteringCoefficient",this.volumetricLightCoefficient),e.setFloat("scatteringPower",this.volumetricLightPower),s.x=this.sourceLight.getDepthMinZ(this._scene.activeCamera),s.y=this.sourceLight.getDepthMaxZ(this._scene.activeCamera),e.setVector2("depthValues",s)}},this.addEffect(new YS(e.getEngine(),"HDRVLS",(()=>this.volumetricLightPostProcess),!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new Zt("HDRVLSMerge","standard",[],["originalSampler"],t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLSMERGE"),this.volumetricLightMergePostProces.onApply=e=>{e.setTextureFromPostProcess("originalSampler",this._bloomEnabled?this.textureAdderFinalPostProcess:this.originalPostProcess),this._currentDepthOfFieldSource=this.volumetricLightFinalPostProcess},this.addEffect(new YS(e.getEngine(),"HDRVLSMerge",(()=>this.volumetricLightMergePostProces),!0))}_createLuminancePostProcesses(e,t){let i=Math.pow(3,Ax.LuminanceSteps);this.luminancePostProcess=new Zt("HDRLuminance","standard",["lumOffsets"],[],{width:i,height:i},null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",t);const n=[];this.luminancePostProcess.onApply=e=>{const t=1/this.luminancePostProcess.width,i=1/this.luminancePostProcess.height;n[0]=-.5*t,n[1]=.5*i,n[2]=.5*t,n[3]=.5*i,n[4]=-.5*t,n[5]=-.5*i,n[6]=.5*t,n[7]=-.5*i,e.setArray2("lumOffsets",n)},this.addEffect(new YS(e.getEngine(),"HDRLuminance",(()=>this.luminancePostProcess),!0));for(let r=Ax.LuminanceSteps-1;r>=0;r--){i=Math.pow(3,r);let n="#define LUMINANCE_DOWN_SAMPLE\n";0===r&&(n+="#define FINAL_DOWN_SAMPLER");const s=new Zt("HDRLuminanceDownSample"+r,"standard",["dsOffsets","halfDestPixelSize"],[],{width:i,height:i},null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,n,t);this.luminanceDownSamplePostProcesses.push(s)}let s=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach(((t,i)=>{const n=new Array(18);t.onApply=e=>{if(!s)return;let r=0;for(let t=-1;t<2;t++)for(let e=-1;e<2;e++)n[r]=t/s.width,n[r+1]=e/s.height,r+=2;e.setArray2("dsOffsets",n),e.setFloat("halfDestPixelSize",.5/s.width),s=i===this.luminanceDownSamplePostProcesses.length-1?this.luminancePostProcess:t},i===this.luminanceDownSamplePostProcesses.length-1&&(t.onAfterRender=()=>{const t=e.getEngine().readPixels(0,0,1,1),i=new o.Lt(1/16581375,1/65025,1/255,1);t.then((e=>{const t=new Uint8Array(e.buffer);this._hdrCurrentLuminance=(t[0]*i.x+t[1]*i.y+t[2]*i.z+t[3]*i.w)/100}))}),this.addEffect(new YS(e.getEngine(),"HDRLuminanceDownSample"+i,(()=>t),!0))}))}_createHdrPostProcess(e,t){const i=["#define HDR"];this._hdrAutoExposure&&i.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new Zt("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,i.join("\n"),0);let n=1,s=0,r=0;this.hdrPostProcess.onApply=t=>{if(t.setTextureFromPostProcess("textureAdderSampler",this._currentDepthOfFieldSource),s+=e.getEngine().getDeltaTime(),n<0)n=this._hdrCurrentLuminance;else{const e=(r-s)/1e3;this._hdrCurrentLuminancen-this.hdrIncreaseRate*e?n-=this.hdrIncreaseRate*e:n=this._hdrCurrentLuminance}this.hdrAutoExposure?this._currentExposure=this._fixedExposure/n:(n=S.R.Clamp(n,this.hdrMinimumLuminance,1e20),t.setFloat("averageLuminance",n)),r=s,this._currentDepthOfFieldSource=this.hdrFinalPostProcess},this.addEffect(new YS(e.getEngine(),"HDR",(()=>this.hdrPostProcess),!0))}_createLensFlarePostProcess(e,t){this.lensFlarePostProcess=new Zt("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",0),this.addEffect(new YS(e.getEngine(),"HDRLensFlare",(()=>this.lensFlarePostProcess),!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new Zt("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",0),this.addEffect(new YS(e.getEngine(),"HDRLensFlareCompose",(()=>this.lensFlareComposePostProcess),!0));const i=new o.FM(0,0);this.lensFlarePostProcess.externalTextureSamplerBinding=!0,this.lensFlarePostProcess.onApply=e=>{e.setTextureFromPostProcess("textureSampler",this._bloomEnabled?this.blurHPostProcesses[0]:this.originalPostProcess),e.setTexture("lensColorSampler",this.lensColorTexture),e.setFloat("strength",this.lensFlareStrength),e.setFloat("ghostDispersal",this.lensFlareGhostDispersal),e.setFloat("haloWidth",this.lensFlareHaloWidth),i.x=this.lensFlarePostProcess.width,i.y=this.lensFlarePostProcess.height,e.setVector2("resolution",i),e.setFloat("distortionStrength",this.lensFlareDistortionStrength)};const n=o.y3.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),s=o.y3.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=e=>{if(!this._scene.activeCamera)return;e.setTextureFromPostProcess("otherSampler",this.lensFlarePostProcess),e.setTexture("lensDirtSampler",this.lensFlareDirtTexture),e.setTexture("lensStarSampler",this.lensStarTexture);const t=this._scene.activeCamera.getViewMatrix().getRow(0),i=this._scene.activeCamera.getViewMatrix().getRow(2);let r=o.P.Dot(t.toVector3(),new o.P(1,0,0))+o.P.Dot(i.toVector3(),new o.P(0,0,1));r*=4;const a=o.y3.FromValues(.5*Math.cos(r),-Math.sin(r),0,0,Math.sin(r),.5*Math.cos(r),0,0,0,0,1,0,0,0,0,1),l=s.multiply(a).multiply(n);e.setMatrix("lensStarMatrix",l),this._currentDepthOfFieldSource=this.lensFlareFinalPostProcess}}_createDepthOfFieldPostProcess(e,t){this.depthOfFieldPostProcess=new Zt("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DEPTH_OF_FIELD",0),this.depthOfFieldPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._currentDepthOfFieldSource),e.setTexture("depthSampler",this._getDepthTexture()),e.setFloat("distance",this.depthOfFieldDistance)},this.addEffect(new YS(e.getEngine(),"HDRDepthOfField",(()=>this.depthOfFieldPostProcess),!0))}_createMotionBlurPostProcess(e,t){if(this._isObjectBasedMotionBlur){const i=new $E("HDRMotionBlur",e,t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,0);i.motionStrength=this.motionStrength,i.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=i}else{this.motionBlurPostProcess=new Zt("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,Le.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+this.motionBlurSamples.toFixed(1),0);let i=0,n=o.y3.Identity();const s=o.y3.Identity();let r=o.y3.Identity();const a=o.FM.Zero();this.motionBlurPostProcess.onApply=t=>{r=e.getProjectionMatrix().multiply(e.getViewMatrix()),r.invertToRef(s),t.setMatrix("inverseViewProjection",s),t.setMatrix("prevViewProjection",n),n=r,a.x=this.motionBlurPostProcess.width,a.y=this.motionBlurPostProcess.height,t.setVector2("screenSize",a),i=e.getEngine().getFps()/60,t.setFloat("motionScale",i),t.setFloat("motionStrength",this.motionStrength),t.setTexture("depthSampler",this._getDepthTexture())}}this.addEffect(new YS(e.getEngine(),"HDRMotionBlur",(()=>this.motionBlurPostProcess),!0))}_getDepthTexture(){if(this._scene.getEngine().getCaps().drawBuffersExtension){return this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0]}return this._scene.enableDepthRenderer().getDepthMap()}_disposePostProcesses(){for(let e=0;enew Ax(e._name,t,e._ratio)),e,t,i);return e.sourceLightId&&(n.sourceLight=t.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&E.p4.Parse((()=>n.screenSpaceReflectionPostProcess),e.screenSpaceReflectionPostProcess,t,i),n}}Ax.LuminanceSteps=6,(0,oe.gn)([(0,E.qC)()],Ax.prototype,"brightThreshold",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"blurWidth",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"horizontalBlur",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"exposure",null),(0,oe.gn)([(0,E.oU)("lensTexture")],Ax.prototype,"lensTexture",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"volumetricLightCoefficient",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"volumetricLightPower",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"volumetricLightBlurScale",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"hdrMinimumLuminance",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"hdrDecreaseRate",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"hdrIncreaseRate",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"hdrAutoExposure",null),(0,oe.gn)([(0,E.oU)("lensColorTexture")],Ax.prototype,"lensColorTexture",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"lensFlareStrength",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"lensFlareGhostDispersal",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"lensFlareHaloWidth",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"lensFlareDistortionStrength",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"lensFlareBlurWidth",void 0),(0,oe.gn)([(0,E.oU)("lensStarTexture")],Ax.prototype,"lensStarTexture",void 0),(0,oe.gn)([(0,E.oU)("lensFlareDirtTexture")],Ax.prototype,"lensFlareDirtTexture",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"depthOfFieldDistance",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"depthOfFieldBlurWidth",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"motionStrength",null),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"objectBasedMotionBlur",null),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"_ratio",void 0),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"BloomEnabled",null),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"DepthOfFieldEnabled",null),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"LensFlareEnabled",null),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"HDREnabled",null),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"VLSEnabled",null),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"MotionBlurEnabled",null),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"fxaaEnabled",null),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"screenSpaceReflectionsEnabled",null),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"volumetricLightStepsCount",null),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"motionBlurSamples",null),(0,oe.gn)([(0,E.qC)()],Ax.prototype,"samples",null),(0,l.H)("BABYLON.StandardRenderingPipeline",Ax);class Rx{constructor(){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[6,3,5]}}const Px="screenSpaceRayTrace",Ix="float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); }\n/**\nparam csOrigin Camera-space ray origin,which must be \nwithin the view volume and must have z>0.01 and project within the valid screen rectangle\nparam csDirection Unit length camera-space ray direction\nparam projectToPixelMatrix A projection matrix that maps to **pixel** coordinates \n(**not** [-1,+1] normalized device coordinates).\nparam csZBuffer The camera-space Z buffer\nparam csZBufferSize Dimensions of csZBuffer\nparam csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer\nparam nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value\nfor clipping rays headed towards the camera\nparam stride Step in horizontal or vertical pixels between samples. This is a float\nbecause integer math is slow on GPUs,but should be set to an integer>=1\nparam jitterFraction Number between 0 and 1 for how far to bump the ray in stride units\nto conceal banding artifacts,plus the stride ray offset.\nparam maxSteps Maximum number of iterations. Higher gives better images but may be slow\nparam maxRayTraceDistance Maximum camera-space distance to trace before returning a miss\nparam selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions.\n1 is a reasonable value,depending on the scene you may need to set this value to 2\nparam hitPixel Pixel coordinates of the first intersection with the scene\nparam numIterations number of iterations performed\nparam csHitPoint Camera space location of the ray hit\n*/\n#define inline\nbool traceScreenSpaceRay1(\nvec3 csOrigin,\nvec3 csDirection,\nmat4 projectToPixelMatrix,\nsampler2D csZBuffer,\nvec2 csZBufferSize,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nsampler2D csZBackBuffer,\nfloat csZBackSizeFactor,\n#endif\nfloat csZThickness,\nfloat nearPlaneZ,\nfloat stride,\nfloat jitterFraction,\nfloat maxSteps,\nfloat maxRayTraceDistance,\nfloat selfCollisionNumSkip,\nout vec2 startPixel,\nout vec2 hitPixel,\nout vec3 csHitPoint,\nout float numIterations\n#ifdef SSRAYTRACE_DEBUG\n,out vec3 debugColor\n#endif\n)\n{\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance;\n#else\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)yMax) || (P1.yyMax) ? yMax : yMin))/(P1.y-P0.y);\n}\nif ((P1.x>xMax) || (P1.xxMax) ? xMax : xMin))/(P1.x-P0.x));\n}\nP1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha);\n#endif\nP1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);\nvec2 delta=P1-P0;\nbool permute=false;\nif (abs(delta.x)rayZMax) { \nfloat t=rayZMin; rayZMin=rayZMax; rayZMax=t;\n}\nsceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r;\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;\nhit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax);\n#else\nhit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax);\n#endif\n#else\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;\nhit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0);\n#else\nhit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax);\n#endif\n#endif\n}\npqk-=dPQK;\nstepCount-=1.0;\nif (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {\nhit=false;\n}\n#ifdef SSRAYTRACE_ENABLE_REFINEMENT\nif (stride>1.0 && hit) {\npqk-=dPQK;\nstepCount-=1.0;\nfloat invStride=1.0/stride;\ndPQK*=invStride;\nfloat refinementStepCount=0.0;\nprevZMaxEstimate=pqk.z/pqk.w;\nrayZMax=prevZMaxEstimate;\nsceneZMax=rayZMax+1e7;\nfor (;\nrefinementStepCount<=1.0 ||\n(refinementStepCount<=stride*1.4) &&\n(rayZMaxend) {\ndebugColor=vec3(0,0,1);\n} else if ((stepCount+1.0)>=maxSteps) {\ndebugColor=vec3(1,0,0);\n} else if (sceneZMax==0.0) {\ndebugColor=vec3(1,1,0);\n} else {\ndebugColor=vec3(0,stepCount/maxSteps,0);\n}\n#endif\nreturn hit;\n}\n/**\ntexCoord: in the [0,1] range\ndepth: depth in view space (range [znear,zfar]])\n*/\nvec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {\nvec4 ndc;\nndc.xy=texCoord*2.0-1.0;\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nndc.z=-projection[2].z-projection[3].z/depth;\n#else\nndc.z=projection[2].z+projection[3].z/depth;\n#endif\nndc.w=1.0;\nvec4 eyePos=invProjectionMatrix*ndc;\neyePos.xyz/=eyePos.w;\nreturn eyePos.xyz;\n}\n";Ht.v.IncludesShadersStore[Px]=Ix;const Mx="screenSpaceReflection2PixelShader",Ox="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#define TEXTURECUBEFUNC(s,c,lod) textureLod(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#define TEXTURECUBEFUNC(s,c,bias) textureCube(s,c,bias)\n#endif\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSR_SUPPORTED\nuniform sampler2D reflectivitySampler;\nuniform sampler2D normalSampler;\nuniform sampler2D depthSampler;\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nuniform sampler2D backDepthSampler;\nuniform float backSizeFactor;\n#endif\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nuniform samplerCube envCubeSampler;\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize;\n#endif\n#endif\nuniform mat4 view;\nuniform mat4 invView;\nuniform mat4 projection;\nuniform mat4 invProjectionMatrix;\nuniform mat4 projectionPixel;\nuniform float nearPlaneZ;\nuniform float stepSize;\nuniform float maxSteps;\nuniform float strength;\nuniform float thickness;\nuniform float roughnessFactor;\nuniform float reflectionSpecularFalloffExponent;\nuniform float maxDistance;\nuniform float selfCollisionNumSkip;\nuniform float reflectivityThreshold;\n#include\n#include\n#include\nvec3 hash(vec3 a)\n{\na=fract(a*0.8);\na+=dot(a,a.yxz+19.19);\nreturn fract((a.xxy+a.yxx)*a.zyx);\n}\nfloat computeAttenuationForIntersection(ivec2 hitPixel,vec2 hitUV,vec3 vsRayOrigin,vec3 vsHitPoint,vec3 reflectionVector,float maxRayDistance,float numIterations) {\nfloat attenuation=1.0;\n#ifdef SSR_ATTENUATE_SCREEN_BORDERS\nvec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-hitUV.xy));\nattenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0);\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE\nattenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0);\n#endif\n#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS\nattenuation*=1.0-(numIterations/maxSteps);\n#endif\n#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION\nvec3 reflectionNormal=texelFetch(normalSampler,hitPixel,0).xyz;\nfloat directionBasedAttenuation=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));\nattenuation*=directionBasedAttenuation;\n#endif\nreturn attenuation;\n}\n#endif\nvoid main()\n{\n#ifdef SSR_SUPPORTED\nvec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);\nvec3 color=colorFull.rgb;\nvec4 reflectivity=TEXTUREFUNC(reflectivitySampler,vUV,0.0);\n#ifndef SSR_DISABLE_REFLECTIVITY_TEST\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {\n#ifdef SSR_USE_BLUR\ngl_FragColor=vec4(0.);\n#else\ngl_FragColor=colorFull;\n#endif\nreturn;\n}\n#endif\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpace(color);\n#endif\nvec2 texSize=vec2(textureSize(depthSampler,0));\nvec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; \nfloat depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;\nvec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);\nvec3 csViewDirection=normalize(csPosition);\nvec3 csReflectedVector=reflect(csViewDirection,csNormal);\n#ifdef SSR_USE_ENVIRONMENT_CUBE\nvec3 wReflectedVector=vec3(invView*vec4(csReflectedVector,0.0));\n#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\nvec4 worldPos=invView*vec4(csPosition,1.0);\nwReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),vReflectionSize,vReflectionPosition);\n#endif\n#ifdef SSR_INVERTCUBICMAP\nwReflectedVector.y*=-1.0;\n#endif\n#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nwReflectedVector.z*=-1.0;\n#endif\nvec3 envColor=TEXTURECUBEFUNC(envCubeSampler,wReflectedVector,0.0).xyz;\n#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE\nenvColor=toLinearSpace(envColor);\n#endif\n#else\nvec3 envColor=color;\n#endif\nfloat reflectionAttenuation=1.0;\nbool rayHasHit=false;\nvec2 startPixel;\nvec2 hitPixel;\nvec3 hitPoint;\nfloat numIterations;\n#ifdef SSRAYTRACE_DEBUG\nvec3 debugColor;\n#endif\n#ifdef SSR_ATTENUATE_FACING_CAMERA\nreflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector));\n#endif\nif (reflectionAttenuation>0.0) {\n#ifdef SSR_USE_BLUR\nvec3 jitt=vec3(0.);\n#else\nfloat roughness=1.0-reflectivity.a;\nvec3 jitt=mix(vec3(0.0),hash(csPosition)-vec3(0.5),roughness)*roughnessFactor; \n#endif\nvec2 uv2=vUV*texSize;\nfloat c=(uv2.x+uv2.y)*0.25;\nfloat jitter=mod(c,1.0); \nrayHasHit=traceScreenSpaceRay1(\ncsPosition,\nnormalize(csReflectedVector+jitt),\nprojectionPixel,\ndepthSampler,\ntexSize,\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nbackDepthSampler,\nbackSizeFactor,\n#endif\nthickness,\nnearPlaneZ,\nstepSize,\njitter,\nmaxSteps,\nmaxDistance,\nselfCollisionNumSkip,\nstartPixel,\nhitPixel,\nhitPoint,\nnumIterations\n#ifdef SSRAYTRACE_DEBUG\n,debugColor\n#endif\n);\n}\n#ifdef SSRAYTRACE_DEBUG\ngl_FragColor=vec4(debugColor,1.);\nreturn;\n#endif\nvec3 F0=reflectivity.rgb;\nvec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));\nvec3 SSR=envColor;\nif (rayHasHit) {\nvec3 reflectedColor=texelFetch(textureSampler,ivec2(hitPixel),0).rgb;\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\nreflectedColor=toLinearSpace(reflectedColor);\n#endif\nreflectionAttenuation*=computeAttenuationForIntersection(ivec2(hitPixel),hitPixel/texSize,csPosition,hitPoint,csReflectedVector,maxDistance,numIterations);\nSSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;\n}\n#ifndef SSR_BLEND_WITH_FRESNEL\nSSR*=fresnel;\n#endif\n#ifdef SSR_USE_BLUR\nfloat blur_radius=0.0;\nfloat roughness=1.0-reflectivity.a*(1.0-roughnessFactor);\nif (roughness>0.001) {\nfloat cone_angle=min(roughness,0.999)*3.14159265*0.5;\nfloat cone_len=distance(startPixel,hitPixel);\nfloat op_len=2.0*tan(cone_angle)*cone_len; \nfloat a=op_len;\nfloat h=cone_len;\nfloat a2=a*a;\nfloat fh2=4.0f*h*h;\nblur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);\n}\ngl_FragColor=vec4(SSR,blur_radius/255.0); \n#else\n#ifdef SSR_BLEND_WITH_FRESNEL\nvec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#else\nvec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#endif\nvec3 colorMultiplier=1.0-reflectionMultiplier;\nvec3 finalColor=(color*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpace(finalColor);\n#endif\ngl_FragColor=vec4(finalColor,colorFull.a);\n#endif\n#else\ngl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0);\n#endif\n}\n";Ht.v.ShadersStore[Mx]=Ox;const Dx="screenSpaceReflection2BlurPixelShader",Nx="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod)\n#else\n#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias)\n#endif\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform vec2 texelOffsetScale;\nconst float weights[8]=float[8] (0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);\nvoid processSample(vec2 uv,float i,vec2 stepSize,inout vec4 accumulator,inout float denominator)\n{\nvec2 offsetUV=stepSize*i+uv;\nfloat coefficient=weights[int(2.0-abs(i))];\naccumulator+=TEXTUREFUNC(textureSampler,offsetUV,0.0)*coefficient;\ndenominator+=coefficient;\n}\nvoid main()\n{\nvec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);\nif (dot(colorFull,vec4(1.0))==0.0) {\ngl_FragColor=colorFull;\nreturn;\n}\nfloat blurRadius=colorFull.a*255.0; \nvec2 stepSize=texelOffsetScale.xy*blurRadius;\nvec4 accumulator=TEXTUREFUNC(textureSampler,vUV,0.0)*0.214607;\nfloat denominator=0.214607;\nprocessSample(vUV,1.0,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*0.2,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*0.4,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*0.6,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*0.8,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*1.2,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*1.4,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*1.6,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*1.8,stepSize,accumulator,denominator);\nprocessSample(vUV,1.0*2.0,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*0.2,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*0.4,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*0.6,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*0.8,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*1.2,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*1.4,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*1.6,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*1.8,stepSize,accumulator,denominator);\nprocessSample(vUV,-1.0*2.0,stepSize,accumulator,denominator);\ngl_FragColor=vec4(accumulator.rgb/denominator,colorFull.a);\n}\n";Ht.v.ShadersStore[Dx]=Nx;const Fx="screenSpaceReflection2BlurCombinerPixelShader",wx="uniform sampler2D textureSampler; \nuniform sampler2D mainSampler;\nuniform sampler2D reflectivitySampler;\nuniform float strength;\nuniform float reflectionSpecularFalloffExponent;\nuniform float reflectivityThreshold;\nvarying vec2 vUV;\n#include\n#ifdef SSR_BLEND_WITH_FRESNEL\n#include\n#include\nuniform mat4 projection;\nuniform mat4 invProjectionMatrix;\nuniform sampler2D normalSampler;\nuniform sampler2D depthSampler;\n#endif\nvoid main()\n{\n#ifdef SSRAYTRACE_DEBUG\ngl_FragColor=texture2D(textureSampler,vUV);\n#else\nvec3 SSR=texture2D(textureSampler,vUV).rgb;\nvec4 color=texture2D(mainSampler,vUV);\nvec4 reflectivity=texture2D(reflectivitySampler,vUV);\n#ifndef SSR_DISABLE_REFLECTIVITY_TEST\nif (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {\ngl_FragColor=color;\nreturn;\n}\n#endif\n#ifdef SSR_INPUT_IS_GAMMA_SPACE\ncolor=toLinearSpace(color);\n#endif\n#ifdef SSR_BLEND_WITH_FRESNEL\nvec2 texSize=vec2(textureSize(depthSampler,0));\nvec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz;\nfloat depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;\nvec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);\nvec3 csViewDirection=normalize(csPosition);\nvec3 F0=reflectivity.rgb;\nvec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));\nvec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#else\nvec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0);\n#endif\nvec3 colorMultiplier=1.0-reflectionMultiplier;\nvec3 finalColor=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier);\n#ifdef SSR_OUTPUT_IS_GAMMA_SPACE\nfinalColor=toGammaSpace(finalColor);\n#endif\ngl_FragColor=vec4(finalColor,color.a);\n#endif\n}\n";Ht.v.ShadersStore[Fx]=wx;const Lx=o.y3.Compose(new o.P(.5,.5,.5),o._f.Identity(),new o.P(.5,.5,.5)),Bx=o.y3.Compose(new o.P(.5,.5,1),o._f.Identity(),new o.P(.5,.5,0));class Ux extends nx{set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}get samples(){return this._samples}get reflectivityThreshold(){return this._reflectivityThreshold}set reflectivityThreshold(e){e!==this._reflectivityThreshold&&(0===e&&0!==this._reflectivityThreshold||0!==e&&0===this._reflectivityThreshold?(this._reflectivityThreshold=e,this._buildPipeline()):this._reflectivityThreshold=e)}get ssrDownsample(){return this._ssrDownsample}set ssrDownsample(e){e!==this._ssrDownsample&&(this._ssrDownsample=e,this._buildPipeline())}get blurDispersionStrength(){return this._blurDispersionStrength}set blurDispersionStrength(e){if(e===this._blurDispersionStrength)return;const t=0===e&&0!==this._blurDispersionStrength||0!==e&&0===this._blurDispersionStrength;this._blurDispersionStrength=e,t&&this._buildPipeline()}_useBlur(){return this._blurDispersionStrength>0}get blurDownsample(){return this._blurDownsample}set blurDownsample(e){e!==this._blurDownsample&&(this._blurDownsample=e,this._buildPipeline())}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e,this._updateEffectDefines()}get environmentTextureIsProbe(){return this._environmentTextureIsProbe}set environmentTextureIsProbe(e){this._environmentTextureIsProbe=e,this._updateEffectDefines()}get attenuateScreenBorders(){return this._attenuateScreenBorders}set attenuateScreenBorders(e){this._attenuateScreenBorders!==e&&(this._attenuateScreenBorders=e,this._updateEffectDefines())}get attenuateIntersectionDistance(){return this._attenuateIntersectionDistance}set attenuateIntersectionDistance(e){this._attenuateIntersectionDistance!==e&&(this._attenuateIntersectionDistance=e,this._updateEffectDefines())}get attenuateIntersectionIterations(){return this._attenuateIntersectionIterations}set attenuateIntersectionIterations(e){this._attenuateIntersectionIterations!==e&&(this._attenuateIntersectionIterations=e,this._updateEffectDefines())}get attenuateFacingCamera(){return this._attenuateFacingCamera}set attenuateFacingCamera(e){this._attenuateFacingCamera!==e&&(this._attenuateFacingCamera=e,this._updateEffectDefines())}get attenuateBackfaceReflection(){return this._attenuateBackfaceReflection}set attenuateBackfaceReflection(e){this._attenuateBackfaceReflection!==e&&(this._attenuateBackfaceReflection=e,this._updateEffectDefines())}get clipToFrustum(){return this._clipToFrustum}set clipToFrustum(e){this._clipToFrustum!==e&&(this._clipToFrustum=e,this._updateEffectDefines())}get useFresnel(){return this._useFresnel}set useFresnel(e){this._useFresnel!==e&&(this._useFresnel=e,this._buildPipeline())}get enableAutomaticThicknessComputation(){return this._enableAutomaticThicknessComputation}set enableAutomaticThicknessComputation(e){this._enableAutomaticThicknessComputation!==e&&(this._enableAutomaticThicknessComputation=e,this._buildPipeline())}get backfaceDepthRenderer(){return this._depthRenderer}get backfaceDepthTextureDownsample(){return this._backfaceDepthTextureDownsample}set backfaceDepthTextureDownsample(e){this._backfaceDepthTextureDownsample!==e&&(this._backfaceDepthTextureDownsample=e,this._resizeDepthRenderer())}get backfaceForceDepthWriteTransparentMeshes(){return this._backfaceForceDepthWriteTransparentMeshes}set backfaceForceDepthWriteTransparentMeshes(e){this._backfaceForceDepthWriteTransparentMeshes!==e&&(this._backfaceForceDepthWriteTransparentMeshes=e,this._depthRenderer&&(this._depthRenderer.forceDepthWriteTransparentMeshes=e))}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)):null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get inputTextureColorIsInGammaSpace(){return this._inputTextureColorIsInGammaSpace}set inputTextureColorIsInGammaSpace(e){this._inputTextureColorIsInGammaSpace!==e&&(this._inputTextureColorIsInGammaSpace=e,this._buildPipeline())}get generateOutputInGammaSpace(){return this._generateOutputInGammaSpace}set generateOutputInGammaSpace(e){this._generateOutputInGammaSpace!==e&&(this._generateOutputInGammaSpace=e,this._buildPipeline())}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._buildPipeline())}getScene(){return this._scene}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}get scene(){return this._scene}get isSupported(){const e=this._scene.getEngine().getCaps();return e.drawBuffersExtension&&e.texelFetch}constructor(e,t,i,n=!1,s=0){if(super(t.getEngine(),e),this.SSRRenderEffect="SSRRenderEffect",this.SSRBlurRenderEffect="SSRBlurRenderEffect",this.SSRCombineRenderEffect="SSRCombineRenderEffect",this._samples=1,this.maxDistance=1e3,this.step=1,this.thickness=.5,this.strength=1,this.reflectionSpecularFalloffExponent=1,this.maxSteps=1e3,this.roughnessFactor=.2,this.selfCollisionNumSkip=1,this._reflectivityThreshold=.04,this._ssrDownsample=0,this._blurDispersionStrength=.03,this._blurDownsample=0,this._enableSmoothReflections=!1,this._environmentTextureIsProbe=!1,this._attenuateScreenBorders=!0,this._attenuateIntersectionDistance=!0,this._attenuateIntersectionIterations=!0,this._attenuateFacingCamera=!1,this._attenuateBackfaceReflection=!1,this._clipToFrustum=!0,this._useFresnel=!1,this._enableAutomaticThicknessComputation=!1,this._backfaceDepthTextureDownsample=0,this._backfaceForceDepthWriteTransparentMeshes=!0,this._isEnabled=!0,this._inputTextureColorIsInGammaSpace=!0,this._generateOutputInGammaSpace=!0,this._debug=!1,this._forceGeometryBuffer=!1,this._isDirty=!1,this._camerasToBeAttached=[],this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=s,this._forceGeometryBuffer=n,this.isSupported){if(t.postProcessRenderPipelineManager.addPipeline(this),this._forceGeometryBuffer){const e=t.enableGeometryBufferRenderer();e&&(e.enableReflectivity=!0,e.useSpecificClearForDepthTexture=!0)}else{const e=t.enablePrePassRenderer();e&&(e.useSpecificClearForDepthTexture=!0,e.markAsDirty())}this._buildPipeline()}}getClassName(){return"SSRRenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){const t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(e=!1){this._disposeDepthRenderer(),this._disposePostProcesses(),e&&this._scene.disableGeometryBufferRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),super.dispose()}_getTextureSize(){var e,t;const i=this._scene.getEngine(),n=this._prePassRenderer;let s={width:i.getRenderWidth(),height:i.getRenderHeight()};if(n&&(null===(e=this._scene.activeCamera)||void 0===e?void 0:e._getFirstPostProcess())===this._ssrPostProcess){const e=n.getRenderTarget();e&&e.textures&&(s=e.textures[n.getIndex(4)].getSize())}else(null===(t=this._ssrPostProcess)||void 0===t?void 0:t.inputTexture)&&(s.width=this._ssrPostProcess.inputTexture.width,s.height=this._ssrPostProcess.inputTexture.height);return s}_updateEffectDefines(){var e;const t=[];(this._geometryBufferRenderer||this._prePassRenderer)&&t.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&t.push("#define SSRAYTRACE_ENABLE_REFINEMENT"),this._scene.useRightHandedSystem&&t.push("#define SSRAYTRACE_RIGHT_HANDED_SCENE"),this._environmentTexture&&(t.push("#define SSR_USE_ENVIRONMENT_CUBE"),this._environmentTexture.boundingBoxSize&&t.push("#define SSR_USE_LOCAL_REFLECTIONMAP_CUBIC"),this._environmentTexture.gammaSpace&&t.push("#define SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE")),this._environmentTextureIsProbe&&t.push("#define SSR_INVERTCUBICMAP"),this._enableAutomaticThicknessComputation&&t.push("#define SSRAYTRACE_USE_BACK_DEPTHBUFFER"),this._attenuateScreenBorders&&t.push("#define SSR_ATTENUATE_SCREEN_BORDERS"),this._attenuateIntersectionDistance&&t.push("#define SSR_ATTENUATE_INTERSECTION_DISTANCE"),this._attenuateIntersectionIterations&&t.push("#define SSR_ATTENUATE_INTERSECTION_NUMITERATIONS"),this._attenuateFacingCamera&&t.push("#define SSR_ATTENUATE_FACING_CAMERA"),this._attenuateBackfaceReflection&&t.push("#define SSR_ATTENUATE_BACKFACE_REFLECTION"),this._clipToFrustum&&t.push("#define SSRAYTRACE_CLIP_TO_FRUSTUM"),this._useBlur()&&t.push("#define SSR_USE_BLUR"),this._debug&&t.push("#define SSRAYTRACE_DEBUG"),this._inputTextureColorIsInGammaSpace&&t.push("#define SSR_INPUT_IS_GAMMA_SPACE"),this._generateOutputInGammaSpace&&t.push("#define SSR_OUTPUT_IS_GAMMA_SPACE"),this._useFresnel&&t.push("#define SSR_BLEND_WITH_FRESNEL"),0===this._reflectivityThreshold&&t.push("#define SSR_DISABLE_REFLECTIVITY_TEST"),null===(e=this._ssrPostProcess)||void 0===e||e.updateEffect(t.join("\n"))}_buildPipeline(){var e;if(!this.isSupported)return;if(!this._isEnabled)return void(this._isDirty=!0);this._isDirty=!1;const t=this._scene.getEngine();if(this._disposeDepthRenderer(),this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._enableAutomaticThicknessComputation){const t=null===(e=this._cameras)||void 0===e?void 0:e[0];t&&(this._depthRendererCamera=t,this._depthRenderer=new Rg(this._scene,void 0,void 0,void 0,1,!0,"SSRBackDepth"),this._depthRenderer.clearColor.r=1e8,this._depthRenderer.reverseCulling=!0,this._depthRenderer.forceDepthWriteTransparentMeshes=this._backfaceForceDepthWriteTransparentMeshes,this._resizeDepthRenderer(),t.customRenderTargets.push(this._depthRenderer.getDepthMap()))}this._createSSRPostProcess(),this.addEffect(new YS(t,this.SSRRenderEffect,(()=>this._ssrPostProcess),!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new YS(t,this.SSRBlurRenderEffect,(()=>[this._blurPostProcessX,this._blurPostProcessY]),!0)),this.addEffect(new YS(t,this.SSRCombineRenderEffect,(()=>this._blurCombinerPostProcess),!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_resizeDepthRenderer(){if(!this._depthRenderer)return;const e=this._getTextureSize(),t=this._depthRenderer.getDepthMap().getSize(),i=Math.floor(e.width/(this._backfaceDepthTextureDownsample+1)),n=Math.floor(e.height/(this._backfaceDepthTextureDownsample+1));t.width===i&&t.height===n||this._depthRenderer.getDepthMap().resize({width:i,height:n})}_disposeDepthRenderer(){var e;if(this._depthRenderer){if(this._depthRendererCamera){const t=null!==(e=this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap()))&&void 0!==e?e:-1;-1!==t&&this._depthRendererCamera.customRenderTargets.splice(t,1)}this._depthRendererCamera=null,this._depthRenderer.getDepthMap().dispose()}this._depthRenderer=null}_disposePostProcesses(){var e,t,i,n;for(let s=0;s{this._resizeDepthRenderer();const t=this._geometryBufferRenderer,i=this._prePassRenderer;if(!i&&!t)return;if(t){const i=t.getTextureIndex(XE.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",t.getGBuffer().textures[1]),e.setTexture("reflectivitySampler",t.getGBuffer().textures[i]),e.setTexture("depthSampler",t.getGBuffer().textures[0])}else if(i){const t=i.getIndex(5),n=i.getIndex(3),s=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[s]),e.setTexture("depthSampler",i.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",i.getRenderTarget().textures[n])}this._enableAutomaticThicknessComputation&&this._depthRenderer&&(e.setTexture("backDepthSampler",this._depthRenderer.getDepthMap()),e.setFloat("backSizeFactor",this._backfaceDepthTextureDownsample+1));const n=this._scene.activeCamera;if(!n)return;const s=n.getViewMatrix(!0),r=n.getProjectionMatrix(!0);r.invertToRef(o.jp.Matrix[0]),s.invertToRef(o.jp.Matrix[1]),e.setMatrix("projection",r),e.setMatrix("view",s),e.setMatrix("invView",o.jp.Matrix[1]),e.setMatrix("invProjectionMatrix",o.jp.Matrix[0]),e.setFloat("thickness",this.thickness),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("maxSteps",this.maxSteps),e.setFloat("roughnessFactor",this.roughnessFactor),e.setFloat("nearPlaneZ",n.minZ),e.setFloat("maxDistance",this.maxDistance),e.setFloat("selfCollisionNumSkip",this.selfCollisionNumSkip),e.setFloat("reflectivityThreshold",this._reflectivityThreshold);const a=this._getTextureSize();o.y3.ScalingToRef(a.width,a.height,1,o.jp.Matrix[2]),r.multiplyToRef(this._scene.getEngine().isWebGPU?Bx:Lx,o.jp.Matrix[3]),o.jp.Matrix[3].multiplyToRef(o.jp.Matrix[2],o.jp.Matrix[4]),e.setMatrix("projectionPixel",o.jp.Matrix[4]),this._environmentTexture&&(e.setTexture("envCubeSampler",this._environmentTexture),this._environmentTexture.boundingBoxSize&&(e.setVector3("vReflectionPosition",this._environmentTexture.boundingBoxPosition),e.setVector3("vReflectionSize",this._environmentTexture.boundingBoxSize)))},this._ssrPostProcess.samples=this.samples,this._forceGeometryBuffer||(this._ssrPostProcess._prePassEffectConfiguration=new Rx)}_createBlurAndCombinerPostProcesses(){const e=this._scene.getEngine();this._blurPostProcessX=new Zt("SSRblurX","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._ssrDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessX.autoClear=!1,this._blurPostProcessX.onApplyObservable.add((e=>{var t,i;const n=null!==(i=null===(t=this._blurPostProcessX)||void 0===t?void 0:t.inputTexture.width)&&void 0!==i?i:this._scene.getEngine().getRenderWidth();e.setFloat2("texelOffsetScale",this._blurDispersionStrength/n,0)})),this._blurPostProcessY=new Zt("SSRblurY","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._blurDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessY.autoClear=!1,this._blurPostProcessY.onApplyObservable.add((e=>{var t,i;const n=null!==(i=null===(t=this._blurPostProcessY)||void 0===t?void 0:t.inputTexture.height)&&void 0!==i?i:this._scene.getEngine().getRenderHeight();e.setFloat2("texelOffsetScale",0,this._blurDispersionStrength/n)}));const t=["strength","reflectionSpecularFalloffExponent","reflectivityThreshold"],i=["textureSampler","mainSampler","reflectivitySampler"];let n="";this._debug&&(n+="#define SSRAYTRACE_DEBUG\n"),this._inputTextureColorIsInGammaSpace&&(n+="#define SSR_INPUT_IS_GAMMA_SPACE\n"),this._generateOutputInGammaSpace&&(n+="#define SSR_OUTPUT_IS_GAMMA_SPACE\n"),this.useFresnel&&(n+="#define SSR_BLEND_WITH_FRESNEL\n",t.push("projection","invProjectionMatrix"),i.push("depthSampler","normalSampler")),0===this._reflectivityThreshold&&(n+="#define SSR_DISABLE_REFLECTIVITY_TEST"),this._blurCombinerPostProcess=new Zt("SSRblurCombiner","screenSpaceReflection2BlurCombiner",t,i,this._useBlur()?1/(this._blurDownsample+1):1,null,1,e,!1,n,this._textureType),this._blurCombinerPostProcess.autoClear=!1,this._blurCombinerPostProcess.onApplyObservable.add((e=>{var t;const i=this._geometryBufferRenderer,n=this._prePassRenderer;if(n||i){if(n&&(null===(t=this._scene.activeCamera)||void 0===t?void 0:t._getFirstPostProcess())===this._ssrPostProcess){const t=n.getRenderTarget();t&&t.textures&&e.setTexture("mainSampler",t.textures[n.getIndex(4)])}else e.setTextureFromPostProcess("mainSampler",this._ssrPostProcess);if(i){const t=i.getTextureIndex(XE.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("reflectivitySampler",i.getGBuffer().textures[t]),this.useFresnel&&(e.setTexture("normalSampler",i.getGBuffer().textures[1]),e.setTexture("depthSampler",i.getGBuffer().textures[0]))}else if(n){const t=n.getIndex(3);if(e.setTexture("reflectivitySampler",n.getRenderTarget().textures[t]),this.useFresnel){const t=n.getIndex(5),i=n.getIndex(6);e.setTexture("normalSampler",n.getRenderTarget().textures[i]),e.setTexture("depthSampler",n.getRenderTarget().textures[t])}}if(e.setFloat("strength",this.strength),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("reflectivityThreshold",this._reflectivityThreshold),this.useFresnel){const t=this._scene.activeCamera;if(t){const i=t.getProjectionMatrix();i.invertToRef(o.jp.Matrix[0]),e.setMatrix("projection",i),e.setMatrix("invProjectionMatrix",o.jp.Matrix[0])}}}}))}serialize(){const e=E.p4.Serialize(this);return e.customType="SSRRenderingPipeline",e}static Parse(e,t,i){return E.p4.Parse((()=>new Ux(e._name,t,e._ratio)),e,t,i)}}(0,oe.gn)([(0,E.qC)()],Ux.prototype,"samples",null),(0,oe.gn)([(0,E.qC)()],Ux.prototype,"maxDistance",void 0),(0,oe.gn)([(0,E.qC)()],Ux.prototype,"step",void 0),(0,oe.gn)([(0,E.qC)()],Ux.prototype,"thickness",void 0),(0,oe.gn)([(0,E.qC)()],Ux.prototype,"strength",void 0),(0,oe.gn)([(0,E.qC)()],Ux.prototype,"reflectionSpecularFalloffExponent",void 0),(0,oe.gn)([(0,E.qC)()],Ux.prototype,"maxSteps",void 0),(0,oe.gn)([(0,E.qC)()],Ux.prototype,"roughnessFactor",void 0),(0,oe.gn)([(0,E.qC)()],Ux.prototype,"selfCollisionNumSkip",void 0),(0,oe.gn)([(0,E.qC)()],Ux.prototype,"_reflectivityThreshold",void 0),(0,oe.gn)([(0,E.qC)("_ssrDownsample")],Ux.prototype,"_ssrDownsample",void 0),(0,oe.gn)([(0,E.qC)()],Ux.prototype,"ssrDownsample",null),(0,oe.gn)([(0,E.qC)("blurDispersionStrength")],Ux.prototype,"_blurDispersionStrength",void 0),(0,oe.gn)([(0,E.qC)("blurDownsample")],Ux.prototype,"_blurDownsample",void 0),(0,oe.gn)([(0,E.qC)("enableSmoothReflections")],Ux.prototype,"_enableSmoothReflections",void 0),(0,oe.gn)([(0,E.qC)("environmentTexture")],Ux.prototype,"_environmentTexture",void 0),(0,oe.gn)([(0,E.qC)("environmentTextureIsProbe")],Ux.prototype,"_environmentTextureIsProbe",void 0),(0,oe.gn)([(0,E.qC)("attenuateScreenBorders")],Ux.prototype,"_attenuateScreenBorders",void 0),(0,oe.gn)([(0,E.qC)("attenuateIntersectionDistance")],Ux.prototype,"_attenuateIntersectionDistance",void 0),(0,oe.gn)([(0,E.qC)("attenuateIntersectionIterations")],Ux.prototype,"_attenuateIntersectionIterations",void 0),(0,oe.gn)([(0,E.qC)("attenuateFacingCamera")],Ux.prototype,"_attenuateFacingCamera",void 0),(0,oe.gn)([(0,E.qC)("attenuateBackfaceReflection")],Ux.prototype,"_attenuateBackfaceReflection",void 0),(0,oe.gn)([(0,E.qC)("clipToFrustum")],Ux.prototype,"_clipToFrustum",void 0),(0,oe.gn)([(0,E.qC)("useFresnel")],Ux.prototype,"_useFresnel",void 0),(0,oe.gn)([(0,E.qC)("enableAutomaticThicknessComputation")],Ux.prototype,"_enableAutomaticThicknessComputation",void 0),(0,oe.gn)([(0,E.qC)("backfaceDepthTextureDownsample")],Ux.prototype,"_backfaceDepthTextureDownsample",void 0),(0,oe.gn)([(0,E.qC)("backfaceForceDepthWriteTransparentMeshes")],Ux.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0),(0,oe.gn)([(0,E.qC)("isEnabled")],Ux.prototype,"_isEnabled",void 0),(0,oe.gn)([(0,E.qC)("inputTextureColorIsInGammaSpace")],Ux.prototype,"_inputTextureColorIsInGammaSpace",void 0),(0,oe.gn)([(0,E.qC)("generateOutputInGammaSpace")],Ux.prototype,"_generateOutputInGammaSpace",void 0),(0,oe.gn)([(0,E.qC)("debug")],Ux.prototype,"_debug",void 0),(0,l.H)("BABYLON.SSRRenderingPipeline",Ux);const Vx="tonemapPixelShader",kx="varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}";Ht.v.ShadersStore[Vx]=kx;var Gx;!function(e){e[e.Hable=0]="Hable",e[e.Reinhard=1]="Reinhard",e[e.HejiDawson=2]="HejiDawson",e[e.Photographic=3]="Photographic"}(Gx||(Gx={}));const zx="volumetricLightScatteringPixelShader",Wx="uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i{this.isSupported||this.dispose(e),this.onActivate=null},this.onApplyObservable.add((e=>{this._updateMeshScreenCoordinates(h),e.setTexture("lightScatteringSampler",this._volumetricLightScatteringRTT),e.setFloat("exposure",this.exposure),e.setFloat("decay",this.decay),e.setFloat("weight",this.weight),e.setFloat("density",this.density),e.setVector2("meshPositionOnScreen",this._screenCoordinates)}))}getClassName(){return"VolumetricLightScatteringPostProcess"}_isReady(e,t){var i;const n=e.getMesh();if(n===this.mesh&&n.material)return n.material.isReady(n);const s=null===(i=n._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[this._scene.getEngine().currentRenderPassId];if(s)return s.isReadyForSubMesh(n,e,t);const r=[],o=[ne.o.PositionKind],a=e.getMaterial();a&&(a.needAlphaTesting()&&r.push("#define ALPHATEST"),n.isVerticesDataPresent(ne.o.UVKind)&&(o.push(ne.o.UVKind),r.push("#define UV1")),n.isVerticesDataPresent(ne.o.UV2Kind)&&(o.push(ne.o.UV2Kind),r.push("#define UV2"))),n.useBones&&n.computeBonesUsingShaders?(o.push(ne.o.MatricesIndicesKind),o.push(ne.o.MatricesWeightsKind),r.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),r.push("#define BonesPerMesh "+(n.skeleton?n.skeleton.bones.length+1:0))):r.push("#define NUM_BONE_INFLUENCERS 0"),t&&(r.push("#define INSTANCES"),It.G.PushAttributesForInstances(o),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES"));const l=e._getDrawWrapper(void 0,!0),h=l.defines,c=r.join("\n");return h!==c&&l.setEffect(n.getScene().getEngine().createEffect("volumetricLightScatteringPass",o,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],c,void 0,void 0,void 0,{maxSimultaneousMorphTargets:n.numBoneInfluencers}),c),l.effect.isReady()}setCustomMeshPosition(e){this.customMeshPosition=e}getCustomMeshPosition(){return this.customMeshPosition}dispose(e){const t=e.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);-1!==t&&e.getScene().customRenderTargets.splice(t,1),this._volumetricLightScatteringRTT.dispose(),super.dispose(e)}getPass(){return this._volumetricLightScatteringRTT}_meshExcluded(e){return this.includedMeshes.length>0&&-1===this.includedMeshes.indexOf(e)||this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)}_createPass(e,t){const i=e.getEngine();this._volumetricLightScatteringRTT=new Ci("volumetricLightScatteringMap",{width:i.getRenderWidth()*t,height:i.getRenderHeight()*t},e,!1,!0,0),this._volumetricLightScatteringRTT.wrapU=Le.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=Le.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;const n=this.getCamera();n?n.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);const s=e=>{var t;const i=e.getRenderingMesh(),n=e.getEffectiveMesh();if(this._meshExcluded(i))return;n._internalAbstractMeshDataInfo._isActiveIntermediate=!1;const s=e.getMaterial();if(!s)return;const r=i.getScene(),o=r.getEngine();o.setState(s.backFaceCulling,void 0,void 0,void 0,s.cullBackFaces);const a=i._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(a.mustReturn)return;const l=o.getCaps().instancedArrays&&(null!==a.visibleInstances[e._id]||i.hasThinInstances);if(this._isReady(e,l)){const h=null===(t=n._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===t?void 0:t[o.currentRenderPassId];let c=e._getDrawWrapper();if(i!==this.mesh||c||(c=s._getDrawWrapper()),!c)return;const d=c.effect;if(o.enableEffect(c),l||i._bind(e,d,s.fillMode),i===this.mesh)s.bind(n.getWorldMatrix(),i);else if(h)h.bindForSubMesh(n.getWorldMatrix(),n,e);else{if(d.setMatrix("viewProjection",r.getTransformMatrix()),s&&s.needAlphaTesting()){const e=s.getAlphaTestTexture();d.setTexture("diffuseSampler",e),e&&d.setMatrix("diffuseMatrix",e.getTextureMatrix())}i.useBones&&i.computeBonesUsingShaders&&i.skeleton&&d.setMatrices("mBones",i.skeleton.getTransformMatrices(i))}l&&i.hasThinInstances&&d.setMatrix("world",n.getWorldMatrix()),i._processRendering(n,e,d,ut.F.TriangleFillMode,a,l,((e,t)=>{e||d.setMatrix("world",t)}))}};let r;const o=new a.HE(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add((()=>{r=e.clearColor,e.clearColor=o})),this._volumetricLightScatteringRTT.onAfterRenderObservable.add((()=>{e.clearColor=r})),this._volumetricLightScatteringRTT.customIsReadyFunction=(e,t,n)=>{if((n||0===t)&&e.subMeshes)for(let s=0;s{const o=e.getEngine();let a;if(r.length){for(o.setColorWrite(!1),a=0;ae._alphaIndex>t._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0)),o.setAlphaMode(2),a=0;a{e.setFloat("curvature_ridge",.5/Math.max(this.ridge*this.ridge,1e-4)),e.setFloat("curvature_valley",.7/Math.max(this.valley*this.valley,1e-4));const t=this._geometryBufferRenderer.getGBuffer().textures[1];e.setTexture("normalSampler",t)}:p.Y.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.")}static get IsSupported(){const e=m.l.LastCreatedEngine;return!!e&&e.getCaps().drawBuffersExtension}static _Parse(e,t,i,n){return E.p4.Parse((()=>new Qx(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable)),e,i,n)}}(0,oe.gn)([(0,E.qC)()],Qx.prototype,"ridge",void 0),(0,oe.gn)([(0,E.qC)()],Qx.prototype,"valley",void 0),(0,l.H)("BABYLON.ScreenSpaceCurvaturePostProcess",Qx);const Zx="boundingBoxRendererFragmentDeclaration",Jx="uniform vec4 color;\n";Ht.v.IncludesShadersStore[Zx]=Jx;const eb="boundingBoxRendererUboDeclaration",tb="#ifdef WEBGL2\nuniform vec4 color;\nuniform mat4 world;\nuniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n#else\nlayout(std140,column_major) uniform;\nuniform BoundingBoxRenderer {\nvec4 color;\nmat4 world;\nmat4 viewProjection;\nmat4 viewProjectionR;\n};\n#endif\n";Ht.v.IncludesShadersStore[eb]=tb;const ib="boundingBoxRendererPixelShader",nb="#include<__decl__boundingBoxRendererFragment>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ht.v.ShadersStore[ib]=nb;const sb="boundingBoxRendererVertexDeclaration",rb="uniform mat4 world;\nuniform mat4 viewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\n#endif\n";Ht.v.IncludesShadersStore[sb]=rb;const ob="boundingBoxRendererVertexShader",ab="attribute vec3 position;\n#include<__decl__boundingBoxRendererVertex>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec4 worldPos=world*vec4(position,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {\ngl_Position=viewProjection*worldPos;\n} else {\ngl_Position=viewProjectionR*worldPos;\n}\n#else\ngl_Position=viewProjection*worldPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\n";Ht.v.ShadersStore[ob]=ab;Object.defineProperty(N.x.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(e){this._forceShowBoundingBoxes=e,e&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0}),N.x.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new lb(this)),this._boundingBoxRenderer},Object.defineProperty(ie.x.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(e){this._showBoundingBox=e,e&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});class lb{constructor(e){this.name=Se.l.NAME_BOUNDINGBOXRENDERER,this.frontColor=new a.Wo(1,1,1),this.backColor=new a.Wo(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new r.y$,this.onAfterBoxRenderingObservable=new r.y$,this.onResourcesReadyObservable=new r.y$,this.enabled=!0,this.renderList=new Wt.t(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,e._addComponent(this),this._uniformBufferFront=new ae.M(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new ae.M(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererBack",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferBack)}_buildUniformLayout(e){e.addUniform("color",4),e.addUniform("world",16),e.addUniform("viewProjection",16),e.addUniform("viewProjectionR",16),e.create()}register(){this.scene._beforeEvaluateActiveMeshStage.registerStep(Se.l.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(Se.l.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(Se.l.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(Se.l.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)}_evaluateSubMesh(e,t){if(e.showSubMeshesBoundingBox){const i=t.getBoundingInfo();null!=i&&(i.boundingBox._tag=e.renderingGroupId,this.renderList.push(i.boundingBox))}}_preActiveMesh(e){if(e.showBoundingBox||this.scene.forceShowBoundingBoxes){const t=e.getBoundingInfo();t.boundingBox._tag=e.renderingGroupId,this.renderList.push(t.boundingBox)}}_prepareResources(){if(this._colorShader)return;this._colorShader=new Il("colorShader",this.scene,"boundingBoxRenderer",{attributes:[ne.o.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new Il("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[ne.o.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};const e=this.scene.getEngine(),t=fl({size:1});this._vertexBuffers[ne.o.PositionKind]=new ne.o(e,t.positions,ne.o.PositionKind,!1),this._createIndexBuffer(),this._fillIndexData=t.indices,this.onResourcesReadyObservable.notifyObservers(this)}_createIndexBuffer(){const e=this.scene.getEngine();this._indexBuffer=e.createIndexBuffer([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,7,1,6,2,5,3,4])}rebuild(){const e=this._vertexBuffers[ne.o.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}reset(){this.renderList.reset()}render(e){var t,i;if(0===this.renderList.length||!this.enabled)return;if(this._prepareResources(),!this._colorShader.isReady())return;const n=this.scene.getEngine();n.setDepthWrite(!1);const s=this.scene.getTransformMatrix();for(let r=0;r{let t=e._getComponent(Se.l.NAME_DEPTHRENDERER);t||(t=new hb(e),e._addComponent(t))};const cb="oitFinalPixelShader",db="precision highp float;\nuniform sampler2D uFrontColor;\nuniform sampler2D uBackColor;\nvoid main() {\nivec2 fragCoord=ivec2(gl_FragCoord.xy);\nvec4 frontColor=texelFetch(uFrontColor,fragCoord,0);\nvec4 backColor=texelFetch(uBackColor,fragCoord,0);\nfloat alphaMultiplier=1.0-frontColor.a;\nglFragColor=vec4(\nfrontColor.rgb+alphaMultiplier*backColor.rgb,\nfrontColor.a+backColor.a\n);\n}";Ht.v.ShadersStore[cb]=db;const ub="oitBackBlendPixelShader",pb="precision highp float;\nuniform sampler2D uBackColor;\nvoid main() {\nglFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);\nif (glFragColor.a==0.0) { \ndiscard;\n}\n}";Ht.v.ShadersStore[ub]=pb;class fb{constructor(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[4]}}class _b{get passCount(){return this._passCount}set passCount(e){this._passCount!==e&&(this._passCount=e,this._createRenderPassIds())}get useRenderPasses(){return this._useRenderPasses}set useRenderPasses(e){this._useRenderPasses!==e&&(this._useRenderPasses=e,this._createRenderPassIds())}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){const t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}constructor(e,t=5){if(this._thinTextures=[],this._currentPingPongState=0,this._layoutCacheFormat=[[!0],[!0,!0],[!0,!0,!0]],this._layoutCache=[],this._candidateSubMeshes=new Wt.t(10),this._excludedSubMeshes=new Wt.t(10),this._excludedMeshes=[],this._colorCache=[new a.HE(_b._DEPTH_CLEAR_VALUE,_b._DEPTH_CLEAR_VALUE,0,0),new a.HE(-_b._MIN_DEPTH,_b._MAX_DEPTH,0,0),new a.HE(0,0,0,0)],this._scene=e,this._engine=e.getEngine(),this._passCount=t,e.enablePrePassRenderer()){for(let e=0;e{this._rebuild()})),this._meshDisposeObserver=this._source.onDisposeObservable.add((()=>{this.dispose()}))}_prepareRessources(){this._lineShader||(this._lineShader=xb._GetShader(this._source.getScene()))}_rebuild(){let e=this._buffers[ne.o.PositionKind];e&&e._rebuild(),e=this._buffers[ne.o.NormalKind],e&&e._rebuild();const t=this._source.getScene().getEngine();this._ib=t.createIndexBuffer(this._linesIndices)}dispose(){var e;this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);let t=this._buffers[ne.o.PositionKind];t&&(t.dispose(),this._buffers[ne.o.PositionKind]=null),t=this._buffers[ne.o.NormalKind],t&&(t.dispose(),this._buffers[ne.o.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose(),null===(e=this._drawWrapper)||void 0===e||e.dispose()}_processEdgeForAdjacencies(e,t,i,n,s){return e===i&&t===n||e===n&&t===i?0:e===n&&t===s||e===s&&t===n?1:e===s&&t===i||e===i&&t===s?2:-1}_processEdgeForAdjacenciesWithVertices(e,t,i,n,s){const r=1e-10;return e.equalsWithEpsilon(i,r)&&t.equalsWithEpsilon(n,r)||e.equalsWithEpsilon(n,r)&&t.equalsWithEpsilon(i,r)?0:e.equalsWithEpsilon(n,r)&&t.equalsWithEpsilon(s,r)||e.equalsWithEpsilon(s,r)&&t.equalsWithEpsilon(n,r)?1:e.equalsWithEpsilon(s,r)&&t.equalsWithEpsilon(i,r)||e.equalsWithEpsilon(i,r)&&t.equalsWithEpsilon(s,r)?2:-1}_checkEdge(e,t,i,n,s){let r;if(void 0===t)r=!0;else{r=o.P.Dot(i[e],i[t]){i>=0&&t.push(i);for(let n=0;n=e[0].length&&e[1].length>=e[2].length?r=1:e[2].length>=e[0].length&&e[2].length>=e[1].length&&(r=2);for(let E=0;E<3;++E)E===r?e[E].sort(((e,t)=>e[1]t[1]?1:0)):e[E].sort(((e,t)=>e[1]>t[1]?-1:e[1]=r+1;--E)s(e[E%3],a,E!==r+2?n[i[t+(E+1)%3]]:-1);const h=a.length;i.push(n[i[t+r]],o[0],a[0]),i.push(n[i[t+(r+1)%3]],a[h-1],o[l-1]);const c=l<=h,d=c?l:h,u=c?h:l,p=c?l-1:h-1,f=c?0:1;let _=l+h-2,m=0,g=0;const v=c?o:a,T=c?a:o;let S=0;for(;_-- >0;){let e;f?i.push(v[m],T[g]):i.push(T[g],v[m]),S+=d,S>=u&&mn){const e=i;i=n,n=e}const r=i+"_"+n,a=g[r];if(a){if(!a.done){o.P.Dot(e,a.normal)0||this._source.hasThinInstances)}render(){const e=this._source.getScene(),t=this._lineShader._getDrawWrapper();if(this._drawWrapper&&this._lineShader._setDrawWrapper(this._drawWrapper),!this.isReady()||!e.activeCamera)return void this._lineShader._setDrawWrapper(t);const i=this._source.hasInstances&&this.customInstances.length>0,n=i||this._source.hasThinInstances;let s=0;if(n)if(this._buffersForInstances.world0=this._source.getVertexBuffer("world0"),this._buffersForInstances.world1=this._source.getVertexBuffer("world1"),this._buffersForInstances.world2=this._source.getVertexBuffer("world2"),this._buffersForInstances.world3=this._source.getVertexBuffer("world3"),i){const e=this._source._instanceDataStorage;if(s=this.customInstances.length,!e.instancesData)return void(this._source.getScene()._activeMeshesFrozen||this.customInstances.reset());if(!e.isFrozen){let t=0;for(let i=0;i0&&(this._useSpecificClearForDepthTexture&&5===this._mrtLayout[s]?(t.push(!1),i.push(!0)):(t.push(!0),i.push(!1)),n.push(!1));this._multiRenderAttachments=this._engine.buildTextureLayout(e),this._clearAttachments=this._engine.buildTextureLayout(t),this._clearDepthAttachments=this._engine.buildTextureLayout(i),this._defaultAttachments=this._engine.buildTextureLayout(n)}_resetLayout(){for(let e=0;enull!=e)),this._scene.autoClear=!0;const n=this._hasImageProcessing(this._postProcessesSourceForThisPass);this._needsCompositionForThisPass=!n&&!this.disableGammaTransform&&this._needsImageProcessing()&&!i;const s=this._getFirstPostProcess(this._postProcessesSourceForThisPass),r=e._beforeCompositionPostProcesses&&e._beforeCompositionPostProcesses[0];let o=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||n,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),r?o=r:this._needsCompositionForThisPass?o=e.imageProcessingPostProcess:s&&(o=s),this._bindFrameBuffer(e),this._linkInternalTexture(e,o)}_linkInternalTexture(e,t){t&&(t.autoClear=!1,t.inputTexture=e.renderTarget),e._outputPostProcess!==t&&(e._outputPostProcess&&this._unlinkInternalTexture(e),e._outputPostProcess=t),e._internalTextureDirty&&(this._updateGeometryBufferLayout(),e._internalTextureDirty=!1)}_unlinkInternalTexture(e){e._outputPostProcess&&(e._outputPostProcess.autoClear=!0,e._outputPostProcess.restoreDefaultInputTexture(),e._outputPostProcess=null)}_needsImageProcessing(){for(let e=0;enull!=e)),e)){for(let n=0;n=0;e--)this.renderTargets[e].dispose();for(let e=0;e{throw(0,ge.S)("PrePassRendererSceneComponent")},yb.TextureFormats=[{purpose:0,type:2,format:5,name:"prePass_Irradiance"},{purpose:1,type:2,format:5,name:"prePass_Position"},{purpose:2,type:0,format:5,name:"prePass_Velocity"},{purpose:3,type:0,format:5,name:"prePass_Reflectivity"},{purpose:4,type:2,format:5,name:"prePass_Color"},{purpose:5,type:1,format:6,name:"prePass_Depth"},{purpose:6,type:2,format:5,name:"prePass_Normal"},{purpose:7,type:0,format:5,name:"prePass_Albedo"}],Object.defineProperty(N.x.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(e){e&&e.isSupported&&(this._prePassRenderer=e)},enumerable:!0,configurable:!0}),N.x.prototype.enablePrePassRenderer=function(){return this._prePassRenderer||(this._prePassRenderer=new yb(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,p.Y.Error("PrePassRenderer needs WebGL 2 support.\nMaybe you tried to use the following features that need the PrePassRenderer :\n + Subsurface Scattering"))),this._prePassRenderer},N.x.prototype.disablePrePassRenderer=function(){this._prePassRenderer&&(this._prePassRenderer.dispose(),this._prePassRenderer=null)};class Ab{constructor(e){this.name=Se.l.NAME_PREPASSRENDERER,this.scene=e}register(){this.scene._beforeCameraDrawStage.registerStep(Se.l.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(Se.l.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(Se.l.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(Se.l.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(Se.l.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(Se.l.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(Se.l.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(Se.l.STEP_AFTERRENDERINGMESH_PREPASS,this,this._afterRenderingMeshStage)}_beforeRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._beforeDraw(void 0,t,i))}_afterRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&this.scene.prePassRenderer._afterDraw(t,i)}_beforeRenderTargetClearStage(e){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(e._prePassRenderTarget||(e._prePassRenderTarget=this.scene.prePassRenderer._createRenderTarget(e.name+"_prePassRTT",e)),this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._clear())}_beforeCameraDraw(e){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._beforeDraw(e))}_afterCameraDraw(){this.scene.prePassRenderer&&this.scene.prePassRenderer._afterDraw()}_beforeClearStage(){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._clear())}_beforeRenderingMeshStage(e,t,i,n){if(!n)return;const s=e.getScene();s.prePassRenderer&&s.prePassRenderer.bindAttachmentsForEffect(n,t)}_afterRenderingMeshStage(e){const t=e.getScene();t.prePassRenderer&&t.prePassRenderer.restoreAttachments()}rebuild(){this.scene.disablePrePassRenderer(),this.scene.enablePrePassRenderer()}dispose(){this.scene.disablePrePassRenderer()}}yb._SceneComponentInitialization=e=>{let t=e._getComponent(Se.l.NAME_PREPASSRENDERER);t||(t=new Ab(e),e._addComponent(t))};const Rb="fibonacci",Pb="#define rcp(x) 1./x\n#define GOLDEN_RATIO 1.618033988749895\n#define TWO_PI 6.2831855\nvec2 Golden2dSeq(int i,float n)\n{\nreturn vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));\n}\nvec2 SampleDiskGolden(int i,int sampleCount)\n{\nvec2 f=Golden2dSeq(i,float(sampleCount));\nreturn vec2(sqrt(f.x),TWO_PI*f.y);\n}";Ht.v.IncludesShadersStore[Rb]=Pb;const Ib="diffusionProfile",Mb="uniform vec3 diffusionS[5];\nuniform float diffusionD[5];\nuniform float filterRadii[5];";Ht.v.IncludesShadersStore[Ib]=Mb;const Ob="subSurfaceScatteringPixelShader",Db="#include\n#include\n#include\n#include\nvarying vec2 vUV;\nuniform vec2 texelSize;\nuniform sampler2D textureSampler;\nuniform sampler2D irradianceSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D albedoSampler;\nuniform vec2 viewportSize;\nuniform float metersPerUnit;\nconst float LOG2_E=1.4426950408889634;\nconst float SSS_PIXELS_PER_SAMPLE=4.;\nconst int _SssSampleBudget=40;\n#define rcp(x) 1./x\n#define Sq(x) x*x\n#define SSS_BILATERAL_FILTER true\nvec3 EvalBurleyDiffusionProfile(float r,vec3 S)\n{\nvec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); \nvec3 expSum=exp_13*(1.+exp_13*exp_13); \nreturn (S*rcp(8.*PI))*expSum; \n}\nvec2 SampleBurleyDiffusionProfile(float u,float rcpS)\n{\nu=1.-u; \nfloat g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));\nfloat n=exp2(log2(g)*(-1.0/3.0)); \nfloat p=(g*n)*n; \nfloat c=1.+p+n; \nfloat d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); \nfloat x=(3./LOG2_E)*log2(c)-d; \nfloat rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));\nfloat r=x*rcpS;\nfloat rcpPdf=(8.*PI*rcpS)*rcpExp; \nreturn vec2(r,rcpPdf);\n}\nvec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf)\n{\n#ifndef SSS_BILATERAL_FILTER\nz=0.;\n#endif\nfloat r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));\nfloat area=rcpPdf;\n#if SSS_CLAMP_ARTIFACT\nreturn clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0);\n#else\nreturn EvalBurleyDiffusionProfile(r,S)*area;\n#endif\n}\nvoid EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm,\nfloat phase,inout vec3 totalIrradiance,inout vec3 totalWeight)\n{\nfloat scale =rcp(float(n));\nfloat offset=rcp(float(n))*0.5;\nfloat sinPhase,cosPhase;\nsinPhase=sin(phase);\ncosPhase=cos(phase);\nvec2 bdp=SampleBurleyDiffusionProfile(float(i)*scale+offset,d);\nfloat r=bdp.x;\nfloat rcpPdf=bdp.y;\nfloat phi=SampleDiskGolden(i,n).y;\nfloat sinPhi,cosPhi;\nsinPhi=sin(phi);\ncosPhi=cos(phi);\nfloat sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; \nfloat cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; \nvec2 vec=r*vec2(cosPsi,sinPsi);\nvec2 position; \nfloat xy2;\nposition=vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*texelSize;\nxy2 =r*r;\nvec4 textureSample=texture2D(irradianceSampler,position);\nfloat viewZ=texture2D(depthSampler,position).r;\nvec3 irradiance =textureSample.rgb;\nif (testLightingForSSS(textureSample.a))\n{\nfloat relZ=viewZ-centerPosVS.z;\nvec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);\ntotalIrradiance+=weight*irradiance;\ntotalWeight +=weight;\n}\nelse\n{\n}\n}\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{\nvec4 irradianceAndDiffusionProfile =texture2D(irradianceSampler,vUV);\nvec3 centerIrradiance=irradianceAndDiffusionProfile.rgb;\nint diffusionProfileIndex=int(round(irradianceAndDiffusionProfile.a*255.));\nfloat centerDepth =0.;\nvec4 inputColor=texture2D(textureSampler,vUV);\nbool passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);\nif (passedStencilTest)\n{\ncenterDepth=texture2D(depthSampler,vUV).r;\n}\nif (!passedStencilTest) { \ngl_FragColor=inputColor;\nreturn;\n}\nfloat distScale =1.;\nvec3 S =diffusionS[diffusionProfileIndex];\nfloat d =diffusionD[diffusionProfileIndex];\nfloat filterRadius=filterRadii[diffusionProfileIndex];\nvec2 centerPosNDC=vUV;\nvec2 cornerPosNDC=vUV+0.5*texelSize;\nvec3 centerPosVS =vec3(centerPosNDC*viewportSize,1.0)*centerDepth; \nvec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; \nfloat mmPerUnit =1000.*(metersPerUnit*rcp(distScale));\nfloat unitsPerMm=rcp(mmPerUnit);\nfloat unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);\nfloat pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;\nfloat filterArea =PI*Sq(filterRadius*pixelsPerMm);\nint sampleCount =int(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));\nint sampleBudget=_SssSampleBudget;\nint texturingMode=0;\nvec3 albedo =texture2D(albedoSampler,vUV).rgb;\nif (distScale==0. || sampleCount<1)\n{\n#ifdef DEBUG_SSS_SAMPLES\nvec3 green=vec3(0.,1.,0.);\ngl_FragColor=vec4(green,1.0);\nreturn;\n#endif\ngl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);\nreturn;\n}\n#ifdef DEBUG_SSS_SAMPLES\nvec3 red =vec3(1.,0.,0.);\nvec3 blue=vec3(0.,0.,1.);\ngl_FragColor=vec4(mix(blue,red,clamp(float(sampleCount)/float(sampleBudget),0.0,1.0)),1.0);\nreturn;\n#endif\nfloat phase=0.;\nint n=min(sampleCount,sampleBudget);\nvec3 centerWeight =vec3(0.); \nvec3 totalIrradiance=vec3(0.);\nvec3 totalWeight =vec3(0.);\nfor (int i=0; i{if(!t.prePassRenderer||!t.subSurfaceConfiguration)return void p.Y.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering.");const i=this.texelSize;e.setFloat("metersPerUnit",t.subSurfaceConfiguration.metersPerUnit),e.setFloat2("texelSize",i.x,i.y),e.setTexture("irradianceSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(0)]),e.setTexture("depthSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(5)]),e.setTexture("albedoSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(7)]),e.setFloat2("viewportSize",Math.tan(t.activeCamera.fov/2)*t.getEngine().getAspectRatio(t.activeCamera,!0),Math.tan(t.activeCamera.fov/2)),e.setArray3("diffusionS",t.subSurfaceConfiguration.ssDiffusionS),e.setArray("diffusionD",t.subSurfaceConfiguration.ssDiffusionD),e.setArray("filterRadii",t.subSurfaceConfiguration.ssFilterRadii)}))}}class Fb{get ssDiffusionS(){return this._ssDiffusionS}get ssDiffusionD(){return this._ssDiffusionD}get ssFilterRadii(){return this._ssFilterRadii}constructor(e){this._ssDiffusionS=[],this._ssFilterRadii=[],this._ssDiffusionD=[],this.enabled=!1,this.needsImageProcessing=!0,this.name=Se.l.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[5,7,4,0],this.addDiffusionProfile(new a.Wo(1,1,1)),this._scene=e,Fb._SceneComponentInitialization(this._scene)}addDiffusionProfile(e){if(this.ssDiffusionD.length>=5)return p.Y.Error("You already reached the maximum number of diffusion profiles."),0;for(let t=0;t{throw(0,ge.S)("SubSurfaceSceneComponent")},n.p.AddParser(Se.l.NAME_SUBSURFACE,((e,t)=>{if(void 0!==e.ssDiffusionProfileColors&&null!==e.ssDiffusionProfileColors&&(t.enableSubSurfaceForPrePass(),t.subSurfaceConfiguration))for(let i=0,n=e.ssDiffusionProfileColors.length;i{let t=e._getComponent(Se.l.NAME_SUBSURFACE);t||(t=new wb(e),e._addComponent(t))};const Lb="outlinePixelShader",Bb="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include\ngl_FragColor=color;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ht.v.ShadersStore[Lb]=Bb;const Ub="outlineVertexShader",Vb="attribute vec3 position;\nattribute vec3 normal;\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nuniform float offset;\n#include\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\n{\nvec3 positionUpdated=position;\nvec3 normalUpdated=normal;\n#ifdef UV1\nvec2 uvUpdated=uv;\n#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\nvec3 offsetPosition=positionUpdated+(normalUpdated*offset);\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(offsetPosition,1.0);\ngl_Position=viewProjection*worldPos;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n#include\n}\n";Ht.v.ShadersStore[Ub]=Vb;N.x.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new kb(this)),this._outlineRenderer},Object.defineProperty(ee.Kj.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOutline=e},enumerable:!0,configurable:!0}),Object.defineProperty(ee.Kj.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOverlay=e},enumerable:!0,configurable:!0});class kb{constructor(e){this.name=Se.l.NAME_OUTLINERENDERER,this.zOffset=1,this.zOffsetUnits=4,this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this),this._passIdForDrawWrapper=[];for(let t=0;t<4;++t)this._passIdForDrawWrapper[t]=this._engine.createRenderPassId(`Outline Renderer (${t})`)}register(){this.scene._beforeRenderingMeshStage.registerStep(Se.l.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(Se.l.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){for(let e=0;e{p.setMatrix("world",t)})),r.setZOffset(0),r.setZOffsetUnits(0)}isReady(e,t,i){i=null!=i?i:this._passIdForDrawWrapper[0];const n=[],s=[ne.o.PositionKind,ne.o.NormalKind],r=e.getMesh(),o=e.getMaterial();if(!o)return!1;const a=r.getScene();o.needAlphaTesting()&&(n.push("#define ALPHATEST"),r.isVerticesDataPresent(ne.o.UVKind)&&(s.push(ne.o.UVKind),n.push("#define UV1")),r.isVerticesDataPresent(ne.o.UV2Kind)&&(s.push(ne.o.UV2Kind),n.push("#define UV2"))),o.useLogarithmicDepth&&n.push("#define LOGARITHMICDEPTH"),(0,ua.lK)(o,a,n),r.useBones&&r.computeBonesUsingShaders?(s.push(ne.o.MatricesIndicesKind),s.push(ne.o.MatricesWeightsKind),r.numBoneInfluencers>4&&(s.push(ne.o.MatricesIndicesExtraKind),s.push(ne.o.MatricesWeightsExtraKind)),n.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),n.push("#define BonesPerMesh "+(r.skeleton?r.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0");const l=r.morphTargetManager;let h=0;l&&l.numInfluencers>0&&(h=l.numInfluencers,n.push("#define MORPHTARGETS"),n.push("#define NUM_MORPH_INFLUENCERS "+h),l.isUsingTextureForTargets&&n.push("#define MORPHTARGETS_TEXTURE"),It.G.PrepareAttributesForMorphTargetsInfluencers(s,r,h)),t&&(n.push("#define INSTANCES"),It.G.PushAttributesForInstances(s),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES"));const c=e._getDrawWrapper(i,!0),d=c.defines,u=n.join("\n");if(d!==u){const e=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];(0,ua.qx)(e),c.setEffect(this.scene.getEngine().createEffect("outline",s,e,["diffuseSampler","morphTargets"],u,void 0,void 0,void 0,{maxSimultaneousMorphTargets:h}),u)}return c.effect.isReady()}_beforeRenderingMesh(e,t,i){if(this._savedDepthWrite=this._engine.getDepthWrite(),e.renderOutline){const n=t.getMaterial();n&&n.needAlphaBlendingForMesh(e)&&(this._engine.cacheStencilState(),this._engine.setDepthWrite(!1),this._engine.setColorWrite(!1),this._engine.setStencilBuffer(!0),this._engine.setStencilOperationPass(7681),this._engine.setStencilFunction(519),this._engine.setStencilMask(kb._StencilReference),this._engine.setStencilFunctionReference(kb._StencilReference),this._engine.stencilStateComposer.useStencilGlobalOnly=!0,this.render(t,i,!0,this._passIdForDrawWrapper[1]),this._engine.setColorWrite(!0),this._engine.setStencilFunction(517)),this._engine.setDepthWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[0]),this._engine.setDepthWrite(this._savedDepthWrite),n&&n.needAlphaBlendingForMesh(e)&&(this._engine.stencilStateComposer.useStencilGlobalOnly=!1,this._engine.restoreStencilState())}}_afterRenderingMesh(e,t,i){if(e.renderOverlay){const e=this._engine.getAlphaMode(),n=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(2),this.render(t,i,!0,this._passIdForDrawWrapper[3]),this._engine.setAlphaMode(e),this._engine.setDepthWrite(this._savedDepthWrite),this._engine.alphaState.alphaBlend=n}e.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[2]),this._engine.setColorWrite(!0))}}kb._StencilReference=4;var Gb;i(4511);class zb{get particleSize(){return this._particleSize}set particleSize(e){e!==this._particleSize&&(this._particleSize=e,this.onParticleSizeChanged.notifyObservers(this))}get useInstancing(){return!this.indexBuffer}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&this._hasVelocity()&&(this._useVelocity=e,this._effectsAreDirty=!0)}_hasVelocity(){var e;return!!(null===(e=this.vertexBuffers)||void 0===e?void 0:e.velocity)}get indexBuffer(){return null}getClassName(){return"FluidRenderingObject"}constructor(e){this.priority=0,this._particleSize=.1,this.onParticleSizeChanged=new r.y$,this.particleThicknessAlpha=.05,this._useVelocity=!1,this._scene=e,this._engine=e.getEngine(),this._effectsAreDirty=!0,this._depthEffectWrapper=null,this._thicknessEffectWrapper=null}_createEffects(){const e=["view","projection","particleRadius","size"],t=["position","offset"],i=[];this._effectsAreDirty=!1,this.useVelocity&&(t.push("velocity"),i.push("#define FLUIDRENDERING_VELOCITY")),this._scene.useRightHandedSystem&&i.push("#define FLUIDRENDERING_RHS"),this._depthEffectWrapper=new Ti({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:i}),e.push("particleAlpha"),this._thicknessEffectWrapper=new Ti({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleThickness",fragmentShader:"fluidRenderingParticleThickness",attributeNames:["position","offset"],uniformNames:e,samplerNames:[]})}isReady(){if(this._effectsAreDirty&&this._createEffects(),!this._depthEffectWrapper||!this._thicknessEffectWrapper)return!1;const e=this._depthEffectWrapper._drawWrapper.effect,t=this._thicknessEffectWrapper._drawWrapper.effect;return e.isReady()&&t.isReady()}renderDepthTexture(){const e=this.numParticles;if(!this._depthEffectWrapper||0===e)return;const t=this._depthEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat2("size",this._particleSize,this._particleSize),i.setFloat("particleRadius",this._particleSize/2),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}renderThicknessTexture(){const e=this.numParticles;if(!this._thicknessEffectWrapper||0===e)return;const t=this._thicknessEffectWrapper._drawWrapper,i=t.effect;this._engine.setAlphaMode(6),this._engine.setDepthWrite(!1),this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat("particleAlpha",this.particleThicknessAlpha),i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0)}renderDiffuseTexture(){}dispose(){var e,t;null===(e=this._depthEffectWrapper)||void 0===e||e.dispose(),null===(t=this._thicknessEffectWrapper)||void 0===t||t.dispose()}}class Wb extends zb{get particleSystem(){return this._particleSystem}getClassName(){return"FluidRenderingObjectParticleSystem"}get useTrueRenderingForDiffuseTexture(){return this._useTrueRenderingForDiffuseTexture}set useTrueRenderingForDiffuseTexture(e){this._useTrueRenderingForDiffuseTexture!==e&&(this._useTrueRenderingForDiffuseTexture=e,e?(this._particleSystem.blendMode=this._blendMode,this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null):(this._particleSystem.blendMode=-1,this._onBeforeDrawParticleObserver=this._particleSystem.onBeforeDrawParticlesObservable.add((()=>{this._engine.setAlphaMode(2)}))))}get vertexBuffers(){return this._particleSystem.vertexBuffers}get indexBuffer(){return this._particleSystem.indexBuffer}constructor(e,t){super(e),this._useTrueRenderingForDiffuseTexture=!0,this._particleSystem=t,this._originalRender=t.render.bind(t),this._blendMode=t.blendMode,this._onBeforeDrawParticleObserver=null,this._updateInAnimate=this._particleSystem.updateInAnimate,this._particleSystem.updateInAnimate=!0,this._particleSystem.render=()=>0,this.particleSize=(t.minSize+t.maxSize)/2,this.useTrueRenderingForDiffuseTexture=!1}isReady(){return super.isReady()&&this._particleSystem.isReady()}get numParticles(){return this._particleSystem.getActiveCount()}renderDiffuseTexture(){this._originalRender()}dispose(){super.dispose(),this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null,this._particleSystem.render=this._originalRender,this._particleSystem.blendMode=this._blendMode,this._particleSystem.updateInAnimate=this._updateInAnimate}}class Hb{get blurNumIterations(){return this._blurNumIterations}set blurNumIterations(e){if(this._blurNumIterations!==e&&(this._blurNumIterations=e,null!==this._blurPostProcesses)){const e=this._blurPostProcesses[0],t=this._blurPostProcesses[1];this._blurPostProcesses=[];for(let i=0;i<2*this._blurNumIterations;++i)this._blurPostProcesses[i]=1&i?t:e}}get renderTarget(){return this._rt}get renderTargetBlur(){return this._rtBlur}get texture(){return this._texture}get textureBlur(){return this._textureBlurred}constructor(e,t,i,n,s,o,a=1,l=6,h=1,c=6,d=!1,u=null,p=!0,f=1){this.enableBlur=!0,this.blurSizeDivisor=1,this.blurFilterSize=7,this._blurNumIterations=3,this.blurMaxFilterSize=100,this.blurDepthScale=10,this.particleSize=.02,this.onDisposeObservable=new r.y$,this._name=e,this._scene=t,this._camera=u,this._engine=t.getEngine(),this._width=i,this._height=n,this._blurTextureSizeX=s,this._blurTextureSizeY=o,this._textureType=a,this._textureFormat=l,this._blurTextureType=h,this._blurTextureFormat=c,this._useStandardBlur=d,this._generateDepthBuffer=p,this._samples=f,this._postProcessRunningIndex=0,this.enableBlur=0!==s&&0!==o,this._rt=null,this._texture=null,this._rtBlur=null,this._textureBlurred=null,this._blurPostProcesses=null}initialize(){if(this.dispose(),this._createRenderTarget(),this.enableBlur&&this._texture){const[e,t,i]=this._createBlurPostProcesses(this._texture,this._blurTextureType,this._blurTextureFormat,this.blurSizeDivisor,this._name,this._useStandardBlur);this._rtBlur=e,this._textureBlurred=t,this._blurPostProcesses=i}}applyBlurPostProcesses(){this.enableBlur&&this._blurPostProcesses&&(this._postProcessRunningIndex=0,this._scene.postProcessManager.directRender(this._blurPostProcesses,this._rtBlur,!0),this._engine.unBindFramebuffer(this._rtBlur))}_createRenderTarget(){this._rt=this._engine.createRenderTargetTexture({width:this._width,height:this._height},{generateMipMaps:!1,type:this._textureType,format:this._textureFormat,samplingMode:1,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTT-${this._name}`});const e=this._rt.texture;e.incrementReferences(),this._texture=new Le(null,this._scene),this._texture.name="rtt"+this._name,this._texture._texture=e,this._texture.wrapU=Le.CLAMP_ADDRESSMODE,this._texture.wrapV=Le.CLAMP_ADDRESSMODE,this._texture.anisotropicFilteringLevel=1}_createBlurPostProcesses(e,t,i,n,s,r=!1){const a=this._scene.getEngine(),l=new o.FM(Math.floor(this._blurTextureSizeX/n),Math.floor(this._blurTextureSizeY/n)),h=1===t&&a.getCaps().textureFloatLinearFiltering||2===t&&a.getCaps().textureHalfFloatLinearFiltering,c=this._engine.createRenderTargetTexture({width:l.x,height:l.y},{generateMipMaps:!1,type:t,format:i,samplingMode:h?2:1,generateDepthBuffer:!1,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTTBlur-${s}`}),d=c.texture;d.incrementReferences();const u=new Le(null,this._scene);if(u.name="rttBlurred"+s,u._texture=d,u.wrapU=Le.CLAMP_ADDRESSMODE,u.wrapV=Le.CLAMP_ADDRESSMODE,u.anisotropicFilteringLevel=1,r){const n=new Zt("BilateralBlurX","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);n.samples=this._samples,n.externalTextureSamplerBinding=!0,n.onApplyObservable.add((t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",n.inputTexture.texture),t.setInt("filterSize",this.blurFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),this._postProcessRunningIndex++})),n.onSizeChangedObservable.add((()=>{n._textures.forEach((e=>{e.texture.wrapU=Le.CLAMP_ADDRESSMODE,e.texture.wrapV=Le.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(n);const s=new Zt("BilateralBlurY","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);s.samples=this._samples,s.onApplyObservable.add((e=>{e.setInt("filterSize",this.blurFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),this._postProcessRunningIndex++})),s.onSizeChangedObservable.add((()=>{s._textures.forEach((e=>{e.texture.wrapU=Le.CLAMP_ADDRESSMODE,e.texture.wrapV=Le.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(s),n.autoClear=!1,s.autoClear=!1;const r=[];for(let e=0;e<2*this._blurNumIterations;++e)r[e]=1&e?s:n;return[c,u,r]}{const n=["maxFilterSize","blurDir","projectedParticleConstant","depthThreshold"],s=new Zt("BilateralBlurX","fluidRenderingBilateralBlur",n,null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);s.samples=this._samples,s.externalTextureSamplerBinding=!0,s.onApplyObservable.add((t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",s.inputTexture.texture),t.setInt("maxFilterSize",this.blurMaxFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),t.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),t.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++})),s.onSizeChangedObservable.add((()=>{s._textures.forEach((e=>{e.texture.wrapU=Le.CLAMP_ADDRESSMODE,e.texture.wrapV=Le.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(s);const r=new Zt("BilateralBlurY","fluidRenderingBilateralBlur",n,null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);r.samples=this._samples,r.onApplyObservable.add((e=>{e.setInt("maxFilterSize",this.blurMaxFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),e.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),e.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++})),r.onSizeChangedObservable.add((()=>{r._textures.forEach((e=>{e.texture.wrapU=Le.CLAMP_ADDRESSMODE,e.texture.wrapV=Le.CLAMP_ADDRESSMODE}))})),this._fixReusablePostProcess(r),s.autoClear=!1,r.autoClear=!1;const o=[];for(let e=0;e<2*this._blurNumIterations;++e)o[e]=1&e?r:s;return[c,u,o]}}_fixReusablePostProcess(e){e.isReusable()&&(e.onActivateObservable.add((()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2})),e.onApplyObservable.add((()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2})))}_getProjectedParticleConstant(){var e,t;return this.blurFilterSize*this.particleSize*.05*(this._height/2)/Math.tan((null!==(t=null===(e=this._camera)||void 0===e?void 0:e.fov)&&void 0!==t?t:45*Math.PI/180)/2)}_getDepthThreshold(){return this.particleSize/2*this.blurDepthScale}dispose(){var e,t,i,n;this.onDisposeObservable.hasObservers()&&this.onDisposeObservable.notifyObservers(this),null===(e=this._rt)||void 0===e||e.dispose(),this._rt=null,null===(t=this._texture)||void 0===t||t.dispose(),this._texture=null,null===(i=this._rtBlur)||void 0===i||i.dispose(),this._rtBlur=null,null===(n=this._textureBlurred)||void 0===n||n.dispose(),this._textureBlurred=null,this._blurPostProcesses&&(this._blurPostProcesses[0].dispose(),this._blurPostProcesses[1].dispose()),this._blurPostProcesses=null}}!function(e){e[e.DepthTexture=0]="DepthTexture",e[e.DepthBlurredTexture=1]="DepthBlurredTexture",e[e.ThicknessTexture=2]="ThicknessTexture",e[e.ThicknessBlurredTexture=3]="ThicknessBlurredTexture",e[e.DiffuseTexture=4]="DiffuseTexture",e[e.Normals=5]="Normals",e[e.DiffuseRendering=6]="DiffuseRendering"}(Gb||(Gb={}));class Xb{get needInitialization(){return this._needInitialization}get generateDiffuseTexture(){return this._generateDiffuseTexture}set generateDiffuseTexture(e){this._generateDiffuseTexture!==e&&(this._generateDiffuseTexture=e,this._needInitialization=!0)}get debugFeature(){return this._debugFeature}set debugFeature(e){this._debugFeature!==e&&(this._needInitialization=!0,this._debugFeature=e)}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._needInitialization=!0)}get environmentMap(){return this._environmentMap}set environmentMap(e){this._environmentMap!==e&&(this._needInitialization=!0,this._environmentMap=e)}get enableBlurDepth(){return this._enableBlurDepth}set enableBlurDepth(e){this._enableBlurDepth!==e&&(this._enableBlurDepth=e,this._needInitialization=!0)}get blurDepthSizeDivisor(){return this._blurDepthSizeDivisor}set blurDepthSizeDivisor(e){this._blurDepthSizeDivisor!==e&&(this._blurDepthSizeDivisor=e,this._needInitialization=!0)}get blurDepthFilterSize(){return this._blurDepthFilterSize}set blurDepthFilterSize(e){this._blurDepthFilterSize!==e&&(this._blurDepthFilterSize=e,this._setBlurParameters())}get blurDepthNumIterations(){return this._blurDepthNumIterations}set blurDepthNumIterations(e){this._blurDepthNumIterations!==e&&(this._blurDepthNumIterations=e,this._setBlurParameters())}get blurDepthMaxFilterSize(){return this._blurDepthMaxFilterSize}set blurDepthMaxFilterSize(e){this._blurDepthMaxFilterSize!==e&&(this._blurDepthMaxFilterSize=e,this._setBlurParameters())}get blurDepthDepthScale(){return this._blurDepthDepthScale}set blurDepthDepthScale(e){this._blurDepthDepthScale!==e&&(this._blurDepthDepthScale=e,this._setBlurParameters())}get enableBlurThickness(){return this._enableBlurThickness}set enableBlurThickness(e){this._enableBlurThickness!==e&&(this._enableBlurThickness=e,this._needInitialization=!0)}get blurThicknessSizeDivisor(){return this._blurThicknessSizeDivisor}set blurThicknessSizeDivisor(e){this._blurThicknessSizeDivisor!==e&&(this._blurThicknessSizeDivisor=e,this._needInitialization=!0)}get blurThicknessFilterSize(){return this._blurThicknessFilterSize}set blurThicknessFilterSize(e){this._blurThicknessFilterSize!==e&&(this._blurThicknessFilterSize=e,this._setBlurParameters())}get blurThicknessNumIterations(){return this._blurThicknessNumIterations}set blurThicknessNumIterations(e){this._blurThicknessNumIterations!==e&&(this._blurThicknessNumIterations=e,this._setBlurParameters())}get useFixedThickness(){return this._useFixedThickness}set useFixedThickness(e){this._useFixedThickness!==e&&(this._useFixedThickness=e,this._needInitialization=!0)}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&(this._useVelocity=e,this._needInitialization=!0,this._onUseVelocityChanged.notifyObservers(this))}get depthMapSize(){return this._depthMapSize}set depthMapSize(e){this._depthMapSize!==e&&(this._depthMapSize=e,this._needInitialization=!0)}get thicknessMapSize(){return this._thicknessMapSize}set thicknessMapSize(e){this._thicknessMapSize!==e&&(this._thicknessMapSize=e,this._needInitialization=!0)}get diffuseMapSize(){return this._diffuseMapSize}set diffuseMapSize(e){this._diffuseMapSize!==e&&(this._diffuseMapSize=e,this._needInitialization=!0)}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._needInitialization=!0)}get camera(){return this._camera}constructor(e,t){this._generateDiffuseTexture=!1,this.fluidColor=new a.Wo(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new o.P(-2,-1,1).normalize(),this._debugFeature=Gb.DepthBlurredTexture,this._debug=!1,this._enableBlurDepth=!0,this._blurDepthSizeDivisor=1,this._blurDepthFilterSize=7,this._blurDepthNumIterations=3,this._blurDepthMaxFilterSize=100,this._blurDepthDepthScale=10,this._enableBlurThickness=!0,this._blurThicknessSizeDivisor=1,this._blurThicknessFilterSize=5,this._blurThicknessNumIterations=1,this._useFixedThickness=!1,this._onUseVelocityChanged=new r.y$,this._useVelocity=!1,this._depthMapSize=null,this._thicknessMapSize=null,this._diffuseMapSize=null,this._samples=1,this._scene=e,this._engine=e.getEngine(),this._camera=null!=t?t:e.activeCamera,this._needInitialization=!0,this._bgDepthTexture=null,this._invProjectionMatrix=new o.y3,this._depthClearColor=new a.HE(1e6,1e6,1e6,1),this._thicknessClearColor=new a.HE(0,0,0,1),this._depthRenderTarget=null,this._diffuseRenderTarget=null,this._thicknessRenderTarget=null,this._renderPostProcess=null}_initialize(){var e,t,i;this.dispose(),this._needInitialization=!1;const n=null!==(e=this._depthMapSize)&&void 0!==e?e:this._engine.getRenderWidth(),s=null!==this._depthMapSize?Math.round(this._depthMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();if(this._depthRenderTarget=new Hb("Depth",this._scene,n,s,n,s,1,7,1,7,!1,this._camera,!0,this._samples),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){const e=null!==(t=this._diffuseMapSize)&&void 0!==t?t:this._engine.getRenderWidth(),i=null!==this._diffuseMapSize?Math.round(this._diffuseMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._diffuseRenderTarget=new Hb("Diffuse",this._scene,e,i,0,0,0,5,0,5,!0,this._camera,!0,this._samples),this._initializeRenderTarget(this._diffuseRenderTarget)}const r=null!==(i=this._thicknessMapSize)&&void 0!==i?i:this._engine.getRenderWidth(),o=null!==this._thicknessMapSize?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new Hb("Thickness",this._scene,r,o,r,o,2,6,2,6,!0,this._camera,!1,this._samples),this._initializeRenderTarget(this._thicknessRenderTarget)),this._createLiquidRenderingPostProcess()}_setBlurParameters(e=null){null!==e&&e!==this._depthRenderTarget||this._setBlurDepthParameters(),null!==e&&e!==this._thicknessRenderTarget||this._setBlurThicknessParameters()}_setBlurDepthParameters(){this._depthRenderTarget&&(this._depthRenderTarget.blurFilterSize=this.blurDepthFilterSize,this._depthRenderTarget.blurMaxFilterSize=this.blurDepthMaxFilterSize,this._depthRenderTarget.blurNumIterations=this.blurDepthNumIterations,this._depthRenderTarget.blurDepthScale=this.blurDepthDepthScale)}_setBlurThicknessParameters(){this._thicknessRenderTarget&&(this._thicknessRenderTarget.blurFilterSize=this.blurThicknessFilterSize,this._thicknessRenderTarget.blurNumIterations=this.blurThicknessNumIterations)}_initializeRenderTarget(e){e!==this._diffuseRenderTarget&&(e.enableBlur=e===this._depthRenderTarget?this.enableBlurDepth:this.enableBlurThickness,e.blurSizeDivisor=e===this._depthRenderTarget?this.blurDepthSizeDivisor:this.blurThicknessSizeDivisor),this._setBlurParameters(e),e.initialize()}_createLiquidRenderingPostProcess(){var e;const t=this._scene.getEngine(),i=["viewMatrix","projectionMatrix","invProjectionMatrix","texelSize","dirLight","cameraFar","density","refractionStrength","fresnelClamp","specularPower"],n=["depthSampler"],s=[];if(this.dispose(!0),!this._camera)return;const r=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,a=new o.FM(1/r.getSize().width,1/r.getSize().height);if(this._scene.useRightHandedSystem&&s.push("#define FLUIDRENDERING_RHS"),null!==this._environmentMap){(null!==(e=this._environmentMap)&&void 0!==e?e:this._scene.environmentTexture)&&(n.push("reflectionSampler"),s.push("#define FLUIDRENDERING_ENVIRONMENT"))}this._diffuseRenderTarget?(n.push("diffuseSampler"),s.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):i.push("diffuseColor"),this._useVelocity&&(n.push("velocitySampler"),s.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(i.push("thickness"),n.push("bgDepthSampler"),s.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(i.push("minimumThickness"),n.push("thicknessSampler")),this._debug&&(s.push("#define FLUIDRENDERING_DEBUG"),this._debugFeature===Gb.Normals?s.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):this._debugFeature===Gb.DiffuseRendering?s.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(s.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),n.push("debugSampler"),this._debugFeature!==Gb.DepthTexture&&this._debugFeature!==Gb.DepthBlurredTexture||s.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new Zt("FluidRendering","fluidRenderingRender",i,n,1,null,2,t,!1,null,0,void 0,void 0,!0,void 0),this._renderPostProcess.updateEffect(s.join("\n")),this._renderPostProcess.samples=this._samples,this._renderPostProcess.onApplyObservable.add((e=>{var i,n,s,r,o,l,h,c,d,u,p,f,_,m,g,v,T,S,E,x,b,C,y;if(this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix()),this._invProjectionMatrix.invert(),t.isWebGPU&&e.setTextureSampler("textureSamplerSampler",this._renderPostProcess.inputTexture.texture),this._depthRenderTarget.enableBlur?(e.setTexture("depthSampler",this._depthRenderTarget.textureBlur),t.isWebGPU&&e.setTextureSampler("depthSamplerSampler",null!==(r=null===(s=this._depthRenderTarget.textureBlur)||void 0===s?void 0:s.getInternalTexture())&&void 0!==r?r:null)):(e.setTexture("depthSampler",this._depthRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("depthSamplerSampler",null!==(n=null===(i=this._depthRenderTarget.texture)||void 0===i?void 0:i.getInternalTexture())&&void 0!==n?n:null)),this._diffuseRenderTarget?this._diffuseRenderTarget.enableBlur?(e.setTexture("diffuseSampler",this._diffuseRenderTarget.textureBlur),t.isWebGPU&&e.setTextureSampler("diffuseSamplerSampler",null!==(c=null===(h=this._diffuseRenderTarget.textureBlur)||void 0===h?void 0:h.getInternalTexture())&&void 0!==c?c:null)):(e.setTexture("diffuseSampler",this._diffuseRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("diffuseSamplerSampler",null!==(l=null===(o=this._diffuseRenderTarget.texture)||void 0===o?void 0:o.getInternalTexture())&&void 0!==l?l:null)):e.setColor3("diffuseColor",this.fluidColor),this._useFixedThickness?(e.setFloat("thickness",this.minimumThickness),e._bindTexture("bgDepthSampler",this._bgDepthTexture),t.isWebGPU&&e.setTextureSampler("bgDepthSamplerSampler",null!==(d=this._bgDepthTexture)&&void 0!==d?d:null)):(this._thicknessRenderTarget.enableBlur?(e.setTexture("thicknessSampler",this._thicknessRenderTarget.textureBlur),t.isWebGPU&&e.setTextureSampler("thicknessSamplerSampler",null!==(_=null===(f=this._thicknessRenderTarget.textureBlur)||void 0===f?void 0:f.getInternalTexture())&&void 0!==_?_:null)):(e.setTexture("thicknessSampler",this._thicknessRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("thicknessSamplerSampler",null!==(p=null===(u=this._thicknessRenderTarget.texture)||void 0===u?void 0:u.getInternalTexture())&&void 0!==p?p:null)),e.setFloat("minimumThickness",this.minimumThickness)),null!==this._environmentMap){const i=null!==(m=this._environmentMap)&&void 0!==m?m:this._scene.environmentTexture;i&&(e.setTexture("reflectionSampler",i),t.isWebGPU&&e.setTextureSampler("reflectionSamplerSampler",null!==(g=null==i?void 0:i.getInternalTexture())&&void 0!==g?g:null))}if(e.setMatrix("viewMatrix",this._scene.getViewMatrix()),e.setMatrix("invProjectionMatrix",this._invProjectionMatrix),e.setMatrix("projectionMatrix",this._scene.getProjectionMatrix()),e.setVector2("texelSize",a),e.setFloat("density",this.density),e.setFloat("refractionStrength",this.refractionStrength),e.setFloat("fresnelClamp",this.fresnelClamp),e.setFloat("specularPower",this.specularPower),e.setVector3("dirLight",this.dirLight),e.setFloat("cameraFar",this._camera.maxZ),this._debug){let i=null;switch(this._debugFeature){case Gb.DepthTexture:i=this._depthRenderTarget.texture;break;case Gb.DepthBlurredTexture:i=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture;break;case Gb.ThicknessTexture:i=null!==(T=null===(v=this._thicknessRenderTarget)||void 0===v?void 0:v.texture)&&void 0!==T?T:null;break;case Gb.ThicknessBlurredTexture:i=(null===(S=this._thicknessRenderTarget)||void 0===S?void 0:S.enableBlur)?null!==(x=null===(E=this._thicknessRenderTarget)||void 0===E?void 0:E.textureBlur)&&void 0!==x?x:null:null!==(C=null===(b=this._thicknessRenderTarget)||void 0===b?void 0:b.texture)&&void 0!==C?C:null;break;case Gb.DiffuseTexture:this._diffuseRenderTarget&&(i=this._diffuseRenderTarget.texture)}this._debugFeature!==Gb.Normals&&(e.setTexture("debugSampler",i),t.isWebGPU&&e.setTextureSampler("debugSamplerSampler",null!==(y=null==i?void 0:i.getInternalTexture())&&void 0!==y?y:null))}}))}_clearTargets(){var e,t,i;(null===(e=this._depthRenderTarget)||void 0===e?void 0:e.renderTarget)&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),this._engine.clear(this._depthClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),(null===(t=this._diffuseRenderTarget)||void 0===t?void 0:t.renderTarget)&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),(null===(i=this._thicknessRenderTarget)||void 0===i?void 0:i.renderTarget)&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!1,!1),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget))}_render(e){var t,i,n,s,r,o;if(this._needInitialization||!e.isReady())return;const a=this._engine._currentRenderTarget;this._engine.setState(!1,void 0,void 0,void 0,!0),this._engine.setDepthBuffer(!0),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0),(null===(t=this._depthRenderTarget)||void 0===t?void 0:t.renderTarget)&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),e.renderDepthTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),(null===(i=this._diffuseRenderTarget)||void 0===i?void 0:i.renderTarget)&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),e.renderDiffuseTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),(null===(n=this._thicknessRenderTarget)||void 0===n?void 0:n.renderTarget)&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),e.renderThicknessTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget)),null===(s=this._depthRenderTarget)||void 0===s||s.applyBlurPostProcesses(),null===(r=this._diffuseRenderTarget)||void 0===r||r.applyBlurPostProcesses(),null===(o=this._thicknessRenderTarget)||void 0===o||o.applyBlurPostProcesses(),a&&this._engine.bindFramebuffer(a)}dispose(e=!1){var t,i,n,s;e||(null===(t=this._depthRenderTarget)||void 0===t||t.dispose(),this._depthRenderTarget=null,null===(i=this._diffuseRenderTarget)||void 0===i||i.dispose(),this._diffuseRenderTarget=null,null===(n=this._thicknessRenderTarget)||void 0===n||n.dispose(),this._thicknessRenderTarget=null),this._renderPostProcess&&this._camera&&this._camera.detachPostProcess(this._renderPostProcess),null===(s=this._renderPostProcess)||void 0===s||s.dispose(),this._renderPostProcess=null,this._needInitialization=!1}}class Yb extends zb{getClassName(){return"FluidRenderingObjectCustomParticles"}get vertexBuffers(){return this._vertexBuffers}constructor(e,t,i){super(e),this._numParticles=i,this._diffuseEffectWrapper=null,this._vertexBuffers={},this.addBuffers(t)}addBuffers(e){for(const t in e){let i,n=!0;switch(t){case"velocity":i=3;break;case"offset":n=!1}this._vertexBuffers[t]=new ne.o(this._engine,e[t],t,!0,!1,i,n)}}_createEffects(){super._createEffects();this._diffuseEffectWrapper=new Ti({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDiffuse",fragmentShader:"fluidRenderingParticleDiffuse",attributeNames:["position","offset","color"],uniformNames:["view","projection","size"],samplerNames:[]})}isReady(){var e,t;return this._vertexBuffers.offset||(this._vertexBuffers.offset=new ne.o(this._engine,[0,0,1,0,0,1,1,1],"offset",!1,!1,2)),super.isReady()&&null!==(t=null===(e=this._diffuseEffectWrapper)||void 0===e?void 0:e.effect.isReady())&&void 0!==t&&t}get numParticles(){return this._numParticles}setNumParticles(e){this._numParticles=e}renderDiffuseTexture(){const e=this.numParticles;if(!this._diffuseEffectWrapper||0===e)return;const t=this._diffuseEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),null!==this._particleSize&&i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}dispose(){var e;super.dispose(),null===(e=this._diffuseEffectWrapper)||void 0===e||e.dispose();for(const t in this._vertexBuffers)this._vertexBuffers[t].dispose();this._vertexBuffers={}}}const jb="copyTextureToTexturePixelShader",Kb="uniform float conversion;\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#include\nvoid main(void) \n{\nvec4 color=texture2D(textureSampler,vUV);\n#ifdef DEPTH_TEXTURE\ngl_FragDepth=color.r;\n#else\nif (conversion==1.) {\ncolor=toLinearSpace(color);\n} else if (conversion==2.) {\ncolor=toGammaSpace(color);\n}\ngl_FragColor=color;\n#endif\n}\n";Ht.v.ShadersStore[jb]=Kb;var qb;!function(e){e[e.None=0]="None",e[e.ToLinearSpace=1]="ToLinearSpace",e[e.ToGammaSpace=2]="ToGammaSpace"}(qb||(qb={}));class $b{_textureIsInternal(e){return void 0===e.getInternalTexture}constructor(e,t=!1){this._engine=e,this._isDepthTexture=t,this._renderer=new vi(e),this._effectWrapper=new Ti({engine:e,name:"CopyTextureToTexture",fragmentShader:"copyTextureToTexture",useShaderStore:!0,uniformNames:["conversion"],samplerNames:["textureSampler"],defines:t?["#define DEPTH_TEXTURE"]:[]}),this._effectWrapper.onApplyObservable.add((()=>{t&&(e.setState(!1),e.setDepthBuffer(!0),e.depthCullingState.depthMask=!0,e.depthCullingState.depthFunc=519),this._textureIsInternal(this._source)?this._effectWrapper.effect._bindTexture("textureSampler",this._source):this._effectWrapper.effect.setTexture("textureSampler",this._source),this._effectWrapper.effect.setFloat("conversion",this._conversion)}))}isReady(){return this._effectWrapper.effect.isReady()}copy(e,t,i=qb.None){if(!this.isReady())return!1;this._source=e,this._conversion=i;const n=this._engine.depthCullingState.depthFunc;return this._renderer.render(this._effectWrapper,t),this._isDepthTexture&&n&&(this._engine.depthCullingState.depthFunc=n),!0}dispose(){this._effectWrapper.dispose(),this._renderer.dispose()}}class Qb{get depthRTWrapper(){return this._depthRTWrapper}constructor(e,t,i,n=1){this._engine=e,this._copyTextureToTexture=new $b(e,!0),this._depthRTWrapper=this._engine.createRenderTargetTexture({width:t,height:i},{generateMipMaps:!1,type:0,format:6,samplingMode:1,generateDepthBuffer:!0,generateStencilBuffer:!1,samples:n,noColorAttachment:!0,label:"FluidRenderingDepthTextureCopyRTT"}),this._depthRTWrapper.createDepthStencilTexture(0,!1,!1,1,void 0,"FluidRenderingDepthTextureCopyRTTDepthStencil")}copy(e){return this._copyTextureToTexture.copy(e,this._depthRTWrapper)}dispose(){this._depthRTWrapper.dispose(),this._copyTextureToTexture.dispose()}}const Zb="fluidRenderingParticleDepthVertexShader",Jb="attribute vec3 position;\nattribute vec2 offset;\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 size;\nvarying vec2 uv;\nvarying vec3 viewPos;\nvarying float sphereRadius;\n#ifdef FLUIDRENDERING_VELOCITY\nattribute vec3 velocity;\nvarying float velocityNorm;\n#endif\nvoid main(void) {\nvec3 cornerPos;\ncornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;\ncornerPos.z=0.0;\nviewPos=(view*vec4(position,1.0)).xyz;\ngl_Position=projection*vec4(viewPos+cornerPos,1.0);\nuv=offset;\nsphereRadius=size.x/2.0;\n#ifdef FLUIDRENDERING_VELOCITY\nvelocityNorm=length(velocity);\n#endif\n}\n";Ht.v.ShadersStore[Zb]=Jb;const eC="fluidRenderingParticleDepthPixelShader",tC="uniform mat4 projection;\nvarying vec2 uv;\nvarying vec3 viewPos;\nvarying float sphereRadius;\n#ifdef FLUIDRENDERING_VELOCITY\nvarying float velocityNorm;\n#endif\nvoid main(void) {\nvec3 normal;\nnormal.xy=uv*2.0-1.0;\nfloat r2=dot(normal.xy,normal.xy);\nif (r2>1.0) discard;\nnormal.z=sqrt(1.0-r2);\n#ifndef FLUIDRENDERING_RHS\nnormal.z=-normal.z;\n#endif\nvec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);\nvec4 clipSpacePos=projection*realViewPos;\n#ifdef WEBGPU\ngl_FragDepth=clipSpacePos.z/clipSpacePos.w;\n#else\ngl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5;\n#endif\n#ifdef FLUIDRENDERING_RHS\nrealViewPos.z=-realViewPos.z;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nglFragColor=vec4(realViewPos.z,velocityNorm,0.,1.);\n#else\nglFragColor=vec4(realViewPos.z,0.,0.,1.);\n#endif\n}\n";Ht.v.ShadersStore[eC]=tC;const iC="fluidRenderingParticleThicknessVertexShader",nC="attribute vec3 position;\nattribute vec2 offset;\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 size;\nvarying vec2 uv;\nvoid main(void) {\nvec3 cornerPos;\ncornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;\ncornerPos.z=0.0;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;\ngl_Position=projection*vec4(viewPos,1.0);\nuv=offset;\n}\n";Ht.v.ShadersStore[iC]=nC;const sC="fluidRenderingParticleThicknessPixelShader",rC="uniform float particleAlpha;\nvarying vec2 uv;\nvoid main(void) {\nvec3 normal;\nnormal.xy=uv*2.0-1.0;\nfloat r2=dot(normal.xy,normal.xy);\nif (r2>1.0) discard;\nfloat thickness=sqrt(1.0-r2);\nglFragColor=vec4(vec3(particleAlpha*thickness),1.0);\n}\n";Ht.v.ShadersStore[sC]=rC;const oC="fluidRenderingParticleDiffuseVertexShader",aC="attribute vec3 position;\nattribute vec2 offset;\nattribute vec4 color;\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 size;\nvarying vec2 uv;\nvarying vec3 diffuseColor;\nvoid main(void) {\nvec3 cornerPos;\ncornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;\ncornerPos.z=0.0;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;\ngl_Position=projection*vec4(viewPos,1.0);\nuv=offset;\ndiffuseColor=color.rgb;\n}\n";Ht.v.ShadersStore[oC]=aC;const lC="fluidRenderingParticleDiffusePixelShader",hC="uniform float particleAlpha;\nvarying vec2 uv;\nvarying vec3 diffuseColor;\nvoid main(void) {\nvec3 normal;\nnormal.xy=uv*2.0-1.0;\nfloat r2=dot(normal.xy,normal.xy);\nif (r2>1.0) discard;\nglFragColor=vec4(diffuseColor,1.0);\n}\n";Ht.v.ShadersStore[lC]=hC;const cC="fluidRenderingBilateralBlurPixelShader",dC="uniform sampler2D textureSampler;\nuniform int maxFilterSize;\nuniform vec2 blurDir;\nuniform float projectedParticleConstant;\nuniform float depthThreshold;\nvarying vec2 vUV;\nvoid main(void) {\nfloat depth=textureLod(textureSampler,vUV,0.).x;\nif (depth>=1e6 || depth<=0.) {\nglFragColor=vec4(vec3(depth),1.);\nreturn;\n}\nint filterSize=min(maxFilterSize,int(ceil(projectedParticleConstant/depth)));\nfloat sigma=float(filterSize)/3.0;\nfloat two_sigma2=2.0*sigma*sigma;\nfloat sigmaDepth=depthThreshold/3.0;\nfloat two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;\nfloat sum=0.;\nfloat wsum=0.;\nfloat sumVel=0.;\nfor (int x=-filterSize; x<=filterSize; ++x) {\nvec2 coords=vec2(x);\nvec2 sampleDepthVel=textureLod(textureSampler,vUV+coords*blurDir,0.).rg;\nfloat r=dot(coords,coords);\nfloat w=exp(-r/two_sigma2);\nfloat rDepth=sampleDepthVel.r-depth;\nfloat wd=exp(-rDepth*rDepth/two_sigmaDepth2);\nsum+=sampleDepthVel.r*w*wd;\nsumVel+=sampleDepthVel.g*w*wd;\nwsum+=w*wd;\n}\nglFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);\n}\n";Ht.v.ShadersStore[cC]=dC;const uC="fluidRenderingStandardBlurPixelShader",pC="uniform sampler2D textureSampler;\nuniform int filterSize;\nuniform vec2 blurDir;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 s=textureLod(textureSampler,vUV,0.);\nif (s.r==0.) {\nglFragColor=vec4(0.,0.,0.,1.);\nreturn;\n}\nfloat sigma=float(filterSize)/3.0;\nfloat twoSigma2=2.0*sigma*sigma;\nvec4 sum=vec4(0.);\nfloat wsum=0.;\nfor (int x=-filterSize; x<=filterSize; ++x) {\nvec2 coords=vec2(x);\nvec4 sampl=textureLod(textureSampler,vUV+coords*blurDir,0.);\nfloat w=exp(-coords.x*coords.x/twoSigma2);\nsum+=sampl*w;\nwsum+=w;\n}\nsum/=wsum;\nglFragColor=vec4(sum.rgb,1.);\n}\n";Ht.v.ShadersStore[uC]=pC;const fC="fluidRenderingRenderPixelShader",_C="/* disable_uniformity_analysis */\n#define IOR 1.333\n#define ETA 1.0/IOR\n#define F0 0.02\nuniform sampler2D textureSampler;\nuniform sampler2D depthSampler;\n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nuniform sampler2D diffuseSampler;\n#else\nuniform vec3 diffuseColor;\n#endif\n#ifdef FLUIDRENDERING_FIXED_THICKNESS\nuniform float thickness;\nuniform sampler2D bgDepthSampler;\n#else\nuniform float minimumThickness;\nuniform sampler2D thicknessSampler;\n#endif\n#ifdef FLUIDRENDERING_ENVIRONMENT\nuniform samplerCube reflectionSampler;\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nuniform sampler2D debugSampler;\n#endif\nuniform mat4 viewMatrix;\nuniform mat4 projectionMatrix;\nuniform mat4 invProjectionMatrix;\nuniform vec2 texelSize;\nuniform vec3 dirLight;\nuniform float cameraFar;\nuniform float density;\nuniform float refractionStrength;\nuniform float fresnelClamp;\nuniform float specularPower;\nvarying vec2 vUV;\nvec3 computeViewPosFromUVDepth(vec2 texCoord,float depth) {\nvec4 ndc;\nndc.xy=texCoord*2.0-1.0;\n#ifdef FLUIDRENDERING_RHS\nndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth;\n#else\nndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth;\n#endif\nndc.w=1.0;\nvec4 eyePos=invProjectionMatrix*ndc;\neyePos.xyz/=eyePos.w;\nreturn eyePos.xyz;\n}\nvec3 getViewPosFromTexCoord(vec2 texCoord) {\nfloat depth=textureLod(depthSampler,texCoord,0.).x;\nreturn computeViewPosFromUVDepth(texCoord,depth);\n}\nvoid main(void) {\nvec2 texCoord=vUV;\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nvec4 color=texture2D(debugSampler,texCoord);\n#ifdef FLUIDRENDERING_DEBUG_DEPTH\nglFragColor=vec4(color.rgb/vec3(2.0),1.);\nif (color.r>0.999 && color.g>0.999) {\nglFragColor=texture2D(textureSampler,texCoord);\n}\n#else\nglFragColor=vec4(color.rgb,1.);\nif (color.r<0.001 && color.g<0.001 && color.b<0.001) {\nglFragColor=texture2D(textureSampler,texCoord);\n}\n#endif\nreturn;\n#endif\nvec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;\nfloat depth=depthVel.r;\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nfloat thickness=texture2D(thicknessSampler,texCoord).x;\n#else\nfloat bgDepth=texture2D(bgDepthSampler,texCoord).x;\nfloat depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;\ndepthNonLinear=depthNonLinear*0.5+0.5;\n#endif\nvec4 backColor=texture2D(textureSampler,texCoord);\n#ifndef FLUIDRENDERING_FIXED_THICKNESS\nif (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) {\n#else\nif (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) {\n#endif\nglFragColor=backColor;\nreturn;\n}\nvec3 viewPos=computeViewPosFromUVDepth(texCoord,depth);\nvec3 ddx=getViewPosFromTexCoord(texCoord+vec2(texelSize.x,0.))-viewPos;\nvec3 ddy=getViewPosFromTexCoord(texCoord+vec2(0.,texelSize.y))-viewPos;\nvec3 ddx2=viewPos-getViewPosFromTexCoord(texCoord+vec2(-texelSize.x,0.));\nif (abs(ddx.z)>abs(ddx2.z)) {\nddx=ddx2;\n}\nvec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));\nif (abs(ddy.z)>abs(ddy2.z)) {\nddy=ddy2;\n}\nvec3 normal=normalize(cross(ddy,ddx));\n#ifdef FLUIDRENDERING_RHS\nnormal=-normal;\n#endif\n#ifndef WEBGPU\nif(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {\nnormal=vec3(0.,0.,-1.);\n}\n#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL)\nglFragColor=vec4(normal*0.5+0.5,1.0);\nreturn;\n#endif\nvec3 rayDir=normalize(viewPos); \n#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nvec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb;\n#endif\nvec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));\nvec3 H =normalize(lightDir-rayDir);\nfloat specular=pow(max(0.0,dot(H,normal)),specularPower);\n#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING\nfloat diffuse =max(0.0,dot(lightDir,normal))*1.0;\nglFragColor=vec4(vec3(0.1) /*ambient*/+vec3(0.42,0.50,1.00)*diffuse+vec3(0,0,0.2)+specular,1.);\nreturn;\n#endif\nvec3 refractionDir=refract(rayDir,normal,ETA);\nvec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0);\nvec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); \nvec3 refractionColor=transmitted.rgb*transmittance;\n#ifdef FLUIDRENDERING_ENVIRONMENT\nvec3 reflectionDir=reflect(rayDir,normal);\nvec3 reflectionColor=(textureCube(reflectionSampler,reflectionDir).rgb);\nfloat fresnel=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,fresnelClamp);\nvec3 finalColor=mix(refractionColor,reflectionColor,fresnel)+specular;\n#else\nvec3 finalColor=refractionColor+specular;\n#endif\n#ifdef FLUIDRENDERING_VELOCITY\nfloat velocity=depthVel.g;\nfinalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0));\n#endif\nglFragColor=vec4(finalColor,transmitted.a);\n}\n";Ht.v.ShadersStore[fC]=_C;function mC(e){return!!e.particleSystem}Object.defineProperty(N.x.prototype,"fluidRenderer",{get:function(){return this._fluidRenderer},set:function(e){this._fluidRenderer=e},enumerable:!0,configurable:!0}),N.x.prototype.enableFluidRenderer=function(){return this._fluidRenderer||(this._fluidRenderer=new vC(this)),this._fluidRenderer},N.x.prototype.disableFluidRenderer=function(){var e;null===(e=this._fluidRenderer)||void 0===e||e.dispose(),this._fluidRenderer=null};class gC{constructor(e){this.name=Se.l.NAME_FLUIDRENDERER,this.scene=e}register(){this.scene._gatherActiveCameraRenderTargetsStage.registerStep(Se.l.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER,this,this._gatherActiveCameraRenderTargets),this.scene._afterCameraDrawStage.registerStep(Se.l.STEP_AFTERCAMERADRAW_FLUIDRENDERER,this,this._afterCameraDraw)}_gatherActiveCameraRenderTargets(e){var t;null===(t=this.scene.fluidRenderer)||void 0===t||t._prepareRendering()}_afterCameraDraw(e){var t;null===(t=this.scene.fluidRenderer)||void 0===t||t._render(e)}rebuild(){this.scene._fluidRenderer&&(this.scene.disableFluidRenderer(),this.scene.enableFluidRenderer())}dispose(){this.scene.disableFluidRenderer()}}class vC{static _SceneComponentInitialization(e){let t=e._getComponent(Se.l.NAME_FLUIDRENDERER);t||(t=new gC(e),e._addComponent(t))}constructor(e){this._scene=e,this._engine=e.getEngine(),this._onEngineResizeObserver=null,this.renderObjects=[],this.targetRenderers=[],this._cameras=new Map,vC._SceneComponentInitialization(this._scene),this._onEngineResizeObserver=this._engine.onResizeObservable.add((()=>{this._initialize()}))}recreate(){this._sortRenderingObjects(),this._initialize()}getRenderObjectFromParticleSystem(e){const t=this._getParticleSystemIndex(e);return-1!==t?this.renderObjects[t]:null}addParticleSystem(e,t,i,n){const s=new Wb(this._scene,e);s.onParticleSizeChanged.add(this._setParticleSizeForRenderTargets.bind(this)),i||(i=new Xb(this._scene,n),this.targetRenderers.push(i)),i._onUseVelocityChanged.hasObservers()||i._onUseVelocityChanged.add(this._setUseVelocityForRenderObject.bind(this)),void 0!==t&&(i.generateDiffuseTexture=t);const r={object:s,targetRenderer:i};return this.renderObjects.push(r),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),r}addCustomParticles(e,t,i,n,s){const r=new Yb(this._scene,e,t);r.onParticleSizeChanged.add(this._setParticleSizeForRenderTargets.bind(this)),n||(n=new Xb(this._scene,s),this.targetRenderers.push(n)),n._onUseVelocityChanged.hasObservers()||n._onUseVelocityChanged.add(this._setUseVelocityForRenderObject.bind(this)),void 0!==i&&(n.generateDiffuseTexture=i);const o={object:r,targetRenderer:n};return this.renderObjects.push(o),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),o}removeRenderObject(e,t=!0){const i=this.renderObjects.indexOf(e);return-1!==i&&(e.object.dispose(),this.renderObjects.splice(i,1),t&&this._removeUnusedTargetRenderers()?this._initialize():this._setParticleSizeForRenderTargets(),!0)}_sortRenderingObjects(){this.renderObjects.sort(((e,t)=>e.object.priorityt.object.priority?1:0))}_removeUnusedTargetRenderers(){const e={};for(let n=0;n{var e;s.inputTexture.depthStencilTexture||s.inputTexture.createDepthStencilTexture(0,!0,this._engine.isStencilEnable,r[0].samples,this._engine.isStencilEnable?13:14,`PostProcessRTTDepthStencil-${s.name}`);for(const t of r){const i=null===(e=t._thicknessRenderTarget)||void 0===e?void 0:e.renderTarget,n=null==i?void 0:i.texture;if(i&&n){const e=n.width+"_"+n.height;let t=o[e];t||(t=o[e]=new Qb(this._engine,n.width,n.height)),t.depthRTWrapper._shareDepth(i)}}}))}t=this._cameras.keys();for(let i=t.next();!0!==i.done;i=t.next()){const t=i.value,n=this._cameras.get(t)[1],s=e.get(t);if(s)for(const e in n)s[1][e]||n[e].dispose();else for(const e in n)n[e].dispose()}this._cameras.clear(),this._cameras=e,this._setParticleSizeForRenderTargets()}_setParticleSizeForRenderTargets(){const e=new Map;for(let t=0;t{t._depthRenderTarget&&(t._depthRenderTarget.particleSize=e)}))}_setUseVelocityForRenderObject(){for(const e of this.renderObjects)e.object.useVelocity=e.targetRenderer.useVelocity}_prepareRendering(){for(const e of this.targetRenderers)if(e.needInitialization)return void this._initialize()}_render(e){var t;for(let n=0;n{const t=e[1];for(const i in t)t[i].dispose()})),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()}}class TC{get animationStarted(){return this._animationStarted}get fromIndex(){return this._fromIndex}get toIndex(){return this._toIndex}get loopAnimation(){return this._loopAnimation}get delay(){return Math.max(this._delay,1)}constructor(){this.width=1,this.height=1,this.angle=0,this.invertU=!1,this.invertV=!1,this.isVisible=!0,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._time=0,this._onBaseAnimationEnd=null,this.position={x:1,y:1,z:1},this.color={r:1,g:1,b:1,a:1}}playAnimation(e,t,i,n,s){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=n||1,this._animationStarted=!0,this._onBaseAnimationEnd=s,ethis._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,(this._direction>0&&this.cellIndex>this._toIndex||this._direction<0&&this.cellIndex0?this._fromIndex:this._toIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onBaseAnimationEnd&&this._onBaseAnimationEnd()))))}}class SC extends TC{get size(){return this.width}set size(e){this.width=e,this.height=e}get manager(){return this._manager}constructor(e,t){super(),this.name=e,this.animations=new Array,this.isPickable=!1,this.useAlphaForPicking=!1,this.onDisposeObservable=new r.y$,this._onAnimationEnd=null,this._endAnimation=()=>{this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()},this.color=new a.HE(1,1,1,1),this.position=o.P.Zero(),this._manager=t,this._manager.sprites.push(this),this.uniqueId=this._manager.scene.getUniqueId()}getClassName(){return"Sprite"}get fromIndex(){return this._fromIndex}set fromIndex(e){this.playAnimation(e,this._toIndex,this._loopAnimation,this._delay,this._onAnimationEnd)}get toIndex(){return this._toIndex}set toIndex(e){this.playAnimation(this._fromIndex,e,this._loopAnimation,this._delay,this._onAnimationEnd)}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){this.playAnimation(this._fromIndex,this._toIndex,e,this._delay,this._onAnimationEnd)}get delay(){return Math.max(this._delay,1)}set delay(e){this.playAnimation(this._fromIndex,this._toIndex,this._loopAnimation,e,this._onAnimationEnd)}playAnimation(e,t,i,n,s=null){this._onAnimationEnd=s,super.playAnimation(e,t,i,n,this._endAnimation)}dispose(){for(let e=0;e0)for(let r=0;r=s.distance))&&(s=a,i)))break}return s||new je.p},N.x.prototype._internalMultiPickSprites=function(e,t,i){if(!je.p)return null;let n=new Array;if(!i){if(!this.activeCamera)return null;i=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let s=0;s!!e.actionManager&&(e.isPickable&&e.actionManager.hasPointerTriggers)}register(){this.scene._pointerMoveStage.registerStep(Se.l.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(Se.l.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(Se.l.STEP_POINTERUP_SPRITE,this,this._pointerUp)}rebuild(){}dispose(){this.scene.onBeforeSpritesRenderingObservable.clear(),this.scene.onAfterSpritesRenderingObservable.clear();const e=this.scene.spriteManagers;if(e)for(;e.length;)e[0].dispose()}_pickSpriteButKeepRay(e,t,i,n,s){const r=this.scene.pickSprite(t,i,this._spritePredicate,n,s);return r&&(r.ray=e?e.ray:null),r}_pointerMove(e,t,i,n,s){const r=this.scene;return n?r.setPointerOverSprite(null):(i=this._pickSpriteButKeepRay(i,e,t,!1,r.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite?(r.setPointerOverSprite(i.pickedSprite),!r.doNotHandleCursors&&s&&(r._pointerOverSprite&&r._pointerOverSprite.actionManager&&r._pointerOverSprite.actionManager.hoverCursor?s.style.cursor=r._pointerOverSprite.actionManager.hoverCursor:s.style.cursor=r.hoverCursor)):r.setPointerOverSprite(null),i}_pointerDown(e,t,i,n){const s=this.scene;if(s._pickedDownSprite=null,s.spriteManagers&&s.spriteManagers.length>0&&(i=s.pickSprite(e,t,this._spritePredicate,!1,s.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager){switch(s._pickedDownSprite=i.pickedSprite,n.button){case 0:i.pickedSprite.actionManager.processTrigger(2,c.V.CreateNewFromSprite(i.pickedSprite,s,n));break;case 1:i.pickedSprite.actionManager.processTrigger(4,c.V.CreateNewFromSprite(i.pickedSprite,s,n));break;case 2:i.pickedSprite.actionManager.processTrigger(3,c.V.CreateNewFromSprite(i.pickedSprite,s,n))}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(5,c.V.CreateNewFromSprite(i.pickedSprite,s,n))}return i}_pointerUp(e,t,i,n,s){const r=this.scene;if(r.spriteManagers&&r.spriteManagers.length>0){const i=r.pickSprite(e,t,this._spritePredicate,!1,r.cameraToUseForPointers||void 0);i&&(i.hit&&i.pickedSprite&&i.pickedSprite.actionManager&&(i.pickedSprite.actionManager.processTrigger(7,c.V.CreateNewFromSprite(i.pickedSprite,r,n)),i.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||i.pickedSprite.actionManager.processTrigger(1,c.V.CreateNewFromSprite(i.pickedSprite,r,n)),s&&i.pickedSprite.actionManager.processTrigger(6,c.V.CreateNewFromSprite(i.pickedSprite,r,n)))),r._pickedDownSprite&&r._pickedDownSprite.actionManager&&r._pickedDownSprite!==i.pickedSprite&&r._pickedDownSprite.actionManager.processTrigger(16,c.V.CreateNewFromSprite(r._pickedDownSprite,r,n)))}return i}}const xC="imageProcessingCompatibility",bC="#ifdef IMAGEPROCESSINGPOSTPROCESS\ngl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2));\n#endif\n";Ht.v.IncludesShadersStore[xC]=bC;const CC="spritesPixelShader",yC="uniform bool alphaTest;\nvarying vec4 vColor;\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#ifdef PIXEL_PERFECT\nvec2 uvPixelPerfect(vec2 uv) {\nvec2 res=vec2(textureSize(diffuseSampler,0));\nuv=uv*res;\nvec2 seam=floor(uv+0.5);\nuv=seam+clamp((uv-seam)/fwidth(uv),-0.5,0.5);\nreturn uv/res;\n}\n#endif\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#ifdef PIXEL_PERFECT\nvec2 uv=uvPixelPerfect(vUV);\n#else\nvec2 uv=vUV;\n#endif\nvec4 color=texture2D(diffuseSampler,uv);\nfloat fAlphaTest=float(alphaTest);\nif (fAlphaTest != 0.)\n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include\ngl_FragColor=color;\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ht.v.ShadersStore[CC]=yC;const AC="spritesVertexShader",RC="attribute vec4 position;\nattribute vec2 options;\nattribute vec2 offsets;\nattribute vec2 inverts;\nattribute vec4 cellInfo;\nattribute vec4 color;\nuniform mat4 view;\nuniform mat4 projection;\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=offsets.xy;\ncornerPos=vec2(offset.x-0.5,offset.y -0.5)*size;\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));\nvec2 uvPlace=cellInfo.xy;\nvec2 uvSize=cellInfo.zw;\nvUV.x=uvPlace.x+uvSize.x*uvOffset.x;\nvUV.y=uvPlace.y+uvSize.y*uvOffset.y;\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}";Ht.v.ShadersStore[AC]=RC;class PC{get capacity(){return this._capacity}get pixelPerfect(){return this._pixelPerfect}set pixelPerfect(e){this._pixelPerfect!==e&&(this._pixelPerfect=e,this._createEffects())}constructor(e,t,i=.01,n=null){this.blendMode=2,this.autoResetAlpha=!0,this.disableDepthWrite=!1,this.fogEnabled=!0,this._pixelPerfect=!1,this._useVAO=!1,this._useInstancing=!1,this._vertexBuffers={},this._capacity=t,this._epsilon=i,this._engine=e,this._useInstancing=e.getCaps().instancedArrays&&e._features.supportSpriteInstancing,this._useVAO=e.getCaps().vertexArrayObject&&!e.disableVertexArrayObjects,this._scene=n,this._useInstancing||this._buildIndexBuffer(),this._vertexBufferSize=this._useInstancing?16:18,this._vertexData=new Float32Array(t*this._vertexBufferSize*(this._useInstancing?1:4)),this._buffer=new ne.l(e,this._vertexData,!0,this._vertexBufferSize);const s=this._buffer.createVertexBuffer(ne.o.PositionKind,0,4,this._vertexBufferSize,this._useInstancing),r=this._buffer.createVertexBuffer("options",4,2,this._vertexBufferSize,this._useInstancing);let o,a=6;if(this._useInstancing){const t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new ne.l(e,t,!1,2),o=this._spriteBuffer.createVertexBuffer("offsets",0,2)}else o=this._buffer.createVertexBuffer("offsets",a,2,this._vertexBufferSize,this._useInstancing),a+=2;const l=this._buffer.createVertexBuffer("inverts",a,2,this._vertexBufferSize,this._useInstancing),h=this._buffer.createVertexBuffer("cellInfo",a+2,4,this._vertexBufferSize,this._useInstancing),c=this._buffer.createVertexBuffer(ne.o.ColorKind,a+6,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[ne.o.PositionKind]=s,this._vertexBuffers.options=r,this._vertexBuffers.offsets=o,this._vertexBuffers.inverts=l,this._vertexBuffers.cellInfo=h,this._vertexBuffers[ne.o.ColorKind]=c,this._createEffects()}_createEffects(){var e,t,i,n;null===(e=this._drawWrapperBase)||void 0===e||e.dispose(),null===(t=this._drawWrapperFog)||void 0===t||t.dispose(),null===(i=this._drawWrapperDepth)||void 0===i||i.dispose(),null===(n=this._drawWrapperFogDepth)||void 0===n||n.dispose(),this._drawWrapperBase=new $t.q(this._engine),this._drawWrapperFog=new $t.q(this._engine),this._drawWrapperDepth=new $t.q(this._engine,!1),this._drawWrapperFogDepth=new $t.q(this._engine,!1),this._drawWrapperBase.drawContext&&(this._drawWrapperBase.drawContext.useInstancing=this._useInstancing),this._drawWrapperFog.drawContext&&(this._drawWrapperFog.drawContext.useInstancing=this._useInstancing),this._drawWrapperDepth.drawContext&&(this._drawWrapperDepth.drawContext.useInstancing=this._useInstancing),this._drawWrapperFogDepth.drawContext&&(this._drawWrapperFogDepth.drawContext.useInstancing=this._useInstancing);const s=this._pixelPerfect?"#define PIXEL_PERFECT\n":"";this._drawWrapperBase.effect=this._engine.createEffect("sprites",[ne.o.PositionKind,"options","offsets","inverts","cellInfo",ne.o.ColorKind],["view","projection","textureInfos","alphaTest"],["diffuseSampler"],s),this._drawWrapperDepth.effect=this._drawWrapperBase.effect,this._drawWrapperDepth.materialContext=this._drawWrapperBase.materialContext,this._scene&&(this._drawWrapperFog.effect=this._scene.getEngine().createEffect("sprites",[ne.o.PositionKind,"options","offsets","inverts","cellInfo",ne.o.ColorKind],["view","projection","textureInfos","alphaTest","vFogInfos","vFogColor"],["diffuseSampler"],s+"#define FOG"),this._drawWrapperFogDepth.effect=this._drawWrapperFog.effect,this._drawWrapperFogDepth.materialContext=this._drawWrapperFog.materialContext)}render(e,t,i,n,s=null){if(!this.texture||!this.texture.isReady()||!e.length)return;let r=this._drawWrapperBase,o=this._drawWrapperDepth,a=!1;this.fogEnabled&&this._scene&&this._scene.fogEnabled&&0!==this._scene.fogMode&&(r=this._drawWrapperFog,o=this._drawWrapperFogDepth,a=!0);const l=r.effect;if(!l.isReady())return;const h=this._engine,c=!(!this._scene||!this._scene.useRightHandedSystem),d=this.texture.getBaseSize(),u=Math.min(this._capacity,e.length);let p=0,f=!0;for(let v=0;v>0;t._xOffset=(t.cellIndex-i*e)*this.cellWidth/s.width,t._yOffset=i*this.cellHeight/s.height,t._xSize=this.cellWidth,t._ySize=this.cellHeight}this._vertexData[a]=t.position.x,this._vertexData[a+1]=t.position.y,this._vertexData[a+2]=t.position.z,this._vertexData[a+3]=t.angle,this._vertexData[a+4]=t.width,this._vertexData[a+5]=t.height,this._useInstancing?a-=2:(this._vertexData[a+6]=i,this._vertexData[a+7]=n),this._vertexData[a+8]=r?t.invertU?0:1:t.invertU?1:0,this._vertexData[a+9]=t.invertV?1:0,this._vertexData[a+10]=t._xOffset,this._vertexData[a+11]=t._yOffset,this._vertexData[a+12]=t._xSize/s.width,this._vertexData[a+13]=t._ySize/s.height,this._vertexData[a+14]=t.color.r,this._vertexData[a+15]=t.color.g,this._vertexData[a+16]=t.color.b,this._vertexData[a+17]=t.color.a}_buildIndexBuffer(){const e=[];let t=0;for(let i=0;i{e.cellRef||(e.cellIndex=0);const i=e.cellIndex;"number"==typeof i&&isFinite(i)&&Math.floor(i)===i&&(e.cellRef=this._spriteMap[e.cellIndex]),e._xOffset=this._cellData[e.cellRef].frame.x/t.width,e._yOffset=this._cellData[e.cellRef].frame.y/t.height,e._xSize=this._cellData[e.cellRef].frame.w,e._ySize=this._cellData[e.cellRef].frame.h},s||(s=m.l.LastCreatedScene),s._getComponent(Se.l.NAME_SPRITE)||s._addComponent(new EC(s)),this._fromPacked=l,this._scene=s;const c=this._scene.getEngine();if(this._spriteRenderer=new PC(c,i,o,s),n.width&&n.height)this.cellWidth=n.width,this.cellHeight=n.height;else{if(void 0===n)return void(this._spriteRenderer=null);this.cellWidth=n,this.cellHeight=n}this._scene.spriteManagers&&this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),t&&(this.texture=new Le(t,s,!0,!1,a)),this._fromPacked&&this._makePacked(t,h)}getClassName(){return"SpriteManager"}_makePacked(e,t){if(null!==t)try{let e;if(e="string"==typeof t?JSON.parse(t):t,e.frames.length){const t={};for(let i=0;i0);const s=e.substring(0,n-1)+".json",r=()=>{p.Y.Error("JSON ERROR: Unable to load JSON file."),this._fromPacked=!1,this._packedAndReady=!1},o=e=>{try{const t=JSON.parse(e),i=Reflect.ownKeys(t.frames);this._spriteMap=i,this._packedAndReady=!0,this._cellData=t.frames}catch(i){throw this._fromPacked=!1,this._packedAndReady=!1,new Error("Invalid JSON format. Please check documentation for format specifications.")}};se.w1.LoadFile(s,o,void 0,void 0,!1,r)}}_checkTextureAlpha(e,t,i,n,s){if(!e.useAlphaForPicking||!this.texture)return!0;const r=this.texture.getSize();this._textureContent||(this._textureContent=new Uint8Array(r.width*r.height*4),this.texture.readPixels(0,0,this._textureContent));const a=o.jp.Vector3[0];a.copyFrom(t.direction),a.normalize(),a.scaleInPlace(i),a.addInPlace(t.origin);const l=(a.x-n.x)/(s.x-n.x),h=1-(a.y-n.y)/(s.y-n.y),c=e._xOffset*r.width+l*e._xSize|0,d=e._yOffset*r.height+h*e._ySize|0;return this._textureContent[4*(c+d*r.width)+3]>.5}intersects(e,t,i,n){const s=Math.min(this.capacity,this.sprites.length),r=o.P.Zero(),a=o.P.Zero();let l=Number.MAX_VALUE,h=null;const c=o.jp.Vector3[0],d=o.jp.Vector3[1],u=t.getViewMatrix();let p=e,f=e;for(let _=0;_e){if(!this._checkTextureAlpha(t,p,e,r,a))continue;if(f=p,l=e,h=t,n)break}}}}if(h){const e=new je.p;u.invertToRef(o.jp.Matrix[0]),e.hit=!0,e.pickedSprite=h,e.distance=l;const t=o.jp.Vector3[2];return t.copyFrom(f.direction),t.normalize(),t.scaleInPlace(l),f.origin.addToRef(t,c),e.pickedPoint=o.P.TransformCoordinates(c,o.jp.Matrix[0]),e}return null}multiIntersects(e,t,i){const n=Math.min(this.capacity,this.sprites.length),s=o.P.Zero(),r=o.P.Zero();let a;const l=[],h=o.jp.Vector3[0].copyFromFloats(0,0,0),c=o.jp.Vector3[1].copyFromFloats(0,0,0),d=t.getViewMatrix();for(let u=0;u{const o=new y.g;o.addEventListener("readystatechange",(()=>{if(4==o.readyState)if(200==o.status){const t=JSON.parse(o.responseText),r=IC.Parse(t,i||m.l.LastCreatedScene,n);e&&(r.name=e),s(r)}else r("Unable to load the sprite manager")})),o.open("GET",t),o.send()}))}static ParseFromSnippetAsync(e,t,i=""){return"_BLANK"===e?Promise.resolve(new IC("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,t)):new Promise(((n,s)=>{const r=new y.g;r.addEventListener("readystatechange",(()=>{if(4==r.readyState)if(200==r.status){const s=JSON.parse(JSON.parse(r.responseText).jsonPayload),o=JSON.parse(s.spriteManager),a=IC.Parse(o,t||m.l.LastCreatedScene,i);a.snippetId=e,n(a)}else s("Unable to load the snippet "+e)})),r.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),r.send()}))}}IC.SnippetUrl="https://snippet.babylonjs.com",IC.CreateFromSnippetAsync=IC.ParseFromSnippetAsync;const MC="spriteMapPixelShader",OC="#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nprecision highp float;\nvarying vec3 vPosition;\nvarying vec2 vUV;\nvarying vec2 tUV;\nuniform float time;\nuniform float spriteCount;\nuniform sampler2D spriteSheet;\nuniform vec2 spriteMapSize;\nuniform vec2 outputSize;\nuniform vec2 stageSize;\nuniform sampler2D frameMap;\nuniform sampler2D tileMaps[LAYERS];\nuniform sampler2D animationMap;\nuniform vec3 colorMul;\nfloat mt;\nconst float fdStep=1./4.;\nconst float aFrameSteps=1./MAX_ANIMATION_FRAMES;\nmat4 getFrameData(float frameID){\nfloat fX=frameID/spriteCount;\nreturn mat4(\ntexture2D(frameMap,vec2(fX,0.),0.),\ntexture2D(frameMap,vec2(fX,fdStep*1.),0.),\ntexture2D(frameMap,vec2(fX,fdStep*2.),0.),\nvec4(0.)\n);\n}\nvoid main(){\nvec4 color=vec4(0.);\nvec2 tileUV=fract(tUV);\n#ifdef FLIPU\ntileUV.y=1.0-tileUV.y;\n#endif\nvec2 tileID=floor(tUV);\nvec2 sheetUnits=1./spriteMapSize;\nfloat spriteUnits=1./spriteCount;\nvec2 stageUnits=1./stageSize;\nfor(int i=0; i0.) {\nmt=mod(time*animationData.z,1.0);\nfor(float f=0.; fmt){\nframeID=animationData.x;\nbreak;\n}\nanimationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.);\n}\n}\nmat4 frameData=getFrameData(frameID+0.5);\nvec2 frameSize=(frameData[0].zw)/spriteMapSize;\nvec2 offset=frameData[0].xy*sheetUnits;\nvec2 ratio=frameData[2].xy/frameData[0].zw;\nif (frameData[2].z==1.){\ntileUV.xy=tileUV.yx;\n}\nvec4 nc=texture2D(spriteSheet,tileUV*frameSize+offset);\nif (i==0){\ncolor=nc;\n} else {\nfloat alpha=min(color.a+nc.a,1.0);\nvec3 mixed=mix(color.xyz,nc.xyz,nc.a);\ncolor=vec4(mixed,alpha);\n}\n}\ncolor.xyz*=colorMul;\ngl_FragColor=color;\n}";Ht.v.ShadersStore[MC]=OC;const DC="spriteMapVertexShader",NC="precision highp float;\nattribute vec3 position;\nattribute vec3 normal;\nattribute vec2 uv;\nvarying vec3 vPosition;\nvarying vec2 vUV;\nvarying vec2 tUV;\nvarying vec2 stageUnits;\nvarying vec2 levelUnits;\nvarying vec2 tileID;\nuniform float time;\nuniform mat4 worldViewProjection;\nuniform vec2 outputSize;\nuniform vec2 stageSize;\nuniform vec2 spriteMapSize;\nuniform float stageScale;\nvoid main() {\nvec4 p=vec4( position,1. );\nvPosition=p.xyz;\nvUV=uv;\ntUV=uv*stageSize; \ngl_Position=worldViewProjection*p;\n}";Ht.v.ShadersStore[DC]=NC;var FC;i(6184),i(2320),i(5776);!function(e){e[e.INIT=0]="INIT",e[e.RUNNING=1]="RUNNING",e[e.DONE=2]="DONE",e[e.ERROR=3]="ERROR"}(FC||(FC={}));class wC{get resolve(){return this._resolve}get reject(){return this._reject}constructor(){this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}}i(3392);r.y$.prototype.notifyObserversWithPromise=async function(e,t=-1,i,n,s){let r=Promise.resolve(e);if(!this.observers.length)return r;const o=this._eventState;return o.mask=t,o.target=i,o.currentTarget=n,o.skipNextObservers=!1,o.userInfo=s,this.observers.forEach((i=>{o.skipNextObservers||i._willBeUnregistered||i.mask&t&&(r=i.scope?r.then((t=>(o.lastReturnValue=t,i.callback.apply(i.scope,[e,o])))):r.then((t=>(o.lastReturnValue=t,i.callback(e,o)))),i.unregisterOnNextCall&&this._deferUnregister(i))})),await r,e};i(4441);class LC{getDescription(){return""}apply(e,t){return!0}constructor(e=0){this.priority=e}}class BC extends LC{constructor(){super(...arguments),this._canBeMerged=e=>{if(!(e instanceof ee.Kj))return!1;const t=e;return!t.isDisposed()&&(!(!t.isVisible||!t.isEnabled())&&(!(t.instances.length>0)&&(!t.skeleton&&!t.hasLODLevels&&0!==t.getTotalVertices())))}}static get UpdateSelectionTree(){return BC._UpdateSelectionTree}static set UpdateSelectionTree(e){BC._UpdateSelectionTree=e}getDescription(){return"Merging similar meshes together"}apply(e,t,i){const n=e.meshes.slice(0);let s=n.length;for(let o=0;o{e.doNotSerialize||(t.vertexData.push(e.serializeVerticeData()),UC[e.id]=!0)},kC=(e,t)=>{const i={},n=e._geometry;return n&&(e.getScene().getGeometryById(n.id)||VC(n,t.geometries)),e.serialize&&e.serialize(i),i};class GC{static ClearCache(){UC=[]}static Serialize(e){return GC._Serialize(e)}static _Serialize(e,t=!0){const i={};if(t&&!e.getEngine()._features.supportSyncTextureRead&&Le.ForceSerializeBuffers&&console.warn("The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead."),GC.ClearCache(),i.useDelayedTextureLoading=e.useDelayedTextureLoading,i.autoClear=e.autoClear,i.clearColor=e.clearColor.asArray(),i.ambientColor=e.ambientColor.asArray(),i.gravity=e.gravity.asArray(),i.collisionsEnabled=e.collisionsEnabled,i.useRightHandedSystem=e.useRightHandedSystem,e.fogMode&&0!==e.fogMode&&(i.fogMode=e.fogMode,i.fogColor=e.fogColor.asArray(),i.fogStart=e.fogStart,i.fogEnd=e.fogEnd,i.fogDensity=e.fogDensity),e.isPhysicsEnabled()){const t=e.getPhysicsEngine();t&&(i.physicsEnabled=!0,i.physicsGravity=t.gravity.asArray(),i.physicsEngine=t.getPhysicsPluginName())}e.metadata&&(i.metadata=e.metadata),i.morphTargetManagers=[];for(const a of e.meshes){const e=a.morphTargetManager;e&&i.morphTargetManagers.push(e.serialize())}let n,s,r;for(i.lights=[],n=0;n0){i.animationGroups=[];for(let t=0;t0)for(i.reflectionProbes=[],n=0;nt))}static _CollectPromises(e,t){if(Array.isArray(e))for(let i=0;ie[i]=t))):(n instanceof Object||Array.isArray(n))&&this._CollectPromises(n,t)}else if(e instanceof Object)for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)){const n=e[i];n instanceof Promise?t.push(n.then((t=>e[i]=t))):(n instanceof Object||Array.isArray(n))&&this._CollectPromises(n,t)}}static SerializeMesh(e,t=!1,i=!1){const n={};if(GC.ClearCache(),e=e instanceof Array?e:[e],t||i)for(let s=0;s{t instanceof ee.Kj&&e.indexOf(t)<0&&!t.doNotSerialize&&e.push(t)})),t&&e[s].parent&&e.indexOf(e[s].parent)<0&&!e[s].parent.doNotSerialize&&e.push(e[s].parent);return e.forEach((e=>{((e,t)=>{if(1===e.delayLoadState||0===e.delayLoadState){const i=i=>{t.materials=t.materials||[],e.material&&!t.materials.some((t=>t.id===e.material.id))&&t.materials.push(i.serialize())};if(e.material&&!e.material.doNotSerialize)if(e.material instanceof zg.G){if(t.multiMaterials=t.multiMaterials||[],!t.multiMaterials.some((t=>t.id===e.material.id))){t.multiMaterials.push(e.material.serialize());for(const t of e.material.subMaterials)t&&i(t)}}else i(e.material);else e.material||i(e.getScene().defaultMaterial);const n=e._geometry;n&&(t.geometries||(t.geometries={},t.geometries.boxes=[],t.geometries.spheres=[],t.geometries.cylinders=[],t.geometries.toruses=[],t.geometries.grounds=[],t.geometries.planes=[],t.geometries.torusKnots=[],t.geometries.vertexData=[]),VC(n,t.geometries)),e.skeleton&&!e.skeleton.doNotSerialize&&(t.skeletons=t.skeletons||[],t.skeletons.push(e.skeleton.serialize())),t.meshes=t.meshes||[],t.meshes.push(kC(e,t))}})(e,n)})),n}}class zC{static IsSupported(e){const t=e.getRenderingCanvas();return!!t&&"function"==typeof t.captureStream}get isRecording(){return!!this._canvas&&this._canvas.isRecording}constructor(e,t={}){if(!zC.IsSupported(e))throw"Your browser does not support recording so far.";const i=e.getRenderingCanvas();if(!i)throw"The babylon engine must have a canvas to be recorded";this._canvas=i,this._canvas.isRecording=!1,this._options=Object.assign(Object.assign({},zC._DefaultOptions),t);const n=this._canvas.captureStream(this._options.fps);if(this._options.audioTracks)for(const s of this._options.audioTracks)n.addTrack(s);this._mediaRecorder=new MediaRecorder(n,{mimeType:this._options.mimeType}),this._mediaRecorder.ondataavailable=this._handleDataAvailable.bind(this),this._mediaRecorder.onerror=this._handleError.bind(this),this._mediaRecorder.onstop=this._handleStop.bind(this)}stopRecording(){this._canvas&&this._mediaRecorder&&this.isRecording&&(this._canvas.isRecording=!1,this._mediaRecorder.stop())}startRecording(e="babylonjs.webm",t=7){if(!this._canvas||!this._mediaRecorder)throw"Recorder has already been disposed";if(this.isRecording)throw"Recording already in progress";return t>0&&setTimeout((()=>{this.stopRecording()}),1e3*t),this._fileName=e,this._recordedChunks=[],this._resolve=null,this._reject=null,this._canvas.isRecording=!0,this._mediaRecorder.start(this._options.recordChunckSize),new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}dispose(){this._canvas=null,this._mediaRecorder=null,this._recordedChunks=[],this._fileName=null,this._resolve=null,this._reject=null}_handleDataAvailable(e){e.data.size>0&&this._recordedChunks.push(e.data)}_handleError(e){if(this.stopRecording(),!this._reject)throw new e.error;this._reject(e.error)}_handleStop(){this.stopRecording();const e=new Blob(this._recordedChunks);this._resolve&&this._resolve(e),window.URL.createObjectURL(e),this._fileName&&se.w1.Download(e,this._fileName)}}zC._DefaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3};let WC=null;function HC(e,t,i,n,s="image/png",r=!1,o){const{height:a,width:l}=KC(e,t,i);if(!a||!l)return void p.Y.Error("Invalid 'size' parameter !");WC||(WC=document.createElement("canvas")),WC.width=l,WC.height=a;const h=WC.getContext("2d"),c=e.getRenderWidth()/e.getRenderHeight();let d=l,u=d/c;u>a&&(u=a,d=u*c);const f=Math.max(0,l-d)/2,_=Math.max(0,a-u)/2;t.getScene().activeCamera!==t?YC(e,t,i,(e=>{if(r){const t=new Blob([e]);se.w1.DownloadBlob(t),n&&n("")}else n&&n(e)}),s,1,e.getCreationOptions().antialias,void 0,void 0,void 0,void 0,o):e.onEndFrameObservable.addOnce((()=>{const t=e.getRenderingCanvas();h&&t&&h.drawImage(t,f,_,d,u),WC&&(r?(se.w1.EncodeScreenshotCanvasData(WC,void 0,s,void 0,o),n&&n("")):se.w1.EncodeScreenshotCanvasData(WC,n,s,void 0,o))}))}function XC(e,t,i,n="image/png",s){return new Promise(((r,o)=>{HC(e,t,i,(e=>{void 0!==e?r(e):o(new Error("Data is undefined"))}),n,void 0,s)}))}function YC(e,t,i,n,s="image/png",r=1,o=!1,a,l=!1,h=!1,c=!0,d){const{height:u,width:f,finalWidth:_,finalHeight:m}=KC(e,t,i),g={width:f,height:u};if(!u||!f)return void p.Y.Error("Invalid 'size' parameter !");const v={width:e.getRenderWidth(),height:e.getRenderHeight()};e.setSize(f,u);const T=t.getScene(),S=new Ci("screenShot",g,T,!1,!1,0,!1,Le.BILINEAR_SAMPLINGMODE,void 0,h,void 0,void 0,void 0,r);S.renderList=T.meshes.slice(),S.samples=r,S.renderSprites=l,S.activeCamera=t,S.forceLayerMaskCheck=c;const E=()=>{e.onEndFrameObservable.addOnce((()=>{_===f&&m===u?S.readPixels(void 0,void 0,void 0,!1).then((e=>{bi.DumpData(f,u,e,n,s,a,!0,void 0,d),S.dispose()})):wh("pass",S.getInternalTexture(),T,void 0,void 0,void 0,_,m).then((t=>{e._readTexturePixels(t,_,m,-1,0,null,!0,!1,0,0).then((e=>{bi.DumpData(_,m,e,n,s,a,!0,void 0,d),t.dispose()}))}))})),T.incrementRenderId(),T.resetCachedMaterial(),S.render(!0),T.incrementRenderId(),T.resetCachedMaterial(),e.setSize(v.width,v.height),t.getProjectionMatrix(!0),T.render()};if(o){const e=new PE("antialiasing",1,T.activeCamera);S.addPostProcess(e),e.getEffect().isReady()?E():e.getEffect().onCompiled=()=>{E()}}else E()}function jC(e,t,i,n="image/png",s=1,r=!1,o,a=!1,l=!1,h=!0,c){return new Promise(((d,u)=>{YC(e,t,i,(e=>{void 0!==e?d(e):u(new Error("Data is undefined"))}),n,s,r,o,a,l,h,c)}))}function KC(e,t,i){let n=0,s=0,r=0,o=0;if("object"==typeof i){const a=i.precision?Math.abs(i.precision):1;i.width&&i.height?(n=i.height*a,s=i.width*a):i.width&&!i.height?(s=i.width*a,n=Math.round(s/e.getAspectRatio(t))):i.height&&!i.width?(n=i.height*a,s=Math.round(n*e.getAspectRatio(t))):(s=Math.round(e.getRenderWidth()*a),n=Math.round(s/e.getAspectRatio(t))),i.finalWidth&&i.finalHeight?(o=i.finalHeight,r=i.finalWidth):i.finalWidth&&!i.finalHeight?(r=i.finalWidth,o=Math.round(r/e.getAspectRatio(t))):i.finalHeight&&!i.finalWidth?(o=i.finalHeight,r=Math.round(o*e.getAspectRatio(t))):(r=s,o=n)}else isNaN(i)||(n=i,s=i,r=i,o=i);return s&&(s=Math.floor(s)),n&&(n=Math.floor(n)),r&&(r=Math.floor(r)),o&&(o=Math.floor(o)),{height:0|n,width:0|s,finalWidth:0|r,finalHeight:0|o}}var qC;se.w1.CreateScreenshot=HC,se.w1.CreateScreenshotAsync=XC,se.w1.CreateScreenshotUsingRenderTarget=YC,se.w1.CreateScreenshotUsingRenderTargetAsync=jC,function(e){e[e.Checkbox=0]="Checkbox",e[e.Slider=1]="Slider",e[e.Vector3=2]="Vector3",e[e.Quaternion=3]="Quaternion",e[e.Color3=4]="Color3",e[e.String=5]="String",e[e.Button=6]="Button",e[e.Options=7]="Options",e[e.Tab=8]="Tab",e[e.FileButton=9]="FileButton",e[e.Vector2=10]="Vector2"}(qC||(qC={}));var $C;i(5077);class QC{constructor(e){this.byteOffset=0,this.buffer=e}loadAsync(e){return this.buffer.readAsync(this.byteOffset,e).then((e=>{this._dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),this._dataByteOffset=0}))}readUint32(){const e=this._dataView.getUint32(this._dataByteOffset,!0);return this._dataByteOffset+=4,this.byteOffset+=4,e}readUint8Array(e){const t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._dataByteOffset,e);return this._dataByteOffset+=e,this.byteOffset+=e,t}readString(e){return(0,Oe.fJ)(this.readUint8Array(e))}skipBytes(e){this._dataByteOffset+=e,this.byteOffset+=e}}class ZC{static _GetStorage(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch(e){const t={};return{getItem:e=>{const i=t[e];return void 0===i?null:i},setItem:(e,i)=>{t[e]=i}}}}static ReadString(e,t){const i=this._Storage.getItem(e);return null!==i?i:t}static WriteString(e,t){this._Storage.setItem(e,t)}static ReadBoolean(e,t){const i=this._Storage.getItem(e);return null!==i?"true"===i:t}static WriteBoolean(e,t){this._Storage.setItem(e,t?"true":"false")}static ReadNumber(e,t){const i=this._Storage.getItem(e);return null!==i?parseFloat(i):t}static WriteNumber(e,t){this._Storage.setItem(e,t.toString())}}ZC._Storage=ZC._GetStorage();!function(e){class t{serialize(){const e={},t=new Array(this._characterToIdx.size);return this._characterToIdx.forEach(((e,i)=>{t[e]=i})),e.characters=t,e.insertionCosts=this._insertionCosts,e.deletionCosts=this._deletionCosts,e.substitutionCosts=this._substitutionCosts,JSON.stringify(e)}static Deserialize(e){const i=JSON.parse(e),n=new t(i.characters);return n._insertionCosts=i.insertionCosts,n._deletionCosts=i.deletionCosts,n._substitutionCosts=i.substitutionCosts,n}constructor(e,t=null,i=null,n=null){let s;t=null!=t?t:()=>1,i=null!=i?i:()=>1,n=null!=n?n:(e,t)=>e===t?0:1,this._characterToIdx=new Map,this._insertionCosts=new Array(e.length),this._deletionCosts=new Array(e.length),this._substitutionCosts=new Array(e.length);for(let r=0;ri._MAX_SEQUENCE_LENGTH)throw new Error("Sequences longer than "+i._MAX_SEQUENCE_LENGTH+" not supported.");this._alphabet=t,this._characters=e.map((e=>this._alphabet.getCharacterIdx(e)))}distance(e){return i._Distance(this,e)}static _Distance(e,t){const n=e._alphabet;if(n!==t._alphabet)throw new Error("Cannot Levenshtein compare Sequences built from different alphabets.");const s=e._characters,r=t._characters,o=s.length,a=r.length,l=i._CostMatrix;l[0][0]=0;for(let i=0;inew Array(i._MAX_SEQUENCE_LENGTH+1))),e.Sequence=i}($C||($C={}));class JC{serialize(){return JSON.stringify(this)}static Deserialize(e){const t=JSON.parse(e),i=new JC(t._segmentLength);return i._points=t._points.map((e=>new o.P(e._x,e._y,e._z))),i}constructor(e=.01){this._points=[],this._segmentLength=e}getLength(){return this._points.length*this._segmentLength}add(e){let t=this._points.length;if(0===t)this._points.push(e.clone());else{const i=()=>this._segmentLength/o.P.Distance(this._points[t-1],e);for(let n=i();n<=1;n=i()){const i=this._points[t-1].scale(1-n);e.scaleAndAddToRef(n,i),this._points.push(i),++t}}}resampleAtTargetResolution(e){const t=new JC(this.getLength()/e);return this._points.forEach((e=>{t.add(e)})),t}tokenize(e){const t=[],i=new o.P;for(let n=2;n.98)&&(o.P.CrossToRef(JC._ForwardDir,JC._InverseFromVec,JC._UpDir),JC._UpDir.normalize(),o.y3.LookAtLHToRef(e,t,JC._UpDir,JC._LookMatrix),i.subtractToRef(t,JC._FromToVec),JC._FromToVec.normalize(),o.P.TransformNormalToRef(JC._FromToVec,JC._LookMatrix,n),!0)}static _TokenizeSegment(e,t){JC._BestMatch=0,JC._Score=o.P.Dot(e,t[0]),JC._BestScore=JC._Score;for(let i=1;iJC._BestScore&&(JC._BestMatch=i,JC._BestScore=JC._Score);return JC._BestMatch}}JC._ForwardDir=new o.P,JC._InverseFromVec=new o.P,JC._UpDir=new o.P,JC._FromToVec=new o.P,JC._LookMatrix=new o.y3;class ey{serialize(){return JSON.stringify(this._sequences.map((e=>e.serialize())))}static Deserialize(e,t){const i=new ey;return i._sequences=JSON.parse(e).map((e=>$C.Sequence.Deserialize(e,t))),i}static CreateFromTrajectory(e,t,i){return ey.CreateFromTokenizationPyramid(ey._GetTokenizationPyramid(e,t),i)}static CreateFromTokenizationPyramid(e,t){const i=new ey;return i._sequences=e.map((e=>new $C.Sequence(e,t))),i}constructor(){this._sequences=[]}static _GetTokenizationPyramid(e,t,i=ey._FINEST_DESCRIPTOR_RESOLUTION){const n=[];for(let s=i;s>4;s=Math.floor(s/2))n.push(e.resampleAtTargetResolution(s).tokenize(t.chars));return n}distance(e){let t,i=0;for(let n=0;ne.serialize())),e.centroidIdx=this._centroidIdx,e.averageDistance=this._averageDistance,JSON.stringify(e)}static Deserialize(e,t){const i=JSON.parse(e),n=new ty;return n._descriptors=i.descriptors.map((e=>ey.Deserialize(e,t))),n._centroidIdx=i.centroidIdx,n._averageDistance=i.averageDistance,n}constructor(e=[]){this._descriptors=e,this._centroidIdx=-1,this._averageDistance=0,this._refreshDescription()}add(e){this._descriptors.push(e),this._refreshDescription()}getMatchCost(e){return e.distance(this._descriptors[this._centroidIdx])/this._averageDistance}getMatchMinimumDistance(e){return Math.min(...this._descriptors.map((t=>t.distance(e))))}_refreshDescription(){let e;this._centroidIdx=-1;const t=this._descriptors.map((t=>(e=0,this._descriptors.forEach((i=>{e+=t.distance(i)})),e)));for(let i=0;i{this._averageDistance+=e.distance(this._descriptors[this._centroidIdx])})),this._descriptors.length>0&&(this._averageDistance=Math.max(this._averageDistance/this._descriptors.length,ty._MIN_AVERAGE_DISTANCE))}}ty._MIN_AVERAGE_DISTANCE=1;class iy{constructor(e,t,i){this._scene=e,p.Y.Log(`[Reflector] Connecting to ws://${t}:${i}`),this._webSocket=new WebSocket(`ws://${t}:${i}`),this._webSocket.onmessage=e=>{const t=e.data;if(t.startsWith(iy._SERVER_PREFIX)){const e=t.substr(iy._SERVER_PREFIX.length);return p.Y.Log(`[Reflector] Received server message: ${e.substr(0,64)}`),void this._handleServerMessage(e)}p.Y.Log(`[Reflector] Received client message: ${t.substr(0,64)}`),this._handleClientMessage()},this._webSocket.onclose=e=>{p.Y.Log(`[Reflector] Disconnected ${e.code} ${e.reason}`)}}close(){this._webSocket.close()}_handleServerMessage(e){if("connected"===e)GC.SerializeAsync(this._scene).then((e=>{this._webSocket.send(`load|${JSON.stringify(e)}`)}))}_handleClientMessage(){}}iy._SERVER_PREFIX="$$";class ny{constructor(e){this._view=new Float32Array(e),this._itemLength=0}get itemLength(){return this._itemLength}at(e){return e<0||e>=this._itemLength?NaN:this._view[e]}subarray(e,t){return e>=t||e<0?new Float32Array(0):(t>this._itemLength&&(t=this._itemLength),this._view.subarray(e,t))}push(e){this._view[this._itemLength]=e,this._itemLength++,this._itemLength>=this._view.length&&this._growArray()}_growArray(){const e=Math.floor(1.5*this._view.length),t=new Float32Array(e);t.set(this._view),this._view=t}}const sy=1800,ry="timestamp",oy="numPoints",ay=/\r/g;class ly{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{const e=F.F.Now-this._startingTimestamp,t=this.datasets.ids.length,i=this.datasets.startingIndices.itemLength;let n=0;if(i>0){const e=this.datasets.startingIndices.at(i-1);n=e+this.datasets.data.at(e+ly.NumberOfPointsOffset)+ly.SliceDataOffset}if(this.datasets.startingIndices.push(n),this.datasets.data.push(e),this.datasets.data.push(t),this.datasets.ids.forEach((e=>{const t=this._strategies.get(e);t&&this.datasets.data.push(t.getData())})),this.datasetObservable.hasObservers()){const i=[e,t];for(let e=0;ee.callback(this._datasetMeta,new r.he(0)))),t&&this.addCollectionStrategies(...t)}registerEvent(e,t,i){var n;if(this._strategies.has(e)&&!t)return;this._strategies.has(e)&&t&&(null===(n=this._strategies.get(e))||void 0===n||n.dispose(),this._strategies.delete(e));const s={name:e};return this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:t=>{let i=0,n=0;const s=t.onAfterRenderObservable.add((()=>{n=i,i=0})),r=this._customEventObservable.add((t=>{e===t.name&&(void 0!==t.value?i=t.value:i++)}));return{id:e,getData:()=>n,dispose:()=>{t.onAfterRenderObservable.remove(s),this._customEventObservable.remove(r)}}},category:i}),s}sendEvent(e){this._customEventObservable.notifyObservers(e)}_restoreStringEvents(){this._eventRestoreSet.size!==this._customEventObservable.observers.length&&this._eventRestoreSet.forEach((e=>{this.registerEvent(e,!0)}))}addCollectionStrategies(...e){for(let{strategyCallback:t,category:i,hidden:n}of e){const e=t(this._scene);this._strategies.has(e.id)?e.dispose():(this.datasets.ids.push(e.id),i&&(i=i.replace(new RegExp("@","g"),"")),this._datasetMeta.set(e.id,{color:this._getHexColorFromId(e.id),category:i,hidden:n}),this._strategies.set(e.id,e))}this.metadataObservable.notifyObservers(this._datasetMeta)}_getHexColorFromId(e){let t=0;for(let n=0;n>n&255).toString(16)).substr(-2)}return i}getCurrentSlice(){const e=[F.F.Now-this._startingTimestamp,this.datasets.ids.length];this.datasets.ids.forEach((t=>{const i=this._strategies.get(t);i&&this.datasetObservable.hasObservers()&&e.push(i.getData())})),this.datasetObservable.hasObservers()&&this.datasetObservable.notifyObservers(e)}updateMetadata(e,t,i){const n=this._datasetMeta.get(e);n&&(n[t]=i,this.metadataObservable.notifyObservers(this._datasetMeta))}clear(e){this.datasets.data=new ny(sy),this.datasets.ids.length=0,this.datasets.startingIndices=new ny(sy),this._datasetMeta.clear(),this._strategies.forEach((e=>e.dispose())),this._strategies.clear(),e||this._eventRestoreSet.clear(),this._hasLoadedData=!1}get hasLoadedData(){return this._hasLoadedData}loadFromFileData(e,t){const i=e.replace(ay,"").split("\n").map((e=>e.split(",").filter((e=>e.length>0)))).filter((e=>e.length>0)),n=ly.NumberOfPointsOffset;if(i.length<2)return!1;const s={ids:[],data:new ny(sy),startingIndices:new ny(sy)},[r,...o]=i;if(r.length<2||r[0]!==ry||r[n]!==oy)return!1;const a=new Map;for(let h=ly.SliceDataOffset;he.dispose())),this._strategies.clear(),!t)for(const h of this.datasets.ids){const e=a.get(h);this._datasetMeta.set(h,{category:e,color:this._getHexColorFromId(h)})}return this.metadataObservable.notifyObservers(this._datasetMeta),this._hasLoadedData=!0,!0}exportDataToCsv(){let e="";e+=`${ry},${oy}`;for(let i=0;i{e.dispose()})),this.datasetObservable.clear(),this.metadataObservable.clear(),this._isStarted=!1,this.datasets=null}}N.x.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new ly(this)),this._perfCollector};var hy=i(140);r.y$.prototype.runCoroutineAsync=function(e){if(!this._coroutineScheduler){const e=function(e){const t=new Array,i=new Array,n=new Array,s=e.add((()=>{const e=t.length;for(let s=0;s{t.push(e),i.push(s),n.push(r)},dispose:()=>{e.remove(s)}}}(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return(0,hy.sM)(e,this._coroutineScheduler)},r.y$.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};class cy extends nt{constructor(e,t={}){super(e),this.options=t,this._direction=new o.P(0,0,-1),this._mat=new o.y3,this._onSelectEnabled=!1,this._origin=new o.P(0,0,0),this.lastNativeXRHitResults=[],this.onHitTestResultObservable=new r.y$,this._onHitTestResults=e=>{const t=e.map((e=>{const t=o.y3.FromArray(e.hitMatrix);return this._xrSessionManager.scene.useRightHandedSystem||t.toggleModelMatrixHandInPlace(),this.options.worldParentNode&&t.multiplyToRef(this.options.worldParentNode.getWorldMatrix(),t),{xrHitResult:e,transformationMatrix:t}}));this.lastNativeXRHitResults=e,this.onHitTestResultObservable.notifyObservers(t)},this._onSelect=e=>{this._onSelectEnabled&&cy.XRHitTestWithSelectEvent(e,this._xrSessionManager.referenceSpace)},this.xrNativeFeatureName="hit-test",se.w1.Warn("A newer version of this plugin is available")}static XRHitTestWithRay(e,t,i,n){return e.requestHitTest(t,i).then((e=>{const t=n||(e=>!!e.hitMatrix);return e.filter(t)}))}static XRHitTestWithSelectEvent(e,t){const i=e.frame.getPose(e.inputSource.targetRaySpace,t);if(!i)return Promise.resolve([]);const n=new XRRay(i.transform);return this.XRHitTestWithRay(e.frame.session,n,t)}attach(){return!!super.attach()&&(this.options.testOnPointerDownOnly&&this._xrSessionManager.session.addEventListener("select",this._onSelect,!1),!0)}detach(){return!!super.detach()&&(this._onSelectEnabled=!1,this._xrSessionManager.session.removeEventListener("select",this._onSelect),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(!this.attached||this.options.testOnPointerDownOnly)return;const t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;o.y3.FromArrayToRef(t.transform.matrix,0,this._mat),o.P.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),o.P.TransformCoordinatesFromFloatsToRef(0,0,-1,this._mat,this._direction),this._direction.subtractInPlace(this._origin),this._direction.normalize();const i=new XRRay({x:this._origin.x,y:this._origin.y,z:this._origin.z,w:0},{x:this._direction.x,y:this._direction.y,z:this._direction.z,w:0});cy.XRHitTestWithRay(this._xrSessionManager.session,i,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}}cy.Name=tt.HIT_TEST,cy.Version=1,it.AddWebXRFeature(cy.Name,((e,t)=>()=>new cy(e,t)),cy.Version,!1);let dy=0;class uy extends nt{set referenceSpaceForFrameAnchors(e){this._referenceSpaceForFrameAnchors=e}constructor(e,t={}){super(e),this._options=t,this._lastFrameDetected=new Set,this._trackedAnchors=[],this._futureAnchors=[],this.onAnchorAddedObservable=new r.y$,this.onAnchorRemovedObservable=new r.y$,this.onAnchorUpdatedObservable=new r.y$,this._tmpVector=new o.P,this._tmpQuaternion=new o._f,this.xrNativeFeatureName="anchors"}_populateTmpTransformation(e,t){return this._tmpVector.copyFrom(e),this._tmpQuaternion.copyFrom(t),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpVector.z*=-1,this._tmpQuaternion.z*=-1,this._tmpQuaternion.w*=-1),{position:this._tmpVector,rotationQuaternion:this._tmpQuaternion}}async addAnchorPointUsingHitTestResultAsync(e,t=new o.P,i=new o._f){this._populateTmpTransformation(t,i);const n=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w});if(!e.xrHitResult.createAnchor)throw this.detach(),new Error("Anchors not enabled in this environment/browser");try{const t=await e.xrHitResult.createAnchor(n);return new Promise(((e,i)=>{this._futureAnchors.push({nativeAnchor:t,resolved:!1,submitted:!0,xrTransformation:n,resolve:e,reject:i})}))}catch(lt){throw new Error(lt)}}async addAnchorAtPositionAndRotationAsync(e,t=new o._f,i=!1){this._populateTmpTransformation(e,t);const n=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w}),s=i&&this.attached&&this._xrSessionManager.currentFrame?await this._createAnchorAtTransformation(n,this._xrSessionManager.currentFrame):void 0;return new Promise(((e,t)=>{this._futureAnchors.push({nativeAnchor:s,resolved:!1,submitted:!1,xrTransformation:n,resolve:e,reject:t})}))}get anchors(){return this._trackedAnchors}detach(){if(!super.detach())return!1;if(!this._options.doNotRemoveAnchorsOnSessionEnded)for(;this._trackedAnchors.length;){const t=this._trackedAnchors.pop();if(t){try{t.remove()}catch(e){}this.onAnchorRemovedObservable.notifyObservers(t)}}return!0}dispose(){this._futureAnchors.length=0,super.dispose(),this.onAnchorAddedObservable.clear(),this.onAnchorRemovedObservable.clear(),this.onAnchorUpdatedObservable.clear()}_onXRFrame(e){if(!this.attached||!e)return;const t=e.trackedAnchors;if(t){const i=this._trackedAnchors.filter((e=>!t.has(e.xrAnchor))).map((e=>this._trackedAnchors.indexOf(e)));let n=0;i.forEach((e=>{const t=this._trackedAnchors.splice(e-n,1)[0];this.onAnchorRemovedObservable.notifyObservers(t),n++})),t.forEach((t=>{if(this._lastFrameDetected.has(t)){const n=this._findIndexInAnchorArray(t),s=this._trackedAnchors[n];try{this._updateAnchorWithXRFrame(t,s,e),s.attachedNode&&(s.attachedNode.rotationQuaternion=s.attachedNode.rotationQuaternion||new o._f,s.transformationMatrix.decompose(s.attachedNode.scaling,s.attachedNode.rotationQuaternion,s.attachedNode.position)),this.onAnchorUpdatedObservable.notifyObservers(s)}catch(i){se.w1.Warn("Anchor could not be updated")}}else{const i={id:dy++,xrAnchor:t,remove:()=>t.delete()},n=this._updateAnchorWithXRFrame(t,i,e);this._trackedAnchors.push(n),this.onAnchorAddedObservable.notifyObservers(n);const s=this._futureAnchors.filter((e=>e.nativeAnchor===t))[0];s&&(s.resolve(n),s.resolved=!0)}})),this._lastFrameDetected=t}this._futureAnchors.forEach((t=>{t.resolved||t.submitted||(this._createAnchorAtTransformation(t.xrTransformation,e).then((e=>{t.nativeAnchor=e}),(e=>{t.resolved=!0,t.reject(e)})),t.submitted=!0)}))}_findIndexInAnchorArray(e){for(let t=0;t()=>new uy(e,t)),uy.Version);let py=0;class fy extends nt{constructor(e,t={}){super(e),this._options=t,this._detectedPlanes=[],this._enabled=!1,this._lastFrameDetected=new Set,this.onPlaneAddedObservable=new r.y$,this.onPlaneRemovedObservable=new r.y$,this.onPlaneUpdatedObservable=new r.y$,this.xrNativeFeatureName="plane-detection",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){if(!super.detach())return!1;if(!this._options.doNotRemovePlanesOnSessionEnded)for(;this._detectedPlanes.length;){const e=this._detectedPlanes.pop();e&&this.onPlaneRemovedObservable.notifyObservers(e)}return!0}dispose(){super.dispose(),this.onPlaneAddedObservable.clear(),this.onPlaneRemovedObservable.clear(),this.onPlaneUpdatedObservable.clear()}isCompatible(){return"undefined"!=typeof XRPlane}_onXRFrame(e){var t;if(!this.attached||!this._enabled||!e)return;const i=e.detectedPlanes||(null===(t=e.worldInformation)||void 0===t?void 0:t.detectedPlanes);if(i){for(let e=0;e{if(this._lastFrameDetected.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){const i=this._findIndexInPlaneArray(t),n=this._detectedPlanes[i];this._updatePlaneWithXRPlane(t,n,e),this.onPlaneUpdatedObservable.notifyObservers(n)}}else{const i={id:py++,xrPlane:t,polygonDefinition:[]},n=this._updatePlaneWithXRPlane(t,i,e);this._detectedPlanes.push(n),this.onPlaneAddedObservable.notifyObservers(n)}})),this._lastFrameDetected=i}}_init(){const e=()=>{this._enabled=!0,this._detectedPlanes.length&&(this._detectedPlanes.length=0)};this._xrSessionManager.isNative&&this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions),this._xrSessionManager.session.updateWorldTrackingState?(this._xrSessionManager.session.updateWorldTrackingState({planeDetectionState:{enabled:!0}}),e()):e()}_updatePlaneWithXRPlane(e,t,i){t.polygonDefinition=e.polygon.map((e=>{const t=this._xrSessionManager.scene.useRightHandedSystem?1:-1;return new o.P(e.x,e.y,e.z*t)}));const n=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(n){const e=t.transformationMatrix||new o.y3;o.y3.FromArrayToRef(n.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t.transformationMatrix=e,this._options.worldParentNode&&e.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),e)}return t}_findIndexInPlaneArray(e){for(let t=0;t()=>new fy(e,t)),fy.Version);class _y extends nt{constructor(e,t={}){super(e),this.options=t,this.onBackgroundStateChangedObservable=new r.y$}attach(){return this._setBackgroundState(!1),super.attach()}detach(){return this._setBackgroundState(!0),super.detach()}dispose(){super.dispose(),this.onBackgroundStateChangedObservable.clear()}_onXRFrame(e){}_setBackgroundState(e){const t=this._xrSessionManager.scene;if(!this.options.ignoreEnvironmentHelper)if(this.options.environmentHelperRemovalFlags){if(this.options.environmentHelperRemovalFlags.skyBox){const i=t.getMeshByName("BackgroundSkybox");i&&i.setEnabled(e)}if(this.options.environmentHelperRemovalFlags.ground){const i=t.getMeshByName("BackgroundPlane");i&&i.setEnabled(e)}}else{const i=t.getMeshByName("BackgroundHelper");i&&i.setEnabled(e)}this.options.backgroundMeshes&&this.options.backgroundMeshes.forEach((t=>t.setEnabled(e))),this.onBackgroundStateChangedObservable.notifyObservers(e)}}_y.Name=tt.BACKGROUND_REMOVER,_y.Version=1,it.AddWebXRFeature(_y.Name,((e,t)=>()=>new _y(e,t)),_y.Version,!0);class my extends nt{_createPhysicsImpostor(e){const t=this._options.physicsProperties.impostorType||rt.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,n=gl("impostor-mesh-"+e.uniqueId,{diameterX:"number"==typeof i?i:i.width,diameterY:"number"==typeof i?i:i.height,diameterZ:"number"==typeof i?i:i.depth});n.isVisible=this._debugMode,n.isPickable=!1,n.rotationQuaternion=new o._f;const s=e.grip||e.pointer;n.position.copyFrom(s.position),n.rotationQuaternion.copyFrom(s.rotationQuaternion);const r=new rt(n,t,Object.assign({mass:0},this._options.physicsProperties));this._controllers[e.uniqueId]={xrController:e,impostor:r,impostorMesh:n}}constructor(e,t){super(e),this._options=t,this._attachController=e=>{this._controllers[e.uniqueId]||(this._xrSessionManager.scene.isPhysicsEnabled()||p.Y.Warn("physics engine not enabled, skipped. Please add this controller manually."),this._options.physicsProperties.useControllerMesh&&e.inputSource.gamepad?e.onMotionControllerInitObservable.addOnce((t=>{t._doNotLoadControllerMesh?this._createPhysicsImpostor(e):t.onModelLoadedObservable.addOnce((()=>{const i=new rt(t.rootMesh,rt.MeshImpostor,Object.assign({mass:0},this._options.physicsProperties)),n=e.grip||e.pointer;this._controllers[e.uniqueId]={xrController:e,impostor:i,oldPos:n.position.clone(),oldRotation:n.rotationQuaternion.clone()}}))})):this._createPhysicsImpostor(e))},this._controllers={},this._debugMode=!1,this._delta=0,this._lastTimestamp=0,this._tmpQuaternion=new o._f,this._tmpVector=new o.P,this._options.physicsProperties||(this._options.physicsProperties={})}_enablePhysicsDebug(){this._debugMode=!0,Object.keys(this._controllers).forEach((e=>{const t=this._controllers[e];t.impostorMesh&&(t.impostorMesh.isVisible=!0)}))}addController(e){this._attachController(e)}attach(){if(!super.attach())return!1;if(!this._options.xrInput)return!0;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),this._options.enableHeadsetImpostor){const e=this._options.headsetImpostorParams||{impostorType:rt.SphereImpostor,restitution:.8,impostorSize:.3},t=e.impostorSize||.3;this._headsetMesh=gl("headset-mesh",{diameterX:"number"==typeof t?t:t.width,diameterY:"number"==typeof t?t:t.height,diameterZ:"number"==typeof t?t:t.depth}),this._headsetMesh.rotationQuaternion=new o._f,this._headsetMesh.isVisible=!1,this._headsetImpostor=new rt(this._headsetMesh,e.impostorType,Object.assign({mass:0},e))}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._headsetMesh&&this._headsetMesh.dispose(),!0)}getHeadsetImpostor(){return this._headsetImpostor}getImpostorForController(e){const t="string"==typeof e?e:e.uniqueId;return this._controllers[t]?this._controllers[t].impostor:null}setPhysicsProperties(e){this._options.physicsProperties=Object.assign(Object.assign({},this._options.physicsProperties),e)}_onXRFrame(e){var t,i;if(this._delta=this._xrSessionManager.currentTimestamp-this._lastTimestamp,this._lastTimestamp=this._xrSessionManager.currentTimestamp,this._headsetMesh&&this._headsetImpostor){if(this._headsetMesh.position.copyFrom(this._options.xrInput.xrCamera.globalPosition),this._headsetMesh.rotationQuaternion.copyFrom(this._options.xrInput.xrCamera.absoluteRotation),null===(t=this._options.xrInput.xrCamera._lastXRViewerPose)||void 0===t?void 0:t.linearVelocity){const e=this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setLinearVelocity(this._tmpVector)}if(null===(i=this._options.xrInput.xrCamera._lastXRViewerPose)||void 0===i?void 0:i.angularVelocity){const e=this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setAngularVelocity(this._tmpVector)}}Object.keys(this._controllers).forEach((e=>{var t,i;const n=this._controllers[e],s=n.xrController.grip||n.xrController.pointer,r=n.oldPos||n.impostorMesh.position;if(null===(t=n.xrController._lastXRPose)||void 0===t?void 0:t.linearVelocity){const e=n.xrController._lastXRPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),n.impostor.setLinearVelocity(this._tmpVector)}else s.position.subtractToRef(r,this._tmpVector),this._tmpVector.scaleInPlace(1e3/this._delta),n.impostor.setLinearVelocity(this._tmpVector);r.copyFrom(s.position),this._debugMode&&console.log(this._tmpVector,"linear");const o=n.oldRotation||n.impostorMesh.rotationQuaternion;if(null===(i=n.xrController._lastXRPose)||void 0===i?void 0:i.angularVelocity){const e=n.xrController._lastXRPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),n.impostor.setAngularVelocity(this._tmpVector)}else if(!o.equalsWithEpsilon(s.rotationQuaternion)){o.conjugateInPlace().multiplyToRef(s.rotationQuaternion,this._tmpQuaternion);const e=Math.sqrt(this._tmpQuaternion.x*this._tmpQuaternion.x+this._tmpQuaternion.y*this._tmpQuaternion.y+this._tmpQuaternion.z*this._tmpQuaternion.z);if(this._tmpVector.set(this._tmpQuaternion.x,this._tmpQuaternion.y,this._tmpQuaternion.z),e<.001)this._tmpVector.scaleInPlace(2);else{const t=2*Math.atan2(e,this._tmpQuaternion.w);this._tmpVector.scaleInPlace(t/(e*(this._delta/1e3)))}n.impostor.setAngularVelocity(this._tmpVector)}o.copyFrom(s.rotationQuaternion),this._debugMode&&console.log(this._tmpVector,this._tmpQuaternion,"angular")}))}_detachController(e){const t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])}}my.Name=tt.PHYSICS_CONTROLLERS,my.Version=1,it.AddWebXRFeature(my.Name,((e,t)=>()=>new my(e,t)),my.Version,!0);class gy extends nt{constructor(e,t={}){super(e),this.options=t,this._tmpMat=new o.y3,this._tmpPos=new o.P,this._tmpQuat=new o._f,this._initHitTestSource=e=>{if(!e)return;const t=new XRRay(this.options.offsetRay||{}),i={space:this.options.useReferenceSpace?e:this._xrSessionManager.viewerReferenceSpace,offsetRay:t};this.options.entityTypes&&(i.entityTypes=this.options.entityTypes),i.space?this._xrSessionManager.session.requestHitTestSource(i).then((e=>{this._xrHitTestSource&&this._xrHitTestSource.cancel(),this._xrHitTestSource=e})):se.w1.Warn("waiting for viewer reference space to initialize")},this.autoCloneTransformation=!1,this.onHitTestResultObservable=new r.y$,this.paused=!1,this.xrNativeFeatureName="hit-test",se.w1.Warn("Hit test is an experimental and unstable feature.")}attach(){if(!super.attach())return!1;if(!this._xrSessionManager.session.requestHitTestSource)return!1;if(this.options.disablePermanentHitTest||(this._xrSessionManager.referenceSpace&&this._initHitTestSource(this._xrSessionManager.referenceSpace),this._xrSessionManager.onXRReferenceSpaceChanged.add(this._initHitTestSource)),this.options.enableTransientHitTest){const e=new XRRay(this.options.transientOffsetRay||{});this._xrSessionManager.session.requestHitTestSourceForTransientInput({profile:this.options.transientHitTestProfile||"generic-touchscreen",offsetRay:e,entityTypes:this.options.entityTypes}).then((e=>{this._transientXrHitTestSource=e}))}return!0}detach(){return!!super.detach()&&(this._xrHitTestSource&&(this._xrHitTestSource.cancel(),this._xrHitTestSource=null),this._xrSessionManager.onXRReferenceSpaceChanged.removeCallback(this._initHitTestSource),this._transientXrHitTestSource&&(this._transientXrHitTestSource.cancel(),this._transientXrHitTestSource=null),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(this.attached&&!this.paused){if(this._xrHitTestSource){const t=e.getHitTestResults(this._xrHitTestSource);this._processWebXRHitTestResult(t)}if(this._transientXrHitTestSource){e.getHitTestResultsForTransientInput(this._transientXrHitTestSource).forEach((e=>{this._processWebXRHitTestResult(e.results,e.inputSource)}))}}}_processWebXRHitTestResult(e,t){const i=[];e.forEach((e=>{const n=e.getPose(this._xrSessionManager.referenceSpace);if(!n)return;const s=n.transform.position,r=n.transform.orientation;this._tmpPos.set(s.x,s.y,s.z),this._tmpQuat.set(r.x,r.y,r.z,r.w),o.y3.FromFloat32ArrayToRefScaled(n.transform.matrix,0,1,this._tmpMat),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpPos.z*=-1,this._tmpQuat.z*=-1,this._tmpQuat.w*=-1,this._tmpMat.toggleModelMatrixHandInPlace());const a={position:this.autoCloneTransformation?this._tmpPos.clone():this._tmpPos,rotationQuaternion:this.autoCloneTransformation?this._tmpQuat.clone():this._tmpQuat,transformationMatrix:this.autoCloneTransformation?this._tmpMat.clone():this._tmpMat,inputSource:t,isTransient:!!t,xrHitResult:e};i.push(a)})),this.onHitTestResultObservable.notifyObservers(i)}}gy.Name=tt.HIT_TEST,gy.Version=2,it.AddWebXRFeature(gy.Name,((e,t)=>()=>new gy(e,t)),gy.Version,!1);class vy extends nt{get featurePointCloud(){return this._featurePointCloud}constructor(e){super(e),this._enabled=!1,this._featurePointCloud=[],this.onFeaturePointsAddedObservable=new r.y$,this.onFeaturePointsUpdatedObservable=new r.y$,this.xrNativeFeatureName="bjsfeature-points",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){return!!super.detach()&&(this.featurePointCloud.length=0,!0)}dispose(){super.dispose(),this._featurePointCloud.length=0,this.onFeaturePointsUpdatedObservable.clear(),this.onFeaturePointsAddedObservable.clear()}_onXRFrame(e){if(!this.attached||!this._enabled||!e)return;const t=e.featurePointCloud;if(t&&0!==t.length){if(t.length%5!=0)throw new Error("Received malformed feature point cloud of length: "+t.length);const e=t.length/5,i=new Array,n=new Array;for(let s=0;s0&&this.onFeaturePointsAddedObservable.notifyObservers(n),i.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(i)}}_init(){this._xrSessionManager.session.trySetFeaturePointCloudEnabled&&this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)&&(this._enabled=!0)}}vy.Name=tt.FEATURE_POINTS,vy.Version=1,it.AddWebXRFeature(vy.Name,(e=>()=>new vy(e)),vy.Version);let Ty=0;class Sy extends nt{constructor(e,t={}){super(e),this._options=t,this._detectedMeshes=new Map,this.onMeshAddedObservable=new r.y$,this.onMeshRemovedObservable=new r.y$,this.onMeshUpdatedObservable=new r.y$,this.xrNativeFeatureName="mesh-detection",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}detach(){return!!super.detach()&&(this._xrSessionManager.isNative&&this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!1),this._options.doNotRemoveMeshesOnSessionEnded||(this._detectedMeshes.forEach((e=>{this.onMeshRemovedObservable.notifyObservers(e)})),this._detectedMeshes.clear()),!0)}dispose(){super.dispose(),this.onMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onMeshUpdatedObservable.clear()}_onXRFrame(e){var t;try{if(!this.attached||!e)return;const i=null===(t=e.worldInformation)||void 0===t?void 0:t.detectedMeshes;if(i){const t=new Set;this._detectedMeshes.forEach(((e,n)=>{i.has(n)||t.add(n)})),t.forEach((e=>{const t=this._detectedMeshes.get(e);t&&(this.onMeshRemovedObservable.notifyObservers(t),this._detectedMeshes.delete(e))})),i.forEach((t=>{if(this._detectedMeshes.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){const i=this._detectedMeshes.get(t);i&&(this._updateVertexDataWithXRMesh(t,i,e),this.onMeshUpdatedObservable.notifyObservers(i))}}else{const i={id:Ty++,xrMesh:t},n=this._updateVertexDataWithXRMesh(t,i,e);this._detectedMeshes.set(t,n),this.onMeshAddedObservable.notifyObservers(n)}}))}}catch(lt){console.log(lt.stack)}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!0),this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions(this._options.preferredDetectorOptions))}_updateVertexDataWithXRMesh(e,t,i){if(t.xrMesh=e,t.worldParentNode=this._options.worldParentNode,this._options.convertCoordinateSystems){if(this._xrSessionManager.scene.useRightHandedSystem)t.positions=e.positions,t.normals=e.normals;else{t.positions=new Float32Array(e.positions.length);for(let i=0;i()=>new Sy(e,t)),Sy.Version,!1),function(e){e[e.NotReceived=0]="NotReceived",e[e.Waiting=1]="Waiting",e[e.Received=2]="Received"}(Ey||(Ey={}));class xy extends nt{constructor(e,t){super(e),this.options=t,this.onUntrackableImageFoundObservable=new r.y$,this.onTrackableImageFoundObservable=new r.y$,this.onTrackedImageUpdatedObservable=new r.y$,this._trackableScoreStatus=Ey.NotReceived,this._trackedImages=[],this.xrNativeFeatureName="image-tracking"}attach(){return super.attach()}detach(){return super.detach()}getTrackedImageById(e){return this._trackedImages[e]||null}dispose(){super.dispose(),this._trackedImages.forEach((e=>{e.originalBitmap.close()})),this._trackedImages.length=0,this.onTrackableImageFoundObservable.clear(),this.onUntrackableImageFoundObservable.clear(),this.onTrackedImageUpdatedObservable.clear()}async getXRSessionInitExtension(){if(!this.options.images||!this.options.images.length)return{};const e=this.options.images.map((e=>"string"==typeof e.src?this._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(e.src):Promise.resolve(e.src)));try{const t=await Promise.all(e);return this._originalTrackingRequest=t.map(((e,t)=>({image:e,widthInMeters:this.options.images[t].estimatedRealWorldWidth}))),{trackedImages:this._originalTrackingRequest}}catch(t){return se.w1.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),{}}}_onXRFrame(e){if(!e.getImageTrackingResults||this._trackableScoreStatus===Ey.Waiting)return;if(this._trackableScoreStatus===Ey.NotReceived)return void this._checkScoresAsync();const t=e.getImageTrackingResults();for(const i of t){let t=!1;const n=i.index,s=this._trackedImages[n];if(!s)continue;s.xrTrackingResult=i,s.realWorldWidth!==i.measuredWidthInMeters&&(s.realWorldWidth=i.measuredWidthInMeters,t=!0);const r=e.getPose(i.imageSpace,this._xrSessionManager.referenceSpace);if(r){const e=s.transformationMatrix;o.y3.FromArrayToRef(r.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t=!0}const a="emulated"===i.trackingState;s.emulated!==a&&(s.emulated=a,t=!0),t&&this.onTrackedImageUpdatedObservable.notifyObservers(s)}}async _checkScoresAsync(){if(!this._xrSessionManager.session.getTrackedImageScores||this._trackableScoreStatus!==Ey.NotReceived)return;this._trackableScoreStatus=Ey.Waiting;const e=await this._xrSessionManager.session.getTrackedImageScores();if(e&&0!==e.length){for(let t=0;t0?Ey.Received:Ey.NotReceived}else this._trackableScoreStatus=Ey.NotReceived}}xy.Name=tt.IMAGE_TRACKING,xy.Version=1,it.AddWebXRFeature(xy.Name,((e,t)=>()=>new xy(e,t)),xy.Version,!1);class by extends nt{constructor(e,t){super(e),this.options=t,this._domOverlayType=null,this._beforeXRSelectListener=null,this._element=null,this.xrNativeFeatureName="dom-overlay",se.w1.Warn("dom-overlay is an experimental and unstable feature.")}attach(){return!!super.attach()&&(!(!this._xrSessionManager.session.domOverlayState||null===this._xrSessionManager.session.domOverlayState.type)&&(this._domOverlayType=this._xrSessionManager.session.domOverlayState.type,null!==this._element&&!0===this.options.supressXRSelectEvents&&(this._beforeXRSelectListener=e=>{e.preventDefault()},this._element.addEventListener("beforexrselect",this._beforeXRSelectListener)),!0))}get domOverlayType(){return this._domOverlayType}dispose(){super.dispose(),null!==this._element&&this._beforeXRSelectListener&&this._element.removeEventListener("beforexrselect",this._beforeXRSelectListener)}_onXRFrame(e){}async getXRSessionInitExtension(){if(void 0===this.options.element)return se.w1.Warn('"element" option must be provided to attach xr-dom-overlay feature.'),{};if("string"==typeof this.options.element){const e=document.querySelector(this.options.element);if(null===e)return se.w1.Warn(`element not found '${this.options.element}' (not requesting xr-dom-overlay)`),{};this._element=e}else this._element=this.options.element;return{domOverlay:{root:this._element}}}}by.Name=tt.DOM_OVERLAY,by.Version=1,it.AddWebXRFeature(by.Name,((e,t)=>()=>new by(e,t)),by.Version,!1);class Cy extends nt{get movementDirection(){return this._movementDirection}get movementEnabled(){return this._featureContext.movementEnabled}set movementEnabled(e){this._featureContext.movementEnabled=e}get movementOrientationFollowsViewerPose(){return this._featureContext.movementOrientationFollowsViewerPose}set movementOrientationFollowsViewerPose(e){this._featureContext.movementOrientationFollowsViewerPose=e}get movementSpeed(){return this._featureContext.movementSpeed}set movementSpeed(e){this._featureContext.movementSpeed=e}get movementThreshold(){return this._featureContext.movementThreshold}set movementThreshold(e){this._featureContext.movementThreshold=e}get rotationEnabled(){return this._featureContext.rotationEnabled}set rotationEnabled(e){this._featureContext.rotationEnabled=e}get rotationSpeed(){return this._featureContext.rotationSpeed}set rotationSpeed(e){this._featureContext.rotationSpeed=e}get rotationThreshold(){return this._featureContext.rotationThreshold}set rotationThreshold(e){this._featureContext.rotationThreshold=e}constructor(e,t){var i,n,s,r,a,l;super(e),this._controllers={},this._currentRegistrationConfigurations=[],this._movementDirection=null,this._tmpRotationMatrix=o.y3.Identity(),this._tmpTranslationDirection=new o.P,this._tmpMovementTranslation=new o.P,this._attachController=e=>{if(this._controllers[e.uniqueId])return;this._controllers[e.uniqueId]={xrController:e,registeredComponents:[]};const t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){const i=()=>{if(e.motionController)for(const i of this._currentRegistrationConfigurations){let n=null;if(i.allowedComponentTypes)for(const t of i.allowedComponentTypes){const i=e.motionController.getComponentOfType(t);if(null!==i){n=i;break}}if(i.mainComponentOnly){const t=e.motionController.getMainComponent();if(null===t)continue;n=t}if("function"==typeof i.componentSelectionPredicate&&(n=i.componentSelectionPredicate(e)),n&&i.forceHandedness&&e.inputSource.handedness!==i.forceHandedness)continue;if(null===n)continue;const s={registrationConfiguration:i,component:n};t.registeredComponents.push(s),"axisChangedHandler"in i&&(s.onAxisChangedObserver=n.onAxisValueChangedObservable.add((e=>{i.axisChangedHandler(e,this._movementState,this._featureContext,this._xrInput)}))),"buttonChangedhandler"in i&&(s.onButtonChangedObserver=n.onButtonStateChangedObservable.add((()=>{n.changes.pressed&&i.buttonChangedhandler(n.changes.pressed,this._movementState,this._featureContext,this._xrInput)})))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce((()=>{i()}))}},t&&void 0!==t.xrInput?(Array.isArray(t.customRegistrationConfigurations)?this._currentRegistrationConfigurations=t.customRegistrationConfigurations:this._currentRegistrationConfigurations=Cy.REGISTRATIONS.default,this._featureContext={movementEnabled:t.movementEnabled||!0,movementOrientationFollowsViewerPose:null===(i=t.movementOrientationFollowsViewerPose)||void 0===i||i,movementSpeed:null!==(n=t.movementSpeed)&&void 0!==n?n:1,movementThreshold:null!==(s=t.movementThreshold)&&void 0!==s?s:.25,rotationEnabled:null===(r=t.rotationEnabled)||void 0===r||r,rotationSpeed:null!==(a=t.rotationSpeed)&&void 0!==a?a:1,rotationThreshold:null!==(l=t.rotationThreshold)&&void 0!==l?l:.25},this._movementState={moveX:0,moveY:0,rotateX:0,rotateY:0},this._xrInput=t.xrInput):se.w1.Error('WebXRControllerMovement feature requires "xrInput" option.')}attach(){return!!super.attach()&&(this._xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._xrInput.onControllerRemovedObservable,(e=>{this._detachController(e.uniqueId)})),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach((e=>{this._detachController(e)})),this._controllers={},!0)}_onXRFrame(e){if(this.attach){if(null===this._movementDirection&&(this._movementDirection=this._xrInput.xrCamera.rotationQuaternion.clone()),0!==this._movementState.rotateX&&this._featureContext.rotationEnabled){const e=.001*this._xrSessionManager.scene.getEngine().getDeltaTime()*this._featureContext.rotationSpeed*this._movementState.rotateX*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);!0===this._featureContext.movementOrientationFollowsViewerPose?(this._xrInput.xrCamera.cameraRotation.y+=e,this._movementDirection=this._xrInput.xrCamera.rotationQuaternion.multiply(o._f.RotationYawPitchRoll(e,0,0))):this._movementDirection.multiplyInPlace(o._f.RotationYawPitchRoll(3*e,0,0))}else!0===this._featureContext.movementOrientationFollowsViewerPose&&this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion);0===this._movementState.moveX&&0===this._movementState.moveY||!this._featureContext.movementEnabled||(o.y3.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),o.P.TransformCoordinatesToRef(this._tmpTranslationDirection,this._tmpRotationMatrix,this._tmpMovementTranslation),this._tmpMovementTranslation.scaleInPlace(this._xrInput.xrCamera._computeLocalCameraSpeed()*this._featureContext.movementSpeed),this._xrInput.xrCamera.cameraDirection.addInPlace(this._tmpMovementTranslation))}}_detachController(e){const t=this._controllers[e];if(t){for(const e of t.registeredComponents)e.onAxisChangedObserver&&e.component.onAxisValueChangedObservable.remove(e.onAxisChangedObserver),e.onButtonChangedObserver&&e.component.onButtonStateChangedObservable.remove(e.onButtonChangedObserver);delete this._controllers[e]}}}Cy.Name=tt.MOVEMENT,Cy.REGISTRATIONS={default:[{allowedComponentTypes:[Z_.THUMBSTICK_TYPE,Z_.TOUCHPAD_TYPE],forceHandedness:"left",axisChangedHandler:(e,t,i)=>{t.rotateX=Math.abs(e.x)>i.rotationThreshold?e.x:0,t.rotateY=Math.abs(e.y)>i.rotationThreshold?e.y:0}},{allowedComponentTypes:[Z_.THUMBSTICK_TYPE,Z_.TOUCHPAD_TYPE],forceHandedness:"right",axisChangedHandler:(e,t,i)=>{t.moveX=Math.abs(e.x)>i.movementThreshold?e.x:0,t.moveY=Math.abs(e.y)>i.movementThreshold?e.y:0}}]},Cy.Version=1,it.AddWebXRFeature(Cy.Name,((e,t)=>()=>new Cy(e,t)),Cy.Version,!0);class yy extends nt{constructor(e,t){super(e),this.options=t,this._canvasContext=null,this._reflectionCubeMap=null,this._xrLightEstimate=null,this._xrLightProbe=null,this._xrWebGLBinding=null,this._lightDirection=o.P.Up().negateInPlace(),this._lightColor=a.Wo.White(),this._intensity=1,this._sphericalHarmonics=new Oh,this._cubeMapPollTime=Date.now(),this._lightEstimationPollTime=Date.now(),this._reflectionCubeMapTextureSize=16,this.directionalLight=null,this.onReflectionCubeMapUpdatedObservable=new r.y$,this._updateReflectionCubeMap=()=>{var e;if(!this._xrLightProbe)return;if(this.options.cubeMapPollInterval){const e=Date.now();if(e-this._cubeMapPollTime{this._xrLightProbe=e,this.options.disableCubeMapReflection||(this._reflectionCubeMap||(this._reflectionCubeMap=new Re(this._xrSessionManager.scene),this._reflectionCubeMap._isCube=!0,this._reflectionCubeMap.coordinatesMode=3,this.options.setSceneEnvironmentTexture&&(this._xrSessionManager.scene.environmentTexture=this._reflectionCubeMap)),this._xrLightProbe.addEventListener("reflectionchange",this._updateReflectionCubeMap))})),!0}detach(){const e=super.detach();return null===this._xrLightProbe||this.options.disableCubeMapReflection||(this._xrLightProbe.removeEventListener("reflectionchange",this._updateReflectionCubeMap),this._xrLightProbe=null),this._canvasContext=null,this._xrLightEstimate=null,this._xrWebGLBinding=null,e}dispose(){super.dispose(),this.onReflectionCubeMapUpdatedObservable.clear(),this.directionalLight&&(this.directionalLight.dispose(),this.directionalLight=null),null!==this._reflectionCubeMap&&(this._reflectionCubeMap._texture&&this._reflectionCubeMap._texture.dispose(),this._reflectionCubeMap.dispose(),this._reflectionCubeMap=null)}_onXRFrame(e){var t;if(null!==this._xrLightProbe){if(this.options.lightEstimationPollInterval){const e=Date.now();if(e-this._lightEstimationPollTime()=>new yy(e,t)),yy.Version,!1);class Ay extends nt{constructor(e){super(e),this.onEyeTrackingStartedObservable=new r.y$,this.onEyeTrackingEndedObservable=new r.y$,this.onEyeTrackingFrameUpdateObservable=new r.y$,this._eyeTrackingStartListener=e=>{this._latestEyeSpace=e.gazeSpace,this._gazeRay=new qe(o.P.Zero(),o.P.Forward()),this.onEyeTrackingStartedObservable.notifyObservers(this._gazeRay)},this._eyeTrackingEndListener=()=>{this._latestEyeSpace=null,this._gazeRay=null,this.onEyeTrackingEndedObservable.notifyObservers()},this.xrNativeFeatureName="eye-tracking",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce((()=>{this._init()}))}dispose(){super.dispose(),this._xrSessionManager.session.removeEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.removeEventListener("eyetrackingend",this._eyeTrackingEndListener),this.onEyeTrackingStartedObservable.clear(),this.onEyeTrackingEndedObservable.clear(),this.onEyeTrackingFrameUpdateObservable.clear()}get isEyeGazeValid(){return!!this._gazeRay}getEyeGaze(){return this._gazeRay}_onXRFrame(e){if(this.attached&&e&&this._latestEyeSpace&&this._gazeRay){const t=e.getPose(this._latestEyeSpace,this._xrSessionManager.referenceSpace);if(t){this._gazeRay.origin.set(t.transform.position.x,t.transform.position.y,t.transform.position.z);const e=t.transform.orientation;o.jp.Quaternion[0].set(e.x,e.y,e.z,e.w),this._xrSessionManager.scene.useRightHandedSystem?o.P.RightHandedForwardReadOnly.rotateByQuaternionToRef(o.jp.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,o.jp.Quaternion[0].z*=-1,o.jp.Quaternion[0].w*=-1,o.P.LeftHandedForwardReadOnly.rotateByQuaternionToRef(o.jp.Quaternion[0],this._gazeRay.direction)),this.onEyeTrackingFrameUpdateObservable.notifyObservers(this._gazeRay)}}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.addEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.addEventListener("eyetrackingend",this._eyeTrackingEndListener))}}Ay.Name=tt.EYE_TRACKING,Ay.Version=1,it.AddWebXRFeature(Ay.Name,(e=>()=>new Ay(e)),Ay.Version,!1);class Ry{constructor(e,t){this._samples=[],this._idx=0;for(let i=0;i=this._samples.length)throw new Error("Index out of bounds");return this._samples[(this._idx+e)%this._samples.length]}}class Py{constructor(){this._samples=new Ry(20),this._entropy=0,this.onFirstStepDetected=new r.y$}update(e,t,i,n){this._samples.push(e,t);const s=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=o.FM.Distance(s,this._samples.at(1)),this._entropy>this._entropyThreshold)return;let r;for(r=this._samePointCheckStartIdx;ra&&(l=E,a=S);if(ar*this._squaredProjectionDistanceThreshold)return;const _=o.jp.Vector3[0];_.set(i,n,0);const m=o.jp.Vector3[1];m.set(c.x,c.y,0);const g=o.P.Cross(_,m).z>0,v=s.clone(),T=s.clone();h.subtractToRef(s,c),g?(c.scaleAndAddToRef(this._axisToApexShrinkFactor,v),c.scaleAndAddToRef(this._axisToApexExtendFactor,T)):(c.scaleAndAddToRef(this._axisToApexExtendFactor,v),c.scaleAndAddToRef(this._axisToApexShrinkFactor,T)),this.onFirstStepDetected.notifyObservers({leftApex:v,rightApex:T,currentPosition:s,currentStepDirection:g?"right":"left"})}reset(){for(let e=0;ethis._maxT&&(this._maxT=this._t,this._maxTPosition.copyFromFloats(e,t)),!(this._vitalityi&&(this.onMovement.notifyObservers({deltaT:this._t-i}),i<.5&&this._t>=.5&&this.onFootfall.notifyObservers({foot:this._steppingLeft?"left":"right"})),this._t<.95*this._maxT&&(this._currentPosition.copyFromFloats(e,t),this._steppingLeft?this._leftApex.copyFrom(this._maxTPosition):this._rightApex.copyFrom(this._maxTPosition),this._reset(this._leftApex,this._rightApex,this._currentPosition,!this._steppingLeft)),!(this._axisLength<.03))}get _vitalityThreshold(){return.1}get forward(){return this._forward}}class My{static get _MillisecondsPerUpdate(){return 1e3/15}constructor(e){this._detector=new Py,this._walker=null,this._movement=new o.FM,this._millisecondsSinceLastUpdate=My._MillisecondsPerUpdate,this.movementThisFrame=o.P.Zero(),this._engine=e,this._detector.onFirstStepDetected.add((e=>{this._walker||(this._walker=new Iy(e.leftApex,e.rightApex,e.currentPosition,e.currentStepDirection),this._walker.onFootfall.add((()=>{console.log("Footfall!")})),this._walker.onMovement.add((e=>{this._walker.forward.scaleAndAddToRef(.024*e.deltaT,this._movement)})))}))}update(e,t){if(t.y=0,t.normalize(),this._millisecondsSinceLastUpdate+=this._engine.getDeltaTime(),this._millisecondsSinceLastUpdate>=My._MillisecondsPerUpdate){if(this._millisecondsSinceLastUpdate-=My._MillisecondsPerUpdate,this._detector.update(e.x,e.z,t.x,t.z),this._walker){this._walker.update(e.x,e.z)||(this._walker=null)}this._movement.scaleInPlace(.85)}this.movementThisFrame.set(this._movement.x,0,this._movement.y)}}class Oy extends nt{static get Name(){return tt.WALKING_LOCOMOTION}static get Version(){return 1}get locomotionTarget(){return this._locomotionTarget}set locomotionTarget(e){this._locomotionTarget=e,this._isLocomotionTargetWebXRCamera="WebXRCamera"===this._locomotionTarget.getClassName()}constructor(e,t){super(e),this._up=new o.P,this._forward=new o.P,this._position=new o.P,this._movement=new o.P,this._sessionManager=e,this.locomotionTarget=t.locomotionTarget,this._isLocomotionTargetWebXRCamera&&p.Y.Warn("Using walking locomotion directly on a WebXRCamera may have unintended interactions with other XR techniques. Using an XR space parent is highly recommended")}isCompatible(){return void 0===this._sessionManager.sessionMode||"immersive-vr"===this._sessionManager.sessionMode}attach(){return!(!this.isCompatible||!super.attach())&&(this._walker=new My(this._sessionManager.scene.getEngine()),!0)}detach(){return!!super.detach()&&(this._walker=null,!0)}_onXRFrame(e){const t=e.getViewerPose(this._sessionManager.baseReferenceSpace);if(!t)return;const i=this.locomotionTarget.getScene().useRightHandedSystem?1:-1,n=t.transform.matrix;this._up.copyFromFloats(n[4],n[5],i*n[6]),this._forward.copyFromFloats(n[8],n[9],i*n[10]),this._position.copyFromFloats(n[12],n[13],i*n[14]),this._forward.scaleAndAddToRef(.05,this._position),this._up.scaleAndAddToRef(-.05,this._position),this._walker.update(this._position,this._forward),this._movement.copyFrom(this._walker.movementThisFrame),this._isLocomotionTargetWebXRCamera||o.P.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}}it.AddWebXRFeature(Oy.Name,((e,t)=>()=>new Oy(e,t)),Oy.Version,!1);class Dy extends Sa{constructor(e,t,i,n,s,r){super(e,t,i,n,r),this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=n,this.isMultiview=s,this.createRTTProvider=r}}class Ny extends Ca{constructor(e,t,i){super(e.scene,i),this._xrSessionManager=e,this._xrWebGLBinding=t,this.layerWrapper=i,this._lastSubImages=new Map,this._compositionLayer=i.layer}_getRenderTargetForSubImage(e,t){var i,n,s,r;const o=this._lastSubImages.get(t),a="left"==t?0:1,l=null!==(i=e.colorTextureWidth)&&void 0!==i?i:e.textureWidth,h=null!==(n=e.colorTextureHeight)&&void 0!==n?n:e.textureHeight;if(!this._renderTargetTextures[a]||(null==o?void 0:o.textureWidth)!==l||(null==o?void 0:o.textureHeight)!==h){let t;const i=null!==(s=e.depthStencilTextureWidth)&&void 0!==s?s:l,n=null!==(r=e.depthStencilTextureHeight)&&void 0!==r?r:h;l!==i&&h!==n||(t=e.depthStencilTexture),this._renderTargetTextures[a]=this._createRenderTargetTexture(l,h,null,e.colorTexture,t,this.layerWrapper.isMultiview),this._framebufferDimensions={framebufferWidth:l,framebufferHeight:h}}return this._lastSubImages.set(t,e),this._renderTargetTextures[a]}_getSubImageForEye(e){const t=this._xrSessionManager.currentFrame;return t?this._xrWebGLBinding.getSubImage(this._compositionLayer,t,e):null}getRenderTargetTextureForEye(e){const t=this._getSubImageForEye(e);return t?this._getRenderTargetForSubImage(t,e):null}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}_setViewportForSubImage(e,t){var i,n;const s=null!==(i=t.colorTextureWidth)&&void 0!==i?i:t.textureWidth,r=null!==(n=t.colorTextureWidth)&&void 0!==n?n:t.textureHeight,o=t.viewport;e.x=o.x/s,e.y=o.y/r,e.width=o.width/s,e.height=o.height/r}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return!!i&&(this._setViewportForSubImage(e,i),!0)}}class Fy extends Dy{constructor(e,t,i){super((()=>e.textureWidth),(()=>e.textureHeight),e,"XRProjectionLayer",t,(e=>new wy(e,i,this))),this.layer=e}}class wy extends Ny{constructor(e,t,i){super(e,t,i),this.layerWrapper=i,this._projectionLayer=i.layer}_getSubImageForView(e){return this._xrWebGLBinding.getViewSubImage(this._projectionLayer,e)}getRenderTargetTextureForView(e){return this._getRenderTargetForSubImage(this._getSubImageForView(e),e.eye)}getRenderTargetTextureForEye(e){const t=this._lastSubImages.get(e);return t?this._getRenderTargetForSubImage(t,e):null}trySetViewportForView(e,t){const i=this._lastSubImages.get(t.eye)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}}const Ly={},By={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1};class Uy extends nt{constructor(e,t={}){super(e),this._options=t,this._existingLayers=[],this.xrNativeFeatureName="layers"}attach(){if(!super.attach())return!1;const e=this._xrSessionManager.scene.getEngine();this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this._existingLayers.length=0;const t=Object.assign({},By),i=this._options.preferMultiviewOnInit&&e.getCaps().multiview;return i&&(t.textureType="texture-array"),this.addXRSessionLayer(this.createProjectionLayer(t,i)),!0}detach(){return!!super.detach()&&(this._existingLayers.length=0,!0)}createXRWebGLLayer(e=Ly){const t=new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e);return new ya(t)}createProjectionLayer(e=By,t=!1){if(t&&"texture-array"!==e.textureType)throw new Error("Projection layers can only be made multiview if they use texture arrays. Set the textureType parameter to 'texture-array'.");if(!t&&"texture-array"===e.textureType)throw new Error("We currently only support multiview rendering when the textureType parameter is set to 'texture-array'.");const i=this._xrWebGLBinding.createProjectionLayer(e);return new Fy(i,t,this._xrWebGLBinding)}addXRSessionLayer(e){this.setXRSessionLayers([...this._existingLayers,e])}setXRSessionLayers(e){this._existingLayers=e;const t=Object.assign({},this._xrSessionManager.session.renderState);t.baseLayer=void 0,t.layers=e.map((e=>e.layer)),this._xrSessionManager.updateRenderState(t),this._xrSessionManager._setBaseLayerWrapper(e.length>0?e[0]:null)}isCompatible(){return!this._xrSessionManager.isNative&&"undefined"!=typeof XRWebGLBinding&&!!XRWebGLBinding.prototype.createProjectionLayer}dispose(){super.dispose()}_onXRFrame(e){}}Uy.Name=tt.LAYERS,Uy.Version=1,it.AddWebXRFeature(Uy.Name,((e,t)=>()=>new Uy(e,t)),Uy.Version,!1);class Vy extends nt{get width(){return this._width}get height(){return this._height}get rawValueToMeters(){return this._rawValueToMeters}get normDepthBufferFromNormView(){return this._normDepthBufferFromNormView}get depthUsage(){switch(this._xrSessionManager.session.depthUsage){case"cpu-optimized":return"cpu";case"gpu-optimized":return"gpu"}}get depthDataFormat(){switch(this._xrSessionManager.session.depthDataFormat){case"luminance-alpha":return"ushort";case"float32":return"float"}}get latestInternalTexture(){var e,t;if(!this._cachedWebGLTexture)return null;const i=this._xrSessionManager.scene.getEngine(),n=new Be.l(i,Be.S.Unknown);return n.isCube=!1,n.invertY=!1,n._useSRGBBuffer=!1,n.format="ushort"===this.depthDataFormat?2:5,n.generateMipMaps=!1,n.type="ushort"===this.depthDataFormat?5:1,n.samplingMode=7,n.width=null!==(e=this.width)&&void 0!==e?e:0,n.height=null!==(t=this.height)&&void 0!==t?t:0,n._cachedWrapU=1,n._cachedWrapV=1,n._hardwareTexture=new ba.B(this._cachedWebGLTexture,i._gl),n}get latestDepthBuffer(){return this._cachedDepthBuffer?"ushort"===this.depthDataFormat?new Uint16Array(this._cachedDepthBuffer):new Float32Array(this._cachedDepthBuffer):null}get latestDepthImageTexture(){return this._cachedDepthImageTexture}constructor(e,t){super(e),this.options=t,this._width=null,this._height=null,this._rawValueToMeters=null,this._normDepthBufferFromNormView=null,this._cachedDepthBuffer=null,this._cachedWebGLTexture=null,this._cachedDepthImageTexture=null,this.onGetDepthInMetersAvailable=new r.y$,this.xrNativeFeatureName="depth-sensing",se.w1.Warn("depth-sensing is an experimental and unstable feature.")}attach(e){if(!super.attach(e))return!1;return null!=this._xrSessionManager.session.depthDataFormat&&null!=this._xrSessionManager.session.depthUsage&&(this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._xrSessionManager.scene.getEngine()._gl),!0)}dispose(){var e;null===(e=this._cachedDepthImageTexture)||void 0===e||e.dispose()}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(null!=i)for(const n of i.views)switch(this.depthUsage){case"cpu":this._updateDepthInformationAndTextureCPUDepthUsage(e,n,this.depthDataFormat);break;case"gpu":if(!this._glBinding)break;this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding,n,this.depthDataFormat);break;default:se.w1.Error("Unknown depth usage"),this.detach()}}_updateDepthInformationAndTextureCPUDepthUsage(e,t,i){const n=e.getDepthInformation(t);if(null===n)return;const{data:s,width:r,height:o,rawValueToMeters:a,getDepthInMeters:l}=n;switch(this._width=r,this._height=o,this._rawValueToMeters=a,this._cachedDepthBuffer=s,this.onGetDepthInMetersAvailable.notifyObservers(l.bind(n)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=ze.CreateRTexture(null,r,o,this._xrSessionManager.scene,!1,!0,Le.NEAREST_SAMPLINGMODE,fe.D.TEXTURETYPE_FLOAT)),i){case"ushort":this._cachedDepthImageTexture.update(Float32Array.from(new Uint16Array(s)).map((e=>e*a)));break;case"float":this._cachedDepthImageTexture.update(new Float32Array(s).map((e=>e*a)))}}_updateDepthInformationAndTextureWebGLDepthUsage(e,t,i){const n=e.getDepthInformation(t);if(null===n)return;const{texture:s,width:r,height:o}=n;this._width=r,this._height=o,this._cachedWebGLTexture=s;const a=this._xrSessionManager.scene,l=a.getEngine().wrapWebGLTexture(s);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=ze.CreateRTexture(null,r,o,a,!1,!0,Le.NEAREST_SAMPLINGMODE,"ushort"===i?fe.D.TEXTURETYPE_UNSIGNED_BYTE:fe.D.TEXTURETYPE_FLOAT)),this._cachedDepthImageTexture._texture=l}getXRSessionInitExtension(){const e=null!=this.options.usagePreference&&0!==this.options.usagePreference.length,t=null!=this.options.dataFormatPreference&&0!==this.options.dataFormatPreference.length;return new Promise((i=>{if(e&&t){i({depthSensing:{usagePreference:this.options.usagePreference.map((e=>{switch(e){case"cpu":return"cpu-optimized";case"gpu":return"gpu-optimized"}})),dataFormatPreference:this.options.dataFormatPreference.map((e=>{switch(e){case"ushort":return"luminance-alpha";case"float":return"float32"}}))}})}else i({})}))}}Vy.Name=tt.DEPTH_SENSING,Vy.Version=1,it.AddWebXRFeature(Vy.Name,((e,t)=>()=>new Vy(e,t)),Vy.Version,!1);const ky="velocityPixelShader",Gy="precision highp float;\n#define CUSTOM_FRAGMENT_BEGIN\nvarying vec4 clipPos;\nvarying vec4 previousClipPos;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\nhighp vec4 motionVector=( clipPos/clipPos.w-previousClipPos/previousClipPos.w );\ngl_FragColor=motionVector;\n#define CUSTOM_FRAGMENT_MAIN_END\n}";Ht.v.ShadersStore[ky]=Gy;const zy="velocityVertexShader",Wy="#define CUSTOM_VERTEX_BEGIN\n#define VELOCITY\nattribute vec3 position;\n#include\nuniform mat4 viewProjection;\nuniform mat4 previousViewProjection;\n#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\nuniform mat4 previousViewProjectionR;\n#endif\nvarying vec4 clipPos;\nvarying vec4 previousClipPos;\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvec4 previousWorldPos=finalPreviousWorld*vec4(positionUpdated,1.0);\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {\nclipPos=viewProjection*worldPos;\npreviousClipPos=previousViewProjection*previousWorldPos;\ngl_Position=clipPos;\n} else {\nclipPos=viewProjectionR*worldPos;\npreviousClipPos=previousViewProjectionR*previousWorldPos;\ngl_Position=clipPos;\n}\n#elif\nclipPos=viewProjection*worldPos;\npreviousClipPos=previousViewProjection*previousWorldPos;\ngl_Position=clipPos;\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}";Ht.v.ShadersStore[zy]=Wy;class Hy extends Ci{constructor(e,t,i,n=512){super("spacewarp rtt",n,i,!1,!0,2,!1,void 0,!1,!1,!0,void 0,!0),this._originalPairing=[],this._previousWorldMatrices=[],this._previousTransforms=[o.y3.Identity(),o.y3.Identity()],this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight(),e,t),this._renderTarget._disposeOnlyFramebuffers=!0,this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,i&&(this._velocityMaterial=new Il("velocity shader material",i,{vertex:"velocity",fragment:"velocity"},{uniforms:["world","previousWorld","viewProjection","viewProjectionR","previousViewProjection","previousViewProjectionR"]}),this._velocityMaterial._materialHelperNeedsPreviousMatrices=!0,this._velocityMaterial.onBindObservable.add((e=>{this._previousWorldMatrices[e.uniqueId]=this._previousWorldMatrices[e.uniqueId]||e.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousWorld",this._previousWorldMatrices[e.uniqueId]),this._previousWorldMatrices[e.uniqueId]=e.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousViewProjection",this._previousTransforms[0]),this._velocityMaterial.getEffect().setMatrix("previousViewProjectionR",this._previousTransforms[1]),this._previousTransforms[0].copyFrom(i.getTransformMatrix()),this._previousTransforms[1].copyFrom(i._transformMatrixR)})),this._velocityMaterial.freeze())}render(e=!1,t=!1){this._originalPairing.length=0;const i=this.getScene();i&&this._velocityMaterial&&i.getActiveMeshes().forEach((e=>{this._originalPairing.push([e,e.material]),e.material=this._velocityMaterial})),super.render(e,t),this._originalPairing.forEach((e=>{e[0].material=e[1]}))}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindSpaceWarpFramebuffer(this._renderTarget)}getViewCount(){return 2}dispose(){super.dispose(),this._velocityMaterial.dispose(),this._previousTransforms.length=0,this._previousWorldMatrices.length=0,this._originalPairing.length=0}}class Xy{constructor(e,t,i){this._scene=e,this._xrSessionManager=t,this._xrWebGLBinding=i,this._lastSubImages=new Map,this._renderTargetTextures=new Map,this._engine=e.getEngine()}_getSubImageForView(e){const t=this._xrSessionManager._getBaseLayerWrapper();if(!t)throw new Error("For Space Warp, the base layer should be a WebXR Projection Layer.");if("XRProjectionLayer"!==t.layerType)throw new Error('For Space Warp, the base layer type should "XRProjectionLayer".');const i=t.layer;return this._xrWebGLBinding.getViewSubImage(i,e)}_setViewportForSubImage(e,t){e.x=0,e.y=0,e.width=t.motionVectorTextureWidth,e.height=t.motionVectorTextureHeight}_createRenderTargetTexture(e,t,i,n,s){if(!this._engine)throw new Error("Engine is disposed");const r={width:e,height:t},o=new Hy(n,s,this._scene,r),a=o.renderTarget;return i&&(a._framebuffer=i),a._colorTextureArray=n,a._depthStencilTextureArray=s,o.disableRescaling(),o.renderListPredicate=()=>!0,o}_getRenderTargetForSubImage(e,t){const i=this._lastSubImages.get(t);let n=this._renderTargetTextures.get(t.eye);const s=e.motionVectorTextureWidth,r=e.motionVectorTextureHeight;return n&&(null==i?void 0:i.textureWidth)===s&&(null==i?void 0:i.textureHeight)==r||(n=this._createRenderTargetTexture(s,r,null,e.motionVectorTexture,e.depthStencilTexture),this._renderTargetTextures.set(t.eye,n),this._framebufferDimensions={framebufferWidth:s,framebufferHeight:r}),this._lastSubImages.set(t,e),n}trySetViewportForView(e,t){const i=this._lastSubImages.get(t)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}accessMotionVector(e){const t=this._getSubImageForView(e);t&&(t.motionVectorTexture,t.depthStencilTexture)}getRenderTargetTextureForEye(e){return null}getRenderTargetTextureForView(e){const t=this._getSubImageForView(e);return t?this._getRenderTargetForSubImage(t,e):null}dispose(){this._renderTargetTextures.forEach((e=>e.dispose())),this._renderTargetTextures.clear()}}class Yy extends nt{constructor(e){super(e),this.dependsOn=[tt.LAYERS],this.xrNativeFeatureName="space-warp",this._xrSessionManager.scene.needsPreviousWorldMatrices=!0}attach(){if(!super.attach())return!1;const e=this._xrSessionManager.scene.getEngine();return this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this.spaceWarpRTTProvider=new Xy(this._xrSessionManager.scene,this._xrSessionManager,this._xrWebGLBinding),this._xrSessionManager.scene.onAfterRenderObservable.add(this._onAfterRender.bind(this)),!0}_onAfterRender(){this.attached&&this._renderTargetTexture&&this._renderTargetTexture.render(!1,!1)}isCompatible(){return this._xrSessionManager.scene.getEngine().getCaps().colorBufferHalfFloat||!1}dispose(){super.dispose()}_onXRFrame(e){const t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;const i=t.views[0];this._renderTargetTexture=this._renderTargetTexture||this.spaceWarpRTTProvider.getRenderTargetTextureForView(i),this.spaceWarpRTTProvider.accessMotionVector(i)}}Yy.Name=tt.SPACE_WARP,Yy.Version=1,it.AddWebXRFeature(Yy.Name,(e=>()=>new Yy(e)),Yy.Version,!1);class jy extends J_{constructor(e,t,i){super(e,Ky[i],t,i,!0),this.profileId="generic-hand-select-grasp"}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){}_updateModel(){}}sm.RegisterController("generic-hand-select-grasp",((e,t)=>new jy(t,e.gamepad,e.handedness)));const Ky={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-none",assetPath:"none.glb"}};class qy extends J_{constructor(e,t,i){super(e,$y["left-right"],t,i),this._mapping={defaultButton:{valueNodeName:"VALUE",unpressedNodeName:"UNPRESSED",pressedNodeName:"PRESSED"},defaultAxis:{valueNodeName:"VALUE",minNodeName:"MIN",maxNodeName:"MAX"},buttons:{"xr-standard-trigger":{rootNodeName:"SELECT",componentProperty:"button",states:["default","touched","pressed"]},"xr-standard-squeeze":{rootNodeName:"GRASP",componentProperty:"state",states:["pressed"]},"xr-standard-touchpad":{rootNodeName:"TOUCHPAD_PRESS",labelAnchorNodeName:"squeeze-label",touchPointNodeName:"TOUCH"},"xr-standard-thumbstick":{rootNodeName:"THUMBSTICK_PRESS",componentProperty:"state",states:["pressed"]}},axes:{"xr-standard-touchpad":{"x-axis":{rootNodeName:"TOUCHPAD_TOUCH_X"},"y-axis":{rootNodeName:"TOUCHPAD_TOUCH_Y"}},"xr-standard-thumbstick":{"x-axis":{rootNodeName:"THUMBSTICK_X"},"y-axis":{rootNodeName:"THUMBSTICK_Y"}}}},this.profileId="microsoft-mixed-reality"}_getFilenameAndPath(){let e="";e="left"===this.handedness?qy.MODEL_LEFT_FILENAME:qy.MODEL_RIGHT_FILENAME;return{filename:e,path:qy.MODEL_BASE_URL+"default/"}}_getModelLoadingConstraints(){const e=ht.IsPluginForExtensionAvailable(".glb");return e||p.Y.Warn("glTF / glb loaded was not registered, using generic controller instead"),e}_processLoadedModel(e){this.rootMesh&&(this.getComponentIds().forEach(((e,t)=>{if(!this.disableAnimation&&e&&this.rootMesh){const i=this._mapping.buttons[e],n=i.rootNodeName;if(!n)return void p.Y.Log("Skipping unknown button at index: "+t+" with mapped name: "+e);const s=this._getChildByName(this.rootMesh,n);if(!s)return void p.Y.Warn("Missing button mesh with name: "+n);if(i.valueMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.valueNodeName),i.pressedMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.pressedNodeName),i.unpressedMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.unpressedNodeName),i.valueMesh&&i.pressedMesh&&i.unpressedMesh){const t=this.getComponent(e);t&&t.onButtonStateChangedObservable.add((e=>{this._lerpTransform(i,e.value)}),void 0,!0)}else p.Y.Warn("Missing button submesh under mesh with name: "+n)}})),this.getComponentIds().forEach((e=>{const t=this.getComponent(e);t.isAxes()&&["x-axis","y-axis"].forEach((i=>{if(!this.rootMesh)return;const n=this._mapping.axes[e][i],s=this._getChildByName(this.rootMesh,n.rootNodeName);s?(n.valueMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.valueNodeName),n.minMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.minNodeName),n.maxMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.maxNodeName),n.valueMesh&&n.minMesh&&n.maxMesh?t&&t.onAxisValueChangedObservable.add((e=>{const t="x-axis"===i?e.x:e.y;this._lerpTransform(n,t,!0)}),void 0,!0):p.Y.Warn("Missing axis submesh under mesh with name: "+n.rootNodeName)):p.Y.Warn("Missing axis mesh with name: "+n.rootNodeName)}))})))}_setRootMesh(e){let t;this.rootMesh=new ee.Kj(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;inew qy(t,e.gamepad,e.handedness)));const $y={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-right",assetPath:"right.glb"}};class Qy extends J_{constructor(e,t,i,n=!1,s=!1){super(e,Zy[i],t,i),this._forceLegacyControllers=s,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";e="left"===this.handedness?Qy.MODEL_LEFT_FILENAME:Qy.MODEL_RIGHT_FILENAME;return{filename:e,path:this._isQuest()?Qy.QUEST_MODEL_BASE_URL:Qy.MODEL_BASE_URL}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){const t=this._isQuest(),i="right"===this.handedness?-1:1;this.getComponentIds().forEach((e=>{const n=e&&this.getComponent(e);n&&n.onButtonStateChangedObservable.add((n=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":return void(t||(this._modelRootNode.getChildren()[3].rotation.x=.2*-n.value,this._modelRootNode.getChildren()[3].position.y=.005*-n.value,this._modelRootNode.getChildren()[3].position.z=.005*-n.value));case"xr-standard-squeeze":return void(t||(this._modelRootNode.getChildren()[4].position.x=i*n.value*.0035));case"xr-standard-thumbstick":return;case"a-button":case"x-button":return void(t||(n.pressed?this._modelRootNode.getChildren()[1].position.y=-.001:this._modelRootNode.getChildren()[1].position.y=0));case"b-button":case"y-button":return void(t||(n.pressed?this._modelRootNode.getChildren()[2].position.y=-.001:this._modelRootNode.getChildren()[2].position.y=0))}}),void 0,!0)}))}_setRootMesh(e){this.rootMesh=new ee.Kj(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=o._f.FromEulerAngles(0,Math.PI,0)),e.forEach((e=>{e.isPickable=!1})),this._isQuest()?this._modelRootNode=e[0]:(this._modelRootNode=e[1],this.rootMesh.position.y=.034,this.rootMesh.position.z=.052),this._modelRootNode.parent=this.rootMesh}_updateModel(){}_isQuest(){return!!navigator.userAgent.match(/Quest/gi)&&!this._forceLegacyControllers}}Qy.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/",Qy.MODEL_LEFT_FILENAME="left.babylon",Qy.MODEL_RIGHT_FILENAME="right.babylon",Qy.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/",sm.RegisterController("oculus-touch",((e,t)=>new Qy(t,e.gamepad,e.handedness))),sm.RegisterController("oculus-touch-legacy",((e,t)=>new Qy(t,e.gamepad,e.handedness,!0)));const Zy={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"x-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"x_button",visualResponses:{}},"y-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"y_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"a-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"a_button",visualResponses:{}},"b-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"b_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-right",assetPath:"right.glb"}};class Jy extends J_{constructor(e,t,i){super(e,eA[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){return{filename:Jy.MODEL_FILENAME,path:Jy.MODEL_BASE_URL}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){this.getComponentIds().forEach((e=>{const t=e&&this.getComponent(e);t&&t.onButtonStateChangedObservable.add((t=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":return void(this._modelRootNode.getChildren()[6].rotation.x=.15*-t.value);case"xr-standard-touchpad":case"xr-standard-squeeze":return}}),void 0,!0)}))}_setRootMesh(e){this.rootMesh=new ee.Kj(this.profileId+" "+this.handedness,this.scene),e.forEach((e=>{e.isPickable=!1})),this._modelRootNode=e[1],this._modelRootNode.parent=this.rootMesh,this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=o._f.FromEulerAngles(0,Math.PI,0))}_updateModel(){}}Jy.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/",Jy.MODEL_FILENAME="wand.babylon",sm.RegisterController("htc-vive",((e,t)=>new Jy(t,e.gamepad,e.handedness)));const eA={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc-vive-none",assetPath:"none.glb"}};function tA(e,t,i,n){const s={externalResourceFunction:e=>n(e).then((e=>new Uint8Array(e)))};return i&&(s.uri="file:"===t?i:t+i),e instanceof ArrayBuffer?GLTFValidator.validateBytes(new Uint8Array(e),s):GLTFValidator.validateString(e,s)}function iA(){const e=[];onmessage=t=>{const i=t.data;switch(i.id){case"init":importScripts(i.url);break;case"validate":tA(i.data,i.rootUrl,i.fileName,(t=>new Promise(((i,n)=>{const s=e.length;e.push({resolve:i,reject:n}),postMessage({id:"getExternalResource",index:s,uri:t})})))).then((e=>{postMessage({id:"validate.resolve",value:e})}),(e=>{postMessage({id:"validate.reject",reason:e})}));break;case"getExternalResource.resolve":e[i.index].resolve(i.value);break;case"getExternalResource.reject":e[i.index].reject(i.reason)}}}!async function(e,t){(await new Promise((e=>{"undefined"==typeof _native?dc.addOnce((t=>e(t))):e(_native)})))[e]=t}("NativeXRFrame",class{get session(){return this._nativeImpl.session}constructor(e){this._nativeImpl=e,this._xrTransform=new XRRigidTransform,this._xrPose={transform:this._xrTransform,emulatedPosition:!1},this._xrPoseVectorData=new Float32Array(8),this.fillPoses=this._nativeImpl.fillPoses.bind(this._nativeImpl),this.getViewerPose=this._nativeImpl.getViewerPose.bind(this._nativeImpl),this.getHitTestResults=this._nativeImpl.getHitTestResults.bind(this._nativeImpl),this.getHitTestResultsForTransientInput=()=>{throw new Error("XRFrame.getHitTestResultsForTransientInput not supported on native.")},this.createAnchor=this._nativeImpl.createAnchor.bind(this._nativeImpl),this.getJointPose=this._nativeImpl.getJointPose.bind(this._nativeImpl),this.fillJointRadii=this._nativeImpl.fillJointRadii.bind(this._nativeImpl),this.getLightEstimate=()=>{throw new Error("XRFrame.getLightEstimate not supported on native.")},this.getImageTrackingResults=()=>{var e;return null!==(e=this._nativeImpl._imageTrackingResults)&&void 0!==e?e:[]}}getPose(e,t){if(!this._nativeImpl.getPoseData(e,t,this._xrPoseVectorData.buffer,this._xrTransform.matrix.buffer))return;const i=this._xrTransform.position;i.x=this._xrPoseVectorData[0],i.y=this._xrPoseVectorData[1],i.z=this._xrPoseVectorData[2],i.w=this._xrPoseVectorData[3];const n=this._xrTransform.orientation;return n.x=this._xrPoseVectorData[4],n.y=this._xrPoseVectorData[5],n.z=this._xrPoseVectorData[6],n.w=this._xrPoseVectorData[7],this._xrPose}get trackedAnchors(){return this._nativeImpl.trackedAnchors}get worldInformation(){return this._nativeImpl.worldInformation}get detectedPlanes(){return this._nativeImpl.detectedPlanes}get featurePointCloud(){return this._nativeImpl.featurePointCloud}getDepthInformation(e){throw new Error("This function is not available in Babylon Native")}});class nA{static ValidateAsync(e,t,i,n){const s=ArrayBuffer.isView(e)?e.slice().buffer:e;return"function"==typeof Worker?new Promise(((e,r)=>{const o=`${tA}(${iA})()`,a=URL.createObjectURL(new Blob([o],{type:"application/javascript"})),l=new Worker(a),h=e=>{l.removeEventListener("error",h),l.removeEventListener("message",c),r(e)},c=t=>{const i=t.data;switch(i.id){case"getExternalResource":n(i.uri).then((e=>{l.postMessage({id:"getExternalResource.resolve",index:i.index,value:e},[e])}),(e=>{l.postMessage({id:"getExternalResource.reject",index:i.index,reason:e})}));break;case"validate.resolve":l.removeEventListener("error",h),l.removeEventListener("message",c),e(i.value),l.terminate();break;case"validate.reject":l.removeEventListener("error",h),l.removeEventListener("message",c),r(i.reason),l.terminate()}};l.addEventListener("error",h),l.addEventListener("message",c),l.postMessage({id:"init",url:this.Configuration.url}),l.postMessage({id:"validate",data:s,rootUrl:t,fileName:i})})):(this._LoadScriptPromise||(this._LoadScriptPromise=se.w1.LoadScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then((()=>tA(s,t,i,n))))}}function sA(e,t,i){try{return Promise.resolve(new Uint8Array(e,t,i))}catch(n){return Promise.reject(n)}}var rA,oA,aA,lA,hA,cA,dA,uA,pA,fA,_A,mA;nA.Configuration={url:"https://preview.babylonjs.com/gltf_validator.js"},function(e){e[e.AUTO=0]="AUTO",e[e.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED"}(rA||(rA={})),function(e){e[e.NONE=0]="NONE",e[e.FIRST=1]="FIRST",e[e.ALL=2]="ALL"}(oA||(oA={})),function(e){e[e.LOADING=0]="LOADING",e[e.READY=1]="READY",e[e.COMPLETE=2]="COMPLETE"}(aA||(aA={}));class gA{constructor(){this.onParsedObservable=new r.y$,this.coordinateSystemMode=rA.AUTO,this.animationStartMode=oA.FIRST,this.compileMaterials=!1,this.useClipPlane=!1,this.compileShadowGenerators=!1,this.transparencyAsCoverage=!1,this.useRangeRequests=!1,this.createInstances=!0,this.alwaysComputeBoundingBox=!1,this.loadAllMaterials=!1,this.loadOnlyMaterials=!1,this.skipMaterials=!1,this.useSRGBBuffers=!0,this.targetFps=60,this.alwaysComputeSkeletonRootNode=!1,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable=new r.y$,this.onSkinLoadedObservable=new r.y$,this.onTextureLoadedObservable=new r.y$,this.onMaterialLoadedObservable=new r.y$,this.onCameraLoadedObservable=new r.y$,this.onCompleteObservable=new r.y$,this.onErrorObservable=new r.y$,this.onDisposeObservable=new r.y$,this.onExtensionLoadedObservable=new r.y$,this.validate=!1,this.onValidatedObservable=new r.y$,this._loader=null,this._state=null,this._requests=new Array,this.name="gltf",this.extensions={".gltf":{isBinary:!1},".glb":{isBinary:!0}},this.onLoaderStateChangedObservable=new r.y$,this._logIndentLevel=0,this._loggingEnabled=!1,this._log=this._logDisabled,this._capturePerformanceCounters=!1,this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled}set onParsed(e){this._onParsedObserver&&this.onParsedObservable.remove(this._onParsedObserver),this._onParsedObserver=this.onParsedObservable.add(e)}set onMeshLoaded(e){this._onMeshLoadedObserver&&this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver),this._onMeshLoadedObserver=this.onMeshLoadedObservable.add(e)}set onTextureLoaded(e){this._onTextureLoadedObserver&&this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver),this._onTextureLoadedObserver=this.onTextureLoadedObservable.add(e)}set onMaterialLoaded(e){this._onMaterialLoadedObserver&&this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver),this._onMaterialLoadedObserver=this.onMaterialLoadedObservable.add(e)}set onCameraLoaded(e){this._onCameraLoadedObserver&&this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver),this._onCameraLoadedObserver=this.onCameraLoadedObservable.add(e)}set onComplete(e){this._onCompleteObserver&&this.onCompleteObservable.remove(this._onCompleteObserver),this._onCompleteObserver=this.onCompleteObservable.add(e)}set onError(e){this._onErrorObserver&&this.onErrorObservable.remove(this._onErrorObserver),this._onErrorObserver=this.onErrorObservable.add(e)}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onExtensionLoaded(e){this._onExtensionLoadedObserver&&this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver),this._onExtensionLoadedObserver=this.onExtensionLoadedObservable.add(e)}get loggingEnabled(){return this._loggingEnabled}set loggingEnabled(e){this._loggingEnabled!==e&&(this._loggingEnabled=e,this._loggingEnabled?this._log=this._logEnabled:this._log=this._logDisabled)}get capturePerformanceCounters(){return this._capturePerformanceCounters}set capturePerformanceCounters(e){this._capturePerformanceCounters!==e&&(this._capturePerformanceCounters=e,this._capturePerformanceCounters?(this._startPerformanceCounter=this._startPerformanceCounterEnabled,this._endPerformanceCounter=this._endPerformanceCounterEnabled):(this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled))}set onValidated(e){this._onValidatedObserver&&this.onValidatedObservable.remove(this._onValidatedObserver),this._onValidatedObserver=this.onValidatedObservable.add(e)}dispose(){this._loader&&(this._loader.dispose(),this._loader=null);for(const e of this._requests)e.abort();this._requests.length=0,delete this._progressCallback,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable.clear(),this.onSkinLoadedObservable.clear(),this.onTextureLoadedObservable.clear(),this.onMaterialLoadedObservable.clear(),this.onCameraLoadedObservable.clear(),this.onCompleteObservable.clear(),this.onExtensionLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(void 0),this.onDisposeObservable.clear()}loadFile(e,t,i,n,s,o,a,l){if(ArrayBuffer.isView(t))return this._loadBinary(e,t,i,n,a,l),null;this._progressCallback=s;const h=t.name||se.w1.GetFilename(t);if(o){if(this.useRangeRequests){this.validate&&p.Y.Warn("glTF validation is not supported when range requests are enabled");const i={abort:()=>{},onCompleteObservable:new r.y$},s={readAsync:(i,n)=>new Promise(((s,r)=>{this._loadFile(e,t,(e=>{s(new Uint8Array(e))}),!0,(e=>{r(e)}),(e=>{e.setRequestHeader("Range",`bytes=${i}-${i+n-1}`)}))})),byteLength:0};return this._unpackBinaryAsync(new QC(s)).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),i,h),this._unpackBinaryAsync(new QC({readAsync:(e,i)=>sA(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=>{this._validate(e,new Uint8Array(t),i,h),n({json:this._parseJson(t)})}),o,a)}_loadBinary(e,t,i,n,s,r){this._validate(e,t,i,r),this._unpackBinaryAsync(new QC({readAsync:(e,i)=>function(e,t,i){try{if(e.byteOffset+i>e.byteLength)throw new Error("Array length out of bounds.");return Promise.resolve(new Uint8Array(e.buffer,e.byteOffset+t,i))}catch(n){return Promise.reject(n)}}(t,e,i),byteLength:t.byteLength})).then((e=>{n(e)}),s?e=>s(void 0,e):void 0)}importMeshAsync(e,t,i,n,s,r){return Promise.resolve().then((()=>(this.onParsedObservable.notifyObservers(i),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(i),this._loader.importMeshAsync(e,t,null,i,n,s,r))))}loadAsync(e,t,i,n,s){return Promise.resolve().then((()=>(this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${s||""}`),this._loader=this._getLoader(t),this._loader.loadAsync(e,t,i,n,s))))}loadAssetContainerAsync(e,t,i,n,s){return Promise.resolve().then((()=>{this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${s||""}`),this._loader=this._getLoader(t);const r=new pe(e),o=[];this.onMaterialLoadedObservable.add((e=>{o.push(e)}));const a=[];this.onTextureLoadedObservable.add((e=>{a.push(e)}));const l=[];this.onCameraLoadedObservable.add((e=>{l.push(e)}));const h=[];return this.onMeshLoadedObservable.add((e=>{e.morphTargetManager&&h.push(e.morphTargetManager)})),this._loader.importMeshAsync(null,e,r,t,i,n,s).then((e=>(Array.prototype.push.apply(r.geometries,e.geometries),Array.prototype.push.apply(r.meshes,e.meshes),Array.prototype.push.apply(r.particleSystems,e.particleSystems),Array.prototype.push.apply(r.skeletons,e.skeletons),Array.prototype.push.apply(r.animationGroups,e.animationGroups),Array.prototype.push.apply(r.materials,o),Array.prototype.push.apply(r.textures,a),Array.prototype.push.apply(r.lights,e.lights),Array.prototype.push.apply(r.transformNodes,e.transformNodes),Array.prototype.push.apply(r.cameras,l),Array.prototype.push.apply(r.morphTargetManagers,h),r)))}))}canDirectLoad(e){return-1!==e.indexOf("asset")&&-1!==e.indexOf("version")||e.startsWith("data:base64,"+gA._MagicBase64Encoded)||e.startsWith("data:;base64,"+gA._MagicBase64Encoded)||e.startsWith("data:application/octet-stream;base64,"+gA._MagicBase64Encoded)||e.startsWith("data:model/gltf-binary;base64,"+gA._MagicBase64Encoded)}directLoad(e,t){if(t.startsWith("base64,"+gA._MagicBase64Encoded)||t.startsWith(";base64,"+gA._MagicBase64Encoded)||t.startsWith("application/octet-stream;base64,"+gA._MagicBase64Encoded)||t.startsWith("model/gltf-binary;base64,"+gA._MagicBase64Encoded)){const i=(0,ye.$K)(t);return this._validate(e,new Uint8Array(i)),this._unpackBinaryAsync(new QC({readAsync:(e,t)=>sA(i,e,t),byteLength:i.byteLength}))}return this._validate(e,t),Promise.resolve({json:this._parseJson(t)})}createPlugin(){return new gA}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(aA[this._state]))}_loadFile(e,t,i,n,s,r){const o=e._loadFile(t,i,(e=>{this._onProgress(e,o)}),!0,n,s,r);return o.onCompleteObservable.add((e=>{this._requests.splice(this._requests.indexOf(e),1)})),this._requests.push(o),o}_onProgress(e,t){if(!this._progressCallback)return;t._lengthComputable=e.lengthComputable,t._loaded=e.loaded,t._total=e.total;let i=!0,n=0,s=0;for(const r of this._requests){if(void 0===r._lengthComputable||void 0===r._loaded||void 0===r._total)return;i=i&&r._lengthComputable,n+=r._loaded,s+=r._total}this._progressCallback({lengthComputable:i,loaded:n,total:i?s:0})}_validate(e,t,i="",n=""){this.validate&&(this._startPerformanceCounter("Validate JSON"),nA.ValidateAsync(t,i,n,(t=>this.preprocessUrlAsync(i+t).then((t=>e._loadFileAsync(t,void 0,!0,!0))))).then((e=>{this._endPerformanceCounter("Validate JSON"),this.onValidatedObservable.notifyObservers(e),this.onValidatedObservable.clear()}),(e=>{this._endPerformanceCounter("Validate JSON"),se.w1.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=gA._parseVersion(t.version);if(!i)throw new Error("Invalid version: "+t.version);if(void 0!==t.minVersion){const e=gA._parseVersion(t.minVersion);if(!e)throw new Error("Invalid minimum version: "+t.minVersion);if(gA._compareVersion(e,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}const n={1:gA._CreateGLTF1Loader,2:gA._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 lt.LH("Unexpected magic: "+t,lt.SM.GLTFLoaderUnexpectedMagicError);const i=e.readUint32();this.loggingEnabled&&this._log(`Binary version: ${i}`);const n=e.readUint32();let s;switch(this.useRangeRequests||n===e.buffer.byteLength||p.Y.Warn(`Length in header does not match actual data length: ${n} != ${e.buffer.byteLength}`),i){case 1:s=this._unpackBinaryV1Async(e,n);break;case 2:s=this._unpackBinaryV2Async(e,n);break;default:throw new Error("Unsupported version: "+i)}return this._endPerformanceCounter("Unpack Binary"),s}))}_unpackBinaryV1Async(e,t){const i=e.readUint32(),n=e.readUint32();if(0!==n)throw new Error(`Unexpected content format: ${n}`);const s=t-e.byteOffset,r={json:this._parseJson(e.readString(i)),bin:null};if(0!==s){const t=e.byteOffset;r.bin={readAsync:(i,n)=>e.buffer.readAsync(t+i,n),byteLength:s}}return Promise.resolve(r)}_unpackBinaryV2Async(e,t){const i=1313821514,n=5130562,s=e.readUint32();if(e.readUint32()!==i)throw new Error("First chunk format is not JSON");return e.byteOffset+s===t?e.loadAsync(s).then((()=>({json:this._parseJson(e.readString(s)),bin:null}))):e.loadAsync(s+8).then((()=>{const r={json:this._parseJson(e.readString(s)),bin:null},o=()=>{const s=e.readUint32();switch(e.readUint32()){case i:throw new Error("Unexpected JSON chunk");case n:{const t=e.byteOffset;r.bin={readAsync:(i,n)=>e.buffer.readAsync(t+i,n),byteLength:s},e.skipBytes(s);break}default:e.skipBytes(s)}return e.byteOffset!==t?e.loadAsync(8).then(o):Promise.resolve(r)};return o()}))}static _parseVersion(e){if("1.0"===e||"1.0.1"===e)return{major:1,minor:0};const t=(e+"").match(/^(\d+)\.(\d+)/);return t?{major:parseInt(t[1]),minor:parseInt(t[2])}:null}static _compareVersion(e,t){return e.major>t.major?1:e.majort.minor?1:e.minorr.byteLength)throw new Error("Buffer access is out of range");const o=r.buffer;switch(i+=r.byteOffset,s){case lA.BYTE:return new Int8Array(o,i,n);case lA.UNSIGNED_BYTE:return new Uint8Array(o,i,n);case lA.SHORT:return new Int16Array(o,i,n);case lA.UNSIGNED_SHORT:return new Uint16Array(o,i,n);default:return new Float32Array(o,i,n)}}static GetBufferFromAccessor(e,t){const i=e.bufferViews[t.bufferView],n=t.count*vA.GetByteStrideFromType(t);return vA.GetBufferFromBufferView(e,i,t.byteOffset,n,t.componentType)}static DecodeBufferToText(e){let t="";const i=e.byteLength;for(let n=0;n=this._maxPos}}const SA=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],EA=["world","view","projection","worldView","worldViewProjection","mBones"],xA=["translation","rotation","scale"],bA=["position","rotationQuaternion","scaling"],CA=(e,t,i)=>{for(const n in e){const s=e[n];i[t][n]=s}},yA=e=>{if(e)for(let t=0;t{if("NORMAL"===e.semantic)return"normal";if("POSITION"===e.semantic)return"position";if("JOINT"===e.semantic)return"matricesIndices";if("WEIGHT"===e.semantic)return"matricesWeights";if("COLOR"===e.semantic)return"color";if(e.semantic&&-1!==e.semantic.indexOf("TEXCOORD_")){const t=Number(e.semantic.split("_")[1]);return"uv"+(0===t?"":t+1)}return null},RA=e=>{let t=null;if(e.translation||e.rotation||e.scale){const i=o.P.FromArray(e.scale||[1,1,1]),n=o._f.FromArray(e.rotation||[0,0,0,1]),s=o.P.FromArray(e.translation||[0,0,0]);t=o.y3.Compose(i,n,s)}else t=o.y3.FromArray(e.matrix);return t},PA=(e,t,i,n)=>{for(let r=0;r{for(let i=0;i{const i=e.nodes;let n=i[t];if(n)return{node:n,id:t};for(const s in i)if(n=i[s],n.jointName===t)return{node:n,id:s};return null},OA=(e,t)=>{for(let i=0;i{if(n||(n=new ji(t.name||"","",e.scene)),!t.babylonSkeleton)return n;const s=[],r=[];((e,t,i,n)=>{for(const s in e.nodes){const r=e.nodes[s],o=s;if(!r.jointName||OA(i,r.jointName))continue;const a=RA(r),l=new B(r.name||"",t,null,a);l.id=o,n.push({bone:l,node:r,id:o})}for(let s=0;s0&&(d=IA(s,l),d&&-1===r.indexOf(d)&&r.push(d));new B(o.jointName||"",n,d,u).id=l}const o=n.bones;n.bones=[];for(let a=0;a{if(s||(e.scene._blockEntityCollection=!!e.assetContainer,(s=new ee.Kj(t.name||"",e.scene))._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,s.id=n),!t.babylonNode)return s;const r=[];let o=null;const a=new Array,l=new Array,h=new Array,c=new Array;for(let p=0;p1?(d=new zg.G("multimat"+n,e.scene),d.subMaterials=r):d=new _a("multimat"+n,e.scene),1===r.length&&(d=r[0]),d._parentContainer=e.assetContainer,s.material||(s.material=d),new Gg.Z(n,e.scene,o,!1,s),s.computeWorldMatrix(!0),e.scene._blockEntityCollection=!1,s.subMeshes=[];let u=0;for(let p=0;p{e.position&&(e.position=t),(e.rotationQuaternion||e.rotation)&&(e.rotationQuaternion=i),e.scaling&&(e.scaling=n)},wA=(e,t,i)=>{let n=null;if(e.importOnlyMeshes&&(t.skin||t.meshes)&&e.importMeshesNames&&e.importMeshesNames.length>0&&-1===e.importMeshesNames.indexOf(t.name||""))return null;if(t.skin){if(t.meshes){const s=e.skins[t.skin],r=NA(e,t,t.meshes,i,t.babylonNode);r.skeleton=e.scene.getLastSkeletonById(t.skin),null===r.skeleton&&(r.skeleton=DA(e,s,0,s.babylonSkeleton),s.babylonSkeleton||(s.babylonSkeleton=r.skeleton)),n=r}}else if(t.meshes){n=NA(e,t,t.mesh?[t.mesh]:t.meshes,i,t.babylonNode)}else if(!t.light||t.babylonNode||e.importOnlyMeshes){if(t.camera&&!t.babylonNode&&!e.importOnlyMeshes){const i=e.cameras[t.camera];if(i){if(e.scene._blockEntityCollection=!!e.assetContainer,"orthographic"===i.type){const i=new Fn(t.camera,o.P.Zero(),e.scene,!1);i.name=t.name||"",i.mode=ce.V.ORTHOGRAPHIC_CAMERA,i.attachControl(),n=i,i._parentContainer=e.assetContainer}else if("perspective"===i.type){const s=i[i.type],r=new Fn(t.camera,o.P.Zero(),e.scene,!1);r.name=t.name||"",r.attachControl(),s.aspectRatio||(s.aspectRatio=e.scene.getEngine().getRenderWidth()/e.scene.getEngine().getRenderHeight()),s.znear&&s.zfar&&(r.maxZ=s.zfar,r.minZ=s.znear),n=r,r._parentContainer=e.assetContainer}e.scene._blockEntityCollection=!1}}}else{const i=e.lights[t.light];if(i)if("ambient"===i.type){const s=i[i.type],r=new Os(t.light,o.P.Zero(),e.scene);r.name=t.name||"",s.color&&(r.diffuse=a.Wo.FromArray(s.color)),n=r}else if("directional"===i.type){const s=i[i.type],r=new sp(t.light,o.P.Zero(),e.scene);r.name=t.name||"",s.color&&(r.diffuse=a.Wo.FromArray(s.color)),n=r}else if("point"===i.type){const s=i[i.type],r=new Vg(t.light,o.P.Zero(),e.scene);r.name=t.name||"",s.color&&(r.diffuse=a.Wo.FromArray(s.color)),n=r}else if("spot"===i.type){const s=i[i.type],r=new op(t.light,o.P.Zero(),o.P.Zero(),0,0,e.scene);r.name=t.name||"",s.color&&(r.diffuse=a.Wo.FromArray(s.color)),s.fallOfAngle&&(r.angle=s.fallOfAngle),s.fallOffExponent&&(r.exponent=s.fallOffExponent),n=r}}if(!t.jointName){if(t.babylonNode)return t.babylonNode;if(null===n){e.scene._blockEntityCollection=!!e.assetContainer;const i=new ee.Kj(t.name||"",e.scene);i._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,t.babylonNode=i,n=i}}if(null!==n){if(t.matrix&&n instanceof ee.Kj)((e,t)=>{if(t.matrix){const i=new o.P(0,0,0),n=new o._f,s=new o.P(0,0,0);o.y3.FromArray(t.matrix).decompose(s,n,i),FA(e,i,n,s)}else t.translation&&t.rotation&&t.scale&&FA(e,o.P.FromArray(t.translation),o._f.FromArray(t.rotation),o.P.FromArray(t.scale));e.computeWorldMatrix(!0)})(n,t);else{const e=t.translation||[0,0,0],i=t.rotation||[0,0,0,1],s=t.scale||[1,1,1];FA(n,o.P.FromArray(e),o._f.FromArray(i),o.P.FromArray(s))}n.updateCache(!0),t.babylonNode=n}return n},LA=(e,t,i,n=!1)=>{const s=e.nodes[t];let r=null;if(n=!(e.importOnlyMeshes&&!n&&e.importMeshesNames)||(-1!==e.importMeshesNames.indexOf(s.name||"")||0===e.importMeshesNames.length),!s.jointName&&n&&(r=wA(e,s,t),null!==r&&(r.id=t,r.parent=i)),s.children)for(let o=0;o{let t=e.currentScene;if(t)for(let i=0;i{for(const t in e.animations){const i=e.animations[t];if(!i.channels||!i.samplers)continue;let n=null;for(let s=0;so=>{((e,t,i,n,s)=>{const r=n.values||i.parameters,o=i.uniforms;for(const a in s){const i=s[a],l=i.type;let h=r[o[a]];if(void 0===h&&(h=i.value),!h)continue;const c=e=>n=>{i.value&&e&&(t.setTexture(e,n),delete s[e])};l===cA.SAMPLER_2D?WA.LoadTextureAsync(e,n.values?h:i.value,c(a),(()=>c(null))):i.value&&vA.SetUniform(t,a,n.values?h:i.value,l)&&delete s[a]}})(e,t,i,n,s),t.onBind=o=>{((e,t,i,n,s,r,o)=>{const a=r.values||s.parameters;for(const l in i){const o=i[l],h=o.type;if(h===cA.FLOAT_MAT2||h===cA.FLOAT_MAT3||h===cA.FLOAT_MAT4)if(!o.semantic||o.source||o.node){if(o.semantic&&(o.source||o.node)){let e=t.scene.getNodeByName(o.source||o.node||"");if(null===e&&(e=t.scene.getNodeById(o.source||o.node||"")),null===e)continue;vA.SetMatrix(t.scene,e,o,l,n.getEffect())}}else vA.SetMatrix(t.scene,e,o,l,n.getEffect());else{const e=a[s.uniforms[l]];if(!e)continue;if(h===cA.SAMPLER_2D){const i=t.textures[r.values?e:o.value].babylonTexture;if(null==i)continue;n.getEffect().setTexture(l,i)}else vA.SetUniform(n.getEffect(),l,e,h)}}o(n)})(o,e,s,t,i,n,r)}},VA=(e,t,i)=>{for(const n in t.uniforms){const s=t.uniforms[n],r=t.parameters[s];if(e.currentIdentifier===n&&r.semantic&&!r.source&&!r.node){const e=SA.indexOf(r.semantic);if(-1!==e)return delete i[n],EA[e]}}return e.currentIdentifier},kA=e=>{for(const t in e.materials)WA.LoadMaterialAsync(e,t,(()=>{}),(()=>{}))};class GA{static CreateRuntime(e,t,i){const n={extensions:{},accessors:{},buffers:{},bufferViews:{},meshes:{},lights:{},cameras:{},nodes:{},images:{},textures:{},shaders:{},programs:{},samplers:{},techniques:{},materials:{},animations:{},skins:{},extensionsUsed:[],scenes:{},buffersCount:0,shaderscount:0,scene:t,rootUrl:i,loadedBufferCount:0,loadedBufferViews:{},loadedShaderCount:0,importOnlyMeshes:!1,dummyNodes:[],assetContainer:null};return e.extensions&&CA(e.extensions,"extensions",n),e.extensionsUsed&&CA(e.extensionsUsed,"extensionsUsed",n),e.buffers&&((e,t)=>{for(const i in e){const n=e[i];t.buffers[i]=n,t.buffersCount++}})(e.buffers,n),e.bufferViews&&CA(e.bufferViews,"bufferViews",n),e.accessors&&CA(e.accessors,"accessors",n),e.meshes&&CA(e.meshes,"meshes",n),e.lights&&CA(e.lights,"lights",n),e.cameras&&CA(e.cameras,"cameras",n),e.nodes&&CA(e.nodes,"nodes",n),e.images&&CA(e.images,"images",n),e.textures&&CA(e.textures,"textures",n),e.shaders&&((e,t)=>{for(const i in e){const n=e[i];t.shaders[i]=n,t.shaderscount++}})(e.shaders,n),e.programs&&CA(e.programs,"programs",n),e.samplers&&CA(e.samplers,"samplers",n),e.techniques&&CA(e.techniques,"techniques",n),e.materials&&CA(e.materials,"materials",n),e.animations&&CA(e.animations,"animations",n),e.skins&&CA(e.skins,"skins",n),e.scenes&&(n.scenes=e.scenes),e.scene&&e.scenes&&(n.currentScene=e.scenes[e.scene]),n}static LoadBufferAsync(e,t,i,n,s){const r=e.buffers[t];se.w1.IsBase64(r.uri)?setTimeout((()=>i(new Uint8Array(se.w1.DecodeBase64(r.uri))))):se.w1.LoadFile(e.rootUrl+r.uri,(e=>i(new Uint8Array(e))),s,void 0,!0,(e=>{e&&n(e.status+" "+e.statusText)}))}static LoadTextureBufferAsync(e,t,i,n){const s=e.textures[t];if(!s||!s.source)return void n("");if(s.babylonTexture)return void i(null);const r=e.images[s.source];se.w1.IsBase64(r.uri)?setTimeout((()=>i(new Uint8Array(se.w1.DecodeBase64(r.uri))))):se.w1.LoadFile(e.rootUrl+r.uri,(e=>i(new Uint8Array(e))),void 0,void 0,!0,(e=>{e&&n(e.status+" "+e.statusText)}))}static CreateTextureAsync(e,t,i,n){const s=e.textures[t];if(s.babylonTexture)return void n(s.babylonTexture);const r=e.samplers[s.sampler],o=r.minFilter===uA.NEAREST_MIPMAP_NEAREST||r.minFilter===uA.NEAREST_MIPMAP_LINEAR||r.minFilter===uA.LINEAR_MIPMAP_NEAREST||r.minFilter===uA.LINEAR_MIPMAP_LINEAR,a=Le.BILINEAR_SAMPLINGMODE,l=null==i?new Blob:new Blob([i]),h=URL.createObjectURL(l),c=()=>URL.revokeObjectURL(h),d=new Le(h,e.scene,!o,!0,a,c,c);void 0!==r.wrapS&&(d.wrapU=vA.GetWrapMode(r.wrapS)),void 0!==r.wrapT&&(d.wrapV=vA.GetWrapMode(r.wrapT)),d.name=t,s.babylonTexture=d,n(d)}static LoadShaderStringAsync(e,t,i,n){const s=e.shaders[t];if(se.w1.IsBase64(s.uri)){const e=atob(s.uri.split(",")[1]);i&&i(e)}else se.w1.LoadFile(e.rootUrl+s.uri,i,void 0,void 0,!1,(e=>{e&&n&&n(e.status+" "+e.statusText)}))}static LoadMaterialAsync(e,t,i,n){const s=e.materials[t];if(!s.technique)return void(n&&n("No technique found."));const r=e.techniques[s.technique];if(!r){e.scene._blockEntityCollection=!!e.assetContainer;const n=new _a(t,e.scene);return n._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,n.diffuseColor=new a.Wo(.5,.5,.5),n.sideOrientation=ut.F.CounterClockWiseSideOrientation,void i(n)}const o=e.programs[r.program],l=r.states,h=ft.Q.ShadersStore[o.vertexShader+"VertexShader"],c=ft.Q.ShadersStore[o.fragmentShader+"PixelShader"];let d="",u="";const p=new TA(h),f=new TA(c),_={},m=[],g=[],v=[];for(const a in r.uniforms){const e=r.uniforms[a],t=r.parameters[e];if(_[a]=t,!t.semantic||t.node||t.source)t.type===cA.SAMPLER_2D?v.push(a):m.push(a);else{const e=SA.indexOf(t.semantic);-1!==e?(m.push(EA[e]),delete _[a]):m.push(a)}}for(const a in r.attributes){const e=r.attributes[a],t=r.parameters[e];if(t.semantic){const e=AA(t);e&&g.push(e)}}for(;!p.isEnd()&&p.getNextToken();){if(p.currentToken!==mA.IDENTIFIER){d+=p.currentString;continue}let e=!1;for(const t in r.attributes){const i=r.attributes[t],n=r.parameters[i];if(p.currentIdentifier===t&&n.semantic){d+=AA(n),e=!0;break}}e||(d+=VA(p,r,_))}for(;!f.isEnd()&&f.getNextToken();){f.currentToken===mA.IDENTIFIER?u+=VA(f,r,_):u+=f.currentString}const T={vertex:o.vertexShader+t,fragment:o.fragmentShader+t},S={attributes:g,uniforms:m,samplers:v,needAlphaBlending:l&&l.enable&&-1!==l.enable.indexOf(3042)};ft.Q.ShadersStore[o.vertexShader+t+"VertexShader"]=d,ft.Q.ShadersStore[o.fragmentShader+t+"PixelShader"]=u;const E=new Il(t,e.scene,T,S);if(E.onError=((e,t,i)=>(n,s)=>{t.dispose(!0),i("Cannot compile program named "+e.name+". Error: "+s+". Default material will be applied")})(o,E,n),E.onCompiled=UA(e,E,r,s,_,i),E.sideOrientation=ut.F.CounterClockWiseSideOrientation,l&&l.functions){const e=l.functions;e.cullFace&&e.cullFace[0]!==fA.BACK&&(E.backFaceCulling=!1);const t=e.blendFuncSeparate;t&&(t[0]===_A.SRC_ALPHA&&t[1]===_A.ONE_MINUS_SRC_ALPHA&&t[2]===_A.ONE&&t[3]===_A.ONE?E.alphaMode=vh.ALPHA_COMBINE:t[0]===_A.ONE&&t[1]===_A.ONE&&t[2]===_A.ZERO&&t[3]===_A.ONE?E.alphaMode=vh.ALPHA_ONEONE:t[0]===_A.SRC_ALPHA&&t[1]===_A.ONE&&t[2]===_A.ZERO&&t[3]===_A.ONE?E.alphaMode=vh.ALPHA_ADD:t[0]===_A.ZERO&&t[1]===_A.ONE_MINUS_SRC_COLOR&&t[2]===_A.ONE&&t[3]===_A.ONE?E.alphaMode=vh.ALPHA_SUBTRACT:t[0]===_A.DST_COLOR&&t[1]===_A.ZERO&&t[2]===_A.ONE&&t[3]===_A.ONE?E.alphaMode=vh.ALPHA_MULTIPLY:t[0]===_A.SRC_ALPHA&&t[1]===_A.ONE_MINUS_SRC_COLOR&&t[2]===_A.ONE&&t[3]===_A.ONE&&(E.alphaMode=vh.ALPHA_MAXIMIZED))}}}class zA{static RegisterExtension(e){zA.Extensions[e.name]?se.w1.Error('Tool with the same name "'+e.name+'" already exists'):zA.Extensions[e.name]=e}dispose(){}_importMeshAsync(e,t,i,n,s,r,o,a){return t.useRightHandedSystem=!0,WA.LoadRuntimeAsync(t,i,n,(t=>{t.assetContainer=s,t.importOnlyMeshes=!0,""===e?t.importMeshesNames=[]:"string"==typeof e?t.importMeshesNames=[e]:!e||e instanceof Array?(t.importMeshesNames=[],se.w1.Warn("Argument meshesNames must be of type string or string[]")):t.importMeshesNames=[e],this._createNodes(t);const i=new Array,n=new Array;for(const e in t.nodes){const n=t.nodes[e];n.babylonNode instanceof ie.x&&i.push(n.babylonNode)}for(const e in t.skins){const i=t.skins[e];i.babylonSkeleton instanceof ji&&n.push(i.babylonSkeleton)}this._loadBuffersAsync(t,(()=>{this._loadShadersAsync(t,(()=>{kA(t),BA(t),!gA.IncrementalLoading&&r&&r(i,n)}))})),gA.IncrementalLoading&&r&&r(i,n)}),a),!0}importMeshAsync(e,t,i,n,s,r){return new Promise(((o,a)=>{this._importMeshAsync(e,t,n,s,i,((e,t)=>{o({meshes:e,particleSystems:[],skeletons:t,animationGroups:[],lights:[],transformNodes:[],geometries:[]})}),r,(e=>{a(new Error(e))}))}))}_loadAsync(e,t,i,n,s,r){e.useRightHandedSystem=!0,WA.LoadRuntimeAsync(e,t,i,(e=>{WA.LoadRuntimeExtensionsAsync(e,(()=>{this._createNodes(e),this._loadBuffersAsync(e,(()=>{this._loadShadersAsync(e,(()=>{kA(e),BA(e),gA.IncrementalLoading||n()}))})),gA.IncrementalLoading&&n()}),r)}),r)}loadAsync(e,t,i,n){return new Promise(((s,r)=>{this._loadAsync(e,t,i,(()=>{s()}),n,(e=>{r(new Error(e))}))}))}_loadShadersAsync(e,t){let i=!1;const n=(i,n)=>{WA.LoadShaderStringAsync(e,i,(s=>{s instanceof ArrayBuffer||(e.loadedShaderCount++,s&&(ft.Q.ShadersStore[i+(n.type===hA.VERTEX?"VertexShader":"PixelShader")]=s),e.loadedShaderCount===e.shaderscount&&t())}),(()=>{se.w1.Error("Error when loading shader program named "+i+" located at "+n.uri)}))};for(const s in e.shaders){i=!0;const t=e.shaders[s];t?n.bind(this,s,t)():se.w1.Error("No shader named: "+s)}i||t()}_loadBuffersAsync(e,t){let i=!1;const n=(i,n)=>{WA.LoadBufferAsync(e,i,(s=>{e.loadedBufferCount++,s&&(s.byteLength!=e.buffers[i].byteLength&&se.w1.Error("Buffer named "+i+" is length "+s.byteLength+". Expected: "+n.byteLength),e.loadedBufferViews[i]=s),e.loadedBufferCount===e.buffersCount&&t()}),(()=>{se.w1.Error("Error when loading buffer named "+i+" located at "+n.uri)}))};for(const s in e.buffers){i=!0;const t=e.buffers[s];t?n.bind(this,s,t)():se.w1.Error("No buffer named: "+s)}i||t()}_createNodes(e){let t=e.currentScene;if(t)for(let i=0;ir.loadRuntimeAsync(e,t,i,n,s)),(()=>{setTimeout((()=>{n&&n(GA.CreateRuntime(t.json,e,i))}))}))}static LoadRuntimeExtensionsAsync(e,t,i){WA._ApplyExtensions((n=>n.loadRuntimeExtensionsAsync(e,t,i)),(()=>{setTimeout((()=>{t()}))}))}static LoadBufferAsync(e,t,i,n,s){WA._ApplyExtensions((r=>r.loadBufferAsync(e,t,i,n,s)),(()=>{GA.LoadBufferAsync(e,t,i,n,s)}))}static LoadTextureAsync(e,t,i,n){WA._LoadTextureBufferAsync(e,t,(s=>{s&&WA._CreateTextureAsync(e,t,s,i,n)}),n)}static LoadShaderStringAsync(e,t,i,n){WA._ApplyExtensions((s=>s.loadShaderStringAsync(e,t,i,n)),(()=>{GA.LoadShaderStringAsync(e,t,i,n)}))}static LoadMaterialAsync(e,t,i,n){WA._ApplyExtensions((s=>s.loadMaterialAsync(e,t,i,n)),(()=>{GA.LoadMaterialAsync(e,t,i,n)}))}static _LoadTextureBufferAsync(e,t,i,n){WA._ApplyExtensions((s=>s.loadTextureBufferAsync(e,t,i,n)),(()=>{GA.LoadTextureBufferAsync(e,t,i,n)}))}static _CreateTextureAsync(e,t,i,n,s){WA._ApplyExtensions((r=>r.createTextureAsync(e,t,i,n,s)),(()=>{GA.CreateTextureAsync(e,t,i,n)}))}static _ApplyExtensions(e,t){for(const i in zA.Extensions){if(e(zA.Extensions[i]))return}t()}}gA._CreateGLTF1Loader=()=>new zA;zA.RegisterExtension(new class extends WA{constructor(){super("KHR_binary_glTF")}loadRuntimeAsync(e,t,i,n){const s=t.json.extensionsUsed;return!(!s||-1===s.indexOf(this.name)||!t.bin)&&(this._bin=t.bin,n(GA.CreateRuntime(t.json,e,i)),!0)}loadBufferAsync(e,t,i,n){return-1!==e.extensionsUsed.indexOf(this.name)&&("binary_glTF"===t&&(this._bin.readAsync(0,this._bin.byteLength).then(i,(e=>n(e.message))),!0))}loadTextureBufferAsync(e,t,i){const n=e.textures[t],s=e.images[n.source];if(!s.extensions||!(this.name in s.extensions))return!1;const r=s.extensions[this.name],o=e.bufferViews[r.bufferView];return i(vA.GetBufferFromBufferView(e,o,0,o.byteLength,lA.UNSIGNED_BYTE)),!0}loadShaderStringAsync(e,t,i){const n=e.shaders[t];if(!n.extensions||!(this.name in n.extensions))return!1;const s=n.extensions[this.name],r=e.bufferViews[s.bufferView],o=vA.GetBufferFromBufferView(e,r,0,r.byteLength,lA.UNSIGNED_BYTE);return setTimeout((()=>{const e=vA.DecodeBufferToText(o);i(e)})),!0}});function HA(e,t,i,n){return o.P.FromArray(t,i).scaleInPlace(n)}zA.RegisterExtension(new class extends WA{constructor(){super("KHR_materials_common")}loadRuntimeExtensionsAsync(e){if(!e.extensions)return!1;const t=e.extensions[this.name];if(!t)return!1;const i=t.lights;if(i)for(const n in i){const t=i[n];switch(t.type){case"ambient":{const i=new Os(t.name,new o.P(0,1,0),e.scene),n=t.ambient;n&&(i.diffuse=a.Wo.FromArray(n.color||[1,1,1]));break}case"point":{const i=new Vg(t.name,new o.P(10,10,10),e.scene),n=t.point;n&&(i.diffuse=a.Wo.FromArray(n.color||[1,1,1]));break}case"directional":{const i=new sp(t.name,new o.P(0,-1,0),e.scene),n=t.directional;n&&(i.diffuse=a.Wo.FromArray(n.color||[1,1,1]));break}case"spot":{const i=t.spot;if(i){new op(t.name,new o.P(0,10,0),new o.P(0,-1,0),i.fallOffAngle||Math.PI,i.fallOffExponent||0,e.scene).diffuse=a.Wo.FromArray(i.color||[1,1,1])}break}default:se.w1.Warn('GLTF Material Common extension: light type "'+t.type+"” not supported")}}return!1}loadMaterialAsync(e,t,i,n){const s=e.materials[t];if(!s||!s.extensions)return!1;const r=s.extensions[this.name];if(!r)return!1;const o=new _a(t,e.scene);return o.sideOrientation=ut.F.CounterClockWiseSideOrientation,"CONSTANT"===r.technique&&(o.disableLighting=!0),o.backFaceCulling=void 0!==r.doubleSided&&!r.doubleSided,o.alpha=void 0===r.values.transparency?1:r.values.transparency,o.specularPower=void 0===r.values.shininess?0:r.values.shininess,"string"==typeof r.values.ambient?this._loadTexture(e,r.values.ambient,o,"ambientTexture",n):o.ambientColor=a.Wo.FromArray(r.values.ambient||[0,0,0]),"string"==typeof r.values.diffuse?this._loadTexture(e,r.values.diffuse,o,"diffuseTexture",n):o.diffuseColor=a.Wo.FromArray(r.values.diffuse||[0,0,0]),"string"==typeof r.values.emission?this._loadTexture(e,r.values.emission,o,"emissiveTexture",n):o.emissiveColor=a.Wo.FromArray(r.values.emission||[0,0,0]),"string"==typeof r.values.specular?this._loadTexture(e,r.values.specular,o,"specularTexture",n):o.specularColor=a.Wo.FromArray(r.values.specular||[0,0,0]),!0}_loadTexture(e,t,i,n,s){GA.LoadTextureBufferAsync(e,t,(s=>{GA.CreateTextureAsync(e,t,s,(e=>i[n]=e))}),s)}});class XA{constructor(e,t,i,n){this.type=e,this.name=t,this.getValue=i,this.getStride=n}_buildAnimation(e,t,i){const n=new A(e,this.name,t,this.type);return n.setKeys(i),n}}class YA extends XA{buildAnimations(e,t,i,n,s){s(e._babylonTransformNode,this._buildAnimation(t,i,n))}}const jA={translation:[new YA(A.ANIMATIONTYPE_VECTOR3,"position",HA,(()=>3))],rotation:[new YA(A.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",(function(e,t,i,n){return o._f.FromArray(t,i).scaleInPlace(n)}),(()=>4))],scale:[new YA(A.ANIMATIONTYPE_VECTOR3,"scaling",HA,(()=>3))],weights:[new class extends XA{buildAnimations(e,t,i,n,s){if(e._numMorphTargets)for(let r=0;r({frame:e.frame,inTangent:e.inTangent?e.inTangent[r]:void 0,value:e.value[r],outTangent:e.outTangent?e.outTangent[r]:void 0,interpolation:e.interpolation})))),e._primitiveBabylonMeshes)for(const t of e._primitiveBabylonMeshes)if(t.morphTargetManager){const e=t.morphTargetManager.getTarget(r),i=o.clone();e.animations.push(i),s(e,i)}}}}(A.ANIMATIONTYPE_FLOAT,"influence",(function(e,t,i,n){const s=new Array(e._numMorphTargets);for(let r=0;re._numMorphTargets))]};function KA(...e){const t=e=>e&&"object"==typeof e;return e.reduce(((e,i)=>(Object.keys(i).forEach((n=>{const s=e[n],r=i[n];Array.isArray(s)&&Array.isArray(r)?e[n]=s.concat(...r):t(s)&&t(r)?e[n]=KA(s,r):e[n]=r})),e)),{})}class qA{static Get(e,t,i){if(!t||null==i||!t[i])throw new Error(`${e}: Failed to find index (${i})`);return t[i]}static Assign(e){if(e)for(let t=0;te.dispose&&e.dispose())),this._extensions.length=0,this._gltf=null,this._bin=null,this._babylonScene=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions.length=0,this._parent.dispose())}importMeshAsync(e,t,i,n,s,r,o=""){return Promise.resolve().then((()=>{this._babylonScene=t,this._assetContainer=i,this._loadData(n);let r=null;if(e){const t={};if(this._gltf.nodes)for(const e of this._gltf.nodes)e.name&&(t[e.name]=e.index);r=(e instanceof Array?e:[e]).map((e=>{const i=t[e];if(void 0===i)throw new Error(`Failed to find node '${e}'`);return i}))}return this._loadAsync(s,o,r,(()=>({meshes:this._getMeshes(),particleSystems:[],skeletons:this._getSkeletons(),animationGroups:this._getAnimationGroups(),lights:this._babylonLights,transformNodes:this._getTransformNodes(),geometries:this._getGeometries()})))}))}loadAsync(e,t,i,n,s=""){return Promise.resolve().then((()=>(this._babylonScene=e,this._loadData(t),this._loadAsync(i,s,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._loadExtensions(),this._checkExtensions();const s=`${aA[aA.LOADING]} => ${aA[aA.READY]}`,r=`${aA[aA.LOADING]} => ${aA[aA.COMPLETE]}`;this._parent._startPerformanceCounter(s),this._parent._startPerformanceCounter(r),this._parent._setState(aA.LOADING),this._extensionsOnLoading();const o=new Array,a=this._babylonScene.blockMaterialDirtyMechanism;if(this._babylonScene.blockMaterialDirtyMechanism=!0,!this.parent.loadOnlyMaterials)if(i)o.push(this.loadSceneAsync("/nodes",{nodes:i,index:-1}));else if(null!=this._gltf.scene||this._gltf.scenes&&this._gltf.scenes[0]){const e=qA.Get("/scene",this._gltf.scenes,this._gltf.scene||0);o.push(this.loadSceneAsync(`/scenes/${e.index}`,e))}if(!this.parent.skipMaterials&&this.parent.loadAllMaterials&&this._gltf.materials)for(let e=0;e{})))}this._babylonScene.blockMaterialDirtyMechanism=a,this._parent.compileMaterials&&o.push(this._compileMaterialsAsync()),this._parent.compileShadowGenerators&&o.push(this._compileShadowGeneratorsAsync());return Promise.all(o).then((()=>(this._rootBabylonMesh&&this._rootBabylonMesh.setEnabled(!0),this._extensionsOnReady(),this._parent._setState(aA.READY),this._startAnimations(),n()))).then((e=>(this._parent._endPerformanceCounter(s),se.w1.SetImmediate((()=>{this._disposed||Promise.all(this._completePromises).then((()=>{this._parent._endPerformanceCounter(r),this._parent._setState(aA.COMPLETE),this._parent.onCompleteObservable.notifyObservers(void 0),this._parent.onCompleteObservable.clear(),this.dispose()}),(e=>{this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()}))})),e)))})).catch((e=>{throw this._disposed||(this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()),e}))}_loadData(e){if(this._gltf=e.json,this._setupData(),e.bin){const t=this._gltf.buffers;if(t&&t[0]&&!t[0].uri){const i=t[0];(i.byteLengthe.bin.byteLength)&&p.Y.Warn(`Binary buffer length (${i.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else p.Y.Warn("Unexpected BIN chunk")}}_setupData(){if(qA.Assign(this._gltf.accessors),qA.Assign(this._gltf.animations),qA.Assign(this._gltf.buffers),qA.Assign(this._gltf.bufferViews),qA.Assign(this._gltf.cameras),qA.Assign(this._gltf.images),qA.Assign(this._gltf.materials),qA.Assign(this._gltf.meshes),qA.Assign(this._gltf.nodes),qA.Assign(this._gltf.samplers),qA.Assign(this._gltf.scenes),qA.Assign(this._gltf.skins),qA.Assign(this._gltf.textures),this._gltf.nodes){const e={};for(const i of this._gltf.nodes)if(i.children)for(const t of i.children)e[t]=i.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 $A._RegisteredExtensions){const t=$A._RegisteredExtensions[e].factory(this);t.name!==e&&p.Y.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)))throw new Error(`Require extension ${e} is not available`)}}_createRootNode(){this._babylonScene._blockEntityCollection=!!this._assetContainer,this._rootBabylonMesh=new ee.Kj("__root__",this._babylonScene),this._rootBabylonMesh._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._rootBabylonMesh.setEnabled(!1);const e={_babylonTransformNode:this._rootBabylonMesh,index:-1};switch(this._parent.coordinateSystemMode){case rA.AUTO:this._babylonScene.useRightHandedSystem||(e.rotation=[0,1,0,0],e.scale=[1,1,-1],$A._LoadTransform(e,this._rootBabylonMesh));break;case rA.FORCE_RIGHT_HANDED:this._babylonScene.useRightHandedSystem=!0;break;default:throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`)}return this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh),e}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 s of t.nodes){const t=qA.Get(`${e}/nodes/${s}`,this._gltf.nodes,s);n.push(this.loadNodeAsync(`/nodes/${t.index}`,t,(e=>{e.parent=this._rootBabylonMesh})))}for(const s of this._postSceneLoadActions)s();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=new Array,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=new Array;this._rootBabylonMesh&&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=new Array,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=new Array,t=this._gltf.skins;if(t)for(const i of t)i._data&&e.push(i._data.babylonSkeleton);return e}_getAnimationGroups(){const e=new Array,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 oA.NONE:break;case oA.FIRST:{const e=this._getAnimationGroups();0!==e.length&&e[0].start(!0);break}case oA.ALL:{const e=this._getAnimationGroups();for(const t of e)t.start(!0);break}default:return void p.Y.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 s=new Array;this.logOpen(`${e} ${t.name||""}`);const r=n=>{if($A.AddPointerMetadata(n,e),$A._LoadTransform(t,n),null!=t.camera){const i=qA.Get(`${e}/camera`,this._gltf.cameras,t.camera);s.push(this.loadCameraAsync(`/cameras/${i.index}`,i,(e=>{e.parent=n})))}if(t.children)for(const i of t.children){const t=qA.Get(`${e}/children/${i}`,this._gltf.nodes,i);s.push(this.loadNodeAsync(`/nodes/${t.index}`,t,(e=>{e.parent=n})))}i(n)};if(null==t.mesh||null!=t.skin){const e=t.name||`node${t.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new te.Y(e,this._babylonScene);i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,null==t.mesh?t._babylonTransformNode=i:t._babylonTransformNodeForSkin=i,r(i)}if(null!=t.mesh)if(null==t.skin){const i=qA.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);s.push(this._loadMeshAsync(`/meshes/${i.index}`,t,i,r))}else{const i=qA.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);s.push(this._loadMeshAsync(`/meshes/${i.index}`,t,i,(i=>{const n=t._babylonTransformNodeForSkin;i.metadata=KA(n.metadata,i.metadata||{});const r=qA.Get(`${e}/skin`,this._gltf.skins,t.skin);s.push(this._loadSkinAsync(`/skins/${r.index}`,t,r,(e=>{this._forEachPrimitive(t,(t=>{t.skeleton=e})),this._postSceneLoadActions.push((()=>{if(null!=r.skeleton){const e=qA.Get(`/skins/${r.index}/skeleton`,this._gltf.nodes,r.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})}))})))})))}return this.logClose(),Promise.all(s).then((()=>(this._forEachPrimitive(t,(e=>{e.geometry&&e.geometry.useBoundingInfoFromGeometry?e._updateBoundingInfo():e.refreshBoundingInfo(!0)})),t._babylonTransformNode)))}_loadMeshAsync(e,t,i,n){const s=i.primitives;if(!s||!s.length)throw new Error(`${e}: Primitives are missing`);null==s[0].index&&qA.Assign(s);const r=new Array;this.logOpen(`${e} ${i.name||""}`);const o=t.name||`node${t.index}`;if(1===s.length){const n=i.primitives[0];r.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${n.index}`,o,t,i,n,(e=>{t._babylonTransformNode=e,t._primitiveBabylonMeshes=[e]})))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,t._babylonTransformNode=new te.Y(o,this._babylonScene),t._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._primitiveBabylonMeshes=[];for(const n of s)r.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${n.index}`,`${o}_primitive${n.index}`,t,i,n,(e=>{e.parent=t._babylonTransformNode,t._primitiveBabylonMeshes.push(e)})))}return n(t._babylonTransformNode),this.logClose(),Promise.all(r).then((()=>t._babylonTransformNode))}_loadMeshPrimitiveAsync(e,t,i,n,s,r){const o=this._extensionsLoadMeshPrimitiveAsync(e,t,i,n,s,r);if(o)return o;this.logOpen(`${e}`);const a=0===this._disableInstancedMesh&&this._parent.createInstances&&null==i.skin&&!n.primitives[0].targets;let l,h;if(a&&s._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,l=s._instanceData.babylonSourceMesh.createInstance(t),l._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,h=s._instanceData.promise;else{const r=new Array;this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new ee.Kj(t,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,o.overrideMaterialSideOrientation=this._babylonScene.useRightHandedSystem?ut.F.CounterClockWiseSideOrientation:ut.F.ClockWiseSideOrientation,this._createMorphTargets(e,i,n,s,o),r.push(this._loadVertexDataAsync(e,s,o).then((t=>this._loadMorphTargetsAsync(e,s,o,t).then((()=>{this._disposed||(this._babylonScene._blockEntityCollection=!!this._assetContainer,t.applyToMesh(o),t._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1)})))));const c=$A._GetDrawMode(e,s.mode);if(null==s.material){let e=this._defaultBabylonMaterialData[c];e||(e=this._createDefaultMaterial("__GLTFLoader._default",c),this._parent.onMaterialLoadedObservable.notifyObservers(e),this._defaultBabylonMaterialData[c]=e),o.material=e}else if(!this.parent.skipMaterials){const t=qA.Get(`${e}/material`,this._gltf.materials,s.material);r.push(this._loadMaterialAsync(`/materials/${t.index}`,t,o,c,(e=>{o.material=e})))}h=Promise.all(r),a&&(s._instanceData={babylonSourceMesh:o,promise:h}),l=o}return $A.AddPointerMetadata(l,e),this._parent.onMeshLoadedObservable.notifyObservers(l),r(l),this.logClose(),h.then((()=>l))}_loadVertexDataAsync(e,t,i){const n=this._extensionsLoadVertexDataAsync(e,t,i);if(n)return n;const s=t.attributes;if(!s)throw new Error(`${e}: Attributes are missing`);const r=new Array,a=new Gg.Z(i.name,this._babylonScene);if(null==t.indices)i.isUnIndexed=!0;else{const i=qA.Get(`${e}/indices`,this._gltf.accessors,t.indices);r.push(this._loadIndicesAccessorAsync(`/accessors/${i.index}`,i).then((e=>{a.setIndices(e)})))}const l=(t,n,l)=>{if(null==s[t])return;i._delayInfo=i._delayInfo||[],-1===i._delayInfo.indexOf(n)&&i._delayInfo.push(n);const h=qA.Get(`${e}/attributes/${t}`,this._gltf.accessors,s[t]);r.push(this._loadVertexAccessorAsync(`/accessors/${h.index}`,h,n).then((e=>{if(e.getKind()===ne.o.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!i.skeleton&&h.min&&h.max){const e=o.jp.Vector3[0].copyFromFloats(...h.min),t=o.jp.Vector3[1].copyFromFloats(...h.max);if(h.normalized&&5126!==h.componentType){let i=1;switch(h.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 ol.j(e,t),a.useBoundingInfoFromGeometry=!0}a.setVerticesBuffer(e,h.count)}))),n==ne.o.MatricesIndicesExtraKind&&(i.numBoneInfluencers=8),l&&l(h)};return l("POSITION",ne.o.PositionKind),l("NORMAL",ne.o.NormalKind),l("TANGENT",ne.o.TangentKind),l("TEXCOORD_0",ne.o.UVKind),l("TEXCOORD_1",ne.o.UV2Kind),l("TEXCOORD_2",ne.o.UV3Kind),l("TEXCOORD_3",ne.o.UV4Kind),l("TEXCOORD_4",ne.o.UV5Kind),l("TEXCOORD_5",ne.o.UV6Kind),l("JOINTS_0",ne.o.MatricesIndicesKind),l("WEIGHTS_0",ne.o.MatricesWeightsKind),l("JOINTS_1",ne.o.MatricesIndicesExtraKind),l("WEIGHTS_1",ne.o.MatricesWeightsExtraKind),l("COLOR_0",ne.o.ColorKind,(e=>{"VEC4"===e.type&&(i.hasVertexAlpha=!0)})),Promise.all(r).then((()=>a))}_createMorphTargets(e,t,i,n,s){if(!n.targets)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 r=i.extras?i.extras.targetNames:null;this._babylonScene._blockEntityCollection=!!this._assetContainer,s.morphTargetManager=new Jg(this._babylonScene),s.morphTargetManager._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,s.morphTargetManager.areUpdatesFrozen=!0;for(let o=0;o{r.areUpdatesFrozen=!1}))}_loadMorphTargetVertexDataAsync(e,t,i,n){const s=new Array,r=(n,r,o)=>{if(null==i[n])return;const a=t.getVertexBuffer(r);if(!a)return;const l=qA.Get(`${e}/${n}`,this._gltf.accessors,i[n]);s.push(this._loadFloatAccessorAsync(`/accessors/${l.index}`,l).then((e=>{o(a,e)})))};return r("POSITION",ne.o.PositionKind,((e,t)=>{const i=new Float32Array(t.length);e.forEach(t.length,((e,n)=>{i[n]=t[n]+e})),n.setPositions(i)})),r("NORMAL",ne.o.NormalKind,((e,t)=>{const i=new Float32Array(t.length);e.forEach(i.length,((e,n)=>{i[n]=t[n]+e})),n.setNormals(i)})),r("TANGENT",ne.o.TangentKind,((e,t)=>{const i=new Float32Array(t.length/3*4);let s=0;e.forEach(t.length/3*4,((e,n)=>{(n+1)%4!=0&&(i[s]=t[s]+e,s++)})),n.setTangents(i)})),Promise.all(s).then((()=>{}))}static _LoadTransform(e,t){if(null!=e.skin)return;let i=o.P.Zero(),n=o._f.Identity(),s=o.P.One();if(e.matrix){o.y3.FromArray(e.matrix).decompose(s,n,i)}else e.translation&&(i=o.P.FromArray(e.translation)),e.rotation&&(n=o._f.FromArray(e.rotation)),e.scale&&(s=o.P.FromArray(e.scale));t.position=i,t.rotationQuaternion=n,t.scaling=s}_loadSkinAsync(e,t,i,n){const s=this._extensionsLoadSkinAsync(e,t,i);if(s)return s;if(i._data)return n(i._data.babylonSkeleton),i._data.promise;const r=`skeleton${i.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new ji(i.name||r,r,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._loadBones(e,i,o);const a=this._loadSkinInverseBindMatricesDataAsync(e,i).then((e=>{this._updateBoneMatrices(o,e)}));return i._data={babylonSkeleton:o,promise:a},n(o),a}_loadBones(e,t,i){if(null==t.skeleton||this._parent.alwaysComputeSkeletonRootNode){const i=this._findSkeletonRootNode(`${e}/joints`,t.joints);if(i)if(void 0===t.skeleton)t.skeleton=i.index;else{const n=(e,t)=>{for(;t.parent;t=t.parent)if(t.parent===e)return!0;return!1},s=qA.Get(`${e}/skeleton`,this._gltf.nodes,t.skeleton);s===i||n(s,i)||(p.Y.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),t.skeleton=i.index)}else p.Y.Warn(`${e}: Failed to find common root`)}const n={};for(const s of t.joints){const r=qA.Get(`${e}/joints/${s}`,this._gltf.nodes,s);this._loadBone(r,t,i,n)}}_findSkeletonRootNode(e,t){if(0===t.length)return null;const i={};for(const s of t){const t=new Array;let n=qA.Get(`${e}/${s}`,this._gltf.nodes,s);for(;-1!==n.index;)t.unshift(n),n=n.parent;i[s]=t}let n=null;for(let s=0;;++s){let e=i[t[0]];if(s>=e.length)return n;const r=e[s];for(let o=1;o=e.length||r!==e[s])return n;n=r}}_loadBone(e,t,i,n){let s=n[e.index];if(s)return s;let r=null;e.index!==t.skeleton&&(e.parent&&-1!==e.parent.index?r=this._loadBone(e.parent,t,i,n):void 0!==t.skeleton&&p.Y.Warn(`/skins/${t.index}/skeleton: Skeleton node is not a common root`));const o=t.joints.indexOf(e.index);return s=new B(e.name||`joint${e.index}`,i,r,this._getNodeMatrix(e),null,null,o),n[e.index]=s,this._postSceneLoadActions.push((()=>{s.linkTransformNode(e._babylonTransformNode)})),s}_loadSkinInverseBindMatricesDataAsync(e,t){if(null==t.inverseBindMatrices)return Promise.resolve(null);const i=qA.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=o.y3.Identity(),n=i._index;t&&-1!==n&&(o.y3.FromArrayToRef(t,16*n,e),e.invertToRef(e));const s=i.getParent();s&&e.multiplyToRef(s.getAbsoluteInverseBindMatrix(),e),i.updateMatrix(e,!1,!1),i._updateAbsoluteBindMatrices(void 0,!1)}}_getNodeMatrix(e){return e.matrix?o.y3.FromArray(e.matrix):o.y3.Compose(e.scale?o.P.FromArray(e.scale):o.P.One(),e.rotation?o._f.FromArray(e.rotation):o._f.Identity(),e.translation?o.P.FromArray(e.translation):o.P.Zero())}loadCameraAsync(e,t,i=(()=>{})){const n=this._extensionsLoadCameraAsync(e,t,i);if(n)return n;const s=new Array;this.logOpen(`${e} ${t.name||""}`),this._babylonScene._blockEntityCollection=!!this._assetContainer;const r=new Fn(t.name||`camera${t.index}`,o.P.Zero(),this._babylonScene,!1);switch(r._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,r.ignoreParentScaling=!0,t._babylonCamera=r,r.rotation=new o.P(0,Math.PI,0),t.type){case"perspective":{const i=t.perspective;if(!i)throw new Error(`${e}: Camera perspective properties are missing`);r.fov=i.yfov,r.minZ=i.znear,r.maxZ=i.zfar||0;break}case"orthographic":if(!t.orthographic)throw new Error(`${e}: Camera orthographic properties are missing`);r.mode=ce.V.ORTHOGRAPHIC_CAMERA,r.orthoLeft=-t.orthographic.xmag,r.orthoRight=t.orthographic.xmag,r.orthoBottom=-t.orthographic.ymag,r.orthoTop=t.orthographic.ymag,r.minZ=t.orthographic.znear,r.maxZ=t.orthographic.zfar;break;default:throw new Error(`${e}: Invalid camera type (${t.type})`)}return $A.AddPointerMetadata(r,e),this._parent.onCameraLoadedObservable.notifyObservers(r),i(r),this.logClose(),Promise.all(s).then((()=>r))}_loadAnimationsAsync(){const e=this._gltf.animations;if(!e)return Promise.resolve();const t=new Array;for(let i=0;i{0===e.targetedAnimations.length&&e.dispose()})))}return Promise.all(t).then((()=>{}))}loadAnimationAsync(e,t){const i=this._extensionsLoadAnimationAsync(e,t);if(i)return i;this._babylonScene._blockEntityCollection=!!this._assetContainer;const n=new J(t.name||`animation${t.index}`,this._babylonScene);n._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=n;const s=new Array;qA.Assign(t.channels),qA.Assign(t.samplers);for(const r of t.channels)s.push(this._loadAnimationChannelAsync(`${e}/channels/${r.index}`,e,t,r,((e,t)=>{e.animations=e.animations||[],e.animations.push(t),n.addTargetedAnimation(t,e)})));return Promise.all(s).then((()=>(n.normalize(0),n)))}_loadAnimationChannelAsync(e,t,i,n,s){const r=this._extensionsLoadAnimationChannelAsync(e,t,i,n,s);if(r)return r;if(null==n.target.node)return Promise.resolve();const o=qA.Get(`${e}/target/node`,this._gltf.nodes,n.target.node);if("weights"===n.target.path&&!o._numMorphTargets||"weights"!==n.target.path&&!o._babylonTransformNode)return Promise.resolve();let a;switch(n.target.path){case"translation":a=jA.translation;break;case"rotation":a=jA.rotation;break;case"scale":a=jA.scale;break;case"weights":a=jA.weights;break;default:throw new Error(`${e}/target/path: Invalid value (${n.target.path})`)}const l={target:o,properties:a};return this._loadAnimationChannelFromTargetInfoAsync(e,t,i,n,l,s)}_loadAnimationChannelFromTargetInfoAsync(e,t,i,n,s,r){const o=this.parent.targetFps,a=1/o,l=qA.Get(`${e}/sampler`,i.samplers,n.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${n.sampler}`,l).then((e=>{let t=0;for(const l of s.properties){const h=l.getStride(s.target),c=e.input,d=e.output,u=new Array(c.length);let p=0;switch(e.interpolation){case"STEP":for(let e=0;e0){const e=`${i.name||`animation${i.index}`}_channel${n.index}_${t}`;l.buildAnimations(s.target,e,o,u,((e,i)=>{++t,r(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=qA.Get(`${e}/input`,this._gltf.accessors,t.input),s=qA.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${n.index}`,n),this._loadFloatAccessorAsync(`/accessors/${s.index}`,s)]).then((([e,t])=>({input:e,interpolation:i,output:t}))),t._data}loadBufferAsync(e,t,i,n){const s=this._extensionsLoadBufferAsync(e,t,i,n);if(s)return s;if(!t._data)if(t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{if(!this._bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);t._data=this._bin.readAsync(0,t.byteLength)}return t._data.then((t=>{try{return new Uint8Array(t.buffer,t.byteOffset+i,n)}catch(s){throw new Error(`${e}: ${s.message}`)}}))}loadBufferViewAsync(e,t){const i=this._extensionsLoadBufferViewAsync(e,t);if(i)return i;if(t._data)return t._data;const n=qA.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=$A._GetNumComponents(e,t.type),s=n*ne.o.GetTypeByteLength(t.componentType),r=n*t.count;if(null==t.bufferView)t._data=Promise.resolve(new i(r));else{const o=qA.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${o.index}`,o).then((a=>{if(5126!==t.componentType||t.normalized||o.byteStride&&o.byteStride!==s){const e=new i(r);return ne.o.ForEach(a,t.byteOffset||0,o.byteStride||s,n,t.componentType,e.length,t.normalized||!1,((t,i)=>{e[i]=t})),e}return $A._GetTypedArray(e,t.componentType,a,t.byteOffset,r)}))}if(t.sparse){const r=t.sparse;t._data=t._data.then((o=>{const a=o,l=qA.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,r.indices.bufferView),h=qA.Get(`${e}/sparse/values/bufferView`,this._gltf.bufferViews,r.values.bufferView);return Promise.all([this.loadBufferViewAsync(`/bufferViews/${l.index}`,l),this.loadBufferViewAsync(`/bufferViews/${h.index}`,h)]).then((([o,l])=>{const h=$A._GetTypedArray(`${e}/sparse/indices`,r.indices.componentType,o,r.indices.byteOffset,r.count),c=n*r.count;let d;if(5126!==t.componentType||t.normalized){const o=$A._GetTypedArray(`${e}/sparse/values`,t.componentType,l,r.values.byteOffset,c);d=new i(c),ne.o.ForEach(o,0,s,n,t.componentType,d.length,t.normalized||!1,((e,t)=>{d[t]=e}))}else d=$A._GetTypedArray(`${e}/sparse/values`,t.componentType,l,r.values.byteOffset,c);let u=0;for(let e=0;e$A._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 ne.l(t,e,!1))),e._babylonBuffer}_loadVertexAccessorAsync(e,t,i){var n;if(null===(n=t._babylonVertexBuffer)||void 0===n?void 0:n[i])return t._babylonVertexBuffer[i];t._babylonVertexBuffer||(t._babylonVertexBuffer={});const s=this._babylonScene.getEngine();if(t.sparse)t._babylonVertexBuffer[i]=this._loadFloatAccessorAsync(e,t).then((e=>new ne.o(s,e,i,!1)));else if(i===ne.o.MatricesIndicesKind||i===ne.o.MatricesIndicesExtraKind)t._babylonVertexBuffer[i]=this._loadFloatAccessorAsync(e,t).then((e=>new ne.o(s,e,i,!1)));else{const n=qA.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._babylonVertexBuffer[i]=this._loadVertexBufferViewAsync(n).then((r=>{const o=$A._GetNumComponents(e,t.type);return new ne.o(s,r,i,!1,!1,n.byteStride,!1,t.byteOffset,o,t.componentType,t.normalized,!0,1,!0)}))}return t._babylonVertexBuffer[i]}_loadMaterialMetallicRoughnessPropertiesAsync(e,t,i){if(!(i instanceof O_))throw new Error(`${e}: Material type not supported`);const n=new Array;return t&&(t.baseColorFactor?(i.albedoColor=a.Wo.FromArray(t.baseColorFactor),i.alpha=t.baseColorFactor[3]):i.albedoColor=a.Wo.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,s=(()=>{})){const r=this._extensionsLoadMaterialAsync(e,t,i,n,s);if(r)return r;t._data=t._data||{};let o=t._data[n];if(!o){this.logOpen(`${e} ${t.name||""}`);const i=this.createMaterial(e,t,n);o={babylonMaterial:i,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(e,t,i)},t._data[n]=o,$A.AddPointerMetadata(i,e),this._parent.onMaterialLoadedObservable.notifyObservers(i),this.logClose()}return i&&(o.babylonMeshes.push(i),i.onDisposeObservable.addOnce((()=>{const e=o.babylonMeshes.indexOf(i);-1!==e&&o.babylonMeshes.splice(e,1)}))),s(o.babylonMaterial),o.promise.then((()=>o.babylonMaterial))}_createDefaultMaterial(e,t){this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new O_(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=O_.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 s=t.name||`material${t.index}`;return this._createDefaultMaterial(s,i)}loadMaterialPropertiesAsync(e,t,i){const n=this._extensionsLoadMaterialPropertiesAsync(e,t,i);if(n)return n;const s=new Array;return s.push(this.loadMaterialBasePropertiesAsync(e,t,i)),t.pbrMetallicRoughness&&s.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,i)),this.loadMaterialAlphaProperties(e,t,i),Promise.all(s).then((()=>{}))}loadMaterialBasePropertiesAsync(e,t,i){if(!(i instanceof O_))throw new Error(`${e}: Material type not supported`);const n=new Array;return i.emissiveColor=t.emissiveFactor?a.Wo.FromArray(t.emissiveFactor):new a.Wo(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 O_))throw new Error(`${e}: Material type not supported`);switch(t.alphaMode||"OPAQUE"){case"OPAQUE":i.transparencyMode=O_.PBRMATERIAL_OPAQUE;break;case"MASK":i.transparencyMode=O_.PBRMATERIAL_ALPHATEST,i.alphaCutOff=null==t.alphaCutoff?.5:t.alphaCutoff,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0);break;case"BLEND":i.transparencyMode=O_.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 s=qA.Get(`${e}/index`,this._gltf.textures,t.index);s._textureInfo=t;const r=this._loadTextureAsync(`/textures/${t.index}`,s,(n=>{n.coordinatesIndex=t.texCoord||0,$A.AddPointerMetadata(n,e),this._parent.onTextureLoadedObservable.notifyObservers(n),i(n)}));return this.logClose(),r}_loadTextureAsync(e,t,i=(()=>{})){const n=this._extensionsLoadTextureAsync(e,t,i);if(n)return n;this.logOpen(`${e} ${t.name||""}`);const s=null==t.sampler?$A.DefaultSampler:qA.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),r=qA.Get(`${e}/source`,this._gltf.images,t.source),o=this._createTextureAsync(e,s,r,i,void 0,!t._textureInfo.nonColorData);return this.logClose(),o}_createTextureAsync(e,t,i,n=(()=>{}),s,r){const o=this._loadSampler(`/samplers/${t.index}`,t),a=new Array,l=new wC;this._babylonScene._blockEntityCollection=!!this._assetContainer;const h={noMipmap:o.noMipMaps,invertY:!1,samplingMode:o.samplingMode,onLoad:()=>{this._disposed||l.resolve()},onError:(t,i)=>{this._disposed||l.reject(new Error(`${e}: ${i&&i.message?i.message:t||"Failed to load texture"}`))},mimeType:i.mimeType,loaderOptions:s,useSRGBBuffer:!!r&&this._parent.useSRGBBuffers},c=new Le(null,this._babylonScene,h);return c._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,a.push(l.promise),a.push(this.loadImageAsync(`/images/${i.index}`,i).then((e=>{const t=i.uri||`${this._fileName}#image${i.index}`,n=`data:${this._uniqueRootUrl}${t}`;c.updateURL(n,e)}))),c.wrapU=o.wrapU,c.wrapV=o.wrapV,n(c),Promise.all(a).then((()=>c))}_loadSampler(e,t){return t._data||(t._data={noMipMaps:9728===t.minFilter||9729===t.minFilter,samplingMode:$A._GetTextureSamplingMode(e,t),wrapU:$A._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:$A._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=qA.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(!$A._ValidateUri(i))throw new Error(`${e}: '${i}' is invalid`);if((0,ye.VL)(i)){const t=new Uint8Array((0,ye.$K)(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,s)=>{this._parent._loadFile(this._babylonScene,t,(t=>{this._disposed||(this.log(`${e}: Loaded ${i} (${t.byteLength} bytes)`),n(new Uint8Array(t)))}),!0,(t=>{s(new ye.eh(`${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 Le.CLAMP_ADDRESSMODE;case 33648:return Le.MIRROR_ADDRESSMODE;case 10497:return Le.WRAP_ADDRESSMODE;default:return p.Y.Warn(`${e}: Invalid value (${t})`),Le.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 Le.LINEAR_NEAREST;case 9729:return Le.LINEAR_LINEAR;case 9984:return Le.LINEAR_NEAREST_MIPNEAREST;case 9985:return Le.LINEAR_LINEAR_MIPNEAREST;case 9986:return Le.LINEAR_NEAREST_MIPLINEAR;case 9987:return Le.LINEAR_LINEAR_MIPLINEAR;default:return p.Y.Warn(`${e}/minFilter: Invalid value (${n})`),Le.LINEAR_LINEAR_MIPLINEAR}else switch(9728!==i&&p.Y.Warn(`${e}/magFilter: Invalid value (${i})`),n){case 9728:return Le.NEAREST_NEAREST;case 9729:return Le.NEAREST_LINEAR;case 9984:return Le.NEAREST_NEAREST_MIPNEAREST;case 9985:return Le.NEAREST_LINEAR_MIPNEAREST;case 9986:return Le.NEAREST_NEAREST_MIPLINEAR;case 9987:return Le.NEAREST_LINEAR_MIPLINEAR;default:return p.Y.Warn(`${e}/minFilter: Invalid value (${n})`),Le.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,s){const r=i.buffer;n=i.byteOffset+(n||0);const o=$A._GetTypedArrayConstructor(`${e}/componentType`,t),a=ne.o.GetTypeByteLength(t);return n%a!=0?(p.Y.Warn(`${e}: Copying buffer as byte offset (${n}) is not a multiple of component type byte length (${a})`),new o(r.slice(n,n+s*a),0)):new o(r,n,s)}static _GetNumComponents(e,t){switch(t){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}throw new Error(`${e}: Invalid type (${t})`)}static _ValidateUri(e){return se.w1.IsBase64(e)||-1===e.indexOf("..")}static _GetDrawMode(e,t){switch(null==t&&(t=4),t){case 0:return ut.F.PointListDrawMode;case 1:return ut.F.LineListDrawMode;case 2:return ut.F.LineLoopDrawMode;case 3:return ut.F.LineStripDrawMode;case 4:return ut.F.TriangleFillMode;case 5:return ut.F.TriangleStripDrawMode;case 6:return ut.F.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 s=`${n.name}.${t}`,r=e;r._activeLoaderExtensionFunctions=r._activeLoaderExtensionFunctions||{};const o=r._activeLoaderExtensionFunctions;if(!o[s]){o[s]=!0;try{const e=i(n);if(e)return e}finally{delete o[s]}}}return null}_extensionsOnLoading(){this._forEachExtensions((e=>e.onLoading&&e.onLoading()))}_extensionsOnReady(){this._forEachExtensions((e=>e.onReady&&e.onReady()))}_extensionsLoadSceneAsync(e,t){return this._applyExtensions(t,"loadScene",(i=>i.loadSceneAsync&&i.loadSceneAsync(e,t)))}_extensionsLoadNodeAsync(e,t,i){return this._applyExtensions(t,"loadNode",(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,s,r){return this._applyExtensions(s,"loadMeshPrimitive",(o=>o._loadMeshPrimitiveAsync&&o._loadMeshPrimitiveAsync(e,t,i,n,s,r)))}_extensionsLoadMaterialAsync(e,t,i,n,s){return this._applyExtensions(t,"loadMaterial",(r=>r._loadMaterialAsync&&r._loadMaterialAsync(e,t,i,n,s)))}_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,s){return this._applyExtensions(i,"loadAnimationChannel",(r=>r._loadAnimationChannelAsync&&r._loadAnimationChannelAsync(e,t,i,n,s)))}_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",(s=>s.loadBufferAsync&&s.loadBufferAsync(e,t,i,n)))}static LoadExtensionAsync(e,t,i,n){if(!t.extensions)return null;const s=t.extensions[i];return s?n(`${e}/extensions/${i}`,s):null}static LoadExtraAsync(e,t,i,n){if(!t.extras)return null;const s=t.extras[i];return s?n(`${e}/extras/${i}`,s):null}isExtensionUsed(e){return!!this._gltf.extensionsUsed&&-1!==this._gltf.extensionsUsed.indexOf(e)}logOpen(e){this._parent._logOpen(e)}logClose(){this._parent._logClose()}log(e){this._parent._log(e)}startPerformanceCounter(e){this._parent._startPerformanceCounter(e)}endPerformanceCounter(e){this._parent._endPerformanceCounter(e)}}$A._RegisteredExtensions={},$A.DefaultSampler={index:-1},gA._CreateGLTF2Loader=e=>new $A(e);const QA="EXT_lights_image_based";class ZA{constructor(e){this.name=QA,this._loader=e,this.enabled=this._loader.isExtensionUsed(QA)}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 $A.LoadExtensionAsync(e,t,this.name,((i,n)=>{const s=new Array;s.push(this._loader.loadSceneAsync(e,t)),this._loader.logOpen(`${i}`);const r=qA.Get(`${i}/light`,this._lights,n.light);return s.push(this._loadLightAsync(`/extensions/${this.name}/lights/${n.light}`,r).then((e=>{this._loader.babylonScene.environmentTexture=e}))),this._loader.logClose(),Promise.all(s).then((()=>{}))}))}_loadLightAsync(e,t){if(!t._loaded){const i=new Array;this._loader.logOpen(`${e}`);const n=new Array(t.specularImages.length);for(let s=0;s{n[s][t]=e}))),this._loader.logClose()}}this._loader.logClose(),t._loaded=Promise.all(i).then((()=>{const i=new zv(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=o._f.FromArray(t.rotation);this._loader.babylonScene.useRightHandedSystem||(e=o._f.Inverse(e)),o.y3.FromQuaternionToRef(e,i.getReflectionTextureMatrix())}if(!t.irradianceCoefficients)throw new Error(`${e}: Irradiance coefficients are missing`);const s=Oh.FromArray(t.irradianceCoefficients);s.scaleInPlace(t.intensity),s.convertIrradianceToLambertianRadiance();const r=Dh.FromHarmonics(s),a=(n.length-1)/S.R.Log2(t.specularImageSize);return i.updateRGBDAsync(n,r,a)}))}return t._loaded.then((()=>t._babylonTexture))}}$A.RegisterExtension(QA,(e=>new ZA(e)));const JA="EXT_mesh_gpu_instancing";class eR{constructor(e){this.name=JA,this._loader=e,this.enabled=this._loader.isExtensionUsed(JA)}dispose(){this._loader=null}loadNodeAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((e,n)=>{this._loader._disableInstancedMesh++;const s=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,i);if(this._loader._disableInstancedMesh--,!t._primitiveBabylonMeshes)return s;const r=new Array;let a=0;const l=t=>{if(null==n.attributes[t])return void r.push(Promise.resolve(null));const i=qA.Get(`${e}/attributes/${t}`,this._loader.gltf.accessors,n.attributes[t]);if(r.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 l("TRANSLATION"),l("ROTATION"),l("SCALE"),s.then((e=>Promise.all(r).then((([i,n,s])=>{const r=new Float32Array(16*a);o.jp.Vector3[0].copyFromFloats(0,0,0),o.jp.Quaternion[0].copyFromFloats(0,0,0,1),o.jp.Vector3[1].copyFromFloats(1,1,1);for(let e=0;enew eR(e)));const tR="EXT_meshopt_compression";class iR{constructor(e){this.name=tR,this.enabled=e.isExtensionUsed(tR),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,t){return $A.LoadExtensionAsync(e,t,this.name,((i,n)=>{const s=t;if(s._meshOptData)return s._meshOptData;const r=qA.Get(`${e}/buffer`,this._loader.gltf.buffers,n.buffer);return s._meshOptData=this._loader.loadBufferAsync(`/buffers/${r.index}`,r,n.byteOffset||0,n.byteLength).then((e=>MT.Default.decodeGltfBufferAsync(e,n.count,n.byteStride,n.mode,n.filter))),s._meshOptData}))}}$A.RegisterExtension(tR,(e=>new iR(e)));const nR="EXT_texture_webp";class sR{constructor(e){this.name=nR,this._loader=e,this.enabled=e.isExtensionUsed(nR)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=null==t.sampler?$A.DefaultSampler:qA.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=qA.Get(`${n}/source`,this._loader.gltf.images,s.source);return this._loader._createTextureAsync(e,r,o,(e=>{i(e)}),void 0,!t._textureInfo.nonColorData)}))}}$A.RegisterExtension(nR,(e=>new sR(e)));const rR="KHR_draco_mesh_compression";class oR{constructor(e){this.name=rR,this._loader=e,this.enabled=IT.DecoderAvailable&&this._loader.isExtensionUsed(rR)}dispose(){delete this.dracoCompression,this._loader=null}_loadVertexDataAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>{if(null!=t.mode){if(5!==t.mode&&4!==t.mode)throw new Error(`${e}: Unsupported mode ${t.mode}`);if(5===t.mode)throw new Error(`${e}: Mode ${t.mode} is not currently supported`)}const r={},o={},a=(n,a)=>{const l=s.attributes[n];if(void 0===l||void 0===t.attributes[n])return;r[a]=l;const h=qA.Get(`${e}/attributes/${n}`,this._loader.gltf.accessors,t.attributes[n]);if(h.normalized&&5126!==h.componentType){let e=1;switch(h.componentType){case 5120:e=127;break;case 5121:e=255;break;case 5122:e=32767;break;case 5123:e=65535}o[a]=e}i._delayInfo=i._delayInfo||[],-1===i._delayInfo.indexOf(a)&&i._delayInfo.push(a)};a("POSITION",ne.o.PositionKind),a("NORMAL",ne.o.NormalKind),a("TANGENT",ne.o.TangentKind),a("TEXCOORD_0",ne.o.UVKind),a("TEXCOORD_1",ne.o.UV2Kind),a("TEXCOORD_2",ne.o.UV3Kind),a("TEXCOORD_3",ne.o.UV4Kind),a("TEXCOORD_4",ne.o.UV5Kind),a("TEXCOORD_5",ne.o.UV6Kind),a("JOINTS_0",ne.o.MatricesIndicesKind),a("WEIGHTS_0",ne.o.MatricesWeightsKind),a("COLOR_0",ne.o.ColorKind);const l=qA.Get(n,this._loader.gltf.bufferViews,s.bufferView);return l._dracoBabylonGeometry||(l._dracoBabylonGeometry=this._loader.loadBufferViewAsync(`/bufferViews/${l.index}`,l).then((t=>(this.dracoCompression||IT.Default).decodeMeshAsync(t,r,o).then((e=>{const t=new Gg.Z(i.name,this._loader.babylonScene);return e.applyToGeometry(t),t})).catch((t=>{throw new Error(`${e}: ${t.message}`)}))))),l._dracoBabylonGeometry}))}}$A.RegisterExtension(rR,(e=>new oR(e)));const aR="KHR_lights_punctual";class lR{constructor(e){this.name=aR,this._loader=e,this.enabled=this._loader.isExtensionUsed(aR)}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,qA.Assign(this._lights)}}loadNodeAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>this._loader.loadNodeAsync(e,t,(e=>{let t;const r=qA.Get(n,this._lights,s.light),l=r.name||e.name;switch(this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,r.type){case"directional":{const e=new sp(l,o.P.Backward(),this._loader.babylonScene);e.position.setAll(0),t=e;break}case"point":t=new Vg(l,o.P.Zero(),this._loader.babylonScene);break;case"spot":{const e=new op(l,o.P.Zero(),o.P.Backward(),0,1,this._loader.babylonScene);e.angle=2*(r.spot&&r.spot.outerConeAngle||Math.PI/4),e.innerAngle=2*(r.spot&&r.spot.innerConeAngle||0),t=e;break}default:throw this._loader.babylonScene._blockEntityCollection=!1,new Error(`${n}: Invalid light type (${r.type})`)}t._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,r._babylonLight=t,t.falloffType=he.FALLOFF_GLTF,t.diffuse=r.color?a.Wo.FromArray(r.color):a.Wo.White(),t.intensity=null==r.intensity?1:r.intensity,t.range=null==r.range?Number.MAX_VALUE:r.range,t.parent=e,this._loader._babylonLights.push(t),$A.AddPointerMetadata(t,n),i(e)}))))}}$A.RegisterExtension(aR,(e=>new lR(e)));const hR="KHR_materials_pbrSpecularGlossiness";class cR{constructor(e){this.name=hR,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(hR)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),r.push(this._loadSpecularGlossinessPropertiesAsync(n,t,s,i)),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(r).then((()=>{}))}))}_loadSpecularGlossinessPropertiesAsync(e,t,i,n){if(!(n instanceof O_))throw new Error(`${e}: Material type not supported`);const s=new Array;return n.metallic=null,n.roughness=null,i.diffuseFactor?(n.albedoColor=a.Wo.FromArray(i.diffuseFactor),n.alpha=i.diffuseFactor[3]):n.albedoColor=a.Wo.White(),n.reflectivityColor=i.specularFactor?a.Wo.FromArray(i.specularFactor):a.Wo.White(),n.microSurface=null==i.glossinessFactor?1:i.glossinessFactor,i.diffuseTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTexture`,i.diffuseTexture,(e=>{e.name=`${n.name} (Diffuse)`,n.albedoTexture=e}))),i.specularGlossinessTexture&&(s.push(this._loader.loadTextureInfoAsync(`${e}/specularGlossinessTexture`,i.specularGlossinessTexture,(e=>{e.name=`${n.name} (Specular Glossiness)`,n.reflectivityTexture=e,n.reflectivityTexture.hasAlpha=!0}))),n.useMicroSurfaceFromReflectivityMapAlpha=!0),Promise.all(s).then((()=>{}))}}$A.RegisterExtension(hR,(e=>new cR(e)));const dR="KHR_materials_unlit";class uR{constructor(e){this.name=dR,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(dR)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,(()=>this._loadUnlitPropertiesAsync(e,t,i)))}_loadUnlitPropertiesAsync(e,t,i){if(!(i instanceof O_))throw new Error(`${e}: Material type not supported`);const n=new Array;i.unlit=!0;const s=t.pbrMetallicRoughness;return s&&(s.baseColorFactor?(i.albedoColor=a.Wo.FromArray(s.baseColorFactor),i.alpha=s.baseColorFactor[3]):i.albedoColor=a.Wo.White(),s.baseColorTexture&&n.push(this._loader.loadTextureInfoAsync(`${e}/baseColorTexture`,s.baseColorTexture,(e=>{e.name=`${i.name} (Base Color)`,i.albedoTexture=e})))),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(n).then((()=>{}))}}$A.RegisterExtension(dR,(e=>new uR(e)));const pR="KHR_materials_clearcoat";class fR{constructor(e){this.name=pR,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(pR)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadClearCoatPropertiesAsync(n,s,i)),Promise.all(r).then((()=>{}))}))}_loadClearCoatPropertiesAsync(e,t,i){if(!(i instanceof O_))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((()=>{}))}}$A.RegisterExtension(pR,(e=>new fR(e)));const _R="KHR_materials_iridescence";class mR{constructor(e){this.name=_R,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(_R)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadIridescencePropertiesAsync(n,s,i)),Promise.all(r).then((()=>{}))}))}_loadIridescencePropertiesAsync(e,t,i){var n,s,r,o,a;if(!(i instanceof O_))throw new Error(`${e}: Material type not supported`);const l=new Array;return i.iridescence.isEnabled=!0,i.iridescence.intensity=null!==(n=t.iridescenceFactor)&&void 0!==n?n:0,i.iridescence.indexOfRefraction=null!==(r=null!==(s=t.iridescenceIor)&&void 0!==s?s:t.iridescenceIOR)&&void 0!==r?r:1.3,i.iridescence.minimumThickness=null!==(o=t.iridescenceThicknessMinimum)&&void 0!==o?o:100,i.iridescence.maximumThickness=null!==(a=t.iridescenceThicknessMaximum)&&void 0!==a?a:400,t.iridescenceTexture&&l.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceTexture`,t.iridescenceTexture,(e=>{e.name=`${i.name} (Iridescence Intensity)`,i.iridescence.texture=e}))),t.iridescenceThicknessTexture&&l.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceThicknessTexture`,t.iridescenceThicknessTexture,(e=>{e.name=`${i.name} (Iridescence Thickness)`,i.iridescence.thicknessTexture=e}))),Promise.all(l).then((()=>{}))}}$A.RegisterExtension(_R,(e=>new mR(e)));const gR="KHR_materials_anisotropy";class vR{constructor(e){this.name=gR,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(gR)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadIridescencePropertiesAsync(n,s,i)),Promise.all(r).then((()=>{}))}))}_loadIridescencePropertiesAsync(e,t,i){var n,s;if(!(i instanceof O_))throw new Error(`${e}: Material type not supported`);const r=new Array;return i.anisotropy.isEnabled=!0,i.anisotropy.intensity=null!==(n=t.anisotropyStrength)&&void 0!==n?n:0,i.anisotropy.angle=null!==(s=t.anisotropyRotation)&&void 0!==s?s:0,t.anisotropyTexture&&r.push(this._loader.loadTextureInfoAsync(`${e}/anisotropyTexture`,t.anisotropyTexture,(e=>{e.name=`${i.name} (Anisotropy Intensity)`,i.anisotropy.texture=e}))),Promise.all(r).then((()=>{}))}}$A.RegisterExtension(gR,(e=>new vR(e)));const TR="KHR_materials_emissive_strength";class SR{constructor(e){this.name=TR,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(TR)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>this._loader.loadMaterialPropertiesAsync(e,t,i).then((()=>{this._loadEmissiveProperties(n,s,i)}))))}_loadEmissiveProperties(e,t,i){if(!(i instanceof O_))throw new Error(`${e}: Material type not supported`);void 0!==t.emissiveStrength&&i.emissiveColor.scaleToRef(t.emissiveStrength,i.emissiveColor)}}$A.RegisterExtension(TR,(e=>new SR(e)));const ER="KHR_materials_sheen";class xR{constructor(e){this.name=ER,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(ER)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadSheenPropertiesAsync(n,s,i)),Promise.all(r).then((()=>{}))}))}_loadSheenPropertiesAsync(e,t,i){if(!(i instanceof O_))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=a.Wo.FromArray(t.sheenColorFactor):i.sheen.color=a.Wo.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((()=>{}))}}$A.RegisterExtension(ER,(e=>new xR(e)));const bR="KHR_materials_specular";class CR{constructor(e){this.name=bR,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(bR)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadSpecularPropertiesAsync(n,s,i)),Promise.all(r).then((()=>{}))}))}_loadSpecularPropertiesAsync(e,t,i){if(!(i instanceof O_))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=a.Wo.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((()=>{}))}}$A.RegisterExtension(bR,(e=>new CR(e)));const yR="KHR_materials_ior";class AR{constructor(e){this.name=yR,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(yR)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadIorPropertiesAsync(n,s,i)),Promise.all(r).then((()=>{}))}))}_loadIorPropertiesAsync(e,t,i){if(!(i instanceof O_))throw new Error(`${e}: Material type not supported`);return void 0!==t.ior?i.indexOfRefraction=t.ior:i.indexOfRefraction=AR._DEFAULT_IOR,Promise.resolve()}}AR._DEFAULT_IOR=1.5,$A.RegisterExtension(yR,(e=>new AR(e)));const RR="KHR_materials_variants";class PR{constructor(e){this.name=RR,this._loader=e,this.enabled=this._loader.isExtensionUsed(RR)}dispose(){this._loader=null}static GetAvailableVariants(e){const t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(e){return PR.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 ${RR} extension`);const n=e=>{const t=i.variants[e];if(t)for(const i of t)i.mesh.material=i.material};if(t instanceof Array)for(const s of t)n(s);else n(t);i.lastSelected=t}selectVariant(e,t){return PR.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 ${RR} extension`);for(const i of t.original)i.mesh.material=i.material;t.lastSelected=null}reset(e){return PR.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 ${RR} extension`);return t.lastSelected}getLastSelectedVariant(e){return PR.GetLastSelectedVariant(e)}static _GetExtensionMetadata(e){var t,i;return(null===(i=null===(t=null==e?void 0:e._internalMetadata)||void 0===t?void 0:t.gltf)||void 0===i?void 0:i[RR])||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,s,r){return $A.LoadExtensionAsync(e,s,this.name,((o,a)=>{const l=new Array;return l.push(this._loader._loadMeshPrimitiveAsync(e,t,i,n,s,(t=>{if(r(t),t instanceof ee.Kj){const i=$A._GetDrawMode(e,s.mode),n=this._loader.rootBabylonMesh,r=n?n._internalMetadata=n._internalMetadata||{}:{},h=r.gltf=r.gltf||{},c=h[RR]=h[RR]||{lastSelected:null,original:[],variants:{}};c.original.push({mesh:t,material:t.material});for(let e=0;e{for(let i=0;i{const i=e;let s=null,r=i;do{if(r=r.parent,!r)return;s=PR._GetExtensionMetadata(r)}while(null===s);if(n&&s===PR._GetExtensionMetadata(n)){r._internalMetadata={};for(const e in n._internalMetadata)r._internalMetadata[e]=n._internalMetadata[e];r._internalMetadata.gltf=[];for(const e in n._internalMetadata.gltf)r._internalMetadata.gltf[e]=n._internalMetadata.gltf[e];r._internalMetadata.gltf[RR]={lastSelected:null,original:[],variants:{}};for(const e of s.original)r._internalMetadata.gltf[RR].original.push({mesh:e.mesh,material:e.material});for(const e in s.variants)if(Object.prototype.hasOwnProperty.call(s.variants,e)){r._internalMetadata.gltf[RR].variants[e]=[];for(const t of s.variants[e])r._internalMetadata.gltf[RR].variants[e].push({mesh:t.mesh,material:t.material})}s=r._internalMetadata.gltf[RR]}for(const n of s.original)n.mesh===t&&(n.mesh=i);for(const n of s.variants[o.name])n.mesh===t&&(n.mesh=i)}))}})))}}}))),Promise.all(l).then((([e])=>e))}))}}$A.RegisterExtension(RR,(e=>new PR(e)));class IR{static _GetDefaultOptions(){return{renderSize:1024,samples:4,lodGenerationScale:1,lodGenerationOffset:-4,renderTargetTextureType:vh.TEXTURETYPE_HALF_FLOAT,generateMipmaps:!0}}constructor(e,t){this._opaqueRenderTarget=null,this._opaqueMeshesCache=[],this._transparentMeshesCache=[],this._materialObservers={},this._options={...IR._GetDefaultOptions(),...e},this._scene=t,this._scene._transmissionHelper=this,this.onErrorObservable=new r.y$,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 O_&&e.subSurface.isRefractionEnabled)}_addMesh(e){this._materialObservers[e.uniqueId]=e.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this)),se.w1.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 O_&&(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)}_setupRenderTargets(){var e,t;let i,n;this._opaqueRenderTarget&&this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=new Ci("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=null!==(t=null===(e=this._options.clearColor)||void 0===e?void 0:e.clone())&&void 0!==t?t: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.onBeforeBindObservable.add((e=>{n=this._scene.environmentIntensity,this._scene.environmentIntensity=1,i=this._scene.imageProcessingConfiguration.applyByPostProcess,this._options.clearColor?e.clearColor.copyFrom(this._options.clearColor):this._scene.clearColor.toLinearSpaceToRef(e.clearColor,this._scene.getEngine().useExactSrgbConversions),this._scene.imageProcessingConfiguration._applyByPostProcess=!0})),this._opaqueRenderTarget.onAfterUnbindObservable.add((()=>{this._scene.environmentIntensity=n,this._scene.imageProcessingConfiguration._applyByPostProcess=i})),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 MR="KHR_materials_transmission";class OR{constructor(e){this.name=MR,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed(MR),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadTransparentPropertiesAsync(n,t,i,s)),Promise.all(r).then((()=>{}))}))}_loadTransparentPropertiesAsync(e,t,i,n){if(!(i instanceof O_))throw new Error(`${e}: Material type not supported`);const s=i;if(s.subSurface.isRefractionEnabled=!0,s.subSurface.volumeIndexOfRefraction=1,s.subSurface.useAlbedoToTintRefraction=!0,void 0===n.transmissionFactor)return s.subSurface.refractionIntensity=0,s.subSurface.isRefractionEnabled=!1,Promise.resolve();{s.subSurface.refractionIntensity=n.transmissionFactor;const e=s.getScene();s.subSurface.refractionIntensity&&!e._transmissionHelper&&new IR({},s.getScene())}return s.subSurface.minimumThickness=0,s.subSurface.maximumThickness=0,n.transmissionTexture?(n.transmissionTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/transmissionTexture`,n.transmissionTexture,void 0).then((e=>{s.subSurface.refractionIntensityTexture=e,s.subSurface.useGltfStyleTextures=!0}))):Promise.resolve()}}$A.RegisterExtension(MR,(e=>new OR(e)));const DR="KHR_materials_translucency";class NR{constructor(e){this.name=DR,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(DR),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadTranslucentPropertiesAsync(n,t,i,s)),Promise.all(r).then((()=>{}))}))}_loadTranslucentPropertiesAsync(e,t,i,n){if(!(i instanceof O_))throw new Error(`${e}: Material type not supported`);const s=i;return s.subSurface.isTranslucencyEnabled=!0,s.subSurface.volumeIndexOfRefraction=1,s.subSurface.minimumThickness=0,s.subSurface.maximumThickness=0,s.subSurface.useAlbedoToTintTranslucency=!0,void 0===n.translucencyFactor?(s.subSurface.translucencyIntensity=0,s.subSurface.isTranslucencyEnabled=!1,Promise.resolve()):(s.subSurface.translucencyIntensity=n.translucencyFactor,n.translucencyTexture?(n.translucencyTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/translucencyTexture`,n.translucencyTexture).then((e=>{s.subSurface.translucencyIntensityTexture=e}))):Promise.resolve())}}$A.RegisterExtension(DR,(e=>new NR(e)));const FR="KHR_materials_volume";class wR{constructor(e){this.name=FR,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(FR),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=new Array;return r.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),r.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),r.push(this._loadVolumePropertiesAsync(n,t,i,s)),Promise.all(r).then((()=>{}))}))}_loadVolumePropertiesAsync(e,t,i,n){if(!(i instanceof O_))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 s=void 0!==n.attenuationDistance?n.attenuationDistance:Number.MAX_VALUE;return i.subSurface.tintColorAtDistance=s,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()}}$A.RegisterExtension(FR,(e=>new wR(e)));const LR="KHR_mesh_quantization";class BR{constructor(e){this.name=LR,this.enabled=e.isExtensionUsed(LR)}dispose(){}}$A.RegisterExtension(LR,(e=>new BR(e)));const UR="KHR_texture_basisu";class VR{constructor(e){this.name=UR,this._loader=e,this.enabled=e.isExtensionUsed(UR)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>{const r=null==t.sampler?$A.DefaultSampler:qA.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=qA.Get(`${n}/source`,this._loader.gltf.images,s.source);return this._loader._createTextureAsync(e,r,o,(e=>{i(e)}),t._textureInfo.nonColorData?{useRGBAIfASTCBC7NotAvailableWhenUASTC:!0}:void 0,!t._textureInfo.nonColorData)}))}}$A.RegisterExtension(UR,(e=>new VR(e)));const kR="KHR_texture_transform";class GR{constructor(e){this.name=kR,this._loader=e,this.enabled=this._loader.isExtensionUsed(kR)}dispose(){this._loader=null}loadTextureInfoAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((n,s)=>this._loader.loadTextureInfoAsync(e,t,(e=>{if(!(e instanceof Le))throw new Error(`${n}: Texture type not supported`);s.offset&&(e.uOffset=s.offset[0],e.vOffset=s.offset[1]),e.uRotationCenter=0,e.vRotationCenter=0,s.rotation&&(e.wAng=-s.rotation),s.scale&&(e.uScale=s.scale[0],e.vScale=s.scale[1]),null!=s.texCoord&&(e.coordinatesIndex=s.texCoord),i(e)}))))}}$A.RegisterExtension(kR,(e=>new GR(e)));const zR="KHR_xmp_json_ld";class WR{constructor(e){this.name=zR,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed(zR)}dispose(){this._loader=null}onLoading(){var e,t,i;if(null===this._loader.rootBabylonMesh)return;const n=null===(e=this._loader.gltf.extensions)||void 0===e?void 0:e.KHR_xmp_json_ld,s=null===(i=null===(t=this._loader.gltf.asset)||void 0===t?void 0:t.extensions)||void 0===i?void 0:i.KHR_xmp_json_ld;if(n&&s){const e=+s.packet;n.packets&&e2)),new QR(A.ANIMATIONTYPE_FLOAT,`${e}.vScale`,jR,(()=>2))],offset:[new QR(A.ANIMATIONTYPE_FLOAT,`${e}.uOffset`,XR,(()=>2)),new QR(A.ANIMATIONTYPE_FLOAT,`${e}.vOffset`,jR,(()=>2))],rotation:[new QR(A.ANIMATIONTYPE_FLOAT,`${e}.wAng`,YR,(()=>1))]}}$A.RegisterExtension(zR,(e=>new WR(e)));class $R extends XA{buildAnimations(e,t,i,n,s){s(e._babylonCamera,this._buildAnimation(t,i,n))}}class QR extends XA{buildAnimations(e,t,i,n,s){for(const r in e._data)s(e._data[r].babylonMaterial,this._buildAnimation(t,i,n))}}class ZR extends XA{buildAnimations(e,t,i,n,s){s(e._babylonLight,this._buildAnimation(t,i,n))}}const JR={__array__:{__target__:!0,...jA}},eP={__array__:{__target__:!0,orthographic:{xmag:[new $R(A.ANIMATIONTYPE_FLOAT,"orthoLeft",YR,(()=>1)),new $R(A.ANIMATIONTYPE_FLOAT,"orthoRight",jR,(()=>1))],ymag:[new $R(A.ANIMATIONTYPE_FLOAT,"orthoBottom",YR,(()=>1)),new $R(A.ANIMATIONTYPE_FLOAT,"orthoTop",jR,(()=>1))],zfar:[new $R(A.ANIMATIONTYPE_FLOAT,"maxZ",XR,(()=>1))],znear:[new $R(A.ANIMATIONTYPE_FLOAT,"minZ",XR,(()=>1))]},perspective:{yfov:[new $R(A.ANIMATIONTYPE_FLOAT,"fov",XR,(()=>1))],zfar:[new $R(A.ANIMATIONTYPE_FLOAT,"maxZ",XR,(()=>1))],znear:[new $R(A.ANIMATIONTYPE_FLOAT,"minZ",XR,(()=>1))]}}},tP={nodes:JR,materials:{__array__:{__target__:!0,pbrMetallicRoughness:{baseColorFactor:[new QR(A.ANIMATIONTYPE_COLOR3,"albedoColor",HR,(()=>4)),new QR(A.ANIMATIONTYPE_FLOAT,"alpha",(function(e,t,i,n){return t[i+3]*n}),(()=>4))],metallicFactor:[new QR(A.ANIMATIONTYPE_FLOAT,"metallic",XR,(()=>1))],roughnessFactor:[new QR(A.ANIMATIONTYPE_FLOAT,"roughness",XR,(()=>1))],baseColorTexture:{extensions:{KHR_texture_transform:qR("albedoTexture")}}},emissiveFactor:[new QR(A.ANIMATIONTYPE_COLOR3,"emissiveColor",HR,(()=>3))],normalTexture:{scale:[new QR(A.ANIMATIONTYPE_FLOAT,"bumpTexture.level",XR,(()=>1))]},occlusionTexture:{strength:[new QR(A.ANIMATIONTYPE_FLOAT,"ambientTextureStrength",XR,(()=>1))],extensions:{KHR_texture_transform:qR("ambientTexture")}},emissiveTexture:{extensions:{KHR_texture_transform:qR("emissiveTexture")}},extensions:{KHR_materials_ior:{ior:[new QR(A.ANIMATIONTYPE_FLOAT,"indexOfRefraction",XR,(()=>1))]},KHR_materials_clearcoat:{clearcoatFactor:[new QR(A.ANIMATIONTYPE_FLOAT,"clearCoat.intensity",XR,(()=>1))],clearcoatRoughnessFactor:[new QR(A.ANIMATIONTYPE_FLOAT,"clearCoat.roughness",XR,(()=>1))]},KHR_materials_sheen:{sheenColorFactor:[new QR(A.ANIMATIONTYPE_COLOR3,"sheen.color",HR,(()=>3))],sheenRoughnessFactor:[new QR(A.ANIMATIONTYPE_FLOAT,"sheen.roughness",XR,(()=>1))]},KHR_materials_specular:{specularFactor:[new QR(A.ANIMATIONTYPE_FLOAT,"metallicF0Factor",XR,(()=>1))],specularColorFactor:[new QR(A.ANIMATIONTYPE_COLOR3,"metallicReflectanceColor",HR,(()=>3))]},KHR_materials_emissive_strength:{emissiveStrength:[new QR(A.ANIMATIONTYPE_FLOAT,"emissiveIntensity",XR,(()=>1))]},KHR_materials_transmission:{transmissionFactor:[new QR(A.ANIMATIONTYPE_FLOAT,"subSurface.refractionIntensity",XR,(()=>1))]},KHR_materials_volume:{attenuationColor:[new QR(A.ANIMATIONTYPE_COLOR3,"subSurface.tintColor",HR,(()=>3))],attenuationDistance:[new QR(A.ANIMATIONTYPE_FLOAT,"subSurface.tintColorAtDistance",XR,(()=>1))],thicknessFactor:[new QR(A.ANIMATIONTYPE_FLOAT,"subSurface.maximumThickness",XR,(()=>1))]},KHR_materials_iridescence:{iridescenceFactor:[new QR(A.ANIMATIONTYPE_FLOAT,"iridescence.intensity",XR,(()=>1))],iridescenceIor:[new QR(A.ANIMATIONTYPE_FLOAT,"iridescence.indexOfRefraction",XR,(()=>1))],iridescenceThicknessMinimum:[new QR(A.ANIMATIONTYPE_FLOAT,"iridescence.minimumThickness",XR,(()=>1))],iridescenceThicknessMaximum:[new QR(A.ANIMATIONTYPE_FLOAT,"iridescence.maximumThickness",XR,(()=>1))]},KHR_materials_anisotropy:{anisotropyStrength:[new QR(A.ANIMATIONTYPE_FLOAT,"anisotropy.intensity",XR,(()=>1))],anisotropyRotation:[new QR(A.ANIMATIONTYPE_FLOAT,"anisotropy.angle",XR,(()=>1))]}}}},cameras:eP,extensions:{KHR_lights_punctual:{lights:{__array__:{__target__:!0,color:[new ZR(A.ANIMATIONTYPE_COLOR3,"diffuse",HR,(()=>3))],intensity:[new ZR(A.ANIMATIONTYPE_FLOAT,"intensity",XR,(()=>1))],range:[new ZR(A.ANIMATIONTYPE_FLOAT,"range",XR,(()=>1))],spot:{innerConeAngle:[new ZR(A.ANIMATIONTYPE_FLOAT,"innerAngle",KR,(()=>1))],outerConeAngle:[new ZR(A.ANIMATIONTYPE_FLOAT,"angle",KR,(()=>1))]}}}}}},iP="KHR_animation_pointer";class nP{constructor(e){this.name=iP,this._loader=e}get enabled(){return this._loader.isExtensionUsed(iP)}dispose(){this._loader=null}_loadAnimationChannelAsync(e,t,i,n,s){var r;const o=null===(r=n.target.extensions)||void 0===r?void 0:r.KHR_animation_pointer;if(!o)return null;"pointer"!==n.target.path&&p.Y.Warn(`${e}/target/path: Value (${n.target.path}) must be (pointer) when using the ${this.name} extension`),null!=n.target.node&&p.Y.Warn(`${e}/target/node: Value (${n.target.node}) must not be present when using the ${this.name} extension`);const a=`${e}/extensions/${this.name}`,l=o.pointer;if(!l)throw new Error(`${a}: Pointer is missing`);const h=this._parseAnimationPointer(`${a}/pointer`,l);return h?this._loader._loadAnimationChannelFromTargetInfoAsync(e,t,i,n,h,s):(p.Y.Warn(`${a}/pointer: Invalid pointer (${l}) skipped`),null)}_parseAnimationPointer(e,t){if(!t.startsWith("/"))return p.Y.Warn(`${e}: Value (${t}) must start with a slash`),null;const i=t.split("/");i.shift();let n,s=tP,r=this._loader.gltf;for(const o of i){if(s.__array__)s=s.__array__;else if(s=s[o],!s)return null;r=r&&r[o],s.__target__&&(n=r)}return n&&Array.isArray(s)?{target:n,properties:s}:null}}$A.RegisterExtension(iP,(e=>new nP(e)));const sP="MSFT_audio_emitter";class rP{constructor(e){this.name=sP,this._loader=e,this.enabled=this._loader.isExtensionUsed(sP)}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,qA.Assign(this._clips),qA.Assign(this._emitters)}}loadSceneAsync(e,t){return $A.LoadExtensionAsync(e,t,this.name,((i,n)=>{const s=new Array;s.push(this._loader.loadSceneAsync(e,t));for(const e of n.emitters){const t=qA.Get(`${i}/emitters`,this._emitters,e);if(null!=t.refDistance||null!=t.maxDistance||null!=t.rolloffFactor||null!=t.distanceModel||null!=t.innerAngle||null!=t.outerAngle)throw new Error(`${i}: Direction or Distance properties are not allowed on emitters attached to a scene`);s.push(this._loadEmitterAsync(`${i}/emitters/${t.index}`,t))}return Promise.all(s).then((()=>{}))}))}loadNodeAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((e,n)=>{const s=new Array;return this._loader.loadNodeAsync(e,t,(t=>{for(const i of n.emitters){const n=qA.Get(`${e}/emitters`,this._emitters,i);s.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(o.P.Forward()),e.setDirectionalCone(2*se.w1.ToDegrees(null==n.innerAngle?Math.PI:n.innerAngle),2*se.w1.ToDegrees(null==n.outerAngle?Math.PI:n.outerAngle),0))})))}i(t)})).then((e=>Promise.all(s).then((()=>e))))}))}loadAnimationAsync(e,t){return $A.LoadExtensionAsync(e,t,this.name,((i,n)=>this._loader.loadAnimationAsync(e,t).then((s=>{const r=new Array;qA.Assign(n.events);for(const o of n.events)r.push(this._loadAnimationEventAsync(`${i}/events/${o.index}`,e,t,o,s));return Promise.all(r).then((()=>s))}))))}_loadClipAsync(e,t){if(t._objectURL)return t._objectURL;let i;if(t.uri)i=this._loader.loadUriAsync(e,t,t.uri);else{const n=qA.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{const s=t._babylonSounds[r]=new ve(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 s=Promise.all(e).then((()=>{const e=t.clips.map((e=>e.weight||1)),i=new xe(t.loop||!1,t._babylonSounds,e);t.innerAngle&&(i.directionalConeInnerAngle=2*se.w1.ToDegrees(t.innerAngle)),t.outerAngle&&(i.directionalConeOuterAngle=2*se.w1.ToDegrees(t.outerAngle)),t.volume&&(i.volume=t.volume),t._babylonData.sound=i}));t._babylonData={loaded:s}}return t._babylonData.loaded}_getEventAction(e,t,i,n,s){switch(i){case"play":return e=>{const i=(s||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,s){if(0==s.targetedAnimations.length)return Promise.resolve();const r=s.targetedAnimations[0],o=n.emitter,a=qA.Get(`/extensions/${this.name}/emitters`,this._emitters,o);return this._loadEmitterAsync(e,a).then((()=>{const t=a._babylonData.sound;if(t){const i=new $(n.time,this._getEventAction(e,t,n.action,n.time,n.startOffset));r.animation.addEvent(i),s.onAnimationGroupEndObservable.add((()=>{t.stop()})),s.onAnimationGroupPauseObservable.add((()=>{t.pause()}))}}))}}$A.RegisterExtension(sP,(e=>new rP(e)));const oP="MSFT_lod";class aP{constructor(e){this.name=oP,this.order=100,this.maxLODsToLoad=10,this.onNodeLODsLoadedObservable=new r.y$,this.onMaterialLODsLoadedObservable=new r.y$,this._bufferLODs=new Array,this._nodeIndexLOD=null,this._nodeSignalLODs=new Array,this._nodePromiseLODs=new Array,this._nodeBufferLODs=new Array,this._materialIndexLOD=null,this._materialSignalLODs=new Array,this._materialPromiseLODs=new Array,this._materialBufferLODs=new Array,this._loader=e,this.enabled=this._loader.isExtensionUsed(oP)}dispose(){this._loader=null,this._nodeIndexLOD=null,this._nodeSignalLODs.length=0,this._nodePromiseLODs.length=0,this._nodeBufferLODs.length=0,this._materialIndexLOD=null,this._materialSignalLODs.length=0,this._materialPromiseLODs.length=0,this._materialBufferLODs.length=0,this.onMaterialLODsLoadedObservable.clear(),this.onNodeLODsLoadedObservable.clear()}onReady(){for(let e=0;e{0!==e&&(this._loader.endPerformanceCounter(`Node LOD ${e}`),this._loader.log(`Loaded node LOD ${e}`)),this.onNodeLODsLoadedObservable.notifyObservers(e),e!==this._nodePromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Node LOD ${e+1}`),this._loadBufferLOD(this._nodeBufferLODs,e+1),this._nodeSignalLODs[e]&&this._nodeSignalLODs[e].resolve())}));this._loader._completePromises.push(t)}for(let e=0;e{0!==e&&(this._loader.endPerformanceCounter(`Material LOD ${e}`),this._loader.log(`Loaded material LOD ${e}`)),this.onMaterialLODsLoadedObservable.notifyObservers(e),e!==this._materialPromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Material LOD ${e+1}`),this._loadBufferLOD(this._materialBufferLODs,e+1),this._materialSignalLODs[e]&&this._materialSignalLODs[e].resolve())}));this._loader._completePromises.push(t)}}loadSceneAsync(e,t){const i=this._loader.loadSceneAsync(e,t);return this._loadBufferLOD(this._bufferLODs,0),i}loadNodeAsync(e,t,i){return $A.LoadExtensionAsync(e,t,this.name,((e,n)=>{let s;const r=this._getLODs(e,t,this._loader.gltf.nodes,n.ids);this._loader.logOpen(`${e}`);for(let t=0;t{i(e),e.setEnabled(!1)},o=this._loader.loadNodeAsync(`/nodes/${e.index}`,e,n).then((e=>{if(0!==t){const e=r[t-1];e._babylonTransformNode&&(this._disposeTransformNode(e._babylonTransformNode),delete e._babylonTransformNode)}return e.setEnabled(!0),e}));this._nodePromiseLODs[t]=this._nodePromiseLODs[t]||[],0===t?s=o:(this._nodeIndexLOD=null,this._nodePromiseLODs[t].push(o))}return this._loader.logClose(),s}))}_loadMaterialAsync(e,t,i,n,s){return this._nodeIndexLOD?null:$A.LoadExtensionAsync(e,t,this.name,((e,r)=>{let o;const a=this._getLODs(e,t,this._loader.gltf.materials,r.ids);this._loader.logOpen(`${e}`);for(let t=0;t{0===t&&s(e)})).then((e=>{if(0!==t){s(e);const i=a[t-1]._data;i[n]&&(this._disposeMaterials([i[n].babylonMaterial]),delete i[n])}return e}));this._materialPromiseLODs[t]=this._materialPromiseLODs[t]||[],0===t?o=r:(this._materialIndexLOD=null,this._materialPromiseLODs[t].push(r))}return this._loader.logClose(),o}))}_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 wC,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 wC,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 s=i,r=s+n-1;let o=e[t];return o?(o.start=Math.min(o.start,s),o.end=Math.max(o.end,r)):(o={start:s,end:r,loaded:new wC},e[t]=o),o.loaded.promise.then((e=>new Uint8Array(e.buffer,e.byteOffset+i-o.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 s=new Array;for(let r=n.length-1;r>=0;r--)if(s.push(qA.Get(`${e}/ids/${n[r]}`,i,n[r])),s.length===this.maxLODsToLoad)return s;return s.push(t),s}_disposeTransformNode(e){const t=new Array,i=e.material;i&&t.push(i);for(const s of e.getChildMeshes())s.material&&t.push(s.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 i in t)for(const e of this._loader.babylonScene.materials)e.hasTexture(t[i])&&delete t[i];for(const i in t)t[i].dispose()}}$A.RegisterExtension(oP,(e=>new aP(e)));const lP="MSFT_minecraftMesh";class hP{constructor(e){this.name=lP,this._loader=e,this.enabled=this._loader.isExtensionUsed(lP)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtraAsync(e,t,this.name,((n,s)=>{if(s){if(!(i instanceof O_))throw new Error(`${n}: Material type not supported`);const s=this._loader.loadMaterialPropertiesAsync(e,t,i);return i.needAlphaBlending()&&(i.forceDepthWrite=!0,i.separateCullingPass=!0),i.backFaceCulling=i.forceDepthWrite,i.twoSidedLighting=!0,s}return null}))}}$A.RegisterExtension(lP,(e=>new hP(e)));const cP="MSFT_sRGBFactors";class dP{constructor(e){this.name=cP,this._loader=e,this.enabled=this._loader.isExtensionUsed(cP)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return $A.LoadExtraAsync(e,t,this.name,((n,s)=>{if(s){if(!(i instanceof O_))throw new Error(`${n}: Material type not supported`);const s=this._loader.loadMaterialPropertiesAsync(e,t,i),r=i.getScene().getEngine().useExactSrgbConversions;return i.albedoTexture||i.albedoColor.toLinearSpaceToRef(i.albedoColor,r),i.reflectivityTexture||i.reflectivityColor.toLinearSpaceToRef(i.reflectivityColor,r),s}return null}))}}$A.RegisterExtension(cP,(e=>new dP(e)));const uP="ExtrasAsMetadata";class pP{_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=uP,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}}let fP,_P,mP,gP;$A.RegisterExtension(uP,(e=>new pP(e)));const vP=async e=>{e.clearColor=a.HE.FromHexString("#000"),mP=new Ln("camera1",se.w1.ToRadians(0),se.w1.ToRadians(0),15,o.P.Zero(),e);const{meshes:t}=await ht.ImportMeshAsync("","buster_drone/","drone.gltf",e);gP=t[0],gP.scaling=new o.P(3,3,3),gP.alwaysSelectAsActiveMesh=!0,gP.enablePointerMoveEvents=!0,gP.isNearPickable=!0;const i=e.getEngine().getRenderingCanvas();mP.allowUpsideDown,mP.wheelDeltaPercentage=.01,mP.lowerRadiusLimit=8,mP.upperRadiusLimit=70,mP.setTarget(gP),mP.attachControl(i,!1);const n=new Os("light",new o.P(0,10,10),e),s=new Os("light2",new o.P(0,-10,10),e);n.intensity=2.5,s.intensity=1.5;const{animation:r,lastFrame:l}=(e=>{const t=20*e,i=new A("zoom","position",20,A.ANIMATIONTYPE_VECTOR3,A.ANIMATIONLOOPMODE_CONSTANT);return i.setKeys([{frame:0,value:new o.P(0,70,0)},{frame:t,value:new o.P(3,7,-15)}]),{animation:[i],lastFrame:t}})(4);e.beginDirectAnimation(mP,r,0,l,!1)};self.onmessage=async e=>{let{data:{canvas:t,width:i,height:n,dispose:s,wheel:r,x:o,y:a}}=e;if(t){const e=(e=>{let{antialias:t,engineOptions:i,adaptToDeviceRatio:n,sceneOptions:s,onRender:r,onSceneReady:o,canvas:a}=e;const l=new fe.D(a,t,i,n),h=new N.x(l,s);return h.isReady()?o(h):h.onReadyObservable.addOnce((e=>o(e))),l.runRenderLoop((()=>{"function"==typeof r&&r(h),h.render()})),{scene:h,canvas:a}})({antialias:!0,onSceneReady:vP,canvas:t});fP=e.scene,_P=e.canvas,self.postMessage("ready")}fP&&_P&&!t&&i&&n&&(_P.width=i,_P.height=n,fP.getEngine().resize(!0)),s&&fP&&fP.getEngine().dispose(),mP&&r&&(mP.radius=mP.radius+r*mP.wheelDeltaPercentage),fP&&void 0!==o&&void 0!==a&&(mP.alpha-=o/100,mP.beta-=a/100)}},9802:function(e,t,i){i.d(t,{O:function(){return n}});class n{constructor(){this.hoverCursor="",this.actions=new Array,this.isRecursive=!1}static get HasTriggers(){for(const e in n.Triggers)if(Object.prototype.hasOwnProperty.call(n.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(const e in n.Triggers)if(Object.prototype.hasOwnProperty.call(n.Triggers,e)){const t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(const t in n.Triggers)if(Object.prototype.hasOwnProperty.call(n.Triggers,t)){if(parseInt(t)===e)return!0}return!1}}n.Triggers={}},9372:function(e,t,i){i.d(t,{V:function(){return n}});class n{constructor(e,t,i,n,s,r){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=n,this.sourceEvent=s,this.additionalData=r}static CreateNew(e,t,i){const s=e.getScene();return new n(e,s.pointerX,s.pointerY,s.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,s){return new n(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,s)}static CreateNewFromScene(e,t){return new n(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,s){return new n(e,t.x,t.y,null,i,s)}}},2186:function(e,t,i){i.d(t,{l:function(){return s},o:function(){return r}});var n=i(1545);class s{constructor(e,t,i,s=0,r=!1,o=!1,a=!1,l){this._isAlreadyOwned=!1,e.getScene?this._engine=e.getScene().getEngine():this._engine=e,this._updatable=i,this._instanced=o,this._divisor=l||1,t instanceof n.h?(this._data=null,this._buffer=t):(this._data=t,this._buffer=null),this.byteStride=a?s:s*Float32Array.BYTES_PER_ELEMENT,r||this.create()}createVertexBuffer(e,t,i,n,s,o=!1,a){const l=o?t:t*Float32Array.BYTES_PER_ELEMENT,h=n?o?n:n*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new r(this._engine,this,e,this._updatable,!0,h,void 0===s?this._instanced:s,l,i,void 0,void 0,!0,this._divisor||a)}isUpdatable(){return this._updatable}getData(){return this._data}getBuffer(){return this._buffer}getStrideSize(){return this.byteStride/Float32Array.BYTES_PER_ELEMENT}create(e=null){!e&&this._buffer||(e=e||this._data)&&(this._buffer?this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e),this._data=e):this._updatable?(this._buffer=this._engine.createDynamicVertexBuffer(e),this._data=e):this._buffer=this._engine.createVertexBuffer(e))}_rebuild(){this._buffer=null,this.create(this._data)}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._buffer=null,this._data=null)}}class r{get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){const t=0!=e;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}constructor(e,t,i,n,o,a,l,h,c,d,u=!1,p=!1,f=1,_=!1){if(t instanceof s?(this._buffer=t,this._ownsBuffer=_):(this._buffer=new s(e,t,n,a,o,l,p),this._ownsBuffer=!0),this.uniqueId=r._Counter++,this._kind=i,null==d){const e=this.getData();this.type=r.FLOAT,e instanceof Int8Array?this.type=r.BYTE:e instanceof Uint8Array?this.type=r.UNSIGNED_BYTE:e instanceof Int16Array?this.type=r.SHORT:e instanceof Uint16Array?this.type=r.UNSIGNED_SHORT:e instanceof Int32Array?this.type=r.INT:e instanceof Uint32Array&&(this.type=r.UNSIGNED_INT)}else this.type=d;const m=r.GetTypeByteLength(this.type);p?(this._size=c||(a?a/m:r.DeduceStride(i)),this.byteStride=a||this._buffer.byteStride||this._size*m,this.byteOffset=h||0):(this._size=c||a||r.DeduceStride(i),this.byteStride=a?a*m:this._buffer.byteStride||this._size*m,this.byteOffset=(h||0)*m),this.normalized=u,this._instanced=void 0!==l&&l,this._instanceDivisor=l?f:0,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&&this._buffer._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){const i=this.getData();if(!i)return null;const n=this.getSize()*r.GetTypeByteLength(this.type),s=e*this.getSize();if(this.type!==r.FLOAT||this.byteStride!==n){const e=new Float32Array(s);return this.forEach(s,((t,i)=>e[i]=t)),e}if(!(i instanceof Array||i instanceof Float32Array)||0!==this.byteOffset||i.length!==s){if(i instanceof Array){const e=this.byteOffset/4;return i.slice(e,e+s)}if(i instanceof ArrayBuffer)return new Float32Array(i,this.byteOffset,s);{let e=i.byteOffset+this.byteOffset;if(t){const t=new Float32Array(s),n=new Float32Array(i.buffer,e,s);return t.set(n),t}const n=e%4;return n&&(e=Math.max(0,e-n)),new Float32Array(i.buffer,e,s)}}return t?i.slice():i}getBuffer(){return this._buffer.getBuffer()}getStrideSize(){return this.byteStride/r.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/r.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*r.GetTypeByteLength(this.type):this._size}getIsInstanced(){return this._instanced}getInstanceDivisor(){return this._instanceDivisor}create(e){this._buffer.create(e)}update(e){this._buffer.update(e)}updateDirectly(e,t,i=!1){this._buffer.updateDirectly(e,t,void 0,i)}dispose(){this._ownsBuffer&&this._buffer.dispose()}forEach(e,t){r.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}static DeduceStride(e){switch(e){case r.UVKind:case r.UV2Kind:case r.UV3Kind:case r.UV4Kind:case r.UV5Kind:case r.UV6Kind:return 2;case r.NormalKind:case r.PositionKind:return 3;case r.ColorKind:case r.MatricesIndicesKind:case r.MatricesIndicesExtraKind:case r.MatricesWeightsKind:case r.MatricesWeightsExtraKind:case r.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetTypeByteLength(e){switch(e){case r.BYTE:case r.UNSIGNED_BYTE:return 1;case r.SHORT:case r.UNSIGNED_SHORT:return 2;case r.INT:case r.UNSIGNED_INT:case r.FLOAT:return 4;default:throw new Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,n,s,o,a,l){if(e instanceof Array){let s=t/4;const r=i/4;for(let t=0;t-1?(c.Y.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 l.y3.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()||(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){var t,i,n,s,r,o,a,h;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 c=this.getEngine(),d=this.getScene(),u=c.useReverseDepthBuffer;if(this.mode===_.PERSPECTIVE_CAMERA){let e;this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=c.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1),e=d.useRightHandedSystem?l.y3.PerspectiveFovRHToRef:l.y3.PerspectiveFovLHToRef,e(this.fov,c.getAspectRatio(this),u?this.maxZ:this.minZ,u?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===_.FOVMODE_VERTICAL_FIXED,c.isNDCHalfZRange,this.projectionPlaneTilt,u)}else{const e=c.getRenderWidth()/2,p=c.getRenderHeight()/2;d.useRightHandedSystem?l.y3.OrthoOffCenterRHToRef(null!==(t=this.orthoLeft)&&void 0!==t?t:-e,null!==(i=this.orthoRight)&&void 0!==i?i:e,null!==(n=this.orthoBottom)&&void 0!==n?n:-p,null!==(s=this.orthoTop)&&void 0!==s?s:p,u?this.maxZ:this.minZ,u?this.minZ:this.maxZ,this._projectionMatrix,c.isNDCHalfZRange):l.y3.OrthoOffCenterLHToRef(null!==(r=this.orthoLeft)&&void 0!==r?r:-e,null!==(o=this.orthoRight)&&void 0!==o?o:e,null!==(a=this.orthoBottom)&&void 0!==a?a:-p,null!==(h=this.orthoTop)&&void 0!==h?h:p,u?this.maxZ:this.minZ,u?this.minZ:this.maxZ,this._projectionMatrix,c.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.renderWidth=c.getRenderWidth(),this._cache.renderHeight=c.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix}getTransformationMatrix(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?f.i.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=f.i.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),t&&this.rigCameras.length>0){let t=!1;return this.rigCameras.forEach((i=>{i._updateFrustumPlanes(),t=t||e.isInFrustum(i._frustumPlanes)})),t}return e.isInFrustum(this._frustumPlanes)}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw(0,u.S)("Ray")}getForwardRayToRef(e,t=100,i,n){throw(0,u.S)("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!==_.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=o.w1.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==_.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 l.y3.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}_updateCameraRotationMatrix(){}_updateWebVRCameraRotationMatrix(){}_getWebVRProjectionMatrix(){return l.y3.Identity()}_getWebVRViewMatrix(){return l.y3.Identity()}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,"interaxialDistance"===e&&(this._cameraRigParams.stereoHalfAngle=o.w1.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;e_._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const i=e.type,n=_.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),r=s.p4.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=l.P.FromArray(e.upVector)),r.setPosition&&(r.position.copyFromFloats(0,0,0),r.setPosition(l.P.FromArray(e.position))),e.target&&r.setTarget&&r.setTarget(l.P.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{throw(0,u.S)("UniversalCamera")},_.PERSPECTIVE_CAMERA=0,_.ORTHOGRAPHIC_CAMERA=1,_.FOVMODE_VERTICAL_FIXED=0,_.FOVMODE_HORIZONTAL_FIXED=1,_.RIG_MODE_NONE=0,_.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,_.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,_.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,_.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,_.RIG_MODE_STEREOSCOPIC_INTERLACED=14,_.RIG_MODE_VR=20,_.RIG_MODE_WEBVR=21,_.RIG_MODE_CUSTOM=22,_.ForceAttachControlToAlwaysPreventDefault=!1,(0,n.gn)([(0,s.hd)("position")],_.prototype,"_position",void 0),(0,n.gn)([(0,s.hd)("upVector")],_.prototype,"_upVector",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"orthoLeft",null),(0,n.gn)([(0,s.qC)()],_.prototype,"orthoRight",null),(0,n.gn)([(0,s.qC)()],_.prototype,"orthoBottom",null),(0,n.gn)([(0,s.qC)()],_.prototype,"orthoTop",null),(0,n.gn)([(0,s.qC)()],_.prototype,"fov",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"projectionPlaneTilt",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"minZ",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"maxZ",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"inertia",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"mode",null),(0,n.gn)([(0,s.qC)()],_.prototype,"layerMask",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"fovMode",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"cameraRigMode",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"interaxialDistance",void 0),(0,n.gn)([(0,s.qC)()],_.prototype,"isStereoscopicSideBySide",void 0)},3573:function(e,t,i){i.d(t,{c:function(){return n}});class n{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}},7901:function(e,t,i){i.d(t,{a:function(){return s}});var n=i(5412);class s{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new n.P(0,0,0),this._diffPositionForCollisions=new n.P(0,0,0),this._collisionResponse=!0}}},318:function(e,t,i){i.d(t,{p:function(){return r}});var n=i(5412),s=i(2186);class r{constructor(){this.hit=!1,this.distance=0,this.pickedPoint=null,this.pickedMesh=null,this.bu=0,this.bv=0,this.faceId=-1,this.subMeshFaceId=-1,this.subMeshId=0,this.pickedSprite=null,this.thinInstanceIndex=-1,this.ray=null,this.originMesh=null,this.aimTransform=null,this.gripTransform=null}getNormal(e=!1,t=!0){if(!this.pickedMesh||t&&!this.pickedMesh.isVerticesDataPresent(s.o.NormalKind))return null;let i,r=this.pickedMesh.getIndices();0===(null==r?void 0:r.length)&&(r=null);const o=n.jp.Vector3[0],a=n.jp.Vector3[1],l=n.jp.Vector3[2];if(t){const e=this.pickedMesh.getVerticesData(s.o.NormalKind);let t=r?n.P.FromArrayToRef(e,3*r[3*this.faceId],o):o.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),h=r?n.P.FromArrayToRef(e,3*r[3*this.faceId+1],a):a.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),c=r?n.P.FromArrayToRef(e,3*r[3*this.faceId+2],l):l.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]);t=t.scale(this.bu),h=h.scale(this.bv),c=c.scale(1-this.bu-this.bv),i=new n.P(t.x+h.x+c.x,t.y+h.y+c.y,t.z+h.z+c.z)}else{const e=this.pickedMesh.getVerticesData(s.o.PositionKind),t=r?n.P.FromArrayToRef(e,3*r[3*this.faceId],o):o.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),h=r?n.P.FromArrayToRef(e,3*r[3*this.faceId+1],a):a.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),c=r?n.P.FromArrayToRef(e,3*r[3*this.faceId+2],l):l.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]),d=t.subtract(h),u=c.subtract(h);i=n.P.Cross(d,u)}const h=(e,t)=>{let i=e.getWorldMatrix();e.nonUniformScaling&&(n.jp.Matrix[0].copyFrom(i),i=n.jp.Matrix[0],i.setTranslationFromFloats(0,0,0),i.invert(),i.transposeToRef(n.jp.Matrix[1]),i=n.jp.Matrix[1]),n.P.TransformNormalToRef(t,i,t)};if(e&&h(this.pickedMesh,i),this.ray){const t=n.jp.Vector3[0].copyFrom(i);e||h(this.pickedMesh,t),n.P.Dot(t,this.ray.direction)>0&&i.negateInPlace()}return i.normalize(),i}getTextureCoordinates(e=s.o.UVKind){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e))return null;const t=this.pickedMesh.getIndices();if(!t)return null;const i=this.pickedMesh.getVerticesData(e);if(!i)return null;let r=n.FM.FromArray(i,2*t[3*this.faceId]),o=n.FM.FromArray(i,2*t[3*this.faceId+1]),a=n.FM.FromArray(i,2*t[3*this.faceId+2]);return r=r.scale(this.bu),o=o.scale(this.bv),a=a.scale(1-this.bu-this.bv),new n.FM(r.x+o.x+a.x,r.y+o.y+a.y)}}},6629:function(e,t,i){i.d(t,{e:function(){return n}});class n{}n.UseOpenGLOrientationForUV=!1},3773:function(e,t,i){i.d(t,{k:function(){return o}});var n=i(2554),s=i(5412),r=i(4551);class o{constructor(e,t,i){this.vectors=n.B.BuildArray(8,s.P.Zero),this.center=s.P.Zero(),this.centerWorld=s.P.Zero(),this.extendSize=s.P.Zero(),this.extendSizeWorld=s.P.Zero(),this.directions=n.B.BuildArray(3,s.P.Zero),this.vectorsWorld=n.B.BuildArray(8,s.P.Zero),this.minimumWorld=s.P.Zero(),this.maximumWorld=s.P.Zero(),this.minimum=s.P.Zero(),this.maximum=s.P.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){const n=e.x,r=e.y,o=e.z,a=t.x,l=t.y,h=t.z,c=this.vectors;this.minimum.copyFromFloats(n,r,o),this.maximum.copyFromFloats(a,l,h),c[0].copyFromFloats(n,r,o),c[1].copyFromFloats(a,l,h),c[2].copyFromFloats(a,r,o),c[3].copyFromFloats(n,l,o),c[4].copyFromFloats(n,r,h),c[5].copyFromFloats(a,l,o),c[6].copyFromFloats(n,l,h),c[7].copyFromFloats(a,r,h),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||s.y3.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=o._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),n=i.length();i.normalizeFromLength(n);const s=n*e,r=i.scaleInPlace(.5*s),a=this.center.subtractToRef(r,t[1]),l=this.center.addToRef(r,t[2]);return this.reConstruct(a,l,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){const t=this.minimumWorld,i=this.maximumWorld,n=this.directions,r=this.vectorsWorld,o=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let e=0;e<8;++e)r[e].copyFrom(o[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];s.P.TransformCoordinatesToRef(o[n],e,a),t.minimizeInPlace(a),i.maximizeInPlace(a)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}s.P.FromArrayToRef(e.m,0,n[0]),s.P.FromArrayToRef(e.m,4,n[1]),s.P.FromArrayToRef(e.m,8,n[2]),this._worldMatrix=e}isInFrustum(e){return o.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return o.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,i=this.maximumWorld,n=t.x,s=t.y,o=t.z,a=i.x,l=i.y,h=i.z,c=e.x,d=e.y,u=e.z,p=-r.kn;return!(a-cc-n)&&(!(l-dd-s)&&!(h-uu-o))}intersectsSphere(e){return o.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const i=this.minimumWorld,n=this.maximumWorld,s=i.x,r=i.y,o=i.z,a=n.x,l=n.y,h=n.z,c=e.x,d=e.y,u=e.z,p=t.x,f=t.y,_=t.z;return!(ap)&&(!(lf)&&!(h_))}dispose(){var e,t;null===(e=this._drawWrapperFront)||void 0===e||e.dispose(),null===(t=this._drawWrapperBack)||void 0===t||t.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,n){const r=o._TmpVector3[0];s.P.ClampToRef(i,e,t,r);return s.P.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 s=t[i];for(let t=0;t<8;++t)if(s.dotCoordinate(e[t])>=0){n=!1;break}if(n)return!1}return!0}}o._TmpVector3=n.B.BuildArray(3,s.P.Zero)},2789:function(e,t,i){i.d(t,{j:function(){return d}});var n=i(2554),s=i(5412),r=i(3773),o=i(2897);const a={min:0,max:0},l={min:0,max:0},h=(e,t,i)=>{const n=s.P.Dot(t.centerWorld,e),r=Math.abs(s.P.Dot(t.directions[0],e))*t.extendSize.x+Math.abs(s.P.Dot(t.directions[1],e))*t.extendSize.y+Math.abs(s.P.Dot(t.directions[2],e))*t.extendSize.z;i.min=n-r,i.max=n+r},c=(e,t,i)=>(h(e,t,a),h(e,i,l),!(a.min>l.max||l.min>a.max));class d{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new r.k(e,t,i),this.boundingSphere=new o.K(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=d._TmpVector3[0].copyFrom(e).subtractInPlace(t),n=d._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=s.P.Minimize(this.minimum,e),i=s.P.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=s.jp.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const i=s.jp.Vector3[0];return s.P.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),s.P.TransformCoordinatesToRef(e.boundingBox.maximumWorld,t,i),this.encapsulate(i),this}scale(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this}isInFrustum(e,t=0){if((2===t||3===t)&&this.boundingSphere.isCenterInFrustum(e))return!0;if(!this.boundingSphere.isInFrustum(e))return!1;return!(1!==t&&3!==t)||this.boundingBox.isInFrustum(e)}get diagonalLength(){const e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,d._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(!o.K.Intersects(this.boundingSphere,e.boundingSphere))return!1;if(!r.k.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const i=this.boundingBox,n=e.boundingBox;return!!c(i.directions[0],i,n)&&(!!c(i.directions[1],i,n)&&(!!c(i.directions[2],i,n)&&(!!c(n.directions[0],i,n)&&(!!c(n.directions[1],i,n)&&(!!c(n.directions[2],i,n)&&(!!c(s.P.Cross(i.directions[0],n.directions[0]),i,n)&&(!!c(s.P.Cross(i.directions[0],n.directions[1]),i,n)&&(!!c(s.P.Cross(i.directions[0],n.directions[2]),i,n)&&(!!c(s.P.Cross(i.directions[1],n.directions[0]),i,n)&&(!!c(s.P.Cross(i.directions[1],n.directions[1]),i,n)&&(!!c(s.P.Cross(i.directions[1],n.directions[2]),i,n)&&(!!c(s.P.Cross(i.directions[2],n.directions[0]),i,n)&&(!!c(s.P.Cross(i.directions[2],n.directions[1]),i,n)&&!!c(s.P.Cross(i.directions[2],n.directions[2]),i,n))))))))))))))}}d._TmpVector3=n.B.BuildArray(2,s.P.Zero)},2897:function(e,t,i){i.d(t,{K:function(){return r}});var n=i(2554),s=i(5412);class r{constructor(e,t,i){this.center=s.P.Zero(),this.centerWorld=s.P.Zero(),this.minimum=s.P.Zero(),this.maximum=s.P.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const n=s.P.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*n,this._update(i||s.y3.IdentityReadOnly)}scale(e){const t=this.radius*e,i=r._TmpVector3,n=i[0].setAll(t),s=this.center.subtractToRef(n,i[1]),o=this.center.addToRef(n,i[2]);return this.reConstruct(s,o,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{s.P.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=r._TmpVector3[0];s.P.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=s.P.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld=n.Fz.LeftClick&&i<=n.Fz.RightClick&&(l.type=1===s?"pointerdown":"pointerup",l.button=i-2),l}static _CreateWheelEvent(e,t,i,s,o,a){const l=this._CreateMouseEvent(e,t,i,s,o,a);switch(l.pointerId=1,l.type="wheel",l.deltaMode=r.G.DOM_DELTA_PIXEL,l.deltaX=0,l.deltaY=0,l.deltaZ=0,i){case n.Fz.MouseWheelX:l.deltaX=s;break;case n.Fz.MouseWheelY:l.deltaY=s;break;case n.Fz.MouseWheelZ:l.deltaZ=s}return l}static _CreateMouseEvent(e,t,i,s,r,o){const a=this._CreateEvent(o),l=r.pollInput(e,t,n.Fz.Horizontal),h=r.pollInput(e,t,n.Fz.Vertical);return o?(a.movementX=0,a.movementY=0,a.offsetX=a.movementX-o.getBoundingClientRect().x,a.offsetY=a.movementY-o.getBoundingClientRect().y):(a.movementX=r.pollInput(e,t,n.FP.DeltaHorizontal),a.movementY=r.pollInput(e,t,n.FP.DeltaVertical),a.offsetX=0,a.offsetY=0),this._CheckNonCharacterKeys(a,r),a.clientX=l,a.clientY=h,a.x=l,a.y=h,a.deviceType=e,a.deviceSlot=t,a.inputIndex=i,a}static _CreateKeyboardEvent(e,t,i,s){const r=this._CreateEvent(s);return this._CheckNonCharacterKeys(r,i),r.deviceType=n.Yi.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(n.Yi.Keyboard),s=i&&1===t.pollInput(n.Yi.Keyboard,0,18),r=i&&1===t.pollInput(n.Yi.Keyboard,0,17),o=i&&(1===t.pollInput(n.Yi.Keyboard,0,91)||1===t.pollInput(n.Yi.Keyboard,0,92)||1===t.pollInput(n.Yi.Keyboard,0,93)),a=i&&1===t.pollInput(n.Yi.Keyboard,0,16);e.altKey=s,e.ctrlKey=r,e.metaKey=o,e.shiftKey=a}static _CreateEvent(e){const t={preventDefault:()=>{}};return t.target=e,t}}class a{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,((e,t,n,s)=>{const r=o.CreateDeviceEvent(e,t,n,s,this);i(e,t,r)})):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===n.Yi.Mouse||e===n.Yi.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}var l=i(1102),h=i(8658);const c=Object.keys(n.Fz).length/2;class d{constructor(e,t,i,n){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=h.w1.IsSafari(),this._usingMacOS=(0,l.up)()&&/(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._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=l.MZ.IsNavigatorAvailable()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Firefox"),this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=e=>{},this._gamepadDisconnectedEvent=e=>{},this._eventPrefix=h.w1.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 s=this._inputs[e][t];if(!s)throw`Unable to find device ${n.Yi[e]}`;e>=n.Yi.DualShock&&e<=n.Yi.DualSense&&this._updateDevice(e,t,i);const r=s[i];if(void 0===r)throw`Unable to find input ${i} for device ${n.Yi[e]} in slot ${t}`;return i===n.Fz.Move&&h.w1.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=null==this?void 0:this._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs)for(const e of this._inputs)if(e)for(const t in e){const i=e[+t];if(i)for(let e=0;e{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(n.Yi.Keyboard,0,255));const t=this._inputs[n.Yi.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(n.Yi.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(n.Yi.Keyboard,0,255));const t=this._inputs[n.Yi.Keyboard][0];if(t){t[e.keyCode]=0;const i=e;if(i.inputIndex=e.keyCode,this._usingMacOS&&"Meta"===e.key&&this._metaKeys.length>0){for(const e of this._metaKeys){const i=o.CreateDeviceEvent(n.Yi.Keyboard,0,e,0,this,this._elementToAttachTo);t[e]=0,this._onInputChanged(n.Yi.Keyboard,0,i)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(n.Yi.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[n.Yi.Keyboard][0];for(let t=0;t{const t=this._getPointerType(e),i=t===n.Yi.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]||this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const r=e;r.inputIndex=n.Fz.Move,s[n.Fz.Horizontal]=e.clientX,s[n.Fz.Vertical]=e.clientY,void 0===e.pointerId&&(e.pointerId=this._mouseId),this._onInputChanged(t,i,r),this._usingSafari||-1===e.button||(r.inputIndex=e.button+2,s[e.button+2]=s[e.button+2]?0:1,this._onInputChanged(t,i,r))}},this._pointerDownEvent=e=>{const t=this._getPointerType(e);let i=t===n.Yi.Mouse?0:e.pointerId;if(t===n.Yi.Touch){const t=this._activeTouchIds.indexOf(-1);if(!(t>=0))return void h.w1.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===n.Yi.Touch&&this._onDeviceConnected(t,i):this._addPointerDevice(t,i,e.clientX,e.clientY);const s=this._inputs[t][i];if(s){const o=s[n.Fz.Horizontal],a=s[n.Fz.Vertical];if(t===n.Yi.Mouse){if(void 0===e.pointerId&&(e.pointerId=this._mouseId),!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(this._mouseId)}catch(r){}}else if(e.pointerId&&!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(e.pointerId)}catch(r){}s[n.Fz.Horizontal]=e.clientX,s[n.Fz.Vertical]=e.clientY,s[e.button+2]=1;const l=e;l.inputIndex=e.button+2,this._onInputChanged(t,i,l),o===e.clientX&&a===e.clientY||(l.inputIndex=n.Fz.Move,this._onInputChanged(t,i,l))}},this._pointerUpEvent=e=>{var t,i,s,r,o;const a=this._getPointerType(e),l=a===n.Yi.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(a===n.Yi.Touch){if(-1===l)return;this._activeTouchIds[l]=-1}const h=null===(t=this._inputs[a])||void 0===t?void 0:t[l];if(h&&0!==h[e.button+2]){const t=h[n.Fz.Horizontal],c=h[n.Fz.Vertical];h[n.Fz.Horizontal]=e.clientX,h[n.Fz.Vertical]=e.clientY,h[e.button+2]=0;const d=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),t===e.clientX&&c===e.clientY||(d.inputIndex=n.Fz.Move,this._onInputChanged(a,l,d)),d.inputIndex=e.button+2,a===n.Yi.Mouse&&this._mouseId>=0&&(null===(s=(i=this._elementToAttachTo).hasPointerCapture)||void 0===s?void 0:s.call(i,this._mouseId))?this._elementToAttachTo.releasePointerCapture(this._mouseId):e.pointerId&&(null===(o=(r=this._elementToAttachTo).hasPointerCapture)||void 0===o?void 0:o.call(r,e.pointerId))&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._onInputChanged(a,l,d),a===n.Yi.Touch&&this._onDeviceDisconnected(a,l)}},this._pointerCancelEvent=e=>{var t,i,s,r;if("mouse"===e.pointerType){const e=this._inputs[n.Yi.Mouse][0];this._mouseId>=0&&(null===(i=(t=this._elementToAttachTo).hasPointerCapture)||void 0===i?void 0:i.call(t,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=n.Fz.LeftClick;t<=n.Fz.BrowserForward;t++)if(1===e[t]){e[t]=0;const i=o.CreateDeviceEvent(n.Yi.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(n.Yi.Mouse,0,i)}}else{const t=this._activeTouchIds.indexOf(e.pointerId);(null===(r=(s=this._elementToAttachTo).hasPointerCapture)||void 0===r?void 0:r.call(s,e.pointerId))&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._inputs[n.Yi.Touch][t][n.Fz.LeftClick]=0;const i=o.CreateDeviceEvent(n.Yi.Touch,t,n.Fz.LeftClick,0,this,this._elementToAttachTo,e.pointerId);this._onInputChanged(n.Yi.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(n.Yi.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(i){}this._pointerBlurEvent=()=>{var e,t,i,s,r;if(this.isDeviceAvailable(n.Yi.Mouse)){const i=this._inputs[n.Yi.Mouse][0];this._mouseId>=0&&(null===(t=(e=this._elementToAttachTo).hasPointerCapture)||void 0===t?void 0:t.call(e,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let e=n.Fz.LeftClick;e<=n.Fz.BrowserForward;e++)if(1===i[e]){i[e]=0;const t=o.CreateDeviceEvent(n.Yi.Mouse,0,e,0,this,this._elementToAttachTo);this._onInputChanged(n.Yi.Mouse,0,t)}}if(this.isDeviceAvailable(n.Yi.Touch)){const e=this._inputs[n.Yi.Touch];for(let t=0;t{const t=n.Yi.Mouse;this._inputs[t]||(this._inputs[t]=[]),this._inputs[t][0]||(this._pointerActive=!0,this._registerDevice(t,0,c));const i=this._inputs[t][0];if(i){i[n.Fz.MouseWheelX]=e.deltaX||0,i[n.Fz.MouseWheelY]=e.deltaY||e.wheelDelta||0,i[n.Fz.MouseWheelZ]=e.deltaZ||0;const s=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),0!==i[n.Fz.MouseWheelX]&&(s.inputIndex=n.Fz.MouseWheelX,this._onInputChanged(t,0,s)),0!==i[n.Fz.MouseWheelY]&&(s.inputIndex=n.Fz.MouseWheelY,this._onInputChanged(t,0,s)),0!==i[n.Fz.MouseWheelZ]&&(s.inputIndex=n.Fz.MouseWheelZ,this._onInputChanged(t,0,s))}},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(n.Yi.Mouse)){const e=this._inputs[n.Yi.Mouse][0];e[n.Fz.MouseWheelX]=0,e[n.Fz.MouseWheelY]=0,e[n.Fz.MouseWheelZ]=0}}))}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){const t=this._getGamepadDeviceType(e.gamepad.id),i=e.gamepad.index;this._unregisterDevice(t,i),delete this._gamepads[i]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,i){const n=navigator.getGamepads()[t];if(n&&e===this._gamepads[t]){const s=this._inputs[e][t];i>=n.buttons.length?s[i]=n.axes[i-n.buttons.length].valueOf():s[i]=n.buttons[i].value}}_getGamepadDeviceType(e){return-1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?n.Yi.DualSense:n.Yi.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")?n.Yi.Xbox:-1!==e.indexOf("057e")?n.Yi.Switch:n.Yi.Generic}_getPointerType(e){let t=n.Yi.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=n.Yi.Touch),t}}var u=i(505);class p{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=e=>{for(let t=0;t{const t=this._registeredManagers.indexOf(e);t>-1&&this._registeredManagers.splice(t,1)};const t=Object.keys(n.Yi).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 u.p(this._deviceInputSystem,e,t);i._addDevice(n)}},s=(e,t)=>{var i;(null===(i=this._devices[e])||void 0===i?void 0:i[t])&&delete this._devices[e][t];for(const n of this._registeredManagers)n._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 a(i,s,r):this._deviceInputSystem=new d(e,i,s,r)}dispose(){this._deviceInputSystem.dispose()}}class f{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(n.Yi).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new p(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new s.y$((e=>{for(const t of this._devices)if(t)for(const i of t)i&&this.onDeviceConnectedObservable.notifyObserver(e,i)})),this.onDeviceDisconnectedObservable=new s.y$,this._engine._deviceSourceManager.registerManager(this),this._onDisposeObserver=e.onDisposeObservable.add((()=>{this.dispose()}))}dispose(){this.onDeviceConnectedObservable.clear(),this.onDeviceDisconnectedObservable.clear(),this._engine._deviceSourceManager&&(this._engine._deviceSourceManager.unregisterManager(this),--this._engine._deviceSourceManager._refCount<1&&(this._engine._deviceSourceManager.dispose(),delete this._engine._deviceSourceManager)),this._engine.onDisposeObservable.remove(this._onDisposeObserver)}_addDevice(e){this._devices[e.deviceType]||(this._devices[e.deviceType]=new Array),this._devices[e.deviceType][e.deviceSlot]||(this._devices[e.deviceType][e.deviceSlot]=e,this._updateFirstDevices(e.deviceType)),this.onDeviceConnectedObservable.notifyObservers(e)}_removeDevice(e,t){var i,n;const s=null===(i=this._devices[e])||void 0===i?void 0:i[t];this.onDeviceDisconnectedObservable.notifyObservers(s),(null===(n=this._devices[e])||void 0===n?void 0:n[t])&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){var n,s;null===(s=null===(n=this._devices[e])||void 0===n?void 0:n[t])||void 0===s||s.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case n.Yi.Keyboard:case n.Yi.Mouse:this._firstDevice[e]=0;break;case n.Yi.Touch:case n.Yi.DualSense:case n.Yi.DualShock:case n.Yi.Xbox:case n.Yi.Switch:case n.Yi.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t)for(let i=0;i=s&&0===i?t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,new Float32Array(t)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,t):t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(i,i+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()}},9834:function(e,t,i){i.d(t,{A:function(){return s}});var n=i(9271);function s(e,t,i=!1,n){switch(e){case 3:{const e=(ArrayBuffer,new Int8Array(t));return n&&e.set(new Int8Array(n)),e}case 0:{const e=(ArrayBuffer,new Uint8Array(t));return n&&e.set(new Uint8Array(n)),e}case 4:{const e=t instanceof ArrayBuffer?new Int16Array(t):new Int16Array(i?t/2:t);return n&&e.set(new Int16Array(n)),e}case 5:case 8:case 9:case 10:case 2:{const e=t instanceof ArrayBuffer?new Uint16Array(t):new Uint16Array(i?t/2:t);return n&&e.set(new Uint16Array(n)),e}case 6:{const e=t instanceof ArrayBuffer?new Int32Array(t):new Int32Array(i?t/4:t);return n&&e.set(new Int32Array(n)),e}case 7:case 11:case 12:case 13:case 14:case 15:{const e=t instanceof ArrayBuffer?new Uint32Array(t):new Uint32Array(i?t/4:t);return n&&e.set(new Uint32Array(n)),e}case 1:{const e=t instanceof ArrayBuffer?new Float32Array(t):new Float32Array(i?t/4:t);return n&&e.set(new Float32Array(n)),e}}const s=(ArrayBuffer,new Uint8Array(t));return n&&s.set(new Uint8Array(n)),s}n.B.prototype._readTexturePixelsSync=function(e,t,i,n=-1,r=0,o=null,a=!0,l=!1,h=0,c=0){var d,u;const p=this._gl;if(!p)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const e=p.createFramebuffer();if(!e)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=e}p.bindFramebuffer(p.FRAMEBUFFER,this._dummyFramebuffer),n>-1?p.framebufferTexture2D(p.FRAMEBUFFER,p.COLOR_ATTACHMENT0,p.TEXTURE_CUBE_MAP_POSITIVE_X+n,null===(d=e._hardwareTexture)||void 0===d?void 0:d.underlyingResource,r):p.framebufferTexture2D(p.FRAMEBUFFER,p.COLOR_ATTACHMENT0,p.TEXTURE_2D,null===(u=e._hardwareTexture)||void 0===u?void 0:u.underlyingResource,r);let f=void 0!==e.type?this._getWebGLTextureType(e.type):p.UNSIGNED_BYTE;if(l)o||(o=s(e.type,4*t*i));else if(f===p.UNSIGNED_BYTE)o||(o=new Uint8Array(4*t*i)),f=p.UNSIGNED_BYTE;else o||(o=new Float32Array(4*t*i)),f=p.FLOAT;return a&&this.flushFramebuffer(),p.readPixels(h,c,t,i,p.RGBA,f,o),p.bindFramebuffer(p.FRAMEBUFFER,this._currentFramebuffer),o},n.B.prototype._readTexturePixels=function(e,t,i,n=-1,s=0,r=null,o=!0,a=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(e,t,i,n,s,r,o,a,l,h))}},4507:function(e,t,i){var n=i(9271),s=i(4081);n.B.prototype.createUniformBuffer=function(e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create uniform buffer");const i=new s.M(t);return this.bindUniformBuffer(i),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),i.references=1,i},n.B.prototype.createDynamicUniformBuffer=function(e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create dynamic uniform buffer");const i=new s.M(t);return this.bindUniformBuffer(i),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),i.references=1,i},n.B.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)},n.B.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},n.B.prototype.bindUniformBufferBase=function(e,t,i){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},n.B.prototype.bindUniformBlock=function(e,t,i){const n=e.program,s=this._gl.getUniformBlockIndex(n,t);4294967295!==s&&this._gl.uniformBlockBinding(n,s,i)}},3525:function(e,t,i){i.d(t,{L:function(){return E}});class n{constructor(){this.children=[]}isValid(e){return!0}process(e,t){var i,n,s,r,o,a,l;let h="";if(this.line){let c=this.line;const d=t.processor;if(d){d.lineProcessor&&(c=d.lineProcessor(c,t.isFragment,t.processingContext));const h=null!==(n=null===(i=t.processor)||void 0===i?void 0:i.attributeKeywordName)&&void 0!==n?n:"attribute",u=t.isFragment&&(null===(s=t.processor)||void 0===s?void 0:s.varyingFragmentKeywordName)?null===(r=t.processor)||void 0===r?void 0:r.varyingFragmentKeywordName:!t.isFragment&&(null===(o=t.processor)||void 0===o?void 0:o.varyingVertexKeywordName)?null===(a=t.processor)||void 0===a?void 0:a.varyingVertexKeywordName:"varying";if(!t.isFragment&&d.attributeProcessor&&this.line.startsWith(h))c=d.attributeProcessor(this.line,e,t.processingContext);else if(d.varyingProcessor&&((null===(l=d.varyingCheck)||void 0===l?void 0:l.call(d,this.line,t.isFragment))||!d.varyingCheck&&this.line.startsWith(u)))c=d.varyingProcessor(this.line,t.isFragment,e,t.processingContext);else if(d.uniformProcessor&&d.uniformRegexp&&d.uniformRegexp.test(this.line))t.lookForClosingBracketForUniformBuffer||(c=d.uniformProcessor(this.line,t.isFragment,e,t.processingContext));else if(d.uniformBufferProcessor&&d.uniformBufferRegexp&&d.uniformBufferRegexp.test(this.line))t.lookForClosingBracketForUniformBuffer||(c=d.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0);else if(d.textureProcessor&&d.textureRegexp&&d.textureRegexp.test(this.line))c=d.textureProcessor(this.line,t.isFragment,e,t.processingContext);else if((d.uniformProcessor||d.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer){/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?d.uniformProcessor&&(c=d.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):d.uniformBufferProcessor&&(c=d.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)}t.lookForClosingBracketForUniformBuffer&&-1!==this.line.indexOf("}")&&(t.lookForClosingBracketForUniformBuffer=!1,d.endOfUniformBufferProcessor&&(c=d.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}h+=c+"\r\n"}return this.children.forEach((i=>{h+=i.process(e,t)})),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),h}}class s{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex{c=c.trim(),""!==c&&(i.push(c),c="")},r=e=>{na._Stack[n],l=()=>-1===n?"!!INVALID EXPRESSION!!":a._Stack[n--];let h=0,c="";for(;h1){for(s();-1!==n&&a._OperatorPriority[o()]>=a._OperatorPriority[d];)i.push(l());r(d),h++}else c+=t;h++}for(s();-1!==n;)"("===o()?l():i.push(l());return a._InfixToPostfixCache.size>=a.InfixToPostfixCacheLimitSize&&a.ClearCache(),a._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){const e=Array.from(a._InfixToPostfixCache.entries()).sort(((e,t)=>e[1].accessTime-t[1].accessTime));for(let t=0;t":i=n>s;break;case"<":i=n=":i=n>=s;break;case"==":i=n===s;break;case"!=":i=n!==s}return i}}var u=i(9069),p=i(475);const f=/defined\s*?\((.+?)\)/g,_=/defined\s*?\[(.+?)\]/g,m=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,g=/__decl__/,v=/light\{X\}.(\w*)/g,T=/\{X\}/g,S=[];class E{static Initialize(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}static Process(e,t,i,n){var s;(null===(s=t.processor)||void 0===s?void 0:s.preProcessShaderCode)&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));const s=this._ProcessShaderConversion(e,t,n);i(s,e)}))}static PreProcess(e,t,i,n){var s;(null===(s=t.processor)||void 0===s?void 0:s.preProcessShaderCode)&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));const s=this._ApplyPreProcessing(e,t,n);i(s,e)}))}static Finalize(e,t,i){return i.processor&&i.processor.finalizeShaders?i.processor.finalizeShaders(e,t,i.processingContext):{vertexCode:e,fragmentCode:t}}static _ProcessPrecision(e,t){var i;if(null===(i=t.processor)||void 0===i?void 0:i.noPrecision)return e;const n=t.shouldUseHighPrecisionShader;return-1===e.indexOf("precision highp float")?e=n?"precision highp float;\n"+e:"precision mediump float;\n"+e:n||(e=e.replace("precision highp float","precision mediump float")),e}static _ExtractOperation(e){const t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new l(t[1].trim(),"!"===e[0]);const i=["==","!=",">=","<=","<",">"];let n="",s=0;for(n of i)if(s=e.indexOf(n),s>-1)break;if(-1===s)return new l(e);const r=e.substring(0,s).trim(),o=e.substring(s+n.length).trim();return new d(r,n,o)}static _BuildSubExpression(e){e=e.replace(f,"defined[$1]");const t=a.infixToPostfix(e),i=[];for(const s of t)if("||"!==s&&"&&"!==s)i.push(s);else if(i.length>=2){let e=i[i.length-1],t=i[i.length-2];i.length-=2;const n="&&"==s?new c:new h;"string"==typeof e&&(e=e.replace(_,"defined($1)")),"string"==typeof t&&(t=t.replace(_,"defined($1)")),n.leftOperand="string"==typeof t?this._ExtractOperation(t):t,n.rightOperand="string"==typeof e?this._ExtractOperation(e):e,i.push(n)}let n=i[i.length-1];return"string"==typeof n&&(n=n.replace(_,"defined($1)")),"string"==typeof n?this._ExtractOperation(n):n}static _BuildExpression(e,t){const i=new o,n=e.substring(0,t);let s=e.substring(t);return s=s.substring(0,(s.indexOf("//")+1||s.length+1)-1).trim(),i.testExpression="#ifdef"===n?new l(s):"#ifndef"===n?new l(s,!0):this._BuildSubExpression(s),i}static _MoveCursorWithinIf(e,t,i){let s=e.currentLine;for(;this._MoveCursor(e,i);){s=e.currentLine;const r=s.substring(0,5).toLowerCase();if("#else"===r){const i=new n;return t.children.push(i),void this._MoveCursor(e,i)}if("#elif"===r){const e=this._BuildExpression(s,5);t.children.push(e),i=e}}}static _MoveCursor(e,t){for(;e.canRead;){e.lineIndex++;const i=e.currentLine;if(i.indexOf("#")>=0){const n=E._MoveCursorRegex.exec(i);if(n&&n.length){switch(n[0]){case"#ifdef":{const n=new r;t.children.push(n);const s=this._BuildExpression(i,6);n.children.push(s),this._MoveCursorWithinIf(e,n,s);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const n=new r;t.children.push(n);const s=this._BuildExpression(i,7);n.children.push(s),this._MoveCursorWithinIf(e,n,s);break}case"#if":{const n=new r,s=this._BuildExpression(i,3);t.children.push(n),n.children.push(s),this._MoveCursorWithinIf(e,n,s);break}}continue}}const s=new n;if(s.line=i,t.children.push(s),"#"===i[0]&&"d"===i[1]){const e=i.replace(";","").split(" ");s.additionalDefineKey=e[1],3===e.length&&(s.additionalDefineValue=e[2])}}return!1}static _EvaluatePreProcessors(e,t,i){const r=new n,o=new s;return o.lineIndex=-1,o.lines=e.split("\n"),this._MoveCursor(o,r),r.process(t,i)}static _PreparePreProcessors(e,t){var i;const n=e.defines,s={};for(const r of n){const e=r.replace("#define","").replace(";","").trim().split(" ");s[e[0]]=e.length>1?e[1]:""}return(null===(i=e.processor)||void 0===i?void 0:i.shaderLanguage)===p.x.GLSL&&(s.GL_ES="true"),s.__VERSION__=e.version,s[e.platformName]="true",t._getGlobalDefines(s),s}static _ProcessShaderConversion(e,t,i){let n=this._ProcessPrecision(e,t);if(!t.processor)return n;if(t.processor.shaderLanguage===p.x.GLSL&&-1!==n.indexOf("#version 3")&&(n=n.replace("#version 300 es",""),!t.processor.parseGLES3))return n;const s=t.defines,r=this._PreparePreProcessors(t,i);return t.processor.preProcessor&&(n=t.processor.preProcessor(n,s,t.isFragment,t.processingContext)),n=this._EvaluatePreProcessors(n,r,t),t.processor.postProcessor&&(n=t.processor.postProcessor(n,s,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(n=i.inlineShaderCode(n)),n}static _ApplyPreProcessing(e,t,i){var n,s;let r=e;const o=t.defines,a=this._PreparePreProcessors(t,i);return(null===(n=t.processor)||void 0===n?void 0:n.preProcessor)&&(r=t.processor.preProcessor(r,o,t.isFragment,t.processingContext)),r=this._EvaluatePreProcessors(r,a,t),(null===(s=t.processor)||void 0===s?void 0:s.postProcessor)&&(r=t.processor.postProcessor(r,o,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(r=i.inlineShaderCode(r)),r}static _ProcessIncludes(e,t,i){let n;for(S.length=0;null!==(n=m.exec(e));)S.push(n);let s=String(e),r=[e],o=!1;for(const a of S){let e=a[1];if(-1!==e.indexOf("__decl__")&&(e=e.replace(g,""),t.supportsUniformBuffers&&(e=e.replace("Vertex","Ubo").replace("Fragment","Ubo")),e+="Declaration"),!t.includesShadersStore[e]){const n=t.shadersRepository+"ShadersInclude/"+e+".fx";return void E._FileToolsLoadFile(n,(n=>{t.includesShadersStore[e]=n,this._ProcessIncludes(r.join(""),t,i)}))}{let i=t.includesShadersStore[e];if(a[2]){const e=a[3].split(",");for(let t=0;tt+"{X}"))),i+=o.replace(T,e.toString())+"\n"}else t.supportsUniformBuffers||(i=i.replace(v,((e,t)=>t+"{X}"))),i=i.replace(T,e)}const n=[];for(const e of r){const t=e.split(a[0]);for(let e=0;e=0||i.indexOf("#include <")>=0}}S.length=0,s=r.join(""),o?this._ProcessIncludes(s.toString(),t,i):i(s)}static _FileToolsLoadFile(e,t,i,n,s,r){throw(0,u.S)("FileTools")}}E._MoveCursorRegex=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/},3156:function(e,t,i){i.d(t,{C:function(){return r}});var n=i(475);const s=/(flat\s)?\s*varying\s*.*/;class r{constructor(){this.shaderLanguage=n.x.GLSL}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return s.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)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?"":"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}}},8449:function(e,t,i){i.d(t,{B:function(){return n}});class n{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}}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}},1917:function(e,t,i){i.d(t,{y:function(){return n}});class n{constructor(){this._valueCache={},this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null}get isAsync(){return this.isParallelCompiled}get isReady(){return!!this.program&&(!this.isParallelCompiled||this.engine._isRenderingStateCompiled(this))}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}_fillEffectInformation(e,t,i,n,s,r,o,a){const l=this.engine;if(l.supportsUniformBuffers)for(const c in t)e.bindUniformBlock(c,t[c]);let h;for(this.engine.getUniforms(this,i).forEach(((e,t)=>{n[i[t]]=e})),this._uniforms=n,h=0;h{r[e]=t}));for(const c of l.getAttributes(this,o))a.push(c)}dispose(){this._uniforms={}}_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 s=!1;return n[0]!==t&&(n[0]=t,s=!0),n[1]!==i&&(n[1]=i,s=!0),s}_cacheFloat3(e,t,i,n){let s=this._valueCache[e];if(!s||3!==s.length)return s=[t,i,n],this._valueCache[e]=s,!0;let r=!1;return s[0]!==t&&(s[0]=t,r=!0),s[1]!==i&&(s[1]=i,r=!0),s[2]!==n&&(s[2]=n,r=!0),r}_cacheFloat4(e,t,i,n,s){let r=this._valueCache[e];if(!r||4!==r.length)return r=[t,i,n,s],this._valueCache[e]=r,!0;let o=!1;return r[0]!==t&&(r[0]=t,o=!0),r[1]!==i&&(r[1]=i,o=!0),r[2]!==n&&(r[2]=n,o=!0),r[3]!==s&&(r[3]=s,o=!0),o}setInt(e,t){const i=this._valueCache[e];void 0!==i&&i===t||this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,n){this._cacheFloat3(e,t,i,n)&&(this.engine.setInt3(this._uniforms[e],t,i,n)||(this._valueCache[e]=null))}setInt4(e,t,i,n,s){this._cacheFloat4(e,t,i,n,s)&&(this.engine.setInt4(this._uniforms[e],t,i,n,s)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const i=this._valueCache[e];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,s){this._cacheFloat4(e,t,i,n,s)&&(this.engine.setUInt4(this._uniforms[e],t,i,n,s)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this.engine.setMatrices(this._uniforms[e],t.toArray())||(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,s){this._cacheFloat4(e,t,i,n,s)&&(this.engine.setFloat4(this._uniforms[e],t,i,n,s)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}_getVertexShaderCode(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null}_getFragmentShaderCode(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null}}},2155:function(e,t,i){i.d(t,{f:function(){return s}});var n=i(475);class s{constructor(){this.shaderLanguage=n.x.GLSL}postProcessor(e,t,i,n,s){if(!s.getCaps().drawBuffersExtension){const t=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(t,"")}return e}}},8838:function(e,t,i){i.d(t,{D:function(){return f}});var n=i(8139),s=i(4679),r=i(1102),o=i(5953),a=i(9069),l=i(9271),h=i(4441),c=i(8482),d=i(4081),u=i(658),p=i(8449);i(2094),i(9834),i(6430);class f extends l.B{static get NpmPackage(){return l.B.NpmPackage}static get Version(){return l.B.Version}static get Instances(){return o.l.Instances}static get LastCreatedEngine(){return o.l.LastCreatedEngine}static get LastCreatedScene(){return o.l.LastCreatedScene}_createImageBitmapFromSource(e,t){return new Promise(((i,n)=>{const s=new Image;s.onload=()=>{s.decode().then((()=>{this.createImageBitmap(s,t).then((e=>{i(e)}))}))},s.onerror=()=>{n(`Error loading image ${s.src}`)},s.src=e}))}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){const n=this.createCanvas(t,i).getContext("2d");if(!n)throw new Error("Unable to get 2d context for resizeImageBitmap");n.drawImage(e,0,0);return n.getImageData(0,0,t,i).data}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i{this.onCanvasFocusObservable.notifyObservers(this)},this._onCanvasBlur=()=>{this.onCanvasBlurObservable.notifyObservers(this)},this._onCanvasContextMenu=e=>{this.disableContextMenu&&e.preventDefault()},e.addEventListener("focus",this._onCanvasFocus),e.addEventListener("blur",this._onCanvasBlur),e.addEventListener("contextmenu",this._onCanvasContextMenu),this._onBlur=()=>{this.disablePerformanceMonitorInBackground&&this._performanceMonitor.disable(),this._windowIsBackground=!0},this._onFocus=()=>{this.disablePerformanceMonitorInBackground&&this._performanceMonitor.enable(),this._windowIsBackground=!1},this._onCanvasPointerOut=t=>{document.elementFromPoint(t.clientX,t.clientY)!==e&&this.onCanvasPointerOutObservable.notifyObservers(t)};const t=this.getHostWindow();t&&"function"==typeof t.addEventListener&&(t.addEventListener("blur",this._onBlur),t.addEventListener("focus",this._onFocus)),e.addEventListener("pointerout",this._onCanvasPointerOut),this._creationOptions.doNotHandleTouchAction||this._disableTouchAction(),!f.audioEngine&&this._creationOptions.audioEngine&&f.AudioEngineFactory&&(f.audioEngine=f.AudioEngineFactory(this.getRenderingCanvas(),this.getAudioContext(),this.getAudioDestination())),(0,r.n5)()&&(this._onFullscreenChange=()=>{this.isFullscreen=!!document.fullscreenElement,this.isFullscreen&&this._pointerLockRequested&&e&&f._RequestPointerlock(e)},document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",this._onFullscreenChange,!1),this._onPointerLockChange=()=>{this.isPointerLock=document.pointerLockElement===e},document.addEventListener("pointerlockchange",this._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",this._onPointerLockChange,!1)),this.enableOfflineSupport=void 0!==f.OfflineProviderFactory,this._deterministicLockstep=!!this._creationOptions.deterministicLockstep,this._lockstepMaxSteps=this._creationOptions.lockstepMaxSteps||0,this._timeStep=this._creationOptions.timeStep||1/60}_verifyPointerLock(){var e;null===(e=this._onPointerLockChange)||void 0===e||e.call(this)}getAspectRatio(e,t=!1){const i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)}getScreenAspectRatio(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)}getRenderingCanvasClientRect(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null}getInputElementClientRect(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return 1e3*this._timeStep}generateMipMapsForCubemap(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)}}getDepthWrite(){return this._depthCullingState.depthMask}setDepthWrite(e){this._depthCullingState.depthMask=e}getStencilBuffer(){return this._stencilState.stencilTest}setStencilBuffer(e){this._stencilState.stencilTest=e}getStencilMask(){return this._stencilState.stencilMask}setStencilMask(e){this._stencilState.stencilMask=e}getStencilFunction(){return this._stencilState.stencilFunc}getStencilFunctionReference(){return this._stencilState.stencilFuncRef}getStencilFunctionMask(){return this._stencilState.stencilFuncMask}setStencilFunction(e){this._stencilState.stencilFunc=e}setStencilFunctionReference(e){this._stencilState.stencilFuncRef=e}setStencilFunctionMask(e){this._stencilState.stencilFuncMask=e}getStencilOperationFail(){return this._stencilState.stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilState.stencilOpDepthFail}getStencilOperationPass(){return this._stencilState.stencilOpStencilDepthPass}setStencilOperationFail(e){this._stencilState.stencilOpStencilFail=e}setStencilOperationDepthFail(e){this._stencilState.stencilOpDepthFail=e}setStencilOperationPass(e){this._stencilState.stencilOpStencilDepthPass=e}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)}getDepthFunction(){return this._depthCullingState.depthFunc}setDepthFunction(e){this._depthCullingState.depthFunc=e}setDepthFunctionToGreater(){this.setDepthFunction(516)}setDepthFunctionToGreaterOrEqual(){this.setDepthFunction(518)}setDepthFunctionToLess(){this.setDepthFunction(513)}setDepthFunctionToLessOrEqual(){this.setDepthFunction(515)}cacheStencilState(){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()}restoreStencilState(){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)}setDirectViewport(e,t,i,n){const s=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,n),s}scissorClear(e,t,i,n,s){this.enableScissor(e,t,i,n),this.clear(s,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,n){const s=this._gl;s.enable(s.SCISSOR_TEST),s.scissor(e,t,i,n)}disableScissor(){const e=this._gl;e.disable(e.SCISSOR_TEST)}_reportDrawCall(e=1){this._drawCalls.addCount(e,!1)}initWebVR(){throw(0,a.S)("WebVRCamera")}_prepareVRComponent(){}_connectVREvents(e,t){}_submitVRFrame(){}disableVR(){}isVRPresenting(){return!1}_requestVRFrame(){}_loadFileAsync(e,t,i){return new Promise(((n,s)=>{this._loadFile(e,(e=>{n(e)}),void 0,t,i,((e,t)=>{s(t)}))}))}getVertexShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}setDepthStencilTexture(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))}setTextureFromPostProcess(e,t,i){var n;let s=null;t&&(t._forcedOutputTexture?s=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(s=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,null!==(n=null==s?void 0:s.texture)&&void 0!==n?n:null,i)}setTextureFromPostProcessOutput(e,t,i){var n,s;this._bindTexture(e,null!==(s=null===(n=null==t?void 0:t._outputTexture)||void 0===n?void 0:n.texture)&&void 0!==s?s:null,i)}_rebuildBuffers(){for(const e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries(),e._rebuildTextures();for(const e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries(),e._rebuildTextures();super._rebuildBuffers()}_renderFrame(){for(let e=0;e0?this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this.isVRPresenting()?this._requestVRFrame():this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()):this._renderingQueueLaunched=!1}_renderViews(){return!1}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&f._RequestFullscreen(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&f._ExitFullscreen()}enterPointerlock(){this._renderingCanvas&&f._RequestPointerlock(this._renderingCanvas)}exitPointerlock(){f._ExitPointerlock()}beginFrame(){this._measureFps(),this.onBeginFrameObservable.notifyObservers(this),super.beginFrame()}endFrame(){super.endFrame(),this._submitVRFrame(),this.onEndFrameObservable.notifyObservers(this)}resize(e=!1){this.isVRPresenting()||super.resize(e)}setSize(e,t,i=!1){if(!this._renderingCanvas)return!1;if(!super.setSize(e,t,i))return!1;if(this.scenes){for(let e=0;e1&&s){const t=this.createTransformFeedback();this.bindTransformFeedback(t),this.setTranformFeedbackVaryings(r,s),e.transformFeedback=t}return n.linkProgram(r),this.webGLVersion>1&&s&&this.bindTransformFeedback(null),e.context=n,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),r}_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)}))}))}))}getRenderPassNames(){return this._renderPassNames}getCurrentRenderPassName(){return this._renderPassNames[this.currentRenderPassId]}createRenderPassId(e){const t=++f._RenderPassIdCounter;return this._renderPassNames[t]=null!=e?e:"NONAME",t}releaseRenderPassId(e){this._renderPassNames[e]=void 0;for(let t=0;t{this._rescalePostProcess.onApply=function(t){t._bindTexture("textureSampler",e)};let o=i;o||(o=this.scenes[this.scenes.length-1]),o.postProcessManager.directRender([this._rescalePostProcess],r,!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(r),r.dispose(),s&&s()})))}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}_measureFps(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0}wrapWebGLTexture(e,t=!1,i=3){const n=new p.B(e,this._gl),r=new s.l(this,s.S.Unknown,!0);return r._hardwareTexture=n,r.isReady=!0,r.useMipMaps=t,this.updateTextureSamplingMode(i,r),r}_uploadImageToTexture(e,t,i=0,n=0){const s=this._gl,r=this._getWebGLTextureType(e.type),o=this._getInternalFormat(e.format),a=this._getRGBABufferInternalSizedFormat(e.type,o),l=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);let h=s.TEXTURE_2D;e.isCube&&(h=s.TEXTURE_CUBE_MAP_POSITIVE_X+i),s.texImage2D(h,n,a,o,r,t),this._bindTextureDirectly(l,null,!0)}updateTextureComparisonFunction(e,t){if(1===this.webGLVersion)return void u.Y.Error("WebGL 1 does not support texture comparison.");const i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),0===t?(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),0===t?(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),e._comparisonFunction=t}createInstancesBuffer(e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create instance buffer");const i=new d.M(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}_clientWaitAsync(e,t=0,i=10){const n=this._gl;return new Promise(((s,r)=>{const o=()=>{const a=n.clientWaitSync(e,t,0);a!=n.WAIT_FAILED?a!=n.TIMEOUT_EXPIRED?s():setTimeout(o,i):r()};o()}))}_readPixelsAsync(e,t,i,n,s,r,o){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const a=this._gl,l=a.createBuffer();a.bindBuffer(a.PIXEL_PACK_BUFFER,l),a.bufferData(a.PIXEL_PACK_BUFFER,o.byteLength,a.STREAM_READ),a.readPixels(e,t,i,n,s,r,0),a.bindBuffer(a.PIXEL_PACK_BUFFER,null);const h=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);return h?(a.flush(),this._clientWaitAsync(h,0,10).then((()=>(a.deleteSync(h),a.bindBuffer(a.PIXEL_PACK_BUFFER,l),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,o),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),a.deleteBuffer(l),o)))):null}dispose(){for(this.hideLoadingUI(),this.onNewSceneAddedObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(this._rescalePostProcess&&this._rescalePostProcess.dispose();this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();1===o.l.Instances.length&&f.audioEngine&&(f.audioEngine.dispose(),f.audioEngine=null),this.disableVR();const e=this.getHostWindow();e&&"function"==typeof e.removeEventListener&&(e.removeEventListener("blur",this._onBlur),e.removeEventListener("focus",this._onFocus)),this._renderingCanvas&&(this._renderingCanvas.removeEventListener("focus",this._onCanvasFocus),this._renderingCanvas.removeEventListener("blur",this._onCanvasBlur),this._renderingCanvas.removeEventListener("pointerout",this._onCanvasPointerOut),this._renderingCanvas.removeEventListener("contextmenu",this._onCanvasContextMenu)),(0,r.n5)()&&(document.removeEventListener("fullscreenchange",this._onFullscreenChange),document.removeEventListener("mozfullscreenchange",this._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",this._onFullscreenChange),document.removeEventListener("msfullscreenchange",this._onFullscreenChange),document.removeEventListener("pointerlockchange",this._onPointerLockChange),document.removeEventListener("mspointerlockchange",this._onPointerLockChange),document.removeEventListener("mozpointerlockchange",this._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",this._onPointerLockChange)),super.dispose();const t=o.l.Instances.indexOf(this);t>=0&&o.l.Instances.splice(t,1),f.Instances.length||o.l.OnEnginesDisposedObservable.notifyObservers(this),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}_disableTouchAction(){this._renderingCanvas&&this._renderingCanvas.setAttribute&&(this._renderingCanvas.setAttribute("touch-action","none"),this._renderingCanvas.style.touchAction="none",this._renderingCanvas.style.webkitTapHighlightColor="transparent")}displayLoadingUI(){if(!(0,r.CG)())return;const e=this.loadingScreen;e&&e.displayLoadingUI()}hideLoadingUI(){if(!(0,r.CG)())return;const e=this._loadingScreen;e&&e.hideLoadingUI()}get loadingScreen(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=f.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen}set loadingScreen(e){this._loadingScreen=e}set loadingUIText(e){this.loadingScreen.loadingUIText=e}set loadingUIBackgroundColor(e){this.loadingScreen.loadingUIBackgroundColor=e}createVideoElement(e){return document.createElement("video")}static _RequestPointerlock(e){if(e.requestPointerLock){const t=e.requestPointerLock();t instanceof Promise?t.then((()=>{e.focus()})).catch((()=>{})):e.focus()}}static _ExitPointerlock(){document.exitPointerLock&&document.exitPointerLock()}static _RequestFullscreen(e){const t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}static _ExitFullscreen(){const e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}getFontOffset(e){const t=document.createElement("span");t.innerHTML="Hg",t.setAttribute("style",`font: ${e} !important`);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 s=0,r=0;try{r=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",s=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(n)}return{ascent:s,height:r,descent:r-s}}}f.ALPHA_DISABLE=0,f.ALPHA_ADD=1,f.ALPHA_COMBINE=2,f.ALPHA_SUBTRACT=3,f.ALPHA_MULTIPLY=4,f.ALPHA_MAXIMIZED=5,f.ALPHA_ONEONE=6,f.ALPHA_PREMULTIPLIED=7,f.ALPHA_PREMULTIPLIED_PORTERDUFF=8,f.ALPHA_INTERPOLATE=9,f.ALPHA_SCREENMODE=10,f.DELAYLOADSTATE_NONE=0,f.DELAYLOADSTATE_LOADED=1,f.DELAYLOADSTATE_LOADING=2,f.DELAYLOADSTATE_NOTLOADED=4,f.NEVER=512,f.ALWAYS=519,f.LESS=513,f.EQUAL=514,f.LEQUAL=515,f.GREATER=516,f.GEQUAL=518,f.NOTEQUAL=517,f.KEEP=7680,f.REPLACE=7681,f.INCR=7682,f.DECR=7683,f.INVERT=5386,f.INCR_WRAP=34055,f.DECR_WRAP=34056,f.TEXTURE_CLAMP_ADDRESSMODE=0,f.TEXTURE_WRAP_ADDRESSMODE=1,f.TEXTURE_MIRROR_ADDRESSMODE=2,f.TEXTUREFORMAT_ALPHA=0,f.TEXTUREFORMAT_LUMINANCE=1,f.TEXTUREFORMAT_LUMINANCE_ALPHA=2,f.TEXTUREFORMAT_RGB=4,f.TEXTUREFORMAT_RGBA=5,f.TEXTUREFORMAT_RED=6,f.TEXTUREFORMAT_R=6,f.TEXTUREFORMAT_RG=7,f.TEXTUREFORMAT_RED_INTEGER=8,f.TEXTUREFORMAT_R_INTEGER=8,f.TEXTUREFORMAT_RG_INTEGER=9,f.TEXTUREFORMAT_RGB_INTEGER=10,f.TEXTUREFORMAT_RGBA_INTEGER=11,f.TEXTURETYPE_UNSIGNED_BYTE=0,f.TEXTURETYPE_UNSIGNED_INT=0,f.TEXTURETYPE_FLOAT=1,f.TEXTURETYPE_HALF_FLOAT=2,f.TEXTURETYPE_BYTE=3,f.TEXTURETYPE_SHORT=4,f.TEXTURETYPE_UNSIGNED_SHORT=5,f.TEXTURETYPE_INT=6,f.TEXTURETYPE_UNSIGNED_INTEGER=7,f.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,f.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,f.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,f.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,f.TEXTURETYPE_UNSIGNED_INT_24_8=12,f.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,f.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,f.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,f.TEXTURE_NEAREST_SAMPLINGMODE=1,f.TEXTURE_BILINEAR_SAMPLINGMODE=2,f.TEXTURE_TRILINEAR_SAMPLINGMODE=3,f.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,f.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,f.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,f.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,f.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,f.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,f.TEXTURE_NEAREST_LINEAR=7,f.TEXTURE_NEAREST_NEAREST=1,f.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,f.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,f.TEXTURE_LINEAR_LINEAR=2,f.TEXTURE_LINEAR_NEAREST=12,f.TEXTURE_EXPLICIT_MODE=0,f.TEXTURE_SPHERICAL_MODE=1,f.TEXTURE_PLANAR_MODE=2,f.TEXTURE_CUBIC_MODE=3,f.TEXTURE_PROJECTION_MODE=4,f.TEXTURE_SKYBOX_MODE=5,f.TEXTURE_INVCUBIC_MODE=6,f.TEXTURE_EQUIRECTANGULAR_MODE=7,f.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,f.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,f.SCALEMODE_FLOOR=1,f.SCALEMODE_NEAREST=2,f.SCALEMODE_CEILING=3,f._RescalePostProcessFactory=null,f._RenderPassIdCounter=0},5953:function(e,t,i){i.d(t,{l:function(){return s}});var n=i(8139);class s{static get LastCreatedEngine(){return 0===this.Instances.length?null:this.Instances[this.Instances.length-1]}static get LastCreatedScene(){return this._LastCreatedScene}}s.Instances=new Array,s.OnEnginesDisposedObservable=new n.y$,s._LastCreatedScene=null,s.UseFallbackTexture=!0,s.FallbackTexture=""},1716:function(e,t,i){i.d(t,{Z:function(){return n}});class n{static SetMatrixPrecision(e){if(n.MatrixTrackPrecisionChange=!1,e&&!n.MatrixUse64Bits&&n.MatrixTrackedMatrices)for(let t=0;t=h.Fz.MouseWheelX&&t.inputIndex<=h.Fz.MouseWheelZ?n.kD.POINTERWHEEL:n.kD.POINTERMOVE;let a;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,o)),e?(a=new n.R5(o,t,e),this._setRayOnPointerInfo(e,t)):(a=new n.R5(o,t,null,this),this._movePointerInfo=a),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(a,o)}_setRayOnPointerInfo(e,t){const i=this._scene;e&&i._pickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,o.y3.Identity(),i.activeCamera)))}_addCameraPointerObserver(e,t){return this._cameraObserverCount++,this._scene.onPointerObservable.add(e,t)}_removeCameraPointerObserver(e){return this._cameraObserverCount--,this._scene.onPointerObservable.remove(e)}_checkForPicking(){return!!(this._scene.onPointerObservable.observers.length>this._cameraObserverCount||this._scene.onPointerPick)}_checkPrePointerObservable(e,t,i){const s=this._scene,r=new n.FV(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(r.originalPickingInfo=e,r.ray=e.ray,e.originMesh&&(r.nearInteractionPickingInfo=e)),s.onPrePointerObservable.notifyObservers(r,i),!!r.skipOnPointerObservable}_pickMove(e){const t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){const n=i.getEngine().getInputElement();if(null==e?void 0: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=h.Fz.Move,this._checkPrePointerObservable(e,i,n.kD.POINTERMOVE)||this._processPointerMove(e,i)}simulatePointerDown(e,t){const i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,this._checkPrePointerObservable(e,i,n.kD.POINTERDOWN)||this._processPointerDown(e,i)}_processPointerDown(e,t){const i=this._scene;if(null==e?void 0:e.pickedMesh){this._pickedDownMesh=e.pickedMesh;const n=e.pickedMesh._getActionManagerForTrigger();if(n){if(n.hasPickTriggers)switch(n.processTrigger(5,a.V.CreateNew(e.pickedMesh,t)),t.button){case 0:n.processTrigger(2,a.V.CreateNew(e.pickedMesh,t));break;case 1:n.processTrigger(4,a.V.CreateNew(e.pickedMesh,t));break;case 2:n.processTrigger(3,a.V.CreateNew(e.pickedMesh,t))}n.hasSpecificTrigger(8)&&window.setTimeout((()=>{const e=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,(e=>e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(8)&&e===this._pickedDownMesh),!1,i.cameraToUseForPointers);(null==e?void 0:e.pickedMesh)&&n&&0!==this._totalPointersPressed&&Date.now()-this._startingPointerTime>p.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,n.processTrigger(8,a.V.CreateNew(e.pickedMesh,t)))}),p.LongPressDelay)}}else for(const n of i._pointerDownStage)e=n.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let s;const r=n.kD.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,r),s=new n.R5(r,t,e),this._setRayOnPointerInfo(e,t)):s=new n.R5(r,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(s,r)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){const s=new PointerEvent("pointerup",t);s.inputIndex=h.Fz.Move;const r=new u;i?r.doubleClick=!0:r.singleClick=!0,this._checkPrePointerObservable(e,s,n.kD.POINTERUP)||this._processPointerUp(e,s,r)}_processPointerUp(e,t,i){const s=this._scene;if(null==e?void 0:e.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(s.onPointerPick&&s.onPointerPick(t,e),i.singleClick&&!i.ignore&&s.onPointerObservable.observers.length>this._cameraObserverCount)){const i=n.kD.POINTERPICK,r=new n.R5(i,t,e);this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,i)}const r=e.pickedMesh._getActionManagerForTrigger();if(r&&!i.ignore){r.processTrigger(7,a.V.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&r.processTrigger(1,a.V.CreateNew(e.pickedMesh,t,e));const n=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&n&&n.processTrigger(6,a.V.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(const n of s._pointerUpStage)e=n.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const e=this._pickedDownMesh._getActionManagerForTrigger(16);e&&e.processTrigger(16,a.V.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){const r=new n.R5(n.kD.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(r,n.kD.POINTERUP),s.onPointerUp&&s.onPointerUp(t,e,n.kD.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let r=0;if(i.singleClick?r=n.kD.POINTERTAP:i.doubleClick&&(r=n.kD.POINTERDOUBLETAP),r){const i=new n.R5(r,t,e);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(r)&&s.onPointerObservable.notifyObservers(i,r)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,o=null){const d=this._scene,f=d.getEngine();o||(o=f.getInputElement()),this._alreadyAttached&&this.detachControl(),o&&(this._alreadyAttachedTo=o),this._deviceSourceManager=new c.U(f),this._initActionManager=e=>{if(!this._meshPickProceed){const t=d.skipPointerUpPicking||0===d._registeredActions&&!this._checkForPicking()&&!d.onPointerUp?null:d.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,d.pointerUpPredicate,d.pointerUpFastCheck,d.cameraToUseForPointers);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>p.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=n.kD.POINTERTAP,s=new n.R5(i,t,this._currentPickResult);d.onPointerObservable.hasObservers()&&d.onPointerObservable.hasSpecificMask(i)&&d.onPointerObservable.notifyObservers(s,i),this._delayedClicks[e]=null}},this._initClickEvent=(e,t,i,r)=>{var o,a;const l=new u;this._currentPickResult=null;let h=null,c=e.hasSpecificMask(n.kD.POINTERPICK)||t.hasSpecificMask(n.kD.POINTERPICK)||e.hasSpecificMask(n.kD.POINTERTAP)||t.hasSpecificMask(n.kD.POINTERTAP)||e.hasSpecificMask(n.kD.POINTERDOUBLETAP)||t.hasSpecificMask(n.kD.POINTERDOUBLETAP);!c&&s.O&&(h=this._initActionManager(h,l),h&&(c=h.hasPickTriggers));let d=!1;if(c){const c=i.button;if(l.hasSwiped=this._isPointerSwiping(),!l.hasSwiped){let u=!p.ExclusiveDoubleClickMode;if(u||(u=!e.hasSpecificMask(n.kD.POINTERDOUBLETAP)&&!t.hasSpecificMask(n.kD.POINTERDOUBLETAP),u&&!s.O.HasSpecificTrigger(6)&&(h=this._initActionManager(h,l),h&&(u=!h.hasSpecificTrigger(6)))),u)(Date.now()-this._previousStartingPointerTime>p.DoubleClickDelay||c!==this._previousButtonPressed)&&(l.singleClick=!0,r(l,this._currentPickResult),d=!0);else{const e={evt:i,clickInfo:l,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,c,l,r),p.DoubleClickDelay)};this._delayedClicks[c]=e}let f=e.hasSpecificMask(n.kD.POINTERDOUBLETAP)||t.hasSpecificMask(n.kD.POINTERDOUBLETAP);!f&&s.O.HasSpecificTrigger(6)&&(h=this._initActionManager(h,l),h&&(f=h.hasSpecificTrigger(6))),f&&(c===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(this._updatePointerPosition(e),this._isSwiping||-1===this._swipeButtonPressed||(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>p.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>p.DragMovementThreshold),f.isPointerLock&&f._verifyPointerLock(),this._checkPrePointerObservable(null,e,e.inputIndex>=h.Fz.MouseWheelX&&e.inputIndex<=h.Fz.MouseWheelZ?n.kD.POINTERWHEEL:n.kD.POINTERMOVE))return;if(!d.cameraToUseForPointers&&!d.activeCamera)return;if(d.skipPointerMovePicking)return void this._processPointerMove(new r.p,e);d.pointerMovePredicate||(d.pointerMovePredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||d.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!d.cameraToUseForPointers||0!=(d.cameraToUseForPointers.layerMask&e.layerMask)));const t=d._registeredActions>0||d.constantlyUpdateMeshUnderPointer?this._pickMove(e):null;this._processPointerMove(t,e)},this._onPointerDown=e=>{var t;if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,p.ExclusiveDoubleClickMode)for(let s=0;se.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!d.cameraToUseForPointers||0!=(d.cameraToUseForPointers.layerMask&e.layerMask))),this._pickedDownMesh=null,i=d.skipPointerDownPicking||0===d._registeredActions&&!this._checkForPicking()&&!d.onPointerDown?new r.p:d.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,d.pointerDownPredicate,d.pointerDownFastCheck,d.cameraToUseForPointers),this._processPointerDown(i,e)},this._onPointerUp=e=>{0!==this._totalPointersPressed&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(e),d.preventDefaultOnPointerUp&&o&&(e.preventDefault(),o.focus()),this._initClickEvent(d.onPrePointerObservable,d.onPointerObservable,e,((t,i)=>{if(d.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!t.ignore)){if(this._checkPrePointerObservable(null,e,n.kD.POINTERUP))return void(this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1));t.hasSwiped||(t.singleClick&&d.onPrePointerObservable.hasSpecificMask(n.kD.POINTERTAP)&&this._checkPrePointerObservable(null,e,n.kD.POINTERTAP)&&(this._skipPointerTap=!0),t.doubleClick&&d.onPrePointerObservable.hasSpecificMask(n.kD.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,e,n.kD.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}this._pointerCaptures[e.pointerId]?(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1),(d.cameraToUseForPointers||d.activeCamera)&&(d.pointerUpPredicate||(d.pointerUpPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!d.cameraToUseForPointers||0!=(d.cameraToUseForPointers.layerMask&e.layerMask))),!this._meshPickProceed&&(s.O&&s.O.HasTriggers||this._checkForPicking()||d.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=l.OG.KEYDOWN;if(d.onPreKeyboardObservable.hasObservers()){const i=new l.WZ(t,e);if(d.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(d.onKeyboardObservable.hasObservers()){const i=new l.NG(t,e);d.onKeyboardObservable.notifyObservers(i,t)}d.actionManager&&d.actionManager.processTrigger(14,a.V.CreateNewFromScene(d,e))},this._onKeyUp=e=>{const t=l.OG.KEYUP;if(d.onPreKeyboardObservable.hasObservers()){const i=new l.WZ(t,e);if(d.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(d.onKeyboardObservable.hasObservers()){const i=new l.NG(t,e);d.onKeyboardObservable.notifyObservers(i,t)}d.actionManager&&d.actionManager.processTrigger(15,a.V.CreateNewFromScene(d,e))},this._deviceSourceManager.onDeviceConnectedObservable.add((n=>{n.deviceType===h.Yi.Mouse?n.onInputChangedObservable.add((s=>{s.inputIndex===h.Fz.LeftClick||s.inputIndex===h.Fz.MiddleClick||s.inputIndex===h.Fz.RightClick||s.inputIndex===h.Fz.BrowserBack||s.inputIndex===h.Fz.BrowserForward?t&&1===n.getInput(s.inputIndex)?this._onPointerDown(s):e&&0===n.getInput(s.inputIndex)&&this._onPointerUp(s):i&&(s.inputIndex===h.Fz.Move?this._onPointerMove(s):s.inputIndex!==h.Fz.MouseWheelX&&s.inputIndex!==h.Fz.MouseWheelY&&s.inputIndex!==h.Fz.MouseWheelZ||this._onPointerMove(s))})):n.deviceType===h.Yi.Touch?n.onInputChangedObservable.add((s=>{s.inputIndex===h.Fz.LeftClick&&(t&&1===n.getInput(s.inputIndex)?(this._onPointerDown(s),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&0===n.getInput(s.inputIndex)&&(this._onPointerUp(s),0===this._totalPointersPressed&&(this._isMultiTouchGesture=!1))),i&&s.inputIndex===h.Fz.Move&&this._onPointerMove(s)})):n.deviceType===h.Yi.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 s=this._meshUnderPointerId[t];let r;s&&(r=s._getActionManagerForTrigger(10),r&&r.processTrigger(10,a.V.CreateNew(s,n,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,r=e._getActionManagerForTrigger(9),r&&r.processTrigger(9,a.V.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]}}p.DragMovementThreshold=10,p.LongPressDelay=500,p.DoubleClickDelay=300,p.ExclusiveDoubleClickMode=!1},183:function(e,t,i){i.d(t,{m:function(){return n}});class n{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}n.FALLOFF_DEFAULT=0,n.FALLOFF_PHYSICAL=1,n.FALLOFF_GLTF=2,n.FALLOFF_STANDARD=3,n.LIGHTMAP_DEFAULT=0,n.LIGHTMAP_SPECULAR=1,n.LIGHTMAP_SHADOWSONLY=2,n.INTENSITYMODE_AUTOMATIC=0,n.INTENSITYMODE_LUMINOUSPOWER=1,n.INTENSITYMODE_LUMINOUSINTENSITY=2,n.INTENSITYMODE_ILLUMINANCE=3,n.INTENSITYMODE_LUMINANCE=4,n.LIGHTTYPEID_POINTLIGHT=0,n.LIGHTTYPEID_DIRECTIONALLIGHT=1,n.LIGHTTYPEID_SPOTLIGHT=2,n.LIGHTTYPEID_HEMISPHERICLIGHT=3},5458:function(e,t,i){i.d(t,{Z:function(){return n}});class n{static get ForceFullSceneLoadingForIncremental(){return n._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){n._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return n._ShowLoadingScreen}static set ShowLoadingScreen(e){n._ShowLoadingScreen=e}static get loggingLevel(){return n._LoggingLevel}static set loggingLevel(e){n._LoggingLevel=e}static get CleanBoneMatrixWeights(){return n._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){n._CleanBoneMatrixWeights=e}}n._ForceFullSceneLoadingForIncremental=!1,n._ShowLoadingScreen=!0,n._CleanBoneMatrixWeights=!1,n._LoggingLevel=0},4679:function(e,t,i){i.d(t,{S:function(){return n},l:function(){return o}});var n,s=i(8139),r=i(2931);!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"}(n||(n={}));class o extends r.a{get useMipMaps(){return this.generateMipMaps}set useMipMaps(e){this.generateMipMaps=e}get uniqueId(){return this._uniqueId}_setUniqueId(e){this._uniqueId=e}getEngine(){return this._engine}get source(){return this._source}constructor(e,t,i=!1){super(),this.isReady=!1,this.isCube=!1,this.is3D=!1,this.is2DArray=!1,this.isMultiview=!1,this.url="",this.generateMipMaps=!1,this.samples=0,this.type=-1,this.format=-1,this.onLoadedObservable=new s.y$,this.onErrorObservable=new s.y$,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=n.Unknown,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._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._engine=e,this._source=t,this._uniqueId=o._Counter++,i||(this._hardwareTexture=e._createHardwareTexture())}incrementReferences(){this._references++}updateSize(e,t,i=1){this._engine.updateTextureDimensions(this,e,t,i),this.width=e,this.height=t,this.depth=i,this.baseWidth=e,this.baseHeight=t,this.baseDepth=i,this._size=e*t*i}_rebuild(){var e;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 t;switch(this.source){case n.Temp:break;case n.Url:return void(t=this._engine.createTexture(null!==(e=this._originalUrl)&&void 0!==e?e: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 n.Raw:t=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,void 0,this._useSRGBBuffer),t._swapAndDie(this,!1),this.isReady=!0;break;case n.Raw3D:t=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),t._swapAndDie(this,!1),this.isReady=!0;break;case n.Raw2DArray:t=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),t._swapAndDie(this,!1),this.isReady=!0;break;case n.Dynamic:t=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),t._swapAndDie(this,!1),this._engine.updateDynamicTexture(this,this._engine.getRenderingCanvas(),this.invertY,void 0,void 0,!0);break;case n.Cube:return void(t=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,(()=>{t._swapAndDie(this,!1),this.isReady=!0}),null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer));case n.CubeRaw:t=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),t._swapAndDie(this,!1),this.isReady=!0;break;case n.CubeRawRGBD:return;case n.CubePrefiltered:return t=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(t._sphericalPolynomial=this._sphericalPolynomial)}}_swapAndDie(e,t=!0){var i;null===(i=this._hardwareTexture)||void 0===i||i.setUsage(e._source,this.generateMipMaps,this.isCube,this.width,this.height),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 n=this._engine.getLoadedTexturesCache();let s=n.indexOf(this);-1!==s&&n.splice(s,1),s=n.indexOf(e),-1===s&&n.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),0===this._references&&(this._engine._releaseTexture(this),this._hardwareTexture=null)}}o._Counter=0},2931:function(e,t,i){i.d(t,{a:function(){return n}});class n{get wrapU(){return this._cachedWrapU}set wrapU(e){this._cachedWrapU=e}get wrapV(){return this._cachedWrapV}set wrapV(e){this._cachedWrapV=e}get wrapR(){return this._cachedWrapR}set wrapR(e){this._cachedWrapR=e}get anisotropicFilteringLevel(){return this._cachedAnisotropicFilteringLevel}set anisotropicFilteringLevel(e){this._cachedAnisotropicFilteringLevel=e}get comparisonFunction(){return this._comparisonFunction}set comparisonFunction(e){this._comparisonFunction=e}get useMipMaps(){return this._useMipMaps}set useMipMaps(e){this._useMipMaps=e}constructor(){this.samplingMode=-1,this._useMipMaps=!0,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this._comparisonFunction=0}setParameters(e=1,t=1,i=1,n=1,s=2,r=0){return this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=i,this._cachedAnisotropicFilteringLevel=n,this.samplingMode=s,this._comparisonFunction=r,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}}},6181:function(e,t,i){function n(e){-1===e.indexOf("vClipPlane")&&e.push("vClipPlane"),-1===e.indexOf("vClipPlane2")&&e.push("vClipPlane2"),-1===e.indexOf("vClipPlane3")&&e.push("vClipPlane3"),-1===e.indexOf("vClipPlane4")&&e.push("vClipPlane4"),-1===e.indexOf("vClipPlane5")&&e.push("vClipPlane5"),-1===e.indexOf("vClipPlane6")&&e.push("vClipPlane6")}function s(e,t,i){var n,s,r,o,a,l;const h=!!(null!==(n=e.clipPlane)&&void 0!==n?n:t.clipPlane),c=!!(null!==(s=e.clipPlane2)&&void 0!==s?s:t.clipPlane2),d=!!(null!==(r=e.clipPlane3)&&void 0!==r?r:t.clipPlane3),u=!!(null!==(o=e.clipPlane4)&&void 0!==o?o:t.clipPlane4),p=!!(null!==(a=e.clipPlane5)&&void 0!==a?a:t.clipPlane5),f=!!(null!==(l=e.clipPlane6)&&void 0!==l?l:t.clipPlane6);h&&i.push("#define CLIPPLANE"),c&&i.push("#define CLIPPLANE2"),d&&i.push("#define CLIPPLANE3"),u&&i.push("#define CLIPPLANE4"),p&&i.push("#define CLIPPLANE5"),f&&i.push("#define CLIPPLANE6")}function r(e,t,i){var n,s,r,o,a,l;let h=!1;const c=!!(null!==(n=e.clipPlane)&&void 0!==n?n:t.clipPlane),d=!!(null!==(s=e.clipPlane2)&&void 0!==s?s:t.clipPlane2),u=!!(null!==(r=e.clipPlane3)&&void 0!==r?r:t.clipPlane3),p=!!(null!==(o=e.clipPlane4)&&void 0!==o?o:t.clipPlane4),f=!!(null!==(a=e.clipPlane5)&&void 0!==a?a:t.clipPlane5),_=!!(null!==(l=e.clipPlane6)&&void 0!==l?l:t.clipPlane6);return i.CLIPPLANE!==c&&(i.CLIPPLANE=c,h=!0),i.CLIPPLANE2!==d&&(i.CLIPPLANE2=d,h=!0),i.CLIPPLANE3!==u&&(i.CLIPPLANE3=u,h=!0),i.CLIPPLANE4!==p&&(i.CLIPPLANE4=p,h=!0),i.CLIPPLANE5!==f&&(i.CLIPPLANE5=f,h=!0),i.CLIPPLANE6!==_&&(i.CLIPPLANE6=_,h=!0),h}function o(e,t,i){var n,s,r,o,l,h;let c=null!==(n=t.clipPlane)&&void 0!==n?n:i.clipPlane;a(e,"vClipPlane",c),c=null!==(s=t.clipPlane2)&&void 0!==s?s:i.clipPlane2,a(e,"vClipPlane2",c),c=null!==(r=t.clipPlane3)&&void 0!==r?r:i.clipPlane3,a(e,"vClipPlane3",c),c=null!==(o=t.clipPlane4)&&void 0!==o?o:i.clipPlane4,a(e,"vClipPlane4",c),c=null!==(l=t.clipPlane5)&&void 0!==l?l:i.clipPlane5,a(e,"vClipPlane5",c),c=null!==(h=t.clipPlane6)&&void 0!==h?h:i.clipPlane6,a(e,"vClipPlane6",c)}function a(e,t,i){i&&e.setFloat4(t,i.normal.x,i.normal.y,i.normal.z,i.d)}i.d(t,{AN:function(){return r},an:function(){return o},lK:function(){return s},qx:function(){return n}})},4839:function(e,t,i){i.d(t,{U:function(){return o}});var n=i(1069),s=i(8137),r=i(2922);class o{constructor(){this._dirty=!0,this._tempColor=new r.HE(0,0,0,0),this._globalCurve=new r.HE(0,0,0,0),this._highlightsCurve=new r.HE(0,0,0,0),this._midtonesCurve=new r.HE(0,0,0,0),this._shadowsCurve=new r.HE(0,0,0,0),this._positiveCurve=new r.HE(0,0,0,0),this._negativeCurve=new r.HE(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}get globalHue(){return this._globalHue}set globalHue(e){this._globalHue=e,this._dirty=!0}get globalDensity(){return this._globalDensity}set globalDensity(e){this._globalDensity=e,this._dirty=!0}get globalSaturation(){return this._globalSaturation}set globalSaturation(e){this._globalSaturation=e,this._dirty=!0}get globalExposure(){return this._globalExposure}set globalExposure(e){this._globalExposure=e,this._dirty=!0}get highlightsHue(){return this._highlightsHue}set highlightsHue(e){this._highlightsHue=e,this._dirty=!0}get highlightsDensity(){return this._highlightsDensity}set highlightsDensity(e){this._highlightsDensity=e,this._dirty=!0}get highlightsSaturation(){return this._highlightsSaturation}set highlightsSaturation(e){this._highlightsSaturation=e,this._dirty=!0}get highlightsExposure(){return this._highlightsExposure}set highlightsExposure(e){this._highlightsExposure=e,this._dirty=!0}get midtonesHue(){return this._midtonesHue}set midtonesHue(e){this._midtonesHue=e,this._dirty=!0}get midtonesDensity(){return this._midtonesDensity}set midtonesDensity(e){this._midtonesDensity=e,this._dirty=!0}get midtonesSaturation(){return this._midtonesSaturation}set midtonesSaturation(e){this._midtonesSaturation=e,this._dirty=!0}get midtonesExposure(){return this._midtonesExposure}set midtonesExposure(e){this._midtonesExposure=e,this._dirty=!0}get shadowsHue(){return this._shadowsHue}set shadowsHue(e){this._shadowsHue=e,this._dirty=!0}get shadowsDensity(){return this._shadowsDensity}set shadowsDensity(e){this._shadowsDensity=e,this._dirty=!0}get shadowsSaturation(){return this._shadowsSaturation}set shadowsSaturation(e){this._shadowsSaturation=e,this._dirty=!0}get shadowsExposure(){return this._shadowsExposure}set shadowsExposure(e){this._shadowsExposure=e,this._dirty=!0}getClassName(){return"ColorCurves"}static Bind(e,t,i="vCameraColorCurvePositive",n="vCameraColorCurveNeutral",s="vCameraColorCurveNegative"){e._dirty&&(e._dirty=!1,e._getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e._getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e._getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e._getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(n,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(s,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}static PrepareUniforms(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}_getColorGradingDataToRef(e,t,i,n,s){null!=e&&(e=o._Clamp(e,0,360),t=o._Clamp(t,-100,100),i=o._Clamp(i,-100,100),n=o._Clamp(n,-100,100),t=o._ApplyColorGradingSliderNonlinear(t),t*=.5,n=o._ApplyColorGradingSliderNonlinear(n),t<0&&(t*=-1,e=(e+180)%360),o._FromHSBToRef(e,t,50+.25*n,s),s.scaleToRef(2,s),s.a=1+.01*i)}static _ApplyColorGradingSliderNonlinear(e){e/=100;let t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100,t}static _FromHSBToRef(e,t,i,n){let s=o._Clamp(e,0,360);const r=o._Clamp(t/100,0,1),a=o._Clamp(i/100,0,1);if(0===r)n.r=a,n.g=a,n.b=a;else{s/=60;const e=Math.floor(s),t=s-e,i=a*(1-r),o=a*(1-r*t),l=a*(1-r*(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 s.p4.Clone((()=>new o),this)}serialize(){return s.p4.Serialize(this)}static Parse(e){return s.p4.Parse((()=>new o),e,null,null)}}(0,n.gn)([(0,s.qC)()],o.prototype,"_globalHue",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_globalDensity",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_globalSaturation",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_globalExposure",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_highlightsHue",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_highlightsDensity",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_highlightsSaturation",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_highlightsExposure",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_midtonesHue",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_midtonesDensity",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_midtonesSaturation",void 0),(0,n.gn)([(0,s.qC)()],o.prototype,"_midtonesExposure",void 0),s.p4._ColorCurvesParser=o.Parse},7050:function(e,t,i){i.d(t,{q:function(){return n}});class n{static IsWrapper(e){return void 0===e.getPipelineContext}static GetEffect(e){return void 0===e.getPipelineContext?e.effect:e}constructor(e,t=!0){this.effect=null,this.defines=null,this.drawContext=e.createDrawContext(),t&&(this.materialContext=e.createMaterialContext())}setEffect(e,t,i=!0){var n;this.effect=e,void 0!==t&&(this.defines=t),i&&(null===(n=this.drawContext)||void 0===n||n.reset())}dispose(){var e;null===(e=this.drawContext)||void 0===e||e.dispose()}}},4442:function(e,t,i){i.d(t,{Q:function(){return h}});var n=i(8139),s=i(1102),r=i(658),o=i(3525),a=i(1206),l=i(475);class h{static get ShadersRepository(){return a.v.ShadersRepository}static set ShadersRepository(e){a.v.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new n.y$),this._onBindObservable}constructor(e,t,i,r=null,c,d=null,u=null,p=null,f=null,_,m="",g=l.x.GLSL){var v,T,S;let E;this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new n.y$,this.onErrorObservable=new n.y$,this._onBindObservable=null,this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!1,this._wasPreviouslyUsingInstances=null,this._isDisposed=!1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this.name=e,this._key=m;let x,b,C=null;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=null!==(v=e.shaderLanguage)&&void 0!==v?v:l.x.GLSL,e.uniformBuffersNames){this._uniformBuffersNamesList=e.uniformBuffersNames.slice();for(let t=0;t{if(R[0]&&R[1]){A.isFragment=!0;const[t,i]=R;o.L.Process(i,A,((i,n)=>{this._fragmentSourceCodeBeforeMigration=n,C&&(i=C("fragment",i));const s=o.L.Finalize(t,i,A);A=null,this._useFinalCode(s.vertexCode,s.fragmentCode,e)}),this._engine)}};this._loadShader(x,"Vertex","",(e=>{o.L.Initialize(A),o.L.Process(e,A,((t,i)=>{this._rawVertexSourceCode=e,this._vertexSourceCodeBeforeMigration=i,C&&(t=C("vertex",t)),R[0]=t,P()}),this._engine)})),this._loadShader(b,"Fragment","Pixel",(e=>{this._rawFragmentSourceCode=e,R[1]=e,P()}))}_useFinalCode(e,t,i){if(i){const n=i.vertexElement||i.vertex||i.spectorName||i,s=i.fragmentElement||i.fragment||i.spectorName||i;this._vertexSourceCode=(this._shaderLanguage===l.x.WGSL?"//":"")+"#define SHADER_NAME vertex:"+n+"\n"+e,this._fragmentSourceCode=(this._shaderLanguage===l.x.WGSL?"//":"")+"#define SHADER_NAME fragment:"+s+"\n"+t}else this._vertexSourceCode=e,this._fragmentSourceCode=t;this._prepareEffect()}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch(e){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)}_loadShader(e,t,i,n){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement){return void n((0,s.v)(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 r=a.v.GetShadersStore(this._shaderLanguage);if(r[e+t+"Shader"])return void n(r[e+t+"Shader"]);if(i&&r[e+i+"Shader"])return void n(r[e+i+"Shader"]);let o;o="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:a.v.GetShadersRepository(this._shaderLanguage)+e,this._engine._loadFile(o+"."+t.toLowerCase()+".fx",n)}get vertexSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:null!==(t=null===(e=this._pipelineContext)||void 0===e?void 0:e._getVertexShaderCode())&&void 0!==t?t:this._vertexSourceCode}get fragmentSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:null!==(t=null===(e=this._pipelineContext)||void 0===e?void 0:e._getFragmentShaderCode())&&void 0!==t?t:this._fragmentSourceCode}get vertexSourceCodeBeforeMigration(){return this._vertexSourceCodeBeforeMigration}get fragmentSourceCodeBeforeMigration(){return this._fragmentSourceCodeBeforeMigration}get rawVertexSourceCode(){return this._rawVertexSourceCode}get rawFragmentSourceCode(){return this._rawFragmentSourceCode}_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{if(this._attributes=[],this._pipelineContext._fillEffectInformation(this,this._uniformBuffersNames,this._uniformsNames,this._uniforms,this._samplerList,this._samplers,e,this._attributes),e)for(let t=0;t=t&&(s=`Offending line [${t}] in ${i?"fragment":"vertex"} code: ${n[t-1]}`)}}return[e,s]}_processCompilationErrors(e,t=null){var i,n,s;this._compilationError=e.message;const o=this._attributesNames,a=this._fallbacks;if(r.Y.Error("Unable to compile effect:"),r.Y.Error("Uniforms: "+this._uniformsNames.map((function(e){return" "+e}))),r.Y.Error("Attributes: "+o.map((function(e){return" "+e}))),r.Y.Error("Defines:\r\n"+this.defines),h.LogShaderCodeOnCompilationError){let e=null,t=null,o=null;(null===(i=this._pipelineContext)||void 0===i?void 0:i._getVertexShaderCode())&&([o,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),o&&(r.Y.Error("Vertex code:"),r.Y.Error(o))),(null===(n=this._pipelineContext)||void 0===n?void 0:n._getFragmentShaderCode())&&([o,t]=this._getShaderCodeAndErrorLine(null===(s=this._pipelineContext)||void 0===s?void 0:s._getFragmentShaderCode(),this._compilationError,!0),o&&(r.Y.Error("Fragment code:"),r.Y.Error(o))),e&&r.Y.Error(e),t&&r.Y.Error(t)}r.Y.Error("Error: "+this._compilationError);const l=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,l()),a?(this._pipelineContext=null,a.hasMoreFallbacks?(this._allFallbacksProcessed=!1,r.Y.Error("Trying next fallback."),this.defines=a.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,l(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||l())}get isSupported(){return""===this._compilationError}_bindTexture(e,t){this._engine._bindTexture(this._samplers[e],t,e)}setTexture(e,t){this._engine.setTexture(this._samplers[e],this._uniforms[e],t,e)}setDepthStencilTexture(e,t){this._engine.setDepthStencilTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){const i=e+"Ex";if(-1===this._samplerList.indexOf(i+"0")){const n=this._samplerList.indexOf(e);for(let e=1;enew d),this)}serialize(){return s.p4.Serialize(this)}static Parse(e){const t=s.p4.Parse((()=>new d),e,null,null);return void 0!==e.vignetteCentreX&&(t.vignetteCenterX=e.vignetteCentreX),void 0!==e.vignetteCentreY&&(t.vignetteCenterY=e.vignetteCentreY),t}static get VIGNETTEMODE_MULTIPLY(){return this._VIGNETTEMODE_MULTIPLY}static get VIGNETTEMODE_OPAQUE(){return this._VIGNETTEMODE_OPAQUE}}d.TONEMAPPING_STANDARD=0,d.TONEMAPPING_ACES=1,d._VIGNETTEMODE_MULTIPLY=0,d._VIGNETTEMODE_OPAQUE=1,(0,n.gn)([(0,s.N$)()],d.prototype,"colorCurves",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_colorCurvesEnabled",void 0),(0,n.gn)([(0,s.oU)("colorGradingTexture")],d.prototype,"_colorGradingTexture",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_colorGradingEnabled",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_colorGradingWithGreenDepth",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_colorGradingBGR",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_exposure",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_toneMappingEnabled",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_toneMappingType",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_contrast",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"vignetteStretch",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"vignetteCenterX",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"vignetteCenterY",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"vignetteWeight",void 0),(0,n.gn)([(0,s.XX)()],d.prototype,"vignetteColor",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"vignetteCameraFov",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_vignetteBlendMode",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_vignetteEnabled",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_ditheringEnabled",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_ditheringIntensity",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_skipFinalColorClamp",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_applyByPostProcess",void 0),(0,n.gn)([(0,s.qC)()],d.prototype,"_isEnabled",void 0),s.p4._ImageProcessingConfigurationParser=d.Parse},2067:function(e,t,i){i.d(t,{F:function(){return g}});var n=i(1069),s=i(8137),r=i(8658),o=i(8139),a=i(5953),l=i(4735),h=i(760),c=i(658),d=i(6504),u=i(2108),p=i(7050);class f{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=519,this.funcRef=1,this.funcMask=255,this.opStencilFail=7680,this.opDepthFail=7680,this.opStencilDepthPass=7681}get func(){return this._func}set func(e){this._func=e}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef=e}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask=e}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail=e}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail=e}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass=e}get mask(){return this._mask}set mask(e){this._mask=e}get enabled(){return this._enabled}set enabled(e){this._enabled=e}getClassName(){return"MaterialStencilState"}copyTo(e){s.p4.Clone((()=>e),this)}serialize(){return s.p4.Serialize(this)}parse(e,t,i){s.p4.Parse((()=>this),e,t,i)}}(0,n.gn)([(0,s.qC)()],f.prototype,"func",null),(0,n.gn)([(0,s.qC)()],f.prototype,"funcRef",null),(0,n.gn)([(0,s.qC)()],f.prototype,"funcMask",null),(0,n.gn)([(0,s.qC)()],f.prototype,"opStencilFail",null),(0,n.gn)([(0,s.qC)()],f.prototype,"opDepthFail",null),(0,n.gn)([(0,s.qC)()],f.prototype,"opStencilDepthPass",null),(0,n.gn)([(0,s.qC)()],f.prototype,"mask",null),(0,n.gn)([(0,s.qC)()],f.prototype,"enabled",null);var _=i(147),m=i(7545);class g{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(g.MiscDirtyFlag+g.PrePassDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(g.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(g.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 o.y$),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 o.y$),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new o.y$),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode!==e&&(this._alphaMode=e,this.markAsDirty(g.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(g.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case g.WireFrameFillMode:case g.LineListDrawMode:case g.LineLoopDrawMode:case g.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?g.WireFrameFillMode:g.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case g.PointFillMode:case g.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?g.PointFillMode:g.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(g.MiscDirtyFlag))}_getDrawWrapper(){return this._drawWrapper}_setDrawWrapper(e){this._drawWrapper=e}constructor(e,t,i){this.shadowDepthWrapper=null,this.allowShaderHotSwapping=!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.onCompiled=null,this.onError=null,this.getRenderTargetTextures=null,this.doNotSerialize=!1,this._storeEffectOnSubMeshes=!1,this.animations=null,this.onDisposeObservable=new o.y$,this._onDisposeObserver=null,this._onUnBindObservable=null,this._onBindObserver=null,this._alphaMode=2,this._needDepthPrePass=!1,this.disableDepthWrite=!1,this.disableColorWrite=!1,this.forceDepthWrite=!1,this.depthFunction=0,this.separateCullingPass=!1,this._fogEnabled=!0,this.pointSize=1,this.zOffset=0,this.zOffsetUnits=0,this.stencil=new f,this._useUBO=!1,this._fillMode=g.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||a.l.LastCreatedScene;n&&(this._scene=n,this._dirtyCallbacks={},this._dirtyCallbacks[1]=this._markAllSubMeshesAsTexturesDirty.bind(this),this._dirtyCallbacks[2]=this._markAllSubMeshesAsLightsDirty.bind(this),this._dirtyCallbacks[4]=this._markAllSubMeshesAsFresnelDirty.bind(this),this._dirtyCallbacks[8]=this._markAllSubMeshesAsAttributesDirty.bind(this),this._dirtyCallbacks[16]=this._markAllSubMeshesAsMiscDirty.bind(this),this._dirtyCallbacks[32]=this._markAllSubMeshesAsPrePassDirty.bind(this),this._dirtyCallbacks[63]=this._markAllSubMeshesAsAllDirty.bind(this),this.id=e||r.w1.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new p.q(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=g.ClockWiseSideOrientation:this.sideOrientation=g.CounterClockWiseSideOrientation,this._uniformBuffer=new h.M(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),g.OnEventObservable.notifyObservers(this,m.S.Created))}toString(e){return"Name: "+this.name}getClassName(){return"Material"}get _isMaterial(){return!0}get isFrozen(){return this.checkReadyOnlyOnce}freeze(){this.markDirty(),this.checkReadyOnlyOnce=!0}unfreeze(){this.markDirty(),this.checkReadyOnlyOnce=!1}isReady(e,t){return!0}isReadyForSubMesh(e,t,i){const 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}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===g.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===g.MATERIAL_OPAQUE||this._transparencyMode===g.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)t.getMaterial()===this&&t.effect&&(t.effect._wasPreviouslyReady=!1,t.effect._wasPreviouslyUsingInstances=null,t.effect._forceRebindOnNextCall=e);e&&this.markAsDirty(g.AllDirtyFlag)}_preBind(e,t=null){const i=this._scene.getEngine(),n=(null==t?this.sideOrientation:t)===g.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(m.S.PrepareUniformBuffer,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){const n=i.effect;n&&(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){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,u.G.BindSceneUniformBuffer(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(m.S.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(m.S.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(m.S.HasTexture,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){const i={};if(this._serializePlugins(i),g._parsePlugins(i,e,this._scene,t),this.pluginManager)for(const n of this.pluginManager._plugins){const t=e.pluginManager.getPlugin(n.name);n.copyTo(t)}}getBindedMeshes(){if(this.meshMap){const e=new Array;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 s=Object.assign({clipPlane:!1,useInstances:!1},i),r=this.getScene(),o=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const a=()=>{if(!this._scene||!this._scene.getEngine())return;const i=r.clipPlane;if(s.clipPlane&&(r.clipPlane=new d.J(0,0,0,1)),this._storeEffectOnSubMeshes){let i=!0,r=null;if(e.subMeshes){const t=new l.P(0,0,0,0,0,e,void 0,!1,!1);t.materialDefines&&(t.materialDefines._renderId=-1),this.isReadyForSubMesh(e,t,s.useInstances)||(t.effect&&t.effect.getCompilationError()&&t.effect.allFallbacksProcessed()?r=t.effect.getCompilationError():(i=!1,setTimeout(a,16)))}i&&(this.allowShaderHotSwapping=o,r&&n&&n(r),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=o,t&&t(this)):setTimeout(a,16);s.clipPlane&&(r.clipPlane=i)};a()}forceCompilationAsync(e,t){return new Promise(((i,n)=>{this.forceCompilation(e,(()=>{i()}),t,(e=>{n(e)}))}))}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(g._DirtyCallbackArray.length=0,e&g.TextureDirtyFlag&&g._DirtyCallbackArray.push(g._TextureDirtyCallBack),e&g.LightDirtyFlag&&g._DirtyCallbackArray.push(g._LightsDirtyCallBack),e&g.FresnelDirtyFlag&&g._DirtyCallbackArray.push(g._FresnelDirtyCallBack),e&g.AttributesDirtyFlag&&g._DirtyCallbackArray.push(g._AttributeDirtyCallBack),e&g.MiscDirtyFlag&&g._DirtyCallbackArray.push(g._MiscDirtyCallBack),e&g.PrePassDirtyFlag&&g._DirtyCallbackArray.push(g._PrePassDirtyCallBack),g._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(g._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(g._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(g._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(g._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(g._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(g._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(g._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(g._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(g._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(g._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(g._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==_.a.BackwardCompatible){this.checkReadyOnlyOnce=!0;const e=this._scene.onScenePerformancePriorityChangedObservable.addOnce((()=>{this.checkReadyOnlyOnce=!1}));this.onDisposeObservable.add((()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)}))}}setPrePassRenderer(e){return!1}dispose(e,t,i){const n=this.getScene();if(n.stopAnimation(this),n.freeProcessedMaterials(),n.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(m.S.Disposed,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 s in this.meshMap){const t=this.meshMap[s];t&&(t.material=null,this.releaseVertexArrayObject(t,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){if(e.geometry){const i=e.geometry;if(this._storeEffectOnSubMeshes)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=s.p4.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 c.Y.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=r.w1.Instantiate(e.customType).Parse(e,t,i);return n._loadedUniqueId=e.uniqueId,n}static _parsePlugins(e,t,i,n){var s;if(e.plugins)for(const o in e.plugins){const a=e.plugins[o];let l=null===(s=t.pluginManager)||void 0===s?void 0:s.getPlugin(a.name);if(!l){const e=r.w1.Instantiate("BABYLON."+o);e&&(l=new e(t))}null==l||l.parse(a,i,n)}}}g.TriangleFillMode=0,g.WireFrameFillMode=1,g.PointFillMode=2,g.PointListDrawMode=3,g.LineListDrawMode=4,g.LineLoopDrawMode=5,g.LineStripDrawMode=6,g.TriangleStripDrawMode=7,g.TriangleFanDrawMode=8,g.ClockWiseSideOrientation=0,g.CounterClockWiseSideOrientation=1,g.TextureDirtyFlag=1,g.LightDirtyFlag=2,g.FresnelDirtyFlag=4,g.AttributesDirtyFlag=8,g.MiscDirtyFlag=16,g.PrePassDirtyFlag=32,g.AllDirtyFlag=63,g.MATERIAL_OPAQUE=0,g.MATERIAL_ALPHATEST=1,g.MATERIAL_ALPHABLEND=2,g.MATERIAL_ALPHATESTANDBLEND=3,g.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,g.MATERIAL_NORMALBLENDMETHOD_RNM=1,g.OnEventObservable=new o.y$,g._AllDirtyCallBack=e=>e.markAllAsDirty(),g._ImageProcessingDirtyCallBack=e=>e.markAsImageProcessingDirty(),g._TextureDirtyCallBack=e=>e.markAsTexturesDirty(),g._FresnelDirtyCallBack=e=>e.markAsFresnelDirty(),g._MiscDirtyCallBack=e=>e.markAsMiscDirty(),g._PrePassDirtyCallBack=e=>e.markAsPrePassDirty(),g._LightsDirtyCallBack=e=>e.markAsLightDirty(),g._AttributeDirtyCallBack=e=>e.markAsAttributesDirty(),g._FresnelAndMiscDirtyCallBack=e=>{g._FresnelDirtyCallBack(e),g._MiscDirtyCallBack(e)},g._TextureAndMiscDirtyCallBack=e=>{g._TextureDirtyCallBack(e),g._MiscDirtyCallBack(e)},g._DirtyCallbackArray=[],g._RunDirtyCallBacks=e=>{for(const t of g._DirtyCallbackArray)t(e)},(0,n.gn)([(0,s.qC)()],g.prototype,"id",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"uniqueId",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"name",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"metadata",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"checkReadyOnEveryCall",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"checkReadyOnlyOnce",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"state",void 0),(0,n.gn)([(0,s.qC)("alpha")],g.prototype,"_alpha",void 0),(0,n.gn)([(0,s.qC)("backFaceCulling")],g.prototype,"_backFaceCulling",void 0),(0,n.gn)([(0,s.qC)("cullBackFaces")],g.prototype,"_cullBackFaces",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"sideOrientation",void 0),(0,n.gn)([(0,s.qC)("alphaMode")],g.prototype,"_alphaMode",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"_needDepthPrePass",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"disableDepthWrite",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"disableColorWrite",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"forceDepthWrite",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"depthFunction",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"separateCullingPass",void 0),(0,n.gn)([(0,s.qC)("fogEnabled")],g.prototype,"_fogEnabled",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"pointSize",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"zOffset",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"zOffsetUnits",void 0),(0,n.gn)([(0,s.qC)()],g.prototype,"pointsCloud",null),(0,n.gn)([(0,s.qC)()],g.prototype,"fillMode",null),(0,n.gn)([(0,s.qC)()],g.prototype,"transparencyMode",null)},4386:function(e,t,i){i.d(t,{H:function(){return n}});class n{constructor(e){if(this._keys=[],this._isDirty=!0,this._areLightsDirty=!0,this._areLightsDisposed=!1,this._areAttributesDirty=!0,this._areTexturesDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!0,this._areImageProcessingDirty=!0,this._normals=!1,this._uvs=!1,this._needNormals=!1,this._needUVs=!1,this._externalProperties=e,e)for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&this._setDefaultValue(t)}get isDirty(){return this._isDirty}markAsProcessed(){this._isDirty=!1,this._areAttributesDirty=!1,this._areTexturesDirty=!1,this._areFresnelDirty=!1,this._areLightsDirty=!1,this._areLightsDisposed=!1,this._areMiscDirty=!1,this._arePrePassDirty=!1,this._areImageProcessingDirty=!1}markAsUnprocessed(){this._isDirty=!0}markAllAsDirty(){this._areTexturesDirty=!0,this._areAttributesDirty=!0,this._areLightsDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!1,this._areImageProcessingDirty=!0,this._isDirty=!0}markAsImageProcessingDirty(){this._areImageProcessingDirty=!0,this._isDirty=!0}markAsLightDirty(e=!1){this._areLightsDirty=!0,this._areLightsDisposed=this._areLightsDisposed||e,this._isDirty=!0}markAsAttributesDirty(){this._areAttributesDirty=!0,this._isDirty=!0}markAsTexturesDirty(){this._areTexturesDirty=!0,this._isDirty=!0}markAsFresnelDirty(){this._areFresnelDirty=!0,this._isDirty=!0}markAsMiscDirty(){this._areMiscDirty=!0,this._isDirty=!0}markAsPrePassDirty(){this._arePrePassDirty=!0,this._isDirty=!0}rebuild(){this._keys.length=0;for(const e of Object.keys(this))"_"!==e[0]&&this._keys.push(e);if(this._externalProperties)for(const e in this._externalProperties)-1===this._keys.indexOf(e)&&this._keys.push(e)}isEqual(e){if(this._keys.length!==e._keys.length)return!1;for(let t=0;tthis._setDefaultValue(e)))}_setDefaultValue(e){var t,i,n,s,r;const o=null!==(n=null===(i=null===(t=this._externalProperties)||void 0===t?void 0:t[e])||void 0===i?void 0:i.type)&&void 0!==n?n:typeof this[e],a=null===(r=null===(s=this._externalProperties)||void 0===s?void 0:s[e])||void 0===r?void 0:r.default;switch(o){case"number":this[e]=null!=a?a:0;break;case"string":this[e]=null!=a?a:"";break;default:this[e]=null!=a&&a}}toString(){let e="";for(let t=0;t0,t.NUM_MORPH_INFLUENCERS=i.numInfluencers,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)}static PrepareDefinesForBakedVertexAnimation(e,t){const i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!(!i||!i.isEnabled)}static PrepareDefinesForAttributes(e,t,i,n,s=!1,r=!0,o=!0){if(!t._areAttributesDirty&&t._needNormals===t._normals&&t._needUVs===t._uvs)return!1;t._normals=t._needNormals,t._uvs=t._needUVs,t.NORMAL=t._needNormals&&e.isVerticesDataPresent(a.o.NormalKind),t._needNormals&&e.isVerticesDataPresent(a.o.TangentKind)&&(t.TANGENT=!0);for(let a=1;a<=6;++a)t["UV"+a]=!!t._needUVs&&e.isVerticesDataPresent(`uv${1===a?"":a}`);if(i){const i=e.useVertexColors&&e.isVerticesDataPresent(a.o.ColorKind);t.VERTEXCOLOR=i,t.VERTEXALPHA=e.hasVertexAlpha&&i&&r}return e.isVerticesDataPresent(a.o.ColorInstanceKind)&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),n&&this.PrepareDefinesForBones(e,t),s&&this.PrepareDefinesForMorphTargets(e,t),o&&this.PrepareDefinesForBakedVertexAnimation(e,t),!0}static PrepareDefinesForMultiview(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()}}static PrepareDefinesForOIT(e,t,i){const n=t.ORDER_INDEPENDENT_TRANSPARENCY,s=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&i,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,n===t.ORDER_INDEPENDENT_TRANSPARENCY&&s===t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS||t.markAsUnprocessed()}static PrepareDefinesForPrePass(e,t,i){const n=t.PREPASS;if(!t._arePrePassDirty)return;const s=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(e.prePassRenderer&&e.prePassRenderer.enabled&&i){t.PREPASS=!0,t.SCENE_MRT_COUNT=e.prePassRenderer.mrtCount;for(let i=0;i0&&(o.shadowEnabled=!0,t.prepareDefines(s,n))}}i.lightmapMode!=l.m.LIGHTMAP_DEFAULT?(o.lightmapMode=!0,s["LIGHTMAPEXCLUDED"+n]=!0,s["LIGHTMAPNOSPECULAR"+n]=i.lightmapMode==l.m.LIGHTMAP_SHADOWSONLY):(s["LIGHTMAPEXCLUDED"+n]=!1,s["LIGHTMAPNOSPECULAR"+n]=!1)}static PrepareDefinesForLights(e,t,i,n,s=4,r=!1){if(!i._areLightsDirty)return i._needNormals;let o=0;const a={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!r)for(const h of t.lightSources)if(this.PrepareDefinesForLight(e,t,h,o,i,n,a),o++,o===s)break;i.SPECULARTERM=a.specularEnabled,i.SHADOWS=a.shadowEnabled;for(let h=o;h0&&(s=n+r,t.addFallback(s,"LIGHT"+r)),e.SHADOWS||(e["SHADOW"+r]&&t.addFallback(n,"SHADOW"+r),e["SHADOWPCF"+r]&&t.addFallback(n,"SHADOWPCF"+r),e["SHADOWPCSS"+r]&&t.addFallback(n,"SHADOWPCSS"+r),e["SHADOWPOISSON"+r]&&t.addFallback(n,"SHADOWPOISSON"+r),e["SHADOWESM"+r]&&t.addFallback(n,"SHADOWESM"+r),e["SHADOWCLOSEESM"+r]&&t.addFallback(n,"SHADOWCLOSEESM"+r));return s++}static PrepareAttributesForMorphTargetsInfluencers(e,t,i){this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS=i,this.PrepareAttributesForMorphTargets(e,t,this._TmpMorphInfluencers)}static PrepareAttributesForMorphTargets(e,t,i){const s=i.NUM_MORPH_INFLUENCERS;if(s>0&&o.l.LastCreatedEngine){const r=o.l.LastCreatedEngine.getCaps().maxVertexAttribs,l=t.morphTargetManager;if(null==l?void 0:l.isUsingTextureForTargets)return;const h=l&&l.supportsNormals&&i.NORMAL,c=l&&l.supportsTangents&&i.TANGENT,d=l&&l.supportsUVs&&i.UV1;for(let i=0;ir&&n.Y.Error("Cannot add more vertex attributes for mesh "+t.name)}}static PrepareAttributesForBakedVertexAnimation(e,t,i){i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES&&e.push("bakedVertexAnimationSettingsInstanced")}static PrepareAttributesForBones(e,t,i,n){i.NUM_BONE_INFLUENCERS>0&&(n.addCPUSkinningFallback(0,t),e.push(a.o.MatricesIndicesKind),e.push(a.o.MatricesWeightsKind),i.NUM_BONE_INFLUENCERS>4&&(e.push(a.o.MatricesIndicesExtraKind),e.push(a.o.MatricesWeightsExtraKind)))}static PrepareAttributesForInstances(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&this.PushAttributesForInstances(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push(a.o.ColorInstanceKind)}static PushAttributesForInstances(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"))}static BindLightProperties(e,t,i){e.transferToEffect(t,i+"")}static BindLight(e,t,i,n,s,r=!0){e._bindLight(t,i,n,s,r)}static BindLights(e,t,i,n,s=4){const r=Math.min(t.lightSources.length,s);for(let o=0;o-1){const i=n.getTransformMatrixTexture(e);t.setTexture("boneSampler",i),t.setFloat("boneTextureWidth",4*(n.bones.length+1))}else{const s=n.getTransformMatrices(e);s&&(t.setMatrices("mBones",s),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(2)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=s.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),d._CopyBonesTransformationMatrices(s,i.previousBones[e.uniqueId])))}}}static _CopyBonesTransformationMatrices(e,t){return t.set(e),t}static BindMorphTargetParameters(e,t){const i=e.morphTargetManager;e&&i&&t.setFloatArray("morphTargetInfluences",i.influences)}static BindLogDepth(e,t,i){if(!e||e.LOGARITHMICDEPTH||e.indexOf&&e.indexOf("LOGARITHMICDEPTH")>=0){const e=i.activeCamera;e.mode===s.V.ORTHOGRAPHIC_CAMERA&&n.Y.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(e.maxZ+1)/Math.LN2))}}}d._TmpMorphInfluencers={NUM_MORPH_INFLUENCERS:0},d._TempFogColor=h.Wo.Black()},7545:function(e,t,i){var n;i.d(t,{S:function(){return n}}),function(e){e[e.Created=1]="Created",e[e.Disposed=2]="Disposed",e[e.GetDefineNames=4]="GetDefineNames",e[e.PrepareUniformBuffer=8]="PrepareUniformBuffer",e[e.IsReadyForSubMesh=16]="IsReadyForSubMesh",e[e.PrepareDefines=32]="PrepareDefines",e[e.BindForSubMesh=64]="BindForSubMesh",e[e.PrepareEffect=128]="PrepareEffect",e[e.GetAnimatables=256]="GetAnimatables",e[e.GetActiveTextures=512]="GetActiveTextures",e[e.HasTexture=1024]="HasTexture",e[e.FillRenderTargetTextures=2048]="FillRenderTargetTextures",e[e.HasRenderTargetTextures=4096]="HasRenderTargetTextures",e[e.HardBindForSubMesh=8192]="HardBindForSubMesh"}(n||(n={}))},8058:function(e,t,i){i.d(t,{G:function(){return o}});var n=i(2067),s=i(4104),r=i(646);class o extends n.F{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=new Array,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 s=i.apply(e,[t,n]);return this._markAllSubMeshesAsTexturesDirty(),s}}getSubMaterial(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]}getActiveTextures(){return super.getActiveTextures().concat(...this.subMaterials.map((e=>e?e.getActiveTextures():[])))}hasTexture(e){var t;if(super.hasTexture(e))return!0;for(let i=0;i=0&&n.multiMaterials.splice(s,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const i=new o(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,s.$&&s.$.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach((e=>i.subMaterials.push(t.getLastMaterialById(e)))),i}}(0,r.H)("BABYLON.MultiMaterial",o)},475:function(e,t,i){var n;i.d(t,{x:function(){return n}}),function(e){e[e.GLSL=0]="GLSL",e[e.WGSL=1]="WGSL"}(n||(n={}))},760:function(e,t,i){i.d(t,{M:function(){return r}});var n=i(658),s=i(8658);i(4507);class r{constructor(e,t,i,n,s=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||s,this._dynamic=i,this._name=null!=n?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 t=0;t0){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;e1&&this._buffers[this._bufferIndex][1]){if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1]))return this._needSync=!1,void(this._createBufferOnWrite=this._engine._features.trackUbosInFrame);this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1])}this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(r._UpdatedUbosInFrame[this._name]||(r._UpdatedUbosInFrame[this._name]=0),r._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}else this._createBufferOnWrite=this._engine._features.trackUbosInFrame;else this.create()}_createNewBuffer(){this._bufferIndex+10?(this._needSync=0!==this._bufferIndex,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,i){this._checkNewFrame();let r=this._uniformLocations[e];if(void 0===r){if(this._buffer)return void n.Y.Error("Cannot add an uniform after UBO has been created.");this.addUniform(e,i),r=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let n=0;n=0&&r<=1?(a=s,l=o):r>=1&&r<=2?(a=o,l=s):r>=2&&r<=3?(l=s,h=o):r>=3&&r<=4?(l=o,h=s):r>=4&&r<=5?(a=o,h=s):r>=5&&r<=6&&(a=s,h=o);const c=i-s;n.set(a+c,l+c,h+c)}static FromHSV(e,t,i){const n=new d(0,0,0);return d.HSVtoRGBToRef(e,t,i,n),n}static FromHexString(e){if("#"!==e.substring(0,1)||7!==e.length)return new d(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 d.FromInts(t,i,n)}static FromArray(e,t=0){return new d(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 d(e/255,t/255,i/255)}static Lerp(e,t,i){const n=new d(0,0,0);return d.LerpToRef(e,t,i,n),n}static LerpToRef(e,t,i,n){n.r=e.r+(t.r-e.r)*i,n.g=e.g+(t.g-e.g)*i,n.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,n,s){const r=s*s,o=s*r,a=2*o-3*r+1,l=-2*o+3*r,h=o-2*r+s,c=o-r,u=e.r*a+i.r*l+t.r*h+n.r*c,p=e.g*a+i.g*l+t.g*h+n.g*c,f=e.b*a+i.b*l+t.b*h+n.b*c;return new d(u,p,f)}static Hermite1stDerivative(e,t,i,n,s){const r=d.Black();return this.Hermite1stDerivativeToRef(e,t,i,n,s,r),r}static Hermite1stDerivativeToRef(e,t,i,n,s,r){const o=s*s;r.r=6*(o-s)*e.r+(3*o-4*s+1)*t.r+6*(-o+s)*i.r+(3*o-2*s)*n.r,r.g=6*(o-s)*e.g+(3*o-4*s+1)*t.g+6*(-o+s)*i.g+(3*o-2*s)*n.g,r.b=6*(o-s)*e.b+(3*o-4*s+1)*t.b+6*(-o+s)*i.b+(3*o-2*s)*n.b}static Red(){return new d(1,0,0)}static Green(){return new d(0,1,0)}static Blue(){return new d(0,0,1)}static Black(){return new d(0,0,0)}static get BlackReadOnly(){return d._BlackReadOnly}static White(){return new d(1,1,1)}static Purple(){return new d(.5,0,.5)}static Magenta(){return new d(1,0,1)}static Yellow(){return new d(1,1,0)}static Gray(){return new d(.5,.5,.5)}static Teal(){return new d(0,1,1)}static Random(){return new d(Math.random(),Math.random(),Math.random())}}d._BlackReadOnly=d.Black();class u{constructor(e=0,t=0,i=0,n=1){this.r=e,this.g=t,this.b=i,this.a=n}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}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 u.FromArrayToRef(e,t,this),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 u(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}subtract(e){return new u(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,this}scale(e){return new u(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,this}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,this}clampToRef(e=0,t=1,i){return i.r=n.R.Clamp(this.r,e,t),i.g=n.R.Clamp(this.g,e,t),i.b=n.R.Clamp(this.b,e,t),i.a=n.R.Clamp(this.a,e,t),this}multiply(e){return new u(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}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|0),e=397*e^(255*this.b|0),e=397*e^(255*this.a|0),e}clone(){return new u(this.r,this.g,this.b,this.a)}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)}toHexString(e=!1){const t=Math.round(255*this.r),i=Math.round(255*this.g),s=Math.round(255*this.b);if(e)return"#"+n.R.ToHex(t)+n.R.ToHex(i)+n.R.ToHex(s);const r=Math.round(255*this.a);return"#"+n.R.ToHex(t)+n.R.ToHex(i)+n.R.ToHex(s)+n.R.ToHex(r)}toLinearSpace(e=!1){const t=new u;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=l(this.r),e.g=l(this.g),e.b=l(this.b)):(e.r=a(this.r),e.g=a(this.g),e.b=a(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new u;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=c(this.r),e.g=c(this.g),e.b=c(this.b)):(e.r=h(this.r),e.g=h(this.g),e.b=h(this.b)),e.a=this.a,this}static FromHexString(e){if("#"!==e.substring(0,1)||9!==e.length&&7!==e.length)return new u(0,0,0,0);const t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),n=parseInt(e.substring(5,7),16),s=9===e.length?parseInt(e.substring(7,9),16):255;return u.FromInts(t,i,n,s)}static Lerp(e,t,i){const n=new u(0,0,0,0);return u.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,n.a=e.a+(t.a-e.a)*i}static Hermite(e,t,i,n,s){const r=s*s,o=s*r,a=2*o-3*r+1,l=-2*o+3*r,h=o-2*r+s,c=o-r,d=e.r*a+i.r*l+t.r*h+n.r*c,p=e.g*a+i.g*l+t.g*h+n.g*c,f=e.b*a+i.b*l+t.b*h+n.b*c,_=e.a*a+i.a*l+t.a*h+n.a*c;return new u(d,p,f,_)}static Hermite1stDerivative(e,t,i,n,s){const r=new u;return this.Hermite1stDerivativeToRef(e,t,i,n,s,r),r}static Hermite1stDerivativeToRef(e,t,i,n,s,r){const o=s*s;r.r=6*(o-s)*e.r+(3*o-4*s+1)*t.r+6*(-o+s)*i.r+(3*o-2*s)*n.r,r.g=6*(o-s)*e.g+(3*o-4*s+1)*t.g+6*(-o+s)*i.g+(3*o-2*s)*n.g,r.b=6*(o-s)*e.b+(3*o-4*s+1)*t.b+6*(-o+s)*i.b+(3*o-2*s)*n.b,r.a=6*(o-s)*e.a+(3*o-4*s+1)*t.a+6*(-o+s)*i.a+(3*o-2*s)*n.a}static FromColor3(e,t=1){return new u(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new u(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 u(e/255,t/255,i/255,n/255)}static CheckColors4(e,t){if(e.length===3*t){const t=[];for(let i=0;inew u(0,0,0,0))),(0,o.H)("BABYLON.Color3",d),(0,o.H)("BABYLON.Color4",u)},4551:function(e,t,i){i.d(t,{Nn:function(){return s},Q_:function(){return r},kn:function(){return o},zp:function(){return n}});const n=1/2.2,s=2.2,r=(1+Math.sqrt(5))/2,o=.001},8952:function(e,t,i){i.d(t,{i:function(){return s}});var n=i(6504);class s{static GetPlanes(e){const t=[];for(let i=0;i<6;i++)t.push(new n.J(0,0,0,0));return s.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[2],t.normal.y=i[7]+i[6],t.normal.z=i[11]+i[10],t.d=i[15]+i[14],t.normalize()}static GetFarPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[2],t.normal.y=i[7]-i[6],t.normal.z=i[11]-i[10],t.d=i[15]-i[14],t.normalize()}static GetLeftPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[0],t.normal.y=i[7]+i[4],t.normal.z=i[11]+i[8],t.d=i[15]+i[12],t.normalize()}static GetRightPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[0],t.normal.y=i[7]-i[4],t.normal.z=i[11]-i[8],t.d=i[15]-i[12],t.normalize()}static GetTopPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]-i[1],t.normal.y=i[7]-i[5],t.normal.z=i[11]-i[9],t.d=i[15]-i[13],t.normalize()}static GetBottomPlaneToRef(e,t){const i=e.m;t.normal.x=i[3]+i[1],t.normal.y=i[7]+i[5],t.normal.z=i[11]+i[9],t.d=i[15]+i[13],t.normalize()}static GetPlanesToRef(e,t){s.GetNearPlaneToRef(e,t[0]),s.GetFarPlaneToRef(e,t[1]),s.GetLeftPlaneToRef(e,t[2]),s.GetRightPlaneToRef(e,t[3]),s.GetTopPlaneToRef(e,t[4]),s.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(t[i].dotCoordinate(e)<0)return!1;return!0}}},7303:function(e,t,i){i.d(t,{k:function(){return l},y:function(){return a}});var n=i(1069),s=i(5412),r=i(8137);class o{static extractMinAndMaxIndexed(e,t,i,n,s,r){for(let o=i;o!Array.isArray(e)&&!Array.isArray(t)))],o,"extractMinAndMaxIndexed",null),(0,n.gn)([r.G6.filter(((...[e])=>!Array.isArray(e)))],o,"extractMinAndMax",null)},6504:function(e,t,i){i.d(t,{J:function(){return s}});var n=i(5412);class s{constructor(e,t,i,s){this.normal=new n.P(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new s(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){let e=this.normal.getHashCode();return e=397*e^(0|this.d),e}normalize(){const e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z);let t=0;return 0!==e&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this}transform(e){const t=s._TmpMatrix;e.invertToRef(t);const i=t.m,n=this.normal.x,r=this.normal.y,o=this.normal.z,a=this.d,l=n*i[0]+r*i[1]+o*i[2]+a*i[3],h=n*i[4]+r*i[5]+o*i[6]+a*i[7],c=n*i[8]+r*i[9]+o*i[10]+a*i[11],d=n*i[12]+r*i[13]+o*i[14]+a*i[15];return new s(l,h,c,d)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){const n=t.x-e.x,s=t.y-e.y,r=t.z-e.z,o=i.x-e.x,a=i.y-e.y,l=i.z-e.z,h=s*l-r*a,c=r*o-n*l,d=n*a-s*o,u=Math.sqrt(h*h+c*c+d*d);let p;return p=0!==u?1/u:0,this.normal.x=h*p,this.normal.y=c*p,this.normal.z=d*p,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return n.P.Dot(this.normal,e)<=t}signedDistanceTo(e){return n.P.Dot(e,this.normal)+this.d}static FromArray(e){return new s(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){const n=new s(0,0,0,0);return n.copyFromPoints(e,t,i),n}static FromPositionAndNormal(e,t){const i=new s(0,0,0,0);return t.normalize(),i.normal=t,i.d=-(t.x*e.x+t.y*e.y+t.z*e.z),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){const s=-(t.x*e.x+t.y*e.y+t.z*e.z);return n.P.Dot(i,t)+s}}s._TmpMatrix=n.y3.Identity()},1226:function(e,t,i){i.d(t,{R:function(){return n}});class n{static WithinEpsilon(e,t,i=1401298e-51){return Math.abs(e-t)<=i}static ToHex(e){const t=e.toString(16);return e<=15?("0"+t).toUpperCase():t.toUpperCase()}static Sign(e){return 0===(e=+e)||isNaN(e)?e:e>0?1:-1}static Clamp(e,t=0,i=1){return Math.min(i,Math.max(t,e))}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=n.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){const i=n.Repeat(e,2*t);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let s=n.Clamp(i);return s=-2*s*s*s+3*s*s,t*s+e*(1-s)}static MoveTowards(e,t,i){let s=0;return s=Math.abs(t-e)<=i?t:e+n.Sign(t-e)*i,s}static MoveTowardsAngle(e,t,i){const s=n.DeltaAngle(e,t);let r=0;return-i180&&(s-=360),e+s*n.Clamp(i)}static InverseLerp(e,t,i){let s=0;return s=e!=t?n.Clamp((i-e)/(t-e)):0,s}static Hermite(e,t,i,n,s){const r=s*s,o=s*r;return e*(2*o-3*r+1)+i*(-2*o+3*r)+t*(o-2*r+s)+n*(o-r)}static Hermite1stDerivative(e,t,i,n,s){const r=s*s;return 6*(r-s)*e+(3*r-4*s+1)*t+6*(-r+s)*i+(3*r-2*s)*n}static RandomRange(e,t){return e===t?e:Math.random()*(t-e)+e}static RangeToPercent(e,t,i){return(e-t)/(i-t)}static PercentToRange(e,t,i){return(i-t)*e+t}static NormalizeRadians(e){return e-=n.TwoPi*Math.floor((e+Math.PI)/n.TwoPi)}static HCF(e,t){const i=e%t;return 0===i?t:n.HCF(t,i)}}n.TwoPi=2*Math.PI},470:function(e,t,i){i.d(t,{l:function(){return n}});class n{constructor(e,t,i,n){this.x=e,this.y=t,this.width=i,this.height=n}toGlobal(e,t){return new n(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 n(this.x,this.y,this.width,this.height)}}},4081:function(e,t,i){i.d(t,{M:function(){return s}});var n=i(1545);class s extends n.h{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}},5068:function(e,t,i){i.d(t,{x:function(){return x}});var n=i(8139),s=i(147),r=i(5412),o=i(8838),a=i(2186),l=i(2341),h=i(4179),c=i(318),d=i(2789),u=i(760),p=i(7901),f=i(9069),_=i(7303),m=i(2922),g=i(4551),v=i(5241),T=i(646);class S{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=r.P.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class E{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new S,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 p.a,this._enableDistantPicking=!1,this._rawBoundingInfo=null}}class x extends h.Y{static get BILLBOARDMODE_NONE(){return h.Y.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return h.Y.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return h.Y.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return h.Y.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return h.Y.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return h.Y.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 pointerOverDisableMeshTesting(){return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting}set pointerOverDisableMeshTesting(e){this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting=e}get renderingGroupId(){return this._internalAbstractMeshDataInfo._renderingGroupId}set renderingGroupId(e){this._internalAbstractMeshDataInfo._renderingGroupId=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){this._internalAbstractMeshDataInfo._material!==e&&(this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&(this.resetDrawCache(),this._unBindEffect()))}getMaterialForRenderPass(e){var t;return null===(t=this._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===t?void 0:t[e]}setMaterialForRenderPass(e,t){this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t}get receiveShadows(){return this._internalAbstractMeshDataInfo._receiveShadows}set receiveShadows(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())}get hasVertexAlpha(){return this._internalAbstractMeshDataInfo._hasVertexAlpha}set hasVertexAlpha(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())}get useVertexColors(){return this._internalAbstractMeshDataInfo._useVertexColors}set useVertexColors(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get numBoneInfluencers(){return this._internalAbstractMeshDataInfo._numBoneInfluencers}set numBoneInfluencers(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())}get applyFog(){return this._internalAbstractMeshDataInfo._applyFog}set applyFog(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())}get enableDistantPicking(){return this._internalAbstractMeshDataInfo._enableDistantPicking}set enableDistantPicking(e){this._internalAbstractMeshDataInfo._enableDistantPicking=e}get layerMask(){return this._internalAbstractMeshDataInfo._layerMask}set layerMask(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())}get collisionMask(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask}set collisionMask(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e}get collisionResponse(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse}set collisionResponse(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e}get collisionGroup(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup}set collisionGroup(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e}get surroundingMeshes(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes}set surroundingMeshes(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e}get lightSources(){return this._lightSources}get _positions(){return null}set skeleton(e){const t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()}get skeleton(){return this._internalAbstractMeshDataInfo._skeleton}constructor(e,t=null){switch(super(e,t,!1),this._internalAbstractMeshDataInfo=new E,this._waitingMaterialId=null,this.cullingStrategy=x.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new n.y$,this.onCollisionPositionChangeObservable=new n.y$,this.onMaterialChangedObservable=new n.y$,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=m.Wo.Red(),this.outlineWidth=.02,this.overlayColor=m.Wo.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 r.P(.5,1,.5),this.ellipsoidOffset=new r.P(0,0,0),this.edgesWidth=1,this.edgesColor=new m.HE(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 n.y$,this._onCollisionPositionChange=(e,t,i=null)=>{t.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>o.D.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 u.M(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case s.a.Aggressive:this.doNotSyncBoundingInfo=!0;case s.a.Intermediate: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!==h.Y.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 t of this.subMeshes)t._rebuild()}_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;it.markAsLightDirty(e)))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty((e=>e.markAsAttributesDirty()))}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty((e=>e.markAsMiscDirty()))}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}resetDrawCache(e){if(this.subMeshes)for(const t of this.subMeshes)t.resetDrawCache(e)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,n){return this}updateVerticesData(e,t,i,n){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){var e;return null!==(e=this.rawBoundingInfo)&&void 0!==e?e:this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return null!==this._boundingInfo}buildBoundingInfo(e,t,i){return this._boundingInfo=new d.j(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(a.o.MatricesIndicesKind)&&this.isVerticesDataPresent(a.o.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===h.Y.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 r.y3;(this.rotationQuaternion?this.rotationQuaternion:r._f.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(n);const s=r.P.Zero(),o=this.definedFacingForward?-1:1;return r.P.TransformCoordinatesFromFloatsToRef(e*o,t,i*o,n,s),s}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 r.P(e*n,t,i*n)}refreshBoundingInfo(e=!1,t=!1){return this._boundingInfo&&this._boundingInfo.isLocked||this._refreshBoundingInfo(this._getPositionData(e,t),null),this}_refreshBoundingInfo(e,t){if(e){const i=(0,_.k)(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new d.j(i.minimum,i.maximum)}if(this.subMeshes)for(let i=0;i0){const e=t.getPositions();e&&(i[s]+=(e[s]-i[s])*n)}}if(e++,n===a.o.PositionKind&&this._positions&&3===e){e=0;const n=3*t;this._positions[t++].copyFromFloats(i[n],i[n+1],i[n+2])}}}if(i&&e&&this.skeleton){const e=this.getVerticesData(a.o.MatricesIndicesKind),t=this.getVerticesData(a.o.MatricesWeightsKind);if(t&&e){const s=this.numBoneInfluencers>4,o=s?this.getVerticesData(a.o.MatricesIndicesExtraKind):null,l=s?this.getVerticesData(a.o.MatricesWeightsExtraKind):null,h=this.skeleton.getTransformMatrices(this),c=r.jp.Vector3[0],d=r.jp.Matrix[0],u=r.jp.Matrix[1];let p=0;for(let f=0;f0&&(r.y3.FromFloat32ArrayToRefScaled(h,Math.floor(16*e[p+_]),m,u),d.addToSelf(u));if(s)for(_=0;_<4;_++)m=l[p+_],m>0&&(r.y3.FromFloat32ArrayToRefScaled(h,Math.floor(16*o[p+_]),m,u),d.addToSelf(u));n===a.o.NormalKind?r.P.TransformNormalFromFloatsToRef(i[f],i[f+1],i[f+2],d,c):r.P.TransformCoordinatesFromFloatsToRef(i[f],i[f+1],i[f+2],d,c),c.toArray(i,f),n===a.o.PositionKind&&this._positions&&this._positions[f/3].copyFrom(c)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,a.o.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,a.o.PositionKind)}_getPositionData(e,t){var i;let n=this.getVerticesData(a.o.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),n&&(e&&this.skeleton||t&&this.morphTargetManager)){if(n=n.slice(),this._generatePointsArray(),this._positions){const e=this._positions;this._internalAbstractMeshDataInfo._positions=new Array(e.length);for(let t=0;t1||!n.IsGlobal)&&n.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){const n=this.getBoundingInfo(),s=e.getBoundingInfo();if(n.intersects(s,t))return!0;if(i)for(const r of this.getChildMeshes())if(r.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){var n;if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];const i=e.verticesStart,n=e.verticesStart+e.verticesCount;for(let s=i;s1&&!r._checkCollision(e)||this._collideForSubMesh(r,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=r.jp.Matrix[0],i=r.jp.Matrix[1];return r.y3.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,n=!1,s,o=!1){const a=new c.p,l=this.getClassName(),h="InstancedLinesMesh"===l||"LinesMesh"===l||"GreasedLineMesh"===l?this.intersectionThreshold:0,d=this.getBoundingInfo();if(!this.subMeshes)return a;if(!(o||e.intersectsSphere(d.boundingSphere,h)&&e.intersectsBox(d.boundingBox,h)))return a;if(n)return a.hit=!o,a.pickedMesh=o?null:this,a.distance=o?0:r.P.Distance(e.origin,d.boundingSphere.center),a.subMeshId=0,a;if(!this._generatePointsArray())return a;let u=null;const p=this._scene.getIntersectingSubMeshCandidates(this,e),f=p.length;let _=!1;for(let r=0;r1&&!n.canIntersects(e))continue;const s=n.intersects(e,this._positions,this.getIndices(),t,i);if(s&&(t||!u||s.distance{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 n=this.getScene().getEngine();if(null!==this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,n.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),n.wipeCaches(),this.getScene().removeMesh(this),this._parentContainer){const e=this._parentContainer.meshes.indexOf(this);e>-1&&this._parentContainer.meshes.splice(e,1),this._parentContainer=null}if(t&&this.material&&("MultiMaterial"===this.material.getClassName()?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i65535){t=!0;break}e.depthSortedIndices=t?new Uint32Array(i):new Uint16Array(i)}if(e.facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!e.facetDepthSortFrom){const t=this.getScene().activeCamera;e.facetDepthSortFrom=t?t.position:r.P.Zero()}e.depthSortedFacets=[];for(let t=0;tg.kn?s.maximum.x-s.minimum.x:g.kn,e.bbSize.y=s.maximum.y-s.minimum.y>g.kn?s.maximum.y-s.minimum.y:g.kn,e.bbSize.z=s.maximum.z-s.minimum.z>g.kn?s.maximum.z-s.minimum.z:g.kn;let o=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(o=o>e.bbSize.z?o:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/o),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/o),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/o),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=s,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),r.P.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,n&&l.x.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;ns.subDiv.max||o<0||o>s.subDiv.max||a<0||a>s.subDiv.max?null:s.facetPartitioning[r+s.subDiv.max*o+s.subDiv.max*s.subDiv.max*a]}getClosestFacetAtCoordinates(e,t,i,n,s=!1,o=!0){const a=this.getWorldMatrix(),l=r.jp.Matrix[5];a.invertToRef(l);const h=r.jp.Vector3[8];r.P.TransformCoordinatesFromFloatsToRef(e,t,i,l,h);const c=this.getClosestFacetAtLocalCoordinates(h.x,h.y,h.z,n,s,o);return n&&r.P.TransformCoordinatesFromFloatsToRef(n.x,n.y,n.z,a,n),c}getClosestFacetAtLocalCoordinates(e,t,i,n,s=!1,r=!0){let o=null,a=0,l=0,h=0,c=0,d=0,u=0,p=0,f=0;const _=this.getFacetLocalPositions(),m=this.getFacetLocalNormals(),g=this.getFacetsAtLocalCoordinates(e,t,i);if(!g)return null;let v,T,S,E=Number.MAX_VALUE,x=E;for(let b=0;b=0||s&&!r&&c<=0)&&(c=T.x*S.x+T.y*S.y+T.z*S.z,d=-(T.x*e+T.y*t+T.z*i-c)/(T.x*T.x+T.y*T.y+T.z*T.z),u=e+T.x*d,p=t+T.y*d,f=i+T.z*d,a=u-e,l=p-t,h=f-i,x=a*a+l*l+h*h,xe.emitter===this))}}x.OCCLUSION_TYPE_NONE=0,x.OCCLUSION_TYPE_OPTIMISTIC=1,x.OCCLUSION_TYPE_STRICT=2,x.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,x.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,x.CULLINGSTRATEGY_STANDARD=0,x.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,x.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,x.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,(0,T.H)("BABYLON.AbstractMesh",x)},4106:function(e,t,i){i.d(t,{Z:function(){return _}});var n=i(5412),s=i(2922),r=i(2341),o=i(2186),a=i(4735),l=i(5458),h=i(2789),c=i(8658),d=i(4104),u=i(7303),p=i(5953),f=i(6629);class _{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 _(_.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,n=!1,s=null){this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||p.l.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=n,i?this.setAllVerticesData(i,n):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),s&&(this.applyToMesh(s),s.computeWorldMatrix(!0)))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return 1===this.delayLoadState||0===this.delayLoadState}get doNotSerialize(){for(let e=0;e0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable)),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()}_notifyUpdate(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects();for(const t of this._meshes)t._markSubMeshesAsAttributesDirty()}load(e,t){2!==this.delayLoadState&&(this.isReady()?t&&t():(this.delayLoadState=2,this._queueLoad(e,t)))}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,(i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);const n=this._meshes,s=n.length;for(let e=0;e0){for(let t=0;t0){for(let e=0;e0){for(let e=0;e-1&&this._parentContainer.geometries.splice(e,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new r.x;t.indices=[];const i=this.getIndices();if(i)for(let r=0;r0){const n=new Float32Array(e,i.positionsAttrDesc.offset,i.positionsAttrDesc.count);t.setVerticesData(o.o.PositionKind,n,!1)}if(i.normalsAttrDesc&&i.normalsAttrDesc.count>0){const n=new Float32Array(e,i.normalsAttrDesc.offset,i.normalsAttrDesc.count);t.setVerticesData(o.o.NormalKind,n,!1)}if(i.tangetsAttrDesc&&i.tangetsAttrDesc.count>0){const n=new Float32Array(e,i.tangetsAttrDesc.offset,i.tangetsAttrDesc.count);t.setVerticesData(o.o.TangentKind,n,!1)}if(i.uvsAttrDesc&&i.uvsAttrDesc.count>0){const n=new Float32Array(e,i.uvsAttrDesc.offset,i.uvsAttrDesc.count);if(f.e.UseOpenGLOrientationForUV)for(let e=1;e0){const n=new Float32Array(e,i.uvs2AttrDesc.offset,i.uvs2AttrDesc.count);if(f.e.UseOpenGLOrientationForUV)for(let e=1;e0){const n=new Float32Array(e,i.uvs3AttrDesc.offset,i.uvs3AttrDesc.count);if(f.e.UseOpenGLOrientationForUV)for(let e=1;e0){const n=new Float32Array(e,i.uvs4AttrDesc.offset,i.uvs4AttrDesc.count);if(f.e.UseOpenGLOrientationForUV)for(let e=1;e0){const n=new Float32Array(e,i.uvs5AttrDesc.offset,i.uvs5AttrDesc.count);if(f.e.UseOpenGLOrientationForUV)for(let e=1;e0){const n=new Float32Array(e,i.uvs6AttrDesc.offset,i.uvs6AttrDesc.count);if(f.e.UseOpenGLOrientationForUV)for(let e=1;e0){const n=new Float32Array(e,i.colorsAttrDesc.offset,i.colorsAttrDesc.count);t.setVerticesData(o.o.ColorKind,n,!1,i.colorsAttrDesc.stride)}if(i.matricesIndicesAttrDesc&&i.matricesIndicesAttrDesc.count>0){const n=new Int32Array(e,i.matricesIndicesAttrDesc.offset,i.matricesIndicesAttrDesc.count),s=[];for(let e=0;e>8),s.push((16711680&t)>>16),s.push(t>>24&255)}t.setVerticesData(o.o.MatricesIndicesKind,s,!1)}if(i.matricesIndicesExtraAttrDesc&&i.matricesIndicesExtraAttrDesc.count>0){const n=new Int32Array(e,i.matricesIndicesExtraAttrDesc.offset,i.matricesIndicesExtraAttrDesc.count),s=[];for(let e=0;e>8),s.push((16711680&t)>>16),s.push(t>>24&255)}t.setVerticesData(o.o.MatricesIndicesExtraKind,s,!1)}if(i.matricesWeightsAttrDesc&&i.matricesWeightsAttrDesc.count>0){const n=new Float32Array(e,i.matricesWeightsAttrDesc.offset,i.matricesWeightsAttrDesc.count);t.setVerticesData(o.o.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>8),i.push((16711680&n)>>16),i.push(n>>24&255)}t.setVerticesData(o.o.MatricesIndicesKind,i,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(o.o.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const i=[];for(let t=0;t>8),i.push((16711680&n)>>16),i.push(n>>24&255)}t.setVerticesData(o.o.MatricesIndicesExtraKind,i,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(_._CleanMatricesWeights(e,t),t.setVerticesData(o.o.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(o.o.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let i=0;i-1))return;{const i=t.getScene().getLastSkeletonById(e.skeletonId);if(!i)return;n=i.bones.length}const s=t.getVerticesData(o.o.MatricesIndicesKind),r=t.getVerticesData(o.o.MatricesIndicesExtraKind),a=e.matricesWeights,h=e.matricesWeightsExtra,c=e.numBoneInfluencer,d=a.length;for(let o=0;oc-1)&&(t=c-1),e>i){const t=1/e;for(let e=0;e<4;e++)a[o+e]*=t;if(h)for(let e=0;e<4;e++)h[o+e]*=t}else t>=4?(h[o+t-4]=1-e,r[o+t-4]=n):(a[o+t]=1-e,s[o+t]=n)}t.setVerticesData(o.o.MatricesIndicesKind,s),e.matricesWeightsExtra&&t.setVerticesData(o.o.MatricesIndicesExtraKind,r)}static Parse(e,t,i){const s=new _(e.id,t,void 0,e.updatable);return s._loadedUniqueId=e.uniqueId,d.$&&d.$.AddTagsTo(s,e.tags),e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s._boundingInfo=new h.j(n.P.FromArray(e.boundingBoxMinimum),n.P.FromArray(e.boundingBoxMaximum)),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(o.o.UVKind),e.hasUVs2&&s._delayInfo.push(o.o.UV2Kind),e.hasUVs3&&s._delayInfo.push(o.o.UV3Kind),e.hasUVs4&&s._delayInfo.push(o.o.UV4Kind),e.hasUVs5&&s._delayInfo.push(o.o.UV5Kind),e.hasUVs6&&s._delayInfo.push(o.o.UV6Kind),e.hasColors&&s._delayInfo.push(o.o.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(o.o.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(o.o.MatricesWeightsKind),s._delayLoadingFunction=r.x.ImportVertexData):r.x.ImportVertexData(e,s),t.pushGeometry(s,!0),s}}},2341:function(e,t,i){i.d(t,{x:function(){return u}});var n=i(1069),s=i(5412),r=i(2186),o=i(9069),a=i(2922),l=i(658),h=i(8137),c=i(140),d=i(9714);class u{constructor(){this._applyTo=(0,c.vp)(this._applyToCoroutine.bind(this))}set(e,t){switch(e.length||l.Y.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case r.o.PositionKind:this.positions=e;break;case r.o.NormalKind:this.normals=e;break;case r.o.TangentKind:this.tangents=e;break;case r.o.UVKind:this.uvs=e;break;case r.o.UV2Kind:this.uvs2=e;break;case r.o.UV3Kind:this.uvs3=e;break;case r.o.UV4Kind:this.uvs4=e;break;case r.o.UV5Kind:this.uvs5=e;break;case r.o.UV6Kind:this.uvs6=e;break;case r.o.ColorKind:this.colors=e;break;case r.o.MatricesIndicesKind:this.matricesIndices=e;break;case r.o.MatricesWeightsKind:this.matricesWeights=e;break;case r.o.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case r.o.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){return this.positions&&(e.setVerticesData(r.o.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(r.o.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(r.o.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(r.o.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(r.o.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(r.o.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(r.o.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(r.o.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(r.o.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(r.o.ColorKind,this.colors,t),i&&(yield)),this.matricesIndices&&(e.setVerticesData(r.o.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(r.o.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(r.o.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(r.o.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),this}_update(e,t,i){return this.positions&&e.updateVerticesData(r.o.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(r.o.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(r.o.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(r.o.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(r.o.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(r.o.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(r.o.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(r.o.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(r.o.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(r.o.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(r.o.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(r.o.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(r.o.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(r.o.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,n=e.length){const r=s.jp.Vector3[0],o=s.jp.Vector3[1];for(let a=i;a({vertexData:e}))):[{vertexData:e}];return(0,c.s3)(this._mergeCoroutine(void 0,n,t,!1,i))}*_mergeCoroutine(e,t,i=!1,n,s){var o,a,l,h;this._validate();const c=t.map((e=>e.vertexData));for(const r of c)if(r._validate(),!this.normals!=!r.normals||!this.tangents!=!r.tangents||!this.uvs!=!r.uvs||!this.uvs2!=!r.uvs2||!this.uvs3!=!r.uvs3||!this.uvs4!=!r.uvs4||!this.uvs5!=!r.uvs5||!this.uvs6!=!r.uvs6||!this.colors!=!r.colors||!this.matricesIndices!=!r.matricesIndices||!this.matricesWeights!=!r.matricesWeights||!this.matricesIndicesExtra!=!r.matricesIndicesExtra||!this.matricesWeightsExtra!=!r.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes");const d=c.reduce(((e,t)=>{var i,n;return e+(null!==(n=null===(i=t.indices)||void 0===i?void 0:i.length)&&void 0!==n?n:0)}),null!==(a=null===(o=this.indices)||void 0===o?void 0:o.length)&&void 0!==a?a:0);let p=s||c.some((e=>e.indices===this.indices))?null===(l=this.indices)||void 0===l?void 0:l.slice():this.indices;if(d>0){let s=null!==(h=null==p?void 0:p.length)&&void 0!==h?h:0;if(p||(p=new Array(d)),p.length!==d){if(Array.isArray(p))p.length=d;else{const e=i||p instanceof Uint32Array?new Uint32Array(d):new Uint16Array(d);e.set(p),p=e}e&&e.determinant()<0&&u._FlipFaces(p,0,s)}let r=this.positions?this.positions.length/3:0;for(const{vertexData:e,transform:i}of t)if(e.indices){for(let t=0;t[e.vertexData.positions,e.transform]))),n&&(yield),this.normals=u._MergeElement(r.o.NormalKind,this.normals,e,t.map((e=>[e.vertexData.normals,e.transform]))),n&&(yield),this.tangents=u._MergeElement(r.o.TangentKind,this.tangents,e,t.map((e=>[e.vertexData.tangents,e.transform]))),n&&(yield),this.uvs=u._MergeElement(r.o.UVKind,this.uvs,e,t.map((e=>[e.vertexData.uvs,e.transform]))),n&&(yield),this.uvs2=u._MergeElement(r.o.UV2Kind,this.uvs2,e,t.map((e=>[e.vertexData.uvs2,e.transform]))),n&&(yield),this.uvs3=u._MergeElement(r.o.UV3Kind,this.uvs3,e,t.map((e=>[e.vertexData.uvs3,e.transform]))),n&&(yield),this.uvs4=u._MergeElement(r.o.UV4Kind,this.uvs4,e,t.map((e=>[e.vertexData.uvs4,e.transform]))),n&&(yield),this.uvs5=u._MergeElement(r.o.UV5Kind,this.uvs5,e,t.map((e=>[e.vertexData.uvs5,e.transform]))),n&&(yield),this.uvs6=u._MergeElement(r.o.UV6Kind,this.uvs6,e,t.map((e=>[e.vertexData.uvs6,e.transform]))),n&&(yield),this.colors=u._MergeElement(r.o.ColorKind,this.colors,e,t.map((e=>[e.vertexData.colors,e.transform]))),n&&(yield),this.matricesIndices=u._MergeElement(r.o.MatricesIndicesKind,this.matricesIndices,e,t.map((e=>[e.vertexData.matricesIndices,e.transform]))),n&&(yield),this.matricesWeights=u._MergeElement(r.o.MatricesWeightsKind,this.matricesWeights,e,t.map((e=>[e.vertexData.matricesWeights,e.transform]))),n&&(yield),this.matricesIndicesExtra=u._MergeElement(r.o.MatricesIndicesExtraKind,this.matricesIndicesExtra,e,t.map((e=>[e.vertexData.matricesIndicesExtra,e.transform]))),n&&(yield),this.matricesWeightsExtra=u._MergeElement(r.o.MatricesWeightsExtraKind,this.matricesWeightsExtra,e,t.map((e=>[e.vertexData.matricesWeightsExtra,e.transform]))),this}static _MergeElement(e,t,i,n){const s=n.filter((e=>null!==e[0]&&void 0!==e[0]));if(!t&&0==s.length)return t;if(!t)return this._MergeElement(e,s[0][0],s[0][1],s.slice(1));const o=s.reduce(((e,t)=>e+t[0].length),t.length),a=e===r.o.PositionKind?u._TransformVector3Coordinates:e===r.o.NormalKind?u._TransformVector3Normals:e===r.o.TangentKind?u._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const e=new Float32Array(o);e.set(t),i&&a(e,i,0,t.length);let n=t.length;for(const[t,i]of s)e.set(t,n),i&&a(e,i,n,t.length),n+=t.length;return e}{const e=new Array(o);for(let i=0;i{const i=r.o.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(r.o.PositionKind,this.positions),i=(i,n)=>{const s=e(i,n);if(s!==t)throw new Error("The "+i+"s element count ("+s+") does not match the positions count ("+t+")")};this.normals&&i(r.o.NormalKind,this.normals),this.tangents&&i(r.o.TangentKind,this.tangents),this.uvs&&i(r.o.UVKind,this.uvs),this.uvs2&&i(r.o.UV2Kind,this.uvs2),this.uvs3&&i(r.o.UV3Kind,this.uvs3),this.uvs4&&i(r.o.UV4Kind,this.uvs4),this.uvs5&&i(r.o.UV5Kind,this.uvs5),this.uvs6&&i(r.o.UV6Kind,this.uvs6),this.colors&&i(r.o.ColorKind,this.colors),this.matricesIndices&&i(r.o.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(r.o.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(r.o.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(r.o.MatricesWeightsExtraKind,this.matricesWeightsExtra)}serialize(){const e={};return this.positions&&(e.positions=this.positions),this.normals&&(e.normals=this.normals),this.tangents&&(e.tangents=this.tangents),this.uvs&&(e.uvs=this.uvs),this.uvs2&&(e.uvs2=this.uvs2),this.uvs3&&(e.uvs3=this.uvs3),this.uvs4&&(e.uvs4=this.uvs4),this.uvs5&&(e.uvs5=this.uvs5),this.uvs6&&(e.uvs6=this.uvs6),this.colors&&(e.colors=this.colors),this.matricesIndices&&(e.matricesIndices=this.matricesIndices,e.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=this.matricesWeights),this.matricesIndicesExtra&&(e.matricesIndicesExtra=this.matricesIndicesExtra,e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=this.matricesWeightsExtra),e.indices=this.indices,e}static ExtractFromMesh(e,t,i){return u._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return u._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){const n=new u;return e.isVerticesDataPresent(r.o.PositionKind)&&(n.positions=e.getVerticesData(r.o.PositionKind,t,i)),e.isVerticesDataPresent(r.o.NormalKind)&&(n.normals=e.getVerticesData(r.o.NormalKind,t,i)),e.isVerticesDataPresent(r.o.TangentKind)&&(n.tangents=e.getVerticesData(r.o.TangentKind,t,i)),e.isVerticesDataPresent(r.o.UVKind)&&(n.uvs=e.getVerticesData(r.o.UVKind,t,i)),e.isVerticesDataPresent(r.o.UV2Kind)&&(n.uvs2=e.getVerticesData(r.o.UV2Kind,t,i)),e.isVerticesDataPresent(r.o.UV3Kind)&&(n.uvs3=e.getVerticesData(r.o.UV3Kind,t,i)),e.isVerticesDataPresent(r.o.UV4Kind)&&(n.uvs4=e.getVerticesData(r.o.UV4Kind,t,i)),e.isVerticesDataPresent(r.o.UV5Kind)&&(n.uvs5=e.getVerticesData(r.o.UV5Kind,t,i)),e.isVerticesDataPresent(r.o.UV6Kind)&&(n.uvs6=e.getVerticesData(r.o.UV6Kind,t,i)),e.isVerticesDataPresent(r.o.ColorKind)&&(n.colors=e.getVerticesData(r.o.ColorKind,t,i)),e.isVerticesDataPresent(r.o.MatricesIndicesKind)&&(n.matricesIndices=e.getVerticesData(r.o.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(r.o.MatricesWeightsKind)&&(n.matricesWeights=e.getVerticesData(r.o.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(r.o.MatricesIndicesExtraKind)&&(n.matricesIndicesExtra=e.getVerticesData(r.o.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(r.o.MatricesWeightsExtraKind)&&(n.matricesWeightsExtra=e.getVerticesData(r.o.MatricesWeightsExtraKind,t,i)),n.indices=e.getIndices(t,i),n}static CreateRibbon(e){throw(0,o.S)("ribbonBuilder")}static CreateBox(e){throw(0,o.S)("boxBuilder")}static CreateTiledBox(e){throw(0,o.S)("tiledBoxBuilder")}static CreateTiledPlane(e){throw(0,o.S)("tiledPlaneBuilder")}static CreateSphere(e){throw(0,o.S)("sphereBuilder")}static CreateCylinder(e){throw(0,o.S)("cylinderBuilder")}static CreateTorus(e){throw(0,o.S)("torusBuilder")}static CreateLineSystem(e){throw(0,o.S)("linesBuilder")}static CreateDashedLines(e){throw(0,o.S)("linesBuilder")}static CreateGround(e){throw(0,o.S)("groundBuilder")}static CreateTiledGround(e){throw(0,o.S)("groundBuilder")}static CreateGroundFromHeightMap(e){throw(0,o.S)("groundBuilder")}static CreatePlane(e){throw(0,o.S)("planeBuilder")}static CreateDisc(e){throw(0,o.S)("discBuilder")}static CreatePolygon(e,t,i,n,s,r,a){throw(0,o.S)("polygonBuilder")}static CreateIcoSphere(e){throw(0,o.S)("icoSphereBuilder")}static CreatePolyhedron(e){throw(0,o.S)("polyhedronBuilder")}static CreateCapsule(e={orientation:s.P.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw(0,o.S)("capsuleBuilder")}static CreateTorusKnot(e){throw(0,o.S)("torusKnotBuilder")}static ComputeNormals(e,t,i,n){let r=0,o=0,a=0,l=0,h=0,c=0,d=0,u=0,p=0,f=0,_=0,m=0,g=0,v=0,T=0,S=0,E=0,x=0,b=0,C=0,y=!1,A=!1,R=!1,P=!1,I=1,M=0,O=null;n&&(y=!!n.facetNormals,A=!!n.facetPositions,R=!!n.facetPartitioning,I=!0===n.useRightHandedSystem?-1:1,M=n.ratio||0,P=!!n.depthSort,O=n.distanceTo,P&&void 0===O&&(O=s.P.Zero()));let D=0,N=0,F=0,w=0;for(R&&n&&n.bbSize&&(D=n.subDiv.X*M/n.bbSize.x,N=n.subDiv.Y*M/n.bbSize.y,F=n.subDiv.Z*M/n.bbSize.z,w=n.subDiv.max*n.subDiv.max,n.facetPartitioning.length=0),r=0;r!Array.isArray(e)))],u,"_TransformVector3Coordinates",null),(0,n.gn)([h.G6.filter(((...[e])=>!Array.isArray(e)))],u,"_TransformVector3Normals",null),(0,n.gn)([h.G6.filter(((...[e])=>!Array.isArray(e)))],u,"_TransformVector4Normals",null),(0,n.gn)([h.G6.filter(((...[e])=>!Array.isArray(e)))],u,"_FlipFaces",null)},1298:function(e,t,i){i.d(t,{g:function(){return n}});class n{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}},4735:function(e,t,i){i.d(t,{P:function(){return l}});var n=i(2186),s=i(3573),r=i(2789),o=i(7303),a=i(7050);class l{get materialDefines(){var e;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:null===(e=this._getDrawWrapper())||void 0===e?void 0:e.defines}set materialDefines(e){var t;(null!==(t=this._mainDrawWrapperOverride)&&void 0!==t?t:this._getDrawWrapper(void 0,!0)).defines=e}_getDrawWrapper(e,t=!1){e=null!=e?e:this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new a.q(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){var i;t&&(null===(i=this._drawWrappers[e])||void 0===i||i.dispose()),this._drawWrappers[e]=void 0}get effect(){var e,t;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:null!==(t=null===(e=this._getDrawWrapper())||void 0===e?void 0:e.effect)&&void 0!==t?t:null}get _drawWrapper(){var e;return null!==(e=this._mainDrawWrapperOverride)&&void 0!==e?e:this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,n=!0){const s=this._drawWrapper;s.setEffect(e,t,n),void 0!==i&&(s.materialContext=i),e||(s.defines=null,s.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers){if(void 0!==e)return void this._removeDrawWrapper(e);for(const e of this._drawWrappers)null==e||e.dispose()}this._drawWrappers=[]}static AddToMesh(e,t,i,n,s,r,o,a=!0){return new l(e,t,i,n,s,r,o,a)}constructor(e,t,i,n,s,r,o,a=!0,l=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=n,this.indexCount=s,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=r,this._renderingMesh=o||r,l&&r.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=r.subMeshes.length-1,a&&(this.refreshBoundingInfo(),r.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.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){var t;const i=null!==(t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId))&&void 0!==t?t:this._renderingMesh.material;if(!i)return e?this._mesh.getScene().defaultMaterial:null;if(this._isMultiMaterial(i)){const e=i.getSubMaterial(this.materialIndex);return this._currentMaterial!==e&&(this._currentMaterial=e,this.resetDrawCache()),e}return i}_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(n.o.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;const t=this._renderingMesh.getIndices();let i;if(0===this.indexStart&&this.indexCount===t.length){const e=this._renderingMesh.getBoundingInfo();i={minimum:e.minimum.clone(),maximum:e.maximum.clone()}}else i=(0,o.y)(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new r.j(i.minimum,i.maximum),this}_checkCollision(e){return this.getBoundingInfo()._checkCollision(e)}updateBoundingInfo(e){let t=this.getBoundingInfo();return t||(this.refreshBoundingInfo(),t=this.getBoundingInfo()),t&&t.update(e),this}isInFrustum(e){const t=this.getBoundingInfo();return!!t&&t.isInFrustum(e,this._mesh.cullingStrategy)}isCompletelyInFrustum(e){const t=this.getBoundingInfo();return!!t&&t.isCompletelyInFrustum(e)}render(e){return this._renderingMesh.render(this,e,this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:void 0),this}_getLinesIndexBuffer(e,t){if(!this._linesIndexBuffer){const i=[];for(let t=this.indexStart;ta&&(a=e)}return new l(e,o,a-o+1,t,i,n,s,r)}}},4179:function(e,t,i){i.d(t,{Y:function(){return c}});var n=i(1069),s=i(8137),r=i(8139),o=i(5412),a=i(6387),l=i(5241);const h=o.y3.Compose(o.P.One(),o._f.FromEulerAngles(0,Math.PI,0),o.P.Zero());class c extends a.N{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=0!=(this._billboardMode&c.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!==c.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}get infiniteDistance(){return this._infiniteDistance}set infiniteDistance(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)}constructor(e,t=null,i=!0){super(e,t),this._forward=new o.P(0,0,1),this._up=new o.P(0,1,0),this._right=new o.P(1,0,0),this._position=o.P.Zero(),this._rotation=o.P.Zero(),this._rotationQuaternion=null,this._scaling=o.P.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=c.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=o.y3.Zero(),this._usePivotMatrix=!1,this._absolutePosition=o.P.Zero(),this._absoluteScaling=o.P.Zero(),this._absoluteRotationQuaternion=o._f.Identity(),this._pivotMatrix=o.y3.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new r.y$,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}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._isDirty=!0}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._isDirty=!0}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._isDirty=!0}get forward(){return o.P.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return o.P.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return o.P.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=o.y3.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return this._billboardMode===e.billboardMode&&this._billboardMode===c.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=o.y3.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){const n=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);n&&i&&i(this,n);for(const s of this.getChildTransformNodes(!0))s.instantiateHierarchy(n,t,i);return n}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||o._f.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=o.jp.Matrix[0];this.parent.getWorldMatrix().invertToRef(e),o.P.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=o.P.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=o.jp.Matrix[0];return this._localMatrix.invertToRef(e),o.P.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=o.P.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,n=0,s=l.T.LOCAL){const r=c._LookAtVectorCache,a=s===l.T.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(a,r),this.setDirection(r,t,i,n),s===l.T.WORLD&&this.parent)if(this.rotationQuaternion){const e=o.jp.Matrix[0];this.rotationQuaternion.toRotationMatrix(e);const t=o.jp.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.invert(),e.multiplyToRef(t,e),this.rotationQuaternion.fromRotationMatrix(e)}else{const e=o.jp.Quaternion[0];o._f.FromEulerVectorToRef(this.rotation,e);const t=o.jp.Matrix[0];e.toRotationMatrix(t);const i=o.jp.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=o.P.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return o.P.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,n=0){const s=-Math.atan2(e.z,e.x)+Math.PI/2,r=Math.sqrt(e.x*e.x+e.z*e.z),a=-Math.atan2(e.y,r);return this.rotationQuaternion?o._f.RotationYawPitchRollToRef(s+t,a+i,n,this.rotationQuaternion):(this.rotation.x=a+i,this.rotation.y=s+t,this.rotation.z=n),this}setPivotPoint(e,t=l.T.LOCAL){0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);const i=this.getWorldMatrix();if(t==l.T.WORLD){const t=o.jp.Matrix[0];i.invertToRef(t),e=o.P.TransformCoordinates(e,t)}return this.setPivotMatrix(o.y3.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=o.P.Zero();return this.getPivotPointToRef(e),e}getPivotPointToRef(e){return e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14],this}getAbsolutePivotPoint(){const e=o.P.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),o.P.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=o.jp.Quaternion[0],s=o.jp.Vector3[0],r=o.jp.Vector3[1],a=o.jp.Matrix[1];o.y3.IdentityToRef(a);const l=o.jp.Matrix[0];this.computeWorldMatrix(!0);let h=this.rotationQuaternion;return h||(h=c._TmpRotation,o._f.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,h)),o.y3.ComposeToRef(this.scaling,h,this.position,l),this.parent&&l.multiplyToRef(this.parent.computeWorldMatrix(!0),l),e&&(e.computeWorldMatrix(!0).invertToRef(a),l.multiplyToRef(a,l)),l.decompose(r,n,s,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(n):n.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(r),this.position.copyFrom(s),this.parent=e,i&&this.setPivotMatrix(o.y3.Identity()),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(),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&&i!==l.T.LOCAL){if(this.parent){const t=o.jp.Matrix[0];this.parent.getWorldMatrix().invertToRef(t),e=o.P.TransformNormal(e,t)}n=o._f.RotationAxisToRef(e,t,c._RotationAxisCache),n.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else n=o._f.RotationAxisToRef(e,t,c._RotationAxisCache),this.rotationQuaternion.multiplyToRef(n,this.rotationQuaternion);return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=o._f.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const n=o.jp.Vector3[0],s=o.jp.Vector3[1],r=o.jp.Vector3[2],a=o.jp.Quaternion[0],l=o.jp.Matrix[0],h=o.jp.Matrix[1],c=o.jp.Matrix[2],d=o.jp.Matrix[3];return e.subtractToRef(this.position,n),o.y3.TranslationToRef(n.x,n.y,n.z,l),o.y3.TranslationToRef(-n.x,-n.y,-n.z,h),o.y3.RotationAxisToRef(t,i,c),h.multiplyToRef(c,d),d.multiplyToRef(l,d),d.decompose(s,a,r),this.position.addInPlace(r),a.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){const n=e.scale(t);if(i&&i!==l.T.LOCAL)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=o.jp.Quaternion[1],o._f.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,n));const s=o.jp.Quaternion[0];return o._f.RotationYawPitchRollToRef(t,e,i,s),n.multiplyInPlace(s),this.rotationQuaternion||n.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==c.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}computeWorldMatrix(e=!1,t=null){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;const i=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===i||this.isSynchronized()))return this._currentRenderId=i,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();const n=this._cache;n.pivotMatrixUpdated=!1,n.billboardMode=this.billboardMode,n.infiniteDistance=this.infiniteDistance,n.parent=this._parentNode,this._currentRenderId=i,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;const s=this._getEffectiveParent(),r=c._TmpScaling;let a,l=this._position;if(this._infiniteDistance&&!this.parent&&t){const e=t.getWorldMatrix(),i=new o.P(e.m[12],e.m[13],e.m[14]);l=c._TmpTranslation,l.copyFromFloats(this._position.x+i.x,this._position.y+i.y,this._position.z+i.z)}if(r.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(o._f.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))}}else a=c._TmpRotation,o._f.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,a);if(this._usePivotMatrix){const e=o.jp.Matrix[1];o.y3.ScalingToRef(r.x,r.y,r.z,e);const t=o.jp.Matrix[0];a.toRotationMatrix(t),this._pivotMatrix.multiplyToRef(e,o.jp.Matrix[4]),o.jp.Matrix[4].multiplyToRef(t,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(l.x,l.y,l.z)}else o.y3.ComposeToRef(r,a,l,this._localMatrix);if(s&&s.getWorldMatrix){if(e&&s.computeWorldMatrix(e),n.useBillboardPath){this._transformToBoneReferal?s.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),o.jp.Matrix[7]):o.jp.Matrix[7].copyFrom(s.getWorldMatrix());const e=o.jp.Vector3[5],t=o.jp.Vector3[6],i=o.jp.Quaternion[0];o.jp.Matrix[7].decompose(t,i,e),o.y3.ScalingToRef(t.x,t.y,t.z,o.jp.Matrix[7]),o.jp.Matrix[7].setTranslation(e),c.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(i,e),this._localMatrix.setTranslation(e)),this._localMatrix.multiplyToRef(o.jp.Matrix[7],this._worldMatrix)}else this._transformToBoneReferal?(this._localMatrix.multiplyToRef(s.getWorldMatrix(),o.jp.Matrix[6]),o.jp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)):this._localMatrix.multiplyToRef(s.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(n.useBillboardPath&&t&&this.billboardMode&&!n.useBillboardPosition){const e=o.jp.Vector3[0];if(this._worldMatrix.getTranslationToRef(e),o.jp.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&o.jp.Matrix[1].multiplyToRef(h,o.jp.Matrix[1]),o.jp.Matrix[1].setTranslationFromFloats(0,0,0),o.jp.Matrix[1].invertToRef(o.jp.Matrix[0]),(this.billboardMode&c.BILLBOARDMODE_ALL)!==c.BILLBOARDMODE_ALL){o.jp.Matrix[0].decompose(void 0,o.jp.Quaternion[0],void 0);const e=o.jp.Vector3[1];o.jp.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&c.BILLBOARDMODE_X)!==c.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&c.BILLBOARDMODE_Y)!==c.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&c.BILLBOARDMODE_Z)!==c.BILLBOARDMODE_Z&&(e.z=0),o.y3.RotationYawPitchRollToRef(e.y,e.x,e.z,o.jp.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(o.jp.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(o.jp.Vector3[0])}else if(n.useBillboardPath&&t&&n.useBillboardPosition){const e=o.jp.Vector3[0];this._worldMatrix.getTranslationToRef(e);const i=t.globalPosition;this._worldMatrix.invertToRef(o.jp.Matrix[1]);const n=o.jp.Vector3[1];o.P.TransformCoordinatesToRef(i,o.jp.Matrix[1],n),n.normalize();const s=-Math.atan2(n.z,n.x)+Math.PI/2,r=Math.sqrt(n.x*n.x+n.z*n.z),a=-Math.atan2(n.y,r);if(o._f.RotationYawPitchRollToRef(s,a,0,o.jp.Quaternion[0]),(this.billboardMode&c.BILLBOARDMODE_ALL)!==c.BILLBOARDMODE_ALL){const e=o.jp.Vector3[1];o.jp.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&c.BILLBOARDMODE_X)!==c.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&c.BILLBOARDMODE_Y)!==c.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&c.BILLBOARDMODE_Z)!==c.BILLBOARDMODE_Z&&(e.z=0),o.y3.RotationYawPitchRollToRef(e.y,e.x,e.z,o.jp.Matrix[0])}else o.y3.FromQuaternionToRef(o.jp.Quaternion[0],o.jp.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(o.jp.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(o.jp.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):s&&s._nonUniformScaling?this._updateNonUniformScalingState(s._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._isAbsoluteSynced=!1,this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=o.y3.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const e=this.getChildren();for(let t=0;tnew c(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;inew c(e.name,t)),e,t,i);return e.localMatrix?n.setPreTransformMatrix(o.y3.FromArray(e.localMatrix)):e.pivotMatrix&&n.setPivotMatrix(o.y3.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),n}getChildTransformNodes(e,t){const i=[];return this._getDescendants(i,e,(e=>(!t||t(e))&&e instanceof c)),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,s=null;t&&(this.rotationQuaternion?(s=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(n=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const r=this.getHierarchyBoundingVectors(e,i),o=r.max.subtract(r.min),a=Math.max(o.x,o.y,o.z);if(0===a)return this;const l=1/a;return this.scaling.scaleInPlace(l),t&&(this.rotationQuaternion&&s?this.rotationQuaternion.copyFrom(s):this.rotation&&n&&this.rotation.copyFrom(n)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}c.BILLBOARDMODE_NONE=0,c.BILLBOARDMODE_X=1,c.BILLBOARDMODE_Y=2,c.BILLBOARDMODE_Z=4,c.BILLBOARDMODE_ALL=7,c.BILLBOARDMODE_USE_POSITION=128,c.BillboardUseParentOrientation=!1,c._TmpRotation=o._f.Zero(),c._TmpScaling=o.P.Zero(),c._TmpTranslation=o.P.Zero(),c._LookAtVectorCache=new o.P(0,0,0),c._RotationAxisCache=new o._f,(0,n.gn)([(0,s.hd)("position")],c.prototype,"_position",void 0),(0,n.gn)([(0,s.hd)("rotation")],c.prototype,"_rotation",void 0),(0,n.gn)([(0,s.mv)("rotationQuaternion")],c.prototype,"_rotationQuaternion",void 0),(0,n.gn)([(0,s.hd)("scaling")],c.prototype,"_scaling",void 0),(0,n.gn)([(0,s.qC)("billboardMode")],c.prototype,"_billboardMode",void 0),(0,n.gn)([(0,s.qC)()],c.prototype,"scalingDeterminant",void 0),(0,n.gn)([(0,s.qC)("infiniteDistance")],c.prototype,"_infiniteDistance",void 0),(0,n.gn)([(0,s.qC)()],c.prototype,"ignoreNonUniformScaling",void 0),(0,n.gn)([(0,s.qC)()],c.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0)},5776:function(e,t,i){i.d(t,{q:function(){return n}});class n{static Eval(e,t){return"true"===(e=e.match(/\([^()]*\)/g)?e.replace(/\([^()]*\)/g,(e=>(e=e.slice(1,e.length-1),n._HandleParenthesisContent(e,t)))):n._HandleParenthesisContent(e,t))||"false"!==e&&n.Eval(e,t)}static _HandleParenthesisContent(e,t){let i;t=t||(e=>"true"===e);const s=e.split("||");for(const r in s)if(Object.prototype.hasOwnProperty.call(s,r)){let e=n._SimplifyNegation(s[r].trim());const o=e.split("&&");if(o.length>1)for(let s=0;s(e=e.replace(/[\s]/g,(()=>""))).length%2?"!":""))).trim())?e="false":"!false"===e&&(e="true"),e}}},2554:function(e,t,i){i.d(t,{B:function(){return n},M:function(){return r}});class n{static BuildArray(e,t){const i=[];for(let n=0;nfunction(e,t,i){const n=e[t];if("function"!=typeof n)return null;const s=function(){const n=e.length,r=s.previous.apply(e,arguments);return i(t,n),r};return n.next=s,s.previous=n,e[t]=s,()=>{const i=s.previous;if(!i)return;const n=s.next;n?(i.next=n,n.previous=i):(i.next=void 0,e[t]=i),s.next=void 0,s.previous=void 0}}(e,i,t)));return()=>{i.forEach((e=>{null==e||e()}))}}},140:function(e,t,i){function n(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(n){i(n)}}function s(e=25){let t;return(i,s,r)=>{const o=performance.now();void 0===t||o-t>e?(t=o,setTimeout((()=>{n(i,s,r)}),0)):n(i,s,r)}}function r(e,t,i,n,s){const r=()=>{let o;const a=e=>{e.done?i(e.value):void 0===o?o=!0:r()};do{o=void 0,s&&s.aborted?n(new Error("Aborted")):t(e,a,n),void 0===o&&(o=!1)}while(o)};r()}function o(e,t){let i;return r(e,n,(e=>i=e),(e=>{throw e}),t),i}function a(e,t,i){return new Promise(((n,s)=>{r(e,t,n,s,i)}))}function l(e,t){return(...i)=>o(e(...i),t)}i.d(t,{KO:function(){return s},WP:function(){return n},s3:function(){return o},sM:function(){return a},vp:function(){return l}})},8137:function(e,t,i){i.d(t,{G6:function(){return R},N$:function(){return S},QC:function(){return g},RR:function(){return T},VE:function(){return y},XX:function(){return E},hd:function(){return v},mv:function(){return b},n9:function(){return _},oQ:function(){return C},oU:function(){return f},p4:function(){return A},qC:function(){return p},qQ:function(){return m},rX:function(){return x},wz:function(){return u}});var n=i(4104),s=i(5412),r=i(9069),o=i(2922);const a={},l={},h=function(e,t,i,s={}){const r=e();n.$&&n.$.HasTags(t)&&n.$.AddTagsTo(r,n.$.GetTags(t,!0));const o=c(r),a={};for(const n in o){const e=o[n],l=t[n],h=e.type;if(null!=l&&("uniqueId"!==n||A.AllowLoadingUniqueId))switch(h){case 0:case 6:case 11:r[n]=l;break;case 1:s.cloneTexturesOnlyOnce&&a[l.uniqueId]?r[n]=a[l.uniqueId]:(r[n]=i||l.isRenderTarget?l:l.clone(),a[l.uniqueId]=r[n]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:r[n]=i?l:l.clone()}}return r};function c(e){const t=e.getClassName();if(l[t])return l[t];l[t]={};const i=l[t];let n=e,s=t;for(;s;){const e=a[s];for(const n in e)i[n]=e[n];let t,r=!1;do{if(t=Object.getPrototypeOf(n),!t.getClassName){r=!0;break}if(t.getClassName()!==s)break;n=t}while(t);if(r)break;s=t.getClassName(),n=t}return i}function d(e,t){return(i,n)=>{const s=function(e){const t=e.getClassName();return a[t]||(a[t]={}),a[t]}(i);s[n]||(s[n]={type:e,sourceName:t})}}function u(e,t=null){return function(e,t=null){return(i,n)=>{const s=t||"_"+n;Object.defineProperty(i,n,{get:function(){return this[s]},set:function(t){"function"==typeof this.equals&&this.equals(t)||this[s]!==t&&(this[s]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}(e,t)}function p(e){return d(0,e)}function f(e){return d(1,e)}function _(e){return d(2,e)}function m(e){return d(3,e)}function g(e){return d(4,e)}function v(e){return d(5,e)}function T(e){return d(6,e)}function S(e){return d(7,e)}function E(e){return d(8,e)}function x(e){return d(9,e)}function b(e){return d(10,e)}function C(e){return d(12,e)}function y(e){return d(11,e)}class A{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{let r=s;if("undefined"!=typeof _native&&_native[t]){const e=_native[t];r=n?(...t)=>n(...t)?e(...t):s(...t):e}return e[t]=r,r(...i)}}A.AllowLoadingUniqueId=!1,A._ImageProcessingConfigurationParser=e=>{throw(0,r.S)("ImageProcessingConfiguration")},A._FresnelParametersParser=e=>{throw(0,r.S)("FresnelParameters")},A._ColorCurvesParser=e=>{throw(0,r.S)("ColorCurves")},A._TextureParser=(e,t,i)=>{throw(0,r.S)("Texture")},R.filter=function(e){return(t,i,n)=>R(t,i,n,e)}},2827:function(e,t,i){i.d(t,{j:function(){return r}});var n=i(658);const s=(e,t)=>e?e.getClassName&&"Mesh"===e.getClassName()?null:!e.getClassName||"SubMesh"!==e.getClassName()&&"PhysicsBody"!==e.getClassName()?e.clone?e.clone():Array.isArray(e)?e.slice():null:e.clone(t):null;class r{static DeepCopy(e,t,i,r){const o=function(e){const t=[];do{Object.getOwnPropertyNames(e).forEach((function(e){-1===t.indexOf(e)&&t.push(e)}))}while(e=Object.getPrototypeOf(e));return t}(e);for(const l of o){if("_"===l[0]&&(!r||-1===r.indexOf(l)))continue;if(l.endsWith("Observable"))continue;if(i&&-1!==i.indexOf(l))continue;const o=e[l],h=typeof o;if("function"!==h)try{if("object"===h)if(o instanceof Uint8Array)t[l]=Uint8Array.from(o);else if(o instanceof Array){if(t[l]=[],o.length>0)if("object"==typeof o[0])for(let e=0;e(e.__proto__=t,e));const s={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class r extends n{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",n._setPrototypeOf(this,r.prototype)}}},9051:function(e,t,i){i.d(t,{$K:function(){return I},$M:function(){return E},FV:function(){return y},Ip:function(){return b},VL:function(){return R},eh:function(){return m},r6:function(){return x},rN:function(){return T},vP:function(){return C}});var n=i(4910),s=i(1102),r=i(8139),o=i(3392),a=i(5077),l=i(9714),h=i(8661),c=i(3525),d=i(9271),u=i(5953),p=i(658),f=i(9447);const _=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class m extends l.LH{constructor(e,t){super(e,l.SM.LoadFileError),this.name="LoadFileError",l.GU._setPrototypeOf(this,m.prototype),t instanceof n.g?this.request=t:this.file=t}}class g extends l.LH{constructor(e,t){super(e,l.SM.RequestFileError),this.request=t,this.name="RequestFileError",l.GU._setPrototypeOf(this,g.prototype)}}class v extends l.LH{constructor(e,t){super(e,l.SM.ReadFileError),this.file=t,this.name="ReadFileError",l.GU._setPrototypeOf(this,v.prototype)}}const T={DefaultRetryStrategy:a.b.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:e=>e},S=e=>e=e.replace(/#/gm,"%23"),E=(e,t)=>{if((!e||0!==e.indexOf("data:"))&&T.CorsBehavior)if("string"==typeof T.CorsBehavior||T.CorsBehavior instanceof String)t.crossOrigin=T.CorsBehavior;else{const i=T.CorsBehavior(e);i&&(t.crossOrigin=i)}},x=(e,t,i,n,s="",r)=>{var a;let l,c=!1;e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"undefined"!=typeof Blob&&"undefined"!=typeof URL?(l=URL.createObjectURL(new Blob([e],{type:s})),c=!0):l=`data:${s};base64,`+(0,h.Gh)(e):e instanceof Blob?(l=URL.createObjectURL(e),c=!0):(l=S(e),l=T.PreprocessUrl(e));const d=u.l.LastCreatedEngine,p=t=>{if(i){const n=l||e.toString();i(`Error while trying to load image: ${0===n.indexOf("http")||n.length<=128?n:n.slice(0,128)+"..."}`,t)}};if("undefined"==typeof Image||null!==(a=null==d?void 0:d._features.forceBitmapOverHTMLImageElement)&&void 0!==a&&a)return C(l,(n=>{d.createImageBitmap(new Blob([n],{type:s}),Object.assign({premultiplyAlpha:"none"},r)).then((e=>{t(e),c&&URL.revokeObjectURL(l)})).catch((t=>{i&&i("Error while trying to load image: "+e,t)}))}),void 0,n||void 0,!0,((e,t)=>{p(t)})),null;const f=new Image;E(l,f);const _=[],m=()=>{_.forEach((e=>{e.target.removeEventListener(e.name,e.handler)})),_.length=0};_.push({target:f,name:"load",handler:()=>{m(),t(f),c&&f.src&&URL.revokeObjectURL(f.src)}}),_.push({target:f,name:"error",handler:e=>{m(),p(e),c&&f.src&&URL.revokeObjectURL(f.src)}}),_.push({target:document,name:"securitypolicyviolation",handler:e=>{if(e.blockedURI!==f.src)return;m();const t=new Error(`CSP violation of policy ${e.effectiveDirective} ${e.blockedURI}. Current policy is ${e.originalPolicy}`);u.l.UseFallbackTexture=!1,p(t),c&&f.src&&URL.revokeObjectURL(f.src),f.src=""}}),_.forEach((e=>{e.target.addEventListener(e.name,e.handler)}));const g="blob:"===l.substring(0,5),v="data:"===l.substring(0,5),x=()=>{g||v?f.src=l:C(l,((e,t,i)=>{const n=new Blob([e],{type:!s&&i?i:s}),r=URL.createObjectURL(n);c=!0,f.src=r}),void 0,n||void 0,!0,((e,t)=>{p(t)}))},b=()=>{n&&n.loadImage(l,f)};if(!g&&!v&&n&&n.enableTexturesOffline)n.open(b,x);else{if(-1!==l.indexOf("file:")){const e=decodeURIComponent(l.substring(5).toLowerCase());if(o.X.FilesToLoad[e]&&"undefined"!=typeof URL){try{let t;try{t=URL.createObjectURL(o.X.FilesToLoad[e])}catch(y){t=URL.createObjectURL(o.X.FilesToLoad[e])}f.src=t,c=!0}catch(A){f.src=""}return f}}x()}return f},b=(e,t,i,n,s)=>{const o=new FileReader,a={onCompleteObservable:new r.y$,abort:()=>o.abort()};return o.onloadend=()=>a.onCompleteObservable.notifyObservers(a),s&&(o.onerror=()=>{s(new v(`Unable to read ${e.name}`,e))}),o.onload=e=>{t(e.target.result)},i&&(o.onprogress=i),n?o.readAsArrayBuffer(e):o.readAsText(e),a},C=(e,t,i,n,s,a,l)=>{if(e.name)return b(e,t,i,s,a?e=>{a(void 0,e)}:void 0);const h=e;if(-1!==h.indexOf("file:")){let e=decodeURIComponent(h.substring(5).toLowerCase());0===e.indexOf("./")&&(e=e.substring(2));const n=o.X.FilesToLoad[e];if(n)return b(n,t,i,s,a?e=>a(void 0,new m(e.message,e.file)):void 0)}const{match:c,type:d}=P(h);if(c){const e={onCompleteObservable:new r.y$,abort:()=>()=>{}};try{const e=s?I(h):M(h);t(e,void 0,d)}catch(u){a?a(void 0,u):p.Y.Error(u.message||"Failed to parse the Data URL")}return f.Q.SetImmediate((()=>{e.onCompleteObservable.notifyObservers(e)})),e}return y(h,((e,i)=>{t(e,null==i?void 0:i.responseURL,null==i?void 0:i.getResponseHeader("content-type"))}),i,n,s,a?e=>{a(e.request,new m(e.message,e.request))}:void 0,l)},y=(e,t,i,o,a,l,h)=>{e=S(e),e=T.PreprocessUrl(e);const c=T.BaseUrl+e;let d=!1;const u={onCompleteObservable:new r.y$,abort:()=>d=!0},f=()=>{let e,r=new n.g,o=null;const f=()=>{r&&(i&&r.removeEventListener("progress",i),e&&r.removeEventListener("readystatechange",e),r.removeEventListener("loadend",_))};let _=()=>{f(),u.onCompleteObservable.notifyObservers(u),u.onCompleteObservable.clear(),i=void 0,e=null,_=null,l=void 0,h=void 0,t=void 0};u.abort=()=>{d=!0,_&&_(),r&&r.readyState!==(XMLHttpRequest.DONE||4)&&r.abort(),null!==o&&(clearTimeout(o),o=null),r=null};const m=e=>{const t=e.message||"Unknown error";l&&r?l(new g(t,r)):p.Y.Error(t)},v=u=>{if(r){if(r.open("GET",c),h)try{h(r)}catch(p){return void m(p)}a&&(r.responseType="arraybuffer"),i&&r.addEventListener("progress",i),_&&r.addEventListener("loadend",_),e=()=>{if(!d&&r&&r.readyState===(XMLHttpRequest.DONE||4)){if(e&&r.removeEventListener("readystatechange",e),r.status>=200&&r.status<300||0===r.status&&(!(0,s.CG)()||A())){try{t&&t(a?r.response:r.responseText,r)}catch(p){m(p)}return}const i=T.DefaultRetryStrategy;if(i){const e=i(c,r,u);if(-1!==e)return f(),r=new n.g,void(o=setTimeout((()=>v(u+1)),e))}const h=new g("Error status: "+r.status+" "+r.statusText+" - Unable to load "+c,r);l&&l(h)}},r.addEventListener("readystatechange",e),r.send()}};v(0)};if(o&&o.enableSceneOffline){const n=e=>{e&&e.status>400?l&&l(e):f()},s=()=>{o&&o.loadFile(T.BaseUrl+e,(e=>{!d&&t&&t(e),u.onCompleteObservable.notifyObservers(u)}),i?e=>{!d&&i&&i(e)}:void 0,n,a)};o.open(s,n)}else f();return u},A=()=>"undefined"!=typeof location&&"file:"===location.protocol,R=e=>_.test(e),P=e=>{const t=_.exec(e);if(null===t||0===t.length)return{match:!1,type:""};return{match:!0,type:t[0].replace("data:","").replace("base64,","")}};function I(e){return(0,h.HQ)(e.split(",")[1])}const M=e=>(0,h.rP)(e.split(",")[1]);let O;d.B._FileToolsLoadImage=x,d.B._FileToolsLoadFile=C,c.L._FileToolsLoadFile=C;((e,t,i,n,s,r,o,a,l,h)=>{O={DecodeBase64UrlToBinary:e,DecodeBase64UrlToString:t,DefaultRetryStrategy:i.DefaultRetryStrategy,BaseUrl:i.BaseUrl,CorsBehavior:i.CorsBehavior,PreprocessUrl:i.PreprocessUrl,IsBase64DataUrl:n,IsFileURL:s,LoadFile:r,LoadImage:o,ReadFile:a,RequestFile:l,SetCorsBehavior:h},Object.defineProperty(O,"DefaultRetryStrategy",{get:function(){return i.DefaultRetryStrategy},set:function(e){i.DefaultRetryStrategy=e}}),Object.defineProperty(O,"BaseUrl",{get:function(){return i.BaseUrl},set:function(e){i.BaseUrl=e}}),Object.defineProperty(O,"PreprocessUrl",{get:function(){return i.PreprocessUrl},set:function(e){i.PreprocessUrl=e}}),Object.defineProperty(O,"CorsBehavior",{get:function(){return i.CorsBehavior},set:function(e){i.CorsBehavior=e}})})(I,M,T,R,A,C,x,b,y,E)},3392:function(e,t,i){i.d(t,{X:function(){return n}});class n{}n.FilesToLoad={}},3706:function(e,t,i){function n(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}i.d(t,{f:function(){return n}})},6448:function(e,t,i){i.d(t,{K:function(){return r}});var n=i(658),s=i(646);class r{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=(0,s.q)(e);if(t)return t;n.Y.Warn(e+" not found, you may have missed an import.");const i=e.split(".");let r=window||this;for(let n=0,s=i.length;ne<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){if(void 0!==i&&!n._CheckLimit(t,i))return;const s=n._FormatMessage(t),r=this._Levels[e];r.logFunc&&r.logFunc("BJS - "+s);const o=`
${s}

`;n._AddLogEntry(o),n._GenerateLimitMessage(t,e)}static get LogCache(){return n._LogCache}static ClearLogCache(){n._LogCache="",n._LogLimitOutputs={},n.errorsCount=0}static set LogLevels(e){n.Log=n._LogDisabled,n.Warn=n._LogDisabled,n.Error=n._LogDisabled,[n.MessageLogLevel,n.WarningLogLevel,n.ErrorLogLevel].forEach((t=>{if((e&t)===t){const e=this._Levels[t];n[e.name]=n._LogEnabled.bind(n,t)}}))}}n.NoneLogLevel=0,n.MessageLogLevel=1,n.WarningLogLevel=2,n.ErrorLogLevel=4,n.AllLogLevel=7,n.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",n._LogCache="",n._LogLimitOutputs={},n._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],n.errorsCount=0,n.Log=n._LogEnabled.bind(n,n.MessageLogLevel),n.Warn=n._LogEnabled.bind(n,n.WarningLogLevel),n.Error=n._LogEnabled.bind(n,n.ErrorLogLevel)},8139:function(e,t,i){i.d(t,{he:function(){return n},y$:function(){return r}});class n{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 s{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(){this._remove&&this._remove()}}class r{static FromPromise(e,t){const i=new r;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 n(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,n=null,r=!1){if(!e)return null;const o=new s(e,t,n);return o.unregisterOnNextCall=r,i?this._observers.unshift(o):this._observers.push(o),this._onObserverAdded&&this._onObserverAdded(o),this._hasNotified&&this.notifyIfTriggered&&void 0!==this._lastNotifiedValue&&this.notifyObserver(o,this._lastNotifiedValue),o._remove=()=>{this.remove(o)},o}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._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,s){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;const r=this._eventState;r.mask=t,r.target=i,r.currentTarget=n,r.skipNextObservers=!1,r.lastReturnValue=e,r.userInfo=s;for(const o of this._observers)if(!o._willBeUnregistered&&(o.mask&t&&(o.unregisterOnNextCall&&this._deferUnregister(o),o.scope?r.lastReturnValue=o.callback.apply(o.scope,[e,r]):r.lastReturnValue=o.callback(e,r)),r.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 r;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}}},8482:function(e,t,i){i.d(t,{z:function(){return s}});var n=i(9665);class s{get min(){return this._min}get max(){return this._max}get average(){return this._average}get lastSecAverage(){return this._lastSecAverage}get current(){return this._current}get total(){return this._totalAccumulated}get count(){return this._totalValueCount}constructor(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}fetchNewFrame(){this._totalValueCount++,this._current=0,this._lastSecValueCount++}addCount(e,t){s.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){s.Enabled&&(this._startMonitoringTime=n.F.Now)}endMonitoring(e=!0){if(!s.Enabled)return;e&&this.fetchNewFrame();const t=n.F.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=n.F.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}s.Enabled=!0},4441:function(e,t,i){i.d(t,{A:function(){return s}});var n=i(9665);class s{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new r(e)}sampleFrame(e=n.F.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 r{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}}},9665:function(e,t,i){i.d(t,{F:function(){return s}});var n=i(1102);class s{static get Now(){return n.MZ.IsWindowObjectExist()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}},5077:function(e,t,i){i.d(t,{b:function(){return n}});class n{static ExponentialBackoff(e=3,t=500){return(i,n,s)=>0!==n.status||s>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,s)*t}}},8173:function(e,t,i){i.d(t,{f:function(){return s},t:function(){return n}});class n{constructor(e){this.length=0,this.data=new Array(e),this._id=n._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;tthis.data.length&&(this.data.length=2*(this.length+e.length));for(let t=0;t=this.length?-1:t}contains(e){return-1!==this.indexOf(e)}}n._GlobalId=0;class s extends n{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;tthis.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}}},8661:function(e,t,i){i.d(t,{Gh:function(){return s},HQ:function(){return o},fJ:function(){return n},rP:function(){return r}});const n=e=>{if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let i=0;i{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let i,n,s,r,o,a,l,h="",c=0;const d=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(;c>2,o=(3&i)<<4|n>>4,a=(15&n)<<2|s>>6,l=63&s,isNaN(n)?a=l=64:isNaN(s)&&(l=64),h+=t.charAt(r)+t.charAt(o)+t.charAt(a)+t.charAt(l);return h},r=e=>atob(e),o=e=>{const t=r(e),i=t.length,n=new Uint8Array(new ArrayBuffer(i));for(let s=0;ss.HasTags(e),e.addTags=t=>s.AddTagsTo(e,t),e.removeTags=t=>s.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>s.MatchesQuery(e,t)}static DisableFor(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery}static HasTags(e){if(!e._tags)return!1;const t=e._tags;for(const i in t)if(Object.prototype.hasOwnProperty.call(t,i))return!0;return!1}static GetTags(e,t=!0){if(!e._tags)return null;if(t){const 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){s._AddTagTo(e,t)}))}static _AddTagTo(e,t){""!==(t=t.trim())&&"true"!==t&&"false"!==t&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(s.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!s.HasTags(e))return;const i=t.split(" ");for(const n in i)s._RemoveTagFrom(e,i[n])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return void 0===t||(""===t?s.HasTags(e):n.q.Eval(t,(t=>s.HasTags(e)&&e._tags[t])))}}},9447:function(e,t,i){i.d(t,{Q:function(){return s}});var n=i(1102);class s{static SetImmediate(e){(0,n.CG)()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}},8658:function(e,t,i){i.d(t,{$g:function(){return m},w1:function(){return _}});var n=i(8139),s=i(1102),r=i(658),o=i(2827),a=i(9665),l=i(9069),h=i(4910),c=i(5953),d=i(9051),u=i(9447),p=i(6448),f=i(3706);class _{static get BaseUrl(){return d.rN.BaseUrl}static set BaseUrl(e){d.rN.BaseUrl=e}static get DefaultRetryStrategy(){return d.rN.DefaultRetryStrategy}static set DefaultRetryStrategy(e){d.rN.DefaultRetryStrategy=e}static get CorsBehavior(){return d.rN.CorsBehavior}static set CorsBehavior(e){d.rN.CorsBehavior=e}static get UseFallbackTexture(){return c.l.UseFallbackTexture}static set UseFallbackTexture(e){c.l.UseFallbackTexture=e}static get RegisteredExternalClasses(){return p.K.RegisteredExternalClasses}static set RegisteredExternalClasses(e){p.K.RegisteredExternalClasses=e}static get fallbackTexture(){return c.l.FallbackTexture}static set fallbackTexture(e){c.l.FallbackTexture=e}static FetchToRef(e,t,i,n,s,r){const o=4*((Math.abs(e)*i%i|0)+(Math.abs(t)*n%n|0)*i);r.r=s[o]/255,r.g=s[o+1]/255,r.b=s[o+2]/255,r.a=s[o+3]/255}static Mix(e,t,i){return e*(1-i)+t*i}static Instantiate(e){return p.K.Instantiate(e)}static SetImmediate(e){u.Q.SetImmediate(e)}static IsExponentOfTwo(e){let t=1;do{t*=2}while(t{(0,d.vP)(e,(e=>{i(e)}),void 0,void 0,t,((e,t)=>{n(t)}))}))}static LoadScript(e,t,i,n){if("function"==typeof importScripts){try{importScripts(e),t()}catch(a){null==i||i(`Unable to load script '${e}' in worker`,a)}return}if(!(0,s.CG)())return void(null==i||i(`Cannot load script '${e}' outside of a window or a worker`));const r=document.getElementsByTagName("head")[0],o=document.createElement("script");o.setAttribute("type","text/javascript"),o.setAttribute("src",e),n&&(o.id=n),o.onload=()=>{t&&t()},o.onerror=t=>{i&&i(`Unable to load script '${e}'`,t)},r.appendChild(o)}static LoadScriptAsync(e){return new Promise(((t,i)=>{this.LoadScript(e,(()=>{t()}),((e,t)=>{i(t||new Error(e))}))}))}static ReadFileAsDataURL(e,t,i){const s=new FileReader,r={onCompleteObservable:new n.y$,abort:()=>s.abort()};return s.onloadend=()=>{r.onCompleteObservable.notifyObservers(r)},s.onload=e=>{t(e.target.result)},s.onprogress=i,s.readAsDataURL(e),r}static ReadFile(e,t,i,n,s){return(0,d.Ip)(e,t,i,n,s)}static FileAsURL(e){const t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,n){o.j.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 n=0;n{const n=atob(this.toDataURL(t,i).split(",")[1]),s=n.length,r=new Uint8Array(s);for(let e=0;et(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"}_.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,s){if("string"!=typeof n&&t){if(t){if(_._IsOffScreenCanvas(e))return void e.convertToBlob({type:i,quality:s}).then((e=>{const i=new FileReader;i.readAsDataURL(e),i.onloadend=()=>{const e=i.result;t(e)}}));const n=e.toDataURL(i,s);t(n)}}else this.ToBlob(e,(function(e){e&&_.DownloadBlob(e,n),t&&t("")}),i,s)}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,s="image/png",r=!1,o){throw(0,l.S)("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,n="image/png",s){throw(0,l.S)("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,n,s="image/png",r=1,o=!1,a,h=!1,c=!1,d=!0,u){throw(0,l.S)("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,n="image/png",s=1,r=!1,o,a=!1,h=!1,c=!0,d){throw(0,l.S)("ScreenshotTools")}static RandomId(){return(0,f.f)()}static IsBase64(e){return(0,d.VL)(e)}static DecodeBase64(e){return(0,d.$K)(e)}static get errorsCount(){return r.Y.errorsCount}static Log(e){r.Y.Log(e)}static Warn(e){r.Y.Warn(e)}static Error(e){r.Y.Error(e)}static get LogCache(){return r.Y.LogCache}static ClearLogCache(){r.Y.ClearLogCache()}static set LogLevels(e){r.Y.LogLevels=e}static set PerformanceLogLevel(e){return(e&_.PerformanceUserMarkLogLevel)===_.PerformanceUserMarkLogLevel?(_.StartPerformanceCounter=_._StartUserMark,void(_.EndPerformanceCounter=_._EndUserMark)):(e&_.PerformanceConsoleLogLevel)===_.PerformanceConsoleLogLevel?(_.StartPerformanceCounter=_._StartPerformanceConsole,void(_.EndPerformanceCounter=_._EndPerformanceConsole)):(_.StartPerformanceCounter=_._StartPerformanceCounterDisabled,void(_.EndPerformanceCounter=_._EndPerformanceCounterDisabled))}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!_._Performance){if(!(0,s.CG)())return;_._Performance=window.performance}t&&_._Performance.mark&&_._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){t&&_._Performance.mark&&(_._Performance.mark(e+"-End"),_._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(_._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(_._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return a.F.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 s=t?e:Object.getPrototypeOf(e);i=s.constructor.__bjsclassName__,n=s.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!!(0,s.up)()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}}_.UseCustomRequestHeaders=!1,_.CustomRequestHeaders=h.g.CustomRequestHeaders,_._TmpFloatArray=new Float32Array(1),_.GetDOMTextContent=s.v,_.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.")},_.NoneLogLevel=r.Y.NoneLogLevel,_.MessageLogLevel=r.Y.MessageLogLevel,_.WarningLogLevel=r.Y.WarningLogLevel,_.ErrorLogLevel=r.Y.ErrorLogLevel,_.AllLogLevel=r.Y.AllLogLevel,_.IsWindowObjectExist=s.CG,_.PerformanceNoneLogLevel=0,_.PerformanceUserMarkLogLevel=1,_.PerformanceConsoleLogLevel=2,_.StartPerformanceCounter=_._StartPerformanceCounterDisabled,_.EndPerformanceCounter=_._EndPerformanceCounterDisabled;class m{constructor(e,t,i,n=0){this.iterations=e,this.index=n-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1{s&&s()?n.breakLoop():setTimeout((()=>{for(let r=0;r=e)break;if(i(o),s&&s()){n.breakLoop();break}}n.executeNext()}),r)}),n)}}c.l.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"},646:function(e,t,i){i.d(t,{H:function(){return s},q:function(){return r}});const n={};function s(e,t){n[e]=t}function r(e){return n[e]}},8501:function(e,t,i){i.d(t,{K:function(){return n}});class n{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}n._UniqueIdCounter=1},4910:function(e,t,i){i.d(t,{g:function(){return n}});class n{constructor(){this._xhr="undefined"!=typeof _native&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest,this._requestURL=""}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(const e in n.CustomRequestHeaders){const t=n.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return n.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){n.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(const i of n.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;i(this._xhr,t)}return 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)}}n.CustomRequestHeaders={},n.CustomRequestModifiers=new Array,n.SkipRequestModificationForBabylonCDN=!0},9093:function(e,t,i){i.d(t,{O:function(){return s}});var n=i(2186);class s{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[n.o.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[n.o.PositionKind]=new n.o(this._scene.getEngine(),e,n.o.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[n.o.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,s=0,r=!1){var o;const a=this._scene.getEngine();for(let l=0;lnull!=e))).length||!this._scene.postProcessesEnabled)return;const a=this._scene.getEngine();for(let l=0,h=n.length;lt._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamerat._distanceToCamera?1:0}static PainterSortCompare(e,t){const i=e.getMesh(),n=t.getMesh();return i.material&&n.material?i.material.uniqueId-n.material.uniqueId:i.uniqueId-n.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,i){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._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;ie=e.concat(t.bones))),e}}n._BabylonFileParsers={},n._IndividualBabylonFileParsers={}},6387:function(e,t,i){i.d(t,{N:function(){return c}});var n=i(1069),s=i(5412),r=i(8137),o=i(8139),a=i(5953),l=i(9069);class h{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new o.y$,this._onClonedObservable=new o.y$}}class c{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,n){const s=this._NodeConstructors[e];return s?s(t,i,n):null}set accessibilityTag(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)}get accessibilityTag(){return this._accessibilityTag}get doNotSerialize(){return!!this._nodeDataStorage._doNotSerialize||!!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._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){this._isDirty=!1,this._nodeDataStorage=new h,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new o.y$,this._parentContainer=null,this.animations=new Array,this._ranges={},this.onReady=null,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._waitingParentInstanceIndex=null,this._waitingParsedUniqueId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=s.y3.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new o.y$,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||a.l.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache()}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={},this._cache.parent=void 0}updateCache(e){!e&&this.isSynchronized()||(this._cache.parent=this.parent,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._cache.parent!==this._parentNode?(this._cache.parent=this._parentNode,!1):!(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(!t||t(e))&&void 0!==e.cullingStrategy)),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){e!==this._nodeDataStorage._isReady&&(e?(this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0):this._nodeDataStorage._isReady=!1)}getAnimationByName(e){for(let t=0;tnew c(e,this.getScene())),this);if(t&&(n.parent=t),!i){const t=this.getDescendants(!0);for(let i=0;i{throw(0,l.S)("AnimationRange")},c._NodeConstructors={},(0,n.gn)([(0,r.qC)()],c.prototype,"name",void 0),(0,n.gn)([(0,r.qC)()],c.prototype,"id",void 0),(0,n.gn)([(0,r.qC)()],c.prototype,"uniqueId",void 0),(0,n.gn)([(0,r.qC)()],c.prototype,"state",void 0),(0,n.gn)([(0,r.qC)()],c.prototype,"metadata",void 0)},4559:function(e,t,i){i.d(t,{H:function(){return s},l:function(){return n}});class n{}n.NAME_EFFECTLAYER="EffectLayer",n.NAME_LAYER="Layer",n.NAME_LENSFLARESYSTEM="LensFlareSystem",n.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer",n.NAME_PARTICLESYSTEM="ParticleSystem",n.NAME_GAMEPAD="Gamepad",n.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue",n.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer",n.NAME_PREPASSRENDERER="PrePassRenderer",n.NAME_DEPTHRENDERER="DepthRenderer",n.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer",n.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager",n.NAME_SPRITE="Sprite",n.NAME_SUBSURFACE="SubSurface",n.NAME_OUTLINERENDERER="Outline",n.NAME_PROCEDURALTEXTURE="ProceduralTexture",n.NAME_SHADOWGENERATOR="ShadowGenerator",n.NAME_OCTREE="Octree",n.NAME_PHYSICSENGINE="PhysicsEngine",n.NAME_AUDIO="Audio",n.NAME_FLUIDRENDERER="FluidRenderer",n.STEP_ISREADYFORMESH_EFFECTLAYER=0,n.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0,n.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0,n.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0,n.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1,n.STEP_BEFORECAMERADRAW_PREPASS=0,n.STEP_BEFORECAMERADRAW_EFFECTLAYER=1,n.STEP_BEFORECAMERADRAW_LAYER=2,n.STEP_BEFORERENDERTARGETDRAW_PREPASS=0,n.STEP_BEFORERENDERTARGETDRAW_LAYER=1,n.STEP_BEFORERENDERINGMESH_PREPASS=0,n.STEP_BEFORERENDERINGMESH_OUTLINE=1,n.STEP_AFTERRENDERINGMESH_PREPASS=0,n.STEP_AFTERRENDERINGMESH_OUTLINE=1,n.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0,n.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1,n.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0,n.STEP_BEFORECAMERAUPDATE_GAMEPAD=1,n.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0,n.STEP_BEFORECLEAR_PREPASS=1,n.STEP_BEFORERENDERTARGETCLEAR_PREPASS=0,n.STEP_AFTERRENDERTARGETDRAW_PREPASS=0,n.STEP_AFTERRENDERTARGETDRAW_LAYER=1,n.STEP_AFTERCAMERADRAW_PREPASS=0,n.STEP_AFTERCAMERADRAW_EFFECTLAYER=1,n.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2,n.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3,n.STEP_AFTERCAMERADRAW_LAYER=4,n.STEP_AFTERCAMERADRAW_FLUIDRENDERER=5,n.STEP_AFTERCAMERAPOSTPROCESS_LAYER=0,n.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER=0,n.STEP_AFTERRENDER_AUDIO=0,n.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0,n.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1,n.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2,n.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3,n.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0,n.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER=1,n.STEP_POINTERMOVE_SPRITE=0,n.STEP_POINTERDOWN_SPRITE=0,n.STEP_POINTERUP_SPRITE=0;class s extends Array{constructor(e){super(...e)}static Create(){return Object.create(s.prototype)}registerStep(e,t,i){let n=0,s=Number.MAX_VALUE;for(;n=0;a--)(s=e[a])&&(o=(r<3?s(o):r>3?s(t,i,o):s(t,i))||o);return r>3&&o&&Object.defineProperty(t,i,o),o}Object.create;Object.create}},n={};function s(e){var t=n[e];if(void 0!==t)return t.exports;var r=n[e]={exports:{}};return i[e](r,r.exports,s),r.exports}s.m=i,s.x=function(){var e=s.O(void 0,[315,568,770,942],(function(){return s(4201)}));return e=s.O(e)},e=[],s.O=function(t,i,n,r){if(!i){var o=1/0;for(c=0;c=r)&&Object.keys(s.O).every((function(e){return s.O[e](i[l])}))?i.splice(l--,1):(a=!1,r0&&e[c-1][2]>r;c--)e[c]=e[c-1];e[c]=[i,n,r]},s.d=function(e,t){for(var i in t)s.o(t,i)&&!s.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},s.f={},s.e=function(e){return Promise.all(Object.keys(s.f).reduce((function(t,i){return s.f[i](e,t),t}),[]))},s.u=function(e){return{315:"c2b82a6e",568:"87a06baf",770:"088d5a4e",942:"256b551e"}[e]+"-"+{315:"1e3631aca5d8280099d6",568:"5d3ac30d48950f0f9b7a",770:"4f2cb64570bdf3425971",942:"1832dd584c826cd29ac8"}[e]+".js"},s.miniCssF=function(e){},s.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},s.p="https://codecave.pro-new/",function(){var e={475:1};s.f.i=function(t,i){e[t]||importScripts(s.p+s.u(t))};var t=self.webpackChunkcode_cave=self.webpackChunkcode_cave||[],i=t.push.bind(t);t.push=function(t){var n=t[0],r=t[1],o=t[2];for(var a in r)s.o(r,a)&&(s.m[a]=r[a]);for(o&&o(s);n.length;)e[n.pop()]=1;i(t)}}(),t=s.x,s.x=function(){return Promise.all([315,568,770,942].map(s.e,s)).then(t)};s.x()}(); +//# sourceMappingURL=475-1b51ef15275da40692d5.js.map \ No newline at end of file diff --git a/475-f022f6fdbc411815273f.js.map b/475-1b51ef15275da40692d5.js.map similarity index 99% rename from 475-f022f6fdbc411815273f.js.map rename to 475-1b51ef15275da40692d5.js.map index 41876a91..c419b142 100644 --- a/475-f022f6fdbc411815273f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ACA,EACD,EACA,GACCA,EACD,EACA,GACC,GACA,EACD,EACA,GACC,EACD,GACC,EACD,EACA,EACA,EACAA,EACA,EACA,EACA,EACA,EACA,GACC,GACA,EACD,EACA,GACC,EACD,GACC,GAGC,EAAc,CAChB,EAAG,GAAI,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,GAAI,GAAI,GAAI,GAAI,EAAG,EAAG,GAAI,EAAG,GAAI,EAAG,GAAI,GAAI,GAAI,GAAI,GAAI,EAAG,EAAG,EAAG,EAAG,GAAI,GAAI,EAAG,GAAI,EAAG,EAAG,GAAI,GAAI,EAAG,GAAI,EAAG,GAAI,EAAG,EAAG,EAAG,EAAG,GAAI,EAAG,GAAI,GACxK,GAAI,EAAG,GAAI,GAAI,GAAI,EAAG,GAAI,EAAG,EAAG,GAG9B,EAAsB,CACxB,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,GACA,GAEA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,GACA,IAGE,EAAe,CACjB,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EAEA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,GAgDE,EAAS,CACX,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,GAEE,EAAU,IAAI,MACd,EAAY,IAAI,MAChB,EAAU,IAAI,MACd,EAAM,IAAI,MAChB,IAAI,EAAiB,EAErB,MAAM,EAAkB,IAAI,MAAM,GAC5B,EAAiB,IAAI,MAAM,GACjC,IAAI,EACJ,IAAK,EAAO,EAAG,EAAO,EAAG,IACrB,EAAgB,GAAQ,EAAyB,EAAE,OAC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K,UAAU,EAAI,EAAqB,EAC7J,C,KAGI,eAAe,KAAK,SAAS,EAAI,KAAK,mBAAoB,KAAK,SAAS,EAAI,KAAK,mBAAoB,KAAK,SAAS,EAAI,KAAK,oBAGhI,KAAK,qBAGL,GAFA,KAAK,oBAAoB,UAAW,EACpC,EAAW,KAAK,oBACZ,KAAK,0CAA2C,CACpC,KAAK,SAAS,kBAEtB,KAAK,oBAAoB,gBAAgB,EAAqE,GAAG,qBAAqB,KAAK,UAAU,EAAG,KAAK,UAAU,EAAG,KAAK,UAAU,IACzL,KAAK,UAAU,eAAe,EAAG,EAAG,GAE5C,O,iBAIA,EAAqE,GAAG,0BAA0B,KAAK,UAAU,EAAG,KAAK,UAAU,EAAG,KAAK,UAAU,EAAG,G,iFCpCxJ,MAAM,EAAiB,EAAqE,GAAG,OAAO,GACtG,EAAS,iBAAiB,GAE1B,KAAD,6C,6JCFE,KAAK,aAAa,yBAAyB,EAAY,EAAG,EAAY,EAAG,EAAY,E","sources":["webpack://code-cave/./node_modules/@babylonjs/core/Actions/action.js","webpack://code-cave/./node_modules/@babylonjs/core/Actions/condition.js","webpack://code-cave/./node_modules/@babylonjs/core/Actions/directActions.js","webpack://code-cave/./node_modules/@babylonjs/core/Actions/actionManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Actions/directAudioActions.js","webpack://code-cave/./node_modules/@babylonjs/core/Animations/animationKey.js","webpack://code-cave/./node_modules/@babylonjs/core/Animations/animationRange.js","webpack://code-cave/./node_modules/@babylonjs/core/Maths/math.size.js","webpack://code-cave/./node_modules/@babylonjs/core/Animations/animation.js","webpack://code-cave/./node_modules/@babylonjs/core/Actions/interpolateValueAction.js","webpack://code-cave/./node_modules/@babylonjs/core/Animations/runtimeAnimation.js","webpack://code-cave/./node_modules/@babylonjs/core/Bones/bone.js","webpack://code-cave/./node_modules/@babylonjs/core/Animations/animatable.js","webpack://code-cave/./node_modules/@babylonjs/core/Maths/math.path.js","webpack://code-cave/./node_modules/@babylonjs/core/Animations/easing.js","webpack://code-cave/./node_modules/@babylonjs/core/Animations/animationEvent.js","webpack://code-cave/./node_modules/@babylonjs/core/Animations/animationGroup.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/instancedMesh.js","webpack://code-cave/./node_modules/@babylonjs/core/Lights/light.js","webpack://code-cave/./node_modules/@babylonjs/core/assetContainer.js","webpack://code-cave/./node_modules/@babylonjs/core/Audio/audioEngine.js","webpack://code-cave/./node_modules/@babylonjs/core/Audio/sound.js","webpack://code-cave/./node_modules/@babylonjs/core/Audio/soundTrack.js","webpack://code-cave/./node_modules/@babylonjs/core/Audio/audioSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Audio/weightedsound.js","webpack://code-cave/./node_modules/@babylonjs/core/BakedVertexAnimation/bakedVertexAnimationManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/thinTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/baseTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/copyTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/texture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.rawTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/rawTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Behaviors/Cameras/autoRotationBehavior.js","webpack://code-cave/./node_modules/@babylonjs/core/Behaviors/Cameras/bouncingBehavior.js","webpack://code-cave/./node_modules/@babylonjs/core/Behaviors/Cameras/framingBehavior.js","webpack://code-cave/./node_modules/@babylonjs/core/Culling/ray.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/pivotTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/planeBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Behaviors/Meshes/pointerDragBehavior.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/webXRFeaturesManager.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRAbstractFeature.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v1/physicsJoint.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v1/physicsImpostor.js","webpack://code-cave/./node_modules/@babylonjs/core/Loading/sceneLoader.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Enums/nodeMaterialBlockTargets.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/pushMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/nodeMaterialBuildState.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/nodeMaterialBuildStateSharedData.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/nodeMaterialBlockConnectionPoint.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/nodeMaterialDecorator.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/nodeMaterialBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/transformBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Vertex/vertexOutputBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Enums/nodeMaterialBlockConnectionPointMode.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Enums/nodeMaterialSystemValues.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/fragmentOutputBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Input/animatedInputBlockTypes.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Input/inputBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/currentScreenBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Particle/particleTextureBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Particle/particleRampGradientBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Particle/particleBlendMultiplyBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/effectFallbacks.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/postprocess.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/renderTargetWrapper.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGL/webGLRenderTargetWrapper.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.renderTarget.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/postProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Enums/nodeMaterialModes.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/vectorMergerBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/remapBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/multiplyBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/EmitterTypes/boxParticleEmitter.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/EmitterTypes/coneParticleEmitter.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/EmitterTypes/cylinderParticleEmitter.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/EmitterTypes/hemisphericParticleEmitter.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/EmitterTypes/IParticleEmitterType.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/EmitterTypes/pointParticleEmitter.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/EmitterTypes/sphereParticleEmitter.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/EmitterTypes/customParticleEmitter.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/EmitterTypes/meshParticleEmitter.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/EmitterTypes/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/baseParticleSystem.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/colorSplitterBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.renderTargetCube.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/effectRenderer.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/pass.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/dumpTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/renderTargetTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Procedurals/proceduralTextureSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/procedural.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Procedurals/proceduralTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/trigonometryBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/nodeMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/icoSphereBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRHandTracking.js","webpack://code-cave/./node_modules/@babylonjs/core/Behaviors/Meshes/handConstraintBehavior.js","webpack://code-cave/./node_modules/@babylonjs/core/Bones/boneIKController.js","webpack://code-cave/./node_modules/@babylonjs/core/Bones/boneLookController.js","webpack://code-cave/./node_modules/@babylonjs/core/Bones/skeleton.js","webpack://code-cave/./node_modules/@babylonjs/core/Bones/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Buffers/storageBuffer.js","webpack://code-cave/./node_modules/@babylonjs/core/Buffers/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/BaseCameraMouseWheelInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/BaseCameraPointersInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/cameraInputsManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/gamepad.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/arcRotateCameraGamepadInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/arcRotateCameraKeyboardMoveInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/arcRotateCameraMouseWheelInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/arcRotateCameraPointersInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/arcRotateCameraInputsManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/arcRotateCameraVRDeviceOrientationInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/flyCameraKeyboardInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/flyCameraMouseInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/followCameraKeyboardMoveInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/followCameraMouseWheelInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/followCameraPointersInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/freeCameraKeyboardMoveInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/freeCameraMouseInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/freeCameraMouseWheelInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/freeCameraTouchInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/freeCameraInputsManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/freeCameraDeviceOrientationInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/freeCameraGamepadInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/virtualJoystick.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/Controllers/poseEnabledController.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/xboxGamepad.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/dualShockGamepad.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/freeCameraVirtualJoystickInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/targetCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/freeCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/touchCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/arcRotateCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/deviceOrientationCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/flyCameraInputsManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/flyCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/followCameraInputsManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/followCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/gamepadManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/gamepadSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/universalCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/gamepadCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/passCube.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/passPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/anaglyphPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/RigModes/stereoscopicAnaglyphRigMode.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Stereoscopic/anaglyphArcRotateCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Stereoscopic/anaglyphFreeCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Stereoscopic/anaglyphGamepadCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Stereoscopic/anaglyphUniversalCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/stereoscopicInterlace.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/stereoscopicInterlacePostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/RigModes/stereoscopicRigMode.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Stereoscopic/stereoscopicArcRotateCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Stereoscopic/stereoscopicFreeCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Stereoscopic/stereoscopicGamepadCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Stereoscopic/stereoscopicUniversalCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Stereoscopic/stereoscopicScreenUniversalCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/VR/vrCameraMetrics.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/vrDistortionCorrection.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/vrDistortionCorrectionPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/vrMultiviewToSingleview.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/MultiviewRenderTarget.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.multiview.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/RigModes/vrRigMode.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/vrMultiviewToSingleviewPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/VR/vrDeviceOrientationArcRotateCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/VR/vrDeviceOrientationFreeCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/VR/vrDeviceOrientationGamepadCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Lights/hemisphericLight.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/RigModes/webVRRigMode.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.webVR.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/VR/webVRCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/Controllers/webVRController.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/prePassConfiguration.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/materialFlags.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/decalFragmentDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/defaultFragmentDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/sceneUboDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/meshUboDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/defaultUboDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/prePassDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/lightFragmentDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/lightUboDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowsFragmentFunctions.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/imageProcessingFunctions.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/bumpFragmentMainFunctions.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/fogFragmentDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/decalFragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/depthPrePass.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/lightFragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/lightVxFragmentDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/lightVxUboDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertexGlobalDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertexDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/bakedVertexAnimation.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/prePassVertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/vertexColorMixing.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pointCloudVertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/default.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/materialPluginManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/materialPluginBase.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/material.detailMapConfiguration.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/standardMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.dynamicTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/dynamicTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/imageProcessing.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/imageProcessingPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/webXRLayerWrapper.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/webXRRenderTargetTextureProvider.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/webXRWebGLLayer.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/webXRManagedOutputCanvas.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/native/nativeXRRenderTarget.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/webXRSessionManager.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/webXRTypes.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/cylinderBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/torusBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/groundMesh.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/groundBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/VR/vrExperienceHelper.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/VR/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/RigModes/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Collisions/collider.js","webpack://code-cave/./node_modules/@babylonjs/core/Collisions/collisionCoordinator.js","webpack://code-cave/./node_modules/@babylonjs/core/Collisions/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Compute/computeEffect.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.computeShader.js","webpack://code-cave/./node_modules/@babylonjs/core/Compute/computeShader.js","webpack://code-cave/./node_modules/@babylonjs/core/Compute/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Culling/Octrees/octreeBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Culling/Octrees/octree.js","webpack://code-cave/./node_modules/@babylonjs/core/Culling/Octrees/octreeSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Culling/Octrees/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Culling/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/utilityLayerRenderer.js","webpack://code-cave/./node_modules/@babylonjs/core/Gizmos/gizmo.js","webpack://code-cave/./node_modules/@babylonjs/core/Debug/axesViewer.js","webpack://code-cave/./node_modules/@babylonjs/core/Gizmos/axisDragGizmo.js","webpack://code-cave/./node_modules/@babylonjs/core/Debug/boneAxesViewer.js","webpack://code-cave/./node_modules/@babylonjs/core/Debug/debugLayer.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/boxBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/ribbonBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/torusKnotBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/sphereBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/capsuleBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/discBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/tiledPlaneBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/shaderMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/color.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/color.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/linesMesh.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/linesBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/polygonMesh.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/polygonBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/shapeBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/latheBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/tubeBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/polyhedronBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/decalBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Maths/math.isovector.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/geodesicMesh.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/geodesicBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/goldbergMesh.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/goldbergBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/textBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/meshBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Debug/physicsViewer.js","webpack://code-cave/./node_modules/@babylonjs/core/Debug/rayHelper.js","webpack://code-cave/./node_modules/@babylonjs/core/Debug/skeletonViewer.js","webpack://code-cave/./node_modules/@babylonjs/core/Debug/ISkeletonViewer.js","webpack://code-cave/./node_modules/@babylonjs/core/Debug/directionalLightFrustumViewer.js","webpack://code-cave/./node_modules/@babylonjs/core/Debug/index.js","webpack://code-cave/./node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceTypes.js","webpack://code-cave/./node_modules/@babylonjs/core/DeviceInput/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/constants.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/nullEngine.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.debugging.js","webpack://code-cave/./node_modules/@babylonjs/core/Instrumentation/timeToken.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.query.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.videoTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.multiRender.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.cubeTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.textureSampler.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.views.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/rgbdTextureTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/HighDynamicRange/cubemapToSphericalPolynomial.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/baseTexture.polynomial.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/rgbdEncode.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/environmentTextureTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/codeStringParsingTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Processors/shaderCodeInliner.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Native/nativePipelineContext.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Native/nativeRenderTargetWrapper.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Native/nativeHardwareTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/nativeEngine.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Native/validatedNativeDataStream.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Native/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuConstants.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuShaderProcessor.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuPipelineContext.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuShaderProcessingContext.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuShaderProcessorsGLSL.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bonesDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bonesVertex.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bakedVertexAnimationDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bakedVertexAnimation.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneFragment.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneFragmentDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneVertex.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneVertexDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/instancesDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/instancesVertex.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/meshUboDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertex.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertexDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertexGlobal.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertexGlobalDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/sceneUboDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuShaderProcessorsWGSL.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuHardwareTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuTextureHelper.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/WebGPU/webgpuDataBuffer.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuBufferManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuRenderPassWrapper.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuCacheSampler.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuCacheRenderPipeline.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuCacheRenderPipelineTree.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuStencilStateComposer.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuDepthCullingState.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/externalTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuMaterialContext.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuDrawContext.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuCacheBindGroups.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/clearQuad.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/clearQuad.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuClearQuad.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuBundleList.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuQuerySet.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuTimestampQuery.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuOcclusionQuery.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuTintWASM.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuSnapshotRendering.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/postprocess.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/webgpuEngine.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.alpha.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuComputeContext.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuComputePipelineContext.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.computeShader.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.cubeTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.debugging.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.dynamicBuffer.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.dynamicTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.externalTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuExternalTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.multiRender.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.query.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.rawTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuRenderTargetWrapper.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.readTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.renderTarget.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.renderTargetCube.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.textureSampler.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.storageBuffer.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.uniformBuffer.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.videoTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/IPipelineContext.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/ICanvas.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/engineFeatures.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/engineFactory.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/IMaterialContext.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/IDrawContext.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Processors/iShaderProcessor.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Events/clipboardEvents.js","webpack://code-cave/./node_modules/@babylonjs/core/Events/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/Controllers/daydreamController.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/Controllers/gearVRController.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/Controllers/genericController.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/Controllers/oculusTouchController.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/Controllers/viveController.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/Controllers/windowsMotionController.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/Controllers/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Gizmos/axisScaleGizmo.js","webpack://code-cave/./node_modules/@babylonjs/core/Gizmos/boundingBoxGizmo.js","webpack://code-cave/./node_modules/@babylonjs/core/Gizmos/planeRotationGizmo.js","webpack://code-cave/./node_modules/@babylonjs/core/Gizmos/rotationGizmo.js","webpack://code-cave/./node_modules/@babylonjs/core/Gizmos/planeDragGizmo.js","webpack://code-cave/./node_modules/@babylonjs/core/Gizmos/positionGizmo.js","webpack://code-cave/./node_modules/@babylonjs/core/Gizmos/scaleGizmo.js","webpack://code-cave/./node_modules/@babylonjs/core/Gizmos/gizmoManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Lights/spotLight.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/cubeTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/backgroundFragmentDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/backgroundUboDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/background.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/backgroundVertexDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/background.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Background/backgroundMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Helpers/environmentHelper.js","webpack://code-cave/./node_modules/@babylonjs/core/Helpers/textureDome.js","webpack://code-cave/./node_modules/@babylonjs/core/Helpers/photoDome.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/brdfTextureTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/PBR/pbrBRDFConfiguration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrFragmentDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrFragmentSamplersDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/subSurfaceScatteringFunctions.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrHelperFunctions.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/hdrFilteringFunctions.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrDirectLightingFunctions.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrIBLFunctions.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockAlbedoOpacity.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockReflectivity.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockAmbientOcclusion.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockAlphaFresnel.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockAnisotropic.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockReflection.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockSheen.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockClearcoat.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockIridescence.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockSubSurface.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockNormalGeometric.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockNormalFinal.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockLightmapInit.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockGeometryInfo.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockReflectance0.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockReflectance.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockDirectLighting.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockFinalLitComponents.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockFinalUnlitComponents.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockFinalColorComposition.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockImageProcessing.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrDebug.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/pbr.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrVertexDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/pbr.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/PBR/pbrClearCoatConfiguration.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/PBR/pbrIridescenceConfiguration.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/PBR/pbrAnisotropicConfiguration.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/PBR/pbrSheenConfiguration.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/PBR/pbrSubSurfaceConfiguration.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/PBR/pbrBaseMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/PBR/pbrMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/dds.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Loaders/ddsTextureLoader.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Loaders/envTextureLoader.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/khronosTextureContainer.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/workerPool.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/ktx2decoderTypes.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/khronosTextureContainer2.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Loaders/ktxTextureLoader.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/webXRCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/webXRExperienceHelper.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/motionController/webXRControllerComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/motionController/webXRAbstractMotionController.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/motionController/webXRGenericMotionController.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/motionController/webXRProfiledMotionController.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/motionController/webXRMotionControllerManager.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/webXRInputSource.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/webXRInput.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRControllerPointerSelection.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/subMesh.project.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRNearInteraction.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/webXREnterExitUI.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/timer.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRControllerTeleportation.js","webpack://code-cave/./node_modules/@babylonjs/core/Helpers/sceneHelpers.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/webXRDefaultExperience.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/videoTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Helpers/videoDome.js","webpack://code-cave/./node_modules/@babylonjs/core/Helpers/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Instrumentation/engineInstrumentation.js","webpack://code-cave/./node_modules/@babylonjs/core/Instrumentation/sceneInstrumentation.js","webpack://code-cave/./node_modules/@babylonjs/core/Instrumentation/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/glowMapGeneration.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/glowMapGeneration.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Layers/effectLayer.js","webpack://code-cave/./node_modules/@babylonjs/core/Layers/effectLayerSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/glowMapMerge.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/glowMapMerge.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Layers/glowLayer.js","webpack://code-cave/./node_modules/@babylonjs/core/Layers/layerSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/glowBlurPostProcess.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Layers/highlightLayer.js","webpack://code-cave/./node_modules/@babylonjs/core/Layers/layer.js","webpack://code-cave/./node_modules/@babylonjs/core/Layers/index.js","webpack://code-cave/./node_modules/@babylonjs/core/LensFlares/lensFlare.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/lensFlare.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/lensFlare.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/LensFlares/lensFlareSystem.js","webpack://code-cave/./node_modules/@babylonjs/core/LensFlares/lensFlareSystemSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/LensFlares/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/bayerDitherFunctions.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapFragmentExtraDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexNormalBias.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexMetric.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapFragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/shadowMap.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/sceneVertexDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/meshVertexDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapUboDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexExtraDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/shadowMap.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/depthBoxBlur.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Lights/Shadows/shadowGenerator.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapFragmentSoftTransparentShadow.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/depth.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/depth.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/depthRenderer.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/minmaxRedux.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/minMaxReducer.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/depthReducer.js","webpack://code-cave/./node_modules/@babylonjs/core/Lights/Shadows/cascadedShadowGenerator.js","webpack://code-cave/./node_modules/@babylonjs/core/Lights/Shadows/shadowGeneratorSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Lights/Shadows/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Lights/pointLight.js","webpack://code-cave/./node_modules/@babylonjs/core/Lights/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Loading/loadingScreen.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/HighDynamicRange/panoramaToCubemap.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/HighDynamicRange/hdr.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/hdrFiltering.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/hdrFiltering.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Filtering/hdrFiltering.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/hdrCubeTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Morph/morphTarget.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/rawTexture2DArray.js","webpack://code-cave/./node_modules/@babylonjs/core/Morph/morphTargetManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/physicsRaycastResult.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v1/physicsEngine.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v1/Plugins/cannonJSPlugin.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v1/Plugins/oimoJSPlugin.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v1/Plugins/ammoJSPlugin.js","webpack://code-cave/./node_modules/@babylonjs/core/Probes/reflectionProbe.js","webpack://code-cave/./node_modules/@babylonjs/core/Loading/Plugins/babylonFileLoader.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/iEffectFallbacks.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/fresnelParameters.js","webpack://code-cave/./node_modules/@babylonjs/core/Loading/Plugins/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Loading/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Background/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Occlusion/occlusionMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/PBR/pbrBaseSimpleMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/PBR/pbrMetallicRoughnessMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/PBR/pbrSpecularGlossinessMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/PBR/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/colorGradingTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/equiRectangularCubeTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/htmlElementTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/internalTextureLoader.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/tga.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Loaders/tgaTextureLoader.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Loaders/hdrTextureLoader.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/basis.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Loaders/basisTextureLoader.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Loaders/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/multiRenderTarget.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Packer/frame.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Packer/packer.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Packer/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Procedurals/customProceduralTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/noise.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Procedurals/noiseProceduralTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Procedurals/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/rawCubeTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/rawTexture3D.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/refractionTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/thinRenderTargetTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Enums/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/nodeMaterialConnectionPointCustomObject.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Vertex/bonesBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Vertex/instancesBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Vertex/morphTargetsBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Vertex/lightInformationBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Vertex/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/imageProcessingBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/TBNBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/perturbNormalBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/discardBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/frontFacingBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/derivativeBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/fragCoordBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/screenSizeBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/screenSpaceBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/twirlBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/heightToNormalBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/fragDepthBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/shadowMapBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/fogBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/lightBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/imageSourceBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/textureBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/reflectionTextureBaseBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/reflectionTextureBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/sceneDepthBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/clipPlanesBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Input/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/addBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/crossBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/customBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/dotBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/colorMergerBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/vectorSplitterBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/lerpBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/stepBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/divideBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/subtractBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/oneMinusBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/viewDirectionBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/fresnelBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/maxBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/negateBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/minBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/distanceBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/lengthBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/powBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/randomNumberBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/arcTan2Block.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/smoothStepBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/reciprocalBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/replaceColorBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/posterizeBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/waveBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/gradientBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/nLerpBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/worleyNoise3DBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/simplexPerlin3DBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/normalBlendBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/rotate2dBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/reflectBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/refractBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/sheenBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/desaturateBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/anisotropyBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/reflectionBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/iridescenceBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/clearCoatBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/refractionBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/subSurfaceBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/pbrMetallicRoughnessBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/modBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/matrixBuilderBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/conditionalBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/cloudBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/voronoiNoiseBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/elbowBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/triPlanarBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/biPlanarBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/meshAttributeExistsBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/matrixDeterminantBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/matrixTransposeBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/curveBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/shadowDepthWrapper.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Optimizers/nodeMaterialOptimizer.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Optimizers/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/material.decalMapConfiguration.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/materialPluginFactoryExport.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/greasedLinePluginMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/standardMaterial.decalMap.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/PBR/pbrMaterial.decalMap.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/abstractMesh.decalMap.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/material.decalMap.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Maths/math.polar.js","webpack://code-cave/./node_modules/@babylonjs/core/Maths/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Compression/dracoCompression.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Compression/meshoptCompression.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Compression/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/csg.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/meshUVSpaceRenderer.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/meshUVSpaceRenderer.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/meshUVSpaceRenderer.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/trailMesh.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/meshSimplification.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/greasedLineMesh.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/meshSimplificationSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/greasedLineTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/greasedLineBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/thinInstanceMesh.js","webpack://code-cave/./node_modules/@babylonjs/core/Navigation/INavigationEngine.js","webpack://code-cave/./node_modules/@babylonjs/core/Navigation/Plugins/recastJSPlugin.js","webpack://code-cave/./node_modules/@babylonjs/core/Offline/database.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/uniformBufferEffectCommonAccessor.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/gpuUpdateParticles.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/gpuUpdateParticles.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/webgl2ParticleSystem.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/gpuUpdateParticles.compute.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/particle.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/particleSystem.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/gpuParticleSystem.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/particleSystemSet.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/particleHelper.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/solidParticle.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/solidParticleSystem.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/cloudPoint.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/pointsCloudSystem.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v1/physicsEngineComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v1/IPhysicsEnginePlugin.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v1/Plugins/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v1/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v2/physicsEngine.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v2/physicsBody.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v2/IPhysicsEnginePlugin.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v2/physicsShape.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v2/physicsConstraint.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v2/physicsMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v2/physicsAggregate.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v2/Plugins/havokPlugin.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/postProcessRenderEffect.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/geometryBufferRenderer.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/motionBlurPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/screenSpaceReflectionPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/filter.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/filterPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/fxaa.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/fxaa.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/fxaaPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/grain.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/grainPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/highlights.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/highlightsPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/lensRenderingPipeline.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/ssao2Configuration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ssao2.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ssaoCombine.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/ssao2RenderingPipeline.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ssao.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/ssaoRenderingPipeline.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/screenSpaceReflectionsConfiguration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/screenSpaceReflection.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/standard.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/standardRenderingPipeline.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/screenSpaceReflections2Configuration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/screenSpaceRayTrace.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/ssrRenderingPipeline.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/index.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/tonemap.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/tonemapPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/volumetricLightScattering.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/volumetricLightScatteringPass.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/volumetricLightScatteringPass.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/volumetricLightScatteringPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/screenSpaceCurvature.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/screenSpaceCurvaturePostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/boundingBoxRendererUboDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/boundingBoxRenderer.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/boundingBoxRendererVertexDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/boundingBoxRenderer.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/boundingBoxRenderer.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/depthRendererSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/oitFinal.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/oitBackBlend.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/depthPeelingRenderer.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/depthPeelingSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/line.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/line.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/edgesRenderer.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/prePassRenderer.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/prePassRendererSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/fibonacci.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/diffusionProfile.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/subSurfaceScattering.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/subSurfaceScatteringPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/subSurfaceConfiguration.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/subSurfaceSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/outline.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/outline.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/outlineRenderer.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderingObject.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderingTextures.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderingTargetRenderer.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderingObjectCustomParticles.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/copyTextureToTexture.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/copyTextureToTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderingDepthTextureCopy.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/fluidRenderingParticleDepth.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/fluidRenderingParticleDepth.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/fluidRenderingParticleThickness.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/fluidRenderingParticleThickness.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/fluidRenderingParticleDiffuse.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/fluidRenderingParticleDiffuse.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/fluidRenderingBilateralBlur.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/fluidRenderingStandardBlur.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/fluidRenderingRender.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderer.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/fluidRenderer/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Sprites/thinSprite.js","webpack://code-cave/./node_modules/@babylonjs/core/Sprites/sprite.js","webpack://code-cave/./node_modules/@babylonjs/core/Sprites/ISprites.js","webpack://code-cave/./node_modules/@babylonjs/core/Sprites/spriteSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/sprites.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/imageProcessingCompatibility.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/sprites.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Sprites/spriteRenderer.js","webpack://code-cave/./node_modules/@babylonjs/core/Sprites/spriteManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/spriteMap.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/spriteMap.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Sprites/spriteMap.js","webpack://code-cave/./node_modules/@babylonjs/core/Sprites/spritePackedManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Sprites/index.js","webpack://code-cave/./node_modules/@babylonjs/core/States/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/assetsManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/deferred.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/meshExploder.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/filesInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/HighDynamicRange/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/observable.extensions.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/sceneOptimizer.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/sceneSerializer.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/videoRecorder.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/screenshotTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/iInspectable.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/fileRequest.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/customAnimationFrameRequester.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/interfaces/screenshotSize.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/dataReader.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/dataStorage.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/sceneRecorder.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/trajectoryClassifier.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/reflector.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/pressureObserverWrapper.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/PerformanceViewer/dynamicFloat32Array.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/PerformanceViewer/performanceViewerCollector.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/PerformanceViewer/performanceViewerCollectionStrategies.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/observableCoroutine.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/index.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRHitTestLegacy.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRAnchorSystem.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRPlaneDetector.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRBackgroundRemover.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRControllerPhysics.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRHitTest.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRFeaturePointSystem.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRMeshDetector.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRImageTracking.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRDOMOverlay.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRControllerMovement.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRLightEstimation.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRWalkingLocomotion.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRSpaceWarp.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/index.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/motionController/webXRMicrosoftMixedRealityController.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/motionController/webXROculusTouchMotionController.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/native/nativeXRFrame.js","webpack://code-cave/./node_modules/@babylonjs/core/index.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/glTFValidation.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/glTFFileLoader.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/native/index.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/index.js","webpack://code-cave/./node_modules/@babylonjs/core/types.js","webpack://code-cave/./node_modules/@babylonjs/core/Compat/index.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/1.0/glTFLoaderUtils.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/1.0/glTFLoaderInterfaces.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/1.0/glTFLoader.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/1.0/glTFBinaryExtension.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/1.0/glTFMaterialsCommonExtension.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/1.0/index.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/glTFLoaderAnimation.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/glTFLoader.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/glTFLoaderExtension.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/EXT_lights_image_based.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/glTFLoaderInterfaces.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/EXT_mesh_gpu_instancing.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/EXT_meshopt_compression.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/EXT_texture_webp.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_draco_mesh_compression.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_lights_punctual.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_unlit.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_clearcoat.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_iridescence.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_anisotropy.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_emissive_strength.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_sheen.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_specular.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_ior.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_variants.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_transmission.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_translucency.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_volume.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_mesh_quantization.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_texture_basisu.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_texture_transform.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_xmp_json_ld.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_animation_pointer.data.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_animation_pointer.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/MSFT_audio_emitter.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/MSFT_lod.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/MSFT_minecraftMesh.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/MSFT_sRGBFactors.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/ExtrasAsMetadata.js","webpack://code-cave/./node_modules/@babylonjs/core/Buffers/buffer.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/camera.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/index.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/index.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/index.js","webpack://code-cave/./src/workers/babylon.worker.ts","webpack://code-cave/./node_modules/@babylonjs/core/Actions/abstractActionManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Actions/actionEvent.js","webpack://code-cave/./node_modules/@babylonjs/core/Buffers/dataBuffer.js","webpack://code-cave/./node_modules/@babylonjs/core/Collisions/intersectionInfo.js","webpack://code-cave/./node_modules/@babylonjs/core/Collisions/meshCollisionData.js","webpack://code-cave/./node_modules/@babylonjs/core/Collisions/pickingInfo.js","webpack://code-cave/./node_modules/@babylonjs/core/Compat/compatibilityOptions.js","webpack://code-cave/./node_modules/@babylonjs/core/Culling/boundingBox.js","webpack://code-cave/./node_modules/@babylonjs/core/Culling/boundingInfo.js","webpack://code-cave/./node_modules/@babylonjs/core/Culling/boundingSphere.js","webpack://code-cave/./node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceEnums.js","webpack://code-cave/./node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceSource.js","webpack://code-cave/./node_modules/@babylonjs/core/DeviceInput/eventFactory.js","webpack://code-cave/./node_modules/@babylonjs/core/DeviceInput/nativeDeviceInputSystem.js","webpack://code-cave/./node_modules/@babylonjs/core/DeviceInput/webDeviceInputSystem.js","webpack://code-cave/./node_modules/@babylonjs/core/DeviceInput/internalDeviceSourceManager.js","webpack://code-cave/./node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceSourceManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.alpha.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.dynamicBuffer.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.readTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.uniformBuffer.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Processors/shaderCodeNode.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Processors/shaderCodeCursor.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Processors/shaderCodeConditionNode.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Processors/shaderCodeTestNode.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Processors/Expressions/shaderDefineExpression.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineIsDefinedOperator.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineAndOperator.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineArithmeticOperator.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Processors/shaderProcessor.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGL/webGL2ShaderProcessors.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGL/webGLHardwareTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGL/webGLPipelineContext.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGL/webGLShaderProcessors.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/engine.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/engineStore.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/shaderStore.js","webpack://code-cave/./node_modules/@babylonjs/core/Events/deviceInputEvents.js","webpack://code-cave/./node_modules/@babylonjs/core/Events/keyboardEvents.js","webpack://code-cave/./node_modules/@babylonjs/core/Events/pointerEvents.js","webpack://code-cave/./node_modules/@babylonjs/core/Inputs/pointerPickingConfiguration.js","webpack://code-cave/./node_modules/@babylonjs/core/Inputs/scene.inputManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Lights/lightConstants.js","webpack://code-cave/./node_modules/@babylonjs/core/Loading/sceneLoaderFlags.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/internalTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/textureSampler.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/clipPlaneMaterialHelper.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/colorCurves.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/drawWrapper.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/effect.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/imageProcessingConfiguration.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/materialStencilState.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/material.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/materialDefines.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/materialHelper.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/materialPluginEvent.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/multiMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/shaderLanguage.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/uniformBuffer.js","webpack://code-cave/./node_modules/@babylonjs/core/Maths/math.axis.js","webpack://code-cave/./node_modules/@babylonjs/core/Maths/math.color.js","webpack://code-cave/./node_modules/@babylonjs/core/Maths/math.constants.js","webpack://code-cave/./node_modules/@babylonjs/core/Maths/math.frustum.js","webpack://code-cave/./node_modules/@babylonjs/core/Maths/math.functions.js","webpack://code-cave/./node_modules/@babylonjs/core/Maths/math.plane.js","webpack://code-cave/./node_modules/@babylonjs/core/Maths/math.scalar.js","webpack://code-cave/./node_modules/@babylonjs/core/Maths/math.viewport.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/WebGL/webGLDataBuffer.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/abstractMesh.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/geometry.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/mesh.vertexData.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/meshLODLevel.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/subMesh.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/transformNode.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/andOrNotEvaluator.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/arrayTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/coroutine.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/decorators.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/deepCopier.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/devTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/domManagement.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/error.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/fileTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/instantiationTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/filesInputStore.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/guid.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/logger.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/observable.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/perfCounter.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/performanceMonitor.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/precisionDate.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/retryStrategy.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/smartArray.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/stringDictionary.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/stringTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/tags.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/timingTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/tools.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/typeStore.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/uniqueIdGenerator.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/webRequest.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/postProcessManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/renderingGroup.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/renderingManager.js","webpack://code-cave/./node_modules/@babylonjs/core/States/alphaCullingState.js","webpack://code-cave/./node_modules/@babylonjs/core/States/depthCullingState.js","webpack://code-cave/./node_modules/@babylonjs/core/States/stencilState.js","webpack://code-cave/./node_modules/@babylonjs/core/States/stencilStateComposer.js","webpack://code-cave/./node_modules/@babylonjs/core/abstractScene.js","webpack://code-cave/./node_modules/@babylonjs/core/node.js","webpack://code-cave/./node_modules/@babylonjs/core/sceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/tslib.es6.js","webpack://code-cave/webpack/bootstrap","webpack://code-cave/webpack/runtime/chunk loaded","webpack://code-cave/webpack/runtime/define property getters","webpack://code-cave/webpack/runtime/ensure chunk","webpack://code-cave/webpack/runtime/get javascript chunk filename","webpack://code-cave/webpack/runtime/get mini-css chunk filename","webpack://code-cave/webpack/runtime/hasOwnProperty shorthand","webpack://code-cave/webpack/runtime/publicPath","webpack://code-cave/webpack/runtime/importScripts chunk loading","webpack://code-cave/webpack/runtime/startup chunk dependencies","webpack://code-cave/webpack/startup"],"sourcesContent":["import { Observable } from \"../Misc/observable.js\";\nimport { Vector2, Vector3 } from \"../Maths/math.vector.js\";\nimport { Color3, Color4 } from \"../Maths/math.color.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\n/**\n * The action to be carried out following a trigger\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#available-actions\n */\nexport class Action {\n /**\n * Creates a new Action\n * @param triggerOptions the trigger, with or without parameters, for the action\n * @param condition an optional determinant of action\n */\n constructor(\n /** the trigger, with or without parameters, for the action */\n triggerOptions, condition) {\n this.triggerOptions = triggerOptions;\n /**\n * An event triggered prior to action being executed.\n */\n this.onBeforeExecuteObservable = new Observable();\n if (triggerOptions.parameter) {\n this.trigger = triggerOptions.trigger;\n this._triggerParameter = triggerOptions.parameter;\n }\n else if (triggerOptions.trigger) {\n this.trigger = triggerOptions.trigger;\n }\n else {\n this.trigger = triggerOptions;\n }\n this._nextActiveAction = this;\n this._condition = condition;\n }\n /**\n * Internal only\n * @internal\n */\n _prepare() { }\n /**\n * Gets the trigger parameter\n * @returns the trigger parameter\n */\n getTriggerParameter() {\n return this._triggerParameter;\n }\n /**\n * Sets the trigger parameter\n * @param value defines the new trigger parameter\n */\n setTriggerParameter(value) {\n this._triggerParameter = value;\n }\n /**\n * Internal only - Returns if the current condition allows to run the action\n * @internal\n */\n _evaluateConditionForCurrentFrame() {\n const condition = this._condition;\n if (!condition) {\n return true;\n }\n const currentRenderId = this._actionManager.getScene().getRenderId();\n // We cache the current evaluation for the current frame\n if (condition._evaluationId !== currentRenderId) {\n condition._evaluationId = currentRenderId;\n condition._currentResult = condition.isValid();\n }\n return condition._currentResult;\n }\n /**\n * Internal only - executes current action event\n * @internal\n */\n _executeCurrent(evt) {\n const isConditionValid = this._evaluateConditionForCurrentFrame();\n if (!isConditionValid) {\n return;\n }\n this.onBeforeExecuteObservable.notifyObservers(this);\n this._nextActiveAction.execute(evt);\n this.skipToNextActiveAction();\n }\n /**\n * Execute placeholder for child classes\n * @param evt optional action event\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n execute(evt) { }\n /**\n * Skips to next active action\n */\n skipToNextActiveAction() {\n if (this._nextActiveAction._child) {\n if (!this._nextActiveAction._child._actionManager) {\n this._nextActiveAction._child._actionManager = this._actionManager;\n }\n this._nextActiveAction = this._nextActiveAction._child;\n }\n else {\n this._nextActiveAction = this;\n }\n }\n /**\n * Adds action to chain of actions, may be a DoNothingAction\n * @param action defines the next action to execute\n * @returns The action passed in\n * @see https://www.babylonjs-playground.com/#1T30HR#0\n */\n then(action) {\n this._child = action;\n action._actionManager = this._actionManager;\n action._prepare();\n return action;\n }\n /**\n * Internal only\n * @internal\n */\n _getProperty(propertyPath) {\n return this._actionManager._getProperty(propertyPath);\n }\n /**\n * @internal\n */\n _getEffectiveTarget(target, propertyPath) {\n return this._actionManager._getEffectiveTarget(target, propertyPath);\n }\n /**\n * Serialize placeholder for child classes\n * @param parent of child\n * @returns the serialized object\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n serialize(parent) { }\n /**\n * Internal only called by serialize\n * @internal\n */\n _serialize(serializedAction, parent) {\n const serializationObject = {\n type: 1,\n children: [],\n name: serializedAction.name,\n properties: serializedAction.properties || [],\n };\n // Serialize child\n if (this._child) {\n this._child.serialize(serializationObject);\n }\n // Check if \"this\" has a condition\n if (this._condition) {\n const serializedCondition = this._condition.serialize();\n serializedCondition.children.push(serializationObject);\n if (parent) {\n parent.children.push(serializedCondition);\n }\n return serializedCondition;\n }\n if (parent) {\n parent.children.push(serializationObject);\n }\n return serializationObject;\n }\n}\n/**\n * Internal only\n * @internal\n */\nAction._SerializeValueAsString = (value) => {\n if (typeof value === \"number\") {\n return value.toString();\n }\n if (typeof value === \"boolean\") {\n return value ? \"true\" : \"false\";\n }\n if (value instanceof Vector2) {\n return value.x + \", \" + value.y;\n }\n if (value instanceof Vector3) {\n return value.x + \", \" + value.y + \", \" + value.z;\n }\n if (value instanceof Color3) {\n return value.r + \", \" + value.g + \", \" + value.b;\n }\n if (value instanceof Color4) {\n return value.r + \", \" + value.g + \", \" + value.b + \", \" + value.a;\n }\n return value; // string\n};\n/**\n * Internal only\n * @internal\n */\nAction._GetTargetProperty = (target) => {\n return {\n name: \"target\",\n targetType: target._isMesh\n ? \"MeshProperties\"\n : target._isLight\n ? \"LightProperties\"\n : target._isCamera\n ? \"CameraProperties\"\n : target._isMaterial\n ? \"MaterialProperties\"\n : \"SceneProperties\",\n value: target._isScene ? \"Scene\" : target.name,\n };\n};\nRegisterClass(\"BABYLON.Action\", Action);\n//# sourceMappingURL=action.js.map","import { Action } from \"./action.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\n/**\n * A Condition applied to an Action\n */\nexport class Condition {\n /**\n * Creates a new Condition\n * @param actionManager the manager of the action the condition is applied to\n */\n constructor(actionManager) {\n this._actionManager = actionManager;\n }\n /**\n * Check if the current condition is valid\n * @returns a boolean\n */\n isValid() {\n return true;\n }\n /**\n * @internal\n */\n _getProperty(propertyPath) {\n return this._actionManager._getProperty(propertyPath);\n }\n /**\n * @internal\n */\n _getEffectiveTarget(target, propertyPath) {\n return this._actionManager._getEffectiveTarget(target, propertyPath);\n }\n /**\n * Serialize placeholder for child classes\n * @returns the serialized object\n */\n serialize() { }\n /**\n * @internal\n */\n _serialize(serializedCondition) {\n return {\n type: 2,\n children: [],\n name: serializedCondition.name,\n properties: serializedCondition.properties,\n };\n }\n}\n/**\n * Defines specific conditional operators as extensions of Condition\n */\nexport class ValueCondition extends Condition {\n /**\n * returns the number for IsEqual\n */\n static get IsEqual() {\n return ValueCondition._IsEqual;\n }\n /**\n * Returns the number for IsDifferent\n */\n static get IsDifferent() {\n return ValueCondition._IsDifferent;\n }\n /**\n * Returns the number for IsGreater\n */\n static get IsGreater() {\n return ValueCondition._IsGreater;\n }\n /**\n * Returns the number for IsLesser\n */\n static get IsLesser() {\n return ValueCondition._IsLesser;\n }\n /**\n * Creates a new ValueCondition\n * @param actionManager manager for the action the condition applies to\n * @param target for the action\n * @param propertyPath path to specify the property of the target the conditional operator uses\n * @param value the value compared by the conditional operator against the current value of the property\n * @param operator the conditional operator, default ValueCondition.IsEqual\n */\n constructor(actionManager, target, \n /** path to specify the property of the target the conditional operator uses */\n propertyPath, \n /** the value compared by the conditional operator against the current value of the property */\n value, \n /** the conditional operator, default ValueCondition.IsEqual */\n operator = ValueCondition.IsEqual) {\n super(actionManager);\n this.propertyPath = propertyPath;\n this.value = value;\n this.operator = operator;\n this._target = target;\n this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);\n this._property = this._getProperty(this.propertyPath);\n }\n /**\n * Compares the given value with the property value for the specified conditional operator\n * @returns the result of the comparison\n */\n isValid() {\n switch (this.operator) {\n case ValueCondition.IsGreater:\n return this._effectiveTarget[this._property] > this.value;\n case ValueCondition.IsLesser:\n return this._effectiveTarget[this._property] < this.value;\n case ValueCondition.IsEqual:\n case ValueCondition.IsDifferent: {\n let check;\n if (this.value.equals) {\n check = this.value.equals(this._effectiveTarget[this._property]);\n }\n else {\n check = this.value === this._effectiveTarget[this._property];\n }\n return this.operator === ValueCondition.IsEqual ? check : !check;\n }\n }\n return false;\n }\n /**\n * Serialize the ValueCondition into a JSON compatible object\n * @returns serialization object\n */\n serialize() {\n return this._serialize({\n name: \"ValueCondition\",\n properties: [\n Action._GetTargetProperty(this._target),\n { name: \"propertyPath\", value: this.propertyPath },\n { name: \"value\", value: Action._SerializeValueAsString(this.value) },\n { name: \"operator\", value: ValueCondition.GetOperatorName(this.operator) },\n ],\n });\n }\n /**\n * Gets the name of the conditional operator for the ValueCondition\n * @param operator the conditional operator\n * @returns the name\n */\n static GetOperatorName(operator) {\n switch (operator) {\n case ValueCondition._IsEqual:\n return \"IsEqual\";\n case ValueCondition._IsDifferent:\n return \"IsDifferent\";\n case ValueCondition._IsGreater:\n return \"IsGreater\";\n case ValueCondition._IsLesser:\n return \"IsLesser\";\n default:\n return \"\";\n }\n }\n}\nValueCondition._IsEqual = 0;\nValueCondition._IsDifferent = 1;\nValueCondition._IsGreater = 2;\nValueCondition._IsLesser = 3;\n/**\n * Defines a predicate condition as an extension of Condition\n */\nexport class PredicateCondition extends Condition {\n /**\n * Creates a new PredicateCondition\n * @param actionManager manager for the action the condition applies to\n * @param predicate defines the predicate function used to validate the condition\n */\n constructor(actionManager, \n /** defines the predicate function used to validate the condition */\n predicate) {\n super(actionManager);\n this.predicate = predicate;\n }\n /**\n * @returns the validity of the predicate condition\n */\n isValid() {\n return this.predicate();\n }\n}\n/**\n * Defines a state condition as an extension of Condition\n */\nexport class StateCondition extends Condition {\n /**\n * Creates a new StateCondition\n * @param actionManager manager for the action the condition applies to\n * @param target of the condition\n * @param value to compare with target state\n */\n constructor(actionManager, target, \n /** Value to compare with target state */\n value) {\n super(actionManager);\n this.value = value;\n this._target = target;\n }\n /**\n * Gets a boolean indicating if the current condition is met\n * @returns the validity of the state\n */\n isValid() {\n return this._target.state === this.value;\n }\n /**\n * Serialize the StateCondition into a JSON compatible object\n * @returns serialization object\n */\n serialize() {\n return this._serialize({\n name: \"StateCondition\",\n properties: [Action._GetTargetProperty(this._target), { name: \"value\", value: this.value }],\n });\n }\n}\nRegisterClass(\"BABYLON.ValueCondition\", ValueCondition);\nRegisterClass(\"BABYLON.PredicateCondition\", PredicateCondition);\nRegisterClass(\"BABYLON.StateCondition\", StateCondition);\n//# sourceMappingURL=condition.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Action } from \"./action.js\";\n\nimport { RegisterClass } from \"../Misc/typeStore.js\";\n/**\n * This defines an action responsible to toggle a boolean once triggered.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\nexport class SwitchBooleanAction extends Action {\n /**\n * Instantiate the action\n * @param triggerOptions defines the trigger options\n * @param target defines the object containing the boolean\n * @param propertyPath defines the path to the boolean property in the target object\n * @param condition defines the trigger related conditions\n */\n constructor(triggerOptions, target, propertyPath, condition) {\n super(triggerOptions, condition);\n this.propertyPath = propertyPath;\n this._target = this._effectiveTarget = target;\n }\n /** @internal */\n _prepare() {\n this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);\n this._property = this._getProperty(this.propertyPath);\n }\n /**\n * Execute the action toggle the boolean value.\n */\n execute() {\n this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];\n }\n /**\n * Serializes the actions and its related information.\n * @param parent defines the object to serialize in\n * @returns the serialized object\n */\n serialize(parent) {\n return super._serialize({\n name: \"SwitchBooleanAction\",\n properties: [Action._GetTargetProperty(this._target), { name: \"propertyPath\", value: this.propertyPath }],\n }, parent);\n }\n}\n/**\n * This defines an action responsible to set a the state field of the target\n * to a desired value once triggered.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\nexport class SetStateAction extends Action {\n /**\n * Instantiate the action\n * @param triggerOptions defines the trigger options\n * @param target defines the object containing the state property\n * @param value defines the value to store in the state field\n * @param condition defines the trigger related conditions\n */\n constructor(triggerOptions, target, value, condition) {\n super(triggerOptions, condition);\n this.value = value;\n this._target = target;\n }\n /**\n * Execute the action and store the value on the target state property.\n */\n execute() {\n this._target.state = this.value;\n }\n /**\n * Serializes the actions and its related information.\n * @param parent defines the object to serialize in\n * @returns the serialized object\n */\n serialize(parent) {\n return super._serialize({\n name: \"SetStateAction\",\n properties: [Action._GetTargetProperty(this._target), { name: \"value\", value: this.value }],\n }, parent);\n }\n}\n/**\n * This defines an action responsible to set a property of the target\n * to a desired value once triggered.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\nexport class SetValueAction extends Action {\n /**\n * Instantiate the action\n * @param triggerOptions defines the trigger options\n * @param target defines the object containing the property\n * @param propertyPath defines the path of the property to set in the target\n * @param value defines the value to set in the property\n * @param condition defines the trigger related conditions\n */\n constructor(triggerOptions, target, propertyPath, value, condition) {\n super(triggerOptions, condition);\n this.propertyPath = propertyPath;\n this.value = value;\n this._target = this._effectiveTarget = target;\n }\n /** @internal */\n _prepare() {\n this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);\n this._property = this._getProperty(this.propertyPath);\n }\n /**\n * Execute the action and set the targeted property to the desired value.\n */\n execute() {\n this._effectiveTarget[this._property] = this.value;\n if (this._target.markAsDirty) {\n this._target.markAsDirty(this._property);\n }\n }\n /**\n * Serializes the actions and its related information.\n * @param parent defines the object to serialize in\n * @returns the serialized object\n */\n serialize(parent) {\n return super._serialize({\n name: \"SetValueAction\",\n properties: [\n Action._GetTargetProperty(this._target),\n { name: \"propertyPath\", value: this.propertyPath },\n { name: \"value\", value: Action._SerializeValueAsString(this.value) },\n ],\n }, parent);\n }\n}\n/**\n * This defines an action responsible to increment the target value\n * to a desired value once triggered.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\nexport class IncrementValueAction extends Action {\n /**\n * Instantiate the action\n * @param triggerOptions defines the trigger options\n * @param target defines the object containing the property\n * @param propertyPath defines the path of the property to increment in the target\n * @param value defines the value value we should increment the property by\n * @param condition defines the trigger related conditions\n */\n constructor(triggerOptions, target, propertyPath, value, condition) {\n super(triggerOptions, condition);\n this.propertyPath = propertyPath;\n this.value = value;\n this._target = this._effectiveTarget = target;\n }\n /** @internal */\n _prepare() {\n this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);\n this._property = this._getProperty(this.propertyPath);\n if (typeof this._effectiveTarget[this._property] !== \"number\") {\n Logger.Warn(\"Warning: IncrementValueAction can only be used with number values\");\n }\n }\n /**\n * Execute the action and increment the target of the value amount.\n */\n execute() {\n this._effectiveTarget[this._property] += this.value;\n if (this._target.markAsDirty) {\n this._target.markAsDirty(this._property);\n }\n }\n /**\n * Serializes the actions and its related information.\n * @param parent defines the object to serialize in\n * @returns the serialized object\n */\n serialize(parent) {\n return super._serialize({\n name: \"IncrementValueAction\",\n properties: [\n Action._GetTargetProperty(this._target),\n { name: \"propertyPath\", value: this.propertyPath },\n { name: \"value\", value: Action._SerializeValueAsString(this.value) },\n ],\n }, parent);\n }\n}\n/**\n * This defines an action responsible to start an animation once triggered.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\nexport class PlayAnimationAction extends Action {\n /**\n * Instantiate the action\n * @param triggerOptions defines the trigger options\n * @param target defines the target animation or animation name\n * @param from defines from where the animation should start (animation frame)\n * @param to defines where the animation should stop (animation frame)\n * @param loop defines if the animation should loop or stop after the first play\n * @param condition defines the trigger related conditions\n */\n constructor(triggerOptions, target, from, to, loop, condition) {\n super(triggerOptions, condition);\n this.from = from;\n this.to = to;\n this.loop = loop;\n this._target = target;\n }\n /** @internal */\n _prepare() { }\n /**\n * Execute the action and play the animation.\n */\n execute() {\n const scene = this._actionManager.getScene();\n scene.beginAnimation(this._target, this.from, this.to, this.loop);\n }\n /**\n * Serializes the actions and its related information.\n * @param parent defines the object to serialize in\n * @returns the serialized object\n */\n serialize(parent) {\n return super._serialize({\n name: \"PlayAnimationAction\",\n properties: [\n Action._GetTargetProperty(this._target),\n { name: \"from\", value: String(this.from) },\n { name: \"to\", value: String(this.to) },\n { name: \"loop\", value: Action._SerializeValueAsString(this.loop) || false },\n ],\n }, parent);\n }\n}\n/**\n * This defines an action responsible to stop an animation once triggered.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\nexport class StopAnimationAction extends Action {\n /**\n * Instantiate the action\n * @param triggerOptions defines the trigger options\n * @param target defines the target animation or animation name\n * @param condition defines the trigger related conditions\n */\n constructor(triggerOptions, target, condition) {\n super(triggerOptions, condition);\n this._target = target;\n }\n /** @internal */\n _prepare() { }\n /**\n * Execute the action and stop the animation.\n */\n execute() {\n const scene = this._actionManager.getScene();\n scene.stopAnimation(this._target);\n }\n /**\n * Serializes the actions and its related information.\n * @param parent defines the object to serialize in\n * @returns the serialized object\n */\n serialize(parent) {\n return super._serialize({\n name: \"StopAnimationAction\",\n properties: [Action._GetTargetProperty(this._target)],\n }, parent);\n }\n}\n/**\n * This defines an action responsible that does nothing once triggered.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\nexport class DoNothingAction extends Action {\n /**\n * Instantiate the action\n * @param triggerOptions defines the trigger options\n * @param condition defines the trigger related conditions\n */\n constructor(triggerOptions = 0, condition) {\n super(triggerOptions, condition);\n }\n /**\n * Execute the action and do nothing.\n */\n execute() { }\n /**\n * Serializes the actions and its related information.\n * @param parent defines the object to serialize in\n * @returns the serialized object\n */\n serialize(parent) {\n return super._serialize({\n name: \"DoNothingAction\",\n properties: [],\n }, parent);\n }\n}\n/**\n * This defines an action responsible to trigger several actions once triggered.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\nexport class CombineAction extends Action {\n /**\n * Instantiate the action\n * @param triggerOptions defines the trigger options\n * @param children defines the list of aggregated animations to run\n * @param condition defines the trigger related conditions\n * @param enableChildrenConditions defines if the children actions conditions should be check before execution\n */\n constructor(triggerOptions, children, condition, enableChildrenConditions = true) {\n super(triggerOptions, condition);\n this.children = children;\n this.enableChildrenConditions = enableChildrenConditions;\n }\n /** @internal */\n _prepare() {\n for (let index = 0; index < this.children.length; index++) {\n this.children[index]._actionManager = this._actionManager;\n this.children[index]._prepare();\n }\n }\n /**\n * Execute the action and executes all the aggregated actions.\n * @param evt\n */\n execute(evt) {\n for (const action of this.children) {\n if (!this.enableChildrenConditions || action._evaluateConditionForCurrentFrame()) {\n action.execute(evt);\n }\n }\n }\n /**\n * Serializes the actions and its related information.\n * @param parent defines the object to serialize in\n * @returns the serialized object\n */\n serialize(parent) {\n const serializationObject = super._serialize({\n name: \"CombineAction\",\n properties: [],\n combine: [],\n }, parent);\n for (let i = 0; i < this.children.length; i++) {\n serializationObject.combine.push(this.children[i].serialize(null));\n }\n return serializationObject;\n }\n}\n/**\n * This defines an action responsible to run code (external event) once triggered.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\nexport class ExecuteCodeAction extends Action {\n /**\n * Instantiate the action\n * @param triggerOptions defines the trigger options\n * @param func defines the callback function to run\n * @param condition defines the trigger related conditions\n */\n constructor(triggerOptions, func, condition) {\n super(triggerOptions, condition);\n this.func = func;\n }\n /**\n * Execute the action and run the attached code.\n * @param evt\n */\n execute(evt) {\n this.func(evt);\n }\n}\n/**\n * This defines an action responsible to set the parent property of the target once triggered.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\nexport class SetParentAction extends Action {\n /**\n * Instantiate the action\n * @param triggerOptions defines the trigger options\n * @param target defines the target containing the parent property\n * @param parent defines from where the animation should start (animation frame)\n * @param condition defines the trigger related conditions\n */\n constructor(triggerOptions, target, parent, condition) {\n super(triggerOptions, condition);\n this._target = target;\n this._parent = parent;\n }\n /** @internal */\n _prepare() { }\n /**\n * Execute the action and set the parent property.\n */\n execute() {\n if (this._target.parent === this._parent) {\n return;\n }\n const invertParentWorldMatrix = this._parent.getWorldMatrix().clone();\n invertParentWorldMatrix.invert();\n this._target.position = Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);\n this._target.parent = this._parent;\n }\n /**\n * Serializes the actions and its related information.\n * @param parent defines the object to serialize in\n * @returns the serialized object\n */\n serialize(parent) {\n return super._serialize({\n name: \"SetParentAction\",\n properties: [Action._GetTargetProperty(this._target), Action._GetTargetProperty(this._parent)],\n }, parent);\n }\n}\nRegisterClass(\"BABYLON.SetParentAction\", SetParentAction);\nRegisterClass(\"BABYLON.ExecuteCodeAction\", ExecuteCodeAction);\nRegisterClass(\"BABYLON.DoNothingAction\", DoNothingAction);\nRegisterClass(\"BABYLON.StopAnimationAction\", StopAnimationAction);\nRegisterClass(\"BABYLON.PlayAnimationAction\", PlayAnimationAction);\nRegisterClass(\"BABYLON.IncrementValueAction\", IncrementValueAction);\nRegisterClass(\"BABYLON.SetValueAction\", SetValueAction);\nRegisterClass(\"BABYLON.SetStateAction\", SetStateAction);\nRegisterClass(\"BABYLON.SetParentAction\", SetParentAction);\nRegisterClass(\"BABYLON.SwitchBooleanAction\", SwitchBooleanAction);\nRegisterClass(\"BABYLON.CombineAction\", CombineAction);\n//# sourceMappingURL=directActions.js.map","import { Vector3, Vector4 } from \"../Maths/math.vector.js\";\nimport { Color3, Color4 } from \"../Maths/math.color.js\";\nimport { Condition, ValueCondition } from \"./condition.js\";\nimport { Action } from \"./action.js\";\nimport { DoNothingAction } from \"./directActions.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { DeepCopier } from \"../Misc/deepCopier.js\";\nimport { GetClass } from \"../Misc/typeStore.js\";\nimport { AbstractActionManager } from \"./abstractActionManager.js\";\n\n/**\n * Action Manager manages all events to be triggered on a given mesh or the global scene.\n * A single scene can have many Action Managers to handle predefined actions on specific meshes.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\nexport class ActionManager extends AbstractActionManager {\n /**\n * Creates a new action manager\n * @param scene defines the hosting scene\n */\n constructor(scene) {\n super();\n scene = scene || EngineStore.LastCreatedScene;\n if (!scene) {\n return;\n }\n this._scene = scene;\n scene.actionManagers.push(this);\n }\n // Methods\n /**\n * Releases all associated resources\n */\n dispose() {\n const index = this._scene.actionManagers.indexOf(this);\n for (let i = 0; i < this.actions.length; i++) {\n const action = this.actions[i];\n ActionManager.Triggers[action.trigger]--;\n if (ActionManager.Triggers[action.trigger] === 0) {\n delete ActionManager.Triggers[action.trigger];\n }\n }\n if (index > -1) {\n this._scene.actionManagers.splice(index, 1);\n }\n }\n /**\n * Gets hosting scene\n * @returns the hosting scene\n */\n getScene() {\n return this._scene;\n }\n /**\n * Does this action manager handles actions of any of the given triggers\n * @param triggers defines the triggers to be tested\n * @returns a boolean indicating whether one (or more) of the triggers is handled\n */\n hasSpecificTriggers(triggers) {\n for (let index = 0; index < this.actions.length; index++) {\n const action = this.actions[index];\n if (triggers.indexOf(action.trigger) > -1) {\n return true;\n }\n }\n return false;\n }\n /**\n * Does this action manager handles actions of any of the given triggers. This function takes two arguments for\n * speed.\n * @param triggerA defines the trigger to be tested\n * @param triggerB defines the trigger to be tested\n * @returns a boolean indicating whether one (or more) of the triggers is handled\n */\n hasSpecificTriggers2(triggerA, triggerB) {\n for (let index = 0; index < this.actions.length; index++) {\n const action = this.actions[index];\n if (triggerA == action.trigger || triggerB == action.trigger) {\n return true;\n }\n }\n return false;\n }\n /**\n * Does this action manager handles actions of a given trigger\n * @param trigger defines the trigger to be tested\n * @param parameterPredicate defines an optional predicate to filter triggers by parameter\n * @returns whether the trigger is handled\n */\n hasSpecificTrigger(trigger, parameterPredicate) {\n for (let index = 0; index < this.actions.length; index++) {\n const action = this.actions[index];\n if (action.trigger === trigger) {\n if (parameterPredicate) {\n if (parameterPredicate(action.getTriggerParameter())) {\n return true;\n }\n }\n else {\n return true;\n }\n }\n }\n return false;\n }\n /**\n * Does this action manager has pointer triggers\n */\n get hasPointerTriggers() {\n for (let index = 0; index < this.actions.length; index++) {\n const action = this.actions[index];\n if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {\n return true;\n }\n }\n return false;\n }\n /**\n * Does this action manager has pick triggers\n */\n get hasPickTriggers() {\n for (let index = 0; index < this.actions.length; index++) {\n const action = this.actions[index];\n if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {\n return true;\n }\n }\n return false;\n }\n /**\n * Registers an action to this action manager\n * @param action defines the action to be registered\n * @returns the action amended (prepared) after registration\n */\n registerAction(action) {\n if (action.trigger === ActionManager.OnEveryFrameTrigger) {\n if (this.getScene().actionManager !== this) {\n Logger.Warn(\"OnEveryFrameTrigger can only be used with scene.actionManager\");\n return null;\n }\n }\n this.actions.push(action);\n this.getScene()._registeredActions++;\n if (ActionManager.Triggers[action.trigger]) {\n ActionManager.Triggers[action.trigger]++;\n }\n else {\n ActionManager.Triggers[action.trigger] = 1;\n }\n action._actionManager = this;\n action._prepare();\n return action;\n }\n /**\n * Unregisters an action to this action manager\n * @param action defines the action to be unregistered\n * @returns a boolean indicating whether the action has been unregistered\n */\n unregisterAction(action) {\n const index = this.actions.indexOf(action);\n if (index !== -1) {\n this.actions.splice(index, 1);\n ActionManager.Triggers[action.trigger] -= 1;\n if (ActionManager.Triggers[action.trigger] === 0) {\n delete ActionManager.Triggers[action.trigger];\n }\n action._actionManager = null;\n this.getScene()._registeredActions--;\n return true;\n }\n return false;\n }\n /**\n * Process a specific trigger\n * @param trigger defines the trigger to process\n * @param evt defines the event details to be processed\n */\n processTrigger(trigger, evt) {\n for (let index = 0; index < this.actions.length; index++) {\n const action = this.actions[index];\n if (action.trigger === trigger) {\n if (evt) {\n if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {\n const parameter = action.getTriggerParameter();\n if (typeof parameter === \"function\") {\n if (!parameter(evt)) {\n continue;\n }\n }\n else if (parameter && parameter !== evt.sourceEvent.keyCode) {\n if (!parameter.toLowerCase) {\n continue;\n }\n const lowerCase = parameter.toLowerCase();\n if (lowerCase !== evt.sourceEvent.key) {\n const unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;\n const actualkey = String.fromCharCode(unicode).toLowerCase();\n if (actualkey !== lowerCase) {\n continue;\n }\n }\n }\n }\n }\n action._executeCurrent(evt);\n }\n }\n }\n /**\n * @internal\n */\n _getEffectiveTarget(target, propertyPath) {\n const properties = propertyPath.split(\".\");\n for (let index = 0; index < properties.length - 1; index++) {\n target = target[properties[index]];\n }\n return target;\n }\n /**\n * @internal\n */\n _getProperty(propertyPath) {\n const properties = propertyPath.split(\".\");\n return properties[properties.length - 1];\n }\n /**\n * Serialize this manager to a JSON object\n * @param name defines the property name to store this manager\n * @returns a JSON representation of this manager\n */\n serialize(name) {\n const root = {\n children: new Array(),\n name: name,\n type: 3,\n properties: new Array(), // Empty for root but required\n };\n for (let i = 0; i < this.actions.length; i++) {\n const triggerObject = {\n type: 0,\n children: new Array(),\n name: ActionManager.GetTriggerName(this.actions[i].trigger),\n properties: new Array(),\n };\n const triggerOptions = this.actions[i].triggerOptions;\n if (triggerOptions && typeof triggerOptions !== \"number\") {\n if (triggerOptions.parameter instanceof Node) {\n triggerObject.properties.push(Action._GetTargetProperty(triggerOptions.parameter));\n }\n else if (typeof triggerOptions.parameter === \"object\") {\n const parameter = {};\n DeepCopier.DeepCopy(triggerOptions.parameter, parameter, [\"mesh\"]);\n if (triggerOptions.parameter && triggerOptions.parameter.mesh) {\n parameter._meshId = triggerOptions.parameter.mesh.id;\n }\n triggerObject.properties.push({ name: \"parameter\", targetType: null, value: parameter });\n }\n else {\n triggerObject.properties.push({ name: \"parameter\", targetType: null, value: triggerOptions.parameter });\n }\n }\n // Serialize child action, recursively\n this.actions[i].serialize(triggerObject);\n // Add serialized trigger\n root.children.push(triggerObject);\n }\n return root;\n }\n /**\n * Creates a new ActionManager from a JSON data\n * @param parsedActions defines the JSON data to read from\n * @param object defines the hosting mesh\n * @param scene defines the hosting scene\n */\n static Parse(parsedActions, object, scene) {\n const actionManager = new ActionManager(scene);\n if (object === null) {\n scene.actionManager = actionManager;\n }\n else {\n object.actionManager = actionManager;\n }\n // instantiate a new object\n const instantiate = (name, params) => {\n const internalClassType = GetClass(\"BABYLON.\" + name);\n return internalClassType && new internalClassType(...params);\n };\n const parseParameter = (name, value, target, propertyPath) => {\n if (propertyPath === null) {\n // String, boolean or float\n const floatValue = parseFloat(value);\n if (value === \"true\" || value === \"false\") {\n return value === \"true\";\n }\n else {\n return isNaN(floatValue) ? value : floatValue;\n }\n }\n const effectiveTarget = propertyPath.split(\".\");\n const values = value.split(\",\");\n // Get effective Target\n for (let i = 0; i < effectiveTarget.length; i++) {\n target = target[effectiveTarget[i]];\n }\n // Return appropriate value with its type\n if (typeof target === \"boolean\") {\n return values[0] === \"true\";\n }\n if (typeof target === \"string\") {\n return values[0];\n }\n // Parameters with multiple values such as Vector3 etc.\n const split = new Array();\n for (let i = 0; i < values.length; i++) {\n split.push(parseFloat(values[i]));\n }\n if (target instanceof Vector3) {\n return Vector3.FromArray(split);\n }\n if (target instanceof Vector4) {\n return Vector4.FromArray(split);\n }\n if (target instanceof Color3) {\n return Color3.FromArray(split);\n }\n if (target instanceof Color4) {\n return Color4.FromArray(split);\n }\n return parseFloat(values[0]);\n };\n // traverse graph per trigger\n const traverse = (parsedAction, trigger, condition, action, combineArray = null) => {\n if (parsedAction.detached) {\n return;\n }\n const parameters = new Array();\n let target = null;\n let propertyPath = null;\n const combine = parsedAction.combine && parsedAction.combine.length > 0;\n // Parameters\n if (parsedAction.type === 2) {\n parameters.push(actionManager);\n }\n else {\n parameters.push(trigger);\n }\n if (combine) {\n const actions = new Array();\n for (let j = 0; j < parsedAction.combine.length; j++) {\n traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);\n }\n parameters.push(actions);\n }\n else {\n for (let i = 0; i < parsedAction.properties.length; i++) {\n let value = parsedAction.properties[i].value;\n const name = parsedAction.properties[i].name;\n const targetType = parsedAction.properties[i].targetType;\n if (name === \"target\") {\n if (targetType === \"SceneProperties\") {\n value = target = scene;\n }\n else if (targetType === \"MaterialProperties\") {\n value = target = scene.getMaterialByName(value);\n }\n else {\n value = target = scene.getNodeByName(value);\n }\n }\n else if (name === \"parent\") {\n value = scene.getNodeByName(value);\n }\n else if (name === \"sound\") {\n // Can not externalize to component, so only checks for the presence off the API.\n if (scene.getSoundByName) {\n value = scene.getSoundByName(value);\n }\n }\n else if (name !== \"propertyPath\") {\n if (parsedAction.type === 2 && name === \"operator\") {\n value = ValueCondition[value];\n }\n else {\n value = parseParameter(name, value, target, name === \"value\" ? propertyPath : null);\n }\n }\n else {\n propertyPath = value;\n }\n parameters.push(value);\n }\n }\n if (combineArray === null) {\n parameters.push(condition);\n }\n else {\n parameters.push(null);\n }\n // If interpolate value action\n if (parsedAction.name === \"InterpolateValueAction\") {\n const param = parameters[parameters.length - 2];\n parameters[parameters.length - 1] = param;\n parameters[parameters.length - 2] = condition;\n }\n // Action or condition(s) and not CombineAction\n let newAction = instantiate(parsedAction.name, parameters);\n if (newAction instanceof Condition && condition !== null) {\n const nothing = new DoNothingAction(trigger, condition);\n if (action) {\n action.then(nothing);\n }\n else {\n actionManager.registerAction(nothing);\n }\n action = nothing;\n }\n if (combineArray === null) {\n if (newAction instanceof Condition) {\n condition = newAction;\n newAction = action;\n }\n else {\n condition = null;\n if (action) {\n action.then(newAction);\n }\n else {\n actionManager.registerAction(newAction);\n }\n }\n }\n else {\n combineArray.push(newAction);\n }\n for (let i = 0; i < parsedAction.children.length; i++) {\n traverse(parsedAction.children[i], trigger, condition, newAction, null);\n }\n };\n // triggers\n for (let i = 0; i < parsedActions.children.length; i++) {\n let triggerParams;\n const trigger = parsedActions.children[i];\n if (trigger.properties.length > 0) {\n const param = trigger.properties[0].value;\n const value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);\n if (value._meshId) {\n value.mesh = scene.getMeshById(value._meshId);\n }\n triggerParams = { trigger: ActionManager[trigger.name], parameter: value };\n }\n else {\n triggerParams = ActionManager[trigger.name];\n }\n for (let j = 0; j < trigger.children.length; j++) {\n if (!trigger.detached) {\n traverse(trigger.children[j], triggerParams, null, null);\n }\n }\n }\n }\n /**\n * Get a trigger name by index\n * @param trigger defines the trigger index\n * @returns a trigger name\n */\n static GetTriggerName(trigger) {\n switch (trigger) {\n case 0:\n return \"NothingTrigger\";\n case 1:\n return \"OnPickTrigger\";\n case 2:\n return \"OnLeftPickTrigger\";\n case 3:\n return \"OnRightPickTrigger\";\n case 4:\n return \"OnCenterPickTrigger\";\n case 5:\n return \"OnPickDownTrigger\";\n case 6:\n return \"OnDoublePickTrigger\"; // start;\n case 7:\n return \"OnPickUpTrigger\";\n case 8:\n return \"OnLongPressTrigger\";\n case 9:\n return \"OnPointerOverTrigger\";\n case 10:\n return \"OnPointerOutTrigger\";\n case 11:\n return \"OnEveryFrameTrigger\";\n case 12:\n return \"OnIntersectionEnterTrigger\";\n case 13:\n return \"OnIntersectionExitTrigger\";\n case 14:\n return \"OnKeyDownTrigger\";\n case 15:\n return \"OnKeyUpTrigger\";\n case 16:\n return \"OnPickOutTrigger\";\n default:\n return \"\";\n }\n }\n}\n/**\n * Nothing\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.NothingTrigger = 0;\n/**\n * On pick\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnPickTrigger = 1;\n/**\n * On left pick\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnLeftPickTrigger = 2;\n/**\n * On right pick\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnRightPickTrigger = 3;\n/**\n * On center pick\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnCenterPickTrigger = 4;\n/**\n * On pick down\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnPickDownTrigger = 5;\n/**\n * On double pick\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnDoublePickTrigger = 6;\n/**\n * On pick up\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnPickUpTrigger = 7;\n/**\n * On pick out.\n * This trigger will only be raised if you also declared a OnPickDown\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnPickOutTrigger = 16;\n/**\n * On long press\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnLongPressTrigger = 8;\n/**\n * On pointer over\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnPointerOverTrigger = 9;\n/**\n * On pointer out\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnPointerOutTrigger = 10;\n/**\n * On every frame\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnEveryFrameTrigger = 11;\n/**\n * On intersection enter\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnIntersectionEnterTrigger = 12;\n/**\n * On intersection exit\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnIntersectionExitTrigger = 13;\n/**\n * On key down\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnKeyDownTrigger = 14;\n/**\n * On key up\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnKeyUpTrigger = 15;\n//# sourceMappingURL=actionManager.js.map","import { Action } from \"./action.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\n/**\n * This defines an action helpful to play a defined sound on a triggered action.\n */\nexport class PlaySoundAction extends Action {\n /**\n * Instantiate the action\n * @param triggerOptions defines the trigger options\n * @param sound defines the sound to play\n * @param condition defines the trigger related conditions\n */\n constructor(triggerOptions, sound, condition) {\n super(triggerOptions, condition);\n this._sound = sound;\n }\n /** @internal */\n _prepare() { }\n /**\n * Execute the action and play the sound.\n */\n execute() {\n if (this._sound !== undefined) {\n this._sound.play();\n }\n }\n /**\n * Serializes the actions and its related information.\n * @param parent defines the object to serialize in\n * @returns the serialized object\n */\n serialize(parent) {\n return super._serialize({\n name: \"PlaySoundAction\",\n properties: [{ name: \"sound\", value: this._sound.name }],\n }, parent);\n }\n}\n/**\n * This defines an action helpful to stop a defined sound on a triggered action.\n */\nexport class StopSoundAction extends Action {\n /**\n * Instantiate the action\n * @param triggerOptions defines the trigger options\n * @param sound defines the sound to stop\n * @param condition defines the trigger related conditions\n */\n constructor(triggerOptions, sound, condition) {\n super(triggerOptions, condition);\n this._sound = sound;\n }\n /** @internal */\n _prepare() { }\n /**\n * Execute the action and stop the sound.\n */\n execute() {\n if (this._sound !== undefined) {\n this._sound.stop();\n }\n }\n /**\n * Serializes the actions and its related information.\n * @param parent defines the object to serialize in\n * @returns the serialized object\n */\n serialize(parent) {\n return super._serialize({\n name: \"StopSoundAction\",\n properties: [{ name: \"sound\", value: this._sound.name }],\n }, parent);\n }\n}\nRegisterClass(\"BABYLON.PlaySoundAction\", PlaySoundAction);\nRegisterClass(\"BABYLON.StopSoundAction\", StopSoundAction);\n//# sourceMappingURL=directAudioActions.js.map","/**\n * Enum for the animation key frame interpolation type\n */\nexport var AnimationKeyInterpolation;\n(function (AnimationKeyInterpolation) {\n /**\n * Use tangents to interpolate between start and end values.\n */\n AnimationKeyInterpolation[AnimationKeyInterpolation[\"NONE\"] = 0] = \"NONE\";\n /**\n * Do not interpolate between keys and use the start key value only. Tangents are ignored\n */\n AnimationKeyInterpolation[AnimationKeyInterpolation[\"STEP\"] = 1] = \"STEP\";\n})(AnimationKeyInterpolation || (AnimationKeyInterpolation = {}));\n//# sourceMappingURL=animationKey.js.map","/**\n * Represents the range of an animation\n */\nexport class AnimationRange {\n /**\n * Initializes the range of an animation\n * @param name The name of the animation range\n * @param from The starting frame of the animation\n * @param to The ending frame of the animation\n */\n constructor(\n /**The name of the animation range**/\n name, \n /**The starting frame of the animation */\n from, \n /**The ending frame of the animation*/\n to) {\n this.name = name;\n this.from = from;\n this.to = to;\n }\n /**\n * Makes a copy of the animation range\n * @returns A copy of the animation range\n */\n clone() {\n return new AnimationRange(this.name, this.from, this.to);\n }\n}\n//# sourceMappingURL=animationRange.js.map","/**\n * Size containing width and height\n */\nexport class Size {\n /**\n * Creates a Size object from the given width and height (floats).\n * @param width width of the new size\n * @param height height of the new size\n */\n constructor(width, height) {\n this.width = width;\n this.height = height;\n }\n /**\n * Returns a string with the Size width and height\n * @returns a string with the Size width and height\n */\n toString() {\n return `{W: ${this.width}, H: ${this.height}}`;\n }\n /**\n * \"Size\"\n * @returns the string \"Size\"\n */\n getClassName() {\n return \"Size\";\n }\n /**\n * Returns the Size hash code.\n * @returns a hash code for a unique width and height\n */\n getHashCode() {\n let hash = this.width | 0;\n hash = (hash * 397) ^ (this.height | 0);\n return hash;\n }\n /**\n * Updates the current size from the given one.\n * @param src the given size\n */\n copyFrom(src) {\n this.width = src.width;\n this.height = src.height;\n }\n /**\n * Updates in place the current Size from the given floats.\n * @param width width of the new size\n * @param height height of the new size\n * @returns the updated Size.\n */\n copyFromFloats(width, height) {\n this.width = width;\n this.height = height;\n return this;\n }\n /**\n * Updates in place the current Size from the given floats.\n * @param width width to set\n * @param height height to set\n * @returns the updated Size.\n */\n set(width, height) {\n return this.copyFromFloats(width, height);\n }\n /**\n * Multiplies the width and height by numbers\n * @param w factor to multiple the width by\n * @param h factor to multiple the height by\n * @returns a new Size set with the multiplication result of the current Size and the given floats.\n */\n multiplyByFloats(w, h) {\n return new Size(this.width * w, this.height * h);\n }\n /**\n * Clones the size\n * @returns a new Size copied from the given one.\n */\n clone() {\n return new Size(this.width, this.height);\n }\n /**\n * True if the current Size and the given one width and height are strictly equal.\n * @param other the other size to compare against\n * @returns True if the current Size and the given one width and height are strictly equal.\n */\n equals(other) {\n if (!other) {\n return false;\n }\n return this.width === other.width && this.height === other.height;\n }\n /**\n * The surface of the Size : width * height (float).\n */\n get surface() {\n return this.width * this.height;\n }\n /**\n * Create a new size of zero\n * @returns a new Size set to (0.0, 0.0)\n */\n static Zero() {\n return new Size(0.0, 0.0);\n }\n /**\n * Sums the width and height of two sizes\n * @param otherSize size to add to this size\n * @returns a new Size set as the addition result of the current Size and the given one.\n */\n add(otherSize) {\n const r = new Size(this.width + otherSize.width, this.height + otherSize.height);\n return r;\n }\n /**\n * Subtracts the width and height of two\n * @param otherSize size to subtract to this size\n * @returns a new Size set as the subtraction result of the given one from the current Size.\n */\n subtract(otherSize) {\n const r = new Size(this.width - otherSize.width, this.height - otherSize.height);\n return r;\n }\n /**\n * Creates a new Size set at the linear interpolation \"amount\" between \"start\" and \"end\"\n * @param start starting size to lerp between\n * @param end end size to lerp between\n * @param amount amount to lerp between the start and end values\n * @returns a new Size set at the linear interpolation \"amount\" between \"start\" and \"end\"\n */\n static Lerp(start, end, amount) {\n const w = start.width + (end.width - start.width) * amount;\n const h = start.height + (end.height - start.height) * amount;\n return new Size(w, h);\n }\n}\n//# sourceMappingURL=math.size.js.map","import { Vector3, Quaternion, Vector2, Matrix, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Color3, Color4 } from \"../Maths/math.color.js\";\nimport { Scalar } from \"../Maths/math.scalar.js\";\nimport { SerializationHelper } from \"../Misc/decorators.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\nimport { AnimationKeyInterpolation } from \"./animationKey.js\";\nimport { AnimationRange } from \"./animationRange.js\";\nimport { Node } from \"../node.js\";\nimport { Size } from \"../Maths/math.size.js\";\nimport { WebRequest } from \"../Misc/webRequest.js\";\n\n/**\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class _IAnimationState {\n}\n/**\n * Class used to store any kind of animation\n */\nexport class Animation {\n /**\n * @internal Internal use\n */\n static _PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {\n let dataType = undefined;\n if (!isNaN(parseFloat(from)) && isFinite(from)) {\n dataType = Animation.ANIMATIONTYPE_FLOAT;\n }\n else if (from instanceof Quaternion) {\n dataType = Animation.ANIMATIONTYPE_QUATERNION;\n }\n else if (from instanceof Vector3) {\n dataType = Animation.ANIMATIONTYPE_VECTOR3;\n }\n else if (from instanceof Vector2) {\n dataType = Animation.ANIMATIONTYPE_VECTOR2;\n }\n else if (from instanceof Color3) {\n dataType = Animation.ANIMATIONTYPE_COLOR3;\n }\n else if (from instanceof Color4) {\n dataType = Animation.ANIMATIONTYPE_COLOR4;\n }\n else if (from instanceof Size) {\n dataType = Animation.ANIMATIONTYPE_SIZE;\n }\n if (dataType == undefined) {\n return null;\n }\n const animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);\n const keys = [\n { frame: 0, value: from },\n { frame: totalFrame, value: to },\n ];\n animation.setKeys(keys);\n if (easingFunction !== undefined) {\n animation.setEasingFunction(easingFunction);\n }\n return animation;\n }\n /**\n * Sets up an animation\n * @param property The property to animate\n * @param animationType The animation type to apply\n * @param framePerSecond The frames per second of the animation\n * @param easingFunction The easing function used in the animation\n * @returns The created animation\n */\n static CreateAnimation(property, animationType, framePerSecond, easingFunction) {\n const animation = new Animation(property + \"Animation\", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);\n animation.setEasingFunction(easingFunction);\n return animation;\n }\n /**\n * Create and start an animation on a node\n * @param name defines the name of the global animation that will be run on all nodes\n * @param target defines the target where the animation will take place\n * @param targetProperty defines property to animate\n * @param framePerSecond defines the number of frame per second yo use\n * @param totalFrame defines the number of frames in total\n * @param from defines the initial value\n * @param to defines the final value\n * @param loopMode defines which loop mode you want to use (off by default)\n * @param easingFunction defines the easing function to use (linear by default)\n * @param onAnimationEnd defines the callback to call when animation end\n * @param scene defines the hosting scene\n * @returns the animatable created for this animation\n */\n static CreateAndStartAnimation(name, target, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd, scene) {\n const animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);\n if (!animation) {\n return null;\n }\n if (target.getScene) {\n scene = target.getScene();\n }\n if (!scene) {\n return null;\n }\n return scene.beginDirectAnimation(target, [animation], 0, totalFrame, animation.loopMode === 1, 1.0, onAnimationEnd);\n }\n /**\n * Create and start an animation on a node and its descendants\n * @param name defines the name of the global animation that will be run on all nodes\n * @param node defines the root node where the animation will take place\n * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used\n * @param targetProperty defines property to animate\n * @param framePerSecond defines the number of frame per second to use\n * @param totalFrame defines the number of frames in total\n * @param from defines the initial value\n * @param to defines the final value\n * @param loopMode defines which loop mode you want to use (off by default)\n * @param easingFunction defines the easing function to use (linear by default)\n * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)\n * @returns the list of animatables created for all nodes\n * @example https://www.babylonjs-playground.com/#MH0VLI\n */\n static CreateAndStartHierarchyAnimation(name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {\n const animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);\n if (!animation) {\n return null;\n }\n const scene = node.getScene();\n return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, animation.loopMode === 1, 1.0, onAnimationEnd);\n }\n /**\n * Creates a new animation, merges it with the existing animations and starts it\n * @param name Name of the animation\n * @param node Node which contains the scene that begins the animations\n * @param targetProperty Specifies which property to animate\n * @param framePerSecond The frames per second of the animation\n * @param totalFrame The total number of frames\n * @param from The frame at the beginning of the animation\n * @param to The frame at the end of the animation\n * @param loopMode Specifies the loop mode of the animation\n * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations\n * @param onAnimationEnd Callback to run once the animation is complete\n * @returns Nullable animation\n */\n static CreateMergeAndStartAnimation(name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {\n const animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);\n if (!animation) {\n return null;\n }\n node.animations.push(animation);\n return node.getScene().beginAnimation(node, 0, totalFrame, animation.loopMode === 1, 1.0, onAnimationEnd);\n }\n /**\n * Convert the keyframes for all animations belonging to the group to be relative to a given reference frame.\n * @param sourceAnimation defines the Animation containing keyframes to convert\n * @param referenceFrame defines the frame that keyframes in the range will be relative to\n * @param range defines the name of the AnimationRange belonging to the Animation to convert\n * @param cloneOriginal defines whether or not to clone the animation and convert the clone or convert the original animation (default is false)\n * @param clonedName defines the name of the resulting cloned Animation if cloneOriginal is true\n * @returns a new Animation if cloneOriginal is true or the original Animation if cloneOriginal is false\n */\n static MakeAnimationAdditive(sourceAnimation, referenceFrame = 0, range, cloneOriginal = false, clonedName) {\n let animation = sourceAnimation;\n if (cloneOriginal) {\n animation = sourceAnimation.clone();\n animation.name = clonedName || animation.name;\n }\n if (!animation._keys.length) {\n return animation;\n }\n referenceFrame = referenceFrame >= 0 ? referenceFrame : 0;\n let startIndex = 0;\n const firstKey = animation._keys[0];\n let endIndex = animation._keys.length - 1;\n const lastKey = animation._keys[endIndex];\n const valueStore = {\n referenceValue: firstKey.value,\n referencePosition: TmpVectors.Vector3[0],\n referenceQuaternion: TmpVectors.Quaternion[0],\n referenceScaling: TmpVectors.Vector3[1],\n keyPosition: TmpVectors.Vector3[2],\n keyQuaternion: TmpVectors.Quaternion[1],\n keyScaling: TmpVectors.Vector3[3],\n };\n let referenceFound = false;\n let from = firstKey.frame;\n let to = lastKey.frame;\n if (range) {\n const rangeValue = animation.getRange(range);\n if (rangeValue) {\n from = rangeValue.from;\n to = rangeValue.to;\n }\n }\n let fromKeyFound = firstKey.frame === from;\n let toKeyFound = lastKey.frame === to;\n // There's only one key, so use it\n if (animation._keys.length === 1) {\n const value = animation._getKeyValue(animation._keys[0]);\n valueStore.referenceValue = value.clone ? value.clone() : value;\n referenceFound = true;\n }\n // Reference frame is before the first frame, so just use the first frame\n else if (referenceFrame <= firstKey.frame) {\n const value = animation._getKeyValue(firstKey.value);\n valueStore.referenceValue = value.clone ? value.clone() : value;\n referenceFound = true;\n }\n // Reference frame is after the last frame, so just use the last frame\n else if (referenceFrame >= lastKey.frame) {\n const value = animation._getKeyValue(lastKey.value);\n valueStore.referenceValue = value.clone ? value.clone() : value;\n referenceFound = true;\n }\n // Find key bookends, create them if they don't exist\n let index = 0;\n while (!referenceFound || !fromKeyFound || (!toKeyFound && index < animation._keys.length - 1)) {\n const currentKey = animation._keys[index];\n const nextKey = animation._keys[index + 1];\n // If reference frame wasn't found yet, check if we can interpolate to it\n if (!referenceFound && referenceFrame >= currentKey.frame && referenceFrame <= nextKey.frame) {\n let value;\n if (referenceFrame === currentKey.frame) {\n value = animation._getKeyValue(currentKey.value);\n }\n else if (referenceFrame === nextKey.frame) {\n value = animation._getKeyValue(nextKey.value);\n }\n else {\n const animationState = {\n key: index,\n repeatCount: 0,\n loopMode: this.ANIMATIONLOOPMODE_CONSTANT,\n };\n value = animation._interpolate(referenceFrame, animationState);\n }\n valueStore.referenceValue = value.clone ? value.clone() : value;\n referenceFound = true;\n }\n // If from key wasn't found yet, check if we can interpolate to it\n if (!fromKeyFound && from >= currentKey.frame && from <= nextKey.frame) {\n if (from === currentKey.frame) {\n startIndex = index;\n }\n else if (from === nextKey.frame) {\n startIndex = index + 1;\n }\n else {\n const animationState = {\n key: index,\n repeatCount: 0,\n loopMode: this.ANIMATIONLOOPMODE_CONSTANT,\n };\n const value = animation._interpolate(from, animationState);\n const key = {\n frame: from,\n value: value.clone ? value.clone() : value,\n };\n animation._keys.splice(index + 1, 0, key);\n startIndex = index + 1;\n }\n fromKeyFound = true;\n }\n // If to key wasn't found yet, check if we can interpolate to it\n if (!toKeyFound && to >= currentKey.frame && to <= nextKey.frame) {\n if (to === currentKey.frame) {\n endIndex = index;\n }\n else if (to === nextKey.frame) {\n endIndex = index + 1;\n }\n else {\n const animationState = {\n key: index,\n repeatCount: 0,\n loopMode: this.ANIMATIONLOOPMODE_CONSTANT,\n };\n const value = animation._interpolate(to, animationState);\n const key = {\n frame: to,\n value: value.clone ? value.clone() : value,\n };\n animation._keys.splice(index + 1, 0, key);\n endIndex = index + 1;\n }\n toKeyFound = true;\n }\n index++;\n }\n // Conjugate the quaternion\n if (animation.dataType === Animation.ANIMATIONTYPE_QUATERNION) {\n valueStore.referenceValue.normalize().conjugateInPlace();\n }\n // Decompose matrix and conjugate the quaternion\n else if (animation.dataType === Animation.ANIMATIONTYPE_MATRIX) {\n valueStore.referenceValue.decompose(valueStore.referenceScaling, valueStore.referenceQuaternion, valueStore.referencePosition);\n valueStore.referenceQuaternion.normalize().conjugateInPlace();\n }\n // Subtract the reference value from all of the key values\n for (index = startIndex; index <= endIndex; index++) {\n const key = animation._keys[index];\n // If this key was duplicated to create a frame 0 key, skip it because its value has already been updated\n if (index && animation.dataType !== Animation.ANIMATIONTYPE_FLOAT && key.value === firstKey.value) {\n continue;\n }\n switch (animation.dataType) {\n case Animation.ANIMATIONTYPE_MATRIX:\n key.value.decompose(valueStore.keyScaling, valueStore.keyQuaternion, valueStore.keyPosition);\n valueStore.keyPosition.subtractInPlace(valueStore.referencePosition);\n valueStore.keyScaling.divideInPlace(valueStore.referenceScaling);\n valueStore.referenceQuaternion.multiplyToRef(valueStore.keyQuaternion, valueStore.keyQuaternion);\n Matrix.ComposeToRef(valueStore.keyScaling, valueStore.keyQuaternion, valueStore.keyPosition, key.value);\n break;\n case Animation.ANIMATIONTYPE_QUATERNION:\n valueStore.referenceValue.multiplyToRef(key.value, key.value);\n break;\n case Animation.ANIMATIONTYPE_VECTOR2:\n case Animation.ANIMATIONTYPE_VECTOR3:\n case Animation.ANIMATIONTYPE_COLOR3:\n case Animation.ANIMATIONTYPE_COLOR4:\n key.value.subtractToRef(valueStore.referenceValue, key.value);\n break;\n case Animation.ANIMATIONTYPE_SIZE:\n key.value.width -= valueStore.referenceValue.width;\n key.value.height -= valueStore.referenceValue.height;\n break;\n default:\n key.value -= valueStore.referenceValue;\n }\n }\n return animation;\n }\n /**\n * Transition property of an host to the target Value\n * @param property The property to transition\n * @param targetValue The target Value of the property\n * @param host The object where the property to animate belongs\n * @param scene Scene used to run the animation\n * @param frameRate Framerate (in frame/s) to use\n * @param transition The transition type we want to use\n * @param duration The duration of the animation, in milliseconds\n * @param onAnimationEnd Callback trigger at the end of the animation\n * @returns Nullable animation\n */\n static TransitionTo(property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd = null) {\n if (duration <= 0) {\n host[property] = targetValue;\n if (onAnimationEnd) {\n onAnimationEnd();\n }\n return null;\n }\n const endFrame = frameRate * (duration / 1000);\n transition.setKeys([\n {\n frame: 0,\n value: host[property].clone ? host[property].clone() : host[property],\n },\n {\n frame: endFrame,\n value: targetValue,\n },\n ]);\n if (!host.animations) {\n host.animations = [];\n }\n host.animations.push(transition);\n const animation = scene.beginAnimation(host, 0, endFrame, false);\n animation.onAnimationEnd = onAnimationEnd;\n return animation;\n }\n /**\n * Return the array of runtime animations currently using this animation\n */\n get runtimeAnimations() {\n return this._runtimeAnimations;\n }\n /**\n * Specifies if any of the runtime animations are currently running\n */\n get hasRunningRuntimeAnimations() {\n for (const runtimeAnimation of this._runtimeAnimations) {\n if (!runtimeAnimation.isStopped()) {\n return true;\n }\n }\n return false;\n }\n /**\n * Initializes the animation\n * @param name Name of the animation\n * @param targetProperty Property to animate\n * @param framePerSecond The frames per second of the animation\n * @param dataType The data type of the animation\n * @param loopMode The loop mode of the animation\n * @param enableBlending Specifies if blending should be enabled\n */\n constructor(\n /**Name of the animation */\n name, \n /**Property to animate */\n targetProperty, \n /**The frames per second of the animation */\n framePerSecond, \n /**The data type of the animation */\n dataType, \n /**The loop mode of the animation */\n loopMode, \n /**Specifies if blending should be enabled */\n enableBlending) {\n this.name = name;\n this.targetProperty = targetProperty;\n this.framePerSecond = framePerSecond;\n this.dataType = dataType;\n this.loopMode = loopMode;\n this.enableBlending = enableBlending;\n /**\n * Stores the easing function of the animation\n */\n this._easingFunction = null;\n /**\n * @internal Internal use only\n */\n this._runtimeAnimations = new Array();\n /**\n * The set of event that will be linked to this animation\n */\n this._events = new Array();\n /**\n * Stores the blending speed of the animation\n */\n this.blendingSpeed = 0.01;\n /**\n * Stores the animation ranges for the animation\n */\n this._ranges = {};\n this.targetPropertyPath = targetProperty.split(\".\");\n this.dataType = dataType;\n this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;\n this.uniqueId = Animation._UniqueIdGenerator++;\n }\n // Methods\n /**\n * Converts the animation to a string\n * @param fullDetails support for multiple levels of logging within scene loading\n * @returns String form of the animation\n */\n toString(fullDetails) {\n let ret = \"Name: \" + this.name + \", property: \" + this.targetProperty;\n ret += \", datatype: \" + [\"Float\", \"Vector3\", \"Quaternion\", \"Matrix\", \"Color3\", \"Vector2\"][this.dataType];\n ret += \", nKeys: \" + (this._keys ? this._keys.length : \"none\");\n ret += \", nRanges: \" + (this._ranges ? Object.keys(this._ranges).length : \"none\");\n if (fullDetails) {\n ret += \", Ranges: {\";\n let first = true;\n for (const name in this._ranges) {\n if (first) {\n ret += \", \";\n first = false;\n }\n ret += name;\n }\n ret += \"}\";\n }\n return ret;\n }\n /**\n * Add an event to this animation\n * @param event Event to add\n */\n addEvent(event) {\n this._events.push(event);\n this._events.sort((a, b) => a.frame - b.frame);\n }\n /**\n * Remove all events found at the given frame\n * @param frame The frame to remove events from\n */\n removeEvents(frame) {\n for (let index = 0; index < this._events.length; index++) {\n if (this._events[index].frame === frame) {\n this._events.splice(index, 1);\n index--;\n }\n }\n }\n /**\n * Retrieves all the events from the animation\n * @returns Events from the animation\n */\n getEvents() {\n return this._events;\n }\n /**\n * Creates an animation range\n * @param name Name of the animation range\n * @param from Starting frame of the animation range\n * @param to Ending frame of the animation\n */\n createRange(name, from, to) {\n // check name not already in use; could happen for bones after serialized\n if (!this._ranges[name]) {\n this._ranges[name] = new AnimationRange(name, from, to);\n }\n }\n /**\n * Deletes an animation range by name\n * @param name Name of the animation range to delete\n * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)\n */\n deleteRange(name, deleteFrames = true) {\n const range = this._ranges[name];\n if (!range) {\n return;\n }\n if (deleteFrames) {\n const from = range.from;\n const to = range.to;\n // this loop MUST go high to low for multiple splices to work\n for (let key = this._keys.length - 1; key >= 0; key--) {\n if (this._keys[key].frame >= from && this._keys[key].frame <= to) {\n this._keys.splice(key, 1);\n }\n }\n }\n this._ranges[name] = null; // said much faster than 'delete this._range[name]'\n }\n /**\n * Gets the animation range by name, or null if not defined\n * @param name Name of the animation range\n * @returns Nullable animation range\n */\n getRange(name) {\n return this._ranges[name];\n }\n /**\n * Gets the key frames from the animation\n * @returns The key frames of the animation\n */\n getKeys() {\n return this._keys;\n }\n /**\n * Gets the highest frame rate of the animation\n * @returns Highest frame rate of the animation\n */\n getHighestFrame() {\n let ret = 0;\n for (let key = 0, nKeys = this._keys.length; key < nKeys; key++) {\n if (ret < this._keys[key].frame) {\n ret = this._keys[key].frame;\n }\n }\n return ret;\n }\n /**\n * Gets the easing function of the animation\n * @returns Easing function of the animation\n */\n getEasingFunction() {\n return this._easingFunction;\n }\n /**\n * Sets the easing function of the animation\n * @param easingFunction A custom mathematical formula for animation\n */\n setEasingFunction(easingFunction) {\n this._easingFunction = easingFunction;\n }\n /**\n * Interpolates a scalar linearly\n * @param startValue Start value of the animation curve\n * @param endValue End value of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated scalar value\n */\n floatInterpolateFunction(startValue, endValue, gradient) {\n return Scalar.Lerp(startValue, endValue, gradient);\n }\n /**\n * Interpolates a scalar cubically\n * @param startValue Start value of the animation curve\n * @param outTangent End tangent of the animation\n * @param endValue End value of the animation curve\n * @param inTangent Start tangent of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated scalar value\n */\n floatInterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) {\n return Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);\n }\n /**\n * Interpolates a quaternion using a spherical linear interpolation\n * @param startValue Start value of the animation curve\n * @param endValue End value of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated quaternion value\n */\n quaternionInterpolateFunction(startValue, endValue, gradient) {\n return Quaternion.Slerp(startValue, endValue, gradient);\n }\n /**\n * Interpolates a quaternion cubically\n * @param startValue Start value of the animation curve\n * @param outTangent End tangent of the animation curve\n * @param endValue End value of the animation curve\n * @param inTangent Start tangent of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated quaternion value\n */\n quaternionInterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) {\n return Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();\n }\n /**\n * Interpolates a Vector3 linearly\n * @param startValue Start value of the animation curve\n * @param endValue End value of the animation curve\n * @param gradient Scalar amount to interpolate (value between 0 and 1)\n * @returns Interpolated scalar value\n */\n vector3InterpolateFunction(startValue, endValue, gradient) {\n return Vector3.Lerp(startValue, endValue, gradient);\n }\n /**\n * Interpolates a Vector3 cubically\n * @param startValue Start value of the animation curve\n * @param outTangent End tangent of the animation\n * @param endValue End value of the animation curve\n * @param inTangent Start tangent of the animation curve\n * @param gradient Scalar amount to interpolate (value between 0 and 1)\n * @returns InterpolatedVector3 value\n */\n vector3InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) {\n return Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);\n }\n /**\n * Interpolates a Vector2 linearly\n * @param startValue Start value of the animation curve\n * @param endValue End value of the animation curve\n * @param gradient Scalar amount to interpolate (value between 0 and 1)\n * @returns Interpolated Vector2 value\n */\n vector2InterpolateFunction(startValue, endValue, gradient) {\n return Vector2.Lerp(startValue, endValue, gradient);\n }\n /**\n * Interpolates a Vector2 cubically\n * @param startValue Start value of the animation curve\n * @param outTangent End tangent of the animation\n * @param endValue End value of the animation curve\n * @param inTangent Start tangent of the animation curve\n * @param gradient Scalar amount to interpolate (value between 0 and 1)\n * @returns Interpolated Vector2 value\n */\n vector2InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) {\n return Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);\n }\n /**\n * Interpolates a size linearly\n * @param startValue Start value of the animation curve\n * @param endValue End value of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated Size value\n */\n sizeInterpolateFunction(startValue, endValue, gradient) {\n return Size.Lerp(startValue, endValue, gradient);\n }\n /**\n * Interpolates a Color3 linearly\n * @param startValue Start value of the animation curve\n * @param endValue End value of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated Color3 value\n */\n color3InterpolateFunction(startValue, endValue, gradient) {\n return Color3.Lerp(startValue, endValue, gradient);\n }\n /**\n * Interpolates a Color3 cubically\n * @param startValue Start value of the animation curve\n * @param outTangent End tangent of the animation\n * @param endValue End value of the animation curve\n * @param inTangent Start tangent of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns interpolated value\n */\n color3InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) {\n return Color3.Hermite(startValue, outTangent, endValue, inTangent, gradient);\n }\n /**\n * Interpolates a Color4 linearly\n * @param startValue Start value of the animation curve\n * @param endValue End value of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated Color3 value\n */\n color4InterpolateFunction(startValue, endValue, gradient) {\n return Color4.Lerp(startValue, endValue, gradient);\n }\n /**\n * Interpolates a Color4 cubically\n * @param startValue Start value of the animation curve\n * @param outTangent End tangent of the animation\n * @param endValue End value of the animation curve\n * @param inTangent Start tangent of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns interpolated value\n */\n color4InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) {\n return Color4.Hermite(startValue, outTangent, endValue, inTangent, gradient);\n }\n /**\n * @internal Internal use only\n */\n _getKeyValue(value) {\n if (typeof value === \"function\") {\n return value();\n }\n return value;\n }\n /**\n * Evaluate the animation value at a given frame\n * @param currentFrame defines the frame where we want to evaluate the animation\n * @returns the animation value\n */\n evaluate(currentFrame) {\n return this._interpolate(currentFrame, {\n key: 0,\n repeatCount: 0,\n loopMode: Animation.ANIMATIONLOOPMODE_CONSTANT,\n });\n }\n /**\n * @internal Internal use only\n */\n _interpolate(currentFrame, state) {\n if (state.loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && state.repeatCount > 0) {\n return state.highLimitValue.clone ? state.highLimitValue.clone() : state.highLimitValue;\n }\n const keys = this._keys;\n const keysLength = keys.length;\n let key = state.key;\n while (key >= 0 && currentFrame < keys[key].frame) {\n --key;\n }\n while (key + 1 <= keysLength - 1 && currentFrame >= keys[key + 1].frame) {\n ++key;\n }\n state.key = key;\n if (key < 0) {\n return this._getKeyValue(keys[0].value);\n }\n else if (key + 1 > keysLength - 1) {\n return this._getKeyValue(keys[keysLength - 1].value);\n }\n const startKey = keys[key];\n const endKey = keys[key + 1];\n const startValue = this._getKeyValue(startKey.value);\n const endValue = this._getKeyValue(endKey.value);\n if (startKey.interpolation === AnimationKeyInterpolation.STEP) {\n if (endKey.frame > currentFrame) {\n return startValue;\n }\n else {\n return endValue;\n }\n }\n const useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;\n const frameDelta = endKey.frame - startKey.frame;\n // gradient : percent of currentFrame between the frame inf and the frame sup\n let gradient = (currentFrame - startKey.frame) / frameDelta;\n // check for easingFunction and correction of gradient\n const easingFunction = this.getEasingFunction();\n if (easingFunction !== null) {\n gradient = easingFunction.ease(gradient);\n }\n switch (this.dataType) {\n // Float\n case Animation.ANIMATIONTYPE_FLOAT: {\n const floatValue = useTangent\n ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient)\n : this.floatInterpolateFunction(startValue, endValue, gradient);\n switch (state.loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n case Animation.ANIMATIONLOOPMODE_YOYO:\n return floatValue;\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return state.offsetValue * state.repeatCount + floatValue;\n }\n break;\n }\n // Quaternion\n case Animation.ANIMATIONTYPE_QUATERNION: {\n const quatValue = useTangent\n ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient)\n : this.quaternionInterpolateFunction(startValue, endValue, gradient);\n switch (state.loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n case Animation.ANIMATIONLOOPMODE_YOYO:\n return quatValue;\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return quatValue.addInPlace(state.offsetValue.scale(state.repeatCount));\n }\n return quatValue;\n }\n // Vector3\n case Animation.ANIMATIONTYPE_VECTOR3: {\n const vec3Value = useTangent\n ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient)\n : this.vector3InterpolateFunction(startValue, endValue, gradient);\n switch (state.loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n case Animation.ANIMATIONLOOPMODE_YOYO:\n return vec3Value;\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return vec3Value.add(state.offsetValue.scale(state.repeatCount));\n }\n break;\n }\n // Vector2\n case Animation.ANIMATIONTYPE_VECTOR2: {\n const vec2Value = useTangent\n ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient)\n : this.vector2InterpolateFunction(startValue, endValue, gradient);\n switch (state.loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n case Animation.ANIMATIONLOOPMODE_YOYO:\n return vec2Value;\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return vec2Value.add(state.offsetValue.scale(state.repeatCount));\n }\n break;\n }\n // Size\n case Animation.ANIMATIONTYPE_SIZE: {\n switch (state.loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n case Animation.ANIMATIONLOOPMODE_YOYO:\n return this.sizeInterpolateFunction(startValue, endValue, gradient);\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return this.sizeInterpolateFunction(startValue, endValue, gradient).add(state.offsetValue.scale(state.repeatCount));\n }\n break;\n }\n // Color3\n case Animation.ANIMATIONTYPE_COLOR3: {\n const color3Value = useTangent\n ? this.color3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient)\n : this.color3InterpolateFunction(startValue, endValue, gradient);\n switch (state.loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n case Animation.ANIMATIONLOOPMODE_YOYO:\n return color3Value;\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return color3Value.add(state.offsetValue.scale(state.repeatCount));\n }\n break;\n }\n // Color4\n case Animation.ANIMATIONTYPE_COLOR4: {\n const color4Value = useTangent\n ? this.color4InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient)\n : this.color4InterpolateFunction(startValue, endValue, gradient);\n switch (state.loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n case Animation.ANIMATIONLOOPMODE_YOYO:\n return color4Value;\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return color4Value.add(state.offsetValue.scale(state.repeatCount));\n }\n break;\n }\n // Matrix\n case Animation.ANIMATIONTYPE_MATRIX: {\n switch (state.loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n case Animation.ANIMATIONLOOPMODE_YOYO: {\n if (Animation.AllowMatricesInterpolation) {\n return this.matrixInterpolateFunction(startValue, endValue, gradient, state.workValue);\n }\n return startValue;\n }\n case Animation.ANIMATIONLOOPMODE_RELATIVE: {\n return startValue;\n }\n }\n break;\n }\n }\n return 0;\n }\n /**\n * Defines the function to use to interpolate matrices\n * @param startValue defines the start matrix\n * @param endValue defines the end matrix\n * @param gradient defines the gradient between both matrices\n * @param result defines an optional target matrix where to store the interpolation\n * @returns the interpolated matrix\n */\n matrixInterpolateFunction(startValue, endValue, gradient, result) {\n if (Animation.AllowMatrixDecomposeForInterpolation) {\n if (result) {\n Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);\n return result;\n }\n return Matrix.DecomposeLerp(startValue, endValue, gradient);\n }\n if (result) {\n Matrix.LerpToRef(startValue, endValue, gradient, result);\n return result;\n }\n return Matrix.Lerp(startValue, endValue, gradient);\n }\n /**\n * Makes a copy of the animation\n * @returns Cloned animation\n */\n clone() {\n const clone = new Animation(this.name, this.targetPropertyPath.join(\".\"), this.framePerSecond, this.dataType, this.loopMode);\n clone.enableBlending = this.enableBlending;\n clone.blendingSpeed = this.blendingSpeed;\n if (this._keys) {\n clone.setKeys(this._keys);\n }\n if (this._ranges) {\n clone._ranges = {};\n for (const name in this._ranges) {\n const range = this._ranges[name];\n if (!range) {\n continue;\n }\n clone._ranges[name] = range.clone();\n }\n }\n return clone;\n }\n /**\n * Sets the key frames of the animation\n * @param values The animation key frames to set\n */\n setKeys(values) {\n this._keys = values.slice(0);\n }\n /**\n * Serializes the animation to an object\n * @returns Serialized object\n */\n serialize() {\n const serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.property = this.targetProperty;\n serializationObject.framePerSecond = this.framePerSecond;\n serializationObject.dataType = this.dataType;\n serializationObject.loopBehavior = this.loopMode;\n serializationObject.enableBlending = this.enableBlending;\n serializationObject.blendingSpeed = this.blendingSpeed;\n const dataType = this.dataType;\n serializationObject.keys = [];\n const keys = this.getKeys();\n for (let index = 0; index < keys.length; index++) {\n const animationKey = keys[index];\n const key = {};\n key.frame = animationKey.frame;\n switch (dataType) {\n case Animation.ANIMATIONTYPE_FLOAT:\n key.values = [animationKey.value];\n if (animationKey.inTangent !== undefined) {\n key.values.push(animationKey.inTangent);\n }\n if (animationKey.outTangent !== undefined) {\n if (animationKey.inTangent === undefined) {\n key.values.push(undefined);\n }\n key.values.push(animationKey.outTangent);\n }\n if (animationKey.interpolation !== undefined) {\n if (animationKey.inTangent === undefined) {\n key.values.push(undefined);\n }\n if (animationKey.outTangent === undefined) {\n key.values.push(undefined);\n }\n key.values.push(animationKey.interpolation);\n }\n break;\n case Animation.ANIMATIONTYPE_QUATERNION:\n case Animation.ANIMATIONTYPE_MATRIX:\n case Animation.ANIMATIONTYPE_VECTOR3:\n case Animation.ANIMATIONTYPE_COLOR3:\n case Animation.ANIMATIONTYPE_COLOR4:\n key.values = animationKey.value.asArray();\n if (animationKey.inTangent != undefined) {\n key.values.push(animationKey.inTangent.asArray());\n }\n if (animationKey.outTangent != undefined) {\n if (animationKey.inTangent === undefined) {\n key.values.push(undefined);\n }\n key.values.push(animationKey.outTangent.asArray());\n }\n if (animationKey.interpolation !== undefined) {\n if (animationKey.inTangent === undefined) {\n key.values.push(undefined);\n }\n if (animationKey.outTangent === undefined) {\n key.values.push(undefined);\n }\n key.values.push(animationKey.interpolation);\n }\n break;\n }\n serializationObject.keys.push(key);\n }\n serializationObject.ranges = [];\n for (const name in this._ranges) {\n const source = this._ranges[name];\n if (!source) {\n continue;\n }\n const range = {};\n range.name = name;\n range.from = source.from;\n range.to = source.to;\n serializationObject.ranges.push(range);\n }\n return serializationObject;\n }\n /**\n * @internal\n */\n static _UniversalLerp(left, right, amount) {\n const constructor = left.constructor;\n if (constructor.Lerp) {\n // Lerp supported\n return constructor.Lerp(left, right, amount);\n }\n else if (constructor.Slerp) {\n // Slerp supported\n return constructor.Slerp(left, right, amount);\n }\n else if (left.toFixed) {\n // Number\n return left * (1.0 - amount) + amount * right;\n }\n else {\n // Blending not supported\n return right;\n }\n }\n /**\n * Parses an animation object and creates an animation\n * @param parsedAnimation Parsed animation object\n * @returns Animation object\n */\n static Parse(parsedAnimation) {\n const animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);\n const dataType = parsedAnimation.dataType;\n const keys = [];\n let data;\n let index;\n if (parsedAnimation.enableBlending) {\n animation.enableBlending = parsedAnimation.enableBlending;\n }\n if (parsedAnimation.blendingSpeed) {\n animation.blendingSpeed = parsedAnimation.blendingSpeed;\n }\n for (index = 0; index < parsedAnimation.keys.length; index++) {\n const key = parsedAnimation.keys[index];\n let inTangent = undefined;\n let outTangent = undefined;\n let interpolation = undefined;\n switch (dataType) {\n case Animation.ANIMATIONTYPE_FLOAT:\n data = key.values[0];\n if (key.values.length >= 2) {\n inTangent = key.values[1];\n }\n if (key.values.length >= 3) {\n outTangent = key.values[2];\n }\n if (key.values.length >= 4) {\n interpolation = key.values[3];\n }\n break;\n case Animation.ANIMATIONTYPE_QUATERNION:\n data = Quaternion.FromArray(key.values);\n if (key.values.length >= 8) {\n const _inTangent = Quaternion.FromArray(key.values.slice(4, 8));\n if (!_inTangent.equals(Quaternion.Zero())) {\n inTangent = _inTangent;\n }\n }\n if (key.values.length >= 12) {\n const _outTangent = Quaternion.FromArray(key.values.slice(8, 12));\n if (!_outTangent.equals(Quaternion.Zero())) {\n outTangent = _outTangent;\n }\n }\n if (key.values.length >= 13) {\n interpolation = key.values[12];\n }\n break;\n case Animation.ANIMATIONTYPE_MATRIX:\n data = Matrix.FromArray(key.values);\n if (key.values.length >= 17) {\n interpolation = key.values[16];\n }\n break;\n case Animation.ANIMATIONTYPE_COLOR3:\n data = Color3.FromArray(key.values);\n if (key.values[3]) {\n inTangent = Color3.FromArray(key.values[3]);\n }\n if (key.values[4]) {\n outTangent = Color3.FromArray(key.values[4]);\n }\n if (key.values[5]) {\n interpolation = key.values[5];\n }\n break;\n case Animation.ANIMATIONTYPE_COLOR4:\n data = Color4.FromArray(key.values);\n if (key.values[4]) {\n inTangent = Color4.FromArray(key.values[4]);\n }\n if (key.values[5]) {\n outTangent = Color4.FromArray(key.values[5]);\n }\n if (key.values[6]) {\n interpolation = Color4.FromArray(key.values[6]);\n }\n break;\n case Animation.ANIMATIONTYPE_VECTOR3:\n default:\n data = Vector3.FromArray(key.values);\n if (key.values[3]) {\n inTangent = Vector3.FromArray(key.values[3]);\n }\n if (key.values[4]) {\n outTangent = Vector3.FromArray(key.values[4]);\n }\n if (key.values[5]) {\n interpolation = key.values[5];\n }\n break;\n }\n const keyData = {};\n keyData.frame = key.frame;\n keyData.value = data;\n if (inTangent != undefined) {\n keyData.inTangent = inTangent;\n }\n if (outTangent != undefined) {\n keyData.outTangent = outTangent;\n }\n if (interpolation != undefined) {\n keyData.interpolation = interpolation;\n }\n keys.push(keyData);\n }\n animation.setKeys(keys);\n if (parsedAnimation.ranges) {\n for (index = 0; index < parsedAnimation.ranges.length; index++) {\n data = parsedAnimation.ranges[index];\n animation.createRange(data.name, data.from, data.to);\n }\n }\n return animation;\n }\n /**\n * Appends the serialized animations from the source animations\n * @param source Source containing the animations\n * @param destination Target to store the animations\n */\n static AppendSerializedAnimations(source, destination) {\n SerializationHelper.AppendSerializedAnimations(source, destination);\n }\n /**\n * Creates a new animation or an array of animations from a snippet saved in a remote file\n * @param name defines the name of the animation to create (can be null or empty to use the one from the json data)\n * @param url defines the url to load from\n * @returns a promise that will resolve to the new animation or an array of animations\n */\n static ParseFromFileAsync(name, url) {\n return new Promise((resolve, reject) => {\n const request = new WebRequest();\n request.addEventListener(\"readystatechange\", () => {\n if (request.readyState == 4) {\n if (request.status == 200) {\n let serializationObject = JSON.parse(request.responseText);\n if (serializationObject.animations) {\n serializationObject = serializationObject.animations;\n }\n if (serializationObject.length) {\n const output = new Array();\n for (const serializedAnimation of serializationObject) {\n output.push(this.Parse(serializedAnimation));\n }\n resolve(output);\n }\n else {\n const output = this.Parse(serializationObject);\n if (name) {\n output.name = name;\n }\n resolve(output);\n }\n }\n else {\n reject(\"Unable to load the animation\");\n }\n }\n });\n request.open(\"GET\", url);\n request.send();\n });\n }\n /**\n * Creates an animation or an array of animations from a snippet saved by the Inspector\n * @param snippetId defines the snippet to load\n * @returns a promise that will resolve to the new animation or a new array of animations\n */\n static ParseFromSnippetAsync(snippetId) {\n return new Promise((resolve, reject) => {\n const request = new WebRequest();\n request.addEventListener(\"readystatechange\", () => {\n if (request.readyState == 4) {\n if (request.status == 200) {\n const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload);\n if (snippet.animations) {\n const serializationObject = JSON.parse(snippet.animations);\n const outputs = new Array();\n for (const serializedAnimation of serializationObject.animations) {\n const output = this.Parse(serializedAnimation);\n output.snippetId = snippetId;\n outputs.push(output);\n }\n resolve(outputs);\n }\n else {\n const serializationObject = JSON.parse(snippet.animation);\n const output = this.Parse(serializationObject);\n output.snippetId = snippetId;\n resolve(output);\n }\n }\n else {\n reject(\"Unable to load the snippet \" + snippetId);\n }\n }\n });\n request.open(\"GET\", this.SnippetUrl + \"/\" + snippetId.replace(/#/g, \"/\"));\n request.send();\n });\n }\n}\nAnimation._UniqueIdGenerator = 0;\n/**\n * Use matrix interpolation instead of using direct key value when animating matrices\n */\nAnimation.AllowMatricesInterpolation = false;\n/**\n * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower\n */\nAnimation.AllowMatrixDecomposeForInterpolation = true;\n/** Define the Url to load snippets */\nAnimation.SnippetUrl = `https://snippet.babylonjs.com`;\n// Statics\n/**\n * Float animation type\n */\nAnimation.ANIMATIONTYPE_FLOAT = 0;\n/**\n * Vector3 animation type\n */\nAnimation.ANIMATIONTYPE_VECTOR3 = 1;\n/**\n * Quaternion animation type\n */\nAnimation.ANIMATIONTYPE_QUATERNION = 2;\n/**\n * Matrix animation type\n */\nAnimation.ANIMATIONTYPE_MATRIX = 3;\n/**\n * Color3 animation type\n */\nAnimation.ANIMATIONTYPE_COLOR3 = 4;\n/**\n * Color3 animation type\n */\nAnimation.ANIMATIONTYPE_COLOR4 = 7;\n/**\n * Vector2 animation type\n */\nAnimation.ANIMATIONTYPE_VECTOR2 = 5;\n/**\n * Size animation type\n */\nAnimation.ANIMATIONTYPE_SIZE = 6;\n/**\n * Relative Loop Mode\n */\nAnimation.ANIMATIONLOOPMODE_RELATIVE = 0;\n/**\n * Cycle Loop Mode\n */\nAnimation.ANIMATIONLOOPMODE_CYCLE = 1;\n/**\n * Constant Loop Mode\n */\nAnimation.ANIMATIONLOOPMODE_CONSTANT = 2;\n/**\n * Yoyo Loop Mode\n */\nAnimation.ANIMATIONLOOPMODE_YOYO = 4;\n/**\n * Creates an animation or an array of animations from a snippet saved by the Inspector\n * @deprecated Please use ParseFromSnippetAsync instead\n * @param snippetId defines the snippet to load\n * @returns a promise that will resolve to the new animation or a new array of animations\n */\nAnimation.CreateFromSnippetAsync = Animation.ParseFromSnippetAsync;\nRegisterClass(\"BABYLON.Animation\", Animation);\nNode._AnimationRangeFactory = (name, from, to) => new AnimationRange(name, from, to);\n//# sourceMappingURL=animation.js.map","import { Action } from \"./action.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { Vector3, Matrix, Quaternion } from \"../Maths/math.vector.js\";\nimport { Animation } from \"../Animations/animation.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\n/**\n * This defines an action responsible to change the value of a property\n * by interpolating between its current value and the newly set one once triggered.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\nexport class InterpolateValueAction extends Action {\n /**\n * Instantiate the action\n * @param triggerOptions defines the trigger options\n * @param target defines the object containing the value to interpolate\n * @param propertyPath defines the path to the property in the target object\n * @param value defines the target value at the end of the interpolation\n * @param duration defines the time it will take for the property to interpolate to the value.\n * @param condition defines the trigger related conditions\n * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered\n * @param onInterpolationDone defines a callback raised once the interpolation animation has been done\n */\n constructor(triggerOptions, target, propertyPath, value, duration = 1000, condition, stopOtherAnimations, onInterpolationDone) {\n super(triggerOptions, condition);\n /**\n * Defines the time it will take for the property to interpolate to the value.\n */\n this.duration = 1000;\n /**\n * Observable triggered once the interpolation animation has been done.\n */\n this.onInterpolationDoneObservable = new Observable();\n this.propertyPath = propertyPath;\n this.value = value;\n this.duration = duration;\n this.stopOtherAnimations = stopOtherAnimations;\n this.onInterpolationDone = onInterpolationDone;\n this._target = this._effectiveTarget = target;\n }\n /** @internal */\n _prepare() {\n this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);\n this._property = this._getProperty(this.propertyPath);\n }\n /**\n * Execute the action starts the value interpolation.\n */\n execute() {\n const scene = this._actionManager.getScene();\n const keys = [\n {\n frame: 0,\n value: this._effectiveTarget[this._property],\n },\n {\n frame: 100,\n value: this.value,\n },\n ];\n let dataType;\n if (typeof this.value === \"number\") {\n dataType = Animation.ANIMATIONTYPE_FLOAT;\n }\n else if (this.value instanceof Color3) {\n dataType = Animation.ANIMATIONTYPE_COLOR3;\n }\n else if (this.value instanceof Vector3) {\n dataType = Animation.ANIMATIONTYPE_VECTOR3;\n }\n else if (this.value instanceof Matrix) {\n dataType = Animation.ANIMATIONTYPE_MATRIX;\n }\n else if (this.value instanceof Quaternion) {\n dataType = Animation.ANIMATIONTYPE_QUATERNION;\n }\n else {\n Logger.Warn(\"InterpolateValueAction: Unsupported type (\" + typeof this.value + \")\");\n return;\n }\n const animation = new Animation(\"InterpolateValueAction\", this._property, 100 * (1000.0 / this.duration), dataType, Animation.ANIMATIONLOOPMODE_CONSTANT);\n animation.setKeys(keys);\n if (this.stopOtherAnimations) {\n scene.stopAnimation(this._effectiveTarget);\n }\n const wrapper = () => {\n this.onInterpolationDoneObservable.notifyObservers(this);\n if (this.onInterpolationDone) {\n this.onInterpolationDone();\n }\n };\n scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);\n }\n /**\n * Serializes the actions and its related information.\n * @param parent defines the object to serialize in\n * @returns the serialized object\n */\n serialize(parent) {\n return super._serialize({\n name: \"InterpolateValueAction\",\n properties: [\n Action._GetTargetProperty(this._target),\n { name: \"propertyPath\", value: this.propertyPath },\n { name: \"value\", value: Action._SerializeValueAsString(this.value) },\n { name: \"duration\", value: Action._SerializeValueAsString(this.duration) },\n { name: \"stopOtherAnimations\", value: Action._SerializeValueAsString(this.stopOtherAnimations) || false },\n ],\n }, parent);\n }\n}\nRegisterClass(\"BABYLON.InterpolateValueAction\", InterpolateValueAction);\n//# sourceMappingURL=interpolateValueAction.js.map","import { Quaternion, Vector3, Vector2, Matrix } from \"../Maths/math.vector.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { Animation } from \"./animation.js\";\nimport { Size } from \"../Maths/math.size.js\";\n// Static values to help the garbage collector\n// Quaternion\nconst _staticOffsetValueQuaternion = Object.freeze(new Quaternion(0, 0, 0, 0));\n// Vector3\nconst _staticOffsetValueVector3 = Object.freeze(Vector3.Zero());\n// Vector2\nconst _staticOffsetValueVector2 = Object.freeze(Vector2.Zero());\n// Size\nconst _staticOffsetValueSize = Object.freeze(Size.Zero());\n// Color3\nconst _staticOffsetValueColor3 = Object.freeze(Color3.Black());\n/**\n * Defines a runtime animation\n */\nexport class RuntimeAnimation {\n /**\n * Gets the current frame of the runtime animation\n */\n get currentFrame() {\n return this._currentFrame;\n }\n /**\n * Gets the weight of the runtime animation\n */\n get weight() {\n return this._weight;\n }\n /**\n * Gets the current value of the runtime animation\n */\n get currentValue() {\n return this._currentValue;\n }\n /**\n * Gets or sets the target path of the runtime animation\n */\n get targetPath() {\n return this._targetPath;\n }\n /**\n * Gets the actual target of the runtime animation\n */\n get target() {\n return this._currentActiveTarget;\n }\n /**\n * Gets the additive state of the runtime animation\n */\n get isAdditive() {\n return this._host && this._host.isAdditive;\n }\n /**\n * Create a new RuntimeAnimation object\n * @param target defines the target of the animation\n * @param animation defines the source animation object\n * @param scene defines the hosting scene\n * @param host defines the initiating Animatable\n */\n constructor(target, animation, scene, host) {\n this._events = new Array();\n /**\n * The current frame of the runtime animation\n */\n this._currentFrame = 0;\n /**\n * The original value of the runtime animation\n */\n this._originalValue = new Array();\n /**\n * The original blend value of the runtime animation\n */\n this._originalBlendValue = null;\n /**\n * The offsets cache of the runtime animation\n */\n this._offsetsCache = {};\n /**\n * The high limits cache of the runtime animation\n */\n this._highLimitsCache = {};\n /**\n * Specifies if the runtime animation has been stopped\n */\n this._stopped = false;\n /**\n * The blending factor of the runtime animation\n */\n this._blendingFactor = 0;\n /**\n * The current value of the runtime animation\n */\n this._currentValue = null;\n this._currentActiveTarget = null;\n this._directTarget = null;\n /**\n * The target path of the runtime animation\n */\n this._targetPath = \"\";\n /**\n * The weight of the runtime animation\n */\n this._weight = 1.0;\n /**\n * The ratio offset of the runtime animation\n */\n this._ratioOffset = 0;\n /**\n * The previous delay of the runtime animation\n */\n this._previousDelay = 0;\n /**\n * The previous ratio of the runtime animation\n */\n this._previousRatio = 0;\n this._targetIsArray = false;\n this._animation = animation;\n this._target = target;\n this._scene = scene;\n this._host = host;\n this._activeTargets = [];\n animation._runtimeAnimations.push(this);\n // State\n this._animationState = {\n key: 0,\n repeatCount: 0,\n loopMode: this._getCorrectLoopMode(),\n };\n if (this._animation.dataType === Animation.ANIMATIONTYPE_MATRIX) {\n this._animationState.workValue = Matrix.Zero();\n }\n // Limits\n this._keys = this._animation.getKeys();\n this._minFrame = this._keys[0].frame;\n this._maxFrame = this._keys[this._keys.length - 1].frame;\n this._minValue = this._keys[0].value;\n this._maxValue = this._keys[this._keys.length - 1].value;\n // Add a start key at frame 0 if missing\n if (this._minFrame !== 0) {\n const newKey = { frame: 0, value: this._minValue };\n this._keys.splice(0, 0, newKey);\n }\n // Check data\n if (this._target instanceof Array) {\n let index = 0;\n for (const target of this._target) {\n this._preparePath(target, index);\n this._getOriginalValues(index);\n index++;\n }\n this._targetIsArray = true;\n }\n else {\n this._preparePath(this._target);\n this._getOriginalValues();\n this._targetIsArray = false;\n this._directTarget = this._activeTargets[0];\n }\n // Cloning events locally\n const events = animation.getEvents();\n if (events && events.length > 0) {\n events.forEach((e) => {\n this._events.push(e._clone());\n });\n }\n this._enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;\n }\n _preparePath(target, targetIndex = 0) {\n const targetPropertyPath = this._animation.targetPropertyPath;\n if (targetPropertyPath.length > 1) {\n let property = target[targetPropertyPath[0]];\n for (let index = 1; index < targetPropertyPath.length - 1; index++) {\n property = property[targetPropertyPath[index]];\n }\n this._targetPath = targetPropertyPath[targetPropertyPath.length - 1];\n this._activeTargets[targetIndex] = property;\n }\n else {\n this._targetPath = targetPropertyPath[0];\n this._activeTargets[targetIndex] = target;\n }\n }\n /**\n * Gets the animation from the runtime animation\n */\n get animation() {\n return this._animation;\n }\n /**\n * Resets the runtime animation to the beginning\n * @param restoreOriginal defines whether to restore the target property to the original value\n */\n reset(restoreOriginal = false) {\n if (restoreOriginal) {\n if (this._target instanceof Array) {\n let index = 0;\n for (const target of this._target) {\n if (this._originalValue[index] !== undefined) {\n this._setValue(target, this._activeTargets[index], this._originalValue[index], -1, index);\n }\n index++;\n }\n }\n else {\n if (this._originalValue[0] !== undefined) {\n this._setValue(this._target, this._directTarget, this._originalValue[0], -1, 0);\n }\n }\n }\n this._offsetsCache = {};\n this._highLimitsCache = {};\n this._currentFrame = 0;\n this._blendingFactor = 0;\n // Events\n for (let index = 0; index < this._events.length; index++) {\n this._events[index].isDone = false;\n }\n }\n /**\n * Specifies if the runtime animation is stopped\n * @returns Boolean specifying if the runtime animation is stopped\n */\n isStopped() {\n return this._stopped;\n }\n /**\n * Disposes of the runtime animation\n */\n dispose() {\n const index = this._animation.runtimeAnimations.indexOf(this);\n if (index > -1) {\n this._animation.runtimeAnimations.splice(index, 1);\n }\n }\n /**\n * Apply the interpolated value to the target\n * @param currentValue defines the value computed by the animation\n * @param weight defines the weight to apply to this value (Defaults to 1.0)\n */\n setValue(currentValue, weight) {\n if (this._targetIsArray) {\n for (let index = 0; index < this._target.length; index++) {\n const target = this._target[index];\n this._setValue(target, this._activeTargets[index], currentValue, weight, index);\n }\n return;\n }\n this._setValue(this._target, this._directTarget, currentValue, weight, 0);\n }\n _getOriginalValues(targetIndex = 0) {\n let originalValue;\n const target = this._activeTargets[targetIndex];\n if (target.getRestPose && this._targetPath === \"_matrix\") {\n // For bones\n originalValue = target.getRestPose();\n }\n else {\n originalValue = target[this._targetPath];\n }\n if (originalValue && originalValue.clone) {\n this._originalValue[targetIndex] = originalValue.clone();\n }\n else {\n this._originalValue[targetIndex] = originalValue;\n }\n }\n _setValue(target, destination, currentValue, weight, targetIndex) {\n // Set value\n this._currentActiveTarget = destination;\n this._weight = weight;\n if (this._enableBlending && this._blendingFactor <= 1.0) {\n if (!this._originalBlendValue) {\n const originalValue = destination[this._targetPath];\n if (originalValue.clone) {\n this._originalBlendValue = originalValue.clone();\n }\n else {\n this._originalBlendValue = originalValue;\n }\n }\n if (this._originalBlendValue.m) {\n // Matrix\n if (Animation.AllowMatrixDecomposeForInterpolation) {\n if (this._currentValue) {\n Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);\n }\n else {\n this._currentValue = Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);\n }\n }\n else {\n if (this._currentValue) {\n Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);\n }\n else {\n this._currentValue = Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);\n }\n }\n }\n else {\n this._currentValue = Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);\n }\n const blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;\n this._blendingFactor += blendingSpeed;\n }\n else {\n if (!this._currentValue) {\n if (currentValue === null || currentValue === void 0 ? void 0 : currentValue.clone) {\n this._currentValue = currentValue.clone();\n }\n else {\n this._currentValue = currentValue;\n }\n }\n else if (this._currentValue.copyFrom) {\n this._currentValue.copyFrom(currentValue);\n }\n else {\n this._currentValue = currentValue;\n }\n }\n if (weight !== -1.0) {\n this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);\n }\n else {\n destination[this._targetPath] = this._currentValue;\n }\n if (target.markAsDirty) {\n target.markAsDirty(this._animation.targetProperty);\n }\n }\n /**\n * Gets the loop pmode of the runtime animation\n * @returns Loop Mode\n */\n _getCorrectLoopMode() {\n if (this._target && this._target.animationPropertiesOverride) {\n return this._target.animationPropertiesOverride.loopMode;\n }\n return this._animation.loopMode;\n }\n /**\n * Move the current animation to a given frame\n * @param frame defines the frame to move to\n */\n goToFrame(frame) {\n const keys = this._animation.getKeys();\n if (frame < keys[0].frame) {\n frame = keys[0].frame;\n }\n else if (frame > keys[keys.length - 1].frame) {\n frame = keys[keys.length - 1].frame;\n }\n // Need to reset animation events\n const events = this._events;\n if (events.length) {\n for (let index = 0; index < events.length; index++) {\n if (!events[index].onlyOnce) {\n // reset events in the future\n events[index].isDone = events[index].frame < frame;\n }\n }\n }\n this._currentFrame = frame;\n const currentValue = this._animation._interpolate(frame, this._animationState);\n this.setValue(currentValue, -1);\n }\n /**\n * @internal Internal use only\n */\n _prepareForSpeedRatioChange(newSpeedRatio) {\n const newRatio = (this._previousDelay * (this._animation.framePerSecond * newSpeedRatio)) / 1000.0;\n this._ratioOffset = this._previousRatio - newRatio;\n }\n /**\n * Execute the current animation\n * @param delay defines the delay to add to the current frame\n * @param from defines the lower bound of the animation range\n * @param to defines the upper bound of the animation range\n * @param loop defines if the current animation must loop\n * @param speedRatio defines the current speed ratio\n * @param weight defines the weight of the animation (default is -1 so no weight)\n * @returns a boolean indicating if the animation is running\n */\n animate(delay, from, to, loop, speedRatio, weight = -1.0) {\n const animation = this._animation;\n const targetPropertyPath = animation.targetPropertyPath;\n if (!targetPropertyPath || targetPropertyPath.length < 1) {\n this._stopped = true;\n return false;\n }\n let returnValue = true;\n // Check limits\n if (from < this._minFrame || from > this._maxFrame) {\n from = this._minFrame;\n }\n if (to < this._minFrame || to > this._maxFrame) {\n to = this._maxFrame;\n }\n const range = to - from;\n let offsetValue;\n // Compute ratio which represents the frame delta between from and to\n let ratio = (delay * (animation.framePerSecond * speedRatio)) / 1000.0 + this._ratioOffset;\n let highLimitValue = 0;\n // Apply the yoyo function if required\n if (loop && this._animationState.loopMode === Animation.ANIMATIONLOOPMODE_YOYO) {\n const position = (ratio - from) / range;\n // Apply the yoyo curve\n const yoyoPosition = Math.abs(Math.sin(position * Math.PI));\n // Map the yoyo position back to the range\n ratio = yoyoPosition * range + from;\n }\n this._previousDelay = delay;\n this._previousRatio = ratio;\n if (!loop && to >= from && ratio >= range) {\n // If we are out of range and not looping get back to caller\n returnValue = false;\n highLimitValue = animation._getKeyValue(this._maxValue);\n }\n else if (!loop && from >= to && ratio <= range) {\n returnValue = false;\n highLimitValue = animation._getKeyValue(this._minValue);\n }\n else if (this._animationState.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {\n const keyOffset = to.toString() + from.toString();\n if (!this._offsetsCache[keyOffset]) {\n this._animationState.repeatCount = 0;\n this._animationState.loopMode = Animation.ANIMATIONLOOPMODE_CYCLE;\n const fromValue = animation._interpolate(from, this._animationState);\n const toValue = animation._interpolate(to, this._animationState);\n this._animationState.loopMode = this._getCorrectLoopMode();\n switch (animation.dataType) {\n // Float\n case Animation.ANIMATIONTYPE_FLOAT:\n this._offsetsCache[keyOffset] = toValue - fromValue;\n break;\n // Quaternion\n case Animation.ANIMATIONTYPE_QUATERNION:\n this._offsetsCache[keyOffset] = toValue.subtract(fromValue);\n break;\n // Vector3\n case Animation.ANIMATIONTYPE_VECTOR3:\n this._offsetsCache[keyOffset] = toValue.subtract(fromValue);\n break;\n // Vector2\n case Animation.ANIMATIONTYPE_VECTOR2:\n this._offsetsCache[keyOffset] = toValue.subtract(fromValue);\n break;\n // Size\n case Animation.ANIMATIONTYPE_SIZE:\n this._offsetsCache[keyOffset] = toValue.subtract(fromValue);\n break;\n // Color3\n case Animation.ANIMATIONTYPE_COLOR3:\n this._offsetsCache[keyOffset] = toValue.subtract(fromValue);\n break;\n default:\n break;\n }\n this._highLimitsCache[keyOffset] = toValue;\n }\n highLimitValue = this._highLimitsCache[keyOffset];\n offsetValue = this._offsetsCache[keyOffset];\n }\n if (offsetValue === undefined) {\n switch (animation.dataType) {\n // Float\n case Animation.ANIMATIONTYPE_FLOAT:\n offsetValue = 0;\n break;\n // Quaternion\n case Animation.ANIMATIONTYPE_QUATERNION:\n offsetValue = _staticOffsetValueQuaternion;\n break;\n // Vector3\n case Animation.ANIMATIONTYPE_VECTOR3:\n offsetValue = _staticOffsetValueVector3;\n break;\n // Vector2\n case Animation.ANIMATIONTYPE_VECTOR2:\n offsetValue = _staticOffsetValueVector2;\n break;\n // Size\n case Animation.ANIMATIONTYPE_SIZE:\n offsetValue = _staticOffsetValueSize;\n break;\n // Color3\n case Animation.ANIMATIONTYPE_COLOR3:\n offsetValue = _staticOffsetValueColor3;\n }\n }\n // Compute value\n let currentFrame;\n if (this._host && this._host.syncRoot) {\n const syncRoot = this._host.syncRoot;\n const hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);\n currentFrame = from + (to - from) * hostNormalizedFrame;\n }\n else {\n if ((ratio > 0 && from > to) || (ratio < 0 && from < to)) {\n currentFrame = returnValue && range !== 0 ? to + (ratio % range) : from;\n }\n else {\n currentFrame = returnValue && range !== 0 ? from + (ratio % range) : to;\n }\n }\n const events = this._events;\n // Reset event/state if looping\n if ((speedRatio > 0 && this.currentFrame > currentFrame) || (speedRatio < 0 && this.currentFrame < currentFrame)) {\n this._onLoop();\n // Need to reset animation events\n for (let index = 0; index < events.length; index++) {\n if (!events[index].onlyOnce) {\n // reset event, the animation is looping\n events[index].isDone = false;\n }\n }\n this._animationState.key = speedRatio > 0 ? 0 : animation.getKeys().length - 1;\n }\n this._currentFrame = currentFrame;\n this._animationState.repeatCount = range === 0 ? 0 : (ratio / range) >> 0;\n this._animationState.highLimitValue = highLimitValue;\n this._animationState.offsetValue = offsetValue;\n const currentValue = animation._interpolate(currentFrame, this._animationState);\n // Set value\n this.setValue(currentValue, weight);\n // Check events\n if (events.length) {\n for (let index = 0; index < events.length; index++) {\n // Make sure current frame has passed event frame and that event frame is within the current range\n // Also, handle both forward and reverse animations\n if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||\n (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {\n const event = events[index];\n if (!event.isDone) {\n // If event should be done only once, remove it.\n if (event.onlyOnce) {\n events.splice(index, 1);\n index--;\n }\n event.isDone = true;\n event.action(currentFrame);\n } // Don't do anything if the event has already be done.\n }\n }\n }\n if (!returnValue) {\n this._stopped = true;\n }\n return returnValue;\n }\n}\n//# sourceMappingURL=runtimeAnimation.js.map","import { Vector3, Quaternion, Matrix, TmpVectors } from \"../Maths/math.vector.js\";\nimport { ArrayTools } from \"../Misc/arrayTools.js\";\nimport { Node } from \"../node.js\";\nimport { Space } from \"../Maths/math.axis.js\";\n/**\n * Class used to store bone information\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons\n */\nexport class Bone extends Node {\n /** @internal */\n get _matrix() {\n this._compose();\n return this._localMatrix;\n }\n /** @internal */\n set _matrix(value) {\n this._needToCompose = false; // in case there was a pending compose\n // skip if the matrices are the same\n if (value.updateFlag === this._localMatrix.updateFlag) {\n return;\n }\n this._localMatrix.copyFrom(value);\n this._markAsDirtyAndDecompose();\n }\n /**\n * Create a new bone\n * @param name defines the bone name\n * @param skeleton defines the parent skeleton\n * @param parentBone defines the parent (can be null if the bone is the root)\n * @param localMatrix defines the local matrix (default: identity)\n * @param restMatrix defines the rest matrix (default: localMatrix)\n * @param bindMatrix defines the bind matrix (default: localMatrix)\n * @param index defines index of the bone in the hierarchy (default: null)\n */\n constructor(\n /**\n * defines the bone name\n */\n name, skeleton, parentBone = null, localMatrix = null, restMatrix = null, bindMatrix = null, index = null) {\n var _a;\n super(name, skeleton.getScene());\n this.name = name;\n /**\n * Gets the list of child bones\n */\n this.children = new Array();\n /** Gets the animations associated with this bone */\n this.animations = new Array();\n /**\n * @internal Internal only\n * Set this value to map this bone to a different index in the transform matrices\n * Set this value to -1 to exclude the bone from the transform matrices\n */\n this._index = null;\n this._scalingDeterminant = 1;\n this._needToDecompose = true;\n this._needToCompose = false;\n /** @internal */\n this._linkedTransformNode = null;\n /** @internal */\n this._waitingTransformNodeId = null;\n this._skeleton = skeleton;\n this._localMatrix = (_a = localMatrix === null || localMatrix === void 0 ? void 0 : localMatrix.clone()) !== null && _a !== void 0 ? _a : Matrix.Identity();\n this._restMatrix = restMatrix !== null && restMatrix !== void 0 ? restMatrix : this._localMatrix.clone();\n this._bindMatrix = bindMatrix !== null && bindMatrix !== void 0 ? bindMatrix : this._localMatrix.clone();\n this._index = index;\n this._absoluteMatrix = new Matrix();\n this._absoluteBindMatrix = new Matrix();\n this._absoluteInverseBindMatrix = new Matrix();\n this._finalMatrix = new Matrix();\n skeleton.bones.push(this);\n this.setParent(parentBone, false);\n this._updateAbsoluteBindMatrices();\n }\n /**\n * Gets the current object class name.\n * @returns the class name\n */\n getClassName() {\n return \"Bone\";\n }\n // Members\n /**\n * Gets the parent skeleton\n * @returns a skeleton\n */\n getSkeleton() {\n return this._skeleton;\n }\n get parent() {\n return this._parentNode;\n }\n /**\n * Gets parent bone\n * @returns a bone or null if the bone is the root of the bone hierarchy\n */\n getParent() {\n return this.parent;\n }\n /**\n * Returns an array containing the children of the bone\n * @returns an array containing the children of the bone (can be empty if the bone has no children)\n */\n getChildren() {\n return this.children;\n }\n /**\n * Gets the node index in matrix array generated for rendering\n * @returns the node index\n */\n getIndex() {\n return this._index === null ? this.getSkeleton().bones.indexOf(this) : this._index;\n }\n set parent(newParent) {\n this.setParent(newParent);\n }\n /**\n * Sets the parent bone\n * @param parent defines the parent (can be null if the bone is the root)\n * @param updateAbsoluteBindMatrices defines if the absolute bind and absolute inverse bind matrices must be updated\n */\n setParent(parent, updateAbsoluteBindMatrices = true) {\n if (this.parent === parent) {\n return;\n }\n if (this.parent) {\n const index = this.parent.children.indexOf(this);\n if (index !== -1) {\n this.parent.children.splice(index, 1);\n }\n }\n this._parentNode = parent;\n if (this.parent) {\n this.parent.children.push(this);\n }\n if (updateAbsoluteBindMatrices) {\n this._updateAbsoluteBindMatrices();\n }\n this.markAsDirty();\n }\n /**\n * Gets the local matrix\n * @returns the local matrix\n */\n getLocalMatrix() {\n this._compose();\n return this._localMatrix;\n }\n /**\n * Gets the bind matrix\n * @returns the bind matrix\n */\n getBindMatrix() {\n return this._bindMatrix;\n }\n /**\n * Gets the bind matrix.\n * @returns the bind matrix\n * @deprecated Please use getBindMatrix instead\n */\n getBaseMatrix() {\n return this.getBindMatrix();\n }\n /**\n * Gets the rest matrix\n * @returns the rest matrix\n */\n getRestMatrix() {\n return this._restMatrix;\n }\n /**\n * Gets the rest matrix\n * @returns the rest matrix\n * @deprecated Please use getRestMatrix instead\n */\n getRestPose() {\n return this.getRestMatrix();\n }\n /**\n * Sets the rest matrix\n * @param matrix the local-space rest matrix to set for this bone\n */\n setRestMatrix(matrix) {\n this._restMatrix.copyFrom(matrix);\n }\n /**\n * Sets the rest matrix\n * @param matrix the local-space rest to set for this bone\n * @deprecated Please use setRestMatrix instead\n */\n setRestPose(matrix) {\n this.setRestMatrix(matrix);\n }\n /**\n * Gets the bind matrix\n * @returns the bind matrix\n * @deprecated Please use getBindMatrix instead\n */\n getBindPose() {\n return this.getBindMatrix();\n }\n /**\n * Sets the bind matrix\n * This will trigger a recomputation of the absolute bind and absolute inverse bind matrices for this bone and its children\n * Note that the local matrix will also be set with the matrix passed in parameter!\n * @param matrix the local-space bind matrix to set for this bone\n */\n setBindMatrix(matrix) {\n this.updateMatrix(matrix);\n }\n /**\n * Sets the bind matrix\n * @param matrix the local-space bind to set for this bone\n * @deprecated Please use setBindMatrix instead\n */\n setBindPose(matrix) {\n this.setBindMatrix(matrix);\n }\n /**\n * Gets the matrix used to store the final world transformation of the bone (ie. the matrix sent to shaders)\n */\n getFinalMatrix() {\n return this._finalMatrix;\n }\n /**\n * Gets the matrix used to store the final world transformation of the bone (ie. the matrix sent to shaders)\n * @deprecated Please use getFinalMatrix instead\n */\n getWorldMatrix() {\n return this.getFinalMatrix();\n }\n /**\n * Sets the local matrix to the rest matrix\n */\n returnToRest() {\n var _a;\n if (this._linkedTransformNode) {\n const localScaling = TmpVectors.Vector3[0];\n const localRotation = TmpVectors.Quaternion[0];\n const localPosition = TmpVectors.Vector3[1];\n this.getRestMatrix().decompose(localScaling, localRotation, localPosition);\n this._linkedTransformNode.position.copyFrom(localPosition);\n this._linkedTransformNode.rotationQuaternion = (_a = this._linkedTransformNode.rotationQuaternion) !== null && _a !== void 0 ? _a : Quaternion.Identity();\n this._linkedTransformNode.rotationQuaternion.copyFrom(localRotation);\n this._linkedTransformNode.scaling.copyFrom(localScaling);\n }\n else {\n this._matrix = this._restMatrix;\n }\n }\n /**\n * Gets the inverse of the bind matrix, in world space (relative to the skeleton root)\n * @returns the inverse bind matrix, in world space\n */\n getAbsoluteInverseBindMatrix() {\n return this._absoluteInverseBindMatrix;\n }\n /**\n * Gets the inverse of the bind matrix, in world space (relative to the skeleton root)\n * @returns the inverse bind matrix, in world space\n * @deprecated Please use getAbsoluteInverseBindMatrix instead\n */\n getInvertedAbsoluteTransform() {\n return this.getAbsoluteInverseBindMatrix();\n }\n /**\n * Gets the bone matrix, in world space (relative to the skeleton root)\n * @returns the bone matrix, in world space\n */\n getAbsoluteMatrix() {\n return this._absoluteMatrix;\n }\n /**\n * Gets the bone matrix, in world space (relative to the skeleton root)\n * @returns the bone matrix, in world space\n * @deprecated Please use getAbsoluteMatrix instead\n */\n getAbsoluteTransform() {\n return this._absoluteMatrix;\n }\n /**\n * Links with the given transform node.\n * The local matrix of this bone is overwritten by the transform of the node every frame.\n * @param transformNode defines the transform node to link to\n */\n linkTransformNode(transformNode) {\n if (this._linkedTransformNode) {\n this._skeleton._numBonesWithLinkedTransformNode--;\n }\n this._linkedTransformNode = transformNode;\n if (this._linkedTransformNode) {\n this._skeleton._numBonesWithLinkedTransformNode++;\n }\n }\n // Properties (matches TransformNode properties)\n /**\n * Gets the node used to drive the bone's transformation\n * @returns a transform node or null\n */\n getTransformNode() {\n return this._linkedTransformNode;\n }\n /** Gets or sets current position (in local space) */\n get position() {\n this._decompose();\n return this._localPosition;\n }\n set position(newPosition) {\n this._decompose();\n this._localPosition.copyFrom(newPosition);\n this._markAsDirtyAndCompose();\n }\n /** Gets or sets current rotation (in local space) */\n get rotation() {\n return this.getRotation();\n }\n set rotation(newRotation) {\n this.setRotation(newRotation);\n }\n /** Gets or sets current rotation quaternion (in local space) */\n get rotationQuaternion() {\n this._decompose();\n return this._localRotation;\n }\n set rotationQuaternion(newRotation) {\n this.setRotationQuaternion(newRotation);\n }\n /** Gets or sets current scaling (in local space) */\n get scaling() {\n return this.getScale();\n }\n set scaling(newScaling) {\n this.setScale(newScaling);\n }\n /**\n * Gets the animation properties override\n */\n get animationPropertiesOverride() {\n return this._skeleton.animationPropertiesOverride;\n }\n // Methods\n _decompose() {\n if (!this._needToDecompose) {\n return;\n }\n this._needToDecompose = false;\n if (!this._localScaling) {\n this._localScaling = Vector3.Zero();\n this._localRotation = Quaternion.Zero();\n this._localPosition = Vector3.Zero();\n }\n this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);\n }\n _compose() {\n if (!this._needToCompose) {\n return;\n }\n if (!this._localScaling) {\n this._needToCompose = false;\n return;\n }\n this._needToCompose = false;\n Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);\n }\n /**\n * Update the bind (and optionally the local) matrix\n * @param bindMatrix defines the new matrix to set to the bind/local matrix, in local space\n * @param updateAbsoluteBindMatrices defines if the absolute bind and absolute inverse bind matrices must be recomputed (default: true)\n * @param updateLocalMatrix defines if the local matrix should also be updated with the matrix passed in parameter (default: true)\n */\n updateMatrix(bindMatrix, updateAbsoluteBindMatrices = true, updateLocalMatrix = true) {\n this._bindMatrix.copyFrom(bindMatrix);\n if (updateAbsoluteBindMatrices) {\n this._updateAbsoluteBindMatrices();\n }\n if (updateLocalMatrix) {\n this._matrix = bindMatrix;\n }\n else {\n this.markAsDirty();\n }\n }\n /**\n * @internal\n */\n _updateAbsoluteBindMatrices(bindMatrix, updateChildren = true) {\n if (!bindMatrix) {\n bindMatrix = this._bindMatrix;\n }\n if (this.parent) {\n bindMatrix.multiplyToRef(this.parent._absoluteBindMatrix, this._absoluteBindMatrix);\n }\n else {\n this._absoluteBindMatrix.copyFrom(bindMatrix);\n }\n this._absoluteBindMatrix.invertToRef(this._absoluteInverseBindMatrix);\n if (updateChildren) {\n for (let index = 0; index < this.children.length; index++) {\n this.children[index]._updateAbsoluteBindMatrices();\n }\n }\n this._scalingDeterminant = this._absoluteBindMatrix.determinant() < 0 ? -1 : 1;\n }\n /**\n * Flag the bone as dirty (Forcing it to update everything)\n * @returns this bone\n */\n markAsDirty() {\n this._currentRenderId++;\n this._childUpdateId++;\n this._skeleton._markAsDirty();\n return this;\n }\n /** @internal */\n _markAsDirtyAndCompose() {\n this.markAsDirty();\n this._needToCompose = true;\n }\n _markAsDirtyAndDecompose() {\n this.markAsDirty();\n this._needToDecompose = true;\n }\n _updatePosition(vec, space = Space.LOCAL, tNode, translationMode = true) {\n const lm = this.getLocalMatrix();\n if (space == Space.LOCAL) {\n if (translationMode) {\n lm.addAtIndex(12, vec.x);\n lm.addAtIndex(13, vec.y);\n lm.addAtIndex(14, vec.z);\n }\n else {\n lm.setTranslationFromFloats(vec.x, vec.y, vec.z);\n }\n }\n else {\n let wm = null;\n //tNode.getWorldMatrix() needs to be called before skeleton.computeAbsoluteMatrices()\n if (tNode) {\n wm = tNode.getWorldMatrix();\n }\n this._skeleton.computeAbsoluteMatrices();\n const tmat = Bone._TmpMats[0];\n const tvec = Bone._TmpVecs[0];\n if (this.parent) {\n if (tNode && wm) {\n tmat.copyFrom(this.parent.getAbsoluteMatrix());\n tmat.multiplyToRef(wm, tmat);\n }\n else {\n tmat.copyFrom(this.parent.getAbsoluteMatrix());\n }\n }\n else {\n Matrix.IdentityToRef(tmat);\n }\n if (translationMode) {\n tmat.setTranslationFromFloats(0, 0, 0);\n }\n tmat.invert();\n Vector3.TransformCoordinatesToRef(vec, tmat, tvec);\n if (translationMode) {\n lm.addAtIndex(12, tvec.x);\n lm.addAtIndex(13, tvec.y);\n lm.addAtIndex(14, tvec.z);\n }\n else {\n lm.setTranslationFromFloats(tvec.x, tvec.y, tvec.z);\n }\n }\n this._markAsDirtyAndDecompose();\n }\n /**\n * Translate the bone in local or world space\n * @param vec The amount to translate the bone\n * @param space The space that the translation is in (default: Space.LOCAL)\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n */\n translate(vec, space = Space.LOCAL, tNode) {\n this._updatePosition(vec, space, tNode, true);\n }\n /**\n * Set the position of the bone in local or world space\n * @param position The position to set the bone\n * @param space The space that the position is in (default: Space.LOCAL)\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n */\n setPosition(position, space = Space.LOCAL, tNode) {\n this._updatePosition(position, space, tNode, false);\n }\n /**\n * Set the absolute position of the bone (world space)\n * @param position The position to set the bone\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n */\n setAbsolutePosition(position, tNode) {\n this.setPosition(position, Space.WORLD, tNode);\n }\n /**\n * Scale the bone on the x, y and z axes (in local space)\n * @param x The amount to scale the bone on the x axis\n * @param y The amount to scale the bone on the y axis\n * @param z The amount to scale the bone on the z axis\n * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)\n */\n scale(x, y, z, scaleChildren = false) {\n const locMat = this.getLocalMatrix();\n // Apply new scaling on top of current local matrix\n const scaleMat = Bone._TmpMats[0];\n Matrix.ScalingToRef(x, y, z, scaleMat);\n scaleMat.multiplyToRef(locMat, locMat);\n // Invert scaling matrix and apply the inverse to all children\n scaleMat.invert();\n for (const child of this.children) {\n const cm = child.getLocalMatrix();\n cm.multiplyToRef(scaleMat, cm);\n cm.multiplyAtIndex(12, x);\n cm.multiplyAtIndex(13, y);\n cm.multiplyAtIndex(14, z);\n child._markAsDirtyAndDecompose();\n }\n this._markAsDirtyAndDecompose();\n if (scaleChildren) {\n for (const child of this.children) {\n child.scale(x, y, z, scaleChildren);\n }\n }\n }\n /**\n * Set the bone scaling in local space\n * @param scale defines the scaling vector\n */\n setScale(scale) {\n this._decompose();\n this._localScaling.copyFrom(scale);\n this._markAsDirtyAndCompose();\n }\n /**\n * Gets the current scaling in local space\n * @returns the current scaling vector\n */\n getScale() {\n this._decompose();\n return this._localScaling;\n }\n /**\n * Gets the current scaling in local space and stores it in a target vector\n * @param result defines the target vector\n */\n getScaleToRef(result) {\n this._decompose();\n result.copyFrom(this._localScaling);\n }\n /**\n * Set the yaw, pitch, and roll of the bone in local or world space\n * @param yaw The rotation of the bone on the y axis\n * @param pitch The rotation of the bone on the x axis\n * @param roll The rotation of the bone on the z axis\n * @param space The space that the axes of rotation are in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n */\n setYawPitchRoll(yaw, pitch, roll, space = Space.LOCAL, tNode) {\n if (space === Space.LOCAL) {\n const quat = Bone._TmpQuat;\n Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);\n this.setRotationQuaternion(quat, space, tNode);\n return;\n }\n const rotMatInv = Bone._TmpMats[0];\n if (!this._getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode)) {\n return;\n }\n const rotMat = Bone._TmpMats[1];\n Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);\n rotMatInv.multiplyToRef(rotMat, rotMat);\n this._rotateWithMatrix(rotMat, space, tNode);\n }\n /**\n * Add a rotation to the bone on an axis in local or world space\n * @param axis The axis to rotate the bone on\n * @param amount The amount to rotate the bone\n * @param space The space that the axis is in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n */\n rotate(axis, amount, space = Space.LOCAL, tNode) {\n const rmat = Bone._TmpMats[0];\n rmat.setTranslationFromFloats(0, 0, 0);\n Matrix.RotationAxisToRef(axis, amount, rmat);\n this._rotateWithMatrix(rmat, space, tNode);\n }\n /**\n * Set the rotation of the bone to a particular axis angle in local or world space\n * @param axis The axis to rotate the bone on\n * @param angle The angle that the bone should be rotated to\n * @param space The space that the axis is in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n */\n setAxisAngle(axis, angle, space = Space.LOCAL, tNode) {\n if (space === Space.LOCAL) {\n const quat = Bone._TmpQuat;\n Quaternion.RotationAxisToRef(axis, angle, quat);\n this.setRotationQuaternion(quat, space, tNode);\n return;\n }\n const rotMatInv = Bone._TmpMats[0];\n if (!this._getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode)) {\n return;\n }\n const rotMat = Bone._TmpMats[1];\n Matrix.RotationAxisToRef(axis, angle, rotMat);\n rotMatInv.multiplyToRef(rotMat, rotMat);\n this._rotateWithMatrix(rotMat, space, tNode);\n }\n /**\n * Set the euler rotation of the bone in local or world space\n * @param rotation The euler rotation that the bone should be set to\n * @param space The space that the rotation is in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n */\n setRotation(rotation, space = Space.LOCAL, tNode) {\n this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, tNode);\n }\n /**\n * Set the quaternion rotation of the bone in local or world space\n * @param quat The quaternion rotation that the bone should be set to\n * @param space The space that the rotation is in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n */\n setRotationQuaternion(quat, space = Space.LOCAL, tNode) {\n if (space === Space.LOCAL) {\n this._decompose();\n this._localRotation.copyFrom(quat);\n this._markAsDirtyAndCompose();\n return;\n }\n const rotMatInv = Bone._TmpMats[0];\n if (!this._getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode)) {\n return;\n }\n const rotMat = Bone._TmpMats[1];\n Matrix.FromQuaternionToRef(quat, rotMat);\n rotMatInv.multiplyToRef(rotMat, rotMat);\n this._rotateWithMatrix(rotMat, space, tNode);\n }\n /**\n * Set the rotation matrix of the bone in local or world space\n * @param rotMat The rotation matrix that the bone should be set to\n * @param space The space that the rotation is in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n */\n setRotationMatrix(rotMat, space = Space.LOCAL, tNode) {\n if (space === Space.LOCAL) {\n const quat = Bone._TmpQuat;\n Quaternion.FromRotationMatrixToRef(rotMat, quat);\n this.setRotationQuaternion(quat, space, tNode);\n return;\n }\n const rotMatInv = Bone._TmpMats[0];\n if (!this._getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode)) {\n return;\n }\n const rotMat2 = Bone._TmpMats[1];\n rotMat2.copyFrom(rotMat);\n rotMatInv.multiplyToRef(rotMat, rotMat2);\n this._rotateWithMatrix(rotMat2, space, tNode);\n }\n _rotateWithMatrix(rmat, space = Space.LOCAL, tNode) {\n const lmat = this.getLocalMatrix();\n const lx = lmat.m[12];\n const ly = lmat.m[13];\n const lz = lmat.m[14];\n const parent = this.getParent();\n const parentScale = Bone._TmpMats[3];\n const parentScaleInv = Bone._TmpMats[4];\n if (parent && space == Space.WORLD) {\n if (tNode) {\n parentScale.copyFrom(tNode.getWorldMatrix());\n parent.getAbsoluteMatrix().multiplyToRef(parentScale, parentScale);\n }\n else {\n parentScale.copyFrom(parent.getAbsoluteMatrix());\n }\n parentScaleInv.copyFrom(parentScale);\n parentScaleInv.invert();\n lmat.multiplyToRef(parentScale, lmat);\n lmat.multiplyToRef(rmat, lmat);\n lmat.multiplyToRef(parentScaleInv, lmat);\n }\n else {\n if (space == Space.WORLD && tNode) {\n parentScale.copyFrom(tNode.getWorldMatrix());\n parentScaleInv.copyFrom(parentScale);\n parentScaleInv.invert();\n lmat.multiplyToRef(parentScale, lmat);\n lmat.multiplyToRef(rmat, lmat);\n lmat.multiplyToRef(parentScaleInv, lmat);\n }\n else {\n lmat.multiplyToRef(rmat, lmat);\n }\n }\n lmat.setTranslationFromFloats(lx, ly, lz);\n this.computeAbsoluteMatrices();\n this._markAsDirtyAndDecompose();\n }\n _getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode) {\n const scaleMatrix = Bone._TmpMats[2];\n rotMatInv.copyFrom(this.getAbsoluteMatrix());\n if (tNode) {\n rotMatInv.multiplyToRef(tNode.getWorldMatrix(), rotMatInv);\n Matrix.ScalingToRef(tNode.scaling.x, tNode.scaling.y, tNode.scaling.z, scaleMatrix);\n }\n else {\n Matrix.IdentityToRef(scaleMatrix);\n }\n rotMatInv.invert();\n if (isNaN(rotMatInv.m[0])) {\n // Matrix failed to invert.\n // This can happen if scale is zero for example.\n return false;\n }\n scaleMatrix.multiplyAtIndex(0, this._scalingDeterminant);\n rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);\n return true;\n }\n /**\n * Get the position of the bone in local or world space\n * @param space The space that the returned position is in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @returns The position of the bone\n */\n getPosition(space = Space.LOCAL, tNode = null) {\n const pos = Vector3.Zero();\n this.getPositionToRef(space, tNode, pos);\n return pos;\n }\n /**\n * Copy the position of the bone to a vector3 in local or world space\n * @param space The space that the returned position is in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @param result The vector3 to copy the position to\n */\n getPositionToRef(space = Space.LOCAL, tNode, result) {\n if (space == Space.LOCAL) {\n const lm = this.getLocalMatrix();\n result.x = lm.m[12];\n result.y = lm.m[13];\n result.z = lm.m[14];\n }\n else {\n let wm = null;\n //tNode.getWorldMatrix() needs to be called before skeleton.computeAbsoluteMatrices()\n if (tNode) {\n wm = tNode.getWorldMatrix();\n }\n this._skeleton.computeAbsoluteMatrices();\n let tmat = Bone._TmpMats[0];\n if (tNode && wm) {\n tmat.copyFrom(this.getAbsoluteMatrix());\n tmat.multiplyToRef(wm, tmat);\n }\n else {\n tmat = this.getAbsoluteMatrix();\n }\n result.x = tmat.m[12];\n result.y = tmat.m[13];\n result.z = tmat.m[14];\n }\n }\n /**\n * Get the absolute position of the bone (world space)\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @returns The absolute position of the bone\n */\n getAbsolutePosition(tNode = null) {\n const pos = Vector3.Zero();\n this.getPositionToRef(Space.WORLD, tNode, pos);\n return pos;\n }\n /**\n * Copy the absolute position of the bone (world space) to the result param\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @param result The vector3 to copy the absolute position to\n */\n getAbsolutePositionToRef(tNode, result) {\n this.getPositionToRef(Space.WORLD, tNode, result);\n }\n /**\n * Compute the absolute matrices of this bone and its children\n */\n computeAbsoluteMatrices() {\n this._compose();\n if (this.parent) {\n this._localMatrix.multiplyToRef(this.parent._absoluteMatrix, this._absoluteMatrix);\n }\n else {\n this._absoluteMatrix.copyFrom(this._localMatrix);\n const poseMatrix = this._skeleton.getPoseMatrix();\n if (poseMatrix) {\n this._absoluteMatrix.multiplyToRef(poseMatrix, this._absoluteMatrix);\n }\n }\n const children = this.children;\n const len = children.length;\n for (let i = 0; i < len; i++) {\n children[i].computeAbsoluteMatrices();\n }\n }\n /**\n * Compute the absolute matrices of this bone and its children\n * @deprecated Please use computeAbsoluteMatrices instead\n */\n computeAbsoluteTransforms() {\n this.computeAbsoluteMatrices();\n }\n /**\n * Get the world direction from an axis that is in the local space of the bone\n * @param localAxis The local direction that is used to compute the world direction\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @returns The world direction\n */\n getDirection(localAxis, tNode = null) {\n const result = Vector3.Zero();\n this.getDirectionToRef(localAxis, tNode, result);\n return result;\n }\n /**\n * Copy the world direction to a vector3 from an axis that is in the local space of the bone\n * @param localAxis The local direction that is used to compute the world direction\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @param result The vector3 that the world direction will be copied to\n */\n getDirectionToRef(localAxis, tNode = null, result) {\n let wm = null;\n //tNode.getWorldMatrix() needs to be called before skeleton.computeAbsoluteMatrices()\n if (tNode) {\n wm = tNode.getWorldMatrix();\n }\n this._skeleton.computeAbsoluteMatrices();\n const mat = Bone._TmpMats[0];\n mat.copyFrom(this.getAbsoluteMatrix());\n if (tNode && wm) {\n mat.multiplyToRef(wm, mat);\n }\n Vector3.TransformNormalToRef(localAxis, mat, result);\n result.normalize();\n }\n /**\n * Get the euler rotation of the bone in local or world space\n * @param space The space that the rotation should be in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @returns The euler rotation\n */\n getRotation(space = Space.LOCAL, tNode = null) {\n const result = Vector3.Zero();\n this.getRotationToRef(space, tNode, result);\n return result;\n }\n /**\n * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space\n * @param space The space that the rotation should be in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @param result The vector3 that the rotation should be copied to\n */\n getRotationToRef(space = Space.LOCAL, tNode = null, result) {\n const quat = Bone._TmpQuat;\n this.getRotationQuaternionToRef(space, tNode, quat);\n quat.toEulerAnglesToRef(result);\n }\n /**\n * Get the quaternion rotation of the bone in either local or world space\n * @param space The space that the rotation should be in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @returns The quaternion rotation\n */\n getRotationQuaternion(space = Space.LOCAL, tNode = null) {\n const result = Quaternion.Identity();\n this.getRotationQuaternionToRef(space, tNode, result);\n return result;\n }\n /**\n * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space\n * @param space The space that the rotation should be in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @param result The quaternion that the rotation should be copied to\n */\n getRotationQuaternionToRef(space = Space.LOCAL, tNode = null, result) {\n if (space == Space.LOCAL) {\n this._decompose();\n result.copyFrom(this._localRotation);\n }\n else {\n const mat = Bone._TmpMats[0];\n const amat = this.getAbsoluteMatrix();\n if (tNode) {\n amat.multiplyToRef(tNode.getWorldMatrix(), mat);\n }\n else {\n mat.copyFrom(amat);\n }\n mat.multiplyAtIndex(0, this._scalingDeterminant);\n mat.multiplyAtIndex(1, this._scalingDeterminant);\n mat.multiplyAtIndex(2, this._scalingDeterminant);\n mat.decompose(undefined, result, undefined);\n }\n }\n /**\n * Get the rotation matrix of the bone in local or world space\n * @param space The space that the rotation should be in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @returns The rotation matrix\n */\n getRotationMatrix(space = Space.LOCAL, tNode) {\n const result = Matrix.Identity();\n this.getRotationMatrixToRef(space, tNode, result);\n return result;\n }\n /**\n * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space\n * @param space The space that the rotation should be in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @param result The quaternion that the rotation should be copied to\n */\n getRotationMatrixToRef(space = Space.LOCAL, tNode, result) {\n if (space == Space.LOCAL) {\n this.getLocalMatrix().getRotationMatrixToRef(result);\n }\n else {\n const mat = Bone._TmpMats[0];\n const amat = this.getAbsoluteMatrix();\n if (tNode) {\n amat.multiplyToRef(tNode.getWorldMatrix(), mat);\n }\n else {\n mat.copyFrom(amat);\n }\n mat.multiplyAtIndex(0, this._scalingDeterminant);\n mat.multiplyAtIndex(1, this._scalingDeterminant);\n mat.multiplyAtIndex(2, this._scalingDeterminant);\n mat.getRotationMatrixToRef(result);\n }\n }\n /**\n * Get the world position of a point that is in the local space of the bone\n * @param position The local position\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @returns The world position\n */\n getAbsolutePositionFromLocal(position, tNode = null) {\n const result = Vector3.Zero();\n this.getAbsolutePositionFromLocalToRef(position, tNode, result);\n return result;\n }\n /**\n * Get the world position of a point that is in the local space of the bone and copy it to the result param\n * @param position The local position\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @param result The vector3 that the world position should be copied to\n */\n getAbsolutePositionFromLocalToRef(position, tNode = null, result) {\n let wm = null;\n //tNode.getWorldMatrix() needs to be called before skeleton.computeAbsoluteMatrices()\n if (tNode) {\n wm = tNode.getWorldMatrix();\n }\n this._skeleton.computeAbsoluteMatrices();\n const tmat = Bone._TmpMats[0];\n tmat.copyFrom(this.getAbsoluteMatrix());\n if (tNode && wm) {\n tmat.multiplyToRef(wm, tmat);\n }\n Vector3.TransformCoordinatesToRef(position, tmat, result);\n }\n /**\n * Get the local position of a point that is in world space\n * @param position The world position\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @returns The local position\n */\n getLocalPositionFromAbsolute(position, tNode = null) {\n const result = Vector3.Zero();\n this.getLocalPositionFromAbsoluteToRef(position, tNode, result);\n return result;\n }\n /**\n * Get the local position of a point that is in world space and copy it to the result param\n * @param position The world position\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @param result The vector3 that the local position should be copied to\n */\n getLocalPositionFromAbsoluteToRef(position, tNode = null, result) {\n let wm = null;\n //tNode.getWorldMatrix() needs to be called before skeleton.computeAbsoluteMatrices()\n if (tNode) {\n wm = tNode.getWorldMatrix();\n }\n this._skeleton.computeAbsoluteMatrices();\n const tmat = Bone._TmpMats[0];\n tmat.copyFrom(this.getAbsoluteMatrix());\n if (tNode && wm) {\n tmat.multiplyToRef(wm, tmat);\n }\n tmat.invert();\n Vector3.TransformCoordinatesToRef(position, tmat, result);\n }\n /**\n * Set the current local matrix as the restMatrix for this bone.\n */\n setCurrentPoseAsRest() {\n this.setRestMatrix(this.getLocalMatrix());\n }\n}\nBone._TmpVecs = ArrayTools.BuildArray(2, Vector3.Zero);\nBone._TmpQuat = Quaternion.Identity();\nBone._TmpMats = ArrayTools.BuildArray(5, Matrix.Identity);\n//# sourceMappingURL=bone.js.map","import { Animation } from \"./animation.js\";\nimport { RuntimeAnimation } from \"./runtimeAnimation.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Scene } from \"../scene.js\";\nimport { Matrix, Quaternion, Vector3, TmpVectors } from \"../Maths/math.vector.js\";\nimport { PrecisionDate } from \"../Misc/precisionDate.js\";\nimport { Bone } from \"../Bones/bone.js\";\n/**\n * Class used to store an actual running animation\n */\nexport class Animatable {\n /**\n * Gets the root Animatable used to synchronize and normalize animations\n */\n get syncRoot() {\n return this._syncRoot;\n }\n /**\n * Gets the current frame of the first RuntimeAnimation\n * Used to synchronize Animatables\n */\n get masterFrame() {\n if (this._runtimeAnimations.length === 0) {\n return 0;\n }\n return this._runtimeAnimations[0].currentFrame;\n }\n /**\n * Gets or sets the animatable weight (-1.0 by default meaning not weighted)\n */\n get weight() {\n return this._weight;\n }\n set weight(value) {\n if (value === -1) {\n // -1 is ok and means no weight\n this._weight = -1;\n return;\n }\n // Else weight must be in [0, 1] range\n this._weight = Math.min(Math.max(value, 0), 1.0);\n }\n /**\n * Gets or sets the speed ratio to apply to the animatable (1.0 by default)\n */\n get speedRatio() {\n return this._speedRatio;\n }\n set speedRatio(value) {\n for (let index = 0; index < this._runtimeAnimations.length; index++) {\n const animation = this._runtimeAnimations[index];\n animation._prepareForSpeedRatioChange(value);\n }\n this._speedRatio = value;\n // Resync _manualJumpDelay in case goToFrame was called before speedRatio was set.\n if (this._goToFrame !== null) {\n this.goToFrame(this._goToFrame);\n }\n }\n /**\n * Creates a new Animatable\n * @param scene defines the hosting scene\n * @param target defines the target object\n * @param fromFrame defines the starting frame number (default is 0)\n * @param toFrame defines the ending frame number (default is 100)\n * @param loopAnimation defines if the animation must loop (default is false)\n * @param speedRatio defines the factor to apply to animation speed (default is 1)\n * @param onAnimationEnd defines a callback to call when animation ends if it is not looping\n * @param animations defines a group of animation to add to the new Animatable\n * @param onAnimationLoop defines a callback to call when animation loops\n * @param isAdditive defines whether the animation should be evaluated additively\n */\n constructor(scene, \n /** defines the target object */\n target, \n /** defines the starting frame number (default is 0) */\n fromFrame = 0, \n /** defines the ending frame number (default is 100) */\n toFrame = 100, \n /** defines if the animation must loop (default is false) */\n loopAnimation = false, speedRatio = 1.0, \n /** defines a callback to call when animation ends if it is not looping */\n onAnimationEnd, animations, \n /** defines a callback to call when animation loops */\n onAnimationLoop, \n /** defines whether the animation should be evaluated additively */\n isAdditive = false) {\n this.target = target;\n this.fromFrame = fromFrame;\n this.toFrame = toFrame;\n this.loopAnimation = loopAnimation;\n this.onAnimationEnd = onAnimationEnd;\n this.onAnimationLoop = onAnimationLoop;\n this.isAdditive = isAdditive;\n this._localDelayOffset = null;\n this._pausedDelay = null;\n this._manualJumpDelay = null;\n /** @hidden */\n this._runtimeAnimations = new Array();\n this._paused = false;\n this._speedRatio = 1;\n this._weight = -1.0;\n this._syncRoot = null;\n this._frameToSyncFromJump = null;\n this._goToFrame = null;\n /**\n * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.\n * This will only apply for non looping animation (default is true)\n */\n this.disposeOnEnd = true;\n /**\n * Gets a boolean indicating if the animation has started\n */\n this.animationStarted = false;\n /**\n * Observer raised when the animation ends\n */\n this.onAnimationEndObservable = new Observable();\n /**\n * Observer raised when the animation loops\n */\n this.onAnimationLoopObservable = new Observable();\n this._scene = scene;\n if (animations) {\n this.appendAnimations(target, animations);\n }\n this._speedRatio = speedRatio;\n scene._activeAnimatables.push(this);\n }\n // Methods\n /**\n * Synchronize and normalize current Animatable with a source Animatable\n * This is useful when using animation weights and when animations are not of the same length\n * @param root defines the root Animatable to synchronize with (null to stop synchronizing)\n * @returns the current Animatable\n */\n syncWith(root) {\n this._syncRoot = root;\n if (root) {\n // Make sure this animatable will animate after the root\n const index = this._scene._activeAnimatables.indexOf(this);\n if (index > -1) {\n this._scene._activeAnimatables.splice(index, 1);\n this._scene._activeAnimatables.push(this);\n }\n }\n return this;\n }\n /**\n * Gets the list of runtime animations\n * @returns an array of RuntimeAnimation\n */\n getAnimations() {\n return this._runtimeAnimations;\n }\n /**\n * Adds more animations to the current animatable\n * @param target defines the target of the animations\n * @param animations defines the new animations to add\n */\n appendAnimations(target, animations) {\n for (let index = 0; index < animations.length; index++) {\n const animation = animations[index];\n const newRuntimeAnimation = new RuntimeAnimation(target, animation, this._scene, this);\n newRuntimeAnimation._onLoop = () => {\n this.onAnimationLoopObservable.notifyObservers(this);\n if (this.onAnimationLoop) {\n this.onAnimationLoop();\n }\n };\n this._runtimeAnimations.push(newRuntimeAnimation);\n }\n }\n /**\n * Gets the source animation for a specific property\n * @param property defines the property to look for\n * @returns null or the source animation for the given property\n */\n getAnimationByTargetProperty(property) {\n const runtimeAnimations = this._runtimeAnimations;\n for (let index = 0; index < runtimeAnimations.length; index++) {\n if (runtimeAnimations[index].animation.targetProperty === property) {\n return runtimeAnimations[index].animation;\n }\n }\n return null;\n }\n /**\n * Gets the runtime animation for a specific property\n * @param property defines the property to look for\n * @returns null or the runtime animation for the given property\n */\n getRuntimeAnimationByTargetProperty(property) {\n const runtimeAnimations = this._runtimeAnimations;\n for (let index = 0; index < runtimeAnimations.length; index++) {\n if (runtimeAnimations[index].animation.targetProperty === property) {\n return runtimeAnimations[index];\n }\n }\n return null;\n }\n /**\n * Resets the animatable to its original state\n */\n reset() {\n const runtimeAnimations = this._runtimeAnimations;\n for (let index = 0; index < runtimeAnimations.length; index++) {\n runtimeAnimations[index].reset(true);\n }\n this._localDelayOffset = null;\n this._pausedDelay = null;\n }\n /**\n * Allows the animatable to blend with current running animations\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#animation-blending\n * @param blendingSpeed defines the blending speed to use\n */\n enableBlending(blendingSpeed) {\n const runtimeAnimations = this._runtimeAnimations;\n for (let index = 0; index < runtimeAnimations.length; index++) {\n runtimeAnimations[index].animation.enableBlending = true;\n runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;\n }\n }\n /**\n * Disable animation blending\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#animation-blending\n */\n disableBlending() {\n const runtimeAnimations = this._runtimeAnimations;\n for (let index = 0; index < runtimeAnimations.length; index++) {\n runtimeAnimations[index].animation.enableBlending = false;\n }\n }\n /**\n * Jump directly to a given frame\n * @param frame defines the frame to jump to\n */\n goToFrame(frame) {\n var _a;\n const runtimeAnimations = this._runtimeAnimations;\n if (runtimeAnimations[0]) {\n const fps = runtimeAnimations[0].animation.framePerSecond;\n this._frameToSyncFromJump = (_a = this._frameToSyncFromJump) !== null && _a !== void 0 ? _a : runtimeAnimations[0].currentFrame;\n const delay = this.speedRatio === 0 ? 0 : (((frame - this._frameToSyncFromJump) / fps) * 1000) / this.speedRatio;\n this._manualJumpDelay = -delay;\n }\n for (let index = 0; index < runtimeAnimations.length; index++) {\n runtimeAnimations[index].goToFrame(frame);\n }\n this._goToFrame = frame;\n }\n /**\n * Pause the animation\n */\n pause() {\n if (this._paused) {\n return;\n }\n this._paused = true;\n }\n /**\n * Restart the animation\n */\n restart() {\n this._paused = false;\n }\n _raiseOnAnimationEnd() {\n if (this.onAnimationEnd) {\n this.onAnimationEnd();\n }\n this.onAnimationEndObservable.notifyObservers(this);\n }\n /**\n * Stop and delete the current animation\n * @param animationName defines a string used to only stop some of the runtime animations instead of all\n * @param targetMask a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)\n * @param useGlobalSplice if true, the animatables will be removed by the caller of this function (false by default)\n */\n stop(animationName, targetMask, useGlobalSplice = false) {\n if (animationName || targetMask) {\n const idx = this._scene._activeAnimatables.indexOf(this);\n if (idx > -1) {\n const runtimeAnimations = this._runtimeAnimations;\n for (let index = runtimeAnimations.length - 1; index >= 0; index--) {\n const runtimeAnimation = runtimeAnimations[index];\n if (animationName && runtimeAnimation.animation.name != animationName) {\n continue;\n }\n if (targetMask && !targetMask(runtimeAnimation.target)) {\n continue;\n }\n runtimeAnimation.dispose();\n runtimeAnimations.splice(index, 1);\n }\n if (runtimeAnimations.length == 0) {\n if (!useGlobalSplice) {\n this._scene._activeAnimatables.splice(idx, 1);\n }\n this._raiseOnAnimationEnd();\n }\n }\n }\n else {\n const index = this._scene._activeAnimatables.indexOf(this);\n if (index > -1) {\n if (!useGlobalSplice) {\n this._scene._activeAnimatables.splice(index, 1);\n }\n const runtimeAnimations = this._runtimeAnimations;\n for (let index = 0; index < runtimeAnimations.length; index++) {\n runtimeAnimations[index].dispose();\n }\n this._runtimeAnimations.length = 0;\n this._raiseOnAnimationEnd();\n }\n }\n }\n /**\n * Wait asynchronously for the animation to end\n * @returns a promise which will be fulfilled when the animation ends\n */\n waitAsync() {\n return new Promise((resolve) => {\n this.onAnimationEndObservable.add(() => {\n resolve(this);\n }, undefined, undefined, this, true);\n });\n }\n /**\n * @internal\n */\n _animate(delay) {\n if (this._paused) {\n this.animationStarted = false;\n if (this._pausedDelay === null) {\n this._pausedDelay = delay;\n }\n return true;\n }\n if (this._localDelayOffset === null) {\n this._localDelayOffset = delay;\n this._pausedDelay = null;\n }\n else if (this._pausedDelay !== null) {\n this._localDelayOffset += delay - this._pausedDelay;\n this._pausedDelay = null;\n }\n if (this._manualJumpDelay !== null) {\n this._localDelayOffset += this._manualJumpDelay;\n this._manualJumpDelay = null;\n this._frameToSyncFromJump = null;\n }\n this._goToFrame = null;\n if (this._weight === 0) {\n // We consider that an animation with a weight === 0 is \"actively\" paused\n return true;\n }\n // Animating\n let running = false;\n const runtimeAnimations = this._runtimeAnimations;\n let index;\n for (index = 0; index < runtimeAnimations.length; index++) {\n const animation = runtimeAnimations[index];\n const isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);\n running = running || isRunning;\n }\n this.animationStarted = running;\n if (!running) {\n if (this.disposeOnEnd) {\n // Remove from active animatables\n index = this._scene._activeAnimatables.indexOf(this);\n this._scene._activeAnimatables.splice(index, 1);\n // Dispose all runtime animations\n for (index = 0; index < runtimeAnimations.length; index++) {\n runtimeAnimations[index].dispose();\n }\n }\n this._raiseOnAnimationEnd();\n if (this.disposeOnEnd) {\n this.onAnimationEnd = null;\n this.onAnimationLoop = null;\n this.onAnimationLoopObservable.clear();\n this.onAnimationEndObservable.clear();\n }\n }\n return running;\n }\n}\nScene.prototype._animate = function () {\n if (!this.animationsEnabled) {\n return;\n }\n // Getting time\n const now = PrecisionDate.Now;\n if (!this._animationTimeLast) {\n if (this._pendingData.length > 0) {\n return;\n }\n this._animationTimeLast = now;\n }\n this.deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;\n this._animationTimeLast = now;\n const animatables = this._activeAnimatables;\n if (animatables.length === 0) {\n return;\n }\n this._animationTime += this.deltaTime;\n const animationTime = this._animationTime;\n for (let index = 0; index < animatables.length; index++) {\n const animatable = animatables[index];\n if (!animatable._animate(animationTime) && animatable.disposeOnEnd) {\n index--; // Array was updated\n }\n }\n // Late animation bindings\n this._processLateAnimationBindings();\n};\nScene.prototype.beginWeightedAnimation = function (target, from, to, weight = 1.0, loop, speedRatio = 1.0, onAnimationEnd, animatable, targetMask, onAnimationLoop, isAdditive = false) {\n const returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask, onAnimationLoop, isAdditive);\n returnedAnimatable.weight = weight;\n return returnedAnimatable;\n};\nScene.prototype.beginAnimation = function (target, from, to, loop, speedRatio = 1.0, onAnimationEnd, animatable, stopCurrent = true, targetMask, onAnimationLoop, isAdditive = false) {\n if (from > to && speedRatio > 0) {\n speedRatio *= -1;\n }\n if (stopCurrent) {\n this.stopAnimation(target, undefined, targetMask);\n }\n if (!animatable) {\n animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, undefined, onAnimationLoop, isAdditive);\n }\n const shouldRunTargetAnimations = targetMask ? targetMask(target) : true;\n // Local animations\n if (target.animations && shouldRunTargetAnimations) {\n animatable.appendAnimations(target, target.animations);\n }\n // Children animations\n if (target.getAnimatables) {\n const animatables = target.getAnimatables();\n for (let index = 0; index < animatables.length; index++) {\n this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, onAnimationLoop);\n }\n }\n animatable.reset();\n return animatable;\n};\nScene.prototype.beginHierarchyAnimation = function (target, directDescendantsOnly, from, to, loop, speedRatio = 1.0, onAnimationEnd, animatable, stopCurrent = true, targetMask, onAnimationLoop, isAdditive = false) {\n const children = target.getDescendants(directDescendantsOnly);\n const result = [];\n result.push(this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, undefined, isAdditive));\n for (const child of children) {\n result.push(this.beginAnimation(child, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, undefined, isAdditive));\n }\n return result;\n};\nScene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop, isAdditive = false) {\n if (speedRatio === undefined) {\n speedRatio = 1.0;\n }\n if (from > to && speedRatio > 0) {\n speedRatio *= -1;\n }\n else if (to > from && speedRatio < 0) {\n const temp = to;\n to = from;\n from = temp;\n }\n const animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations, onAnimationLoop, isAdditive);\n return animatable;\n};\nScene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop, isAdditive = false) {\n const children = target.getDescendants(directDescendantsOnly);\n const result = [];\n result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop, isAdditive));\n for (const child of children) {\n result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop, isAdditive));\n }\n return result;\n};\nScene.prototype.getAnimatableByTarget = function (target) {\n for (let index = 0; index < this._activeAnimatables.length; index++) {\n if (this._activeAnimatables[index].target === target) {\n return this._activeAnimatables[index];\n }\n }\n return null;\n};\nScene.prototype.getAllAnimatablesByTarget = function (target) {\n const result = [];\n for (let index = 0; index < this._activeAnimatables.length; index++) {\n if (this._activeAnimatables[index].target === target) {\n result.push(this._activeAnimatables[index]);\n }\n }\n return result;\n};\n/**\n * Will stop the animation of the given target\n * @param target - the target\n * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)\n * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)\n */\nScene.prototype.stopAnimation = function (target, animationName, targetMask) {\n const animatables = this.getAllAnimatablesByTarget(target);\n for (const animatable of animatables) {\n animatable.stop(animationName, targetMask);\n }\n};\n/**\n * Stops and removes all animations that have been applied to the scene\n */\nScene.prototype.stopAllAnimations = function () {\n if (this._activeAnimatables) {\n for (let i = 0; i < this._activeAnimatables.length; i++) {\n this._activeAnimatables[i].stop(undefined, undefined, true);\n }\n this._activeAnimatables.length = 0;\n }\n for (const group of this.animationGroups) {\n group.stop();\n }\n};\nScene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {\n const target = runtimeAnimation.target;\n this._registeredForLateAnimationBindings.pushNoDuplicate(target);\n if (!target._lateAnimationHolders) {\n target._lateAnimationHolders = {};\n }\n if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {\n target._lateAnimationHolders[runtimeAnimation.targetPath] = {\n totalWeight: 0,\n totalAdditiveWeight: 0,\n animations: [],\n additiveAnimations: [],\n originalValue: originalValue,\n };\n }\n if (runtimeAnimation.isAdditive) {\n target._lateAnimationHolders[runtimeAnimation.targetPath].additiveAnimations.push(runtimeAnimation);\n target._lateAnimationHolders[runtimeAnimation.targetPath].totalAdditiveWeight += runtimeAnimation.weight;\n }\n else {\n target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);\n target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;\n }\n};\nScene.prototype._processLateAnimationBindingsForMatrices = function (holder) {\n if (holder.totalWeight === 0 && holder.totalAdditiveWeight === 0) {\n return holder.originalValue;\n }\n let normalizer = 1.0;\n const finalPosition = TmpVectors.Vector3[0];\n const finalScaling = TmpVectors.Vector3[1];\n const finalQuaternion = TmpVectors.Quaternion[0];\n let startIndex = 0;\n const originalAnimation = holder.animations[0];\n const originalValue = holder.originalValue;\n let scale = 1;\n let skipOverride = false;\n if (holder.totalWeight < 1.0) {\n // We need to mix the original value in\n scale = 1.0 - holder.totalWeight;\n originalValue.decompose(finalScaling, finalQuaternion, finalPosition);\n }\n else {\n startIndex = 1;\n // We need to normalize the weights\n normalizer = holder.totalWeight;\n scale = originalAnimation.weight / normalizer;\n if (scale == 1) {\n if (holder.totalAdditiveWeight) {\n skipOverride = true;\n }\n else {\n return originalAnimation.currentValue;\n }\n }\n originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);\n }\n // Add up the override animations\n if (!skipOverride) {\n finalScaling.scaleInPlace(scale);\n finalPosition.scaleInPlace(scale);\n finalQuaternion.scaleInPlace(scale);\n for (let animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {\n const runtimeAnimation = holder.animations[animIndex];\n if (runtimeAnimation.weight === 0) {\n continue;\n }\n scale = runtimeAnimation.weight / normalizer;\n const currentPosition = TmpVectors.Vector3[2];\n const currentScaling = TmpVectors.Vector3[3];\n const currentQuaternion = TmpVectors.Quaternion[1];\n runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);\n currentScaling.scaleAndAddToRef(scale, finalScaling);\n currentQuaternion.scaleAndAddToRef(Quaternion.Dot(finalQuaternion, currentQuaternion) > 0 ? scale : -scale, finalQuaternion);\n currentPosition.scaleAndAddToRef(scale, finalPosition);\n }\n finalQuaternion.normalize();\n }\n // Add up the additive animations\n for (let animIndex = 0; animIndex < holder.additiveAnimations.length; animIndex++) {\n const runtimeAnimation = holder.additiveAnimations[animIndex];\n if (runtimeAnimation.weight === 0) {\n continue;\n }\n const currentPosition = TmpVectors.Vector3[2];\n const currentScaling = TmpVectors.Vector3[3];\n const currentQuaternion = TmpVectors.Quaternion[1];\n runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);\n currentScaling.multiplyToRef(finalScaling, currentScaling);\n Vector3.LerpToRef(finalScaling, currentScaling, runtimeAnimation.weight, finalScaling);\n finalQuaternion.multiplyToRef(currentQuaternion, currentQuaternion);\n Quaternion.SlerpToRef(finalQuaternion, currentQuaternion, runtimeAnimation.weight, finalQuaternion);\n currentPosition.scaleAndAddToRef(runtimeAnimation.weight, finalPosition);\n }\n const workValue = originalAnimation ? originalAnimation._animationState.workValue : TmpVectors.Matrix[0].clone();\n Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, workValue);\n return workValue;\n};\nScene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {\n if (holder.totalWeight === 0 && holder.totalAdditiveWeight === 0) {\n return refQuaternion;\n }\n const originalAnimation = holder.animations[0];\n const originalValue = holder.originalValue;\n let cumulativeQuaternion = refQuaternion;\n if (holder.totalWeight === 0 && holder.totalAdditiveWeight > 0) {\n cumulativeQuaternion.copyFrom(originalValue);\n }\n else if (holder.animations.length === 1) {\n Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), cumulativeQuaternion);\n if (holder.totalAdditiveWeight === 0) {\n return cumulativeQuaternion;\n }\n }\n else if (holder.animations.length > 1) {\n // Add up the override animations\n let normalizer = 1.0;\n let quaternions;\n let weights;\n if (holder.totalWeight < 1.0) {\n const scale = 1.0 - holder.totalWeight;\n quaternions = [];\n weights = [];\n quaternions.push(originalValue);\n weights.push(scale);\n }\n else {\n if (holder.animations.length === 2) {\n // Slerp as soon as we can\n Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);\n if (holder.totalAdditiveWeight === 0) {\n return refQuaternion;\n }\n }\n quaternions = [];\n weights = [];\n normalizer = holder.totalWeight;\n }\n for (let animIndex = 0; animIndex < holder.animations.length; animIndex++) {\n const runtimeAnimation = holder.animations[animIndex];\n quaternions.push(runtimeAnimation.currentValue);\n weights.push(runtimeAnimation.weight / normalizer);\n }\n // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions\n let cumulativeAmount = 0;\n for (let index = 0; index < quaternions.length;) {\n if (!index) {\n Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);\n cumulativeQuaternion = refQuaternion;\n cumulativeAmount = weights[index] + weights[index + 1];\n index += 2;\n continue;\n }\n cumulativeAmount += weights[index];\n Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);\n index++;\n }\n }\n // Add up the additive animations\n for (let animIndex = 0; animIndex < holder.additiveAnimations.length; animIndex++) {\n const runtimeAnimation = holder.additiveAnimations[animIndex];\n if (runtimeAnimation.weight === 0) {\n continue;\n }\n cumulativeQuaternion.multiplyToRef(runtimeAnimation.currentValue, TmpVectors.Quaternion[0]);\n Quaternion.SlerpToRef(cumulativeQuaternion, TmpVectors.Quaternion[0], runtimeAnimation.weight, cumulativeQuaternion);\n }\n return cumulativeQuaternion;\n};\nScene.prototype._processLateAnimationBindings = function () {\n if (!this._registeredForLateAnimationBindings.length) {\n return;\n }\n for (let index = 0; index < this._registeredForLateAnimationBindings.length; index++) {\n const target = this._registeredForLateAnimationBindings.data[index];\n for (const path in target._lateAnimationHolders) {\n const holder = target._lateAnimationHolders[path];\n const originalAnimation = holder.animations[0];\n const originalValue = holder.originalValue;\n if (originalValue === undefined || originalValue === null) {\n continue;\n }\n const matrixDecomposeMode = Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix\n let finalValue = target[path];\n if (matrixDecomposeMode) {\n finalValue = this._processLateAnimationBindingsForMatrices(holder);\n }\n else {\n const quaternionMode = originalValue.w !== undefined;\n if (quaternionMode) {\n finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || Quaternion.Identity());\n }\n else {\n let startIndex = 0;\n let normalizer = 1.0;\n if (holder.totalWeight < 1.0) {\n // We need to mix the original value in\n if (originalAnimation && originalValue.scale) {\n finalValue = originalValue.scale(1.0 - holder.totalWeight);\n }\n else if (originalAnimation) {\n finalValue = originalValue * (1.0 - holder.totalWeight);\n }\n else if (originalValue.clone) {\n finalValue = originalValue.clone();\n }\n else {\n finalValue = originalValue;\n }\n }\n else if (originalAnimation) {\n // We need to normalize the weights\n normalizer = holder.totalWeight;\n const scale = originalAnimation.weight / normalizer;\n if (scale !== 1) {\n if (originalAnimation.currentValue.scale) {\n finalValue = originalAnimation.currentValue.scale(scale);\n }\n else {\n finalValue = originalAnimation.currentValue * scale;\n }\n }\n else {\n finalValue = originalAnimation.currentValue;\n }\n startIndex = 1;\n }\n // Add up the override animations\n for (let animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {\n const runtimeAnimation = holder.animations[animIndex];\n const scale = runtimeAnimation.weight / normalizer;\n if (!scale) {\n continue;\n }\n else if (runtimeAnimation.currentValue.scaleAndAddToRef) {\n runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);\n }\n else {\n finalValue += runtimeAnimation.currentValue * scale;\n }\n }\n // Add up the additive animations\n for (let animIndex = 0; animIndex < holder.additiveAnimations.length; animIndex++) {\n const runtimeAnimation = holder.additiveAnimations[animIndex];\n const scale = runtimeAnimation.weight;\n if (!scale) {\n continue;\n }\n else if (runtimeAnimation.currentValue.scaleAndAddToRef) {\n runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);\n }\n else {\n finalValue += runtimeAnimation.currentValue * scale;\n }\n }\n }\n }\n target[path] = finalValue;\n }\n target._lateAnimationHolders = {};\n }\n this._registeredForLateAnimationBindings.reset();\n};\nBone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired = false, skelDimensionsRatio = null) {\n // all animation may be coming from a library skeleton, so may need to create animation\n if (this.animations.length === 0) {\n this.animations.push(new Animation(this.name, \"_matrix\", source.animations[0].framePerSecond, Animation.ANIMATIONTYPE_MATRIX, 0));\n this.animations[0].setKeys([]);\n }\n // get animation info / verify there is such a range from the source bone\n const sourceRange = source.animations[0].getRange(rangeName);\n if (!sourceRange) {\n return false;\n }\n const from = sourceRange.from;\n const to = sourceRange.to;\n const sourceKeys = source.animations[0].getKeys();\n // rescaling prep\n const sourceBoneLength = source.length;\n const sourceParent = source.getParent();\n const parent = this.getParent();\n const parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;\n const parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;\n const dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);\n const destKeys = this.animations[0].getKeys();\n // loop vars declaration\n let orig;\n let origTranslation;\n let mat;\n for (let key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {\n orig = sourceKeys[key];\n if (orig.frame >= from && orig.frame <= to) {\n if (rescaleAsRequired) {\n mat = orig.value.clone();\n // scale based on parent ratio, when bone has parent\n if (parentScalingReqd) {\n origTranslation = mat.getTranslation();\n mat.setTranslation(origTranslation.scaleInPlace(parentRatio));\n // scale based on skeleton dimension ratio when root bone, and value is passed\n }\n else if (dimensionsScalingReqd && skelDimensionsRatio) {\n origTranslation = mat.getTranslation();\n mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));\n // use original when root bone, and no data for skelDimensionsRatio\n }\n else {\n mat = orig.value;\n }\n }\n else {\n mat = orig.value;\n }\n destKeys.push({ frame: orig.frame + frameOffset, value: mat });\n }\n }\n this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);\n return true;\n};\n//# sourceMappingURL=animatable.js.map","import { Scalar } from \"./math.scalar.js\";\nimport { Vector2, Vector3, Quaternion, Matrix } from \"./math.vector.js\";\nimport { Epsilon } from \"./math.constants.js\";\n/**\n * Defines potential orientation for back face culling\n */\nexport var Orientation;\n(function (Orientation) {\n /**\n * Clockwise\n */\n Orientation[Orientation[\"CW\"] = 0] = \"CW\";\n /** Counter clockwise */\n Orientation[Orientation[\"CCW\"] = 1] = \"CCW\";\n})(Orientation || (Orientation = {}));\n/** Class used to represent a Bezier curve */\nexport class BezierCurve {\n /**\n * Returns the cubic Bezier interpolated value (float) at \"t\" (float) from the given x1, y1, x2, y2 floats\n * @param t defines the time\n * @param x1 defines the left coordinate on X axis\n * @param y1 defines the left coordinate on Y axis\n * @param x2 defines the right coordinate on X axis\n * @param y2 defines the right coordinate on Y axis\n * @returns the interpolated value\n */\n static Interpolate(t, x1, y1, x2, y2) {\n // Extract X (which is equal to time here)\n const f0 = 1 - 3 * x2 + 3 * x1;\n const f1 = 3 * x2 - 6 * x1;\n const f2 = 3 * x1;\n let refinedT = t;\n for (let i = 0; i < 5; i++) {\n const refinedT2 = refinedT * refinedT;\n const refinedT3 = refinedT2 * refinedT;\n const x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;\n const slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);\n refinedT -= (x - t) * slope;\n refinedT = Math.min(1, Math.max(0, refinedT));\n }\n // Resolve cubic bezier for the given x\n return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);\n }\n}\n/**\n * Defines angle representation\n */\nexport class Angle {\n /**\n * Creates an Angle object of \"radians\" radians (float).\n * @param radians the angle in radians\n */\n constructor(radians) {\n this._radians = radians;\n if (this._radians < 0.0) {\n this._radians += 2.0 * Math.PI;\n }\n }\n /**\n * Get value in degrees\n * @returns the Angle value in degrees (float)\n */\n degrees() {\n return (this._radians * 180.0) / Math.PI;\n }\n /**\n * Get value in radians\n * @returns the Angle value in radians (float)\n */\n radians() {\n return this._radians;\n }\n /**\n * Gets a new Angle object valued with the gradient angle, in radians, of the line joining two points\n * @param a defines first point as the origin\n * @param b defines point\n * @returns a new Angle\n */\n static BetweenTwoPoints(a, b) {\n const delta = b.subtract(a);\n const theta = Math.atan2(delta.y, delta.x);\n return new Angle(theta);\n }\n /**\n * Gets a new Angle object from the given float in radians\n * @param radians defines the angle value in radians\n * @returns a new Angle\n */\n static FromRadians(radians) {\n return new Angle(radians);\n }\n /**\n * Gets a new Angle object from the given float in degrees\n * @param degrees defines the angle value in degrees\n * @returns a new Angle\n */\n static FromDegrees(degrees) {\n return new Angle((degrees * Math.PI) / 180.0);\n }\n}\n/**\n * This represents an arc in a 2d space.\n */\nexport class Arc2 {\n /**\n * Creates an Arc object from the three given points : start, middle and end.\n * @param startPoint Defines the start point of the arc\n * @param midPoint Defines the middle point of the arc\n * @param endPoint Defines the end point of the arc\n */\n constructor(\n /** Defines the start point of the arc */\n startPoint, \n /** Defines the mid point of the arc */\n midPoint, \n /** Defines the end point of the arc */\n endPoint) {\n this.startPoint = startPoint;\n this.midPoint = midPoint;\n this.endPoint = endPoint;\n const temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);\n const startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2;\n const midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2;\n const det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);\n this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);\n this.radius = this.centerPoint.subtract(this.startPoint).length();\n this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);\n const a1 = this.startAngle.degrees();\n let a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();\n let a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();\n // angles correction\n if (a2 - a1 > +180.0) {\n a2 -= 360.0;\n }\n if (a2 - a1 < -180.0) {\n a2 += 360.0;\n }\n if (a3 - a2 > +180.0) {\n a3 -= 360.0;\n }\n if (a3 - a2 < -180.0) {\n a3 += 360.0;\n }\n this.orientation = a2 - a1 < 0 ? Orientation.CW : Orientation.CCW;\n this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);\n }\n}\n/**\n * Represents a 2D path made up of multiple 2D points\n */\nexport class Path2 {\n /**\n * Creates a Path2 object from the starting 2D coordinates x and y.\n * @param x the starting points x value\n * @param y the starting points y value\n */\n constructor(x, y) {\n this._points = new Array();\n this._length = 0.0;\n /**\n * If the path start and end point are the same\n */\n this.closed = false;\n this._points.push(new Vector2(x, y));\n }\n /**\n * Adds a new segment until the given coordinates (x, y) to the current Path2.\n * @param x the added points x value\n * @param y the added points y value\n * @returns the updated Path2.\n */\n addLineTo(x, y) {\n if (this.closed) {\n return this;\n }\n const newPoint = new Vector2(x, y);\n const previousPoint = this._points[this._points.length - 1];\n this._points.push(newPoint);\n this._length += newPoint.subtract(previousPoint).length();\n return this;\n }\n /**\n * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.\n * @param midX middle point x value\n * @param midY middle point y value\n * @param endX end point x value\n * @param endY end point y value\n * @param numberOfSegments (default: 36)\n * @returns the updated Path2.\n */\n addArcTo(midX, midY, endX, endY, numberOfSegments = 36) {\n if (this.closed) {\n return this;\n }\n const startPoint = this._points[this._points.length - 1];\n const midPoint = new Vector2(midX, midY);\n const endPoint = new Vector2(endX, endY);\n const arc = new Arc2(startPoint, midPoint, endPoint);\n let increment = arc.angle.radians() / numberOfSegments;\n if (arc.orientation === Orientation.CW) {\n increment *= -1;\n }\n let currentAngle = arc.startAngle.radians() + increment;\n for (let i = 0; i < numberOfSegments; i++) {\n const x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;\n const y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;\n this.addLineTo(x, y);\n currentAngle += increment;\n }\n return this;\n }\n /**\n * Adds _numberOfSegments_ segments according to the quadratic curve definition to the current Path2.\n * @param controlX control point x value\n * @param controlY control point y value\n * @param endX end point x value\n * @param endY end point y value\n * @param numberOfSegments (default: 36)\n * @returns the updated Path2.\n */\n addQuadraticCurveTo(controlX, controlY, endX, endY, numberOfSegments = 36) {\n if (this.closed) {\n return this;\n }\n const equation = (t, val0, val1, val2) => {\n const res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;\n return res;\n };\n const startPoint = this._points[this._points.length - 1];\n for (let i = 0; i <= numberOfSegments; i++) {\n const step = i / numberOfSegments;\n const x = equation(step, startPoint.x, controlX, endX);\n const y = equation(step, startPoint.y, controlY, endY);\n this.addLineTo(x, y);\n }\n return this;\n }\n /**\n * Adds _numberOfSegments_ segments according to the bezier curve definition to the current Path2.\n * @param originTangentX tangent vector at the origin point x value\n * @param originTangentY tangent vector at the origin point y value\n * @param destinationTangentX tangent vector at the destination point x value\n * @param destinationTangentY tangent vector at the destination point y value\n * @param endX end point x value\n * @param endY end point y value\n * @param numberOfSegments (default: 36)\n * @returns the updated Path2.\n */\n addBezierCurveTo(originTangentX, originTangentY, destinationTangentX, destinationTangentY, endX, endY, numberOfSegments = 36) {\n if (this.closed) {\n return this;\n }\n const equation = (t, val0, val1, val2, val3) => {\n const res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;\n return res;\n };\n const startPoint = this._points[this._points.length - 1];\n for (let i = 0; i <= numberOfSegments; i++) {\n const step = i / numberOfSegments;\n const x = equation(step, startPoint.x, originTangentX, destinationTangentX, endX);\n const y = equation(step, startPoint.y, originTangentY, destinationTangentY, endY);\n this.addLineTo(x, y);\n }\n return this;\n }\n /**\n * Defines if a given point is inside the polygon defines by the path\n * @param point defines the point to test\n * @returns true if the point is inside\n */\n isPointInside(point) {\n let isInside = false;\n const count = this._points.length;\n for (let p = count - 1, q = 0; q < count; p = q++) {\n let edgeLow = this._points[p];\n let edgeHigh = this._points[q];\n let edgeDx = edgeHigh.x - edgeLow.x;\n let edgeDy = edgeHigh.y - edgeLow.y;\n if (Math.abs(edgeDy) > Number.EPSILON) {\n // Not parallel\n if (edgeDy < 0) {\n edgeLow = this._points[q];\n edgeDx = -edgeDx;\n edgeHigh = this._points[p];\n edgeDy = -edgeDy;\n }\n if (point.y < edgeLow.y || point.y > edgeHigh.y) {\n continue;\n }\n if (point.y === edgeLow.y && point.x === edgeLow.x) {\n return true;\n }\n else {\n const perpEdge = edgeDy * (point.x - edgeLow.x) - edgeDx * (point.y - edgeLow.y);\n if (perpEdge === 0) {\n return true;\n }\n if (perpEdge < 0) {\n continue;\n }\n isInside = !isInside;\n }\n }\n else {\n // parallel or collinear\n if (point.y !== edgeLow.y) {\n continue;\n }\n if ((edgeHigh.x <= point.x && point.x <= edgeLow.x) || (edgeLow.x <= point.x && point.x <= edgeHigh.x)) {\n return true;\n }\n }\n }\n return isInside;\n }\n /**\n * Closes the Path2.\n * @returns the Path2.\n */\n close() {\n this.closed = true;\n return this;\n }\n /**\n * Gets the sum of the distance between each sequential point in the path\n * @returns the Path2 total length (float).\n */\n length() {\n let result = this._length;\n if (this.closed) {\n const lastPoint = this._points[this._points.length - 1];\n const firstPoint = this._points[0];\n result += firstPoint.subtract(lastPoint).length();\n }\n return result;\n }\n /**\n * Gets the area of the polygon defined by the path\n * @returns area value\n */\n area() {\n const n = this._points.length;\n let value = 0.0;\n for (let p = n - 1, q = 0; q < n; p = q++) {\n value += this._points[p].x * this._points[q].y - this._points[q].x * this._points[p].y;\n }\n return value * 0.5;\n }\n /**\n * Gets the points which construct the path\n * @returns the Path2 internal array of points.\n */\n getPoints() {\n return this._points;\n }\n /**\n * Retreives the point at the distance aways from the starting point\n * @param normalizedLengthPosition the length along the path to retrieve the point from\n * @returns a new Vector2 located at a percentage of the Path2 total length on this path.\n */\n getPointAtLengthPosition(normalizedLengthPosition) {\n if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {\n return Vector2.Zero();\n }\n const lengthPosition = normalizedLengthPosition * this.length();\n let previousOffset = 0;\n for (let i = 0; i < this._points.length; i++) {\n const j = (i + 1) % this._points.length;\n const a = this._points[i];\n const b = this._points[j];\n const bToA = b.subtract(a);\n const nextOffset = bToA.length() + previousOffset;\n if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {\n const dir = bToA.normalize();\n const localOffset = lengthPosition - previousOffset;\n return new Vector2(a.x + dir.x * localOffset, a.y + dir.y * localOffset);\n }\n previousOffset = nextOffset;\n }\n return Vector2.Zero();\n }\n /**\n * Creates a new path starting from an x and y position\n * @param x starting x value\n * @param y starting y value\n * @returns a new Path2 starting at the coordinates (x, y).\n */\n static StartingAt(x, y) {\n return new Path2(x, y);\n }\n}\n/**\n * Represents a 3D path made up of multiple 3D points\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/path3D\n */\nexport class Path3D {\n /**\n * new Path3D(path, normal, raw)\n * Creates a Path3D. A Path3D is a logical math object, so not a mesh.\n * please read the description in the tutorial : https://doc.babylonjs.com/features/featuresDeepDive/mesh/path3D\n * @param path an array of Vector3, the curve axis of the Path3D\n * @param firstNormal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.\n * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.\n * @param alignTangentsWithPath (optional, default false) : boolean, if true the tangents will be aligned with the path.\n */\n constructor(\n /**\n * an array of Vector3, the curve axis of the Path3D\n */\n path, firstNormal = null, raw, alignTangentsWithPath = false) {\n this.path = path;\n this._curve = new Array();\n this._distances = new Array();\n this._tangents = new Array();\n this._normals = new Array();\n this._binormals = new Array();\n // holds interpolated point data\n this._pointAtData = {\n id: 0,\n point: Vector3.Zero(),\n previousPointArrayIndex: 0,\n position: 0,\n subPosition: 0,\n interpolateReady: false,\n interpolationMatrix: Matrix.Identity(),\n };\n for (let p = 0; p < path.length; p++) {\n this._curve[p] = path[p].clone(); // hard copy\n }\n this._raw = raw || false;\n this._alignTangentsWithPath = alignTangentsWithPath;\n this._compute(firstNormal, alignTangentsWithPath);\n }\n /**\n * Returns the Path3D array of successive Vector3 designing its curve.\n * @returns the Path3D array of successive Vector3 designing its curve.\n */\n getCurve() {\n return this._curve;\n }\n /**\n * Returns the Path3D array of successive Vector3 designing its curve.\n * @returns the Path3D array of successive Vector3 designing its curve.\n */\n getPoints() {\n return this._curve;\n }\n /**\n * @returns the computed length (float) of the path.\n */\n length() {\n return this._distances[this._distances.length - 1];\n }\n /**\n * Returns an array populated with tangent vectors on each Path3D curve point.\n * @returns an array populated with tangent vectors on each Path3D curve point.\n */\n getTangents() {\n return this._tangents;\n }\n /**\n * Returns an array populated with normal vectors on each Path3D curve point.\n * @returns an array populated with normal vectors on each Path3D curve point.\n */\n getNormals() {\n return this._normals;\n }\n /**\n * Returns an array populated with binormal vectors on each Path3D curve point.\n * @returns an array populated with binormal vectors on each Path3D curve point.\n */\n getBinormals() {\n return this._binormals;\n }\n /**\n * Returns an array populated with distances (float) of the i-th point from the first curve point.\n * @returns an array populated with distances (float) of the i-th point from the first curve point.\n */\n getDistances() {\n return this._distances;\n }\n /**\n * Returns an interpolated point along this path\n * @param position the position of the point along this path, from 0.0 to 1.0\n * @returns a new Vector3 as the point\n */\n getPointAt(position) {\n return this._updatePointAtData(position).point;\n }\n /**\n * Returns the tangent vector of an interpolated Path3D curve point at the specified position along this path.\n * @param position the position of the point along this path, from 0.0 to 1.0\n * @param interpolated (optional, default false) : boolean, if true returns an interpolated tangent instead of the tangent of the previous path point.\n * @returns a tangent vector corresponding to the interpolated Path3D curve point, if not interpolated, the tangent is taken from the precomputed tangents array.\n */\n getTangentAt(position, interpolated = false) {\n this._updatePointAtData(position, interpolated);\n return interpolated ? Vector3.TransformCoordinates(Vector3.Forward(), this._pointAtData.interpolationMatrix) : this._tangents[this._pointAtData.previousPointArrayIndex];\n }\n /**\n * Returns the tangent vector of an interpolated Path3D curve point at the specified position along this path.\n * @param position the position of the point along this path, from 0.0 to 1.0\n * @param interpolated (optional, default false) : boolean, if true returns an interpolated normal instead of the normal of the previous path point.\n * @returns a normal vector corresponding to the interpolated Path3D curve point, if not interpolated, the normal is taken from the precomputed normals array.\n */\n getNormalAt(position, interpolated = false) {\n this._updatePointAtData(position, interpolated);\n return interpolated ? Vector3.TransformCoordinates(Vector3.Right(), this._pointAtData.interpolationMatrix) : this._normals[this._pointAtData.previousPointArrayIndex];\n }\n /**\n * Returns the binormal vector of an interpolated Path3D curve point at the specified position along this path.\n * @param position the position of the point along this path, from 0.0 to 1.0\n * @param interpolated (optional, default false) : boolean, if true returns an interpolated binormal instead of the binormal of the previous path point.\n * @returns a binormal vector corresponding to the interpolated Path3D curve point, if not interpolated, the binormal is taken from the precomputed binormals array.\n */\n getBinormalAt(position, interpolated = false) {\n this._updatePointAtData(position, interpolated);\n return interpolated ? Vector3.TransformCoordinates(Vector3.UpReadOnly, this._pointAtData.interpolationMatrix) : this._binormals[this._pointAtData.previousPointArrayIndex];\n }\n /**\n * Returns the distance (float) of an interpolated Path3D curve point at the specified position along this path.\n * @param position the position of the point along this path, from 0.0 to 1.0\n * @returns the distance of the interpolated Path3D curve point at the specified position along this path.\n */\n getDistanceAt(position) {\n return this.length() * position;\n }\n /**\n * Returns the array index of the previous point of an interpolated point along this path\n * @param position the position of the point to interpolate along this path, from 0.0 to 1.0\n * @returns the array index\n */\n getPreviousPointIndexAt(position) {\n this._updatePointAtData(position);\n return this._pointAtData.previousPointArrayIndex;\n }\n /**\n * Returns the position of an interpolated point relative to the two path points it lies between, from 0.0 (point A) to 1.0 (point B)\n * @param position the position of the point to interpolate along this path, from 0.0 to 1.0\n * @returns the sub position\n */\n getSubPositionAt(position) {\n this._updatePointAtData(position);\n return this._pointAtData.subPosition;\n }\n /**\n * Returns the position of the closest virtual point on this path to an arbitrary Vector3, from 0.0 to 1.0\n * @param target the vector of which to get the closest position to\n * @returns the position of the closest virtual point on this path to the target vector\n */\n getClosestPositionTo(target) {\n let smallestDistance = Number.MAX_VALUE;\n let closestPosition = 0.0;\n for (let i = 0; i < this._curve.length - 1; i++) {\n const point = this._curve[i + 0];\n const tangent = this._curve[i + 1].subtract(point).normalize();\n const subLength = this._distances[i + 1] - this._distances[i + 0];\n const subPosition = Math.min((Math.max(Vector3.Dot(tangent, target.subtract(point).normalize()), 0.0) * Vector3.Distance(point, target)) / subLength, 1.0);\n const distance = Vector3.Distance(point.add(tangent.scale(subPosition * subLength)), target);\n if (distance < smallestDistance) {\n smallestDistance = distance;\n closestPosition = (this._distances[i + 0] + subLength * subPosition) / this.length();\n }\n }\n return closestPosition;\n }\n /**\n * Returns a sub path (slice) of this path\n * @param start the position of the fist path point, from 0.0 to 1.0, or a negative value, which will get wrapped around from the end of the path to 0.0 to 1.0 values\n * @param end the position of the last path point, from 0.0 to 1.0, or a negative value, which will get wrapped around from the end of the path to 0.0 to 1.0 values\n * @returns a sub path (slice) of this path\n */\n slice(start = 0.0, end = 1.0) {\n if (start < 0.0) {\n start = 1 - ((start * -1.0) % 1.0);\n }\n if (end < 0.0) {\n end = 1 - ((end * -1.0) % 1.0);\n }\n if (start > end) {\n const _start = start;\n start = end;\n end = _start;\n }\n const curvePoints = this.getCurve();\n const startPoint = this.getPointAt(start);\n let startIndex = this.getPreviousPointIndexAt(start);\n const endPoint = this.getPointAt(end);\n const endIndex = this.getPreviousPointIndexAt(end) + 1;\n const slicePoints = [];\n if (start !== 0.0) {\n startIndex++;\n slicePoints.push(startPoint);\n }\n slicePoints.push(...curvePoints.slice(startIndex, endIndex));\n if (end !== 1.0 || start === 1.0) {\n slicePoints.push(endPoint);\n }\n return new Path3D(slicePoints, this.getNormalAt(start), this._raw, this._alignTangentsWithPath);\n }\n /**\n * Forces the Path3D tangent, normal, binormal and distance recomputation.\n * @param path path which all values are copied into the curves points\n * @param firstNormal which should be projected onto the curve\n * @param alignTangentsWithPath (optional, default false) : boolean, if true the tangents will be aligned with the path\n * @returns the same object updated.\n */\n update(path, firstNormal = null, alignTangentsWithPath = false) {\n for (let p = 0; p < path.length; p++) {\n this._curve[p].x = path[p].x;\n this._curve[p].y = path[p].y;\n this._curve[p].z = path[p].z;\n }\n this._compute(firstNormal, alignTangentsWithPath);\n return this;\n }\n // private function compute() : computes tangents, normals and binormals\n _compute(firstNormal, alignTangentsWithPath = false) {\n const l = this._curve.length;\n if (l < 2) {\n return;\n }\n // first and last tangents\n this._tangents[0] = this._getFirstNonNullVector(0);\n if (!this._raw) {\n this._tangents[0].normalize();\n }\n this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);\n if (!this._raw) {\n this._tangents[l - 1].normalize();\n }\n // normals and binormals at first point : arbitrary vector with _normalVector()\n const tg0 = this._tangents[0];\n const pp0 = this._normalVector(tg0, firstNormal);\n this._normals[0] = pp0;\n if (!this._raw) {\n this._normals[0].normalize();\n }\n this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);\n if (!this._raw) {\n this._binormals[0].normalize();\n }\n this._distances[0] = 0.0;\n // normals and binormals : next points\n let prev; // previous vector (segment)\n let cur; // current vector (segment)\n let curTang; // current tangent\n // previous normal\n let prevNor; // previous normal\n let prevBinor; // previous binormal\n for (let i = 1; i < l; i++) {\n // tangents\n prev = this._getLastNonNullVector(i);\n if (i < l - 1) {\n cur = this._getFirstNonNullVector(i);\n this._tangents[i] = alignTangentsWithPath ? cur : prev.add(cur);\n this._tangents[i].normalize();\n }\n this._distances[i] = this._distances[i - 1] + this._curve[i].subtract(this._curve[i - 1]).length();\n // normals and binormals\n // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html\n curTang = this._tangents[i];\n prevBinor = this._binormals[i - 1];\n this._normals[i] = Vector3.Cross(prevBinor, curTang);\n if (!this._raw) {\n if (this._normals[i].length() === 0) {\n prevNor = this._normals[i - 1];\n this._normals[i] = prevNor.clone();\n }\n else {\n this._normals[i].normalize();\n }\n }\n this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);\n if (!this._raw) {\n this._binormals[i].normalize();\n }\n }\n this._pointAtData.id = NaN;\n }\n // private function getFirstNonNullVector(index)\n // returns the first non null vector from index : curve[index + N].subtract(curve[index])\n _getFirstNonNullVector(index) {\n let i = 1;\n let nNVector = this._curve[index + i].subtract(this._curve[index]);\n while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {\n i++;\n nNVector = this._curve[index + i].subtract(this._curve[index]);\n }\n return nNVector;\n }\n // private function getLastNonNullVector(index)\n // returns the last non null vector from index : curve[index].subtract(curve[index - N])\n _getLastNonNullVector(index) {\n let i = 1;\n let nLVector = this._curve[index].subtract(this._curve[index - i]);\n while (nLVector.length() === 0 && index > i + 1) {\n i++;\n nLVector = this._curve[index].subtract(this._curve[index - i]);\n }\n return nLVector;\n }\n // private function normalVector(v0, vt, va) :\n // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane\n // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0\n _normalVector(vt, va) {\n let normal0;\n let tgl = vt.length();\n if (tgl === 0.0) {\n tgl = 1.0;\n }\n if (va === undefined || va === null) {\n let point;\n if (!Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, Epsilon)) {\n // search for a point in the plane\n point = new Vector3(0.0, -1.0, 0.0);\n }\n else if (!Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, Epsilon)) {\n point = new Vector3(1.0, 0.0, 0.0);\n }\n else if (!Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, Epsilon)) {\n point = new Vector3(0.0, 0.0, 1.0);\n }\n else {\n point = Vector3.Zero();\n }\n normal0 = Vector3.Cross(vt, point);\n }\n else {\n normal0 = Vector3.Cross(vt, va);\n Vector3.CrossToRef(normal0, vt, normal0);\n }\n normal0.normalize();\n return normal0;\n }\n /**\n * Updates the point at data for an interpolated point along this curve\n * @param position the position of the point along this curve, from 0.0 to 1.0\n * @param interpolateTNB\n * @interpolateTNB whether to compute the interpolated tangent, normal and binormal\n * @returns the (updated) point at data\n */\n _updatePointAtData(position, interpolateTNB = false) {\n // set an id for caching the result\n if (this._pointAtData.id === position) {\n if (!this._pointAtData.interpolateReady) {\n this._updateInterpolationMatrix();\n }\n return this._pointAtData;\n }\n else {\n this._pointAtData.id = position;\n }\n const curvePoints = this.getPoints();\n // clamp position between 0.0 and 1.0\n if (position <= 0.0) {\n return this._setPointAtData(0.0, 0.0, curvePoints[0], 0, interpolateTNB);\n }\n else if (position >= 1.0) {\n return this._setPointAtData(1.0, 1.0, curvePoints[curvePoints.length - 1], curvePoints.length - 1, interpolateTNB);\n }\n let previousPoint = curvePoints[0];\n let currentPoint;\n let currentLength = 0.0;\n const targetLength = position * this.length();\n for (let i = 1; i < curvePoints.length; i++) {\n currentPoint = curvePoints[i];\n const distance = Vector3.Distance(previousPoint, currentPoint);\n currentLength += distance;\n if (currentLength === targetLength) {\n return this._setPointAtData(position, 1.0, currentPoint, i, interpolateTNB);\n }\n else if (currentLength > targetLength) {\n const toLength = currentLength - targetLength;\n const diff = toLength / distance;\n const dir = previousPoint.subtract(currentPoint);\n const point = currentPoint.add(dir.scaleInPlace(diff));\n return this._setPointAtData(position, 1 - diff, point, i - 1, interpolateTNB);\n }\n previousPoint = currentPoint;\n }\n return this._pointAtData;\n }\n /**\n * Updates the point at data from the specified parameters\n * @param position where along the path the interpolated point is, from 0.0 to 1.0\n * @param subPosition\n * @param point the interpolated point\n * @param parentIndex the index of an existing curve point that is on, or else positionally the first behind, the interpolated point\n * @param interpolateTNB\n */\n _setPointAtData(position, subPosition, point, parentIndex, interpolateTNB) {\n this._pointAtData.point = point;\n this._pointAtData.position = position;\n this._pointAtData.subPosition = subPosition;\n this._pointAtData.previousPointArrayIndex = parentIndex;\n this._pointAtData.interpolateReady = interpolateTNB;\n if (interpolateTNB) {\n this._updateInterpolationMatrix();\n }\n return this._pointAtData;\n }\n /**\n * Updates the point at interpolation matrix for the tangents, normals and binormals\n */\n _updateInterpolationMatrix() {\n this._pointAtData.interpolationMatrix = Matrix.Identity();\n const parentIndex = this._pointAtData.previousPointArrayIndex;\n if (parentIndex !== this._tangents.length - 1) {\n const index = parentIndex + 1;\n const tangentFrom = this._tangents[parentIndex].clone();\n const normalFrom = this._normals[parentIndex].clone();\n const binormalFrom = this._binormals[parentIndex].clone();\n const tangentTo = this._tangents[index].clone();\n const normalTo = this._normals[index].clone();\n const binormalTo = this._binormals[index].clone();\n const quatFrom = Quaternion.RotationQuaternionFromAxis(normalFrom, binormalFrom, tangentFrom);\n const quatTo = Quaternion.RotationQuaternionFromAxis(normalTo, binormalTo, tangentTo);\n const quatAt = Quaternion.Slerp(quatFrom, quatTo, this._pointAtData.subPosition);\n quatAt.toRotationMatrix(this._pointAtData.interpolationMatrix);\n }\n }\n}\n/**\n * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.\n * A Curve3 is designed from a series of successive Vector3.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves\n */\nexport class Curve3 {\n /**\n * Returns a Curve3 object along a Quadratic Bezier curve : https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#quadratic-bezier-curve\n * @param v0 (Vector3) the origin point of the Quadratic Bezier\n * @param v1 (Vector3) the control point\n * @param v2 (Vector3) the end point of the Quadratic Bezier\n * @param nbPoints (integer) the wanted number of points in the curve\n * @returns the created Curve3\n */\n static CreateQuadraticBezier(v0, v1, v2, nbPoints) {\n nbPoints = nbPoints > 2 ? nbPoints : 3;\n const bez = new Array();\n const equation = (t, val0, val1, val2) => {\n const res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;\n return res;\n };\n for (let i = 0; i <= nbPoints; i++) {\n bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));\n }\n return new Curve3(bez);\n }\n /**\n * Returns a Curve3 object along a Cubic Bezier curve : https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#cubic-bezier-curve\n * @param v0 (Vector3) the origin point of the Cubic Bezier\n * @param v1 (Vector3) the first control point\n * @param v2 (Vector3) the second control point\n * @param v3 (Vector3) the end point of the Cubic Bezier\n * @param nbPoints (integer) the wanted number of points in the curve\n * @returns the created Curve3\n */\n static CreateCubicBezier(v0, v1, v2, v3, nbPoints) {\n nbPoints = nbPoints > 3 ? nbPoints : 4;\n const bez = new Array();\n const equation = (t, val0, val1, val2, val3) => {\n const res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;\n return res;\n };\n for (let i = 0; i <= nbPoints; i++) {\n bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));\n }\n return new Curve3(bez);\n }\n /**\n * Returns a Curve3 object along a Hermite Spline curve : https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#hermite-spline\n * @param p1 (Vector3) the origin point of the Hermite Spline\n * @param t1 (Vector3) the tangent vector at the origin point\n * @param p2 (Vector3) the end point of the Hermite Spline\n * @param t2 (Vector3) the tangent vector at the end point\n * @param nSeg (integer) the number of curve segments or nSeg + 1 points in the array\n * @returns the created Curve3\n */\n static CreateHermiteSpline(p1, t1, p2, t2, nSeg) {\n const hermite = new Array();\n const step = 1.0 / nSeg;\n for (let i = 0; i <= nSeg; i++) {\n hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));\n }\n return new Curve3(hermite);\n }\n /**\n * Returns a Curve3 object along a CatmullRom Spline curve :\n * @param points (array of Vector3) the points the spline must pass through. At least, four points required\n * @param nbPoints (integer) the wanted number of points between each curve control points\n * @param closed (boolean) optional with default false, when true forms a closed loop from the points\n * @returns the created Curve3\n */\n static CreateCatmullRomSpline(points, nbPoints, closed) {\n const catmullRom = new Array();\n const step = 1.0 / nbPoints;\n let amount = 0.0;\n if (closed) {\n const pointsCount = points.length;\n for (let i = 0; i < pointsCount; i++) {\n amount = 0;\n for (let c = 0; c < nbPoints; c++) {\n catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));\n amount += step;\n }\n }\n catmullRom.push(catmullRom[0]);\n }\n else {\n const totalPoints = new Array();\n totalPoints.push(points[0].clone());\n Array.prototype.push.apply(totalPoints, points);\n totalPoints.push(points[points.length - 1].clone());\n let i = 0;\n for (; i < totalPoints.length - 3; i++) {\n amount = 0;\n for (let c = 0; c < nbPoints; c++) {\n catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));\n amount += step;\n }\n }\n i--;\n catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));\n }\n return new Curve3(catmullRom);\n }\n /**\n * Returns a Curve3 object along an arc through three vector3 points:\n * The three points should not be colinear. When they are the Curve3 is empty.\n * @param first (Vector3) the first point the arc must pass through.\n * @param second (Vector3) the second point the arc must pass through.\n * @param third (Vector3) the third point the arc must pass through.\n * @param steps (number) the larger the number of steps the more detailed the arc.\n * @param closed (boolean) optional with default false, when true forms the chord from the first and third point\n * @param fullCircle Circle (boolean) optional with default false, when true forms the complete circle through the three points\n * @returns the created Curve3\n */\n static ArcThru3Points(first, second, third, steps = 32, closed = false, fullCircle = false) {\n const arc = new Array();\n const vec1 = second.subtract(first);\n const vec2 = third.subtract(second);\n const vec3 = first.subtract(third);\n const zAxis = Vector3.Cross(vec1, vec2);\n const len4 = zAxis.length();\n if (len4 < Math.pow(10, -8)) {\n return new Curve3(arc); // colinear points arc is empty\n }\n const len1_sq = vec1.lengthSquared();\n const len2_sq = vec2.lengthSquared();\n const len3_sq = vec3.lengthSquared();\n const len4_sq = zAxis.lengthSquared();\n const len1 = vec1.length();\n const len2 = vec2.length();\n const len3 = vec3.length();\n const radius = (0.5 * len1 * len2 * len3) / len4;\n const dot1 = Vector3.Dot(vec1, vec3);\n const dot2 = Vector3.Dot(vec1, vec2);\n const dot3 = Vector3.Dot(vec2, vec3);\n const a = (-0.5 * len2_sq * dot1) / len4_sq;\n const b = (-0.5 * len3_sq * dot2) / len4_sq;\n const c = (-0.5 * len1_sq * dot3) / len4_sq;\n const center = first.scale(a).add(second.scale(b)).add(third.scale(c));\n const radiusVec = first.subtract(center);\n const xAxis = radiusVec.normalize();\n const yAxis = Vector3.Cross(zAxis, xAxis).normalize();\n if (fullCircle) {\n const dStep = (2 * Math.PI) / steps;\n for (let theta = 0; theta <= 2 * Math.PI; theta += dStep) {\n arc.push(center.add(xAxis.scale(radius * Math.cos(theta)).add(yAxis.scale(radius * Math.sin(theta)))));\n }\n arc.push(first);\n }\n else {\n const dStep = 1 / steps;\n let theta = 0;\n let point = Vector3.Zero();\n do {\n point = center.add(xAxis.scale(radius * Math.cos(theta)).add(yAxis.scale(radius * Math.sin(theta))));\n arc.push(point);\n theta += dStep;\n } while (!point.equalsWithEpsilon(third, radius * dStep * 1.1));\n arc.push(third);\n if (closed) {\n arc.push(first);\n }\n }\n return new Curve3(arc);\n }\n /**\n * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.\n * A Curve3 is designed from a series of successive Vector3.\n * Tuto : https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#curve3-object\n * @param points points which make up the curve\n */\n constructor(points) {\n this._length = 0.0;\n this._points = points;\n this._length = this._computeLength(points);\n }\n /**\n * @returns the Curve3 stored array of successive Vector3\n */\n getPoints() {\n return this._points;\n }\n /**\n * @returns the computed length (float) of the curve.\n */\n length() {\n return this._length;\n }\n /**\n * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);\n * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.\n * curveA and curveB keep unchanged.\n * @param curve the curve to continue from this curve\n * @returns the newly constructed curve\n */\n continue(curve) {\n const lastPoint = this._points[this._points.length - 1];\n const continuedPoints = this._points.slice();\n const curvePoints = curve.getPoints();\n for (let i = 1; i < curvePoints.length; i++) {\n continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));\n }\n const continuedCurve = new Curve3(continuedPoints);\n return continuedCurve;\n }\n _computeLength(path) {\n let l = 0;\n for (let i = 1; i < path.length; i++) {\n l += path[i].subtract(path[i - 1]).length();\n }\n return l;\n }\n}\n//# sourceMappingURL=math.path.js.map","import { BezierCurve } from \"../Maths/math.path.js\";\n/**\n * Base class used for every default easing function.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions\n */\nexport class EasingFunction {\n constructor() {\n this._easingMode = EasingFunction.EASINGMODE_EASEIN;\n }\n /**\n * Sets the easing mode of the current function.\n * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)\n */\n setEasingMode(easingMode) {\n const n = Math.min(Math.max(easingMode, 0), 2);\n this._easingMode = n;\n }\n /**\n * Gets the current easing mode.\n * @returns the easing mode\n */\n getEasingMode() {\n return this._easingMode;\n }\n /**\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n easeInCore(gradient) {\n throw new Error(\"You must implement this method\");\n }\n /**\n * Given an input gradient between 0 and 1, this returns the corresponding value\n * of the easing function.\n * @param gradient Defines the value between 0 and 1 we want the easing value for\n * @returns the corresponding value on the curve defined by the easing function\n */\n ease(gradient) {\n switch (this._easingMode) {\n case EasingFunction.EASINGMODE_EASEIN:\n return this.easeInCore(gradient);\n case EasingFunction.EASINGMODE_EASEOUT:\n return 1 - this.easeInCore(1 - gradient);\n }\n if (gradient >= 0.5) {\n return (1 - this.easeInCore((1 - gradient) * 2)) * 0.5 + 0.5;\n }\n return this.easeInCore(gradient * 2) * 0.5;\n }\n}\n/**\n * Interpolation follows the mathematical formula associated with the easing function.\n */\nEasingFunction.EASINGMODE_EASEIN = 0;\n/**\n * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.\n */\nEasingFunction.EASINGMODE_EASEOUT = 1;\n/**\n * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.\n */\nEasingFunction.EASINGMODE_EASEINOUT = 2;\n/**\n * Easing function with a circle shape (see link below).\n * @see https://easings.net/#easeInCirc\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions\n */\nexport class CircleEase extends EasingFunction {\n /**\n * @internal\n */\n easeInCore(gradient) {\n gradient = Math.max(0, Math.min(1, gradient));\n return 1.0 - Math.sqrt(1.0 - gradient * gradient);\n }\n}\n/**\n * Easing function with a ease back shape (see link below).\n * @see https://easings.net/#easeInBack\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions\n */\nexport class BackEase extends EasingFunction {\n /**\n * Instantiates a back ease easing\n * @see https://easings.net/#easeInBack\n * @param amplitude Defines the amplitude of the function\n */\n constructor(\n /** Defines the amplitude of the function */\n amplitude = 1) {\n super();\n this.amplitude = amplitude;\n }\n /**\n * @internal\n */\n easeInCore(gradient) {\n const num = Math.max(0, this.amplitude);\n return Math.pow(gradient, 3.0) - gradient * num * Math.sin(3.1415926535897931 * gradient);\n }\n}\n/**\n * Easing function with a bouncing shape (see link below).\n * @see https://easings.net/#easeInBounce\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions\n */\nexport class BounceEase extends EasingFunction {\n /**\n * Instantiates a bounce easing\n * @see https://easings.net/#easeInBounce\n * @param bounces Defines the number of bounces\n * @param bounciness Defines the amplitude of the bounce\n */\n constructor(\n /** Defines the number of bounces */\n bounces = 3, \n /** Defines the amplitude of the bounce */\n bounciness = 2) {\n super();\n this.bounces = bounces;\n this.bounciness = bounciness;\n }\n /**\n * @internal\n */\n easeInCore(gradient) {\n const y = Math.max(0.0, this.bounces);\n let bounciness = this.bounciness;\n if (bounciness <= 1.0) {\n bounciness = 1.001;\n }\n const num9 = Math.pow(bounciness, y);\n const num5 = 1.0 - bounciness;\n const num4 = (1.0 - num9) / num5 + num9 * 0.5;\n const num15 = gradient * num4;\n const num65 = Math.log(-num15 * (1.0 - bounciness) + 1.0) / Math.log(bounciness);\n const num3 = Math.floor(num65);\n const num13 = num3 + 1.0;\n const num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);\n const num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);\n const num7 = (num8 + num12) * 0.5;\n const num6 = gradient - num7;\n const num2 = num7 - num8;\n return (-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2) * (num6 + num2);\n }\n}\n/**\n * Easing function with a power of 3 shape (see link below).\n * @see https://easings.net/#easeInCubic\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions\n */\nexport class CubicEase extends EasingFunction {\n /**\n * @internal\n */\n easeInCore(gradient) {\n return gradient * gradient * gradient;\n }\n}\n/**\n * Easing function with an elastic shape (see link below).\n * @see https://easings.net/#easeInElastic\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions\n */\nexport class ElasticEase extends EasingFunction {\n /**\n * Instantiates an elastic easing function\n * @see https://easings.net/#easeInElastic\n * @param oscillations Defines the number of oscillations\n * @param springiness Defines the amplitude of the oscillations\n */\n constructor(\n /** Defines the number of oscillations*/\n oscillations = 3, \n /** Defines the amplitude of the oscillations*/\n springiness = 3) {\n super();\n this.oscillations = oscillations;\n this.springiness = springiness;\n }\n /**\n * @internal\n */\n easeInCore(gradient) {\n let num2;\n const num3 = Math.max(0.0, this.oscillations);\n const num = Math.max(0.0, this.springiness);\n if (num == 0) {\n num2 = gradient;\n }\n else {\n num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);\n }\n return num2 * Math.sin((6.2831853071795862 * num3 + 1.5707963267948966) * gradient);\n }\n}\n/**\n * Easing function with an exponential shape (see link below).\n * @see https://easings.net/#easeInExpo\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions\n */\nexport class ExponentialEase extends EasingFunction {\n /**\n * Instantiates an exponential easing function\n * @see https://easings.net/#easeInExpo\n * @param exponent Defines the exponent of the function\n */\n constructor(\n /** Defines the exponent of the function */\n exponent = 2) {\n super();\n this.exponent = exponent;\n }\n /**\n * @internal\n */\n easeInCore(gradient) {\n if (this.exponent <= 0) {\n return gradient;\n }\n return (Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0);\n }\n}\n/**\n * Easing function with a power shape (see link below).\n * @see https://easings.net/#easeInQuad\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions\n */\nexport class PowerEase extends EasingFunction {\n /**\n * Instantiates an power base easing function\n * @see https://easings.net/#easeInQuad\n * @param power Defines the power of the function\n */\n constructor(\n /** Defines the power of the function */\n power = 2) {\n super();\n this.power = power;\n }\n /**\n * @internal\n */\n easeInCore(gradient) {\n const y = Math.max(0.0, this.power);\n return Math.pow(gradient, y);\n }\n}\n/**\n * Easing function with a power of 2 shape (see link below).\n * @see https://easings.net/#easeInQuad\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions\n */\nexport class QuadraticEase extends EasingFunction {\n /**\n * @internal\n */\n easeInCore(gradient) {\n return gradient * gradient;\n }\n}\n/**\n * Easing function with a power of 4 shape (see link below).\n * @see https://easings.net/#easeInQuart\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions\n */\nexport class QuarticEase extends EasingFunction {\n /**\n * @internal\n */\n easeInCore(gradient) {\n return gradient * gradient * gradient * gradient;\n }\n}\n/**\n * Easing function with a power of 5 shape (see link below).\n * @see https://easings.net/#easeInQuint\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions\n */\nexport class QuinticEase extends EasingFunction {\n /**\n * @internal\n */\n easeInCore(gradient) {\n return gradient * gradient * gradient * gradient * gradient;\n }\n}\n/**\n * Easing function with a sin shape (see link below).\n * @see https://easings.net/#easeInSine\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions\n */\nexport class SineEase extends EasingFunction {\n /**\n * @internal\n */\n easeInCore(gradient) {\n return 1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient));\n }\n}\n/**\n * Easing function with a bezier shape (see link below).\n * @see http://cubic-bezier.com/#.17,.67,.83,.67\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions\n */\nexport class BezierCurveEase extends EasingFunction {\n /**\n * Instantiates a bezier function\n * @see http://cubic-bezier.com/#.17,.67,.83,.67\n * @param x1 Defines the x component of the start tangent in the bezier curve\n * @param y1 Defines the y component of the start tangent in the bezier curve\n * @param x2 Defines the x component of the end tangent in the bezier curve\n * @param y2 Defines the y component of the end tangent in the bezier curve\n */\n constructor(\n /** Defines the x component of the start tangent in the bezier curve */\n x1 = 0, \n /** Defines the y component of the start tangent in the bezier curve */\n y1 = 0, \n /** Defines the x component of the end tangent in the bezier curve */\n x2 = 1, \n /** Defines the y component of the end tangent in the bezier curve */\n y2 = 1) {\n super();\n this.x1 = x1;\n this.y1 = y1;\n this.x2 = x2;\n this.y2 = y2;\n }\n /**\n * @internal\n */\n easeInCore(gradient) {\n return BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);\n }\n}\n//# sourceMappingURL=easing.js.map","/**\n * Composed of a frame, and an action function\n */\nexport class AnimationEvent {\n /**\n * Initializes the animation event\n * @param frame The frame for which the event is triggered\n * @param action The event to perform when triggered\n * @param onlyOnce Specifies if the event should be triggered only once\n */\n constructor(\n /** The frame for which the event is triggered **/\n frame, \n /** The event to perform when triggered **/\n action, \n /** Specifies if the event should be triggered only once**/\n onlyOnce) {\n this.frame = frame;\n this.action = action;\n this.onlyOnce = onlyOnce;\n /**\n * Specifies if the animation event is done\n */\n this.isDone = false;\n }\n /** @internal */\n _clone() {\n return new AnimationEvent(this.frame, this.action, this.onlyOnce);\n }\n}\n//# sourceMappingURL=animationEvent.js.map","import { Animation } from \"./animation.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { Tags } from \"../Misc/tags.js\";\n/**\n * This class defines the direct association between an animation and a target\n */\nexport class TargetedAnimation {\n /**\n * Returns the string \"TargetedAnimation\"\n * @returns \"TargetedAnimation\"\n */\n getClassName() {\n return \"TargetedAnimation\";\n }\n /**\n * Serialize the object\n * @returns the JSON object representing the current entity\n */\n serialize() {\n const serializationObject = {};\n serializationObject.animation = this.animation.serialize();\n serializationObject.targetId = this.target.id;\n return serializationObject;\n }\n}\n/**\n * Use this class to create coordinated animations on multiple targets\n */\nexport class AnimationGroup {\n /**\n * Gets the first frame\n */\n get from() {\n return this._from;\n }\n /**\n * Gets the last frame\n */\n get to() {\n return this._to;\n }\n /**\n * Define if the animations are started\n */\n get isStarted() {\n return this._isStarted;\n }\n /**\n * Gets a value indicating that the current group is playing\n */\n get isPlaying() {\n return this._isStarted && !this._isPaused;\n }\n /**\n * Gets or sets the speed ratio to use for all animations\n */\n get speedRatio() {\n return this._speedRatio;\n }\n /**\n * Gets or sets the speed ratio to use for all animations\n */\n set speedRatio(value) {\n if (this._speedRatio === value) {\n return;\n }\n this._speedRatio = value;\n for (let index = 0; index < this._animatables.length; index++) {\n const animatable = this._animatables[index];\n animatable.speedRatio = this._speedRatio;\n }\n }\n /**\n * Gets or sets if all animations should loop or not\n */\n get loopAnimation() {\n return this._loopAnimation;\n }\n set loopAnimation(value) {\n if (this._loopAnimation === value) {\n return;\n }\n this._loopAnimation = value;\n for (let index = 0; index < this._animatables.length; index++) {\n const animatable = this._animatables[index];\n animatable.loopAnimation = this._loopAnimation;\n }\n }\n /**\n * Gets or sets if all animations should be evaluated additively\n */\n get isAdditive() {\n return this._isAdditive;\n }\n set isAdditive(value) {\n if (this._isAdditive === value) {\n return;\n }\n this._isAdditive = value;\n for (let index = 0; index < this._animatables.length; index++) {\n const animatable = this._animatables[index];\n animatable.isAdditive = this._isAdditive;\n }\n }\n /**\n * Gets the targeted animations for this animation group\n */\n get targetedAnimations() {\n return this._targetedAnimations;\n }\n /**\n * returning the list of animatables controlled by this animation group.\n */\n get animatables() {\n return this._animatables;\n }\n /**\n * Gets the list of target animations\n */\n get children() {\n return this._targetedAnimations;\n }\n /**\n * Instantiates a new Animation Group.\n * This helps managing several animations at once.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/groupAnimations\n * @param name Defines the name of the group\n * @param scene Defines the scene the group belongs to\n */\n constructor(\n /** The name of the animation group */\n name, scene = null) {\n this.name = name;\n this._targetedAnimations = new Array();\n this._animatables = new Array();\n this._from = Number.MAX_VALUE;\n this._to = -Number.MAX_VALUE;\n this._speedRatio = 1;\n this._loopAnimation = false;\n this._isAdditive = false;\n /** @internal */\n this._parentContainer = null;\n /**\n * This observable will notify when one animation have ended\n */\n this.onAnimationEndObservable = new Observable();\n /**\n * Observer raised when one animation loops\n */\n this.onAnimationLoopObservable = new Observable();\n /**\n * Observer raised when all animations have looped\n */\n this.onAnimationGroupLoopObservable = new Observable();\n /**\n * This observable will notify when all animations have ended.\n */\n this.onAnimationGroupEndObservable = new Observable();\n /**\n * This observable will notify when all animations have paused.\n */\n this.onAnimationGroupPauseObservable = new Observable();\n /**\n * This observable will notify when all animations are playing.\n */\n this.onAnimationGroupPlayObservable = new Observable();\n /**\n * Gets or sets an object used to store user defined information for the node\n */\n this.metadata = null;\n this._animationLoopFlags = [];\n this._scene = scene || EngineStore.LastCreatedScene;\n this.uniqueId = this._scene.getUniqueId();\n this._scene.addAnimationGroup(this);\n }\n /**\n * Add an animation (with its target) in the group\n * @param animation defines the animation we want to add\n * @param target defines the target of the animation\n * @returns the TargetedAnimation object\n */\n addTargetedAnimation(animation, target) {\n const targetedAnimation = new TargetedAnimation();\n targetedAnimation.animation = animation;\n targetedAnimation.target = target;\n const keys = animation.getKeys();\n if (this._from > keys[0].frame) {\n this._from = keys[0].frame;\n }\n if (this._to < keys[keys.length - 1].frame) {\n this._to = keys[keys.length - 1].frame;\n }\n this._targetedAnimations.push(targetedAnimation);\n return targetedAnimation;\n }\n /**\n * Remove an animation from the group\n * @param animation defines the animation we want to remove\n */\n removeTargetedAnimation(animation) {\n for (let index = this._targetedAnimations.length - 1; index > -1; index--) {\n const targetedAnimation = this._targetedAnimations[index];\n if (targetedAnimation.animation === animation) {\n this._targetedAnimations.splice(index, 1);\n }\n }\n }\n /**\n * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame\n * It can add constant keys at begin or end\n * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)\n * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)\n * @returns the animation group\n */\n normalize(beginFrame = null, endFrame = null) {\n if (beginFrame == null) {\n beginFrame = this._from;\n }\n if (endFrame == null) {\n endFrame = this._to;\n }\n for (let index = 0; index < this._targetedAnimations.length; index++) {\n const targetedAnimation = this._targetedAnimations[index];\n const keys = targetedAnimation.animation.getKeys();\n const startKey = keys[0];\n const endKey = keys[keys.length - 1];\n if (startKey.frame > beginFrame) {\n const newKey = {\n frame: beginFrame,\n value: startKey.value,\n inTangent: startKey.inTangent,\n outTangent: startKey.outTangent,\n interpolation: startKey.interpolation,\n };\n keys.splice(0, 0, newKey);\n }\n if (endKey.frame < endFrame) {\n const newKey = {\n frame: endFrame,\n value: endKey.value,\n inTangent: endKey.inTangent,\n outTangent: endKey.outTangent,\n interpolation: endKey.interpolation,\n };\n keys.push(newKey);\n }\n }\n this._from = beginFrame;\n this._to = endFrame;\n return this;\n }\n _processLoop(animatable, targetedAnimation, index) {\n animatable.onAnimationLoop = () => {\n this.onAnimationLoopObservable.notifyObservers(targetedAnimation);\n if (this._animationLoopFlags[index]) {\n return;\n }\n this._animationLoopFlags[index] = true;\n this._animationLoopCount++;\n if (this._animationLoopCount === this._targetedAnimations.length) {\n this.onAnimationGroupLoopObservable.notifyObservers(this);\n this._animationLoopCount = 0;\n this._animationLoopFlags.length = 0;\n }\n };\n }\n /**\n * Start all animations on given targets\n * @param loop defines if animations must loop\n * @param speedRatio defines the ratio to apply to animation speed (1 by default)\n * @param from defines the from key (optional)\n * @param to defines the to key (optional)\n * @param isAdditive defines the additive state for the resulting animatables (optional)\n * @returns the current animation group\n */\n start(loop = false, speedRatio = 1, from, to, isAdditive) {\n if (this._isStarted || this._targetedAnimations.length === 0) {\n return this;\n }\n this._loopAnimation = loop;\n this._animationLoopCount = 0;\n this._animationLoopFlags.length = 0;\n for (let index = 0; index < this._targetedAnimations.length; index++) {\n const targetedAnimation = this._targetedAnimations[index];\n const animatable = this._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this._from, to !== undefined ? to : this._to, loop, speedRatio, undefined, undefined, isAdditive !== undefined ? isAdditive : this._isAdditive);\n animatable.onAnimationEnd = () => {\n this.onAnimationEndObservable.notifyObservers(targetedAnimation);\n this._checkAnimationGroupEnded(animatable);\n };\n this._processLoop(animatable, targetedAnimation, index);\n this._animatables.push(animatable);\n }\n this._speedRatio = speedRatio;\n this._isStarted = true;\n this._isPaused = false;\n this.onAnimationGroupPlayObservable.notifyObservers(this);\n return this;\n }\n /**\n * Pause all animations\n * @returns the animation group\n */\n pause() {\n if (!this._isStarted) {\n return this;\n }\n this._isPaused = true;\n for (let index = 0; index < this._animatables.length; index++) {\n const animatable = this._animatables[index];\n animatable.pause();\n }\n this.onAnimationGroupPauseObservable.notifyObservers(this);\n return this;\n }\n /**\n * Play all animations to initial state\n * This function will start() the animations if they were not started or will restart() them if they were paused\n * @param loop defines if animations must loop\n * @returns the animation group\n */\n play(loop) {\n // only if all animatables are ready and exist\n if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {\n if (loop !== undefined) {\n this.loopAnimation = loop;\n }\n this.restart();\n }\n else {\n this.stop();\n this.start(loop, this._speedRatio);\n }\n this._isPaused = false;\n return this;\n }\n /**\n * Reset all animations to initial state\n * @returns the animation group\n */\n reset() {\n if (!this._isStarted) {\n this.play();\n this.goToFrame(0);\n this.stop();\n return this;\n }\n for (let index = 0; index < this._animatables.length; index++) {\n const animatable = this._animatables[index];\n animatable.reset();\n }\n return this;\n }\n /**\n * Restart animations from key 0\n * @returns the animation group\n */\n restart() {\n if (!this._isStarted) {\n return this;\n }\n for (let index = 0; index < this._animatables.length; index++) {\n const animatable = this._animatables[index];\n animatable.restart();\n }\n this.onAnimationGroupPlayObservable.notifyObservers(this);\n return this;\n }\n /**\n * Stop all animations\n * @returns the animation group\n */\n stop() {\n if (!this._isStarted) {\n return this;\n }\n const list = this._animatables.slice();\n for (let index = 0; index < list.length; index++) {\n list[index].stop(undefined, undefined, true);\n }\n // We will take care of removing all stopped animatables\n let curIndex = 0;\n for (let index = 0; index < this._scene._activeAnimatables.length; index++) {\n const animatable = this._scene._activeAnimatables[index];\n if (animatable._runtimeAnimations.length > 0) {\n this._scene._activeAnimatables[curIndex++] = animatable;\n }\n }\n this._scene._activeAnimatables.length = curIndex;\n this._isStarted = false;\n return this;\n }\n /**\n * Set animation weight for all animatables\n * @param weight defines the weight to use\n * @returns the animationGroup\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#animation-weights\n */\n setWeightForAllAnimatables(weight) {\n for (let index = 0; index < this._animatables.length; index++) {\n const animatable = this._animatables[index];\n animatable.weight = weight;\n }\n return this;\n }\n /**\n * Synchronize and normalize all animatables with a source animatable\n * @param root defines the root animatable to synchronize with (null to stop synchronizing)\n * @returns the animationGroup\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#animation-weights\n */\n syncAllAnimationsWith(root) {\n for (let index = 0; index < this._animatables.length; index++) {\n const animatable = this._animatables[index];\n animatable.syncWith(root);\n }\n return this;\n }\n /**\n * Goes to a specific frame in this animation group\n * @param frame the frame number to go to\n * @returns the animationGroup\n */\n goToFrame(frame) {\n if (!this._isStarted) {\n return this;\n }\n for (let index = 0; index < this._animatables.length; index++) {\n const animatable = this._animatables[index];\n animatable.goToFrame(frame);\n }\n return this;\n }\n /**\n * Dispose all associated resources\n */\n dispose() {\n this._targetedAnimations.length = 0;\n this._animatables.length = 0;\n // Remove from scene\n const index = this._scene.animationGroups.indexOf(this);\n if (index > -1) {\n this._scene.animationGroups.splice(index, 1);\n }\n if (this._parentContainer) {\n const index = this._parentContainer.animationGroups.indexOf(this);\n if (index > -1) {\n this._parentContainer.animationGroups.splice(index, 1);\n }\n this._parentContainer = null;\n }\n this.onAnimationEndObservable.clear();\n this.onAnimationGroupEndObservable.clear();\n this.onAnimationGroupPauseObservable.clear();\n this.onAnimationGroupPlayObservable.clear();\n this.onAnimationLoopObservable.clear();\n this.onAnimationGroupLoopObservable.clear();\n }\n _checkAnimationGroupEnded(animatable) {\n // animatable should be taken out of the array\n const idx = this._animatables.indexOf(animatable);\n if (idx > -1) {\n this._animatables.splice(idx, 1);\n }\n // all animatables were removed? animation group ended!\n if (this._animatables.length === 0) {\n this._isStarted = false;\n this.onAnimationGroupEndObservable.notifyObservers(this);\n }\n }\n /**\n * Clone the current animation group and returns a copy\n * @param newName defines the name of the new group\n * @param targetConverter defines an optional function used to convert current animation targets to new ones\n * @param cloneAnimations defines if the animations should be cloned or referenced\n * @returns the new animation group\n */\n clone(newName, targetConverter, cloneAnimations = false) {\n const newGroup = new AnimationGroup(newName || this.name, this._scene);\n for (const targetAnimation of this._targetedAnimations) {\n newGroup.addTargetedAnimation(cloneAnimations ? targetAnimation.animation.clone() : targetAnimation.animation, targetConverter ? targetConverter(targetAnimation.target) : targetAnimation.target);\n }\n return newGroup;\n }\n /**\n * Serializes the animationGroup to an object\n * @returns Serialized object\n */\n serialize() {\n const serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.from = this.from;\n serializationObject.to = this.to;\n serializationObject.targetedAnimations = [];\n for (let targetedAnimationIndex = 0; targetedAnimationIndex < this.targetedAnimations.length; targetedAnimationIndex++) {\n const targetedAnimation = this.targetedAnimations[targetedAnimationIndex];\n serializationObject.targetedAnimations[targetedAnimationIndex] = targetedAnimation.serialize();\n }\n if (Tags && Tags.HasTags(this)) {\n serializationObject.tags = Tags.GetTags(this);\n }\n // Metadata\n if (this.metadata) {\n serializationObject.metadata = this.metadata;\n }\n return serializationObject;\n }\n // Statics\n /**\n * Returns a new AnimationGroup object parsed from the source provided.\n * @param parsedAnimationGroup defines the source\n * @param scene defines the scene that will receive the animationGroup\n * @returns a new AnimationGroup\n */\n static Parse(parsedAnimationGroup, scene) {\n const animationGroup = new AnimationGroup(parsedAnimationGroup.name, scene);\n for (let i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {\n const targetedAnimation = parsedAnimationGroup.targetedAnimations[i];\n const animation = Animation.Parse(targetedAnimation.animation);\n const id = targetedAnimation.targetId;\n if (targetedAnimation.animation.property === \"influence\") {\n // morph target animation\n const morphTarget = scene.getMorphTargetById(id);\n if (morphTarget) {\n animationGroup.addTargetedAnimation(animation, morphTarget);\n }\n }\n else {\n const targetNode = scene.getNodeById(id);\n if (targetNode != null) {\n animationGroup.addTargetedAnimation(animation, targetNode);\n }\n }\n }\n if (parsedAnimationGroup.from !== null && parsedAnimationGroup.to !== null) {\n animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);\n }\n if (Tags) {\n Tags.AddTagsTo(animationGroup, parsedAnimationGroup.tags);\n }\n if (parsedAnimationGroup.metadata !== undefined) {\n animationGroup.metadata = parsedAnimationGroup.metadata;\n }\n return animationGroup;\n }\n /**\n * Convert the keyframes for all animations belonging to the group to be relative to a given reference frame.\n * @param sourceAnimationGroup defines the AnimationGroup containing animations to convert\n * @param referenceFrame defines the frame that keyframes in the range will be relative to\n * @param range defines the name of the AnimationRange belonging to the animations in the group to convert\n * @param cloneOriginal defines whether or not to clone the group and convert the clone or convert the original group (default is false)\n * @param clonedName defines the name of the resulting cloned AnimationGroup if cloneOriginal is true\n * @returns a new AnimationGroup if cloneOriginal is true or the original AnimationGroup if cloneOriginal is false\n */\n static MakeAnimationAdditive(sourceAnimationGroup, referenceFrame = 0, range, cloneOriginal = false, clonedName) {\n let animationGroup = sourceAnimationGroup;\n if (cloneOriginal) {\n animationGroup = sourceAnimationGroup.clone(clonedName || animationGroup.name);\n }\n const targetedAnimations = animationGroup.targetedAnimations;\n for (let index = 0; index < targetedAnimations.length; index++) {\n const targetedAnimation = targetedAnimations[index];\n Animation.MakeAnimationAdditive(targetedAnimation.animation, referenceFrame, range);\n }\n animationGroup.isAdditive = true;\n return animationGroup;\n }\n /**\n * Returns the string \"AnimationGroup\"\n * @returns \"AnimationGroup\"\n */\n getClassName() {\n return \"AnimationGroup\";\n }\n /**\n * Creates a detailed string about the object\n * @param fullDetails defines if the output string will support multiple levels of logging within scene loading\n * @returns a string representing the object\n */\n toString(fullDetails) {\n let ret = \"Name: \" + this.name;\n ret += \", type: \" + this.getClassName();\n if (fullDetails) {\n ret += \", from: \" + this._from;\n ret += \", to: \" + this._to;\n ret += \", isStarted: \" + this._isStarted;\n ret += \", speedRatio: \" + this._speedRatio;\n ret += \", targetedAnimations length: \" + this._targetedAnimations.length;\n ret += \", animatables length: \" + this._animatables;\n }\n return ret;\n }\n}\n//# sourceMappingURL=animationGroup.js.map","import { Matrix, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { AbstractMesh } from \"../Meshes/abstractMesh.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { DeepCopier } from \"../Misc/deepCopier.js\";\nimport { TransformNode } from \"./transformNode.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Tools } from \"../Misc/tools.js\";\nMesh._instancedMeshFactory = (name, mesh) => {\n const instance = new InstancedMesh(name, mesh);\n if (mesh.instancedBuffers) {\n instance.instancedBuffers = {};\n for (const key in mesh.instancedBuffers) {\n instance.instancedBuffers[key] = mesh.instancedBuffers[key];\n }\n }\n return instance;\n};\n/**\n * Creates an instance based on a source mesh.\n */\nexport class InstancedMesh extends AbstractMesh {\n /**\n * Creates a new InstancedMesh object from the mesh source.\n * @param name defines the name of the instance\n * @param source the mesh to create the instance from\n */\n constructor(name, source) {\n super(name, source.getScene());\n /** @internal */\n this._indexInSourceMeshInstanceArray = -1;\n /** @internal */\n this._distanceToCamera = 0;\n source.addInstance(this);\n this._sourceMesh = source;\n this._unIndexed = source._unIndexed;\n this.position.copyFrom(source.position);\n this.rotation.copyFrom(source.rotation);\n this.scaling.copyFrom(source.scaling);\n if (source.rotationQuaternion) {\n this.rotationQuaternion = source.rotationQuaternion.clone();\n }\n this.animations = source.animations.slice();\n for (const range of source.getAnimationRanges()) {\n if (range != null) {\n this.createAnimationRange(range.name, range.from, range.to);\n }\n }\n this.infiniteDistance = source.infiniteDistance;\n this.setPivotMatrix(source.getPivotMatrix());\n this.refreshBoundingInfo(true, true);\n this._syncSubMeshes();\n }\n /**\n * Returns the string \"InstancedMesh\".\n */\n getClassName() {\n return \"InstancedMesh\";\n }\n /** Gets the list of lights affecting that mesh */\n get lightSources() {\n return this._sourceMesh._lightSources;\n }\n _resyncLightSources() {\n // Do nothing as all the work will be done by source mesh\n }\n _resyncLightSource() {\n // Do nothing as all the work will be done by source mesh\n }\n _removeLightSource() {\n // Do nothing as all the work will be done by source mesh\n }\n // Methods\n /**\n * If the source mesh receives shadows\n */\n get receiveShadows() {\n return this._sourceMesh.receiveShadows;\n }\n set receiveShadows(_value) {\n var _a;\n if (((_a = this._sourceMesh) === null || _a === void 0 ? void 0 : _a.receiveShadows) !== _value) {\n Tools.Warn(\"Setting receiveShadows on an instanced mesh has no effect\");\n }\n }\n /**\n * The material of the source mesh\n */\n get material() {\n return this._sourceMesh.material;\n }\n set material(_value) {\n var _a;\n if (((_a = this._sourceMesh) === null || _a === void 0 ? void 0 : _a.material) !== _value) {\n Tools.Warn(\"Setting material on an instanced mesh has no effect\");\n }\n }\n /**\n * Visibility of the source mesh\n */\n get visibility() {\n return this._sourceMesh.visibility;\n }\n set visibility(_value) {\n var _a;\n if (((_a = this._sourceMesh) === null || _a === void 0 ? void 0 : _a.visibility) !== _value) {\n Tools.Warn(\"Setting visibility on an instanced mesh has no effect\");\n }\n }\n /**\n * Skeleton of the source mesh\n */\n get skeleton() {\n return this._sourceMesh.skeleton;\n }\n set skeleton(_value) {\n var _a;\n if (((_a = this._sourceMesh) === null || _a === void 0 ? void 0 : _a.skeleton) !== _value) {\n Tools.Warn(\"Setting skeleton on an instanced mesh has no effect\");\n }\n }\n /**\n * Rendering ground id of the source mesh\n */\n get renderingGroupId() {\n return this._sourceMesh.renderingGroupId;\n }\n set renderingGroupId(value) {\n if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {\n return;\n }\n //no-op with warning\n Logger.Warn(\"Note - setting renderingGroupId of an instanced mesh has no effect on the scene\");\n }\n /**\n * Returns the total number of vertices (integer).\n */\n getTotalVertices() {\n return this._sourceMesh ? this._sourceMesh.getTotalVertices() : 0;\n }\n /**\n * Returns a positive integer : the total number of indices in this mesh geometry.\n * @returns the number of indices or zero if the mesh has no geometry.\n */\n getTotalIndices() {\n return this._sourceMesh.getTotalIndices();\n }\n /**\n * The source mesh of the instance\n */\n get sourceMesh() {\n return this._sourceMesh;\n }\n /**\n * Creates a new InstancedMesh object from the mesh model.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/copies/instances\n * @param name defines the name of the new instance\n * @returns a new InstancedMesh\n */\n createInstance(name) {\n return this._sourceMesh.createInstance(name);\n }\n /**\n * Is this node ready to be used/rendered\n * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)\n * @returns {boolean} is it ready\n */\n isReady(completeCheck = false) {\n return this._sourceMesh.isReady(completeCheck, true);\n }\n /**\n * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.\n * @param kind kind of verticies to retrieve (eg. positions, normals, uvs, etc.)\n * @param copyWhenShared If true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.\n * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is\n * @returns a float array or a Float32Array of the requested kind of data : positions, normals, uvs, etc.\n */\n getVerticesData(kind, copyWhenShared, forceCopy) {\n return this._sourceMesh.getVerticesData(kind, copyWhenShared, forceCopy);\n }\n /**\n * Sets the vertex data of the mesh geometry for the requested `kind`.\n * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.\n * The `data` are either a numeric array either a Float32Array.\n * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initially none) or updater.\n * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).\n * Note that a new underlying VertexBuffer object is created each call.\n * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.\n *\n * Possible `kind` values :\n * - VertexBuffer.PositionKind\n * - VertexBuffer.UVKind\n * - VertexBuffer.UV2Kind\n * - VertexBuffer.UV3Kind\n * - VertexBuffer.UV4Kind\n * - VertexBuffer.UV5Kind\n * - VertexBuffer.UV6Kind\n * - VertexBuffer.ColorKind\n * - VertexBuffer.MatricesIndicesKind\n * - VertexBuffer.MatricesIndicesExtraKind\n * - VertexBuffer.MatricesWeightsKind\n * - VertexBuffer.MatricesWeightsExtraKind\n *\n * Returns the Mesh.\n * @param kind\n * @param data\n * @param updatable\n * @param stride\n */\n setVerticesData(kind, data, updatable, stride) {\n if (this.sourceMesh) {\n this.sourceMesh.setVerticesData(kind, data, updatable, stride);\n }\n return this.sourceMesh;\n }\n /**\n * Updates the existing vertex data of the mesh geometry for the requested `kind`.\n * If the mesh has no geometry, it is simply returned as it is.\n * The `data` are either a numeric array either a Float32Array.\n * No new underlying VertexBuffer object is created.\n * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.\n * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.\n *\n * Possible `kind` values :\n * - VertexBuffer.PositionKind\n * - VertexBuffer.UVKind\n * - VertexBuffer.UV2Kind\n * - VertexBuffer.UV3Kind\n * - VertexBuffer.UV4Kind\n * - VertexBuffer.UV5Kind\n * - VertexBuffer.UV6Kind\n * - VertexBuffer.ColorKind\n * - VertexBuffer.MatricesIndicesKind\n * - VertexBuffer.MatricesIndicesExtraKind\n * - VertexBuffer.MatricesWeightsKind\n * - VertexBuffer.MatricesWeightsExtraKind\n *\n * Returns the Mesh.\n * @param kind\n * @param data\n * @param updateExtends\n * @param makeItUnique\n */\n updateVerticesData(kind, data, updateExtends, makeItUnique) {\n if (this.sourceMesh) {\n this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);\n }\n return this.sourceMesh;\n }\n /**\n * Sets the mesh indices.\n * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).\n * If the mesh has no geometry, a new Geometry object is created and set to the mesh.\n * This method creates a new index buffer each call.\n * Returns the Mesh.\n * @param indices\n * @param totalVertices\n */\n setIndices(indices, totalVertices = null) {\n if (this.sourceMesh) {\n this.sourceMesh.setIndices(indices, totalVertices);\n }\n return this.sourceMesh;\n }\n /**\n * Boolean : True if the mesh owns the requested kind of data.\n * @param kind\n */\n isVerticesDataPresent(kind) {\n return this._sourceMesh.isVerticesDataPresent(kind);\n }\n /**\n * Returns an array of indices (IndicesArray).\n */\n getIndices() {\n return this._sourceMesh.getIndices();\n }\n get _positions() {\n return this._sourceMesh._positions;\n }\n /**\n * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.\n * This means the mesh underlying bounding box and sphere are recomputed.\n * @param applySkeleton defines whether to apply the skeleton before computing the bounding info\n * @param applyMorph defines whether to apply the morph target before computing the bounding info\n * @returns the current mesh\n */\n refreshBoundingInfo(applySkeleton = false, applyMorph = false) {\n if (this.hasBoundingInfo && this.getBoundingInfo().isLocked) {\n return this;\n }\n const bias = this._sourceMesh.geometry ? this._sourceMesh.geometry.boundingBias : null;\n this._refreshBoundingInfo(this._sourceMesh._getPositionData(applySkeleton, applyMorph), bias);\n return this;\n }\n /** @internal */\n _preActivate() {\n if (this._currentLOD) {\n this._currentLOD._preActivate();\n }\n return this;\n }\n /**\n * @internal\n */\n _activate(renderId, intermediateRendering) {\n super._activate(renderId, intermediateRendering);\n if (!this._sourceMesh.subMeshes) {\n Logger.Warn(\"Instances should only be created for meshes with geometry.\");\n }\n if (this._currentLOD) {\n const differentSign = this._currentLOD._getWorldMatrixDeterminant() >= 0 !== this._getWorldMatrixDeterminant() >= 0;\n if (differentSign) {\n this._internalAbstractMeshDataInfo._actAsRegularMesh = true;\n return true;\n }\n this._internalAbstractMeshDataInfo._actAsRegularMesh = false;\n this._currentLOD._registerInstanceForRenderId(this, renderId);\n if (intermediateRendering) {\n if (!this._currentLOD._internalAbstractMeshDataInfo._isActiveIntermediate) {\n this._currentLOD._internalAbstractMeshDataInfo._onlyForInstancesIntermediate = true;\n return true;\n }\n }\n else {\n if (!this._currentLOD._internalAbstractMeshDataInfo._isActive) {\n this._currentLOD._internalAbstractMeshDataInfo._onlyForInstances = true;\n return true;\n }\n }\n }\n return false;\n }\n /** @internal */\n _postActivate() {\n if (this._sourceMesh.edgesShareWithInstances && this._sourceMesh._edgesRenderer && this._sourceMesh._edgesRenderer.isEnabled && this._sourceMesh._renderingGroup) {\n // we are using the edge renderer of the source mesh\n this._sourceMesh._renderingGroup._edgesRenderers.pushNoDuplicate(this._sourceMesh._edgesRenderer);\n this._sourceMesh._edgesRenderer.customInstances.push(this.getWorldMatrix());\n }\n else if (this._edgesRenderer && this._edgesRenderer.isEnabled && this._sourceMesh._renderingGroup) {\n // we are using the edge renderer defined for this instance\n this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer);\n }\n }\n getWorldMatrix() {\n if (this._currentLOD && this._currentLOD.billboardMode !== TransformNode.BILLBOARDMODE_NONE && this._currentLOD._masterMesh !== this) {\n if (!this._billboardWorldMatrix) {\n this._billboardWorldMatrix = new Matrix();\n }\n const tempMaster = this._currentLOD._masterMesh;\n this._currentLOD._masterMesh = this;\n TmpVectors.Vector3[7].copyFrom(this._currentLOD.position);\n this._currentLOD.position.set(0, 0, 0);\n this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(true));\n this._currentLOD.position.copyFrom(TmpVectors.Vector3[7]);\n this._currentLOD._masterMesh = tempMaster;\n return this._billboardWorldMatrix;\n }\n return super.getWorldMatrix();\n }\n get isAnInstance() {\n return true;\n }\n /**\n * Returns the current associated LOD AbstractMesh.\n * @param camera\n */\n getLOD(camera) {\n if (!camera) {\n return this;\n }\n const sourceMeshLODLevels = this.sourceMesh.getLODLevels();\n if (!sourceMeshLODLevels || sourceMeshLODLevels.length === 0) {\n this._currentLOD = this.sourceMesh;\n }\n else {\n const boundingInfo = this.getBoundingInfo();\n this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);\n }\n return this._currentLOD;\n }\n /**\n * @internal\n */\n _preActivateForIntermediateRendering(renderId) {\n return this.sourceMesh._preActivateForIntermediateRendering(renderId);\n }\n /** @internal */\n _syncSubMeshes() {\n this.releaseSubMeshes();\n if (this._sourceMesh.subMeshes) {\n for (let index = 0; index < this._sourceMesh.subMeshes.length; index++) {\n this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);\n }\n }\n return this;\n }\n /** @internal */\n _generatePointsArray() {\n return this._sourceMesh._generatePointsArray();\n }\n /** @internal */\n _updateBoundingInfo() {\n if (this.hasBoundingInfo) {\n this.getBoundingInfo().update(this.worldMatrixFromCache);\n }\n else {\n this.buildBoundingInfo(this.absolutePosition, this.absolutePosition, this.worldMatrixFromCache);\n }\n this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);\n return this;\n }\n /**\n * Creates a new InstancedMesh from the current mesh.\n *\n * Returns the clone.\n * @param name the cloned mesh name\n * @param newParent the optional Node to parent the clone to.\n * @param doNotCloneChildren if `true` the model children aren't cloned.\n * @param newSourceMesh if set this mesh will be used as the source mesh instead of ths instance's one\n * @returns the clone\n */\n clone(name, newParent = null, doNotCloneChildren, newSourceMesh) {\n const result = (newSourceMesh || this._sourceMesh).createInstance(name);\n // Deep copy\n DeepCopier.DeepCopy(this, result, [\n \"name\",\n \"subMeshes\",\n \"uniqueId\",\n \"parent\",\n \"lightSources\",\n \"receiveShadows\",\n \"material\",\n \"visibility\",\n \"skeleton\",\n \"sourceMesh\",\n \"isAnInstance\",\n \"facetNb\",\n \"isFacetDataEnabled\",\n \"isBlocked\",\n \"useBones\",\n \"hasInstances\",\n \"collider\",\n \"edgesRenderer\",\n \"forward\",\n \"up\",\n \"right\",\n \"absolutePosition\",\n \"absoluteScaling\",\n \"absoluteRotationQuaternion\",\n \"isWorldMatrixFrozen\",\n \"nonUniformScaling\",\n \"behaviors\",\n \"worldMatrixFromCache\",\n \"hasThinInstances\",\n \"hasBoundingInfo\",\n ], []);\n // Bounding info\n this.refreshBoundingInfo();\n // Parent\n if (newParent) {\n result.parent = newParent;\n }\n if (!doNotCloneChildren) {\n // Children\n for (let index = 0; index < this.getScene().meshes.length; index++) {\n const mesh = this.getScene().meshes[index];\n if (mesh.parent === this) {\n mesh.clone(mesh.name, result);\n }\n }\n }\n result.computeWorldMatrix(true);\n this.onClonedObservable.notifyObservers(result);\n return result;\n }\n /**\n * Disposes the InstancedMesh.\n * Returns nothing.\n * @param doNotRecurse\n * @param disposeMaterialAndTextures\n */\n dispose(doNotRecurse, disposeMaterialAndTextures = false) {\n // Remove from mesh\n this._sourceMesh.removeInstance(this);\n super.dispose(doNotRecurse, disposeMaterialAndTextures);\n }\n /**\n * @internal\n */\n _serializeAsParent(serializationObject) {\n super._serializeAsParent(serializationObject);\n serializationObject.parentId = this._sourceMesh.uniqueId;\n serializationObject.parentInstanceIndex = this._indexInSourceMeshInstanceArray;\n }\n /**\n * Instantiate (when possible) or clone that node with its hierarchy\n * @param newParent defines the new parent to use for the instance (or clone)\n * @param options defines options to configure how copy is done\n * @param options.doNotInstantiate defines if the model must be instantiated or just cloned\n * @param options.newSourcedMesh newSourcedMesh the new source mesh for the instance (or clone)\n * @param onNewNodeCreated defines an option callback to call when a clone or an instance is created\n * @returns an instance (or a clone) of the current node with its hierarchy\n */\n instantiateHierarchy(newParent = null, options, onNewNodeCreated) {\n const clone = this.clone(\"Clone of \" + (this.name || this.id), newParent || this.parent, true, options && options.newSourcedMesh);\n if (clone) {\n if (onNewNodeCreated) {\n onNewNodeCreated(this, clone);\n }\n }\n for (const child of this.getChildTransformNodes(true)) {\n child.instantiateHierarchy(clone, options, onNewNodeCreated);\n }\n return clone;\n }\n}\nMesh.prototype.registerInstancedBuffer = function (kind, stride) {\n var _a, _b;\n // Remove existing one\n (_b = (_a = this._userInstancedBuffersStorage) === null || _a === void 0 ? void 0 : _a.vertexBuffers[kind]) === null || _b === void 0 ? void 0 : _b.dispose();\n // Creates the instancedBuffer field if not present\n if (!this.instancedBuffers) {\n this.instancedBuffers = {};\n for (const instance of this.instances) {\n instance.instancedBuffers = {};\n }\n if (!this._userInstancedBuffersStorage) {\n this._userInstancedBuffersStorage = {\n data: {},\n vertexBuffers: {},\n strides: {},\n sizes: {},\n vertexArrayObjects: this.getEngine().getCaps().vertexArrayObject ? {} : undefined,\n };\n }\n }\n // Creates an empty property for this kind\n this.instancedBuffers[kind] = null;\n this._userInstancedBuffersStorage.strides[kind] = stride;\n this._userInstancedBuffersStorage.sizes[kind] = stride * 32; // Initial size\n this._userInstancedBuffersStorage.data[kind] = new Float32Array(this._userInstancedBuffersStorage.sizes[kind]);\n this._userInstancedBuffersStorage.vertexBuffers[kind] = new VertexBuffer(this.getEngine(), this._userInstancedBuffersStorage.data[kind], kind, true, false, stride, true);\n for (const instance of this.instances) {\n instance.instancedBuffers[kind] = null;\n }\n this._invalidateInstanceVertexArrayObject();\n this._markSubMeshesAsAttributesDirty();\n};\nMesh.prototype._processInstancedBuffers = function (visibleInstances, renderSelf) {\n const instanceCount = visibleInstances ? visibleInstances.length : 0;\n for (const kind in this.instancedBuffers) {\n let size = this._userInstancedBuffersStorage.sizes[kind];\n const stride = this._userInstancedBuffersStorage.strides[kind];\n // Resize if required\n const expectedSize = (instanceCount + 1) * stride;\n while (size < expectedSize) {\n size *= 2;\n }\n if (this._userInstancedBuffersStorage.data[kind].length != size) {\n this._userInstancedBuffersStorage.data[kind] = new Float32Array(size);\n this._userInstancedBuffersStorage.sizes[kind] = size;\n if (this._userInstancedBuffersStorage.vertexBuffers[kind]) {\n this._userInstancedBuffersStorage.vertexBuffers[kind].dispose();\n this._userInstancedBuffersStorage.vertexBuffers[kind] = null;\n }\n }\n const data = this._userInstancedBuffersStorage.data[kind];\n // Update data buffer\n let offset = 0;\n if (renderSelf) {\n const value = this.instancedBuffers[kind];\n if (value.toArray) {\n value.toArray(data, offset);\n }\n else if (value.copyToArray) {\n value.copyToArray(data, offset);\n }\n else {\n data[offset] = value;\n }\n offset += stride;\n }\n for (let instanceIndex = 0; instanceIndex < instanceCount; instanceIndex++) {\n const instance = visibleInstances[instanceIndex];\n const value = instance.instancedBuffers[kind];\n if (value.toArray) {\n value.toArray(data, offset);\n }\n else if (value.copyToArray) {\n value.copyToArray(data, offset);\n }\n else {\n data[offset] = value;\n }\n offset += stride;\n }\n // Update vertex buffer\n if (!this._userInstancedBuffersStorage.vertexBuffers[kind]) {\n this._userInstancedBuffersStorage.vertexBuffers[kind] = new VertexBuffer(this.getEngine(), this._userInstancedBuffersStorage.data[kind], kind, true, false, stride, true);\n this._invalidateInstanceVertexArrayObject();\n }\n else {\n this._userInstancedBuffersStorage.vertexBuffers[kind].updateDirectly(data, 0);\n }\n }\n};\nMesh.prototype._invalidateInstanceVertexArrayObject = function () {\n if (!this._userInstancedBuffersStorage || this._userInstancedBuffersStorage.vertexArrayObjects === undefined) {\n return;\n }\n for (const kind in this._userInstancedBuffersStorage.vertexArrayObjects) {\n this.getEngine().releaseVertexArrayObject(this._userInstancedBuffersStorage.vertexArrayObjects[kind]);\n }\n this._userInstancedBuffersStorage.vertexArrayObjects = {};\n};\nMesh.prototype._disposeInstanceSpecificData = function () {\n if (this._instanceDataStorage.instancesBuffer) {\n this._instanceDataStorage.instancesBuffer.dispose();\n this._instanceDataStorage.instancesBuffer = null;\n }\n while (this.instances.length) {\n this.instances[0].dispose();\n }\n for (const kind in this.instancedBuffers) {\n if (this._userInstancedBuffersStorage.vertexBuffers[kind]) {\n this._userInstancedBuffersStorage.vertexBuffers[kind].dispose();\n }\n }\n this._invalidateInstanceVertexArrayObject();\n this.instancedBuffers = {};\n};\n//# sourceMappingURL=instancedMesh.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize, SerializationHelper, serializeAsColor3, expandToProperty } from \"../Misc/decorators.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Color3, TmpColors } from \"../Maths/math.color.js\";\nimport { Node } from \"../node.js\";\nimport { UniformBuffer } from \"../Materials/uniformBuffer.js\";\nimport { GetClass } from \"../Misc/typeStore.js\";\nimport { LightConstants } from \"./lightConstants.js\";\n/**\n * Base class of all the lights in Babylon. It groups all the generic information about lights.\n * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.\n * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased.\n */\nexport class Light extends Node {\n /**\n * Defines how far from the source the light is impacting in scene units.\n * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.\n */\n get range() {\n return this._range;\n }\n /**\n * Defines how far from the source the light is impacting in scene units.\n * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.\n */\n set range(value) {\n this._range = value;\n this._inverseSquaredRange = 1.0 / (this.range * this.range);\n }\n /**\n * Gets the photometric scale used to interpret the intensity.\n * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.\n */\n get intensityMode() {\n return this._intensityMode;\n }\n /**\n * Sets the photometric scale used to interpret the intensity.\n * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.\n */\n set intensityMode(value) {\n this._intensityMode = value;\n this._computePhotometricScale();\n }\n /**\n * Gets the light radius used by PBR Materials to simulate soft area lights.\n */\n get radius() {\n return this._radius;\n }\n /**\n * sets the light radius used by PBR Materials to simulate soft area lights.\n */\n set radius(value) {\n this._radius = value;\n this._computePhotometricScale();\n }\n /**\n * Gets whether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching\n * the current shadow generator.\n */\n get shadowEnabled() {\n return this._shadowEnabled;\n }\n /**\n * Sets whether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching\n * the current shadow generator.\n */\n set shadowEnabled(value) {\n if (this._shadowEnabled === value) {\n return;\n }\n this._shadowEnabled = value;\n this._markMeshesAsLightDirty();\n }\n /**\n * Gets the only meshes impacted by this light.\n */\n get includedOnlyMeshes() {\n return this._includedOnlyMeshes;\n }\n /**\n * Sets the only meshes impacted by this light.\n */\n set includedOnlyMeshes(value) {\n this._includedOnlyMeshes = value;\n this._hookArrayForIncludedOnly(value);\n }\n /**\n * Gets the meshes not impacted by this light.\n */\n get excludedMeshes() {\n return this._excludedMeshes;\n }\n /**\n * Sets the meshes not impacted by this light.\n */\n set excludedMeshes(value) {\n this._excludedMeshes = value;\n this._hookArrayForExcluded(value);\n }\n /**\n * Gets the layer id use to find what meshes are not impacted by the light.\n * Inactive if 0\n */\n get excludeWithLayerMask() {\n return this._excludeWithLayerMask;\n }\n /**\n * Sets the layer id use to find what meshes are not impacted by the light.\n * Inactive if 0\n */\n set excludeWithLayerMask(value) {\n this._excludeWithLayerMask = value;\n this._resyncMeshes();\n }\n /**\n * Gets the layer id use to find what meshes are impacted by the light.\n * Inactive if 0\n */\n get includeOnlyWithLayerMask() {\n return this._includeOnlyWithLayerMask;\n }\n /**\n * Sets the layer id use to find what meshes are impacted by the light.\n * Inactive if 0\n */\n set includeOnlyWithLayerMask(value) {\n this._includeOnlyWithLayerMask = value;\n this._resyncMeshes();\n }\n /**\n * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)\n */\n get lightmapMode() {\n return this._lightmapMode;\n }\n /**\n * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)\n */\n set lightmapMode(value) {\n if (this._lightmapMode === value) {\n return;\n }\n this._lightmapMode = value;\n this._markMeshesAsLightDirty();\n }\n /**\n * Creates a Light object in the scene.\n * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction\n * @param name The friendly name of the light\n * @param scene The scene the light belongs too\n */\n constructor(name, scene) {\n super(name, scene);\n /**\n * Diffuse gives the basic color to an object.\n */\n this.diffuse = new Color3(1.0, 1.0, 1.0);\n /**\n * Specular produces a highlight color on an object.\n * Note: This is not affecting PBR materials.\n */\n this.specular = new Color3(1.0, 1.0, 1.0);\n /**\n * Defines the falloff type for this light. This lets overriding how punctual light are\n * falling off base on range or angle.\n * This can be set to any values in Light.FALLOFF_x.\n *\n * Note: This is only useful for PBR Materials at the moment. This could be extended if required to\n * other types of materials.\n */\n this.falloffType = Light.FALLOFF_DEFAULT;\n /**\n * Strength of the light.\n * Note: By default it is define in the framework own unit.\n * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.\n */\n this.intensity = 1.0;\n this._range = Number.MAX_VALUE;\n this._inverseSquaredRange = 0;\n /**\n * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type\n * of light.\n */\n this._photometricScale = 1.0;\n this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;\n this._radius = 0.00001;\n /**\n * Defines the rendering priority of the lights. It can help in case of fallback or number of lights\n * exceeding the number allowed of the materials.\n */\n this.renderPriority = 0;\n this._shadowEnabled = true;\n this._excludeWithLayerMask = 0;\n this._includeOnlyWithLayerMask = 0;\n this._lightmapMode = 0;\n /**\n * Shadow generators associated to the light.\n * @internal Internal use only.\n */\n this._shadowGenerators = null;\n /**\n * @internal Internal use only.\n */\n this._excludedMeshesIds = new Array();\n /**\n * @internal Internal use only.\n */\n this._includedOnlyMeshesIds = new Array();\n /** @internal */\n this._isLight = true;\n this.getScene().addLight(this);\n this._uniformBuffer = new UniformBuffer(this.getScene().getEngine(), undefined, undefined, name);\n this._buildUniformLayout();\n this.includedOnlyMeshes = new Array();\n this.excludedMeshes = new Array();\n this._resyncMeshes();\n }\n /**\n * Sets the passed Effect \"effect\" with the Light textures.\n * @param effect The effect to update\n * @param lightIndex The index of the light in the effect to update\n * @returns The light\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n transferTexturesToEffect(effect, lightIndex) {\n // Do nothing by default.\n return this;\n }\n /**\n * Binds the lights information from the scene to the effect for the given mesh.\n * @param lightIndex Light index\n * @param scene The scene where the light belongs to\n * @param effect The effect we are binding the data to\n * @param useSpecular Defines if specular is supported\n * @param receiveShadows Defines if the effect (mesh) we bind the light for receives shadows\n */\n _bindLight(lightIndex, scene, effect, useSpecular, receiveShadows = true) {\n var _a;\n const iAsString = lightIndex.toString();\n let needUpdate = false;\n this._uniformBuffer.bindToEffect(effect, \"Light\" + iAsString);\n if (this._renderId !== scene.getRenderId() || this._lastUseSpecular !== useSpecular || !this._uniformBuffer.useUbo) {\n this._renderId = scene.getRenderId();\n this._lastUseSpecular = useSpecular;\n const scaledIntensity = this.getScaledIntensity();\n this.transferToEffect(effect, iAsString);\n this.diffuse.scaleToRef(scaledIntensity, TmpColors.Color3[0]);\n this._uniformBuffer.updateColor4(\"vLightDiffuse\", TmpColors.Color3[0], this.range, iAsString);\n if (useSpecular) {\n this.specular.scaleToRef(scaledIntensity, TmpColors.Color3[1]);\n this._uniformBuffer.updateColor4(\"vLightSpecular\", TmpColors.Color3[1], this.radius, iAsString);\n }\n needUpdate = true;\n }\n // Textures might still need to be rebound.\n this.transferTexturesToEffect(effect, iAsString);\n // Shadows\n if (scene.shadowsEnabled && this.shadowEnabled && receiveShadows) {\n const shadowGenerator = (_a = this.getShadowGenerator(scene.activeCamera)) !== null && _a !== void 0 ? _a : this.getShadowGenerator();\n if (shadowGenerator) {\n shadowGenerator.bindShadowLight(iAsString, effect);\n needUpdate = true;\n }\n }\n if (needUpdate) {\n this._uniformBuffer.update();\n }\n else {\n this._uniformBuffer.bindUniformBuffer();\n }\n }\n /**\n * Returns the string \"Light\".\n * @returns the class name\n */\n getClassName() {\n return \"Light\";\n }\n /**\n * Converts the light information to a readable string for debug purpose.\n * @param fullDetails Supports for multiple levels of logging within scene loading\n * @returns the human readable light info\n */\n toString(fullDetails) {\n let ret = \"Name: \" + this.name;\n ret += \", type: \" + [\"Point\", \"Directional\", \"Spot\", \"Hemispheric\"][this.getTypeID()];\n if (this.animations) {\n for (let i = 0; i < this.animations.length; i++) {\n ret += \", animation[0]: \" + this.animations[i].toString(fullDetails);\n }\n }\n return ret;\n }\n /** @internal */\n _syncParentEnabledState() {\n super._syncParentEnabledState();\n if (!this.isDisposed()) {\n this._resyncMeshes();\n }\n }\n /**\n * Set the enabled state of this node.\n * @param value - the new enabled state\n */\n setEnabled(value) {\n super.setEnabled(value);\n this._resyncMeshes();\n }\n /**\n * Returns the Light associated shadow generator if any.\n * @param camera Camera for which the shadow generator should be retrieved (default: null). If null, retrieves the default shadow generator\n * @returns the associated shadow generator.\n */\n getShadowGenerator(camera = null) {\n var _a;\n if (this._shadowGenerators === null) {\n return null;\n }\n return (_a = this._shadowGenerators.get(camera)) !== null && _a !== void 0 ? _a : null;\n }\n /**\n * Returns all the shadow generators associated to this light\n * @returns\n */\n getShadowGenerators() {\n return this._shadowGenerators;\n }\n /**\n * Returns a Vector3, the absolute light position in the World.\n * @returns the world space position of the light\n */\n getAbsolutePosition() {\n return Vector3.Zero();\n }\n /**\n * Specifies if the light will affect the passed mesh.\n * @param mesh The mesh to test against the light\n * @returns true the mesh is affected otherwise, false.\n */\n canAffectMesh(mesh) {\n if (!mesh) {\n return true;\n }\n if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {\n return false;\n }\n if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {\n return false;\n }\n if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {\n return false;\n }\n if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {\n return false;\n }\n return true;\n }\n /**\n * Releases resources associated with this node.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n dispose(doNotRecurse, disposeMaterialAndTextures = false) {\n if (this._shadowGenerators) {\n const iterator = this._shadowGenerators.values();\n for (let key = iterator.next(); key.done !== true; key = iterator.next()) {\n const shadowGenerator = key.value;\n shadowGenerator.dispose();\n }\n this._shadowGenerators = null;\n }\n // Animations\n this.getScene().stopAnimation(this);\n if (this._parentContainer) {\n const index = this._parentContainer.lights.indexOf(this);\n if (index > -1) {\n this._parentContainer.lights.splice(index, 1);\n }\n this._parentContainer = null;\n }\n // Remove from meshes\n for (const mesh of this.getScene().meshes) {\n mesh._removeLightSource(this, true);\n }\n this._uniformBuffer.dispose();\n // Remove from scene\n this.getScene().removeLight(this);\n super.dispose(doNotRecurse, disposeMaterialAndTextures);\n }\n /**\n * Returns the light type ID (integer).\n * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x\n */\n getTypeID() {\n return 0;\n }\n /**\n * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.\n * @returns the scaled intensity in intensity mode unit\n */\n getScaledIntensity() {\n return this._photometricScale * this.intensity;\n }\n /**\n * Returns a new Light object, named \"name\", from the current one.\n * @param name The name of the cloned light\n * @param newParent The parent of this light, if it has one\n * @returns the new created light\n */\n clone(name, newParent = null) {\n const constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());\n if (!constructor) {\n return null;\n }\n const clonedLight = SerializationHelper.Clone(constructor, this);\n if (name) {\n clonedLight.name = name;\n }\n if (newParent) {\n clonedLight.parent = newParent;\n }\n clonedLight.setEnabled(this.isEnabled());\n this.onClonedObservable.notifyObservers(clonedLight);\n return clonedLight;\n }\n /**\n * Serializes the current light into a Serialization object.\n * @returns the serialized object.\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this);\n serializationObject.uniqueId = this.uniqueId;\n // Type\n serializationObject.type = this.getTypeID();\n // Parent\n if (this.parent) {\n this.parent._serializeAsParent(serializationObject);\n }\n // Inclusion / exclusions\n if (this.excludedMeshes.length > 0) {\n serializationObject.excludedMeshesIds = [];\n this.excludedMeshes.forEach((mesh) => {\n serializationObject.excludedMeshesIds.push(mesh.id);\n });\n }\n if (this.includedOnlyMeshes.length > 0) {\n serializationObject.includedOnlyMeshesIds = [];\n this.includedOnlyMeshes.forEach((mesh) => {\n serializationObject.includedOnlyMeshesIds.push(mesh.id);\n });\n }\n // Animations\n SerializationHelper.AppendSerializedAnimations(this, serializationObject);\n serializationObject.ranges = this.serializeAnimationRanges();\n serializationObject.isEnabled = this.isEnabled();\n return serializationObject;\n }\n /**\n * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.\n * This new light is named \"name\" and added to the passed scene.\n * @param type Type according to the types available in Light.LIGHTTYPEID_x\n * @param name The friendly name of the light\n * @param scene The scene the new light will belong to\n * @returns the constructor function\n */\n static GetConstructorFromName(type, name, scene) {\n const constructorFunc = Node.Construct(\"Light_Type_\" + type, name, scene);\n if (constructorFunc) {\n return constructorFunc;\n }\n // Default to no light for none present once.\n return null;\n }\n /**\n * Parses the passed \"parsedLight\" and returns a new instanced Light from this parsing.\n * @param parsedLight The JSON representation of the light\n * @param scene The scene to create the parsed light in\n * @returns the created light after parsing\n */\n static Parse(parsedLight, scene) {\n const constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);\n if (!constructor) {\n return null;\n }\n const light = SerializationHelper.Parse(constructor, parsedLight, scene);\n // Inclusion / exclusions\n if (parsedLight.excludedMeshesIds) {\n light._excludedMeshesIds = parsedLight.excludedMeshesIds;\n }\n if (parsedLight.includedOnlyMeshesIds) {\n light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;\n }\n // Parent\n if (parsedLight.parentId !== undefined) {\n light._waitingParentId = parsedLight.parentId;\n }\n if (parsedLight.parentInstanceIndex !== undefined) {\n light._waitingParentInstanceIndex = parsedLight.parentInstanceIndex;\n }\n // Falloff\n if (parsedLight.falloffType !== undefined) {\n light.falloffType = parsedLight.falloffType;\n }\n // Lightmaps\n if (parsedLight.lightmapMode !== undefined) {\n light.lightmapMode = parsedLight.lightmapMode;\n }\n // Animations\n if (parsedLight.animations) {\n for (let animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {\n const parsedAnimation = parsedLight.animations[animationIndex];\n const internalClass = GetClass(\"BABYLON.Animation\");\n if (internalClass) {\n light.animations.push(internalClass.Parse(parsedAnimation));\n }\n }\n Node.ParseAnimationRanges(light, parsedLight, scene);\n }\n if (parsedLight.autoAnimate) {\n scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);\n }\n // Check if isEnabled is defined to be back compatible with prior serialized versions.\n if (parsedLight.isEnabled !== undefined) {\n light.setEnabled(parsedLight.isEnabled);\n }\n return light;\n }\n _hookArrayForExcluded(array) {\n const oldPush = array.push;\n array.push = (...items) => {\n const result = oldPush.apply(array, items);\n for (const item of items) {\n item._resyncLightSource(this);\n }\n return result;\n };\n const oldSplice = array.splice;\n array.splice = (index, deleteCount) => {\n const deleted = oldSplice.apply(array, [index, deleteCount]);\n for (const item of deleted) {\n item._resyncLightSource(this);\n }\n return deleted;\n };\n for (const item of array) {\n item._resyncLightSource(this);\n }\n }\n _hookArrayForIncludedOnly(array) {\n const oldPush = array.push;\n array.push = (...items) => {\n const result = oldPush.apply(array, items);\n this._resyncMeshes();\n return result;\n };\n const oldSplice = array.splice;\n array.splice = (index, deleteCount) => {\n const deleted = oldSplice.apply(array, [index, deleteCount]);\n this._resyncMeshes();\n return deleted;\n };\n this._resyncMeshes();\n }\n _resyncMeshes() {\n for (const mesh of this.getScene().meshes) {\n mesh._resyncLightSource(this);\n }\n }\n /**\n * Forces the meshes to update their light related information in their rendering used effects\n * @internal Internal Use Only\n */\n _markMeshesAsLightDirty() {\n for (const mesh of this.getScene().meshes) {\n if (mesh.lightSources.indexOf(this) !== -1) {\n mesh._markSubMeshesAsLightDirty();\n }\n }\n }\n /**\n * Recomputes the cached photometric scale if needed.\n */\n _computePhotometricScale() {\n this._photometricScale = this._getPhotometricScale();\n this.getScene().resetCachedMaterial();\n }\n /**\n * Returns the Photometric Scale according to the light type and intensity mode.\n */\n _getPhotometricScale() {\n let photometricScale = 0.0;\n const lightTypeID = this.getTypeID();\n //get photometric mode\n let photometricMode = this.intensityMode;\n if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {\n if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {\n photometricMode = Light.INTENSITYMODE_ILLUMINANCE;\n }\n else {\n photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;\n }\n }\n //compute photometric scale\n switch (lightTypeID) {\n case Light.LIGHTTYPEID_POINTLIGHT:\n case Light.LIGHTTYPEID_SPOTLIGHT:\n switch (photometricMode) {\n case Light.INTENSITYMODE_LUMINOUSPOWER:\n photometricScale = 1.0 / (4.0 * Math.PI);\n break;\n case Light.INTENSITYMODE_LUMINOUSINTENSITY:\n photometricScale = 1.0;\n break;\n case Light.INTENSITYMODE_LUMINANCE:\n photometricScale = this.radius * this.radius;\n break;\n }\n break;\n case Light.LIGHTTYPEID_DIRECTIONALLIGHT:\n switch (photometricMode) {\n case Light.INTENSITYMODE_ILLUMINANCE:\n photometricScale = 1.0;\n break;\n case Light.INTENSITYMODE_LUMINANCE: {\n // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.\n // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).\n let apexAngleRadians = this.radius;\n // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).\n apexAngleRadians = Math.max(apexAngleRadians, 0.001);\n const solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));\n photometricScale = solidAngle;\n break;\n }\n }\n break;\n case Light.LIGHTTYPEID_HEMISPHERICLIGHT:\n // No fall off in hemispheric light.\n photometricScale = 1.0;\n break;\n }\n return photometricScale;\n }\n /**\n * Reorder the light in the scene according to their defined priority.\n * @internal Internal Use Only\n */\n _reorderLightsInScene() {\n const scene = this.getScene();\n if (this._renderPriority != 0) {\n scene.requireLightSorting = true;\n }\n this.getScene().sortLightsByPriority();\n }\n}\n/**\n * Falloff Default: light is falling off following the material specification:\n * standard material is using standard falloff whereas pbr material can request special falloff per materials.\n */\nLight.FALLOFF_DEFAULT = LightConstants.FALLOFF_DEFAULT;\n/**\n * Falloff Physical: light is falling off following the inverse squared distance law.\n */\nLight.FALLOFF_PHYSICAL = LightConstants.FALLOFF_PHYSICAL;\n/**\n * Falloff gltf: light is falling off as described in the gltf moving to PBR document\n * to enhance interoperability with other engines.\n */\nLight.FALLOFF_GLTF = LightConstants.FALLOFF_GLTF;\n/**\n * Falloff Standard: light is falling off like in the standard material\n * to enhance interoperability with other materials.\n */\nLight.FALLOFF_STANDARD = LightConstants.FALLOFF_STANDARD;\n//lightmapMode Consts\n/**\n * If every light affecting the material is in this lightmapMode,\n * material.lightmapTexture adds or multiplies\n * (depends on material.useLightmapAsShadowmap)\n * after every other light calculations.\n */\nLight.LIGHTMAP_DEFAULT = LightConstants.LIGHTMAP_DEFAULT;\n/**\n * material.lightmapTexture as only diffuse lighting from this light\n * adds only specular lighting from this light\n * adds dynamic shadows\n */\nLight.LIGHTMAP_SPECULAR = LightConstants.LIGHTMAP_SPECULAR;\n/**\n * material.lightmapTexture as only lighting\n * no light calculation from this light\n * only adds dynamic shadows from this light\n */\nLight.LIGHTMAP_SHADOWSONLY = LightConstants.LIGHTMAP_SHADOWSONLY;\n// Intensity Mode Consts\n/**\n * Each light type uses the default quantity according to its type:\n * point/spot lights use luminous intensity\n * directional lights use illuminance\n */\nLight.INTENSITYMODE_AUTOMATIC = LightConstants.INTENSITYMODE_AUTOMATIC;\n/**\n * lumen (lm)\n */\nLight.INTENSITYMODE_LUMINOUSPOWER = LightConstants.INTENSITYMODE_LUMINOUSPOWER;\n/**\n * candela (lm/sr)\n */\nLight.INTENSITYMODE_LUMINOUSINTENSITY = LightConstants.INTENSITYMODE_LUMINOUSINTENSITY;\n/**\n * lux (lm/m^2)\n */\nLight.INTENSITYMODE_ILLUMINANCE = LightConstants.INTENSITYMODE_ILLUMINANCE;\n/**\n * nit (cd/m^2)\n */\nLight.INTENSITYMODE_LUMINANCE = LightConstants.INTENSITYMODE_LUMINANCE;\n// Light types ids const.\n/**\n * Light type const id of the point light.\n */\nLight.LIGHTTYPEID_POINTLIGHT = LightConstants.LIGHTTYPEID_POINTLIGHT;\n/**\n * Light type const id of the directional light.\n */\nLight.LIGHTTYPEID_DIRECTIONALLIGHT = LightConstants.LIGHTTYPEID_DIRECTIONALLIGHT;\n/**\n * Light type const id of the spot light.\n */\nLight.LIGHTTYPEID_SPOTLIGHT = LightConstants.LIGHTTYPEID_SPOTLIGHT;\n/**\n * Light type const id of the hemispheric light.\n */\nLight.LIGHTTYPEID_HEMISPHERICLIGHT = LightConstants.LIGHTTYPEID_HEMISPHERICLIGHT;\n__decorate([\n serializeAsColor3()\n], Light.prototype, \"diffuse\", void 0);\n__decorate([\n serializeAsColor3()\n], Light.prototype, \"specular\", void 0);\n__decorate([\n serialize()\n], Light.prototype, \"falloffType\", void 0);\n__decorate([\n serialize()\n], Light.prototype, \"intensity\", void 0);\n__decorate([\n serialize()\n], Light.prototype, \"range\", null);\n__decorate([\n serialize()\n], Light.prototype, \"intensityMode\", null);\n__decorate([\n serialize()\n], Light.prototype, \"radius\", null);\n__decorate([\n serialize()\n], Light.prototype, \"_renderPriority\", void 0);\n__decorate([\n expandToProperty(\"_reorderLightsInScene\")\n], Light.prototype, \"renderPriority\", void 0);\n__decorate([\n serialize(\"shadowEnabled\")\n], Light.prototype, \"_shadowEnabled\", void 0);\n__decorate([\n serialize(\"excludeWithLayerMask\")\n], Light.prototype, \"_excludeWithLayerMask\", void 0);\n__decorate([\n serialize(\"includeOnlyWithLayerMask\")\n], Light.prototype, \"_includeOnlyWithLayerMask\", void 0);\n__decorate([\n serialize(\"lightmapMode\")\n], Light.prototype, \"_lightmapMode\", void 0);\n//# sourceMappingURL=light.js.map","import { AbstractScene } from \"./abstractScene.js\";\nimport { Mesh } from \"./Meshes/mesh.js\";\nimport { TransformNode } from \"./Meshes/transformNode.js\";\nimport { Logger } from \"./Misc/logger.js\";\nimport { EngineStore } from \"./Engines/engineStore.js\";\nimport { InstancedMesh } from \"./Meshes/instancedMesh.js\";\nimport { Light } from \"./Lights/light.js\";\nimport { Camera } from \"./Cameras/camera.js\";\nimport { Tools } from \"./Misc/tools.js\";\n/**\n * Set of assets to keep when moving a scene into an asset container.\n */\nexport class KeepAssets extends AbstractScene {\n}\n/**\n * Class used to store the output of the AssetContainer.instantiateAllMeshesToScene function\n */\nexport class InstantiatedEntries {\n constructor() {\n /**\n * List of new root nodes (eg. nodes with no parent)\n */\n this.rootNodes = [];\n /**\n * List of new skeletons\n */\n this.skeletons = [];\n /**\n * List of new animation groups\n */\n this.animationGroups = [];\n }\n /**\n * Disposes the instantiated entries from the scene\n */\n dispose() {\n this.rootNodes.slice(0).forEach((o) => {\n o.dispose();\n });\n this.rootNodes.length = 0;\n this.skeletons.slice(0).forEach((o) => {\n o.dispose();\n });\n this.skeletons.length = 0;\n this.animationGroups.slice(0).forEach((o) => {\n o.dispose();\n });\n this.animationGroups.length = 0;\n }\n}\n/**\n * Container with a set of assets that can be added or removed from a scene.\n */\nexport class AssetContainer extends AbstractScene {\n /**\n * Instantiates an AssetContainer.\n * @param scene The scene the AssetContainer belongs to.\n */\n constructor(scene) {\n super();\n this._wasAddedToScene = false;\n scene = scene || EngineStore.LastCreatedScene;\n if (!scene) {\n return;\n }\n this.scene = scene;\n this[\"sounds\"] = [];\n this[\"effectLayers\"] = [];\n this[\"layers\"] = [];\n this[\"lensFlareSystems\"] = [];\n this[\"proceduralTextures\"] = [];\n this[\"reflectionProbes\"] = [];\n scene.onDisposeObservable.add(() => {\n if (!this._wasAddedToScene) {\n this.dispose();\n }\n });\n this._onContextRestoredObserver = scene.getEngine().onContextRestoredObservable.add(() => {\n for (const geometry of this.geometries) {\n geometry._rebuild();\n }\n for (const mesh of this.meshes) {\n mesh._rebuild();\n }\n for (const system of this.particleSystems) {\n system.rebuild();\n }\n for (const texture of this.textures) {\n texture._rebuild();\n }\n });\n }\n /**\n * Given a list of nodes, return a topological sorting of them.\n * @param nodes\n */\n _topologicalSort(nodes) {\n const nodesUidMap = new Map();\n for (const node of nodes) {\n nodesUidMap.set(node.uniqueId, node);\n }\n const dependencyGraph = {\n dependsOn: new Map(),\n dependedBy: new Map(), // given a node id, what are the ids of the nodes that depend on it\n };\n // Build the dependency graph given the list of nodes\n // First pass: Initialize the empty dependency graph\n for (const node of nodes) {\n const nodeId = node.uniqueId;\n dependencyGraph.dependsOn.set(nodeId, new Set());\n dependencyGraph.dependedBy.set(nodeId, new Set());\n }\n // Second pass: Populate the dependency graph. We assume that we\n // don't need to check for cycles here, as the scene graph cannot\n // contain cycles. Our graph also already contains all transitive\n // dependencies because getDescendants returns the transitive\n // dependencies by default.\n for (const node of nodes) {\n const nodeId = node.uniqueId;\n const dependsOn = dependencyGraph.dependsOn.get(nodeId);\n if (node instanceof InstancedMesh) {\n const masterMesh = node.sourceMesh;\n if (nodesUidMap.has(masterMesh.uniqueId)) {\n dependsOn.add(masterMesh.uniqueId);\n dependencyGraph.dependedBy.get(masterMesh.uniqueId).add(nodeId);\n }\n }\n const dependedBy = dependencyGraph.dependedBy.get(nodeId);\n for (const child of node.getDescendants()) {\n const childId = child.uniqueId;\n if (nodesUidMap.has(childId)) {\n dependedBy.add(childId);\n const childDependsOn = dependencyGraph.dependsOn.get(childId);\n childDependsOn.add(nodeId);\n }\n }\n }\n // Third pass: Topological sort\n const sortedNodes = [];\n // First: Find all nodes that have no dependencies\n const leaves = [];\n for (const node of nodes) {\n const nodeId = node.uniqueId;\n if (dependencyGraph.dependsOn.get(nodeId).size === 0) {\n leaves.push(node);\n nodesUidMap.delete(nodeId);\n }\n }\n const visitList = leaves;\n while (visitList.length > 0) {\n const nodeToVisit = visitList.shift();\n sortedNodes.push(nodeToVisit);\n // Remove the node from the dependency graph\n // When a node is visited, we know that dependsOn is empty.\n // So we only need to remove the node from dependedBy.\n const dependedByVisitedNode = dependencyGraph.dependedBy.get(nodeToVisit.uniqueId);\n // Array.from(x.values()) is to make the TS compiler happy\n for (const dependedByVisitedNodeId of Array.from(dependedByVisitedNode.values())) {\n const dependsOnDependedByVisitedNode = dependencyGraph.dependsOn.get(dependedByVisitedNodeId);\n dependsOnDependedByVisitedNode.delete(nodeToVisit.uniqueId);\n if (dependsOnDependedByVisitedNode.size === 0 && nodesUidMap.get(dependedByVisitedNodeId)) {\n visitList.push(nodesUidMap.get(dependedByVisitedNodeId));\n nodesUidMap.delete(dependedByVisitedNodeId);\n }\n }\n }\n if (nodesUidMap.size > 0) {\n console.error(\"SceneSerializer._topologicalSort: There were unvisited nodes:\");\n nodesUidMap.forEach((node) => console.error(node.name));\n }\n return sortedNodes;\n }\n _addNodeAndDescendantsToList(list, addedIds, rootNode, predicate) {\n if (!rootNode || (predicate && !predicate(rootNode)) || addedIds.has(rootNode.uniqueId)) {\n return;\n }\n list.push(rootNode);\n addedIds.add(rootNode.uniqueId);\n for (const child of rootNode.getDescendants(true)) {\n this._addNodeAndDescendantsToList(list, addedIds, child, predicate);\n }\n }\n /**\n * Check if a specific node is contained in this asset container.\n * @param node\n */\n _isNodeInContainer(node) {\n if (node instanceof Mesh && this.meshes.indexOf(node) !== -1) {\n return true;\n }\n if (node instanceof TransformNode && this.transformNodes.indexOf(node) !== -1) {\n return true;\n }\n if (node instanceof Light && this.lights.indexOf(node) !== -1) {\n return true;\n }\n if (node instanceof Camera && this.cameras.indexOf(node) !== -1) {\n return true;\n }\n return false;\n }\n /**\n * For every node in the scene, check if its parent node is also in the scene.\n */\n _isValidHierarchy() {\n for (const node of this.meshes) {\n if (node.parent && !this._isNodeInContainer(node.parent)) {\n Logger.Warn(`Node ${node.name} has a parent that is not in the container.`);\n return false;\n }\n }\n for (const node of this.transformNodes) {\n if (node.parent && !this._isNodeInContainer(node.parent)) {\n Logger.Warn(`Node ${node.name} has a parent that is not in the container.`);\n return false;\n }\n }\n for (const node of this.lights) {\n if (node.parent && !this._isNodeInContainer(node.parent)) {\n Logger.Warn(`Node ${node.name} has a parent that is not in the container.`);\n return false;\n }\n }\n for (const node of this.cameras) {\n if (node.parent && !this._isNodeInContainer(node.parent)) {\n Logger.Warn(`Node ${node.name} has a parent that is not in the container.`);\n return false;\n }\n }\n return true;\n }\n /**\n * Instantiate or clone all meshes and add the new ones to the scene.\n * Skeletons and animation groups will all be cloned\n * @param nameFunction defines an optional function used to get new names for clones\n * @param cloneMaterials defines an optional boolean that defines if materials must be cloned as well (false by default)\n * @param options defines an optional list of options to control how to instantiate / clone models\n * @param options.doNotInstantiate defines if the model must be instantiated or just cloned\n * @param options.predicate defines a predicate used to filter whih mesh to instantiate/clone\n * @returns a list of rootNodes, skeletons and animation groups that were duplicated\n */\n instantiateModelsToScene(nameFunction, cloneMaterials = false, options) {\n if (!this._isValidHierarchy()) {\n Tools.Warn(\"SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.\");\n }\n const conversionMap = {};\n const storeMap = {};\n const result = new InstantiatedEntries();\n const alreadySwappedSkeletons = [];\n const alreadySwappedMaterials = [];\n const localOptions = Object.assign({ doNotInstantiate: true }, options);\n const onClone = (source, clone) => {\n conversionMap[source.uniqueId] = clone.uniqueId;\n storeMap[clone.uniqueId] = clone;\n if (nameFunction) {\n clone.name = nameFunction(source.name);\n }\n if (clone instanceof Mesh) {\n const clonedMesh = clone;\n if (clonedMesh.morphTargetManager) {\n const oldMorphTargetManager = source.morphTargetManager;\n clonedMesh.morphTargetManager = oldMorphTargetManager.clone();\n for (let index = 0; index < oldMorphTargetManager.numTargets; index++) {\n const oldTarget = oldMorphTargetManager.getTarget(index);\n const newTarget = clonedMesh.morphTargetManager.getTarget(index);\n conversionMap[oldTarget.uniqueId] = newTarget.uniqueId;\n storeMap[newTarget.uniqueId] = newTarget;\n }\n }\n }\n };\n const nodesToSort = [];\n const idsOnSortList = new Set();\n for (const transformNode of this.transformNodes) {\n if (transformNode.parent === null) {\n this._addNodeAndDescendantsToList(nodesToSort, idsOnSortList, transformNode, localOptions.predicate);\n }\n }\n for (const mesh of this.meshes) {\n if (mesh.parent === null) {\n this._addNodeAndDescendantsToList(nodesToSort, idsOnSortList, mesh, localOptions.predicate);\n }\n }\n // Topologically sort nodes by parenting/instancing relationships so that all resources are in place\n // when a given node is instantiated.\n const sortedNodes = this._topologicalSort(nodesToSort);\n const onNewCreated = (source, clone) => {\n onClone(source, clone);\n if (source.parent) {\n const replicatedParentId = conversionMap[source.parent.uniqueId];\n const replicatedParent = storeMap[replicatedParentId];\n if (replicatedParent) {\n clone.parent = replicatedParent;\n }\n else {\n clone.parent = source.parent;\n }\n }\n if (clone.position && source.position) {\n clone.position.copyFrom(source.position);\n }\n if (clone.rotationQuaternion && source.rotationQuaternion) {\n clone.rotationQuaternion.copyFrom(source.rotationQuaternion);\n }\n if (clone.rotation && source.rotation) {\n clone.rotation.copyFrom(source.rotation);\n }\n if (clone.scaling && source.scaling) {\n clone.scaling.copyFrom(source.scaling);\n }\n if (clone.material) {\n const mesh = clone;\n if (mesh.material) {\n if (cloneMaterials) {\n const sourceMaterial = source.material;\n if (alreadySwappedMaterials.indexOf(sourceMaterial) === -1) {\n let swap = sourceMaterial.clone(nameFunction ? nameFunction(sourceMaterial.name) : \"Clone of \" + sourceMaterial.name);\n alreadySwappedMaterials.push(sourceMaterial);\n conversionMap[sourceMaterial.uniqueId] = swap.uniqueId;\n storeMap[swap.uniqueId] = swap;\n if (sourceMaterial.getClassName() === \"MultiMaterial\") {\n const multi = sourceMaterial;\n for (const material of multi.subMaterials) {\n if (!material) {\n continue;\n }\n swap = material.clone(nameFunction ? nameFunction(material.name) : \"Clone of \" + material.name);\n alreadySwappedMaterials.push(material);\n conversionMap[material.uniqueId] = swap.uniqueId;\n storeMap[swap.uniqueId] = swap;\n }\n multi.subMaterials = multi.subMaterials.map((m) => m && storeMap[conversionMap[m.uniqueId]]);\n }\n }\n if (mesh.getClassName() !== \"InstancedMesh\") {\n mesh.material = storeMap[conversionMap[sourceMaterial.uniqueId]];\n }\n }\n else {\n if (mesh.material.getClassName() === \"MultiMaterial\") {\n if (this.scene.multiMaterials.indexOf(mesh.material) === -1) {\n this.scene.addMultiMaterial(mesh.material);\n }\n }\n else {\n if (this.scene.materials.indexOf(mesh.material) === -1) {\n this.scene.addMaterial(mesh.material);\n }\n }\n }\n }\n }\n if (clone.parent === null) {\n result.rootNodes.push(clone);\n }\n };\n sortedNodes.forEach((node) => {\n if (node.getClassName() === \"InstancedMesh\") {\n const instancedNode = node;\n const sourceMesh = instancedNode.sourceMesh;\n const replicatedSourceId = conversionMap[sourceMesh.uniqueId];\n const replicatedSource = typeof replicatedSourceId === \"number\" ? storeMap[replicatedSourceId] : sourceMesh;\n const replicatedInstancedNode = replicatedSource.createInstance(instancedNode.name);\n onNewCreated(instancedNode, replicatedInstancedNode);\n }\n else {\n // Mesh or TransformNode\n let canInstance = true;\n if (node.getClassName() === \"TransformNode\" ||\n node.getClassName() === \"Node\" ||\n node.skeleton ||\n !node.getTotalVertices ||\n node.getTotalVertices() === 0) {\n // Transform nodes, skinned meshes, and meshes with no vertices can never be instanced!\n canInstance = false;\n }\n else if (localOptions.doNotInstantiate) {\n if (typeof localOptions.doNotInstantiate === \"function\") {\n canInstance = !localOptions.doNotInstantiate(node);\n }\n else {\n canInstance = !localOptions.doNotInstantiate;\n }\n }\n const replicatedNode = canInstance ? node.createInstance(`instance of ${node.name}`) : node.clone(`Clone of ${node.name}`, null, true);\n if (!replicatedNode) {\n throw new Error(`Could not clone or instantiate node on Asset Container ${node.name}`);\n }\n onNewCreated(node, replicatedNode);\n }\n });\n this.skeletons.forEach((s) => {\n if (localOptions.predicate && !localOptions.predicate(s)) {\n return;\n }\n const clone = s.clone(nameFunction ? nameFunction(s.name) : \"Clone of \" + s.name);\n for (const m of this.meshes) {\n if (m.skeleton === s && !m.isAnInstance) {\n const copy = storeMap[conversionMap[m.uniqueId]];\n if (!copy || copy.isAnInstance) {\n continue;\n }\n copy.skeleton = clone;\n if (alreadySwappedSkeletons.indexOf(clone) !== -1) {\n continue;\n }\n alreadySwappedSkeletons.push(clone);\n // Check if bones are mesh linked\n for (const bone of clone.bones) {\n if (bone._linkedTransformNode) {\n bone._linkedTransformNode = storeMap[conversionMap[bone._linkedTransformNode.uniqueId]];\n }\n }\n }\n }\n result.skeletons.push(clone);\n });\n this.animationGroups.forEach((o) => {\n if (localOptions.predicate && !localOptions.predicate(o)) {\n return;\n }\n const clone = o.clone(nameFunction ? nameFunction(o.name) : \"Clone of \" + o.name, (oldTarget) => {\n const newTarget = storeMap[conversionMap[oldTarget.uniqueId]];\n return newTarget || oldTarget;\n });\n result.animationGroups.push(clone);\n });\n return result;\n }\n /**\n * Adds all the assets from the container to the scene.\n */\n addAllToScene() {\n if (this._wasAddedToScene) {\n return;\n }\n if (!this._isValidHierarchy()) {\n Tools.Warn(\"SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid.\");\n }\n this._wasAddedToScene = true;\n this.addToScene(null);\n if (this.environmentTexture) {\n this.scene.environmentTexture = this.environmentTexture;\n }\n for (const component of this.scene._serializableComponents) {\n component.addFromContainer(this);\n }\n this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver);\n this._onContextRestoredObserver = null;\n }\n /**\n * Adds assets from the container to the scene.\n * @param predicate defines a predicate used to select which entity will be added (can be null)\n */\n addToScene(predicate = null) {\n this.cameras.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addCamera(o);\n });\n this.lights.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addLight(o);\n });\n this.meshes.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addMesh(o);\n });\n this.skeletons.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addSkeleton(o);\n });\n this.animations.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addAnimation(o);\n });\n this.animationGroups.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addAnimationGroup(o);\n });\n this.multiMaterials.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addMultiMaterial(o);\n });\n this.materials.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addMaterial(o);\n });\n this.morphTargetManagers.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addMorphTargetManager(o);\n });\n this.geometries.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addGeometry(o);\n });\n this.transformNodes.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addTransformNode(o);\n });\n this.actionManagers.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addActionManager(o);\n });\n this.textures.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addTexture(o);\n });\n this.reflectionProbes.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addReflectionProbe(o);\n });\n }\n /**\n * Removes all the assets in the container from the scene\n */\n removeAllFromScene() {\n if (!this._isValidHierarchy()) {\n Tools.Warn(\"SceneSerializer.removeAllFromScene: The Asset Container hierarchy is not valid.\");\n }\n this._wasAddedToScene = false;\n this.removeFromScene(null);\n if (this.environmentTexture === this.scene.environmentTexture) {\n this.scene.environmentTexture = null;\n }\n for (const component of this.scene._serializableComponents) {\n component.removeFromContainer(this);\n }\n }\n /**\n * Removes assets in the container from the scene\n * @param predicate defines a predicate used to select which entity will be added (can be null)\n */\n removeFromScene(predicate = null) {\n this.cameras.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeCamera(o);\n });\n this.lights.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeLight(o);\n });\n this.meshes.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeMesh(o);\n });\n this.skeletons.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeSkeleton(o);\n });\n this.animations.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeAnimation(o);\n });\n this.animationGroups.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeAnimationGroup(o);\n });\n this.multiMaterials.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeMultiMaterial(o);\n });\n this.materials.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeMaterial(o);\n });\n this.morphTargetManagers.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeMorphTargetManager(o);\n });\n this.geometries.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeGeometry(o);\n });\n this.transformNodes.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeTransformNode(o);\n });\n this.actionManagers.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeActionManager(o);\n });\n this.textures.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeTexture(o);\n });\n this.reflectionProbes.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeReflectionProbe(o);\n });\n }\n /**\n * Disposes all the assets in the container\n */\n dispose() {\n this.cameras.slice(0).forEach((o) => {\n o.dispose();\n });\n this.cameras.length = 0;\n this.lights.slice(0).forEach((o) => {\n o.dispose();\n });\n this.lights.length = 0;\n this.meshes.slice(0).forEach((o) => {\n o.dispose();\n });\n this.meshes.length = 0;\n this.skeletons.slice(0).forEach((o) => {\n o.dispose();\n });\n this.skeletons.length = 0;\n this.animationGroups.slice(0).forEach((o) => {\n o.dispose();\n });\n this.animationGroups.length = 0;\n this.multiMaterials.slice(0).forEach((o) => {\n o.dispose();\n });\n this.multiMaterials.length = 0;\n this.materials.slice(0).forEach((o) => {\n o.dispose();\n });\n this.materials.length = 0;\n this.geometries.slice(0).forEach((o) => {\n o.dispose();\n });\n this.geometries.length = 0;\n this.transformNodes.slice(0).forEach((o) => {\n o.dispose();\n });\n this.transformNodes.length = 0;\n this.actionManagers.slice(0).forEach((o) => {\n o.dispose();\n });\n this.actionManagers.length = 0;\n this.textures.slice(0).forEach((o) => {\n o.dispose();\n });\n this.textures.length = 0;\n this.reflectionProbes.slice(0).forEach((o) => {\n o.dispose();\n });\n this.reflectionProbes.length = 0;\n this.morphTargetManagers.slice(0).forEach((o) => {\n o.dispose();\n });\n this.morphTargetManagers.length = 0;\n if (this.environmentTexture) {\n this.environmentTexture.dispose();\n this.environmentTexture = null;\n }\n for (const component of this.scene._serializableComponents) {\n component.removeFromContainer(this, true);\n }\n if (this._onContextRestoredObserver) {\n this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver);\n this._onContextRestoredObserver = null;\n }\n }\n _moveAssets(sourceAssets, targetAssets, keepAssets) {\n if (!sourceAssets || !targetAssets) {\n return;\n }\n for (const asset of sourceAssets) {\n let move = true;\n if (keepAssets) {\n for (const keepAsset of keepAssets) {\n if (asset === keepAsset) {\n move = false;\n break;\n }\n }\n }\n if (move) {\n targetAssets.push(asset);\n asset._parentContainer = this;\n }\n }\n }\n /**\n * Removes all the assets contained in the scene and adds them to the container.\n * @param keepAssets Set of assets to keep in the scene. (default: empty)\n */\n moveAllFromScene(keepAssets) {\n this._wasAddedToScene = false;\n if (keepAssets === undefined) {\n keepAssets = new KeepAssets();\n }\n for (const key in this) {\n if (Object.prototype.hasOwnProperty.call(this, key)) {\n this[key] = this[key] || (key === \"_environmentTexture\" ? null : []);\n this._moveAssets(this.scene[key], this[key], keepAssets[key]);\n }\n }\n this.environmentTexture = this.scene.environmentTexture;\n this.removeAllFromScene();\n }\n /**\n * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.\n * @returns the root mesh\n */\n createRootMesh() {\n const rootMesh = new Mesh(\"assetContainerRootMesh\", this.scene);\n this.meshes.forEach((m) => {\n if (!m.parent) {\n rootMesh.addChild(m);\n }\n });\n this.meshes.unshift(rootMesh);\n return rootMesh;\n }\n /**\n * Merge animations (direct and animation groups) from this asset container into a scene\n * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)\n * @param animatables set of animatables to retarget to a node from the scene\n * @param targetConverter defines a function used to convert animation targets from the asset container to the scene (default: search node by name)\n * @returns an array of the new AnimationGroup added to the scene (empty array if none)\n */\n mergeAnimationsTo(scene = EngineStore.LastCreatedScene, animatables, targetConverter = null) {\n if (!scene) {\n Logger.Error(\"No scene available to merge animations to\");\n return [];\n }\n const _targetConverter = targetConverter\n ? targetConverter\n : (target) => {\n let node = null;\n const targetProperty = target.animations.length ? target.animations[0].targetProperty : \"\";\n /*\n BabylonJS adds special naming to targets that are children of nodes.\n This name attempts to remove that special naming to get the parent nodes name in case the target\n can't be found in the node tree\n\n Ex: Torso_primitive0 likely points to a Mesh primitive. We take away primitive0 and are left with \"Torso\" which is the name\n of the primitive's parent.\n */\n const name = target.name.split(\".\").join(\"\").split(\"_primitive\")[0];\n switch (targetProperty) {\n case \"position\":\n case \"rotationQuaternion\":\n node = scene.getTransformNodeByName(target.name) || scene.getTransformNodeByName(name);\n break;\n case \"influence\":\n node = scene.getMorphTargetByName(target.name) || scene.getMorphTargetByName(name);\n break;\n default:\n node = scene.getNodeByName(target.name) || scene.getNodeByName(name);\n }\n return node;\n };\n // Copy new node animations\n const nodesInAC = this.getNodes();\n nodesInAC.forEach((nodeInAC) => {\n const nodeInScene = _targetConverter(nodeInAC);\n if (nodeInScene !== null) {\n // Remove old animations with same target property as a new one\n for (const animationInAC of nodeInAC.animations) {\n // Doing treatment on an array for safety measure\n const animationsWithSameProperty = nodeInScene.animations.filter((animationInScene) => {\n return animationInScene.targetProperty === animationInAC.targetProperty;\n });\n for (const animationWithSameProperty of animationsWithSameProperty) {\n const index = nodeInScene.animations.indexOf(animationWithSameProperty, 0);\n if (index > -1) {\n nodeInScene.animations.splice(index, 1);\n }\n }\n }\n // Append new animations\n nodeInScene.animations = nodeInScene.animations.concat(nodeInAC.animations);\n }\n });\n const newAnimationGroups = new Array();\n // Copy new animation groups\n this.animationGroups.slice().forEach((animationGroupInAC) => {\n // Clone the animation group and all its animatables\n newAnimationGroups.push(animationGroupInAC.clone(animationGroupInAC.name, _targetConverter));\n // Remove animatables related to the asset container\n animationGroupInAC.animatables.forEach((animatable) => {\n animatable.stop();\n });\n });\n // Retarget animatables\n animatables.forEach((animatable) => {\n const target = _targetConverter(animatable.target);\n if (target) {\n // Clone the animatable and retarget it\n scene.beginAnimation(target, animatable.fromFrame, animatable.toFrame, animatable.loopAnimation, animatable.speedRatio, animatable.onAnimationEnd ? animatable.onAnimationEnd : undefined, undefined, true, undefined, animatable.onAnimationLoop ? animatable.onAnimationLoop : undefined);\n // Stop animation for the target in the asset container\n scene.stopAnimation(animatable.target);\n }\n });\n return newAnimationGroups;\n }\n}\n//# sourceMappingURL=assetContainer.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { IsWindowObjectExist } from \"../Misc/domManagement.js\";\n// Sets the default audio engine to Babylon.js\nEngine.AudioEngineFactory = (hostElement, audioContext, audioDestination) => {\n return new AudioEngine(hostElement, audioContext, audioDestination);\n};\n/**\n * This represents the default audio engine used in babylon.\n * It is responsible to play, synchronize and analyse sounds throughout the application.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic\n */\nexport class AudioEngine {\n /**\n * Gets the current AudioContext if available.\n */\n get audioContext() {\n if (!this._audioContextInitialized) {\n this._initializeAudioContext();\n }\n else {\n if (!this.unlocked && !this._muteButton) {\n this._displayMuteButton();\n }\n }\n return this._audioContext;\n }\n /**\n * Instantiates a new audio engine.\n *\n * There should be only one per page as some browsers restrict the number\n * of audio contexts you can create.\n * @param hostElement defines the host element where to display the mute icon if necessary\n * @param audioContext defines the audio context to be used by the audio engine\n * @param audioDestination defines the audio destination node to be used by audio engine\n */\n constructor(hostElement = null, audioContext = null, audioDestination = null) {\n this._audioContext = null;\n this._audioContextInitialized = false;\n this._muteButton = null;\n this._audioDestination = null;\n /**\n * Gets whether the current host supports Web Audio and thus could create AudioContexts.\n */\n this.canUseWebAudio = false;\n /**\n * Defines if Babylon should emit a warning if WebAudio is not supported.\n * @ignoreNaming\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n this.WarnedWebAudioUnsupported = false;\n /**\n * Gets whether or not mp3 are supported by your browser.\n */\n this.isMP3supported = false;\n /**\n * Gets whether or not ogg are supported by your browser.\n */\n this.isOGGsupported = false;\n /**\n * Gets whether audio has been unlocked on the device.\n * Some Browsers have strong restrictions about Audio and won t autoplay unless\n * a user interaction has happened.\n */\n this.unlocked = true;\n /**\n * Defines if the audio engine relies on a custom unlocked button.\n * In this case, the embedded button will not be displayed.\n */\n this.useCustomUnlockedButton = false;\n /**\n * Event raised when audio has been unlocked on the browser.\n */\n this.onAudioUnlockedObservable = new Observable();\n /**\n * Event raised when audio has been locked on the browser.\n */\n this.onAudioLockedObservable = new Observable();\n this._tryToRun = false;\n this._onResize = () => {\n this._moveButtonToTopLeft();\n };\n if (!IsWindowObjectExist()) {\n return;\n }\n if (typeof window.AudioContext !== \"undefined\") {\n this.canUseWebAudio = true;\n }\n const audioElem = document.createElement(\"audio\");\n this._hostElement = hostElement;\n this._audioContext = audioContext;\n this._audioDestination = audioDestination;\n try {\n if (audioElem &&\n !!audioElem.canPlayType &&\n (audioElem.canPlayType('audio/mpeg; codecs=\"mp3\"').replace(/^no$/, \"\") || audioElem.canPlayType(\"audio/mp3\").replace(/^no$/, \"\"))) {\n this.isMP3supported = true;\n }\n }\n catch (e) {\n // protect error during capability check.\n }\n try {\n if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs=\"vorbis\"').replace(/^no$/, \"\")) {\n this.isOGGsupported = true;\n }\n }\n catch (e) {\n // protect error during capability check.\n }\n }\n /**\n * Flags the audio engine in Locked state.\n * This happens due to new browser policies preventing audio to autoplay.\n */\n lock() {\n this._triggerSuspendedState();\n }\n /**\n * Unlocks the audio engine once a user action has been done on the dom.\n * This is helpful to resume play once browser policies have been satisfied.\n */\n unlock() {\n this._triggerRunningState();\n }\n _resumeAudioContext() {\n let result;\n if (this._audioContext.resume !== undefined) {\n result = this._audioContext.resume();\n }\n return result || Promise.resolve();\n }\n _initializeAudioContext() {\n try {\n if (this.canUseWebAudio) {\n if (!this._audioContext) {\n this._audioContext = new AudioContext();\n }\n // create a global volume gain node\n this.masterGain = this._audioContext.createGain();\n this.masterGain.gain.value = 1;\n if (!this._audioDestination) {\n this._audioDestination = this._audioContext.destination;\n }\n this.masterGain.connect(this._audioDestination);\n this._audioContextInitialized = true;\n if (this._audioContext.state === \"running\") {\n // Do not wait for the promise to unlock.\n this._triggerRunningState();\n }\n }\n }\n catch (e) {\n this.canUseWebAudio = false;\n Logger.Error(\"Web Audio: \" + e.message);\n }\n }\n _triggerRunningState() {\n if (this._tryToRun) {\n return;\n }\n this._tryToRun = true;\n this._resumeAudioContext()\n .then(() => {\n this._tryToRun = false;\n if (this._muteButton) {\n this._hideMuteButton();\n }\n // Notify users that the audio stack is unlocked/unmuted\n this.unlocked = true;\n this.onAudioUnlockedObservable.notifyObservers(this);\n })\n .catch(() => {\n this._tryToRun = false;\n this.unlocked = false;\n });\n }\n _triggerSuspendedState() {\n this.unlocked = false;\n this.onAudioLockedObservable.notifyObservers(this);\n this._displayMuteButton();\n }\n _displayMuteButton() {\n if (this.useCustomUnlockedButton || this._muteButton) {\n return;\n }\n this._muteButton = document.createElement(\"BUTTON\");\n this._muteButton.className = \"babylonUnmuteIcon\";\n this._muteButton.id = \"babylonUnmuteIconBtn\";\n this._muteButton.title = \"Unmute\";\n const imageUrl = !window.SVGSVGElement\n ? \"https://cdn.babylonjs.com/Assets/audio.png\"\n : \"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\";\n const css = \".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url(\" +\n imageUrl +\n \"); 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) }\";\n const style = document.createElement(\"style\");\n style.appendChild(document.createTextNode(css));\n document.getElementsByTagName(\"head\")[0].appendChild(style);\n document.body.appendChild(this._muteButton);\n this._moveButtonToTopLeft();\n this._muteButton.addEventListener(\"touchend\", () => {\n this._triggerRunningState();\n }, true);\n this._muteButton.addEventListener(\"click\", () => {\n this._triggerRunningState();\n }, true);\n window.addEventListener(\"resize\", this._onResize);\n }\n _moveButtonToTopLeft() {\n if (this._hostElement && this._muteButton) {\n this._muteButton.style.top = this._hostElement.offsetTop + 20 + \"px\";\n this._muteButton.style.left = this._hostElement.offsetLeft + 20 + \"px\";\n }\n }\n _hideMuteButton() {\n if (this._muteButton) {\n document.body.removeChild(this._muteButton);\n this._muteButton = null;\n }\n }\n /**\n * Destroy and release the resources associated with the audio context.\n */\n dispose() {\n if (this.canUseWebAudio && this._audioContextInitialized) {\n if (this._connectedAnalyser && this._audioContext) {\n this._connectedAnalyser.stopDebugCanvas();\n this._connectedAnalyser.dispose();\n this.masterGain.disconnect();\n this.masterGain.connect(this._audioContext.destination);\n this._connectedAnalyser = null;\n }\n this.masterGain.gain.value = 1;\n }\n this.WarnedWebAudioUnsupported = false;\n this._hideMuteButton();\n window.removeEventListener(\"resize\", this._onResize);\n this.onAudioUnlockedObservable.clear();\n this.onAudioLockedObservable.clear();\n }\n /**\n * Gets the global volume sets on the master gain.\n * @returns the global volume if set or -1 otherwise\n */\n getGlobalVolume() {\n if (this.canUseWebAudio && this._audioContextInitialized) {\n return this.masterGain.gain.value;\n }\n else {\n return -1;\n }\n }\n /**\n * Sets the global volume of your experience (sets on the master gain).\n * @param newVolume Defines the new global volume of the application\n */\n setGlobalVolume(newVolume) {\n if (this.canUseWebAudio && this._audioContextInitialized) {\n this.masterGain.gain.value = newVolume;\n }\n }\n /**\n * Connect the audio engine to an audio analyser allowing some amazing\n * synchronization between the sounds/music and your visualization (VuMeter for instance).\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#using-the-analyser\n * @param analyser The analyser to connect to the engine\n */\n connectToAnalyser(analyser) {\n if (this._connectedAnalyser) {\n this._connectedAnalyser.stopDebugCanvas();\n }\n if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {\n this._connectedAnalyser = analyser;\n this.masterGain.disconnect();\n this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);\n }\n }\n}\n//# sourceMappingURL=audioEngine.js.map","import { Tools } from \"../Misc/tools.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { _WarnImport } from \"../Misc/devTools.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n/**\n * Defines a sound that can be played in the application.\n * The sound can either be an ambient track or a simple sound played in reaction to a user action.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic\n */\nexport class Sound {\n /**\n * Does the sound loop after it finishes playing once.\n */\n get loop() {\n return this._loop;\n }\n set loop(value) {\n if (value === this._loop) {\n return;\n }\n this._loop = value;\n this.updateOptions({ loop: value });\n }\n /**\n * Gets the current time for the sound.\n */\n get currentTime() {\n var _a;\n if (this._htmlAudioElement) {\n return this._htmlAudioElement.currentTime;\n }\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.audioContext) && (this.isPlaying || this.isPaused)) {\n // The `_currentTime` member is only updated when the sound is paused. Add the time since the last start\n // to get the actual current time.\n const timeSinceLastStart = this.isPaused ? 0 : Engine.audioEngine.audioContext.currentTime - this._startTime;\n return this._currentTime + timeSinceLastStart;\n }\n return 0;\n }\n /**\n * Does this sound enables spatial sound.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound\n */\n get spatialSound() {\n return this._spatialSound;\n }\n /**\n * Does this sound enables spatial sound.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound\n */\n set spatialSound(newValue) {\n var _a;\n this._spatialSound = newValue;\n if (this._spatialSound && ((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && Engine.audioEngine.audioContext) {\n this._createSpatialParameters();\n }\n }\n /**\n * Create a sound and attach it to a scene\n * @param name Name of your sound\n * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams and AudioBuffers\n * @param scene defines the scene the sound belongs to\n * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played\n * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming\n */\n constructor(name, urlOrArrayBuffer, scene, readyToPlayCallback = null, options) {\n var _a, _b, _c, _d, _e;\n /**\n * Does the sound autoplay once loaded.\n */\n this.autoplay = false;\n this._loop = false;\n /**\n * Does the sound use a custom attenuation curve to simulate the falloff\n * happening when the source gets further away from the camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-your-own-custom-attenuation-function\n */\n this.useCustomAttenuation = false;\n /**\n * Is this sound currently played.\n */\n this.isPlaying = false;\n /**\n * Is this sound currently paused.\n */\n this.isPaused = false;\n /**\n * Define the reference distance the sound should be heard perfectly.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound\n */\n this.refDistance = 1;\n /**\n * Define the roll off factor of spatial sounds.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound\n */\n this.rolloffFactor = 1;\n /**\n * Define the max distance the sound should be heard (intensity just became 0 at this point).\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound\n */\n this.maxDistance = 100;\n /**\n * Define the distance attenuation model the sound will follow.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound\n */\n this.distanceModel = \"linear\";\n /**\n * Gets or sets an object used to store user defined information for the sound.\n */\n this.metadata = null;\n /**\n * Observable event when the current playing sound finishes.\n */\n this.onEndedObservable = new Observable();\n this._spatialSound = false;\n this._panningModel = \"equalpower\";\n this._playbackRate = 1;\n this._streaming = false;\n this._startTime = 0;\n this._currentTime = 0;\n this._position = Vector3.Zero();\n this._localDirection = new Vector3(1, 0, 0);\n this._volume = 1;\n this._isReadyToPlay = false;\n this._isDirectional = false;\n // Used if you'd like to create a directional sound.\n // If not set, the sound will be omnidirectional\n this._coneInnerAngle = 360;\n this._coneOuterAngle = 360;\n this._coneOuterGain = 0;\n this._isOutputConnected = false;\n this._urlType = \"Unknown\";\n this.name = name;\n scene = scene || EngineStore.LastCreatedScene;\n if (!scene) {\n return;\n }\n this._scene = scene;\n Sound._SceneComponentInitialization(scene);\n this._readyToPlayCallback = readyToPlayCallback;\n // Default custom attenuation function is a linear attenuation\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this._customAttenuationFunction = (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) => {\n if (currentDistance < maxDistance) {\n return currentVolume * (1 - currentDistance / maxDistance);\n }\n else {\n return 0;\n }\n };\n if (options) {\n this.autoplay = options.autoplay || false;\n this._loop = options.loop || false;\n // if volume === 0, we need another way to check this option\n if (options.volume !== undefined) {\n this._volume = options.volume;\n }\n this._spatialSound = (_a = options.spatialSound) !== null && _a !== void 0 ? _a : false;\n this.maxDistance = (_b = options.maxDistance) !== null && _b !== void 0 ? _b : 100;\n this.useCustomAttenuation = (_c = options.useCustomAttenuation) !== null && _c !== void 0 ? _c : false;\n this.rolloffFactor = options.rolloffFactor || 1;\n this.refDistance = options.refDistance || 1;\n this.distanceModel = options.distanceModel || \"linear\";\n this._playbackRate = options.playbackRate || 1;\n this._streaming = (_d = options.streaming) !== null && _d !== void 0 ? _d : false;\n this._length = options.length;\n this._offset = options.offset;\n }\n if (((_e = Engine.audioEngine) === null || _e === void 0 ? void 0 : _e.canUseWebAudio) && Engine.audioEngine.audioContext) {\n this._soundGain = Engine.audioEngine.audioContext.createGain();\n this._soundGain.gain.value = this._volume;\n this._inputAudioNode = this._soundGain;\n this._outputAudioNode = this._soundGain;\n if (this._spatialSound) {\n this._createSpatialParameters();\n }\n this._scene.mainSoundTrack.addSound(this);\n let validParameter = true;\n // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound\n if (urlOrArrayBuffer) {\n try {\n if (typeof urlOrArrayBuffer === \"string\") {\n this._urlType = \"String\";\n }\n else if (urlOrArrayBuffer instanceof ArrayBuffer) {\n this._urlType = \"ArrayBuffer\";\n }\n else if (urlOrArrayBuffer instanceof HTMLMediaElement) {\n this._urlType = \"MediaElement\";\n }\n else if (urlOrArrayBuffer instanceof MediaStream) {\n this._urlType = \"MediaStream\";\n }\n else if (urlOrArrayBuffer instanceof AudioBuffer) {\n this._urlType = \"AudioBuffer\";\n }\n else if (Array.isArray(urlOrArrayBuffer)) {\n this._urlType = \"Array\";\n }\n let urls = [];\n let codecSupportedFound = false;\n switch (this._urlType) {\n case \"MediaElement\":\n this._streaming = true;\n this._isReadyToPlay = true;\n this._streamingSource = Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);\n if (this.autoplay) {\n this.play(0, this._offset, this._length);\n }\n if (this._readyToPlayCallback) {\n this._readyToPlayCallback();\n }\n break;\n case \"MediaStream\":\n this._streaming = true;\n this._isReadyToPlay = true;\n this._streamingSource = Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);\n if (this.autoplay) {\n this.play(0, this._offset, this._length);\n }\n if (this._readyToPlayCallback) {\n this._readyToPlayCallback();\n }\n break;\n case \"ArrayBuffer\":\n if (urlOrArrayBuffer.byteLength > 0) {\n codecSupportedFound = true;\n this._soundLoaded(urlOrArrayBuffer);\n }\n break;\n case \"AudioBuffer\":\n this._audioBufferLoaded(urlOrArrayBuffer);\n break;\n case \"String\":\n urls.push(urlOrArrayBuffer);\n // eslint-disable-next-line no-fallthrough\n case \"Array\":\n if (urls.length === 0) {\n urls = urlOrArrayBuffer;\n }\n // If we found a supported format, we load it immediately and stop the loop\n for (let i = 0; i < urls.length; i++) {\n const url = urls[i];\n codecSupportedFound =\n (options && options.skipCodecCheck) ||\n (url.indexOf(\".mp3\", url.length - 4) !== -1 && Engine.audioEngine.isMP3supported) ||\n (url.indexOf(\".ogg\", url.length - 4) !== -1 && Engine.audioEngine.isOGGsupported) ||\n url.indexOf(\".wav\", url.length - 4) !== -1 ||\n url.indexOf(\".m4a\", url.length - 4) !== -1 ||\n url.indexOf(\".mp4\", url.length - 4) !== -1 ||\n url.indexOf(\"blob:\") !== -1;\n if (codecSupportedFound) {\n // Loading sound\n if (!this._streaming) {\n this._scene._loadFile(url, (data) => {\n this._soundLoaded(data);\n }, undefined, true, true, (exception) => {\n if (exception) {\n Logger.Error(\"XHR \" + exception.status + \" error on: \" + url + \".\");\n }\n Logger.Error(\"Sound creation aborted.\");\n this._scene.mainSoundTrack.removeSound(this);\n });\n }\n // Streaming sound using HTML5 Audio tag\n else {\n this._htmlAudioElement = new Audio(url);\n this._htmlAudioElement.controls = false;\n this._htmlAudioElement.loop = this.loop;\n Tools.SetCorsBehavior(url, this._htmlAudioElement);\n this._htmlAudioElement.preload = \"auto\";\n this._htmlAudioElement.addEventListener(\"canplaythrough\", () => {\n this._isReadyToPlay = true;\n if (this.autoplay) {\n this.play(0, this._offset, this._length);\n }\n if (this._readyToPlayCallback) {\n this._readyToPlayCallback();\n }\n });\n document.body.appendChild(this._htmlAudioElement);\n this._htmlAudioElement.load();\n }\n break;\n }\n }\n break;\n default:\n validParameter = false;\n break;\n }\n if (!validParameter) {\n Logger.Error(\"Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.\");\n }\n else {\n if (!codecSupportedFound) {\n this._isReadyToPlay = true;\n // Simulating a ready to play event to avoid breaking code path\n if (this._readyToPlayCallback) {\n setTimeout(() => {\n if (this._readyToPlayCallback) {\n this._readyToPlayCallback();\n }\n }, 1000);\n }\n }\n }\n }\n catch (ex) {\n Logger.Error(\"Unexpected error. Sound creation aborted.\");\n this._scene.mainSoundTrack.removeSound(this);\n }\n }\n }\n else {\n // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers\n this._scene.mainSoundTrack.addSound(this);\n if (Engine.audioEngine && !Engine.audioEngine.WarnedWebAudioUnsupported) {\n Logger.Error(\"Web Audio is not supported by your browser.\");\n Engine.audioEngine.WarnedWebAudioUnsupported = true;\n }\n // Simulating a ready to play event to avoid breaking code for non web audio browsers\n if (this._readyToPlayCallback) {\n setTimeout(() => {\n if (this._readyToPlayCallback) {\n this._readyToPlayCallback();\n }\n }, 1000);\n }\n }\n }\n /**\n * Release the sound and its associated resources\n */\n dispose() {\n var _a;\n if ((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) {\n if (this.isPlaying) {\n this.stop();\n }\n this._isReadyToPlay = false;\n if (this.soundTrackId === -1) {\n this._scene.mainSoundTrack.removeSound(this);\n }\n else if (this._scene.soundTracks) {\n this._scene.soundTracks[this.soundTrackId].removeSound(this);\n }\n if (this._soundGain) {\n this._soundGain.disconnect();\n this._soundGain = null;\n }\n if (this._soundPanner) {\n this._soundPanner.disconnect();\n this._soundPanner = null;\n }\n if (this._soundSource) {\n this._soundSource.disconnect();\n this._soundSource = null;\n }\n this._audioBuffer = null;\n if (this._htmlAudioElement) {\n this._htmlAudioElement.pause();\n this._htmlAudioElement.src = \"\";\n document.body.removeChild(this._htmlAudioElement);\n }\n if (this._streamingSource) {\n this._streamingSource.disconnect();\n }\n if (this._connectedTransformNode && this._registerFunc) {\n this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc);\n this._connectedTransformNode = null;\n }\n }\n }\n /**\n * Gets if the sounds is ready to be played or not.\n * @returns true if ready, otherwise false\n */\n isReady() {\n return this._isReadyToPlay;\n }\n /**\n * Get the current class name.\n * @returns current class name\n */\n getClassName() {\n return \"Sound\";\n }\n _audioBufferLoaded(buffer) {\n var _a;\n if (!((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.audioContext)) {\n return;\n }\n this._audioBuffer = buffer;\n this._isReadyToPlay = true;\n if (this.autoplay) {\n this.play(0, this._offset, this._length);\n }\n if (this._readyToPlayCallback) {\n this._readyToPlayCallback();\n }\n }\n _soundLoaded(audioData) {\n var _a;\n if (!((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.audioContext)) {\n return;\n }\n Engine.audioEngine.audioContext.decodeAudioData(audioData, (buffer) => {\n this._audioBufferLoaded(buffer);\n }, (err) => {\n Logger.Error(\"Error while decoding audio data for: \" + this.name + \" / Error: \" + err);\n });\n }\n /**\n * Sets the data of the sound from an audiobuffer\n * @param audioBuffer The audioBuffer containing the data\n */\n setAudioBuffer(audioBuffer) {\n var _a;\n if ((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) {\n this._audioBuffer = audioBuffer;\n this._isReadyToPlay = true;\n }\n }\n /**\n * Updates the current sounds options such as maxdistance, loop...\n * @param options A JSON object containing values named as the object properties\n */\n updateOptions(options) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;\n if (options) {\n this.loop = (_a = options.loop) !== null && _a !== void 0 ? _a : this.loop;\n this.maxDistance = (_b = options.maxDistance) !== null && _b !== void 0 ? _b : this.maxDistance;\n this.useCustomAttenuation = (_c = options.useCustomAttenuation) !== null && _c !== void 0 ? _c : this.useCustomAttenuation;\n this.rolloffFactor = (_d = options.rolloffFactor) !== null && _d !== void 0 ? _d : this.rolloffFactor;\n this.refDistance = (_e = options.refDistance) !== null && _e !== void 0 ? _e : this.refDistance;\n this.distanceModel = (_f = options.distanceModel) !== null && _f !== void 0 ? _f : this.distanceModel;\n this._playbackRate = (_g = options.playbackRate) !== null && _g !== void 0 ? _g : this._playbackRate;\n this._length = (_h = options.length) !== null && _h !== void 0 ? _h : undefined;\n this._setOffset((_j = options.offset) !== null && _j !== void 0 ? _j : undefined);\n this.setVolume((_k = options.volume) !== null && _k !== void 0 ? _k : this._volume);\n this._updateSpatialParameters();\n if (this.isPlaying) {\n if (this._streaming && this._htmlAudioElement) {\n this._htmlAudioElement.playbackRate = this._playbackRate;\n if (this._htmlAudioElement.loop !== this.loop) {\n this._htmlAudioElement.loop = this.loop;\n }\n }\n else {\n if (this._soundSource) {\n this._soundSource.playbackRate.value = this._playbackRate;\n if (this._soundSource.loop !== this.loop) {\n this._soundSource.loop = this.loop;\n }\n if (this._offset !== undefined && this._soundSource.loopStart !== this._offset) {\n this._soundSource.loopStart = this._offset;\n }\n if (this._length !== undefined && this._length !== this._soundSource.loopEnd) {\n this._soundSource.loopEnd = (this._offset | 0) + this._length;\n }\n }\n }\n }\n }\n }\n _createSpatialParameters() {\n var _a, _b;\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && Engine.audioEngine.audioContext) {\n if (this._scene.headphone) {\n this._panningModel = \"HRTF\";\n }\n this._soundPanner = (_b = this._soundPanner) !== null && _b !== void 0 ? _b : Engine.audioEngine.audioContext.createPanner();\n if (this._soundPanner && this._outputAudioNode) {\n this._updateSpatialParameters();\n this._soundPanner.connect(this._outputAudioNode);\n this._inputAudioNode = this._soundPanner;\n }\n }\n }\n _updateSpatialParameters() {\n if (this._spatialSound && this._soundPanner) {\n if (this.useCustomAttenuation) {\n // Tricks to disable in a way embedded Web Audio attenuation\n this._soundPanner.distanceModel = \"linear\";\n this._soundPanner.maxDistance = Number.MAX_VALUE;\n this._soundPanner.refDistance = 1;\n this._soundPanner.rolloffFactor = 1;\n this._soundPanner.panningModel = this._panningModel;\n }\n else {\n this._soundPanner.distanceModel = this.distanceModel;\n this._soundPanner.maxDistance = this.maxDistance;\n this._soundPanner.refDistance = this.refDistance;\n this._soundPanner.rolloffFactor = this.rolloffFactor;\n this._soundPanner.panningModel = this._panningModel;\n }\n }\n }\n /**\n * Switch the panning model to HRTF:\n * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound\n */\n switchPanningModelToHRTF() {\n this._panningModel = \"HRTF\";\n this._switchPanningModel();\n }\n /**\n * Switch the panning model to Equal Power:\n * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound\n */\n switchPanningModelToEqualPower() {\n this._panningModel = \"equalpower\";\n this._switchPanningModel();\n }\n _switchPanningModel() {\n var _a;\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._spatialSound && this._soundPanner) {\n this._soundPanner.panningModel = this._panningModel;\n }\n }\n /**\n * Connect this sound to a sound track audio node like gain...\n * @param soundTrackAudioNode the sound track audio node to connect to\n */\n connectToSoundTrackAudioNode(soundTrackAudioNode) {\n var _a;\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._outputAudioNode) {\n if (this._isOutputConnected) {\n this._outputAudioNode.disconnect();\n }\n this._outputAudioNode.connect(soundTrackAudioNode);\n this._isOutputConnected = true;\n }\n }\n /**\n * Transform this sound into a directional source\n * @param coneInnerAngle Size of the inner cone in degree\n * @param coneOuterAngle Size of the outer cone in degree\n * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)\n */\n setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {\n if (coneOuterAngle < coneInnerAngle) {\n Logger.Error(\"setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.\");\n return;\n }\n this._coneInnerAngle = coneInnerAngle;\n this._coneOuterAngle = coneOuterAngle;\n this._coneOuterGain = coneOuterGain;\n this._isDirectional = true;\n if (this.isPlaying && this.loop) {\n this.stop();\n this.play(0, this._offset, this._length);\n }\n }\n /**\n * Gets or sets the inner angle for the directional cone.\n */\n get directionalConeInnerAngle() {\n return this._coneInnerAngle;\n }\n /**\n * Gets or sets the inner angle for the directional cone.\n */\n set directionalConeInnerAngle(value) {\n var _a;\n if (value != this._coneInnerAngle) {\n if (this._coneOuterAngle < value) {\n Logger.Error(\"directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.\");\n return;\n }\n this._coneInnerAngle = value;\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._spatialSound && this._soundPanner) {\n this._soundPanner.coneInnerAngle = this._coneInnerAngle;\n }\n }\n }\n /**\n * Gets or sets the outer angle for the directional cone.\n */\n get directionalConeOuterAngle() {\n return this._coneOuterAngle;\n }\n /**\n * Gets or sets the outer angle for the directional cone.\n */\n set directionalConeOuterAngle(value) {\n var _a;\n if (value != this._coneOuterAngle) {\n if (value < this._coneInnerAngle) {\n Logger.Error(\"directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.\");\n return;\n }\n this._coneOuterAngle = value;\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._spatialSound && this._soundPanner) {\n this._soundPanner.coneOuterAngle = this._coneOuterAngle;\n }\n }\n }\n /**\n * Sets the position of the emitter if spatial sound is enabled\n * @param newPosition Defines the new position\n */\n setPosition(newPosition) {\n var _a;\n if (newPosition.equals(this._position)) {\n return;\n }\n this._position.copyFrom(newPosition);\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {\n this._soundPanner.positionX.value = this._position.x;\n this._soundPanner.positionY.value = this._position.y;\n this._soundPanner.positionZ.value = this._position.z;\n }\n }\n /**\n * Sets the local direction of the emitter if spatial sound is enabled\n * @param newLocalDirection Defines the new local direction\n */\n setLocalDirectionToMesh(newLocalDirection) {\n var _a;\n this._localDirection = newLocalDirection;\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._connectedTransformNode && this.isPlaying) {\n this._updateDirection();\n }\n }\n _updateDirection() {\n if (!this._connectedTransformNode || !this._soundPanner) {\n return;\n }\n const mat = this._connectedTransformNode.getWorldMatrix();\n const direction = Vector3.TransformNormal(this._localDirection, mat);\n direction.normalize();\n this._soundPanner.orientationX.value = direction.x;\n this._soundPanner.orientationY.value = direction.y;\n this._soundPanner.orientationZ.value = direction.z;\n }\n /** @internal */\n updateDistanceFromListener() {\n var _a;\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._connectedTransformNode && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {\n const distance = this._scene.audioListenerPositionProvider\n ? this._connectedTransformNode.position.subtract(this._scene.audioListenerPositionProvider()).length()\n : this._connectedTransformNode.getDistanceToCamera(this._scene.activeCamera);\n this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);\n }\n }\n /**\n * Sets a new custom attenuation function for the sound.\n * @param callback Defines the function used for the attenuation\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-your-own-custom-attenuation-function\n */\n setAttenuationFunction(callback) {\n this._customAttenuationFunction = callback;\n }\n /**\n * Play the sound\n * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.\n * @param offset (optional) Start the sound at a specific time in seconds\n * @param length (optional) Sound duration (in seconds)\n */\n play(time, offset, length) {\n var _a, _b, _c, _d;\n if (this._isReadyToPlay && this._scene.audioEnabled && ((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.audioContext)) {\n try {\n let startTime = time ? ((_b = Engine.audioEngine) === null || _b === void 0 ? void 0 : _b.audioContext.currentTime) + time : (_c = Engine.audioEngine) === null || _c === void 0 ? void 0 : _c.audioContext.currentTime;\n if (!this._soundSource || !this._streamingSource) {\n if (this._spatialSound && this._soundPanner) {\n if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {\n this._soundPanner.positionX.value = this._position.x;\n this._soundPanner.positionY.value = this._position.y;\n this._soundPanner.positionZ.value = this._position.z;\n }\n if (this._isDirectional) {\n this._soundPanner.coneInnerAngle = this._coneInnerAngle;\n this._soundPanner.coneOuterAngle = this._coneOuterAngle;\n this._soundPanner.coneOuterGain = this._coneOuterGain;\n if (this._connectedTransformNode) {\n this._updateDirection();\n }\n else {\n this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);\n }\n }\n }\n }\n if (this._streaming) {\n if (!this._streamingSource) {\n this._streamingSource = Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);\n this._htmlAudioElement.onended = () => {\n this._onended();\n };\n this._htmlAudioElement.playbackRate = this._playbackRate;\n }\n this._streamingSource.disconnect();\n if (this._inputAudioNode) {\n this._streamingSource.connect(this._inputAudioNode);\n }\n if (this._htmlAudioElement) {\n // required to manage properly the new suspended default state of Chrome\n // When the option 'streaming: true' is used, we need first to wait for\n // the audio engine to be unlocked by a user gesture before trying to play\n // an HTML Audio element\n const tryToPlay = () => {\n var _a, _b;\n if ((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.unlocked) {\n const playPromise = this._htmlAudioElement.play();\n // In browsers that don’t yet support this functionality,\n // playPromise won’t be defined.\n if (playPromise !== undefined) {\n playPromise.catch(() => {\n var _a, _b;\n // Automatic playback failed.\n // Waiting for the audio engine to be unlocked by user click on unmute\n (_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.lock();\n if (this.loop || this.autoplay) {\n (_b = Engine.audioEngine) === null || _b === void 0 ? void 0 : _b.onAudioUnlockedObservable.addOnce(() => {\n tryToPlay();\n });\n }\n });\n }\n }\n else {\n if (this.loop || this.autoplay) {\n (_b = Engine.audioEngine) === null || _b === void 0 ? void 0 : _b.onAudioUnlockedObservable.addOnce(() => {\n tryToPlay();\n });\n }\n }\n };\n tryToPlay();\n }\n }\n else {\n const tryToPlay = () => {\n var _a, _b, _c, _d;\n if ((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.audioContext) {\n length = length || this._length;\n if (offset !== undefined) {\n this._setOffset(offset);\n }\n if (this._soundSource) {\n const oldSource = this._soundSource;\n oldSource.onended = () => {\n oldSource.disconnect();\n };\n }\n this._soundSource = (_b = Engine.audioEngine) === null || _b === void 0 ? void 0 : _b.audioContext.createBufferSource();\n if (this._soundSource && this._inputAudioNode) {\n this._soundSource.buffer = this._audioBuffer;\n this._soundSource.connect(this._inputAudioNode);\n this._soundSource.loop = this.loop;\n if (offset !== undefined) {\n this._soundSource.loopStart = offset;\n }\n if (length !== undefined) {\n this._soundSource.loopEnd = (offset | 0) + length;\n }\n this._soundSource.playbackRate.value = this._playbackRate;\n this._soundSource.onended = () => {\n this._onended();\n };\n startTime = time ? ((_c = Engine.audioEngine) === null || _c === void 0 ? void 0 : _c.audioContext.currentTime) + time : Engine.audioEngine.audioContext.currentTime;\n const actualOffset = ((this.isPaused ? this.currentTime : 0) + ((_d = this._offset) !== null && _d !== void 0 ? _d : 0)) % this._soundSource.buffer.duration;\n this._soundSource.start(startTime, actualOffset, this.loop ? undefined : length);\n }\n }\n };\n if (((_d = Engine.audioEngine) === null || _d === void 0 ? void 0 : _d.audioContext.state) === \"suspended\") {\n // Wait a bit for FF as context seems late to be ready.\n setTimeout(() => {\n var _a;\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.audioContext.state) === \"suspended\") {\n // Automatic playback failed.\n // Waiting for the audio engine to be unlocked by user click on unmute\n Engine.audioEngine.lock();\n if (this.loop || this.autoplay) {\n Engine.audioEngine.onAudioUnlockedObservable.addOnce(() => {\n tryToPlay();\n });\n }\n }\n else {\n tryToPlay();\n }\n }, 500);\n }\n else {\n tryToPlay();\n }\n }\n this._startTime = startTime;\n this.isPlaying = true;\n this.isPaused = false;\n }\n catch (ex) {\n Logger.Error(\"Error while trying to play audio: \" + this.name + \", \" + ex.message);\n }\n }\n }\n _onended() {\n this.isPlaying = false;\n this._startTime = 0;\n this._currentTime = 0;\n if (this.onended) {\n this.onended();\n }\n this.onEndedObservable.notifyObservers(this);\n }\n /**\n * Stop the sound\n * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.\n */\n stop(time) {\n var _a;\n if (this.isPlaying) {\n if (this._streaming) {\n if (this._htmlAudioElement) {\n this._htmlAudioElement.pause();\n // Test needed for Firefox or it will generate an Invalid State Error\n if (this._htmlAudioElement.currentTime > 0) {\n this._htmlAudioElement.currentTime = 0;\n }\n }\n else {\n this._streamingSource.disconnect();\n }\n this.isPlaying = false;\n }\n else if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.audioContext) && this._soundSource) {\n const stopTime = time ? Engine.audioEngine.audioContext.currentTime + time : undefined;\n this._soundSource.onended = () => {\n this.isPlaying = false;\n this.isPaused = false;\n this._startTime = 0;\n this._currentTime = 0;\n if (this._soundSource) {\n this._soundSource.onended = () => void 0;\n }\n this._onended();\n };\n this._soundSource.stop(stopTime);\n }\n }\n else if (this.isPaused) {\n this.isPaused = false;\n this._startTime = 0;\n this._currentTime = 0;\n }\n }\n /**\n * Put the sound in pause\n */\n pause() {\n var _a;\n if (this.isPlaying) {\n if (this._streaming) {\n if (this._htmlAudioElement) {\n this._htmlAudioElement.pause();\n }\n else {\n this._streamingSource.disconnect();\n }\n this.isPlaying = false;\n this.isPaused = true;\n }\n else if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.audioContext) && this._soundSource) {\n this._soundSource.onended = () => void 0;\n this._soundSource.stop();\n this.isPlaying = false;\n this.isPaused = true;\n this._currentTime += Engine.audioEngine.audioContext.currentTime - this._startTime;\n }\n }\n }\n /**\n * Sets a dedicated volume for this sounds\n * @param newVolume Define the new volume of the sound\n * @param time Define time for gradual change to new volume\n */\n setVolume(newVolume, time) {\n var _a;\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._soundGain) {\n if (time && Engine.audioEngine.audioContext) {\n this._soundGain.gain.cancelScheduledValues(Engine.audioEngine.audioContext.currentTime);\n this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, Engine.audioEngine.audioContext.currentTime);\n this._soundGain.gain.linearRampToValueAtTime(newVolume, Engine.audioEngine.audioContext.currentTime + time);\n }\n else {\n this._soundGain.gain.value = newVolume;\n }\n }\n this._volume = newVolume;\n }\n /**\n * Set the sound play back rate\n * @param newPlaybackRate Define the playback rate the sound should be played at\n */\n setPlaybackRate(newPlaybackRate) {\n this._playbackRate = newPlaybackRate;\n if (this.isPlaying) {\n if (this._streaming && this._htmlAudioElement) {\n this._htmlAudioElement.playbackRate = this._playbackRate;\n }\n else if (this._soundSource) {\n this._soundSource.playbackRate.value = this._playbackRate;\n }\n }\n }\n /**\n * Gets the sound play back rate.\n * @returns the play back rate of the sound\n */\n getPlaybackRate() {\n return this._playbackRate;\n }\n /**\n * Gets the volume of the sound.\n * @returns the volume of the sound\n */\n getVolume() {\n return this._volume;\n }\n /**\n * Attach the sound to a dedicated mesh\n * @param transformNode The transform node to connect the sound with\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#attaching-a-sound-to-a-mesh\n */\n attachToMesh(transformNode) {\n if (this._connectedTransformNode && this._registerFunc) {\n this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc);\n this._registerFunc = null;\n }\n this._connectedTransformNode = transformNode;\n if (!this._spatialSound) {\n this._spatialSound = true;\n this._createSpatialParameters();\n if (this.isPlaying && this.loop) {\n this.stop();\n this.play(0, this._offset, this._length);\n }\n }\n this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode);\n this._registerFunc = (transformNode) => this._onRegisterAfterWorldMatrixUpdate(transformNode);\n this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc);\n }\n /**\n * Detach the sound from the previously attached mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#attaching-a-sound-to-a-mesh\n */\n detachFromMesh() {\n if (this._connectedTransformNode && this._registerFunc) {\n this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc);\n this._registerFunc = null;\n this._connectedTransformNode = null;\n }\n }\n _onRegisterAfterWorldMatrixUpdate(node) {\n var _a;\n if (!node.getBoundingInfo) {\n this.setPosition(node.absolutePosition);\n }\n else {\n const mesh = node;\n const boundingInfo = mesh.getBoundingInfo();\n this.setPosition(boundingInfo.boundingSphere.centerWorld);\n }\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._isDirectional && this.isPlaying) {\n this._updateDirection();\n }\n }\n /**\n * Clone the current sound in the scene.\n * @returns the new sound clone\n */\n clone() {\n if (!this._streaming) {\n const setBufferAndRun = () => {\n if (this._isReadyToPlay) {\n clonedSound._audioBuffer = this.getAudioBuffer();\n clonedSound._isReadyToPlay = true;\n if (clonedSound.autoplay) {\n clonedSound.play(0, this._offset, this._length);\n }\n }\n else {\n setTimeout(setBufferAndRun, 300);\n }\n };\n const currentOptions = {\n autoplay: this.autoplay,\n loop: this.loop,\n volume: this._volume,\n spatialSound: this._spatialSound,\n maxDistance: this.maxDistance,\n useCustomAttenuation: this.useCustomAttenuation,\n rolloffFactor: this.rolloffFactor,\n refDistance: this.refDistance,\n distanceModel: this.distanceModel,\n };\n const clonedSound = new Sound(this.name + \"_cloned\", new ArrayBuffer(0), this._scene, null, currentOptions);\n if (this.useCustomAttenuation) {\n clonedSound.setAttenuationFunction(this._customAttenuationFunction);\n }\n clonedSound.setPosition(this._position);\n clonedSound.setPlaybackRate(this._playbackRate);\n setBufferAndRun();\n return clonedSound;\n }\n // Can't clone a streaming sound\n else {\n return null;\n }\n }\n /**\n * Gets the current underlying audio buffer containing the data\n * @returns the audio buffer\n */\n getAudioBuffer() {\n return this._audioBuffer;\n }\n /**\n * Gets the WebAudio AudioBufferSourceNode, lets you keep track of and stop instances of this Sound.\n * @returns the source node\n */\n getSoundSource() {\n return this._soundSource;\n }\n /**\n * Gets the WebAudio GainNode, gives you precise control over the gain of instances of this Sound.\n * @returns the gain node\n */\n getSoundGain() {\n return this._soundGain;\n }\n /**\n * Serializes the Sound in a JSON representation\n * @returns the JSON representation of the sound\n */\n serialize() {\n const serializationObject = {\n name: this.name,\n url: this.name,\n autoplay: this.autoplay,\n loop: this.loop,\n volume: this._volume,\n spatialSound: this._spatialSound,\n maxDistance: this.maxDistance,\n rolloffFactor: this.rolloffFactor,\n refDistance: this.refDistance,\n distanceModel: this.distanceModel,\n playbackRate: this._playbackRate,\n panningModel: this._panningModel,\n soundTrackId: this.soundTrackId,\n metadata: this.metadata,\n };\n if (this._spatialSound) {\n if (this._connectedTransformNode) {\n serializationObject.connectedMeshId = this._connectedTransformNode.id;\n }\n serializationObject.position = this._position.asArray();\n serializationObject.refDistance = this.refDistance;\n serializationObject.distanceModel = this.distanceModel;\n serializationObject.isDirectional = this._isDirectional;\n serializationObject.localDirectionToMesh = this._localDirection.asArray();\n serializationObject.coneInnerAngle = this._coneInnerAngle;\n serializationObject.coneOuterAngle = this._coneOuterAngle;\n serializationObject.coneOuterGain = this._coneOuterGain;\n }\n return serializationObject;\n }\n /**\n * Parse a JSON representation of a sound to instantiate in a given scene\n * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)\n * @param scene Define the scene the new parsed sound should be created in\n * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies\n * @param sourceSound Define a sound place holder if do not need to instantiate a new one\n * @returns the newly parsed sound\n */\n static Parse(parsedSound, scene, rootUrl, sourceSound) {\n const soundName = parsedSound.name;\n let soundUrl;\n if (parsedSound.url) {\n soundUrl = rootUrl + parsedSound.url;\n }\n else {\n soundUrl = rootUrl + soundName;\n }\n const options = {\n autoplay: parsedSound.autoplay,\n loop: parsedSound.loop,\n volume: parsedSound.volume,\n spatialSound: parsedSound.spatialSound,\n maxDistance: parsedSound.maxDistance,\n rolloffFactor: parsedSound.rolloffFactor,\n refDistance: parsedSound.refDistance,\n distanceModel: parsedSound.distanceModel,\n playbackRate: parsedSound.playbackRate,\n };\n let newSound;\n if (!sourceSound) {\n newSound = new Sound(soundName, soundUrl, scene, () => {\n scene.removePendingData(newSound);\n }, options);\n scene.addPendingData(newSound);\n }\n else {\n const setBufferAndRun = () => {\n if (sourceSound._isReadyToPlay) {\n newSound._audioBuffer = sourceSound.getAudioBuffer();\n newSound._isReadyToPlay = true;\n if (newSound.autoplay) {\n newSound.play(0, newSound._offset, newSound._length);\n }\n }\n else {\n setTimeout(setBufferAndRun, 300);\n }\n };\n newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);\n setBufferAndRun();\n }\n if (parsedSound.position) {\n const soundPosition = Vector3.FromArray(parsedSound.position);\n newSound.setPosition(soundPosition);\n }\n if (parsedSound.isDirectional) {\n newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);\n if (parsedSound.localDirectionToMesh) {\n const localDirectionToMesh = Vector3.FromArray(parsedSound.localDirectionToMesh);\n newSound.setLocalDirectionToMesh(localDirectionToMesh);\n }\n }\n if (parsedSound.connectedMeshId) {\n const connectedMesh = scene.getMeshById(parsedSound.connectedMeshId);\n if (connectedMesh) {\n newSound.attachToMesh(connectedMesh);\n }\n }\n if (parsedSound.metadata) {\n newSound.metadata = parsedSound.metadata;\n }\n return newSound;\n }\n _setOffset(value) {\n if (this._offset === value) {\n return;\n }\n if (this.isPaused) {\n this.stop();\n this.isPaused = false;\n }\n this._offset = value;\n }\n}\n/**\n * @internal\n */\nSound._SceneComponentInitialization = (_) => {\n throw _WarnImport(\"AudioSceneComponent\");\n};\n//# sourceMappingURL=sound.js.map","import { Engine } from \"../Engines/engine.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n/**\n * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.\n * It will be also used in a future release to apply effects on a specific track.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#using-sound-tracks\n */\nexport class SoundTrack {\n /**\n * Creates a new sound track.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#using-sound-tracks\n * @param scene Define the scene the sound track belongs to\n * @param options\n */\n constructor(scene, options = {}) {\n /**\n * The unique identifier of the sound track in the scene.\n */\n this.id = -1;\n this._isInitialized = false;\n scene = scene || EngineStore.LastCreatedScene;\n if (!scene) {\n return;\n }\n this._scene = scene;\n this.soundCollection = new Array();\n this._options = options;\n if (!this._options.mainTrack && this._scene.soundTracks) {\n this._scene.soundTracks.push(this);\n this.id = this._scene.soundTracks.length - 1;\n }\n }\n _initializeSoundTrackAudioGraph() {\n var _a;\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && Engine.audioEngine.audioContext) {\n this._outputAudioNode = Engine.audioEngine.audioContext.createGain();\n this._outputAudioNode.connect(Engine.audioEngine.masterGain);\n if (this._options) {\n if (this._options.volume) {\n this._outputAudioNode.gain.value = this._options.volume;\n }\n }\n this._isInitialized = true;\n }\n }\n /**\n * Release the sound track and its associated resources\n */\n dispose() {\n if (Engine.audioEngine && Engine.audioEngine.canUseWebAudio) {\n if (this._connectedAnalyser) {\n this._connectedAnalyser.stopDebugCanvas();\n }\n while (this.soundCollection.length) {\n this.soundCollection[0].dispose();\n }\n if (this._outputAudioNode) {\n this._outputAudioNode.disconnect();\n }\n this._outputAudioNode = null;\n }\n }\n /**\n * Adds a sound to this sound track\n * @param sound define the sound to add\n * @ignoreNaming\n */\n addSound(sound) {\n var _a;\n if (!this._isInitialized) {\n this._initializeSoundTrackAudioGraph();\n }\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._outputAudioNode) {\n sound.connectToSoundTrackAudioNode(this._outputAudioNode);\n }\n if (sound.soundTrackId) {\n if (sound.soundTrackId === -1) {\n this._scene.mainSoundTrack.removeSound(sound);\n }\n else if (this._scene.soundTracks) {\n this._scene.soundTracks[sound.soundTrackId].removeSound(sound);\n }\n }\n this.soundCollection.push(sound);\n sound.soundTrackId = this.id;\n }\n /**\n * Removes a sound to this sound track\n * @param sound define the sound to remove\n * @ignoreNaming\n */\n removeSound(sound) {\n const index = this.soundCollection.indexOf(sound);\n if (index !== -1) {\n this.soundCollection.splice(index, 1);\n }\n }\n /**\n * Set a global volume for the full sound track.\n * @param newVolume Define the new volume of the sound track\n */\n setVolume(newVolume) {\n var _a;\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._outputAudioNode) {\n this._outputAudioNode.gain.value = newVolume;\n }\n }\n /**\n * Switch the panning model to HRTF:\n * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound\n */\n switchPanningModelToHRTF() {\n var _a;\n if ((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) {\n for (let i = 0; i < this.soundCollection.length; i++) {\n this.soundCollection[i].switchPanningModelToHRTF();\n }\n }\n }\n /**\n * Switch the panning model to Equal Power:\n * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound\n */\n switchPanningModelToEqualPower() {\n var _a;\n if ((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) {\n for (let i = 0; i < this.soundCollection.length; i++) {\n this.soundCollection[i].switchPanningModelToEqualPower();\n }\n }\n }\n /**\n * Connect the sound track to an audio analyser allowing some amazing\n * synchronization between the sounds/music and your visualization (VuMeter for instance).\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#using-the-analyser\n * @param analyser The analyser to connect to the engine\n */\n connectToAnalyser(analyser) {\n var _a;\n if (this._connectedAnalyser) {\n this._connectedAnalyser.stopDebugCanvas();\n }\n this._connectedAnalyser = analyser;\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._outputAudioNode) {\n this._outputAudioNode.disconnect();\n this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, Engine.audioEngine.masterGain);\n }\n }\n}\n//# sourceMappingURL=soundTrack.js.map","import { Sound } from \"./sound.js\";\nimport { SoundTrack } from \"./soundTrack.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { Matrix, Vector3 } from \"../Maths/math.vector.js\";\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { Scene } from \"../scene.js\";\nimport { AbstractScene } from \"../abstractScene.js\";\nimport \"./audioEngine.js\";\nimport { PrecisionDate } from \"../Misc/precisionDate.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n// Adds the parser to the scene parsers.\nAbstractScene.AddParser(SceneComponentConstants.NAME_AUDIO, (parsedData, scene, container, rootUrl) => {\n var _a;\n // TODO: add sound\n let loadedSounds = [];\n let loadedSound;\n container.sounds = container.sounds || [];\n if (parsedData.sounds !== undefined && parsedData.sounds !== null) {\n for (let index = 0, cache = parsedData.sounds.length; index < cache; index++) {\n const parsedSound = parsedData.sounds[index];\n if ((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) {\n if (!parsedSound.url) {\n parsedSound.url = parsedSound.name;\n }\n if (!loadedSounds[parsedSound.url]) {\n loadedSound = Sound.Parse(parsedSound, scene, rootUrl);\n loadedSounds[parsedSound.url] = loadedSound;\n container.sounds.push(loadedSound);\n }\n else {\n container.sounds.push(Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));\n }\n }\n else {\n container.sounds.push(new Sound(parsedSound.name, null, scene));\n }\n }\n }\n loadedSounds = [];\n});\nObject.defineProperty(Scene.prototype, \"mainSoundTrack\", {\n get: function () {\n let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);\n if (!compo) {\n compo = new AudioSceneComponent(this);\n this._addComponent(compo);\n }\n if (!this._mainSoundTrack) {\n this._mainSoundTrack = new SoundTrack(this, { mainTrack: true });\n }\n return this._mainSoundTrack;\n },\n enumerable: true,\n configurable: true,\n});\nScene.prototype.getSoundByName = function (name) {\n let index;\n for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {\n if (this.mainSoundTrack.soundCollection[index].name === name) {\n return this.mainSoundTrack.soundCollection[index];\n }\n }\n if (this.soundTracks) {\n for (let sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {\n for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {\n if (this.soundTracks[sdIndex].soundCollection[index].name === name) {\n return this.soundTracks[sdIndex].soundCollection[index];\n }\n }\n }\n }\n return null;\n};\nObject.defineProperty(Scene.prototype, \"audioEnabled\", {\n get: function () {\n let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);\n if (!compo) {\n compo = new AudioSceneComponent(this);\n this._addComponent(compo);\n }\n return compo.audioEnabled;\n },\n set: function (value) {\n let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);\n if (!compo) {\n compo = new AudioSceneComponent(this);\n this._addComponent(compo);\n }\n if (value) {\n compo.enableAudio();\n }\n else {\n compo.disableAudio();\n }\n },\n enumerable: true,\n configurable: true,\n});\nObject.defineProperty(Scene.prototype, \"headphone\", {\n get: function () {\n let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);\n if (!compo) {\n compo = new AudioSceneComponent(this);\n this._addComponent(compo);\n }\n return compo.headphone;\n },\n set: function (value) {\n let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);\n if (!compo) {\n compo = new AudioSceneComponent(this);\n this._addComponent(compo);\n }\n if (value) {\n compo.switchAudioModeForHeadphones();\n }\n else {\n compo.switchAudioModeForNormalSpeakers();\n }\n },\n enumerable: true,\n configurable: true,\n});\nObject.defineProperty(Scene.prototype, \"audioListenerPositionProvider\", {\n get: function () {\n let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);\n if (!compo) {\n compo = new AudioSceneComponent(this);\n this._addComponent(compo);\n }\n return compo.audioListenerPositionProvider;\n },\n set: function (value) {\n let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);\n if (!compo) {\n compo = new AudioSceneComponent(this);\n this._addComponent(compo);\n }\n if (value && typeof value !== \"function\") {\n throw new Error(\"The value passed to [Scene.audioListenerPositionProvider] must be a function that returns a Vector3\");\n }\n else {\n compo.audioListenerPositionProvider = value;\n }\n },\n enumerable: true,\n configurable: true,\n});\nObject.defineProperty(Scene.prototype, \"audioListenerRotationProvider\", {\n get: function () {\n let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);\n if (!compo) {\n compo = new AudioSceneComponent(this);\n this._addComponent(compo);\n }\n return compo.audioListenerRotationProvider;\n },\n set: function (value) {\n let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);\n if (!compo) {\n compo = new AudioSceneComponent(this);\n this._addComponent(compo);\n }\n if (value && typeof value !== \"function\") {\n throw new Error(\"The value passed to [Scene.audioListenerRotationProvider] must be a function that returns a Vector3\");\n }\n else {\n compo.audioListenerRotationProvider = value;\n }\n },\n enumerable: true,\n configurable: true,\n});\nObject.defineProperty(Scene.prototype, \"audioPositioningRefreshRate\", {\n get: function () {\n let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);\n if (!compo) {\n compo = new AudioSceneComponent(this);\n this._addComponent(compo);\n }\n return compo.audioPositioningRefreshRate;\n },\n set: function (value) {\n let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);\n if (!compo) {\n compo = new AudioSceneComponent(this);\n this._addComponent(compo);\n }\n compo.audioPositioningRefreshRate = value;\n },\n enumerable: true,\n configurable: true,\n});\n/**\n * Defines the sound scene component responsible to manage any sounds\n * in a given scene.\n */\nexport class AudioSceneComponent {\n /**\n * Gets whether audio is enabled or not.\n * Please use related enable/disable method to switch state.\n */\n get audioEnabled() {\n return this._audioEnabled;\n }\n /**\n * Gets whether audio is outputting to headphone or not.\n * Please use the according Switch methods to change output.\n */\n get headphone() {\n return this._headphone;\n }\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpful to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_AUDIO;\n this._audioEnabled = true;\n this._headphone = false;\n /**\n * Gets or sets a refresh rate when using 3D audio positioning\n */\n this.audioPositioningRefreshRate = 500;\n /**\n * Gets or Sets a custom listener position for all sounds in the scene\n * By default, this is the position of the first active camera\n */\n this.audioListenerPositionProvider = null;\n /**\n * Gets or Sets a custom listener rotation for all sounds in the scene\n * By default, this is the rotation of the first active camera\n */\n this.audioListenerRotationProvider = null;\n this._cachedCameraDirection = new Vector3();\n this._cachedCameraPosition = new Vector3();\n this._lastCheck = 0;\n this._invertMatrixTemp = new Matrix();\n this._cameraDirectionTemp = new Vector3();\n scene = scene || EngineStore.LastCreatedScene;\n if (!scene) {\n return;\n }\n this.scene = scene;\n scene.soundTracks = new Array();\n scene.sounds = new Array();\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene._afterRenderStage.registerStep(SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n // Nothing to do here. (Not rendering related)\n }\n /**\n * Serializes the component data to the specified json object\n * @param serializationObject The object to serialize to\n */\n serialize(serializationObject) {\n serializationObject.sounds = [];\n if (this.scene.soundTracks) {\n for (let index = 0; index < this.scene.soundTracks.length; index++) {\n const soundtrack = this.scene.soundTracks[index];\n for (let soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {\n serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());\n }\n }\n }\n }\n /**\n * Adds all the elements from the container to the scene\n * @param container the container holding the elements\n */\n addFromContainer(container) {\n if (!container.sounds) {\n return;\n }\n container.sounds.forEach((sound) => {\n sound.play();\n sound.autoplay = true;\n this.scene.mainSoundTrack.addSound(sound);\n });\n }\n /**\n * Removes all the elements in the container from the scene\n * @param container contains the elements to remove\n * @param dispose if the removed element should be disposed (default: false)\n */\n removeFromContainer(container, dispose = false) {\n if (!container.sounds) {\n return;\n }\n container.sounds.forEach((sound) => {\n sound.stop();\n sound.autoplay = false;\n this.scene.mainSoundTrack.removeSound(sound);\n if (dispose) {\n sound.dispose();\n }\n });\n }\n /**\n * Disposes the component and the associated resources.\n */\n dispose() {\n const scene = this.scene;\n if (scene._mainSoundTrack) {\n scene.mainSoundTrack.dispose();\n }\n if (scene.soundTracks) {\n for (let scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {\n scene.soundTracks[scIndex].dispose();\n }\n }\n }\n /**\n * Disables audio in the associated scene.\n */\n disableAudio() {\n const scene = this.scene;\n this._audioEnabled = false;\n if (Engine.audioEngine && Engine.audioEngine.audioContext) {\n Engine.audioEngine.audioContext.suspend();\n }\n let i;\n for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {\n scene.mainSoundTrack.soundCollection[i].pause();\n }\n if (scene.soundTracks) {\n for (i = 0; i < scene.soundTracks.length; i++) {\n for (let j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {\n scene.soundTracks[i].soundCollection[j].pause();\n }\n }\n }\n }\n /**\n * Enables audio in the associated scene.\n */\n enableAudio() {\n const scene = this.scene;\n this._audioEnabled = true;\n if (Engine.audioEngine && Engine.audioEngine.audioContext) {\n Engine.audioEngine.audioContext.resume();\n }\n let i;\n for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {\n if (scene.mainSoundTrack.soundCollection[i].isPaused) {\n scene.mainSoundTrack.soundCollection[i].play();\n }\n }\n if (scene.soundTracks) {\n for (i = 0; i < scene.soundTracks.length; i++) {\n for (let j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {\n if (scene.soundTracks[i].soundCollection[j].isPaused) {\n scene.soundTracks[i].soundCollection[j].play();\n }\n }\n }\n }\n }\n /**\n * Switch audio to headphone output.\n */\n switchAudioModeForHeadphones() {\n const scene = this.scene;\n this._headphone = true;\n scene.mainSoundTrack.switchPanningModelToHRTF();\n if (scene.soundTracks) {\n for (let i = 0; i < scene.soundTracks.length; i++) {\n scene.soundTracks[i].switchPanningModelToHRTF();\n }\n }\n }\n /**\n * Switch audio to normal speakers.\n */\n switchAudioModeForNormalSpeakers() {\n const scene = this.scene;\n this._headphone = false;\n scene.mainSoundTrack.switchPanningModelToEqualPower();\n if (scene.soundTracks) {\n for (let i = 0; i < scene.soundTracks.length; i++) {\n scene.soundTracks[i].switchPanningModelToEqualPower();\n }\n }\n }\n _afterRender() {\n const now = PrecisionDate.Now;\n if (this._lastCheck && now - this._lastCheck < this.audioPositioningRefreshRate) {\n return;\n }\n this._lastCheck = now;\n const scene = this.scene;\n if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {\n return;\n }\n const audioEngine = Engine.audioEngine;\n if (!audioEngine) {\n return;\n }\n if (audioEngine.audioContext) {\n let listeningCamera = scene.activeCamera;\n if (scene.activeCameras && scene.activeCameras.length > 0) {\n listeningCamera = scene.activeCameras[0];\n }\n // A custom listener position provider was set\n // Use the users provided position instead of camera's\n if (this.audioListenerPositionProvider) {\n const position = this.audioListenerPositionProvider();\n // Set the listener position\n audioEngine.audioContext.listener.setPosition(position.x || 0, position.y || 0, position.z || 0);\n // Check if there is a listening camera\n }\n else if (listeningCamera) {\n // Set the listener position to the listening camera global position\n if (!this._cachedCameraPosition.equals(listeningCamera.globalPosition)) {\n this._cachedCameraPosition.copyFrom(listeningCamera.globalPosition);\n audioEngine.audioContext.listener.setPosition(listeningCamera.globalPosition.x, listeningCamera.globalPosition.y, listeningCamera.globalPosition.z);\n }\n }\n // Otherwise set the listener position to 0, 0 ,0\n else {\n // Set the listener position\n audioEngine.audioContext.listener.setPosition(0, 0, 0);\n }\n // A custom listener rotation provider was set\n // Use the users provided rotation instead of camera's\n if (this.audioListenerRotationProvider) {\n const rotation = this.audioListenerRotationProvider();\n audioEngine.audioContext.listener.setOrientation(rotation.x || 0, rotation.y || 0, rotation.z || 0, 0, 1, 0);\n // Check if there is a listening camera\n }\n else if (listeningCamera) {\n // for VR cameras\n if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {\n listeningCamera = listeningCamera.rigCameras[0];\n }\n listeningCamera.getViewMatrix().invertToRef(this._invertMatrixTemp);\n Vector3.TransformNormalToRef(AudioSceneComponent._CameraDirection, this._invertMatrixTemp, this._cameraDirectionTemp);\n this._cameraDirectionTemp.normalize();\n // To avoid some errors on GearVR\n if (!isNaN(this._cameraDirectionTemp.x) && !isNaN(this._cameraDirectionTemp.y) && !isNaN(this._cameraDirectionTemp.z)) {\n if (!this._cachedCameraDirection.equals(this._cameraDirectionTemp)) {\n this._cachedCameraDirection.copyFrom(this._cameraDirectionTemp);\n audioEngine.audioContext.listener.setOrientation(this._cameraDirectionTemp.x, this._cameraDirectionTemp.y, this._cameraDirectionTemp.z, 0, 1, 0);\n }\n }\n }\n // Otherwise set the listener rotation to 0, 0 ,0\n else {\n // Set the listener position\n audioEngine.audioContext.listener.setOrientation(0, 0, 0, 0, 1, 0);\n }\n let i;\n for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {\n const sound = scene.mainSoundTrack.soundCollection[i];\n if (sound.useCustomAttenuation) {\n sound.updateDistanceFromListener();\n }\n }\n if (scene.soundTracks) {\n for (i = 0; i < scene.soundTracks.length; i++) {\n for (let j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {\n const sound = scene.soundTracks[i].soundCollection[j];\n if (sound.useCustomAttenuation) {\n sound.updateDistanceFromListener();\n }\n }\n }\n }\n }\n }\n}\nAudioSceneComponent._CameraDirection = new Vector3(0, 0, -1);\nSound._SceneComponentInitialization = (scene) => {\n let compo = scene._getComponent(SceneComponentConstants.NAME_AUDIO);\n if (!compo) {\n compo = new AudioSceneComponent(scene);\n scene._addComponent(compo);\n }\n};\n//# sourceMappingURL=audioSceneComponent.js.map","import { Logger } from \"../Misc/logger.js\";\n/**\n * Wraps one or more Sound objects and selects one with random weight for playback.\n */\nexport class WeightedSound {\n /**\n * Creates a new WeightedSound from the list of sounds given.\n * @param loop When true a Sound will be selected and played when the current playing Sound completes.\n * @param sounds Array of Sounds that will be selected from.\n * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1\n */\n constructor(loop, sounds, weights) {\n /** When true a Sound will be selected and played when the current playing Sound completes. */\n this.loop = false;\n this._coneInnerAngle = 360;\n this._coneOuterAngle = 360;\n this._volume = 1;\n /** A Sound is currently playing. */\n this.isPlaying = false;\n /** A Sound is currently paused. */\n this.isPaused = false;\n this._sounds = [];\n this._weights = [];\n if (sounds.length !== weights.length) {\n throw new Error(\"Sounds length does not equal weights length\");\n }\n this.loop = loop;\n this._weights = weights;\n // Normalize the weights\n let weightSum = 0;\n for (const weight of weights) {\n weightSum += weight;\n }\n const invWeightSum = weightSum > 0 ? 1 / weightSum : 0;\n for (let i = 0; i < this._weights.length; i++) {\n this._weights[i] *= invWeightSum;\n }\n this._sounds = sounds;\n for (const sound of this._sounds) {\n sound.onEndedObservable.add(() => {\n this._onended();\n });\n }\n }\n /**\n * The size of cone in degrees for a directional sound in which there will be no attenuation.\n */\n get directionalConeInnerAngle() {\n return this._coneInnerAngle;\n }\n /**\n * The size of cone in degrees for a directional sound in which there will be no attenuation.\n */\n set directionalConeInnerAngle(value) {\n if (value !== this._coneInnerAngle) {\n if (this._coneOuterAngle < value) {\n Logger.Error(\"directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.\");\n return;\n }\n this._coneInnerAngle = value;\n for (const sound of this._sounds) {\n sound.directionalConeInnerAngle = value;\n }\n }\n }\n /**\n * Size of cone in degrees for a directional sound outside of which there will be no sound.\n * Listener angles between innerAngle and outerAngle will falloff linearly.\n */\n get directionalConeOuterAngle() {\n return this._coneOuterAngle;\n }\n /**\n * Size of cone in degrees for a directional sound outside of which there will be no sound.\n * Listener angles between innerAngle and outerAngle will falloff linearly.\n */\n set directionalConeOuterAngle(value) {\n if (value !== this._coneOuterAngle) {\n if (value < this._coneInnerAngle) {\n Logger.Error(\"directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.\");\n return;\n }\n this._coneOuterAngle = value;\n for (const sound of this._sounds) {\n sound.directionalConeOuterAngle = value;\n }\n }\n }\n /**\n * Playback volume.\n */\n get volume() {\n return this._volume;\n }\n /**\n * Playback volume.\n */\n set volume(value) {\n if (value !== this._volume) {\n for (const sound of this._sounds) {\n sound.setVolume(value);\n }\n }\n }\n _onended() {\n if (this._currentIndex !== undefined) {\n this._sounds[this._currentIndex].autoplay = false;\n }\n if (this.loop && this.isPlaying) {\n this.play();\n }\n else {\n this.isPlaying = false;\n }\n }\n /**\n * Suspend playback\n */\n pause() {\n this.isPaused = true;\n if (this._currentIndex !== undefined) {\n this._sounds[this._currentIndex].pause();\n }\n }\n /**\n * Stop playback\n */\n stop() {\n this.isPlaying = false;\n if (this._currentIndex !== undefined) {\n this._sounds[this._currentIndex].stop();\n }\n }\n /**\n * Start playback.\n * @param startOffset Position the clip head at a specific time in seconds.\n */\n play(startOffset) {\n if (!this.isPaused) {\n this.stop();\n const randomValue = Math.random();\n let total = 0;\n for (let i = 0; i < this._weights.length; i++) {\n total += this._weights[i];\n if (randomValue <= total) {\n this._currentIndex = i;\n break;\n }\n }\n }\n const sound = this._sounds[this._currentIndex];\n if (sound.isReady()) {\n sound.play(0, this.isPaused ? undefined : startOffset);\n }\n else {\n sound.autoplay = true;\n }\n this.isPlaying = true;\n this.isPaused = false;\n }\n}\n//# sourceMappingURL=weightedsound.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize, expandToProperty, serializeAsTexture, SerializationHelper } from \"../Misc/decorators.js\";\nimport { Vector4 } from \"../Maths/math.vector.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n/**\n * This class is used to animate meshes using a baked vertex animation texture\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/baked_texture_animations\n * @since 5.0\n */\nexport class BakedVertexAnimationManager {\n /**\n * Creates a new BakedVertexAnimationManager\n * @param scene defines the current scene\n */\n constructor(scene) {\n this._texture = null;\n this._isEnabled = true;\n /**\n * Enable or disable the vertex animation manager\n */\n this.isEnabled = true;\n /**\n * The time counter, to pick the correct animation frame.\n */\n this.time = 0;\n scene = scene || EngineStore.LastCreatedScene;\n if (!scene) {\n return;\n }\n this._scene = scene;\n this.animationParameters = new Vector4(0, 0, 0, 30);\n }\n /** @internal */\n _markSubMeshesAsAttributesDirty() {\n for (const mesh of this._scene.meshes) {\n if (mesh.bakedVertexAnimationManager === this) {\n mesh._markSubMeshesAsAttributesDirty();\n }\n }\n }\n /**\n * Binds to the effect.\n * @param effect The effect to bind to.\n * @param useInstances True when it's an instance.\n */\n bind(effect, useInstances = false) {\n if (!this._texture || !this._isEnabled) {\n return;\n }\n const size = this._texture.getSize();\n effect.setFloat2(\"bakedVertexAnimationTextureSizeInverted\", 1.0 / size.width, 1.0 / size.height);\n effect.setFloat(\"bakedVertexAnimationTime\", this.time);\n if (!useInstances) {\n effect.setVector4(\"bakedVertexAnimationSettings\", this.animationParameters);\n }\n effect.setTexture(\"bakedVertexAnimationTexture\", this._texture);\n }\n /**\n * Clone the current manager\n * @returns a new BakedVertexAnimationManager\n */\n clone() {\n const copy = new BakedVertexAnimationManager(this._scene);\n this.copyTo(copy);\n return copy;\n }\n /**\n * Sets animation parameters.\n * @param startFrame The first frame of the animation.\n * @param endFrame The last frame of the animation.\n * @param offset The offset when starting the animation.\n * @param speedFramesPerSecond The frame rate.\n */\n setAnimationParameters(startFrame, endFrame, offset = 0, speedFramesPerSecond = 30) {\n this.animationParameters = new Vector4(startFrame, endFrame, offset, speedFramesPerSecond);\n }\n /**\n * Disposes the resources of the manager.\n * @param forceDisposeTextures - Forces the disposal of all textures.\n */\n dispose(forceDisposeTextures) {\n var _a;\n if (forceDisposeTextures) {\n (_a = this._texture) === null || _a === void 0 ? void 0 : _a.dispose();\n }\n }\n /**\n * Get the current class name useful for serialization or dynamic coding.\n * @returns \"BakedVertexAnimationManager\"\n */\n getClassName() {\n return \"BakedVertexAnimationManager\";\n }\n /**\n * Makes a duplicate of the current instance into another one.\n * @param vatMap define the instance where to copy the info\n */\n copyTo(vatMap) {\n SerializationHelper.Clone(() => vatMap, this);\n }\n /**\n * Serializes this vertex animation instance\n * @returns - An object with the serialized instance.\n */\n serialize() {\n return SerializationHelper.Serialize(this);\n }\n /**\n * Parses a vertex animation setting from a serialized object.\n * @param source - Serialized object.\n * @param scene Defines the scene we are parsing for\n * @param rootUrl Defines the rootUrl to load from\n */\n parse(source, scene, rootUrl) {\n SerializationHelper.Parse(() => this, source, scene, rootUrl);\n }\n}\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markSubMeshesAsAttributesDirty\")\n], BakedVertexAnimationManager.prototype, \"texture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markSubMeshesAsAttributesDirty\")\n], BakedVertexAnimationManager.prototype, \"isEnabled\", void 0);\n__decorate([\n serialize()\n], BakedVertexAnimationManager.prototype, \"animationParameters\", void 0);\n__decorate([\n serialize()\n], BakedVertexAnimationManager.prototype, \"time\", void 0);\n//# sourceMappingURL=bakedVertexAnimationManager.js.map","\nimport { Size } from \"../../Maths/math.size.js\";\n/**\n * Base class of all the textures in babylon.\n * It groups all the common properties required to work with Thin Engine.\n */\nexport class ThinTexture {\n /**\n * | Value | Type | Description |\n * | ----- | ------------------ | ----------- |\n * | 0 | CLAMP_ADDRESSMODE | |\n * | 1 | WRAP_ADDRESSMODE | |\n * | 2 | MIRROR_ADDRESSMODE | |\n */\n get wrapU() {\n return this._wrapU;\n }\n set wrapU(value) {\n this._wrapU = value;\n }\n /**\n * | Value | Type | Description |\n * | ----- | ------------------ | ----------- |\n * | 0 | CLAMP_ADDRESSMODE | |\n * | 1 | WRAP_ADDRESSMODE | |\n * | 2 | MIRROR_ADDRESSMODE | |\n */\n get wrapV() {\n return this._wrapV;\n }\n set wrapV(value) {\n this._wrapV = value;\n }\n /**\n * How a texture is mapped.\n * Unused in thin texture mode.\n */\n get coordinatesMode() {\n return 0;\n }\n /**\n * Define if the texture is a cube texture or if false a 2d texture.\n */\n get isCube() {\n if (!this._texture) {\n return false;\n }\n return this._texture.isCube;\n }\n set isCube(value) {\n if (!this._texture) {\n return;\n }\n this._texture.isCube = value;\n }\n /**\n * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.\n */\n get is3D() {\n if (!this._texture) {\n return false;\n }\n return this._texture.is3D;\n }\n set is3D(value) {\n if (!this._texture) {\n return;\n }\n this._texture.is3D = value;\n }\n /**\n * Define if the texture is a 2d array texture (webgl 2) or if false a 2d texture.\n */\n get is2DArray() {\n if (!this._texture) {\n return false;\n }\n return this._texture.is2DArray;\n }\n set is2DArray(value) {\n if (!this._texture) {\n return;\n }\n this._texture.is2DArray = value;\n }\n /**\n * Get the class name of the texture.\n * @returns \"ThinTexture\"\n */\n getClassName() {\n return \"ThinTexture\";\n }\n static _IsRenderTargetWrapper(texture) {\n return (texture === null || texture === void 0 ? void 0 : texture._shareDepth) !== undefined;\n }\n /**\n * Instantiates a new ThinTexture.\n * Base class of all the textures in babylon.\n * This can be used as an internal texture wrapper in ThinEngine to benefit from the cache\n * @param internalTexture Define the internalTexture to wrap. You can also pass a RenderTargetWrapper, in which case the texture will be the render target's texture\n */\n constructor(internalTexture) {\n this._wrapU = 1;\n this._wrapV = 1;\n /**\n * | Value | Type | Description |\n * | ----- | ------------------ | ----------- |\n * | 0 | CLAMP_ADDRESSMODE | |\n * | 1 | WRAP_ADDRESSMODE | |\n * | 2 | MIRROR_ADDRESSMODE | |\n */\n this.wrapR = 1;\n /**\n * With compliant hardware and browser (supporting anisotropic filtering)\n * this defines the level of anisotropic filtering in the texture.\n * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.\n */\n this.anisotropicFilteringLevel = 4;\n /**\n * Define the current state of the loading sequence when in delayed load mode.\n */\n this.delayLoadState = 0;\n /** @internal */\n this._texture = null;\n this._engine = null;\n this._cachedSize = Size.Zero();\n this._cachedBaseSize = Size.Zero();\n /** @internal */\n this._initialSamplingMode = 2;\n this._texture = ThinTexture._IsRenderTargetWrapper(internalTexture) ? internalTexture.texture : internalTexture;\n if (this._texture) {\n this._engine = this._texture.getEngine();\n }\n }\n /**\n * Get if the texture is ready to be used (downloaded, converted, mip mapped...).\n * @returns true if fully ready\n */\n isReady() {\n if (this.delayLoadState === 4) {\n this.delayLoad();\n return false;\n }\n if (this._texture) {\n return this._texture.isReady;\n }\n return false;\n }\n /**\n * Triggers the load sequence in delayed load mode.\n */\n delayLoad() { }\n /**\n * Get the underlying lower level texture from Babylon.\n * @returns the internal texture\n */\n getInternalTexture() {\n return this._texture;\n }\n /**\n * Get the size of the texture.\n * @returns the texture size.\n */\n getSize() {\n if (this._texture) {\n if (this._texture.width) {\n this._cachedSize.width = this._texture.width;\n this._cachedSize.height = this._texture.height;\n return this._cachedSize;\n }\n if (this._texture._size) {\n this._cachedSize.width = this._texture._size;\n this._cachedSize.height = this._texture._size;\n return this._cachedSize;\n }\n }\n return this._cachedSize;\n }\n /**\n * Get the base size of the texture.\n * It can be different from the size if the texture has been resized for POT for instance\n * @returns the base size\n */\n getBaseSize() {\n if (!this.isReady() || !this._texture) {\n this._cachedBaseSize.width = 0;\n this._cachedBaseSize.height = 0;\n return this._cachedBaseSize;\n }\n if (this._texture._size) {\n this._cachedBaseSize.width = this._texture._size;\n this._cachedBaseSize.height = this._texture._size;\n return this._cachedBaseSize;\n }\n this._cachedBaseSize.width = this._texture.baseWidth;\n this._cachedBaseSize.height = this._texture.baseHeight;\n return this._cachedBaseSize;\n }\n /**\n * Get the current sampling mode associated with the texture.\n */\n get samplingMode() {\n if (!this._texture) {\n return this._initialSamplingMode;\n }\n return this._texture.samplingMode;\n }\n /**\n * Update the sampling mode of the texture.\n * Default is Trilinear mode.\n *\n * | Value | Type | Description |\n * | ----- | ------------------ | ----------- |\n * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |\n * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |\n * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |\n * | 4 | NEAREST_NEAREST_MIPNEAREST | |\n * | 5 | NEAREST_LINEAR_MIPNEAREST | |\n * | 6 | NEAREST_LINEAR_MIPLINEAR | |\n * | 7 | NEAREST_LINEAR | |\n * | 8 | NEAREST_NEAREST | |\n * | 9 | LINEAR_NEAREST_MIPNEAREST | |\n * | 10 | LINEAR_NEAREST_MIPLINEAR | |\n * | 11 | LINEAR_LINEAR | |\n * | 12 | LINEAR_NEAREST | |\n *\n * > _mag_: magnification filter (close to the viewer)\n * > _min_: minification filter (far from the viewer)\n * > _mip_: filter used between mip map levels\n *@param samplingMode Define the new sampling mode of the texture\n */\n updateSamplingMode(samplingMode) {\n if (this._texture && this._engine) {\n this._engine.updateTextureSamplingMode(samplingMode, this._texture);\n }\n }\n /**\n * Release and destroy the underlying lower level texture aka internalTexture.\n */\n releaseInternalTexture() {\n if (this._texture) {\n this._texture.dispose();\n this._texture = null;\n }\n }\n /**\n * Dispose the texture and release its associated resources.\n */\n dispose() {\n if (this._texture) {\n this.releaseInternalTexture();\n this._engine = null;\n }\n }\n}\n//# sourceMappingURL=thinTexture.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize, SerializationHelper, serializeAsTexture } from \"../../Misc/decorators.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { Matrix } from \"../../Maths/math.vector.js\";\nimport { EngineStore } from \"../../Engines/engineStore.js\";\n\nimport { RandomGUID } from \"../../Misc/guid.js\";\nimport \"../../Misc/fileTools.js\";\nimport { ThinTexture } from \"./thinTexture.js\";\n/**\n * Base class of all the textures in babylon.\n * It groups all the common properties the materials, post process, lights... might need\n * in order to make a correct use of the texture.\n */\nexport class BaseTexture extends ThinTexture {\n /**\n * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance).\n */\n set hasAlpha(value) {\n if (this._hasAlpha === value) {\n return;\n }\n this._hasAlpha = value;\n if (this._scene) {\n this._scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(this);\n });\n }\n }\n get hasAlpha() {\n return this._hasAlpha;\n }\n /**\n * Defines if the alpha value should be determined via the rgb values.\n * If true the luminance of the pixel might be used to find the corresponding alpha value.\n */\n set getAlphaFromRGB(value) {\n if (this._getAlphaFromRGB === value) {\n return;\n }\n this._getAlphaFromRGB = value;\n if (this._scene) {\n this._scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(this);\n });\n }\n }\n get getAlphaFromRGB() {\n return this._getAlphaFromRGB;\n }\n /**\n * Define the UV channel to use starting from 0 and defaulting to 0.\n * This is part of the texture as textures usually maps to one uv set.\n */\n set coordinatesIndex(value) {\n if (this._coordinatesIndex === value) {\n return;\n }\n this._coordinatesIndex = value;\n if (this._scene) {\n this._scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(this);\n });\n }\n }\n get coordinatesIndex() {\n return this._coordinatesIndex;\n }\n /**\n * How a texture is mapped.\n *\n * | Value | Type | Description |\n * | ----- | ----------------------------------- | ----------- |\n * | 0 | EXPLICIT_MODE | |\n * | 1 | SPHERICAL_MODE | |\n * | 2 | PLANAR_MODE | |\n * | 3 | CUBIC_MODE | |\n * | 4 | PROJECTION_MODE | |\n * | 5 | SKYBOX_MODE | |\n * | 6 | INVCUBIC_MODE | |\n * | 7 | EQUIRECTANGULAR_MODE | |\n * | 8 | FIXED_EQUIRECTANGULAR_MODE | |\n * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |\n */\n set coordinatesMode(value) {\n if (this._coordinatesMode === value) {\n return;\n }\n this._coordinatesMode = value;\n if (this._scene) {\n this._scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(this);\n });\n }\n }\n get coordinatesMode() {\n return this._coordinatesMode;\n }\n /**\n * | Value | Type | Description |\n * | ----- | ------------------ | ----------- |\n * | 0 | CLAMP_ADDRESSMODE | |\n * | 1 | WRAP_ADDRESSMODE | |\n * | 2 | MIRROR_ADDRESSMODE | |\n */\n get wrapU() {\n return this._wrapU;\n }\n set wrapU(value) {\n this._wrapU = value;\n }\n /**\n * | Value | Type | Description |\n * | ----- | ------------------ | ----------- |\n * | 0 | CLAMP_ADDRESSMODE | |\n * | 1 | WRAP_ADDRESSMODE | |\n * | 2 | MIRROR_ADDRESSMODE | |\n */\n get wrapV() {\n return this._wrapV;\n }\n set wrapV(value) {\n this._wrapV = value;\n }\n /**\n * Define if the texture is a cube texture or if false a 2d texture.\n */\n get isCube() {\n if (!this._texture) {\n return this._isCube;\n }\n return this._texture.isCube;\n }\n set isCube(value) {\n if (!this._texture) {\n this._isCube = value;\n }\n else {\n this._texture.isCube = value;\n }\n }\n /**\n * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.\n */\n get is3D() {\n if (!this._texture) {\n return false;\n }\n return this._texture.is3D;\n }\n set is3D(value) {\n if (!this._texture) {\n return;\n }\n this._texture.is3D = value;\n }\n /**\n * Define if the texture is a 2d array texture (webgl 2) or if false a 2d texture.\n */\n get is2DArray() {\n if (!this._texture) {\n return false;\n }\n return this._texture.is2DArray;\n }\n set is2DArray(value) {\n if (!this._texture) {\n return;\n }\n this._texture.is2DArray = value;\n }\n /**\n * Define if the texture contains data in gamma space (most of the png/jpg aside bump).\n * HDR texture are usually stored in linear space.\n * This only impacts the PBR and Background materials\n */\n get gammaSpace() {\n if (!this._texture) {\n return this._gammaSpace;\n }\n else {\n if (this._texture._gammaSpace === null) {\n this._texture._gammaSpace = this._gammaSpace;\n }\n }\n return this._texture._gammaSpace && !this._texture._useSRGBBuffer;\n }\n set gammaSpace(gamma) {\n if (!this._texture) {\n if (this._gammaSpace === gamma) {\n return;\n }\n this._gammaSpace = gamma;\n }\n else {\n if (this._texture._gammaSpace === gamma) {\n return;\n }\n this._texture._gammaSpace = gamma;\n }\n this._markAllSubMeshesAsTexturesDirty();\n }\n /**\n * Gets or sets whether or not the texture contains RGBD data.\n */\n get isRGBD() {\n return this._texture != null && this._texture._isRGBD;\n }\n set isRGBD(value) {\n if (this._texture) {\n this._texture._isRGBD = value;\n }\n }\n /**\n * Are mip maps generated for this texture or not.\n */\n get noMipmap() {\n return false;\n }\n /**\n * With prefiltered texture, defined the offset used during the prefiltering steps.\n */\n get lodGenerationOffset() {\n if (this._texture) {\n return this._texture._lodGenerationOffset;\n }\n return 0.0;\n }\n set lodGenerationOffset(value) {\n if (this._texture) {\n this._texture._lodGenerationOffset = value;\n }\n }\n /**\n * With prefiltered texture, defined the scale used during the prefiltering steps.\n */\n get lodGenerationScale() {\n if (this._texture) {\n return this._texture._lodGenerationScale;\n }\n return 0.0;\n }\n set lodGenerationScale(value) {\n if (this._texture) {\n this._texture._lodGenerationScale = value;\n }\n }\n /**\n * With prefiltered texture, defined if the specular generation is based on a linear ramp.\n * By default we are using a log2 of the linear roughness helping to keep a better resolution for\n * average roughness values.\n */\n get linearSpecularLOD() {\n if (this._texture) {\n return this._texture._linearSpecularLOD;\n }\n return false;\n }\n set linearSpecularLOD(value) {\n if (this._texture) {\n this._texture._linearSpecularLOD = value;\n }\n }\n /**\n * In case a better definition than spherical harmonics is required for the diffuse part of the environment.\n * You can set the irradiance texture to rely on a texture instead of the spherical approach.\n * This texture need to have the same characteristics than its parent (Cube vs 2d, coordinates mode, Gamma/Linear, RGBD).\n */\n get irradianceTexture() {\n if (this._texture) {\n return this._texture._irradianceTexture;\n }\n return null;\n }\n set irradianceTexture(value) {\n if (this._texture) {\n this._texture._irradianceTexture = value;\n }\n }\n /**\n * Define the unique id of the texture in the scene.\n */\n get uid() {\n if (!this._uid) {\n this._uid = RandomGUID();\n }\n return this._uid;\n }\n /**\n * Return a string representation of the texture.\n * @returns the texture as a string\n */\n toString() {\n return this.name;\n }\n /**\n * Get the class name of the texture.\n * @returns \"BaseTexture\"\n */\n getClassName() {\n return \"BaseTexture\";\n }\n /**\n * Callback triggered when the texture has been disposed.\n * Kept for back compatibility, you can use the onDisposeObservable instead.\n */\n set onDispose(callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n }\n /**\n * Define if the texture is preventing a material to render or not.\n * If not and the texture is not ready, the engine will use a default black texture instead.\n */\n get isBlocking() {\n return true;\n }\n /**\n * Was there any loading error?\n */\n get loadingError() {\n return this._loadingError;\n }\n /**\n * If a loading error occurred this object will be populated with information about the error.\n */\n get errorObject() {\n return this._errorObject;\n }\n /**\n * Instantiates a new BaseTexture.\n * Base class of all the textures in babylon.\n * It groups all the common properties the materials, post process, lights... might need\n * in order to make a correct use of the texture.\n * @param sceneOrEngine Define the scene or engine the texture belongs to\n * @param internalTexture Define the internal texture associated with the texture\n */\n constructor(sceneOrEngine, internalTexture = null) {\n super(null);\n /**\n * Gets or sets an object used to store user defined information.\n */\n this.metadata = null;\n /**\n * For internal use only. Please do not use.\n */\n this.reservedDataStore = null;\n this._hasAlpha = false;\n this._getAlphaFromRGB = false;\n /**\n * Intensity or strength of the texture.\n * It is commonly used by materials to fine tune the intensity of the texture\n */\n this.level = 1;\n this._coordinatesIndex = 0;\n /**\n * Gets or sets a boolean indicating that the texture should try to reduce shader code if there is no UV manipulation.\n * (ie. when texture.getTextureMatrix().isIdentityAs3x2() returns true)\n */\n this.optimizeUVAllocation = true;\n this._coordinatesMode = 0;\n /**\n * | Value | Type | Description |\n * | ----- | ------------------ | ----------- |\n * | 0 | CLAMP_ADDRESSMODE | |\n * | 1 | WRAP_ADDRESSMODE | |\n * | 2 | MIRROR_ADDRESSMODE | |\n */\n this.wrapR = 1;\n /**\n * With compliant hardware and browser (supporting anisotropic filtering)\n * this defines the level of anisotropic filtering in the texture.\n * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.\n */\n this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;\n /** @internal */\n this._isCube = false;\n this._gammaSpace = true;\n /**\n * Is Z inverted in the texture (useful in a cube texture).\n */\n this.invertZ = false;\n /**\n * @internal\n */\n this.lodLevelInAlpha = false;\n /**\n * Define if the texture is a render target.\n */\n this.isRenderTarget = false;\n /** @internal */\n this._prefiltered = false;\n /** @internal */\n this._forceSerialize = false;\n /**\n * Define the list of animation attached to the texture.\n */\n this.animations = new Array();\n /**\n * An event triggered when the texture is disposed.\n */\n this.onDisposeObservable = new Observable();\n this._onDisposeObserver = null;\n this._scene = null;\n /** @internal */\n this._uid = null;\n /** @internal */\n this._parentContainer = null;\n this._loadingError = false;\n if (sceneOrEngine) {\n if (BaseTexture._IsScene(sceneOrEngine)) {\n this._scene = sceneOrEngine;\n }\n else {\n this._engine = sceneOrEngine;\n }\n }\n else {\n this._scene = EngineStore.LastCreatedScene;\n }\n if (this._scene) {\n this.uniqueId = this._scene.getUniqueId();\n this._scene.addTexture(this);\n this._engine = this._scene.getEngine();\n }\n this._texture = internalTexture;\n this._uid = null;\n }\n /**\n * Get the scene the texture belongs to.\n * @returns the scene or null if undefined\n */\n getScene() {\n return this._scene;\n }\n /** @internal */\n _getEngine() {\n return this._engine;\n }\n /**\n * Checks if the texture has the same transform matrix than another texture\n * @param texture texture to check against\n * @returns true if the transforms are the same, else false\n */\n checkTransformsAreIdentical(texture) {\n return texture !== null;\n }\n /**\n * Get the texture transform matrix used to offset tile the texture for instance.\n * @returns the transformation matrix\n */\n getTextureMatrix() {\n return Matrix.IdentityReadOnly;\n }\n /**\n * Get the texture reflection matrix used to rotate/transform the reflection.\n * @returns the reflection matrix\n */\n getReflectionTextureMatrix() {\n return Matrix.IdentityReadOnly;\n }\n /**\n * Gets a suitable rotate/transform matrix when the texture is used for refraction.\n * There's a separate function from getReflectionTextureMatrix because refraction requires a special configuration of the matrix in right-handed mode.\n * @returns The refraction matrix\n */\n getRefractionTextureMatrix() {\n return this.getReflectionTextureMatrix();\n }\n /**\n * Get if the texture is ready to be consumed (either it is ready or it is not blocking)\n * @returns true if ready, not blocking or if there was an error loading the texture\n */\n isReadyOrNotBlocking() {\n return !this.isBlocking || this.isReady() || this.loadingError;\n }\n /**\n * Scales the texture if is `canRescale()`\n * @param ratio the resize factor we want to use to rescale\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n scale(ratio) { }\n /**\n * Get if the texture can rescale.\n */\n get canRescale() {\n return false;\n }\n /**\n * @internal\n */\n _getFromCache(url, noMipmap, sampling, invertY, useSRGBBuffer, isCube) {\n const engine = this._getEngine();\n if (!engine) {\n return null;\n }\n const correctedUseSRGBBuffer = engine._getUseSRGBBuffer(!!useSRGBBuffer, noMipmap);\n const texturesCache = engine.getLoadedTexturesCache();\n for (let index = 0; index < texturesCache.length; index++) {\n const texturesCacheEntry = texturesCache[index];\n if (useSRGBBuffer === undefined || correctedUseSRGBBuffer === texturesCacheEntry._useSRGBBuffer) {\n if (invertY === undefined || invertY === texturesCacheEntry.invertY) {\n if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {\n if (!sampling || sampling === texturesCacheEntry.samplingMode) {\n if (isCube === undefined || isCube === texturesCacheEntry.isCube) {\n texturesCacheEntry.incrementReferences();\n return texturesCacheEntry;\n }\n }\n }\n }\n }\n }\n return null;\n }\n /** @internal */\n _rebuild() { }\n /**\n * Clones the texture.\n * @returns the cloned texture\n */\n clone() {\n return null;\n }\n /**\n * Get the texture underlying type (INT, FLOAT...)\n */\n get textureType() {\n if (!this._texture) {\n return 0;\n }\n return this._texture.type !== undefined ? this._texture.type : 0;\n }\n /**\n * Get the texture underlying format (RGB, RGBA...)\n */\n get textureFormat() {\n if (!this._texture) {\n return 5;\n }\n return this._texture.format !== undefined ? this._texture.format : 5;\n }\n /**\n * Indicates that textures need to be re-calculated for all materials\n */\n _markAllSubMeshesAsTexturesDirty() {\n const scene = this.getScene();\n if (!scene) {\n return;\n }\n scene.markAllMaterialsAsDirty(1);\n }\n /**\n * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.\n * This will returns an RGBA array buffer containing either in values (0-255) or\n * float values (0-1) depending of the underlying buffer type.\n * @param faceIndex defines the face of the texture to read (in case of cube texture)\n * @param level defines the LOD level of the texture to read (in case of Mip Maps)\n * @param buffer defines a user defined buffer to fill with data (can be null)\n * @param flushRenderer true to flush the renderer from the pending commands before reading the pixels\n * @param noDataConversion false to convert the data to Uint8Array (if texture type is UNSIGNED_BYTE) or to Float32Array (if texture type is anything but UNSIGNED_BYTE). If true, the type of the generated buffer (if buffer==null) will depend on the type of the texture\n * @param x defines the region x coordinates to start reading from (default to 0)\n * @param y defines the region y coordinates to start reading from (default to 0)\n * @param width defines the region width to read from (default to the texture size at level)\n * @param height defines the region width to read from (default to the texture size at level)\n * @returns The Array buffer promise containing the pixels data.\n */\n readPixels(faceIndex = 0, level = 0, buffer = null, flushRenderer = true, noDataConversion = false, x = 0, y = 0, width = Number.MAX_VALUE, height = Number.MAX_VALUE) {\n if (!this._texture) {\n return null;\n }\n const engine = this._getEngine();\n if (!engine) {\n return null;\n }\n const size = this.getSize();\n let maxWidth = size.width;\n let maxHeight = size.height;\n if (level !== 0) {\n maxWidth = maxWidth / Math.pow(2, level);\n maxHeight = maxHeight / Math.pow(2, level);\n maxWidth = Math.round(maxWidth);\n maxHeight = Math.round(maxHeight);\n }\n width = Math.min(maxWidth, width);\n height = Math.min(maxHeight, height);\n try {\n if (this._texture.isCube) {\n return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer, flushRenderer, noDataConversion, x, y);\n }\n return engine._readTexturePixels(this._texture, width, height, -1, level, buffer, flushRenderer, noDataConversion, x, y);\n }\n catch (e) {\n return null;\n }\n }\n /**\n * @internal\n */\n _readPixelsSync(faceIndex = 0, level = 0, buffer = null, flushRenderer = true, noDataConversion = false) {\n if (!this._texture) {\n return null;\n }\n const size = this.getSize();\n let width = size.width;\n let height = size.height;\n const engine = this._getEngine();\n if (!engine) {\n return null;\n }\n if (level != 0) {\n width = width / Math.pow(2, level);\n height = height / Math.pow(2, level);\n width = Math.round(width);\n height = Math.round(height);\n }\n try {\n if (this._texture.isCube) {\n return engine._readTexturePixelsSync(this._texture, width, height, faceIndex, level, buffer, flushRenderer, noDataConversion);\n }\n return engine._readTexturePixelsSync(this._texture, width, height, -1, level, buffer, flushRenderer, noDataConversion);\n }\n catch (e) {\n return null;\n }\n }\n /** @internal */\n get _lodTextureHigh() {\n if (this._texture) {\n return this._texture._lodTextureHigh;\n }\n return null;\n }\n /** @internal */\n get _lodTextureMid() {\n if (this._texture) {\n return this._texture._lodTextureMid;\n }\n return null;\n }\n /** @internal */\n get _lodTextureLow() {\n if (this._texture) {\n return this._texture._lodTextureLow;\n }\n return null;\n }\n /**\n * Dispose the texture and release its associated resources.\n */\n dispose() {\n if (this._scene) {\n // Animations\n if (this._scene.stopAnimation) {\n this._scene.stopAnimation(this);\n }\n // Remove from scene\n this._scene.removePendingData(this);\n const index = this._scene.textures.indexOf(this);\n if (index >= 0) {\n this._scene.textures.splice(index, 1);\n }\n this._scene.onTextureRemovedObservable.notifyObservers(this);\n this._scene = null;\n if (this._parentContainer) {\n const index = this._parentContainer.textures.indexOf(this);\n if (index > -1) {\n this._parentContainer.textures.splice(index, 1);\n }\n this._parentContainer = null;\n }\n }\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n this.metadata = null;\n super.dispose();\n }\n /**\n * Serialize the texture into a JSON representation that can be parsed later on.\n * @param allowEmptyName True to force serialization even if name is empty. Default: false\n * @returns the JSON representation of the texture\n */\n serialize(allowEmptyName = false) {\n if (!this.name && !allowEmptyName) {\n return null;\n }\n const serializationObject = SerializationHelper.Serialize(this);\n // Animations\n SerializationHelper.AppendSerializedAnimations(this, serializationObject);\n return serializationObject;\n }\n /**\n * Helper function to be called back once a list of texture contains only ready textures.\n * @param textures Define the list of textures to wait for\n * @param callback Define the callback triggered once the entire list will be ready\n */\n static WhenAllReady(textures, callback) {\n let numRemaining = textures.length;\n if (numRemaining === 0) {\n callback();\n return;\n }\n for (let i = 0; i < textures.length; i++) {\n const texture = textures[i];\n if (texture.isReady()) {\n if (--numRemaining === 0) {\n callback();\n }\n }\n else {\n const onLoadObservable = texture.onLoadObservable;\n if (onLoadObservable) {\n onLoadObservable.addOnce(() => {\n if (--numRemaining === 0) {\n callback();\n }\n });\n }\n else {\n if (--numRemaining === 0) {\n callback();\n }\n }\n }\n }\n }\n static _IsScene(sceneOrEngine) {\n return sceneOrEngine.getClassName() === \"Scene\";\n }\n}\n/**\n * Default anisotropic filtering level for the application.\n * It is set to 4 as a good tradeoff between perf and quality.\n */\nBaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;\n__decorate([\n serialize()\n], BaseTexture.prototype, \"uniqueId\", void 0);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"name\", void 0);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"metadata\", void 0);\n__decorate([\n serialize(\"hasAlpha\")\n], BaseTexture.prototype, \"_hasAlpha\", void 0);\n__decorate([\n serialize(\"getAlphaFromRGB\")\n], BaseTexture.prototype, \"_getAlphaFromRGB\", void 0);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"level\", void 0);\n__decorate([\n serialize(\"coordinatesIndex\")\n], BaseTexture.prototype, \"_coordinatesIndex\", void 0);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"optimizeUVAllocation\", void 0);\n__decorate([\n serialize(\"coordinatesMode\")\n], BaseTexture.prototype, \"_coordinatesMode\", void 0);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"wrapU\", null);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"wrapV\", null);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"wrapR\", void 0);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"anisotropicFilteringLevel\", void 0);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"isCube\", null);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"is3D\", null);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"is2DArray\", null);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"gammaSpace\", null);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"invertZ\", void 0);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"lodLevelInAlpha\", void 0);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"lodGenerationOffset\", null);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"lodGenerationScale\", null);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"linearSpecularLOD\", null);\n__decorate([\n serializeAsTexture()\n], BaseTexture.prototype, \"irradianceTexture\", null);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"isRenderTarget\", void 0);\n//# sourceMappingURL=baseTexture.js.map","/**\n * Transform some pixel data to a base64 string\n * @param pixels defines the pixel data to transform to base64\n * @param size defines the width and height of the (texture) data\n * @param invertY true if the data must be inverted for the Y coordinate during the conversion\n * @returns The base64 encoded string or null\n */\nexport function GenerateBase64StringFromPixelData(pixels, size, invertY = false) {\n const width = size.width;\n const height = size.height;\n if (pixels instanceof Float32Array) {\n let len = pixels.byteLength / pixels.BYTES_PER_ELEMENT;\n const npixels = new Uint8Array(len);\n while (--len >= 0) {\n let val = pixels[len];\n if (val < 0) {\n val = 0;\n }\n else if (val > 1) {\n val = 1;\n }\n npixels[len] = val * 255;\n }\n pixels = npixels;\n }\n const canvas = document.createElement(\"canvas\");\n canvas.width = width;\n canvas.height = height;\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) {\n return null;\n }\n const imageData = ctx.createImageData(width, height);\n const castData = imageData.data;\n castData.set(pixels);\n ctx.putImageData(imageData, 0, 0);\n if (invertY) {\n const canvas2 = document.createElement(\"canvas\");\n canvas2.width = width;\n canvas2.height = height;\n const ctx2 = canvas2.getContext(\"2d\");\n if (!ctx2) {\n return null;\n }\n ctx2.translate(0, height);\n ctx2.scale(1, -1);\n ctx2.drawImage(canvas, 0, 0);\n return canvas2.toDataURL(\"image/png\");\n }\n return canvas.toDataURL(\"image/png\");\n}\n/**\n * Reads the pixels stored in the webgl texture and returns them as a base64 string\n * @param texture defines the texture to read pixels from\n * @param faceIndex defines the face of the texture to read (in case of cube texture)\n * @param level defines the LOD level of the texture to read (in case of Mip Maps)\n * @returns The base64 encoded string or null\n */\nexport function GenerateBase64StringFromTexture(texture, faceIndex = 0, level = 0) {\n const internalTexture = texture.getInternalTexture();\n if (!internalTexture) {\n return null;\n }\n const pixels = texture._readPixelsSync(faceIndex, level);\n if (!pixels) {\n return null;\n }\n return GenerateBase64StringFromPixelData(pixels, texture.getSize(), internalTexture.invertY);\n}\n/**\n * Reads the pixels stored in the webgl texture and returns them as a base64 string\n * @param texture defines the texture to read pixels from\n * @param faceIndex defines the face of the texture to read (in case of cube texture)\n * @param level defines the LOD level of the texture to read (in case of Mip Maps)\n * @returns The base64 encoded string or null wrapped in a promise\n */\nexport async function GenerateBase64StringFromTextureAsync(texture, faceIndex = 0, level = 0) {\n const internalTexture = texture.getInternalTexture();\n if (!internalTexture) {\n return null;\n }\n const pixels = await texture.readPixels(faceIndex, level);\n if (!pixels) {\n return null;\n }\n return GenerateBase64StringFromPixelData(pixels, texture.getSize(), internalTexture.invertY);\n}\n/**\n * Class used to host copy specific utilities\n * (Back-compat)\n */\nexport const CopyTools = {\n /**\n * Transform some pixel data to a base64 string\n * @param pixels defines the pixel data to transform to base64\n * @param size defines the width and height of the (texture) data\n * @param invertY true if the data must be inverted for the Y coordinate during the conversion\n * @returns The base64 encoded string or null\n */\n GenerateBase64StringFromPixelData,\n /**\n * Reads the pixels stored in the webgl texture and returns them as a base64 string\n * @param texture defines the texture to read pixels from\n * @param faceIndex defines the face of the texture to read (in case of cube texture)\n * @param level defines the LOD level of the texture to read (in case of Mip Maps)\n * @returns The base64 encoded string or null\n */\n GenerateBase64StringFromTexture,\n /**\n * Reads the pixels stored in the webgl texture and returns them as a base64 string\n * @param texture defines the texture to read pixels from\n * @param faceIndex defines the face of the texture to read (in case of cube texture)\n * @param level defines the LOD level of the texture to read (in case of Mip Maps)\n * @returns The base64 encoded string or null wrapped in a promise\n */\n GenerateBase64StringFromTextureAsync,\n};\n//# sourceMappingURL=copyTools.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize, SerializationHelper } from \"../../Misc/decorators.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { Matrix, TmpVectors, Vector3 } from \"../../Maths/math.vector.js\";\nimport { BaseTexture } from \"../../Materials/Textures/baseTexture.js\";\n\nimport { GetClass, RegisterClass } from \"../../Misc/typeStore.js\";\nimport { _WarnImport } from \"../../Misc/devTools.js\";\nimport { TimingTools } from \"../../Misc/timingTools.js\";\nimport { InstantiationTools } from \"../../Misc/instantiationTools.js\";\nimport { Plane } from \"../../Maths/math.plane.js\";\nimport { EncodeArrayBufferToBase64 } from \"../../Misc/stringTools.js\";\nimport { GenerateBase64StringFromTexture, GenerateBase64StringFromTextureAsync } from \"../../Misc/copyTools.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n/**\n * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction#texture\n */\nexport class Texture extends BaseTexture {\n /**\n * Are mip maps generated for this texture or not.\n */\n get noMipmap() {\n return this._noMipmap;\n }\n /** Returns the texture mime type if it was defined by a loader (undefined else) */\n get mimeType() {\n return this._mimeType;\n }\n /**\n * Is the texture preventing material to render while loading.\n * If false, a default texture will be used instead of the loading one during the preparation step.\n */\n set isBlocking(value) {\n this._isBlocking = value;\n }\n get isBlocking() {\n return this._isBlocking;\n }\n /**\n * Gets a boolean indicating if the texture needs to be inverted on the y axis during loading\n */\n get invertY() {\n return this._invertY;\n }\n /**\n * Instantiates a new texture.\n * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction#texture\n * @param url defines the url of the picture to load as a texture\n * @param sceneOrEngine defines the scene or engine the texture will belong to\n * @param noMipmapOrOptions defines if the texture will require mip maps or not or set of all options to create the texture\n * @param invertY defines if the texture needs to be inverted on the y axis during loading\n * @param samplingMode defines the sampling mode we want for the texture while fetching from it (Texture.NEAREST_SAMPLINGMODE...)\n * @param onLoad defines a callback triggered when the texture has been loaded\n * @param onError defines a callback triggered when an error occurred during the loading session\n * @param buffer defines the buffer to load the texture from in case the texture is loaded from a buffer representation\n * @param deleteBuffer defines if the buffer we are loading the texture from should be deleted after load\n * @param format defines the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)\n * @param mimeType defines an optional mime type information\n * @param loaderOptions options to be passed to the loader\n * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)\n * @param forcedExtension defines the extension to use to pick the right loader\n */\n constructor(url, sceneOrEngine, noMipmapOrOptions, invertY, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, onLoad = null, onError = null, buffer = null, deleteBuffer = false, format, mimeType, loaderOptions, creationFlags, forcedExtension) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j;\n super(sceneOrEngine);\n /**\n * Define the url of the texture.\n */\n this.url = null;\n /**\n * Define an offset on the texture to offset the u coordinates of the UVs\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials#offsetting\n */\n this.uOffset = 0;\n /**\n * Define an offset on the texture to offset the v coordinates of the UVs\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials#offsetting\n */\n this.vOffset = 0;\n /**\n * Define an offset on the texture to scale the u coordinates of the UVs\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials#tiling\n */\n this.uScale = 1.0;\n /**\n * Define an offset on the texture to scale the v coordinates of the UVs\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials#tiling\n */\n this.vScale = 1.0;\n /**\n * Define an offset on the texture to rotate around the u coordinates of the UVs\n * The angle is defined in radians.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials\n */\n this.uAng = 0;\n /**\n * Define an offset on the texture to rotate around the v coordinates of the UVs\n * The angle is defined in radians.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials\n */\n this.vAng = 0;\n /**\n * Define an offset on the texture to rotate around the w coordinates of the UVs (in case of 3d texture)\n * The angle is defined in radians.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials\n */\n this.wAng = 0;\n /**\n * Defines the center of rotation (U)\n */\n this.uRotationCenter = 0.5;\n /**\n * Defines the center of rotation (V)\n */\n this.vRotationCenter = 0.5;\n /**\n * Defines the center of rotation (W)\n */\n this.wRotationCenter = 0.5;\n /**\n * Sets this property to true to avoid deformations when rotating the texture with non-uniform scaling\n */\n this.homogeneousRotationInUVTransform = false;\n /**\n * List of inspectable custom properties (used by the Inspector)\n * @see https://doc.babylonjs.com/toolsAndResources/inspector#extensibility\n */\n this.inspectableCustomProperties = null;\n /** @internal */\n this._noMipmap = false;\n /** @internal */\n this._invertY = false;\n this._rowGenerationMatrix = null;\n this._cachedTextureMatrix = null;\n this._projectionModeMatrix = null;\n this._t0 = null;\n this._t1 = null;\n this._t2 = null;\n this._cachedUOffset = -1;\n this._cachedVOffset = -1;\n this._cachedUScale = 0;\n this._cachedVScale = 0;\n this._cachedUAng = -1;\n this._cachedVAng = -1;\n this._cachedWAng = -1;\n this._cachedReflectionProjectionMatrixId = -1;\n this._cachedURotationCenter = -1;\n this._cachedVRotationCenter = -1;\n this._cachedWRotationCenter = -1;\n this._cachedHomogeneousRotationInUVTransform = false;\n this._cachedReflectionTextureMatrix = null;\n this._cachedReflectionUOffset = -1;\n this._cachedReflectionVOffset = -1;\n this._cachedReflectionUScale = 0;\n this._cachedReflectionVScale = 0;\n this._cachedReflectionCoordinatesMode = -1;\n /** @internal */\n this._buffer = null;\n this._deleteBuffer = false;\n this._format = null;\n this._delayedOnLoad = null;\n this._delayedOnError = null;\n /**\n * Observable triggered once the texture has been loaded.\n */\n this.onLoadObservable = new Observable();\n this._isBlocking = true;\n this.name = url || \"\";\n this.url = url;\n let noMipmap;\n let useSRGBBuffer = false;\n let internalTexture = null;\n if (typeof noMipmapOrOptions === \"object\" && noMipmapOrOptions !== null) {\n noMipmap = (_a = noMipmapOrOptions.noMipmap) !== null && _a !== void 0 ? _a : false;\n invertY = (_b = noMipmapOrOptions.invertY) !== null && _b !== void 0 ? _b : (CompatibilityOptions.UseOpenGLOrientationForUV ? false : true);\n samplingMode = (_c = noMipmapOrOptions.samplingMode) !== null && _c !== void 0 ? _c : Texture.TRILINEAR_SAMPLINGMODE;\n onLoad = (_d = noMipmapOrOptions.onLoad) !== null && _d !== void 0 ? _d : null;\n onError = (_e = noMipmapOrOptions.onError) !== null && _e !== void 0 ? _e : null;\n buffer = (_f = noMipmapOrOptions.buffer) !== null && _f !== void 0 ? _f : null;\n deleteBuffer = (_g = noMipmapOrOptions.deleteBuffer) !== null && _g !== void 0 ? _g : false;\n format = noMipmapOrOptions.format;\n mimeType = noMipmapOrOptions.mimeType;\n loaderOptions = noMipmapOrOptions.loaderOptions;\n creationFlags = noMipmapOrOptions.creationFlags;\n useSRGBBuffer = (_h = noMipmapOrOptions.useSRGBBuffer) !== null && _h !== void 0 ? _h : false;\n internalTexture = (_j = noMipmapOrOptions.internalTexture) !== null && _j !== void 0 ? _j : null;\n }\n else {\n noMipmap = !!noMipmapOrOptions;\n }\n this._noMipmap = noMipmap;\n this._invertY = invertY === undefined ? (CompatibilityOptions.UseOpenGLOrientationForUV ? false : true) : invertY;\n this._initialSamplingMode = samplingMode;\n this._buffer = buffer;\n this._deleteBuffer = deleteBuffer;\n this._mimeType = mimeType;\n this._loaderOptions = loaderOptions;\n this._creationFlags = creationFlags;\n this._useSRGBBuffer = useSRGBBuffer;\n this._forcedExtension = forcedExtension;\n if (format) {\n this._format = format;\n }\n const scene = this.getScene();\n const engine = this._getEngine();\n if (!engine) {\n return;\n }\n engine.onBeforeTextureInitObservable.notifyObservers(this);\n const load = () => {\n if (this._texture) {\n if (this._texture._invertVScale) {\n this.vScale *= -1;\n this.vOffset += 1;\n }\n // Update texture to match internal texture's wrapping\n if (this._texture._cachedWrapU !== null) {\n this.wrapU = this._texture._cachedWrapU;\n this._texture._cachedWrapU = null;\n }\n if (this._texture._cachedWrapV !== null) {\n this.wrapV = this._texture._cachedWrapV;\n this._texture._cachedWrapV = null;\n }\n if (this._texture._cachedWrapR !== null) {\n this.wrapR = this._texture._cachedWrapR;\n this._texture._cachedWrapR = null;\n }\n }\n if (this.onLoadObservable.hasObservers()) {\n this.onLoadObservable.notifyObservers(this);\n }\n if (onLoad) {\n onLoad();\n }\n if (!this.isBlocking && scene) {\n scene.resetCachedMaterial();\n }\n };\n const errorHandler = (message, exception) => {\n this._loadingError = true;\n this._errorObject = { message, exception };\n if (onError) {\n onError(message, exception);\n }\n Texture.OnTextureLoadErrorObservable.notifyObservers(this);\n };\n if (!this.url && !internalTexture) {\n this._delayedOnLoad = load;\n this._delayedOnError = errorHandler;\n return;\n }\n this._texture = internalTexture !== null && internalTexture !== void 0 ? internalTexture : this._getFromCache(this.url, noMipmap, samplingMode, this._invertY, useSRGBBuffer);\n if (!this._texture) {\n if (!scene || !scene.useDelayedTextureLoading) {\n try {\n this._texture = engine.createTexture(this.url, noMipmap, this._invertY, scene, samplingMode, load, errorHandler, this._buffer, undefined, this._format, this._forcedExtension, mimeType, loaderOptions, creationFlags, useSRGBBuffer);\n }\n catch (e) {\n errorHandler(\"error loading\", e);\n throw e;\n }\n if (deleteBuffer) {\n this._buffer = null;\n }\n }\n else {\n this.delayLoadState = 4;\n this._delayedOnLoad = load;\n this._delayedOnError = errorHandler;\n }\n }\n else {\n if (this._texture.isReady) {\n TimingTools.SetImmediate(() => load());\n }\n else {\n const loadObserver = this._texture.onLoadedObservable.add(load);\n this._texture.onErrorObservable.add((e) => {\n var _a;\n errorHandler(e.message, e.exception);\n (_a = this._texture) === null || _a === void 0 ? void 0 : _a.onLoadedObservable.remove(loadObserver);\n });\n }\n }\n }\n /**\n * Update the url (and optional buffer) of this texture if url was null during construction.\n * @param url the url of the texture\n * @param buffer the buffer of the texture (defaults to null)\n * @param onLoad callback called when the texture is loaded (defaults to null)\n * @param forcedExtension defines the extension to use to pick the right loader\n */\n updateURL(url, buffer = null, onLoad, forcedExtension) {\n if (this.url) {\n this.releaseInternalTexture();\n this.getScene().markAllMaterialsAsDirty(1);\n }\n if (!this.name || this.name.startsWith(\"data:\")) {\n this.name = url;\n }\n this.url = url;\n this._buffer = buffer;\n this._forcedExtension = forcedExtension;\n this.delayLoadState = 4;\n if (onLoad) {\n this._delayedOnLoad = onLoad;\n }\n this.delayLoad();\n }\n /**\n * Finish the loading sequence of a texture flagged as delayed load.\n * @internal\n */\n delayLoad() {\n if (this.delayLoadState !== 4) {\n return;\n }\n const scene = this.getScene();\n if (!scene) {\n return;\n }\n this.delayLoadState = 1;\n this._texture = this._getFromCache(this.url, this._noMipmap, this.samplingMode, this._invertY, this._useSRGBBuffer);\n if (!this._texture) {\n this._texture = scene\n .getEngine()\n .createTexture(this.url, this._noMipmap, this._invertY, scene, this.samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format, this._forcedExtension, this._mimeType, this._loaderOptions, this._creationFlags, this._useSRGBBuffer);\n if (this._deleteBuffer) {\n this._buffer = null;\n }\n }\n else {\n if (this._delayedOnLoad) {\n if (this._texture.isReady) {\n TimingTools.SetImmediate(this._delayedOnLoad);\n }\n else {\n this._texture.onLoadedObservable.add(this._delayedOnLoad);\n }\n }\n }\n this._delayedOnLoad = null;\n this._delayedOnError = null;\n }\n _prepareRowForTextureGeneration(x, y, z, t) {\n x *= this._cachedUScale;\n y *= this._cachedVScale;\n x -= this.uRotationCenter * this._cachedUScale;\n y -= this.vRotationCenter * this._cachedVScale;\n z -= this.wRotationCenter;\n Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);\n t.x += this.uRotationCenter * this._cachedUScale + this._cachedUOffset;\n t.y += this.vRotationCenter * this._cachedVScale + this._cachedVOffset;\n t.z += this.wRotationCenter;\n }\n /**\n * Checks if the texture has the same transform matrix than another texture\n * @param texture texture to check against\n * @returns true if the transforms are the same, else false\n */\n checkTransformsAreIdentical(texture) {\n return (texture !== null &&\n this.uOffset === texture.uOffset &&\n this.vOffset === texture.vOffset &&\n this.uScale === texture.uScale &&\n this.vScale === texture.vScale &&\n this.uAng === texture.uAng &&\n this.vAng === texture.vAng &&\n this.wAng === texture.wAng);\n }\n /**\n * Get the current texture matrix which includes the requested offsetting, tiling and rotation components.\n * @param uBase\n * @returns the transform matrix of the texture.\n */\n getTextureMatrix(uBase = 1) {\n if (this.uOffset === this._cachedUOffset &&\n this.vOffset === this._cachedVOffset &&\n this.uScale * uBase === this._cachedUScale &&\n this.vScale === this._cachedVScale &&\n this.uAng === this._cachedUAng &&\n this.vAng === this._cachedVAng &&\n this.wAng === this._cachedWAng &&\n this.uRotationCenter === this._cachedURotationCenter &&\n this.vRotationCenter === this._cachedVRotationCenter &&\n this.wRotationCenter === this._cachedWRotationCenter &&\n this.homogeneousRotationInUVTransform === this._cachedHomogeneousRotationInUVTransform) {\n return this._cachedTextureMatrix;\n }\n this._cachedUOffset = this.uOffset;\n this._cachedVOffset = this.vOffset;\n this._cachedUScale = this.uScale * uBase;\n this._cachedVScale = this.vScale;\n this._cachedUAng = this.uAng;\n this._cachedVAng = this.vAng;\n this._cachedWAng = this.wAng;\n this._cachedURotationCenter = this.uRotationCenter;\n this._cachedVRotationCenter = this.vRotationCenter;\n this._cachedWRotationCenter = this.wRotationCenter;\n this._cachedHomogeneousRotationInUVTransform = this.homogeneousRotationInUVTransform;\n if (!this._cachedTextureMatrix || !this._rowGenerationMatrix) {\n this._cachedTextureMatrix = Matrix.Zero();\n this._rowGenerationMatrix = new Matrix();\n this._t0 = Vector3.Zero();\n this._t1 = Vector3.Zero();\n this._t2 = Vector3.Zero();\n }\n Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);\n if (this.homogeneousRotationInUVTransform) {\n Matrix.TranslationToRef(-this._cachedURotationCenter, -this._cachedVRotationCenter, -this._cachedWRotationCenter, TmpVectors.Matrix[0]);\n Matrix.TranslationToRef(this._cachedURotationCenter, this._cachedVRotationCenter, this._cachedWRotationCenter, TmpVectors.Matrix[1]);\n Matrix.ScalingToRef(this._cachedUScale, this._cachedVScale, 0, TmpVectors.Matrix[2]);\n Matrix.TranslationToRef(this._cachedUOffset, this._cachedVOffset, 0, TmpVectors.Matrix[3]);\n TmpVectors.Matrix[0].multiplyToRef(this._rowGenerationMatrix, this._cachedTextureMatrix);\n this._cachedTextureMatrix.multiplyToRef(TmpVectors.Matrix[1], this._cachedTextureMatrix);\n this._cachedTextureMatrix.multiplyToRef(TmpVectors.Matrix[2], this._cachedTextureMatrix);\n this._cachedTextureMatrix.multiplyToRef(TmpVectors.Matrix[3], this._cachedTextureMatrix);\n // copy the translation row to the 3rd row of the matrix so that we don't need to update the shaders (which expects the translation to be on the 3rd row)\n this._cachedTextureMatrix.setRowFromFloats(2, this._cachedTextureMatrix.m[12], this._cachedTextureMatrix.m[13], this._cachedTextureMatrix.m[14], 1);\n }\n else {\n this._prepareRowForTextureGeneration(0, 0, 0, this._t0);\n this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);\n this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);\n this._t1.subtractInPlace(this._t0);\n this._t2.subtractInPlace(this._t0);\n Matrix.FromValuesToRef(this._t1.x, this._t1.y, this._t1.z, 0.0, this._t2.x, this._t2.y, this._t2.z, 0.0, this._t0.x, this._t0.y, this._t0.z, 0.0, 0.0, 0.0, 0.0, 1.0, this._cachedTextureMatrix);\n }\n const scene = this.getScene();\n if (!scene) {\n return this._cachedTextureMatrix;\n }\n if (this.optimizeUVAllocation) {\n // We flag the materials that are using this texture as \"texture dirty\" because depending on the fact that the matrix is the identity or not, some defines\n // will get different values (see MaterialHelper.PrepareDefinesForMergedUV), meaning we should regenerate the effect accordingly\n scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(this);\n });\n }\n return this._cachedTextureMatrix;\n }\n /**\n * Get the current matrix used to apply reflection. This is useful to rotate an environment texture for instance.\n * @returns The reflection texture transform\n */\n getReflectionTextureMatrix() {\n const scene = this.getScene();\n if (!scene) {\n return this._cachedReflectionTextureMatrix;\n }\n if (this.uOffset === this._cachedReflectionUOffset &&\n this.vOffset === this._cachedReflectionVOffset &&\n this.uScale === this._cachedReflectionUScale &&\n this.vScale === this._cachedReflectionVScale &&\n this.coordinatesMode === this._cachedReflectionCoordinatesMode) {\n if (this.coordinatesMode === Texture.PROJECTION_MODE) {\n if (this._cachedReflectionProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {\n return this._cachedReflectionTextureMatrix;\n }\n }\n else {\n return this._cachedReflectionTextureMatrix;\n }\n }\n if (!this._cachedReflectionTextureMatrix) {\n this._cachedReflectionTextureMatrix = Matrix.Zero();\n }\n if (!this._projectionModeMatrix) {\n this._projectionModeMatrix = Matrix.Zero();\n }\n const flagMaterialsAsTextureDirty = this._cachedReflectionCoordinatesMode !== this.coordinatesMode;\n this._cachedReflectionUOffset = this.uOffset;\n this._cachedReflectionVOffset = this.vOffset;\n this._cachedReflectionUScale = this.uScale;\n this._cachedReflectionVScale = this.vScale;\n this._cachedReflectionCoordinatesMode = this.coordinatesMode;\n switch (this.coordinatesMode) {\n case Texture.PLANAR_MODE: {\n Matrix.IdentityToRef(this._cachedReflectionTextureMatrix);\n this._cachedReflectionTextureMatrix[0] = this.uScale;\n this._cachedReflectionTextureMatrix[5] = this.vScale;\n this._cachedReflectionTextureMatrix[12] = this.uOffset;\n this._cachedReflectionTextureMatrix[13] = this.vOffset;\n break;\n }\n case Texture.PROJECTION_MODE: {\n Matrix.FromValuesToRef(0.5, 0.0, 0.0, 0.0, 0.0, -0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5, 1.0, 1.0, this._projectionModeMatrix);\n const projectionMatrix = scene.getProjectionMatrix();\n this._cachedReflectionProjectionMatrixId = projectionMatrix.updateFlag;\n projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedReflectionTextureMatrix);\n break;\n }\n default:\n Matrix.IdentityToRef(this._cachedReflectionTextureMatrix);\n break;\n }\n if (flagMaterialsAsTextureDirty) {\n // We flag the materials that are using this texture as \"texture dirty\" if the coordinatesMode has changed.\n // Indeed, this property is used to set the value of some defines used to generate the effect (in material.isReadyForSubMesh), so we must make sure this code will be re-executed and the effect recreated if necessary\n scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.getActiveTextures().indexOf(this) !== -1;\n });\n }\n return this._cachedReflectionTextureMatrix;\n }\n /**\n * Clones the texture.\n * @returns the cloned texture\n */\n clone() {\n const options = {\n noMipmap: this._noMipmap,\n invertY: this._invertY,\n samplingMode: this.samplingMode,\n onLoad: undefined,\n onError: undefined,\n buffer: this._texture ? this._texture._buffer : undefined,\n deleteBuffer: this._deleteBuffer,\n format: this.textureFormat,\n mimeType: this.mimeType,\n loaderOptions: this._loaderOptions,\n creationFlags: this._creationFlags,\n useSRGBBuffer: this._useSRGBBuffer,\n };\n return SerializationHelper.Clone(() => {\n return new Texture(this._texture ? this._texture.url : null, this.getScene(), options);\n }, this);\n }\n /**\n * Serialize the texture to a JSON representation we can easily use in the respective Parse function.\n * @returns The JSON representation of the texture\n */\n serialize() {\n var _a, _b;\n const savedName = this.name;\n if (!Texture.SerializeBuffers) {\n if (this.name.startsWith(\"data:\")) {\n this.name = \"\";\n }\n }\n if (this.name.startsWith(\"data:\") && this.url === this.name) {\n this.url = \"\";\n }\n const serializationObject = super.serialize(Texture._SerializeInternalTextureUniqueId);\n if (!serializationObject) {\n return null;\n }\n if (Texture.SerializeBuffers || Texture.ForceSerializeBuffers) {\n if (typeof this._buffer === \"string\" && this._buffer.substr(0, 5) === \"data:\") {\n serializationObject.base64String = this._buffer;\n serializationObject.name = serializationObject.name.replace(\"data:\", \"\");\n }\n else if (this.url && this.url.startsWith(\"data:\") && this._buffer instanceof Uint8Array) {\n serializationObject.base64String = \"data:image/png;base64,\" + EncodeArrayBufferToBase64(this._buffer);\n }\n else if (Texture.ForceSerializeBuffers || (this.url && this.url.startsWith(\"blob:\")) || this._forceSerialize) {\n serializationObject.base64String =\n !this._engine || this._engine._features.supportSyncTextureRead ? GenerateBase64StringFromTexture(this) : GenerateBase64StringFromTextureAsync(this);\n }\n }\n serializationObject.invertY = this._invertY;\n serializationObject.samplingMode = this.samplingMode;\n serializationObject._creationFlags = this._creationFlags;\n serializationObject._useSRGBBuffer = this._useSRGBBuffer;\n if (Texture._SerializeInternalTextureUniqueId) {\n serializationObject.internalTextureUniqueId = (_b = (_a = this._texture) === null || _a === void 0 ? void 0 : _a.uniqueId) !== null && _b !== void 0 ? _b : undefined;\n }\n this.name = savedName;\n return serializationObject;\n }\n /**\n * Get the current class name of the texture useful for serialization or dynamic coding.\n * @returns \"Texture\"\n */\n getClassName() {\n return \"Texture\";\n }\n /**\n * Dispose the texture and release its associated resources.\n */\n dispose() {\n super.dispose();\n this.onLoadObservable.clear();\n this._delayedOnLoad = null;\n this._delayedOnError = null;\n this._buffer = null;\n }\n /**\n * Parse the JSON representation of a texture in order to recreate the texture in the given scene.\n * @param parsedTexture Define the JSON representation of the texture\n * @param scene Define the scene the parsed texture should be instantiated in\n * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies\n * @returns The parsed texture if successful\n */\n static Parse(parsedTexture, scene, rootUrl) {\n if (parsedTexture.customType) {\n const customTexture = InstantiationTools.Instantiate(parsedTexture.customType);\n // Update Sampling Mode\n const parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);\n if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {\n if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {\n parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);\n }\n }\n return parsedCustomTexture;\n }\n if (parsedTexture.isCube && !parsedTexture.isRenderTarget) {\n return Texture._CubeTextureParser(parsedTexture, scene, rootUrl);\n }\n const hasInternalTextureUniqueId = parsedTexture.internalTextureUniqueId !== undefined;\n if (!parsedTexture.name && !parsedTexture.isRenderTarget && !hasInternalTextureUniqueId) {\n return null;\n }\n let internalTexture;\n if (hasInternalTextureUniqueId) {\n const cache = scene.getEngine().getLoadedTexturesCache();\n for (const texture of cache) {\n if (texture.uniqueId === parsedTexture.internalTextureUniqueId) {\n internalTexture = texture;\n break;\n }\n }\n }\n const onLoaded = (texture) => {\n var _a;\n // Clear cache\n if (texture && texture._texture) {\n texture._texture._cachedWrapU = null;\n texture._texture._cachedWrapV = null;\n texture._texture._cachedWrapR = null;\n }\n // Update Sampling Mode\n if (parsedTexture.samplingMode) {\n const sampling = parsedTexture.samplingMode;\n if (texture && texture.samplingMode !== sampling) {\n texture.updateSamplingMode(sampling);\n }\n }\n // Animations\n if (texture && parsedTexture.animations) {\n for (let animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {\n const parsedAnimation = parsedTexture.animations[animationIndex];\n const internalClass = GetClass(\"BABYLON.Animation\");\n if (internalClass) {\n texture.animations.push(internalClass.Parse(parsedAnimation));\n }\n }\n }\n if (hasInternalTextureUniqueId && !internalTexture) {\n (_a = texture === null || texture === void 0 ? void 0 : texture._texture) === null || _a === void 0 ? void 0 : _a._setUniqueId(parsedTexture.internalTextureUniqueId);\n }\n };\n const texture = SerializationHelper.Parse(() => {\n var _a, _b, _c;\n let generateMipMaps = true;\n if (parsedTexture.noMipmap) {\n generateMipMaps = false;\n }\n if (parsedTexture.mirrorPlane) {\n const mirrorTexture = Texture._CreateMirror(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);\n mirrorTexture._waitingRenderList = parsedTexture.renderList;\n mirrorTexture.mirrorPlane = Plane.FromArray(parsedTexture.mirrorPlane);\n onLoaded(mirrorTexture);\n return mirrorTexture;\n }\n else if (parsedTexture.isRenderTarget) {\n let renderTargetTexture = null;\n if (parsedTexture.isCube) {\n // Search for an existing reflection probe (which contains a cube render target texture)\n if (scene.reflectionProbes) {\n for (let index = 0; index < scene.reflectionProbes.length; index++) {\n const probe = scene.reflectionProbes[index];\n if (probe.name === parsedTexture.name) {\n return probe.cubeTexture;\n }\n }\n }\n }\n else {\n renderTargetTexture = Texture._CreateRenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps, (_a = parsedTexture._creationFlags) !== null && _a !== void 0 ? _a : 0);\n renderTargetTexture._waitingRenderList = parsedTexture.renderList;\n }\n onLoaded(renderTargetTexture);\n return renderTargetTexture;\n }\n else {\n let texture;\n if (parsedTexture.base64String && !internalTexture) {\n // name and url are the same to ensure caching happens from the actual base64 string\n texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.base64String, scene, !generateMipMaps, parsedTexture.invertY, parsedTexture.samplingMode, () => {\n onLoaded(texture);\n }, (_b = parsedTexture._creationFlags) !== null && _b !== void 0 ? _b : 0, (_c = parsedTexture._useSRGBBuffer) !== null && _c !== void 0 ? _c : false);\n // prettier name to fit with the loaded data\n texture.name = parsedTexture.name;\n }\n else {\n let url;\n if (parsedTexture.name && (parsedTexture.name.indexOf(\"://\") > 0 || parsedTexture.name.startsWith(\"data:\"))) {\n url = parsedTexture.name;\n }\n else {\n url = rootUrl + parsedTexture.name;\n }\n if (parsedTexture.url && (parsedTexture.url.startsWith(\"data:\") || Texture.UseSerializedUrlIfAny)) {\n url = parsedTexture.url;\n }\n const options = {\n noMipmap: !generateMipMaps,\n invertY: parsedTexture.invertY,\n samplingMode: parsedTexture.samplingMode,\n onLoad: () => {\n onLoaded(texture);\n },\n internalTexture,\n };\n texture = new Texture(url, scene, options);\n }\n return texture;\n }\n }, parsedTexture, scene);\n return texture;\n }\n /**\n * Creates a texture from its base 64 representation.\n * @param data Define the base64 payload without the data: prefix\n * @param name Define the name of the texture in the scene useful fo caching purpose for instance\n * @param scene Define the scene the texture should belong to\n * @param noMipmapOrOptions defines if the texture will require mip maps or not or set of all options to create the texture\n * @param invertY define if the texture needs to be inverted on the y axis during loading\n * @param samplingMode define the sampling mode we want for the texture while fetching from it (Texture.NEAREST_SAMPLINGMODE...)\n * @param onLoad define a callback triggered when the texture has been loaded\n * @param onError define a callback triggered when an error occurred during the loading session\n * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)\n * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)\n * @returns the created texture\n */\n static CreateFromBase64String(data, name, scene, noMipmapOrOptions, invertY, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, onLoad = null, onError = null, format = 5, creationFlags) {\n return new Texture(\"data:\" + name, scene, noMipmapOrOptions, invertY, samplingMode, onLoad, onError, data, false, format, undefined, undefined, creationFlags);\n }\n /**\n * Creates a texture from its data: representation. (data: will be added in case only the payload has been passed in)\n * @param name Define the name of the texture in the scene useful fo caching purpose for instance\n * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation\n * @param scene Define the scene the texture should belong to\n * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load\n * @param noMipmapOrOptions defines if the texture will require mip maps or not or set of all options to create the texture\n * @param invertY define if the texture needs to be inverted on the y axis during loading\n * @param samplingMode define the sampling mode we want for the texture while fetching from it (Texture.NEAREST_SAMPLINGMODE...)\n * @param onLoad define a callback triggered when the texture has been loaded\n * @param onError define a callback triggered when an error occurred during the loading session\n * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)\n * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)\n * @returns the created texture\n */\n static LoadFromDataString(name, buffer, scene, deleteBuffer = false, noMipmapOrOptions, invertY = true, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, onLoad = null, onError = null, format = 5, creationFlags) {\n if (name.substr(0, 5) !== \"data:\") {\n name = \"data:\" + name;\n }\n return new Texture(name, scene, noMipmapOrOptions, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format, undefined, undefined, creationFlags);\n }\n}\n/**\n * Gets or sets a general boolean used to indicate that textures containing direct data (buffers) must be saved as part of the serialization process\n */\nTexture.SerializeBuffers = true;\n/**\n * Gets or sets a general boolean used to indicate that texture buffers must be saved as part of the serialization process.\n * If no buffer exists, one will be created as base64 string from the internal webgl data.\n */\nTexture.ForceSerializeBuffers = false;\n/**\n * This observable will notify when any texture had a loading error\n */\nTexture.OnTextureLoadErrorObservable = new Observable();\n/** @internal */\nTexture._SerializeInternalTextureUniqueId = false;\n/**\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nTexture._CubeTextureParser = (jsonTexture, scene, rootUrl) => {\n throw _WarnImport(\"CubeTexture\");\n};\n/**\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nTexture._CreateMirror = (name, renderTargetSize, scene, generateMipMaps) => {\n throw _WarnImport(\"MirrorTexture\");\n};\n/**\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nTexture._CreateRenderTargetTexture = (name, renderTargetSize, scene, generateMipMaps, creationFlags) => {\n throw _WarnImport(\"RenderTargetTexture\");\n};\n/** nearest is mag = nearest and min = nearest and no mip */\nTexture.NEAREST_SAMPLINGMODE = 1;\n/** nearest is mag = nearest and min = nearest and mip = linear */\nTexture.NEAREST_NEAREST_MIPLINEAR = 8; // nearest is mag = nearest and min = nearest and mip = linear\n/** Bilinear is mag = linear and min = linear and no mip */\nTexture.BILINEAR_SAMPLINGMODE = 2;\n/** Bilinear is mag = linear and min = linear and mip = nearest */\nTexture.LINEAR_LINEAR_MIPNEAREST = 11; // Bilinear is mag = linear and min = linear and mip = nearest\n/** Trilinear is mag = linear and min = linear and mip = linear */\nTexture.TRILINEAR_SAMPLINGMODE = 3;\n/** Trilinear is mag = linear and min = linear and mip = linear */\nTexture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear\n/** mag = nearest and min = nearest and mip = nearest */\nTexture.NEAREST_NEAREST_MIPNEAREST = 4;\n/** mag = nearest and min = linear and mip = nearest */\nTexture.NEAREST_LINEAR_MIPNEAREST = 5;\n/** mag = nearest and min = linear and mip = linear */\nTexture.NEAREST_LINEAR_MIPLINEAR = 6;\n/** mag = nearest and min = linear and mip = none */\nTexture.NEAREST_LINEAR = 7;\n/** mag = nearest and min = nearest and mip = none */\nTexture.NEAREST_NEAREST = 1;\n/** mag = linear and min = nearest and mip = nearest */\nTexture.LINEAR_NEAREST_MIPNEAREST = 9;\n/** mag = linear and min = nearest and mip = linear */\nTexture.LINEAR_NEAREST_MIPLINEAR = 10;\n/** mag = linear and min = linear and mip = none */\nTexture.LINEAR_LINEAR = 2;\n/** mag = linear and min = nearest and mip = none */\nTexture.LINEAR_NEAREST = 12;\n/** Explicit coordinates mode */\nTexture.EXPLICIT_MODE = 0;\n/** Spherical coordinates mode */\nTexture.SPHERICAL_MODE = 1;\n/** Planar coordinates mode */\nTexture.PLANAR_MODE = 2;\n/** Cubic coordinates mode */\nTexture.CUBIC_MODE = 3;\n/** Projection coordinates mode */\nTexture.PROJECTION_MODE = 4;\n/** Inverse Cubic coordinates mode */\nTexture.SKYBOX_MODE = 5;\n/** Inverse Cubic coordinates mode */\nTexture.INVCUBIC_MODE = 6;\n/** Equirectangular coordinates mode */\nTexture.EQUIRECTANGULAR_MODE = 7;\n/** Equirectangular Fixed coordinates mode */\nTexture.FIXED_EQUIRECTANGULAR_MODE = 8;\n/** Equirectangular Fixed Mirrored coordinates mode */\nTexture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;\n/** Texture is not repeating outside of 0..1 UVs */\nTexture.CLAMP_ADDRESSMODE = 0;\n/** Texture is repeating outside of 0..1 UVs */\nTexture.WRAP_ADDRESSMODE = 1;\n/** Texture is repeating and mirrored */\nTexture.MIRROR_ADDRESSMODE = 2;\n/**\n * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file\n */\nTexture.UseSerializedUrlIfAny = false;\n__decorate([\n serialize()\n], Texture.prototype, \"url\", void 0);\n__decorate([\n serialize()\n], Texture.prototype, \"uOffset\", void 0);\n__decorate([\n serialize()\n], Texture.prototype, \"vOffset\", void 0);\n__decorate([\n serialize()\n], Texture.prototype, \"uScale\", void 0);\n__decorate([\n serialize()\n], Texture.prototype, \"vScale\", void 0);\n__decorate([\n serialize()\n], Texture.prototype, \"uAng\", void 0);\n__decorate([\n serialize()\n], Texture.prototype, \"vAng\", void 0);\n__decorate([\n serialize()\n], Texture.prototype, \"wAng\", void 0);\n__decorate([\n serialize()\n], Texture.prototype, \"uRotationCenter\", void 0);\n__decorate([\n serialize()\n], Texture.prototype, \"vRotationCenter\", void 0);\n__decorate([\n serialize()\n], Texture.prototype, \"wRotationCenter\", void 0);\n__decorate([\n serialize()\n], Texture.prototype, \"homogeneousRotationInUVTransform\", void 0);\n__decorate([\n serialize()\n], Texture.prototype, \"isBlocking\", null);\n// References the dependencies.\nRegisterClass(\"BABYLON.Texture\", Texture);\nSerializationHelper._TextureParser = Texture.Parse;\n//# sourceMappingURL=texture.js.map","import { InternalTexture, InternalTextureSource } from \"../../Materials/Textures/internalTexture.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n\nimport { ThinEngine } from \"../thinEngine.js\";\nThinEngine.prototype.updateRawTexture = function (texture, data, format, invertY, compression = null, type = 0, useSRGBBuffer = false) {\n if (!texture) {\n return;\n }\n // Babylon's internalSizedFomat but gl's texImage2D internalFormat\n const internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format, useSRGBBuffer);\n // Babylon's internalFormat but gl's texImage2D format\n const internalFormat = this._getInternalFormat(format);\n const textureType = this._getWebGLTextureType(type);\n this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);\n this._unpackFlipY(invertY === undefined ? true : invertY ? true : false);\n if (!this._doNotHandleContextLost) {\n texture._bufferView = data;\n texture.format = format;\n texture.type = type;\n texture.invertY = invertY;\n texture._compression = compression;\n }\n if (texture.width % 4 !== 0) {\n this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);\n }\n if (compression && data) {\n this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);\n }\n else {\n this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);\n }\n if (texture.generateMipMaps) {\n this._gl.generateMipmap(this._gl.TEXTURE_2D);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_2D, null);\n // this.resetTextureCache();\n texture.isReady = true;\n};\nThinEngine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression = null, type = 0, \n// eslint-disable-next-line @typescript-eslint/no-unused-vars\ncreationFlags = 0, useSRGBBuffer = false) {\n const texture = new InternalTexture(this, InternalTextureSource.Raw);\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = width;\n texture.height = height;\n texture.format = format;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.invertY = invertY;\n texture._compression = compression;\n texture.type = type;\n texture._useSRGBBuffer = this._getUseSRGBBuffer(useSRGBBuffer, !generateMipMaps);\n if (!this._doNotHandleContextLost) {\n texture._bufferView = data;\n }\n this.updateRawTexture(texture, data, format, invertY, compression, type, texture._useSRGBBuffer);\n this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);\n // Filters\n const filters = this._getSamplingParameters(samplingMode, generateMipMaps);\n this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);\n this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);\n if (generateMipMaps) {\n this._gl.generateMipmap(this._gl.TEXTURE_2D);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_2D, null);\n this._internalTexturesCache.push(texture);\n return texture;\n};\nThinEngine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression = null) {\n const gl = this._gl;\n const texture = new InternalTexture(this, InternalTextureSource.CubeRaw);\n texture.isCube = true;\n texture.format = format;\n texture.type = type;\n if (!this._doNotHandleContextLost) {\n texture._bufferViewArray = data;\n }\n const textureType = this._getWebGLTextureType(type);\n let internalFormat = this._getInternalFormat(format);\n if (internalFormat === gl.RGB) {\n internalFormat = gl.RGBA;\n }\n // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable\n if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {\n generateMipMaps = false;\n samplingMode = 1;\n Logger.Warn(\"Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.\");\n }\n else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {\n generateMipMaps = false;\n samplingMode = 1;\n Logger.Warn(\"Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.\");\n }\n else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {\n generateMipMaps = false;\n Logger.Warn(\"Render to float textures is not supported. Mipmap generation forced to false.\");\n }\n else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {\n generateMipMaps = false;\n Logger.Warn(\"Render to half float textures is not supported. Mipmap generation forced to false.\");\n }\n const width = size;\n const height = width;\n texture.width = width;\n texture.height = height;\n texture.invertY = invertY;\n texture._compression = compression;\n // Double check on POT to generate Mips.\n const isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));\n if (!isPot) {\n generateMipMaps = false;\n }\n // Upload data if needed. The texture won't be ready until then.\n if (data) {\n this.updateRawCubeTexture(texture, data, format, type, invertY, compression);\n }\n else {\n const internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);\n const level = 0;\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);\n for (let faceIndex = 0; faceIndex < 6; faceIndex++) {\n if (compression) {\n gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, undefined);\n }\n else {\n gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, null);\n }\n }\n this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);\n // Filters\n if (data && generateMipMaps) {\n this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);\n }\n const filters = this._getSamplingParameters(samplingMode, generateMipMaps);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.isReady = true;\n return texture;\n};\nThinEngine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression = null, level = 0) {\n texture._bufferViewArray = data;\n texture.format = format;\n texture.type = type;\n texture.invertY = invertY;\n texture._compression = compression;\n const gl = this._gl;\n const textureType = this._getWebGLTextureType(type);\n let internalFormat = this._getInternalFormat(format);\n const internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);\n let needConversion = false;\n if (internalFormat === gl.RGB) {\n internalFormat = gl.RGBA;\n needConversion = true;\n }\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);\n this._unpackFlipY(invertY === undefined ? true : invertY ? true : false);\n if (texture.width % 4 !== 0) {\n gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);\n }\n // Data are known to be in +X +Y +Z -X -Y -Z\n for (let faceIndex = 0; faceIndex < 6; faceIndex++) {\n let faceData = data[faceIndex];\n if (compression) {\n gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, faceData);\n }\n else {\n if (needConversion) {\n faceData = _convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);\n }\n gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);\n }\n }\n const isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));\n if (isPot && texture.generateMipMaps && level === 0) {\n this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);\n // this.resetTextureCache();\n texture.isReady = true;\n};\nThinEngine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad = null, onError = null, samplingMode = 3, invertY = false) {\n const gl = this._gl;\n const texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode, null);\n scene === null || scene === void 0 ? void 0 : scene.addPendingData(texture);\n texture.url = url;\n texture.isReady = false;\n this._internalTexturesCache.push(texture);\n const onerror = (request, exception) => {\n scene === null || scene === void 0 ? void 0 : scene.removePendingData(texture);\n if (onError && request) {\n onError(request.status + \" \" + request.statusText, exception);\n }\n };\n const internalCallback = (data) => {\n const width = texture.width;\n const faceDataArrays = callback(data);\n if (!faceDataArrays) {\n return;\n }\n if (mipmapGenerator) {\n const textureType = this._getWebGLTextureType(type);\n let internalFormat = this._getInternalFormat(format);\n const internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);\n let needConversion = false;\n if (internalFormat === gl.RGB) {\n internalFormat = gl.RGBA;\n needConversion = true;\n }\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);\n this._unpackFlipY(false);\n const mipData = mipmapGenerator(faceDataArrays);\n for (let level = 0; level < mipData.length; level++) {\n const mipSize = width >> level;\n for (let faceIndex = 0; faceIndex < 6; faceIndex++) {\n let mipFaceData = mipData[level][faceIndex];\n if (needConversion) {\n mipFaceData = _convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);\n }\n gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);\n }\n }\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n }\n else {\n this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);\n }\n texture.isReady = true;\n // this.resetTextureCache();\n scene === null || scene === void 0 ? void 0 : scene.removePendingData(texture);\n texture.onLoadedObservable.notifyObservers(texture);\n texture.onLoadedObservable.clear();\n if (onLoad) {\n onLoad();\n }\n };\n this._loadFile(url, (data) => {\n internalCallback(data);\n }, undefined, scene === null || scene === void 0 ? void 0 : scene.offlineProvider, true, onerror);\n return texture;\n};\n/**\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nfunction _convertRGBtoRGBATextureData(rgbData, width, height, textureType) {\n // Create new RGBA data container.\n let rgbaData;\n let val1 = 1;\n if (textureType === 1) {\n rgbaData = new Float32Array(width * height * 4);\n }\n else if (textureType === 2) {\n rgbaData = new Uint16Array(width * height * 4);\n val1 = 15360; // 15360 is the encoding of 1 in half float\n }\n else if (textureType === 7) {\n rgbaData = new Uint32Array(width * height * 4);\n }\n else {\n rgbaData = new Uint8Array(width * height * 4);\n }\n // Convert each pixel.\n for (let x = 0; x < width; x++) {\n for (let y = 0; y < height; y++) {\n const index = (y * width + x) * 3;\n const newIndex = (y * width + x) * 4;\n // Map Old Value to new value.\n rgbaData[newIndex + 0] = rgbData[index + 0];\n rgbaData[newIndex + 1] = rgbData[index + 1];\n rgbaData[newIndex + 2] = rgbData[index + 2];\n // Add fully opaque alpha channel.\n rgbaData[newIndex + 3] = val1;\n }\n }\n return rgbaData;\n}\n/**\n * Create a function for createRawTexture3D/createRawTexture2DArray\n * @param is3D true for TEXTURE_3D and false for TEXTURE_2D_ARRAY\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nfunction _makeCreateRawTextureFunction(is3D) {\n return function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression = null, textureType = 0) {\n const target = is3D ? this._gl.TEXTURE_3D : this._gl.TEXTURE_2D_ARRAY;\n const source = is3D ? InternalTextureSource.Raw3D : InternalTextureSource.Raw2DArray;\n const texture = new InternalTexture(this, source);\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.baseDepth = depth;\n texture.width = width;\n texture.height = height;\n texture.depth = depth;\n texture.format = format;\n texture.type = textureType;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n if (is3D) {\n texture.is3D = true;\n }\n else {\n texture.is2DArray = true;\n }\n if (!this._doNotHandleContextLost) {\n texture._bufferView = data;\n }\n if (is3D) {\n this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);\n }\n else {\n this.updateRawTexture2DArray(texture, data, format, invertY, compression, textureType);\n }\n this._bindTextureDirectly(target, texture, true);\n // Filters\n const filters = this._getSamplingParameters(samplingMode, generateMipMaps);\n this._gl.texParameteri(target, this._gl.TEXTURE_MAG_FILTER, filters.mag);\n this._gl.texParameteri(target, this._gl.TEXTURE_MIN_FILTER, filters.min);\n if (generateMipMaps) {\n this._gl.generateMipmap(target);\n }\n this._bindTextureDirectly(target, null);\n this._internalTexturesCache.push(texture);\n return texture;\n };\n}\nThinEngine.prototype.createRawTexture2DArray = _makeCreateRawTextureFunction(false);\nThinEngine.prototype.createRawTexture3D = _makeCreateRawTextureFunction(true);\n/**\n * Create a function for updateRawTexture3D/updateRawTexture2DArray\n * @param is3D true for TEXTURE_3D and false for TEXTURE_2D_ARRAY\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nfunction _makeUpdateRawTextureFunction(is3D) {\n return function (texture, data, format, invertY, compression = null, textureType = 0) {\n const target = is3D ? this._gl.TEXTURE_3D : this._gl.TEXTURE_2D_ARRAY;\n const internalType = this._getWebGLTextureType(textureType);\n const internalFormat = this._getInternalFormat(format);\n const internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);\n this._bindTextureDirectly(target, texture, true);\n this._unpackFlipY(invertY === undefined ? true : invertY ? true : false);\n if (!this._doNotHandleContextLost) {\n texture._bufferView = data;\n texture.format = format;\n texture.invertY = invertY;\n texture._compression = compression;\n }\n if (texture.width % 4 !== 0) {\n this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);\n }\n if (compression && data) {\n this._gl.compressedTexImage3D(target, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);\n }\n else {\n this._gl.texImage3D(target, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);\n }\n if (texture.generateMipMaps) {\n this._gl.generateMipmap(target);\n }\n this._bindTextureDirectly(target, null);\n // this.resetTextureCache();\n texture.isReady = true;\n };\n}\nThinEngine.prototype.updateRawTexture2DArray = _makeUpdateRawTextureFunction(false);\nThinEngine.prototype.updateRawTexture3D = _makeUpdateRawTextureFunction(true);\n//# sourceMappingURL=engine.rawTexture.js.map","import { Texture } from \"./texture.js\";\n\nimport \"../../Engines/Extensions/engine.rawTexture.js\";\n/**\n * Raw texture can help creating a texture directly from an array of data.\n * This can be super useful if you either get the data from an uncompressed source or\n * if you wish to create your texture pixel by pixel.\n */\nexport class RawTexture extends Texture {\n /**\n * Instantiates a new RawTexture.\n * Raw texture can help creating a texture directly from an array of data.\n * This can be super useful if you either get the data from an uncompressed source or\n * if you wish to create your texture pixel by pixel.\n * @param data define the array of data to use to create the texture (null to create an empty texture)\n * @param width define the width of the texture\n * @param height define the height of the texture\n * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)\n * @param sceneOrEngine defines the scene or engine the texture will belong to\n * @param generateMipMaps define whether mip maps should be generated or not\n * @param invertY define if the data should be flipped on Y when uploaded to the GPU\n * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)\n * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)\n * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)\n * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU).\n */\n constructor(data, width, height, \n /**\n * Define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)\n */\n format, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, creationFlags, useSRGBBuffer) {\n super(null, sceneOrEngine, !generateMipMaps, invertY, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, creationFlags);\n this.format = format;\n if (!this._engine) {\n return;\n }\n if (!this._engine._caps.textureFloatLinearFiltering && type === 1) {\n samplingMode = 1;\n }\n if (!this._engine._caps.textureHalfFloatLinearFiltering && type === 2) {\n samplingMode = 1;\n }\n this._texture = this._engine.createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type, creationFlags !== null && creationFlags !== void 0 ? creationFlags : 0, useSRGBBuffer !== null && useSRGBBuffer !== void 0 ? useSRGBBuffer : false);\n this.wrapU = Texture.CLAMP_ADDRESSMODE;\n this.wrapV = Texture.CLAMP_ADDRESSMODE;\n }\n /**\n * Updates the texture underlying data.\n * @param data Define the new data of the texture\n */\n update(data) {\n this._getEngine().updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, null, this._texture.type, this._texture._useSRGBBuffer);\n }\n /**\n * Creates a luminance texture from some data.\n * @param data Define the texture data\n * @param width Define the width of the texture\n * @param height Define the height of the texture\n * @param sceneOrEngine defines the scene or engine the texture will belong to\n * @param generateMipMaps Define whether or not to create mip maps for the texture\n * @param invertY define if the data should be flipped on Y when uploaded to the GPU\n * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)\n * @returns the luminance texture\n */\n static CreateLuminanceTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3) {\n return new RawTexture(data, width, height, 1, sceneOrEngine, generateMipMaps, invertY, samplingMode);\n }\n /**\n * Creates a luminance alpha texture from some data.\n * @param data Define the texture data\n * @param width Define the width of the texture\n * @param height Define the height of the texture\n * @param sceneOrEngine defines the scene or engine the texture will belong to\n * @param generateMipMaps Define whether or not to create mip maps for the texture\n * @param invertY define if the data should be flipped on Y when uploaded to the GPU\n * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)\n * @returns the luminance alpha texture\n */\n static CreateLuminanceAlphaTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3) {\n return new RawTexture(data, width, height, 2, sceneOrEngine, generateMipMaps, invertY, samplingMode);\n }\n /**\n * Creates an alpha texture from some data.\n * @param data Define the texture data\n * @param width Define the width of the texture\n * @param height Define the height of the texture\n * @param sceneOrEngine defines the scene or engine the texture will belong to\n * @param generateMipMaps Define whether or not to create mip maps for the texture\n * @param invertY define if the data should be flipped on Y when uploaded to the GPU\n * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)\n * @returns the alpha texture\n */\n static CreateAlphaTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3) {\n return new RawTexture(data, width, height, 0, sceneOrEngine, generateMipMaps, invertY, samplingMode);\n }\n /**\n * Creates a RGB texture from some data.\n * @param data Define the texture data\n * @param width Define the width of the texture\n * @param height Define the height of the texture\n * @param sceneOrEngine defines the scene or engine the texture will belong to\n * @param generateMipMaps Define whether or not to create mip maps for the texture\n * @param invertY define if the data should be flipped on Y when uploaded to the GPU\n * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)\n * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)\n * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)\n * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU).\n * @returns the RGB alpha texture\n */\n static CreateRGBTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, creationFlags = 0, useSRGBBuffer = false) {\n return new RawTexture(data, width, height, 4, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, creationFlags, useSRGBBuffer);\n }\n /**\n * Creates a RGBA texture from some data.\n * @param data Define the texture data\n * @param width Define the width of the texture\n * @param height Define the height of the texture\n * @param sceneOrEngine defines the scene or engine the texture will belong to\n * @param generateMipMaps Define whether or not to create mip maps for the texture\n * @param invertY define if the data should be flipped on Y when uploaded to the GPU\n * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)\n * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)\n * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)\n * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU).\n * @returns the RGBA texture\n */\n static CreateRGBATexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, creationFlags = 0, useSRGBBuffer = false) {\n return new RawTexture(data, width, height, 5, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, creationFlags, useSRGBBuffer);\n }\n /**\n * Creates a RGBA storage texture from some data.\n * @param data Define the texture data\n * @param width Define the width of the texture\n * @param height Define the height of the texture\n * @param sceneOrEngine defines the scene or engine the texture will belong to\n * @param generateMipMaps Define whether or not to create mip maps for the texture\n * @param invertY define if the data should be flipped on Y when uploaded to the GPU\n * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)\n * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)\n * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU).\n * @returns the RGBA texture\n */\n static CreateRGBAStorageTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, useSRGBBuffer = false) {\n return new RawTexture(data, width, height, 5, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, 1, useSRGBBuffer);\n }\n /**\n * Creates a R texture from some data.\n * @param data Define the texture data\n * @param width Define the width of the texture\n * @param height Define the height of the texture\n * @param sceneOrEngine defines the scene or engine the texture will belong to\n * @param generateMipMaps Define whether or not to create mip maps for the texture\n * @param invertY define if the data should be flipped on Y when uploaded to the GPU\n * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)\n * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)\n * @returns the R texture\n */\n static CreateRTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, type = 1) {\n return new RawTexture(data, width, height, 6, sceneOrEngine, generateMipMaps, invertY, samplingMode, type);\n }\n /**\n * Creates a R storage texture from some data.\n * @param data Define the texture data\n * @param width Define the width of the texture\n * @param height Define the height of the texture\n * @param sceneOrEngine defines the scene or engine the texture will belong to\n * @param generateMipMaps Define whether or not to create mip maps for the texture\n * @param invertY define if the data should be flipped on Y when uploaded to the GPU\n * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)\n * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)\n * @returns the R texture\n */\n static CreateRStorageTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, type = 1) {\n return new RawTexture(data, width, height, 6, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, 1);\n }\n}\n//# sourceMappingURL=rawTexture.js.map","import { PointerEventTypes } from \"../../Events/pointerEvents.js\";\nimport { PrecisionDate } from \"../../Misc/precisionDate.js\";\nimport { Epsilon } from \"../../Maths/math.constants.js\";\n/**\n * The autoRotation behavior (AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#autorotation-behavior\n */\nexport class AutoRotationBehavior {\n constructor() {\n this._zoomStopsAnimation = false;\n this._idleRotationSpeed = 0.05;\n this._idleRotationWaitTime = 2000;\n this._idleRotationSpinupTime = 2000;\n this.targetAlpha = null;\n this._isPointerDown = false;\n this._lastFrameTime = null;\n this._lastInteractionTime = -Infinity;\n this._cameraRotationSpeed = 0;\n this._lastFrameRadius = 0;\n }\n /**\n * Gets the name of the behavior.\n */\n get name() {\n return \"AutoRotation\";\n }\n /**\n * Sets the flag that indicates if user zooming should stop animation.\n */\n set zoomStopsAnimation(flag) {\n this._zoomStopsAnimation = flag;\n }\n /**\n * Gets the flag that indicates if user zooming should stop animation.\n */\n get zoomStopsAnimation() {\n return this._zoomStopsAnimation;\n }\n /**\n * Sets the default speed at which the camera rotates around the model.\n */\n set idleRotationSpeed(speed) {\n this._idleRotationSpeed = speed;\n }\n /**\n * Gets the default speed at which the camera rotates around the model.\n */\n get idleRotationSpeed() {\n return this._idleRotationSpeed;\n }\n /**\n * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.\n */\n set idleRotationWaitTime(time) {\n this._idleRotationWaitTime = time;\n }\n /**\n * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.\n */\n get idleRotationWaitTime() {\n return this._idleRotationWaitTime;\n }\n /**\n * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.\n */\n set idleRotationSpinupTime(time) {\n this._idleRotationSpinupTime = time;\n }\n /**\n * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.\n */\n get idleRotationSpinupTime() {\n return this._idleRotationSpinupTime;\n }\n /**\n * Gets a value indicating if the camera is currently rotating because of this behavior\n */\n get rotationInProgress() {\n return Math.abs(this._cameraRotationSpeed) > 0;\n }\n /**\n * Initializes the behavior.\n */\n init() {\n // Do nothing\n }\n /**\n * Attaches the behavior to its arc rotate camera.\n * @param camera Defines the camera to attach the behavior to\n */\n attach(camera) {\n this._attachedCamera = camera;\n const scene = this._attachedCamera.getScene();\n this._onPrePointerObservableObserver = scene.onPrePointerObservable.add((pointerInfoPre) => {\n if (pointerInfoPre.type === PointerEventTypes.POINTERDOWN) {\n this._isPointerDown = true;\n return;\n }\n if (pointerInfoPre.type === PointerEventTypes.POINTERUP) {\n this._isPointerDown = false;\n }\n });\n this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(() => {\n if (this._reachTargetAlpha()) {\n return;\n }\n const now = PrecisionDate.Now;\n let dt = 0;\n if (this._lastFrameTime != null) {\n dt = now - this._lastFrameTime;\n }\n this._lastFrameTime = now;\n // Stop the animation if there is user interaction and the animation should stop for this interaction\n this._applyUserInteraction();\n const timeToRotation = now - this._lastInteractionTime - this._idleRotationWaitTime;\n const scale = Math.max(Math.min(timeToRotation / this._idleRotationSpinupTime, 1), 0);\n this._cameraRotationSpeed = this._idleRotationSpeed * scale;\n // Step camera rotation by rotation speed\n if (this._attachedCamera) {\n this._attachedCamera.alpha -= this._cameraRotationSpeed * (dt / 1000);\n }\n });\n }\n /**\n * Detaches the behavior from its current arc rotate camera.\n */\n detach() {\n if (!this._attachedCamera) {\n return;\n }\n const scene = this._attachedCamera.getScene();\n if (this._onPrePointerObservableObserver) {\n scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);\n }\n this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);\n this._attachedCamera = null;\n }\n /**\n * Force-reset the last interaction time\n * @param customTime an optional time that will be used instead of the current last interaction time. For example `Date.now()`\n */\n resetLastInteractionTime(customTime) {\n this._lastInteractionTime = customTime !== null && customTime !== void 0 ? customTime : PrecisionDate.Now;\n }\n /**\n * Returns true if camera alpha reaches the target alpha\n * @returns true if camera alpha reaches the target alpha\n */\n _reachTargetAlpha() {\n if (this._attachedCamera && this.targetAlpha) {\n return Math.abs(this._attachedCamera.alpha - this.targetAlpha) < Epsilon;\n }\n return false;\n }\n /**\n * Returns true if user is scrolling.\n * @returns true if user is scrolling.\n */\n _userIsZooming() {\n if (!this._attachedCamera) {\n return false;\n }\n return this._attachedCamera.inertialRadiusOffset !== 0;\n }\n _shouldAnimationStopForInteraction() {\n if (!this._attachedCamera) {\n return false;\n }\n let zoomHasHitLimit = false;\n if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {\n zoomHasHitLimit = true;\n }\n // Update the record of previous radius - works as an approx. indicator of hitting radius limits\n this._lastFrameRadius = this._attachedCamera.radius;\n return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();\n }\n /**\n * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.\n */\n _applyUserInteraction() {\n if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {\n this._lastInteractionTime = PrecisionDate.Now;\n }\n }\n // Tools\n _userIsMoving() {\n if (!this._attachedCamera) {\n return false;\n }\n return (this._attachedCamera.inertialAlphaOffset !== 0 ||\n this._attachedCamera.inertialBetaOffset !== 0 ||\n this._attachedCamera.inertialRadiusOffset !== 0 ||\n this._attachedCamera.inertialPanningX !== 0 ||\n this._attachedCamera.inertialPanningY !== 0 ||\n this._isPointerDown);\n }\n}\n//# sourceMappingURL=autoRotationBehavior.js.map","import { BackEase, EasingFunction } from \"../../Animations/easing.js\";\nimport { Animation } from \"../../Animations/animation.js\";\n/**\n * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius\n * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#bouncing-behavior\n */\nexport class BouncingBehavior {\n constructor() {\n /**\n * The duration of the animation, in milliseconds\n */\n this.transitionDuration = 450;\n /**\n * Length of the distance animated by the transition when lower radius is reached\n */\n this.lowerRadiusTransitionRange = 2;\n /**\n * Length of the distance animated by the transition when upper radius is reached\n */\n this.upperRadiusTransitionRange = -2;\n this._autoTransitionRange = false;\n // Animations\n this._radiusIsAnimating = false;\n this._radiusBounceTransition = null;\n this._animatables = new Array();\n }\n /**\n * Gets the name of the behavior.\n */\n get name() {\n return \"Bouncing\";\n }\n /**\n * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically\n */\n get autoTransitionRange() {\n return this._autoTransitionRange;\n }\n /**\n * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically\n * Transition ranges will be set to 5% of the bounding box diagonal in world space\n */\n set autoTransitionRange(value) {\n if (this._autoTransitionRange === value) {\n return;\n }\n this._autoTransitionRange = value;\n const camera = this._attachedCamera;\n if (!camera) {\n return;\n }\n if (value) {\n this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add((mesh) => {\n if (!mesh) {\n return;\n }\n mesh.computeWorldMatrix(true);\n const diagonal = mesh.getBoundingInfo().diagonalLength;\n this.lowerRadiusTransitionRange = diagonal * 0.05;\n this.upperRadiusTransitionRange = diagonal * 0.05;\n });\n }\n else if (this._onMeshTargetChangedObserver) {\n camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);\n }\n }\n /**\n * Initializes the behavior.\n */\n init() {\n // Do nothing\n }\n /**\n * Attaches the behavior to its arc rotate camera.\n * @param camera Defines the camera to attach the behavior to\n */\n attach(camera) {\n this._attachedCamera = camera;\n this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(() => {\n if (!this._attachedCamera) {\n return;\n }\n // Add the bounce animation to the lower radius limit\n if (this._isRadiusAtLimit(this._attachedCamera.lowerRadiusLimit)) {\n this._applyBoundRadiusAnimation(this.lowerRadiusTransitionRange);\n }\n // Add the bounce animation to the upper radius limit\n if (this._isRadiusAtLimit(this._attachedCamera.upperRadiusLimit)) {\n this._applyBoundRadiusAnimation(this.upperRadiusTransitionRange);\n }\n });\n }\n /**\n * Detaches the behavior from its current arc rotate camera.\n */\n detach() {\n if (!this._attachedCamera) {\n return;\n }\n if (this._onAfterCheckInputsObserver) {\n this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);\n }\n if (this._onMeshTargetChangedObserver) {\n this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);\n }\n this._attachedCamera = null;\n }\n /**\n * Checks if the camera radius is at the specified limit. Takes into account animation locks.\n * @param radiusLimit The limit to check against.\n * @returns Bool to indicate if at limit.\n */\n _isRadiusAtLimit(radiusLimit) {\n if (!this._attachedCamera) {\n return false;\n }\n if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {\n return true;\n }\n return false;\n }\n /**\n * Applies an animation to the radius of the camera, extending by the radiusDelta.\n * @param radiusDelta The delta by which to animate to. Can be negative.\n */\n _applyBoundRadiusAnimation(radiusDelta) {\n if (!this._attachedCamera) {\n return;\n }\n if (!this._radiusBounceTransition) {\n BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);\n this._radiusBounceTransition = Animation.CreateAnimation(\"radius\", Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);\n }\n // Prevent zoom until bounce has completed\n this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;\n this._attachedCamera.wheelPrecision = Infinity;\n this._attachedCamera.inertialRadiusOffset = 0;\n // Animate to the radius limit\n this.stopAllAnimations();\n this._radiusIsAnimating = true;\n const animatable = Animation.TransitionTo(\"radius\", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, () => this._clearAnimationLocks());\n if (animatable) {\n this._animatables.push(animatable);\n }\n }\n /**\n * Removes all animation locks. Allows new animations to be added to any of the camera properties.\n */\n _clearAnimationLocks() {\n this._radiusIsAnimating = false;\n if (this._attachedCamera) {\n this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;\n }\n }\n /**\n * Stops and removes all animations that have been applied to the camera\n */\n stopAllAnimations() {\n if (this._attachedCamera) {\n this._attachedCamera.animations = [];\n }\n while (this._animatables.length) {\n this._animatables[0].onAnimationEnd = null;\n this._animatables[0].stop();\n this._animatables.shift();\n }\n }\n}\n/**\n * The easing function used by animations\n */\nBouncingBehavior.EasingFunction = new BackEase(0.3);\n/**\n * The easing mode used by animations\n */\nBouncingBehavior.EasingMode = EasingFunction.EASINGMODE_EASEOUT;\n//# sourceMappingURL=bouncingBehavior.js.map","import { ExponentialEase, EasingFunction } from \"../../Animations/easing.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { PointerEventTypes } from \"../../Events/pointerEvents.js\";\nimport { PrecisionDate } from \"../../Misc/precisionDate.js\";\nimport { Vector3, Vector2 } from \"../../Maths/math.vector.js\";\nimport { Animation } from \"../../Animations/animation.js\";\n/**\n * The framing behavior (FramingBehavior) is designed to automatically position an ArcRotateCamera when its target is set to a mesh. It is also useful if you want to prevent the camera to go under a virtual horizontal plane.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#framing-behavior\n */\nexport class FramingBehavior {\n constructor() {\n /**\n * An event triggered when the animation to zoom on target mesh has ended\n */\n this.onTargetFramingAnimationEndObservable = new Observable();\n this._mode = FramingBehavior.FitFrustumSidesMode;\n this._radiusScale = 1.0;\n this._positionScale = 0.5;\n this._defaultElevation = 0.3;\n this._elevationReturnTime = 1500;\n this._elevationReturnWaitTime = 1000;\n this._zoomStopsAnimation = false;\n this._framingTime = 1500;\n /**\n * Define if the behavior should automatically change the configured\n * camera limits and sensibilities.\n */\n this.autoCorrectCameraLimitsAndSensibility = true;\n this._isPointerDown = false;\n this._lastInteractionTime = -Infinity;\n // Framing control\n this._animatables = new Array();\n this._betaIsAnimating = false;\n }\n /**\n * Gets the name of the behavior.\n */\n get name() {\n return \"Framing\";\n }\n /**\n * Sets the current mode used by the behavior\n */\n set mode(mode) {\n this._mode = mode;\n }\n /**\n * Gets current mode used by the behavior.\n */\n get mode() {\n return this._mode;\n }\n /**\n * Sets the scale applied to the radius (1 by default)\n */\n set radiusScale(radius) {\n this._radiusScale = radius;\n }\n /**\n * Gets the scale applied to the radius\n */\n get radiusScale() {\n return this._radiusScale;\n }\n /**\n * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.\n */\n set positionScale(scale) {\n this._positionScale = scale;\n }\n /**\n * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.\n */\n get positionScale() {\n return this._positionScale;\n }\n /**\n * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle\n * behaviour is triggered, in radians.\n */\n set defaultElevation(elevation) {\n this._defaultElevation = elevation;\n }\n /**\n * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle\n * behaviour is triggered, in radians.\n */\n get defaultElevation() {\n return this._defaultElevation;\n }\n /**\n * Sets the time (in milliseconds) taken to return to the default beta position.\n * Negative value indicates camera should not return to default.\n */\n set elevationReturnTime(speed) {\n this._elevationReturnTime = speed;\n }\n /**\n * Gets the time (in milliseconds) taken to return to the default beta position.\n * Negative value indicates camera should not return to default.\n */\n get elevationReturnTime() {\n return this._elevationReturnTime;\n }\n /**\n * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.\n */\n set elevationReturnWaitTime(time) {\n this._elevationReturnWaitTime = time;\n }\n /**\n * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.\n */\n get elevationReturnWaitTime() {\n return this._elevationReturnWaitTime;\n }\n /**\n * Sets the flag that indicates if user zooming should stop animation.\n */\n set zoomStopsAnimation(flag) {\n this._zoomStopsAnimation = flag;\n }\n /**\n * Gets the flag that indicates if user zooming should stop animation.\n */\n get zoomStopsAnimation() {\n return this._zoomStopsAnimation;\n }\n /**\n * Sets the transition time when framing the mesh, in milliseconds\n */\n set framingTime(time) {\n this._framingTime = time;\n }\n /**\n * Gets the transition time when framing the mesh, in milliseconds\n */\n get framingTime() {\n return this._framingTime;\n }\n /**\n * Initializes the behavior.\n */\n init() {\n // Do nothing\n }\n /**\n * Attaches the behavior to its arc rotate camera.\n * @param camera Defines the camera to attach the behavior to\n */\n attach(camera) {\n this._attachedCamera = camera;\n const scene = this._attachedCamera.getScene();\n FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);\n this._onPrePointerObservableObserver = scene.onPrePointerObservable.add((pointerInfoPre) => {\n if (pointerInfoPre.type === PointerEventTypes.POINTERDOWN) {\n this._isPointerDown = true;\n return;\n }\n if (pointerInfoPre.type === PointerEventTypes.POINTERUP) {\n this._isPointerDown = false;\n }\n });\n this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add((mesh) => {\n if (mesh) {\n this.zoomOnMesh(mesh, undefined, () => {\n this.onTargetFramingAnimationEndObservable.notifyObservers();\n });\n }\n });\n this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(() => {\n // Stop the animation if there is user interaction and the animation should stop for this interaction\n this._applyUserInteraction();\n // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it\n // back to the default position after a given timeout\n this._maintainCameraAboveGround();\n });\n }\n /**\n * Detaches the behavior from its current arc rotate camera.\n */\n detach() {\n if (!this._attachedCamera) {\n return;\n }\n const scene = this._attachedCamera.getScene();\n if (this._onPrePointerObservableObserver) {\n scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);\n }\n if (this._onAfterCheckInputsObserver) {\n this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);\n }\n if (this._onMeshTargetChangedObserver) {\n this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);\n }\n this._attachedCamera = null;\n }\n /**\n * Targets the given mesh and updates zoom level accordingly.\n * @param mesh The mesh to target.\n * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh\n * @param onAnimationEnd Callback triggered at the end of the framing animation\n */\n zoomOnMesh(mesh, focusOnOriginXZ = false, onAnimationEnd = null) {\n mesh.computeWorldMatrix(true);\n const boundingBox = mesh.getBoundingInfo().boundingBox;\n this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);\n }\n /**\n * Targets the given mesh with its children and updates zoom level accordingly.\n * @param mesh The mesh to target.\n * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh\n * @param onAnimationEnd Callback triggered at the end of the framing animation\n */\n zoomOnMeshHierarchy(mesh, focusOnOriginXZ = false, onAnimationEnd = null) {\n mesh.computeWorldMatrix(true);\n const boundingBox = mesh.getHierarchyBoundingVectors(true);\n this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);\n }\n /**\n * Targets the given meshes with their children and updates zoom level accordingly.\n * @param meshes The mesh to target.\n * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh\n * @param onAnimationEnd Callback triggered at the end of the framing animation\n */\n zoomOnMeshesHierarchy(meshes, focusOnOriginXZ = false, onAnimationEnd = null) {\n const min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n const max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);\n for (let i = 0; i < meshes.length; i++) {\n const boundingInfo = meshes[i].getHierarchyBoundingVectors(true);\n Vector3.CheckExtends(boundingInfo.min, min, max);\n Vector3.CheckExtends(boundingInfo.max, min, max);\n }\n this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);\n }\n /**\n * Targets the bounding box info defined by its extends and updates zoom level accordingly.\n * @param minimumWorld Determines the smaller position of the bounding box extend\n * @param maximumWorld Determines the bigger position of the bounding box extend\n * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh\n * @param onAnimationEnd Callback triggered at the end of the framing animation\n */\n zoomOnBoundingInfo(minimumWorld, maximumWorld, focusOnOriginXZ = false, onAnimationEnd = null) {\n let zoomTarget;\n if (!this._attachedCamera) {\n return;\n }\n // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY\n const bottom = minimumWorld.y;\n const top = maximumWorld.y;\n const zoomTargetY = bottom + (top - bottom) * this._positionScale;\n const radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);\n if (focusOnOriginXZ) {\n zoomTarget = new Vector3(0, zoomTargetY, 0);\n }\n else {\n const centerWorld = minimumWorld.add(radiusWorld);\n zoomTarget = new Vector3(centerWorld.x, zoomTargetY, centerWorld.z);\n }\n if (!this._vectorTransition) {\n this._vectorTransition = Animation.CreateAnimation(\"target\", Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);\n }\n this._betaIsAnimating = true;\n let animatable = Animation.TransitionTo(\"target\", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);\n if (animatable) {\n this._animatables.push(animatable);\n }\n // sets the radius and lower radius bounds\n // Small delta ensures camera is not always at lower zoom limit.\n let radius = 0;\n if (this._mode === FramingBehavior.FitFrustumSidesMode) {\n const position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);\n if (this.autoCorrectCameraLimitsAndSensibility) {\n this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;\n }\n radius = position;\n }\n else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {\n radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);\n if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {\n this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;\n }\n }\n // Set sensibilities\n if (this.autoCorrectCameraLimitsAndSensibility) {\n const extend = maximumWorld.subtract(minimumWorld).length();\n this._attachedCamera.panningSensibility = 5000 / extend;\n this._attachedCamera.wheelPrecision = 100 / radius;\n }\n // transition to new radius\n if (!this._radiusTransition) {\n this._radiusTransition = Animation.CreateAnimation(\"radius\", Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);\n }\n animatable = Animation.TransitionTo(\"radius\", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, () => {\n this.stopAllAnimations();\n if (onAnimationEnd) {\n onAnimationEnd();\n }\n if (this._attachedCamera && this._attachedCamera.useInputToRestoreState) {\n this._attachedCamera.storeState();\n }\n });\n if (animatable) {\n this._animatables.push(animatable);\n }\n }\n /**\n * Calculates the lowest radius for the camera based on the bounding box of the mesh.\n * @param minimumWorld\n * @param maximumWorld\n * @returns The minimum distance from the primary mesh's center point at which the camera must be kept in order\n *\t\t to fully enclose the mesh in the viewing frustum.\n */\n _calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld) {\n const size = maximumWorld.subtract(minimumWorld);\n const boxVectorGlobalDiagonal = size.length();\n const frustumSlope = this._getFrustumSlope();\n // Formula for setting distance\n // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)\n const radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;\n // Horizon distance\n const radius = radiusWithoutFraming * this._radiusScale;\n const distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));\n const distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));\n let distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);\n const camera = this._attachedCamera;\n if (!camera) {\n return 0;\n }\n if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {\n // Don't exceed the requested limit\n distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;\n }\n // Don't exceed the upper radius limit\n if (camera.upperRadiusLimit) {\n distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;\n }\n return distance;\n }\n /**\n * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera\n * is automatically returned to its default position (expected to be above ground plane).\n */\n _maintainCameraAboveGround() {\n if (this._elevationReturnTime < 0) {\n return;\n }\n const timeSinceInteraction = PrecisionDate.Now - this._lastInteractionTime;\n const defaultBeta = Math.PI * 0.5 - this._defaultElevation;\n const limitBeta = Math.PI * 0.5;\n // Bring the camera back up if below the ground plane\n if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {\n this._betaIsAnimating = true;\n //Transition to new position\n this.stopAllAnimations();\n if (!this._betaTransition) {\n this._betaTransition = Animation.CreateAnimation(\"beta\", Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);\n }\n const animatabe = Animation.TransitionTo(\"beta\", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, () => {\n this._clearAnimationLocks();\n this.stopAllAnimations();\n });\n if (animatabe) {\n this._animatables.push(animatabe);\n }\n }\n }\n /**\n * Returns the frustum slope based on the canvas ratio and camera FOV\n * @returns The frustum slope represented as a Vector2 with X and Y slopes\n */\n _getFrustumSlope() {\n // Calculate the viewport ratio\n // Aspect Ratio is Height/Width.\n const camera = this._attachedCamera;\n if (!camera) {\n return Vector2.Zero();\n }\n const engine = camera.getScene().getEngine();\n const aspectRatio = engine.getAspectRatio(camera);\n // Camera FOV is the vertical field of view (top-bottom) in radians.\n // Slope of the frustum top/bottom planes in view space, relative to the forward vector.\n const frustumSlopeY = Math.tan(camera.fov / 2);\n // Slope of the frustum left/right planes in view space, relative to the forward vector.\n // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit\n // along the forward vector.\n const frustumSlopeX = frustumSlopeY * aspectRatio;\n return new Vector2(frustumSlopeX, frustumSlopeY);\n }\n /**\n * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.\n */\n _clearAnimationLocks() {\n this._betaIsAnimating = false;\n }\n /**\n * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.\n */\n _applyUserInteraction() {\n if (this.isUserIsMoving) {\n this._lastInteractionTime = PrecisionDate.Now;\n this.stopAllAnimations();\n this._clearAnimationLocks();\n }\n }\n /**\n * Stops and removes all animations that have been applied to the camera\n */\n stopAllAnimations() {\n if (this._attachedCamera) {\n this._attachedCamera.animations = [];\n }\n while (this._animatables.length) {\n if (this._animatables[0]) {\n this._animatables[0].onAnimationEnd = null;\n this._animatables[0].stop();\n }\n this._animatables.shift();\n }\n }\n /**\n * Gets a value indicating if the user is moving the camera\n */\n get isUserIsMoving() {\n if (!this._attachedCamera) {\n return false;\n }\n return (this._attachedCamera.inertialAlphaOffset !== 0 ||\n this._attachedCamera.inertialBetaOffset !== 0 ||\n this._attachedCamera.inertialRadiusOffset !== 0 ||\n this._attachedCamera.inertialPanningX !== 0 ||\n this._attachedCamera.inertialPanningY !== 0 ||\n this._isPointerDown);\n }\n}\n/**\n * The easing function used by animations\n */\nFramingBehavior.EasingFunction = new ExponentialEase();\n/**\n * The easing mode used by animations\n */\nFramingBehavior.EasingMode = EasingFunction.EASINGMODE_EASEINOUT;\n// Statics\n/**\n * The camera can move all the way towards the mesh.\n */\nFramingBehavior.IgnoreBoundsSizeMode = 0;\n/**\n * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides\n */\nFramingBehavior.FitFrustumSidesMode = 1;\n//# sourceMappingURL=framingBehavior.js.map","import { ArrayTools } from \"../Misc/arrayTools.js\";\nimport { Matrix, Vector3, TmpVectors } from \"../Maths/math.vector.js\";\nimport { PickingInfo } from \"../Collisions/pickingInfo.js\";\nimport { IntersectionInfo } from \"../Collisions/intersectionInfo.js\";\nimport { Scene } from \"../scene.js\";\nimport { Camera } from \"../Cameras/camera.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n/**\n * Class representing a ray with position and direction\n */\nexport class Ray {\n /**\n * Creates a new ray\n * @param origin origin point\n * @param direction direction\n * @param length length of the ray\n */\n constructor(\n /** origin point */\n origin, \n /** direction */\n direction, \n /** length of the ray */\n length = Number.MAX_VALUE) {\n this.origin = origin;\n this.direction = direction;\n this.length = length;\n }\n // Methods\n /**\n * Clone the current ray\n * @returns a new ray\n */\n clone() {\n return new Ray(this.origin.clone(), this.direction.clone(), this.length);\n }\n /**\n * Checks if the ray intersects a box\n * This does not account for the ray length by design to improve perfs.\n * @param minimum bound of the box\n * @param maximum bound of the box\n * @param intersectionTreshold extra extend to be added to the box in all direction\n * @returns if the box was hit\n */\n intersectsBoxMinMax(minimum, maximum, intersectionTreshold = 0) {\n const newMinimum = Ray._TmpVector3[0].copyFromFloats(minimum.x - intersectionTreshold, minimum.y - intersectionTreshold, minimum.z - intersectionTreshold);\n const newMaximum = Ray._TmpVector3[1].copyFromFloats(maximum.x + intersectionTreshold, maximum.y + intersectionTreshold, maximum.z + intersectionTreshold);\n let d = 0.0;\n let maxValue = Number.MAX_VALUE;\n let inv;\n let min;\n let max;\n let temp;\n if (Math.abs(this.direction.x) < 0.0000001) {\n if (this.origin.x < newMinimum.x || this.origin.x > newMaximum.x) {\n return false;\n }\n }\n else {\n inv = 1.0 / this.direction.x;\n min = (newMinimum.x - this.origin.x) * inv;\n max = (newMaximum.x - this.origin.x) * inv;\n if (max === -Infinity) {\n max = Infinity;\n }\n if (min > max) {\n temp = min;\n min = max;\n max = temp;\n }\n d = Math.max(min, d);\n maxValue = Math.min(max, maxValue);\n if (d > maxValue) {\n return false;\n }\n }\n if (Math.abs(this.direction.y) < 0.0000001) {\n if (this.origin.y < newMinimum.y || this.origin.y > newMaximum.y) {\n return false;\n }\n }\n else {\n inv = 1.0 / this.direction.y;\n min = (newMinimum.y - this.origin.y) * inv;\n max = (newMaximum.y - this.origin.y) * inv;\n if (max === -Infinity) {\n max = Infinity;\n }\n if (min > max) {\n temp = min;\n min = max;\n max = temp;\n }\n d = Math.max(min, d);\n maxValue = Math.min(max, maxValue);\n if (d > maxValue) {\n return false;\n }\n }\n if (Math.abs(this.direction.z) < 0.0000001) {\n if (this.origin.z < newMinimum.z || this.origin.z > newMaximum.z) {\n return false;\n }\n }\n else {\n inv = 1.0 / this.direction.z;\n min = (newMinimum.z - this.origin.z) * inv;\n max = (newMaximum.z - this.origin.z) * inv;\n if (max === -Infinity) {\n max = Infinity;\n }\n if (min > max) {\n temp = min;\n min = max;\n max = temp;\n }\n d = Math.max(min, d);\n maxValue = Math.min(max, maxValue);\n if (d > maxValue) {\n return false;\n }\n }\n return true;\n }\n /**\n * Checks if the ray intersects a box\n * This does not account for the ray lenght by design to improve perfs.\n * @param box the bounding box to check\n * @param intersectionTreshold extra extend to be added to the BoundingBox in all direction\n * @returns if the box was hit\n */\n intersectsBox(box, intersectionTreshold = 0) {\n return this.intersectsBoxMinMax(box.minimum, box.maximum, intersectionTreshold);\n }\n /**\n * If the ray hits a sphere\n * @param sphere the bounding sphere to check\n * @param intersectionTreshold extra extend to be added to the BoundingSphere in all direction\n * @returns true if it hits the sphere\n */\n intersectsSphere(sphere, intersectionTreshold = 0) {\n const x = sphere.center.x - this.origin.x;\n const y = sphere.center.y - this.origin.y;\n const z = sphere.center.z - this.origin.z;\n const pyth = x * x + y * y + z * z;\n const radius = sphere.radius + intersectionTreshold;\n const rr = radius * radius;\n if (pyth <= rr) {\n return true;\n }\n const dot = x * this.direction.x + y * this.direction.y + z * this.direction.z;\n if (dot < 0.0) {\n return false;\n }\n const temp = pyth - dot * dot;\n return temp <= rr;\n }\n /**\n * If the ray hits a triange\n * @param vertex0 triangle vertex\n * @param vertex1 triangle vertex\n * @param vertex2 triangle vertex\n * @returns intersection information if hit\n */\n intersectsTriangle(vertex0, vertex1, vertex2) {\n const edge1 = Ray._TmpVector3[0];\n const edge2 = Ray._TmpVector3[1];\n const pvec = Ray._TmpVector3[2];\n const tvec = Ray._TmpVector3[3];\n const qvec = Ray._TmpVector3[4];\n vertex1.subtractToRef(vertex0, edge1);\n vertex2.subtractToRef(vertex0, edge2);\n Vector3.CrossToRef(this.direction, edge2, pvec);\n const det = Vector3.Dot(edge1, pvec);\n if (det === 0) {\n return null;\n }\n const invdet = 1 / det;\n this.origin.subtractToRef(vertex0, tvec);\n const bv = Vector3.Dot(tvec, pvec) * invdet;\n if (bv < 0 || bv > 1.0) {\n return null;\n }\n Vector3.CrossToRef(tvec, edge1, qvec);\n const bw = Vector3.Dot(this.direction, qvec) * invdet;\n if (bw < 0 || bv + bw > 1.0) {\n return null;\n }\n //check if the distance is longer than the predefined length.\n const distance = Vector3.Dot(edge2, qvec) * invdet;\n if (distance > this.length) {\n return null;\n }\n return new IntersectionInfo(1 - bv - bw, bv, distance);\n }\n /**\n * Checks if ray intersects a plane\n * @param plane the plane to check\n * @returns the distance away it was hit\n */\n intersectsPlane(plane) {\n let distance;\n const result1 = Vector3.Dot(plane.normal, this.direction);\n if (Math.abs(result1) < 9.99999997475243e-7) {\n return null;\n }\n else {\n const result2 = Vector3.Dot(plane.normal, this.origin);\n distance = (-plane.d - result2) / result1;\n if (distance < 0.0) {\n if (distance < -9.99999997475243e-7) {\n return null;\n }\n else {\n return 0;\n }\n }\n return distance;\n }\n }\n /**\n * Calculate the intercept of a ray on a given axis\n * @param axis to check 'x' | 'y' | 'z'\n * @param offset from axis interception (i.e. an offset of 1y is intercepted above ground)\n * @returns a vector containing the coordinates where 'axis' is equal to zero (else offset), or null if there is no intercept.\n */\n intersectsAxis(axis, offset = 0) {\n switch (axis) {\n case \"y\": {\n const t = (this.origin.y - offset) / this.direction.y;\n if (t > 0) {\n return null;\n }\n return new Vector3(this.origin.x + this.direction.x * -t, offset, this.origin.z + this.direction.z * -t);\n }\n case \"x\": {\n const t = (this.origin.x - offset) / this.direction.x;\n if (t > 0) {\n return null;\n }\n return new Vector3(offset, this.origin.y + this.direction.y * -t, this.origin.z + this.direction.z * -t);\n }\n case \"z\": {\n const t = (this.origin.z - offset) / this.direction.z;\n if (t > 0) {\n return null;\n }\n return new Vector3(this.origin.x + this.direction.x * -t, this.origin.y + this.direction.y * -t, offset);\n }\n default:\n return null;\n }\n }\n /**\n * Checks if ray intersects a mesh. The ray is defined in WORLD space. A mesh triangle can be picked both from its front and back sides,\n * irrespective of orientation.\n * @param mesh the mesh to check\n * @param fastCheck defines if the first intersection will be used (and not the closest)\n * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected\n * @param onlyBoundingInfo defines a boolean indicating if picking should only happen using bounding info (false by default)\n * @param worldToUse defines the world matrix to use to get the world coordinate of the intersection point\n * @param skipBoundingInfo a boolean indicating if we should skip the bounding info check\n * @returns picking info of the intersection\n */\n intersectsMesh(mesh, fastCheck, trianglePredicate, onlyBoundingInfo = false, worldToUse, skipBoundingInfo = false) {\n const tm = TmpVectors.Matrix[0];\n mesh.getWorldMatrix().invertToRef(tm);\n if (this._tmpRay) {\n Ray.TransformToRef(this, tm, this._tmpRay);\n }\n else {\n this._tmpRay = Ray.Transform(this, tm);\n }\n return mesh.intersects(this._tmpRay, fastCheck, trianglePredicate, onlyBoundingInfo, worldToUse, skipBoundingInfo);\n }\n /**\n * Checks if ray intersects a mesh\n * @param meshes the meshes to check\n * @param fastCheck defines if the first intersection will be used (and not the closest)\n * @param results array to store result in\n * @returns Array of picking infos\n */\n intersectsMeshes(meshes, fastCheck, results) {\n if (results) {\n results.length = 0;\n }\n else {\n results = [];\n }\n for (let i = 0; i < meshes.length; i++) {\n const pickInfo = this.intersectsMesh(meshes[i], fastCheck);\n if (pickInfo.hit) {\n results.push(pickInfo);\n }\n }\n results.sort(this._comparePickingInfo);\n return results;\n }\n _comparePickingInfo(pickingInfoA, pickingInfoB) {\n if (pickingInfoA.distance < pickingInfoB.distance) {\n return -1;\n }\n else if (pickingInfoA.distance > pickingInfoB.distance) {\n return 1;\n }\n else {\n return 0;\n }\n }\n /**\n * Intersection test between the ray and a given segment within a given tolerance (threshold)\n * @param sega the first point of the segment to test the intersection against\n * @param segb the second point of the segment to test the intersection against\n * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful\n * @returns the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection\n */\n intersectionSegment(sega, segb, threshold) {\n const o = this.origin;\n const u = TmpVectors.Vector3[0];\n const rsegb = TmpVectors.Vector3[1];\n const v = TmpVectors.Vector3[2];\n const w = TmpVectors.Vector3[3];\n segb.subtractToRef(sega, u);\n this.direction.scaleToRef(Ray._Rayl, v);\n o.addToRef(v, rsegb);\n sega.subtractToRef(o, w);\n const a = Vector3.Dot(u, u); // always >= 0\n const b = Vector3.Dot(u, v);\n const c = Vector3.Dot(v, v); // always >= 0\n const d = Vector3.Dot(u, w);\n const e = Vector3.Dot(v, w);\n const D = a * c - b * b; // always >= 0\n let sN, sD = D; // sc = sN / sD, default sD = D >= 0\n let tN, tD = D; // tc = tN / tD, default tD = D >= 0\n // compute the line parameters of the two closest points\n if (D < Ray._Smallnum) {\n // the lines are almost parallel\n sN = 0.0; // force using point P0 on segment S1\n sD = 1.0; // to prevent possible division by 0.0 later\n tN = e;\n tD = c;\n }\n else {\n // get the closest points on the infinite lines\n sN = b * e - c * d;\n tN = a * e - b * d;\n if (sN < 0.0) {\n // sc < 0 => the s=0 edge is visible\n sN = 0.0;\n tN = e;\n tD = c;\n }\n else if (sN > sD) {\n // sc > 1 => the s=1 edge is visible\n sN = sD;\n tN = e + b;\n tD = c;\n }\n }\n if (tN < 0.0) {\n // tc < 0 => the t=0 edge is visible\n tN = 0.0;\n // recompute sc for this edge\n if (-d < 0.0) {\n sN = 0.0;\n }\n else if (-d > a) {\n sN = sD;\n }\n else {\n sN = -d;\n sD = a;\n }\n }\n else if (tN > tD) {\n // tc > 1 => the t=1 edge is visible\n tN = tD;\n // recompute sc for this edge\n if (-d + b < 0.0) {\n sN = 0;\n }\n else if (-d + b > a) {\n sN = sD;\n }\n else {\n sN = -d + b;\n sD = a;\n }\n }\n // finally do the division to get sc and tc\n const sc = Math.abs(sN) < Ray._Smallnum ? 0.0 : sN / sD;\n const tc = Math.abs(tN) < Ray._Smallnum ? 0.0 : tN / tD;\n // get the difference of the two closest points\n const qtc = TmpVectors.Vector3[4];\n v.scaleToRef(tc, qtc);\n const qsc = TmpVectors.Vector3[5];\n u.scaleToRef(sc, qsc);\n qsc.addInPlace(w);\n const dP = TmpVectors.Vector3[6];\n qsc.subtractToRef(qtc, dP); // = S1(sc) - S2(tc)\n const isIntersected = tc > 0 && tc <= this.length && dP.lengthSquared() < threshold * threshold; // return intersection result\n if (isIntersected) {\n return qsc.length();\n }\n return -1;\n }\n /**\n * Update the ray from viewport position\n * @param x position\n * @param y y position\n * @param viewportWidth viewport width\n * @param viewportHeight viewport height\n * @param world world matrix\n * @param view view matrix\n * @param projection projection matrix\n * @param enableDistantPicking defines if picking should handle large values for mesh position/scaling (false by default)\n * @returns this ray updated\n */\n update(x, y, viewportWidth, viewportHeight, world, view, projection, enableDistantPicking = false) {\n if (enableDistantPicking) {\n // With world matrices having great values (like 8000000000 on 1 or more scaling or position axis),\n // multiplying view/projection/world and doing invert will result in loss of float precision in the matrix.\n // One way to fix it is to compute the ray with world at identity then transform the ray in object space.\n // This is slower (2 matrix inverts instead of 1) but precision is preserved.\n // This is hidden behind `EnableDistantPicking` flag (default is false)\n if (!Ray._RayDistant) {\n Ray._RayDistant = Ray.Zero();\n }\n Ray._RayDistant.unprojectRayToRef(x, y, viewportWidth, viewportHeight, Matrix.IdentityReadOnly, view, projection);\n const tm = TmpVectors.Matrix[0];\n world.invertToRef(tm);\n Ray.TransformToRef(Ray._RayDistant, tm, this);\n }\n else {\n this.unprojectRayToRef(x, y, viewportWidth, viewportHeight, world, view, projection);\n }\n return this;\n }\n // Statics\n /**\n * Creates a ray with origin and direction of 0,0,0\n * @returns the new ray\n */\n static Zero() {\n return new Ray(Vector3.Zero(), Vector3.Zero());\n }\n /**\n * Creates a new ray from screen space and viewport\n * @param x position\n * @param y y position\n * @param viewportWidth viewport width\n * @param viewportHeight viewport height\n * @param world world matrix\n * @param view view matrix\n * @param projection projection matrix\n * @returns new ray\n */\n static CreateNew(x, y, viewportWidth, viewportHeight, world, view, projection) {\n const result = Ray.Zero();\n return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);\n }\n /**\n * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be\n * transformed to the given world matrix.\n * @param origin The origin point\n * @param end The end point\n * @param world a matrix to transform the ray to. Default is the identity matrix.\n * @returns the new ray\n */\n static CreateNewFromTo(origin, end, world = Matrix.IdentityReadOnly) {\n const direction = end.subtract(origin);\n const length = Math.sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z);\n direction.normalize();\n return Ray.Transform(new Ray(origin, direction, length), world);\n }\n /**\n * Transforms a ray by a matrix\n * @param ray ray to transform\n * @param matrix matrix to apply\n * @returns the resulting new ray\n */\n static Transform(ray, matrix) {\n const result = new Ray(new Vector3(0, 0, 0), new Vector3(0, 0, 0));\n Ray.TransformToRef(ray, matrix, result);\n return result;\n }\n /**\n * Transforms a ray by a matrix\n * @param ray ray to transform\n * @param matrix matrix to apply\n * @param result ray to store result in\n */\n static TransformToRef(ray, matrix, result) {\n Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);\n Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);\n result.length = ray.length;\n const dir = result.direction;\n const len = dir.length();\n if (!(len === 0 || len === 1)) {\n const num = 1.0 / len;\n dir.x *= num;\n dir.y *= num;\n dir.z *= num;\n result.length *= len;\n }\n }\n /**\n * Unproject a ray from screen space to object space\n * @param sourceX defines the screen space x coordinate to use\n * @param sourceY defines the screen space y coordinate to use\n * @param viewportWidth defines the current width of the viewport\n * @param viewportHeight defines the current height of the viewport\n * @param world defines the world matrix to use (can be set to Identity to go to world space)\n * @param view defines the view matrix to use\n * @param projection defines the projection matrix to use\n */\n unprojectRayToRef(sourceX, sourceY, viewportWidth, viewportHeight, world, view, projection) {\n var _a;\n const matrix = TmpVectors.Matrix[0];\n world.multiplyToRef(view, matrix);\n matrix.multiplyToRef(projection, matrix);\n matrix.invert();\n const nearScreenSource = TmpVectors.Vector3[0];\n nearScreenSource.x = (sourceX / viewportWidth) * 2 - 1;\n nearScreenSource.y = -((sourceY / viewportHeight) * 2 - 1);\n nearScreenSource.z = ((_a = EngineStore.LastCreatedEngine) === null || _a === void 0 ? void 0 : _a.isNDCHalfZRange) ? 0 : -1;\n // far Z need to be close but < to 1 or camera projection matrix with maxZ = 0 will NaN\n const farScreenSource = TmpVectors.Vector3[1].copyFromFloats(nearScreenSource.x, nearScreenSource.y, 1.0 - 1e-8);\n const nearVec3 = TmpVectors.Vector3[2];\n const farVec3 = TmpVectors.Vector3[3];\n Vector3._UnprojectFromInvertedMatrixToRef(nearScreenSource, matrix, nearVec3);\n Vector3._UnprojectFromInvertedMatrixToRef(farScreenSource, matrix, farVec3);\n this.origin.copyFrom(nearVec3);\n farVec3.subtractToRef(nearVec3, this.direction);\n this.direction.normalize();\n }\n}\nRay._TmpVector3 = ArrayTools.BuildArray(6, Vector3.Zero);\nRay._RayDistant = Ray.Zero();\nRay._Smallnum = 0.00000001;\nRay._Rayl = 10e8;\nScene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace = false) {\n const result = Ray.Zero();\n this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);\n return result;\n};\nScene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace = false, enableDistantPicking = false) {\n const engine = this.getEngine();\n if (!camera) {\n if (!this.activeCamera) {\n return this;\n }\n camera = this.activeCamera;\n }\n const cameraViewport = camera.viewport;\n const viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());\n // Moving coordinates to local viewport world\n x = x / engine.getHardwareScalingLevel() - viewport.x;\n y = y / engine.getHardwareScalingLevel() - (engine.getRenderHeight() - viewport.y - viewport.height);\n result.update(x, y, viewport.width, viewport.height, world ? world : Matrix.IdentityReadOnly, cameraViewSpace ? Matrix.IdentityReadOnly : camera.getViewMatrix(), camera.getProjectionMatrix(), enableDistantPicking);\n return this;\n};\nScene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {\n const result = Ray.Zero();\n this.createPickingRayInCameraSpaceToRef(x, y, result, camera);\n return result;\n};\nScene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {\n if (!PickingInfo) {\n return this;\n }\n const engine = this.getEngine();\n if (!camera) {\n if (!this.activeCamera) {\n throw new Error(\"Active camera not set\");\n }\n camera = this.activeCamera;\n }\n const cameraViewport = camera.viewport;\n const viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());\n const identity = Matrix.Identity();\n // Moving coordinates to local viewport world\n x = x / engine.getHardwareScalingLevel() - viewport.x;\n y = y / engine.getHardwareScalingLevel() - (engine.getRenderHeight() - viewport.y - viewport.height);\n result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());\n return this;\n};\nScene.prototype._internalPickForMesh = function (pickingInfo, rayFunction, mesh, world, fastCheck, onlyBoundingInfo, trianglePredicate, skipBoundingInfo) {\n const ray = rayFunction(world, mesh.enableDistantPicking);\n const result = mesh.intersects(ray, fastCheck, trianglePredicate, onlyBoundingInfo, world, skipBoundingInfo);\n if (!result || !result.hit) {\n return null;\n }\n if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {\n return null;\n }\n return result;\n};\nScene.prototype._internalPick = function (rayFunction, predicate, fastCheck, onlyBoundingInfo, trianglePredicate) {\n let pickingInfo = null;\n const computeWorldMatrixForCamera = !!(this.activeCameras && this.activeCameras.length > 1 && this.cameraToUseForPointers !== this.activeCamera);\n const currentCamera = this.cameraToUseForPointers || this.activeCamera;\n for (let meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {\n const mesh = this.meshes[meshIndex];\n if (predicate) {\n if (!predicate(mesh)) {\n continue;\n }\n }\n else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {\n continue;\n }\n const forceCompute = computeWorldMatrixForCamera && mesh.isWorldMatrixCameraDependent();\n const world = mesh.computeWorldMatrix(forceCompute, currentCamera);\n if (mesh.hasThinInstances && mesh.thinInstanceEnablePicking) {\n // first check if the ray intersects the whole bounding box/sphere of the mesh\n const result = this._internalPickForMesh(pickingInfo, rayFunction, mesh, world, true, true, trianglePredicate);\n if (result) {\n if (onlyBoundingInfo) {\n // the user only asked for a bounding info check so we can return\n return result;\n }\n const tmpMatrix = TmpVectors.Matrix[1];\n const thinMatrices = mesh.thinInstanceGetWorldMatrices();\n for (let index = 0; index < thinMatrices.length; index++) {\n const thinMatrix = thinMatrices[index];\n thinMatrix.multiplyToRef(world, tmpMatrix);\n const result = this._internalPickForMesh(pickingInfo, rayFunction, mesh, tmpMatrix, fastCheck, onlyBoundingInfo, trianglePredicate, true);\n if (result) {\n pickingInfo = result;\n pickingInfo.thinInstanceIndex = index;\n if (fastCheck) {\n return pickingInfo;\n }\n }\n }\n }\n }\n else {\n const result = this._internalPickForMesh(pickingInfo, rayFunction, mesh, world, fastCheck, onlyBoundingInfo, trianglePredicate);\n if (result) {\n pickingInfo = result;\n if (fastCheck) {\n return pickingInfo;\n }\n }\n }\n }\n return pickingInfo || new PickingInfo();\n};\nScene.prototype._internalMultiPick = function (rayFunction, predicate, trianglePredicate) {\n if (!PickingInfo) {\n return null;\n }\n const pickingInfos = new Array();\n const computeWorldMatrixForCamera = !!(this.activeCameras && this.activeCameras.length > 1 && this.cameraToUseForPointers !== this.activeCamera);\n const currentCamera = this.cameraToUseForPointers || this.activeCamera;\n for (let meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {\n const mesh = this.meshes[meshIndex];\n if (predicate) {\n if (!predicate(mesh)) {\n continue;\n }\n }\n else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {\n continue;\n }\n const forceCompute = computeWorldMatrixForCamera && mesh.isWorldMatrixCameraDependent();\n const world = mesh.computeWorldMatrix(forceCompute, currentCamera);\n if (mesh.hasThinInstances && mesh.thinInstanceEnablePicking) {\n const result = this._internalPickForMesh(null, rayFunction, mesh, world, true, true, trianglePredicate);\n if (result) {\n const tmpMatrix = TmpVectors.Matrix[1];\n const thinMatrices = mesh.thinInstanceGetWorldMatrices();\n for (let index = 0; index < thinMatrices.length; index++) {\n const thinMatrix = thinMatrices[index];\n thinMatrix.multiplyToRef(world, tmpMatrix);\n const result = this._internalPickForMesh(null, rayFunction, mesh, tmpMatrix, false, false, trianglePredicate, true);\n if (result) {\n result.thinInstanceIndex = index;\n pickingInfos.push(result);\n }\n }\n }\n }\n else {\n const result = this._internalPickForMesh(null, rayFunction, mesh, world, false, false, trianglePredicate);\n if (result) {\n pickingInfos.push(result);\n }\n }\n }\n return pickingInfos;\n};\nScene.prototype.pickWithBoundingInfo = function (x, y, predicate, fastCheck, camera) {\n if (!PickingInfo) {\n return null;\n }\n const result = this._internalPick((world) => {\n if (!this._tempPickingRay) {\n this._tempPickingRay = Ray.Zero();\n }\n this.createPickingRayToRef(x, y, world, this._tempPickingRay, camera || null);\n return this._tempPickingRay;\n }, predicate, fastCheck, true);\n if (result) {\n result.ray = this.createPickingRay(x, y, Matrix.Identity(), camera || null);\n }\n return result;\n};\nObject.defineProperty(Scene.prototype, \"_pickingAvailable\", {\n get: () => true,\n enumerable: false,\n configurable: false,\n});\nScene.prototype.pick = function (x, y, predicate, fastCheck, camera, trianglePredicate, _enableDistantPicking = false) {\n const result = this._internalPick((world, enableDistantPicking) => {\n if (!this._tempPickingRay) {\n this._tempPickingRay = Ray.Zero();\n }\n this.createPickingRayToRef(x, y, world, this._tempPickingRay, camera || null, false, enableDistantPicking);\n return this._tempPickingRay;\n }, predicate, fastCheck, false, trianglePredicate);\n if (result) {\n result.ray = this.createPickingRay(x, y, Matrix.Identity(), camera || null);\n }\n return result;\n};\nScene.prototype.pickWithRay = function (ray, predicate, fastCheck, trianglePredicate) {\n const result = this._internalPick((world) => {\n if (!this._pickWithRayInverseMatrix) {\n this._pickWithRayInverseMatrix = Matrix.Identity();\n }\n world.invertToRef(this._pickWithRayInverseMatrix);\n if (!this._cachedRayForTransform) {\n this._cachedRayForTransform = Ray.Zero();\n }\n Ray.TransformToRef(ray, this._pickWithRayInverseMatrix, this._cachedRayForTransform);\n return this._cachedRayForTransform;\n }, predicate, fastCheck, false, trianglePredicate);\n if (result) {\n result.ray = ray;\n }\n return result;\n};\nScene.prototype.multiPick = function (x, y, predicate, camera, trianglePredicate) {\n return this._internalMultiPick((world) => this.createPickingRay(x, y, world, camera || null), predicate, trianglePredicate);\n};\nScene.prototype.multiPickWithRay = function (ray, predicate, trianglePredicate) {\n return this._internalMultiPick((world) => {\n if (!this._pickWithRayInverseMatrix) {\n this._pickWithRayInverseMatrix = Matrix.Identity();\n }\n world.invertToRef(this._pickWithRayInverseMatrix);\n if (!this._cachedRayForTransform) {\n this._cachedRayForTransform = Ray.Zero();\n }\n Ray.TransformToRef(ray, this._pickWithRayInverseMatrix, this._cachedRayForTransform);\n return this._cachedRayForTransform;\n }, predicate, trianglePredicate);\n};\nCamera.prototype.getForwardRay = function (length = 100, transform, origin) {\n return this.getForwardRayToRef(new Ray(Vector3.Zero(), Vector3.Zero(), length), length, transform, origin);\n};\nCamera.prototype.getForwardRayToRef = function (refRay, length = 100, transform, origin) {\n if (!transform) {\n transform = this.getWorldMatrix();\n }\n refRay.length = length;\n if (!origin) {\n refRay.origin.copyFrom(this.position);\n }\n else {\n refRay.origin.copyFrom(origin);\n }\n TmpVectors.Vector3[2].set(0, 0, this._scene.useRightHandedSystem ? -1 : 1);\n Vector3.TransformNormalToRef(TmpVectors.Vector3[2], transform, TmpVectors.Vector3[3]);\n Vector3.NormalizeToRef(TmpVectors.Vector3[3], refRay.direction);\n return refRay;\n};\n//# sourceMappingURL=ray.js.map","import { Vector3, Matrix } from \"../Maths/math.vector.js\";\n/**\n * Class containing a set of static utilities functions for managing Pivots\n * @internal\n */\nexport class PivotTools {\n /**\n * @internal\n */\n static _RemoveAndStorePivotPoint(mesh) {\n if (mesh && PivotTools._PivotCached === 0) {\n // Save old pivot and set pivot to 0,0,0\n mesh.getPivotPointToRef(PivotTools._OldPivotPoint);\n PivotTools._PivotPostMultiplyPivotMatrix = mesh._postMultiplyPivotMatrix;\n if (!PivotTools._OldPivotPoint.equalsToFloats(0, 0, 0)) {\n mesh.setPivotMatrix(Matrix.IdentityReadOnly);\n PivotTools._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), PivotTools._PivotTranslation);\n PivotTools._PivotTmpVector.copyFromFloats(1, 1, 1);\n PivotTools._PivotTmpVector.subtractInPlace(mesh.scaling);\n PivotTools._PivotTmpVector.multiplyInPlace(PivotTools._PivotTranslation);\n mesh.position.addInPlace(PivotTools._PivotTmpVector);\n }\n }\n PivotTools._PivotCached++;\n }\n /**\n * @internal\n */\n static _RestorePivotPoint(mesh) {\n if (mesh && !PivotTools._OldPivotPoint.equalsToFloats(0, 0, 0) && PivotTools._PivotCached === 1) {\n mesh.setPivotPoint(PivotTools._OldPivotPoint);\n mesh._postMultiplyPivotMatrix = PivotTools._PivotPostMultiplyPivotMatrix;\n PivotTools._PivotTmpVector.copyFromFloats(1, 1, 1);\n PivotTools._PivotTmpVector.subtractInPlace(mesh.scaling);\n PivotTools._PivotTmpVector.multiplyInPlace(PivotTools._PivotTranslation);\n mesh.position.subtractInPlace(PivotTools._PivotTmpVector);\n }\n this._PivotCached--;\n }\n}\n// Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)\n// store/remove pivot point should only be applied during their outermost calls\nPivotTools._PivotCached = 0;\nPivotTools._OldPivotPoint = new Vector3();\nPivotTools._PivotTranslation = new Vector3();\nPivotTools._PivotTmpVector = new Vector3();\nPivotTools._PivotPostMultiplyPivotMatrix = false;\n//# sourceMappingURL=pivotTools.js.map","import { Mesh } from \"../mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n/**\n * Creates the VertexData for a Plane\n * @param options an object used to set the following optional parameters for the plane, required but can be empty\n * * size sets the width and height of the plane to the value of size, optional default 1\n * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size\n * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.size\n * @param options.width\n * @param options.height\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the box\n */\nexport function CreatePlaneVertexData(options) {\n const indices = [];\n const positions = [];\n const normals = [];\n const uvs = [];\n const width = options.width || options.size || 1;\n const height = options.height || options.size || 1;\n const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;\n // Vertices\n const halfWidth = width / 2.0;\n const halfHeight = height / 2.0;\n positions.push(-halfWidth, -halfHeight, 0);\n normals.push(0, 0, -1.0);\n uvs.push(0.0, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 : 0.0);\n positions.push(halfWidth, -halfHeight, 0);\n normals.push(0, 0, -1.0);\n uvs.push(1.0, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 : 0.0);\n positions.push(halfWidth, halfHeight, 0);\n normals.push(0, 0, -1.0);\n uvs.push(1.0, CompatibilityOptions.UseOpenGLOrientationForUV ? 0.0 : 1.0);\n positions.push(-halfWidth, halfHeight, 0);\n normals.push(0, 0, -1.0);\n uvs.push(0.0, CompatibilityOptions.UseOpenGLOrientationForUV ? 0.0 : 1.0);\n // Indices\n indices.push(0);\n indices.push(1);\n indices.push(2);\n indices.push(0);\n indices.push(2);\n indices.push(3);\n // Sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Result\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n}\n/**\n * Creates a plane mesh\n * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)\n * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)\n * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.size\n * @param options.width\n * @param options.height\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.updatable\n * @param options.sourcePlane\n * @param scene defines the hosting scene\n * @returns the plane mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#plane\n */\nexport function CreatePlane(name, options = {}, scene = null) {\n const plane = new Mesh(name, scene);\n options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n plane._originalBuilderSideOrientation = options.sideOrientation;\n const vertexData = CreatePlaneVertexData(options);\n vertexData.applyToMesh(plane, options.updatable);\n if (options.sourcePlane) {\n plane.translate(options.sourcePlane.normal, -options.sourcePlane.d);\n plane.setDirection(options.sourcePlane.normal.scale(-1));\n }\n return plane;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use the function directly from the module\n */\nexport const PlaneBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreatePlane,\n};\nVertexData.CreatePlane = CreatePlaneVertexData;\nMesh.CreatePlane = (name, size, scene, updatable, sideOrientation) => {\n const options = {\n size,\n width: size,\n height: size,\n sideOrientation,\n updatable,\n };\n return CreatePlane(name, options, scene);\n};\n//# sourceMappingURL=planeBuilder.js.map","import { Mesh } from \"../../Meshes/mesh.js\";\nimport { Scene } from \"../../scene.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { PointerEventTypes } from \"../../Events/pointerEvents.js\";\nimport { Ray } from \"../../Culling/ray.js\";\nimport { PivotTools } from \"../../Misc/pivotTools.js\";\nimport { CreatePlane } from \"../../Meshes/Builders/planeBuilder.js\";\n/**\n * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events\n */\nexport class PointerDragBehavior {\n /**\n * Get or set the currentDraggingPointerId\n * @deprecated Please use currentDraggingPointerId instead\n */\n get currentDraggingPointerID() {\n return this.currentDraggingPointerId;\n }\n set currentDraggingPointerID(currentDraggingPointerID) {\n this.currentDraggingPointerId = currentDraggingPointerID;\n }\n /**\n * If the drag behavior will react to drag events (Default: true)\n */\n set enabled(value) {\n if (value != this._enabled) {\n this.onEnabledObservable.notifyObservers(value);\n }\n this._enabled = value;\n }\n get enabled() {\n return this._enabled;\n }\n /**\n * Gets the options used by the behavior\n */\n get options() {\n return this._options;\n }\n /**\n * Sets the options used by the behavior\n */\n set options(options) {\n this._options = options;\n }\n /**\n * Creates a pointer drag behavior that can be attached to a mesh\n * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)\n * @param options.dragAxis\n * @param options.dragPlaneNormal\n */\n constructor(options) {\n this._useAlternatePickedPointAboveMaxDragAngleDragSpeed = -1.1;\n this._activeDragButton = -1;\n /**\n * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0)\n */\n this.maxDragAngle = 0;\n /**\n * Butttons that can be used to initiate a drag\n */\n this.dragButtons = [0, 1, 2];\n /**\n * @internal\n */\n this._useAlternatePickedPointAboveMaxDragAngle = false;\n /**\n * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)\n */\n this.currentDraggingPointerId = -1;\n /**\n * If the behavior is currently in a dragging state\n */\n this.dragging = false;\n /**\n * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)\n */\n this.dragDeltaRatio = 0.2;\n /**\n * If the drag plane orientation should be updated during the dragging (Default: true)\n */\n this.updateDragPlane = true;\n // Debug mode will display drag planes to help visualize behavior\n this._debugMode = false;\n this._moving = false;\n /**\n * Fires each time the attached mesh is dragged with the pointer\n * * delta between last drag position and current drag position in world space\n * * dragDistance along the drag axis\n * * dragPlaneNormal normal of the current drag plane used during the drag\n * * dragPlanePoint in world space where the drag intersects the drag plane\n *\n * (if validatedDrag is used, the position of the attached mesh might not equal dragPlanePoint)\n */\n this.onDragObservable = new Observable();\n /**\n * Fires each time a drag begins (eg. mouse down on mesh)\n * * dragPlanePoint in world space where the drag intersects the drag plane\n *\n * (if validatedDrag is used, the position of the attached mesh might not equal dragPlanePoint)\n */\n this.onDragStartObservable = new Observable();\n /**\n * Fires each time a drag ends (eg. mouse release after drag)\n * * dragPlanePoint in world space where the drag intersects the drag plane\n *\n * (if validatedDrag is used, the position of the attached mesh might not equal dragPlanePoint)\n */\n this.onDragEndObservable = new Observable();\n /**\n * Fires each time behavior enabled state changes\n */\n this.onEnabledObservable = new Observable();\n /**\n * If the attached mesh should be moved when dragged\n */\n this.moveAttached = true;\n this._enabled = true;\n /**\n * If pointer events should start and release the drag (Default: true)\n */\n this.startAndReleaseDragOnPointerEvents = true;\n /**\n * If camera controls should be detached during the drag\n */\n this.detachCameraControls = true;\n /**\n * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)\n */\n this.useObjectOrientationForDragging = true;\n /**\n * Predicate to determine if it is valid to move the object to a new position when it is moved\n * @param targetPosition\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this.validateDrag = (targetPosition) => {\n return true;\n };\n this._tmpVector = new Vector3(0, 0, 0);\n this._alternatePickedPoint = new Vector3(0, 0, 0);\n this._worldDragAxis = new Vector3(0, 0, 0);\n this._targetPosition = new Vector3(0, 0, 0);\n this._attachedToElement = false;\n this._startDragRay = new Ray(new Vector3(), new Vector3());\n this._lastPointerRay = {};\n this._dragDelta = new Vector3();\n // Variables to avoid instantiation in the below method\n this._pointA = new Vector3(0, 0, 0);\n this._pointC = new Vector3(0, 0, 0);\n this._localAxis = new Vector3(0, 0, 0);\n this._lookAt = new Vector3(0, 0, 0);\n this._options = options ? options : {};\n let optionCount = 0;\n if (this._options.dragAxis) {\n optionCount++;\n }\n if (this._options.dragPlaneNormal) {\n optionCount++;\n }\n if (optionCount > 1) {\n throw \"Multiple drag modes specified in dragBehavior options. Only one expected\";\n }\n }\n /**\n * The name of the behavior\n */\n get name() {\n return \"PointerDrag\";\n }\n /**\n * Initializes the behavior\n */\n init() { }\n /**\n * Attaches the drag behavior the passed in mesh\n * @param ownerNode The mesh that will be dragged around once attached\n * @param predicate Predicate to use for pick filtering\n */\n attach(ownerNode, predicate) {\n this._scene = ownerNode.getScene();\n ownerNode.isNearGrabbable = true;\n this.attachedNode = ownerNode;\n // Initialize drag plane to not interfere with existing scene\n if (!PointerDragBehavior._PlaneScene) {\n if (this._debugMode) {\n PointerDragBehavior._PlaneScene = this._scene;\n }\n else {\n PointerDragBehavior._PlaneScene = new Scene(this._scene.getEngine(), { virtual: true });\n PointerDragBehavior._PlaneScene.detachControl();\n this._scene.onDisposeObservable.addOnce(() => {\n PointerDragBehavior._PlaneScene.dispose();\n PointerDragBehavior._PlaneScene = null;\n });\n }\n }\n this._dragPlane = CreatePlane(\"pointerDragPlane\", { size: this._debugMode ? 1 : 10000, updatable: false, sideOrientation: Mesh.DOUBLESIDE }, PointerDragBehavior._PlaneScene);\n // State of the drag\n this.lastDragPosition = new Vector3(0, 0, 0);\n const pickPredicate = predicate\n ? predicate\n : (m) => {\n return this.attachedNode == m || m.isDescendantOf(this.attachedNode);\n };\n this._pointerObserver = this._scene.onPointerObservable.add((pointerInfo) => {\n if (!this.enabled) {\n // If behavior is disabled before releaseDrag is ever called, call it now.\n if (this._attachedToElement) {\n this.releaseDrag();\n }\n return;\n }\n if (pointerInfo.type == PointerEventTypes.POINTERDOWN) {\n if (this.startAndReleaseDragOnPointerEvents &&\n !this.dragging &&\n pointerInfo.pickInfo &&\n pointerInfo.pickInfo.hit &&\n pointerInfo.pickInfo.pickedMesh &&\n pointerInfo.pickInfo.pickedPoint &&\n pointerInfo.pickInfo.ray &&\n pickPredicate(pointerInfo.pickInfo.pickedMesh)) {\n if (this._activeDragButton === -1 && this.dragButtons.indexOf(pointerInfo.event.button) !== -1) {\n this._activeDragButton = pointerInfo.event.button;\n this._activePointerInfo = pointerInfo;\n this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);\n }\n }\n }\n else if (pointerInfo.type == PointerEventTypes.POINTERUP) {\n if (this.startAndReleaseDragOnPointerEvents &&\n this.currentDraggingPointerId == pointerInfo.event.pointerId &&\n (this._activeDragButton === pointerInfo.event.button || this._activeDragButton === -1)) {\n this.releaseDrag();\n }\n }\n else if (pointerInfo.type == PointerEventTypes.POINTERMOVE) {\n const pointerId = pointerInfo.event.pointerId;\n // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved\n if (this.currentDraggingPointerId === PointerDragBehavior._AnyMouseId && pointerId !== PointerDragBehavior._AnyMouseId) {\n const evt = pointerInfo.event;\n const isMouseEvent = evt.pointerType === \"mouse\" || (!this._scene.getEngine().hostInformation.isMobile && evt instanceof MouseEvent);\n if (isMouseEvent) {\n if (this._lastPointerRay[this.currentDraggingPointerId]) {\n this._lastPointerRay[pointerId] = this._lastPointerRay[this.currentDraggingPointerId];\n delete this._lastPointerRay[this.currentDraggingPointerId];\n }\n this.currentDraggingPointerId = pointerId;\n }\n }\n // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()\n if (!this._lastPointerRay[pointerId]) {\n this._lastPointerRay[pointerId] = new Ray(new Vector3(), new Vector3());\n }\n if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {\n this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);\n this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);\n if (this.currentDraggingPointerId == pointerId && this.dragging) {\n this._moveDrag(pointerInfo.pickInfo.ray);\n }\n }\n }\n });\n this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(() => {\n if (this._moving && this.moveAttached) {\n let needMatrixUpdate = false;\n PivotTools._RemoveAndStorePivotPoint(this.attachedNode);\n // Slowly move mesh to avoid jitter\n this._targetPosition.subtractToRef(this.attachedNode.absolutePosition, this._tmpVector);\n this._tmpVector.scaleInPlace(this.dragDeltaRatio);\n this.attachedNode.getAbsolutePosition().addToRef(this._tmpVector, this._tmpVector);\n if (this.validateDrag(this._tmpVector)) {\n this.attachedNode.setAbsolutePosition(this._tmpVector);\n needMatrixUpdate = true;\n }\n PivotTools._RestorePivotPoint(this.attachedNode);\n if (needMatrixUpdate) {\n this.attachedNode.computeWorldMatrix();\n }\n }\n });\n }\n /**\n * Force release the drag action by code.\n */\n releaseDrag() {\n if (this.dragging) {\n this.dragging = false;\n this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerId, pointerInfo: this._activePointerInfo });\n }\n this.currentDraggingPointerId = -1;\n this._activeDragButton = -1;\n this._activePointerInfo = null;\n this._moving = false;\n // Reattach camera controls\n if (this.detachCameraControls && this._attachedToElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {\n if (this._scene.activeCamera.getClassName() === \"ArcRotateCamera\") {\n const arcRotateCamera = this._scene.activeCamera;\n arcRotateCamera.attachControl(arcRotateCamera.inputs ? arcRotateCamera.inputs.noPreventDefault : true, arcRotateCamera._useCtrlForPanning, arcRotateCamera._panningMouseButton);\n }\n else {\n this._scene.activeCamera.attachControl(this._scene.activeCamera.inputs ? this._scene.activeCamera.inputs.noPreventDefault : true);\n }\n this._attachedToElement = false;\n }\n }\n /**\n * Simulates the start of a pointer drag event on the behavior\n * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)\n * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)\n * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)\n */\n startDrag(pointerId = PointerDragBehavior._AnyMouseId, fromRay, startPickedPoint) {\n this._startDrag(pointerId, fromRay, startPickedPoint);\n let lastRay = this._lastPointerRay[pointerId];\n if (pointerId === PointerDragBehavior._AnyMouseId) {\n lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];\n }\n if (lastRay) {\n // if there was a last pointer ray drag the object there\n this._moveDrag(lastRay);\n }\n }\n _startDrag(pointerId, fromRay, startPickedPoint) {\n if (!this._scene.activeCamera || this.dragging || !this.attachedNode) {\n return;\n }\n PivotTools._RemoveAndStorePivotPoint(this.attachedNode);\n // Create start ray from the camera to the object\n if (fromRay) {\n this._startDragRay.direction.copyFrom(fromRay.direction);\n this._startDragRay.origin.copyFrom(fromRay.origin);\n }\n else {\n this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);\n this.attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);\n this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);\n }\n this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);\n const pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);\n if (pickedPoint) {\n this.dragging = true;\n this.currentDraggingPointerId = pointerId;\n this.lastDragPosition.copyFrom(pickedPoint);\n this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerId, pointerInfo: this._activePointerInfo });\n this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition());\n // Detatch camera controls\n if (this.detachCameraControls && this._scene.activeCamera && this._scene.activeCamera.inputs && !this._scene.activeCamera.leftCamera) {\n if (this._scene.activeCamera.inputs.attachedToElement) {\n this._scene.activeCamera.detachControl();\n this._attachedToElement = true;\n }\n else {\n this._attachedToElement = false;\n }\n }\n }\n else {\n this.releaseDrag();\n }\n PivotTools._RestorePivotPoint(this.attachedNode);\n }\n _moveDrag(ray) {\n this._moving = true;\n const pickedPoint = this._pickWithRayOnDragPlane(ray);\n if (pickedPoint) {\n PivotTools._RemoveAndStorePivotPoint(this.attachedNode);\n if (this.updateDragPlane) {\n this._updateDragPlanePosition(ray, pickedPoint);\n }\n let dragLength = 0;\n // depending on the drag mode option drag accordingly\n if (this._options.dragAxis) {\n // Convert local drag axis to world if useObjectOrientationForDragging\n this.useObjectOrientationForDragging\n ? Vector3.TransformCoordinatesToRef(this._options.dragAxis, this.attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis)\n : this._worldDragAxis.copyFrom(this._options.dragAxis);\n // Project delta drag from the drag plane onto the drag axis\n pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);\n dragLength = Vector3.Dot(this._tmpVector, this._worldDragAxis);\n this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);\n }\n else {\n dragLength = this._dragDelta.length();\n pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);\n }\n this._targetPosition.addInPlace(this._dragDelta);\n this.onDragObservable.notifyObservers({\n dragDistance: dragLength,\n delta: this._dragDelta,\n dragPlanePoint: pickedPoint,\n dragPlaneNormal: this._dragPlane.forward,\n pointerId: this.currentDraggingPointerId,\n pointerInfo: this._activePointerInfo,\n });\n this.lastDragPosition.copyFrom(pickedPoint);\n PivotTools._RestorePivotPoint(this.attachedNode);\n }\n }\n _pickWithRayOnDragPlane(ray) {\n if (!ray) {\n return null;\n }\n // Calculate angle between plane normal and ray\n let angle = Math.acos(Vector3.Dot(this._dragPlane.forward, ray.direction));\n // Correct if ray is casted from oposite side\n if (angle > Math.PI / 2) {\n angle = Math.PI - angle;\n }\n // If the angle is too perpendicular to the plane pick another point on the plane where it is looking\n if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {\n if (this._useAlternatePickedPointAboveMaxDragAngle) {\n // Invert ray direction along the towards object axis\n this._tmpVector.copyFrom(ray.direction);\n this.attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);\n this._alternatePickedPoint.normalize();\n this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed * Vector3.Dot(this._alternatePickedPoint, this._tmpVector));\n this._tmpVector.addInPlace(this._alternatePickedPoint);\n // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point\n const dot = Vector3.Dot(this._dragPlane.forward, this._tmpVector);\n this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);\n this._alternatePickedPoint.addInPlace(this._tmpVector);\n this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition);\n return this._alternatePickedPoint;\n }\n else {\n return null;\n }\n }\n const pickResult = PointerDragBehavior._PlaneScene.pickWithRay(ray, (m) => {\n return m == this._dragPlane;\n });\n if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {\n return pickResult.pickedPoint;\n }\n else {\n return null;\n }\n }\n // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera\n _updateDragPlanePosition(ray, dragPlanePosition) {\n this._pointA.copyFrom(dragPlanePosition);\n if (this._options.dragAxis) {\n this.useObjectOrientationForDragging\n ? Vector3.TransformCoordinatesToRef(this._options.dragAxis, this.attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis)\n : this._localAxis.copyFrom(this._options.dragAxis);\n // Calculate plane normal that is the cross product of local axis and (eye-dragPlanePosition)\n ray.origin.subtractToRef(this._pointA, this._pointC);\n this._pointC.normalize();\n if (Math.abs(Vector3.Dot(this._localAxis, this._pointC)) > 0.999) {\n // the drag axis is colinear with the (eye to position) ray. The cross product will give jittered values.\n // A new axis vector need to be computed\n if (Math.abs(Vector3.Dot(Vector3.UpReadOnly, this._pointC)) > 0.999) {\n this._lookAt.copyFrom(Vector3.Right());\n }\n else {\n this._lookAt.copyFrom(Vector3.UpReadOnly);\n }\n }\n else {\n Vector3.CrossToRef(this._localAxis, this._pointC, this._lookAt);\n // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendicular to camera\n Vector3.CrossToRef(this._localAxis, this._lookAt, this._lookAt);\n this._lookAt.normalize();\n }\n this._dragPlane.position.copyFrom(this._pointA);\n this._pointA.addToRef(this._lookAt, this._lookAt);\n this._dragPlane.lookAt(this._lookAt);\n }\n else if (this._options.dragPlaneNormal) {\n this.useObjectOrientationForDragging\n ? Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this.attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis)\n : this._localAxis.copyFrom(this._options.dragPlaneNormal);\n this._dragPlane.position.copyFrom(this._pointA);\n this._pointA.addToRef(this._localAxis, this._lookAt);\n this._dragPlane.lookAt(this._lookAt);\n }\n else {\n this._dragPlane.position.copyFrom(this._pointA);\n this._dragPlane.lookAt(ray.origin);\n }\n // Update the position of the drag plane so it doesn't get out of sync with the node (eg. when moving back and forth quickly)\n this._dragPlane.position.copyFrom(this.attachedNode.getAbsolutePosition());\n this._dragPlane.computeWorldMatrix(true);\n }\n /**\n * Detaches the behavior from the mesh\n */\n detach() {\n this._lastPointerRay = {};\n if (this.attachedNode) {\n this.attachedNode.isNearGrabbable = false;\n }\n if (this._pointerObserver) {\n this._scene.onPointerObservable.remove(this._pointerObserver);\n }\n if (this._beforeRenderObserver) {\n this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);\n }\n if (this._dragPlane) {\n this._dragPlane.dispose();\n }\n this.releaseDrag();\n }\n}\nPointerDragBehavior._AnyMouseId = -2;\n//# sourceMappingURL=pointerDragBehavior.js.map","import { Tools } from \"../Misc/tools.js\";\n/**\n * A list of the currently available features without referencing them\n */\nexport class WebXRFeatureName {\n}\n/**\n * The name of the anchor system feature\n */\nWebXRFeatureName.ANCHOR_SYSTEM = \"xr-anchor-system\";\n/**\n * The name of the background remover feature\n */\nWebXRFeatureName.BACKGROUND_REMOVER = \"xr-background-remover\";\n/**\n * The name of the hit test feature\n */\nWebXRFeatureName.HIT_TEST = \"xr-hit-test\";\n/**\n * The name of the mesh detection feature\n */\nWebXRFeatureName.MESH_DETECTION = \"xr-mesh-detection\";\n/**\n * physics impostors for xr controllers feature\n */\nWebXRFeatureName.PHYSICS_CONTROLLERS = \"xr-physics-controller\";\n/**\n * The name of the plane detection feature\n */\nWebXRFeatureName.PLANE_DETECTION = \"xr-plane-detection\";\n/**\n * The name of the pointer selection feature\n */\nWebXRFeatureName.POINTER_SELECTION = \"xr-controller-pointer-selection\";\n/**\n * The name of the teleportation feature\n */\nWebXRFeatureName.TELEPORTATION = \"xr-controller-teleportation\";\n/**\n * The name of the feature points feature.\n */\nWebXRFeatureName.FEATURE_POINTS = \"xr-feature-points\";\n/**\n * The name of the hand tracking feature.\n */\nWebXRFeatureName.HAND_TRACKING = \"xr-hand-tracking\";\n/**\n * The name of the image tracking feature\n */\nWebXRFeatureName.IMAGE_TRACKING = \"xr-image-tracking\";\n/**\n * The name of the near interaction feature\n */\nWebXRFeatureName.NEAR_INTERACTION = \"xr-near-interaction\";\n/**\n * The name of the DOM overlay feature\n */\nWebXRFeatureName.DOM_OVERLAY = \"xr-dom-overlay\";\n/**\n * The name of the movement feature\n */\nWebXRFeatureName.MOVEMENT = \"xr-controller-movement\";\n/**\n * The name of the light estimation feature\n */\nWebXRFeatureName.LIGHT_ESTIMATION = \"xr-light-estimation\";\n/**\n * The name of the eye tracking feature\n */\nWebXRFeatureName.EYE_TRACKING = \"xr-eye-tracking\";\n/**\n * The name of the walking locomotion feature\n */\nWebXRFeatureName.WALKING_LOCOMOTION = \"xr-walking-locomotion\";\n/**\n * The name of the composition layers feature\n */\nWebXRFeatureName.LAYERS = \"xr-layers\";\n/**\n * The name of the depth sensing feature\n */\nWebXRFeatureName.DEPTH_SENSING = \"xr-depth-sensing\";\n/**\n * The name of the WebXR Space Warp feature\n */\nWebXRFeatureName.SPACE_WARP = \"xr-space-warp\";\n/**\n * The WebXR features manager is responsible of enabling or disabling features required for the current XR session.\n * It is mainly used in AR sessions.\n *\n * A feature can have a version that is defined by Babylon (and does not correspond with the webxr version).\n */\nexport class WebXRFeaturesManager {\n /**\n * constructs a new features manages.\n *\n * @param _xrSessionManager an instance of WebXRSessionManager\n */\n constructor(_xrSessionManager) {\n this._xrSessionManager = _xrSessionManager;\n this._features = {};\n // when session starts / initialized - attach\n this._xrSessionManager.onXRSessionInit.add(() => {\n this.getEnabledFeatures().forEach((featureName) => {\n const feature = this._features[featureName];\n if (feature.enabled && !feature.featureImplementation.attached && !feature.featureImplementation.disableAutoAttach) {\n this.attachFeature(featureName);\n }\n });\n });\n // when session ends - detach\n this._xrSessionManager.onXRSessionEnded.add(() => {\n this.getEnabledFeatures().forEach((featureName) => {\n const feature = this._features[featureName];\n if (feature.enabled && feature.featureImplementation.attached) {\n // detach, but don't disable!\n this.detachFeature(featureName);\n }\n });\n });\n }\n /**\n * Used to register a module. After calling this function a developer can use this feature in the scene.\n * Mainly used internally.\n *\n * @param featureName the name of the feature to register\n * @param constructorFunction the function used to construct the module\n * @param version the (babylon) version of the module\n * @param stable is that a stable version of this module\n */\n static AddWebXRFeature(featureName, constructorFunction, version = 1, stable = false) {\n this._AvailableFeatures[featureName] = this._AvailableFeatures[featureName] || { latest: version };\n if (version > this._AvailableFeatures[featureName].latest) {\n this._AvailableFeatures[featureName].latest = version;\n }\n if (stable) {\n this._AvailableFeatures[featureName].stable = version;\n }\n this._AvailableFeatures[featureName][version] = constructorFunction;\n }\n /**\n * Returns a constructor of a specific feature.\n *\n * @param featureName the name of the feature to construct\n * @param version the version of the feature to load\n * @param xrSessionManager the xrSessionManager. Used to construct the module\n * @param options optional options provided to the module.\n * @returns a function that, when called, will return a new instance of this feature\n */\n static ConstructFeature(featureName, version = 1, xrSessionManager, options) {\n const constructorFunction = this._AvailableFeatures[featureName][version];\n if (!constructorFunction) {\n // throw an error? return nothing?\n throw new Error(\"feature not found\");\n }\n return constructorFunction(xrSessionManager, options);\n }\n /**\n * Can be used to return the list of features currently registered\n *\n * @returns an Array of available features\n */\n static GetAvailableFeatures() {\n return Object.keys(this._AvailableFeatures);\n }\n /**\n * Gets the versions available for a specific feature\n * @param featureName the name of the feature\n * @returns an array with the available versions\n */\n static GetAvailableVersions(featureName) {\n return Object.keys(this._AvailableFeatures[featureName]);\n }\n /**\n * Return the latest unstable version of this feature\n * @param featureName the name of the feature to search\n * @returns the version number. if not found will return -1\n */\n static GetLatestVersionOfFeature(featureName) {\n return (this._AvailableFeatures[featureName] && this._AvailableFeatures[featureName].latest) || -1;\n }\n /**\n * Return the latest stable version of this feature\n * @param featureName the name of the feature to search\n * @returns the version number. if not found will return -1\n */\n static GetStableVersionOfFeature(featureName) {\n return (this._AvailableFeatures[featureName] && this._AvailableFeatures[featureName].stable) || -1;\n }\n /**\n * Attach a feature to the current session. Mainly used when session started to start the feature effect.\n * Can be used during a session to start a feature\n * @param featureName the name of feature to attach\n */\n attachFeature(featureName) {\n const feature = this._features[featureName];\n if (feature && feature.enabled && !feature.featureImplementation.attached) {\n feature.featureImplementation.attach();\n }\n }\n /**\n * Can be used inside a session or when the session ends to detach a specific feature\n * @param featureName the name of the feature to detach\n */\n detachFeature(featureName) {\n const feature = this._features[featureName];\n if (feature && feature.featureImplementation.attached) {\n feature.featureImplementation.detach();\n }\n }\n /**\n * Used to disable an already-enabled feature\n * The feature will be disposed and will be recreated once enabled.\n * @param featureName the feature to disable\n * @returns true if disable was successful\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n disableFeature(featureName) {\n const name = typeof featureName === \"string\" ? featureName : featureName.Name;\n const feature = this._features[name];\n if (feature && feature.enabled) {\n feature.enabled = false;\n this.detachFeature(name);\n feature.featureImplementation.dispose();\n delete this._features[name];\n return true;\n }\n return false;\n }\n /**\n * dispose this features manager\n */\n dispose() {\n this.getEnabledFeatures().forEach((feature) => {\n this.disableFeature(feature);\n });\n }\n /**\n * Enable a feature using its name and a version. This will enable it in the scene, and will be responsible to attach it when the session starts.\n * If used twice, the old version will be disposed and a new one will be constructed. This way you can re-enable with different configuration.\n *\n * @param featureName the name of the feature to load or the class of the feature\n * @param version optional version to load. if not provided the latest version will be enabled\n * @param moduleOptions options provided to the module. Ses the module documentation / constructor\n * @param attachIfPossible if set to true (default) the feature will be automatically attached, if it is currently possible\n * @param required is this feature required to the app. If set to true the session init will fail if the feature is not available.\n * @returns a new constructed feature or throws an error if feature not found or conflicts with another enabled feature.\n */\n enableFeature(\n // eslint-disable-next-line @typescript-eslint/naming-convention\n featureName, version = \"latest\", moduleOptions = {}, attachIfPossible = true, required = true) {\n const name = typeof featureName === \"string\" ? featureName : featureName.Name;\n let versionToLoad = 0;\n if (typeof version === \"string\") {\n if (!version) {\n throw new Error(`Error in provided version - ${name} (${version})`);\n }\n if (version === \"stable\") {\n versionToLoad = WebXRFeaturesManager.GetStableVersionOfFeature(name);\n }\n else if (version === \"latest\") {\n versionToLoad = WebXRFeaturesManager.GetLatestVersionOfFeature(name);\n }\n else {\n // try loading the number the string represents\n versionToLoad = +version;\n }\n if (versionToLoad === -1 || isNaN(versionToLoad)) {\n throw new Error(`feature not found - ${name} (${version})`);\n }\n }\n else {\n versionToLoad = version;\n }\n // check if there is a feature conflict\n const conflictingFeature = WebXRFeaturesManager._ConflictingFeatures[name];\n if (conflictingFeature !== undefined && this.getEnabledFeatures().indexOf(conflictingFeature) !== -1) {\n throw new Error(`Feature ${name} cannot be enabled while ${conflictingFeature} is enabled.`);\n }\n // check if already initialized\n const feature = this._features[name];\n const constructFunction = WebXRFeaturesManager.ConstructFeature(name, versionToLoad, this._xrSessionManager, moduleOptions);\n if (!constructFunction) {\n // report error?\n throw new Error(`feature not found - ${name}`);\n }\n /* If the feature is already enabled, detach and dispose it, and create a new one */\n if (feature) {\n this.disableFeature(name);\n }\n const constructed = constructFunction();\n if (constructed.dependsOn) {\n const dependentsFound = constructed.dependsOn.every((featureName) => !!this._features[featureName]);\n if (!dependentsFound) {\n throw new Error(`Dependant features missing. Make sure the following features are enabled - ${constructed.dependsOn.join(\", \")}`);\n }\n }\n if (constructed.isCompatible()) {\n this._features[name] = {\n featureImplementation: constructed,\n enabled: true,\n version: versionToLoad,\n required,\n };\n if (attachIfPossible) {\n // if session started already, request and enable\n if (this._xrSessionManager.session && !this._features[name].featureImplementation.attached) {\n // enable feature\n this.attachFeature(name);\n }\n }\n else {\n // disable auto-attach when session starts\n this._features[name].featureImplementation.disableAutoAttach = true;\n }\n return this._features[name].featureImplementation;\n }\n else {\n if (required) {\n throw new Error(\"required feature not compatible\");\n }\n else {\n Tools.Warn(`Feature ${name} not compatible with the current environment/browser and was not enabled.`);\n return constructed;\n }\n }\n }\n /**\n * get the implementation of an enabled feature.\n * @param featureName the name of the feature to load\n * @returns the feature class, if found\n */\n getEnabledFeature(featureName) {\n return this._features[featureName] && this._features[featureName].featureImplementation;\n }\n /**\n * Get the list of enabled features\n * @returns an array of enabled features\n */\n getEnabledFeatures() {\n return Object.keys(this._features);\n }\n /**\n * This function will extend the session creation configuration object with enabled features.\n * If, for example, the anchors feature is enabled, it will be automatically added to the optional or required features list,\n * according to the defined \"required\" variable, provided during enableFeature call\n * @param xrSessionInit the xr Session init object to extend\n *\n * @returns an extended XRSessionInit object\n */\n async _extendXRSessionInitObject(xrSessionInit) {\n const enabledFeatures = this.getEnabledFeatures();\n for (const featureName of enabledFeatures) {\n const feature = this._features[featureName];\n const nativeName = feature.featureImplementation.xrNativeFeatureName;\n if (nativeName) {\n if (feature.required) {\n xrSessionInit.requiredFeatures = xrSessionInit.requiredFeatures || [];\n if (xrSessionInit.requiredFeatures.indexOf(nativeName) === -1) {\n xrSessionInit.requiredFeatures.push(nativeName);\n }\n }\n else {\n xrSessionInit.optionalFeatures = xrSessionInit.optionalFeatures || [];\n if (xrSessionInit.optionalFeatures.indexOf(nativeName) === -1) {\n xrSessionInit.optionalFeatures.push(nativeName);\n }\n }\n }\n if (feature.featureImplementation.getXRSessionInitExtension) {\n const extended = await feature.featureImplementation.getXRSessionInitExtension();\n xrSessionInit = Object.assign(Object.assign({}, xrSessionInit), extended);\n }\n }\n return xrSessionInit;\n }\n}\nWebXRFeaturesManager._AvailableFeatures = {};\n/**\n * The key is the feature to check and the value is the feature that conflicts.\n */\nWebXRFeaturesManager._ConflictingFeatures = {\n [WebXRFeatureName.TELEPORTATION]: WebXRFeatureName.MOVEMENT,\n [WebXRFeatureName.MOVEMENT]: WebXRFeatureName.TELEPORTATION,\n};\n//# sourceMappingURL=webXRFeaturesManager.js.map","/**\n * This is the base class for all WebXR features.\n * Since most features require almost the same resources and callbacks, this class can be used to simplify the development\n * Note that since the features manager is using the `IWebXRFeature` you are in no way obligated to use this class\n */\nexport class WebXRAbstractFeature {\n /**\n * Construct a new (abstract) WebXR feature\n * @param _xrSessionManager the xr session manager for this feature\n */\n constructor(_xrSessionManager) {\n this._xrSessionManager = _xrSessionManager;\n this._attached = false;\n this._removeOnDetach = [];\n /**\n * Is this feature disposed?\n */\n this.isDisposed = false;\n /**\n * Should auto-attach be disabled?\n */\n this.disableAutoAttach = false;\n /**\n * The name of the native xr feature name (like anchor, hit-test, or hand-tracking)\n */\n this.xrNativeFeatureName = \"\";\n }\n /**\n * Is this feature attached\n */\n get attached() {\n return this._attached;\n }\n /**\n * attach this feature\n *\n * @param force should attachment be forced (even when already attached)\n * @returns true if successful, false is failed or already attached\n */\n attach(force) {\n // do not attach a disposed feature\n if (this.isDisposed) {\n return false;\n }\n if (!force) {\n if (this.attached) {\n return false;\n }\n }\n else {\n if (this.attached) {\n // detach first, to be sure\n this.detach();\n }\n }\n this._attached = true;\n this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable, (frame) => this._onXRFrame(frame));\n return true;\n }\n /**\n * detach this feature.\n *\n * @returns true if successful, false if failed or already detached\n */\n detach() {\n if (!this._attached) {\n this.disableAutoAttach = true;\n return false;\n }\n this._attached = false;\n this._removeOnDetach.forEach((toRemove) => {\n toRemove.observable.remove(toRemove.observer);\n });\n return true;\n }\n /**\n * Dispose this feature and all of the resources attached\n */\n dispose() {\n this.detach();\n this.isDisposed = true;\n }\n /**\n * This function will be executed during before enabling the feature and can be used to not-allow enabling it.\n * Note that at this point the session has NOT started, so this is purely checking if the browser supports it\n *\n * @returns whether or not the feature is compatible in this environment\n */\n isCompatible() {\n return true;\n }\n /**\n * This is used to register callbacks that will automatically be removed when detach is called.\n * @param observable the observable to which the observer will be attached\n * @param callback the callback to register\n */\n _addNewAttachObserver(observable, callback) {\n this._removeOnDetach.push({\n observable,\n observer: observable.add(callback),\n });\n }\n}\n//# sourceMappingURL=WebXRAbstractFeature.js.map","/**\n * This is a holder class for the physics joint created by the physics plugin\n * It holds a set of functions to control the underlying joint\n * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine\n */\nexport class PhysicsJoint {\n /**\n * Initializes the physics joint\n * @param type The type of the physics joint\n * @param jointData The data for the physics joint\n */\n constructor(\n /**\n * The type of the physics joint\n */\n type, \n /**\n * The data for the physics joint\n */\n jointData) {\n this.type = type;\n this.jointData = jointData;\n jointData.nativeParams = jointData.nativeParams || {};\n }\n /**\n * Gets the physics joint\n */\n get physicsJoint() {\n return this._physicsJoint;\n }\n /**\n * Sets the physics joint\n */\n set physicsJoint(newJoint) {\n if (this._physicsJoint) {\n //remove from the world\n }\n this._physicsJoint = newJoint;\n }\n /**\n * Sets the physics plugin\n */\n set physicsPlugin(physicsPlugin) {\n this._physicsPlugin = physicsPlugin;\n }\n /**\n * Execute a function that is physics-plugin specific.\n * @param {Function} func the function that will be executed.\n * It accepts two parameters: the physics world and the physics joint\n */\n executeNativeFunction(func) {\n func(this._physicsPlugin.world, this._physicsJoint);\n }\n}\n//TODO check if the native joints are the same\n//Joint Types\n/**\n * Distance-Joint type\n */\nPhysicsJoint.DistanceJoint = 0;\n/**\n * Hinge-Joint type\n */\nPhysicsJoint.HingeJoint = 1;\n/**\n * Ball-and-Socket joint type\n */\nPhysicsJoint.BallAndSocketJoint = 2;\n/**\n * Wheel-Joint type\n */\nPhysicsJoint.WheelJoint = 3;\n/**\n * Slider-Joint type\n */\nPhysicsJoint.SliderJoint = 4;\n//OIMO\n/**\n * Prismatic-Joint type\n */\nPhysicsJoint.PrismaticJoint = 5;\n//\n/**\n * Universal-Joint type\n * ENERGY FTW! (compare with this - @see http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)\n */\nPhysicsJoint.UniversalJoint = 6;\n/**\n * Hinge-Joint 2 type\n */\nPhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;\n//Cannon\n/**\n * Point to Point Joint type. Similar to a Ball-Joint. Different in parameters\n */\nPhysicsJoint.PointToPointJoint = 8;\n//Cannon only at the moment\n/**\n * Spring-Joint type\n */\nPhysicsJoint.SpringJoint = 9;\n/**\n * Lock-Joint type\n */\nPhysicsJoint.LockJoint = 10;\n/**\n * A class representing a physics distance joint\n * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine\n */\nexport class DistanceJoint extends PhysicsJoint {\n /**\n *\n * @param jointData The data for the Distance-Joint\n */\n constructor(jointData) {\n super(PhysicsJoint.DistanceJoint, jointData);\n }\n /**\n * Update the predefined distance.\n * @param maxDistance The maximum preferred distance\n * @param minDistance The minimum preferred distance\n */\n updateDistance(maxDistance, minDistance) {\n this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);\n }\n}\n/**\n * Represents a Motor-Enabled Joint\n * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine\n */\nexport class MotorEnabledJoint extends PhysicsJoint {\n /**\n * Initializes the Motor-Enabled Joint\n * @param type The type of the joint\n * @param jointData The physical joint data for the joint\n */\n constructor(type, jointData) {\n super(type, jointData);\n }\n /**\n * Set the motor values.\n * Attention, this function is plugin specific. Engines won't react 100% the same.\n * @param force the force to apply\n * @param maxForce max force for this motor.\n */\n setMotor(force, maxForce) {\n this._physicsPlugin.setMotor(this, force || 0, maxForce);\n }\n /**\n * Set the motor's limits.\n * Attention, this function is plugin specific. Engines won't react 100% the same.\n * @param upperLimit The upper limit of the motor\n * @param lowerLimit The lower limit of the motor\n */\n setLimit(upperLimit, lowerLimit) {\n this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);\n }\n}\n/**\n * This class represents a single physics Hinge-Joint\n * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine\n */\nexport class HingeJoint extends MotorEnabledJoint {\n /**\n * Initializes the Hinge-Joint\n * @param jointData The joint data for the Hinge-Joint\n */\n constructor(jointData) {\n super(PhysicsJoint.HingeJoint, jointData);\n }\n /**\n * Set the motor values.\n * Attention, this function is plugin specific. Engines won't react 100% the same.\n * @param {number} force the force to apply\n * @param {number} maxForce max force for this motor.\n */\n setMotor(force, maxForce) {\n this._physicsPlugin.setMotor(this, force || 0, maxForce);\n }\n /**\n * Set the motor's limits.\n * Attention, this function is plugin specific. Engines won't react 100% the same.\n * @param upperLimit The upper limit of the motor\n * @param lowerLimit The lower limit of the motor\n */\n setLimit(upperLimit, lowerLimit) {\n this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);\n }\n}\n/**\n * This class represents a dual hinge physics joint (same as wheel joint)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine\n */\nexport class Hinge2Joint extends MotorEnabledJoint {\n /**\n * Initializes the Hinge2-Joint\n * @param jointData The joint data for the Hinge2-Joint\n */\n constructor(jointData) {\n super(PhysicsJoint.Hinge2Joint, jointData);\n }\n /**\n * Set the motor values.\n * Attention, this function is plugin specific. Engines won't react 100% the same.\n * @param targetSpeed the speed the motor is to reach\n * @param maxForce max force for this motor.\n * @param motorIndex motor's index, 0 or 1.\n */\n setMotor(targetSpeed, maxForce, motorIndex = 0) {\n this._physicsPlugin.setMotor(this, targetSpeed || 0, maxForce, motorIndex);\n }\n /**\n * Set the motor limits.\n * Attention, this function is plugin specific. Engines won't react 100% the same.\n * @param upperLimit the upper limit\n * @param lowerLimit lower limit\n * @param motorIndex the motor's index, 0 or 1.\n */\n setLimit(upperLimit, lowerLimit, motorIndex = 0) {\n this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);\n }\n}\n//# sourceMappingURL=physicsJoint.js.map","import { Logger } from \"../../Misc/logger.js\";\nimport { ArrayTools } from \"../../Misc/arrayTools.js\";\nimport { Vector3, Quaternion } from \"../../Maths/math.vector.js\";\nimport { AbstractMesh } from \"../../Meshes/abstractMesh.js\";\nimport { Mesh } from \"../../Meshes/mesh.js\";\nimport { PhysicsJoint } from \"./physicsJoint.js\";\nimport { Space } from \"../../Maths/math.axis.js\";\nMesh._PhysicsImpostorParser = function (scene, physicObject, jsonObject) {\n return new PhysicsImpostor(physicObject, jsonObject.physicsImpostor, {\n mass: jsonObject.physicsMass,\n friction: jsonObject.physicsFriction,\n restitution: jsonObject.physicsRestitution,\n }, scene);\n};\n/**\n * Represents a physics imposter\n * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine\n */\nexport class PhysicsImpostor {\n /**\n * Specifies if the physics imposter is disposed\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Gets the mass of the physics imposter\n */\n get mass() {\n return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;\n }\n set mass(value) {\n this.setMass(value);\n }\n /**\n * Gets the coefficient of friction\n */\n get friction() {\n return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;\n }\n /**\n * Sets the coefficient of friction\n */\n set friction(value) {\n if (!this._physicsEngine) {\n return;\n }\n this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);\n }\n /**\n * Gets the coefficient of restitution\n */\n get restitution() {\n return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;\n }\n /**\n * Sets the coefficient of restitution\n */\n set restitution(value) {\n if (!this._physicsEngine) {\n return;\n }\n this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);\n }\n /**\n * Gets the pressure of a soft body; only supported by the AmmoJSPlugin\n */\n get pressure() {\n if (!this._physicsEngine) {\n return 0;\n }\n const plugin = this._physicsEngine.getPhysicsPlugin();\n if (!plugin.setBodyPressure) {\n return 0;\n }\n return plugin.getBodyPressure(this);\n }\n /**\n * Sets the pressure of a soft body; only supported by the AmmoJSPlugin\n */\n set pressure(value) {\n if (!this._physicsEngine) {\n return;\n }\n const plugin = this._physicsEngine.getPhysicsPlugin();\n if (!plugin.setBodyPressure) {\n return;\n }\n plugin.setBodyPressure(this, value);\n }\n /**\n * Gets the stiffness of a soft body; only supported by the AmmoJSPlugin\n */\n get stiffness() {\n if (!this._physicsEngine) {\n return 0;\n }\n const plugin = this._physicsEngine.getPhysicsPlugin();\n if (!plugin.getBodyStiffness) {\n return 0;\n }\n return plugin.getBodyStiffness(this);\n }\n /**\n * Sets the stiffness of a soft body; only supported by the AmmoJSPlugin\n */\n set stiffness(value) {\n if (!this._physicsEngine) {\n return;\n }\n const plugin = this._physicsEngine.getPhysicsPlugin();\n if (!plugin.setBodyStiffness) {\n return;\n }\n plugin.setBodyStiffness(this, value);\n }\n /**\n * Gets the velocityIterations of a soft body; only supported by the AmmoJSPlugin\n */\n get velocityIterations() {\n if (!this._physicsEngine) {\n return 0;\n }\n const plugin = this._physicsEngine.getPhysicsPlugin();\n if (!plugin.getBodyVelocityIterations) {\n return 0;\n }\n return plugin.getBodyVelocityIterations(this);\n }\n /**\n * Sets the velocityIterations of a soft body; only supported by the AmmoJSPlugin\n */\n set velocityIterations(value) {\n if (!this._physicsEngine) {\n return;\n }\n const plugin = this._physicsEngine.getPhysicsPlugin();\n if (!plugin.setBodyVelocityIterations) {\n return;\n }\n plugin.setBodyVelocityIterations(this, value);\n }\n /**\n * Gets the positionIterations of a soft body; only supported by the AmmoJSPlugin\n */\n get positionIterations() {\n if (!this._physicsEngine) {\n return 0;\n }\n const plugin = this._physicsEngine.getPhysicsPlugin();\n if (!plugin.getBodyPositionIterations) {\n return 0;\n }\n return plugin.getBodyPositionIterations(this);\n }\n /**\n * Sets the positionIterations of a soft body; only supported by the AmmoJSPlugin\n */\n set positionIterations(value) {\n if (!this._physicsEngine) {\n return;\n }\n const plugin = this._physicsEngine.getPhysicsPlugin();\n if (!plugin.setBodyPositionIterations) {\n return;\n }\n plugin.setBodyPositionIterations(this, value);\n }\n /**\n * Initializes the physics imposter\n * @param object The physics-enabled object used as the physics imposter\n * @param type The type of the physics imposter. Types are available as static members of this class.\n * @param _options The options for the physics imposter\n * @param _scene The Babylon scene\n */\n constructor(\n /**\n * The physics-enabled object used as the physics imposter\n */\n object, \n /**\n * The type of the physics imposter\n */\n type, _options = { mass: 0 }, _scene) {\n this.object = object;\n this.type = type;\n this._options = _options;\n this._scene = _scene;\n /** @internal */\n this._pluginData = {};\n this._bodyUpdateRequired = false;\n this._onBeforePhysicsStepCallbacks = new Array();\n this._onAfterPhysicsStepCallbacks = new Array();\n /** @internal */\n this._onPhysicsCollideCallbacks = [];\n this._deltaPosition = Vector3.Zero();\n this._isDisposed = false;\n /**\n * @internal\n */\n this.soft = false;\n /**\n * @internal\n */\n this.segments = 0;\n //temp variables for parent rotation calculations\n //private _mats: Array = [new Matrix(), new Matrix()];\n this._tmpQuat = new Quaternion();\n this._tmpQuat2 = new Quaternion();\n /**\n * this function is executed by the physics engine.\n */\n this.beforeStep = () => {\n if (!this._physicsEngine) {\n return;\n }\n this.object.translate(this._deltaPosition, -1);\n this._deltaRotationConjugated &&\n this.object.rotationQuaternion &&\n this.object.rotationQuaternion.multiplyToRef(this._deltaRotationConjugated, this.object.rotationQuaternion);\n this.object.computeWorldMatrix(false);\n if (this.object.parent && this.object.rotationQuaternion) {\n this.getParentsRotation();\n this._tmpQuat.multiplyToRef(this.object.rotationQuaternion, this._tmpQuat);\n }\n else {\n this._tmpQuat.copyFrom(this.object.rotationQuaternion || new Quaternion());\n }\n if (!this._options.disableBidirectionalTransformation) {\n this.object.rotationQuaternion &&\n this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this, /*bInfo.boundingBox.centerWorld*/ this.object.getAbsolutePosition(), this._tmpQuat);\n }\n this._onBeforePhysicsStepCallbacks.forEach((func) => {\n func(this);\n });\n };\n /**\n * this function is executed by the physics engine\n */\n this.afterStep = () => {\n if (!this._physicsEngine) {\n return;\n }\n this._onAfterPhysicsStepCallbacks.forEach((func) => {\n func(this);\n });\n this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(this);\n // object has now its world rotation. needs to be converted to local.\n if (this.object.parent && this.object.rotationQuaternion) {\n this.getParentsRotation();\n this._tmpQuat.conjugateInPlace();\n this._tmpQuat.multiplyToRef(this.object.rotationQuaternion, this.object.rotationQuaternion);\n }\n // take the position set and make it the absolute position of this object.\n this.object.setAbsolutePosition(this.object.position);\n if (this._deltaRotation) {\n this.object.rotationQuaternion && this.object.rotationQuaternion.multiplyToRef(this._deltaRotation, this.object.rotationQuaternion);\n this._deltaPosition.applyRotationQuaternionToRef(this._deltaRotation, PhysicsImpostor._TmpVecs[0]);\n this.object.translate(PhysicsImpostor._TmpVecs[0], 1);\n }\n else {\n this.object.translate(this._deltaPosition, 1);\n }\n this.object.computeWorldMatrix(true);\n };\n /**\n * Legacy collision detection event support\n */\n this.onCollideEvent = null;\n /**\n *\n * @param e\n * @returns\n */\n this.onCollide = (e) => {\n if (!this._onPhysicsCollideCallbacks.length && !this.onCollideEvent) {\n return;\n }\n if (!this._physicsEngine) {\n return;\n }\n const otherImpostor = this._physicsEngine.getImpostorWithPhysicsBody(e.body);\n if (otherImpostor) {\n // Legacy collision detection event support\n if (this.onCollideEvent) {\n this.onCollideEvent(this, otherImpostor);\n }\n this._onPhysicsCollideCallbacks\n .filter((obj) => {\n return obj.otherImpostors.indexOf(otherImpostor) !== -1;\n })\n .forEach((obj) => {\n obj.callback(this, otherImpostor, e.point, e.distance, e.impulse, e.normal);\n });\n }\n };\n //sanity check!\n if (!this.object) {\n Logger.Error(\"No object was provided. A physics object is obligatory\");\n return;\n }\n if (this.object.parent && _options.mass !== 0) {\n Logger.Warn(\"A physics impostor has been created for an object which has a parent. Babylon physics currently works in local space so unexpected issues may occur.\");\n }\n // Legacy support for old syntax.\n if (!this._scene && object.getScene) {\n this._scene = object.getScene();\n }\n if (!this._scene) {\n return;\n }\n if (this.type > 100) {\n this.soft = true;\n }\n this._physicsEngine = this._scene.getPhysicsEngine();\n if (!this._physicsEngine) {\n Logger.Error(\"Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.\");\n }\n else {\n //set the object's quaternion, if not set\n if (!this.object.rotationQuaternion) {\n if (this.object.rotation) {\n this.object.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);\n }\n else {\n this.object.rotationQuaternion = new Quaternion();\n }\n }\n //default options params\n this._options.mass = _options.mass === void 0 ? 0 : _options.mass;\n this._options.friction = _options.friction === void 0 ? 0.2 : _options.friction;\n this._options.restitution = _options.restitution === void 0 ? 0.2 : _options.restitution;\n if (this.soft) {\n //softbody mass must be above 0;\n this._options.mass = this._options.mass > 0 ? this._options.mass : 1;\n this._options.pressure = _options.pressure === void 0 ? 200 : _options.pressure;\n this._options.stiffness = _options.stiffness === void 0 ? 1 : _options.stiffness;\n this._options.velocityIterations = _options.velocityIterations === void 0 ? 20 : _options.velocityIterations;\n this._options.positionIterations = _options.positionIterations === void 0 ? 20 : _options.positionIterations;\n this._options.fixedPoints = _options.fixedPoints === void 0 ? 0 : _options.fixedPoints;\n this._options.margin = _options.margin === void 0 ? 0 : _options.margin;\n this._options.damping = _options.damping === void 0 ? 0 : _options.damping;\n this._options.path = _options.path === void 0 ? null : _options.path;\n this._options.shape = _options.shape === void 0 ? null : _options.shape;\n }\n this._joints = [];\n //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.\n if (!this.object.parent || this._options.ignoreParent) {\n this._init();\n }\n else if (this.object.parent.physicsImpostor) {\n Logger.Warn(\"You must affect impostors to children before affecting impostor to parent.\");\n }\n }\n }\n /**\n * This function will completely initialize this impostor.\n * It will create a new body - but only if this mesh has no parent.\n * If it has, this impostor will not be used other than to define the impostor\n * of the child mesh.\n * @internal\n */\n _init() {\n if (!this._physicsEngine) {\n return;\n }\n this._physicsEngine.removeImpostor(this);\n this.physicsBody = null;\n this._parent = this._parent || this._getPhysicsParent();\n if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {\n this._physicsEngine.addImpostor(this);\n }\n }\n _getPhysicsParent() {\n if (this.object.parent instanceof AbstractMesh) {\n const parentMesh = this.object.parent;\n return parentMesh.physicsImpostor;\n }\n return null;\n }\n /**\n * Should a new body be generated.\n * @returns boolean specifying if body initialization is required\n */\n isBodyInitRequired() {\n return this._bodyUpdateRequired || (!this._physicsBody && (!this._parent || !!this._options.ignoreParent));\n }\n /**\n * Sets the updated scaling\n */\n setScalingUpdated() {\n this.forceUpdate();\n }\n /**\n * Force a regeneration of this or the parent's impostor's body.\n * Use with caution - This will remove all previously-instantiated joints.\n */\n forceUpdate() {\n this._init();\n if (this.parent && !this._options.ignoreParent) {\n this.parent.forceUpdate();\n }\n }\n /*public get mesh(): AbstractMesh {\n return this._mesh;\n }*/\n /**\n * Gets the body that holds this impostor. Either its own, or its parent.\n */\n get physicsBody() {\n return this._parent && !this._options.ignoreParent ? this._parent.physicsBody : this._physicsBody;\n }\n /**\n * Get the parent of the physics imposter\n * @returns Physics imposter or null\n */\n get parent() {\n return !this._options.ignoreParent && this._parent ? this._parent : null;\n }\n /**\n * Sets the parent of the physics imposter\n */\n set parent(value) {\n this._parent = value;\n }\n /**\n * Set the physics body. Used mainly by the physics engine/plugin\n */\n set physicsBody(physicsBody) {\n if (this._physicsBody && this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);\n }\n this._physicsBody = physicsBody;\n this.resetUpdateFlags();\n }\n /**\n * Resets the update flags\n */\n resetUpdateFlags() {\n this._bodyUpdateRequired = false;\n }\n /**\n * Gets the object extents\n * @returns the object extents\n */\n getObjectExtents() {\n if (this.object.getBoundingInfo) {\n const q = this.object.rotationQuaternion;\n const scaling = this.object.scaling.clone();\n //reset rotation\n this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;\n //calculate the world matrix with no rotation\n const worldMatrix = this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);\n if (worldMatrix) {\n worldMatrix.decompose(scaling, undefined, undefined);\n }\n const boundingInfo = this.object.getBoundingInfo();\n // get the global scaling of the object\n const size = boundingInfo.boundingBox.extendSize.scale(2).multiplyInPlace(scaling);\n size.x = Math.abs(size.x);\n size.y = Math.abs(size.y);\n size.z = Math.abs(size.z);\n //bring back the rotation\n this.object.rotationQuaternion = q;\n //calculate the world matrix with the new rotation\n this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);\n return size;\n }\n else {\n return PhysicsImpostor.DEFAULT_OBJECT_SIZE;\n }\n }\n /**\n * Gets the object center\n * @returns The object center\n */\n getObjectCenter() {\n if (this.object.getBoundingInfo) {\n const boundingInfo = this.object.getBoundingInfo();\n return boundingInfo.boundingBox.centerWorld;\n }\n else {\n return this.object.position;\n }\n }\n /**\n * Get a specific parameter from the options parameters\n * @param paramName The object parameter name\n * @returns The object parameter\n */\n getParam(paramName) {\n return this._options[paramName];\n }\n /**\n * Sets a specific parameter in the options given to the physics plugin\n * @param paramName The parameter name\n * @param value The value of the parameter\n */\n setParam(paramName, value) {\n this._options[paramName] = value;\n this._bodyUpdateRequired = true;\n }\n /**\n * Specifically change the body's mass. Won't recreate the physics body object\n * @param mass The mass of the physics imposter\n */\n setMass(mass) {\n if (this.getParam(\"mass\") !== mass) {\n this.setParam(\"mass\", mass);\n }\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);\n }\n }\n /**\n * Gets the linear velocity\n * @returns linear velocity or null\n */\n getLinearVelocity() {\n return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : Vector3.Zero();\n }\n /**\n * Sets the linear velocity\n * @param velocity linear velocity or null\n */\n setLinearVelocity(velocity) {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);\n }\n }\n /**\n * Gets the angular velocity\n * @returns angular velocity or null\n */\n getAngularVelocity() {\n return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : Vector3.Zero();\n }\n /**\n * Sets the angular velocity\n * @param velocity The velocity or null\n */\n setAngularVelocity(velocity) {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);\n }\n }\n /**\n * Execute a function with the physics plugin native code\n * Provide a function the will have two variables - the world object and the physics body object\n * @param func The function to execute with the physics plugin native code\n */\n executeNativeFunction(func) {\n if (this._physicsEngine) {\n func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);\n }\n }\n /**\n * Register a function that will be executed before the physics world is stepping forward\n * @param func The function to execute before the physics world is stepped forward\n */\n registerBeforePhysicsStep(func) {\n this._onBeforePhysicsStepCallbacks.push(func);\n }\n /**\n * Unregister a function that will be executed before the physics world is stepping forward\n * @param func The function to execute before the physics world is stepped forward\n */\n unregisterBeforePhysicsStep(func) {\n const index = this._onBeforePhysicsStepCallbacks.indexOf(func);\n if (index > -1) {\n this._onBeforePhysicsStepCallbacks.splice(index, 1);\n }\n else {\n Logger.Warn(\"Function to remove was not found\");\n }\n }\n /**\n * Register a function that will be executed after the physics step\n * @param func The function to execute after physics step\n */\n registerAfterPhysicsStep(func) {\n this._onAfterPhysicsStepCallbacks.push(func);\n }\n /**\n * Unregisters a function that will be executed after the physics step\n * @param func The function to execute after physics step\n */\n unregisterAfterPhysicsStep(func) {\n const index = this._onAfterPhysicsStepCallbacks.indexOf(func);\n if (index > -1) {\n this._onAfterPhysicsStepCallbacks.splice(index, 1);\n }\n else {\n Logger.Warn(\"Function to remove was not found\");\n }\n }\n /**\n * register a function that will be executed when this impostor collides against a different body\n * @param collideAgainst Physics imposter, or array of physics imposters to collide against\n * @param func Callback that is executed on collision\n */\n registerOnPhysicsCollide(collideAgainst, func) {\n const collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];\n this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });\n }\n /**\n * Unregisters the physics imposter's collision callback\n * @param collideAgainst The physics object to collide against\n * @param func Callback to execute on collision\n */\n unregisterOnPhysicsCollide(collideAgainst, func) {\n const collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];\n let index = -1;\n const found = this._onPhysicsCollideCallbacks.some((cbDef, idx) => {\n if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {\n // chcek the arrays match\n const sameList = cbDef.otherImpostors.every((impostor) => {\n return collidedAgainstList.indexOf(impostor) > -1;\n });\n if (sameList) {\n index = idx;\n }\n return sameList;\n }\n return false;\n });\n if (found) {\n this._onPhysicsCollideCallbacks.splice(index, 1);\n }\n else {\n Logger.Warn(\"Function to remove was not found\");\n }\n }\n /**\n * Get the parent rotation\n * @returns The parent rotation\n */\n getParentsRotation() {\n let parent = this.object.parent;\n this._tmpQuat.copyFromFloats(0, 0, 0, 1);\n while (parent) {\n if (parent.rotationQuaternion) {\n this._tmpQuat2.copyFrom(parent.rotationQuaternion);\n }\n else {\n Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);\n }\n this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);\n parent = parent.parent;\n }\n return this._tmpQuat;\n }\n /**\n * Apply a force\n * @param force The force to apply\n * @param contactPoint The contact point for the force\n * @returns The physics imposter\n */\n applyForce(force, contactPoint) {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);\n }\n return this;\n }\n /**\n * Apply an impulse\n * @param force The impulse force\n * @param contactPoint The contact point for the impulse force\n * @returns The physics imposter\n */\n applyImpulse(force, contactPoint) {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);\n }\n return this;\n }\n /**\n * A help function to create a joint\n * @param otherImpostor A physics imposter used to create a joint\n * @param jointType The type of joint\n * @param jointData The data for the joint\n * @returns The physics imposter\n */\n createJoint(otherImpostor, jointType, jointData) {\n const joint = new PhysicsJoint(jointType, jointData);\n this.addJoint(otherImpostor, joint);\n return this;\n }\n /**\n * Add a joint to this impostor with a different impostor\n * @param otherImpostor A physics imposter used to add a joint\n * @param joint The joint to add\n * @returns The physics imposter\n */\n addJoint(otherImpostor, joint) {\n this._joints.push({\n otherImpostor: otherImpostor,\n joint: joint,\n });\n if (this._physicsEngine) {\n this._physicsEngine.addJoint(this, otherImpostor, joint);\n }\n return this;\n }\n /**\n * Add an anchor to a cloth impostor\n * @param otherImpostor rigid impostor to anchor to\n * @param width ratio across width from 0 to 1\n * @param height ratio up height from 0 to 1\n * @param influence the elasticity between cloth impostor and anchor from 0, very stretchy to 1, little stretch\n * @param noCollisionBetweenLinkedBodies when true collisions between cloth impostor and anchor are ignored; default false\n * @returns impostor the soft imposter\n */\n addAnchor(otherImpostor, width, height, influence, noCollisionBetweenLinkedBodies) {\n if (!this._physicsEngine) {\n return this;\n }\n const plugin = this._physicsEngine.getPhysicsPlugin();\n if (!plugin.appendAnchor) {\n return this;\n }\n if (this._physicsEngine) {\n plugin.appendAnchor(this, otherImpostor, width, height, influence, noCollisionBetweenLinkedBodies);\n }\n return this;\n }\n /**\n * Add a hook to a rope impostor\n * @param otherImpostor rigid impostor to anchor to\n * @param length ratio across rope from 0 to 1\n * @param influence the elasticity between rope impostor and anchor from 0, very stretchy to 1, little stretch\n * @param noCollisionBetweenLinkedBodies when true collisions between soft impostor and anchor are ignored; default false\n * @returns impostor the rope imposter\n */\n addHook(otherImpostor, length, influence, noCollisionBetweenLinkedBodies) {\n if (!this._physicsEngine) {\n return this;\n }\n const plugin = this._physicsEngine.getPhysicsPlugin();\n if (!plugin.appendAnchor) {\n return this;\n }\n if (this._physicsEngine) {\n plugin.appendHook(this, otherImpostor, length, influence, noCollisionBetweenLinkedBodies);\n }\n return this;\n }\n /**\n * Will keep this body still, in a sleep mode.\n * @returns the physics imposter\n */\n sleep() {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().sleepBody(this);\n }\n return this;\n }\n /**\n * Wake the body up.\n * @returns The physics imposter\n */\n wakeUp() {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);\n }\n return this;\n }\n /**\n * Clones the physics imposter\n * @param newObject The physics imposter clones to this physics-enabled object\n * @returns A nullable physics imposter\n */\n clone(newObject) {\n if (!newObject) {\n return null;\n }\n return new PhysicsImpostor(newObject, this.type, this._options, this._scene);\n }\n /**\n * Disposes the physics imposter\n */\n dispose( /*disposeChildren: boolean = true*/) {\n //no dispose if no physics engine is available.\n if (!this._physicsEngine) {\n return;\n }\n this._joints.forEach((j) => {\n if (this._physicsEngine) {\n this._physicsEngine.removeJoint(this, j.otherImpostor, j.joint);\n }\n });\n //dispose the physics body\n this._physicsEngine.removeImpostor(this);\n if (this.parent) {\n this.parent.forceUpdate();\n }\n else {\n /*this._object.getChildMeshes().forEach(function(mesh) {\n if (mesh.physicsImpostor) {\n if (disposeChildren) {\n mesh.physicsImpostor.dispose();\n mesh.physicsImpostor = null;\n }\n }\n })*/\n }\n this._isDisposed = true;\n }\n /**\n * Sets the delta position\n * @param position The delta position amount\n */\n setDeltaPosition(position) {\n this._deltaPosition.copyFrom(position);\n }\n /**\n * Sets the delta rotation\n * @param rotation The delta rotation amount\n */\n setDeltaRotation(rotation) {\n if (!this._deltaRotation) {\n this._deltaRotation = new Quaternion();\n }\n this._deltaRotation.copyFrom(rotation);\n this._deltaRotationConjugated = this._deltaRotation.conjugate();\n }\n /**\n * Gets the box size of the physics imposter and stores the result in the input parameter\n * @param result Stores the box size\n * @returns The physics imposter\n */\n getBoxSizeToRef(result) {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);\n }\n return this;\n }\n /**\n * Gets the radius of the physics imposter\n * @returns Radius of the physics imposter\n */\n getRadius() {\n return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;\n }\n /**\n * Sync a bone with this impostor\n * @param bone The bone to sync to the impostor.\n * @param boneMesh The mesh that the bone is influencing.\n * @param jointPivot The pivot of the joint / bone in local space.\n * @param distToJoint Optional distance from the impostor to the joint.\n * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.\n */\n syncBoneWithImpostor(bone, boneMesh, jointPivot, distToJoint, adjustRotation) {\n const tempVec = PhysicsImpostor._TmpVecs[0];\n const mesh = this.object;\n if (mesh.rotationQuaternion) {\n if (adjustRotation) {\n const tempQuat = PhysicsImpostor._TmpQuat;\n mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);\n bone.setRotationQuaternion(tempQuat, Space.WORLD, boneMesh);\n }\n else {\n bone.setRotationQuaternion(mesh.rotationQuaternion, Space.WORLD, boneMesh);\n }\n }\n tempVec.x = 0;\n tempVec.y = 0;\n tempVec.z = 0;\n if (jointPivot) {\n tempVec.x = jointPivot.x;\n tempVec.y = jointPivot.y;\n tempVec.z = jointPivot.z;\n bone.getDirectionToRef(tempVec, boneMesh, tempVec);\n if (distToJoint === undefined || distToJoint === null) {\n distToJoint = jointPivot.length();\n }\n tempVec.x *= distToJoint;\n tempVec.y *= distToJoint;\n tempVec.z *= distToJoint;\n }\n if (bone.getParent()) {\n tempVec.addInPlace(mesh.getAbsolutePosition());\n bone.setAbsolutePosition(tempVec, boneMesh);\n }\n else {\n boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());\n boneMesh.position.x -= tempVec.x;\n boneMesh.position.y -= tempVec.y;\n boneMesh.position.z -= tempVec.z;\n }\n }\n /**\n * Sync impostor to a bone\n * @param bone The bone that the impostor will be synced to.\n * @param boneMesh The mesh that the bone is influencing.\n * @param jointPivot The pivot of the joint / bone in local space.\n * @param distToJoint Optional distance from the impostor to the joint.\n * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.\n * @param boneAxis Optional vector3 axis the bone is aligned with\n */\n syncImpostorWithBone(bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {\n const mesh = this.object;\n if (mesh.rotationQuaternion) {\n if (adjustRotation) {\n const tempQuat = PhysicsImpostor._TmpQuat;\n bone.getRotationQuaternionToRef(Space.WORLD, boneMesh, tempQuat);\n tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);\n }\n else {\n bone.getRotationQuaternionToRef(Space.WORLD, boneMesh, mesh.rotationQuaternion);\n }\n }\n const pos = PhysicsImpostor._TmpVecs[0];\n const boneDir = PhysicsImpostor._TmpVecs[1];\n if (!boneAxis) {\n boneAxis = PhysicsImpostor._TmpVecs[2];\n boneAxis.x = 0;\n boneAxis.y = 1;\n boneAxis.z = 0;\n }\n bone.getDirectionToRef(boneAxis, boneMesh, boneDir);\n bone.getAbsolutePositionToRef(boneMesh, pos);\n if ((distToJoint === undefined || distToJoint === null) && jointPivot) {\n distToJoint = jointPivot.length();\n }\n if (distToJoint !== undefined && distToJoint !== null) {\n pos.x += boneDir.x * distToJoint;\n pos.y += boneDir.y * distToJoint;\n pos.z += boneDir.z * distToJoint;\n }\n mesh.setAbsolutePosition(pos);\n }\n}\n/**\n * The default object size of the imposter\n */\nPhysicsImpostor.DEFAULT_OBJECT_SIZE = new Vector3(1, 1, 1);\n/**\n * The identity quaternion of the imposter\n */\nPhysicsImpostor.IDENTITY_QUATERNION = Quaternion.Identity();\nPhysicsImpostor._TmpVecs = ArrayTools.BuildArray(3, Vector3.Zero);\nPhysicsImpostor._TmpQuat = Quaternion.Identity();\n//Impostor types\n/**\n * No-Imposter type\n */\nPhysicsImpostor.NoImpostor = 0;\n/**\n * Sphere-Imposter type\n */\nPhysicsImpostor.SphereImpostor = 1;\n/**\n * Box-Imposter type\n */\nPhysicsImpostor.BoxImpostor = 2;\n/**\n * Plane-Imposter type\n */\nPhysicsImpostor.PlaneImpostor = 3;\n/**\n * Mesh-imposter type (Only available to objects with vertices data)\n */\nPhysicsImpostor.MeshImpostor = 4;\n/**\n * Capsule-Impostor type (Ammo.js plugin only)\n */\nPhysicsImpostor.CapsuleImpostor = 6;\n/**\n * Cylinder-Imposter type\n */\nPhysicsImpostor.CylinderImpostor = 7;\n/**\n * Particle-Imposter type\n */\nPhysicsImpostor.ParticleImpostor = 8;\n/**\n * Heightmap-Imposter type\n */\nPhysicsImpostor.HeightmapImpostor = 9;\n/**\n * ConvexHull-Impostor type (Ammo.js plugin only)\n */\nPhysicsImpostor.ConvexHullImpostor = 10;\n/**\n * Custom-Imposter type (Ammo.js plugin only)\n */\nPhysicsImpostor.CustomImpostor = 100;\n/**\n * Rope-Imposter type\n */\nPhysicsImpostor.RopeImpostor = 101;\n/**\n * Cloth-Imposter type\n */\nPhysicsImpostor.ClothImpostor = 102;\n/**\n * Softbody-Imposter type\n */\nPhysicsImpostor.SoftbodyImpostor = 103;\n//# sourceMappingURL=physicsImpostor.js.map","import { Tools } from \"../Misc/tools.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Scene } from \"../scene.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { Logger } from \"../Misc/logger.js\";\n\nimport { SceneLoaderFlags } from \"./sceneLoaderFlags.js\";\nimport { IsBase64DataUrl } from \"../Misc/fileTools.js\";\nimport { RuntimeError, ErrorCodes } from \"../Misc/error.js\";\n/**\n * Mode that determines how to handle old animation groups before loading new ones.\n */\nexport var SceneLoaderAnimationGroupLoadingMode;\n(function (SceneLoaderAnimationGroupLoadingMode) {\n /**\n * Reset all old animations to initial state then dispose them.\n */\n SceneLoaderAnimationGroupLoadingMode[SceneLoaderAnimationGroupLoadingMode[\"Clean\"] = 0] = \"Clean\";\n /**\n * Stop all old animations.\n */\n SceneLoaderAnimationGroupLoadingMode[SceneLoaderAnimationGroupLoadingMode[\"Stop\"] = 1] = \"Stop\";\n /**\n * Restart old animations from first frame.\n */\n SceneLoaderAnimationGroupLoadingMode[SceneLoaderAnimationGroupLoadingMode[\"Sync\"] = 2] = \"Sync\";\n /**\n * Old animations remains untouched.\n */\n SceneLoaderAnimationGroupLoadingMode[SceneLoaderAnimationGroupLoadingMode[\"NoSync\"] = 3] = \"NoSync\";\n})(SceneLoaderAnimationGroupLoadingMode || (SceneLoaderAnimationGroupLoadingMode = {}));\n/**\n * Class used to load scene from various file formats using registered plugins\n * @see https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes\n */\nexport class SceneLoader {\n /**\n * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data\n */\n static get ForceFullSceneLoadingForIncremental() {\n return SceneLoaderFlags.ForceFullSceneLoadingForIncremental;\n }\n static set ForceFullSceneLoadingForIncremental(value) {\n SceneLoaderFlags.ForceFullSceneLoadingForIncremental = value;\n }\n /**\n * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene\n */\n static get ShowLoadingScreen() {\n return SceneLoaderFlags.ShowLoadingScreen;\n }\n static set ShowLoadingScreen(value) {\n SceneLoaderFlags.ShowLoadingScreen = value;\n }\n /**\n * Defines the current logging level (while loading the scene)\n * @ignorenaming\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static get loggingLevel() {\n return SceneLoaderFlags.loggingLevel;\n }\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static set loggingLevel(value) {\n SceneLoaderFlags.loggingLevel = value;\n }\n /**\n * Gets or set a boolean indicating if matrix weights must be cleaned upon loading\n */\n static get CleanBoneMatrixWeights() {\n return SceneLoaderFlags.CleanBoneMatrixWeights;\n }\n static set CleanBoneMatrixWeights(value) {\n SceneLoaderFlags.CleanBoneMatrixWeights = value;\n }\n /**\n * Gets the default plugin (used to load Babylon files)\n * @returns the .babylon plugin\n */\n static GetDefaultPlugin() {\n return SceneLoader._RegisteredPlugins[\".babylon\"];\n }\n static _GetPluginForExtension(extension) {\n const registeredPlugin = SceneLoader._RegisteredPlugins[extension];\n if (registeredPlugin) {\n return registeredPlugin;\n }\n Logger.Warn(\"Unable to find a plugin to load \" +\n extension +\n \" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes\");\n return SceneLoader.GetDefaultPlugin();\n }\n static _GetPluginForDirectLoad(data) {\n for (const extension in SceneLoader._RegisteredPlugins) {\n const plugin = SceneLoader._RegisteredPlugins[extension].plugin;\n if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {\n return SceneLoader._RegisteredPlugins[extension];\n }\n }\n return SceneLoader.GetDefaultPlugin();\n }\n static _GetPluginForFilename(sceneFilename) {\n const queryStringPosition = sceneFilename.indexOf(\"?\");\n if (queryStringPosition !== -1) {\n sceneFilename = sceneFilename.substring(0, queryStringPosition);\n }\n const dotPosition = sceneFilename.lastIndexOf(\".\");\n const extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();\n return SceneLoader._GetPluginForExtension(extension);\n }\n static _GetDirectLoad(sceneFilename) {\n if (sceneFilename.substr(0, 5) === \"data:\") {\n return sceneFilename.substr(5);\n }\n return null;\n }\n static _FormatErrorMessage(fileInfo, message, exception) {\n const fromLoad = fileInfo.rawData ? \"binary data\" : fileInfo.url;\n let errorMessage = \"Unable to load from \" + fromLoad;\n if (message) {\n errorMessage += `: ${message}`;\n }\n else if (exception) {\n errorMessage += `: ${exception}`;\n }\n return errorMessage;\n }\n static _LoadData(fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension, name) {\n const directLoad = SceneLoader._GetDirectLoad(fileInfo.url);\n if (fileInfo.rawData && !pluginExtension) {\n throw \"When using ArrayBufferView to load data the file extension must be provided.\";\n }\n const registeredPlugin = pluginExtension\n ? SceneLoader._GetPluginForExtension(pluginExtension)\n : directLoad\n ? SceneLoader._GetPluginForDirectLoad(fileInfo.url)\n : SceneLoader._GetPluginForFilename(fileInfo.url);\n if (fileInfo.rawData && !registeredPlugin.isBinary) {\n throw \"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.\";\n }\n let plugin;\n if (registeredPlugin.plugin.createPlugin !== undefined) {\n plugin = registeredPlugin.plugin.createPlugin();\n }\n else {\n plugin = registeredPlugin.plugin;\n }\n if (!plugin) {\n throw \"The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.\";\n }\n SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);\n // Check if we have a direct load url. If the plugin is registered to handle\n // it or it's not a base64 data url, then pass it through the direct load path.\n if (directLoad && ((plugin.canDirectLoad && plugin.canDirectLoad(fileInfo.url)) || !IsBase64DataUrl(fileInfo.url))) {\n if (plugin.directLoad) {\n const result = plugin.directLoad(scene, directLoad);\n if (result.then) {\n result\n .then((data) => {\n onSuccess(plugin, data);\n })\n .catch((error) => {\n onError(\"Error in directLoad of _loadData: \" + error, error);\n });\n }\n else {\n onSuccess(plugin, result);\n }\n }\n else {\n onSuccess(plugin, directLoad);\n }\n return plugin;\n }\n const useArrayBuffer = registeredPlugin.isBinary;\n const dataCallback = (data, responseURL) => {\n if (scene.isDisposed) {\n onError(\"Scene has been disposed\");\n return;\n }\n onSuccess(plugin, data, responseURL);\n };\n let request = null;\n let pluginDisposed = false;\n const onDisposeObservable = plugin.onDisposeObservable;\n if (onDisposeObservable) {\n onDisposeObservable.add(() => {\n pluginDisposed = true;\n if (request) {\n request.abort();\n request = null;\n }\n onDispose();\n });\n }\n const manifestChecked = () => {\n if (pluginDisposed) {\n return;\n }\n const errorCallback = (request, exception) => {\n onError(request === null || request === void 0 ? void 0 : request.statusText, exception);\n };\n if (!plugin.loadFile && fileInfo.rawData) {\n throw \"Plugin does not support loading ArrayBufferView.\";\n }\n request = plugin.loadFile\n ? plugin.loadFile(scene, fileInfo.rawData || fileInfo.file || fileInfo.url, fileInfo.rootUrl, dataCallback, onProgress, useArrayBuffer, errorCallback, name)\n : scene._loadFile(fileInfo.file || fileInfo.url, dataCallback, onProgress, true, useArrayBuffer, errorCallback);\n };\n const engine = scene.getEngine();\n let canUseOfflineSupport = engine.enableOfflineSupport;\n if (canUseOfflineSupport) {\n // Also check for exceptions\n let exceptionFound = false;\n for (const regex of scene.disableOfflineSupportExceptionRules) {\n if (regex.test(fileInfo.url)) {\n exceptionFound = true;\n break;\n }\n }\n canUseOfflineSupport = !exceptionFound;\n }\n if (canUseOfflineSupport && Engine.OfflineProviderFactory) {\n // Checking if a manifest file has been set for this scene and if offline mode has been requested\n scene.offlineProvider = Engine.OfflineProviderFactory(fileInfo.url, manifestChecked, engine.disableManifestCheck);\n }\n else {\n manifestChecked();\n }\n return plugin;\n }\n static _GetFileInfo(rootUrl, sceneFilename) {\n let url;\n let name;\n let file = null;\n let rawData = null;\n if (!sceneFilename) {\n url = rootUrl;\n name = Tools.GetFilename(rootUrl);\n rootUrl = Tools.GetFolderPath(rootUrl);\n }\n else if (sceneFilename.name) {\n const sceneFile = sceneFilename;\n url = `file:${sceneFile.name}`;\n name = sceneFile.name;\n file = sceneFile;\n }\n else if (ArrayBuffer.isView(sceneFilename)) {\n url = \"\";\n name = \"arrayBuffer\";\n rawData = sceneFilename;\n }\n else if (typeof sceneFilename === \"string\" && sceneFilename.startsWith(\"data:\")) {\n url = sceneFilename;\n name = \"\";\n }\n else {\n const filename = sceneFilename;\n if (filename.substr(0, 1) === \"/\") {\n Tools.Error(\"Wrong sceneFilename parameter\");\n return null;\n }\n url = rootUrl + filename;\n name = filename;\n }\n return {\n url: url,\n rootUrl: rootUrl,\n name: name,\n file: file,\n rawData,\n };\n }\n // Public functions\n /**\n * Gets a plugin that can load the given extension\n * @param extension defines the extension to load\n * @returns a plugin or null if none works\n */\n static GetPluginForExtension(extension) {\n return SceneLoader._GetPluginForExtension(extension).plugin;\n }\n /**\n * Gets a boolean indicating that the given extension can be loaded\n * @param extension defines the extension to load\n * @returns true if the extension is supported\n */\n static IsPluginForExtensionAvailable(extension) {\n return !!SceneLoader._RegisteredPlugins[extension];\n }\n /**\n * Adds a new plugin to the list of registered plugins\n * @param plugin defines the plugin to add\n */\n static RegisterPlugin(plugin) {\n if (typeof plugin.extensions === \"string\") {\n const extension = plugin.extensions;\n SceneLoader._RegisteredPlugins[extension.toLowerCase()] = {\n plugin: plugin,\n isBinary: false,\n };\n }\n else {\n const extensions = plugin.extensions;\n Object.keys(extensions).forEach((extension) => {\n SceneLoader._RegisteredPlugins[extension.toLowerCase()] = {\n plugin: plugin,\n isBinary: extensions[extension].isBinary,\n };\n });\n }\n }\n /**\n * Import meshes into a scene\n * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported\n * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file or starts with \"data:\" following by the stringified version of the scene or a File object (default: empty string)\n * @param scene the instance of BABYLON.Scene to append to\n * @param onSuccess a callback with a list of imported meshes, particleSystems, skeletons, and animationGroups when import succeeds\n * @param onProgress a callback with a progress event for each file being loaded\n * @param onError a callback with the scene, a message, and possibly an exception when import fails\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded plugin\n */\n static ImportMesh(meshNames, rootUrl, sceneFilename = \"\", scene = EngineStore.LastCreatedScene, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name = \"\") {\n if (!scene) {\n Logger.Error(\"No scene available to import mesh to\");\n return null;\n }\n const fileInfo = SceneLoader._GetFileInfo(rootUrl, sceneFilename);\n if (!fileInfo) {\n return null;\n }\n const loadingToken = {};\n scene.addPendingData(loadingToken);\n const disposeHandler = () => {\n scene.removePendingData(loadingToken);\n };\n const errorHandler = (message, exception) => {\n const errorMessage = SceneLoader._FormatErrorMessage(fileInfo, message, exception);\n if (onError) {\n onError(scene, errorMessage, new RuntimeError(errorMessage, ErrorCodes.SceneLoaderError, exception));\n }\n else {\n Logger.Error(errorMessage);\n // should the exception be thrown?\n }\n disposeHandler();\n };\n const progressHandler = onProgress\n ? (event) => {\n try {\n onProgress(event);\n }\n catch (e) {\n errorHandler(\"Error in onProgress callback: \" + e, e);\n }\n }\n : undefined;\n const successHandler = (meshes, particleSystems, skeletons, animationGroups, transformNodes, geometries, lights) => {\n scene.importedMeshesFiles.push(fileInfo.url);\n if (onSuccess) {\n try {\n onSuccess(meshes, particleSystems, skeletons, animationGroups, transformNodes, geometries, lights);\n }\n catch (e) {\n errorHandler(\"Error in onSuccess callback: \" + e, e);\n }\n }\n scene.removePendingData(loadingToken);\n };\n return SceneLoader._LoadData(fileInfo, scene, (plugin, data, responseURL) => {\n if (plugin.rewriteRootURL) {\n fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);\n }\n if (plugin.importMesh) {\n const syncedPlugin = plugin;\n const meshes = new Array();\n const particleSystems = new Array();\n const skeletons = new Array();\n if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {\n return;\n }\n scene.loadingPluginName = plugin.name;\n successHandler(meshes, particleSystems, skeletons, [], [], [], []);\n }\n else {\n const asyncedPlugin = plugin;\n asyncedPlugin\n .importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name)\n .then((result) => {\n scene.loadingPluginName = plugin.name;\n successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups, result.transformNodes, result.geometries, result.lights);\n })\n .catch((error) => {\n errorHandler(error.message, error);\n });\n }\n }, progressHandler, errorHandler, disposeHandler, pluginExtension, name);\n }\n /**\n * Import meshes into a scene\n * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported\n * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file or starts with \"data:\" following by the stringified version of the scene or a File object (default: empty string)\n * @param scene the instance of BABYLON.Scene to append to\n * @param onProgress a callback with a progress event for each file being loaded\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups\n */\n static ImportMeshAsync(meshNames, rootUrl, sceneFilename = \"\", scene = EngineStore.LastCreatedScene, onProgress = null, pluginExtension = null, name = \"\") {\n return new Promise((resolve, reject) => {\n SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, (meshes, particleSystems, skeletons, animationGroups, transformNodes, geometries, lights) => {\n resolve({\n meshes: meshes,\n particleSystems: particleSystems,\n skeletons: skeletons,\n animationGroups: animationGroups,\n transformNodes: transformNodes,\n geometries: geometries,\n lights: lights,\n });\n }, onProgress, (scene, message, exception) => {\n reject(exception || new Error(message));\n }, pluginExtension, name);\n });\n }\n /**\n * Load a scene\n * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file or starts with \"data:\" following by the stringified version of the scene or a File object (default: empty string)\n * @param engine is the instance of BABYLON.Engine to use to create the scene\n * @param onSuccess a callback with the scene when import succeeds\n * @param onProgress a callback with a progress event for each file being loaded\n * @param onError a callback with the scene, a message, and possibly an exception when import fails\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded plugin\n */\n static Load(rootUrl, sceneFilename = \"\", engine = EngineStore.LastCreatedEngine, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name = \"\") {\n if (!engine) {\n Tools.Error(\"No engine available\");\n return null;\n }\n return SceneLoader.Append(rootUrl, sceneFilename, new Scene(engine), onSuccess, onProgress, onError, pluginExtension, name);\n }\n /**\n * Load a scene\n * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file or starts with \"data:\" following by the stringified version of the scene or a File object (default: empty string)\n * @param engine is the instance of BABYLON.Engine to use to create the scene\n * @param onProgress a callback with a progress event for each file being loaded\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded scene\n */\n static LoadAsync(rootUrl, sceneFilename = \"\", engine = EngineStore.LastCreatedEngine, onProgress = null, pluginExtension = null, name = \"\") {\n return new Promise((resolve, reject) => {\n SceneLoader.Load(rootUrl, sceneFilename, engine, (scene) => {\n resolve(scene);\n }, onProgress, (scene, message, exception) => {\n reject(exception || new Error(message));\n }, pluginExtension, name);\n });\n }\n /**\n * Append a scene\n * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file or starts with \"data:\" following by the stringified version of the scene or a File object (default: empty string)\n * @param scene is the instance of BABYLON.Scene to append to\n * @param onSuccess a callback with the scene when import succeeds\n * @param onProgress a callback with a progress event for each file being loaded\n * @param onError a callback with the scene, a message, and possibly an exception when import fails\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded plugin\n */\n static Append(rootUrl, sceneFilename = \"\", scene = EngineStore.LastCreatedScene, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name = \"\") {\n if (!scene) {\n Logger.Error(\"No scene available to append to\");\n return null;\n }\n const fileInfo = SceneLoader._GetFileInfo(rootUrl, sceneFilename);\n if (!fileInfo) {\n return null;\n }\n const loadingToken = {};\n scene.addPendingData(loadingToken);\n const disposeHandler = () => {\n scene.removePendingData(loadingToken);\n };\n if (SceneLoader.ShowLoadingScreen && !this._ShowingLoadingScreen) {\n this._ShowingLoadingScreen = true;\n scene.getEngine().displayLoadingUI();\n scene.executeWhenReady(() => {\n scene.getEngine().hideLoadingUI();\n this._ShowingLoadingScreen = false;\n });\n }\n const errorHandler = (message, exception) => {\n const errorMessage = SceneLoader._FormatErrorMessage(fileInfo, message, exception);\n if (onError) {\n onError(scene, errorMessage, new RuntimeError(errorMessage, ErrorCodes.SceneLoaderError, exception));\n }\n else {\n Logger.Error(errorMessage);\n // should the exception be thrown?\n }\n disposeHandler();\n };\n const progressHandler = onProgress\n ? (event) => {\n try {\n onProgress(event);\n }\n catch (e) {\n errorHandler(\"Error in onProgress callback\", e);\n }\n }\n : undefined;\n const successHandler = () => {\n if (onSuccess) {\n try {\n onSuccess(scene);\n }\n catch (e) {\n errorHandler(\"Error in onSuccess callback\", e);\n }\n }\n scene.removePendingData(loadingToken);\n };\n return SceneLoader._LoadData(fileInfo, scene, (plugin, data) => {\n if (plugin.load) {\n const syncedPlugin = plugin;\n if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {\n return;\n }\n scene.loadingPluginName = plugin.name;\n successHandler();\n }\n else {\n const asyncedPlugin = plugin;\n asyncedPlugin\n .loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name)\n .then(() => {\n scene.loadingPluginName = plugin.name;\n successHandler();\n })\n .catch((error) => {\n errorHandler(error.message, error);\n });\n }\n }, progressHandler, errorHandler, disposeHandler, pluginExtension, name);\n }\n /**\n * Append a scene\n * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file or starts with \"data:\" following by the stringified version of the scene or a File object (default: empty string)\n * @param scene is the instance of BABYLON.Scene to append to\n * @param onProgress a callback with a progress event for each file being loaded\n * @param pluginExtension the extension used to determine the plugin\n * @returns The given scene\n */\n static AppendAsync(rootUrl, sceneFilename = \"\", scene = EngineStore.LastCreatedScene, onProgress = null, pluginExtension = null, name = \"\") {\n return new Promise((resolve, reject) => {\n SceneLoader.Append(rootUrl, sceneFilename, scene, (scene) => {\n resolve(scene);\n }, onProgress, (scene, message, exception) => {\n reject(exception || new Error(message));\n }, pluginExtension, name);\n });\n }\n /**\n * Load a scene into an asset container\n * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file or starts with \"data:\" following by the stringified version of the scene or a File object (default: empty string)\n * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)\n * @param onSuccess a callback with the scene when import succeeds\n * @param onProgress a callback with a progress event for each file being loaded\n * @param onError a callback with the scene, a message, and possibly an exception when import fails\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded plugin\n */\n static LoadAssetContainer(rootUrl, sceneFilename = \"\", scene = EngineStore.LastCreatedScene, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name = \"\") {\n if (!scene) {\n Logger.Error(\"No scene available to load asset container to\");\n return null;\n }\n const fileInfo = SceneLoader._GetFileInfo(rootUrl, sceneFilename);\n if (!fileInfo) {\n return null;\n }\n const loadingToken = {};\n scene.addPendingData(loadingToken);\n const disposeHandler = () => {\n scene.removePendingData(loadingToken);\n };\n const errorHandler = (message, exception) => {\n const errorMessage = SceneLoader._FormatErrorMessage(fileInfo, message, exception);\n if (onError) {\n onError(scene, errorMessage, new RuntimeError(errorMessage, ErrorCodes.SceneLoaderError, exception));\n }\n else {\n Logger.Error(errorMessage);\n // should the exception be thrown?\n }\n disposeHandler();\n };\n const progressHandler = onProgress\n ? (event) => {\n try {\n onProgress(event);\n }\n catch (e) {\n errorHandler(\"Error in onProgress callback\", e);\n }\n }\n : undefined;\n const successHandler = (assets) => {\n if (onSuccess) {\n try {\n onSuccess(assets);\n }\n catch (e) {\n errorHandler(\"Error in onSuccess callback\", e);\n }\n }\n scene.removePendingData(loadingToken);\n };\n return SceneLoader._LoadData(fileInfo, scene, (plugin, data) => {\n if (plugin.loadAssetContainer) {\n const syncedPlugin = plugin;\n const assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);\n if (!assetContainer) {\n return;\n }\n scene.loadingPluginName = plugin.name;\n successHandler(assetContainer);\n }\n else if (plugin.loadAssetContainerAsync) {\n const asyncedPlugin = plugin;\n asyncedPlugin\n .loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name)\n .then((assetContainer) => {\n scene.loadingPluginName = plugin.name;\n successHandler(assetContainer);\n })\n .catch((error) => {\n errorHandler(error.message, error);\n });\n }\n else {\n errorHandler(\"LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.\");\n }\n }, progressHandler, errorHandler, disposeHandler, pluginExtension, name);\n }\n /**\n * Load a scene into an asset container\n * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file or starts with \"data:\" following by the stringified version of the scene (default: empty string)\n * @param scene is the instance of Scene to append to\n * @param onProgress a callback with a progress event for each file being loaded\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded asset container\n */\n static LoadAssetContainerAsync(rootUrl, sceneFilename = \"\", scene = EngineStore.LastCreatedScene, onProgress = null, pluginExtension = null) {\n return new Promise((resolve, reject) => {\n SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, (assetContainer) => {\n resolve(assetContainer);\n }, onProgress, (scene, message, exception) => {\n reject(exception || new Error(message));\n }, pluginExtension);\n });\n }\n /**\n * Import animations from a file into a scene\n * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file or starts with \"data:\" following by the stringified version of the scene or a File object (default: empty string)\n * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)\n * @param overwriteAnimations when true, animations are cleaned before importing new ones. Animations are appended otherwise\n * @param animationGroupLoadingMode defines how to handle old animations groups before importing new ones\n * @param targetConverter defines a function used to convert animation targets from loaded scene to current scene (default: search node by name)\n * @param onSuccess a callback with the scene when import succeeds\n * @param onProgress a callback with a progress event for each file being loaded\n * @param onError a callback with the scene, a message, and possibly an exception when import fails\n * @param pluginExtension the extension used to determine the plugin\n */\n static ImportAnimations(rootUrl, sceneFilename = \"\", scene = EngineStore.LastCreatedScene, overwriteAnimations = true, animationGroupLoadingMode = SceneLoaderAnimationGroupLoadingMode.Clean, targetConverter = null, onSuccess = null, onProgress = null, onError = null, pluginExtension = null) {\n if (!scene) {\n Logger.Error(\"No scene available to load animations to\");\n return;\n }\n if (overwriteAnimations) {\n // Reset, stop and dispose all animations before loading new ones\n for (const animatable of scene.animatables) {\n animatable.reset();\n }\n scene.stopAllAnimations();\n scene.animationGroups.slice().forEach((animationGroup) => {\n animationGroup.dispose();\n });\n const nodes = scene.getNodes();\n nodes.forEach((node) => {\n if (node.animations) {\n node.animations = [];\n }\n });\n }\n else {\n switch (animationGroupLoadingMode) {\n case SceneLoaderAnimationGroupLoadingMode.Clean:\n scene.animationGroups.slice().forEach((animationGroup) => {\n animationGroup.dispose();\n });\n break;\n case SceneLoaderAnimationGroupLoadingMode.Stop:\n scene.animationGroups.forEach((animationGroup) => {\n animationGroup.stop();\n });\n break;\n case SceneLoaderAnimationGroupLoadingMode.Sync:\n scene.animationGroups.forEach((animationGroup) => {\n animationGroup.reset();\n animationGroup.restart();\n });\n break;\n case SceneLoaderAnimationGroupLoadingMode.NoSync:\n // nothing to do\n break;\n default:\n Logger.Error(\"Unknown animation group loading mode value '\" + animationGroupLoadingMode + \"'\");\n return;\n }\n }\n const startingIndexForNewAnimatables = scene.animatables.length;\n const onAssetContainerLoaded = (container) => {\n container.mergeAnimationsTo(scene, scene.animatables.slice(startingIndexForNewAnimatables), targetConverter);\n container.dispose();\n scene.onAnimationFileImportedObservable.notifyObservers(scene);\n if (onSuccess) {\n onSuccess(scene);\n }\n };\n this.LoadAssetContainer(rootUrl, sceneFilename, scene, onAssetContainerLoaded, onProgress, onError, pluginExtension);\n }\n /**\n * Import animations from a file into a scene\n * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file or starts with \"data:\" following by the stringified version of the scene or a File object (default: empty string)\n * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)\n * @param overwriteAnimations when true, animations are cleaned before importing new ones. Animations are appended otherwise\n * @param animationGroupLoadingMode defines how to handle old animations groups before importing new ones\n * @param targetConverter defines a function used to convert animation targets from loaded scene to current scene (default: search node by name)\n * @param onSuccess a callback with the scene when import succeeds\n * @param onProgress a callback with a progress event for each file being loaded\n * @param onError a callback with the scene, a message, and possibly an exception when import fails\n * @param pluginExtension the extension used to determine the plugin\n * @returns the updated scene with imported animations\n */\n static ImportAnimationsAsync(rootUrl, sceneFilename = \"\", scene = EngineStore.LastCreatedScene, overwriteAnimations = true, animationGroupLoadingMode = SceneLoaderAnimationGroupLoadingMode.Clean, targetConverter = null, \n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onSuccess = null, onProgress = null, \n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onError = null, pluginExtension = null) {\n return new Promise((resolve, reject) => {\n SceneLoader.ImportAnimations(rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, (_scene) => {\n resolve(_scene);\n }, onProgress, (_scene, message, exception) => {\n reject(exception || new Error(message));\n }, pluginExtension);\n });\n }\n}\n/**\n * No logging while loading\n */\nSceneLoader.NO_LOGGING = 0;\n/**\n * Minimal logging while loading\n */\nSceneLoader.MINIMAL_LOGGING = 1;\n/**\n * Summary logging while loading\n */\nSceneLoader.SUMMARY_LOGGING = 2;\n/**\n * Detailed logging while loading\n */\nSceneLoader.DETAILED_LOGGING = 3;\n// Members\n/**\n * Event raised when a plugin is used to load a scene\n */\nSceneLoader.OnPluginActivatedObservable = new Observable();\nSceneLoader._RegisteredPlugins = {};\nSceneLoader._ShowingLoadingScreen = false;\n//# sourceMappingURL=sceneLoader.js.map","/**\n * Defines the kind of connection point for node based material\n */\nexport var NodeMaterialBlockConnectionPointTypes;\n(function (NodeMaterialBlockConnectionPointTypes) {\n /** Float */\n NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes[\"Float\"] = 1] = \"Float\";\n /** Int */\n NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes[\"Int\"] = 2] = \"Int\";\n /** Vector2 */\n NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes[\"Vector2\"] = 4] = \"Vector2\";\n /** Vector3 */\n NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes[\"Vector3\"] = 8] = \"Vector3\";\n /** Vector4 */\n NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes[\"Vector4\"] = 16] = \"Vector4\";\n /** Color3 */\n NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes[\"Color3\"] = 32] = \"Color3\";\n /** Color4 */\n NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes[\"Color4\"] = 64] = \"Color4\";\n /** Matrix */\n NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes[\"Matrix\"] = 128] = \"Matrix\";\n /** Custom object */\n NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes[\"Object\"] = 256] = \"Object\";\n /** Detect type based on connection */\n NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes[\"AutoDetect\"] = 1024] = \"AutoDetect\";\n /** Output type that will be defined by input type */\n NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes[\"BasedOnInput\"] = 2048] = \"BasedOnInput\";\n /** Bitmask of all types */\n NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes[\"All\"] = 4095] = \"All\";\n})(NodeMaterialBlockConnectionPointTypes || (NodeMaterialBlockConnectionPointTypes = {}));\n//# sourceMappingURL=nodeMaterialBlockConnectionPointTypes.js.map","/**\n * Enum used to define the target of a block\n */\nexport var NodeMaterialBlockTargets;\n(function (NodeMaterialBlockTargets) {\n /** Vertex shader */\n NodeMaterialBlockTargets[NodeMaterialBlockTargets[\"Vertex\"] = 1] = \"Vertex\";\n /** Fragment shader */\n NodeMaterialBlockTargets[NodeMaterialBlockTargets[\"Fragment\"] = 2] = \"Fragment\";\n /** Neutral */\n NodeMaterialBlockTargets[NodeMaterialBlockTargets[\"Neutral\"] = 4] = \"Neutral\";\n /** Vertex and Fragment */\n NodeMaterialBlockTargets[NodeMaterialBlockTargets[\"VertexAndFragment\"] = 3] = \"VertexAndFragment\";\n})(NodeMaterialBlockTargets || (NodeMaterialBlockTargets = {}));\n//# sourceMappingURL=nodeMaterialBlockTargets.js.map","import { Matrix } from \"../Maths/math.vector.js\";\nimport { Material } from \"../Materials/material.js\";\n/**\n * Base class of materials working in push mode in babylon JS\n * @internal\n */\nexport class PushMaterial extends Material {\n constructor(name, scene, storeEffectOnSubMeshes = true) {\n super(name, scene);\n this._normalMatrix = new Matrix();\n this._storeEffectOnSubMeshes = storeEffectOnSubMeshes;\n }\n getEffect() {\n return this._storeEffectOnSubMeshes ? this._activeEffect : super.getEffect();\n }\n isReady(mesh, useInstances) {\n if (!mesh) {\n return false;\n }\n if (!this._storeEffectOnSubMeshes) {\n return true;\n }\n if (!mesh.subMeshes || mesh.subMeshes.length === 0) {\n return true;\n }\n return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);\n }\n _isReadyForSubMesh(subMesh) {\n const defines = subMesh.materialDefines;\n if (!this.checkReadyOnEveryCall && subMesh.effect && defines) {\n if (defines._renderId === this.getScene().getRenderId()) {\n return true;\n }\n }\n return false;\n }\n /**\n * Binds the given world matrix to the active effect\n *\n * @param world the matrix to bind\n */\n bindOnlyWorldMatrix(world) {\n this._activeEffect.setMatrix(\"world\", world);\n }\n /**\n * Binds the given normal matrix to the active effect\n *\n * @param normalMatrix the matrix to bind\n */\n bindOnlyNormalMatrix(normalMatrix) {\n this._activeEffect.setMatrix(\"normalMatrix\", normalMatrix);\n }\n bind(world, mesh) {\n if (!mesh) {\n return;\n }\n this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);\n }\n _afterBind(mesh, effect = null) {\n super._afterBind(mesh, effect);\n this.getScene()._cachedEffect = effect;\n if (effect) {\n effect._forceRebindOnNextCall = false;\n }\n }\n _mustRebind(scene, effect, visibility = 1) {\n return scene.isCachedMaterialInvalid(this, effect, visibility);\n }\n dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {\n this._activeEffect = undefined;\n super.dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh);\n }\n}\n//# sourceMappingURL=pushMaterial.js.map","import { NodeMaterialBlockConnectionPointTypes } from \"./Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"./Enums/nodeMaterialBlockTargets.js\";\nimport { Effect } from \"../effect.js\";\n/**\n * Class used to store node based material build state\n */\nexport class NodeMaterialBuildState {\n constructor() {\n /** Gets or sets a boolean indicating if the current state can emit uniform buffers */\n this.supportUniformBuffers = false;\n /**\n * Gets the list of emitted attributes\n */\n this.attributes = new Array();\n /**\n * Gets the list of emitted uniforms\n */\n this.uniforms = new Array();\n /**\n * Gets the list of emitted constants\n */\n this.constants = new Array();\n /**\n * Gets the list of emitted samplers\n */\n this.samplers = new Array();\n /**\n * Gets the list of emitted functions\n */\n this.functions = {};\n /**\n * Gets the list of emitted extensions\n */\n this.extensions = {};\n /**\n * Gets the list of emitted counters\n */\n this.counters = {};\n /** @internal */\n this._attributeDeclaration = \"\";\n /** @internal */\n this._uniformDeclaration = \"\";\n /** @internal */\n this._constantDeclaration = \"\";\n /** @internal */\n this._samplerDeclaration = \"\";\n /** @internal */\n this._varyingTransfer = \"\";\n /** @internal */\n this._injectAtEnd = \"\";\n this._repeatableContentAnchorIndex = 0;\n /** @internal */\n this._builtCompilationString = \"\";\n /**\n * Gets the emitted compilation strings\n */\n this.compilationString = \"\";\n }\n /**\n * Finalize the compilation strings\n * @param state defines the current compilation state\n */\n finalize(state) {\n const emitComments = state.sharedData.emitComments;\n const isFragmentMode = this.target === NodeMaterialBlockTargets.Fragment;\n this.compilationString = `\\r\\n${emitComments ? \"//Entry point\\r\\n\" : \"\"}void main(void) {\\r\\n${this.compilationString}`;\n if (this._constantDeclaration) {\n this.compilationString = `\\r\\n${emitComments ? \"//Constants\\r\\n\" : \"\"}${this._constantDeclaration}\\r\\n${this.compilationString}`;\n }\n let functionCode = \"\";\n for (const functionName in this.functions) {\n functionCode += this.functions[functionName] + `\\r\\n`;\n }\n this.compilationString = `\\r\\n${functionCode}\\r\\n${this.compilationString}`;\n if (!isFragmentMode && this._varyingTransfer) {\n this.compilationString = `${this.compilationString}\\r\\n${this._varyingTransfer}`;\n }\n if (this._injectAtEnd) {\n this.compilationString = `${this.compilationString}\\r\\n${this._injectAtEnd}`;\n }\n this.compilationString = `${this.compilationString}\\r\\n}`;\n if (this.sharedData.varyingDeclaration) {\n this.compilationString = `\\r\\n${emitComments ? \"//Varyings\\r\\n\" : \"\"}${this.sharedData.varyingDeclaration}\\r\\n${this.compilationString}`;\n }\n if (this._samplerDeclaration) {\n this.compilationString = `\\r\\n${emitComments ? \"//Samplers\\r\\n\" : \"\"}${this._samplerDeclaration}\\r\\n${this.compilationString}`;\n }\n if (this._uniformDeclaration) {\n this.compilationString = `\\r\\n${emitComments ? \"//Uniforms\\r\\n\" : \"\"}${this._uniformDeclaration}\\r\\n${this.compilationString}`;\n }\n if (this._attributeDeclaration && !isFragmentMode) {\n this.compilationString = `\\r\\n${emitComments ? \"//Attributes\\r\\n\" : \"\"}${this._attributeDeclaration}\\r\\n${this.compilationString}`;\n }\n this.compilationString = \"precision highp float;\\r\\n\" + this.compilationString;\n this.compilationString = \"#if defined(WEBGL2) || defines(WEBGPU)\\r\\nprecision highp sampler2DArray;\\r\\n#endif\\r\\n\" + this.compilationString;\n for (const extensionName in this.extensions) {\n const extension = this.extensions[extensionName];\n this.compilationString = `\\r\\n${extension}\\r\\n${this.compilationString}`;\n }\n this._builtCompilationString = this.compilationString;\n }\n /** @internal */\n get _repeatableContentAnchor() {\n return `###___ANCHOR${this._repeatableContentAnchorIndex++}___###`;\n }\n /**\n * @internal\n */\n _getFreeVariableName(prefix) {\n prefix = prefix.replace(/[^a-zA-Z_]+/g, \"\");\n if (this.sharedData.variableNames[prefix] === undefined) {\n this.sharedData.variableNames[prefix] = 0;\n // Check reserved words\n if (prefix === \"output\" || prefix === \"texture\") {\n return prefix + this.sharedData.variableNames[prefix];\n }\n return prefix;\n }\n else {\n this.sharedData.variableNames[prefix]++;\n }\n return prefix + this.sharedData.variableNames[prefix];\n }\n /**\n * @internal\n */\n _getFreeDefineName(prefix) {\n if (this.sharedData.defineNames[prefix] === undefined) {\n this.sharedData.defineNames[prefix] = 0;\n }\n else {\n this.sharedData.defineNames[prefix]++;\n }\n return prefix + this.sharedData.defineNames[prefix];\n }\n /**\n * @internal\n */\n _excludeVariableName(name) {\n this.sharedData.variableNames[name] = 0;\n }\n /**\n * @internal\n */\n _emit2DSampler(name) {\n if (this.samplers.indexOf(name) < 0) {\n this._samplerDeclaration += `uniform sampler2D ${name};\\r\\n`;\n this.samplers.push(name);\n }\n }\n /**\n * @internal\n */\n _emit2DArraySampler(name) {\n if (this.samplers.indexOf(name) < 0) {\n this._samplerDeclaration += `uniform sampler2DArray ${name};\\r\\n`;\n this.samplers.push(name);\n }\n }\n /**\n * @internal\n */\n _getGLType(type) {\n switch (type) {\n case NodeMaterialBlockConnectionPointTypes.Float:\n return \"float\";\n case NodeMaterialBlockConnectionPointTypes.Int:\n return \"int\";\n case NodeMaterialBlockConnectionPointTypes.Vector2:\n return \"vec2\";\n case NodeMaterialBlockConnectionPointTypes.Color3:\n case NodeMaterialBlockConnectionPointTypes.Vector3:\n return \"vec3\";\n case NodeMaterialBlockConnectionPointTypes.Color4:\n case NodeMaterialBlockConnectionPointTypes.Vector4:\n return \"vec4\";\n case NodeMaterialBlockConnectionPointTypes.Matrix:\n return \"mat4\";\n }\n return \"\";\n }\n /**\n * @internal\n */\n _emitExtension(name, extension, define = \"\") {\n if (this.extensions[name]) {\n return;\n }\n if (define) {\n extension = `#if ${define}\\r\\n${extension}\\r\\n#endif`;\n }\n this.extensions[name] = extension;\n }\n /**\n * @internal\n */\n _emitFunction(name, code, comments) {\n if (this.functions[name]) {\n return;\n }\n if (this.sharedData.emitComments) {\n code = comments + `\\r\\n` + code;\n }\n this.functions[name] = code;\n }\n /**\n * @internal\n */\n _emitCodeFromInclude(includeName, comments, options) {\n if (options && options.repeatKey) {\n return `#include<${includeName}>${options.substitutionVars ? \"(\" + options.substitutionVars + \")\" : \"\"}[0..${options.repeatKey}]\\r\\n`;\n }\n let code = Effect.IncludesShadersStore[includeName] + \"\\r\\n\";\n if (this.sharedData.emitComments) {\n code = comments + `\\r\\n` + code;\n }\n if (!options) {\n return code;\n }\n if (options.replaceStrings) {\n for (let index = 0; index < options.replaceStrings.length; index++) {\n const replaceString = options.replaceStrings[index];\n code = code.replace(replaceString.search, replaceString.replace);\n }\n }\n return code;\n }\n /**\n * @internal\n */\n _emitFunctionFromInclude(includeName, comments, options, storeKey = \"\") {\n const key = includeName + storeKey;\n if (this.functions[key]) {\n return;\n }\n if (!options || (!options.removeAttributes && !options.removeUniforms && !options.removeVaryings && !options.removeIfDef && !options.replaceStrings)) {\n if (options && options.repeatKey) {\n this.functions[key] = `#include<${includeName}>${options.substitutionVars ? \"(\" + options.substitutionVars + \")\" : \"\"}[0..${options.repeatKey}]\\r\\n`;\n }\n else {\n this.functions[key] = `#include<${includeName}>${(options === null || options === void 0 ? void 0 : options.substitutionVars) ? \"(\" + (options === null || options === void 0 ? void 0 : options.substitutionVars) + \")\" : \"\"}\\r\\n`;\n }\n if (this.sharedData.emitComments) {\n this.functions[key] = comments + `\\r\\n` + this.functions[key];\n }\n return;\n }\n this.functions[key] = Effect.IncludesShadersStore[includeName];\n if (this.sharedData.emitComments) {\n this.functions[key] = comments + `\\r\\n` + this.functions[key];\n }\n if (options.removeIfDef) {\n this.functions[key] = this.functions[key].replace(/^\\s*?#ifdef.+$/gm, \"\");\n this.functions[key] = this.functions[key].replace(/^\\s*?#endif.*$/gm, \"\");\n this.functions[key] = this.functions[key].replace(/^\\s*?#else.*$/gm, \"\");\n this.functions[key] = this.functions[key].replace(/^\\s*?#elif.*$/gm, \"\");\n }\n if (options.removeAttributes) {\n this.functions[key] = this.functions[key].replace(/^\\s*?attribute.+$/gm, \"\");\n }\n if (options.removeUniforms) {\n this.functions[key] = this.functions[key].replace(/^\\s*?uniform.+$/gm, \"\");\n }\n if (options.removeVaryings) {\n this.functions[key] = this.functions[key].replace(/^\\s*?varying.+$/gm, \"\");\n }\n if (options.replaceStrings) {\n for (let index = 0; index < options.replaceStrings.length; index++) {\n const replaceString = options.replaceStrings[index];\n this.functions[key] = this.functions[key].replace(replaceString.search, replaceString.replace);\n }\n }\n }\n /**\n * @internal\n */\n _registerTempVariable(name) {\n if (this.sharedData.temps.indexOf(name) !== -1) {\n return false;\n }\n this.sharedData.temps.push(name);\n return true;\n }\n /**\n * @internal\n */\n _emitVaryingFromString(name, type, define = \"\", notDefine = false) {\n if (this.sharedData.varyings.indexOf(name) !== -1) {\n return false;\n }\n this.sharedData.varyings.push(name);\n if (define) {\n if (define.startsWith(\"defined(\")) {\n this.sharedData.varyingDeclaration += `#if ${define}\\r\\n`;\n }\n else {\n this.sharedData.varyingDeclaration += `${notDefine ? \"#ifndef\" : \"#ifdef\"} ${define}\\r\\n`;\n }\n }\n this.sharedData.varyingDeclaration += `varying ${type} ${name};\\r\\n`;\n if (define) {\n this.sharedData.varyingDeclaration += `#endif\\r\\n`;\n }\n return true;\n }\n /**\n * @internal\n */\n _emitUniformFromString(name, type, define = \"\", notDefine = false) {\n if (this.uniforms.indexOf(name) !== -1) {\n return;\n }\n this.uniforms.push(name);\n if (define) {\n if (define.startsWith(\"defined(\")) {\n this._uniformDeclaration += `#if ${define}\\r\\n`;\n }\n else {\n this._uniformDeclaration += `${notDefine ? \"#ifndef\" : \"#ifdef\"} ${define}\\r\\n`;\n }\n }\n this._uniformDeclaration += `uniform ${type} ${name};\\r\\n`;\n if (define) {\n this._uniformDeclaration += `#endif\\r\\n`;\n }\n }\n /**\n * @internal\n */\n _emitFloat(value) {\n if (value.toString() === value.toFixed(0)) {\n return `${value}.0`;\n }\n return value.toString();\n }\n}\n//# sourceMappingURL=nodeMaterialBuildState.js.map","/**\n * Class used to store shared data between 2 NodeMaterialBuildState\n */\nexport class NodeMaterialBuildStateSharedData {\n /** Creates a new shared data */\n constructor() {\n /**\n * Gets the list of emitted varyings\n */\n this.temps = new Array();\n /**\n * Gets the list of emitted varyings\n */\n this.varyings = new Array();\n /**\n * Gets the varying declaration string\n */\n this.varyingDeclaration = \"\";\n /**\n * Input blocks\n */\n this.inputBlocks = new Array();\n /**\n * Input blocks\n */\n this.textureBlocks = new Array();\n /**\n * Bindable blocks (Blocks that need to set data to the effect)\n */\n this.bindableBlocks = new Array();\n /**\n * Bindable blocks (Blocks that need to set data to the effect) that will always be called (by bindForSubMesh), contrary to bindableBlocks that won't be called if _mustRebind() returns false\n */\n this.forcedBindableBlocks = new Array();\n /**\n * List of blocks that can provide a compilation fallback\n */\n this.blocksWithFallbacks = new Array();\n /**\n * List of blocks that can provide a define update\n */\n this.blocksWithDefines = new Array();\n /**\n * List of blocks that can provide a repeatable content\n */\n this.repeatableContentBlocks = new Array();\n /**\n * List of blocks that can provide a dynamic list of uniforms\n */\n this.dynamicUniformBlocks = new Array();\n /**\n * List of blocks that can block the isReady function for the material\n */\n this.blockingBlocks = new Array();\n /**\n * Gets the list of animated inputs\n */\n this.animatedInputs = new Array();\n /** List of emitted variables */\n this.variableNames = {};\n /** List of emitted defines */\n this.defineNames = {};\n /**\n * Gets the compilation hints emitted at compilation time\n */\n this.hints = {\n needWorldViewMatrix: false,\n needWorldViewProjectionMatrix: false,\n needAlphaBlending: false,\n needAlphaTesting: false,\n };\n /**\n * List of compilation checks\n */\n this.checks = {\n emitVertex: false,\n emitFragment: false,\n notConnectedNonOptionalInputs: new Array(),\n };\n /**\n * Is vertex program allowed to be empty?\n */\n this.allowEmptyVertexProgram = false;\n // Exclude usual attributes from free variable names\n this.variableNames[\"position\"] = 0;\n this.variableNames[\"normal\"] = 0;\n this.variableNames[\"tangent\"] = 0;\n this.variableNames[\"uv\"] = 0;\n this.variableNames[\"uv2\"] = 0;\n this.variableNames[\"uv3\"] = 0;\n this.variableNames[\"uv4\"] = 0;\n this.variableNames[\"uv5\"] = 0;\n this.variableNames[\"uv6\"] = 0;\n this.variableNames[\"color\"] = 0;\n this.variableNames[\"matricesIndices\"] = 0;\n this.variableNames[\"matricesWeights\"] = 0;\n this.variableNames[\"matricesIndicesExtra\"] = 0;\n this.variableNames[\"matricesWeightsExtra\"] = 0;\n this.variableNames[\"diffuseBase\"] = 0;\n this.variableNames[\"specularBase\"] = 0;\n this.variableNames[\"worldPos\"] = 0;\n this.variableNames[\"shadow\"] = 0;\n this.variableNames[\"view\"] = 0;\n // Exclude known varyings\n this.variableNames[\"vTBN\"] = 0;\n // Exclude defines\n this.defineNames[\"MAINUV0\"] = 0;\n this.defineNames[\"MAINUV1\"] = 0;\n this.defineNames[\"MAINUV2\"] = 0;\n this.defineNames[\"MAINUV3\"] = 0;\n this.defineNames[\"MAINUV4\"] = 0;\n this.defineNames[\"MAINUV5\"] = 0;\n this.defineNames[\"MAINUV6\"] = 0;\n this.defineNames[\"MAINUV7\"] = 0;\n }\n /**\n * Emits console errors and exceptions if there is a failing check\n */\n emitErrors() {\n let errorMessage = \"\";\n if (!this.checks.emitVertex && !this.allowEmptyVertexProgram) {\n errorMessage += \"NodeMaterial does not have a vertex output. You need to at least add a block that generates a glPosition value.\\r\\n\";\n }\n if (!this.checks.emitFragment) {\n errorMessage += \"NodeMaterial does not have a fragment output. You need to at least add a block that generates a glFragColor value.\\r\\n\";\n }\n for (const notConnectedInput of this.checks.notConnectedNonOptionalInputs) {\n errorMessage += `input ${notConnectedInput.name} from block ${notConnectedInput.ownerBlock.name}[${notConnectedInput.ownerBlock.getClassName()}] is not connected and is not optional.\\r\\n`;\n }\n if (errorMessage) {\n throw \"Build of NodeMaterial failed:\\r\\n\" + errorMessage;\n }\n }\n}\n//# sourceMappingURL=nodeMaterialBuildStateSharedData.js.map","import { NodeMaterialBlockConnectionPointTypes } from \"./Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"./Enums/nodeMaterialBlockTargets.js\";\nimport { Observable } from \"../../Misc/observable.js\";\n/**\n * Enum used to define the compatibility state between two connection points\n */\nexport var NodeMaterialConnectionPointCompatibilityStates;\n(function (NodeMaterialConnectionPointCompatibilityStates) {\n /** Points are compatibles */\n NodeMaterialConnectionPointCompatibilityStates[NodeMaterialConnectionPointCompatibilityStates[\"Compatible\"] = 0] = \"Compatible\";\n /** Points are incompatible because of their types */\n NodeMaterialConnectionPointCompatibilityStates[NodeMaterialConnectionPointCompatibilityStates[\"TypeIncompatible\"] = 1] = \"TypeIncompatible\";\n /** Points are incompatible because of their targets (vertex vs fragment) */\n NodeMaterialConnectionPointCompatibilityStates[NodeMaterialConnectionPointCompatibilityStates[\"TargetIncompatible\"] = 2] = \"TargetIncompatible\";\n /** Points are incompatible because they are in the same hierarchy **/\n NodeMaterialConnectionPointCompatibilityStates[NodeMaterialConnectionPointCompatibilityStates[\"HierarchyIssue\"] = 3] = \"HierarchyIssue\";\n})(NodeMaterialConnectionPointCompatibilityStates || (NodeMaterialConnectionPointCompatibilityStates = {}));\n/**\n * Defines the direction of a connection point\n */\nexport var NodeMaterialConnectionPointDirection;\n(function (NodeMaterialConnectionPointDirection) {\n /** Input */\n NodeMaterialConnectionPointDirection[NodeMaterialConnectionPointDirection[\"Input\"] = 0] = \"Input\";\n /** Output */\n NodeMaterialConnectionPointDirection[NodeMaterialConnectionPointDirection[\"Output\"] = 1] = \"Output\";\n})(NodeMaterialConnectionPointDirection || (NodeMaterialConnectionPointDirection = {}));\n/**\n * Defines a connection point for a block\n */\nexport class NodeMaterialConnectionPoint {\n /**\n * Checks if two types are equivalent\n * @param type1 type 1 to check\n * @param type2 type 2 to check\n * @returns true if both types are equivalent, else false\n */\n static AreEquivalentTypes(type1, type2) {\n switch (type1) {\n case NodeMaterialBlockConnectionPointTypes.Vector3: {\n if (type2 === NodeMaterialBlockConnectionPointTypes.Color3) {\n return true;\n }\n break;\n }\n case NodeMaterialBlockConnectionPointTypes.Vector4: {\n if (type2 === NodeMaterialBlockConnectionPointTypes.Color4) {\n return true;\n }\n break;\n }\n case NodeMaterialBlockConnectionPointTypes.Color3: {\n if (type2 === NodeMaterialBlockConnectionPointTypes.Vector3) {\n return true;\n }\n break;\n }\n case NodeMaterialBlockConnectionPointTypes.Color4: {\n if (type2 === NodeMaterialBlockConnectionPointTypes.Vector4) {\n return true;\n }\n break;\n }\n }\n return false;\n }\n /** Gets the direction of the point */\n get direction() {\n return this._direction;\n }\n /**\n * Gets or sets the associated variable name in the shader\n */\n get associatedVariableName() {\n if (this._ownerBlock.isInput) {\n return this._ownerBlock.associatedVariableName;\n }\n if ((!this._enforceAssociatedVariableName || !this._associatedVariableName) && this._connectedPoint) {\n return this._connectedPoint.associatedVariableName;\n }\n return this._associatedVariableName;\n }\n set associatedVariableName(value) {\n this._associatedVariableName = value;\n }\n /** Get the inner type (ie AutoDetect for instance instead of the inferred one) */\n get innerType() {\n if (this._linkedConnectionSource && this._linkedConnectionSource.isConnected) {\n return this.type;\n }\n return this._type;\n }\n /**\n * Gets or sets the connection point type (default is float)\n */\n get type() {\n if (this._type === NodeMaterialBlockConnectionPointTypes.AutoDetect) {\n if (this._ownerBlock.isInput) {\n return this._ownerBlock.type;\n }\n if (this._connectedPoint) {\n return this._connectedPoint.type;\n }\n if (this._linkedConnectionSource && this._linkedConnectionSource.isConnected) {\n return this._linkedConnectionSource.type;\n }\n }\n if (this._type === NodeMaterialBlockConnectionPointTypes.BasedOnInput) {\n if (this._typeConnectionSource) {\n if (!this._typeConnectionSource.isConnected && this._defaultConnectionPointType) {\n return this._defaultConnectionPointType;\n }\n return this._typeConnectionSource.type;\n }\n else if (this._defaultConnectionPointType) {\n return this._defaultConnectionPointType;\n }\n }\n return this._type;\n }\n set type(value) {\n this._type = value;\n }\n /** Gets or sets the target of that connection point */\n get target() {\n if (!this._prioritizeVertex || !this._ownerBlock) {\n return this._target;\n }\n if (this._target !== NodeMaterialBlockTargets.VertexAndFragment) {\n return this._target;\n }\n if (this._ownerBlock.target === NodeMaterialBlockTargets.Fragment) {\n return NodeMaterialBlockTargets.Fragment;\n }\n return NodeMaterialBlockTargets.Vertex;\n }\n set target(value) {\n this._target = value;\n }\n /**\n * Gets a boolean indicating that the current point is connected to another NodeMaterialBlock\n */\n get isConnected() {\n return this.connectedPoint !== null || this.hasEndpoints;\n }\n /**\n * Gets a boolean indicating that the current point is connected to an input block\n */\n get isConnectedToInputBlock() {\n return this.connectedPoint !== null && this.connectedPoint.ownerBlock.isInput;\n }\n /**\n * Gets a the connected input block (if any)\n */\n get connectInputBlock() {\n if (!this.isConnectedToInputBlock) {\n return null;\n }\n return this.connectedPoint.ownerBlock;\n }\n /** Get the other side of the connection (if any) */\n get connectedPoint() {\n return this._connectedPoint;\n }\n /** Get the block that owns this connection point */\n get ownerBlock() {\n return this._ownerBlock;\n }\n /** Get the block connected on the other side of this connection (if any) */\n get sourceBlock() {\n if (!this._connectedPoint) {\n return null;\n }\n return this._connectedPoint.ownerBlock;\n }\n /** Get the block connected on the endpoints of this connection (if any) */\n get connectedBlocks() {\n if (this._endpoints.length === 0) {\n return [];\n }\n return this._endpoints.map((e) => e.ownerBlock);\n }\n /** Gets the list of connected endpoints */\n get endpoints() {\n return this._endpoints;\n }\n /** Gets a boolean indicating if that output point is connected to at least one input */\n get hasEndpoints() {\n return this._endpoints && this._endpoints.length > 0;\n }\n /** Gets a boolean indicating that this connection has a path to the vertex output*/\n get isDirectlyConnectedToVertexOutput() {\n if (!this.hasEndpoints) {\n return false;\n }\n for (const endpoint of this._endpoints) {\n if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Vertex) {\n return true;\n }\n if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Neutral || endpoint.ownerBlock.target === NodeMaterialBlockTargets.VertexAndFragment) {\n if (endpoint.ownerBlock.outputs.some((o) => o.isDirectlyConnectedToVertexOutput)) {\n return true;\n }\n }\n }\n return false;\n }\n /** Gets a boolean indicating that this connection will be used in the vertex shader */\n get isConnectedInVertexShader() {\n if (this.target === NodeMaterialBlockTargets.Vertex) {\n return true;\n }\n if (!this.hasEndpoints) {\n return false;\n }\n for (const endpoint of this._endpoints) {\n if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Vertex) {\n return true;\n }\n if (endpoint.target === NodeMaterialBlockTargets.Vertex) {\n return true;\n }\n if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Neutral || endpoint.ownerBlock.target === NodeMaterialBlockTargets.VertexAndFragment) {\n if (endpoint.ownerBlock.outputs.some((o) => o.isConnectedInVertexShader)) {\n return true;\n }\n }\n }\n return false;\n }\n /** Gets a boolean indicating that this connection will be used in the fragment shader */\n get isConnectedInFragmentShader() {\n if (this.target === NodeMaterialBlockTargets.Fragment) {\n return true;\n }\n if (!this.hasEndpoints) {\n return false;\n }\n for (const endpoint of this._endpoints) {\n if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {\n return true;\n }\n if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Neutral || endpoint.ownerBlock.target === NodeMaterialBlockTargets.VertexAndFragment) {\n if (endpoint.ownerBlock.outputs.some((o) => o.isConnectedInFragmentShader)) {\n return true;\n }\n }\n }\n return false;\n }\n /**\n * Creates a block suitable to be used as an input for this input point.\n * If null is returned, a block based on the point type will be created.\n * @returns The returned string parameter is the name of the output point of NodeMaterialBlock (first parameter of the returned array) that can be connected to the input\n */\n createCustomInputBlock() {\n return null;\n }\n /**\n * Creates a new connection point\n * @param name defines the connection point name\n * @param ownerBlock defines the block hosting this connection point\n * @param direction defines the direction of the connection point\n */\n constructor(name, ownerBlock, direction) {\n /** @internal */\n this._connectedPoint = null;\n this._endpoints = new Array();\n /** @internal */\n this._typeConnectionSource = null;\n /** @internal */\n this._defaultConnectionPointType = null;\n /** @internal */\n this._linkedConnectionSource = null;\n /** @internal */\n this._acceptedConnectionPointType = null;\n this._type = NodeMaterialBlockConnectionPointTypes.Float;\n /** @internal */\n this._enforceAssociatedVariableName = false;\n /** Indicates that this connection point needs dual validation before being connected to another point */\n this.needDualDirectionValidation = false;\n /**\n * Gets or sets the additional types supported by this connection point\n */\n this.acceptedConnectionPointTypes = new Array();\n /**\n * Gets or sets the additional types excluded by this connection point\n */\n this.excludedConnectionPointTypes = new Array();\n /**\n * Observable triggered when this point is connected\n */\n this.onConnectionObservable = new Observable();\n /**\n * Gets or sets a boolean indicating that this connection point is exposed on a frame\n */\n this.isExposedOnFrame = false;\n /**\n * Gets or sets number indicating the position that the port is exposed to on a frame\n */\n this.exposedPortPosition = -1;\n /** @internal */\n this._prioritizeVertex = false;\n this._target = NodeMaterialBlockTargets.VertexAndFragment;\n this._ownerBlock = ownerBlock;\n this.name = name;\n this._direction = direction;\n }\n /**\n * Gets the current class name e.g. \"NodeMaterialConnectionPoint\"\n * @returns the class name\n */\n getClassName() {\n return \"NodeMaterialConnectionPoint\";\n }\n /**\n * Gets a boolean indicating if the current point can be connected to another point\n * @param connectionPoint defines the other connection point\n * @returns a boolean\n */\n canConnectTo(connectionPoint) {\n return this.checkCompatibilityState(connectionPoint) === NodeMaterialConnectionPointCompatibilityStates.Compatible;\n }\n /**\n * Gets a number indicating if the current point can be connected to another point\n * @param connectionPoint defines the other connection point\n * @returns a number defining the compatibility state\n */\n checkCompatibilityState(connectionPoint) {\n const ownerBlock = this._ownerBlock;\n const otherBlock = connectionPoint.ownerBlock;\n if (ownerBlock.target === NodeMaterialBlockTargets.Fragment) {\n // Let's check we are not going reverse\n if (otherBlock.target === NodeMaterialBlockTargets.Vertex) {\n return NodeMaterialConnectionPointCompatibilityStates.TargetIncompatible;\n }\n for (const output of otherBlock.outputs) {\n if (output.ownerBlock.target != NodeMaterialBlockTargets.Neutral && output.isConnectedInVertexShader) {\n return NodeMaterialConnectionPointCompatibilityStates.TargetIncompatible;\n }\n }\n }\n if (this.type !== connectionPoint.type && connectionPoint.innerType !== NodeMaterialBlockConnectionPointTypes.AutoDetect) {\n // Equivalents\n if (NodeMaterialConnectionPoint.AreEquivalentTypes(this.type, connectionPoint.type)) {\n return NodeMaterialConnectionPointCompatibilityStates.Compatible;\n }\n // Accepted types\n if ((connectionPoint.acceptedConnectionPointTypes && connectionPoint.acceptedConnectionPointTypes.indexOf(this.type) !== -1) ||\n (connectionPoint._acceptedConnectionPointType && NodeMaterialConnectionPoint.AreEquivalentTypes(connectionPoint._acceptedConnectionPointType.type, this.type))) {\n return NodeMaterialConnectionPointCompatibilityStates.Compatible;\n }\n else {\n return NodeMaterialConnectionPointCompatibilityStates.TypeIncompatible;\n }\n }\n // Excluded\n if (connectionPoint.excludedConnectionPointTypes && connectionPoint.excludedConnectionPointTypes.indexOf(this.type) !== -1) {\n return NodeMaterialConnectionPointCompatibilityStates.TypeIncompatible;\n }\n // Check hierarchy\n let targetBlock = otherBlock;\n let sourceBlock = ownerBlock;\n if (this.direction === NodeMaterialConnectionPointDirection.Input) {\n targetBlock = ownerBlock;\n sourceBlock = otherBlock;\n }\n if (targetBlock.isAnAncestorOf(sourceBlock)) {\n return NodeMaterialConnectionPointCompatibilityStates.HierarchyIssue;\n }\n return NodeMaterialConnectionPointCompatibilityStates.Compatible;\n }\n /**\n * Connect this point to another connection point\n * @param connectionPoint defines the other connection point\n * @param ignoreConstraints defines if the system will ignore connection type constraints (default is false)\n * @returns the current connection point\n */\n connectTo(connectionPoint, ignoreConstraints = false) {\n if (!ignoreConstraints && !this.canConnectTo(connectionPoint)) {\n throw \"Cannot connect these two connectors.\";\n }\n this._endpoints.push(connectionPoint);\n connectionPoint._connectedPoint = this;\n this._enforceAssociatedVariableName = false;\n this.onConnectionObservable.notifyObservers(connectionPoint);\n connectionPoint.onConnectionObservable.notifyObservers(this);\n return this;\n }\n /**\n * Disconnect this point from one of his endpoint\n * @param endpoint defines the other connection point\n * @returns the current connection point\n */\n disconnectFrom(endpoint) {\n const index = this._endpoints.indexOf(endpoint);\n if (index === -1) {\n return this;\n }\n this._endpoints.splice(index, 1);\n endpoint._connectedPoint = null;\n this._enforceAssociatedVariableName = false;\n endpoint._enforceAssociatedVariableName = false;\n return this;\n }\n /**\n * Fill the list of excluded connection point types with all types other than those passed in the parameter\n * @param mask Types (ORed values of NodeMaterialBlockConnectionPointTypes) that are allowed, and thus will not be pushed to the excluded list\n */\n addExcludedConnectionPointFromAllowedTypes(mask) {\n let bitmask = 1;\n while (bitmask < NodeMaterialBlockConnectionPointTypes.All) {\n if (!(mask & bitmask)) {\n this.excludedConnectionPointTypes.push(bitmask);\n }\n bitmask = bitmask << 1;\n }\n }\n /**\n * Serializes this point in a JSON representation\n * @param isInput defines if the connection point is an input (default is true)\n * @returns the serialized point object\n */\n serialize(isInput = true) {\n const serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.displayName = this.displayName;\n if (isInput && this.connectedPoint) {\n serializationObject.inputName = this.name;\n serializationObject.targetBlockId = this.connectedPoint.ownerBlock.uniqueId;\n serializationObject.targetConnectionName = this.connectedPoint.name;\n serializationObject.isExposedOnFrame = true;\n serializationObject.exposedPortPosition = this.exposedPortPosition;\n }\n if (this.isExposedOnFrame || this.exposedPortPosition >= 0) {\n serializationObject.isExposedOnFrame = true;\n serializationObject.exposedPortPosition = this.exposedPortPosition;\n }\n return serializationObject;\n }\n /**\n * Release resources\n */\n dispose() {\n this.onConnectionObservable.clear();\n }\n}\n//# sourceMappingURL=nodeMaterialBlockConnectionPoint.js.map","/**\n * Enum defining the type of properties that can be edited in the property pages in the NME\n */\nexport var PropertyTypeForEdition;\n(function (PropertyTypeForEdition) {\n /** property is a boolean */\n PropertyTypeForEdition[PropertyTypeForEdition[\"Boolean\"] = 0] = \"Boolean\";\n /** property is a float */\n PropertyTypeForEdition[PropertyTypeForEdition[\"Float\"] = 1] = \"Float\";\n /** property is a int */\n PropertyTypeForEdition[PropertyTypeForEdition[\"Int\"] = 2] = \"Int\";\n /** property is a Vector2 */\n PropertyTypeForEdition[PropertyTypeForEdition[\"Vector2\"] = 3] = \"Vector2\";\n /** property is a list of values */\n PropertyTypeForEdition[PropertyTypeForEdition[\"List\"] = 4] = \"List\";\n})(PropertyTypeForEdition || (PropertyTypeForEdition = {}));\n/**\n * Decorator that flags a property in a node material block as being editable\n * @param displayName\n * @param propertyType\n * @param groupName\n * @param options\n */\nexport function editableInPropertyPage(displayName, propertyType = PropertyTypeForEdition.Boolean, groupName = \"PROPERTIES\", options) {\n return (target, propertyKey) => {\n let propStore = target._propStore;\n if (!propStore) {\n propStore = [];\n target._propStore = propStore;\n }\n propStore.push({\n propertyName: propertyKey,\n displayName: displayName,\n type: propertyType,\n groupName: groupName,\n options: options !== null && options !== void 0 ? options : {},\n });\n };\n}\n//# sourceMappingURL=nodeMaterialDecorator.js.map","import { NodeMaterialBlockConnectionPointTypes } from \"./Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialConnectionPoint, NodeMaterialConnectionPointDirection } from \"./nodeMaterialBlockConnectionPoint.js\";\nimport { NodeMaterialBlockTargets } from \"./Enums/nodeMaterialBlockTargets.js\";\nimport { UniqueIdGenerator } from \"../../Misc/uniqueIdGenerator.js\";\nimport { GetClass } from \"../../Misc/typeStore.js\";\n/**\n * Defines a block that can be used inside a node based material\n */\nexport class NodeMaterialBlock {\n /**\n * Gets the name of the block\n */\n get name() {\n return this._name;\n }\n /**\n * Sets the name of the block. Will check if the name is valid.\n */\n set name(newName) {\n if (!this.validateBlockName(newName)) {\n return;\n }\n this._name = newName;\n }\n /**\n * Gets a boolean indicating that this block can only be used once per NodeMaterial\n */\n get isUnique() {\n return this._isUnique;\n }\n /**\n * Gets a boolean indicating that this block is an end block (e.g. it is generating a system value)\n */\n get isFinalMerger() {\n return this._isFinalMerger;\n }\n /**\n * Gets a boolean indicating that this block is an input (e.g. it sends data to the shader)\n */\n get isInput() {\n return this._isInput;\n }\n /**\n * Gets or sets the build Id\n */\n get buildId() {\n return this._buildId;\n }\n set buildId(value) {\n this._buildId = value;\n }\n /**\n * Gets or sets the target of the block\n */\n get target() {\n return this._target;\n }\n set target(value) {\n if ((this._target & value) !== 0) {\n return;\n }\n this._target = value;\n }\n /**\n * Gets the list of input points\n */\n get inputs() {\n return this._inputs;\n }\n /** Gets the list of output points */\n get outputs() {\n return this._outputs;\n }\n /**\n * Find an input by its name\n * @param name defines the name of the input to look for\n * @returns the input or null if not found\n */\n getInputByName(name) {\n const filter = this._inputs.filter((e) => e.name === name);\n if (filter.length) {\n return filter[0];\n }\n return null;\n }\n /**\n * Find an output by its name\n * @param name defines the name of the output to look for\n * @returns the output or null if not found\n */\n getOutputByName(name) {\n const filter = this._outputs.filter((e) => e.name === name);\n if (filter.length) {\n return filter[0];\n }\n return null;\n }\n /**\n * Creates a new NodeMaterialBlock\n * @param name defines the block name\n * @param target defines the target of that block (Vertex by default)\n * @param isFinalMerger defines a boolean indicating that this block is an end block (e.g. it is generating a system value). Default is false\n * @param isInput defines a boolean indicating that this block is an input (e.g. it sends data to the shader). Default is false\n */\n constructor(name, target = NodeMaterialBlockTargets.Vertex, isFinalMerger = false, isInput = false) {\n this._isFinalMerger = false;\n this._isInput = false;\n this._name = \"\";\n this._isUnique = false;\n /** Gets or sets a boolean indicating that only one input can be connected at a time */\n this.inputsAreExclusive = false;\n /** @internal */\n this._codeVariableName = \"\";\n /** @internal */\n this._inputs = new Array();\n /** @internal */\n this._outputs = new Array();\n /**\n * Gets or sets the comments associated with this block\n */\n this.comments = \"\";\n /** Gets or sets a boolean indicating that this input can be edited in the Inspector (false by default) */\n this.visibleInInspector = false;\n /** Gets or sets a boolean indicating that this input can be edited from a collapsed frame */\n this.visibleOnFrame = false;\n this._target = target;\n this._originalTargetIsNeutral = target === NodeMaterialBlockTargets.Neutral;\n this._isFinalMerger = isFinalMerger;\n this._isInput = isInput;\n this._name = name;\n this.uniqueId = UniqueIdGenerator.UniqueId;\n }\n /** @internal */\n _setInitialTarget(target) {\n this._target = target;\n this._originalTargetIsNeutral = target === NodeMaterialBlockTargets.Neutral;\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n initialize(state) {\n // Do nothing\n }\n /**\n * Bind data to effect. Will only be called for blocks with isBindable === true\n * @param effect defines the effect to bind data to\n * @param nodeMaterial defines the hosting NodeMaterial\n * @param mesh defines the mesh that will be rendered\n * @param subMesh defines the submesh that will be rendered\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n bind(effect, nodeMaterial, mesh, subMesh) {\n // Do nothing\n }\n _declareOutput(output, state) {\n return `${state._getGLType(output.type)} ${output.associatedVariableName}`;\n }\n _writeVariable(currentPoint) {\n const connectionPoint = currentPoint.connectedPoint;\n if (connectionPoint) {\n return `${currentPoint.associatedVariableName}`;\n }\n return `0.`;\n }\n _writeFloat(value) {\n let stringVersion = value.toString();\n if (stringVersion.indexOf(\".\") === -1) {\n stringVersion += \".0\";\n }\n return `${stringVersion}`;\n }\n /**\n * Gets the current class name e.g. \"NodeMaterialBlock\"\n * @returns the class name\n */\n getClassName() {\n return \"NodeMaterialBlock\";\n }\n /**\n * Register a new input. Must be called inside a block constructor\n * @param name defines the connection point name\n * @param type defines the connection point type\n * @param isOptional defines a boolean indicating that this input can be omitted\n * @param target defines the target to use to limit the connection point (will be VertexAndFragment by default)\n * @param point an already created connection point. If not provided, create a new one\n * @returns the current block\n */\n registerInput(name, type, isOptional = false, target, point) {\n point = point !== null && point !== void 0 ? point : new NodeMaterialConnectionPoint(name, this, NodeMaterialConnectionPointDirection.Input);\n point.type = type;\n point.isOptional = isOptional;\n if (target) {\n point.target = target;\n }\n this._inputs.push(point);\n return this;\n }\n /**\n * Register a new output. Must be called inside a block constructor\n * @param name defines the connection point name\n * @param type defines the connection point type\n * @param target defines the target to use to limit the connection point (will be VertexAndFragment by default)\n * @param point an already created connection point. If not provided, create a new one\n * @returns the current block\n */\n registerOutput(name, type, target, point) {\n point = point !== null && point !== void 0 ? point : new NodeMaterialConnectionPoint(name, this, NodeMaterialConnectionPointDirection.Output);\n point.type = type;\n if (target) {\n point.target = target;\n }\n this._outputs.push(point);\n return this;\n }\n /**\n * Will return the first available input e.g. the first one which is not an uniform or an attribute\n * @param forOutput defines an optional connection point to check compatibility with\n * @returns the first available input or null\n */\n getFirstAvailableInput(forOutput = null) {\n for (const input of this._inputs) {\n if (!input.connectedPoint) {\n if (!forOutput || forOutput.type === input.type || input.type === NodeMaterialBlockConnectionPointTypes.AutoDetect) {\n return input;\n }\n }\n }\n return null;\n }\n /**\n * Will return the first available output e.g. the first one which is not yet connected and not a varying\n * @param forBlock defines an optional block to check compatibility with\n * @returns the first available input or null\n */\n getFirstAvailableOutput(forBlock = null) {\n for (const output of this._outputs) {\n if (!forBlock || !forBlock.target || forBlock.target === NodeMaterialBlockTargets.Neutral || (forBlock.target & output.target) !== 0) {\n return output;\n }\n }\n return null;\n }\n /**\n * Gets the sibling of the given output\n * @param current defines the current output\n * @returns the next output in the list or null\n */\n getSiblingOutput(current) {\n const index = this._outputs.indexOf(current);\n if (index === -1 || index >= this._outputs.length) {\n return null;\n }\n return this._outputs[index + 1];\n }\n /**\n * Checks if the current block is an ancestor of a given block\n * @param block defines the potential descendant block to check\n * @returns true if block is a descendant\n */\n isAnAncestorOf(block) {\n for (const output of this._outputs) {\n if (!output.hasEndpoints) {\n continue;\n }\n for (const endpoint of output.endpoints) {\n if (endpoint.ownerBlock === block) {\n return true;\n }\n if (endpoint.ownerBlock.isAnAncestorOf(block)) {\n return true;\n }\n }\n }\n return false;\n }\n /**\n * Connect current block with another block\n * @param other defines the block to connect with\n * @param options define the various options to help pick the right connections\n * @param options.input\n * @param options.output\n * @param options.outputSwizzle\n * @returns the current block\n */\n connectTo(other, options) {\n if (this._outputs.length === 0) {\n return;\n }\n let output = options && options.output ? this.getOutputByName(options.output) : this.getFirstAvailableOutput(other);\n let notFound = true;\n while (notFound) {\n const input = options && options.input ? other.getInputByName(options.input) : other.getFirstAvailableInput(output);\n if (output && input && output.canConnectTo(input)) {\n output.connectTo(input);\n notFound = false;\n }\n else if (!output) {\n throw \"Unable to find a compatible match\";\n }\n else {\n output = this.getSiblingOutput(output);\n }\n }\n return this;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _buildBlock(state) {\n // Empty. Must be defined by child nodes\n }\n /**\n * Add uniforms, samplers and uniform buffers at compilation time\n * @param state defines the state to update\n * @param nodeMaterial defines the node material requesting the update\n * @param defines defines the material defines to update\n * @param uniformBuffers defines the list of uniform buffer names\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n updateUniformsAndSamples(state, nodeMaterial, defines, uniformBuffers) {\n // Do nothing\n }\n /**\n * Add potential fallbacks if shader compilation fails\n * @param mesh defines the mesh to be rendered\n * @param fallbacks defines the current prioritized list of fallbacks\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n provideFallbacks(mesh, fallbacks) {\n // Do nothing\n }\n /**\n * Initialize defines for shader compilation\n * @param mesh defines the mesh to be rendered\n * @param nodeMaterial defines the node material requesting the update\n * @param defines defines the material defines to update\n * @param useInstances specifies that instances should be used\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n initializeDefines(mesh, nodeMaterial, defines, useInstances = false) { }\n /**\n * Update defines for shader compilation\n * @param mesh defines the mesh to be rendered\n * @param nodeMaterial defines the node material requesting the update\n * @param defines defines the material defines to update\n * @param useInstances specifies that instances should be used\n * @param subMesh defines which submesh to render\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n prepareDefines(mesh, nodeMaterial, defines, useInstances = false, subMesh) {\n // Do nothing\n }\n /**\n * Lets the block try to connect some inputs automatically\n * @param material defines the hosting NodeMaterial\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n autoConfigure(material) {\n // Do nothing\n }\n /**\n * Function called when a block is declared as repeatable content generator\n * @param vertexShaderState defines the current compilation state for the vertex shader\n * @param fragmentShaderState defines the current compilation state for the fragment shader\n * @param mesh defines the mesh to be rendered\n * @param defines defines the material defines to update\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n replaceRepeatableContent(vertexShaderState, fragmentShaderState, mesh, defines) {\n // Do nothing\n }\n /** Gets a boolean indicating that the code of this block will be promoted to vertex shader even if connected to fragment output */\n get willBeGeneratedIntoVertexShaderFromFragmentShader() {\n if (this.isInput || this.isFinalMerger) {\n return false;\n }\n if (this._outputs.some((o) => o.isDirectlyConnectedToVertexOutput)) {\n return false;\n }\n if (this.target === NodeMaterialBlockTargets.Vertex) {\n return false;\n }\n if (this.target === NodeMaterialBlockTargets.VertexAndFragment || this.target === NodeMaterialBlockTargets.Neutral) {\n if (this._outputs.some((o) => o.isConnectedInVertexShader)) {\n return true;\n }\n }\n return false;\n }\n /**\n * Checks if the block is ready\n * @param mesh defines the mesh to be rendered\n * @param nodeMaterial defines the node material requesting the update\n * @param defines defines the material defines to update\n * @param useInstances specifies that instances should be used\n * @returns true if the block is ready\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isReady(mesh, nodeMaterial, defines, useInstances = false) {\n return true;\n }\n _linkConnectionTypes(inputIndex0, inputIndex1, looseCoupling = false) {\n if (looseCoupling) {\n this._inputs[inputIndex1]._acceptedConnectionPointType = this._inputs[inputIndex0];\n }\n else {\n this._inputs[inputIndex0]._linkedConnectionSource = this._inputs[inputIndex1];\n }\n this._inputs[inputIndex1]._linkedConnectionSource = this._inputs[inputIndex0];\n }\n _processBuild(block, state, input, activeBlocks) {\n block.build(state, activeBlocks);\n const localBlockIsFragment = state._vertexState != null;\n const otherBlockWasGeneratedInVertexShader = block._buildTarget === NodeMaterialBlockTargets.Vertex && block.target !== NodeMaterialBlockTargets.VertexAndFragment;\n if (localBlockIsFragment &&\n ((block.target & block._buildTarget) === 0 ||\n (block.target & input.target) === 0 ||\n (this.target !== NodeMaterialBlockTargets.VertexAndFragment && otherBlockWasGeneratedInVertexShader))) {\n // context switch! We need a varying\n if ((!block.isInput && state.target !== block._buildTarget) || // block was already emitted by vertex shader\n (block.isInput && block.isAttribute && !block._noContextSwitch) // block is an attribute\n ) {\n const connectedPoint = input.connectedPoint;\n if (state._vertexState._emitVaryingFromString(\"v_\" + connectedPoint.associatedVariableName, state._getGLType(connectedPoint.type))) {\n state._vertexState.compilationString += `${\"v_\" + connectedPoint.associatedVariableName} = ${connectedPoint.associatedVariableName};\\r\\n`;\n }\n input.associatedVariableName = \"v_\" + connectedPoint.associatedVariableName;\n input._enforceAssociatedVariableName = true;\n }\n }\n }\n /**\n * Validates the new name for the block node.\n * @param newName the new name to be given to the node.\n * @returns false if the name is a reserve word, else true.\n */\n validateBlockName(newName) {\n const reservedNames = [\n \"position\",\n \"normal\",\n \"tangent\",\n \"particle_positionw\",\n \"uv\",\n \"uv2\",\n \"uv3\",\n \"uv4\",\n \"uv5\",\n \"uv6\",\n \"position2d\",\n \"particle_uv\",\n \"matricesIndices\",\n \"matricesWeights\",\n \"world0\",\n \"world1\",\n \"world2\",\n \"world3\",\n \"particle_color\",\n \"particle_texturemask\",\n ];\n for (const reservedName of reservedNames) {\n if (newName === reservedName) {\n return false;\n }\n }\n return true;\n }\n /**\n * Compile the current node and generate the shader code\n * @param state defines the current compilation state (uniforms, samplers, current string)\n * @param activeBlocks defines the list of active blocks (i.e. blocks to compile)\n * @returns true if already built\n */\n build(state, activeBlocks) {\n if (this._buildId === state.sharedData.buildId) {\n return true;\n }\n if (!this.isInput) {\n /** Prepare outputs */\n for (const output of this._outputs) {\n if (!output.associatedVariableName) {\n output.associatedVariableName = state._getFreeVariableName(output.name);\n }\n }\n }\n // Check if \"parent\" blocks are compiled\n for (const input of this._inputs) {\n if (!input.connectedPoint) {\n if (!input.isOptional) {\n // Emit a warning\n state.sharedData.checks.notConnectedNonOptionalInputs.push(input);\n }\n continue;\n }\n if (this.target !== NodeMaterialBlockTargets.Neutral) {\n if ((input.target & this.target) === 0) {\n continue;\n }\n if ((input.target & state.target) === 0) {\n continue;\n }\n }\n const block = input.connectedPoint.ownerBlock;\n if (block && block !== this) {\n this._processBuild(block, state, input, activeBlocks);\n }\n }\n if (this._buildId === state.sharedData.buildId) {\n return true; // Need to check again as inputs can be connected multiple time to this endpoint\n }\n // Logs\n if (state.sharedData.verbose) {\n console.log(`${state.target === NodeMaterialBlockTargets.Vertex ? \"Vertex shader\" : \"Fragment shader\"}: Building ${this.name} [${this.getClassName()}]`);\n }\n // Checks final outputs\n if (this.isFinalMerger) {\n switch (state.target) {\n case NodeMaterialBlockTargets.Vertex:\n state.sharedData.checks.emitVertex = true;\n break;\n case NodeMaterialBlockTargets.Fragment:\n state.sharedData.checks.emitFragment = true;\n break;\n }\n }\n if (!this.isInput && state.sharedData.emitComments) {\n state.compilationString += `\\r\\n//${this.name}\\r\\n`;\n }\n this._buildBlock(state);\n this._buildId = state.sharedData.buildId;\n this._buildTarget = state.target;\n // Compile connected blocks\n for (const output of this._outputs) {\n if ((output.target & state.target) === 0) {\n continue;\n }\n for (const endpoint of output.endpoints) {\n const block = endpoint.ownerBlock;\n if (block && (block.target & state.target) !== 0 && activeBlocks.indexOf(block) !== -1) {\n this._processBuild(block, state, endpoint, activeBlocks);\n }\n }\n }\n return false;\n }\n _inputRename(name) {\n return name;\n }\n _outputRename(name) {\n return name;\n }\n _dumpPropertiesCode() {\n const variableName = this._codeVariableName;\n return `${variableName}.visibleInInspector = ${this.visibleInInspector};\\r\\n${variableName}.visibleOnFrame = ${this.visibleOnFrame};\\r\\n${variableName}.target = ${this.target};\\r\\n`;\n }\n /**\n * @internal\n */\n _dumpCode(uniqueNames, alreadyDumped) {\n alreadyDumped.push(this);\n let codeString;\n // Get unique name\n const nameAsVariableName = this.name.replace(/[^A-Za-z_]+/g, \"\");\n this._codeVariableName = nameAsVariableName || `${this.getClassName()}_${this.uniqueId}`;\n if (uniqueNames.indexOf(this._codeVariableName) !== -1) {\n let index = 0;\n do {\n index++;\n this._codeVariableName = nameAsVariableName + index;\n } while (uniqueNames.indexOf(this._codeVariableName) !== -1);\n }\n uniqueNames.push(this._codeVariableName);\n // Declaration\n codeString = `\\r\\n// ${this.getClassName()}\\r\\n`;\n if (this.comments) {\n codeString += `// ${this.comments}\\r\\n`;\n }\n codeString += `var ${this._codeVariableName} = new BABYLON.${this.getClassName()}(\"${this.name}\");\\r\\n`;\n // Properties\n codeString += this._dumpPropertiesCode();\n // Inputs\n for (const input of this.inputs) {\n if (!input.isConnected) {\n continue;\n }\n const connectedOutput = input.connectedPoint;\n const connectedBlock = connectedOutput.ownerBlock;\n if (alreadyDumped.indexOf(connectedBlock) === -1) {\n codeString += connectedBlock._dumpCode(uniqueNames, alreadyDumped);\n }\n }\n // Outputs\n for (const output of this.outputs) {\n if (!output.hasEndpoints) {\n continue;\n }\n for (const endpoint of output.endpoints) {\n const connectedBlock = endpoint.ownerBlock;\n if (connectedBlock && alreadyDumped.indexOf(connectedBlock) === -1) {\n codeString += connectedBlock._dumpCode(uniqueNames, alreadyDumped);\n }\n }\n }\n return codeString;\n }\n /**\n * @internal\n */\n _dumpCodeForOutputConnections(alreadyDumped) {\n let codeString = \"\";\n if (alreadyDumped.indexOf(this) !== -1) {\n return codeString;\n }\n alreadyDumped.push(this);\n for (const input of this.inputs) {\n if (!input.isConnected) {\n continue;\n }\n const connectedOutput = input.connectedPoint;\n const connectedBlock = connectedOutput.ownerBlock;\n codeString += connectedBlock._dumpCodeForOutputConnections(alreadyDumped);\n codeString += `${connectedBlock._codeVariableName}.${connectedBlock._outputRename(connectedOutput.name)}.connectTo(${this._codeVariableName}.${this._inputRename(input.name)});\\r\\n`;\n }\n return codeString;\n }\n /**\n * Clone the current block to a new identical block\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @returns a copy of the current block\n */\n clone(scene, rootUrl = \"\") {\n const serializationObject = this.serialize();\n const blockType = GetClass(serializationObject.customType);\n if (blockType) {\n const block = new blockType();\n block._deserialize(serializationObject, scene, rootUrl);\n return block;\n }\n return null;\n }\n /**\n * Serializes this block in a JSON representation\n * @returns the serialized block object\n */\n serialize() {\n const serializationObject = {};\n serializationObject.customType = \"BABYLON.\" + this.getClassName();\n serializationObject.id = this.uniqueId;\n serializationObject.name = this.name;\n serializationObject.comments = this.comments;\n serializationObject.visibleInInspector = this.visibleInInspector;\n serializationObject.visibleOnFrame = this.visibleOnFrame;\n serializationObject.target = this.target;\n serializationObject.inputs = [];\n serializationObject.outputs = [];\n for (const input of this.inputs) {\n serializationObject.inputs.push(input.serialize());\n }\n for (const output of this.outputs) {\n serializationObject.outputs.push(output.serialize(false));\n }\n return serializationObject;\n }\n /**\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _deserialize(serializationObject, scene, rootUrl) {\n var _a;\n this.name = serializationObject.name;\n this.comments = serializationObject.comments;\n this.visibleInInspector = !!serializationObject.visibleInInspector;\n this.visibleOnFrame = !!serializationObject.visibleOnFrame;\n this._target = (_a = serializationObject.target) !== null && _a !== void 0 ? _a : this.target;\n this._deserializePortDisplayNamesAndExposedOnFrame(serializationObject);\n }\n _deserializePortDisplayNamesAndExposedOnFrame(serializationObject) {\n const serializedInputs = serializationObject.inputs;\n const serializedOutputs = serializationObject.outputs;\n if (serializedInputs) {\n serializedInputs.forEach((port, i) => {\n if (port.displayName) {\n this.inputs[i].displayName = port.displayName;\n }\n if (port.isExposedOnFrame) {\n this.inputs[i].isExposedOnFrame = port.isExposedOnFrame;\n this.inputs[i].exposedPortPosition = port.exposedPortPosition;\n }\n });\n }\n if (serializedOutputs) {\n serializedOutputs.forEach((port, i) => {\n if (port.displayName) {\n this.outputs[i].displayName = port.displayName;\n }\n if (port.isExposedOnFrame) {\n this.outputs[i].isExposedOnFrame = port.isExposedOnFrame;\n this.outputs[i].exposedPortPosition = port.exposedPortPosition;\n }\n });\n }\n }\n /**\n * Release resources\n */\n dispose() {\n for (const input of this.inputs) {\n input.dispose();\n }\n for (const output of this.outputs) {\n output.dispose();\n }\n }\n}\n//# sourceMappingURL=nodeMaterialBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to transform a vector (2, 3 or 4) with a matrix. It will generate a Vector4\n */\nexport class TransformBlock extends NodeMaterialBlock {\n /**\n * Creates a new TransformBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n /**\n * Defines the value to use to complement W value to transform it to a Vector4\n */\n this.complementW = 1;\n /**\n * Defines the value to use to complement z value to transform it to a Vector4\n */\n this.complementZ = 0;\n this.target = NodeMaterialBlockTargets.Vertex;\n this.registerInput(\"vector\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"transform\", NodeMaterialBlockConnectionPointTypes.Matrix);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerOutput(\"xyz\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this._inputs[0].onConnectionObservable.add((other) => {\n if (other.ownerBlock.isInput) {\n const otherAsInput = other.ownerBlock;\n if (otherAsInput.name === \"normal\" || otherAsInput.name === \"tangent\") {\n this.complementW = 0;\n }\n }\n });\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"TransformBlock\";\n }\n /**\n * Gets the vector input\n */\n get vector() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n /**\n * Gets the xyz output component\n */\n get xyz() {\n return this._outputs[1];\n }\n /**\n * Gets the matrix transform input\n */\n get transform() {\n return this._inputs[1];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const vector = this.vector;\n const transform = this.transform;\n if (vector.connectedPoint) {\n // None uniform scaling case.\n if (this.complementW === 0) {\n const comments = `//${this.name}`;\n state._emitFunctionFromInclude(\"helperFunctions\", comments);\n state.sharedData.blocksWithDefines.push(this);\n const transformName = state._getFreeVariableName(`${transform.associatedVariableName}_NUS`);\n state.compilationString += `mat3 ${transformName} = mat3(${transform.associatedVariableName});\\r\\n`;\n state.compilationString += `#ifdef NONUNIFORMSCALING\\r\\n`;\n state.compilationString += `${transformName} = transposeMat3(inverseMat3(${transformName}));\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n switch (vector.connectedPoint.type) {\n case NodeMaterialBlockConnectionPointTypes.Vector2:\n state.compilationString +=\n this._declareOutput(this.output, state) +\n ` = vec4(${transformName} * vec3(${vector.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)});\\r\\n`;\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector3:\n case NodeMaterialBlockConnectionPointTypes.Color3:\n state.compilationString +=\n this._declareOutput(this.output, state) + ` = vec4(${transformName} * ${vector.associatedVariableName}, ${this._writeFloat(this.complementW)});\\r\\n`;\n break;\n default:\n state.compilationString +=\n this._declareOutput(this.output, state) +\n ` = vec4(${transformName} * ${vector.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)});\\r\\n`;\n break;\n }\n }\n else {\n const transformName = transform.associatedVariableName;\n switch (vector.connectedPoint.type) {\n case NodeMaterialBlockConnectionPointTypes.Vector2:\n state.compilationString +=\n this._declareOutput(this.output, state) +\n ` = ${transformName} * vec4(${vector.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)});\\r\\n`;\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector3:\n case NodeMaterialBlockConnectionPointTypes.Color3:\n state.compilationString +=\n this._declareOutput(this.output, state) + ` = ${transformName} * vec4(${vector.associatedVariableName}, ${this._writeFloat(this.complementW)});\\r\\n`;\n break;\n default:\n state.compilationString += this._declareOutput(this.output, state) + ` = ${transformName} * ${vector.associatedVariableName};\\r\\n`;\n break;\n }\n }\n if (this.xyz.hasEndpoints) {\n state.compilationString += this._declareOutput(this.xyz, state) + ` = ${this.output.associatedVariableName}.xyz;\\r\\n`;\n }\n }\n return this;\n }\n /**\n * Update defines for shader compilation\n * @param mesh defines the mesh to be rendered\n * @param nodeMaterial defines the node material requesting the update\n * @param defines defines the material defines to update\n */\n prepareDefines(mesh, nodeMaterial, defines) {\n // Do nothing\n if (mesh.nonUniformScaling) {\n defines.setValue(\"NONUNIFORMSCALING\", true);\n }\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.complementZ = this.complementZ;\n serializationObject.complementW = this.complementW;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.complementZ = serializationObject.complementZ !== undefined ? serializationObject.complementZ : 0.0;\n this.complementW = serializationObject.complementW !== undefined ? serializationObject.complementW : 1.0;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.complementZ = ${this.complementZ};\\r\\n`;\n codeString += `${this._codeVariableName}.complementW = ${this.complementW};\\r\\n`;\n return codeString;\n }\n}\nRegisterClass(\"BABYLON.TransformBlock\", TransformBlock);\n//# sourceMappingURL=transformBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\n/**\n * Block used to output the vertex position\n */\nexport class VertexOutputBlock extends NodeMaterialBlock {\n /**\n * Creates a new VertexOutputBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Vertex, true);\n this.registerInput(\"vector\", NodeMaterialBlockConnectionPointTypes.Vector4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"VertexOutputBlock\";\n }\n /**\n * Gets the vector input component\n */\n get vector() {\n return this._inputs[0];\n }\n _isLogarithmicDepthEnabled(nodeList) {\n for (const node of nodeList) {\n if (node.useLogarithmicDepth) {\n return true;\n }\n }\n return false;\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const input = this.vector;\n state.compilationString += `gl_Position = ${input.associatedVariableName};\\r\\n`;\n if (this._isLogarithmicDepthEnabled(state.sharedData.fragmentOutputNodes)) {\n state._emitUniformFromString(\"logarithmicDepthConstant\", \"float\");\n state._emitVaryingFromString(\"vFragmentDepth\", \"float\");\n state.compilationString += `vFragmentDepth = 1.0 + gl_Position.w;\\r\\n`;\n state.compilationString += `gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\\r\\n`;\n }\n return this;\n }\n}\nRegisterClass(\"BABYLON.VertexOutputBlock\", VertexOutputBlock);\n//# sourceMappingURL=vertexOutputBlock.js.map","/**\n * Enum defining the mode of a NodeMaterialBlockConnectionPoint\n */\nexport var NodeMaterialBlockConnectionPointMode;\n(function (NodeMaterialBlockConnectionPointMode) {\n /** Value is an uniform */\n NodeMaterialBlockConnectionPointMode[NodeMaterialBlockConnectionPointMode[\"Uniform\"] = 0] = \"Uniform\";\n /** Value is a mesh attribute */\n NodeMaterialBlockConnectionPointMode[NodeMaterialBlockConnectionPointMode[\"Attribute\"] = 1] = \"Attribute\";\n /** Value is a varying between vertex and fragment shaders */\n NodeMaterialBlockConnectionPointMode[NodeMaterialBlockConnectionPointMode[\"Varying\"] = 2] = \"Varying\";\n /** Mode is undefined */\n NodeMaterialBlockConnectionPointMode[NodeMaterialBlockConnectionPointMode[\"Undefined\"] = 3] = \"Undefined\";\n})(NodeMaterialBlockConnectionPointMode || (NodeMaterialBlockConnectionPointMode = {}));\n//# sourceMappingURL=nodeMaterialBlockConnectionPointMode.js.map","/**\n * Enum used to define system values e.g. values automatically provided by the system\n */\nexport var NodeMaterialSystemValues;\n(function (NodeMaterialSystemValues) {\n /** World */\n NodeMaterialSystemValues[NodeMaterialSystemValues[\"World\"] = 1] = \"World\";\n /** View */\n NodeMaterialSystemValues[NodeMaterialSystemValues[\"View\"] = 2] = \"View\";\n /** Projection */\n NodeMaterialSystemValues[NodeMaterialSystemValues[\"Projection\"] = 3] = \"Projection\";\n /** ViewProjection */\n NodeMaterialSystemValues[NodeMaterialSystemValues[\"ViewProjection\"] = 4] = \"ViewProjection\";\n /** WorldView */\n NodeMaterialSystemValues[NodeMaterialSystemValues[\"WorldView\"] = 5] = \"WorldView\";\n /** WorldViewProjection */\n NodeMaterialSystemValues[NodeMaterialSystemValues[\"WorldViewProjection\"] = 6] = \"WorldViewProjection\";\n /** CameraPosition */\n NodeMaterialSystemValues[NodeMaterialSystemValues[\"CameraPosition\"] = 7] = \"CameraPosition\";\n /** Fog Color */\n NodeMaterialSystemValues[NodeMaterialSystemValues[\"FogColor\"] = 8] = \"FogColor\";\n /** Delta time */\n NodeMaterialSystemValues[NodeMaterialSystemValues[\"DeltaTime\"] = 9] = \"DeltaTime\";\n /** Camera parameters */\n NodeMaterialSystemValues[NodeMaterialSystemValues[\"CameraParameters\"] = 10] = \"CameraParameters\";\n /** Material alpha */\n NodeMaterialSystemValues[NodeMaterialSystemValues[\"MaterialAlpha\"] = 11] = \"MaterialAlpha\";\n})(NodeMaterialSystemValues || (NodeMaterialSystemValues = {}));\n//# sourceMappingURL=nodeMaterialSystemValues.js.map","import { __decorate } from \"../../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../../nodeMaterialDecorator.js\";\nimport { MaterialHelper } from \"../../../materialHelper.js\";\n/**\n * Block used to output the final color\n */\nexport class FragmentOutputBlock extends NodeMaterialBlock {\n /**\n * Create a new FragmentOutputBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment, true);\n /** Gets or sets a boolean indicating if content needs to be converted to gamma space */\n this.convertToGammaSpace = false;\n /** Gets or sets a boolean indicating if content needs to be converted to linear space */\n this.convertToLinearSpace = false;\n /** Gets or sets a boolean indicating if logarithmic depth should be used */\n this.useLogarithmicDepth = false;\n this.registerInput(\"rgba\", NodeMaterialBlockConnectionPointTypes.Color4, true);\n this.registerInput(\"rgb\", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);\n this.registerInput(\"a\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.rgb.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"FragmentOutputBlock\";\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"logarithmicDepthConstant\");\n state._excludeVariableName(\"vFragmentDepth\");\n }\n /**\n * Gets the rgba input component\n */\n get rgba() {\n return this._inputs[0];\n }\n /**\n * Gets the rgb input component\n */\n get rgb() {\n return this._inputs[1];\n }\n /**\n * Gets the a input component\n */\n get a() {\n return this._inputs[2];\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n defines.setValue(this._linearDefineName, this.convertToLinearSpace, true);\n defines.setValue(this._gammaDefineName, this.convertToGammaSpace, true);\n }\n bind(effect, nodeMaterial, mesh) {\n if (this.useLogarithmicDepth && mesh) {\n MaterialHelper.BindLogDepth(undefined, effect, mesh.getScene());\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const rgba = this.rgba;\n const rgb = this.rgb;\n const a = this.a;\n state.sharedData.hints.needAlphaBlending = rgba.isConnected || a.isConnected;\n state.sharedData.blocksWithDefines.push(this);\n if (this.useLogarithmicDepth) {\n state._emitUniformFromString(\"logarithmicDepthConstant\", \"float\");\n state._emitVaryingFromString(\"vFragmentDepth\", \"float\");\n state.sharedData.bindableBlocks.push(this);\n }\n this._linearDefineName = state._getFreeDefineName(\"CONVERTTOLINEAR\");\n this._gammaDefineName = state._getFreeDefineName(\"CONVERTTOGAMMA\");\n const comments = `//${this.name}`;\n state._emitFunctionFromInclude(\"helperFunctions\", comments);\n if (rgba.connectedPoint) {\n if (a.isConnected) {\n state.compilationString += `gl_FragColor = vec4(${rgba.associatedVariableName}.rgb, ${a.associatedVariableName});\\r\\n`;\n }\n else {\n state.compilationString += `gl_FragColor = ${rgba.associatedVariableName};\\r\\n`;\n }\n }\n else if (rgb.connectedPoint) {\n let aValue = \"1.0\";\n if (a.connectedPoint) {\n aValue = a.associatedVariableName;\n }\n if (rgb.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Float) {\n state.compilationString += `gl_FragColor = vec4(${rgb.associatedVariableName}, ${rgb.associatedVariableName}, ${rgb.associatedVariableName}, ${aValue});\\r\\n`;\n }\n else {\n state.compilationString += `gl_FragColor = vec4(${rgb.associatedVariableName}, ${aValue});\\r\\n`;\n }\n }\n else {\n state.sharedData.checks.notConnectedNonOptionalInputs.push(rgba);\n }\n state.compilationString += `#ifdef ${this._linearDefineName}\\r\\n`;\n state.compilationString += `gl_FragColor = toLinearSpace(gl_FragColor);\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n state.compilationString += `#ifdef ${this._gammaDefineName}\\r\\n`;\n state.compilationString += `gl_FragColor = toGammaSpace(gl_FragColor);\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n if (this.useLogarithmicDepth) {\n state.compilationString += `gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\\r\\n`;\n }\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n codeString += `${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\\r\\n`;\n codeString += `${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\\r\\n`;\n codeString += `${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.convertToGammaSpace = this.convertToGammaSpace;\n serializationObject.convertToLinearSpace = this.convertToLinearSpace;\n serializationObject.useLogarithmicDepth = this.useLogarithmicDepth;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n var _a;\n super._deserialize(serializationObject, scene, rootUrl);\n this.convertToGammaSpace = serializationObject.convertToGammaSpace;\n this.convertToLinearSpace = serializationObject.convertToLinearSpace;\n this.useLogarithmicDepth = (_a = serializationObject.useLogarithmicDepth) !== null && _a !== void 0 ? _a : false;\n }\n}\n__decorate([\n editableInPropertyPage(\"Convert to gamma space\", PropertyTypeForEdition.Boolean, \"PROPERTIES\", { notifiers: { update: true } })\n], FragmentOutputBlock.prototype, \"convertToGammaSpace\", void 0);\n__decorate([\n editableInPropertyPage(\"Convert to linear space\", PropertyTypeForEdition.Boolean, \"PROPERTIES\", { notifiers: { update: true } })\n], FragmentOutputBlock.prototype, \"convertToLinearSpace\", void 0);\n__decorate([\n editableInPropertyPage(\"Use logarithmic depth\", PropertyTypeForEdition.Boolean, \"PROPERTIES\")\n], FragmentOutputBlock.prototype, \"useLogarithmicDepth\", void 0);\nRegisterClass(\"BABYLON.FragmentOutputBlock\", FragmentOutputBlock);\n//# sourceMappingURL=fragmentOutputBlock.js.map","/**\n * Enum defining the type of animations supported by InputBlock\n */\nexport var AnimatedInputBlockTypes;\n(function (AnimatedInputBlockTypes) {\n /** No animation */\n AnimatedInputBlockTypes[AnimatedInputBlockTypes[\"None\"] = 0] = \"None\";\n /** Time based animation (is incremented by 0.6 each second). Will only work for floats */\n AnimatedInputBlockTypes[AnimatedInputBlockTypes[\"Time\"] = 1] = \"Time\";\n /** Time elapsed (in seconds) since the engine was initialized. Will only work for floats */\n AnimatedInputBlockTypes[AnimatedInputBlockTypes[\"RealTime\"] = 2] = \"RealTime\";\n})(AnimatedInputBlockTypes || (AnimatedInputBlockTypes = {}));\n//# sourceMappingURL=animatedInputBlockTypes.js.map","/* eslint-disable @typescript-eslint/naming-convention */\nimport { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockConnectionPointMode } from \"../../Enums/nodeMaterialBlockConnectionPointMode.js\";\nimport { NodeMaterialSystemValues } from \"../../Enums/nodeMaterialSystemValues.js\";\nimport { Matrix, Vector2, Vector3, Vector4 } from \"../../../../Maths/math.vector.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { GetClass, RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { Color3, Color4, TmpColors } from \"../../../../Maths/math.js\";\nimport { AnimatedInputBlockTypes } from \"./animatedInputBlockTypes.js\";\nimport { Observable } from \"../../../../Misc/observable.js\";\nimport { PrecisionDate } from \"../../../../Misc/precisionDate.js\";\nconst remapAttributeName = {\n position2d: \"position\",\n particle_uv: \"vUV\",\n particle_color: \"vColor\",\n particle_texturemask: \"textureMask\",\n particle_positionw: \"vPositionW\",\n};\nconst attributeInFragmentOnly = {\n particle_uv: true,\n particle_color: true,\n particle_texturemask: true,\n particle_positionw: true,\n};\nconst attributeAsUniform = {\n particle_texturemask: true,\n};\n/**\n * Block used to expose an input value\n */\nexport class InputBlock extends NodeMaterialBlock {\n /**\n * Gets or sets the connection point type (default is float)\n */\n get type() {\n if (this._type === NodeMaterialBlockConnectionPointTypes.AutoDetect) {\n if (this.isUniform && this.value != null) {\n if (!isNaN(this.value)) {\n this._type = NodeMaterialBlockConnectionPointTypes.Float;\n return this._type;\n }\n switch (this.value.getClassName()) {\n case \"Vector2\":\n this._type = NodeMaterialBlockConnectionPointTypes.Vector2;\n return this._type;\n case \"Vector3\":\n this._type = NodeMaterialBlockConnectionPointTypes.Vector3;\n return this._type;\n case \"Vector4\":\n this._type = NodeMaterialBlockConnectionPointTypes.Vector4;\n return this._type;\n case \"Color3\":\n this._type = NodeMaterialBlockConnectionPointTypes.Color3;\n return this._type;\n case \"Color4\":\n this._type = NodeMaterialBlockConnectionPointTypes.Color4;\n return this._type;\n case \"Matrix\":\n this._type = NodeMaterialBlockConnectionPointTypes.Matrix;\n return this._type;\n }\n }\n if (this.isAttribute) {\n switch (this.name) {\n case \"position\":\n case \"normal\":\n case \"particle_positionw\":\n this._type = NodeMaterialBlockConnectionPointTypes.Vector3;\n return this._type;\n case \"uv\":\n case \"uv2\":\n case \"uv3\":\n case \"uv4\":\n case \"uv5\":\n case \"uv6\":\n case \"position2d\":\n case \"particle_uv\":\n this._type = NodeMaterialBlockConnectionPointTypes.Vector2;\n return this._type;\n case \"matricesIndices\":\n case \"matricesWeights\":\n case \"matricesIndicesExtra\":\n case \"matricesWeightsExtra\":\n case \"world0\":\n case \"world1\":\n case \"world2\":\n case \"world3\":\n case \"tangent\":\n this._type = NodeMaterialBlockConnectionPointTypes.Vector4;\n return this._type;\n case \"color\":\n case \"instanceColor\":\n case \"particle_color\":\n case \"particle_texturemask\":\n this._type = NodeMaterialBlockConnectionPointTypes.Color4;\n return this._type;\n }\n }\n if (this.isSystemValue) {\n switch (this._systemValue) {\n case NodeMaterialSystemValues.World:\n case NodeMaterialSystemValues.WorldView:\n case NodeMaterialSystemValues.WorldViewProjection:\n case NodeMaterialSystemValues.View:\n case NodeMaterialSystemValues.ViewProjection:\n case NodeMaterialSystemValues.Projection:\n this._type = NodeMaterialBlockConnectionPointTypes.Matrix;\n return this._type;\n case NodeMaterialSystemValues.CameraPosition:\n this._type = NodeMaterialBlockConnectionPointTypes.Vector3;\n return this._type;\n case NodeMaterialSystemValues.FogColor:\n this._type = NodeMaterialBlockConnectionPointTypes.Color3;\n return this._type;\n case NodeMaterialSystemValues.DeltaTime:\n case NodeMaterialSystemValues.MaterialAlpha:\n this._type = NodeMaterialBlockConnectionPointTypes.Float;\n return this._type;\n case NodeMaterialSystemValues.CameraParameters:\n this._type = NodeMaterialBlockConnectionPointTypes.Vector4;\n return this._type;\n }\n }\n }\n return this._type;\n }\n /**\n * Creates a new InputBlock\n * @param name defines the block name\n * @param target defines the target of that block (Vertex by default)\n * @param type defines the type of the input (can be set to NodeMaterialBlockConnectionPointTypes.AutoDetect)\n */\n constructor(name, target = NodeMaterialBlockTargets.Vertex, type = NodeMaterialBlockConnectionPointTypes.AutoDetect) {\n super(name, target, false, true);\n this._mode = NodeMaterialBlockConnectionPointMode.Undefined;\n this._animationType = AnimatedInputBlockTypes.None;\n /** Gets or set a value used to limit the range of float values */\n this.min = 0;\n /** Gets or set a value used to limit the range of float values */\n this.max = 0;\n /** Gets or set a value indicating that this input can only get 0 and 1 values */\n this.isBoolean = false;\n /** Gets or sets a value used by the Node Material editor to determine how to configure the current value if it is a matrix */\n this.matrixMode = 0;\n /** @internal */\n this._systemValue = null;\n /** Gets or sets a boolean indicating that the value of this input will not change after a build */\n this.isConstant = false;\n /** Gets or sets the group to use to display this block in the Inspector */\n this.groupInInspector = \"\";\n /** Gets an observable raised when the value is changed */\n this.onValueChangedObservable = new Observable();\n /** Gets or sets a boolean indicating if content needs to be converted to gamma space (for color3/4 only) */\n this.convertToGammaSpace = false;\n /** Gets or sets a boolean indicating if content needs to be converted to linear space (for color3/4 only) */\n this.convertToLinearSpace = false;\n this._type = type;\n this.setDefaultValue();\n this.registerOutput(\"output\", type);\n }\n /**\n * Validates if a name is a reserve word.\n * @param newName the new name to be given to the node.\n * @returns false if the name is a reserve word, else true.\n */\n validateBlockName(newName) {\n if (!this.isAttribute) {\n return super.validateBlockName(newName);\n }\n return true;\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n /**\n * Set the source of this connection point to a vertex attribute\n * @param attributeName defines the attribute name (position, uv, normal, etc...). If not specified it will take the connection point name\n * @returns the current connection point\n */\n setAsAttribute(attributeName) {\n this._mode = NodeMaterialBlockConnectionPointMode.Attribute;\n if (attributeName) {\n this.name = attributeName;\n }\n return this;\n }\n /**\n * Set the source of this connection point to a system value\n * @param value define the system value to use (world, view, etc...) or null to switch to manual value\n * @returns the current connection point\n */\n setAsSystemValue(value) {\n this.systemValue = value;\n return this;\n }\n /**\n * Gets or sets the value of that point.\n * Please note that this value will be ignored if valueCallback is defined\n */\n get value() {\n return this._storedValue;\n }\n set value(value) {\n if (this.type === NodeMaterialBlockConnectionPointTypes.Float) {\n if (this.isBoolean) {\n value = value ? 1 : 0;\n }\n else if (this.min !== this.max) {\n value = Math.max(this.min, value);\n value = Math.min(this.max, value);\n }\n }\n this._storedValue = value;\n this._mode = NodeMaterialBlockConnectionPointMode.Uniform;\n this.onValueChangedObservable.notifyObservers(this);\n }\n /**\n * Gets or sets a callback used to get the value of that point.\n * Please note that setting this value will force the connection point to ignore the value property\n */\n get valueCallback() {\n return this._valueCallback;\n }\n set valueCallback(value) {\n this._valueCallback = value;\n this._mode = NodeMaterialBlockConnectionPointMode.Uniform;\n }\n /**\n * Gets or sets the associated variable name in the shader\n */\n get associatedVariableName() {\n return this._associatedVariableName;\n }\n set associatedVariableName(value) {\n this._associatedVariableName = value;\n }\n /** Gets or sets the type of animation applied to the input */\n get animationType() {\n return this._animationType;\n }\n set animationType(value) {\n this._animationType = value;\n }\n /**\n * Gets a boolean indicating that this connection point not defined yet\n */\n get isUndefined() {\n return this._mode === NodeMaterialBlockConnectionPointMode.Undefined;\n }\n /**\n * Gets or sets a boolean indicating that this connection point is coming from an uniform.\n * In this case the connection point name must be the name of the uniform to use.\n * Can only be set on inputs\n */\n get isUniform() {\n return this._mode === NodeMaterialBlockConnectionPointMode.Uniform;\n }\n set isUniform(value) {\n this._mode = value ? NodeMaterialBlockConnectionPointMode.Uniform : NodeMaterialBlockConnectionPointMode.Undefined;\n this.associatedVariableName = \"\";\n }\n /**\n * Gets or sets a boolean indicating that this connection point is coming from an attribute.\n * In this case the connection point name must be the name of the attribute to use\n * Can only be set on inputs\n */\n get isAttribute() {\n return this._mode === NodeMaterialBlockConnectionPointMode.Attribute;\n }\n set isAttribute(value) {\n this._mode = value ? NodeMaterialBlockConnectionPointMode.Attribute : NodeMaterialBlockConnectionPointMode.Undefined;\n this.associatedVariableName = \"\";\n }\n /**\n * Gets or sets a boolean indicating that this connection point is generating a varying variable.\n * Can only be set on exit points\n */\n get isVarying() {\n return this._mode === NodeMaterialBlockConnectionPointMode.Varying;\n }\n set isVarying(value) {\n this._mode = value ? NodeMaterialBlockConnectionPointMode.Varying : NodeMaterialBlockConnectionPointMode.Undefined;\n this.associatedVariableName = \"\";\n }\n /**\n * Gets a boolean indicating that the current connection point is a system value\n */\n get isSystemValue() {\n return this._systemValue != null;\n }\n /**\n * Gets or sets the current well known value or null if not defined as a system value\n */\n get systemValue() {\n return this._systemValue;\n }\n set systemValue(value) {\n this._mode = NodeMaterialBlockConnectionPointMode.Uniform;\n this.associatedVariableName = \"\";\n this._systemValue = value;\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"InputBlock\";\n }\n /**\n * Animate the input if animationType !== None\n * @param scene defines the rendering scene\n */\n animate(scene) {\n switch (this._animationType) {\n case AnimatedInputBlockTypes.Time: {\n if (this.type === NodeMaterialBlockConnectionPointTypes.Float) {\n this.value += scene.getAnimationRatio() * 0.01;\n }\n break;\n }\n case AnimatedInputBlockTypes.RealTime: {\n if (this.type === NodeMaterialBlockConnectionPointTypes.Float) {\n this.value = (PrecisionDate.Now - scene.getEngine().startTime) / 1000;\n }\n break;\n }\n }\n }\n _emitDefine(define) {\n if (define[0] === \"!\") {\n return `#ifndef ${define.substring(1)}\\r\\n`;\n }\n return `#ifdef ${define}\\r\\n`;\n }\n initialize() {\n this.associatedVariableName = \"\";\n }\n /**\n * Set the input block to its default value (based on its type)\n */\n setDefaultValue() {\n switch (this.type) {\n case NodeMaterialBlockConnectionPointTypes.Float:\n this.value = 0;\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector2:\n this.value = Vector2.Zero();\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector3:\n this.value = Vector3.Zero();\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector4:\n this.value = Vector4.Zero();\n break;\n case NodeMaterialBlockConnectionPointTypes.Color3:\n this.value = Color3.White();\n break;\n case NodeMaterialBlockConnectionPointTypes.Color4:\n this.value = new Color4(1, 1, 1, 1);\n break;\n case NodeMaterialBlockConnectionPointTypes.Matrix:\n this.value = Matrix.Identity();\n break;\n }\n }\n _emitConstant(state) {\n switch (this.type) {\n case NodeMaterialBlockConnectionPointTypes.Float:\n return `${state._emitFloat(this.value)}`;\n case NodeMaterialBlockConnectionPointTypes.Vector2:\n return `vec2(${this.value.x}, ${this.value.y})`;\n case NodeMaterialBlockConnectionPointTypes.Vector3:\n return `vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;\n case NodeMaterialBlockConnectionPointTypes.Vector4:\n return `vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;\n case NodeMaterialBlockConnectionPointTypes.Color3:\n TmpColors.Color3[0].set(this.value.r, this.value.g, this.value.b);\n if (this.convertToGammaSpace) {\n TmpColors.Color3[0].toGammaSpaceToRef(TmpColors.Color3[0], state.sharedData.scene.getEngine().useExactSrgbConversions);\n }\n if (this.convertToLinearSpace) {\n TmpColors.Color3[0].toLinearSpaceToRef(TmpColors.Color3[0], state.sharedData.scene.getEngine().useExactSrgbConversions);\n }\n return `vec3(${TmpColors.Color3[0].r}, ${TmpColors.Color3[0].g}, ${TmpColors.Color3[0].b})`;\n case NodeMaterialBlockConnectionPointTypes.Color4:\n TmpColors.Color4[0].set(this.value.r, this.value.g, this.value.b, this.value.a);\n if (this.convertToGammaSpace) {\n TmpColors.Color4[0].toGammaSpaceToRef(TmpColors.Color4[0], state.sharedData.scene.getEngine().useExactSrgbConversions);\n }\n if (this.convertToLinearSpace) {\n TmpColors.Color4[0].toLinearSpaceToRef(TmpColors.Color4[0], state.sharedData.scene.getEngine().useExactSrgbConversions);\n }\n return `vec4(${TmpColors.Color4[0].r}, ${TmpColors.Color4[0].g}, ${TmpColors.Color4[0].b}, ${TmpColors.Color4[0].a})`;\n }\n return \"\";\n }\n /** @internal */\n get _noContextSwitch() {\n return attributeInFragmentOnly[this.name];\n }\n _emit(state, define) {\n var _a;\n // Uniforms\n if (this.isUniform) {\n if (!this.associatedVariableName) {\n this.associatedVariableName = state._getFreeVariableName(\"u_\" + this.name);\n }\n if (this.isConstant) {\n if (state.constants.indexOf(this.associatedVariableName) !== -1) {\n return;\n }\n state.constants.push(this.associatedVariableName);\n state._constantDeclaration += this._declareOutput(this.output, state) + ` = ${this._emitConstant(state)};\\r\\n`;\n return;\n }\n if (state.uniforms.indexOf(this.associatedVariableName) !== -1) {\n return;\n }\n state.uniforms.push(this.associatedVariableName);\n if (define) {\n state._uniformDeclaration += this._emitDefine(define);\n }\n state._uniformDeclaration += `uniform ${state._getGLType(this.type)} ${this.associatedVariableName};\\r\\n`;\n if (define) {\n state._uniformDeclaration += `#endif\\r\\n`;\n }\n // well known\n const hints = state.sharedData.hints;\n if (this._systemValue !== null && this._systemValue !== undefined) {\n switch (this._systemValue) {\n case NodeMaterialSystemValues.WorldView:\n hints.needWorldViewMatrix = true;\n break;\n case NodeMaterialSystemValues.WorldViewProjection:\n hints.needWorldViewProjectionMatrix = true;\n break;\n }\n }\n else {\n if (this._animationType !== AnimatedInputBlockTypes.None) {\n state.sharedData.animatedInputs.push(this);\n }\n }\n return;\n }\n // Attribute\n if (this.isAttribute) {\n this.associatedVariableName = (_a = remapAttributeName[this.name]) !== null && _a !== void 0 ? _a : this.name;\n if (this.target === NodeMaterialBlockTargets.Vertex && state._vertexState) {\n // Attribute for fragment need to be carried over by varyings\n if (attributeInFragmentOnly[this.name]) {\n if (attributeAsUniform[this.name]) {\n state._emitUniformFromString(this.associatedVariableName, state._getGLType(this.type), define);\n }\n else {\n state._emitVaryingFromString(this.associatedVariableName, state._getGLType(this.type), define);\n }\n }\n else {\n this._emit(state._vertexState, define);\n }\n return;\n }\n if (state.attributes.indexOf(this.associatedVariableName) !== -1) {\n return;\n }\n state.attributes.push(this.associatedVariableName);\n if (attributeInFragmentOnly[this.name]) {\n if (attributeAsUniform[this.name]) {\n state._emitUniformFromString(this.associatedVariableName, state._getGLType(this.type), define);\n }\n else {\n state._emitVaryingFromString(this.associatedVariableName, state._getGLType(this.type), define);\n }\n }\n else {\n if (define) {\n state._attributeDeclaration += this._emitDefine(define);\n }\n state._attributeDeclaration += `attribute ${state._getGLType(this.type)} ${this.associatedVariableName};\\r\\n`;\n if (define) {\n state._attributeDeclaration += `#endif\\r\\n`;\n }\n }\n }\n }\n /**\n * @internal\n */\n _transmitWorld(effect, world, worldView, worldViewProjection) {\n if (!this._systemValue) {\n return;\n }\n const variableName = this.associatedVariableName;\n switch (this._systemValue) {\n case NodeMaterialSystemValues.World:\n effect.setMatrix(variableName, world);\n break;\n case NodeMaterialSystemValues.WorldView:\n effect.setMatrix(variableName, worldView);\n break;\n case NodeMaterialSystemValues.WorldViewProjection:\n effect.setMatrix(variableName, worldViewProjection);\n break;\n }\n }\n /**\n * @internal\n */\n _transmit(effect, scene, material) {\n if (this.isAttribute) {\n return;\n }\n const variableName = this.associatedVariableName;\n if (this._systemValue) {\n switch (this._systemValue) {\n case NodeMaterialSystemValues.World:\n case NodeMaterialSystemValues.WorldView:\n case NodeMaterialSystemValues.WorldViewProjection:\n return;\n case NodeMaterialSystemValues.View:\n effect.setMatrix(variableName, scene.getViewMatrix());\n break;\n case NodeMaterialSystemValues.Projection:\n effect.setMatrix(variableName, scene.getProjectionMatrix());\n break;\n case NodeMaterialSystemValues.ViewProjection:\n effect.setMatrix(variableName, scene.getTransformMatrix());\n break;\n case NodeMaterialSystemValues.CameraPosition:\n scene.bindEyePosition(effect, variableName, true);\n break;\n case NodeMaterialSystemValues.FogColor:\n effect.setColor3(variableName, scene.fogColor);\n break;\n case NodeMaterialSystemValues.DeltaTime:\n effect.setFloat(variableName, scene.deltaTime / 1000.0);\n break;\n case NodeMaterialSystemValues.CameraParameters:\n if (scene.activeCamera) {\n effect.setFloat4(variableName, scene.getEngine().hasOriginBottomLeft ? -1 : 1, scene.activeCamera.minZ, scene.activeCamera.maxZ, 1 / scene.activeCamera.maxZ);\n }\n break;\n case NodeMaterialSystemValues.MaterialAlpha:\n effect.setFloat(variableName, material.alpha);\n break;\n }\n return;\n }\n const value = this._valueCallback ? this._valueCallback() : this._storedValue;\n if (value === null) {\n return;\n }\n switch (this.type) {\n case NodeMaterialBlockConnectionPointTypes.Float:\n effect.setFloat(variableName, value);\n break;\n case NodeMaterialBlockConnectionPointTypes.Int:\n effect.setInt(variableName, value);\n break;\n case NodeMaterialBlockConnectionPointTypes.Color3:\n TmpColors.Color3[0].set(this.value.r, this.value.g, this.value.b);\n if (this.convertToGammaSpace) {\n TmpColors.Color3[0].toGammaSpaceToRef(TmpColors.Color3[0], scene.getEngine().useExactSrgbConversions);\n }\n if (this.convertToLinearSpace) {\n TmpColors.Color3[0].toLinearSpaceToRef(TmpColors.Color3[0], scene.getEngine().useExactSrgbConversions);\n }\n effect.setColor3(variableName, TmpColors.Color3[0]);\n break;\n case NodeMaterialBlockConnectionPointTypes.Color4:\n TmpColors.Color4[0].set(this.value.r, this.value.g, this.value.b, this.value.a);\n if (this.convertToGammaSpace) {\n TmpColors.Color4[0].toGammaSpaceToRef(TmpColors.Color4[0], scene.getEngine().useExactSrgbConversions);\n }\n if (this.convertToLinearSpace) {\n TmpColors.Color4[0].toLinearSpaceToRef(TmpColors.Color4[0], scene.getEngine().useExactSrgbConversions);\n }\n effect.setDirectColor4(variableName, TmpColors.Color4[0]);\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector2:\n effect.setVector2(variableName, value);\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector3:\n effect.setVector3(variableName, value);\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector4:\n effect.setVector4(variableName, value);\n break;\n case NodeMaterialBlockConnectionPointTypes.Matrix:\n effect.setMatrix(variableName, value);\n break;\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (this.isUniform || this.isSystemValue) {\n state.sharedData.inputBlocks.push(this);\n }\n this._emit(state);\n }\n _dumpPropertiesCode() {\n const variableName = this._codeVariableName;\n if (this.isAttribute) {\n return super._dumpPropertiesCode() + `${variableName}.setAsAttribute(\"${this.name}\");\\r\\n`;\n }\n if (this.isSystemValue) {\n return super._dumpPropertiesCode() + `${variableName}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${NodeMaterialSystemValues[this._systemValue]});\\r\\n`;\n }\n if (this.isUniform) {\n const codes = [];\n let valueString = \"\";\n switch (this.type) {\n case NodeMaterialBlockConnectionPointTypes.Float:\n valueString = `${this.value}`;\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector2:\n valueString = `new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector3:\n valueString = `new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector4:\n valueString = `new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;\n break;\n case NodeMaterialBlockConnectionPointTypes.Color3:\n valueString = `new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`;\n if (this.convertToGammaSpace) {\n valueString += \".toGammaSpace()\";\n }\n if (this.convertToLinearSpace) {\n valueString += \".toLinearSpace()\";\n }\n break;\n case NodeMaterialBlockConnectionPointTypes.Color4:\n valueString = `new BABYLON.Color4(${this.value.r}, ${this.value.g}, ${this.value.b}, ${this.value.a})`;\n if (this.convertToGammaSpace) {\n valueString += \".toGammaSpace()\";\n }\n if (this.convertToLinearSpace) {\n valueString += \".toLinearSpace()\";\n }\n break;\n case NodeMaterialBlockConnectionPointTypes.Matrix:\n valueString = `BABYLON.Matrix.FromArray([${this.value.m}])`;\n break;\n }\n // Common Property \"Value\"\n codes.push(`${variableName}.value = ${valueString}`);\n // Float-Value-Specific Properties\n if (this.type === NodeMaterialBlockConnectionPointTypes.Float) {\n codes.push(`${variableName}.min = ${this.min}`, `${variableName}.max = ${this.max}`, `${variableName}.isBoolean = ${this.isBoolean}`, `${variableName}.matrixMode = ${this.matrixMode}`, `${variableName}.animationType = BABYLON.AnimatedInputBlockTypes.${AnimatedInputBlockTypes[this.animationType]}`);\n }\n // Common Property \"Type\"\n codes.push(`${variableName}.isConstant = ${this.isConstant}`);\n codes.push(\"\");\n return super._dumpPropertiesCode() + codes.join(\";\\r\\n\");\n }\n return super._dumpPropertiesCode();\n }\n dispose() {\n this.onValueChangedObservable.clear();\n super.dispose();\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.type = this.type;\n serializationObject.mode = this._mode;\n serializationObject.systemValue = this._systemValue;\n serializationObject.animationType = this._animationType;\n serializationObject.min = this.min;\n serializationObject.max = this.max;\n serializationObject.isBoolean = this.isBoolean;\n serializationObject.matrixMode = this.matrixMode;\n serializationObject.isConstant = this.isConstant;\n serializationObject.groupInInspector = this.groupInInspector;\n serializationObject.convertToGammaSpace = this.convertToGammaSpace;\n serializationObject.convertToLinearSpace = this.convertToLinearSpace;\n if (this._storedValue != null && this._mode === NodeMaterialBlockConnectionPointMode.Uniform) {\n if (this._storedValue.asArray) {\n serializationObject.valueType = \"BABYLON.\" + this._storedValue.getClassName();\n serializationObject.value = this._storedValue.asArray();\n }\n else {\n serializationObject.valueType = \"number\";\n serializationObject.value = this._storedValue;\n }\n }\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n this._mode = serializationObject.mode;\n super._deserialize(serializationObject, scene, rootUrl);\n this._type = serializationObject.type;\n this._systemValue = serializationObject.systemValue || serializationObject.wellKnownValue;\n this._animationType = serializationObject.animationType;\n this.min = serializationObject.min || 0;\n this.max = serializationObject.max || 0;\n this.isBoolean = !!serializationObject.isBoolean;\n this.matrixMode = serializationObject.matrixMode || 0;\n this.isConstant = !!serializationObject.isConstant;\n this.groupInInspector = serializationObject.groupInInspector || \"\";\n this.convertToGammaSpace = !!serializationObject.convertToGammaSpace;\n this.convertToLinearSpace = !!serializationObject.convertToLinearSpace;\n // Tangents back compat\n if (serializationObject.name === \"tangent\" &&\n serializationObject.mode === NodeMaterialBlockConnectionPointMode.Attribute &&\n serializationObject.type === NodeMaterialBlockConnectionPointTypes.Vector3) {\n this._type = NodeMaterialBlockConnectionPointTypes.Vector4;\n }\n if (!serializationObject.valueType) {\n return;\n }\n if (serializationObject.valueType === \"number\") {\n this._storedValue = serializationObject.value;\n }\n else {\n const valueType = GetClass(serializationObject.valueType);\n if (valueType) {\n this._storedValue = valueType.FromArray(serializationObject.value);\n }\n }\n }\n}\nRegisterClass(\"BABYLON.InputBlock\", InputBlock);\n//# sourceMappingURL=inputBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { Texture } from \"../../../Textures/texture.js\";\n/**\n * Base block used as input for post process\n */\nexport class CurrentScreenBlock extends NodeMaterialBlock {\n /**\n * Create a new CurrentScreenBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.VertexAndFragment);\n this._samplerName = \"textureSampler\";\n /**\n * Gets or sets a boolean indicating if content needs to be converted to gamma space\n */\n this.convertToGammaSpace = false;\n /**\n * Gets or sets a boolean indicating if content needs to be converted to linear space\n */\n this.convertToLinearSpace = false;\n this._isUnique = false;\n this.registerInput(\"uv\", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.VertexAndFragment);\n this.registerOutput(\"rgba\", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"rgb\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"r\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"g\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"b\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"a\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector2 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);\n this._inputs[0]._prioritizeVertex = false;\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"CurrentScreenBlock\";\n }\n /**\n * Gets the uv input component\n */\n get uv() {\n return this._inputs[0];\n }\n /**\n * Gets the rgba output component\n */\n get rgba() {\n return this._outputs[0];\n }\n /**\n * Gets the rgb output component\n */\n get rgb() {\n return this._outputs[1];\n }\n /**\n * Gets the r output component\n */\n get r() {\n return this._outputs[2];\n }\n /**\n * Gets the g output component\n */\n get g() {\n return this._outputs[3];\n }\n /**\n * Gets the b output component\n */\n get b() {\n return this._outputs[4];\n }\n /**\n * Gets the a output component\n */\n get a() {\n return this._outputs[5];\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"textureSampler\");\n }\n get target() {\n if (!this.uv.isConnected) {\n return NodeMaterialBlockTargets.VertexAndFragment;\n }\n if (this.uv.sourceBlock.isInput) {\n return NodeMaterialBlockTargets.VertexAndFragment;\n }\n return NodeMaterialBlockTargets.Fragment;\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n defines.setValue(this._linearDefineName, this.convertToGammaSpace, true);\n defines.setValue(this._gammaDefineName, this.convertToLinearSpace, true);\n }\n isReady() {\n if (this.texture && !this.texture.isReadyOrNotBlocking()) {\n return false;\n }\n return true;\n }\n _injectVertexCode(state) {\n const uvInput = this.uv;\n if (uvInput.connectedPoint.ownerBlock.isInput) {\n const uvInputOwnerBlock = uvInput.connectedPoint.ownerBlock;\n if (!uvInputOwnerBlock.isAttribute) {\n state._emitUniformFromString(uvInput.associatedVariableName, \"vec2\");\n }\n }\n this._mainUVName = \"vMain\" + uvInput.associatedVariableName;\n state._emitVaryingFromString(this._mainUVName, \"vec2\");\n state.compilationString += `${this._mainUVName} = ${uvInput.associatedVariableName}.xy;\\r\\n`;\n if (!this._outputs.some((o) => o.isConnectedInVertexShader)) {\n return;\n }\n this._writeTextureRead(state, true);\n for (const output of this._outputs) {\n if (output.hasEndpoints) {\n this._writeOutput(state, output, output.name, true);\n }\n }\n }\n _writeTextureRead(state, vertexMode = false) {\n const uvInput = this.uv;\n if (vertexMode) {\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n return;\n }\n state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${uvInput.associatedVariableName});\\r\\n`;\n return;\n }\n if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {\n state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${uvInput.associatedVariableName});\\r\\n`;\n return;\n }\n state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\\r\\n`;\n }\n _writeOutput(state, output, swizzle, vertexMode = false) {\n if (vertexMode) {\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n return;\n }\n state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\\r\\n`;\n return;\n }\n if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {\n state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\\r\\n`;\n return;\n }\n state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\\r\\n`;\n state.compilationString += `#ifdef ${this._linearDefineName}\\r\\n`;\n state.compilationString += `${output.associatedVariableName} = toGammaSpace(${output.associatedVariableName});\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n state.compilationString += `#ifdef ${this._gammaDefineName}\\r\\n`;\n state.compilationString += `${output.associatedVariableName} = toLinearSpace(${output.associatedVariableName});\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n }\n _buildBlock(state) {\n super._buildBlock(state);\n this._tempTextureRead = state._getFreeVariableName(\"tempTextureRead\");\n if (state.sharedData.blockingBlocks.indexOf(this) < 0) {\n state.sharedData.blockingBlocks.push(this);\n }\n if (state.sharedData.textureBlocks.indexOf(this) < 0) {\n state.sharedData.textureBlocks.push(this);\n }\n if (state.sharedData.blocksWithDefines.indexOf(this) < 0) {\n state.sharedData.blocksWithDefines.push(this);\n }\n if (state.target !== NodeMaterialBlockTargets.Fragment) {\n // Vertex\n state._emit2DSampler(this._samplerName);\n this._injectVertexCode(state);\n return;\n }\n // Fragment\n if (!this._outputs.some((o) => o.isConnectedInFragmentShader)) {\n return;\n }\n state._emit2DSampler(this._samplerName);\n this._linearDefineName = state._getFreeDefineName(\"ISLINEAR\");\n this._gammaDefineName = state._getFreeDefineName(\"ISGAMMA\");\n const comments = `//${this.name}`;\n state._emitFunctionFromInclude(\"helperFunctions\", comments);\n this._writeTextureRead(state);\n for (const output of this._outputs) {\n if (output.hasEndpoints) {\n this._writeOutput(state, output, output.name);\n }\n }\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.convertToGammaSpace = this.convertToGammaSpace;\n serializationObject.convertToLinearSpace = this.convertToLinearSpace;\n if (this.texture && !this.texture.isRenderTarget) {\n serializationObject.texture = this.texture.serialize();\n }\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.convertToGammaSpace = serializationObject.convertToGammaSpace;\n this.convertToLinearSpace = !!serializationObject.convertToLinearSpace;\n if (serializationObject.texture) {\n rootUrl = serializationObject.texture.url.indexOf(\"data:\") === 0 ? \"\" : rootUrl;\n this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl);\n }\n }\n}\nRegisterClass(\"BABYLON.CurrentScreenBlock\", CurrentScreenBlock);\n//# sourceMappingURL=currentScreenBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { Texture } from \"../../../Textures/texture.js\";\n/**\n * Base block used for the particle texture\n */\nexport class ParticleTextureBlock extends NodeMaterialBlock {\n /**\n * Create a new ParticleTextureBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this._samplerName = \"diffuseSampler\";\n /**\n * Gets or sets a boolean indicating if content needs to be converted to gamma space\n */\n this.convertToGammaSpace = false;\n /**\n * Gets or sets a boolean indicating if content needs to be converted to linear space\n */\n this.convertToLinearSpace = false;\n this._isUnique = false;\n this.registerInput(\"uv\", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.VertexAndFragment);\n this.registerOutput(\"rgba\", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"rgb\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"r\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"g\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"b\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"a\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector2 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ParticleTextureBlock\";\n }\n /**\n * Gets the uv input component\n */\n get uv() {\n return this._inputs[0];\n }\n /**\n * Gets the rgba output component\n */\n get rgba() {\n return this._outputs[0];\n }\n /**\n * Gets the rgb output component\n */\n get rgb() {\n return this._outputs[1];\n }\n /**\n * Gets the r output component\n */\n get r() {\n return this._outputs[2];\n }\n /**\n * Gets the g output component\n */\n get g() {\n return this._outputs[3];\n }\n /**\n * Gets the b output component\n */\n get b() {\n return this._outputs[4];\n }\n /**\n * Gets the a output component\n */\n get a() {\n return this._outputs[5];\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"diffuseSampler\");\n }\n autoConfigure(material) {\n if (!this.uv.isConnected) {\n let uvInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"particle_uv\");\n if (!uvInput) {\n uvInput = new InputBlock(\"uv\");\n uvInput.setAsAttribute(\"particle_uv\");\n }\n uvInput.output.connectTo(this.uv);\n }\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n defines.setValue(this._linearDefineName, this.convertToGammaSpace, true);\n defines.setValue(this._gammaDefineName, this.convertToLinearSpace, true);\n }\n isReady() {\n if (this.texture && !this.texture.isReadyOrNotBlocking()) {\n return false;\n }\n return true;\n }\n _writeOutput(state, output, swizzle) {\n state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\\r\\n`;\n state.compilationString += `#ifdef ${this._linearDefineName}\\r\\n`;\n state.compilationString += `${output.associatedVariableName} = toGammaSpace(${output.associatedVariableName});\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n state.compilationString += `#ifdef ${this._gammaDefineName}\\r\\n`;\n state.compilationString += `${output.associatedVariableName} = toLinearSpace(${output.associatedVariableName});\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (state.target === NodeMaterialBlockTargets.Vertex) {\n return;\n }\n this._tempTextureRead = state._getFreeVariableName(\"tempTextureRead\");\n state._emit2DSampler(this._samplerName);\n state.sharedData.blockingBlocks.push(this);\n state.sharedData.textureBlocks.push(this);\n state.sharedData.blocksWithDefines.push(this);\n this._linearDefineName = state._getFreeDefineName(\"ISLINEAR\");\n this._gammaDefineName = state._getFreeDefineName(\"ISGAMMA\");\n const comments = `//${this.name}`;\n state._emitFunctionFromInclude(\"helperFunctions\", comments);\n state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this.uv.associatedVariableName});\\r\\n`;\n for (const output of this._outputs) {\n if (output.hasEndpoints) {\n this._writeOutput(state, output, output.name);\n }\n }\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.convertToGammaSpace = this.convertToGammaSpace;\n serializationObject.convertToLinearSpace = this.convertToLinearSpace;\n if (this.texture && !this.texture.isRenderTarget) {\n serializationObject.texture = this.texture.serialize();\n }\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.convertToGammaSpace = serializationObject.convertToGammaSpace;\n this.convertToLinearSpace = !!serializationObject.convertToLinearSpace;\n if (serializationObject.texture) {\n rootUrl = serializationObject.texture.url.indexOf(\"data:\") === 0 ? \"\" : rootUrl;\n this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl);\n }\n }\n}\nRegisterClass(\"BABYLON.ParticleTextureBlock\", ParticleTextureBlock);\n//# sourceMappingURL=particleTextureBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\n/**\n * Block used for the particle ramp gradient section\n */\nexport class ParticleRampGradientBlock extends NodeMaterialBlock {\n /**\n * Create a new ParticleRampGradientBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this._isUnique = true;\n this.registerInput(\"color\", NodeMaterialBlockConnectionPointTypes.Color4, false, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"rampColor\", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Fragment);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ParticleRampGradientBlock\";\n }\n /**\n * Gets the color input component\n */\n get color() {\n return this._inputs[0];\n }\n /**\n * Gets the rampColor output component\n */\n get rampColor() {\n return this._outputs[0];\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"remapRanges\");\n state._excludeVariableName(\"rampSampler\");\n state._excludeVariableName(\"baseColor\");\n state._excludeVariableName(\"alpha\");\n state._excludeVariableName(\"remappedColorIndex\");\n state._excludeVariableName(\"rampColor\");\n state._excludeVariableName(\"finalAlpha\");\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (state.target === NodeMaterialBlockTargets.Vertex) {\n return;\n }\n state._emit2DSampler(\"rampSampler\");\n state._emitVaryingFromString(\"remapRanges\", \"vec4\", \"RAMPGRADIENT\");\n state.compilationString += `\r\n #ifdef RAMPGRADIENT\r\n vec4 baseColor = ${this.color.associatedVariableName};\r\n float alpha = ${this.color.associatedVariableName}.a;\r\n\r\n float remappedColorIndex = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0);\r\n\r\n vec4 rampColor = texture2D(rampSampler, vec2(1.0 - remappedColorIndex, 0.));\r\n baseColor.rgb *= rampColor.rgb;\r\n\r\n // Remapped alpha\r\n float finalAlpha = baseColor.a;\r\n baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0);\r\n\r\n ${this._declareOutput(this.rampColor, state)} = baseColor;\r\n #else\r\n ${this._declareOutput(this.rampColor, state)} = ${this.color.associatedVariableName};\r\n #endif\r\n `;\n return this;\n }\n}\nRegisterClass(\"BABYLON.ParticleRampGradientBlock\", ParticleRampGradientBlock);\n//# sourceMappingURL=particleRampGradientBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\n/**\n * Block used for the particle blend multiply section\n */\nexport class ParticleBlendMultiplyBlock extends NodeMaterialBlock {\n /**\n * Create a new ParticleBlendMultiplyBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this._isUnique = true;\n this.registerInput(\"color\", NodeMaterialBlockConnectionPointTypes.Color4, false, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"alphaTexture\", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"alphaColor\", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"blendColor\", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Fragment);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ParticleBlendMultiplyBlock\";\n }\n /**\n * Gets the color input component\n */\n get color() {\n return this._inputs[0];\n }\n /**\n * Gets the alphaTexture input component\n */\n get alphaTexture() {\n return this._inputs[1];\n }\n /**\n * Gets the alphaColor input component\n */\n get alphaColor() {\n return this._inputs[2];\n }\n /**\n * Gets the blendColor output component\n */\n get blendColor() {\n return this._outputs[0];\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"sourceAlpha\");\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (state.target === NodeMaterialBlockTargets.Vertex) {\n return;\n }\n state.compilationString += `\r\n #ifdef BLENDMULTIPLYMODE\r\n ${this._declareOutput(this.blendColor, state)};\r\n float sourceAlpha = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName};\r\n ${this.blendColor.associatedVariableName}.rgb = ${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha);\r\n ${this.blendColor.associatedVariableName}.a = ${this.color.associatedVariableName}.a;\r\n #else\r\n ${this._declareOutput(this.blendColor, state)} = ${this.color.associatedVariableName};\r\n #endif\r\n `;\n return this;\n }\n}\nRegisterClass(\"BABYLON.ParticleBlendMultiplyBlock\", ParticleBlendMultiplyBlock);\n//# sourceMappingURL=particleBlendMultiplyBlock.js.map","/**\n * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.\n * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)\n */\nexport class EffectFallbacks {\n constructor() {\n this._defines = {};\n this._currentRank = 32;\n this._maxRank = -1;\n this._mesh = null;\n }\n /**\n * Removes the fallback from the bound mesh.\n */\n unBindMesh() {\n this._mesh = null;\n }\n /**\n * Adds a fallback on the specified property.\n * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)\n * @param define The name of the define in the shader\n */\n addFallback(rank, define) {\n if (!this._defines[rank]) {\n if (rank < this._currentRank) {\n this._currentRank = rank;\n }\n if (rank > this._maxRank) {\n this._maxRank = rank;\n }\n this._defines[rank] = new Array();\n }\n this._defines[rank].push(define);\n }\n /**\n * Sets the mesh to use CPU skinning when needing to fallback.\n * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)\n * @param mesh The mesh to use the fallbacks.\n */\n addCPUSkinningFallback(rank, mesh) {\n this._mesh = mesh;\n if (rank < this._currentRank) {\n this._currentRank = rank;\n }\n if (rank > this._maxRank) {\n this._maxRank = rank;\n }\n }\n /**\n * Checks to see if more fallbacks are still available.\n */\n get hasMoreFallbacks() {\n return this._currentRank <= this._maxRank;\n }\n /**\n * Removes the defines that should be removed when falling back.\n * @param currentDefines defines the current define statements for the shader.\n * @param effect defines the current effect we try to compile\n * @returns The resulting defines with defines of the current rank removed.\n */\n reduce(currentDefines, effect) {\n // First we try to switch to CPU skinning\n if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {\n this._mesh.computeBonesUsingShaders = false;\n currentDefines = currentDefines.replace(\"#define NUM_BONE_INFLUENCERS \" + this._mesh.numBoneInfluencers, \"#define NUM_BONE_INFLUENCERS 0\");\n effect._bonesComputationForcedToCPU = true;\n const scene = this._mesh.getScene();\n for (let index = 0; index < scene.meshes.length; index++) {\n const otherMesh = scene.meshes[index];\n if (!otherMesh.material) {\n if (!this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {\n otherMesh.computeBonesUsingShaders = false;\n }\n continue;\n }\n if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {\n continue;\n }\n if (otherMesh.material.getEffect() === effect) {\n otherMesh.computeBonesUsingShaders = false;\n }\n else if (otherMesh.subMeshes) {\n for (const subMesh of otherMesh.subMeshes) {\n const subMeshEffect = subMesh.effect;\n if (subMeshEffect === effect) {\n otherMesh.computeBonesUsingShaders = false;\n break;\n }\n }\n }\n }\n }\n else {\n const currentFallbacks = this._defines[this._currentRank];\n if (currentFallbacks) {\n for (let index = 0; index < currentFallbacks.length; index++) {\n currentDefines = currentDefines.replace(\"#define \" + currentFallbacks[index], \"\");\n }\n }\n this._currentRank++;\n }\n return currentDefines;\n }\n}\n//# sourceMappingURL=effectFallbacks.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"postprocessVertexShader\";\nconst shader = `attribute vec2 position;\runiform vec2 scale;\rvarying vec2 vUV;\rconst vec2 madd=vec2(0.5,0.5);\r#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=(position*madd+madd)*scale;\rgl_Position=vec4(position,0.0,1.0);\r#define CUSTOM_VERTEX_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const postprocessVertexShader = { name, shader };\n//# sourceMappingURL=postprocess.vertex.js.map","import { InternalTextureSource } from \"../Materials/Textures/internalTexture.js\";\n\n/**\n * Wrapper around a render target (either single or multi textures)\n */\nexport class RenderTargetWrapper {\n /**\n * Gets the depth/stencil texture (if created by a createDepthStencilTexture() call)\n */\n get depthStencilTexture() {\n return this._depthStencilTexture;\n }\n /**\n * Indicates if the depth/stencil texture has a stencil aspect\n */\n get depthStencilTextureWithStencil() {\n return this._depthStencilTextureWithStencil;\n }\n /**\n * Defines if the render target wrapper is for a cube texture or if false a 2d texture\n */\n get isCube() {\n return this._isCube;\n }\n /**\n * Defines if the render target wrapper is for a single or multi target render wrapper\n */\n get isMulti() {\n return this._isMulti;\n }\n /**\n * Defines if the render target wrapper is for a single or an array of textures\n */\n get is2DArray() {\n return this.layers > 0;\n }\n /**\n * Gets the size of the render target wrapper (used for cubes, as width=height in this case)\n */\n get size() {\n return this.width;\n }\n /**\n * Gets the width of the render target wrapper\n */\n get width() {\n return this._size.width || this._size;\n }\n /**\n * Gets the height of the render target wrapper\n */\n get height() {\n return this._size.height || this._size;\n }\n /**\n * Gets the number of layers of the render target wrapper (only used if is2DArray is true and wrapper is not a multi render target)\n */\n get layers() {\n return this._size.layers || 0;\n }\n /**\n * Gets the render texture. If this is a multi render target, gets the first texture\n */\n get texture() {\n var _a, _b;\n return (_b = (_a = this._textures) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : null;\n }\n /**\n * Gets the list of render textures. If we are not in a multi render target, the list will be null (use the texture getter instead)\n */\n get textures() {\n return this._textures;\n }\n /**\n * Gets the face indices that correspond to the list of render textures. If we are not in a multi render target, the list will be null\n */\n get faceIndices() {\n return this._faceIndices;\n }\n /**\n * Gets the layer indices that correspond to the list of render textures. If we are not in a multi render target, the list will be null\n */\n get layerIndices() {\n return this._layerIndices;\n }\n /**\n * Gets the sample count of the render target\n */\n get samples() {\n return this._samples;\n }\n /**\n * Sets the sample count of the render target\n * @param value sample count\n * @param initializeBuffers If set to true, the engine will make an initializing call to drawBuffers (only used when isMulti=true).\n * @param force true to force calling the update sample count engine function even if the current sample count is equal to value\n * @returns the sample count that has been set\n */\n setSamples(value, initializeBuffers = true, force = false) {\n if (this.samples === value && !force) {\n return value;\n }\n const result = this._isMulti\n ? this._engine.updateMultipleRenderTargetTextureSampleCount(this, value, initializeBuffers)\n : this._engine.updateRenderTargetTextureSampleCount(this, value);\n this._samples = value;\n return result;\n }\n /**\n * Initializes the render target wrapper\n * @param isMulti true if the wrapper is a multi render target\n * @param isCube true if the wrapper should render to a cube texture\n * @param size size of the render target (width/height/layers)\n * @param engine engine used to create the render target\n */\n constructor(isMulti, isCube, size, engine) {\n this._textures = null;\n this._faceIndices = null;\n this._layerIndices = null;\n /** @internal */\n this._samples = 1;\n /** @internal */\n this._attachments = null;\n /** @internal */\n this._generateStencilBuffer = false;\n /** @internal */\n this._generateDepthBuffer = false;\n /** @internal */\n this._depthStencilTextureWithStencil = false;\n this._isMulti = isMulti;\n this._isCube = isCube;\n this._size = size;\n this._engine = engine;\n this._depthStencilTexture = null;\n }\n /**\n * Sets the render target texture(s)\n * @param textures texture(s) to set\n */\n setTextures(textures) {\n if (Array.isArray(textures)) {\n this._textures = textures;\n }\n else if (textures) {\n this._textures = [textures];\n }\n else {\n this._textures = null;\n }\n }\n /**\n * Set a texture in the textures array\n * @param texture The texture to set\n * @param index The index in the textures array to set\n * @param disposePrevious If this function should dispose the previous texture\n */\n setTexture(texture, index = 0, disposePrevious = true) {\n if (!this._textures) {\n this._textures = [];\n }\n if (this._textures[index] && disposePrevious) {\n this._textures[index].dispose();\n }\n this._textures[index] = texture;\n }\n /**\n * Sets the layer and face indices of every render target texture bound to each color attachment\n * @param layers The layers of each texture to be set\n * @param faces The faces of each texture to be set\n */\n setLayerAndFaceIndices(layers, faces) {\n this._layerIndices = layers;\n this._faceIndices = faces;\n }\n /**\n * Sets the layer and face indices of a texture in the textures array that should be bound to each color attachment\n * @param index The index of the texture in the textures array to modify\n * @param layer The layer of the texture to be set\n * @param face The face of the texture to be set\n */\n setLayerAndFaceIndex(index = 0, layer, face) {\n if (!this._layerIndices) {\n this._layerIndices = [];\n }\n if (!this._faceIndices) {\n this._faceIndices = [];\n }\n if (layer !== undefined && layer >= 0) {\n this._layerIndices[index] = layer;\n }\n if (face !== undefined && face >= 0) {\n this._faceIndices[index] = face;\n }\n }\n /**\n * Creates the depth/stencil texture\n * @param comparisonFunction Comparison function to use for the texture\n * @param bilinearFiltering true if bilinear filtering should be used when sampling the texture\n * @param generateStencil true if the stencil aspect should also be created\n * @param samples sample count to use when creating the texture\n * @param format format of the depth texture\n * @param label defines the label to use for the texture (for debugging purpose only)\n * @returns the depth/stencil created texture\n */\n createDepthStencilTexture(comparisonFunction = 0, bilinearFiltering = true, generateStencil = false, samples = 1, format = 14, label) {\n var _a;\n (_a = this._depthStencilTexture) === null || _a === void 0 ? void 0 : _a.dispose();\n this._depthStencilTextureWithStencil = generateStencil;\n this._depthStencilTexture = this._engine.createDepthStencilTexture(this._size, {\n bilinearFiltering,\n comparisonFunction,\n generateStencil,\n isCube: this._isCube,\n samples,\n depthTextureFormat: format,\n label,\n }, this);\n return this._depthStencilTexture;\n }\n /**\n * Shares the depth buffer of this render target with another render target.\n * @internal\n * @param renderTarget Destination renderTarget\n */\n _shareDepth(renderTarget) {\n if (this._depthStencilTexture) {\n if (renderTarget._depthStencilTexture) {\n renderTarget._depthStencilTexture.dispose();\n }\n renderTarget._depthStencilTexture = this._depthStencilTexture;\n this._depthStencilTexture.incrementReferences();\n }\n }\n /**\n * @internal\n */\n _swapAndDie(target) {\n if (this.texture) {\n this.texture._swapAndDie(target);\n }\n this._textures = null;\n this.dispose(true);\n }\n _cloneRenderTargetWrapper() {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n let rtw = null;\n if (this._isMulti) {\n const textureArray = this.textures;\n if (textureArray && textureArray.length > 0) {\n let generateDepthTexture = false;\n let textureCount = textureArray.length;\n const lastTextureSource = textureArray[textureArray.length - 1]._source;\n if (lastTextureSource === InternalTextureSource.Depth || lastTextureSource === InternalTextureSource.DepthStencil) {\n generateDepthTexture = true;\n textureCount--;\n }\n const samplingModes = [];\n const types = [];\n const formats = [];\n const targetTypes = [];\n const faceIndex = [];\n const layerIndex = [];\n const layerCounts = [];\n const internalTexture2Index = {};\n for (let i = 0; i < textureCount; ++i) {\n const texture = textureArray[i];\n samplingModes.push(texture.samplingMode);\n types.push(texture.type);\n formats.push(texture.format);\n const index = internalTexture2Index[texture.uniqueId];\n if (index !== undefined) {\n targetTypes.push(-1);\n layerCounts.push(0);\n }\n else {\n internalTexture2Index[texture.uniqueId] = i;\n if (texture.is2DArray) {\n targetTypes.push(35866);\n layerCounts.push(texture.depth);\n }\n else if (texture.isCube) {\n targetTypes.push(34067);\n layerCounts.push(0);\n } /*else if (texture.isCubeArray) {\n targetTypes.push(3735928559);\n layerCounts.push(texture.depth);\n }*/\n else if (texture.is3D) {\n targetTypes.push(32879);\n layerCounts.push(texture.depth);\n }\n else {\n targetTypes.push(3553);\n layerCounts.push(0);\n }\n }\n if (this._faceIndices) {\n faceIndex.push((_a = this._faceIndices[i]) !== null && _a !== void 0 ? _a : 0);\n }\n if (this._layerIndices) {\n layerIndex.push((_b = this._layerIndices[i]) !== null && _b !== void 0 ? _b : 0);\n }\n }\n const optionsMRT = {\n samplingModes,\n generateMipMaps: textureArray[0].generateMipMaps,\n generateDepthBuffer: this._generateDepthBuffer,\n generateStencilBuffer: this._generateStencilBuffer,\n generateDepthTexture,\n types,\n formats,\n textureCount,\n targetTypes,\n faceIndex,\n layerIndex,\n layerCounts,\n };\n const size = {\n width: this.width,\n height: this.height,\n };\n rtw = this._engine.createMultipleRenderTarget(size, optionsMRT);\n for (let i = 0; i < textureCount; ++i) {\n if (targetTypes[i] !== -1) {\n continue;\n }\n const index = internalTexture2Index[textureArray[i].uniqueId];\n rtw.setTexture(rtw.textures[index], i);\n }\n }\n }\n else {\n const options = {};\n options.generateDepthBuffer = this._generateDepthBuffer;\n options.generateMipMaps = (_d = (_c = this.texture) === null || _c === void 0 ? void 0 : _c.generateMipMaps) !== null && _d !== void 0 ? _d : false;\n options.generateStencilBuffer = this._generateStencilBuffer;\n options.samplingMode = (_e = this.texture) === null || _e === void 0 ? void 0 : _e.samplingMode;\n options.type = (_f = this.texture) === null || _f === void 0 ? void 0 : _f.type;\n options.format = (_g = this.texture) === null || _g === void 0 ? void 0 : _g.format;\n if (this.isCube) {\n rtw = this._engine.createRenderTargetCubeTexture(this.width, options);\n }\n else {\n const size = {\n width: this.width,\n height: this.height,\n layers: this.is2DArray ? (_h = this.texture) === null || _h === void 0 ? void 0 : _h.depth : undefined,\n };\n rtw = this._engine.createRenderTargetTexture(size, options);\n }\n rtw.texture.isReady = true;\n }\n return rtw;\n }\n _swapRenderTargetWrapper(target) {\n if (this._textures && target._textures) {\n for (let i = 0; i < this._textures.length; ++i) {\n this._textures[i]._swapAndDie(target._textures[i], false);\n target._textures[i].isReady = true;\n }\n }\n if (this._depthStencilTexture && target._depthStencilTexture) {\n this._depthStencilTexture._swapAndDie(target._depthStencilTexture);\n target._depthStencilTexture.isReady = true;\n }\n this._textures = null;\n this._depthStencilTexture = null;\n }\n /** @internal */\n _rebuild() {\n const rtw = this._cloneRenderTargetWrapper();\n if (!rtw) {\n return;\n }\n if (this._depthStencilTexture) {\n const samplingMode = this._depthStencilTexture.samplingMode;\n const bilinear = samplingMode === 2 ||\n samplingMode === 3 ||\n samplingMode === 11;\n rtw.createDepthStencilTexture(this._depthStencilTexture._comparisonFunction, bilinear, this._depthStencilTextureWithStencil, this._depthStencilTexture.samples);\n }\n if (this.samples > 1) {\n rtw.setSamples(this.samples);\n }\n rtw._swapRenderTargetWrapper(this);\n rtw.dispose();\n }\n /**\n * Releases the internal render textures\n */\n releaseTextures() {\n var _a, _b;\n if (this._textures) {\n for (let i = 0; (_b = i < ((_a = this._textures) === null || _a === void 0 ? void 0 : _a.length)) !== null && _b !== void 0 ? _b : 0; ++i) {\n this._textures[i].dispose();\n }\n }\n this._textures = null;\n }\n /**\n * Disposes the whole render target wrapper\n * @param disposeOnlyFramebuffers true if only the frame buffers should be released (used for the WebGL engine). If false, all the textures will also be released\n */\n dispose(disposeOnlyFramebuffers = false) {\n var _a;\n if (!disposeOnlyFramebuffers) {\n (_a = this._depthStencilTexture) === null || _a === void 0 ? void 0 : _a.dispose();\n this._depthStencilTexture = null;\n this.releaseTextures();\n }\n this._engine._releaseRenderTargetWrapper(this);\n }\n}\n//# sourceMappingURL=renderTargetWrapper.js.map","import { RenderTargetWrapper } from \"../renderTargetWrapper.js\";\n/** @internal */\nexport class WebGLRenderTargetWrapper extends RenderTargetWrapper {\n constructor(isMulti, isCube, size, engine, context) {\n super(isMulti, isCube, size, engine);\n /**\n * @internal\n */\n this._framebuffer = null;\n /**\n * @internal\n */\n this._depthStencilBuffer = null;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n /**\n * @internal\n */\n this._MSAAFramebuffer = null;\n // Multiview\n /**\n * @internal\n */\n this._colorTextureArray = null;\n /**\n * @internal\n */\n this._depthStencilTextureArray = null;\n /**\n * @internal\n */\n this._disposeOnlyFramebuffers = false;\n this._context = context;\n }\n _cloneRenderTargetWrapper() {\n let rtw = null;\n if (this._colorTextureArray && this._depthStencilTextureArray) {\n rtw = this._engine.createMultiviewRenderTargetTexture(this.width, this.height);\n rtw.texture.isReady = true;\n }\n else {\n rtw = super._cloneRenderTargetWrapper();\n }\n return rtw;\n }\n _swapRenderTargetWrapper(target) {\n super._swapRenderTargetWrapper(target);\n target._framebuffer = this._framebuffer;\n target._depthStencilBuffer = this._depthStencilBuffer;\n target._MSAAFramebuffer = this._MSAAFramebuffer;\n target._colorTextureArray = this._colorTextureArray;\n target._depthStencilTextureArray = this._depthStencilTextureArray;\n this._framebuffer = this._depthStencilBuffer = this._MSAAFramebuffer = this._colorTextureArray = this._depthStencilTextureArray = null;\n }\n /**\n * Shares the depth buffer of this render target with another render target.\n * @internal\n * @param renderTarget Destination renderTarget\n */\n _shareDepth(renderTarget) {\n super._shareDepth(renderTarget);\n const gl = this._context;\n const depthbuffer = this._depthStencilBuffer;\n const framebuffer = renderTarget._MSAAFramebuffer || renderTarget._framebuffer;\n if (renderTarget._depthStencilBuffer) {\n gl.deleteRenderbuffer(renderTarget._depthStencilBuffer);\n }\n renderTarget._depthStencilBuffer = this._depthStencilBuffer;\n this._engine._bindUnboundFramebuffer(framebuffer);\n gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthbuffer);\n this._engine._bindUnboundFramebuffer(null);\n }\n /**\n * Binds a texture to this render target on a specific attachment\n * @param texture The texture to bind to the framebuffer\n * @param attachmentIndex Index of the attachment\n * @param faceIndexOrLayer The face or layer of the texture to render to in case of cube texture or array texture\n * @param lodLevel defines the lod level to bind to the frame buffer\n */\n _bindTextureRenderTarget(texture, attachmentIndex = 0, faceIndexOrLayer, lodLevel = 0) {\n var _a, _b, _c, _d;\n if (!texture._hardwareTexture) {\n return;\n }\n const framebuffer = this._framebuffer;\n const currentFB = this._engine._currentFramebuffer;\n this._engine._bindUnboundFramebuffer(framebuffer);\n if (this._engine.webGLVersion > 1) {\n const gl = this._context;\n const attachment = gl[\"COLOR_ATTACHMENT\" + attachmentIndex];\n if (texture.is2DArray || texture.is3D) {\n faceIndexOrLayer = (_b = faceIndexOrLayer !== null && faceIndexOrLayer !== void 0 ? faceIndexOrLayer : (_a = this.layerIndices) === null || _a === void 0 ? void 0 : _a[attachmentIndex]) !== null && _b !== void 0 ? _b : 0;\n gl.framebufferTextureLayer(gl.FRAMEBUFFER, attachment, texture._hardwareTexture.underlyingResource, lodLevel, faceIndexOrLayer);\n }\n else if (texture.isCube) {\n // if face index is not specified, try to query it from faceIndices\n // default is face 0\n faceIndexOrLayer = (_d = faceIndexOrLayer !== null && faceIndexOrLayer !== void 0 ? faceIndexOrLayer : (_c = this.faceIndices) === null || _c === void 0 ? void 0 : _c[attachmentIndex]) !== null && _d !== void 0 ? _d : 0;\n gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndexOrLayer, texture._hardwareTexture.underlyingResource, lodLevel);\n }\n else {\n gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._hardwareTexture.underlyingResource, lodLevel);\n }\n }\n else {\n // Default behavior (WebGL)\n const gl = this._context;\n const attachment = gl[\"COLOR_ATTACHMENT\" + attachmentIndex + \"_WEBGL\"];\n const target = faceIndexOrLayer !== undefined ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndexOrLayer : gl.TEXTURE_2D;\n gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, target, texture._hardwareTexture.underlyingResource, lodLevel);\n }\n this._engine._bindUnboundFramebuffer(currentFB);\n }\n /**\n * Set a texture in the textures array\n * @param texture the texture to set\n * @param index the index in the textures array to set\n * @param disposePrevious If this function should dispose the previous texture\n */\n setTexture(texture, index = 0, disposePrevious = true) {\n super.setTexture(texture, index, disposePrevious);\n this._bindTextureRenderTarget(texture, index);\n }\n /**\n * Sets the layer and face indices of every render target texture\n * @param layers The layer of the texture to be set (make negative to not modify)\n * @param faces The face of the texture to be set (make negative to not modify)\n */\n setLayerAndFaceIndices(layers, faces) {\n var _a, _b;\n super.setLayerAndFaceIndices(layers, faces);\n if (!this.textures || !this.layerIndices || !this.faceIndices) {\n return;\n }\n // the length of this._attachments is the right one as it does not count the depth texture, in case we generated it\n const textureCount = (_b = (_a = this._attachments) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : this.textures.length;\n for (let index = 0; index < textureCount; index++) {\n const texture = this.textures[index];\n if (!texture) {\n // The target type was probably -1 at creation time and setTexture has not been called yet for this index\n continue;\n }\n if (texture.is2DArray || texture.is3D) {\n this._bindTextureRenderTarget(texture, index, this.layerIndices[index]);\n }\n else if (texture.isCube) {\n this._bindTextureRenderTarget(texture, index, this.faceIndices[index]);\n }\n else {\n this._bindTextureRenderTarget(texture, index);\n }\n }\n }\n /**\n * Set the face and layer indices of a texture in the textures array\n * @param index The index of the texture in the textures array to modify\n * @param layer The layer of the texture to be set\n * @param face The face of the texture to be set\n */\n setLayerAndFaceIndex(index = 0, layer, face) {\n super.setLayerAndFaceIndex(index, layer, face);\n if (!this.textures || !this.layerIndices || !this.faceIndices) {\n return;\n }\n const texture = this.textures[index];\n if (texture.is2DArray || texture.is3D) {\n this._bindTextureRenderTarget(this.textures[index], index, this.layerIndices[index]);\n }\n else if (texture.isCube) {\n this._bindTextureRenderTarget(this.textures[index], index, this.faceIndices[index]);\n }\n }\n dispose(disposeOnlyFramebuffers = this._disposeOnlyFramebuffers) {\n const gl = this._context;\n if (!disposeOnlyFramebuffers) {\n if (this._colorTextureArray) {\n this._context.deleteTexture(this._colorTextureArray);\n this._colorTextureArray = null;\n }\n if (this._depthStencilTextureArray) {\n this._context.deleteTexture(this._depthStencilTextureArray);\n this._depthStencilTextureArray = null;\n }\n }\n if (this._framebuffer) {\n gl.deleteFramebuffer(this._framebuffer);\n this._framebuffer = null;\n }\n if (this._depthStencilBuffer) {\n gl.deleteRenderbuffer(this._depthStencilBuffer);\n this._depthStencilBuffer = null;\n }\n if (this._MSAAFramebuffer) {\n gl.deleteFramebuffer(this._MSAAFramebuffer);\n this._MSAAFramebuffer = null;\n }\n super.dispose(disposeOnlyFramebuffers);\n }\n}\n//# sourceMappingURL=webGLRenderTargetWrapper.js.map","import { InternalTexture, InternalTextureSource } from \"../../Materials/Textures/internalTexture.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { ThinEngine } from \"../thinEngine.js\";\nimport { WebGLRenderTargetWrapper } from \"../WebGL/webGLRenderTargetWrapper.js\";\n\nThinEngine.prototype._createHardwareRenderTargetWrapper = function (isMulti, isCube, size) {\n const rtWrapper = new WebGLRenderTargetWrapper(isMulti, isCube, size, this, this._gl);\n this._renderTargetWrapperCache.push(rtWrapper);\n return rtWrapper;\n};\nThinEngine.prototype.createRenderTargetTexture = function (size, options) {\n var _a, _b;\n const rtWrapper = this._createHardwareRenderTargetWrapper(false, false, size);\n let generateDepthBuffer = true;\n let generateStencilBuffer = false;\n let noColorAttachment = false;\n let colorAttachment = undefined;\n let samples = 1;\n if (options !== undefined && typeof options === \"object\") {\n generateDepthBuffer = (_a = options.generateDepthBuffer) !== null && _a !== void 0 ? _a : true;\n generateStencilBuffer = !!options.generateStencilBuffer;\n noColorAttachment = !!options.noColorAttachment;\n colorAttachment = options.colorAttachment;\n samples = (_b = options.samples) !== null && _b !== void 0 ? _b : 1;\n }\n const texture = colorAttachment || (noColorAttachment ? null : this._createInternalTexture(size, options, true, InternalTextureSource.RenderTarget));\n const width = size.width || size;\n const height = size.height || size;\n const currentFrameBuffer = this._currentFramebuffer;\n const gl = this._gl;\n // Create the framebuffer\n const framebuffer = gl.createFramebuffer();\n this._bindUnboundFramebuffer(framebuffer);\n rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);\n // No need to rebind on every frame\n if (texture && !texture.is2DArray) {\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._hardwareTexture.underlyingResource, 0);\n }\n this._bindUnboundFramebuffer(currentFrameBuffer);\n rtWrapper._framebuffer = framebuffer;\n rtWrapper._generateDepthBuffer = generateDepthBuffer;\n rtWrapper._generateStencilBuffer = generateStencilBuffer;\n rtWrapper.setTextures(texture);\n this.updateRenderTargetTextureSampleCount(rtWrapper, samples);\n return rtWrapper;\n};\nThinEngine.prototype.createDepthStencilTexture = function (size, options, rtWrapper) {\n if (options.isCube) {\n const width = size.width || size;\n return this._createDepthStencilCubeTexture(width, options, rtWrapper);\n }\n else {\n return this._createDepthStencilTexture(size, options, rtWrapper);\n }\n};\nThinEngine.prototype._createDepthStencilTexture = function (size, options, rtWrapper) {\n const gl = this._gl;\n const layers = size.layers || 0;\n const target = layers !== 0 ? gl.TEXTURE_2D_ARRAY : gl.TEXTURE_2D;\n const internalTexture = new InternalTexture(this, InternalTextureSource.DepthStencil);\n if (!this._caps.depthTextureExtension) {\n Logger.Error(\"Depth texture is not supported by your browser or hardware.\");\n return internalTexture;\n }\n const internalOptions = Object.assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);\n this._bindTextureDirectly(target, internalTexture, true);\n this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.comparisonFunction === 0 ? false : internalOptions.bilinearFiltering, internalOptions.comparisonFunction, internalOptions.samples);\n if (internalOptions.depthTextureFormat !== undefined) {\n if (internalOptions.depthTextureFormat !== 15 &&\n internalOptions.depthTextureFormat !== 16 &&\n internalOptions.depthTextureFormat !== 17 &&\n internalOptions.depthTextureFormat !== 13 &&\n internalOptions.depthTextureFormat !== 14 &&\n internalOptions.depthTextureFormat !== 18) {\n Logger.Error(\"Depth texture format is not supported.\");\n return internalTexture;\n }\n internalTexture.format = internalOptions.depthTextureFormat;\n }\n else {\n internalTexture.format = internalOptions.generateStencil ? 13 : 16;\n }\n const hasStencil = internalTexture.format === 17 ||\n internalTexture.format === 13 ||\n internalTexture.format === 18;\n rtWrapper._depthStencilTexture = internalTexture;\n rtWrapper._depthStencilTextureWithStencil = hasStencil;\n let type = gl.UNSIGNED_INT;\n if (internalTexture.format === 15) {\n type = gl.UNSIGNED_SHORT;\n }\n else if (internalTexture.format === 17 || internalTexture.format === 13) {\n type = gl.UNSIGNED_INT_24_8;\n }\n else if (internalTexture.format === 14) {\n type = gl.FLOAT;\n }\n else if (internalTexture.format === 18) {\n type = gl.FLOAT_32_UNSIGNED_INT_24_8_REV;\n }\n const format = hasStencil ? gl.DEPTH_STENCIL : gl.DEPTH_COMPONENT;\n let internalFormat = format;\n if (this.webGLVersion > 1) {\n if (internalTexture.format === 15) {\n internalFormat = gl.DEPTH_COMPONENT16;\n }\n else if (internalTexture.format === 16) {\n internalFormat = gl.DEPTH_COMPONENT24;\n }\n else if (internalTexture.format === 17 || internalTexture.format === 13) {\n internalFormat = gl.DEPTH24_STENCIL8;\n }\n else if (internalTexture.format === 14) {\n internalFormat = gl.DEPTH_COMPONENT32F;\n }\n else if (internalTexture.format === 18) {\n internalFormat = gl.DEPTH32F_STENCIL8;\n }\n }\n if (internalTexture.is2DArray) {\n gl.texImage3D(target, 0, internalFormat, internalTexture.width, internalTexture.height, layers, 0, format, type, null);\n }\n else {\n gl.texImage2D(target, 0, internalFormat, internalTexture.width, internalTexture.height, 0, format, type, null);\n }\n this._bindTextureDirectly(target, null);\n this._internalTexturesCache.push(internalTexture);\n // Dispose previous depth/stencil render buffers and clear the corresponding attachment.\n // Next time this framebuffer is bound, the new depth/stencil texture will be attached.\n const glRtWrapper = rtWrapper;\n if (glRtWrapper._depthStencilBuffer) {\n const currentFrameBuffer = this._currentFramebuffer;\n this._bindUnboundFramebuffer(glRtWrapper._framebuffer);\n gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, null);\n gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, null);\n gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, null);\n this._bindUnboundFramebuffer(currentFrameBuffer);\n gl.deleteRenderbuffer(glRtWrapper._depthStencilBuffer);\n glRtWrapper._depthStencilBuffer = null;\n }\n return internalTexture;\n};\nThinEngine.prototype.updateRenderTargetTextureSampleCount = function (rtWrapper, samples) {\n if (this.webGLVersion < 2 || !rtWrapper || !rtWrapper.texture) {\n return 1;\n }\n if (rtWrapper.samples === samples) {\n return samples;\n }\n const gl = this._gl;\n samples = Math.min(samples, this.getCaps().maxMSAASamples);\n // Dispose previous render buffers\n if (rtWrapper._depthStencilBuffer) {\n gl.deleteRenderbuffer(rtWrapper._depthStencilBuffer);\n rtWrapper._depthStencilBuffer = null;\n }\n if (rtWrapper._MSAAFramebuffer) {\n gl.deleteFramebuffer(rtWrapper._MSAAFramebuffer);\n rtWrapper._MSAAFramebuffer = null;\n }\n const hardwareTexture = rtWrapper.texture._hardwareTexture;\n hardwareTexture.releaseMSAARenderBuffers();\n if (samples > 1 && typeof gl.renderbufferStorageMultisample === \"function\") {\n const framebuffer = gl.createFramebuffer();\n if (!framebuffer) {\n throw new Error(\"Unable to create multi sampled framebuffer\");\n }\n rtWrapper._MSAAFramebuffer = framebuffer;\n this._bindUnboundFramebuffer(rtWrapper._MSAAFramebuffer);\n const colorRenderbuffer = this._createRenderBuffer(rtWrapper.texture.width, rtWrapper.texture.height, samples, -1 /* not used */, this._getRGBAMultiSampleBufferFormat(rtWrapper.texture.type), gl.COLOR_ATTACHMENT0, false);\n if (!colorRenderbuffer) {\n throw new Error(\"Unable to create multi sampled framebuffer\");\n }\n hardwareTexture.addMSAARenderBuffer(colorRenderbuffer);\n }\n else {\n this._bindUnboundFramebuffer(rtWrapper._framebuffer);\n }\n rtWrapper.texture.samples = samples;\n rtWrapper._samples = samples;\n rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(rtWrapper._generateStencilBuffer, rtWrapper._generateDepthBuffer, rtWrapper.texture.width, rtWrapper.texture.height, samples);\n this._bindUnboundFramebuffer(null);\n return samples;\n};\n//# sourceMappingURL=engine.renderTarget.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { SmartArray } from \"../Misc/smartArray.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Vector2 } from \"../Maths/math.vector.js\";\n\nimport \"../Shaders/postprocess.vertex.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport \"../Engines/Extensions/engine.renderTarget.js\";\nimport { serialize, serializeAsColor4, SerializationHelper } from \"../Misc/decorators.js\";\nimport { GetClass, RegisterClass } from \"../Misc/typeStore.js\";\nimport { DrawWrapper } from \"../Materials/drawWrapper.js\";\nimport { ShaderLanguage } from \"../Materials/shaderLanguage.js\";\n/**\n * PostProcess can be used to apply a shader to a texture after it has been rendered\n * See https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses\n */\nexport class PostProcess {\n /**\n * Registers a shader code processing with a post process name.\n * @param postProcessName name of the post process. Use null for the fallback shader code processing. This is the shader code processing that will be used in case no specific shader code processing has been associated to a post process name\n * @param customShaderCodeProcessing shader code processing to associate to the post process name\n * @returns\n */\n static RegisterShaderCodeProcessing(postProcessName, customShaderCodeProcessing) {\n if (!customShaderCodeProcessing) {\n delete PostProcess._CustomShaderCodeProcessing[postProcessName !== null && postProcessName !== void 0 ? postProcessName : \"\"];\n return;\n }\n PostProcess._CustomShaderCodeProcessing[postProcessName !== null && postProcessName !== void 0 ? postProcessName : \"\"] = customShaderCodeProcessing;\n }\n static _GetShaderCodeProcessing(postProcessName) {\n var _a;\n return (_a = PostProcess._CustomShaderCodeProcessing[postProcessName]) !== null && _a !== void 0 ? _a : PostProcess._CustomShaderCodeProcessing[\"\"];\n }\n /**\n * Number of sample textures (default: 1)\n */\n get samples() {\n return this._samples;\n }\n set samples(n) {\n this._samples = Math.min(n, this._engine.getCaps().maxMSAASamples);\n this._textures.forEach((texture) => {\n texture.setSamples(this._samples);\n });\n }\n /**\n * Returns the fragment url or shader name used in the post process.\n * @returns the fragment url or name in the shader store.\n */\n getEffectName() {\n return this._fragmentUrl;\n }\n /**\n * A function that is added to the onActivateObservable\n */\n set onActivate(callback) {\n if (this._onActivateObserver) {\n this.onActivateObservable.remove(this._onActivateObserver);\n }\n if (callback) {\n this._onActivateObserver = this.onActivateObservable.add(callback);\n }\n }\n /**\n * A function that is added to the onSizeChangedObservable\n */\n set onSizeChanged(callback) {\n if (this._onSizeChangedObserver) {\n this.onSizeChangedObservable.remove(this._onSizeChangedObserver);\n }\n this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);\n }\n /**\n * A function that is added to the onApplyObservable\n */\n set onApply(callback) {\n if (this._onApplyObserver) {\n this.onApplyObservable.remove(this._onApplyObserver);\n }\n this._onApplyObserver = this.onApplyObservable.add(callback);\n }\n /**\n * A function that is added to the onBeforeRenderObservable\n */\n set onBeforeRender(callback) {\n if (this._onBeforeRenderObserver) {\n this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);\n }\n this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);\n }\n /**\n * A function that is added to the onAfterRenderObservable\n */\n set onAfterRender(callback) {\n if (this._onAfterRenderObserver) {\n this.onAfterRenderObservable.remove(this._onAfterRenderObserver);\n }\n this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);\n }\n /**\n * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will\n * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.\n */\n get inputTexture() {\n return this._textures.data[this._currentRenderTextureInd];\n }\n set inputTexture(value) {\n this._forcedOutputTexture = value;\n }\n /**\n * Since inputTexture should always be defined, if we previously manually set `inputTexture`,\n * the only way to unset it is to use this function to restore its internal state\n */\n restoreDefaultInputTexture() {\n if (this._forcedOutputTexture) {\n this._forcedOutputTexture = null;\n this.markTextureDirty();\n }\n }\n /**\n * Gets the camera which post process is applied to.\n * @returns The camera the post process is applied to.\n */\n getCamera() {\n return this._camera;\n }\n /**\n * Gets the texel size of the postprocess.\n * See https://en.wikipedia.org/wiki/Texel_(graphics)\n */\n get texelSize() {\n if (this._shareOutputWithPostProcess) {\n return this._shareOutputWithPostProcess.texelSize;\n }\n if (this._forcedOutputTexture) {\n this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);\n }\n return this._texelSize;\n }\n /**\n * Creates a new instance PostProcess\n * @param name The name of the PostProcess.\n * @param fragmentUrl The url of the fragment shader to be used.\n * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.\n * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.\n * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param defines String of defines that will be set when running the fragment shader. (default: null)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param vertexUrl The url of the vertex shader to be used. (default: \"postprocess\")\n * @param indexParameters The index parameters to be used for babylons include syntax \"#include[0..varyingCount]\". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx\n * @param blockCompilation If the shader should not be compiled immediatly. (default: false)\n * @param textureFormat Format of textures used when performing the post process. (default: TEXTUREFORMAT_RGBA)\n */\n constructor(name, fragmentUrl, parameters, samplers, options, camera, samplingMode = 1, engine, reusable, defines = null, textureType = 0, vertexUrl = \"postprocess\", indexParameters, blockCompilation = false, textureFormat = 5, shaderLanguage = ShaderLanguage.GLSL) {\n /** @internal */\n this._parentContainer = null;\n /**\n * Width of the texture to apply the post process on\n */\n this.width = -1;\n /**\n * Height of the texture to apply the post process on\n */\n this.height = -1;\n /**\n * Gets the node material used to create this postprocess (null if the postprocess was manually created)\n */\n this.nodeMaterialSource = null;\n /**\n * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)\n * @internal\n */\n this._outputTexture = null;\n /**\n * If the buffer needs to be cleared before applying the post process. (default: true)\n * Should be set to false if shader will overwrite all previous pixels.\n */\n this.autoClear = true;\n /**\n * If clearing the buffer should be forced in autoClear mode, even when alpha mode is enabled (default: false).\n * By default, the buffer will only be cleared if alpha mode is disabled (and autoClear is true).\n */\n this.forceAutoClearInAlphaMode = false;\n /**\n * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)\n */\n this.alphaMode = 0;\n /**\n * Animations to be used for the post processing\n */\n this.animations = new Array();\n /**\n * Enable Pixel Perfect mode where texture is not scaled to be power of 2.\n * Can only be used on a single postprocess or on the last one of a chain. (default: false)\n */\n this.enablePixelPerfectMode = false;\n /**\n * Force the postprocess to be applied without taking in account viewport\n */\n this.forceFullscreenViewport = true;\n /**\n * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)\n *\n * | Value | Type | Description |\n * | ----- | ----------------------------------- | ----------- |\n * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](https://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |\n * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](https://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |\n * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](https://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |\n *\n */\n this.scaleMode = 1;\n /**\n * Force textures to be a power of two (default: false)\n */\n this.alwaysForcePOT = false;\n this._samples = 1;\n /**\n * Modify the scale of the post process to be the same as the viewport (default: false)\n */\n this.adaptScaleToCurrentViewport = false;\n this._reusable = false;\n this._renderId = 0;\n /**\n * if externalTextureSamplerBinding is true, the \"apply\" method won't bind the textureSampler texture, it is expected to be done by the \"outside\" (by the onApplyObservable observer most probably).\n * counter-productive in some cases because if the texture bound by \"apply\" is different from the currently texture bound, (the one set by the onApplyObservable observer, for eg) some\n * internal structures (materialContext) will be dirtified, which may impact performances\n */\n this.externalTextureSamplerBinding = false;\n /**\n * Smart array of input and output textures for the post process.\n * @internal\n */\n this._textures = new SmartArray(2);\n /**\n * Smart array of input and output textures for the post process.\n * @internal\n */\n this._textureCache = [];\n /**\n * The index in _textures that corresponds to the output texture.\n * @internal\n */\n this._currentRenderTextureInd = 0;\n this._scaleRatio = new Vector2(1, 1);\n this._texelSize = Vector2.Zero();\n // Events\n /**\n * An event triggered when the postprocess is activated.\n */\n this.onActivateObservable = new Observable();\n /**\n * An event triggered when the postprocess changes its size.\n */\n this.onSizeChangedObservable = new Observable();\n /**\n * An event triggered when the postprocess applies its effect.\n */\n this.onApplyObservable = new Observable();\n /**\n * An event triggered before rendering the postprocess\n */\n this.onBeforeRenderObservable = new Observable();\n /**\n * An event triggered after rendering the postprocess\n */\n this.onAfterRenderObservable = new Observable();\n this.name = name;\n if (camera != null) {\n this._camera = camera;\n this._scene = camera.getScene();\n camera.attachPostProcess(this);\n this._engine = this._scene.getEngine();\n this._scene.postProcesses.push(this);\n this.uniqueId = this._scene.getUniqueId();\n }\n else if (engine) {\n this._engine = engine;\n this._engine.postProcesses.push(this);\n }\n this._options = options;\n this.renderTargetSamplingMode = samplingMode ? samplingMode : 1;\n this._reusable = reusable || false;\n this._textureType = textureType;\n this._textureFormat = textureFormat;\n this._shaderLanguage = shaderLanguage;\n this._samplers = samplers || [];\n this._samplers.push(\"textureSampler\");\n this._fragmentUrl = fragmentUrl;\n this._vertexUrl = vertexUrl;\n this._parameters = parameters || [];\n this._parameters.push(\"scale\");\n this._indexParameters = indexParameters;\n this._drawWrapper = new DrawWrapper(this._engine);\n if (!blockCompilation) {\n this.updateEffect(defines);\n }\n }\n /**\n * Gets a string identifying the name of the class\n * @returns \"PostProcess\" string\n */\n getClassName() {\n return \"PostProcess\";\n }\n /**\n * Gets the engine which this post process belongs to.\n * @returns The engine the post process was enabled with.\n */\n getEngine() {\n return this._engine;\n }\n /**\n * The effect that is created when initializing the post process.\n * @returns The created effect corresponding the the postprocess.\n */\n getEffect() {\n return this._drawWrapper.effect;\n }\n /**\n * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.\n * @param postProcess The post process to share the output with.\n * @returns This post process.\n */\n shareOutputWith(postProcess) {\n this._disposeTextures();\n this._shareOutputWithPostProcess = postProcess;\n return this;\n }\n /**\n * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.\n * This should be called if the post process that shares output with this post process is disabled/disposed.\n */\n useOwnOutput() {\n if (this._textures.length == 0) {\n this._textures = new SmartArray(2);\n }\n this._shareOutputWithPostProcess = null;\n }\n /**\n * Updates the effect with the current post process compile time values and recompiles the shader.\n * @param defines Define statements that should be added at the beginning of the shader. (default: null)\n * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)\n * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)\n * @param indexParameters The index parameters to be used for babylons include syntax \"#include[0..varyingCount]\". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx\n * @param onCompiled Called when the shader has been compiled.\n * @param onError Called if there is an error when compiling a shader.\n * @param vertexUrl The url of the vertex shader to be used (default: the one given at construction time)\n * @param fragmentUrl The url of the fragment shader to be used (default: the one given at construction time)\n */\n updateEffect(defines = null, uniforms = null, samplers = null, indexParameters, onCompiled, onError, vertexUrl, fragmentUrl) {\n var _a, _b;\n const customShaderCodeProcessing = PostProcess._GetShaderCodeProcessing(this.name);\n if (customShaderCodeProcessing === null || customShaderCodeProcessing === void 0 ? void 0 : customShaderCodeProcessing.defineCustomBindings) {\n const newUniforms = (_a = uniforms === null || uniforms === void 0 ? void 0 : uniforms.slice()) !== null && _a !== void 0 ? _a : [];\n newUniforms.push(...this._parameters);\n const newSamplers = (_b = samplers === null || samplers === void 0 ? void 0 : samplers.slice()) !== null && _b !== void 0 ? _b : [];\n newSamplers.push(...this._samplers);\n defines = customShaderCodeProcessing.defineCustomBindings(this.name, defines, newUniforms, newSamplers);\n uniforms = newUniforms;\n samplers = newSamplers;\n }\n this._postProcessDefines = defines;\n this._drawWrapper.effect = this._engine.createEffect({ vertex: vertexUrl !== null && vertexUrl !== void 0 ? vertexUrl : this._vertexUrl, fragment: fragmentUrl !== null && fragmentUrl !== void 0 ? fragmentUrl : this._fragmentUrl }, {\n attributes: [\"position\"],\n uniformsNames: uniforms || this._parameters,\n uniformBuffersNames: [],\n samplers: samplers || this._samplers,\n defines: defines !== null ? defines : \"\",\n fallbacks: null,\n onCompiled: onCompiled !== null && onCompiled !== void 0 ? onCompiled : null,\n onError: onError !== null && onError !== void 0 ? onError : null,\n indexParameters: indexParameters || this._indexParameters,\n processCodeAfterIncludes: (customShaderCodeProcessing === null || customShaderCodeProcessing === void 0 ? void 0 : customShaderCodeProcessing.processCodeAfterIncludes)\n ? (shaderType, code) => customShaderCodeProcessing.processCodeAfterIncludes(this.name, shaderType, code)\n : null,\n processFinalCode: (customShaderCodeProcessing === null || customShaderCodeProcessing === void 0 ? void 0 : customShaderCodeProcessing.processFinalCode)\n ? (shaderType, code) => customShaderCodeProcessing.processFinalCode(this.name, shaderType, code)\n : null,\n shaderLanguage: this._shaderLanguage,\n }, this._engine);\n }\n /**\n * The post process is reusable if it can be used multiple times within one frame.\n * @returns If the post process is reusable\n */\n isReusable() {\n return this._reusable;\n }\n /** invalidate frameBuffer to hint the postprocess to create a depth buffer */\n markTextureDirty() {\n this.width = -1;\n }\n _createRenderTargetTexture(textureSize, textureOptions, channel = 0) {\n for (let i = 0; i < this._textureCache.length; i++) {\n if (this._textureCache[i].texture.width === textureSize.width &&\n this._textureCache[i].texture.height === textureSize.height &&\n this._textureCache[i].postProcessChannel === channel &&\n this._textureCache[i].texture._generateDepthBuffer === textureOptions.generateDepthBuffer &&\n this._textureCache[i].texture.samples === textureOptions.samples) {\n return this._textureCache[i].texture;\n }\n }\n const tex = this._engine.createRenderTargetTexture(textureSize, textureOptions);\n this._textureCache.push({ texture: tex, postProcessChannel: channel, lastUsedRenderId: -1 });\n return tex;\n }\n _flushTextureCache() {\n const currentRenderId = this._renderId;\n for (let i = this._textureCache.length - 1; i >= 0; i--) {\n if (currentRenderId - this._textureCache[i].lastUsedRenderId > 100) {\n let currentlyUsed = false;\n for (let j = 0; j < this._textures.length; j++) {\n if (this._textures.data[j] === this._textureCache[i].texture) {\n currentlyUsed = true;\n break;\n }\n }\n if (!currentlyUsed) {\n this._textureCache[i].texture.dispose();\n this._textureCache.splice(i, 1);\n }\n }\n }\n }\n _resize(width, height, camera, needMipMaps, forceDepthStencil) {\n if (this._textures.length > 0) {\n this._textures.reset();\n }\n this.width = width;\n this.height = height;\n let firstPP = null;\n for (let i = 0; i < camera._postProcesses.length; i++) {\n if (camera._postProcesses[i] !== null) {\n firstPP = camera._postProcesses[i];\n break;\n }\n }\n const textureSize = { width: this.width, height: this.height };\n const textureOptions = {\n generateMipMaps: needMipMaps,\n generateDepthBuffer: forceDepthStencil || firstPP === this,\n generateStencilBuffer: (forceDepthStencil || firstPP === this) && this._engine.isStencilEnable,\n samplingMode: this.renderTargetSamplingMode,\n type: this._textureType,\n format: this._textureFormat,\n samples: this._samples,\n label: \"PostProcessRTT-\" + this.name,\n };\n this._textures.push(this._createRenderTargetTexture(textureSize, textureOptions, 0));\n if (this._reusable) {\n this._textures.push(this._createRenderTargetTexture(textureSize, textureOptions, 1));\n }\n this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);\n this.onSizeChangedObservable.notifyObservers(this);\n }\n /**\n * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.\n * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous.\n * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.\n * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)\n * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)\n * @returns The render target wrapper that was bound to be written to.\n */\n activate(camera, sourceTexture = null, forceDepthStencil) {\n var _a, _b;\n camera = camera || this._camera;\n const scene = camera.getScene();\n const engine = scene.getEngine();\n const maxSize = engine.getCaps().maxTextureSize;\n let requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;\n const requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;\n // If rendering to a webvr camera's left or right eye only half the width should be used to avoid resize when rendered to screen\n const webVRCamera = camera.parent;\n if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {\n requiredWidth /= 2;\n }\n let desiredWidth = this._options.width || requiredWidth;\n let desiredHeight = this._options.height || requiredHeight;\n const needMipMaps = this.renderTargetSamplingMode !== 7 &&\n this.renderTargetSamplingMode !== 1 &&\n this.renderTargetSamplingMode !== 2;\n if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {\n if (this.adaptScaleToCurrentViewport) {\n const currentViewport = engine.currentViewport;\n if (currentViewport) {\n desiredWidth *= currentViewport.width;\n desiredHeight *= currentViewport.height;\n }\n }\n if (needMipMaps || this.alwaysForcePOT) {\n if (!this._options.width) {\n desiredWidth = engine.needPOTTextures ? Engine.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;\n }\n if (!this._options.height) {\n desiredHeight = engine.needPOTTextures ? Engine.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;\n }\n }\n if (this.width !== desiredWidth || this.height !== desiredHeight) {\n this._resize(desiredWidth, desiredHeight, camera, needMipMaps, forceDepthStencil);\n }\n this._textures.forEach((texture) => {\n if (texture.samples !== this.samples) {\n this._engine.updateRenderTargetTextureSampleCount(texture, this.samples);\n }\n });\n this._flushTextureCache();\n this._renderId++;\n }\n let target;\n if (this._shareOutputWithPostProcess) {\n target = this._shareOutputWithPostProcess.inputTexture;\n }\n else if (this._forcedOutputTexture) {\n target = this._forcedOutputTexture;\n this.width = this._forcedOutputTexture.width;\n this.height = this._forcedOutputTexture.height;\n }\n else {\n target = this.inputTexture;\n let cache;\n for (let i = 0; i < this._textureCache.length; i++) {\n if (this._textureCache[i].texture === target) {\n cache = this._textureCache[i];\n break;\n }\n }\n if (cache) {\n cache.lastUsedRenderId = this._renderId;\n }\n }\n // Bind the input of this post process to be used as the output of the previous post process.\n if (this.enablePixelPerfectMode) {\n this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);\n this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);\n }\n else {\n this._scaleRatio.copyFromFloats(1, 1);\n this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);\n }\n (_b = (_a = this._engine)._debugInsertMarker) === null || _b === void 0 ? void 0 : _b.call(_a, `post process ${this.name} input`);\n this.onActivateObservable.notifyObservers(camera);\n // Clear\n if (this.autoClear && (this.alphaMode === 0 || this.forceAutoClearInAlphaMode)) {\n this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);\n }\n if (this._reusable) {\n this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;\n }\n return target;\n }\n /**\n * If the post process is supported.\n */\n get isSupported() {\n return this._drawWrapper.effect.isSupported;\n }\n /**\n * The aspect ratio of the output texture.\n */\n get aspectRatio() {\n if (this._shareOutputWithPostProcess) {\n return this._shareOutputWithPostProcess.aspectRatio;\n }\n if (this._forcedOutputTexture) {\n return this._forcedOutputTexture.width / this._forcedOutputTexture.height;\n }\n return this.width / this.height;\n }\n /**\n * Get a value indicating if the post-process is ready to be used\n * @returns true if the post-process is ready (shader is compiled)\n */\n isReady() {\n var _a, _b;\n return (_b = (_a = this._drawWrapper.effect) === null || _a === void 0 ? void 0 : _a.isReady()) !== null && _b !== void 0 ? _b : false;\n }\n /**\n * Binds all textures and uniforms to the shader, this will be run on every pass.\n * @returns the effect corresponding to this post process. Null if not compiled or not ready.\n */\n apply() {\n var _a, _b, _c;\n // Check\n if (!((_a = this._drawWrapper.effect) === null || _a === void 0 ? void 0 : _a.isReady())) {\n return null;\n }\n // States\n this._engine.enableEffect(this._drawWrapper);\n this._engine.setState(false);\n this._engine.setDepthBuffer(false);\n this._engine.setDepthWrite(false);\n // Alpha\n this._engine.setAlphaMode(this.alphaMode);\n if (this.alphaConstants) {\n this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);\n }\n // Bind the output texture of the preivous post process as the input to this post process.\n let source;\n if (this._shareOutputWithPostProcess) {\n source = this._shareOutputWithPostProcess.inputTexture;\n }\n else if (this._forcedOutputTexture) {\n source = this._forcedOutputTexture;\n }\n else {\n source = this.inputTexture;\n }\n if (!this.externalTextureSamplerBinding) {\n this._drawWrapper.effect._bindTexture(\"textureSampler\", source === null || source === void 0 ? void 0 : source.texture);\n }\n // Parameters\n this._drawWrapper.effect.setVector2(\"scale\", this._scaleRatio);\n this.onApplyObservable.notifyObservers(this._drawWrapper.effect);\n (_c = (_b = PostProcess._GetShaderCodeProcessing(this.name)) === null || _b === void 0 ? void 0 : _b.bindCustomBindings) === null || _c === void 0 ? void 0 : _c.call(_b, this.name, this._drawWrapper.effect);\n return this._drawWrapper.effect;\n }\n _disposeTextures() {\n if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {\n this._disposeTextureCache();\n return;\n }\n this._disposeTextureCache();\n this._textures.dispose();\n }\n _disposeTextureCache() {\n for (let i = this._textureCache.length - 1; i >= 0; i--) {\n this._textureCache[i].texture.dispose();\n }\n this._textureCache.length = 0;\n }\n /**\n * Sets the required values to the prepass renderer.\n * @param prePassRenderer defines the prepass renderer to setup.\n * @returns true if the pre pass is needed.\n */\n setPrePassRenderer(prePassRenderer) {\n if (this._prePassEffectConfiguration) {\n this._prePassEffectConfiguration = prePassRenderer.addEffectConfiguration(this._prePassEffectConfiguration);\n this._prePassEffectConfiguration.enabled = true;\n return true;\n }\n return false;\n }\n /**\n * Disposes the post process.\n * @param camera The camera to dispose the post process on.\n */\n dispose(camera) {\n camera = camera || this._camera;\n this._disposeTextures();\n let index;\n if (this._scene) {\n index = this._scene.postProcesses.indexOf(this);\n if (index !== -1) {\n this._scene.postProcesses.splice(index, 1);\n }\n }\n if (this._parentContainer) {\n const index = this._parentContainer.postProcesses.indexOf(this);\n if (index > -1) {\n this._parentContainer.postProcesses.splice(index, 1);\n }\n this._parentContainer = null;\n }\n index = this._engine.postProcesses.indexOf(this);\n if (index !== -1) {\n this._engine.postProcesses.splice(index, 1);\n }\n if (!camera) {\n return;\n }\n camera.detachPostProcess(this);\n index = camera._postProcesses.indexOf(this);\n if (index === 0 && camera._postProcesses.length > 0) {\n const firstPostProcess = this._camera._getFirstPostProcess();\n if (firstPostProcess) {\n firstPostProcess.markTextureDirty();\n }\n }\n this.onActivateObservable.clear();\n this.onAfterRenderObservable.clear();\n this.onApplyObservable.clear();\n this.onBeforeRenderObservable.clear();\n this.onSizeChangedObservable.clear();\n }\n /**\n * Serializes the post process to a JSON object\n * @returns the JSON object\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this);\n const camera = this.getCamera() || (this._scene && this._scene.activeCamera);\n serializationObject.customType = \"BABYLON.\" + this.getClassName();\n serializationObject.cameraId = camera ? camera.id : null;\n serializationObject.reusable = this._reusable;\n serializationObject.textureType = this._textureType;\n serializationObject.fragmentUrl = this._fragmentUrl;\n serializationObject.parameters = this._parameters;\n serializationObject.samplers = this._samplers;\n serializationObject.options = this._options;\n serializationObject.defines = this._postProcessDefines;\n serializationObject.textureFormat = this._textureFormat;\n serializationObject.vertexUrl = this._vertexUrl;\n serializationObject.indexParameters = this._indexParameters;\n return serializationObject;\n }\n /**\n * Clones this post process\n * @returns a new post process similar to this one\n */\n clone() {\n const serializationObject = this.serialize();\n serializationObject._engine = this._engine;\n serializationObject.cameraId = null;\n const result = PostProcess.Parse(serializationObject, this._scene, \"\");\n if (!result) {\n return null;\n }\n result.onActivateObservable = this.onActivateObservable.clone();\n result.onSizeChangedObservable = this.onSizeChangedObservable.clone();\n result.onApplyObservable = this.onApplyObservable.clone();\n result.onBeforeRenderObservable = this.onBeforeRenderObservable.clone();\n result.onAfterRenderObservable = this.onAfterRenderObservable.clone();\n result._prePassEffectConfiguration = this._prePassEffectConfiguration;\n return result;\n }\n /**\n * Creates a material from parsed material data\n * @param parsedPostProcess defines parsed post process data\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures\n * @returns a new post process\n */\n static Parse(parsedPostProcess, scene, rootUrl) {\n const postProcessType = GetClass(parsedPostProcess.customType);\n if (!postProcessType || !postProcessType._Parse) {\n return null;\n }\n const camera = scene ? scene.getCameraById(parsedPostProcess.cameraId) : null;\n return postProcessType._Parse(parsedPostProcess, camera, scene, rootUrl);\n }\n /**\n * @internal\n */\n static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) {\n return SerializationHelper.Parse(() => {\n return new PostProcess(parsedPostProcess.name, parsedPostProcess.fragmentUrl, parsedPostProcess.parameters, parsedPostProcess.samplers, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, parsedPostProcess._engine, parsedPostProcess.reusable, parsedPostProcess.defines, parsedPostProcess.textureType, parsedPostProcess.vertexUrl, parsedPostProcess.indexParameters, false, parsedPostProcess.textureFormat);\n }, parsedPostProcess, scene, rootUrl);\n }\n}\nPostProcess._CustomShaderCodeProcessing = {};\n__decorate([\n serialize()\n], PostProcess.prototype, \"uniqueId\", void 0);\n__decorate([\n serialize()\n], PostProcess.prototype, \"name\", void 0);\n__decorate([\n serialize()\n], PostProcess.prototype, \"width\", void 0);\n__decorate([\n serialize()\n], PostProcess.prototype, \"height\", void 0);\n__decorate([\n serialize()\n], PostProcess.prototype, \"renderTargetSamplingMode\", void 0);\n__decorate([\n serializeAsColor4()\n], PostProcess.prototype, \"clearColor\", void 0);\n__decorate([\n serialize()\n], PostProcess.prototype, \"autoClear\", void 0);\n__decorate([\n serialize()\n], PostProcess.prototype, \"forceAutoClearInAlphaMode\", void 0);\n__decorate([\n serialize()\n], PostProcess.prototype, \"alphaMode\", void 0);\n__decorate([\n serialize()\n], PostProcess.prototype, \"alphaConstants\", void 0);\n__decorate([\n serialize()\n], PostProcess.prototype, \"enablePixelPerfectMode\", void 0);\n__decorate([\n serialize()\n], PostProcess.prototype, \"forceFullscreenViewport\", void 0);\n__decorate([\n serialize()\n], PostProcess.prototype, \"scaleMode\", void 0);\n__decorate([\n serialize()\n], PostProcess.prototype, \"alwaysForcePOT\", void 0);\n__decorate([\n serialize(\"samples\")\n], PostProcess.prototype, \"_samples\", void 0);\n__decorate([\n serialize()\n], PostProcess.prototype, \"adaptScaleToCurrentViewport\", void 0);\nRegisterClass(\"BABYLON.PostProcess\", PostProcess);\n//# sourceMappingURL=postProcess.js.map","/**\n * Enum used to define the material modes\n */\nexport var NodeMaterialModes;\n(function (NodeMaterialModes) {\n /** Regular material */\n NodeMaterialModes[NodeMaterialModes[\"Material\"] = 0] = \"Material\";\n /** For post process */\n NodeMaterialModes[NodeMaterialModes[\"PostProcess\"] = 1] = \"PostProcess\";\n /** For particle system */\n NodeMaterialModes[NodeMaterialModes[\"Particle\"] = 2] = \"Particle\";\n /** For procedural texture */\n NodeMaterialModes[NodeMaterialModes[\"ProceduralTexture\"] = 3] = \"ProceduralTexture\";\n})(NodeMaterialModes || (NodeMaterialModes = {}));\n//# sourceMappingURL=nodeMaterialModes.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to create a Vector2/3/4 out of individual inputs (one for each component)\n */\nexport class VectorMergerBlock extends NodeMaterialBlock {\n /**\n * Create a new VectorMergerBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n /**\n * Gets or sets the swizzle for x (meaning which component to affect to the output.x)\n */\n this.xSwizzle = \"x\";\n /**\n * Gets or sets the swizzle for y (meaning which component to affect to the output.y)\n */\n this.ySwizzle = \"y\";\n /**\n * Gets or sets the swizzle for z (meaning which component to affect to the output.z)\n */\n this.zSwizzle = \"z\";\n /**\n * Gets or sets the swizzle for w (meaning which component to affect to the output.w)\n */\n this.wSwizzle = \"w\";\n this.registerInput(\"xyzw \", NodeMaterialBlockConnectionPointTypes.Vector4, true);\n this.registerInput(\"xyz \", NodeMaterialBlockConnectionPointTypes.Vector3, true);\n this.registerInput(\"xy \", NodeMaterialBlockConnectionPointTypes.Vector2, true);\n this.registerInput(\"zw \", NodeMaterialBlockConnectionPointTypes.Vector2, true);\n this.registerInput(\"x\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"y\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"z\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"w\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerOutput(\"xyzw\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerOutput(\"xyz\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerOutput(\"xy\", NodeMaterialBlockConnectionPointTypes.Vector2);\n this.registerOutput(\"zw\", NodeMaterialBlockConnectionPointTypes.Vector2);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"VectorMergerBlock\";\n }\n /**\n * Gets the xyzw component (input)\n */\n get xyzwIn() {\n return this._inputs[0];\n }\n /**\n * Gets the xyz component (input)\n */\n get xyzIn() {\n return this._inputs[1];\n }\n /**\n * Gets the xy component (input)\n */\n get xyIn() {\n return this._inputs[2];\n }\n /**\n * Gets the zw component (input)\n */\n get zwIn() {\n return this._inputs[3];\n }\n /**\n * Gets the x component (input)\n */\n get x() {\n return this._inputs[4];\n }\n /**\n * Gets the y component (input)\n */\n get y() {\n return this._inputs[5];\n }\n /**\n * Gets the z component (input)\n */\n get z() {\n return this._inputs[6];\n }\n /**\n * Gets the w component (input)\n */\n get w() {\n return this._inputs[7];\n }\n /**\n * Gets the xyzw component (output)\n */\n get xyzw() {\n return this._outputs[0];\n }\n /**\n * Gets the xyz component (output)\n */\n get xyzOut() {\n return this._outputs[1];\n }\n /**\n * Gets the xy component (output)\n */\n get xyOut() {\n return this._outputs[2];\n }\n /**\n * Gets the zw component (output)\n */\n get zwOut() {\n return this._outputs[3];\n }\n /**\n * Gets the xy component (output)\n * @deprecated Please use xyOut instead.\n */\n get xy() {\n return this.xyOut;\n }\n /**\n * Gets the xyz component (output)\n * @deprecated Please use xyzOut instead.\n */\n get xyz() {\n return this.xyzOut;\n }\n _inputRename(name) {\n if (name === \"xyzw \") {\n return \"xyzwIn\";\n }\n if (name === \"xyz \") {\n return \"xyzIn\";\n }\n if (name === \"xy \") {\n return \"xyIn\";\n }\n if (name === \"zw \") {\n return \"zwIn\";\n }\n return name;\n }\n _buildSwizzle(len) {\n const swizzle = this.xSwizzle + this.ySwizzle + this.zSwizzle + this.wSwizzle;\n return \".\" + swizzle.substr(0, len);\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const xInput = this.x;\n const yInput = this.y;\n const zInput = this.z;\n const wInput = this.w;\n const xyInput = this.xyIn;\n const zwInput = this.zwIn;\n const xyzInput = this.xyzIn;\n const xyzwInput = this.xyzwIn;\n const v4Output = this._outputs[0];\n const v3Output = this._outputs[1];\n const v2Output = this._outputs[2];\n const v2CompOutput = this._outputs[3];\n if (xyzwInput.isConnected) {\n if (v4Output.hasEndpoints) {\n state.compilationString += this._declareOutput(v4Output, state) + ` = ${xyzwInput.associatedVariableName}${this._buildSwizzle(4)};\\r\\n`;\n }\n if (v3Output.hasEndpoints) {\n state.compilationString += this._declareOutput(v3Output, state) + ` = ${xyzwInput.associatedVariableName}${this._buildSwizzle(3)};\\r\\n`;\n }\n if (v2Output.hasEndpoints) {\n state.compilationString += this._declareOutput(v2Output, state) + ` = ${xyzwInput.associatedVariableName}${this._buildSwizzle(2)};\\r\\n`;\n }\n }\n else if (xyzInput.isConnected) {\n if (v4Output.hasEndpoints) {\n state.compilationString +=\n this._declareOutput(v4Output, state) +\n ` = vec4(${xyzInput.associatedVariableName}, ${wInput.isConnected ? this._writeVariable(wInput) : \"0.0\"})${this._buildSwizzle(4)};\\r\\n`;\n }\n if (v3Output.hasEndpoints) {\n state.compilationString += this._declareOutput(v3Output, state) + ` = ${xyzInput.associatedVariableName}${this._buildSwizzle(3)};\\r\\n`;\n }\n if (v2Output.hasEndpoints) {\n state.compilationString += this._declareOutput(v2Output, state) + ` = ${xyzInput.associatedVariableName}${this._buildSwizzle(2)};\\r\\n`;\n }\n }\n else if (xyInput.isConnected) {\n if (v4Output.hasEndpoints) {\n if (zwInput.isConnected) {\n state.compilationString +=\n this._declareOutput(v4Output, state) + ` = vec4(${xyInput.associatedVariableName}, ${zwInput.associatedVariableName})${this._buildSwizzle(4)};\\r\\n`;\n }\n else {\n state.compilationString +=\n this._declareOutput(v4Output, state) +\n ` = vec4(${xyInput.associatedVariableName}, ${zInput.isConnected ? this._writeVariable(zInput) : \"0.0\"}, ${wInput.isConnected ? this._writeVariable(wInput) : \"0.0\"})${this._buildSwizzle(4)};\\r\\n`;\n }\n }\n if (v3Output.hasEndpoints) {\n state.compilationString +=\n this._declareOutput(v3Output, state) +\n ` = vec3(${xyInput.associatedVariableName}, ${zInput.isConnected ? this._writeVariable(zInput) : \"0.0\"})${this._buildSwizzle(3)};\\r\\n`;\n }\n if (v2Output.hasEndpoints) {\n state.compilationString += this._declareOutput(v2Output, state) + ` = ${xyInput.associatedVariableName}${this._buildSwizzle(2)};\\r\\n`;\n }\n if (v2CompOutput.hasEndpoints) {\n if (zwInput.isConnected) {\n state.compilationString += this._declareOutput(v2CompOutput, state) + ` = ${zwInput.associatedVariableName}${this._buildSwizzle(2)};\\r\\n`;\n }\n else {\n state.compilationString +=\n this._declareOutput(v2CompOutput, state) +\n ` = vec2(${zInput.isConnected ? this._writeVariable(zInput) : \"0.0\"}, ${wInput.isConnected ? this._writeVariable(wInput) : \"0.0\"})${this._buildSwizzle(2)};\\r\\n`;\n }\n }\n }\n else {\n if (v4Output.hasEndpoints) {\n if (zwInput.isConnected) {\n state.compilationString +=\n this._declareOutput(v4Output, state) +\n ` = vec4(${xInput.isConnected ? this._writeVariable(xInput) : \"0.0\"}, ${yInput.isConnected ? this._writeVariable(yInput) : \"0.0\"}, ${zwInput.associatedVariableName})${this._buildSwizzle(4)};\\r\\n`;\n }\n else {\n state.compilationString +=\n this._declareOutput(v4Output, state) +\n ` = vec4(${xInput.isConnected ? this._writeVariable(xInput) : \"0.0\"}, ${yInput.isConnected ? this._writeVariable(yInput) : \"0.0\"}, ${zInput.isConnected ? this._writeVariable(zInput) : \"0.0\"}, ${wInput.isConnected ? this._writeVariable(wInput) : \"0.0\"})${this._buildSwizzle(4)};\\r\\n`;\n }\n }\n if (v3Output.hasEndpoints) {\n state.compilationString +=\n this._declareOutput(v3Output, state) +\n ` = vec3(${xInput.isConnected ? this._writeVariable(xInput) : \"0.0\"}, ${yInput.isConnected ? this._writeVariable(yInput) : \"0.0\"}, ${zInput.isConnected ? this._writeVariable(zInput) : \"0.0\"})${this._buildSwizzle(3)};\\r\\n`;\n }\n if (v2Output.hasEndpoints) {\n state.compilationString +=\n this._declareOutput(v2Output, state) +\n ` = vec2(${xInput.isConnected ? this._writeVariable(xInput) : \"0.0\"}, ${yInput.isConnected ? this._writeVariable(yInput) : \"0.0\"})${this._buildSwizzle(2)};\\r\\n`;\n }\n if (v2CompOutput.hasEndpoints) {\n if (zwInput.isConnected) {\n state.compilationString += this._declareOutput(v2CompOutput, state) + ` = ${zwInput.associatedVariableName}${this._buildSwizzle(2)};\\r\\n`;\n }\n else {\n state.compilationString +=\n this._declareOutput(v2CompOutput, state) +\n ` = vec2(${zInput.isConnected ? this._writeVariable(zInput) : \"0.0\"}, ${wInput.isConnected ? this._writeVariable(wInput) : \"0.0\"})${this._buildSwizzle(2)};\\r\\n`;\n }\n }\n }\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.xSwizzle = this.xSwizzle;\n serializationObject.ySwizzle = this.ySwizzle;\n serializationObject.zSwizzle = this.zSwizzle;\n serializationObject.wSwizzle = this.wSwizzle;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n var _a, _b, _c, _d;\n super._deserialize(serializationObject, scene, rootUrl);\n this.xSwizzle = (_a = serializationObject.xSwizzle) !== null && _a !== void 0 ? _a : \"x\";\n this.ySwizzle = (_b = serializationObject.ySwizzle) !== null && _b !== void 0 ? _b : \"y\";\n this.zSwizzle = (_c = serializationObject.zSwizzle) !== null && _c !== void 0 ? _c : \"z\";\n this.wSwizzle = (_d = serializationObject.wSwizzle) !== null && _d !== void 0 ? _d : \"w\";\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n codeString += `${this._codeVariableName}.xSwizzle = \"${this.xSwizzle}\";\\r\\n`;\n codeString += `${this._codeVariableName}.ySwizzle = \"${this.ySwizzle}\";\\r\\n`;\n codeString += `${this._codeVariableName}.zSwizzle = \"${this.zSwizzle}\";\\r\\n`;\n codeString += `${this._codeVariableName}.wSwizzle = \"${this.wSwizzle}\";\\r\\n`;\n return codeString;\n }\n}\nRegisterClass(\"BABYLON.VectorMergerBlock\", VectorMergerBlock);\n//# sourceMappingURL=vectorMergerBlock.js.map","import { __decorate } from \"../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { Vector2 } from \"../../../Maths/math.vector.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../nodeMaterialDecorator.js\";\n/**\n * Block used to remap a float from a range to a new one\n */\nexport class RemapBlock extends NodeMaterialBlock {\n /**\n * Creates a new RemapBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n /**\n * Gets or sets the source range\n */\n this.sourceRange = new Vector2(-1, 1);\n /**\n * Gets or sets the target range\n */\n this.targetRange = new Vector2(0, 1);\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"sourceMin\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"sourceMax\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"targetMin\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"targetMax\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"RemapBlock\";\n }\n /**\n * Gets the input component\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the source min input component\n */\n get sourceMin() {\n return this._inputs[1];\n }\n /**\n * Gets the source max input component\n */\n get sourceMax() {\n return this._inputs[2];\n }\n /**\n * Gets the target min input component\n */\n get targetMin() {\n return this._inputs[3];\n }\n /**\n * Gets the target max input component\n */\n get targetMax() {\n return this._inputs[4];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n const sourceMin = this.sourceMin.isConnected ? this.sourceMin.associatedVariableName : this._writeFloat(this.sourceRange.x);\n const sourceMax = this.sourceMax.isConnected ? this.sourceMax.associatedVariableName : this._writeFloat(this.sourceRange.y);\n const targetMin = this.targetMin.isConnected ? this.targetMin.associatedVariableName : this._writeFloat(this.targetRange.x);\n const targetMax = this.targetMax.isConnected ? this.targetMax.associatedVariableName : this._writeFloat(this.targetRange.y);\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = ${targetMin} + (${this._inputs[0].associatedVariableName} - ${sourceMin}) * (${targetMax} - ${targetMin}) / (${sourceMax} - ${sourceMin});\\r\\n`;\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y});\\r\\n`;\n codeString += `${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y});\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.sourceRange = this.sourceRange.asArray();\n serializationObject.targetRange = this.targetRange.asArray();\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.sourceRange = Vector2.FromArray(serializationObject.sourceRange);\n this.targetRange = Vector2.FromArray(serializationObject.targetRange);\n }\n}\n__decorate([\n editableInPropertyPage(\"From\", PropertyTypeForEdition.Vector2)\n], RemapBlock.prototype, \"sourceRange\", void 0);\n__decorate([\n editableInPropertyPage(\"To\", PropertyTypeForEdition.Vector2)\n], RemapBlock.prototype, \"targetRange\", void 0);\nRegisterClass(\"BABYLON.RemapBlock\", RemapBlock);\n//# sourceMappingURL=remapBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to multiply 2 values\n */\nexport class MultiplyBlock extends NodeMaterialBlock {\n /**\n * Creates a new MultiplyBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"left\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"right\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._linkConnectionTypes(0, 1);\n this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"MultiplyBlock\";\n }\n /**\n * Gets the left operand input component\n */\n get left() {\n return this._inputs[0];\n }\n /**\n * Gets the right operand input component\n */\n get right() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = ${this.left.associatedVariableName} * ${this.right.associatedVariableName};\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.MultiplyBlock\", MultiplyBlock);\n//# sourceMappingURL=multiplyBlock.js.map","import { DeepCopier } from \"../../Misc/deepCopier.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Scalar } from \"../../Maths/math.scalar.js\";\n/**\n * Particle emitter emitting particles from the inside of a box.\n * It emits the particles randomly between 2 given directions.\n */\nexport class BoxParticleEmitter {\n /**\n * Creates a new instance BoxParticleEmitter\n */\n constructor() {\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n */\n this.direction1 = new Vector3(0, 1.0, 0);\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n */\n this.direction2 = new Vector3(0, 1.0, 0);\n /**\n * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.\n */\n this.minEmitBox = new Vector3(-0.5, -0.5, -0.5);\n /**\n * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.\n */\n this.maxEmitBox = new Vector3(0.5, 0.5, 0.5);\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n * @param isLocal defines if the direction should be set in local space\n */\n startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) {\n const randX = Scalar.RandomRange(this.direction1.x, this.direction2.x);\n const randY = Scalar.RandomRange(this.direction1.y, this.direction2.y);\n const randZ = Scalar.RandomRange(this.direction1.z, this.direction2.z);\n if (isLocal) {\n directionToUpdate.x = randX;\n directionToUpdate.y = randY;\n directionToUpdate.z = randZ;\n return;\n }\n Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);\n }\n /**\n * Called by the particle System when the position is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param positionToUpdate is the position vector to update with the result\n * @param particle is the particle we are computed the position for\n * @param isLocal defines if the position should be set in local space\n */\n startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) {\n const randX = Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);\n const randY = Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);\n const randZ = Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);\n if (isLocal) {\n positionToUpdate.x = randX;\n positionToUpdate.y = randY;\n positionToUpdate.z = randZ;\n return;\n }\n Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);\n }\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n clone() {\n const newOne = new BoxParticleEmitter();\n DeepCopier.DeepCopy(this, newOne);\n return newOne;\n }\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param uboOrEffect defines the update shader\n */\n applyToShader(uboOrEffect) {\n uboOrEffect.setVector3(\"direction1\", this.direction1);\n uboOrEffect.setVector3(\"direction2\", this.direction2);\n uboOrEffect.setVector3(\"minEmitBox\", this.minEmitBox);\n uboOrEffect.setVector3(\"maxEmitBox\", this.maxEmitBox);\n }\n /**\n * Creates the structure of the ubo for this particle emitter\n * @param ubo ubo to create the structure for\n */\n buildUniformLayout(ubo) {\n ubo.addUniform(\"direction1\", 3);\n ubo.addUniform(\"direction2\", 3);\n ubo.addUniform(\"minEmitBox\", 3);\n ubo.addUniform(\"maxEmitBox\", 3);\n }\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containing the defines string\n */\n getEffectDefines() {\n return \"#define BOXEMITTER\";\n }\n /**\n * Returns the string \"BoxParticleEmitter\"\n * @returns a string containing the class name\n */\n getClassName() {\n return \"BoxParticleEmitter\";\n }\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n serialize() {\n const serializationObject = {};\n serializationObject.type = this.getClassName();\n serializationObject.direction1 = this.direction1.asArray();\n serializationObject.direction2 = this.direction2.asArray();\n serializationObject.minEmitBox = this.minEmitBox.asArray();\n serializationObject.maxEmitBox = this.maxEmitBox.asArray();\n return serializationObject;\n }\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n parse(serializationObject) {\n Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);\n Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);\n Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);\n Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);\n }\n}\n//# sourceMappingURL=boxParticleEmitter.js.map","import { DeepCopier } from \"../../Misc/deepCopier.js\";\nimport { Vector3, TmpVectors } from \"../../Maths/math.vector.js\";\nimport { Scalar } from \"../../Maths/math.scalar.js\";\n/**\n * Particle emitter emitting particles from the inside of a cone.\n * It emits the particles alongside the cone volume from the base to the particle.\n * The emission direction might be randomized.\n */\nexport class ConeParticleEmitter {\n /**\n * Gets or sets the radius of the emission cone\n */\n get radius() {\n return this._radius;\n }\n set radius(value) {\n this._radius = value;\n this._buildHeight();\n }\n /**\n * Gets or sets the angle of the emission cone\n */\n get angle() {\n return this._angle;\n }\n set angle(value) {\n this._angle = value;\n this._buildHeight();\n }\n _buildHeight() {\n if (this._angle !== 0) {\n this._height = this._radius / Math.tan(this._angle / 2);\n }\n else {\n this._height = 1;\n }\n }\n /**\n * Creates a new instance ConeParticleEmitter\n * @param radius the radius of the emission cone (1 by default)\n * @param angle the cone base angle (PI by default)\n * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)\n */\n constructor(radius = 1, angle = Math.PI, \n /** defines how much to randomize the particle direction [0-1] (default is 0) */\n directionRandomizer = 0) {\n this.directionRandomizer = directionRandomizer;\n /**\n * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)\n */\n this.radiusRange = 1;\n /**\n * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)\n */\n this.heightRange = 1;\n /**\n * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)\n */\n this.emitFromSpawnPointOnly = false;\n this.angle = angle;\n this.radius = radius;\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n * @param isLocal defines if the direction should be set in local space\n */\n startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) {\n if (isLocal) {\n TmpVectors.Vector3[0].copyFrom(particle._localPosition).normalize();\n }\n else {\n particle.position.subtractToRef(worldMatrix.getTranslation(), TmpVectors.Vector3[0]).normalize();\n }\n const randX = Scalar.RandomRange(0, this.directionRandomizer);\n const randY = Scalar.RandomRange(0, this.directionRandomizer);\n const randZ = Scalar.RandomRange(0, this.directionRandomizer);\n directionToUpdate.x = TmpVectors.Vector3[0].x + randX;\n directionToUpdate.y = TmpVectors.Vector3[0].y + randY;\n directionToUpdate.z = TmpVectors.Vector3[0].z + randZ;\n directionToUpdate.normalize();\n }\n /**\n * Called by the particle System when the position is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param positionToUpdate is the position vector to update with the result\n * @param particle is the particle we are computed the position for\n * @param isLocal defines if the position should be set in local space\n */\n startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) {\n const s = Scalar.RandomRange(0, Math.PI * 2);\n let h;\n if (!this.emitFromSpawnPointOnly) {\n h = Scalar.RandomRange(0, this.heightRange);\n // Better distribution in a cone at normal angles.\n h = 1 - h * h;\n }\n else {\n h = 0.0001;\n }\n let radius = this._radius - Scalar.RandomRange(0, this._radius * this.radiusRange);\n radius = radius * h;\n const randX = radius * Math.sin(s);\n const randZ = radius * Math.cos(s);\n const randY = h * this._height;\n if (isLocal) {\n positionToUpdate.x = randX;\n positionToUpdate.y = randY;\n positionToUpdate.z = randZ;\n return;\n }\n Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);\n }\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n clone() {\n const newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);\n DeepCopier.DeepCopy(this, newOne);\n return newOne;\n }\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param uboOrEffect defines the update shader\n */\n applyToShader(uboOrEffect) {\n uboOrEffect.setFloat2(\"radius\", this._radius, this.radiusRange);\n uboOrEffect.setFloat(\"coneAngle\", this._angle);\n uboOrEffect.setFloat2(\"height\", this._height, this.heightRange);\n uboOrEffect.setFloat(\"directionRandomizer\", this.directionRandomizer);\n }\n /**\n * Creates the structure of the ubo for this particle emitter\n * @param ubo ubo to create the structure for\n */\n buildUniformLayout(ubo) {\n ubo.addUniform(\"radius\", 2);\n ubo.addUniform(\"coneAngle\", 1);\n ubo.addUniform(\"height\", 2);\n ubo.addUniform(\"directionRandomizer\", 1);\n }\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containing the defines string\n */\n getEffectDefines() {\n let defines = \"#define CONEEMITTER\";\n if (this.emitFromSpawnPointOnly) {\n defines += \"\\n#define CONEEMITTERSPAWNPOINT\";\n }\n return defines;\n }\n /**\n * Returns the string \"ConeParticleEmitter\"\n * @returns a string containing the class name\n */\n getClassName() {\n return \"ConeParticleEmitter\";\n }\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n serialize() {\n const serializationObject = {};\n serializationObject.type = this.getClassName();\n serializationObject.radius = this._radius;\n serializationObject.angle = this._angle;\n serializationObject.directionRandomizer = this.directionRandomizer;\n serializationObject.radiusRange = this.radiusRange;\n serializationObject.heightRange = this.heightRange;\n serializationObject.emitFromSpawnPointOnly = this.emitFromSpawnPointOnly;\n return serializationObject;\n }\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n parse(serializationObject) {\n this.radius = serializationObject.radius;\n this.angle = serializationObject.angle;\n this.directionRandomizer = serializationObject.directionRandomizer;\n this.radiusRange = serializationObject.radiusRange !== undefined ? serializationObject.radiusRange : 1;\n this.heightRange = serializationObject.radiusRange !== undefined ? serializationObject.heightRange : 1;\n this.emitFromSpawnPointOnly = serializationObject.emitFromSpawnPointOnly !== undefined ? serializationObject.emitFromSpawnPointOnly : false;\n }\n}\n//# sourceMappingURL=coneParticleEmitter.js.map","import { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Scalar } from \"../../Maths/math.scalar.js\";\nimport { DeepCopier } from \"../../Misc/deepCopier.js\";\n/**\n * Particle emitter emitting particles from the inside of a cylinder.\n * It emits the particles alongside the cylinder radius. The emission direction might be randomized.\n */\nexport class CylinderParticleEmitter {\n /**\n * Creates a new instance CylinderParticleEmitter\n * @param radius the radius of the emission cylinder (1 by default)\n * @param height the height of the emission cylinder (1 by default)\n * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)\n * @param directionRandomizer defines how much to randomize the particle direction [0-1]\n */\n constructor(\n /**\n * The radius of the emission cylinder.\n */\n radius = 1, \n /**\n * The height of the emission cylinder.\n */\n height = 1, \n /**\n * The range of emission [0-1] 0 Surface only, 1 Entire Radius.\n */\n radiusRange = 1, \n /**\n * How much to randomize the particle direction [0-1].\n */\n directionRandomizer = 0) {\n this.radius = radius;\n this.height = height;\n this.radiusRange = radiusRange;\n this.directionRandomizer = directionRandomizer;\n this._tempVector = Vector3.Zero();\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n * @param isLocal defines if the direction should be set in local space\n * @param inverseWorldMatrix defines the inverted world matrix to use if isLocal is false\n */\n startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal, inverseWorldMatrix) {\n particle.position.subtractToRef(worldMatrix.getTranslation(), this._tempVector);\n this._tempVector.normalize();\n Vector3.TransformNormalToRef(this._tempVector, inverseWorldMatrix, this._tempVector);\n const randY = Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);\n let angle = Math.atan2(this._tempVector.x, this._tempVector.z);\n angle += Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;\n this._tempVector.y = randY; // set direction y to rand y to mirror normal of cylinder surface\n this._tempVector.x = Math.sin(angle);\n this._tempVector.z = Math.cos(angle);\n this._tempVector.normalize();\n if (isLocal) {\n directionToUpdate.copyFrom(this._tempVector);\n return;\n }\n Vector3.TransformNormalFromFloatsToRef(this._tempVector.x, this._tempVector.y, this._tempVector.z, worldMatrix, directionToUpdate);\n }\n /**\n * Called by the particle System when the position is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param positionToUpdate is the position vector to update with the result\n * @param particle is the particle we are computed the position for\n * @param isLocal defines if the position should be set in local space\n */\n startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) {\n const yPos = Scalar.RandomRange(-this.height / 2, this.height / 2);\n const angle = Scalar.RandomRange(0, 2 * Math.PI);\n // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html\n const radiusDistribution = Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);\n const positionRadius = Math.sqrt(radiusDistribution) * this.radius;\n const xPos = positionRadius * Math.cos(angle);\n const zPos = positionRadius * Math.sin(angle);\n if (isLocal) {\n positionToUpdate.copyFromFloats(xPos, yPos, zPos);\n return;\n }\n Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);\n }\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n clone() {\n const newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);\n DeepCopier.DeepCopy(this, newOne);\n return newOne;\n }\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param uboOrEffect defines the update shader\n */\n applyToShader(uboOrEffect) {\n uboOrEffect.setFloat(\"radius\", this.radius);\n uboOrEffect.setFloat(\"height\", this.height);\n uboOrEffect.setFloat(\"radiusRange\", this.radiusRange);\n uboOrEffect.setFloat(\"directionRandomizer\", this.directionRandomizer);\n }\n /**\n * Creates the structure of the ubo for this particle emitter\n * @param ubo ubo to create the structure for\n */\n buildUniformLayout(ubo) {\n ubo.addUniform(\"radius\", 1);\n ubo.addUniform(\"height\", 1);\n ubo.addUniform(\"radiusRange\", 1);\n ubo.addUniform(\"directionRandomizer\", 1);\n }\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containing the defines string\n */\n getEffectDefines() {\n return \"#define CYLINDEREMITTER\";\n }\n /**\n * Returns the string \"CylinderParticleEmitter\"\n * @returns a string containing the class name\n */\n getClassName() {\n return \"CylinderParticleEmitter\";\n }\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n serialize() {\n const serializationObject = {};\n serializationObject.type = this.getClassName();\n serializationObject.radius = this.radius;\n serializationObject.height = this.height;\n serializationObject.radiusRange = this.radiusRange;\n serializationObject.directionRandomizer = this.directionRandomizer;\n return serializationObject;\n }\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n parse(serializationObject) {\n this.radius = serializationObject.radius;\n this.height = serializationObject.height;\n this.radiusRange = serializationObject.radiusRange;\n this.directionRandomizer = serializationObject.directionRandomizer;\n }\n}\n/**\n * Particle emitter emitting particles from the inside of a cylinder.\n * It emits the particles randomly between two vectors.\n */\nexport class CylinderDirectedParticleEmitter extends CylinderParticleEmitter {\n /**\n * Creates a new instance CylinderDirectedParticleEmitter\n * @param radius the radius of the emission cylinder (1 by default)\n * @param height the height of the emission cylinder (1 by default)\n * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)\n * @param direction1 the min limit of the emission direction (up vector by default)\n * @param direction2 the max limit of the emission direction (up vector by default)\n */\n constructor(radius = 1, height = 1, radiusRange = 1, \n /**\n * The min limit of the emission direction.\n */\n direction1 = new Vector3(0, 1, 0), \n /**\n * The max limit of the emission direction.\n */\n direction2 = new Vector3(0, 1, 0)) {\n super(radius, height, radiusRange);\n this.direction1 = direction1;\n this.direction2 = direction2;\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n */\n startDirectionFunction(worldMatrix, directionToUpdate) {\n const randX = Scalar.RandomRange(this.direction1.x, this.direction2.x);\n const randY = Scalar.RandomRange(this.direction1.y, this.direction2.y);\n const randZ = Scalar.RandomRange(this.direction1.z, this.direction2.z);\n Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);\n }\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n clone() {\n const newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);\n DeepCopier.DeepCopy(this, newOne);\n return newOne;\n }\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param uboOrEffect defines the update shader\n */\n applyToShader(uboOrEffect) {\n uboOrEffect.setFloat(\"radius\", this.radius);\n uboOrEffect.setFloat(\"height\", this.height);\n uboOrEffect.setFloat(\"radiusRange\", this.radiusRange);\n uboOrEffect.setVector3(\"direction1\", this.direction1);\n uboOrEffect.setVector3(\"direction2\", this.direction2);\n }\n /**\n * Creates the structure of the ubo for this particle emitter\n * @param ubo ubo to create the structure for\n */\n buildUniformLayout(ubo) {\n ubo.addUniform(\"radius\", 1);\n ubo.addUniform(\"height\", 1);\n ubo.addUniform(\"radiusRange\", 1);\n ubo.addUniform(\"direction1\", 3);\n ubo.addUniform(\"direction2\", 3);\n }\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containing the defines string\n */\n getEffectDefines() {\n return \"#define CYLINDEREMITTER\\n#define DIRECTEDCYLINDEREMITTER\";\n }\n /**\n * Returns the string \"CylinderDirectedParticleEmitter\"\n * @returns a string containing the class name\n */\n getClassName() {\n return \"CylinderDirectedParticleEmitter\";\n }\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.direction1 = this.direction1.asArray();\n serializationObject.direction2 = this.direction2.asArray();\n return serializationObject;\n }\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n parse(serializationObject) {\n super.parse(serializationObject);\n this.direction1.copyFrom(serializationObject.direction1);\n this.direction2.copyFrom(serializationObject.direction2);\n }\n}\n//# sourceMappingURL=cylinderParticleEmitter.js.map","import { DeepCopier } from \"../../Misc/deepCopier.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Scalar } from \"../../Maths/math.scalar.js\";\n/**\n * Particle emitter emitting particles from the inside of a hemisphere.\n * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.\n */\nexport class HemisphericParticleEmitter {\n /**\n * Creates a new instance HemisphericParticleEmitter\n * @param radius the radius of the emission hemisphere (1 by default)\n * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)\n * @param directionRandomizer defines how much to randomize the particle direction [0-1]\n */\n constructor(\n /**\n * The radius of the emission hemisphere.\n */\n radius = 1, \n /**\n * The range of emission [0-1] 0 Surface only, 1 Entire Radius.\n */\n radiusRange = 1, \n /**\n * How much to randomize the particle direction [0-1].\n */\n directionRandomizer = 0) {\n this.radius = radius;\n this.radiusRange = radiusRange;\n this.directionRandomizer = directionRandomizer;\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n * @param isLocal defines if the direction should be set in local space\n */\n startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) {\n const direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();\n const randX = Scalar.RandomRange(0, this.directionRandomizer);\n const randY = Scalar.RandomRange(0, this.directionRandomizer);\n const randZ = Scalar.RandomRange(0, this.directionRandomizer);\n direction.x += randX;\n direction.y += randY;\n direction.z += randZ;\n direction.normalize();\n if (isLocal) {\n directionToUpdate.copyFrom(direction);\n return;\n }\n Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);\n }\n /**\n * Called by the particle System when the position is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param positionToUpdate is the position vector to update with the result\n * @param particle is the particle we are computed the position for\n * @param isLocal defines if the position should be set in local space\n */\n startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) {\n const randRadius = this.radius - Scalar.RandomRange(0, this.radius * this.radiusRange);\n const v = Scalar.RandomRange(0, 1.0);\n const phi = Scalar.RandomRange(0, 2 * Math.PI);\n const theta = Math.acos(2 * v - 1);\n const randX = randRadius * Math.cos(phi) * Math.sin(theta);\n const randY = randRadius * Math.cos(theta);\n const randZ = randRadius * Math.sin(phi) * Math.sin(theta);\n if (isLocal) {\n positionToUpdate.copyFromFloats(randX, Math.abs(randY), randZ);\n return;\n }\n Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);\n }\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n clone() {\n const newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);\n DeepCopier.DeepCopy(this, newOne);\n return newOne;\n }\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param uboOrEffect defines the update shader\n */\n applyToShader(uboOrEffect) {\n uboOrEffect.setFloat(\"radius\", this.radius);\n uboOrEffect.setFloat(\"radiusRange\", this.radiusRange);\n uboOrEffect.setFloat(\"directionRandomizer\", this.directionRandomizer);\n }\n /**\n * Creates the structure of the ubo for this particle emitter\n * @param ubo ubo to create the structure for\n */\n buildUniformLayout(ubo) {\n ubo.addUniform(\"radius\", 1);\n ubo.addUniform(\"radiusRange\", 1);\n ubo.addUniform(\"directionRandomizer\", 1);\n }\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containing the defines string\n */\n getEffectDefines() {\n return \"#define HEMISPHERICEMITTER\";\n }\n /**\n * Returns the string \"HemisphericParticleEmitter\"\n * @returns a string containing the class name\n */\n getClassName() {\n return \"HemisphericParticleEmitter\";\n }\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n serialize() {\n const serializationObject = {};\n serializationObject.type = this.getClassName();\n serializationObject.radius = this.radius;\n serializationObject.radiusRange = this.radiusRange;\n serializationObject.directionRandomizer = this.directionRandomizer;\n return serializationObject;\n }\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n parse(serializationObject) {\n this.radius = serializationObject.radius;\n this.radiusRange = serializationObject.radiusRange;\n this.directionRandomizer = serializationObject.directionRandomizer;\n }\n}\n//# sourceMappingURL=hemisphericParticleEmitter.js.map","export {};\n//# sourceMappingURL=IParticleEmitterType.js.map","import { DeepCopier } from \"../../Misc/deepCopier.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Scalar } from \"../../Maths/math.scalar.js\";\n/**\n * Particle emitter emitting particles from a point.\n * It emits the particles randomly between 2 given directions.\n */\nexport class PointParticleEmitter {\n /**\n * Creates a new instance PointParticleEmitter\n */\n constructor() {\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n */\n this.direction1 = new Vector3(0, 1.0, 0);\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n */\n this.direction2 = new Vector3(0, 1.0, 0);\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n * @param isLocal defines if the direction should be set in local space\n */\n startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) {\n const randX = Scalar.RandomRange(this.direction1.x, this.direction2.x);\n const randY = Scalar.RandomRange(this.direction1.y, this.direction2.y);\n const randZ = Scalar.RandomRange(this.direction1.z, this.direction2.z);\n if (isLocal) {\n directionToUpdate.copyFromFloats(randX, randY, randZ);\n return;\n }\n Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);\n }\n /**\n * Called by the particle System when the position is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param positionToUpdate is the position vector to update with the result\n * @param particle is the particle we are computed the position for\n * @param isLocal defines if the position should be set in local space\n */\n startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) {\n if (isLocal) {\n positionToUpdate.copyFromFloats(0, 0, 0);\n return;\n }\n Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);\n }\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n clone() {\n const newOne = new PointParticleEmitter();\n DeepCopier.DeepCopy(this, newOne);\n return newOne;\n }\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param uboOrEffect defines the update shader\n */\n applyToShader(uboOrEffect) {\n uboOrEffect.setVector3(\"direction1\", this.direction1);\n uboOrEffect.setVector3(\"direction2\", this.direction2);\n }\n /**\n * Creates the structure of the ubo for this particle emitter\n * @param ubo ubo to create the structure for\n */\n buildUniformLayout(ubo) {\n ubo.addUniform(\"direction1\", 3);\n ubo.addUniform(\"direction2\", 3);\n }\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containing the defines string\n */\n getEffectDefines() {\n return \"#define POINTEMITTER\";\n }\n /**\n * Returns the string \"PointParticleEmitter\"\n * @returns a string containing the class name\n */\n getClassName() {\n return \"PointParticleEmitter\";\n }\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n serialize() {\n const serializationObject = {};\n serializationObject.type = this.getClassName();\n serializationObject.direction1 = this.direction1.asArray();\n serializationObject.direction2 = this.direction2.asArray();\n return serializationObject;\n }\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n parse(serializationObject) {\n Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);\n Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);\n }\n}\n//# sourceMappingURL=pointParticleEmitter.js.map","import { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Scalar } from \"../../Maths/math.scalar.js\";\nimport { DeepCopier } from \"../../Misc/deepCopier.js\";\n/**\n * Particle emitter emitting particles from the inside of a sphere.\n * It emits the particles alongside the sphere radius. The emission direction might be randomized.\n */\nexport class SphereParticleEmitter {\n /**\n * Creates a new instance SphereParticleEmitter\n * @param radius the radius of the emission sphere (1 by default)\n * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)\n * @param directionRandomizer defines how much to randomize the particle direction [0-1]\n */\n constructor(\n /**\n * The radius of the emission sphere.\n */\n radius = 1, \n /**\n * The range of emission [0-1] 0 Surface only, 1 Entire Radius.\n */\n radiusRange = 1, \n /**\n * How much to randomize the particle direction [0-1].\n */\n directionRandomizer = 0) {\n this.radius = radius;\n this.radiusRange = radiusRange;\n this.directionRandomizer = directionRandomizer;\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n * @param isLocal defines if the direction should be set in local space\n */\n startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) {\n const direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();\n const randX = Scalar.RandomRange(0, this.directionRandomizer);\n const randY = Scalar.RandomRange(0, this.directionRandomizer);\n const randZ = Scalar.RandomRange(0, this.directionRandomizer);\n direction.x += randX;\n direction.y += randY;\n direction.z += randZ;\n direction.normalize();\n if (isLocal) {\n directionToUpdate.copyFrom(direction);\n return;\n }\n Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);\n }\n /**\n * Called by the particle System when the position is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param positionToUpdate is the position vector to update with the result\n * @param particle is the particle we are computed the position for\n * @param isLocal defines if the position should be set in local space\n */\n startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) {\n const randRadius = this.radius - Scalar.RandomRange(0, this.radius * this.radiusRange);\n const v = Scalar.RandomRange(0, 1.0);\n const phi = Scalar.RandomRange(0, 2 * Math.PI);\n const theta = Math.acos(2 * v - 1);\n const randX = randRadius * Math.cos(phi) * Math.sin(theta);\n const randY = randRadius * Math.cos(theta);\n const randZ = randRadius * Math.sin(phi) * Math.sin(theta);\n if (isLocal) {\n positionToUpdate.copyFromFloats(randX, randY, randZ);\n return;\n }\n Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);\n }\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n clone() {\n const newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);\n DeepCopier.DeepCopy(this, newOne);\n return newOne;\n }\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param uboOrEffect defines the update shader\n */\n applyToShader(uboOrEffect) {\n uboOrEffect.setFloat(\"radius\", this.radius);\n uboOrEffect.setFloat(\"radiusRange\", this.radiusRange);\n uboOrEffect.setFloat(\"directionRandomizer\", this.directionRandomizer);\n }\n /**\n * Creates the structure of the ubo for this particle emitter\n * @param ubo ubo to create the structure for\n */\n buildUniformLayout(ubo) {\n ubo.addUniform(\"radius\", 1);\n ubo.addUniform(\"radiusRange\", 1);\n ubo.addUniform(\"directionRandomizer\", 1);\n }\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containing the defines string\n */\n getEffectDefines() {\n return \"#define SPHEREEMITTER\";\n }\n /**\n * Returns the string \"SphereParticleEmitter\"\n * @returns a string containing the class name\n */\n getClassName() {\n return \"SphereParticleEmitter\";\n }\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n serialize() {\n const serializationObject = {};\n serializationObject.type = this.getClassName();\n serializationObject.radius = this.radius;\n serializationObject.radiusRange = this.radiusRange;\n serializationObject.directionRandomizer = this.directionRandomizer;\n return serializationObject;\n }\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n parse(serializationObject) {\n this.radius = serializationObject.radius;\n this.radiusRange = serializationObject.radiusRange;\n this.directionRandomizer = serializationObject.directionRandomizer;\n }\n}\n/**\n * Particle emitter emitting particles from the inside of a sphere.\n * It emits the particles randomly between two vectors.\n */\nexport class SphereDirectedParticleEmitter extends SphereParticleEmitter {\n /**\n * Creates a new instance SphereDirectedParticleEmitter\n * @param radius the radius of the emission sphere (1 by default)\n * @param direction1 the min limit of the emission direction (up vector by default)\n * @param direction2 the max limit of the emission direction (up vector by default)\n */\n constructor(radius = 1, \n /**\n * The min limit of the emission direction.\n */\n direction1 = new Vector3(0, 1, 0), \n /**\n * The max limit of the emission direction.\n */\n direction2 = new Vector3(0, 1, 0)) {\n super(radius);\n this.direction1 = direction1;\n this.direction2 = direction2;\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n */\n startDirectionFunction(worldMatrix, directionToUpdate) {\n const randX = Scalar.RandomRange(this.direction1.x, this.direction2.x);\n const randY = Scalar.RandomRange(this.direction1.y, this.direction2.y);\n const randZ = Scalar.RandomRange(this.direction1.z, this.direction2.z);\n Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);\n }\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n clone() {\n const newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);\n DeepCopier.DeepCopy(this, newOne);\n return newOne;\n }\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param uboOrEffect defines the update shader\n */\n applyToShader(uboOrEffect) {\n uboOrEffect.setFloat(\"radius\", this.radius);\n uboOrEffect.setFloat(\"radiusRange\", this.radiusRange);\n uboOrEffect.setVector3(\"direction1\", this.direction1);\n uboOrEffect.setVector3(\"direction2\", this.direction2);\n }\n /**\n * Creates the structure of the ubo for this particle emitter\n * @param ubo ubo to create the structure for\n */\n buildUniformLayout(ubo) {\n ubo.addUniform(\"radius\", 1);\n ubo.addUniform(\"radiusRange\", 1);\n ubo.addUniform(\"direction1\", 3);\n ubo.addUniform(\"direction2\", 3);\n }\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containing the defines string\n */\n getEffectDefines() {\n return \"#define SPHEREEMITTER\\n#define DIRECTEDSPHEREEMITTER\";\n }\n /**\n * Returns the string \"SphereDirectedParticleEmitter\"\n * @returns a string containing the class name\n */\n getClassName() {\n return \"SphereDirectedParticleEmitter\";\n }\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.direction1 = this.direction1.asArray();\n serializationObject.direction2 = this.direction2.asArray();\n return serializationObject;\n }\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n parse(serializationObject) {\n super.parse(serializationObject);\n this.direction1.copyFrom(serializationObject.direction1);\n this.direction2.copyFrom(serializationObject.direction2);\n }\n}\n//# sourceMappingURL=sphereParticleEmitter.js.map","import { DeepCopier } from \"../../Misc/deepCopier.js\";\nimport { Vector3, TmpVectors } from \"../../Maths/math.vector.js\";\n/**\n * Particle emitter emitting particles from a custom list of positions.\n */\nexport class CustomParticleEmitter {\n /**\n * Creates a new instance CustomParticleEmitter\n */\n constructor() {\n /**\n * Gets or sets the position generator that will create the initial position of each particle.\n * Index will be provided when used with GPU particle. Particle will be provided when used with CPU particles\n */\n this.particlePositionGenerator = () => { };\n /**\n * Gets or sets the destination generator that will create the final destination of each particle.\n * * Index will be provided when used with GPU particle. Particle will be provided when used with CPU particles\n */\n this.particleDestinationGenerator = () => { };\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n * @param isLocal defines if the direction should be set in local space\n */\n startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) {\n const tmpVector = TmpVectors.Vector3[0];\n if (this.particleDestinationGenerator) {\n this.particleDestinationGenerator(-1, particle, tmpVector);\n // Get direction\n const diffVector = TmpVectors.Vector3[1];\n tmpVector.subtractToRef(particle.position, diffVector);\n diffVector.scaleToRef(1 / particle.lifeTime, tmpVector);\n }\n else {\n tmpVector.set(0, 0, 0);\n }\n if (isLocal) {\n directionToUpdate.copyFrom(tmpVector);\n return;\n }\n Vector3.TransformNormalToRef(tmpVector, worldMatrix, directionToUpdate);\n }\n /**\n * Called by the particle System when the position is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param positionToUpdate is the position vector to update with the result\n * @param particle is the particle we are computed the position for\n * @param isLocal defines if the position should be set in local space\n */\n startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) {\n const tmpVector = TmpVectors.Vector3[0];\n if (this.particlePositionGenerator) {\n this.particlePositionGenerator(-1, particle, tmpVector);\n }\n else {\n tmpVector.set(0, 0, 0);\n }\n if (isLocal) {\n positionToUpdate.copyFrom(tmpVector);\n return;\n }\n Vector3.TransformCoordinatesToRef(tmpVector, worldMatrix, positionToUpdate);\n }\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n clone() {\n const newOne = new CustomParticleEmitter();\n DeepCopier.DeepCopy(this, newOne);\n return newOne;\n }\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param uboOrEffect defines the update shader\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n applyToShader(uboOrEffect) { }\n /**\n * Creates the structure of the ubo for this particle emitter\n * @param ubo ubo to create the structure for\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n buildUniformLayout(ubo) { }\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containing the defines string\n */\n getEffectDefines() {\n return \"#define CUSTOMEMITTER\";\n }\n /**\n * Returns the string \"PointParticleEmitter\"\n * @returns a string containing the class name\n */\n getClassName() {\n return \"CustomParticleEmitter\";\n }\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n serialize() {\n const serializationObject = {};\n serializationObject.type = this.getClassName();\n return serializationObject;\n }\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n parse(serializationObject) { }\n}\n//# sourceMappingURL=customParticleEmitter.js.map","import { DeepCopier } from \"../../Misc/deepCopier.js\";\nimport { Vector3, TmpVectors } from \"../../Maths/math.vector.js\";\nimport { Scalar } from \"../../Maths/math.scalar.js\";\nimport { VertexBuffer } from \"../../Buffers/buffer.js\";\n/**\n * Particle emitter emitting particles from the inside of a box.\n * It emits the particles randomly between 2 given directions.\n */\nexport class MeshParticleEmitter {\n /** Defines the mesh to use as source */\n get mesh() {\n return this._mesh;\n }\n set mesh(value) {\n if (this._mesh === value) {\n return;\n }\n this._mesh = value;\n if (value) {\n this._indices = value.getIndices();\n this._positions = value.getVerticesData(VertexBuffer.PositionKind);\n this._normals = value.getVerticesData(VertexBuffer.NormalKind);\n }\n else {\n this._indices = null;\n this._positions = null;\n this._normals = null;\n }\n }\n /**\n * Creates a new instance MeshParticleEmitter\n * @param mesh defines the mesh to use as source\n */\n constructor(mesh = null) {\n this._indices = null;\n this._positions = null;\n this._normals = null;\n this._storedNormal = Vector3.Zero();\n this._mesh = null;\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n */\n this.direction1 = new Vector3(0, 1.0, 0);\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n */\n this.direction2 = new Vector3(0, 1.0, 0);\n /**\n * Gets or sets a boolean indicating that particle directions must be built from mesh face normals\n */\n this.useMeshNormalsForDirection = true;\n this.mesh = mesh;\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n * @param isLocal defines if the direction should be set in local space\n */\n startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) {\n if (this.useMeshNormalsForDirection && this._normals) {\n Vector3.TransformNormalToRef(this._storedNormal, worldMatrix, directionToUpdate);\n return;\n }\n const randX = Scalar.RandomRange(this.direction1.x, this.direction2.x);\n const randY = Scalar.RandomRange(this.direction1.y, this.direction2.y);\n const randZ = Scalar.RandomRange(this.direction1.z, this.direction2.z);\n if (isLocal) {\n directionToUpdate.copyFromFloats(randX, randY, randZ);\n return;\n }\n Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);\n }\n /**\n * Called by the particle System when the position is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param positionToUpdate is the position vector to update with the result\n * @param particle is the particle we are computed the position for\n * @param isLocal defines if the position should be set in local space\n */\n startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) {\n if (!this._indices || !this._positions) {\n return;\n }\n const randomFaceIndex = (3 * Math.random() * (this._indices.length / 3)) | 0;\n const bu = Math.random();\n const bv = Math.random() * (1.0 - bu);\n const bw = 1.0 - bu - bv;\n const faceIndexA = this._indices[randomFaceIndex];\n const faceIndexB = this._indices[randomFaceIndex + 1];\n const faceIndexC = this._indices[randomFaceIndex + 2];\n const vertexA = TmpVectors.Vector3[0];\n const vertexB = TmpVectors.Vector3[1];\n const vertexC = TmpVectors.Vector3[2];\n const randomVertex = TmpVectors.Vector3[3];\n Vector3.FromArrayToRef(this._positions, faceIndexA * 3, vertexA);\n Vector3.FromArrayToRef(this._positions, faceIndexB * 3, vertexB);\n Vector3.FromArrayToRef(this._positions, faceIndexC * 3, vertexC);\n randomVertex.x = bu * vertexA.x + bv * vertexB.x + bw * vertexC.x;\n randomVertex.y = bu * vertexA.y + bv * vertexB.y + bw * vertexC.y;\n randomVertex.z = bu * vertexA.z + bv * vertexB.z + bw * vertexC.z;\n if (isLocal) {\n positionToUpdate.copyFromFloats(randomVertex.x, randomVertex.y, randomVertex.z);\n }\n else {\n Vector3.TransformCoordinatesFromFloatsToRef(randomVertex.x, randomVertex.y, randomVertex.z, worldMatrix, positionToUpdate);\n }\n if (this.useMeshNormalsForDirection && this._normals) {\n Vector3.FromArrayToRef(this._normals, faceIndexA * 3, vertexA);\n Vector3.FromArrayToRef(this._normals, faceIndexB * 3, vertexB);\n Vector3.FromArrayToRef(this._normals, faceIndexC * 3, vertexC);\n this._storedNormal.x = bu * vertexA.x + bv * vertexB.x + bw * vertexC.x;\n this._storedNormal.y = bu * vertexA.y + bv * vertexB.y + bw * vertexC.y;\n this._storedNormal.z = bu * vertexA.z + bv * vertexB.z + bw * vertexC.z;\n }\n }\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n clone() {\n const newOne = new MeshParticleEmitter(this.mesh);\n DeepCopier.DeepCopy(this, newOne);\n return newOne;\n }\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param uboOrEffect defines the update shader\n */\n applyToShader(uboOrEffect) {\n uboOrEffect.setVector3(\"direction1\", this.direction1);\n uboOrEffect.setVector3(\"direction2\", this.direction2);\n }\n /**\n * Creates the structure of the ubo for this particle emitter\n * @param ubo ubo to create the structure for\n */\n buildUniformLayout(ubo) {\n ubo.addUniform(\"direction1\", 3);\n ubo.addUniform(\"direction2\", 3);\n }\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containing the defines string\n */\n getEffectDefines() {\n return \"\";\n }\n /**\n * Returns the string \"BoxParticleEmitter\"\n * @returns a string containing the class name\n */\n getClassName() {\n return \"MeshParticleEmitter\";\n }\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n serialize() {\n var _a;\n const serializationObject = {};\n serializationObject.type = this.getClassName();\n serializationObject.direction1 = this.direction1.asArray();\n serializationObject.direction2 = this.direction2.asArray();\n serializationObject.meshId = (_a = this.mesh) === null || _a === void 0 ? void 0 : _a.id;\n serializationObject.useMeshNormalsForDirection = this.useMeshNormalsForDirection;\n return serializationObject;\n }\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n * @param scene defines the hosting scene\n */\n parse(serializationObject, scene) {\n Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);\n Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);\n if (serializationObject.meshId && scene) {\n this.mesh = scene.getLastMeshById(serializationObject.meshId);\n }\n this.useMeshNormalsForDirection = serializationObject.useMeshNormalsForDirection;\n }\n}\n//# sourceMappingURL=meshParticleEmitter.js.map","export * from \"./boxParticleEmitter.js\";\nexport * from \"./coneParticleEmitter.js\";\nexport * from \"./cylinderParticleEmitter.js\";\nexport * from \"./hemisphericParticleEmitter.js\";\nexport * from \"./IParticleEmitterType.js\";\nexport * from \"./pointParticleEmitter.js\";\nexport * from \"./sphereParticleEmitter.js\";\nexport * from \"./customParticleEmitter.js\";\nexport * from \"./meshParticleEmitter.js\";\n//# sourceMappingURL=index.js.map","import { Vector2, Vector3 } from \"../Maths/math.vector.js\";\nimport { ImageProcessingConfigurationDefines } from \"../Materials/imageProcessingConfiguration.js\";\nimport { BoxParticleEmitter, PointParticleEmitter, HemisphericParticleEmitter, SphereParticleEmitter, SphereDirectedParticleEmitter, CylinderParticleEmitter, CylinderDirectedParticleEmitter, ConeParticleEmitter, } from \"../Particles/EmitterTypes/index.js\";\n\nimport { Color4 } from \"../Maths/math.color.js\";\nimport \"../Engines/Extensions/engine.dynamicBuffer.js\";\n/**\n * This represents the base class for particle system in Babylon.\n * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.\n * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.\n * @example https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro\n */\nexport class BaseParticleSystem {\n /**\n * Gets or sets a texture used to add random noise to particle positions\n */\n get noiseTexture() {\n return this._noiseTexture;\n }\n set noiseTexture(value) {\n if (this._noiseTexture === value) {\n return;\n }\n this._noiseTexture = value;\n this._reset();\n }\n /**\n * Gets or sets whether an animation sprite sheet is enabled or not on the particle system\n */\n get isAnimationSheetEnabled() {\n return this._isAnimationSheetEnabled;\n }\n set isAnimationSheetEnabled(value) {\n if (this._isAnimationSheetEnabled == value) {\n return;\n }\n this._isAnimationSheetEnabled = value;\n this._reset();\n }\n /**\n * Gets or sets a boolean enabling the use of logarithmic depth buffers, which is good for wide depth buffers.\n */\n get useLogarithmicDepth() {\n return this._useLogarithmicDepth;\n }\n set useLogarithmicDepth(value) {\n this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;\n }\n /**\n * Get hosting scene\n * @returns the scene\n */\n getScene() {\n return this._scene;\n }\n _hasTargetStopDurationDependantGradient() {\n return ((this._startSizeGradients && this._startSizeGradients.length > 0) ||\n (this._emitRateGradients && this._emitRateGradients.length > 0) ||\n (this._lifeTimeGradients && this._lifeTimeGradients.length > 0));\n }\n /**\n * Gets the current list of drag gradients.\n * You must use addDragGradient and removeDragGradient to update this list\n * @returns the list of drag gradients\n */\n getDragGradients() {\n return this._dragGradients;\n }\n /**\n * Gets the current list of limit velocity gradients.\n * You must use addLimitVelocityGradient and removeLimitVelocityGradient to update this list\n * @returns the list of limit velocity gradients\n */\n getLimitVelocityGradients() {\n return this._limitVelocityGradients;\n }\n /**\n * Gets the current list of color gradients.\n * You must use addColorGradient and removeColorGradient to update this list\n * @returns the list of color gradients\n */\n getColorGradients() {\n return this._colorGradients;\n }\n /**\n * Gets the current list of size gradients.\n * You must use addSizeGradient and removeSizeGradient to update this list\n * @returns the list of size gradients\n */\n getSizeGradients() {\n return this._sizeGradients;\n }\n /**\n * Gets the current list of color remap gradients.\n * You must use addColorRemapGradient and removeColorRemapGradient to update this list\n * @returns the list of color remap gradients\n */\n getColorRemapGradients() {\n return this._colorRemapGradients;\n }\n /**\n * Gets the current list of alpha remap gradients.\n * You must use addAlphaRemapGradient and removeAlphaRemapGradient to update this list\n * @returns the list of alpha remap gradients\n */\n getAlphaRemapGradients() {\n return this._alphaRemapGradients;\n }\n /**\n * Gets the current list of life time gradients.\n * You must use addLifeTimeGradient and removeLifeTimeGradient to update this list\n * @returns the list of life time gradients\n */\n getLifeTimeGradients() {\n return this._lifeTimeGradients;\n }\n /**\n * Gets the current list of angular speed gradients.\n * You must use addAngularSpeedGradient and removeAngularSpeedGradient to update this list\n * @returns the list of angular speed gradients\n */\n getAngularSpeedGradients() {\n return this._angularSpeedGradients;\n }\n /**\n * Gets the current list of velocity gradients.\n * You must use addVelocityGradient and removeVelocityGradient to update this list\n * @returns the list of velocity gradients\n */\n getVelocityGradients() {\n return this._velocityGradients;\n }\n /**\n * Gets the current list of start size gradients.\n * You must use addStartSizeGradient and removeStartSizeGradient to update this list\n * @returns the list of start size gradients\n */\n getStartSizeGradients() {\n return this._startSizeGradients;\n }\n /**\n * Gets the current list of emit rate gradients.\n * You must use addEmitRateGradient and removeEmitRateGradient to update this list\n * @returns the list of emit rate gradients\n */\n getEmitRateGradients() {\n return this._emitRateGradients;\n }\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n * This only works when particleEmitterTyps is a BoxParticleEmitter\n */\n get direction1() {\n if (this.particleEmitterType.direction1) {\n return this.particleEmitterType.direction1;\n }\n return Vector3.Zero();\n }\n set direction1(value) {\n if (this.particleEmitterType.direction1) {\n this.particleEmitterType.direction1 = value;\n }\n }\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n * This only works when particleEmitterTyps is a BoxParticleEmitter\n */\n get direction2() {\n if (this.particleEmitterType.direction2) {\n return this.particleEmitterType.direction2;\n }\n return Vector3.Zero();\n }\n set direction2(value) {\n if (this.particleEmitterType.direction2) {\n this.particleEmitterType.direction2 = value;\n }\n }\n /**\n * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.\n * This only works when particleEmitterTyps is a BoxParticleEmitter\n */\n get minEmitBox() {\n if (this.particleEmitterType.minEmitBox) {\n return this.particleEmitterType.minEmitBox;\n }\n return Vector3.Zero();\n }\n set minEmitBox(value) {\n if (this.particleEmitterType.minEmitBox) {\n this.particleEmitterType.minEmitBox = value;\n }\n }\n /**\n * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.\n * This only works when particleEmitterTyps is a BoxParticleEmitter\n */\n get maxEmitBox() {\n if (this.particleEmitterType.maxEmitBox) {\n return this.particleEmitterType.maxEmitBox;\n }\n return Vector3.Zero();\n }\n set maxEmitBox(value) {\n if (this.particleEmitterType.maxEmitBox) {\n this.particleEmitterType.maxEmitBox = value;\n }\n }\n /**\n * Gets or sets the billboard mode to use when isBillboardBased = true.\n * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED\n */\n get billboardMode() {\n return this._billboardMode;\n }\n set billboardMode(value) {\n if (this._billboardMode === value) {\n return;\n }\n this._billboardMode = value;\n this._reset();\n }\n /**\n * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction\n */\n get isBillboardBased() {\n return this._isBillboardBased;\n }\n set isBillboardBased(value) {\n if (this._isBillboardBased === value) {\n return;\n }\n this._isBillboardBased = value;\n this._reset();\n }\n /**\n * Gets the image processing configuration used either in this material.\n */\n get imageProcessingConfiguration() {\n return this._imageProcessingConfiguration;\n }\n /**\n * Sets the Default image processing configuration used either in the this material.\n *\n * If sets to null, the scene one is in use.\n */\n set imageProcessingConfiguration(value) {\n this._attachImageProcessingConfiguration(value);\n }\n /**\n * Attaches a new image processing configuration to the Standard Material.\n * @param configuration\n */\n _attachImageProcessingConfiguration(configuration) {\n if (configuration === this._imageProcessingConfiguration) {\n return;\n }\n // Pick the scene configuration if needed.\n if (!configuration && this._scene) {\n this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;\n }\n else {\n this._imageProcessingConfiguration = configuration;\n }\n }\n /** @internal */\n _reset() { }\n /**\n * @internal\n */\n _removeGradientAndTexture(gradient, gradients, texture) {\n if (!gradients) {\n return this;\n }\n let index = 0;\n for (const valueGradient of gradients) {\n if (valueGradient.gradient === gradient) {\n gradients.splice(index, 1);\n break;\n }\n index++;\n }\n if (texture) {\n texture.dispose();\n }\n return this;\n }\n /**\n * Instantiates a particle system.\n * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.\n * @param name The name of the particle system\n */\n constructor(name) {\n /**\n * List of animations used by the particle system.\n */\n this.animations = [];\n /**\n * The rendering group used by the Particle system to chose when to render.\n */\n this.renderingGroupId = 0;\n /**\n * The emitter represents the Mesh or position we are attaching the particle system to.\n */\n this.emitter = Vector3.Zero();\n /**\n * The maximum number of particles to emit per frame\n */\n this.emitRate = 10;\n /**\n * If you want to launch only a few particles at once, that can be done, as well.\n */\n this.manualEmitCount = -1;\n /**\n * The overall motion speed (0.01 is default update speed, faster updates = faster animation)\n */\n this.updateSpeed = 0.01;\n /**\n * The amount of time the particle system is running (depends of the overall update speed).\n */\n this.targetStopDuration = 0;\n /**\n * Specifies whether the particle system will be disposed once it reaches the end of the animation.\n */\n this.disposeOnStop = false;\n /**\n * Minimum power of emitting particles.\n */\n this.minEmitPower = 1;\n /**\n * Maximum power of emitting particles.\n */\n this.maxEmitPower = 1;\n /**\n * Minimum life time of emitting particles.\n */\n this.minLifeTime = 1;\n /**\n * Maximum life time of emitting particles.\n */\n this.maxLifeTime = 1;\n /**\n * Minimum Size of emitting particles.\n */\n this.minSize = 1;\n /**\n * Maximum Size of emitting particles.\n */\n this.maxSize = 1;\n /**\n * Minimum scale of emitting particles on X axis.\n */\n this.minScaleX = 1;\n /**\n * Maximum scale of emitting particles on X axis.\n */\n this.maxScaleX = 1;\n /**\n * Minimum scale of emitting particles on Y axis.\n */\n this.minScaleY = 1;\n /**\n * Maximum scale of emitting particles on Y axis.\n */\n this.maxScaleY = 1;\n /**\n * Gets or sets the minimal initial rotation in radians.\n */\n this.minInitialRotation = 0;\n /**\n * Gets or sets the maximal initial rotation in radians.\n */\n this.maxInitialRotation = 0;\n /**\n * Minimum angular speed of emitting particles (Z-axis rotation for each particle).\n */\n this.minAngularSpeed = 0;\n /**\n * Maximum angular speed of emitting particles (Z-axis rotation for each particle).\n */\n this.maxAngularSpeed = 0;\n /**\n * The layer mask we are rendering the particles through.\n */\n this.layerMask = 0x0fffffff;\n /**\n * This can help using your own shader to render the particle system.\n * The according effect will be created\n */\n this.customShader = null;\n /**\n * By default particle system starts as soon as they are created. This prevents the\n * automatic start to happen and let you decide when to start emitting particles.\n */\n this.preventAutoStart = false;\n /** @internal */\n this._wasDispatched = false;\n this._rootUrl = \"\";\n /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */\n this.noiseStrength = new Vector3(10, 10, 10);\n /**\n * Callback triggered when the particle animation is ending.\n */\n this.onAnimationEnd = null;\n /**\n * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.\n */\n this.blendMode = BaseParticleSystem.BLENDMODE_ONEONE;\n /**\n * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls\n * to override the particles.\n */\n this.forceDepthWrite = false;\n /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */\n this.preWarmCycles = 0;\n /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */\n this.preWarmStepOffset = 1;\n /**\n * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)\n */\n this.spriteCellChangeSpeed = 1;\n /**\n * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display\n */\n this.startSpriteCellID = 0;\n /**\n * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display\n */\n this.endSpriteCellID = 0;\n /**\n * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use\n */\n this.spriteCellWidth = 0;\n /**\n * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use\n */\n this.spriteCellHeight = 0;\n /**\n * If using a spritesheet (isAnimationSheetEnabled), defines wether the sprite animation is looping\n */\n this.spriteCellLoop = true;\n /**\n * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID\n */\n this.spriteRandomStartCell = false;\n /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */\n this.translationPivot = new Vector2(0, 0);\n /**\n * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called\n */\n this.beginAnimationOnStart = false;\n /**\n * Gets or sets the frame to start the animation from when beginAnimationOnStart is true\n */\n this.beginAnimationFrom = 0;\n /**\n * Gets or sets the frame to end the animation on when beginAnimationOnStart is true\n */\n this.beginAnimationTo = 60;\n /**\n * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true\n */\n this.beginAnimationLoop = false;\n /**\n * Gets or sets a world offset applied to all particles\n */\n this.worldOffset = new Vector3(0, 0, 0);\n this._useLogarithmicDepth = false;\n /**\n * You can use gravity if you want to give an orientation to your particles.\n */\n this.gravity = Vector3.Zero();\n this._colorGradients = null;\n this._sizeGradients = null;\n this._lifeTimeGradients = null;\n this._angularSpeedGradients = null;\n this._velocityGradients = null;\n this._limitVelocityGradients = null;\n this._dragGradients = null;\n this._emitRateGradients = null;\n this._startSizeGradients = null;\n this._rampGradients = null;\n this._colorRemapGradients = null;\n this._alphaRemapGradients = null;\n /**\n * Defines the delay in milliseconds before starting the system (0 by default)\n */\n this.startDelay = 0;\n /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */\n this.limitVelocityDamping = 0.4;\n /**\n * Random color of each particle after it has been emitted, between color1 and color2 vectors\n */\n this.color1 = new Color4(1.0, 1.0, 1.0, 1.0);\n /**\n * Random color of each particle after it has been emitted, between color1 and color2 vectors\n */\n this.color2 = new Color4(1.0, 1.0, 1.0, 1.0);\n /**\n * Color the particle will have at the end of its lifetime\n */\n this.colorDead = new Color4(0, 0, 0, 1.0);\n /**\n * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel\n */\n this.textureMask = new Color4(1.0, 1.0, 1.0, 1.0);\n /** @internal */\n this._isSubEmitter = false;\n /** @internal */\n this._billboardMode = 7;\n /** @internal */\n this._isBillboardBased = true;\n /**\n * Local cache of defines for image processing.\n */\n this._imageProcessingConfigurationDefines = new ImageProcessingConfigurationDefines();\n this.id = name;\n this.name = name;\n }\n /**\n * Creates a Point Emitter for the particle system (emits directly from the emitter position)\n * @param direction1 Particles are emitted between the direction1 and direction2 from within the box\n * @param direction2 Particles are emitted between the direction1 and direction2 from within the box\n * @returns the emitter\n */\n createPointEmitter(direction1, direction2) {\n const particleEmitter = new PointParticleEmitter();\n particleEmitter.direction1 = direction1;\n particleEmitter.direction2 = direction2;\n this.particleEmitterType = particleEmitter;\n return particleEmitter;\n }\n /**\n * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)\n * @param radius The radius of the hemisphere to emit from\n * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius\n * @returns the emitter\n */\n createHemisphericEmitter(radius = 1, radiusRange = 1) {\n const particleEmitter = new HemisphericParticleEmitter(radius, radiusRange);\n this.particleEmitterType = particleEmitter;\n return particleEmitter;\n }\n /**\n * Creates a Sphere Emitter for the particle system (emits along the sphere radius)\n * @param radius The radius of the sphere to emit from\n * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius\n * @returns the emitter\n */\n createSphereEmitter(radius = 1, radiusRange = 1) {\n const particleEmitter = new SphereParticleEmitter(radius, radiusRange);\n this.particleEmitterType = particleEmitter;\n return particleEmitter;\n }\n /**\n * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)\n * @param radius The radius of the sphere to emit from\n * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere\n * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere\n * @returns the emitter\n */\n createDirectedSphereEmitter(radius = 1, direction1 = new Vector3(0, 1.0, 0), direction2 = new Vector3(0, 1.0, 0)) {\n const particleEmitter = new SphereDirectedParticleEmitter(radius, direction1, direction2);\n this.particleEmitterType = particleEmitter;\n return particleEmitter;\n }\n /**\n * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)\n * @param radius The radius of the emission cylinder\n * @param height The height of the emission cylinder\n * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius\n * @param directionRandomizer How much to randomize the particle direction [0-1]\n * @returns the emitter\n */\n createCylinderEmitter(radius = 1, height = 1, radiusRange = 1, directionRandomizer = 0) {\n const particleEmitter = new CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);\n this.particleEmitterType = particleEmitter;\n return particleEmitter;\n }\n /**\n * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)\n * @param radius The radius of the cylinder to emit from\n * @param height The height of the emission cylinder\n * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)\n * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder\n * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder\n * @returns the emitter\n */\n createDirectedCylinderEmitter(radius = 1, height = 1, radiusRange = 1, direction1 = new Vector3(0, 1.0, 0), direction2 = new Vector3(0, 1.0, 0)) {\n const particleEmitter = new CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);\n this.particleEmitterType = particleEmitter;\n return particleEmitter;\n }\n /**\n * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)\n * @param radius The radius of the cone to emit from\n * @param angle The base angle of the cone\n * @returns the emitter\n */\n createConeEmitter(radius = 1, angle = Math.PI / 4) {\n const particleEmitter = new ConeParticleEmitter(radius, angle);\n this.particleEmitterType = particleEmitter;\n return particleEmitter;\n }\n /**\n * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)\n * @param direction1 Particles are emitted between the direction1 and direction2 from within the box\n * @param direction2 Particles are emitted between the direction1 and direction2 from within the box\n * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox\n * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox\n * @returns the emitter\n */\n createBoxEmitter(direction1, direction2, minEmitBox, maxEmitBox) {\n const particleEmitter = new BoxParticleEmitter();\n this.particleEmitterType = particleEmitter;\n this.direction1 = direction1;\n this.direction2 = direction2;\n this.minEmitBox = minEmitBox;\n this.maxEmitBox = maxEmitBox;\n return particleEmitter;\n }\n}\n/**\n * Source color is added to the destination color without alpha affecting the result\n */\nBaseParticleSystem.BLENDMODE_ONEONE = 0;\n/**\n * Blend current color and particle color using particle’s alpha\n */\nBaseParticleSystem.BLENDMODE_STANDARD = 1;\n/**\n * Add current color and particle color multiplied by particle’s alpha\n */\nBaseParticleSystem.BLENDMODE_ADD = 2;\n/**\n * Multiply current color with particle color\n */\nBaseParticleSystem.BLENDMODE_MULTIPLY = 3;\n/**\n * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha\n */\nBaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;\n//# sourceMappingURL=baseParticleSystem.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to expand a Color3/4 into 4 outputs (one for each component)\n */\nexport class ColorSplitterBlock extends NodeMaterialBlock {\n /**\n * Create a new ColorSplitterBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"rgba\", NodeMaterialBlockConnectionPointTypes.Color4, true);\n this.registerInput(\"rgb \", NodeMaterialBlockConnectionPointTypes.Color3, true);\n this.registerOutput(\"rgb\", NodeMaterialBlockConnectionPointTypes.Color3);\n this.registerOutput(\"r\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"g\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"b\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"a\", NodeMaterialBlockConnectionPointTypes.Float);\n this.inputsAreExclusive = true;\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ColorSplitterBlock\";\n }\n /**\n * Gets the rgba component (input)\n */\n get rgba() {\n return this._inputs[0];\n }\n /**\n * Gets the rgb component (input)\n */\n get rgbIn() {\n return this._inputs[1];\n }\n /**\n * Gets the rgb component (output)\n */\n get rgbOut() {\n return this._outputs[0];\n }\n /**\n * Gets the r component (output)\n */\n get r() {\n return this._outputs[1];\n }\n /**\n * Gets the g component (output)\n */\n get g() {\n return this._outputs[2];\n }\n /**\n * Gets the b component (output)\n */\n get b() {\n return this._outputs[3];\n }\n /**\n * Gets the a component (output)\n */\n get a() {\n return this._outputs[4];\n }\n _inputRename(name) {\n if (name === \"rgb \") {\n return \"rgbIn\";\n }\n return name;\n }\n _outputRename(name) {\n if (name === \"rgb\") {\n return \"rgbOut\";\n }\n return name;\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const input = this.rgba.isConnected ? this.rgba : this.rgbIn;\n if (!input.isConnected) {\n return;\n }\n const rgbOutput = this._outputs[0];\n const rOutput = this._outputs[1];\n const gOutput = this._outputs[2];\n const bOutput = this._outputs[3];\n const aOutput = this._outputs[4];\n if (rgbOutput.hasEndpoints) {\n state.compilationString += this._declareOutput(rgbOutput, state) + ` = ${input.associatedVariableName}.rgb;\\r\\n`;\n }\n if (rOutput.hasEndpoints) {\n state.compilationString += this._declareOutput(rOutput, state) + ` = ${input.associatedVariableName}.r;\\r\\n`;\n }\n if (gOutput.hasEndpoints) {\n state.compilationString += this._declareOutput(gOutput, state) + ` = ${input.associatedVariableName}.g;\\r\\n`;\n }\n if (bOutput.hasEndpoints) {\n state.compilationString += this._declareOutput(bOutput, state) + ` = ${input.associatedVariableName}.b;\\r\\n`;\n }\n if (aOutput.hasEndpoints) {\n state.compilationString += this._declareOutput(aOutput, state) + ` = ${input.associatedVariableName}.a;\\r\\n`;\n }\n return this;\n }\n}\nRegisterClass(\"BABYLON.ColorSplitterBlock\", ColorSplitterBlock);\n//# sourceMappingURL=colorSplitterBlock.js.map","import { InternalTexture, InternalTextureSource } from \"../../Materials/Textures/internalTexture.js\";\nimport { Logger } from \"../../Misc/logger.js\";\n\nimport { ThinEngine } from \"../thinEngine.js\";\nThinEngine.prototype.createRenderTargetCubeTexture = function (size, options) {\n const rtWrapper = this._createHardwareRenderTargetWrapper(false, true, size);\n const fullOptions = Object.assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: 0, samplingMode: 3, format: 5 }, options);\n fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;\n if (fullOptions.type === 1 && !this._caps.textureFloatLinearFiltering) {\n // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE\n fullOptions.samplingMode = 1;\n }\n else if (fullOptions.type === 2 && !this._caps.textureHalfFloatLinearFiltering) {\n // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE\n fullOptions.samplingMode = 1;\n }\n const gl = this._gl;\n const texture = new InternalTexture(this, InternalTextureSource.RenderTarget);\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);\n const filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);\n if (fullOptions.type === 1 && !this._caps.textureFloat) {\n fullOptions.type = 0;\n Logger.Warn(\"Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type\");\n }\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n for (let face = 0; face < 6; face++) {\n gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);\n }\n // Create the framebuffer\n const framebuffer = gl.createFramebuffer();\n this._bindUnboundFramebuffer(framebuffer);\n rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);\n // MipMaps\n if (fullOptions.generateMipMaps) {\n gl.generateMipmap(gl.TEXTURE_CUBE_MAP);\n }\n // Unbind\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n this._bindUnboundFramebuffer(null);\n rtWrapper._framebuffer = framebuffer;\n rtWrapper._generateDepthBuffer = fullOptions.generateDepthBuffer;\n rtWrapper._generateStencilBuffer = fullOptions.generateStencilBuffer;\n texture.width = size;\n texture.height = size;\n texture.isReady = true;\n texture.isCube = true;\n texture.samples = 1;\n texture.generateMipMaps = fullOptions.generateMipMaps;\n texture.samplingMode = fullOptions.samplingMode;\n texture.type = fullOptions.type;\n texture.format = fullOptions.format;\n this._internalTexturesCache.push(texture);\n rtWrapper.setTextures(texture);\n return rtWrapper;\n};\n//# sourceMappingURL=engine.renderTargetCube.js.map","import { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Viewport } from \"../Maths/math.viewport.js\";\n\nimport { Observable } from \"../Misc/observable.js\";\nimport { Effect } from \"./effect.js\";\nimport { DrawWrapper } from \"./drawWrapper.js\";\n// Prevents ES6 Crash if not imported.\nimport \"../Shaders/postprocess.vertex.js\";\n// Fullscreen quad buffers by default.\nconst defaultOptions = {\n positions: [1, 1, -1, 1, -1, -1, 1, -1],\n indices: [0, 1, 2, 0, 2, 3],\n};\n/**\n * Helper class to render one or more effects.\n * You can access the previous rendering in your shader by declaring a sampler named textureSampler\n */\nexport class EffectRenderer {\n /**\n * Creates an effect renderer\n * @param engine the engine to use for rendering\n * @param options defines the options of the effect renderer\n */\n constructor(engine, options = defaultOptions) {\n var _a, _b;\n this._fullscreenViewport = new Viewport(0, 0, 1, 1);\n const positions = (_a = options.positions) !== null && _a !== void 0 ? _a : defaultOptions.positions;\n const indices = (_b = options.indices) !== null && _b !== void 0 ? _b : defaultOptions.indices;\n this.engine = engine;\n this._vertexBuffers = {\n [VertexBuffer.PositionKind]: new VertexBuffer(engine, positions, VertexBuffer.PositionKind, false, false, 2),\n };\n this._indexBuffer = engine.createIndexBuffer(indices);\n this._onContextRestoredObserver = engine.onContextRestoredObservable.add(() => {\n this._indexBuffer = engine.createIndexBuffer(indices);\n for (const key in this._vertexBuffers) {\n const vertexBuffer = this._vertexBuffers[key];\n vertexBuffer._rebuild();\n }\n });\n }\n /**\n * Sets the current viewport in normalized coordinates 0-1\n * @param viewport Defines the viewport to set (defaults to 0 0 1 1)\n */\n setViewport(viewport = this._fullscreenViewport) {\n this.engine.setViewport(viewport);\n }\n /**\n * Binds the embedded attributes buffer to the effect.\n * @param effect Defines the effect to bind the attributes for\n */\n bindBuffers(effect) {\n this.engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);\n }\n /**\n * Sets the current effect wrapper to use during draw.\n * The effect needs to be ready before calling this api.\n * This also sets the default full screen position attribute.\n * @param effectWrapper Defines the effect to draw with\n */\n applyEffectWrapper(effectWrapper) {\n this.engine.setState(true);\n this.engine.depthCullingState.depthTest = false;\n this.engine.stencilState.stencilTest = false;\n this.engine.enableEffect(effectWrapper._drawWrapper);\n this.bindBuffers(effectWrapper.effect);\n effectWrapper.onApplyObservable.notifyObservers({});\n }\n /**\n * Restores engine states\n */\n restoreStates() {\n this.engine.depthCullingState.depthTest = true;\n this.engine.stencilState.stencilTest = true;\n }\n /**\n * Draws a full screen quad.\n */\n draw() {\n this.engine.drawElementsType(0, 0, 6);\n }\n _isRenderTargetTexture(texture) {\n return texture.renderTarget !== undefined;\n }\n /**\n * renders one or more effects to a specified texture\n * @param effectWrapper the effect to renderer\n * @param outputTexture texture to draw to, if null it will render to the screen.\n */\n render(effectWrapper, outputTexture = null) {\n // Ensure effect is ready\n if (!effectWrapper.effect.isReady()) {\n return;\n }\n // Reset state\n this.setViewport();\n const out = outputTexture === null ? null : this._isRenderTargetTexture(outputTexture) ? outputTexture.renderTarget : outputTexture;\n if (out) {\n this.engine.bindFramebuffer(out);\n }\n this.applyEffectWrapper(effectWrapper);\n this.draw();\n if (out) {\n this.engine.unBindFramebuffer(out);\n }\n this.restoreStates();\n }\n /**\n * Disposes of the effect renderer\n */\n dispose() {\n const vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];\n if (vertexBuffer) {\n vertexBuffer.dispose();\n delete this._vertexBuffers[VertexBuffer.PositionKind];\n }\n if (this._indexBuffer) {\n this.engine._releaseBuffer(this._indexBuffer);\n }\n if (this._onContextRestoredObserver) {\n this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver);\n this._onContextRestoredObserver = null;\n }\n }\n}\n/**\n * Wraps an effect to be used for rendering\n */\nexport class EffectWrapper {\n /**\n * The underlying effect\n */\n get effect() {\n return this._drawWrapper.effect;\n }\n set effect(effect) {\n this._drawWrapper.effect = effect;\n }\n /**\n * Creates an effect to be renderer\n * @param creationOptions options to create the effect\n */\n constructor(creationOptions) {\n /**\n * Event that is fired right before the effect is drawn (should be used to update uniforms)\n */\n this.onApplyObservable = new Observable();\n let effectCreationOptions;\n const uniformNames = creationOptions.uniformNames || [];\n if (creationOptions.vertexShader) {\n effectCreationOptions = {\n fragmentSource: creationOptions.fragmentShader,\n vertexSource: creationOptions.vertexShader,\n spectorName: creationOptions.name || \"effectWrapper\",\n };\n }\n else {\n // Default scale to use in post process vertex shader.\n uniformNames.push(\"scale\");\n effectCreationOptions = {\n fragmentSource: creationOptions.fragmentShader,\n vertex: \"postprocess\",\n spectorName: creationOptions.name || \"effectWrapper\",\n };\n // Sets the default scale to identity for the post process vertex shader.\n this.onApplyObservable.add(() => {\n this.effect.setFloat2(\"scale\", 1, 1);\n });\n }\n const defines = creationOptions.defines ? creationOptions.defines.join(\"\\n\") : \"\";\n this._drawWrapper = new DrawWrapper(creationOptions.engine);\n if (creationOptions.useShaderStore) {\n effectCreationOptions.fragment = effectCreationOptions.fragmentSource;\n if (!effectCreationOptions.vertex) {\n effectCreationOptions.vertex = effectCreationOptions.vertexSource;\n }\n delete effectCreationOptions.fragmentSource;\n delete effectCreationOptions.vertexSource;\n this.effect = creationOptions.engine.createEffect(effectCreationOptions, creationOptions.attributeNames || [\"position\"], uniformNames, creationOptions.samplerNames, defines, undefined, creationOptions.onCompiled, undefined, undefined, creationOptions.shaderLanguage);\n }\n else {\n this.effect = new Effect(effectCreationOptions, creationOptions.attributeNames || [\"position\"], uniformNames, creationOptions.samplerNames, creationOptions.engine, defines, undefined, creationOptions.onCompiled, undefined, undefined, undefined, creationOptions.shaderLanguage);\n this._onContextRestoredObserver = creationOptions.engine.onContextRestoredObservable.add(() => {\n this.effect._pipelineContext = null; // because _prepareEffect will try to dispose this pipeline before recreating it and that would lead to webgl errors\n this.effect._wasPreviouslyReady = false;\n this.effect._prepareEffect();\n });\n }\n }\n /**\n * Disposes of the effect wrapper\n */\n dispose() {\n if (this._onContextRestoredObserver) {\n this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver);\n this._onContextRestoredObserver = null;\n }\n this.effect.dispose();\n }\n}\n//# sourceMappingURL=effectRenderer.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"passPixelShader\";\nconst shader = `varying vec2 vUV;\runiform sampler2D textureSampler;\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \r{\rgl_FragColor=texture2D(textureSampler,vUV);\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const passPixelShader = { name, shader };\n//# sourceMappingURL=pass.fragment.js.map","import { ThinEngine } from \"../Engines/thinEngine.js\";\n\nimport { EffectRenderer, EffectWrapper } from \"../Materials/effectRenderer.js\";\nimport { Tools } from \"./tools.js\";\nimport { passPixelShader } from \"../Shaders/pass.fragment.js\";\nimport { Scalar } from \"../Maths/math.scalar.js\";\n/**\n * Class containing a set of static utilities functions to dump data from a canvas\n */\nexport class DumpTools {\n static _CreateDumpRenderer() {\n if (!DumpTools._DumpToolsEngine) {\n const canvas = new OffscreenCanvas(100, 100); // will be resized later\n const engine = new ThinEngine(canvas, false, {\n preserveDrawingBuffer: true,\n depth: false,\n stencil: false,\n alpha: true,\n premultipliedAlpha: false,\n antialias: false,\n failIfMajorPerformanceCaveat: false,\n });\n engine.getCaps().parallelShaderCompile = undefined;\n const renderer = new EffectRenderer(engine);\n const wrapper = new EffectWrapper({\n engine,\n name: passPixelShader.name,\n fragmentShader: passPixelShader.shader,\n samplerNames: [\"textureSampler\"],\n });\n DumpTools._DumpToolsEngine = {\n canvas,\n engine,\n renderer,\n wrapper,\n };\n }\n return DumpTools._DumpToolsEngine;\n }\n /**\n * Dumps the current bound framebuffer\n * @param width defines the rendering width\n * @param height defines the rendering height\n * @param engine defines the hosting engine\n * @param successCallback defines the callback triggered once the data are available\n * @param mimeType defines the mime type of the result\n * @param fileName defines the filename to download. If present, the result will automatically be downloaded\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n * @returns a void promise\n */\n static async DumpFramebuffer(width, height, engine, successCallback, mimeType = \"image/png\", fileName, quality) {\n // Read the contents of the framebuffer\n const bufferView = await engine.readPixels(0, 0, width, height);\n const data = new Uint8Array(bufferView.buffer);\n DumpTools.DumpData(width, height, data, successCallback, mimeType, fileName, true, undefined, quality);\n }\n /**\n * Dumps an array buffer\n * @param width defines the rendering width\n * @param height defines the rendering height\n * @param data the data array\n * @param mimeType defines the mime type of the result\n * @param fileName defines the filename to download. If present, the result will automatically be downloaded\n * @param invertY true to invert the picture in the Y dimension\n * @param toArrayBuffer true to convert the data to an ArrayBuffer (encoded as `mimeType`) instead of a base64 string\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n * @returns a promise that resolve to the final data\n */\n static DumpDataAsync(width, height, data, mimeType = \"image/png\", fileName, invertY = false, toArrayBuffer = false, quality) {\n return new Promise((resolve) => {\n DumpTools.DumpData(width, height, data, (result) => resolve(result), mimeType, fileName, invertY, toArrayBuffer, quality);\n });\n }\n /**\n * Dumps an array buffer\n * @param width defines the rendering width\n * @param height defines the rendering height\n * @param data the data array\n * @param successCallback defines the callback triggered once the data are available\n * @param mimeType defines the mime type of the result\n * @param fileName defines the filename to download. If present, the result will automatically be downloaded\n * @param invertY true to invert the picture in the Y dimension\n * @param toArrayBuffer true to convert the data to an ArrayBuffer (encoded as `mimeType`) instead of a base64 string\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n */\n static DumpData(width, height, data, successCallback, mimeType = \"image/png\", fileName, invertY = false, toArrayBuffer = false, quality) {\n const renderer = DumpTools._CreateDumpRenderer();\n renderer.engine.setSize(width, height, true);\n // Convert if data are float32\n if (data instanceof Float32Array) {\n const data2 = new Uint8Array(data.length);\n let n = data.length;\n while (n--) {\n const v = data[n];\n data2[n] = Math.round(Scalar.Clamp(v) * 255);\n }\n data = data2;\n }\n // Create the image\n const texture = renderer.engine.createRawTexture(data, width, height, 5, false, !invertY, 1);\n renderer.renderer.setViewport();\n renderer.renderer.applyEffectWrapper(renderer.wrapper);\n renderer.wrapper.effect._bindTexture(\"textureSampler\", texture);\n renderer.renderer.draw();\n if (toArrayBuffer) {\n Tools.ToBlob(renderer.canvas, (blob) => {\n const fileReader = new FileReader();\n fileReader.onload = (event) => {\n const arrayBuffer = event.target.result;\n if (successCallback) {\n successCallback(arrayBuffer);\n }\n };\n fileReader.readAsArrayBuffer(blob);\n }, mimeType, quality);\n }\n else {\n Tools.EncodeScreenshotCanvasData(renderer.canvas, successCallback, mimeType, fileName, quality);\n }\n texture.dispose();\n }\n /**\n * Dispose the dump tools associated resources\n */\n static Dispose() {\n if (DumpTools._DumpToolsEngine) {\n DumpTools._DumpToolsEngine.wrapper.dispose();\n DumpTools._DumpToolsEngine.renderer.dispose();\n DumpTools._DumpToolsEngine.engine.dispose();\n }\n DumpTools._DumpToolsEngine = null;\n }\n}\n/**\n * This will be executed automatically for UMD and es5.\n * If esm dev wants the side effects to execute they will have to run it manually\n * Once we build native modules those need to be exported.\n * @internal\n */\nconst initSideEffects = () => {\n // References the dependencies.\n Tools.DumpData = DumpTools.DumpData;\n Tools.DumpDataAsync = DumpTools.DumpDataAsync;\n Tools.DumpFramebuffer = DumpTools.DumpFramebuffer;\n};\ninitSideEffects();\n//# sourceMappingURL=dumpTools.js.map","import { Observable } from \"../../Misc/observable.js\";\nimport { Matrix, Vector3 } from \"../../Maths/math.vector.js\";\nimport { Texture } from \"../../Materials/Textures/texture.js\";\nimport { PostProcessManager } from \"../../PostProcesses/postProcessManager.js\";\nimport { RenderingManager } from \"../../Rendering/renderingManager.js\";\n\nimport \"../../Engines/Extensions/engine.renderTarget.js\";\nimport \"../../Engines/Extensions/engine.renderTargetCube.js\";\nimport { Engine } from \"../../Engines/engine.js\";\nimport { _ObserveArray } from \"../../Misc/arrayTools.js\";\nimport { DumpTools } from \"../../Misc/dumpTools.js\";\n/**\n * This Helps creating a texture that will be created from a camera in your scene.\n * It is basically a dynamic texture that could be used to create special effects for instance.\n * Actually, It is the base of lot of effects in the framework like post process, shadows, effect layers and rendering pipelines...\n */\nexport class RenderTargetTexture extends Texture {\n /**\n * Use this list to define the list of mesh you want to render.\n */\n get renderList() {\n return this._renderList;\n }\n set renderList(value) {\n if (this._unObserveRenderList) {\n this._unObserveRenderList();\n this._unObserveRenderList = null;\n }\n if (value) {\n this._unObserveRenderList = _ObserveArray(value, this._renderListHasChanged);\n }\n this._renderList = value;\n }\n /**\n * Post-processes for this render target\n */\n get postProcesses() {\n return this._postProcesses;\n }\n get _prePassEnabled() {\n return !!this._prePassRenderTarget && this._prePassRenderTarget.enabled;\n }\n /**\n * Set a after unbind callback in the texture.\n * This has been kept for backward compatibility and use of onAfterUnbindObservable is recommended.\n */\n set onAfterUnbind(callback) {\n if (this._onAfterUnbindObserver) {\n this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);\n }\n this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);\n }\n /**\n * Set a before render callback in the texture.\n * This has been kept for backward compatibility and use of onBeforeRenderObservable is recommended.\n */\n set onBeforeRender(callback) {\n if (this._onBeforeRenderObserver) {\n this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);\n }\n this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);\n }\n /**\n * Set a after render callback in the texture.\n * This has been kept for backward compatibility and use of onAfterRenderObservable is recommended.\n */\n set onAfterRender(callback) {\n if (this._onAfterRenderObserver) {\n this.onAfterRenderObservable.remove(this._onAfterRenderObserver);\n }\n this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);\n }\n /**\n * Set a clear callback in the texture.\n * This has been kept for backward compatibility and use of onClearObservable is recommended.\n */\n set onClear(callback) {\n if (this._onClearObserver) {\n this.onClearObservable.remove(this._onClearObserver);\n }\n this._onClearObserver = this.onClearObservable.add(callback);\n }\n /**\n * Gets the render pass ids used by the render target texture. For a single render target the array length will be 1, for a cube texture it will be 6 and for\n * a 2D texture array it will return an array of ids the size of the 2D texture array\n */\n get renderPassIds() {\n return this._renderPassIds;\n }\n /**\n * Gets the current value of the refreshId counter\n */\n get currentRefreshId() {\n return this._currentRefreshId;\n }\n /**\n * Sets a specific material to be used to render a mesh/a list of meshes in this render target texture\n * @param mesh mesh or array of meshes\n * @param material material or array of materials to use for this render pass. If undefined is passed, no specific material will be used but the regular material instead (mesh.material). It's possible to provide an array of materials to use a different material for each rendering in the case of a cube texture (6 rendering) and a 2D texture array (as many rendering as the length of the array)\n */\n setMaterialForRendering(mesh, material) {\n let meshes;\n if (!Array.isArray(mesh)) {\n meshes = [mesh];\n }\n else {\n meshes = mesh;\n }\n for (let j = 0; j < meshes.length; ++j) {\n for (let i = 0; i < this._renderPassIds.length; ++i) {\n meshes[j].setMaterialForRenderPass(this._renderPassIds[i], material !== undefined ? (Array.isArray(material) ? material[i] : material) : undefined);\n }\n }\n }\n /**\n * Define if the texture has multiple draw buffers or if false a single draw buffer.\n */\n get isMulti() {\n var _a, _b;\n return (_b = (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.isMulti) !== null && _b !== void 0 ? _b : false;\n }\n /**\n * Gets render target creation options that were used.\n */\n get renderTargetOptions() {\n return this._renderTargetOptions;\n }\n /**\n * Gets the render target wrapper associated with this render target\n */\n get renderTarget() {\n return this._renderTarget;\n }\n _onRatioRescale() {\n if (this._sizeRatio) {\n this.resize(this._initialSizeParameter);\n }\n }\n /**\n * Gets or sets the size of the bounding box associated with the texture (when in cube mode)\n * When defined, the cubemap will switch to local mode\n * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity\n * @example https://www.babylonjs-playground.com/#RNASML\n */\n set boundingBoxSize(value) {\n if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {\n return;\n }\n this._boundingBoxSize = value;\n const scene = this.getScene();\n if (scene) {\n scene.markAllMaterialsAsDirty(1);\n }\n }\n get boundingBoxSize() {\n return this._boundingBoxSize;\n }\n /**\n * In case the RTT has been created with a depth texture, get the associated\n * depth texture.\n * Otherwise, return null.\n */\n get depthStencilTexture() {\n var _a, _b;\n return (_b = (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a._depthStencilTexture) !== null && _b !== void 0 ? _b : null;\n }\n /** @internal */\n constructor(name, size, scene, generateMipMaps = false, doNotChangeAspectRatio = true, type = 0, isCube = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, generateDepthBuffer = true, generateStencilBuffer = false, isMulti = false, format = 5, delayAllocation = false, samples, creationFlags, noColorAttachment = false, useSRGBBuffer = false) {\n var _a, _b, _c, _d, _e, _f;\n let colorAttachment = undefined;\n if (typeof generateMipMaps === \"object\") {\n const options = generateMipMaps;\n generateMipMaps = !!options.generateMipMaps;\n doNotChangeAspectRatio = (_a = options.doNotChangeAspectRatio) !== null && _a !== void 0 ? _a : true;\n type = (_b = options.type) !== null && _b !== void 0 ? _b : 0;\n isCube = !!options.isCube;\n samplingMode = (_c = options.samplingMode) !== null && _c !== void 0 ? _c : Texture.TRILINEAR_SAMPLINGMODE;\n generateDepthBuffer = (_d = options.generateDepthBuffer) !== null && _d !== void 0 ? _d : true;\n generateStencilBuffer = !!options.generateStencilBuffer;\n isMulti = !!options.isMulti;\n format = (_e = options.format) !== null && _e !== void 0 ? _e : 5;\n delayAllocation = !!options.delayAllocation;\n samples = options.samples;\n creationFlags = options.creationFlags;\n noColorAttachment = !!options.noColorAttachment;\n useSRGBBuffer = !!options.useSRGBBuffer;\n colorAttachment = options.colorAttachment;\n }\n super(null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format);\n this._unObserveRenderList = null;\n this._renderListHasChanged = (_functionName, previousLength) => {\n var _a;\n const newLength = this._renderList ? this._renderList.length : 0;\n if ((previousLength === 0 && newLength > 0) || newLength === 0) {\n (_a = this.getScene()) === null || _a === void 0 ? void 0 : _a.meshes.forEach((mesh) => {\n mesh._markSubMeshesAsLightDirty();\n });\n }\n };\n /**\n * Define if particles should be rendered in your texture.\n */\n this.renderParticles = true;\n /**\n * Define if sprites should be rendered in your texture.\n */\n this.renderSprites = false;\n /**\n * Force checking the layerMask property even if a custom list of meshes is provided (ie. if renderList is not undefined)\n */\n this.forceLayerMaskCheck = false;\n /**\n * Define if the camera viewport should be respected while rendering the texture or if the render should be done to the entire texture.\n */\n this.ignoreCameraViewport = false;\n /**\n * An event triggered when the texture is unbind.\n */\n this.onBeforeBindObservable = new Observable();\n /**\n * An event triggered when the texture is unbind.\n */\n this.onAfterUnbindObservable = new Observable();\n /**\n * An event triggered before rendering the texture\n */\n this.onBeforeRenderObservable = new Observable();\n /**\n * An event triggered after rendering the texture\n */\n this.onAfterRenderObservable = new Observable();\n /**\n * An event triggered after the texture clear\n */\n this.onClearObservable = new Observable();\n /**\n * An event triggered when the texture is resized.\n */\n this.onResizeObservable = new Observable();\n /** @internal */\n this._cleared = false;\n /**\n * Skip the initial clear of the rtt at the beginning of the frame render loop\n */\n this.skipInitialClear = false;\n this._currentRefreshId = -1;\n this._refreshRate = 1;\n this._samples = 1;\n this._canRescale = true;\n this._renderTarget = null;\n /**\n * Gets or sets the center of the bounding box associated with the texture (when in cube mode)\n * It must define where the camera used to render the texture is set\n */\n this.boundingBoxPosition = Vector3.Zero();\n scene = this.getScene();\n if (!scene) {\n return;\n }\n const engine = this.getScene().getEngine();\n this._coordinatesMode = Texture.PROJECTION_MODE;\n this.renderList = new Array();\n this.name = name;\n this.isRenderTarget = true;\n this._initialSizeParameter = size;\n this._renderPassIds = [];\n this._isCubeData = isCube;\n this._processSizeParameter(size);\n this.renderPassId = this._renderPassIds[0];\n this._resizeObserver = engine.onResizeObservable.add(() => { });\n this._generateMipMaps = generateMipMaps ? true : false;\n this._doNotChangeAspectRatio = doNotChangeAspectRatio;\n // Rendering groups\n this._renderingManager = new RenderingManager(scene);\n this._renderingManager._useSceneAutoClearSetup = true;\n if (isMulti) {\n return;\n }\n this._renderTargetOptions = {\n generateMipMaps: generateMipMaps,\n type: type,\n format: (_f = this._format) !== null && _f !== void 0 ? _f : undefined,\n samplingMode: this.samplingMode,\n generateDepthBuffer: generateDepthBuffer,\n generateStencilBuffer: generateStencilBuffer,\n samples,\n creationFlags,\n noColorAttachment: noColorAttachment,\n useSRGBBuffer,\n colorAttachment: colorAttachment,\n label: this.name,\n };\n if (this.samplingMode === Texture.NEAREST_SAMPLINGMODE) {\n this.wrapU = Texture.CLAMP_ADDRESSMODE;\n this.wrapV = Texture.CLAMP_ADDRESSMODE;\n }\n if (!delayAllocation) {\n if (isCube) {\n this._renderTarget = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);\n this.coordinatesMode = Texture.INVCUBIC_MODE;\n this._textureMatrix = Matrix.Identity();\n }\n else {\n this._renderTarget = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);\n }\n this._texture = this._renderTarget.texture;\n if (samples !== undefined) {\n this.samples = samples;\n }\n }\n }\n /**\n * Creates a depth stencil texture.\n * This is only available in WebGL 2 or with the depth texture extension available.\n * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode (default: 0)\n * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture (default: true)\n * @param generateStencil Specifies whether or not a stencil should be allocated in the texture (default: false)\n * @param samples sample count of the depth/stencil texture (default: 1)\n * @param format format of the depth texture (default: 14)\n */\n createDepthStencilTexture(comparisonFunction = 0, bilinearFiltering = true, generateStencil = false, samples = 1, format = 14) {\n var _a;\n (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.createDepthStencilTexture(comparisonFunction, bilinearFiltering, generateStencil, samples, format);\n }\n _releaseRenderPassId() {\n if (this._scene) {\n const engine = this._scene.getEngine();\n for (let i = 0; i < this._renderPassIds.length; ++i) {\n engine.releaseRenderPassId(this._renderPassIds[i]);\n }\n }\n this._renderPassIds = [];\n }\n _createRenderPassId() {\n this._releaseRenderPassId();\n const engine = this._scene.getEngine(); // scene can't be null in a RenderTargetTexture, see constructor\n const numPasses = this._isCubeData ? 6 : this.getRenderLayers() || 1;\n for (let i = 0; i < numPasses; ++i) {\n this._renderPassIds[i] = engine.createRenderPassId(`RenderTargetTexture - ${this.name}#${i}`);\n }\n }\n _processSizeParameter(size, createRenderPassIds = true) {\n if (size.ratio) {\n this._sizeRatio = size.ratio;\n const engine = this._getEngine();\n this._size = {\n width: this._bestReflectionRenderTargetDimension(engine.getRenderWidth(), this._sizeRatio),\n height: this._bestReflectionRenderTargetDimension(engine.getRenderHeight(), this._sizeRatio),\n };\n }\n else {\n this._size = size;\n }\n if (createRenderPassIds) {\n this._createRenderPassId();\n }\n }\n /**\n * Define the number of samples to use in case of MSAA.\n * It defaults to one meaning no MSAA has been enabled.\n */\n get samples() {\n var _a, _b;\n return (_b = (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.samples) !== null && _b !== void 0 ? _b : this._samples;\n }\n set samples(value) {\n if (this._renderTarget) {\n this._samples = this._renderTarget.setSamples(value);\n }\n }\n /**\n * Resets the refresh counter of the texture and start bak from scratch.\n * Could be useful to regenerate the texture if it is setup to render only once.\n */\n resetRefreshCounter() {\n this._currentRefreshId = -1;\n }\n /**\n * Define the refresh rate of the texture or the rendering frequency.\n * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...\n */\n get refreshRate() {\n return this._refreshRate;\n }\n set refreshRate(value) {\n this._refreshRate = value;\n this.resetRefreshCounter();\n }\n /**\n * Adds a post process to the render target rendering passes.\n * @param postProcess define the post process to add\n */\n addPostProcess(postProcess) {\n if (!this._postProcessManager) {\n const scene = this.getScene();\n if (!scene) {\n return;\n }\n this._postProcessManager = new PostProcessManager(scene);\n this._postProcesses = new Array();\n }\n this._postProcesses.push(postProcess);\n this._postProcesses[0].autoClear = false;\n }\n /**\n * Clear all the post processes attached to the render target\n * @param dispose define if the cleared post processes should also be disposed (false by default)\n */\n clearPostProcesses(dispose = false) {\n if (!this._postProcesses) {\n return;\n }\n if (dispose) {\n for (const postProcess of this._postProcesses) {\n postProcess.dispose();\n }\n }\n this._postProcesses = [];\n }\n /**\n * Remove one of the post process from the list of attached post processes to the texture\n * @param postProcess define the post process to remove from the list\n */\n removePostProcess(postProcess) {\n if (!this._postProcesses) {\n return;\n }\n const index = this._postProcesses.indexOf(postProcess);\n if (index === -1) {\n return;\n }\n this._postProcesses.splice(index, 1);\n if (this._postProcesses.length > 0) {\n this._postProcesses[0].autoClear = false;\n }\n }\n /** @internal */\n _shouldRender() {\n if (this._currentRefreshId === -1) {\n // At least render once\n this._currentRefreshId = 1;\n return true;\n }\n if (this.refreshRate === this._currentRefreshId) {\n this._currentRefreshId = 1;\n return true;\n }\n this._currentRefreshId++;\n return false;\n }\n /**\n * Gets the actual render size of the texture.\n * @returns the width of the render size\n */\n getRenderSize() {\n return this.getRenderWidth();\n }\n /**\n * Gets the actual render width of the texture.\n * @returns the width of the render size\n */\n getRenderWidth() {\n if (this._size.width) {\n return this._size.width;\n }\n return this._size;\n }\n /**\n * Gets the actual render height of the texture.\n * @returns the height of the render size\n */\n getRenderHeight() {\n if (this._size.width) {\n return this._size.height;\n }\n return this._size;\n }\n /**\n * Gets the actual number of layers of the texture.\n * @returns the number of layers\n */\n getRenderLayers() {\n const layers = this._size.layers;\n if (layers) {\n return layers;\n }\n return 0;\n }\n /**\n * Don't allow this render target texture to rescale. Mainly used to prevent rescaling by the scene optimizer.\n */\n disableRescaling() {\n this._canRescale = false;\n }\n /**\n * Get if the texture can be rescaled or not.\n */\n get canRescale() {\n return this._canRescale;\n }\n /**\n * Resize the texture using a ratio.\n * @param ratio the ratio to apply to the texture size in order to compute the new target size\n */\n scale(ratio) {\n const newSize = Math.max(1, this.getRenderSize() * ratio);\n this.resize(newSize);\n }\n /**\n * Get the texture reflection matrix used to rotate/transform the reflection.\n * @returns the reflection matrix\n */\n getReflectionTextureMatrix() {\n if (this.isCube) {\n return this._textureMatrix;\n }\n return super.getReflectionTextureMatrix();\n }\n /**\n * Resize the texture to a new desired size.\n * Be careful as it will recreate all the data in the new texture.\n * @param size Define the new size. It can be:\n * - a number for squared texture,\n * - an object containing { width: number, height: number }\n * - or an object containing a ratio { ratio: number }\n */\n resize(size) {\n var _a;\n const wasCube = this.isCube;\n (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.dispose();\n this._renderTarget = null;\n const scene = this.getScene();\n if (!scene) {\n return;\n }\n this._processSizeParameter(size, false);\n if (wasCube) {\n this._renderTarget = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);\n }\n else {\n this._renderTarget = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);\n }\n this._texture = this._renderTarget.texture;\n if (this._renderTargetOptions.samples !== undefined) {\n this.samples = this._renderTargetOptions.samples;\n }\n if (this.onResizeObservable.hasObservers()) {\n this.onResizeObservable.notifyObservers(this);\n }\n }\n /**\n * Renders all the objects from the render list into the texture.\n * @param useCameraPostProcess Define if camera post processes should be used during the rendering\n * @param dumpForDebug Define if the rendering result should be dumped (copied) for debugging purpose\n */\n render(useCameraPostProcess = false, dumpForDebug = false) {\n this._render(useCameraPostProcess, dumpForDebug);\n }\n /**\n * This function will check if the render target texture can be rendered (textures are loaded, shaders are compiled)\n * @returns true if all required resources are ready\n */\n isReadyForRendering() {\n return this._render(false, false, true);\n }\n _render(useCameraPostProcess = false, dumpForDebug = false, checkReadiness = false) {\n var _a;\n const scene = this.getScene();\n if (!scene) {\n return checkReadiness;\n }\n const engine = scene.getEngine();\n if (this.useCameraPostProcesses !== undefined) {\n useCameraPostProcess = this.useCameraPostProcesses;\n }\n if (this._waitingRenderList) {\n this.renderList = [];\n for (let index = 0; index < this._waitingRenderList.length; index++) {\n const id = this._waitingRenderList[index];\n const mesh = scene.getMeshById(id);\n if (mesh) {\n this.renderList.push(mesh);\n }\n }\n this._waitingRenderList = undefined;\n }\n // Is predicate defined?\n if (this.renderListPredicate) {\n if (this.renderList) {\n this.renderList.length = 0; // Clear previous renderList\n }\n else {\n this.renderList = [];\n }\n const scene = this.getScene();\n if (!scene) {\n return checkReadiness;\n }\n const sceneMeshes = scene.meshes;\n for (let index = 0; index < sceneMeshes.length; index++) {\n const mesh = sceneMeshes[index];\n if (this.renderListPredicate(mesh)) {\n this.renderList.push(mesh);\n }\n }\n }\n const currentRenderPassId = engine.currentRenderPassId;\n this.onBeforeBindObservable.notifyObservers(this);\n // Set custom projection.\n // Needs to be before binding to prevent changing the aspect ratio.\n const camera = (_a = this.activeCamera) !== null && _a !== void 0 ? _a : scene.activeCamera;\n const sceneCamera = scene.activeCamera;\n if (camera) {\n if (camera !== scene.activeCamera) {\n scene.setTransformMatrix(camera.getViewMatrix(), camera.getProjectionMatrix(true));\n scene.activeCamera = camera;\n }\n engine.setViewport(camera.rigParent ? camera.rigParent.viewport : camera.viewport, this.getRenderWidth(), this.getRenderHeight());\n }\n this._defaultRenderListPrepared = false;\n let returnValue = checkReadiness;\n if (!checkReadiness) {\n if (this.is2DArray && !this.isMulti) {\n for (let layer = 0; layer < this.getRenderLayers(); layer++) {\n this._renderToTarget(0, useCameraPostProcess, dumpForDebug, layer, camera);\n scene.incrementRenderId();\n scene.resetCachedMaterial();\n }\n }\n else if (this.isCube && !this.isMulti) {\n for (let face = 0; face < 6; face++) {\n this._renderToTarget(face, useCameraPostProcess, dumpForDebug, undefined, camera);\n scene.incrementRenderId();\n scene.resetCachedMaterial();\n }\n }\n else {\n this._renderToTarget(0, useCameraPostProcess, dumpForDebug, undefined, camera);\n }\n }\n else {\n if (!scene.getViewMatrix()) {\n // We probably didn't execute scene.render() yet, so make sure we have a view/projection matrix setup for the scene\n scene.updateTransformMatrix();\n }\n const numLayers = this.is2DArray ? this.getRenderLayers() : this.isCube ? 6 : 1;\n for (let layer = 0; layer < numLayers && returnValue; layer++) {\n let currentRenderList = null;\n const defaultRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;\n const defaultRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;\n engine.currentRenderPassId = this._renderPassIds[layer];\n this.onBeforeRenderObservable.notifyObservers(layer);\n if (this.getCustomRenderList) {\n currentRenderList = this.getCustomRenderList(layer, defaultRenderList, defaultRenderListLength);\n }\n if (!currentRenderList) {\n currentRenderList = defaultRenderList;\n }\n if (!this._doNotChangeAspectRatio) {\n scene.updateTransformMatrix(true);\n }\n for (let i = 0; i < currentRenderList.length && returnValue; ++i) {\n const mesh = currentRenderList[i];\n if (!mesh.isEnabled() || mesh.isBlocked || !mesh.isVisible || !mesh.subMeshes) {\n continue;\n }\n if (this.customIsReadyFunction) {\n if (!this.customIsReadyFunction(mesh, this.refreshRate, checkReadiness)) {\n returnValue = false;\n continue;\n }\n }\n else if (!mesh.isReady(true)) {\n returnValue = false;\n continue;\n }\n }\n this.onAfterRenderObservable.notifyObservers(layer);\n if (this.is2DArray || this.isCube) {\n scene.incrementRenderId();\n scene.resetCachedMaterial();\n }\n }\n }\n this.onAfterUnbindObservable.notifyObservers(this);\n engine.currentRenderPassId = currentRenderPassId;\n if (sceneCamera) {\n scene.activeCamera = sceneCamera;\n // Do not avoid setting uniforms when multiple scenes are active as another camera may have overwrite these\n if (scene.getEngine().scenes.length > 1 || (this.activeCamera && this.activeCamera !== scene.activeCamera)) {\n scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));\n }\n engine.setViewport(scene.activeCamera.viewport);\n }\n scene.resetCachedMaterial();\n return returnValue;\n }\n _bestReflectionRenderTargetDimension(renderDimension, scale) {\n const minimum = 128;\n const x = renderDimension * scale;\n const curved = Engine.NearestPOT(x + (minimum * minimum) / (minimum + x));\n // Ensure we don't exceed the render dimension (while staying POT)\n return Math.min(Engine.FloorPOT(renderDimension), curved);\n }\n _prepareRenderingManager(currentRenderList, currentRenderListLength, camera, checkLayerMask) {\n const scene = this.getScene();\n if (!scene) {\n return;\n }\n this._renderingManager.reset();\n const sceneRenderId = scene.getRenderId();\n for (let meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {\n const mesh = currentRenderList[meshIndex];\n if (mesh && !mesh.isBlocked) {\n if (this.customIsReadyFunction) {\n if (!this.customIsReadyFunction(mesh, this.refreshRate, false)) {\n this.resetRefreshCounter();\n continue;\n }\n }\n else if (!mesh.isReady(this.refreshRate === 0)) {\n this.resetRefreshCounter();\n continue;\n }\n if (!mesh._internalAbstractMeshDataInfo._currentLODIsUpToDate && scene.activeCamera) {\n mesh._internalAbstractMeshDataInfo._currentLOD = scene.customLODSelector\n ? scene.customLODSelector(mesh, this.activeCamera || scene.activeCamera)\n : mesh.getLOD(this.activeCamera || scene.activeCamera);\n mesh._internalAbstractMeshDataInfo._currentLODIsUpToDate = true;\n }\n if (!mesh._internalAbstractMeshDataInfo._currentLOD) {\n continue;\n }\n let meshToRender = mesh._internalAbstractMeshDataInfo._currentLOD;\n meshToRender._preActivateForIntermediateRendering(sceneRenderId);\n let isMasked;\n if (checkLayerMask && camera) {\n isMasked = (mesh.layerMask & camera.layerMask) === 0;\n }\n else {\n isMasked = false;\n }\n if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {\n if (meshToRender !== mesh) {\n meshToRender._activate(sceneRenderId, true);\n }\n if (mesh._activate(sceneRenderId, true) && mesh.subMeshes.length) {\n if (!mesh.isAnInstance) {\n meshToRender._internalAbstractMeshDataInfo._onlyForInstancesIntermediate = false;\n }\n else {\n if (mesh._internalAbstractMeshDataInfo._actAsRegularMesh) {\n meshToRender = mesh;\n }\n }\n meshToRender._internalAbstractMeshDataInfo._isActiveIntermediate = true;\n for (let subIndex = 0; subIndex < meshToRender.subMeshes.length; subIndex++) {\n const subMesh = meshToRender.subMeshes[subIndex];\n this._renderingManager.dispatch(subMesh, meshToRender);\n }\n }\n }\n }\n }\n for (let particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {\n const particleSystem = scene.particleSystems[particleIndex];\n const emitter = particleSystem.emitter;\n if (!particleSystem.isStarted() || !emitter || (emitter.position && !emitter.isEnabled())) {\n continue;\n }\n this._renderingManager.dispatchParticles(particleSystem);\n }\n }\n /**\n * @internal\n * @param faceIndex face index to bind to if this is a cubetexture\n * @param layer defines the index of the texture to bind in the array\n */\n _bindFrameBuffer(faceIndex = 0, layer = 0) {\n const scene = this.getScene();\n if (!scene) {\n return;\n }\n const engine = scene.getEngine();\n if (this._renderTarget) {\n engine.bindFramebuffer(this._renderTarget, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, 0, layer);\n }\n }\n _unbindFrameBuffer(engine, faceIndex) {\n if (!this._renderTarget) {\n return;\n }\n engine.unBindFramebuffer(this._renderTarget, this.isCube, () => {\n this.onAfterRenderObservable.notifyObservers(faceIndex);\n });\n }\n /**\n * @internal\n */\n _prepareFrame(scene, faceIndex, layer, useCameraPostProcess) {\n if (this._postProcessManager) {\n if (!this._prePassEnabled) {\n this._postProcessManager._prepareFrame(this._texture, this._postProcesses);\n }\n }\n else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {\n this._bindFrameBuffer(faceIndex, layer);\n }\n }\n _renderToTarget(faceIndex, useCameraPostProcess, dumpForDebug, layer = 0, camera = null) {\n var _a, _b, _c, _d, _e, _f;\n const scene = this.getScene();\n if (!scene) {\n return;\n }\n const engine = scene.getEngine();\n (_a = engine._debugPushGroup) === null || _a === void 0 ? void 0 : _a.call(engine, `render to face #${faceIndex} layer #${layer}`, 1);\n // Bind\n this._prepareFrame(scene, faceIndex, layer, useCameraPostProcess);\n if (this.is2DArray) {\n engine.currentRenderPassId = this._renderPassIds[layer];\n this.onBeforeRenderObservable.notifyObservers(layer);\n }\n else {\n engine.currentRenderPassId = this._renderPassIds[faceIndex];\n this.onBeforeRenderObservable.notifyObservers(faceIndex);\n }\n const fastPath = engine.snapshotRendering && engine.snapshotRenderingMode === 1;\n if (!fastPath) {\n // Get the list of meshes to render\n let currentRenderList = null;\n const defaultRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;\n const defaultRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;\n if (this.getCustomRenderList) {\n currentRenderList = this.getCustomRenderList(this.is2DArray ? layer : faceIndex, defaultRenderList, defaultRenderListLength);\n }\n if (!currentRenderList) {\n // No custom render list provided, we prepare the rendering for the default list, but check\n // first if we did not already performed the preparation before so as to avoid re-doing it several times\n if (!this._defaultRenderListPrepared) {\n this._prepareRenderingManager(defaultRenderList, defaultRenderListLength, camera, !this.renderList || this.forceLayerMaskCheck);\n this._defaultRenderListPrepared = true;\n }\n currentRenderList = defaultRenderList;\n }\n else {\n // Prepare the rendering for the custom render list provided\n this._prepareRenderingManager(currentRenderList, currentRenderList.length, camera, this.forceLayerMaskCheck);\n }\n // Before clear\n for (const step of scene._beforeRenderTargetClearStage) {\n step.action(this, faceIndex, layer);\n }\n // Clear\n if (this.onClearObservable.hasObservers()) {\n this.onClearObservable.notifyObservers(engine);\n }\n else {\n if (!this.skipInitialClear) {\n engine.clear(this.clearColor || scene.clearColor, true, true, true);\n }\n }\n if (!this._doNotChangeAspectRatio) {\n scene.updateTransformMatrix(true);\n }\n // Before Camera Draw\n for (const step of scene._beforeRenderTargetDrawStage) {\n step.action(this, faceIndex, layer);\n }\n // Render\n this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);\n // After Camera Draw\n for (const step of scene._afterRenderTargetDrawStage) {\n step.action(this, faceIndex, layer);\n }\n const saveGenerateMipMaps = (_c = (_b = this._texture) === null || _b === void 0 ? void 0 : _b.generateMipMaps) !== null && _c !== void 0 ? _c : false;\n if (this._texture) {\n this._texture.generateMipMaps = false; // if left true, the mipmaps will be generated (if this._texture.generateMipMaps = true) when the first post process binds its own RTT: by doing so it will unbind the current RTT,\n // which will trigger a mipmap generation. We don't want this because it's a wasted work, we will do an unbind of the current RTT at the end of the process (see unbindFrameBuffer) which will\n // trigger the generation of the final mipmaps\n }\n if (this._postProcessManager) {\n this._postProcessManager._finalizeFrame(false, (_d = this._renderTarget) !== null && _d !== void 0 ? _d : undefined, faceIndex, this._postProcesses, this.ignoreCameraViewport);\n }\n else if (useCameraPostProcess) {\n scene.postProcessManager._finalizeFrame(false, (_e = this._renderTarget) !== null && _e !== void 0 ? _e : undefined, faceIndex);\n }\n for (const step of scene._afterRenderTargetPostProcessStage) {\n step.action(this, faceIndex, layer);\n }\n if (this._texture) {\n this._texture.generateMipMaps = saveGenerateMipMaps;\n }\n if (!this._doNotChangeAspectRatio) {\n scene.updateTransformMatrix(true);\n }\n // Dump ?\n if (dumpForDebug) {\n DumpTools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);\n }\n }\n else {\n // Clear\n if (this.onClearObservable.hasObservers()) {\n this.onClearObservable.notifyObservers(engine);\n }\n else {\n if (!this.skipInitialClear) {\n engine.clear(this.clearColor || scene.clearColor, true, true, true);\n }\n }\n }\n // Unbind\n this._unbindFrameBuffer(engine, faceIndex);\n if (this._texture && this.isCube && faceIndex === 5) {\n engine.generateMipMapsForCubemap(this._texture);\n }\n (_f = engine._debugPopGroup) === null || _f === void 0 ? void 0 : _f.call(engine, 1);\n }\n /**\n * Overrides the default sort function applied in the rendering group to prepare the meshes.\n * This allowed control for front to back rendering or reversely depending of the special needs.\n *\n * @param renderingGroupId The rendering group id corresponding to its index\n * @param opaqueSortCompareFn The opaque queue comparison function use to sort.\n * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.\n * @param transparentSortCompareFn The transparent queue comparison function use to sort.\n */\n setRenderingOrder(renderingGroupId, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) {\n this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);\n }\n /**\n * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.\n *\n * @param renderingGroupId The rendering group id corresponding to its index\n * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.\n */\n setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil) {\n this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);\n this._renderingManager._useSceneAutoClearSetup = false;\n }\n /**\n * Clones the texture.\n * @returns the cloned texture\n */\n clone() {\n const textureSize = this.getSize();\n const newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer, undefined, this._renderTargetOptions.format, undefined, this._renderTargetOptions.samples);\n // Base texture\n newTexture.hasAlpha = this.hasAlpha;\n newTexture.level = this.level;\n // RenderTarget Texture\n newTexture.coordinatesMode = this.coordinatesMode;\n if (this.renderList) {\n newTexture.renderList = this.renderList.slice(0);\n }\n return newTexture;\n }\n /**\n * Serialize the texture to a JSON representation we can easily use in the respective Parse function.\n * @returns The JSON representation of the texture\n */\n serialize() {\n if (!this.name) {\n return null;\n }\n const serializationObject = super.serialize();\n serializationObject.renderTargetSize = this.getRenderSize();\n serializationObject.renderList = [];\n if (this.renderList) {\n for (let index = 0; index < this.renderList.length; index++) {\n serializationObject.renderList.push(this.renderList[index].id);\n }\n }\n return serializationObject;\n }\n /**\n * This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore\n */\n disposeFramebufferObjects() {\n var _a;\n (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.dispose(true);\n }\n /**\n * Release and destroy the underlying lower level texture aka internalTexture.\n */\n releaseInternalTexture() {\n var _a;\n (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.releaseTextures();\n this._texture = null;\n }\n /**\n * Dispose the texture and release its associated resources.\n */\n dispose() {\n var _a;\n this.onResizeObservable.clear();\n this.onClearObservable.clear();\n this.onAfterRenderObservable.clear();\n this.onAfterUnbindObservable.clear();\n this.onBeforeBindObservable.clear();\n this.onBeforeRenderObservable.clear();\n if (this._postProcessManager) {\n this._postProcessManager.dispose();\n this._postProcessManager = null;\n }\n if (this._prePassRenderTarget) {\n this._prePassRenderTarget.dispose();\n }\n this._releaseRenderPassId();\n this.clearPostProcesses(true);\n if (this._resizeObserver) {\n this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);\n this._resizeObserver = null;\n }\n this.renderList = null;\n // Remove from custom render targets\n const scene = this.getScene();\n if (!scene) {\n return;\n }\n let index = scene.customRenderTargets.indexOf(this);\n if (index >= 0) {\n scene.customRenderTargets.splice(index, 1);\n }\n for (const camera of scene.cameras) {\n index = camera.customRenderTargets.indexOf(this);\n if (index >= 0) {\n camera.customRenderTargets.splice(index, 1);\n }\n }\n (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.dispose();\n this._renderTarget = null;\n this._texture = null;\n super.dispose();\n }\n /** @internal */\n _rebuild() {\n if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {\n this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;\n }\n if (this._postProcessManager) {\n this._postProcessManager._rebuild();\n }\n }\n /**\n * Clear the info related to rendering groups preventing retention point in material dispose.\n */\n freeRenderingGroups() {\n if (this._renderingManager) {\n this._renderingManager.freeRenderingGroups();\n }\n }\n /**\n * Gets the number of views the corresponding to the texture (eg. a MultiviewRenderTarget will have > 1)\n * @returns the view count\n */\n getViewCount() {\n return 1;\n }\n}\n/**\n * The texture will only be rendered once which can be useful to improve performance if everything in your render is static for instance.\n */\nRenderTargetTexture.REFRESHRATE_RENDER_ONCE = 0;\n/**\n * The texture will only be rendered rendered every frame and is recommended for dynamic contents.\n */\nRenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME = 1;\n/**\n * The texture will be rendered every 2 frames which could be enough if your dynamic objects are not\n * the central point of your effect and can save a lot of performances.\n */\nRenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nTexture._CreateRenderTargetTexture = (name, renderTargetSize, scene, generateMipMaps, creationFlags) => {\n return new RenderTargetTexture(name, renderTargetSize, scene, generateMipMaps);\n};\n//# sourceMappingURL=renderTargetTexture.js.map","import { Tools } from \"../../../Misc/tools.js\";\nimport { SceneComponentConstants } from \"../../../sceneComponent.js\";\n/**\n * Defines the Procedural Texture scene component responsible to manage any Procedural Texture\n * in a given scene.\n */\nexport class ProceduralTextureSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpful to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_PROCEDURALTEXTURE;\n this.scene = scene;\n this.scene.proceduralTextures = new Array();\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene._beforeClearStage.registerStep(SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n // Nothing to do here.\n }\n /**\n * Disposes the component and the associated resources.\n */\n dispose() {\n // Nothing to do here.\n }\n _beforeClear() {\n if (this.scene.proceduralTexturesEnabled) {\n Tools.StartPerformanceCounter(\"Procedural textures\", this.scene.proceduralTextures.length > 0);\n for (let proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {\n const proceduralTexture = this.scene.proceduralTextures[proceduralIndex];\n if (proceduralTexture._shouldRender()) {\n proceduralTexture.render();\n }\n }\n Tools.EndPerformanceCounter(\"Procedural textures\", this.scene.proceduralTextures.length > 0);\n }\n }\n}\n//# sourceMappingURL=proceduralTextureSceneComponent.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"proceduralVertexShader\";\nconst shader = `attribute vec2 position;\rvarying vec2 vPosition;\rvarying vec2 vUV;\rconst vec2 madd=vec2(0.5,0.5);\r#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_VERTEX_MAIN_BEGIN\nvPosition=position;\rvUV=position*madd+madd;\rgl_Position=vec4(position,0.0,1.0);\r#define CUSTOM_VERTEX_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const proceduralVertexShader = { name, shader };\n//# sourceMappingURL=procedural.vertex.js.map","import { __decorate } from \"../../../tslib.es6.js\";\nimport { serialize } from \"../../../Misc/decorators.js\";\nimport { Observable } from \"../../../Misc/observable.js\";\nimport { VertexBuffer } from \"../../../Buffers/buffer.js\";\nimport { SceneComponentConstants } from \"../../../sceneComponent.js\";\nimport { Material } from \"../../../Materials/material.js\";\nimport { Texture } from \"../../../Materials/Textures/texture.js\";\nimport { RenderTargetTexture } from \"../../../Materials/Textures/renderTargetTexture.js\";\nimport { ProceduralTextureSceneComponent } from \"./proceduralTextureSceneComponent.js\";\nimport \"../../../Engines/Extensions/engine.renderTarget.js\";\nimport \"../../../Engines/Extensions/engine.renderTargetCube.js\";\nimport \"../../../Shaders/procedural.vertex.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { EngineStore } from \"../../../Engines/engineStore.js\";\n\nimport { DrawWrapper } from \"../../drawWrapper.js\";\n/**\n * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes calmpler' images.\n * This is the base class of any Procedural texture and contains most of the shareable code.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/proceduralTextures\n */\nexport class ProceduralTexture extends Texture {\n /**\n * Instantiates a new procedural texture.\n * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.\n * This is the base class of any Procedural texture and contains most of the shareable code.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/proceduralTextures\n * @param name Define the name of the texture\n * @param size Define the size of the texture to create\n * @param fragment Define the fragment shader to use to generate the texture or null if it is defined later\n * @param scene Define the scene the texture belongs to\n * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture\n * @param generateMipMaps Define if the texture should creates mip maps or not\n * @param isCube Define if the texture is a cube texture or not (this will render each faces of the cube)\n * @param textureType The FBO internal texture type\n */\n constructor(name, size, fragment, scene, fallbackTexture = null, generateMipMaps = true, isCube = false, textureType = 0) {\n super(null, scene, !generateMipMaps);\n /**\n * Define if the texture is enabled or not (disabled texture will not render)\n */\n this.isEnabled = true;\n /**\n * Define if the texture must be cleared before rendering (default is true)\n */\n this.autoClear = true;\n /**\n * Event raised when the texture is generated\n */\n this.onGeneratedObservable = new Observable();\n /**\n * Event raised before the texture is generated\n */\n this.onBeforeGenerationObservable = new Observable();\n /**\n * Gets or sets the node material used to create this texture (null if the texture was manually created)\n */\n this.nodeMaterialSource = null;\n /** @internal */\n this._textures = {};\n this._currentRefreshId = -1;\n this._frameId = -1;\n this._refreshRate = 1;\n this._vertexBuffers = {};\n this._uniforms = new Array();\n this._samplers = new Array();\n this._floats = {};\n this._ints = {};\n this._floatsArrays = {};\n this._colors3 = {};\n this._colors4 = {};\n this._vectors2 = {};\n this._vectors3 = {};\n this._matrices = {};\n this._fallbackTextureUsed = false;\n this._cachedDefines = null;\n this._contentUpdateId = -1;\n this._rtWrapper = null;\n scene = this.getScene() || EngineStore.LastCreatedScene;\n let component = scene._getComponent(SceneComponentConstants.NAME_PROCEDURALTEXTURE);\n if (!component) {\n component = new ProceduralTextureSceneComponent(scene);\n scene._addComponent(component);\n }\n scene.proceduralTextures.push(this);\n this._fullEngine = scene.getEngine();\n this.name = name;\n this.isRenderTarget = true;\n this._size = size;\n this._textureType = textureType;\n this._generateMipMaps = generateMipMaps;\n this._drawWrapper = new DrawWrapper(this._fullEngine);\n this.setFragment(fragment);\n this._fallbackTexture = fallbackTexture;\n const rtWrapper = this._createRtWrapper(isCube, size, generateMipMaps, textureType);\n this._texture = rtWrapper.texture;\n // VBO\n const vertices = [];\n vertices.push(1, 1);\n vertices.push(-1, 1);\n vertices.push(-1, -1);\n vertices.push(1, -1);\n this._vertexBuffers[VertexBuffer.PositionKind] = new VertexBuffer(this._fullEngine, vertices, VertexBuffer.PositionKind, false, false, 2);\n this._createIndexBuffer();\n }\n _createRtWrapper(isCube, size, generateMipMaps, textureType) {\n if (isCube) {\n this._rtWrapper = this._fullEngine.createRenderTargetCubeTexture(size, {\n generateMipMaps: generateMipMaps,\n generateDepthBuffer: false,\n generateStencilBuffer: false,\n type: textureType,\n });\n this.setFloat(\"face\", 0);\n }\n else {\n this._rtWrapper = this._fullEngine.createRenderTargetTexture(size, {\n generateMipMaps: generateMipMaps,\n generateDepthBuffer: false,\n generateStencilBuffer: false,\n type: textureType,\n });\n }\n return this._rtWrapper;\n }\n /**\n * The effect that is created when initializing the post process.\n * @returns The created effect corresponding the the postprocess.\n */\n getEffect() {\n return this._drawWrapper.effect;\n }\n /**\n * @internal*\n */\n _setEffect(effect) {\n this._drawWrapper.effect = effect;\n }\n /**\n * Gets texture content (Use this function wisely as reading from a texture can be slow)\n * @returns an ArrayBufferView promise (Uint8Array or Float32Array)\n */\n getContent() {\n if (this._contentData && this._frameId === this._contentUpdateId) {\n return this._contentData;\n }\n if (this._contentData) {\n this._contentData.then((buffer) => {\n this._contentData = this.readPixels(0, 0, buffer);\n this._contentUpdateId = this._frameId;\n });\n }\n else {\n this._contentData = this.readPixels(0, 0);\n this._contentUpdateId = this._frameId;\n }\n return this._contentData;\n }\n _createIndexBuffer() {\n const engine = this._fullEngine;\n // Indices\n const indices = [];\n indices.push(0);\n indices.push(1);\n indices.push(2);\n indices.push(0);\n indices.push(2);\n indices.push(3);\n this._indexBuffer = engine.createIndexBuffer(indices);\n }\n /** @internal */\n _rebuild() {\n const vb = this._vertexBuffers[VertexBuffer.PositionKind];\n if (vb) {\n vb._rebuild();\n }\n this._createIndexBuffer();\n if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {\n this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;\n }\n }\n /**\n * Resets the texture in order to recreate its associated resources.\n * This can be called in case of context loss\n */\n reset() {\n var _a;\n (_a = this._drawWrapper.effect) === null || _a === void 0 ? void 0 : _a.dispose();\n }\n _getDefines() {\n return \"\";\n }\n /**\n * Is the texture ready to be used ? (rendered at least once)\n * @returns true if ready, otherwise, false.\n */\n isReady() {\n const engine = this._fullEngine;\n let shaders;\n if (this.nodeMaterialSource) {\n return this._drawWrapper.effect.isReady();\n }\n if (!this._fragment) {\n return false;\n }\n if (this._fallbackTextureUsed) {\n return true;\n }\n if (!this._texture) {\n return false;\n }\n const defines = this._getDefines();\n if (this._drawWrapper.effect && defines === this._cachedDefines && this._drawWrapper.effect.isReady()) {\n return true;\n }\n if (this._fragment.fragmentElement !== undefined) {\n shaders = { vertex: \"procedural\", fragmentElement: this._fragment.fragmentElement };\n }\n else {\n shaders = { vertex: \"procedural\", fragment: this._fragment };\n }\n if (this._cachedDefines !== defines) {\n this._cachedDefines = defines;\n this._drawWrapper.effect = engine.createEffect(shaders, [VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, () => {\n var _a;\n (_a = this._rtWrapper) === null || _a === void 0 ? void 0 : _a.dispose();\n this._rtWrapper = this._texture = null;\n if (this._fallbackTexture) {\n this._texture = this._fallbackTexture._texture;\n if (this._texture) {\n this._texture.incrementReferences();\n }\n }\n this._fallbackTextureUsed = true;\n });\n }\n return this._drawWrapper.effect.isReady();\n }\n /**\n * Resets the refresh counter of the texture and start bak from scratch.\n * Could be useful to regenerate the texture if it is setup to render only once.\n */\n resetRefreshCounter() {\n this._currentRefreshId = -1;\n }\n /**\n * Set the fragment shader to use in order to render the texture.\n * @param fragment This can be set to a path (into the shader store) or to a json object containing a fragmentElement property.\n */\n setFragment(fragment) {\n this._fragment = fragment;\n }\n /**\n * Define the refresh rate of the texture or the rendering frequency.\n * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...\n */\n get refreshRate() {\n return this._refreshRate;\n }\n set refreshRate(value) {\n this._refreshRate = value;\n this.resetRefreshCounter();\n }\n /** @internal */\n _shouldRender() {\n if (!this.isEnabled || !this.isReady() || !this._texture) {\n if (this._texture) {\n this._texture.isReady = false;\n }\n return false;\n }\n if (this._fallbackTextureUsed) {\n return false;\n }\n if (this._currentRefreshId === -1) {\n // At least render once\n this._currentRefreshId = 1;\n this._frameId++;\n return true;\n }\n if (this.refreshRate === this._currentRefreshId) {\n this._currentRefreshId = 1;\n this._frameId++;\n return true;\n }\n this._currentRefreshId++;\n return false;\n }\n /**\n * Get the size the texture is rendering at.\n * @returns the size (on cube texture it is always squared)\n */\n getRenderSize() {\n return this._size;\n }\n /**\n * Resize the texture to new value.\n * @param size Define the new size the texture should have\n * @param generateMipMaps Define whether the new texture should create mip maps\n */\n resize(size, generateMipMaps) {\n if (this._fallbackTextureUsed || !this._rtWrapper || !this._texture) {\n return;\n }\n const isCube = this._texture.isCube;\n this._rtWrapper.dispose();\n const rtWrapper = this._createRtWrapper(isCube, size, generateMipMaps, this._textureType);\n this._texture = rtWrapper.texture;\n // Update properties\n this._size = size;\n this._generateMipMaps = generateMipMaps;\n }\n _checkUniform(uniformName) {\n if (this._uniforms.indexOf(uniformName) === -1) {\n this._uniforms.push(uniformName);\n }\n }\n /**\n * Set a texture in the shader program used to render.\n * @param name Define the name of the uniform samplers as defined in the shader\n * @param texture Define the texture to bind to this sampler\n * @returns the texture itself allowing \"fluent\" like uniform updates\n */\n setTexture(name, texture) {\n if (this._samplers.indexOf(name) === -1) {\n this._samplers.push(name);\n }\n this._textures[name] = texture;\n return this;\n }\n /**\n * Set a float in the shader.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the texture itself allowing \"fluent\" like uniform updates\n */\n setFloat(name, value) {\n this._checkUniform(name);\n this._floats[name] = value;\n return this;\n }\n /**\n * Set a int in the shader.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the texture itself allowing \"fluent\" like uniform updates\n */\n setInt(name, value) {\n this._checkUniform(name);\n this._ints[name] = value;\n return this;\n }\n /**\n * Set an array of floats in the shader.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the texture itself allowing \"fluent\" like uniform updates\n */\n setFloats(name, value) {\n this._checkUniform(name);\n this._floatsArrays[name] = value;\n return this;\n }\n /**\n * Set a vec3 in the shader from a Color3.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the texture itself allowing \"fluent\" like uniform updates\n */\n setColor3(name, value) {\n this._checkUniform(name);\n this._colors3[name] = value;\n return this;\n }\n /**\n * Set a vec4 in the shader from a Color4.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the texture itself allowing \"fluent\" like uniform updates\n */\n setColor4(name, value) {\n this._checkUniform(name);\n this._colors4[name] = value;\n return this;\n }\n /**\n * Set a vec2 in the shader from a Vector2.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the texture itself allowing \"fluent\" like uniform updates\n */\n setVector2(name, value) {\n this._checkUniform(name);\n this._vectors2[name] = value;\n return this;\n }\n /**\n * Set a vec3 in the shader from a Vector3.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the texture itself allowing \"fluent\" like uniform updates\n */\n setVector3(name, value) {\n this._checkUniform(name);\n this._vectors3[name] = value;\n return this;\n }\n /**\n * Set a mat4 in the shader from a MAtrix.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the texture itself allowing \"fluent\" like uniform updates\n */\n setMatrix(name, value) {\n this._checkUniform(name);\n this._matrices[name] = value;\n return this;\n }\n /**\n * Render the texture to its associated render target.\n * @param useCameraPostProcess Define if camera post process should be applied to the texture\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n render(useCameraPostProcess) {\n var _a, _b;\n const scene = this.getScene();\n if (!scene) {\n return;\n }\n const engine = this._fullEngine;\n // Render\n engine.enableEffect(this._drawWrapper);\n this.onBeforeGenerationObservable.notifyObservers(this);\n engine.setState(false);\n if (!this.nodeMaterialSource) {\n // Texture\n for (const name in this._textures) {\n this._drawWrapper.effect.setTexture(name, this._textures[name]);\n }\n // Float\n for (const name in this._ints) {\n this._drawWrapper.effect.setInt(name, this._ints[name]);\n }\n // Float\n for (const name in this._floats) {\n this._drawWrapper.effect.setFloat(name, this._floats[name]);\n }\n // Floats\n for (const name in this._floatsArrays) {\n this._drawWrapper.effect.setArray(name, this._floatsArrays[name]);\n }\n // Color3\n for (const name in this._colors3) {\n this._drawWrapper.effect.setColor3(name, this._colors3[name]);\n }\n // Color4\n for (const name in this._colors4) {\n const color = this._colors4[name];\n this._drawWrapper.effect.setFloat4(name, color.r, color.g, color.b, color.a);\n }\n // Vector2\n for (const name in this._vectors2) {\n this._drawWrapper.effect.setVector2(name, this._vectors2[name]);\n }\n // Vector3\n for (const name in this._vectors3) {\n this._drawWrapper.effect.setVector3(name, this._vectors3[name]);\n }\n // Matrix\n for (const name in this._matrices) {\n this._drawWrapper.effect.setMatrix(name, this._matrices[name]);\n }\n }\n if (!this._texture || !this._rtWrapper) {\n return;\n }\n (_a = engine._debugPushGroup) === null || _a === void 0 ? void 0 : _a.call(engine, `procedural texture generation for ${this.name}`, 1);\n const viewPort = engine.currentViewport;\n if (this.isCube) {\n for (let face = 0; face < 6; face++) {\n engine.bindFramebuffer(this._rtWrapper, face, undefined, undefined, true);\n // VBOs\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._drawWrapper.effect);\n this._drawWrapper.effect.setFloat(\"face\", face);\n // Clear\n if (this.autoClear) {\n engine.clear(scene.clearColor, true, false, false);\n }\n // Draw order\n engine.drawElementsType(Material.TriangleFillMode, 0, 6);\n }\n }\n else {\n engine.bindFramebuffer(this._rtWrapper, 0, undefined, undefined, true);\n // VBOs\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._drawWrapper.effect);\n // Clear\n if (this.autoClear) {\n engine.clear(scene.clearColor, true, false, false);\n }\n // Draw order\n engine.drawElementsType(Material.TriangleFillMode, 0, 6);\n }\n // Unbind and restore viewport\n engine.unBindFramebuffer(this._rtWrapper, this.isCube);\n if (viewPort) {\n engine.setViewport(viewPort);\n }\n // Mipmaps\n if (this.isCube) {\n engine.generateMipMapsForCubemap(this._texture);\n }\n (_b = engine._debugPopGroup) === null || _b === void 0 ? void 0 : _b.call(engine, 1);\n if (this.onGenerated) {\n this.onGenerated();\n }\n this.onGeneratedObservable.notifyObservers(this);\n }\n /**\n * Clone the texture.\n * @returns the cloned texture\n */\n clone() {\n const textureSize = this.getSize();\n const newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);\n // Base texture\n newTexture.hasAlpha = this.hasAlpha;\n newTexture.level = this.level;\n // RenderTarget Texture\n newTexture.coordinatesMode = this.coordinatesMode;\n return newTexture;\n }\n /**\n * Dispose the texture and release its associated resources.\n */\n dispose() {\n const scene = this.getScene();\n if (!scene) {\n return;\n }\n const index = scene.proceduralTextures.indexOf(this);\n if (index >= 0) {\n scene.proceduralTextures.splice(index, 1);\n }\n const vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];\n if (vertexBuffer) {\n vertexBuffer.dispose();\n this._vertexBuffers[VertexBuffer.PositionKind] = null;\n }\n if (this._indexBuffer && this._fullEngine._releaseBuffer(this._indexBuffer)) {\n this._indexBuffer = null;\n }\n this.onGeneratedObservable.clear();\n this.onBeforeGenerationObservable.clear();\n super.dispose();\n }\n}\n__decorate([\n serialize()\n], ProceduralTexture.prototype, \"isEnabled\", void 0);\n__decorate([\n serialize()\n], ProceduralTexture.prototype, \"autoClear\", void 0);\n__decorate([\n serialize()\n], ProceduralTexture.prototype, \"_generateMipMaps\", void 0);\n__decorate([\n serialize()\n], ProceduralTexture.prototype, \"_size\", void 0);\n__decorate([\n serialize()\n], ProceduralTexture.prototype, \"refreshRate\", null);\nRegisterClass(\"BABYLON.ProceduralTexture\", ProceduralTexture);\n//# sourceMappingURL=proceduralTexture.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Operations supported by the Trigonometry block\n */\nexport var TrigonometryBlockOperations;\n(function (TrigonometryBlockOperations) {\n /** Cos */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Cos\"] = 0] = \"Cos\";\n /** Sin */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Sin\"] = 1] = \"Sin\";\n /** Abs */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Abs\"] = 2] = \"Abs\";\n /** Exp */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Exp\"] = 3] = \"Exp\";\n /** Exp2 */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Exp2\"] = 4] = \"Exp2\";\n /** Round */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Round\"] = 5] = \"Round\";\n /** Floor */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Floor\"] = 6] = \"Floor\";\n /** Ceiling */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Ceiling\"] = 7] = \"Ceiling\";\n /** Square root */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Sqrt\"] = 8] = \"Sqrt\";\n /** Log */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Log\"] = 9] = \"Log\";\n /** Tangent */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Tan\"] = 10] = \"Tan\";\n /** Arc tangent */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"ArcTan\"] = 11] = \"ArcTan\";\n /** Arc cosinus */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"ArcCos\"] = 12] = \"ArcCos\";\n /** Arc sinus */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"ArcSin\"] = 13] = \"ArcSin\";\n /** Fraction */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Fract\"] = 14] = \"Fract\";\n /** Sign */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Sign\"] = 15] = \"Sign\";\n /** To radians (from degrees) */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Radians\"] = 16] = \"Radians\";\n /** To degrees (from radians) */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Degrees\"] = 17] = \"Degrees\";\n})(TrigonometryBlockOperations || (TrigonometryBlockOperations = {}));\n/**\n * Block used to apply trigonometry operation to floats\n */\nexport class TrigonometryBlock extends NodeMaterialBlock {\n /**\n * Creates a new TrigonometryBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n /**\n * Gets or sets the operation applied by the block\n */\n this.operation = TrigonometryBlockOperations.Cos;\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"TrigonometryBlock\";\n }\n /**\n * Gets the input component\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n let operation = \"\";\n switch (this.operation) {\n case TrigonometryBlockOperations.Cos: {\n operation = \"cos\";\n break;\n }\n case TrigonometryBlockOperations.Sin: {\n operation = \"sin\";\n break;\n }\n case TrigonometryBlockOperations.Abs: {\n operation = \"abs\";\n break;\n }\n case TrigonometryBlockOperations.Exp: {\n operation = \"exp\";\n break;\n }\n case TrigonometryBlockOperations.Exp2: {\n operation = \"exp2\";\n break;\n }\n case TrigonometryBlockOperations.Round: {\n operation = \"round\";\n break;\n }\n case TrigonometryBlockOperations.Floor: {\n operation = \"floor\";\n break;\n }\n case TrigonometryBlockOperations.Ceiling: {\n operation = \"ceil\";\n break;\n }\n case TrigonometryBlockOperations.Sqrt: {\n operation = \"sqrt\";\n break;\n }\n case TrigonometryBlockOperations.Log: {\n operation = \"log\";\n break;\n }\n case TrigonometryBlockOperations.Tan: {\n operation = \"tan\";\n break;\n }\n case TrigonometryBlockOperations.ArcTan: {\n operation = \"atan\";\n break;\n }\n case TrigonometryBlockOperations.ArcCos: {\n operation = \"acos\";\n break;\n }\n case TrigonometryBlockOperations.ArcSin: {\n operation = \"asin\";\n break;\n }\n case TrigonometryBlockOperations.Fract: {\n operation = \"fract\";\n break;\n }\n case TrigonometryBlockOperations.Sign: {\n operation = \"sign\";\n break;\n }\n case TrigonometryBlockOperations.Radians: {\n operation = \"radians\";\n break;\n }\n case TrigonometryBlockOperations.Degrees: {\n operation = \"degrees\";\n break;\n }\n }\n state.compilationString += this._declareOutput(output, state) + ` = ${operation}(${this.input.associatedVariableName});\\r\\n`;\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.operation = this.operation;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.operation = serializationObject.operation;\n }\n _dumpPropertiesCode() {\n const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.operation = BABYLON.TrigonometryBlockOperations.${TrigonometryBlockOperations[this.operation]};\\r\\n`;\n return codeString;\n }\n}\nRegisterClass(\"BABYLON.TrigonometryBlock\", TrigonometryBlock);\n//# sourceMappingURL=trigonometryBlock.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { PushMaterial } from \"../pushMaterial.js\";\nimport { AbstractMesh } from \"../../Meshes/abstractMesh.js\";\nimport { Matrix, Vector2 } from \"../../Maths/math.vector.js\";\nimport { Color3, Color4 } from \"../../Maths/math.color.js\";\nimport { Engine } from \"../../Engines/engine.js\";\nimport { NodeMaterialBuildState } from \"./nodeMaterialBuildState.js\";\nimport { Effect } from \"../effect.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { NodeMaterialBlockTargets } from \"./Enums/nodeMaterialBlockTargets.js\";\nimport { NodeMaterialBuildStateSharedData } from \"./nodeMaterialBuildStateSharedData.js\";\nimport { MaterialDefines } from \"../../Materials/materialDefines.js\";\nimport { VertexBuffer } from \"../../Buffers/buffer.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nimport { TransformBlock } from \"./Blocks/transformBlock.js\";\nimport { VertexOutputBlock } from \"./Blocks/Vertex/vertexOutputBlock.js\";\nimport { FragmentOutputBlock } from \"./Blocks/Fragment/fragmentOutputBlock.js\";\nimport { InputBlock } from \"./Blocks/Input/inputBlock.js\";\nimport { GetClass, RegisterClass } from \"../../Misc/typeStore.js\";\nimport { serialize, SerializationHelper } from \"../../Misc/decorators.js\";\nimport { CurrentScreenBlock } from \"./Blocks/Dual/currentScreenBlock.js\";\nimport { ParticleTextureBlock } from \"./Blocks/Particle/particleTextureBlock.js\";\nimport { ParticleRampGradientBlock } from \"./Blocks/Particle/particleRampGradientBlock.js\";\nimport { ParticleBlendMultiplyBlock } from \"./Blocks/Particle/particleBlendMultiplyBlock.js\";\nimport { EffectFallbacks } from \"../effectFallbacks.js\";\nimport { WebRequest } from \"../../Misc/webRequest.js\";\nimport { PostProcess } from \"../../PostProcesses/postProcess.js\";\n\nimport { VectorMergerBlock } from \"./Blocks/vectorMergerBlock.js\";\nimport { RemapBlock } from \"./Blocks/remapBlock.js\";\nimport { MultiplyBlock } from \"./Blocks/multiplyBlock.js\";\nimport { NodeMaterialModes } from \"./Enums/nodeMaterialModes.js\";\nimport { Texture } from \"../Textures/texture.js\";\nimport { BaseParticleSystem } from \"../../Particles/baseParticleSystem.js\";\nimport { ColorSplitterBlock } from \"./Blocks/colorSplitterBlock.js\";\nimport { TimingTools } from \"../../Misc/timingTools.js\";\nimport { ProceduralTexture } from \"../Textures/Procedurals/proceduralTexture.js\";\nimport { AnimatedInputBlockTypes } from \"./Blocks/Input/animatedInputBlockTypes.js\";\nimport { TrigonometryBlock, TrigonometryBlockOperations } from \"./Blocks/trigonometryBlock.js\";\nimport { NodeMaterialSystemValues } from \"./Enums/nodeMaterialSystemValues.js\";\nimport { EngineStore } from \"../../Engines/engineStore.js\";\nimport { MaterialHelper } from \"../materialHelper.js\";\nconst onCreatedEffectParameters = { effect: null, subMesh: null };\n/** @internal */\nexport class NodeMaterialDefines extends MaterialDefines {\n constructor() {\n super();\n this.NORMAL = false;\n this.TANGENT = false;\n this.VERTEXCOLOR_NME = false;\n this.UV1 = false;\n this.UV2 = false;\n this.UV3 = false;\n this.UV4 = false;\n this.UV5 = false;\n this.UV6 = false;\n /** BONES */\n this.NUM_BONE_INFLUENCERS = 0;\n this.BonesPerMesh = 0;\n this.BONETEXTURE = false;\n /** MORPH TARGETS */\n this.MORPHTARGETS = false;\n this.MORPHTARGETS_NORMAL = false;\n this.MORPHTARGETS_TANGENT = false;\n this.MORPHTARGETS_UV = false;\n this.NUM_MORPH_INFLUENCERS = 0;\n this.MORPHTARGETS_TEXTURE = false;\n /** IMAGE PROCESSING */\n this.IMAGEPROCESSING = false;\n this.VIGNETTE = false;\n this.VIGNETTEBLENDMODEMULTIPLY = false;\n this.VIGNETTEBLENDMODEOPAQUE = false;\n this.TONEMAPPING = false;\n this.TONEMAPPING_ACES = false;\n this.CONTRAST = false;\n this.EXPOSURE = false;\n this.COLORCURVES = false;\n this.COLORGRADING = false;\n this.COLORGRADING3D = false;\n this.SAMPLER3DGREENDEPTH = false;\n this.SAMPLER3DBGRMAP = false;\n this.DITHER = false;\n this.IMAGEPROCESSINGPOSTPROCESS = false;\n this.SKIPFINALCOLORCLAMP = false;\n /** MISC. */\n this.BUMPDIRECTUV = 0;\n this.CAMERA_ORTHOGRAPHIC = false;\n this.CAMERA_PERSPECTIVE = false;\n this.rebuild();\n }\n setValue(name, value, markAsUnprocessedIfDirty = false) {\n if (this[name] === undefined) {\n this._keys.push(name);\n }\n if (markAsUnprocessedIfDirty && this[name] !== value) {\n this.markAsUnprocessed();\n }\n this[name] = value;\n }\n}\n/**\n * Class used to create a node based material built by assembling shader blocks\n */\nexport class NodeMaterial extends PushMaterial {\n /**\n * Checks if a block is a texture block\n * @param block The block to check\n * @returns True if the block is a texture block\n */\n static _BlockIsTextureBlock(block) {\n return (block.getClassName() === \"TextureBlock\" ||\n block.getClassName() === \"ReflectionTextureBaseBlock\" ||\n block.getClassName() === \"RefractionBlock\" ||\n block.getClassName() === \"CurrentScreenBlock\" ||\n block.getClassName() === \"ParticleTextureBlock\" ||\n block.getClassName() === \"ImageSourceBlock\" ||\n block.getClassName() === \"TriPlanarBlock\" ||\n block.getClassName() === \"BiPlanarBlock\");\n }\n /** Get the inspector from bundle or global */\n _getGlobalNodeMaterialEditor() {\n // UMD Global name detection from Webpack Bundle UMD Name.\n if (typeof NODEEDITOR !== \"undefined\") {\n return NODEEDITOR;\n }\n // In case of module let's check the global emitted from the editor entry point.\n if (typeof BABYLON !== \"undefined\" && typeof BABYLON.NodeEditor !== \"undefined\") {\n return BABYLON;\n }\n return undefined;\n }\n /** Gets or sets options to control the node material overall behavior */\n get options() {\n return this._options;\n }\n set options(options) {\n this._options = options;\n }\n /**\n * Gets the image processing configuration used either in this material.\n */\n get imageProcessingConfiguration() {\n return this._imageProcessingConfiguration;\n }\n /**\n * Sets the Default image processing configuration used either in the this material.\n *\n * If sets to null, the scene one is in use.\n */\n set imageProcessingConfiguration(value) {\n this._attachImageProcessingConfiguration(value);\n // Ensure the effect will be rebuilt.\n this._markAllSubMeshesAsTexturesDirty();\n }\n /**\n * Gets or sets the mode property\n */\n get mode() {\n return this._mode;\n }\n set mode(value) {\n this._mode = value;\n }\n /** Gets or sets the unique identifier used to identified the effect associated with the material */\n get buildId() {\n return this._buildId;\n }\n set buildId(value) {\n this._buildId = value;\n }\n /**\n * Create a new node based material\n * @param name defines the material name\n * @param scene defines the hosting scene\n * @param options defines creation option\n */\n constructor(name, scene, options = {}) {\n super(name, scene || EngineStore.LastCreatedScene);\n this._buildId = NodeMaterial._BuildIdGenerator++;\n this._buildWasSuccessful = false;\n this._cachedWorldViewMatrix = new Matrix();\n this._cachedWorldViewProjectionMatrix = new Matrix();\n this._optimizers = new Array();\n this._animationFrame = -1;\n this.BJSNODEMATERIALEDITOR = this._getGlobalNodeMaterialEditor();\n /**\n * Gets or sets data used by visual editor\n * @see https://nme.babylonjs.com\n */\n this.editorData = null;\n /**\n * Gets or sets a boolean indicating that alpha value must be ignored (This will turn alpha blending off even if an alpha value is produced by the material)\n */\n this.ignoreAlpha = false;\n /**\n * Defines the maximum number of lights that can be used in the material\n */\n this.maxSimultaneousLights = 4;\n /**\n * Observable raised when the material is built\n */\n this.onBuildObservable = new Observable();\n /**\n * Gets or sets the root nodes of the material vertex shader\n */\n this._vertexOutputNodes = new Array();\n /**\n * Gets or sets the root nodes of the material fragment (pixel) shader\n */\n this._fragmentOutputNodes = new Array();\n /**\n * Gets an array of blocks that needs to be serialized even if they are not yet connected\n */\n this.attachedBlocks = new Array();\n /**\n * Specifies the mode of the node material\n * @internal\n */\n this._mode = NodeMaterialModes.Material;\n /**\n * Gets or sets a boolean indicating that alpha blending must be enabled no matter what alpha value or alpha channel of the FragmentBlock are\n */\n this.forceAlphaBlending = false;\n this._options = Object.assign({ emitComments: false }, options);\n // Setup the default processing configuration to the scene.\n this._attachImageProcessingConfiguration(null);\n }\n /**\n * Gets the current class name of the material e.g. \"NodeMaterial\"\n * @returns the class name\n */\n getClassName() {\n return \"NodeMaterial\";\n }\n /**\n * Attaches a new image processing configuration to the Standard Material.\n * @param configuration\n */\n _attachImageProcessingConfiguration(configuration) {\n if (configuration === this._imageProcessingConfiguration) {\n return;\n }\n // Detaches observer.\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n // Pick the scene configuration if needed.\n if (!configuration) {\n this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;\n }\n else {\n this._imageProcessingConfiguration = configuration;\n }\n // Attaches observer.\n if (this._imageProcessingConfiguration) {\n this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => {\n this._markAllSubMeshesAsImageProcessingDirty();\n });\n }\n }\n /**\n * Get a block by its name\n * @param name defines the name of the block to retrieve\n * @returns the required block or null if not found\n */\n getBlockByName(name) {\n let result = null;\n for (const block of this.attachedBlocks) {\n if (block.name === name) {\n if (!result) {\n result = block;\n }\n else {\n Tools.Warn(\"More than one block was found with the name `\" + name + \"`\");\n return result;\n }\n }\n }\n return result;\n }\n /**\n * Get a block by its name\n * @param predicate defines the predicate used to find the good candidate\n * @returns the required block or null if not found\n */\n getBlockByPredicate(predicate) {\n for (const block of this.attachedBlocks) {\n if (predicate(block)) {\n return block;\n }\n }\n return null;\n }\n /**\n * Get an input block by its name\n * @param predicate defines the predicate used to find the good candidate\n * @returns the required input block or null if not found\n */\n getInputBlockByPredicate(predicate) {\n for (const block of this.attachedBlocks) {\n if (block.isInput && predicate(block)) {\n return block;\n }\n }\n return null;\n }\n /**\n * Gets the list of input blocks attached to this material\n * @returns an array of InputBlocks\n */\n getInputBlocks() {\n const blocks = [];\n for (const block of this.attachedBlocks) {\n if (block.isInput) {\n blocks.push(block);\n }\n }\n return blocks;\n }\n /**\n * Adds a new optimizer to the list of optimizers\n * @param optimizer defines the optimizers to add\n * @returns the current material\n */\n registerOptimizer(optimizer) {\n const index = this._optimizers.indexOf(optimizer);\n if (index > -1) {\n return;\n }\n this._optimizers.push(optimizer);\n return this;\n }\n /**\n * Remove an optimizer from the list of optimizers\n * @param optimizer defines the optimizers to remove\n * @returns the current material\n */\n unregisterOptimizer(optimizer) {\n const index = this._optimizers.indexOf(optimizer);\n if (index === -1) {\n return;\n }\n this._optimizers.splice(index, 1);\n return this;\n }\n /**\n * Add a new block to the list of output nodes\n * @param node defines the node to add\n * @returns the current material\n */\n addOutputNode(node) {\n if (node.target === null) {\n throw \"This node is not meant to be an output node. You may want to explicitly set its target value.\";\n }\n if ((node.target & NodeMaterialBlockTargets.Vertex) !== 0) {\n this._addVertexOutputNode(node);\n }\n if ((node.target & NodeMaterialBlockTargets.Fragment) !== 0) {\n this._addFragmentOutputNode(node);\n }\n return this;\n }\n /**\n * Remove a block from the list of root nodes\n * @param node defines the node to remove\n * @returns the current material\n */\n removeOutputNode(node) {\n if (node.target === null) {\n return this;\n }\n if ((node.target & NodeMaterialBlockTargets.Vertex) !== 0) {\n this._removeVertexOutputNode(node);\n }\n if ((node.target & NodeMaterialBlockTargets.Fragment) !== 0) {\n this._removeFragmentOutputNode(node);\n }\n return this;\n }\n _addVertexOutputNode(node) {\n if (this._vertexOutputNodes.indexOf(node) !== -1) {\n return;\n }\n node.target = NodeMaterialBlockTargets.Vertex;\n this._vertexOutputNodes.push(node);\n return this;\n }\n _removeVertexOutputNode(node) {\n const index = this._vertexOutputNodes.indexOf(node);\n if (index === -1) {\n return;\n }\n this._vertexOutputNodes.splice(index, 1);\n return this;\n }\n _addFragmentOutputNode(node) {\n if (this._fragmentOutputNodes.indexOf(node) !== -1) {\n return;\n }\n node.target = NodeMaterialBlockTargets.Fragment;\n this._fragmentOutputNodes.push(node);\n return this;\n }\n _removeFragmentOutputNode(node) {\n const index = this._fragmentOutputNodes.indexOf(node);\n if (index === -1) {\n return;\n }\n this._fragmentOutputNodes.splice(index, 1);\n return this;\n }\n /**\n * Specifies if the material will require alpha blending\n * @returns a boolean specifying if alpha blending is needed\n */\n needAlphaBlending() {\n if (this.ignoreAlpha) {\n return false;\n }\n return this.forceAlphaBlending || this.alpha < 1.0 || (this._sharedData && this._sharedData.hints.needAlphaBlending);\n }\n /**\n * Specifies if this material should be rendered in alpha test mode\n * @returns a boolean specifying if an alpha test is needed.\n */\n needAlphaTesting() {\n return this._sharedData && this._sharedData.hints.needAlphaTesting;\n }\n _initializeBlock(node, state, nodesToProcessForOtherBuildState, autoConfigure = true) {\n node.initialize(state);\n if (autoConfigure) {\n node.autoConfigure(this);\n }\n node._preparationId = this._buildId;\n if (this.attachedBlocks.indexOf(node) === -1) {\n if (node.isUnique) {\n const className = node.getClassName();\n for (const other of this.attachedBlocks) {\n if (other.getClassName() === className) {\n throw `Cannot have multiple blocks of type ${className} in the same NodeMaterial`;\n }\n }\n }\n this.attachedBlocks.push(node);\n }\n for (const input of node.inputs) {\n input.associatedVariableName = \"\";\n const connectedPoint = input.connectedPoint;\n if (connectedPoint) {\n const block = connectedPoint.ownerBlock;\n if (block !== node) {\n if (block.target === NodeMaterialBlockTargets.VertexAndFragment) {\n nodesToProcessForOtherBuildState.push(block);\n }\n else if (state.target === NodeMaterialBlockTargets.Fragment && block.target === NodeMaterialBlockTargets.Vertex && block._preparationId !== this._buildId) {\n nodesToProcessForOtherBuildState.push(block);\n }\n this._initializeBlock(block, state, nodesToProcessForOtherBuildState, autoConfigure);\n }\n }\n }\n for (const output of node.outputs) {\n output.associatedVariableName = \"\";\n }\n }\n _resetDualBlocks(node, id) {\n if (node.target === NodeMaterialBlockTargets.VertexAndFragment) {\n node.buildId = id;\n }\n for (const inputs of node.inputs) {\n const connectedPoint = inputs.connectedPoint;\n if (connectedPoint) {\n const block = connectedPoint.ownerBlock;\n if (block !== node) {\n this._resetDualBlocks(block, id);\n }\n }\n }\n }\n /**\n * Remove a block from the current node material\n * @param block defines the block to remove\n */\n removeBlock(block) {\n const attachedBlockIndex = this.attachedBlocks.indexOf(block);\n if (attachedBlockIndex > -1) {\n this.attachedBlocks.splice(attachedBlockIndex, 1);\n }\n if (block.isFinalMerger) {\n this.removeOutputNode(block);\n }\n }\n /**\n * Build the material and generates the inner effect\n * @param verbose defines if the build should log activity\n * @param updateBuildId defines if the internal build Id should be updated (default is true)\n * @param autoConfigure defines if the autoConfigure method should be called when initializing blocks (default is true)\n */\n build(verbose = false, updateBuildId = true, autoConfigure = true) {\n this._buildWasSuccessful = false;\n const engine = this.getScene().getEngine();\n const allowEmptyVertexProgram = this._mode === NodeMaterialModes.Particle;\n if (this._vertexOutputNodes.length === 0 && !allowEmptyVertexProgram) {\n throw \"You must define at least one vertexOutputNode\";\n }\n if (this._fragmentOutputNodes.length === 0) {\n throw \"You must define at least one fragmentOutputNode\";\n }\n // Compilation state\n this._vertexCompilationState = new NodeMaterialBuildState();\n this._vertexCompilationState.supportUniformBuffers = engine.supportsUniformBuffers;\n this._vertexCompilationState.target = NodeMaterialBlockTargets.Vertex;\n this._fragmentCompilationState = new NodeMaterialBuildState();\n this._fragmentCompilationState.supportUniformBuffers = engine.supportsUniformBuffers;\n this._fragmentCompilationState.target = NodeMaterialBlockTargets.Fragment;\n // Shared data\n this._sharedData = new NodeMaterialBuildStateSharedData();\n this._sharedData.fragmentOutputNodes = this._fragmentOutputNodes;\n this._vertexCompilationState.sharedData = this._sharedData;\n this._fragmentCompilationState.sharedData = this._sharedData;\n this._sharedData.buildId = this._buildId;\n this._sharedData.emitComments = this._options.emitComments;\n this._sharedData.verbose = verbose;\n this._sharedData.scene = this.getScene();\n this._sharedData.allowEmptyVertexProgram = allowEmptyVertexProgram;\n // Initialize blocks\n const vertexNodes = [];\n const fragmentNodes = [];\n for (const vertexOutputNode of this._vertexOutputNodes) {\n vertexNodes.push(vertexOutputNode);\n this._initializeBlock(vertexOutputNode, this._vertexCompilationState, fragmentNodes, autoConfigure);\n }\n for (const fragmentOutputNode of this._fragmentOutputNodes) {\n fragmentNodes.push(fragmentOutputNode);\n this._initializeBlock(fragmentOutputNode, this._fragmentCompilationState, vertexNodes, autoConfigure);\n }\n // Optimize\n this.optimize();\n // Vertex\n for (const vertexOutputNode of vertexNodes) {\n vertexOutputNode.build(this._vertexCompilationState, vertexNodes);\n }\n // Fragment\n this._fragmentCompilationState.uniforms = this._vertexCompilationState.uniforms.slice(0);\n this._fragmentCompilationState._uniformDeclaration = this._vertexCompilationState._uniformDeclaration;\n this._fragmentCompilationState._constantDeclaration = this._vertexCompilationState._constantDeclaration;\n this._fragmentCompilationState._vertexState = this._vertexCompilationState;\n for (const fragmentOutputNode of fragmentNodes) {\n this._resetDualBlocks(fragmentOutputNode, this._buildId - 1);\n }\n for (const fragmentOutputNode of fragmentNodes) {\n fragmentOutputNode.build(this._fragmentCompilationState, fragmentNodes);\n }\n // Finalize\n this._vertexCompilationState.finalize(this._vertexCompilationState);\n this._fragmentCompilationState.finalize(this._fragmentCompilationState);\n if (updateBuildId) {\n this._buildId = NodeMaterial._BuildIdGenerator++;\n }\n // Errors\n this._sharedData.emitErrors();\n if (verbose) {\n console.log(\"Vertex shader:\");\n console.log(this._vertexCompilationState.compilationString);\n console.log(\"Fragment shader:\");\n console.log(this._fragmentCompilationState.compilationString);\n }\n this._buildWasSuccessful = true;\n this.onBuildObservable.notifyObservers(this);\n // Wipe defines\n const meshes = this.getScene().meshes;\n for (const mesh of meshes) {\n if (!mesh.subMeshes) {\n continue;\n }\n for (const subMesh of mesh.subMeshes) {\n if (subMesh.getMaterial() !== this) {\n continue;\n }\n if (!subMesh.materialDefines) {\n continue;\n }\n const defines = subMesh.materialDefines;\n defines.markAllAsDirty();\n defines.reset();\n }\n }\n }\n /**\n * Runs an otpimization phase to try to improve the shader code\n */\n optimize() {\n for (const optimizer of this._optimizers) {\n optimizer.optimize(this._vertexOutputNodes, this._fragmentOutputNodes);\n }\n }\n _prepareDefinesForAttributes(mesh, defines) {\n const oldNormal = defines[\"NORMAL\"];\n const oldTangent = defines[\"TANGENT\"];\n const oldColor = defines[\"VERTEXCOLOR_NME\"];\n defines[\"NORMAL\"] = mesh.isVerticesDataPresent(VertexBuffer.NormalKind);\n defines[\"TANGENT\"] = mesh.isVerticesDataPresent(VertexBuffer.TangentKind);\n const hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(VertexBuffer.ColorKind);\n defines[\"VERTEXCOLOR_NME\"] = hasVertexColors;\n let uvChanged = false;\n for (let i = 1; i <= 6; ++i) {\n const oldUV = defines[\"UV\" + i];\n defines[\"UV\" + i] = mesh.isVerticesDataPresent(`uv${i === 1 ? \"\" : i}`);\n uvChanged = uvChanged || defines[\"UV\" + i] !== oldUV;\n }\n if (oldNormal !== defines[\"NORMAL\"] || oldTangent !== defines[\"TANGENT\"] || oldColor !== defines[\"VERTEXCOLOR_NME\"] || uvChanged) {\n defines.markAsAttributesDirty();\n }\n }\n /**\n * Create a post process from the material\n * @param camera The camera to apply the render pass to.\n * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param textureFormat Format of textures used when performing the post process. (default: TEXTUREFORMAT_RGBA)\n * @returns the post process created\n */\n createPostProcess(camera, options = 1, samplingMode = 1, engine, reusable, textureType = 0, textureFormat = 5) {\n if (this.mode !== NodeMaterialModes.PostProcess) {\n console.log(\"Incompatible material mode\");\n return null;\n }\n return this._createEffectForPostProcess(null, camera, options, samplingMode, engine, reusable, textureType, textureFormat);\n }\n /**\n * Create the post process effect from the material\n * @param postProcess The post process to create the effect for\n */\n createEffectForPostProcess(postProcess) {\n this._createEffectForPostProcess(postProcess);\n }\n _createEffectForPostProcess(postProcess, camera, options = 1, samplingMode = 1, engine, reusable, textureType = 0, textureFormat = 5) {\n let tempName = this.name + this._buildId;\n const defines = new NodeMaterialDefines();\n const dummyMesh = new AbstractMesh(tempName + \"PostProcess\", this.getScene());\n let buildId = this._buildId;\n this._processDefines(dummyMesh, defines);\n Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString, this._vertexCompilationState._builtCompilationString);\n if (!postProcess) {\n postProcess = new PostProcess(this.name + \"PostProcess\", tempName, this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, options, camera, samplingMode, engine, reusable, defines.toString(), textureType, tempName, { maxSimultaneousLights: this.maxSimultaneousLights }, false, textureFormat);\n }\n else {\n postProcess.updateEffect(defines.toString(), this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, { maxSimultaneousLights: this.maxSimultaneousLights }, undefined, undefined, tempName, tempName);\n }\n postProcess.nodeMaterialSource = this;\n postProcess.onApplyObservable.add((effect) => {\n if (buildId !== this._buildId) {\n delete Effect.ShadersStore[tempName + \"VertexShader\"];\n delete Effect.ShadersStore[tempName + \"PixelShader\"];\n tempName = this.name + this._buildId;\n defines.markAllAsDirty();\n buildId = this._buildId;\n }\n const result = this._processDefines(dummyMesh, defines);\n if (result) {\n Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString, this._vertexCompilationState._builtCompilationString);\n TimingTools.SetImmediate(() => postProcess.updateEffect(defines.toString(), this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, { maxSimultaneousLights: this.maxSimultaneousLights }, undefined, undefined, tempName, tempName));\n }\n this._checkInternals(effect);\n });\n return postProcess;\n }\n /**\n * Create a new procedural texture based on this node material\n * @param size defines the size of the texture\n * @param scene defines the hosting scene\n * @returns the new procedural texture attached to this node material\n */\n createProceduralTexture(size, scene) {\n if (this.mode !== NodeMaterialModes.ProceduralTexture) {\n console.log(\"Incompatible material mode\");\n return null;\n }\n let tempName = this.name + this._buildId;\n const proceduralTexture = new ProceduralTexture(tempName, size, null, scene);\n const dummyMesh = new AbstractMesh(tempName + \"Procedural\", this.getScene());\n dummyMesh.reservedDataStore = {\n hidden: true,\n };\n const defines = new NodeMaterialDefines();\n const result = this._processDefines(dummyMesh, defines);\n Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString, this._vertexCompilationState._builtCompilationString);\n let effect = this.getScene().getEngine().createEffect({\n vertexElement: tempName,\n fragmentElement: tempName,\n }, [VertexBuffer.PositionKind], this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, defines.toString(), result === null || result === void 0 ? void 0 : result.fallbacks, undefined);\n proceduralTexture.nodeMaterialSource = this;\n proceduralTexture._setEffect(effect);\n let buildId = this._buildId;\n proceduralTexture.onBeforeGenerationObservable.add(() => {\n if (buildId !== this._buildId) {\n delete Effect.ShadersStore[tempName + \"VertexShader\"];\n delete Effect.ShadersStore[tempName + \"PixelShader\"];\n tempName = this.name + this._buildId;\n defines.markAllAsDirty();\n buildId = this._buildId;\n }\n const result = this._processDefines(dummyMesh, defines);\n if (result) {\n Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString, this._vertexCompilationState._builtCompilationString);\n TimingTools.SetImmediate(() => {\n effect = this.getScene().getEngine().createEffect({\n vertexElement: tempName,\n fragmentElement: tempName,\n }, [VertexBuffer.PositionKind], this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, defines.toString(), result === null || result === void 0 ? void 0 : result.fallbacks, undefined);\n proceduralTexture._setEffect(effect);\n });\n }\n this._checkInternals(effect);\n });\n return proceduralTexture;\n }\n _createEffectForParticles(particleSystem, blendMode, onCompiled, onError, effect, defines, dummyMesh, particleSystemDefinesJoined = \"\") {\n let tempName = this.name + this._buildId + \"_\" + blendMode;\n if (!defines) {\n defines = new NodeMaterialDefines();\n }\n if (!dummyMesh) {\n dummyMesh = this.getScene().getMeshByName(this.name + \"Particle\");\n if (!dummyMesh) {\n dummyMesh = new AbstractMesh(this.name + \"Particle\", this.getScene());\n dummyMesh.reservedDataStore = {\n hidden: true,\n };\n }\n }\n let buildId = this._buildId;\n const particleSystemDefines = [];\n let join = particleSystemDefinesJoined;\n if (!effect) {\n const result = this._processDefines(dummyMesh, defines);\n Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString);\n particleSystem.fillDefines(particleSystemDefines, blendMode);\n join = particleSystemDefines.join(\"\\n\");\n effect = this.getScene()\n .getEngine()\n .createEffectForParticles(tempName, this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, defines.toString() + \"\\n\" + join, result === null || result === void 0 ? void 0 : result.fallbacks, onCompiled, onError, particleSystem);\n particleSystem.setCustomEffect(effect, blendMode);\n }\n effect.onBindObservable.add((effect) => {\n if (buildId !== this._buildId) {\n delete Effect.ShadersStore[tempName + \"PixelShader\"];\n tempName = this.name + this._buildId + \"_\" + blendMode;\n defines.markAllAsDirty();\n buildId = this._buildId;\n }\n particleSystemDefines.length = 0;\n particleSystem.fillDefines(particleSystemDefines, blendMode);\n const particleSystemDefinesJoinedCurrent = particleSystemDefines.join(\"\\n\");\n if (particleSystemDefinesJoinedCurrent !== join) {\n defines.markAllAsDirty();\n join = particleSystemDefinesJoinedCurrent;\n }\n const result = this._processDefines(dummyMesh, defines);\n if (result) {\n Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString);\n effect = this.getScene()\n .getEngine()\n .createEffectForParticles(tempName, this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, defines.toString() + \"\\n\" + join, result === null || result === void 0 ? void 0 : result.fallbacks, onCompiled, onError, particleSystem);\n particleSystem.setCustomEffect(effect, blendMode);\n this._createEffectForParticles(particleSystem, blendMode, onCompiled, onError, effect, defines, dummyMesh, particleSystemDefinesJoined); // add the effect.onBindObservable observer\n return;\n }\n this._checkInternals(effect);\n });\n }\n _checkInternals(effect) {\n // Animated blocks\n if (this._sharedData.animatedInputs) {\n const scene = this.getScene();\n const frameId = scene.getFrameId();\n if (this._animationFrame !== frameId) {\n for (const input of this._sharedData.animatedInputs) {\n input.animate(scene);\n }\n this._animationFrame = frameId;\n }\n }\n // Bindable blocks\n for (const block of this._sharedData.bindableBlocks) {\n block.bind(effect, this);\n }\n // Connection points\n for (const inputBlock of this._sharedData.inputBlocks) {\n inputBlock._transmit(effect, this.getScene(), this);\n }\n }\n /**\n * Create the effect to be used as the custom effect for a particle system\n * @param particleSystem Particle system to create the effect for\n * @param onCompiled defines a function to call when the effect creation is successful\n * @param onError defines a function to call when the effect creation has failed\n */\n createEffectForParticles(particleSystem, onCompiled, onError) {\n if (this.mode !== NodeMaterialModes.Particle) {\n console.log(\"Incompatible material mode\");\n return;\n }\n this._createEffectForParticles(particleSystem, BaseParticleSystem.BLENDMODE_ONEONE, onCompiled, onError);\n this._createEffectForParticles(particleSystem, BaseParticleSystem.BLENDMODE_MULTIPLY, onCompiled, onError);\n }\n /**\n * Use this material as the shadow depth wrapper of a target material\n * @param targetMaterial defines the target material\n */\n createAsShadowDepthWrapper(targetMaterial) {\n if (this.mode !== NodeMaterialModes.Material) {\n console.log(\"Incompatible material mode\");\n return;\n }\n targetMaterial.shadowDepthWrapper = new BABYLON.ShadowDepthWrapper(this, this.getScene());\n }\n _processDefines(mesh, defines, useInstances = false, subMesh) {\n let result = null;\n // Global defines\n const scene = this.getScene();\n if (MaterialHelper.PrepareDefinesForCamera(scene, defines)) {\n defines.markAsMiscDirty();\n }\n // Shared defines\n this._sharedData.blocksWithDefines.forEach((b) => {\n b.initializeDefines(mesh, this, defines, useInstances);\n });\n this._sharedData.blocksWithDefines.forEach((b) => {\n b.prepareDefines(mesh, this, defines, useInstances, subMesh);\n });\n // Need to recompile?\n if (defines.isDirty) {\n const lightDisposed = defines._areLightsDisposed;\n defines.markAsProcessed();\n // Repeatable content generators\n this._vertexCompilationState.compilationString = this._vertexCompilationState._builtCompilationString;\n this._fragmentCompilationState.compilationString = this._fragmentCompilationState._builtCompilationString;\n this._sharedData.repeatableContentBlocks.forEach((b) => {\n b.replaceRepeatableContent(this._vertexCompilationState, this._fragmentCompilationState, mesh, defines);\n });\n // Uniforms\n const uniformBuffers = [];\n this._sharedData.dynamicUniformBlocks.forEach((b) => {\n b.updateUniformsAndSamples(this._vertexCompilationState, this, defines, uniformBuffers);\n });\n const mergedUniforms = this._vertexCompilationState.uniforms;\n this._fragmentCompilationState.uniforms.forEach((u) => {\n const index = mergedUniforms.indexOf(u);\n if (index === -1) {\n mergedUniforms.push(u);\n }\n });\n // Samplers\n const mergedSamplers = this._vertexCompilationState.samplers;\n this._fragmentCompilationState.samplers.forEach((s) => {\n const index = mergedSamplers.indexOf(s);\n if (index === -1) {\n mergedSamplers.push(s);\n }\n });\n const fallbacks = new EffectFallbacks();\n this._sharedData.blocksWithFallbacks.forEach((b) => {\n b.provideFallbacks(mesh, fallbacks);\n });\n result = {\n lightDisposed,\n uniformBuffers,\n mergedUniforms,\n mergedSamplers,\n fallbacks,\n };\n }\n return result;\n }\n /**\n * Get if the submesh is ready to be used and all its information available.\n * Child classes can use it to update shaders\n * @param mesh defines the mesh to check\n * @param subMesh defines which submesh to check\n * @param useInstances specifies that instances should be used\n * @returns a boolean indicating that the submesh is ready or not\n */\n isReadyForSubMesh(mesh, subMesh, useInstances = false) {\n if (!this._buildWasSuccessful) {\n return false;\n }\n const scene = this.getScene();\n if (this._sharedData.animatedInputs) {\n const frameId = scene.getFrameId();\n if (this._animationFrame !== frameId) {\n for (const input of this._sharedData.animatedInputs) {\n input.animate(scene);\n }\n this._animationFrame = frameId;\n }\n }\n if (subMesh.effect && this.isFrozen) {\n if (subMesh.effect._wasPreviouslyReady && subMesh.effect._wasPreviouslyUsingInstances === useInstances) {\n return true;\n }\n }\n if (!subMesh.materialDefines) {\n subMesh.materialDefines = new NodeMaterialDefines();\n }\n const defines = subMesh.materialDefines;\n if (this._isReadyForSubMesh(subMesh)) {\n return true;\n }\n const engine = scene.getEngine();\n this._prepareDefinesForAttributes(mesh, defines);\n // Check if blocks are ready\n if (this._sharedData.blockingBlocks.some((b) => !b.isReady(mesh, this, defines, useInstances))) {\n return false;\n }\n const result = this._processDefines(mesh, defines, useInstances, subMesh);\n if (result) {\n const previousEffect = subMesh.effect;\n // Compilation\n const join = defines.toString();\n let effect = engine.createEffect({\n vertex: \"nodeMaterial\" + this._buildId,\n fragment: \"nodeMaterial\" + this._buildId,\n vertexSource: this._vertexCompilationState.compilationString,\n fragmentSource: this._fragmentCompilationState.compilationString,\n }, {\n attributes: this._vertexCompilationState.attributes,\n uniformsNames: result.mergedUniforms,\n uniformBuffersNames: result.uniformBuffers,\n samplers: result.mergedSamplers,\n defines: join,\n fallbacks: result.fallbacks,\n onCompiled: this.onCompiled,\n onError: this.onError,\n indexParameters: { maxSimultaneousLights: this.maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS },\n }, engine);\n if (effect) {\n if (this._onEffectCreatedObservable) {\n onCreatedEffectParameters.effect = effect;\n onCreatedEffectParameters.subMesh = subMesh;\n this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters);\n }\n // Use previous effect while new one is compiling\n if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {\n effect = previousEffect;\n defines.markAsUnprocessed();\n if (result.lightDisposed) {\n // re register in case it takes more than one frame.\n defines._areLightsDisposed = true;\n return false;\n }\n }\n else {\n scene.resetCachedMaterial();\n subMesh.setEffect(effect, defines, this._materialContext);\n }\n }\n }\n if (!subMesh.effect || !subMesh.effect.isReady()) {\n return false;\n }\n defines._renderId = scene.getRenderId();\n subMesh.effect._wasPreviouslyReady = true;\n subMesh.effect._wasPreviouslyUsingInstances = useInstances;\n this._checkScenePerformancePriority();\n return true;\n }\n /**\n * Get a string representing the shaders built by the current node graph\n */\n get compiledShaders() {\n return `// Vertex shader\\r\\n${this._vertexCompilationState.compilationString}\\r\\n\\r\\n// Fragment shader\\r\\n${this._fragmentCompilationState.compilationString}`;\n }\n /**\n * Binds the world matrix to the material\n * @param world defines the world transformation matrix\n */\n bindOnlyWorldMatrix(world) {\n const scene = this.getScene();\n if (!this._activeEffect) {\n return;\n }\n const hints = this._sharedData.hints;\n if (hints.needWorldViewMatrix) {\n world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);\n }\n if (hints.needWorldViewProjectionMatrix) {\n world.multiplyToRef(scene.getTransformMatrix(), this._cachedWorldViewProjectionMatrix);\n }\n // Connection points\n for (const inputBlock of this._sharedData.inputBlocks) {\n inputBlock._transmitWorld(this._activeEffect, world, this._cachedWorldViewMatrix, this._cachedWorldViewProjectionMatrix);\n }\n }\n /**\n * Binds the submesh to this material by preparing the effect and shader to draw\n * @param world defines the world transformation matrix\n * @param mesh defines the mesh containing the submesh\n * @param subMesh defines the submesh to bind the material to\n */\n bindForSubMesh(world, mesh, subMesh) {\n const scene = this.getScene();\n const effect = subMesh.effect;\n if (!effect) {\n return;\n }\n this._activeEffect = effect;\n // Matrices\n this.bindOnlyWorldMatrix(world);\n const mustRebind = this._mustRebind(scene, effect, mesh.visibility);\n const sharedData = this._sharedData;\n if (mustRebind) {\n // Bindable blocks\n for (const block of sharedData.bindableBlocks) {\n block.bind(effect, this, mesh, subMesh);\n }\n for (const block of sharedData.forcedBindableBlocks) {\n block.bind(effect, this, mesh, subMesh);\n }\n // Connection points\n for (const inputBlock of sharedData.inputBlocks) {\n inputBlock._transmit(effect, scene, this);\n }\n }\n else if (!this.isFrozen) {\n for (const block of sharedData.forcedBindableBlocks) {\n block.bind(effect, this, mesh, subMesh);\n }\n }\n this._afterBind(mesh, this._activeEffect);\n }\n /**\n * Gets the active textures from the material\n * @returns an array of textures\n */\n getActiveTextures() {\n const activeTextures = super.getActiveTextures();\n if (this._sharedData) {\n activeTextures.push(...this._sharedData.textureBlocks.filter((tb) => tb.texture).map((tb) => tb.texture));\n }\n return activeTextures;\n }\n /**\n * Gets the list of texture blocks\n * Note that this method will only return blocks that are reachable from the final block(s) and only after the material has been built!\n * @returns an array of texture blocks\n */\n getTextureBlocks() {\n if (!this._sharedData) {\n return [];\n }\n return this._sharedData.textureBlocks;\n }\n /**\n * Gets the list of all texture blocks\n * Note that this method will scan all attachedBlocks and return blocks that are texture blocks\n * @returns\n */\n getAllTextureBlocks() {\n const textureBlocks = [];\n for (const block of this.attachedBlocks) {\n if (NodeMaterial._BlockIsTextureBlock(block)) {\n textureBlocks.push(block);\n }\n }\n return textureBlocks;\n }\n /**\n * Specifies if the material uses a texture\n * @param texture defines the texture to check against the material\n * @returns a boolean specifying if the material uses the texture\n */\n hasTexture(texture) {\n if (super.hasTexture(texture)) {\n return true;\n }\n if (!this._sharedData) {\n return false;\n }\n for (const t of this._sharedData.textureBlocks) {\n if (t.texture === texture) {\n return true;\n }\n }\n return false;\n }\n /**\n * Disposes the material\n * @param forceDisposeEffect specifies if effects should be forcefully disposed\n * @param forceDisposeTextures specifies if textures should be forcefully disposed\n * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh\n */\n dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {\n if (forceDisposeTextures) {\n for (const texture of this.getTextureBlocks()\n .filter((tb) => tb.texture)\n .map((tb) => tb.texture)) {\n texture.dispose();\n }\n }\n for (const block of this.attachedBlocks) {\n block.dispose();\n }\n this.attachedBlocks.length = 0;\n this._sharedData = null;\n this._vertexCompilationState = null;\n this._fragmentCompilationState = null;\n this.onBuildObservable.clear();\n if (this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n this._imageProcessingObserver = null;\n }\n super.dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh);\n }\n /** Creates the node editor window. */\n _createNodeEditor(additionalConfig) {\n const nodeEditorConfig = Object.assign({ nodeMaterial: this }, additionalConfig);\n this.BJSNODEMATERIALEDITOR.NodeEditor.Show(nodeEditorConfig);\n }\n /**\n * Launch the node material editor\n * @param config Define the configuration of the editor\n * @returns a promise fulfilled when the node editor is visible\n */\n edit(config) {\n return new Promise((resolve) => {\n this.BJSNODEMATERIALEDITOR = this.BJSNODEMATERIALEDITOR || this._getGlobalNodeMaterialEditor();\n if (typeof this.BJSNODEMATERIALEDITOR == \"undefined\") {\n const editorUrl = config && config.editorURL ? config.editorURL : NodeMaterial.EditorURL;\n // Load editor and add it to the DOM\n Tools.LoadScript(editorUrl, () => {\n this.BJSNODEMATERIALEDITOR = this.BJSNODEMATERIALEDITOR || this._getGlobalNodeMaterialEditor();\n this._createNodeEditor(config === null || config === void 0 ? void 0 : config.nodeEditorConfig);\n resolve();\n });\n }\n else {\n // Otherwise creates the editor\n this._createNodeEditor(config === null || config === void 0 ? void 0 : config.nodeEditorConfig);\n resolve();\n }\n });\n }\n /**\n * Clear the current material\n */\n clear() {\n this._vertexOutputNodes.length = 0;\n this._fragmentOutputNodes.length = 0;\n this.attachedBlocks.length = 0;\n }\n /**\n * Clear the current material and set it to a default state\n */\n setToDefault() {\n this.clear();\n this.editorData = null;\n const positionInput = new InputBlock(\"Position\");\n positionInput.setAsAttribute(\"position\");\n const worldInput = new InputBlock(\"World\");\n worldInput.setAsSystemValue(NodeMaterialSystemValues.World);\n const worldPos = new TransformBlock(\"WorldPos\");\n positionInput.connectTo(worldPos);\n worldInput.connectTo(worldPos);\n const viewProjectionInput = new InputBlock(\"ViewProjection\");\n viewProjectionInput.setAsSystemValue(NodeMaterialSystemValues.ViewProjection);\n const worldPosdMultipliedByViewProjection = new TransformBlock(\"WorldPos * ViewProjectionTransform\");\n worldPos.connectTo(worldPosdMultipliedByViewProjection);\n viewProjectionInput.connectTo(worldPosdMultipliedByViewProjection);\n const vertexOutput = new VertexOutputBlock(\"VertexOutput\");\n worldPosdMultipliedByViewProjection.connectTo(vertexOutput);\n // Pixel\n const pixelColor = new InputBlock(\"color\");\n pixelColor.value = new Color4(0.8, 0.8, 0.8, 1);\n const fragmentOutput = new FragmentOutputBlock(\"FragmentOutput\");\n pixelColor.connectTo(fragmentOutput);\n // Add to nodes\n this.addOutputNode(vertexOutput);\n this.addOutputNode(fragmentOutput);\n this._mode = NodeMaterialModes.Material;\n }\n /**\n * Clear the current material and set it to a default state for post process\n */\n setToDefaultPostProcess() {\n this.clear();\n this.editorData = null;\n const position = new InputBlock(\"Position\");\n position.setAsAttribute(\"position2d\");\n const const1 = new InputBlock(\"Constant1\");\n const1.isConstant = true;\n const1.value = 1;\n const vmerger = new VectorMergerBlock(\"Position3D\");\n position.connectTo(vmerger);\n const1.connectTo(vmerger, { input: \"w\" });\n const vertexOutput = new VertexOutputBlock(\"VertexOutput\");\n vmerger.connectTo(vertexOutput);\n // Pixel\n const scale = new InputBlock(\"Scale\");\n scale.visibleInInspector = true;\n scale.value = new Vector2(1, 1);\n const uv0 = new RemapBlock(\"uv0\");\n position.connectTo(uv0);\n const uv = new MultiplyBlock(\"UV scale\");\n uv0.connectTo(uv);\n scale.connectTo(uv);\n const currentScreen = new CurrentScreenBlock(\"CurrentScreen\");\n uv.connectTo(currentScreen);\n currentScreen.texture = new Texture(\"https://assets.babylonjs.com/nme/currentScreenPostProcess.png\", this.getScene());\n const fragmentOutput = new FragmentOutputBlock(\"FragmentOutput\");\n currentScreen.connectTo(fragmentOutput, { output: \"rgba\" });\n // Add to nodes\n this.addOutputNode(vertexOutput);\n this.addOutputNode(fragmentOutput);\n this._mode = NodeMaterialModes.PostProcess;\n }\n /**\n * Clear the current material and set it to a default state for procedural texture\n */\n setToDefaultProceduralTexture() {\n this.clear();\n this.editorData = null;\n const position = new InputBlock(\"Position\");\n position.setAsAttribute(\"position2d\");\n const const1 = new InputBlock(\"Constant1\");\n const1.isConstant = true;\n const1.value = 1;\n const vmerger = new VectorMergerBlock(\"Position3D\");\n position.connectTo(vmerger);\n const1.connectTo(vmerger, { input: \"w\" });\n const vertexOutput = new VertexOutputBlock(\"VertexOutput\");\n vmerger.connectTo(vertexOutput);\n // Pixel\n const time = new InputBlock(\"Time\");\n time.value = 0;\n time.min = 0;\n time.max = 0;\n time.isBoolean = false;\n time.matrixMode = 0;\n time.animationType = AnimatedInputBlockTypes.Time;\n time.isConstant = false;\n const color = new InputBlock(\"Color3\");\n color.value = new Color3(1, 1, 1);\n color.isConstant = false;\n const fragmentOutput = new FragmentOutputBlock(\"FragmentOutput\");\n const vectorMerger = new VectorMergerBlock(\"VectorMerger\");\n vectorMerger.visibleInInspector = false;\n const cos = new TrigonometryBlock(\"Cos\");\n cos.operation = TrigonometryBlockOperations.Cos;\n position.connectTo(vectorMerger);\n time.output.connectTo(cos.input);\n cos.output.connectTo(vectorMerger.z);\n vectorMerger.xyzOut.connectTo(fragmentOutput.rgb);\n // Add to nodes\n this.addOutputNode(vertexOutput);\n this.addOutputNode(fragmentOutput);\n this._mode = NodeMaterialModes.ProceduralTexture;\n }\n /**\n * Clear the current material and set it to a default state for particle\n */\n setToDefaultParticle() {\n this.clear();\n this.editorData = null;\n // Pixel\n const uv = new InputBlock(\"uv\");\n uv.setAsAttribute(\"particle_uv\");\n const texture = new ParticleTextureBlock(\"ParticleTexture\");\n uv.connectTo(texture);\n const color = new InputBlock(\"Color\");\n color.setAsAttribute(\"particle_color\");\n const multiply = new MultiplyBlock(\"Texture * Color\");\n texture.connectTo(multiply);\n color.connectTo(multiply);\n const rampGradient = new ParticleRampGradientBlock(\"ParticleRampGradient\");\n multiply.connectTo(rampGradient);\n const cSplitter = new ColorSplitterBlock(\"ColorSplitter\");\n color.connectTo(cSplitter);\n const blendMultiply = new ParticleBlendMultiplyBlock(\"ParticleBlendMultiply\");\n rampGradient.connectTo(blendMultiply);\n texture.connectTo(blendMultiply, { output: \"a\" });\n cSplitter.connectTo(blendMultiply, { output: \"a\" });\n const fragmentOutput = new FragmentOutputBlock(\"FragmentOutput\");\n blendMultiply.connectTo(fragmentOutput);\n // Add to nodes\n this.addOutputNode(fragmentOutput);\n this._mode = NodeMaterialModes.Particle;\n }\n /**\n * Loads the current Node Material from a url pointing to a file save by the Node Material Editor\n * @deprecated Please use NodeMaterial.ParseFromFileAsync instead\n * @param url defines the url to load from\n * @param rootUrl defines the root URL for nested url in the node material\n * @returns a promise that will fulfil when the material is fully loaded\n */\n async loadAsync(url, rootUrl = \"\") {\n return NodeMaterial.ParseFromFileAsync(\"\", url, this.getScene(), rootUrl, true, this);\n }\n _gatherBlocks(rootNode, list) {\n if (list.indexOf(rootNode) !== -1) {\n return;\n }\n list.push(rootNode);\n for (const input of rootNode.inputs) {\n const connectedPoint = input.connectedPoint;\n if (connectedPoint) {\n const block = connectedPoint.ownerBlock;\n if (block !== rootNode) {\n this._gatherBlocks(block, list);\n }\n }\n }\n }\n /**\n * Generate a string containing the code declaration required to create an equivalent of this material\n * @returns a string\n */\n generateCode() {\n let alreadyDumped = [];\n const vertexBlocks = [];\n const uniqueNames = [\"const\", \"var\", \"let\"];\n // Gets active blocks\n for (const outputNode of this._vertexOutputNodes) {\n this._gatherBlocks(outputNode, vertexBlocks);\n }\n const fragmentBlocks = [];\n for (const outputNode of this._fragmentOutputNodes) {\n this._gatherBlocks(outputNode, fragmentBlocks);\n }\n // Generate vertex shader\n let codeString = `var nodeMaterial = new BABYLON.NodeMaterial(\"${this.name || \"node material\"}\");\\r\\n`;\n for (const node of vertexBlocks) {\n if (node.isInput && alreadyDumped.indexOf(node) === -1) {\n codeString += node._dumpCode(uniqueNames, alreadyDumped);\n }\n }\n // Generate fragment shader\n for (const node of fragmentBlocks) {\n if (node.isInput && alreadyDumped.indexOf(node) === -1) {\n codeString += node._dumpCode(uniqueNames, alreadyDumped);\n }\n }\n // Connections\n alreadyDumped = [];\n codeString += \"\\r\\n// Connections\\r\\n\";\n for (const node of this._vertexOutputNodes) {\n codeString += node._dumpCodeForOutputConnections(alreadyDumped);\n }\n for (const node of this._fragmentOutputNodes) {\n codeString += node._dumpCodeForOutputConnections(alreadyDumped);\n }\n // Output nodes\n codeString += \"\\r\\n// Output nodes\\r\\n\";\n for (const node of this._vertexOutputNodes) {\n codeString += `nodeMaterial.addOutputNode(${node._codeVariableName});\\r\\n`;\n }\n for (const node of this._fragmentOutputNodes) {\n codeString += `nodeMaterial.addOutputNode(${node._codeVariableName});\\r\\n`;\n }\n codeString += `nodeMaterial.build();\\r\\n`;\n return codeString;\n }\n /**\n * Serializes this material in a JSON representation\n * @param selectedBlocks\n * @returns the serialized material object\n */\n serialize(selectedBlocks) {\n const serializationObject = selectedBlocks ? {} : SerializationHelper.Serialize(this);\n serializationObject.editorData = JSON.parse(JSON.stringify(this.editorData)); // Copy\n let blocks = [];\n if (selectedBlocks) {\n blocks = selectedBlocks;\n }\n else {\n serializationObject.customType = \"BABYLON.NodeMaterial\";\n serializationObject.outputNodes = [];\n // Outputs\n for (const outputNode of this._vertexOutputNodes) {\n this._gatherBlocks(outputNode, blocks);\n serializationObject.outputNodes.push(outputNode.uniqueId);\n }\n for (const outputNode of this._fragmentOutputNodes) {\n this._gatherBlocks(outputNode, blocks);\n if (serializationObject.outputNodes.indexOf(outputNode.uniqueId) === -1) {\n serializationObject.outputNodes.push(outputNode.uniqueId);\n }\n }\n }\n // Blocks\n serializationObject.blocks = [];\n for (const block of blocks) {\n serializationObject.blocks.push(block.serialize());\n }\n if (!selectedBlocks) {\n for (const block of this.attachedBlocks) {\n if (blocks.indexOf(block) !== -1) {\n continue;\n }\n serializationObject.blocks.push(block.serialize());\n }\n }\n return serializationObject;\n }\n _restoreConnections(block, source, map) {\n for (const outputPoint of block.outputs) {\n for (const candidate of source.blocks) {\n const target = map[candidate.id];\n if (!target) {\n continue;\n }\n for (const input of candidate.inputs) {\n if (map[input.targetBlockId] === block && input.targetConnectionName === outputPoint.name) {\n const inputPoint = target.getInputByName(input.inputName);\n if (!inputPoint || inputPoint.isConnected) {\n continue;\n }\n outputPoint.connectTo(inputPoint, true);\n this._restoreConnections(target, source, map);\n continue;\n }\n }\n }\n }\n }\n /**\n * Clear the current graph and load a new one from a serialization object\n * @param source defines the JSON representation of the material\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @param merge defines whether or not the source must be merged or replace the current content\n */\n parseSerializedObject(source, rootUrl = \"\", merge = false) {\n var _a;\n if (!merge) {\n this.clear();\n }\n const map = {};\n // Create blocks\n for (const parsedBlock of source.blocks) {\n const blockType = GetClass(parsedBlock.customType);\n if (blockType) {\n const block = new blockType();\n block._deserialize(parsedBlock, this.getScene(), rootUrl);\n map[parsedBlock.id] = block;\n this.attachedBlocks.push(block);\n }\n }\n // Connections - Starts with input blocks only (except if in \"merge\" mode where we scan all blocks)\n for (let blockIndex = 0; blockIndex < source.blocks.length; blockIndex++) {\n const parsedBlock = source.blocks[blockIndex];\n const block = map[parsedBlock.id];\n if (!block) {\n continue;\n }\n if (block.inputs.length && !merge) {\n continue;\n }\n this._restoreConnections(block, source, map);\n }\n // Outputs\n if (source.outputNodes) {\n for (const outputNodeId of source.outputNodes) {\n this.addOutputNode(map[outputNodeId]);\n }\n }\n // UI related info\n if (source.locations || (source.editorData && source.editorData.locations)) {\n const locations = source.locations || source.editorData.locations;\n for (const location of locations) {\n if (map[location.blockId]) {\n location.blockId = map[location.blockId].uniqueId;\n }\n }\n if (merge && this.editorData && this.editorData.locations) {\n locations.concat(this.editorData.locations);\n }\n if (source.locations) {\n this.editorData = {\n locations: locations,\n };\n }\n else {\n this.editorData = source.editorData;\n this.editorData.locations = locations;\n }\n const blockMap = [];\n for (const key in map) {\n blockMap[key] = map[key].uniqueId;\n }\n this.editorData.map = blockMap;\n }\n this.comment = source.comment;\n if (source.forceAlphaBlending !== undefined) {\n this.forceAlphaBlending = source.forceAlphaBlending;\n }\n if (!merge) {\n this._mode = (_a = source.mode) !== null && _a !== void 0 ? _a : NodeMaterialModes.Material;\n }\n }\n /**\n * Clear the current graph and load a new one from a serialization object\n * @param source defines the JSON representation of the material\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @param merge defines whether or not the source must be merged or replace the current content\n * @deprecated Please use the parseSerializedObject method instead\n */\n loadFromSerialization(source, rootUrl = \"\", merge = false) {\n this.parseSerializedObject(source, rootUrl, merge);\n }\n /**\n * Makes a duplicate of the current material.\n * @param name defines the name to use for the new material\n * @param shareEffect defines if the clone material should share the same effect (default is false)\n */\n clone(name, shareEffect = false) {\n const serializationObject = this.serialize();\n const clone = SerializationHelper.Clone(() => new NodeMaterial(name, this.getScene(), this.options), this);\n clone.id = name;\n clone.name = name;\n clone.parseSerializedObject(serializationObject);\n clone._buildId = this._buildId;\n clone.build(false, !shareEffect);\n return clone;\n }\n /**\n * Creates a node material from parsed material data\n * @param source defines the JSON representation of the material\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @returns a new node material\n */\n static Parse(source, scene, rootUrl = \"\") {\n const nodeMaterial = SerializationHelper.Parse(() => new NodeMaterial(source.name, scene), source, scene, rootUrl);\n nodeMaterial.parseSerializedObject(source, rootUrl);\n nodeMaterial.build();\n return nodeMaterial;\n }\n /**\n * Creates a node material from a snippet saved in a remote file\n * @param name defines the name of the material to create\n * @param url defines the url to load from\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL for nested url in the node material\n * @param skipBuild defines whether to build the node material\n * @param targetMaterial defines a material to use instead of creating a new one\n * @returns a promise that will resolve to the new node material\n */\n static async ParseFromFileAsync(name, url, scene, rootUrl = \"\", skipBuild = false, targetMaterial) {\n const material = targetMaterial !== null && targetMaterial !== void 0 ? targetMaterial : new NodeMaterial(name, scene);\n const data = await scene._loadFileAsync(url);\n const serializationObject = JSON.parse(data);\n material.parseSerializedObject(serializationObject, rootUrl);\n if (!skipBuild) {\n material.build();\n }\n return material;\n }\n /**\n * Creates a node material from a snippet saved by the node material editor\n * @param snippetId defines the snippet to load\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @param nodeMaterial defines a node material to update (instead of creating a new one)\n * @param skipBuild defines whether to build the node material\n * @returns a promise that will resolve to the new node material\n */\n static ParseFromSnippetAsync(snippetId, scene = EngineStore.LastCreatedScene, rootUrl = \"\", nodeMaterial, skipBuild = false) {\n if (snippetId === \"_BLANK\") {\n return Promise.resolve(NodeMaterial.CreateDefault(\"blank\", scene));\n }\n return new Promise((resolve, reject) => {\n const request = new WebRequest();\n request.addEventListener(\"readystatechange\", () => {\n if (request.readyState == 4) {\n if (request.status == 200) {\n const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload);\n const serializationObject = JSON.parse(snippet.nodeMaterial);\n if (!nodeMaterial) {\n nodeMaterial = SerializationHelper.Parse(() => new NodeMaterial(snippetId, scene), serializationObject, scene, rootUrl);\n nodeMaterial.uniqueId = scene.getUniqueId();\n }\n nodeMaterial.parseSerializedObject(serializationObject);\n nodeMaterial.snippetId = snippetId;\n try {\n if (!skipBuild) {\n nodeMaterial.build();\n }\n resolve(nodeMaterial);\n }\n catch (err) {\n reject(err);\n }\n }\n else {\n reject(\"Unable to load the snippet \" + snippetId);\n }\n }\n });\n request.open(\"GET\", this.SnippetUrl + \"/\" + snippetId.replace(/#/g, \"/\"));\n request.send();\n });\n }\n /**\n * Creates a new node material set to default basic configuration\n * @param name defines the name of the material\n * @param scene defines the hosting scene\n * @returns a new NodeMaterial\n */\n static CreateDefault(name, scene) {\n const newMaterial = new NodeMaterial(name, scene);\n newMaterial.setToDefault();\n newMaterial.build();\n return newMaterial;\n }\n}\nNodeMaterial._BuildIdGenerator = 0;\n/** Define the Url to load node editor script */\nNodeMaterial.EditorURL = `https://unpkg.com/babylonjs-node-editor@${Engine.Version}/babylon.nodeEditor.js`;\n/** Define the Url to load snippets */\nNodeMaterial.SnippetUrl = `https://snippet.babylonjs.com`;\n/** Gets or sets a boolean indicating that node materials should not deserialize textures from json / snippet content */\nNodeMaterial.IgnoreTexturesAtLoadTime = false;\n__decorate([\n serialize()\n], NodeMaterial.prototype, \"ignoreAlpha\", void 0);\n__decorate([\n serialize()\n], NodeMaterial.prototype, \"maxSimultaneousLights\", void 0);\n__decorate([\n serialize(\"mode\")\n], NodeMaterial.prototype, \"_mode\", void 0);\n__decorate([\n serialize(\"comment\")\n], NodeMaterial.prototype, \"comment\", void 0);\n__decorate([\n serialize()\n], NodeMaterial.prototype, \"forceAlphaBlending\", void 0);\nRegisterClass(\"BABYLON.NodeMaterial\", NodeMaterial);\n//# sourceMappingURL=nodeMaterial.js.map","import { Vector3, Vector2 } from \"../../Maths/math.vector.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n/**\n * Creates the VertexData of the IcoSphere\n * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty\n * * radius the radius of the IcoSphere, optional default 1\n * * radiusX allows stretching in the x direction, optional, default radius\n * * radiusY allows stretching in the y direction, optional, default radius\n * * radiusZ allows stretching in the z direction, optional, default radius\n * * flat when true creates a flat shaded mesh, optional, default true\n * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.radius\n * @param options.radiusX\n * @param options.radiusY\n * @param options.radiusZ\n * @param options.flat\n * @param options.subdivisions\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the IcoSphere\n */\nexport function CreateIcoSphereVertexData(options) {\n const sideOrientation = options.sideOrientation || VertexData.DEFAULTSIDE;\n const radius = options.radius || 1;\n const flat = options.flat === undefined ? true : options.flat;\n const subdivisions = options.subdivisions || 4;\n const radiusX = options.radiusX || radius;\n const radiusY = options.radiusY || radius;\n const radiusZ = options.radiusZ || radius;\n const t = (1 + Math.sqrt(5)) / 2;\n // 12 vertex x,y,z\n const icoVertices = [\n -1,\n t,\n -0,\n 1,\n t,\n 0,\n -1,\n -t,\n 0,\n 1,\n -t,\n 0,\n 0,\n -1,\n -t,\n 0,\n 1,\n -t,\n 0,\n -1,\n t,\n 0,\n 1,\n t,\n t,\n 0,\n 1,\n t,\n 0,\n -1,\n -t,\n 0,\n 1,\n -t,\n 0,\n -1, // v8-11\n ];\n // index of 3 vertex makes a face of icopshere\n const ico_indices = [\n 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23, 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8, 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9, 4, 21, 5, 13, 17,\n 23, 6, 13, 22, 19, 6, 18, 9, 8, 1,\n ];\n // vertex for uv have aliased position, not for UV\n const vertices_unalias_id = [\n 0,\n 1,\n 2,\n 3,\n 4,\n 5,\n 6,\n 7,\n 8,\n 9,\n 10,\n 11,\n // vertex alias\n 0,\n 2,\n 3,\n 3,\n 3,\n 4,\n 7,\n 8,\n 9,\n 9,\n 10,\n 11, // 23: B + 12\n ];\n // uv as integer step (not pixels !)\n const ico_vertexuv = [\n 5,\n 1,\n 3,\n 1,\n 6,\n 4,\n 0,\n 0,\n 5,\n 3,\n 4,\n 2,\n 2,\n 2,\n 4,\n 0,\n 2,\n 0,\n 1,\n 1,\n 6,\n 0,\n 6,\n 2,\n // vertex alias (for same vertex on different faces)\n 0,\n 4,\n 3,\n 3,\n 4,\n 4,\n 3,\n 1,\n 4,\n 2,\n 4,\n 4,\n 0,\n 2,\n 1,\n 1,\n 2,\n 2,\n 3,\n 3,\n 1,\n 3,\n 2,\n 4, // 23: B + 12\n ];\n // Vertices[0, 1, ...9, A, B] : position on UV plane\n // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)\n // First island of uv mapping\n // v = 4h 3+ 2\n // v = 3h 9+ 4\n // v = 2h 9+ 5 B\n // v = 1h 9 1 0\n // v = 0h 3 8 7 A\n // u = 0 1 2 3 4 5 6 *a\n // Second island of uv mapping\n // v = 4h 0+ B+ 4+\n // v = 3h A+ 2+\n // v = 2h 7+ 6 3+\n // v = 1h 8+ 3+\n // v = 0h\n // u = 0 1 2 3 4 5 6 *a\n // Face layout on texture UV mapping\n // ============\n // \\ 4 /\\ 16 / ======\n // \\ / \\ / /\\ 11 /\n // \\/ 7 \\/ / \\ /\n // ======= / 10 \\/\n // /\\ 17 /\\ =======\n // / \\ / \\ \\ 15 /\\\n // / 8 \\/ 12 \\ \\ / \\\n // ============ \\/ 6 \\\n // \\ 18 /\\ ============\n // \\ / \\ \\ 5 /\\ 0 /\n // \\/ 13 \\ \\ / \\ /\n // ======= \\/ 1 \\/\n // =============\n // /\\ 19 /\\ 2 /\\\n // / \\ / \\ / \\\n // / 14 \\/ 9 \\/ 3 \\\n // ===================\n // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97\n const ustep = 138 / 1024;\n const vstep = 239 / 1024;\n const uoffset = 60 / 1024;\n const voffset = 26 / 1024;\n // Second island should have margin, not to touch the first island\n // avoid any borderline artefact in pixel rounding\n const island_u_offset = -40 / 1024;\n const island_v_offset = +20 / 1024;\n // face is either island 0 or 1 :\n // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]\n const island = [\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n 0,\n 1,\n 1,\n 0,\n 0,\n 0,\n 1,\n 1,\n 0,\n 0,\n 1,\n 1,\n 1,\n 0, // 15 - 19\n ];\n const indices = new Array();\n const positions = new Array();\n const normals = new Array();\n const uvs = new Array();\n let current_indice = 0;\n // prepare array of 3 vector (empty) (to be worked in place, shared for each face)\n const face_vertex_pos = new Array(3);\n const face_vertex_uv = new Array(3);\n let v012;\n for (v012 = 0; v012 < 3; v012++) {\n face_vertex_pos[v012] = Vector3.Zero();\n face_vertex_uv[v012] = Vector2.Zero();\n }\n // create all with normals\n for (let face = 0; face < 20; face++) {\n // 3 vertex per face\n for (v012 = 0; v012 < 3; v012++) {\n // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)\n const v_id = ico_indices[3 * face + v012];\n // vertex have 3D position (x,y,z)\n face_vertex_pos[v012].copyFromFloats(icoVertices[3 * vertices_unalias_id[v_id]], icoVertices[3 * vertices_unalias_id[v_id] + 1], icoVertices[3 * vertices_unalias_id[v_id] + 2]);\n // Normalize to get normal\n face_vertex_pos[v012].normalize();\n // uv Coordinates from vertex ID\n face_vertex_uv[v012].copyFromFloats(ico_vertexuv[2 * v_id] * ustep + uoffset + island[face] * island_u_offset, ico_vertexuv[2 * v_id + 1] * vstep + voffset + island[face] * island_v_offset);\n }\n // Subdivide the face (interpolate pos, norm, uv)\n // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)\n // - norm is linear interpolation of vertex corner normal\n // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )\n // - uv is linear interpolation\n //\n // Topology is as below for sub-divide by 2\n // vertex shown as v0,v1,v2\n // interp index is i1 to progress in range [v0,v1[\n // interp index is i2 to progress in range [v0,v2[\n // face index as (i1,i2) for /\\ : (i1,i2),(i1+1,i2),(i1,i2+1)\n // and (i1,i2)' for \\/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)\n //\n //\n // i2 v2\n // ^ ^\n // / / \\\n // / / \\\n // / / \\\n // / / (0,1) \\\n // / #---------\\\n // / / \\ (0,0)'/ \\\n // / / \\ / \\\n // / / \\ / \\\n // / / (0,0) \\ / (1,0) \\\n // / #---------#---------\\\n // v0 v1\n //\n // --------------------> i1\n //\n // interp of (i1,i2):\n // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)\n // along i1 : lerp(x0,x1, i1/(S-i2))\n //\n // centroid of triangle is needed to get help normal computation\n // (c1,c2) are used for centroid location\n const interp_vertex = (i1, i2, c1, c2) => {\n // vertex is interpolated from\n // - face_vertex_pos[0..2]\n // - face_vertex_uv[0..2]\n const pos_x0 = Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);\n const pos_x1 = Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);\n const pos_interp = subdivisions === i2 ? face_vertex_pos[2] : Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));\n pos_interp.normalize();\n let vertex_normal;\n if (flat) {\n // in flat mode, recalculate normal as face centroid normal\n const centroid_x0 = Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);\n const centroid_x1 = Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);\n vertex_normal = Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));\n }\n else {\n // in smooth mode, recalculate normal from each single vertex position\n vertex_normal = new Vector3(pos_interp.x, pos_interp.y, pos_interp.z);\n }\n // Vertex normal need correction due to X,Y,Z radius scaling\n vertex_normal.x /= radiusX;\n vertex_normal.y /= radiusY;\n vertex_normal.z /= radiusZ;\n vertex_normal.normalize();\n const uv_x0 = Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);\n const uv_x1 = Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);\n const uv_interp = subdivisions === i2 ? face_vertex_uv[2] : Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));\n positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);\n normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);\n uvs.push(uv_interp.x, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - uv_interp.y : uv_interp.y);\n // push each vertex has member of a face\n // Same vertex can belong to multiple face, it is pushed multiple time (duplicate vertex are present)\n indices.push(current_indice);\n current_indice++;\n };\n for (let i2 = 0; i2 < subdivisions; i2++) {\n for (let i1 = 0; i1 + i2 < subdivisions; i1++) {\n // face : (i1,i2) for /\\ :\n // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)\n interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);\n interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);\n interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);\n if (i1 + i2 + 1 < subdivisions) {\n // face : (i1,i2)' for \\/ :\n // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)\n interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);\n interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);\n interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);\n }\n }\n }\n }\n // Sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Result\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n}\n/**\n * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided\n * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)\n * * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value of `radius`)\n * * The parameter `subdivisions` sets the number of subdivisions (positive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size\n * * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.radius\n * @param options.radiusX\n * @param options.radiusY\n * @param options.radiusZ\n * @param options.flat\n * @param options.subdivisions\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.updatable\n * @param scene defines the hosting scene\n * @returns the icosahedron mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/polyhedra#icosphere\n */\nexport function CreateIcoSphere(name, options = {}, scene = null) {\n const sphere = new Mesh(name, scene);\n options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n sphere._originalBuilderSideOrientation = options.sideOrientation;\n const vertexData = CreateIcoSphereVertexData(options);\n vertexData.applyToMesh(sphere, options.updatable);\n return sphere;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use the function directly from the module\n */\nexport const IcoSphereBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateIcoSphere,\n};\nVertexData.CreateIcoSphere = CreateIcoSphereVertexData;\nMesh.CreateIcoSphere = (name, options, scene) => {\n return CreateIcoSphere(name, options, scene);\n};\n//# sourceMappingURL=icoSphereBuilder.js.map","import { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nimport { WebXRFeatureName, WebXRFeaturesManager } from \"../webXRFeaturesManager.js\";\nimport { Matrix, Quaternion } from \"../../Maths/math.vector.js\";\nimport { PhysicsImpostor } from \"../../Physics/v1/physicsImpostor.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { SceneLoader } from \"../../Loading/sceneLoader.js\";\nimport { Color3 } from \"../../Maths/math.color.js\";\nimport { NodeMaterial } from \"../../Materials/Node/nodeMaterial.js\";\nimport { Material } from \"../../Materials/material.js\";\nimport { CreateIcoSphere } from \"../../Meshes/Builders/icoSphereBuilder.js\";\nimport { TransformNode } from \"../../Meshes/transformNode.js\";\nimport { Axis } from \"../../Maths/math.axis.js\";\nimport { EngineStore } from \"../../Engines/engineStore.js\";\n\n/**\n * Parts of the hands divided to writs and finger names\n */\nexport var HandPart;\n(function (HandPart) {\n /**\n * HandPart - Wrist\n */\n HandPart[\"WRIST\"] = \"wrist\";\n /**\n * HandPart - The thumb\n */\n HandPart[\"THUMB\"] = \"thumb\";\n /**\n * HandPart - Index finger\n */\n HandPart[\"INDEX\"] = \"index\";\n /**\n * HandPart - Middle finger\n */\n HandPart[\"MIDDLE\"] = \"middle\";\n /**\n * HandPart - Ring finger\n */\n HandPart[\"RING\"] = \"ring\";\n /**\n * HandPart - Little finger\n */\n HandPart[\"LITTLE\"] = \"little\";\n})(HandPart || (HandPart = {}));\n/**\n * Joints of the hand as defined by the WebXR specification.\n * https://immersive-web.github.io/webxr-hand-input/#skeleton-joints-section\n */\nexport var WebXRHandJoint;\n(function (WebXRHandJoint) {\n /** Wrist */\n WebXRHandJoint[\"WRIST\"] = \"wrist\";\n /** Thumb near wrist */\n WebXRHandJoint[\"THUMB_METACARPAL\"] = \"thumb-metacarpal\";\n /** Thumb first knuckle */\n WebXRHandJoint[\"THUMB_PHALANX_PROXIMAL\"] = \"thumb-phalanx-proximal\";\n /** Thumb second knuckle */\n WebXRHandJoint[\"THUMB_PHALANX_DISTAL\"] = \"thumb-phalanx-distal\";\n /** Thumb tip */\n WebXRHandJoint[\"THUMB_TIP\"] = \"thumb-tip\";\n /** Index finger near wrist */\n WebXRHandJoint[\"INDEX_FINGER_METACARPAL\"] = \"index-finger-metacarpal\";\n /** Index finger first knuckle */\n WebXRHandJoint[\"INDEX_FINGER_PHALANX_PROXIMAL\"] = \"index-finger-phalanx-proximal\";\n /** Index finger second knuckle */\n WebXRHandJoint[\"INDEX_FINGER_PHALANX_INTERMEDIATE\"] = \"index-finger-phalanx-intermediate\";\n /** Index finger third knuckle */\n WebXRHandJoint[\"INDEX_FINGER_PHALANX_DISTAL\"] = \"index-finger-phalanx-distal\";\n /** Index finger tip */\n WebXRHandJoint[\"INDEX_FINGER_TIP\"] = \"index-finger-tip\";\n /** Middle finger near wrist */\n WebXRHandJoint[\"MIDDLE_FINGER_METACARPAL\"] = \"middle-finger-metacarpal\";\n /** Middle finger first knuckle */\n WebXRHandJoint[\"MIDDLE_FINGER_PHALANX_PROXIMAL\"] = \"middle-finger-phalanx-proximal\";\n /** Middle finger second knuckle */\n WebXRHandJoint[\"MIDDLE_FINGER_PHALANX_INTERMEDIATE\"] = \"middle-finger-phalanx-intermediate\";\n /** Middle finger third knuckle */\n WebXRHandJoint[\"MIDDLE_FINGER_PHALANX_DISTAL\"] = \"middle-finger-phalanx-distal\";\n /** Middle finger tip */\n WebXRHandJoint[\"MIDDLE_FINGER_TIP\"] = \"middle-finger-tip\";\n /** Ring finger near wrist */\n WebXRHandJoint[\"RING_FINGER_METACARPAL\"] = \"ring-finger-metacarpal\";\n /** Ring finger first knuckle */\n WebXRHandJoint[\"RING_FINGER_PHALANX_PROXIMAL\"] = \"ring-finger-phalanx-proximal\";\n /** Ring finger second knuckle */\n WebXRHandJoint[\"RING_FINGER_PHALANX_INTERMEDIATE\"] = \"ring-finger-phalanx-intermediate\";\n /** Ring finger third knuckle */\n WebXRHandJoint[\"RING_FINGER_PHALANX_DISTAL\"] = \"ring-finger-phalanx-distal\";\n /** Ring finger tip */\n WebXRHandJoint[\"RING_FINGER_TIP\"] = \"ring-finger-tip\";\n /** Pinky finger near wrist */\n WebXRHandJoint[\"PINKY_FINGER_METACARPAL\"] = \"pinky-finger-metacarpal\";\n /** Pinky finger first knuckle */\n WebXRHandJoint[\"PINKY_FINGER_PHALANX_PROXIMAL\"] = \"pinky-finger-phalanx-proximal\";\n /** Pinky finger second knuckle */\n WebXRHandJoint[\"PINKY_FINGER_PHALANX_INTERMEDIATE\"] = \"pinky-finger-phalanx-intermediate\";\n /** Pinky finger third knuckle */\n WebXRHandJoint[\"PINKY_FINGER_PHALANX_DISTAL\"] = \"pinky-finger-phalanx-distal\";\n /** Pinky finger tip */\n WebXRHandJoint[\"PINKY_FINGER_TIP\"] = \"pinky-finger-tip\";\n})(WebXRHandJoint || (WebXRHandJoint = {}));\nconst handJointReferenceArray = [\n WebXRHandJoint.WRIST,\n WebXRHandJoint.THUMB_METACARPAL,\n WebXRHandJoint.THUMB_PHALANX_PROXIMAL,\n WebXRHandJoint.THUMB_PHALANX_DISTAL,\n WebXRHandJoint.THUMB_TIP,\n WebXRHandJoint.INDEX_FINGER_METACARPAL,\n WebXRHandJoint.INDEX_FINGER_PHALANX_PROXIMAL,\n WebXRHandJoint.INDEX_FINGER_PHALANX_INTERMEDIATE,\n WebXRHandJoint.INDEX_FINGER_PHALANX_DISTAL,\n WebXRHandJoint.INDEX_FINGER_TIP,\n WebXRHandJoint.MIDDLE_FINGER_METACARPAL,\n WebXRHandJoint.MIDDLE_FINGER_PHALANX_PROXIMAL,\n WebXRHandJoint.MIDDLE_FINGER_PHALANX_INTERMEDIATE,\n WebXRHandJoint.MIDDLE_FINGER_PHALANX_DISTAL,\n WebXRHandJoint.MIDDLE_FINGER_TIP,\n WebXRHandJoint.RING_FINGER_METACARPAL,\n WebXRHandJoint.RING_FINGER_PHALANX_PROXIMAL,\n WebXRHandJoint.RING_FINGER_PHALANX_INTERMEDIATE,\n WebXRHandJoint.RING_FINGER_PHALANX_DISTAL,\n WebXRHandJoint.RING_FINGER_TIP,\n WebXRHandJoint.PINKY_FINGER_METACARPAL,\n WebXRHandJoint.PINKY_FINGER_PHALANX_PROXIMAL,\n WebXRHandJoint.PINKY_FINGER_PHALANX_INTERMEDIATE,\n WebXRHandJoint.PINKY_FINGER_PHALANX_DISTAL,\n WebXRHandJoint.PINKY_FINGER_TIP,\n];\nconst handPartsDefinition = {\n [HandPart.WRIST]: [WebXRHandJoint.WRIST],\n [HandPart.THUMB]: [WebXRHandJoint.THUMB_METACARPAL, WebXRHandJoint.THUMB_PHALANX_PROXIMAL, WebXRHandJoint.THUMB_PHALANX_DISTAL, WebXRHandJoint.THUMB_TIP],\n [HandPart.INDEX]: [\n WebXRHandJoint.INDEX_FINGER_METACARPAL,\n WebXRHandJoint.INDEX_FINGER_PHALANX_PROXIMAL,\n WebXRHandJoint.INDEX_FINGER_PHALANX_INTERMEDIATE,\n WebXRHandJoint.INDEX_FINGER_PHALANX_DISTAL,\n WebXRHandJoint.INDEX_FINGER_TIP,\n ],\n [HandPart.MIDDLE]: [\n WebXRHandJoint.MIDDLE_FINGER_METACARPAL,\n WebXRHandJoint.MIDDLE_FINGER_PHALANX_PROXIMAL,\n WebXRHandJoint.MIDDLE_FINGER_PHALANX_INTERMEDIATE,\n WebXRHandJoint.MIDDLE_FINGER_PHALANX_DISTAL,\n WebXRHandJoint.MIDDLE_FINGER_TIP,\n ],\n [HandPart.RING]: [\n WebXRHandJoint.RING_FINGER_METACARPAL,\n WebXRHandJoint.RING_FINGER_PHALANX_PROXIMAL,\n WebXRHandJoint.RING_FINGER_PHALANX_INTERMEDIATE,\n WebXRHandJoint.RING_FINGER_PHALANX_DISTAL,\n WebXRHandJoint.RING_FINGER_TIP,\n ],\n [HandPart.LITTLE]: [\n WebXRHandJoint.PINKY_FINGER_METACARPAL,\n WebXRHandJoint.PINKY_FINGER_PHALANX_PROXIMAL,\n WebXRHandJoint.PINKY_FINGER_PHALANX_INTERMEDIATE,\n WebXRHandJoint.PINKY_FINGER_PHALANX_DISTAL,\n WebXRHandJoint.PINKY_FINGER_TIP,\n ],\n};\n/**\n * Representing a single hand (with its corresponding native XRHand object)\n */\nexport class WebXRHand {\n /**\n * Get the hand mesh.\n */\n get handMesh() {\n return this._handMesh;\n }\n /**\n * Get meshes of part of the hand.\n * @param part The part of hand to get.\n * @returns An array of meshes that correlate to the hand part requested.\n */\n getHandPartMeshes(part) {\n return handPartsDefinition[part].map((name) => this._jointMeshes[handJointReferenceArray.indexOf(name)]);\n }\n /**\n * Retrieves a mesh linked to a named joint in the hand.\n * @param jointName The name of the joint.\n * @returns An AbstractMesh whose position corresponds with the joint position.\n */\n getJointMesh(jointName) {\n return this._jointMeshes[handJointReferenceArray.indexOf(jointName)];\n }\n /**\n * Construct a new hand object\n * @param xrController The controller to which the hand correlates.\n * @param _jointMeshes The meshes to be used to track the hand joints.\n * @param _handMesh An optional hand mesh.\n * @param rigMapping An optional rig mapping for the hand mesh.\n * If not provided (but a hand mesh is provided),\n * it will be assumed that the hand mesh's bones are named\n * directly after the WebXR bone names.\n * @param _leftHandedMeshes Are the hand meshes left-handed-system meshes\n * @param _jointsInvisible Are the tracked joint meshes visible\n * @param _jointScaleFactor Scale factor for all joint meshes\n */\n constructor(\n /** The controller to which the hand correlates. */\n xrController, _jointMeshes, _handMesh, \n /** An optional rig mapping for the hand mesh. If not provided (but a hand mesh is provided),\n * it will be assumed that the hand mesh's bones are named directly after the WebXR bone names. */\n rigMapping, _leftHandedMeshes = false, _jointsInvisible = false, _jointScaleFactor = 1) {\n this.xrController = xrController;\n this._jointMeshes = _jointMeshes;\n this._handMesh = _handMesh;\n this.rigMapping = rigMapping;\n this._leftHandedMeshes = _leftHandedMeshes;\n this._jointsInvisible = _jointsInvisible;\n this._jointScaleFactor = _jointScaleFactor;\n /**\n * Transform nodes that will directly receive the transforms from the WebXR matrix data.\n */\n this._jointTransforms = new Array(handJointReferenceArray.length);\n /**\n * The float array that will directly receive the transform matrix data from WebXR.\n */\n this._jointTransformMatrices = new Float32Array(handJointReferenceArray.length * 16);\n this._tempJointMatrix = new Matrix();\n /**\n * The float array that will directly receive the joint radii from WebXR.\n */\n this._jointRadii = new Float32Array(handJointReferenceArray.length);\n this._scene = _jointMeshes[0].getScene();\n // Initialize the joint transform quaternions and link the transforms to the bones.\n for (let jointIdx = 0; jointIdx < this._jointTransforms.length; jointIdx++) {\n const jointTransform = (this._jointTransforms[jointIdx] = new TransformNode(handJointReferenceArray[jointIdx], this._scene));\n jointTransform.rotationQuaternion = new Quaternion();\n // Set the rotation quaternion so we can use it later for tracking.\n _jointMeshes[jointIdx].rotationQuaternion = new Quaternion();\n }\n if (_handMesh) {\n // Note that this logic needs to happen after we initialize the joint tracking transform nodes.\n this.setHandMesh(_handMesh, rigMapping);\n }\n // hide the motion controller, if available/loaded\n if (this.xrController.motionController) {\n if (this.xrController.motionController.rootMesh) {\n this.xrController.motionController.rootMesh.setEnabled(false);\n }\n else {\n this.xrController.motionController.onModelLoadedObservable.add((controller) => {\n if (controller.rootMesh) {\n controller.rootMesh.setEnabled(false);\n }\n });\n }\n }\n this.xrController.onMotionControllerInitObservable.add((motionController) => {\n motionController.onModelLoadedObservable.add((controller) => {\n if (controller.rootMesh) {\n controller.rootMesh.setEnabled(false);\n }\n });\n if (motionController.rootMesh) {\n motionController.rootMesh.setEnabled(false);\n }\n });\n }\n /**\n * Sets the current hand mesh to render for the WebXRHand.\n * @param handMesh The rigged hand mesh that will be tracked to the user's hand.\n * @param rigMapping The mapping from XRHandJoint to bone names to use with the mesh.\n */\n setHandMesh(handMesh, rigMapping) {\n this._handMesh = handMesh;\n // Avoid any strange frustum culling. We will manually control visibility via attach and detach.\n handMesh.alwaysSelectAsActiveMesh = true;\n handMesh.getChildMeshes().forEach((mesh) => (mesh.alwaysSelectAsActiveMesh = true));\n // Link the bones in the hand mesh to the transform nodes that will be bound to the WebXR tracked joints.\n if (this._handMesh.skeleton) {\n const handMeshSkeleton = this._handMesh.skeleton;\n handJointReferenceArray.forEach((jointName, jointIdx) => {\n const jointBoneIdx = handMeshSkeleton.getBoneIndexByName(rigMapping ? rigMapping[jointName] : jointName);\n if (jointBoneIdx !== -1) {\n handMeshSkeleton.bones[jointBoneIdx].linkTransformNode(this._jointTransforms[jointIdx]);\n }\n });\n }\n }\n /**\n * Update this hand from the latest xr frame.\n * @param xrFrame The latest frame received from WebXR.\n * @param referenceSpace The current viewer reference space.\n */\n updateFromXRFrame(xrFrame, referenceSpace) {\n const hand = this.xrController.inputSource.hand;\n if (!hand) {\n return;\n }\n // TODO: Modify webxr.d.ts to better match WebXR IDL so we don't need this any cast.\n const anyHand = hand;\n const jointSpaces = handJointReferenceArray.map((jointName) => anyHand[jointName] || hand.get(jointName));\n let trackingSuccessful = false;\n if (xrFrame.fillPoses && xrFrame.fillJointRadii) {\n trackingSuccessful = xrFrame.fillPoses(jointSpaces, referenceSpace, this._jointTransformMatrices) && xrFrame.fillJointRadii(jointSpaces, this._jointRadii);\n }\n else if (xrFrame.getJointPose) {\n trackingSuccessful = true;\n // Warning: This codepath is slow by comparison, only here for compat.\n for (let jointIdx = 0; jointIdx < jointSpaces.length; jointIdx++) {\n const jointPose = xrFrame.getJointPose(jointSpaces[jointIdx], referenceSpace);\n if (jointPose) {\n this._jointTransformMatrices.set(jointPose.transform.matrix, jointIdx * 16);\n this._jointRadii[jointIdx] = jointPose.radius || 0.008;\n }\n else {\n trackingSuccessful = false;\n break;\n }\n }\n }\n if (!trackingSuccessful) {\n return;\n }\n handJointReferenceArray.forEach((_jointName, jointIdx) => {\n const jointTransform = this._jointTransforms[jointIdx];\n Matrix.FromArrayToRef(this._jointTransformMatrices, jointIdx * 16, this._tempJointMatrix);\n this._tempJointMatrix.decompose(undefined, jointTransform.rotationQuaternion, jointTransform.position);\n // The radius we need to make the joint in order for it to roughly cover the joints of the user's real hand.\n const scaledJointRadius = this._jointRadii[jointIdx] * this._jointScaleFactor;\n const jointMesh = this._jointMeshes[jointIdx];\n jointMesh.isVisible = !this._handMesh && !this._jointsInvisible;\n jointMesh.position.copyFrom(jointTransform.position);\n jointMesh.rotationQuaternion.copyFrom(jointTransform.rotationQuaternion);\n jointMesh.scaling.setAll(scaledJointRadius);\n // The WebXR data comes as right-handed, so we might need to do some conversions.\n if (!this._scene.useRightHandedSystem) {\n jointMesh.position.z *= -1;\n jointMesh.rotationQuaternion.z *= -1;\n jointMesh.rotationQuaternion.w *= -1;\n if (this._leftHandedMeshes && this._handMesh) {\n jointTransform.position.z *= -1;\n jointTransform.rotationQuaternion.z *= -1;\n jointTransform.rotationQuaternion.w *= -1;\n }\n }\n });\n if (this._handMesh) {\n this._handMesh.isVisible = true;\n }\n }\n /**\n * Dispose this Hand object\n */\n dispose() {\n if (this._handMesh) {\n this._handMesh.isVisible = false;\n }\n }\n}\n/**\n * WebXR Hand Joint tracking feature, available for selected browsers and devices\n */\nexport class WebXRHandTracking extends WebXRAbstractFeature {\n static _GenerateTrackedJointMeshes(featureOptions) {\n const meshes = {};\n [\"left\", \"right\"].map((handedness) => {\n var _a, _b, _c, _d, _e;\n const trackedMeshes = [];\n const originalMesh = ((_a = featureOptions.jointMeshes) === null || _a === void 0 ? void 0 : _a.sourceMesh) || CreateIcoSphere(\"jointParent\", WebXRHandTracking._ICOSPHERE_PARAMS);\n originalMesh.isVisible = !!((_b = featureOptions.jointMeshes) === null || _b === void 0 ? void 0 : _b.keepOriginalVisible);\n for (let i = 0; i < handJointReferenceArray.length; ++i) {\n let newInstance = originalMesh.createInstance(`${handedness}-handJoint-${i}`);\n if ((_c = featureOptions.jointMeshes) === null || _c === void 0 ? void 0 : _c.onHandJointMeshGenerated) {\n const returnedMesh = featureOptions.jointMeshes.onHandJointMeshGenerated(newInstance, i, handedness);\n if (returnedMesh) {\n if (returnedMesh !== newInstance) {\n newInstance.dispose();\n newInstance = returnedMesh;\n }\n }\n }\n newInstance.isPickable = false;\n if ((_d = featureOptions.jointMeshes) === null || _d === void 0 ? void 0 : _d.enablePhysics) {\n const props = ((_e = featureOptions.jointMeshes) === null || _e === void 0 ? void 0 : _e.physicsProps) || {};\n // downscale the instances so that physics will be initialized correctly\n newInstance.scaling.setAll(0.02);\n const type = props.impostorType !== undefined ? props.impostorType : PhysicsImpostor.SphereImpostor;\n newInstance.physicsImpostor = new PhysicsImpostor(newInstance, type, Object.assign({ mass: 0 }, props));\n }\n newInstance.rotationQuaternion = new Quaternion();\n newInstance.isVisible = false;\n trackedMeshes.push(newInstance);\n }\n meshes[handedness] = trackedMeshes;\n });\n return { left: meshes.left, right: meshes.right };\n }\n static _GenerateDefaultHandMeshesAsync(scene, options) {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve) => {\n var _a, _b, _c, _d, _e;\n const riggedMeshes = {};\n // check the cache, defensive\n if ((_b = (_a = WebXRHandTracking._RightHandGLB) === null || _a === void 0 ? void 0 : _a.meshes[1]) === null || _b === void 0 ? void 0 : _b.isDisposed()) {\n WebXRHandTracking._RightHandGLB = null;\n }\n if ((_d = (_c = WebXRHandTracking._LeftHandGLB) === null || _c === void 0 ? void 0 : _c.meshes[1]) === null || _d === void 0 ? void 0 : _d.isDisposed()) {\n WebXRHandTracking._LeftHandGLB = null;\n }\n const handsDefined = !!(WebXRHandTracking._RightHandGLB && WebXRHandTracking._LeftHandGLB);\n // load them in parallel\n const handGLBs = await Promise.all([\n WebXRHandTracking._RightHandGLB ||\n SceneLoader.ImportMeshAsync(\"\", WebXRHandTracking.DEFAULT_HAND_MODEL_BASE_URL, WebXRHandTracking.DEFAULT_HAND_MODEL_RIGHT_FILENAME, scene),\n WebXRHandTracking._LeftHandGLB ||\n SceneLoader.ImportMeshAsync(\"\", WebXRHandTracking.DEFAULT_HAND_MODEL_BASE_URL, WebXRHandTracking.DEFAULT_HAND_MODEL_LEFT_FILENAME, scene),\n ]);\n WebXRHandTracking._RightHandGLB = handGLBs[0];\n WebXRHandTracking._LeftHandGLB = handGLBs[1];\n const handShader = new NodeMaterial(\"handShader\", scene, { emitComments: false });\n await handShader.loadAsync(WebXRHandTracking.DEFAULT_HAND_MODEL_SHADER_URL);\n // depth prepass and alpha mode\n handShader.needDepthPrePass = true;\n handShader.transparencyMode = Material.MATERIAL_ALPHABLEND;\n handShader.alphaMode = 2;\n // build node materials\n handShader.build(false);\n // shader\n const handColors = Object.assign({ base: Color3.FromInts(116, 63, 203), fresnel: Color3.FromInts(149, 102, 229), fingerColor: Color3.FromInts(177, 130, 255), tipFresnel: Color3.FromInts(220, 200, 255) }, (_e = options === null || options === void 0 ? void 0 : options.handMeshes) === null || _e === void 0 ? void 0 : _e.customColors);\n const handNodes = {\n base: handShader.getBlockByName(\"baseColor\"),\n fresnel: handShader.getBlockByName(\"fresnelColor\"),\n fingerColor: handShader.getBlockByName(\"fingerColor\"),\n tipFresnel: handShader.getBlockByName(\"tipFresnelColor\"),\n };\n handNodes.base.value = handColors.base;\n handNodes.fresnel.value = handColors.fresnel;\n handNodes.fingerColor.value = handColors.fingerColor;\n handNodes.tipFresnel.value = handColors.tipFresnel;\n [\"left\", \"right\"].forEach((handedness) => {\n const handGLB = handedness == \"left\" ? WebXRHandTracking._LeftHandGLB : WebXRHandTracking._RightHandGLB;\n if (!handGLB) {\n // this should never happen!\n throw new Error(\"Could not load hand model\");\n }\n const handMesh = handGLB.meshes[1];\n handMesh._internalAbstractMeshDataInfo._computeBonesUsingShaders = true;\n handMesh.material = handShader.clone(`${handedness}HandShaderClone`, true);\n handMesh.isVisible = false;\n riggedMeshes[handedness] = handMesh;\n // single change for left handed systems\n if (!handsDefined && !scene.useRightHandedSystem) {\n handGLB.meshes[1].rotate(Axis.Y, Math.PI);\n }\n });\n handShader.dispose();\n resolve({ left: riggedMeshes.left, right: riggedMeshes.right });\n });\n }\n /**\n * Generates a mapping from XRHandJoint to bone name for the default hand mesh.\n * @param handedness The handedness being mapped for.\n */\n static _GenerateDefaultHandMeshRigMapping(handedness) {\n const H = handedness == \"right\" ? \"R\" : \"L\";\n return {\n [WebXRHandJoint.WRIST]: `wrist_${H}`,\n [WebXRHandJoint.THUMB_METACARPAL]: `thumb_metacarpal_${H}`,\n [WebXRHandJoint.THUMB_PHALANX_PROXIMAL]: `thumb_proxPhalanx_${H}`,\n [WebXRHandJoint.THUMB_PHALANX_DISTAL]: `thumb_distPhalanx_${H}`,\n [WebXRHandJoint.THUMB_TIP]: `thumb_tip_${H}`,\n [WebXRHandJoint.INDEX_FINGER_METACARPAL]: `index_metacarpal_${H}`,\n [WebXRHandJoint.INDEX_FINGER_PHALANX_PROXIMAL]: `index_proxPhalanx_${H}`,\n [WebXRHandJoint.INDEX_FINGER_PHALANX_INTERMEDIATE]: `index_intPhalanx_${H}`,\n [WebXRHandJoint.INDEX_FINGER_PHALANX_DISTAL]: `index_distPhalanx_${H}`,\n [WebXRHandJoint.INDEX_FINGER_TIP]: `index_tip_${H}`,\n [WebXRHandJoint.MIDDLE_FINGER_METACARPAL]: `middle_metacarpal_${H}`,\n [WebXRHandJoint.MIDDLE_FINGER_PHALANX_PROXIMAL]: `middle_proxPhalanx_${H}`,\n [WebXRHandJoint.MIDDLE_FINGER_PHALANX_INTERMEDIATE]: `middle_intPhalanx_${H}`,\n [WebXRHandJoint.MIDDLE_FINGER_PHALANX_DISTAL]: `middle_distPhalanx_${H}`,\n [WebXRHandJoint.MIDDLE_FINGER_TIP]: `middle_tip_${H}`,\n [WebXRHandJoint.RING_FINGER_METACARPAL]: `ring_metacarpal_${H}`,\n [WebXRHandJoint.RING_FINGER_PHALANX_PROXIMAL]: `ring_proxPhalanx_${H}`,\n [WebXRHandJoint.RING_FINGER_PHALANX_INTERMEDIATE]: `ring_intPhalanx_${H}`,\n [WebXRHandJoint.RING_FINGER_PHALANX_DISTAL]: `ring_distPhalanx_${H}`,\n [WebXRHandJoint.RING_FINGER_TIP]: `ring_tip_${H}`,\n [WebXRHandJoint.PINKY_FINGER_METACARPAL]: `little_metacarpal_${H}`,\n [WebXRHandJoint.PINKY_FINGER_PHALANX_PROXIMAL]: `little_proxPhalanx_${H}`,\n [WebXRHandJoint.PINKY_FINGER_PHALANX_INTERMEDIATE]: `little_intPhalanx_${H}`,\n [WebXRHandJoint.PINKY_FINGER_PHALANX_DISTAL]: `little_distPhalanx_${H}`,\n [WebXRHandJoint.PINKY_FINGER_TIP]: `little_tip_${H}`,\n };\n }\n /**\n * Check if the needed objects are defined.\n * This does not mean that the feature is enabled, but that the objects needed are well defined.\n */\n isCompatible() {\n return typeof XRHand !== \"undefined\";\n }\n /**\n * Get the hand object according to the controller id\n * @param controllerId the controller id to which we want to get the hand\n * @returns null if not found or the WebXRHand object if found\n */\n getHandByControllerId(controllerId) {\n return this._attachedHands[controllerId];\n }\n /**\n * Get a hand object according to the requested handedness\n * @param handedness the handedness to request\n * @returns null if not found or the WebXRHand object if found\n */\n getHandByHandedness(handedness) {\n if (handedness == \"none\") {\n return null;\n }\n return this._trackingHands[handedness];\n }\n /**\n * Creates a new instance of the XR hand tracking feature.\n * @param _xrSessionManager An instance of WebXRSessionManager.\n * @param options Options to use when constructing this feature.\n */\n constructor(_xrSessionManager, \n /** Options to use when constructing this feature. */\n options) {\n super(_xrSessionManager);\n this.options = options;\n this._attachedHands = {};\n this._trackingHands = { left: null, right: null };\n this._handResources = { jointMeshes: null, handMeshes: null, rigMappings: null };\n /**\n * This observable will notify registered observers when a new hand object was added and initialized\n */\n this.onHandAddedObservable = new Observable();\n /**\n * This observable will notify its observers right before the hand object is disposed\n */\n this.onHandRemovedObservable = new Observable();\n this._attachHand = (xrController) => {\n var _a, _b, _c;\n if (!xrController.inputSource.hand || xrController.inputSource.handedness == \"none\" || !this._handResources.jointMeshes) {\n return;\n }\n const handedness = xrController.inputSource.handedness;\n const webxrHand = new WebXRHand(xrController, this._handResources.jointMeshes[handedness], this._handResources.handMeshes && this._handResources.handMeshes[handedness], this._handResources.rigMappings && this._handResources.rigMappings[handedness], (_a = this.options.handMeshes) === null || _a === void 0 ? void 0 : _a.meshesUseLeftHandedCoordinates, (_b = this.options.jointMeshes) === null || _b === void 0 ? void 0 : _b.invisible, (_c = this.options.jointMeshes) === null || _c === void 0 ? void 0 : _c.scaleFactor);\n this._attachedHands[xrController.uniqueId] = webxrHand;\n this._trackingHands[handedness] = webxrHand;\n this.onHandAddedObservable.notifyObservers(webxrHand);\n };\n this._detachHand = (xrController) => {\n this._detachHandById(xrController.uniqueId);\n };\n this.xrNativeFeatureName = \"hand-tracking\";\n // Support legacy versions of the options object by copying over joint mesh properties\n const anyOptions = options;\n const anyJointMeshOptions = anyOptions.jointMeshes;\n if (anyJointMeshOptions) {\n if (typeof anyJointMeshOptions.disableDefaultHandMesh !== \"undefined\") {\n options.handMeshes = options.handMeshes || {};\n options.handMeshes.disableDefaultMeshes = anyJointMeshOptions.disableDefaultHandMesh;\n }\n if (typeof anyJointMeshOptions.handMeshes !== \"undefined\") {\n options.handMeshes = options.handMeshes || {};\n options.handMeshes.customMeshes = anyJointMeshOptions.handMeshes;\n }\n if (typeof anyJointMeshOptions.leftHandedSystemMeshes !== \"undefined\") {\n options.handMeshes = options.handMeshes || {};\n options.handMeshes.meshesUseLeftHandedCoordinates = anyJointMeshOptions.leftHandedSystemMeshes;\n }\n if (typeof anyJointMeshOptions.rigMapping !== \"undefined\") {\n options.handMeshes = options.handMeshes || {};\n const leftRigMapping = {};\n const rightRigMapping = {};\n [\n [anyJointMeshOptions.rigMapping.left, leftRigMapping],\n [anyJointMeshOptions.rigMapping.right, rightRigMapping],\n ].forEach((rigMappingTuple) => {\n const legacyRigMapping = rigMappingTuple[0];\n const rigMapping = rigMappingTuple[1];\n legacyRigMapping.forEach((modelJointName, index) => {\n rigMapping[handJointReferenceArray[index]] = modelJointName;\n });\n });\n options.handMeshes.customRigMappings = {\n left: leftRigMapping,\n right: rightRigMapping,\n };\n }\n }\n }\n /**\n * Attach this feature.\n * Will usually be called by the features manager.\n *\n * @returns true if successful.\n */\n attach() {\n var _a, _b, _c, _d;\n if (!super.attach()) {\n return false;\n }\n this._handResources = {\n jointMeshes: WebXRHandTracking._GenerateTrackedJointMeshes(this.options),\n handMeshes: ((_a = this.options.handMeshes) === null || _a === void 0 ? void 0 : _a.customMeshes) || null,\n rigMappings: ((_b = this.options.handMeshes) === null || _b === void 0 ? void 0 : _b.customRigMappings) || null,\n };\n // If they didn't supply custom meshes and are not disabling the default meshes...\n if (!((_c = this.options.handMeshes) === null || _c === void 0 ? void 0 : _c.customMeshes) && !((_d = this.options.handMeshes) === null || _d === void 0 ? void 0 : _d.disableDefaultMeshes)) {\n WebXRHandTracking._GenerateDefaultHandMeshesAsync(EngineStore.LastCreatedScene, this.options).then((defaultHandMeshes) => {\n var _a, _b;\n this._handResources.handMeshes = defaultHandMeshes;\n this._handResources.rigMappings = {\n left: WebXRHandTracking._GenerateDefaultHandMeshRigMapping(\"left\"),\n right: WebXRHandTracking._GenerateDefaultHandMeshRigMapping(\"right\"),\n };\n // Apply meshes to existing hands if already tracking.\n (_a = this._trackingHands.left) === null || _a === void 0 ? void 0 : _a.setHandMesh(this._handResources.handMeshes.left, this._handResources.rigMappings.left);\n (_b = this._trackingHands.right) === null || _b === void 0 ? void 0 : _b.setHandMesh(this._handResources.handMeshes.right, this._handResources.rigMappings.right);\n });\n }\n this.options.xrInput.controllers.forEach(this._attachHand);\n this._addNewAttachObserver(this.options.xrInput.onControllerAddedObservable, this._attachHand);\n this._addNewAttachObserver(this.options.xrInput.onControllerRemovedObservable, this._detachHand);\n return true;\n }\n _onXRFrame(_xrFrame) {\n var _a, _b;\n (_a = this._trackingHands.left) === null || _a === void 0 ? void 0 : _a.updateFromXRFrame(_xrFrame, this._xrSessionManager.referenceSpace);\n (_b = this._trackingHands.right) === null || _b === void 0 ? void 0 : _b.updateFromXRFrame(_xrFrame, this._xrSessionManager.referenceSpace);\n }\n _detachHandById(controllerId) {\n var _a;\n const hand = this.getHandByControllerId(controllerId);\n if (hand) {\n const handedness = hand.xrController.inputSource.handedness == \"left\" ? \"left\" : \"right\";\n if (((_a = this._trackingHands[handedness]) === null || _a === void 0 ? void 0 : _a.xrController.uniqueId) === controllerId) {\n this._trackingHands[handedness] = null;\n }\n this.onHandRemovedObservable.notifyObservers(hand);\n hand.dispose();\n delete this._attachedHands[controllerId];\n }\n }\n /**\n * Detach this feature.\n * Will usually be called by the features manager.\n *\n * @returns true if successful.\n */\n detach() {\n if (!super.detach()) {\n return false;\n }\n Object.keys(this._attachedHands).forEach((uniqueId) => this._detachHandById(uniqueId));\n return true;\n }\n /**\n * Dispose this feature and all of the resources attached.\n */\n dispose() {\n var _a;\n super.dispose();\n this.onHandAddedObservable.clear();\n this.onHandRemovedObservable.clear();\n if (this._handResources.handMeshes && !((_a = this.options.handMeshes) === null || _a === void 0 ? void 0 : _a.customMeshes)) {\n // this will dispose the cached meshes\n this._handResources.handMeshes.left.dispose();\n this._handResources.handMeshes.right.dispose();\n // remove the cached meshes\n WebXRHandTracking._RightHandGLB = null;\n WebXRHandTracking._LeftHandGLB = null;\n }\n if (this._handResources.jointMeshes) {\n this._handResources.jointMeshes.left.forEach((trackedMesh) => trackedMesh.dispose());\n this._handResources.jointMeshes.right.forEach((trackedMesh) => trackedMesh.dispose());\n }\n }\n}\n/**\n * The module's name\n */\nWebXRHandTracking.Name = WebXRFeatureName.HAND_TRACKING;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRHandTracking.Version = 1;\n/** The base URL for the default hand model. */\nWebXRHandTracking.DEFAULT_HAND_MODEL_BASE_URL = \"https://assets.babylonjs.com/meshes/HandMeshes/\";\n/** The filename to use for the default right hand model. */\nWebXRHandTracking.DEFAULT_HAND_MODEL_RIGHT_FILENAME = \"r_hand_rhs.glb\";\n/** The filename to use for the default left hand model. */\nWebXRHandTracking.DEFAULT_HAND_MODEL_LEFT_FILENAME = \"l_hand_rhs.glb\";\n/** The URL pointing to the default hand model NodeMaterial shader. */\nWebXRHandTracking.DEFAULT_HAND_MODEL_SHADER_URL = \"https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json\";\n// We want to use lightweight models, diameter will initially be 1 but scaled to the values returned from WebXR.\nWebXRHandTracking._ICOSPHERE_PARAMS = { radius: 0.5, flat: false, subdivisions: 2 };\nWebXRHandTracking._RightHandGLB = null;\nWebXRHandTracking._LeftHandGLB = null;\n//register the plugin\nWebXRFeaturesManager.AddWebXRFeature(WebXRHandTracking.Name, (xrSessionManager, options) => {\n return () => new WebXRHandTracking(xrSessionManager, options);\n}, WebXRHandTracking.Version, false);\n//# sourceMappingURL=WebXRHandTracking.js.map","import { WebXRFeatureName } from \"../../XR/webXRFeaturesManager.js\";\nimport { WebXRHandJoint } from \"../../XR/features/WebXRHandTracking.js\";\nimport { Quaternion, TmpVectors, Vector3 } from \"../../Maths/math.vector.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * Zones around the hand\n */\nexport var HandConstraintZone;\n(function (HandConstraintZone) {\n /**\n * Above finger tips\n */\n HandConstraintZone[HandConstraintZone[\"ABOVE_FINGER_TIPS\"] = 0] = \"ABOVE_FINGER_TIPS\";\n /**\n * Next to the thumb\n */\n HandConstraintZone[HandConstraintZone[\"RADIAL_SIDE\"] = 1] = \"RADIAL_SIDE\";\n /**\n * Next to the pinky finger\n */\n HandConstraintZone[HandConstraintZone[\"ULNAR_SIDE\"] = 2] = \"ULNAR_SIDE\";\n /**\n * Below the wrist\n */\n HandConstraintZone[HandConstraintZone[\"BELOW_WRIST\"] = 3] = \"BELOW_WRIST\";\n})(HandConstraintZone || (HandConstraintZone = {}));\n/**\n * Orientations for the hand zones and for the attached node\n */\nexport var HandConstraintOrientation;\n(function (HandConstraintOrientation) {\n /**\n * Orientation is towards the camera\n */\n HandConstraintOrientation[HandConstraintOrientation[\"LOOK_AT_CAMERA\"] = 0] = \"LOOK_AT_CAMERA\";\n /**\n * Orientation is determined by the rotation of the palm\n */\n HandConstraintOrientation[HandConstraintOrientation[\"HAND_ROTATION\"] = 1] = \"HAND_ROTATION\";\n})(HandConstraintOrientation || (HandConstraintOrientation = {}));\n/**\n * Orientations for the hand zones and for the attached node\n */\nexport var HandConstraintVisibility;\n(function (HandConstraintVisibility) {\n /**\n * Constraint is always visible\n */\n HandConstraintVisibility[HandConstraintVisibility[\"ALWAYS_VISIBLE\"] = 0] = \"ALWAYS_VISIBLE\";\n /**\n * Constraint is only visible when the palm is up\n */\n HandConstraintVisibility[HandConstraintVisibility[\"PALM_UP\"] = 1] = \"PALM_UP\";\n /**\n * Constraint is only visible when the user is looking at the constraint.\n * Uses XR Eye Tracking if enabled/available, otherwise uses camera direction\n */\n HandConstraintVisibility[HandConstraintVisibility[\"GAZE_FOCUS\"] = 2] = \"GAZE_FOCUS\";\n /**\n * Constraint is only visible when the palm is up and the user is looking at it\n */\n HandConstraintVisibility[HandConstraintVisibility[\"PALM_AND_GAZE\"] = 3] = \"PALM_AND_GAZE\";\n})(HandConstraintVisibility || (HandConstraintVisibility = {}));\n/**\n * Hand constraint behavior that makes the attached `TransformNode` follow hands in XR experiences.\n * @since 5.0.0\n */\nexport class HandConstraintBehavior {\n /**\n * Builds a hand constraint behavior\n */\n constructor() {\n this._sceneRenderObserver = null;\n this._zoneAxis = {};\n /**\n * Sets the HandConstraintVisibility level for the hand constraint\n */\n this.handConstraintVisibility = HandConstraintVisibility.PALM_AND_GAZE;\n /**\n * A number from 0.0 to 1.0, marking how restricted the direction the palm faces is for the attached node to be enabled.\n * A 1 means the palm must be directly facing the user before the node is enabled, a 0 means it is always enabled.\n * Used with HandConstraintVisibility.PALM_UP\n */\n this.palmUpStrictness = 0.95;\n /**\n * The radius in meters around the center of the hand that the user must gaze inside for the attached node to be enabled and appear.\n * Used with HandConstraintVisibility.GAZE_FOCUS\n */\n this.gazeProximityRadius = 0.15;\n /**\n * Offset distance from the hand in meters\n */\n this.targetOffset = 0.1;\n /**\n * Where to place the node regarding the center of the hand.\n */\n this.targetZone = HandConstraintZone.ULNAR_SIDE;\n /**\n * Orientation mode of the 4 zones around the hand\n */\n this.zoneOrientationMode = HandConstraintOrientation.HAND_ROTATION;\n /**\n * Orientation mode of the node attached to this behavior\n */\n this.nodeOrientationMode = HandConstraintOrientation.HAND_ROTATION;\n /**\n * Set the hand this behavior should follow. If set to \"none\", it will follow any visible hand (prioritising the left one).\n */\n this.handedness = \"none\";\n /**\n * Rate of interpolation of position and rotation of the attached node.\n * Higher values will give a slower interpolation.\n */\n this.lerpTime = 100;\n // For a right hand\n this._zoneAxis[HandConstraintZone.ABOVE_FINGER_TIPS] = new Vector3(0, 1, 0);\n this._zoneAxis[HandConstraintZone.RADIAL_SIDE] = new Vector3(-1, 0, 0);\n this._zoneAxis[HandConstraintZone.ULNAR_SIDE] = new Vector3(1, 0, 0);\n this._zoneAxis[HandConstraintZone.BELOW_WRIST] = new Vector3(0, -1, 0);\n }\n /** gets or sets behavior's name */\n get name() {\n return \"HandConstraint\";\n }\n /** Enable the behavior */\n enable() {\n this._node.setEnabled(true);\n }\n /** Disable the behavior */\n disable() {\n this._node.setEnabled(false);\n }\n _getHandPose() {\n if (!this._handTracking) {\n return null;\n }\n // Retrieve any available hand, starting by the left\n let hand;\n if (this.handedness === \"none\") {\n hand = this._handTracking.getHandByHandedness(\"left\") || this._handTracking.getHandByHandedness(\"right\");\n }\n else {\n hand = this._handTracking.getHandByHandedness(this.handedness);\n }\n if (hand) {\n const pinkyMetacarpal = hand.getJointMesh(WebXRHandJoint.PINKY_FINGER_METACARPAL);\n const middleMetacarpal = hand.getJointMesh(WebXRHandJoint.MIDDLE_FINGER_METACARPAL);\n const wrist = hand.getJointMesh(WebXRHandJoint.WRIST);\n if (wrist && middleMetacarpal && pinkyMetacarpal) {\n const handPose = { position: middleMetacarpal.absolutePosition, quaternion: new Quaternion(), id: hand.xrController.uniqueId };\n // palm forward\n const up = TmpVectors.Vector3[0];\n const forward = TmpVectors.Vector3[1];\n const left = TmpVectors.Vector3[2];\n up.copyFrom(middleMetacarpal.absolutePosition).subtractInPlace(wrist.absolutePosition).normalize();\n forward.copyFrom(pinkyMetacarpal.absolutePosition).subtractInPlace(middleMetacarpal.absolutePosition).normalize();\n // Create vectors for a rotation quaternion, where forward points out from the palm\n Vector3.CrossToRef(up, forward, forward);\n Vector3.CrossToRef(forward, up, left);\n Quaternion.FromLookDirectionLHToRef(forward, up, handPose.quaternion);\n return handPose;\n }\n }\n return null;\n }\n /**\n * Initializes the hand constraint behavior\n */\n init() { }\n /**\n * Attaches the hand constraint to a `TransformNode`\n * @param node defines the node to attach the behavior to\n */\n attach(node) {\n this._node = node;\n this._scene = node.getScene();\n if (!this._node.rotationQuaternion) {\n this._node.rotationQuaternion = Quaternion.RotationYawPitchRoll(this._node.rotation.y, this._node.rotation.x, this._node.rotation.z);\n }\n let lastTick = Date.now();\n this._sceneRenderObserver = this._scene.onBeforeRenderObservable.add(() => {\n const pose = this._getHandPose();\n this._node.reservedDataStore = this._node.reservedDataStore || {};\n this._node.reservedDataStore.nearInteraction = this._node.reservedDataStore.nearInteraction || {};\n this._node.reservedDataStore.nearInteraction.excludedControllerId = null;\n if (pose) {\n const zoneOffset = TmpVectors.Vector3[0];\n const camera = this._scene.activeCamera;\n zoneOffset.copyFrom(this._zoneAxis[this.targetZone]);\n const cameraLookAtQuaternion = TmpVectors.Quaternion[0];\n if (camera && (this.zoneOrientationMode === HandConstraintOrientation.LOOK_AT_CAMERA || this.nodeOrientationMode === HandConstraintOrientation.LOOK_AT_CAMERA)) {\n const toCamera = TmpVectors.Vector3[1];\n toCamera.copyFrom(camera.position).subtractInPlace(pose.position).normalize();\n if (this._scene.useRightHandedSystem) {\n Quaternion.FromLookDirectionRHToRef(toCamera, Vector3.UpReadOnly, cameraLookAtQuaternion);\n }\n else {\n Quaternion.FromLookDirectionLHToRef(toCamera, Vector3.UpReadOnly, cameraLookAtQuaternion);\n }\n }\n if (this.zoneOrientationMode === HandConstraintOrientation.HAND_ROTATION) {\n pose.quaternion.toRotationMatrix(TmpVectors.Matrix[0]);\n }\n else {\n cameraLookAtQuaternion.toRotationMatrix(TmpVectors.Matrix[0]);\n }\n Vector3.TransformNormalToRef(zoneOffset, TmpVectors.Matrix[0], zoneOffset);\n zoneOffset.scaleInPlace(this.targetOffset);\n const targetPosition = TmpVectors.Vector3[2];\n const targetRotation = TmpVectors.Quaternion[1];\n targetPosition.copyFrom(pose.position).addInPlace(zoneOffset);\n if (this.nodeOrientationMode === HandConstraintOrientation.HAND_ROTATION) {\n targetRotation.copyFrom(pose.quaternion);\n }\n else {\n targetRotation.copyFrom(cameraLookAtQuaternion);\n }\n const elapsed = Date.now() - lastTick;\n Vector3.SmoothToRef(this._node.position, targetPosition, elapsed, this.lerpTime, this._node.position);\n Quaternion.SmoothToRef(this._node.rotationQuaternion, targetRotation, elapsed, this.lerpTime, this._node.rotationQuaternion);\n this._node.reservedDataStore.nearInteraction.excludedControllerId = pose.id;\n }\n this._setVisibility(pose);\n lastTick = Date.now();\n });\n }\n _setVisibility(pose) {\n let palmVisible = true;\n let gazeVisible = true;\n const camera = this._scene.activeCamera;\n if (camera) {\n const cameraForward = camera.getForwardRay();\n if (this.handConstraintVisibility === HandConstraintVisibility.GAZE_FOCUS || this.handConstraintVisibility === HandConstraintVisibility.PALM_AND_GAZE) {\n gazeVisible = false;\n let gaze;\n if (this._eyeTracking) {\n gaze = this._eyeTracking.getEyeGaze();\n }\n gaze = gaze || cameraForward;\n const gazeToBehavior = TmpVectors.Vector3[0];\n if (pose) {\n pose.position.subtractToRef(gaze.origin, gazeToBehavior);\n }\n else {\n this._node.getAbsolutePosition().subtractToRef(gaze.origin, gazeToBehavior);\n }\n const projectedDistance = Vector3.Dot(gazeToBehavior, gaze.direction);\n const projectedSquared = projectedDistance * projectedDistance;\n if (projectedDistance > 0) {\n const radiusSquared = gazeToBehavior.lengthSquared() - projectedSquared;\n if (radiusSquared < this.gazeProximityRadius * this.gazeProximityRadius) {\n gazeVisible = true;\n }\n }\n }\n if (this.handConstraintVisibility === HandConstraintVisibility.PALM_UP || this.handConstraintVisibility === HandConstraintVisibility.PALM_AND_GAZE) {\n palmVisible = false;\n if (pose) {\n const palmDirection = TmpVectors.Vector3[0];\n Vector3.LeftHandedForwardReadOnly.rotateByQuaternionToRef(pose.quaternion, palmDirection);\n if (Vector3.Dot(palmDirection, cameraForward.direction) > this.palmUpStrictness * 2 - 1) {\n palmVisible = true;\n }\n }\n }\n }\n this._node.setEnabled(palmVisible && gazeVisible);\n }\n /**\n * Detaches the behavior from the `TransformNode`\n */\n detach() {\n this._scene.onBeforeRenderObservable.remove(this._sceneRenderObserver);\n }\n /**\n * Links the behavior to the XR experience in which to retrieve hand transform information.\n * @param xr xr experience\n */\n linkToXRExperience(xr) {\n const featuresManager = xr.featuresManager ? xr.featuresManager : xr;\n if (!featuresManager) {\n Tools.Error(\"XR features manager must be available or provided directly for the Hand Menu to work\");\n }\n else {\n try {\n this._eyeTracking = featuresManager.getEnabledFeature(WebXRFeatureName.EYE_TRACKING);\n }\n catch (_a) { }\n try {\n this._handTracking = featuresManager.getEnabledFeature(WebXRFeatureName.HAND_TRACKING);\n }\n catch (_b) {\n Tools.Error(\"Hand tracking must be enabled for the Hand Menu to work\");\n }\n }\n }\n}\n//# sourceMappingURL=handConstraintBehavior.js.map","import { Vector3, Quaternion, Matrix } from \"../Maths/math.vector.js\";\nimport { Space } from \"../Maths/math.axis.js\";\nimport { Logger } from \"../Misc/logger.js\";\n/**\n * Class used to apply inverse kinematics to bones\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons#boneikcontroller\n */\nexport class BoneIKController {\n /**\n * Gets or sets maximum allowed angle\n */\n get maxAngle() {\n return this._maxAngle;\n }\n set maxAngle(value) {\n this._setMaxAngle(value);\n }\n /**\n * Creates a new BoneIKController\n * @param mesh defines the TransformNode to control\n * @param bone defines the bone to control. The bone needs to have a parent bone. It also needs to have a length greater than 0 or a children we can use to infer its length.\n * @param options defines options to set up the controller\n * @param options.targetMesh\n * @param options.poleTargetMesh\n * @param options.poleTargetBone\n * @param options.poleTargetLocalOffset\n * @param options.poleAngle\n * @param options.bendAxis\n * @param options.maxAngle\n * @param options.slerpAmount\n */\n constructor(mesh, bone, options) {\n /**\n * Gets or sets the target position\n */\n this.targetPosition = Vector3.Zero();\n /**\n * Gets or sets the pole target position\n */\n this.poleTargetPosition = Vector3.Zero();\n /**\n * Gets or sets the pole target local offset\n */\n this.poleTargetLocalOffset = Vector3.Zero();\n /**\n * Gets or sets the pole angle\n */\n this.poleAngle = 0;\n /**\n * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp)\n */\n this.slerpAmount = 1;\n this._bone1Quat = Quaternion.Identity();\n this._bone1Mat = Matrix.Identity();\n this._bone2Ang = Math.PI;\n this._maxAngle = Math.PI;\n this._rightHandedSystem = false;\n this._bendAxis = Vector3.Right();\n this._slerping = false;\n this._adjustRoll = 0;\n this._notEnoughInformation = false;\n this._bone2 = bone;\n const bone1 = bone.getParent();\n if (!bone1) {\n this._notEnoughInformation = true;\n Logger.Error(\"BoneIKController: bone must have a parent for IK to work.\");\n return;\n }\n this._bone1 = bone1;\n if (this._bone2.children.length === 0 && !this._bone2.length) {\n this._notEnoughInformation = true;\n Logger.Error(\"BoneIKController: bone must not be a leaf or it should have a length for IK to work.\");\n return;\n }\n this.mesh = mesh;\n const bonePos = bone.getPosition();\n if (bone.getAbsoluteMatrix().determinant() > 0) {\n this._rightHandedSystem = true;\n this._bendAxis.x = 0;\n this._bendAxis.y = 0;\n this._bendAxis.z = -1;\n if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {\n this._adjustRoll = Math.PI * 0.5;\n this._bendAxis.z = 1;\n }\n }\n if (this._bone1.length && this._bone2.length) {\n const boneScale1 = this._bone1.getScale();\n const boneScale2 = this._bone2.getScale();\n this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;\n this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;\n }\n else if (this._bone2.children[0]) {\n mesh.computeWorldMatrix(true);\n const pos1 = this._bone2.children[0].getAbsolutePosition(mesh);\n const pos2 = this._bone2.getAbsolutePosition(mesh);\n const pos3 = this._bone1.getAbsolutePosition(mesh);\n this._bone2Length = Vector3.Distance(pos1, pos2);\n this._bone1Length = Vector3.Distance(pos2, pos3);\n }\n else {\n mesh.computeWorldMatrix(true);\n const boneScale2 = this._bone2.getScale();\n this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;\n const pos2 = this._bone2.getAbsolutePosition(mesh);\n const pos3 = this._bone1.getAbsolutePosition(mesh);\n this._bone1Length = Vector3.Distance(pos2, pos3);\n }\n this._bone1.getRotationMatrixToRef(Space.WORLD, mesh, this._bone1Mat);\n this.maxAngle = Math.PI;\n if (options) {\n if (options.targetMesh) {\n this.targetMesh = options.targetMesh;\n this.targetMesh.computeWorldMatrix(true);\n }\n if (options.poleTargetMesh) {\n this.poleTargetMesh = options.poleTargetMesh;\n this.poleTargetMesh.computeWorldMatrix(true);\n }\n else if (options.poleTargetBone) {\n this.poleTargetBone = options.poleTargetBone;\n }\n else if (this._bone1.getParent()) {\n this.poleTargetBone = this._bone1.getParent();\n }\n if (options.poleTargetLocalOffset) {\n this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);\n }\n if (options.poleAngle) {\n this.poleAngle = options.poleAngle;\n }\n if (options.bendAxis) {\n this._bendAxis.copyFrom(options.bendAxis);\n }\n if (options.maxAngle) {\n this.maxAngle = options.maxAngle;\n }\n if (options.slerpAmount) {\n this.slerpAmount = options.slerpAmount;\n }\n }\n }\n _setMaxAngle(ang) {\n if (ang < 0) {\n ang = 0;\n }\n if (ang > Math.PI || ang == undefined) {\n ang = Math.PI;\n }\n this._maxAngle = ang;\n const a = this._bone1Length;\n const b = this._bone2Length;\n this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));\n }\n /**\n * Force the controller to update the bones\n */\n update() {\n if (this._notEnoughInformation) {\n return;\n }\n const target = this.targetPosition;\n const poleTarget = this.poleTargetPosition;\n const mat1 = BoneIKController._TmpMats[0];\n const mat2 = BoneIKController._TmpMats[1];\n if (this.targetMesh) {\n target.copyFrom(this.targetMesh.getAbsolutePosition());\n }\n if (this.poleTargetBone) {\n this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);\n }\n else if (this.poleTargetMesh) {\n Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);\n }\n const bonePos = BoneIKController._TmpVecs[0];\n const zaxis = BoneIKController._TmpVecs[1];\n const xaxis = BoneIKController._TmpVecs[2];\n const yaxis = BoneIKController._TmpVecs[3];\n const upAxis = BoneIKController._TmpVecs[4];\n const tmpQuat = BoneIKController._TmpQuat;\n this._bone1.getAbsolutePositionToRef(this.mesh, bonePos);\n poleTarget.subtractToRef(bonePos, upAxis);\n if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {\n upAxis.y = 1;\n }\n else {\n upAxis.normalize();\n }\n target.subtractToRef(bonePos, yaxis);\n yaxis.normalize();\n Vector3.CrossToRef(yaxis, upAxis, zaxis);\n zaxis.normalize();\n Vector3.CrossToRef(yaxis, zaxis, xaxis);\n xaxis.normalize();\n Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);\n const a = this._bone1Length;\n const b = this._bone2Length;\n let c = Vector3.Distance(bonePos, target);\n if (this._maxReach > 0) {\n c = Math.min(this._maxReach, c);\n }\n let acosa = (b * b + c * c - a * a) / (2 * b * c);\n let acosb = (c * c + a * a - b * b) / (2 * c * a);\n if (acosa > 1) {\n acosa = 1;\n }\n if (acosb > 1) {\n acosb = 1;\n }\n if (acosa < -1) {\n acosa = -1;\n }\n if (acosb < -1) {\n acosb = -1;\n }\n const angA = Math.acos(acosa);\n const angB = Math.acos(acosb);\n let angC = -angA - angB;\n if (this._rightHandedSystem) {\n Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);\n mat2.multiplyToRef(mat1, mat1);\n Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);\n mat2.multiplyToRef(mat1, mat1);\n }\n else {\n const _tmpVec = BoneIKController._TmpVecs[5];\n _tmpVec.copyFrom(this._bendAxis);\n _tmpVec.x *= -1;\n Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);\n mat2.multiplyToRef(mat1, mat1);\n }\n if (this.poleAngle) {\n Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);\n mat1.multiplyToRef(mat2, mat1);\n }\n if (this._bone1) {\n if (this.slerpAmount < 1) {\n if (!this._slerping) {\n Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);\n }\n Quaternion.FromRotationMatrixToRef(mat1, tmpQuat);\n Quaternion.SlerpToRef(this._bone1Quat, tmpQuat, this.slerpAmount, this._bone1Quat);\n angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;\n this._bone1.setRotationQuaternion(this._bone1Quat, Space.WORLD, this.mesh);\n this._slerping = true;\n }\n else {\n this._bone1.setRotationMatrix(mat1, Space.WORLD, this.mesh);\n this._bone1Mat.copyFrom(mat1);\n this._slerping = false;\n }\n this._updateLinkedTransformRotation(this._bone1);\n }\n this._bone2.setAxisAngle(this._bendAxis, angC, Space.LOCAL);\n this._updateLinkedTransformRotation(this._bone2);\n this._bone2Ang = angC;\n }\n _updateLinkedTransformRotation(bone) {\n if (bone._linkedTransformNode) {\n if (!bone._linkedTransformNode.rotationQuaternion) {\n bone._linkedTransformNode.rotationQuaternion = new Quaternion();\n }\n bone.getRotationQuaternionToRef(Space.LOCAL, null, bone._linkedTransformNode.rotationQuaternion);\n }\n }\n}\nBoneIKController._TmpVecs = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];\nBoneIKController._TmpQuat = Quaternion.Identity();\nBoneIKController._TmpMats = [Matrix.Identity(), Matrix.Identity()];\n//# sourceMappingURL=boneIKController.js.map","import { ArrayTools } from \"../Misc/arrayTools.js\";\nimport { Vector3, Quaternion, Matrix } from \"../Maths/math.vector.js\";\nimport { Space, Axis } from \"../Maths/math.axis.js\";\n/**\n * Class used to make a bone look toward a point in space\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons#bonelookcontroller\n */\nexport class BoneLookController {\n /**\n * Gets or sets the minimum yaw angle that the bone can look to\n */\n get minYaw() {\n return this._minYaw;\n }\n set minYaw(value) {\n this._minYaw = value;\n this._minYawSin = Math.sin(value);\n this._minYawCos = Math.cos(value);\n if (this._maxYaw != null) {\n this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * 0.5 + this._minYaw;\n this._yawRange = this._maxYaw - this._minYaw;\n }\n }\n /**\n * Gets or sets the maximum yaw angle that the bone can look to\n */\n get maxYaw() {\n return this._maxYaw;\n }\n set maxYaw(value) {\n this._maxYaw = value;\n this._maxYawSin = Math.sin(value);\n this._maxYawCos = Math.cos(value);\n if (this._minYaw != null) {\n this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * 0.5 + this._minYaw;\n this._yawRange = this._maxYaw - this._minYaw;\n }\n }\n /**\n * Gets or sets the minimum pitch angle that the bone can look to\n */\n get minPitch() {\n return this._minPitch;\n }\n set minPitch(value) {\n this._minPitch = value;\n this._minPitchTan = Math.tan(value);\n }\n /**\n * Gets or sets the maximum pitch angle that the bone can look to\n */\n get maxPitch() {\n return this._maxPitch;\n }\n set maxPitch(value) {\n this._maxPitch = value;\n this._maxPitchTan = Math.tan(value);\n }\n /**\n * Create a BoneLookController\n * @param mesh the TransformNode that the bone belongs to\n * @param bone the bone that will be looking to the target\n * @param target the target Vector3 to look at\n * @param options optional settings:\n * * maxYaw: the maximum angle the bone will yaw to\n * * minYaw: the minimum angle the bone will yaw to\n * * maxPitch: the maximum angle the bone will pitch to\n * * minPitch: the minimum angle the bone will yaw to\n * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.\n * * upAxis: the up axis of the coordinate system\n * * upAxisSpace: the space that the up axis is in - Space.BONE, Space.LOCAL (default), or Space.WORLD.\n * * yawAxis: set yawAxis if the bone does not yaw on the y axis\n * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis\n * * adjustYaw: used to make an adjustment to the yaw of the bone\n * * adjustPitch: used to make an adjustment to the pitch of the bone\n * * adjustRoll: used to make an adjustment to the roll of the bone\n * @param options.maxYaw\n * @param options.minYaw\n * @param options.maxPitch\n * @param options.minPitch\n * @param options.slerpAmount\n * @param options.upAxis\n * @param options.upAxisSpace\n * @param options.yawAxis\n * @param options.pitchAxis\n * @param options.adjustYaw\n * @param options.adjustPitch\n * @param options.adjustRoll\n **/\n constructor(mesh, bone, target, options) {\n /**\n * The up axis of the coordinate system that is used when the bone is rotated\n */\n this.upAxis = Vector3.Up();\n /**\n * The space that the up axis is in - Space.BONE, Space.LOCAL (default), or Space.WORLD\n */\n this.upAxisSpace = Space.LOCAL;\n /**\n * Used to make an adjustment to the yaw of the bone\n */\n this.adjustYaw = 0;\n /**\n * Used to make an adjustment to the pitch of the bone\n */\n this.adjustPitch = 0;\n /**\n * Used to make an adjustment to the roll of the bone\n */\n this.adjustRoll = 0;\n /**\n * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp)\n */\n this.slerpAmount = 1;\n this._boneQuat = Quaternion.Identity();\n this._slerping = false;\n this._firstFrameSkipped = false;\n this._fowardAxis = Vector3.Forward();\n /**\n * Use the absolute value for yaw when checking the min/max constraints\n */\n this.useAbsoluteValueForYaw = false;\n this.mesh = mesh;\n this.bone = bone;\n this.target = target;\n if (options) {\n if (options.adjustYaw) {\n this.adjustYaw = options.adjustYaw;\n }\n if (options.adjustPitch) {\n this.adjustPitch = options.adjustPitch;\n }\n if (options.adjustRoll) {\n this.adjustRoll = options.adjustRoll;\n }\n if (options.maxYaw != null) {\n this.maxYaw = options.maxYaw;\n }\n else {\n this.maxYaw = Math.PI;\n }\n if (options.minYaw != null) {\n this.minYaw = options.minYaw;\n }\n else {\n this.minYaw = -Math.PI;\n }\n if (options.maxPitch != null) {\n this.maxPitch = options.maxPitch;\n }\n else {\n this.maxPitch = Math.PI;\n }\n if (options.minPitch != null) {\n this.minPitch = options.minPitch;\n }\n else {\n this.minPitch = -Math.PI;\n }\n if (options.slerpAmount != null) {\n this.slerpAmount = options.slerpAmount;\n }\n if (options.upAxis != null) {\n this.upAxis = options.upAxis;\n }\n if (options.upAxisSpace != null) {\n this.upAxisSpace = options.upAxisSpace;\n }\n if (options.yawAxis != null || options.pitchAxis != null) {\n let newYawAxis = Axis.Y;\n let newPitchAxis = Axis.X;\n if (options.yawAxis != null) {\n newYawAxis = options.yawAxis.clone();\n newYawAxis.normalize();\n }\n if (options.pitchAxis != null) {\n newPitchAxis = options.pitchAxis.clone();\n newPitchAxis.normalize();\n }\n const newRollAxis = Vector3.Cross(newPitchAxis, newYawAxis);\n this._transformYawPitch = Matrix.Identity();\n Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);\n this._transformYawPitchInv = this._transformYawPitch.clone();\n this._transformYawPitch.invert();\n }\n if (options.useAbsoluteValueForYaw !== undefined) {\n this.useAbsoluteValueForYaw = options.useAbsoluteValueForYaw;\n }\n }\n if (!bone.getParent() && this.upAxisSpace == Space.BONE) {\n this.upAxisSpace = Space.LOCAL;\n }\n }\n /**\n * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())\n */\n update() {\n //skip the first frame when slerping so that the TransformNode rotation is correct\n if (this.slerpAmount < 1 && !this._firstFrameSkipped) {\n this._firstFrameSkipped = true;\n return;\n }\n const bone = this.bone;\n const bonePos = BoneLookController._TmpVecs[0];\n bone.getAbsolutePositionToRef(this.mesh, bonePos);\n let target = this.target;\n const _tmpMat1 = BoneLookController._TmpMats[0];\n const _tmpMat2 = BoneLookController._TmpMats[1];\n const mesh = this.mesh;\n const parentBone = bone.getParent();\n const upAxis = BoneLookController._TmpVecs[1];\n upAxis.copyFrom(this.upAxis);\n if (this.upAxisSpace == Space.BONE && parentBone) {\n if (this._transformYawPitch) {\n Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);\n }\n parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);\n }\n else if (this.upAxisSpace == Space.LOCAL) {\n mesh.getDirectionToRef(upAxis, upAxis);\n if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {\n upAxis.normalize();\n }\n }\n let checkYaw = false;\n let checkPitch = false;\n if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {\n checkYaw = true;\n }\n if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {\n checkPitch = true;\n }\n if (checkYaw || checkPitch) {\n const spaceMat = BoneLookController._TmpMats[2];\n const spaceMatInv = BoneLookController._TmpMats[3];\n if (this.upAxisSpace == Space.BONE && upAxis.y == 1 && parentBone) {\n parentBone.getRotationMatrixToRef(Space.WORLD, this.mesh, spaceMat);\n }\n else if (this.upAxisSpace == Space.LOCAL && upAxis.y == 1 && !parentBone) {\n spaceMat.copyFrom(mesh.getWorldMatrix());\n }\n else {\n let forwardAxis = BoneLookController._TmpVecs[2];\n forwardAxis.copyFrom(this._fowardAxis);\n if (this._transformYawPitch) {\n Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);\n }\n if (parentBone) {\n parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);\n }\n else {\n mesh.getDirectionToRef(forwardAxis, forwardAxis);\n }\n const rightAxis = Vector3.Cross(upAxis, forwardAxis);\n rightAxis.normalize();\n forwardAxis = Vector3.Cross(rightAxis, upAxis);\n Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);\n }\n spaceMat.invertToRef(spaceMatInv);\n let xzlen = null;\n if (checkPitch) {\n const localTarget = BoneLookController._TmpVecs[3];\n target.subtractToRef(bonePos, localTarget);\n Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);\n xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);\n const pitch = Math.atan2(localTarget.y, xzlen);\n let newPitch = pitch;\n if (pitch > this._maxPitch) {\n localTarget.y = this._maxPitchTan * xzlen;\n newPitch = this._maxPitch;\n }\n else if (pitch < this._minPitch) {\n localTarget.y = this._minPitchTan * xzlen;\n newPitch = this._minPitch;\n }\n if (pitch != newPitch) {\n Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);\n localTarget.addInPlace(bonePos);\n target = localTarget;\n }\n }\n if (checkYaw) {\n const localTarget = BoneLookController._TmpVecs[4];\n target.subtractToRef(bonePos, localTarget);\n Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);\n const yaw = Math.atan2(localTarget.x, localTarget.z);\n const yawCheck = this.useAbsoluteValueForYaw ? Math.abs(yaw) : yaw;\n let newYaw = yaw;\n if (yawCheck > this._maxYaw || yawCheck < this._minYaw) {\n if (xzlen == null) {\n xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);\n }\n if (this._yawRange > Math.PI) {\n if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {\n localTarget.z = this._maxYawCos * xzlen;\n localTarget.x = this._maxYawSin * xzlen;\n newYaw = this._maxYaw;\n }\n else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {\n localTarget.z = this._minYawCos * xzlen;\n localTarget.x = this._minYawSin * xzlen;\n newYaw = this._minYaw;\n }\n }\n else {\n if (yawCheck > this._maxYaw) {\n localTarget.z = this._maxYawCos * xzlen;\n localTarget.x = this._maxYawSin * xzlen;\n if (yaw < 0 && this.useAbsoluteValueForYaw) {\n localTarget.x *= -1;\n }\n newYaw = this._maxYaw;\n }\n else if (yawCheck < this._minYaw) {\n localTarget.z = this._minYawCos * xzlen;\n localTarget.x = this._minYawSin * xzlen;\n if (yaw < 0 && this.useAbsoluteValueForYaw) {\n localTarget.x *= -1;\n }\n newYaw = this._minYaw;\n }\n }\n }\n if (this._slerping && this._yawRange > Math.PI) {\n //are we going to be crossing into the min/max region?\n const boneFwd = BoneLookController._TmpVecs[8];\n boneFwd.copyFrom(Axis.Z);\n if (this._transformYawPitch) {\n Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);\n }\n const boneRotMat = BoneLookController._TmpMats[4];\n this._boneQuat.toRotationMatrix(boneRotMat);\n this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);\n Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);\n Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);\n const boneYaw = Math.atan2(boneFwd.x, boneFwd.z);\n const angBtwTar = this._getAngleBetween(boneYaw, yaw);\n const angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);\n if (angBtwTar > angBtwMidYaw) {\n if (xzlen == null) {\n xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);\n }\n const angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);\n const angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);\n if (angBtwMin < angBtwMax) {\n newYaw = boneYaw + Math.PI * 0.75;\n localTarget.z = Math.cos(newYaw) * xzlen;\n localTarget.x = Math.sin(newYaw) * xzlen;\n }\n else {\n newYaw = boneYaw - Math.PI * 0.75;\n localTarget.z = Math.cos(newYaw) * xzlen;\n localTarget.x = Math.sin(newYaw) * xzlen;\n }\n }\n }\n if (yaw != newYaw) {\n Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);\n localTarget.addInPlace(bonePos);\n target = localTarget;\n }\n }\n }\n const zaxis = BoneLookController._TmpVecs[5];\n const xaxis = BoneLookController._TmpVecs[6];\n const yaxis = BoneLookController._TmpVecs[7];\n const tmpQuat = BoneLookController._TmpQuat;\n target.subtractToRef(bonePos, zaxis);\n zaxis.normalize();\n Vector3.CrossToRef(upAxis, zaxis, xaxis);\n xaxis.normalize();\n Vector3.CrossToRef(zaxis, xaxis, yaxis);\n yaxis.normalize();\n Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);\n if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {\n return;\n }\n if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {\n return;\n }\n if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {\n return;\n }\n if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {\n Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);\n _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);\n }\n if (this.slerpAmount < 1) {\n if (!this._slerping) {\n this.bone.getRotationQuaternionToRef(Space.WORLD, this.mesh, this._boneQuat);\n }\n if (this._transformYawPitch) {\n this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);\n }\n Quaternion.FromRotationMatrixToRef(_tmpMat1, tmpQuat);\n Quaternion.SlerpToRef(this._boneQuat, tmpQuat, this.slerpAmount, this._boneQuat);\n this.bone.setRotationQuaternion(this._boneQuat, Space.WORLD, this.mesh);\n this._slerping = true;\n }\n else {\n if (this._transformYawPitch) {\n this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);\n }\n this.bone.setRotationMatrix(_tmpMat1, Space.WORLD, this.mesh);\n this._slerping = false;\n }\n this._updateLinkedTransformRotation();\n }\n _getAngleDiff(ang1, ang2) {\n let angDiff = ang2 - ang1;\n angDiff %= Math.PI * 2;\n if (angDiff > Math.PI) {\n angDiff -= Math.PI * 2;\n }\n else if (angDiff < -Math.PI) {\n angDiff += Math.PI * 2;\n }\n return angDiff;\n }\n _getAngleBetween(ang1, ang2) {\n ang1 %= 2 * Math.PI;\n ang1 = ang1 < 0 ? ang1 + 2 * Math.PI : ang1;\n ang2 %= 2 * Math.PI;\n ang2 = ang2 < 0 ? ang2 + 2 * Math.PI : ang2;\n let ab = 0;\n if (ang1 < ang2) {\n ab = ang2 - ang1;\n }\n else {\n ab = ang1 - ang2;\n }\n if (ab > Math.PI) {\n ab = Math.PI * 2 - ab;\n }\n return ab;\n }\n _isAngleBetween(ang, ang1, ang2) {\n ang %= 2 * Math.PI;\n ang = ang < 0 ? ang + 2 * Math.PI : ang;\n ang1 %= 2 * Math.PI;\n ang1 = ang1 < 0 ? ang1 + 2 * Math.PI : ang1;\n ang2 %= 2 * Math.PI;\n ang2 = ang2 < 0 ? ang2 + 2 * Math.PI : ang2;\n if (ang1 < ang2) {\n if (ang > ang1 && ang < ang2) {\n return true;\n }\n }\n else {\n if (ang > ang2 && ang < ang1) {\n return true;\n }\n }\n return false;\n }\n _updateLinkedTransformRotation() {\n const bone = this.bone;\n if (bone._linkedTransformNode) {\n if (!bone._linkedTransformNode.rotationQuaternion) {\n bone._linkedTransformNode.rotationQuaternion = new Quaternion();\n }\n bone.getRotationQuaternionToRef(Space.LOCAL, null, bone._linkedTransformNode.rotationQuaternion);\n }\n }\n}\nBoneLookController._TmpVecs = ArrayTools.BuildArray(10, Vector3.Zero);\nBoneLookController._TmpQuat = Quaternion.Identity();\nBoneLookController._TmpMats = ArrayTools.BuildArray(5, Matrix.Identity);\n//# sourceMappingURL=boneLookController.js.map","import { Bone } from \"./bone.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Vector3, Matrix, TmpVectors } from \"../Maths/math.vector.js\";\nimport { RawTexture } from \"../Materials/Textures/rawTexture.js\";\nimport { Animation } from \"../Animations/animation.js\";\nimport { AnimationRange } from \"../Animations/animationRange.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n\nimport { Logger } from \"../Misc/logger.js\";\nimport { DeepCopier } from \"../Misc/deepCopier.js\";\n/**\n * Class used to handle skinning animations\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons\n */\nexport class Skeleton {\n /**\n * Gets or sets a boolean indicating that bone matrices should be stored as a texture instead of using shader uniforms (default is true).\n * Please note that this option is not available if the hardware does not support it\n */\n get useTextureToStoreBoneMatrices() {\n return this._useTextureToStoreBoneMatrices;\n }\n set useTextureToStoreBoneMatrices(value) {\n this._useTextureToStoreBoneMatrices = value;\n this._markAsDirty();\n }\n /**\n * Gets or sets the animation properties override\n */\n get animationPropertiesOverride() {\n if (!this._animationPropertiesOverride) {\n return this._scene.animationPropertiesOverride;\n }\n return this._animationPropertiesOverride;\n }\n set animationPropertiesOverride(value) {\n this._animationPropertiesOverride = value;\n }\n /**\n * Gets a boolean indicating that the skeleton effectively stores matrices into a texture\n */\n get isUsingTextureForMatrices() {\n return this.useTextureToStoreBoneMatrices && this._canUseTextureForBones;\n }\n /**\n * Gets the unique ID of this skeleton\n */\n get uniqueId() {\n return this._uniqueId;\n }\n /**\n * Creates a new skeleton\n * @param name defines the skeleton name\n * @param id defines the skeleton Id\n * @param scene defines the hosting scene\n */\n constructor(\n /** defines the skeleton name */\n name, \n /** defines the skeleton Id */\n id, scene) {\n this.name = name;\n this.id = id;\n /**\n * Defines the list of child bones\n */\n this.bones = new Array();\n /**\n * Defines a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)\n */\n this.needInitialSkinMatrix = false;\n this._isDirty = true;\n this._meshesWithPoseMatrix = new Array();\n this._identity = Matrix.Identity();\n this._ranges = {};\n this._absoluteTransformIsDirty = true;\n this._canUseTextureForBones = false;\n this._uniqueId = 0;\n /** @internal */\n this._numBonesWithLinkedTransformNode = 0;\n /** @internal */\n this._hasWaitingData = null;\n /** @internal */\n this._parentContainer = null;\n /**\n * Specifies if the skeleton should be serialized\n */\n this.doNotSerialize = false;\n this._useTextureToStoreBoneMatrices = true;\n this._animationPropertiesOverride = null;\n // Events\n /**\n * An observable triggered before computing the skeleton's matrices\n */\n this.onBeforeComputeObservable = new Observable();\n this.bones = [];\n this._scene = scene || EngineStore.LastCreatedScene;\n this._uniqueId = this._scene.getUniqueId();\n this._scene.addSkeleton(this);\n //make sure it will recalculate the matrix next time prepare is called.\n this._isDirty = true;\n const engineCaps = this._scene.getEngine().getCaps();\n this._canUseTextureForBones = engineCaps.textureFloat && engineCaps.maxVertexTextureImageUnits > 0;\n }\n /**\n * Gets the current object class name.\n * @returns the class name\n */\n getClassName() {\n return \"Skeleton\";\n }\n /**\n * Returns an array containing the root bones\n * @returns an array containing the root bones\n */\n getChildren() {\n return this.bones.filter((b) => !b.getParent());\n }\n // Members\n /**\n * Gets the list of transform matrices to send to shaders (one matrix per bone)\n * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)\n * @returns a Float32Array containing matrices data\n */\n getTransformMatrices(mesh) {\n if (this.needInitialSkinMatrix) {\n if (!mesh._bonesTransformMatrices) {\n this.prepare();\n }\n return mesh._bonesTransformMatrices;\n }\n if (!this._transformMatrices || this._isDirty) {\n this.prepare();\n }\n return this._transformMatrices;\n }\n /**\n * Gets the list of transform matrices to send to shaders inside a texture (one matrix per bone)\n * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)\n * @returns a raw texture containing the data\n */\n getTransformMatrixTexture(mesh) {\n if (this.needInitialSkinMatrix && mesh._transformMatrixTexture) {\n return mesh._transformMatrixTexture;\n }\n return this._transformMatrixTexture;\n }\n /**\n * Gets the current hosting scene\n * @returns a scene object\n */\n getScene() {\n return this._scene;\n }\n // Methods\n /**\n * Gets a string representing the current skeleton data\n * @param fullDetails defines a boolean indicating if we want a verbose version\n * @returns a string representing the current skeleton data\n */\n toString(fullDetails) {\n let ret = `Name: ${this.name}, nBones: ${this.bones.length}`;\n ret += `, nAnimationRanges: ${this._ranges ? Object.keys(this._ranges).length : \"none\"}`;\n if (fullDetails) {\n ret += \", Ranges: {\";\n let first = true;\n for (const name in this._ranges) {\n if (first) {\n ret += \", \";\n first = false;\n }\n ret += name;\n }\n ret += \"}\";\n }\n return ret;\n }\n /**\n * Get bone's index searching by name\n * @param name defines bone's name to search for\n * @returns the indice of the bone. Returns -1 if not found\n */\n getBoneIndexByName(name) {\n for (let boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {\n if (this.bones[boneIndex].name === name) {\n return boneIndex;\n }\n }\n return -1;\n }\n /**\n * Create a new animation range\n * @param name defines the name of the range\n * @param from defines the start key\n * @param to defines the end key\n */\n createAnimationRange(name, from, to) {\n // check name not already in use\n if (!this._ranges[name]) {\n this._ranges[name] = new AnimationRange(name, from, to);\n for (let i = 0, nBones = this.bones.length; i < nBones; i++) {\n if (this.bones[i].animations[0]) {\n this.bones[i].animations[0].createRange(name, from, to);\n }\n }\n }\n }\n /**\n * Delete a specific animation range\n * @param name defines the name of the range\n * @param deleteFrames defines if frames must be removed as well\n */\n deleteAnimationRange(name, deleteFrames = true) {\n for (let i = 0, nBones = this.bones.length; i < nBones; i++) {\n if (this.bones[i].animations[0]) {\n this.bones[i].animations[0].deleteRange(name, deleteFrames);\n }\n }\n this._ranges[name] = null; // said much faster than 'delete this._range[name]'\n }\n /**\n * Gets a specific animation range\n * @param name defines the name of the range to look for\n * @returns the requested animation range or null if not found\n */\n getAnimationRange(name) {\n return this._ranges[name] || null;\n }\n /**\n * Gets the list of all animation ranges defined on this skeleton\n * @returns an array\n */\n getAnimationRanges() {\n const animationRanges = [];\n let name;\n for (name in this._ranges) {\n animationRanges.push(this._ranges[name]);\n }\n return animationRanges;\n }\n /**\n * Copy animation range from a source skeleton.\n * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences\n * @param source defines the source skeleton\n * @param name defines the name of the range to copy\n * @param rescaleAsRequired defines if rescaling must be applied if required\n * @returns true if operation was successful\n */\n copyAnimationRange(source, name, rescaleAsRequired = false) {\n if (this._ranges[name] || !source.getAnimationRange(name)) {\n return false;\n }\n let ret = true;\n const frameOffset = this._getHighestAnimationFrame() + 1;\n // make a dictionary of source skeleton's bones, so exact same order or doubly nested loop is not required\n const boneDict = {};\n const sourceBones = source.bones;\n let nBones;\n let i;\n for (i = 0, nBones = sourceBones.length; i < nBones; i++) {\n boneDict[sourceBones[i].name] = sourceBones[i];\n }\n if (this.bones.length !== sourceBones.length) {\n Logger.Warn(`copyAnimationRange: this rig has ${this.bones.length} bones, while source as ${sourceBones.length}`);\n ret = false;\n }\n const skelDimensionsRatio = rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;\n for (i = 0, nBones = this.bones.length; i < nBones; i++) {\n const boneName = this.bones[i].name;\n const sourceBone = boneDict[boneName];\n if (sourceBone) {\n ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);\n }\n else {\n Logger.Warn(\"copyAnimationRange: not same rig, missing source bone \" + boneName);\n ret = false;\n }\n }\n // do not call createAnimationRange(), since it also is done to bones, which was already done\n const range = source.getAnimationRange(name);\n if (range) {\n this._ranges[name] = new AnimationRange(name, range.from + frameOffset, range.to + frameOffset);\n }\n return ret;\n }\n /**\n * Forces the skeleton to go to rest pose\n */\n returnToRest() {\n for (const bone of this.bones) {\n if (bone._index !== -1) {\n bone.returnToRest();\n }\n }\n }\n _getHighestAnimationFrame() {\n let ret = 0;\n for (let i = 0, nBones = this.bones.length; i < nBones; i++) {\n if (this.bones[i].animations[0]) {\n const highest = this.bones[i].animations[0].getHighestFrame();\n if (ret < highest) {\n ret = highest;\n }\n }\n }\n return ret;\n }\n /**\n * Begin a specific animation range\n * @param name defines the name of the range to start\n * @param loop defines if looping must be turned on (false by default)\n * @param speedRatio defines the speed ratio to apply (1 by default)\n * @param onAnimationEnd defines a callback which will be called when animation will end\n * @returns a new animatable\n */\n beginAnimation(name, loop, speedRatio, onAnimationEnd) {\n const range = this.getAnimationRange(name);\n if (!range) {\n return null;\n }\n return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);\n }\n /**\n * Convert the keyframes for a range of animation on a skeleton to be relative to a given reference frame.\n * @param skeleton defines the Skeleton containing the animation range to convert\n * @param referenceFrame defines the frame that keyframes in the range will be relative to\n * @param range defines the name of the AnimationRange belonging to the Skeleton to convert\n * @returns the original skeleton\n */\n static MakeAnimationAdditive(skeleton, referenceFrame = 0, range) {\n const rangeValue = skeleton.getAnimationRange(range);\n // We can't make a range additive if it doesn't exist\n if (!rangeValue) {\n return null;\n }\n // Find any current scene-level animatable belonging to the target that matches the range\n const sceneAnimatables = skeleton._scene.getAllAnimatablesByTarget(skeleton);\n let rangeAnimatable = null;\n for (let index = 0; index < sceneAnimatables.length; index++) {\n const sceneAnimatable = sceneAnimatables[index];\n if (sceneAnimatable.fromFrame === (rangeValue === null || rangeValue === void 0 ? void 0 : rangeValue.from) && sceneAnimatable.toFrame === (rangeValue === null || rangeValue === void 0 ? void 0 : rangeValue.to)) {\n rangeAnimatable = sceneAnimatable;\n break;\n }\n }\n // Convert the animations belonging to the skeleton to additive keyframes\n const animatables = skeleton.getAnimatables();\n for (let index = 0; index < animatables.length; index++) {\n const animatable = animatables[index];\n const animations = animatable.animations;\n if (!animations) {\n continue;\n }\n for (let animIndex = 0; animIndex < animations.length; animIndex++) {\n Animation.MakeAnimationAdditive(animations[animIndex], referenceFrame, range);\n }\n }\n // Mark the scene-level animatable as additive\n if (rangeAnimatable) {\n rangeAnimatable.isAdditive = true;\n }\n return skeleton;\n }\n /** @internal */\n _markAsDirty() {\n this._isDirty = true;\n this._absoluteTransformIsDirty = true;\n }\n /**\n * @internal\n */\n _registerMeshWithPoseMatrix(mesh) {\n this._meshesWithPoseMatrix.push(mesh);\n }\n /**\n * @internal\n */\n _unregisterMeshWithPoseMatrix(mesh) {\n const index = this._meshesWithPoseMatrix.indexOf(mesh);\n if (index > -1) {\n this._meshesWithPoseMatrix.splice(index, 1);\n }\n }\n _computeTransformMatrices(targetMatrix, initialSkinMatrix) {\n this.onBeforeComputeObservable.notifyObservers(this);\n for (let index = 0; index < this.bones.length; index++) {\n const bone = this.bones[index];\n bone._childUpdateId++;\n const parentBone = bone.getParent();\n if (parentBone) {\n bone.getLocalMatrix().multiplyToRef(parentBone.getFinalMatrix(), bone.getFinalMatrix());\n }\n else {\n if (initialSkinMatrix) {\n bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getFinalMatrix());\n }\n else {\n bone.getFinalMatrix().copyFrom(bone.getLocalMatrix());\n }\n }\n if (bone._index !== -1) {\n const mappedIndex = bone._index === null ? index : bone._index;\n bone.getAbsoluteInverseBindMatrix().multiplyToArray(bone.getFinalMatrix(), targetMatrix, mappedIndex * 16);\n }\n }\n this._identity.copyToArray(targetMatrix, this.bones.length * 16);\n }\n /**\n * Build all resources required to render a skeleton\n */\n prepare() {\n // Update the local matrix of bones with linked transform nodes.\n if (this._numBonesWithLinkedTransformNode > 0) {\n for (const bone of this.bones) {\n if (bone._linkedTransformNode) {\n const node = bone._linkedTransformNode;\n bone.position = node.position;\n if (node.rotationQuaternion) {\n bone.rotationQuaternion = node.rotationQuaternion;\n }\n else {\n bone.rotation = node.rotation;\n }\n bone.scaling = node.scaling;\n }\n }\n }\n if (this.needInitialSkinMatrix) {\n for (const mesh of this._meshesWithPoseMatrix) {\n const poseMatrix = mesh.getPoseMatrix();\n let needsUpdate = this._isDirty;\n if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {\n mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));\n needsUpdate = true;\n }\n if (!needsUpdate) {\n continue;\n }\n if (this._synchronizedWithMesh !== mesh) {\n this._synchronizedWithMesh = mesh;\n // Prepare bones\n for (const bone of this.bones) {\n if (!bone.getParent()) {\n const matrix = bone.getBindMatrix();\n matrix.multiplyToRef(poseMatrix, TmpVectors.Matrix[1]);\n bone._updateAbsoluteBindMatrices(TmpVectors.Matrix[1]);\n }\n }\n if (this.isUsingTextureForMatrices) {\n const textureWidth = (this.bones.length + 1) * 4;\n if (!mesh._transformMatrixTexture || mesh._transformMatrixTexture.getSize().width !== textureWidth) {\n if (mesh._transformMatrixTexture) {\n mesh._transformMatrixTexture.dispose();\n }\n mesh._transformMatrixTexture = RawTexture.CreateRGBATexture(mesh._bonesTransformMatrices, (this.bones.length + 1) * 4, 1, this._scene, false, false, 1, 1);\n }\n }\n }\n this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);\n if (this.isUsingTextureForMatrices && mesh._transformMatrixTexture) {\n mesh._transformMatrixTexture.update(mesh._bonesTransformMatrices);\n }\n }\n }\n else {\n if (!this._isDirty) {\n return;\n }\n if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {\n this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));\n if (this.isUsingTextureForMatrices) {\n if (this._transformMatrixTexture) {\n this._transformMatrixTexture.dispose();\n }\n this._transformMatrixTexture = RawTexture.CreateRGBATexture(this._transformMatrices, (this.bones.length + 1) * 4, 1, this._scene, false, false, 1, 1);\n }\n }\n this._computeTransformMatrices(this._transformMatrices, null);\n if (this.isUsingTextureForMatrices && this._transformMatrixTexture) {\n this._transformMatrixTexture.update(this._transformMatrices);\n }\n }\n this._isDirty = false;\n }\n /**\n * Gets the list of animatables currently running for this skeleton\n * @returns an array of animatables\n */\n getAnimatables() {\n if (!this._animatables || this._animatables.length !== this.bones.length) {\n this._animatables = [];\n for (let index = 0; index < this.bones.length; index++) {\n this._animatables.push(this.bones[index]);\n }\n }\n return this._animatables;\n }\n /**\n * Clone the current skeleton\n * @param name defines the name of the new skeleton\n * @param id defines the id of the new skeleton\n * @returns the new skeleton\n */\n clone(name, id) {\n const result = new Skeleton(name, id || name, this._scene);\n result.needInitialSkinMatrix = this.needInitialSkinMatrix;\n for (let index = 0; index < this.bones.length; index++) {\n const source = this.bones[index];\n let parentBone = null;\n const parent = source.getParent();\n if (parent) {\n const parentIndex = this.bones.indexOf(parent);\n parentBone = result.bones[parentIndex];\n }\n const bone = new Bone(source.name, result, parentBone, source.getBindMatrix().clone(), source.getRestMatrix().clone());\n bone._index = source._index;\n if (source._linkedTransformNode) {\n bone.linkTransformNode(source._linkedTransformNode);\n }\n DeepCopier.DeepCopy(source.animations, bone.animations);\n }\n if (this._ranges) {\n result._ranges = {};\n for (const rangeName in this._ranges) {\n const range = this._ranges[rangeName];\n if (range) {\n result._ranges[rangeName] = range.clone();\n }\n }\n }\n this._isDirty = true;\n return result;\n }\n /**\n * Enable animation blending for this skeleton\n * @param blendingSpeed defines the blending speed to apply\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#animation-blending\n */\n enableBlending(blendingSpeed = 0.01) {\n this.bones.forEach((bone) => {\n bone.animations.forEach((animation) => {\n animation.enableBlending = true;\n animation.blendingSpeed = blendingSpeed;\n });\n });\n }\n /**\n * Releases all resources associated with the current skeleton\n */\n dispose() {\n this._meshesWithPoseMatrix.length = 0;\n // Animations\n this.getScene().stopAnimation(this);\n // Remove from scene\n this.getScene().removeSkeleton(this);\n if (this._parentContainer) {\n const index = this._parentContainer.skeletons.indexOf(this);\n if (index > -1) {\n this._parentContainer.skeletons.splice(index, 1);\n }\n this._parentContainer = null;\n }\n if (this._transformMatrixTexture) {\n this._transformMatrixTexture.dispose();\n this._transformMatrixTexture = null;\n }\n }\n /**\n * Serialize the skeleton in a JSON object\n * @returns a JSON object\n */\n serialize() {\n var _a;\n const serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.id = this.id;\n if (this.dimensionsAtRest) {\n serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();\n }\n serializationObject.bones = [];\n serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;\n for (let index = 0; index < this.bones.length; index++) {\n const bone = this.bones[index];\n const parent = bone.getParent();\n const serializedBone = {\n parentBoneIndex: parent ? this.bones.indexOf(parent) : -1,\n index: bone.getIndex(),\n name: bone.name,\n id: bone.id,\n matrix: bone.getBindMatrix().toArray(),\n rest: bone.getRestMatrix().toArray(),\n linkedTransformNodeId: (_a = bone.getTransformNode()) === null || _a === void 0 ? void 0 : _a.id,\n };\n serializationObject.bones.push(serializedBone);\n if (bone.length) {\n serializedBone.length = bone.length;\n }\n if (bone.metadata) {\n serializedBone.metadata = bone.metadata;\n }\n if (bone.animations && bone.animations.length > 0) {\n serializedBone.animation = bone.animations[0].serialize();\n }\n serializationObject.ranges = [];\n for (const name in this._ranges) {\n const source = this._ranges[name];\n if (!source) {\n continue;\n }\n const range = {};\n range.name = name;\n range.from = source.from;\n range.to = source.to;\n serializationObject.ranges.push(range);\n }\n }\n return serializationObject;\n }\n /**\n * Creates a new skeleton from serialized data\n * @param parsedSkeleton defines the serialized data\n * @param scene defines the hosting scene\n * @returns a new skeleton\n */\n static Parse(parsedSkeleton, scene) {\n const skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);\n if (parsedSkeleton.dimensionsAtRest) {\n skeleton.dimensionsAtRest = Vector3.FromArray(parsedSkeleton.dimensionsAtRest);\n }\n skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;\n let index;\n for (index = 0; index < parsedSkeleton.bones.length; index++) {\n const parsedBone = parsedSkeleton.bones[index];\n const parsedBoneIndex = parsedSkeleton.bones[index].index;\n let parentBone = null;\n if (parsedBone.parentBoneIndex > -1) {\n parentBone = skeleton.bones[parsedBone.parentBoneIndex];\n }\n const rest = parsedBone.rest ? Matrix.FromArray(parsedBone.rest) : null;\n const bone = new Bone(parsedBone.name, skeleton, parentBone, Matrix.FromArray(parsedBone.matrix), rest, null, parsedBoneIndex);\n if (parsedBone.id !== undefined && parsedBone.id !== null) {\n bone.id = parsedBone.id;\n }\n if (parsedBone.length) {\n bone.length = parsedBone.length;\n }\n if (parsedBone.metadata) {\n bone.metadata = parsedBone.metadata;\n }\n if (parsedBone.animation) {\n bone.animations.push(Animation.Parse(parsedBone.animation));\n }\n if (parsedBone.linkedTransformNodeId !== undefined && parsedBone.linkedTransformNodeId !== null) {\n skeleton._hasWaitingData = true;\n bone._waitingTransformNodeId = parsedBone.linkedTransformNodeId;\n }\n }\n // placed after bones, so createAnimationRange can cascade down\n if (parsedSkeleton.ranges) {\n for (index = 0; index < parsedSkeleton.ranges.length; index++) {\n const data = parsedSkeleton.ranges[index];\n skeleton.createAnimationRange(data.name, data.from, data.to);\n }\n }\n return skeleton;\n }\n /**\n * Compute all node absolute matrices\n * @param forceUpdate defines if computation must be done even if cache is up to date\n */\n computeAbsoluteMatrices(forceUpdate = false) {\n if (this._absoluteTransformIsDirty || forceUpdate) {\n this.bones[0].computeAbsoluteMatrices();\n this._absoluteTransformIsDirty = false;\n }\n }\n /**\n * Compute all node absolute matrices\n * @param forceUpdate defines if computation must be done even if cache is up to date\n * @deprecated Please use computeAbsoluteMatrices instead\n */\n computeAbsoluteTransforms(forceUpdate = false) {\n this.computeAbsoluteMatrices(forceUpdate);\n }\n /**\n * Gets the root pose matrix\n * @returns a matrix\n */\n getPoseMatrix() {\n let poseMatrix = null;\n if (this._meshesWithPoseMatrix.length > 0) {\n poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();\n }\n return poseMatrix;\n }\n /**\n * Sorts bones per internal index\n */\n sortBones() {\n const bones = new Array();\n const visited = new Array(this.bones.length);\n for (let index = 0; index < this.bones.length; index++) {\n this._sortBones(index, bones, visited);\n }\n this.bones = bones;\n }\n _sortBones(index, bones, visited) {\n if (visited[index]) {\n return;\n }\n visited[index] = true;\n const bone = this.bones[index];\n if (!bone)\n return;\n if (bone._index === undefined) {\n bone._index = index;\n }\n const parentBone = bone.getParent();\n if (parentBone) {\n this._sortBones(this.bones.indexOf(parentBone), bones, visited);\n }\n bones.push(bone);\n }\n /**\n * Set the current local matrix as the restPose for all bones in the skeleton.\n */\n setCurrentPoseAsRest() {\n this.bones.forEach((b) => {\n b.setCurrentPoseAsRest();\n });\n }\n}\n//# sourceMappingURL=skeleton.js.map","export * from \"./bone.js\";\nexport * from \"./boneIKController.js\";\nexport * from \"./boneLookController.js\";\nexport * from \"./skeleton.js\";\n//# sourceMappingURL=index.js.map","\n/**\n * This class is a small wrapper around a native buffer that can be read and/or written\n */\nexport class StorageBuffer {\n /**\n * Creates a new storage buffer instance\n * @param engine The engine the buffer will be created inside\n * @param size The size of the buffer in bytes\n * @param creationFlags flags to use when creating the buffer (see undefined). The BUFFER_CREATIONFLAG_STORAGE flag will be automatically added.\n */\n constructor(engine, size, creationFlags = 3) {\n this._engine = engine;\n this._engine._storageBuffers.push(this);\n this._create(size, creationFlags);\n }\n _create(size, creationFlags) {\n this._bufferSize = size;\n this._creationFlags = creationFlags;\n this._buffer = this._engine.createStorageBuffer(size, creationFlags);\n }\n /** @internal */\n _rebuild() {\n this._create(this._bufferSize, this._creationFlags);\n }\n /**\n * Gets underlying native buffer\n * @returns underlying native buffer\n */\n getBuffer() {\n return this._buffer;\n }\n /**\n * Updates the storage buffer\n * @param data the data used to update the storage buffer\n * @param byteOffset the byte offset of the data (optional)\n * @param byteLength the byte length of the data (optional)\n */\n update(data, byteOffset, byteLength) {\n if (!this._buffer) {\n return;\n }\n this._engine.updateStorageBuffer(this._buffer, data, byteOffset, byteLength);\n }\n /**\n * Reads data from the storage buffer\n * @param offset The offset in the storage buffer to start reading from (default: 0)\n * @param size The number of bytes to read from the storage buffer (default: capacity of the buffer)\n * @param buffer The buffer to write the data we have read from the storage buffer to (optional)\n * @returns If not undefined, returns the (promise) buffer (as provided by the 4th parameter) filled with the data, else it returns a (promise) Uint8Array with the data read from the storage buffer\n */\n read(offset, size, buffer) {\n return this._engine.readFromStorageBuffer(this._buffer, offset, size, buffer);\n }\n /**\n * Disposes the storage buffer\n */\n dispose() {\n const storageBuffers = this._engine._storageBuffers;\n const index = storageBuffers.indexOf(this);\n if (index !== -1) {\n storageBuffers[index] = storageBuffers[storageBuffers.length - 1];\n storageBuffers.pop();\n }\n this._engine._releaseBuffer(this._buffer);\n this._buffer = null;\n }\n}\n//# sourceMappingURL=storageBuffer.js.map","export * from \"./buffer.js\";\nexport * from \"./dataBuffer.js\";\nexport * from \"./storageBuffer.js\";\n//# sourceMappingURL=index.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { PointerEventTypes } from \"../../Events/pointerEvents.js\";\nimport { EventConstants } from \"../../Events/deviceInputEvents.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * Base class for mouse wheel input..\n * See FollowCameraMouseWheelInput in src/Cameras/Inputs/freeCameraMouseWheelInput.ts\n * for example usage.\n */\nexport class BaseCameraMouseWheelInput {\n constructor() {\n /**\n * How fast is the camera moves in relation to X axis mouseWheel events.\n * Use negative value to reverse direction.\n */\n this.wheelPrecisionX = 3.0;\n /**\n * How fast is the camera moves in relation to Y axis mouseWheel events.\n * Use negative value to reverse direction.\n */\n this.wheelPrecisionY = 3.0;\n /**\n * How fast is the camera moves in relation to Z axis mouseWheel events.\n * Use negative value to reverse direction.\n */\n this.wheelPrecisionZ = 3.0;\n /**\n * Observable for when a mouse wheel move event occurs.\n */\n this.onChangedObservable = new Observable();\n /**\n * Incremental value of multiple mouse wheel movements of the X axis.\n * Should be zero-ed when read.\n */\n this._wheelDeltaX = 0;\n /**\n * Incremental value of multiple mouse wheel movements of the Y axis.\n * Should be zero-ed when read.\n */\n this._wheelDeltaY = 0;\n /**\n * Incremental value of multiple mouse wheel movements of the Z axis.\n * Should be zero-ed when read.\n */\n this._wheelDeltaZ = 0;\n /**\n * Firefox uses a different scheme to report scroll distances to other\n * browsers. Rather than use complicated methods to calculate the exact\n * multiple we need to apply, let's just cheat and use a constant.\n * https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/deltaMode\n * https://stackoverflow.com/questions/20110224/what-is-the-height-of-a-line-in-a-wheel-event-deltamode-dom-delta-line\n */\n this._ffMultiplier = 12;\n /**\n * Different event attributes for wheel data fall into a few set ranges.\n * Some relevant but dated date here:\n * https://stackoverflow.com/questions/5527601/normalizing-mousewheel-speed-across-browsers\n */\n this._normalize = 120;\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n * @param noPreventDefault Defines whether event caught by the controls\n * should call preventdefault().\n * (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(noPreventDefault) {\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n this._wheel = (pointer) => {\n // sanity check - this should be a PointerWheel event.\n if (pointer.type !== PointerEventTypes.POINTERWHEEL) {\n return;\n }\n const event = pointer.event;\n const platformScale = event.deltaMode === EventConstants.DOM_DELTA_LINE ? this._ffMultiplier : 1; // If this happens to be set to DOM_DELTA_LINE, adjust accordingly\n this._wheelDeltaX += (this.wheelPrecisionX * platformScale * event.deltaX) / this._normalize;\n this._wheelDeltaY -= (this.wheelPrecisionY * platformScale * event.deltaY) / this._normalize;\n this._wheelDeltaZ += (this.wheelPrecisionZ * platformScale * event.deltaZ) / this._normalize;\n if (event.preventDefault) {\n if (!noPreventDefault) {\n event.preventDefault();\n }\n }\n };\n this._observer = this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel, PointerEventTypes.POINTERWHEEL);\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n if (this._observer) {\n this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer);\n this._observer = null;\n this._wheel = null;\n }\n if (this.onChangedObservable) {\n this.onChangedObservable.clear();\n }\n }\n /**\n * Called for each rendered frame.\n */\n checkInputs() {\n this.onChangedObservable.notifyObservers({\n wheelDeltaX: this._wheelDeltaX,\n wheelDeltaY: this._wheelDeltaY,\n wheelDeltaZ: this._wheelDeltaZ,\n });\n // Clear deltas.\n this._wheelDeltaX = 0;\n this._wheelDeltaY = 0;\n this._wheelDeltaZ = 0;\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"BaseCameraMouseWheelInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"mousewheel\";\n }\n}\n__decorate([\n serialize()\n], BaseCameraMouseWheelInput.prototype, \"wheelPrecisionX\", void 0);\n__decorate([\n serialize()\n], BaseCameraMouseWheelInput.prototype, \"wheelPrecisionY\", void 0);\n__decorate([\n serialize()\n], BaseCameraMouseWheelInput.prototype, \"wheelPrecisionZ\", void 0);\n//# sourceMappingURL=BaseCameraMouseWheelInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nimport { PointerEventTypes } from \"../../Events/pointerEvents.js\";\n/**\n * Base class for Camera Pointer Inputs.\n * See FollowCameraPointersInput in src/Cameras/Inputs/followCameraPointersInput.ts\n * for example usage.\n */\nexport class BaseCameraPointersInput {\n constructor() {\n this._currentActiveButton = -1;\n /**\n * Defines the buttons associated with the input to handle camera move.\n */\n this.buttons = [0, 1, 2];\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(noPreventDefault) {\n // eslint-disable-next-line prefer-rest-params\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n const engine = this.camera.getEngine();\n const element = engine.getInputElement();\n let previousPinchSquaredDistance = 0;\n let previousMultiTouchPanPosition = null;\n this._pointA = null;\n this._pointB = null;\n this._altKey = false;\n this._ctrlKey = false;\n this._metaKey = false;\n this._shiftKey = false;\n this._buttonsPressed = 0;\n this._pointerInput = (p) => {\n var _a, _b;\n const evt = p.event;\n const isTouch = evt.pointerType === \"touch\";\n if (engine.isInVRExclusivePointerMode) {\n return;\n }\n if (p.type !== PointerEventTypes.POINTERMOVE && this.buttons.indexOf(evt.button) === -1) {\n return;\n }\n const srcElement = evt.target;\n this._altKey = evt.altKey;\n this._ctrlKey = evt.ctrlKey;\n this._metaKey = evt.metaKey;\n this._shiftKey = evt.shiftKey;\n this._buttonsPressed = evt.buttons;\n if (engine.isPointerLock) {\n const offsetX = evt.movementX;\n const offsetY = evt.movementY;\n this.onTouch(null, offsetX, offsetY);\n this._pointA = null;\n this._pointB = null;\n }\n else if (p.type !== PointerEventTypes.POINTERDOWN && isTouch && ((_a = this._pointA) === null || _a === void 0 ? void 0 : _a.pointerId) !== evt.pointerId && ((_b = this._pointB) === null || _b === void 0 ? void 0 : _b.pointerId) !== evt.pointerId) {\n return; // If we get a non-down event for a touch that we're not tracking, ignore it\n }\n else if (p.type === PointerEventTypes.POINTERDOWN && (this._currentActiveButton === -1 || isTouch)) {\n try {\n srcElement === null || srcElement === void 0 ? void 0 : srcElement.setPointerCapture(evt.pointerId);\n }\n catch (e) {\n //Nothing to do with the error. Execution will continue.\n }\n if (this._pointA === null) {\n this._pointA = {\n x: evt.clientX,\n y: evt.clientY,\n pointerId: evt.pointerId,\n type: evt.pointerType,\n };\n }\n else if (this._pointB === null) {\n this._pointB = {\n x: evt.clientX,\n y: evt.clientY,\n pointerId: evt.pointerId,\n type: evt.pointerType,\n };\n }\n else {\n return; // We are already tracking two pointers so ignore this one\n }\n if (this._currentActiveButton === -1 && !isTouch) {\n this._currentActiveButton = evt.button;\n }\n this.onButtonDown(evt);\n if (!noPreventDefault) {\n evt.preventDefault();\n element && element.focus();\n }\n }\n else if (p.type === PointerEventTypes.POINTERDOUBLETAP) {\n this.onDoubleTap(evt.pointerType);\n }\n else if (p.type === PointerEventTypes.POINTERUP && (this._currentActiveButton === evt.button || isTouch)) {\n try {\n srcElement === null || srcElement === void 0 ? void 0 : srcElement.releasePointerCapture(evt.pointerId);\n }\n catch (e) {\n //Nothing to do with the error.\n }\n if (!isTouch) {\n this._pointB = null; // Mouse and pen are mono pointer\n }\n //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,\n //but emptying completely pointers collection is required to fix a bug on iPhone :\n //when changing orientation while pinching camera,\n //one pointer stay pressed forever if we don't release all pointers\n //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected\n if (engine._badOS) {\n this._pointA = this._pointB = null;\n }\n else {\n //only remove the impacted pointer in case of multitouch allowing on most\n //platforms switching from rotate to zoom and pan seamlessly.\n if (this._pointB && this._pointA && this._pointA.pointerId == evt.pointerId) {\n this._pointA = this._pointB;\n this._pointB = null;\n }\n else if (this._pointA && this._pointB && this._pointB.pointerId == evt.pointerId) {\n this._pointB = null;\n }\n else {\n this._pointA = this._pointB = null;\n }\n }\n if (previousPinchSquaredDistance !== 0 || previousMultiTouchPanPosition) {\n // Previous pinch data is populated but a button has been lifted\n // so pinch has ended.\n this.onMultiTouch(this._pointA, this._pointB, previousPinchSquaredDistance, 0, // pinchSquaredDistance\n previousMultiTouchPanPosition, null // multiTouchPanPosition\n );\n previousPinchSquaredDistance = 0;\n previousMultiTouchPanPosition = null;\n }\n this._currentActiveButton = -1;\n this.onButtonUp(evt);\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n else if (p.type === PointerEventTypes.POINTERMOVE) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n // One button down\n if (this._pointA && this._pointB === null) {\n const offsetX = evt.clientX - this._pointA.x;\n const offsetY = evt.clientY - this._pointA.y;\n this.onTouch(this._pointA, offsetX, offsetY);\n this._pointA.x = evt.clientX;\n this._pointA.y = evt.clientY;\n }\n // Two buttons down: pinch\n else if (this._pointA && this._pointB) {\n const ed = this._pointA.pointerId === evt.pointerId ? this._pointA : this._pointB;\n ed.x = evt.clientX;\n ed.y = evt.clientY;\n const distX = this._pointA.x - this._pointB.x;\n const distY = this._pointA.y - this._pointB.y;\n const pinchSquaredDistance = distX * distX + distY * distY;\n const multiTouchPanPosition = {\n x: (this._pointA.x + this._pointB.x) / 2,\n y: (this._pointA.y + this._pointB.y) / 2,\n pointerId: evt.pointerId,\n type: p.type,\n };\n this.onMultiTouch(this._pointA, this._pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition);\n previousMultiTouchPanPosition = multiTouchPanPosition;\n previousPinchSquaredDistance = pinchSquaredDistance;\n }\n }\n };\n this._observer = this.camera\n .getScene()\n ._inputManager._addCameraPointerObserver(this._pointerInput, PointerEventTypes.POINTERDOWN | PointerEventTypes.POINTERUP | PointerEventTypes.POINTERMOVE | PointerEventTypes.POINTERDOUBLETAP);\n this._onLostFocus = () => {\n this._pointA = this._pointB = null;\n previousPinchSquaredDistance = 0;\n previousMultiTouchPanPosition = null;\n this.onLostFocus();\n };\n this._contextMenuBind = this.onContextMenu.bind(this);\n element && element.addEventListener(\"contextmenu\", this._contextMenuBind, false);\n const hostWindow = this.camera.getScene().getEngine().getHostWindow();\n if (hostWindow) {\n Tools.RegisterTopRootEvents(hostWindow, [{ name: \"blur\", handler: this._onLostFocus }]);\n }\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n if (this._onLostFocus) {\n const hostWindow = this.camera.getScene().getEngine().getHostWindow();\n if (hostWindow) {\n Tools.UnregisterTopRootEvents(hostWindow, [{ name: \"blur\", handler: this._onLostFocus }]);\n }\n }\n if (this._observer) {\n this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer);\n this._observer = null;\n if (this._contextMenuBind) {\n const inputElement = this.camera.getScene().getEngine().getInputElement();\n inputElement && inputElement.removeEventListener(\"contextmenu\", this._contextMenuBind);\n }\n this._onLostFocus = null;\n }\n this._altKey = false;\n this._ctrlKey = false;\n this._metaKey = false;\n this._shiftKey = false;\n this._buttonsPressed = 0;\n this._currentActiveButton = -1;\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"BaseCameraPointersInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"pointers\";\n }\n /**\n * Called on pointer POINTERDOUBLETAP event.\n * Override this method to provide functionality on POINTERDOUBLETAP event.\n * @param type\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onDoubleTap(type) { }\n /**\n * Called on pointer POINTERMOVE event if only a single touch is active.\n * Override this method to provide functionality.\n * @param point\n * @param offsetX\n * @param offsetY\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onTouch(point, offsetX, offsetY) { }\n /**\n * Called on pointer POINTERMOVE event if multiple touches are active.\n * Override this method to provide functionality.\n * @param _pointA\n * @param _pointB\n * @param previousPinchSquaredDistance\n * @param pinchSquaredDistance\n * @param previousMultiTouchPanPosition\n * @param multiTouchPanPosition\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onMultiTouch(_pointA, _pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition) { }\n /**\n * Called on JS contextmenu event.\n * Override this method to provide functionality.\n * @param evt\n */\n onContextMenu(evt) {\n evt.preventDefault();\n }\n /**\n * Called each time a new POINTERDOWN event occurs. Ie, for each button\n * press.\n * Override this method to provide functionality.\n * @param evt\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onButtonDown(evt) { }\n /**\n * Called each time a new POINTERUP event occurs. Ie, for each button\n * release.\n * Override this method to provide functionality.\n * @param evt\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onButtonUp(evt) { }\n /**\n * Called when window becomes inactive.\n * Override this method to provide functionality.\n */\n onLostFocus() { }\n}\n__decorate([\n serialize()\n], BaseCameraPointersInput.prototype, \"buttons\", void 0);\n//# sourceMappingURL=BaseCameraPointersInput.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { SerializationHelper } from \"../Misc/decorators.js\";\nimport { Camera } from \"./camera.js\";\n/**\n * @ignore\n * This is a list of all the different input types that are available in the application.\n * Fo instance: ArcRotateCameraGamepadInput...\n */\n// eslint-disable-next-line no-var, @typescript-eslint/naming-convention\nexport var CameraInputTypes = {};\n/**\n * This represents the input manager used within a camera.\n * It helps dealing with all the different kind of input attached to a camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class CameraInputsManager {\n /**\n * Instantiate a new Camera Input Manager.\n * @param camera Defines the camera the input manager belongs to\n */\n constructor(camera) {\n /**\n * Defines the dom element the camera is collecting inputs from.\n * This is null if the controls have not been attached.\n */\n this.attachedToElement = false;\n this.attached = {};\n this.camera = camera;\n this.checkInputs = () => { };\n }\n /**\n * Add an input method to a camera\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n * @param input Camera input method\n */\n add(input) {\n const type = input.getSimpleName();\n if (this.attached[type]) {\n Logger.Warn(\"camera input of type \" + type + \" already exists on camera\");\n return;\n }\n this.attached[type] = input;\n input.camera = this.camera;\n // for checkInputs, we are dynamically creating a function\n // the goal is to avoid the performance penalty of looping for inputs in the render loop\n if (input.checkInputs) {\n this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));\n }\n if (this.attachedToElement) {\n input.attachControl(this.noPreventDefault);\n }\n }\n /**\n * Remove a specific input method from a camera\n * example: camera.inputs.remove(camera.inputs.attached.mouse);\n * @param inputToRemove camera input method\n */\n remove(inputToRemove) {\n for (const cam in this.attached) {\n const input = this.attached[cam];\n if (input === inputToRemove) {\n input.detachControl();\n input.camera = null;\n delete this.attached[cam];\n this.rebuildInputCheck();\n return;\n }\n }\n }\n /**\n * Remove a specific input type from a camera\n * example: camera.inputs.remove(\"ArcRotateCameraGamepadInput\");\n * @param inputType the type of the input to remove\n */\n removeByType(inputType) {\n for (const cam in this.attached) {\n const input = this.attached[cam];\n if (input.getClassName() === inputType) {\n input.detachControl();\n input.camera = null;\n delete this.attached[cam];\n this.rebuildInputCheck();\n }\n }\n }\n _addCheckInputs(fn) {\n const current = this.checkInputs;\n return () => {\n current();\n fn();\n };\n }\n /**\n * Attach the input controls to the currently attached dom element to listen the events from.\n * @param input Defines the input to attach\n */\n attachInput(input) {\n if (this.attachedToElement) {\n input.attachControl(this.noPreventDefault);\n }\n }\n /**\n * Attach the current manager inputs controls to a specific dom element to listen the events from.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachElement(noPreventDefault = false) {\n if (this.attachedToElement) {\n return;\n }\n noPreventDefault = Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;\n this.attachedToElement = true;\n this.noPreventDefault = noPreventDefault;\n for (const cam in this.attached) {\n this.attached[cam].attachControl(noPreventDefault);\n }\n }\n /**\n * Detach the current manager inputs controls from a specific dom element.\n * @param disconnect Defines whether the input should be removed from the current list of attached inputs\n */\n detachElement(disconnect = false) {\n for (const cam in this.attached) {\n this.attached[cam].detachControl();\n if (disconnect) {\n this.attached[cam].camera = null;\n }\n }\n this.attachedToElement = false;\n }\n /**\n * Rebuild the dynamic inputCheck function from the current list of\n * defined inputs in the manager.\n */\n rebuildInputCheck() {\n this.checkInputs = () => { };\n for (const cam in this.attached) {\n const input = this.attached[cam];\n if (input.checkInputs) {\n this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));\n }\n }\n }\n /**\n * Remove all attached input methods from a camera\n */\n clear() {\n if (this.attachedToElement) {\n this.detachElement(true);\n }\n this.attached = {};\n this.attachedToElement = false;\n this.checkInputs = () => { };\n }\n /**\n * Serialize the current input manager attached to a camera.\n * This ensures than once parsed,\n * the input associated to the camera will be identical to the current ones\n * @param serializedCamera Defines the camera serialization JSON the input serialization should write to\n */\n serialize(serializedCamera) {\n const inputs = {};\n for (const cam in this.attached) {\n const input = this.attached[cam];\n const res = SerializationHelper.Serialize(input);\n inputs[input.getClassName()] = res;\n }\n serializedCamera.inputsmgr = inputs;\n }\n /**\n * Parses an input manager serialized JSON to restore the previous list of inputs\n * and states associated to a camera.\n * @param parsedCamera Defines the JSON to parse\n */\n parse(parsedCamera) {\n const parsedInputs = parsedCamera.inputsmgr;\n if (parsedInputs) {\n this.clear();\n for (const n in parsedInputs) {\n const construct = CameraInputTypes[n];\n if (construct) {\n const parsedinput = parsedInputs[n];\n const input = SerializationHelper.Parse(() => {\n return new construct();\n }, parsedinput, null);\n this.add(input);\n }\n }\n }\n else {\n //2016-03-08 this part is for managing backward compatibility\n for (const n in this.attached) {\n const construct = CameraInputTypes[this.attached[n].getClassName()];\n if (construct) {\n const input = SerializationHelper.Parse(() => {\n return new construct();\n }, parsedCamera, null);\n this.remove(this.attached[n]);\n this.add(input);\n }\n }\n }\n }\n}\n//# sourceMappingURL=cameraInputsManager.js.map","import { Observable } from \"../Misc/observable.js\";\n/**\n * Represents a gamepad control stick position\n */\nexport class StickValues {\n /**\n * Initializes the gamepad x and y control stick values\n * @param x The x component of the gamepad control stick value\n * @param y The y component of the gamepad control stick value\n */\n constructor(\n /**\n * The x component of the control stick\n */\n x, \n /**\n * The y component of the control stick\n */\n y) {\n this.x = x;\n this.y = y;\n }\n}\n/**\n * Represents a gamepad\n */\nexport class Gamepad {\n /**\n * Specifies if the gamepad has been connected\n */\n get isConnected() {\n return this._isConnected;\n }\n /**\n * Initializes the gamepad\n * @param id The id of the gamepad\n * @param index The index of the gamepad\n * @param browserGamepad The browser gamepad\n * @param leftStickX The x component of the left joystick\n * @param leftStickY The y component of the left joystick\n * @param rightStickX The x component of the right joystick\n * @param rightStickY The y component of the right joystick\n */\n constructor(\n /**\n * The id of the gamepad\n */\n id, \n /**\n * The index of the gamepad\n */\n index, \n /**\n * The browser gamepad\n */\n browserGamepad, leftStickX = 0, leftStickY = 1, rightStickX = 2, rightStickY = 3) {\n this.id = id;\n this.index = index;\n this.browserGamepad = browserGamepad;\n this._leftStick = { x: 0, y: 0 };\n this._rightStick = { x: 0, y: 0 };\n /** @internal */\n this._isConnected = true;\n /**\n * Specifies whether the left control stick should be Y-inverted\n */\n this._invertLeftStickY = false;\n this.type = Gamepad.GAMEPAD;\n this._leftStickAxisX = leftStickX;\n this._leftStickAxisY = leftStickY;\n this._rightStickAxisX = rightStickX;\n this._rightStickAxisY = rightStickY;\n if (this.browserGamepad.axes.length >= 2) {\n this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };\n }\n if (this.browserGamepad.axes.length >= 4) {\n this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };\n }\n }\n /**\n * Callback triggered when the left joystick has changed\n * @param callback\n */\n onleftstickchanged(callback) {\n this._onleftstickchanged = callback;\n }\n /**\n * Callback triggered when the right joystick has changed\n * @param callback\n */\n onrightstickchanged(callback) {\n this._onrightstickchanged = callback;\n }\n /**\n * Gets the left joystick\n */\n get leftStick() {\n return this._leftStick;\n }\n /**\n * Sets the left joystick values\n */\n set leftStick(newValues) {\n if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {\n this._onleftstickchanged(newValues);\n }\n this._leftStick = newValues;\n }\n /**\n * Gets the right joystick\n */\n get rightStick() {\n return this._rightStick;\n }\n /**\n * Sets the right joystick value\n */\n set rightStick(newValues) {\n if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {\n this._onrightstickchanged(newValues);\n }\n this._rightStick = newValues;\n }\n /**\n * Updates the gamepad joystick positions\n */\n update() {\n if (this._leftStick) {\n this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };\n if (this._invertLeftStickY) {\n this.leftStick.y *= -1;\n }\n }\n if (this._rightStick) {\n this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };\n }\n }\n /**\n * Disposes the gamepad\n */\n dispose() { }\n}\n/**\n * Represents a gamepad controller\n */\nGamepad.GAMEPAD = 0;\n/**\n * Represents a generic controller\n */\nGamepad.GENERIC = 1;\n/**\n * Represents an XBox controller\n */\nGamepad.XBOX = 2;\n/**\n * Represents a pose-enabled controller\n */\nGamepad.POSE_ENABLED = 3;\n/**\n * Represents an Dual Shock controller\n */\nGamepad.DUALSHOCK = 4;\n/**\n * Represents a generic gamepad\n */\nexport class GenericPad extends Gamepad {\n /**\n * Callback triggered when a button has been pressed\n * @param callback Called when a button has been pressed\n */\n onbuttondown(callback) {\n this._onbuttondown = callback;\n }\n /**\n * Callback triggered when a button has been released\n * @param callback Called when a button has been released\n */\n onbuttonup(callback) {\n this._onbuttonup = callback;\n }\n /**\n * Initializes the generic gamepad\n * @param id The id of the generic gamepad\n * @param index The index of the generic gamepad\n * @param browserGamepad The browser gamepad\n */\n constructor(id, index, browserGamepad) {\n super(id, index, browserGamepad);\n /**\n * Observable triggered when a button has been pressed\n */\n this.onButtonDownObservable = new Observable();\n /**\n * Observable triggered when a button has been released\n */\n this.onButtonUpObservable = new Observable();\n this.type = Gamepad.GENERIC;\n this._buttons = new Array(browserGamepad.buttons.length);\n }\n _setButtonValue(newValue, currentValue, buttonIndex) {\n if (newValue !== currentValue) {\n if (newValue === 1) {\n if (this._onbuttondown) {\n this._onbuttondown(buttonIndex);\n }\n this.onButtonDownObservable.notifyObservers(buttonIndex);\n }\n if (newValue === 0) {\n if (this._onbuttonup) {\n this._onbuttonup(buttonIndex);\n }\n this.onButtonUpObservable.notifyObservers(buttonIndex);\n }\n }\n return newValue;\n }\n /**\n * Updates the generic gamepad\n */\n update() {\n super.update();\n for (let index = 0; index < this._buttons.length; index++) {\n this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);\n }\n }\n /**\n * Disposes the generic gamepad\n */\n dispose() {\n super.dispose();\n this.onButtonDownObservable.clear();\n this.onButtonUpObservable.clear();\n }\n}\n//# sourceMappingURL=gamepad.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { Gamepad } from \"../../Gamepads/gamepad.js\";\n/**\n * Manage the gamepad inputs to control an arc rotate camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class ArcRotateCameraGamepadInput {\n constructor() {\n /**\n * Defines the gamepad rotation sensibility.\n * This is the threshold from when rotation starts to be accounted for to prevent jittering.\n */\n this.gamepadRotationSensibility = 80;\n /**\n * Defines the gamepad move sensibility.\n * This is the threshold from when moving starts to be accounted for for to prevent jittering.\n */\n this.gamepadMoveSensibility = 40;\n this._yAxisScale = 1.0;\n }\n /**\n * Gets or sets a boolean indicating that Yaxis (for right stick) should be inverted\n */\n get invertYAxis() {\n return this._yAxisScale !== 1.0;\n }\n set invertYAxis(value) {\n this._yAxisScale = value ? -1.0 : 1.0;\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n */\n attachControl() {\n const manager = this.camera.getScene().gamepadManager;\n this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add((gamepad) => {\n if (gamepad.type !== Gamepad.POSE_ENABLED) {\n // prioritize XBOX gamepads.\n if (!this.gamepad || gamepad.type === Gamepad.XBOX) {\n this.gamepad = gamepad;\n }\n }\n });\n this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add((gamepad) => {\n if (this.gamepad === gamepad) {\n this.gamepad = null;\n }\n });\n this.gamepad = manager.getGamepadByType(Gamepad.XBOX);\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);\n this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);\n this.gamepad = null;\n }\n /**\n * Update the current camera state depending on the inputs that have been used this frame.\n * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.\n */\n checkInputs() {\n if (this.gamepad) {\n const camera = this.camera;\n const rsValues = this.gamepad.rightStick;\n if (rsValues) {\n if (rsValues.x != 0) {\n const normalizedRX = rsValues.x / this.gamepadRotationSensibility;\n if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {\n camera.inertialAlphaOffset += normalizedRX;\n }\n }\n if (rsValues.y != 0) {\n const normalizedRY = (rsValues.y / this.gamepadRotationSensibility) * this._yAxisScale;\n if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {\n camera.inertialBetaOffset += normalizedRY;\n }\n }\n }\n const lsValues = this.gamepad.leftStick;\n if (lsValues && lsValues.y != 0) {\n const normalizedLY = lsValues.y / this.gamepadMoveSensibility;\n if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {\n this.camera.inertialRadiusOffset -= normalizedLY;\n }\n }\n }\n }\n /**\n * Gets the class name of the current intput.\n * @returns the class name\n */\n getClassName() {\n return \"ArcRotateCameraGamepadInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"gamepad\";\n }\n}\n__decorate([\n serialize()\n], ArcRotateCameraGamepadInput.prototype, \"gamepadRotationSensibility\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraGamepadInput.prototype, \"gamepadMoveSensibility\", void 0);\nCameraInputTypes[\"ArcRotateCameraGamepadInput\"] = ArcRotateCameraGamepadInput;\n//# sourceMappingURL=arcRotateCameraGamepadInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { KeyboardEventTypes } from \"../../Events/keyboardEvents.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * Manage the keyboard inputs to control the movement of an arc rotate camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class ArcRotateCameraKeyboardMoveInput {\n constructor() {\n /**\n * Defines the list of key codes associated with the up action (increase alpha)\n */\n this.keysUp = [38];\n /**\n * Defines the list of key codes associated with the down action (decrease alpha)\n */\n this.keysDown = [40];\n /**\n * Defines the list of key codes associated with the left action (increase beta)\n */\n this.keysLeft = [37];\n /**\n * Defines the list of key codes associated with the right action (decrease beta)\n */\n this.keysRight = [39];\n /**\n * Defines the list of key codes associated with the reset action.\n * Those keys reset the camera to its last stored state (with the method camera.storeState())\n */\n this.keysReset = [220];\n /**\n * Defines the panning sensibility of the inputs.\n * (How fast is the camera panning)\n */\n this.panningSensibility = 50.0;\n /**\n * Defines the zooming sensibility of the inputs.\n * (How fast is the camera zooming)\n */\n this.zoomingSensibility = 25.0;\n /**\n * Defines whether maintaining the alt key down switch the movement mode from\n * orientation to zoom.\n */\n this.useAltToZoom = true;\n /**\n * Rotation speed of the camera\n */\n this.angularSpeed = 0.01;\n this._keys = new Array();\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(noPreventDefault) {\n // was there a second variable defined?\n // eslint-disable-next-line prefer-rest-params\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n if (this._onCanvasBlurObserver) {\n return;\n }\n this._scene = this.camera.getScene();\n this._engine = this._scene.getEngine();\n this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(() => {\n this._keys.length = 0;\n });\n this._onKeyboardObserver = this._scene.onKeyboardObservable.add((info) => {\n const evt = info.event;\n if (!evt.metaKey) {\n if (info.type === KeyboardEventTypes.KEYDOWN) {\n this._ctrlPressed = evt.ctrlKey;\n this._altPressed = evt.altKey;\n if (this.keysUp.indexOf(evt.keyCode) !== -1 ||\n this.keysDown.indexOf(evt.keyCode) !== -1 ||\n this.keysLeft.indexOf(evt.keyCode) !== -1 ||\n this.keysRight.indexOf(evt.keyCode) !== -1 ||\n this.keysReset.indexOf(evt.keyCode) !== -1) {\n const index = this._keys.indexOf(evt.keyCode);\n if (index === -1) {\n this._keys.push(evt.keyCode);\n }\n if (evt.preventDefault) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n }\n }\n else {\n if (this.keysUp.indexOf(evt.keyCode) !== -1 ||\n this.keysDown.indexOf(evt.keyCode) !== -1 ||\n this.keysLeft.indexOf(evt.keyCode) !== -1 ||\n this.keysRight.indexOf(evt.keyCode) !== -1 ||\n this.keysReset.indexOf(evt.keyCode) !== -1) {\n const index = this._keys.indexOf(evt.keyCode);\n if (index >= 0) {\n this._keys.splice(index, 1);\n }\n if (evt.preventDefault) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n }\n }\n }\n });\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n if (this._scene) {\n if (this._onKeyboardObserver) {\n this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);\n }\n if (this._onCanvasBlurObserver) {\n this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);\n }\n this._onKeyboardObserver = null;\n this._onCanvasBlurObserver = null;\n }\n this._keys.length = 0;\n }\n /**\n * Update the current camera state depending on the inputs that have been used this frame.\n * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.\n */\n checkInputs() {\n if (this._onKeyboardObserver) {\n const camera = this.camera;\n for (let index = 0; index < this._keys.length; index++) {\n const keyCode = this._keys[index];\n if (this.keysLeft.indexOf(keyCode) !== -1) {\n if (this._ctrlPressed && this.camera._useCtrlForPanning) {\n camera.inertialPanningX -= 1 / this.panningSensibility;\n }\n else {\n camera.inertialAlphaOffset -= this.angularSpeed;\n }\n }\n else if (this.keysUp.indexOf(keyCode) !== -1) {\n if (this._ctrlPressed && this.camera._useCtrlForPanning) {\n camera.inertialPanningY += 1 / this.panningSensibility;\n }\n else if (this._altPressed && this.useAltToZoom) {\n camera.inertialRadiusOffset += 1 / this.zoomingSensibility;\n }\n else {\n camera.inertialBetaOffset -= this.angularSpeed;\n }\n }\n else if (this.keysRight.indexOf(keyCode) !== -1) {\n if (this._ctrlPressed && this.camera._useCtrlForPanning) {\n camera.inertialPanningX += 1 / this.panningSensibility;\n }\n else {\n camera.inertialAlphaOffset += this.angularSpeed;\n }\n }\n else if (this.keysDown.indexOf(keyCode) !== -1) {\n if (this._ctrlPressed && this.camera._useCtrlForPanning) {\n camera.inertialPanningY -= 1 / this.panningSensibility;\n }\n else if (this._altPressed && this.useAltToZoom) {\n camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;\n }\n else {\n camera.inertialBetaOffset += this.angularSpeed;\n }\n }\n else if (this.keysReset.indexOf(keyCode) !== -1) {\n if (camera.useInputToRestoreState) {\n camera.restoreState();\n }\n }\n }\n }\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"ArcRotateCameraKeyboardMoveInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"keyboard\";\n }\n}\n__decorate([\n serialize()\n], ArcRotateCameraKeyboardMoveInput.prototype, \"keysUp\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraKeyboardMoveInput.prototype, \"keysDown\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraKeyboardMoveInput.prototype, \"keysLeft\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraKeyboardMoveInput.prototype, \"keysRight\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraKeyboardMoveInput.prototype, \"keysReset\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraKeyboardMoveInput.prototype, \"panningSensibility\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraKeyboardMoveInput.prototype, \"zoomingSensibility\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraKeyboardMoveInput.prototype, \"useAltToZoom\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraKeyboardMoveInput.prototype, \"angularSpeed\", void 0);\nCameraInputTypes[\"ArcRotateCameraKeyboardMoveInput\"] = ArcRotateCameraKeyboardMoveInput;\n//# sourceMappingURL=arcRotateCameraKeyboardMoveInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { PointerEventTypes } from \"../../Events/pointerEvents.js\";\nimport { Plane } from \"../../Maths/math.plane.js\";\nimport { Vector3, Matrix, TmpVectors } from \"../../Maths/math.vector.js\";\nimport { Epsilon } from \"../../Maths/math.constants.js\";\nimport { EventConstants } from \"../../Events/deviceInputEvents.js\";\nimport { Scalar } from \"../../Maths/math.scalar.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * Firefox uses a different scheme to report scroll distances to other\n * browsers. Rather than use complicated methods to calculate the exact\n * multiple we need to apply, let's just cheat and use a constant.\n * https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/deltaMode\n * https://stackoverflow.com/questions/20110224/what-is-the-height-of-a-line-in-a-wheel-event-deltamode-dom-delta-line\n */\nconst ffMultiplier = 40;\n/**\n * Manage the mouse wheel inputs to control an arc rotate camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class ArcRotateCameraMouseWheelInput {\n constructor() {\n /**\n * Gets or Set the mouse wheel precision or how fast is the camera zooming.\n */\n this.wheelPrecision = 3.0;\n /**\n * Gets or Set the boolean value that controls whether or not the mouse wheel\n * zooms to the location of the mouse pointer or not. The default is false.\n */\n this.zoomToMouseLocation = false;\n /**\n * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.\n * It defines the percentage of current camera.radius to use as delta when wheel is used.\n */\n this.wheelDeltaPercentage = 0;\n /**\n * If set, this function will be used to set the radius delta that will be added to the current camera radius\n */\n this.customComputeDeltaFromMouseWheel = null;\n this._inertialPanning = Vector3.Zero();\n }\n _computeDeltaFromMouseWheelLegacyEvent(mouseWheelDelta, radius) {\n let delta = 0;\n const wheelDelta = mouseWheelDelta * 0.01 * this.wheelDeltaPercentage * radius;\n if (mouseWheelDelta > 0) {\n delta = wheelDelta / (1.0 + this.wheelDeltaPercentage);\n }\n else {\n delta = wheelDelta * (1.0 + this.wheelDeltaPercentage);\n }\n return delta;\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(noPreventDefault) {\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n this._wheel = (p) => {\n //sanity check - this should be a PointerWheel event.\n if (p.type !== PointerEventTypes.POINTERWHEEL) {\n return;\n }\n const event = p.event;\n let delta = 0;\n const platformScale = event.deltaMode === EventConstants.DOM_DELTA_LINE ? ffMultiplier : 1; // If this happens to be set to DOM_DELTA_LINE, adjust accordingly\n const wheelDelta = -(event.deltaY * platformScale);\n if (this.customComputeDeltaFromMouseWheel) {\n delta = this.customComputeDeltaFromMouseWheel(wheelDelta, this, event);\n }\n else {\n if (this.wheelDeltaPercentage) {\n delta = this._computeDeltaFromMouseWheelLegacyEvent(wheelDelta, this.camera.radius);\n // If zooming in, estimate the target radius and use that to compute the delta for inertia\n // this will stop multiple scroll events zooming in from adding too much inertia\n if (delta > 0) {\n let estimatedTargetRadius = this.camera.radius;\n let targetInertia = this.camera.inertialRadiusOffset + delta;\n for (let i = 0; i < 20 && Math.abs(targetInertia) > 0.001; i++) {\n estimatedTargetRadius -= targetInertia;\n targetInertia *= this.camera.inertia;\n }\n estimatedTargetRadius = Scalar.Clamp(estimatedTargetRadius, 0, Number.MAX_VALUE);\n delta = this._computeDeltaFromMouseWheelLegacyEvent(wheelDelta, estimatedTargetRadius);\n }\n }\n else {\n delta = wheelDelta / (this.wheelPrecision * 40);\n }\n }\n if (delta) {\n if (this.zoomToMouseLocation) {\n // If we are zooming to the mouse location, then we need to get the hit plane at the start of the zoom gesture if it doesn't exist\n // The hit plane is normally calculated after the first motion and each time there's motion so if we don't do this first,\n // the first zoom will be to the center of the screen\n if (!this._hitPlane) {\n this._updateHitPlane();\n }\n this._zoomToMouse(delta);\n }\n else {\n this.camera.inertialRadiusOffset += delta;\n }\n }\n if (event.preventDefault) {\n if (!noPreventDefault) {\n event.preventDefault();\n }\n }\n };\n this._observer = this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel, PointerEventTypes.POINTERWHEEL);\n if (this.zoomToMouseLocation) {\n this._inertialPanning.setAll(0);\n }\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n if (this._observer) {\n this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer);\n this._observer = null;\n this._wheel = null;\n }\n }\n /**\n * Update the current camera state depending on the inputs that have been used this frame.\n * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.\n */\n checkInputs() {\n if (!this.zoomToMouseLocation) {\n return;\n }\n const camera = this.camera;\n const motion = 0.0 + camera.inertialAlphaOffset + camera.inertialBetaOffset + camera.inertialRadiusOffset;\n if (motion) {\n // if zooming is still happening as a result of inertia, then we also need to update\n // the hit plane.\n this._updateHitPlane();\n // Note we cannot use arcRotateCamera.inertialPlanning here because arcRotateCamera panning\n // uses a different panningInertia which could cause this panning to get out of sync with\n // the zooming, and for this to work they must be exactly in sync.\n camera.target.addInPlace(this._inertialPanning);\n this._inertialPanning.scaleInPlace(camera.inertia);\n this._zeroIfClose(this._inertialPanning);\n }\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"ArcRotateCameraMouseWheelInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"mousewheel\";\n }\n _updateHitPlane() {\n const camera = this.camera;\n const direction = camera.target.subtract(camera.position);\n this._hitPlane = Plane.FromPositionAndNormal(camera.target, direction);\n }\n // Get position on the hit plane\n _getPosition() {\n var _a;\n const camera = this.camera;\n const scene = camera.getScene();\n // since the _hitPlane is always updated to be orthogonal to the camera position vector\n // we don't have to worry about this ray shooting off to infinity. This ray creates\n // a vector defining where we want to zoom to.\n const ray = scene.createPickingRay(scene.pointerX, scene.pointerY, Matrix.Identity(), camera, false);\n // Since the camera is the origin of the picking ray, we need to offset it by the camera's offset manually\n ray.origin.x -= camera.targetScreenOffset.x;\n ray.origin.y -= camera.targetScreenOffset.y;\n let distance = 0;\n if (this._hitPlane) {\n distance = (_a = ray.intersectsPlane(this._hitPlane)) !== null && _a !== void 0 ? _a : 0;\n }\n // not using this ray again, so modifying its vectors here is fine\n return ray.origin.addInPlace(ray.direction.scaleInPlace(distance));\n }\n _zoomToMouse(delta) {\n var _a, _b;\n const camera = this.camera;\n const inertiaComp = 1 - camera.inertia;\n if (camera.lowerRadiusLimit) {\n const lowerLimit = (_a = camera.lowerRadiusLimit) !== null && _a !== void 0 ? _a : 0;\n if (camera.radius - (camera.inertialRadiusOffset + delta) / inertiaComp < lowerLimit) {\n delta = (camera.radius - lowerLimit) * inertiaComp - camera.inertialRadiusOffset;\n }\n }\n if (camera.upperRadiusLimit) {\n const upperLimit = (_b = camera.upperRadiusLimit) !== null && _b !== void 0 ? _b : 0;\n if (camera.radius - (camera.inertialRadiusOffset + delta) / inertiaComp > upperLimit) {\n delta = (camera.radius - upperLimit) * inertiaComp - camera.inertialRadiusOffset;\n }\n }\n const zoomDistance = delta / inertiaComp;\n const ratio = zoomDistance / camera.radius;\n const vec = this._getPosition();\n // Now this vector tells us how much we also need to pan the camera\n // so the targeted mouse location becomes the center of zooming.\n const directionToZoomLocation = TmpVectors.Vector3[6];\n vec.subtractToRef(camera.target, directionToZoomLocation);\n directionToZoomLocation.scaleInPlace(ratio);\n directionToZoomLocation.scaleInPlace(inertiaComp);\n this._inertialPanning.addInPlace(directionToZoomLocation);\n camera.inertialRadiusOffset += delta;\n }\n // Sets x y or z of passed in vector to zero if less than Epsilon.\n _zeroIfClose(vec) {\n if (Math.abs(vec.x) < Epsilon) {\n vec.x = 0;\n }\n if (Math.abs(vec.y) < Epsilon) {\n vec.y = 0;\n }\n if (Math.abs(vec.z) < Epsilon) {\n vec.z = 0;\n }\n }\n}\n__decorate([\n serialize()\n], ArcRotateCameraMouseWheelInput.prototype, \"wheelPrecision\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraMouseWheelInput.prototype, \"zoomToMouseLocation\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraMouseWheelInput.prototype, \"wheelDeltaPercentage\", void 0);\nCameraInputTypes[\"ArcRotateCameraMouseWheelInput\"] = ArcRotateCameraMouseWheelInput;\n//# sourceMappingURL=arcRotateCameraMouseWheelInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { BaseCameraPointersInput } from \"../../Cameras/Inputs/BaseCameraPointersInput.js\";\n/**\n * Manage the pointers inputs to control an arc rotate camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class ArcRotateCameraPointersInput extends BaseCameraPointersInput {\n constructor() {\n super(...arguments);\n /**\n * Defines the buttons associated with the input to handle camera move.\n */\n this.buttons = [0, 1, 2];\n /**\n * Defines the pointer angular sensibility along the X axis or how fast is\n * the camera rotating.\n */\n this.angularSensibilityX = 1000.0;\n /**\n * Defines the pointer angular sensibility along the Y axis or how fast is\n * the camera rotating.\n */\n this.angularSensibilityY = 1000.0;\n /**\n * Defines the pointer pinch precision or how fast is the camera zooming.\n */\n this.pinchPrecision = 12.0;\n /**\n * pinchDeltaPercentage will be used instead of pinchPrecision if different\n * from 0.\n * It defines the percentage of current camera.radius to use as delta when\n * pinch zoom is used.\n */\n this.pinchDeltaPercentage = 0;\n /**\n * When useNaturalPinchZoom is true, multi touch zoom will zoom in such\n * that any object in the plane at the camera's target point will scale\n * perfectly with finger motion.\n * Overrides pinchDeltaPercentage and pinchPrecision.\n */\n this.useNaturalPinchZoom = false;\n /**\n * Defines whether zoom (2 fingers pinch) is enabled through multitouch\n */\n this.pinchZoom = true;\n /**\n * Defines the pointer panning sensibility or how fast is the camera moving.\n */\n this.panningSensibility = 1000.0;\n /**\n * Defines whether panning (2 fingers swipe) is enabled through multitouch.\n */\n this.multiTouchPanning = true;\n /**\n * Defines whether panning is enabled for both pan (2 fingers swipe) and\n * zoom (pinch) through multitouch.\n */\n this.multiTouchPanAndZoom = true;\n /**\n * Revers pinch action direction.\n */\n this.pinchInwards = true;\n this._isPanClick = false;\n this._twoFingerActivityCount = 0;\n this._isPinching = false;\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"ArcRotateCameraPointersInput\";\n }\n /**\n * Move camera from multi touch panning positions.\n * @param previousMultiTouchPanPosition\n * @param multiTouchPanPosition\n */\n _computeMultiTouchPanning(previousMultiTouchPanPosition, multiTouchPanPosition) {\n if (this.panningSensibility !== 0 && previousMultiTouchPanPosition && multiTouchPanPosition) {\n const moveDeltaX = multiTouchPanPosition.x - previousMultiTouchPanPosition.x;\n const moveDeltaY = multiTouchPanPosition.y - previousMultiTouchPanPosition.y;\n this.camera.inertialPanningX += -moveDeltaX / this.panningSensibility;\n this.camera.inertialPanningY += moveDeltaY / this.panningSensibility;\n }\n }\n /**\n * Move camera from pinch zoom distances.\n * @param previousPinchSquaredDistance\n * @param pinchSquaredDistance\n */\n _computePinchZoom(previousPinchSquaredDistance, pinchSquaredDistance) {\n const radius = this.camera.radius || ArcRotateCameraPointersInput.MinimumRadiusForPinch;\n if (this.useNaturalPinchZoom) {\n this.camera.radius = (radius * Math.sqrt(previousPinchSquaredDistance)) / Math.sqrt(pinchSquaredDistance);\n }\n else if (this.pinchDeltaPercentage) {\n this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) * 0.001 * radius * this.pinchDeltaPercentage;\n }\n else {\n this.camera.inertialRadiusOffset +=\n (pinchSquaredDistance - previousPinchSquaredDistance) /\n ((this.pinchPrecision * (this.pinchInwards ? 1 : -1) * (this.angularSensibilityX + this.angularSensibilityY)) / 2);\n }\n }\n /**\n * Called on pointer POINTERMOVE event if only a single touch is active.\n * @param point\n * @param offsetX\n * @param offsetY\n */\n onTouch(point, offsetX, offsetY) {\n if (this.panningSensibility !== 0 && ((this._ctrlKey && this.camera._useCtrlForPanning) || this._isPanClick)) {\n this.camera.inertialPanningX += -offsetX / this.panningSensibility;\n this.camera.inertialPanningY += offsetY / this.panningSensibility;\n }\n else {\n this.camera.inertialAlphaOffset -= offsetX / this.angularSensibilityX;\n this.camera.inertialBetaOffset -= offsetY / this.angularSensibilityY;\n }\n }\n /**\n * Called on pointer POINTERDOUBLETAP event.\n */\n onDoubleTap() {\n if (this.camera.useInputToRestoreState) {\n this.camera.restoreState();\n }\n }\n /**\n * Called on pointer POINTERMOVE event if multiple touches are active.\n * @param pointA\n * @param pointB\n * @param previousPinchSquaredDistance\n * @param pinchSquaredDistance\n * @param previousMultiTouchPanPosition\n * @param multiTouchPanPosition\n */\n onMultiTouch(pointA, pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition) {\n if (previousPinchSquaredDistance === 0 && previousMultiTouchPanPosition === null) {\n // First time this method is called for new pinch.\n // Next time this is called there will be a\n // previousPinchSquaredDistance and pinchSquaredDistance to compare.\n return;\n }\n if (pinchSquaredDistance === 0 && multiTouchPanPosition === null) {\n // Last time this method is called at the end of a pinch.\n return;\n }\n // Zoom and panning enabled together\n if (this.multiTouchPanAndZoom) {\n this._computePinchZoom(previousPinchSquaredDistance, pinchSquaredDistance);\n this._computeMultiTouchPanning(previousMultiTouchPanPosition, multiTouchPanPosition);\n // Zoom and panning enabled but only one at a time\n }\n else if (this.multiTouchPanning && this.pinchZoom) {\n this._twoFingerActivityCount++;\n if (this._isPinching ||\n (this._twoFingerActivityCount < 20 && Math.abs(Math.sqrt(pinchSquaredDistance) - Math.sqrt(previousPinchSquaredDistance)) > this.camera.pinchToPanMaxDistance)) {\n // Since pinch has not been active long, assume we intend to zoom.\n this._computePinchZoom(previousPinchSquaredDistance, pinchSquaredDistance);\n // Since we are pinching, remain pinching on next iteration.\n this._isPinching = true;\n }\n else {\n // Pause between pinch starting and moving implies not a zoom event. Pan instead.\n this._computeMultiTouchPanning(previousMultiTouchPanPosition, multiTouchPanPosition);\n }\n // Panning enabled, zoom disabled\n }\n else if (this.multiTouchPanning) {\n this._computeMultiTouchPanning(previousMultiTouchPanPosition, multiTouchPanPosition);\n // Zoom enabled, panning disabled\n }\n else if (this.pinchZoom) {\n this._computePinchZoom(previousPinchSquaredDistance, pinchSquaredDistance);\n }\n }\n /**\n * Called each time a new POINTERDOWN event occurs. Ie, for each button\n * press.\n * @param evt\n */\n onButtonDown(evt) {\n this._isPanClick = evt.button === this.camera._panningMouseButton;\n }\n /**\n * Called each time a new POINTERUP event occurs. Ie, for each button\n * release.\n */\n onButtonUp() {\n this._twoFingerActivityCount = 0;\n this._isPinching = false;\n }\n /**\n * Called when window becomes inactive.\n */\n onLostFocus() {\n this._isPanClick = false;\n this._twoFingerActivityCount = 0;\n this._isPinching = false;\n }\n}\n/**\n * The minimum radius used for pinch, to avoid radius lock at 0\n */\nArcRotateCameraPointersInput.MinimumRadiusForPinch = 0.001;\n__decorate([\n serialize()\n], ArcRotateCameraPointersInput.prototype, \"buttons\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraPointersInput.prototype, \"angularSensibilityX\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraPointersInput.prototype, \"angularSensibilityY\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraPointersInput.prototype, \"pinchPrecision\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraPointersInput.prototype, \"pinchDeltaPercentage\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraPointersInput.prototype, \"useNaturalPinchZoom\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraPointersInput.prototype, \"pinchZoom\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraPointersInput.prototype, \"panningSensibility\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraPointersInput.prototype, \"multiTouchPanning\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraPointersInput.prototype, \"multiTouchPanAndZoom\", void 0);\nCameraInputTypes[\"ArcRotateCameraPointersInput\"] = ArcRotateCameraPointersInput;\n//# sourceMappingURL=arcRotateCameraPointersInput.js.map","import { ArcRotateCameraPointersInput } from \"../Cameras/Inputs/arcRotateCameraPointersInput.js\";\nimport { ArcRotateCameraKeyboardMoveInput } from \"../Cameras/Inputs/arcRotateCameraKeyboardMoveInput.js\";\nimport { ArcRotateCameraMouseWheelInput } from \"../Cameras/Inputs/arcRotateCameraMouseWheelInput.js\";\nimport { CameraInputsManager } from \"../Cameras/cameraInputsManager.js\";\n/**\n * Default Inputs manager for the ArcRotateCamera.\n * It groups all the default supported inputs for ease of use.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class ArcRotateCameraInputsManager extends CameraInputsManager {\n /**\n * Instantiates a new ArcRotateCameraInputsManager.\n * @param camera Defines the camera the inputs belong to\n */\n constructor(camera) {\n super(camera);\n }\n /**\n * Add mouse wheel input support to the input manager.\n * @returns the current input manager\n */\n addMouseWheel() {\n this.add(new ArcRotateCameraMouseWheelInput());\n return this;\n }\n /**\n * Add pointers input support to the input manager.\n * @returns the current input manager\n */\n addPointers() {\n this.add(new ArcRotateCameraPointersInput());\n return this;\n }\n /**\n * Add keyboard input support to the input manager.\n * @returns the current input manager\n */\n addKeyboard() {\n this.add(new ArcRotateCameraKeyboardMoveInput());\n return this;\n }\n}\n//# sourceMappingURL=arcRotateCameraInputsManager.js.map","import { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { ArcRotateCameraInputsManager } from \"../../Cameras/arcRotateCameraInputsManager.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * Add orientation input support to the input manager.\n * @returns the current input manager\n */\nArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {\n this.add(new ArcRotateCameraVRDeviceOrientationInput());\n return this;\n};\n/**\n * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class ArcRotateCameraVRDeviceOrientationInput {\n /**\n * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.\n */\n constructor() {\n /**\n * Defines a correction factor applied on the alpha value retrieved from the orientation events.\n */\n this.alphaCorrection = 1;\n /**\n * Defines a correction factor applied on the gamma value retrieved from the orientation events.\n */\n this.gammaCorrection = 1;\n this._alpha = 0;\n this._gamma = 0;\n this._dirty = false;\n this._deviceOrientationHandler = this._onOrientationEvent.bind(this);\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(noPreventDefault) {\n // eslint-disable-next-line prefer-rest-params\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n this.camera.attachControl(noPreventDefault);\n const hostWindow = this.camera.getScene().getEngine().getHostWindow();\n if (hostWindow) {\n // check iOS 13+ support\n if (typeof DeviceOrientationEvent !== \"undefined\" && typeof DeviceOrientationEvent.requestPermission === \"function\") {\n DeviceOrientationEvent\n .requestPermission()\n .then((response) => {\n if (response === \"granted\") {\n hostWindow.addEventListener(\"deviceorientation\", this._deviceOrientationHandler);\n }\n else {\n Tools.Warn(\"Permission not granted.\");\n }\n })\n .catch((error) => {\n Tools.Error(error);\n });\n }\n else {\n hostWindow.addEventListener(\"deviceorientation\", this._deviceOrientationHandler);\n }\n }\n }\n /**\n * @internal\n */\n _onOrientationEvent(evt) {\n if (evt.alpha !== null) {\n this._alpha = (+evt.alpha | 0) * this.alphaCorrection;\n }\n if (evt.gamma !== null) {\n this._gamma = (+evt.gamma | 0) * this.gammaCorrection;\n }\n this._dirty = true;\n }\n /**\n * Update the current camera state depending on the inputs that have been used this frame.\n * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.\n */\n checkInputs() {\n if (this._dirty) {\n this._dirty = false;\n if (this._gamma < 0) {\n this._gamma = 180 + this._gamma;\n }\n this.camera.alpha = (((-this._alpha / 180.0) * Math.PI) % Math.PI) * 2;\n this.camera.beta = (this._gamma / 180.0) * Math.PI;\n }\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n window.removeEventListener(\"deviceorientation\", this._deviceOrientationHandler);\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"ArcRotateCameraVRDeviceOrientationInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"VRDeviceOrientation\";\n }\n}\nCameraInputTypes[\"ArcRotateCameraVRDeviceOrientationInput\"] = ArcRotateCameraVRDeviceOrientationInput;\n//# sourceMappingURL=arcRotateCameraVRDeviceOrientationInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { KeyboardEventTypes } from \"../../Events/keyboardEvents.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * Listen to keyboard events to control the camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FlyCameraKeyboardInput {\n constructor() {\n /**\n * The list of keyboard keys used to control the forward move of the camera.\n */\n this.keysForward = [87];\n /**\n * The list of keyboard keys used to control the backward move of the camera.\n */\n this.keysBackward = [83];\n /**\n * The list of keyboard keys used to control the forward move of the camera.\n */\n this.keysUp = [69];\n /**\n * The list of keyboard keys used to control the backward move of the camera.\n */\n this.keysDown = [81];\n /**\n * The list of keyboard keys used to control the right strafe move of the camera.\n */\n this.keysRight = [68];\n /**\n * The list of keyboard keys used to control the left strafe move of the camera.\n */\n this.keysLeft = [65];\n this._keys = new Array();\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(noPreventDefault) {\n // eslint-disable-next-line prefer-rest-params\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n if (this._onCanvasBlurObserver) {\n return;\n }\n this._scene = this.camera.getScene();\n this._engine = this._scene.getEngine();\n this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(() => {\n this._keys.length = 0;\n });\n this._onKeyboardObserver = this._scene.onKeyboardObservable.add((info) => {\n const evt = info.event;\n if (info.type === KeyboardEventTypes.KEYDOWN) {\n if (this.keysForward.indexOf(evt.keyCode) !== -1 ||\n this.keysBackward.indexOf(evt.keyCode) !== -1 ||\n this.keysUp.indexOf(evt.keyCode) !== -1 ||\n this.keysDown.indexOf(evt.keyCode) !== -1 ||\n this.keysLeft.indexOf(evt.keyCode) !== -1 ||\n this.keysRight.indexOf(evt.keyCode) !== -1) {\n const index = this._keys.indexOf(evt.keyCode);\n if (index === -1) {\n this._keys.push(evt.keyCode);\n }\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n }\n else {\n if (this.keysForward.indexOf(evt.keyCode) !== -1 ||\n this.keysBackward.indexOf(evt.keyCode) !== -1 ||\n this.keysUp.indexOf(evt.keyCode) !== -1 ||\n this.keysDown.indexOf(evt.keyCode) !== -1 ||\n this.keysLeft.indexOf(evt.keyCode) !== -1 ||\n this.keysRight.indexOf(evt.keyCode) !== -1) {\n const index = this._keys.indexOf(evt.keyCode);\n if (index >= 0) {\n this._keys.splice(index, 1);\n }\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n }\n });\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n if (this._scene) {\n if (this._onKeyboardObserver) {\n this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);\n }\n if (this._onCanvasBlurObserver) {\n this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);\n }\n this._onKeyboardObserver = null;\n this._onCanvasBlurObserver = null;\n }\n this._keys.length = 0;\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"FlyCameraKeyboardInput\";\n }\n /**\n * @internal\n */\n _onLostFocus() {\n this._keys.length = 0;\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"keyboard\";\n }\n /**\n * Update the current camera state depending on the inputs that have been used this frame.\n * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.\n */\n checkInputs() {\n if (this._onKeyboardObserver) {\n const camera = this.camera;\n // Keyboard\n for (let index = 0; index < this._keys.length; index++) {\n const keyCode = this._keys[index];\n const speed = camera._computeLocalCameraSpeed();\n if (this.keysForward.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, 0, speed);\n }\n else if (this.keysBackward.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, 0, -speed);\n }\n else if (this.keysUp.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, speed, 0);\n }\n else if (this.keysDown.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, -speed, 0);\n }\n else if (this.keysRight.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(speed, 0, 0);\n }\n else if (this.keysLeft.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(-speed, 0, 0);\n }\n if (camera.getScene().useRightHandedSystem) {\n camera._localDirection.z *= -1;\n }\n camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);\n Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);\n camera.cameraDirection.addInPlace(camera._transformedDirection);\n }\n }\n }\n}\n__decorate([\n serialize()\n], FlyCameraKeyboardInput.prototype, \"keysForward\", void 0);\n__decorate([\n serialize()\n], FlyCameraKeyboardInput.prototype, \"keysBackward\", void 0);\n__decorate([\n serialize()\n], FlyCameraKeyboardInput.prototype, \"keysUp\", void 0);\n__decorate([\n serialize()\n], FlyCameraKeyboardInput.prototype, \"keysDown\", void 0);\n__decorate([\n serialize()\n], FlyCameraKeyboardInput.prototype, \"keysRight\", void 0);\n__decorate([\n serialize()\n], FlyCameraKeyboardInput.prototype, \"keysLeft\", void 0);\nCameraInputTypes[\"FlyCameraKeyboardInput\"] = FlyCameraKeyboardInput;\n//# sourceMappingURL=flyCameraKeyboardInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { PointerEventTypes } from \"../../Events/pointerEvents.js\";\nimport { Quaternion } from \"../../Maths/math.vector.js\";\nimport { Axis } from \"../../Maths/math.axis.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * Listen to mouse events to control the camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FlyCameraMouseInput {\n /**\n * Listen to mouse events to control the camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\n constructor() {\n /**\n * Defines the buttons associated with the input to handle camera rotation.\n */\n this.buttons = [0, 1, 2];\n /**\n * Assign buttons for Yaw control.\n */\n this.buttonsYaw = [-1, 0, 1];\n /**\n * Assign buttons for Pitch control.\n */\n this.buttonsPitch = [-1, 0, 1];\n /**\n * Assign buttons for Roll control.\n */\n this.buttonsRoll = [2];\n /**\n * Detect if any button is being pressed while mouse is moved.\n * -1 = Mouse locked.\n * 0 = Left button.\n * 1 = Middle Button.\n * 2 = Right Button.\n */\n this.activeButton = -1;\n /**\n * Defines the pointer's angular sensibility, to control the camera rotation speed.\n * Higher values reduce its sensitivity.\n */\n this.angularSensibility = 1000.0;\n this._previousPosition = null;\n }\n /**\n * Attach the mouse control to the HTML DOM element.\n * @param noPreventDefault Defines whether events caught by the controls should call preventdefault().\n */\n attachControl(noPreventDefault) {\n // eslint-disable-next-line prefer-rest-params\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n this._noPreventDefault = noPreventDefault;\n this._observer = this.camera.getScene()._inputManager._addCameraPointerObserver((p) => {\n this._pointerInput(p);\n }, PointerEventTypes.POINTERDOWN | PointerEventTypes.POINTERUP | PointerEventTypes.POINTERMOVE);\n // Correct Roll by rate, if enabled.\n this._rollObserver = this.camera.getScene().onBeforeRenderObservable.add(() => {\n if (this.camera.rollCorrect) {\n this.camera.restoreRoll(this.camera.rollCorrect);\n }\n });\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n if (this._observer) {\n this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer);\n this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver);\n this._observer = null;\n this._rollObserver = null;\n this._previousPosition = null;\n this._noPreventDefault = undefined;\n }\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name.\n */\n getClassName() {\n return \"FlyCameraMouseInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input's friendly name.\n */\n getSimpleName() {\n return \"mouse\";\n }\n // Track mouse movement, when the pointer is not locked.\n _pointerInput(p) {\n const e = p.event;\n const camera = this.camera;\n const engine = camera.getEngine();\n if (engine.isInVRExclusivePointerMode) {\n return;\n }\n if (!this.touchEnabled && e.pointerType === \"touch\") {\n return;\n }\n // Mouse is moved but an unknown mouse button is pressed.\n if (p.type !== PointerEventTypes.POINTERMOVE && this.buttons.indexOf(e.button) === -1) {\n return;\n }\n const srcElement = e.target;\n // Mouse down.\n if (p.type === PointerEventTypes.POINTERDOWN) {\n try {\n srcElement === null || srcElement === void 0 ? void 0 : srcElement.setPointerCapture(e.pointerId);\n }\n catch (e) {\n // Nothing to do with the error. Execution continues.\n }\n this._previousPosition = {\n x: e.clientX,\n y: e.clientY,\n };\n this.activeButton = e.button;\n if (!this._noPreventDefault) {\n e.preventDefault();\n this._element.focus();\n }\n // This is required to move while pointer button is down\n if (engine.isPointerLock) {\n this._onMouseMove(p.event);\n }\n }\n // Mouse up.\n else if (p.type === PointerEventTypes.POINTERUP) {\n try {\n srcElement === null || srcElement === void 0 ? void 0 : srcElement.releasePointerCapture(e.pointerId);\n }\n catch (e) {\n // Nothing to do with the error. Execution continues.\n }\n this.activeButton = -1;\n this._previousPosition = null;\n if (!this._noPreventDefault) {\n e.preventDefault();\n }\n }\n // Mouse move.\n else if (p.type === PointerEventTypes.POINTERMOVE) {\n if (!this._previousPosition) {\n if (engine.isPointerLock) {\n this._onMouseMove(p.event);\n }\n return;\n }\n const offsetX = e.clientX - this._previousPosition.x;\n const offsetY = e.clientY - this._previousPosition.y;\n this._rotateCamera(offsetX, offsetY);\n this._previousPosition = {\n x: e.clientX,\n y: e.clientY,\n };\n if (!this._noPreventDefault) {\n e.preventDefault();\n }\n }\n }\n // Track mouse movement, when pointer is locked.\n _onMouseMove(e) {\n const camera = this.camera;\n const engine = camera.getEngine();\n if (!engine.isPointerLock || engine.isInVRExclusivePointerMode) {\n return;\n }\n const offsetX = e.movementX;\n const offsetY = e.movementY;\n this._rotateCamera(offsetX, offsetY);\n this._previousPosition = null;\n if (!this._noPreventDefault) {\n e.preventDefault();\n }\n }\n /**\n * Rotate camera by mouse offset.\n * @param offsetX\n * @param offsetY\n */\n _rotateCamera(offsetX, offsetY) {\n const camera = this.camera;\n const scene = this.camera.getScene();\n if (scene.useRightHandedSystem) {\n offsetX *= -1;\n }\n if (camera.parent && camera.parent._getWorldMatrixDeterminant() < 0) {\n offsetX *= -1;\n }\n const x = offsetX / this.angularSensibility;\n const y = offsetY / this.angularSensibility;\n // Initialize to current rotation.\n const currentRotation = Quaternion.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, camera.rotation.z);\n let rotationChange;\n // Pitch.\n if (this.buttonsPitch.some((v) => {\n return v === this.activeButton;\n })) {\n // Apply change in Radians to vector Angle.\n rotationChange = Quaternion.RotationAxis(Axis.X, y);\n // Apply Pitch to quaternion.\n currentRotation.multiplyInPlace(rotationChange);\n }\n // Yaw.\n if (this.buttonsYaw.some((v) => {\n return v === this.activeButton;\n })) {\n // Apply change in Radians to vector Angle.\n rotationChange = Quaternion.RotationAxis(Axis.Y, x);\n // Apply Yaw to quaternion.\n currentRotation.multiplyInPlace(rotationChange);\n // Add Roll, if banked turning is enabled, within Roll limit.\n const limit = camera.bankedTurnLimit + camera._trackRoll; // Defaults to 90° plus manual roll.\n if (camera.bankedTurn && -limit < camera.rotation.z && camera.rotation.z < limit) {\n const bankingDelta = camera.bankedTurnMultiplier * -x;\n // Apply change in Radians to vector Angle.\n rotationChange = Quaternion.RotationAxis(Axis.Z, bankingDelta);\n // Apply Yaw to quaternion.\n currentRotation.multiplyInPlace(rotationChange);\n }\n }\n // Roll.\n if (this.buttonsRoll.some((v) => {\n return v === this.activeButton;\n })) {\n // Apply change in Radians to vector Angle.\n rotationChange = Quaternion.RotationAxis(Axis.Z, -x);\n // Track Rolling.\n camera._trackRoll -= x;\n // Apply Pitch to quaternion.\n currentRotation.multiplyInPlace(rotationChange);\n }\n // Apply rotationQuaternion to Euler camera.rotation.\n currentRotation.toEulerAnglesToRef(camera.rotation);\n }\n}\n__decorate([\n serialize()\n], FlyCameraMouseInput.prototype, \"buttons\", void 0);\n__decorate([\n serialize()\n], FlyCameraMouseInput.prototype, \"angularSensibility\", void 0);\nCameraInputTypes[\"FlyCameraMouseInput\"] = FlyCameraMouseInput;\n//# sourceMappingURL=flyCameraMouseInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { KeyboardEventTypes } from \"../../Events/keyboardEvents.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * Manage the keyboard inputs to control the movement of a follow camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FollowCameraKeyboardMoveInput {\n constructor() {\n /**\n * Defines the list of key codes associated with the up action (increase heightOffset)\n */\n this.keysHeightOffsetIncr = [38];\n /**\n * Defines the list of key codes associated with the down action (decrease heightOffset)\n */\n this.keysHeightOffsetDecr = [40];\n /**\n * Defines whether the Alt modifier key is required to move up/down (alter heightOffset)\n */\n this.keysHeightOffsetModifierAlt = false;\n /**\n * Defines whether the Ctrl modifier key is required to move up/down (alter heightOffset)\n */\n this.keysHeightOffsetModifierCtrl = false;\n /**\n * Defines whether the Shift modifier key is required to move up/down (alter heightOffset)\n */\n this.keysHeightOffsetModifierShift = false;\n /**\n * Defines the list of key codes associated with the left action (increase rotationOffset)\n */\n this.keysRotationOffsetIncr = [37];\n /**\n * Defines the list of key codes associated with the right action (decrease rotationOffset)\n */\n this.keysRotationOffsetDecr = [39];\n /**\n * Defines whether the Alt modifier key is required to move left/right (alter rotationOffset)\n */\n this.keysRotationOffsetModifierAlt = false;\n /**\n * Defines whether the Ctrl modifier key is required to move left/right (alter rotationOffset)\n */\n this.keysRotationOffsetModifierCtrl = false;\n /**\n * Defines whether the Shift modifier key is required to move left/right (alter rotationOffset)\n */\n this.keysRotationOffsetModifierShift = false;\n /**\n * Defines the list of key codes associated with the zoom-in action (decrease radius)\n */\n this.keysRadiusIncr = [40];\n /**\n * Defines the list of key codes associated with the zoom-out action (increase radius)\n */\n this.keysRadiusDecr = [38];\n /**\n * Defines whether the Alt modifier key is required to zoom in/out (alter radius value)\n */\n this.keysRadiusModifierAlt = true;\n /**\n * Defines whether the Ctrl modifier key is required to zoom in/out (alter radius value)\n */\n this.keysRadiusModifierCtrl = false;\n /**\n * Defines whether the Shift modifier key is required to zoom in/out (alter radius value)\n */\n this.keysRadiusModifierShift = false;\n /**\n * Defines the rate of change of heightOffset.\n */\n this.heightSensibility = 1;\n /**\n * Defines the rate of change of rotationOffset.\n */\n this.rotationSensibility = 1;\n /**\n * Defines the rate of change of radius.\n */\n this.radiusSensibility = 1;\n this._keys = new Array();\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(noPreventDefault) {\n // eslint-disable-next-line prefer-rest-params\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n if (this._onCanvasBlurObserver) {\n return;\n }\n this._scene = this.camera.getScene();\n this._engine = this._scene.getEngine();\n this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(() => {\n this._keys.length = 0;\n });\n this._onKeyboardObserver = this._scene.onKeyboardObservable.add((info) => {\n const evt = info.event;\n if (!evt.metaKey) {\n if (info.type === KeyboardEventTypes.KEYDOWN) {\n this._ctrlPressed = evt.ctrlKey;\n this._altPressed = evt.altKey;\n this._shiftPressed = evt.shiftKey;\n if (this.keysHeightOffsetIncr.indexOf(evt.keyCode) !== -1 ||\n this.keysHeightOffsetDecr.indexOf(evt.keyCode) !== -1 ||\n this.keysRotationOffsetIncr.indexOf(evt.keyCode) !== -1 ||\n this.keysRotationOffsetDecr.indexOf(evt.keyCode) !== -1 ||\n this.keysRadiusIncr.indexOf(evt.keyCode) !== -1 ||\n this.keysRadiusDecr.indexOf(evt.keyCode) !== -1) {\n const index = this._keys.indexOf(evt.keyCode);\n if (index === -1) {\n this._keys.push(evt.keyCode);\n }\n if (evt.preventDefault) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n }\n }\n else {\n if (this.keysHeightOffsetIncr.indexOf(evt.keyCode) !== -1 ||\n this.keysHeightOffsetDecr.indexOf(evt.keyCode) !== -1 ||\n this.keysRotationOffsetIncr.indexOf(evt.keyCode) !== -1 ||\n this.keysRotationOffsetDecr.indexOf(evt.keyCode) !== -1 ||\n this.keysRadiusIncr.indexOf(evt.keyCode) !== -1 ||\n this.keysRadiusDecr.indexOf(evt.keyCode) !== -1) {\n const index = this._keys.indexOf(evt.keyCode);\n if (index >= 0) {\n this._keys.splice(index, 1);\n }\n if (evt.preventDefault) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n }\n }\n }\n });\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n if (this._scene) {\n if (this._onKeyboardObserver) {\n this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);\n }\n if (this._onCanvasBlurObserver) {\n this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);\n }\n this._onKeyboardObserver = null;\n this._onCanvasBlurObserver = null;\n }\n this._keys.length = 0;\n }\n /**\n * Update the current camera state depending on the inputs that have been used this frame.\n * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.\n */\n checkInputs() {\n if (this._onKeyboardObserver) {\n this._keys.forEach((keyCode) => {\n if (this.keysHeightOffsetIncr.indexOf(keyCode) !== -1 && this._modifierHeightOffset()) {\n this.camera.heightOffset += this.heightSensibility;\n }\n else if (this.keysHeightOffsetDecr.indexOf(keyCode) !== -1 && this._modifierHeightOffset()) {\n this.camera.heightOffset -= this.heightSensibility;\n }\n else if (this.keysRotationOffsetIncr.indexOf(keyCode) !== -1 && this._modifierRotationOffset()) {\n this.camera.rotationOffset += this.rotationSensibility;\n this.camera.rotationOffset %= 360;\n }\n else if (this.keysRotationOffsetDecr.indexOf(keyCode) !== -1 && this._modifierRotationOffset()) {\n this.camera.rotationOffset -= this.rotationSensibility;\n this.camera.rotationOffset %= 360;\n }\n else if (this.keysRadiusIncr.indexOf(keyCode) !== -1 && this._modifierRadius()) {\n this.camera.radius += this.radiusSensibility;\n }\n else if (this.keysRadiusDecr.indexOf(keyCode) !== -1 && this._modifierRadius()) {\n this.camera.radius -= this.radiusSensibility;\n }\n });\n }\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"FollowCameraKeyboardMoveInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"keyboard\";\n }\n /**\n * Check if the pressed modifier keys (Alt/Ctrl/Shift) match those configured to\n * allow modification of the heightOffset value.\n */\n _modifierHeightOffset() {\n return (this.keysHeightOffsetModifierAlt === this._altPressed &&\n this.keysHeightOffsetModifierCtrl === this._ctrlPressed &&\n this.keysHeightOffsetModifierShift === this._shiftPressed);\n }\n /**\n * Check if the pressed modifier keys (Alt/Ctrl/Shift) match those configured to\n * allow modification of the rotationOffset value.\n */\n _modifierRotationOffset() {\n return (this.keysRotationOffsetModifierAlt === this._altPressed &&\n this.keysRotationOffsetModifierCtrl === this._ctrlPressed &&\n this.keysRotationOffsetModifierShift === this._shiftPressed);\n }\n /**\n * Check if the pressed modifier keys (Alt/Ctrl/Shift) match those configured to\n * allow modification of the radius value.\n */\n _modifierRadius() {\n return this.keysRadiusModifierAlt === this._altPressed && this.keysRadiusModifierCtrl === this._ctrlPressed && this.keysRadiusModifierShift === this._shiftPressed;\n }\n}\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysHeightOffsetIncr\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysHeightOffsetDecr\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysHeightOffsetModifierAlt\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysHeightOffsetModifierCtrl\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysHeightOffsetModifierShift\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysRotationOffsetIncr\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysRotationOffsetDecr\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysRotationOffsetModifierAlt\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysRotationOffsetModifierCtrl\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysRotationOffsetModifierShift\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysRadiusIncr\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysRadiusDecr\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysRadiusModifierAlt\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysRadiusModifierCtrl\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysRadiusModifierShift\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"heightSensibility\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"rotationSensibility\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"radiusSensibility\", void 0);\nCameraInputTypes[\"FollowCameraKeyboardMoveInput\"] = FollowCameraKeyboardMoveInput;\n//# sourceMappingURL=followCameraKeyboardMoveInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { PointerEventTypes } from \"../../Events/pointerEvents.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * Manage the mouse wheel inputs to control a follow camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FollowCameraMouseWheelInput {\n constructor() {\n /**\n * Moue wheel controls zoom. (Mouse wheel modifies camera.radius value.)\n */\n this.axisControlRadius = true;\n /**\n * Moue wheel controls height. (Mouse wheel modifies camera.heightOffset value.)\n */\n this.axisControlHeight = false;\n /**\n * Moue wheel controls angle. (Mouse wheel modifies camera.rotationOffset value.)\n */\n this.axisControlRotation = false;\n /**\n * Gets or Set the mouse wheel precision or how fast is the camera moves in\n * relation to mouseWheel events.\n */\n this.wheelPrecision = 3.0;\n /**\n * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.\n * It defines the percentage of current camera.radius to use as delta when wheel is used.\n */\n this.wheelDeltaPercentage = 0;\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(noPreventDefault) {\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n this._wheel = (p) => {\n // sanity check - this should be a PointerWheel event.\n if (p.type !== PointerEventTypes.POINTERWHEEL) {\n return;\n }\n const event = p.event;\n let delta = 0;\n const wheelDelta = Math.max(-1, Math.min(1, event.deltaY));\n if (this.wheelDeltaPercentage) {\n console.assert(this.axisControlRadius + this.axisControlHeight + this.axisControlRotation <= 1, \"wheelDeltaPercentage only usable when mouse wheel \" +\n \"controls ONE axis. \" +\n \"Currently enabled: \" +\n \"axisControlRadius: \" +\n this.axisControlRadius +\n \", axisControlHeightOffset: \" +\n this.axisControlHeight +\n \", axisControlRotationOffset: \" +\n this.axisControlRotation);\n if (this.axisControlRadius) {\n delta = wheelDelta * 0.01 * this.wheelDeltaPercentage * this.camera.radius;\n }\n else if (this.axisControlHeight) {\n delta = wheelDelta * 0.01 * this.wheelDeltaPercentage * this.camera.heightOffset;\n }\n else if (this.axisControlRotation) {\n delta = wheelDelta * 0.01 * this.wheelDeltaPercentage * this.camera.rotationOffset;\n }\n }\n else {\n delta = wheelDelta * this.wheelPrecision;\n }\n if (delta) {\n if (this.axisControlRadius) {\n this.camera.radius += delta;\n }\n else if (this.axisControlHeight) {\n this.camera.heightOffset -= delta;\n }\n else if (this.axisControlRotation) {\n this.camera.rotationOffset -= delta;\n }\n }\n if (event.preventDefault) {\n if (!noPreventDefault) {\n event.preventDefault();\n }\n }\n };\n this._observer = this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel, PointerEventTypes.POINTERWHEEL);\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n if (this._observer) {\n this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer);\n this._observer = null;\n this._wheel = null;\n }\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"ArcRotateCameraMouseWheelInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"mousewheel\";\n }\n}\n__decorate([\n serialize()\n], FollowCameraMouseWheelInput.prototype, \"axisControlRadius\", void 0);\n__decorate([\n serialize()\n], FollowCameraMouseWheelInput.prototype, \"axisControlHeight\", void 0);\n__decorate([\n serialize()\n], FollowCameraMouseWheelInput.prototype, \"axisControlRotation\", void 0);\n__decorate([\n serialize()\n], FollowCameraMouseWheelInput.prototype, \"wheelPrecision\", void 0);\n__decorate([\n serialize()\n], FollowCameraMouseWheelInput.prototype, \"wheelDeltaPercentage\", void 0);\nCameraInputTypes[\"FollowCameraMouseWheelInput\"] = FollowCameraMouseWheelInput;\n//# sourceMappingURL=followCameraMouseWheelInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { BaseCameraPointersInput } from \"../../Cameras/Inputs/BaseCameraPointersInput.js\";\n/**\n * Manage the pointers inputs to control an follow camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FollowCameraPointersInput extends BaseCameraPointersInput {\n constructor() {\n super(...arguments);\n /**\n * Defines the pointer angular sensibility along the X axis or how fast is\n * the camera rotating.\n * A negative number will reverse the axis direction.\n */\n this.angularSensibilityX = 1;\n /**\n * Defines the pointer angular sensibility along the Y axis or how fast is\n * the camera rotating.\n * A negative number will reverse the axis direction.\n */\n this.angularSensibilityY = 1;\n /**\n * Defines the pointer pinch precision or how fast is the camera zooming.\n * A negative number will reverse the axis direction.\n */\n this.pinchPrecision = 10000.0;\n /**\n * pinchDeltaPercentage will be used instead of pinchPrecision if different\n * from 0.\n * It defines the percentage of current camera.radius to use as delta when\n * pinch zoom is used.\n */\n this.pinchDeltaPercentage = 0;\n /**\n * Pointer X axis controls zoom. (X axis modifies camera.radius value.)\n */\n this.axisXControlRadius = false;\n /**\n * Pointer X axis controls height. (X axis modifies camera.heightOffset value.)\n */\n this.axisXControlHeight = false;\n /**\n * Pointer X axis controls angle. (X axis modifies camera.rotationOffset value.)\n */\n this.axisXControlRotation = true;\n /**\n * Pointer Y axis controls zoom. (Y axis modifies camera.radius value.)\n */\n this.axisYControlRadius = false;\n /**\n * Pointer Y axis controls height. (Y axis modifies camera.heightOffset value.)\n */\n this.axisYControlHeight = true;\n /**\n * Pointer Y axis controls angle. (Y axis modifies camera.rotationOffset value.)\n */\n this.axisYControlRotation = false;\n /**\n * Pinch controls zoom. (Pinch modifies camera.radius value.)\n */\n this.axisPinchControlRadius = true;\n /**\n * Pinch controls height. (Pinch modifies camera.heightOffset value.)\n */\n this.axisPinchControlHeight = false;\n /**\n * Pinch controls angle. (Pinch modifies camera.rotationOffset value.)\n */\n this.axisPinchControlRotation = false;\n /**\n * Log error messages if basic misconfiguration has occurred.\n */\n this.warningEnable = true;\n /* Check for obvious misconfiguration. */\n this._warningCounter = 0;\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"FollowCameraPointersInput\";\n }\n onTouch(pointA, offsetX, offsetY) {\n this._warning();\n if (this.axisXControlRotation) {\n this.camera.rotationOffset += offsetX / this.angularSensibilityX;\n }\n else if (this.axisYControlRotation) {\n this.camera.rotationOffset += offsetY / this.angularSensibilityX;\n }\n if (this.axisXControlHeight) {\n this.camera.heightOffset += offsetX / this.angularSensibilityY;\n }\n else if (this.axisYControlHeight) {\n this.camera.heightOffset += offsetY / this.angularSensibilityY;\n }\n if (this.axisXControlRadius) {\n this.camera.radius -= offsetX / this.angularSensibilityY;\n }\n else if (this.axisYControlRadius) {\n this.camera.radius -= offsetY / this.angularSensibilityY;\n }\n }\n onMultiTouch(pointA, pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition) {\n if (previousPinchSquaredDistance === 0 && previousMultiTouchPanPosition === null) {\n // First time this method is called for new pinch.\n // Next time this is called there will be a\n // previousPinchSquaredDistance and pinchSquaredDistance to compare.\n return;\n }\n if (pinchSquaredDistance === 0 && multiTouchPanPosition === null) {\n // Last time this method is called at the end of a pinch.\n return;\n }\n let pinchDelta = (pinchSquaredDistance - previousPinchSquaredDistance) / ((this.pinchPrecision * (this.angularSensibilityX + this.angularSensibilityY)) / 2);\n if (this.pinchDeltaPercentage) {\n pinchDelta *= 0.01 * this.pinchDeltaPercentage;\n if (this.axisPinchControlRotation) {\n this.camera.rotationOffset += pinchDelta * this.camera.rotationOffset;\n }\n if (this.axisPinchControlHeight) {\n this.camera.heightOffset += pinchDelta * this.camera.heightOffset;\n }\n if (this.axisPinchControlRadius) {\n this.camera.radius -= pinchDelta * this.camera.radius;\n }\n }\n else {\n if (this.axisPinchControlRotation) {\n this.camera.rotationOffset += pinchDelta;\n }\n if (this.axisPinchControlHeight) {\n this.camera.heightOffset += pinchDelta;\n }\n if (this.axisPinchControlRadius) {\n this.camera.radius -= pinchDelta;\n }\n }\n }\n _warning() {\n if (!this.warningEnable || this._warningCounter++ % 100 !== 0) {\n return;\n }\n const warn = \"It probably only makes sense to control ONE camera \" + \"property with each pointer axis. Set 'warningEnable = false' \" + \"if you are sure. Currently enabled: \";\n console.assert(this.axisXControlRotation + this.axisXControlHeight + this.axisXControlRadius <= 1, warn + \"axisXControlRotation: \" + this.axisXControlRotation + \", axisXControlHeight: \" + this.axisXControlHeight + \", axisXControlRadius: \" + this.axisXControlRadius);\n console.assert(this.axisYControlRotation + this.axisYControlHeight + this.axisYControlRadius <= 1, warn + \"axisYControlRotation: \" + this.axisYControlRotation + \", axisYControlHeight: \" + this.axisYControlHeight + \", axisYControlRadius: \" + this.axisYControlRadius);\n console.assert(this.axisPinchControlRotation + this.axisPinchControlHeight + this.axisPinchControlRadius <= 1, warn +\n \"axisPinchControlRotation: \" +\n this.axisPinchControlRotation +\n \", axisPinchControlHeight: \" +\n this.axisPinchControlHeight +\n \", axisPinchControlRadius: \" +\n this.axisPinchControlRadius);\n }\n}\n__decorate([\n serialize()\n], FollowCameraPointersInput.prototype, \"angularSensibilityX\", void 0);\n__decorate([\n serialize()\n], FollowCameraPointersInput.prototype, \"angularSensibilityY\", void 0);\n__decorate([\n serialize()\n], FollowCameraPointersInput.prototype, \"pinchPrecision\", void 0);\n__decorate([\n serialize()\n], FollowCameraPointersInput.prototype, \"pinchDeltaPercentage\", void 0);\n__decorate([\n serialize()\n], FollowCameraPointersInput.prototype, \"axisXControlRadius\", void 0);\n__decorate([\n serialize()\n], FollowCameraPointersInput.prototype, \"axisXControlHeight\", void 0);\n__decorate([\n serialize()\n], FollowCameraPointersInput.prototype, \"axisXControlRotation\", void 0);\n__decorate([\n serialize()\n], FollowCameraPointersInput.prototype, \"axisYControlRadius\", void 0);\n__decorate([\n serialize()\n], FollowCameraPointersInput.prototype, \"axisYControlHeight\", void 0);\n__decorate([\n serialize()\n], FollowCameraPointersInput.prototype, \"axisYControlRotation\", void 0);\n__decorate([\n serialize()\n], FollowCameraPointersInput.prototype, \"axisPinchControlRadius\", void 0);\n__decorate([\n serialize()\n], FollowCameraPointersInput.prototype, \"axisPinchControlHeight\", void 0);\n__decorate([\n serialize()\n], FollowCameraPointersInput.prototype, \"axisPinchControlRotation\", void 0);\nCameraInputTypes[\"FollowCameraPointersInput\"] = FollowCameraPointersInput;\n//# sourceMappingURL=followCameraPointersInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { KeyboardEventTypes } from \"../../Events/keyboardEvents.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * Manage the keyboard inputs to control the movement of a free camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FreeCameraKeyboardMoveInput {\n constructor() {\n /**\n * Gets or Set the list of keyboard keys used to control the forward move of the camera.\n */\n this.keysUp = [38];\n /**\n * Gets or Set the list of keyboard keys used to control the upward move of the camera.\n */\n this.keysUpward = [33];\n /**\n * Gets or Set the list of keyboard keys used to control the backward move of the camera.\n */\n this.keysDown = [40];\n /**\n * Gets or Set the list of keyboard keys used to control the downward move of the camera.\n */\n this.keysDownward = [34];\n /**\n * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.\n */\n this.keysLeft = [37];\n /**\n * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.\n */\n this.keysRight = [39];\n /**\n * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.\n */\n this.rotationSpeed = 0.5;\n /**\n * Gets or Set the list of keyboard keys used to control the left rotation move of the camera.\n */\n this.keysRotateLeft = [];\n /**\n * Gets or Set the list of keyboard keys used to control the right rotation move of the camera.\n */\n this.keysRotateRight = [];\n /**\n * Gets or Set the list of keyboard keys used to control the up rotation move of the camera.\n */\n this.keysRotateUp = [];\n /**\n * Gets or Set the list of keyboard keys used to control the down rotation move of the camera.\n */\n this.keysRotateDown = [];\n this._keys = new Array();\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(noPreventDefault) {\n // eslint-disable-next-line prefer-rest-params\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n if (this._onCanvasBlurObserver) {\n return;\n }\n this._scene = this.camera.getScene();\n this._engine = this._scene.getEngine();\n this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(() => {\n this._keys.length = 0;\n });\n this._onKeyboardObserver = this._scene.onKeyboardObservable.add((info) => {\n const evt = info.event;\n if (!evt.metaKey) {\n if (info.type === KeyboardEventTypes.KEYDOWN) {\n if (this.keysUp.indexOf(evt.keyCode) !== -1 ||\n this.keysDown.indexOf(evt.keyCode) !== -1 ||\n this.keysLeft.indexOf(evt.keyCode) !== -1 ||\n this.keysRight.indexOf(evt.keyCode) !== -1 ||\n this.keysUpward.indexOf(evt.keyCode) !== -1 ||\n this.keysDownward.indexOf(evt.keyCode) !== -1 ||\n this.keysRotateLeft.indexOf(evt.keyCode) !== -1 ||\n this.keysRotateRight.indexOf(evt.keyCode) !== -1 ||\n this.keysRotateUp.indexOf(evt.keyCode) !== -1 ||\n this.keysRotateDown.indexOf(evt.keyCode) !== -1) {\n const index = this._keys.indexOf(evt.keyCode);\n if (index === -1) {\n this._keys.push(evt.keyCode);\n }\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n }\n else {\n if (this.keysUp.indexOf(evt.keyCode) !== -1 ||\n this.keysDown.indexOf(evt.keyCode) !== -1 ||\n this.keysLeft.indexOf(evt.keyCode) !== -1 ||\n this.keysRight.indexOf(evt.keyCode) !== -1 ||\n this.keysUpward.indexOf(evt.keyCode) !== -1 ||\n this.keysDownward.indexOf(evt.keyCode) !== -1 ||\n this.keysRotateLeft.indexOf(evt.keyCode) !== -1 ||\n this.keysRotateRight.indexOf(evt.keyCode) !== -1 ||\n this.keysRotateUp.indexOf(evt.keyCode) !== -1 ||\n this.keysRotateDown.indexOf(evt.keyCode) !== -1) {\n const index = this._keys.indexOf(evt.keyCode);\n if (index >= 0) {\n this._keys.splice(index, 1);\n }\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n }\n }\n });\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n if (this._scene) {\n if (this._onKeyboardObserver) {\n this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);\n }\n if (this._onCanvasBlurObserver) {\n this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);\n }\n this._onKeyboardObserver = null;\n this._onCanvasBlurObserver = null;\n }\n this._keys.length = 0;\n }\n /**\n * Update the current camera state depending on the inputs that have been used this frame.\n * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.\n */\n checkInputs() {\n if (this._onKeyboardObserver) {\n const camera = this.camera;\n // Keyboard\n for (let index = 0; index < this._keys.length; index++) {\n const keyCode = this._keys[index];\n const speed = camera._computeLocalCameraSpeed();\n if (this.keysLeft.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(-speed, 0, 0);\n }\n else if (this.keysUp.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, 0, speed);\n }\n else if (this.keysRight.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(speed, 0, 0);\n }\n else if (this.keysDown.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, 0, -speed);\n }\n else if (this.keysUpward.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, speed, 0);\n }\n else if (this.keysDownward.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, -speed, 0);\n }\n else if (this.keysRotateLeft.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, 0, 0);\n camera.cameraRotation.y -= this._getLocalRotation();\n }\n else if (this.keysRotateRight.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, 0, 0);\n camera.cameraRotation.y += this._getLocalRotation();\n }\n else if (this.keysRotateUp.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, 0, 0);\n camera.cameraRotation.x -= this._getLocalRotation();\n }\n else if (this.keysRotateDown.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, 0, 0);\n camera.cameraRotation.x += this._getLocalRotation();\n }\n if (camera.getScene().useRightHandedSystem) {\n camera._localDirection.z *= -1;\n }\n camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);\n Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);\n camera.cameraDirection.addInPlace(camera._transformedDirection);\n }\n }\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"FreeCameraKeyboardMoveInput\";\n }\n /** @internal */\n _onLostFocus() {\n this._keys.length = 0;\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"keyboard\";\n }\n _getLocalRotation() {\n let rotation = (this.rotationSpeed * this._engine.getDeltaTime()) / 1000;\n if (this.camera.getScene().useRightHandedSystem) {\n rotation *= -1;\n }\n if (this.camera.parent && this.camera.parent._getWorldMatrixDeterminant() < 0) {\n rotation *= -1;\n }\n return rotation;\n }\n}\n__decorate([\n serialize()\n], FreeCameraKeyboardMoveInput.prototype, \"keysUp\", void 0);\n__decorate([\n serialize()\n], FreeCameraKeyboardMoveInput.prototype, \"keysUpward\", void 0);\n__decorate([\n serialize()\n], FreeCameraKeyboardMoveInput.prototype, \"keysDown\", void 0);\n__decorate([\n serialize()\n], FreeCameraKeyboardMoveInput.prototype, \"keysDownward\", void 0);\n__decorate([\n serialize()\n], FreeCameraKeyboardMoveInput.prototype, \"keysLeft\", void 0);\n__decorate([\n serialize()\n], FreeCameraKeyboardMoveInput.prototype, \"keysRight\", void 0);\n__decorate([\n serialize()\n], FreeCameraKeyboardMoveInput.prototype, \"rotationSpeed\", void 0);\n__decorate([\n serialize()\n], FreeCameraKeyboardMoveInput.prototype, \"keysRotateLeft\", void 0);\n__decorate([\n serialize()\n], FreeCameraKeyboardMoveInput.prototype, \"keysRotateRight\", void 0);\n__decorate([\n serialize()\n], FreeCameraKeyboardMoveInput.prototype, \"keysRotateUp\", void 0);\n__decorate([\n serialize()\n], FreeCameraKeyboardMoveInput.prototype, \"keysRotateDown\", void 0);\nCameraInputTypes[\"FreeCameraKeyboardMoveInput\"] = FreeCameraKeyboardMoveInput;\n//# sourceMappingURL=freeCameraKeyboardMoveInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { PointerEventTypes } from \"../../Events/pointerEvents.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * Manage the mouse inputs to control the movement of a free camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FreeCameraMouseInput {\n /**\n * Manage the mouse inputs to control the movement of a free camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n * @param touchEnabled Defines if touch is enabled or not\n */\n constructor(\n /**\n * Define if touch is enabled in the mouse input\n */\n touchEnabled = true) {\n this.touchEnabled = touchEnabled;\n /**\n * Defines the buttons associated with the input to handle camera move.\n */\n this.buttons = [0, 1, 2];\n /**\n * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.\n */\n this.angularSensibility = 2000.0;\n this._previousPosition = null;\n /**\n * Observable for when a pointer move event occurs containing the move offset\n */\n this.onPointerMovedObservable = new Observable();\n /**\n * @internal\n * If the camera should be rotated automatically based on pointer movement\n */\n this._allowCameraRotation = true;\n this._currentActiveButton = -1;\n this._activePointerId = -1;\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(noPreventDefault) {\n // eslint-disable-next-line prefer-rest-params\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n const engine = this.camera.getEngine();\n const element = engine.getInputElement();\n if (!this._pointerInput) {\n this._pointerInput = (p) => {\n const evt = p.event;\n const isTouch = evt.pointerType === \"touch\";\n if (engine.isInVRExclusivePointerMode) {\n return;\n }\n if (!this.touchEnabled && isTouch) {\n return;\n }\n if (p.type !== PointerEventTypes.POINTERMOVE && this.buttons.indexOf(evt.button) === -1) {\n return;\n }\n const srcElement = evt.target;\n if (p.type === PointerEventTypes.POINTERDOWN) {\n // If the input is touch with more than one touch OR if the input is mouse and there is already an active button, return\n if ((isTouch && this._activePointerId !== -1) || (!isTouch && this._currentActiveButton !== -1)) {\n return;\n }\n this._activePointerId = evt.pointerId;\n try {\n srcElement === null || srcElement === void 0 ? void 0 : srcElement.setPointerCapture(evt.pointerId);\n }\n catch (e) {\n //Nothing to do with the error. Execution will continue.\n }\n if (this._currentActiveButton === -1) {\n this._currentActiveButton = evt.button;\n }\n this._previousPosition = {\n x: evt.clientX,\n y: evt.clientY,\n };\n if (!noPreventDefault) {\n evt.preventDefault();\n element && element.focus();\n }\n // This is required to move while pointer button is down\n if (engine.isPointerLock && this._onMouseMove) {\n this._onMouseMove(p.event);\n }\n }\n else if (p.type === PointerEventTypes.POINTERUP) {\n // If input is touch with a different touch id OR if input is mouse with a different button, return\n if ((isTouch && this._activePointerId !== evt.pointerId) || (!isTouch && this._currentActiveButton !== evt.button)) {\n return;\n }\n try {\n srcElement === null || srcElement === void 0 ? void 0 : srcElement.releasePointerCapture(evt.pointerId);\n }\n catch (e) {\n //Nothing to do with the error.\n }\n this._currentActiveButton = -1;\n this._previousPosition = null;\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n this._activePointerId = -1;\n }\n else if (p.type === PointerEventTypes.POINTERMOVE && (this._activePointerId === evt.pointerId || !isTouch)) {\n if (engine.isPointerLock && this._onMouseMove) {\n this._onMouseMove(p.event);\n }\n else if (this._previousPosition) {\n let offsetX = evt.clientX - this._previousPosition.x;\n const offsetY = evt.clientY - this._previousPosition.y;\n if (this.camera.getScene().useRightHandedSystem) {\n offsetX *= -1;\n }\n if (this.camera.parent && this.camera.parent._getWorldMatrixDeterminant() < 0) {\n offsetX *= -1;\n }\n if (this._allowCameraRotation) {\n this.camera.cameraRotation.y += offsetX / this.angularSensibility;\n this.camera.cameraRotation.x += offsetY / this.angularSensibility;\n }\n this.onPointerMovedObservable.notifyObservers({ offsetX: offsetX, offsetY: offsetY });\n this._previousPosition = {\n x: evt.clientX,\n y: evt.clientY,\n };\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n }\n };\n }\n this._onMouseMove = (evt) => {\n if (!engine.isPointerLock) {\n return;\n }\n if (engine.isInVRExclusivePointerMode) {\n return;\n }\n let offsetX = evt.movementX;\n if (this.camera.getScene().useRightHandedSystem) {\n offsetX *= -1;\n }\n if (this.camera.parent && this.camera.parent._getWorldMatrixDeterminant() < 0) {\n offsetX *= -1;\n }\n this.camera.cameraRotation.y += offsetX / this.angularSensibility;\n const offsetY = evt.movementY;\n this.camera.cameraRotation.x += offsetY / this.angularSensibility;\n this._previousPosition = null;\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n };\n this._observer = this.camera\n .getScene()\n ._inputManager._addCameraPointerObserver(this._pointerInput, PointerEventTypes.POINTERDOWN | PointerEventTypes.POINTERUP | PointerEventTypes.POINTERMOVE);\n if (element) {\n this._contextMenuBind = this.onContextMenu.bind(this);\n element.addEventListener(\"contextmenu\", this._contextMenuBind, false); // TODO: We need to figure out how to handle this for Native\n }\n }\n /**\n * Called on JS contextmenu event.\n * Override this method to provide functionality.\n * @param evt\n */\n onContextMenu(evt) {\n evt.preventDefault();\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n if (this._observer) {\n this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer);\n if (this._contextMenuBind) {\n const engine = this.camera.getEngine();\n const element = engine.getInputElement();\n element && element.removeEventListener(\"contextmenu\", this._contextMenuBind);\n }\n if (this.onPointerMovedObservable) {\n this.onPointerMovedObservable.clear();\n }\n this._observer = null;\n this._onMouseMove = null;\n this._previousPosition = null;\n }\n this._currentActiveButton = -1;\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"FreeCameraMouseInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"mouse\";\n }\n}\n__decorate([\n serialize()\n], FreeCameraMouseInput.prototype, \"buttons\", void 0);\n__decorate([\n serialize()\n], FreeCameraMouseInput.prototype, \"angularSensibility\", void 0);\nCameraInputTypes[\"FreeCameraMouseInput\"] = FreeCameraMouseInput;\n//# sourceMappingURL=freeCameraMouseInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { BaseCameraMouseWheelInput } from \"../../Cameras/Inputs/BaseCameraMouseWheelInput.js\";\nimport { Matrix, Vector3 } from \"../../Maths/math.vector.js\";\nimport { Coordinate } from \"../../Maths/math.axis.js\";\n// eslint-disable-next-line @typescript-eslint/naming-convention\nvar _CameraProperty;\n(function (_CameraProperty) {\n _CameraProperty[_CameraProperty[\"MoveRelative\"] = 0] = \"MoveRelative\";\n _CameraProperty[_CameraProperty[\"RotateRelative\"] = 1] = \"RotateRelative\";\n _CameraProperty[_CameraProperty[\"MoveScene\"] = 2] = \"MoveScene\";\n})(_CameraProperty || (_CameraProperty = {}));\n/**\n * Manage the mouse wheel inputs to control a free camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FreeCameraMouseWheelInput extends BaseCameraMouseWheelInput {\n constructor() {\n super(...arguments);\n this._moveRelative = Vector3.Zero();\n this._rotateRelative = Vector3.Zero();\n this._moveScene = Vector3.Zero();\n /**\n * These are set to the desired default behaviour.\n */\n this._wheelXAction = _CameraProperty.MoveRelative;\n this._wheelXActionCoordinate = Coordinate.X;\n this._wheelYAction = _CameraProperty.MoveRelative;\n this._wheelYActionCoordinate = Coordinate.Z;\n this._wheelZAction = null;\n this._wheelZActionCoordinate = null;\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"FreeCameraMouseWheelInput\";\n }\n /**\n * Set which movement axis (relative to camera's orientation) the mouse\n * wheel's X axis controls.\n * @param axis The axis to be moved. Set null to clear.\n */\n set wheelXMoveRelative(axis) {\n if (axis === null && this._wheelXAction !== _CameraProperty.MoveRelative) {\n // Attempting to clear different _wheelXAction.\n return;\n }\n this._wheelXAction = _CameraProperty.MoveRelative;\n this._wheelXActionCoordinate = axis;\n }\n /**\n * Get the configured movement axis (relative to camera's orientation) the\n * mouse wheel's X axis controls.\n * @returns The configured axis or null if none.\n */\n get wheelXMoveRelative() {\n if (this._wheelXAction !== _CameraProperty.MoveRelative) {\n return null;\n }\n return this._wheelXActionCoordinate;\n }\n /**\n * Set which movement axis (relative to camera's orientation) the mouse\n * wheel's Y axis controls.\n * @param axis The axis to be moved. Set null to clear.\n */\n set wheelYMoveRelative(axis) {\n if (axis === null && this._wheelYAction !== _CameraProperty.MoveRelative) {\n // Attempting to clear different _wheelYAction.\n return;\n }\n this._wheelYAction = _CameraProperty.MoveRelative;\n this._wheelYActionCoordinate = axis;\n }\n /**\n * Get the configured movement axis (relative to camera's orientation) the\n * mouse wheel's Y axis controls.\n * @returns The configured axis or null if none.\n */\n get wheelYMoveRelative() {\n if (this._wheelYAction !== _CameraProperty.MoveRelative) {\n return null;\n }\n return this._wheelYActionCoordinate;\n }\n /**\n * Set which movement axis (relative to camera's orientation) the mouse\n * wheel's Z axis controls.\n * @param axis The axis to be moved. Set null to clear.\n */\n set wheelZMoveRelative(axis) {\n if (axis === null && this._wheelZAction !== _CameraProperty.MoveRelative) {\n // Attempting to clear different _wheelZAction.\n return;\n }\n this._wheelZAction = _CameraProperty.MoveRelative;\n this._wheelZActionCoordinate = axis;\n }\n /**\n * Get the configured movement axis (relative to camera's orientation) the\n * mouse wheel's Z axis controls.\n * @returns The configured axis or null if none.\n */\n get wheelZMoveRelative() {\n if (this._wheelZAction !== _CameraProperty.MoveRelative) {\n return null;\n }\n return this._wheelZActionCoordinate;\n }\n /**\n * Set which rotation axis (relative to camera's orientation) the mouse\n * wheel's X axis controls.\n * @param axis The axis to be moved. Set null to clear.\n */\n set wheelXRotateRelative(axis) {\n if (axis === null && this._wheelXAction !== _CameraProperty.RotateRelative) {\n // Attempting to clear different _wheelXAction.\n return;\n }\n this._wheelXAction = _CameraProperty.RotateRelative;\n this._wheelXActionCoordinate = axis;\n }\n /**\n * Get the configured rotation axis (relative to camera's orientation) the\n * mouse wheel's X axis controls.\n * @returns The configured axis or null if none.\n */\n get wheelXRotateRelative() {\n if (this._wheelXAction !== _CameraProperty.RotateRelative) {\n return null;\n }\n return this._wheelXActionCoordinate;\n }\n /**\n * Set which rotation axis (relative to camera's orientation) the mouse\n * wheel's Y axis controls.\n * @param axis The axis to be moved. Set null to clear.\n */\n set wheelYRotateRelative(axis) {\n if (axis === null && this._wheelYAction !== _CameraProperty.RotateRelative) {\n // Attempting to clear different _wheelYAction.\n return;\n }\n this._wheelYAction = _CameraProperty.RotateRelative;\n this._wheelYActionCoordinate = axis;\n }\n /**\n * Get the configured rotation axis (relative to camera's orientation) the\n * mouse wheel's Y axis controls.\n * @returns The configured axis or null if none.\n */\n get wheelYRotateRelative() {\n if (this._wheelYAction !== _CameraProperty.RotateRelative) {\n return null;\n }\n return this._wheelYActionCoordinate;\n }\n /**\n * Set which rotation axis (relative to camera's orientation) the mouse\n * wheel's Z axis controls.\n * @param axis The axis to be moved. Set null to clear.\n */\n set wheelZRotateRelative(axis) {\n if (axis === null && this._wheelZAction !== _CameraProperty.RotateRelative) {\n // Attempting to clear different _wheelZAction.\n return;\n }\n this._wheelZAction = _CameraProperty.RotateRelative;\n this._wheelZActionCoordinate = axis;\n }\n /**\n * Get the configured rotation axis (relative to camera's orientation) the\n * mouse wheel's Z axis controls.\n * @returns The configured axis or null if none.\n */\n get wheelZRotateRelative() {\n if (this._wheelZAction !== _CameraProperty.RotateRelative) {\n return null;\n }\n return this._wheelZActionCoordinate;\n }\n /**\n * Set which movement axis (relative to the scene) the mouse wheel's X axis\n * controls.\n * @param axis The axis to be moved. Set null to clear.\n */\n set wheelXMoveScene(axis) {\n if (axis === null && this._wheelXAction !== _CameraProperty.MoveScene) {\n // Attempting to clear different _wheelXAction.\n return;\n }\n this._wheelXAction = _CameraProperty.MoveScene;\n this._wheelXActionCoordinate = axis;\n }\n /**\n * Get the configured movement axis (relative to the scene) the mouse wheel's\n * X axis controls.\n * @returns The configured axis or null if none.\n */\n get wheelXMoveScene() {\n if (this._wheelXAction !== _CameraProperty.MoveScene) {\n return null;\n }\n return this._wheelXActionCoordinate;\n }\n /**\n * Set which movement axis (relative to the scene) the mouse wheel's Y axis\n * controls.\n * @param axis The axis to be moved. Set null to clear.\n */\n set wheelYMoveScene(axis) {\n if (axis === null && this._wheelYAction !== _CameraProperty.MoveScene) {\n // Attempting to clear different _wheelYAction.\n return;\n }\n this._wheelYAction = _CameraProperty.MoveScene;\n this._wheelYActionCoordinate = axis;\n }\n /**\n * Get the configured movement axis (relative to the scene) the mouse wheel's\n * Y axis controls.\n * @returns The configured axis or null if none.\n */\n get wheelYMoveScene() {\n if (this._wheelYAction !== _CameraProperty.MoveScene) {\n return null;\n }\n return this._wheelYActionCoordinate;\n }\n /**\n * Set which movement axis (relative to the scene) the mouse wheel's Z axis\n * controls.\n * @param axis The axis to be moved. Set null to clear.\n */\n set wheelZMoveScene(axis) {\n if (axis === null && this._wheelZAction !== _CameraProperty.MoveScene) {\n // Attempting to clear different _wheelZAction.\n return;\n }\n this._wheelZAction = _CameraProperty.MoveScene;\n this._wheelZActionCoordinate = axis;\n }\n /**\n * Get the configured movement axis (relative to the scene) the mouse wheel's\n * Z axis controls.\n * @returns The configured axis or null if none.\n */\n get wheelZMoveScene() {\n if (this._wheelZAction !== _CameraProperty.MoveScene) {\n return null;\n }\n return this._wheelZActionCoordinate;\n }\n /**\n * Called for each rendered frame.\n */\n checkInputs() {\n if (this._wheelDeltaX === 0 && this._wheelDeltaY === 0 && this._wheelDeltaZ == 0) {\n return;\n }\n // Clear the camera properties that we might be updating.\n this._moveRelative.setAll(0);\n this._rotateRelative.setAll(0);\n this._moveScene.setAll(0);\n // Set the camera properties that are to be updated.\n this._updateCamera();\n if (this.camera.getScene().useRightHandedSystem) {\n // TODO: Does this need done for worldUpdate too?\n this._moveRelative.z *= -1;\n }\n // Convert updates relative to camera to world position update.\n const cameraTransformMatrix = Matrix.Zero();\n this.camera.getViewMatrix().invertToRef(cameraTransformMatrix);\n const transformedDirection = Vector3.Zero();\n Vector3.TransformNormalToRef(this._moveRelative, cameraTransformMatrix, transformedDirection);\n // Apply updates to camera position.\n this.camera.cameraRotation.x += this._rotateRelative.x / 200;\n this.camera.cameraRotation.y += this._rotateRelative.y / 200;\n this.camera.cameraDirection.addInPlace(transformedDirection);\n this.camera.cameraDirection.addInPlace(this._moveScene);\n // Call the base class implementation to handle observers and do cleanup.\n super.checkInputs();\n }\n /**\n * Update the camera according to any configured properties for the 3\n * mouse-wheel axis.\n */\n _updateCamera() {\n // Do the camera updates for each of the 3 touch-wheel axis.\n this._updateCameraProperty(this._wheelDeltaX, this._wheelXAction, this._wheelXActionCoordinate);\n this._updateCameraProperty(this._wheelDeltaY, this._wheelYAction, this._wheelYActionCoordinate);\n this._updateCameraProperty(this._wheelDeltaZ, this._wheelZAction, this._wheelZActionCoordinate);\n }\n /**\n * Update one property of the camera.\n * @param value\n * @param cameraProperty\n * @param coordinate\n */\n _updateCameraProperty(\n /* Mouse-wheel delta. */\n value, \n /* Camera property to be changed. */\n cameraProperty, \n /* Axis of Camera property to be changed. */\n coordinate) {\n if (value === 0) {\n // Mouse wheel has not moved.\n return;\n }\n if (cameraProperty === null || coordinate === null) {\n // Mouse wheel axis not configured.\n return;\n }\n let action = null;\n switch (cameraProperty) {\n case _CameraProperty.MoveRelative:\n action = this._moveRelative;\n break;\n case _CameraProperty.RotateRelative:\n action = this._rotateRelative;\n break;\n case _CameraProperty.MoveScene:\n action = this._moveScene;\n break;\n }\n switch (coordinate) {\n case Coordinate.X:\n action.set(value, 0, 0);\n break;\n case Coordinate.Y:\n action.set(0, value, 0);\n break;\n case Coordinate.Z:\n action.set(0, 0, value);\n break;\n }\n }\n}\n__decorate([\n serialize()\n], FreeCameraMouseWheelInput.prototype, \"wheelXMoveRelative\", null);\n__decorate([\n serialize()\n], FreeCameraMouseWheelInput.prototype, \"wheelYMoveRelative\", null);\n__decorate([\n serialize()\n], FreeCameraMouseWheelInput.prototype, \"wheelZMoveRelative\", null);\n__decorate([\n serialize()\n], FreeCameraMouseWheelInput.prototype, \"wheelXRotateRelative\", null);\n__decorate([\n serialize()\n], FreeCameraMouseWheelInput.prototype, \"wheelYRotateRelative\", null);\n__decorate([\n serialize()\n], FreeCameraMouseWheelInput.prototype, \"wheelZRotateRelative\", null);\n__decorate([\n serialize()\n], FreeCameraMouseWheelInput.prototype, \"wheelXMoveScene\", null);\n__decorate([\n serialize()\n], FreeCameraMouseWheelInput.prototype, \"wheelYMoveScene\", null);\n__decorate([\n serialize()\n], FreeCameraMouseWheelInput.prototype, \"wheelZMoveScene\", null);\nCameraInputTypes[\"FreeCameraMouseWheelInput\"] = FreeCameraMouseWheelInput;\n//# sourceMappingURL=freeCameraMouseWheelInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { PointerEventTypes } from \"../../Events/pointerEvents.js\";\nimport { Matrix, Vector3 } from \"../../Maths/math.vector.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * Manage the touch inputs to control the movement of a free camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FreeCameraTouchInput {\n /**\n * Manage the touch inputs to control the movement of a free camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n * @param allowMouse Defines if mouse events can be treated as touch events\n */\n constructor(\n /**\n * Define if mouse events can be treated as touch events\n */\n allowMouse = false) {\n this.allowMouse = allowMouse;\n /**\n * Defines the touch sensibility for rotation.\n * The lower the faster.\n */\n this.touchAngularSensibility = 200000.0;\n /**\n * Defines the touch sensibility for move.\n * The lower the faster.\n */\n this.touchMoveSensibility = 250.0;\n /**\n * Swap touch actions so that one touch is used for rotation and multiple for movement\n */\n this.singleFingerRotate = false;\n this._offsetX = null;\n this._offsetY = null;\n this._pointerPressed = new Array();\n this._isSafari = Tools.IsSafari();\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(noPreventDefault) {\n // eslint-disable-next-line prefer-rest-params\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n let previousPosition = null;\n if (this._pointerInput === undefined) {\n this._onLostFocus = () => {\n this._offsetX = null;\n this._offsetY = null;\n };\n this._pointerInput = (p) => {\n const evt = p.event;\n const isMouseEvent = evt.pointerType === \"mouse\" || (this._isSafari && typeof evt.pointerType === \"undefined\");\n if (!this.allowMouse && isMouseEvent) {\n return;\n }\n if (p.type === PointerEventTypes.POINTERDOWN) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n this._pointerPressed.push(evt.pointerId);\n if (this._pointerPressed.length !== 1) {\n return;\n }\n previousPosition = {\n x: evt.clientX,\n y: evt.clientY,\n };\n }\n else if (p.type === PointerEventTypes.POINTERUP) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n const index = this._pointerPressed.indexOf(evt.pointerId);\n if (index === -1) {\n return;\n }\n this._pointerPressed.splice(index, 1);\n if (index != 0) {\n return;\n }\n previousPosition = null;\n this._offsetX = null;\n this._offsetY = null;\n }\n else if (p.type === PointerEventTypes.POINTERMOVE) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n if (!previousPosition) {\n return;\n }\n const index = this._pointerPressed.indexOf(evt.pointerId);\n if (index != 0) {\n return;\n }\n this._offsetX = evt.clientX - previousPosition.x;\n this._offsetY = -(evt.clientY - previousPosition.y);\n }\n };\n }\n this._observer = this.camera\n .getScene()\n ._inputManager._addCameraPointerObserver(this._pointerInput, PointerEventTypes.POINTERDOWN | PointerEventTypes.POINTERUP | PointerEventTypes.POINTERMOVE);\n if (this._onLostFocus) {\n const engine = this.camera.getEngine();\n const element = engine.getInputElement();\n element && element.addEventListener(\"blur\", this._onLostFocus);\n }\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n if (this._pointerInput) {\n if (this._observer) {\n this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer);\n this._observer = null;\n }\n if (this._onLostFocus) {\n const engine = this.camera.getEngine();\n const element = engine.getInputElement();\n element && element.removeEventListener(\"blur\", this._onLostFocus);\n this._onLostFocus = null;\n }\n this._pointerPressed.length = 0;\n this._offsetX = null;\n this._offsetY = null;\n }\n }\n /**\n * Update the current camera state depending on the inputs that have been used this frame.\n * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.\n */\n checkInputs() {\n if (this._offsetX === null || this._offsetY === null) {\n return;\n }\n if (this._offsetX === 0 && this._offsetY === 0) {\n return;\n }\n const camera = this.camera;\n camera.cameraRotation.y = this._offsetX / this.touchAngularSensibility;\n const rotateCamera = (this.singleFingerRotate && this._pointerPressed.length === 1) || (!this.singleFingerRotate && this._pointerPressed.length > 1);\n if (rotateCamera) {\n camera.cameraRotation.x = -this._offsetY / this.touchAngularSensibility;\n }\n else {\n const speed = camera._computeLocalCameraSpeed();\n const direction = new Vector3(0, 0, this.touchMoveSensibility !== 0 ? (speed * this._offsetY) / this.touchMoveSensibility : 0);\n Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);\n camera.cameraDirection.addInPlace(Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));\n }\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"FreeCameraTouchInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"touch\";\n }\n}\n__decorate([\n serialize()\n], FreeCameraTouchInput.prototype, \"touchAngularSensibility\", void 0);\n__decorate([\n serialize()\n], FreeCameraTouchInput.prototype, \"touchMoveSensibility\", void 0);\nCameraInputTypes[\"FreeCameraTouchInput\"] = FreeCameraTouchInput;\n//# sourceMappingURL=freeCameraTouchInput.js.map","import { CameraInputsManager } from \"./cameraInputsManager.js\";\nimport { FreeCameraKeyboardMoveInput } from \"../Cameras/Inputs/freeCameraKeyboardMoveInput.js\";\nimport { FreeCameraMouseInput } from \"../Cameras/Inputs/freeCameraMouseInput.js\";\nimport { FreeCameraMouseWheelInput } from \"../Cameras/Inputs/freeCameraMouseWheelInput.js\";\nimport { FreeCameraTouchInput } from \"../Cameras/Inputs/freeCameraTouchInput.js\";\n/**\n * Default Inputs manager for the FreeCamera.\n * It groups all the default supported inputs for ease of use.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FreeCameraInputsManager extends CameraInputsManager {\n /**\n * Instantiates a new FreeCameraInputsManager.\n * @param camera Defines the camera the inputs belong to\n */\n constructor(camera) {\n super(camera);\n /**\n * @internal\n */\n this._mouseInput = null;\n /**\n * @internal\n */\n this._mouseWheelInput = null;\n }\n /**\n * Add keyboard input support to the input manager.\n * @returns the current input manager\n */\n addKeyboard() {\n this.add(new FreeCameraKeyboardMoveInput());\n return this;\n }\n /**\n * Add mouse input support to the input manager.\n * @param touchEnabled if the FreeCameraMouseInput should support touch (default: true)\n * @returns the current input manager\n */\n addMouse(touchEnabled = true) {\n if (!this._mouseInput) {\n this._mouseInput = new FreeCameraMouseInput(touchEnabled);\n this.add(this._mouseInput);\n }\n return this;\n }\n /**\n * Removes the mouse input support from the manager\n * @returns the current input manager\n */\n removeMouse() {\n if (this._mouseInput) {\n this.remove(this._mouseInput);\n }\n return this;\n }\n /**\n * Add mouse wheel input support to the input manager.\n * @returns the current input manager\n */\n addMouseWheel() {\n if (!this._mouseWheelInput) {\n this._mouseWheelInput = new FreeCameraMouseWheelInput();\n this.add(this._mouseWheelInput);\n }\n return this;\n }\n /**\n * Removes the mouse wheel input support from the manager\n * @returns the current input manager\n */\n removeMouseWheel() {\n if (this._mouseWheelInput) {\n this.remove(this._mouseWheelInput);\n }\n return this;\n }\n /**\n * Add touch input support to the input manager.\n * @returns the current input manager\n */\n addTouch() {\n this.add(new FreeCameraTouchInput());\n return this;\n }\n /**\n * Remove all attached input methods from a camera\n */\n clear() {\n super.clear();\n this._mouseInput = null;\n }\n}\n//# sourceMappingURL=freeCameraInputsManager.js.map","import { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { Quaternion } from \"../../Maths/math.vector.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nimport { FreeCameraInputsManager } from \"../../Cameras/freeCameraInputsManager.js\";\nimport { Observable } from \"../../Misc/observable.js\";\n/**\n * Add orientation input support to the input manager.\n * @param smoothFactor deviceOrientation smoothing. 0: no smoothing, 1: new data ignored, 0.9 recommended for smoothing\n * @returns the current input manager\n */\nFreeCameraInputsManager.prototype.addDeviceOrientation = function (smoothFactor) {\n if (!this._deviceOrientationInput) {\n this._deviceOrientationInput = new FreeCameraDeviceOrientationInput();\n if (smoothFactor) {\n this._deviceOrientationInput.smoothFactor = smoothFactor;\n }\n this.add(this._deviceOrientationInput);\n }\n return this;\n};\n/**\n * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.\n * Screen rotation is taken into account.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FreeCameraDeviceOrientationInput {\n /**\n * Can be used to detect if a device orientation sensor is available on a device\n * @param timeout amount of time in milliseconds to wait for a response from the sensor (default: infinite)\n * @returns a promise that will resolve on orientation change\n */\n static WaitForOrientationChangeAsync(timeout) {\n return new Promise((res, rej) => {\n let gotValue = false;\n const eventHandler = () => {\n window.removeEventListener(\"deviceorientation\", eventHandler);\n gotValue = true;\n res();\n };\n // If timeout is populated reject the promise\n if (timeout) {\n setTimeout(() => {\n if (!gotValue) {\n window.removeEventListener(\"deviceorientation\", eventHandler);\n rej(\"WaitForOrientationChangeAsync timed out\");\n }\n }, timeout);\n }\n if (typeof DeviceOrientationEvent !== \"undefined\" && typeof DeviceOrientationEvent.requestPermission === \"function\") {\n DeviceOrientationEvent\n .requestPermission()\n .then((response) => {\n if (response == \"granted\") {\n window.addEventListener(\"deviceorientation\", eventHandler);\n }\n else {\n Tools.Warn(\"Permission not granted.\");\n }\n })\n .catch((error) => {\n Tools.Error(error);\n });\n }\n else {\n window.addEventListener(\"deviceorientation\", eventHandler);\n }\n });\n }\n /**\n * Instantiates a new input\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\n constructor() {\n this._screenOrientationAngle = 0;\n this._screenQuaternion = new Quaternion();\n this._alpha = 0;\n this._beta = 0;\n this._gamma = 0;\n /** alpha+beta+gamma smoothing. 0: no smoothing, 1: new data ignored, 0.9 recommended for smoothing */\n this.smoothFactor = 0;\n /**\n * @internal\n */\n this._onDeviceOrientationChangedObservable = new Observable();\n this._orientationChanged = () => {\n this._screenOrientationAngle =\n window.orientation !== undefined\n ? +window.orientation\n : window.screen.orientation && window.screen.orientation[\"angle\"]\n ? window.screen.orientation.angle\n : 0;\n this._screenOrientationAngle = -Tools.ToRadians(this._screenOrientationAngle / 2);\n this._screenQuaternion.copyFromFloats(0, Math.sin(this._screenOrientationAngle), 0, Math.cos(this._screenOrientationAngle));\n };\n this._deviceOrientation = (evt) => {\n if (this.smoothFactor) {\n this._alpha = evt.alpha !== null ? Tools.SmoothAngleChange(this._alpha, evt.alpha, this.smoothFactor) : 0;\n this._beta = evt.beta !== null ? Tools.SmoothAngleChange(this._beta, evt.beta, this.smoothFactor) : 0;\n this._gamma = evt.gamma !== null ? Tools.SmoothAngleChange(this._gamma, evt.gamma, this.smoothFactor) : 0;\n }\n else {\n this._alpha = evt.alpha !== null ? evt.alpha : 0;\n this._beta = evt.beta !== null ? evt.beta : 0;\n this._gamma = evt.gamma !== null ? evt.gamma : 0;\n }\n if (evt.alpha !== null) {\n this._onDeviceOrientationChangedObservable.notifyObservers();\n }\n };\n this._constantTranform = new Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));\n this._orientationChanged();\n }\n /**\n * Define the camera controlled by the input.\n */\n get camera() {\n return this._camera;\n }\n set camera(camera) {\n this._camera = camera;\n if (this._camera != null && !this._camera.rotationQuaternion) {\n this._camera.rotationQuaternion = new Quaternion();\n }\n if (this._camera) {\n this._camera.onDisposeObservable.add(() => {\n this._onDeviceOrientationChangedObservable.clear();\n });\n }\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n */\n attachControl() {\n const hostWindow = this.camera.getScene().getEngine().getHostWindow();\n if (hostWindow) {\n const eventHandler = () => {\n hostWindow.addEventListener(\"orientationchange\", this._orientationChanged);\n hostWindow.addEventListener(\"deviceorientation\", this._deviceOrientation);\n //In certain cases, the attach control is called AFTER orientation was changed,\n //So this is needed.\n this._orientationChanged();\n };\n if (typeof DeviceOrientationEvent !== \"undefined\" && typeof DeviceOrientationEvent.requestPermission === \"function\") {\n DeviceOrientationEvent\n .requestPermission()\n .then((response) => {\n if (response === \"granted\") {\n eventHandler();\n }\n else {\n Tools.Warn(\"Permission not granted.\");\n }\n })\n .catch((error) => {\n Tools.Error(error);\n });\n }\n else {\n eventHandler();\n }\n }\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n window.removeEventListener(\"orientationchange\", this._orientationChanged);\n window.removeEventListener(\"deviceorientation\", this._deviceOrientation);\n this._alpha = 0;\n }\n /**\n * Update the current camera state depending on the inputs that have been used this frame.\n * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.\n */\n checkInputs() {\n //if no device orientation provided, don't update the rotation.\n //Only testing against alpha under the assumption thatnorientation will never be so exact when set.\n if (!this._alpha) {\n return;\n }\n Quaternion.RotationYawPitchRollToRef(Tools.ToRadians(this._alpha), Tools.ToRadians(this._beta), -Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);\n this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);\n this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);\n //Mirror on XY Plane\n this._camera.rotationQuaternion.z *= -1;\n this._camera.rotationQuaternion.w *= -1;\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"FreeCameraDeviceOrientationInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"deviceOrientation\";\n }\n}\nCameraInputTypes[\"FreeCameraDeviceOrientationInput\"] = FreeCameraDeviceOrientationInput;\n//# sourceMappingURL=freeCameraDeviceOrientationInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { Matrix, Vector3, Vector2 } from \"../../Maths/math.vector.js\";\nimport { Gamepad } from \"../../Gamepads/gamepad.js\";\n/**\n * Manage the gamepad inputs to control a free camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FreeCameraGamepadInput {\n constructor() {\n /**\n * Defines the gamepad rotation sensibility.\n * This is the threshold from when rotation starts to be accounted for to prevent jittering.\n */\n this.gamepadAngularSensibility = 200;\n /**\n * Defines the gamepad move sensibility.\n * This is the threshold from when moving starts to be accounted for for to prevent jittering.\n */\n this.gamepadMoveSensibility = 40;\n /**\n * Defines the minimum value at which any analog stick input is ignored.\n * Note: This value should only be a value between 0 and 1.\n */\n this.deadzoneDelta = 0.1;\n this._yAxisScale = 1.0;\n this._cameraTransform = Matrix.Identity();\n this._deltaTransform = Vector3.Zero();\n this._vector3 = Vector3.Zero();\n this._vector2 = Vector2.Zero();\n }\n /**\n * Gets or sets a boolean indicating that Yaxis (for right stick) should be inverted\n */\n get invertYAxis() {\n return this._yAxisScale !== 1.0;\n }\n set invertYAxis(value) {\n this._yAxisScale = value ? -1.0 : 1.0;\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n */\n attachControl() {\n const manager = this.camera.getScene().gamepadManager;\n this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add((gamepad) => {\n if (gamepad.type !== Gamepad.POSE_ENABLED) {\n // prioritize XBOX gamepads.\n if (!this.gamepad || gamepad.type === Gamepad.XBOX) {\n this.gamepad = gamepad;\n }\n }\n });\n this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add((gamepad) => {\n if (this.gamepad === gamepad) {\n this.gamepad = null;\n }\n });\n // check if there are already other controllers connected\n this.gamepad = manager.getGamepadByType(Gamepad.XBOX);\n // if no xbox controller was found, but there are gamepad controllers, take the first one\n if (!this.gamepad && manager.gamepads.length) {\n this.gamepad = manager.gamepads[0];\n }\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);\n this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);\n this.gamepad = null;\n }\n /**\n * Update the current camera state depending on the inputs that have been used this frame.\n * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.\n */\n checkInputs() {\n if (this.gamepad && this.gamepad.leftStick) {\n const camera = this.camera;\n const lsValues = this.gamepad.leftStick;\n if (this.gamepadMoveSensibility !== 0) {\n lsValues.x = Math.abs(lsValues.x) > this.deadzoneDelta ? lsValues.x / this.gamepadMoveSensibility : 0;\n lsValues.y = Math.abs(lsValues.y) > this.deadzoneDelta ? lsValues.y / this.gamepadMoveSensibility : 0;\n }\n let rsValues = this.gamepad.rightStick;\n if (rsValues && this.gamepadAngularSensibility !== 0) {\n rsValues.x = Math.abs(rsValues.x) > this.deadzoneDelta ? rsValues.x / this.gamepadAngularSensibility : 0;\n rsValues.y = (Math.abs(rsValues.y) > this.deadzoneDelta ? rsValues.y / this.gamepadAngularSensibility : 0) * this._yAxisScale;\n }\n else {\n rsValues = { x: 0, y: 0 };\n }\n if (!camera.rotationQuaternion) {\n Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);\n }\n else {\n camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);\n }\n const speed = camera._computeLocalCameraSpeed() * 50.0;\n this._vector3.copyFromFloats(lsValues.x * speed, 0, -lsValues.y * speed);\n Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);\n camera.cameraDirection.addInPlace(this._deltaTransform);\n this._vector2.copyFromFloats(rsValues.y, rsValues.x);\n camera.cameraRotation.addInPlace(this._vector2);\n }\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"FreeCameraGamepadInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"gamepad\";\n }\n}\n__decorate([\n serialize()\n], FreeCameraGamepadInput.prototype, \"gamepadAngularSensibility\", void 0);\n__decorate([\n serialize()\n], FreeCameraGamepadInput.prototype, \"gamepadMoveSensibility\", void 0);\nCameraInputTypes[\"FreeCameraGamepadInput\"] = FreeCameraGamepadInput;\n//# sourceMappingURL=freeCameraGamepadInput.js.map","import { Vector3, Vector2 } from \"../Maths/math.vector.js\";\nimport { StringDictionary } from \"./stringDictionary.js\";\n// Mainly based on these 2 articles :\n// Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx\n// & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/\n/**\n * Defines the potential axis of a Joystick\n */\nexport var JoystickAxis;\n(function (JoystickAxis) {\n /** X axis */\n JoystickAxis[JoystickAxis[\"X\"] = 0] = \"X\";\n /** Y axis */\n JoystickAxis[JoystickAxis[\"Y\"] = 1] = \"Y\";\n /** Z axis */\n JoystickAxis[JoystickAxis[\"Z\"] = 2] = \"Z\";\n})(JoystickAxis || (JoystickAxis = {}));\n/**\n * Class used to define virtual joystick (used in touch mode)\n */\nexport class VirtualJoystick {\n static _GetDefaultOptions() {\n return {\n puckSize: 40,\n containerSize: 60,\n color: \"cyan\",\n puckImage: undefined,\n containerImage: undefined,\n position: undefined,\n alwaysVisible: false,\n limitToContainer: false,\n };\n }\n /**\n * Creates a new virtual joystick\n * @param leftJoystick defines that the joystick is for left hand (false by default)\n * @param customizations Defines the options we want to customize the VirtualJoystick\n */\n constructor(leftJoystick, customizations) {\n this._released = false;\n const options = Object.assign(Object.assign({}, VirtualJoystick._GetDefaultOptions()), customizations);\n if (leftJoystick) {\n this._leftJoystick = true;\n }\n else {\n this._leftJoystick = false;\n }\n VirtualJoystick._GlobalJoystickIndex++;\n // By default left & right arrow keys are moving the X\n // and up & down keys are moving the Y\n this._axisTargetedByLeftAndRight = JoystickAxis.X;\n this._axisTargetedByUpAndDown = JoystickAxis.Y;\n this.reverseLeftRight = false;\n this.reverseUpDown = false;\n // collections of pointers\n this._touches = new StringDictionary();\n this.deltaPosition = Vector3.Zero();\n this._joystickSensibility = 25;\n this._inversedSensibility = 1 / (this._joystickSensibility / 1000);\n this._onResize = () => {\n VirtualJoystick._VJCanvasWidth = window.innerWidth;\n VirtualJoystick._VJCanvasHeight = window.innerHeight;\n if (VirtualJoystick.Canvas) {\n VirtualJoystick.Canvas.width = VirtualJoystick._VJCanvasWidth;\n VirtualJoystick.Canvas.height = VirtualJoystick._VJCanvasHeight;\n }\n VirtualJoystick._HalfWidth = VirtualJoystick._VJCanvasWidth / 2;\n };\n // injecting a canvas element on top of the canvas 3D game\n if (!VirtualJoystick.Canvas) {\n window.addEventListener(\"resize\", this._onResize, false);\n VirtualJoystick.Canvas = document.createElement(\"canvas\");\n VirtualJoystick._VJCanvasWidth = window.innerWidth;\n VirtualJoystick._VJCanvasHeight = window.innerHeight;\n VirtualJoystick.Canvas.width = window.innerWidth;\n VirtualJoystick.Canvas.height = window.innerHeight;\n VirtualJoystick.Canvas.style.width = \"100%\";\n VirtualJoystick.Canvas.style.height = \"100%\";\n VirtualJoystick.Canvas.style.position = \"absolute\";\n VirtualJoystick.Canvas.style.backgroundColor = \"transparent\";\n VirtualJoystick.Canvas.style.top = \"0px\";\n VirtualJoystick.Canvas.style.left = \"0px\";\n VirtualJoystick.Canvas.style.zIndex = \"5\";\n VirtualJoystick.Canvas.style.touchAction = \"none\"; // fix https://forum.babylonjs.com/t/virtualjoystick-needs-to-set-style-touch-action-none-explicitly/9562\n // Support for jQuery PEP polyfill\n VirtualJoystick.Canvas.setAttribute(\"touch-action\", \"none\");\n const context = VirtualJoystick.Canvas.getContext(\"2d\");\n if (!context) {\n throw new Error(\"Unable to create canvas for virtual joystick\");\n }\n VirtualJoystick._VJCanvasContext = context;\n VirtualJoystick._VJCanvasContext.strokeStyle = \"#ffffff\";\n VirtualJoystick._VJCanvasContext.lineWidth = 2;\n document.body.appendChild(VirtualJoystick.Canvas);\n }\n VirtualJoystick._HalfWidth = VirtualJoystick.Canvas.width / 2;\n this.pressed = false;\n this.limitToContainer = options.limitToContainer;\n // default joystick color\n this._joystickColor = options.color;\n // default joystick size\n this.containerSize = options.containerSize;\n this.puckSize = options.puckSize;\n if (options.position) {\n this.setPosition(options.position.x, options.position.y);\n }\n if (options.puckImage) {\n this.setPuckImage(options.puckImage);\n }\n if (options.containerImage) {\n this.setContainerImage(options.containerImage);\n }\n if (options.alwaysVisible) {\n VirtualJoystick._AlwaysVisibleSticks++;\n }\n // must come after position potentially set\n this.alwaysVisible = options.alwaysVisible;\n this._joystickPointerId = -1;\n // current joystick position\n this._joystickPointerPos = new Vector2(0, 0);\n this._joystickPreviousPointerPos = new Vector2(0, 0);\n // origin joystick position\n this._joystickPointerStartPos = new Vector2(0, 0);\n this._deltaJoystickVector = new Vector2(0, 0);\n this._onPointerDownHandlerRef = (evt) => {\n this._onPointerDown(evt);\n };\n this._onPointerMoveHandlerRef = (evt) => {\n this._onPointerMove(evt);\n };\n this._onPointerUpHandlerRef = (evt) => {\n this._onPointerUp(evt);\n };\n VirtualJoystick.Canvas.addEventListener(\"pointerdown\", this._onPointerDownHandlerRef, false);\n VirtualJoystick.Canvas.addEventListener(\"pointermove\", this._onPointerMoveHandlerRef, false);\n VirtualJoystick.Canvas.addEventListener(\"pointerup\", this._onPointerUpHandlerRef, false);\n VirtualJoystick.Canvas.addEventListener(\"pointerout\", this._onPointerUpHandlerRef, false);\n VirtualJoystick.Canvas.addEventListener(\"contextmenu\", (evt) => {\n evt.preventDefault(); // Disables system menu\n }, false);\n requestAnimationFrame(() => {\n this._drawVirtualJoystick();\n });\n }\n /**\n * Defines joystick sensibility (ie. the ratio between a physical move and virtual joystick position change)\n * @param newJoystickSensibility defines the new sensibility\n */\n setJoystickSensibility(newJoystickSensibility) {\n this._joystickSensibility = newJoystickSensibility;\n this._inversedSensibility = 1 / (this._joystickSensibility / 1000);\n }\n _onPointerDown(e) {\n let positionOnScreenCondition;\n e.preventDefault();\n if (this._leftJoystick === true) {\n positionOnScreenCondition = e.clientX < VirtualJoystick._HalfWidth;\n }\n else {\n positionOnScreenCondition = e.clientX > VirtualJoystick._HalfWidth;\n }\n if (positionOnScreenCondition && this._joystickPointerId < 0) {\n // First contact will be dedicated to the virtual joystick\n this._joystickPointerId = e.pointerId;\n if (this._joystickPosition) {\n this._joystickPointerStartPos = this._joystickPosition.clone();\n this._joystickPointerPos = this._joystickPosition.clone();\n this._joystickPreviousPointerPos = this._joystickPosition.clone();\n // in case the user only clicks down && doesn't move:\n // this ensures the delta is properly set\n this._onPointerMove(e);\n }\n else {\n this._joystickPointerStartPos.x = e.clientX;\n this._joystickPointerStartPos.y = e.clientY;\n this._joystickPointerPos = this._joystickPointerStartPos.clone();\n this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();\n }\n this._deltaJoystickVector.x = 0;\n this._deltaJoystickVector.y = 0;\n this.pressed = true;\n this._touches.add(e.pointerId.toString(), e);\n }\n else {\n // You can only trigger the action buttons with a joystick declared\n if (VirtualJoystick._GlobalJoystickIndex < 2 && this._action) {\n this._action();\n this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });\n }\n }\n }\n _onPointerMove(e) {\n // If the current pointer is the one associated to the joystick (first touch contact)\n if (this._joystickPointerId == e.pointerId) {\n // limit to container if need be\n if (this.limitToContainer) {\n const vector = new Vector2(e.clientX - this._joystickPointerStartPos.x, e.clientY - this._joystickPointerStartPos.y);\n const distance = vector.length();\n if (distance > this.containerSize) {\n vector.scaleInPlace(this.containerSize / distance);\n }\n this._joystickPointerPos.x = this._joystickPointerStartPos.x + vector.x;\n this._joystickPointerPos.y = this._joystickPointerStartPos.y + vector.y;\n }\n else {\n this._joystickPointerPos.x = e.clientX;\n this._joystickPointerPos.y = e.clientY;\n }\n // create delta vector\n this._deltaJoystickVector = this._joystickPointerPos.clone();\n this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);\n // if a joystick is always visible, there will be clipping issues if\n // you drag the puck from one over the container of the other\n if (0 < VirtualJoystick._AlwaysVisibleSticks) {\n if (this._leftJoystick) {\n this._joystickPointerPos.x = Math.min(VirtualJoystick._HalfWidth, this._joystickPointerPos.x);\n }\n else {\n this._joystickPointerPos.x = Math.max(VirtualJoystick._HalfWidth, this._joystickPointerPos.x);\n }\n }\n const directionLeftRight = this.reverseLeftRight ? -1 : 1;\n const deltaJoystickX = (directionLeftRight * this._deltaJoystickVector.x) / this._inversedSensibility;\n switch (this._axisTargetedByLeftAndRight) {\n case JoystickAxis.X:\n this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));\n break;\n case JoystickAxis.Y:\n this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));\n break;\n case JoystickAxis.Z:\n this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));\n break;\n }\n const directionUpDown = this.reverseUpDown ? 1 : -1;\n const deltaJoystickY = (directionUpDown * this._deltaJoystickVector.y) / this._inversedSensibility;\n switch (this._axisTargetedByUpAndDown) {\n case JoystickAxis.X:\n this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));\n break;\n case JoystickAxis.Y:\n this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));\n break;\n case JoystickAxis.Z:\n this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));\n break;\n }\n }\n else {\n const data = this._touches.get(e.pointerId.toString());\n if (data) {\n data.x = e.clientX;\n data.y = e.clientY;\n }\n }\n }\n _onPointerUp(e) {\n if (this._joystickPointerId == e.pointerId) {\n this._clearPreviousDraw();\n this._joystickPointerId = -1;\n this.pressed = false;\n }\n else {\n const touch = this._touches.get(e.pointerId.toString());\n if (touch) {\n VirtualJoystick._VJCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);\n }\n }\n this._deltaJoystickVector.x = 0;\n this._deltaJoystickVector.y = 0;\n this._touches.remove(e.pointerId.toString());\n }\n /**\n * Change the color of the virtual joystick\n * @param newColor a string that must be a CSS color value (like \"red\") or the hexa value (like \"#FF0000\")\n */\n setJoystickColor(newColor) {\n this._joystickColor = newColor;\n }\n /**\n * Size of the joystick's container\n */\n set containerSize(newSize) {\n this._joystickContainerSize = newSize;\n this._clearContainerSize = ~~(this._joystickContainerSize * 2.1);\n this._clearContainerSizeOffset = ~~(this._clearContainerSize / 2);\n }\n get containerSize() {\n return this._joystickContainerSize;\n }\n /**\n * Size of the joystick's puck\n */\n set puckSize(newSize) {\n this._joystickPuckSize = newSize;\n this._clearPuckSize = ~~(this._joystickPuckSize * 2.1);\n this._clearPuckSizeOffset = ~~(this._clearPuckSize / 2);\n }\n get puckSize() {\n return this._joystickPuckSize;\n }\n /**\n * Clears the set position of the joystick\n */\n clearPosition() {\n this.alwaysVisible = false;\n this._joystickPosition = null;\n }\n /**\n * Defines whether or not the joystick container is always visible\n */\n set alwaysVisible(value) {\n if (this._alwaysVisible === value) {\n return;\n }\n if (value && this._joystickPosition) {\n VirtualJoystick._AlwaysVisibleSticks++;\n this._alwaysVisible = true;\n }\n else {\n VirtualJoystick._AlwaysVisibleSticks--;\n this._alwaysVisible = false;\n }\n }\n get alwaysVisible() {\n return this._alwaysVisible;\n }\n /**\n * Sets the constant position of the Joystick container\n * @param x X axis coordinate\n * @param y Y axis coordinate\n */\n setPosition(x, y) {\n // just in case position is moved while the container is visible\n if (this._joystickPointerStartPos) {\n this._clearPreviousDraw();\n }\n this._joystickPosition = new Vector2(x, y);\n }\n /**\n * Defines a callback to call when the joystick is touched\n * @param action defines the callback\n */\n setActionOnTouch(action) {\n this._action = action;\n }\n /**\n * Defines which axis you'd like to control for left & right\n * @param axis defines the axis to use\n */\n setAxisForLeftRight(axis) {\n switch (axis) {\n case JoystickAxis.X:\n case JoystickAxis.Y:\n case JoystickAxis.Z:\n this._axisTargetedByLeftAndRight = axis;\n break;\n default:\n this._axisTargetedByLeftAndRight = JoystickAxis.X;\n break;\n }\n }\n /**\n * Defines which axis you'd like to control for up & down\n * @param axis defines the axis to use\n */\n setAxisForUpDown(axis) {\n switch (axis) {\n case JoystickAxis.X:\n case JoystickAxis.Y:\n case JoystickAxis.Z:\n this._axisTargetedByUpAndDown = axis;\n break;\n default:\n this._axisTargetedByUpAndDown = JoystickAxis.Y;\n break;\n }\n }\n /**\n * Clears the canvas from the previous puck / container draw\n */\n _clearPreviousDraw() {\n const jp = this._joystickPosition || this._joystickPointerStartPos;\n // clear container pixels\n VirtualJoystick._VJCanvasContext.clearRect(jp.x - this._clearContainerSizeOffset, jp.y - this._clearContainerSizeOffset, this._clearContainerSize, this._clearContainerSize);\n // clear puck pixels + 1 pixel for the change made before it moved\n VirtualJoystick._VJCanvasContext.clearRect(this._joystickPreviousPointerPos.x - this._clearPuckSizeOffset - 1, this._joystickPreviousPointerPos.y - this._clearPuckSizeOffset - 1, this._clearPuckSize + 2, this._clearPuckSize + 2);\n }\n /**\n * Loads `urlPath` to be used for the container's image\n * @param urlPath defines the urlPath of an image to use\n */\n setContainerImage(urlPath) {\n const image = new Image();\n image.src = urlPath;\n image.onload = () => (this._containerImage = image);\n }\n /**\n * Loads `urlPath` to be used for the puck's image\n * @param urlPath defines the urlPath of an image to use\n */\n setPuckImage(urlPath) {\n const image = new Image();\n image.src = urlPath;\n image.onload = () => (this._puckImage = image);\n }\n /**\n * Draws the Virtual Joystick's container\n */\n _drawContainer() {\n const jp = this._joystickPosition || this._joystickPointerStartPos;\n this._clearPreviousDraw();\n if (this._containerImage) {\n VirtualJoystick._VJCanvasContext.drawImage(this._containerImage, jp.x - this.containerSize, jp.y - this.containerSize, this.containerSize * 2, this.containerSize * 2);\n }\n else {\n // outer container\n VirtualJoystick._VJCanvasContext.beginPath();\n VirtualJoystick._VJCanvasContext.strokeStyle = this._joystickColor;\n VirtualJoystick._VJCanvasContext.lineWidth = 2;\n VirtualJoystick._VJCanvasContext.arc(jp.x, jp.y, this.containerSize, 0, Math.PI * 2, true);\n VirtualJoystick._VJCanvasContext.stroke();\n VirtualJoystick._VJCanvasContext.closePath();\n // inner container\n VirtualJoystick._VJCanvasContext.beginPath();\n VirtualJoystick._VJCanvasContext.lineWidth = 6;\n VirtualJoystick._VJCanvasContext.strokeStyle = this._joystickColor;\n VirtualJoystick._VJCanvasContext.arc(jp.x, jp.y, this.puckSize, 0, Math.PI * 2, true);\n VirtualJoystick._VJCanvasContext.stroke();\n VirtualJoystick._VJCanvasContext.closePath();\n }\n }\n /**\n * Draws the Virtual Joystick's puck\n */\n _drawPuck() {\n if (this._puckImage) {\n VirtualJoystick._VJCanvasContext.drawImage(this._puckImage, this._joystickPointerPos.x - this.puckSize, this._joystickPointerPos.y - this.puckSize, this.puckSize * 2, this.puckSize * 2);\n }\n else {\n VirtualJoystick._VJCanvasContext.beginPath();\n VirtualJoystick._VJCanvasContext.strokeStyle = this._joystickColor;\n VirtualJoystick._VJCanvasContext.lineWidth = 2;\n VirtualJoystick._VJCanvasContext.arc(this._joystickPointerPos.x, this._joystickPointerPos.y, this.puckSize, 0, Math.PI * 2, true);\n VirtualJoystick._VJCanvasContext.stroke();\n VirtualJoystick._VJCanvasContext.closePath();\n }\n }\n _drawVirtualJoystick() {\n // canvas released? don't continue iterating\n if (this._released) {\n return;\n }\n if (this.alwaysVisible) {\n this._drawContainer();\n }\n if (this.pressed) {\n this._touches.forEach((key, touch) => {\n if (touch.pointerId === this._joystickPointerId) {\n if (!this.alwaysVisible) {\n this._drawContainer();\n }\n this._drawPuck();\n // store current pointer for next clear\n this._joystickPreviousPointerPos = this._joystickPointerPos.clone();\n }\n else {\n VirtualJoystick._VJCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);\n VirtualJoystick._VJCanvasContext.beginPath();\n VirtualJoystick._VJCanvasContext.fillStyle = \"white\";\n VirtualJoystick._VJCanvasContext.beginPath();\n VirtualJoystick._VJCanvasContext.strokeStyle = \"red\";\n VirtualJoystick._VJCanvasContext.lineWidth = 6;\n VirtualJoystick._VJCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);\n VirtualJoystick._VJCanvasContext.stroke();\n VirtualJoystick._VJCanvasContext.closePath();\n touch.prevX = touch.x;\n touch.prevY = touch.y;\n }\n });\n }\n requestAnimationFrame(() => {\n this._drawVirtualJoystick();\n });\n }\n /**\n * Release internal HTML canvas\n */\n releaseCanvas() {\n if (VirtualJoystick.Canvas) {\n VirtualJoystick.Canvas.removeEventListener(\"pointerdown\", this._onPointerDownHandlerRef);\n VirtualJoystick.Canvas.removeEventListener(\"pointermove\", this._onPointerMoveHandlerRef);\n VirtualJoystick.Canvas.removeEventListener(\"pointerup\", this._onPointerUpHandlerRef);\n VirtualJoystick.Canvas.removeEventListener(\"pointerout\", this._onPointerUpHandlerRef);\n window.removeEventListener(\"resize\", this._onResize);\n document.body.removeChild(VirtualJoystick.Canvas);\n VirtualJoystick.Canvas = null;\n }\n this._released = true;\n }\n}\n// Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas\nVirtualJoystick._GlobalJoystickIndex = 0;\nVirtualJoystick._AlwaysVisibleSticks = 0;\n//# sourceMappingURL=virtualJoystick.js.map","import { Observable } from \"../../Misc/observable.js\";\nimport { Quaternion, Matrix, Vector3, TmpVectors } from \"../../Maths/math.vector.js\";\nimport { Ray } from \"../../Culling/ray.js\";\nimport { EngineStore } from \"../../Engines/engineStore.js\";\nimport { Gamepad } from \"../../Gamepads/gamepad.js\";\n/**\n * Defines the types of pose enabled controllers that are supported\n */\nexport var PoseEnabledControllerType;\n(function (PoseEnabledControllerType) {\n /**\n * HTC Vive\n */\n PoseEnabledControllerType[PoseEnabledControllerType[\"VIVE\"] = 0] = \"VIVE\";\n /**\n * Oculus Rift\n */\n PoseEnabledControllerType[PoseEnabledControllerType[\"OCULUS\"] = 1] = \"OCULUS\";\n /**\n * Windows mixed reality\n */\n PoseEnabledControllerType[PoseEnabledControllerType[\"WINDOWS\"] = 2] = \"WINDOWS\";\n /**\n * Samsung gear VR\n */\n PoseEnabledControllerType[PoseEnabledControllerType[\"GEAR_VR\"] = 3] = \"GEAR_VR\";\n /**\n * Google Daydream\n */\n PoseEnabledControllerType[PoseEnabledControllerType[\"DAYDREAM\"] = 4] = \"DAYDREAM\";\n /**\n * Generic\n */\n PoseEnabledControllerType[PoseEnabledControllerType[\"GENERIC\"] = 5] = \"GENERIC\";\n})(PoseEnabledControllerType || (PoseEnabledControllerType = {}));\n/**\n * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)\n */\nexport class PoseEnabledControllerHelper {\n /**\n * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)\n * @param vrGamepad the gamepad to initialized\n * @returns a vr controller of the type the gamepad identified as\n */\n static InitiateController(vrGamepad) {\n for (const factory of this._ControllerFactories) {\n if (factory.canCreate(vrGamepad)) {\n return factory.create(vrGamepad);\n }\n }\n if (this._DefaultControllerFactory) {\n return this._DefaultControllerFactory(vrGamepad);\n }\n throw \"The type of gamepad you are trying to load needs to be imported first or is not supported.\";\n }\n}\n/** @internal */\nPoseEnabledControllerHelper._ControllerFactories = [];\n/** @internal */\nPoseEnabledControllerHelper._DefaultControllerFactory = null;\n/**\n * Defines the PoseEnabledController object that contains state of a vr capable controller\n */\nexport class PoseEnabledController extends Gamepad {\n /**\n * @internal\n */\n _disableTrackPosition(fixedPosition) {\n if (this._trackPosition) {\n this._calculatedPosition.copyFrom(fixedPosition);\n this._trackPosition = false;\n }\n }\n /**\n * Creates a new PoseEnabledController from a gamepad\n * @param browserGamepad the gamepad that the PoseEnabledController should be created from\n */\n constructor(browserGamepad) {\n super(browserGamepad.id, browserGamepad.index, browserGamepad);\n /**\n * If the controller is used in a webXR session\n */\n this.isXR = false;\n // Represents device position and rotation in room space. Should only be used to help calculate babylon space values\n this._deviceRoomPosition = Vector3.Zero();\n this._deviceRoomRotationQuaternion = new Quaternion();\n /**\n * The device position in babylon space\n */\n this.devicePosition = Vector3.Zero();\n /**\n * The device rotation in babylon space\n */\n this.deviceRotationQuaternion = new Quaternion();\n /**\n * The scale factor of the device in babylon space\n */\n this.deviceScaleFactor = 1;\n // Used to convert 6dof controllers to 3dof\n this._trackPosition = true;\n this._maxRotationDistFromHeadset = Math.PI / 5;\n this._draggedRoomRotation = 0;\n this._leftHandSystemQuaternion = new Quaternion();\n /**\n * Internal, matrix used to convert room space to babylon space\n * @internal\n */\n this._deviceToWorld = Matrix.Identity();\n /**\n * Node to be used when casting a ray from the controller\n * @internal\n */\n this._pointingPoseNode = null;\n this._workingMatrix = Matrix.Identity();\n /**\n * @internal\n */\n this._meshAttachedObservable = new Observable();\n this.type = Gamepad.POSE_ENABLED;\n this.controllerType = PoseEnabledControllerType.GENERIC;\n this.position = Vector3.Zero();\n this.rotationQuaternion = new Quaternion();\n this._calculatedPosition = Vector3.Zero();\n this._calculatedRotation = new Quaternion();\n Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, this._leftHandSystemQuaternion);\n }\n /**\n * Updates the state of the pose enabled controller and mesh based on the current position and rotation of the controller\n */\n update() {\n super.update();\n this._updatePoseAndMesh();\n }\n /**\n * Updates only the pose device and mesh without doing any button event checking\n */\n _updatePoseAndMesh() {\n if (this.isXR) {\n return;\n }\n const pose = this.browserGamepad.pose;\n this.updateFromDevice(pose);\n if (!this._trackPosition &&\n EngineStore.LastCreatedScene &&\n EngineStore.LastCreatedScene.activeCamera &&\n EngineStore.LastCreatedScene.activeCamera.devicePosition) {\n const camera = EngineStore.LastCreatedScene.activeCamera;\n camera._computeDevicePosition();\n this._deviceToWorld.setTranslation(camera.devicePosition);\n if (camera.deviceRotationQuaternion) {\n camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(TmpVectors.Vector3[0]);\n // Find the radian distance away that the headset is from the controllers rotation\n const distanceAway = Math.atan2(Math.sin(TmpVectors.Vector3[0].y - this._draggedRoomRotation), Math.cos(TmpVectors.Vector3[0].y - this._draggedRoomRotation));\n if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {\n // Only rotate enouph to be within the _maxRotationDistFromHeadset\n const rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);\n this._draggedRoomRotation += rotationAmount;\n // Rotate controller around headset\n const sin = Math.sin(-rotationAmount);\n const cos = Math.cos(-rotationAmount);\n this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;\n this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;\n }\n }\n }\n Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);\n this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);\n Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);\n this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);\n if (this._mesh) {\n this._mesh.position.copyFrom(this.devicePosition);\n if (this._mesh.rotationQuaternion) {\n this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);\n }\n }\n }\n /**\n * Updates the state of the pose enbaled controller based on the raw pose data from the device\n * @param poseData raw pose fromthe device\n */\n updateFromDevice(poseData) {\n if (this.isXR) {\n return;\n }\n if (poseData) {\n this.rawPose = poseData;\n if (poseData.position) {\n this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);\n if (this._mesh && this._mesh.getScene().useRightHandedSystem) {\n this._deviceRoomPosition.z *= -1;\n }\n if (this._trackPosition) {\n this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);\n }\n this._calculatedPosition.addInPlace(this.position);\n }\n const pose = this.rawPose;\n if (poseData.orientation && pose.orientation && pose.orientation.length === 4) {\n this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);\n if (this._mesh) {\n if (this._mesh.getScene().useRightHandedSystem) {\n this._deviceRoomRotationQuaternion.z *= -1;\n this._deviceRoomRotationQuaternion.w *= -1;\n }\n else {\n this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);\n }\n }\n // if the camera is set, rotate to the camera's rotation\n this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);\n }\n }\n }\n /**\n * Attaches a mesh to the controller\n * @param mesh the mesh to be attached\n */\n attachToMesh(mesh) {\n if (this._mesh) {\n this._mesh.parent = null;\n }\n this._mesh = mesh;\n if (this._poseControlledCamera) {\n this._mesh.parent = this._poseControlledCamera;\n }\n if (!this._mesh.rotationQuaternion) {\n this._mesh.rotationQuaternion = new Quaternion();\n }\n // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh\n if (!this.isXR) {\n this._updatePoseAndMesh();\n if (this._pointingPoseNode) {\n const parents = [];\n let obj = this._pointingPoseNode;\n while (obj.parent) {\n parents.push(obj.parent);\n obj = obj.parent;\n }\n parents.reverse().forEach((p) => {\n p.computeWorldMatrix(true);\n });\n }\n }\n this._meshAttachedObservable.notifyObservers(mesh);\n }\n /**\n * Attaches the controllers mesh to a camera\n * @param camera the camera the mesh should be attached to\n */\n attachToPoseControlledCamera(camera) {\n this._poseControlledCamera = camera;\n if (this._mesh) {\n this._mesh.parent = this._poseControlledCamera;\n }\n }\n /**\n * Disposes of the controller\n */\n dispose() {\n if (this._mesh) {\n this._mesh.dispose();\n }\n this._mesh = null;\n super.dispose();\n }\n /**\n * The mesh that is attached to the controller\n */\n get mesh() {\n return this._mesh;\n }\n /**\n * Gets the ray of the controller in the direction the controller is pointing\n * @param length the length the resulting ray should be\n * @returns a ray in the direction the controller is pointing\n */\n getForwardRay(length = 100) {\n if (!this.mesh) {\n return new Ray(Vector3.Zero(), new Vector3(0, 0, 1), length);\n }\n const m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();\n const origin = m.getTranslation();\n const forward = new Vector3(0, 0, -1);\n const forwardWorld = Vector3.TransformNormal(forward, m);\n const direction = Vector3.Normalize(forwardWorld);\n return new Ray(origin, direction, length);\n }\n}\n/**\n * Name of the child mesh that can be used to cast a ray from the controller\n */\nPoseEnabledController.POINTING_POSE = \"POINTING_POSE\";\n//# sourceMappingURL=poseEnabledController.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { Gamepad } from \"../Gamepads/gamepad.js\";\n/**\n * Defines supported buttons for XBox360 compatible gamepads\n */\nexport var Xbox360Button;\n(function (Xbox360Button) {\n /** A */\n Xbox360Button[Xbox360Button[\"A\"] = 0] = \"A\";\n /** B */\n Xbox360Button[Xbox360Button[\"B\"] = 1] = \"B\";\n /** X */\n Xbox360Button[Xbox360Button[\"X\"] = 2] = \"X\";\n /** Y */\n Xbox360Button[Xbox360Button[\"Y\"] = 3] = \"Y\";\n /** Left button */\n Xbox360Button[Xbox360Button[\"LB\"] = 4] = \"LB\";\n /** Right button */\n Xbox360Button[Xbox360Button[\"RB\"] = 5] = \"RB\";\n /** Back */\n Xbox360Button[Xbox360Button[\"Back\"] = 8] = \"Back\";\n /** Start */\n Xbox360Button[Xbox360Button[\"Start\"] = 9] = \"Start\";\n /** Left stick */\n Xbox360Button[Xbox360Button[\"LeftStick\"] = 10] = \"LeftStick\";\n /** Right stick */\n Xbox360Button[Xbox360Button[\"RightStick\"] = 11] = \"RightStick\";\n})(Xbox360Button || (Xbox360Button = {}));\n/** Defines values for XBox360 DPad */\nexport var Xbox360Dpad;\n(function (Xbox360Dpad) {\n /** Up */\n Xbox360Dpad[Xbox360Dpad[\"Up\"] = 12] = \"Up\";\n /** Down */\n Xbox360Dpad[Xbox360Dpad[\"Down\"] = 13] = \"Down\";\n /** Left */\n Xbox360Dpad[Xbox360Dpad[\"Left\"] = 14] = \"Left\";\n /** Right */\n Xbox360Dpad[Xbox360Dpad[\"Right\"] = 15] = \"Right\";\n})(Xbox360Dpad || (Xbox360Dpad = {}));\n/**\n * Defines a XBox360 gamepad\n */\nexport class Xbox360Pad extends Gamepad {\n /**\n * Creates a new XBox360 gamepad object\n * @param id defines the id of this gamepad\n * @param index defines its index\n * @param gamepad defines the internal HTML gamepad object\n * @param xboxOne defines if it is a XBox One gamepad\n */\n constructor(id, index, gamepad, xboxOne = false) {\n super(id, index, gamepad, 0, 1, 2, 3);\n this._leftTrigger = 0;\n this._rightTrigger = 0;\n /** Observable raised when a button is pressed */\n this.onButtonDownObservable = new Observable();\n /** Observable raised when a button is released */\n this.onButtonUpObservable = new Observable();\n /** Observable raised when a pad is pressed */\n this.onPadDownObservable = new Observable();\n /** Observable raised when a pad is released */\n this.onPadUpObservable = new Observable();\n this._buttonA = 0;\n this._buttonB = 0;\n this._buttonX = 0;\n this._buttonY = 0;\n this._buttonBack = 0;\n this._buttonStart = 0;\n this._buttonLB = 0;\n this._buttonRB = 0;\n this._buttonLeftStick = 0;\n this._buttonRightStick = 0;\n this._dPadUp = 0;\n this._dPadDown = 0;\n this._dPadLeft = 0;\n this._dPadRight = 0;\n this._isXboxOnePad = false;\n this.type = Gamepad.XBOX;\n this._isXboxOnePad = xboxOne;\n }\n /**\n * Defines the callback to call when left trigger is pressed\n * @param callback defines the callback to use\n */\n onlefttriggerchanged(callback) {\n this._onlefttriggerchanged = callback;\n }\n /**\n * Defines the callback to call when right trigger is pressed\n * @param callback defines the callback to use\n */\n onrighttriggerchanged(callback) {\n this._onrighttriggerchanged = callback;\n }\n /**\n * Gets the left trigger value\n */\n get leftTrigger() {\n return this._leftTrigger;\n }\n /**\n * Sets the left trigger value\n */\n set leftTrigger(newValue) {\n if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {\n this._onlefttriggerchanged(newValue);\n }\n this._leftTrigger = newValue;\n }\n /**\n * Gets the right trigger value\n */\n get rightTrigger() {\n return this._rightTrigger;\n }\n /**\n * Sets the right trigger value\n */\n set rightTrigger(newValue) {\n if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {\n this._onrighttriggerchanged(newValue);\n }\n this._rightTrigger = newValue;\n }\n /**\n * Defines the callback to call when a button is pressed\n * @param callback defines the callback to use\n */\n onbuttondown(callback) {\n this._onbuttondown = callback;\n }\n /**\n * Defines the callback to call when a button is released\n * @param callback defines the callback to use\n */\n onbuttonup(callback) {\n this._onbuttonup = callback;\n }\n /**\n * Defines the callback to call when a pad is pressed\n * @param callback defines the callback to use\n */\n ondpaddown(callback) {\n this._ondpaddown = callback;\n }\n /**\n * Defines the callback to call when a pad is released\n * @param callback defines the callback to use\n */\n ondpadup(callback) {\n this._ondpadup = callback;\n }\n _setButtonValue(newValue, currentValue, buttonType) {\n if (newValue !== currentValue) {\n if (newValue === 1) {\n if (this._onbuttondown) {\n this._onbuttondown(buttonType);\n }\n this.onButtonDownObservable.notifyObservers(buttonType);\n }\n if (newValue === 0) {\n if (this._onbuttonup) {\n this._onbuttonup(buttonType);\n }\n this.onButtonUpObservable.notifyObservers(buttonType);\n }\n }\n return newValue;\n }\n _setDPadValue(newValue, currentValue, buttonType) {\n if (newValue !== currentValue) {\n if (newValue === 1) {\n if (this._ondpaddown) {\n this._ondpaddown(buttonType);\n }\n this.onPadDownObservable.notifyObservers(buttonType);\n }\n if (newValue === 0) {\n if (this._ondpadup) {\n this._ondpadup(buttonType);\n }\n this.onPadUpObservable.notifyObservers(buttonType);\n }\n }\n return newValue;\n }\n /**\n * Gets the value of the `A` button\n */\n get buttonA() {\n return this._buttonA;\n }\n /**\n * Sets the value of the `A` button\n */\n set buttonA(value) {\n this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);\n }\n /**\n * Gets the value of the `B` button\n */\n get buttonB() {\n return this._buttonB;\n }\n /**\n * Sets the value of the `B` button\n */\n set buttonB(value) {\n this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);\n }\n /**\n * Gets the value of the `X` button\n */\n get buttonX() {\n return this._buttonX;\n }\n /**\n * Sets the value of the `X` button\n */\n set buttonX(value) {\n this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);\n }\n /**\n * Gets the value of the `Y` button\n */\n get buttonY() {\n return this._buttonY;\n }\n /**\n * Sets the value of the `Y` button\n */\n set buttonY(value) {\n this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);\n }\n /**\n * Gets the value of the `Start` button\n */\n get buttonStart() {\n return this._buttonStart;\n }\n /**\n * Sets the value of the `Start` button\n */\n set buttonStart(value) {\n this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);\n }\n /**\n * Gets the value of the `Back` button\n */\n get buttonBack() {\n return this._buttonBack;\n }\n /**\n * Sets the value of the `Back` button\n */\n set buttonBack(value) {\n this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);\n }\n /**\n * Gets the value of the `Left` button\n */\n get buttonLB() {\n return this._buttonLB;\n }\n /**\n * Sets the value of the `Left` button\n */\n set buttonLB(value) {\n this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);\n }\n /**\n * Gets the value of the `Right` button\n */\n get buttonRB() {\n return this._buttonRB;\n }\n /**\n * Sets the value of the `Right` button\n */\n set buttonRB(value) {\n this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);\n }\n /**\n * Gets the value of the Left joystick\n */\n get buttonLeftStick() {\n return this._buttonLeftStick;\n }\n /**\n * Sets the value of the Left joystick\n */\n set buttonLeftStick(value) {\n this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);\n }\n /**\n * Gets the value of the Right joystick\n */\n get buttonRightStick() {\n return this._buttonRightStick;\n }\n /**\n * Sets the value of the Right joystick\n */\n set buttonRightStick(value) {\n this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);\n }\n /**\n * Gets the value of D-pad up\n */\n get dPadUp() {\n return this._dPadUp;\n }\n /**\n * Sets the value of D-pad up\n */\n set dPadUp(value) {\n this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);\n }\n /**\n * Gets the value of D-pad down\n */\n get dPadDown() {\n return this._dPadDown;\n }\n /**\n * Sets the value of D-pad down\n */\n set dPadDown(value) {\n this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);\n }\n /**\n * Gets the value of D-pad left\n */\n get dPadLeft() {\n return this._dPadLeft;\n }\n /**\n * Sets the value of D-pad left\n */\n set dPadLeft(value) {\n this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);\n }\n /**\n * Gets the value of D-pad right\n */\n get dPadRight() {\n return this._dPadRight;\n }\n /**\n * Sets the value of D-pad right\n */\n set dPadRight(value) {\n this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);\n }\n /**\n * Force the gamepad to synchronize with device values\n */\n update() {\n super.update();\n if (this._isXboxOnePad) {\n this.buttonA = this.browserGamepad.buttons[0].value;\n this.buttonB = this.browserGamepad.buttons[1].value;\n this.buttonX = this.browserGamepad.buttons[2].value;\n this.buttonY = this.browserGamepad.buttons[3].value;\n this.buttonLB = this.browserGamepad.buttons[4].value;\n this.buttonRB = this.browserGamepad.buttons[5].value;\n this.leftTrigger = this.browserGamepad.buttons[6].value;\n this.rightTrigger = this.browserGamepad.buttons[7].value;\n this.buttonBack = this.browserGamepad.buttons[8].value;\n this.buttonStart = this.browserGamepad.buttons[9].value;\n this.buttonLeftStick = this.browserGamepad.buttons[10].value;\n this.buttonRightStick = this.browserGamepad.buttons[11].value;\n this.dPadUp = this.browserGamepad.buttons[12].value;\n this.dPadDown = this.browserGamepad.buttons[13].value;\n this.dPadLeft = this.browserGamepad.buttons[14].value;\n this.dPadRight = this.browserGamepad.buttons[15].value;\n }\n else {\n this.buttonA = this.browserGamepad.buttons[0].value;\n this.buttonB = this.browserGamepad.buttons[1].value;\n this.buttonX = this.browserGamepad.buttons[2].value;\n this.buttonY = this.browserGamepad.buttons[3].value;\n this.buttonLB = this.browserGamepad.buttons[4].value;\n this.buttonRB = this.browserGamepad.buttons[5].value;\n this.leftTrigger = this.browserGamepad.buttons[6].value;\n this.rightTrigger = this.browserGamepad.buttons[7].value;\n this.buttonBack = this.browserGamepad.buttons[8].value;\n this.buttonStart = this.browserGamepad.buttons[9].value;\n this.buttonLeftStick = this.browserGamepad.buttons[10].value;\n this.buttonRightStick = this.browserGamepad.buttons[11].value;\n this.dPadUp = this.browserGamepad.buttons[12].value;\n this.dPadDown = this.browserGamepad.buttons[13].value;\n this.dPadLeft = this.browserGamepad.buttons[14].value;\n this.dPadRight = this.browserGamepad.buttons[15].value;\n }\n }\n /**\n * Disposes the gamepad\n */\n dispose() {\n super.dispose();\n this.onButtonDownObservable.clear();\n this.onButtonUpObservable.clear();\n this.onPadDownObservable.clear();\n this.onPadUpObservable.clear();\n }\n}\n//# sourceMappingURL=xboxGamepad.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { Gamepad } from \"./gamepad.js\";\n/**\n * Defines supported buttons for DualShock compatible gamepads\n */\nexport var DualShockButton;\n(function (DualShockButton) {\n /** Cross */\n DualShockButton[DualShockButton[\"Cross\"] = 0] = \"Cross\";\n /** Circle */\n DualShockButton[DualShockButton[\"Circle\"] = 1] = \"Circle\";\n /** Square */\n DualShockButton[DualShockButton[\"Square\"] = 2] = \"Square\";\n /** Triangle */\n DualShockButton[DualShockButton[\"Triangle\"] = 3] = \"Triangle\";\n /** L1 */\n DualShockButton[DualShockButton[\"L1\"] = 4] = \"L1\";\n /** R1 */\n DualShockButton[DualShockButton[\"R1\"] = 5] = \"R1\";\n /** Share */\n DualShockButton[DualShockButton[\"Share\"] = 8] = \"Share\";\n /** Options */\n DualShockButton[DualShockButton[\"Options\"] = 9] = \"Options\";\n /** Left stick */\n DualShockButton[DualShockButton[\"LeftStick\"] = 10] = \"LeftStick\";\n /** Right stick */\n DualShockButton[DualShockButton[\"RightStick\"] = 11] = \"RightStick\";\n})(DualShockButton || (DualShockButton = {}));\n/** Defines values for DualShock DPad */\nexport var DualShockDpad;\n(function (DualShockDpad) {\n /** Up */\n DualShockDpad[DualShockDpad[\"Up\"] = 12] = \"Up\";\n /** Down */\n DualShockDpad[DualShockDpad[\"Down\"] = 13] = \"Down\";\n /** Left */\n DualShockDpad[DualShockDpad[\"Left\"] = 14] = \"Left\";\n /** Right */\n DualShockDpad[DualShockDpad[\"Right\"] = 15] = \"Right\";\n})(DualShockDpad || (DualShockDpad = {}));\n/**\n * Defines a DualShock gamepad\n */\nexport class DualShockPad extends Gamepad {\n /**\n * Creates a new DualShock gamepad object\n * @param id defines the id of this gamepad\n * @param index defines its index\n * @param gamepad defines the internal HTML gamepad object\n */\n constructor(id, index, gamepad) {\n super(id.replace(\"STANDARD GAMEPAD\", \"SONY PLAYSTATION DUALSHOCK\"), index, gamepad, 0, 1, 2, 3);\n this._leftTrigger = 0;\n this._rightTrigger = 0;\n /** Observable raised when a button is pressed */\n this.onButtonDownObservable = new Observable();\n /** Observable raised when a button is released */\n this.onButtonUpObservable = new Observable();\n /** Observable raised when a pad is pressed */\n this.onPadDownObservable = new Observable();\n /** Observable raised when a pad is released */\n this.onPadUpObservable = new Observable();\n this._buttonCross = 0;\n this._buttonCircle = 0;\n this._buttonSquare = 0;\n this._buttonTriangle = 0;\n this._buttonShare = 0;\n this._buttonOptions = 0;\n this._buttonL1 = 0;\n this._buttonR1 = 0;\n this._buttonLeftStick = 0;\n this._buttonRightStick = 0;\n this._dPadUp = 0;\n this._dPadDown = 0;\n this._dPadLeft = 0;\n this._dPadRight = 0;\n this.type = Gamepad.DUALSHOCK;\n }\n /**\n * Defines the callback to call when left trigger is pressed\n * @param callback defines the callback to use\n */\n onlefttriggerchanged(callback) {\n this._onlefttriggerchanged = callback;\n }\n /**\n * Defines the callback to call when right trigger is pressed\n * @param callback defines the callback to use\n */\n onrighttriggerchanged(callback) {\n this._onrighttriggerchanged = callback;\n }\n /**\n * Gets the left trigger value\n */\n get leftTrigger() {\n return this._leftTrigger;\n }\n /**\n * Sets the left trigger value\n */\n set leftTrigger(newValue) {\n if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {\n this._onlefttriggerchanged(newValue);\n }\n this._leftTrigger = newValue;\n }\n /**\n * Gets the right trigger value\n */\n get rightTrigger() {\n return this._rightTrigger;\n }\n /**\n * Sets the right trigger value\n */\n set rightTrigger(newValue) {\n if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {\n this._onrighttriggerchanged(newValue);\n }\n this._rightTrigger = newValue;\n }\n /**\n * Defines the callback to call when a button is pressed\n * @param callback defines the callback to use\n */\n onbuttondown(callback) {\n this._onbuttondown = callback;\n }\n /**\n * Defines the callback to call when a button is released\n * @param callback defines the callback to use\n */\n onbuttonup(callback) {\n this._onbuttonup = callback;\n }\n /**\n * Defines the callback to call when a pad is pressed\n * @param callback defines the callback to use\n */\n ondpaddown(callback) {\n this._ondpaddown = callback;\n }\n /**\n * Defines the callback to call when a pad is released\n * @param callback defines the callback to use\n */\n ondpadup(callback) {\n this._ondpadup = callback;\n }\n _setButtonValue(newValue, currentValue, buttonType) {\n if (newValue !== currentValue) {\n if (newValue === 1) {\n if (this._onbuttondown) {\n this._onbuttondown(buttonType);\n }\n this.onButtonDownObservable.notifyObservers(buttonType);\n }\n if (newValue === 0) {\n if (this._onbuttonup) {\n this._onbuttonup(buttonType);\n }\n this.onButtonUpObservable.notifyObservers(buttonType);\n }\n }\n return newValue;\n }\n _setDPadValue(newValue, currentValue, buttonType) {\n if (newValue !== currentValue) {\n if (newValue === 1) {\n if (this._ondpaddown) {\n this._ondpaddown(buttonType);\n }\n this.onPadDownObservable.notifyObservers(buttonType);\n }\n if (newValue === 0) {\n if (this._ondpadup) {\n this._ondpadup(buttonType);\n }\n this.onPadUpObservable.notifyObservers(buttonType);\n }\n }\n return newValue;\n }\n /**\n * Gets the value of the `Cross` button\n */\n get buttonCross() {\n return this._buttonCross;\n }\n /**\n * Sets the value of the `Cross` button\n */\n set buttonCross(value) {\n this._buttonCross = this._setButtonValue(value, this._buttonCross, DualShockButton.Cross);\n }\n /**\n * Gets the value of the `Circle` button\n */\n get buttonCircle() {\n return this._buttonCircle;\n }\n /**\n * Sets the value of the `Circle` button\n */\n set buttonCircle(value) {\n this._buttonCircle = this._setButtonValue(value, this._buttonCircle, DualShockButton.Circle);\n }\n /**\n * Gets the value of the `Square` button\n */\n get buttonSquare() {\n return this._buttonSquare;\n }\n /**\n * Sets the value of the `Square` button\n */\n set buttonSquare(value) {\n this._buttonSquare = this._setButtonValue(value, this._buttonSquare, DualShockButton.Square);\n }\n /**\n * Gets the value of the `Triangle` button\n */\n get buttonTriangle() {\n return this._buttonTriangle;\n }\n /**\n * Sets the value of the `Triangle` button\n */\n set buttonTriangle(value) {\n this._buttonTriangle = this._setButtonValue(value, this._buttonTriangle, DualShockButton.Triangle);\n }\n /**\n * Gets the value of the `Options` button\n */\n get buttonOptions() {\n return this._buttonOptions;\n }\n /**\n * Sets the value of the `Options` button\n */\n set buttonOptions(value) {\n this._buttonOptions = this._setButtonValue(value, this._buttonOptions, DualShockButton.Options);\n }\n /**\n * Gets the value of the `Share` button\n */\n get buttonShare() {\n return this._buttonShare;\n }\n /**\n * Sets the value of the `Share` button\n */\n set buttonShare(value) {\n this._buttonShare = this._setButtonValue(value, this._buttonShare, DualShockButton.Share);\n }\n /**\n * Gets the value of the `L1` button\n */\n get buttonL1() {\n return this._buttonL1;\n }\n /**\n * Sets the value of the `L1` button\n */\n set buttonL1(value) {\n this._buttonL1 = this._setButtonValue(value, this._buttonL1, DualShockButton.L1);\n }\n /**\n * Gets the value of the `R1` button\n */\n get buttonR1() {\n return this._buttonR1;\n }\n /**\n * Sets the value of the `R1` button\n */\n set buttonR1(value) {\n this._buttonR1 = this._setButtonValue(value, this._buttonR1, DualShockButton.R1);\n }\n /**\n * Gets the value of the Left joystick\n */\n get buttonLeftStick() {\n return this._buttonLeftStick;\n }\n /**\n * Sets the value of the Left joystick\n */\n set buttonLeftStick(value) {\n this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, DualShockButton.LeftStick);\n }\n /**\n * Gets the value of the Right joystick\n */\n get buttonRightStick() {\n return this._buttonRightStick;\n }\n /**\n * Sets the value of the Right joystick\n */\n set buttonRightStick(value) {\n this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, DualShockButton.RightStick);\n }\n /**\n * Gets the value of D-pad up\n */\n get dPadUp() {\n return this._dPadUp;\n }\n /**\n * Sets the value of D-pad up\n */\n set dPadUp(value) {\n this._dPadUp = this._setDPadValue(value, this._dPadUp, DualShockDpad.Up);\n }\n /**\n * Gets the value of D-pad down\n */\n get dPadDown() {\n return this._dPadDown;\n }\n /**\n * Sets the value of D-pad down\n */\n set dPadDown(value) {\n this._dPadDown = this._setDPadValue(value, this._dPadDown, DualShockDpad.Down);\n }\n /**\n * Gets the value of D-pad left\n */\n get dPadLeft() {\n return this._dPadLeft;\n }\n /**\n * Sets the value of D-pad left\n */\n set dPadLeft(value) {\n this._dPadLeft = this._setDPadValue(value, this._dPadLeft, DualShockDpad.Left);\n }\n /**\n * Gets the value of D-pad right\n */\n get dPadRight() {\n return this._dPadRight;\n }\n /**\n * Sets the value of D-pad right\n */\n set dPadRight(value) {\n this._dPadRight = this._setDPadValue(value, this._dPadRight, DualShockDpad.Right);\n }\n /**\n * Force the gamepad to synchronize with device values\n */\n update() {\n super.update();\n this.buttonCross = this.browserGamepad.buttons[0].value;\n this.buttonCircle = this.browserGamepad.buttons[1].value;\n this.buttonSquare = this.browserGamepad.buttons[2].value;\n this.buttonTriangle = this.browserGamepad.buttons[3].value;\n this.buttonL1 = this.browserGamepad.buttons[4].value;\n this.buttonR1 = this.browserGamepad.buttons[5].value;\n this.leftTrigger = this.browserGamepad.buttons[6].value;\n this.rightTrigger = this.browserGamepad.buttons[7].value;\n this.buttonShare = this.browserGamepad.buttons[8].value;\n this.buttonOptions = this.browserGamepad.buttons[9].value;\n this.buttonLeftStick = this.browserGamepad.buttons[10].value;\n this.buttonRightStick = this.browserGamepad.buttons[11].value;\n this.dPadUp = this.browserGamepad.buttons[12].value;\n this.dPadDown = this.browserGamepad.buttons[13].value;\n this.dPadLeft = this.browserGamepad.buttons[14].value;\n this.dPadRight = this.browserGamepad.buttons[15].value;\n }\n /**\n * Disposes the gamepad\n */\n dispose() {\n super.dispose();\n this.onButtonDownObservable.clear();\n this.onButtonUpObservable.clear();\n this.onPadDownObservable.clear();\n this.onPadUpObservable.clear();\n }\n}\n//# sourceMappingURL=dualShockGamepad.js.map","import { VirtualJoystick, JoystickAxis } from \"../../Misc/virtualJoystick.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { Matrix, Vector3 } from \"../../Maths/math.vector.js\";\nimport { FreeCameraInputsManager } from \"../../Cameras/freeCameraInputsManager.js\";\n/**\n * Add virtual joystick input support to the input manager.\n * @returns the current input manager\n */\nFreeCameraInputsManager.prototype.addVirtualJoystick = function () {\n this.add(new FreeCameraVirtualJoystickInput());\n return this;\n};\n/**\n * Manage the Virtual Joystick inputs to control the movement of a free camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FreeCameraVirtualJoystickInput {\n /**\n * Gets the left stick of the virtual joystick.\n * @returns The virtual Joystick\n */\n getLeftJoystick() {\n return this._leftjoystick;\n }\n /**\n * Gets the right stick of the virtual joystick.\n * @returns The virtual Joystick\n */\n getRightJoystick() {\n return this._rightjoystick;\n }\n /**\n * Update the current camera state depending on the inputs that have been used this frame.\n * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.\n */\n checkInputs() {\n if (this._leftjoystick) {\n const camera = this.camera;\n const speed = camera._computeLocalCameraSpeed() * 50;\n const cameraTransform = Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);\n const deltaTransform = Vector3.TransformCoordinates(new Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);\n camera.cameraDirection = camera.cameraDirection.add(deltaTransform);\n camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);\n if (!this._leftjoystick.pressed) {\n this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);\n }\n if (!this._rightjoystick.pressed) {\n this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);\n }\n }\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n */\n attachControl() {\n this._leftjoystick = new VirtualJoystick(true);\n this._leftjoystick.setAxisForUpDown(JoystickAxis.Z);\n this._leftjoystick.setAxisForLeftRight(JoystickAxis.X);\n this._leftjoystick.setJoystickSensibility(0.15);\n this._rightjoystick = new VirtualJoystick(false);\n this._rightjoystick.setAxisForUpDown(JoystickAxis.X);\n this._rightjoystick.setAxisForLeftRight(JoystickAxis.Y);\n this._rightjoystick.reverseUpDown = true;\n this._rightjoystick.setJoystickSensibility(0.05);\n this._rightjoystick.setJoystickColor(\"yellow\");\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n this._leftjoystick.releaseCanvas();\n this._rightjoystick.releaseCanvas();\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"FreeCameraVirtualJoystickInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"virtualJoystick\";\n }\n}\nCameraInputTypes[\"FreeCameraVirtualJoystickInput\"] = FreeCameraVirtualJoystickInput;\n//# sourceMappingURL=freeCameraVirtualJoystickInput.js.map","export * from \"./BaseCameraMouseWheelInput.js\";\nexport * from \"./BaseCameraPointersInput.js\";\nexport * from \"./arcRotateCameraGamepadInput.js\";\nexport * from \"./arcRotateCameraKeyboardMoveInput.js\";\nexport * from \"./arcRotateCameraMouseWheelInput.js\";\nexport * from \"./arcRotateCameraPointersInput.js\";\nexport * from \"./arcRotateCameraVRDeviceOrientationInput.js\";\nexport * from \"./flyCameraKeyboardInput.js\";\nexport * from \"./flyCameraMouseInput.js\";\nexport * from \"./followCameraKeyboardMoveInput.js\";\nexport * from \"./followCameraMouseWheelInput.js\";\nexport * from \"./followCameraPointersInput.js\";\nexport * from \"./freeCameraDeviceOrientationInput.js\";\nexport * from \"./freeCameraGamepadInput.js\";\nexport * from \"./freeCameraKeyboardMoveInput.js\";\nexport * from \"./freeCameraMouseInput.js\";\nexport * from \"./freeCameraMouseWheelInput.js\";\nexport * from \"./freeCameraTouchInput.js\";\nexport * from \"./freeCameraVirtualJoystickInput.js\";\n//# sourceMappingURL=index.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize, serializeAsVector3, serializeAsMeshReference } from \"../Misc/decorators.js\";\nimport { Camera } from \"./camera.js\";\nimport { Quaternion, Matrix, Vector3, Vector2, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Epsilon } from \"../Maths/math.constants.js\";\nimport { Axis } from \"../Maths/math.axis.js\";\n/**\n * A target camera takes a mesh or position as a target and continues to look at it while it moves.\n * This is the base of the follow, arc rotate cameras and Free camera\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras\n */\nexport class TargetCamera extends Camera {\n /**\n * Instantiates a target camera that takes a mesh or position as a target and continues to look at it while it moves.\n * This is the base of the follow, arc rotate cameras and Free camera\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras\n * @param name Defines the name of the camera in the scene\n * @param position Defines the start position of the camera in the scene\n * @param scene Defines the scene the camera belongs to\n * @param setActiveOnSceneIfNoneActive Defines whether the camera should be marked as active if not other active cameras have been defined\n */\n constructor(name, position, scene, setActiveOnSceneIfNoneActive = true) {\n super(name, position, scene, setActiveOnSceneIfNoneActive);\n this._tmpUpVector = Vector3.Zero();\n this._tmpTargetVector = Vector3.Zero();\n /**\n * Define the current direction the camera is moving to\n */\n this.cameraDirection = new Vector3(0, 0, 0);\n /**\n * Define the current rotation the camera is rotating to\n */\n this.cameraRotation = new Vector2(0, 0);\n /** Gets or sets a boolean indicating that the scaling of the parent hierarchy will not be taken in account by the camera */\n this.ignoreParentScaling = false;\n /**\n * When set, the up vector of the camera will be updated by the rotation of the camera\n */\n this.updateUpVectorFromRotation = false;\n this._tmpQuaternion = new Quaternion();\n /**\n * Define the current rotation of the camera\n */\n this.rotation = new Vector3(0, 0, 0);\n /**\n * Define the current speed of the camera\n */\n this.speed = 2.0;\n /**\n * Add constraint to the camera to prevent it to move freely in all directions and\n * around all axis.\n */\n this.noRotationConstraint = false;\n /**\n * Reverses mouselook direction to 'natural' panning as opposed to traditional direct\n * panning\n */\n this.invertRotation = false;\n /**\n * Speed multiplier for inverse camera panning\n */\n this.inverseRotationSpeed = 0.2;\n /**\n * Define the current target of the camera as an object or a position.\n * Please note that locking a target will disable panning.\n */\n this.lockedTarget = null;\n /** @internal */\n this._currentTarget = Vector3.Zero();\n /** @internal */\n this._initialFocalDistance = 1;\n /** @internal */\n this._viewMatrix = Matrix.Zero();\n /** @internal */\n this._camMatrix = Matrix.Zero();\n /** @internal */\n this._cameraTransformMatrix = Matrix.Zero();\n /** @internal */\n this._cameraRotationMatrix = Matrix.Zero();\n /** @internal */\n this._referencePoint = new Vector3(0, 0, 1);\n /** @internal */\n this._transformedReferencePoint = Vector3.Zero();\n this._defaultUp = Vector3.Up();\n this._cachedRotationZ = 0;\n this._cachedQuaternionRotationZ = 0;\n }\n /**\n * Gets the position in front of the camera at a given distance.\n * @param distance The distance from the camera we want the position to be\n * @returns the position\n */\n getFrontPosition(distance) {\n this.getWorldMatrix();\n const direction = this.getTarget().subtract(this.position);\n direction.normalize();\n direction.scaleInPlace(distance);\n return this.globalPosition.add(direction);\n }\n /** @internal */\n _getLockedTargetPosition() {\n if (!this.lockedTarget) {\n return null;\n }\n if (this.lockedTarget.absolutePosition) {\n const lockedTarget = this.lockedTarget;\n const m = lockedTarget.computeWorldMatrix();\n // in some cases the absolute position resets externally, but doesn't update since the matrix is cached.\n m.getTranslationToRef(lockedTarget.absolutePosition);\n }\n return this.lockedTarget.absolutePosition || this.lockedTarget;\n }\n /**\n * Store current camera state of the camera (fov, position, rotation, etc..)\n * @returns the camera\n */\n storeState() {\n this._storedPosition = this.position.clone();\n this._storedRotation = this.rotation.clone();\n if (this.rotationQuaternion) {\n this._storedRotationQuaternion = this.rotationQuaternion.clone();\n }\n return super.storeState();\n }\n /**\n * Restored camera state. You must call storeState() first\n * @returns whether it was successful or not\n * @internal\n */\n _restoreStateValues() {\n if (!super._restoreStateValues()) {\n return false;\n }\n this.position = this._storedPosition.clone();\n this.rotation = this._storedRotation.clone();\n if (this.rotationQuaternion) {\n this.rotationQuaternion = this._storedRotationQuaternion.clone();\n }\n this.cameraDirection.copyFromFloats(0, 0, 0);\n this.cameraRotation.copyFromFloats(0, 0);\n return true;\n }\n /** @internal */\n _initCache() {\n super._initCache();\n this._cache.lockedTarget = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._cache.rotation = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._cache.rotationQuaternion = new Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n }\n /**\n * @internal\n */\n _updateCache(ignoreParentClass) {\n if (!ignoreParentClass) {\n super._updateCache();\n }\n const lockedTargetPosition = this._getLockedTargetPosition();\n if (!lockedTargetPosition) {\n this._cache.lockedTarget = null;\n }\n else {\n if (!this._cache.lockedTarget) {\n this._cache.lockedTarget = lockedTargetPosition.clone();\n }\n else {\n this._cache.lockedTarget.copyFrom(lockedTargetPosition);\n }\n }\n this._cache.rotation.copyFrom(this.rotation);\n if (this.rotationQuaternion) {\n this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);\n }\n }\n // Synchronized\n /** @internal */\n _isSynchronizedViewMatrix() {\n if (!super._isSynchronizedViewMatrix()) {\n return false;\n }\n const lockedTargetPosition = this._getLockedTargetPosition();\n return ((this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) &&\n (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation)));\n }\n // Methods\n /** @internal */\n _computeLocalCameraSpeed() {\n const engine = this.getEngine();\n return this.speed * Math.sqrt(engine.getDeltaTime() / (engine.getFps() * 100.0));\n }\n // Target\n /**\n * Defines the target the camera should look at.\n * @param target Defines the new target as a Vector\n */\n setTarget(target) {\n this.upVector.normalize();\n this._initialFocalDistance = target.subtract(this.position).length();\n if (this.position.z === target.z) {\n this.position.z += Epsilon;\n }\n this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance);\n Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);\n this._camMatrix.invert();\n this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);\n const vDir = target.subtract(this.position);\n if (vDir.x >= 0.0) {\n this.rotation.y = -Math.atan(vDir.z / vDir.x) + Math.PI / 2.0;\n }\n else {\n this.rotation.y = -Math.atan(vDir.z / vDir.x) - Math.PI / 2.0;\n }\n this.rotation.z = 0;\n if (isNaN(this.rotation.x)) {\n this.rotation.x = 0;\n }\n if (isNaN(this.rotation.y)) {\n this.rotation.y = 0;\n }\n if (isNaN(this.rotation.z)) {\n this.rotation.z = 0;\n }\n if (this.rotationQuaternion) {\n Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);\n }\n }\n /**\n * Defines the target point of the camera.\n * The camera looks towards it form the radius distance.\n */\n get target() {\n return this.getTarget();\n }\n set target(value) {\n this.setTarget(value);\n }\n /**\n * Return the current target position of the camera. This value is expressed in local space.\n * @returns the target position\n */\n getTarget() {\n return this._currentTarget;\n }\n /** @internal */\n _decideIfNeedsToMove() {\n return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;\n }\n /** @internal */\n _updatePosition() {\n if (this.parent) {\n this.parent.getWorldMatrix().invertToRef(TmpVectors.Matrix[0]);\n Vector3.TransformNormalToRef(this.cameraDirection, TmpVectors.Matrix[0], TmpVectors.Vector3[0]);\n this.position.addInPlace(TmpVectors.Vector3[0]);\n return;\n }\n this.position.addInPlace(this.cameraDirection);\n }\n /** @internal */\n _checkInputs() {\n const directionMultiplier = this.invertRotation ? -this.inverseRotationSpeed : 1.0;\n const needToMove = this._decideIfNeedsToMove();\n const needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;\n // Move\n if (needToMove) {\n this._updatePosition();\n }\n // Rotate\n if (needToRotate) {\n //rotate, if quaternion is set and rotation was used\n if (this.rotationQuaternion) {\n this.rotationQuaternion.toEulerAnglesToRef(this.rotation);\n }\n this.rotation.x += this.cameraRotation.x * directionMultiplier;\n this.rotation.y += this.cameraRotation.y * directionMultiplier;\n // Apply constraints\n if (!this.noRotationConstraint) {\n const limit = 1.570796;\n if (this.rotation.x > limit) {\n this.rotation.x = limit;\n }\n if (this.rotation.x < -limit) {\n this.rotation.x = -limit;\n }\n }\n //rotate, if quaternion is set and rotation was used\n if (this.rotationQuaternion) {\n const len = this.rotation.lengthSquared();\n if (len) {\n Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);\n }\n }\n }\n // Inertia\n if (needToMove) {\n if (Math.abs(this.cameraDirection.x) < this.speed * Epsilon) {\n this.cameraDirection.x = 0;\n }\n if (Math.abs(this.cameraDirection.y) < this.speed * Epsilon) {\n this.cameraDirection.y = 0;\n }\n if (Math.abs(this.cameraDirection.z) < this.speed * Epsilon) {\n this.cameraDirection.z = 0;\n }\n this.cameraDirection.scaleInPlace(this.inertia);\n }\n if (needToRotate) {\n if (Math.abs(this.cameraRotation.x) < this.speed * Epsilon) {\n this.cameraRotation.x = 0;\n }\n if (Math.abs(this.cameraRotation.y) < this.speed * Epsilon) {\n this.cameraRotation.y = 0;\n }\n this.cameraRotation.scaleInPlace(this.inertia);\n }\n super._checkInputs();\n }\n _updateCameraRotationMatrix() {\n if (this.rotationQuaternion) {\n this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);\n }\n else {\n Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);\n }\n }\n /**\n * Update the up vector to apply the rotation of the camera (So if you changed the camera rotation.z this will let you update the up vector as well)\n * @returns the current camera\n */\n _rotateUpVectorWithCameraRotationMatrix() {\n Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);\n return this;\n }\n /** @internal */\n _getViewMatrix() {\n if (this.lockedTarget) {\n this.setTarget(this._getLockedTargetPosition());\n }\n // Compute\n this._updateCameraRotationMatrix();\n // Apply the changed rotation to the upVector\n if (this.rotationQuaternion && this._cachedQuaternionRotationZ != this.rotationQuaternion.z) {\n this._rotateUpVectorWithCameraRotationMatrix();\n this._cachedQuaternionRotationZ = this.rotationQuaternion.z;\n }\n else if (this._cachedRotationZ !== this.rotation.z) {\n this._rotateUpVectorWithCameraRotationMatrix();\n this._cachedRotationZ = this.rotation.z;\n }\n Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);\n // Computing target and final matrix\n this.position.addToRef(this._transformedReferencePoint, this._currentTarget);\n if (this.updateUpVectorFromRotation) {\n if (this.rotationQuaternion) {\n Axis.Y.rotateByQuaternionToRef(this.rotationQuaternion, this.upVector);\n }\n else {\n Quaternion.FromEulerVectorToRef(this.rotation, this._tmpQuaternion);\n Axis.Y.rotateByQuaternionToRef(this._tmpQuaternion, this.upVector);\n }\n }\n this._computeViewMatrix(this.position, this._currentTarget, this.upVector);\n return this._viewMatrix;\n }\n _computeViewMatrix(position, target, up) {\n if (this.ignoreParentScaling) {\n if (this.parent) {\n const parentWorldMatrix = this.parent.getWorldMatrix();\n Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);\n Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._tmpTargetVector);\n Vector3.TransformNormalToRef(up, parentWorldMatrix, this._tmpUpVector);\n this._markSyncedWithParent();\n }\n else {\n this._globalPosition.copyFrom(position);\n this._tmpTargetVector.copyFrom(target);\n this._tmpUpVector.copyFrom(up);\n }\n if (this.getScene().useRightHandedSystem) {\n Matrix.LookAtRHToRef(this._globalPosition, this._tmpTargetVector, this._tmpUpVector, this._viewMatrix);\n }\n else {\n Matrix.LookAtLHToRef(this._globalPosition, this._tmpTargetVector, this._tmpUpVector, this._viewMatrix);\n }\n return;\n }\n if (this.getScene().useRightHandedSystem) {\n Matrix.LookAtRHToRef(position, target, up, this._viewMatrix);\n }\n else {\n Matrix.LookAtLHToRef(position, target, up, this._viewMatrix);\n }\n if (this.parent) {\n const parentWorldMatrix = this.parent.getWorldMatrix();\n this._viewMatrix.invert();\n this._viewMatrix.multiplyToRef(parentWorldMatrix, this._viewMatrix);\n this._viewMatrix.getTranslationToRef(this._globalPosition);\n this._viewMatrix.invert();\n this._markSyncedWithParent();\n }\n else {\n this._globalPosition.copyFrom(position);\n }\n }\n /**\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n createRigCamera(name, cameraIndex) {\n if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {\n const rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());\n rigCamera.isRigCamera = true;\n rigCamera.rigParent = this;\n if (this.cameraRigMode === Camera.RIG_MODE_VR || this.cameraRigMode === Camera.RIG_MODE_WEBVR) {\n if (!this.rotationQuaternion) {\n this.rotationQuaternion = new Quaternion();\n }\n rigCamera._cameraRigParams = {};\n rigCamera.rotationQuaternion = new Quaternion();\n }\n rigCamera.mode = this.mode;\n rigCamera.orthoLeft = this.orthoLeft;\n rigCamera.orthoRight = this.orthoRight;\n rigCamera.orthoTop = this.orthoTop;\n rigCamera.orthoBottom = this.orthoBottom;\n return rigCamera;\n }\n return null;\n }\n /**\n * @internal\n */\n _updateRigCameras() {\n const camLeft = this._rigCameras[0];\n const camRight = this._rigCameras[1];\n this.computeWorldMatrix();\n switch (this.cameraRigMode) {\n case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:\n case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:\n case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:\n case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:\n case Camera.RIG_MODE_STEREOSCOPIC_INTERLACED: {\n //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:\n const leftSign = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED ? 1 : -1;\n const rightSign = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED ? -1 : 1;\n this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft);\n this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle * rightSign, camRight);\n break;\n }\n case Camera.RIG_MODE_VR:\n if (camLeft.rotationQuaternion) {\n camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);\n camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);\n }\n else {\n camLeft.rotation.copyFrom(this.rotation);\n camRight.rotation.copyFrom(this.rotation);\n }\n camLeft.position.copyFrom(this.position);\n camRight.position.copyFrom(this.position);\n break;\n }\n super._updateRigCameras();\n }\n _getRigCamPositionAndTarget(halfSpace, rigCamera) {\n const target = this.getTarget();\n target.subtractToRef(this.position, TargetCamera._TargetFocalPoint);\n TargetCamera._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance);\n const newFocalTarget = TargetCamera._TargetFocalPoint.addInPlace(this.position);\n Matrix.TranslationToRef(-newFocalTarget.x, -newFocalTarget.y, -newFocalTarget.z, TargetCamera._TargetTransformMatrix);\n TargetCamera._TargetTransformMatrix.multiplyToRef(Matrix.RotationAxis(rigCamera.upVector, halfSpace), TargetCamera._RigCamTransformMatrix);\n Matrix.TranslationToRef(newFocalTarget.x, newFocalTarget.y, newFocalTarget.z, TargetCamera._TargetTransformMatrix);\n TargetCamera._RigCamTransformMatrix.multiplyToRef(TargetCamera._TargetTransformMatrix, TargetCamera._RigCamTransformMatrix);\n Vector3.TransformCoordinatesToRef(this.position, TargetCamera._RigCamTransformMatrix, rigCamera.position);\n rigCamera.setTarget(newFocalTarget);\n }\n /**\n * Gets the current object class name.\n * @returns the class name\n */\n getClassName() {\n return \"TargetCamera\";\n }\n}\nTargetCamera._RigCamTransformMatrix = new Matrix();\nTargetCamera._TargetTransformMatrix = new Matrix();\nTargetCamera._TargetFocalPoint = new Vector3();\n__decorate([\n serializeAsVector3()\n], TargetCamera.prototype, \"rotation\", void 0);\n__decorate([\n serialize()\n], TargetCamera.prototype, \"speed\", void 0);\n__decorate([\n serializeAsMeshReference(\"lockedTargetId\")\n], TargetCamera.prototype, \"lockedTarget\", void 0);\n//# sourceMappingURL=targetCamera.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serializeAsVector3, serialize } from \"../Misc/decorators.js\";\nimport { Vector3, Vector2 } from \"../Maths/math.vector.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { TargetCamera } from \"./targetCamera.js\";\nimport { FreeCameraInputsManager } from \"./freeCameraInputsManager.js\";\nimport { Tools } from \"../Misc/tools.js\";\n/**\n * This represents a free type of camera. It can be useful in First Person Shooter game for instance.\n * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera\n */\nexport class FreeCamera extends TargetCamera {\n /**\n * Gets the input sensibility for a mouse input. (default is 2000.0)\n * Higher values reduce sensitivity.\n */\n get angularSensibility() {\n const mouse = this.inputs.attached[\"mouse\"];\n if (mouse) {\n return mouse.angularSensibility;\n }\n return 0;\n }\n /**\n * Sets the input sensibility for a mouse input. (default is 2000.0)\n * Higher values reduce sensitivity.\n */\n set angularSensibility(value) {\n const mouse = this.inputs.attached[\"mouse\"];\n if (mouse) {\n mouse.angularSensibility = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control the forward move of the camera.\n */\n get keysUp() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysUp;\n }\n return [];\n }\n set keysUp(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysUp = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control the upward move of the camera.\n */\n get keysUpward() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysUpward;\n }\n return [];\n }\n set keysUpward(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysUpward = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control the backward move of the camera.\n */\n get keysDown() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysDown;\n }\n return [];\n }\n set keysDown(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysDown = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control the downward move of the camera.\n */\n get keysDownward() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysDownward;\n }\n return [];\n }\n set keysDownward(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysDownward = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.\n */\n get keysLeft() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysLeft;\n }\n return [];\n }\n set keysLeft(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysLeft = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.\n */\n get keysRight() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysRight;\n }\n return [];\n }\n set keysRight(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysRight = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control the left rotation move of the camera.\n */\n get keysRotateLeft() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysRotateLeft;\n }\n return [];\n }\n set keysRotateLeft(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysRotateLeft = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control the right rotation move of the camera.\n */\n get keysRotateRight() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysRotateRight;\n }\n return [];\n }\n set keysRotateRight(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysRotateRight = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control the up rotation move of the camera.\n */\n get keysRotateUp() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysRotateUp;\n }\n return [];\n }\n set keysRotateUp(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysRotateUp = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control the down rotation move of the camera.\n */\n get keysRotateDown() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysRotateDown;\n }\n return [];\n }\n set keysRotateDown(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysRotateDown = value;\n }\n }\n /**\n * Instantiates a Free Camera.\n * This represents a free type of camera. It can be useful in First Person Shooter game for instance.\n * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera\n * @param name Define the name of the camera in the scene\n * @param position Define the start position of the camera in the scene\n * @param scene Define the scene the camera belongs to\n * @param setActiveOnSceneIfNoneActive Defines whether the camera should be marked as active if not other active cameras have been defined\n */\n constructor(name, position, scene, setActiveOnSceneIfNoneActive = true) {\n super(name, position, scene, setActiveOnSceneIfNoneActive);\n /**\n * Define the collision ellipsoid of the camera.\n * This is helpful to simulate a camera body like the player body around the camera\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions#arcrotatecamera\n */\n this.ellipsoid = new Vector3(0.5, 1, 0.5);\n /**\n * Define an offset for the position of the ellipsoid around the camera.\n * This can be helpful to determine the center of the body near the gravity center of the body\n * instead of its head.\n */\n this.ellipsoidOffset = new Vector3(0, 0, 0);\n /**\n * Enable or disable collisions of the camera with the rest of the scene objects.\n */\n this.checkCollisions = false;\n /**\n * Enable or disable gravity on the camera.\n */\n this.applyGravity = false;\n this._needMoveForGravity = false;\n this._oldPosition = Vector3.Zero();\n this._diffPosition = Vector3.Zero();\n this._newPosition = Vector3.Zero();\n // Collisions\n this._collisionMask = -1;\n this._onCollisionPositionChange = (collisionId, newPosition, collidedMesh = null) => {\n const updatePosition = (newPos) => {\n this._newPosition.copyFrom(newPos);\n this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);\n if (this._diffPosition.length() > Engine.CollisionsEpsilon) {\n this.position.addInPlace(this._diffPosition);\n if (this.onCollide && collidedMesh) {\n this.onCollide(collidedMesh);\n }\n }\n };\n updatePosition(newPosition);\n };\n this.inputs = new FreeCameraInputsManager(this);\n this.inputs.addKeyboard().addMouse();\n }\n /**\n * Attached controls to the current camera.\n * @param ignored defines an ignored parameter kept for backward compatibility.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(ignored, noPreventDefault) {\n // eslint-disable-next-line prefer-rest-params\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n this.inputs.attachElement(noPreventDefault);\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n this.inputs.detachElement();\n this.cameraDirection = new Vector3(0, 0, 0);\n this.cameraRotation = new Vector2(0, 0);\n }\n /**\n * Define a collision mask to limit the list of object the camera can collide with\n */\n get collisionMask() {\n return this._collisionMask;\n }\n set collisionMask(mask) {\n this._collisionMask = !isNaN(mask) ? mask : -1;\n }\n /**\n * @internal\n */\n _collideWithWorld(displacement) {\n let globalPosition;\n if (this.parent) {\n globalPosition = Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());\n }\n else {\n globalPosition = this.position;\n }\n globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);\n this._oldPosition.addInPlace(this.ellipsoidOffset);\n const coordinator = this.getScene().collisionCoordinator;\n if (!this._collider) {\n this._collider = coordinator.createCollider();\n }\n this._collider._radius = this.ellipsoid;\n this._collider.collisionMask = this._collisionMask;\n //no need for clone, as long as gravity is not on.\n let actualDisplacement = displacement;\n //add gravity to the direction to prevent the dual-collision checking\n if (this.applyGravity) {\n //this prevents mending with cameraDirection, a global variable of the free camera class.\n actualDisplacement = displacement.add(this.getScene().gravity);\n }\n coordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);\n }\n /** @internal */\n _checkInputs() {\n if (!this._localDirection) {\n this._localDirection = Vector3.Zero();\n this._transformedDirection = Vector3.Zero();\n }\n this.inputs.checkInputs();\n super._checkInputs();\n }\n /**\n * Enable movement without a user input. This allows gravity to always be applied.\n */\n set needMoveForGravity(value) {\n this._needMoveForGravity = value;\n }\n /**\n * When true, gravity is applied whether there is user input or not.\n */\n get needMoveForGravity() {\n return this._needMoveForGravity;\n }\n /** @internal */\n _decideIfNeedsToMove() {\n return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;\n }\n /** @internal */\n _updatePosition() {\n if (this.checkCollisions && this.getScene().collisionsEnabled) {\n this._collideWithWorld(this.cameraDirection);\n }\n else {\n super._updatePosition();\n }\n }\n /**\n * Destroy the camera and release the current resources hold by it.\n */\n dispose() {\n this.inputs.clear();\n super.dispose();\n }\n /**\n * Gets the current object class name.\n * @returns the class name\n */\n getClassName() {\n return \"FreeCamera\";\n }\n}\n__decorate([\n serializeAsVector3()\n], FreeCamera.prototype, \"ellipsoid\", void 0);\n__decorate([\n serializeAsVector3()\n], FreeCamera.prototype, \"ellipsoidOffset\", void 0);\n__decorate([\n serialize()\n], FreeCamera.prototype, \"checkCollisions\", void 0);\n__decorate([\n serialize()\n], FreeCamera.prototype, \"applyGravity\", void 0);\n//# sourceMappingURL=freeCamera.js.map","import { FreeCamera } from \"./freeCamera.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Node } from \"../node.js\";\nNode.AddNodeConstructor(\"TouchCamera\", (name, scene) => {\n return () => new TouchCamera(name, Vector3.Zero(), scene);\n});\n/**\n * This represents a FPS type of camera controlled by touch.\n * This is like a universal camera minus the Gamepad controls.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera\n */\nexport class TouchCamera extends FreeCamera {\n /**\n * Defines the touch sensibility for rotation.\n * The higher the faster.\n */\n get touchAngularSensibility() {\n const touch = this.inputs.attached[\"touch\"];\n if (touch) {\n return touch.touchAngularSensibility;\n }\n return 0;\n }\n set touchAngularSensibility(value) {\n const touch = this.inputs.attached[\"touch\"];\n if (touch) {\n touch.touchAngularSensibility = value;\n }\n }\n /**\n * Defines the touch sensibility for move.\n * The higher the faster.\n */\n get touchMoveSensibility() {\n const touch = this.inputs.attached[\"touch\"];\n if (touch) {\n return touch.touchMoveSensibility;\n }\n return 0;\n }\n set touchMoveSensibility(value) {\n const touch = this.inputs.attached[\"touch\"];\n if (touch) {\n touch.touchMoveSensibility = value;\n }\n }\n /**\n * Instantiates a new touch camera.\n * This represents a FPS type of camera controlled by touch.\n * This is like a universal camera minus the Gamepad controls.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera\n * @param name Define the name of the camera in the scene\n * @param position Define the start position of the camera in the scene\n * @param scene Define the scene the camera belongs to\n */\n constructor(name, position, scene) {\n super(name, position, scene);\n this.inputs.addTouch();\n this._setupInputs();\n }\n /**\n * Gets the current object class name.\n * @returns the class name\n */\n getClassName() {\n return \"TouchCamera\";\n }\n /** @internal */\n _setupInputs() {\n const touch = this.inputs.attached[\"touch\"];\n const mouse = this.inputs.attached[\"mouse\"];\n if (mouse) {\n mouse.touchEnabled = false;\n }\n else {\n touch.allowMouse = true;\n }\n }\n}\n//# sourceMappingURL=touchCamera.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize, serializeAsVector3, serializeAsMeshReference, serializeAsVector2 } from \"../Misc/decorators.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Matrix, Vector3, Vector2 } from \"../Maths/math.vector.js\";\nimport { Node } from \"../node.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { AutoRotationBehavior } from \"../Behaviors/Cameras/autoRotationBehavior.js\";\nimport { BouncingBehavior } from \"../Behaviors/Cameras/bouncingBehavior.js\";\nimport { FramingBehavior } from \"../Behaviors/Cameras/framingBehavior.js\";\nimport { Camera } from \"./camera.js\";\nimport { TargetCamera } from \"./targetCamera.js\";\nimport { ArcRotateCameraInputsManager } from \"../Cameras/arcRotateCameraInputsManager.js\";\nimport { Epsilon } from \"../Maths/math.constants.js\";\nimport { Tools } from \"../Misc/tools.js\";\nNode.AddNodeConstructor(\"ArcRotateCamera\", (name, scene) => {\n return () => new ArcRotateCamera(name, 0, 0, 1.0, Vector3.Zero(), scene);\n});\n/**\n * This represents an orbital type of camera.\n *\n * This camera always points towards a given target position and can be rotated around that target with the target as the centre of rotation. It can be controlled with cursors and mouse, or with touch events.\n * Think of this camera as one orbiting its target position, or more imaginatively as a spy satellite orbiting the earth. Its position relative to the target (earth) can be set by three parameters, alpha (radians) the longitudinal rotation, beta (radians) the latitudinal rotation and radius the distance from the target position.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#arc-rotate-camera\n */\nexport class ArcRotateCamera extends TargetCamera {\n /**\n * Defines the target point of the camera.\n * The camera looks towards it from the radius distance.\n */\n get target() {\n return this._target;\n }\n set target(value) {\n this.setTarget(value);\n }\n /**\n * Defines the target mesh of the camera.\n * The camera looks towards it from the radius distance.\n * Please note that setting a target host will disable panning.\n */\n get targetHost() {\n return this._targetHost;\n }\n set targetHost(value) {\n if (value) {\n this.setTarget(value);\n }\n }\n /**\n * Return the current target position of the camera. This value is expressed in local space.\n * @returns the target position\n */\n getTarget() {\n return this.target;\n }\n /**\n * Define the current local position of the camera in the scene\n */\n get position() {\n return this._position;\n }\n set position(newPosition) {\n this.setPosition(newPosition);\n }\n /**\n * The vector the camera should consider as up. (default is Vector3(0, 1, 0) as returned by Vector3.Up())\n * Setting this will copy the given vector to the camera's upVector, and set rotation matrices to and from Y up.\n * DO NOT set the up vector using copyFrom or copyFromFloats, as this bypasses setting the above matrices.\n */\n set upVector(vec) {\n if (!this._upToYMatrix) {\n this._yToUpMatrix = new Matrix();\n this._upToYMatrix = new Matrix();\n this._upVector = Vector3.Zero();\n }\n vec.normalize();\n this._upVector.copyFrom(vec);\n this.setMatUp();\n }\n get upVector() {\n return this._upVector;\n }\n /**\n * Sets the Y-up to camera up-vector rotation matrix, and the up-vector to Y-up rotation matrix.\n */\n setMatUp() {\n // from y-up to custom-up (used in _getViewMatrix)\n Matrix.RotationAlignToRef(Vector3.UpReadOnly, this._upVector, this._yToUpMatrix);\n // from custom-up to y-up (used in rebuildAnglesAndRadius)\n Matrix.RotationAlignToRef(this._upVector, Vector3.UpReadOnly, this._upToYMatrix);\n }\n //-- begin properties for backward compatibility for inputs\n /**\n * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.\n */\n get angularSensibilityX() {\n const pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n return pointers.angularSensibilityX;\n }\n return 0;\n }\n set angularSensibilityX(value) {\n const pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n pointers.angularSensibilityX = value;\n }\n }\n /**\n * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.\n */\n get angularSensibilityY() {\n const pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n return pointers.angularSensibilityY;\n }\n return 0;\n }\n set angularSensibilityY(value) {\n const pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n pointers.angularSensibilityY = value;\n }\n }\n /**\n * Gets or Set the pointer pinch precision or how fast is the camera zooming.\n */\n get pinchPrecision() {\n const pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n return pointers.pinchPrecision;\n }\n return 0;\n }\n set pinchPrecision(value) {\n const pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n pointers.pinchPrecision = value;\n }\n }\n /**\n * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.\n * It will be used instead of pinchDeltaPrecision if different from 0.\n * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.\n */\n get pinchDeltaPercentage() {\n const pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n return pointers.pinchDeltaPercentage;\n }\n return 0;\n }\n set pinchDeltaPercentage(value) {\n const pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n pointers.pinchDeltaPercentage = value;\n }\n }\n /**\n * Gets or Set the pointer use natural pinch zoom to override the pinch precision\n * and pinch delta percentage.\n * When useNaturalPinchZoom is true, multi touch zoom will zoom in such\n * that any object in the plane at the camera's target point will scale\n * perfectly with finger motion.\n */\n get useNaturalPinchZoom() {\n const pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n return pointers.useNaturalPinchZoom;\n }\n return false;\n }\n set useNaturalPinchZoom(value) {\n const pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n pointers.useNaturalPinchZoom = value;\n }\n }\n /**\n * Gets or Set the pointer panning sensibility or how fast is the camera moving.\n */\n get panningSensibility() {\n const pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n return pointers.panningSensibility;\n }\n return 0;\n }\n set panningSensibility(value) {\n const pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n pointers.panningSensibility = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.\n */\n get keysUp() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysUp;\n }\n return [];\n }\n set keysUp(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysUp = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.\n */\n get keysDown() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysDown;\n }\n return [];\n }\n set keysDown(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysDown = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.\n */\n get keysLeft() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysLeft;\n }\n return [];\n }\n set keysLeft(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysLeft = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.\n */\n get keysRight() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysRight;\n }\n return [];\n }\n set keysRight(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysRight = value;\n }\n }\n /**\n * Gets or Set the mouse wheel precision or how fast is the camera zooming.\n */\n get wheelPrecision() {\n const mousewheel = this.inputs.attached[\"mousewheel\"];\n if (mousewheel) {\n return mousewheel.wheelPrecision;\n }\n return 0;\n }\n set wheelPrecision(value) {\n const mousewheel = this.inputs.attached[\"mousewheel\"];\n if (mousewheel) {\n mousewheel.wheelPrecision = value;\n }\n }\n /**\n * Gets or Set the boolean value that controls whether or not the mouse wheel\n * zooms to the location of the mouse pointer or not. The default is false.\n */\n get zoomToMouseLocation() {\n const mousewheel = this.inputs.attached[\"mousewheel\"];\n if (mousewheel) {\n return mousewheel.zoomToMouseLocation;\n }\n return false;\n }\n set zoomToMouseLocation(value) {\n const mousewheel = this.inputs.attached[\"mousewheel\"];\n if (mousewheel) {\n mousewheel.zoomToMouseLocation = value;\n }\n }\n /**\n * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.\n * It will be used instead of pinchDeltaPrecision if different from 0.\n * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.\n */\n get wheelDeltaPercentage() {\n const mousewheel = this.inputs.attached[\"mousewheel\"];\n if (mousewheel) {\n return mousewheel.wheelDeltaPercentage;\n }\n return 0;\n }\n set wheelDeltaPercentage(value) {\n const mousewheel = this.inputs.attached[\"mousewheel\"];\n if (mousewheel) {\n mousewheel.wheelDeltaPercentage = value;\n }\n }\n /**\n * Gets the bouncing behavior of the camera if it has been enabled.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#bouncing-behavior\n */\n get bouncingBehavior() {\n return this._bouncingBehavior;\n }\n /**\n * Defines if the bouncing behavior of the camera is enabled on the camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#bouncing-behavior\n */\n get useBouncingBehavior() {\n return this._bouncingBehavior != null;\n }\n set useBouncingBehavior(value) {\n if (value === this.useBouncingBehavior) {\n return;\n }\n if (value) {\n this._bouncingBehavior = new BouncingBehavior();\n this.addBehavior(this._bouncingBehavior);\n }\n else if (this._bouncingBehavior) {\n this.removeBehavior(this._bouncingBehavior);\n this._bouncingBehavior = null;\n }\n }\n /**\n * Gets the framing behavior of the camera if it has been enabled.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#framing-behavior\n */\n get framingBehavior() {\n return this._framingBehavior;\n }\n /**\n * Defines if the framing behavior of the camera is enabled on the camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#framing-behavior\n */\n get useFramingBehavior() {\n return this._framingBehavior != null;\n }\n set useFramingBehavior(value) {\n if (value === this.useFramingBehavior) {\n return;\n }\n if (value) {\n this._framingBehavior = new FramingBehavior();\n this.addBehavior(this._framingBehavior);\n }\n else if (this._framingBehavior) {\n this.removeBehavior(this._framingBehavior);\n this._framingBehavior = null;\n }\n }\n /**\n * Gets the auto rotation behavior of the camera if it has been enabled.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#autorotation-behavior\n */\n get autoRotationBehavior() {\n return this._autoRotationBehavior;\n }\n /**\n * Defines if the auto rotation behavior of the camera is enabled on the camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#autorotation-behavior\n */\n get useAutoRotationBehavior() {\n return this._autoRotationBehavior != null;\n }\n set useAutoRotationBehavior(value) {\n if (value === this.useAutoRotationBehavior) {\n return;\n }\n if (value) {\n this._autoRotationBehavior = new AutoRotationBehavior();\n this.addBehavior(this._autoRotationBehavior);\n }\n else if (this._autoRotationBehavior) {\n this.removeBehavior(this._autoRotationBehavior);\n this._autoRotationBehavior = null;\n }\n }\n /**\n * Instantiates a new ArcRotateCamera in a given scene\n * @param name Defines the name of the camera\n * @param alpha Defines the camera rotation along the longitudinal axis\n * @param beta Defines the camera rotation along the latitudinal axis\n * @param radius Defines the camera distance from its target\n * @param target Defines the camera target\n * @param scene Defines the scene the camera belongs to\n * @param setActiveOnSceneIfNoneActive Defines whether the camera should be marked as active if not other active cameras have been defined\n */\n constructor(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive = true) {\n super(name, Vector3.Zero(), scene, setActiveOnSceneIfNoneActive);\n /**\n * Current inertia value on the longitudinal axis.\n * The bigger this number the longer it will take for the camera to stop.\n */\n this.inertialAlphaOffset = 0;\n /**\n * Current inertia value on the latitudinal axis.\n * The bigger this number the longer it will take for the camera to stop.\n */\n this.inertialBetaOffset = 0;\n /**\n * Current inertia value on the radius axis.\n * The bigger this number the longer it will take for the camera to stop.\n */\n this.inertialRadiusOffset = 0;\n /**\n * Minimum allowed angle on the longitudinal axis.\n * This can help limiting how the Camera is able to move in the scene.\n */\n this.lowerAlphaLimit = null;\n /**\n * Maximum allowed angle on the longitudinal axis.\n * This can help limiting how the Camera is able to move in the scene.\n */\n this.upperAlphaLimit = null;\n /**\n * Minimum allowed angle on the latitudinal axis.\n * This can help limiting how the Camera is able to move in the scene.\n */\n this.lowerBetaLimit = 0.01;\n /**\n * Maximum allowed angle on the latitudinal axis.\n * This can help limiting how the Camera is able to move in the scene.\n */\n this.upperBetaLimit = Math.PI - 0.01;\n /**\n * Minimum allowed distance of the camera to the target (The camera can not get closer).\n * This can help limiting how the Camera is able to move in the scene.\n */\n this.lowerRadiusLimit = null;\n /**\n * Maximum allowed distance of the camera to the target (The camera can not get further).\n * This can help limiting how the Camera is able to move in the scene.\n */\n this.upperRadiusLimit = null;\n /**\n * Defines the current inertia value used during panning of the camera along the X axis.\n */\n this.inertialPanningX = 0;\n /**\n * Defines the current inertia value used during panning of the camera along the Y axis.\n */\n this.inertialPanningY = 0;\n /**\n * Defines the distance used to consider the camera in pan mode vs pinch/zoom.\n * Basically if your fingers moves away from more than this distance you will be considered\n * in pinch mode.\n */\n this.pinchToPanMaxDistance = 20;\n /**\n * Defines the maximum distance the camera can pan.\n * This could help keeping the camera always in your scene.\n */\n this.panningDistanceLimit = null;\n /**\n * Defines the target of the camera before panning.\n */\n this.panningOriginTarget = Vector3.Zero();\n /**\n * Defines the value of the inertia used during panning.\n * 0 would mean stop inertia and one would mean no deceleration at all.\n */\n this.panningInertia = 0.9;\n //-- end properties for backward compatibility for inputs\n /**\n * Defines how much the radius should be scaled while zooming on a particular mesh (through the zoomOn function)\n */\n this.zoomOnFactor = 1;\n /**\n * Defines a screen offset for the camera position.\n */\n this.targetScreenOffset = Vector2.Zero();\n /**\n * Allows the camera to be completely reversed.\n * If false the camera can not arrive upside down.\n */\n this.allowUpsideDown = true;\n /**\n * Define if double tap/click is used to restore the previously saved state of the camera.\n */\n this.useInputToRestoreState = true;\n /** @internal */\n this._viewMatrix = new Matrix();\n /**\n * Defines the allowed panning axis.\n */\n this.panningAxis = new Vector3(1, 1, 0);\n this._transformedDirection = new Vector3();\n /**\n * Defines if camera will eliminate transform on y axis.\n */\n this.mapPanning = false;\n /**\n * Observable triggered when the mesh target has been changed on the camera.\n */\n this.onMeshTargetChangedObservable = new Observable();\n /**\n * Defines whether the camera should check collision with the objects oh the scene.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions#how-can-i-do-this-\n */\n this.checkCollisions = false;\n /**\n * Defines the collision radius of the camera.\n * This simulates a sphere around the camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions#arcrotatecamera\n */\n this.collisionRadius = new Vector3(0.5, 0.5, 0.5);\n this._previousPosition = Vector3.Zero();\n this._collisionVelocity = Vector3.Zero();\n this._newPosition = Vector3.Zero();\n this._computationVector = Vector3.Zero();\n this._onCollisionPositionChange = (collisionId, newPosition, collidedMesh = null) => {\n if (!collidedMesh) {\n this._previousPosition.copyFrom(this._position);\n }\n else {\n this.setPosition(newPosition);\n if (this.onCollide) {\n this.onCollide(collidedMesh);\n }\n }\n // Recompute because of constraints\n const cosa = Math.cos(this.alpha);\n const sina = Math.sin(this.alpha);\n const cosb = Math.cos(this.beta);\n let sinb = Math.sin(this.beta);\n if (sinb === 0) {\n sinb = 0.0001;\n }\n const target = this._getTargetPosition();\n this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);\n target.addToRef(this._computationVector, this._newPosition);\n this._position.copyFrom(this._newPosition);\n let up = this.upVector;\n if (this.allowUpsideDown && this.beta < 0) {\n up = up.clone();\n up = up.negate();\n }\n this._computeViewMatrix(this._position, target, up);\n this._viewMatrix.addAtIndex(12, this.targetScreenOffset.x);\n this._viewMatrix.addAtIndex(13, this.targetScreenOffset.y);\n this._collisionTriggered = false;\n };\n this._target = Vector3.Zero();\n if (target) {\n this.setTarget(target);\n }\n this.alpha = alpha;\n this.beta = beta;\n this.radius = radius;\n this.getViewMatrix();\n this.inputs = new ArcRotateCameraInputsManager(this);\n this.inputs.addKeyboard().addMouseWheel().addPointers();\n }\n // Cache\n /** @internal */\n _initCache() {\n super._initCache();\n this._cache._target = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._cache.alpha = undefined;\n this._cache.beta = undefined;\n this._cache.radius = undefined;\n this._cache.targetScreenOffset = Vector2.Zero();\n }\n /**\n * @internal\n */\n _updateCache(ignoreParentClass) {\n if (!ignoreParentClass) {\n super._updateCache();\n }\n this._cache._target.copyFrom(this._getTargetPosition());\n this._cache.alpha = this.alpha;\n this._cache.beta = this.beta;\n this._cache.radius = this.radius;\n this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);\n }\n _getTargetPosition() {\n if (this._targetHost && this._targetHost.getAbsolutePosition) {\n const pos = this._targetHost.getAbsolutePosition();\n if (this._targetBoundingCenter) {\n pos.addToRef(this._targetBoundingCenter, this._target);\n }\n else {\n this._target.copyFrom(pos);\n }\n }\n const lockedTargetPosition = this._getLockedTargetPosition();\n if (lockedTargetPosition) {\n return lockedTargetPosition;\n }\n return this._target;\n }\n /**\n * Stores the current state of the camera (alpha, beta, radius and target)\n * @returns the camera itself\n */\n storeState() {\n this._storedAlpha = this.alpha;\n this._storedBeta = this.beta;\n this._storedRadius = this.radius;\n this._storedTarget = this._getTargetPosition().clone();\n this._storedTargetScreenOffset = this.targetScreenOffset.clone();\n return super.storeState();\n }\n /**\n * @internal\n * Restored camera state. You must call storeState() first\n */\n _restoreStateValues() {\n if (!super._restoreStateValues()) {\n return false;\n }\n this.setTarget(this._storedTarget.clone());\n this.alpha = this._storedAlpha;\n this.beta = this._storedBeta;\n this.radius = this._storedRadius;\n this.targetScreenOffset = this._storedTargetScreenOffset.clone();\n this.inertialAlphaOffset = 0;\n this.inertialBetaOffset = 0;\n this.inertialRadiusOffset = 0;\n this.inertialPanningX = 0;\n this.inertialPanningY = 0;\n return true;\n }\n // Synchronized\n /** @internal */\n _isSynchronizedViewMatrix() {\n if (!super._isSynchronizedViewMatrix()) {\n return false;\n }\n return (this._cache._target.equals(this._getTargetPosition()) &&\n this._cache.alpha === this.alpha &&\n this._cache.beta === this.beta &&\n this._cache.radius === this.radius &&\n this._cache.targetScreenOffset.equals(this.targetScreenOffset));\n }\n /**\n * Attached controls to the current camera.\n * @param ignored defines an ignored parameter kept for backward compatibility.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n * @param useCtrlForPanning Defines whether ctrl is used for panning within the controls\n * @param panningMouseButton Defines whether panning is allowed through mouse click button\n */\n attachControl(ignored, noPreventDefault, useCtrlForPanning = true, panningMouseButton = 2) {\n // eslint-disable-next-line prefer-rest-params\n const args = arguments;\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(args);\n this._useCtrlForPanning = useCtrlForPanning;\n this._panningMouseButton = panningMouseButton;\n // backwards compatibility\n if (typeof args[0] === \"boolean\") {\n if (args.length > 1) {\n this._useCtrlForPanning = args[1];\n }\n if (args.length > 2) {\n this._panningMouseButton = args[2];\n }\n }\n this.inputs.attachElement(noPreventDefault);\n this._reset = () => {\n this.inertialAlphaOffset = 0;\n this.inertialBetaOffset = 0;\n this.inertialRadiusOffset = 0;\n this.inertialPanningX = 0;\n this.inertialPanningY = 0;\n };\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n this.inputs.detachElement();\n if (this._reset) {\n this._reset();\n }\n }\n /** @internal */\n _checkInputs() {\n //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.\n if (this._collisionTriggered) {\n return;\n }\n this.inputs.checkInputs();\n // Inertia\n if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {\n const directionModifier = this.invertRotation ? -1 : 1;\n let inertialAlphaOffset = this.inertialAlphaOffset;\n if (this.beta <= 0) {\n inertialAlphaOffset *= -1;\n }\n if (this.getScene().useRightHandedSystem) {\n inertialAlphaOffset *= -1;\n }\n if (this.parent && this.parent._getWorldMatrixDeterminant() < 0) {\n inertialAlphaOffset *= -1;\n }\n this.alpha += inertialAlphaOffset * directionModifier;\n this.beta += this.inertialBetaOffset * directionModifier;\n this.radius -= this.inertialRadiusOffset;\n this.inertialAlphaOffset *= this.inertia;\n this.inertialBetaOffset *= this.inertia;\n this.inertialRadiusOffset *= this.inertia;\n if (Math.abs(this.inertialAlphaOffset) < Epsilon) {\n this.inertialAlphaOffset = 0;\n }\n if (Math.abs(this.inertialBetaOffset) < Epsilon) {\n this.inertialBetaOffset = 0;\n }\n if (Math.abs(this.inertialRadiusOffset) < this.speed * Epsilon) {\n this.inertialRadiusOffset = 0;\n }\n }\n // Panning inertia\n if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {\n const localDirection = new Vector3(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);\n this._viewMatrix.invertToRef(this._cameraTransformMatrix);\n localDirection.multiplyInPlace(this.panningAxis);\n Vector3.TransformNormalToRef(localDirection, this._cameraTransformMatrix, this._transformedDirection);\n // Eliminate y if mapPanning is enabled\n if (this.mapPanning || !this.panningAxis.y) {\n this._transformedDirection.y = 0;\n }\n if (!this._targetHost) {\n if (this.panningDistanceLimit) {\n this._transformedDirection.addInPlace(this._target);\n const distanceSquared = Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);\n if (distanceSquared <= this.panningDistanceLimit * this.panningDistanceLimit) {\n this._target.copyFrom(this._transformedDirection);\n }\n }\n else {\n this._target.addInPlace(this._transformedDirection);\n }\n }\n this.inertialPanningX *= this.panningInertia;\n this.inertialPanningY *= this.panningInertia;\n if (Math.abs(this.inertialPanningX) < this.speed * Epsilon) {\n this.inertialPanningX = 0;\n }\n if (Math.abs(this.inertialPanningY) < this.speed * Epsilon) {\n this.inertialPanningY = 0;\n }\n }\n // Limits\n this._checkLimits();\n super._checkInputs();\n }\n _checkLimits() {\n if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {\n if (this.allowUpsideDown && this.beta > Math.PI) {\n this.beta = this.beta - 2 * Math.PI;\n }\n }\n else {\n if (this.beta < this.lowerBetaLimit) {\n this.beta = this.lowerBetaLimit;\n }\n }\n if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {\n if (this.allowUpsideDown && this.beta < -Math.PI) {\n this.beta = this.beta + 2 * Math.PI;\n }\n }\n else {\n if (this.beta > this.upperBetaLimit) {\n this.beta = this.upperBetaLimit;\n }\n }\n if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {\n this.alpha = this.lowerAlphaLimit;\n }\n if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {\n this.alpha = this.upperAlphaLimit;\n }\n if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {\n this.radius = this.lowerRadiusLimit;\n this.inertialRadiusOffset = 0;\n }\n if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {\n this.radius = this.upperRadiusLimit;\n this.inertialRadiusOffset = 0;\n }\n }\n /**\n * Rebuilds angles (alpha, beta) and radius from the give position and target\n */\n rebuildAnglesAndRadius() {\n this._position.subtractToRef(this._getTargetPosition(), this._computationVector);\n // need to rotate to Y up equivalent if up vector not Axis.Y\n if (this._upVector.x !== 0 || this._upVector.y !== 1.0 || this._upVector.z !== 0) {\n Vector3.TransformCoordinatesToRef(this._computationVector, this._upToYMatrix, this._computationVector);\n }\n this.radius = this._computationVector.length();\n if (this.radius === 0) {\n this.radius = 0.0001; // Just to avoid division by zero\n }\n // Alpha\n const previousAlpha = this.alpha;\n if (this._computationVector.x === 0 && this._computationVector.z === 0) {\n this.alpha = Math.PI / 2; // avoid division by zero when looking along up axis, and set to acos(0)\n }\n else {\n this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));\n }\n if (this._computationVector.z < 0) {\n this.alpha = 2 * Math.PI - this.alpha;\n }\n // Calculate the number of revolutions between the new and old alpha values.\n const alphaCorrectionTurns = Math.round((previousAlpha - this.alpha) / (2.0 * Math.PI));\n // Adjust alpha so that its numerical representation is the closest one to the old value.\n this.alpha += alphaCorrectionTurns * 2.0 * Math.PI;\n // Beta\n this.beta = Math.acos(this._computationVector.y / this.radius);\n this._checkLimits();\n }\n /**\n * Use a position to define the current camera related information like alpha, beta and radius\n * @param position Defines the position to set the camera at\n */\n setPosition(position) {\n if (this._position.equals(position)) {\n return;\n }\n this._position.copyFrom(position);\n this.rebuildAnglesAndRadius();\n }\n /**\n * Defines the target the camera should look at.\n * This will automatically adapt alpha beta and radius to fit within the new target.\n * Please note that setting a target as a mesh will disable panning.\n * @param target Defines the new target as a Vector or a mesh\n * @param toBoundingCenter In case of a mesh target, defines whether to target the mesh position or its bounding information center\n * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)\n * @param cloneAlphaBetaRadius If true, replicate the current setup (alpha, beta, radius) on the new target\n */\n setTarget(target, toBoundingCenter = false, allowSamePosition = false, cloneAlphaBetaRadius = false) {\n var _a;\n cloneAlphaBetaRadius = (_a = this.overrideCloneAlphaBetaRadius) !== null && _a !== void 0 ? _a : cloneAlphaBetaRadius;\n if (target.getBoundingInfo) {\n if (toBoundingCenter) {\n this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();\n }\n else {\n this._targetBoundingCenter = null;\n }\n target.computeWorldMatrix();\n this._targetHost = target;\n this._target = this._getTargetPosition();\n this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);\n }\n else {\n const newTarget = target;\n const currentTarget = this._getTargetPosition();\n if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {\n return;\n }\n this._targetHost = null;\n this._target = newTarget;\n this._targetBoundingCenter = null;\n this.onMeshTargetChangedObservable.notifyObservers(null);\n }\n if (!cloneAlphaBetaRadius) {\n this.rebuildAnglesAndRadius();\n }\n }\n /** @internal */\n _getViewMatrix() {\n // Compute\n const cosa = Math.cos(this.alpha);\n const sina = Math.sin(this.alpha);\n const cosb = Math.cos(this.beta);\n let sinb = Math.sin(this.beta);\n if (sinb === 0) {\n sinb = 0.0001;\n }\n if (this.radius === 0) {\n this.radius = 0.0001; // Just to avoid division by zero\n }\n const target = this._getTargetPosition();\n this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);\n // Rotate according to up vector\n if (this._upVector.x !== 0 || this._upVector.y !== 1.0 || this._upVector.z !== 0) {\n Vector3.TransformCoordinatesToRef(this._computationVector, this._yToUpMatrix, this._computationVector);\n }\n target.addToRef(this._computationVector, this._newPosition);\n if (this.getScene().collisionsEnabled && this.checkCollisions) {\n const coordinator = this.getScene().collisionCoordinator;\n if (!this._collider) {\n this._collider = coordinator.createCollider();\n }\n this._collider._radius = this.collisionRadius;\n this._newPosition.subtractToRef(this._position, this._collisionVelocity);\n this._collisionTriggered = true;\n coordinator.getNewPosition(this._position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);\n }\n else {\n this._position.copyFrom(this._newPosition);\n let up = this.upVector;\n if (this.allowUpsideDown && sinb < 0) {\n up = up.negate();\n }\n this._computeViewMatrix(this._position, target, up);\n this._viewMatrix.addAtIndex(12, this.targetScreenOffset.x);\n this._viewMatrix.addAtIndex(13, this.targetScreenOffset.y);\n }\n this._currentTarget = target;\n return this._viewMatrix;\n }\n /**\n * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.\n * @param meshes Defines the mesh to zoom on\n * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)\n */\n zoomOn(meshes, doNotUpdateMaxZ = false) {\n meshes = meshes || this.getScene().meshes;\n const minMaxVector = Mesh.MinMax(meshes);\n const distance = Vector3.Distance(minMaxVector.min, minMaxVector.max);\n this.radius = distance * this.zoomOnFactor;\n this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);\n }\n /**\n * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.\n * The target will be changed but the radius\n * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on\n * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)\n */\n focusOn(meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ = false) {\n let meshesOrMinMaxVector;\n let distance;\n if (meshesOrMinMaxVectorAndDistance.min === undefined) {\n // meshes\n const meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;\n meshesOrMinMaxVector = Mesh.MinMax(meshes);\n distance = Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);\n }\n else {\n //minMaxVector and distance\n const minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;\n meshesOrMinMaxVector = minMaxVectorAndDistance;\n distance = minMaxVectorAndDistance.distance;\n }\n this._target = Mesh.Center(meshesOrMinMaxVector);\n if (!doNotUpdateMaxZ) {\n this.maxZ = distance * 2;\n }\n }\n /**\n * @override\n * Override Camera.createRigCamera\n */\n createRigCamera(name, cameraIndex) {\n let alphaShift = 0;\n switch (this.cameraRigMode) {\n case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:\n case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:\n case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:\n case Camera.RIG_MODE_STEREOSCOPIC_INTERLACED:\n case Camera.RIG_MODE_VR:\n alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);\n break;\n case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:\n alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);\n break;\n }\n const rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());\n rigCam._cameraRigParams = {};\n rigCam.isRigCamera = true;\n rigCam.rigParent = this;\n rigCam.upVector = this.upVector;\n rigCam.mode = this.mode;\n rigCam.orthoLeft = this.orthoLeft;\n rigCam.orthoRight = this.orthoRight;\n rigCam.orthoBottom = this.orthoBottom;\n rigCam.orthoTop = this.orthoTop;\n return rigCam;\n }\n /**\n * @internal\n * @override\n * Override Camera._updateRigCameras\n */\n _updateRigCameras() {\n const camLeft = this._rigCameras[0];\n const camRight = this._rigCameras[1];\n camLeft.beta = camRight.beta = this.beta;\n switch (this.cameraRigMode) {\n case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:\n case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:\n case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:\n case Camera.RIG_MODE_STEREOSCOPIC_INTERLACED:\n case Camera.RIG_MODE_VR:\n camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;\n camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;\n break;\n case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:\n camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;\n camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;\n break;\n }\n super._updateRigCameras();\n }\n /**\n * Destroy the camera and release the current resources hold by it.\n */\n dispose() {\n this.inputs.clear();\n super.dispose();\n }\n /**\n * Gets the current object class name.\n * @returns the class name\n */\n getClassName() {\n return \"ArcRotateCamera\";\n }\n}\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"alpha\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"beta\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"radius\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"overrideCloneAlphaBetaRadius\", void 0);\n__decorate([\n serializeAsVector3(\"target\")\n], ArcRotateCamera.prototype, \"_target\", void 0);\n__decorate([\n serializeAsMeshReference(\"targetHost\")\n], ArcRotateCamera.prototype, \"_targetHost\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"inertialAlphaOffset\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"inertialBetaOffset\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"inertialRadiusOffset\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"lowerAlphaLimit\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"upperAlphaLimit\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"lowerBetaLimit\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"upperBetaLimit\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"lowerRadiusLimit\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"upperRadiusLimit\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"inertialPanningX\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"inertialPanningY\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"pinchToPanMaxDistance\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"panningDistanceLimit\", void 0);\n__decorate([\n serializeAsVector3()\n], ArcRotateCamera.prototype, \"panningOriginTarget\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"panningInertia\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"zoomToMouseLocation\", null);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"zoomOnFactor\", void 0);\n__decorate([\n serializeAsVector2()\n], ArcRotateCamera.prototype, \"targetScreenOffset\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"allowUpsideDown\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"useInputToRestoreState\", void 0);\n//# sourceMappingURL=arcRotateCamera.js.map","import { FreeCamera } from \"./freeCamera.js\";\nimport { Quaternion, Vector3 } from \"../Maths/math.vector.js\";\nimport { Node } from \"../node.js\";\nimport \"./Inputs/freeCameraDeviceOrientationInput.js\";\nimport { Axis } from \"../Maths/math.axis.js\";\nNode.AddNodeConstructor(\"DeviceOrientationCamera\", (name, scene) => {\n return () => new DeviceOrientationCamera(name, Vector3.Zero(), scene);\n});\n// We're mainly based on the logic defined into the FreeCamera code\n/**\n * This is a camera specifically designed to react to device orientation events such as a modern mobile device\n * being tilted forward or back and left or right.\n */\nexport class DeviceOrientationCamera extends FreeCamera {\n /**\n * Creates a new device orientation camera\n * @param name The name of the camera\n * @param position The start position camera\n * @param scene The scene the camera belongs to\n */\n constructor(name, position, scene) {\n super(name, position, scene);\n this._tmpDragQuaternion = new Quaternion();\n this._disablePointerInputWhenUsingDeviceOrientation = true;\n this._dragFactor = 0;\n this._quaternionCache = new Quaternion();\n this.inputs.addDeviceOrientation();\n // When the orientation sensor fires it's first event, disable mouse input\n if (this.inputs._deviceOrientationInput) {\n this.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce(() => {\n if (this._disablePointerInputWhenUsingDeviceOrientation) {\n if (this.inputs._mouseInput) {\n this.inputs._mouseInput._allowCameraRotation = false;\n this.inputs._mouseInput.onPointerMovedObservable.add((e) => {\n if (this._dragFactor != 0) {\n if (!this._initialQuaternion) {\n this._initialQuaternion = new Quaternion();\n }\n // Rotate the initial space around the y axis to allow users to \"turn around\" via touch/mouse\n Quaternion.FromEulerAnglesToRef(0, e.offsetX * this._dragFactor, 0, this._tmpDragQuaternion);\n this._initialQuaternion.multiplyToRef(this._tmpDragQuaternion, this._initialQuaternion);\n }\n });\n }\n }\n });\n }\n }\n /**\n * Gets or sets a boolean indicating that pointer input must be disabled on first orientation sensor update (Default: true)\n */\n get disablePointerInputWhenUsingDeviceOrientation() {\n return this._disablePointerInputWhenUsingDeviceOrientation;\n }\n set disablePointerInputWhenUsingDeviceOrientation(value) {\n this._disablePointerInputWhenUsingDeviceOrientation = value;\n }\n /**\n * Enabled turning on the y axis when the orientation sensor is active\n * @param dragFactor the factor that controls the turn speed (default: 1/300)\n */\n enableHorizontalDragging(dragFactor = 1 / 300) {\n this._dragFactor = dragFactor;\n }\n /**\n * Gets the current instance class name (\"DeviceOrientationCamera\").\n * This helps avoiding instanceof at run time.\n * @returns the class name\n */\n getClassName() {\n return \"DeviceOrientationCamera\";\n }\n /**\n * @internal\n * Checks and applies the current values of the inputs to the camera. (Internal use only)\n */\n _checkInputs() {\n super._checkInputs();\n this._quaternionCache.copyFrom(this.rotationQuaternion);\n if (this._initialQuaternion) {\n this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);\n }\n }\n /**\n * Reset the camera to its default orientation on the specified axis only.\n * @param axis The axis to reset\n */\n resetToCurrentRotation(axis = Axis.Y) {\n //can only work if this camera has a rotation quaternion already.\n if (!this.rotationQuaternion) {\n return;\n }\n if (!this._initialQuaternion) {\n this._initialQuaternion = new Quaternion();\n }\n this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);\n [\"x\", \"y\", \"z\"].forEach((axisName) => {\n if (!axis[axisName]) {\n this._initialQuaternion[axisName] = 0;\n }\n else {\n this._initialQuaternion[axisName] *= -1;\n }\n });\n this._initialQuaternion.normalize();\n //force rotation update\n this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);\n }\n}\n//# sourceMappingURL=deviceOrientationCamera.js.map","import { CameraInputsManager } from \"./cameraInputsManager.js\";\nimport { FlyCameraMouseInput } from \"../Cameras/Inputs/flyCameraMouseInput.js\";\nimport { FlyCameraKeyboardInput } from \"../Cameras/Inputs/flyCameraKeyboardInput.js\";\n/**\n * Default Inputs manager for the FlyCamera.\n * It groups all the default supported inputs for ease of use.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FlyCameraInputsManager extends CameraInputsManager {\n /**\n * Instantiates a new FlyCameraInputsManager.\n * @param camera Defines the camera the inputs belong to.\n */\n constructor(camera) {\n super(camera);\n }\n /**\n * Add keyboard input support to the input manager.\n * @returns the new FlyCameraKeyboardMoveInput().\n */\n addKeyboard() {\n this.add(new FlyCameraKeyboardInput());\n return this;\n }\n /**\n * Add mouse input support to the input manager.\n * @returns the new FlyCameraMouseInput().\n */\n addMouse() {\n this.add(new FlyCameraMouseInput());\n return this;\n }\n}\n//# sourceMappingURL=flyCameraInputsManager.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize, serializeAsVector3 } from \"../Misc/decorators.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { TargetCamera } from \"./targetCamera.js\";\nimport { FlyCameraInputsManager } from \"./flyCameraInputsManager.js\";\nimport { Tools } from \"../Misc/tools.js\";\n/**\n * This is a flying camera, designed for 3D movement and rotation in all directions,\n * such as in a 3D Space Shooter or a Flight Simulator.\n */\nexport class FlyCamera extends TargetCamera {\n /**\n * Gets the input sensibility for mouse input.\n * Higher values reduce sensitivity.\n */\n get angularSensibility() {\n const mouse = this.inputs.attached[\"mouse\"];\n if (mouse) {\n return mouse.angularSensibility;\n }\n return 0;\n }\n /**\n * Sets the input sensibility for a mouse input.\n * Higher values reduce sensitivity.\n */\n set angularSensibility(value) {\n const mouse = this.inputs.attached[\"mouse\"];\n if (mouse) {\n mouse.angularSensibility = value;\n }\n }\n /**\n * Get the keys for camera movement forward.\n */\n get keysForward() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysForward;\n }\n return [];\n }\n /**\n * Set the keys for camera movement forward.\n */\n set keysForward(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysForward = value;\n }\n }\n /**\n * Get the keys for camera movement backward.\n */\n get keysBackward() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysBackward;\n }\n return [];\n }\n set keysBackward(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysBackward = value;\n }\n }\n /**\n * Get the keys for camera movement up.\n */\n get keysUp() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysUp;\n }\n return [];\n }\n /**\n * Set the keys for camera movement up.\n */\n set keysUp(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysUp = value;\n }\n }\n /**\n * Get the keys for camera movement down.\n */\n get keysDown() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysDown;\n }\n return [];\n }\n /**\n * Set the keys for camera movement down.\n */\n set keysDown(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysDown = value;\n }\n }\n /**\n * Get the keys for camera movement left.\n */\n get keysLeft() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysLeft;\n }\n return [];\n }\n /**\n * Set the keys for camera movement left.\n */\n set keysLeft(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysLeft = value;\n }\n }\n /**\n * Set the keys for camera movement right.\n */\n get keysRight() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysRight;\n }\n return [];\n }\n /**\n * Set the keys for camera movement right.\n */\n set keysRight(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysRight = value;\n }\n }\n /**\n * Instantiates a FlyCamera.\n * This is a flying camera, designed for 3D movement and rotation in all directions,\n * such as in a 3D Space Shooter or a Flight Simulator.\n * @param name Define the name of the camera in the scene.\n * @param position Define the starting position of the camera in the scene.\n * @param scene Define the scene the camera belongs to.\n * @param setActiveOnSceneIfNoneActive Defines whether the camera should be marked as active, if no other camera has been defined as active.\n */\n constructor(name, position, scene, setActiveOnSceneIfNoneActive = true) {\n super(name, position, scene, setActiveOnSceneIfNoneActive);\n /**\n * Define the collision ellipsoid of the camera.\n * This is helpful for simulating a camera body, like a player's body.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions#arcrotatecamera\n */\n this.ellipsoid = new Vector3(1, 1, 1);\n /**\n * Define an offset for the position of the ellipsoid around the camera.\n * This can be helpful if the camera is attached away from the player's body center,\n * such as at its head.\n */\n this.ellipsoidOffset = new Vector3(0, 0, 0);\n /**\n * Enable or disable collisions of the camera with the rest of the scene objects.\n */\n this.checkCollisions = false;\n /**\n * Enable or disable gravity on the camera.\n */\n this.applyGravity = false;\n /**\n * Define the current direction the camera is moving to.\n */\n this.cameraDirection = Vector3.Zero();\n /**\n * Track Roll to maintain the wanted Rolling when looking around.\n */\n this._trackRoll = 0;\n /**\n * Slowly correct the Roll to its original value after a Pitch+Yaw rotation.\n */\n this.rollCorrect = 100;\n /**\n * Mimic a banked turn, Rolling the camera when Yawing.\n * It's recommended to use rollCorrect = 10 for faster banking correction.\n */\n this.bankedTurn = false;\n /**\n * Limit in radians for how much Roll banking will add. (Default: 90°)\n */\n this.bankedTurnLimit = Math.PI / 2;\n /**\n * Value of 0 disables the banked Roll.\n * Value of 1 is equal to the Yaw angle in radians.\n */\n this.bankedTurnMultiplier = 1;\n this._needMoveForGravity = false;\n this._oldPosition = Vector3.Zero();\n this._diffPosition = Vector3.Zero();\n this._newPosition = Vector3.Zero();\n // Collisions.\n this._collisionMask = -1;\n /**\n * @internal\n */\n this._onCollisionPositionChange = (collisionId, newPosition, collidedMesh = null) => {\n const updatePosition = (newPos) => {\n this._newPosition.copyFrom(newPos);\n this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);\n if (this._diffPosition.length() > Engine.CollisionsEpsilon) {\n this.position.addInPlace(this._diffPosition);\n if (this.onCollide && collidedMesh) {\n this.onCollide(collidedMesh);\n }\n }\n };\n updatePosition(newPosition);\n };\n this.inputs = new FlyCameraInputsManager(this);\n this.inputs.addKeyboard().addMouse();\n }\n /**\n * Attached controls to the current camera.\n * @param ignored defines an ignored parameter kept for backward compatibility.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(ignored, noPreventDefault) {\n // eslint-disable-next-line prefer-rest-params\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n this.inputs.attachElement(noPreventDefault);\n }\n /**\n * Detach a control from the HTML DOM element.\n * The camera will stop reacting to that input.\n */\n detachControl() {\n this.inputs.detachElement();\n this.cameraDirection = new Vector3(0, 0, 0);\n }\n /**\n * Get the mask that the camera ignores in collision events.\n */\n get collisionMask() {\n return this._collisionMask;\n }\n /**\n * Set the mask that the camera ignores in collision events.\n */\n set collisionMask(mask) {\n this._collisionMask = !isNaN(mask) ? mask : -1;\n }\n /**\n * @internal\n */\n _collideWithWorld(displacement) {\n let globalPosition;\n if (this.parent) {\n globalPosition = Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());\n }\n else {\n globalPosition = this.position;\n }\n globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);\n this._oldPosition.addInPlace(this.ellipsoidOffset);\n const coordinator = this.getScene().collisionCoordinator;\n if (!this._collider) {\n this._collider = coordinator.createCollider();\n }\n this._collider._radius = this.ellipsoid;\n this._collider.collisionMask = this._collisionMask;\n // No need for clone, as long as gravity is not on.\n let actualDisplacement = displacement;\n // Add gravity to direction to prevent dual-collision checking.\n if (this.applyGravity) {\n // This prevents mending with cameraDirection, a global variable of the fly camera class.\n actualDisplacement = displacement.add(this.getScene().gravity);\n }\n coordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);\n }\n /** @internal */\n _checkInputs() {\n if (!this._localDirection) {\n this._localDirection = Vector3.Zero();\n this._transformedDirection = Vector3.Zero();\n }\n this.inputs.checkInputs();\n super._checkInputs();\n }\n /**\n * Enable movement without a user input. This allows gravity to always be applied.\n */\n set needMoveForGravity(value) {\n this._needMoveForGravity = value;\n }\n /**\n * When true, gravity is applied whether there is user input or not.\n */\n get needMoveForGravity() {\n return this._needMoveForGravity;\n }\n /** @internal */\n _decideIfNeedsToMove() {\n return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;\n }\n /** @internal */\n _updatePosition() {\n if (this.checkCollisions && this.getScene().collisionsEnabled) {\n this._collideWithWorld(this.cameraDirection);\n }\n else {\n super._updatePosition();\n }\n }\n /**\n * Restore the Roll to its target value at the rate specified.\n * @param rate - Higher means slower restoring.\n * @internal\n */\n restoreRoll(rate) {\n const limit = this._trackRoll; // Target Roll.\n const z = this.rotation.z; // Current Roll.\n const delta = limit - z; // Difference in Roll.\n const minRad = 0.001; // Tenth of a radian is a barely noticable difference.\n // If the difference is noticable, restore the Roll.\n if (Math.abs(delta) >= minRad) {\n // Change Z rotation towards the target Roll.\n this.rotation.z += delta / rate;\n // Match when near enough.\n if (Math.abs(limit - this.rotation.z) <= minRad) {\n this.rotation.z = limit;\n }\n }\n }\n /**\n * Destroy the camera and release the current resources held by it.\n */\n dispose() {\n this.inputs.clear();\n super.dispose();\n }\n /**\n * Get the current object class name.\n * @returns the class name.\n */\n getClassName() {\n return \"FlyCamera\";\n }\n}\n__decorate([\n serializeAsVector3()\n], FlyCamera.prototype, \"ellipsoid\", void 0);\n__decorate([\n serializeAsVector3()\n], FlyCamera.prototype, \"ellipsoidOffset\", void 0);\n__decorate([\n serialize()\n], FlyCamera.prototype, \"checkCollisions\", void 0);\n__decorate([\n serialize()\n], FlyCamera.prototype, \"applyGravity\", void 0);\n//# sourceMappingURL=flyCamera.js.map","import { CameraInputsManager } from \"./cameraInputsManager.js\";\nimport { FollowCameraKeyboardMoveInput } from \"./Inputs/followCameraKeyboardMoveInput.js\";\nimport { FollowCameraMouseWheelInput } from \"./Inputs/followCameraMouseWheelInput.js\";\nimport { FollowCameraPointersInput } from \"./Inputs/followCameraPointersInput.js\";\n/**\n * Default Inputs manager for the FollowCamera.\n * It groups all the default supported inputs for ease of use.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FollowCameraInputsManager extends CameraInputsManager {\n /**\n * Instantiates a new FollowCameraInputsManager.\n * @param camera Defines the camera the inputs belong to\n */\n constructor(camera) {\n super(camera);\n }\n /**\n * Add keyboard input support to the input manager.\n * @returns the current input manager\n */\n addKeyboard() {\n this.add(new FollowCameraKeyboardMoveInput());\n return this;\n }\n /**\n * Add mouse wheel input support to the input manager.\n * @returns the current input manager\n */\n addMouseWheel() {\n this.add(new FollowCameraMouseWheelInput());\n return this;\n }\n /**\n * Add pointers input support to the input manager.\n * @returns the current input manager\n */\n addPointers() {\n this.add(new FollowCameraPointersInput());\n return this;\n }\n /**\n * Add orientation input support to the input manager.\n * @returns the current input manager\n */\n addVRDeviceOrientation() {\n console.warn(\"DeviceOrientation support not yet implemented for FollowCamera.\");\n return this;\n }\n}\n//# sourceMappingURL=followCameraInputsManager.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize, serializeAsMeshReference } from \"../Misc/decorators.js\";\nimport { Tools } from \"../Misc/tools.js\";\nimport { TargetCamera } from \"./targetCamera.js\";\nimport { TmpVectors, Vector3 } from \"../Maths/math.vector.js\";\nimport { Node } from \"../node.js\";\nimport { FollowCameraInputsManager } from \"./followCameraInputsManager.js\";\nNode.AddNodeConstructor(\"FollowCamera\", (name, scene) => {\n return () => new FollowCamera(name, Vector3.Zero(), scene);\n});\nNode.AddNodeConstructor(\"ArcFollowCamera\", (name, scene) => {\n return () => new ArcFollowCamera(name, 0, 0, 1.0, null, scene);\n});\n/**\n * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and\n * an arc rotate version arcFollowCamera are available.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#followcamera\n */\nexport class FollowCamera extends TargetCamera {\n /**\n * Instantiates the follow camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#followcamera\n * @param name Define the name of the camera in the scene\n * @param position Define the position of the camera\n * @param scene Define the scene the camera belong to\n * @param lockedTarget Define the target of the camera\n */\n constructor(name, position, scene, lockedTarget = null) {\n super(name, position, scene);\n /**\n * Distance the follow camera should follow an object at\n */\n this.radius = 12;\n /**\n * Minimum allowed distance of the camera to the axis of rotation\n * (The camera can not get closer).\n * This can help limiting how the Camera is able to move in the scene.\n */\n this.lowerRadiusLimit = null;\n /**\n * Maximum allowed distance of the camera to the axis of rotation\n * (The camera can not get further).\n * This can help limiting how the Camera is able to move in the scene.\n */\n this.upperRadiusLimit = null;\n /**\n * Define a rotation offset between the camera and the object it follows\n */\n this.rotationOffset = 0;\n /**\n * Minimum allowed angle to camera position relative to target object.\n * This can help limiting how the Camera is able to move in the scene.\n */\n this.lowerRotationOffsetLimit = null;\n /**\n * Maximum allowed angle to camera position relative to target object.\n * This can help limiting how the Camera is able to move in the scene.\n */\n this.upperRotationOffsetLimit = null;\n /**\n * Define a height offset between the camera and the object it follows.\n * It can help following an object from the top (like a car chasing a plane)\n */\n this.heightOffset = 4;\n /**\n * Minimum allowed height of camera position relative to target object.\n * This can help limiting how the Camera is able to move in the scene.\n */\n this.lowerHeightOffsetLimit = null;\n /**\n * Maximum allowed height of camera position relative to target object.\n * This can help limiting how the Camera is able to move in the scene.\n */\n this.upperHeightOffsetLimit = null;\n /**\n * Define how fast the camera can accelerate to follow it s target.\n */\n this.cameraAcceleration = 0.05;\n /**\n * Define the speed limit of the camera following an object.\n */\n this.maxCameraSpeed = 20;\n this.lockedTarget = lockedTarget;\n this.inputs = new FollowCameraInputsManager(this);\n this.inputs.addKeyboard().addMouseWheel().addPointers();\n // Uncomment the following line when the relevant handlers have been implemented.\n // this.inputs.addKeyboard().addMouseWheel().addPointers().addVRDeviceOrientation();\n }\n _follow(cameraTarget) {\n if (!cameraTarget) {\n return;\n }\n const rotMatrix = TmpVectors.Matrix[0];\n cameraTarget.absoluteRotationQuaternion.toRotationMatrix(rotMatrix);\n const yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);\n const radians = Tools.ToRadians(this.rotationOffset) + yRotation;\n const targetPosition = cameraTarget.getAbsolutePosition();\n const targetX = targetPosition.x + Math.sin(radians) * this.radius;\n const targetZ = targetPosition.z + Math.cos(radians) * this.radius;\n const dx = targetX - this.position.x;\n const dy = targetPosition.y + this.heightOffset - this.position.y;\n const dz = targetZ - this.position.z;\n let vx = dx * this.cameraAcceleration * 2; //this is set to .05\n let vy = dy * this.cameraAcceleration;\n let vz = dz * this.cameraAcceleration * 2;\n if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {\n vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;\n }\n if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {\n vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;\n }\n if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {\n vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;\n }\n this.position = new Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);\n this.setTarget(targetPosition);\n }\n /**\n * Attached controls to the current camera.\n * @param ignored defines an ignored parameter kept for backward compatibility.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(ignored, noPreventDefault) {\n // eslint-disable-next-line prefer-rest-params\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n this.inputs.attachElement(noPreventDefault);\n this._reset = () => { };\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n this.inputs.detachElement();\n if (this._reset) {\n this._reset();\n }\n }\n /** @internal */\n _checkInputs() {\n this.inputs.checkInputs();\n this._checkLimits();\n super._checkInputs();\n if (this.lockedTarget) {\n this._follow(this.lockedTarget);\n }\n }\n _checkLimits() {\n if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {\n this.radius = this.lowerRadiusLimit;\n }\n if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {\n this.radius = this.upperRadiusLimit;\n }\n if (this.lowerHeightOffsetLimit !== null && this.heightOffset < this.lowerHeightOffsetLimit) {\n this.heightOffset = this.lowerHeightOffsetLimit;\n }\n if (this.upperHeightOffsetLimit !== null && this.heightOffset > this.upperHeightOffsetLimit) {\n this.heightOffset = this.upperHeightOffsetLimit;\n }\n if (this.lowerRotationOffsetLimit !== null && this.rotationOffset < this.lowerRotationOffsetLimit) {\n this.rotationOffset = this.lowerRotationOffsetLimit;\n }\n if (this.upperRotationOffsetLimit !== null && this.rotationOffset > this.upperRotationOffsetLimit) {\n this.rotationOffset = this.upperRotationOffsetLimit;\n }\n }\n /**\n * Gets the camera class name.\n * @returns the class name\n */\n getClassName() {\n return \"FollowCamera\";\n }\n}\n__decorate([\n serialize()\n], FollowCamera.prototype, \"radius\", void 0);\n__decorate([\n serialize()\n], FollowCamera.prototype, \"lowerRadiusLimit\", void 0);\n__decorate([\n serialize()\n], FollowCamera.prototype, \"upperRadiusLimit\", void 0);\n__decorate([\n serialize()\n], FollowCamera.prototype, \"rotationOffset\", void 0);\n__decorate([\n serialize()\n], FollowCamera.prototype, \"lowerRotationOffsetLimit\", void 0);\n__decorate([\n serialize()\n], FollowCamera.prototype, \"upperRotationOffsetLimit\", void 0);\n__decorate([\n serialize()\n], FollowCamera.prototype, \"heightOffset\", void 0);\n__decorate([\n serialize()\n], FollowCamera.prototype, \"lowerHeightOffsetLimit\", void 0);\n__decorate([\n serialize()\n], FollowCamera.prototype, \"upperHeightOffsetLimit\", void 0);\n__decorate([\n serialize()\n], FollowCamera.prototype, \"cameraAcceleration\", void 0);\n__decorate([\n serialize()\n], FollowCamera.prototype, \"maxCameraSpeed\", void 0);\n__decorate([\n serializeAsMeshReference(\"lockedTargetId\")\n], FollowCamera.prototype, \"lockedTarget\", void 0);\n/**\n * Arc Rotate version of the follow camera.\n * It still follows a Defined mesh but in an Arc Rotate Camera fashion.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#followcamera\n */\nexport class ArcFollowCamera extends TargetCamera {\n /**\n * Instantiates a new ArcFollowCamera\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#followcamera\n * @param name Define the name of the camera\n * @param alpha Define the rotation angle of the camera around the longitudinal axis\n * @param beta Define the rotation angle of the camera around the elevation axis\n * @param radius Define the radius of the camera from its target point\n * @param target Define the target of the camera\n * @param scene Define the scene the camera belongs to\n */\n constructor(name, \n /** The longitudinal angle of the camera */\n alpha, \n /** The latitudinal angle of the camera */\n beta, \n /** The radius of the camera from its target */\n radius, \n /** Define the camera target (the mesh it should follow) */\n target, scene) {\n super(name, Vector3.Zero(), scene);\n this.alpha = alpha;\n this.beta = beta;\n this.radius = radius;\n this._cartesianCoordinates = Vector3.Zero();\n this.setMeshTarget(target);\n }\n /**\n * Sets the mesh to follow with this camera.\n * @param target the target to follow\n */\n setMeshTarget(target) {\n this._meshTarget = target;\n this._follow();\n }\n _follow() {\n if (!this._meshTarget) {\n return;\n }\n this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);\n this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);\n this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);\n const targetPosition = this._meshTarget.getAbsolutePosition();\n this.position = targetPosition.add(this._cartesianCoordinates);\n this.setTarget(targetPosition);\n }\n /** @internal */\n _checkInputs() {\n super._checkInputs();\n this._follow();\n }\n /**\n * Returns the class name of the object.\n * It is mostly used internally for serialization purposes.\n */\n getClassName() {\n return \"ArcFollowCamera\";\n }\n}\n//# sourceMappingURL=followCamera.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { IsWindowObjectExist } from \"../Misc/domManagement.js\";\nimport { PoseEnabledControllerHelper } from \"../Gamepads/Controllers/poseEnabledController.js\";\nimport { Xbox360Pad } from \"./xboxGamepad.js\";\nimport { Gamepad, GenericPad } from \"./gamepad.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { DualShockPad } from \"./dualShockGamepad.js\";\nimport { Tools } from \"../Misc/tools.js\";\n/**\n * Manager for handling gamepads\n */\nexport class GamepadManager {\n /**\n * Initializes the gamepad manager\n * @param _scene BabylonJS scene\n */\n constructor(_scene) {\n this._scene = _scene;\n this._babylonGamepads = [];\n this._oneGamepadConnected = false;\n /** @internal */\n this._isMonitoring = false;\n /**\n * observable to be triggered when the gamepad controller has been disconnected\n */\n this.onGamepadDisconnectedObservable = new Observable();\n if (!IsWindowObjectExist()) {\n this._gamepadEventSupported = false;\n }\n else {\n this._gamepadEventSupported = \"GamepadEvent\" in window;\n this._gamepadSupport = navigator && navigator.getGamepads;\n }\n this.onGamepadConnectedObservable = new Observable((observer) => {\n // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected\n for (const i in this._babylonGamepads) {\n const gamepad = this._babylonGamepads[i];\n if (gamepad && gamepad._isConnected) {\n this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);\n }\n }\n });\n this._onGamepadConnectedEvent = (evt) => {\n const gamepad = evt.gamepad;\n if (gamepad.index in this._babylonGamepads) {\n if (this._babylonGamepads[gamepad.index].isConnected) {\n return;\n }\n }\n let newGamepad;\n if (this._babylonGamepads[gamepad.index]) {\n newGamepad = this._babylonGamepads[gamepad.index];\n newGamepad.browserGamepad = gamepad;\n newGamepad._isConnected = true;\n }\n else {\n newGamepad = this._addNewGamepad(gamepad);\n }\n this.onGamepadConnectedObservable.notifyObservers(newGamepad);\n this._startMonitoringGamepads();\n };\n this._onGamepadDisconnectedEvent = (evt) => {\n const gamepad = evt.gamepad;\n // Remove the gamepad from the list of gamepads to monitor.\n for (const i in this._babylonGamepads) {\n if (this._babylonGamepads[i].index === gamepad.index) {\n const disconnectedGamepad = this._babylonGamepads[i];\n disconnectedGamepad._isConnected = false;\n this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);\n disconnectedGamepad.dispose && disconnectedGamepad.dispose();\n break;\n }\n }\n };\n if (this._gamepadSupport) {\n //first add already-connected gamepads\n this._updateGamepadObjects();\n if (this._babylonGamepads.length) {\n this._startMonitoringGamepads();\n }\n // Checking if the gamepad connected event is supported (like in Firefox)\n if (this._gamepadEventSupported) {\n const hostWindow = this._scene ? this._scene.getEngine().getHostWindow() : window;\n if (hostWindow) {\n hostWindow.addEventListener(\"gamepadconnected\", this._onGamepadConnectedEvent, false);\n hostWindow.addEventListener(\"gamepaddisconnected\", this._onGamepadDisconnectedEvent, false);\n }\n }\n else {\n this._startMonitoringGamepads();\n }\n }\n }\n /**\n * The gamepads in the game pad manager\n */\n get gamepads() {\n return this._babylonGamepads;\n }\n /**\n * Get the gamepad controllers based on type\n * @param type The type of gamepad controller\n * @returns Nullable gamepad\n */\n getGamepadByType(type = Gamepad.XBOX) {\n for (const gamepad of this._babylonGamepads) {\n if (gamepad && gamepad.type === type) {\n return gamepad;\n }\n }\n return null;\n }\n /**\n * Disposes the gamepad manager\n */\n dispose() {\n if (this._gamepadEventSupported) {\n if (this._onGamepadConnectedEvent) {\n window.removeEventListener(\"gamepadconnected\", this._onGamepadConnectedEvent);\n }\n if (this._onGamepadDisconnectedEvent) {\n window.removeEventListener(\"gamepaddisconnected\", this._onGamepadDisconnectedEvent);\n }\n this._onGamepadConnectedEvent = null;\n this._onGamepadDisconnectedEvent = null;\n }\n this._babylonGamepads.forEach((gamepad) => {\n gamepad.dispose();\n });\n this.onGamepadConnectedObservable.clear();\n this.onGamepadDisconnectedObservable.clear();\n this._oneGamepadConnected = false;\n this._stopMonitoringGamepads();\n this._babylonGamepads = [];\n }\n _addNewGamepad(gamepad) {\n if (!this._oneGamepadConnected) {\n this._oneGamepadConnected = true;\n }\n let newGamepad;\n const dualShock = gamepad.id.search(\"054c\") !== -1 && gamepad.id.search(\"0ce6\") === -1;\n const xboxOne = gamepad.id.search(\"Xbox One\") !== -1;\n if (xboxOne ||\n gamepad.id.search(\"Xbox 360\") !== -1 ||\n gamepad.id.search(\"xinput\") !== -1 ||\n (gamepad.id.search(\"045e\") !== -1 && gamepad.id.search(\"Surface Dock\") === -1)) {\n // make sure the Surface Dock Extender is not detected as an xbox controller\n newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);\n }\n else if (dualShock) {\n newGamepad = new DualShockPad(gamepad.id, gamepad.index, gamepad);\n }\n // if pose is supported, use the (WebVR) pose enabled controller\n else if (gamepad.pose) {\n newGamepad = PoseEnabledControllerHelper.InitiateController(gamepad);\n }\n else {\n newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);\n }\n this._babylonGamepads[newGamepad.index] = newGamepad;\n return newGamepad;\n }\n _startMonitoringGamepads() {\n if (!this._isMonitoring) {\n this._isMonitoring = true;\n //back-comp\n this._checkGamepadsStatus();\n }\n }\n _stopMonitoringGamepads() {\n this._isMonitoring = false;\n }\n /** @internal */\n _checkGamepadsStatus() {\n // Hack to be compatible Chrome\n this._updateGamepadObjects();\n for (const i in this._babylonGamepads) {\n const gamepad = this._babylonGamepads[i];\n if (!gamepad || !gamepad.isConnected) {\n continue;\n }\n try {\n gamepad.update();\n }\n catch (_a) {\n if (this._loggedErrors.indexOf(gamepad.index) === -1) {\n Tools.Warn(`Error updating gamepad ${gamepad.id}`);\n this._loggedErrors.push(gamepad.index);\n }\n }\n }\n if (this._isMonitoring) {\n Engine.QueueNewFrame(() => {\n this._checkGamepadsStatus();\n });\n }\n }\n // This function is called only on Chrome, which does not properly support\n // connection/disconnection events and forces you to recopy again the gamepad object\n _updateGamepadObjects() {\n const gamepads = navigator.getGamepads ? navigator.getGamepads() : [];\n for (let i = 0; i < gamepads.length; i++) {\n const gamepad = gamepads[i];\n if (gamepad) {\n if (!this._babylonGamepads[gamepad.index]) {\n const newGamepad = this._addNewGamepad(gamepad);\n this.onGamepadConnectedObservable.notifyObservers(newGamepad);\n }\n else {\n // Forced to copy again this object for Chrome for unknown reason\n this._babylonGamepads[i].browserGamepad = gamepad;\n if (!this._babylonGamepads[i].isConnected) {\n this._babylonGamepads[i]._isConnected = true;\n this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);\n }\n }\n }\n }\n }\n}\n//# sourceMappingURL=gamepadManager.js.map","import { Scene } from \"../scene.js\";\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { GamepadManager } from \"./gamepadManager.js\";\nimport { FreeCameraInputsManager } from \"../Cameras/freeCameraInputsManager.js\";\nimport { FreeCameraGamepadInput } from \"../Cameras/Inputs/freeCameraGamepadInput.js\";\nimport { ArcRotateCameraInputsManager } from \"../Cameras/arcRotateCameraInputsManager.js\";\nimport { ArcRotateCameraGamepadInput } from \"../Cameras/Inputs/arcRotateCameraGamepadInput.js\";\nObject.defineProperty(Scene.prototype, \"gamepadManager\", {\n get: function () {\n if (!this._gamepadManager) {\n this._gamepadManager = new GamepadManager(this);\n let component = this._getComponent(SceneComponentConstants.NAME_GAMEPAD);\n if (!component) {\n component = new GamepadSystemSceneComponent(this);\n this._addComponent(component);\n }\n }\n return this._gamepadManager;\n },\n enumerable: true,\n configurable: true,\n});\n/**\n * Adds a gamepad to the free camera inputs manager\n */\nFreeCameraInputsManager.prototype.addGamepad = function () {\n this.add(new FreeCameraGamepadInput());\n return this;\n};\n/**\n * Adds a gamepad to the arc rotate camera inputs manager\n */\nArcRotateCameraInputsManager.prototype.addGamepad = function () {\n this.add(new ArcRotateCameraGamepadInput());\n return this;\n};\n/**\n * Defines the gamepad scene component responsible to manage gamepads in a given scene\n */\nexport class GamepadSystemSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpfull to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_GAMEPAD;\n this.scene = scene;\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene._beforeCameraUpdateStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n // Nothing to do for gamepads\n }\n /**\n * Disposes the component and the associated resources\n */\n dispose() {\n const gamepadManager = this.scene._gamepadManager;\n if (gamepadManager) {\n gamepadManager.dispose();\n this.scene._gamepadManager = null;\n }\n }\n _beforeCameraUpdate() {\n const gamepadManager = this.scene._gamepadManager;\n if (gamepadManager && gamepadManager._isMonitoring) {\n gamepadManager._checkGamepadsStatus();\n }\n }\n}\n//# sourceMappingURL=gamepadSceneComponent.js.map","import { TouchCamera } from \"./touchCamera.js\";\nimport { Node } from \"../node.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Camera } from \"./camera.js\";\nimport \"../Gamepads/gamepadSceneComponent.js\";\nNode.AddNodeConstructor(\"FreeCamera\", (name, scene) => {\n // Forcing to use the Universal camera\n return () => new UniversalCamera(name, Vector3.Zero(), scene);\n});\n/**\n * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,\n * which still works and will still be found in many Playgrounds.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera\n */\nexport class UniversalCamera extends TouchCamera {\n /**\n * Defines the gamepad rotation sensibility.\n * This is the threshold from when rotation starts to be accounted for to prevent jittering.\n */\n get gamepadAngularSensibility() {\n const gamepad = this.inputs.attached[\"gamepad\"];\n if (gamepad) {\n return gamepad.gamepadAngularSensibility;\n }\n return 0;\n }\n set gamepadAngularSensibility(value) {\n const gamepad = this.inputs.attached[\"gamepad\"];\n if (gamepad) {\n gamepad.gamepadAngularSensibility = value;\n }\n }\n /**\n * Defines the gamepad move sensibility.\n * This is the threshold from when moving starts to be accounted for to prevent jittering.\n */\n get gamepadMoveSensibility() {\n const gamepad = this.inputs.attached[\"gamepad\"];\n if (gamepad) {\n return gamepad.gamepadMoveSensibility;\n }\n return 0;\n }\n set gamepadMoveSensibility(value) {\n const gamepad = this.inputs.attached[\"gamepad\"];\n if (gamepad) {\n gamepad.gamepadMoveSensibility = value;\n }\n }\n /**\n * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,\n * which still works and will still be found in many Playgrounds.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera\n * @param name Define the name of the camera in the scene\n * @param position Define the start position of the camera in the scene\n * @param scene Define the scene the camera belongs to\n */\n constructor(name, position, scene) {\n super(name, position, scene);\n this.inputs.addGamepad();\n }\n /**\n * Gets the current object class name.\n * @returns the class name\n */\n getClassName() {\n return \"UniversalCamera\";\n }\n}\nCamera._CreateDefaultParsedCamera = (name, scene) => {\n return new UniversalCamera(name, Vector3.Zero(), scene);\n};\n//# sourceMappingURL=universalCamera.js.map","import { UniversalCamera } from \"./universalCamera.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Node } from \"../node.js\";\nNode.AddNodeConstructor(\"GamepadCamera\", (name, scene) => {\n return () => new GamepadCamera(name, Vector3.Zero(), scene);\n});\n/**\n * This represents a FPS type of camera. This is only here for back compat purpose.\n * Please use the UniversalCamera instead as both are identical.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera\n */\nexport class GamepadCamera extends UniversalCamera {\n /**\n * Instantiates a new Gamepad Camera\n * This represents a FPS type of camera. This is only here for back compat purpose.\n * Please use the UniversalCamera instead as both are identical.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera\n * @param name Define the name of the camera in the scene\n * @param position Define the start position of the camera in the scene\n * @param scene Define the scene the camera belongs to\n */\n constructor(name, position, scene) {\n super(name, position, scene);\n }\n /**\n * Gets the current object class name.\n * @returns the class name\n */\n getClassName() {\n return \"GamepadCamera\";\n }\n}\n//# sourceMappingURL=gamepadCamera.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"passCubePixelShader\";\nconst shader = `varying vec2 vUV;\runiform samplerCube textureSampler;\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \r{\rvec2 uv=vUV*2.0-1.0;\r#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x));\r#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x));\r#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x));\r#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x));\r#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001));\r#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001));\r#endif\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const passCubePixelShader = { name, shader };\n//# sourceMappingURL=passCube.fragment.js.map","\nimport { PostProcess } from \"./postProcess.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport \"../Shaders/pass.fragment.js\";\nimport \"../Shaders/passCube.fragment.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\nimport { SerializationHelper } from \"../Misc/decorators.js\";\n/**\n * PassPostProcess which produces an output the same as it's input\n */\nexport class PassPostProcess extends PostProcess {\n /**\n * Gets a string identifying the name of the class\n * @returns \"PassPostProcess\" string\n */\n getClassName() {\n return \"PassPostProcess\";\n }\n /**\n * Creates the PassPostProcess\n * @param name The name of the effect.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType The type of texture to be used when performing the post processing.\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n constructor(name, options, camera = null, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) {\n super(name, \"pass\", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation);\n }\n /**\n * @internal\n */\n static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) {\n return SerializationHelper.Parse(() => {\n return new PassPostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, parsedPostProcess._engine, parsedPostProcess.reusable);\n }, parsedPostProcess, scene, rootUrl);\n }\n}\nRegisterClass(\"BABYLON.PassPostProcess\", PassPostProcess);\n/**\n * PassCubePostProcess which produces an output the same as it's input (which must be a cube texture)\n */\nexport class PassCubePostProcess extends PostProcess {\n /**\n * Gets or sets the cube face to display.\n * * 0 is +X\n * * 1 is -X\n * * 2 is +Y\n * * 3 is -Y\n * * 4 is +Z\n * * 5 is -Z\n */\n get face() {\n return this._face;\n }\n set face(value) {\n if (value < 0 || value > 5) {\n return;\n }\n this._face = value;\n switch (this._face) {\n case 0:\n this.updateEffect(\"#define POSITIVEX\");\n break;\n case 1:\n this.updateEffect(\"#define NEGATIVEX\");\n break;\n case 2:\n this.updateEffect(\"#define POSITIVEY\");\n break;\n case 3:\n this.updateEffect(\"#define NEGATIVEY\");\n break;\n case 4:\n this.updateEffect(\"#define POSITIVEZ\");\n break;\n case 5:\n this.updateEffect(\"#define NEGATIVEZ\");\n break;\n }\n }\n /**\n * Gets a string identifying the name of the class\n * @returns \"PassCubePostProcess\" string\n */\n getClassName() {\n return \"PassCubePostProcess\";\n }\n /**\n * Creates the PassCubePostProcess\n * @param name The name of the effect.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType The type of texture to be used when performing the post processing.\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n constructor(name, options, camera = null, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) {\n super(name, \"passCube\", null, null, options, camera, samplingMode, engine, reusable, \"#define POSITIVEX\", textureType, undefined, null, blockCompilation);\n this._face = 0;\n }\n /**\n * @internal\n */\n static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) {\n return SerializationHelper.Parse(() => {\n return new PassCubePostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, parsedPostProcess._engine, parsedPostProcess.reusable);\n }, parsedPostProcess, scene, rootUrl);\n }\n}\nEngine._RescalePostProcessFactory = (engine) => {\n return new PassPostProcess(\"rescale\", 1, null, 2, engine, false, 0);\n};\n//# sourceMappingURL=passPostProcess.js.map","import { PostProcess } from \"./postProcess.js\";\nimport \"../Shaders/anaglyph.fragment.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\n/**\n * Postprocess used to generate anaglyphic rendering\n */\nexport class AnaglyphPostProcess extends PostProcess {\n /**\n * Gets a string identifying the name of the class\n * @returns \"AnaglyphPostProcess\" string\n */\n getClassName() {\n return \"AnaglyphPostProcess\";\n }\n /**\n * Creates a new AnaglyphPostProcess\n * @param name defines postprocess name\n * @param options defines creation options or target ratio scale\n * @param rigCameras defines cameras using this postprocess\n * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)\n * @param engine defines hosting engine\n * @param reusable defines if the postprocess will be reused multiple times per frame\n */\n constructor(name, options, rigCameras, samplingMode, engine, reusable) {\n super(name, \"anaglyph\", null, [\"leftSampler\"], options, rigCameras[1], samplingMode, engine, reusable);\n this._passedProcess = rigCameras[0]._rigPostProcess;\n this.onApplyObservable.add((effect) => {\n effect.setTextureFromPostProcess(\"leftSampler\", this._passedProcess);\n });\n }\n}\nRegisterClass(\"BABYLON.AnaglyphPostProcess\", AnaglyphPostProcess);\n//# sourceMappingURL=anaglyphPostProcess.js.map","import { PassPostProcess } from \"../../PostProcesses/passPostProcess.js\";\nimport { AnaglyphPostProcess } from \"../../PostProcesses/anaglyphPostProcess.js\";\n/**\n * @internal\n */\nexport function setStereoscopicAnaglyphRigMode(camera) {\n camera._rigCameras[0]._rigPostProcess = new PassPostProcess(camera.name + \"_passthru\", 1.0, camera._rigCameras[0]);\n camera._rigCameras[1]._rigPostProcess = new AnaglyphPostProcess(camera.name + \"_anaglyph\", 1.0, camera._rigCameras);\n}\n//# sourceMappingURL=stereoscopicAnaglyphRigMode.js.map","import { Camera } from \"../../Cameras/camera.js\";\nimport { ArcRotateCamera } from \"../../Cameras/arcRotateCamera.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Node } from \"../../node.js\";\nimport { setStereoscopicAnaglyphRigMode } from \"../RigModes/stereoscopicAnaglyphRigMode.js\";\nNode.AddNodeConstructor(\"AnaglyphArcRotateCamera\", (name, scene, options) => {\n return () => new AnaglyphArcRotateCamera(name, 0, 0, 1.0, Vector3.Zero(), options.interaxial_distance, scene);\n});\n/**\n * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#anaglyph-cameras\n */\nexport class AnaglyphArcRotateCamera extends ArcRotateCamera {\n /**\n * Creates a new AnaglyphArcRotateCamera\n * @param name defines camera name\n * @param alpha defines alpha angle (in radians)\n * @param beta defines beta angle (in radians)\n * @param radius defines radius\n * @param target defines camera target\n * @param interaxialDistance defines distance between each color axis\n * @param scene defines the hosting scene\n */\n constructor(name, alpha, beta, radius, target, interaxialDistance, scene) {\n super(name, alpha, beta, radius, target, scene);\n this._setRigMode = setStereoscopicAnaglyphRigMode.bind(null, this);\n this.interaxialDistance = interaxialDistance;\n this.setCameraRigMode(Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });\n }\n /**\n * Gets camera class name\n * @returns AnaglyphArcRotateCamera\n */\n getClassName() {\n return \"AnaglyphArcRotateCamera\";\n }\n}\n//# sourceMappingURL=anaglyphArcRotateCamera.js.map","import { Camera } from \"../../Cameras/camera.js\";\nimport { FreeCamera } from \"../../Cameras/freeCamera.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Node } from \"../../node.js\";\nimport { setStereoscopicAnaglyphRigMode } from \"../RigModes/stereoscopicAnaglyphRigMode.js\";\nNode.AddNodeConstructor(\"AnaglyphFreeCamera\", (name, scene, options) => {\n return () => new AnaglyphFreeCamera(name, Vector3.Zero(), options.interaxial_distance, scene);\n});\n/**\n * Camera used to simulate anaglyphic rendering (based on FreeCamera)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#anaglyph-cameras\n */\nexport class AnaglyphFreeCamera extends FreeCamera {\n /**\n * Creates a new AnaglyphFreeCamera\n * @param name defines camera name\n * @param position defines initial position\n * @param interaxialDistance defines distance between each color axis\n * @param scene defines the hosting scene\n */\n constructor(name, position, interaxialDistance, scene) {\n super(name, position, scene);\n this._setRigMode = setStereoscopicAnaglyphRigMode.bind(null, this);\n this.interaxialDistance = interaxialDistance;\n this.setCameraRigMode(Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });\n }\n /**\n * Gets camera class name\n * @returns AnaglyphFreeCamera\n */\n getClassName() {\n return \"AnaglyphFreeCamera\";\n }\n}\n//# sourceMappingURL=anaglyphFreeCamera.js.map","import { Camera } from \"../../Cameras/camera.js\";\nimport { GamepadCamera } from \"../../Cameras/gamepadCamera.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Node } from \"../../node.js\";\nimport { setStereoscopicAnaglyphRigMode } from \"../RigModes/stereoscopicAnaglyphRigMode.js\";\nNode.AddNodeConstructor(\"AnaglyphGamepadCamera\", (name, scene, options) => {\n return () => new AnaglyphGamepadCamera(name, Vector3.Zero(), options.interaxial_distance, scene);\n});\n/**\n * Camera used to simulate anaglyphic rendering (based on GamepadCamera)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#anaglyph-cameras\n */\nexport class AnaglyphGamepadCamera extends GamepadCamera {\n /**\n * Creates a new AnaglyphGamepadCamera\n * @param name defines camera name\n * @param position defines initial position\n * @param interaxialDistance defines distance between each color axis\n * @param scene defines the hosting scene\n */\n constructor(name, position, interaxialDistance, scene) {\n super(name, position, scene);\n this._setRigMode = setStereoscopicAnaglyphRigMode.bind(null, this);\n this.interaxialDistance = interaxialDistance;\n this.setCameraRigMode(Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });\n }\n /**\n * Gets camera class name\n * @returns AnaglyphGamepadCamera\n */\n getClassName() {\n return \"AnaglyphGamepadCamera\";\n }\n}\n//# sourceMappingURL=anaglyphGamepadCamera.js.map","import { Camera } from \"../../Cameras/camera.js\";\nimport { UniversalCamera } from \"../../Cameras/universalCamera.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Node } from \"../../node.js\";\nimport { setStereoscopicAnaglyphRigMode } from \"../RigModes/stereoscopicAnaglyphRigMode.js\";\nNode.AddNodeConstructor(\"AnaglyphUniversalCamera\", (name, scene, options) => {\n return () => new AnaglyphUniversalCamera(name, Vector3.Zero(), options.interaxial_distance, scene);\n});\n/**\n * Camera used to simulate anaglyphic rendering (based on UniversalCamera)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#anaglyph-cameras\n */\nexport class AnaglyphUniversalCamera extends UniversalCamera {\n /**\n * Creates a new AnaglyphUniversalCamera\n * @param name defines camera name\n * @param position defines initial position\n * @param interaxialDistance defines distance between each color axis\n * @param scene defines the hosting scene\n */\n constructor(name, position, interaxialDistance, scene) {\n super(name, position, scene);\n this._setRigMode = setStereoscopicAnaglyphRigMode.bind(null, this);\n this.interaxialDistance = interaxialDistance;\n this.setCameraRigMode(Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });\n }\n /**\n * Gets camera class name\n * @returns AnaglyphUniversalCamera\n */\n getClassName() {\n return \"AnaglyphUniversalCamera\";\n }\n}\n//# sourceMappingURL=anaglyphUniversalCamera.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"stereoscopicInterlacePixelShader\";\nconst shader = `const vec3 TWO=vec3(2.0,2.0,2.0);\rvarying vec2 vUV;\runiform sampler2D camASampler;\runiform sampler2D textureSampler;\runiform vec2 stepSize;\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\r{\rbool useCamA;\rbool useCamB;\rvec2 texCoord1;\rvec2 texCoord2;\rvec3 frag1;\rvec3 frag2;\r#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ruseCamA=!useCamB;\rtexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\rtexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\r#else\n#ifdef IS_STEREOSCOPIC_INTERLACED\nfloat rowNum=floor(vUV.y/stepSize.y);\ruseCamA=mod(rowNum,2.0)==1.0;\ruseCamB=mod(rowNum,2.0)==0.0;\rtexCoord1=vec2(vUV.x,vUV.y);\rtexCoord2=vec2(vUV.x,vUV.y);\r#else\nuseCamB=vUV.y>0.5;\ruseCamA=!useCamB;\rtexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\rtexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\r#endif\n#endif\nif (useCamB){\rfrag1=texture2D(textureSampler,texCoord1).rgb;\rfrag2=texture2D(textureSampler,texCoord2).rgb;\r}else if (useCamA){\rfrag1=texture2D(camASampler ,texCoord1).rgb;\rfrag2=texture2D(camASampler ,texCoord2).rgb;\r}else {\rdiscard;\r}\rgl_FragColor=vec4((frag1+frag2)/TWO,1.0);\r}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const stereoscopicInterlacePixelShader = { name, shader };\n//# sourceMappingURL=stereoscopicInterlace.fragment.js.map","import { Vector2 } from \"../Maths/math.vector.js\";\nimport { PostProcess } from \"./postProcess.js\";\nimport \"../Shaders/stereoscopicInterlace.fragment.js\";\n/**\n * StereoscopicInterlacePostProcessI used to render stereo views from a rigged camera with support for alternate line interlacing\n */\nexport class StereoscopicInterlacePostProcessI extends PostProcess {\n /**\n * Gets a string identifying the name of the class\n * @returns \"StereoscopicInterlacePostProcessI\" string\n */\n getClassName() {\n return \"StereoscopicInterlacePostProcessI\";\n }\n /**\n * Initializes a StereoscopicInterlacePostProcessI\n * @param name The name of the effect.\n * @param rigCameras The rig cameras to be applied to the post process\n * @param isStereoscopicHoriz If the rendered results are horizontal or vertical\n * @param isStereoscopicInterlaced If the rendered results are alternate line interlaced\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n */\n constructor(name, rigCameras, isStereoscopicHoriz, isStereoscopicInterlaced, samplingMode, engine, reusable) {\n super(name, \"stereoscopicInterlace\", [\"stepSize\"], [\"camASampler\"], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicInterlaced ? \"#define IS_STEREOSCOPIC_INTERLACED 1\" : isStereoscopicHoriz ? \"#define IS_STEREOSCOPIC_HORIZ 1\" : undefined);\n this._passedProcess = rigCameras[0]._rigPostProcess;\n this._stepSize = new Vector2(1 / this.width, 1 / this.height);\n this.onSizeChangedObservable.add(() => {\n this._stepSize = new Vector2(1 / this.width, 1 / this.height);\n });\n this.onApplyObservable.add((effect) => {\n effect.setTextureFromPostProcess(\"camASampler\", this._passedProcess);\n effect.setFloat2(\"stepSize\", this._stepSize.x, this._stepSize.y);\n });\n }\n}\n/**\n * StereoscopicInterlacePostProcess used to render stereo views from a rigged camera\n */\nexport class StereoscopicInterlacePostProcess extends PostProcess {\n /**\n * Gets a string identifying the name of the class\n * @returns \"StereoscopicInterlacePostProcess\" string\n */\n getClassName() {\n return \"StereoscopicInterlacePostProcess\";\n }\n /**\n * Initializes a StereoscopicInterlacePostProcess\n * @param name The name of the effect.\n * @param rigCameras The rig cameras to be applied to the post process\n * @param isStereoscopicHoriz If the rendered results are horizontal or vertical\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n */\n constructor(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {\n super(name, \"stereoscopicInterlace\", [\"stepSize\"], [\"camASampler\"], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? \"#define IS_STEREOSCOPIC_HORIZ 1\" : undefined);\n this._passedProcess = rigCameras[0]._rigPostProcess;\n this._stepSize = new Vector2(1 / this.width, 1 / this.height);\n this.onSizeChangedObservable.add(() => {\n this._stepSize = new Vector2(1 / this.width, 1 / this.height);\n });\n this.onApplyObservable.add((effect) => {\n effect.setTextureFromPostProcess(\"camASampler\", this._passedProcess);\n effect.setFloat2(\"stepSize\", this._stepSize.x, this._stepSize.y);\n });\n }\n}\n//# sourceMappingURL=stereoscopicInterlacePostProcess.js.map","import { Camera } from \"../camera.js\";\nimport { Viewport } from \"../../Maths/math.viewport.js\";\nimport { PassPostProcess } from \"../../PostProcesses/passPostProcess.js\";\nimport { StereoscopicInterlacePostProcessI } from \"../../PostProcesses/stereoscopicInterlacePostProcess.js\";\n/**\n * @internal\n */\nexport function setStereoscopicRigMode(camera) {\n const isStereoscopicHoriz = camera.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || camera.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;\n const isCrossEye = camera.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;\n const isInterlaced = camera.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_INTERLACED;\n // Use post-processors for interlacing\n if (isInterlaced) {\n camera._rigCameras[0]._rigPostProcess = new PassPostProcess(camera.name + \"_passthru\", 1.0, camera._rigCameras[0]);\n camera._rigCameras[1]._rigPostProcess = new StereoscopicInterlacePostProcessI(camera.name + \"_stereoInterlace\", camera._rigCameras, false, true);\n }\n // Otherwise, create appropriate viewports\n else {\n camera._rigCameras[isCrossEye ? 1 : 0].viewport = new Viewport(0, 0, isStereoscopicHoriz ? 0.5 : 1.0, isStereoscopicHoriz ? 1.0 : 0.5);\n camera._rigCameras[isCrossEye ? 0 : 1].viewport = new Viewport(isStereoscopicHoriz ? 0.5 : 0, isStereoscopicHoriz ? 0 : 0.5, isStereoscopicHoriz ? 0.5 : 1.0, isStereoscopicHoriz ? 1.0 : 0.5);\n }\n}\n//# sourceMappingURL=stereoscopicRigMode.js.map","import { Camera } from \"../../Cameras/camera.js\";\nimport { ArcRotateCamera } from \"../../Cameras/arcRotateCamera.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Node } from \"../../node.js\";\nimport { setStereoscopicRigMode } from \"../RigModes/stereoscopicRigMode.js\";\nNode.AddNodeConstructor(\"StereoscopicArcRotateCamera\", (name, scene, options) => {\n return () => new StereoscopicArcRotateCamera(name, 0, 0, 1.0, Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene);\n});\n/**\n * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras\n */\nexport class StereoscopicArcRotateCamera extends ArcRotateCamera {\n /**\n * Creates a new StereoscopicArcRotateCamera\n * @param name defines camera name\n * @param alpha defines alpha angle (in radians)\n * @param beta defines beta angle (in radians)\n * @param radius defines radius\n * @param target defines camera target\n * @param interaxialDistance defines distance between each color axis\n * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under\n * @param scene defines the hosting scene\n */\n constructor(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {\n super(name, alpha, beta, radius, target, scene);\n this._setRigMode = setStereoscopicRigMode.bind(null, this);\n this.interaxialDistance = interaxialDistance;\n this.isStereoscopicSideBySide = isStereoscopicSideBySide;\n this.setCameraRigMode(isStereoscopicSideBySide ? Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, {\n interaxialDistance: interaxialDistance,\n });\n }\n /**\n * Gets camera class name\n * @returns StereoscopicArcRotateCamera\n */\n getClassName() {\n return \"StereoscopicArcRotateCamera\";\n }\n}\n//# sourceMappingURL=stereoscopicArcRotateCamera.js.map","import { Camera } from \"../../Cameras/camera.js\";\nimport { FreeCamera } from \"../../Cameras/freeCamera.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Node } from \"../../node.js\";\nimport { setStereoscopicRigMode } from \"../RigModes/stereoscopicRigMode.js\";\nNode.AddNodeConstructor(\"StereoscopicFreeCamera\", (name, scene, options) => {\n return () => new StereoscopicFreeCamera(name, Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene);\n});\n/**\n * Camera used to simulate stereoscopic rendering (based on FreeCamera)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras\n */\nexport class StereoscopicFreeCamera extends FreeCamera {\n /**\n * Creates a new StereoscopicFreeCamera\n * @param name defines camera name\n * @param position defines initial position\n * @param interaxialDistance defines distance between each color axis\n * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under\n * @param scene defines the hosting scene\n */\n constructor(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {\n super(name, position, scene);\n this._setRigMode = setStereoscopicRigMode.bind(null, this);\n this.interaxialDistance = interaxialDistance;\n this.isStereoscopicSideBySide = isStereoscopicSideBySide;\n this.setCameraRigMode(isStereoscopicSideBySide ? Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, {\n interaxialDistance: interaxialDistance,\n });\n }\n /**\n * Gets camera class name\n * @returns StereoscopicFreeCamera\n */\n getClassName() {\n return \"StereoscopicFreeCamera\";\n }\n}\n//# sourceMappingURL=stereoscopicFreeCamera.js.map","import { Camera } from \"../../Cameras/camera.js\";\nimport { GamepadCamera } from \"../../Cameras/gamepadCamera.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Node } from \"../../node.js\";\nimport { setStereoscopicRigMode } from \"../RigModes/stereoscopicRigMode.js\";\nNode.AddNodeConstructor(\"StereoscopicGamepadCamera\", (name, scene, options) => {\n return () => new StereoscopicGamepadCamera(name, Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene);\n});\n/**\n * Camera used to simulate stereoscopic rendering (based on GamepadCamera)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras\n */\nexport class StereoscopicGamepadCamera extends GamepadCamera {\n /**\n * Creates a new StereoscopicGamepadCamera\n * @param name defines camera name\n * @param position defines initial position\n * @param interaxialDistance defines distance between each color axis\n * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under\n * @param scene defines the hosting scene\n */\n constructor(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {\n super(name, position, scene);\n this._setRigMode = setStereoscopicRigMode.bind(null, this);\n this.interaxialDistance = interaxialDistance;\n this.isStereoscopicSideBySide = isStereoscopicSideBySide;\n this.setCameraRigMode(isStereoscopicSideBySide ? Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, {\n interaxialDistance: interaxialDistance,\n });\n }\n /**\n * Gets camera class name\n * @returns StereoscopicGamepadCamera\n */\n getClassName() {\n return \"StereoscopicGamepadCamera\";\n }\n}\n//# sourceMappingURL=stereoscopicGamepadCamera.js.map","import { Camera } from \"../../Cameras/camera.js\";\nimport { UniversalCamera } from \"../../Cameras/universalCamera.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Node } from \"../../node.js\";\nimport { setStereoscopicRigMode } from \"../RigModes/stereoscopicRigMode.js\";\nNode.AddNodeConstructor(\"StereoscopicFreeCamera\", (name, scene, options) => {\n return () => new StereoscopicUniversalCamera(name, Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene);\n});\n/**\n * Camera used to simulate stereoscopic rendering (based on UniversalCamera)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras\n */\nexport class StereoscopicUniversalCamera extends UniversalCamera {\n /**\n * Creates a new StereoscopicUniversalCamera\n * @param name defines camera name\n * @param position defines initial position\n * @param interaxialDistance defines distance between each color axis\n * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under\n * @param scene defines the hosting scene\n */\n constructor(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {\n super(name, position, scene);\n this._setRigMode = setStereoscopicRigMode.bind(null, this);\n this.interaxialDistance = interaxialDistance;\n this.isStereoscopicSideBySide = isStereoscopicSideBySide;\n this.setCameraRigMode(isStereoscopicSideBySide ? Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, {\n interaxialDistance: interaxialDistance,\n });\n }\n /**\n * Gets camera class name\n * @returns StereoscopicUniversalCamera\n */\n getClassName() {\n return \"StereoscopicUniversalCamera\";\n }\n}\n//# sourceMappingURL=stereoscopicUniversalCamera.js.map","import { Camera } from \"../../Cameras/camera.js\";\nimport { UniversalCamera } from \"../../Cameras/universalCamera.js\";\nimport { Matrix, Vector3 } from \"../../Maths/math.vector.js\";\nimport { TargetCamera } from \"../targetCamera.js\";\nimport { TransformNode } from \"../../Meshes/transformNode.js\";\nimport { Viewport } from \"../../Maths/math.viewport.js\";\n/**\n * Camera used to simulate stereoscopic rendering on real screens (based on UniversalCamera)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras\n */\nexport class StereoscopicScreenUniversalCamera extends UniversalCamera {\n set distanceBetweenEyes(newValue) {\n this._distanceBetweenEyes = newValue;\n }\n /**\n * distance between the eyes\n */\n get distanceBetweenEyes() {\n return this._distanceBetweenEyes;\n }\n set distanceToProjectionPlane(newValue) {\n this._distanceToProjectionPlane = newValue;\n }\n /**\n * Distance to projection plane (should be the same units the like distance between the eyes)\n */\n get distanceToProjectionPlane() {\n return this._distanceToProjectionPlane;\n }\n /**\n * Creates a new StereoscopicScreenUniversalCamera\n * @param name defines camera name\n * @param position defines initial position\n * @param scene defines the hosting scene\n * @param distanceToProjectionPlane defines distance between each color axis. The rig cameras will receive this as their negative z position!\n * @param distanceBetweenEyes defines is stereoscopic is done side by side or over under\n */\n constructor(name, position, scene, distanceToProjectionPlane = 1, distanceBetweenEyes = 0.065) {\n super(name, position, scene);\n this._distanceBetweenEyes = distanceBetweenEyes;\n this._distanceToProjectionPlane = distanceToProjectionPlane;\n this.setCameraRigMode(Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL, {\n stereoHalfAngle: 0,\n });\n this._cameraRigParams.stereoHalfAngle = 0;\n this._cameraRigParams.interaxialDistance = distanceBetweenEyes;\n }\n /**\n * Gets camera class name\n * @returns StereoscopicScreenUniversalCamera\n */\n getClassName() {\n return \"StereoscopicUniversalCamera\";\n }\n /**\n * @internal\n */\n createRigCamera(name) {\n const camera = new TargetCamera(name, Vector3.Zero(), this.getScene());\n const transform = new TransformNode(\"tm_\" + name, this.getScene());\n camera.parent = transform;\n transform.setPivotMatrix(Matrix.Identity(), false);\n camera.isRigCamera = true;\n camera.rigParent = this;\n return camera;\n }\n /**\n * @internal\n */\n _updateRigCameras() {\n for (let cameraIndex = 0; cameraIndex < this._rigCameras.length; cameraIndex++) {\n const cam = this._rigCameras[cameraIndex];\n cam.minZ = this.minZ;\n cam.maxZ = this.maxZ;\n cam.fov = this.fov;\n cam.upVector.copyFrom(this.upVector);\n if (cam.rotationQuaternion) {\n cam.rotationQuaternion.copyFrom(this.rotationQuaternion);\n }\n else {\n cam.rotation.copyFrom(this.rotation);\n }\n this._updateCamera(this._rigCameras[cameraIndex], cameraIndex);\n }\n }\n _updateCamera(camera, cameraIndex) {\n const b = this.distanceBetweenEyes / 2;\n const z = b / this.distanceToProjectionPlane;\n camera.position.copyFrom(this.position);\n camera.position.addInPlaceFromFloats(cameraIndex === 0 ? -b : b, 0, -this._distanceToProjectionPlane);\n const transform = camera.parent;\n const m = transform.getPivotMatrix();\n m.setTranslationFromFloats(cameraIndex === 0 ? b : -b, 0, 0);\n m.setRowFromFloats(2, cameraIndex === 0 ? z : -z, 0, 1, 0);\n transform.setPivotMatrix(m, false);\n }\n _setRigMode() {\n this._rigCameras[0].viewport = new Viewport(0, 0, 0.5, 1);\n this._rigCameras[1].viewport = new Viewport(0.5, 0, 0.5, 1.0);\n for (let cameraIndex = 0; cameraIndex < this._rigCameras.length; cameraIndex++) {\n this._updateCamera(this._rigCameras[cameraIndex], cameraIndex);\n }\n }\n}\n//# sourceMappingURL=stereoscopicScreenUniversalCamera.js.map","import { Matrix } from \"../../Maths/math.vector.js\";\n/**\n * This represents all the required metrics to create a VR camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#device-orientation-camera\n */\nexport class VRCameraMetrics {\n constructor() {\n /**\n * Define if the current vr camera should compensate the distortion of the lens or not.\n */\n this.compensateDistortion = true;\n /**\n * Defines if multiview should be enabled when rendering (Default: false)\n */\n this.multiviewEnabled = false;\n }\n /**\n * Gets the rendering aspect ratio based on the provided resolutions.\n */\n get aspectRatio() {\n return this.hResolution / (2 * this.vResolution);\n }\n /**\n * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.\n */\n get aspectRatioFov() {\n return 2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance));\n }\n /**\n * @internal\n */\n get leftHMatrix() {\n const meters = this.hScreenSize / 4 - this.lensSeparationDistance / 2;\n const h = (4 * meters) / this.hScreenSize;\n return Matrix.Translation(h, 0, 0);\n }\n /**\n * @internal\n */\n get rightHMatrix() {\n const meters = this.hScreenSize / 4 - this.lensSeparationDistance / 2;\n const h = (4 * meters) / this.hScreenSize;\n return Matrix.Translation(-h, 0, 0);\n }\n /**\n * @internal\n */\n get leftPreViewMatrix() {\n return Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);\n }\n /**\n * @internal\n */\n get rightPreViewMatrix() {\n return Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);\n }\n /**\n * Get the default VRMetrics based on the most generic setup.\n * @returns the default vr metrics\n */\n static GetDefault() {\n const result = new VRCameraMetrics();\n result.hResolution = 1280;\n result.vResolution = 800;\n result.hScreenSize = 0.149759993;\n result.vScreenSize = 0.0935999975;\n result.vScreenCenter = 0.0467999987;\n result.eyeToScreenDistance = 0.0410000011;\n result.lensSeparationDistance = 0.063500002;\n result.interpupillaryDistance = 0.064000003;\n result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];\n result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];\n result.postProcessScaleFactor = 1.714605507808412;\n result.lensCenterOffset = 0.151976421;\n return result;\n }\n}\n//# sourceMappingURL=vrCameraMetrics.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"vrDistortionCorrectionPixelShader\";\nconst shader = `varying vec2 vUV;\runiform sampler2D textureSampler;\runiform vec2 LensCenter;\runiform vec2 Scale;\runiform vec2 ScaleIn;\runiform vec4 HmdWarpParam;\rvec2 HmdWarp(vec2 in01) {\rvec2 theta=(in01-LensCenter)*ScaleIn; \rfloat rSq=theta.x*theta.x+theta.y*theta.y;\rvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\rreturn LensCenter+Scale*rvector;\r}\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\r{\rvec2 tc=HmdWarp(vUV);\rif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\rgl_FragColor=vec4(0.0,0.0,0.0,0.0);\relse{\rgl_FragColor=texture2D(textureSampler,tc);\r}\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const vrDistortionCorrectionPixelShader = { name, shader };\n//# sourceMappingURL=vrDistortionCorrection.fragment.js.map","import { Vector2 } from \"../Maths/math.vector.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { PostProcess } from \"./postProcess.js\";\nimport \"../Shaders/vrDistortionCorrection.fragment.js\";\n/**\n * VRDistortionCorrectionPostProcess used for mobile VR\n */\nexport class VRDistortionCorrectionPostProcess extends PostProcess {\n /**\n * Gets a string identifying the name of the class\n * @returns \"VRDistortionCorrectionPostProcess\" string\n */\n getClassName() {\n return \"VRDistortionCorrectionPostProcess\";\n }\n /**\n * Initializes the VRDistortionCorrectionPostProcess\n * @param name The name of the effect.\n * @param camera The camera to apply the render pass to.\n * @param isRightEye If this is for the right eye distortion\n * @param vrMetrics All the required metrics for the VR camera\n */\n constructor(name, camera, isRightEye, vrMetrics) {\n super(name, \"vrDistortionCorrection\", [\"LensCenter\", \"Scale\", \"ScaleIn\", \"HmdWarpParam\"], null, vrMetrics.postProcessScaleFactor, camera, Texture.BILINEAR_SAMPLINGMODE);\n this._isRightEye = isRightEye;\n this._distortionFactors = vrMetrics.distortionK;\n this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;\n this._lensCenterOffset = vrMetrics.lensCenterOffset;\n this.adaptScaleToCurrentViewport = true;\n this.onSizeChangedObservable.add(() => {\n this._scaleIn = new Vector2(2, 2 / this.aspectRatio);\n this._scaleFactor = new Vector2(0.5 * (1 / this._postProcessScaleFactor), 0.5 * (1 / this._postProcessScaleFactor) * this.aspectRatio);\n this._lensCenter = new Vector2(this._isRightEye ? 0.5 - this._lensCenterOffset * 0.5 : 0.5 + this._lensCenterOffset * 0.5, 0.5);\n });\n this.onApplyObservable.add((effect) => {\n effect.setFloat2(\"LensCenter\", this._lensCenter.x, this._lensCenter.y);\n effect.setFloat2(\"Scale\", this._scaleFactor.x, this._scaleFactor.y);\n effect.setFloat2(\"ScaleIn\", this._scaleIn.x, this._scaleIn.y);\n effect.setFloat4(\"HmdWarpParam\", this._distortionFactors[0], this._distortionFactors[1], this._distortionFactors[2], this._distortionFactors[3]);\n });\n }\n}\n//# sourceMappingURL=vrDistortionCorrectionPostProcess.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"vrMultiviewToSingleviewPixelShader\";\nconst shader = `precision mediump sampler2DArray;\rvarying vec2 vUV;\runiform sampler2DArray multiviewSampler;\runiform int imageIndex;\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\r{\rgl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const vrMultiviewToSingleviewPixelShader = { name, shader };\n//# sourceMappingURL=vrMultiviewToSingleview.fragment.js.map","import { RenderTargetTexture } from \"../Textures/renderTargetTexture.js\";\n\n/**\n * Renders to multiple views with a single draw call\n * @see https://www.khronos.org/registry/webgl/extensions/OVR_multiview2/\n */\nexport class MultiviewRenderTarget extends RenderTargetTexture {\n set samples(value) {\n // We override this setter because multisampling is handled by framebufferTextureMultisampleMultiviewOVR\n this._samples = value;\n }\n get samples() {\n return this._samples;\n }\n /**\n * Creates a multiview render target\n * @param scene scene used with the render target\n * @param size the size of the render target (used for each view)\n */\n constructor(scene, size = 512) {\n super(\"multiview rtt\", size, scene, false, true, 0, false, undefined, false, false, true, undefined, true);\n this._renderTarget = this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(), this.getRenderHeight());\n this._texture = this._renderTarget.texture;\n this._texture.isMultiview = true;\n this._texture.format = 5;\n this.samples = this._getEngine().getCaps().maxSamples || this.samples;\n this._texture.samples = this._samples;\n }\n /**\n * @internal\n */\n _bindFrameBuffer() {\n if (!this._renderTarget) {\n return;\n }\n this.getScene().getEngine().bindMultiviewFramebuffer(this._renderTarget);\n }\n /**\n * Gets the number of views the corresponding to the texture (eg. a MultiviewRenderTarget will have > 1)\n * @returns the view count\n */\n getViewCount() {\n return 2;\n }\n}\n//# sourceMappingURL=MultiviewRenderTarget.js.map","import { Camera } from \"../../Cameras/camera.js\";\nimport { Engine } from \"../../Engines/engine.js\";\nimport { Scene } from \"../../scene.js\";\nimport { InternalTexture, InternalTextureSource } from \"../../Materials/Textures/internalTexture.js\";\nimport { Matrix, TmpVectors } from \"../../Maths/math.vector.js\";\nimport { UniformBuffer } from \"../../Materials/uniformBuffer.js\";\nimport { MultiviewRenderTarget } from \"../../Materials/Textures/MultiviewRenderTarget.js\";\nimport { Frustum } from \"../../Maths/math.frustum.js\";\nEngine.prototype.createMultiviewRenderTargetTexture = function (width, height, colorTexture, depthStencilTexture) {\n const gl = this._gl;\n if (!this.getCaps().multiview) {\n throw \"Multiview is not supported\";\n }\n const rtWrapper = this._createHardwareRenderTargetWrapper(false, false, { width, height });\n rtWrapper._framebuffer = gl.createFramebuffer();\n const internalTexture = new InternalTexture(this, InternalTextureSource.Unknown, true);\n internalTexture.width = width;\n internalTexture.height = height;\n internalTexture.isMultiview = true;\n if (!colorTexture) {\n colorTexture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D_ARRAY, colorTexture);\n gl.texStorage3D(gl.TEXTURE_2D_ARRAY, 1, gl.RGBA8, width, height, 2);\n }\n rtWrapper._colorTextureArray = colorTexture;\n if (!depthStencilTexture) {\n depthStencilTexture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D_ARRAY, depthStencilTexture);\n gl.texStorage3D(gl.TEXTURE_2D_ARRAY, 1, gl.DEPTH24_STENCIL8, width, height, 2);\n }\n rtWrapper._depthStencilTextureArray = depthStencilTexture;\n internalTexture.isReady = true;\n rtWrapper.setTextures(internalTexture);\n rtWrapper._depthStencilTexture = internalTexture;\n return rtWrapper;\n};\nEngine.prototype.bindMultiviewFramebuffer = function (_multiviewTexture) {\n const multiviewTexture = _multiviewTexture;\n const gl = this._gl;\n const ext = this.getCaps().oculusMultiview || this.getCaps().multiview;\n this.bindFramebuffer(multiviewTexture, undefined, undefined, undefined, true);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, multiviewTexture._framebuffer);\n if (multiviewTexture._colorTextureArray && multiviewTexture._depthStencilTextureArray) {\n if (this.getCaps().oculusMultiview) {\n ext.framebufferTextureMultisampleMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, multiviewTexture._colorTextureArray, 0, multiviewTexture.samples, 0, 2);\n ext.framebufferTextureMultisampleMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, multiviewTexture._depthStencilTextureArray, 0, multiviewTexture.samples, 0, 2);\n }\n else {\n ext.framebufferTextureMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, multiviewTexture._colorTextureArray, 0, 0, 2);\n ext.framebufferTextureMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, multiviewTexture._depthStencilTextureArray, 0, 0, 2);\n }\n }\n else {\n throw \"Invalid multiview frame buffer\";\n }\n};\nEngine.prototype.bindSpaceWarpFramebuffer = function (_spaceWarpTexture) {\n const spaceWarpTexture = _spaceWarpTexture;\n const gl = this._gl;\n const ext = this.getCaps().oculusMultiview || this.getCaps().multiview;\n this.bindFramebuffer(spaceWarpTexture, undefined, undefined, undefined, true);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, spaceWarpTexture._framebuffer);\n if (spaceWarpTexture._colorTextureArray && spaceWarpTexture._depthStencilTextureArray) {\n ext.framebufferTextureMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, spaceWarpTexture._colorTextureArray, 0, 0, 2);\n ext.framebufferTextureMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.DEPTH_ATTACHMENT, spaceWarpTexture._depthStencilTextureArray, 0, 0, 2);\n }\n else {\n throw new Error(\"Invalid Space Warp framebuffer\");\n }\n};\nCamera.prototype._useMultiviewToSingleView = false;\nCamera.prototype._multiviewTexture = null;\nCamera.prototype._resizeOrCreateMultiviewTexture = function (width, height) {\n if (!this._multiviewTexture) {\n this._multiviewTexture = new MultiviewRenderTarget(this.getScene(), { width: width, height: height });\n }\n else if (this._multiviewTexture.getRenderWidth() != width || this._multiviewTexture.getRenderHeight() != height) {\n this._multiviewTexture.dispose();\n this._multiviewTexture = new MultiviewRenderTarget(this.getScene(), { width: width, height: height });\n }\n};\nfunction createMultiviewUbo(engine, name) {\n const ubo = new UniformBuffer(engine, undefined, true, name);\n ubo.addUniform(\"viewProjection\", 16);\n ubo.addUniform(\"viewProjectionR\", 16);\n ubo.addUniform(\"view\", 16);\n ubo.addUniform(\"projection\", 16);\n ubo.addUniform(\"vEyePosition\", 4);\n return ubo;\n}\nconst currentCreateSceneUniformBuffer = Scene.prototype.createSceneUniformBuffer;\nScene.prototype._transformMatrixR = Matrix.Zero();\nScene.prototype._multiviewSceneUbo = null;\nScene.prototype._createMultiviewUbo = function () {\n this._multiviewSceneUbo = createMultiviewUbo(this.getEngine(), \"scene_multiview\");\n};\nScene.prototype.createSceneUniformBuffer = function (name) {\n if (this._multiviewSceneUbo) {\n return createMultiviewUbo(this.getEngine(), name);\n }\n return currentCreateSceneUniformBuffer.bind(this)(name);\n};\nScene.prototype._updateMultiviewUbo = function (viewR, projectionR) {\n if (viewR && projectionR) {\n viewR.multiplyToRef(projectionR, this._transformMatrixR);\n }\n if (viewR && projectionR) {\n viewR.multiplyToRef(projectionR, TmpVectors.Matrix[0]);\n Frustum.GetRightPlaneToRef(TmpVectors.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane\n }\n if (this._multiviewSceneUbo) {\n this._multiviewSceneUbo.updateMatrix(\"viewProjection\", this.getTransformMatrix());\n this._multiviewSceneUbo.updateMatrix(\"viewProjectionR\", this._transformMatrixR);\n this._multiviewSceneUbo.updateMatrix(\"view\", this._viewMatrix);\n this._multiviewSceneUbo.updateMatrix(\"projection\", this._projectionMatrix);\n }\n};\nScene.prototype._renderMultiviewToSingleView = function (camera) {\n // Multiview is only able to be displayed directly for API's such as webXR\n // This displays a multiview image by rendering to the multiview image and then\n // copying the result into the sub cameras instead of rendering them and proceeding as normal from there\n // Render to a multiview texture\n camera._resizeOrCreateMultiviewTexture(camera._rigPostProcess && camera._rigPostProcess && camera._rigPostProcess.width > 0 ? camera._rigPostProcess.width : this.getEngine().getRenderWidth(true), camera._rigPostProcess && camera._rigPostProcess && camera._rigPostProcess.height > 0 ? camera._rigPostProcess.height : this.getEngine().getRenderHeight(true));\n if (!this._multiviewSceneUbo) {\n this._createMultiviewUbo();\n }\n camera.outputRenderTarget = camera._multiviewTexture;\n this._renderForCamera(camera);\n camera.outputRenderTarget = null;\n // Consume the multiview texture through a shader for each eye\n for (let index = 0; index < camera._rigCameras.length; index++) {\n const engine = this.getEngine();\n this._activeCamera = camera._rigCameras[index];\n engine.setViewport(this._activeCamera.viewport);\n if (this.postProcessManager) {\n this.postProcessManager._prepareFrame();\n this.postProcessManager._finalizeFrame(this._activeCamera.isIntermediate);\n }\n }\n};\n//# sourceMappingURL=engine.multiview.js.map","import { Matrix } from \"../../Maths/math.vector.js\";\nimport { VRDistortionCorrectionPostProcess } from \"../../PostProcesses/vrDistortionCorrectionPostProcess.js\";\nimport { VRMultiviewToSingleviewPostProcess } from \"../../PostProcesses/vrMultiviewToSingleviewPostProcess.js\";\nimport { VRCameraMetrics } from \"../VR/vrCameraMetrics.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { Viewport } from \"../../Maths/math.viewport.js\";\n/**\n * @internal\n */\nexport function setVRRigMode(camera, rigParams) {\n const metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();\n camera._rigCameras[0]._cameraRigParams.vrMetrics = metrics;\n camera._rigCameras[0].viewport = new Viewport(0, 0, 0.5, 1.0);\n camera._rigCameras[0]._cameraRigParams.vrWorkMatrix = new Matrix();\n camera._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;\n camera._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;\n camera._rigCameras[0].getProjectionMatrix = camera._rigCameras[0]._getVRProjectionMatrix;\n camera._rigCameras[1]._cameraRigParams.vrMetrics = metrics;\n camera._rigCameras[1].viewport = new Viewport(0.5, 0, 0.5, 1.0);\n camera._rigCameras[1]._cameraRigParams.vrWorkMatrix = new Matrix();\n camera._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;\n camera._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;\n camera._rigCameras[1].getProjectionMatrix = camera._rigCameras[1]._getVRProjectionMatrix;\n // For multiview on a webVR camera\n // First multiview will be rendered to camera._multiviewTexture\n // Then this postprocess will run on each eye to copy the right texture to each eye\n if (metrics.multiviewEnabled) {\n if (!camera.getScene().getEngine().getCaps().multiview) {\n Logger.Warn(\"Multiview is not supported, falling back to standard rendering\");\n metrics.multiviewEnabled = false;\n }\n else {\n camera._useMultiviewToSingleView = true;\n camera._rigPostProcess = new VRMultiviewToSingleviewPostProcess(\"VRMultiviewToSingleview\", camera, metrics.postProcessScaleFactor);\n }\n }\n if (metrics.compensateDistortion) {\n camera._rigCameras[0]._rigPostProcess = new VRDistortionCorrectionPostProcess(\"VR_Distort_Compensation_Left\", camera._rigCameras[0], false, metrics);\n camera._rigCameras[1]._rigPostProcess = new VRDistortionCorrectionPostProcess(\"VR_Distort_Compensation_Right\", camera._rigCameras[1], true, metrics);\n }\n}\n//# sourceMappingURL=vrRigMode.js.map","import { Texture } from \"../Materials/Textures/texture.js\";\nimport { PostProcess } from \"./postProcess.js\";\nimport \"../Shaders/vrMultiviewToSingleview.fragment.js\";\nimport \"../Engines/Extensions/engine.multiview.js\";\n/**\n * VRMultiviewToSingleview used to convert multiview texture arrays to standard textures for scenarios such as webVR\n * This will not be used for webXR as it supports displaying texture arrays directly\n */\nexport class VRMultiviewToSingleviewPostProcess extends PostProcess {\n /**\n * Gets a string identifying the name of the class\n * @returns \"VRMultiviewToSingleviewPostProcess\" string\n */\n getClassName() {\n return \"VRMultiviewToSingleviewPostProcess\";\n }\n /**\n * Initializes a VRMultiviewToSingleview\n * @param name name of the post process\n * @param camera camera to be applied to\n * @param scaleFactor scaling factor to the size of the output texture\n */\n constructor(name, camera, scaleFactor) {\n super(name, \"vrMultiviewToSingleview\", [\"imageIndex\"], [\"multiviewSampler\"], scaleFactor, camera, Texture.BILINEAR_SAMPLINGMODE);\n const cam = camera !== null && camera !== void 0 ? camera : this.getCamera();\n this.onSizeChangedObservable.add(() => { });\n this.onApplyObservable.add((effect) => {\n if (cam._scene.activeCamera && cam._scene.activeCamera.isLeftCamera) {\n effect.setInt(\"imageIndex\", 0);\n }\n else {\n effect.setInt(\"imageIndex\", 1);\n }\n effect.setTexture(\"multiviewSampler\", cam._multiviewTexture);\n });\n }\n}\n//# sourceMappingURL=vrMultiviewToSingleviewPostProcess.js.map","import { Camera } from \"../../Cameras/camera.js\";\nimport { ArcRotateCamera } from \"../../Cameras/arcRotateCamera.js\";\nimport { VRCameraMetrics } from \"./vrCameraMetrics.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Node } from \"../../node.js\";\nimport { setVRRigMode } from \"../RigModes/vrRigMode.js\";\nimport \"../Inputs/arcRotateCameraVRDeviceOrientationInput.js\";\nNode.AddNodeConstructor(\"VRDeviceOrientationArcRotateCamera\", (name, scene) => {\n return () => new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, Vector3.Zero(), scene);\n});\n/**\n * Camera used to simulate VR rendering (based on ArcRotateCamera)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#vr-device-orientation-cameras\n */\nexport class VRDeviceOrientationArcRotateCamera extends ArcRotateCamera {\n /**\n * Creates a new VRDeviceOrientationArcRotateCamera\n * @param name defines camera name\n * @param alpha defines the camera rotation along the longitudinal axis\n * @param beta defines the camera rotation along the latitudinal axis\n * @param radius defines the camera distance from its target\n * @param target defines the camera target\n * @param scene defines the scene the camera belongs to\n * @param compensateDistortion defines if the camera needs to compensate the lens distortion\n * @param vrCameraMetrics defines the vr metrics associated to the camera\n */\n constructor(name, alpha, beta, radius, target, scene, compensateDistortion = true, vrCameraMetrics = VRCameraMetrics.GetDefault()) {\n super(name, alpha, beta, radius, target, scene);\n this._setRigMode = setVRRigMode.bind(null, this);\n vrCameraMetrics.compensateDistortion = compensateDistortion;\n this.setCameraRigMode(Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });\n this.inputs.addVRDeviceOrientation();\n }\n /**\n * Gets camera class name\n * @returns VRDeviceOrientationArcRotateCamera\n */\n getClassName() {\n return \"VRDeviceOrientationArcRotateCamera\";\n }\n}\n//# sourceMappingURL=vrDeviceOrientationArcRotateCamera.js.map","import { Camera } from \"../../Cameras/camera.js\";\nimport { DeviceOrientationCamera } from \"../../Cameras/deviceOrientationCamera.js\";\nimport { VRCameraMetrics } from \"./vrCameraMetrics.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Node } from \"../../node.js\";\nimport { setVRRigMode } from \"../RigModes/vrRigMode.js\";\nNode.AddNodeConstructor(\"VRDeviceOrientationFreeCamera\", (name, scene) => {\n return () => new VRDeviceOrientationFreeCamera(name, Vector3.Zero(), scene);\n});\n/**\n * Camera used to simulate VR rendering (based on FreeCamera)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#vr-device-orientation-cameras\n */\nexport class VRDeviceOrientationFreeCamera extends DeviceOrientationCamera {\n /**\n * Creates a new VRDeviceOrientationFreeCamera\n * @param name defines camera name\n * @param position defines the start position of the camera\n * @param scene defines the scene the camera belongs to\n * @param compensateDistortion defines if the camera needs to compensate the lens distortion\n * @param vrCameraMetrics defines the vr metrics associated to the camera\n */\n constructor(name, position, scene, compensateDistortion = true, vrCameraMetrics = VRCameraMetrics.GetDefault()) {\n super(name, position, scene);\n this._setRigMode = setVRRigMode.bind(null, this);\n vrCameraMetrics.compensateDistortion = compensateDistortion;\n this.setCameraRigMode(Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });\n }\n /**\n * Gets camera class name\n * @returns VRDeviceOrientationFreeCamera\n */\n getClassName() {\n return \"VRDeviceOrientationFreeCamera\";\n }\n}\n//# sourceMappingURL=vrDeviceOrientationFreeCamera.js.map","import { VRDeviceOrientationFreeCamera } from \"./vrDeviceOrientationFreeCamera.js\";\nimport { VRCameraMetrics } from \"./vrCameraMetrics.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Node } from \"../../node.js\";\nimport { setVRRigMode } from \"../RigModes/vrRigMode.js\";\nimport \"../../Gamepads/gamepadSceneComponent.js\";\nNode.AddNodeConstructor(\"VRDeviceOrientationGamepadCamera\", (name, scene) => {\n return () => new VRDeviceOrientationGamepadCamera(name, Vector3.Zero(), scene);\n});\n/**\n * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#vr-device-orientation-cameras\n */\nexport class VRDeviceOrientationGamepadCamera extends VRDeviceOrientationFreeCamera {\n /**\n * Creates a new VRDeviceOrientationGamepadCamera\n * @param name defines camera name\n * @param position defines the start position of the camera\n * @param scene defines the scene the camera belongs to\n * @param compensateDistortion defines if the camera needs to compensate the lens distortion\n * @param vrCameraMetrics defines the vr metrics associated to the camera\n */\n constructor(name, position, scene, compensateDistortion = true, vrCameraMetrics = VRCameraMetrics.GetDefault()) {\n super(name, position, scene, compensateDistortion, vrCameraMetrics);\n this._setRigMode = setVRRigMode.bind(null, this);\n this.inputs.addGamepad();\n }\n /**\n * Gets camera class name\n * @returns VRDeviceOrientationGamepadCamera\n */\n getClassName() {\n return \"VRDeviceOrientationGamepadCamera\";\n }\n}\n//# sourceMappingURL=vrDeviceOrientationGamepadCamera.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serializeAsColor3, serializeAsVector3 } from \"../Misc/decorators.js\";\nimport { Matrix, Vector3 } from \"../Maths/math.vector.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { Node } from \"../node.js\";\nimport { Light } from \"./light.js\";\nNode.AddNodeConstructor(\"Light_Type_3\", (name, scene) => {\n return () => new HemisphericLight(name, Vector3.Zero(), scene);\n});\n/**\n * The HemisphericLight simulates the ambient environment light,\n * so the passed direction is the light reflection direction, not the incoming direction.\n */\nexport class HemisphericLight extends Light {\n /**\n * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).\n * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.\n * The HemisphericLight can't cast shadows.\n * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction\n * @param name The friendly name of the light\n * @param direction The direction of the light reflection\n * @param scene The scene the light belongs to\n */\n constructor(name, direction, scene) {\n super(name, scene);\n /**\n * The groundColor is the light in the opposite direction to the one specified during creation.\n * You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction.\n */\n this.groundColor = new Color3(0.0, 0.0, 0.0);\n this.direction = direction || Vector3.Up();\n }\n _buildUniformLayout() {\n this._uniformBuffer.addUniform(\"vLightData\", 4);\n this._uniformBuffer.addUniform(\"vLightDiffuse\", 4);\n this._uniformBuffer.addUniform(\"vLightSpecular\", 4);\n this._uniformBuffer.addUniform(\"vLightGround\", 3);\n this._uniformBuffer.addUniform(\"shadowsInfo\", 3);\n this._uniformBuffer.addUniform(\"depthValues\", 2);\n this._uniformBuffer.create();\n }\n /**\n * Returns the string \"HemisphericLight\".\n * @returns The class name\n */\n getClassName() {\n return \"HemisphericLight\";\n }\n /**\n * Sets the HemisphericLight direction towards the passed target (Vector3).\n * Returns the updated direction.\n * @param target The target the direction should point to\n * @returns The computed direction\n */\n setDirectionToTarget(target) {\n this.direction = Vector3.Normalize(target.subtract(Vector3.Zero()));\n return this.direction;\n }\n /**\n * Returns the shadow generator associated to the light.\n * @returns Always null for hemispheric lights because it does not support shadows.\n */\n getShadowGenerator() {\n return null;\n }\n /**\n * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).\n * @param _effect The effect to update\n * @param lightIndex The index of the light in the effect to update\n * @returns The hemispheric light\n */\n transferToEffect(_effect, lightIndex) {\n const normalizeDirection = Vector3.Normalize(this.direction);\n this._uniformBuffer.updateFloat4(\"vLightData\", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);\n this._uniformBuffer.updateColor3(\"vLightGround\", this.groundColor.scale(this.intensity), lightIndex);\n return this;\n }\n transferToNodeMaterialEffect(effect, lightDataUniformName) {\n const normalizeDirection = Vector3.Normalize(this.direction);\n effect.setFloat3(lightDataUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z);\n return this;\n }\n /**\n * Computes the world matrix of the node\n * @returns the world matrix\n */\n computeWorldMatrix() {\n if (!this._worldMatrix) {\n this._worldMatrix = Matrix.Identity();\n }\n return this._worldMatrix;\n }\n /**\n * Returns the integer 3.\n * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x\n */\n getTypeID() {\n return Light.LIGHTTYPEID_HEMISPHERICLIGHT;\n }\n /**\n * Prepares the list of defines specific to the light type.\n * @param defines the list of defines\n * @param lightIndex defines the index of the light for the effect\n */\n prepareLightSpecificDefines(defines, lightIndex) {\n defines[\"HEMILIGHT\" + lightIndex] = true;\n }\n}\n__decorate([\n serializeAsColor3()\n], HemisphericLight.prototype, \"groundColor\", void 0);\n__decorate([\n serializeAsVector3()\n], HemisphericLight.prototype, \"direction\", void 0);\n//# sourceMappingURL=hemisphericLight.js.map","import { Matrix } from \"../../Maths/math.vector.js\";\nimport { Viewport } from \"../../Maths/math.viewport.js\";\n/**\n * @internal\n */\nexport function setWebVRRigMode(camera, rigParams) {\n if (rigParams.vrDisplay) {\n const leftEye = rigParams.vrDisplay.getEyeParameters(\"left\");\n const rightEye = rigParams.vrDisplay.getEyeParameters(\"right\");\n //Left eye\n camera._rigCameras[0].viewport = new Viewport(0, 0, 0.5, 1.0);\n camera._rigCameras[0].setCameraRigParameter(\"left\", true);\n //leaving this for future reference\n camera._rigCameras[0].setCameraRigParameter(\"specs\", rigParams.specs);\n camera._rigCameras[0].setCameraRigParameter(\"eyeParameters\", leftEye);\n camera._rigCameras[0].setCameraRigParameter(\"frameData\", rigParams.frameData);\n camera._rigCameras[0].setCameraRigParameter(\"parentCamera\", rigParams.parentCamera);\n camera._rigCameras[0]._cameraRigParams.vrWorkMatrix = new Matrix();\n camera._rigCameras[0].getProjectionMatrix = camera._getWebVRProjectionMatrix;\n camera._rigCameras[0].parent = camera;\n camera._rigCameras[0]._getViewMatrix = camera._getWebVRViewMatrix;\n //Right eye\n camera._rigCameras[1].viewport = new Viewport(0.5, 0, 0.5, 1.0);\n camera._rigCameras[1].setCameraRigParameter(\"eyeParameters\", rightEye);\n camera._rigCameras[1].setCameraRigParameter(\"specs\", rigParams.specs);\n camera._rigCameras[1].setCameraRigParameter(\"frameData\", rigParams.frameData);\n camera._rigCameras[1].setCameraRigParameter(\"parentCamera\", rigParams.parentCamera);\n camera._rigCameras[1]._cameraRigParams.vrWorkMatrix = new Matrix();\n camera._rigCameras[1].getProjectionMatrix = camera._getWebVRProjectionMatrix;\n camera._rigCameras[1].parent = camera;\n camera._rigCameras[1]._getViewMatrix = camera._getWebVRViewMatrix;\n }\n}\n//# sourceMappingURL=webVRRigMode.js.map","import { Engine } from \"../../Engines/engine.js\";\nimport { Size } from \"../../Maths/math.size.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nimport { IsWindowObjectExist } from \"../../Misc/domManagement.js\";\nObject.defineProperty(Engine.prototype, \"isInVRExclusivePointerMode\", {\n get: function () {\n return this._vrExclusivePointerMode;\n },\n enumerable: true,\n configurable: true,\n});\nEngine.prototype._prepareVRComponent = function () {\n this._vrSupported = false;\n this._vrExclusivePointerMode = false;\n this.onVRDisplayChangedObservable = new Observable();\n this.onVRRequestPresentComplete = new Observable();\n this.onVRRequestPresentStart = new Observable();\n};\nEngine.prototype.isVRDevicePresent = function () {\n return !!this._vrDisplay;\n};\nEngine.prototype.getVRDevice = function () {\n return this._vrDisplay;\n};\nEngine.prototype.initWebVR = function () {\n this.initWebVRAsync();\n return this.onVRDisplayChangedObservable;\n};\nEngine.prototype.initWebVRAsync = function () {\n const notifyObservers = () => {\n const eventArgs = {\n vrDisplay: this._vrDisplay,\n vrSupported: this._vrSupported,\n };\n this.onVRDisplayChangedObservable.notifyObservers(eventArgs);\n this._webVRInitPromise = new Promise((res) => {\n res(eventArgs);\n });\n };\n if (!this._onVrDisplayConnect) {\n this._onVrDisplayConnect = (event) => {\n this._vrDisplay = event.display;\n notifyObservers();\n };\n this._onVrDisplayDisconnect = () => {\n this._vrDisplay.cancelAnimationFrame(this._frameHandler);\n this._vrDisplay = undefined;\n this._frameHandler = Engine.QueueNewFrame(this._boundRenderFunction);\n notifyObservers();\n };\n this._onVrDisplayPresentChange = () => {\n this._vrExclusivePointerMode = this._vrDisplay && this._vrDisplay.isPresenting;\n };\n const hostWindow = this.getHostWindow();\n if (hostWindow) {\n hostWindow.addEventListener(\"vrdisplayconnect\", this._onVrDisplayConnect);\n hostWindow.addEventListener(\"vrdisplaydisconnect\", this._onVrDisplayDisconnect);\n hostWindow.addEventListener(\"vrdisplaypresentchange\", this._onVrDisplayPresentChange);\n }\n }\n this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();\n this._webVRInitPromise.then(notifyObservers);\n return this._webVRInitPromise;\n};\nEngine.prototype._getVRDisplaysAsync = function () {\n return new Promise((res) => {\n if (navigator.getVRDisplays) {\n navigator.getVRDisplays().then((devices) => {\n this._vrSupported = true;\n // note that devices may actually be an empty array. This is fine;\n // we expect this._vrDisplay to be undefined in this case.\n this._vrDisplay = devices[0];\n res({\n vrDisplay: this._vrDisplay,\n vrSupported: this._vrSupported,\n });\n });\n }\n else {\n this._vrDisplay = undefined;\n this._vrSupported = false;\n res({\n vrDisplay: this._vrDisplay,\n vrSupported: this._vrSupported,\n });\n }\n });\n};\nEngine.prototype.enableVR = function (options) {\n if (this._vrDisplay && !this._vrDisplay.isPresenting) {\n const onResolved = () => {\n this.onVRRequestPresentComplete.notifyObservers(true);\n this._onVRFullScreenTriggered();\n };\n const onRejected = () => {\n this.onVRRequestPresentComplete.notifyObservers(false);\n };\n this.onVRRequestPresentStart.notifyObservers(this);\n const presentationAttributes = {\n highRefreshRate: this.vrPresentationAttributes ? this.vrPresentationAttributes.highRefreshRate : false,\n foveationLevel: this.vrPresentationAttributes ? this.vrPresentationAttributes.foveationLevel : 1,\n multiview: (this.getCaps().multiview || this.getCaps().oculusMultiview) && options.useMultiview,\n };\n this._vrDisplay\n .requestPresent([\n Object.assign({ source: this.getRenderingCanvas(), attributes: presentationAttributes }, presentationAttributes),\n ])\n .then(onResolved)\n .catch(onRejected);\n }\n};\nEngine.prototype._onVRFullScreenTriggered = function () {\n if (this._vrDisplay && this._vrDisplay.isPresenting) {\n //get the old size before we change\n this._oldSize = new Size(this.getRenderWidth(), this.getRenderHeight());\n this._oldHardwareScaleFactor = this.getHardwareScalingLevel();\n //get the width and height, change the render size\n const leftEye = this._vrDisplay.getEyeParameters(\"left\");\n this.setHardwareScalingLevel(1);\n this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);\n }\n else {\n this.setHardwareScalingLevel(this._oldHardwareScaleFactor);\n this.setSize(this._oldSize.width, this._oldSize.height);\n }\n};\nEngine.prototype.disableVR = function () {\n if (this._vrDisplay && this._vrDisplay.isPresenting) {\n this._vrDisplay\n .exitPresent()\n .then(() => this._onVRFullScreenTriggered())\n .catch(() => this._onVRFullScreenTriggered());\n }\n if (IsWindowObjectExist()) {\n window.removeEventListener(\"vrdisplaypointerrestricted\", this._onVRDisplayPointerRestricted);\n window.removeEventListener(\"vrdisplaypointerunrestricted\", this._onVRDisplayPointerUnrestricted);\n if (this._onVrDisplayConnect) {\n window.removeEventListener(\"vrdisplayconnect\", this._onVrDisplayConnect);\n if (this._onVrDisplayDisconnect) {\n window.removeEventListener(\"vrdisplaydisconnect\", this._onVrDisplayDisconnect);\n }\n if (this._onVrDisplayPresentChange) {\n window.removeEventListener(\"vrdisplaypresentchange\", this._onVrDisplayPresentChange);\n }\n this._onVrDisplayConnect = null;\n this._onVrDisplayDisconnect = null;\n }\n }\n};\nEngine.prototype._connectVREvents = function (canvas, document) {\n this._onVRDisplayPointerRestricted = () => {\n if (canvas) {\n canvas.requestPointerLock();\n }\n };\n this._onVRDisplayPointerUnrestricted = () => {\n // Edge fix - for some reason document is not present and this is window\n if (!document) {\n const hostWindow = this.getHostWindow();\n if (hostWindow.document && hostWindow.document.exitPointerLock) {\n hostWindow.document.exitPointerLock();\n }\n return;\n }\n if (!document.exitPointerLock) {\n return;\n }\n document.exitPointerLock();\n };\n if (IsWindowObjectExist()) {\n const hostWindow = this.getHostWindow();\n hostWindow.addEventListener(\"vrdisplaypointerrestricted\", this._onVRDisplayPointerRestricted, false);\n hostWindow.addEventListener(\"vrdisplaypointerunrestricted\", this._onVRDisplayPointerUnrestricted, false);\n }\n};\nEngine.prototype._submitVRFrame = function () {\n // Submit frame to the vr device, if enabled\n if (this._vrDisplay && this._vrDisplay.isPresenting) {\n // TODO: We should only submit the frame if we read frameData successfully.\n try {\n this._vrDisplay.submitFrame();\n }\n catch (e) {\n Tools.Warn(\"webVR submitFrame has had an unexpected failure: \" + e);\n }\n }\n};\nEngine.prototype.isVRPresenting = function () {\n return this._vrDisplay && this._vrDisplay.isPresenting;\n};\nEngine.prototype._requestVRFrame = function () {\n this._frameHandler = Engine.QueueNewFrame(this._boundRenderFunction, this._vrDisplay);\n};\n//# sourceMappingURL=engine.webVR.js.map","import { Observable } from \"../../Misc/observable.js\";\nimport { FreeCamera } from \"../../Cameras/freeCamera.js\";\nimport { Camera } from \"../../Cameras/camera.js\";\nimport { Quaternion, Matrix, Vector3 } from \"../../Maths/math.vector.js\";\nimport { Gamepad } from \"../../Gamepads/gamepad.js\";\nimport { PoseEnabledControllerType } from \"../../Gamepads/Controllers/poseEnabledController.js\";\nimport { Node } from \"../../node.js\";\nimport { HemisphericLight } from \"../../Lights/hemisphericLight.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { VRMultiviewToSingleviewPostProcess } from \"../../PostProcesses/vrMultiviewToSingleviewPostProcess.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nimport { setWebVRRigMode } from \"../RigModes/webVRRigMode.js\";\n// Side effect import to add webvr support to engine\nimport \"../../Engines/Extensions/engine.webVR.js\";\nNode.AddNodeConstructor(\"WebVRFreeCamera\", (name, scene) => {\n return () => new WebVRFreeCamera(name, Vector3.Zero(), scene);\n});\nNode.AddNodeConstructor(\"WebVRGamepadCamera\", (name, scene) => {\n return () => new WebVRFreeCamera(name, Vector3.Zero(), scene);\n});\n/**\n * This represents a WebVR camera.\n * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.\n * @deprecated Use WebXR instead - https://doc.babylonjs.com/features/featuresDeepDive/webXR\n * @example https://doc.babylonjs.com/features/featuresDeepDive/cameras/webVRCamera\n */\nexport class WebVRFreeCamera extends FreeCamera {\n /**\n * Instantiates a WebVRFreeCamera.\n * @param name The name of the WebVRFreeCamera\n * @param position The starting anchor position for the camera\n * @param scene The scene the camera belongs to\n * @param _webVROptions a set of customizable options for the webVRCamera\n */\n constructor(name, position, scene, _webVROptions = {}) {\n super(name, position, scene);\n this._webVROptions = _webVROptions;\n /**\n * @internal\n * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay\n */\n this._vrDevice = null;\n /**\n * The rawPose of the vrDevice.\n */\n this.rawPose = null;\n this._specsVersion = \"1.1\";\n this._attached = false;\n this._descendants = [];\n // Represents device position and rotation in room space. Should only be used to help calculate babylon space values\n this._deviceRoomPosition = Vector3.Zero();\n /** @internal */\n this._deviceRoomRotationQuaternion = Quaternion.Identity();\n this._standingMatrix = null;\n /**\n * Represents device position in babylon space.\n */\n this.devicePosition = Vector3.Zero();\n /**\n * Represents device rotation in babylon space.\n */\n this.deviceRotationQuaternion = Quaternion.Identity();\n /**\n * The scale of the device to be used when translating from device space to babylon space.\n */\n this.deviceScaleFactor = 1;\n this._deviceToWorld = Matrix.Identity();\n this._worldToDevice = Matrix.Identity();\n /**\n * References to the webVR controllers for the vrDevice.\n */\n this.controllers = [];\n /**\n * Emits an event when a controller is attached.\n */\n this.onControllersAttachedObservable = new Observable();\n /**\n * Emits an event when a controller's mesh has been loaded;\n */\n this.onControllerMeshLoadedObservable = new Observable();\n /**\n * Emits an event when the HMD's pose has been updated.\n */\n this.onPoseUpdatedFromDeviceObservable = new Observable();\n this._poseSet = false;\n /**\n * If the rig cameras be used as parent instead of this camera.\n */\n this.rigParenting = true;\n this._defaultHeight = undefined;\n this._setRigMode = setWebVRRigMode.bind(null, this);\n this._detachIfAttached = () => {\n const vrDisplay = this.getEngine().getVRDevice();\n if (vrDisplay && !vrDisplay.isPresenting) {\n this.detachControl();\n }\n };\n this._workingVector = Vector3.Zero();\n this._oneVector = Vector3.One();\n this._workingMatrix = Matrix.Identity();\n this._tmpMatrix = new Matrix();\n this._cache.position = Vector3.Zero();\n if (_webVROptions.defaultHeight) {\n this._defaultHeight = _webVROptions.defaultHeight;\n this.position.y = this._defaultHeight;\n }\n this.minZ = 0.1;\n //legacy support - the compensation boolean was removed.\n if (arguments.length === 5) {\n // eslint-disable-next-line prefer-rest-params\n this._webVROptions = arguments[4];\n }\n // default webVR options\n if (this._webVROptions.trackPosition == undefined) {\n this._webVROptions.trackPosition = true;\n }\n if (this._webVROptions.controllerMeshes == undefined) {\n this._webVROptions.controllerMeshes = true;\n }\n if (this._webVROptions.defaultLightingOnControllers == undefined) {\n this._webVROptions.defaultLightingOnControllers = true;\n }\n this.rotationQuaternion = new Quaternion();\n if (this._webVROptions && this._webVROptions.positionScale) {\n this.deviceScaleFactor = this._webVROptions.positionScale;\n }\n //enable VR\n const engine = this.getEngine();\n this._onVREnabled = (success) => {\n if (success) {\n this.initControllers();\n }\n };\n engine.onVRRequestPresentComplete.add(this._onVREnabled);\n engine.initWebVR().add((event) => {\n if (!event.vrDisplay || this._vrDevice === event.vrDisplay) {\n return;\n }\n this._vrDevice = event.vrDisplay;\n //reset the rig parameters.\n this.setCameraRigMode(Camera.RIG_MODE_WEBVR, { parentCamera: this, vrDisplay: this._vrDevice, frameData: this._frameData, specs: this._specsVersion });\n if (this._attached) {\n this.getEngine().enableVR(this._webVROptions);\n }\n });\n if (typeof VRFrameData !== \"undefined\") {\n this._frameData = new VRFrameData();\n }\n if (_webVROptions.useMultiview) {\n if (!this.getScene().getEngine().getCaps().multiview) {\n Logger.Warn(\"Multiview is not supported, falling back to standard rendering\");\n this._useMultiviewToSingleView = false;\n }\n else {\n this._useMultiviewToSingleView = true;\n this._rigPostProcess = new VRMultiviewToSingleviewPostProcess(\"VRMultiviewToSingleview\", this, 1.0);\n }\n }\n /**\n * The idea behind the following lines:\n * objects that have the camera as parent should actually have the rig cameras as a parent.\n * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,\n * the second will not show it correctly.\n *\n * To solve this - each object that has the camera as parent will be added to a protected array.\n * When the rig camera renders, it will take this array and set all of those to be its children.\n * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.\n * Amazing!\n */\n this.getScene().onBeforeCameraRenderObservable.add((camera) => {\n if (camera.parent === this && this.rigParenting) {\n this._descendants = this.getDescendants(true, (n) => {\n // don't take the cameras or the controllers!\n const isController = this.controllers.some((controller) => {\n return controller._mesh === n;\n });\n const isRigCamera = this._rigCameras.indexOf(n) !== -1;\n return !isController && !isRigCamera;\n });\n this._descendants.forEach((node) => {\n node.parent = camera;\n });\n }\n });\n this.getScene().onAfterCameraRenderObservable.add((camera) => {\n if (camera.parent === this && this.rigParenting) {\n this._descendants.forEach((node) => {\n node.parent = this;\n });\n }\n });\n }\n /**\n * Gets the device distance from the ground in meters.\n * @returns the distance in meters from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.\n */\n deviceDistanceToRoomGround() {\n if (this._standingMatrix) {\n // Add standing matrix offset to get real offset from ground in room\n this._standingMatrix.getTranslationToRef(this._workingVector);\n return this._deviceRoomPosition.y + this._workingVector.y;\n }\n //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.\n return this._defaultHeight || 0;\n }\n /**\n * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.\n * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n useStandingMatrix(callback = (bool) => { }) {\n // Use standing matrix if available\n this.getEngine()\n .initWebVRAsync()\n .then((result) => {\n if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !this._webVROptions.trackPosition) {\n callback(false);\n }\n else {\n this._standingMatrix = new Matrix();\n Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, this._standingMatrix);\n if (!this.getScene().useRightHandedSystem) {\n if (this._standingMatrix) {\n this._standingMatrix.toggleModelMatrixHandInPlace();\n }\n }\n callback(true);\n }\n });\n }\n /**\n * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.\n * @returns A promise with a boolean set to if the standing matrix is supported.\n */\n useStandingMatrixAsync() {\n return new Promise((res) => {\n this.useStandingMatrix((supported) => {\n res(supported);\n });\n });\n }\n /**\n * Disposes the camera\n */\n dispose() {\n this._detachIfAttached();\n this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);\n if (this._updateCacheWhenTrackingDisabledObserver) {\n this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);\n }\n super.dispose();\n }\n /**\n * Gets a vrController by name.\n * @param name The name of the controller to retrieve\n * @returns the controller matching the name specified or null if not found\n */\n getControllerByName(name) {\n for (const gp of this.controllers) {\n if (gp.hand === name) {\n return gp;\n }\n }\n return null;\n }\n /**\n * The controller corresponding to the users left hand.\n */\n get leftController() {\n if (!this._leftController) {\n this._leftController = this.getControllerByName(\"left\");\n }\n return this._leftController;\n }\n /**\n * The controller corresponding to the users right hand.\n */\n get rightController() {\n if (!this._rightController) {\n this._rightController = this.getControllerByName(\"right\");\n }\n return this._rightController;\n }\n /**\n * Casts a ray forward from the vrCamera's gaze.\n * @param length Length of the ray (default: 100)\n * @returns the ray corresponding to the gaze\n */\n getForwardRay(length = 100) {\n if (this.leftCamera) {\n // Use left eye to avoid computation to compute center on every call\n return super.getForwardRay(length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera\n }\n else {\n return super.getForwardRay(length);\n }\n }\n /**\n * @internal\n * Updates the camera based on device's frame data\n */\n _checkInputs() {\n if (this._vrDevice && this._vrDevice.isPresenting) {\n this._vrDevice.getFrameData(this._frameData);\n this.updateFromDevice(this._frameData.pose);\n }\n super._checkInputs();\n }\n /**\n * Updates the poseControlled values based on the input device pose.\n * @param poseData Pose coming from the device\n */\n updateFromDevice(poseData) {\n if (poseData && poseData.orientation && poseData.orientation.length === 4) {\n this.rawPose = poseData;\n this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);\n if (this.getScene().useRightHandedSystem) {\n this._deviceRoomRotationQuaternion.z *= -1;\n this._deviceRoomRotationQuaternion.w *= -1;\n }\n if (this._webVROptions.trackPosition && this.rawPose.position) {\n this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);\n if (this.getScene().useRightHandedSystem) {\n this._deviceRoomPosition.z *= -1;\n }\n }\n this._poseSet = true;\n }\n }\n /**\n * WebVR's attach control will start broadcasting frames to the device.\n * Note that in certain browsers (chrome for example) this function must be called\n * within a user-interaction callback. Example:\n *
 scene.onPointerDown = function() { camera.attachControl(canvas); }
\n *\n * @param noPreventDefault prevent the default html element operation when attaching the vrDevice\n */\n attachControl(noPreventDefault) {\n // eslint-disable-next-line prefer-rest-params\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n super.attachControl(noPreventDefault);\n this._attached = true;\n noPreventDefault = Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;\n if (this._vrDevice) {\n this.getEngine().enableVR(this._webVROptions);\n }\n const hostWindow = this._scene.getEngine().getHostWindow();\n if (hostWindow) {\n hostWindow.addEventListener(\"vrdisplaypresentchange\", this._detachIfAttached);\n }\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);\n this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);\n super.detachControl();\n this._attached = false;\n this.getEngine().disableVR();\n window.removeEventListener(\"vrdisplaypresentchange\", this._detachIfAttached);\n }\n /**\n * @returns the name of this class\n */\n getClassName() {\n return \"WebVRFreeCamera\";\n }\n /**\n * Calls resetPose on the vrDisplay\n * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose\n */\n resetToCurrentRotation() {\n //uses the vrDisplay's \"resetPose()\".\n //pitch and roll won't be affected.\n this._vrDevice.resetPose();\n }\n /**\n * @internal\n * Updates the rig cameras (left and right eye)\n */\n _updateRigCameras() {\n const camLeft = this._rigCameras[0];\n const camRight = this._rigCameras[1];\n camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);\n camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);\n camLeft.position.copyFrom(this._deviceRoomPosition);\n camRight.position.copyFrom(this._deviceRoomPosition);\n }\n // Remove translation from 6dof headset if trackposition is set to false\n _correctPositionIfNotTrackPosition(matrix, isViewMatrix = false) {\n if (this.rawPose && this.rawPose.position && !this._webVROptions.trackPosition) {\n Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);\n if (!isViewMatrix) {\n this._tmpMatrix.invert();\n }\n this._tmpMatrix.multiplyToRef(matrix, matrix);\n }\n }\n /**\n * @internal\n * Updates the cached values of the camera\n * @param ignoreParentClass ignores updating the parent class's cache (default: false)\n */\n _updateCache(ignoreParentClass) {\n if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {\n // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition\n if (!this._updateCacheCalled) {\n // make sure it is only called once per loop. this.update() might cause an infinite loop.\n this._updateCacheCalled = true;\n this.update();\n }\n // Set working vector to the device position in room space rotated by the new rotation\n this.rotationQuaternion.toRotationMatrix(this._workingMatrix);\n Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);\n // Subtract this vector from the current device position in world to get the translation for the device world matrix\n this.devicePosition.subtractToRef(this._workingVector, this._workingVector);\n Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);\n // Add translation from anchor position\n this._deviceToWorld.getTranslationToRef(this._workingVector);\n this._workingVector.addInPlace(this.position);\n this._workingVector.subtractInPlace(this._cache.position);\n this._deviceToWorld.setTranslation(this._workingVector);\n // Set an inverted matrix to be used when updating the camera\n this._deviceToWorld.invertToRef(this._worldToDevice);\n // Update the gamepad to ensure the mesh is updated on the same frame as camera\n this.controllers.forEach((controller) => {\n controller._deviceToWorld.copyFrom(this._deviceToWorld);\n this._correctPositionIfNotTrackPosition(controller._deviceToWorld);\n controller.update();\n });\n }\n if (!ignoreParentClass) {\n super._updateCache();\n }\n this._updateCacheCalled = false;\n }\n /**\n * @internal\n * Get current device position in babylon world\n */\n _computeDevicePosition() {\n Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);\n }\n /**\n * Updates the current device position and rotation in the babylon world\n */\n update() {\n this._computeDevicePosition();\n // Get current device rotation in babylon world\n Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);\n this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);\n Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);\n if (this._poseSet) {\n this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);\n }\n super.update();\n }\n /**\n * @internal\n * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)\n * @returns an identity matrix\n */\n _getViewMatrix() {\n return Matrix.Identity();\n }\n /**\n * This function is called by the two RIG cameras.\n * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)\n * @internal\n */\n _getWebVRViewMatrix() {\n // Update the parent camera prior to using a child camera to avoid desynchronization\n const parentCamera = this._cameraRigParams[\"parentCamera\"];\n parentCamera._updateCache();\n //WebVR 1.1\n const viewArray = this._cameraRigParams[\"left\"] ? this._cameraRigParams[\"frameData\"].leftViewMatrix : this._cameraRigParams[\"frameData\"].rightViewMatrix;\n Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);\n if (!this.getScene().useRightHandedSystem) {\n this._webvrViewMatrix.toggleModelMatrixHandInPlace();\n }\n // update the camera rotation matrix\n this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);\n Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);\n // Computing target and final matrix\n this.position.addToRef(this._transformedReferencePoint, this._currentTarget);\n // should the view matrix be updated with scale and position offset?\n if (parentCamera.deviceScaleFactor !== 1) {\n this._webvrViewMatrix.invert();\n // scale the position, if set\n if (parentCamera.deviceScaleFactor) {\n this._webvrViewMatrix.multiplyAtIndex(12, parentCamera.deviceScaleFactor);\n this._webvrViewMatrix.multiplyAtIndex(13, parentCamera.deviceScaleFactor);\n this._webvrViewMatrix.multiplyAtIndex(14, parentCamera.deviceScaleFactor);\n }\n this._webvrViewMatrix.invert();\n }\n // Remove translation from 6dof headset if trackposition is set to false\n parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);\n parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);\n // Compute global position\n this._workingMatrix = this._workingMatrix || Matrix.Identity();\n this._webvrViewMatrix.invertToRef(this._workingMatrix);\n this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);\n this._workingMatrix.getTranslationToRef(this._globalPosition);\n this._markSyncedWithParent();\n return this._webvrViewMatrix;\n }\n /** @internal */\n _getWebVRProjectionMatrix() {\n const parentCamera = this.parent;\n parentCamera._vrDevice.depthNear = parentCamera.minZ;\n parentCamera._vrDevice.depthFar = parentCamera.maxZ;\n const projectionArray = this._cameraRigParams[\"left\"] ? this._cameraRigParams[\"frameData\"].leftProjectionMatrix : this._cameraRigParams[\"frameData\"].rightProjectionMatrix;\n Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);\n //babylon compatible matrix\n if (!this.getScene().useRightHandedSystem) {\n this._projectionMatrix.toggleProjectionMatrixHandInPlace();\n }\n return this._projectionMatrix;\n }\n /**\n * Initializes the controllers and their meshes\n */\n initControllers() {\n this.controllers.length = 0;\n const manager = this.getScene().gamepadManager;\n this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add((gamepad) => {\n if (gamepad.type === Gamepad.POSE_ENABLED) {\n const webVrController = gamepad;\n if (webVrController.defaultModel) {\n webVrController.defaultModel.setEnabled(false);\n }\n if (webVrController.hand === \"right\") {\n this._rightController = null;\n }\n if (webVrController.hand === \"left\") {\n this._leftController = null;\n }\n const controllerIndex = this.controllers.indexOf(webVrController);\n if (controllerIndex !== -1) {\n this.controllers.splice(controllerIndex, 1);\n }\n }\n });\n this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add((gamepad) => {\n if (gamepad.type === Gamepad.POSE_ENABLED) {\n const webVrController = gamepad;\n if (!this._webVROptions.trackPosition) {\n webVrController._disableTrackPosition(new Vector3(webVrController.hand == \"left\" ? -0.15 : 0.15, -0.5, 0.25));\n // Cache must be updated before rendering controllers to avoid them being one frame behind\n if (!this._updateCacheWhenTrackingDisabledObserver) {\n this._updateCacheWhenTrackingDisabledObserver = this._scene.onBeforeRenderObservable.add(() => {\n this._updateCache();\n });\n }\n }\n webVrController.deviceScaleFactor = this.deviceScaleFactor;\n webVrController._deviceToWorld.copyFrom(this._deviceToWorld);\n this._correctPositionIfNotTrackPosition(webVrController._deviceToWorld);\n if (this._webVROptions.controllerMeshes) {\n if (webVrController.defaultModel) {\n webVrController.defaultModel.setEnabled(true);\n }\n else {\n // Load the meshes\n webVrController.initControllerMesh(this.getScene(), (loadedMesh) => {\n loadedMesh.scaling.scaleInPlace(this.deviceScaleFactor);\n this.onControllerMeshLoadedObservable.notifyObservers(webVrController);\n if (this._webVROptions.defaultLightingOnControllers) {\n if (!this._lightOnControllers) {\n this._lightOnControllers = new HemisphericLight(\"vrControllersLight\", new Vector3(0, 1, 0), this.getScene());\n }\n const activateLightOnSubMeshes = function (mesh, light) {\n const children = mesh.getChildren();\n if (children && children.length !== 0) {\n children.forEach((mesh) => {\n light.includedOnlyMeshes.push(mesh);\n activateLightOnSubMeshes(mesh, light);\n });\n }\n };\n this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);\n activateLightOnSubMeshes(loadedMesh, this._lightOnControllers);\n }\n });\n }\n }\n webVrController.attachToPoseControlledCamera(this);\n // since this is async - sanity check. Is the controller already stored?\n if (this.controllers.indexOf(webVrController) === -1) {\n //add to the controllers array\n this.controllers.push(webVrController);\n // Forced to add some control code for Vive as it doesn't always fill properly the \"hand\" property\n // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...\n // So we're overriding setting left & right manually to be sure\n let firstViveWandDetected = false;\n for (let i = 0; i < this.controllers.length; i++) {\n if (this.controllers[i].controllerType === PoseEnabledControllerType.VIVE) {\n if (!firstViveWandDetected) {\n firstViveWandDetected = true;\n this.controllers[i].hand = \"left\";\n }\n else {\n this.controllers[i].hand = \"right\";\n }\n }\n }\n //did we find enough controllers? Great! let the developer know.\n if (this.controllers.length >= 2) {\n this.onControllersAttachedObservable.notifyObservers(this.controllers);\n }\n }\n }\n });\n }\n}\n//# sourceMappingURL=webVRCamera.js.map","import { Observable } from \"../../Misc/observable.js\";\nimport { PoseEnabledController } from \"./poseEnabledController.js\";\n/**\n * Defines the WebVRController object that represents controllers tracked in 3D space\n * @deprecated Use WebXR instead\n */\nexport class WebVRController extends PoseEnabledController {\n /**\n * Fired when a controller button's state has changed\n * @param callback the callback containing the button that was modified\n */\n onButtonStateChange(callback) {\n this._onButtonStateChange = callback;\n }\n /**\n * The default controller model for the controller\n */\n get defaultModel() {\n return this._defaultModel;\n }\n /**\n * Creates a new WebVRController from a gamepad\n * @param vrGamepad the gamepad that the WebVRController should be created from\n */\n constructor(vrGamepad) {\n super(vrGamepad);\n // Observables\n /**\n * Fired when the trigger state has changed\n */\n this.onTriggerStateChangedObservable = new Observable();\n /**\n * Fired when the main button state has changed\n */\n this.onMainButtonStateChangedObservable = new Observable();\n /**\n * Fired when the secondary button state has changed\n */\n this.onSecondaryButtonStateChangedObservable = new Observable();\n /**\n * Fired when the pad state has changed\n */\n this.onPadStateChangedObservable = new Observable();\n /**\n * Fired when controllers stick values have changed\n */\n this.onPadValuesChangedObservable = new Observable();\n /**\n * X and Y axis corresponding to the controllers joystick\n */\n this.pad = { x: 0, y: 0 };\n // avoid GC, store state in a tmp object\n this._changes = {\n pressChanged: false,\n touchChanged: false,\n valueChanged: false,\n changed: false,\n };\n this._buttons = new Array(vrGamepad.buttons.length);\n this.hand = vrGamepad.hand;\n }\n /**\n * Updates the state of the controller and mesh based on the current position and rotation of the controller\n */\n update() {\n super.update();\n for (let index = 0; index < this._buttons.length; index++) {\n this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);\n }\n if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {\n this.pad.x = this.leftStick.x;\n this.pad.y = this.leftStick.y;\n this.onPadValuesChangedObservable.notifyObservers(this.pad);\n }\n }\n _setButtonValue(newState, currentState, buttonIndex) {\n if (!newState) {\n newState = {\n pressed: false,\n touched: false,\n value: 0,\n };\n }\n if (!currentState) {\n this._buttons[buttonIndex] = {\n pressed: newState.pressed,\n touched: newState.touched,\n value: newState.value,\n };\n return;\n }\n this._checkChanges(newState, currentState);\n if (this._changes.changed) {\n this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);\n this._handleButtonChange(buttonIndex, newState, this._changes);\n }\n this._buttons[buttonIndex].pressed = newState.pressed;\n this._buttons[buttonIndex].touched = newState.touched;\n // oculus triggers are never 0, thou not touched.\n this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;\n }\n _checkChanges(newState, currentState) {\n this._changes.pressChanged = newState.pressed !== currentState.pressed;\n this._changes.touchChanged = newState.touched !== currentState.touched;\n this._changes.valueChanged = newState.value !== currentState.value;\n this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;\n return this._changes;\n }\n /**\n * Disposes of th webVRController\n */\n dispose() {\n super.dispose();\n this._defaultModel = null;\n this.onTriggerStateChangedObservable.clear();\n this.onMainButtonStateChangedObservable.clear();\n this.onSecondaryButtonStateChangedObservable.clear();\n this.onPadStateChangedObservable.clear();\n this.onPadValuesChangedObservable.clear();\n }\n}\n//# sourceMappingURL=webVRController.js.map","\n/**\n * Configuration needed for prepass-capable materials\n */\nexport class PrePassConfiguration {\n constructor() {\n /**\n * Previous world matrices of meshes carrying this material\n * Used for computing velocity\n */\n this.previousWorldMatrices = {};\n /**\n * Previous bones of meshes carrying this material\n * Used for computing velocity\n */\n this.previousBones = {};\n }\n /**\n * Add the required uniforms to the current list.\n * @param uniforms defines the current uniform list.\n */\n static AddUniforms(uniforms) {\n uniforms.push(\"previousWorld\", \"previousViewProjection\", \"mPreviousBones\");\n }\n /**\n * Add the required samplers to the current list.\n * @param samplers defines the current sampler list.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n static AddSamplers(samplers) {\n // pass\n }\n /**\n * Binds the material data.\n * @param effect defines the effect to update\n * @param scene defines the scene the material belongs to.\n * @param mesh The mesh\n * @param world World matrix of this mesh\n * @param isFrozen Is the material frozen\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n bindForSubMesh(effect, scene, mesh, world, isFrozen) {\n if (scene.prePassRenderer && scene.prePassRenderer.enabled && scene.prePassRenderer.currentRTisSceneRT) {\n if (scene.prePassRenderer.getIndex(2) !== -1) {\n if (!this.previousWorldMatrices[mesh.uniqueId]) {\n this.previousWorldMatrices[mesh.uniqueId] = world.clone();\n }\n if (!this.previousViewProjection) {\n this.previousViewProjection = scene.getTransformMatrix().clone();\n this.currentViewProjection = scene.getTransformMatrix().clone();\n }\n const engine = scene.getEngine();\n if (this.currentViewProjection.updateFlag !== scene.getTransformMatrix().updateFlag) {\n // First update of the prepass configuration for this rendering pass\n this._lastUpdateFrameId = engine.frameId;\n this.previousViewProjection.copyFrom(this.currentViewProjection);\n this.currentViewProjection.copyFrom(scene.getTransformMatrix());\n }\n else if (this._lastUpdateFrameId !== engine.frameId) {\n // The scene transformation did not change from the previous frame (so no camera motion), we must update previousViewProjection accordingly\n this._lastUpdateFrameId = engine.frameId;\n this.previousViewProjection.copyFrom(this.currentViewProjection);\n }\n effect.setMatrix(\"previousWorld\", this.previousWorldMatrices[mesh.uniqueId]);\n effect.setMatrix(\"previousViewProjection\", this.previousViewProjection);\n this.previousWorldMatrices[mesh.uniqueId] = world.clone();\n }\n }\n }\n}\n//# sourceMappingURL=prePassConfiguration.js.map","import { Engine } from \"../Engines/engine.js\";\n\n/**\n * This groups all the flags used to control the materials channel.\n */\nexport class MaterialFlags {\n /**\n * Are diffuse textures enabled in the application.\n */\n static get DiffuseTextureEnabled() {\n return this._DiffuseTextureEnabled;\n }\n static set DiffuseTextureEnabled(value) {\n if (this._DiffuseTextureEnabled === value) {\n return;\n }\n this._DiffuseTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are detail textures enabled in the application.\n */\n static get DetailTextureEnabled() {\n return this._DetailTextureEnabled;\n }\n static set DetailTextureEnabled(value) {\n if (this._DetailTextureEnabled === value) {\n return;\n }\n this._DetailTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are decal maps enabled in the application.\n */\n static get DecalMapEnabled() {\n return this._DecalMapEnabled;\n }\n static set DecalMapEnabled(value) {\n if (this._DecalMapEnabled === value) {\n return;\n }\n this._DecalMapEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are ambient textures enabled in the application.\n */\n static get AmbientTextureEnabled() {\n return this._AmbientTextureEnabled;\n }\n static set AmbientTextureEnabled(value) {\n if (this._AmbientTextureEnabled === value) {\n return;\n }\n this._AmbientTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are opacity textures enabled in the application.\n */\n static get OpacityTextureEnabled() {\n return this._OpacityTextureEnabled;\n }\n static set OpacityTextureEnabled(value) {\n if (this._OpacityTextureEnabled === value) {\n return;\n }\n this._OpacityTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are reflection textures enabled in the application.\n */\n static get ReflectionTextureEnabled() {\n return this._ReflectionTextureEnabled;\n }\n static set ReflectionTextureEnabled(value) {\n if (this._ReflectionTextureEnabled === value) {\n return;\n }\n this._ReflectionTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are emissive textures enabled in the application.\n */\n static get EmissiveTextureEnabled() {\n return this._EmissiveTextureEnabled;\n }\n static set EmissiveTextureEnabled(value) {\n if (this._EmissiveTextureEnabled === value) {\n return;\n }\n this._EmissiveTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are specular textures enabled in the application.\n */\n static get SpecularTextureEnabled() {\n return this._SpecularTextureEnabled;\n }\n static set SpecularTextureEnabled(value) {\n if (this._SpecularTextureEnabled === value) {\n return;\n }\n this._SpecularTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are bump textures enabled in the application.\n */\n static get BumpTextureEnabled() {\n return this._BumpTextureEnabled;\n }\n static set BumpTextureEnabled(value) {\n if (this._BumpTextureEnabled === value) {\n return;\n }\n this._BumpTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are lightmap textures enabled in the application.\n */\n static get LightmapTextureEnabled() {\n return this._LightmapTextureEnabled;\n }\n static set LightmapTextureEnabled(value) {\n if (this._LightmapTextureEnabled === value) {\n return;\n }\n this._LightmapTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are refraction textures enabled in the application.\n */\n static get RefractionTextureEnabled() {\n return this._RefractionTextureEnabled;\n }\n static set RefractionTextureEnabled(value) {\n if (this._RefractionTextureEnabled === value) {\n return;\n }\n this._RefractionTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are color grading textures enabled in the application.\n */\n static get ColorGradingTextureEnabled() {\n return this._ColorGradingTextureEnabled;\n }\n static set ColorGradingTextureEnabled(value) {\n if (this._ColorGradingTextureEnabled === value) {\n return;\n }\n this._ColorGradingTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are fresnels enabled in the application.\n */\n static get FresnelEnabled() {\n return this._FresnelEnabled;\n }\n static set FresnelEnabled(value) {\n if (this._FresnelEnabled === value) {\n return;\n }\n this._FresnelEnabled = value;\n Engine.MarkAllMaterialsAsDirty(4);\n }\n /**\n * Are clear coat textures enabled in the application.\n */\n static get ClearCoatTextureEnabled() {\n return this._ClearCoatTextureEnabled;\n }\n static set ClearCoatTextureEnabled(value) {\n if (this._ClearCoatTextureEnabled === value) {\n return;\n }\n this._ClearCoatTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are clear coat bump textures enabled in the application.\n */\n static get ClearCoatBumpTextureEnabled() {\n return this._ClearCoatBumpTextureEnabled;\n }\n static set ClearCoatBumpTextureEnabled(value) {\n if (this._ClearCoatBumpTextureEnabled === value) {\n return;\n }\n this._ClearCoatBumpTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are clear coat tint textures enabled in the application.\n */\n static get ClearCoatTintTextureEnabled() {\n return this._ClearCoatTintTextureEnabled;\n }\n static set ClearCoatTintTextureEnabled(value) {\n if (this._ClearCoatTintTextureEnabled === value) {\n return;\n }\n this._ClearCoatTintTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are sheen textures enabled in the application.\n */\n static get SheenTextureEnabled() {\n return this._SheenTextureEnabled;\n }\n static set SheenTextureEnabled(value) {\n if (this._SheenTextureEnabled === value) {\n return;\n }\n this._SheenTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are anisotropic textures enabled in the application.\n */\n static get AnisotropicTextureEnabled() {\n return this._AnisotropicTextureEnabled;\n }\n static set AnisotropicTextureEnabled(value) {\n if (this._AnisotropicTextureEnabled === value) {\n return;\n }\n this._AnisotropicTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are thickness textures enabled in the application.\n */\n static get ThicknessTextureEnabled() {\n return this._ThicknessTextureEnabled;\n }\n static set ThicknessTextureEnabled(value) {\n if (this._ThicknessTextureEnabled === value) {\n return;\n }\n this._ThicknessTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are refraction intensity textures enabled in the application.\n */\n static get RefractionIntensityTextureEnabled() {\n return this._ThicknessTextureEnabled;\n }\n static set RefractionIntensityTextureEnabled(value) {\n if (this._RefractionIntensityTextureEnabled === value) {\n return;\n }\n this._RefractionIntensityTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are translucency intensity textures enabled in the application.\n */\n static get TranslucencyIntensityTextureEnabled() {\n return this._ThicknessTextureEnabled;\n }\n static set TranslucencyIntensityTextureEnabled(value) {\n if (this._TranslucencyIntensityTextureEnabled === value) {\n return;\n }\n this._TranslucencyIntensityTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are translucency intensity textures enabled in the application.\n */\n static get IridescenceTextureEnabled() {\n return this._IridescenceTextureEnabled;\n }\n static set IridescenceTextureEnabled(value) {\n if (this._IridescenceTextureEnabled === value) {\n return;\n }\n this._IridescenceTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n}\n// Flags used to enable or disable a type of texture for all Standard Materials\nMaterialFlags._DiffuseTextureEnabled = true;\nMaterialFlags._DetailTextureEnabled = true;\nMaterialFlags._DecalMapEnabled = true;\nMaterialFlags._AmbientTextureEnabled = true;\nMaterialFlags._OpacityTextureEnabled = true;\nMaterialFlags._ReflectionTextureEnabled = true;\nMaterialFlags._EmissiveTextureEnabled = true;\nMaterialFlags._SpecularTextureEnabled = true;\nMaterialFlags._BumpTextureEnabled = true;\nMaterialFlags._LightmapTextureEnabled = true;\nMaterialFlags._RefractionTextureEnabled = true;\nMaterialFlags._ColorGradingTextureEnabled = true;\nMaterialFlags._FresnelEnabled = true;\nMaterialFlags._ClearCoatTextureEnabled = true;\nMaterialFlags._ClearCoatBumpTextureEnabled = true;\nMaterialFlags._ClearCoatTintTextureEnabled = true;\nMaterialFlags._SheenTextureEnabled = true;\nMaterialFlags._AnisotropicTextureEnabled = true;\nMaterialFlags._ThicknessTextureEnabled = true;\nMaterialFlags._RefractionIntensityTextureEnabled = true;\nMaterialFlags._TranslucencyIntensityTextureEnabled = true;\nMaterialFlags._IridescenceTextureEnabled = true;\n//# sourceMappingURL=materialFlags.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"decalFragmentDeclaration\";\nconst shader = `#ifdef DECAL\nuniform vec4 vDecalInfos;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const decalFragmentDeclaration = { name, shader };\n//# sourceMappingURL=decalFragmentDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nimport \"./decalFragmentDeclaration.js\";\nconst name = \"defaultFragmentDeclaration\";\nconst shader = `uniform vec4 vEyePosition;\runiform vec4 vDiffuseColor;\r#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\r#endif\nuniform vec3 vEmissiveColor;\runiform vec3 vAmbientColor;\runiform float visibility;\r#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\r#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\r#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\r#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\r#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\r#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\runiform vec2 vTangentSpaceParams;\r#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\r#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS)\nuniform mat4 view;\r#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\r#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\r#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\runiform vec4 refractionRightColor;\r#endif\n#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D)\nuniform vec3 vRefractionPosition;\runiform vec3 vRefractionSize; \r#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\r#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\runiform vec4 diffuseRightColor;\r#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\r#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\runiform vec4 emissiveRightColor;\r#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\r#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX)\nuniform mat4 reflectionMatrix;\r#endif\n#ifndef REFLECTIONMAP_SKYBOX\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\runiform vec3 vReflectionSize; \r#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\runiform vec4 reflectionRightColor;\r#endif\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\r#endif\n#include\n#define ADDITIONAL_FRAGMENT_DECLARATION\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const defaultFragmentDeclaration = { name, shader };\n//# sourceMappingURL=defaultFragmentDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"sceneUboDeclaration\";\nconst shader = `layout(std140,column_major) uniform;\runiform Scene {\rmat4 viewProjection;\r#ifdef MULTIVIEW\nmat4 viewProjectionR;\r#endif \nmat4 view;\rmat4 projection;\rvec4 vEyePosition;\r};\r`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const sceneUboDeclaration = { name, shader };\n//# sourceMappingURL=sceneUboDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"meshUboDeclaration\";\nconst shader = `#ifdef WEBGL2\nuniform mat4 world;\runiform float visibility;\r#else\nlayout(std140,column_major) uniform;\runiform Mesh\r{\rmat4 world;\rfloat visibility;\r};\r#endif\n#define WORLD_UBO\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const meshUboDeclaration = { name, shader };\n//# sourceMappingURL=meshUboDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nimport \"./sceneUboDeclaration.js\";\nimport \"./meshUboDeclaration.js\";\nconst name = \"defaultUboDeclaration\";\nconst shader = `layout(std140,column_major) uniform;\runiform Material\r{\rvec4 diffuseLeftColor;\rvec4 diffuseRightColor;\rvec4 opacityParts;\rvec4 reflectionLeftColor;\rvec4 reflectionRightColor;\rvec4 refractionLeftColor;\rvec4 refractionRightColor;\rvec4 emissiveLeftColor;\rvec4 emissiveRightColor;\rvec2 vDiffuseInfos;\rvec2 vAmbientInfos;\rvec2 vOpacityInfos;\rvec2 vReflectionInfos;\rvec3 vReflectionPosition;\rvec3 vReflectionSize;\rvec2 vEmissiveInfos;\rvec2 vLightmapInfos;\rvec2 vSpecularInfos;\rvec3 vBumpInfos;\rmat4 diffuseMatrix;\rmat4 ambientMatrix;\rmat4 opacityMatrix;\rmat4 reflectionMatrix;\rmat4 emissiveMatrix;\rmat4 lightmapMatrix;\rmat4 specularMatrix;\rmat4 bumpMatrix;\rvec2 vTangentSpaceParams;\rfloat pointSize;\rfloat alphaCutOff;\rmat4 refractionMatrix;\rvec4 vRefractionInfos;\rvec3 vRefractionPosition;\rvec3 vRefractionSize;\rvec4 vSpecularColor;\rvec3 vEmissiveColor;\rvec4 vDiffuseColor;\rvec3 vAmbientColor;\r#define ADDITIONAL_UBO_DECLARATION\n};\r#include\n#include\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const defaultUboDeclaration = { name, shader };\n//# sourceMappingURL=defaultUboDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"prePassDeclaration\";\nconst shader = `#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`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const prePassDeclaration = { name, shader };\n//# sourceMappingURL=prePassDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"lightFragmentDeclaration\";\nconst shader = `#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\runiform vec4 vLightDiffuse{X};\r#ifdef SPECULARTERM\nuniform vec4 vLightSpecular{X};\r#else\nvec4 vLightSpecular{X}=vec4(0.);\r#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];\runiform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];\runiform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];\runiform float cascadeBlendFactor{X};\rvarying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];\rvarying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];\rvarying vec4 vPositionFromCamera{X};\r#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\runiform highp sampler2DArray depthSampler{X};\runiform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];\runiform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];\runiform float penumbraDarkness{X};\r#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\r#else\nuniform highp sampler2DArray shadowSampler{X};\r#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\r(\rvec3 ( 1.5,0.0,0.0 ),\rvec3 ( 0.0,1.5,0.0 ),\rvec3 ( 0.0,0.0,5.5 ),\rvec3 ( 1.5,0.0,5.5 ),\rvec3 ( 1.5,1.5,0.0 ),\rvec3 ( 1.0,1.0,1.0 ),\rvec3 ( 0.0,1.0,5.5 ),\rvec3 ( 0.5,3.5,0.75 )\r);\rvec3 shadowDebug{X};\r#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\r#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\r#endif\nfloat diff{X}=0.;\r#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\r#else\nvarying vec4 vPositionFromLight{X};\rvarying float vDepthMetric{X};\r#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\runiform highp sampler2D depthSampler{X};\r#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\r#else\nuniform sampler2D shadowSampler{X};\r#endif\nuniform mat4 lightMatrix{X};\r#endif\nuniform vec4 shadowsInfo{X};\runiform vec2 depthValues{X};\r#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\runiform vec4 vLightFalloff{X};\r#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\r#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\r#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\runiform sampler2D projectionLightSampler{X};\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const lightFragmentDeclaration = { name, shader };\n//# sourceMappingURL=lightFragmentDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"lightUboDeclaration\";\nconst shader = `#ifdef LIGHT{X}\nuniform Light{X}\r{\rvec4 vLightData;\rvec4 vLightDiffuse;\rvec4 vLightSpecular;\r#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\rvec4 vLightFalloff;\r#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\r#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\r#endif\nvec4 shadowsInfo;\rvec2 depthValues;\r} light{X};\r#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\runiform sampler2D projectionLightSampler{X};\r#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];\runiform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];\runiform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];\runiform float cascadeBlendFactor{X};\rvarying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];\rvarying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];\rvarying vec4 vPositionFromCamera{X};\r#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\runiform highp sampler2DArray depthSampler{X};\runiform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];\runiform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];\runiform float penumbraDarkness{X};\r#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\r#else\nuniform highp sampler2DArray shadowSampler{X};\r#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\r(\rvec3 ( 1.5,0.0,0.0 ),\rvec3 ( 0.0,1.5,0.0 ),\rvec3 ( 0.0,0.0,5.5 ),\rvec3 ( 1.5,0.0,5.5 ),\rvec3 ( 1.5,1.5,0.0 ),\rvec3 ( 1.0,1.0,1.0 ),\rvec3 ( 0.0,1.0,5.5 ),\rvec3 ( 0.5,3.5,0.75 )\r);\rvec3 shadowDebug{X};\r#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\r#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\r#endif\nfloat diff{X}=0.;\r#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \r#else\nvarying vec4 vPositionFromLight{X};\rvarying float vDepthMetric{X};\r#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\runiform highp sampler2D depthSampler{X};\r#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\r#else\nuniform sampler2D shadowSampler{X};\r#endif\nuniform mat4 lightMatrix{X};\r#endif\n#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const lightUboDeclaration = { name, shader };\n//# sourceMappingURL=lightUboDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"shadowsFragmentFunctions\";\nconst shader = `#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)\r{\rconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\rreturn dot(color,bit_shift);\r}\r#endif\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\r{\rfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));\rreturn mix(value,1.0,mask);\r}\r#define inline\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\r{\rvec3 directionToLight=vPositionW-lightPosition;\rfloat depth=length(directionToLight);\rdepth=(depth+depthValues.x)/(depthValues.y);\rdepth=clamp(depth,0.,1.0);\rdirectionToLight=normalize(directionToLight);\rdirectionToLight.y=-directionToLight.y;\r#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\r#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\r#endif\nreturn depth>shadow ? darkness : 1.0;\r}\r#define inline\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\r{\rvec3 directionToLight=vPositionW-lightPosition;\rfloat depth=length(directionToLight);\rdepth=(depth+depthValues.x)/(depthValues.y);\rdepth=clamp(depth,0.,1.0);\rdirectionToLight=normalize(directionToLight);\rdirectionToLight.y=-directionToLight.y;\rfloat visibility=1.;\rvec3 poissonDisk[4];\rpoissonDisk[0]=vec3(-1.0,1.0,-1.0);\rpoissonDisk[1]=vec3(1.0,-1.0,-1.0);\rpoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\rpoissonDisk[3]=vec3(1.0,-1.0,1.0);\r#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;\r}\r#endif\n#define inline\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\r{\rvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\rvec2 uv=0.5*clipSpace.xy+vec2(0.5);\rif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\r{\rreturn 1.0;\r}\relse\r{\rfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\r#ifndef SHADOWFLOAT\nfloat shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\r#else\nfloat shadow=TEXTUREFUNC(shadowSampler,uv,0.).x;\r#endif\nreturn shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;\r}\r}\r#define inline\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\r{\rvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\rvec2 uv=0.5*clipSpace.xy+vec2(0.5);\rif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\r{\rreturn 1.0;\r}\relse\r{\rfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\rfloat visibility=1.;\rvec2 poissonDisk[4];\rpoissonDisk[0]=vec2(-0.94201624,-0.39906216);\rpoissonDisk[1]=vec2(0.94558609,-0.76890725);\rpoissonDisk[2]=vec2(-0.094184101,-0.92938870);\rpoissonDisk[3]=vec2(0.34495938,0.29387760);\r#ifndef SHADOWFLOAT\nif (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))1.0 || uv.y<0. || uv.y>1.0)\r{\rreturn 1.0;\r}\relse\r{\rfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\r#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\r#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\r#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\rreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\r}\r}\r#define inline\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\r{\rvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\rvec2 uv=0.5*clipSpace.xy+vec2(0.5);\rif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\r{\rreturn 1.0;\r}\relse\r{\rfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \r#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\r#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\r#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\rreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\r}\r}\r#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 inline\nfloat computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff)\r{\rvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\rvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\ruvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);\rvec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);\rfloat shadow=texture2D(shadowSampler,uvDepthLayer);\rshadow=mix(darkness,1.,shadow);\rreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\r}\r#define inline\nfloat computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\r{\rvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\rvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\ruvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);\rvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \ruv+=0.5; \rvec2 st=fract(uv); \rvec2 base_uv=floor(uv)-0.5; \rbase_uv*=shadowMapSizeAndInverse.y; \rvec2 uvw0=3.-2.*st;\rvec2 uvw1=1.+2.*st;\rvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\rvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\rfloat shadow=0.;\rshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));\rshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));\rshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));\rshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));\rshadow=shadow/16.;\rshadow=mix(darkness,1.,shadow);\rreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\r}\r#define inline\nfloat computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\r{\rvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\rvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\ruvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);\rvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \ruv+=0.5; \rvec2 st=fract(uv); \rvec2 base_uv=floor(uv)-0.5; \rbase_uv*=shadowMapSizeAndInverse.y; \rvec2 uvw0=4.-3.*st;\rvec2 uvw1=vec2(7.);\rvec2 uvw2=1.+3.*st;\rvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\rvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\rfloat shadow=0.;\rshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));\rshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));\rshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));\rshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));\rshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));\rshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));\rshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));\rshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));\rshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));\rshadow=shadow/144.;\rshadow=mix(darkness,1.,shadow);\rreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\r}\r#define inline\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\r{\rif (depthMetric>1.0 || depthMetric<0.0) {\rreturn 1.0;\r}\relse\r{\rvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\rvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\ruvDepth.z=ZINCLIP;\rfloat shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);\rshadow=mix(darkness,1.,shadow);\rreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\r}\r}\r#define inline\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\r{\rif (depthMetric>1.0 || depthMetric<0.0) {\rreturn 1.0;\r}\relse\r{\rvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\rvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\ruvDepth.z=ZINCLIP;\rvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \ruv+=0.5; \rvec2 st=fract(uv); \rvec2 base_uv=floor(uv)-0.5; \rbase_uv*=shadowMapSizeAndInverse.y; \rvec2 uvw0=3.-2.*st;\rvec2 uvw1=1.+2.*st;\rvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\rvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\rfloat shadow=0.;\rshadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);\rshadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);\rshadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);\rshadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);\rshadow=shadow/16.;\rshadow=mix(darkness,1.,shadow);\rreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\r}\r}\r#define inline\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\r{\rif (depthMetric>1.0 || depthMetric<0.0) {\rreturn 1.0;\r}\relse\r{\rvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\rvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\ruvDepth.z=ZINCLIP;\rvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \ruv+=0.5; \rvec2 st=fract(uv); \rvec2 base_uv=floor(uv)-0.5; \rbase_uv*=shadowMapSizeAndInverse.y; \rvec2 uvw0=4.-3.*st;\rvec2 uvw1=vec2(7.);\rvec2 uvw2=1.+3.*st;\rvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\rvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\rfloat shadow=0.;\rshadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);\rshadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);\rshadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);\rshadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);\rshadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);\rshadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);\rshadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);\rshadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);\rshadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);\rshadow=shadow/144.;\rshadow=mix(darkness,1.,shadow);\rreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\r}\r}\rconst vec3 PoissonSamplers32[64]=vec3[64](\rvec3(0.06407013,0.05409927,0.),\rvec3(0.7366577,0.5789394,0.),\rvec3(-0.6270542,-0.5320278,0.),\rvec3(-0.4096107,0.8411095,0.),\rvec3(0.6849564,-0.4990818,0.),\rvec3(-0.874181,-0.04579735,0.),\rvec3(0.9989998,0.0009880066,0.),\rvec3(-0.004920578,-0.9151649,0.),\rvec3(0.1805763,0.9747483,0.),\rvec3(-0.2138451,0.2635818,0.),\rvec3(0.109845,0.3884785,0.),\rvec3(0.06876755,-0.3581074,0.),\rvec3(0.374073,-0.7661266,0.),\rvec3(0.3079132,-0.1216763,0.),\rvec3(-0.3794335,-0.8271583,0.),\rvec3(-0.203878,-0.07715034,0.),\rvec3(0.5912697,0.1469799,0.),\rvec3(-0.88069,0.3031784,0.),\rvec3(0.5040108,0.8283722,0.),\rvec3(-0.5844124,0.5494877,0.),\rvec3(0.6017799,-0.1726654,0.),\rvec3(-0.5554981,0.1559997,0.),\rvec3(-0.3016369,-0.3900928,0.),\rvec3(-0.5550632,-0.1723762,0.),\rvec3(0.925029,0.2995041,0.),\rvec3(-0.2473137,0.5538505,0.),\rvec3(0.9183037,-0.2862392,0.),\rvec3(0.2469421,0.6718712,0.),\rvec3(0.3916397,-0.4328209,0.),\rvec3(-0.03576927,-0.6220032,0.),\rvec3(-0.04661255,0.7995201,0.),\rvec3(0.4402924,0.3640312,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.)\r);\rconst vec3 PoissonSamplers64[64]=vec3[64](\rvec3(-0.613392,0.617481,0.),\rvec3(0.170019,-0.040254,0.),\rvec3(-0.299417,0.791925,0.),\rvec3(0.645680,0.493210,0.),\rvec3(-0.651784,0.717887,0.),\rvec3(0.421003,0.027070,0.),\rvec3(-0.817194,-0.271096,0.),\rvec3(-0.705374,-0.668203,0.),\rvec3(0.977050,-0.108615,0.),\rvec3(0.063326,0.142369,0.),\rvec3(0.203528,0.214331,0.),\rvec3(-0.667531,0.326090,0.),\rvec3(-0.098422,-0.295755,0.),\rvec3(-0.885922,0.215369,0.),\rvec3(0.566637,0.605213,0.),\rvec3(0.039766,-0.396100,0.),\rvec3(0.751946,0.453352,0.),\rvec3(0.078707,-0.715323,0.),\rvec3(-0.075838,-0.529344,0.),\rvec3(0.724479,-0.580798,0.),\rvec3(0.222999,-0.215125,0.),\rvec3(-0.467574,-0.405438,0.),\rvec3(-0.248268,-0.814753,0.),\rvec3(0.354411,-0.887570,0.),\rvec3(0.175817,0.382366,0.),\rvec3(0.487472,-0.063082,0.),\rvec3(-0.084078,0.898312,0.),\rvec3(0.488876,-0.783441,0.),\rvec3(0.470016,0.217933,0.),\rvec3(-0.696890,-0.549791,0.),\rvec3(-0.149693,0.605762,0.),\rvec3(0.034211,0.979980,0.),\rvec3(0.503098,-0.308878,0.),\rvec3(-0.016205,-0.872921,0.),\rvec3(0.385784,-0.393902,0.),\rvec3(-0.146886,-0.859249,0.),\rvec3(0.643361,0.164098,0.),\rvec3(0.634388,-0.049471,0.),\rvec3(-0.688894,0.007843,0.),\rvec3(0.464034,-0.188818,0.),\rvec3(-0.440840,0.137486,0.),\rvec3(0.364483,0.511704,0.),\rvec3(0.034028,0.325968,0.),\rvec3(0.099094,-0.308023,0.),\rvec3(0.693960,-0.366253,0.),\rvec3(0.678884,-0.204688,0.),\rvec3(0.001801,0.780328,0.),\rvec3(0.145177,-0.898984,0.),\rvec3(0.062655,-0.611866,0.),\rvec3(0.315226,-0.604297,0.),\rvec3(-0.780145,0.486251,0.),\rvec3(-0.371868,0.882138,0.),\rvec3(0.200476,0.494430,0.),\rvec3(-0.494552,-0.711051,0.),\rvec3(0.612476,0.705252,0.),\rvec3(-0.578845,-0.768792,0.),\rvec3(-0.772454,-0.090976,0.),\rvec3(0.504440,0.372295,0.),\rvec3(0.155736,0.065157,0.),\rvec3(0.391522,0.849605,0.),\rvec3(-0.620106,-0.328104,0.),\rvec3(0.789239,-0.419965,0.),\rvec3(-0.545396,0.538133,0.),\rvec3(-0.178564,-0.596057,0.)\r);\r#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)\r{\rvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\rvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\ruvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);\rvec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);\rfloat blockerDepth=0.0;\rfloat sumBlockerDepth=0.0;\rfloat numBlocker=0.0;\rfor (int i=0; i1.0 || depthMetric<0.0) {\rreturn 1.0;\r}\relse\r{\rvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\rvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\ruvDepth.z=ZINCLIP;\rfloat blockerDepth=0.0;\rfloat sumBlockerDepth=0.0;\rfloat numBlocker=0.0;\rfor (int i=0; i=0.) {\rindex{X}=i;\rbreak;\r}\r}\r#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nif (index{X}>=0)\r#endif\n{\r#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#else\nshadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\r#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\r#else\nshadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\r#endif\n#else\nshadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#endif\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=vec3(shadow)*vCascadeColorsMultiplier{X}[index{X}];\r#endif\n#ifndef SHADOWCSMNOBLEND{X}\nfloat frustumLength=frustumLengths{X}[index{X}];\rfloat diffRatio=clamp(diff{X}/frustumLength,0.,1.)*cascadeBlendFactor{X};\rif (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.)\r{\rindex{X}+=1;\rfloat nextShadow=0.;\r#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#else\nnextShadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\r#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\r#else\nnextShadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\r#endif\n#else\nnextShadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#endif\nshadow=mix(nextShadow,shadow,diffRatio);\r#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio);\r#endif\n}\r#endif\n}\r#elif defined(SHADOWCLOSEESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\r#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\r#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\r#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\r#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\r#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\r#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\rshadowLightCount+=1.0;\r#endif\n#else\nshadow=1.;\r#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\r#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\r#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor.rgb*shadow;\r#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor.rgb;\r#endif\n#endif\n#ifdef CLEARCOAT\n#ifndef LIGHTMAPNOSPECULAR{X}\nclearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb;\r#endif\n#endif\n#ifdef SHEEN\n#ifndef LIGHTMAPNOSPECULAR{X}\nsheenBase+=info.sheen.rgb*shadow;\r#endif\n#endif\n#else\n#ifdef SHADOWCSMDEBUG{X}\ndiffuseBase+=info.diffuse*shadowDebug{X};\r#else \ndiffuseBase+=info.diffuse*shadow;\r#endif\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\r#endif\n#ifdef CLEARCOAT\nclearCoatBase+=info.clearCoat.rgb*shadow;\r#endif\n#ifdef SHEEN\nsheenBase+=info.sheen.rgb*shadow;\r#endif\n#endif\n#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const lightFragment = { name, shader };\n//# sourceMappingURL=lightFragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"lightVxFragmentDeclaration\";\nconst shader = `#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\runiform vec4 vLightDiffuse{X};\r#ifdef SPECULARTERM\nuniform vec4 vLightSpecular{X};\r#else\nvec4 vLightSpecular{X}=vec4(0.);\r#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];\rvarying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];\rvarying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];\rvarying vec4 vPositionFromCamera{X};\r#elif defined(SHADOWCUBE{X})\n#else\nvarying vec4 vPositionFromLight{X};\rvarying float vDepthMetric{X};\runiform mat4 lightMatrix{X};\r#endif\nuniform vec4 shadowsInfo{X};\runiform vec2 depthValues{X};\r#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\runiform vec4 vLightFalloff{X};\r#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\r#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const lightVxFragmentDeclaration = { name, shader };\n//# sourceMappingURL=lightVxFragmentDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"lightVxUboDeclaration\";\nconst shader = `#ifdef LIGHT{X}\nuniform Light{X}\r{\rvec4 vLightData;\rvec4 vLightDiffuse;\rvec4 vLightSpecular;\r#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\rvec4 vLightFalloff;\r#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\r#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\r#endif\nvec4 shadowsInfo;\rvec2 depthValues;\r} light{X};\r#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];\rvarying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];\rvarying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];\rvarying vec4 vPositionFromCamera{X};\r#elif defined(SHADOWCUBE{X})\n#else\nvarying vec4 vPositionFromLight{X};\rvarying float vDepthMetric{X};\runiform mat4 lightMatrix{X};\r#endif\n#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const lightVxUboDeclaration = { name, shader };\n//# sourceMappingURL=lightVxUboDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"morphTargetsVertexGlobalDeclaration\";\nconst shader = `#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\r#ifdef MORPHTARGETS_TEXTURE \nprecision mediump sampler2DArray; \runiform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];\runiform vec3 morphTargetTextureInfo;\runiform sampler2DArray morphTargets;\rvec3 readVector3FromRawSampler(int targetIndex,float vertexIndex)\r{ \rfloat y=floor(vertexIndex/morphTargetTextureInfo.y);\rfloat x=vertexIndex-y*morphTargetTextureInfo.y;\rvec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);\rreturn texture(morphTargets,textureUV).xyz;\r}\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const morphTargetsVertexGlobalDeclaration = { name, shader };\n//# sourceMappingURL=morphTargetsVertexGlobalDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"morphTargetsVertexDeclaration\";\nconst shader = `#ifdef MORPHTARGETS\n#ifndef MORPHTARGETS_TEXTURE\nattribute vec3 position{X};\r#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\r#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\r#endif\n#ifdef MORPHTARGETS_UV\nattribute vec2 uv_{X};\r#endif\n#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const morphTargetsVertexDeclaration = { name, shader };\n//# sourceMappingURL=morphTargetsVertexDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"bakedVertexAnimation\";\nconst shader = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\n{\r#ifdef INSTANCES\n#define BVASNAME bakedVertexAnimationSettingsInstanced\n#else\n#define BVASNAME bakedVertexAnimationSettings\n#endif\nfloat VATStartFrame=BVASNAME.x;\rfloat VATEndFrame=BVASNAME.y;\rfloat VATOffsetFrame=BVASNAME.z;\rfloat VATSpeed=BVASNAME.w;\rfloat totalFrames=VATEndFrame-VATStartFrame+1.0;\rfloat time=bakedVertexAnimationTime*VATSpeed/totalFrames;\rfloat frameCorrection=time<1.0 ? 0.0 : 1.0;\rfloat numOfFrames=totalFrames-frameCorrection;\rfloat VATFrameNum=fract(time)*numOfFrames;\rVATFrameNum=mod(VATFrameNum+VATOffsetFrame,numOfFrames);\rVATFrameNum=floor(VATFrameNum);\rVATFrameNum+=VATStartFrame+frameCorrection;\rmat4 VATInfluence;\rVATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[0],VATFrameNum)*matricesWeights[0];\r#if NUM_BONE_INFLUENCERS>1\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1];\r#endif\n#if NUM_BONE_INFLUENCERS>2\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2];\r#endif\n#if NUM_BONE_INFLUENCERS>3\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3];\r#endif\n#if NUM_BONE_INFLUENCERS>4\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0];\r#endif\n#if NUM_BONE_INFLUENCERS>5\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1];\r#endif\n#if NUM_BONE_INFLUENCERS>6\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2];\r#endif\n#if NUM_BONE_INFLUENCERS>7\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3];\r#endif\nfinalWorld=finalWorld*VATInfluence;\r}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const bakedVertexAnimation = { name, shader };\n//# sourceMappingURL=bakedVertexAnimation.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"prePassVertex\";\nconst shader = `#ifdef PREPASS_DEPTH\nvViewPos=(view*worldPos).rgb;\r#endif\n#if defined(PREPASS_VELOCITY) && defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*worldPos;\r#if NUM_BONE_INFLUENCERS>0\nmat4 previousInfluence;\rpreviousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];\r#if NUM_BONE_INFLUENCERS>1\npreviousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];\r#endif \n#if NUM_BONE_INFLUENCERS>2\npreviousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];\r#endif \n#if NUM_BONE_INFLUENCERS>3\npreviousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];\r#endif\n#if NUM_BONE_INFLUENCERS>4\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\r#endif \n#if NUM_BONE_INFLUENCERS>5\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\r#endif \n#if NUM_BONE_INFLUENCERS>6\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\r#endif \n#if NUM_BONE_INFLUENCERS>7\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\r#endif\nvPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0);\r#else\nvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const prePassVertex = { name, shader };\n//# sourceMappingURL=prePassVertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"vertexColorMixing\";\nconst shader = `#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvColor=vec4(1.0);\r#ifdef VERTEXCOLOR\n#ifdef VERTEXALPHA\nvColor*=color;\r#else\nvColor.rgb*=color.rgb;\r#endif\n#endif\n#ifdef INSTANCESCOLOR\nvColor*=instanceColor;\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const vertexColorMixing = { name, shader };\n//# sourceMappingURL=vertexColorMixing.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pointCloudVertex\";\nconst shader = `#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pointCloudVertex = { name, shader };\n//# sourceMappingURL=pointCloudVertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/defaultVertexDeclaration.js\";\nimport \"./ShadersInclude/defaultUboDeclaration.js\";\nimport \"./ShadersInclude/uvAttributeDeclaration.js\";\nimport \"./ShadersInclude/helperFunctions.js\";\nimport \"./ShadersInclude/bonesDeclaration.js\";\nimport \"./ShadersInclude/bakedVertexAnimationDeclaration.js\";\nimport \"./ShadersInclude/instancesDeclaration.js\";\nimport \"./ShadersInclude/prePassVertexDeclaration.js\";\nimport \"./ShadersInclude/mainUVVaryingDeclaration.js\";\nimport \"./ShadersInclude/samplerVertexDeclaration.js\";\nimport \"./ShadersInclude/bumpVertexDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneVertexDeclaration.js\";\nimport \"./ShadersInclude/fogVertexDeclaration.js\";\nimport \"./ShadersInclude/lightVxFragmentDeclaration.js\";\nimport \"./ShadersInclude/lightVxUboDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexGlobalDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexDeclaration.js\";\nimport \"./ShadersInclude/logDepthDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexGlobal.js\";\nimport \"./ShadersInclude/morphTargetsVertex.js\";\nimport \"./ShadersInclude/instancesVertex.js\";\nimport \"./ShadersInclude/bonesVertex.js\";\nimport \"./ShadersInclude/bakedVertexAnimation.js\";\nimport \"./ShadersInclude/prePassVertex.js\";\nimport \"./ShadersInclude/uvVariableDeclaration.js\";\nimport \"./ShadersInclude/samplerVertexImplementation.js\";\nimport \"./ShadersInclude/bumpVertex.js\";\nimport \"./ShadersInclude/clipPlaneVertex.js\";\nimport \"./ShadersInclude/fogVertex.js\";\nimport \"./ShadersInclude/shadowsVertex.js\";\nimport \"./ShadersInclude/vertexColorMixing.js\";\nimport \"./ShadersInclude/pointCloudVertex.js\";\nimport \"./ShadersInclude/logDepthVertex.js\";\nconst name = \"defaultVertexShader\";\nconst shader = `#include<__decl__defaultVertex>\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\r#ifdef NORMAL\nattribute vec3 normal;\r#endif\n#ifdef TANGENT\nattribute vec4 tangent;\r#endif\n#ifdef UV1\nattribute vec2 uv;\r#endif\n#include[2..7]\n#ifdef VERTEXCOLOR\nattribute vec4 color;\r#endif\n#include\n#include\n#include\n#include\n#include\n#include[1..7]\n#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)\n#if defined(SPECULARTERM)\n#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular)\n#endif\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)\nvarying vec3 vPositionW;\r#ifdef NORMAL\nvarying vec3 vNormalW;\r#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\r#endif\n#include\n#include\n#include\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\r#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\r#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\r#ifdef NORMAL\nvec3 normalUpdated=normal;\r#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\r#endif\n#ifdef UV1\nvec2 uvUpdated=uv;\r#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\r#endif\n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include\n#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\rvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\r#endif\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\r#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\r#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));\rvNormalW=normalize(normalWorld*vNormalW);\r#else\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\r#endif\nvNormalW=normalize(normalWorld*normalUpdated);\r#endif\n#endif\n#define CUSTOM_VERTEX_UPDATE_WORLDPOS\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {\rgl_Position=viewProjection*worldPos;\r} else {\rgl_Position=viewProjectionR*worldPos;\r}\r#else\ngl_Position=viewProjection*worldPos;\r#endif\nvPositionW=vec3(worldPos);\r#include\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\r#endif\n#ifndef UV1\nvec2 uvUpdated=vec2(0.,0.);\r#endif\n#ifdef MAINUV1\nvMainUV1=uvUpdated;\r#endif\n#include[2..7]\n#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)\n#if defined(SPECULARTERM)\n#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x)\n#endif\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const defaultVertexShader = { name, shader };\n//# sourceMappingURL=default.vertex.js.map","import { Material } from \"./material.js\";\nimport { MaterialPluginEvent } from \"./materialPluginEvent.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nconst rxOption = new RegExp(\"^([gimus]+)!\");\n/**\n * Class that manages the plugins of a material\n * @since 5.0\n */\nexport class MaterialPluginManager {\n /**\n * Creates a new instance of the plugin manager\n * @param material material that this manager will manage the plugins for\n */\n constructor(material) {\n /** @internal */\n this._plugins = [];\n this._activePlugins = [];\n this._activePluginsForExtraEvents = [];\n this._material = material;\n this._scene = material.getScene();\n this._engine = this._scene.getEngine();\n }\n /**\n * @internal\n */\n _addPlugin(plugin) {\n for (let i = 0; i < this._plugins.length; ++i) {\n if (this._plugins[i].name === plugin.name) {\n return false;\n }\n }\n if (this._material._uniformBufferLayoutBuilt) {\n throw `The plugin \"${plugin.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.`;\n }\n const pluginClassName = plugin.getClassName();\n if (!MaterialPluginManager._MaterialPluginClassToMainDefine[pluginClassName]) {\n MaterialPluginManager._MaterialPluginClassToMainDefine[pluginClassName] = \"MATERIALPLUGIN_\" + ++MaterialPluginManager._MaterialPluginCounter;\n }\n this._material._callbackPluginEventGeneric = this._handlePluginEvent.bind(this);\n this._plugins.push(plugin);\n this._plugins.sort((a, b) => a.priority - b.priority);\n this._codeInjectionPoints = {};\n const defineNamesFromPlugins = {};\n defineNamesFromPlugins[MaterialPluginManager._MaterialPluginClassToMainDefine[pluginClassName]] = {\n type: \"boolean\",\n default: true,\n };\n for (const plugin of this._plugins) {\n plugin.collectDefines(defineNamesFromPlugins);\n this._collectPointNames(\"vertex\", plugin.getCustomCode(\"vertex\"));\n this._collectPointNames(\"fragment\", plugin.getCustomCode(\"fragment\"));\n }\n this._defineNamesFromPlugins = defineNamesFromPlugins;\n return true;\n }\n /**\n * @internal\n */\n _activatePlugin(plugin) {\n if (this._activePlugins.indexOf(plugin) === -1) {\n this._activePlugins.push(plugin);\n this._activePlugins.sort((a, b) => a.priority - b.priority);\n this._material._callbackPluginEventIsReadyForSubMesh = this._handlePluginEventIsReadyForSubMesh.bind(this);\n this._material._callbackPluginEventPrepareDefinesBeforeAttributes = this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this);\n this._material._callbackPluginEventPrepareDefines = this._handlePluginEventPrepareDefines.bind(this);\n this._material._callbackPluginEventBindForSubMesh = this._handlePluginEventBindForSubMesh.bind(this);\n if (plugin.registerForExtraEvents) {\n this._activePluginsForExtraEvents.push(plugin);\n this._activePluginsForExtraEvents.sort((a, b) => a.priority - b.priority);\n this._material._callbackPluginEventHasRenderTargetTextures = this._handlePluginEventHasRenderTargetTextures.bind(this);\n this._material._callbackPluginEventFillRenderTargetTextures = this._handlePluginEventFillRenderTargetTextures.bind(this);\n this._material._callbackPluginEventHardBindForSubMesh = this._handlePluginEventHardBindForSubMesh.bind(this);\n }\n }\n }\n /**\n * Gets a plugin from the list of plugins managed by this manager\n * @param name name of the plugin\n * @returns the plugin if found, else null\n */\n getPlugin(name) {\n for (let i = 0; i < this._plugins.length; ++i) {\n if (this._plugins[i].name === name) {\n return this._plugins[i];\n }\n }\n return null;\n }\n _handlePluginEventIsReadyForSubMesh(eventData) {\n let isReady = true;\n for (const plugin of this._activePlugins) {\n isReady = isReady && plugin.isReadyForSubMesh(eventData.defines, this._scene, this._engine, eventData.subMesh);\n }\n eventData.isReadyForSubMesh = isReady;\n }\n _handlePluginEventPrepareDefinesBeforeAttributes(eventData) {\n for (const plugin of this._activePlugins) {\n plugin.prepareDefinesBeforeAttributes(eventData.defines, this._scene, eventData.mesh);\n }\n }\n _handlePluginEventPrepareDefines(eventData) {\n for (const plugin of this._activePlugins) {\n plugin.prepareDefines(eventData.defines, this._scene, eventData.mesh);\n }\n }\n _handlePluginEventHardBindForSubMesh(eventData) {\n for (const plugin of this._activePluginsForExtraEvents) {\n plugin.hardBindForSubMesh(this._material._uniformBuffer, this._scene, this._engine, eventData.subMesh);\n }\n }\n _handlePluginEventBindForSubMesh(eventData) {\n for (const plugin of this._activePlugins) {\n plugin.bindForSubMesh(this._material._uniformBuffer, this._scene, this._engine, eventData.subMesh);\n }\n }\n _handlePluginEventHasRenderTargetTextures(eventData) {\n let hasRenderTargetTextures = false;\n for (const plugin of this._activePluginsForExtraEvents) {\n hasRenderTargetTextures = plugin.hasRenderTargetTextures();\n if (hasRenderTargetTextures) {\n break;\n }\n }\n eventData.hasRenderTargetTextures = hasRenderTargetTextures;\n }\n _handlePluginEventFillRenderTargetTextures(eventData) {\n for (const plugin of this._activePluginsForExtraEvents) {\n plugin.fillRenderTargetTextures(eventData.renderTargets);\n }\n }\n _handlePluginEvent(id, info) {\n var _a;\n switch (id) {\n case MaterialPluginEvent.GetActiveTextures: {\n const eventData = info;\n for (const plugin of this._activePlugins) {\n plugin.getActiveTextures(eventData.activeTextures);\n }\n break;\n }\n case MaterialPluginEvent.GetAnimatables: {\n const eventData = info;\n for (const plugin of this._activePlugins) {\n plugin.getAnimatables(eventData.animatables);\n }\n break;\n }\n case MaterialPluginEvent.HasTexture: {\n const eventData = info;\n let hasTexture = false;\n for (const plugin of this._activePlugins) {\n hasTexture = plugin.hasTexture(eventData.texture);\n if (hasTexture) {\n break;\n }\n }\n eventData.hasTexture = hasTexture;\n break;\n }\n case MaterialPluginEvent.Disposed: {\n const eventData = info;\n for (const plugin of this._plugins) {\n plugin.dispose(eventData.forceDisposeTextures);\n }\n break;\n }\n case MaterialPluginEvent.GetDefineNames: {\n const eventData = info;\n eventData.defineNames = this._defineNamesFromPlugins;\n break;\n }\n case MaterialPluginEvent.PrepareEffect: {\n const eventData = info;\n for (const plugin of this._activePlugins) {\n eventData.fallbackRank = plugin.addFallbacks(eventData.defines, eventData.fallbacks, eventData.fallbackRank);\n plugin.getAttributes(eventData.attributes, this._scene, eventData.mesh);\n }\n if (this._uniformList.length > 0) {\n eventData.uniforms.push(...this._uniformList);\n }\n if (this._samplerList.length > 0) {\n eventData.samplers.push(...this._samplerList);\n }\n if (this._uboList.length > 0) {\n eventData.uniformBuffersNames.push(...this._uboList);\n }\n eventData.customCode = this._injectCustomCode(eventData.customCode);\n break;\n }\n case MaterialPluginEvent.PrepareUniformBuffer: {\n const eventData = info;\n this._uboDeclaration = \"\";\n this._vertexDeclaration = \"\";\n this._fragmentDeclaration = \"\";\n this._uniformList = [];\n this._samplerList = [];\n this._uboList = [];\n for (const plugin of this._plugins) {\n const uniforms = plugin.getUniforms();\n if (uniforms) {\n if (uniforms.ubo) {\n for (const uniform of uniforms.ubo) {\n if (uniform.size && uniform.type) {\n const arraySize = (_a = uniform.arraySize) !== null && _a !== void 0 ? _a : 0;\n eventData.ubo.addUniform(uniform.name, uniform.size, arraySize);\n this._uboDeclaration += `${uniform.type} ${uniform.name}${arraySize > 0 ? `[${arraySize}]` : \"\"};\\r\\n`;\n }\n this._uniformList.push(uniform.name);\n }\n }\n if (uniforms.vertex) {\n this._vertexDeclaration += uniforms.vertex + \"\\r\\n\";\n }\n if (uniforms.fragment) {\n this._fragmentDeclaration += uniforms.fragment + \"\\r\\n\";\n }\n }\n plugin.getSamplers(this._samplerList);\n plugin.getUniformBuffersNames(this._uboList);\n }\n break;\n }\n }\n }\n _collectPointNames(shaderType, customCode) {\n if (!customCode) {\n return;\n }\n for (const pointName in customCode) {\n if (!this._codeInjectionPoints[shaderType]) {\n this._codeInjectionPoints[shaderType] = {};\n }\n this._codeInjectionPoints[shaderType][pointName] = true;\n }\n }\n _injectCustomCode(existingCallback) {\n return (shaderType, code) => {\n var _a;\n if (existingCallback) {\n code = existingCallback(shaderType, code);\n }\n if (this._uboDeclaration) {\n code = code.replace(\"#define ADDITIONAL_UBO_DECLARATION\", this._uboDeclaration);\n }\n if (this._vertexDeclaration) {\n code = code.replace(\"#define ADDITIONAL_VERTEX_DECLARATION\", this._vertexDeclaration);\n }\n if (this._fragmentDeclaration) {\n code = code.replace(\"#define ADDITIONAL_FRAGMENT_DECLARATION\", this._fragmentDeclaration);\n }\n const points = (_a = this._codeInjectionPoints) === null || _a === void 0 ? void 0 : _a[shaderType];\n if (!points) {\n return code;\n }\n for (let pointName in points) {\n let injectedCode = \"\";\n for (const plugin of this._activePlugins) {\n const customCode = plugin.getCustomCode(shaderType);\n if (customCode === null || customCode === void 0 ? void 0 : customCode[pointName]) {\n injectedCode += customCode[pointName] + \"\\r\\n\";\n }\n }\n if (injectedCode.length > 0) {\n if (pointName.charAt(0) === \"!\") {\n // pointName is a regular expression\n pointName = pointName.substring(1);\n let regexFlags = \"g\";\n if (pointName.charAt(0) === \"!\") {\n // no flags\n regexFlags = \"\";\n pointName = pointName.substring(1);\n }\n else {\n // get the flag(s)\n const matchOption = rxOption.exec(pointName);\n if (matchOption && matchOption.length >= 2) {\n regexFlags = matchOption[1];\n pointName = pointName.substring(regexFlags.length + 1);\n }\n }\n if (regexFlags.indexOf(\"g\") < 0) {\n // we force the \"g\" flag so that the regexp object is stateful!\n regexFlags += \"g\";\n }\n const sourceCode = code;\n const rx = new RegExp(pointName, regexFlags);\n let match = rx.exec(sourceCode);\n while (match !== null) {\n let newCode = injectedCode;\n for (let i = 0; i < match.length; ++i) {\n newCode = newCode.replace(\"$\" + i, match[i]);\n }\n code = code.replace(match[0], newCode);\n match = rx.exec(sourceCode);\n }\n }\n else {\n const fullPointName = \"#define \" + pointName;\n code = code.replace(fullPointName, \"\\r\\n\" + injectedCode + \"\\r\\n\" + fullPointName);\n }\n }\n }\n return code;\n };\n }\n}\n/** Map a plugin class name to a #define name (used in the vertex/fragment shaders as a marker of the plugin usage) */\nMaterialPluginManager._MaterialPluginClassToMainDefine = {};\nMaterialPluginManager._MaterialPluginCounter = 0;\n(() => {\n EngineStore.OnEnginesDisposedObservable.add(() => {\n UnregisterAllMaterialPlugins();\n });\n})();\nconst plugins = [];\nlet inited = false;\nlet observer = null;\n/**\n * Registers a new material plugin through a factory, or updates it. This makes the plugin available to all materials instantiated after its registration.\n * @param pluginName The plugin name\n * @param factory The factory function which allows to create the plugin\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function RegisterMaterialPlugin(pluginName, factory) {\n if (!inited) {\n observer = Material.OnEventObservable.add((material) => {\n for (const [, factory] of plugins) {\n factory(material);\n }\n }, MaterialPluginEvent.Created);\n inited = true;\n }\n const existing = plugins.filter(([name, _factory]) => name === pluginName);\n if (existing.length > 0) {\n existing[0][1] = factory;\n }\n else {\n plugins.push([pluginName, factory]);\n }\n}\n/**\n * Removes a material plugin from the list of global plugins.\n * @param pluginName The plugin name\n * @returns true if the plugin has been removed, else false\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function UnregisterMaterialPlugin(pluginName) {\n for (let i = 0; i < plugins.length; ++i) {\n if (plugins[i][0] === pluginName) {\n plugins.splice(i, 1);\n if (plugins.length === 0) {\n UnregisterAllMaterialPlugins();\n }\n return true;\n }\n }\n return false;\n}\n/**\n * Clear the list of global material plugins\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function UnregisterAllMaterialPlugins() {\n plugins.length = 0;\n inited = false;\n Material.OnEventObservable.remove(observer);\n observer = null;\n}\n//# sourceMappingURL=materialPluginManager.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { SerializationHelper, serialize } from \"../Misc/decorators.js\";\nimport { MaterialPluginManager } from \"./materialPluginManager.js\";\n\n/**\n * Base class for material plugins.\n * @since 5.0\n */\nexport class MaterialPluginBase {\n _enable(enable) {\n if (enable) {\n this._pluginManager._activatePlugin(this);\n }\n }\n /**\n * Creates a new material plugin\n * @param material parent material of the plugin\n * @param name name of the plugin\n * @param priority priority of the plugin\n * @param defines list of defines used by the plugin. The value of the property is the default value for this property\n * @param addToPluginList true to add the plugin to the list of plugins managed by the material plugin manager of the material (default: true)\n * @param enable true to enable the plugin (it is handy if the plugin does not handle properties to switch its current activation)\n */\n constructor(material, name, priority, defines, addToPluginList = true, enable = false) {\n /**\n * Defines the priority of the plugin. Lower numbers run first.\n */\n this.priority = 500;\n /**\n * Indicates that this plugin should be notified for the extra events (HasRenderTargetTextures / FillRenderTargetTextures / HardBindForSubMesh)\n */\n this.registerForExtraEvents = false;\n this._material = material;\n this.name = name;\n this.priority = priority;\n if (!material.pluginManager) {\n material.pluginManager = new MaterialPluginManager(material);\n material.onDisposeObservable.add(() => {\n material.pluginManager = undefined;\n });\n }\n this._pluginDefineNames = defines;\n this._pluginManager = material.pluginManager;\n if (addToPluginList) {\n this._pluginManager._addPlugin(this);\n }\n if (enable) {\n this._enable(true);\n }\n this.markAllDefinesAsDirty = material._dirtyCallbacks[63];\n }\n /**\n * Gets the current class name useful for serialization or dynamic coding.\n * @returns The class name.\n */\n getClassName() {\n return \"MaterialPluginBase\";\n }\n /**\n * Specifies that the submesh is ready to be used.\n * @param defines the list of \"defines\" to update.\n * @param scene defines the scene the material belongs to.\n * @param engine the engine this scene belongs to.\n * @param subMesh the submesh to check for readiness\n * @returns - boolean indicating that the submesh is ready or not.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isReadyForSubMesh(defines, scene, engine, subMesh) {\n return true;\n }\n /**\n * Binds the material data (this function is called even if mustRebind() returns false)\n * @param uniformBuffer defines the Uniform buffer to fill in.\n * @param scene defines the scene the material belongs to.\n * @param engine defines the engine the material belongs to.\n * @param subMesh the submesh to bind data for\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n hardBindForSubMesh(uniformBuffer, scene, engine, subMesh) { }\n /**\n * Binds the material data.\n * @param uniformBuffer defines the Uniform buffer to fill in.\n * @param scene defines the scene the material belongs to.\n * @param engine the engine this scene belongs to.\n * @param subMesh the submesh to bind data for\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n bindForSubMesh(uniformBuffer, scene, engine, subMesh) { }\n /**\n * Disposes the resources of the material.\n * @param forceDisposeTextures - Forces the disposal of all textures.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n dispose(forceDisposeTextures) { }\n /**\n * Returns a list of custom shader code fragments to customize the shader.\n * @param shaderType \"vertex\" or \"fragment\"\n * @returns null if no code to be added, or a list of pointName => code.\n * Note that `pointName` can also be a regular expression if it starts with a `!`.\n * In that case, the string found by the regular expression (if any) will be\n * replaced by the code provided.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getCustomCode(shaderType) {\n return null;\n }\n /**\n * Collects all defines.\n * @param defines The object to append to.\n */\n collectDefines(defines) {\n if (!this._pluginDefineNames) {\n return;\n }\n for (const key of Object.keys(this._pluginDefineNames)) {\n if (key[0] === \"_\") {\n continue;\n }\n const type = typeof this._pluginDefineNames[key];\n defines[key] = {\n type: type === \"number\" ? \"number\" : type === \"string\" ? \"string\" : type === \"boolean\" ? \"boolean\" : \"object\",\n default: this._pluginDefineNames[key],\n };\n }\n }\n /**\n * Sets the defines for the next rendering. Called before MaterialHelper.PrepareDefinesForAttributes is called.\n * @param defines the list of \"defines\" to update.\n * @param scene defines the scene to the material belongs to.\n * @param mesh the mesh being rendered\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n prepareDefinesBeforeAttributes(defines, scene, mesh) { }\n /**\n * Sets the defines for the next rendering\n * @param defines the list of \"defines\" to update.\n * @param scene defines the scene to the material belongs to.\n * @param mesh the mesh being rendered\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n prepareDefines(defines, scene, mesh) { }\n /**\n * Checks to see if a texture is used in the material.\n * @param texture - Base texture to use.\n * @returns - Boolean specifying if a texture is used in the material.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n hasTexture(texture) {\n return false;\n }\n /**\n * Gets a boolean indicating that current material needs to register RTT\n * @returns true if this uses a render target otherwise false.\n */\n hasRenderTargetTextures() {\n return false;\n }\n /**\n * Fills the list of render target textures.\n * @param renderTargets the list of render targets to update\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n fillRenderTargetTextures(renderTargets) { }\n /**\n * Returns an array of the actively used textures.\n * @param activeTextures Array of BaseTextures\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getActiveTextures(activeTextures) { }\n /**\n * Returns the animatable textures.\n * @param animatables Array of animatable textures.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getAnimatables(animatables) { }\n /**\n * Add fallbacks to the effect fallbacks list.\n * @param defines defines the Base texture to use.\n * @param fallbacks defines the current fallback list.\n * @param currentRank defines the current fallback rank.\n * @returns the new fallback rank.\n */\n addFallbacks(defines, fallbacks, currentRank) {\n return currentRank;\n }\n /**\n * Gets the samplers used by the plugin.\n * @param samplers list that the sampler names should be added to.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getSamplers(samplers) { }\n /**\n * Gets the attributes used by the plugin.\n * @param attributes list that the attribute names should be added to.\n * @param scene the scene that the material belongs to.\n * @param mesh the mesh being rendered.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getAttributes(attributes, scene, mesh) { }\n /**\n * Gets the uniform buffers names added by the plugin.\n * @param ubos list that the ubo names should be added to.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getUniformBuffersNames(ubos) { }\n /**\n * Gets the description of the uniforms to add to the ubo (if engine supports ubos) or to inject directly in the vertex/fragment shaders (if engine does not support ubos)\n * @returns the description of the uniforms\n */\n getUniforms() {\n return {};\n }\n /**\n * Makes a duplicate of the current configuration into another one.\n * @param plugin define the config where to copy the info\n */\n copyTo(plugin) {\n SerializationHelper.Clone(() => plugin, this);\n }\n /**\n * Serializes this plugin configuration.\n * @returns - An object with the serialized config.\n */\n serialize() {\n return SerializationHelper.Serialize(this);\n }\n /**\n * Parses a plugin configuration from a serialized object.\n * @param source - Serialized object.\n * @param scene Defines the scene we are parsing for\n * @param rootUrl Defines the rootUrl to load from\n */\n parse(source, scene, rootUrl) {\n SerializationHelper.Parse(() => this, source, scene, rootUrl);\n }\n}\n__decorate([\n serialize()\n], MaterialPluginBase.prototype, \"name\", void 0);\n__decorate([\n serialize()\n], MaterialPluginBase.prototype, \"priority\", void 0);\n__decorate([\n serialize()\n], MaterialPluginBase.prototype, \"registerForExtraEvents\", void 0);\n//# sourceMappingURL=materialPluginBase.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { Material } from \"./material.js\";\nimport { serialize, expandToProperty, serializeAsTexture } from \"../Misc/decorators.js\";\nimport { MaterialFlags } from \"./materialFlags.js\";\nimport { MaterialHelper } from \"./materialHelper.js\";\nimport { MaterialDefines } from \"./materialDefines.js\";\nimport { MaterialPluginBase } from \"./materialPluginBase.js\";\n\n/**\n * @internal\n */\nexport class MaterialDetailMapDefines extends MaterialDefines {\n constructor() {\n super(...arguments);\n this.DETAIL = false;\n this.DETAILDIRECTUV = 0;\n this.DETAIL_NORMALBLENDMETHOD = 0;\n }\n}\n/**\n * Plugin that implements the detail map component of a material\n *\n * Inspired from:\n * Unity: https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@9.0/manual/Mask-Map-and-Detail-Map.html and https://docs.unity3d.com/Manual/StandardShaderMaterialParameterDetail.html\n * Unreal: https://docs.unrealengine.com/en-US/Engine/Rendering/Materials/HowTo/DetailTexturing/index.html\n * Cryengine: https://docs.cryengine.com/display/SDKDOC2/Detail+Maps\n */\nexport class DetailMapConfiguration extends MaterialPluginBase {\n /** @internal */\n _markAllSubMeshesAsTexturesDirty() {\n this._enable(this._isEnabled);\n this._internalMarkAllSubMeshesAsTexturesDirty();\n }\n constructor(material, addToPluginList = true) {\n super(material, \"DetailMap\", 140, new MaterialDetailMapDefines(), addToPluginList);\n this._texture = null;\n /**\n * Defines how strongly the detail diffuse/albedo channel is blended with the regular diffuse/albedo texture\n * Bigger values mean stronger blending\n */\n this.diffuseBlendLevel = 1;\n /**\n * Defines how strongly the detail roughness channel is blended with the regular roughness value\n * Bigger values mean stronger blending. Only used with PBR materials\n */\n this.roughnessBlendLevel = 1;\n /**\n * Defines how strong the bump effect from the detail map is\n * Bigger values mean stronger effect\n */\n this.bumpLevel = 1;\n this._normalBlendMethod = Material.MATERIAL_NORMALBLENDMETHOD_WHITEOUT;\n this._isEnabled = false;\n /**\n * Enable or disable the detail map on this material\n */\n this.isEnabled = false;\n this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];\n }\n isReadyForSubMesh(defines, scene, engine) {\n if (!this._isEnabled) {\n return true;\n }\n if (defines._areTexturesDirty && scene.texturesEnabled) {\n if (engine.getCaps().standardDerivatives && this._texture && MaterialFlags.DetailTextureEnabled) {\n // Detail texture cannot be not blocking.\n if (!this._texture.isReady()) {\n return false;\n }\n }\n }\n return true;\n }\n prepareDefines(defines, scene) {\n if (this._isEnabled) {\n defines.DETAIL_NORMALBLENDMETHOD = this._normalBlendMethod;\n const engine = scene.getEngine();\n if (defines._areTexturesDirty) {\n if (engine.getCaps().standardDerivatives && this._texture && MaterialFlags.DetailTextureEnabled && this._isEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._texture, defines, \"DETAIL\");\n defines.DETAIL_NORMALBLENDMETHOD = this._normalBlendMethod;\n }\n else {\n defines.DETAIL = false;\n }\n }\n }\n else {\n defines.DETAIL = false;\n }\n }\n bindForSubMesh(uniformBuffer, scene) {\n if (!this._isEnabled) {\n return;\n }\n const isFrozen = this._material.isFrozen;\n if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {\n if (this._texture && MaterialFlags.DetailTextureEnabled) {\n uniformBuffer.updateFloat4(\"vDetailInfos\", this._texture.coordinatesIndex, this.diffuseBlendLevel, this.bumpLevel, this.roughnessBlendLevel);\n MaterialHelper.BindTextureMatrix(this._texture, uniformBuffer, \"detail\");\n }\n }\n // Textures\n if (scene.texturesEnabled) {\n if (this._texture && MaterialFlags.DetailTextureEnabled) {\n uniformBuffer.setTexture(\"detailSampler\", this._texture);\n }\n }\n }\n hasTexture(texture) {\n if (this._texture === texture) {\n return true;\n }\n return false;\n }\n getActiveTextures(activeTextures) {\n if (this._texture) {\n activeTextures.push(this._texture);\n }\n }\n getAnimatables(animatables) {\n if (this._texture && this._texture.animations && this._texture.animations.length > 0) {\n animatables.push(this._texture);\n }\n }\n dispose(forceDisposeTextures) {\n var _a;\n if (forceDisposeTextures) {\n (_a = this._texture) === null || _a === void 0 ? void 0 : _a.dispose();\n }\n }\n getClassName() {\n return \"DetailMapConfiguration\";\n }\n getSamplers(samplers) {\n samplers.push(\"detailSampler\");\n }\n getUniforms() {\n return {\n ubo: [\n { name: \"vDetailInfos\", size: 4, type: \"vec4\" },\n { name: \"detailMatrix\", size: 16, type: \"mat4\" },\n ],\n };\n }\n}\n__decorate([\n serializeAsTexture(\"detailTexture\"),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], DetailMapConfiguration.prototype, \"texture\", void 0);\n__decorate([\n serialize()\n], DetailMapConfiguration.prototype, \"diffuseBlendLevel\", void 0);\n__decorate([\n serialize()\n], DetailMapConfiguration.prototype, \"roughnessBlendLevel\", void 0);\n__decorate([\n serialize()\n], DetailMapConfiguration.prototype, \"bumpLevel\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], DetailMapConfiguration.prototype, \"normalBlendMethod\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], DetailMapConfiguration.prototype, \"isEnabled\", void 0);\n//# sourceMappingURL=material.detailMapConfiguration.js.map","import { __decorate } from \"../tslib.es6.js\";\n/* eslint-disable @typescript-eslint/naming-convention */\nimport { serialize, SerializationHelper, serializeAsColor3, expandToProperty, serializeAsFresnelParameters, serializeAsTexture } from \"../Misc/decorators.js\";\nimport { SmartArray } from \"../Misc/smartArray.js\";\nimport { Scene } from \"../scene.js\";\nimport { Matrix } from \"../Maths/math.vector.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { PrePassConfiguration } from \"./prePassConfiguration.js\";\nimport { ImageProcessingConfiguration } from \"./imageProcessingConfiguration.js\";\nimport { Material } from \"../Materials/material.js\";\nimport { MaterialPluginEvent } from \"./materialPluginEvent.js\";\nimport { MaterialDefines } from \"../Materials/materialDefines.js\";\nimport { PushMaterial } from \"./pushMaterial.js\";\nimport { MaterialHelper } from \"./materialHelper.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\nimport { MaterialFlags } from \"./materialFlags.js\";\nimport \"../Shaders/default.fragment.js\";\nimport \"../Shaders/default.vertex.js\";\n\nimport { EffectFallbacks } from \"./effectFallbacks.js\";\nimport { DetailMapConfiguration } from \"./material.detailMapConfiguration.js\";\nimport { addClipPlaneUniforms, bindClipPlane } from \"./clipPlaneMaterialHelper.js\";\nconst onCreatedEffectParameters = { effect: null, subMesh: null };\n/** @internal */\nexport class StandardMaterialDefines extends MaterialDefines {\n /**\n * Initializes the Standard Material defines.\n * @param externalProperties The external properties\n */\n constructor(externalProperties) {\n super(externalProperties);\n this.MAINUV1 = false;\n this.MAINUV2 = false;\n this.MAINUV3 = false;\n this.MAINUV4 = false;\n this.MAINUV5 = false;\n this.MAINUV6 = false;\n this.DIFFUSE = false;\n this.DIFFUSEDIRECTUV = 0;\n this.BAKED_VERTEX_ANIMATION_TEXTURE = false;\n this.AMBIENT = false;\n this.AMBIENTDIRECTUV = 0;\n this.OPACITY = false;\n this.OPACITYDIRECTUV = 0;\n this.OPACITYRGB = false;\n this.REFLECTION = false;\n this.EMISSIVE = false;\n this.EMISSIVEDIRECTUV = 0;\n this.SPECULAR = false;\n this.SPECULARDIRECTUV = 0;\n this.BUMP = false;\n this.BUMPDIRECTUV = 0;\n this.PARALLAX = false;\n this.PARALLAXOCCLUSION = false;\n this.SPECULAROVERALPHA = false;\n this.CLIPPLANE = false;\n this.CLIPPLANE2 = false;\n this.CLIPPLANE3 = false;\n this.CLIPPLANE4 = false;\n this.CLIPPLANE5 = false;\n this.CLIPPLANE6 = false;\n this.ALPHATEST = false;\n this.DEPTHPREPASS = false;\n this.ALPHAFROMDIFFUSE = false;\n this.POINTSIZE = false;\n this.FOG = false;\n this.SPECULARTERM = false;\n this.DIFFUSEFRESNEL = false;\n this.OPACITYFRESNEL = false;\n this.REFLECTIONFRESNEL = false;\n this.REFRACTIONFRESNEL = false;\n this.EMISSIVEFRESNEL = false;\n this.FRESNEL = false;\n this.NORMAL = false;\n this.TANGENT = false;\n this.UV1 = false;\n this.UV2 = false;\n this.UV3 = false;\n this.UV4 = false;\n this.UV5 = false;\n this.UV6 = false;\n this.VERTEXCOLOR = false;\n this.VERTEXALPHA = false;\n this.NUM_BONE_INFLUENCERS = 0;\n this.BonesPerMesh = 0;\n this.BONETEXTURE = false;\n this.BONES_VELOCITY_ENABLED = false;\n this.INSTANCES = false;\n this.THIN_INSTANCES = false;\n this.INSTANCESCOLOR = false;\n this.GLOSSINESS = false;\n this.ROUGHNESS = false;\n this.EMISSIVEASILLUMINATION = false;\n this.LINKEMISSIVEWITHDIFFUSE = false;\n this.REFLECTIONFRESNELFROMSPECULAR = false;\n this.LIGHTMAP = false;\n this.LIGHTMAPDIRECTUV = 0;\n this.OBJECTSPACE_NORMALMAP = false;\n this.USELIGHTMAPASSHADOWMAP = false;\n this.REFLECTIONMAP_3D = false;\n this.REFLECTIONMAP_SPHERICAL = false;\n this.REFLECTIONMAP_PLANAR = false;\n this.REFLECTIONMAP_CUBIC = false;\n this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;\n this.USE_LOCAL_REFRACTIONMAP_CUBIC = false;\n this.REFLECTIONMAP_PROJECTION = false;\n this.REFLECTIONMAP_SKYBOX = false;\n this.REFLECTIONMAP_EXPLICIT = false;\n this.REFLECTIONMAP_EQUIRECTANGULAR = false;\n this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;\n this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;\n this.REFLECTIONMAP_OPPOSITEZ = false;\n this.INVERTCUBICMAP = false;\n this.LOGARITHMICDEPTH = false;\n this.REFRACTION = false;\n this.REFRACTIONMAP_3D = false;\n this.REFLECTIONOVERALPHA = false;\n this.TWOSIDEDLIGHTING = false;\n this.SHADOWFLOAT = false;\n this.MORPHTARGETS = false;\n this.MORPHTARGETS_NORMAL = false;\n this.MORPHTARGETS_TANGENT = false;\n this.MORPHTARGETS_UV = false;\n this.NUM_MORPH_INFLUENCERS = 0;\n this.MORPHTARGETS_TEXTURE = false;\n this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH\n this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7\n this.ALPHATEST_AFTERALLALPHACOMPUTATIONS = false;\n this.ALPHABLEND = true;\n this.PREPASS = false;\n this.PREPASS_IRRADIANCE = false;\n this.PREPASS_IRRADIANCE_INDEX = -1;\n this.PREPASS_ALBEDO_SQRT = false;\n this.PREPASS_ALBEDO_SQRT_INDEX = -1;\n this.PREPASS_DEPTH = false;\n this.PREPASS_DEPTH_INDEX = -1;\n this.PREPASS_NORMAL = false;\n this.PREPASS_NORMAL_INDEX = -1;\n this.PREPASS_POSITION = false;\n this.PREPASS_POSITION_INDEX = -1;\n this.PREPASS_VELOCITY = false;\n this.PREPASS_VELOCITY_INDEX = -1;\n this.PREPASS_REFLECTIVITY = false;\n this.PREPASS_REFLECTIVITY_INDEX = -1;\n this.SCENE_MRT_COUNT = 0;\n this.RGBDLIGHTMAP = false;\n this.RGBDREFLECTION = false;\n this.RGBDREFRACTION = false;\n this.IMAGEPROCESSING = false;\n this.VIGNETTE = false;\n this.VIGNETTEBLENDMODEMULTIPLY = false;\n this.VIGNETTEBLENDMODEOPAQUE = false;\n this.TONEMAPPING = false;\n this.TONEMAPPING_ACES = false;\n this.CONTRAST = false;\n this.COLORCURVES = false;\n this.COLORGRADING = false;\n this.COLORGRADING3D = false;\n this.SAMPLER3DGREENDEPTH = false;\n this.SAMPLER3DBGRMAP = false;\n this.DITHER = false;\n this.IMAGEPROCESSINGPOSTPROCESS = false;\n this.SKIPFINALCOLORCLAMP = false;\n this.MULTIVIEW = false;\n this.ORDER_INDEPENDENT_TRANSPARENCY = false;\n this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS = false;\n this.CAMERA_ORTHOGRAPHIC = false;\n this.CAMERA_PERSPECTIVE = false;\n /**\n * If the reflection texture on this material is in linear color space\n * @internal\n */\n this.IS_REFLECTION_LINEAR = false;\n /**\n * If the refraction texture on this material is in linear color space\n * @internal\n */\n this.IS_REFRACTION_LINEAR = false;\n this.EXPOSURE = false;\n this.rebuild();\n }\n setReflectionMode(modeToEnable) {\n const modes = [\n \"REFLECTIONMAP_CUBIC\",\n \"REFLECTIONMAP_EXPLICIT\",\n \"REFLECTIONMAP_PLANAR\",\n \"REFLECTIONMAP_PROJECTION\",\n \"REFLECTIONMAP_PROJECTION\",\n \"REFLECTIONMAP_SKYBOX\",\n \"REFLECTIONMAP_SPHERICAL\",\n \"REFLECTIONMAP_EQUIRECTANGULAR\",\n \"REFLECTIONMAP_EQUIRECTANGULAR_FIXED\",\n \"REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\",\n ];\n for (const mode of modes) {\n this[mode] = mode === modeToEnable;\n }\n }\n}\n/**\n * This is the default material used in Babylon. It is the best trade off between quality\n * and performances.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction\n */\nexport class StandardMaterial extends PushMaterial {\n /**\n * Gets the image processing configuration used either in this material.\n */\n get imageProcessingConfiguration() {\n return this._imageProcessingConfiguration;\n }\n /**\n * Sets the Default image processing configuration used either in the this material.\n *\n * If sets to null, the scene one is in use.\n */\n set imageProcessingConfiguration(value) {\n this._attachImageProcessingConfiguration(value);\n // Ensure the effect will be rebuilt.\n this._markAllSubMeshesAsTexturesDirty();\n }\n /**\n * Attaches a new image processing configuration to the Standard Material.\n * @param configuration\n */\n _attachImageProcessingConfiguration(configuration) {\n if (configuration === this._imageProcessingConfiguration) {\n return;\n }\n // Detaches observer\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n // Pick the scene configuration if needed\n if (!configuration) {\n this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;\n }\n else {\n this._imageProcessingConfiguration = configuration;\n }\n // Attaches observer\n if (this._imageProcessingConfiguration) {\n this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => {\n this._markAllSubMeshesAsImageProcessingDirty();\n });\n }\n }\n /**\n * Can this material render to prepass\n */\n get isPrePassCapable() {\n return !this.disableDepthWrite;\n }\n /**\n * Gets whether the color curves effect is enabled.\n */\n get cameraColorCurvesEnabled() {\n return this.imageProcessingConfiguration.colorCurvesEnabled;\n }\n /**\n * Sets whether the color curves effect is enabled.\n */\n set cameraColorCurvesEnabled(value) {\n this.imageProcessingConfiguration.colorCurvesEnabled = value;\n }\n /**\n * Gets whether the color grading effect is enabled.\n */\n get cameraColorGradingEnabled() {\n return this.imageProcessingConfiguration.colorGradingEnabled;\n }\n /**\n * Gets whether the color grading effect is enabled.\n */\n set cameraColorGradingEnabled(value) {\n this.imageProcessingConfiguration.colorGradingEnabled = value;\n }\n /**\n * Gets whether tonemapping is enabled or not.\n */\n get cameraToneMappingEnabled() {\n return this._imageProcessingConfiguration.toneMappingEnabled;\n }\n /**\n * Sets whether tonemapping is enabled or not\n */\n set cameraToneMappingEnabled(value) {\n this._imageProcessingConfiguration.toneMappingEnabled = value;\n }\n /**\n * The camera exposure used on this material.\n * This property is here and not in the camera to allow controlling exposure without full screen post process.\n * This corresponds to a photographic exposure.\n */\n get cameraExposure() {\n return this._imageProcessingConfiguration.exposure;\n }\n /**\n * The camera exposure used on this material.\n * This property is here and not in the camera to allow controlling exposure without full screen post process.\n * This corresponds to a photographic exposure.\n */\n set cameraExposure(value) {\n this._imageProcessingConfiguration.exposure = value;\n }\n /**\n * Gets The camera contrast used on this material.\n */\n get cameraContrast() {\n return this._imageProcessingConfiguration.contrast;\n }\n /**\n * Sets The camera contrast used on this material.\n */\n set cameraContrast(value) {\n this._imageProcessingConfiguration.contrast = value;\n }\n /**\n * Gets the Color Grading 2D Lookup Texture.\n */\n get cameraColorGradingTexture() {\n return this._imageProcessingConfiguration.colorGradingTexture;\n }\n /**\n * Sets the Color Grading 2D Lookup Texture.\n */\n set cameraColorGradingTexture(value) {\n this._imageProcessingConfiguration.colorGradingTexture = value;\n }\n /**\n * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\n get cameraColorCurves() {\n return this._imageProcessingConfiguration.colorCurves;\n }\n /**\n * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\n set cameraColorCurves(value) {\n this._imageProcessingConfiguration.colorCurves = value;\n }\n /**\n * Can this material render to several textures at once\n */\n get canRenderToMRT() {\n return true;\n }\n /**\n * Instantiates a new standard material.\n * This is the default material used in Babylon. It is the best trade off between quality\n * and performances.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction\n * @param name Define the name of the material in the scene\n * @param scene Define the scene the material belong to\n */\n constructor(name, scene) {\n super(name, scene);\n this._diffuseTexture = null;\n this._ambientTexture = null;\n this._opacityTexture = null;\n this._reflectionTexture = null;\n this._emissiveTexture = null;\n this._specularTexture = null;\n this._bumpTexture = null;\n this._lightmapTexture = null;\n this._refractionTexture = null;\n /**\n * The color of the material lit by the environmental background lighting.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction#ambient-color-example\n */\n this.ambientColor = new Color3(0, 0, 0);\n /**\n * The basic color of the material as viewed under a light.\n */\n this.diffuseColor = new Color3(1, 1, 1);\n /**\n * Define how the color and intensity of the highlight given by the light in the material.\n */\n this.specularColor = new Color3(1, 1, 1);\n /**\n * Define the color of the material as if self lit.\n * This will be mixed in the final result even in the absence of light.\n */\n this.emissiveColor = new Color3(0, 0, 0);\n /**\n * Defines how sharp are the highlights in the material.\n * The bigger the value the sharper giving a more glossy feeling to the result.\n * Reversely, the smaller the value the blurrier giving a more rough feeling to the result.\n */\n this.specularPower = 64;\n this._useAlphaFromDiffuseTexture = false;\n this._useEmissiveAsIllumination = false;\n this._linkEmissiveWithDiffuse = false;\n this._useSpecularOverAlpha = false;\n this._useReflectionOverAlpha = false;\n this._disableLighting = false;\n this._useObjectSpaceNormalMap = false;\n this._useParallax = false;\n this._useParallaxOcclusion = false;\n /**\n * Apply a scaling factor that determine which \"depth\" the height map should reprensent. A value between 0.05 and 0.1 is reasonnable in Parallax, you can reach 0.2 using Parallax Occlusion.\n */\n this.parallaxScaleBias = 0.05;\n this._roughness = 0;\n /**\n * In case of refraction, define the value of the index of refraction.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#how-to-obtain-reflections-and-refractions\n */\n this.indexOfRefraction = 0.98;\n /**\n * Invert the refraction texture alongside the y axis.\n * It can be useful with procedural textures or probe for instance.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#how-to-obtain-reflections-and-refractions\n */\n this.invertRefractionY = true;\n /**\n * Defines the alpha limits in alpha test mode.\n */\n this.alphaCutOff = 0.4;\n this._useLightmapAsShadowmap = false;\n this._useReflectionFresnelFromSpecular = false;\n this._useGlossinessFromSpecularMapAlpha = false;\n this._maxSimultaneousLights = 4;\n this._invertNormalMapX = false;\n this._invertNormalMapY = false;\n this._twoSidedLighting = false;\n this._renderTargets = new SmartArray(16);\n this._worldViewProjectionMatrix = Matrix.Zero();\n this._globalAmbientColor = new Color3(0, 0, 0);\n this._cacheHasRenderTargetTextures = false;\n this.detailMap = new DetailMapConfiguration(this);\n // Setup the default processing configuration to the scene.\n this._attachImageProcessingConfiguration(null);\n this.prePassConfiguration = new PrePassConfiguration();\n this.getRenderTargetTextures = () => {\n this._renderTargets.reset();\n if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {\n this._renderTargets.push(this._reflectionTexture);\n }\n if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {\n this._renderTargets.push(this._refractionTexture);\n }\n this._eventInfo.renderTargets = this._renderTargets;\n this._callbackPluginEventFillRenderTargetTextures(this._eventInfo);\n return this._renderTargets;\n };\n }\n /**\n * Gets a boolean indicating that current material needs to register RTT\n */\n get hasRenderTargetTextures() {\n if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {\n return true;\n }\n if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {\n return true;\n }\n return this._cacheHasRenderTargetTextures;\n }\n /**\n * Gets the current class name of the material e.g. \"StandardMaterial\"\n * Mainly use in serialization.\n * @returns the class name\n */\n getClassName() {\n return \"StandardMaterial\";\n }\n /**\n * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes)\n * You can try switching to logarithmic depth.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/logarithmicDepthBuffer\n */\n get useLogarithmicDepth() {\n return this._useLogarithmicDepth;\n }\n set useLogarithmicDepth(value) {\n this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;\n this._markAllSubMeshesAsMiscDirty();\n }\n /**\n * Specifies if the material will require alpha blending\n * @returns a boolean specifying if alpha blending is needed\n */\n needAlphaBlending() {\n if (this._disableAlphaBlending) {\n return false;\n }\n return (this.alpha < 1.0 ||\n this._opacityTexture != null ||\n this._shouldUseAlphaFromDiffuseTexture() ||\n (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled));\n }\n /**\n * Specifies if this material should be rendered in alpha test mode\n * @returns a boolean specifying if an alpha test is needed.\n */\n needAlphaTesting() {\n if (this._forceAlphaTest) {\n return true;\n }\n return this._hasAlphaChannel() && (this._transparencyMode == null || this._transparencyMode === Material.MATERIAL_ALPHATEST);\n }\n /**\n * Specifies whether or not the alpha value of the diffuse texture should be used for alpha blending.\n */\n _shouldUseAlphaFromDiffuseTexture() {\n return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture && this._transparencyMode !== Material.MATERIAL_OPAQUE;\n }\n /**\n * Specifies whether or not there is a usable alpha channel for transparency.\n */\n _hasAlphaChannel() {\n return (this._diffuseTexture != null && this._diffuseTexture.hasAlpha) || this._opacityTexture != null;\n }\n /**\n * Get the texture used for alpha test purpose.\n * @returns the diffuse texture in case of the standard material.\n */\n getAlphaTestTexture() {\n return this._diffuseTexture;\n }\n /**\n * Get if the submesh is ready to be used and all its information available.\n * Child classes can use it to update shaders\n * @param mesh defines the mesh to check\n * @param subMesh defines which submesh to check\n * @param useInstances specifies that instances should be used\n * @returns a boolean indicating that the submesh is ready or not\n */\n isReadyForSubMesh(mesh, subMesh, useInstances = false) {\n if (!this._uniformBufferLayoutBuilt) {\n this.buildUniformLayout();\n }\n if (subMesh.effect && this.isFrozen) {\n if (subMesh.effect._wasPreviouslyReady && subMesh.effect._wasPreviouslyUsingInstances === useInstances) {\n return true;\n }\n }\n if (!subMesh.materialDefines) {\n this._callbackPluginEventGeneric(MaterialPluginEvent.GetDefineNames, this._eventInfo);\n subMesh.materialDefines = new StandardMaterialDefines(this._eventInfo.defineNames);\n }\n const scene = this.getScene();\n const defines = subMesh.materialDefines;\n if (this._isReadyForSubMesh(subMesh)) {\n return true;\n }\n const engine = scene.getEngine();\n // Lights\n defines._needNormals = MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);\n // Multiview\n MaterialHelper.PrepareDefinesForMultiview(scene, defines);\n // PrePass\n const oit = this.needAlphaBlendingForMesh(mesh) && this.getScene().useOrderIndependentTransparency;\n MaterialHelper.PrepareDefinesForPrePass(scene, defines, this.canRenderToMRT && !oit);\n // Order independant transparency\n MaterialHelper.PrepareDefinesForOIT(scene, defines, oit);\n // Textures\n if (defines._areTexturesDirty) {\n this._eventInfo.hasRenderTargetTextures = false;\n this._callbackPluginEventHasRenderTargetTextures(this._eventInfo);\n this._cacheHasRenderTargetTextures = this._eventInfo.hasRenderTargetTextures;\n defines._needUVs = false;\n for (let i = 1; i <= 6; ++i) {\n defines[\"MAINUV\" + i] = false;\n }\n if (scene.texturesEnabled) {\n defines.DIFFUSEDIRECTUV = 0;\n defines.BUMPDIRECTUV = 0;\n defines.AMBIENTDIRECTUV = 0;\n defines.OPACITYDIRECTUV = 0;\n defines.EMISSIVEDIRECTUV = 0;\n defines.SPECULARDIRECTUV = 0;\n defines.LIGHTMAPDIRECTUV = 0;\n if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {\n if (!this._diffuseTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, \"DIFFUSE\");\n }\n }\n else {\n defines.DIFFUSE = false;\n }\n if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {\n if (!this._ambientTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, \"AMBIENT\");\n }\n }\n else {\n defines.AMBIENT = false;\n }\n if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {\n if (!this._opacityTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, \"OPACITY\");\n defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;\n }\n }\n else {\n defines.OPACITY = false;\n }\n if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {\n if (!this._reflectionTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n defines._needNormals = true;\n defines.REFLECTION = true;\n defines.ROUGHNESS = this._roughness > 0;\n defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;\n defines.INVERTCUBICMAP = this._reflectionTexture.coordinatesMode === Texture.INVCUBIC_MODE;\n defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;\n defines.REFLECTIONMAP_OPPOSITEZ =\n defines.REFLECTIONMAP_3D && this.getScene().useRightHandedSystem ? !this._reflectionTexture.invertZ : this._reflectionTexture.invertZ;\n defines.RGBDREFLECTION = this._reflectionTexture.isRGBD;\n switch (this._reflectionTexture.coordinatesMode) {\n case Texture.EXPLICIT_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_EXPLICIT\");\n break;\n case Texture.PLANAR_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_PLANAR\");\n break;\n case Texture.PROJECTION_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_PROJECTION\");\n break;\n case Texture.SKYBOX_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_SKYBOX\");\n break;\n case Texture.SPHERICAL_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_SPHERICAL\");\n break;\n case Texture.EQUIRECTANGULAR_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_EQUIRECTANGULAR\");\n break;\n case Texture.FIXED_EQUIRECTANGULAR_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_EQUIRECTANGULAR_FIXED\");\n break;\n case Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\");\n break;\n case Texture.CUBIC_MODE:\n case Texture.INVCUBIC_MODE:\n default:\n defines.setReflectionMode(\"REFLECTIONMAP_CUBIC\");\n break;\n }\n defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;\n }\n }\n else {\n defines.REFLECTION = false;\n defines.REFLECTIONMAP_OPPOSITEZ = false;\n }\n if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {\n if (!this._emissiveTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, \"EMISSIVE\");\n }\n }\n else {\n defines.EMISSIVE = false;\n }\n if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {\n if (!this._lightmapTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, \"LIGHTMAP\");\n defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;\n defines.RGBDLIGHTMAP = this._lightmapTexture.isRGBD;\n }\n }\n else {\n defines.LIGHTMAP = false;\n }\n if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {\n if (!this._specularTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, \"SPECULAR\");\n defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;\n }\n }\n else {\n defines.SPECULAR = false;\n }\n if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {\n // Bump texture can not be not blocking.\n if (!this._bumpTexture.isReady()) {\n return false;\n }\n else {\n MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, \"BUMP\");\n defines.PARALLAX = this._useParallax;\n defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;\n }\n defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;\n }\n else {\n defines.BUMP = false;\n defines.PARALLAX = false;\n defines.PARALLAXOCCLUSION = false;\n }\n if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {\n if (!this._refractionTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n defines._needUVs = true;\n defines.REFRACTION = true;\n defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;\n defines.RGBDREFRACTION = this._refractionTexture.isRGBD;\n defines.USE_LOCAL_REFRACTIONMAP_CUBIC = this._refractionTexture.boundingBoxSize ? true : false;\n }\n }\n else {\n defines.REFRACTION = false;\n }\n defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;\n }\n else {\n defines.DIFFUSE = false;\n defines.AMBIENT = false;\n defines.OPACITY = false;\n defines.REFLECTION = false;\n defines.EMISSIVE = false;\n defines.LIGHTMAP = false;\n defines.BUMP = false;\n defines.REFRACTION = false;\n }\n defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();\n defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;\n defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;\n defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;\n defines.PREMULTIPLYALPHA = this.alphaMode === 7 || this.alphaMode === 8;\n defines.ALPHATEST_AFTERALLALPHACOMPUTATIONS = this.transparencyMode !== null;\n defines.ALPHABLEND = this.transparencyMode === null || this.needAlphaBlendingForMesh(mesh); // check on null for backward compatibility\n }\n this._eventInfo.isReadyForSubMesh = true;\n this._eventInfo.defines = defines;\n this._eventInfo.subMesh = subMesh;\n this._callbackPluginEventIsReadyForSubMesh(this._eventInfo);\n if (!this._eventInfo.isReadyForSubMesh) {\n return false;\n }\n if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {\n if (!this._imageProcessingConfiguration.isReady()) {\n return false;\n }\n this._imageProcessingConfiguration.prepareDefines(defines);\n defines.IS_REFLECTION_LINEAR = this.reflectionTexture != null && !this.reflectionTexture.gammaSpace;\n defines.IS_REFRACTION_LINEAR = this.refractionTexture != null && !this.refractionTexture.gammaSpace;\n }\n if (defines._areFresnelDirty) {\n if (StandardMaterial.FresnelEnabled) {\n // Fresnel\n if (this._diffuseFresnelParameters ||\n this._opacityFresnelParameters ||\n this._emissiveFresnelParameters ||\n this._refractionFresnelParameters ||\n this._reflectionFresnelParameters) {\n defines.DIFFUSEFRESNEL = this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled;\n defines.OPACITYFRESNEL = this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;\n defines.REFLECTIONFRESNEL = this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled;\n defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;\n defines.REFRACTIONFRESNEL = this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled;\n defines.EMISSIVEFRESNEL = this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled;\n defines._needNormals = true;\n defines.FRESNEL = true;\n }\n }\n else {\n defines.FRESNEL = false;\n }\n }\n // Misc.\n MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);\n // Values that need to be evaluated on every frame\n MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, this, defines, useInstances, null, subMesh.getRenderingMesh().hasThinInstances);\n // External config\n this._eventInfo.defines = defines;\n this._eventInfo.mesh = mesh;\n this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo);\n // Attribs\n MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);\n // External config\n this._callbackPluginEventPrepareDefines(this._eventInfo);\n // Get correct effect\n let forceWasNotReadyPreviously = false;\n if (defines.isDirty) {\n const lightDisposed = defines._areLightsDisposed;\n defines.markAsProcessed();\n // Fallbacks\n const fallbacks = new EffectFallbacks();\n if (defines.REFLECTION) {\n fallbacks.addFallback(0, \"REFLECTION\");\n }\n if (defines.SPECULAR) {\n fallbacks.addFallback(0, \"SPECULAR\");\n }\n if (defines.BUMP) {\n fallbacks.addFallback(0, \"BUMP\");\n }\n if (defines.PARALLAX) {\n fallbacks.addFallback(1, \"PARALLAX\");\n }\n if (defines.PARALLAXOCCLUSION) {\n fallbacks.addFallback(0, \"PARALLAXOCCLUSION\");\n }\n if (defines.SPECULAROVERALPHA) {\n fallbacks.addFallback(0, \"SPECULAROVERALPHA\");\n }\n if (defines.FOG) {\n fallbacks.addFallback(1, \"FOG\");\n }\n if (defines.POINTSIZE) {\n fallbacks.addFallback(0, \"POINTSIZE\");\n }\n if (defines.LOGARITHMICDEPTH) {\n fallbacks.addFallback(0, \"LOGARITHMICDEPTH\");\n }\n MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);\n if (defines.SPECULARTERM) {\n fallbacks.addFallback(0, \"SPECULARTERM\");\n }\n if (defines.DIFFUSEFRESNEL) {\n fallbacks.addFallback(1, \"DIFFUSEFRESNEL\");\n }\n if (defines.OPACITYFRESNEL) {\n fallbacks.addFallback(2, \"OPACITYFRESNEL\");\n }\n if (defines.REFLECTIONFRESNEL) {\n fallbacks.addFallback(3, \"REFLECTIONFRESNEL\");\n }\n if (defines.EMISSIVEFRESNEL) {\n fallbacks.addFallback(4, \"EMISSIVEFRESNEL\");\n }\n if (defines.FRESNEL) {\n fallbacks.addFallback(4, \"FRESNEL\");\n }\n if (defines.MULTIVIEW) {\n fallbacks.addFallback(0, \"MULTIVIEW\");\n }\n //Attributes\n const attribs = [VertexBuffer.PositionKind];\n if (defines.NORMAL) {\n attribs.push(VertexBuffer.NormalKind);\n }\n if (defines.TANGENT) {\n attribs.push(VertexBuffer.TangentKind);\n }\n for (let i = 1; i <= 6; ++i) {\n if (defines[\"UV\" + i]) {\n attribs.push(`uv${i === 1 ? \"\" : i}`);\n }\n }\n if (defines.VERTEXCOLOR) {\n attribs.push(VertexBuffer.ColorKind);\n }\n MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);\n MaterialHelper.PrepareAttributesForInstances(attribs, defines);\n MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);\n MaterialHelper.PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines);\n let shaderName = \"default\";\n const uniforms = [\n \"world\",\n \"view\",\n \"viewProjection\",\n \"vEyePosition\",\n \"vLightsType\",\n \"vAmbientColor\",\n \"vDiffuseColor\",\n \"vSpecularColor\",\n \"vEmissiveColor\",\n \"visibility\",\n \"vFogInfos\",\n \"vFogColor\",\n \"pointSize\",\n \"vDiffuseInfos\",\n \"vAmbientInfos\",\n \"vOpacityInfos\",\n \"vReflectionInfos\",\n \"vEmissiveInfos\",\n \"vSpecularInfos\",\n \"vBumpInfos\",\n \"vLightmapInfos\",\n \"vRefractionInfos\",\n \"mBones\",\n \"diffuseMatrix\",\n \"ambientMatrix\",\n \"opacityMatrix\",\n \"reflectionMatrix\",\n \"emissiveMatrix\",\n \"specularMatrix\",\n \"bumpMatrix\",\n \"normalMatrix\",\n \"lightmapMatrix\",\n \"refractionMatrix\",\n \"diffuseLeftColor\",\n \"diffuseRightColor\",\n \"opacityParts\",\n \"reflectionLeftColor\",\n \"reflectionRightColor\",\n \"emissiveLeftColor\",\n \"emissiveRightColor\",\n \"refractionLeftColor\",\n \"refractionRightColor\",\n \"vReflectionPosition\",\n \"vReflectionSize\",\n \"vRefractionPosition\",\n \"vRefractionSize\",\n \"logarithmicDepthConstant\",\n \"vTangentSpaceParams\",\n \"alphaCutOff\",\n \"boneTextureWidth\",\n \"morphTargetTextureInfo\",\n \"morphTargetTextureIndices\",\n ];\n const samplers = [\n \"diffuseSampler\",\n \"ambientSampler\",\n \"opacitySampler\",\n \"reflectionCubeSampler\",\n \"reflection2DSampler\",\n \"emissiveSampler\",\n \"specularSampler\",\n \"bumpSampler\",\n \"lightmapSampler\",\n \"refractionCubeSampler\",\n \"refraction2DSampler\",\n \"boneSampler\",\n \"morphTargets\",\n \"oitDepthSampler\",\n \"oitFrontColorSampler\",\n ];\n const uniformBuffers = [\"Material\", \"Scene\", \"Mesh\"];\n this._eventInfo.fallbacks = fallbacks;\n this._eventInfo.fallbackRank = 0;\n this._eventInfo.defines = defines;\n this._eventInfo.uniforms = uniforms;\n this._eventInfo.attributes = attribs;\n this._eventInfo.samplers = samplers;\n this._eventInfo.uniformBuffersNames = uniformBuffers;\n this._eventInfo.customCode = undefined;\n this._eventInfo.mesh = mesh;\n this._callbackPluginEventGeneric(MaterialPluginEvent.PrepareEffect, this._eventInfo);\n PrePassConfiguration.AddUniforms(uniforms);\n PrePassConfiguration.AddSamplers(samplers);\n if (ImageProcessingConfiguration) {\n ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);\n ImageProcessingConfiguration.PrepareSamplers(samplers, defines);\n }\n MaterialHelper.PrepareUniformsAndSamplersList({\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: defines,\n maxSimultaneousLights: this._maxSimultaneousLights,\n });\n addClipPlaneUniforms(uniforms);\n const csnrOptions = {};\n if (this.customShaderNameResolve) {\n shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines, attribs, csnrOptions);\n }\n const join = defines.toString();\n const previousEffect = subMesh.effect;\n let effect = scene.getEngine().createEffect(shaderName, {\n attributes: attribs,\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: join,\n fallbacks: fallbacks,\n onCompiled: this.onCompiled,\n onError: this.onError,\n indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS },\n processFinalCode: csnrOptions.processFinalCode,\n processCodeAfterIncludes: this._eventInfo.customCode,\n multiTarget: defines.PREPASS,\n }, engine);\n this._eventInfo.customCode = undefined;\n if (effect) {\n if (this._onEffectCreatedObservable) {\n onCreatedEffectParameters.effect = effect;\n onCreatedEffectParameters.subMesh = subMesh;\n this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters);\n }\n // Use previous effect while new one is compiling\n if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {\n effect = previousEffect;\n defines.markAsUnprocessed();\n forceWasNotReadyPreviously = this.isFrozen;\n if (lightDisposed) {\n // re register in case it takes more than one frame.\n defines._areLightsDisposed = true;\n return false;\n }\n }\n else {\n scene.resetCachedMaterial();\n subMesh.setEffect(effect, defines, this._materialContext);\n }\n }\n }\n if (!subMesh.effect || !subMesh.effect.isReady()) {\n return false;\n }\n defines._renderId = scene.getRenderId();\n subMesh.effect._wasPreviouslyReady = forceWasNotReadyPreviously ? false : true;\n subMesh.effect._wasPreviouslyUsingInstances = useInstances;\n this._checkScenePerformancePriority();\n return true;\n }\n /**\n * Builds the material UBO layouts.\n * Used internally during the effect preparation.\n */\n buildUniformLayout() {\n // Order is important !\n const ubo = this._uniformBuffer;\n ubo.addUniform(\"diffuseLeftColor\", 4);\n ubo.addUniform(\"diffuseRightColor\", 4);\n ubo.addUniform(\"opacityParts\", 4);\n ubo.addUniform(\"reflectionLeftColor\", 4);\n ubo.addUniform(\"reflectionRightColor\", 4);\n ubo.addUniform(\"refractionLeftColor\", 4);\n ubo.addUniform(\"refractionRightColor\", 4);\n ubo.addUniform(\"emissiveLeftColor\", 4);\n ubo.addUniform(\"emissiveRightColor\", 4);\n ubo.addUniform(\"vDiffuseInfos\", 2);\n ubo.addUniform(\"vAmbientInfos\", 2);\n ubo.addUniform(\"vOpacityInfos\", 2);\n ubo.addUniform(\"vReflectionInfos\", 2);\n ubo.addUniform(\"vReflectionPosition\", 3);\n ubo.addUniform(\"vReflectionSize\", 3);\n ubo.addUniform(\"vEmissiveInfos\", 2);\n ubo.addUniform(\"vLightmapInfos\", 2);\n ubo.addUniform(\"vSpecularInfos\", 2);\n ubo.addUniform(\"vBumpInfos\", 3);\n ubo.addUniform(\"diffuseMatrix\", 16);\n ubo.addUniform(\"ambientMatrix\", 16);\n ubo.addUniform(\"opacityMatrix\", 16);\n ubo.addUniform(\"reflectionMatrix\", 16);\n ubo.addUniform(\"emissiveMatrix\", 16);\n ubo.addUniform(\"lightmapMatrix\", 16);\n ubo.addUniform(\"specularMatrix\", 16);\n ubo.addUniform(\"bumpMatrix\", 16);\n ubo.addUniform(\"vTangentSpaceParams\", 2);\n ubo.addUniform(\"pointSize\", 1);\n ubo.addUniform(\"alphaCutOff\", 1);\n ubo.addUniform(\"refractionMatrix\", 16);\n ubo.addUniform(\"vRefractionInfos\", 4);\n ubo.addUniform(\"vRefractionPosition\", 3);\n ubo.addUniform(\"vRefractionSize\", 3);\n ubo.addUniform(\"vSpecularColor\", 4);\n ubo.addUniform(\"vEmissiveColor\", 3);\n ubo.addUniform(\"vDiffuseColor\", 4);\n ubo.addUniform(\"vAmbientColor\", 3);\n super.buildUniformLayout();\n }\n /**\n * Binds the submesh to this material by preparing the effect and shader to draw\n * @param world defines the world transformation matrix\n * @param mesh defines the mesh containing the submesh\n * @param subMesh defines the submesh to bind the material to\n */\n bindForSubMesh(world, mesh, subMesh) {\n var _a;\n const scene = this.getScene();\n const defines = subMesh.materialDefines;\n if (!defines) {\n return;\n }\n const effect = subMesh.effect;\n if (!effect) {\n return;\n }\n this._activeEffect = effect;\n // Matrices Mesh.\n mesh.getMeshUniformBuffer().bindToEffect(effect, \"Mesh\");\n mesh.transferToEffect(world);\n // Binding unconditionally\n this._uniformBuffer.bindToEffect(effect, \"Material\");\n this.prePassConfiguration.bindForSubMesh(this._activeEffect, scene, mesh, world, this.isFrozen);\n this._eventInfo.subMesh = subMesh;\n this._callbackPluginEventHardBindForSubMesh(this._eventInfo);\n // Normal Matrix\n if (defines.OBJECTSPACE_NORMALMAP) {\n world.toNormalMatrix(this._normalMatrix);\n this.bindOnlyNormalMatrix(this._normalMatrix);\n }\n const mustRebind = effect._forceRebindOnNextCall || this._mustRebind(scene, effect, mesh.visibility);\n // Bones\n MaterialHelper.BindBonesParameters(mesh, effect);\n const ubo = this._uniformBuffer;\n if (mustRebind) {\n this.bindViewProjection(effect);\n if (!ubo.useUbo || !this.isFrozen || !ubo.isSync || effect._forceRebindOnNextCall) {\n if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {\n // Fresnel\n if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {\n ubo.updateColor4(\"diffuseLeftColor\", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);\n ubo.updateColor4(\"diffuseRightColor\", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);\n }\n if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {\n ubo.updateColor4(\"opacityParts\", new Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);\n }\n if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {\n ubo.updateColor4(\"reflectionLeftColor\", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);\n ubo.updateColor4(\"reflectionRightColor\", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);\n }\n if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {\n ubo.updateColor4(\"refractionLeftColor\", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);\n ubo.updateColor4(\"refractionRightColor\", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);\n }\n if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {\n ubo.updateColor4(\"emissiveLeftColor\", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);\n ubo.updateColor4(\"emissiveRightColor\", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);\n }\n }\n // Textures\n if (scene.texturesEnabled) {\n if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {\n ubo.updateFloat2(\"vDiffuseInfos\", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);\n MaterialHelper.BindTextureMatrix(this._diffuseTexture, ubo, \"diffuse\");\n }\n if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {\n ubo.updateFloat2(\"vAmbientInfos\", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);\n MaterialHelper.BindTextureMatrix(this._ambientTexture, ubo, \"ambient\");\n }\n if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {\n ubo.updateFloat2(\"vOpacityInfos\", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);\n MaterialHelper.BindTextureMatrix(this._opacityTexture, ubo, \"opacity\");\n }\n if (this._hasAlphaChannel()) {\n ubo.updateFloat(\"alphaCutOff\", this.alphaCutOff);\n }\n if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {\n ubo.updateFloat2(\"vReflectionInfos\", this._reflectionTexture.level, this.roughness);\n ubo.updateMatrix(\"reflectionMatrix\", this._reflectionTexture.getReflectionTextureMatrix());\n if (this._reflectionTexture.boundingBoxSize) {\n const cubeTexture = this._reflectionTexture;\n ubo.updateVector3(\"vReflectionPosition\", cubeTexture.boundingBoxPosition);\n ubo.updateVector3(\"vReflectionSize\", cubeTexture.boundingBoxSize);\n }\n }\n if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {\n ubo.updateFloat2(\"vEmissiveInfos\", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);\n MaterialHelper.BindTextureMatrix(this._emissiveTexture, ubo, \"emissive\");\n }\n if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {\n ubo.updateFloat2(\"vLightmapInfos\", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);\n MaterialHelper.BindTextureMatrix(this._lightmapTexture, ubo, \"lightmap\");\n }\n if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {\n ubo.updateFloat2(\"vSpecularInfos\", this._specularTexture.coordinatesIndex, this._specularTexture.level);\n MaterialHelper.BindTextureMatrix(this._specularTexture, ubo, \"specular\");\n }\n if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {\n ubo.updateFloat3(\"vBumpInfos\", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);\n MaterialHelper.BindTextureMatrix(this._bumpTexture, ubo, \"bump\");\n if (scene._mirroredCameraPosition) {\n ubo.updateFloat2(\"vTangentSpaceParams\", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);\n }\n else {\n ubo.updateFloat2(\"vTangentSpaceParams\", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);\n }\n }\n if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {\n let depth = 1.0;\n if (!this._refractionTexture.isCube) {\n ubo.updateMatrix(\"refractionMatrix\", this._refractionTexture.getReflectionTextureMatrix());\n if (this._refractionTexture.depth) {\n depth = this._refractionTexture.depth;\n }\n }\n ubo.updateFloat4(\"vRefractionInfos\", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);\n if (this._refractionTexture.boundingBoxSize) {\n const cubeTexture = this._refractionTexture;\n ubo.updateVector3(\"vRefractionPosition\", cubeTexture.boundingBoxPosition);\n ubo.updateVector3(\"vRefractionSize\", cubeTexture.boundingBoxSize);\n }\n }\n }\n // Point size\n if (this.pointsCloud) {\n ubo.updateFloat(\"pointSize\", this.pointSize);\n }\n if (defines.SPECULARTERM) {\n ubo.updateColor4(\"vSpecularColor\", this.specularColor, this.specularPower);\n }\n ubo.updateColor3(\"vEmissiveColor\", StandardMaterial.EmissiveTextureEnabled ? this.emissiveColor : Color3.BlackReadOnly);\n ubo.updateColor4(\"vDiffuseColor\", this.diffuseColor, this.alpha);\n scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);\n ubo.updateColor3(\"vAmbientColor\", this._globalAmbientColor);\n }\n // Textures\n if (scene.texturesEnabled) {\n if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {\n effect.setTexture(\"diffuseSampler\", this._diffuseTexture);\n }\n if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {\n effect.setTexture(\"ambientSampler\", this._ambientTexture);\n }\n if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {\n effect.setTexture(\"opacitySampler\", this._opacityTexture);\n }\n if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {\n if (this._reflectionTexture.isCube) {\n effect.setTexture(\"reflectionCubeSampler\", this._reflectionTexture);\n }\n else {\n effect.setTexture(\"reflection2DSampler\", this._reflectionTexture);\n }\n }\n if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {\n effect.setTexture(\"emissiveSampler\", this._emissiveTexture);\n }\n if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {\n effect.setTexture(\"lightmapSampler\", this._lightmapTexture);\n }\n if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {\n effect.setTexture(\"specularSampler\", this._specularTexture);\n }\n if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {\n effect.setTexture(\"bumpSampler\", this._bumpTexture);\n }\n if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {\n if (this._refractionTexture.isCube) {\n effect.setTexture(\"refractionCubeSampler\", this._refractionTexture);\n }\n else {\n effect.setTexture(\"refraction2DSampler\", this._refractionTexture);\n }\n }\n }\n // OIT with depth peeling\n if (this.getScene().useOrderIndependentTransparency && this.needAlphaBlendingForMesh(mesh)) {\n this.getScene().depthPeelingRenderer.bind(effect);\n }\n this._eventInfo.subMesh = subMesh;\n this._callbackPluginEventBindForSubMesh(this._eventInfo);\n // Clip plane\n bindClipPlane(effect, this, scene);\n // Colors\n this.bindEyePosition(effect);\n }\n else if (scene.getEngine()._features.needToAlwaysBindUniformBuffers) {\n this._needToBindSceneUbo = true;\n }\n if (mustRebind || !this.isFrozen) {\n // Lights\n if (scene.lightsEnabled && !this._disableLighting) {\n MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);\n }\n // View\n if ((scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) ||\n this._reflectionTexture ||\n this._refractionTexture ||\n mesh.receiveShadows ||\n defines.PREPASS) {\n this.bindView(effect);\n }\n // Fog\n MaterialHelper.BindFogParameters(scene, mesh, effect);\n // Morph targets\n if (defines.NUM_MORPH_INFLUENCERS) {\n MaterialHelper.BindMorphTargetParameters(mesh, effect);\n }\n if (defines.BAKED_VERTEX_ANIMATION_TEXTURE) {\n (_a = mesh.bakedVertexAnimationManager) === null || _a === void 0 ? void 0 : _a.bind(effect, defines.INSTANCES);\n }\n // Log. depth\n if (this.useLogarithmicDepth) {\n MaterialHelper.BindLogDepth(defines, effect, scene);\n }\n // image processing\n if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {\n this._imageProcessingConfiguration.bind(this._activeEffect);\n }\n }\n this._afterBind(mesh, this._activeEffect);\n ubo.update();\n }\n /**\n * Get the list of animatables in the material.\n * @returns the list of animatables object used in the material\n */\n getAnimatables() {\n const results = super.getAnimatables();\n if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {\n results.push(this._diffuseTexture);\n }\n if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {\n results.push(this._ambientTexture);\n }\n if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {\n results.push(this._opacityTexture);\n }\n if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {\n results.push(this._reflectionTexture);\n }\n if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {\n results.push(this._emissiveTexture);\n }\n if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {\n results.push(this._specularTexture);\n }\n if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {\n results.push(this._bumpTexture);\n }\n if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {\n results.push(this._lightmapTexture);\n }\n if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {\n results.push(this._refractionTexture);\n }\n return results;\n }\n /**\n * Gets the active textures from the material\n * @returns an array of textures\n */\n getActiveTextures() {\n const activeTextures = super.getActiveTextures();\n if (this._diffuseTexture) {\n activeTextures.push(this._diffuseTexture);\n }\n if (this._ambientTexture) {\n activeTextures.push(this._ambientTexture);\n }\n if (this._opacityTexture) {\n activeTextures.push(this._opacityTexture);\n }\n if (this._reflectionTexture) {\n activeTextures.push(this._reflectionTexture);\n }\n if (this._emissiveTexture) {\n activeTextures.push(this._emissiveTexture);\n }\n if (this._specularTexture) {\n activeTextures.push(this._specularTexture);\n }\n if (this._bumpTexture) {\n activeTextures.push(this._bumpTexture);\n }\n if (this._lightmapTexture) {\n activeTextures.push(this._lightmapTexture);\n }\n if (this._refractionTexture) {\n activeTextures.push(this._refractionTexture);\n }\n return activeTextures;\n }\n /**\n * Specifies if the material uses a texture\n * @param texture defines the texture to check against the material\n * @returns a boolean specifying if the material uses the texture\n */\n hasTexture(texture) {\n if (super.hasTexture(texture)) {\n return true;\n }\n if (this._diffuseTexture === texture) {\n return true;\n }\n if (this._ambientTexture === texture) {\n return true;\n }\n if (this._opacityTexture === texture) {\n return true;\n }\n if (this._reflectionTexture === texture) {\n return true;\n }\n if (this._emissiveTexture === texture) {\n return true;\n }\n if (this._specularTexture === texture) {\n return true;\n }\n if (this._bumpTexture === texture) {\n return true;\n }\n if (this._lightmapTexture === texture) {\n return true;\n }\n if (this._refractionTexture === texture) {\n return true;\n }\n return false;\n }\n /**\n * Disposes the material\n * @param forceDisposeEffect specifies if effects should be forcefully disposed\n * @param forceDisposeTextures specifies if textures should be forcefully disposed\n */\n dispose(forceDisposeEffect, forceDisposeTextures) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j;\n if (forceDisposeTextures) {\n (_a = this._diffuseTexture) === null || _a === void 0 ? void 0 : _a.dispose();\n (_b = this._ambientTexture) === null || _b === void 0 ? void 0 : _b.dispose();\n (_c = this._opacityTexture) === null || _c === void 0 ? void 0 : _c.dispose();\n (_d = this._reflectionTexture) === null || _d === void 0 ? void 0 : _d.dispose();\n (_e = this._emissiveTexture) === null || _e === void 0 ? void 0 : _e.dispose();\n (_f = this._specularTexture) === null || _f === void 0 ? void 0 : _f.dispose();\n (_g = this._bumpTexture) === null || _g === void 0 ? void 0 : _g.dispose();\n (_h = this._lightmapTexture) === null || _h === void 0 ? void 0 : _h.dispose();\n (_j = this._refractionTexture) === null || _j === void 0 ? void 0 : _j.dispose();\n }\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n super.dispose(forceDisposeEffect, forceDisposeTextures);\n }\n /**\n * Makes a duplicate of the material, and gives it a new name\n * @param name defines the new name for the duplicated material\n * @param cloneTexturesOnlyOnce - if a texture is used in more than one channel (e.g diffuse and opacity), only clone it once and reuse it on the other channels. Default false.\n * @param rootUrl defines the root URL to use to load textures\n * @returns the cloned material\n */\n clone(name, cloneTexturesOnlyOnce = true, rootUrl = \"\") {\n const result = SerializationHelper.Clone(() => new StandardMaterial(name, this.getScene()), this, { cloneTexturesOnlyOnce });\n result.name = name;\n result.id = name;\n this.stencil.copyTo(result.stencil);\n this._clonePlugins(result, rootUrl);\n return result;\n }\n /**\n * Creates a standard material from parsed material data\n * @param source defines the JSON representation of the material\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @returns a new standard material\n */\n static Parse(source, scene, rootUrl) {\n const material = SerializationHelper.Parse(() => new StandardMaterial(source.name, scene), source, scene, rootUrl);\n if (source.stencil) {\n material.stencil.parse(source.stencil, scene, rootUrl);\n }\n Material._parsePlugins(source, material, scene, rootUrl);\n return material;\n }\n // Flags used to enable or disable a type of texture for all Standard Materials\n /**\n * Are diffuse textures enabled in the application.\n */\n static get DiffuseTextureEnabled() {\n return MaterialFlags.DiffuseTextureEnabled;\n }\n static set DiffuseTextureEnabled(value) {\n MaterialFlags.DiffuseTextureEnabled = value;\n }\n /**\n * Are detail textures enabled in the application.\n */\n static get DetailTextureEnabled() {\n return MaterialFlags.DetailTextureEnabled;\n }\n static set DetailTextureEnabled(value) {\n MaterialFlags.DetailTextureEnabled = value;\n }\n /**\n * Are ambient textures enabled in the application.\n */\n static get AmbientTextureEnabled() {\n return MaterialFlags.AmbientTextureEnabled;\n }\n static set AmbientTextureEnabled(value) {\n MaterialFlags.AmbientTextureEnabled = value;\n }\n /**\n * Are opacity textures enabled in the application.\n */\n static get OpacityTextureEnabled() {\n return MaterialFlags.OpacityTextureEnabled;\n }\n static set OpacityTextureEnabled(value) {\n MaterialFlags.OpacityTextureEnabled = value;\n }\n /**\n * Are reflection textures enabled in the application.\n */\n static get ReflectionTextureEnabled() {\n return MaterialFlags.ReflectionTextureEnabled;\n }\n static set ReflectionTextureEnabled(value) {\n MaterialFlags.ReflectionTextureEnabled = value;\n }\n /**\n * Are emissive textures enabled in the application.\n */\n static get EmissiveTextureEnabled() {\n return MaterialFlags.EmissiveTextureEnabled;\n }\n static set EmissiveTextureEnabled(value) {\n MaterialFlags.EmissiveTextureEnabled = value;\n }\n /**\n * Are specular textures enabled in the application.\n */\n static get SpecularTextureEnabled() {\n return MaterialFlags.SpecularTextureEnabled;\n }\n static set SpecularTextureEnabled(value) {\n MaterialFlags.SpecularTextureEnabled = value;\n }\n /**\n * Are bump textures enabled in the application.\n */\n static get BumpTextureEnabled() {\n return MaterialFlags.BumpTextureEnabled;\n }\n static set BumpTextureEnabled(value) {\n MaterialFlags.BumpTextureEnabled = value;\n }\n /**\n * Are lightmap textures enabled in the application.\n */\n static get LightmapTextureEnabled() {\n return MaterialFlags.LightmapTextureEnabled;\n }\n static set LightmapTextureEnabled(value) {\n MaterialFlags.LightmapTextureEnabled = value;\n }\n /**\n * Are refraction textures enabled in the application.\n */\n static get RefractionTextureEnabled() {\n return MaterialFlags.RefractionTextureEnabled;\n }\n static set RefractionTextureEnabled(value) {\n MaterialFlags.RefractionTextureEnabled = value;\n }\n /**\n * Are color grading textures enabled in the application.\n */\n static get ColorGradingTextureEnabled() {\n return MaterialFlags.ColorGradingTextureEnabled;\n }\n static set ColorGradingTextureEnabled(value) {\n MaterialFlags.ColorGradingTextureEnabled = value;\n }\n /**\n * Are fresnels enabled in the application.\n */\n static get FresnelEnabled() {\n return MaterialFlags.FresnelEnabled;\n }\n static set FresnelEnabled(value) {\n MaterialFlags.FresnelEnabled = value;\n }\n}\n__decorate([\n serializeAsTexture(\"diffuseTexture\")\n], StandardMaterial.prototype, \"_diffuseTexture\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesAndMiscDirty\")\n], StandardMaterial.prototype, \"diffuseTexture\", void 0);\n__decorate([\n serializeAsTexture(\"ambientTexture\")\n], StandardMaterial.prototype, \"_ambientTexture\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"ambientTexture\", void 0);\n__decorate([\n serializeAsTexture(\"opacityTexture\")\n], StandardMaterial.prototype, \"_opacityTexture\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesAndMiscDirty\")\n], StandardMaterial.prototype, \"opacityTexture\", void 0);\n__decorate([\n serializeAsTexture(\"reflectionTexture\")\n], StandardMaterial.prototype, \"_reflectionTexture\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"reflectionTexture\", void 0);\n__decorate([\n serializeAsTexture(\"emissiveTexture\")\n], StandardMaterial.prototype, \"_emissiveTexture\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"emissiveTexture\", void 0);\n__decorate([\n serializeAsTexture(\"specularTexture\")\n], StandardMaterial.prototype, \"_specularTexture\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"specularTexture\", void 0);\n__decorate([\n serializeAsTexture(\"bumpTexture\")\n], StandardMaterial.prototype, \"_bumpTexture\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"bumpTexture\", void 0);\n__decorate([\n serializeAsTexture(\"lightmapTexture\")\n], StandardMaterial.prototype, \"_lightmapTexture\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"lightmapTexture\", void 0);\n__decorate([\n serializeAsTexture(\"refractionTexture\")\n], StandardMaterial.prototype, \"_refractionTexture\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"refractionTexture\", void 0);\n__decorate([\n serializeAsColor3(\"ambient\")\n], StandardMaterial.prototype, \"ambientColor\", void 0);\n__decorate([\n serializeAsColor3(\"diffuse\")\n], StandardMaterial.prototype, \"diffuseColor\", void 0);\n__decorate([\n serializeAsColor3(\"specular\")\n], StandardMaterial.prototype, \"specularColor\", void 0);\n__decorate([\n serializeAsColor3(\"emissive\")\n], StandardMaterial.prototype, \"emissiveColor\", void 0);\n__decorate([\n serialize()\n], StandardMaterial.prototype, \"specularPower\", void 0);\n__decorate([\n serialize(\"useAlphaFromDiffuseTexture\")\n], StandardMaterial.prototype, \"_useAlphaFromDiffuseTexture\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesAndMiscDirty\")\n], StandardMaterial.prototype, \"useAlphaFromDiffuseTexture\", void 0);\n__decorate([\n serialize(\"useEmissiveAsIllumination\")\n], StandardMaterial.prototype, \"_useEmissiveAsIllumination\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"useEmissiveAsIllumination\", void 0);\n__decorate([\n serialize(\"linkEmissiveWithDiffuse\")\n], StandardMaterial.prototype, \"_linkEmissiveWithDiffuse\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"linkEmissiveWithDiffuse\", void 0);\n__decorate([\n serialize(\"useSpecularOverAlpha\")\n], StandardMaterial.prototype, \"_useSpecularOverAlpha\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"useSpecularOverAlpha\", void 0);\n__decorate([\n serialize(\"useReflectionOverAlpha\")\n], StandardMaterial.prototype, \"_useReflectionOverAlpha\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"useReflectionOverAlpha\", void 0);\n__decorate([\n serialize(\"disableLighting\")\n], StandardMaterial.prototype, \"_disableLighting\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n], StandardMaterial.prototype, \"disableLighting\", void 0);\n__decorate([\n serialize(\"useObjectSpaceNormalMap\")\n], StandardMaterial.prototype, \"_useObjectSpaceNormalMap\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"useObjectSpaceNormalMap\", void 0);\n__decorate([\n serialize(\"useParallax\")\n], StandardMaterial.prototype, \"_useParallax\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"useParallax\", void 0);\n__decorate([\n serialize(\"useParallaxOcclusion\")\n], StandardMaterial.prototype, \"_useParallaxOcclusion\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"useParallaxOcclusion\", void 0);\n__decorate([\n serialize()\n], StandardMaterial.prototype, \"parallaxScaleBias\", void 0);\n__decorate([\n serialize(\"roughness\")\n], StandardMaterial.prototype, \"_roughness\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"roughness\", void 0);\n__decorate([\n serialize()\n], StandardMaterial.prototype, \"indexOfRefraction\", void 0);\n__decorate([\n serialize()\n], StandardMaterial.prototype, \"invertRefractionY\", void 0);\n__decorate([\n serialize()\n], StandardMaterial.prototype, \"alphaCutOff\", void 0);\n__decorate([\n serialize(\"useLightmapAsShadowmap\")\n], StandardMaterial.prototype, \"_useLightmapAsShadowmap\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"useLightmapAsShadowmap\", void 0);\n__decorate([\n serializeAsFresnelParameters(\"diffuseFresnelParameters\")\n], StandardMaterial.prototype, \"_diffuseFresnelParameters\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsFresnelDirty\")\n], StandardMaterial.prototype, \"diffuseFresnelParameters\", void 0);\n__decorate([\n serializeAsFresnelParameters(\"opacityFresnelParameters\")\n], StandardMaterial.prototype, \"_opacityFresnelParameters\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsFresnelAndMiscDirty\")\n], StandardMaterial.prototype, \"opacityFresnelParameters\", void 0);\n__decorate([\n serializeAsFresnelParameters(\"reflectionFresnelParameters\")\n], StandardMaterial.prototype, \"_reflectionFresnelParameters\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsFresnelDirty\")\n], StandardMaterial.prototype, \"reflectionFresnelParameters\", void 0);\n__decorate([\n serializeAsFresnelParameters(\"refractionFresnelParameters\")\n], StandardMaterial.prototype, \"_refractionFresnelParameters\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsFresnelDirty\")\n], StandardMaterial.prototype, \"refractionFresnelParameters\", void 0);\n__decorate([\n serializeAsFresnelParameters(\"emissiveFresnelParameters\")\n], StandardMaterial.prototype, \"_emissiveFresnelParameters\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsFresnelDirty\")\n], StandardMaterial.prototype, \"emissiveFresnelParameters\", void 0);\n__decorate([\n serialize(\"useReflectionFresnelFromSpecular\")\n], StandardMaterial.prototype, \"_useReflectionFresnelFromSpecular\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsFresnelDirty\")\n], StandardMaterial.prototype, \"useReflectionFresnelFromSpecular\", void 0);\n__decorate([\n serialize(\"useGlossinessFromSpecularMapAlpha\")\n], StandardMaterial.prototype, \"_useGlossinessFromSpecularMapAlpha\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"useGlossinessFromSpecularMapAlpha\", void 0);\n__decorate([\n serialize(\"maxSimultaneousLights\")\n], StandardMaterial.prototype, \"_maxSimultaneousLights\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n], StandardMaterial.prototype, \"maxSimultaneousLights\", void 0);\n__decorate([\n serialize(\"invertNormalMapX\")\n], StandardMaterial.prototype, \"_invertNormalMapX\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"invertNormalMapX\", void 0);\n__decorate([\n serialize(\"invertNormalMapY\")\n], StandardMaterial.prototype, \"_invertNormalMapY\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"invertNormalMapY\", void 0);\n__decorate([\n serialize(\"twoSidedLighting\")\n], StandardMaterial.prototype, \"_twoSidedLighting\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"twoSidedLighting\", void 0);\n__decorate([\n serialize()\n], StandardMaterial.prototype, \"useLogarithmicDepth\", null);\nRegisterClass(\"BABYLON.StandardMaterial\", StandardMaterial);\nScene.DefaultMaterialFactory = (scene) => {\n return new StandardMaterial(\"default material\", scene);\n};\n//# sourceMappingURL=standardMaterial.js.map","import { ThinEngine } from \"../../Engines/thinEngine.js\";\nimport { InternalTexture, InternalTextureSource } from \"../../Materials/Textures/internalTexture.js\";\nThinEngine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {\n const texture = new InternalTexture(this, InternalTextureSource.Dynamic);\n texture.baseWidth = width;\n texture.baseHeight = height;\n if (generateMipMaps) {\n width = this.needPOTTextures ? ThinEngine.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;\n height = this.needPOTTextures ? ThinEngine.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;\n }\n // this.resetTextureCache();\n texture.width = width;\n texture.height = height;\n texture.isReady = false;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n this.updateTextureSamplingMode(samplingMode, texture);\n this._internalTexturesCache.push(texture);\n return texture;\n};\nThinEngine.prototype.updateDynamicTexture = function (texture, source, invertY, premulAlpha = false, format, forceBindTexture = false, \n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nallowGPUOptimization = false) {\n if (!texture) {\n return;\n }\n const gl = this._gl;\n const target = gl.TEXTURE_2D;\n const wasPreviouslyBound = this._bindTextureDirectly(target, texture, true, forceBindTexture);\n this._unpackFlipY(invertY === undefined ? texture.invertY : invertY);\n if (premulAlpha) {\n gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);\n }\n const textureType = this._getWebGLTextureType(texture.type);\n const glformat = this._getInternalFormat(format ? format : texture.format);\n const internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, glformat);\n gl.texImage2D(target, 0, internalFormat, glformat, textureType, source);\n if (texture.generateMipMaps) {\n gl.generateMipmap(target);\n }\n if (!wasPreviouslyBound) {\n this._bindTextureDirectly(target, null);\n }\n if (premulAlpha) {\n gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);\n }\n texture.isReady = true;\n};\n//# sourceMappingURL=engine.dynamicTexture.js.map","import { Logger } from \"../../Misc/logger.js\";\nimport { Texture } from \"../../Materials/Textures/texture.js\";\n\nimport \"../../Engines/Extensions/engine.dynamicTexture.js\";\n/**\n * A class extending Texture allowing drawing on a texture\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/dynamicTexture\n */\nexport class DynamicTexture extends Texture {\n /**\n * Creates a DynamicTexture\n * @param name defines the name of the texture\n * @param options provides 3 alternatives for width and height of texture, a canvas, object with width and height properties, number for both width and height\n * @param scene defines the scene where you want the texture\n * @param generateMipMaps defines the use of MinMaps or not (default is false)\n * @param samplingMode defines the sampling mode to use (default is Texture.TRILINEAR_SAMPLINGMODE)\n * @param format defines the texture format to use (default is Engine.TEXTUREFORMAT_RGBA)\n * @param invertY defines if the texture needs to be inverted on the y axis during loading\n */\n constructor(name, options, scene = null, generateMipMaps = false, samplingMode = 3, format = 5, invertY) {\n super(null, scene, !generateMipMaps, invertY, samplingMode, undefined, undefined, undefined, undefined, format);\n this.name = name;\n this.wrapU = Texture.CLAMP_ADDRESSMODE;\n this.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._generateMipMaps = generateMipMaps;\n const engine = this._getEngine();\n if (!engine) {\n return;\n }\n if (options.getContext) {\n this._canvas = options;\n this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);\n }\n else {\n this._canvas = engine.createCanvas(1, 1);\n if (options.width || options.width === 0) {\n this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);\n }\n else {\n this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);\n }\n }\n const textureSize = this.getSize();\n if (this._canvas.width !== textureSize.width) {\n this._canvas.width = textureSize.width;\n }\n if (this._canvas.height !== textureSize.height) {\n this._canvas.height = textureSize.height;\n }\n this._context = this._canvas.getContext(\"2d\");\n }\n /**\n * Get the current class name of the texture useful for serialization or dynamic coding.\n * @returns \"DynamicTexture\"\n */\n getClassName() {\n return \"DynamicTexture\";\n }\n /**\n * Gets the current state of canRescale\n */\n get canRescale() {\n return true;\n }\n _recreate(textureSize) {\n this._canvas.width = textureSize.width;\n this._canvas.height = textureSize.height;\n this.releaseInternalTexture();\n this._texture = this._getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this.samplingMode);\n }\n /**\n * Scales the texture\n * @param ratio the scale factor to apply to both width and height\n */\n scale(ratio) {\n const textureSize = this.getSize();\n textureSize.width *= ratio;\n textureSize.height *= ratio;\n this._recreate(textureSize);\n }\n /**\n * Resizes the texture\n * @param width the new width\n * @param height the new height\n */\n scaleTo(width, height) {\n const textureSize = this.getSize();\n textureSize.width = width;\n textureSize.height = height;\n this._recreate(textureSize);\n }\n /**\n * Gets the context of the canvas used by the texture\n * @returns the canvas context of the dynamic texture\n */\n getContext() {\n return this._context;\n }\n /**\n * Clears the texture\n */\n clear() {\n const size = this.getSize();\n this._context.fillRect(0, 0, size.width, size.height);\n }\n /**\n * Updates the texture\n * @param invertY defines the direction for the Y axis (default is true - y increases downwards)\n * @param premulAlpha defines if alpha is stored as premultiplied (default is false)\n * @param allowGPUOptimization true to allow some specific GPU optimizations (subject to engine feature \"allowGPUOptimizationsForGUI\" being true)\n */\n update(invertY, premulAlpha = false, allowGPUOptimization = false) {\n this._getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined, undefined, allowGPUOptimization);\n }\n /**\n * Draws text onto the texture\n * @param text defines the text to be drawn\n * @param x defines the placement of the text from the left\n * @param y defines the placement of the text from the top when invertY is true and from the bottom when false\n * @param font defines the font to be used with font-style, font-size, font-name\n * @param color defines the color used for the text\n * @param clearColor defines the color for the canvas, use null to not overwrite canvas\n * @param invertY defines the direction for the Y axis (default is true - y increases downwards)\n * @param update defines whether texture is immediately update (default is true)\n */\n drawText(text, x, y, font, color, clearColor, invertY, update = true) {\n const size = this.getSize();\n if (clearColor) {\n this._context.fillStyle = clearColor;\n this._context.fillRect(0, 0, size.width, size.height);\n }\n this._context.font = font;\n if (x === null || x === undefined) {\n const textSize = this._context.measureText(text);\n x = (size.width - textSize.width) / 2;\n }\n if (y === null || y === undefined) {\n const fontSize = parseInt(font.replace(/\\D/g, \"\"));\n y = size.height / 2 + fontSize / 3.65;\n }\n this._context.fillStyle = color || \"\";\n this._context.fillText(text, x, y);\n if (update) {\n this.update(invertY);\n }\n }\n /**\n * Clones the texture\n * @returns the clone of the texture.\n */\n clone() {\n const scene = this.getScene();\n if (!scene) {\n return this;\n }\n const textureSize = this.getSize();\n const newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);\n // Base texture\n newTexture.hasAlpha = this.hasAlpha;\n newTexture.level = this.level;\n // Dynamic Texture\n newTexture.wrapU = this.wrapU;\n newTexture.wrapV = this.wrapV;\n return newTexture;\n }\n /**\n * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized\n * @returns a serialized dynamic texture object\n */\n serialize() {\n const scene = this.getScene();\n if (scene && !scene.isReady()) {\n Logger.Warn(\"The scene must be ready before serializing the dynamic texture\");\n }\n const serializationObject = super.serialize();\n if (DynamicTexture._IsCanvasElement(this._canvas)) {\n serializationObject.base64String = this._canvas.toDataURL();\n }\n serializationObject.invertY = this._invertY;\n serializationObject.samplingMode = this.samplingMode;\n return serializationObject;\n }\n static _IsCanvasElement(canvas) {\n return canvas.toDataURL !== undefined;\n }\n /** @internal */\n _rebuild() {\n this.update();\n }\n}\n//# sourceMappingURL=dynamicTexture.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/imageProcessingDeclaration.js\";\nimport \"./ShadersInclude/helperFunctions.js\";\nimport \"./ShadersInclude/imageProcessingFunctions.js\";\nconst name = \"imageProcessingPixelShader\";\nconst shader = `varying vec2 vUV;\runiform sampler2D textureSampler;\r#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\r{\rvec4 result=texture2D(textureSampler,vUV);\r#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\nresult.rgb=toLinearSpace(result.rgb);\r#endif\nresult=applyImageProcessing(result);\r#else\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\r#endif\n#endif\ngl_FragColor=result;\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const imageProcessingPixelShader = { name, shader };\n//# sourceMappingURL=imageProcessing.fragment.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize } from \"../Misc/decorators.js\";\nimport { ImageProcessingConfiguration } from \"../Materials/imageProcessingConfiguration.js\";\nimport { PostProcess } from \"./postProcess.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n\nimport \"../Shaders/imageProcessing.fragment.js\";\nimport \"../Shaders/postprocess.vertex.js\";\n/**\n * ImageProcessingPostProcess\n * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses#imageprocessing\n */\nexport class ImageProcessingPostProcess extends PostProcess {\n /**\n * Gets the image processing configuration used either in this material.\n */\n get imageProcessingConfiguration() {\n return this._imageProcessingConfiguration;\n }\n /**\n * Sets the Default image processing configuration used either in the this material.\n *\n * If sets to null, the scene one is in use.\n */\n set imageProcessingConfiguration(value) {\n // We are almost sure it is applied by post process as\n // We are in the post process :-)\n value.applyByPostProcess = true;\n this._attachImageProcessingConfiguration(value);\n }\n /**\n * Attaches a new image processing configuration to the PBR Material.\n * @param configuration\n * @param doNotBuild\n */\n _attachImageProcessingConfiguration(configuration, doNotBuild = false) {\n if (configuration === this._imageProcessingConfiguration) {\n return;\n }\n // Detaches observer.\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n // Pick the scene configuration if needed.\n if (!configuration) {\n let scene = null;\n const engine = this.getEngine();\n const camera = this.getCamera();\n if (camera) {\n scene = camera.getScene();\n }\n else if (engine && engine.scenes) {\n const scenes = engine.scenes;\n scene = scenes[scenes.length - 1];\n }\n else {\n scene = EngineStore.LastCreatedScene;\n }\n if (scene) {\n this._imageProcessingConfiguration = scene.imageProcessingConfiguration;\n }\n else {\n this._imageProcessingConfiguration = new ImageProcessingConfiguration();\n }\n }\n else {\n this._imageProcessingConfiguration = configuration;\n }\n // Attaches observer.\n if (this._imageProcessingConfiguration) {\n this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => {\n this._updateParameters();\n });\n }\n // Ensure the effect will be rebuilt.\n if (!doNotBuild) {\n this._updateParameters();\n }\n }\n /**\n * If the post process is supported.\n */\n get isSupported() {\n const effect = this.getEffect();\n return !effect || effect.isSupported;\n }\n /**\n * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .\n */\n get colorCurves() {\n return this.imageProcessingConfiguration.colorCurves;\n }\n /**\n * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .\n */\n set colorCurves(value) {\n this.imageProcessingConfiguration.colorCurves = value;\n }\n /**\n * Gets whether the color curves effect is enabled.\n */\n get colorCurvesEnabled() {\n return this.imageProcessingConfiguration.colorCurvesEnabled;\n }\n /**\n * Sets whether the color curves effect is enabled.\n */\n set colorCurvesEnabled(value) {\n this.imageProcessingConfiguration.colorCurvesEnabled = value;\n }\n /**\n * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.\n */\n get colorGradingTexture() {\n return this.imageProcessingConfiguration.colorGradingTexture;\n }\n /**\n * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.\n */\n set colorGradingTexture(value) {\n this.imageProcessingConfiguration.colorGradingTexture = value;\n }\n /**\n * Gets whether the color grading effect is enabled.\n */\n get colorGradingEnabled() {\n return this.imageProcessingConfiguration.colorGradingEnabled;\n }\n /**\n * Gets whether the color grading effect is enabled.\n */\n set colorGradingEnabled(value) {\n this.imageProcessingConfiguration.colorGradingEnabled = value;\n }\n /**\n * Gets exposure used in the effect.\n */\n get exposure() {\n return this.imageProcessingConfiguration.exposure;\n }\n /**\n * Sets exposure used in the effect.\n */\n set exposure(value) {\n this.imageProcessingConfiguration.exposure = value;\n }\n /**\n * Gets whether tonemapping is enabled or not.\n */\n get toneMappingEnabled() {\n return this._imageProcessingConfiguration.toneMappingEnabled;\n }\n /**\n * Sets whether tonemapping is enabled or not\n */\n set toneMappingEnabled(value) {\n this._imageProcessingConfiguration.toneMappingEnabled = value;\n }\n /**\n * Gets the type of tone mapping effect.\n */\n get toneMappingType() {\n return this._imageProcessingConfiguration.toneMappingType;\n }\n /**\n * Sets the type of tone mapping effect.\n */\n set toneMappingType(value) {\n this._imageProcessingConfiguration.toneMappingType = value;\n }\n /**\n * Gets contrast used in the effect.\n */\n get contrast() {\n return this.imageProcessingConfiguration.contrast;\n }\n /**\n * Sets contrast used in the effect.\n */\n set contrast(value) {\n this.imageProcessingConfiguration.contrast = value;\n }\n /**\n * Gets Vignette stretch size.\n */\n get vignetteStretch() {\n return this.imageProcessingConfiguration.vignetteStretch;\n }\n /**\n * Sets Vignette stretch size.\n */\n set vignetteStretch(value) {\n this.imageProcessingConfiguration.vignetteStretch = value;\n }\n /**\n * Gets Vignette center X Offset.\n * @deprecated use vignetteCenterX instead\n */\n get vignetteCentreX() {\n return this.imageProcessingConfiguration.vignetteCenterX;\n }\n /**\n * Sets Vignette center X Offset.\n * @deprecated use vignetteCenterX instead\n */\n set vignetteCentreX(value) {\n this.imageProcessingConfiguration.vignetteCenterX = value;\n }\n /**\n * Gets Vignette center Y Offset.\n * @deprecated use vignetteCenterY instead\n */\n get vignetteCentreY() {\n return this.imageProcessingConfiguration.vignetteCenterY;\n }\n /**\n * Sets Vignette center Y Offset.\n * @deprecated use vignetteCenterY instead\n */\n set vignetteCentreY(value) {\n this.imageProcessingConfiguration.vignetteCenterY = value;\n }\n /**\n * Vignette center Y Offset.\n */\n get vignetteCenterY() {\n return this.imageProcessingConfiguration.vignetteCenterY;\n }\n set vignetteCenterY(value) {\n this.imageProcessingConfiguration.vignetteCenterY = value;\n }\n /**\n * Vignette center X Offset.\n */\n get vignetteCenterX() {\n return this.imageProcessingConfiguration.vignetteCenterX;\n }\n set vignetteCenterX(value) {\n this.imageProcessingConfiguration.vignetteCenterX = value;\n }\n /**\n * Gets Vignette weight or intensity of the vignette effect.\n */\n get vignetteWeight() {\n return this.imageProcessingConfiguration.vignetteWeight;\n }\n /**\n * Sets Vignette weight or intensity of the vignette effect.\n */\n set vignetteWeight(value) {\n this.imageProcessingConfiguration.vignetteWeight = value;\n }\n /**\n * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)\n * if vignetteEnabled is set to true.\n */\n get vignetteColor() {\n return this.imageProcessingConfiguration.vignetteColor;\n }\n /**\n * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)\n * if vignetteEnabled is set to true.\n */\n set vignetteColor(value) {\n this.imageProcessingConfiguration.vignetteColor = value;\n }\n /**\n * Gets Camera field of view used by the Vignette effect.\n */\n get vignetteCameraFov() {\n return this.imageProcessingConfiguration.vignetteCameraFov;\n }\n /**\n * Sets Camera field of view used by the Vignette effect.\n */\n set vignetteCameraFov(value) {\n this.imageProcessingConfiguration.vignetteCameraFov = value;\n }\n /**\n * Gets the vignette blend mode allowing different kind of effect.\n */\n get vignetteBlendMode() {\n return this.imageProcessingConfiguration.vignetteBlendMode;\n }\n /**\n * Sets the vignette blend mode allowing different kind of effect.\n */\n set vignetteBlendMode(value) {\n this.imageProcessingConfiguration.vignetteBlendMode = value;\n }\n /**\n * Gets whether the vignette effect is enabled.\n */\n get vignetteEnabled() {\n return this.imageProcessingConfiguration.vignetteEnabled;\n }\n /**\n * Sets whether the vignette effect is enabled.\n */\n set vignetteEnabled(value) {\n this.imageProcessingConfiguration.vignetteEnabled = value;\n }\n /**\n * Gets intensity of the dithering effect.\n */\n get ditheringIntensity() {\n return this.imageProcessingConfiguration.ditheringIntensity;\n }\n /**\n * Sets intensity of the dithering effect.\n */\n set ditheringIntensity(value) {\n this.imageProcessingConfiguration.ditheringIntensity = value;\n }\n /**\n * Gets whether the dithering effect is enabled.\n */\n get ditheringEnabled() {\n return this.imageProcessingConfiguration.ditheringEnabled;\n }\n /**\n * Sets whether the dithering effect is enabled.\n */\n set ditheringEnabled(value) {\n this.imageProcessingConfiguration.ditheringEnabled = value;\n }\n /**\n * Gets whether the input of the processing is in Gamma or Linear Space.\n */\n get fromLinearSpace() {\n return this._fromLinearSpace;\n }\n /**\n * Sets whether the input of the processing is in Gamma or Linear Space.\n */\n set fromLinearSpace(value) {\n if (this._fromLinearSpace === value) {\n return;\n }\n this._fromLinearSpace = value;\n this._updateParameters();\n }\n constructor(name, options, camera = null, samplingMode, engine, reusable, textureType = 0, imageProcessingConfiguration) {\n super(name, \"imageProcessing\", [], [], options, camera, samplingMode, engine, reusable, null, textureType, \"postprocess\", null, true);\n this._fromLinearSpace = true;\n /**\n * Defines cache preventing GC.\n */\n this._defines = {\n IMAGEPROCESSING: false,\n VIGNETTE: false,\n VIGNETTEBLENDMODEMULTIPLY: false,\n VIGNETTEBLENDMODEOPAQUE: false,\n TONEMAPPING: false,\n TONEMAPPING_ACES: false,\n CONTRAST: false,\n COLORCURVES: false,\n COLORGRADING: false,\n COLORGRADING3D: false,\n FROMLINEARSPACE: false,\n SAMPLER3DGREENDEPTH: false,\n SAMPLER3DBGRMAP: false,\n DITHER: false,\n IMAGEPROCESSINGPOSTPROCESS: false,\n EXPOSURE: false,\n SKIPFINALCOLORCLAMP: false,\n };\n // Setup the configuration as forced by the constructor. This would then not force the\n // scene materials output in linear space and let untouched the default forward pass.\n if (imageProcessingConfiguration) {\n imageProcessingConfiguration.applyByPostProcess = true;\n this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);\n // This will cause the shader to be compiled\n this._updateParameters();\n }\n // Setup the default processing configuration to the scene.\n else {\n this._attachImageProcessingConfiguration(null, true);\n this.imageProcessingConfiguration.applyByPostProcess = true;\n }\n this.onApply = (effect) => {\n this.imageProcessingConfiguration.bind(effect, this.aspectRatio);\n };\n }\n /**\n * \"ImageProcessingPostProcess\"\n * @returns \"ImageProcessingPostProcess\"\n */\n getClassName() {\n return \"ImageProcessingPostProcess\";\n }\n /**\n * @internal\n */\n _updateParameters() {\n this._defines.FROMLINEARSPACE = this._fromLinearSpace;\n this.imageProcessingConfiguration.prepareDefines(this._defines, true);\n let defines = \"\";\n for (const define in this._defines) {\n if (this._defines[define]) {\n defines += `#define ${define};\\r\\n`;\n }\n }\n const samplers = [\"textureSampler\"];\n const uniforms = [\"scale\"];\n if (ImageProcessingConfiguration) {\n ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);\n ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);\n }\n this.updateEffect(defines, uniforms, samplers);\n }\n dispose(camera) {\n super.dispose(camera);\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n if (this._imageProcessingConfiguration) {\n this.imageProcessingConfiguration.applyByPostProcess = false;\n }\n }\n}\n__decorate([\n serialize()\n], ImageProcessingPostProcess.prototype, \"_fromLinearSpace\", void 0);\n//# sourceMappingURL=imageProcessingPostProcess.js.map","/**\n * Wrapper over subclasses of XRLayer.\n * @internal\n */\nexport class WebXRLayerWrapper {\n /**\n * Check if fixed foveation is supported on this device\n */\n get isFixedFoveationSupported() {\n return this.layerType == \"XRWebGLLayer\" && typeof this.layer.fixedFoveation == \"number\";\n }\n /**\n * Get the fixed foveation currently set, as specified by the webxr specs\n * If this returns null, then fixed foveation is not supported\n */\n get fixedFoveation() {\n if (this.isFixedFoveationSupported) {\n return this.layer.fixedFoveation;\n }\n return null;\n }\n /**\n * Set the fixed foveation to the specified value, as specified by the webxr specs\n * This value will be normalized to be between 0 and 1, 1 being max foveation, 0 being no foveation\n */\n set fixedFoveation(value) {\n if (this.isFixedFoveationSupported) {\n const val = Math.max(0, Math.min(1, value || 0));\n this.layer.fixedFoveation = val;\n }\n }\n constructor(\n /** The width of the layer's framebuffer. */\n getWidth, \n /** The height of the layer's framebuffer. */\n getHeight, \n /** The XR layer that this WebXRLayerWrapper wraps. */\n layer, \n /** The type of XR layer that is being wrapped. */\n layerType, \n /** Create a render target provider for the wrapped layer. */\n createRenderTargetTextureProvider) {\n this.getWidth = getWidth;\n this.getHeight = getHeight;\n this.layer = layer;\n this.layerType = layerType;\n this.createRenderTargetTextureProvider = createRenderTargetTextureProvider;\n }\n}\n//# sourceMappingURL=webXRLayerWrapper.js.map","import { WebGLHardwareTexture } from \"../Engines/WebGL/webGLHardwareTexture.js\";\nimport { InternalTexture, InternalTextureSource } from \"../Materials/Textures/internalTexture.js\";\nimport { MultiviewRenderTarget } from \"../Materials/Textures/MultiviewRenderTarget.js\";\nimport { RenderTargetTexture } from \"../Materials/Textures/renderTargetTexture.js\";\n/**\n * Provides render target textures and other important rendering information for a given XRLayer.\n * @internal\n */\nexport class WebXRLayerRenderTargetTextureProvider {\n constructor(_scene, layerWrapper) {\n this._scene = _scene;\n this.layerWrapper = layerWrapper;\n this._renderTargetTextures = new Array();\n this._engine = _scene.getEngine();\n }\n _createInternalTexture(textureSize, texture) {\n const internalTexture = new InternalTexture(this._engine, InternalTextureSource.Unknown, true);\n internalTexture.width = textureSize.width;\n internalTexture.height = textureSize.height;\n internalTexture._hardwareTexture = new WebGLHardwareTexture(texture, this._engine._gl);\n internalTexture.isReady = true;\n return internalTexture;\n }\n _createRenderTargetTexture(width, height, framebuffer, colorTexture, depthStencilTexture, multiview) {\n if (!this._engine) {\n throw new Error(\"Engine is disposed\");\n }\n const textureSize = { width, height };\n // Create render target texture from the internal texture\n const renderTargetTexture = multiview ? new MultiviewRenderTarget(this._scene, textureSize) : new RenderTargetTexture(\"XR renderTargetTexture\", textureSize, this._scene);\n const renderTargetWrapper = renderTargetTexture.renderTarget;\n renderTargetWrapper._samples = renderTargetTexture.samples;\n // Set the framebuffer, make sure it works in all scenarios - emulator, no layers and layers\n if (framebuffer || !colorTexture) {\n renderTargetWrapper._framebuffer = framebuffer;\n }\n // Create internal texture\n if (colorTexture) {\n if (multiview) {\n renderTargetWrapper._colorTextureArray = colorTexture;\n }\n else {\n const internalTexture = this._createInternalTexture(textureSize, colorTexture);\n renderTargetWrapper.setTexture(internalTexture, 0);\n renderTargetTexture._texture = internalTexture;\n }\n }\n if (depthStencilTexture) {\n if (multiview) {\n renderTargetWrapper._depthStencilTextureArray = depthStencilTexture;\n }\n else {\n renderTargetWrapper._depthStencilTexture = this._createInternalTexture(textureSize, depthStencilTexture);\n }\n }\n renderTargetTexture.disableRescaling();\n // Firefox reality fails if skipInitialClear is set to true, so make sure only modern XR implementations set it.\n if (typeof XRWebGLBinding !== \"undefined\") {\n // WebXR pre-clears textures\n renderTargetTexture.skipInitialClear = true;\n }\n this._renderTargetTextures.push(renderTargetTexture);\n return renderTargetTexture;\n }\n _destroyRenderTargetTexture(renderTargetTexture) {\n this._renderTargetTextures.splice(this._renderTargetTextures.indexOf(renderTargetTexture), 1);\n renderTargetTexture.dispose();\n }\n getFramebufferDimensions() {\n return this._framebufferDimensions;\n }\n dispose() {\n this._renderTargetTextures.forEach((rtt) => rtt.dispose());\n this._renderTargetTextures.length = 0;\n }\n}\n//# sourceMappingURL=webXRRenderTargetTextureProvider.js.map","import { WebXRLayerWrapper } from \"./webXRLayerWrapper.js\";\nimport { WebXRLayerRenderTargetTextureProvider } from \"./webXRRenderTargetTextureProvider.js\";\n/**\n * Wraps xr webgl layers.\n * @internal\n */\nexport class WebXRWebGLLayerWrapper extends WebXRLayerWrapper {\n /**\n * @param layer is the layer to be wrapped.\n * @returns a new WebXRLayerWrapper wrapping the provided XRWebGLLayer.\n */\n constructor(layer) {\n super(() => layer.framebufferWidth, () => layer.framebufferHeight, layer, \"XRWebGLLayer\", (sessionManager) => new WebXRWebGLLayerRenderTargetTextureProvider(sessionManager.scene, this));\n this.layer = layer;\n }\n}\n/**\n * Provides render target textures and other important rendering information for a given XRWebGLLayer.\n * @internal\n */\nexport class WebXRWebGLLayerRenderTargetTextureProvider extends WebXRLayerRenderTargetTextureProvider {\n constructor(scene, layerWrapper) {\n super(scene, layerWrapper);\n this.layerWrapper = layerWrapper;\n this._layer = layerWrapper.layer;\n this._framebufferDimensions = {\n framebufferWidth: this._layer.framebufferWidth,\n framebufferHeight: this._layer.framebufferHeight,\n };\n }\n trySetViewportForView(viewport, view) {\n const xrViewport = this._layer.getViewport(view);\n if (!xrViewport) {\n return false;\n }\n const framebufferWidth = this._framebufferDimensions.framebufferWidth;\n const framebufferHeight = this._framebufferDimensions.framebufferHeight;\n viewport.x = xrViewport.x / framebufferWidth;\n viewport.y = xrViewport.y / framebufferHeight;\n viewport.width = xrViewport.width / framebufferWidth;\n viewport.height = xrViewport.height / framebufferHeight;\n return true;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getRenderTargetTextureForEye(eye) {\n const layerWidth = this._layer.framebufferWidth;\n const layerHeight = this._layer.framebufferHeight;\n const framebuffer = this._layer.framebuffer;\n if (!this._rtt ||\n layerWidth !== this._framebufferDimensions.framebufferWidth ||\n layerHeight !== this._framebufferDimensions.framebufferHeight ||\n framebuffer !== this._framebuffer) {\n this._rtt = this._createRenderTargetTexture(layerWidth, layerHeight, framebuffer);\n this._framebufferDimensions.framebufferWidth = layerWidth;\n this._framebufferDimensions.framebufferHeight = layerHeight;\n this._framebuffer = framebuffer;\n }\n return this._rtt;\n }\n getRenderTargetTextureForView(view) {\n return this.getRenderTargetTextureForEye(view.eye);\n }\n}\n//# sourceMappingURL=webXRWebGLLayer.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { Tools } from \"../Misc/tools.js\";\nimport { WebXRWebGLLayerWrapper } from \"./webXRWebGLLayer.js\";\n/**\n * Configuration object for WebXR output canvas\n */\nexport class WebXRManagedOutputCanvasOptions {\n /**\n * Get the default values of the configuration object\n * @param engine defines the engine to use (can be null)\n * @returns default values of this configuration object\n */\n static GetDefaults(engine) {\n const defaults = new WebXRManagedOutputCanvasOptions();\n defaults.canvasOptions = {\n antialias: true,\n depth: true,\n stencil: engine ? engine.isStencilEnable : true,\n alpha: true,\n framebufferScaleFactor: 1,\n };\n defaults.newCanvasCssStyle = \"position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;\";\n return defaults;\n }\n}\n/**\n * Creates a canvas that is added/removed from the webpage when entering/exiting XR\n */\nexport class WebXRManagedOutputCanvas {\n /**\n * Initializes the canvas to be added/removed upon entering/exiting xr\n * @param _xrSessionManager The XR Session manager\n * @param _options optional configuration for this canvas output. defaults will be used if not provided\n */\n constructor(_xrSessionManager, _options = WebXRManagedOutputCanvasOptions.GetDefaults()) {\n this._options = _options;\n this._canvas = null;\n this._engine = null;\n /**\n * xr layer for the canvas\n */\n this.xrLayer = null;\n this._xrLayerWrapper = null;\n /**\n * Observers registered here will be triggered when the xr layer was initialized\n */\n this.onXRLayerInitObservable = new Observable();\n this._engine = _xrSessionManager.scene.getEngine();\n this._engine.onDisposeObservable.addOnce(() => {\n this._engine = null;\n });\n if (!_options.canvasElement) {\n const canvas = document.createElement(\"canvas\");\n canvas.style.cssText = this._options.newCanvasCssStyle || \"position:absolute; bottom:0px;right:0px;\";\n this._setManagedOutputCanvas(canvas);\n }\n else {\n this._setManagedOutputCanvas(_options.canvasElement);\n }\n _xrSessionManager.onXRSessionInit.add(() => {\n this._addCanvas();\n });\n _xrSessionManager.onXRSessionEnded.add(() => {\n this._removeCanvas();\n });\n }\n /**\n * Disposes of the object\n */\n dispose() {\n this._removeCanvas();\n this._setManagedOutputCanvas(null);\n }\n /**\n * Initializes a XRWebGLLayer to be used as the session's baseLayer.\n * @param xrSession xr session\n * @returns a promise that will resolve once the XR Layer has been created\n */\n async initializeXRLayerAsync(xrSession) {\n const createLayer = () => {\n this.xrLayer = new XRWebGLLayer(xrSession, this.canvasContext, this._options.canvasOptions);\n this._xrLayerWrapper = new WebXRWebGLLayerWrapper(this.xrLayer);\n this.onXRLayerInitObservable.notifyObservers(this.xrLayer);\n return this.xrLayer;\n };\n // support canvases without makeXRCompatible\n if (!this.canvasContext.makeXRCompatible) {\n return Promise.resolve(createLayer());\n }\n return this.canvasContext\n .makeXRCompatible()\n .then(\n // catch any error and continue. When using the emulator is throws this error for no apparent reason.\n () => { }, () => {\n // log the error, continue nonetheless!\n Tools.Warn(\"Error executing makeXRCompatible. This does not mean that the session will work incorrectly.\");\n })\n .then(() => {\n return createLayer();\n });\n }\n _addCanvas() {\n if (this._canvas && this._engine && this._canvas !== this._engine.getRenderingCanvas()) {\n document.body.appendChild(this._canvas);\n }\n if (this.xrLayer) {\n this._setCanvasSize(true);\n }\n else {\n this.onXRLayerInitObservable.addOnce(() => {\n this._setCanvasSize(true);\n });\n }\n }\n _removeCanvas() {\n if (this._canvas && this._engine && document.body.contains(this._canvas) && this._canvas !== this._engine.getRenderingCanvas()) {\n document.body.removeChild(this._canvas);\n }\n this._setCanvasSize(false);\n }\n _setCanvasSize(init = true, xrLayer = this._xrLayerWrapper) {\n if (!this._canvas || !this._engine) {\n return;\n }\n if (init) {\n if (xrLayer) {\n if (this._canvas !== this._engine.getRenderingCanvas()) {\n this._canvas.style.width = xrLayer.getWidth() + \"px\";\n this._canvas.style.height = xrLayer.getHeight() + \"px\";\n }\n else {\n this._engine.setSize(xrLayer.getWidth(), xrLayer.getHeight());\n }\n }\n }\n else {\n if (this._originalCanvasSize) {\n if (this._canvas !== this._engine.getRenderingCanvas()) {\n this._canvas.style.width = this._originalCanvasSize.width + \"px\";\n this._canvas.style.height = this._originalCanvasSize.height + \"px\";\n }\n else {\n this._engine.setSize(this._originalCanvasSize.width, this._originalCanvasSize.height);\n }\n }\n }\n }\n _setManagedOutputCanvas(canvas) {\n this._removeCanvas();\n if (!canvas) {\n this._canvas = null;\n this.canvasContext = null;\n }\n else {\n this._originalCanvasSize = {\n width: canvas.offsetWidth,\n height: canvas.offsetHeight,\n };\n this._canvas = canvas;\n this.canvasContext = this._canvas.getContext(\"webgl2\");\n if (!this.canvasContext) {\n this.canvasContext = this._canvas.getContext(\"webgl\");\n }\n }\n }\n}\n//# sourceMappingURL=webXRManagedOutputCanvas.js.map","import { WebXRLayerWrapper } from \"../webXRLayerWrapper.js\";\nimport { WebXRLayerRenderTargetTextureProvider } from \"../webXRRenderTargetTextureProvider.js\";\n/**\n * Wraps XRWebGLLayer's created by Babylon Native.\n * @internal\n */\nexport class NativeXRLayerWrapper extends WebXRLayerWrapper {\n constructor(layer) {\n super(() => layer.framebufferWidth, () => layer.framebufferHeight, layer, \"XRWebGLLayer\", (sessionManager) => new NativeXRLayerRenderTargetTextureProvider(sessionManager, this));\n this.layer = layer;\n }\n}\n/**\n * Provides render target textures for layers created by Babylon Native.\n * @internal\n */\nexport class NativeXRLayerRenderTargetTextureProvider extends WebXRLayerRenderTargetTextureProvider {\n constructor(sessionManager, layerWrapper) {\n super(sessionManager.scene, layerWrapper);\n this.layerWrapper = layerWrapper;\n this._nativeRTTProvider = navigator.xr.getNativeRenderTargetProvider(sessionManager.session, this._createRenderTargetTexture.bind(this), this._destroyRenderTargetTexture.bind(this));\n this._nativeLayer = layerWrapper.layer;\n }\n trySetViewportForView(viewport) {\n viewport.x = 0;\n viewport.y = 0;\n viewport.width = 1;\n viewport.height = 1;\n return true;\n }\n getRenderTargetTextureForEye(eye) {\n // TODO (rgerd): Update the contract on the BabylonNative side to call this \"getRenderTargetTextureForEye\"\n return this._nativeRTTProvider.getRenderTargetForEye(eye);\n }\n getRenderTargetTextureForView(view) {\n return this._nativeRTTProvider.getRenderTargetForEye(view.eye);\n }\n getFramebufferDimensions() {\n return {\n framebufferWidth: this._nativeLayer.framebufferWidth,\n framebufferHeight: this._nativeLayer.framebufferHeight,\n };\n }\n}\n/**\n * Creates the xr layer that will be used as the xr session's base layer.\n * @internal\n */\nexport class NativeXRRenderTarget {\n constructor(_xrSessionManager) {\n this._nativeRenderTarget = navigator.xr.getWebXRRenderTarget(_xrSessionManager.scene.getEngine());\n }\n async initializeXRLayerAsync(xrSession) {\n await this._nativeRenderTarget.initializeXRLayerAsync(xrSession);\n this.xrLayer = this._nativeRenderTarget.xrLayer;\n return this.xrLayer;\n }\n dispose() {\n /* empty */\n }\n}\n//# sourceMappingURL=nativeXRRenderTarget.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { WebXRManagedOutputCanvas, WebXRManagedOutputCanvasOptions } from \"./webXRManagedOutputCanvas.js\";\nimport { NativeXRLayerWrapper, NativeXRRenderTarget } from \"./native/nativeXRRenderTarget.js\";\nimport { WebXRWebGLLayerWrapper } from \"./webXRWebGLLayer.js\";\n/**\n * Manages an XRSession to work with Babylon's engine\n * @see https://doc.babylonjs.com/features/featuresDeepDive/webXR/webXRSessionManagers\n */\nexport class WebXRSessionManager {\n /**\n * Constructs a WebXRSessionManager, this must be initialized within a user action before usage\n * @param scene The scene which the session should be created for\n */\n constructor(\n /** The scene which the session should be created for */\n scene) {\n this.scene = scene;\n /** WebXR timestamp updated every frame */\n this.currentTimestamp = -1;\n /**\n * Used just in case of a failure to initialize an immersive session.\n * The viewer reference space is compensated using this height, creating a kind of \"viewer-floor\" reference space\n */\n this.defaultHeightCompensation = 1.7;\n /**\n * Fires every time a new xrFrame arrives which can be used to update the camera\n */\n this.onXRFrameObservable = new Observable();\n /**\n * Fires when the reference space changed\n */\n this.onXRReferenceSpaceChanged = new Observable();\n /**\n * Fires when the xr session is ended either by the device or manually done\n */\n this.onXRSessionEnded = new Observable();\n /**\n * Fires when the xr session is initialized: right after requestSession was called and returned with a successful result\n */\n this.onXRSessionInit = new Observable();\n /**\n * Are we currently in the XR loop?\n */\n this.inXRFrameLoop = false;\n /**\n * Are we in an XR session?\n */\n this.inXRSession = false;\n this._engine = scene.getEngine();\n this._onEngineDisposedObserver = this._engine.onDisposeObservable.addOnce(() => {\n this._engine = null;\n });\n scene.onDisposeObservable.addOnce(() => {\n this.dispose();\n });\n }\n /**\n * The current reference space used in this session. This reference space can constantly change!\n * It is mainly used to offset the camera's position.\n */\n get referenceSpace() {\n return this._referenceSpace;\n }\n /**\n * Set a new reference space and triggers the observable\n */\n set referenceSpace(newReferenceSpace) {\n this._referenceSpace = newReferenceSpace;\n this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace);\n }\n /**\n * The mode for the managed XR session\n */\n get sessionMode() {\n return this._sessionMode;\n }\n /**\n * Disposes of the session manager\n * This should be called explicitly by the dev, if required.\n */\n dispose() {\n var _a;\n // disposing without leaving XR? Exit XR first\n if (this.inXRSession) {\n this.exitXRAsync();\n }\n this.onXRFrameObservable.clear();\n this.onXRSessionEnded.clear();\n this.onXRReferenceSpaceChanged.clear();\n this.onXRSessionInit.clear();\n (_a = this._engine) === null || _a === void 0 ? void 0 : _a.onDisposeObservable.remove(this._onEngineDisposedObserver);\n this._engine = null;\n }\n /**\n * Stops the xrSession and restores the render loop\n * @returns Promise which resolves after it exits XR\n */\n exitXRAsync() {\n if (this.session && this.inXRSession) {\n this.inXRSession = false;\n return this.session.end().catch(() => {\n Logger.Warn(\"Could not end XR session.\");\n });\n }\n return Promise.resolve();\n }\n /**\n * Attempts to set the framebuffer-size-normalized viewport to be rendered this frame for this view.\n * In the event of a failure, the supplied viewport is not updated.\n * @param viewport the viewport to which the view will be rendered\n * @param view the view for which to set the viewport\n * @returns whether the operation was successful\n */\n trySetViewportForView(viewport, view) {\n var _a;\n return ((_a = this._baseLayerRTTProvider) === null || _a === void 0 ? void 0 : _a.trySetViewportForView(viewport, view)) || false;\n }\n /**\n * Gets the correct render target texture to be rendered this frame for this eye\n * @param eye the eye for which to get the render target\n * @returns the render target for the specified eye or null if not available\n */\n getRenderTargetTextureForEye(eye) {\n var _a;\n return ((_a = this._baseLayerRTTProvider) === null || _a === void 0 ? void 0 : _a.getRenderTargetTextureForEye(eye)) || null;\n }\n /**\n * Gets the correct render target texture to be rendered this frame for this view\n * @param view the view for which to get the render target\n * @returns the render target for the specified view or null if not available\n */\n getRenderTargetTextureForView(view) {\n var _a;\n return ((_a = this._baseLayerRTTProvider) === null || _a === void 0 ? void 0 : _a.getRenderTargetTextureForView(view)) || null;\n }\n /**\n * Creates a WebXRRenderTarget object for the XR session\n * @param options optional options to provide when creating a new render target\n * @returns a WebXR render target to which the session can render\n */\n getWebXRRenderTarget(options) {\n const engine = this.scene.getEngine();\n if (this._xrNavigator.xr.native) {\n return new NativeXRRenderTarget(this);\n }\n else {\n options = options || WebXRManagedOutputCanvasOptions.GetDefaults(engine);\n options.canvasElement = options.canvasElement || engine.getRenderingCanvas() || undefined;\n return new WebXRManagedOutputCanvas(this, options);\n }\n }\n /**\n * Initializes the manager\n * After initialization enterXR can be called to start an XR session\n * @returns Promise which resolves after it is initialized\n */\n initializeAsync() {\n // Check if the browser supports webXR\n this._xrNavigator = navigator;\n if (!this._xrNavigator.xr) {\n return Promise.reject(\"WebXR not available\");\n }\n return Promise.resolve();\n }\n /**\n * Initializes an xr session\n * @param xrSessionMode mode to initialize\n * @param xrSessionInit defines optional and required values to pass to the session builder\n * @returns a promise which will resolve once the session has been initialized\n */\n initializeSessionAsync(xrSessionMode = \"immersive-vr\", xrSessionInit = {}) {\n return this._xrNavigator.xr.requestSession(xrSessionMode, xrSessionInit).then((session) => {\n this.session = session;\n this._sessionMode = xrSessionMode;\n this.onXRSessionInit.notifyObservers(session);\n this.inXRSession = true;\n // handle when the session is ended (By calling session.end or device ends its own session eg. pressing home button on phone)\n this.session.addEventListener(\"end\", () => {\n var _a;\n this.inXRSession = false;\n // Notify frame observers\n this.onXRSessionEnded.notifyObservers(null);\n if (this._engine) {\n // make sure dimensions object is restored\n this._engine.framebufferDimensionsObject = null;\n // Restore frame buffer to avoid clear on xr framebuffer after session end\n this._engine.restoreDefaultFramebuffer();\n // Need to restart render loop as after the session is ended the last request for new frame will never call callback\n this._engine.customAnimationFrameRequester = null;\n this._engine._renderLoop();\n }\n // Dispose render target textures.\n // Only dispose on native because we can't destroy opaque textures on browser.\n if (this.isNative) {\n (_a = this._baseLayerRTTProvider) === null || _a === void 0 ? void 0 : _a.dispose();\n }\n this._baseLayerRTTProvider = null;\n this._baseLayerWrapper = null;\n }, { once: true });\n return this.session;\n });\n }\n /**\n * Checks if a session would be supported for the creation options specified\n * @param sessionMode session mode to check if supported eg. immersive-vr\n * @returns A Promise that resolves to true if supported and false if not\n */\n isSessionSupportedAsync(sessionMode) {\n return WebXRSessionManager.IsSessionSupportedAsync(sessionMode);\n }\n /**\n * Resets the reference space to the one started the session\n */\n resetReferenceSpace() {\n this.referenceSpace = this.baseReferenceSpace;\n }\n /**\n * Starts rendering to the xr layer\n */\n runXRRenderLoop() {\n var _a;\n if (!this.inXRSession || !this._engine) {\n return;\n }\n // Tell the engine's render loop to be driven by the xr session's refresh rate and provide xr pose information\n this._engine.customAnimationFrameRequester = {\n requestAnimationFrame: this.session.requestAnimationFrame.bind(this.session),\n renderFunction: (timestamp, xrFrame) => {\n var _a;\n if (!this.inXRSession || !this._engine) {\n return;\n }\n // Store the XR frame and timestamp in the session manager\n this.currentFrame = xrFrame;\n this.currentTimestamp = timestamp;\n if (xrFrame) {\n this.inXRFrameLoop = true;\n this._engine.framebufferDimensionsObject = ((_a = this._baseLayerRTTProvider) === null || _a === void 0 ? void 0 : _a.getFramebufferDimensions()) || null;\n this.onXRFrameObservable.notifyObservers(xrFrame);\n this._engine._renderLoop();\n this._engine.framebufferDimensionsObject = null;\n this.inXRFrameLoop = false;\n }\n },\n };\n this._engine.framebufferDimensionsObject = ((_a = this._baseLayerRTTProvider) === null || _a === void 0 ? void 0 : _a.getFramebufferDimensions()) || null;\n // Stop window's animation frame and trigger sessions animation frame\n if (typeof window !== \"undefined\" && window.cancelAnimationFrame) {\n window.cancelAnimationFrame(this._engine._frameHandler);\n }\n this._engine._renderLoop();\n }\n /**\n * Sets the reference space on the xr session\n * @param referenceSpaceType space to set\n * @returns a promise that will resolve once the reference space has been set\n */\n setReferenceSpaceTypeAsync(referenceSpaceType = \"local-floor\") {\n return this.session\n .requestReferenceSpace(referenceSpaceType)\n .then((referenceSpace) => {\n return referenceSpace;\n }, (rejectionReason) => {\n Logger.Error(\"XR.requestReferenceSpace failed for the following reason: \");\n Logger.Error(rejectionReason);\n Logger.Log('Defaulting to universally-supported \"viewer\" reference space type.');\n return this.session.requestReferenceSpace(\"viewer\").then((referenceSpace) => {\n const heightCompensation = new XRRigidTransform({ x: 0, y: -this.defaultHeightCompensation, z: 0 });\n return referenceSpace.getOffsetReferenceSpace(heightCompensation);\n }, (rejectionReason) => {\n Logger.Error(rejectionReason);\n throw 'XR initialization failed: required \"viewer\" reference space type not supported.';\n });\n })\n .then((referenceSpace) => {\n // create viewer reference space before setting the first reference space\n return this.session.requestReferenceSpace(\"viewer\").then((viewerReferenceSpace) => {\n this.viewerReferenceSpace = viewerReferenceSpace;\n return referenceSpace;\n });\n })\n .then((referenceSpace) => {\n // initialize the base and offset (currently the same)\n this.referenceSpace = this.baseReferenceSpace = referenceSpace;\n return this.referenceSpace;\n });\n }\n /**\n * Updates the render state of the session.\n * Note that this is deprecated in favor of WebXRSessionManager.updateRenderState().\n * @param state state to set\n * @returns a promise that resolves once the render state has been updated\n * @deprecated\n */\n updateRenderStateAsync(state) {\n return Promise.resolve(this.session.updateRenderState(state));\n }\n /**\n * @internal\n */\n _setBaseLayerWrapper(baseLayerWrapper) {\n var _a, _b;\n if (this.isNative) {\n (_a = this._baseLayerRTTProvider) === null || _a === void 0 ? void 0 : _a.dispose();\n }\n this._baseLayerWrapper = baseLayerWrapper;\n this._baseLayerRTTProvider = ((_b = this._baseLayerWrapper) === null || _b === void 0 ? void 0 : _b.createRenderTargetTextureProvider(this)) || null;\n }\n /**\n * @internal\n */\n _getBaseLayerWrapper() {\n return this._baseLayerWrapper;\n }\n /**\n * Updates the render state of the session\n * @param state state to set\n */\n updateRenderState(state) {\n if (state.baseLayer) {\n this._setBaseLayerWrapper(this.isNative ? new NativeXRLayerWrapper(state.baseLayer) : new WebXRWebGLLayerWrapper(state.baseLayer));\n }\n this.session.updateRenderState(state);\n }\n /**\n * Returns a promise that resolves with a boolean indicating if the provided session mode is supported by this browser\n * @param sessionMode defines the session to test\n * @returns a promise with boolean as final value\n */\n static IsSessionSupportedAsync(sessionMode) {\n if (!navigator.xr) {\n return Promise.resolve(false);\n }\n // When the specs are final, remove supportsSession!\n const functionToUse = navigator.xr.isSessionSupported || navigator.xr.supportsSession;\n if (!functionToUse) {\n return Promise.resolve(false);\n }\n else {\n return functionToUse\n .call(navigator.xr, sessionMode)\n .then((result) => {\n const returnValue = typeof result === \"undefined\" ? true : result;\n return Promise.resolve(returnValue);\n })\n .catch((e) => {\n Logger.Warn(e);\n return Promise.resolve(false);\n });\n }\n }\n /**\n * Returns true if Babylon.js is using the BabylonNative backend, otherwise false\n */\n get isNative() {\n var _a;\n return (_a = this._xrNavigator.xr.native) !== null && _a !== void 0 ? _a : false;\n }\n /**\n * The current frame rate as reported by the device\n */\n get currentFrameRate() {\n var _a;\n return (_a = this.session) === null || _a === void 0 ? void 0 : _a.frameRate;\n }\n /**\n * A list of supported frame rates (only available in-session!\n */\n get supportedFrameRates() {\n var _a;\n return (_a = this.session) === null || _a === void 0 ? void 0 : _a.supportedFrameRates;\n }\n /**\n * Set the framerate of the session.\n * @param rate the new framerate. This value needs to be in the supportedFrameRates array\n * @returns a promise that resolves once the framerate has been set\n */\n updateTargetFrameRate(rate) {\n return this.session.updateTargetFrameRate(rate);\n }\n /**\n * Run a callback in the xr render loop\n * @param callback the callback to call when in XR Frame\n * @param ignoreIfNotInSession if no session is currently running, run it first thing on the next session\n */\n runInXRFrame(callback, ignoreIfNotInSession = true) {\n if (this.inXRFrameLoop) {\n callback();\n }\n else if (this.inXRSession || !ignoreIfNotInSession) {\n this.onXRFrameObservable.addOnce(callback);\n }\n }\n /**\n * Check if fixed foveation is supported on this device\n */\n get isFixedFoveationSupported() {\n var _a;\n return ((_a = this._baseLayerWrapper) === null || _a === void 0 ? void 0 : _a.isFixedFoveationSupported) || false;\n }\n /**\n * Get the fixed foveation currently set, as specified by the webxr specs\n * If this returns null, then fixed foveation is not supported\n */\n get fixedFoveation() {\n var _a;\n return ((_a = this._baseLayerWrapper) === null || _a === void 0 ? void 0 : _a.fixedFoveation) || null;\n }\n /**\n * Set the fixed foveation to the specified value, as specified by the webxr specs\n * This value will be normalized to be between 0 and 1, 1 being max foveation, 0 being no foveation\n */\n set fixedFoveation(value) {\n const val = Math.max(0, Math.min(1, value || 0));\n if (this._baseLayerWrapper) {\n this._baseLayerWrapper.fixedFoveation = val;\n }\n }\n /**\n * Get the features enabled on the current session\n * This is only available in-session!\n * @see https://www.w3.org/TR/webxr/#dom-xrsession-enabledfeatures\n */\n get enabledFeatures() {\n var _a, _b;\n return (_b = (_a = this.session) === null || _a === void 0 ? void 0 : _a.enabledFeatures) !== null && _b !== void 0 ? _b : null;\n }\n}\n//# sourceMappingURL=webXRSessionManager.js.map","/**\n * States of the webXR experience\n */\nexport var WebXRState;\n(function (WebXRState) {\n /**\n * Transitioning to being in XR mode\n */\n WebXRState[WebXRState[\"ENTERING_XR\"] = 0] = \"ENTERING_XR\";\n /**\n * Transitioning to non XR mode\n */\n WebXRState[WebXRState[\"EXITING_XR\"] = 1] = \"EXITING_XR\";\n /**\n * In XR mode and presenting\n */\n WebXRState[WebXRState[\"IN_XR\"] = 2] = \"IN_XR\";\n /**\n * Not entered XR mode\n */\n WebXRState[WebXRState[\"NOT_IN_XR\"] = 3] = \"NOT_IN_XR\";\n})(WebXRState || (WebXRState = {}));\n/**\n * The state of the XR camera's tracking\n */\nexport var WebXRTrackingState;\n(function (WebXRTrackingState) {\n /**\n * No transformation received, device is not being tracked\n */\n WebXRTrackingState[WebXRTrackingState[\"NOT_TRACKING\"] = 0] = \"NOT_TRACKING\";\n /**\n * Tracking lost - using emulated position\n */\n WebXRTrackingState[WebXRTrackingState[\"TRACKING_LOST\"] = 1] = \"TRACKING_LOST\";\n /**\n * Transformation tracking works normally\n */\n WebXRTrackingState[WebXRTrackingState[\"TRACKING\"] = 2] = \"TRACKING\";\n})(WebXRTrackingState || (WebXRTrackingState = {}));\n//# sourceMappingURL=webXRTypes.js.map","import { Vector4, Vector3, Vector2 } from \"../../Maths/math.vector.js\";\nimport { Color4 } from \"../../Maths/math.color.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { Scene } from \"../../scene.js\";\nimport { Axis } from \"../../Maths/math.axis.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n/**\n * Creates the VertexData for a cylinder, cone or prism\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * height sets the height (y direction) of the cylinder, optional, default 2\n * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter\n * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter\n * * diameter sets the diameter of the top and bottom of the cone, optional default 1\n * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24\n * * subdivisions` the number of rings along the cylinder height, optional, default 1\n * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1\n * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively\n * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively\n * * hasRings when true makes each subdivision independently treated as a face for faceUV and faceColors, optional, default false\n * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.height\n * @param options.diameterTop\n * @param options.diameterBottom\n * @param options.diameter\n * @param options.tessellation\n * @param options.subdivisions\n * @param options.arc\n * @param options.faceColors\n * @param options.faceUV\n * @param options.hasRings\n * @param options.enclose\n * @param options.cap\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the cylinder, cone or prism\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function CreateCylinderVertexData(options) {\n const height = options.height || 2;\n let diameterTop = options.diameterTop === 0 ? 0 : options.diameterTop || options.diameter || 1;\n let diameterBottom = options.diameterBottom === 0 ? 0 : options.diameterBottom || options.diameter || 1;\n diameterTop = diameterTop || 0.00001; // Prevent broken normals\n diameterBottom = diameterBottom || 0.00001; // Prevent broken normals\n const tessellation = options.tessellation || 24;\n const subdivisions = options.subdivisions || 1;\n const hasRings = options.hasRings ? true : false;\n const enclose = options.enclose ? true : false;\n const cap = options.cap === 0 ? 0 : options.cap || Mesh.CAP_ALL;\n const arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;\n const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;\n const faceUV = options.faceUV || new Array(3);\n const faceColors = options.faceColors;\n // default face colors and UV if undefined\n const quadNb = arc !== 1 && enclose ? 2 : 0;\n const ringNb = hasRings ? subdivisions : 1;\n const surfaceNb = 2 + (1 + quadNb) * ringNb;\n let f;\n for (f = 0; f < surfaceNb; f++) {\n if (faceColors && faceColors[f] === undefined) {\n faceColors[f] = new Color4(1, 1, 1, 1);\n }\n }\n for (f = 0; f < surfaceNb; f++) {\n if (faceUV && faceUV[f] === undefined) {\n faceUV[f] = new Vector4(0, 0, 1, 1);\n }\n }\n const indices = new Array();\n const positions = new Array();\n const normals = new Array();\n const uvs = new Array();\n const colors = new Array();\n const angleStep = (Math.PI * 2 * arc) / tessellation;\n let angle;\n let h;\n let radius;\n const tan = (diameterBottom - diameterTop) / 2 / height;\n const ringVertex = Vector3.Zero();\n const ringNormal = Vector3.Zero();\n const ringFirstVertex = Vector3.Zero();\n const ringFirstNormal = Vector3.Zero();\n const quadNormal = Vector3.Zero();\n const Y = Axis.Y;\n // positions, normals, uvs\n let i;\n let j;\n let r;\n let ringIdx = 1;\n let s = 1; // surface index\n let cs = 0;\n let v = 0;\n for (i = 0; i <= subdivisions; i++) {\n h = i / subdivisions;\n radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;\n ringIdx = hasRings && i !== 0 && i !== subdivisions ? 2 : 1;\n for (r = 0; r < ringIdx; r++) {\n if (hasRings) {\n s += r;\n }\n if (enclose) {\n s += 2 * r;\n }\n for (j = 0; j <= tessellation; j++) {\n angle = j * angleStep;\n // position\n ringVertex.x = Math.cos(-angle) * radius;\n ringVertex.y = -height / 2 + h * height;\n ringVertex.z = Math.sin(-angle) * radius;\n // normal\n if (diameterTop === 0 && i === subdivisions) {\n // if no top cap, reuse former normals\n ringNormal.x = normals[normals.length - (tessellation + 1) * 3];\n ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];\n ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];\n }\n else {\n ringNormal.x = ringVertex.x;\n ringNormal.z = ringVertex.z;\n ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;\n ringNormal.normalize();\n }\n // keep first ring vertex values for enclose\n if (j === 0) {\n ringFirstVertex.copyFrom(ringVertex);\n ringFirstNormal.copyFrom(ringNormal);\n }\n positions.push(ringVertex.x, ringVertex.y, ringVertex.z);\n normals.push(ringNormal.x, ringNormal.y, ringNormal.z);\n if (hasRings) {\n v = cs !== s ? faceUV[s].y : faceUV[s].w;\n }\n else {\n v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;\n }\n uvs.push(faceUV[s].x + ((faceUV[s].z - faceUV[s].x) * j) / tessellation, CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v);\n if (faceColors) {\n colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);\n }\n }\n // if enclose, add four vertices and their dedicated normals\n if (arc !== 1 && enclose) {\n positions.push(ringVertex.x, ringVertex.y, ringVertex.z);\n positions.push(0, ringVertex.y, 0);\n positions.push(0, ringVertex.y, 0);\n positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);\n Vector3.CrossToRef(Y, ringNormal, quadNormal);\n quadNormal.normalize();\n normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);\n Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);\n quadNormal.normalize();\n normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);\n if (hasRings) {\n v = cs !== s ? faceUV[s + 1].y : faceUV[s + 1].w;\n }\n else {\n v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;\n }\n uvs.push(faceUV[s + 1].x, CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v);\n uvs.push(faceUV[s + 1].z, CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v);\n if (hasRings) {\n v = cs !== s ? faceUV[s + 2].y : faceUV[s + 2].w;\n }\n else {\n v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;\n }\n uvs.push(faceUV[s + 2].x, CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v);\n uvs.push(faceUV[s + 2].z, CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v);\n if (faceColors) {\n colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);\n colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);\n colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);\n colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);\n }\n }\n if (cs !== s) {\n cs = s;\n }\n }\n }\n // indices\n const e = arc !== 1 && enclose ? tessellation + 4 : tessellation; // correction of number of iteration if enclose\n i = 0;\n for (s = 0; s < subdivisions; s++) {\n let i0 = 0;\n let i1 = 0;\n let i2 = 0;\n let i3 = 0;\n for (j = 0; j < tessellation; j++) {\n i0 = i * (e + 1) + j;\n i1 = (i + 1) * (e + 1) + j;\n i2 = i * (e + 1) + (j + 1);\n i3 = (i + 1) * (e + 1) + (j + 1);\n indices.push(i0, i1, i2);\n indices.push(i3, i2, i1);\n }\n if (arc !== 1 && enclose) {\n // if enclose, add two quads\n indices.push(i0 + 2, i1 + 2, i2 + 2);\n indices.push(i3 + 2, i2 + 2, i1 + 2);\n indices.push(i0 + 4, i1 + 4, i2 + 4);\n indices.push(i3 + 4, i2 + 4, i1 + 4);\n }\n i = hasRings ? i + 2 : i + 1;\n }\n // Caps\n const createCylinderCap = (isTop) => {\n const radius = isTop ? diameterTop / 2 : diameterBottom / 2;\n if (radius === 0) {\n return;\n }\n // Cap positions, normals & uvs\n let angle;\n let circleVector;\n let i;\n const u = isTop ? faceUV[surfaceNb - 1] : faceUV[0];\n let c = null;\n if (faceColors) {\n c = isTop ? faceColors[surfaceNb - 1] : faceColors[0];\n }\n // cap center\n const vbase = positions.length / 3;\n const offset = isTop ? height / 2 : -height / 2;\n const center = new Vector3(0, offset, 0);\n positions.push(center.x, center.y, center.z);\n normals.push(0, isTop ? 1 : -1, 0);\n const v = u.y + (u.w - u.y) * 0.5;\n uvs.push(u.x + (u.z - u.x) * 0.5, CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v);\n if (c) {\n colors.push(c.r, c.g, c.b, c.a);\n }\n const textureScale = new Vector2(0.5, 0.5);\n for (i = 0; i <= tessellation; i++) {\n angle = (Math.PI * 2 * i * arc) / tessellation;\n const cos = Math.cos(-angle);\n const sin = Math.sin(-angle);\n circleVector = new Vector3(cos * radius, offset, sin * radius);\n const textureCoordinate = new Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);\n positions.push(circleVector.x, circleVector.y, circleVector.z);\n normals.push(0, isTop ? 1 : -1, 0);\n const v = u.y + (u.w - u.y) * textureCoordinate.y;\n uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v);\n if (c) {\n colors.push(c.r, c.g, c.b, c.a);\n }\n }\n // Cap indices\n for (i = 0; i < tessellation; i++) {\n if (!isTop) {\n indices.push(vbase);\n indices.push(vbase + (i + 1));\n indices.push(vbase + (i + 2));\n }\n else {\n indices.push(vbase);\n indices.push(vbase + (i + 2));\n indices.push(vbase + (i + 1));\n }\n }\n };\n // add caps to geometry based on cap parameter\n if (cap === Mesh.CAP_START || cap === Mesh.CAP_ALL) {\n createCylinderCap(false);\n }\n if (cap === Mesh.CAP_END || cap === Mesh.CAP_ALL) {\n createCylinderCap(true);\n }\n // Sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n if (faceColors) {\n vertexData.colors = colors;\n }\n return vertexData;\n}\n/**\n * Creates a cylinder or a cone mesh\n * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).\n * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).\n * * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter \"diameterBottom\" can't be zero.\n * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.\n * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).\n * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.\n * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.\n * * The parameter `cap` sets the way the cylinder is capped. Possible values : BABYLON.Mesh.NO_CAP, BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL (default).\n * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.\n * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n Color3 elements) and `faceUV` (an array of n Vector4 elements).\n * * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3\n * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7\n * * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17\n * * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface.\n * * If `enclose` is false, a ring surface is one element.\n * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.\n * * Example how to set colors and textures on a sliced cylinder : https://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.height\n * @param options.diameterTop\n * @param options.diameterBottom\n * @param options.diameter\n * @param options.tessellation\n * @param options.subdivisions\n * @param options.arc\n * @param options.faceColors\n * @param options.faceUV\n * @param options.updatable\n * @param options.hasRings\n * @param options.enclose\n * @param options.cap\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param scene defines the hosting scene\n * @returns the cylinder mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#cylinder-or-cone\n */\nexport function CreateCylinder(name, options = {}, scene) {\n const cylinder = new Mesh(name, scene);\n options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n cylinder._originalBuilderSideOrientation = options.sideOrientation;\n const vertexData = CreateCylinderVertexData(options);\n vertexData.applyToMesh(cylinder, options.updatable);\n return cylinder;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated Please use CreateCylinder directly\n */\nexport const CylinderBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateCylinder,\n};\nVertexData.CreateCylinder = CreateCylinderVertexData;\nMesh.CreateCylinder = (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) => {\n if (scene === undefined || !(scene instanceof Scene)) {\n if (scene !== undefined) {\n sideOrientation = updatable || Mesh.DEFAULTSIDE;\n updatable = scene;\n }\n scene = subdivisions;\n subdivisions = 1;\n }\n const options = {\n height,\n diameterTop,\n diameterBottom,\n tessellation,\n subdivisions,\n sideOrientation,\n updatable,\n };\n return CreateCylinder(name, options, scene);\n};\n//# sourceMappingURL=cylinderBuilder.js.map","import { Matrix, Vector3, Vector2 } from \"../../Maths/math.vector.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n/**\n * Creates the VertexData for a torus\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * diameter the diameter of the torus, optional default 1\n * * thickness the diameter of the tube forming the torus, optional default 0.5\n * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.diameter\n * @param options.thickness\n * @param options.tessellation\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the torus\n */\nexport function CreateTorusVertexData(options) {\n const indices = [];\n const positions = [];\n const normals = [];\n const uvs = [];\n const diameter = options.diameter || 1;\n const thickness = options.thickness || 0.5;\n const tessellation = options.tessellation || 16;\n const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;\n const stride = tessellation + 1;\n for (let i = 0; i <= tessellation; i++) {\n const u = i / tessellation;\n const outerAngle = (i * Math.PI * 2.0) / tessellation - Math.PI / 2.0;\n const transform = Matrix.Translation(diameter / 2.0, 0, 0).multiply(Matrix.RotationY(outerAngle));\n for (let j = 0; j <= tessellation; j++) {\n const v = 1 - j / tessellation;\n const innerAngle = (j * Math.PI * 2.0) / tessellation + Math.PI;\n const dx = Math.cos(innerAngle);\n const dy = Math.sin(innerAngle);\n // Create a vertex.\n let normal = new Vector3(dx, dy, 0);\n let position = normal.scale(thickness / 2);\n const textureCoordinate = new Vector2(u, v);\n position = Vector3.TransformCoordinates(position, transform);\n normal = Vector3.TransformNormal(normal, transform);\n positions.push(position.x, position.y, position.z);\n normals.push(normal.x, normal.y, normal.z);\n uvs.push(textureCoordinate.x, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - textureCoordinate.y : textureCoordinate.y);\n // And create indices for two triangles.\n const nextI = (i + 1) % stride;\n const nextJ = (j + 1) % stride;\n indices.push(i * stride + j);\n indices.push(i * stride + nextJ);\n indices.push(nextI * stride + j);\n indices.push(i * stride + nextJ);\n indices.push(nextI * stride + nextJ);\n indices.push(nextI * stride + j);\n }\n }\n // Sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Result\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n}\n/**\n * Creates a torus mesh\n * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)\n * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)\n * * The parameter `tessellation` sets the number of torus sides (positive integer, default 16)\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.diameter\n * @param options.thickness\n * @param options.tessellation\n * @param options.updatable\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param scene defines the hosting scene\n * @returns the torus mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#torus\n */\nexport function CreateTorus(name, options = {}, scene) {\n const torus = new Mesh(name, scene);\n options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n torus._originalBuilderSideOrientation = options.sideOrientation;\n const vertexData = CreateTorusVertexData(options);\n vertexData.applyToMesh(torus, options.updatable);\n return torus;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use CreateTorus instead\n */\nexport const TorusBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateTorus,\n};\nVertexData.CreateTorus = CreateTorusVertexData;\nMesh.CreateTorus = (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) => {\n const options = {\n diameter,\n thickness,\n tessellation,\n sideOrientation,\n updatable,\n };\n return CreateTorus(name, options, scene);\n};\n//# sourceMappingURL=torusBuilder.js.map","import { Vector3, Vector2, TmpVectors, Vector4 } from \"../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nMesh._GroundMeshParser = (parsedMesh, scene) => {\n return GroundMesh.Parse(parsedMesh, scene);\n};\n/**\n * Mesh representing the ground\n */\nexport class GroundMesh extends Mesh {\n constructor(name, scene) {\n super(name, scene);\n /** If octree should be generated */\n this.generateOctree = false;\n }\n /**\n * \"GroundMesh\"\n * @returns \"GroundMesh\"\n */\n getClassName() {\n return \"GroundMesh\";\n }\n /**\n * The minimum of x and y subdivisions\n */\n get subdivisions() {\n return Math.min(this._subdivisionsX, this._subdivisionsY);\n }\n /**\n * X subdivisions\n */\n get subdivisionsX() {\n return this._subdivisionsX;\n }\n /**\n * Y subdivisions\n */\n get subdivisionsY() {\n return this._subdivisionsY;\n }\n /**\n * This function will divide the mesh into submeshes and update an octree to help to select the right submeshes\n * for rendering, picking and collision computations. Please note that you must have a decent number of submeshes\n * to get performance improvements when using an octree.\n * @param chunksCount the number of submeshes the mesh will be divided into\n * @param octreeBlocksSize the maximum size of the octree blocks (Default: 32)\n */\n optimize(chunksCount, octreeBlocksSize = 32) {\n this._subdivisionsX = chunksCount;\n this._subdivisionsY = chunksCount;\n this.subdivide(chunksCount);\n // Call the octree system optimization if it is defined.\n const thisAsAny = this;\n if (thisAsAny.createOrUpdateSubmeshesOctree) {\n thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);\n }\n }\n /**\n * Returns a height (y) value in the World system :\n * the ground altitude at the coordinates (x, z) expressed in the World system.\n * @param x x coordinate\n * @param z z coordinate\n * @returns the ground y position if (x, z) are outside the ground surface.\n */\n getHeightAtCoordinates(x, z) {\n const world = this.getWorldMatrix();\n const invMat = TmpVectors.Matrix[5];\n world.invertToRef(invMat);\n const tmpVect = TmpVectors.Vector3[8];\n Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space\n x = tmpVect.x;\n z = tmpVect.z;\n if (x < this._minX || x >= this._maxX || z <= this._minZ || z > this._maxZ) {\n return this.position.y;\n }\n if (!this._heightQuads || this._heightQuads.length == 0) {\n this._initHeightQuads();\n this._computeHeightQuads();\n }\n const facet = this._getFacetAt(x, z);\n const y = -(facet.x * x + facet.z * z + facet.w) / facet.y;\n // return y in the World system\n Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);\n return tmpVect.y;\n }\n /**\n * Returns a normalized vector (Vector3) orthogonal to the ground\n * at the ground coordinates (x, z) expressed in the World system.\n * @param x x coordinate\n * @param z z coordinate\n * @returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.\n */\n getNormalAtCoordinates(x, z) {\n const normal = new Vector3(0.0, 1.0, 0.0);\n this.getNormalAtCoordinatesToRef(x, z, normal);\n return normal;\n }\n /**\n * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground\n * at the ground coordinates (x, z) expressed in the World system.\n * Doesn't update the reference Vector3 if (x, z) are outside the ground surface.\n * @param x x coordinate\n * @param z z coordinate\n * @param ref vector to store the result\n * @returns the GroundMesh.\n */\n getNormalAtCoordinatesToRef(x, z, ref) {\n const world = this.getWorldMatrix();\n const tmpMat = TmpVectors.Matrix[5];\n world.invertToRef(tmpMat);\n const tmpVect = TmpVectors.Vector3[8];\n Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space\n x = tmpVect.x;\n z = tmpVect.z;\n if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {\n return this;\n }\n if (!this._heightQuads || this._heightQuads.length == 0) {\n this._initHeightQuads();\n this._computeHeightQuads();\n }\n const facet = this._getFacetAt(x, z);\n Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);\n return this;\n }\n /**\n * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()\n * if the ground has been updated.\n * This can be used in the render loop.\n * @returns the GroundMesh.\n */\n updateCoordinateHeights() {\n if (!this._heightQuads || this._heightQuads.length == 0) {\n this._initHeightQuads();\n }\n this._computeHeightQuads();\n return this;\n }\n // Returns the element \"facet\" from the heightQuads array relative to (x, z) local coordinates\n _getFacetAt(x, z) {\n // retrieve col and row from x, z coordinates in the ground local system\n const col = Math.floor(((x + this._maxX) * this._subdivisionsX) / this._width);\n const row = Math.floor((-(z + this._maxZ) * this._subdivisionsY) / this._height + this._subdivisionsY);\n const quad = this._heightQuads[row * this._subdivisionsX + col];\n let facet;\n if (z < quad.slope.x * x + quad.slope.y) {\n facet = quad.facet1;\n }\n else {\n facet = quad.facet2;\n }\n return facet;\n }\n // Creates and populates the heightMap array with \"facet\" elements :\n // a quad is two triangular facets separated by a slope, so a \"facet\" element is 1 slope + 2 facets\n // slope : Vector2(c, h) = 2D diagonal line equation setting apart two triangular facets in a quad : z = cx + h\n // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0\n // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0\n // Returns the GroundMesh.\n _initHeightQuads() {\n const subdivisionsX = this._subdivisionsX;\n const subdivisionsY = this._subdivisionsY;\n this._heightQuads = new Array();\n for (let row = 0; row < subdivisionsY; row++) {\n for (let col = 0; col < subdivisionsX; col++) {\n const quad = { slope: Vector2.Zero(), facet1: new Vector4(0.0, 0.0, 0.0, 0.0), facet2: new Vector4(0.0, 0.0, 0.0, 0.0) };\n this._heightQuads[row * subdivisionsX + col] = quad;\n }\n }\n return this;\n }\n // Compute each quad element values and update the the heightMap array :\n // slope : Vector2(c, h) = 2D diagonal line equation setting apart two triangular facets in a quad : z = cx + h\n // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0\n // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0\n // Returns the GroundMesh.\n _computeHeightQuads() {\n const positions = this.getVerticesData(VertexBuffer.PositionKind);\n if (!positions) {\n return this;\n }\n const v1 = TmpVectors.Vector3[3];\n const v2 = TmpVectors.Vector3[2];\n const v3 = TmpVectors.Vector3[1];\n const v4 = TmpVectors.Vector3[0];\n const v1v2 = TmpVectors.Vector3[4];\n const v1v3 = TmpVectors.Vector3[5];\n const v1v4 = TmpVectors.Vector3[6];\n const norm1 = TmpVectors.Vector3[7];\n const norm2 = TmpVectors.Vector3[8];\n let i = 0;\n let j = 0;\n let k = 0;\n let cd = 0; // 2D slope coefficient : z = cd * x + h\n let h = 0;\n let d1 = 0; // facet plane equation : ax + by + cz + d = 0\n let d2 = 0;\n const subdivisionsX = this._subdivisionsX;\n const subdivisionsY = this._subdivisionsY;\n for (let row = 0; row < subdivisionsY; row++) {\n for (let col = 0; col < subdivisionsX; col++) {\n i = col * 3;\n j = row * (subdivisionsX + 1) * 3;\n k = (row + 1) * (subdivisionsX + 1) * 3;\n v1.x = positions[j + i];\n v1.y = positions[j + i + 1];\n v1.z = positions[j + i + 2];\n v2.x = positions[j + i + 3];\n v2.y = positions[j + i + 4];\n v2.z = positions[j + i + 5];\n v3.x = positions[k + i];\n v3.y = positions[k + i + 1];\n v3.z = positions[k + i + 2];\n v4.x = positions[k + i + 3];\n v4.y = positions[k + i + 4];\n v4.z = positions[k + i + 5];\n // 2D slope V1V4\n cd = (v4.z - v1.z) / (v4.x - v1.x);\n h = v1.z - cd * v1.x; // v1 belongs to the slope\n // facet equations :\n // we compute each facet normal vector\n // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0\n // we compute the value d by applying the equation to v1 which belongs to the plane\n // then we store the facet equation in a Vector4\n v2.subtractToRef(v1, v1v2);\n v3.subtractToRef(v1, v1v3);\n v4.subtractToRef(v1, v1v4);\n Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class\n Vector3.CrossToRef(v1v2, v1v4, norm2);\n norm1.normalize();\n norm2.normalize();\n d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);\n d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);\n const quad = this._heightQuads[row * subdivisionsX + col];\n quad.slope.copyFromFloats(cd, h);\n quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);\n quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);\n }\n }\n return this;\n }\n /**\n * Serializes this ground mesh\n * @param serializationObject object to write serialization to\n */\n serialize(serializationObject) {\n super.serialize(serializationObject);\n serializationObject.subdivisionsX = this._subdivisionsX;\n serializationObject.subdivisionsY = this._subdivisionsY;\n serializationObject.minX = this._minX;\n serializationObject.maxX = this._maxX;\n serializationObject.minZ = this._minZ;\n serializationObject.maxZ = this._maxZ;\n serializationObject.width = this._width;\n serializationObject.height = this._height;\n }\n /**\n * Parses a serialized ground mesh\n * @param parsedMesh the serialized mesh\n * @param scene the scene to create the ground mesh in\n * @returns the created ground mesh\n */\n static Parse(parsedMesh, scene) {\n const result = new GroundMesh(parsedMesh.name, scene);\n result._subdivisionsX = parsedMesh.subdivisionsX || 1;\n result._subdivisionsY = parsedMesh.subdivisionsY || 1;\n result._minX = parsedMesh.minX;\n result._maxX = parsedMesh.maxX;\n result._minZ = parsedMesh.minZ;\n result._maxZ = parsedMesh.maxZ;\n result._width = parsedMesh.width;\n result._height = parsedMesh.height;\n return result;\n }\n}\n//# sourceMappingURL=groundMesh.js.map","import { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Color3 } from \"../../Maths/math.color.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { GroundMesh } from \"../groundMesh.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nimport { EngineStore } from \"../../Engines/engineStore.js\";\nimport { Epsilon } from \"../../Maths/math.constants.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n/**\n * Creates the VertexData for a Ground\n * @param options an object used to set the following optional parameters for the Ground, required but can be empty\n * - width the width (x direction) of the ground, optional, default 1\n * - height the height (z direction) of the ground, optional, default 1\n * - subdivisions the number of subdivisions per side, optional, default 1\n * @param options.width\n * @param options.height\n * @param options.subdivisions\n * @param options.subdivisionsX\n * @param options.subdivisionsY\n * @returns the VertexData of the Ground\n */\nexport function CreateGroundVertexData(options) {\n const indices = [];\n const positions = [];\n const normals = [];\n const uvs = [];\n let row, col;\n const width = options.width || 1;\n const height = options.height || 1;\n const subdivisionsX = options.subdivisionsX || options.subdivisions || 1;\n const subdivisionsY = options.subdivisionsY || options.subdivisions || 1;\n for (row = 0; row <= subdivisionsY; row++) {\n for (col = 0; col <= subdivisionsX; col++) {\n const position = new Vector3((col * width) / subdivisionsX - width / 2.0, 0, ((subdivisionsY - row) * height) / subdivisionsY - height / 2.0);\n const normal = new Vector3(0, 1.0, 0);\n positions.push(position.x, position.y, position.z);\n normals.push(normal.x, normal.y, normal.z);\n uvs.push(col / subdivisionsX, CompatibilityOptions.UseOpenGLOrientationForUV ? row / subdivisionsY : 1.0 - row / subdivisionsY);\n }\n }\n for (row = 0; row < subdivisionsY; row++) {\n for (col = 0; col < subdivisionsX; col++) {\n indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));\n indices.push(col + 1 + row * (subdivisionsX + 1));\n indices.push(col + row * (subdivisionsX + 1));\n indices.push(col + (row + 1) * (subdivisionsX + 1));\n indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));\n indices.push(col + row * (subdivisionsX + 1));\n }\n }\n // Result\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n}\n/**\n * Creates the VertexData for a TiledGround by subdividing the ground into tiles\n * @param options an object used to set the following optional parameters for the Ground, required but can be empty\n * * xmin the ground minimum X coordinate, optional, default -1\n * * zmin the ground minimum Z coordinate, optional, default -1\n * * xmax the ground maximum X coordinate, optional, default 1\n * * zmax the ground maximum Z coordinate, optional, default 1\n * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}\n * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}\n * @param options.xmin\n * @param options.zmin\n * @param options.xmax\n * @param options.zmax\n * @param options.subdivisions\n * @param options.subdivisions.w\n * @param options.subdivisions.h\n * @param options.precision\n * @param options.precision.w\n * @param options.precision.h\n * @returns the VertexData of the TiledGround\n */\nexport function CreateTiledGroundVertexData(options) {\n const xmin = options.xmin !== undefined && options.xmin !== null ? options.xmin : -1.0;\n const zmin = options.zmin !== undefined && options.zmin !== null ? options.zmin : -1.0;\n const xmax = options.xmax !== undefined && options.xmax !== null ? options.xmax : 1.0;\n const zmax = options.zmax !== undefined && options.zmax !== null ? options.zmax : 1.0;\n const subdivisions = options.subdivisions || { w: 1, h: 1 };\n const precision = options.precision || { w: 1, h: 1 };\n const indices = new Array();\n const positions = new Array();\n const normals = new Array();\n const uvs = new Array();\n let row, col, tileRow, tileCol;\n subdivisions.h = subdivisions.h < 1 ? 1 : subdivisions.h;\n subdivisions.w = subdivisions.w < 1 ? 1 : subdivisions.w;\n precision.w = precision.w < 1 ? 1 : precision.w;\n precision.h = precision.h < 1 ? 1 : precision.h;\n const tileSize = {\n w: (xmax - xmin) / subdivisions.w,\n h: (zmax - zmin) / subdivisions.h,\n };\n function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {\n // Indices\n const base = positions.length / 3;\n const rowLength = precision.w + 1;\n for (row = 0; row < precision.h; row++) {\n for (col = 0; col < precision.w; col++) {\n const square = [base + col + row * rowLength, base + (col + 1) + row * rowLength, base + (col + 1) + (row + 1) * rowLength, base + col + (row + 1) * rowLength];\n indices.push(square[1]);\n indices.push(square[2]);\n indices.push(square[3]);\n indices.push(square[0]);\n indices.push(square[1]);\n indices.push(square[3]);\n }\n }\n // Position, normals and uvs\n const position = Vector3.Zero();\n const normal = new Vector3(0, 1.0, 0);\n for (row = 0; row <= precision.h; row++) {\n position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;\n for (col = 0; col <= precision.w; col++) {\n position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;\n position.y = 0;\n positions.push(position.x, position.y, position.z);\n normals.push(normal.x, normal.y, normal.z);\n uvs.push(col / precision.w, row / precision.h);\n }\n }\n }\n for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {\n for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {\n applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);\n }\n }\n // Result\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n}\n/**\n * Creates the VertexData of the Ground designed from a heightmap\n * @param options an object used to set the following parameters for the Ground, required and provided by CreateGroundFromHeightMap\n * * width the width (x direction) of the ground\n * * height the height (z direction) of the ground\n * * subdivisions the number of subdivisions per side\n * * minHeight the minimum altitude on the ground, optional, default 0\n * * maxHeight the maximum altitude on the ground, optional default 1\n * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)\n * * buffer the array holding the image color data\n * * bufferWidth the width of image\n * * bufferHeight the height of image\n * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)\n * @param options.width\n * @param options.height\n * @param options.subdivisions\n * @param options.minHeight\n * @param options.maxHeight\n * @param options.colorFilter\n * @param options.buffer\n * @param options.bufferWidth\n * @param options.bufferHeight\n * @param options.alphaFilter\n * @returns the VertexData of the Ground designed from a heightmap\n */\nexport function CreateGroundFromHeightMapVertexData(options) {\n const indices = [];\n const positions = [];\n const normals = [];\n const uvs = [];\n let row, col;\n const filter = options.colorFilter || new Color3(0.3, 0.59, 0.11);\n const alphaFilter = options.alphaFilter || 0.0;\n let invert = false;\n if (options.minHeight > options.maxHeight) {\n invert = true;\n const temp = options.maxHeight;\n options.maxHeight = options.minHeight;\n options.minHeight = temp;\n }\n // Vertices\n for (row = 0; row <= options.subdivisions; row++) {\n for (col = 0; col <= options.subdivisions; col++) {\n const position = new Vector3((col * options.width) / options.subdivisions - options.width / 2.0, 0, ((options.subdivisions - row) * options.height) / options.subdivisions - options.height / 2.0);\n // Compute height\n const heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;\n const heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;\n const pos = (heightMapX + heightMapY * options.bufferWidth) * 4;\n let r = options.buffer[pos] / 255.0;\n let g = options.buffer[pos + 1] / 255.0;\n let b = options.buffer[pos + 2] / 255.0;\n const a = options.buffer[pos + 3] / 255.0;\n if (invert) {\n r = 1.0 - r;\n g = 1.0 - g;\n b = 1.0 - b;\n }\n const gradient = r * filter.r + g * filter.g + b * filter.b;\n // If our alpha channel is not within our filter then we will assign a 'special' height\n // Then when building the indices, we will ignore any vertex that is using the special height\n if (a >= alphaFilter) {\n position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;\n }\n else {\n position.y = options.minHeight - Epsilon; // We can't have a height below minHeight, normally.\n }\n // Add vertex\n positions.push(position.x, position.y, position.z);\n normals.push(0, 0, 0);\n uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);\n }\n }\n // Indices\n for (row = 0; row < options.subdivisions; row++) {\n for (col = 0; col < options.subdivisions; col++) {\n // Calculate Indices\n const idx1 = col + 1 + (row + 1) * (options.subdivisions + 1);\n const idx2 = col + 1 + row * (options.subdivisions + 1);\n const idx3 = col + row * (options.subdivisions + 1);\n const idx4 = col + (row + 1) * (options.subdivisions + 1);\n // Check that all indices are visible (based on our special height)\n // Only display the vertex if all Indices are visible\n // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height\n const isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;\n const isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;\n const isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;\n if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {\n indices.push(idx1);\n indices.push(idx2);\n indices.push(idx3);\n }\n const isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;\n if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {\n indices.push(idx4);\n indices.push(idx1);\n indices.push(idx3);\n }\n }\n }\n // Normals\n VertexData.ComputeNormals(positions, indices, normals);\n // Result\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n}\n/**\n * Creates a ground mesh\n * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground\n * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.width\n * @param options.height\n * @param options.subdivisions\n * @param options.subdivisionsX\n * @param options.subdivisionsY\n * @param options.updatable\n * @param scene defines the hosting scene\n * @returns the ground mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#ground\n */\nexport function CreateGround(name, options = {}, scene) {\n const ground = new GroundMesh(name, scene);\n ground._setReady(false);\n ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;\n ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;\n ground._width = options.width || 1;\n ground._height = options.height || 1;\n ground._maxX = ground._width / 2;\n ground._maxZ = ground._height / 2;\n ground._minX = -ground._maxX;\n ground._minZ = -ground._maxZ;\n const vertexData = CreateGroundVertexData(options);\n vertexData.applyToMesh(ground, options.updatable);\n ground._setReady(true);\n return ground;\n}\n/**\n * Creates a tiled ground mesh\n * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates\n * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates\n * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile\n * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.xmin\n * @param options.zmin\n * @param options.xmax\n * @param options.zmax\n * @param options.subdivisions\n * @param options.subdivisions.w\n * @param options.subdivisions.h\n * @param options.precision\n * @param options.precision.w\n * @param options.precision.h\n * @param options.updatable\n * @param scene defines the hosting scene\n * @returns the tiled ground mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#tiled-ground\n */\nexport function CreateTiledGround(name, options, scene = null) {\n const tiledGround = new Mesh(name, scene);\n const vertexData = CreateTiledGroundVertexData(options);\n vertexData.applyToMesh(tiledGround, options.updatable);\n return tiledGround;\n}\n/**\n * Creates a ground mesh from a height map\n * * The parameter `url` sets the URL of the height map image resource.\n * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.\n * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.\n * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.\n * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.\n * * The parameter `colorFilter` (optional Color3, default (0.3, 0.59, 0.11) ) is the filter to apply to the image pixel colors to compute the height.\n * * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).\n * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n * @param name defines the name of the mesh\n * @param url defines the url to the height map\n * @param options defines the options used to create the mesh\n * @param options.width\n * @param options.height\n * @param options.subdivisions\n * @param options.minHeight\n * @param options.maxHeight\n * @param options.colorFilter\n * @param options.alphaFilter\n * @param options.updatable\n * @param options.onReady\n * @param scene defines the hosting scene\n * @returns the ground mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/height_map\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#ground-from-a-height-map\n */\nexport function CreateGroundFromHeightMap(name, url, options = {}, scene = null) {\n const width = options.width || 10.0;\n const height = options.height || 10.0;\n const subdivisions = options.subdivisions || 1 | 0;\n const minHeight = options.minHeight || 0.0;\n const maxHeight = options.maxHeight || 1.0;\n const filter = options.colorFilter || new Color3(0.3, 0.59, 0.11);\n const alphaFilter = options.alphaFilter || 0.0;\n const updatable = options.updatable;\n const onReady = options.onReady;\n scene = scene || EngineStore.LastCreatedScene;\n const ground = new GroundMesh(name, scene);\n ground._subdivisionsX = subdivisions;\n ground._subdivisionsY = subdivisions;\n ground._width = width;\n ground._height = height;\n ground._maxX = ground._width / 2.0;\n ground._maxZ = ground._height / 2.0;\n ground._minX = -ground._maxX;\n ground._minZ = -ground._maxZ;\n ground._setReady(false);\n const onload = (img) => {\n const bufferWidth = img.width;\n const bufferHeight = img.height;\n if (scene.isDisposed) {\n return;\n }\n const buffer = scene === null || scene === void 0 ? void 0 : scene.getEngine().resizeImageBitmap(img, bufferWidth, bufferHeight);\n const vertexData = CreateGroundFromHeightMapVertexData({\n width: width,\n height: height,\n subdivisions: subdivisions,\n minHeight: minHeight,\n maxHeight: maxHeight,\n colorFilter: filter,\n buffer: buffer,\n bufferWidth: bufferWidth,\n bufferHeight: bufferHeight,\n alphaFilter: alphaFilter,\n });\n vertexData.applyToMesh(ground, updatable);\n //execute ready callback, if set\n if (onReady) {\n onReady(ground);\n }\n ground._setReady(true);\n };\n Tools.LoadImage(url, onload, () => { }, scene.offlineProvider);\n return ground;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use the functions directly from the module\n */\nexport const GroundBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateGround,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateGroundFromHeightMap,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateTiledGround,\n};\nVertexData.CreateGround = CreateGroundVertexData;\nVertexData.CreateTiledGround = CreateTiledGroundVertexData;\nVertexData.CreateGroundFromHeightMap = CreateGroundFromHeightMapVertexData;\nMesh.CreateGround = (name, width, height, subdivisions, scene, updatable) => {\n const options = {\n width,\n height,\n subdivisions,\n updatable,\n };\n return CreateGround(name, options, scene);\n};\nMesh.CreateTiledGround = (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) => {\n const options = {\n xmin,\n zmin,\n xmax,\n zmax,\n subdivisions,\n precision,\n updatable,\n };\n return CreateTiledGround(name, options, scene);\n};\nMesh.CreateGroundFromHeightMap = (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) => {\n const options = {\n width,\n height,\n subdivisions,\n minHeight,\n maxHeight,\n updatable,\n onReady,\n alphaFilter,\n };\n return CreateGroundFromHeightMap(name, url, options, scene);\n};\n//# sourceMappingURL=groundBuilder.js.map","import { Logger } from \"../../Misc/logger.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { FreeCamera } from \"../../Cameras/freeCamera.js\";\nimport { TargetCamera } from \"../../Cameras/targetCamera.js\";\nimport { DeviceOrientationCamera } from \"../../Cameras/deviceOrientationCamera.js\";\nimport { VRDeviceOrientationFreeCamera } from \"../../Cameras/VR/vrDeviceOrientationFreeCamera.js\";\nimport { WebVRFreeCamera } from \"../../Cameras/VR/webVRCamera.js\";\nimport { PointerEventTypes } from \"../../Events/pointerEvents.js\";\nimport { Quaternion, Matrix, Vector3 } from \"../../Maths/math.vector.js\";\nimport { Color3, Color4 } from \"../../Maths/math.color.js\";\nimport { Gamepad } from \"../../Gamepads/gamepad.js\";\nimport { PoseEnabledController, PoseEnabledControllerType } from \"../../Gamepads/Controllers/poseEnabledController.js\";\nimport { WebVRController } from \"../../Gamepads/Controllers/webVRController.js\";\nimport { Xbox360Button } from \"../../Gamepads/xboxGamepad.js\";\nimport { Mesh } from \"../../Meshes/mesh.js\";\nimport { Ray } from \"../../Culling/ray.js\";\nimport { ImageProcessingConfiguration } from \"../../Materials/imageProcessingConfiguration.js\";\nimport { StandardMaterial } from \"../../Materials/standardMaterial.js\";\nimport { DynamicTexture } from \"../../Materials/Textures/dynamicTexture.js\";\nimport { ImageProcessingPostProcess } from \"../../PostProcesses/imageProcessingPostProcess.js\";\nimport { SineEase, EasingFunction, CircleEase } from \"../../Animations/easing.js\";\nimport { Animation } from \"../../Animations/animation.js\";\nimport { VRCameraMetrics } from \"../../Cameras/VR/vrCameraMetrics.js\";\nimport \"../../Gamepads/gamepadSceneComponent.js\";\nimport \"../../Animations/animatable.js\";\nimport { Axis } from \"../../Maths/math.axis.js\";\nimport { WebXRSessionManager } from \"../../XR/webXRSessionManager.js\";\nimport { WebXRState } from \"../../XR/webXRTypes.js\";\nimport { CreateCylinder } from \"../../Meshes/Builders/cylinderBuilder.js\";\nimport { CreateTorus } from \"../../Meshes/Builders/torusBuilder.js\";\nimport { CreateGround } from \"../../Meshes/Builders/groundBuilder.js\";\nclass VRExperienceHelperGazer {\n constructor(scene, gazeTrackerToClone = null) {\n this.scene = scene;\n /** @internal */\n this._pointerDownOnMeshAsked = false;\n /** @internal */\n this._isActionableMesh = false;\n /** @internal */\n this._teleportationRequestInitiated = false;\n /** @internal */\n this._teleportationBackRequestInitiated = false;\n /** @internal */\n this._rotationRightAsked = false;\n /** @internal */\n this._rotationLeftAsked = false;\n /** @internal */\n this._dpadPressed = true;\n /** @internal */\n this._activePointer = false;\n this._id = VRExperienceHelperGazer._IdCounter++;\n // Gaze tracker\n if (!gazeTrackerToClone) {\n this._gazeTracker = CreateTorus(\"gazeTracker\", {\n diameter: 0.0035,\n thickness: 0.0025,\n tessellation: 20,\n updatable: false,\n }, scene);\n this._gazeTracker.bakeCurrentTransformIntoVertices();\n this._gazeTracker.isPickable = false;\n this._gazeTracker.isVisible = false;\n const targetMat = new StandardMaterial(\"targetMat\", scene);\n targetMat.specularColor = Color3.Black();\n targetMat.emissiveColor = new Color3(0.7, 0.7, 0.7);\n targetMat.backFaceCulling = false;\n this._gazeTracker.material = targetMat;\n }\n else {\n this._gazeTracker = gazeTrackerToClone.clone(\"gazeTracker\");\n }\n }\n /**\n * @internal\n */\n _getForwardRay(length) {\n return new Ray(Vector3.Zero(), new Vector3(0, 0, length));\n }\n /** @internal */\n _selectionPointerDown() {\n this._pointerDownOnMeshAsked = true;\n if (this._currentHit) {\n this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });\n }\n }\n /** @internal */\n _selectionPointerUp() {\n if (this._currentHit) {\n this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });\n }\n this._pointerDownOnMeshAsked = false;\n }\n /** @internal */\n _activatePointer() {\n this._activePointer = true;\n }\n /** @internal */\n _deactivatePointer() {\n this._activePointer = false;\n }\n /**\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _updatePointerDistance(distance = 100) { }\n dispose() {\n this._interactionsEnabled = false;\n this._teleportationEnabled = false;\n if (this._gazeTracker) {\n this._gazeTracker.dispose();\n }\n }\n}\nVRExperienceHelperGazer._IdCounter = 0;\nclass VRExperienceHelperControllerGazer extends VRExperienceHelperGazer {\n constructor(webVRController, scene, gazeTrackerToClone) {\n super(scene, gazeTrackerToClone);\n this.webVRController = webVRController;\n // Laser pointer\n this._laserPointer = CreateCylinder(\"laserPointer\", {\n updatable: false,\n height: 1,\n diameterTop: 0.004,\n diameterBottom: 0.0002,\n tessellation: 20,\n subdivisions: 1,\n }, scene);\n const laserPointerMaterial = new StandardMaterial(\"laserPointerMat\", scene);\n laserPointerMaterial.emissiveColor = new Color3(0.7, 0.7, 0.7);\n laserPointerMaterial.alpha = 0.6;\n this._laserPointer.material = laserPointerMaterial;\n this._laserPointer.rotation.x = Math.PI / 2;\n this._laserPointer.position.z = -0.5;\n this._laserPointer.isVisible = false;\n this._laserPointer.isPickable = false;\n if (!webVRController.mesh) {\n // Create an empty mesh that is used prior to loading the high quality model\n const preloadMesh = new Mesh(\"preloadControllerMesh\", scene);\n const preloadPointerPose = new Mesh(PoseEnabledController.POINTING_POSE, scene);\n preloadPointerPose.rotation.x = -0.7;\n preloadMesh.addChild(preloadPointerPose);\n webVRController.attachToMesh(preloadMesh);\n }\n this._setLaserPointerParent(webVRController.mesh);\n this._meshAttachedObserver = webVRController._meshAttachedObservable.add((mesh) => {\n this._setLaserPointerParent(mesh);\n });\n }\n _getForwardRay(length) {\n return this.webVRController.getForwardRay(length);\n }\n /** @internal */\n _activatePointer() {\n super._activatePointer();\n this._laserPointer.isVisible = true;\n }\n /** @internal */\n _deactivatePointer() {\n super._deactivatePointer();\n this._laserPointer.isVisible = false;\n }\n /**\n * @internal\n */\n _setLaserPointerColor(color) {\n this._laserPointer.material.emissiveColor = color;\n }\n /**\n * @internal\n */\n _setLaserPointerLightingDisabled(disabled) {\n this._laserPointer.material.disableLighting = disabled;\n }\n /**\n * @internal\n */\n _setLaserPointerParent(mesh) {\n const makeNotPick = (root) => {\n root.isPickable = false;\n root.getChildMeshes().forEach((c) => {\n makeNotPick(c);\n });\n };\n makeNotPick(mesh);\n const meshChildren = mesh.getChildren(undefined, false);\n let laserParent = mesh;\n this.webVRController._pointingPoseNode = null;\n for (let i = 0; i < meshChildren.length; i++) {\n if (meshChildren[i].name && meshChildren[i].name.indexOf(PoseEnabledController.POINTING_POSE) >= 0) {\n laserParent = meshChildren[i];\n this.webVRController._pointingPoseNode = laserParent;\n break;\n }\n }\n this._laserPointer.parent = laserParent;\n }\n _updatePointerDistance(distance = 100) {\n this._laserPointer.scaling.y = distance;\n this._laserPointer.position.z = -distance / 2;\n }\n dispose() {\n super.dispose();\n this._laserPointer.dispose();\n if (this._meshAttachedObserver) {\n this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);\n }\n }\n}\nclass VRExperienceHelperCameraGazer extends VRExperienceHelperGazer {\n constructor(_getCamera, scene) {\n super(scene);\n this._getCamera = _getCamera;\n }\n _getForwardRay(length) {\n const camera = this._getCamera();\n if (camera) {\n return camera.getForwardRay(length);\n }\n else {\n return new Ray(Vector3.Zero(), Vector3.Forward());\n }\n }\n}\n/**\n * Event containing information after VR has been entered\n */\nexport class OnAfterEnteringVRObservableEvent {\n}\n/**\n * Helps to quickly add VR support to an existing scene.\n * See https://doc.babylonjs.com/features/featuresDeepDive/cameras/webVRHelper\n * @deprecated\n */\nexport class VRExperienceHelper {\n /** Return this.onEnteringVRObservable\n * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly\n */\n get onEnteringVR() {\n return this.onEnteringVRObservable;\n }\n /** Return this.onExitingVRObservable\n * Note: This one is for backward compatibility. Please use onExitingVRObservable directly\n */\n get onExitingVR() {\n return this.onExitingVRObservable;\n }\n /** Return this.onControllerMeshLoadedObservable\n * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly\n */\n get onControllerMeshLoaded() {\n return this.onControllerMeshLoadedObservable;\n }\n /**\n * The mesh used to display where the user is going to teleport.\n */\n get teleportationTarget() {\n return this._teleportationTarget;\n }\n /**\n * Sets the mesh to be used to display where the user is going to teleport.\n */\n set teleportationTarget(value) {\n if (value) {\n value.name = \"teleportationTarget\";\n this._isDefaultTeleportationTarget = false;\n this._teleportationTarget = value;\n }\n }\n /**\n * The mesh used to display where the user is selecting, this mesh will be cloned and set as the gazeTracker for the left and right controller\n * when set bakeCurrentTransformIntoVertices will be called on the mesh.\n * See https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/bakingTransforms\n */\n get gazeTrackerMesh() {\n return this._cameraGazer._gazeTracker;\n }\n set gazeTrackerMesh(value) {\n if (value) {\n // Dispose of existing meshes\n if (this._cameraGazer._gazeTracker) {\n this._cameraGazer._gazeTracker.dispose();\n }\n if (this._leftController && this._leftController._gazeTracker) {\n this._leftController._gazeTracker.dispose();\n }\n if (this._rightController && this._rightController._gazeTracker) {\n this._rightController._gazeTracker.dispose();\n }\n // Set and create gaze trackers on head and controllers\n this._cameraGazer._gazeTracker = value;\n this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();\n this._cameraGazer._gazeTracker.isPickable = false;\n this._cameraGazer._gazeTracker.isVisible = false;\n this._cameraGazer._gazeTracker.name = \"gazeTracker\";\n if (this._leftController) {\n this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone(\"gazeTracker\");\n }\n if (this._rightController) {\n this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone(\"gazeTracker\");\n }\n }\n }\n /**\n * The gaze tracking mesh corresponding to the left controller\n */\n get leftControllerGazeTrackerMesh() {\n if (this._leftController) {\n return this._leftController._gazeTracker;\n }\n return null;\n }\n /**\n * The gaze tracking mesh corresponding to the right controller\n */\n get rightControllerGazeTrackerMesh() {\n if (this._rightController) {\n return this._rightController._gazeTracker;\n }\n return null;\n }\n /**\n * If the ray of the gaze should be displayed.\n */\n get displayGaze() {\n return this._displayGaze;\n }\n /**\n * Sets if the ray of the gaze should be displayed.\n */\n set displayGaze(value) {\n this._displayGaze = value;\n if (!value) {\n this._cameraGazer._gazeTracker.isVisible = false;\n if (this._leftController) {\n this._leftController._gazeTracker.isVisible = false;\n }\n if (this._rightController) {\n this._rightController._gazeTracker.isVisible = false;\n }\n }\n }\n /**\n * If the ray of the LaserPointer should be displayed.\n */\n get displayLaserPointer() {\n return this._displayLaserPointer;\n }\n /**\n * Sets if the ray of the LaserPointer should be displayed.\n */\n set displayLaserPointer(value) {\n this._displayLaserPointer = value;\n if (!value) {\n if (this._rightController) {\n this._rightController._deactivatePointer();\n this._rightController._gazeTracker.isVisible = false;\n }\n if (this._leftController) {\n this._leftController._deactivatePointer();\n this._leftController._gazeTracker.isVisible = false;\n }\n }\n else {\n if (this._rightController) {\n this._rightController._activatePointer();\n }\n if (this._leftController) {\n this._leftController._activatePointer();\n }\n }\n }\n /**\n * The deviceOrientationCamera used as the camera when not in VR.\n */\n get deviceOrientationCamera() {\n return this._deviceOrientationCamera;\n }\n /**\n * Based on the current WebVR support, returns the current VR camera used.\n */\n get currentVRCamera() {\n if (this._webVRready) {\n return this._webVRCamera;\n }\n else {\n return this._scene.activeCamera;\n }\n }\n /**\n * The webVRCamera which is used when in VR.\n */\n get webVRCamera() {\n return this._webVRCamera;\n }\n /**\n * The deviceOrientationCamera that is used as a fallback when vr device is not connected.\n */\n get vrDeviceOrientationCamera() {\n return this._vrDeviceOrientationCamera;\n }\n /**\n * The html button that is used to trigger entering into VR.\n */\n get vrButton() {\n return this._btnVR;\n }\n get _teleportationRequestInitiated() {\n const result = this._cameraGazer._teleportationRequestInitiated ||\n (this._leftController !== null && this._leftController._teleportationRequestInitiated) ||\n (this._rightController !== null && this._rightController._teleportationRequestInitiated);\n return result;\n }\n /**\n * Instantiates a VRExperienceHelper.\n * Helps to quickly add VR support to an existing scene.\n * @param scene The scene the VRExperienceHelper belongs to.\n * @param webVROptions Options to modify the vr experience helper's behavior.\n */\n constructor(scene, \n /** Options to modify the vr experience helper's behavior. */\n webVROptions = {}) {\n this.webVROptions = webVROptions;\n // Can the system support WebVR, even if a headset isn't plugged in?\n this._webVRsupported = false;\n // If WebVR is supported, is a headset plugged in and are we ready to present?\n this._webVRready = false;\n // Are we waiting for the requestPresent callback to complete?\n this._webVRrequesting = false;\n // Are we presenting to the headset right now? (this is the vrDevice state)\n this._webVRpresenting = false;\n // Are we presenting in the fullscreen fallback?\n this._fullscreenVRpresenting = false;\n /**\n * Gets or sets a boolean indicating that gaze can be enabled even if pointer lock is not engage (useful on iOS where fullscreen mode and pointer lock are not supported)\n */\n this.enableGazeEvenWhenNoPointerLock = false;\n /**\n * Gets or sets a boolean indicating that the VREXperienceHelper will exit VR if double tap is detected\n */\n this.exitVROnDoubleTap = true;\n /**\n * Observable raised right before entering VR.\n */\n this.onEnteringVRObservable = new Observable();\n /**\n * Observable raised when entering VR has completed.\n */\n this.onAfterEnteringVRObservable = new Observable();\n /**\n * Observable raised when exiting VR.\n */\n this.onExitingVRObservable = new Observable();\n /**\n * Observable raised when controller mesh is loaded.\n */\n this.onControllerMeshLoadedObservable = new Observable();\n this._useCustomVRButton = false;\n this._teleportationRequested = false;\n this._teleportActive = false;\n this._floorMeshesCollection = [];\n this._teleportationMode = VRExperienceHelper.TELEPORTATIONMODE_CONSTANTTIME;\n this._teleportationTime = 122;\n this._teleportationSpeed = 20;\n this._rotationAllowed = true;\n this._teleportBackwardsVector = new Vector3(0, -1, -1);\n this._isDefaultTeleportationTarget = true;\n this._teleportationFillColor = \"#444444\";\n this._teleportationBorderColor = \"#FFFFFF\";\n this._rotationAngle = 0;\n this._haloCenter = new Vector3(0, 0, 0);\n this._padSensibilityUp = 0.65;\n this._padSensibilityDown = 0.35;\n this._leftController = null;\n this._rightController = null;\n this._gazeColor = new Color3(0.7, 0.7, 0.7);\n this._laserColor = new Color3(0.7, 0.7, 0.7);\n this._pickedLaserColor = new Color3(0.2, 0.2, 1);\n this._pickedGazeColor = new Color3(0, 0, 1);\n /**\n * Observable raised when a new mesh is selected based on meshSelectionPredicate\n */\n this.onNewMeshSelected = new Observable();\n /**\n * Observable raised when a new mesh is selected based on meshSelectionPredicate.\n * This observable will provide the mesh and the controller used to select the mesh\n */\n this.onMeshSelectedWithController = new Observable();\n /**\n * Observable raised when a new mesh is picked based on meshSelectionPredicate\n */\n this.onNewMeshPicked = new Observable();\n /**\n * Observable raised before camera teleportation\n */\n this.onBeforeCameraTeleport = new Observable();\n /**\n * Observable raised after camera teleportation\n */\n this.onAfterCameraTeleport = new Observable();\n /**\n * Observable raised when current selected mesh gets unselected\n */\n this.onSelectedMeshUnselected = new Observable();\n /**\n * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.\n */\n this.teleportationEnabled = true;\n this._teleportationInitialized = false;\n this._interactionsEnabled = false;\n this._interactionsRequested = false;\n this._displayGaze = true;\n this._displayLaserPointer = true;\n /**\n * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes\n */\n this.updateGazeTrackerScale = true;\n /**\n * If the gaze trackers color should be updated when selecting meshes\n */\n this.updateGazeTrackerColor = true;\n /**\n * If the controller laser color should be updated when selecting meshes\n */\n this.updateControllerLaserColor = true;\n /**\n * Defines whether or not Pointer lock should be requested when switching to\n * full screen.\n */\n this.requestPointerLockOnFullScreen = true;\n /**\n * Was the XR test done already. If this is true AND this.xr exists, xr is initialized.\n * If this is true and no this.xr, xr exists but is not supported, using WebVR.\n */\n this.xrTestDone = false;\n this._onResize = () => {\n this._moveButtonToBottomRight();\n if (this._fullscreenVRpresenting && this._webVRready) {\n this.exitVR();\n }\n };\n this._onFullscreenChange = () => {\n this._fullscreenVRpresenting = !!document.fullscreenElement;\n if (!this._fullscreenVRpresenting && this._inputElement) {\n this.exitVR();\n if (!this._useCustomVRButton && this._btnVR) {\n this._btnVR.style.top = this._inputElement.offsetTop + this._inputElement.offsetHeight - 70 + \"px\";\n this._btnVR.style.left = this._inputElement.offsetLeft + this._inputElement.offsetWidth - 100 + \"px\";\n // make sure the button is visible after setting its position\n this._updateButtonVisibility();\n }\n }\n };\n this._cachedAngularSensibility = { angularSensibilityX: null, angularSensibilityY: null, angularSensibility: null };\n this._beforeRender = () => {\n if (this._leftController && this._leftController._activePointer) {\n this._castRayAndSelectObject(this._leftController);\n }\n if (this._rightController && this._rightController._activePointer) {\n this._castRayAndSelectObject(this._rightController);\n }\n if (this._noControllerIsActive && (this._scene.getEngine().isPointerLock || this.enableGazeEvenWhenNoPointerLock)) {\n this._castRayAndSelectObject(this._cameraGazer);\n }\n else {\n this._cameraGazer._gazeTracker.isVisible = false;\n }\n };\n this._onNewGamepadConnected = (gamepad) => {\n if (gamepad.type !== Gamepad.POSE_ENABLED) {\n if (gamepad.leftStick) {\n gamepad.onleftstickchanged((stickValues) => {\n if (this._teleportationInitialized && this.teleportationEnabled) {\n // Listening to classic/xbox gamepad only if no VR controller is active\n if ((!this._leftController && !this._rightController) ||\n (this._leftController && !this._leftController._activePointer && this._rightController && !this._rightController._activePointer)) {\n this._checkTeleportWithRay(stickValues, this._cameraGazer);\n this._checkTeleportBackwards(stickValues, this._cameraGazer);\n }\n }\n });\n }\n if (gamepad.rightStick) {\n gamepad.onrightstickchanged((stickValues) => {\n if (this._teleportationInitialized) {\n this._checkRotate(stickValues, this._cameraGazer);\n }\n });\n }\n if (gamepad.type === Gamepad.XBOX) {\n gamepad.onbuttondown((buttonPressed) => {\n if (this._interactionsEnabled && buttonPressed === Xbox360Button.A) {\n this._cameraGazer._selectionPointerDown();\n }\n });\n gamepad.onbuttonup((buttonPressed) => {\n if (this._interactionsEnabled && buttonPressed === Xbox360Button.A) {\n this._cameraGazer._selectionPointerUp();\n }\n });\n }\n }\n else {\n const webVRController = gamepad;\n const controller = new VRExperienceHelperControllerGazer(webVRController, this._scene, this._cameraGazer._gazeTracker);\n if (webVRController.hand === \"right\" || (this._leftController && this._leftController.webVRController != webVRController)) {\n this._rightController = controller;\n }\n else {\n this._leftController = controller;\n }\n this._tryEnableInteractionOnController(controller);\n }\n };\n // This only succeeds if the controller's mesh exists for the controller so this must be called whenever new controller is connected or when mesh is loaded\n this._tryEnableInteractionOnController = (controller) => {\n if (this._interactionsRequested && !controller._interactionsEnabled) {\n this._enableInteractionOnController(controller);\n }\n if (this._teleportationRequested && !controller._teleportationEnabled) {\n this._enableTeleportationOnController(controller);\n }\n };\n this._onNewGamepadDisconnected = (gamepad) => {\n if (gamepad instanceof WebVRController) {\n if (gamepad.hand === \"left\" && this._leftController != null) {\n this._leftController.dispose();\n this._leftController = null;\n }\n if (gamepad.hand === \"right\" && this._rightController != null) {\n this._rightController.dispose();\n this._rightController = null;\n }\n }\n };\n this._workingVector = Vector3.Zero();\n this._workingQuaternion = Quaternion.Identity();\n this._workingMatrix = Matrix.Identity();\n Logger.Warn(\"WebVR is deprecated. Please avoid using this experience helper and use the WebXR experience helper instead\");\n this._scene = scene;\n this._inputElement = scene.getEngine().getInputElement();\n // check for VR support:\n const vrSupported = \"getVRDisplays\" in navigator;\n // no VR support? force XR but only when it is not set because web vr can work without the getVRDisplays\n if (!vrSupported && webVROptions.useXR === undefined) {\n webVROptions.useXR = true;\n }\n // Parse options\n if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {\n webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;\n }\n if (webVROptions.createDeviceOrientationCamera === undefined) {\n webVROptions.createDeviceOrientationCamera = true;\n }\n if (webVROptions.laserToggle === undefined) {\n webVROptions.laserToggle = true;\n }\n if (webVROptions.defaultHeight === undefined) {\n webVROptions.defaultHeight = 1.7;\n }\n if (webVROptions.useCustomVRButton) {\n this._useCustomVRButton = true;\n if (webVROptions.customVRButton) {\n this._btnVR = webVROptions.customVRButton;\n }\n }\n if (webVROptions.rayLength) {\n this._rayLength = webVROptions.rayLength;\n }\n this._defaultHeight = webVROptions.defaultHeight;\n if (webVROptions.positionScale) {\n this._rayLength *= webVROptions.positionScale;\n this._defaultHeight *= webVROptions.positionScale;\n }\n this._hasEnteredVR = false;\n // Set position\n if (this._scene.activeCamera) {\n this._position = this._scene.activeCamera.position.clone();\n }\n else {\n this._position = new Vector3(0, this._defaultHeight, 0);\n }\n // Set non-vr camera\n if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {\n this._deviceOrientationCamera = new DeviceOrientationCamera(\"deviceOrientationVRHelper\", this._position.clone(), scene);\n // Copy data from existing camera\n if (this._scene.activeCamera) {\n this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;\n this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;\n // Set rotation from previous camera\n if (this._scene.activeCamera instanceof TargetCamera && this._scene.activeCamera.rotation) {\n const targetCamera = this._scene.activeCamera;\n if (targetCamera.rotationQuaternion) {\n this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);\n }\n else {\n this._deviceOrientationCamera.rotationQuaternion.copyFrom(Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));\n }\n this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();\n }\n }\n this._scene.activeCamera = this._deviceOrientationCamera;\n if (this._inputElement) {\n this._scene.activeCamera.attachControl();\n }\n }\n else {\n this._existingCamera = this._scene.activeCamera;\n }\n if (this.webVROptions.useXR && navigator.xr) {\n // force-check XR session support\n WebXRSessionManager.IsSessionSupportedAsync(\"immersive-vr\").then((supported) => {\n if (supported) {\n Logger.Log(\"Using WebXR. It is recommended to use the WebXRDefaultExperience directly\");\n // it is possible to use XR, let's do it!\n scene\n .createDefaultXRExperienceAsync({\n floorMeshes: webVROptions.floorMeshes || [],\n })\n .then((xr) => {\n this.xr = xr;\n // connect observables\n this.xrTestDone = true;\n this._cameraGazer = new VRExperienceHelperCameraGazer(() => {\n return this.xr.baseExperience.camera;\n }, scene);\n this.xr.baseExperience.onStateChangedObservable.add((state) => {\n // support for entering / exiting\n switch (state) {\n case WebXRState.ENTERING_XR:\n this.onEnteringVRObservable.notifyObservers(this);\n if (!this._interactionsEnabled) {\n this.xr.pointerSelection.detach();\n }\n this.xr.pointerSelection.displayLaserPointer = this._displayLaserPointer;\n break;\n case WebXRState.EXITING_XR:\n this.onExitingVRObservable.notifyObservers(this);\n // resize to update width and height when exiting vr exits fullscreen\n this._scene.getEngine().resize();\n break;\n case WebXRState.IN_XR:\n this._hasEnteredVR = true;\n break;\n case WebXRState.NOT_IN_XR:\n this._hasEnteredVR = false;\n break;\n }\n });\n });\n }\n else {\n // XR not supported (thou exists), continue WebVR init\n this._completeVRInit(scene, webVROptions);\n }\n });\n }\n else {\n // no XR, continue init synchronous\n this._completeVRInit(scene, webVROptions);\n }\n }\n _completeVRInit(scene, webVROptions) {\n this.xrTestDone = true;\n // Create VR cameras\n if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {\n if (webVROptions.useMultiview) {\n if (!webVROptions.vrDeviceOrientationCameraMetrics) {\n webVROptions.vrDeviceOrientationCameraMetrics = VRCameraMetrics.GetDefault();\n }\n webVROptions.vrDeviceOrientationCameraMetrics.multiviewEnabled = true;\n }\n this._vrDeviceOrientationCamera = new VRDeviceOrientationFreeCamera(\"VRDeviceOrientationVRHelper\", this._position, this._scene, true, webVROptions.vrDeviceOrientationCameraMetrics);\n this._vrDeviceOrientationCamera.angularSensibility = Number.MAX_VALUE;\n }\n this._webVRCamera = new WebVRFreeCamera(\"WebVRHelper\", this._position, this._scene, webVROptions);\n this._webVRCamera.useStandingMatrix();\n this._cameraGazer = new VRExperienceHelperCameraGazer(() => {\n return this.currentVRCamera;\n }, scene);\n // Create default button\n if (!this._useCustomVRButton) {\n this._btnVR = document.createElement(\"BUTTON\");\n this._btnVR.className = \"babylonVRicon\";\n this._btnVR.id = \"babylonVRiconbtn\";\n this._btnVR.title = \"Click to switch to VR\";\n const url = !window.SVGSVGElement\n ? \"https://cdn.babylonjs.com/Assets/vrButton.png\"\n : \"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A\";\n let css = \".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(\" +\n url +\n \"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }\";\n css += \".babylonVRicon.vrdisplaypresenting { display: none; }\";\n // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)\n // css += \".babylonVRicon.vrdisplaysupported { }\";\n // css += \".babylonVRicon.vrdisplayready { }\";\n // css += \".babylonVRicon.vrdisplayrequesting { }\";\n const style = document.createElement(\"style\");\n style.appendChild(document.createTextNode(css));\n document.getElementsByTagName(\"head\")[0].appendChild(style);\n this._moveButtonToBottomRight();\n }\n // VR button click event\n if (this._btnVR) {\n this._btnVR.addEventListener(\"click\", () => {\n if (!this.isInVRMode) {\n this.enterVR();\n }\n else {\n this._scene.getEngine().disableVR();\n }\n });\n }\n // Window events\n const hostWindow = this._scene.getEngine().getHostWindow();\n if (!hostWindow) {\n return;\n }\n hostWindow.addEventListener(\"resize\", this._onResize);\n document.addEventListener(\"fullscreenchange\", this._onFullscreenChange, false);\n // Display vr button when headset is connected\n if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {\n this._displayVRButton();\n }\n else {\n this._scene.getEngine().onVRDisplayChangedObservable.add((e) => {\n if (e.vrDisplay) {\n this._displayVRButton();\n }\n });\n }\n // Exiting VR mode using 'ESC' key on desktop\n this._onKeyDown = (event) => {\n if (event.keyCode === 27 && this.isInVRMode) {\n this.exitVR();\n }\n };\n document.addEventListener(\"keydown\", this._onKeyDown);\n // Exiting VR mode double tapping the touch screen\n this._scene.onPrePointerObservable.add(() => {\n if (this._hasEnteredVR && this.exitVROnDoubleTap) {\n this.exitVR();\n if (this._fullscreenVRpresenting) {\n this._scene.getEngine().exitFullscreen();\n }\n }\n }, PointerEventTypes.POINTERDOUBLETAP, false);\n // Listen for WebVR display changes\n this._onVRDisplayChangedBind = (eventArgs) => this._onVRDisplayChanged(eventArgs);\n this._onVrDisplayPresentChangeBind = () => this._onVrDisplayPresentChange();\n this._onVRRequestPresentStart = () => {\n this._webVRrequesting = true;\n this._updateButtonVisibility();\n };\n this._onVRRequestPresentComplete = () => {\n this._webVRrequesting = false;\n this._updateButtonVisibility();\n };\n scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChangedBind);\n scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);\n scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);\n hostWindow.addEventListener(\"vrdisplaypresentchange\", this._onVrDisplayPresentChangeBind);\n scene.onDisposeObservable.add(() => {\n this.dispose();\n });\n // Gamepad connection events\n this._webVRCamera.onControllerMeshLoadedObservable.add((webVRController) => this._onDefaultMeshLoaded(webVRController));\n this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);\n this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);\n this._updateButtonVisibility();\n //create easing functions\n this._circleEase = new CircleEase();\n this._circleEase.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT);\n this._teleportationEasing = this._circleEase;\n // Allow clicking in the vrDeviceOrientationCamera\n scene.onPointerObservable.add((e) => {\n if (this._interactionsEnabled) {\n if (scene.activeCamera === this.vrDeviceOrientationCamera && e.event.pointerType === \"mouse\") {\n if (e.type === PointerEventTypes.POINTERDOWN) {\n this._cameraGazer._selectionPointerDown();\n }\n else if (e.type === PointerEventTypes.POINTERUP) {\n this._cameraGazer._selectionPointerUp();\n }\n }\n }\n });\n if (this.webVROptions.floorMeshes) {\n this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });\n }\n }\n // Raised when one of the controller has loaded successfully its associated default mesh\n _onDefaultMeshLoaded(webVRController) {\n if (this._leftController && this._leftController.webVRController == webVRController) {\n if (webVRController.mesh) {\n this._leftController._setLaserPointerParent(webVRController.mesh);\n }\n }\n if (this._rightController && this._rightController.webVRController == webVRController) {\n if (webVRController.mesh) {\n this._rightController._setLaserPointerParent(webVRController.mesh);\n }\n }\n try {\n this.onControllerMeshLoadedObservable.notifyObservers(webVRController);\n }\n catch (err) {\n Logger.Warn(\"Error in your custom logic onControllerMeshLoaded: \" + err);\n }\n }\n /**\n * Gets a value indicating if we are currently in VR mode.\n */\n get isInVRMode() {\n return (this.xr && this.webVROptions.useXR && this.xr.baseExperience.state === WebXRState.IN_XR) || this._webVRpresenting || this._fullscreenVRpresenting;\n }\n _onVrDisplayPresentChange() {\n const vrDisplay = this._scene.getEngine().getVRDevice();\n if (vrDisplay) {\n const wasPresenting = this._webVRpresenting;\n this._webVRpresenting = vrDisplay.isPresenting;\n if (wasPresenting && !this._webVRpresenting) {\n this.exitVR();\n }\n }\n else {\n Logger.Warn(\"Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?\");\n }\n this._updateButtonVisibility();\n }\n _onVRDisplayChanged(eventArgs) {\n this._webVRsupported = eventArgs.vrSupported;\n this._webVRready = !!eventArgs.vrDisplay;\n this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;\n this._updateButtonVisibility();\n }\n _moveButtonToBottomRight() {\n if (this._inputElement && !this._useCustomVRButton && this._btnVR) {\n const rect = this._inputElement.getBoundingClientRect();\n this._btnVR.style.top = rect.top + rect.height - 70 + \"px\";\n this._btnVR.style.left = rect.left + rect.width - 100 + \"px\";\n }\n }\n _displayVRButton() {\n if (!this._useCustomVRButton && !this._btnVRDisplayed && this._btnVR) {\n document.body.appendChild(this._btnVR);\n this._btnVRDisplayed = true;\n }\n }\n _updateButtonVisibility() {\n if (!this._btnVR || this._useCustomVRButton) {\n return;\n }\n this._btnVR.className = \"babylonVRicon\";\n if (this.isInVRMode) {\n this._btnVR.className += \" vrdisplaypresenting\";\n }\n else {\n if (this._webVRready) {\n this._btnVR.className += \" vrdisplayready\";\n }\n if (this._webVRsupported) {\n this._btnVR.className += \" vrdisplaysupported\";\n }\n if (this._webVRrequesting) {\n this._btnVR.className += \" vrdisplayrequesting\";\n }\n }\n }\n /**\n * Attempt to enter VR. If a headset is connected and ready, will request present on that.\n * Otherwise, will use the fullscreen API.\n */\n enterVR() {\n if (this.xr) {\n this.xr.baseExperience.enterXRAsync(\"immersive-vr\", \"local-floor\", this.xr.renderTarget);\n return;\n }\n if (this.onEnteringVRObservable) {\n try {\n this.onEnteringVRObservable.notifyObservers(this);\n }\n catch (err) {\n Logger.Warn(\"Error in your custom logic onEnteringVR: \" + err);\n }\n }\n if (this._scene.activeCamera) {\n this._position = this._scene.activeCamera.position.clone();\n if (this.vrDeviceOrientationCamera) {\n this.vrDeviceOrientationCamera.rotation = Quaternion.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles();\n this.vrDeviceOrientationCamera.angularSensibility = 2000;\n }\n if (this.webVRCamera) {\n const currentYRotation = this.webVRCamera.deviceRotationQuaternion.toEulerAngles().y;\n const desiredYRotation = Quaternion.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles().y;\n const delta = desiredYRotation - currentYRotation;\n const currentGlobalRotation = this.webVRCamera.rotationQuaternion.toEulerAngles().y;\n this.webVRCamera.rotationQuaternion = Quaternion.FromEulerAngles(0, currentGlobalRotation + delta, 0);\n }\n // make sure that we return to the last active camera\n this._existingCamera = this._scene.activeCamera;\n // Remove and cache angular sensability to avoid camera rotation when in VR\n if (this._existingCamera.angularSensibilityX) {\n this._cachedAngularSensibility.angularSensibilityX = this._existingCamera.angularSensibilityX;\n this._existingCamera.angularSensibilityX = Number.MAX_VALUE;\n }\n if (this._existingCamera.angularSensibilityY) {\n this._cachedAngularSensibility.angularSensibilityY = this._existingCamera.angularSensibilityY;\n this._existingCamera.angularSensibilityY = Number.MAX_VALUE;\n }\n if (this._existingCamera.angularSensibility) {\n this._cachedAngularSensibility.angularSensibility = this._existingCamera.angularSensibility;\n this._existingCamera.angularSensibility = Number.MAX_VALUE;\n }\n }\n if (this._webVRrequesting) {\n return;\n }\n // If WebVR is supported and a headset is connected\n if (this._webVRready) {\n if (!this._webVRpresenting) {\n this._scene.getEngine().onVRRequestPresentComplete.addOnce((result) => {\n this.onAfterEnteringVRObservable.notifyObservers({ success: result });\n });\n this._webVRCamera.position = this._position;\n this._scene.activeCamera = this._webVRCamera;\n }\n }\n else if (this._vrDeviceOrientationCamera) {\n this._vrDeviceOrientationCamera.position = this._position;\n if (this._scene.activeCamera) {\n this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;\n }\n this._scene.activeCamera = this._vrDeviceOrientationCamera;\n this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen);\n this._updateButtonVisibility();\n this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce(() => {\n this.onAfterEnteringVRObservable.notifyObservers({ success: true });\n });\n }\n if (this._scene.activeCamera && this._inputElement) {\n this._scene.activeCamera.attachControl();\n }\n if (this._interactionsEnabled) {\n this._scene.registerBeforeRender(this._beforeRender);\n }\n if (this._displayLaserPointer) {\n [this._leftController, this._rightController].forEach((controller) => {\n if (controller) {\n controller._activatePointer();\n }\n });\n }\n this._hasEnteredVR = true;\n }\n /**\n * Attempt to exit VR, or fullscreen.\n */\n exitVR() {\n if (this.xr) {\n this.xr.baseExperience.exitXRAsync();\n return;\n }\n if (this._hasEnteredVR) {\n if (this.onExitingVRObservable) {\n try {\n this.onExitingVRObservable.notifyObservers(this);\n }\n catch (err) {\n Logger.Warn(\"Error in your custom logic onExitingVR: \" + err);\n }\n }\n if (this._webVRpresenting) {\n this._scene.getEngine().disableVR();\n }\n if (this._scene.activeCamera) {\n this._position = this._scene.activeCamera.position.clone();\n }\n if (this.vrDeviceOrientationCamera) {\n this.vrDeviceOrientationCamera.angularSensibility = Number.MAX_VALUE;\n }\n if (this._deviceOrientationCamera) {\n this._deviceOrientationCamera.position = this._position;\n this._scene.activeCamera = this._deviceOrientationCamera;\n // Restore angular sensibility\n if (this._cachedAngularSensibility.angularSensibilityX) {\n this._deviceOrientationCamera.angularSensibilityX = this._cachedAngularSensibility.angularSensibilityX;\n this._cachedAngularSensibility.angularSensibilityX = null;\n }\n if (this._cachedAngularSensibility.angularSensibilityY) {\n this._deviceOrientationCamera.angularSensibilityY = this._cachedAngularSensibility.angularSensibilityY;\n this._cachedAngularSensibility.angularSensibilityY = null;\n }\n if (this._cachedAngularSensibility.angularSensibility) {\n this._deviceOrientationCamera.angularSensibility = this._cachedAngularSensibility.angularSensibility;\n this._cachedAngularSensibility.angularSensibility = null;\n }\n }\n else if (this._existingCamera) {\n this._existingCamera.position = this._position;\n this._scene.activeCamera = this._existingCamera;\n if (this._inputElement) {\n this._scene.activeCamera.attachControl();\n }\n // Restore angular sensibility\n if (this._cachedAngularSensibility.angularSensibilityX) {\n this._existingCamera.angularSensibilityX = this._cachedAngularSensibility.angularSensibilityX;\n this._cachedAngularSensibility.angularSensibilityX = null;\n }\n if (this._cachedAngularSensibility.angularSensibilityY) {\n this._existingCamera.angularSensibilityY = this._cachedAngularSensibility.angularSensibilityY;\n this._cachedAngularSensibility.angularSensibilityY = null;\n }\n if (this._cachedAngularSensibility.angularSensibility) {\n this._existingCamera.angularSensibility = this._cachedAngularSensibility.angularSensibility;\n this._cachedAngularSensibility.angularSensibility = null;\n }\n }\n this._updateButtonVisibility();\n if (this._interactionsEnabled) {\n this._scene.unregisterBeforeRender(this._beforeRender);\n this._cameraGazer._gazeTracker.isVisible = false;\n if (this._leftController) {\n this._leftController._gazeTracker.isVisible = false;\n }\n if (this._rightController) {\n this._rightController._gazeTracker.isVisible = false;\n }\n }\n // resize to update width and height when exiting vr exits fullscreen\n this._scene.getEngine().resize();\n [this._leftController, this._rightController].forEach((controller) => {\n if (controller) {\n controller._deactivatePointer();\n }\n });\n this._hasEnteredVR = false;\n // Update engine state to re enable non-vr camera input\n const engine = this._scene.getEngine();\n if (engine._onVrDisplayPresentChange) {\n engine._onVrDisplayPresentChange();\n }\n }\n }\n /**\n * The position of the vr experience helper.\n */\n get position() {\n return this._position;\n }\n /**\n * Sets the position of the vr experience helper.\n */\n set position(value) {\n this._position = value;\n if (this._scene.activeCamera) {\n this._scene.activeCamera.position = value;\n }\n }\n /**\n * Enables controllers and user interactions such as selecting and object or clicking on an object.\n */\n enableInteractions() {\n if (!this._interactionsEnabled) {\n this._interactionsRequested = true;\n // in XR it is enabled by default, but just to make sure, re-attach\n if (this.xr) {\n if (this.xr.baseExperience.state === WebXRState.IN_XR) {\n this.xr.pointerSelection.attach();\n }\n return;\n }\n if (this._leftController) {\n this._enableInteractionOnController(this._leftController);\n }\n if (this._rightController) {\n this._enableInteractionOnController(this._rightController);\n }\n this.raySelectionPredicate = (mesh) => {\n return mesh.isVisible && (mesh.isPickable || mesh.name === this._floorMeshName);\n };\n this.meshSelectionPredicate = () => {\n return true;\n };\n this._raySelectionPredicate = (mesh) => {\n if (this._isTeleportationFloor(mesh) ||\n (mesh.name.indexOf(\"gazeTracker\") === -1 && mesh.name.indexOf(\"teleportationTarget\") === -1 && mesh.name.indexOf(\"torusTeleportation\") === -1)) {\n return this.raySelectionPredicate(mesh);\n }\n return false;\n };\n this._interactionsEnabled = true;\n }\n }\n get _noControllerIsActive() {\n return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);\n }\n _isTeleportationFloor(mesh) {\n for (let i = 0; i < this._floorMeshesCollection.length; i++) {\n if (this._floorMeshesCollection[i].id === mesh.id) {\n return true;\n }\n }\n if (this._floorMeshName && mesh.name === this._floorMeshName) {\n return true;\n }\n return false;\n }\n /**\n * Adds a floor mesh to be used for teleportation.\n * @param floorMesh the mesh to be used for teleportation.\n */\n addFloorMesh(floorMesh) {\n if (!this._floorMeshesCollection) {\n return;\n }\n if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {\n return;\n }\n this._floorMeshesCollection.push(floorMesh);\n }\n /**\n * Removes a floor mesh from being used for teleportation.\n * @param floorMesh the mesh to be removed.\n */\n removeFloorMesh(floorMesh) {\n if (!this._floorMeshesCollection) {\n return;\n }\n const meshIndex = this._floorMeshesCollection.indexOf(floorMesh);\n if (meshIndex !== -1) {\n this._floorMeshesCollection.splice(meshIndex, 1);\n }\n }\n /**\n * Enables interactions and teleportation using the VR controllers and gaze.\n * @param vrTeleportationOptions options to modify teleportation behavior.\n */\n enableTeleportation(vrTeleportationOptions = {}) {\n if (!this._teleportationInitialized) {\n this._teleportationRequested = true;\n this.enableInteractions();\n if (this.webVROptions.useXR && (vrTeleportationOptions.floorMeshes || vrTeleportationOptions.floorMeshName)) {\n const floorMeshes = vrTeleportationOptions.floorMeshes || [];\n if (!floorMeshes.length) {\n const floorMesh = this._scene.getMeshByName(vrTeleportationOptions.floorMeshName);\n if (floorMesh) {\n floorMeshes.push(floorMesh);\n }\n }\n if (this.xr) {\n floorMeshes.forEach((mesh) => {\n this.xr.teleportation.addFloorMesh(mesh);\n });\n if (!this.xr.teleportation.attached) {\n this.xr.teleportation.attach();\n }\n return;\n }\n else if (!this.xrTestDone) {\n const waitForXr = () => {\n if (this.xrTestDone) {\n this._scene.unregisterBeforeRender(waitForXr);\n if (this.xr) {\n if (!this.xr.teleportation.attached) {\n this.xr.teleportation.attach();\n }\n }\n else {\n this.enableTeleportation(vrTeleportationOptions);\n }\n }\n };\n this._scene.registerBeforeRender(waitForXr);\n return;\n }\n }\n if (vrTeleportationOptions.floorMeshName) {\n this._floorMeshName = vrTeleportationOptions.floorMeshName;\n }\n if (vrTeleportationOptions.floorMeshes) {\n this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;\n }\n if (vrTeleportationOptions.teleportationMode) {\n this._teleportationMode = vrTeleportationOptions.teleportationMode;\n }\n if (vrTeleportationOptions.teleportationTime && vrTeleportationOptions.teleportationTime > 0) {\n this._teleportationTime = vrTeleportationOptions.teleportationTime;\n }\n if (vrTeleportationOptions.teleportationSpeed && vrTeleportationOptions.teleportationSpeed > 0) {\n this._teleportationSpeed = vrTeleportationOptions.teleportationSpeed;\n }\n if (vrTeleportationOptions.easingFunction !== undefined) {\n this._teleportationEasing = vrTeleportationOptions.easingFunction;\n }\n if (this._leftController != null) {\n this._enableTeleportationOnController(this._leftController);\n }\n if (this._rightController != null) {\n this._enableTeleportationOnController(this._rightController);\n }\n // Creates an image processing post process for the vignette not relying\n // on the main scene configuration for image processing to reduce setup and spaces\n // (gamma/linear) conflicts.\n const imageProcessingConfiguration = new ImageProcessingConfiguration();\n imageProcessingConfiguration.vignetteColor = new Color4(0, 0, 0, 0);\n imageProcessingConfiguration.vignetteEnabled = true;\n this._postProcessMove = new ImageProcessingPostProcess(\"postProcessMove\", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);\n this._webVRCamera.detachPostProcess(this._postProcessMove);\n this._teleportationInitialized = true;\n if (this._isDefaultTeleportationTarget) {\n this._createTeleportationCircles();\n this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);\n }\n }\n }\n _enableInteractionOnController(controller) {\n const controllerMesh = controller.webVRController.mesh;\n if (controllerMesh) {\n controller._interactionsEnabled = true;\n if (this.isInVRMode && this._displayLaserPointer) {\n controller._activatePointer();\n }\n if (this.webVROptions.laserToggle) {\n controller.webVRController.onMainButtonStateChangedObservable.add((stateObject) => {\n // Enabling / disabling laserPointer\n if (this._displayLaserPointer && stateObject.value === 1) {\n if (controller._activePointer) {\n controller._deactivatePointer();\n }\n else {\n controller._activatePointer();\n }\n if (this.displayGaze) {\n controller._gazeTracker.isVisible = controller._activePointer;\n }\n }\n });\n }\n controller.webVRController.onTriggerStateChangedObservable.add((stateObject) => {\n let gazer = controller;\n if (this._noControllerIsActive) {\n gazer = this._cameraGazer;\n }\n if (!gazer._pointerDownOnMeshAsked) {\n if (stateObject.value > this._padSensibilityUp) {\n gazer._selectionPointerDown();\n }\n }\n else if (stateObject.value < this._padSensibilityDown) {\n gazer._selectionPointerUp();\n }\n });\n }\n }\n _checkTeleportWithRay(stateObject, gazer) {\n // Dont teleport if another gaze already requested teleportation\n if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {\n return;\n }\n if (!gazer._teleportationRequestInitiated) {\n if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {\n gazer._activatePointer();\n gazer._teleportationRequestInitiated = true;\n }\n }\n else {\n // Listening to the proper controller values changes to confirm teleportation\n if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {\n if (this._teleportActive) {\n this.teleportCamera(this._haloCenter);\n }\n gazer._teleportationRequestInitiated = false;\n }\n }\n }\n _checkRotate(stateObject, gazer) {\n // Only rotate when user is not currently selecting a teleportation location\n if (gazer._teleportationRequestInitiated) {\n return;\n }\n if (!gazer._rotationLeftAsked) {\n if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {\n gazer._rotationLeftAsked = true;\n if (this._rotationAllowed) {\n this._rotateCamera(false);\n }\n }\n }\n else {\n if (stateObject.x > -this._padSensibilityDown) {\n gazer._rotationLeftAsked = false;\n }\n }\n if (!gazer._rotationRightAsked) {\n if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {\n gazer._rotationRightAsked = true;\n if (this._rotationAllowed) {\n this._rotateCamera(true);\n }\n }\n }\n else {\n if (stateObject.x < this._padSensibilityDown) {\n gazer._rotationRightAsked = false;\n }\n }\n }\n _checkTeleportBackwards(stateObject, gazer) {\n // Only teleport backwards when user is not currently selecting a teleportation location\n if (gazer._teleportationRequestInitiated) {\n return;\n }\n // Teleport backwards\n if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {\n if (!gazer._teleportationBackRequestInitiated) {\n if (!this.currentVRCamera) {\n return;\n }\n // Get rotation and position of the current camera\n let rotation = Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());\n let position = this.currentVRCamera.position;\n // If the camera has device position, use that instead\n if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {\n rotation = this.currentVRCamera.deviceRotationQuaternion;\n position = this.currentVRCamera.devicePosition;\n }\n // Get matrix with only the y rotation of the device rotation\n rotation.toEulerAnglesToRef(this._workingVector);\n this._workingVector.z = 0;\n this._workingVector.x = 0;\n Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);\n this._workingQuaternion.toRotationMatrix(this._workingMatrix);\n // Rotate backwards ray by device rotation to cast at the ground behind the user\n Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);\n // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff\n const ray = new Ray(position, this._workingVector);\n const hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);\n if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {\n this.teleportCamera(hit.pickedPoint);\n }\n gazer._teleportationBackRequestInitiated = true;\n }\n }\n else {\n gazer._teleportationBackRequestInitiated = false;\n }\n }\n _enableTeleportationOnController(controller) {\n const controllerMesh = controller.webVRController.mesh;\n if (controllerMesh) {\n if (!controller._interactionsEnabled) {\n this._enableInteractionOnController(controller);\n }\n controller._interactionsEnabled = true;\n controller._teleportationEnabled = true;\n if (controller.webVRController.controllerType === PoseEnabledControllerType.VIVE) {\n controller._dpadPressed = false;\n controller.webVRController.onPadStateChangedObservable.add((stateObject) => {\n controller._dpadPressed = stateObject.pressed;\n if (!controller._dpadPressed) {\n controller._rotationLeftAsked = false;\n controller._rotationRightAsked = false;\n controller._teleportationBackRequestInitiated = false;\n }\n });\n }\n controller.webVRController.onPadValuesChangedObservable.add((stateObject) => {\n if (this.teleportationEnabled) {\n this._checkTeleportBackwards(stateObject, controller);\n this._checkTeleportWithRay(stateObject, controller);\n }\n this._checkRotate(stateObject, controller);\n });\n }\n }\n _createTeleportationCircles() {\n this._teleportationTarget = CreateGround(\"teleportationTarget\", { width: 2, height: 2, subdivisions: 2 }, this._scene);\n this._teleportationTarget.isPickable = false;\n const length = 512;\n const dynamicTexture = new DynamicTexture(\"DynamicTexture\", length, this._scene, true);\n dynamicTexture.hasAlpha = true;\n const context = dynamicTexture.getContext();\n const centerX = length / 2;\n const centerY = length / 2;\n const radius = 200;\n context.beginPath();\n context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);\n context.fillStyle = this._teleportationFillColor;\n context.fill();\n context.lineWidth = 10;\n context.strokeStyle = this._teleportationBorderColor;\n context.stroke();\n context.closePath();\n dynamicTexture.update();\n const teleportationCircleMaterial = new StandardMaterial(\"TextPlaneMaterial\", this._scene);\n teleportationCircleMaterial.diffuseTexture = dynamicTexture;\n this._teleportationTarget.material = teleportationCircleMaterial;\n const torus = CreateTorus(\"torusTeleportation\", {\n diameter: 0.75,\n thickness: 0.1,\n tessellation: 25,\n updatable: false,\n }, this._scene);\n torus.isPickable = false;\n torus.parent = this._teleportationTarget;\n const animationInnerCircle = new Animation(\"animationInnerCircle\", \"position.y\", 30, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CYCLE);\n const keys = [];\n keys.push({\n frame: 0,\n value: 0,\n });\n keys.push({\n frame: 30,\n value: 0.4,\n });\n keys.push({\n frame: 60,\n value: 0,\n });\n animationInnerCircle.setKeys(keys);\n const easingFunction = new SineEase();\n easingFunction.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT);\n animationInnerCircle.setEasingFunction(easingFunction);\n torus.animations = [];\n torus.animations.push(animationInnerCircle);\n this._scene.beginAnimation(torus, 0, 60, true);\n this._hideTeleportationTarget();\n }\n _displayTeleportationTarget() {\n this._teleportActive = true;\n if (this._teleportationInitialized) {\n this._teleportationTarget.isVisible = true;\n if (this._isDefaultTeleportationTarget) {\n this._teleportationTarget.getChildren()[0].isVisible = true;\n }\n }\n }\n _hideTeleportationTarget() {\n this._teleportActive = false;\n if (this._teleportationInitialized) {\n this._teleportationTarget.isVisible = false;\n if (this._isDefaultTeleportationTarget) {\n this._teleportationTarget.getChildren()[0].isVisible = false;\n }\n }\n }\n _rotateCamera(right) {\n if (!(this.currentVRCamera instanceof FreeCamera)) {\n return;\n }\n if (right) {\n this._rotationAngle++;\n }\n else {\n this._rotationAngle--;\n }\n this.currentVRCamera.animations = [];\n const target = Quaternion.FromRotationMatrix(Matrix.RotationY((Math.PI / 4) * this._rotationAngle));\n const animationRotation = new Animation(\"animationRotation\", \"rotationQuaternion\", 90, Animation.ANIMATIONTYPE_QUATERNION, Animation.ANIMATIONLOOPMODE_CONSTANT);\n const animationRotationKeys = [];\n animationRotationKeys.push({\n frame: 0,\n value: this.currentVRCamera.rotationQuaternion,\n });\n animationRotationKeys.push({\n frame: 6,\n value: target,\n });\n animationRotation.setKeys(animationRotationKeys);\n animationRotation.setEasingFunction(this._circleEase);\n this.currentVRCamera.animations.push(animationRotation);\n this._postProcessMove.animations = [];\n const animationPP = new Animation(\"animationPP\", \"vignetteWeight\", 90, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CONSTANT);\n const vignetteWeightKeys = [];\n vignetteWeightKeys.push({\n frame: 0,\n value: 0,\n });\n vignetteWeightKeys.push({\n frame: 3,\n value: 4,\n });\n vignetteWeightKeys.push({\n frame: 6,\n value: 0,\n });\n animationPP.setKeys(vignetteWeightKeys);\n animationPP.setEasingFunction(this._circleEase);\n this._postProcessMove.animations.push(animationPP);\n const animationPP2 = new Animation(\"animationPP2\", \"vignetteStretch\", 90, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CONSTANT);\n const vignetteStretchKeys = [];\n vignetteStretchKeys.push({\n frame: 0,\n value: 0,\n });\n vignetteStretchKeys.push({\n frame: 3,\n value: 10,\n });\n vignetteStretchKeys.push({\n frame: 6,\n value: 0,\n });\n animationPP2.setKeys(vignetteStretchKeys);\n animationPP2.setEasingFunction(this._circleEase);\n this._postProcessMove.animations.push(animationPP2);\n this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;\n this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;\n this._postProcessMove.samples = 4;\n this._webVRCamera.attachPostProcess(this._postProcessMove);\n this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, () => {\n this._webVRCamera.detachPostProcess(this._postProcessMove);\n });\n this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);\n }\n _moveTeleportationSelectorTo(hit, gazer, ray) {\n if (hit.pickedPoint) {\n if (gazer._teleportationRequestInitiated) {\n this._displayTeleportationTarget();\n this._haloCenter.copyFrom(hit.pickedPoint);\n this._teleportationTarget.position.copyFrom(hit.pickedPoint);\n }\n const pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);\n if (pickNormal) {\n const axis1 = Vector3.Cross(Axis.Y, pickNormal);\n const axis2 = Vector3.Cross(pickNormal, axis1);\n Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);\n }\n this._teleportationTarget.position.y += 0.1;\n }\n }\n /**\n * Teleports the users feet to the desired location\n * @param location The location where the user's feet should be placed\n */\n teleportCamera(location) {\n if (!(this.currentVRCamera instanceof FreeCamera)) {\n return;\n }\n // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the\n // offset of the headset from the anchor.\n if (this.webVRCamera.leftCamera) {\n this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);\n this._workingVector.subtractInPlace(this.webVRCamera.position);\n location.subtractToRef(this._workingVector, this._workingVector);\n }\n else {\n this._workingVector.copyFrom(location);\n }\n // Add height to account for user's height offset\n if (this.isInVRMode) {\n this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;\n }\n else {\n this._workingVector.y += this._defaultHeight;\n }\n this.onBeforeCameraTeleport.notifyObservers(this._workingVector);\n // Animations FPS\n const FPS = 90;\n let speedRatio, lastFrame;\n if (this._teleportationMode == VRExperienceHelper.TELEPORTATIONMODE_CONSTANTSPEED) {\n lastFrame = FPS;\n const dist = Vector3.Distance(this.currentVRCamera.position, this._workingVector);\n speedRatio = this._teleportationSpeed / dist;\n }\n else {\n // teleportationMode is TELEPORTATIONMODE_CONSTANTTIME\n lastFrame = Math.round((this._teleportationTime * FPS) / 1000);\n speedRatio = 1;\n }\n // Create animation from the camera's position to the new location\n this.currentVRCamera.animations = [];\n const animationCameraTeleportation = new Animation(\"animationCameraTeleportation\", \"position\", FPS, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT);\n const animationCameraTeleportationKeys = [\n {\n frame: 0,\n value: this.currentVRCamera.position,\n },\n {\n frame: lastFrame,\n value: this._workingVector,\n },\n ];\n animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);\n animationCameraTeleportation.setEasingFunction(this._teleportationEasing);\n this.currentVRCamera.animations.push(animationCameraTeleportation);\n this._postProcessMove.animations = [];\n // Calculate the mid frame for vignette animations\n const midFrame = Math.round(lastFrame / 2);\n const animationPP = new Animation(\"animationPP\", \"vignetteWeight\", FPS, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CONSTANT);\n const vignetteWeightKeys = [];\n vignetteWeightKeys.push({\n frame: 0,\n value: 0,\n });\n vignetteWeightKeys.push({\n frame: midFrame,\n value: 8,\n });\n vignetteWeightKeys.push({\n frame: lastFrame,\n value: 0,\n });\n animationPP.setKeys(vignetteWeightKeys);\n this._postProcessMove.animations.push(animationPP);\n const animationPP2 = new Animation(\"animationPP2\", \"vignetteStretch\", FPS, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CONSTANT);\n const vignetteStretchKeys = [];\n vignetteStretchKeys.push({\n frame: 0,\n value: 0,\n });\n vignetteStretchKeys.push({\n frame: midFrame,\n value: 10,\n });\n vignetteStretchKeys.push({\n frame: lastFrame,\n value: 0,\n });\n animationPP2.setKeys(vignetteStretchKeys);\n this._postProcessMove.animations.push(animationPP2);\n this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;\n this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;\n this._webVRCamera.attachPostProcess(this._postProcessMove);\n this._scene.beginAnimation(this._postProcessMove, 0, lastFrame, false, speedRatio, () => {\n this._webVRCamera.detachPostProcess(this._postProcessMove);\n });\n this._scene.beginAnimation(this.currentVRCamera, 0, lastFrame, false, speedRatio, () => {\n this.onAfterCameraTeleport.notifyObservers(this._workingVector);\n });\n this._hideTeleportationTarget();\n }\n _convertNormalToDirectionOfRay(normal, ray) {\n if (normal) {\n const angle = Math.acos(Vector3.Dot(normal, ray.direction));\n if (angle < Math.PI / 2) {\n normal.scaleInPlace(-1);\n }\n }\n return normal;\n }\n _castRayAndSelectObject(gazer) {\n if (!(this.currentVRCamera instanceof FreeCamera)) {\n return;\n }\n const ray = gazer._getForwardRay(this._rayLength);\n const hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);\n if (hit) {\n this._scene.simulatePointerMove(hit, { pointerId: gazer._id });\n }\n gazer._currentHit = hit;\n // Moving the gazeTracker on the mesh face targetted\n if (hit && hit.pickedPoint) {\n if (this._displayGaze) {\n let multiplier = 1;\n gazer._gazeTracker.isVisible = true;\n if (gazer._isActionableMesh) {\n multiplier = 3;\n }\n if (this.updateGazeTrackerScale) {\n gazer._gazeTracker.scaling.x = hit.distance * multiplier;\n gazer._gazeTracker.scaling.y = hit.distance * multiplier;\n gazer._gazeTracker.scaling.z = hit.distance * multiplier;\n }\n const pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);\n // To avoid z-fighting\n const deltaFighting = 0.002;\n if (pickNormal) {\n const axis1 = Vector3.Cross(Axis.Y, pickNormal);\n const axis2 = Vector3.Cross(pickNormal, axis1);\n Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);\n }\n gazer._gazeTracker.position.copyFrom(hit.pickedPoint);\n if (gazer._gazeTracker.position.x < 0) {\n gazer._gazeTracker.position.x += deltaFighting;\n }\n else {\n gazer._gazeTracker.position.x -= deltaFighting;\n }\n if (gazer._gazeTracker.position.y < 0) {\n gazer._gazeTracker.position.y += deltaFighting;\n }\n else {\n gazer._gazeTracker.position.y -= deltaFighting;\n }\n if (gazer._gazeTracker.position.z < 0) {\n gazer._gazeTracker.position.z += deltaFighting;\n }\n else {\n gazer._gazeTracker.position.z -= deltaFighting;\n }\n }\n // Changing the size of the laser pointer based on the distance from the targetted point\n gazer._updatePointerDistance(hit.distance);\n }\n else {\n gazer._updatePointerDistance();\n gazer._gazeTracker.isVisible = false;\n }\n if (hit && hit.pickedMesh) {\n // The object selected is the floor, we're in a teleportation scenario\n if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {\n // Moving the teleportation area to this targetted point\n //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected\n if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {\n this._notifySelectedMeshUnselected(gazer._currentMeshSelected);\n }\n gazer._currentMeshSelected = null;\n if (gazer._teleportationRequestInitiated) {\n this._moveTeleportationSelectorTo(hit, gazer, ray);\n }\n return;\n }\n // If not, we're in a selection scenario\n //this._teleportationAllowed = false;\n if (hit.pickedMesh !== gazer._currentMeshSelected) {\n if (this.meshSelectionPredicate(hit.pickedMesh)) {\n this.onNewMeshPicked.notifyObservers(hit);\n gazer._currentMeshSelected = hit.pickedMesh;\n if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {\n this.changeGazeColor(this._pickedGazeColor);\n this.changeLaserColor(this._pickedLaserColor);\n gazer._isActionableMesh = true;\n }\n else {\n this.changeGazeColor(this._gazeColor);\n this.changeLaserColor(this._laserColor);\n gazer._isActionableMesh = false;\n }\n try {\n this.onNewMeshSelected.notifyObservers(hit.pickedMesh);\n const gazerAsControllerGazer = gazer;\n if (gazerAsControllerGazer.webVRController) {\n this.onMeshSelectedWithController.notifyObservers({ mesh: hit.pickedMesh, controller: gazerAsControllerGazer.webVRController });\n }\n }\n catch (err) {\n Logger.Warn(\"Error while raising onNewMeshSelected or onMeshSelectedWithController: \" + err);\n }\n }\n else {\n this._notifySelectedMeshUnselected(gazer._currentMeshSelected);\n gazer._currentMeshSelected = null;\n this.changeGazeColor(this._gazeColor);\n this.changeLaserColor(this._laserColor);\n }\n }\n }\n else {\n this._notifySelectedMeshUnselected(gazer._currentMeshSelected);\n gazer._currentMeshSelected = null;\n //this._teleportationAllowed = false;\n this.changeGazeColor(this._gazeColor);\n this.changeLaserColor(this._laserColor);\n }\n }\n _notifySelectedMeshUnselected(mesh) {\n if (mesh) {\n this.onSelectedMeshUnselected.notifyObservers(mesh);\n }\n }\n /**\n * Permanently set new colors for the laser pointer\n * @param color the new laser color\n * @param pickedColor the new laser color when picked mesh detected\n */\n setLaserColor(color, pickedColor = this._pickedLaserColor) {\n this._laserColor = color;\n this._pickedLaserColor = pickedColor;\n }\n /**\n * Set lighting enabled / disabled on the laser pointer of both controllers\n * @param enabled should the lighting be enabled on the laser pointer\n */\n setLaserLightingState(enabled = true) {\n if (this._leftController) {\n this._leftController._setLaserPointerLightingDisabled(!enabled);\n }\n if (this._rightController) {\n this._rightController._setLaserPointerLightingDisabled(!enabled);\n }\n }\n /**\n * Permanently set new colors for the gaze pointer\n * @param color the new gaze color\n * @param pickedColor the new gaze color when picked mesh detected\n */\n setGazeColor(color, pickedColor = this._pickedGazeColor) {\n this._gazeColor = color;\n this._pickedGazeColor = pickedColor;\n }\n /**\n * Sets the color of the laser ray from the vr controllers.\n * @param color new color for the ray.\n */\n changeLaserColor(color) {\n if (!this.updateControllerLaserColor) {\n return;\n }\n if (this._leftController) {\n this._leftController._setLaserPointerColor(color);\n }\n if (this._rightController) {\n this._rightController._setLaserPointerColor(color);\n }\n }\n /**\n * Sets the color of the ray from the vr headsets gaze.\n * @param color new color for the ray.\n */\n changeGazeColor(color) {\n if (!this.updateGazeTrackerColor) {\n return;\n }\n if (!this._cameraGazer._gazeTracker.material) {\n return;\n }\n this._cameraGazer._gazeTracker.material.emissiveColor = color;\n if (this._leftController) {\n this._leftController._gazeTracker.material.emissiveColor = color;\n }\n if (this._rightController) {\n this._rightController._gazeTracker.material.emissiveColor = color;\n }\n }\n /**\n * Exits VR and disposes of the vr experience helper\n */\n dispose() {\n if (this.isInVRMode) {\n this.exitVR();\n }\n if (this._postProcessMove) {\n this._postProcessMove.dispose();\n }\n if (this._webVRCamera) {\n this._webVRCamera.dispose();\n }\n if (this._vrDeviceOrientationCamera) {\n this._vrDeviceOrientationCamera.dispose();\n }\n if (!this._useCustomVRButton && this._btnVR && this._btnVR.parentNode) {\n document.body.removeChild(this._btnVR);\n }\n if (this._deviceOrientationCamera && this._scene.activeCamera != this._deviceOrientationCamera) {\n this._deviceOrientationCamera.dispose();\n }\n if (this._cameraGazer) {\n this._cameraGazer.dispose();\n }\n if (this._leftController) {\n this._leftController.dispose();\n }\n if (this._rightController) {\n this._rightController.dispose();\n }\n if (this._teleportationTarget) {\n this._teleportationTarget.dispose();\n }\n if (this.xr) {\n this.xr.dispose();\n }\n this._floorMeshesCollection.length = 0;\n document.removeEventListener(\"keydown\", this._onKeyDown);\n window.removeEventListener(\"vrdisplaypresentchange\", this._onVrDisplayPresentChangeBind);\n window.removeEventListener(\"resize\", this._onResize);\n document.removeEventListener(\"fullscreenchange\", this._onFullscreenChange);\n this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChangedBind);\n this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);\n this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);\n this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);\n this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);\n this._scene.unregisterBeforeRender(this._beforeRender);\n }\n /**\n * Gets the name of the VRExperienceHelper class\n * @returns \"VRExperienceHelper\"\n */\n getClassName() {\n return \"VRExperienceHelper\";\n }\n}\n/**\n * Time Constant Teleportation Mode\n */\nVRExperienceHelper.TELEPORTATIONMODE_CONSTANTTIME = 0;\n/**\n * Speed Constant Teleportation Mode\n */\nVRExperienceHelper.TELEPORTATIONMODE_CONSTANTSPEED = 1;\n//# sourceMappingURL=vrExperienceHelper.js.map","export * from \"./vrCameraMetrics.js\";\nexport * from \"./vrDeviceOrientationArcRotateCamera.js\";\nexport * from \"./vrDeviceOrientationFreeCamera.js\";\nexport * from \"./vrDeviceOrientationGamepadCamera.js\";\nexport * from \"./vrExperienceHelper.js\";\nexport * from \"./webVRCamera.js\";\n//# sourceMappingURL=index.js.map","export * from \"./stereoscopicAnaglyphRigMode.js\";\nexport * from \"./stereoscopicRigMode.js\";\nexport * from \"./vrRigMode.js\";\nexport * from \"./webVRRigMode.js\";\n//# sourceMappingURL=index.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./Inputs/index.js\";\nexport * from \"./cameraInputsManager.js\";\nexport * from \"./camera.js\";\nexport * from \"./targetCamera.js\";\nexport * from \"./freeCamera.js\";\nexport * from \"./freeCameraInputsManager.js\";\nexport * from \"./touchCamera.js\";\nexport * from \"./arcRotateCamera.js\";\nexport * from \"./arcRotateCameraInputsManager.js\";\nexport * from \"./deviceOrientationCamera.js\";\nexport * from \"./flyCamera.js\";\nexport * from \"./flyCameraInputsManager.js\";\nexport * from \"./followCamera.js\";\nexport * from \"./followCameraInputsManager.js\";\nexport * from \"./gamepadCamera.js\";\nexport * from \"./Stereoscopic/index.js\";\nexport * from \"./universalCamera.js\";\nexport * from \"./virtualJoysticksCamera.js\";\nexport * from \"./VR/index.js\";\nexport * from \"./RigModes/index.js\";\n//# sourceMappingURL=index.js.map","import { Vector3 } from \"../Maths/math.vector.js\";\nimport { Plane } from \"../Maths/math.plane.js\";\nconst intersectBoxAASphere = (boxMin, boxMax, sphereCenter, sphereRadius) => {\n if (boxMin.x > sphereCenter.x + sphereRadius) {\n return false;\n }\n if (sphereCenter.x - sphereRadius > boxMax.x) {\n return false;\n }\n if (boxMin.y > sphereCenter.y + sphereRadius) {\n return false;\n }\n if (sphereCenter.y - sphereRadius > boxMax.y) {\n return false;\n }\n if (boxMin.z > sphereCenter.z + sphereRadius) {\n return false;\n }\n if (sphereCenter.z - sphereRadius > boxMax.z) {\n return false;\n }\n return true;\n};\nconst getLowestRoot = (function () {\n const result = { root: 0, found: false };\n return function (a, b, c, maxR) {\n result.root = 0;\n result.found = false;\n const determinant = b * b - 4.0 * a * c;\n if (determinant < 0) {\n return result;\n }\n const sqrtD = Math.sqrt(determinant);\n let r1 = (-b - sqrtD) / (2.0 * a);\n let r2 = (-b + sqrtD) / (2.0 * a);\n if (r1 > r2) {\n const temp = r2;\n r2 = r1;\n r1 = temp;\n }\n if (r1 > 0 && r1 < maxR) {\n result.root = r1;\n result.found = true;\n return result;\n }\n if (r2 > 0 && r2 < maxR) {\n result.root = r2;\n result.found = true;\n return result;\n }\n return result;\n };\n})();\n/** @internal */\nexport class Collider {\n constructor() {\n // Implementation of the \"Improved Collision detection and Response\" algorithm proposed by Kasper Fauerby\n // https://www.peroxide.dk/papers/collision/collision.pdf\n this._collisionPoint = Vector3.Zero();\n this._planeIntersectionPoint = Vector3.Zero();\n this._tempVector = Vector3.Zero();\n this._tempVector2 = Vector3.Zero();\n this._tempVector3 = Vector3.Zero();\n this._tempVector4 = Vector3.Zero();\n this._edge = Vector3.Zero();\n this._baseToVertex = Vector3.Zero();\n this._destinationPoint = Vector3.Zero();\n this._slidePlaneNormal = Vector3.Zero();\n this._displacementVector = Vector3.Zero();\n /** @internal */\n this._radius = Vector3.One();\n /** @internal */\n this._retry = 0;\n /** @internal */\n this._basePointWorld = Vector3.Zero();\n this._velocityWorld = Vector3.Zero();\n this._normalizedVelocity = Vector3.Zero();\n this._collisionMask = -1;\n }\n get collisionMask() {\n return this._collisionMask;\n }\n set collisionMask(mask) {\n this._collisionMask = !isNaN(mask) ? mask : -1;\n }\n /**\n * Gets the plane normal used to compute the sliding response (in local space)\n */\n get slidePlaneNormal() {\n return this._slidePlaneNormal;\n }\n // Methods\n /**\n * @internal\n */\n _initialize(source, dir, e) {\n this._velocity = dir;\n this._velocitySquaredLength = this._velocity.lengthSquared();\n const len = Math.sqrt(this._velocitySquaredLength);\n if (len === 0 || len === 1.0) {\n this._normalizedVelocity.copyFromFloats(dir._x, dir._y, dir._z);\n }\n else {\n dir.scaleToRef(1.0 / len, this._normalizedVelocity);\n }\n this._basePoint = source;\n source.multiplyToRef(this._radius, this._basePointWorld);\n dir.multiplyToRef(this._radius, this._velocityWorld);\n this._velocityWorldLength = this._velocityWorld.length();\n this._epsilon = e;\n this.collisionFound = false;\n }\n /**\n * @internal\n */\n _checkPointInTriangle(point, pa, pb, pc, n) {\n pa.subtractToRef(point, this._tempVector);\n pb.subtractToRef(point, this._tempVector2);\n Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);\n let d = Vector3.Dot(this._tempVector4, n);\n if (d < 0) {\n return false;\n }\n pc.subtractToRef(point, this._tempVector3);\n Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);\n d = Vector3.Dot(this._tempVector4, n);\n if (d < 0) {\n return false;\n }\n Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);\n d = Vector3.Dot(this._tempVector4, n);\n return d >= 0;\n }\n /**\n * @internal\n */\n _canDoCollision(sphereCenter, sphereRadius, vecMin, vecMax) {\n const distance = Vector3.Distance(this._basePointWorld, sphereCenter);\n const max = Math.max(this._radius.x, this._radius.y, this._radius.z);\n if (distance > this._velocityWorldLength + max + sphereRadius) {\n return false;\n }\n if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max)) {\n return false;\n }\n return true;\n }\n /**\n * @internal\n */\n _testTriangle(faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial, hostMesh) {\n let t0;\n let embeddedInPlane = false;\n //defensive programming, actually not needed.\n if (!trianglePlaneArray) {\n trianglePlaneArray = [];\n }\n if (!trianglePlaneArray[faceIndex]) {\n trianglePlaneArray[faceIndex] = new Plane(0, 0, 0, 0);\n trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);\n }\n const trianglePlane = trianglePlaneArray[faceIndex];\n if (!hasMaterial && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0)) {\n return;\n }\n const signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);\n const normalDotVelocity = Vector3.Dot(trianglePlane.normal, this._velocity);\n // if DoubleSidedCheck is false(default), a double sided face will be consided 2 times.\n // if true, it discard the faces having normal not facing velocity\n if (Collider.DoubleSidedCheck && normalDotVelocity > 0.0001) {\n return;\n }\n if (normalDotVelocity == 0) {\n if (Math.abs(signedDistToTrianglePlane) >= 1.0) {\n return;\n }\n embeddedInPlane = true;\n t0 = 0;\n }\n else {\n t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;\n let t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;\n if (t0 > t1) {\n const temp = t1;\n t1 = t0;\n t0 = temp;\n }\n if (t0 > 1.0 || t1 < 0.0) {\n return;\n }\n if (t0 < 0) {\n t0 = 0;\n }\n if (t0 > 1.0) {\n t0 = 1.0;\n }\n }\n this._collisionPoint.copyFromFloats(0, 0, 0);\n let found = false;\n let t = 1.0;\n if (!embeddedInPlane) {\n this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);\n this._velocity.scaleToRef(t0, this._tempVector);\n this._planeIntersectionPoint.addInPlace(this._tempVector);\n if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {\n found = true;\n t = t0;\n this._collisionPoint.copyFrom(this._planeIntersectionPoint);\n }\n }\n if (!found) {\n let a = this._velocitySquaredLength;\n this._basePoint.subtractToRef(p1, this._tempVector);\n let b = 2.0 * Vector3.Dot(this._velocity, this._tempVector);\n let c = this._tempVector.lengthSquared() - 1.0;\n let lowestRoot = getLowestRoot(a, b, c, t);\n if (lowestRoot.found) {\n t = lowestRoot.root;\n found = true;\n this._collisionPoint.copyFrom(p1);\n }\n this._basePoint.subtractToRef(p2, this._tempVector);\n b = 2.0 * Vector3.Dot(this._velocity, this._tempVector);\n c = this._tempVector.lengthSquared() - 1.0;\n lowestRoot = getLowestRoot(a, b, c, t);\n if (lowestRoot.found) {\n t = lowestRoot.root;\n found = true;\n this._collisionPoint.copyFrom(p2);\n }\n this._basePoint.subtractToRef(p3, this._tempVector);\n b = 2.0 * Vector3.Dot(this._velocity, this._tempVector);\n c = this._tempVector.lengthSquared() - 1.0;\n lowestRoot = getLowestRoot(a, b, c, t);\n if (lowestRoot.found) {\n t = lowestRoot.root;\n found = true;\n this._collisionPoint.copyFrom(p3);\n }\n p2.subtractToRef(p1, this._edge);\n p1.subtractToRef(this._basePoint, this._baseToVertex);\n let edgeSquaredLength = this._edge.lengthSquared();\n let edgeDotVelocity = Vector3.Dot(this._edge, this._velocity);\n let edgeDotBaseToVertex = Vector3.Dot(this._edge, this._baseToVertex);\n a = edgeSquaredLength * -this._velocitySquaredLength + edgeDotVelocity * edgeDotVelocity;\n b = 2 * (edgeSquaredLength * Vector3.Dot(this._velocity, this._baseToVertex) - edgeDotVelocity * edgeDotBaseToVertex);\n c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;\n lowestRoot = getLowestRoot(a, b, c, t);\n if (lowestRoot.found) {\n const f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;\n if (f >= 0.0 && f <= 1.0) {\n t = lowestRoot.root;\n found = true;\n this._edge.scaleInPlace(f);\n p1.addToRef(this._edge, this._collisionPoint);\n }\n }\n p3.subtractToRef(p2, this._edge);\n p2.subtractToRef(this._basePoint, this._baseToVertex);\n edgeSquaredLength = this._edge.lengthSquared();\n edgeDotVelocity = Vector3.Dot(this._edge, this._velocity);\n edgeDotBaseToVertex = Vector3.Dot(this._edge, this._baseToVertex);\n a = edgeSquaredLength * -this._velocitySquaredLength + edgeDotVelocity * edgeDotVelocity;\n b = 2 * (edgeSquaredLength * Vector3.Dot(this._velocity, this._baseToVertex) - edgeDotVelocity * edgeDotBaseToVertex);\n c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;\n lowestRoot = getLowestRoot(a, b, c, t);\n if (lowestRoot.found) {\n const f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;\n if (f >= 0.0 && f <= 1.0) {\n t = lowestRoot.root;\n found = true;\n this._edge.scaleInPlace(f);\n p2.addToRef(this._edge, this._collisionPoint);\n }\n }\n p1.subtractToRef(p3, this._edge);\n p3.subtractToRef(this._basePoint, this._baseToVertex);\n edgeSquaredLength = this._edge.lengthSquared();\n edgeDotVelocity = Vector3.Dot(this._edge, this._velocity);\n edgeDotBaseToVertex = Vector3.Dot(this._edge, this._baseToVertex);\n a = edgeSquaredLength * -this._velocitySquaredLength + edgeDotVelocity * edgeDotVelocity;\n b = 2 * (edgeSquaredLength * Vector3.Dot(this._velocity, this._baseToVertex) - edgeDotVelocity * edgeDotBaseToVertex);\n c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;\n lowestRoot = getLowestRoot(a, b, c, t);\n if (lowestRoot.found) {\n const f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;\n if (f >= 0.0 && f <= 1.0) {\n t = lowestRoot.root;\n found = true;\n this._edge.scaleInPlace(f);\n p3.addToRef(this._edge, this._collisionPoint);\n }\n }\n }\n if (found) {\n const distToCollisionSquared = t * t * this._velocitySquaredLength;\n if (!this.collisionFound || distToCollisionSquared < this._nearestDistanceSquared) {\n // if collisionResponse is false, collision is not found but the collidedMesh is set anyway.\n // onCollide observable are triggered if collideMesh is set\n // this allow trigger volumes to be created.\n if (hostMesh.collisionResponse) {\n if (!this.intersectionPoint) {\n this.intersectionPoint = this._collisionPoint.clone();\n }\n else {\n this.intersectionPoint.copyFrom(this._collisionPoint);\n }\n this._nearestDistanceSquared = distToCollisionSquared;\n this._nearestDistance = Math.sqrt(distToCollisionSquared);\n this.collisionFound = true;\n }\n this.collidedMesh = hostMesh;\n }\n }\n }\n /**\n * @internal\n */\n _collide(trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial, hostMesh, invertTriangles, triangleStrip = false) {\n if (triangleStrip) {\n if (!indices || indices.length === 0) {\n for (let i = 0; i < pts.length - 2; i += 1) {\n const p1 = pts[i];\n const p2 = pts[i + 1];\n const p3 = pts[i + 2];\n // stay defensive and don't check against undefined positions.\n if (!p1 || !p2 || !p3) {\n continue;\n }\n // Handles strip faces one on two is reversed\n if ((invertTriangles ? 1 : 0) ^ i % 2) {\n this._testTriangle(i, trianglePlaneArray, p1, p2, p3, hasMaterial, hostMesh);\n }\n else {\n this._testTriangle(i, trianglePlaneArray, p2, p1, p3, hasMaterial, hostMesh);\n }\n }\n }\n else {\n for (let i = indexStart; i < indexEnd - 2; i += 1) {\n const indexA = indices[i];\n const indexB = indices[i + 1];\n const indexC = indices[i + 2];\n if (indexC === 0xffffffff) {\n i += 2;\n continue;\n }\n const p1 = pts[indexA];\n const p2 = pts[indexB];\n const p3 = pts[indexC];\n // stay defensive and don't check against undefined positions.\n if (!p1 || !p2 || !p3) {\n continue;\n }\n // Handles strip faces one on two is reversed\n if ((invertTriangles ? 1 : 0) ^ i % 2) {\n this._testTriangle(i, trianglePlaneArray, p1, p2, p3, hasMaterial, hostMesh);\n }\n else {\n this._testTriangle(i, trianglePlaneArray, p2, p1, p3, hasMaterial, hostMesh);\n }\n }\n }\n }\n else if (!indices || indices.length === 0) {\n for (let i = 0; i < pts.length; i += 3) {\n const p1 = pts[i];\n const p2 = pts[i + 1];\n const p3 = pts[i + 2];\n if (invertTriangles) {\n this._testTriangle(i, trianglePlaneArray, p1, p2, p3, hasMaterial, hostMesh);\n }\n else {\n this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial, hostMesh);\n }\n }\n }\n else {\n for (let i = indexStart; i < indexEnd; i += 3) {\n const p1 = pts[indices[i] - decal];\n const p2 = pts[indices[i + 1] - decal];\n const p3 = pts[indices[i + 2] - decal];\n if (invertTriangles) {\n this._testTriangle(i, trianglePlaneArray, p1, p2, p3, hasMaterial, hostMesh);\n }\n else {\n this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial, hostMesh);\n }\n }\n }\n }\n /**\n * @internal\n */\n _getResponse(pos, vel) {\n pos.addToRef(vel, this._destinationPoint);\n vel.scaleInPlace(this._nearestDistance / vel.length());\n this._basePoint.addToRef(vel, pos);\n pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);\n this._slidePlaneNormal.normalize();\n this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);\n pos.addInPlace(this._displacementVector);\n this.intersectionPoint.addInPlace(this._displacementVector);\n this._slidePlaneNormal.scaleInPlace(Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));\n this._destinationPoint.subtractInPlace(this._slidePlaneNormal);\n this._destinationPoint.subtractToRef(this.intersectionPoint, vel);\n }\n}\n/**\n * If true, it check for double sided faces and only returns 1 collision instead of 2\n */\nCollider.DoubleSidedCheck = false;\n//# sourceMappingURL=collider.js.map","import { Scene } from \"../scene.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { Collider } from \"./collider.js\";\n/** @internal */\nexport class DefaultCollisionCoordinator {\n constructor() {\n this._scaledPosition = Vector3.Zero();\n this._scaledVelocity = Vector3.Zero();\n this._finalPosition = Vector3.Zero();\n }\n getNewPosition(position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {\n position.divideToRef(collider._radius, this._scaledPosition);\n displacement.divideToRef(collider._radius, this._scaledVelocity);\n collider.collidedMesh = null;\n collider._retry = 0;\n collider._initialVelocity = this._scaledVelocity;\n collider._initialPosition = this._scaledPosition;\n this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);\n this._finalPosition.multiplyInPlace(collider._radius);\n //run the callback\n onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);\n }\n createCollider() {\n return new Collider();\n }\n init(scene) {\n this._scene = scene;\n }\n _collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh = null) {\n const closeDistance = Engine.CollisionsEpsilon * 10.0;\n if (collider._retry >= maximumRetry) {\n finalPosition.copyFrom(position);\n return;\n }\n // Check if this is a mesh else camera or -1\n const collisionMask = excludedMesh ? excludedMesh.collisionMask : collider.collisionMask;\n collider._initialize(position, velocity, closeDistance);\n // Check if collision detection should happen against specified list of meshes or,\n // if not specified, against all meshes in the scene\n const meshes = (excludedMesh && excludedMesh.surroundingMeshes) || this._scene.meshes;\n for (let index = 0; index < meshes.length; index++) {\n const mesh = meshes[index];\n if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && (collisionMask & mesh.collisionGroup) !== 0) {\n mesh._checkCollision(collider);\n }\n }\n if (!collider.collisionFound) {\n position.addToRef(velocity, finalPosition);\n return;\n }\n if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {\n collider._getResponse(position, velocity);\n }\n if (velocity.length() <= closeDistance) {\n finalPosition.copyFrom(position);\n return;\n }\n collider._retry++;\n this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);\n }\n}\nScene.CollisionCoordinatorFactory = () => {\n return new DefaultCollisionCoordinator();\n};\n//# sourceMappingURL=collisionCoordinator.js.map","export * from \"./collider.js\";\nexport * from \"./collisionCoordinator.js\";\nexport * from \"./pickingInfo.js\";\nexport * from \"./intersectionInfo.js\";\nexport * from \"./meshCollisionData.js\";\n//# sourceMappingURL=index.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { GetDOMTextContent, IsWindowObjectExist } from \"../Misc/domManagement.js\";\nimport { ShaderProcessor } from \"../Engines/Processors/shaderProcessor.js\";\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport { ShaderLanguage } from \"../Materials/shaderLanguage.js\";\n/**\n * Effect wrapping a compute shader and let execute (dispatch) the shader\n */\nexport class ComputeEffect {\n /**\n * Creates a compute effect that can be used to execute a compute shader\n * @param baseName Name of the effect\n * @param options Set of all options to create the effect\n * @param engine The engine the effect is created for\n * @param key Effect Key identifying uniquely compiled shader variants\n */\n constructor(baseName, options, engine, key = \"\") {\n var _a, _b;\n /**\n * Name of the effect.\n */\n this.name = null;\n /**\n * String container all the define statements that should be set on the shader.\n */\n this.defines = \"\";\n /**\n * Callback that will be called when the shader is compiled.\n */\n this.onCompiled = null;\n /**\n * Callback that will be called if an error occurs during shader compilation.\n */\n this.onError = null;\n /**\n * Unique ID of the effect.\n */\n this.uniqueId = 0;\n /**\n * Observable that will be called when the shader is compiled.\n * It is recommended to use executeWhenCompile() or to make sure that scene.isReady() is called to get this observable raised.\n */\n this.onCompileObservable = new Observable();\n /**\n * Observable that will be called if an error occurs during shader compilation.\n */\n this.onErrorObservable = new Observable();\n /**\n * Observable that will be called when effect is bound.\n */\n this.onBindObservable = new Observable();\n /**\n * @internal\n * Specifies if the effect was previously ready\n */\n this._wasPreviouslyReady = false;\n this._isReady = false;\n this._compilationError = \"\";\n /** @internal */\n this._key = \"\";\n this._computeSourceCodeOverride = \"\";\n /** @internal */\n this._pipelineContext = null;\n /** @internal */\n this._computeSourceCode = \"\";\n this._rawComputeSourceCode = \"\";\n this._shaderLanguage = ShaderLanguage.WGSL;\n this.name = baseName;\n this._key = key;\n this._engine = engine;\n this.uniqueId = ComputeEffect._UniqueIdSeed++;\n this.defines = (_a = options.defines) !== null && _a !== void 0 ? _a : \"\";\n this.onError = options.onError;\n this.onCompiled = options.onCompiled;\n this._entryPoint = (_b = options.entryPoint) !== null && _b !== void 0 ? _b : \"main\";\n this._shaderStore = ShaderStore.GetShadersStore(this._shaderLanguage);\n this._shaderRepository = ShaderStore.GetShadersRepository(this._shaderLanguage);\n this._includeShaderStore = ShaderStore.GetIncludesShadersStore(this._shaderLanguage);\n let computeSource;\n const hostDocument = IsWindowObjectExist() ? this._engine.getHostDocument() : null;\n if (baseName.computeSource) {\n computeSource = \"source:\" + baseName.computeSource;\n }\n else if (baseName.computeElement) {\n computeSource = hostDocument ? hostDocument.getElementById(baseName.computeElement) : null;\n if (!computeSource) {\n computeSource = baseName.computeElement;\n }\n }\n else {\n computeSource = baseName.compute || baseName;\n }\n const processorOptions = {\n defines: this.defines.split(\"\\n\"),\n indexParameters: undefined,\n isFragment: false,\n shouldUseHighPrecisionShader: false,\n processor: null,\n supportsUniformBuffers: this._engine.supportsUniformBuffers,\n shadersRepository: this._shaderRepository,\n includesShadersStore: this._includeShaderStore,\n version: (this._engine.version * 100).toString(),\n platformName: this._engine.shaderPlatformName,\n processingContext: null,\n isNDCHalfZRange: this._engine.isNDCHalfZRange,\n useReverseDepthBuffer: this._engine.useReverseDepthBuffer,\n };\n this._loadShader(computeSource, \"Compute\", \"\", (computeCode) => {\n ShaderProcessor.Initialize(processorOptions);\n ShaderProcessor.PreProcess(computeCode, processorOptions, (migratedCommputeCode) => {\n this._rawComputeSourceCode = computeCode;\n if (options.processFinalCode) {\n migratedCommputeCode = options.processFinalCode(migratedCommputeCode);\n }\n const finalShaders = ShaderProcessor.Finalize(migratedCommputeCode, \"\", processorOptions);\n this._useFinalCode(finalShaders.vertexCode, baseName);\n }, this._engine);\n });\n }\n _useFinalCode(migratedCommputeCode, baseName) {\n if (baseName) {\n const compute = baseName.computeElement || baseName.compute || baseName.spectorName || baseName;\n this._computeSourceCode = \"//#define SHADER_NAME compute:\" + compute + \"\\n\" + migratedCommputeCode;\n }\n else {\n this._computeSourceCode = migratedCommputeCode;\n }\n this._prepareEffect();\n }\n /**\n * Unique key for this effect\n */\n get key() {\n return this._key;\n }\n /**\n * If the effect has been compiled and prepared.\n * @returns if the effect is compiled and prepared.\n */\n isReady() {\n try {\n return this._isReadyInternal();\n }\n catch (_a) {\n return false;\n }\n }\n _isReadyInternal() {\n if (this._isReady) {\n return true;\n }\n if (this._pipelineContext) {\n return this._pipelineContext.isReady;\n }\n return false;\n }\n /**\n * The engine the effect was initialized with.\n * @returns the engine.\n */\n getEngine() {\n return this._engine;\n }\n /**\n * The pipeline context for this effect\n * @returns the associated pipeline context\n */\n getPipelineContext() {\n return this._pipelineContext;\n }\n /**\n * The error from the last compilation.\n * @returns the error string.\n */\n getCompilationError() {\n return this._compilationError;\n }\n /**\n * Adds a callback to the onCompiled observable and call the callback immediately if already ready.\n * @param func The callback to be used.\n */\n executeWhenCompiled(func) {\n if (this.isReady()) {\n func(this);\n return;\n }\n this.onCompileObservable.add((effect) => {\n func(effect);\n });\n if (!this._pipelineContext || this._pipelineContext.isAsync) {\n setTimeout(() => {\n this._checkIsReady(null);\n }, 16);\n }\n }\n _checkIsReady(previousPipelineContext) {\n try {\n if (this._isReadyInternal()) {\n return;\n }\n }\n catch (e) {\n this._processCompilationErrors(e, previousPipelineContext);\n return;\n }\n setTimeout(() => {\n this._checkIsReady(previousPipelineContext);\n }, 16);\n }\n _loadShader(shader, key, optionalKey, callback) {\n if (typeof HTMLElement !== \"undefined\") {\n // DOM element ?\n if (shader instanceof HTMLElement) {\n const shaderCode = GetDOMTextContent(shader);\n callback(shaderCode);\n return;\n }\n }\n // Direct source ?\n if (shader.substr(0, 7) === \"source:\") {\n callback(shader.substr(7));\n return;\n }\n // Base64 encoded ?\n if (shader.substr(0, 7) === \"base64:\") {\n const shaderBinary = window.atob(shader.substr(7));\n callback(shaderBinary);\n return;\n }\n // Is in local store ?\n if (this._shaderStore[shader + key + \"Shader\"]) {\n callback(this._shaderStore[shader + key + \"Shader\"]);\n return;\n }\n if (optionalKey && this._shaderStore[shader + optionalKey + \"Shader\"]) {\n callback(this._shaderStore[shader + optionalKey + \"Shader\"]);\n return;\n }\n let shaderUrl;\n if (shader[0] === \".\" || shader[0] === \"/\" || shader.indexOf(\"http\") > -1) {\n shaderUrl = shader;\n }\n else {\n shaderUrl = this._shaderRepository + shader;\n }\n this._engine._loadFile(shaderUrl + \".\" + key.toLowerCase() + \".fx\", callback);\n }\n /**\n * Gets the compute shader source code of this effect\n */\n get computeSourceCode() {\n var _a, _b;\n return this._computeSourceCodeOverride ? this._computeSourceCodeOverride : (_b = (_a = this._pipelineContext) === null || _a === void 0 ? void 0 : _a._getComputeShaderCode()) !== null && _b !== void 0 ? _b : this._computeSourceCode;\n }\n /**\n * Gets the compute shader source code before it has been processed by the preprocessor\n */\n get rawComputeSourceCode() {\n return this._rawComputeSourceCode;\n }\n /**\n * Prepares the effect\n * @internal\n */\n _prepareEffect() {\n const defines = this.defines;\n const previousPipelineContext = this._pipelineContext;\n this._isReady = false;\n try {\n const engine = this._engine;\n this._pipelineContext = engine.createComputePipelineContext();\n this._pipelineContext._name = this._key;\n engine._prepareComputePipelineContext(this._pipelineContext, this._computeSourceCodeOverride ? this._computeSourceCodeOverride : this._computeSourceCode, this._rawComputeSourceCode, this._computeSourceCodeOverride ? null : defines, this._entryPoint);\n engine._executeWhenComputeStateIsCompiled(this._pipelineContext, () => {\n this._compilationError = \"\";\n this._isReady = true;\n if (this.onCompiled) {\n this.onCompiled(this);\n }\n this.onCompileObservable.notifyObservers(this);\n this.onCompileObservable.clear();\n if (previousPipelineContext) {\n this.getEngine()._deleteComputePipelineContext(previousPipelineContext);\n }\n });\n if (this._pipelineContext.isAsync) {\n this._checkIsReady(previousPipelineContext);\n }\n }\n catch (e) {\n this._processCompilationErrors(e, previousPipelineContext);\n }\n }\n _getShaderCodeAndErrorLine(code, error) {\n const regexp = /COMPUTE SHADER ERROR: 0:(\\d+?):/;\n let errorLine = null;\n if (error && code) {\n const res = error.match(regexp);\n if (res && res.length === 2) {\n const lineNumber = parseInt(res[1]);\n const lines = code.split(\"\\n\", -1);\n if (lines.length >= lineNumber) {\n errorLine = `Offending line [${lineNumber}] in compute code: ${lines[lineNumber - 1]}`;\n }\n }\n }\n return [code, errorLine];\n }\n _processCompilationErrors(e, previousPipelineContext = null) {\n var _a;\n this._compilationError = e.message;\n // Let's go through fallbacks then\n Logger.Error(\"Unable to compile compute effect:\");\n Logger.Error(\"Defines:\\r\\n\" + this.defines);\n if (ComputeEffect.LogShaderCodeOnCompilationError) {\n let lineErrorVertex = null, code = null;\n if ((_a = this._pipelineContext) === null || _a === void 0 ? void 0 : _a._getComputeShaderCode()) {\n [code, lineErrorVertex] = this._getShaderCodeAndErrorLine(this._pipelineContext._getComputeShaderCode(), this._compilationError);\n if (code) {\n Logger.Error(\"Compute code:\");\n Logger.Error(code);\n }\n }\n if (lineErrorVertex) {\n Logger.Error(lineErrorVertex);\n }\n }\n Logger.Error(\"Error: \" + this._compilationError);\n if (previousPipelineContext) {\n this._pipelineContext = previousPipelineContext;\n this._isReady = true;\n if (this.onError) {\n this.onError(this, this._compilationError);\n }\n this.onErrorObservable.notifyObservers(this);\n }\n }\n /**\n * Release all associated resources.\n **/\n dispose() {\n if (this._pipelineContext) {\n this._pipelineContext.dispose();\n }\n this._engine._releaseComputeEffect(this);\n }\n /**\n * This function will add a new compute shader to the shader store\n * @param name the name of the shader\n * @param computeShader compute shader content\n */\n static RegisterShader(name, computeShader) {\n ShaderStore.GetShadersStore(ShaderLanguage.WGSL)[`${name}ComputeShader`] = computeShader;\n }\n}\nComputeEffect._UniqueIdSeed = 0;\n/**\n * Enable logging of the shader code when a compilation error occurs\n */\nComputeEffect.LogShaderCodeOnCompilationError = true;\n//# sourceMappingURL=computeEffect.js.map","import { ThinEngine } from \"../../Engines/thinEngine.js\";\n/** @internal */\nexport var ComputeBindingType;\n(function (ComputeBindingType) {\n ComputeBindingType[ComputeBindingType[\"Texture\"] = 0] = \"Texture\";\n ComputeBindingType[ComputeBindingType[\"StorageTexture\"] = 1] = \"StorageTexture\";\n ComputeBindingType[ComputeBindingType[\"UniformBuffer\"] = 2] = \"UniformBuffer\";\n ComputeBindingType[ComputeBindingType[\"StorageBuffer\"] = 3] = \"StorageBuffer\";\n ComputeBindingType[ComputeBindingType[\"TextureWithoutSampler\"] = 4] = \"TextureWithoutSampler\";\n ComputeBindingType[ComputeBindingType[\"Sampler\"] = 5] = \"Sampler\";\n})(ComputeBindingType || (ComputeBindingType = {}));\nThinEngine.prototype.createComputeEffect = function (baseName, options) {\n throw new Error(\"createComputeEffect: This engine does not support compute shaders!\");\n};\nThinEngine.prototype.createComputePipelineContext = function () {\n throw new Error(\"createComputePipelineContext: This engine does not support compute shaders!\");\n};\nThinEngine.prototype.createComputeContext = function () {\n return undefined;\n};\nThinEngine.prototype.computeDispatch = function (effect, context, bindings, x, y, z, bindingsMapping) {\n throw new Error(\"computeDispatch: This engine does not support compute shaders!\");\n};\nThinEngine.prototype.areAllComputeEffectsReady = function () {\n return true;\n};\nThinEngine.prototype.releaseComputeEffects = function () { };\nThinEngine.prototype._prepareComputePipelineContext = function (pipelineContext, computeSourceCode, rawComputeSourceCode, defines, entryPoint) { };\nThinEngine.prototype._rebuildComputeEffects = function () { };\nThinEngine.prototype._executeWhenComputeStateIsCompiled = function (pipelineContext, action) {\n action();\n};\nThinEngine.prototype._releaseComputeEffect = function (effect) { };\nThinEngine.prototype._deleteComputePipelineContext = function (pipelineContext) { };\n//# sourceMappingURL=engine.computeShader.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { SerializationHelper, serialize } from \"../Misc/decorators.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\nimport { ComputeBindingType } from \"../Engines/Extensions/engine.computeShader.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { UniqueIdGenerator } from \"../Misc/uniqueIdGenerator.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { TextureSampler } from \"../Materials/Textures/textureSampler.js\";\n/**\n * The ComputeShader object lets you execute a compute shader on your GPU (if supported by the engine)\n */\nexport class ComputeShader {\n /**\n * The options used to create the shader\n */\n get options() {\n return this._options;\n }\n /**\n * The shaderPath used to create the shader\n */\n get shaderPath() {\n return this._shaderPath;\n }\n /**\n * Instantiates a new compute shader.\n * @param name Defines the name of the compute shader in the scene\n * @param engine Defines the engine the compute shader belongs to\n * @param shaderPath Defines the route to the shader code in one of three ways:\n * * object: \\{ compute: \"custom\" \\}, used with ShaderStore.ShadersStoreWGSL[\"customComputeShader\"]\n * * object: \\{ computeElement: \"HTMLElementId\" \\}, used with shader code in script tags\n * * object: \\{ computeSource: \"compute shader code string\" \\}, where the string contains the shader code\n * * string: try first to find the code in ShaderStore.ShadersStoreWGSL[shaderPath + \"ComputeShader\"]. If not, assumes it is a file with name shaderPath.compute.fx in index.html folder.\n * @param options Define the options used to create the shader\n */\n constructor(name, engine, shaderPath, options = {}) {\n this._bindings = {};\n this._samplers = {};\n this._contextIsDirty = false;\n /**\n * Callback triggered when the shader is compiled\n */\n this.onCompiled = null;\n /**\n * Callback triggered when an error occurs\n */\n this.onError = null;\n this.name = name;\n this._engine = engine;\n this.uniqueId = UniqueIdGenerator.UniqueId;\n if (!this._engine.getCaps().supportComputeShaders) {\n Logger.Error(\"This engine does not support compute shaders!\");\n return;\n }\n if (!options.bindingsMapping) {\n Logger.Error(\"You must provide the binding mappings as browsers don't support reflection for wgsl shaders yet!\");\n return;\n }\n this._context = engine.createComputeContext();\n this._shaderPath = shaderPath;\n this._options = Object.assign({ bindingsMapping: {}, defines: [] }, options);\n }\n /**\n * Gets the current class name of the material e.g. \"ComputeShader\"\n * Mainly use in serialization.\n * @returns the class name\n */\n getClassName() {\n return \"ComputeShader\";\n }\n /**\n * Binds a texture to the shader\n * @param name Binding name of the texture\n * @param texture Texture to bind\n * @param bindSampler Bind the sampler corresponding to the texture (default: true). The sampler will be bound just before the binding index of the texture\n */\n setTexture(name, texture, bindSampler = true) {\n const current = this._bindings[name];\n this._bindings[name] = {\n type: bindSampler ? ComputeBindingType.Texture : ComputeBindingType.TextureWithoutSampler,\n object: texture,\n indexInGroupEntries: current === null || current === void 0 ? void 0 : current.indexInGroupEntries,\n };\n this._contextIsDirty || (this._contextIsDirty = !current || current.object !== texture || current.type !== this._bindings[name].type);\n }\n /**\n * Binds a storage texture to the shader\n * @param name Binding name of the texture\n * @param texture Texture to bind\n */\n setStorageTexture(name, texture) {\n const current = this._bindings[name];\n this._contextIsDirty || (this._contextIsDirty = !current || current.object !== texture);\n this._bindings[name] = {\n type: ComputeBindingType.StorageTexture,\n object: texture,\n indexInGroupEntries: current === null || current === void 0 ? void 0 : current.indexInGroupEntries,\n };\n }\n /**\n * Binds a uniform buffer to the shader\n * @param name Binding name of the buffer\n * @param buffer Buffer to bind\n */\n setUniformBuffer(name, buffer) {\n const current = this._bindings[name];\n this._contextIsDirty || (this._contextIsDirty = !current || current.object !== buffer);\n this._bindings[name] = {\n type: ComputeBindingType.UniformBuffer,\n object: buffer,\n indexInGroupEntries: current === null || current === void 0 ? void 0 : current.indexInGroupEntries,\n };\n }\n /**\n * Binds a storage buffer to the shader\n * @param name Binding name of the buffer\n * @param buffer Buffer to bind\n */\n setStorageBuffer(name, buffer) {\n const current = this._bindings[name];\n this._contextIsDirty || (this._contextIsDirty = !current || current.object !== buffer);\n this._bindings[name] = {\n type: ComputeBindingType.StorageBuffer,\n object: buffer,\n indexInGroupEntries: current === null || current === void 0 ? void 0 : current.indexInGroupEntries,\n };\n }\n /**\n * Binds a texture sampler to the shader\n * @param name Binding name of the sampler\n * @param sampler Sampler to bind\n */\n setTextureSampler(name, sampler) {\n const current = this._bindings[name];\n this._contextIsDirty || (this._contextIsDirty = !current || !sampler.compareSampler(current.object));\n this._bindings[name] = {\n type: ComputeBindingType.Sampler,\n object: sampler,\n indexInGroupEntries: current === null || current === void 0 ? void 0 : current.indexInGroupEntries,\n };\n }\n /**\n * Specifies that the compute shader is ready to be executed (the compute effect and all the resources are ready)\n * @returns true if the compute shader is ready to be executed\n */\n isReady() {\n let effect = this._effect;\n for (const key in this._bindings) {\n const binding = this._bindings[key], type = binding.type, object = binding.object;\n switch (type) {\n case ComputeBindingType.Texture:\n case ComputeBindingType.TextureWithoutSampler:\n case ComputeBindingType.StorageTexture: {\n const texture = object;\n if (!texture.isReady()) {\n return false;\n }\n break;\n }\n }\n }\n const defines = [];\n const shaderName = this._shaderPath;\n if (this._options.defines) {\n for (let index = 0; index < this._options.defines.length; index++) {\n defines.push(this._options.defines[index]);\n }\n }\n const join = defines.join(\"\\n\");\n if (this._cachedDefines !== join) {\n this._cachedDefines = join;\n effect = this._engine.createComputeEffect(shaderName, {\n defines: join,\n entryPoint: this._options.entryPoint,\n onCompiled: this.onCompiled,\n onError: this.onError,\n });\n this._effect = effect;\n }\n if (!effect.isReady()) {\n return false;\n }\n return true;\n }\n /**\n * Dispatches (executes) the compute shader\n * @param x Number of workgroups to execute on the X dimension\n * @param y Number of workgroups to execute on the Y dimension (default: 1)\n * @param z Number of workgroups to execute on the Z dimension (default: 1)\n * @returns True if the dispatch could be done, else false (meaning either the compute effect or at least one of the bound resources was not ready)\n */\n dispatch(x, y, z) {\n var _a;\n if (!this.isReady()) {\n return false;\n }\n // If the sampling parameters of a texture bound to the shader have changed, we must clear the compute context so that it is recreated with the updated values\n // Also, if the actual (gpu) buffer used by a uniform buffer has changed, we must clear the compute context so that it is recreated with the updated value\n for (const key in this._bindings) {\n const binding = this._bindings[key];\n if (!this._options.bindingsMapping[key]) {\n throw new Error(\"ComputeShader ('\" + this.name + \"'): No binding mapping has been provided for the property '\" + key + \"'\");\n }\n switch (binding.type) {\n case ComputeBindingType.Texture: {\n const sampler = this._samplers[key];\n const texture = binding.object;\n if (!sampler || !texture._texture || !sampler.compareSampler(texture._texture)) {\n this._samplers[key] = new TextureSampler().setParameters(texture.wrapU, texture.wrapV, texture.wrapR, texture.anisotropicFilteringLevel, texture._texture.samplingMode, (_a = texture._texture) === null || _a === void 0 ? void 0 : _a._comparisonFunction);\n this._contextIsDirty = true;\n }\n break;\n }\n case ComputeBindingType.UniformBuffer: {\n const ubo = binding.object;\n if (ubo.getBuffer() !== binding.buffer) {\n binding.buffer = ubo.getBuffer();\n this._contextIsDirty = true;\n }\n break;\n }\n }\n }\n if (this._contextIsDirty) {\n this._contextIsDirty = false;\n this._context.clear();\n }\n this._engine.computeDispatch(this._effect, this._context, this._bindings, x, y, z, this._options.bindingsMapping);\n return true;\n }\n /**\n * Waits for the compute shader to be ready and executes it\n * @param x Number of workgroups to execute on the X dimension\n * @param y Number of workgroups to execute on the Y dimension (default: 1)\n * @param z Number of workgroups to execute on the Z dimension (default: 1)\n * @param delay Delay between the retries while the shader is not ready (in milliseconds - 10 by default)\n * @returns A promise that is resolved once the shader has been sent to the GPU. Note that it does not mean that the shader execution itself is finished!\n */\n dispatchWhenReady(x, y, z, delay = 10) {\n return new Promise((resolve) => {\n const check = () => {\n if (!this.dispatch(x, y, z)) {\n setTimeout(check, delay);\n }\n else {\n resolve();\n }\n };\n check();\n });\n }\n /**\n * Serializes this compute shader in a JSON representation\n * @returns the serialized compute shader object\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this);\n serializationObject.options = this._options;\n serializationObject.shaderPath = this._shaderPath;\n serializationObject.bindings = {};\n serializationObject.textures = {};\n for (const key in this._bindings) {\n const binding = this._bindings[key];\n const object = binding.object;\n switch (binding.type) {\n case ComputeBindingType.Texture:\n case ComputeBindingType.TextureWithoutSampler:\n case ComputeBindingType.StorageTexture: {\n const serializedData = object.serialize();\n if (serializedData) {\n serializationObject.textures[key] = serializedData;\n serializationObject.bindings[key] = {\n type: binding.type,\n };\n }\n break;\n }\n case ComputeBindingType.UniformBuffer: {\n break;\n }\n }\n }\n return serializationObject;\n }\n /**\n * Creates a compute shader from parsed compute shader data\n * @param source defines the JSON representation of the compute shader\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @returns a new compute shader\n */\n static Parse(source, scene, rootUrl) {\n const compute = SerializationHelper.Parse(() => new ComputeShader(source.name, scene.getEngine(), source.shaderPath, source.options), source, scene, rootUrl);\n for (const key in source.textures) {\n const binding = source.bindings[key];\n const texture = Texture.Parse(source.textures[key], scene, rootUrl);\n if (binding.type === ComputeBindingType.Texture) {\n compute.setTexture(key, texture);\n }\n else if (binding.type === ComputeBindingType.TextureWithoutSampler) {\n compute.setTexture(key, texture, false);\n }\n else {\n compute.setStorageTexture(key, texture);\n }\n }\n return compute;\n }\n}\n__decorate([\n serialize()\n], ComputeShader.prototype, \"name\", void 0);\nRegisterClass(\"BABYLON.ComputeShader\", ComputeShader);\n//# sourceMappingURL=computeShader.js.map","export * from \"./computeEffect.js\";\nexport * from \"./computeShader.js\";\n//# sourceMappingURL=index.js.map","import { Vector3 } from \"../../Maths/math.vector.js\";\nimport { BoundingBox } from \"../../Culling/boundingBox.js\";\n/**\n * Class used to store a cell in an octree\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimizeOctrees\n */\nexport class OctreeBlock {\n /**\n * Creates a new block\n * @param minPoint defines the minimum vector (in world space) of the block's bounding box\n * @param maxPoint defines the maximum vector (in world space) of the block's bounding box\n * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)\n * @param depth defines the current depth of this block in the octree\n * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)\n * @param creationFunc defines a callback to call when an element is added to the block\n */\n constructor(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {\n /**\n * Gets the content of the current block\n */\n this.entries = new Array();\n this._boundingVectors = new Array();\n this._capacity = capacity;\n this._depth = depth;\n this._maxDepth = maxDepth;\n this._creationFunc = creationFunc;\n this._minPoint = minPoint;\n this._maxPoint = maxPoint;\n this._boundingVectors.push(minPoint.clone());\n this._boundingVectors.push(maxPoint.clone());\n this._boundingVectors.push(minPoint.clone());\n this._boundingVectors[2].x = maxPoint.x;\n this._boundingVectors.push(minPoint.clone());\n this._boundingVectors[3].y = maxPoint.y;\n this._boundingVectors.push(minPoint.clone());\n this._boundingVectors[4].z = maxPoint.z;\n this._boundingVectors.push(maxPoint.clone());\n this._boundingVectors[5].z = minPoint.z;\n this._boundingVectors.push(maxPoint.clone());\n this._boundingVectors[6].x = minPoint.x;\n this._boundingVectors.push(maxPoint.clone());\n this._boundingVectors[7].y = minPoint.y;\n }\n // Property\n /**\n * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)\n */\n get capacity() {\n return this._capacity;\n }\n /**\n * Gets the minimum vector (in world space) of the block's bounding box\n */\n get minPoint() {\n return this._minPoint;\n }\n /**\n * Gets the maximum vector (in world space) of the block's bounding box\n */\n get maxPoint() {\n return this._maxPoint;\n }\n // Methods\n /**\n * Add a new element to this block\n * @param entry defines the element to add\n */\n addEntry(entry) {\n if (this.blocks) {\n for (let index = 0; index < this.blocks.length; index++) {\n const block = this.blocks[index];\n block.addEntry(entry);\n }\n return;\n }\n this._creationFunc(entry, this);\n if (this.entries.length > this.capacity && this._depth < this._maxDepth) {\n this.createInnerBlocks();\n }\n }\n /**\n * Remove an element from this block\n * @param entry defines the element to remove\n */\n removeEntry(entry) {\n if (this.blocks) {\n for (let index = 0; index < this.blocks.length; index++) {\n const block = this.blocks[index];\n block.removeEntry(entry);\n }\n return;\n }\n const entryIndex = this.entries.indexOf(entry);\n if (entryIndex > -1) {\n this.entries.splice(entryIndex, 1);\n }\n }\n /**\n * Add an array of elements to this block\n * @param entries defines the array of elements to add\n */\n addEntries(entries) {\n for (let index = 0; index < entries.length; index++) {\n const mesh = entries[index];\n this.addEntry(mesh);\n }\n }\n /**\n * Test if the current block intersects the frustum planes and if yes, then add its content to the selection array\n * @param frustumPlanes defines the frustum planes to test\n * @param selection defines the array to store current content if selection is positive\n * @param allowDuplicate defines if the selection array can contains duplicated entries\n */\n select(frustumPlanes, selection, allowDuplicate) {\n if (BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {\n if (this.blocks) {\n for (let index = 0; index < this.blocks.length; index++) {\n const block = this.blocks[index];\n block.select(frustumPlanes, selection, allowDuplicate);\n }\n return;\n }\n if (allowDuplicate) {\n selection.concat(this.entries);\n }\n else {\n selection.concatWithNoDuplicate(this.entries);\n }\n }\n }\n /**\n * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array\n * @param sphereCenter defines the bounding sphere center\n * @param sphereRadius defines the bounding sphere radius\n * @param selection defines the array to store current content if selection is positive\n * @param allowDuplicate defines if the selection array can contains duplicated entries\n */\n intersects(sphereCenter, sphereRadius, selection, allowDuplicate) {\n if (BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {\n if (this.blocks) {\n for (let index = 0; index < this.blocks.length; index++) {\n const block = this.blocks[index];\n block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);\n }\n return;\n }\n if (allowDuplicate) {\n selection.concat(this.entries);\n }\n else {\n selection.concatWithNoDuplicate(this.entries);\n }\n }\n }\n /**\n * Test if the current block intersect with the given ray and if yes, then add its content to the selection array\n * @param ray defines the ray to test with\n * @param selection defines the array to store current content if selection is positive\n */\n intersectsRay(ray, selection) {\n if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {\n if (this.blocks) {\n for (let index = 0; index < this.blocks.length; index++) {\n const block = this.blocks[index];\n block.intersectsRay(ray, selection);\n }\n return;\n }\n selection.concatWithNoDuplicate(this.entries);\n }\n }\n /**\n * Subdivide the content into child blocks (this block will then be empty)\n */\n createInnerBlocks() {\n OctreeBlock._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);\n this.entries.splice(0);\n }\n /**\n * @internal\n */\n static _CreateBlocks(worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {\n target.blocks = new Array();\n const blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);\n // Segmenting space\n for (let x = 0; x < 2; x++) {\n for (let y = 0; y < 2; y++) {\n for (let z = 0; z < 2; z++) {\n const localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));\n const localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));\n const block = new OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);\n block.addEntries(entries);\n target.blocks.push(block);\n }\n }\n }\n }\n}\n//# sourceMappingURL=octreeBlock.js.map","import { SmartArrayNoDuplicate } from \"../../Misc/smartArray.js\";\nimport { OctreeBlock } from \"./octreeBlock.js\";\n/**\n * Octrees are a really powerful data structure that can quickly select entities based on space coordinates.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimizeOctrees\n */\nexport class Octree {\n /**\n * Creates a octree\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimizeOctrees\n * @param creationFunc function to be used to instantiate the octree\n * @param maxBlockCapacity defines the maximum number of meshes you want on your octree's leaves (default: 64)\n * @param maxDepth defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.)\n */\n constructor(creationFunc, maxBlockCapacity, \n /** Defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.) */\n maxDepth = 2) {\n this.maxDepth = maxDepth;\n /**\n * Content stored in the octree\n */\n this.dynamicContent = new Array();\n this._maxBlockCapacity = maxBlockCapacity || 64;\n this._selectionContent = new SmartArrayNoDuplicate(1024);\n this._creationFunc = creationFunc;\n }\n // Methods\n /**\n * Updates the octree by adding blocks for the passed in meshes within the min and max world parameters\n * @param worldMin worldMin for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);\n * @param worldMax worldMax for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);\n * @param entries meshes to be added to the octree blocks\n */\n update(worldMin, worldMax, entries) {\n OctreeBlock._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);\n }\n /**\n * Adds a mesh to the octree\n * @param entry Mesh to add to the octree\n */\n addMesh(entry) {\n for (let index = 0; index < this.blocks.length; index++) {\n const block = this.blocks[index];\n block.addEntry(entry);\n }\n }\n /**\n * Remove an element from the octree\n * @param entry defines the element to remove\n */\n removeMesh(entry) {\n for (let index = 0; index < this.blocks.length; index++) {\n const block = this.blocks[index];\n block.removeEntry(entry);\n }\n }\n /**\n * Selects an array of meshes within the frustum\n * @param frustumPlanes The frustum planes to use which will select all meshes within it\n * @param allowDuplicate If duplicate objects are allowed in the resulting object array\n * @returns array of meshes within the frustum\n */\n select(frustumPlanes, allowDuplicate) {\n this._selectionContent.reset();\n for (let index = 0; index < this.blocks.length; index++) {\n const block = this.blocks[index];\n block.select(frustumPlanes, this._selectionContent, allowDuplicate);\n }\n if (allowDuplicate) {\n this._selectionContent.concat(this.dynamicContent);\n }\n else {\n this._selectionContent.concatWithNoDuplicate(this.dynamicContent);\n }\n return this._selectionContent;\n }\n /**\n * Test if the octree intersect with the given bounding sphere and if yes, then add its content to the selection array\n * @param sphereCenter defines the bounding sphere center\n * @param sphereRadius defines the bounding sphere radius\n * @param allowDuplicate defines if the selection array can contains duplicated entries\n * @returns an array of objects that intersect the sphere\n */\n intersects(sphereCenter, sphereRadius, allowDuplicate) {\n this._selectionContent.reset();\n for (let index = 0; index < this.blocks.length; index++) {\n const block = this.blocks[index];\n block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);\n }\n if (allowDuplicate) {\n this._selectionContent.concat(this.dynamicContent);\n }\n else {\n this._selectionContent.concatWithNoDuplicate(this.dynamicContent);\n }\n return this._selectionContent;\n }\n /**\n * Test if the octree intersect with the given ray and if yes, then add its content to resulting array\n * @param ray defines the ray to test with\n * @returns array of intersected objects\n */\n intersectsRay(ray) {\n this._selectionContent.reset();\n for (let index = 0; index < this.blocks.length; index++) {\n const block = this.blocks[index];\n block.intersectsRay(ray, this._selectionContent);\n }\n this._selectionContent.concatWithNoDuplicate(this.dynamicContent);\n return this._selectionContent;\n }\n}\n/**\n * Adds a mesh into the octree block if it intersects the block\n * @param entry\n * @param block\n */\nOctree.CreationFuncForMeshes = (entry, block) => {\n const boundingInfo = entry.getBoundingInfo();\n if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {\n block.entries.push(entry);\n }\n};\n/**\n * Adds a submesh into the octree block if it intersects the block\n * @param entry\n * @param block\n */\nOctree.CreationFuncForSubMeshes = (entry, block) => {\n const boundingInfo = entry.getBoundingInfo();\n if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {\n block.entries.push(entry);\n }\n};\n//# sourceMappingURL=octree.js.map","import { Scene } from \"../../scene.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { AbstractMesh } from \"../../Meshes/abstractMesh.js\";\nimport { Ray } from \"../../Culling/ray.js\";\nimport { SceneComponentConstants } from \"../../sceneComponent.js\";\nimport { Octree } from \"./octree.js\";\nimport { EngineStore } from \"../../Engines/engineStore.js\";\nScene.prototype.createOrUpdateSelectionOctree = function (maxCapacity = 64, maxDepth = 2) {\n let component = this._getComponent(SceneComponentConstants.NAME_OCTREE);\n if (!component) {\n component = new OctreeSceneComponent(this);\n this._addComponent(component);\n }\n if (!this._selectionOctree) {\n this._selectionOctree = new Octree(Octree.CreationFuncForMeshes, maxCapacity, maxDepth);\n }\n const worldExtends = this.getWorldExtends();\n // Update octree\n this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);\n return this._selectionOctree;\n};\nObject.defineProperty(Scene.prototype, \"selectionOctree\", {\n get: function () {\n return this._selectionOctree;\n },\n enumerable: true,\n configurable: true,\n});\n/**\n * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.\n * Please note that you must have a decent number of submeshes to get performance improvements when using an octree\n * @param maxCapacity defines the maximum size of each block (64 by default)\n * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)\n * @returns the new octree\n * @see https://www.babylonjs-playground.com/#NA4OQ#12\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimizeOctrees\n */\nAbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity = 64, maxDepth = 2) {\n const scene = this.getScene();\n let component = scene._getComponent(SceneComponentConstants.NAME_OCTREE);\n if (!component) {\n component = new OctreeSceneComponent(scene);\n scene._addComponent(component);\n }\n if (!this._submeshesOctree) {\n this._submeshesOctree = new Octree(Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);\n }\n this.computeWorldMatrix(true);\n const boundingInfo = this.getBoundingInfo();\n // Update octree\n const bbox = boundingInfo.boundingBox;\n this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);\n return this._submeshesOctree;\n};\n/**\n * Defines the octree scene component responsible to manage any octrees\n * in a given scene.\n */\nexport class OctreeSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name help to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_OCTREE;\n /**\n * Indicates if the meshes have been checked to make sure they are isEnabled()\n */\n this.checksIsEnabled = true;\n this._tempRay = new Ray(Vector3.Zero(), new Vector3(1, 1, 1));\n scene = scene || EngineStore.LastCreatedScene;\n if (!scene) {\n return;\n }\n this.scene = scene;\n this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);\n this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);\n this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);\n this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene.onMeshRemovedObservable.add((mesh) => {\n const sceneOctree = this.scene.selectionOctree;\n if (sceneOctree !== undefined && sceneOctree !== null) {\n const index = sceneOctree.dynamicContent.indexOf(mesh);\n if (index !== -1) {\n sceneOctree.dynamicContent.splice(index, 1);\n }\n }\n });\n this.scene.onMeshImportedObservable.add((mesh) => {\n const sceneOctree = this.scene.selectionOctree;\n if (sceneOctree !== undefined && sceneOctree !== null) {\n sceneOctree.addMesh(mesh);\n }\n });\n }\n /**\n * Return the list of active meshes\n * @returns the list of active meshes\n */\n getActiveMeshCandidates() {\n var _a;\n return ((_a = this.scene._selectionOctree) === null || _a === void 0 ? void 0 : _a.select(this.scene.frustumPlanes)) || this.scene._getDefaultMeshCandidates();\n }\n /**\n * Return the list of active sub meshes\n * @param mesh The mesh to get the candidates sub meshes from\n * @returns the list of active sub meshes\n */\n getActiveSubMeshCandidates(mesh) {\n if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {\n const intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);\n return intersections;\n }\n return this.scene._getDefaultSubMeshCandidates(mesh);\n }\n /**\n * Return the list of sub meshes intersecting with a given local ray\n * @param mesh defines the mesh to find the submesh for\n * @param localRay defines the ray in local space\n * @returns the list of intersecting sub meshes\n */\n getIntersectingSubMeshCandidates(mesh, localRay) {\n if (mesh._submeshesOctree && mesh.useOctreeForPicking) {\n Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);\n const intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);\n return intersections;\n }\n return this.scene._getDefaultSubMeshCandidates(mesh);\n }\n /**\n * Return the list of sub meshes colliding with a collider\n * @param mesh defines the mesh to find the submesh for\n * @param collider defines the collider to evaluate the collision against\n * @returns the list of colliding sub meshes\n */\n getCollidingSubMeshCandidates(mesh, collider) {\n if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {\n const radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);\n const intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);\n return intersections;\n }\n return this.scene._getDefaultSubMeshCandidates(mesh);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n // Nothing to do here.\n }\n /**\n * Disposes the component and the associated resources.\n */\n dispose() {\n // Nothing to do here.\n }\n}\n//# sourceMappingURL=octreeSceneComponent.js.map","export * from \"./octree.js\";\nexport * from \"./octreeBlock.js\";\nexport * from \"./octreeSceneComponent.js\";\n//# sourceMappingURL=index.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./boundingBox.js\";\nexport * from \"./boundingInfo.js\";\nexport * from \"./boundingSphere.js\";\nexport * from \"./Octrees/index.js\";\nexport * from \"./ray.js\";\n//# sourceMappingURL=index.js.map","import { Scene } from \"../scene.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { PointerInfo, PointerEventTypes } from \"../Events/pointerEvents.js\";\nimport { PickingInfo } from \"../Collisions/pickingInfo.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { HemisphericLight } from \"../Lights/hemisphericLight.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\n/**\n * Renders a layer on top of an existing scene\n */\nexport class UtilityLayerRenderer {\n /**\n * Gets the camera that is used to render the utility layer (when not set, this will be the last active camera)\n * @param getRigParentIfPossible if the current active camera is a rig camera, should its parent camera be returned\n * @returns the camera that is used when rendering the utility layer\n */\n getRenderCamera(getRigParentIfPossible) {\n if (this._renderCamera) {\n return this._renderCamera;\n }\n else {\n let activeCam;\n if (this.originalScene.activeCameras && this.originalScene.activeCameras.length > 1) {\n activeCam = this.originalScene.activeCameras[this.originalScene.activeCameras.length - 1];\n }\n else {\n activeCam = this.originalScene.activeCamera;\n }\n if (getRigParentIfPossible && activeCam && activeCam.isRigCamera) {\n return activeCam.rigParent;\n }\n return activeCam;\n }\n }\n /**\n * Sets the camera that should be used when rendering the utility layer (If set to null the last active camera will be used)\n * @param cam the camera that should be used when rendering the utility layer\n */\n setRenderCamera(cam) {\n this._renderCamera = cam;\n }\n /**\n * @internal\n * Light which used by gizmos to get light shading\n */\n _getSharedGizmoLight() {\n if (!this._sharedGizmoLight) {\n this._sharedGizmoLight = new HemisphericLight(\"shared gizmo light\", new Vector3(0, 1, 0), this.utilityLayerScene);\n this._sharedGizmoLight.intensity = 2;\n this._sharedGizmoLight.groundColor = Color3.Gray();\n }\n return this._sharedGizmoLight;\n }\n /**\n * A shared utility layer that can be used to overlay objects into a scene (Depth map of the previous scene is cleared before drawing on top of it)\n */\n static get DefaultUtilityLayer() {\n if (UtilityLayerRenderer._DefaultUtilityLayer == null) {\n return UtilityLayerRenderer._CreateDefaultUtilityLayerFromScene(EngineStore.LastCreatedScene);\n }\n return UtilityLayerRenderer._DefaultUtilityLayer;\n }\n /**\n * Creates an utility layer, and set it as a default utility layer\n * @param scene associated scene\n * @internal\n */\n static _CreateDefaultUtilityLayerFromScene(scene) {\n UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(scene);\n UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(() => {\n UtilityLayerRenderer._DefaultUtilityLayer = null;\n });\n return UtilityLayerRenderer._DefaultUtilityLayer;\n }\n /**\n * A shared utility layer that can be used to embed objects into a scene (Depth map of the previous scene is not cleared before drawing on top of it)\n */\n static get DefaultKeepDepthUtilityLayer() {\n if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {\n UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(EngineStore.LastCreatedScene);\n UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;\n UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(() => {\n UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;\n });\n }\n return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;\n }\n /**\n * Instantiates a UtilityLayerRenderer\n * @param originalScene the original scene that will be rendered on top of\n * @param handleEvents boolean indicating if the utility layer should handle events\n */\n constructor(\n /** the original scene that will be rendered on top of */\n originalScene, handleEvents = true) {\n this.originalScene = originalScene;\n this._pointerCaptures = {};\n this._lastPointerEvents = {};\n this._sharedGizmoLight = null;\n this._renderCamera = null;\n /**\n * If the picking should be done on the utility layer prior to the actual scene (Default: true)\n */\n this.pickUtilitySceneFirst = true;\n /**\n * If the utility layer should automatically be rendered on top of existing scene\n */\n this.shouldRender = true;\n /**\n * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene\n */\n this.onlyCheckPointerDownEvents = true;\n /**\n * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)\n */\n this.processAllEvents = false;\n /**\n * Set to false to disable picking\n */\n this.pickingEnabled = true;\n /**\n * Observable raised when the pointer moves from the utility layer scene to the main scene\n */\n this.onPointerOutObservable = new Observable();\n // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app\n this.utilityLayerScene = new Scene(originalScene.getEngine(), { virtual: true });\n this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;\n this.utilityLayerScene._allowPostProcessClearColor = false;\n // Deactivate post processes\n this.utilityLayerScene.postProcessesEnabled = false;\n // Detach controls on utility scene, events will be fired by logic below to handle picking priority\n this.utilityLayerScene.detachControl();\n if (handleEvents) {\n this._originalPointerObserver = originalScene.onPrePointerObservable.add((prePointerInfo) => {\n if (!this.utilityLayerScene.activeCamera) {\n return;\n }\n if (!this.pickingEnabled) {\n return;\n }\n if (!this.processAllEvents) {\n if (prePointerInfo.type !== PointerEventTypes.POINTERMOVE &&\n prePointerInfo.type !== PointerEventTypes.POINTERUP &&\n prePointerInfo.type !== PointerEventTypes.POINTERDOWN &&\n prePointerInfo.type !== PointerEventTypes.POINTERDOUBLETAP) {\n return;\n }\n }\n this.utilityLayerScene.pointerX = originalScene.pointerX;\n this.utilityLayerScene.pointerY = originalScene.pointerY;\n const pointerEvent = prePointerInfo.event;\n if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {\n this._pointerCaptures[pointerEvent.pointerId] = false;\n return;\n }\n const getNearPickDataForScene = (scene) => {\n let scenePick = null;\n if (prePointerInfo.nearInteractionPickingInfo) {\n if (prePointerInfo.nearInteractionPickingInfo.pickedMesh.getScene() == scene) {\n scenePick = prePointerInfo.nearInteractionPickingInfo;\n }\n else {\n scenePick = new PickingInfo();\n }\n }\n else if (scene !== this.utilityLayerScene && prePointerInfo.originalPickingInfo) {\n scenePick = prePointerInfo.originalPickingInfo;\n }\n else {\n let previousActiveCamera = null;\n // If a camera is set for rendering with this layer\n // it will also be used for the ray computation\n // To preserve back compat and because scene.pick always use activeCamera\n // it's substituted temporarily and a new scenePick is forced.\n // otherwise, the ray with previously active camera is always used.\n // It's set back to previous activeCamera after operation.\n if (this._renderCamera) {\n previousActiveCamera = scene._activeCamera;\n scene._activeCamera = this._renderCamera;\n prePointerInfo.ray = null;\n }\n scenePick = prePointerInfo.ray ? scene.pickWithRay(prePointerInfo.ray) : scene.pick(originalScene.pointerX, originalScene.pointerY);\n if (previousActiveCamera) {\n scene._activeCamera = previousActiveCamera;\n }\n }\n return scenePick;\n };\n const utilityScenePick = getNearPickDataForScene(this.utilityLayerScene);\n if (!prePointerInfo.ray && utilityScenePick) {\n prePointerInfo.ray = utilityScenePick.ray;\n }\n // always fire the prepointer observable\n this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);\n // allow every non pointer down event to flow to the utility layer\n if (this.onlyCheckPointerDownEvents && prePointerInfo.type != PointerEventTypes.POINTERDOWN) {\n if (!prePointerInfo.skipOnPointerObservable) {\n this.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick), prePointerInfo.type);\n }\n if (prePointerInfo.type === PointerEventTypes.POINTERUP && this._pointerCaptures[pointerEvent.pointerId]) {\n this._pointerCaptures[pointerEvent.pointerId] = false;\n }\n return;\n }\n if (this.utilityLayerScene.autoClearDepthAndStencil || this.pickUtilitySceneFirst) {\n // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene\n if (utilityScenePick && utilityScenePick.hit) {\n if (!prePointerInfo.skipOnPointerObservable) {\n this.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick), prePointerInfo.type);\n }\n prePointerInfo.skipOnPointerObservable = true;\n }\n }\n else {\n const originalScenePick = getNearPickDataForScene(originalScene);\n const pointerEvent = prePointerInfo.event;\n // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray\n if (originalScenePick && utilityScenePick) {\n // No pick in utility scene\n if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {\n if (this.mainSceneTrackerPredicate && this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {\n // We touched an utility mesh present in the main scene\n this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent);\n prePointerInfo.skipOnPointerObservable = true;\n }\n else if (prePointerInfo.type === PointerEventTypes.POINTERDOWN) {\n this._pointerCaptures[pointerEvent.pointerId] = true;\n }\n else if (prePointerInfo.type === PointerEventTypes.POINTERMOVE || prePointerInfo.type === PointerEventTypes.POINTERUP) {\n if (this._lastPointerEvents[pointerEvent.pointerId]) {\n // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete\n this.onPointerOutObservable.notifyObservers(pointerEvent.pointerId);\n delete this._lastPointerEvents[pointerEvent.pointerId];\n }\n this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent);\n }\n }\n else if (!this._pointerCaptures[pointerEvent.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {\n // We pick something in utility scene or the pick in utility is closer than the one in main scene\n this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent);\n // If a previous utility layer set this, do not unset this\n if (!prePointerInfo.skipOnPointerObservable) {\n prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;\n }\n }\n else if (!this._pointerCaptures[pointerEvent.pointerId] && utilityScenePick.distance >= originalScenePick.distance) {\n // We have a pick in both scenes but main is closer than utility\n // We touched an utility mesh present in the main scene\n if (this.mainSceneTrackerPredicate && this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {\n this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent);\n prePointerInfo.skipOnPointerObservable = true;\n }\n else {\n if (prePointerInfo.type === PointerEventTypes.POINTERMOVE || prePointerInfo.type === PointerEventTypes.POINTERUP) {\n if (this._lastPointerEvents[pointerEvent.pointerId]) {\n // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete\n this.onPointerOutObservable.notifyObservers(pointerEvent.pointerId);\n delete this._lastPointerEvents[pointerEvent.pointerId];\n }\n }\n this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent);\n }\n }\n if (prePointerInfo.type === PointerEventTypes.POINTERUP && this._pointerCaptures[pointerEvent.pointerId]) {\n this._pointerCaptures[pointerEvent.pointerId] = false;\n }\n }\n }\n });\n // As a newly added utility layer will be rendered over the screen last, it's pointer events should be processed first\n if (this._originalPointerObserver) {\n originalScene.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver);\n }\n }\n // Render directly on top of existing scene without clearing\n this.utilityLayerScene.autoClear = false;\n this._afterRenderObserver = this.originalScene.onAfterRenderCameraObservable.add((camera) => {\n // Only render when the render camera finishes rendering\n if (this.shouldRender && camera == this.getRenderCamera()) {\n this.render();\n }\n });\n this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(() => {\n this.dispose();\n });\n this._updateCamera();\n }\n _notifyObservers(prePointerInfo, pickInfo, pointerEvent) {\n if (!prePointerInfo.skipOnPointerObservable) {\n this.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo), prePointerInfo.type);\n this._lastPointerEvents[pointerEvent.pointerId] = true;\n }\n }\n /**\n * Renders the utility layers scene on top of the original scene\n */\n render() {\n this._updateCamera();\n if (this.utilityLayerScene.activeCamera) {\n // Set the camera's scene to utility layers scene\n const oldScene = this.utilityLayerScene.activeCamera.getScene();\n const camera = this.utilityLayerScene.activeCamera;\n camera._scene = this.utilityLayerScene;\n if (camera.leftCamera) {\n camera.leftCamera._scene = this.utilityLayerScene;\n }\n if (camera.rightCamera) {\n camera.rightCamera._scene = this.utilityLayerScene;\n }\n this.utilityLayerScene.render(false);\n // Reset camera's scene back to original\n camera._scene = oldScene;\n if (camera.leftCamera) {\n camera.leftCamera._scene = oldScene;\n }\n if (camera.rightCamera) {\n camera.rightCamera._scene = oldScene;\n }\n }\n }\n /**\n * Disposes of the renderer\n */\n dispose() {\n this.onPointerOutObservable.clear();\n if (this._afterRenderObserver) {\n this.originalScene.onAfterCameraRenderObservable.remove(this._afterRenderObserver);\n }\n if (this._sceneDisposeObserver) {\n this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);\n }\n if (this._originalPointerObserver) {\n this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);\n }\n this.utilityLayerScene.dispose();\n }\n _updateCamera() {\n this.utilityLayerScene.cameraToUseForPointers = this.getRenderCamera();\n this.utilityLayerScene.activeCamera = this.getRenderCamera();\n }\n}\n/** @internal */\nUtilityLayerRenderer._DefaultUtilityLayer = null;\n/** @internal */\nUtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;\n//# sourceMappingURL=utilityLayerRenderer.js.map","import { Quaternion, Vector3, Matrix, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { Camera } from \"../Cameras/camera.js\";\nimport { UtilityLayerRenderer } from \"../Rendering/utilityLayerRenderer.js\";\nimport { PointerEventTypes } from \"../Events/pointerEvents.js\";\nimport { Light } from \"../Lights/light.js\";\n/**\n * Anchor options where the Gizmo can be positioned in relation to its anchored node\n */\nexport var GizmoAnchorPoint;\n(function (GizmoAnchorPoint) {\n /** The origin of the attached node */\n GizmoAnchorPoint[GizmoAnchorPoint[\"Origin\"] = 0] = \"Origin\";\n /** The pivot point of the attached node*/\n GizmoAnchorPoint[GizmoAnchorPoint[\"Pivot\"] = 1] = \"Pivot\";\n})(GizmoAnchorPoint || (GizmoAnchorPoint = {}));\n/**\n * Coordinates mode: Local or World. Defines how axis is aligned: either on world axis or transform local axis\n */\nexport var GizmoCoordinatesMode;\n(function (GizmoCoordinatesMode) {\n GizmoCoordinatesMode[GizmoCoordinatesMode[\"World\"] = 0] = \"World\";\n GizmoCoordinatesMode[GizmoCoordinatesMode[\"Local\"] = 1] = \"Local\";\n})(GizmoCoordinatesMode || (GizmoCoordinatesMode = {}));\n/**\n * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.\n */\nexport class Gizmo {\n /**\n * Ratio for the scale of the gizmo (Default: 1)\n */\n set scaleRatio(value) {\n this._scaleRatio = value;\n }\n get scaleRatio() {\n return this._scaleRatio;\n }\n /**\n * True when the mouse pointer is hovered a gizmo mesh\n */\n get isHovered() {\n return this._isHovered;\n }\n /**\n * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)\n * * When set, interactions will be enabled\n */\n get attachedMesh() {\n return this._attachedMesh;\n }\n set attachedMesh(value) {\n this._attachedMesh = value;\n if (value) {\n this._attachedNode = value;\n }\n this._rootMesh.setEnabled(value ? true : false);\n this._attachedNodeChanged(value);\n }\n /**\n * Node that the gizmo will be attached to. (eg. on a drag gizmo the mesh, bone or NodeTransform that will be dragged)\n * * When set, interactions will be enabled\n */\n get attachedNode() {\n return this._attachedNode;\n }\n set attachedNode(value) {\n this._attachedNode = value;\n this._attachedMesh = null;\n this._rootMesh.setEnabled(value ? true : false);\n this._attachedNodeChanged(value);\n }\n /**\n * Disposes and replaces the current meshes in the gizmo with the specified mesh\n * @param mesh The mesh to replace the default mesh of the gizmo\n */\n setCustomMesh(mesh) {\n if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {\n throw \"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)\";\n }\n this._rootMesh.getChildMeshes().forEach((c) => {\n c.dispose();\n });\n mesh.parent = this._rootMesh;\n this._customMeshSet = true;\n }\n /**\n * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)\n * NOTE: This is only possible for meshes with uniform scaling, as otherwise it's not possible to decompose the rotation\n */\n set updateGizmoRotationToMatchAttachedMesh(value) {\n this._updateGizmoRotationToMatchAttachedMesh = value;\n }\n get updateGizmoRotationToMatchAttachedMesh() {\n return this._updateGizmoRotationToMatchAttachedMesh;\n }\n /**\n * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)\n */\n set updateGizmoPositionToMatchAttachedMesh(value) {\n this._updateGizmoPositionToMatchAttachedMesh = value;\n }\n get updateGizmoPositionToMatchAttachedMesh() {\n return this._updateGizmoPositionToMatchAttachedMesh;\n }\n /**\n * Defines where the gizmo will be positioned if `updateGizmoPositionToMatchAttachedMesh` is enabled.\n * (Default: GizmoAnchorPoint.Origin)\n */\n set anchorPoint(value) {\n this._anchorPoint = value;\n }\n get anchorPoint() {\n return this._anchorPoint;\n }\n /**\n * Set the coordinate system to use. By default it's local.\n * But it's possible for a user to tweak so its local for translation and world for rotation.\n * In that case, setting the coordinate system will change `updateGizmoRotationToMatchAttachedMesh` and `updateGizmoPositionToMatchAttachedMesh`\n */\n set coordinatesMode(coordinatesMode) {\n this._coordinatesMode = coordinatesMode;\n const local = coordinatesMode == GizmoCoordinatesMode.Local;\n this.updateGizmoRotationToMatchAttachedMesh = local;\n this.updateGizmoPositionToMatchAttachedMesh = local;\n }\n get coordinatesMode() {\n return this._coordinatesMode;\n }\n /**\n * When set, the gizmo will always appear the same size no matter where the camera is (default: true)\n */\n set updateScale(value) {\n this._updateScale = value;\n }\n get updateScale() {\n return this._updateScale;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _attachedNodeChanged(value) { }\n /**\n * Creates a gizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n */\n constructor(\n /** The utility layer the gizmo will be added to */\n gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer) {\n this.gizmoLayer = gizmoLayer;\n this._attachedMesh = null;\n this._attachedNode = null;\n this._customRotationQuaternion = null;\n /**\n * Ratio for the scale of the gizmo (Default: 1)\n */\n this._scaleRatio = 1;\n /**\n * boolean updated by pointermove when a gizmo mesh is hovered\n */\n this._isHovered = false;\n /**\n * If a custom mesh has been set (Default: false)\n */\n this._customMeshSet = false;\n this._updateGizmoRotationToMatchAttachedMesh = true;\n this._updateGizmoPositionToMatchAttachedMesh = true;\n this._anchorPoint = GizmoAnchorPoint.Origin;\n this._updateScale = true;\n this._coordinatesMode = GizmoCoordinatesMode.Local;\n this._interactionsEnabled = true;\n this._rightHandtoLeftHandMatrix = Matrix.RotationY(Math.PI);\n this._rootMesh = new Mesh(\"gizmoRootNode\", gizmoLayer.utilityLayerScene);\n this._rootMesh.rotationQuaternion = Quaternion.Identity();\n this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(() => {\n this._update();\n });\n }\n /**\n * posture that the gizmo will be display\n * When set null, default value will be used (Quaternion(0, 0, 0, 1))\n */\n get customRotationQuaternion() {\n return this._customRotationQuaternion;\n }\n set customRotationQuaternion(customRotationQuaternion) {\n this._customRotationQuaternion = customRotationQuaternion;\n }\n /**\n * Updates the gizmo to match the attached mesh's position/rotation\n */\n _update() {\n if (this.attachedNode) {\n let effectiveNode = this.attachedNode;\n if (this.attachedMesh) {\n effectiveNode = this.attachedMesh || this.attachedNode;\n }\n // Position\n if (this.updateGizmoPositionToMatchAttachedMesh) {\n if (this.anchorPoint == GizmoAnchorPoint.Pivot && effectiveNode.getAbsolutePivotPoint) {\n const position = effectiveNode.getAbsolutePivotPoint();\n this._rootMesh.position.copyFrom(position);\n }\n else {\n const row = effectiveNode.getWorldMatrix().getRow(3);\n const position = row ? row.toVector3() : new Vector3(0, 0, 0);\n this._rootMesh.position.copyFrom(position);\n }\n }\n // Rotation\n if (this.updateGizmoRotationToMatchAttachedMesh) {\n const supportedNode = effectiveNode._isMesh ||\n effectiveNode.getClassName() === \"AbstractMesh\" ||\n effectiveNode.getClassName() === \"TransformNode\" ||\n effectiveNode.getClassName() === \"InstancedMesh\";\n const transformNode = supportedNode ? effectiveNode : undefined;\n effectiveNode.getWorldMatrix().decompose(undefined, this._rootMesh.rotationQuaternion, undefined, Gizmo.PreserveScaling ? transformNode : undefined);\n }\n else {\n if (this._customRotationQuaternion) {\n this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion);\n }\n else {\n this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);\n }\n }\n // Scale\n if (this.updateScale) {\n const activeCamera = this.gizmoLayer.utilityLayerScene.activeCamera;\n let cameraPosition = activeCamera.globalPosition;\n if (activeCamera.devicePosition) {\n cameraPosition = activeCamera.devicePosition;\n }\n this._rootMesh.position.subtractToRef(cameraPosition, TmpVectors.Vector3[0]);\n let scale = this.scaleRatio;\n if (activeCamera.mode == Camera.ORTHOGRAPHIC_CAMERA) {\n if (activeCamera.orthoTop && activeCamera.orthoBottom) {\n const orthoHeight = activeCamera.orthoTop - activeCamera.orthoBottom;\n scale *= orthoHeight;\n }\n }\n else {\n const camForward = activeCamera.getScene().useRightHandedSystem ? Vector3.RightHandedForwardReadOnly : Vector3.LeftHandedForwardReadOnly;\n const direction = activeCamera.getDirection(camForward);\n scale *= Vector3.Dot(TmpVectors.Vector3[0], direction);\n }\n this._rootMesh.scaling.setAll(scale);\n // Account for handedness, similar to Matrix.decompose\n if (effectiveNode._getWorldMatrixDeterminant() < 0 && !Gizmo.PreserveScaling) {\n this._rootMesh.scaling.y *= -1;\n }\n }\n else {\n this._rootMesh.scaling.setAll(this.scaleRatio);\n }\n }\n }\n /**\n * Handle position/translation when using an attached node using pivot\n */\n _handlePivot() {\n const attachedNodeTransform = this._attachedNode;\n // check there is an active pivot for the TransformNode attached\n if (attachedNodeTransform.isUsingPivotMatrix && attachedNodeTransform.isUsingPivotMatrix() && attachedNodeTransform.position) {\n // When a TransformNode has an active pivot, even without parenting,\n // translation from the world matrix is different from TransformNode.position.\n // Pivot works like a virtual parent that's using the node orientation.\n // As the world matrix is transformed by the gizmo and then decomposed to TRS\n // its translation part must be set to the Node's position.\n attachedNodeTransform.getWorldMatrix().setTranslation(attachedNodeTransform.position);\n }\n }\n /**\n * computes the rotation/scaling/position of the transform once the Node world matrix has changed.\n */\n _matrixChanged() {\n if (!this._attachedNode) {\n return;\n }\n if (this._attachedNode._isCamera) {\n const camera = this._attachedNode;\n let worldMatrix;\n let worldMatrixUC;\n if (camera.parent) {\n const parentInv = TmpVectors.Matrix[1];\n camera.parent._worldMatrix.invertToRef(parentInv);\n this._attachedNode._worldMatrix.multiplyToRef(parentInv, TmpVectors.Matrix[0]);\n worldMatrix = TmpVectors.Matrix[0];\n }\n else {\n worldMatrix = this._attachedNode._worldMatrix;\n }\n if (camera.getScene().useRightHandedSystem) {\n // avoid desync with RH matrix computation. Otherwise, rotation of PI around Y axis happens each frame resulting in axis flipped because worldMatrix is computed as inverse of viewMatrix.\n this._rightHandtoLeftHandMatrix.multiplyToRef(worldMatrix, TmpVectors.Matrix[1]);\n worldMatrixUC = TmpVectors.Matrix[1];\n }\n else {\n worldMatrixUC = worldMatrix;\n }\n worldMatrixUC.decompose(TmpVectors.Vector3[1], TmpVectors.Quaternion[0], TmpVectors.Vector3[0]);\n const inheritsTargetCamera = this._attachedNode.getClassName() === \"FreeCamera\" ||\n this._attachedNode.getClassName() === \"FlyCamera\" ||\n this._attachedNode.getClassName() === \"ArcFollowCamera\" ||\n this._attachedNode.getClassName() === \"TargetCamera\" ||\n this._attachedNode.getClassName() === \"TouchCamera\" ||\n this._attachedNode.getClassName() === \"UniversalCamera\";\n if (inheritsTargetCamera) {\n const targetCamera = this._attachedNode;\n targetCamera.rotation = TmpVectors.Quaternion[0].toEulerAngles();\n if (targetCamera.rotationQuaternion) {\n targetCamera.rotationQuaternion.copyFrom(TmpVectors.Quaternion[0]);\n targetCamera.rotationQuaternion.normalize();\n }\n }\n camera.position.copyFrom(TmpVectors.Vector3[0]);\n }\n else if (this._attachedNode._isMesh ||\n this._attachedNode.getClassName() === \"AbstractMesh\" ||\n this._attachedNode.getClassName() === \"TransformNode\" ||\n this._attachedNode.getClassName() === \"InstancedMesh\") {\n const transform = this._attachedNode;\n if (transform.parent) {\n const parentInv = TmpVectors.Matrix[0];\n const localMat = TmpVectors.Matrix[1];\n transform.parent.getWorldMatrix().invertToRef(parentInv);\n this._attachedNode.getWorldMatrix().multiplyToRef(parentInv, localMat);\n localMat.decompose(TmpVectors.Vector3[0], TmpVectors.Quaternion[0], transform.position, Gizmo.PreserveScaling ? transform : undefined);\n }\n else {\n this._attachedNode._worldMatrix.decompose(TmpVectors.Vector3[0], TmpVectors.Quaternion[0], transform.position, Gizmo.PreserveScaling ? transform : undefined);\n }\n TmpVectors.Vector3[0].scaleInPlace(1.0 / transform.scalingDeterminant);\n transform.scaling.copyFrom(TmpVectors.Vector3[0]);\n if (!transform.billboardMode) {\n if (transform.rotationQuaternion) {\n transform.rotationQuaternion.copyFrom(TmpVectors.Quaternion[0]);\n transform.rotationQuaternion.normalize();\n }\n else {\n transform.rotation = TmpVectors.Quaternion[0].toEulerAngles();\n }\n }\n }\n else if (this._attachedNode.getClassName() === \"Bone\") {\n const bone = this._attachedNode;\n const parent = bone.getParent();\n if (parent) {\n const invParent = TmpVectors.Matrix[0];\n const boneLocalMatrix = TmpVectors.Matrix[1];\n parent.getFinalMatrix().invertToRef(invParent);\n bone.getFinalMatrix().multiplyToRef(invParent, boneLocalMatrix);\n const lmat = bone.getLocalMatrix();\n lmat.copyFrom(boneLocalMatrix);\n }\n else {\n const lmat = bone.getLocalMatrix();\n lmat.copyFrom(bone.getFinalMatrix());\n }\n bone.markAsDirty();\n }\n else {\n const light = this._attachedNode;\n if (light.getTypeID) {\n const type = light.getTypeID();\n if (type === Light.LIGHTTYPEID_DIRECTIONALLIGHT || type === Light.LIGHTTYPEID_SPOTLIGHT || type === Light.LIGHTTYPEID_POINTLIGHT) {\n const parent = light.parent;\n if (parent) {\n const invParent = TmpVectors.Matrix[0];\n const nodeLocalMatrix = TmpVectors.Matrix[1];\n parent.getWorldMatrix().invertToRef(invParent);\n light.getWorldMatrix().multiplyToRef(invParent, nodeLocalMatrix);\n nodeLocalMatrix.decompose(undefined, TmpVectors.Quaternion[0], TmpVectors.Vector3[0]);\n }\n else {\n this._attachedNode._worldMatrix.decompose(undefined, TmpVectors.Quaternion[0], TmpVectors.Vector3[0]);\n }\n // setter doesn't copy values. Need a new Vector3\n light.position = new Vector3(TmpVectors.Vector3[0].x, TmpVectors.Vector3[0].y, TmpVectors.Vector3[0].z);\n if (light.direction) {\n light.direction = new Vector3(light.direction.x, light.direction.y, light.direction.z);\n }\n }\n }\n }\n }\n /**\n * refresh gizmo mesh material\n * @param gizmoMeshes\n * @param material material to apply\n */\n _setGizmoMeshMaterial(gizmoMeshes, material) {\n if (gizmoMeshes) {\n gizmoMeshes.forEach((m) => {\n m.material = material;\n if (m.color) {\n m.color = material.diffuseColor;\n }\n });\n }\n }\n /**\n * Subscribes to pointer up, down, and hover events. Used for responsive gizmos.\n * @param gizmoLayer The utility layer the gizmo will be added to\n * @param gizmoAxisCache Gizmo axis definition used for reactive gizmo UI\n * @returns {Observer} pointerObserver\n */\n static GizmoAxisPointerObserver(gizmoLayer, gizmoAxisCache) {\n let dragging = false;\n const pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add((pointerInfo) => {\n var _a, _b;\n if (pointerInfo.pickInfo) {\n // On Hover Logic\n if (pointerInfo.type === PointerEventTypes.POINTERMOVE) {\n if (dragging) {\n return;\n }\n gizmoAxisCache.forEach((cache) => {\n var _a, _b;\n if (cache.colliderMeshes && cache.gizmoMeshes) {\n const isHovered = ((_a = cache.colliderMeshes) === null || _a === void 0 ? void 0 : _a.indexOf((_b = pointerInfo === null || pointerInfo === void 0 ? void 0 : pointerInfo.pickInfo) === null || _b === void 0 ? void 0 : _b.pickedMesh)) != -1;\n const material = cache.dragBehavior.enabled ? (isHovered || cache.active ? cache.hoverMaterial : cache.material) : cache.disableMaterial;\n cache.gizmoMeshes.forEach((m) => {\n m.material = material;\n if (m.color) {\n m.color = material.diffuseColor;\n }\n });\n }\n });\n }\n // On Mouse Down\n if (pointerInfo.type === PointerEventTypes.POINTERDOWN) {\n // If user Clicked Gizmo\n if (gizmoAxisCache.has((_a = pointerInfo.pickInfo.pickedMesh) === null || _a === void 0 ? void 0 : _a.parent)) {\n dragging = true;\n const statusMap = gizmoAxisCache.get((_b = pointerInfo.pickInfo.pickedMesh) === null || _b === void 0 ? void 0 : _b.parent);\n statusMap.active = true;\n gizmoAxisCache.forEach((cache) => {\n var _a, _b;\n const isHovered = ((_a = cache.colliderMeshes) === null || _a === void 0 ? void 0 : _a.indexOf((_b = pointerInfo === null || pointerInfo === void 0 ? void 0 : pointerInfo.pickInfo) === null || _b === void 0 ? void 0 : _b.pickedMesh)) != -1;\n const material = (isHovered || cache.active) && cache.dragBehavior.enabled ? cache.hoverMaterial : cache.disableMaterial;\n cache.gizmoMeshes.forEach((m) => {\n m.material = material;\n if (m.color) {\n m.color = material.diffuseColor;\n }\n });\n });\n }\n }\n // On Mouse Up\n if (pointerInfo.type === PointerEventTypes.POINTERUP) {\n gizmoAxisCache.forEach((cache) => {\n cache.active = false;\n dragging = false;\n cache.gizmoMeshes.forEach((m) => {\n m.material = cache.dragBehavior.enabled ? cache.material : cache.disableMaterial;\n if (m.color) {\n m.color = cache.material.diffuseColor;\n }\n });\n });\n }\n }\n });\n return pointerObserver;\n }\n /**\n * Disposes of the gizmo\n */\n dispose() {\n this._rootMesh.dispose();\n if (this._beforeRenderObserver) {\n this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);\n }\n }\n}\n/**\n * When enabled, any gizmo operation will perserve scaling sign. Default is off.\n * Only valid for TransformNode derived classes (Mesh, AbstractMesh, ...)\n */\nGizmo.PreserveScaling = false;\n//# sourceMappingURL=gizmo.js.map","import { Vector3 } from \"../Maths/math.vector.js\";\nimport { StandardMaterial } from \"../Materials/standardMaterial.js\";\nimport { AxisDragGizmo } from \"../Gizmos/axisDragGizmo.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n/**\n * The Axes viewer will show 3 axes in a specific point in space\n * @see https://doc.babylonjs.com/toolsAndResources/utilities/World_Axes\n */\nexport class AxesViewer {\n /** Gets the node hierarchy used to render x-axis */\n get xAxis() {\n return this._xAxis;\n }\n /** Gets the node hierarchy used to render y-axis */\n get yAxis() {\n return this._yAxis;\n }\n /** Gets the node hierarchy used to render z-axis */\n get zAxis() {\n return this._zAxis;\n }\n /**\n * Creates a new AxesViewer\n * @param scene defines the hosting scene\n * @param scaleLines defines a number used to scale line length (1 by default)\n * @param renderingGroupId defines a number used to set the renderingGroupId of the meshes (2 by default)\n * @param xAxis defines the node hierarchy used to render the x-axis\n * @param yAxis defines the node hierarchy used to render the y-axis\n * @param zAxis defines the node hierarchy used to render the z-axis\n * @param lineThickness The line thickness to use when creating the arrow. defaults to 1.\n */\n constructor(scene, scaleLines = 1, renderingGroupId = 2, xAxis, yAxis, zAxis, lineThickness = 1) {\n this._scaleLinesFactor = 4;\n this._instanced = false;\n /**\n * Gets the hosting scene\n */\n this.scene = null;\n /**\n * Gets or sets a number used to scale line length\n */\n this.scaleLines = 1;\n scene = scene || EngineStore.LastCreatedScene;\n if (!scene) {\n return;\n }\n this.scaleLines = scaleLines;\n if (!xAxis) {\n const redColoredMaterial = new StandardMaterial(\"\", scene);\n redColoredMaterial.disableLighting = true;\n redColoredMaterial.emissiveColor = Color3.Red().scale(0.5);\n xAxis = AxisDragGizmo._CreateArrow(scene, redColoredMaterial, lineThickness);\n }\n if (!yAxis) {\n const greenColoredMaterial = new StandardMaterial(\"\", scene);\n greenColoredMaterial.disableLighting = true;\n greenColoredMaterial.emissiveColor = Color3.Green().scale(0.5);\n yAxis = AxisDragGizmo._CreateArrow(scene, greenColoredMaterial, lineThickness);\n }\n if (!zAxis) {\n const blueColoredMaterial = new StandardMaterial(\"\", scene);\n blueColoredMaterial.disableLighting = true;\n blueColoredMaterial.emissiveColor = Color3.Blue().scale(0.5);\n zAxis = AxisDragGizmo._CreateArrow(scene, blueColoredMaterial, lineThickness);\n }\n this._xAxis = xAxis;\n this._xAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor);\n this._yAxis = yAxis;\n this._yAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor);\n this._zAxis = zAxis;\n this._zAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor);\n if (renderingGroupId != null) {\n AxesViewer._SetRenderingGroupId(this._xAxis, renderingGroupId);\n AxesViewer._SetRenderingGroupId(this._yAxis, renderingGroupId);\n AxesViewer._SetRenderingGroupId(this._zAxis, renderingGroupId);\n }\n this.scene = scene;\n this.update(new Vector3(), Vector3.Right(), Vector3.Up(), Vector3.Forward());\n }\n /**\n * Force the viewer to update\n * @param position defines the position of the viewer\n * @param xaxis defines the x axis of the viewer\n * @param yaxis defines the y axis of the viewer\n * @param zaxis defines the z axis of the viewer\n */\n update(position, xaxis, yaxis, zaxis) {\n this._xAxis.position.copyFrom(position);\n this._xAxis.setDirection(xaxis);\n this._xAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor);\n this._yAxis.position.copyFrom(position);\n this._yAxis.setDirection(yaxis);\n this._yAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor);\n this._zAxis.position.copyFrom(position);\n this._zAxis.setDirection(zaxis);\n this._zAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor);\n }\n /**\n * Creates an instance of this axes viewer.\n * @returns a new axes viewer with instanced meshes\n */\n createInstance() {\n const xAxis = AxisDragGizmo._CreateArrowInstance(this.scene, this._xAxis);\n const yAxis = AxisDragGizmo._CreateArrowInstance(this.scene, this._yAxis);\n const zAxis = AxisDragGizmo._CreateArrowInstance(this.scene, this._zAxis);\n const axesViewer = new AxesViewer(this.scene, this.scaleLines, null, xAxis, yAxis, zAxis);\n axesViewer._instanced = true;\n return axesViewer;\n }\n /** Releases resources */\n dispose() {\n if (this._xAxis) {\n this._xAxis.dispose(false, !this._instanced);\n }\n if (this._yAxis) {\n this._yAxis.dispose(false, !this._instanced);\n }\n if (this._zAxis) {\n this._zAxis.dispose(false, !this._instanced);\n }\n this.scene = null;\n }\n static _SetRenderingGroupId(node, id) {\n node.getChildMeshes().forEach((mesh) => {\n mesh.renderingGroupId = id;\n });\n }\n}\n//# sourceMappingURL=axesViewer.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { TransformNode } from \"../Meshes/transformNode.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { CreateCylinder } from \"../Meshes/Builders/cylinderBuilder.js\";\nimport { PointerDragBehavior } from \"../Behaviors/Meshes/pointerDragBehavior.js\";\nimport { Gizmo } from \"./gizmo.js\";\nimport { UtilityLayerRenderer } from \"../Rendering/utilityLayerRenderer.js\";\nimport { StandardMaterial } from \"../Materials/standardMaterial.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { TmpVectors } from \"../Maths/math.vector.js\";\n/**\n * Single axis drag gizmo\n */\nexport class AxisDragGizmo extends Gizmo {\n /** Default material used to render when gizmo is not disabled or hovered */\n get coloredMaterial() {\n return this._coloredMaterial;\n }\n /** Material used to render when gizmo is hovered with mouse*/\n get hoverMaterial() {\n return this._hoverMaterial;\n }\n /** Material used to render when gizmo is disabled. typically grey.*/\n get disableMaterial() {\n return this._disableMaterial;\n }\n /**\n * @internal\n */\n static _CreateArrow(scene, material, thickness = 1, isCollider = false) {\n const arrow = new TransformNode(\"arrow\", scene);\n const cylinder = CreateCylinder(\"cylinder\", { diameterTop: 0, height: 0.075, diameterBottom: 0.0375 * (1 + (thickness - 1) / 4), tessellation: 96 }, scene);\n const line = CreateCylinder(\"cylinder\", { diameterTop: 0.005 * thickness, height: 0.275, diameterBottom: 0.005 * thickness, tessellation: 96 }, scene);\n // Position arrow pointing in its drag axis\n cylinder.parent = arrow;\n cylinder.material = material;\n cylinder.rotation.x = Math.PI / 2;\n cylinder.position.z += 0.3;\n line.parent = arrow;\n line.material = material;\n line.position.z += 0.275 / 2;\n line.rotation.x = Math.PI / 2;\n if (isCollider) {\n line.visibility = 0;\n cylinder.visibility = 0;\n }\n return arrow;\n }\n /**\n * @internal\n */\n static _CreateArrowInstance(scene, arrow) {\n const instance = new TransformNode(\"arrow\", scene);\n for (const mesh of arrow.getChildMeshes()) {\n const childInstance = mesh.createInstance(mesh.name);\n childInstance.parent = instance;\n }\n return instance;\n }\n /**\n * Creates an AxisDragGizmo\n * @param dragAxis The axis which the gizmo will be able to drag on\n * @param color The color of the gizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n * @param parent\n * @param thickness display gizmo axis thickness\n */\n constructor(dragAxis, color = Color3.Gray(), gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer, parent = null, thickness = 1) {\n var _a;\n super(gizmoLayer);\n this._pointerObserver = null;\n /**\n * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)\n */\n this.snapDistance = 0;\n /**\n * Event that fires each time the gizmo snaps to a new location.\n * * snapDistance is the the change in distance\n */\n this.onSnapObservable = new Observable();\n this._isEnabled = true;\n this._parent = null;\n this._dragging = false;\n this._parent = parent;\n // Create Material\n this._coloredMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._coloredMaterial.diffuseColor = color;\n this._coloredMaterial.specularColor = color.subtract(new Color3(0.1, 0.1, 0.1));\n this._hoverMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._hoverMaterial.diffuseColor = Color3.Yellow();\n this._disableMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._disableMaterial.diffuseColor = Color3.Gray();\n this._disableMaterial.alpha = 0.4;\n // Build Mesh + Collider\n const arrow = AxisDragGizmo._CreateArrow(gizmoLayer.utilityLayerScene, this._coloredMaterial, thickness);\n const collider = AxisDragGizmo._CreateArrow(gizmoLayer.utilityLayerScene, this._coloredMaterial, thickness + 4, true);\n // Add to Root Node\n this._gizmoMesh = new Mesh(\"\", gizmoLayer.utilityLayerScene);\n this._gizmoMesh.addChild(arrow);\n this._gizmoMesh.addChild(collider);\n this._gizmoMesh.lookAt(this._rootMesh.position.add(dragAxis));\n this._gizmoMesh.scaling.scaleInPlace(1 / 3);\n this._gizmoMesh.parent = this._rootMesh;\n let currentSnapDragDistance = 0;\n const tmpSnapEvent = { snapDistance: 0 };\n // Add drag behavior to handle events when the gizmo is dragged\n this.dragBehavior = new PointerDragBehavior({ dragAxis: dragAxis });\n this.dragBehavior.moveAttached = false;\n this.dragBehavior.updateDragPlane = false;\n this._rootMesh.addBehavior(this.dragBehavior);\n this.dragBehavior.onDragObservable.add((event) => {\n if (this.attachedNode) {\n this._handlePivot();\n // Keep world translation and use it to update world transform\n // if the node has parent, the local transform properties (position, rotation, scale)\n // will be recomputed in _matrixChanged function\n let matrixChanged = false;\n // Snapping logic\n if (this.snapDistance == 0) {\n this.attachedNode.getWorldMatrix().getTranslationToRef(TmpVectors.Vector3[2]);\n TmpVectors.Vector3[2].addInPlace(event.delta);\n if (this.dragBehavior.validateDrag(TmpVectors.Vector3[2])) {\n if (this.attachedNode.position) {\n // Required for nodes like lights\n this.attachedNode.position.addInPlaceFromFloats(event.delta.x, event.delta.y, event.delta.z);\n }\n // use _worldMatrix to not force a matrix update when calling GetWorldMatrix especially with Cameras\n this.attachedNode.getWorldMatrix().addTranslationFromFloats(event.delta.x, event.delta.y, event.delta.z);\n this.attachedNode.updateCache();\n matrixChanged = true;\n }\n }\n else {\n currentSnapDragDistance += event.dragDistance;\n if (Math.abs(currentSnapDragDistance) > this.snapDistance) {\n const dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / this.snapDistance);\n currentSnapDragDistance = currentSnapDragDistance % this.snapDistance;\n event.delta.normalizeToRef(TmpVectors.Vector3[1]);\n TmpVectors.Vector3[1].scaleInPlace(this.snapDistance * dragSteps);\n this.attachedNode.getWorldMatrix().getTranslationToRef(TmpVectors.Vector3[2]);\n TmpVectors.Vector3[2].addInPlace(TmpVectors.Vector3[1]);\n if (this.dragBehavior.validateDrag(TmpVectors.Vector3[2])) {\n this.attachedNode.getWorldMatrix().addTranslationFromFloats(TmpVectors.Vector3[1].x, TmpVectors.Vector3[1].y, TmpVectors.Vector3[1].z);\n this.attachedNode.updateCache();\n tmpSnapEvent.snapDistance = this.snapDistance * dragSteps;\n this.onSnapObservable.notifyObservers(tmpSnapEvent);\n matrixChanged = true;\n }\n }\n }\n if (matrixChanged) {\n this._matrixChanged();\n }\n }\n });\n this.dragBehavior.onDragStartObservable.add(() => {\n this._dragging = true;\n });\n this.dragBehavior.onDragEndObservable.add(() => {\n this._dragging = false;\n });\n const light = gizmoLayer._getSharedGizmoLight();\n light.includedOnlyMeshes = light.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(false));\n const cache = {\n gizmoMeshes: arrow.getChildMeshes(),\n colliderMeshes: collider.getChildMeshes(),\n material: this._coloredMaterial,\n hoverMaterial: this._hoverMaterial,\n disableMaterial: this._disableMaterial,\n active: false,\n dragBehavior: this.dragBehavior,\n };\n (_a = this._parent) === null || _a === void 0 ? void 0 : _a.addToAxisCache(collider, cache);\n this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add((pointerInfo) => {\n var _a;\n if (this._customMeshSet) {\n return;\n }\n this._isHovered = !!(cache.colliderMeshes.indexOf((_a = pointerInfo === null || pointerInfo === void 0 ? void 0 : pointerInfo.pickInfo) === null || _a === void 0 ? void 0 : _a.pickedMesh) != -1);\n if (!this._parent) {\n const material = this.dragBehavior.enabled ? (this._isHovered || this._dragging ? this._hoverMaterial : this._coloredMaterial) : this._disableMaterial;\n this._setGizmoMeshMaterial(cache.gizmoMeshes, material);\n }\n });\n this.dragBehavior.onEnabledObservable.add((newState) => {\n this._setGizmoMeshMaterial(cache.gizmoMeshes, newState ? cache.material : cache.disableMaterial);\n });\n }\n _attachedNodeChanged(value) {\n if (this.dragBehavior) {\n this.dragBehavior.enabled = value ? true : false;\n }\n }\n /**\n * If the gizmo is enabled\n */\n set isEnabled(value) {\n this._isEnabled = value;\n if (!value) {\n this.attachedMesh = null;\n this.attachedNode = null;\n }\n else {\n if (this._parent) {\n this.attachedMesh = this._parent.attachedMesh;\n this.attachedNode = this._parent.attachedNode;\n }\n }\n }\n get isEnabled() {\n return this._isEnabled;\n }\n /**\n * Disposes of the gizmo\n */\n dispose() {\n this.onSnapObservable.clear();\n this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);\n this.dragBehavior.detach();\n if (this._gizmoMesh) {\n this._gizmoMesh.dispose();\n }\n [this._coloredMaterial, this._hoverMaterial, this._disableMaterial].forEach((matl) => {\n if (matl) {\n matl.dispose();\n }\n });\n super.dispose();\n }\n}\n//# sourceMappingURL=axisDragGizmo.js.map","import { AxesViewer } from \"../Debug/axesViewer.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Axis } from \"../Maths/math.axis.js\";\n/**\n * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh\n * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8\n */\nexport class BoneAxesViewer extends AxesViewer {\n /**\n * Creates a new BoneAxesViewer\n * @param scene defines the hosting scene\n * @param bone defines the target bone\n * @param mesh defines the target mesh\n * @param scaleLines defines a scaling factor for line length (1 by default)\n */\n constructor(scene, bone, mesh, scaleLines = 1) {\n super(scene, scaleLines);\n /** Gets current position */\n this.pos = Vector3.Zero();\n /** Gets direction of X axis */\n this.xaxis = Vector3.Zero();\n /** Gets direction of Y axis */\n this.yaxis = Vector3.Zero();\n /** Gets direction of Z axis */\n this.zaxis = Vector3.Zero();\n this.mesh = mesh;\n this.bone = bone;\n }\n /**\n * Force the viewer to update\n */\n update() {\n if (!this.mesh || !this.bone) {\n return;\n }\n const bone = this.bone;\n bone.getAbsolutePositionToRef(this.mesh, this.pos);\n bone.getDirectionToRef(Axis.X, this.mesh, this.xaxis);\n bone.getDirectionToRef(Axis.Y, this.mesh, this.yaxis);\n bone.getDirectionToRef(Axis.Z, this.mesh, this.zaxis);\n super.update(this.pos, this.xaxis, this.yaxis, this.zaxis);\n }\n /** Releases resources */\n dispose() {\n if (this.mesh) {\n this.mesh = null;\n this.bone = null;\n super.dispose();\n }\n }\n}\n//# sourceMappingURL=boneAxesViewer.js.map","import { Tools } from \"../Misc/tools.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Scene } from \"../scene.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nObject.defineProperty(Scene.prototype, \"debugLayer\", {\n get: function () {\n if (!this._debugLayer) {\n this._debugLayer = new DebugLayer(this);\n }\n return this._debugLayer;\n },\n enumerable: true,\n configurable: true,\n});\n/**\n * Enum of inspector action tab\n */\nexport var DebugLayerTab;\n(function (DebugLayerTab) {\n /**\n * Properties tag (default)\n */\n DebugLayerTab[DebugLayerTab[\"Properties\"] = 0] = \"Properties\";\n /**\n * Debug tab\n */\n DebugLayerTab[DebugLayerTab[\"Debug\"] = 1] = \"Debug\";\n /**\n * Statistics tab\n */\n DebugLayerTab[DebugLayerTab[\"Statistics\"] = 2] = \"Statistics\";\n /**\n * Tools tab\n */\n DebugLayerTab[DebugLayerTab[\"Tools\"] = 3] = \"Tools\";\n /**\n * Settings tab\n */\n DebugLayerTab[DebugLayerTab[\"Settings\"] = 4] = \"Settings\";\n})(DebugLayerTab || (DebugLayerTab = {}));\n/**\n * The debug layer (aka Inspector) is the go to tool in order to better understand\n * what is happening in your scene\n * @see https://doc.babylonjs.com/toolsAndResources/inspector\n */\nexport class DebugLayer {\n /**\n * Observable triggered when a property is changed through the inspector.\n */\n get onPropertyChangedObservable() {\n if (this.BJSINSPECTOR && this.BJSINSPECTOR.Inspector) {\n return this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable;\n }\n if (!this._onPropertyChangedObservable) {\n this._onPropertyChangedObservable = new Observable();\n }\n return this._onPropertyChangedObservable;\n }\n /**\n * Observable triggered when the selection is changed through the inspector.\n */\n get onSelectionChangedObservable() {\n if (this.BJSINSPECTOR && this.BJSINSPECTOR.Inspector) {\n return this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable;\n }\n if (!this._onSelectionChangedObservable) {\n this._onSelectionChangedObservable = new Observable();\n }\n return this._onSelectionChangedObservable;\n }\n /**\n * Instantiates a new debug layer.\n * The debug layer (aka Inspector) is the go to tool in order to better understand\n * what is happening in your scene\n * @see https://doc.babylonjs.com/toolsAndResources/inspector\n * @param scene Defines the scene to inspect\n */\n constructor(scene) {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n this.BJSINSPECTOR = this._getGlobalInspector();\n this._scene = scene || EngineStore.LastCreatedScene;\n if (!this._scene) {\n return;\n }\n this._scene.onDisposeObservable.add(() => {\n // Debug layer\n if (this._scene._debugLayer) {\n this._scene._debugLayer.hide();\n }\n });\n }\n /**\n * Creates the inspector window.\n * @param config\n */\n _createInspector(config) {\n if (this.isVisible()) {\n return;\n }\n if (this._onPropertyChangedObservable) {\n for (const observer of this._onPropertyChangedObservable.observers) {\n this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(observer);\n }\n this._onPropertyChangedObservable.clear();\n this._onPropertyChangedObservable = undefined;\n }\n if (this._onSelectionChangedObservable) {\n for (const observer of this._onSelectionChangedObservable.observers) {\n this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(observer);\n }\n this._onSelectionChangedObservable.clear();\n this._onSelectionChangedObservable = undefined;\n }\n const userOptions = Object.assign({ overlay: false, showExplorer: true, showInspector: true, embedMode: false, handleResize: true, enablePopup: true }, config);\n this.BJSINSPECTOR = this.BJSINSPECTOR || this._getGlobalInspector();\n this.BJSINSPECTOR.Inspector.Show(this._scene, userOptions);\n }\n /**\n * Select a specific entity in the scene explorer and highlight a specific block in that entity property grid\n * @param entity defines the entity to select\n * @param lineContainerTitles defines the specific blocks to highlight (could be a string or an array of strings)\n */\n select(entity, lineContainerTitles) {\n if (this.BJSINSPECTOR) {\n if (lineContainerTitles) {\n if (Object.prototype.toString.call(lineContainerTitles) == \"[object String]\") {\n this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(lineContainerTitles);\n }\n else {\n this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(lineContainerTitles);\n }\n }\n this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(entity);\n }\n }\n /** Get the inspector from bundle or global */\n _getGlobalInspector() {\n // UMD Global name detection from Webpack Bundle UMD Name.\n if (typeof INSPECTOR !== \"undefined\") {\n return INSPECTOR;\n }\n // In case of module let s check the global emitted from the Inspector entry point.\n if (typeof BABYLON !== \"undefined\" && typeof BABYLON.Inspector !== \"undefined\") {\n return BABYLON;\n }\n return undefined;\n }\n /**\n * Get if the inspector is visible or not.\n * @returns true if visible otherwise, false\n */\n isVisible() {\n return this.BJSINSPECTOR && this.BJSINSPECTOR.Inspector.IsVisible;\n }\n /**\n * Hide the inspector and close its window.\n */\n hide() {\n if (this.BJSINSPECTOR) {\n this.BJSINSPECTOR.Inspector.Hide();\n }\n }\n /**\n * Update the scene in the inspector\n */\n setAsActiveScene() {\n if (this.BJSINSPECTOR) {\n this.BJSINSPECTOR.Inspector._SetNewScene(this._scene);\n }\n }\n /**\n * Launch the debugLayer.\n * @param config Define the configuration of the inspector\n * @returns a promise fulfilled when the debug layer is visible\n */\n show(config) {\n return new Promise((resolve) => {\n if (typeof this.BJSINSPECTOR == \"undefined\") {\n const inspectorUrl = config && config.inspectorURL ? config.inspectorURL : DebugLayer.InspectorURL;\n // Load inspector and add it to the DOM\n Tools.LoadScript(inspectorUrl, () => {\n this._createInspector(config);\n resolve(this);\n });\n }\n else {\n // Otherwise creates the inspector\n this._createInspector(config);\n resolve(this);\n }\n });\n }\n}\n/**\n * Define the url to get the inspector script from.\n * By default it uses the babylonjs CDN.\n * @ignoreNaming\n */\nDebugLayer.InspectorURL = `https://unpkg.com/babylonjs-inspector@${Engine.Version}/babylon.inspector.bundle.js`;\n//# sourceMappingURL=debugLayer.js.map","import { Vector4 } from \"../../Maths/math.vector.js\";\nimport { Color4 } from \"../../Maths/math.color.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n/**\n * Creates the VertexData for a box\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * size sets the width, height and depth of the box to the value of size, optional default 1\n * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size\n * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size\n * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size\n * * faceUV an array of 6 Vector4 elements used to set different images to each box side\n * * faceColors an array of 6 Color3 elements used to set different colors to each box side\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.size\n * @param options.width\n * @param options.height\n * @param options.depth\n * @param options.faceUV\n * @param options.faceColors\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.wrap\n * @param options.topBaseAt\n * @param options.bottomBaseAt\n * @returns the VertexData of the box\n */\nexport function CreateBoxVertexData(options) {\n const nbFaces = 6;\n let indices = [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];\n const normals = [\n 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,\n 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0,\n ];\n const uvs = [];\n let positions = [];\n const width = options.width || options.size || 1;\n const height = options.height || options.size || 1;\n const depth = options.depth || options.size || 1;\n const wrap = options.wrap || false;\n let topBaseAt = options.topBaseAt === void 0 ? 1 : options.topBaseAt;\n let bottomBaseAt = options.bottomBaseAt === void 0 ? 0 : options.bottomBaseAt;\n topBaseAt = (topBaseAt + 4) % 4; // places values as 0 to 3\n bottomBaseAt = (bottomBaseAt + 4) % 4; // places values as 0 to 3\n const topOrder = [2, 0, 3, 1];\n const bottomOrder = [2, 0, 1, 3];\n let topIndex = topOrder[topBaseAt];\n let bottomIndex = bottomOrder[bottomBaseAt];\n let basePositions = [\n 1, -1, 1, -1, -1, 1, -1, 1, 1, 1, 1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1, 1, 1, 1, -1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1,\n 1, 1, -1, 1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1, -1, -1, -1, -1, -1, -1, -1, 1,\n ];\n if (wrap) {\n indices = [2, 3, 0, 2, 0, 1, 4, 5, 6, 4, 6, 7, 9, 10, 11, 9, 11, 8, 12, 14, 15, 12, 13, 14];\n basePositions = [\n -1, 1, 1, 1, 1, 1, 1, -1, 1, -1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1, 1, 1, 1, 1, 1, -1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1, -1, -1,\n ];\n let topFaceBase = [\n [1, 1, 1],\n [-1, 1, 1],\n [-1, 1, -1],\n [1, 1, -1],\n ];\n let bottomFaceBase = [\n [-1, -1, 1],\n [1, -1, 1],\n [1, -1, -1],\n [-1, -1, -1],\n ];\n const topFaceOrder = [17, 18, 19, 16];\n const bottomFaceOrder = [22, 23, 20, 21];\n while (topIndex > 0) {\n topFaceBase.unshift(topFaceBase.pop());\n topFaceOrder.unshift(topFaceOrder.pop());\n topIndex--;\n }\n while (bottomIndex > 0) {\n bottomFaceBase.unshift(bottomFaceBase.pop());\n bottomFaceOrder.unshift(bottomFaceOrder.pop());\n bottomIndex--;\n }\n topFaceBase = topFaceBase.flat();\n bottomFaceBase = bottomFaceBase.flat();\n basePositions = basePositions.concat(topFaceBase).concat(bottomFaceBase);\n indices.push(topFaceOrder[0], topFaceOrder[2], topFaceOrder[3], topFaceOrder[0], topFaceOrder[1], topFaceOrder[2]);\n indices.push(bottomFaceOrder[0], bottomFaceOrder[2], bottomFaceOrder[3], bottomFaceOrder[0], bottomFaceOrder[1], bottomFaceOrder[2]);\n }\n const scaleArray = [width / 2, height / 2, depth / 2];\n positions = basePositions.reduce((accumulator, currentValue, currentIndex) => accumulator.concat(currentValue * scaleArray[currentIndex % 3]), []);\n const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;\n const faceUV = options.faceUV || new Array(6);\n const faceColors = options.faceColors;\n const colors = [];\n // default face colors and UV if undefined\n for (let f = 0; f < 6; f++) {\n if (faceUV[f] === undefined) {\n faceUV[f] = new Vector4(0, 0, 1, 1);\n }\n if (faceColors && faceColors[f] === undefined) {\n faceColors[f] = new Color4(1, 1, 1, 1);\n }\n }\n // Create each face in turn.\n for (let index = 0; index < nbFaces; index++) {\n uvs.push(faceUV[index].z, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - faceUV[index].w : faceUV[index].w);\n uvs.push(faceUV[index].x, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - faceUV[index].w : faceUV[index].w);\n uvs.push(faceUV[index].x, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - faceUV[index].y : faceUV[index].y);\n uvs.push(faceUV[index].z, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - faceUV[index].y : faceUV[index].y);\n if (faceColors) {\n for (let c = 0; c < 4; c++) {\n colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);\n }\n }\n }\n // sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Result\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n if (faceColors) {\n const totalColors = sideOrientation === VertexData.DOUBLESIDE ? colors.concat(colors) : colors;\n vertexData.colors = totalColors;\n }\n return vertexData;\n}\n/**\n * Creates a box mesh\n * * The parameter `size` sets the size (float) of each box side (default 1)\n * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)\n * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 Color3 elements) and `faceUV` (an array of 6 Vector4 elements)\n * * Please read this tutorial : https://doc.babylonjs.com/features/featuresDeepDive/materials/using/texturePerBoxFace\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#box\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.size\n * @param options.width\n * @param options.height\n * @param options.depth\n * @param options.faceUV\n * @param options.faceColors\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.wrap\n * @param options.topBaseAt\n * @param options.bottomBaseAt\n * @param options.updatable\n * @param scene defines the hosting scene\n * @returns the box mesh\n */\nexport function CreateBox(name, options = {}, scene = null) {\n const box = new Mesh(name, scene);\n options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n box._originalBuilderSideOrientation = options.sideOrientation;\n const vertexData = CreateBoxVertexData(options);\n vertexData.applyToMesh(box, options.updatable);\n return box;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated please use CreateBox directly\n */\nexport const BoxBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateBox,\n};\n// Side effects\nVertexData.CreateBox = CreateBoxVertexData;\nMesh.CreateBox = (name, size, scene = null, updatable, sideOrientation) => {\n const options = {\n size,\n sideOrientation,\n updatable,\n };\n return CreateBox(name, options, scene);\n};\n//# sourceMappingURL=boxBuilder.js.map","import { TmpVectors } from \"../../Maths/math.vector.js\";\nimport { Mesh, _CreationDataStorage } from \"../mesh.js\";\nimport { VertexBuffer } from \"../../Buffers/buffer.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n/**\n * Creates the VertexData for a Ribbon\n * @param options an object used to set the following optional parameters for the ribbon, required but can be empty\n * * pathArray array of paths, each of which an array of successive Vector3\n * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false\n * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false\n * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false\n * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional\n * * colors a linear array, of length 4 * number of vertices, of custom color values, optional\n * @param options.pathArray\n * @param options.closeArray\n * @param options.closePath\n * @param options.offset\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.invertUV\n * @param options.uvs\n * @param options.colors\n * @returns the VertexData of the ribbon\n */\nexport function CreateRibbonVertexData(options) {\n let pathArray = options.pathArray;\n const closeArray = options.closeArray || false;\n const closePath = options.closePath || false;\n const invertUV = options.invertUV || false;\n const defaultOffset = Math.floor(pathArray[0].length / 2);\n let offset = options.offset || defaultOffset;\n offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset\n const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;\n const customUV = options.uvs;\n const customColors = options.colors;\n const positions = [];\n const indices = [];\n const normals = [];\n const uvs = [];\n const us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id\n const vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutive paths from pathArray\n const uTotalDistance = []; // uTotalDistance[p] : total distance of path p\n const vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray\n let minlg; // minimal length among all paths from pathArray\n const lg = []; // array of path lengths : nb of vertex per path\n const idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number\n let p; // path iterator\n let i; // point iterator\n let j; // point iterator\n // if single path in pathArray\n if (pathArray.length < 2) {\n const ar1 = [];\n const ar2 = [];\n for (i = 0; i < pathArray[0].length - offset; i++) {\n ar1.push(pathArray[0][i]);\n ar2.push(pathArray[0][i + offset]);\n }\n pathArray = [ar1, ar2];\n }\n // positions and horizontal distances (u)\n let idc = 0;\n const closePathCorr = closePath ? 1 : 0; // the final index will be +1 if closePath\n let path;\n let l;\n minlg = pathArray[0].length;\n let vectlg;\n let dist;\n for (p = 0; p < pathArray.length; p++) {\n uTotalDistance[p] = 0;\n us[p] = [0];\n path = pathArray[p];\n l = path.length;\n minlg = minlg < l ? minlg : l;\n j = 0;\n while (j < l) {\n positions.push(path[j].x, path[j].y, path[j].z);\n if (j > 0) {\n vectlg = path[j].subtract(path[j - 1]).length();\n dist = vectlg + uTotalDistance[p];\n us[p].push(dist);\n uTotalDistance[p] = dist;\n }\n j++;\n }\n if (closePath) {\n // an extra hidden vertex is added in the \"positions\" array\n j--;\n positions.push(path[0].x, path[0].y, path[0].z);\n vectlg = path[j].subtract(path[0]).length();\n dist = vectlg + uTotalDistance[p];\n us[p].push(dist);\n uTotalDistance[p] = dist;\n }\n lg[p] = l + closePathCorr;\n idx[p] = idc;\n idc += l + closePathCorr;\n }\n // vertical distances (v)\n let path1;\n let path2;\n let vertex1 = null;\n let vertex2 = null;\n for (i = 0; i < minlg + closePathCorr; i++) {\n vTotalDistance[i] = 0;\n vs[i] = [0];\n for (p = 0; p < pathArray.length - 1; p++) {\n path1 = pathArray[p];\n path2 = pathArray[p + 1];\n if (i === minlg) {\n // closePath\n vertex1 = path1[0];\n vertex2 = path2[0];\n }\n else {\n vertex1 = path1[i];\n vertex2 = path2[i];\n }\n vectlg = vertex2.subtract(vertex1).length();\n dist = vectlg + vTotalDistance[i];\n vs[i].push(dist);\n vTotalDistance[i] = dist;\n }\n if (closeArray && vertex2 && vertex1) {\n path1 = pathArray[p];\n path2 = pathArray[0];\n if (i === minlg) {\n // closePath\n vertex2 = path2[0];\n }\n vectlg = vertex2.subtract(vertex1).length();\n dist = vectlg + vTotalDistance[i];\n vTotalDistance[i] = dist;\n }\n }\n // uvs\n let u;\n let v;\n if (customUV) {\n for (p = 0; p < customUV.length; p++) {\n uvs.push(customUV[p].x, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - customUV[p].y : customUV[p].y);\n }\n }\n else {\n for (p = 0; p < pathArray.length; p++) {\n for (i = 0; i < minlg + closePathCorr; i++) {\n u = uTotalDistance[p] != 0.0 ? us[p][i] / uTotalDistance[p] : 0.0;\n v = vTotalDistance[i] != 0.0 ? vs[i][p] / vTotalDistance[i] : 0.0;\n if (invertUV) {\n uvs.push(v, u);\n }\n else {\n uvs.push(u, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - v : v);\n }\n }\n }\n }\n // indices\n p = 0; // path index\n let pi = 0; // positions array index\n let l1 = lg[p] - 1; // path1 length\n let l2 = lg[p + 1] - 1; // path2 length\n let min = l1 < l2 ? l1 : l2; // current path stop index\n let shft = idx[1] - idx[0]; // shift\n const path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate\ton\n while (pi <= min && p < path1nb) {\n // stay under min and don't go over next to last path\n // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise\n indices.push(pi, pi + shft, pi + 1);\n indices.push(pi + shft + 1, pi + 1, pi + shft);\n pi += 1;\n if (pi === min) {\n // if end of one of two consecutive paths reached, go to next existing path\n p++;\n if (p === lg.length - 1) {\n // last path of pathArray reached <=> closeArray == true\n shft = idx[0] - idx[p];\n l1 = lg[p] - 1;\n l2 = lg[0] - 1;\n }\n else {\n shft = idx[p + 1] - idx[p];\n l1 = lg[p] - 1;\n l2 = lg[p + 1] - 1;\n }\n pi = idx[p];\n min = l1 < l2 ? l1 + pi : l2 + pi;\n }\n }\n // normals\n VertexData.ComputeNormals(positions, indices, normals);\n if (closePath) {\n // update both the first and last vertex normals to their average value\n let indexFirst = 0;\n let indexLast = 0;\n for (p = 0; p < pathArray.length; p++) {\n indexFirst = idx[p] * 3;\n if (p + 1 < pathArray.length) {\n indexLast = (idx[p + 1] - 1) * 3;\n }\n else {\n indexLast = normals.length - 3;\n }\n normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;\n normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;\n normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;\n normals[indexLast] = normals[indexFirst];\n normals[indexLast + 1] = normals[indexFirst + 1];\n normals[indexLast + 2] = normals[indexFirst + 2];\n }\n }\n // sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Colors\n let colors = null;\n if (customColors) {\n colors = new Float32Array(customColors.length * 4);\n for (let c = 0; c < customColors.length; c++) {\n colors[c * 4] = customColors[c].r;\n colors[c * 4 + 1] = customColors[c].g;\n colors[c * 4 + 2] = customColors[c].b;\n colors[c * 4 + 3] = customColors[c].a;\n }\n }\n // Result\n const vertexData = new VertexData();\n const positions32 = new Float32Array(positions);\n const normals32 = new Float32Array(normals);\n const uvs32 = new Float32Array(uvs);\n vertexData.indices = indices;\n vertexData.positions = positions32;\n vertexData.normals = normals32;\n vertexData.uvs = uvs32;\n if (colors) {\n vertexData.set(colors, VertexBuffer.ColorKind);\n }\n if (closePath) {\n vertexData._idx = idx;\n }\n return vertexData;\n}\n/**\n * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters\n * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry\n * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array\n * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array\n * * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path\n * * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11\n * * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#ribbon\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture\n * * The parameter `uvs` is an optional flat array of `Vector2` to update/set each ribbon vertex with its own custom UV values instead of the computed ones\n * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values\n * * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that if you set `closePath` to `true`, there's one extra vertex per path in the geometry\n * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.pathArray\n * @param options.closeArray\n * @param options.closePath\n * @param options.offset\n * @param options.updatable\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.instance\n * @param options.invertUV\n * @param options.uvs\n * @param options.colors\n * @param scene defines the hosting scene\n * @returns the ribbon mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param/ribbon_extra\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param\n */\nexport function CreateRibbon(name, options, scene = null) {\n const pathArray = options.pathArray;\n const closeArray = options.closeArray;\n const closePath = options.closePath;\n const sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n const instance = options.instance;\n const updatable = options.updatable;\n if (instance) {\n // existing ribbon instance update\n // positionFunction : ribbon case\n // only pathArray and sideOrientation parameters are taken into account for positions update\n const minimum = TmpVectors.Vector3[0].setAll(Number.MAX_VALUE);\n const maximum = TmpVectors.Vector3[1].setAll(-Number.MAX_VALUE);\n const positionFunction = (positions) => {\n let minlg = pathArray[0].length;\n const mesh = instance;\n let i = 0;\n const ns = mesh._originalBuilderSideOrientation === Mesh.DOUBLESIDE ? 2 : 1;\n for (let si = 1; si <= ns; ++si) {\n for (let p = 0; p < pathArray.length; ++p) {\n const path = pathArray[p];\n const l = path.length;\n minlg = minlg < l ? minlg : l;\n for (let j = 0; j < minlg; ++j) {\n const pathPoint = path[j];\n positions[i] = pathPoint.x;\n positions[i + 1] = pathPoint.y;\n positions[i + 2] = pathPoint.z;\n minimum.minimizeInPlaceFromFloats(pathPoint.x, pathPoint.y, pathPoint.z);\n maximum.maximizeInPlaceFromFloats(pathPoint.x, pathPoint.y, pathPoint.z);\n i += 3;\n }\n if (mesh._creationDataStorage && mesh._creationDataStorage.closePath) {\n const pathPoint = path[0];\n positions[i] = pathPoint.x;\n positions[i + 1] = pathPoint.y;\n positions[i + 2] = pathPoint.z;\n i += 3;\n }\n }\n }\n };\n const positions = instance.getVerticesData(VertexBuffer.PositionKind);\n positionFunction(positions);\n if (instance.hasBoundingInfo) {\n instance.getBoundingInfo().reConstruct(minimum, maximum, instance._worldMatrix);\n }\n else {\n instance.buildBoundingInfo(minimum, maximum, instance._worldMatrix);\n }\n instance.updateVerticesData(VertexBuffer.PositionKind, positions, false, false);\n if (options.colors) {\n const colors = instance.getVerticesData(VertexBuffer.ColorKind);\n for (let c = 0, colorIndex = 0; c < options.colors.length; c++, colorIndex += 4) {\n const color = options.colors[c];\n colors[colorIndex] = color.r;\n colors[colorIndex + 1] = color.g;\n colors[colorIndex + 2] = color.b;\n colors[colorIndex + 3] = color.a;\n }\n instance.updateVerticesData(VertexBuffer.ColorKind, colors, false, false);\n }\n if (options.uvs) {\n const uvs = instance.getVerticesData(VertexBuffer.UVKind);\n for (let i = 0; i < options.uvs.length; i++) {\n uvs[i * 2] = options.uvs[i].x;\n uvs[i * 2 + 1] = CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - options.uvs[i].y : options.uvs[i].y;\n }\n instance.updateVerticesData(VertexBuffer.UVKind, uvs, false, false);\n }\n if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {\n const indices = instance.getIndices();\n const normals = instance.getVerticesData(VertexBuffer.NormalKind);\n const params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;\n VertexData.ComputeNormals(positions, indices, normals, params);\n if (instance._creationDataStorage && instance._creationDataStorage.closePath) {\n let indexFirst = 0;\n let indexLast = 0;\n for (let p = 0; p < pathArray.length; p++) {\n indexFirst = instance._creationDataStorage.idx[p] * 3;\n if (p + 1 < pathArray.length) {\n indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3;\n }\n else {\n indexLast = normals.length - 3;\n }\n normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;\n normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;\n normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;\n normals[indexLast] = normals[indexFirst];\n normals[indexLast + 1] = normals[indexFirst + 1];\n normals[indexLast + 2] = normals[indexFirst + 2];\n }\n }\n if (!instance.areNormalsFrozen) {\n instance.updateVerticesData(VertexBuffer.NormalKind, normals, false, false);\n }\n }\n return instance;\n }\n else {\n // new ribbon creation\n const ribbon = new Mesh(name, scene);\n ribbon._originalBuilderSideOrientation = sideOrientation;\n ribbon._creationDataStorage = new _CreationDataStorage();\n const vertexData = CreateRibbonVertexData(options);\n if (closePath) {\n ribbon._creationDataStorage.idx = vertexData._idx;\n }\n ribbon._creationDataStorage.closePath = closePath;\n ribbon._creationDataStorage.closeArray = closeArray;\n vertexData.applyToMesh(ribbon, updatable);\n return ribbon;\n }\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use CreateRibbon directly\n */\nexport const RibbonBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateRibbon,\n};\nVertexData.CreateRibbon = CreateRibbonVertexData;\nMesh.CreateRibbon = (name, pathArray, closeArray = false, closePath, offset, scene, updatable = false, sideOrientation, instance) => {\n return CreateRibbon(name, {\n pathArray: pathArray,\n closeArray: closeArray,\n closePath: closePath,\n offset: offset,\n updatable: updatable,\n sideOrientation: sideOrientation,\n instance: instance,\n }, scene);\n};\n//# sourceMappingURL=ribbonBuilder.js.map","import { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n// based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473\n/**\n * Creates the VertexData for a TorusKnot\n * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty\n * * radius the radius of the torus knot, optional, default 2\n * * tube the thickness of the tube, optional, default 0.5\n * * radialSegments the number of sides on each tube segments, optional, default 32\n * * tubularSegments the number of tubes to decompose the knot into, optional, default 32\n * * p the number of windings around the z axis, optional, default 2\n * * q the number of windings around the x axis, optional, default 3\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.radius\n * @param options.tube\n * @param options.radialSegments\n * @param options.tubularSegments\n * @param options.p\n * @param options.q\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the Torus Knot\n */\nexport function CreateTorusKnotVertexData(options) {\n const indices = new Array();\n const positions = new Array();\n const normals = new Array();\n const uvs = new Array();\n const radius = options.radius || 2;\n const tube = options.tube || 0.5;\n const radialSegments = options.radialSegments || 32;\n const tubularSegments = options.tubularSegments || 32;\n const p = options.p || 2;\n const q = options.q || 3;\n const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;\n // Helper\n const getPos = (angle) => {\n const cu = Math.cos(angle);\n const su = Math.sin(angle);\n const quOverP = (q / p) * angle;\n const cs = Math.cos(quOverP);\n const tx = radius * (2 + cs) * 0.5 * cu;\n const ty = radius * (2 + cs) * su * 0.5;\n const tz = radius * Math.sin(quOverP) * 0.5;\n return new Vector3(tx, ty, tz);\n };\n // Vertices\n let i;\n let j;\n for (i = 0; i <= radialSegments; i++) {\n const modI = i % radialSegments;\n const u = (modI / radialSegments) * 2 * p * Math.PI;\n const p1 = getPos(u);\n const p2 = getPos(u + 0.01);\n const tang = p2.subtract(p1);\n let n = p2.add(p1);\n const bitan = Vector3.Cross(tang, n);\n n = Vector3.Cross(bitan, tang);\n bitan.normalize();\n n.normalize();\n for (j = 0; j < tubularSegments; j++) {\n const modJ = j % tubularSegments;\n const v = (modJ / tubularSegments) * 2 * Math.PI;\n const cx = -tube * Math.cos(v);\n const cy = tube * Math.sin(v);\n positions.push(p1.x + cx * n.x + cy * bitan.x);\n positions.push(p1.y + cx * n.y + cy * bitan.y);\n positions.push(p1.z + cx * n.z + cy * bitan.z);\n uvs.push(i / radialSegments);\n uvs.push(CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - j / tubularSegments : j / tubularSegments);\n }\n }\n for (i = 0; i < radialSegments; i++) {\n for (j = 0; j < tubularSegments; j++) {\n const jNext = (j + 1) % tubularSegments;\n const a = i * tubularSegments + j;\n const b = (i + 1) * tubularSegments + j;\n const c = (i + 1) * tubularSegments + jNext;\n const d = i * tubularSegments + jNext;\n indices.push(d);\n indices.push(b);\n indices.push(a);\n indices.push(d);\n indices.push(c);\n indices.push(b);\n }\n }\n // Normals\n VertexData.ComputeNormals(positions, indices, normals);\n // Sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Result\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n}\n/**\n * Creates a torus knot mesh\n * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)\n * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)\n * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)\n * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.radius\n * @param options.tube\n * @param options.radialSegments\n * @param options.tubularSegments\n * @param options.p\n * @param options.q\n * @param options.updatable\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param scene defines the hosting scene\n * @returns the torus knot mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#torus-knot\n */\nexport function CreateTorusKnot(name, options = {}, scene) {\n const torusKnot = new Mesh(name, scene);\n options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n torusKnot._originalBuilderSideOrientation = options.sideOrientation;\n const vertexData = CreateTorusKnotVertexData(options);\n vertexData.applyToMesh(torusKnot, options.updatable);\n return torusKnot;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use CreateTorusKnot instead\n */\nexport const TorusKnotBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateTorusKnot,\n};\nVertexData.CreateTorusKnot = CreateTorusKnotVertexData;\nMesh.CreateTorusKnot = (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) => {\n const options = {\n radius,\n tube,\n radialSegments,\n tubularSegments,\n p,\n q,\n sideOrientation,\n updatable,\n };\n return CreateTorusKnot(name, options, scene);\n};\n//# sourceMappingURL=torusKnotBuilder.js.map","import { Vector3, Matrix } from \"../../Maths/math.vector.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n/**\n * Creates the VertexData for an ellipsoid, defaults to a sphere\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * segments sets the number of horizontal strips optional, default 32\n * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1\n * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter\n * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter\n * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter\n * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1\n * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.segments\n * @param options.diameter\n * @param options.diameterX\n * @param options.diameterY\n * @param options.diameterZ\n * @param options.arc\n * @param options.slice\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.dedupTopBottomIndices\n * @returns the VertexData of the ellipsoid\n */\nexport function CreateSphereVertexData(options) {\n const segments = options.segments || 32;\n const diameterX = options.diameterX || options.diameter || 1;\n const diameterY = options.diameterY || options.diameter || 1;\n const diameterZ = options.diameterZ || options.diameter || 1;\n const arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;\n const slice = options.slice && options.slice <= 0 ? 1.0 : options.slice || 1.0;\n const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;\n const dedupTopBottomIndices = !!options.dedupTopBottomIndices;\n const radius = new Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);\n const totalZRotationSteps = 2 + segments;\n const totalYRotationSteps = 2 * totalZRotationSteps;\n const indices = [];\n const positions = [];\n const normals = [];\n const uvs = [];\n for (let zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {\n const normalizedZ = zRotationStep / totalZRotationSteps;\n const angleZ = normalizedZ * Math.PI * slice;\n for (let yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {\n const normalizedY = yRotationStep / totalYRotationSteps;\n const angleY = normalizedY * Math.PI * 2 * arc;\n const rotationZ = Matrix.RotationZ(-angleZ);\n const rotationY = Matrix.RotationY(angleY);\n const afterRotZ = Vector3.TransformCoordinates(Vector3.Up(), rotationZ);\n const complete = Vector3.TransformCoordinates(afterRotZ, rotationY);\n const vertex = complete.multiply(radius);\n const normal = complete.divide(radius).normalize();\n positions.push(vertex.x, vertex.y, vertex.z);\n normals.push(normal.x, normal.y, normal.z);\n uvs.push(normalizedY, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - normalizedZ : normalizedZ);\n }\n if (zRotationStep > 0) {\n const verticesCount = positions.length / 3;\n for (let firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); firstIndex + totalYRotationSteps + 2 < verticesCount; firstIndex++) {\n if (dedupTopBottomIndices) {\n if (zRotationStep > 1) {\n indices.push(firstIndex);\n indices.push(firstIndex + 1);\n indices.push(firstIndex + totalYRotationSteps + 1);\n }\n if (zRotationStep < totalZRotationSteps || slice < 1.0) {\n indices.push(firstIndex + totalYRotationSteps + 1);\n indices.push(firstIndex + 1);\n indices.push(firstIndex + totalYRotationSteps + 2);\n }\n }\n else {\n indices.push(firstIndex);\n indices.push(firstIndex + 1);\n indices.push(firstIndex + totalYRotationSteps + 1);\n indices.push(firstIndex + totalYRotationSteps + 1);\n indices.push(firstIndex + 1);\n indices.push(firstIndex + totalYRotationSteps + 2);\n }\n }\n }\n }\n // Sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Result\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n}\n/**\n * Creates a sphere mesh\n * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)\n * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value of `diameter`)\n * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)\n * * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio\n * * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude)\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.segments\n * @param options.diameter\n * @param options.diameterX\n * @param options.diameterY\n * @param options.diameterZ\n * @param options.arc\n * @param options.slice\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.updatable\n * @param scene defines the hosting scene\n * @returns the sphere mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#sphere\n */\nexport function CreateSphere(name, options = {}, scene = null) {\n const sphere = new Mesh(name, scene);\n options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n sphere._originalBuilderSideOrientation = options.sideOrientation;\n const vertexData = CreateSphereVertexData(options);\n vertexData.applyToMesh(sphere, options.updatable);\n return sphere;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use CreateSphere directly\n */\nexport const SphereBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateSphere,\n};\nVertexData.CreateSphere = CreateSphereVertexData;\nMesh.CreateSphere = (name, segments, diameter, scene, updatable, sideOrientation) => {\n const options = {\n segments: segments,\n diameterX: diameter,\n diameterY: diameter,\n diameterZ: diameter,\n sideOrientation: sideOrientation,\n updatable: updatable,\n };\n return CreateSphere(name, options, scene);\n};\n//# sourceMappingURL=sphereBuilder.js.map","import { VertexData } from \"../mesh.vertexData.js\";\nimport { Vector2, Vector3, Matrix } from \"../../Maths/math.vector.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n/**\n * Scripts based off of https://github.com/maximeq/three-js-capsule-geometry/blob/master/src/CapsuleBufferGeometry.js\n * @param options the constructors options used to shape the mesh.\n * @returns the capsule VertexData\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/capsule\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function CreateCapsuleVertexData(options = {\n subdivisions: 2,\n tessellation: 16,\n height: 1,\n radius: 0.25,\n capSubdivisions: 6,\n}) {\n const subdivisions = Math.max(options.subdivisions ? options.subdivisions : 2, 1);\n const tessellation = Math.max(options.tessellation ? options.tessellation : 16, 3);\n const height = Math.max(options.height ? options.height : 1, 0);\n const radius = Math.max(options.radius ? options.radius : 0.25, 0);\n const capDetail = Math.max(options.capSubdivisions ? options.capSubdivisions : 6, 1);\n const radialSegments = tessellation;\n const heightSegments = subdivisions;\n const radiusTop = Math.max(options.radiusTop ? options.radiusTop : radius, 0);\n const radiusBottom = Math.max(options.radiusBottom ? options.radiusBottom : radius, 0);\n const heightMinusCaps = height - (radiusTop + radiusBottom);\n const thetaStart = 0.0;\n const thetaLength = 2.0 * Math.PI;\n const capsTopSegments = Math.max(options.topCapSubdivisions ? options.topCapSubdivisions : capDetail, 1);\n const capsBottomSegments = Math.max(options.bottomCapSubdivisions ? options.bottomCapSubdivisions : capDetail, 1);\n const alpha = Math.acos((radiusBottom - radiusTop) / height);\n let indices = [];\n const vertices = [];\n const normals = [];\n const uvs = [];\n let index = 0;\n const indexArray = [], halfHeight = heightMinusCaps * 0.5;\n const pi2 = Math.PI * 0.5;\n let x, y;\n const normal = Vector3.Zero();\n const vertex = Vector3.Zero();\n const cosAlpha = Math.cos(alpha);\n const sinAlpha = Math.sin(alpha);\n const coneLength = new Vector2(radiusTop * sinAlpha, halfHeight + radiusTop * cosAlpha)\n .subtract(new Vector2(radiusBottom * sinAlpha, -halfHeight + radiusBottom * cosAlpha))\n .length();\n // Total length for v texture coord\n const vl = radiusTop * alpha + coneLength + radiusBottom * (pi2 - alpha);\n let v = 0;\n for (y = 0; y <= capsTopSegments; y++) {\n const indexRow = [];\n const a = pi2 - alpha * (y / capsTopSegments);\n v += (radiusTop * alpha) / capsTopSegments;\n const cosA = Math.cos(a);\n const sinA = Math.sin(a);\n // calculate the radius of the current row\n const _radius = cosA * radiusTop;\n for (x = 0; x <= radialSegments; x++) {\n const u = x / radialSegments;\n const theta = u * thetaLength + thetaStart;\n const sinTheta = Math.sin(theta);\n const cosTheta = Math.cos(theta);\n // vertex\n vertex.x = _radius * sinTheta;\n vertex.y = halfHeight + sinA * radiusTop;\n vertex.z = _radius * cosTheta;\n vertices.push(vertex.x, vertex.y, vertex.z);\n // normal\n normal.set(cosA * sinTheta, sinA, cosA * cosTheta);\n normals.push(normal.x, normal.y, normal.z);\n // uv\n uvs.push(u, CompatibilityOptions.UseOpenGLOrientationForUV ? v / vl : 1 - v / vl);\n // save index of vertex in respective row\n indexRow.push(index);\n // increase index\n index++;\n }\n // now save vertices of the row in our index array\n indexArray.push(indexRow);\n }\n const coneHeight = height - radiusTop - radiusBottom + cosAlpha * radiusTop - cosAlpha * radiusBottom;\n const slope = (sinAlpha * (radiusBottom - radiusTop)) / coneHeight;\n for (y = 1; y <= heightSegments; y++) {\n const indexRow = [];\n v += coneLength / heightSegments;\n // calculate the radius of the current row\n const _radius = sinAlpha * ((y * (radiusBottom - radiusTop)) / heightSegments + radiusTop);\n for (x = 0; x <= radialSegments; x++) {\n const u = x / radialSegments;\n const theta = u * thetaLength + thetaStart;\n const sinTheta = Math.sin(theta);\n const cosTheta = Math.cos(theta);\n // vertex\n vertex.x = _radius * sinTheta;\n vertex.y = halfHeight + cosAlpha * radiusTop - (y * coneHeight) / heightSegments;\n vertex.z = _radius * cosTheta;\n vertices.push(vertex.x, vertex.y, vertex.z);\n // normal\n normal.set(sinTheta, slope, cosTheta).normalize();\n normals.push(normal.x, normal.y, normal.z);\n // uv\n uvs.push(u, CompatibilityOptions.UseOpenGLOrientationForUV ? v / vl : 1 - v / vl);\n // save index of vertex in respective row\n indexRow.push(index);\n // increase index\n index++;\n }\n // now save vertices of the row in our index array\n indexArray.push(indexRow);\n }\n for (y = 1; y <= capsBottomSegments; y++) {\n const indexRow = [];\n const a = pi2 - alpha - (Math.PI - alpha) * (y / capsBottomSegments);\n v += (radiusBottom * alpha) / capsBottomSegments;\n const cosA = Math.cos(a);\n const sinA = Math.sin(a);\n // calculate the radius of the current row\n const _radius = cosA * radiusBottom;\n for (x = 0; x <= radialSegments; x++) {\n const u = x / radialSegments;\n const theta = u * thetaLength + thetaStart;\n const sinTheta = Math.sin(theta);\n const cosTheta = Math.cos(theta);\n // vertex\n vertex.x = _radius * sinTheta;\n vertex.y = -halfHeight + sinA * radiusBottom;\n vertex.z = _radius * cosTheta;\n vertices.push(vertex.x, vertex.y, vertex.z);\n // normal\n normal.set(cosA * sinTheta, sinA, cosA * cosTheta);\n normals.push(normal.x, normal.y, normal.z);\n // uv\n uvs.push(u, CompatibilityOptions.UseOpenGLOrientationForUV ? v / vl : 1 - v / vl);\n // save index of vertex in respective row\n indexRow.push(index);\n // increase index\n index++;\n }\n // now save vertices of the row in our index array\n indexArray.push(indexRow);\n }\n // generate indices\n for (x = 0; x < radialSegments; x++) {\n for (y = 0; y < capsTopSegments + heightSegments + capsBottomSegments; y++) {\n // we use the index array to access the correct indices\n const i1 = indexArray[y][x];\n const i2 = indexArray[y + 1][x];\n const i3 = indexArray[y + 1][x + 1];\n const i4 = indexArray[y][x + 1];\n // face one\n indices.push(i1);\n indices.push(i2);\n indices.push(i4);\n // face two\n indices.push(i2);\n indices.push(i3);\n indices.push(i4);\n }\n }\n indices = indices.reverse();\n if (options.orientation && !options.orientation.equals(Vector3.Up())) {\n const m = new Matrix();\n options.orientation\n .clone()\n .scale(Math.PI * 0.5)\n .cross(Vector3.Up())\n .toQuaternion()\n .toRotationMatrix(m);\n const v = Vector3.Zero();\n for (let i = 0; i < vertices.length; i += 3) {\n v.set(vertices[i], vertices[i + 1], vertices[i + 2]);\n Vector3.TransformCoordinatesToRef(v.clone(), m, v);\n vertices[i] = v.x;\n vertices[i + 1] = v.y;\n vertices[i + 2] = v.z;\n }\n }\n const vDat = new VertexData();\n vDat.positions = vertices;\n vDat.normals = normals;\n vDat.uvs = uvs;\n vDat.indices = indices;\n return vDat;\n}\n/**\n * Creates a capsule or a pill mesh\n * @param name defines the name of the mesh\n * @param options The constructors options.\n * @param scene The scene the mesh is scoped to.\n * @returns Capsule Mesh\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function CreateCapsule(name, options = {\n orientation: Vector3.Up(),\n subdivisions: 2,\n tessellation: 16,\n height: 1,\n radius: 0.25,\n capSubdivisions: 6,\n updatable: false,\n}, scene = null) {\n const capsule = new Mesh(name, scene);\n const vertexData = CreateCapsuleVertexData(options);\n vertexData.applyToMesh(capsule, options.updatable);\n return capsule;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated please use CreateCapsule directly\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const CapsuleBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateCapsule,\n};\n/**\n * Creates a capsule or a pill mesh\n * @param name defines the name of the mesh.\n * @param options the constructors options used to shape the mesh.\n * @param scene defines the scene the mesh is scoped to.\n * @returns the capsule mesh\n * @see https://doc.babylonjs.com/how_to/capsule_shape\n */\nMesh.CreateCapsule = (name, options, scene) => {\n return CreateCapsule(name, options, scene);\n};\nVertexData.CreateCapsule = CreateCapsuleVertexData;\n//# sourceMappingURL=capsuleBuilder.js.map","import { Mesh } from \"../mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n/**\n * Creates the VertexData of the Disc or regular Polygon\n * @param options an object used to set the following optional parameters for the disc, required but can be empty\n * * radius the radius of the disc, optional default 0.5\n * * tessellation the number of polygon sides, optional, default 64\n * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.radius\n * @param options.tessellation\n * @param options.arc\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the box\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function CreateDiscVertexData(options) {\n const positions = new Array();\n const indices = new Array();\n const normals = new Array();\n const uvs = new Array();\n const radius = options.radius || 0.5;\n const tessellation = options.tessellation || 64;\n const arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;\n const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;\n // positions and uvs\n positions.push(0, 0, 0); // disc center first\n uvs.push(0.5, 0.5);\n const theta = Math.PI * 2 * arc;\n const step = arc === 1 ? theta / tessellation : theta / (tessellation - 1);\n let a = 0;\n for (let t = 0; t < tessellation; t++) {\n const x = Math.cos(a);\n const y = Math.sin(a);\n const u = (x + 1) / 2;\n const v = (1 - y) / 2;\n positions.push(radius * x, radius * y, 0);\n uvs.push(u, CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v);\n a += step;\n }\n if (arc === 1) {\n positions.push(positions[3], positions[4], positions[5]); // close the circle\n uvs.push(uvs[2], CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - uvs[3] : uvs[3]);\n }\n //indices\n const vertexNb = positions.length / 3;\n for (let i = 1; i < vertexNb - 1; i++) {\n indices.push(i + 1, 0, i);\n }\n // result\n VertexData.ComputeNormals(positions, indices, normals);\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n}\n/**\n * Creates a plane polygonal mesh. By default, this is a disc\n * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)\n * * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc\n * * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.radius\n * @param options.tessellation\n * @param options.arc\n * @param options.updatable\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param scene defines the hosting scene\n * @returns the plane polygonal mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#disc-or-regular-polygon\n */\nexport function CreateDisc(name, options = {}, scene = null) {\n const disc = new Mesh(name, scene);\n options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n disc._originalBuilderSideOrientation = options.sideOrientation;\n const vertexData = CreateDiscVertexData(options);\n vertexData.applyToMesh(disc, options.updatable);\n return disc;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated please use CreateDisc directly\n */\nexport const DiscBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateDisc,\n};\nVertexData.CreateDisc = CreateDiscVertexData;\nMesh.CreateDisc = (name, radius, tessellation, scene = null, updatable, sideOrientation) => {\n const options = {\n radius,\n tessellation,\n sideOrientation,\n updatable,\n };\n return CreateDisc(name, options, scene);\n};\n//# sourceMappingURL=discBuilder.js.map","import { Mesh } from \"../mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\n/**\n * Creates the VertexData for a tiled plane\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/tiled_plane\n * @param options an object used to set the following optional parameters for the tiled plane, required but can be empty\n * * pattern a limited pattern arrangement depending on the number\n * * size of the box\n * * width of the box, overwrites size\n * * height of the box, overwrites size\n * * tileSize sets the width, height and depth of the tile to the value of size, optional default 1\n * * tileWidth sets the width (x direction) of the tile, overwrites the width set by size, optional, default size\n * * tileHeight sets the height (y direction) of the tile, overwrites the height set by size, optional, default size\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * alignHorizontal places whole tiles aligned to the center, left or right of a row\n * * alignVertical places whole tiles aligned to the center, left or right of a column\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * @param options.pattern\n * @param options.tileSize\n * @param options.tileWidth\n * @param options.tileHeight\n * @param options.size\n * @param options.width\n * @param options.height\n * @param options.alignHorizontal\n * @param options.alignVertical\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @returns the VertexData of the tiled plane\n */\nexport function CreateTiledPlaneVertexData(options) {\n const flipTile = options.pattern || Mesh.NO_FLIP;\n const tileWidth = options.tileWidth || options.tileSize || 1;\n const tileHeight = options.tileHeight || options.tileSize || 1;\n const alignH = options.alignHorizontal || 0;\n const alignV = options.alignVertical || 0;\n const width = options.width || options.size || 1;\n const tilesX = Math.floor(width / tileWidth);\n let offsetX = width - tilesX * tileWidth;\n const height = options.height || options.size || 1;\n const tilesY = Math.floor(height / tileHeight);\n let offsetY = height - tilesY * tileHeight;\n const halfWidth = (tileWidth * tilesX) / 2;\n const halfHeight = (tileHeight * tilesY) / 2;\n let adjustX = 0;\n let adjustY = 0;\n let startX = 0;\n let startY = 0;\n let endX = 0;\n let endY = 0;\n //Part Tiles\n if (offsetX > 0 || offsetY > 0) {\n startX = -halfWidth;\n startY = -halfHeight;\n endX = halfWidth;\n endY = halfHeight;\n switch (alignH) {\n case Mesh.CENTER:\n offsetX /= 2;\n startX -= offsetX;\n endX += offsetX;\n break;\n case Mesh.LEFT:\n endX += offsetX;\n adjustX = -offsetX / 2;\n break;\n case Mesh.RIGHT:\n startX -= offsetX;\n adjustX = offsetX / 2;\n break;\n }\n switch (alignV) {\n case Mesh.CENTER:\n offsetY /= 2;\n startY -= offsetY;\n endY += offsetY;\n break;\n case Mesh.BOTTOM:\n endY += offsetY;\n adjustY = -offsetY / 2;\n break;\n case Mesh.TOP:\n startY -= offsetY;\n adjustY = offsetY / 2;\n break;\n }\n }\n const positions = [];\n const normals = [];\n const uvBase = [];\n uvBase[0] = [0, 0, 1, 0, 1, 1, 0, 1];\n uvBase[1] = [0, 0, 1, 0, 1, 1, 0, 1];\n if (flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.ROTATE_ROW) {\n uvBase[1] = [1, 1, 0, 1, 0, 0, 1, 0];\n }\n if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.FLIP_ROW) {\n uvBase[1] = [1, 0, 0, 0, 0, 1, 1, 1];\n }\n if (flipTile === Mesh.FLIP_N_ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_ROW) {\n uvBase[1] = [0, 1, 1, 1, 1, 0, 0, 0];\n }\n let uvs = [];\n const colors = [];\n const indices = [];\n let index = 0;\n for (let y = 0; y < tilesY; y++) {\n for (let x = 0; x < tilesX; x++) {\n positions.push(-halfWidth + x * tileWidth + adjustX, -halfHeight + y * tileHeight + adjustY, 0);\n positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, -halfHeight + y * tileHeight + adjustY, 0);\n positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0);\n positions.push(-halfWidth + x * tileWidth + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0);\n indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);\n if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_TILE) {\n uvs = uvs.concat(uvBase[((x % 2) + (y % 2)) % 2]);\n }\n else if (flipTile === Mesh.FLIP_ROW || flipTile === Mesh.ROTATE_ROW || flipTile === Mesh.FLIP_N_ROTATE_ROW) {\n uvs = uvs.concat(uvBase[y % 2]);\n }\n else {\n uvs = uvs.concat(uvBase[0]);\n }\n colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);\n normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);\n index += 4;\n }\n }\n //Part Tiles\n if (offsetX > 0 || offsetY > 0) {\n const partialBottomRow = offsetY > 0 && (alignV === Mesh.CENTER || alignV === Mesh.TOP);\n const partialTopRow = offsetY > 0 && (alignV === Mesh.CENTER || alignV === Mesh.BOTTOM);\n const partialLeftCol = offsetX > 0 && (alignH === Mesh.CENTER || alignH === Mesh.RIGHT);\n const partialRightCol = offsetX > 0 && (alignH === Mesh.CENTER || alignH === Mesh.LEFT);\n let uvPart = [];\n let a, b, c, d;\n //corners\n if (partialBottomRow && partialLeftCol) {\n //bottom left corner\n positions.push(startX + adjustX, startY + adjustY, 0);\n positions.push(-halfWidth + adjustX, startY + adjustY, 0);\n positions.push(-halfWidth + adjustX, startY + offsetY + adjustY, 0);\n positions.push(startX + adjustX, startY + offsetY + adjustY, 0);\n indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);\n index += 4;\n a = 1 - offsetX / tileWidth;\n b = 1 - offsetY / tileHeight;\n c = 1;\n d = 1;\n uvPart = [a, b, c, b, c, d, a, d];\n if (flipTile === Mesh.ROTATE_ROW) {\n uvPart = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d];\n }\n if (flipTile === Mesh.FLIP_ROW) {\n uvPart = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d];\n }\n if (flipTile === Mesh.FLIP_N_ROTATE_ROW) {\n uvPart = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d];\n }\n uvs = uvs.concat(uvPart);\n colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);\n normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);\n }\n if (partialBottomRow && partialRightCol) {\n //bottom right corner\n positions.push(halfWidth + adjustX, startY + adjustY, 0);\n positions.push(endX + adjustX, startY + adjustY, 0);\n positions.push(endX + adjustX, startY + offsetY + adjustY, 0);\n positions.push(halfWidth + adjustX, startY + offsetY + adjustY, 0);\n indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);\n index += 4;\n a = 0;\n b = 1 - offsetY / tileHeight;\n c = offsetX / tileWidth;\n d = 1;\n uvPart = [a, b, c, b, c, d, a, d];\n if (flipTile === Mesh.ROTATE_ROW || (flipTile === Mesh.ROTATE_TILE && tilesX % 2 === 0)) {\n uvPart = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d];\n }\n if (flipTile === Mesh.FLIP_ROW || (flipTile === Mesh.FLIP_TILE && tilesX % 2 === 0)) {\n uvPart = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d];\n }\n if (flipTile === Mesh.FLIP_N_ROTATE_ROW || (flipTile === Mesh.FLIP_N_ROTATE_TILE && tilesX % 2 === 0)) {\n uvPart = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d];\n }\n uvs = uvs.concat(uvPart);\n colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);\n normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);\n }\n if (partialTopRow && partialLeftCol) {\n //top left corner\n positions.push(startX + adjustX, halfHeight + adjustY, 0);\n positions.push(-halfWidth + adjustX, halfHeight + adjustY, 0);\n positions.push(-halfWidth + adjustX, endY + adjustY, 0);\n positions.push(startX + adjustX, endY + adjustY, 0);\n indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);\n index += 4;\n a = 1 - offsetX / tileWidth;\n b = 0;\n c = 1;\n d = offsetY / tileHeight;\n uvPart = [a, b, c, b, c, d, a, d];\n if ((flipTile === Mesh.ROTATE_ROW && tilesY % 2 === 1) || (flipTile === Mesh.ROTATE_TILE && tilesY % 1 === 0)) {\n uvPart = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d];\n }\n if ((flipTile === Mesh.FLIP_ROW && tilesY % 2 === 1) || (flipTile === Mesh.FLIP_TILE && tilesY % 2 === 0)) {\n uvPart = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d];\n }\n if ((flipTile === Mesh.FLIP_N_ROTATE_ROW && tilesY % 2 === 1) || (flipTile === Mesh.FLIP_N_ROTATE_TILE && tilesY % 2 === 0)) {\n uvPart = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d];\n }\n uvs = uvs.concat(uvPart);\n colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);\n normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);\n }\n if (partialTopRow && partialRightCol) {\n //top right corner\n positions.push(halfWidth + adjustX, halfHeight + adjustY, 0);\n positions.push(endX + adjustX, halfHeight + adjustY, 0);\n positions.push(endX + adjustX, endY + adjustY, 0);\n positions.push(halfWidth + adjustX, endY + adjustY, 0);\n indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);\n index += 4;\n a = 0;\n b = 0;\n c = offsetX / tileWidth;\n d = offsetY / tileHeight;\n uvPart = [a, b, c, b, c, d, a, d];\n if ((flipTile === Mesh.ROTATE_ROW && tilesY % 2 === 1) || (flipTile === Mesh.ROTATE_TILE && (tilesY + tilesX) % 2 === 1)) {\n uvPart = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d];\n }\n if ((flipTile === Mesh.FLIP_ROW && tilesY % 2 === 1) || (flipTile === Mesh.FLIP_TILE && (tilesY + tilesX) % 2 === 1)) {\n uvPart = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d];\n }\n if ((flipTile === Mesh.FLIP_N_ROTATE_ROW && tilesY % 2 === 1) || (flipTile === Mesh.FLIP_N_ROTATE_TILE && (tilesY + tilesX) % 2 === 1)) {\n uvPart = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d];\n }\n uvs = uvs.concat(uvPart);\n colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);\n normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);\n }\n //part rows\n if (partialBottomRow) {\n const uvBaseBR = [];\n a = 0;\n b = 1 - offsetY / tileHeight;\n c = 1;\n d = 1;\n uvBaseBR[0] = [a, b, c, b, c, d, a, d];\n uvBaseBR[1] = [a, b, c, b, c, d, a, d];\n if (flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.ROTATE_ROW) {\n uvBaseBR[1] = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d];\n }\n if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.FLIP_ROW) {\n uvBaseBR[1] = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d];\n }\n if (flipTile === Mesh.FLIP_N_ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_ROW) {\n uvBaseBR[1] = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d];\n }\n for (let x = 0; x < tilesX; x++) {\n positions.push(-halfWidth + x * tileWidth + adjustX, startY + adjustY, 0);\n positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, startY + adjustY, 0);\n positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, startY + offsetY + adjustY, 0);\n positions.push(-halfWidth + x * tileWidth + adjustX, startY + offsetY + adjustY, 0);\n indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);\n index += 4;\n if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_TILE) {\n uvs = uvs.concat(uvBaseBR[(x + 1) % 2]);\n }\n else if (flipTile === Mesh.FLIP_ROW || flipTile === Mesh.ROTATE_ROW || flipTile === Mesh.FLIP_N_ROTATE_ROW) {\n uvs = uvs.concat(uvBaseBR[1]);\n }\n else {\n uvs = uvs.concat(uvBaseBR[0]);\n }\n colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);\n normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);\n }\n }\n if (partialTopRow) {\n const uvBaseTR = [];\n a = 0;\n b = 0;\n c = 1;\n d = offsetY / tileHeight;\n uvBaseTR[0] = [a, b, c, b, c, d, a, d];\n uvBaseTR[1] = [a, b, c, b, c, d, a, d];\n if (flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.ROTATE_ROW) {\n uvBaseTR[1] = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d];\n }\n if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.FLIP_ROW) {\n uvBaseTR[1] = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d];\n }\n if (flipTile === Mesh.FLIP_N_ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_ROW) {\n uvBaseTR[1] = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d];\n }\n for (let x = 0; x < tilesX; x++) {\n positions.push(-halfWidth + x * tileWidth + adjustX, endY - offsetY + adjustY, 0);\n positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, endY - offsetY + adjustY, 0);\n positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, endY + adjustY, 0);\n positions.push(-halfWidth + x * tileWidth + adjustX, endY + adjustY, 0);\n indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);\n index += 4;\n if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_TILE) {\n uvs = uvs.concat(uvBaseTR[(x + tilesY) % 2]);\n }\n else if (flipTile === Mesh.FLIP_ROW || flipTile === Mesh.ROTATE_ROW || flipTile === Mesh.FLIP_N_ROTATE_ROW) {\n uvs = uvs.concat(uvBaseTR[tilesY % 2]);\n }\n else {\n uvs = uvs.concat(uvBaseTR[0]);\n }\n colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);\n normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);\n }\n }\n if (partialLeftCol) {\n const uvBaseLC = [];\n a = 1 - offsetX / tileWidth;\n b = 0;\n c = 1;\n d = 1;\n uvBaseLC[0] = [a, b, c, b, c, d, a, d];\n uvBaseLC[1] = [a, b, c, b, c, d, a, d];\n if (flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.ROTATE_ROW) {\n uvBaseLC[1] = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d];\n }\n if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.FLIP_ROW) {\n uvBaseLC[1] = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d];\n }\n if (flipTile === Mesh.FLIP_N_ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_ROW) {\n uvBaseLC[1] = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d];\n }\n for (let y = 0; y < tilesY; y++) {\n positions.push(startX + adjustX, -halfHeight + y * tileHeight + adjustY, 0);\n positions.push(startX + offsetX + adjustX, -halfHeight + y * tileHeight + adjustY, 0);\n positions.push(startX + offsetX + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0);\n positions.push(startX + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0);\n indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);\n index += 4;\n if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_TILE) {\n uvs = uvs.concat(uvBaseLC[(y + 1) % 2]);\n }\n else if (flipTile === Mesh.FLIP_ROW || flipTile === Mesh.ROTATE_ROW || flipTile === Mesh.FLIP_N_ROTATE_ROW) {\n uvs = uvs.concat(uvBaseLC[y % 2]);\n }\n else {\n uvs = uvs.concat(uvBaseLC[0]);\n }\n colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);\n normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);\n }\n }\n if (partialRightCol) {\n const uvBaseRC = [];\n a = 0;\n b = 0;\n c = offsetX / tileHeight;\n d = 1;\n uvBaseRC[0] = [a, b, c, b, c, d, a, d];\n uvBaseRC[1] = [a, b, c, b, c, d, a, d];\n if (flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.ROTATE_ROW) {\n uvBaseRC[1] = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d];\n }\n if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.FLIP_ROW) {\n uvBaseRC[1] = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d];\n }\n if (flipTile === Mesh.FLIP_N_ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_ROW) {\n uvBaseRC[1] = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d];\n }\n for (let y = 0; y < tilesY; y++) {\n positions.push(endX - offsetX + adjustX, -halfHeight + y * tileHeight + adjustY, 0);\n positions.push(endX + adjustX, -halfHeight + y * tileHeight + adjustY, 0);\n positions.push(endX + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0);\n positions.push(endX - offsetX + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0);\n indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);\n index += 4;\n if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_TILE) {\n uvs = uvs.concat(uvBaseRC[(y + tilesX) % 2]);\n }\n else if (flipTile === Mesh.FLIP_ROW || flipTile === Mesh.ROTATE_ROW || flipTile === Mesh.FLIP_N_ROTATE_ROW) {\n uvs = uvs.concat(uvBaseRC[y % 2]);\n }\n else {\n uvs = uvs.concat(uvBaseRC[0]);\n }\n colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);\n normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);\n }\n }\n }\n const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;\n // sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Result\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n const totalColors = sideOrientation === VertexData.DOUBLESIDE ? colors.concat(colors) : colors;\n vertexData.colors = totalColors;\n return vertexData;\n}\n/**\n * Creates a tiled plane mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/tiled_plane\n * @param name defines the name of the mesh\n * @param options an object used to set the following optional parameters for the tiled plane, required but can be empty\n * * pattern a limited pattern arrangement depending on the number\n * * size of the box\n * * width of the box, overwrites size\n * * height of the box, overwrites size\n * * tileSize sets the width, height and depth of the tile to the value of size, optional default 1\n * * tileWidth sets the width (x direction) of the tile, overwrites the width set by size, optional, default size\n * * tileHeight sets the height (y direction) of the tile, overwrites the height set by size, optional, default size\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * alignHorizontal places whole tiles aligned to the center, left or right of a row\n * * alignVertical places whole tiles aligned to the center, left or right of a column\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.pattern\n * @param options.tileSize\n * @param options.tileWidth\n * @param options.tileHeight\n * @param options.size\n * @param options.width\n * @param options.height\n * @param options.alignHorizontal\n * @param options.alignVertical\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.updatable\n * @param scene defines the hosting scene\n * @returns the box mesh\n */\nexport function CreateTiledPlane(name, options, scene = null) {\n const plane = new Mesh(name, scene);\n options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n plane._originalBuilderSideOrientation = options.sideOrientation;\n const vertexData = CreateTiledPlaneVertexData(options);\n vertexData.applyToMesh(plane, options.updatable);\n return plane;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use CreateTiledPlane instead\n */\nexport const TiledPlaneBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateTiledPlane,\n};\nVertexData.CreateTiledPlane = CreateTiledPlaneVertexData;\n//# sourceMappingURL=tiledPlaneBuilder.js.map","import { SerializationHelper } from \"../Misc/decorators.js\";\nimport { Matrix, Vector3, Vector2, Vector4, Quaternion } from \"../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { MaterialHelper } from \"./materialHelper.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\nimport { Color3, Color4 } from \"../Maths/math.color.js\";\nimport { EffectFallbacks } from \"./effectFallbacks.js\";\nimport { WebRequest } from \"../Misc/webRequest.js\";\nimport { PushMaterial } from \"./pushMaterial.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n\nimport { addClipPlaneUniforms, bindClipPlane, prepareStringDefinesForClipPlanes } from \"./clipPlaneMaterialHelper.js\";\nconst onCreatedEffectParameters = { effect: null, subMesh: null };\n/**\n * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.\n *\n * This returned material effects how the mesh will look based on the code in the shaders.\n *\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/shaders/shaderMaterial\n */\nexport class ShaderMaterial extends PushMaterial {\n /**\n * Instantiate a new shader material.\n * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.\n * This returned material effects how the mesh will look based on the code in the shaders.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/shaders/shaderMaterial\n * @param name Define the name of the material in the scene\n * @param scene Define the scene the material belongs to\n * @param shaderPath Defines the route to the shader code in one of three ways:\n * * object: \\{ vertex: \"custom\", fragment: \"custom\" \\}, used with Effect.ShadersStore[\"customVertexShader\"] and Effect.ShadersStore[\"customFragmentShader\"]\n * * object: \\{ vertexElement: \"vertexShaderCode\", fragmentElement: \"fragmentShaderCode\" \\}, used with shader code in script tags\n * * object: \\{ vertexSource: \"vertex shader code string\", fragmentSource: \"fragment shader code string\" \\} using with strings containing the shaders code\n * * string: \"./COMMON_NAME\", used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in index.html folder.\n * @param options Define the options used to create the shader\n * @param storeEffectOnSubMeshes true to store effect on submeshes, false to store the effect directly in the material class.\n */\n constructor(name, scene, shaderPath, options = {}, storeEffectOnSubMeshes = true) {\n super(name, scene, storeEffectOnSubMeshes);\n this._textures = {};\n this._textureArrays = {};\n this._externalTextures = {};\n this._floats = {};\n this._ints = {};\n this._uints = {};\n this._floatsArrays = {};\n this._colors3 = {};\n this._colors3Arrays = {};\n this._colors4 = {};\n this._colors4Arrays = {};\n this._vectors2 = {};\n this._vectors3 = {};\n this._vectors4 = {};\n this._quaternions = {};\n this._quaternionsArrays = {};\n this._matrices = {};\n this._matrixArrays = {};\n this._matrices3x3 = {};\n this._matrices2x2 = {};\n this._vectors2Arrays = {};\n this._vectors3Arrays = {};\n this._vectors4Arrays = {};\n this._uniformBuffers = {};\n this._textureSamplers = {};\n this._storageBuffers = {};\n this._cachedWorldViewMatrix = new Matrix();\n this._cachedWorldViewProjectionMatrix = new Matrix();\n this._multiview = false;\n /**\n * @internal\n */\n this._materialHelperNeedsPreviousMatrices = false;\n this._shaderPath = shaderPath;\n this._options = Object.assign({ needAlphaBlending: false, needAlphaTesting: false, attributes: [\"position\", \"normal\", \"uv\"], uniforms: [\"worldViewProjection\"], uniformBuffers: [], samplers: [], externalTextures: [], samplerObjects: [], storageBuffers: [], defines: [], useClipPlane: false }, options);\n }\n /**\n * Gets the shader path used to define the shader code\n * It can be modified to trigger a new compilation\n */\n get shaderPath() {\n return this._shaderPath;\n }\n /**\n * Sets the shader path used to define the shader code\n * It can be modified to trigger a new compilation\n */\n set shaderPath(shaderPath) {\n this._shaderPath = shaderPath;\n }\n /**\n * Gets the options used to compile the shader.\n * They can be modified to trigger a new compilation\n */\n get options() {\n return this._options;\n }\n /**\n * is multiview set to true?\n */\n get isMultiview() {\n return this._multiview;\n }\n /**\n * Gets the current class name of the material e.g. \"ShaderMaterial\"\n * Mainly use in serialization.\n * @returns the class name\n */\n getClassName() {\n return \"ShaderMaterial\";\n }\n /**\n * Specifies if the material will require alpha blending\n * @returns a boolean specifying if alpha blending is needed\n */\n needAlphaBlending() {\n return this.alpha < 1.0 || this._options.needAlphaBlending;\n }\n /**\n * Specifies if this material should be rendered in alpha test mode\n * @returns a boolean specifying if an alpha test is needed.\n */\n needAlphaTesting() {\n return this._options.needAlphaTesting;\n }\n _checkUniform(uniformName) {\n if (this._options.uniforms.indexOf(uniformName) === -1) {\n this._options.uniforms.push(uniformName);\n }\n }\n /**\n * Set a texture in the shader.\n * @param name Define the name of the uniform samplers as defined in the shader\n * @param texture Define the texture to bind to this sampler\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setTexture(name, texture) {\n if (this._options.samplers.indexOf(name) === -1) {\n this._options.samplers.push(name);\n }\n this._textures[name] = texture;\n return this;\n }\n /**\n * Set a texture array in the shader.\n * @param name Define the name of the uniform sampler array as defined in the shader\n * @param textures Define the list of textures to bind to this sampler\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setTextureArray(name, textures) {\n if (this._options.samplers.indexOf(name) === -1) {\n this._options.samplers.push(name);\n }\n this._checkUniform(name);\n this._textureArrays[name] = textures;\n return this;\n }\n /**\n * Set an internal texture in the shader.\n * @param name Define the name of the uniform samplers as defined in the shader\n * @param texture Define the texture to bind to this sampler\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setExternalTexture(name, texture) {\n if (this._options.externalTextures.indexOf(name) === -1) {\n this._options.externalTextures.push(name);\n }\n this._externalTextures[name] = texture;\n return this;\n }\n /**\n * Set a float in the shader.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setFloat(name, value) {\n this._checkUniform(name);\n this._floats[name] = value;\n return this;\n }\n /**\n * Set a int in the shader.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setInt(name, value) {\n this._checkUniform(name);\n this._ints[name] = value;\n return this;\n }\n /**\n * Set a unsigned int in the shader.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setUInt(name, value) {\n this._checkUniform(name);\n this._uints[name] = value;\n return this;\n }\n /**\n * Set an array of floats in the shader.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setFloats(name, value) {\n this._checkUniform(name);\n this._floatsArrays[name] = value;\n return this;\n }\n /**\n * Set a vec3 in the shader from a Color3.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setColor3(name, value) {\n this._checkUniform(name);\n this._colors3[name] = value;\n return this;\n }\n /**\n * Set a vec3 array in the shader from a Color3 array.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setColor3Array(name, value) {\n this._checkUniform(name);\n this._colors3Arrays[name] = value.reduce((arr, color) => {\n color.toArray(arr, arr.length);\n return arr;\n }, []);\n return this;\n }\n /**\n * Set a vec4 in the shader from a Color4.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setColor4(name, value) {\n this._checkUniform(name);\n this._colors4[name] = value;\n return this;\n }\n /**\n * Set a vec4 array in the shader from a Color4 array.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setColor4Array(name, value) {\n this._checkUniform(name);\n this._colors4Arrays[name] = value.reduce((arr, color) => {\n color.toArray(arr, arr.length);\n return arr;\n }, []);\n return this;\n }\n /**\n * Set a vec2 in the shader from a Vector2.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setVector2(name, value) {\n this._checkUniform(name);\n this._vectors2[name] = value;\n return this;\n }\n /**\n * Set a vec3 in the shader from a Vector3.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setVector3(name, value) {\n this._checkUniform(name);\n this._vectors3[name] = value;\n return this;\n }\n /**\n * Set a vec4 in the shader from a Vector4.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setVector4(name, value) {\n this._checkUniform(name);\n this._vectors4[name] = value;\n return this;\n }\n /**\n * Set a vec4 in the shader from a Quaternion.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setQuaternion(name, value) {\n this._checkUniform(name);\n this._quaternions[name] = value;\n return this;\n }\n /**\n * Set a vec4 array in the shader from a Quaternion array.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setQuaternionArray(name, value) {\n this._checkUniform(name);\n this._quaternionsArrays[name] = value.reduce((arr, quaternion) => {\n quaternion.toArray(arr, arr.length);\n return arr;\n }, []);\n return this;\n }\n /**\n * Set a mat4 in the shader from a Matrix.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setMatrix(name, value) {\n this._checkUniform(name);\n this._matrices[name] = value;\n return this;\n }\n /**\n * Set a float32Array in the shader from a matrix array.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setMatrices(name, value) {\n this._checkUniform(name);\n const float32Array = new Float32Array(value.length * 16);\n for (let index = 0; index < value.length; index++) {\n const matrix = value[index];\n matrix.copyToArray(float32Array, index * 16);\n }\n this._matrixArrays[name] = float32Array;\n return this;\n }\n /**\n * Set a mat3 in the shader from a Float32Array.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setMatrix3x3(name, value) {\n this._checkUniform(name);\n this._matrices3x3[name] = value;\n return this;\n }\n /**\n * Set a mat2 in the shader from a Float32Array.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setMatrix2x2(name, value) {\n this._checkUniform(name);\n this._matrices2x2[name] = value;\n return this;\n }\n /**\n * Set a vec2 array in the shader from a number array.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setArray2(name, value) {\n this._checkUniform(name);\n this._vectors2Arrays[name] = value;\n return this;\n }\n /**\n * Set a vec3 array in the shader from a number array.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setArray3(name, value) {\n this._checkUniform(name);\n this._vectors3Arrays[name] = value;\n return this;\n }\n /**\n * Set a vec4 array in the shader from a number array.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setArray4(name, value) {\n this._checkUniform(name);\n this._vectors4Arrays[name] = value;\n return this;\n }\n /**\n * Set a uniform buffer in the shader\n * @param name Define the name of the uniform as defined in the shader\n * @param buffer Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setUniformBuffer(name, buffer) {\n if (this._options.uniformBuffers.indexOf(name) === -1) {\n this._options.uniformBuffers.push(name);\n }\n this._uniformBuffers[name] = buffer;\n return this;\n }\n /**\n * Set a texture sampler in the shader\n * @param name Define the name of the uniform as defined in the shader\n * @param sampler Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setTextureSampler(name, sampler) {\n if (this._options.samplerObjects.indexOf(name) === -1) {\n this._options.samplerObjects.push(name);\n }\n this._textureSamplers[name] = sampler;\n return this;\n }\n /**\n * Set a storage buffer in the shader\n * @param name Define the name of the storage buffer as defined in the shader\n * @param buffer Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setStorageBuffer(name, buffer) {\n if (this._options.storageBuffers.indexOf(name) === -1) {\n this._options.storageBuffers.push(name);\n }\n this._storageBuffers[name] = buffer;\n return this;\n }\n /**\n * Adds, removes, or replaces the specified shader define and value.\n * * setDefine(\"MY_DEFINE\", true); // enables a boolean define\n * * setDefine(\"MY_DEFINE\", \"0.5\"); // adds \"#define MY_DEFINE 0.5\" to the shader (or sets and replaces the value of any existing define with that name)\n * * setDefine(\"MY_DEFINE\", false); // disables and removes the define\n * Note if the active defines do change, the shader will be recompiled and this can be expensive.\n * @param define the define name e.g., \"OUTPUT_TO_SRGB\" or \"#define OUTPUT_TO_SRGB\". If the define was passed into the constructor already, the version used should match that, and in either case, it should not include any appended value.\n * @param value either the value of the define (e.g. a numerical value) or for booleans, true if the define should be enabled or false if it should be disabled\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setDefine(define, value) {\n // First remove any existing define with this name.\n const defineName = define.trimEnd() + \" \";\n const existingDefineIdx = this.options.defines.findIndex((x) => x === define || x.startsWith(defineName));\n if (existingDefineIdx >= 0) {\n this.options.defines.splice(existingDefineIdx, 1);\n }\n // Then add the new define value. (If it's a boolean value and false, don't add it.)\n if (typeof value !== \"boolean\" || value) {\n this.options.defines.push(defineName + value);\n }\n return this;\n }\n /**\n * Specifies that the submesh is ready to be used\n * @param mesh defines the mesh to check\n * @param subMesh defines which submesh to check\n * @param useInstances specifies that instances should be used\n * @returns a boolean indicating that the submesh is ready or not\n */\n isReadyForSubMesh(mesh, subMesh, useInstances) {\n return this.isReady(mesh, useInstances, subMesh);\n }\n /**\n * Checks if the material is ready to render the requested mesh\n * @param mesh Define the mesh to render\n * @param useInstances Define whether or not the material is used with instances\n * @param subMesh defines which submesh to render\n * @returns true if ready, otherwise false\n */\n isReady(mesh, useInstances, subMesh) {\n var _a, _b, _c, _d;\n const storeEffectOnSubMeshes = subMesh && this._storeEffectOnSubMeshes;\n if (this.isFrozen) {\n if (storeEffectOnSubMeshes) {\n if (subMesh.effect && subMesh.effect._wasPreviouslyReady) {\n return true;\n }\n }\n else {\n const effect = this._drawWrapper.effect;\n if (effect && effect._wasPreviouslyReady && effect._wasPreviouslyUsingInstances === useInstances) {\n return true;\n }\n }\n }\n const scene = this.getScene();\n const engine = scene.getEngine();\n // Instances\n const defines = [];\n const attribs = [];\n const fallbacks = new EffectFallbacks();\n let shaderName = this._shaderPath, uniforms = this._options.uniforms, uniformBuffers = this._options.uniformBuffers, samplers = this._options.samplers;\n // global multiview\n if (engine.getCaps().multiview && scene.activeCamera && scene.activeCamera.outputRenderTarget && scene.activeCamera.outputRenderTarget.getViewCount() > 1) {\n this._multiview = true;\n defines.push(\"#define MULTIVIEW\");\n if (this._options.uniforms.indexOf(\"viewProjection\") !== -1 && this._options.uniforms.indexOf(\"viewProjectionR\") === -1) {\n this._options.uniforms.push(\"viewProjectionR\");\n }\n }\n for (let index = 0; index < this._options.defines.length; index++) {\n const defineToAdd = this._options.defines[index].indexOf(\"#define\") === 0 ? this._options.defines[index] : `#define ${this._options.defines[index]}`;\n defines.push(defineToAdd);\n }\n for (let index = 0; index < this._options.attributes.length; index++) {\n attribs.push(this._options.attributes[index]);\n }\n if (mesh && mesh.isVerticesDataPresent(VertexBuffer.ColorKind)) {\n attribs.push(VertexBuffer.ColorKind);\n defines.push(\"#define VERTEXCOLOR\");\n }\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n MaterialHelper.PushAttributesForInstances(attribs, this._materialHelperNeedsPreviousMatrices);\n if (mesh === null || mesh === void 0 ? void 0 : mesh.hasThinInstances) {\n defines.push(\"#define THIN_INSTANCES\");\n if (mesh && mesh.isVerticesDataPresent(VertexBuffer.ColorInstanceKind)) {\n attribs.push(VertexBuffer.ColorInstanceKind);\n defines.push(\"#define INSTANCESCOLOR\");\n }\n }\n }\n // Bones\n if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {\n attribs.push(VertexBuffer.MatricesIndicesKind);\n attribs.push(VertexBuffer.MatricesWeightsKind);\n if (mesh.numBoneInfluencers > 4) {\n attribs.push(VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(VertexBuffer.MatricesWeightsExtraKind);\n }\n const skeleton = mesh.skeleton;\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n fallbacks.addCPUSkinningFallback(0, mesh);\n if (skeleton.isUsingTextureForMatrices) {\n defines.push(\"#define BONETEXTURE\");\n if (this._options.uniforms.indexOf(\"boneTextureWidth\") === -1) {\n this._options.uniforms.push(\"boneTextureWidth\");\n }\n if (this._options.samplers.indexOf(\"boneSampler\") === -1) {\n this._options.samplers.push(\"boneSampler\");\n }\n }\n else {\n defines.push(\"#define BonesPerMesh \" + (skeleton.bones.length + 1));\n if (this._options.uniforms.indexOf(\"mBones\") === -1) {\n this._options.uniforms.push(\"mBones\");\n }\n }\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Morph\n let numInfluencers = 0;\n const manager = mesh ? mesh.morphTargetManager : null;\n if (manager) {\n const uv = manager.supportsUVs && defines.indexOf(\"#define UV1\") !== -1;\n const tangent = manager.supportsTangents && defines.indexOf(\"#define TANGENT\") !== -1;\n const normal = manager.supportsNormals && defines.indexOf(\"#define NORMAL\") !== -1;\n numInfluencers = manager.numInfluencers;\n if (uv) {\n defines.push(\"#define MORPHTARGETS_UV\");\n }\n if (tangent) {\n defines.push(\"#define MORPHTARGETS_TANGENT\");\n }\n if (normal) {\n defines.push(\"#define MORPHTARGETS_NORMAL\");\n }\n if (numInfluencers > 0) {\n defines.push(\"#define MORPHTARGETS\");\n }\n if (manager.isUsingTextureForTargets) {\n defines.push(\"#define MORPHTARGETS_TEXTURE\");\n if (this._options.uniforms.indexOf(\"morphTargetTextureIndices\") === -1) {\n this._options.uniforms.push(\"morphTargetTextureIndices\");\n }\n if (this._options.samplers.indexOf(\"morphTargets\") === -1) {\n this._options.samplers.push(\"morphTargets\");\n }\n }\n defines.push(\"#define NUM_MORPH_INFLUENCERS \" + numInfluencers);\n for (let index = 0; index < numInfluencers; index++) {\n attribs.push(VertexBuffer.PositionKind + index);\n if (normal) {\n attribs.push(VertexBuffer.NormalKind + index);\n }\n if (tangent) {\n attribs.push(VertexBuffer.TangentKind + index);\n }\n if (uv) {\n attribs.push(VertexBuffer.UVKind + \"_\" + index);\n }\n }\n if (numInfluencers > 0) {\n uniforms = uniforms.slice();\n uniforms.push(\"morphTargetInfluences\");\n uniforms.push(\"morphTargetTextureInfo\");\n uniforms.push(\"morphTargetTextureIndices\");\n }\n }\n else {\n defines.push(\"#define NUM_MORPH_INFLUENCERS 0\");\n }\n // Baked Vertex Animation\n if (mesh) {\n const bvaManager = mesh.bakedVertexAnimationManager;\n if (bvaManager && bvaManager.isEnabled) {\n defines.push(\"#define BAKED_VERTEX_ANIMATION_TEXTURE\");\n if (this._options.uniforms.indexOf(\"bakedVertexAnimationSettings\") === -1) {\n this._options.uniforms.push(\"bakedVertexAnimationSettings\");\n }\n if (this._options.uniforms.indexOf(\"bakedVertexAnimationTextureSizeInverted\") === -1) {\n this._options.uniforms.push(\"bakedVertexAnimationTextureSizeInverted\");\n }\n if (this._options.uniforms.indexOf(\"bakedVertexAnimationTime\") === -1) {\n this._options.uniforms.push(\"bakedVertexAnimationTime\");\n }\n if (this._options.samplers.indexOf(\"bakedVertexAnimationTexture\") === -1) {\n this._options.samplers.push(\"bakedVertexAnimationTexture\");\n }\n }\n MaterialHelper.PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines);\n }\n // Textures\n for (const name in this._textures) {\n if (!this._textures[name].isReady()) {\n return false;\n }\n }\n // Alpha test\n if (mesh && this._shouldTurnAlphaTestOn(mesh)) {\n defines.push(\"#define ALPHATEST\");\n }\n // Clip planes\n if (this._options.useClipPlane !== false) {\n addClipPlaneUniforms(uniforms);\n prepareStringDefinesForClipPlanes(this, scene, defines);\n }\n if (this.customShaderNameResolve) {\n uniforms = uniforms.slice();\n uniformBuffers = uniformBuffers.slice();\n samplers = samplers.slice();\n shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines, attribs);\n }\n const drawWrapper = storeEffectOnSubMeshes ? subMesh._getDrawWrapper() : this._drawWrapper;\n const previousEffect = (_a = drawWrapper === null || drawWrapper === void 0 ? void 0 : drawWrapper.effect) !== null && _a !== void 0 ? _a : null;\n const previousDefines = (_b = drawWrapper === null || drawWrapper === void 0 ? void 0 : drawWrapper.defines) !== null && _b !== void 0 ? _b : null;\n const join = defines.join(\"\\n\");\n let effect = previousEffect;\n if (previousDefines !== join) {\n effect = engine.createEffect(shaderName, {\n attributes: attribs,\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: join,\n fallbacks: fallbacks,\n onCompiled: this.onCompiled,\n onError: this.onError,\n indexParameters: { maxSimultaneousMorphTargets: numInfluencers },\n shaderLanguage: this._options.shaderLanguage,\n }, engine);\n if (storeEffectOnSubMeshes) {\n subMesh.setEffect(effect, join, this._materialContext);\n }\n else if (drawWrapper) {\n drawWrapper.setEffect(effect, join);\n }\n if (this._onEffectCreatedObservable) {\n onCreatedEffectParameters.effect = effect;\n onCreatedEffectParameters.subMesh = (_c = subMesh !== null && subMesh !== void 0 ? subMesh : mesh === null || mesh === void 0 ? void 0 : mesh.subMeshes[0]) !== null && _c !== void 0 ? _c : null;\n this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters);\n }\n }\n effect._wasPreviouslyUsingInstances = !!useInstances;\n if ((_d = !(effect === null || effect === void 0 ? void 0 : effect.isReady())) !== null && _d !== void 0 ? _d : true) {\n return false;\n }\n if (previousEffect !== effect) {\n scene.resetCachedMaterial();\n }\n effect._wasPreviouslyReady = true;\n return true;\n }\n /**\n * Binds the world matrix to the material\n * @param world defines the world transformation matrix\n * @param effectOverride - If provided, use this effect instead of internal effect\n */\n bindOnlyWorldMatrix(world, effectOverride) {\n const scene = this.getScene();\n const effect = effectOverride !== null && effectOverride !== void 0 ? effectOverride : this.getEffect();\n if (!effect) {\n return;\n }\n if (this._options.uniforms.indexOf(\"world\") !== -1) {\n effect.setMatrix(\"world\", world);\n }\n if (this._options.uniforms.indexOf(\"worldView\") !== -1) {\n world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);\n effect.setMatrix(\"worldView\", this._cachedWorldViewMatrix);\n }\n if (this._options.uniforms.indexOf(\"worldViewProjection\") !== -1) {\n world.multiplyToRef(scene.getTransformMatrix(), this._cachedWorldViewProjectionMatrix);\n effect.setMatrix(\"worldViewProjection\", this._cachedWorldViewProjectionMatrix);\n }\n }\n /**\n * Binds the submesh to this material by preparing the effect and shader to draw\n * @param world defines the world transformation matrix\n * @param mesh defines the mesh containing the submesh\n * @param subMesh defines the submesh to bind the material to\n */\n bindForSubMesh(world, mesh, subMesh) {\n var _a;\n this.bind(world, mesh, (_a = subMesh._drawWrapperOverride) === null || _a === void 0 ? void 0 : _a.effect, subMesh);\n }\n /**\n * Binds the material to the mesh\n * @param world defines the world transformation matrix\n * @param mesh defines the mesh to bind the material to\n * @param effectOverride - If provided, use this effect instead of internal effect\n * @param subMesh defines the submesh to bind the material to\n */\n bind(world, mesh, effectOverride, subMesh) {\n var _a;\n // Std values\n const storeEffectOnSubMeshes = subMesh && this._storeEffectOnSubMeshes;\n const effect = effectOverride !== null && effectOverride !== void 0 ? effectOverride : (storeEffectOnSubMeshes ? subMesh.effect : this.getEffect());\n if (!effect) {\n return;\n }\n this._activeEffect = effect;\n this.bindOnlyWorldMatrix(world, effectOverride);\n const uniformBuffers = this._options.uniformBuffers;\n let useSceneUBO = false;\n if (effect && uniformBuffers && uniformBuffers.length > 0 && this.getScene().getEngine().supportsUniformBuffers) {\n for (let i = 0; i < uniformBuffers.length; ++i) {\n const bufferName = uniformBuffers[i];\n switch (bufferName) {\n case \"Mesh\":\n if (mesh) {\n mesh.getMeshUniformBuffer().bindToEffect(effect, \"Mesh\");\n mesh.transferToEffect(world);\n }\n break;\n case \"Scene\":\n MaterialHelper.BindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());\n this.getScene().finalizeSceneUbo();\n useSceneUBO = true;\n break;\n }\n }\n }\n const mustRebind = mesh && storeEffectOnSubMeshes ? this._mustRebind(this.getScene(), effect, mesh.visibility) : this.getScene().getCachedMaterial() !== this;\n if (effect && mustRebind) {\n if (!useSceneUBO && this._options.uniforms.indexOf(\"view\") !== -1) {\n effect.setMatrix(\"view\", this.getScene().getViewMatrix());\n }\n if (!useSceneUBO && this._options.uniforms.indexOf(\"projection\") !== -1) {\n effect.setMatrix(\"projection\", this.getScene().getProjectionMatrix());\n }\n if (!useSceneUBO && this._options.uniforms.indexOf(\"viewProjection\") !== -1) {\n effect.setMatrix(\"viewProjection\", this.getScene().getTransformMatrix());\n if (this._multiview) {\n effect.setMatrix(\"viewProjectionR\", this.getScene()._transformMatrixR);\n }\n }\n if (this.getScene().activeCamera && this._options.uniforms.indexOf(\"cameraPosition\") !== -1) {\n effect.setVector3(\"cameraPosition\", this.getScene().activeCamera.globalPosition);\n }\n // Bones\n MaterialHelper.BindBonesParameters(mesh, effect);\n // Clip plane\n bindClipPlane(effect, this, this.getScene());\n let name;\n // Texture\n for (name in this._textures) {\n effect.setTexture(name, this._textures[name]);\n }\n // Texture arrays\n for (name in this._textureArrays) {\n effect.setTextureArray(name, this._textureArrays[name]);\n }\n // External texture\n for (name in this._externalTextures) {\n effect.setExternalTexture(name, this._externalTextures[name]);\n }\n // Int\n for (name in this._ints) {\n effect.setInt(name, this._ints[name]);\n }\n // UInt\n for (name in this._uints) {\n effect.setUInt(name, this._uints[name]);\n }\n // Float\n for (name in this._floats) {\n effect.setFloat(name, this._floats[name]);\n }\n // Floats\n for (name in this._floatsArrays) {\n effect.setArray(name, this._floatsArrays[name]);\n }\n // Color3\n for (name in this._colors3) {\n effect.setColor3(name, this._colors3[name]);\n }\n // Color3Array\n for (name in this._colors3Arrays) {\n effect.setArray3(name, this._colors3Arrays[name]);\n }\n // Color4\n for (name in this._colors4) {\n const color = this._colors4[name];\n effect.setFloat4(name, color.r, color.g, color.b, color.a);\n }\n // Color4Array\n for (name in this._colors4Arrays) {\n effect.setArray4(name, this._colors4Arrays[name]);\n }\n // Vector2\n for (name in this._vectors2) {\n effect.setVector2(name, this._vectors2[name]);\n }\n // Vector3\n for (name in this._vectors3) {\n effect.setVector3(name, this._vectors3[name]);\n }\n // Vector4\n for (name in this._vectors4) {\n effect.setVector4(name, this._vectors4[name]);\n }\n // Quaternion\n for (name in this._quaternions) {\n effect.setQuaternion(name, this._quaternions[name]);\n }\n // Matrix\n for (name in this._matrices) {\n effect.setMatrix(name, this._matrices[name]);\n }\n // MatrixArray\n for (name in this._matrixArrays) {\n effect.setMatrices(name, this._matrixArrays[name]);\n }\n // Matrix 3x3\n for (name in this._matrices3x3) {\n effect.setMatrix3x3(name, this._matrices3x3[name]);\n }\n // Matrix 2x2\n for (name in this._matrices2x2) {\n effect.setMatrix2x2(name, this._matrices2x2[name]);\n }\n // Vector2Array\n for (name in this._vectors2Arrays) {\n effect.setArray2(name, this._vectors2Arrays[name]);\n }\n // Vector3Array\n for (name in this._vectors3Arrays) {\n effect.setArray3(name, this._vectors3Arrays[name]);\n }\n // Vector4Array\n for (name in this._vectors4Arrays) {\n effect.setArray4(name, this._vectors4Arrays[name]);\n }\n // QuaternionArray\n for (name in this._quaternionsArrays) {\n effect.setArray4(name, this._quaternionsArrays[name]);\n }\n // Uniform buffers\n for (name in this._uniformBuffers) {\n const buffer = this._uniformBuffers[name].getBuffer();\n if (buffer) {\n effect.bindUniformBuffer(buffer, name);\n }\n }\n // Samplers\n for (name in this._textureSamplers) {\n effect.setTextureSampler(name, this._textureSamplers[name]);\n }\n // Storage buffers\n for (name in this._storageBuffers) {\n effect.setStorageBuffer(name, this._storageBuffers[name]);\n }\n }\n if (effect && mesh && (mustRebind || !this.isFrozen)) {\n // Morph targets\n const manager = mesh.morphTargetManager;\n if (manager && manager.numInfluencers > 0) {\n MaterialHelper.BindMorphTargetParameters(mesh, effect);\n }\n const bvaManager = mesh.bakedVertexAnimationManager;\n if (bvaManager && bvaManager.isEnabled) {\n (_a = mesh.bakedVertexAnimationManager) === null || _a === void 0 ? void 0 : _a.bind(effect, !!effect._wasPreviouslyUsingInstances);\n }\n }\n this._afterBind(mesh, effect);\n }\n /**\n * Gets the active textures from the material\n * @returns an array of textures\n */\n getActiveTextures() {\n const activeTextures = super.getActiveTextures();\n for (const name in this._textures) {\n activeTextures.push(this._textures[name]);\n }\n for (const name in this._textureArrays) {\n const array = this._textureArrays[name];\n for (let index = 0; index < array.length; index++) {\n activeTextures.push(array[index]);\n }\n }\n return activeTextures;\n }\n /**\n * Specifies if the material uses a texture\n * @param texture defines the texture to check against the material\n * @returns a boolean specifying if the material uses the texture\n */\n hasTexture(texture) {\n if (super.hasTexture(texture)) {\n return true;\n }\n for (const name in this._textures) {\n if (this._textures[name] === texture) {\n return true;\n }\n }\n for (const name in this._textureArrays) {\n const array = this._textureArrays[name];\n for (let index = 0; index < array.length; index++) {\n if (array[index] === texture) {\n return true;\n }\n }\n }\n return false;\n }\n /**\n * Makes a duplicate of the material, and gives it a new name\n * @param name defines the new name for the duplicated material\n * @returns the cloned material\n */\n clone(name) {\n const result = SerializationHelper.Clone(() => new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options, this._storeEffectOnSubMeshes), this);\n result.name = name;\n result.id = name;\n // Shader code path\n if (typeof result._shaderPath === \"object\") {\n result._shaderPath = Object.assign({}, result._shaderPath);\n }\n // Options\n this._options = Object.assign({}, this._options);\n Object.keys(this._options).forEach((propName) => {\n const propValue = this._options[propName];\n if (Array.isArray(propValue)) {\n this._options[propName] = propValue.slice(0);\n }\n });\n // Stencil\n this.stencil.copyTo(result.stencil);\n // Texture\n for (const key in this._textures) {\n result.setTexture(key, this._textures[key]);\n }\n // TextureArray\n for (const key in this._textureArrays) {\n result.setTextureArray(key, this._textureArrays[key]);\n }\n // External texture\n for (const key in this._externalTextures) {\n result.setExternalTexture(key, this._externalTextures[key]);\n }\n // Int\n for (const key in this._ints) {\n result.setInt(key, this._ints[key]);\n }\n // UInt\n for (const key in this._uints) {\n result.setUInt(key, this._uints[key]);\n }\n // Float\n for (const key in this._floats) {\n result.setFloat(key, this._floats[key]);\n }\n // Floats\n for (const key in this._floatsArrays) {\n result.setFloats(key, this._floatsArrays[key]);\n }\n // Color3\n for (const key in this._colors3) {\n result.setColor3(key, this._colors3[key]);\n }\n // Color3Array\n for (const key in this._colors3Arrays) {\n result._colors3Arrays[key] = this._colors3Arrays[key];\n }\n // Color4\n for (const key in this._colors4) {\n result.setColor4(key, this._colors4[key]);\n }\n // Color4Array\n for (const key in this._colors4Arrays) {\n result._colors4Arrays[key] = this._colors4Arrays[key];\n }\n // Vector2\n for (const key in this._vectors2) {\n result.setVector2(key, this._vectors2[key]);\n }\n // Vector3\n for (const key in this._vectors3) {\n result.setVector3(key, this._vectors3[key]);\n }\n // Vector4\n for (const key in this._vectors4) {\n result.setVector4(key, this._vectors4[key]);\n }\n // Quaternion\n for (const key in this._quaternions) {\n result.setQuaternion(key, this._quaternions[key]);\n }\n // QuaternionArray\n for (const key in this._quaternionsArrays) {\n result._quaternionsArrays[key] = this._quaternionsArrays[key];\n }\n // Matrix\n for (const key in this._matrices) {\n result.setMatrix(key, this._matrices[key]);\n }\n // MatrixArray\n for (const key in this._matrixArrays) {\n result._matrixArrays[key] = this._matrixArrays[key].slice();\n }\n // Matrix 3x3\n for (const key in this._matrices3x3) {\n result.setMatrix3x3(key, this._matrices3x3[key]);\n }\n // Matrix 2x2\n for (const key in this._matrices2x2) {\n result.setMatrix2x2(key, this._matrices2x2[key]);\n }\n // Vector2Array\n for (const key in this._vectors2Arrays) {\n result.setArray2(key, this._vectors2Arrays[key]);\n }\n // Vector3Array\n for (const key in this._vectors3Arrays) {\n result.setArray3(key, this._vectors3Arrays[key]);\n }\n // Vector4Array\n for (const key in this._vectors4Arrays) {\n result.setArray4(key, this._vectors4Arrays[key]);\n }\n // Uniform buffers\n for (const key in this._uniformBuffers) {\n result.setUniformBuffer(key, this._uniformBuffers[key]);\n }\n // Samplers\n for (const key in this._textureSamplers) {\n result.setTextureSampler(key, this._textureSamplers[key]);\n }\n // Storag buffers\n for (const key in this._storageBuffers) {\n result.setStorageBuffer(key, this._storageBuffers[key]);\n }\n return result;\n }\n /**\n * Disposes the material\n * @param forceDisposeEffect specifies if effects should be forcefully disposed\n * @param forceDisposeTextures specifies if textures should be forcefully disposed\n * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh\n */\n dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {\n if (forceDisposeTextures) {\n let name;\n for (name in this._textures) {\n this._textures[name].dispose();\n }\n for (name in this._textureArrays) {\n const array = this._textureArrays[name];\n for (let index = 0; index < array.length; index++) {\n array[index].dispose();\n }\n }\n }\n this._textures = {};\n super.dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh);\n }\n /**\n * Serializes this material in a JSON representation\n * @returns the serialized material object\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this);\n serializationObject.customType = \"BABYLON.ShaderMaterial\";\n serializationObject.uniqueId = this.uniqueId;\n serializationObject.options = this._options;\n serializationObject.shaderPath = this._shaderPath;\n serializationObject.storeEffectOnSubMeshes = this._storeEffectOnSubMeshes;\n let name;\n // Stencil\n serializationObject.stencil = this.stencil.serialize();\n // Texture\n serializationObject.textures = {};\n for (name in this._textures) {\n serializationObject.textures[name] = this._textures[name].serialize();\n }\n // Texture arrays\n serializationObject.textureArrays = {};\n for (name in this._textureArrays) {\n serializationObject.textureArrays[name] = [];\n const array = this._textureArrays[name];\n for (let index = 0; index < array.length; index++) {\n serializationObject.textureArrays[name].push(array[index].serialize());\n }\n }\n // Int\n serializationObject.ints = {};\n for (name in this._ints) {\n serializationObject.ints[name] = this._ints[name];\n }\n // UInt\n serializationObject.uints = {};\n for (name in this._uints) {\n serializationObject.uints[name] = this._uints[name];\n }\n // Float\n serializationObject.floats = {};\n for (name in this._floats) {\n serializationObject.floats[name] = this._floats[name];\n }\n // Floats\n serializationObject.FloatArrays = {};\n for (name in this._floatsArrays) {\n serializationObject.FloatArrays[name] = this._floatsArrays[name];\n }\n // Color3\n serializationObject.colors3 = {};\n for (name in this._colors3) {\n serializationObject.colors3[name] = this._colors3[name].asArray();\n }\n // Color3 array\n serializationObject.colors3Arrays = {};\n for (name in this._colors3Arrays) {\n serializationObject.colors3Arrays[name] = this._colors3Arrays[name];\n }\n // Color4\n serializationObject.colors4 = {};\n for (name in this._colors4) {\n serializationObject.colors4[name] = this._colors4[name].asArray();\n }\n // Color4 array\n serializationObject.colors4Arrays = {};\n for (name in this._colors4Arrays) {\n serializationObject.colors4Arrays[name] = this._colors4Arrays[name];\n }\n // Vector2\n serializationObject.vectors2 = {};\n for (name in this._vectors2) {\n serializationObject.vectors2[name] = this._vectors2[name].asArray();\n }\n // Vector3\n serializationObject.vectors3 = {};\n for (name in this._vectors3) {\n serializationObject.vectors3[name] = this._vectors3[name].asArray();\n }\n // Vector4\n serializationObject.vectors4 = {};\n for (name in this._vectors4) {\n serializationObject.vectors4[name] = this._vectors4[name].asArray();\n }\n // Quaternion\n serializationObject.quaternions = {};\n for (name in this._quaternions) {\n serializationObject.quaternions[name] = this._quaternions[name].asArray();\n }\n // Matrix\n serializationObject.matrices = {};\n for (name in this._matrices) {\n serializationObject.matrices[name] = this._matrices[name].asArray();\n }\n // MatrixArray\n serializationObject.matrixArray = {};\n for (name in this._matrixArrays) {\n serializationObject.matrixArray[name] = this._matrixArrays[name];\n }\n // Matrix 3x3\n serializationObject.matrices3x3 = {};\n for (name in this._matrices3x3) {\n serializationObject.matrices3x3[name] = this._matrices3x3[name];\n }\n // Matrix 2x2\n serializationObject.matrices2x2 = {};\n for (name in this._matrices2x2) {\n serializationObject.matrices2x2[name] = this._matrices2x2[name];\n }\n // Vector2Array\n serializationObject.vectors2Arrays = {};\n for (name in this._vectors2Arrays) {\n serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];\n }\n // Vector3Array\n serializationObject.vectors3Arrays = {};\n for (name in this._vectors3Arrays) {\n serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];\n }\n // Vector4Array\n serializationObject.vectors4Arrays = {};\n for (name in this._vectors4Arrays) {\n serializationObject.vectors4Arrays[name] = this._vectors4Arrays[name];\n }\n // QuaternionArray\n serializationObject.quaternionsArrays = {};\n for (name in this._quaternionsArrays) {\n serializationObject.quaternionsArrays[name] = this._quaternionsArrays[name];\n }\n return serializationObject;\n }\n /**\n * Creates a shader material from parsed shader material data\n * @param source defines the JSON representation of the material\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @returns a new material\n */\n static Parse(source, scene, rootUrl) {\n const material = SerializationHelper.Parse(() => new ShaderMaterial(source.name, scene, source.shaderPath, source.options, source.storeEffectOnSubMeshes), source, scene, rootUrl);\n let name;\n // Stencil\n if (source.stencil) {\n material.stencil.parse(source.stencil, scene, rootUrl);\n }\n // Texture\n for (name in source.textures) {\n material.setTexture(name, Texture.Parse(source.textures[name], scene, rootUrl));\n }\n // Texture arrays\n for (name in source.textureArrays) {\n const array = source.textureArrays[name];\n const textureArray = new Array();\n for (let index = 0; index < array.length; index++) {\n textureArray.push(Texture.Parse(array[index], scene, rootUrl));\n }\n material.setTextureArray(name, textureArray);\n }\n // Int\n for (name in source.ints) {\n material.setInt(name, source.ints[name]);\n }\n // UInt\n for (name in source.uints) {\n material.setUInt(name, source.uints[name]);\n }\n // Float\n for (name in source.floats) {\n material.setFloat(name, source.floats[name]);\n }\n // Floats\n for (name in source.floatsArrays) {\n material.setFloats(name, source.floatsArrays[name]);\n }\n // Color3\n for (name in source.colors3) {\n material.setColor3(name, Color3.FromArray(source.colors3[name]));\n }\n // Color3 arrays\n for (name in source.colors3Arrays) {\n const colors = source.colors3Arrays[name]\n .reduce((arr, num, i) => {\n if (i % 3 === 0) {\n arr.push([num]);\n }\n else {\n arr[arr.length - 1].push(num);\n }\n return arr;\n }, [])\n .map((color) => Color3.FromArray(color));\n material.setColor3Array(name, colors);\n }\n // Color4\n for (name in source.colors4) {\n material.setColor4(name, Color4.FromArray(source.colors4[name]));\n }\n // Color4 arrays\n for (name in source.colors4Arrays) {\n const colors = source.colors4Arrays[name]\n .reduce((arr, num, i) => {\n if (i % 4 === 0) {\n arr.push([num]);\n }\n else {\n arr[arr.length - 1].push(num);\n }\n return arr;\n }, [])\n .map((color) => Color4.FromArray(color));\n material.setColor4Array(name, colors);\n }\n // Vector2\n for (name in source.vectors2) {\n material.setVector2(name, Vector2.FromArray(source.vectors2[name]));\n }\n // Vector3\n for (name in source.vectors3) {\n material.setVector3(name, Vector3.FromArray(source.vectors3[name]));\n }\n // Vector4\n for (name in source.vectors4) {\n material.setVector4(name, Vector4.FromArray(source.vectors4[name]));\n }\n // Quaternion\n for (name in source.quaternions) {\n material.setQuaternion(name, Quaternion.FromArray(source.quaternions[name]));\n }\n // Matrix\n for (name in source.matrices) {\n material.setMatrix(name, Matrix.FromArray(source.matrices[name]));\n }\n // MatrixArray\n for (name in source.matrixArray) {\n material._matrixArrays[name] = new Float32Array(source.matrixArray[name]);\n }\n // Matrix 3x3\n for (name in source.matrices3x3) {\n material.setMatrix3x3(name, source.matrices3x3[name]);\n }\n // Matrix 2x2\n for (name in source.matrices2x2) {\n material.setMatrix2x2(name, source.matrices2x2[name]);\n }\n // Vector2Array\n for (name in source.vectors2Arrays) {\n material.setArray2(name, source.vectors2Arrays[name]);\n }\n // Vector3Array\n for (name in source.vectors3Arrays) {\n material.setArray3(name, source.vectors3Arrays[name]);\n }\n // Vector4Array\n for (name in source.vectors4Arrays) {\n material.setArray4(name, source.vectors4Arrays[name]);\n }\n // QuaternionArray\n for (name in source.quaternionsArrays) {\n material.setArray4(name, source.quaternionsArrays[name]);\n }\n return material;\n }\n /**\n * Creates a new ShaderMaterial from a snippet saved in a remote file\n * @param name defines the name of the ShaderMaterial to create (can be null or empty to use the one from the json data)\n * @param url defines the url to load from\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @returns a promise that will resolve to the new ShaderMaterial\n */\n static ParseFromFileAsync(name, url, scene, rootUrl = \"\") {\n return new Promise((resolve, reject) => {\n const request = new WebRequest();\n request.addEventListener(\"readystatechange\", () => {\n if (request.readyState == 4) {\n if (request.status == 200) {\n const serializationObject = JSON.parse(request.responseText);\n const output = this.Parse(serializationObject, scene || EngineStore.LastCreatedScene, rootUrl);\n if (name) {\n output.name = name;\n }\n resolve(output);\n }\n else {\n reject(\"Unable to load the ShaderMaterial\");\n }\n }\n });\n request.open(\"GET\", url);\n request.send();\n });\n }\n /**\n * Creates a ShaderMaterial from a snippet saved by the Inspector\n * @param snippetId defines the snippet to load\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @returns a promise that will resolve to the new ShaderMaterial\n */\n static ParseFromSnippetAsync(snippetId, scene, rootUrl = \"\") {\n return new Promise((resolve, reject) => {\n const request = new WebRequest();\n request.addEventListener(\"readystatechange\", () => {\n if (request.readyState == 4) {\n if (request.status == 200) {\n const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload);\n const serializationObject = JSON.parse(snippet.shaderMaterial);\n const output = this.Parse(serializationObject, scene || EngineStore.LastCreatedScene, rootUrl);\n output.snippetId = snippetId;\n resolve(output);\n }\n else {\n reject(\"Unable to load the snippet \" + snippetId);\n }\n }\n });\n request.open(\"GET\", this.SnippetUrl + \"/\" + snippetId.replace(/#/g, \"/\"));\n request.send();\n });\n }\n}\n/** Define the Url to load snippets */\nShaderMaterial.SnippetUrl = `https://snippet.babylonjs.com`;\n/**\n * Creates a ShaderMaterial from a snippet saved by the Inspector\n * @deprecated Please use ParseFromSnippetAsync instead\n * @param snippetId defines the snippet to load\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @returns a promise that will resolve to the new ShaderMaterial\n */\nShaderMaterial.CreateFromSnippetAsync = ShaderMaterial.ParseFromSnippetAsync;\nRegisterClass(\"BABYLON.ShaderMaterial\", ShaderMaterial);\n//# sourceMappingURL=shaderMaterial.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/clipPlaneFragmentDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneFragment.js\";\nconst name = \"colorPixelShader\";\nconst shader = `#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\n#define VERTEXCOLOR\nvarying vec4 vColor;\r#else\nuniform vec4 color;\r#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\ngl_FragColor=vColor;\r#else\ngl_FragColor=color;\r#endif\n#define CUSTOM_FRAGMENT_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const colorPixelShader = { name, shader };\n//# sourceMappingURL=color.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/bonesDeclaration.js\";\nimport \"./ShadersInclude/bakedVertexAnimationDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneVertexDeclaration.js\";\nimport \"./ShadersInclude/instancesDeclaration.js\";\nimport \"./ShadersInclude/instancesVertex.js\";\nimport \"./ShadersInclude/bonesVertex.js\";\nimport \"./ShadersInclude/bakedVertexAnimation.js\";\nimport \"./ShadersInclude/clipPlaneVertex.js\";\nimport \"./ShadersInclude/vertexColorMixing.js\";\nconst name = \"colorVertexShader\";\nconst shader = `attribute vec3 position;\r#ifdef VERTEXCOLOR\nattribute vec4 color;\r#endif\n#include\n#include\n#include\n#include\nuniform mat4 viewProjection;\r#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\r#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\r#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);\r#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {\rgl_Position=viewProjection*worldPos;\r} else {\rgl_Position=viewProjectionR*worldPos;\r}\r#else\ngl_Position=viewProjection*worldPos;\r#endif\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const colorVertexShader = { name, shader };\n//# sourceMappingURL=color.vertex.js.map","import { Color3, Color4 } from \"../Maths/math.color.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { InstancedMesh } from \"../Meshes/instancedMesh.js\";\nimport { Material } from \"../Materials/material.js\";\nimport { ShaderMaterial } from \"../Materials/shaderMaterial.js\";\nimport \"../Shaders/color.fragment.js\";\nimport \"../Shaders/color.vertex.js\";\nMesh._LinesMeshParser = (parsedMesh, scene) => {\n return LinesMesh.Parse(parsedMesh, scene);\n};\n/**\n * Line mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param\n */\nexport class LinesMesh extends Mesh {\n _isShaderMaterial(shader) {\n return shader.getClassName() === \"ShaderMaterial\";\n }\n /**\n * Creates a new LinesMesh\n * @param name defines the name\n * @param scene defines the hosting scene\n * @param parent defines the parent mesh if any\n * @param source defines the optional source LinesMesh used to clone data from\n * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.\n * When false, achieved by calling a clone(), also passing False.\n * This will make creation of children, recursive.\n * @param useVertexColor defines if this LinesMesh supports vertex color\n * @param useVertexAlpha defines if this LinesMesh supports vertex alpha\n * @param material material to use to draw the line. If not provided, will create a new one\n */\n constructor(name, scene = null, parent = null, source = null, doNotCloneChildren, \n /**\n * If vertex color should be applied to the mesh\n */\n useVertexColor, \n /**\n * If vertex alpha should be applied to the mesh\n */\n useVertexAlpha, material) {\n super(name, scene, parent, source, doNotCloneChildren);\n this.useVertexColor = useVertexColor;\n this.useVertexAlpha = useVertexAlpha;\n /**\n * Color of the line (Default: White)\n */\n this.color = new Color3(1, 1, 1);\n /**\n * Alpha of the line (Default: 1)\n */\n this.alpha = 1;\n if (source) {\n this.color = source.color.clone();\n this.alpha = source.alpha;\n this.useVertexColor = source.useVertexColor;\n this.useVertexAlpha = source.useVertexAlpha;\n }\n this.intersectionThreshold = 0.1;\n const defines = [];\n const options = {\n attributes: [VertexBuffer.PositionKind],\n uniforms: [\"world\", \"viewProjection\"],\n needAlphaBlending: true,\n defines: defines,\n useClipPlane: null,\n };\n if (useVertexAlpha === false) {\n options.needAlphaBlending = false;\n }\n else {\n options.defines.push(\"#define VERTEXALPHA\");\n }\n if (!useVertexColor) {\n options.uniforms.push(\"color\");\n this._color4 = new Color4();\n }\n else {\n options.defines.push(\"#define VERTEXCOLOR\");\n options.attributes.push(VertexBuffer.ColorKind);\n }\n if (material) {\n this.material = material;\n }\n else {\n this.material = new ShaderMaterial(\"colorShader\", this.getScene(), \"color\", options, false);\n this.material.doNotSerialize = true;\n }\n }\n isReady() {\n if (!this._lineMaterial.isReady(this, !!this._userInstancedBuffersStorage)) {\n return false;\n }\n return super.isReady();\n }\n /**\n * Returns the string \"LineMesh\"\n */\n getClassName() {\n return \"LinesMesh\";\n }\n /**\n * @internal\n */\n get material() {\n return this._lineMaterial;\n }\n /**\n * @internal\n */\n set material(value) {\n this._lineMaterial = value;\n this._lineMaterial.fillMode = Material.LineListDrawMode;\n }\n /**\n * @internal\n */\n get checkCollisions() {\n return false;\n }\n set checkCollisions(value) {\n // Just ignore it\n }\n /**\n * @internal\n */\n _bind(_subMesh, colorEffect) {\n if (!this._geometry) {\n return this;\n }\n // VBOs\n const indexToBind = this.isUnIndexed ? null : this._geometry.getIndexBuffer();\n if (!this._userInstancedBuffersStorage) {\n this._geometry._bind(colorEffect, indexToBind);\n }\n else {\n this._geometry._bind(colorEffect, indexToBind, this._userInstancedBuffersStorage.vertexBuffers, this._userInstancedBuffersStorage.vertexArrayObjects);\n }\n // Color\n if (!this.useVertexColor && this._isShaderMaterial(this._lineMaterial)) {\n const { r, g, b } = this.color;\n this._color4.set(r, g, b, this.alpha);\n this._lineMaterial.setColor4(\"color\", this._color4);\n }\n return this;\n }\n /**\n * @internal\n */\n _draw(subMesh, fillMode, instancesCount) {\n if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {\n return this;\n }\n const engine = this.getScene().getEngine();\n // Draw order\n if (this._unIndexed) {\n engine.drawArraysType(Material.LineListDrawMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);\n }\n else {\n engine.drawElementsType(Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);\n }\n return this;\n }\n /**\n * Disposes of the line mesh\n * @param doNotRecurse If children should be disposed\n * @param disposeMaterialAndTextures This parameter is not used by the LineMesh class\n * @param doNotDisposeMaterial If the material should not be disposed (default: false, meaning the material is disposed)\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n dispose(doNotRecurse, disposeMaterialAndTextures = false, doNotDisposeMaterial) {\n if (!doNotDisposeMaterial) {\n this._lineMaterial.dispose(false, false, true);\n }\n super.dispose(doNotRecurse);\n }\n /**\n * Returns a new LineMesh object cloned from the current one.\n * @param name\n * @param newParent\n * @param doNotCloneChildren\n */\n clone(name, newParent = null, doNotCloneChildren) {\n return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);\n }\n /**\n * Creates a new InstancedLinesMesh object from the mesh model.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/copies/instances\n * @param name defines the name of the new instance\n * @returns a new InstancedLinesMesh\n */\n createInstance(name) {\n const instance = new InstancedLinesMesh(name, this);\n if (this.instancedBuffers) {\n instance.instancedBuffers = {};\n for (const key in this.instancedBuffers) {\n instance.instancedBuffers[key] = this.instancedBuffers[key];\n }\n }\n return instance;\n }\n /**\n * Serializes this ground mesh\n * @param serializationObject object to write serialization to\n */\n serialize(serializationObject) {\n super.serialize(serializationObject);\n serializationObject.color = this.color.asArray();\n serializationObject.alpha = this.alpha;\n }\n /**\n * Parses a serialized ground mesh\n * @param parsedMesh the serialized mesh\n * @param scene the scene to create the ground mesh in\n * @returns the created ground mesh\n */\n static Parse(parsedMesh, scene) {\n const result = new LinesMesh(parsedMesh.name, scene);\n result.color = Color3.FromArray(parsedMesh.color);\n result.alpha = parsedMesh.alpha;\n return result;\n }\n}\n/**\n * Creates an instance based on a source LinesMesh\n */\nexport class InstancedLinesMesh extends InstancedMesh {\n constructor(name, source) {\n super(name, source);\n this.intersectionThreshold = source.intersectionThreshold;\n }\n /**\n * Returns the string \"InstancedLinesMesh\".\n */\n getClassName() {\n return \"InstancedLinesMesh\";\n }\n}\n//# sourceMappingURL=linesMesh.js.map","/* eslint-disable @typescript-eslint/naming-convention */\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { _CreationDataStorage, Mesh } from \"../mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { LinesMesh } from \"../../Meshes/linesMesh.js\";\nimport { VertexBuffer } from \"../../Buffers/buffer.js\";\nimport { Logger } from \"../../Misc/logger.js\";\n/**\n * Creates the VertexData of the LineSystem\n * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty\n * - lines an array of lines, each line being an array of successive Vector3\n * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point\n * @param options.lines\n * @param options.colors\n * @returns the VertexData of the LineSystem\n */\nexport function CreateLineSystemVertexData(options) {\n const indices = [];\n const positions = [];\n const lines = options.lines;\n const colors = options.colors;\n const vertexColors = [];\n let idx = 0;\n for (let l = 0; l < lines.length; l++) {\n const points = lines[l];\n for (let index = 0; index < points.length; index++) {\n positions.push(points[index].x, points[index].y, points[index].z);\n if (colors) {\n const color = colors[l];\n vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);\n }\n if (index > 0) {\n indices.push(idx - 1);\n indices.push(idx);\n }\n idx++;\n }\n }\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n if (colors) {\n vertexData.colors = vertexColors;\n }\n return vertexData;\n}\n/**\n * Create the VertexData for a DashedLines\n * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty\n * - points an array successive Vector3\n * - dashSize the size of the dashes relative to the dash number, optional, default 3\n * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1\n * - dashNb the intended total number of dashes, optional, default 200\n * @param options.points\n * @param options.dashSize\n * @param options.gapSize\n * @param options.dashNb\n * @returns the VertexData for the DashedLines\n */\nexport function CreateDashedLinesVertexData(options) {\n const dashSize = options.dashSize || 3;\n const gapSize = options.gapSize || 1;\n const dashNb = options.dashNb || 200;\n const points = options.points;\n const positions = new Array();\n const indices = new Array();\n const curvect = Vector3.Zero();\n let lg = 0;\n let nb = 0;\n let shft = 0;\n let dashshft = 0;\n let curshft = 0;\n let idx = 0;\n let i = 0;\n for (i = 0; i < points.length - 1; i++) {\n points[i + 1].subtractToRef(points[i], curvect);\n lg += curvect.length();\n }\n shft = lg / dashNb;\n dashshft = (dashSize * shft) / (dashSize + gapSize);\n for (i = 0; i < points.length - 1; i++) {\n points[i + 1].subtractToRef(points[i], curvect);\n nb = Math.floor(curvect.length() / shft);\n curvect.normalize();\n for (let j = 0; j < nb; j++) {\n curshft = shft * j;\n positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);\n positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);\n indices.push(idx, idx + 1);\n idx += 2;\n }\n }\n // Result\n const vertexData = new VertexData();\n vertexData.positions = positions;\n vertexData.indices = indices;\n return vertexData;\n}\n/**\n * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh\n * * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter\n * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function\n * * The parameter `lines` is an array of lines, each line being an array of successive Vector3\n * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter\n * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point\n * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)\n * * The optional parameter `material` is the material to use to draw the lines if provided. If not, a default material will be created\n * * Updating a simple Line mesh, you just need to update every line in the `lines` array : https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#lines-and-dashedlines\n * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#line-system\n * @param name defines the name of the new line system\n * @param options defines the options used to create the line system\n * @param options.lines\n * @param options.updatable\n * @param options.instance\n * @param options.colors\n * @param options.useVertexAlpha\n * @param options.material\n * @param scene defines the hosting scene\n * @returns a new line system mesh\n */\nexport function CreateLineSystem(name, options, scene) {\n const instance = options.instance;\n const lines = options.lines;\n const colors = options.colors;\n if (instance) {\n // lines update\n const positions = instance.getVerticesData(VertexBuffer.PositionKind);\n let vertexColor;\n let lineColors;\n if (colors) {\n vertexColor = instance.getVerticesData(VertexBuffer.ColorKind);\n }\n let i = 0;\n let c = 0;\n for (let l = 0; l < lines.length; l++) {\n const points = lines[l];\n for (let p = 0; p < points.length; p++) {\n positions[i] = points[p].x;\n positions[i + 1] = points[p].y;\n positions[i + 2] = points[p].z;\n if (colors && vertexColor) {\n lineColors = colors[l];\n vertexColor[c] = lineColors[p].r;\n vertexColor[c + 1] = lineColors[p].g;\n vertexColor[c + 2] = lineColors[p].b;\n vertexColor[c + 3] = lineColors[p].a;\n c += 4;\n }\n i += 3;\n }\n }\n instance.updateVerticesData(VertexBuffer.PositionKind, positions, false, false);\n if (colors && vertexColor) {\n instance.updateVerticesData(VertexBuffer.ColorKind, vertexColor, false, false);\n }\n return instance;\n }\n // line system creation\n const useVertexColor = colors ? true : false;\n const lineSystem = new LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha, options.material);\n const vertexData = CreateLineSystemVertexData(options);\n vertexData.applyToMesh(lineSystem, options.updatable);\n return lineSystem;\n}\n/**\n * Creates a line mesh\n * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter\n * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function\n * * The parameter `points` is an array successive Vector3\n * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#lines-and-dashedlines\n * * The optional parameter `colors` is an array of successive Color4, one per line point\n * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)\n * * The optional parameter `material` is the material to use to draw the lines if provided. If not, a default material will be created\n * * When updating an instance, remember that only point positions can change, not the number of points\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#lines\n * @param name defines the name of the new line system\n * @param options defines the options used to create the line system\n * @param options.points\n * @param options.updatable\n * @param options.instance\n * @param options.colors\n * @param options.useVertexAlpha\n * @param options.material\n * @param scene defines the hosting scene\n * @returns a new line mesh\n */\nexport function CreateLines(name, options, scene = null) {\n const colors = options.colors ? [options.colors] : null;\n const lines = CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha, material: options.material }, scene);\n return lines;\n}\n/**\n * Creates a dashed line mesh\n * * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter\n * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function\n * * The parameter `points` is an array successive Vector3\n * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)\n * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)\n * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)\n * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#lines-and-dashedlines\n * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)\n * * The optional parameter `material` is the material to use to draw the lines if provided. If not, a default material will be created\n * * When updating an instance, remember that only point positions can change, not the number of points\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.points\n * @param options.dashSize\n * @param options.gapSize\n * @param options.dashNb\n * @param options.updatable\n * @param options.instance\n * @param options.useVertexAlpha\n * @param options.material\n * @param scene defines the hosting scene\n * @returns the dashed line mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#dashed-lines\n */\nexport function CreateDashedLines(name, options, scene = null) {\n const points = options.points;\n const instance = options.instance;\n const gapSize = options.gapSize || 1;\n const dashSize = options.dashSize || 3;\n if (instance) {\n // dashed lines update\n const positionFunction = (positions) => {\n const curvect = Vector3.Zero();\n const nbSeg = positions.length / 6;\n let lg = 0;\n let nb = 0;\n let shft = 0;\n let dashshft = 0;\n let curshft = 0;\n let p = 0;\n let i = 0;\n let j = 0;\n for (i = 0; i < points.length - 1; i++) {\n points[i + 1].subtractToRef(points[i], curvect);\n lg += curvect.length();\n }\n shft = lg / nbSeg;\n const dashSize = instance._creationDataStorage.dashSize;\n const gapSize = instance._creationDataStorage.gapSize;\n dashshft = (dashSize * shft) / (dashSize + gapSize);\n for (i = 0; i < points.length - 1; i++) {\n points[i + 1].subtractToRef(points[i], curvect);\n nb = Math.floor(curvect.length() / shft);\n curvect.normalize();\n j = 0;\n while (j < nb && p < positions.length) {\n curshft = shft * j;\n positions[p] = points[i].x + curshft * curvect.x;\n positions[p + 1] = points[i].y + curshft * curvect.y;\n positions[p + 2] = points[i].z + curshft * curvect.z;\n positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;\n positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;\n positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;\n p += 6;\n j++;\n }\n }\n while (p < positions.length) {\n positions[p] = points[i].x;\n positions[p + 1] = points[i].y;\n positions[p + 2] = points[i].z;\n p += 3;\n }\n };\n if (options.dashNb || options.dashSize || options.gapSize || options.useVertexAlpha || options.material) {\n Logger.Warn(\"You have used an option other than points with the instance option. Please be aware that these other options will be ignored.\");\n }\n instance.updateMeshPositions(positionFunction, false);\n return instance;\n }\n // dashed lines creation\n const dashedLines = new LinesMesh(name, scene, null, undefined, undefined, undefined, options.useVertexAlpha, options.material);\n const vertexData = CreateDashedLinesVertexData(options);\n vertexData.applyToMesh(dashedLines, options.updatable);\n dashedLines._creationDataStorage = new _CreationDataStorage();\n dashedLines._creationDataStorage.dashSize = dashSize;\n dashedLines._creationDataStorage.gapSize = gapSize;\n return dashedLines;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use the functions directly from the module\n */\nexport const LinesBuilder = {\n CreateDashedLines,\n CreateLineSystem,\n CreateLines,\n};\nVertexData.CreateLineSystem = CreateLineSystemVertexData;\nVertexData.CreateDashedLines = CreateDashedLinesVertexData;\nMesh.CreateLines = (name, points, scene = null, updatable = false, instance = null) => {\n const options = {\n points,\n updatable,\n instance,\n };\n return CreateLines(name, options, scene);\n};\nMesh.CreateDashedLines = (name, points, dashSize, gapSize, dashNb, scene = null, updatable, instance) => {\n const options = {\n points,\n dashSize,\n gapSize,\n dashNb,\n updatable,\n instance,\n };\n return CreateDashedLines(name, options, scene);\n};\n//# sourceMappingURL=linesBuilder.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { Vector3, Vector2 } from \"../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { VertexData } from \"../Meshes/mesh.vertexData.js\";\nimport { Path2 } from \"../Maths/math.path.js\";\nimport { Epsilon } from \"../Maths/math.constants.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n/**\n * Vector2 wth index property\n */\nclass IndexedVector2 extends Vector2 {\n constructor(original, \n /** Index of the vector2 */\n index) {\n super(original.x, original.y);\n this.index = index;\n }\n}\n/**\n * Defines points to create a polygon\n */\nclass PolygonPoints {\n constructor() {\n this.elements = new Array();\n }\n add(originalPoints) {\n const result = new Array();\n originalPoints.forEach((point) => {\n const newPoint = new IndexedVector2(point, this.elements.length);\n result.push(newPoint);\n this.elements.push(newPoint);\n });\n return result;\n }\n computeBounds() {\n const lmin = new Vector2(this.elements[0].x, this.elements[0].y);\n const lmax = new Vector2(this.elements[0].x, this.elements[0].y);\n this.elements.forEach((point) => {\n // x\n if (point.x < lmin.x) {\n lmin.x = point.x;\n }\n else if (point.x > lmax.x) {\n lmax.x = point.x;\n }\n // y\n if (point.y < lmin.y) {\n lmin.y = point.y;\n }\n else if (point.y > lmax.y) {\n lmax.y = point.y;\n }\n });\n return {\n min: lmin,\n max: lmax,\n width: lmax.x - lmin.x,\n height: lmax.y - lmin.y,\n };\n }\n}\n/**\n * Polygon\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#non-regular-polygon\n */\nexport class Polygon {\n /**\n * Creates a rectangle\n * @param xmin bottom X coord\n * @param ymin bottom Y coord\n * @param xmax top X coord\n * @param ymax top Y coord\n * @returns points that make the resulting rectangle\n */\n static Rectangle(xmin, ymin, xmax, ymax) {\n return [new Vector2(xmin, ymin), new Vector2(xmax, ymin), new Vector2(xmax, ymax), new Vector2(xmin, ymax)];\n }\n /**\n * Creates a circle\n * @param radius radius of circle\n * @param cx scale in x\n * @param cy scale in y\n * @param numberOfSides number of sides that make up the circle\n * @returns points that make the resulting circle\n */\n static Circle(radius, cx = 0, cy = 0, numberOfSides = 32) {\n const result = new Array();\n let angle = 0;\n const increment = (Math.PI * 2) / numberOfSides;\n for (let i = 0; i < numberOfSides; i++) {\n result.push(new Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));\n angle -= increment;\n }\n return result;\n }\n /**\n * Creates a polygon from input string\n * @param input Input polygon data\n * @returns the parsed points\n */\n static Parse(input) {\n const floats = input\n .split(/[^-+eE.\\d]+/)\n .map(parseFloat)\n .filter((val) => !isNaN(val));\n let i;\n const result = [];\n for (i = 0; i < (floats.length & 0x7ffffffe); i += 2) {\n result.push(new Vector2(floats[i], floats[i + 1]));\n }\n return result;\n }\n /**\n * Starts building a polygon from x and y coordinates\n * @param x x coordinate\n * @param y y coordinate\n * @returns the started path2\n */\n static StartingAt(x, y) {\n return Path2.StartingAt(x, y);\n }\n}\n/**\n * Builds a polygon\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param/polyMeshBuilder\n */\nexport class PolygonMeshBuilder {\n _addToepoint(points) {\n for (const p of points) {\n this._epoints.push(p.x, p.y);\n }\n }\n /**\n * Creates a PolygonMeshBuilder\n * @param name name of the builder\n * @param contours Path of the polygon\n * @param scene scene to add to when creating the mesh\n * @param earcutInjection can be used to inject your own earcut reference\n */\n constructor(name, contours, scene, earcutInjection = earcut) {\n this._points = new PolygonPoints();\n this._outlinepoints = new PolygonPoints();\n this._holes = new Array();\n this._epoints = new Array();\n this._eholes = new Array();\n this.bjsEarcut = earcutInjection;\n this._name = name;\n this._scene = scene || EngineStore.LastCreatedScene;\n let points;\n if (contours instanceof Path2) {\n points = contours.getPoints();\n }\n else {\n points = contours;\n }\n this._addToepoint(points);\n this._points.add(points);\n this._outlinepoints.add(points);\n if (typeof this.bjsEarcut === \"undefined\") {\n Logger.Warn(\"Earcut was not found, the polygon will not be built.\");\n }\n }\n /**\n * Adds a hole within the polygon\n * @param hole Array of points defining the hole\n * @returns this\n */\n addHole(hole) {\n this._points.add(hole);\n const holepoints = new PolygonPoints();\n holepoints.add(hole);\n this._holes.push(holepoints);\n this._eholes.push(this._epoints.length / 2);\n this._addToepoint(hole);\n return this;\n }\n /**\n * Creates the polygon\n * @param updatable If the mesh should be updatable\n * @param depth The depth of the mesh created\n * @param smoothingThreshold Dot product threshold for smoothed normals\n * @returns the created mesh\n */\n build(updatable = false, depth = 0, smoothingThreshold = 2) {\n const result = new Mesh(this._name, this._scene);\n const vertexData = this.buildVertexData(depth, smoothingThreshold);\n result.setVerticesData(VertexBuffer.PositionKind, vertexData.positions, updatable);\n result.setVerticesData(VertexBuffer.NormalKind, vertexData.normals, updatable);\n result.setVerticesData(VertexBuffer.UVKind, vertexData.uvs, updatable);\n result.setIndices(vertexData.indices);\n return result;\n }\n /**\n * Creates the polygon\n * @param depth The depth of the mesh created\n * @param smoothingThreshold Dot product threshold for smoothed normals\n * @returns the created VertexData\n */\n buildVertexData(depth = 0, smoothingThreshold = 2) {\n const result = new VertexData();\n const normals = new Array();\n const positions = new Array();\n const uvs = new Array();\n const bounds = this._points.computeBounds();\n this._points.elements.forEach((p) => {\n normals.push(0, 1.0, 0);\n positions.push(p.x, 0, p.y);\n uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);\n });\n const indices = new Array();\n const res = this.bjsEarcut(this._epoints, this._eholes, 2);\n for (let i = 0; i < res.length; i++) {\n indices.push(res[i]);\n }\n if (depth > 0) {\n const positionscount = positions.length / 3; //get the current pointcount\n this._points.elements.forEach((p) => {\n //add the elements at the depth\n normals.push(0, -1.0, 0);\n positions.push(p.x, -depth, p.y);\n uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);\n });\n const totalCount = indices.length;\n for (let i = 0; i < totalCount; i += 3) {\n const i0 = indices[i + 0];\n const i1 = indices[i + 1];\n const i2 = indices[i + 2];\n indices.push(i2 + positionscount);\n indices.push(i1 + positionscount);\n indices.push(i0 + positionscount);\n }\n //Add the sides\n this._addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false, smoothingThreshold);\n this._holes.forEach((hole) => {\n this._addSide(positions, normals, uvs, indices, bounds, hole, depth, true, smoothingThreshold);\n });\n }\n result.indices = indices;\n result.positions = positions;\n result.normals = normals;\n result.uvs = uvs;\n return result;\n }\n /**\n * Adds a side to the polygon\n * @param positions points that make the polygon\n * @param normals normals of the polygon\n * @param uvs uvs of the polygon\n * @param indices indices of the polygon\n * @param bounds bounds of the polygon\n * @param points points of the polygon\n * @param depth depth of the polygon\n * @param flip flip of the polygon\n * @param smoothingThreshold\n */\n _addSide(positions, normals, uvs, indices, bounds, points, depth, flip, smoothingThreshold) {\n let startIndex = positions.length / 3;\n let ulength = 0;\n for (let i = 0; i < points.elements.length; i++) {\n const p = points.elements[i];\n const p1 = points.elements[(i + 1) % points.elements.length];\n positions.push(p.x, 0, p.y);\n positions.push(p.x, -depth, p.y);\n positions.push(p1.x, 0, p1.y);\n positions.push(p1.x, -depth, p1.y);\n const p0 = points.elements[(i + points.elements.length - 1) % points.elements.length];\n const p2 = points.elements[(i + 2) % points.elements.length];\n let vc = new Vector3(-(p1.y - p.y), 0, p1.x - p.x);\n let vp = new Vector3(-(p.y - p0.y), 0, p.x - p0.x);\n let vn = new Vector3(-(p2.y - p1.y), 0, p2.x - p1.x);\n if (!flip) {\n vc = vc.scale(-1);\n vp = vp.scale(-1);\n vn = vn.scale(-1);\n }\n const vc_norm = vc.normalizeToNew();\n let vp_norm = vp.normalizeToNew();\n let vn_norm = vn.normalizeToNew();\n const dotp = Vector3.Dot(vp_norm, vc_norm);\n if (dotp > smoothingThreshold) {\n if (dotp < Epsilon - 1) {\n vp_norm = new Vector3(p.x, 0, p.y).subtract(new Vector3(p1.x, 0, p1.y)).normalize();\n }\n else {\n // cheap average weighed by side length\n vp_norm = vp.add(vc).normalize();\n }\n }\n else {\n vp_norm = vc_norm;\n }\n const dotn = Vector3.Dot(vn, vc);\n if (dotn > smoothingThreshold) {\n if (dotn < Epsilon - 1) {\n // back to back\n vn_norm = new Vector3(p1.x, 0, p1.y).subtract(new Vector3(p.x, 0, p.y)).normalize();\n }\n else {\n // cheap average weighed by side length\n vn_norm = vn.add(vc).normalize();\n }\n }\n else {\n vn_norm = vc_norm;\n }\n uvs.push(ulength / bounds.width, 0);\n uvs.push(ulength / bounds.width, 1);\n ulength += vc.length();\n uvs.push(ulength / bounds.width, 0);\n uvs.push(ulength / bounds.width, 1);\n normals.push(vp_norm.x, vp_norm.y, vp_norm.z);\n normals.push(vp_norm.x, vp_norm.y, vp_norm.z);\n normals.push(vn_norm.x, vn_norm.y, vn_norm.z);\n normals.push(vn_norm.x, vn_norm.y, vn_norm.z);\n if (!flip) {\n indices.push(startIndex);\n indices.push(startIndex + 1);\n indices.push(startIndex + 2);\n indices.push(startIndex + 1);\n indices.push(startIndex + 3);\n indices.push(startIndex + 2);\n }\n else {\n indices.push(startIndex);\n indices.push(startIndex + 2);\n indices.push(startIndex + 1);\n indices.push(startIndex + 1);\n indices.push(startIndex + 2);\n indices.push(startIndex + 3);\n }\n startIndex += 4;\n }\n }\n}\n//# sourceMappingURL=polygonMesh.js.map","import { Vector2, Vector4 } from \"../../Maths/math.vector.js\";\nimport { Color4 } from \"../../Maths/math.color.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { PolygonMeshBuilder } from \"../polygonMesh.js\";\nimport { VertexBuffer } from \"../../Buffers/buffer.js\";\nimport { EngineStore } from \"../../Engines/engineStore.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n/**\n * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()\n * All parameters are provided by CreatePolygon as needed\n * @param polygon a mesh built from polygonTriangulation.build()\n * @param sideOrientation takes the values Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively\n * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively\n * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param wrp a boolean, default false, when true and fUVs used texture is wrapped around all sides, when false texture is applied side\n * @returns the VertexData of the Polygon\n */\nexport function CreatePolygonVertexData(polygon, sideOrientation, fUV, fColors, frontUVs, backUVs, wrp) {\n const faceUV = fUV || new Array(3);\n const faceColors = fColors;\n const colors = [];\n const wrap = wrp || false;\n // default face colors and UV if undefined\n for (let f = 0; f < 3; f++) {\n if (faceUV[f] === undefined) {\n faceUV[f] = new Vector4(0, 0, 1, 1);\n }\n if (faceColors && faceColors[f] === undefined) {\n faceColors[f] = new Color4(1, 1, 1, 1);\n }\n }\n const positions = polygon.getVerticesData(VertexBuffer.PositionKind);\n const normals = polygon.getVerticesData(VertexBuffer.NormalKind);\n const uvs = polygon.getVerticesData(VertexBuffer.UVKind);\n const indices = polygon.getIndices();\n const startIndex = positions.length / 9;\n let disp = 0;\n let distX = 0;\n let distZ = 0;\n let dist = 0;\n let totalLen = 0;\n const cumulate = [0];\n if (wrap) {\n for (let idx = startIndex; idx < positions.length / 3; idx += 4) {\n distX = positions[3 * (idx + 2)] - positions[3 * idx];\n distZ = positions[3 * (idx + 2) + 2] - positions[3 * idx + 2];\n dist = Math.sqrt(distX * distX + distZ * distZ);\n totalLen += dist;\n cumulate.push(totalLen);\n }\n }\n // set face colours and textures\n let idx = 0;\n let face = 0;\n for (let index = 0; index < normals.length; index += 3) {\n //Edge Face no. 1\n if (Math.abs(normals[index + 1]) < 0.001) {\n face = 1;\n }\n //Top Face no. 0\n if (Math.abs(normals[index + 1] - 1) < 0.001) {\n face = 0;\n }\n //Bottom Face no. 2\n if (Math.abs(normals[index + 1] + 1) < 0.001) {\n face = 2;\n }\n idx = index / 3;\n if (face === 1) {\n disp = idx - startIndex;\n if (disp % 4 < 1.5) {\n if (wrap) {\n uvs[2 * idx] = faceUV[face].x + ((faceUV[face].z - faceUV[face].x) * cumulate[Math.floor(disp / 4)]) / totalLen;\n }\n else {\n uvs[2 * idx] = faceUV[face].x;\n }\n }\n else {\n if (wrap) {\n uvs[2 * idx] = faceUV[face].x + ((faceUV[face].z - faceUV[face].x) * cumulate[Math.floor(disp / 4) + 1]) / totalLen;\n }\n else {\n uvs[2 * idx] = faceUV[face].z;\n }\n }\n if (disp % 2 === 0) {\n uvs[2 * idx + 1] = CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - faceUV[face].w : faceUV[face].w;\n }\n else {\n uvs[2 * idx + 1] = CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - faceUV[face].y : faceUV[face].y;\n }\n }\n else {\n uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;\n uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;\n if (CompatibilityOptions.UseOpenGLOrientationForUV) {\n uvs[2 * idx + 1] = 1.0 - uvs[2 * idx + 1];\n }\n }\n if (faceColors) {\n colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);\n }\n }\n // sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);\n // Result\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n if (faceColors) {\n const totalColors = sideOrientation === VertexData.DOUBLESIDE ? colors.concat(colors) : colors;\n vertexData.colors = totalColors;\n }\n return vertexData;\n}\n/**\n * Creates a polygon mesh\n * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh\n * * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors\n * * You can set the mesh side orientation with the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4)\n * * Remember you can only change the shape positions, not their number when updating a polygon\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.shape\n * @param options.holes\n * @param options.depth\n * @param options.smoothingThreshold\n * @param options.faceUV\n * @param options.faceColors\n * @param options.updatable\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.wrap\n * @param scene defines the hosting scene\n * @param earcutInjection can be used to inject your own earcut reference\n * @returns the polygon mesh\n */\nexport function CreatePolygon(name, options, scene = null, earcutInjection = earcut) {\n options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n const shape = options.shape;\n const holes = options.holes || [];\n const depth = options.depth || 0;\n const smoothingThreshold = options.smoothingThreshold || 2;\n const contours = [];\n let hole = [];\n for (let i = 0; i < shape.length; i++) {\n contours[i] = new Vector2(shape[i].x, shape[i].z);\n }\n const epsilon = 0.00000001;\n if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {\n contours.pop();\n }\n const polygonTriangulation = new PolygonMeshBuilder(name, contours, scene || EngineStore.LastCreatedScene, earcutInjection);\n for (let hNb = 0; hNb < holes.length; hNb++) {\n hole = [];\n for (let hPoint = 0; hPoint < holes[hNb].length; hPoint++) {\n hole.push(new Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));\n }\n polygonTriangulation.addHole(hole);\n }\n //updatability is set during applyToMesh; setting to true in triangulation build produces errors\n const polygon = polygonTriangulation.build(false, depth, smoothingThreshold);\n polygon._originalBuilderSideOrientation = options.sideOrientation;\n const vertexData = CreatePolygonVertexData(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs, options.wrap);\n vertexData.applyToMesh(polygon, options.updatable);\n return polygon;\n}\n/**\n * Creates an extruded polygon mesh, with depth in the Y direction.\n * * You can set different colors and different images to the top, bottom and extruded side by using the parameters `faceColors` (an array of 3 Color3 elements) and `faceUV` (an array of 3 Vector4 elements)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/texturePerBoxFace\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.shape\n * @param options.holes\n * @param options.depth\n * @param options.faceUV\n * @param options.faceColors\n * @param options.updatable\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.wrap\n * @param scene defines the hosting scene\n * @param earcutInjection can be used to inject your own earcut reference\n * @returns the polygon mesh\n */\nexport function ExtrudePolygon(name, options, scene = null, earcutInjection = earcut) {\n return CreatePolygon(name, options, scene, earcutInjection);\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use the functions directly from the module\n */\nexport const PolygonBuilder = {\n ExtrudePolygon,\n CreatePolygon,\n};\nVertexData.CreatePolygon = CreatePolygonVertexData;\nMesh.CreatePolygon = (name, shape, scene, holes, updatable, sideOrientation, earcutInjection = earcut) => {\n const options = {\n shape: shape,\n holes: holes,\n updatable: updatable,\n sideOrientation: sideOrientation,\n };\n return CreatePolygon(name, options, scene, earcutInjection);\n};\nMesh.ExtrudePolygon = (name, shape, depth, scene, holes, updatable, sideOrientation, earcutInjection = earcut) => {\n const options = {\n shape: shape,\n holes: holes,\n depth: depth,\n updatable: updatable,\n sideOrientation: sideOrientation,\n };\n return ExtrudePolygon(name, options, scene, earcutInjection);\n};\n//# sourceMappingURL=polygonBuilder.js.map","import { Vector3, TmpVectors, Matrix } from \"../../Maths/math.vector.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { CreateRibbon } from \"./ribbonBuilder.js\";\nimport { Path3D } from \"../../Maths/math.path.js\";\n/**\n * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.\n * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.\n * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.\n * * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.\n * * The parameter `scale` (float, default 1) is the value to scale the shape.\n * * The parameter `closeShape` (boolean, default false) closes the shape when true, since v5.0.0.\n * * The parameter `closePath` (boolean, default false) closes the path when true and no caps, since v5.0.0.\n * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL\n * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#extruded-shape\n * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n * * The optional parameter `firstNormal` (Vector3) defines the direction of the first normal of the supplied path. Consider using this for any path that is straight, and particular for paths in the xy plane.\n * * The optional `adjustFrame` (boolean, default false) will cause the internally generated Path3D tangents, normals, and binormals to be adjusted so that a) they are always well-defined, and b) they do not reverse from one path point to the next. This prevents the extruded shape from being flipped and/or rotated with resulting mesh self-intersections. This is primarily useful for straight paths that can reverse direction.\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.shape\n * @param options.path\n * @param options.scale\n * @param options.rotation\n * @param options.closeShape\n * @param options.closePath\n * @param options.cap\n * @param options.updatable\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.instance\n * @param options.invertUV\n * @param options.firstNormal\n * @param options.adjustFrame\n * @param scene defines the hosting scene\n * @returns the extruded shape mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#extruded-shapes\n */\nexport function ExtrudeShape(name, options, scene = null) {\n const path = options.path;\n const shape = options.shape;\n const scale = options.scale || 1;\n const rotation = options.rotation || 0;\n const cap = options.cap === 0 ? 0 : options.cap || Mesh.NO_CAP;\n const updatable = options.updatable;\n const sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n const instance = options.instance || null;\n const invertUV = options.invertUV || false;\n const closeShape = options.closeShape || false;\n const closePath = options.closePath || false;\n return _ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, closePath, closeShape, cap, false, scene, updatable ? true : false, sideOrientation, instance, invertUV, options.frontUVs || null, options.backUVs || null, options.firstNormal || null, options.adjustFrame ? true : false);\n}\n/**\n * Creates an custom extruded shape mesh.\n * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.\n * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.\n * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.\n * * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the beginning of the path\n * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.\n * * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the beginning of the path\n * * It must returns a float value that will be the scale value applied to the shape on each path point\n * * The parameter `closeShape` (boolean, default false) closes the shape when true, since v5.0.0.\n * * The parameter `closePath` (boolean, default false) closes the path when true and no caps, since v5.0.0.\n * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray` - depreciated in favor of closeShape\n * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray` - depreciated in favor of closePath\n * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL\n * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#extruded-shape\n * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * * The optional parameter `firstNormal` (Vector3) defines the direction of the first normal of the supplied path. It should be supplied when the path is in the xy plane, and particularly if these sections are straight, because the underlying Path3D object will pick a normal in the xy plane that causes the extrusion to be collapsed into the plane. This should be used for any path that is straight.\n * * The optional `adjustFrame` (boolean, default false) will cause the internally generated Path3D tangents, normals, and binormals to be adjusted so that a) they are always well-defined, and b) they do not reverse from one path point to the next. This prevents the extruded shape from being flipped and/or rotated with resulting mesh self-intersections. This is primarily useful for straight paths that can reverse direction.\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.shape\n * @param options.path\n * @param options.scaleFunction\n * @param options.rotationFunction\n * @param options.ribbonCloseArray\n * @param options.ribbonClosePath\n * @param options.closeShape\n * @param options.closePath\n * @param options.cap\n * @param options.updatable\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.instance\n * @param options.invertUV\n * @param options.firstNormal\n * @param options.adjustFrame\n * @param scene defines the hosting scene\n * @returns the custom extruded shape mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#custom-extruded-shapes\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#extruded-shapes\n */\nexport function ExtrudeShapeCustom(name, options, scene = null) {\n const path = options.path;\n const shape = options.shape;\n const scaleFunction = options.scaleFunction ||\n (() => {\n return 1;\n });\n const rotationFunction = options.rotationFunction ||\n (() => {\n return 0;\n });\n const ribbonCloseArray = options.closePath || options.ribbonCloseArray || false;\n const ribbonClosePath = options.closeShape || options.ribbonClosePath || false;\n const cap = options.cap === 0 ? 0 : options.cap || Mesh.NO_CAP;\n const updatable = options.updatable;\n const firstNormal = options.firstNormal || null;\n const adjustFrame = options.adjustFrame || false;\n const sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n const instance = options.instance;\n const invertUV = options.invertUV || false;\n return _ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable ? true : false, sideOrientation, instance || null, invertUV, options.frontUVs || null, options.backUVs || null, firstNormal, adjustFrame);\n}\nfunction _ExtrudeShapeGeneric(name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs, firstNormal, adjustFrame) {\n // extrusion geometry\n const extrusionPathArray = (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom, adjustFrame) => {\n const tangents = path3D.getTangents();\n const normals = path3D.getNormals();\n const binormals = path3D.getBinormals();\n const distances = path3D.getDistances();\n if (adjustFrame) {\n /* fix tangents,normals, binormals */\n for (let i = 0; i < tangents.length; i++) {\n if (tangents[i].x == 0 && tangents[i].y == 0 && tangents[i].z == 0) {\n tangents[i].copyFrom(tangents[i - 1]);\n }\n if (normals[i].x == 0 && normals[i].y == 0 && normals[i].z == 0) {\n normals[i].copyFrom(normals[i - 1]);\n }\n if (binormals[i].x == 0 && binormals[i].y == 0 && binormals[i].z == 0) {\n binormals[i].copyFrom(binormals[i - 1]);\n }\n if (i > 0) {\n let v = tangents[i - 1];\n if (Vector3.Dot(v, tangents[i]) < 0) {\n tangents[i].scaleInPlace(-1);\n }\n v = normals[i - 1];\n if (Vector3.Dot(v, normals[i]) < 0) {\n normals[i].scaleInPlace(-1);\n }\n v = binormals[i - 1];\n if (Vector3.Dot(v, binormals[i]) < 0) {\n binormals[i].scaleInPlace(-1);\n }\n }\n }\n }\n let angle = 0;\n const returnScale = () => {\n return scale !== null ? scale : 1;\n };\n const returnRotation = () => {\n return rotation !== null ? rotation : 0;\n };\n const rotate = custom && rotateFunction ? rotateFunction : returnRotation;\n const scl = custom && scaleFunction ? scaleFunction : returnScale;\n let index = cap === Mesh.NO_CAP || cap === Mesh.CAP_END ? 0 : 2;\n const rotationMatrix = TmpVectors.Matrix[0];\n for (let i = 0; i < curve.length; i++) {\n const shapePath = new Array();\n const angleStep = rotate(i, distances[i]);\n const scaleRatio = scl(i, distances[i]);\n Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);\n for (let p = 0; p < shape.length; p++) {\n const planed = tangents[i].scale(shape[p].z).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y));\n const rotated = Vector3.Zero();\n Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);\n rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);\n shapePath[p] = rotated;\n }\n shapePaths[index] = shapePath;\n angle += angleStep;\n index++;\n }\n // cap\n const capPath = (shapePath) => {\n const pointCap = Array();\n const barycenter = Vector3.Zero();\n let i;\n for (i = 0; i < shapePath.length; i++) {\n barycenter.addInPlace(shapePath[i]);\n }\n barycenter.scaleInPlace(1.0 / shapePath.length);\n for (i = 0; i < shapePath.length; i++) {\n pointCap.push(barycenter);\n }\n return pointCap;\n };\n switch (cap) {\n case Mesh.NO_CAP:\n break;\n case Mesh.CAP_START:\n shapePaths[0] = capPath(shapePaths[2]);\n shapePaths[1] = shapePaths[2];\n break;\n case Mesh.CAP_END:\n shapePaths[index] = shapePaths[index - 1];\n shapePaths[index + 1] = capPath(shapePaths[index - 1]);\n break;\n case Mesh.CAP_ALL:\n shapePaths[0] = capPath(shapePaths[2]);\n shapePaths[1] = shapePaths[2];\n shapePaths[index] = shapePaths[index - 1];\n shapePaths[index + 1] = capPath(shapePaths[index - 1]);\n break;\n default:\n break;\n }\n return shapePaths;\n };\n let path3D;\n let pathArray;\n if (instance) {\n // instance update\n const storage = instance._creationDataStorage;\n path3D = firstNormal ? storage.path3D.update(curve, firstNormal) : storage.path3D.update(curve);\n pathArray = extrusionPathArray(shape, curve, storage.path3D, storage.pathArray, scale, rotation, scaleFunction, rotateFunction, storage.cap, custom, adjustFrame);\n instance = CreateRibbon(\"\", { pathArray, closeArray: false, closePath: false, offset: 0, updatable: false, sideOrientation: 0, instance }, scene || undefined);\n return instance;\n }\n // extruded shape creation\n path3D = firstNormal ? new Path3D(curve, firstNormal) : new Path3D(curve);\n const newShapePaths = new Array();\n cap = cap < 0 || cap > 3 ? 0 : cap;\n pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom, adjustFrame);\n const extrudedGeneric = CreateRibbon(name, {\n pathArray: pathArray,\n closeArray: rbCA,\n closePath: rbCP,\n updatable: updtbl,\n sideOrientation: side,\n invertUV: invertUV,\n frontUVs: frontUVs || undefined,\n backUVs: backUVs || undefined,\n }, scene);\n extrudedGeneric._creationDataStorage.pathArray = pathArray;\n extrudedGeneric._creationDataStorage.path3D = path3D;\n extrudedGeneric._creationDataStorage.cap = cap;\n return extrudedGeneric;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated please use the functions directly from the module\n */\nexport const ShapeBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ExtrudeShape,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ExtrudeShapeCustom,\n};\nMesh.ExtrudeShape = (name, shape, path, scale, rotation, cap, scene = null, updatable, sideOrientation, instance) => {\n const options = {\n shape: shape,\n path: path,\n scale: scale,\n rotation: rotation,\n cap: cap === 0 ? 0 : cap || Mesh.NO_CAP,\n sideOrientation: sideOrientation,\n instance: instance,\n updatable: updatable,\n };\n return ExtrudeShape(name, options, scene);\n};\nMesh.ExtrudeShapeCustom = (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) => {\n const options = {\n shape: shape,\n path: path,\n scaleFunction: scaleFunction,\n rotationFunction: rotationFunction,\n ribbonCloseArray: ribbonCloseArray,\n ribbonClosePath: ribbonClosePath,\n cap: cap === 0 ? 0 : cap || Mesh.NO_CAP,\n sideOrientation: sideOrientation,\n instance: instance,\n updatable: updatable,\n };\n return ExtrudeShapeCustom(name, options, scene);\n};\n//# sourceMappingURL=shapeBuilder.js.map","import { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { CreateRibbon } from \"./ribbonBuilder.js\";\n/**\n * Creates lathe mesh.\n * The lathe is a shape with a symmetry axis : a 2D model shape is rotated around this axis to design the lathe\n * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero\n * * The parameter `radius` (positive float, default 1) is the radius value of the lathe\n * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe\n * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides\n * * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape\n * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter \"arc\"\n * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.shape\n * @param options.radius\n * @param options.tessellation\n * @param options.clip\n * @param options.arc\n * @param options.closed\n * @param options.updatable\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.cap\n * @param options.invertUV\n * @param scene defines the hosting scene\n * @returns the lathe mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#lathe\n */\nexport function CreateLathe(name, options, scene = null) {\n const arc = options.arc ? (options.arc <= 0 || options.arc > 1 ? 1.0 : options.arc) : 1.0;\n const closed = options.closed === undefined ? true : options.closed;\n const shape = options.shape;\n const radius = options.radius || 1;\n const tessellation = options.tessellation || 64;\n const clip = options.clip || 0;\n const updatable = options.updatable;\n const sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n const cap = options.cap || Mesh.NO_CAP;\n const pi2 = Math.PI * 2;\n const paths = new Array();\n const invertUV = options.invertUV || false;\n let i = 0;\n let p = 0;\n const step = (pi2 / tessellation) * arc;\n let rotated;\n let path;\n for (i = 0; i <= tessellation - clip; i++) {\n path = [];\n if (cap == Mesh.CAP_START || cap == Mesh.CAP_ALL) {\n path.push(new Vector3(0, shape[0].y, 0));\n path.push(new Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));\n }\n for (p = 0; p < shape.length; p++) {\n rotated = new Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);\n path.push(rotated);\n }\n if (cap == Mesh.CAP_END || cap == Mesh.CAP_ALL) {\n path.push(new Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius));\n path.push(new Vector3(0, shape[shape.length - 1].y, 0));\n }\n paths.push(path);\n }\n // lathe ribbon\n const lathe = CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);\n return lathe;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use the function direction from the module\n */\nexport const LatheBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateLathe,\n};\nMesh.CreateLathe = (name, shape, radius, tessellation, scene, updatable, sideOrientation) => {\n const options = {\n shape: shape,\n radius: radius,\n tessellation: tessellation,\n sideOrientation: sideOrientation,\n updatable: updatable,\n };\n return CreateLathe(name, options, scene);\n};\n//# sourceMappingURL=latheBuilder.js.map","import { Vector3, TmpVectors, Matrix } from \"../../Maths/math.vector.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { CreateRibbon } from \"./ribbonBuilder.js\";\nimport { Path3D } from \"../../Maths/math.path.js\";\n/**\n * Creates a tube mesh.\n * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters\n * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube\n * * The parameter `radius` (positive float, default 1) sets the tube radius size\n * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface\n * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overrides the parameter `radius`\n * * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. It must return a radius value (positive float)\n * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc\n * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL\n * * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter. The `path`Array HAS to have the SAME number of points as the previous one: https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#tube\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. The NUMBER of points CAN'T CHANGE, only their positions.\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.path\n * @param options.radius\n * @param options.tessellation\n * @param options.radiusFunction\n * @param options.cap\n * @param options.arc\n * @param options.updatable\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.instance\n * @param options.invertUV\n * @param scene defines the hosting scene\n * @returns the tube mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#tube\n */\nexport function CreateTube(name, options, scene = null) {\n const path = options.path;\n let instance = options.instance;\n let radius = 1.0;\n if (options.radius !== undefined) {\n radius = options.radius;\n }\n else if (instance) {\n radius = instance._creationDataStorage.radius;\n }\n const tessellation = options.tessellation || 64 | 0;\n const radiusFunction = options.radiusFunction || null;\n let cap = options.cap || Mesh.NO_CAP;\n const invertUV = options.invertUV || false;\n const updatable = options.updatable;\n const sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;\n // tube geometry\n const tubePathArray = (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) => {\n const tangents = path3D.getTangents();\n const normals = path3D.getNormals();\n const distances = path3D.getDistances();\n const pi2 = Math.PI * 2;\n const step = (pi2 / tessellation) * arc;\n const returnRadius = () => radius;\n const radiusFunctionFinal = radiusFunction || returnRadius;\n let circlePath;\n let rad;\n let normal;\n let rotated;\n const rotationMatrix = TmpVectors.Matrix[0];\n let index = cap === Mesh.NO_CAP || cap === Mesh.CAP_END ? 0 : 2;\n for (let i = 0; i < path.length; i++) {\n rad = radiusFunctionFinal(i, distances[i]); // current radius\n circlePath = Array(); // current circle array\n normal = normals[i]; // current normal\n for (let t = 0; t < tessellation; t++) {\n Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);\n rotated = circlePath[t] ? circlePath[t] : Vector3.Zero();\n Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);\n rotated.scaleInPlace(rad).addInPlace(path[i]);\n circlePath[t] = rotated;\n }\n circlePaths[index] = circlePath;\n index++;\n }\n // cap\n const capPath = (nbPoints, pathIndex) => {\n const pointCap = Array();\n for (let i = 0; i < nbPoints; i++) {\n pointCap.push(path[pathIndex]);\n }\n return pointCap;\n };\n switch (cap) {\n case Mesh.NO_CAP:\n break;\n case Mesh.CAP_START:\n circlePaths[0] = capPath(tessellation, 0);\n circlePaths[1] = circlePaths[2].slice(0);\n break;\n case Mesh.CAP_END:\n circlePaths[index] = circlePaths[index - 1].slice(0);\n circlePaths[index + 1] = capPath(tessellation, path.length - 1);\n break;\n case Mesh.CAP_ALL:\n circlePaths[0] = capPath(tessellation, 0);\n circlePaths[1] = circlePaths[2].slice(0);\n circlePaths[index] = circlePaths[index - 1].slice(0);\n circlePaths[index + 1] = capPath(tessellation, path.length - 1);\n break;\n default:\n break;\n }\n return circlePaths;\n };\n let path3D;\n let pathArray;\n if (instance) {\n // tube update\n const storage = instance._creationDataStorage;\n const arc = options.arc || storage.arc;\n path3D = storage.path3D.update(path);\n pathArray = tubePathArray(path, path3D, storage.pathArray, radius, storage.tessellation, radiusFunction, storage.cap, arc);\n instance = CreateRibbon(\"\", { pathArray: pathArray, instance: instance });\n // Update mode, no need to recreate the storage.\n storage.path3D = path3D;\n storage.pathArray = pathArray;\n storage.arc = arc;\n storage.radius = radius;\n return instance;\n }\n // tube creation\n path3D = new Path3D(path);\n const newPathArray = new Array();\n cap = cap < 0 || cap > 3 ? 0 : cap;\n pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);\n const tube = CreateRibbon(name, {\n pathArray: pathArray,\n closePath: true,\n closeArray: false,\n updatable: updatable,\n sideOrientation: sideOrientation,\n invertUV: invertUV,\n frontUVs: options.frontUVs,\n backUVs: options.backUVs,\n }, scene);\n tube._creationDataStorage.pathArray = pathArray;\n tube._creationDataStorage.path3D = path3D;\n tube._creationDataStorage.tessellation = tessellation;\n tube._creationDataStorage.cap = cap;\n tube._creationDataStorage.arc = options.arc;\n tube._creationDataStorage.radius = radius;\n return tube;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use CreateTube directly\n */\nexport const TubeBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateTube,\n};\nMesh.CreateTube = (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) => {\n const options = {\n path: path,\n radius: radius,\n tessellation: tessellation,\n radiusFunction: radiusFunction,\n arc: 1,\n cap: cap,\n updatable: updatable,\n sideOrientation: sideOrientation,\n instance: instance,\n };\n return CreateTube(name, options, scene);\n};\n//# sourceMappingURL=tubeBuilder.js.map","import { Vector4 } from \"../../Maths/math.vector.js\";\nimport { Color4 } from \"../../Maths/math.color.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n// inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html\n/**\n * Creates the VertexData for a Polyhedron\n * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty\n * * type provided types are:\n * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)\n * * 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)\n * * size the size of the IcoSphere, optional default 1\n * * sizeX allows stretching in the x direction, optional, default size\n * * sizeY allows stretching in the y direction, optional, default size\n * * sizeZ allows stretching in the z direction, optional, default size\n * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor\n * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively\n * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively\n * * flat when true creates a flat shaded mesh, optional, default true\n * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.type\n * @param options.size\n * @param options.sizeX\n * @param options.sizeY\n * @param options.sizeZ\n * @param options.custom\n * @param options.faceUV\n * @param options.faceColors\n * @param options.flat\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the Polyhedron\n */\nexport function CreatePolyhedronVertexData(options) {\n // provided polyhedron types :\n // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)\n // 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)\n const polyhedra = [];\n polyhedra[0] = {\n vertex: [\n [0, 0, 1.732051],\n [1.632993, 0, -0.5773503],\n [-0.8164966, 1.414214, -0.5773503],\n [-0.8164966, -1.414214, -0.5773503],\n ],\n face: [\n [0, 1, 2],\n [0, 2, 3],\n [0, 3, 1],\n [1, 3, 2],\n ],\n };\n polyhedra[1] = {\n vertex: [\n [0, 0, 1.414214],\n [1.414214, 0, 0],\n [0, 1.414214, 0],\n [-1.414214, 0, 0],\n [0, -1.414214, 0],\n [0, 0, -1.414214],\n ],\n face: [\n [0, 1, 2],\n [0, 2, 3],\n [0, 3, 4],\n [0, 4, 1],\n [1, 4, 5],\n [1, 5, 2],\n [2, 5, 3],\n [3, 5, 4],\n ],\n };\n polyhedra[2] = {\n vertex: [\n [0, 0, 1.070466],\n [0.7136442, 0, 0.7978784],\n [-0.3568221, 0.618034, 0.7978784],\n [-0.3568221, -0.618034, 0.7978784],\n [0.7978784, 0.618034, 0.3568221],\n [0.7978784, -0.618034, 0.3568221],\n [-0.9341724, 0.381966, 0.3568221],\n [0.1362939, 1, 0.3568221],\n [0.1362939, -1, 0.3568221],\n [-0.9341724, -0.381966, 0.3568221],\n [0.9341724, 0.381966, -0.3568221],\n [0.9341724, -0.381966, -0.3568221],\n [-0.7978784, 0.618034, -0.3568221],\n [-0.1362939, 1, -0.3568221],\n [-0.1362939, -1, -0.3568221],\n [-0.7978784, -0.618034, -0.3568221],\n [0.3568221, 0.618034, -0.7978784],\n [0.3568221, -0.618034, -0.7978784],\n [-0.7136442, 0, -0.7978784],\n [0, 0, -1.070466],\n ],\n face: [\n [0, 1, 4, 7, 2],\n [0, 2, 6, 9, 3],\n [0, 3, 8, 5, 1],\n [1, 5, 11, 10, 4],\n [2, 7, 13, 12, 6],\n [3, 9, 15, 14, 8],\n [4, 10, 16, 13, 7],\n [5, 8, 14, 17, 11],\n [6, 12, 18, 15, 9],\n [10, 11, 17, 19, 16],\n [12, 13, 16, 19, 18],\n [14, 15, 18, 19, 17],\n ],\n };\n polyhedra[3] = {\n vertex: [\n [0, 0, 1.175571],\n [1.051462, 0, 0.5257311],\n [0.3249197, 1, 0.5257311],\n [-0.8506508, 0.618034, 0.5257311],\n [-0.8506508, -0.618034, 0.5257311],\n [0.3249197, -1, 0.5257311],\n [0.8506508, 0.618034, -0.5257311],\n [0.8506508, -0.618034, -0.5257311],\n [-0.3249197, 1, -0.5257311],\n [-1.051462, 0, -0.5257311],\n [-0.3249197, -1, -0.5257311],\n [0, 0, -1.175571],\n ],\n face: [\n [0, 1, 2],\n [0, 2, 3],\n [0, 3, 4],\n [0, 4, 5],\n [0, 5, 1],\n [1, 5, 7],\n [1, 7, 6],\n [1, 6, 2],\n [2, 6, 8],\n [2, 8, 3],\n [3, 8, 9],\n [3, 9, 4],\n [4, 9, 10],\n [4, 10, 5],\n [5, 10, 7],\n [6, 7, 11],\n [6, 11, 8],\n [7, 10, 11],\n [8, 11, 9],\n [9, 11, 10],\n ],\n };\n polyhedra[4] = {\n vertex: [\n [0, 0, 1.070722],\n [0.7148135, 0, 0.7971752],\n [-0.104682, 0.7071068, 0.7971752],\n [-0.6841528, 0.2071068, 0.7971752],\n [-0.104682, -0.7071068, 0.7971752],\n [0.6101315, 0.7071068, 0.5236279],\n [1.04156, 0.2071068, 0.1367736],\n [0.6101315, -0.7071068, 0.5236279],\n [-0.3574067, 1, 0.1367736],\n [-0.7888348, -0.5, 0.5236279],\n [-0.9368776, 0.5, 0.1367736],\n [-0.3574067, -1, 0.1367736],\n [0.3574067, 1, -0.1367736],\n [0.9368776, -0.5, -0.1367736],\n [0.7888348, 0.5, -0.5236279],\n [0.3574067, -1, -0.1367736],\n [-0.6101315, 0.7071068, -0.5236279],\n [-1.04156, -0.2071068, -0.1367736],\n [-0.6101315, -0.7071068, -0.5236279],\n [0.104682, 0.7071068, -0.7971752],\n [0.6841528, -0.2071068, -0.7971752],\n [0.104682, -0.7071068, -0.7971752],\n [-0.7148135, 0, -0.7971752],\n [0, 0, -1.070722],\n ],\n face: [\n [0, 2, 3],\n [1, 6, 5],\n [4, 9, 11],\n [7, 15, 13],\n [8, 16, 10],\n [12, 14, 19],\n [17, 22, 18],\n [20, 21, 23],\n [0, 1, 5, 2],\n [0, 3, 9, 4],\n [0, 4, 7, 1],\n [1, 7, 13, 6],\n [2, 5, 12, 8],\n [2, 8, 10, 3],\n [3, 10, 17, 9],\n [4, 11, 15, 7],\n [5, 6, 14, 12],\n [6, 13, 20, 14],\n [8, 12, 19, 16],\n [9, 17, 18, 11],\n [10, 16, 22, 17],\n [11, 18, 21, 15],\n [13, 15, 21, 20],\n [14, 20, 23, 19],\n [16, 19, 23, 22],\n [18, 22, 23, 21],\n ],\n };\n polyhedra[5] = {\n vertex: [\n [0, 0, 1.322876],\n [1.309307, 0, 0.1889822],\n [-0.9819805, 0.8660254, 0.1889822],\n [0.1636634, -1.299038, 0.1889822],\n [0.3273268, 0.8660254, -0.9449112],\n [-0.8183171, -0.4330127, -0.9449112],\n ],\n face: [\n [0, 3, 1],\n [2, 4, 5],\n [0, 1, 4, 2],\n [0, 2, 5, 3],\n [1, 3, 5, 4],\n ],\n };\n polyhedra[6] = {\n vertex: [\n [0, 0, 1.159953],\n [1.013464, 0, 0.5642542],\n [-0.3501431, 0.9510565, 0.5642542],\n [-0.7715208, -0.6571639, 0.5642542],\n [0.6633206, 0.9510565, -0.03144481],\n [0.8682979, -0.6571639, -0.3996071],\n [-1.121664, 0.2938926, -0.03144481],\n [-0.2348831, -1.063314, -0.3996071],\n [0.5181548, 0.2938926, -0.9953061],\n [-0.5850262, -0.112257, -0.9953061],\n ],\n face: [\n [0, 1, 4, 2],\n [0, 2, 6, 3],\n [1, 5, 8, 4],\n [3, 6, 9, 7],\n [5, 7, 9, 8],\n [0, 3, 7, 5, 1],\n [2, 4, 8, 9, 6],\n ],\n };\n polyhedra[7] = {\n vertex: [\n [0, 0, 1.118034],\n [0.8944272, 0, 0.6708204],\n [-0.2236068, 0.8660254, 0.6708204],\n [-0.7826238, -0.4330127, 0.6708204],\n [0.6708204, 0.8660254, 0.2236068],\n [1.006231, -0.4330127, -0.2236068],\n [-1.006231, 0.4330127, 0.2236068],\n [-0.6708204, -0.8660254, -0.2236068],\n [0.7826238, 0.4330127, -0.6708204],\n [0.2236068, -0.8660254, -0.6708204],\n [-0.8944272, 0, -0.6708204],\n [0, 0, -1.118034],\n ],\n face: [\n [0, 1, 4, 2],\n [0, 2, 6, 3],\n [1, 5, 8, 4],\n [3, 6, 10, 7],\n [5, 9, 11, 8],\n [7, 10, 11, 9],\n [0, 3, 7, 9, 5, 1],\n [2, 4, 8, 11, 10, 6],\n ],\n };\n polyhedra[8] = {\n vertex: [\n [-0.729665, 0.670121, 0.319155],\n [-0.655235, -0.29213, -0.754096],\n [-0.093922, -0.607123, 0.537818],\n [0.702196, 0.595691, 0.485187],\n [0.776626, -0.36656, -0.588064],\n ],\n face: [\n [1, 4, 2],\n [0, 1, 2],\n [3, 0, 2],\n [4, 3, 2],\n [4, 1, 0, 3],\n ],\n };\n polyhedra[9] = {\n vertex: [\n [-0.868849, -0.100041, 0.61257],\n [-0.329458, 0.976099, 0.28078],\n [-0.26629, -0.013796, -0.477654],\n [-0.13392, -1.034115, 0.229829],\n [0.738834, 0.707117, -0.307018],\n [0.859683, -0.535264, -0.338508],\n ],\n face: [\n [3, 0, 2],\n [5, 3, 2],\n [4, 5, 2],\n [1, 4, 2],\n [0, 1, 2],\n [0, 3, 5, 4, 1],\n ],\n };\n polyhedra[10] = {\n vertex: [\n [-0.610389, 0.243975, 0.531213],\n [-0.187812, -0.48795, -0.664016],\n [-0.187812, 0.9759, -0.664016],\n [0.187812, -0.9759, 0.664016],\n [0.798201, 0.243975, 0.132803],\n ],\n face: [\n [1, 3, 0],\n [3, 4, 0],\n [3, 1, 4],\n [0, 2, 1],\n [0, 4, 2],\n [2, 4, 1],\n ],\n };\n polyhedra[11] = {\n vertex: [\n [-1.028778, 0.392027, -0.048786],\n [-0.640503, -0.646161, 0.621837],\n [-0.125162, -0.395663, -0.540059],\n [0.004683, 0.888447, -0.651988],\n [0.125161, 0.395663, 0.540059],\n [0.632925, -0.791376, 0.433102],\n [1.031672, 0.157063, -0.354165],\n ],\n face: [\n [3, 2, 0],\n [2, 1, 0],\n [2, 5, 1],\n [0, 4, 3],\n [0, 1, 4],\n [4, 1, 5],\n [2, 3, 6],\n [3, 4, 6],\n [5, 2, 6],\n [4, 5, 6],\n ],\n };\n polyhedra[12] = {\n vertex: [\n [-0.669867, 0.334933, -0.529576],\n [-0.669867, 0.334933, 0.529577],\n [-0.4043, 1.212901, 0],\n [-0.334933, -0.669867, -0.529576],\n [-0.334933, -0.669867, 0.529577],\n [0.334933, 0.669867, -0.529576],\n [0.334933, 0.669867, 0.529577],\n [0.4043, -1.212901, 0],\n [0.669867, -0.334933, -0.529576],\n [0.669867, -0.334933, 0.529577],\n ],\n face: [\n [8, 9, 7],\n [6, 5, 2],\n [3, 8, 7],\n [5, 0, 2],\n [4, 3, 7],\n [0, 1, 2],\n [9, 4, 7],\n [1, 6, 2],\n [9, 8, 5, 6],\n [8, 3, 0, 5],\n [3, 4, 1, 0],\n [4, 9, 6, 1],\n ],\n };\n polyhedra[13] = {\n vertex: [\n [-0.931836, 0.219976, -0.264632],\n [-0.636706, 0.318353, 0.692816],\n [-0.613483, -0.735083, -0.264632],\n [-0.326545, 0.979634, 0],\n [-0.318353, -0.636706, 0.692816],\n [-0.159176, 0.477529, -0.856368],\n [0.159176, -0.477529, -0.856368],\n [0.318353, 0.636706, 0.692816],\n [0.326545, -0.979634, 0],\n [0.613482, 0.735082, -0.264632],\n [0.636706, -0.318353, 0.692816],\n [0.931835, -0.219977, -0.264632],\n ],\n face: [\n [11, 10, 8],\n [7, 9, 3],\n [6, 11, 8],\n [9, 5, 3],\n [2, 6, 8],\n [5, 0, 3],\n [4, 2, 8],\n [0, 1, 3],\n [10, 4, 8],\n [1, 7, 3],\n [10, 11, 9, 7],\n [11, 6, 5, 9],\n [6, 2, 0, 5],\n [2, 4, 1, 0],\n [4, 10, 7, 1],\n ],\n };\n polyhedra[14] = {\n vertex: [\n [-0.93465, 0.300459, -0.271185],\n [-0.838689, -0.260219, -0.516017],\n [-0.711319, 0.717591, 0.128359],\n [-0.710334, -0.156922, 0.080946],\n [-0.599799, 0.556003, -0.725148],\n [-0.503838, -0.004675, -0.969981],\n [-0.487004, 0.26021, 0.48049],\n [-0.460089, -0.750282, -0.512622],\n [-0.376468, 0.973135, -0.325605],\n [-0.331735, -0.646985, 0.084342],\n [-0.254001, 0.831847, 0.530001],\n [-0.125239, -0.494738, -0.966586],\n [0.029622, 0.027949, 0.730817],\n [0.056536, -0.982543, -0.262295],\n [0.08085, 1.087391, 0.076037],\n [0.125583, -0.532729, 0.485984],\n [0.262625, 0.599586, 0.780328],\n [0.391387, -0.726999, -0.716259],\n [0.513854, -0.868287, 0.139347],\n [0.597475, 0.85513, 0.326364],\n [0.641224, 0.109523, 0.783723],\n [0.737185, -0.451155, 0.538891],\n [0.848705, -0.612742, -0.314616],\n [0.976075, 0.365067, 0.32976],\n [1.072036, -0.19561, 0.084927],\n ],\n face: [\n [15, 18, 21],\n [12, 20, 16],\n [6, 10, 2],\n [3, 0, 1],\n [9, 7, 13],\n [2, 8, 4, 0],\n [0, 4, 5, 1],\n [1, 5, 11, 7],\n [7, 11, 17, 13],\n [13, 17, 22, 18],\n [18, 22, 24, 21],\n [21, 24, 23, 20],\n [20, 23, 19, 16],\n [16, 19, 14, 10],\n [10, 14, 8, 2],\n [15, 9, 13, 18],\n [12, 15, 21, 20],\n [6, 12, 16, 10],\n [3, 6, 2, 0],\n [9, 3, 1, 7],\n [9, 15, 12, 6, 3],\n [22, 17, 11, 5, 4, 8, 14, 19, 23, 24],\n ],\n };\n const type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;\n const size = options.size;\n const sizeX = options.sizeX || size || 1;\n const sizeY = options.sizeY || size || 1;\n const sizeZ = options.sizeZ || size || 1;\n const data = options.custom || polyhedra[type];\n const nbfaces = data.face.length;\n const faceUV = options.faceUV || new Array(nbfaces);\n const faceColors = options.faceColors;\n const flat = options.flat === undefined ? true : options.flat;\n const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;\n const positions = new Array();\n const indices = new Array();\n const normals = new Array();\n const uvs = new Array();\n const colors = new Array();\n let index = 0;\n let faceIdx = 0; // face cursor in the array \"indexes\"\n const indexes = new Array();\n let i = 0;\n let f = 0;\n let u, v, ang, x, y, tmp;\n // default face colors and UV if undefined\n if (flat) {\n for (f = 0; f < nbfaces; f++) {\n if (faceColors && faceColors[f] === undefined) {\n faceColors[f] = new Color4(1, 1, 1, 1);\n }\n if (faceUV && faceUV[f] === undefined) {\n faceUV[f] = new Vector4(0, 0, 1, 1);\n }\n }\n }\n if (!flat) {\n for (i = 0; i < data.vertex.length; i++) {\n positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);\n uvs.push(0, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 : 0);\n }\n for (f = 0; f < nbfaces; f++) {\n for (i = 0; i < data.face[f].length - 2; i++) {\n indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);\n }\n }\n }\n else {\n for (f = 0; f < nbfaces; f++) {\n const fl = data.face[f].length; // number of vertices of the current face\n ang = (2 * Math.PI) / fl;\n x = 0.5 * Math.tan(ang / 2);\n y = 0.5;\n // positions, uvs, colors\n for (i = 0; i < fl; i++) {\n // positions\n positions.push(data.vertex[data.face[f][i]][0] * sizeX, data.vertex[data.face[f][i]][1] * sizeY, data.vertex[data.face[f][i]][2] * sizeZ);\n indexes.push(index);\n index++;\n // uvs\n u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);\n v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);\n uvs.push(u, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - v : v);\n tmp = x * Math.cos(ang) - y * Math.sin(ang);\n y = x * Math.sin(ang) + y * Math.cos(ang);\n x = tmp;\n // colors\n if (faceColors) {\n colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);\n }\n }\n // indices from indexes\n for (i = 0; i < fl - 2; i++) {\n indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);\n }\n faceIdx += fl;\n }\n }\n VertexData.ComputeNormals(positions, indices, normals);\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n const vertexData = new VertexData();\n vertexData.positions = positions;\n vertexData.indices = indices;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n if (faceColors && flat) {\n vertexData.colors = colors;\n }\n return vertexData;\n}\n/**\n * Creates a polyhedron mesh\n * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type\n * * The parameter `size` (positive float, default 1) sets the polygon size\n * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)\n * * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overrides the parameter `type`\n * * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron\n * * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`)\n * * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : https://doc.babylonjs.com/features/featuresDeepDive/materials/using/texturePerBoxFace\n * * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.type\n * @param options.size\n * @param options.sizeX\n * @param options.sizeY\n * @param options.sizeZ\n * @param options.custom\n * @param options.faceUV\n * @param options.faceColors\n * @param options.flat\n * @param options.updatable\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param scene defines the hosting scene\n * @returns the polyhedron mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/polyhedra\n */\nexport function CreatePolyhedron(name, options = {}, scene = null) {\n const polyhedron = new Mesh(name, scene);\n options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n polyhedron._originalBuilderSideOrientation = options.sideOrientation;\n const vertexData = CreatePolyhedronVertexData(options);\n vertexData.applyToMesh(polyhedron, options.updatable);\n return polyhedron;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use the function directly from the module\n */\nexport const PolyhedronBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreatePolyhedron,\n};\nVertexData.CreatePolyhedron = CreatePolyhedronVertexData;\nMesh.CreatePolyhedron = (name, options, scene) => {\n return CreatePolyhedron(name, options, scene);\n};\n//# sourceMappingURL=polyhedronBuilder.js.map","import { Vector3, Matrix, Vector2, TmpVectors } from \"../../Maths/math.vector.js\";\nimport { Scalar } from \"../../Maths/math.scalar.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { VertexBuffer } from \"../../Buffers/buffer.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\nconst xpAxis = new Vector3(1, 0, 0);\nconst xnAxis = new Vector3(-1, 0, 0);\nconst ypAxis = new Vector3(0, 1, 0);\nconst ynAxis = new Vector3(0, -1, 0);\nconst zpAxis = new Vector3(0, 0, 1);\nconst znAxis = new Vector3(0, 0, -1);\n/** @internal */\nclass DecalVertex {\n constructor(position = Vector3.Zero(), normal = Vector3.Up(), uv = Vector2.Zero(), vertexIdx = 0, vertexIdxForBones = 0, localPositionOverride = null, localNormalOverride = null, matrixIndicesOverride = null, matrixWeightsOverride = null) {\n this.position = position;\n this.normal = normal;\n this.uv = uv;\n this.vertexIdx = vertexIdx;\n this.vertexIdxForBones = vertexIdxForBones;\n this.localPositionOverride = localPositionOverride;\n this.localNormalOverride = localNormalOverride;\n this.matrixIndicesOverride = matrixIndicesOverride;\n this.matrixWeightsOverride = matrixWeightsOverride;\n }\n clone() {\n var _a, _b, _c, _d;\n return new DecalVertex(this.position.clone(), this.normal.clone(), this.uv.clone(), this.vertexIdx, this.vertexIdxForBones, (_a = this.localPositionOverride) === null || _a === void 0 ? void 0 : _a.slice(), (_b = this.localNormalOverride) === null || _b === void 0 ? void 0 : _b.slice(), (_c = this.matrixIndicesOverride) === null || _c === void 0 ? void 0 : _c.slice(), (_d = this.matrixWeightsOverride) === null || _d === void 0 ? void 0 : _d.slice());\n }\n}\n/**\n * Creates a decal mesh.\n * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal\n * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates\n * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates\n * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling\n * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal\n * * The parameter `captureUVS` defines if we need to capture the uvs or compute them\n * * The parameter `cullBackFaces` defines if the back faces should be removed from the decal mesh\n * * The parameter `localMode` defines that the computations should be done with the local mesh coordinates instead of the world space coordinates.\n * * Use this mode if you want the decal to be parented to the sourceMesh and move/rotate with it.\n * Note: Meshes with morph targets are not supported!\n * @param name defines the name of the mesh\n * @param sourceMesh defines the mesh where the decal must be applied\n * @param options defines the options used to create the mesh\n * @param options.position\n * @param options.normal\n * @param options.size\n * @param options.angle\n * @param options.captureUVS\n * @param options.cullBackFaces\n * @param options.localMode\n * @returns the decal mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/decals\n */\nexport function CreateDecal(name, sourceMesh, options) {\n var _a, _b, _c, _d;\n const hasSkeleton = !!sourceMesh.skeleton;\n const useLocalComputation = options.localMode || hasSkeleton;\n const meshHasOverridenMaterial = sourceMesh.overrideMaterialSideOrientation !== null && sourceMesh.overrideMaterialSideOrientation !== undefined;\n const indices = sourceMesh.getIndices();\n const positions = hasSkeleton ? sourceMesh.getPositionData(true, true) : sourceMesh.getVerticesData(VertexBuffer.PositionKind);\n const normals = hasSkeleton ? sourceMesh.getNormalsData(true, true) : sourceMesh.getVerticesData(VertexBuffer.NormalKind);\n const localPositions = useLocalComputation ? (hasSkeleton ? sourceMesh.getVerticesData(VertexBuffer.PositionKind) : positions) : null;\n const localNormals = useLocalComputation ? (hasSkeleton ? sourceMesh.getVerticesData(VertexBuffer.NormalKind) : normals) : null;\n const uvs = sourceMesh.getVerticesData(VertexBuffer.UVKind);\n const matIndices = hasSkeleton ? sourceMesh.getVerticesData(VertexBuffer.MatricesIndicesKind) : null;\n const matWeights = hasSkeleton ? sourceMesh.getVerticesData(VertexBuffer.MatricesWeightsKind) : null;\n const matIndicesExtra = hasSkeleton ? sourceMesh.getVerticesData(VertexBuffer.MatricesIndicesExtraKind) : null;\n const matWeightsExtra = hasSkeleton ? sourceMesh.getVerticesData(VertexBuffer.MatricesWeightsExtraKind) : null;\n const position = options.position || Vector3.Zero();\n let normal = options.normal || Vector3.Up();\n const size = options.size || Vector3.One();\n const angle = options.angle || 0;\n // Getting correct rotation\n if (!normal) {\n const target = new Vector3(0, 0, 1);\n const camera = sourceMesh.getScene().activeCamera;\n const cameraWorldTarget = Vector3.TransformCoordinates(target, camera.getWorldMatrix());\n normal = camera.globalPosition.subtract(cameraWorldTarget);\n }\n const yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;\n const len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);\n const pitch = Math.atan2(normal.y, len);\n const vertexData = new VertexData();\n vertexData.indices = [];\n vertexData.positions = [];\n vertexData.normals = [];\n vertexData.uvs = [];\n vertexData.matricesIndices = hasSkeleton ? [] : null;\n vertexData.matricesWeights = hasSkeleton ? [] : null;\n vertexData.matricesIndicesExtra = matIndicesExtra ? [] : null;\n vertexData.matricesWeightsExtra = matWeightsExtra ? [] : null;\n let currentVertexDataIndex = 0;\n const extractDecalVector3 = (indexId, transformMatrix) => {\n const result = new DecalVertex();\n if (!indices || !positions || !normals) {\n return result;\n }\n const vertexId = indices[indexId];\n result.vertexIdx = vertexId * 3;\n result.vertexIdxForBones = vertexId * 4;\n // Send vector to decal local world\n result.position = new Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);\n Vector3.TransformCoordinatesToRef(result.position, transformMatrix, result.position);\n // Get normal\n result.normal = new Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);\n Vector3.TransformNormalToRef(result.normal, transformMatrix, result.normal);\n if (options.captureUVS && uvs) {\n const v = uvs[vertexId * 2 + 1];\n result.uv = new Vector2(uvs[vertexId * 2], CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v);\n }\n return result;\n };\n const emptyArray = [0, 0, 0, 0];\n // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js\n const clip = (vertices, axis) => {\n if (vertices.length === 0) {\n return vertices;\n }\n const clipSize = 0.5 * Math.abs(Vector3.Dot(size, axis));\n const indexOf = (arr, val, start, num) => {\n for (let i = 0; i < num; ++i) {\n if (arr[start + i] === val) {\n return start + i;\n }\n }\n return -1;\n };\n const clipVertices = (v0, v1) => {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;\n const clipFactor = Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);\n let indices = emptyArray;\n let weights = emptyArray;\n if (matIndices && matWeights) {\n const mat0Index = v0.matrixIndicesOverride ? 0 : v0.vertexIdxForBones;\n const v0Indices = (_a = v0.matrixIndicesOverride) !== null && _a !== void 0 ? _a : matIndices;\n const v0Weights = (_b = v0.matrixWeightsOverride) !== null && _b !== void 0 ? _b : matWeights;\n const mat1Index = v1.matrixIndicesOverride ? 0 : v1.vertexIdxForBones;\n const v1Indices = (_c = v1.matrixIndicesOverride) !== null && _c !== void 0 ? _c : matIndices;\n const v1Weights = (_d = v1.matrixWeightsOverride) !== null && _d !== void 0 ? _d : matWeights;\n indices = [0, 0, 0, 0];\n weights = [0, 0, 0, 0];\n let index = 0;\n for (let i = 0; i < 4; ++i) {\n if (v0Weights[mat0Index + i] > 0) {\n const idx = indexOf(v1Indices, v0Indices[mat0Index + i], mat1Index, 4);\n indices[index] = v0Indices[mat0Index + i];\n weights[index] = Scalar.Lerp(v0Weights[mat0Index + i], idx >= 0 ? v1Weights[idx] : 0, clipFactor);\n index++;\n }\n }\n for (let i = 0; i < 4 && index < 4; ++i) {\n const ind = v1Indices[mat1Index + i];\n if (indexOf(v0Indices, ind, mat0Index, 4) !== -1)\n continue;\n indices[index] = ind;\n weights[index] = Scalar.Lerp(0, v1Weights[mat1Index + i], clipFactor);\n index++;\n }\n const sumw = weights[0] + weights[1] + weights[2] + weights[3];\n weights[0] /= sumw;\n weights[1] /= sumw;\n weights[2] /= sumw;\n weights[3] /= sumw;\n }\n const v0LocalPositionX = v0.localPositionOverride ? v0.localPositionOverride[0] : (_e = localPositions === null || localPositions === void 0 ? void 0 : localPositions[v0.vertexIdx]) !== null && _e !== void 0 ? _e : 0;\n const v0LocalPositionY = v0.localPositionOverride ? v0.localPositionOverride[1] : (_f = localPositions === null || localPositions === void 0 ? void 0 : localPositions[v0.vertexIdx + 1]) !== null && _f !== void 0 ? _f : 0;\n const v0LocalPositionZ = v0.localPositionOverride ? v0.localPositionOverride[2] : (_g = localPositions === null || localPositions === void 0 ? void 0 : localPositions[v0.vertexIdx + 2]) !== null && _g !== void 0 ? _g : 0;\n const v1LocalPositionX = v1.localPositionOverride ? v1.localPositionOverride[0] : (_h = localPositions === null || localPositions === void 0 ? void 0 : localPositions[v1.vertexIdx]) !== null && _h !== void 0 ? _h : 0;\n const v1LocalPositionY = v1.localPositionOverride ? v1.localPositionOverride[1] : (_j = localPositions === null || localPositions === void 0 ? void 0 : localPositions[v1.vertexIdx + 1]) !== null && _j !== void 0 ? _j : 0;\n const v1LocalPositionZ = v1.localPositionOverride ? v1.localPositionOverride[2] : (_k = localPositions === null || localPositions === void 0 ? void 0 : localPositions[v1.vertexIdx + 2]) !== null && _k !== void 0 ? _k : 0;\n const v0LocalNormalX = v0.localNormalOverride ? v0.localNormalOverride[0] : (_l = localNormals === null || localNormals === void 0 ? void 0 : localNormals[v0.vertexIdx]) !== null && _l !== void 0 ? _l : 0;\n const v0LocalNormalY = v0.localNormalOverride ? v0.localNormalOverride[1] : (_m = localNormals === null || localNormals === void 0 ? void 0 : localNormals[v0.vertexIdx + 1]) !== null && _m !== void 0 ? _m : 0;\n const v0LocalNormalZ = v0.localNormalOverride ? v0.localNormalOverride[2] : (_o = localNormals === null || localNormals === void 0 ? void 0 : localNormals[v0.vertexIdx + 2]) !== null && _o !== void 0 ? _o : 0;\n const v1LocalNormalX = v1.localNormalOverride ? v1.localNormalOverride[0] : (_p = localNormals === null || localNormals === void 0 ? void 0 : localNormals[v1.vertexIdx]) !== null && _p !== void 0 ? _p : 0;\n const v1LocalNormalY = v1.localNormalOverride ? v1.localNormalOverride[1] : (_q = localNormals === null || localNormals === void 0 ? void 0 : localNormals[v1.vertexIdx + 1]) !== null && _q !== void 0 ? _q : 0;\n const v1LocalNormalZ = v1.localNormalOverride ? v1.localNormalOverride[2] : (_r = localNormals === null || localNormals === void 0 ? void 0 : localNormals[v1.vertexIdx + 2]) !== null && _r !== void 0 ? _r : 0;\n const interpNormalX = v0LocalNormalX + (v1LocalNormalX - v0LocalNormalX) * clipFactor;\n const interpNormalY = v0LocalNormalY + (v1LocalNormalY - v0LocalNormalY) * clipFactor;\n const interpNormalZ = v0LocalNormalZ + (v1LocalNormalZ - v0LocalNormalZ) * clipFactor;\n const norm = Math.sqrt(interpNormalX * interpNormalX + interpNormalY * interpNormalY + interpNormalZ * interpNormalZ);\n return new DecalVertex(Vector3.Lerp(v0.position, v1.position, clipFactor), Vector3.Lerp(v0.normal, v1.normal, clipFactor).normalize(), Vector2.Lerp(v0.uv, v1.uv, clipFactor), -1, -1, localPositions\n ? [\n v0LocalPositionX + (v1LocalPositionX - v0LocalPositionX) * clipFactor,\n v0LocalPositionY + (v1LocalPositionY - v0LocalPositionY) * clipFactor,\n v0LocalPositionZ + (v1LocalPositionZ - v0LocalPositionZ) * clipFactor,\n ]\n : null, localNormals ? [interpNormalX / norm, interpNormalY / norm, interpNormalZ / norm] : null, indices, weights);\n };\n let clipResult = null;\n if (vertices.length > 3) {\n clipResult = new Array();\n }\n for (let index = 0; index < vertices.length; index += 3) {\n let total = 0;\n let nV1 = null;\n let nV2 = null;\n let nV3 = null;\n let nV4 = null;\n const d1 = Vector3.Dot(vertices[index].position, axis) - clipSize;\n const d2 = Vector3.Dot(vertices[index + 1].position, axis) - clipSize;\n const d3 = Vector3.Dot(vertices[index + 2].position, axis) - clipSize;\n const v1Out = d1 > 0;\n const v2Out = d2 > 0;\n const v3Out = d3 > 0;\n total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);\n switch (total) {\n case 0:\n if (vertices.length > 3) {\n clipResult.push(vertices[index]);\n clipResult.push(vertices[index + 1]);\n clipResult.push(vertices[index + 2]);\n }\n else {\n clipResult = vertices;\n }\n break;\n case 1:\n clipResult = clipResult !== null && clipResult !== void 0 ? clipResult : new Array();\n if (v1Out) {\n nV1 = vertices[index + 1];\n nV2 = vertices[index + 2];\n nV3 = clipVertices(vertices[index], nV1);\n nV4 = clipVertices(vertices[index], nV2);\n }\n if (v2Out) {\n nV1 = vertices[index];\n nV2 = vertices[index + 2];\n nV3 = clipVertices(vertices[index + 1], nV1);\n nV4 = clipVertices(vertices[index + 1], nV2);\n clipResult.push(nV3);\n clipResult.push(nV2.clone());\n clipResult.push(nV1.clone());\n clipResult.push(nV2.clone());\n clipResult.push(nV3.clone());\n clipResult.push(nV4);\n break;\n }\n if (v3Out) {\n nV1 = vertices[index];\n nV2 = vertices[index + 1];\n nV3 = clipVertices(vertices[index + 2], nV1);\n nV4 = clipVertices(vertices[index + 2], nV2);\n }\n if (nV1 && nV2 && nV3 && nV4) {\n clipResult.push(nV1.clone());\n clipResult.push(nV2.clone());\n clipResult.push(nV3);\n clipResult.push(nV4);\n clipResult.push(nV3.clone());\n clipResult.push(nV2.clone());\n }\n break;\n case 2:\n clipResult = clipResult !== null && clipResult !== void 0 ? clipResult : new Array();\n if (!v1Out) {\n nV1 = vertices[index].clone();\n nV2 = clipVertices(nV1, vertices[index + 1]);\n nV3 = clipVertices(nV1, vertices[index + 2]);\n clipResult.push(nV1);\n clipResult.push(nV2);\n clipResult.push(nV3);\n }\n if (!v2Out) {\n nV1 = vertices[index + 1].clone();\n nV2 = clipVertices(nV1, vertices[index + 2]);\n nV3 = clipVertices(nV1, vertices[index]);\n clipResult.push(nV1);\n clipResult.push(nV2);\n clipResult.push(nV3);\n }\n if (!v3Out) {\n nV1 = vertices[index + 2].clone();\n nV2 = clipVertices(nV1, vertices[index]);\n nV3 = clipVertices(nV1, vertices[index + 1]);\n clipResult.push(nV1);\n clipResult.push(nV2);\n clipResult.push(nV3);\n }\n break;\n case 3:\n break;\n }\n }\n return clipResult;\n };\n const sourceMeshAsMesh = sourceMesh instanceof Mesh ? sourceMesh : null;\n const matrixData = sourceMeshAsMesh === null || sourceMeshAsMesh === void 0 ? void 0 : sourceMeshAsMesh._thinInstanceDataStorage.matrixData;\n const numMatrices = (sourceMeshAsMesh === null || sourceMeshAsMesh === void 0 ? void 0 : sourceMeshAsMesh.thinInstanceCount) || 1;\n const thinInstanceMatrix = TmpVectors.Matrix[0];\n thinInstanceMatrix.copyFrom(Matrix.IdentityReadOnly);\n for (let m = 0; m < numMatrices; ++m) {\n if ((sourceMeshAsMesh === null || sourceMeshAsMesh === void 0 ? void 0 : sourceMeshAsMesh.hasThinInstances) && matrixData) {\n const ofst = m * 16;\n thinInstanceMatrix.setRowFromFloats(0, matrixData[ofst + 0], matrixData[ofst + 1], matrixData[ofst + 2], matrixData[ofst + 3]);\n thinInstanceMatrix.setRowFromFloats(1, matrixData[ofst + 4], matrixData[ofst + 5], matrixData[ofst + 6], matrixData[ofst + 7]);\n thinInstanceMatrix.setRowFromFloats(2, matrixData[ofst + 8], matrixData[ofst + 9], matrixData[ofst + 10], matrixData[ofst + 11]);\n thinInstanceMatrix.setRowFromFloats(3, matrixData[ofst + 12], matrixData[ofst + 13], matrixData[ofst + 14], matrixData[ofst + 15]);\n }\n // Matrix\n const decalWorldMatrix = Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(Matrix.Translation(position.x, position.y, position.z));\n const inverseDecalWorldMatrix = Matrix.Invert(decalWorldMatrix);\n const meshWorldMatrix = sourceMesh.getWorldMatrix();\n const transformMatrix = thinInstanceMatrix.multiply(meshWorldMatrix).multiply(inverseDecalWorldMatrix);\n const oneFaceVertices = new Array(3);\n for (let index = 0; index < indices.length; index += 3) {\n let faceVertices = oneFaceVertices;\n faceVertices[0] = extractDecalVector3(index, transformMatrix);\n if (meshHasOverridenMaterial && useLocalComputation) {\n faceVertices[1] = extractDecalVector3(index + 2, transformMatrix);\n faceVertices[2] = extractDecalVector3(index + 1, transformMatrix);\n }\n else {\n faceVertices[1] = extractDecalVector3(index + 1, transformMatrix);\n faceVertices[2] = extractDecalVector3(index + 2, transformMatrix);\n }\n if (options.cullBackFaces) {\n // If all the normals of the vertices of the face are pointing away from the view direction we discard the face.\n // As computations are done in the decal coordinate space, the viewDirection is (0,0,1), so when dot(vertexNormal, -viewDirection) <= 0 the vertex is culled\n if (-faceVertices[0].normal.z <= 0 && -faceVertices[1].normal.z <= 0 && -faceVertices[2].normal.z <= 0) {\n continue;\n }\n }\n // Clip\n faceVertices = clip(faceVertices, xpAxis);\n if (!faceVertices)\n continue;\n faceVertices = clip(faceVertices, xnAxis);\n if (!faceVertices)\n continue;\n faceVertices = clip(faceVertices, ypAxis);\n if (!faceVertices)\n continue;\n faceVertices = clip(faceVertices, ynAxis);\n if (!faceVertices)\n continue;\n faceVertices = clip(faceVertices, zpAxis);\n if (!faceVertices)\n continue;\n faceVertices = clip(faceVertices, znAxis);\n if (!faceVertices)\n continue;\n // Add UVs and get back to world\n for (let vIndex = 0; vIndex < faceVertices.length; vIndex++) {\n const vertex = faceVertices[vIndex];\n //TODO check for Int32Array | Uint32Array | Uint16Array\n vertexData.indices.push(currentVertexDataIndex);\n if (useLocalComputation) {\n if (vertex.localPositionOverride) {\n vertexData.positions[currentVertexDataIndex * 3] = vertex.localPositionOverride[0];\n vertexData.positions[currentVertexDataIndex * 3 + 1] = vertex.localPositionOverride[1];\n vertexData.positions[currentVertexDataIndex * 3 + 2] = vertex.localPositionOverride[2];\n }\n else if (localPositions) {\n vertexData.positions[currentVertexDataIndex * 3] = localPositions[vertex.vertexIdx];\n vertexData.positions[currentVertexDataIndex * 3 + 1] = localPositions[vertex.vertexIdx + 1];\n vertexData.positions[currentVertexDataIndex * 3 + 2] = localPositions[vertex.vertexIdx + 2];\n }\n if (vertex.localNormalOverride) {\n vertexData.normals[currentVertexDataIndex * 3] = vertex.localNormalOverride[0];\n vertexData.normals[currentVertexDataIndex * 3 + 1] = vertex.localNormalOverride[1];\n vertexData.normals[currentVertexDataIndex * 3 + 2] = vertex.localNormalOverride[2];\n }\n else if (localNormals) {\n vertexData.normals[currentVertexDataIndex * 3] = localNormals[vertex.vertexIdx];\n vertexData.normals[currentVertexDataIndex * 3 + 1] = localNormals[vertex.vertexIdx + 1];\n vertexData.normals[currentVertexDataIndex * 3 + 2] = localNormals[vertex.vertexIdx + 2];\n }\n }\n else {\n vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);\n vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);\n }\n if (vertexData.matricesIndices && vertexData.matricesWeights) {\n if (vertex.matrixIndicesOverride) {\n vertexData.matricesIndices[currentVertexDataIndex * 4] = vertex.matrixIndicesOverride[0];\n vertexData.matricesIndices[currentVertexDataIndex * 4 + 1] = vertex.matrixIndicesOverride[1];\n vertexData.matricesIndices[currentVertexDataIndex * 4 + 2] = vertex.matrixIndicesOverride[2];\n vertexData.matricesIndices[currentVertexDataIndex * 4 + 3] = vertex.matrixIndicesOverride[3];\n }\n else {\n if (matIndices) {\n vertexData.matricesIndices[currentVertexDataIndex * 4] = matIndices[vertex.vertexIdxForBones];\n vertexData.matricesIndices[currentVertexDataIndex * 4 + 1] = matIndices[vertex.vertexIdxForBones + 1];\n vertexData.matricesIndices[currentVertexDataIndex * 4 + 2] = matIndices[vertex.vertexIdxForBones + 2];\n vertexData.matricesIndices[currentVertexDataIndex * 4 + 3] = matIndices[vertex.vertexIdxForBones + 3];\n }\n if (matIndicesExtra && vertexData.matricesIndicesExtra) {\n vertexData.matricesIndicesExtra[currentVertexDataIndex * 4] = matIndicesExtra[vertex.vertexIdxForBones];\n vertexData.matricesIndicesExtra[currentVertexDataIndex * 4 + 1] = matIndicesExtra[vertex.vertexIdxForBones + 1];\n vertexData.matricesIndicesExtra[currentVertexDataIndex * 4 + 2] = matIndicesExtra[vertex.vertexIdxForBones + 2];\n vertexData.matricesIndicesExtra[currentVertexDataIndex * 4 + 3] = matIndicesExtra[vertex.vertexIdxForBones + 3];\n }\n }\n if (vertex.matrixWeightsOverride) {\n vertexData.matricesWeights[currentVertexDataIndex * 4] = vertex.matrixWeightsOverride[0];\n vertexData.matricesWeights[currentVertexDataIndex * 4 + 1] = vertex.matrixWeightsOverride[1];\n vertexData.matricesWeights[currentVertexDataIndex * 4 + 2] = vertex.matrixWeightsOverride[2];\n vertexData.matricesWeights[currentVertexDataIndex * 4 + 3] = vertex.matrixWeightsOverride[3];\n }\n else {\n if (matWeights) {\n vertexData.matricesWeights[currentVertexDataIndex * 4] = matWeights[vertex.vertexIdxForBones];\n vertexData.matricesWeights[currentVertexDataIndex * 4 + 1] = matWeights[vertex.vertexIdxForBones + 1];\n vertexData.matricesWeights[currentVertexDataIndex * 4 + 2] = matWeights[vertex.vertexIdxForBones + 2];\n vertexData.matricesWeights[currentVertexDataIndex * 4 + 3] = matWeights[vertex.vertexIdxForBones + 3];\n }\n if (matWeightsExtra && vertexData.matricesWeightsExtra) {\n vertexData.matricesWeightsExtra[currentVertexDataIndex * 4] = matWeightsExtra[vertex.vertexIdxForBones];\n vertexData.matricesWeightsExtra[currentVertexDataIndex * 4 + 1] = matWeightsExtra[vertex.vertexIdxForBones + 1];\n vertexData.matricesWeightsExtra[currentVertexDataIndex * 4 + 2] = matWeightsExtra[vertex.vertexIdxForBones + 2];\n vertexData.matricesWeightsExtra[currentVertexDataIndex * 4 + 3] = matWeightsExtra[vertex.vertexIdxForBones + 3];\n }\n }\n }\n if (!options.captureUVS) {\n vertexData.uvs.push(0.5 + vertex.position.x / size.x);\n const v = 0.5 + vertex.position.y / size.y;\n vertexData.uvs.push(CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v);\n }\n else {\n vertex.uv.toArray(vertexData.uvs, currentVertexDataIndex * 2);\n }\n currentVertexDataIndex++;\n }\n }\n }\n // Avoid the \"Setting vertex data kind 'XXX' with an empty array\" warning when calling vertexData.applyToMesh\n if (vertexData.indices.length === 0)\n vertexData.indices = null;\n if (vertexData.positions.length === 0)\n vertexData.positions = null;\n if (vertexData.normals.length === 0)\n vertexData.normals = null;\n if (vertexData.uvs.length === 0)\n vertexData.uvs = null;\n if (((_a = vertexData.matricesIndices) === null || _a === void 0 ? void 0 : _a.length) === 0)\n vertexData.matricesIndices = null;\n if (((_b = vertexData.matricesWeights) === null || _b === void 0 ? void 0 : _b.length) === 0)\n vertexData.matricesWeights = null;\n if (((_c = vertexData.matricesIndicesExtra) === null || _c === void 0 ? void 0 : _c.length) === 0)\n vertexData.matricesIndicesExtra = null;\n if (((_d = vertexData.matricesWeightsExtra) === null || _d === void 0 ? void 0 : _d.length) === 0)\n vertexData.matricesWeightsExtra = null;\n // Return mesh\n const decal = new Mesh(name, sourceMesh.getScene());\n vertexData.applyToMesh(decal);\n if (useLocalComputation) {\n decal.skeleton = sourceMesh.skeleton;\n decal.parent = sourceMesh;\n }\n else {\n decal.position = position.clone();\n decal.rotation = new Vector3(pitch, yaw, angle);\n }\n decal.computeWorldMatrix(true);\n decal.refreshBoundingInfo(true, true);\n return decal;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use the function directly from the module\n */\nexport const DecalBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateDecal,\n};\nMesh.CreateDecal = (name, sourceMesh, position, normal, size, angle) => {\n const options = {\n position,\n normal,\n size,\n angle,\n };\n return CreateDecal(name, sourceMesh, options);\n};\n//# sourceMappingURL=decalBuilder.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { Vector3 } from \"./math.vector.js\";\n/**\n * Class representing an isovector a vector containing 2 INTEGER coordinates\n * x axis is horizontal\n * y axis is 60 deg counter clockwise from positive y axis\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class _IsoVector {\n /**\n * Creates a new isovector from the given x and y coordinates\n * @param x defines the first coordinate, must be an integer\n * @param y defines the second coordinate, must be an integer\n */\n constructor(\n /** defines the first coordinate */\n x = 0, \n /** defines the second coordinate */\n y = 0) {\n this.x = x;\n this.y = y;\n if (x !== Math.floor(x)) {\n x === Math.floor(x);\n Logger.Warn(\"x is not an integer, floor(x) used\");\n }\n if (y !== Math.floor(y)) {\n y === Math.floor(y);\n Logger.Warn(\"y is not an integer, floor(y) used\");\n }\n }\n // Operators\n /**\n * Gets a new IsoVector copied from the IsoVector\n * @returns a new IsoVector\n */\n clone() {\n return new _IsoVector(this.x, this.y);\n }\n /**\n * Rotates one IsoVector 60 degrees counter clockwise about another\n * Please note that this is an in place operation\n * @param other an IsoVector a center of rotation\n * @returns the rotated IsoVector\n */\n rotate60About(other) {\n //other IsoVector\n const x = this.x;\n this.x = other.x + other.y - this.y;\n this.y = x + this.y - other.x;\n return this;\n }\n /**\n * Rotates one IsoVector 60 degrees clockwise about another\n * Please note that this is an in place operation\n * @param other an IsoVector as center of rotation\n * @returns the rotated IsoVector\n */\n rotateNeg60About(other) {\n const x = this.x;\n this.x = x + this.y - other.y;\n this.y = other.x + other.y - x;\n return this;\n }\n /**\n * For an equilateral triangle OAB with O at isovector (0, 0) and A at isovector (m, n)\n * Rotates one IsoVector 120 degrees counter clockwise about the center of the triangle\n * Please note that this is an in place operation\n * @param m integer a measure a Primary triangle of order (m, n) m > n\n * @param n >= 0 integer a measure for a Primary triangle of order (m, n)\n * @returns the rotated IsoVector\n */\n rotate120(m, n) {\n //m, n integers\n if (m !== Math.floor(m)) {\n m === Math.floor(m);\n Logger.Warn(\"m not an integer only floor(m) used\");\n }\n if (n !== Math.floor(n)) {\n n === Math.floor(n);\n Logger.Warn(\"n not an integer only floor(n) used\");\n }\n const x = this.x;\n this.x = m - x - this.y;\n this.y = n + x;\n return this;\n }\n /**\n * For an equilateral triangle OAB with O at isovector (0, 0) and A at isovector (m, n)\n * Rotates one IsoVector 120 degrees clockwise about the center of the triangle\n * Please note that this is an in place operation\n * @param m integer a measure a Primary triangle of order (m, n) m > n\n * @param n >= 0 integer a measure for a Primary triangle of order (m, n)\n * @returns the rotated IsoVector\n */\n rotateNeg120(m, n) {\n //m, n integers\n if (m !== Math.floor(m)) {\n m === Math.floor(m);\n Logger.Warn(\"m is not an integer, floor(m) used\");\n }\n if (n !== Math.floor(n)) {\n n === Math.floor(n);\n Logger.Warn(\"n is not an integer, floor(n) used\");\n }\n const x = this.x;\n this.x = this.y - n;\n this.y = m + n - x - this.y;\n return this;\n }\n /**\n * Transforms an IsoVector to one in Cartesian 3D space based on an isovector\n * @param origin an IsoVector\n * @param isoGridSize\n * @returns Point as a Vector3\n */\n toCartesianOrigin(origin, isoGridSize) {\n const point = Vector3.Zero();\n point.x = origin.x + 2 * this.x * isoGridSize + this.y * isoGridSize;\n point.y = origin.y + Math.sqrt(3) * this.y * isoGridSize;\n return point;\n }\n // Statics\n /**\n * Gets a new IsoVector(0, 0)\n * @returns a new IsoVector\n */\n static Zero() {\n return new _IsoVector(0, 0);\n }\n}\n//# sourceMappingURL=math.isovector.js.map","import { Vector3, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Scalar } from \"../Maths/math.scalar.js\";\nimport { PHI } from \"../Maths/math.constants.js\";\nimport { _IsoVector } from \"../Maths/math.isovector.js\";\n/**\n * Class representing data for one face OAB of an equilateral icosahedron\n * When O is the isovector (0, 0), A is isovector (m, n)\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class _PrimaryIsoTriangle {\n constructor() {\n this.cartesian = [];\n this.vertices = [];\n this.max = [];\n this.min = [];\n this.closestTo = [];\n this.innerFacets = [];\n this.isoVecsABOB = [];\n this.isoVecsOBOA = [];\n this.isoVecsBAOA = [];\n this.vertexTypes = [];\n // eslint-disable-next-line @typescript-eslint/naming-convention\n this.IDATA = new PolyhedronData(\"icosahedron\", \"Regular\", [\n [0, PHI, -1],\n [-PHI, 1, 0],\n [-1, 0, -PHI],\n [1, 0, -PHI],\n [PHI, 1, 0],\n [0, PHI, 1],\n [-1, 0, PHI],\n [-PHI, -1, 0],\n [0, -PHI, -1],\n [PHI, -1, 0],\n [1, 0, PHI],\n [0, -PHI, 1],\n ], [\n [0, 2, 1],\n [0, 3, 2],\n [0, 4, 3],\n [0, 5, 4],\n [0, 1, 5],\n [7, 6, 1],\n [8, 7, 2],\n [9, 8, 3],\n [10, 9, 4],\n [6, 10, 5],\n [2, 7, 1],\n [3, 8, 2],\n [4, 9, 3],\n [5, 10, 4],\n [1, 6, 5],\n [11, 6, 7],\n [11, 7, 8],\n [11, 8, 9],\n [11, 9, 10],\n [11, 10, 6],\n ]);\n }\n /**\n * Creates the PrimaryIsoTriangle Triangle OAB\n * @param m an integer\n * @param n an integer\n */\n //operators\n setIndices() {\n let indexCount = 12; // 12 vertices already assigned\n const vecToidx = {}; //maps iso-vectors to indexCount;\n const m = this.m;\n const n = this.n;\n let g = m; // hcf of m, n when n != 0\n let m1 = 1;\n let n1 = 0;\n if (n !== 0) {\n g = Scalar.HCF(m, n);\n }\n m1 = m / g;\n n1 = n / g;\n let fr; //face to the right of current face\n let rot; //rotation about which vertex for fr\n let O;\n let A;\n let B;\n const oVec = _IsoVector.Zero();\n const aVec = new _IsoVector(m, n);\n const bVec = new _IsoVector(-n, m + n);\n const oaVec = _IsoVector.Zero();\n const abVec = _IsoVector.Zero();\n const obVec = _IsoVector.Zero();\n let verts = [];\n let idx;\n let idxR;\n let isoId;\n let isoIdR;\n const closestTo = [];\n const vDist = this.vertByDist;\n const matchIdx = (f, fr, isoId, isoIdR) => {\n idx = f + \"|\" + isoId;\n idxR = fr + \"|\" + isoIdR;\n if (!(idx in vecToidx || idxR in vecToidx)) {\n vecToidx[idx] = indexCount;\n vecToidx[idxR] = indexCount;\n indexCount++;\n }\n else if (idx in vecToidx && !(idxR in vecToidx)) {\n vecToidx[idxR] = vecToidx[idx];\n }\n else if (idxR in vecToidx && !(idx in vecToidx)) {\n vecToidx[idx] = vecToidx[idxR];\n }\n if (vDist[isoId][0] > 2) {\n closestTo[vecToidx[idx]] = [-vDist[isoId][0], vDist[isoId][1], vecToidx[idx]];\n }\n else {\n closestTo[vecToidx[idx]] = [verts[vDist[isoId][0]], vDist[isoId][1], vecToidx[idx]];\n }\n };\n this.IDATA.edgematch = [\n [1, \"B\"],\n [2, \"B\"],\n [3, \"B\"],\n [4, \"B\"],\n [0, \"B\"],\n [10, \"O\", 14, \"A\"],\n [11, \"O\", 10, \"A\"],\n [12, \"O\", 11, \"A\"],\n [13, \"O\", 12, \"A\"],\n [14, \"O\", 13, \"A\"],\n [0, \"O\"],\n [1, \"O\"],\n [2, \"O\"],\n [3, \"O\"],\n [4, \"O\"],\n [19, \"B\", 5, \"A\"],\n [15, \"B\", 6, \"A\"],\n [16, \"B\", 7, \"A\"],\n [17, \"B\", 8, \"A\"],\n [18, \"B\", 9, \"A\"],\n ];\n /***edges AB to OB***** rotation about B*/\n for (let f = 0; f < 20; f++) {\n //f current face\n verts = this.IDATA.face[f];\n O = verts[2];\n A = verts[1];\n B = verts[0];\n isoId = oVec.x + \"|\" + oVec.y;\n idx = f + \"|\" + isoId;\n if (!(idx in vecToidx)) {\n vecToidx[idx] = O;\n closestTo[O] = [verts[vDist[isoId][0]], vDist[isoId][1]];\n }\n isoId = aVec.x + \"|\" + aVec.y;\n idx = f + \"|\" + isoId;\n if (!(idx in vecToidx)) {\n vecToidx[idx] = A;\n closestTo[A] = [verts[vDist[isoId][0]], vDist[isoId][1]];\n }\n isoId = bVec.x + \"|\" + bVec.y;\n idx = f + \"|\" + isoId;\n if (!(idx in vecToidx)) {\n vecToidx[idx] = B;\n closestTo[B] = [verts[vDist[isoId][0]], vDist[isoId][1]];\n }\n //for edge vertices\n fr = this.IDATA.edgematch[f][0];\n rot = this.IDATA.edgematch[f][1];\n if (rot === \"B\") {\n for (let i = 1; i < g; i++) {\n abVec.x = m - i * (m1 + n1);\n abVec.y = n + i * m1;\n obVec.x = -i * n1;\n obVec.y = i * (m1 + n1);\n isoId = abVec.x + \"|\" + abVec.y;\n isoIdR = obVec.x + \"|\" + obVec.y;\n matchIdx(f, fr, isoId, isoIdR);\n }\n }\n if (rot === \"O\") {\n for (let i = 1; i < g; i++) {\n obVec.x = -i * n1;\n obVec.y = i * (m1 + n1);\n oaVec.x = i * m1;\n oaVec.y = i * n1;\n isoId = obVec.x + \"|\" + obVec.y;\n isoIdR = oaVec.x + \"|\" + oaVec.y;\n matchIdx(f, fr, isoId, isoIdR);\n }\n }\n fr = this.IDATA.edgematch[f][2];\n rot = this.IDATA.edgematch[f][3];\n if (rot && rot === \"A\") {\n for (let i = 1; i < g; i++) {\n oaVec.x = i * m1;\n oaVec.y = i * n1;\n abVec.x = m - (g - i) * (m1 + n1); //reversed for BA\n abVec.y = n + (g - i) * m1; //reversed for BA\n isoId = oaVec.x + \"|\" + oaVec.y;\n isoIdR = abVec.x + \"|\" + abVec.y;\n matchIdx(f, fr, isoId, isoIdR);\n }\n }\n for (let i = 0; i < this.vertices.length; i++) {\n isoId = this.vertices[i].x + \"|\" + this.vertices[i].y;\n idx = f + \"|\" + isoId;\n if (!(idx in vecToidx)) {\n vecToidx[idx] = indexCount++;\n if (vDist[isoId][0] > 2) {\n closestTo[vecToidx[idx]] = [-vDist[isoId][0], vDist[isoId][1], vecToidx[idx]];\n }\n else {\n closestTo[vecToidx[idx]] = [verts[vDist[isoId][0]], vDist[isoId][1], vecToidx[idx]];\n }\n }\n }\n }\n this.closestTo = closestTo;\n this.vecToidx = vecToidx;\n }\n calcCoeffs() {\n const m = this.m;\n const n = this.n;\n const thirdR3 = Math.sqrt(3) / 3;\n const LSQD = m * m + n * n + m * n;\n this.coau = (m + n) / LSQD;\n this.cobu = -n / LSQD;\n this.coav = (-thirdR3 * (m - n)) / LSQD;\n this.cobv = (thirdR3 * (2 * m + n)) / LSQD;\n }\n createInnerFacets() {\n const m = this.m;\n const n = this.n;\n for (let y = 0; y < n + m + 1; y++) {\n for (let x = this.min[y]; x < this.max[y] + 1; x++) {\n if (x < this.max[y] && x < this.max[y + 1] + 1) {\n this.innerFacets.push([\"|\" + x + \"|\" + y, \"|\" + x + \"|\" + (y + 1), \"|\" + (x + 1) + \"|\" + y]);\n }\n if (y > 0 && x < this.max[y - 1] && x + 1 < this.max[y] + 1) {\n this.innerFacets.push([\"|\" + x + \"|\" + y, \"|\" + (x + 1) + \"|\" + y, \"|\" + (x + 1) + \"|\" + (y - 1)]);\n }\n }\n }\n }\n edgeVecsABOB() {\n const m = this.m;\n const n = this.n;\n const B = new _IsoVector(-n, m + n);\n for (let y = 1; y < m + n; y++) {\n const point = new _IsoVector(this.min[y], y);\n const prev = new _IsoVector(this.min[y - 1], y - 1);\n const next = new _IsoVector(this.min[y + 1], y + 1);\n const pointR = point.clone();\n const prevR = prev.clone();\n const nextR = next.clone();\n pointR.rotate60About(B);\n prevR.rotate60About(B);\n nextR.rotate60About(B);\n const maxPoint = new _IsoVector(this.max[pointR.y], pointR.y);\n const maxPrev = new _IsoVector(this.max[pointR.y - 1], pointR.y - 1);\n const maxLeftPrev = new _IsoVector(this.max[pointR.y - 1] - 1, pointR.y - 1);\n if (pointR.x !== maxPoint.x || pointR.y !== maxPoint.y) {\n if (pointR.x !== maxPrev.x) {\n // type2\n //up\n this.vertexTypes.push([1, 0, 0]);\n this.isoVecsABOB.push([point, maxPrev, maxLeftPrev]);\n //down\n this.vertexTypes.push([1, 0, 0]);\n this.isoVecsABOB.push([point, maxLeftPrev, maxPoint]);\n }\n else if (pointR.y === nextR.y) {\n // type1\n //up\n this.vertexTypes.push([1, 1, 0]);\n this.isoVecsABOB.push([point, prev, maxPrev]);\n //down\n this.vertexTypes.push([1, 0, 1]);\n this.isoVecsABOB.push([point, maxPrev, next]);\n }\n else {\n // type 0\n //up\n this.vertexTypes.push([1, 1, 0]);\n this.isoVecsABOB.push([point, prev, maxPrev]);\n //down\n this.vertexTypes.push([1, 0, 0]);\n this.isoVecsABOB.push([point, maxPrev, maxPoint]);\n }\n }\n }\n }\n mapABOBtoOBOA() {\n const point = new _IsoVector(0, 0);\n for (let i = 0; i < this.isoVecsABOB.length; i++) {\n const temp = [];\n for (let j = 0; j < 3; j++) {\n point.x = this.isoVecsABOB[i][j].x;\n point.y = this.isoVecsABOB[i][j].y;\n if (this.vertexTypes[i][j] === 0) {\n point.rotateNeg120(this.m, this.n);\n }\n temp.push(point.clone());\n }\n this.isoVecsOBOA.push(temp);\n }\n }\n mapABOBtoBAOA() {\n const point = new _IsoVector(0, 0);\n for (let i = 0; i < this.isoVecsABOB.length; i++) {\n const temp = [];\n for (let j = 0; j < 3; j++) {\n point.x = this.isoVecsABOB[i][j].x;\n point.y = this.isoVecsABOB[i][j].y;\n if (this.vertexTypes[i][j] === 1) {\n point.rotate120(this.m, this.n);\n }\n temp.push(point.clone());\n }\n this.isoVecsBAOA.push(temp);\n }\n }\n // eslint-disable-next-line @typescript-eslint/naming-convention\n MapToFace(faceNb, geodesicData) {\n const F = this.IDATA.face[faceNb];\n const oidx = F[2];\n const aidx = F[1];\n const bidx = F[0];\n const O = Vector3.FromArray(this.IDATA.vertex[oidx]);\n const A = Vector3.FromArray(this.IDATA.vertex[aidx]);\n const B = Vector3.FromArray(this.IDATA.vertex[bidx]);\n const OA = A.subtract(O);\n const OB = B.subtract(O);\n const x = OA.scale(this.coau).add(OB.scale(this.cobu));\n const y = OA.scale(this.coav).add(OB.scale(this.cobv));\n const mapped = [];\n let idx;\n let tempVec = TmpVectors.Vector3[0];\n for (let i = 0; i < this.cartesian.length; i++) {\n tempVec = x.scale(this.cartesian[i].x).add(y.scale(this.cartesian[i].y)).add(O);\n mapped[i] = [tempVec.x, tempVec.y, tempVec.z];\n idx = faceNb + \"|\" + this.vertices[i].x + \"|\" + this.vertices[i].y;\n geodesicData.vertex[this.vecToidx[idx]] = [tempVec.x, tempVec.y, tempVec.z];\n }\n }\n //statics\n /**Creates a primary triangle\n * @internal\n */\n build(m, n) {\n const vertices = new Array();\n const O = _IsoVector.Zero();\n const A = new _IsoVector(m, n);\n const B = new _IsoVector(-n, m + n);\n vertices.push(O, A, B);\n //max internal isoceles triangle vertices\n for (let y = n; y < m + 1; y++) {\n for (let x = 0; x < m + 1 - y; x++) {\n vertices.push(new _IsoVector(x, y));\n }\n }\n //shared vertices along edges when needed\n if (n > 0) {\n const g = Scalar.HCF(m, n);\n const m1 = m / g;\n const n1 = n / g;\n for (let i = 1; i < g; i++) {\n vertices.push(new _IsoVector(i * m1, i * n1)); //OA\n vertices.push(new _IsoVector(-i * n1, i * (m1 + n1))); //OB\n vertices.push(new _IsoVector(m - i * (m1 + n1), n + i * m1)); // AB\n }\n //lower rows vertices and their rotations\n const ratio = m / n;\n for (let y = 1; y < n; y++) {\n for (let x = 0; x < y * ratio; x++) {\n vertices.push(new _IsoVector(x, y));\n vertices.push(new _IsoVector(x, y).rotate120(m, n));\n vertices.push(new _IsoVector(x, y).rotateNeg120(m, n));\n }\n }\n }\n //order vertices by x and then y\n vertices.sort((a, b) => {\n return a.x - b.x;\n });\n vertices.sort((a, b) => {\n return a.y - b.y;\n });\n const min = new Array(m + n + 1);\n const max = new Array(m + n + 1);\n for (let i = 0; i < min.length; i++) {\n min[i] = Infinity;\n max[i] = -Infinity;\n }\n let y = 0;\n let x = 0;\n const len = vertices.length;\n for (let i = 0; i < len; i++) {\n x = vertices[i].x;\n y = vertices[i].y;\n min[y] = Math.min(x, min[y]);\n max[y] = Math.max(x, max[y]);\n }\n //calculates the distance of a vertex from a given primary vertex\n const distFrom = (vert, primVert) => {\n const v = vert.clone();\n if (primVert === \"A\") {\n v.rotateNeg120(m, n);\n }\n if (primVert === \"B\") {\n v.rotate120(m, n);\n }\n if (v.x < 0) {\n return v.y;\n }\n return v.x + v.y;\n };\n const cartesian = [];\n const distFromO = [];\n const distFromA = [];\n const distFromB = [];\n const vertByDist = {};\n const vertData = [];\n let closest = -1;\n let dist = -1;\n for (let i = 0; i < len; i++) {\n cartesian[i] = vertices[i].toCartesianOrigin(new _IsoVector(0, 0), 0.5);\n distFromO[i] = distFrom(vertices[i], \"O\");\n distFromA[i] = distFrom(vertices[i], \"A\");\n distFromB[i] = distFrom(vertices[i], \"B\");\n if (distFromO[i] === distFromA[i] && distFromA[i] === distFromB[i]) {\n closest = 3;\n dist = distFromO[i];\n }\n else if (distFromO[i] === distFromA[i]) {\n closest = 4;\n dist = distFromO[i];\n }\n else if (distFromA[i] === distFromB[i]) {\n closest = 5;\n dist = distFromA[i];\n }\n else if (distFromB[i] === distFromO[i]) {\n closest = 6;\n dist = distFromO[i];\n }\n if (distFromO[i] < distFromA[i] && distFromO[i] < distFromB[i]) {\n closest = 2;\n dist = distFromO[i];\n }\n if (distFromA[i] < distFromO[i] && distFromA[i] < distFromB[i]) {\n closest = 1;\n dist = distFromA[i];\n }\n if (distFromB[i] < distFromA[i] && distFromB[i] < distFromO[i]) {\n closest = 0;\n dist = distFromB[i];\n }\n vertData.push([closest, dist, vertices[i].x, vertices[i].y]);\n }\n vertData.sort((a, b) => {\n return a[2] - b[2];\n });\n vertData.sort((a, b) => {\n return a[3] - b[3];\n });\n vertData.sort((a, b) => {\n return a[1] - b[1];\n });\n vertData.sort((a, b) => {\n return a[0] - b[0];\n });\n for (let v = 0; v < vertData.length; v++) {\n vertByDist[vertData[v][2] + \"|\" + vertData[v][3]] = [vertData[v][0], vertData[v][1], v];\n }\n this.m = m;\n this.n = n;\n this.vertices = vertices;\n this.vertByDist = vertByDist;\n this.cartesian = cartesian;\n this.min = min;\n this.max = max;\n return this;\n }\n}\n/** Builds Polyhedron Data\n * @internal\n */\nexport class PolyhedronData {\n constructor(name, category, vertex, face) {\n this.name = name;\n this.category = category;\n this.vertex = vertex;\n this.face = face;\n }\n}\n/**\n * This class Extends the PolyhedronData Class to provide measures for a Geodesic Polyhedron\n */\nexport class GeodesicData extends PolyhedronData {\n /**\n * @internal\n */\n innerToData(face, primTri) {\n for (let i = 0; i < primTri.innerFacets.length; i++) {\n this.face.push(primTri.innerFacets[i].map((el) => primTri.vecToidx[face + el]));\n }\n }\n /**\n * @internal\n */\n mapABOBtoDATA(faceNb, primTri) {\n const fr = primTri.IDATA.edgematch[faceNb][0];\n for (let i = 0; i < primTri.isoVecsABOB.length; i++) {\n const temp = [];\n for (let j = 0; j < 3; j++) {\n if (primTri.vertexTypes[i][j] === 0) {\n temp.push(faceNb + \"|\" + primTri.isoVecsABOB[i][j].x + \"|\" + primTri.isoVecsABOB[i][j].y);\n }\n else {\n temp.push(fr + \"|\" + primTri.isoVecsABOB[i][j].x + \"|\" + primTri.isoVecsABOB[i][j].y);\n }\n }\n this.face.push([primTri.vecToidx[temp[0]], primTri.vecToidx[temp[1]], primTri.vecToidx[temp[2]]]);\n }\n }\n /**\n * @internal\n */\n mapOBOAtoDATA(faceNb, primTri) {\n const fr = primTri.IDATA.edgematch[faceNb][0];\n for (let i = 0; i < primTri.isoVecsOBOA.length; i++) {\n const temp = [];\n for (let j = 0; j < 3; j++) {\n if (primTri.vertexTypes[i][j] === 1) {\n temp.push(faceNb + \"|\" + primTri.isoVecsOBOA[i][j].x + \"|\" + primTri.isoVecsOBOA[i][j].y);\n }\n else {\n temp.push(fr + \"|\" + primTri.isoVecsOBOA[i][j].x + \"|\" + primTri.isoVecsOBOA[i][j].y);\n }\n }\n this.face.push([primTri.vecToidx[temp[0]], primTri.vecToidx[temp[1]], primTri.vecToidx[temp[2]]]);\n }\n }\n /**\n * @internal\n */\n mapBAOAtoDATA(faceNb, primTri) {\n const fr = primTri.IDATA.edgematch[faceNb][2];\n for (let i = 0; i < primTri.isoVecsBAOA.length; i++) {\n const temp = [];\n for (let j = 0; j < 3; j++) {\n if (primTri.vertexTypes[i][j] === 1) {\n temp.push(faceNb + \"|\" + primTri.isoVecsBAOA[i][j].x + \"|\" + primTri.isoVecsBAOA[i][j].y);\n }\n else {\n temp.push(fr + \"|\" + primTri.isoVecsBAOA[i][j].x + \"|\" + primTri.isoVecsBAOA[i][j].y);\n }\n }\n this.face.push([primTri.vecToidx[temp[0]], primTri.vecToidx[temp[1]], primTri.vecToidx[temp[2]]]);\n }\n }\n /**\n * @internal\n */\n orderData(primTri) {\n const nearTo = [];\n for (let i = 0; i < 13; i++) {\n nearTo[i] = [];\n }\n const close = primTri.closestTo;\n for (let i = 0; i < close.length; i++) {\n if (close[i][0] > -1) {\n if (close[i][1] > 0) {\n nearTo[close[i][0]].push([i, close[i][1]]);\n }\n }\n else {\n nearTo[12].push([i, close[i][0]]);\n }\n }\n const near = [];\n for (let i = 0; i < 12; i++) {\n near[i] = i;\n }\n let nearIndex = 12;\n for (let i = 0; i < 12; i++) {\n nearTo[i].sort((a, b) => {\n return a[1] - b[1];\n });\n for (let j = 0; j < nearTo[i].length; j++) {\n near[nearTo[i][j][0]] = nearIndex++;\n }\n }\n for (let j = 0; j < nearTo[12].length; j++) {\n near[nearTo[12][j][0]] = nearIndex++;\n }\n for (let i = 0; i < this.vertex.length; i++) {\n this.vertex[i].push(near[i]);\n }\n this.vertex.sort((a, b) => {\n return a[3] - b[3];\n });\n for (let i = 0; i < this.vertex.length; i++) {\n this.vertex[i].pop();\n }\n for (let i = 0; i < this.face.length; i++) {\n for (let j = 0; j < this.face[i].length; j++) {\n this.face[i][j] = near[this.face[i][j]];\n }\n }\n this.sharedNodes = nearTo[12].length;\n this.poleNodes = this.vertex.length - this.sharedNodes;\n }\n /**\n * @internal\n */\n setOrder(m, faces) {\n const adjVerts = [];\n const dualFaces = [];\n let face = faces.pop();\n dualFaces.push(face);\n let index = this.face[face].indexOf(m);\n index = (index + 2) % 3;\n let v = this.face[face][index];\n adjVerts.push(v);\n let f = 0;\n while (faces.length > 0) {\n face = faces[f];\n if (this.face[face].indexOf(v) > -1) {\n // v is a vertex of face f\n index = (this.face[face].indexOf(v) + 1) % 3;\n v = this.face[face][index];\n adjVerts.push(v);\n dualFaces.push(face);\n faces.splice(f, 1);\n f = 0;\n }\n else {\n f++;\n }\n }\n this.adjacentFaces.push(adjVerts);\n return dualFaces;\n }\n /**\n * @internal\n */\n toGoldbergPolyhedronData() {\n const goldbergPolyhedronData = new PolyhedronData(\"GeoDual\", \"Goldberg\", [], []);\n goldbergPolyhedronData.name = \"GD dual\";\n const verticesNb = this.vertex.length;\n const map = new Array(verticesNb);\n for (let v = 0; v < verticesNb; v++) {\n map[v] = [];\n }\n for (let f = 0; f < this.face.length; f++) {\n for (let i = 0; i < 3; i++) {\n map[this.face[f][i]].push(f);\n }\n }\n let cx = 0;\n let cy = 0;\n let cz = 0;\n let face = [];\n let vertex = [];\n this.adjacentFaces = [];\n for (let m = 0; m < map.length; m++) {\n goldbergPolyhedronData.face[m] = this.setOrder(m, map[m].concat([]));\n map[m].forEach((el) => {\n cx = 0;\n cy = 0;\n cz = 0;\n face = this.face[el];\n for (let i = 0; i < 3; i++) {\n vertex = this.vertex[face[i]];\n cx += vertex[0];\n cy += vertex[1];\n cz += vertex[2];\n }\n goldbergPolyhedronData.vertex[el] = [cx / 3, cy / 3, cz / 3];\n });\n }\n return goldbergPolyhedronData;\n }\n //statics\n /**Builds the data for a Geodesic Polyhedron from a primary triangle\n * @param primTri the primary triangle\n * @internal\n */\n static BuildGeodesicData(primTri) {\n const geodesicData = new GeodesicData(\"Geodesic-m-n\", \"Geodesic\", [\n [0, PHI, -1],\n [-PHI, 1, 0],\n [-1, 0, -PHI],\n [1, 0, -PHI],\n [PHI, 1, 0],\n [0, PHI, 1],\n [-1, 0, PHI],\n [-PHI, -1, 0],\n [0, -PHI, -1],\n [PHI, -1, 0],\n [1, 0, PHI],\n [0, -PHI, 1],\n ], []);\n primTri.setIndices();\n primTri.calcCoeffs();\n primTri.createInnerFacets();\n primTri.edgeVecsABOB();\n primTri.mapABOBtoOBOA();\n primTri.mapABOBtoBAOA();\n for (let f = 0; f < primTri.IDATA.face.length; f++) {\n primTri.MapToFace(f, geodesicData);\n geodesicData.innerToData(f, primTri);\n if (primTri.IDATA.edgematch[f][1] === \"B\") {\n geodesicData.mapABOBtoDATA(f, primTri);\n }\n if (primTri.IDATA.edgematch[f][1] === \"O\") {\n geodesicData.mapOBOAtoDATA(f, primTri);\n }\n if (primTri.IDATA.edgematch[f][3] === \"A\") {\n geodesicData.mapBAOAtoDATA(f, primTri);\n }\n }\n geodesicData.orderData(primTri);\n const radius = 1;\n geodesicData.vertex = geodesicData.vertex.map(function (el) {\n const a = el[0];\n const b = el[1];\n const c = el[2];\n const d = Math.sqrt(a * a + b * b + c * c);\n el[0] *= radius / d;\n el[1] *= radius / d;\n el[2] *= radius / d;\n return el;\n });\n return geodesicData;\n }\n}\n//# sourceMappingURL=geodesicMesh.js.map","import { CreatePolyhedron } from \"./polyhedronBuilder.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { _PrimaryIsoTriangle, GeodesicData } from \"../geodesicMesh.js\";\n/**\n * Creates the Mesh for a Geodesic Polyhedron\n * @see https://en.wikipedia.org/wiki/Geodesic_polyhedron\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/polyhedra/geodesic_poly\n * @param name defines the name of the mesh\n * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty\n * * m number of horizontal steps along an isogrid\n * * n number of angled steps along an isogrid\n * * size the size of the Geodesic, optional default 1\n * * sizeX allows stretching in the x direction, optional, default size\n * * sizeY allows stretching in the y direction, optional, default size\n * * sizeZ allows stretching in the z direction, optional, default size\n * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively\n * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively\n * * flat when true creates a flat shaded mesh, optional, default true\n * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.n\n * @param options.size\n * @param options.sizeX\n * @param options.sizeY\n * @param options.sizeZ\n * @param options.faceUV\n * @param options.faceColors\n * @param options.flat\n * @param options.updatable\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.m\n * @param scene defines the hosting scene\n * @returns Geodesic mesh\n */\nexport function CreateGeodesic(name, options, scene = null) {\n let m = options.m || 1;\n if (m !== Math.floor(m)) {\n m === Math.floor(m);\n Logger.Warn(\"m not an integer only floor(m) used\");\n }\n let n = options.n || 0;\n if (n !== Math.floor(n)) {\n n === Math.floor(n);\n Logger.Warn(\"n not an integer only floor(n) used\");\n }\n if (n > m) {\n const temp = n;\n n = m;\n m = temp;\n Logger.Warn(\"n > m therefore m and n swapped\");\n }\n const primTri = new _PrimaryIsoTriangle();\n primTri.build(m, n);\n const geodesicData = GeodesicData.BuildGeodesicData(primTri);\n const geoOptions = {\n custom: geodesicData,\n size: options.size,\n sizeX: options.sizeX,\n sizeY: options.sizeY,\n sizeZ: options.sizeZ,\n faceUV: options.faceUV,\n faceColors: options.faceColors,\n flat: options.flat,\n updatable: options.updatable,\n sideOrientation: options.sideOrientation,\n frontUVs: options.frontUVs,\n backUVs: options.backUVs,\n };\n const geodesic = CreatePolyhedron(name, geoOptions, scene);\n return geodesic;\n}\n//# sourceMappingURL=geodesicBuilder.js.map","import { Vector3 } from \"../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { Logger } from \"../Misc/logger.js\";\nMesh._GoldbergMeshParser = (parsedMesh, scene) => {\n return GoldbergMesh.Parse(parsedMesh, scene);\n};\n/**\n * Mesh for a Goldberg Polyhedron which is made from 12 pentagonal and the rest hexagonal faces\n * @see https://en.wikipedia.org/wiki/Goldberg_polyhedron\n */\nexport class GoldbergMesh extends Mesh {\n constructor() {\n super(...arguments);\n /**\n * Defines the specific Goldberg data used in this mesh construction.\n */\n this.goldbergData = {\n faceColors: [],\n faceCenters: [],\n faceZaxis: [],\n faceXaxis: [],\n faceYaxis: [],\n nbSharedFaces: 0,\n nbUnsharedFaces: 0,\n nbFaces: 0,\n nbFacesAtPole: 0,\n adjacentFaces: [],\n };\n }\n /**\n * Gets the related Goldberg face from pole infos\n * @param poleOrShared Defines the pole index or the shared face index if the fromPole parameter is passed in\n * @param fromPole Defines an optional pole index to find the related info from\n * @returns the goldberg face number\n */\n relatedGoldbergFace(poleOrShared, fromPole) {\n if (fromPole === void 0) {\n if (poleOrShared > this.goldbergData.nbUnsharedFaces - 1) {\n Logger.Warn(\"Maximum number of unshared faces used\");\n poleOrShared = this.goldbergData.nbUnsharedFaces - 1;\n }\n return this.goldbergData.nbUnsharedFaces + poleOrShared;\n }\n if (poleOrShared > 11) {\n Logger.Warn(\"Last pole used\");\n poleOrShared = 11;\n }\n if (fromPole > this.goldbergData.nbFacesAtPole - 1) {\n Logger.Warn(\"Maximum number of faces at a pole used\");\n fromPole = this.goldbergData.nbFacesAtPole - 1;\n }\n return 12 + poleOrShared * this.goldbergData.nbFacesAtPole + fromPole;\n }\n _changeGoldbergFaceColors(colorRange) {\n for (let i = 0; i < colorRange.length; i++) {\n const min = colorRange[i][0];\n const max = colorRange[i][1];\n const col = colorRange[i][2];\n for (let f = min; f < max + 1; f++) {\n this.goldbergData.faceColors[f] = col;\n }\n }\n const newCols = [];\n for (let f = 0; f < 12; f++) {\n for (let i = 0; i < 5; i++) {\n newCols.push(this.goldbergData.faceColors[f].r, this.goldbergData.faceColors[f].g, this.goldbergData.faceColors[f].b, this.goldbergData.faceColors[f].a);\n }\n }\n for (let f = 12; f < this.goldbergData.faceColors.length; f++) {\n for (let i = 0; i < 6; i++) {\n newCols.push(this.goldbergData.faceColors[f].r, this.goldbergData.faceColors[f].g, this.goldbergData.faceColors[f].b, this.goldbergData.faceColors[f].a);\n }\n }\n return newCols;\n }\n /**\n * Set new goldberg face colors\n * @param colorRange the new color to apply to the mesh\n */\n setGoldbergFaceColors(colorRange) {\n const newCols = this._changeGoldbergFaceColors(colorRange);\n this.setVerticesData(VertexBuffer.ColorKind, newCols);\n }\n /**\n * Updates new goldberg face colors\n * @param colorRange the new color to apply to the mesh\n */\n updateGoldbergFaceColors(colorRange) {\n const newCols = this._changeGoldbergFaceColors(colorRange);\n this.updateVerticesData(VertexBuffer.ColorKind, newCols);\n }\n _changeGoldbergFaceUVs(uvRange) {\n const uvs = this.getVerticesData(VertexBuffer.UVKind);\n for (let i = 0; i < uvRange.length; i++) {\n const min = uvRange[i][0];\n const max = uvRange[i][1];\n const center = uvRange[i][2];\n const radius = uvRange[i][3];\n const angle = uvRange[i][4];\n const points5 = [];\n const points6 = [];\n let u;\n let v;\n for (let p = 0; p < 5; p++) {\n u = center.x + radius * Math.cos(angle + (p * Math.PI) / 2.5);\n v = center.y + radius * Math.sin(angle + (p * Math.PI) / 2.5);\n if (u < 0) {\n u = 0;\n }\n if (u > 1) {\n u = 1;\n }\n points5.push(u, v);\n }\n for (let p = 0; p < 6; p++) {\n u = center.x + radius * Math.cos(angle + (p * Math.PI) / 3);\n v = center.y + radius * Math.sin(angle + (p * Math.PI) / 3);\n if (u < 0) {\n u = 0;\n }\n if (u > 1) {\n u = 1;\n }\n points6.push(u, v);\n }\n for (let f = min; f < Math.min(12, max + 1); f++) {\n for (let p = 0; p < 5; p++) {\n uvs[10 * f + 2 * p] = points5[2 * p];\n uvs[10 * f + 2 * p + 1] = points5[2 * p + 1];\n }\n }\n for (let f = Math.max(12, min); f < max + 1; f++) {\n for (let p = 0; p < 6; p++) {\n //120 + 12 * (f - 12) = 12 * f - 24\n uvs[12 * f - 24 + 2 * p] = points6[2 * p];\n uvs[12 * f - 23 + 2 * p] = points6[2 * p + 1];\n }\n }\n }\n return uvs;\n }\n /**\n * set new goldberg face UVs\n * @param uvRange the new UVs to apply to the mesh\n */\n setGoldbergFaceUVs(uvRange) {\n const newUVs = this._changeGoldbergFaceUVs(uvRange);\n this.setVerticesData(VertexBuffer.UVKind, newUVs);\n }\n /**\n * Updates new goldberg face UVs\n * @param uvRange the new UVs to apply to the mesh\n */\n updateGoldbergFaceUVs(uvRange) {\n const newUVs = this._changeGoldbergFaceUVs(uvRange);\n this.updateVerticesData(VertexBuffer.UVKind, newUVs);\n }\n /**\n * Places a mesh on a particular face of the goldberg polygon\n * @param mesh Defines the mesh to position\n * @param face Defines the face to position onto\n * @param position Defines the position relative to the face we are positioning the mesh onto\n */\n placeOnGoldbergFaceAt(mesh, face, position) {\n const orientation = Vector3.RotationFromAxis(this.goldbergData.faceXaxis[face], this.goldbergData.faceYaxis[face], this.goldbergData.faceZaxis[face]);\n mesh.rotation = orientation;\n mesh.position = this.goldbergData.faceCenters[face]\n .add(this.goldbergData.faceXaxis[face].scale(position.x))\n .add(this.goldbergData.faceYaxis[face].scale(position.y))\n .add(this.goldbergData.faceZaxis[face].scale(position.z));\n }\n /**\n * Serialize current mesh\n * @param serializationObject defines the object which will receive the serialization data\n */\n serialize(serializationObject) {\n super.serialize(serializationObject);\n serializationObject.type = \"GoldbergMesh\";\n const goldbergData = {};\n goldbergData.adjacentFaces = this.goldbergData.adjacentFaces;\n goldbergData.nbSharedFaces = this.goldbergData.nbSharedFaces;\n goldbergData.nbUnsharedFaces = this.goldbergData.nbUnsharedFaces;\n goldbergData.nbFaces = this.goldbergData.nbFaces;\n goldbergData.nbFacesAtPole = this.goldbergData.nbFacesAtPole;\n if (this.goldbergData.faceColors) {\n goldbergData.faceColors = [];\n for (const color of this.goldbergData.faceColors) {\n goldbergData.faceColors.push(color.asArray());\n }\n }\n if (this.goldbergData.faceCenters) {\n goldbergData.faceCenters = [];\n for (const vector of this.goldbergData.faceCenters) {\n goldbergData.faceCenters.push(vector.asArray());\n }\n }\n if (this.goldbergData.faceZaxis) {\n goldbergData.faceZaxis = [];\n for (const vector of this.goldbergData.faceZaxis) {\n goldbergData.faceZaxis.push(vector.asArray());\n }\n }\n if (this.goldbergData.faceYaxis) {\n goldbergData.faceYaxis = [];\n for (const vector of this.goldbergData.faceYaxis) {\n goldbergData.faceYaxis.push(vector.asArray());\n }\n }\n if (this.goldbergData.faceXaxis) {\n goldbergData.faceXaxis = [];\n for (const vector of this.goldbergData.faceXaxis) {\n goldbergData.faceXaxis.push(vector.asArray());\n }\n }\n serializationObject.goldbergData = goldbergData;\n }\n /**\n * Parses a serialized goldberg mesh\n * @param parsedMesh the serialized mesh\n * @param scene the scene to create the goldberg mesh in\n * @returns the created goldberg mesh\n */\n static Parse(parsedMesh, scene) {\n const goldbergData = parsedMesh.goldbergData;\n goldbergData.faceColors = goldbergData.faceColors.map((el) => Color4.FromArray(el));\n goldbergData.faceCenters = goldbergData.faceCenters.map((el) => Vector3.FromArray(el));\n goldbergData.faceZaxis = goldbergData.faceZaxis.map((el) => Vector3.FromArray(el));\n goldbergData.faceXaxis = goldbergData.faceXaxis.map((el) => Vector3.FromArray(el));\n goldbergData.faceYaxis = goldbergData.faceYaxis.map((el) => Vector3.FromArray(el));\n const goldberg = new GoldbergMesh(parsedMesh.name, scene);\n goldberg.goldbergData = goldbergData;\n return goldberg;\n }\n}\n//# sourceMappingURL=goldbergMesh.js.map","import { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Color4 } from \"../../Maths/math.color.js\";\nimport { Mesh } from \"../../Meshes/mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { _PrimaryIsoTriangle, GeodesicData } from \"../geodesicMesh.js\";\nimport { GoldbergMesh } from \"../goldbergMesh.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n/**\n * Creates the Mesh for a Goldberg Polyhedron\n * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty\n * @param goldbergData polyhedronData defining the Goldberg polyhedron\n * @returns GoldbergSphere mesh\n */\nexport function CreateGoldbergVertexData(options, goldbergData) {\n const size = options.size;\n const sizeX = options.sizeX || size || 1;\n const sizeY = options.sizeY || size || 1;\n const sizeZ = options.sizeZ || size || 1;\n const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;\n const positions = new Array();\n const indices = new Array();\n const normals = new Array();\n const uvs = new Array();\n let minX = Infinity;\n let maxX = -Infinity;\n let minY = Infinity;\n let maxY = -Infinity;\n for (let v = 0; v < goldbergData.vertex.length; v++) {\n minX = Math.min(minX, goldbergData.vertex[v][0] * sizeX);\n maxX = Math.max(maxX, goldbergData.vertex[v][0] * sizeX);\n minY = Math.min(minY, goldbergData.vertex[v][1] * sizeY);\n maxY = Math.max(maxY, goldbergData.vertex[v][1] * sizeY);\n }\n let index = 0;\n for (let f = 0; f < goldbergData.face.length; f++) {\n const verts = goldbergData.face[f];\n const a = Vector3.FromArray(goldbergData.vertex[verts[0]]);\n const b = Vector3.FromArray(goldbergData.vertex[verts[2]]);\n const c = Vector3.FromArray(goldbergData.vertex[verts[1]]);\n const ba = b.subtract(a);\n const ca = c.subtract(a);\n const norm = Vector3.Cross(ca, ba).normalize();\n for (let v = 0; v < verts.length; v++) {\n normals.push(norm.x, norm.y, norm.z);\n const pdata = goldbergData.vertex[verts[v]];\n positions.push(pdata[0] * sizeX, pdata[1] * sizeY, pdata[2] * sizeZ);\n const vCoord = (pdata[1] * sizeY - minY) / (maxY - minY);\n uvs.push((pdata[0] * sizeX - minX) / (maxX - minX), CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - vCoord : vCoord);\n }\n for (let v = 0; v < verts.length - 2; v++) {\n indices.push(index, index + v + 2, index + v + 1);\n }\n index += verts.length;\n }\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);\n const vertexData = new VertexData();\n vertexData.positions = positions;\n vertexData.indices = indices;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n}\n/**\n * Creates the Mesh for a Goldberg Polyhedron which is made from 12 pentagonal and the rest hexagonal faces\n * @see https://en.wikipedia.org/wiki/Goldberg_polyhedron\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/polyhedra/goldberg_poly\n * @param name defines the name of the mesh\n * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty\n * @param scene defines the hosting scene\n * @returns Goldberg mesh\n */\nexport function CreateGoldberg(name, options, scene = null) {\n const size = options.size;\n const sizeX = options.sizeX || size || 1;\n const sizeY = options.sizeY || size || 1;\n const sizeZ = options.sizeZ || size || 1;\n let m = options.m || 1;\n if (m !== Math.floor(m)) {\n m === Math.floor(m);\n Logger.Warn(\"m not an integer only floor(m) used\");\n }\n let n = options.n || 0;\n if (n !== Math.floor(n)) {\n n === Math.floor(n);\n Logger.Warn(\"n not an integer only floor(n) used\");\n }\n if (n > m) {\n const temp = n;\n n = m;\n m = temp;\n Logger.Warn(\"n > m therefore m and n swapped\");\n }\n const primTri = new _PrimaryIsoTriangle();\n primTri.build(m, n);\n const geodesicData = GeodesicData.BuildGeodesicData(primTri);\n const goldbergData = geodesicData.toGoldbergPolyhedronData();\n const goldberg = new GoldbergMesh(name, scene);\n options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n goldberg._originalBuilderSideOrientation = options.sideOrientation;\n const vertexData = CreateGoldbergVertexData(options, goldbergData);\n vertexData.applyToMesh(goldberg, options.updatable);\n goldberg.goldbergData.nbSharedFaces = geodesicData.sharedNodes;\n goldberg.goldbergData.nbUnsharedFaces = geodesicData.poleNodes;\n goldberg.goldbergData.adjacentFaces = geodesicData.adjacentFaces;\n goldberg.goldbergData.nbFaces = goldberg.goldbergData.nbSharedFaces + goldberg.goldbergData.nbUnsharedFaces;\n goldberg.goldbergData.nbFacesAtPole = (goldberg.goldbergData.nbUnsharedFaces - 12) / 12;\n for (let f = 0; f < geodesicData.vertex.length; f++) {\n goldberg.goldbergData.faceCenters.push(Vector3.FromArray(geodesicData.vertex[f]));\n goldberg.goldbergData.faceCenters[f].x *= sizeX;\n goldberg.goldbergData.faceCenters[f].y *= sizeY;\n goldberg.goldbergData.faceCenters[f].z *= sizeZ;\n goldberg.goldbergData.faceColors.push(new Color4(1, 1, 1, 1));\n }\n for (let f = 0; f < goldbergData.face.length; f++) {\n const verts = goldbergData.face[f];\n const a = Vector3.FromArray(goldbergData.vertex[verts[0]]);\n const b = Vector3.FromArray(goldbergData.vertex[verts[2]]);\n const c = Vector3.FromArray(goldbergData.vertex[verts[1]]);\n const ba = b.subtract(a);\n const ca = c.subtract(a);\n const norm = Vector3.Cross(ca, ba).normalize();\n const z = Vector3.Cross(ca, norm).normalize();\n goldberg.goldbergData.faceXaxis.push(ca.normalize());\n goldberg.goldbergData.faceYaxis.push(norm);\n goldberg.goldbergData.faceZaxis.push(z);\n }\n return goldberg;\n}\nMesh.CreateGoldberg = CreateGoldberg;\n//# sourceMappingURL=goldbergBuilder.js.map","import { Path2 } from \"../../Maths/math.path.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { ExtrudePolygon } from \"./polygonBuilder.js\";\n// Shape functions\nclass ShapePath {\n /** Create the ShapePath used to support glyphs */\n constructor(resolution) {\n this._paths = [];\n this._tempPaths = [];\n this._holes = [];\n this._resolution = resolution;\n }\n /** Move the virtual cursor to a coordinate */\n moveTo(x, y) {\n this._currentPath = new Path2(x, y);\n this._tempPaths.push(this._currentPath);\n }\n /** Draw a line from the virtual cursor to a given coordinate */\n lineTo(x, y) {\n this._currentPath.addLineTo(x, y);\n }\n /** Create a quadratic curve from the virtual cursor to a given coordinate */\n quadraticCurveTo(cpx, cpy, x, y) {\n this._currentPath.addQuadraticCurveTo(cpx, cpy, x, y, this._resolution);\n }\n /** Create a bezier curve from the virtual cursor to a given coordinate */\n bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x, y) {\n this._currentPath.addBezierCurveTo(cpx1, cpy1, cpx2, cpy2, x, y, this._resolution);\n }\n /** Extract holes based on CW / CCW */\n extractHoles() {\n for (const path of this._tempPaths) {\n if (path.area() > 0) {\n this._holes.push(path);\n }\n else {\n this._paths.push(path);\n }\n }\n if (!this._paths.length && this._holes.length) {\n const temp = this._holes;\n this._holes = this._paths;\n this._paths = temp;\n }\n this._tempPaths.length = 0;\n }\n /** Gets the list of paths */\n get paths() {\n return this._paths;\n }\n /** Gets the list of holes */\n get holes() {\n return this._holes;\n }\n}\n// Utility functions\nfunction CreateShapePath(char, scale, offsetX, offsetY, resolution, fontData) {\n const glyph = fontData.glyphs[char] || fontData.glyphs[\"?\"];\n if (!glyph) {\n // return if there is no glyph data\n return null;\n }\n const shapePath = new ShapePath(resolution);\n if (glyph.o) {\n const outline = glyph.o.split(\" \");\n for (let i = 0, l = outline.length; i < l;) {\n const action = outline[i++];\n switch (action) {\n case \"m\": {\n // moveTo\n const x = parseInt(outline[i++]) * scale + offsetX;\n const y = parseInt(outline[i++]) * scale + offsetY;\n shapePath.moveTo(x, y);\n break;\n }\n case \"l\": {\n // lineTo\n const x = parseInt(outline[i++]) * scale + offsetX;\n const y = parseInt(outline[i++]) * scale + offsetY;\n shapePath.lineTo(x, y);\n break;\n }\n case \"q\": {\n // quadraticCurveTo\n const cpx = parseInt(outline[i++]) * scale + offsetX;\n const cpy = parseInt(outline[i++]) * scale + offsetY;\n const cpx1 = parseInt(outline[i++]) * scale + offsetX;\n const cpy1 = parseInt(outline[i++]) * scale + offsetY;\n shapePath.quadraticCurveTo(cpx1, cpy1, cpx, cpy);\n break;\n }\n case \"b\": {\n // bezierCurveTo\n const cpx = parseInt(outline[i++]) * scale + offsetX;\n const cpy = parseInt(outline[i++]) * scale + offsetY;\n const cpx1 = parseInt(outline[i++]) * scale + offsetX;\n const cpy1 = parseInt(outline[i++]) * scale + offsetY;\n const cpx2 = parseInt(outline[i++]) * scale + offsetX;\n const cpy2 = parseInt(outline[i++]) * scale + offsetY;\n shapePath.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);\n break;\n }\n }\n }\n }\n // Extract holes (based on clockwise data)\n shapePath.extractHoles();\n return { offsetX: glyph.ha * scale, shapePath: shapePath };\n}\n/**\n * Creates shape paths from a text and font\n * @param text the text\n * @param size size of the font\n * @param resolution resolution of the font\n * @param fontData defines the font data (can be generated with http://gero3.github.io/facetype.js/)\n * @returns array of ShapePath objects\n */\nexport function CreateTextShapePaths(text, size, resolution, fontData) {\n const chars = Array.from(text);\n const scale = size / fontData.resolution;\n const line_height = (fontData.boundingBox.yMax - fontData.boundingBox.yMin + fontData.underlineThickness) * scale;\n const shapePaths = [];\n let offsetX = 0, offsetY = 0;\n for (let i = 0; i < chars.length; i++) {\n const char = chars[i];\n if (char === \"\\n\") {\n offsetX = 0;\n offsetY -= line_height;\n }\n else {\n const ret = CreateShapePath(char, scale, offsetX, offsetY, resolution, fontData);\n if (ret) {\n offsetX += ret.offsetX;\n shapePaths.push(ret.shapePath);\n }\n }\n }\n return shapePaths;\n}\n/**\n * Create a text mesh\n * @param name defines the name of the mesh\n * @param text defines the text to use to build the mesh\n * @param fontData defines the font data (can be generated with http://gero3.github.io/facetype.js/)\n * @param options defines options used to create the mesh\n * @param scene defines the hosting scene\n * @param earcutInjection can be used to inject your own earcut reference\n * @returns a new Mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/text\n */\nexport function CreateText(name, text, fontData, options = {\n size: 50,\n resolution: 8,\n depth: 1.0,\n}, scene = null, earcutInjection = earcut) {\n // First we need to generate the paths\n const shapePaths = CreateTextShapePaths(text, options.size || 50, options.resolution || 8, fontData);\n // And extrude them\n const meshes = [];\n for (const shapePath of shapePaths) {\n if (!shapePath.paths.length) {\n continue;\n }\n const holes = shapePath.holes.slice(); // Copy it as we will update the copy\n for (const path of shapePath.paths) {\n const holeVectors = [];\n const shapeVectors = [];\n const points = path.getPoints();\n for (const point of points) {\n shapeVectors.push(new Vector3(point.x, 0, point.y)); // ExtrudePolygon expects data on the xz plane\n }\n // Holes\n const localHolesCopy = holes.slice();\n for (const hole of localHolesCopy) {\n const points = hole.getPoints();\n let found = false;\n for (const point of points) {\n if (path.isPointInside(point)) {\n found = true;\n break;\n }\n }\n if (!found) {\n continue;\n }\n const holePoints = [];\n for (const point of points) {\n holePoints.push(new Vector3(point.x, 0, point.y)); // ExtrudePolygon expects data on the xz plane\n }\n holeVectors.push(holePoints);\n // Remove the hole as it was already used\n holes.splice(holes.indexOf(hole), 1);\n }\n // There is at least a hole but it was unaffected\n if (!holeVectors.length && holes.length) {\n for (const hole of holes) {\n const points = hole.getPoints();\n const holePoints = [];\n for (const point of points) {\n holePoints.push(new Vector3(point.x, 0, point.y)); // ExtrudePolygon expects data on the xz plane\n }\n holeVectors.push(holePoints);\n }\n }\n // Extrusion!\n const mesh = ExtrudePolygon(name, {\n shape: shapeVectors,\n holes: holeVectors.length ? holeVectors : undefined,\n depth: options.depth || 1.0,\n sideOrientation: Mesh._GetDefaultSideOrientation(options.sideOrientation || Mesh.DOUBLESIDE),\n }, scene, earcutInjection);\n meshes.push(mesh);\n }\n }\n // Then we can merge everyone into one single mesh\n const newMesh = Mesh.MergeMeshes(meshes, true, true);\n if (newMesh) {\n // Move pivot to center\n const bbox = newMesh === null || newMesh === void 0 ? void 0 : newMesh.getBoundingInfo();\n newMesh.position.x = -(bbox === null || bbox === void 0 ? void 0 : bbox.boundingBox.extendSizeWorld._x);\n newMesh.position.y = -(bbox === null || bbox === void 0 ? void 0 : bbox.boundingBox.extendSizeWorld._y);\n newMesh.position.z = -(bbox === null || bbox === void 0 ? void 0 : bbox.boundingBox.extendSizeWorld._z);\n newMesh.name = name;\n newMesh.rotation.x = -Math.PI / 2;\n newMesh.bakeCurrentTransformIntoVertices();\n }\n return newMesh;\n}\n//# sourceMappingURL=textBuilder.js.map","/* eslint-disable @typescript-eslint/naming-convention */\nimport { CreateRibbon } from \"./Builders/ribbonBuilder.js\";\nimport { CreateDisc } from \"./Builders/discBuilder.js\";\nimport { CreateBox } from \"./Builders/boxBuilder.js\";\nimport { CreateTiledBox } from \"./Builders/tiledBoxBuilder.js\";\nimport { CreateSphere } from \"./Builders/sphereBuilder.js\";\nimport { CreateCylinder } from \"./Builders/cylinderBuilder.js\";\nimport { CreateTorus } from \"./Builders/torusBuilder.js\";\nimport { CreateTorusKnot } from \"./Builders/torusKnotBuilder.js\";\nimport { CreateDashedLines, CreateLineSystem, CreateLines } from \"./Builders/linesBuilder.js\";\nimport { CreatePolygon, ExtrudePolygon } from \"./Builders/polygonBuilder.js\";\nimport { ExtrudeShape, ExtrudeShapeCustom } from \"./Builders/shapeBuilder.js\";\nimport { CreateLathe } from \"./Builders/latheBuilder.js\";\nimport { CreatePlane } from \"./Builders/planeBuilder.js\";\nimport { CreateTiledPlane } from \"./Builders/tiledPlaneBuilder.js\";\nimport { CreateGround, CreateGroundFromHeightMap, CreateTiledGround } from \"./Builders/groundBuilder.js\";\nimport { CreateTube } from \"./Builders/tubeBuilder.js\";\nimport { CreatePolyhedron } from \"./Builders/polyhedronBuilder.js\";\nimport { CreateIcoSphere } from \"./Builders/icoSphereBuilder.js\";\nimport { CreateDecal } from \"./Builders/decalBuilder.js\";\nimport { CreateCapsule } from \"./Builders/capsuleBuilder.js\";\nimport { CreateGeodesic } from \"./Builders/geodesicBuilder.js\";\nimport { CreateGoldberg } from \"./Builders/goldbergBuilder.js\";\nimport { CreateText } from \"./Builders/textBuilder.js\";\n/**\n * Class containing static functions to help procedurally build meshes\n */\nexport const MeshBuilder = {\n CreateBox,\n CreateTiledBox,\n CreateSphere,\n CreateDisc,\n CreateIcoSphere,\n CreateRibbon,\n CreateCylinder,\n CreateTorus,\n CreateTorusKnot,\n CreateLineSystem,\n CreateLines,\n CreateDashedLines,\n ExtrudeShape,\n ExtrudeShapeCustom,\n CreateLathe,\n CreateTiledPlane,\n CreatePlane,\n CreateGround,\n CreateTiledGround,\n CreateGroundFromHeightMap,\n CreatePolygon,\n ExtrudePolygon,\n CreateTube,\n CreatePolyhedron,\n CreateGeodesic,\n CreateGoldberg,\n CreateDecal,\n CreateCapsule,\n CreateText,\n};\n//# sourceMappingURL=meshBuilder.js.map","import { Mesh } from \"../Meshes/mesh.js\";\nimport { CreateBox } from \"../Meshes/Builders/boxBuilder.js\";\nimport { CreateSphere } from \"../Meshes/Builders/sphereBuilder.js\";\nimport { Matrix, Quaternion, TmpVectors, Vector3 } from \"../Maths/math.vector.js\";\nimport { Color3, Color4 } from \"../Maths/math.color.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { StandardMaterial } from \"../Materials/standardMaterial.js\";\nimport { PhysicsImpostor } from \"../Physics/v1/physicsImpostor.js\";\nimport { UtilityLayerRenderer } from \"../Rendering/utilityLayerRenderer.js\";\nimport { CreateCylinder } from \"../Meshes/Builders/cylinderBuilder.js\";\nimport { CreateCapsule } from \"../Meshes/Builders/capsuleBuilder.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { VertexData } from \"../Meshes/mesh.vertexData.js\";\nimport { MeshBuilder } from \"../Meshes/meshBuilder.js\";\n/**\n * Used to show the physics impostor around the specific mesh\n */\nexport class PhysicsViewer {\n /**\n * Creates a new PhysicsViewer\n * @param scene defines the hosting scene\n */\n constructor(scene) {\n /** @internal */\n this._impostors = [];\n /** @internal */\n this._meshes = [];\n /** @internal */\n this._bodies = [];\n this._inertiaBodies = [];\n /** @internal */\n this._bodyMeshes = [];\n /** @internal */\n this._inertiaMeshes = [];\n /** @internal */\n this._numMeshes = 0;\n /** @internal */\n this._numBodies = 0;\n this._numInertiaBodies = 0;\n this._debugMeshMeshes = new Array();\n this._scene = scene || EngineStore.LastCreatedScene;\n if (!this._scene) {\n return;\n }\n const physicEngine = this._scene.getPhysicsEngine();\n if (physicEngine) {\n this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();\n }\n this._utilityLayer = new UtilityLayerRenderer(this._scene, false);\n this._utilityLayer.pickUtilitySceneFirst = false;\n this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil = true;\n }\n /**\n * Updates the debug meshes of the physics engine.\n *\n * This code is useful for synchronizing the debug meshes of the physics engine with the physics impostor and mesh.\n * It checks if the impostor is disposed and if the plugin version is 1, then it syncs the mesh with the impostor.\n * This ensures that the debug meshes are up to date with the physics engine.\n */\n _updateDebugMeshes() {\n const plugin = this._physicsEnginePlugin;\n if ((plugin === null || plugin === void 0 ? void 0 : plugin.getPluginVersion()) === 1) {\n this._updateDebugMeshesV1();\n }\n else {\n this._updateDebugMeshesV2();\n }\n }\n /**\n * Updates the debug meshes of the physics engine.\n *\n * This method is useful for synchronizing the debug meshes with the physics impostors.\n * It iterates through the impostors and meshes, and if the plugin version is 1, it syncs the mesh with the impostor.\n * This ensures that the debug meshes accurately reflect the physics impostors, which is important for debugging the physics engine.\n */\n _updateDebugMeshesV1() {\n const plugin = this._physicsEnginePlugin;\n for (let i = 0; i < this._numMeshes; i++) {\n const impostor = this._impostors[i];\n if (!impostor) {\n continue;\n }\n if (impostor.isDisposed) {\n this.hideImpostor(this._impostors[i--]);\n }\n else {\n if (impostor.type === PhysicsImpostor.MeshImpostor) {\n continue;\n }\n const mesh = this._meshes[i];\n if (mesh && plugin) {\n plugin.syncMeshWithImpostor(mesh, impostor);\n }\n }\n }\n }\n /**\n * Updates the debug meshes of the physics engine for V2 plugin.\n *\n * This method is useful for synchronizing the debug meshes of the physics engine with the current state of the bodies.\n * It iterates through the bodies array and updates the debug meshes with the current transform of each body.\n * This ensures that the debug meshes accurately reflect the current state of the physics engine.\n */\n _updateDebugMeshesV2() {\n const plugin = this._physicsEnginePlugin;\n for (let i = 0; i < this._numBodies; i++) {\n const body = this._bodies[i];\n const transform = this._bodyMeshes[i];\n if (body && transform) {\n plugin.syncTransform(body, transform);\n }\n }\n }\n _updateInertiaMeshes() {\n for (let i = 0; i < this._numInertiaBodies; i++) {\n const body = this._inertiaBodies[i];\n const mesh = this._inertiaMeshes[i];\n if (body && mesh) {\n this._updateDebugInertia(body, mesh);\n }\n }\n }\n _updateDebugInertia(body, inertiaMesh) {\n var _a;\n const inertiaMatrixRef = Matrix.Identity();\n const transformMatrixRef = Matrix.Identity();\n const finalMatrixRef = Matrix.Identity();\n if (body._pluginDataInstances.length) {\n const inertiaAsMesh = inertiaMesh;\n const inertiaMeshMatrixData = inertiaAsMesh._thinInstanceDataStorage.matrixData;\n const bodyTransformMatrixData = body.transformNode._thinInstanceDataStorage.matrixData;\n for (let i = 0; i < body._pluginDataInstances.length; i++) {\n const props = body.getMassProperties(i);\n this._getMeshDebugInertiaMatrixToRef(props, inertiaMatrixRef);\n Matrix.FromArrayToRef(bodyTransformMatrixData, i * 16, transformMatrixRef);\n inertiaMatrixRef.multiplyToRef(transformMatrixRef, finalMatrixRef);\n finalMatrixRef.copyToArray(inertiaMeshMatrixData, i * 16);\n }\n inertiaAsMesh.thinInstanceBufferUpdated(\"matrix\");\n }\n else {\n const props = body.getMassProperties();\n this._getMeshDebugInertiaMatrixToRef(props, inertiaMatrixRef);\n (_a = body.transformNode.rotationQuaternion) === null || _a === void 0 ? void 0 : _a.toRotationMatrix(transformMatrixRef);\n transformMatrixRef.setTranslation(body.transformNode.position);\n inertiaMatrixRef.multiplyToRef(transformMatrixRef, inertiaMatrixRef);\n inertiaMatrixRef.decomposeToTransformNode(inertiaMesh);\n }\n }\n /**\n * Renders a specified physic impostor\n * @param impostor defines the impostor to render\n * @param targetMesh defines the mesh represented by the impostor\n * @returns the new debug mesh used to render the impostor\n */\n showImpostor(impostor, targetMesh) {\n if (!this._scene) {\n return null;\n }\n for (let i = 0; i < this._numMeshes; i++) {\n if (this._impostors[i] == impostor) {\n return null;\n }\n }\n const debugMesh = this._getDebugMesh(impostor, targetMesh);\n if (debugMesh) {\n this._impostors[this._numMeshes] = impostor;\n this._meshes[this._numMeshes] = debugMesh;\n if (this._numMeshes === 0) {\n this._renderFunction = this._updateDebugMeshes.bind(this);\n this._scene.registerBeforeRender(this._renderFunction);\n }\n this._numMeshes++;\n }\n return debugMesh;\n }\n /**\n * Shows a debug mesh for a given physics body.\n * @param body The physics body to show.\n * @returns The debug mesh, or null if the body is already shown.\n *\n * This function is useful for visualizing the physics body in the scene.\n * It creates a debug mesh for the given body and adds it to the scene.\n * It also registers a before render function to update the debug mesh position and rotation.\n */\n showBody(body) {\n if (!this._scene) {\n return null;\n }\n for (let i = 0; i < this._numBodies; i++) {\n if (this._bodies[i] == body) {\n return null;\n }\n }\n const debugMesh = this._getDebugBodyMesh(body);\n if (debugMesh) {\n this._bodies[this._numBodies] = body;\n this._bodyMeshes[this._numBodies] = debugMesh;\n if (this._numBodies === 0) {\n this._renderFunction = this._updateDebugMeshes.bind(this);\n this._scene.registerBeforeRender(this._renderFunction);\n }\n this._numBodies++;\n }\n return debugMesh;\n }\n /**\n * Shows a debug box corresponding to the inertia of a given body\n * @param body\n */\n showInertia(body) {\n if (!this._scene) {\n return null;\n }\n for (let i = 0; i < this._numInertiaBodies; i++) {\n if (this._inertiaBodies[i] == body) {\n return null;\n }\n }\n const debugMesh = this._getDebugInertiaMesh(body);\n if (debugMesh) {\n this._inertiaBodies[this._numInertiaBodies] = body;\n this._inertiaMeshes[this._numInertiaBodies] = debugMesh;\n if (this._numInertiaBodies === 0) {\n this._inertiaRenderFunction = this._updateInertiaMeshes.bind(this);\n this._scene.registerBeforeRender(this._inertiaRenderFunction);\n }\n this._numInertiaBodies++;\n }\n return debugMesh;\n }\n /**\n * Hides an impostor from the scene.\n * @param impostor - The impostor to hide.\n *\n * This method is useful for hiding an impostor from the scene. It removes the\n * impostor from the utility layer scene, disposes the mesh, and removes the\n * impostor from the list of impostors. If the impostor is the last one in the\n * list, it also unregisters the render function.\n */\n hideImpostor(impostor) {\n if (!impostor || !this._scene || !this._utilityLayer) {\n return;\n }\n let removed = false;\n const utilityLayerScene = this._utilityLayer.utilityLayerScene;\n for (let i = 0; i < this._numMeshes; i++) {\n if (this._impostors[i] == impostor) {\n const mesh = this._meshes[i];\n if (!mesh) {\n continue;\n }\n utilityLayerScene.removeMesh(mesh);\n mesh.dispose();\n const index = this._debugMeshMeshes.indexOf(mesh);\n if (index > -1) {\n this._debugMeshMeshes.splice(index, 1);\n }\n this._numMeshes--;\n if (this._numMeshes > 0) {\n this._meshes[i] = this._meshes[this._numMeshes];\n this._impostors[i] = this._impostors[this._numMeshes];\n this._meshes[this._numMeshes] = null;\n this._impostors[this._numMeshes] = null;\n }\n else {\n this._meshes[0] = null;\n this._impostors[0] = null;\n }\n removed = true;\n break;\n }\n }\n if (removed && this._numMeshes === 0) {\n this._scene.unregisterBeforeRender(this._renderFunction);\n }\n }\n /**\n * Hides a body from the physics engine.\n * @param body - The body to hide.\n *\n * This function is useful for hiding a body from the physics engine.\n * It removes the body from the utility layer scene and disposes the mesh associated with it.\n * It also unregisters the render function if the number of bodies is 0.\n * This is useful for hiding a body from the physics engine without deleting it.\n */\n hideBody(body) {\n if (!body || !this._scene || !this._utilityLayer) {\n return;\n }\n let removed = false;\n const utilityLayerScene = this._utilityLayer.utilityLayerScene;\n for (let i = 0; i < this._numBodies; i++) {\n if (this._bodies[i] === body) {\n const mesh = this._bodyMeshes[i];\n if (!mesh) {\n continue;\n }\n utilityLayerScene.removeMesh(mesh);\n mesh.dispose();\n this._numBodies--;\n if (this._numBodies > 0) {\n this._bodyMeshes[i] = this._bodyMeshes[this._numBodies];\n this._bodies[i] = this._bodies[this._numBodies];\n this._bodyMeshes[this._numBodies] = null;\n this._bodies[this._numBodies] = null;\n }\n else {\n this._bodyMeshes[0] = null;\n this._bodies[0] = null;\n }\n removed = true;\n break;\n }\n }\n if (removed && this._numBodies === 0) {\n this._scene.unregisterBeforeRender(this._renderFunction);\n }\n }\n hideInertia(body) {\n if (!body || !this._scene || !this._utilityLayer) {\n return;\n }\n let removed = false;\n const utilityLayerScene = this._utilityLayer.utilityLayerScene;\n for (let i = 0; i < this._numInertiaBodies; i++) {\n if (this._inertiaBodies[i] === body) {\n const mesh = this._inertiaMeshes[i];\n if (!mesh) {\n continue;\n }\n utilityLayerScene.removeMesh(mesh);\n mesh.dispose();\n this._inertiaBodies.splice(i, 1);\n this._inertiaMeshes.splice(i, 1);\n this._numInertiaBodies--;\n removed = true;\n break;\n }\n }\n if (removed && this._numInertiaBodies === 0) {\n this._scene.unregisterBeforeRender(this._inertiaRenderFunction);\n }\n }\n _getDebugMaterial(scene) {\n if (!this._debugMaterial) {\n this._debugMaterial = new StandardMaterial(\"\", scene);\n this._debugMaterial.wireframe = true;\n this._debugMaterial.emissiveColor = Color3.White();\n this._debugMaterial.disableLighting = true;\n }\n return this._debugMaterial;\n }\n _getDebugInertiaMaterial(scene) {\n if (!this._debugInertiaMaterial) {\n this._debugInertiaMaterial = new StandardMaterial(\"\", scene);\n this._debugInertiaMaterial.disableLighting = true;\n this._debugInertiaMaterial.alpha = 0.0;\n }\n return this._debugInertiaMaterial;\n }\n _getDebugBoxMesh(scene) {\n if (!this._debugBoxMesh) {\n this._debugBoxMesh = CreateBox(\"physicsBodyBoxViewMesh\", { size: 1 }, scene);\n this._debugBoxMesh.rotationQuaternion = Quaternion.Identity();\n this._debugBoxMesh.material = this._getDebugMaterial(scene);\n this._debugBoxMesh.setEnabled(false);\n }\n return this._debugBoxMesh.createInstance(\"physicsBodyBoxViewInstance\");\n }\n _getDebugSphereMesh(scene) {\n if (!this._debugSphereMesh) {\n this._debugSphereMesh = CreateSphere(\"physicsBodySphereViewMesh\", { diameter: 1 }, scene);\n this._debugSphereMesh.rotationQuaternion = Quaternion.Identity();\n this._debugSphereMesh.material = this._getDebugMaterial(scene);\n this._debugSphereMesh.setEnabled(false);\n }\n return this._debugSphereMesh.createInstance(\"physicsBodySphereViewInstance\");\n }\n _getDebugCapsuleMesh(scene) {\n if (!this._debugCapsuleMesh) {\n this._debugCapsuleMesh = CreateCapsule(\"physicsBodyCapsuleViewMesh\", { height: 1 }, scene);\n this._debugCapsuleMesh.rotationQuaternion = Quaternion.Identity();\n this._debugCapsuleMesh.material = this._getDebugMaterial(scene);\n this._debugCapsuleMesh.setEnabled(false);\n }\n return this._debugCapsuleMesh.createInstance(\"physicsBodyCapsuleViewInstance\");\n }\n _getDebugCylinderMesh(scene) {\n if (!this._debugCylinderMesh) {\n this._debugCylinderMesh = CreateCylinder(\"physicsBodyCylinderViewMesh\", { diameterTop: 1, diameterBottom: 1, height: 1 }, scene);\n this._debugCylinderMesh.rotationQuaternion = Quaternion.Identity();\n this._debugCylinderMesh.material = this._getDebugMaterial(scene);\n this._debugCylinderMesh.setEnabled(false);\n }\n return this._debugCylinderMesh.createInstance(\"physicsBodyCylinderViewInstance\");\n }\n _getDebugMeshMesh(mesh, scene) {\n const wireframeOver = new Mesh(mesh.name, scene, null, mesh);\n wireframeOver.setParent(mesh);\n wireframeOver.position = Vector3.Zero();\n wireframeOver.material = this._getDebugMaterial(scene);\n this._debugMeshMeshes.push(wireframeOver);\n return wireframeOver;\n }\n _getDebugMesh(impostor, targetMesh) {\n if (!this._utilityLayer) {\n return null;\n }\n // Only create child impostor debug meshes when evaluating the parent\n if (targetMesh && targetMesh.parent && targetMesh.parent.physicsImpostor) {\n return null;\n }\n let mesh = null;\n const utilityLayerScene = this._utilityLayer.utilityLayerScene;\n if (!impostor.physicsBody) {\n Logger.Warn(\"Unable to get physicsBody of impostor. It might be initialized later by its parent's impostor.\");\n return null;\n }\n switch (impostor.type) {\n case PhysicsImpostor.BoxImpostor:\n mesh = this._getDebugBoxMesh(utilityLayerScene);\n impostor.getBoxSizeToRef(mesh.scaling);\n break;\n case PhysicsImpostor.SphereImpostor: {\n mesh = this._getDebugSphereMesh(utilityLayerScene);\n const radius = impostor.getRadius();\n mesh.scaling.x = radius * 2;\n mesh.scaling.y = radius * 2;\n mesh.scaling.z = radius * 2;\n break;\n }\n case PhysicsImpostor.CapsuleImpostor: {\n mesh = this._getDebugCapsuleMesh(utilityLayerScene);\n const bi = impostor.object.getBoundingInfo();\n mesh.scaling.x = (bi.boundingBox.maximum.x - bi.boundingBox.minimum.x) * 2 * impostor.object.scaling.x;\n mesh.scaling.y = (bi.boundingBox.maximum.y - bi.boundingBox.minimum.y) * impostor.object.scaling.y;\n mesh.scaling.z = (bi.boundingBox.maximum.z - bi.boundingBox.minimum.z) * 2 * impostor.object.scaling.z;\n break;\n }\n case PhysicsImpostor.MeshImpostor:\n if (targetMesh) {\n mesh = this._getDebugMeshMesh(targetMesh, utilityLayerScene);\n }\n break;\n case PhysicsImpostor.NoImpostor:\n if (targetMesh) {\n // Handle compound impostors\n const childMeshes = targetMesh.getChildMeshes().filter((c) => {\n return c.physicsImpostor ? 1 : 0;\n });\n childMeshes.forEach((m) => {\n if (m.physicsImpostor && m.getClassName() === \"Mesh\") {\n const boundingInfo = m.getBoundingInfo();\n const min = boundingInfo.boundingBox.minimum;\n const max = boundingInfo.boundingBox.maximum;\n switch (m.physicsImpostor.type) {\n case PhysicsImpostor.BoxImpostor:\n mesh = this._getDebugBoxMesh(utilityLayerScene);\n mesh.position.copyFrom(min);\n mesh.position.addInPlace(max);\n mesh.position.scaleInPlace(0.5);\n break;\n case PhysicsImpostor.SphereImpostor:\n mesh = this._getDebugSphereMesh(utilityLayerScene);\n break;\n case PhysicsImpostor.CylinderImpostor:\n mesh = this._getDebugCylinderMesh(utilityLayerScene);\n break;\n default:\n mesh = null;\n break;\n }\n if (mesh) {\n mesh.scaling.x = max.x - min.x;\n mesh.scaling.y = max.y - min.y;\n mesh.scaling.z = max.z - min.z;\n mesh.parent = m;\n }\n }\n });\n }\n else {\n Logger.Warn(\"No target mesh parameter provided for NoImpostor. Skipping.\");\n }\n mesh = null;\n break;\n case PhysicsImpostor.CylinderImpostor: {\n mesh = this._getDebugCylinderMesh(utilityLayerScene);\n const bi = impostor.object.getBoundingInfo();\n mesh.scaling.x = (bi.boundingBox.maximum.x - bi.boundingBox.minimum.x) * impostor.object.scaling.x;\n mesh.scaling.y = (bi.boundingBox.maximum.y - bi.boundingBox.minimum.y) * impostor.object.scaling.y;\n mesh.scaling.z = (bi.boundingBox.maximum.z - bi.boundingBox.minimum.z) * impostor.object.scaling.z;\n break;\n }\n }\n return mesh;\n }\n /**\n * Creates a debug mesh for a given physics body\n * @param body The physics body to create the debug mesh for\n * @returns The created debug mesh or null if the utility layer is not available\n *\n * This code is useful for creating a debug mesh for a given physics body.\n * It creates a Mesh object with a VertexData object containing the positions and indices\n * of the geometry of the body. The mesh is then assigned a debug material from the utility layer scene.\n * This allows for visualizing the physics body in the scene.\n */\n _getDebugBodyMesh(body) {\n if (!this._utilityLayer) {\n return null;\n }\n const utilityLayerScene = this._utilityLayer.utilityLayerScene;\n const mesh = new Mesh(\"custom\", utilityLayerScene);\n const vertexData = new VertexData();\n const geometry = body.getGeometry();\n vertexData.positions = geometry.positions;\n vertexData.indices = geometry.indices;\n vertexData.applyToMesh(mesh);\n if (body._pluginDataInstances) {\n const instanceBuffer = new Float32Array(body._pluginDataInstances.length * 16);\n mesh.thinInstanceSetBuffer(\"matrix\", instanceBuffer, 16);\n }\n mesh.material = this._getDebugMaterial(utilityLayerScene);\n return mesh;\n }\n _getMeshDebugInertiaMatrixToRef(massProps, matrix) {\n var _a, _b, _c;\n const orientation = (_a = massProps.inertiaOrientation) !== null && _a !== void 0 ? _a : Quaternion.Identity();\n const inertiaLocal = (_b = massProps.inertia) !== null && _b !== void 0 ? _b : Vector3.Zero();\n const center = (_c = massProps.centerOfMass) !== null && _c !== void 0 ? _c : Vector3.Zero();\n const betaSqrd = (inertiaLocal.x - inertiaLocal.y + inertiaLocal.z) * 6;\n const beta = Math.sqrt(Math.max(betaSqrd, 0)); // Safety check for zeroed elements!\n const gammaSqrd = inertiaLocal.x * 12 - betaSqrd;\n const gamma = Math.sqrt(Math.max(gammaSqrd, 0)); // Safety check for zeroed elements!\n const alphaSqrd = inertiaLocal.z * 12 - betaSqrd;\n const alpha = Math.sqrt(Math.max(alphaSqrd, 0)); // Safety check for zeroed elements!\n const extents = TmpVectors.Vector3[0];\n extents.set(alpha, beta, gamma);\n const scaling = Matrix.ScalingToRef(extents.x, extents.y, extents.z, TmpVectors.Matrix[0]);\n const rotation = orientation.toRotationMatrix(TmpVectors.Matrix[1]);\n const translation = Matrix.TranslationToRef(center.x, center.y, center.z, TmpVectors.Matrix[2]);\n scaling.multiplyToRef(rotation, matrix);\n matrix.multiplyToRef(translation, matrix);\n return matrix;\n }\n _getDebugInertiaMesh(body) {\n if (!this._utilityLayer) {\n return null;\n }\n const utilityLayerScene = this._utilityLayer.utilityLayerScene;\n // The base inertia mesh is going to be a 1x1 cube that's scaled and rotated according to the inertia\n const inertiaBoxMesh = MeshBuilder.CreateBox(\"custom\", { size: 1 }, utilityLayerScene);\n const matrixRef = Matrix.Identity();\n if (body._pluginDataInstances.length) {\n const instanceBuffer = new Float32Array(body._pluginDataInstances.length * 16);\n for (let i = 0; i < body._pluginDataInstances.length; ++i) {\n const props = body.getMassProperties(i);\n this._getMeshDebugInertiaMatrixToRef(props, matrixRef);\n matrixRef.copyToArray(instanceBuffer, i * 16);\n }\n inertiaBoxMesh.thinInstanceSetBuffer(\"matrix\", instanceBuffer, 16);\n }\n else {\n const props = body.getMassProperties();\n this._getMeshDebugInertiaMatrixToRef(props, matrixRef);\n matrixRef.decomposeToTransformNode(inertiaBoxMesh);\n }\n inertiaBoxMesh.enableEdgesRendering();\n inertiaBoxMesh.edgesWidth = 2.0;\n inertiaBoxMesh.edgesColor = new Color4(1, 0, 1, 1);\n inertiaBoxMesh.material = this._getDebugInertiaMaterial(utilityLayerScene);\n return inertiaBoxMesh;\n }\n /**\n * Clean up physics debug display\n */\n dispose() {\n // impostors\n for (let index = this._numMeshes - 1; index >= 0; index--) {\n this.hideImpostor(this._impostors[0]);\n }\n // bodies\n for (let index = this._numBodies - 1; index >= 0; index--) {\n this.hideBody(this._bodies[0]);\n }\n // inertia\n for (let index = this._numInertiaBodies - 1; index >= 0; index--) {\n this.hideInertia(this._inertiaBodies[0]);\n }\n if (this._debugBoxMesh) {\n this._debugBoxMesh.dispose();\n }\n if (this._debugSphereMesh) {\n this._debugSphereMesh.dispose();\n }\n if (this._debugCylinderMesh) {\n this._debugCylinderMesh.dispose();\n }\n if (this._debugMaterial) {\n this._debugMaterial.dispose();\n }\n this._impostors.length = 0;\n this._scene = null;\n this._physicsEnginePlugin = null;\n if (this._utilityLayer) {\n this._utilityLayer.dispose();\n this._utilityLayer = null;\n }\n }\n}\n//# sourceMappingURL=physicsViewer.js.map","import { Vector3 } from \"../Maths/math.vector.js\";\nimport { CreateLines } from \"../Meshes/Builders/linesBuilder.js\";\n/**\n * As raycast might be hard to debug, the RayHelper can help rendering the different rays\n * in order to better appreciate the issue one might have.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/picking_collisions#debugging\n */\nexport class RayHelper {\n /**\n * Helper function to create a colored helper in a scene in one line.\n * @param ray Defines the ray we are currently tryin to visualize\n * @param scene Defines the scene the ray is used in\n * @param color Defines the color we want to see the ray in\n * @returns The newly created ray helper.\n */\n static CreateAndShow(ray, scene, color) {\n const helper = new RayHelper(ray);\n helper.show(scene, color);\n return helper;\n }\n /**\n * Instantiate a new ray helper.\n * As raycast might be hard to debug, the RayHelper can help rendering the different rays\n * in order to better appreciate the issue one might have.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/picking_collisions#debugging\n * @param ray Defines the ray we are currently tryin to visualize\n */\n constructor(ray) {\n this.ray = ray;\n }\n /**\n * Shows the ray we are willing to debug.\n * @param scene Defines the scene the ray needs to be rendered in\n * @param color Defines the color the ray needs to be rendered in\n */\n show(scene, color) {\n if (!this._renderFunction && this.ray) {\n const ray = this.ray;\n this._renderFunction = this._render.bind(this);\n this._scene = scene;\n this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];\n this._renderLine = CreateLines(\"ray\", { points: this._renderPoints, updatable: true }, scene);\n this._renderLine.isPickable = false;\n if (this._renderFunction) {\n this._scene.registerBeforeRender(this._renderFunction);\n }\n }\n if (color && this._renderLine) {\n this._renderLine.color.copyFrom(color);\n }\n }\n /**\n * Hides the ray we are debugging.\n */\n hide() {\n if (this._renderFunction && this._scene) {\n this._scene.unregisterBeforeRender(this._renderFunction);\n this._scene = null;\n this._renderFunction = null;\n if (this._renderLine) {\n this._renderLine.dispose();\n this._renderLine = null;\n }\n this._renderPoints = [];\n }\n }\n _render() {\n var _a;\n const ray = this.ray;\n if (!ray) {\n return;\n }\n const point = this._renderPoints[1];\n const len = Math.min(ray.length, 1000000);\n point.copyFrom(ray.direction);\n point.scaleInPlace(len);\n point.addInPlace(ray.origin);\n this._renderPoints[0].copyFrom(ray.origin);\n CreateLines(\"ray\", { points: this._renderPoints, updatable: true, instance: this._renderLine }, this._scene);\n (_a = this._renderLine) === null || _a === void 0 ? void 0 : _a.refreshBoundingInfo();\n }\n /**\n * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.\n * @param mesh Defines the mesh we want the helper attached to\n * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)\n * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)\n * @param length Defines the length of the ray\n */\n attachToMesh(mesh, meshSpaceDirection, meshSpaceOrigin, length) {\n this._attachedToMesh = mesh;\n const ray = this.ray;\n if (!ray) {\n return;\n }\n if (!ray.direction) {\n ray.direction = Vector3.Zero();\n }\n if (!ray.origin) {\n ray.origin = Vector3.Zero();\n }\n if (length) {\n ray.length = length;\n }\n if (!meshSpaceOrigin) {\n meshSpaceOrigin = Vector3.Zero();\n }\n if (!meshSpaceDirection) {\n // -1 so that this will work with Mesh.lookAt\n meshSpaceDirection = new Vector3(0, 0, -1);\n }\n if (!this._scene) {\n this._scene = mesh.getScene();\n }\n if (!this._meshSpaceDirection) {\n this._meshSpaceDirection = meshSpaceDirection.clone();\n this._meshSpaceOrigin = meshSpaceOrigin.clone();\n }\n else {\n this._meshSpaceDirection.copyFrom(meshSpaceDirection);\n this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);\n }\n if (!this._onAfterRenderObserver) {\n this._onAfterRenderObserver = this._scene.onBeforeRenderObservable.add(() => this._updateToMesh());\n this._onAfterStepObserver = this._scene.onAfterStepObservable.add(() => this._updateToMesh());\n }\n // force world matrix computation before the first ray helper computation\n this._attachedToMesh.computeWorldMatrix(true);\n this._updateToMesh();\n }\n /**\n * Detach the ray helper from the mesh it has previously been attached to.\n */\n detachFromMesh() {\n if (this._attachedToMesh && this._scene) {\n if (this._onAfterRenderObserver) {\n this._scene.onBeforeRenderObservable.remove(this._onAfterRenderObserver);\n this._scene.onAfterStepObservable.remove(this._onAfterStepObserver);\n }\n this._attachedToMesh = null;\n this._onAfterRenderObserver = null;\n this._onAfterStepObserver = null;\n this._scene = null;\n }\n }\n _updateToMesh() {\n const ray = this.ray;\n if (!this._attachedToMesh || !ray) {\n return;\n }\n if (this._attachedToMesh.isDisposed()) {\n this.detachFromMesh();\n return;\n }\n this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);\n Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);\n }\n /**\n * Dispose the helper and release its associated resources.\n */\n dispose() {\n this.hide();\n this.detachFromMesh();\n this.ray = null;\n }\n}\n//# sourceMappingURL=rayHelper.js.map","import { Vector3, Matrix, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Color3, Color4 } from \"../Maths/math.color.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { CreateLineSystem } from \"../Meshes/Builders/linesBuilder.js\";\nimport { UtilityLayerRenderer } from \"../Rendering/utilityLayerRenderer.js\";\nimport { Material } from \"../Materials/material.js\";\nimport { ShaderMaterial } from \"../Materials/shaderMaterial.js\";\nimport { DynamicTexture } from \"../Materials/Textures/dynamicTexture.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Effect } from \"../Materials/effect.js\";\nimport { CreateSphere } from \"../Meshes/Builders/sphereBuilder.js\";\nimport { ExtrudeShapeCustom } from \"../Meshes/Builders/shapeBuilder.js\";\n/**\n * Class used to render a debug view of a given skeleton\n * @see http://www.babylonjs-playground.com/#1BZJVJ#8\n */\nexport class SkeletonViewer {\n /** public static method to create a BoneWeight Shader\n * @param options The constructor options\n * @param scene The scene that the shader is scoped to\n * @returns The created ShaderMaterial\n * @see http://www.babylonjs-playground.com/#1BZJVJ#395\n */\n static CreateBoneWeightShader(options, scene) {\n var _a, _c, _d, _e, _f, _g;\n const skeleton = options.skeleton;\n const colorBase = (_a = options.colorBase) !== null && _a !== void 0 ? _a : Color3.Black();\n const colorZero = (_c = options.colorZero) !== null && _c !== void 0 ? _c : Color3.Blue();\n const colorQuarter = (_d = options.colorQuarter) !== null && _d !== void 0 ? _d : Color3.Green();\n const colorHalf = (_e = options.colorHalf) !== null && _e !== void 0 ? _e : Color3.Yellow();\n const colorFull = (_f = options.colorFull) !== null && _f !== void 0 ? _f : Color3.Red();\n const targetBoneIndex = (_g = options.targetBoneIndex) !== null && _g !== void 0 ? _g : 0;\n Effect.ShadersStore[\"boneWeights:\" + skeleton.name + \"VertexShader\"] = `precision highp float;\r\n\r\n attribute vec3 position;\r\n attribute vec2 uv;\r\n\r\n uniform mat4 view;\r\n uniform mat4 projection;\r\n uniform mat4 worldViewProjection;\r\n\r\n #include\r\n #if NUM_BONE_INFLUENCERS == 0\r\n attribute vec4 matricesIndices;\r\n attribute vec4 matricesWeights;\r\n #endif\r\n #include\r\n\r\n #include\r\n\r\n varying vec3 vColor;\r\n\r\n uniform vec3 colorBase;\r\n uniform vec3 colorZero;\r\n uniform vec3 colorQuarter;\r\n uniform vec3 colorHalf;\r\n uniform vec3 colorFull;\r\n\r\n uniform float targetBoneIndex;\r\n\r\n void main() {\r\n vec3 positionUpdated = position;\r\n\r\n #include\r\n #include\r\n #include\r\n\r\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\r\n\r\n vec3 color = colorBase;\r\n float totalWeight = 0.;\r\n if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){\r\n totalWeight += matricesWeights[0];\r\n }\r\n if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){\r\n totalWeight += matricesWeights[1];\r\n }\r\n if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){\r\n totalWeight += matricesWeights[2];\r\n }\r\n if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){\r\n totalWeight += matricesWeights[3];\r\n }\r\n\r\n color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight));\r\n color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight));\r\n color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight));\r\n color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight));\r\n vColor = color;\r\n\r\n gl_Position = projection * view * worldPos;\r\n }`;\n Effect.ShadersStore[\"boneWeights:\" + skeleton.name + \"FragmentShader\"] = `\r\n precision highp float;\r\n varying vec3 vPosition;\r\n\r\n varying vec3 vColor;\r\n\r\n void main() {\r\n vec4 color = vec4(vColor, 1.0);\r\n gl_FragColor = color;\r\n }\r\n `;\n const shader = new ShaderMaterial(\"boneWeight:\" + skeleton.name, scene, {\n vertex: \"boneWeights:\" + skeleton.name,\n fragment: \"boneWeights:\" + skeleton.name,\n }, {\n attributes: [\"position\", \"normal\", \"matricesIndices\", \"matricesWeights\"],\n uniforms: [\n \"world\",\n \"worldView\",\n \"worldViewProjection\",\n \"view\",\n \"projection\",\n \"viewProjection\",\n \"colorBase\",\n \"colorZero\",\n \"colorQuarter\",\n \"colorHalf\",\n \"colorFull\",\n \"targetBoneIndex\",\n ],\n });\n shader.setColor3(\"colorBase\", colorBase);\n shader.setColor3(\"colorZero\", colorZero);\n shader.setColor3(\"colorQuarter\", colorQuarter);\n shader.setColor3(\"colorHalf\", colorHalf);\n shader.setColor3(\"colorFull\", colorFull);\n shader.setFloat(\"targetBoneIndex\", targetBoneIndex);\n shader.getClassName = () => {\n return \"BoneWeightShader\";\n };\n shader.transparencyMode = Material.MATERIAL_OPAQUE;\n return shader;\n }\n /** public static method to create a BoneWeight Shader\n * @param options The constructor options\n * @param scene The scene that the shader is scoped to\n * @returns The created ShaderMaterial\n */\n static CreateSkeletonMapShader(options, scene) {\n var _a;\n const skeleton = options.skeleton;\n const colorMap = (_a = options.colorMap) !== null && _a !== void 0 ? _a : [\n {\n color: new Color3(1, 0.38, 0.18),\n location: 0,\n },\n {\n color: new Color3(0.59, 0.18, 1.0),\n location: 0.2,\n },\n {\n color: new Color3(0.59, 1, 0.18),\n location: 0.4,\n },\n {\n color: new Color3(1, 0.87, 0.17),\n location: 0.6,\n },\n {\n color: new Color3(1, 0.17, 0.42),\n location: 0.8,\n },\n {\n color: new Color3(0.17, 0.68, 1.0),\n location: 1.0,\n },\n ];\n const bufferWidth = skeleton.bones.length + 1;\n const colorMapBuffer = SkeletonViewer._CreateBoneMapColorBuffer(bufferWidth, colorMap, scene);\n const shader = new ShaderMaterial(\"boneWeights:\" + skeleton.name, scene, {\n vertexSource: `precision highp float;\r\n\r\n attribute vec3 position;\r\n attribute vec2 uv;\r\n\r\n uniform mat4 view;\r\n uniform mat4 projection;\r\n uniform mat4 worldViewProjection;\r\n uniform float colorMap[` +\n skeleton.bones.length * 4 +\n `];\r\n\r\n #include\r\n #if NUM_BONE_INFLUENCERS == 0\r\n attribute vec4 matricesIndices;\r\n attribute vec4 matricesWeights;\r\n #endif\r\n #include\r\n #include\r\n\r\n varying vec3 vColor;\r\n\r\n void main() {\r\n vec3 positionUpdated = position;\r\n\r\n #include\r\n #include\r\n #include\r\n\r\n vec3 color = vec3(0.);\r\n bool first = true;\r\n\r\n for (int i = 0; i < 4; i++) {\r\n int boneIdx = int(matricesIndices[i]);\r\n float boneWgt = matricesWeights[i];\r\n\r\n vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]);\r\n\r\n if (boneWgt > 0.) {\r\n if (first) {\r\n first = false;\r\n color = c;\r\n } else {\r\n color = mix(color, c, boneWgt);\r\n }\r\n }\r\n }\r\n\r\n vColor = color;\r\n\r\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\r\n\r\n gl_Position = projection * view * worldPos;\r\n }`,\n fragmentSource: `\r\n precision highp float;\r\n varying vec3 vColor;\r\n\r\n void main() {\r\n vec4 color = vec4( vColor, 1.0 );\r\n gl_FragColor = color;\r\n }\r\n `,\n }, {\n attributes: [\"position\", \"normal\", \"matricesIndices\", \"matricesWeights\"],\n uniforms: [\"world\", \"worldView\", \"worldViewProjection\", \"view\", \"projection\", \"viewProjection\", \"colorMap\"],\n });\n shader.setFloats(\"colorMap\", colorMapBuffer);\n shader.getClassName = () => {\n return \"SkeletonMapShader\";\n };\n shader.transparencyMode = Material.MATERIAL_OPAQUE;\n return shader;\n }\n /** private static method to create a BoneWeight Shader\n * @param size The size of the buffer to create (usually the bone count)\n * @param colorMap The gradient data to generate\n * @param scene The scene that the shader is scoped to\n * @returns an Array of floats from the color gradient values\n */\n static _CreateBoneMapColorBuffer(size, colorMap, scene) {\n const tempGrad = new DynamicTexture(\"temp\", { width: size, height: 1 }, scene, false);\n const ctx = tempGrad.getContext();\n const grad = ctx.createLinearGradient(0, 0, size, 0);\n colorMap.forEach((stop) => {\n grad.addColorStop(stop.location, stop.color.toHexString());\n });\n ctx.fillStyle = grad;\n ctx.fillRect(0, 0, size, 1);\n tempGrad.update();\n const buffer = [];\n const data = ctx.getImageData(0, 0, size, 1).data;\n const rUnit = 1 / 255;\n for (let i = 0; i < data.length; i++) {\n buffer.push(data[i] * rUnit);\n }\n tempGrad.dispose();\n return buffer;\n }\n /** Gets the Scene. */\n get scene() {\n return this._scene;\n }\n /** Gets the utilityLayer. */\n get utilityLayer() {\n return this._utilityLayer;\n }\n /** Checks Ready Status. */\n get isReady() {\n return this._ready;\n }\n /** Sets Ready Status. */\n set ready(value) {\n this._ready = value;\n }\n /** Gets the debugMesh */\n get debugMesh() {\n return this._debugMesh;\n }\n /** Sets the debugMesh */\n set debugMesh(value) {\n this._debugMesh = value;\n }\n /** Gets the displayMode */\n get displayMode() {\n return this.options.displayMode || SkeletonViewer.DISPLAY_LINES;\n }\n /** Sets the displayMode */\n set displayMode(value) {\n if (value > SkeletonViewer.DISPLAY_SPHERE_AND_SPURS) {\n value = SkeletonViewer.DISPLAY_LINES;\n }\n this.options.displayMode = value;\n }\n /**\n * Creates a new SkeletonViewer\n * @param skeleton defines the skeleton to render\n * @param mesh defines the mesh attached to the skeleton\n * @param scene defines the hosting scene\n * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)\n * @param renderingGroupId defines the rendering group id to use with the viewer\n * @param options All of the extra constructor options for the SkeletonViewer\n */\n constructor(\n /** defines the skeleton to render */\n skeleton, \n /** defines the mesh attached to the skeleton */\n mesh, \n /** The Scene scope*/\n scene, \n /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */\n autoUpdateBonesMatrices = true, \n /** defines the rendering group id to use with the viewer */\n renderingGroupId = 3, \n /** is the options for the viewer */\n options = {}) {\n var _a, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;\n this.skeleton = skeleton;\n this.mesh = mesh;\n this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;\n this.renderingGroupId = renderingGroupId;\n this.options = options;\n /** Gets or sets the color used to render the skeleton */\n this.color = Color3.White();\n /** Array of the points of the skeleton fo the line view. */\n this._debugLines = new Array();\n /** The local axes Meshes. */\n this._localAxes = null;\n /** If SkeletonViewer is enabled. */\n this._isEnabled = true;\n /** SkeletonViewer render observable. */\n this._obs = null;\n this._scene = scene;\n this._ready = false;\n //Defaults\n options.pauseAnimations = (_a = options.pauseAnimations) !== null && _a !== void 0 ? _a : true;\n options.returnToRest = (_c = options.returnToRest) !== null && _c !== void 0 ? _c : false;\n options.displayMode = (_d = options.displayMode) !== null && _d !== void 0 ? _d : SkeletonViewer.DISPLAY_LINES;\n options.displayOptions = (_e = options.displayOptions) !== null && _e !== void 0 ? _e : {};\n options.displayOptions.midStep = (_f = options.displayOptions.midStep) !== null && _f !== void 0 ? _f : 0.235;\n options.displayOptions.midStepFactor = (_g = options.displayOptions.midStepFactor) !== null && _g !== void 0 ? _g : 0.155;\n options.displayOptions.sphereBaseSize = (_h = options.displayOptions.sphereBaseSize) !== null && _h !== void 0 ? _h : 0.15;\n options.displayOptions.sphereScaleUnit = (_j = options.displayOptions.sphereScaleUnit) !== null && _j !== void 0 ? _j : 2;\n options.displayOptions.sphereFactor = (_k = options.displayOptions.sphereFactor) !== null && _k !== void 0 ? _k : 0.865;\n options.displayOptions.spurFollowsChild = (_l = options.displayOptions.spurFollowsChild) !== null && _l !== void 0 ? _l : false;\n options.displayOptions.showLocalAxes = (_m = options.displayOptions.showLocalAxes) !== null && _m !== void 0 ? _m : false;\n options.displayOptions.localAxesSize = (_o = options.displayOptions.localAxesSize) !== null && _o !== void 0 ? _o : 0.075;\n options.computeBonesUsingShaders = (_p = options.computeBonesUsingShaders) !== null && _p !== void 0 ? _p : true;\n options.useAllBones = (_q = options.useAllBones) !== null && _q !== void 0 ? _q : true;\n const initialMeshBoneIndices = mesh.getVerticesData(VertexBuffer.MatricesIndicesKind);\n const initialMeshBoneWeights = mesh.getVerticesData(VertexBuffer.MatricesWeightsKind);\n this._boneIndices = new Set();\n if (!options.useAllBones) {\n if (initialMeshBoneIndices && initialMeshBoneWeights) {\n for (let i = 0; i < initialMeshBoneIndices.length; ++i) {\n const index = initialMeshBoneIndices[i], weight = initialMeshBoneWeights[i];\n if (weight !== 0) {\n this._boneIndices.add(index);\n }\n }\n }\n }\n /* Create Utility Layer */\n this._utilityLayer = new UtilityLayerRenderer(this._scene, false);\n this._utilityLayer.pickUtilitySceneFirst = false;\n this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil = true;\n let displayMode = this.options.displayMode || 0;\n if (displayMode > SkeletonViewer.DISPLAY_SPHERE_AND_SPURS) {\n displayMode = SkeletonViewer.DISPLAY_LINES;\n }\n this.displayMode = displayMode;\n //Prep the Systems\n this.update();\n this._bindObs();\n }\n /** The Dynamic bindings for the update functions */\n _bindObs() {\n switch (this.displayMode) {\n case SkeletonViewer.DISPLAY_LINES: {\n this._obs = this.scene.onBeforeRenderObservable.add(() => {\n this._displayLinesUpdate();\n });\n break;\n }\n }\n }\n /** Update the viewer to sync with current skeleton state, only used to manually update. */\n update() {\n switch (this.displayMode) {\n case SkeletonViewer.DISPLAY_LINES: {\n this._displayLinesUpdate();\n break;\n }\n case SkeletonViewer.DISPLAY_SPHERES: {\n this._buildSpheresAndSpurs(true);\n break;\n }\n case SkeletonViewer.DISPLAY_SPHERE_AND_SPURS: {\n this._buildSpheresAndSpurs(false);\n break;\n }\n }\n this._buildLocalAxes();\n }\n /** Gets or sets a boolean indicating if the viewer is enabled */\n set isEnabled(value) {\n if (this.isEnabled === value) {\n return;\n }\n this._isEnabled = value;\n if (this.debugMesh) {\n this.debugMesh.setEnabled(value);\n }\n if (value && !this._obs) {\n this._bindObs();\n }\n else if (!value && this._obs) {\n this.scene.onBeforeRenderObservable.remove(this._obs);\n this._obs = null;\n }\n }\n get isEnabled() {\n return this._isEnabled;\n }\n _getBonePosition(position, bone, meshMat, x = 0, y = 0, z = 0) {\n const tmat = TmpVectors.Matrix[0];\n const parentBone = bone.getParent();\n tmat.copyFrom(bone.getLocalMatrix());\n if (x !== 0 || y !== 0 || z !== 0) {\n const tmat2 = TmpVectors.Matrix[1];\n Matrix.IdentityToRef(tmat2);\n tmat2.setTranslationFromFloats(x, y, z);\n tmat2.multiplyToRef(tmat, tmat);\n }\n if (parentBone) {\n tmat.multiplyToRef(parentBone.getAbsoluteMatrix(), tmat);\n }\n tmat.multiplyToRef(meshMat, tmat);\n position.x = tmat.m[12];\n position.y = tmat.m[13];\n position.z = tmat.m[14];\n }\n _getLinesForBonesWithLength(bones, meshMat) {\n const len = bones.length;\n const mesh = this.mesh;\n const meshPos = mesh.position;\n let idx = 0;\n for (let i = 0; i < len; i++) {\n const bone = bones[i];\n let points = this._debugLines[idx];\n if (bone._index === -1 || (!this._boneIndices.has(bone.getIndex()) && !this.options.useAllBones)) {\n continue;\n }\n if (!points) {\n points = [Vector3.Zero(), Vector3.Zero()];\n this._debugLines[idx] = points;\n }\n this._getBonePosition(points[0], bone, meshMat);\n this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);\n points[0].subtractInPlace(meshPos);\n points[1].subtractInPlace(meshPos);\n idx++;\n }\n }\n _getLinesForBonesNoLength(bones) {\n const len = bones.length;\n let boneNum = 0;\n const mesh = this.mesh;\n const meshPos = mesh.position;\n for (let i = len - 1; i >= 0; i--) {\n const childBone = bones[i];\n const parentBone = childBone.getParent();\n if (!parentBone || (!this._boneIndices.has(childBone.getIndex()) && !this.options.useAllBones)) {\n continue;\n }\n let points = this._debugLines[boneNum];\n if (!points) {\n points = [Vector3.Zero(), Vector3.Zero()];\n this._debugLines[boneNum] = points;\n }\n childBone.getAbsolutePositionToRef(mesh, points[0]);\n parentBone.getAbsolutePositionToRef(mesh, points[1]);\n points[0].subtractInPlace(meshPos);\n points[1].subtractInPlace(meshPos);\n boneNum++;\n }\n }\n /**\n * function to revert the mesh and scene back to the initial state.\n * @param animationState\n */\n _revert(animationState) {\n if (this.options.pauseAnimations) {\n this.scene.animationsEnabled = animationState;\n this.utilityLayer.utilityLayerScene.animationsEnabled = animationState;\n }\n }\n /**\n * function to get the absolute bind pose of a bone by accumulating transformations up the bone hierarchy.\n * @param bone\n * @param matrix\n */\n _getAbsoluteBindPoseToRef(bone, matrix) {\n if (bone === null || bone._index === -1) {\n matrix.copyFrom(Matrix.Identity());\n return;\n }\n this._getAbsoluteBindPoseToRef(bone.getParent(), matrix);\n bone.getBaseMatrix().multiplyToRef(matrix, matrix);\n return;\n }\n /**\n * function to build and bind sphere joint points and spur bone representations.\n * @param spheresOnly\n */\n _buildSpheresAndSpurs(spheresOnly = true) {\n var _a, _c;\n if (this._debugMesh) {\n this._debugMesh.dispose();\n this._debugMesh = null;\n this.ready = false;\n }\n this._ready = false;\n const utilityLayerScene = (_a = this.utilityLayer) === null || _a === void 0 ? void 0 : _a.utilityLayerScene;\n const bones = this.skeleton.bones;\n const spheres = [];\n const spurs = [];\n const animationState = this.scene.animationsEnabled;\n try {\n if (this.options.pauseAnimations) {\n this.scene.animationsEnabled = false;\n utilityLayerScene.animationsEnabled = false;\n }\n if (this.options.returnToRest) {\n this.skeleton.returnToRest();\n }\n if (this.autoUpdateBonesMatrices) {\n this.skeleton.computeAbsoluteMatrices();\n }\n let longestBoneLength = Number.NEGATIVE_INFINITY;\n const displayOptions = this.options.displayOptions || {};\n for (let i = 0; i < bones.length; i++) {\n const bone = bones[i];\n if (bone._index === -1 || (!this._boneIndices.has(bone.getIndex()) && !this.options.useAllBones)) {\n continue;\n }\n const boneAbsoluteBindPoseTransform = new Matrix();\n this._getAbsoluteBindPoseToRef(bone, boneAbsoluteBindPoseTransform);\n const anchorPoint = new Vector3();\n boneAbsoluteBindPoseTransform.decompose(undefined, undefined, anchorPoint);\n bone.children.forEach((bc) => {\n const childAbsoluteBindPoseTransform = new Matrix();\n bc.getBaseMatrix().multiplyToRef(boneAbsoluteBindPoseTransform, childAbsoluteBindPoseTransform);\n const childPoint = new Vector3();\n childAbsoluteBindPoseTransform.decompose(undefined, undefined, childPoint);\n const distanceFromParent = Vector3.Distance(anchorPoint, childPoint);\n if (distanceFromParent > longestBoneLength) {\n longestBoneLength = distanceFromParent;\n }\n if (spheresOnly) {\n return;\n }\n const dir = childPoint.clone().subtract(anchorPoint.clone());\n const h = dir.length();\n const up = dir.normalize().scale(h);\n const midStep = displayOptions.midStep || 0.165;\n const midStepFactor = displayOptions.midStepFactor || 0.215;\n const up0 = up.scale(midStep);\n const spur = ExtrudeShapeCustom(\"skeletonViewer\", {\n shape: [new Vector3(1, -1, 0), new Vector3(1, 1, 0), new Vector3(-1, 1, 0), new Vector3(-1, -1, 0), new Vector3(1, -1, 0)],\n path: [Vector3.Zero(), up0, up],\n scaleFunction: (i) => {\n switch (i) {\n case 0:\n case 2:\n return 0;\n case 1:\n return h * midStepFactor;\n }\n return 0;\n },\n sideOrientation: Mesh.DEFAULTSIDE,\n updatable: false,\n }, utilityLayerScene);\n const numVertices = spur.getTotalVertices();\n const mwk = [], mik = [];\n for (let i = 0; i < numVertices; i++) {\n mwk.push(1, 0, 0, 0);\n // Select verts at end of spur (ie vert 10 to 14) and bind to child\n // bone if spurFollowsChild is enabled.\n if (displayOptions.spurFollowsChild && i > 9) {\n mik.push(bc.getIndex(), 0, 0, 0);\n }\n else {\n mik.push(bone.getIndex(), 0, 0, 0);\n }\n }\n spur.position = anchorPoint.clone();\n spur.setVerticesData(VertexBuffer.MatricesWeightsKind, mwk, false);\n spur.setVerticesData(VertexBuffer.MatricesIndicesKind, mik, false);\n spur.convertToFlatShadedMesh();\n spurs.push(spur);\n });\n const sphereBaseSize = displayOptions.sphereBaseSize || 0.2;\n const sphere = CreateSphere(\"skeletonViewer\", {\n segments: 6,\n diameter: sphereBaseSize,\n updatable: true,\n }, utilityLayerScene);\n const numVertices = sphere.getTotalVertices();\n const mwk = [], mik = [];\n for (let i = 0; i < numVertices; i++) {\n mwk.push(1, 0, 0, 0);\n mik.push(bone.getIndex(), 0, 0, 0);\n }\n sphere.setVerticesData(VertexBuffer.MatricesWeightsKind, mwk, false);\n sphere.setVerticesData(VertexBuffer.MatricesIndicesKind, mik, false);\n sphere.position = anchorPoint.clone();\n spheres.push([sphere, bone]);\n }\n const sphereScaleUnit = displayOptions.sphereScaleUnit || 2;\n const sphereFactor = displayOptions.sphereFactor || 0.85;\n const meshes = [];\n for (let i = 0; i < spheres.length; i++) {\n const [sphere, bone] = spheres[i];\n const scale = 1 / (sphereScaleUnit / longestBoneLength);\n let _stepsOut = 0;\n let _b = bone;\n while (_b.getParent() && _b.getParent().getIndex() !== -1) {\n _stepsOut++;\n _b = _b.getParent();\n }\n sphere.scaling.scaleInPlace(scale * Math.pow(sphereFactor, _stepsOut));\n meshes.push(sphere);\n }\n this.debugMesh = Mesh.MergeMeshes(meshes.concat(spurs), true, true);\n if (this.debugMesh) {\n this.debugMesh.renderingGroupId = this.renderingGroupId;\n this.debugMesh.skeleton = this.skeleton;\n this.debugMesh.parent = this.mesh;\n this.debugMesh.computeBonesUsingShaders = (_c = this.options.computeBonesUsingShaders) !== null && _c !== void 0 ? _c : true;\n this.debugMesh.alwaysSelectAsActiveMesh = true;\n }\n const light = this.utilityLayer._getSharedGizmoLight();\n light.intensity = 0.7;\n this._revert(animationState);\n this.ready = true;\n }\n catch (err) {\n console.error(err);\n this._revert(animationState);\n this.dispose();\n }\n }\n _buildLocalAxes() {\n var _a;\n if (this._localAxes) {\n this._localAxes.dispose();\n }\n this._localAxes = null;\n const displayOptions = this.options.displayOptions || {};\n if (!displayOptions.showLocalAxes) {\n return;\n }\n const targetScene = this._utilityLayer.utilityLayerScene;\n const size = displayOptions.localAxesSize || 0.075;\n const lines = [];\n const colors = [];\n const red = new Color4(1, 0, 0, 1);\n const green = new Color4(0, 1, 0, 1);\n const blue = new Color4(0, 0, 1, 1);\n const mwk = [];\n const mik = [];\n const vertsPerBone = 6;\n for (const i in this.skeleton.bones) {\n const bone = this.skeleton.bones[i];\n if (bone._index === -1 || (!this._boneIndices.has(bone.getIndex()) && !this.options.useAllBones)) {\n continue;\n }\n const boneAbsoluteBindPoseTransform = new Matrix();\n const boneOrigin = new Vector3();\n this._getAbsoluteBindPoseToRef(bone, boneAbsoluteBindPoseTransform);\n boneAbsoluteBindPoseTransform.decompose(undefined, TmpVectors.Quaternion[0], boneOrigin);\n const m = new Matrix();\n TmpVectors.Quaternion[0].toRotationMatrix(m);\n const boneAxisX = Vector3.TransformCoordinates(new Vector3(0 + size, 0, 0), m);\n const boneAxisY = Vector3.TransformCoordinates(new Vector3(0, 0 + size, 0), m);\n const boneAxisZ = Vector3.TransformCoordinates(new Vector3(0, 0, 0 + size), m);\n const axisX = [boneOrigin, boneOrigin.add(boneAxisX)];\n const axisY = [boneOrigin, boneOrigin.add(boneAxisY)];\n const axisZ = [boneOrigin, boneOrigin.add(boneAxisZ)];\n const linePoints = [axisX, axisY, axisZ];\n const lineColors = [\n [red, red],\n [green, green],\n [blue, blue],\n ];\n lines.push(...linePoints);\n colors.push(...lineColors);\n for (let j = 0; j < vertsPerBone; j++) {\n mwk.push(1, 0, 0, 0);\n mik.push(bone.getIndex(), 0, 0, 0);\n }\n }\n this._localAxes = CreateLineSystem(\"localAxes\", { lines: lines, colors: colors, updatable: true }, targetScene);\n this._localAxes.setVerticesData(VertexBuffer.MatricesWeightsKind, mwk, false);\n this._localAxes.setVerticesData(VertexBuffer.MatricesIndicesKind, mik, false);\n this._localAxes.skeleton = this.skeleton;\n this._localAxes.renderingGroupId = this.renderingGroupId + 1;\n this._localAxes.parent = this.mesh;\n this._localAxes.computeBonesUsingShaders = (_a = this.options.computeBonesUsingShaders) !== null && _a !== void 0 ? _a : true;\n }\n /** Update the viewer to sync with current skeleton state, only used for the line display. */\n _displayLinesUpdate() {\n if (!this._utilityLayer) {\n return;\n }\n if (this.autoUpdateBonesMatrices) {\n this.skeleton.computeAbsoluteMatrices();\n }\n if (this.skeleton.bones[0].length === undefined) {\n this._getLinesForBonesNoLength(this.skeleton.bones);\n }\n else {\n this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());\n }\n const targetScene = this._utilityLayer.utilityLayerScene;\n if (targetScene) {\n if (!this._debugMesh) {\n this._debugMesh = CreateLineSystem(\"\", { lines: this._debugLines, updatable: true, instance: null }, targetScene);\n this._debugMesh.renderingGroupId = this.renderingGroupId;\n }\n else {\n CreateLineSystem(\"\", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, targetScene);\n }\n this._debugMesh.position.copyFrom(this.mesh.position);\n this._debugMesh.color = this.color;\n }\n }\n /** Changes the displayMode of the skeleton viewer\n * @param mode The displayMode numerical value\n */\n changeDisplayMode(mode) {\n const wasEnabled = this.isEnabled ? true : false;\n if (this.displayMode !== mode) {\n this.isEnabled = false;\n if (this._debugMesh) {\n this._debugMesh.dispose();\n this._debugMesh = null;\n this.ready = false;\n }\n this.displayMode = mode;\n this.update();\n this._bindObs();\n this.isEnabled = wasEnabled;\n }\n }\n /** Sets a display option of the skeleton viewer\n *\n * | Option | Type | Default | Description |\n * | ---------------- | ------- | ------- | ----------- |\n * | midStep | float | 0.235 | A percentage between a bone and its child that determines the widest part of a spur. Only used when `displayMode` is set to `DISPLAY_SPHERE_AND_SPURS`. |\n * | midStepFactor | float | 0.15 | Mid step width expressed as a factor of the length. A value of 0.5 makes the spur width half of the spur length. Only used when `displayMode` is set to `DISPLAY_SPHERE_AND_SPURS`. |\n * | sphereBaseSize | float | 2 | Sphere base size. Only used when `displayMode` is set to `DISPLAY_SPHERE_AND_SPURS`. |\n * | sphereScaleUnit | float | 0.865 | Sphere scale factor used to scale spheres in relation to the longest bone. Only used when `displayMode` is set to `DISPLAY_SPHERE_AND_SPURS`. |\n * | spurFollowsChild | boolean | false | Whether a spur should attach its far end to the child bone. |\n * | showLocalAxes | boolean | false | Displays local axes on all bones. |\n * | localAxesSize | float | 0.075 | Determines the length of each local axis. |\n *\n * @param option String of the option name\n * @param value The numerical option value\n */\n changeDisplayOptions(option, value) {\n const wasEnabled = this.isEnabled ? true : false;\n this.options.displayOptions[option] = value;\n this.isEnabled = false;\n if (this._debugMesh) {\n this._debugMesh.dispose();\n this._debugMesh = null;\n this.ready = false;\n }\n this.update();\n this._bindObs();\n this.isEnabled = wasEnabled;\n }\n /** Release associated resources */\n dispose() {\n this.isEnabled = false;\n if (this._debugMesh) {\n this._debugMesh.dispose();\n this._debugMesh = null;\n }\n if (this._utilityLayer) {\n this._utilityLayer.dispose();\n this._utilityLayer = null;\n }\n this.ready = false;\n }\n}\n/** public Display constants BABYLON.SkeletonViewer.DISPLAY_LINES */\nSkeletonViewer.DISPLAY_LINES = 0;\n/** public Display constants BABYLON.SkeletonViewer.DISPLAY_SPHERES */\nSkeletonViewer.DISPLAY_SPHERES = 1;\n/** public Display constants BABYLON.SkeletonViewer.DISPLAY_SPHERE_AND_SPURS */\nSkeletonViewer.DISPLAY_SPHERE_AND_SPURS = 2;\n//# sourceMappingURL=skeletonViewer.js.map","export {};\n//# sourceMappingURL=ISkeletonViewer.js.map","import { StandardMaterial } from \"../Materials/standardMaterial.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { Matrix, TmpVectors, Vector3 } from \"../Maths/math.vector.js\";\nimport { CreateLines } from \"../Meshes/Builders/linesBuilder.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { VertexData } from \"../Meshes/mesh.vertexData.js\";\nimport { TransformNode } from \"../Meshes/transformNode.js\";\n/**\n * Class used to render a debug view of the frustum for a directional light\n * @see https://playground.babylonjs.com/#7EFGSG#4\n * @since 5.0.0\n */\nexport class DirectionalLightFrustumViewer {\n /**\n * Gets or sets the transparency of the frustum planes\n */\n get transparency() {\n return this._transparency;\n }\n set transparency(alpha) {\n this._transparency = alpha;\n for (let i = 6; i < 12; ++i) {\n this._lightHelperFrustumMeshes[i].material.alpha = alpha;\n }\n }\n /**\n * true to display the edges of the frustum\n */\n get showLines() {\n return this._showLines;\n }\n set showLines(show) {\n if (this._showLines === show) {\n return;\n }\n this._showLines = show;\n for (let i = 0; i < 6; ++i) {\n this._lightHelperFrustumMeshes[i].setEnabled(show);\n }\n }\n /**\n * true to display the planes of the frustum\n */\n get showPlanes() {\n return this._showPlanes;\n }\n set showPlanes(show) {\n if (this._showPlanes === show) {\n return;\n }\n this._showPlanes = show;\n for (let i = 6; i < 12; ++i) {\n this._lightHelperFrustumMeshes[i].setEnabled(show);\n }\n }\n /**\n * Creates a new frustum viewer\n * @param light directional light to display the frustum for\n * @param camera camera used to retrieve the minZ / maxZ values if the shadowMinZ/shadowMaxZ values of the light are not setup\n */\n constructor(light, camera) {\n this._oldPosition = new Vector3(Number.NaN, Number.NaN, Number.NaN);\n this._oldDirection = new Vector3(Number.NaN, Number.NaN, Number.NaN);\n this._transparency = 0.3;\n this._showLines = true;\n this._showPlanes = true;\n this._scene = light.getScene();\n this._light = light;\n this._camera = camera;\n this._inverseViewMatrix = Matrix.Identity();\n this._lightHelperFrustumMeshes = [];\n this._createGeometry();\n this.show();\n this.update();\n }\n /**\n * Shows the frustum\n */\n show() {\n this._lightHelperFrustumMeshes.forEach((mesh, index) => {\n mesh.setEnabled((index < 6 && this._showLines) || (index >= 6 && this._showPlanes));\n });\n this._oldPosition.set(Number.NaN, Number.NaN, Number.NaN);\n this._visible = true;\n }\n /**\n * Hides the frustum\n */\n hide() {\n this._lightHelperFrustumMeshes.forEach((mesh) => {\n mesh.setEnabled(false);\n });\n this._visible = false;\n }\n /**\n * Updates the frustum.\n * Call this method to update the frustum view if the light has changed position/direction\n */\n update() {\n var _a, _b, _c, _d, _e, _f;\n if (!this._visible) {\n return;\n }\n if (this._oldPosition.equals(this._light.position) &&\n this._oldDirection.equals(this._light.direction) &&\n this._oldAutoCalc === this._light.autoCalcShadowZBounds &&\n this._oldMinZ === this._light.shadowMinZ &&\n this._oldMaxZ === this._light.shadowMaxZ) {\n return;\n }\n this._oldPosition.copyFrom(this._light.position);\n this._oldDirection.copyFrom(this._light.direction);\n this._oldAutoCalc = this._light.autoCalcShadowZBounds;\n this._oldMinZ = this._light.shadowMinZ;\n this._oldMaxZ = this._light.shadowMaxZ;\n TmpVectors.Vector3[0].set(this._light.orthoLeft, this._light.orthoBottom, this._light.shadowMinZ !== undefined ? this._light.shadowMinZ : this._camera.minZ); // min light extents\n TmpVectors.Vector3[1].set(this._light.orthoRight, this._light.orthoTop, this._light.shadowMaxZ !== undefined ? this._light.shadowMaxZ : this._camera.maxZ); // max light extents\n const invLightView = this._getInvertViewMatrix();\n TmpVectors.Vector3[2].copyFromFloats(TmpVectors.Vector3[1].x, TmpVectors.Vector3[1].y, TmpVectors.Vector3[0].z); // n1\n TmpVectors.Vector3[3].copyFromFloats(TmpVectors.Vector3[1].x, TmpVectors.Vector3[0].y, TmpVectors.Vector3[0].z); // n2\n TmpVectors.Vector3[4].copyFromFloats(TmpVectors.Vector3[0].x, TmpVectors.Vector3[0].y, TmpVectors.Vector3[0].z); // n3\n TmpVectors.Vector3[5].copyFromFloats(TmpVectors.Vector3[0].x, TmpVectors.Vector3[1].y, TmpVectors.Vector3[0].z); // n4\n Vector3.TransformCoordinatesToRef(TmpVectors.Vector3[2], invLightView, TmpVectors.Vector3[2]); // near1\n Vector3.TransformCoordinatesToRef(TmpVectors.Vector3[3], invLightView, TmpVectors.Vector3[3]); // near2\n Vector3.TransformCoordinatesToRef(TmpVectors.Vector3[4], invLightView, TmpVectors.Vector3[4]); // near3\n Vector3.TransformCoordinatesToRef(TmpVectors.Vector3[5], invLightView, TmpVectors.Vector3[5]); // near4\n TmpVectors.Vector3[6].copyFromFloats(TmpVectors.Vector3[1].x, TmpVectors.Vector3[1].y, TmpVectors.Vector3[1].z); // f1\n TmpVectors.Vector3[7].copyFromFloats(TmpVectors.Vector3[1].x, TmpVectors.Vector3[0].y, TmpVectors.Vector3[1].z); // f2\n TmpVectors.Vector3[8].copyFromFloats(TmpVectors.Vector3[0].x, TmpVectors.Vector3[0].y, TmpVectors.Vector3[1].z); // f3\n TmpVectors.Vector3[9].copyFromFloats(TmpVectors.Vector3[0].x, TmpVectors.Vector3[1].y, TmpVectors.Vector3[1].z); // f4\n Vector3.TransformCoordinatesToRef(TmpVectors.Vector3[6], invLightView, TmpVectors.Vector3[6]); // far1\n Vector3.TransformCoordinatesToRef(TmpVectors.Vector3[7], invLightView, TmpVectors.Vector3[7]); // far2\n Vector3.TransformCoordinatesToRef(TmpVectors.Vector3[8], invLightView, TmpVectors.Vector3[8]); // far3\n Vector3.TransformCoordinatesToRef(TmpVectors.Vector3[9], invLightView, TmpVectors.Vector3[9]); // far4\n CreateLines(\"nearlines\", { updatable: true, points: this._nearLinesPoints, instance: this._lightHelperFrustumMeshes[0] }, this._scene);\n CreateLines(\"farlines\", { updatable: true, points: this._farLinesPoints, instance: this._lightHelperFrustumMeshes[1] }, this._scene);\n CreateLines(\"trlines\", { updatable: true, points: this._trLinesPoints, instance: this._lightHelperFrustumMeshes[2] }, this._scene);\n CreateLines(\"brlines\", { updatable: true, points: this._brLinesPoints, instance: this._lightHelperFrustumMeshes[3] }, this._scene);\n CreateLines(\"tllines\", { updatable: true, points: this._tlLinesPoints, instance: this._lightHelperFrustumMeshes[4] }, this._scene);\n CreateLines(\"bllines\", { updatable: true, points: this._blLinesPoints, instance: this._lightHelperFrustumMeshes[5] }, this._scene);\n TmpVectors.Vector3[2].toArray(this._nearPlaneVertices, 0);\n TmpVectors.Vector3[3].toArray(this._nearPlaneVertices, 3);\n TmpVectors.Vector3[4].toArray(this._nearPlaneVertices, 6);\n TmpVectors.Vector3[5].toArray(this._nearPlaneVertices, 9);\n (_a = this._lightHelperFrustumMeshes[6].geometry) === null || _a === void 0 ? void 0 : _a.updateVerticesDataDirectly(\"position\", this._nearPlaneVertices, 0);\n TmpVectors.Vector3[6].toArray(this._farPlaneVertices, 0);\n TmpVectors.Vector3[7].toArray(this._farPlaneVertices, 3);\n TmpVectors.Vector3[8].toArray(this._farPlaneVertices, 6);\n TmpVectors.Vector3[9].toArray(this._farPlaneVertices, 9);\n (_b = this._lightHelperFrustumMeshes[7].geometry) === null || _b === void 0 ? void 0 : _b.updateVerticesDataDirectly(\"position\", this._farPlaneVertices, 0);\n TmpVectors.Vector3[2].toArray(this._rightPlaneVertices, 0);\n TmpVectors.Vector3[6].toArray(this._rightPlaneVertices, 3);\n TmpVectors.Vector3[7].toArray(this._rightPlaneVertices, 6);\n TmpVectors.Vector3[3].toArray(this._rightPlaneVertices, 9);\n (_c = this._lightHelperFrustumMeshes[8].geometry) === null || _c === void 0 ? void 0 : _c.updateVerticesDataDirectly(\"position\", this._rightPlaneVertices, 0);\n TmpVectors.Vector3[5].toArray(this._leftPlaneVertices, 0);\n TmpVectors.Vector3[9].toArray(this._leftPlaneVertices, 3);\n TmpVectors.Vector3[8].toArray(this._leftPlaneVertices, 6);\n TmpVectors.Vector3[4].toArray(this._leftPlaneVertices, 9);\n (_d = this._lightHelperFrustumMeshes[9].geometry) === null || _d === void 0 ? void 0 : _d.updateVerticesDataDirectly(\"position\", this._leftPlaneVertices, 0);\n TmpVectors.Vector3[2].toArray(this._topPlaneVertices, 0);\n TmpVectors.Vector3[6].toArray(this._topPlaneVertices, 3);\n TmpVectors.Vector3[9].toArray(this._topPlaneVertices, 6);\n TmpVectors.Vector3[5].toArray(this._topPlaneVertices, 9);\n (_e = this._lightHelperFrustumMeshes[10].geometry) === null || _e === void 0 ? void 0 : _e.updateVerticesDataDirectly(\"position\", this._topPlaneVertices, 0);\n TmpVectors.Vector3[3].toArray(this._bottomPlaneVertices, 0);\n TmpVectors.Vector3[7].toArray(this._bottomPlaneVertices, 3);\n TmpVectors.Vector3[8].toArray(this._bottomPlaneVertices, 6);\n TmpVectors.Vector3[4].toArray(this._bottomPlaneVertices, 9);\n (_f = this._lightHelperFrustumMeshes[11].geometry) === null || _f === void 0 ? void 0 : _f.updateVerticesDataDirectly(\"position\", this._bottomPlaneVertices, 0);\n }\n /**\n * Dispose of the class / remove the frustum view\n */\n dispose() {\n this._lightHelperFrustumMeshes.forEach((mesh) => {\n var _a;\n (_a = mesh.material) === null || _a === void 0 ? void 0 : _a.dispose();\n mesh.dispose();\n });\n this._rootNode.dispose();\n }\n _createGeometry() {\n this._rootNode = new TransformNode(\"directionalLightHelperRoot_\" + this._light.name, this._scene);\n this._rootNode.parent = this._light.parent;\n this._nearLinesPoints = [Vector3.ZeroReadOnly, Vector3.ZeroReadOnly, Vector3.ZeroReadOnly, Vector3.ZeroReadOnly, Vector3.ZeroReadOnly];\n const nearLines = CreateLines(\"nearlines\", { updatable: true, points: this._nearLinesPoints }, this._scene);\n nearLines.parent = this._rootNode;\n nearLines.alwaysSelectAsActiveMesh = true;\n this._farLinesPoints = [Vector3.ZeroReadOnly, Vector3.ZeroReadOnly, Vector3.ZeroReadOnly, Vector3.ZeroReadOnly, Vector3.ZeroReadOnly];\n const farLines = CreateLines(\"farlines\", { updatable: true, points: this._farLinesPoints }, this._scene);\n farLines.parent = this._rootNode;\n farLines.alwaysSelectAsActiveMesh = true;\n this._trLinesPoints = [Vector3.ZeroReadOnly, Vector3.ZeroReadOnly];\n const trLines = CreateLines(\"trlines\", { updatable: true, points: this._trLinesPoints }, this._scene);\n trLines.parent = this._rootNode;\n trLines.alwaysSelectAsActiveMesh = true;\n this._brLinesPoints = [Vector3.ZeroReadOnly, Vector3.ZeroReadOnly];\n const brLines = CreateLines(\"brlines\", { updatable: true, points: this._brLinesPoints }, this._scene);\n brLines.parent = this._rootNode;\n brLines.alwaysSelectAsActiveMesh = true;\n this._tlLinesPoints = [Vector3.ZeroReadOnly, Vector3.ZeroReadOnly];\n const tlLines = CreateLines(\"tllines\", { updatable: true, points: this._tlLinesPoints }, this._scene);\n tlLines.parent = this._rootNode;\n tlLines.alwaysSelectAsActiveMesh = true;\n this._blLinesPoints = [Vector3.ZeroReadOnly, Vector3.ZeroReadOnly];\n const blLines = CreateLines(\"bllines\", { updatable: true, points: this._blLinesPoints }, this._scene);\n blLines.parent = this._rootNode;\n blLines.alwaysSelectAsActiveMesh = true;\n this._lightHelperFrustumMeshes.push(nearLines, farLines, trLines, brLines, tlLines, blLines);\n const makePlane = (name, color, positions) => {\n const plane = new Mesh(name + \"plane\", this._scene);\n const mat = new StandardMaterial(name + \"PlaneMat\", this._scene);\n plane.material = mat;\n plane.parent = this._rootNode;\n plane.alwaysSelectAsActiveMesh = true;\n mat.emissiveColor = color;\n mat.alpha = this.transparency;\n mat.backFaceCulling = false;\n mat.disableLighting = true;\n const indices = [0, 1, 2, 0, 2, 3];\n const vertexData = new VertexData();\n vertexData.positions = positions;\n vertexData.indices = indices;\n vertexData.applyToMesh(plane, true);\n this._lightHelperFrustumMeshes.push(plane);\n };\n this._nearPlaneVertices = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n this._farPlaneVertices = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n this._rightPlaneVertices = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n this._leftPlaneVertices = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n this._topPlaneVertices = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n this._bottomPlaneVertices = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n makePlane(\"near\", new Color3(1, 0, 0), this._nearPlaneVertices);\n makePlane(\"far\", new Color3(0.3, 0, 0), this._farPlaneVertices);\n makePlane(\"right\", new Color3(0, 1, 0), this._rightPlaneVertices);\n makePlane(\"left\", new Color3(0, 0.3, 0), this._leftPlaneVertices);\n makePlane(\"top\", new Color3(0, 0, 1), this._topPlaneVertices);\n makePlane(\"bottom\", new Color3(0, 0, 0.3), this._bottomPlaneVertices);\n this._nearLinesPoints[0] = TmpVectors.Vector3[2];\n this._nearLinesPoints[1] = TmpVectors.Vector3[3];\n this._nearLinesPoints[2] = TmpVectors.Vector3[4];\n this._nearLinesPoints[3] = TmpVectors.Vector3[5];\n this._nearLinesPoints[4] = TmpVectors.Vector3[2];\n this._farLinesPoints[0] = TmpVectors.Vector3[6];\n this._farLinesPoints[1] = TmpVectors.Vector3[7];\n this._farLinesPoints[2] = TmpVectors.Vector3[8];\n this._farLinesPoints[3] = TmpVectors.Vector3[9];\n this._farLinesPoints[4] = TmpVectors.Vector3[6];\n this._trLinesPoints[0] = TmpVectors.Vector3[2];\n this._trLinesPoints[1] = TmpVectors.Vector3[6];\n this._brLinesPoints[0] = TmpVectors.Vector3[3];\n this._brLinesPoints[1] = TmpVectors.Vector3[7];\n this._tlLinesPoints[0] = TmpVectors.Vector3[4];\n this._tlLinesPoints[1] = TmpVectors.Vector3[8];\n this._blLinesPoints[0] = TmpVectors.Vector3[5];\n this._blLinesPoints[1] = TmpVectors.Vector3[9];\n }\n _getInvertViewMatrix() {\n Matrix.LookAtLHToRef(this._light.position, this._light.position.add(this._light.direction), Vector3.UpReadOnly, this._inverseViewMatrix);\n this._inverseViewMatrix.invertToRef(this._inverseViewMatrix);\n return this._inverseViewMatrix;\n }\n}\n//# sourceMappingURL=directionalLightFrustumViewer.js.map","export * from \"./axesViewer.js\";\nexport * from \"./boneAxesViewer.js\";\nexport * from \"./debugLayer.js\";\nexport * from \"./physicsViewer.js\";\nexport * from \"./rayHelper.js\";\nexport * from \"./skeletonViewer.js\";\nexport * from \"./ISkeletonViewer.js\";\nexport * from \"./directionalLightFrustumViewer.js\";\n//# sourceMappingURL=index.js.map","export {};\n//# sourceMappingURL=deviceTypes.js.map","export * from \"./InputDevices/deviceEnums.js\";\nexport * from \"./InputDevices/deviceTypes.js\";\nexport * from \"./InputDevices/deviceSource.js\";\nexport * from \"./InputDevices/deviceSourceManager.js\";\n//# sourceMappingURL=index.js.map","/* eslint-disable @typescript-eslint/naming-convention */\n/** Defines the cross module used constants to avoid circular dependencies */\nexport class Constants {\n}\n/** Defines that alpha blending is disabled */\nConstants.ALPHA_DISABLE = 0;\n/** Defines that alpha blending is SRC ALPHA * SRC + DEST */\nConstants.ALPHA_ADD = 1;\n/** Defines that alpha blending is SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */\nConstants.ALPHA_COMBINE = 2;\n/** Defines that alpha blending is DEST - SRC * DEST */\nConstants.ALPHA_SUBTRACT = 3;\n/** Defines that alpha blending is SRC * DEST */\nConstants.ALPHA_MULTIPLY = 4;\n/** Defines that alpha blending is SRC ALPHA * SRC + (1 - SRC) * DEST */\nConstants.ALPHA_MAXIMIZED = 5;\n/** Defines that alpha blending is SRC + DEST */\nConstants.ALPHA_ONEONE = 6;\n/** Defines that alpha blending is SRC + (1 - SRC ALPHA) * DEST */\nConstants.ALPHA_PREMULTIPLIED = 7;\n/**\n * Defines that alpha blending is SRC + (1 - SRC ALPHA) * DEST\n * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA\n */\nConstants.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;\n/** Defines that alpha blending is CST * SRC + (1 - CST) * DEST */\nConstants.ALPHA_INTERPOLATE = 9;\n/**\n * Defines that alpha blending is SRC + (1 - SRC) * DEST\n * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA\n */\nConstants.ALPHA_SCREENMODE = 10;\n/**\n * Defines that alpha blending is SRC + DST\n * Alpha will be set to SRC ALPHA + DST ALPHA\n */\nConstants.ALPHA_ONEONE_ONEONE = 11;\n/**\n * Defines that alpha blending is SRC * DST ALPHA + DST\n * Alpha will be set to 0\n */\nConstants.ALPHA_ALPHATOCOLOR = 12;\n/**\n * Defines that alpha blending is SRC * (1 - DST) + DST * (1 - SRC)\n */\nConstants.ALPHA_REVERSEONEMINUS = 13;\n/**\n * Defines that alpha blending is SRC + DST * (1 - SRC ALPHA)\n * Alpha will be set to SRC ALPHA + DST ALPHA * (1 - SRC ALPHA)\n */\nConstants.ALPHA_SRC_DSTONEMINUSSRCALPHA = 14;\n/**\n * Defines that alpha blending is SRC + DST\n * Alpha will be set to SRC ALPHA\n */\nConstants.ALPHA_ONEONE_ONEZERO = 15;\n/**\n * Defines that alpha blending is SRC * (1 - DST) + DST * (1 - SRC)\n * Alpha will be set to DST ALPHA\n */\nConstants.ALPHA_EXCLUSION = 16;\n/**\n * Defines that alpha blending is SRC * SRC ALPHA + DST * (1 - SRC ALPHA)\n * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DST ALPHA\n */\nConstants.ALPHA_LAYER_ACCUMULATE = 17;\n/** Defines that alpha blending equation a SUM */\nConstants.ALPHA_EQUATION_ADD = 0;\n/** Defines that alpha blending equation a SUBSTRACTION */\nConstants.ALPHA_EQUATION_SUBSTRACT = 1;\n/** Defines that alpha blending equation a REVERSE SUBSTRACTION */\nConstants.ALPHA_EQUATION_REVERSE_SUBTRACT = 2;\n/** Defines that alpha blending equation a MAX operation */\nConstants.ALPHA_EQUATION_MAX = 3;\n/** Defines that alpha blending equation a MIN operation */\nConstants.ALPHA_EQUATION_MIN = 4;\n/**\n * Defines that alpha blending equation a DARKEN operation:\n * It takes the min of the src and sums the alpha channels.\n */\nConstants.ALPHA_EQUATION_DARKEN = 5;\n/** Defines that the resource is not delayed*/\nConstants.DELAYLOADSTATE_NONE = 0;\n/** Defines that the resource was successfully delay loaded */\nConstants.DELAYLOADSTATE_LOADED = 1;\n/** Defines that the resource is currently delay loading */\nConstants.DELAYLOADSTATE_LOADING = 2;\n/** Defines that the resource is delayed and has not started loading */\nConstants.DELAYLOADSTATE_NOTLOADED = 4;\n// Depth or Stencil test Constants.\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */\nConstants.NEVER = 0x0200;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */\nConstants.ALWAYS = 0x0207;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */\nConstants.LESS = 0x0201;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */\nConstants.EQUAL = 0x0202;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */\nConstants.LEQUAL = 0x0203;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */\nConstants.GREATER = 0x0204;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */\nConstants.GEQUAL = 0x0206;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */\nConstants.NOTEQUAL = 0x0205;\n// Stencil Actions Constants.\n/** Passed to stencilOperation to specify that stencil value must be kept */\nConstants.KEEP = 0x1e00;\n/** Passed to stencilOperation to specify that stencil value must be zero */\nConstants.ZERO = 0x0000;\n/** Passed to stencilOperation to specify that stencil value must be replaced */\nConstants.REPLACE = 0x1e01;\n/** Passed to stencilOperation to specify that stencil value must be incremented */\nConstants.INCR = 0x1e02;\n/** Passed to stencilOperation to specify that stencil value must be decremented */\nConstants.DECR = 0x1e03;\n/** Passed to stencilOperation to specify that stencil value must be inverted */\nConstants.INVERT = 0x150a;\n/** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */\nConstants.INCR_WRAP = 0x8507;\n/** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */\nConstants.DECR_WRAP = 0x8508;\n/** Texture is not repeating outside of 0..1 UVs */\nConstants.TEXTURE_CLAMP_ADDRESSMODE = 0;\n/** Texture is repeating outside of 0..1 UVs */\nConstants.TEXTURE_WRAP_ADDRESSMODE = 1;\n/** Texture is repeating and mirrored */\nConstants.TEXTURE_MIRROR_ADDRESSMODE = 2;\n/** Flag to create a storage texture */\nConstants.TEXTURE_CREATIONFLAG_STORAGE = 1;\n/** ALPHA */\nConstants.TEXTUREFORMAT_ALPHA = 0;\n/** LUMINANCE */\nConstants.TEXTUREFORMAT_LUMINANCE = 1;\n/** LUMINANCE_ALPHA */\nConstants.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;\n/** RGB */\nConstants.TEXTUREFORMAT_RGB = 4;\n/** RGBA */\nConstants.TEXTUREFORMAT_RGBA = 5;\n/** RED */\nConstants.TEXTUREFORMAT_RED = 6;\n/** RED (2nd reference) */\nConstants.TEXTUREFORMAT_R = 6;\n/** RG */\nConstants.TEXTUREFORMAT_RG = 7;\n/** RED_INTEGER */\nConstants.TEXTUREFORMAT_RED_INTEGER = 8;\n/** RED_INTEGER (2nd reference) */\nConstants.TEXTUREFORMAT_R_INTEGER = 8;\n/** RG_INTEGER */\nConstants.TEXTUREFORMAT_RG_INTEGER = 9;\n/** RGB_INTEGER */\nConstants.TEXTUREFORMAT_RGB_INTEGER = 10;\n/** RGBA_INTEGER */\nConstants.TEXTUREFORMAT_RGBA_INTEGER = 11;\n/** BGRA */\nConstants.TEXTUREFORMAT_BGRA = 12;\n/** Depth 24 bits + Stencil 8 bits */\nConstants.TEXTUREFORMAT_DEPTH24_STENCIL8 = 13;\n/** Depth 32 bits float */\nConstants.TEXTUREFORMAT_DEPTH32_FLOAT = 14;\n/** Depth 16 bits */\nConstants.TEXTUREFORMAT_DEPTH16 = 15;\n/** Depth 24 bits */\nConstants.TEXTUREFORMAT_DEPTH24 = 16;\n/** Depth 24 bits unorm + Stencil 8 bits */\nConstants.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8 = 17;\n/** Depth 32 bits float + Stencil 8 bits */\nConstants.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8 = 18;\n/** Stencil 8 bits */\nConstants.TEXTUREFORMAT_STENCIL8 = 19;\n/** Compressed BC7 */\nConstants.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM = 36492;\n/** Compressed BC7 (SRGB) */\nConstants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM = 36493;\n/** Compressed BC6 unsigned float */\nConstants.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT = 36495;\n/** Compressed BC6 signed float */\nConstants.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT = 36494;\n/** Compressed BC3 */\nConstants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5 = 33779;\n/** Compressed BC3 (SRGB) */\nConstants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT = 35919;\n/** Compressed BC2 */\nConstants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3 = 33778;\n/** Compressed BC2 (SRGB) */\nConstants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT = 35918;\n/** Compressed BC1 (RGBA) */\nConstants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1 = 33777;\n/** Compressed BC1 (RGB) */\nConstants.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1 = 33776;\n/** Compressed BC1 (SRGB+A) */\nConstants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT = 35917;\n/** Compressed BC1 (SRGB) */\nConstants.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT = 35916;\n/** Compressed ASTC 4x4 */\nConstants.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4 = 37808;\n/** Compressed ASTC 4x4 (SRGB) */\nConstants.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = 37840;\n/** Compressed ETC1 (RGB) */\nConstants.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL = 36196;\n/** Compressed ETC2 (RGB) */\nConstants.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2 = 37492;\n/** Compressed ETC2 (SRGB) */\nConstants.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2 = 37493;\n/** Compressed ETC2 (RGB+A1) */\nConstants.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 37494;\n/** Compressed ETC2 (SRGB+A1)*/\nConstants.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 37495;\n/** Compressed ETC2 (RGB+A) */\nConstants.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC = 37496;\n/** Compressed ETC2 (SRGB+1) */\nConstants.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 37497;\n/** UNSIGNED_BYTE */\nConstants.TEXTURETYPE_UNSIGNED_BYTE = 0;\n/** UNSIGNED_BYTE (2nd reference) */\nConstants.TEXTURETYPE_UNSIGNED_INT = 0;\n/** FLOAT */\nConstants.TEXTURETYPE_FLOAT = 1;\n/** HALF_FLOAT */\nConstants.TEXTURETYPE_HALF_FLOAT = 2;\n/** BYTE */\nConstants.TEXTURETYPE_BYTE = 3;\n/** SHORT */\nConstants.TEXTURETYPE_SHORT = 4;\n/** UNSIGNED_SHORT */\nConstants.TEXTURETYPE_UNSIGNED_SHORT = 5;\n/** INT */\nConstants.TEXTURETYPE_INT = 6;\n/** UNSIGNED_INT */\nConstants.TEXTURETYPE_UNSIGNED_INTEGER = 7;\n/** UNSIGNED_SHORT_4_4_4_4 */\nConstants.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;\n/** UNSIGNED_SHORT_5_5_5_1 */\nConstants.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;\n/** UNSIGNED_SHORT_5_6_5 */\nConstants.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;\n/** UNSIGNED_INT_2_10_10_10_REV */\nConstants.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;\n/** UNSIGNED_INT_24_8 */\nConstants.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;\n/** UNSIGNED_INT_10F_11F_11F_REV */\nConstants.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;\n/** UNSIGNED_INT_5_9_9_9_REV */\nConstants.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;\n/** FLOAT_32_UNSIGNED_INT_24_8_REV */\nConstants.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;\n/** UNDEFINED */\nConstants.TEXTURETYPE_UNDEFINED = 16;\n/** 2D Texture target*/\nConstants.TEXTURE_2D = 3553;\n/** 2D Array Texture target */\nConstants.TEXTURE_2D_ARRAY = 35866;\n/** Cube Map Texture target */\nConstants.TEXTURE_CUBE_MAP = 34067;\n/** Cube Map Array Texture target */\nConstants.TEXTURE_CUBE_MAP_ARRAY = 0xdeadbeef;\n/** 3D Texture target */\nConstants.TEXTURE_3D = 32879;\n/** nearest is mag = nearest and min = nearest and no mip */\nConstants.TEXTURE_NEAREST_SAMPLINGMODE = 1;\n/** mag = nearest and min = nearest and mip = none */\nConstants.TEXTURE_NEAREST_NEAREST = 1;\n/** Bilinear is mag = linear and min = linear and no mip */\nConstants.TEXTURE_BILINEAR_SAMPLINGMODE = 2;\n/** mag = linear and min = linear and mip = none */\nConstants.TEXTURE_LINEAR_LINEAR = 2;\n/** Trilinear is mag = linear and min = linear and mip = linear */\nConstants.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;\n/** Trilinear is mag = linear and min = linear and mip = linear */\nConstants.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;\n/** mag = nearest and min = nearest and mip = nearest */\nConstants.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;\n/** mag = nearest and min = linear and mip = nearest */\nConstants.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;\n/** mag = nearest and min = linear and mip = linear */\nConstants.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;\n/** mag = nearest and min = linear and mip = none */\nConstants.TEXTURE_NEAREST_LINEAR = 7;\n/** nearest is mag = nearest and min = nearest and mip = linear */\nConstants.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 8;\n/** mag = linear and min = nearest and mip = nearest */\nConstants.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;\n/** mag = linear and min = nearest and mip = linear */\nConstants.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;\n/** Bilinear is mag = linear and min = linear and mip = nearest */\nConstants.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 11;\n/** mag = linear and min = nearest and mip = none */\nConstants.TEXTURE_LINEAR_NEAREST = 12;\n/** Explicit coordinates mode */\nConstants.TEXTURE_EXPLICIT_MODE = 0;\n/** Spherical coordinates mode */\nConstants.TEXTURE_SPHERICAL_MODE = 1;\n/** Planar coordinates mode */\nConstants.TEXTURE_PLANAR_MODE = 2;\n/** Cubic coordinates mode */\nConstants.TEXTURE_CUBIC_MODE = 3;\n/** Projection coordinates mode */\nConstants.TEXTURE_PROJECTION_MODE = 4;\n/** Skybox coordinates mode */\nConstants.TEXTURE_SKYBOX_MODE = 5;\n/** Inverse Cubic coordinates mode */\nConstants.TEXTURE_INVCUBIC_MODE = 6;\n/** Equirectangular coordinates mode */\nConstants.TEXTURE_EQUIRECTANGULAR_MODE = 7;\n/** Equirectangular Fixed coordinates mode */\nConstants.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;\n/** Equirectangular Fixed Mirrored coordinates mode */\nConstants.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;\n/** Offline (baking) quality for texture filtering */\nConstants.TEXTURE_FILTERING_QUALITY_OFFLINE = 4096;\n/** High quality for texture filtering */\nConstants.TEXTURE_FILTERING_QUALITY_HIGH = 64;\n/** Medium quality for texture filtering */\nConstants.TEXTURE_FILTERING_QUALITY_MEDIUM = 16;\n/** Low quality for texture filtering */\nConstants.TEXTURE_FILTERING_QUALITY_LOW = 8;\n// Texture rescaling mode\n/** Defines that texture rescaling will use a floor to find the closer power of 2 size */\nConstants.SCALEMODE_FLOOR = 1;\n/** Defines that texture rescaling will look for the nearest power of 2 size */\nConstants.SCALEMODE_NEAREST = 2;\n/** Defines that texture rescaling will use a ceil to find the closer power of 2 size */\nConstants.SCALEMODE_CEILING = 3;\n/**\n * The dirty texture flag value\n */\nConstants.MATERIAL_TextureDirtyFlag = 1;\n/**\n * The dirty light flag value\n */\nConstants.MATERIAL_LightDirtyFlag = 2;\n/**\n * The dirty fresnel flag value\n */\nConstants.MATERIAL_FresnelDirtyFlag = 4;\n/**\n * The dirty attribute flag value\n */\nConstants.MATERIAL_AttributesDirtyFlag = 8;\n/**\n * The dirty misc flag value\n */\nConstants.MATERIAL_MiscDirtyFlag = 16;\n/**\n * The dirty prepass flag value\n */\nConstants.MATERIAL_PrePassDirtyFlag = 32;\n/**\n * The all dirty flag value\n */\nConstants.MATERIAL_AllDirtyFlag = 63;\n/**\n * Returns the triangle fill mode\n */\nConstants.MATERIAL_TriangleFillMode = 0;\n/**\n * Returns the wireframe mode\n */\nConstants.MATERIAL_WireFrameFillMode = 1;\n/**\n * Returns the point fill mode\n */\nConstants.MATERIAL_PointFillMode = 2;\n/**\n * Returns the point list draw mode\n */\nConstants.MATERIAL_PointListDrawMode = 3;\n/**\n * Returns the line list draw mode\n */\nConstants.MATERIAL_LineListDrawMode = 4;\n/**\n * Returns the line loop draw mode\n */\nConstants.MATERIAL_LineLoopDrawMode = 5;\n/**\n * Returns the line strip draw mode\n */\nConstants.MATERIAL_LineStripDrawMode = 6;\n/**\n * Returns the triangle strip draw mode\n */\nConstants.MATERIAL_TriangleStripDrawMode = 7;\n/**\n * Returns the triangle fan draw mode\n */\nConstants.MATERIAL_TriangleFanDrawMode = 8;\n/**\n * Stores the clock-wise side orientation\n */\nConstants.MATERIAL_ClockWiseSideOrientation = 0;\n/**\n * Stores the counter clock-wise side orientation\n */\nConstants.MATERIAL_CounterClockWiseSideOrientation = 1;\n/**\n * Nothing\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_NothingTrigger = 0;\n/**\n * On pick\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnPickTrigger = 1;\n/**\n * On left pick\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnLeftPickTrigger = 2;\n/**\n * On right pick\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnRightPickTrigger = 3;\n/**\n * On center pick\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnCenterPickTrigger = 4;\n/**\n * On pick down\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnPickDownTrigger = 5;\n/**\n * On double pick\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnDoublePickTrigger = 6;\n/**\n * On pick up\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnPickUpTrigger = 7;\n/**\n * On pick out.\n * This trigger will only be raised if you also declared a OnPickDown\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnPickOutTrigger = 16;\n/**\n * On long press\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnLongPressTrigger = 8;\n/**\n * On pointer over\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnPointerOverTrigger = 9;\n/**\n * On pointer out\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnPointerOutTrigger = 10;\n/**\n * On every frame\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnEveryFrameTrigger = 11;\n/**\n * On intersection enter\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnIntersectionEnterTrigger = 12;\n/**\n * On intersection exit\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnIntersectionExitTrigger = 13;\n/**\n * On key down\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnKeyDownTrigger = 14;\n/**\n * On key up\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnKeyUpTrigger = 15;\n/**\n * Billboard mode will only apply to Y axis\n */\nConstants.PARTICLES_BILLBOARDMODE_Y = 2;\n/**\n * Billboard mode will apply to all axes\n */\nConstants.PARTICLES_BILLBOARDMODE_ALL = 7;\n/**\n * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction\n */\nConstants.PARTICLES_BILLBOARDMODE_STRETCHED = 8;\n/**\n * Special billboard mode where the particle will be billboard to the camera but only around the axis of the direction of particle emission\n */\nConstants.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL = 9;\n/** Default culling strategy : this is an exclusion test and it's the more accurate.\n * Test order :\n * Is the bounding sphere outside the frustum ?\n * If not, are the bounding box vertices outside the frustum ?\n * It not, then the cullable object is in the frustum.\n */\nConstants.MESHES_CULLINGSTRATEGY_STANDARD = 0;\n/** Culling strategy : Bounding Sphere Only.\n * This is an exclusion test. It's faster than the standard strategy because the bounding box is not tested.\n * It's also less accurate than the standard because some not visible objects can still be selected.\n * Test : is the bounding sphere outside the frustum ?\n * If not, then the cullable object is in the frustum.\n */\nConstants.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;\n/** Culling strategy : Optimistic Inclusion.\n * This in an inclusion test first, then the standard exclusion test.\n * This can be faster when a cullable object is expected to be almost always in the camera frustum.\n * This could also be a little slower than the standard test when the tested object center is not the frustum but one of its bounding box vertex is still inside.\n * Anyway, it's as accurate as the standard strategy.\n * Test :\n * Is the cullable object bounding sphere center in the frustum ?\n * If not, apply the default culling strategy.\n */\nConstants.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION = 2;\n/** Culling strategy : Optimistic Inclusion then Bounding Sphere Only.\n * This in an inclusion test first, then the bounding sphere only exclusion test.\n * This can be the fastest test when a cullable object is expected to be almost always in the camera frustum.\n * This could also be a little slower than the BoundingSphereOnly strategy when the tested object center is not in the frustum but its bounding sphere still intersects it.\n * It's less accurate than the standard strategy and as accurate as the BoundingSphereOnly strategy.\n * Test :\n * Is the cullable object bounding sphere center in the frustum ?\n * If not, apply the Bounding Sphere Only strategy. No Bounding Box is tested here.\n */\nConstants.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY = 3;\n/**\n * No logging while loading\n */\nConstants.SCENELOADER_NO_LOGGING = 0;\n/**\n * Minimal logging while loading\n */\nConstants.SCENELOADER_MINIMAL_LOGGING = 1;\n/**\n * Summary logging while loading\n */\nConstants.SCENELOADER_SUMMARY_LOGGING = 2;\n/**\n * Detailed logging while loading\n */\nConstants.SCENELOADER_DETAILED_LOGGING = 3;\n/**\n * Constant used to retrieve the irradiance texture index in the textures array in the prepass\n * using getIndex(Constants.PREPASS_IRRADIANCE_TEXTURE_TYPE)\n */\nConstants.PREPASS_IRRADIANCE_TEXTURE_TYPE = 0;\n/**\n * Constant used to retrieve the position texture index in the textures array in the prepass\n * using getIndex(Constants.PREPASS_POSITION_TEXTURE_INDEX)\n */\nConstants.PREPASS_POSITION_TEXTURE_TYPE = 1;\n/**\n * Constant used to retrieve the velocity texture index in the textures array in the prepass\n * using getIndex(Constants.PREPASS_VELOCITY_TEXTURE_INDEX)\n */\nConstants.PREPASS_VELOCITY_TEXTURE_TYPE = 2;\n/**\n * Constant used to retrieve the reflectivity texture index in the textures array in the prepass\n * using the getIndex(Constants.PREPASS_REFLECTIVITY_TEXTURE_TYPE)\n */\nConstants.PREPASS_REFLECTIVITY_TEXTURE_TYPE = 3;\n/**\n * Constant used to retrieve the lit color texture index in the textures array in the prepass\n * using the getIndex(Constants.PREPASS_COLOR_TEXTURE_TYPE)\n */\nConstants.PREPASS_COLOR_TEXTURE_TYPE = 4;\n/**\n * Constant used to retrieve depth index in the textures array in the prepass\n * using the getIndex(Constants.PREPASS_DEPTH_TEXTURE_TYPE)\n */\nConstants.PREPASS_DEPTH_TEXTURE_TYPE = 5;\n/**\n * Constant used to retrieve normal index in the textures array in the prepass\n * using the getIndex(Constants.PREPASS_NORMAL_TEXTURE_TYPE)\n */\nConstants.PREPASS_NORMAL_TEXTURE_TYPE = 6;\n/**\n * Constant used to retrieve albedo index in the textures array in the prepass\n * using the getIndex(Constants.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE)\n */\nConstants.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE = 7;\n/** Flag to create a readable buffer (the buffer can be the source of a copy) */\nConstants.BUFFER_CREATIONFLAG_READ = 1;\n/** Flag to create a writable buffer (the buffer can be the destination of a copy) */\nConstants.BUFFER_CREATIONFLAG_WRITE = 2;\n/** Flag to create a readable and writable buffer */\nConstants.BUFFER_CREATIONFLAG_READWRITE = 3;\n/** Flag to create a buffer suitable to be used as a uniform buffer */\nConstants.BUFFER_CREATIONFLAG_UNIFORM = 4;\n/** Flag to create a buffer suitable to be used as a vertex buffer */\nConstants.BUFFER_CREATIONFLAG_VERTEX = 8;\n/** Flag to create a buffer suitable to be used as an index buffer */\nConstants.BUFFER_CREATIONFLAG_INDEX = 16;\n/** Flag to create a buffer suitable to be used as a storage buffer */\nConstants.BUFFER_CREATIONFLAG_STORAGE = 32;\n/**\n * Prefixes used by the engine for sub mesh draw wrappers\n */\n/** @internal */\nConstants.RENDERPASS_MAIN = 0;\n/**\n * Constant used as key code for Alt key\n */\nConstants.INPUT_ALT_KEY = 18;\n/**\n * Constant used as key code for Ctrl key\n */\nConstants.INPUT_CTRL_KEY = 17;\n/**\n * Constant used as key code for Meta key (Left Win, Left Cmd)\n */\nConstants.INPUT_META_KEY1 = 91;\n/**\n * Constant used as key code for Meta key (Right Win)\n */\nConstants.INPUT_META_KEY2 = 92;\n/**\n * Constant used as key code for Meta key (Right Win, Right Cmd)\n */\nConstants.INPUT_META_KEY3 = 93;\n/**\n * Constant used as key code for Shift key\n */\nConstants.INPUT_SHIFT_KEY = 16;\n/** Standard snapshot rendering. In this mode, some form of dynamic behavior is possible (for eg, uniform buffers are still updated) */\nConstants.SNAPSHOTRENDERING_STANDARD = 0;\n/** Fast snapshot rendering. In this mode, everything is static and only some limited form of dynamic behaviour is possible */\nConstants.SNAPSHOTRENDERING_FAST = 1;\n/**\n * This is the default projection mode used by the cameras.\n * It helps recreating a feeling of perspective and better appreciate depth.\n * This is the best way to simulate real life cameras.\n */\nConstants.PERSPECTIVE_CAMERA = 0;\n/**\n * This helps creating camera with an orthographic mode.\n * Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object.\n */\nConstants.ORTHOGRAPHIC_CAMERA = 1;\n/**\n * This is the default FOV mode for perspective cameras.\n * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.\n */\nConstants.FOVMODE_VERTICAL_FIXED = 0;\n/**\n * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.\n */\nConstants.FOVMODE_HORIZONTAL_FIXED = 1;\n/**\n * This specifies there is no need for a camera rig.\n * Basically only one eye is rendered corresponding to the camera.\n */\nConstants.RIG_MODE_NONE = 0;\n/**\n * Simulates a camera Rig with one blue eye and one red eye.\n * This can be use with 3d blue and red glasses.\n */\nConstants.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;\n/**\n * Defines that both eyes of the camera will be rendered side by side with a parallel target.\n */\nConstants.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;\n/**\n * Defines that both eyes of the camera will be rendered side by side with a none parallel target.\n */\nConstants.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;\n/**\n * Defines that both eyes of the camera will be rendered over under each other.\n */\nConstants.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;\n/**\n * Defines that both eyes of the camera will be rendered on successive lines interlaced for passive 3d monitors.\n */\nConstants.RIG_MODE_STEREOSCOPIC_INTERLACED = 14;\n/**\n * Defines that both eyes of the camera should be renderered in a VR mode (carbox).\n */\nConstants.RIG_MODE_VR = 20;\n/**\n * Defines that both eyes of the camera should be renderered in a VR mode (webVR).\n */\nConstants.RIG_MODE_WEBVR = 21;\n/**\n * Custom rig mode allowing rig cameras to be populated manually with any number of cameras\n */\nConstants.RIG_MODE_CUSTOM = 22;\n/**\n * Maximum number of uv sets supported\n */\nConstants.MAX_SUPPORTED_UV_SETS = 6;\n/**\n * GL constants\n */\n/** Alpha blend equation: ADD */\nConstants.GL_ALPHA_EQUATION_ADD = 0x8006;\n/** Alpha equation: MIN */\nConstants.GL_ALPHA_EQUATION_MIN = 0x8007;\n/** Alpha equation: MAX */\nConstants.GL_ALPHA_EQUATION_MAX = 0x8008;\n/** Alpha equation: SUBTRACT */\nConstants.GL_ALPHA_EQUATION_SUBTRACT = 0x800a;\n/** Alpha equation: REVERSE_SUBTRACT */\nConstants.GL_ALPHA_EQUATION_REVERSE_SUBTRACT = 0x800b;\n/** Alpha blend function: SRC */\nConstants.GL_ALPHA_FUNCTION_SRC = 0x0300;\n/** Alpha blend function: ONE_MINUS_SRC */\nConstants.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR = 0x0301;\n/** Alpha blend function: SRC_ALPHA */\nConstants.GL_ALPHA_FUNCTION_SRC_ALPHA = 0x0302;\n/** Alpha blend function: ONE_MINUS_SRC_ALPHA */\nConstants.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA = 0x0303;\n/** Alpha blend function: DST_ALPHA */\nConstants.GL_ALPHA_FUNCTION_DST_ALPHA = 0x0304;\n/** Alpha blend function: ONE_MINUS_DST_ALPHA */\nConstants.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA = 0x0305;\n/** Alpha blend function: ONE_MINUS_DST */\nConstants.GL_ALPHA_FUNCTION_DST_COLOR = 0x0306;\n/** Alpha blend function: ONE_MINUS_DST */\nConstants.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR = 0x0307;\n/** Alpha blend function: SRC_ALPHA_SATURATED */\nConstants.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED = 0x0308;\n/** Alpha blend function: CONSTANT */\nConstants.GL_ALPHA_FUNCTION_CONSTANT_COLOR = 0x8001;\n/** Alpha blend function: ONE_MINUS_CONSTANT */\nConstants.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR = 0x8002;\n/** Alpha blend function: CONSTANT_ALPHA */\nConstants.GL_ALPHA_FUNCTION_CONSTANT_ALPHA = 0x8003;\n/** Alpha blend function: ONE_MINUS_CONSTANT_ALPHA */\nConstants.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA = 0x8004;\n/** URL to the snippet server. Points to the public snippet server by default */\nConstants.SnippetUrl = \"https://snippet.babylonjs.com\";\n//# sourceMappingURL=constants.js.map","/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { Logger } from \"../Misc/logger.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { InternalTexture, InternalTextureSource } from \"../Materials/Textures/internalTexture.js\";\n\nimport { DataBuffer } from \"../Buffers/dataBuffer.js\";\nimport { PerformanceConfigurator } from \"./performanceConfigurator.js\";\nimport { DrawWrapper } from \"../Materials/drawWrapper.js\";\nimport { RenderTargetWrapper } from \"./renderTargetWrapper.js\";\n/**\n * Options to create the null engine\n */\nexport class NullEngineOptions {\n constructor() {\n /**\n * Render width (Default: 512)\n */\n this.renderWidth = 512;\n /**\n * Render height (Default: 256)\n */\n this.renderHeight = 256;\n /**\n * Texture size (Default: 512)\n */\n this.textureSize = 512;\n /**\n * If delta time between frames should be constant\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep\n */\n this.deterministicLockstep = false;\n /**\n * Maximum about of steps between frames (Default: 4)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep\n */\n this.lockstepMaxSteps = 4;\n }\n}\n/**\n * The null engine class provides support for headless version of babylon.js.\n * This can be used in server side scenario or for testing purposes\n */\nexport class NullEngine extends Engine {\n /**\n * Gets a boolean indicating that the engine is running in deterministic lock step mode\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep\n * @returns true if engine is in deterministic lock step mode\n */\n isDeterministicLockStep() {\n return this._options.deterministicLockstep;\n }\n /**\n * Gets the max steps when engine is running in deterministic lock step\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep\n * @returns the max steps\n */\n getLockstepMaxSteps() {\n return this._options.lockstepMaxSteps;\n }\n /**\n * Gets the current hardware scaling level.\n * By default the hardware scaling level is computed from the window device ratio.\n * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.\n * @returns a number indicating the current hardware scaling level\n */\n getHardwareScalingLevel() {\n return 1.0;\n }\n constructor(options = new NullEngineOptions()) {\n super(null);\n Engine.Instances.push(this);\n if (options.deterministicLockstep === undefined) {\n options.deterministicLockstep = false;\n }\n if (options.lockstepMaxSteps === undefined) {\n options.lockstepMaxSteps = 4;\n }\n this._options = options;\n PerformanceConfigurator.SetMatrixPrecision(!!options.useHighPrecisionMatrix);\n // Init caps\n // We consider we are on a webgl1 capable device\n this._caps = {\n maxTexturesImageUnits: 16,\n maxVertexTextureImageUnits: 16,\n maxCombinedTexturesImageUnits: 32,\n maxTextureSize: 512,\n maxCubemapTextureSize: 512,\n maxRenderTextureSize: 512,\n maxVertexAttribs: 16,\n maxVaryingVectors: 16,\n maxFragmentUniformVectors: 16,\n maxVertexUniformVectors: 16,\n standardDerivatives: false,\n astc: null,\n pvrtc: null,\n etc1: null,\n etc2: null,\n bptc: null,\n maxAnisotropy: 0,\n uintIndices: false,\n fragmentDepthSupported: false,\n highPrecisionShaderSupported: true,\n colorBufferFloat: false,\n textureFloat: false,\n textureFloatLinearFiltering: false,\n textureFloatRender: false,\n textureHalfFloat: false,\n textureHalfFloatLinearFiltering: false,\n textureHalfFloatRender: false,\n textureLOD: false,\n texelFetch: false,\n drawBuffersExtension: false,\n depthTextureExtension: false,\n vertexArrayObject: false,\n instancedArrays: false,\n supportOcclusionQuery: false,\n canUseTimestampForTimerQuery: false,\n maxMSAASamples: 1,\n blendMinMax: false,\n canUseGLInstanceID: false,\n canUseGLVertexID: false,\n supportComputeShaders: false,\n supportSRGBBuffers: false,\n supportTransformFeedbacks: false,\n textureMaxLevel: false,\n texture2DArrayMaxLayerCount: 128,\n disableMorphTargetTexture: false,\n };\n this._features = {\n forceBitmapOverHTMLImageElement: false,\n supportRenderAndCopyToLodForFloatTextures: false,\n supportDepthStencilTexture: false,\n supportShadowSamplers: false,\n uniformBufferHardCheckMatrix: false,\n allowTexturePrefiltering: false,\n trackUbosInFrame: false,\n checkUbosContentBeforeUpload: false,\n supportCSM: false,\n basisNeedsPOT: false,\n support3DTextures: false,\n needTypeSuffixInShaderConstants: false,\n supportMSAA: false,\n supportSSAO2: false,\n supportExtendedTextureFormats: false,\n supportSwitchCaseInShader: false,\n supportSyncTextureRead: false,\n needsInvertingBitmap: false,\n useUBOBindingCache: false,\n needShaderCodeInlining: false,\n needToAlwaysBindUniformBuffers: false,\n supportRenderPasses: true,\n supportSpriteInstancing: false,\n _collectUbosUpdatedInFrame: false,\n };\n Logger.Log(`Babylon.js v${Engine.Version} - Null engine`);\n // Wrappers\n const theCurrentGlobal = typeof self !== \"undefined\" ? self : typeof global !== \"undefined\" ? global : window;\n if (typeof URL === \"undefined\") {\n theCurrentGlobal.URL = {\n createObjectURL: function () { },\n revokeObjectURL: function () { },\n };\n }\n if (typeof Blob === \"undefined\") {\n theCurrentGlobal.Blob = function () { };\n }\n }\n /**\n * Creates a vertex buffer\n * @param vertices the data for the vertex buffer\n * @returns the new WebGL static buffer\n */\n createVertexBuffer(vertices) {\n const buffer = new DataBuffer();\n buffer.references = 1;\n return buffer;\n }\n /**\n * Creates a new index buffer\n * @param indices defines the content of the index buffer\n * @returns a new webGL buffer\n */\n createIndexBuffer(indices) {\n const buffer = new DataBuffer();\n buffer.references = 1;\n return buffer;\n }\n /**\n * Clear the current render buffer or the current render target (if any is set up)\n * @param color defines the color to use\n * @param backBuffer defines if the back buffer must be cleared\n * @param depth defines if the depth buffer must be cleared\n * @param stencil defines if the stencil buffer must be cleared\n */\n clear(color, backBuffer, depth, stencil = false) { }\n /**\n * Gets the current render width\n * @param useScreen defines if screen size must be used (or the current render target if any)\n * @returns a number defining the current render width\n */\n getRenderWidth(useScreen = false) {\n if (!useScreen && this._currentRenderTarget) {\n return this._currentRenderTarget.width;\n }\n return this._options.renderWidth;\n }\n /**\n * Gets the current render height\n * @param useScreen defines if screen size must be used (or the current render target if any)\n * @returns a number defining the current render height\n */\n getRenderHeight(useScreen = false) {\n if (!useScreen && this._currentRenderTarget) {\n return this._currentRenderTarget.height;\n }\n return this._options.renderHeight;\n }\n /**\n * Set the WebGL's viewport\n * @param viewport defines the viewport element to be used\n * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used\n * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used\n */\n setViewport(viewport, requiredWidth, requiredHeight) {\n this._cachedViewport = viewport;\n }\n createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context) {\n return {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n __SPECTOR_rebuildProgram: null,\n };\n }\n /**\n * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names\n * @param pipelineContext defines the pipeline context to use\n * @param uniformsNames defines the list of uniform names\n * @returns an array of webGL uniform locations\n */\n getUniforms(pipelineContext, uniformsNames) {\n return [];\n }\n /**\n * Gets the lsit of active attributes for a given webGL program\n * @param pipelineContext defines the pipeline context to use\n * @param attributesNames defines the list of attribute names to get\n * @returns an array of indices indicating the offset of each attribute\n */\n getAttributes(pipelineContext, attributesNames) {\n return [];\n }\n /**\n * Binds an effect to the webGL context\n * @param effect defines the effect to bind\n */\n bindSamplers(effect) {\n this._currentEffect = null;\n }\n /**\n * Activates an effect, making it the current one (ie. the one used for rendering)\n * @param effect defines the effect to activate\n */\n enableEffect(effect) {\n effect = effect !== null && DrawWrapper.IsWrapper(effect) ? effect.effect : effect; // get only the effect, we don't need a Wrapper in the WebGL engine\n this._currentEffect = effect;\n if (!effect) {\n return;\n }\n if (effect.onBind) {\n effect.onBind(effect);\n }\n if (effect._onBindObservable) {\n effect._onBindObservable.notifyObservers(effect);\n }\n }\n /**\n * Set various states to the webGL context\n * @param culling defines culling state: true to enable culling, false to disable it\n * @param zOffset defines the value to apply to zOffset (0 by default)\n * @param force defines if states must be applied even if cache is up to date\n * @param reverseSide defines if culling must be reversed (CCW if false, CW if true)\n * @param cullBackFaces true to cull back faces, false to cull front faces (if culling is enabled)\n * @param stencil stencil states to set\n * @param zOffsetUnits defines the value to apply to zOffsetUnits (0 by default)\n */\n setState(culling, zOffset = 0, force, reverseSide = false, cullBackFaces, stencil, zOffsetUnits = 0) { }\n /**\n * Set the value of an uniform to an array of int32\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of int32 to store\n * @returns true if value was set\n */\n setIntArray(uniform, array) {\n return true;\n }\n /**\n * Set the value of an uniform to an array of int32 (stored as vec2)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of int32 to store\n * @returns true if value was set\n */\n setIntArray2(uniform, array) {\n return true;\n }\n /**\n * Set the value of an uniform to an array of int32 (stored as vec3)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of int32 to store\n * @returns true if value was set\n */\n setIntArray3(uniform, array) {\n return true;\n }\n /**\n * Set the value of an uniform to an array of int32 (stored as vec4)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of int32 to store\n * @returns true if value was set\n */\n setIntArray4(uniform, array) {\n return true;\n }\n /**\n * Set the value of an uniform to an array of float32\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of float32 to store\n * @returns true if value was set\n */\n setFloatArray(uniform, array) {\n return true;\n }\n /**\n * Set the value of an uniform to an array of float32 (stored as vec2)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of float32 to store\n * @returns true if value was set\n */\n setFloatArray2(uniform, array) {\n return true;\n }\n /**\n * Set the value of an uniform to an array of float32 (stored as vec3)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of float32 to store\n * @returns true if value was set\n */\n setFloatArray3(uniform, array) {\n return true;\n }\n /**\n * Set the value of an uniform to an array of float32 (stored as vec4)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of float32 to store\n * @returns true if value was set\n */\n setFloatArray4(uniform, array) {\n return true;\n }\n /**\n * Set the value of an uniform to an array of number\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of number to store\n * @returns true if value was set\n */\n setArray(uniform, array) {\n return true;\n }\n /**\n * Set the value of an uniform to an array of number (stored as vec2)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of number to store\n * @returns true if value was set\n */\n setArray2(uniform, array) {\n return true;\n }\n /**\n * Set the value of an uniform to an array of number (stored as vec3)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of number to store\n * @returns true if value was set\n */\n setArray3(uniform, array) {\n return true;\n }\n /**\n * Set the value of an uniform to an array of number (stored as vec4)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of number to store\n * @returns true if value was set\n */\n setArray4(uniform, array) {\n return true;\n }\n /**\n * Set the value of an uniform to an array of float32 (stored as matrices)\n * @param uniform defines the webGL uniform location where to store the value\n * @param matrices defines the array of float32 to store\n * @returns true if value was set\n */\n setMatrices(uniform, matrices) {\n return true;\n }\n /**\n * Set the value of an uniform to a matrix (3x3)\n * @param uniform defines the webGL uniform location where to store the value\n * @param matrix defines the Float32Array representing the 3x3 matrix to store\n * @returns true if value was set\n */\n setMatrix3x3(uniform, matrix) {\n return true;\n }\n /**\n * Set the value of an uniform to a matrix (2x2)\n * @param uniform defines the webGL uniform location where to store the value\n * @param matrix defines the Float32Array representing the 2x2 matrix to store\n * @returns true if value was set\n */\n setMatrix2x2(uniform, matrix) {\n return true;\n }\n /**\n * Set the value of an uniform to a number (float)\n * @param uniform defines the webGL uniform location where to store the value\n * @param value defines the float number to store\n * @returns true if value was set\n */\n setFloat(uniform, value) {\n return true;\n }\n /**\n * Set the value of an uniform to a vec2\n * @param uniform defines the webGL uniform location where to store the value\n * @param x defines the 1st component of the value\n * @param y defines the 2nd component of the value\n * @returns true if value was set\n */\n setFloat2(uniform, x, y) {\n return true;\n }\n /**\n * Set the value of an uniform to a vec3\n * @param uniform defines the webGL uniform location where to store the value\n * @param x defines the 1st component of the value\n * @param y defines the 2nd component of the value\n * @param z defines the 3rd component of the value\n * @returns true if value was set\n */\n setFloat3(uniform, x, y, z) {\n return true;\n }\n /**\n * Set the value of an uniform to a boolean\n * @param uniform defines the webGL uniform location where to store the value\n * @param bool defines the boolean to store\n * @returns true if value was set\n */\n setBool(uniform, bool) {\n return true;\n }\n /**\n * Set the value of an uniform to a vec4\n * @param uniform defines the webGL uniform location where to store the value\n * @param x defines the 1st component of the value\n * @param y defines the 2nd component of the value\n * @param z defines the 3rd component of the value\n * @param w defines the 4th component of the value\n * @returns true if value was set\n */\n setFloat4(uniform, x, y, z, w) {\n return true;\n }\n /**\n * Sets the current alpha mode\n * @param mode defines the mode to use (one of the Engine.ALPHA_XXX)\n * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/transparent_rendering\n */\n setAlphaMode(mode, noDepthWriteChange = false) {\n if (this._alphaMode === mode) {\n return;\n }\n this.alphaState.alphaBlend = mode !== 0;\n if (!noDepthWriteChange) {\n this.setDepthWrite(mode === 0);\n }\n this._alphaMode = mode;\n }\n /**\n * Bind webGl buffers directly to the webGL context\n * @param vertexBuffers defines the vertex buffer to bind\n * @param indexBuffer defines the index buffer to bind\n * @param effect defines the effect associated with the vertex buffer\n */\n bindBuffers(vertexBuffers, indexBuffer, effect) { }\n /**\n * Force the entire cache to be cleared\n * You should not have to use this function unless your engine needs to share the webGL context with another engine\n * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)\n */\n wipeCaches(bruteForce) {\n if (this.preventCacheWipeBetweenFrames) {\n return;\n }\n this.resetTextureCache();\n this._currentEffect = null;\n if (bruteForce) {\n this._currentProgram = null;\n this._stencilStateComposer.reset();\n this.depthCullingState.reset();\n this.alphaState.reset();\n }\n this._cachedVertexBuffers = null;\n this._cachedIndexBuffer = null;\n this._cachedEffectForVertexBuffers = null;\n }\n /**\n * Send a draw order\n * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)\n * @param indexStart defines the starting index\n * @param indexCount defines the number of index to draw\n * @param instancesCount defines the number of instances to draw (if instantiation is enabled)\n */\n draw(useTriangles, indexStart, indexCount, instancesCount) { }\n /**\n * Draw a list of indexed primitives\n * @param fillMode defines the primitive to use\n * @param indexStart defines the starting index\n * @param indexCount defines the number of index to draw\n * @param instancesCount defines the number of instances to draw (if instantiation is enabled)\n */\n drawElementsType(fillMode, indexStart, indexCount, instancesCount) { }\n /**\n * Draw a list of unindexed primitives\n * @param fillMode defines the primitive to use\n * @param verticesStart defines the index of first vertex to draw\n * @param verticesCount defines the count of vertices to draw\n * @param instancesCount defines the number of instances to draw (if instantiation is enabled)\n */\n drawArraysType(fillMode, verticesStart, verticesCount, instancesCount) { }\n /** @internal */\n _createTexture() {\n return {};\n }\n /**\n * @internal\n */\n _releaseTexture(texture) { }\n /**\n * Usually called from Texture.ts.\n * Passed information to create a WebGLTexture\n * @param urlArg defines a value which contains one of the following:\n * * A conventional http URL, e.g. 'http://...' or 'file://...'\n * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'\n * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'\n * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file\n * @param invertY when true, image is flipped when loaded. You probably want true. Certain compressed textures may invert this if their default is inverted (eg. ktx)\n * @param scene needed for loading to the correct scene\n * @param samplingMode mode with should be used sample / access the texture (Default: Texture.TRILINEAR_SAMPLINGMODE)\n * @param onLoad optional callback to be called upon successful completion\n * @param onError optional callback to be called upon failure\n * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob\n * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities\n * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures\n * @param forcedExtension defines the extension to use to pick the right loader\n * @param mimeType defines an optional mime type\n * @returns a InternalTexture for assignment back into BABYLON.Texture\n */\n createTexture(urlArg, noMipmap, invertY, scene, samplingMode = 3, onLoad = null, onError = null, buffer = null, fallback = null, format = null, forcedExtension = null, mimeType) {\n const texture = new InternalTexture(this, InternalTextureSource.Url);\n const url = String(urlArg);\n texture.url = url;\n texture.generateMipMaps = !noMipmap;\n texture.samplingMode = samplingMode;\n texture.invertY = invertY;\n texture.baseWidth = this._options.textureSize;\n texture.baseHeight = this._options.textureSize;\n texture.width = this._options.textureSize;\n texture.height = this._options.textureSize;\n if (format) {\n texture.format = format;\n }\n texture.isReady = true;\n if (onLoad) {\n setTimeout(() => {\n onLoad(texture);\n });\n }\n this._internalTexturesCache.push(texture);\n return texture;\n }\n /**\n * @internal\n */\n _createHardwareRenderTargetWrapper(isMulti, isCube, size) {\n const rtWrapper = new RenderTargetWrapper(isMulti, isCube, size, this);\n this._renderTargetWrapperCache.push(rtWrapper);\n return rtWrapper;\n }\n /**\n * Creates a new render target wrapper\n * @param size defines the size of the texture\n * @param options defines the options used to create the texture\n * @returns a new render target wrapper\n */\n createRenderTargetTexture(size, options) {\n const rtWrapper = this._createHardwareRenderTargetWrapper(false, false, size);\n const fullOptions = {};\n if (options !== undefined && typeof options === \"object\") {\n fullOptions.generateMipMaps = options.generateMipMaps;\n fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;\n fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;\n fullOptions.type = options.type === undefined ? 0 : options.type;\n fullOptions.samplingMode = options.samplingMode === undefined ? 3 : options.samplingMode;\n }\n else {\n fullOptions.generateMipMaps = options;\n fullOptions.generateDepthBuffer = true;\n fullOptions.generateStencilBuffer = false;\n fullOptions.type = 0;\n fullOptions.samplingMode = 3;\n }\n const texture = new InternalTexture(this, InternalTextureSource.RenderTarget);\n const width = size.width || size;\n const height = size.height || size;\n rtWrapper._generateDepthBuffer = fullOptions.generateDepthBuffer;\n rtWrapper._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = width;\n texture.height = height;\n texture.isReady = true;\n texture.samples = 1;\n texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;\n texture.samplingMode = fullOptions.samplingMode;\n texture.type = fullOptions.type;\n this._internalTexturesCache.push(texture);\n return rtWrapper;\n }\n /**\n * Creates a new render target wrapper\n * @param size defines the size of the texture\n * @param options defines the options used to create the texture\n * @returns a new render target wrapper\n */\n createRenderTargetCubeTexture(size, options) {\n const rtWrapper = this._createHardwareRenderTargetWrapper(false, true, size);\n const fullOptions = Object.assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: 0, samplingMode: 3, format: 5 }, options);\n fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;\n if (fullOptions.type === 1 && !this._caps.textureFloatLinearFiltering) {\n // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE\n fullOptions.samplingMode = 1;\n }\n else if (fullOptions.type === 2 && !this._caps.textureHalfFloatLinearFiltering) {\n // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE\n fullOptions.samplingMode = 1;\n }\n rtWrapper._generateDepthBuffer = fullOptions.generateDepthBuffer;\n rtWrapper._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;\n const texture = new InternalTexture(this, InternalTextureSource.RenderTarget);\n texture.baseWidth = size;\n texture.baseHeight = size;\n texture.width = size;\n texture.height = size;\n texture.isReady = true;\n texture.isCube = true;\n texture.samples = 1;\n texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;\n texture.samplingMode = fullOptions.samplingMode;\n texture.type = fullOptions.type;\n this._internalTexturesCache.push(texture);\n return rtWrapper;\n }\n /**\n * Update the sampling mode of a given texture\n * @param samplingMode defines the required sampling mode\n * @param texture defines the texture to update\n */\n updateTextureSamplingMode(samplingMode, texture) {\n texture.samplingMode = samplingMode;\n }\n /**\n * Creates a raw texture\n * @param data defines the data to store in the texture\n * @param width defines the width of the texture\n * @param height defines the height of the texture\n * @param format defines the format of the data\n * @param generateMipMaps defines if the engine should generate the mip levels\n * @param invertY defines if data must be stored with Y axis inverted\n * @param samplingMode defines the required sampling mode (Texture.NEAREST_SAMPLINGMODE by default)\n * @param compression defines the compression used (null by default)\n * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_INT by default)\n * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)\n * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU).\n * @returns the raw texture inside an InternalTexture\n */\n createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, compression = null, type = 0, creationFlags = 0, useSRGBBuffer = false) {\n const texture = new InternalTexture(this, InternalTextureSource.Raw);\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = width;\n texture.height = height;\n texture.format = format;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.invertY = invertY;\n texture._compression = compression;\n texture.type = type;\n texture._useSRGBBuffer = useSRGBBuffer;\n if (!this._doNotHandleContextLost) {\n texture._bufferView = data;\n }\n return texture;\n }\n /**\n * Update a raw texture\n * @param texture defines the texture to update\n * @param data defines the data to store in the texture\n * @param format defines the format of the data\n * @param invertY defines if data must be stored with Y axis inverted\n * @param compression defines the compression used (null by default)\n * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_INT by default)\n * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU).\n */\n updateRawTexture(texture, data, format, invertY, compression = null, type = 0, useSRGBBuffer = false) {\n if (texture) {\n texture._bufferView = data;\n texture.format = format;\n texture.invertY = invertY;\n texture._compression = compression;\n texture.type = type;\n texture._useSRGBBuffer = useSRGBBuffer;\n }\n }\n /**\n * Binds the frame buffer to the specified texture.\n * @param rtWrapper The render target wrapper to render to\n * @param faceIndex The face of the texture to render to in case of cube texture\n * @param requiredWidth The width of the target to render to\n * @param requiredHeight The height of the target to render to\n * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true\n */\n bindFramebuffer(rtWrapper, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {\n if (this._currentRenderTarget) {\n this.unBindFramebuffer(this._currentRenderTarget);\n }\n this._currentRenderTarget = rtWrapper;\n this._currentFramebuffer = null;\n if (this._cachedViewport && !forceFullscreenViewport) {\n this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);\n }\n }\n /**\n * Unbind the current render target texture from the webGL context\n * @param rtWrapper defines the render target wrapper to unbind\n * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated\n * @param onBeforeUnbind defines a function which will be called before the effective unbind\n */\n unBindFramebuffer(rtWrapper, disableGenerateMipMaps = false, onBeforeUnbind) {\n this._currentRenderTarget = null;\n if (onBeforeUnbind) {\n onBeforeUnbind();\n }\n this._currentFramebuffer = null;\n }\n /**\n * Creates a dynamic vertex buffer\n * @param vertices the data for the dynamic vertex buffer\n * @returns the new WebGL dynamic buffer\n */\n createDynamicVertexBuffer(vertices) {\n const buffer = new DataBuffer();\n buffer.references = 1;\n buffer.capacity = 1;\n return buffer;\n }\n /**\n * Update the content of a dynamic texture\n * @param texture defines the texture to update\n * @param canvas defines the canvas containing the source\n * @param invertY defines if data must be stored with Y axis inverted\n * @param premulAlpha defines if alpha is stored as premultiplied\n * @param format defines the format of the data\n */\n updateDynamicTexture(texture, canvas, invertY, premulAlpha = false, format) { }\n /**\n * Gets a boolean indicating if all created effects are ready\n * @returns true if all effects are ready\n */\n areAllEffectsReady() {\n return true;\n }\n /**\n * @internal\n * Get the current error code of the webGL context\n * @returns the error code\n * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError\n */\n getError() {\n return 0;\n }\n /** @internal */\n _getUnpackAlignement() {\n return 1;\n }\n /**\n * @internal\n */\n _unpackFlipY(value) { }\n /**\n * Update a dynamic index buffer\n * @param indexBuffer defines the target index buffer\n * @param indices defines the data to update\n * @param offset defines the offset in the target index buffer where update should start\n */\n updateDynamicIndexBuffer(indexBuffer, indices, offset = 0) { }\n /**\n * Updates a dynamic vertex buffer.\n * @param vertexBuffer the vertex buffer to update\n * @param vertices the data used to update the vertex buffer\n * @param byteOffset the byte offset of the data (optional)\n * @param byteLength the byte length of the data (optional)\n */\n updateDynamicVertexBuffer(vertexBuffer, vertices, byteOffset, byteLength) { }\n /**\n * @internal\n */\n _bindTextureDirectly(target, texture) {\n if (this._boundTexturesCache[this._activeChannel] !== texture) {\n this._boundTexturesCache[this._activeChannel] = texture;\n return true;\n }\n return false;\n }\n /**\n * @internal\n */\n _bindTexture(channel, texture) {\n if (channel < 0) {\n return;\n }\n this._bindTextureDirectly(0, texture);\n }\n _deleteBuffer(buffer) { }\n /**\n * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled\n */\n releaseEffects() { }\n displayLoadingUI() { }\n hideLoadingUI() { }\n set loadingUIText(_) { }\n /**\n * @internal\n */\n _uploadCompressedDataToTextureDirectly(texture, internalFormat, width, height, data, faceIndex = 0, lod = 0) { }\n /**\n * @internal\n */\n _uploadDataToTextureDirectly(texture, imageData, faceIndex = 0, lod = 0) { }\n /**\n * @internal\n */\n _uploadArrayBufferViewToTexture(texture, imageData, faceIndex = 0, lod = 0) { }\n /**\n * @internal\n */\n _uploadImageToTexture(texture, image, faceIndex = 0, lod = 0) { }\n}\n//# sourceMappingURL=nullEngine.js.map","/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { ThinEngine } from \"../../Engines/thinEngine.js\";\nThinEngine.prototype._debugPushGroup = function (groupName, targetObject) { };\nThinEngine.prototype._debugPopGroup = function (targetObject) { };\nThinEngine.prototype._debugInsertMarker = function (text, targetObject) { };\nThinEngine.prototype._debugFlushPendingCommands = function () { };\n//# sourceMappingURL=engine.debugging.js.map","/**\n * @internal\n **/\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class _TimeToken {\n constructor() {\n this._timeElapsedQueryEnded = false;\n }\n}\n//# sourceMappingURL=timeToken.js.map","import { Engine } from \"../../Engines/engine.js\";\nimport { AbstractMesh } from \"../../Meshes/abstractMesh.js\";\nimport { _TimeToken } from \"../../Instrumentation/timeToken.js\";\nimport { PerfCounter } from \"../../Misc/perfCounter.js\";\n/** @internal */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class _OcclusionDataStorage {\n constructor() {\n /** @internal */\n this.occlusionInternalRetryCounter = 0;\n /** @internal */\n this.isOcclusionQueryInProgress = false;\n /** @internal */\n this.isOccluded = false;\n /** @internal */\n this.occlusionRetryCount = -1;\n /** @internal */\n this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;\n /** @internal */\n this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;\n /** @internal */\n this.forceRenderingWhenOccluded = false;\n }\n}\nEngine.prototype.createQuery = function () {\n const query = this._gl.createQuery();\n if (!query) {\n throw new Error(\"Unable to create Occlusion Query\");\n }\n return query;\n};\nEngine.prototype.deleteQuery = function (query) {\n this._gl.deleteQuery(query);\n return this;\n};\nEngine.prototype.isQueryResultAvailable = function (query) {\n return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);\n};\nEngine.prototype.getQueryResult = function (query) {\n return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);\n};\nEngine.prototype.beginOcclusionQuery = function (algorithmType, query) {\n const glAlgorithm = this._getGlAlgorithmType(algorithmType);\n this._gl.beginQuery(glAlgorithm, query);\n return true;\n};\nEngine.prototype.endOcclusionQuery = function (algorithmType) {\n const glAlgorithm = this._getGlAlgorithmType(algorithmType);\n this._gl.endQuery(glAlgorithm);\n return this;\n};\nEngine.prototype._createTimeQuery = function () {\n const timerQuery = this.getCaps().timerQuery;\n if (timerQuery.createQueryEXT) {\n return timerQuery.createQueryEXT();\n }\n return this.createQuery();\n};\nEngine.prototype._deleteTimeQuery = function (query) {\n const timerQuery = this.getCaps().timerQuery;\n if (timerQuery.deleteQueryEXT) {\n timerQuery.deleteQueryEXT(query);\n return;\n }\n this.deleteQuery(query);\n};\nEngine.prototype._getTimeQueryResult = function (query) {\n const timerQuery = this.getCaps().timerQuery;\n if (timerQuery.getQueryObjectEXT) {\n return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);\n }\n return this.getQueryResult(query);\n};\nEngine.prototype._getTimeQueryAvailability = function (query) {\n const timerQuery = this.getCaps().timerQuery;\n if (timerQuery.getQueryObjectEXT) {\n return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);\n }\n return this.isQueryResultAvailable(query);\n};\nEngine.prototype.startTimeQuery = function () {\n const caps = this.getCaps();\n const timerQuery = caps.timerQuery;\n if (!timerQuery) {\n return null;\n }\n const token = new _TimeToken();\n this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);\n if (caps.canUseTimestampForTimerQuery) {\n token._startTimeQuery = this._createTimeQuery();\n timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);\n }\n else {\n if (this._currentNonTimestampToken) {\n return this._currentNonTimestampToken;\n }\n token._timeElapsedQuery = this._createTimeQuery();\n if (timerQuery.beginQueryEXT) {\n timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);\n }\n else {\n this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);\n }\n this._currentNonTimestampToken = token;\n }\n return token;\n};\nEngine.prototype.endTimeQuery = function (token) {\n const caps = this.getCaps();\n const timerQuery = caps.timerQuery;\n if (!timerQuery || !token) {\n return -1;\n }\n if (caps.canUseTimestampForTimerQuery) {\n if (!token._startTimeQuery) {\n return -1;\n }\n if (!token._endTimeQuery) {\n token._endTimeQuery = this._createTimeQuery();\n timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);\n }\n }\n else if (!token._timeElapsedQueryEnded) {\n if (!token._timeElapsedQuery) {\n return -1;\n }\n if (timerQuery.endQueryEXT) {\n timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);\n }\n else {\n this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);\n this._currentNonTimestampToken = null;\n }\n token._timeElapsedQueryEnded = true;\n }\n const disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);\n let available = false;\n if (token._endTimeQuery) {\n available = this._getTimeQueryAvailability(token._endTimeQuery);\n }\n else if (token._timeElapsedQuery) {\n available = this._getTimeQueryAvailability(token._timeElapsedQuery);\n }\n if (available && !disjoint) {\n let result = 0;\n if (caps.canUseTimestampForTimerQuery) {\n if (!token._startTimeQuery || !token._endTimeQuery) {\n return -1;\n }\n const timeStart = this._getTimeQueryResult(token._startTimeQuery);\n const timeEnd = this._getTimeQueryResult(token._endTimeQuery);\n result = timeEnd - timeStart;\n this._deleteTimeQuery(token._startTimeQuery);\n this._deleteTimeQuery(token._endTimeQuery);\n token._startTimeQuery = null;\n token._endTimeQuery = null;\n }\n else {\n if (!token._timeElapsedQuery) {\n return -1;\n }\n result = this._getTimeQueryResult(token._timeElapsedQuery);\n this._deleteTimeQuery(token._timeElapsedQuery);\n token._timeElapsedQuery = null;\n token._timeElapsedQueryEnded = false;\n }\n return result;\n }\n return -1;\n};\nEngine.prototype._captureGPUFrameTime = false;\nEngine.prototype._gpuFrameTime = new PerfCounter();\nEngine.prototype.getGPUFrameTimeCounter = function () {\n return this._gpuFrameTime;\n};\nEngine.prototype.captureGPUFrameTime = function (value) {\n if (value === this._captureGPUFrameTime) {\n return;\n }\n this._captureGPUFrameTime = value;\n if (value) {\n this._onBeginFrameObserver = this.onBeginFrameObservable.add(() => {\n if (!this._gpuFrameTimeToken) {\n this._gpuFrameTimeToken = this.startTimeQuery();\n }\n });\n this._onEndFrameObserver = this.onEndFrameObservable.add(() => {\n if (!this._gpuFrameTimeToken) {\n return;\n }\n const time = this.endTimeQuery(this._gpuFrameTimeToken);\n if (time > -1) {\n this._gpuFrameTimeToken = null;\n this._gpuFrameTime.fetchNewFrame();\n this._gpuFrameTime.addCount(time, true);\n }\n });\n }\n else {\n this.onBeginFrameObservable.remove(this._onBeginFrameObserver);\n this._onBeginFrameObserver = null;\n this.onEndFrameObservable.remove(this._onEndFrameObserver);\n this._onEndFrameObserver = null;\n }\n};\nEngine.prototype._getGlAlgorithmType = function (algorithmType) {\n return algorithmType === AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;\n};\nObject.defineProperty(AbstractMesh.prototype, \"isOcclusionQueryInProgress\", {\n get: function () {\n return this._occlusionDataStorage.isOcclusionQueryInProgress;\n },\n set: function (value) {\n this._occlusionDataStorage.isOcclusionQueryInProgress = value;\n },\n enumerable: false,\n configurable: true,\n});\nObject.defineProperty(AbstractMesh.prototype, \"_occlusionDataStorage\", {\n get: function () {\n if (!this.__occlusionDataStorage) {\n this.__occlusionDataStorage = new _OcclusionDataStorage();\n }\n return this.__occlusionDataStorage;\n },\n enumerable: false,\n configurable: true,\n});\nObject.defineProperty(AbstractMesh.prototype, \"isOccluded\", {\n get: function () {\n return this._occlusionDataStorage.isOccluded;\n },\n set: function (value) {\n this._occlusionDataStorage.isOccluded = value;\n },\n enumerable: true,\n configurable: true,\n});\nObject.defineProperty(AbstractMesh.prototype, \"occlusionQueryAlgorithmType\", {\n get: function () {\n return this._occlusionDataStorage.occlusionQueryAlgorithmType;\n },\n set: function (value) {\n this._occlusionDataStorage.occlusionQueryAlgorithmType = value;\n },\n enumerable: true,\n configurable: true,\n});\nObject.defineProperty(AbstractMesh.prototype, \"occlusionType\", {\n get: function () {\n return this._occlusionDataStorage.occlusionType;\n },\n set: function (value) {\n this._occlusionDataStorage.occlusionType = value;\n },\n enumerable: true,\n configurable: true,\n});\nObject.defineProperty(AbstractMesh.prototype, \"occlusionRetryCount\", {\n get: function () {\n return this._occlusionDataStorage.occlusionRetryCount;\n },\n set: function (value) {\n this._occlusionDataStorage.occlusionRetryCount = value;\n },\n enumerable: true,\n configurable: true,\n});\nObject.defineProperty(AbstractMesh.prototype, \"forceRenderingWhenOccluded\", {\n get: function () {\n return this._occlusionDataStorage.forceRenderingWhenOccluded;\n },\n set: function (value) {\n this._occlusionDataStorage.forceRenderingWhenOccluded = value;\n },\n enumerable: true,\n configurable: true,\n});\n// We also need to update AbstractMesh as there is a portion of the code there\nAbstractMesh.prototype._checkOcclusionQuery = function () {\n const dataStorage = this._occlusionDataStorage;\n if (dataStorage.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {\n dataStorage.isOccluded = false;\n return false;\n }\n const engine = this.getEngine();\n if (!engine.getCaps().supportOcclusionQuery) {\n dataStorage.isOccluded = false;\n return false;\n }\n if (!engine.isQueryResultAvailable) {\n // Occlusion query where not referenced\n dataStorage.isOccluded = false;\n return false;\n }\n if (this.isOcclusionQueryInProgress && this._occlusionQuery) {\n const isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);\n if (isOcclusionQueryAvailable) {\n const occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);\n dataStorage.isOcclusionQueryInProgress = false;\n dataStorage.occlusionInternalRetryCounter = 0;\n dataStorage.isOccluded = occlusionQueryResult > 0 ? false : true;\n }\n else {\n dataStorage.occlusionInternalRetryCounter++;\n if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {\n dataStorage.isOcclusionQueryInProgress = false;\n dataStorage.occlusionInternalRetryCounter = 0;\n // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)\n // if strict continue the last state of the object.\n dataStorage.isOccluded = dataStorage.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;\n }\n else {\n return dataStorage.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;\n }\n }\n }\n const scene = this.getScene();\n if (scene.getBoundingBoxRenderer) {\n const occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();\n if (this._occlusionQuery === null) {\n this._occlusionQuery = engine.createQuery();\n }\n if (engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery)) {\n occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);\n engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);\n this._occlusionDataStorage.isOcclusionQueryInProgress = true;\n }\n }\n return dataStorage.isOccluded;\n};\n//# sourceMappingURL=engine.query.js.map","import { ThinEngine } from \"../../Engines/thinEngine.js\";\n\nThinEngine.prototype.updateVideoTexture = function (texture, video, invertY) {\n if (!texture || texture._isDisabled) {\n return;\n }\n const glformat = this._getInternalFormat(texture.format);\n const internalFormat = this._getRGBABufferInternalSizedFormat(0, texture.format);\n const wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);\n this._unpackFlipY(!invertY); // Video are upside down by default\n try {\n // Testing video texture support\n if (this._videoTextureSupported === undefined) {\n // clear old errors just in case.\n this._gl.getError();\n this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, glformat, this._gl.UNSIGNED_BYTE, video);\n if (this._gl.getError() !== 0) {\n this._videoTextureSupported = false;\n }\n else {\n this._videoTextureSupported = true;\n }\n }\n // Copy video through the current working canvas if video texture is not supported\n if (!this._videoTextureSupported) {\n if (!texture._workingCanvas) {\n texture._workingCanvas = this.createCanvas(texture.width, texture.height);\n const context = texture._workingCanvas.getContext(\"2d\");\n if (!context) {\n throw new Error(\"Unable to get 2d context\");\n }\n texture._workingContext = context;\n texture._workingCanvas.width = texture.width;\n texture._workingCanvas.height = texture.height;\n }\n texture._workingContext.clearRect(0, 0, texture.width, texture.height);\n texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);\n this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, glformat, this._gl.UNSIGNED_BYTE, texture._workingCanvas);\n }\n else {\n this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, glformat, this._gl.UNSIGNED_BYTE, video);\n }\n if (texture.generateMipMaps) {\n this._gl.generateMipmap(this._gl.TEXTURE_2D);\n }\n if (!wasPreviouslyBound) {\n this._bindTextureDirectly(this._gl.TEXTURE_2D, null);\n }\n // this.resetTextureCache();\n texture.isReady = true;\n }\n catch (ex) {\n // Something unexpected\n // Let's disable the texture\n texture._isDisabled = true;\n }\n};\n//# sourceMappingURL=engine.videoTexture.js.map","import { InternalTexture, InternalTextureSource } from \"../../Materials/Textures/internalTexture.js\";\nimport { Logger } from \"../../Misc/logger.js\";\n\nimport { ThinEngine } from \"../thinEngine.js\";\nThinEngine.prototype.restoreSingleAttachment = function () {\n const gl = this._gl;\n this.bindAttachments([gl.BACK]);\n};\nThinEngine.prototype.restoreSingleAttachmentForRenderTarget = function () {\n const gl = this._gl;\n this.bindAttachments([gl.COLOR_ATTACHMENT0]);\n};\nThinEngine.prototype.buildTextureLayout = function (textureStatus) {\n const gl = this._gl;\n const result = [];\n for (let i = 0; i < textureStatus.length; i++) {\n if (textureStatus[i]) {\n result.push(gl[\"COLOR_ATTACHMENT\" + i]);\n }\n else {\n result.push(gl.NONE);\n }\n }\n return result;\n};\nThinEngine.prototype.bindAttachments = function (attachments) {\n const gl = this._gl;\n gl.drawBuffers(attachments);\n};\nThinEngine.prototype.unBindMultiColorAttachmentFramebuffer = function (rtWrapper, disableGenerateMipMaps = false, onBeforeUnbind) {\n this._currentRenderTarget = null;\n // If MSAA, we need to bitblt back to main texture\n const gl = this._gl;\n const attachments = rtWrapper._attachments;\n const count = attachments.length;\n if (rtWrapper._MSAAFramebuffer) {\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, rtWrapper._MSAAFramebuffer);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, rtWrapper._framebuffer);\n for (let i = 0; i < count; i++) {\n const texture = rtWrapper.textures[i];\n for (let j = 0; j < count; j++) {\n attachments[j] = gl.NONE;\n }\n attachments[i] = gl[this.webGLVersion > 1 ? \"COLOR_ATTACHMENT\" + i : \"COLOR_ATTACHMENT\" + i + \"_WEBGL\"];\n gl.readBuffer(attachments[i]);\n gl.drawBuffers(attachments);\n gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);\n }\n for (let i = 0; i < count; i++) {\n attachments[i] = gl[this.webGLVersion > 1 ? \"COLOR_ATTACHMENT\" + i : \"COLOR_ATTACHMENT\" + i + \"_WEBGL\"];\n }\n gl.drawBuffers(attachments);\n }\n for (let i = 0; i < count; i++) {\n const texture = rtWrapper.textures[i];\n if ((texture === null || texture === void 0 ? void 0 : texture.generateMipMaps) && !disableGenerateMipMaps && !texture.isCube) {\n this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);\n gl.generateMipmap(gl.TEXTURE_2D);\n this._bindTextureDirectly(gl.TEXTURE_2D, null);\n }\n }\n if (onBeforeUnbind) {\n if (rtWrapper._MSAAFramebuffer) {\n // Bind the correct framebuffer\n this._bindUnboundFramebuffer(rtWrapper._framebuffer);\n }\n onBeforeUnbind();\n }\n this._bindUnboundFramebuffer(null);\n};\nThinEngine.prototype.createMultipleRenderTarget = function (size, options, initializeBuffers = true) {\n var _a;\n let generateMipMaps = false;\n let generateDepthBuffer = true;\n let generateStencilBuffer = false;\n let generateDepthTexture = false;\n let depthTextureFormat = 15;\n let textureCount = 1;\n const defaultType = 0;\n const defaultSamplingMode = 3;\n const defaultUseSRGBBuffer = false;\n const defaultFormat = 5;\n const defaultTarget = 3553;\n let types = new Array();\n let samplingModes = new Array();\n let useSRGBBuffers = new Array();\n let formats = new Array();\n let targets = new Array();\n let faceIndex = new Array();\n let layerIndex = new Array();\n let layers = new Array();\n const rtWrapper = this._createHardwareRenderTargetWrapper(true, false, size);\n if (options !== undefined) {\n generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;\n generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;\n generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;\n generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;\n textureCount = options.textureCount || 1;\n if (options.types) {\n types = options.types;\n }\n if (options.samplingModes) {\n samplingModes = options.samplingModes;\n }\n if (options.useSRGBBuffers) {\n useSRGBBuffers = options.useSRGBBuffers;\n }\n if (options.formats) {\n formats = options.formats;\n }\n if (options.targetTypes) {\n targets = options.targetTypes;\n }\n if (options.faceIndex) {\n faceIndex = options.faceIndex;\n }\n if (options.layerIndex) {\n layerIndex = options.layerIndex;\n }\n if (options.layerCounts) {\n layers = options.layerCounts;\n }\n if (this.webGLVersion > 1 &&\n (options.depthTextureFormat === 13 ||\n options.depthTextureFormat === 17 ||\n options.depthTextureFormat === 16 ||\n options.depthTextureFormat === 14 ||\n options.depthTextureFormat === 18)) {\n depthTextureFormat = options.depthTextureFormat;\n }\n }\n const gl = this._gl;\n // Create the framebuffer\n const framebuffer = gl.createFramebuffer();\n this._bindUnboundFramebuffer(framebuffer);\n const width = size.width || size;\n const height = size.height || size;\n const textures = [];\n const attachments = [];\n const useStencilTexture = this.webGLVersion > 1 &&\n generateDepthTexture &&\n (options.depthTextureFormat === 13 ||\n options.depthTextureFormat === 17 ||\n options.depthTextureFormat === 18);\n const depthStencilBuffer = this._setupFramebufferDepthAttachments(!useStencilTexture && generateStencilBuffer, !generateDepthTexture && generateDepthBuffer, width, height);\n rtWrapper._framebuffer = framebuffer;\n rtWrapper._depthStencilBuffer = depthStencilBuffer;\n rtWrapper._generateDepthBuffer = !generateDepthTexture && generateDepthBuffer;\n rtWrapper._generateStencilBuffer = !useStencilTexture && generateStencilBuffer;\n rtWrapper._attachments = attachments;\n for (let i = 0; i < textureCount; i++) {\n let samplingMode = samplingModes[i] || defaultSamplingMode;\n let type = types[i] || defaultType;\n let useSRGBBuffer = useSRGBBuffers[i] || defaultUseSRGBBuffer;\n const format = formats[i] || defaultFormat;\n const target = targets[i] || defaultTarget;\n const layerCount = (_a = layers[i]) !== null && _a !== void 0 ? _a : 1;\n if (type === 1 && !this._caps.textureFloatLinearFiltering) {\n // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE\n samplingMode = 1;\n }\n else if (type === 2 && !this._caps.textureHalfFloatLinearFiltering) {\n // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE\n samplingMode = 1;\n }\n const filters = this._getSamplingParameters(samplingMode, generateMipMaps);\n if (type === 1 && !this._caps.textureFloat) {\n type = 0;\n Logger.Warn(\"Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type\");\n }\n useSRGBBuffer = useSRGBBuffer && this._caps.supportSRGBBuffers && (this.webGLVersion > 1 || this.isWebGPU);\n const isWebGL2 = this.webGLVersion > 1;\n const attachment = gl[isWebGL2 ? \"COLOR_ATTACHMENT\" + i : \"COLOR_ATTACHMENT\" + i + \"_WEBGL\"];\n attachments.push(attachment);\n if (target === -1) {\n continue;\n }\n const texture = new InternalTexture(this, InternalTextureSource.MultiRenderTarget);\n textures[i] = texture;\n gl.activeTexture(gl[\"TEXTURE\" + i]);\n gl.bindTexture(target, texture._hardwareTexture.underlyingResource);\n gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, filters.mag);\n gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, filters.min);\n gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n const internalSizedFormat = this._getRGBABufferInternalSizedFormat(type, format, useSRGBBuffer);\n const internalFormat = this._getInternalFormat(format);\n const webGLTextureType = this._getWebGLTextureType(type);\n if (isWebGL2 && (target === 35866 || target === 32879)) {\n if (target === 35866) {\n texture.is2DArray = true;\n }\n else {\n texture.is3D = true;\n }\n texture.baseDepth = texture.depth = layerCount;\n gl.texImage3D(target, 0, internalSizedFormat, width, height, layerCount, 0, internalFormat, webGLTextureType, null);\n }\n else if (target === 34067) {\n // We have to generate all faces to complete the framebuffer\n for (let i = 0; i < 6; i++) {\n gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, internalSizedFormat, width, height, 0, internalFormat, webGLTextureType, null);\n }\n texture.isCube = true;\n }\n else {\n gl.texImage2D(gl.TEXTURE_2D, 0, internalSizedFormat, width, height, 0, internalFormat, webGLTextureType, null);\n }\n if (generateMipMaps) {\n gl.generateMipmap(target);\n }\n // Unbind\n this._bindTextureDirectly(target, null);\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = width;\n texture.height = height;\n texture.isReady = true;\n texture.samples = 1;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.type = type;\n texture._useSRGBBuffer = useSRGBBuffer;\n texture.format = format;\n this._internalTexturesCache.push(texture);\n }\n if (generateDepthTexture && this._caps.depthTextureExtension) {\n // Depth texture\n const depthTexture = new InternalTexture(this, InternalTextureSource.Depth);\n let depthTextureType = 5;\n let glDepthTextureInternalFormat = gl.DEPTH_COMPONENT16;\n let glDepthTextureFormat = gl.DEPTH_COMPONENT;\n let glDepthTextureType = gl.UNSIGNED_SHORT;\n let glDepthTextureAttachment = gl.DEPTH_ATTACHMENT;\n if (this.webGLVersion < 2) {\n glDepthTextureInternalFormat = gl.DEPTH_COMPONENT;\n }\n else {\n if (depthTextureFormat === 14) {\n depthTextureType = 1;\n glDepthTextureType = gl.FLOAT;\n glDepthTextureInternalFormat = gl.DEPTH_COMPONENT32F;\n }\n else if (depthTextureFormat === 18) {\n depthTextureType = 0;\n glDepthTextureType = gl.FLOAT_32_UNSIGNED_INT_24_8_REV;\n glDepthTextureInternalFormat = gl.DEPTH32F_STENCIL8;\n glDepthTextureFormat = gl.DEPTH_STENCIL;\n glDepthTextureAttachment = gl.DEPTH_STENCIL_ATTACHMENT;\n }\n else if (depthTextureFormat === 16) {\n depthTextureType = 0;\n glDepthTextureType = gl.UNSIGNED_INT;\n glDepthTextureInternalFormat = gl.DEPTH_COMPONENT24;\n glDepthTextureAttachment = gl.DEPTH_ATTACHMENT;\n }\n else if (depthTextureFormat === 13 || depthTextureFormat === 17) {\n depthTextureType = 12;\n glDepthTextureType = gl.UNSIGNED_INT_24_8;\n glDepthTextureInternalFormat = gl.DEPTH24_STENCIL8;\n glDepthTextureFormat = gl.DEPTH_STENCIL;\n glDepthTextureAttachment = gl.DEPTH_STENCIL_ATTACHMENT;\n }\n }\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, depthTexture._hardwareTexture.underlyingResource);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texImage2D(gl.TEXTURE_2D, 0, glDepthTextureInternalFormat, width, height, 0, glDepthTextureFormat, glDepthTextureType, null);\n gl.framebufferTexture2D(gl.FRAMEBUFFER, glDepthTextureAttachment, gl.TEXTURE_2D, depthTexture._hardwareTexture.underlyingResource, 0);\n depthTexture.baseWidth = width;\n depthTexture.baseHeight = height;\n depthTexture.width = width;\n depthTexture.height = height;\n depthTexture.isReady = true;\n depthTexture.samples = 1;\n depthTexture.generateMipMaps = generateMipMaps;\n depthTexture.samplingMode = 1;\n depthTexture.format = depthTextureFormat;\n depthTexture.type = depthTextureType;\n textures[textureCount] = depthTexture;\n this._internalTexturesCache.push(depthTexture);\n }\n rtWrapper.setTextures(textures);\n if (initializeBuffers) {\n gl.drawBuffers(attachments);\n }\n this._bindUnboundFramebuffer(null);\n rtWrapper.setLayerAndFaceIndices(layerIndex, faceIndex);\n this.resetTextureCache();\n return rtWrapper;\n};\nThinEngine.prototype.updateMultipleRenderTargetTextureSampleCount = function (rtWrapper, samples, initializeBuffers = true) {\n if (this.webGLVersion < 2 || !rtWrapper || !rtWrapper.texture) {\n return 1;\n }\n if (rtWrapper.samples === samples) {\n return samples;\n }\n const count = rtWrapper._attachments.length;\n if (count === 0) {\n return 1;\n }\n const gl = this._gl;\n samples = Math.min(samples, this.getCaps().maxMSAASamples);\n // Dispose previous render buffers\n const useDepthStencil = !!rtWrapper._depthStencilBuffer;\n if (useDepthStencil) {\n gl.deleteRenderbuffer(rtWrapper._depthStencilBuffer);\n rtWrapper._depthStencilBuffer = null;\n }\n if (rtWrapper._MSAAFramebuffer) {\n gl.deleteFramebuffer(rtWrapper._MSAAFramebuffer);\n rtWrapper._MSAAFramebuffer = null;\n }\n if (samples > 1 && typeof gl.renderbufferStorageMultisample === \"function\") {\n const framebuffer = gl.createFramebuffer();\n if (!framebuffer) {\n throw new Error(\"Unable to create multi sampled framebuffer\");\n }\n rtWrapper._MSAAFramebuffer = framebuffer;\n this._bindUnboundFramebuffer(framebuffer);\n const attachments = [];\n for (let i = 0; i < count; i++) {\n const texture = rtWrapper.textures[i];\n const hardwareTexture = texture._hardwareTexture;\n hardwareTexture.releaseMSAARenderBuffers();\n }\n for (let i = 0; i < count; i++) {\n const texture = rtWrapper.textures[i];\n const hardwareTexture = texture._hardwareTexture;\n const attachment = gl[this.webGLVersion > 1 ? \"COLOR_ATTACHMENT\" + i : \"COLOR_ATTACHMENT\" + i + \"_WEBGL\"];\n const colorRenderbuffer = this._createRenderBuffer(texture.width, texture.height, samples, -1 /* not used */, this._getRGBAMultiSampleBufferFormat(texture.type, texture.format), attachment);\n if (!colorRenderbuffer) {\n throw new Error(\"Unable to create multi sampled framebuffer\");\n }\n hardwareTexture.addMSAARenderBuffer(colorRenderbuffer);\n texture.samples = samples;\n attachments.push(attachment);\n }\n if (initializeBuffers) {\n gl.drawBuffers(attachments);\n }\n }\n else {\n this._bindUnboundFramebuffer(rtWrapper._framebuffer);\n }\n if (useDepthStencil) {\n rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(rtWrapper._generateStencilBuffer, rtWrapper._generateDepthBuffer, rtWrapper.texture.width, rtWrapper.texture.height, samples);\n }\n this._bindUnboundFramebuffer(null);\n return samples;\n};\n//# sourceMappingURL=engine.multiRender.js.map","import { ThinEngine } from \"../../Engines/thinEngine.js\";\nimport { InternalTexture, InternalTextureSource } from \"../../Materials/Textures/internalTexture.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { LoadImage } from \"../../Misc/fileTools.js\";\nimport { RandomGUID } from \"../../Misc/guid.js\";\n\nThinEngine.prototype._createDepthStencilCubeTexture = function (size, options, rtWrapper) {\n const internalTexture = new InternalTexture(this, InternalTextureSource.DepthStencil);\n internalTexture.isCube = true;\n if (this.webGLVersion === 1) {\n Logger.Error(\"Depth cube texture is not supported by WebGL 1.\");\n return internalTexture;\n }\n const internalOptions = Object.assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);\n const gl = this._gl;\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);\n this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);\n rtWrapper._depthStencilTexture = internalTexture;\n rtWrapper._depthStencilTextureWithStencil = internalOptions.generateStencil;\n // Create the depth/stencil buffer\n for (let face = 0; face < 6; face++) {\n if (internalOptions.generateStencil) {\n gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);\n }\n else {\n gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);\n }\n }\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n this._internalTexturesCache.push(internalTexture);\n return internalTexture;\n};\nThinEngine.prototype._partialLoadFile = function (url, index, loadedFiles, onfinish, onErrorCallBack = null) {\n const onload = (data) => {\n loadedFiles[index] = data;\n loadedFiles._internalCount++;\n if (loadedFiles._internalCount === 6) {\n onfinish(loadedFiles);\n }\n };\n const onerror = (request, exception) => {\n if (onErrorCallBack && request) {\n onErrorCallBack(request.status + \" \" + request.statusText, exception);\n }\n };\n this._loadFile(url, onload, undefined, undefined, true, onerror);\n};\nThinEngine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError = null) {\n const loadedFiles = [];\n loadedFiles._internalCount = 0;\n for (let index = 0; index < 6; index++) {\n this._partialLoadFile(files[index], index, loadedFiles, onfinish, onError);\n }\n};\nThinEngine.prototype._cascadeLoadImgs = function (scene, texture, onfinish, files, onError = null, mimeType) {\n const loadedImages = [];\n loadedImages._internalCount = 0;\n for (let index = 0; index < 6; index++) {\n this._partialLoadImg(files[index], index, loadedImages, scene, texture, onfinish, onError, mimeType);\n }\n};\nThinEngine.prototype._partialLoadImg = function (url, index, loadedImages, scene, texture, onfinish, onErrorCallBack = null, mimeType) {\n const tokenPendingData = RandomGUID();\n const onload = (img) => {\n loadedImages[index] = img;\n loadedImages._internalCount++;\n if (scene) {\n scene.removePendingData(tokenPendingData);\n }\n if (loadedImages._internalCount === 6 && onfinish) {\n onfinish(texture, loadedImages);\n }\n };\n const onerror = (message, exception) => {\n if (scene) {\n scene.removePendingData(tokenPendingData);\n }\n if (onErrorCallBack) {\n onErrorCallBack(message, exception);\n }\n };\n LoadImage(url, onload, onerror, scene ? scene.offlineProvider : null, mimeType);\n if (scene) {\n scene.addPendingData(tokenPendingData);\n }\n};\nThinEngine.prototype._setCubeMapTextureParams = function (texture, loadMipmap, maxLevel) {\n const gl = this._gl;\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n texture.samplingMode = loadMipmap ? 3 : 2;\n if (loadMipmap && this.getCaps().textureMaxLevel && maxLevel !== undefined && maxLevel > 0) {\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAX_LEVEL, maxLevel);\n texture._maxLodLevel = maxLevel;\n }\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n};\nThinEngine.prototype.createCubeTextureBase = function (rootUrl, scene, files, noMipmap, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = false, lodScale = 0, lodOffset = 0, fallback = null, beforeLoadCubeDataCallback = null, imageHandler = null, useSRGBBuffer = false) {\n const texture = fallback ? fallback : new InternalTexture(this, InternalTextureSource.Cube);\n texture.isCube = true;\n texture.url = rootUrl;\n texture.generateMipMaps = !noMipmap;\n texture._lodGenerationScale = lodScale;\n texture._lodGenerationOffset = lodOffset;\n texture._useSRGBBuffer = !!useSRGBBuffer && this._caps.supportSRGBBuffers && (this.webGLVersion > 1 || this.isWebGPU || !!noMipmap);\n if (texture !== fallback) {\n texture.label = rootUrl.substring(0, 60); // default label, can be overriden by the caller\n }\n if (!this._doNotHandleContextLost) {\n texture._extension = forcedExtension;\n texture._files = files;\n }\n const originalRootUrl = rootUrl;\n if (this._transformTextureUrl && !fallback) {\n rootUrl = this._transformTextureUrl(rootUrl);\n }\n const rootUrlWithoutUriParams = rootUrl.split(\"?\")[0];\n const lastDot = rootUrlWithoutUriParams.lastIndexOf(\".\");\n const extension = forcedExtension ? forcedExtension : lastDot > -1 ? rootUrlWithoutUriParams.substring(lastDot).toLowerCase() : \"\";\n let loader = null;\n for (const availableLoader of ThinEngine._TextureLoaders) {\n if (availableLoader.canLoad(extension)) {\n loader = availableLoader;\n break;\n }\n }\n const onInternalError = (request, exception) => {\n if (rootUrl === originalRootUrl) {\n if (onError && request) {\n onError(request.status + \" \" + request.statusText, exception);\n }\n }\n else {\n // fall back to the original url if the transformed url fails to load\n Logger.Warn(`Failed to load ${rootUrl}, falling back to the ${originalRootUrl}`);\n this.createCubeTextureBase(originalRootUrl, scene, files, !!noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, texture, beforeLoadCubeDataCallback, imageHandler, useSRGBBuffer);\n }\n };\n if (loader) {\n const onloaddata = (data) => {\n if (beforeLoadCubeDataCallback) {\n beforeLoadCubeDataCallback(texture, data);\n }\n loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);\n };\n if (files && files.length === 6) {\n if (loader.supportCascades) {\n this._cascadeLoadFiles(scene, (images) => onloaddata(images.map((image) => new Uint8Array(image))), files, onError);\n }\n else {\n if (onError) {\n onError(\"Textures type does not support cascades.\");\n }\n else {\n Logger.Warn(\"Texture loader does not support cascades.\");\n }\n }\n }\n else {\n this._loadFile(rootUrl, (data) => onloaddata(new Uint8Array(data)), undefined, undefined, true, onInternalError);\n }\n }\n else {\n if (!files) {\n throw new Error(\"Cannot load cubemap because files were not defined\");\n }\n this._cascadeLoadImgs(scene, texture, (texture, imgs) => {\n if (imageHandler) {\n imageHandler(texture, imgs);\n }\n }, files, onError);\n }\n this._internalTexturesCache.push(texture);\n return texture;\n};\nThinEngine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = false, lodScale = 0, lodOffset = 0, fallback = null, loaderOptions, useSRGBBuffer = false) {\n const gl = this._gl;\n return this.createCubeTextureBase(rootUrl, scene, files, !!noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback, (texture) => this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true), (texture, imgs) => {\n const width = this.needPOTTextures ? ThinEngine.GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize) : imgs[0].width;\n const height = width;\n const faces = [\n gl.TEXTURE_CUBE_MAP_POSITIVE_X,\n gl.TEXTURE_CUBE_MAP_POSITIVE_Y,\n gl.TEXTURE_CUBE_MAP_POSITIVE_Z,\n gl.TEXTURE_CUBE_MAP_NEGATIVE_X,\n gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,\n gl.TEXTURE_CUBE_MAP_NEGATIVE_Z,\n ];\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);\n this._unpackFlipY(false);\n const internalFormat = format ? this._getInternalFormat(format, texture._useSRGBBuffer) : texture._useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8_ALPHA8 : gl.RGBA;\n let texelFormat = format ? this._getInternalFormat(format) : gl.RGBA;\n if (texture._useSRGBBuffer && this.webGLVersion === 1) {\n texelFormat = internalFormat;\n }\n for (let index = 0; index < faces.length; index++) {\n if (imgs[index].width !== width || imgs[index].height !== height) {\n this._prepareWorkingCanvas();\n if (!this._workingCanvas || !this._workingContext) {\n Logger.Warn(\"Cannot create canvas to resize texture.\");\n return;\n }\n this._workingCanvas.width = width;\n this._workingCanvas.height = height;\n this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);\n gl.texImage2D(faces[index], 0, internalFormat, texelFormat, gl.UNSIGNED_BYTE, this._workingCanvas);\n }\n else {\n gl.texImage2D(faces[index], 0, internalFormat, texelFormat, gl.UNSIGNED_BYTE, imgs[index]);\n }\n }\n if (!noMipmap) {\n gl.generateMipmap(gl.TEXTURE_CUBE_MAP);\n }\n this._setCubeMapTextureParams(texture, !noMipmap);\n texture.width = width;\n texture.height = height;\n texture.isReady = true;\n if (format) {\n texture.format = format;\n }\n texture.onLoadedObservable.notifyObservers(texture);\n texture.onLoadedObservable.clear();\n if (onLoad) {\n onLoad();\n }\n }, !!useSRGBBuffer);\n};\n//# sourceMappingURL=engine.cubeTexture.js.map","import { ThinEngine } from \"../../Engines/thinEngine.js\";\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nThinEngine.prototype.setTextureSampler = function (name, sampler) {\n throw new Error(\"setTextureSampler: This engine does not support separate texture sampler objects!\");\n};\n//# sourceMappingURL=engine.textureSampler.js.map","import { Engine } from \"../engine.js\";\nimport { Observable } from \"../../Misc/observable.js\";\n/**\n * Class used to define an additional view for the engine\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/multiCanvas\n */\nexport class EngineView {\n}\nconst _onBeforeViewRenderObservable = new Observable();\nconst _onAfterViewRenderObservable = new Observable();\nObject.defineProperty(Engine.prototype, \"onBeforeViewRenderObservable\", {\n get: function () {\n return _onBeforeViewRenderObservable;\n },\n});\nObject.defineProperty(Engine.prototype, \"onAfterViewRenderObservable\", {\n get: function () {\n return _onAfterViewRenderObservable;\n },\n});\nObject.defineProperty(Engine.prototype, \"inputElement\", {\n get: function () {\n return this._inputElement;\n },\n set: function (value) {\n var _a;\n if (this._inputElement !== value) {\n this._inputElement = value;\n (_a = this._onEngineViewChanged) === null || _a === void 0 ? void 0 : _a.call(this);\n }\n },\n});\nEngine.prototype.getInputElement = function () {\n return this.inputElement || this.getRenderingCanvas();\n};\nEngine.prototype.registerView = function (canvas, camera, clearBeforeCopy) {\n if (!this.views) {\n this.views = [];\n }\n for (const view of this.views) {\n if (view.target === canvas) {\n return view;\n }\n }\n const masterCanvas = this.getRenderingCanvas();\n if (masterCanvas) {\n canvas.width = masterCanvas.width;\n canvas.height = masterCanvas.height;\n }\n const newView = { target: canvas, camera, clearBeforeCopy, enabled: true, id: (Math.random() * 100000).toFixed() };\n this.views.push(newView);\n if (camera) {\n camera.onDisposeObservable.add(() => {\n this.unRegisterView(canvas);\n });\n }\n return newView;\n};\nEngine.prototype.unRegisterView = function (canvas) {\n if (!this.views || this.views.length === 0) {\n return this;\n }\n for (const view of this.views) {\n if (view.target === canvas) {\n const index = this.views.indexOf(view);\n if (index !== -1) {\n this.views.splice(index, 1);\n }\n break;\n }\n }\n return this;\n};\nEngine.prototype._renderViewStep = function (view) {\n const canvas = view.target;\n const context = canvas.getContext(\"2d\");\n if (!context) {\n return true;\n }\n const parent = this.getRenderingCanvas();\n _onBeforeViewRenderObservable.notifyObservers(view);\n const camera = view.camera;\n let previewCamera = null;\n let scene = null;\n if (camera) {\n scene = camera.getScene();\n if (!scene || (scene.activeCameras && scene.activeCameras.length)) {\n return true;\n }\n this.activeView = view;\n previewCamera = scene.activeCamera;\n scene.activeCamera = camera;\n }\n if (view.customResize) {\n view.customResize(canvas);\n }\n else {\n // Set sizes\n const width = Math.floor(canvas.clientWidth / this._hardwareScalingLevel);\n const height = Math.floor(canvas.clientHeight / this._hardwareScalingLevel);\n const dimsChanged = width !== canvas.width || parent.width !== canvas.width || height !== canvas.height || parent.height !== canvas.height;\n if (canvas.clientWidth && canvas.clientHeight && dimsChanged) {\n canvas.width = width;\n canvas.height = height;\n this.setSize(width, height);\n }\n }\n if (!parent.width || !parent.height) {\n return false;\n }\n // Render the frame\n this._renderFrame();\n this.flushFramebuffer();\n // Copy to target\n if (view.clearBeforeCopy) {\n context.clearRect(0, 0, parent.width, parent.height);\n }\n context.drawImage(parent, 0, 0);\n // Restore\n if (previewCamera && scene) {\n scene.activeCamera = previewCamera;\n }\n _onAfterViewRenderObservable.notifyObservers(view);\n return true;\n};\nEngine.prototype._renderViews = function () {\n if (!this.views || this.views.length === 0) {\n return false;\n }\n const parent = this.getRenderingCanvas();\n if (!parent) {\n return false;\n }\n let inputElementView;\n for (const view of this.views) {\n if (!view.enabled) {\n continue;\n }\n const canvas = view.target;\n // Always render the view correspondent to the inputElement for last\n if (canvas === this.inputElement) {\n inputElementView = view;\n continue;\n }\n if (!this._renderViewStep(view)) {\n return false;\n }\n }\n if (inputElementView) {\n if (!this._renderViewStep(inputElementView)) {\n return false;\n }\n }\n this.activeView = null;\n return true;\n};\n//# sourceMappingURL=engine.views.js.map","\nimport { PostProcess } from \"../PostProcesses/postProcess.js\";\nimport \"../Shaders/rgbdDecode.fragment.js\";\nimport \"../Engines/Extensions/engine.renderTarget.js\";\nimport { ApplyPostProcess } from \"./textureTools.js\";\n/**\n * Class used to host RGBD texture specific utilities\n */\nexport class RGBDTextureTools {\n /**\n * Expand the RGBD Texture from RGBD to Half Float if possible.\n * @param texture the texture to expand.\n */\n static ExpandRGBDTexture(texture) {\n const internalTexture = texture._texture;\n if (!internalTexture || !texture.isRGBD) {\n return;\n }\n // Gets everything ready.\n const engine = internalTexture.getEngine();\n const caps = engine.getCaps();\n const isReady = internalTexture.isReady;\n let expandTexture = false;\n // If half float available we can uncompress the texture\n if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {\n expandTexture = true;\n internalTexture.type = 2;\n }\n // If full float available we can uncompress the texture\n else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {\n expandTexture = true;\n internalTexture.type = 1;\n }\n if (expandTexture) {\n // Do not use during decode.\n internalTexture.isReady = false;\n internalTexture._isRGBD = false;\n internalTexture.invertY = false;\n }\n const expandRGBDTexture = () => {\n // Expand the texture if possible\n if (expandTexture) {\n // Simply run through the decode PP.\n const rgbdPostProcess = new PostProcess(\"rgbdDecode\", \"rgbdDecode\", null, null, 1, null, 3, engine, false, undefined, internalTexture.type, undefined, null, false);\n rgbdPostProcess.externalTextureSamplerBinding = true;\n // Hold the output of the decoding.\n const expandedTexture = engine.createRenderTargetTexture(internalTexture.width, {\n generateDepthBuffer: false,\n generateMipMaps: false,\n generateStencilBuffer: false,\n samplingMode: internalTexture.samplingMode,\n type: internalTexture.type,\n format: 5,\n });\n rgbdPostProcess.getEffect().executeWhenCompiled(() => {\n // PP Render Pass\n rgbdPostProcess.onApply = (effect) => {\n effect._bindTexture(\"textureSampler\", internalTexture);\n effect.setFloat2(\"scale\", 1, 1);\n };\n texture.getScene().postProcessManager.directRender([rgbdPostProcess], expandedTexture, true);\n // Cleanup\n engine.restoreDefaultFramebuffer();\n engine._releaseTexture(internalTexture);\n if (rgbdPostProcess) {\n rgbdPostProcess.dispose();\n }\n // Internal Swap\n expandedTexture._swapAndDie(internalTexture);\n // Ready to get rolling again.\n internalTexture.isReady = true;\n });\n }\n };\n if (isReady) {\n expandRGBDTexture();\n }\n else {\n texture.onLoadObservable.addOnce(expandRGBDTexture);\n }\n }\n /**\n * Encode the texture to RGBD if possible.\n * @param internalTexture the texture to encode\n * @param scene the scene hosting the texture\n * @param outputTextureType type of the texture in which the encoding is performed\n * @returns a promise with the internalTexture having its texture replaced by the result of the processing\n */\n static EncodeTextureToRGBD(internalTexture, scene, outputTextureType = 0) {\n return ApplyPostProcess(\"rgbdEncode\", internalTexture, scene, outputTextureType, 1, 5);\n }\n}\n//# sourceMappingURL=rgbdTextureTools.js.map","import { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Scalar } from \"../../Maths/math.scalar.js\";\nimport { SphericalPolynomial, SphericalHarmonics } from \"../../Maths/sphericalPolynomial.js\";\n\nimport { ToLinearSpace } from \"../../Maths/math.constants.js\";\nimport { Color3 } from \"../../Maths/math.color.js\";\nclass FileFaceOrientation {\n constructor(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {\n this.name = name;\n this.worldAxisForNormal = worldAxisForNormal;\n this.worldAxisForFileX = worldAxisForFileX;\n this.worldAxisForFileY = worldAxisForFileY;\n }\n}\n/**\n * Helper class dealing with the extraction of spherical polynomial dataArray\n * from a cube map.\n */\nexport class CubeMapToSphericalPolynomialTools {\n /**\n * Converts a texture to the according Spherical Polynomial data.\n * This extracts the first 3 orders only as they are the only one used in the lighting.\n *\n * @param texture The texture to extract the information from.\n * @returns The Spherical Polynomial data.\n */\n static ConvertCubeMapTextureToSphericalPolynomial(texture) {\n var _a;\n if (!texture.isCube) {\n // Only supports cube Textures currently.\n return null;\n }\n (_a = texture.getScene()) === null || _a === void 0 ? void 0 : _a.getEngine().flushFramebuffer();\n const size = texture.getSize().width;\n const rightPromise = texture.readPixels(0, undefined, undefined, false);\n const leftPromise = texture.readPixels(1, undefined, undefined, false);\n let upPromise;\n let downPromise;\n if (texture.isRenderTarget) {\n upPromise = texture.readPixels(3, undefined, undefined, false);\n downPromise = texture.readPixels(2, undefined, undefined, false);\n }\n else {\n upPromise = texture.readPixels(2, undefined, undefined, false);\n downPromise = texture.readPixels(3, undefined, undefined, false);\n }\n const frontPromise = texture.readPixels(4, undefined, undefined, false);\n const backPromise = texture.readPixels(5, undefined, undefined, false);\n const gammaSpace = texture.gammaSpace;\n // Always read as RGBA.\n const format = 5;\n let type = 0;\n if (texture.textureType == 1 || texture.textureType == 2) {\n type = 1;\n }\n return new Promise((resolve) => {\n Promise.all([leftPromise, rightPromise, upPromise, downPromise, frontPromise, backPromise]).then(([left, right, up, down, front, back]) => {\n const cubeInfo = {\n size,\n right,\n left,\n up,\n down,\n front,\n back,\n format,\n type,\n gammaSpace,\n };\n resolve(this.ConvertCubeMapToSphericalPolynomial(cubeInfo));\n });\n });\n }\n /**\n * Compute the area on the unit sphere of the rectangle defined by (x,y) and the origin\n * See https://www.rorydriscoll.com/2012/01/15/cubemap-texel-solid-angle/\n * @param x\n * @param y\n */\n static _AreaElement(x, y) {\n return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));\n }\n /**\n * Converts a cubemap to the according Spherical Polynomial data.\n * This extracts the first 3 orders only as they are the only one used in the lighting.\n *\n * @param cubeInfo The Cube map to extract the information from.\n * @returns The Spherical Polynomial data.\n */\n static ConvertCubeMapToSphericalPolynomial(cubeInfo) {\n const sphericalHarmonics = new SphericalHarmonics();\n let totalSolidAngle = 0.0;\n // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.\n const du = 2.0 / cubeInfo.size;\n const dv = du;\n const halfTexel = 0.5 * du;\n // The (u,v) of the first texel is half a texel from the corner (-1,-1).\n const minUV = halfTexel - 1.0;\n for (let faceIndex = 0; faceIndex < 6; faceIndex++) {\n const fileFace = this._FileFaces[faceIndex];\n const dataArray = cubeInfo[fileFace.name];\n let v = minUV;\n // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).\n // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.\n // Because SP is still linear, so summation is fine in that basis.\n const stride = cubeInfo.format === 5 ? 4 : 3;\n for (let y = 0; y < cubeInfo.size; y++) {\n let u = minUV;\n for (let x = 0; x < cubeInfo.size; x++) {\n // World direction (not normalised)\n const worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);\n worldDirection.normalize();\n const deltaSolidAngle = this._AreaElement(u - halfTexel, v - halfTexel) -\n this._AreaElement(u - halfTexel, v + halfTexel) -\n this._AreaElement(u + halfTexel, v - halfTexel) +\n this._AreaElement(u + halfTexel, v + halfTexel);\n let r = dataArray[y * cubeInfo.size * stride + x * stride + 0];\n let g = dataArray[y * cubeInfo.size * stride + x * stride + 1];\n let b = dataArray[y * cubeInfo.size * stride + x * stride + 2];\n // Prevent NaN harmonics with extreme HDRI data.\n if (isNaN(r)) {\n r = 0;\n }\n if (isNaN(g)) {\n g = 0;\n }\n if (isNaN(b)) {\n b = 0;\n }\n // Handle Integer types.\n if (cubeInfo.type === 0) {\n r /= 255;\n g /= 255;\n b /= 255;\n }\n // Handle Gamma space textures.\n if (cubeInfo.gammaSpace) {\n r = Math.pow(Scalar.Clamp(r), ToLinearSpace);\n g = Math.pow(Scalar.Clamp(g), ToLinearSpace);\n b = Math.pow(Scalar.Clamp(b), ToLinearSpace);\n }\n // Prevent to explode in case of really high dynamic ranges.\n // sh 3 would not be enough to accurately represent it.\n const max = this.MAX_HDRI_VALUE;\n if (this.PRESERVE_CLAMPED_COLORS) {\n const currentMax = Math.max(r, g, b);\n if (currentMax > max) {\n const factor = max / currentMax;\n r *= factor;\n g *= factor;\n b *= factor;\n }\n }\n else {\n r = Scalar.Clamp(r, 0, max);\n g = Scalar.Clamp(g, 0, max);\n b = Scalar.Clamp(b, 0, max);\n }\n const color = new Color3(r, g, b);\n sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);\n totalSolidAngle += deltaSolidAngle;\n u += du;\n }\n v += dv;\n }\n }\n // Solid angle for entire sphere is 4*pi\n const sphereSolidAngle = 4.0 * Math.PI;\n // Adjust the solid angle to allow for how many faces we processed.\n const facesProcessed = 6.0;\n const expectedSolidAngle = (sphereSolidAngle * facesProcessed) / 6.0;\n // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.\n // This is needed because the numerical integration over the cube uses a\n // small angle approximation of solid angle for each texel (see deltaSolidAngle),\n // and also to compensate for accumulative error due to float precision in the summation.\n const correctionFactor = expectedSolidAngle / totalSolidAngle;\n sphericalHarmonics.scaleInPlace(correctionFactor);\n sphericalHarmonics.convertIncidentRadianceToIrradiance();\n sphericalHarmonics.convertIrradianceToLambertianRadiance();\n return SphericalPolynomial.FromHarmonics(sphericalHarmonics);\n }\n}\nCubeMapToSphericalPolynomialTools._FileFaces = [\n new FileFaceOrientation(\"right\", new Vector3(1, 0, 0), new Vector3(0, 0, -1), new Vector3(0, -1, 0)),\n new FileFaceOrientation(\"left\", new Vector3(-1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, -1, 0)),\n new FileFaceOrientation(\"up\", new Vector3(0, 1, 0), new Vector3(1, 0, 0), new Vector3(0, 0, 1)),\n new FileFaceOrientation(\"down\", new Vector3(0, -1, 0), new Vector3(1, 0, 0), new Vector3(0, 0, -1)),\n new FileFaceOrientation(\"front\", new Vector3(0, 0, 1), new Vector3(1, 0, 0), new Vector3(0, -1, 0)),\n new FileFaceOrientation(\"back\", new Vector3(0, 0, -1), new Vector3(-1, 0, 0), new Vector3(0, -1, 0)), // -Z bottom\n];\n/** @internal */\nCubeMapToSphericalPolynomialTools.MAX_HDRI_VALUE = 4096;\n/** @internal */\nCubeMapToSphericalPolynomialTools.PRESERVE_CLAMPED_COLORS = false;\n//# sourceMappingURL=cubemapToSphericalPolynomial.js.map","import { CubeMapToSphericalPolynomialTools } from \"../../Misc/HighDynamicRange/cubemapToSphericalPolynomial.js\";\nimport { BaseTexture } from \"./baseTexture.js\";\nBaseTexture.prototype.forceSphericalPolynomialsRecompute = function () {\n if (this._texture) {\n this._texture._sphericalPolynomial = null;\n this._texture._sphericalPolynomialPromise = null;\n this._texture._sphericalPolynomialComputed = false;\n }\n};\nObject.defineProperty(BaseTexture.prototype, \"sphericalPolynomial\", {\n get: function () {\n if (this._texture) {\n if (this._texture._sphericalPolynomial || this._texture._sphericalPolynomialComputed) {\n return this._texture._sphericalPolynomial;\n }\n if (this._texture.isReady) {\n if (!this._texture._sphericalPolynomialPromise) {\n this._texture._sphericalPolynomialPromise = CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);\n if (this._texture._sphericalPolynomialPromise === null) {\n this._texture._sphericalPolynomialComputed = true;\n }\n else {\n this._texture._sphericalPolynomialPromise.then((sphericalPolynomial) => {\n this._texture._sphericalPolynomial = sphericalPolynomial;\n this._texture._sphericalPolynomialComputed = true;\n });\n }\n }\n return null;\n }\n }\n return null;\n },\n set: function (value) {\n if (this._texture) {\n this._texture._sphericalPolynomial = value;\n }\n },\n enumerable: true,\n configurable: true,\n});\n//# sourceMappingURL=baseTexture.polynomial.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/helperFunctions.js\";\nconst name = \"rgbdEncodePixelShader\";\nconst shader = `varying vec2 vUV;\runiform sampler2D textureSampler;\r#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \r{\rgl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const rgbdEncodePixelShader = { name, shader };\n//# sourceMappingURL=rgbdEncode.fragment.js.map","import { Tools } from \"./tools.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Scalar } from \"../Maths/math.scalar.js\";\nimport { SphericalPolynomial } from \"../Maths/sphericalPolynomial.js\";\nimport { InternalTexture, InternalTextureSource } from \"../Materials/Textures/internalTexture.js\";\nimport { BaseTexture } from \"../Materials/Textures/baseTexture.js\";\n\nimport { Scene } from \"../scene.js\";\nimport { PostProcess } from \"../PostProcesses/postProcess.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { RGBDTextureTools } from \"./rgbdTextureTools.js\";\nimport \"../Engines/Extensions/engine.renderTargetCube.js\";\nimport \"../Engines/Extensions/engine.readTexture.js\";\nimport \"../Materials/Textures/baseTexture.polynomial.js\";\nimport \"../Shaders/rgbdEncode.fragment.js\";\nimport \"../Shaders/rgbdDecode.fragment.js\";\nimport { DumpTools } from \"../Misc/dumpTools.js\";\nconst DefaultEnvironmentTextureImageType = \"image/png\";\nconst CurrentVersion = 2;\n/**\n * Magic number identifying the env file.\n */\nconst MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];\n/**\n * Gets the environment info from an env file.\n * @param data The array buffer containing the .env bytes.\n * @returns the environment file info (the json header) if successfully parsed, normalized to the latest supported version.\n */\nexport function GetEnvInfo(data) {\n const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);\n let pos = 0;\n for (let i = 0; i < MagicBytes.length; i++) {\n if (dataView.getUint8(pos++) !== MagicBytes[i]) {\n Logger.Error(\"Not a babylon environment map\");\n return null;\n }\n }\n // Read json manifest - collect characters up to null terminator\n let manifestString = \"\";\n let charCode = 0x00;\n while ((charCode = dataView.getUint8(pos++))) {\n manifestString += String.fromCharCode(charCode);\n }\n let manifest = JSON.parse(manifestString);\n manifest = normalizeEnvInfo(manifest);\n if (manifest.specular) {\n // Extend the header with the position of the payload.\n manifest.specular.specularDataPosition = pos;\n // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.\n manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;\n }\n return manifest;\n}\n/**\n * Normalizes any supported version of the environment file info to the latest version\n * @param info environment file info on any supported version\n * @returns environment file info in the latest supported version\n * @private\n */\nexport function normalizeEnvInfo(info) {\n if (info.version > CurrentVersion) {\n throw new Error(`Unsupported babylon environment map version \"${info.version}\". Latest supported version is \"${CurrentVersion}\".`);\n }\n if (info.version === 2) {\n return info;\n }\n // Migrate a v1 info to v2\n info = Object.assign(Object.assign({}, info), { version: 2, imageType: DefaultEnvironmentTextureImageType });\n return info;\n}\n/**\n * Creates an environment texture from a loaded cube texture.\n * @param texture defines the cube texture to convert in env file\n * @param options options for the conversion process\n * @param options.imageType the mime type for the encoded images, with support for \"image/png\" (default) and \"image/webp\"\n * @param options.imageQuality the image quality of encoded WebP images.\n * @returns a promise containing the environment data if successful.\n */\nexport async function CreateEnvTextureAsync(texture, options = {}) {\n var _a, _b;\n const internalTexture = texture.getInternalTexture();\n if (!internalTexture) {\n return Promise.reject(\"The cube texture is invalid.\");\n }\n const imageType = (_a = options.imageType) !== null && _a !== void 0 ? _a : DefaultEnvironmentTextureImageType;\n const engine = internalTexture.getEngine();\n if (texture.textureType !== 2 &&\n texture.textureType !== 1 &&\n texture.textureType !== 0 &&\n texture.textureType !== 0 &&\n texture.textureType !== 7 &&\n texture.textureType !== -1) {\n return Promise.reject(\"The cube texture should allow HDR (Full Float or Half Float).\");\n }\n let textureType = 1;\n if (!engine.getCaps().textureFloatRender) {\n textureType = 2;\n if (!engine.getCaps().textureHalfFloatRender) {\n return Promise.reject(\"Env texture can only be created when the browser supports half float or full float rendering.\");\n }\n }\n // sphericalPolynomial is lazy loaded so simply accessing it should trigger the computation.\n texture.sphericalPolynomial;\n // Lets keep track of the polynomial promise so we can wait for it to be ready before generating the pixels.\n const sphericalPolynomialPromise = (_b = texture.getInternalTexture()) === null || _b === void 0 ? void 0 : _b._sphericalPolynomialPromise;\n const cubeWidth = internalTexture.width;\n const hostingScene = new Scene(engine);\n const specularTextures = {};\n // As we are going to readPixels the faces of the cube, make sure the drawing/update commands for the cube texture are fully sent to the GPU in case it is drawn for the first time in this very frame!\n engine.flushFramebuffer();\n // Read and collect all mipmaps data from the cube.\n const mipmapsCount = Scalar.ILog2(internalTexture.width);\n for (let i = 0; i <= mipmapsCount; i++) {\n const faceWidth = Math.pow(2, mipmapsCount - i);\n // All faces of the cube.\n for (let face = 0; face < 6; face++) {\n let faceData = await texture.readPixels(face, i, undefined, false);\n if (faceData && faceData.byteLength === faceData.length) {\n const faceDataFloat = new Float32Array(faceData.byteLength * 4);\n for (let i = 0; i < faceData.byteLength; i++) {\n faceDataFloat[i] = faceData[i] / 255;\n // Gamma to linear\n faceDataFloat[i] = Math.pow(faceDataFloat[i], 2.2);\n }\n faceData = faceDataFloat;\n }\n else if (faceData && texture.gammaSpace) {\n const floatData = faceData;\n for (let i = 0; i < floatData.length; i++) {\n // Gamma to linear\n floatData[i] = Math.pow(floatData[i], 2.2);\n }\n }\n const tempTexture = engine.createRawTexture(faceData, faceWidth, faceWidth, 5, false, true, 1, null, textureType);\n await RGBDTextureTools.EncodeTextureToRGBD(tempTexture, hostingScene, textureType);\n const rgbdEncodedData = await engine._readTexturePixels(tempTexture, faceWidth, faceWidth);\n const imageEncodedData = await DumpTools.DumpDataAsync(faceWidth, faceWidth, rgbdEncodedData, imageType, undefined, false, true, options.imageQuality);\n specularTextures[i * 6 + face] = imageEncodedData;\n tempTexture.dispose();\n }\n }\n // We can delete the hosting scene keeping track of all the creation objects\n hostingScene.dispose();\n // Ensure completion of the polynomial creation promise.\n if (sphericalPolynomialPromise) {\n await sphericalPolynomialPromise;\n }\n // Creates the json header for the env texture\n const info = {\n version: CurrentVersion,\n width: cubeWidth,\n imageType,\n irradiance: _CreateEnvTextureIrradiance(texture),\n specular: {\n mipmaps: [],\n lodGenerationScale: texture.lodGenerationScale,\n },\n };\n // Sets the specular image data information\n let position = 0;\n for (let i = 0; i <= mipmapsCount; i++) {\n for (let face = 0; face < 6; face++) {\n const byteLength = specularTextures[i * 6 + face].byteLength;\n info.specular.mipmaps.push({\n length: byteLength,\n position: position,\n });\n position += byteLength;\n }\n }\n // Encode the JSON as an array buffer\n const infoString = JSON.stringify(info);\n const infoBuffer = new ArrayBuffer(infoString.length + 1);\n const infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.\n for (let i = 0, strLen = infoString.length; i < strLen; i++) {\n infoView[i] = infoString.charCodeAt(i);\n }\n // Ends up with a null terminator for easier parsing\n infoView[infoString.length] = 0x00;\n // Computes the final required size and creates the storage\n const totalSize = MagicBytes.length + position + infoBuffer.byteLength;\n const finalBuffer = new ArrayBuffer(totalSize);\n const finalBufferView = new Uint8Array(finalBuffer);\n const dataView = new DataView(finalBuffer);\n // Copy the magic bytes identifying the file in\n let pos = 0;\n for (let i = 0; i < MagicBytes.length; i++) {\n dataView.setUint8(pos++, MagicBytes[i]);\n }\n // Add the json info\n finalBufferView.set(new Uint8Array(infoBuffer), pos);\n pos += infoBuffer.byteLength;\n // Finally inserts the texture data\n for (let i = 0; i <= mipmapsCount; i++) {\n for (let face = 0; face < 6; face++) {\n const dataBuffer = specularTextures[i * 6 + face];\n finalBufferView.set(new Uint8Array(dataBuffer), pos);\n pos += dataBuffer.byteLength;\n }\n }\n // Voila\n return finalBuffer;\n}\n/**\n * Creates a JSON representation of the spherical data.\n * @param texture defines the texture containing the polynomials\n * @returns the JSON representation of the spherical info\n */\nfunction _CreateEnvTextureIrradiance(texture) {\n const polynmials = texture.sphericalPolynomial;\n if (polynmials == null) {\n return null;\n }\n return {\n x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],\n y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],\n z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],\n xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],\n yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],\n zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],\n yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],\n zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],\n xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z],\n };\n}\n/**\n * Creates the ArrayBufferViews used for initializing environment texture image data.\n * @param data the image data\n * @param info parameters that determine what views will be created for accessing the underlying buffer\n * @returns the views described by info providing access to the underlying buffer\n */\nexport function CreateImageDataArrayBufferViews(data, info) {\n info = normalizeEnvInfo(info);\n const specularInfo = info.specular;\n // Double checks the enclosed info\n let mipmapsCount = Scalar.Log2(info.width);\n mipmapsCount = Math.round(mipmapsCount) + 1;\n if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {\n throw new Error(`Unsupported specular mipmaps number \"${specularInfo.mipmaps.length}\"`);\n }\n const imageData = new Array(mipmapsCount);\n for (let i = 0; i < mipmapsCount; i++) {\n imageData[i] = new Array(6);\n for (let face = 0; face < 6; face++) {\n const imageInfo = specularInfo.mipmaps[i * 6 + face];\n imageData[i][face] = new Uint8Array(data.buffer, data.byteOffset + specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);\n }\n }\n return imageData;\n}\n/**\n * Uploads the texture info contained in the env file to the GPU.\n * @param texture defines the internal texture to upload to\n * @param data defines the data to load\n * @param info defines the texture info retrieved through the GetEnvInfo method\n * @returns a promise\n */\nexport function UploadEnvLevelsAsync(texture, data, info) {\n info = normalizeEnvInfo(info);\n const specularInfo = info.specular;\n if (!specularInfo) {\n // Nothing else parsed so far\n return Promise.resolve();\n }\n texture._lodGenerationScale = specularInfo.lodGenerationScale;\n const imageData = CreateImageDataArrayBufferViews(data, info);\n return UploadLevelsAsync(texture, imageData, info.imageType);\n}\nfunction _OnImageReadyAsync(image, engine, expandTexture, rgbdPostProcess, url, face, i, generateNonLODTextures, lodTextures, cubeRtt, texture) {\n return new Promise((resolve, reject) => {\n if (expandTexture) {\n const tempTexture = engine.createTexture(null, true, true, null, 1, null, (message) => {\n reject(message);\n }, image);\n rgbdPostProcess.getEffect().executeWhenCompiled(() => {\n // Uncompress the data to a RTT\n rgbdPostProcess.externalTextureSamplerBinding = true;\n rgbdPostProcess.onApply = (effect) => {\n effect._bindTexture(\"textureSampler\", tempTexture);\n effect.setFloat2(\"scale\", 1, engine._features.needsInvertingBitmap && image instanceof ImageBitmap ? -1 : 1);\n };\n if (!engine.scenes.length) {\n return;\n }\n engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);\n // Cleanup\n engine.restoreDefaultFramebuffer();\n tempTexture.dispose();\n URL.revokeObjectURL(url);\n resolve();\n });\n }\n else {\n engine._uploadImageToTexture(texture, image, face, i);\n // Upload the face to the non lod texture support\n if (generateNonLODTextures) {\n const lodTexture = lodTextures[i];\n if (lodTexture) {\n engine._uploadImageToTexture(lodTexture._texture, image, face, 0);\n }\n }\n resolve();\n }\n });\n}\n/**\n * Uploads the levels of image data to the GPU.\n * @param texture defines the internal texture to upload to\n * @param imageData defines the array buffer views of image data [mipmap][face]\n * @param imageType the mime type of the image data\n * @returns a promise\n */\nexport function UploadLevelsAsync(texture, imageData, imageType = DefaultEnvironmentTextureImageType) {\n if (!Tools.IsExponentOfTwo(texture.width)) {\n throw new Error(\"Texture size must be a power of two\");\n }\n const mipmapsCount = Scalar.ILog2(texture.width) + 1;\n // Gets everything ready.\n const engine = texture.getEngine();\n let expandTexture = false;\n let generateNonLODTextures = false;\n let rgbdPostProcess = null;\n let cubeRtt = null;\n let lodTextures = null;\n const caps = engine.getCaps();\n texture.format = 5;\n texture.type = 0;\n texture.generateMipMaps = true;\n texture._cachedAnisotropicFilteringLevel = null;\n engine.updateTextureSamplingMode(3, texture);\n // Add extra process if texture lod is not supported\n if (!caps.textureLOD) {\n expandTexture = false;\n generateNonLODTextures = true;\n lodTextures = {};\n }\n // in webgl 1 there are no ways to either render or copy lod level information for float textures.\n else if (!engine._features.supportRenderAndCopyToLodForFloatTextures) {\n expandTexture = false;\n }\n // If half float available we can uncompress the texture\n else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {\n expandTexture = true;\n texture.type = 2;\n }\n // If full float available we can uncompress the texture\n else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {\n expandTexture = true;\n texture.type = 1;\n }\n // Expand the texture if possible\n if (expandTexture) {\n // Simply run through the decode PP\n rgbdPostProcess = new PostProcess(\"rgbdDecode\", \"rgbdDecode\", null, null, 1, null, 3, engine, false, undefined, texture.type, undefined, null, false);\n texture._isRGBD = false;\n texture.invertY = false;\n cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {\n generateDepthBuffer: false,\n generateMipMaps: true,\n generateStencilBuffer: false,\n samplingMode: 3,\n type: texture.type,\n format: 5,\n });\n }\n else {\n texture._isRGBD = true;\n texture.invertY = true;\n // In case of missing support, applies the same patch than DDS files.\n if (generateNonLODTextures) {\n const mipSlices = 3;\n const scale = texture._lodGenerationScale;\n const offset = texture._lodGenerationOffset;\n for (let i = 0; i < mipSlices; i++) {\n //compute LOD from even spacing in smoothness (matching shader calculation)\n const smoothness = i / (mipSlices - 1);\n const roughness = 1 - smoothness;\n const minLODIndex = offset; // roughness = 0\n const maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)\n const lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;\n const mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));\n const glTextureFromLod = new InternalTexture(engine, InternalTextureSource.Temp);\n glTextureFromLod.isCube = true;\n glTextureFromLod.invertY = true;\n glTextureFromLod.generateMipMaps = false;\n engine.updateTextureSamplingMode(2, glTextureFromLod);\n // Wrap in a base texture for easy binding.\n const lodTexture = new BaseTexture(null);\n lodTexture._isCube = true;\n lodTexture._texture = glTextureFromLod;\n lodTextures[mipmapIndex] = lodTexture;\n switch (i) {\n case 0:\n texture._lodTextureLow = lodTexture;\n break;\n case 1:\n texture._lodTextureMid = lodTexture;\n break;\n case 2:\n texture._lodTextureHigh = lodTexture;\n break;\n }\n }\n }\n }\n const promises = [];\n // All mipmaps up to provided number of images\n for (let i = 0; i < imageData.length; i++) {\n // All faces\n for (let face = 0; face < 6; face++) {\n // Constructs an image element from image data\n const bytes = imageData[i][face];\n const blob = new Blob([bytes], { type: imageType });\n const url = URL.createObjectURL(blob);\n let promise;\n if (typeof Image === \"undefined\" || engine._features.forceBitmapOverHTMLImageElement) {\n promise = engine.createImageBitmap(blob, { premultiplyAlpha: \"none\" }).then((img) => {\n return _OnImageReadyAsync(img, engine, expandTexture, rgbdPostProcess, url, face, i, generateNonLODTextures, lodTextures, cubeRtt, texture);\n });\n }\n else {\n const image = new Image();\n image.src = url;\n // Enqueue promise to upload to the texture.\n promise = new Promise((resolve, reject) => {\n image.onload = () => {\n _OnImageReadyAsync(image, engine, expandTexture, rgbdPostProcess, url, face, i, generateNonLODTextures, lodTextures, cubeRtt, texture)\n .then(() => resolve())\n .catch((reason) => {\n reject(reason);\n });\n };\n image.onerror = (error) => {\n reject(error);\n };\n });\n }\n promises.push(promise);\n }\n }\n // Fill remaining mipmaps with black textures.\n if (imageData.length < mipmapsCount) {\n let data;\n const size = Math.pow(2, mipmapsCount - 1 - imageData.length);\n const dataLength = size * size * 4;\n switch (texture.type) {\n case 0: {\n data = new Uint8Array(dataLength);\n break;\n }\n case 2: {\n data = new Uint16Array(dataLength);\n break;\n }\n case 1: {\n data = new Float32Array(dataLength);\n break;\n }\n }\n for (let i = imageData.length; i < mipmapsCount; i++) {\n for (let face = 0; face < 6; face++) {\n engine._uploadArrayBufferViewToTexture(texture, data, face, i);\n }\n }\n }\n // Once all done, finishes the cleanup and return\n return Promise.all(promises).then(() => {\n // Release temp RTT.\n if (cubeRtt) {\n engine._releaseTexture(texture);\n cubeRtt._swapAndDie(texture);\n }\n // Release temp Post Process.\n if (rgbdPostProcess) {\n rgbdPostProcess.dispose();\n }\n // Flag internal texture as ready in case they are in use.\n if (generateNonLODTextures) {\n if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {\n texture._lodTextureHigh._texture.isReady = true;\n }\n if (texture._lodTextureMid && texture._lodTextureMid._texture) {\n texture._lodTextureMid._texture.isReady = true;\n }\n if (texture._lodTextureLow && texture._lodTextureLow._texture) {\n texture._lodTextureLow._texture.isReady = true;\n }\n }\n });\n}\n/**\n * Uploads spherical polynomials information to the texture.\n * @param texture defines the texture we are trying to upload the information to\n * @param info defines the environment texture info retrieved through the GetEnvInfo method\n */\nexport function UploadEnvSpherical(texture, info) {\n info = normalizeEnvInfo(info);\n const irradianceInfo = info.irradiance;\n if (!irradianceInfo) {\n return;\n }\n const sp = new SphericalPolynomial();\n Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);\n Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);\n Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);\n Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);\n Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);\n Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);\n Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);\n Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);\n Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);\n texture._sphericalPolynomial = sp;\n}\n/**\n * @internal\n */\nexport function _UpdateRGBDAsync(internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {\n const proxy = internalTexture\n .getEngine()\n .createRawCubeTexture(null, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);\n const proxyPromise = UploadLevelsAsync(proxy, data).then(() => internalTexture);\n internalTexture.onRebuildCallback = (_internalTexture) => {\n return {\n proxy: proxyPromise,\n isReady: true,\n isAsync: true,\n };\n };\n internalTexture._source = InternalTextureSource.CubeRawRGBD;\n internalTexture._bufferViewArrayArray = data;\n internalTexture._lodGenerationScale = lodScale;\n internalTexture._lodGenerationOffset = lodOffset;\n internalTexture._sphericalPolynomial = sphericalPolynomial;\n return UploadLevelsAsync(internalTexture, data).then(() => {\n internalTexture.isReady = true;\n return internalTexture;\n });\n}\n/**\n * Sets of helpers addressing the serialization and deserialization of environment texture\n * stored in a BabylonJS env file.\n * Those files are usually stored as .env files.\n */\nexport const EnvironmentTextureTools = {\n /**\n * Gets the environment info from an env file.\n * @param data The array buffer containing the .env bytes.\n * @returns the environment file info (the json header) if successfully parsed, normalized to the latest supported version.\n */\n GetEnvInfo,\n /**\n * Creates an environment texture from a loaded cube texture.\n * @param texture defines the cube texture to convert in env file\n * @param options options for the conversion process\n * @param options.imageType the mime type for the encoded images, with support for \"image/png\" (default) and \"image/webp\"\n * @param options.imageQuality the image quality of encoded WebP images.\n * @returns a promise containing the environment data if successful.\n */\n CreateEnvTextureAsync,\n /**\n * Creates the ArrayBufferViews used for initializing environment texture image data.\n * @param data the image data\n * @param info parameters that determine what views will be created for accessing the underlying buffer\n * @returns the views described by info providing access to the underlying buffer\n */\n CreateImageDataArrayBufferViews,\n /**\n * Uploads the texture info contained in the env file to the GPU.\n * @param texture defines the internal texture to upload to\n * @param data defines the data to load\n * @param info defines the texture info retrieved through the GetEnvInfo method\n * @returns a promise\n */\n UploadEnvLevelsAsync,\n /**\n * Uploads the levels of image data to the GPU.\n * @param texture defines the internal texture to upload to\n * @param imageData defines the array buffer views of image data [mipmap][face]\n * @param imageType the mime type of the image data\n * @returns a promise\n */\n UploadLevelsAsync,\n /**\n * Uploads spherical polynomials information to the texture.\n * @param texture defines the texture we are trying to upload the information to\n * @param info defines the environment texture info retrieved through the GetEnvInfo method\n */\n UploadEnvSpherical,\n};\n//# sourceMappingURL=environmentTextureTools.js.map","/**\n * Extracts the characters between two markers (for eg, between \"(\" and \")\"). The function handles nested markers as well as markers inside strings (delimited by \", ' or `) and comments\n * @param markerOpen opening marker\n * @param markerClose closing marker\n * @param block code block to parse\n * @param startIndex starting index in block where the extraction must start. The character at block[startIndex] should be the markerOpen character!\n * @returns index of the last character for the extraction (or -1 if the string is invalid - no matching closing marker found). The string to extract (without the markers) is the string between startIndex + 1 and the returned value (exclusive)\n */\nexport function ExtractBetweenMarkers(markerOpen, markerClose, block, startIndex) {\n let currPos = startIndex, openMarkers = 0, waitForChar = \"\";\n while (currPos < block.length) {\n const currChar = block.charAt(currPos);\n if (!waitForChar) {\n switch (currChar) {\n case markerOpen:\n openMarkers++;\n break;\n case markerClose:\n openMarkers--;\n break;\n case '\"':\n case \"'\":\n case \"`\":\n waitForChar = currChar;\n break;\n case \"/\":\n if (currPos + 1 < block.length) {\n const nextChar = block.charAt(currPos + 1);\n if (nextChar === \"/\") {\n waitForChar = \"\\n\";\n }\n else if (nextChar === \"*\") {\n waitForChar = \"*/\";\n }\n }\n break;\n }\n }\n else {\n if (currChar === waitForChar) {\n if (waitForChar === '\"' || waitForChar === \"'\") {\n block.charAt(currPos - 1) !== \"\\\\\" && (waitForChar = \"\");\n }\n else {\n waitForChar = \"\";\n }\n }\n else if (waitForChar === \"*/\" && currChar === \"*\" && currPos + 1 < block.length) {\n block.charAt(currPos + 1) === \"/\" && (waitForChar = \"\");\n if (waitForChar === \"\") {\n currPos++;\n }\n }\n }\n currPos++;\n if (openMarkers === 0) {\n break;\n }\n }\n return openMarkers === 0 ? currPos - 1 : -1;\n}\n/**\n * Parses a string and skip whitespaces\n * @param s string to parse\n * @param index index where to start parsing\n * @returns the index after all whitespaces have been skipped\n */\nexport function SkipWhitespaces(s, index) {\n while (index < s.length) {\n const c = s[index];\n if (c !== \" \" && c !== \"\\n\" && c !== \"\\r\" && c !== \"\\t\" && c !== \"\\u000a\" && c !== \"\\u00a0\") {\n break;\n }\n index++;\n }\n return index;\n}\n/**\n * Checks if a character is an identifier character (meaning, if it is 0-9, A-Z, a-z or _)\n * @param c character to check\n * @returns true if the character is an identifier character\n */\nexport function IsIdentifierChar(c) {\n const v = c.charCodeAt(0);\n return ((v >= 48 && v <= 57) || // 0-9\n (v >= 65 && v <= 90) || // A-Z\n (v >= 97 && v <= 122) || // a-z\n v == 95); // _\n}\n/**\n * Removes the comments of a code block\n * @param block code block to parse\n * @returns block with the comments removed\n */\nexport function RemoveComments(block) {\n let currPos = 0, waitForChar = \"\", inComments = false;\n const s = [];\n while (currPos < block.length) {\n const currChar = block.charAt(currPos);\n if (!waitForChar) {\n switch (currChar) {\n case '\"':\n case \"'\":\n case \"`\":\n waitForChar = currChar;\n break;\n case \"/\":\n if (currPos + 1 < block.length) {\n const nextChar = block.charAt(currPos + 1);\n if (nextChar === \"/\") {\n waitForChar = \"\\n\";\n inComments = true;\n }\n else if (nextChar === \"*\") {\n waitForChar = \"*/\";\n inComments = true;\n }\n }\n break;\n }\n if (!inComments) {\n s.push(currChar);\n }\n }\n else {\n if (currChar === waitForChar) {\n if (waitForChar === '\"' || waitForChar === \"'\") {\n block.charAt(currPos - 1) !== \"\\\\\" && (waitForChar = \"\");\n s.push(currChar);\n }\n else {\n waitForChar = \"\";\n inComments = false;\n }\n }\n else if (waitForChar === \"*/\" && currChar === \"*\" && currPos + 1 < block.length) {\n block.charAt(currPos + 1) === \"/\" && (waitForChar = \"\");\n if (waitForChar === \"\") {\n inComments = false;\n currPos++;\n }\n }\n else {\n if (!inComments) {\n s.push(currChar);\n }\n }\n }\n currPos++;\n }\n return s.join(\"\");\n}\n/**\n * Finds the first occurrence of a character in a string going backward\n * @param s the string to parse\n * @param index starting index in the string\n * @param c the character to find\n * @returns the index of the character if found, else -1\n */\nexport function FindBackward(s, index, c) {\n while (index >= 0 && s.charAt(index) !== c) {\n index--;\n }\n return index;\n}\n/**\n * Escapes a string so that it is usable as a regular expression\n * @param s string to escape\n * @returns escaped string\n */\nexport function EscapeRegExp(s) {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n//# sourceMappingURL=codeStringParsingTools.js.map","import { EscapeRegExp, ExtractBetweenMarkers, FindBackward, IsIdentifierChar, RemoveComments, SkipWhitespaces } from \"../../Misc/codeStringParsingTools.js\";\n/**\n * Class used to inline functions in shader code\n */\nexport class ShaderCodeInliner {\n /** Gets the code after the inlining process */\n get code() {\n return this._sourceCode;\n }\n /**\n * Initializes the inliner\n * @param sourceCode shader code source to inline\n * @param numMaxIterations maximum number of iterations (used to detect recursive calls)\n */\n constructor(sourceCode, numMaxIterations = 20) {\n /** Gets or sets the debug mode */\n this.debug = false;\n this._sourceCode = sourceCode;\n this._numMaxIterations = numMaxIterations;\n this._functionDescr = [];\n this.inlineToken = \"#define inline\";\n }\n /**\n * Start the processing of the shader code\n */\n processCode() {\n if (this.debug) {\n console.log(`Start inlining process (code size=${this._sourceCode.length})...`);\n }\n this._collectFunctions();\n this._processInlining(this._numMaxIterations);\n if (this.debug) {\n console.log(\"End of inlining process.\");\n }\n }\n _collectFunctions() {\n let startIndex = 0;\n while (startIndex < this._sourceCode.length) {\n // locate the function to inline and extract its name\n const inlineTokenIndex = this._sourceCode.indexOf(this.inlineToken, startIndex);\n if (inlineTokenIndex < 0) {\n break;\n }\n const funcParamsStartIndex = this._sourceCode.indexOf(\"(\", inlineTokenIndex + this.inlineToken.length);\n if (funcParamsStartIndex < 0) {\n if (this.debug) {\n console.warn(`Could not find the opening parenthesis after the token. startIndex=${startIndex}`);\n }\n startIndex = inlineTokenIndex + this.inlineToken.length;\n continue;\n }\n const funcNameMatch = ShaderCodeInliner._RegexpFindFunctionNameAndType.exec(this._sourceCode.substring(inlineTokenIndex + this.inlineToken.length, funcParamsStartIndex));\n if (!funcNameMatch) {\n if (this.debug) {\n console.warn(`Could not extract the name/type of the function from: ${this._sourceCode.substring(inlineTokenIndex + this.inlineToken.length, funcParamsStartIndex)}`);\n }\n startIndex = inlineTokenIndex + this.inlineToken.length;\n continue;\n }\n const [funcType, funcName] = [funcNameMatch[3], funcNameMatch[4]];\n // extract the parameters of the function as a whole string (without the leading / trailing parenthesis)\n const funcParamsEndIndex = ExtractBetweenMarkers(\"(\", \")\", this._sourceCode, funcParamsStartIndex);\n if (funcParamsEndIndex < 0) {\n if (this.debug) {\n console.warn(`Could not extract the parameters the function '${funcName}' (type=${funcType}). funcParamsStartIndex=${funcParamsStartIndex}`);\n }\n startIndex = inlineTokenIndex + this.inlineToken.length;\n continue;\n }\n const funcParams = this._sourceCode.substring(funcParamsStartIndex + 1, funcParamsEndIndex);\n // extract the body of the function (with the curly brackets)\n const funcBodyStartIndex = SkipWhitespaces(this._sourceCode, funcParamsEndIndex + 1);\n if (funcBodyStartIndex === this._sourceCode.length) {\n if (this.debug) {\n console.warn(`Could not extract the body of the function '${funcName}' (type=${funcType}). funcParamsEndIndex=${funcParamsEndIndex}`);\n }\n startIndex = inlineTokenIndex + this.inlineToken.length;\n continue;\n }\n const funcBodyEndIndex = ExtractBetweenMarkers(\"{\", \"}\", this._sourceCode, funcBodyStartIndex);\n if (funcBodyEndIndex < 0) {\n if (this.debug) {\n console.warn(`Could not extract the body of the function '${funcName}' (type=${funcType}). funcBodyStartIndex=${funcBodyStartIndex}`);\n }\n startIndex = inlineTokenIndex + this.inlineToken.length;\n continue;\n }\n const funcBody = this._sourceCode.substring(funcBodyStartIndex, funcBodyEndIndex + 1);\n // process the parameters: extract each names\n const params = RemoveComments(funcParams).split(\",\");\n const paramNames = [];\n for (let p = 0; p < params.length; ++p) {\n const param = params[p].trim();\n const idx = param.lastIndexOf(\" \");\n if (idx >= 0) {\n paramNames.push(param.substring(idx + 1));\n }\n }\n if (funcType !== \"void\") {\n // for functions that return a value, we will replace \"return\" by \"tempvarname = \", tempvarname being a unique generated name\n paramNames.push(\"return\");\n }\n // collect the function\n this._functionDescr.push({\n name: funcName,\n type: funcType,\n parameters: paramNames,\n body: funcBody,\n callIndex: 0,\n });\n startIndex = funcBodyEndIndex + 1;\n // remove the function from the source code\n const partBefore = inlineTokenIndex > 0 ? this._sourceCode.substring(0, inlineTokenIndex) : \"\";\n const partAfter = funcBodyEndIndex + 1 < this._sourceCode.length - 1 ? this._sourceCode.substring(funcBodyEndIndex + 1) : \"\";\n this._sourceCode = partBefore + partAfter;\n startIndex -= funcBodyEndIndex + 1 - inlineTokenIndex;\n }\n if (this.debug) {\n console.log(`Collect functions: ${this._functionDescr.length} functions found. functionDescr=`, this._functionDescr);\n }\n }\n _processInlining(numMaxIterations = 20) {\n while (numMaxIterations-- >= 0) {\n if (!this._replaceFunctionCallsByCode()) {\n break;\n }\n }\n if (this.debug) {\n console.log(`numMaxIterations is ${numMaxIterations} after inlining process`);\n }\n return numMaxIterations >= 0;\n }\n _replaceFunctionCallsByCode() {\n let doAgain = false;\n for (const func of this._functionDescr) {\n const { name, type, parameters, body } = func;\n let startIndex = 0;\n while (startIndex < this._sourceCode.length) {\n // Look for the function name in the source code\n const functionCallIndex = this._sourceCode.indexOf(name, startIndex);\n if (functionCallIndex < 0) {\n break;\n }\n // Make sure \"name\" is not part of a bigger string\n if (functionCallIndex === 0 || IsIdentifierChar(this._sourceCode.charAt(functionCallIndex - 1))) {\n startIndex = functionCallIndex + name.length;\n continue;\n }\n // Find the opening parenthesis\n const callParamsStartIndex = SkipWhitespaces(this._sourceCode, functionCallIndex + name.length);\n if (callParamsStartIndex === this._sourceCode.length || this._sourceCode.charAt(callParamsStartIndex) !== \"(\") {\n startIndex = functionCallIndex + name.length;\n continue;\n }\n // extract the parameters of the function call as a whole string (without the leading / trailing parenthesis)\n const callParamsEndIndex = ExtractBetweenMarkers(\"(\", \")\", this._sourceCode, callParamsStartIndex);\n if (callParamsEndIndex < 0) {\n if (this.debug) {\n console.warn(`Could not extract the parameters of the function call. Function '${name}' (type=${type}). callParamsStartIndex=${callParamsStartIndex}`);\n }\n startIndex = functionCallIndex + name.length;\n continue;\n }\n const callParams = this._sourceCode.substring(callParamsStartIndex + 1, callParamsEndIndex);\n // process the parameter call: extract each names\n // this function split the parameter list used in the function call at ',' boundaries by taking care of potential parenthesis like in:\n // myfunc(a, vec2(1., 0.), 4.)\n const splitParameterCall = (s) => {\n const parameters = [];\n let curIdx = 0, startParamIdx = 0;\n while (curIdx < s.length) {\n if (s.charAt(curIdx) === \"(\") {\n const idx2 = ExtractBetweenMarkers(\"(\", \")\", s, curIdx);\n if (idx2 < 0) {\n return null;\n }\n curIdx = idx2;\n }\n else if (s.charAt(curIdx) === \",\") {\n parameters.push(s.substring(startParamIdx, curIdx));\n startParamIdx = curIdx + 1;\n }\n curIdx++;\n }\n if (startParamIdx < curIdx) {\n parameters.push(s.substring(startParamIdx, curIdx));\n }\n return parameters;\n };\n const params = splitParameterCall(RemoveComments(callParams));\n if (params === null) {\n if (this.debug) {\n console.warn(`Invalid function call: can't extract the parameters of the function call. Function '${name}' (type=${type}). callParamsStartIndex=${callParamsStartIndex}, callParams=` +\n callParams);\n }\n startIndex = functionCallIndex + name.length;\n continue;\n }\n const paramNames = [];\n for (let p = 0; p < params.length; ++p) {\n const param = params[p].trim();\n paramNames.push(param);\n }\n const retParamName = type !== \"void\" ? name + \"_\" + func.callIndex++ : null;\n if (retParamName) {\n paramNames.push(retParamName + \" =\");\n }\n if (paramNames.length !== parameters.length) {\n if (this.debug) {\n console.warn(`Invalid function call: not the same number of parameters for the call than the number expected by the function. Function '${name}' (type=${type}). function parameters=${parameters}, call parameters=${paramNames}`);\n }\n startIndex = functionCallIndex + name.length;\n continue;\n }\n startIndex = callParamsEndIndex + 1;\n // replace the function call by the body function\n const funcBody = this._replaceNames(body, parameters, paramNames);\n let partBefore = functionCallIndex > 0 ? this._sourceCode.substring(0, functionCallIndex) : \"\";\n const partAfter = callParamsEndIndex + 1 < this._sourceCode.length - 1 ? this._sourceCode.substring(callParamsEndIndex + 1) : \"\";\n if (retParamName) {\n // case where the function returns a value. We generate:\n // FUNCTYPE retParamName;\n // {function body}\n // and replace the function call by retParamName\n const injectDeclarationIndex = FindBackward(this._sourceCode, functionCallIndex - 1, \"\\n\");\n partBefore = this._sourceCode.substring(0, injectDeclarationIndex + 1);\n const partBetween = this._sourceCode.substring(injectDeclarationIndex + 1, functionCallIndex);\n this._sourceCode = partBefore + type + \" \" + retParamName + \";\\n\" + funcBody + \"\\n\" + partBetween + retParamName + partAfter;\n if (this.debug) {\n console.log(`Replace function call by code. Function '${name}' (type=${type}). injectDeclarationIndex=${injectDeclarationIndex}, call parameters=${paramNames}`);\n }\n }\n else {\n // simple case where the return value of the function is \"void\"\n this._sourceCode = partBefore + funcBody + partAfter;\n startIndex += funcBody.length - (callParamsEndIndex + 1 - functionCallIndex);\n if (this.debug) {\n console.log(`Replace function call by code. Function '${name}' (type=${type}). functionCallIndex=${functionCallIndex}, call parameters=${paramNames}`);\n }\n }\n doAgain = true;\n }\n }\n return doAgain;\n }\n _replaceNames(code, sources, destinations) {\n for (let i = 0; i < sources.length; ++i) {\n const source = new RegExp(EscapeRegExp(sources[i]), \"g\"), sourceLen = sources[i].length, destination = destinations[i];\n code = code.replace(source, (match, ...args) => {\n const offset = args[0];\n // Make sure \"source\" is not part of a bigger identifier (for eg, if source=view and we matched it with viewDirection)\n if (IsIdentifierChar(code.charAt(offset - 1)) || IsIdentifierChar(code.charAt(offset + sourceLen))) {\n return sources[i];\n }\n return destination;\n });\n }\n return code;\n }\n}\nShaderCodeInliner._RegexpFindFunctionNameAndType = /((\\s+?)(\\w+)\\s+(\\w+)\\s*?)$/;\n//# sourceMappingURL=shaderCodeInliner.js.map","export class NativePipelineContext {\n get isAsync() {\n return this.isParallelCompiled;\n }\n get isReady() {\n if (this.compilationError) {\n const message = this.compilationError.message;\n throw new Error(\"SHADER ERROR\" + (typeof message === \"string\" ? \"\\n\" + message : \"\"));\n }\n return this.isCompiled;\n }\n _getVertexShaderCode() {\n return null;\n }\n _getFragmentShaderCode() {\n return null;\n }\n // TODO: what should this do?\n _handlesSpectorRebuildCallback(onCompiled) {\n throw new Error(\"Not implemented\");\n }\n constructor(engine) {\n this.isParallelCompiled = true;\n this.isCompiled = false;\n this._valueCache = {};\n this._engine = engine;\n }\n _fillEffectInformation(effect, uniformBuffersNames, uniformsNames, uniforms, samplerList, samplers, attributesNames, attributes) {\n const engine = this._engine;\n if (engine.supportsUniformBuffers) {\n for (const name in uniformBuffersNames) {\n effect.bindUniformBlock(name, uniformBuffersNames[name]);\n }\n }\n const effectAvailableUniforms = this._engine.getUniforms(this, uniformsNames);\n effectAvailableUniforms.forEach((uniform, index) => {\n uniforms[uniformsNames[index]] = uniform;\n });\n this._uniforms = uniforms;\n let index;\n for (index = 0; index < samplerList.length; index++) {\n const sampler = effect.getUniform(samplerList[index]);\n if (sampler == null) {\n samplerList.splice(index, 1);\n index--;\n }\n }\n samplerList.forEach((name, index) => {\n samplers[name] = index;\n });\n attributes.push(...engine.getAttributes(this, attributesNames));\n }\n /**\n * Release all associated resources.\n **/\n dispose() {\n this._uniforms = {};\n }\n /**\n * @internal\n */\n _cacheMatrix(uniformName, matrix) {\n const cache = this._valueCache[uniformName];\n const flag = matrix.updateFlag;\n if (cache !== undefined && cache === flag) {\n return false;\n }\n this._valueCache[uniformName] = flag;\n return true;\n }\n /**\n * @internal\n */\n _cacheFloat2(uniformName, x, y) {\n let cache = this._valueCache[uniformName];\n if (!cache) {\n cache = [x, y];\n this._valueCache[uniformName] = cache;\n return true;\n }\n let changed = false;\n if (cache[0] !== x) {\n cache[0] = x;\n changed = true;\n }\n if (cache[1] !== y) {\n cache[1] = y;\n changed = true;\n }\n return changed;\n }\n /**\n * @internal\n */\n _cacheFloat3(uniformName, x, y, z) {\n let cache = this._valueCache[uniformName];\n if (!cache) {\n cache = [x, y, z];\n this._valueCache[uniformName] = cache;\n return true;\n }\n let changed = false;\n if (cache[0] !== x) {\n cache[0] = x;\n changed = true;\n }\n if (cache[1] !== y) {\n cache[1] = y;\n changed = true;\n }\n if (cache[2] !== z) {\n cache[2] = z;\n changed = true;\n }\n return changed;\n }\n /**\n * @internal\n */\n _cacheFloat4(uniformName, x, y, z, w) {\n let cache = this._valueCache[uniformName];\n if (!cache) {\n cache = [x, y, z, w];\n this._valueCache[uniformName] = cache;\n return true;\n }\n let changed = false;\n if (cache[0] !== x) {\n cache[0] = x;\n changed = true;\n }\n if (cache[1] !== y) {\n cache[1] = y;\n changed = true;\n }\n if (cache[2] !== z) {\n cache[2] = z;\n changed = true;\n }\n if (cache[3] !== w) {\n cache[3] = w;\n changed = true;\n }\n return changed;\n }\n /**\n * Sets an integer value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value Value to be set.\n */\n setInt(uniformName, value) {\n const cache = this._valueCache[uniformName];\n if (cache !== undefined && cache === value) {\n return;\n }\n if (this._engine.setInt(this._uniforms[uniformName], value)) {\n this._valueCache[uniformName] = value;\n }\n }\n /**\n * Sets a int2 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First int in int2.\n * @param y Second int in int2.\n */\n setInt2(uniformName, x, y) {\n if (this._cacheFloat2(uniformName, x, y)) {\n if (!this._engine.setInt2(this._uniforms[uniformName], x, y)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a int3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First int in int3.\n * @param y Second int in int3.\n * @param z Third int in int3.\n */\n setInt3(uniformName, x, y, z) {\n if (this._cacheFloat3(uniformName, x, y, z)) {\n if (!this._engine.setInt3(this._uniforms[uniformName], x, y, z)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a int4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First int in int4.\n * @param y Second int in int4.\n * @param z Third int in int4.\n * @param w Fourth int in int4.\n */\n setInt4(uniformName, x, y, z, w) {\n if (this._cacheFloat4(uniformName, x, y, z, w)) {\n if (!this._engine.setInt4(this._uniforms[uniformName], x, y, z, w)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets an int array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setIntArray(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setIntArray(this._uniforms[uniformName], array);\n }\n /**\n * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setIntArray2(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setIntArray2(this._uniforms[uniformName], array);\n }\n /**\n * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setIntArray3(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setIntArray3(this._uniforms[uniformName], array);\n }\n /**\n * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setIntArray4(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setIntArray4(this._uniforms[uniformName], array);\n }\n /**\n * Sets an unsigned integer value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value Value to be set.\n */\n setUInt(uniformName, value) {\n const cache = this._valueCache[uniformName];\n if (cache !== undefined && cache === value) {\n return;\n }\n if (this._engine.setUInt(this._uniforms[uniformName], value)) {\n this._valueCache[uniformName] = value;\n }\n }\n /**\n * Sets a unsigned int2 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First unsigned int in uint2.\n * @param y Second unsigned int in uint2.\n */\n setUInt2(uniformName, x, y) {\n if (this._cacheFloat2(uniformName, x, y)) {\n if (!this._engine.setUInt2(this._uniforms[uniformName], x, y)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a unsigned int3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First unsigned int in uint3.\n * @param y Second unsigned int in uint3.\n * @param z Third unsigned int in uint3.\n */\n setUInt3(uniformName, x, y, z) {\n if (this._cacheFloat3(uniformName, x, y, z)) {\n if (!this._engine.setUInt3(this._uniforms[uniformName], x, y, z)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a unsigned int4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First unsigned int in uint4.\n * @param y Second unsigned int in uint4.\n * @param z Third unsigned int in uint4.\n * @param w Fourth unsigned int in uint4.\n */\n setUInt4(uniformName, x, y, z, w) {\n if (this._cacheFloat4(uniformName, x, y, z, w)) {\n if (!this._engine.setUInt4(this._uniforms[uniformName], x, y, z, w)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets an unsigned int array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setUIntArray(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setUIntArray(this._uniforms[uniformName], array);\n }\n /**\n * Sets an unsigned int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setUIntArray2(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setUIntArray2(this._uniforms[uniformName], array);\n }\n /**\n * Sets an unsigned int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setUIntArray3(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setUIntArray3(this._uniforms[uniformName], array);\n }\n /**\n * Sets an unsigned int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setUIntArray4(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setUIntArray4(this._uniforms[uniformName], array);\n }\n /**\n * Sets an float array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setFloatArray(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setFloatArray(this._uniforms[uniformName], array);\n }\n /**\n * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setFloatArray2(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setFloatArray2(this._uniforms[uniformName], array);\n }\n /**\n * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setFloatArray3(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setFloatArray3(this._uniforms[uniformName], array);\n }\n /**\n * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setFloatArray4(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setFloatArray4(this._uniforms[uniformName], array);\n }\n /**\n * Sets an array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setArray(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setArray(this._uniforms[uniformName], array);\n }\n /**\n * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setArray2(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setArray2(this._uniforms[uniformName], array);\n }\n /**\n * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setArray3(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setArray3(this._uniforms[uniformName], array);\n }\n /**\n * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setArray4(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setArray4(this._uniforms[uniformName], array);\n }\n /**\n * Sets matrices on a uniform variable.\n * @param uniformName Name of the variable.\n * @param matrices matrices to be set.\n */\n setMatrices(uniformName, matrices) {\n if (!matrices) {\n return;\n }\n this._valueCache[uniformName] = null;\n this._engine.setMatrices(this._uniforms[uniformName], matrices);\n }\n /**\n * Sets matrix on a uniform variable.\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n */\n setMatrix(uniformName, matrix) {\n if (this._cacheMatrix(uniformName, matrix)) {\n if (!this._engine.setMatrices(this._uniforms[uniformName], matrix.toArray())) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a 3x3 matrix on a uniform variable. (Specified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n */\n setMatrix3x3(uniformName, matrix) {\n this._valueCache[uniformName] = null;\n this._engine.setMatrix3x3(this._uniforms[uniformName], matrix);\n }\n /**\n * Sets a 2x2 matrix on a uniform variable. (Specified as [1,2,3,4] will result in [1,2][3,4] matrix)\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n */\n setMatrix2x2(uniformName, matrix) {\n this._valueCache[uniformName] = null;\n this._engine.setMatrix2x2(this._uniforms[uniformName], matrix);\n }\n /**\n * Sets a float on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value value to be set.\n * @returns this effect.\n */\n setFloat(uniformName, value) {\n const cache = this._valueCache[uniformName];\n if (cache !== undefined && cache === value) {\n return;\n }\n if (this._engine.setFloat(this._uniforms[uniformName], value)) {\n this._valueCache[uniformName] = value;\n }\n }\n /**\n * Sets a boolean on a uniform variable.\n * @param uniformName Name of the variable.\n * @param bool value to be set.\n */\n setBool(uniformName, bool) {\n const cache = this._valueCache[uniformName];\n if (cache !== undefined && cache === bool) {\n return;\n }\n if (this._engine.setInt(this._uniforms[uniformName], bool ? 1 : 0)) {\n this._valueCache[uniformName] = bool ? 1 : 0;\n }\n }\n /**\n * Sets a Vector2 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector2 vector2 to be set.\n */\n setVector2(uniformName, vector2) {\n if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {\n if (!this._engine.setFloat2(this._uniforms[uniformName], vector2.x, vector2.y)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a float2 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float2.\n * @param y Second float in float2.\n */\n setFloat2(uniformName, x, y) {\n if (this._cacheFloat2(uniformName, x, y)) {\n if (!this._engine.setFloat2(this._uniforms[uniformName], x, y)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a Vector3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector3 Value to be set.\n */\n setVector3(uniformName, vector3) {\n if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {\n if (!this._engine.setFloat3(this._uniforms[uniformName], vector3.x, vector3.y, vector3.z)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a float3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float3.\n * @param y Second float in float3.\n * @param z Third float in float3.\n */\n setFloat3(uniformName, x, y, z) {\n if (this._cacheFloat3(uniformName, x, y, z)) {\n if (!this._engine.setFloat3(this._uniforms[uniformName], x, y, z)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a Vector4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector4 Value to be set.\n */\n setVector4(uniformName, vector4) {\n if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {\n if (!this._engine.setFloat4(this._uniforms[uniformName], vector4.x, vector4.y, vector4.z, vector4.w)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a Quaternion on a uniform variable.\n * @param uniformName Name of the variable.\n * @param quaternion Value to be set.\n */\n setQuaternion(uniformName, quaternion) {\n if (this._cacheFloat4(uniformName, quaternion.x, quaternion.y, quaternion.z, quaternion.w)) {\n if (!this._engine.setFloat4(this._uniforms[uniformName], quaternion.x, quaternion.y, quaternion.z, quaternion.w)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a float4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float4.\n * @param y Second float in float4.\n * @param z Third float in float4.\n * @param w Fourth float in float4.\n * @returns this effect.\n */\n setFloat4(uniformName, x, y, z, w) {\n if (this._cacheFloat4(uniformName, x, y, z, w)) {\n if (!this._engine.setFloat4(this._uniforms[uniformName], x, y, z, w)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a Color3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param color3 Value to be set.\n */\n setColor3(uniformName, color3) {\n if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {\n if (!this._engine.setFloat3(this._uniforms[uniformName], color3.r, color3.g, color3.b)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a Color4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param color3 Value to be set.\n * @param alpha Alpha value to be set.\n */\n setColor4(uniformName, color3, alpha) {\n if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {\n if (!this._engine.setFloat4(this._uniforms[uniformName], color3.r, color3.g, color3.b, alpha)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a Color4 on a uniform variable\n * @param uniformName defines the name of the variable\n * @param color4 defines the value to be set\n */\n setDirectColor4(uniformName, color4) {\n if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {\n if (!this._engine.setFloat4(this._uniforms[uniformName], color4.r, color4.g, color4.b, color4.a)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n}\n//# sourceMappingURL=nativePipelineContext.js.map","import { RenderTargetWrapper } from \"../renderTargetWrapper.js\";\nexport class NativeRenderTargetWrapper extends RenderTargetWrapper {\n get _framebuffer() {\n return this.__framebuffer;\n }\n set _framebuffer(framebuffer) {\n if (this.__framebuffer) {\n this._engine._releaseFramebufferObjects(this.__framebuffer);\n }\n this.__framebuffer = framebuffer;\n }\n get _framebufferDepthStencil() {\n return this.__framebufferDepthStencil;\n }\n set _framebufferDepthStencil(framebufferDepthStencil) {\n if (this.__framebufferDepthStencil) {\n this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil);\n }\n this.__framebufferDepthStencil = framebufferDepthStencil;\n }\n constructor(isMulti, isCube, size, engine) {\n super(isMulti, isCube, size, engine);\n this.__framebuffer = null;\n this.__framebufferDepthStencil = null;\n this._engine = engine;\n }\n dispose(disposeOnlyFramebuffers = false) {\n this._framebuffer = null;\n this._framebufferDepthStencil = null;\n super.dispose(disposeOnlyFramebuffers);\n }\n}\n//# sourceMappingURL=nativeRenderTargetWrapper.js.map","/** @internal */\nexport class NativeHardwareTexture {\n get underlyingResource() {\n return this._nativeTexture;\n }\n constructor(existingTexture, engine) {\n this._engine = engine;\n this.set(existingTexture);\n }\n setUsage() { }\n set(hardwareTexture) {\n this._nativeTexture = hardwareTexture;\n }\n reset() {\n this._nativeTexture = null;\n }\n release() {\n if (this._nativeTexture) {\n this._engine.deleteTexture(this._nativeTexture);\n }\n this.reset();\n }\n}\n//# sourceMappingURL=nativeHardwareTexture.js.map","import { Engine } from \"../Engines/engine.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { InternalTexture, InternalTextureSource } from \"../Materials/Textures/internalTexture.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { DataBuffer } from \"../Buffers/dataBuffer.js\";\nimport { Tools } from \"../Misc/tools.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { CreateImageDataArrayBufferViews, GetEnvInfo, UploadEnvSpherical } from \"../Misc/environmentTextureTools.js\";\nimport { Logger } from \"../Misc/logger.js\";\n\nimport { ThinEngine } from \"./thinEngine.js\";\nimport { EngineStore } from \"./engineStore.js\";\nimport { ShaderCodeInliner } from \"./Processors/shaderCodeInliner.js\";\nimport { WebGL2ShaderProcessor } from \"../Engines/WebGL/webGL2ShaderProcessors.js\";\nimport { NativeDataStream } from \"./Native/nativeDataStream.js\";\nimport { RuntimeError, ErrorCodes } from \"../Misc/error.js\";\nimport { NativePipelineContext } from \"./Native/nativePipelineContext.js\";\nimport { NativeRenderTargetWrapper } from \"./Native/nativeRenderTargetWrapper.js\";\nimport { NativeHardwareTexture } from \"./Native/nativeHardwareTexture.js\";\nconst onNativeObjectInitialized = new Observable();\nif (typeof self !== \"undefined\" && !Object.prototype.hasOwnProperty.call(self, \"_native\")) {\n let __native;\n Object.defineProperty(self, \"_native\", {\n get: () => __native,\n set: (value) => {\n __native = value;\n if (__native) {\n onNativeObjectInitialized.notifyObservers(__native);\n }\n },\n });\n}\n/**\n * Returns _native only after it has been defined by BabylonNative.\n * @internal\n */\nexport function AcquireNativeObjectAsync() {\n return new Promise((resolve) => {\n if (typeof _native === \"undefined\") {\n onNativeObjectInitialized.addOnce((nativeObject) => resolve(nativeObject));\n }\n else {\n resolve(_native);\n }\n });\n}\n/**\n * Registers a constructor on the _native object. See NativeXRFrame for an example.\n * @internal\n */\nexport async function RegisterNativeTypeAsync(typeName, constructor) {\n (await AcquireNativeObjectAsync())[typeName] = constructor;\n}\n/**\n * Container for accessors for natively-stored mesh data buffers.\n */\nclass NativeDataBuffer extends DataBuffer {\n}\n/** @internal */\nclass CommandBufferEncoder {\n constructor(_engine) {\n this._engine = _engine;\n this._pending = new Array();\n this._isCommandBufferScopeActive = false;\n this._commandStream = NativeEngine._createNativeDataStream();\n this._engine.setCommandDataStream(this._commandStream);\n }\n beginCommandScope() {\n if (this._isCommandBufferScopeActive) {\n throw new Error(\"Command scope already active.\");\n }\n this._isCommandBufferScopeActive = true;\n }\n endCommandScope() {\n if (!this._isCommandBufferScopeActive) {\n throw new Error(\"Command scope is not active.\");\n }\n this._isCommandBufferScopeActive = false;\n this._submit();\n }\n startEncodingCommand(command) {\n this._commandStream.writeNativeData(command);\n }\n encodeCommandArgAsUInt32(commandArg) {\n this._commandStream.writeUint32(commandArg);\n }\n encodeCommandArgAsUInt32s(commandArg) {\n this._commandStream.writeUint32Array(commandArg);\n }\n encodeCommandArgAsInt32(commandArg) {\n this._commandStream.writeInt32(commandArg);\n }\n encodeCommandArgAsInt32s(commandArg) {\n this._commandStream.writeInt32Array(commandArg);\n }\n encodeCommandArgAsFloat32(commandArg) {\n this._commandStream.writeFloat32(commandArg);\n }\n encodeCommandArgAsFloat32s(commandArg) {\n this._commandStream.writeFloat32Array(commandArg);\n }\n encodeCommandArgAsNativeData(commandArg) {\n this._commandStream.writeNativeData(commandArg);\n this._pending.push(commandArg);\n }\n finishEncodingCommand() {\n if (!this._isCommandBufferScopeActive) {\n this._submit();\n }\n }\n _submit() {\n this._engine.submitCommands();\n this._pending.length = 0;\n }\n}\n/** @internal */\nexport class NativeEngine extends Engine {\n setHardwareScalingLevel(level) {\n super.setHardwareScalingLevel(level);\n this._engine.setHardwareScalingLevel(level);\n }\n constructor(options = {}) {\n super(null, false, undefined, options.adaptToDeviceRatio);\n this._engine = new _native.Engine();\n this._camera = _native.Camera ? new _native.Camera() : null;\n this._commandBufferEncoder = new CommandBufferEncoder(this._engine);\n this._boundBuffersVertexArray = null;\n this._currentDepthTest = _native.Engine.DEPTH_TEST_LEQUAL;\n this._stencilTest = false;\n this._stencilMask = 255;\n this._stencilFunc = 519;\n this._stencilFuncRef = 0;\n this._stencilFuncMask = 255;\n this._stencilOpStencilFail = 7680;\n this._stencilOpDepthFail = 7680;\n this._stencilOpStencilDepthPass = 7681;\n this._zOffset = 0;\n this._zOffsetUnits = 0;\n this._depthWrite = true;\n if (_native.Engine.PROTOCOL_VERSION !== NativeEngine.PROTOCOL_VERSION) {\n throw new Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${NativeEngine.PROTOCOL_VERSION} (JS)`);\n }\n this._webGLVersion = 2;\n this.disableUniformBuffers = true;\n this._shaderPlatformName = \"NATIVE\";\n // TODO: Initialize this more correctly based on the hardware capabilities.\n // Init caps\n this._caps = {\n maxTexturesImageUnits: 16,\n maxVertexTextureImageUnits: 16,\n maxCombinedTexturesImageUnits: 32,\n maxTextureSize: _native.Engine.CAPS_LIMITS_MAX_TEXTURE_SIZE,\n maxCubemapTextureSize: 512,\n maxRenderTextureSize: 512,\n maxVertexAttribs: 16,\n maxVaryingVectors: 16,\n maxFragmentUniformVectors: 16,\n maxVertexUniformVectors: 16,\n standardDerivatives: true,\n astc: null,\n pvrtc: null,\n etc1: null,\n etc2: null,\n bptc: null,\n maxAnisotropy: 16,\n uintIndices: true,\n fragmentDepthSupported: false,\n highPrecisionShaderSupported: true,\n colorBufferFloat: false,\n textureFloat: true,\n textureFloatLinearFiltering: false,\n textureFloatRender: false,\n textureHalfFloat: false,\n textureHalfFloatLinearFiltering: false,\n textureHalfFloatRender: false,\n textureLOD: true,\n texelFetch: false,\n drawBuffersExtension: false,\n depthTextureExtension: false,\n vertexArrayObject: true,\n instancedArrays: true,\n supportOcclusionQuery: false,\n canUseTimestampForTimerQuery: false,\n blendMinMax: false,\n maxMSAASamples: 1,\n canUseGLInstanceID: true,\n canUseGLVertexID: true,\n supportComputeShaders: false,\n supportSRGBBuffers: true,\n supportTransformFeedbacks: false,\n textureMaxLevel: false,\n texture2DArrayMaxLayerCount: _native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS,\n disableMorphTargetTexture: false,\n };\n this._features = {\n forceBitmapOverHTMLImageElement: false,\n supportRenderAndCopyToLodForFloatTextures: false,\n supportDepthStencilTexture: false,\n supportShadowSamplers: false,\n uniformBufferHardCheckMatrix: false,\n allowTexturePrefiltering: false,\n trackUbosInFrame: false,\n checkUbosContentBeforeUpload: false,\n supportCSM: false,\n basisNeedsPOT: false,\n support3DTextures: false,\n needTypeSuffixInShaderConstants: false,\n supportMSAA: false,\n supportSSAO2: false,\n supportExtendedTextureFormats: false,\n supportSwitchCaseInShader: false,\n supportSyncTextureRead: false,\n needsInvertingBitmap: true,\n useUBOBindingCache: true,\n needShaderCodeInlining: true,\n needToAlwaysBindUniformBuffers: false,\n supportRenderPasses: true,\n supportSpriteInstancing: false,\n _collectUbosUpdatedInFrame: false,\n };\n Tools.Log(\"Babylon Native (v\" + Engine.Version + \") launched\");\n Tools.LoadScript = function (scriptUrl, onSuccess, onError, scriptId) {\n Tools.LoadFile(scriptUrl, (data) => {\n Function(data).apply(null);\n if (onSuccess) {\n onSuccess();\n }\n }, undefined, undefined, false, (request, exception) => {\n if (onError) {\n onError(\"LoadScript Error\", exception);\n }\n });\n };\n // Wrappers\n if (typeof URL === \"undefined\") {\n window.URL = {\n createObjectURL: function () { },\n revokeObjectURL: function () { },\n };\n }\n if (typeof Blob === \"undefined\") {\n window.Blob = function (v) {\n return v;\n };\n }\n // polyfill for Chakra\n if (!Array.prototype.flat) {\n Object.defineProperty(Array.prototype, \"flat\", {\n configurable: true,\n value: function flat() {\n const depth = isNaN(arguments[0]) ? 1 : Number(arguments[0]);\n return depth\n ? Array.prototype.reduce.call(this, function (acc, cur) {\n if (Array.isArray(cur)) {\n acc.push.apply(acc, flat.call(cur, depth - 1));\n }\n else {\n acc.push(cur);\n }\n return acc;\n }, [])\n : Array.prototype.slice.call(this);\n },\n writable: true,\n });\n }\n // Currently we do not fully configure the ThinEngine on construction of NativeEngine.\n // Setup resolution scaling based on display settings.\n const devicePixelRatio = window ? window.devicePixelRatio || 1.0 : 1.0;\n this._hardwareScalingLevel = options.adaptToDeviceRatio ? 1.0 / devicePixelRatio : 1.0;\n this._engine.setHardwareScalingLevel(this._hardwareScalingLevel);\n this._lastDevicePixelRatio = devicePixelRatio;\n this.resize();\n const currentDepthFunction = this.getDepthFunction();\n if (currentDepthFunction) {\n this.setDepthFunction(currentDepthFunction);\n }\n // Shader processor\n this._shaderProcessor = new WebGL2ShaderProcessor();\n this.onNewSceneAddedObservable.add((scene) => {\n const originalRender = scene.render;\n scene.render = (...args) => {\n this._commandBufferEncoder.beginCommandScope();\n originalRender.apply(scene, args);\n this._commandBufferEncoder.endCommandScope();\n };\n });\n }\n dispose() {\n super.dispose();\n if (this._boundBuffersVertexArray) {\n this._deleteVertexArray(this._boundBuffersVertexArray);\n }\n this._engine.dispose();\n }\n /** @internal */\n static _createNativeDataStream() {\n return new NativeDataStream();\n }\n /**\n * Can be used to override the current requestAnimationFrame requester.\n * @internal\n */\n _queueNewFrame(bindedRenderFunction, requester) {\n // Use the provided requestAnimationFrame, unless the requester is the window. In that case, we will default to the Babylon Native version of requestAnimationFrame.\n if (requester.requestAnimationFrame && requester !== window) {\n requester.requestAnimationFrame(bindedRenderFunction);\n }\n else {\n this._engine.requestAnimationFrame(bindedRenderFunction);\n }\n return 0;\n }\n /**\n * Override default engine behavior.\n * @param framebuffer\n */\n _bindUnboundFramebuffer(framebuffer) {\n if (this._currentFramebuffer !== framebuffer) {\n if (this._currentFramebuffer) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n if (framebuffer) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(framebuffer);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n this._currentFramebuffer = framebuffer;\n }\n }\n /**\n * Gets host document\n * @returns the host document object\n */\n getHostDocument() {\n return null;\n }\n clear(color, backBuffer, depth, stencil = false) {\n if (this.useReverseDepthBuffer) {\n throw new Error(\"reverse depth buffer is not currently implemented\");\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(backBuffer && color ? 1 : 0);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(color ? color.r : 0);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(color ? color.g : 0);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(color ? color.b : 0);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(color ? color.a : 1);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(depth ? 1 : 0);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(1);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(stencil ? 1 : 0);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(0);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n createIndexBuffer(indices, updateable) {\n const data = this._normalizeIndexData(indices);\n const buffer = new NativeDataBuffer();\n buffer.references = 1;\n buffer.is32Bits = data.BYTES_PER_ELEMENT === 4;\n if (data.byteLength) {\n buffer.nativeIndexBuffer = this._engine.createIndexBuffer(data.buffer, data.byteOffset, data.byteLength, buffer.is32Bits, updateable !== null && updateable !== void 0 ? updateable : false);\n }\n return buffer;\n }\n createVertexBuffer(vertices, updateable) {\n const data = ArrayBuffer.isView(vertices) ? vertices : new Float32Array(vertices);\n const buffer = new NativeDataBuffer();\n buffer.references = 1;\n if (data.byteLength) {\n buffer.nativeVertexBuffer = this._engine.createVertexBuffer(data.buffer, data.byteOffset, data.byteLength, updateable !== null && updateable !== void 0 ? updateable : false);\n }\n return buffer;\n }\n _recordVertexArrayObject(vertexArray, vertexBuffers, indexBuffer, effect, overrideVertexBuffers) {\n if (indexBuffer) {\n this._engine.recordIndexBuffer(vertexArray, indexBuffer.nativeIndexBuffer);\n }\n const attributes = effect.getAttributesNames();\n for (let index = 0; index < attributes.length; index++) {\n const location = effect.getAttributeLocation(index);\n if (location >= 0) {\n const kind = attributes[index];\n let vertexBuffer = null;\n if (overrideVertexBuffers) {\n vertexBuffer = overrideVertexBuffers[kind];\n }\n if (!vertexBuffer) {\n vertexBuffer = vertexBuffers[kind];\n }\n if (vertexBuffer) {\n const buffer = vertexBuffer.getBuffer();\n if (buffer && buffer.nativeVertexBuffer) {\n this._engine.recordVertexBuffer(vertexArray, buffer.nativeVertexBuffer, location, vertexBuffer.byteOffset, vertexBuffer.byteStride, vertexBuffer.getSize(), this._getNativeAttribType(vertexBuffer.type), vertexBuffer.normalized, vertexBuffer.getInstanceDivisor());\n }\n }\n }\n }\n }\n bindBuffers(vertexBuffers, indexBuffer, effect) {\n if (this._boundBuffersVertexArray) {\n this._deleteVertexArray(this._boundBuffersVertexArray);\n }\n this._boundBuffersVertexArray = this._engine.createVertexArray();\n this._recordVertexArrayObject(this._boundBuffersVertexArray, vertexBuffers, indexBuffer, effect);\n this.bindVertexArrayObject(this._boundBuffersVertexArray);\n }\n recordVertexArrayObject(vertexBuffers, indexBuffer, effect, overrideVertexBuffers) {\n const vertexArray = this._engine.createVertexArray();\n this._recordVertexArrayObject(vertexArray, vertexBuffers, indexBuffer, effect, overrideVertexBuffers);\n return vertexArray;\n }\n _deleteVertexArray(vertexArray) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(vertexArray);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n bindVertexArrayObject(vertexArray) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(vertexArray);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n releaseVertexArrayObject(vertexArray) {\n this._deleteVertexArray(vertexArray);\n }\n getAttributes(pipelineContext, attributesNames) {\n const nativePipelineContext = pipelineContext;\n return this._engine.getAttributes(nativePipelineContext.nativeProgram, attributesNames);\n }\n /**\n * Draw a list of indexed primitives\n * @param fillMode defines the primitive to use\n * @param indexStart defines the starting index\n * @param indexCount defines the number of index to draw\n * @param instancesCount defines the number of instances to draw (if instantiation is enabled)\n */\n drawElementsType(fillMode, indexStart, indexCount, instancesCount) {\n // Apply states\n this._drawCalls.addCount(1, false);\n // TODO: Make this implementation more robust like core Engine version.\n // Render\n //var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;\n //var mult = this._uintIndicesCurrentlySet ? 4 : 2;\n // if (instancesCount) {\n // this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);\n // } else {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXED);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(fillMode);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(indexStart);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(indexCount);\n this._commandBufferEncoder.finishEncodingCommand();\n // }\n }\n /**\n * Draw a list of unindexed primitives\n * @param fillMode defines the primitive to use\n * @param verticesStart defines the index of first vertex to draw\n * @param verticesCount defines the count of vertices to draw\n * @param instancesCount defines the number of instances to draw (if instantiation is enabled)\n */\n drawArraysType(fillMode, verticesStart, verticesCount, instancesCount) {\n // Apply states\n this._drawCalls.addCount(1, false);\n // TODO: Make this implementation more robust like core Engine version.\n // if (instancesCount) {\n // this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);\n // } else {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAW);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(fillMode);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(verticesStart);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(verticesCount);\n this._commandBufferEncoder.finishEncodingCommand();\n // }\n }\n createPipelineContext() {\n return new NativePipelineContext(this);\n }\n createMaterialContext() {\n return undefined;\n }\n createDrawContext() {\n return undefined;\n }\n _preparePipelineContext(pipelineContext, vertexSourceCode, fragmentSourceCode, createAsRaw, _rawVertexSourceCode, _rawFragmentSourceCode, _rebuildRebind, defines) {\n const nativePipelineContext = pipelineContext;\n if (createAsRaw) {\n nativePipelineContext.nativeProgram = this.createRawShaderProgram();\n }\n else {\n nativePipelineContext.nativeProgram = this.createShaderProgram(pipelineContext, vertexSourceCode, fragmentSourceCode, defines);\n }\n }\n isAsync(pipelineContext) {\n return !!(pipelineContext.isAsync && this._engine.createProgramAsync);\n }\n /**\n * @internal\n */\n _executeWhenRenderingStateIsCompiled(pipelineContext, action) {\n const nativePipelineContext = pipelineContext;\n if (!this.isAsync(pipelineContext)) {\n action();\n return;\n }\n const oldHandler = nativePipelineContext.onCompiled;\n if (oldHandler) {\n nativePipelineContext.onCompiled = () => {\n oldHandler();\n action();\n };\n }\n else {\n nativePipelineContext.onCompiled = action;\n }\n }\n createRawShaderProgram() {\n throw new Error(\"Not Supported\");\n }\n createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines) {\n const nativePipelineContext = pipelineContext;\n if (nativePipelineContext.nativeProgram) {\n throw new Error(\"Tried to create a second program in the same NativePipelineContext\");\n }\n this.onBeforeShaderCompilationObservable.notifyObservers(this);\n const vertexInliner = new ShaderCodeInliner(vertexCode);\n vertexInliner.processCode();\n vertexCode = vertexInliner.code;\n const fragmentInliner = new ShaderCodeInliner(fragmentCode);\n fragmentInliner.processCode();\n fragmentCode = fragmentInliner.code;\n vertexCode = ThinEngine._ConcatenateShader(vertexCode, defines);\n fragmentCode = ThinEngine._ConcatenateShader(fragmentCode, defines);\n const onSuccess = () => {\n var _a;\n nativePipelineContext.isCompiled = true;\n (_a = nativePipelineContext.onCompiled) === null || _a === void 0 ? void 0 : _a.call(nativePipelineContext);\n this.onAfterShaderCompilationObservable.notifyObservers(this);\n };\n if (this.isAsync(pipelineContext)) {\n return this._engine.createProgramAsync(vertexCode, fragmentCode, onSuccess, (error) => {\n nativePipelineContext.compilationError = error;\n });\n }\n else {\n try {\n const program = (nativePipelineContext.nativeProgram = this._engine.createProgram(vertexCode, fragmentCode));\n onSuccess();\n return program;\n }\n catch (e) {\n const message = e === null || e === void 0 ? void 0 : e.message;\n throw new Error(\"SHADER ERROR\" + (typeof message === \"string\" ? \"\\n\" + message : \"\"));\n }\n }\n }\n /**\n * Inline functions in shader code that are marked to be inlined\n * @param code code to inline\n * @returns inlined code\n */\n inlineShaderCode(code) {\n const sci = new ShaderCodeInliner(code);\n sci.debug = false;\n sci.processCode();\n return sci.code;\n }\n _setProgram(program) {\n if (this._currentProgram !== program) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETPROGRAM);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(program);\n this._commandBufferEncoder.finishEncodingCommand();\n this._currentProgram = program;\n }\n }\n _deletePipelineContext(pipelineContext) {\n const nativePipelineContext = pipelineContext;\n if (nativePipelineContext && nativePipelineContext.nativeProgram) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(nativePipelineContext.nativeProgram);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n }\n getUniforms(pipelineContext, uniformsNames) {\n const nativePipelineContext = pipelineContext;\n return this._engine.getUniforms(nativePipelineContext.nativeProgram, uniformsNames);\n }\n bindUniformBlock(pipelineContext, blockName, index) {\n // TODO\n throw new Error(\"Not Implemented\");\n }\n bindSamplers(effect) {\n const nativePipelineContext = effect.getPipelineContext();\n this._setProgram(nativePipelineContext.nativeProgram);\n // TODO: share this with engine?\n const samplers = effect.getSamplers();\n for (let index = 0; index < samplers.length; index++) {\n const uniform = effect.getUniform(samplers[index]);\n if (uniform) {\n this._boundUniforms[index] = uniform;\n }\n }\n this._currentEffect = null;\n }\n getRenderWidth(useScreen = false) {\n if (!useScreen && this._currentRenderTarget) {\n return this._currentRenderTarget.width;\n }\n return this._engine.getRenderWidth();\n }\n getRenderHeight(useScreen = false) {\n if (!useScreen && this._currentRenderTarget) {\n return this._currentRenderTarget.height;\n }\n return this._engine.getRenderHeight();\n }\n setViewport(viewport, requiredWidth, requiredHeight) {\n this._cachedViewport = viewport;\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETVIEWPORT);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(viewport.x);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(viewport.y);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(viewport.width);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(viewport.height);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n enableScissor(x, y, width, height) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSCISSOR);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(x);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(y);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(width);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(height);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n disableScissor() {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSCISSOR);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(0);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(0);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(0);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(0);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n setState(culling, zOffset = 0, force, reverseSide = false, cullBackFaces, stencil, zOffsetUnits = 0) {\n var _a, _b;\n this._zOffset = zOffset;\n this._zOffsetUnits = zOffsetUnits;\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTATE);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(culling ? 1 : 0);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(zOffset);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(zOffsetUnits);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(((_b = (_a = this.cullBackFaces) !== null && _a !== void 0 ? _a : cullBackFaces) !== null && _b !== void 0 ? _b : true) ? 1 : 0);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(reverseSide ? 1 : 0);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n /**\n * Gets the client rect of native canvas. Needed for InputManager.\n * @returns a client rectangle\n */\n getInputElementClientRect() {\n const rect = {\n bottom: this.getRenderHeight(),\n height: this.getRenderHeight(),\n left: 0,\n right: this.getRenderWidth(),\n top: 0,\n width: this.getRenderWidth(),\n x: 0,\n y: 0,\n toJSON: () => { },\n };\n return rect;\n }\n /**\n * Set the z offset Factor to apply to current rendering\n * @param value defines the offset to apply\n */\n setZOffset(value) {\n if (value !== this._zOffset) {\n this._zOffset = value;\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSET);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer ? -value : value);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n }\n /**\n * Gets the current value of the zOffset Factor\n * @returns the current zOffset Factor state\n */\n getZOffset() {\n return this._zOffset;\n }\n /**\n * Set the z offset Units to apply to current rendering\n * @param value defines the offset to apply\n */\n setZOffsetUnits(value) {\n if (value !== this._zOffsetUnits) {\n this._zOffsetUnits = value;\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSETUNITS);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer ? -value : value);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n }\n /**\n * Gets the current value of the zOffset Units\n * @returns the current zOffset Units state\n */\n getZOffsetUnits() {\n return this._zOffsetUnits;\n }\n /**\n * Enable or disable depth buffering\n * @param enable defines the state to set\n */\n setDepthBuffer(enable) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(enable ? this._currentDepthTest : _native.Engine.DEPTH_TEST_ALWAYS);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n /**\n * Gets a boolean indicating if depth writing is enabled\n * @returns the current depth writing state\n */\n getDepthWrite() {\n return this._depthWrite;\n }\n getDepthFunction() {\n switch (this._currentDepthTest) {\n case _native.Engine.DEPTH_TEST_NEVER:\n return 512;\n case _native.Engine.DEPTH_TEST_ALWAYS:\n return 519;\n case _native.Engine.DEPTH_TEST_GREATER:\n return 516;\n case _native.Engine.DEPTH_TEST_GEQUAL:\n return 518;\n case _native.Engine.DEPTH_TEST_NOTEQUAL:\n return 517;\n case _native.Engine.DEPTH_TEST_EQUAL:\n return 514;\n case _native.Engine.DEPTH_TEST_LESS:\n return 513;\n case _native.Engine.DEPTH_TEST_LEQUAL:\n return 515;\n }\n return null;\n }\n setDepthFunction(depthFunc) {\n let nativeDepthFunc = 0;\n switch (depthFunc) {\n case 512:\n nativeDepthFunc = _native.Engine.DEPTH_TEST_NEVER;\n break;\n case 519:\n nativeDepthFunc = _native.Engine.DEPTH_TEST_ALWAYS;\n break;\n case 516:\n nativeDepthFunc = _native.Engine.DEPTH_TEST_GREATER;\n break;\n case 518:\n nativeDepthFunc = _native.Engine.DEPTH_TEST_GEQUAL;\n break;\n case 517:\n nativeDepthFunc = _native.Engine.DEPTH_TEST_NOTEQUAL;\n break;\n case 514:\n nativeDepthFunc = _native.Engine.DEPTH_TEST_EQUAL;\n break;\n case 513:\n nativeDepthFunc = _native.Engine.DEPTH_TEST_LESS;\n break;\n case 515:\n nativeDepthFunc = _native.Engine.DEPTH_TEST_LEQUAL;\n break;\n }\n this._currentDepthTest = nativeDepthFunc;\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(this._currentDepthTest);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n /**\n * Enable or disable depth writing\n * @param enable defines the state to set\n */\n setDepthWrite(enable) {\n this._depthWrite = enable;\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHWRITE);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(enable));\n this._commandBufferEncoder.finishEncodingCommand();\n }\n /**\n * Enable or disable color writing\n * @param enable defines the state to set\n */\n setColorWrite(enable) {\n this._colorWrite = enable;\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETCOLORWRITE);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(enable));\n this._commandBufferEncoder.finishEncodingCommand();\n }\n /**\n * Gets a boolean indicating if color writing is enabled\n * @returns the current color writing state\n */\n getColorWrite() {\n return this._colorWrite;\n }\n applyStencil() {\n this._setStencil(this._stencilMask, this._getStencilOpFail(this._stencilOpStencilFail), this._getStencilDepthFail(this._stencilOpDepthFail), this._getStencilDepthPass(this._stencilOpStencilDepthPass), this._getStencilFunc(this._stencilFunc), this._stencilFuncRef);\n }\n _setStencil(mask, stencilOpFail, depthOpFail, depthOpPass, func, ref) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(mask);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(stencilOpFail);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(depthOpFail);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(depthOpPass);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(func);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(ref);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n /**\n * Enable or disable the stencil buffer\n * @param enable defines if the stencil buffer must be enabled or disabled\n */\n setStencilBuffer(enable) {\n this._stencilTest = enable;\n if (enable) {\n this.applyStencil();\n }\n else {\n this._setStencil(255, _native.Engine.STENCIL_OP_FAIL_S_KEEP, _native.Engine.STENCIL_OP_FAIL_Z_KEEP, _native.Engine.STENCIL_OP_PASS_Z_KEEP, _native.Engine.STENCIL_TEST_ALWAYS, 0);\n }\n }\n /**\n * Gets a boolean indicating if stencil buffer is enabled\n * @returns the current stencil buffer state\n */\n getStencilBuffer() {\n return this._stencilTest;\n }\n /**\n * Gets the current stencil operation when stencil passes\n * @returns a number defining stencil operation to use when stencil passes\n */\n getStencilOperationPass() {\n return this._stencilOpStencilDepthPass;\n }\n /**\n * Sets the stencil operation to use when stencil passes\n * @param operation defines the stencil operation to use when stencil passes\n */\n setStencilOperationPass(operation) {\n this._stencilOpStencilDepthPass = operation;\n this.applyStencil();\n }\n /**\n * Sets the current stencil mask\n * @param mask defines the new stencil mask to use\n */\n setStencilMask(mask) {\n this._stencilMask = mask;\n this.applyStencil();\n }\n /**\n * Sets the current stencil function\n * @param stencilFunc defines the new stencil function to use\n */\n setStencilFunction(stencilFunc) {\n this._stencilFunc = stencilFunc;\n this.applyStencil();\n }\n /**\n * Sets the current stencil reference\n * @param reference defines the new stencil reference to use\n */\n setStencilFunctionReference(reference) {\n this._stencilFuncRef = reference;\n this.applyStencil();\n }\n /**\n * Sets the current stencil mask\n * @param mask defines the new stencil mask to use\n */\n setStencilFunctionMask(mask) {\n this._stencilFuncMask = mask;\n }\n /**\n * Sets the stencil operation to use when stencil fails\n * @param operation defines the stencil operation to use when stencil fails\n */\n setStencilOperationFail(operation) {\n this._stencilOpStencilFail = operation;\n this.applyStencil();\n }\n /**\n * Sets the stencil operation to use when depth fails\n * @param operation defines the stencil operation to use when depth fails\n */\n setStencilOperationDepthFail(operation) {\n this._stencilOpDepthFail = operation;\n this.applyStencil();\n }\n /**\n * Gets the current stencil mask\n * @returns a number defining the new stencil mask to use\n */\n getStencilMask() {\n return this._stencilMask;\n }\n /**\n * Gets the current stencil function\n * @returns a number defining the stencil function to use\n */\n getStencilFunction() {\n return this._stencilFunc;\n }\n /**\n * Gets the current stencil reference value\n * @returns a number defining the stencil reference value to use\n */\n getStencilFunctionReference() {\n return this._stencilFuncRef;\n }\n /**\n * Gets the current stencil mask\n * @returns a number defining the stencil mask to use\n */\n getStencilFunctionMask() {\n return this._stencilFuncMask;\n }\n /**\n * Gets the current stencil operation when stencil fails\n * @returns a number defining stencil operation to use when stencil fails\n */\n getStencilOperationFail() {\n return this._stencilOpStencilFail;\n }\n /**\n * Gets the current stencil operation when depth fails\n * @returns a number defining stencil operation to use when depth fails\n */\n getStencilOperationDepthFail() {\n return this._stencilOpDepthFail;\n }\n /**\n * Sets alpha constants used by some alpha blending modes\n * @param r defines the red component\n * @param g defines the green component\n * @param b defines the blue component\n * @param a defines the alpha component\n */\n setAlphaConstants(r, g, b, a) {\n throw new Error(\"Setting alpha blend constant color not yet implemented.\");\n }\n /**\n * Sets the current alpha mode\n * @param mode defines the mode to use (one of the BABYLON.undefined)\n * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/transparent_rendering\n */\n setAlphaMode(mode, noDepthWriteChange = false) {\n if (this._alphaMode === mode) {\n return;\n }\n const nativeMode = this._getNativeAlphaMode(mode);\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(nativeMode);\n this._commandBufferEncoder.finishEncodingCommand();\n if (!noDepthWriteChange) {\n this.setDepthWrite(mode === 0);\n }\n this._alphaMode = mode;\n }\n /**\n * Gets the current alpha mode\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/transparent_rendering\n * @returns the current alpha mode\n */\n getAlphaMode() {\n return this._alphaMode;\n }\n setInt(uniform, int) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsInt32(int);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setIntArray(uniform, array) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsInt32s(array);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setIntArray2(uniform, array) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsInt32s(array);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setIntArray3(uniform, array) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsInt32s(array);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setIntArray4(uniform, array) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsInt32s(array);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setFloatArray(uniform, array) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsFloat32s(array);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setFloatArray2(uniform, array) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsFloat32s(array);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setFloatArray3(uniform, array) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsFloat32s(array);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setFloatArray4(uniform, array) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsFloat32s(array);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setArray(uniform, array) {\n if (!uniform) {\n return false;\n }\n return this.setFloatArray(uniform, new Float32Array(array));\n }\n setArray2(uniform, array) {\n if (!uniform) {\n return false;\n }\n return this.setFloatArray2(uniform, new Float32Array(array));\n }\n setArray3(uniform, array) {\n if (!uniform) {\n return false;\n }\n return this.setFloatArray3(uniform, new Float32Array(array));\n }\n setArray4(uniform, array) {\n if (!uniform) {\n return false;\n }\n return this.setFloatArray4(uniform, new Float32Array(array));\n }\n setMatrices(uniform, matrices) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsFloat32s(matrices);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setMatrix3x3(uniform, matrix) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsFloat32s(matrix);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setMatrix2x2(uniform, matrix) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsFloat32s(matrix);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setFloat(uniform, value) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(value);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setFloat2(uniform, x, y) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT2);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(x);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(y);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setFloat3(uniform, x, y, z) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(x);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(y);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(z);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setFloat4(uniform, x, y, z, w) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(x);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(y);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(z);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(w);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setColor3(uniform, color3) {\n if (!uniform) {\n return false;\n }\n this.setFloat3(uniform, color3.r, color3.g, color3.b);\n return true;\n }\n setColor4(uniform, color3, alpha) {\n if (!uniform) {\n return false;\n }\n this.setFloat4(uniform, color3.r, color3.g, color3.b, alpha);\n return true;\n }\n wipeCaches(bruteForce) {\n if (this.preventCacheWipeBetweenFrames) {\n return;\n }\n this.resetTextureCache();\n this._currentEffect = null;\n if (bruteForce) {\n this._currentProgram = null;\n this._stencilStateComposer.reset();\n this._depthCullingState.reset();\n this._alphaState.reset();\n }\n this._cachedVertexBuffers = null;\n this._cachedIndexBuffer = null;\n this._cachedEffectForVertexBuffers = null;\n }\n _createTexture() {\n return this._engine.createTexture();\n }\n _deleteTexture(texture) {\n if (texture) {\n this._engine.deleteTexture(texture);\n }\n }\n /**\n * Update the content of a dynamic texture\n * @param texture defines the texture to update\n * @param canvas defines the canvas containing the source\n * @param invertY defines if data must be stored with Y axis inverted\n * @param premulAlpha defines if alpha is stored as premultiplied\n * @param format defines the format of the data\n */\n updateDynamicTexture(texture, canvas, invertY, premulAlpha = false, format) {\n if (premulAlpha === void 0) {\n premulAlpha = false;\n }\n if (!!texture && !!texture._hardwareTexture) {\n const source = canvas.getCanvasTexture();\n const destination = texture._hardwareTexture.underlyingResource;\n this._engine.copyTexture(destination, source);\n texture.isReady = true;\n }\n }\n createDynamicTexture(width, height, generateMipMaps, samplingMode) {\n // it's not possible to create 0x0 texture sized. Many bgfx methods assume texture size is at least 1x1(best case).\n // Worst case is getting a crash/assert.\n width = Math.max(width, 1);\n height = Math.max(height, 1);\n return this.createRawTexture(new Uint8Array(width * height * 4), width, height, 5, false, false, samplingMode);\n }\n createVideoElement(constraints) {\n // create native object depending on stream. Only NativeCamera is supported for now.\n if (this._camera) {\n return this._camera.createVideo(constraints);\n }\n return null;\n }\n updateVideoTexture(texture, video, invertY) {\n if (texture && texture._hardwareTexture && this._camera) {\n const webGLTexture = texture._hardwareTexture.underlyingResource;\n this._camera.updateVideoTexture(webGLTexture, video, invertY);\n }\n }\n createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, compression = null, type = 0, creationFlags = 0, useSRGBBuffer = false) {\n const texture = new InternalTexture(this, InternalTextureSource.Raw);\n texture.format = format;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.invertY = invertY;\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = texture.baseWidth;\n texture.height = texture.baseHeight;\n texture._compression = compression;\n texture.type = type;\n texture._useSRGBBuffer = this._getUseSRGBBuffer(useSRGBBuffer, !generateMipMaps);\n this.updateRawTexture(texture, data, format, invertY, compression, type, texture._useSRGBBuffer);\n if (texture._hardwareTexture) {\n const webGLTexture = texture._hardwareTexture.underlyingResource;\n const filter = this._getNativeSamplingMode(samplingMode);\n this._setTextureSampling(webGLTexture, filter);\n }\n this._internalTexturesCache.push(texture);\n return texture;\n }\n createRawTexture2DArray(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression = null, textureType = 0) {\n const texture = new InternalTexture(this, InternalTextureSource.Raw2DArray);\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.baseDepth = depth;\n texture.width = width;\n texture.height = height;\n texture.depth = depth;\n texture.format = format;\n texture.type = textureType;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.is2DArray = true;\n if (texture._hardwareTexture) {\n const nativeTexture = texture._hardwareTexture.underlyingResource;\n this._engine.loadRawTexture2DArray(nativeTexture, data, width, height, depth, this._getNativeTextureFormat(format, textureType), generateMipMaps, invertY);\n const filter = this._getNativeSamplingMode(samplingMode);\n this._setTextureSampling(nativeTexture, filter);\n }\n texture.isReady = true;\n this._internalTexturesCache.push(texture);\n return texture;\n }\n updateRawTexture(texture, bufferView, format, invertY, compression = null, type = 0, useSRGBBuffer = false) {\n if (!texture) {\n return;\n }\n if (bufferView && texture._hardwareTexture) {\n const underlyingResource = texture._hardwareTexture.underlyingResource;\n this._engine.loadRawTexture(underlyingResource, bufferView, texture.width, texture.height, this._getNativeTextureFormat(format, type), texture.generateMipMaps, texture.invertY);\n }\n texture.isReady = true;\n }\n // TODO: Refactor to share more logic with babylon.engine.ts version.\n /**\n * Usually called from Texture.ts.\n * Passed information to create a NativeTexture\n * @param url defines a value which contains one of the following:\n * * A conventional http URL, e.g. 'http://...' or 'file://...'\n * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'\n * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'\n * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file\n * @param invertY when true, image is flipped when loaded. You probably want true. Certain compressed textures may invert this if their default is inverted (eg. ktx)\n * @param scene needed for loading to the correct scene\n * @param samplingMode mode with should be used sample / access the texture (Default: Texture.TRILINEAR_SAMPLINGMODE)\n * @param onLoad optional callback to be called upon successful completion\n * @param onError optional callback to be called upon failure\n * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob\n * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities\n * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures\n * @param forcedExtension defines the extension to use to pick the right loader\n * @param mimeType defines an optional mime type\n * @param loaderOptions options to be passed to the loader\n * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)\n * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU).\n * @returns a InternalTexture for assignment back into BABYLON.Texture\n */\n createTexture(url, noMipmap, invertY, scene, samplingMode = 3, onLoad = null, onError = null, buffer = null, fallback = null, format = null, forcedExtension = null, mimeType, loaderOptions, creationFlags, useSRGBBuffer = false) {\n url = url || \"\";\n const fromData = url.substr(0, 5) === \"data:\";\n //const fromBlob = url.substr(0, 5) === \"blob:\";\n const isBase64 = fromData && url.indexOf(\";base64,\") !== -1;\n const texture = fallback ? fallback : new InternalTexture(this, InternalTextureSource.Url);\n const originalUrl = url;\n if (this._transformTextureUrl && !isBase64 && !fallback && !buffer) {\n url = this._transformTextureUrl(url);\n }\n // establish the file extension, if possible\n const lastDot = url.lastIndexOf(\".\");\n const extension = forcedExtension ? forcedExtension : lastDot > -1 ? url.substring(lastDot).toLowerCase() : \"\";\n let loader = null;\n for (const availableLoader of Engine._TextureLoaders) {\n if (availableLoader.canLoad(extension)) {\n loader = availableLoader;\n break;\n }\n }\n if (scene) {\n scene.addPendingData(texture);\n }\n texture.url = url;\n texture.generateMipMaps = !noMipmap;\n texture.samplingMode = samplingMode;\n texture.invertY = invertY;\n texture._useSRGBBuffer = this._getUseSRGBBuffer(useSRGBBuffer, noMipmap);\n if (!this.doNotHandleContextLost) {\n // Keep a link to the buffer only if we plan to handle context lost\n texture._buffer = buffer;\n }\n let onLoadObserver = null;\n if (onLoad && !fallback) {\n onLoadObserver = texture.onLoadedObservable.add(onLoad);\n }\n if (!fallback) {\n this._internalTexturesCache.push(texture);\n }\n const onInternalError = (message, exception) => {\n if (scene) {\n scene.removePendingData(texture);\n }\n if (url === originalUrl) {\n if (onLoadObserver) {\n texture.onLoadedObservable.remove(onLoadObserver);\n }\n if (EngineStore.UseFallbackTexture) {\n this.createTexture(EngineStore.FallbackTexture, noMipmap, texture.invertY, scene, samplingMode, null, onError, buffer, texture);\n }\n if (onError) {\n onError((message || \"Unknown error\") + (EngineStore.UseFallbackTexture ? \" - Fallback texture was used\" : \"\"), exception);\n }\n }\n else {\n // fall back to the original url if the transformed url fails to load\n Logger.Warn(`Failed to load ${url}, falling back to ${originalUrl}`);\n this.createTexture(originalUrl, noMipmap, texture.invertY, scene, samplingMode, onLoad, onError, buffer, texture, format, forcedExtension, mimeType, loaderOptions);\n }\n };\n // processing for non-image formats\n if (loader) {\n throw new Error(\"Loading textures from IInternalTextureLoader not yet implemented.\");\n }\n else {\n const onload = (data) => {\n if (!texture._hardwareTexture) {\n if (scene) {\n scene.removePendingData(texture);\n }\n return;\n }\n const underlyingResource = texture._hardwareTexture.underlyingResource;\n this._engine.loadTexture(underlyingResource, data, !noMipmap, invertY, useSRGBBuffer, () => {\n texture.baseWidth = this._engine.getTextureWidth(underlyingResource);\n texture.baseHeight = this._engine.getTextureHeight(underlyingResource);\n texture.width = texture.baseWidth;\n texture.height = texture.baseHeight;\n texture.isReady = true;\n const filter = this._getNativeSamplingMode(samplingMode);\n this._setTextureSampling(underlyingResource, filter);\n if (scene) {\n scene.removePendingData(texture);\n }\n texture.onLoadedObservable.notifyObservers(texture);\n texture.onLoadedObservable.clear();\n }, () => {\n throw new Error(\"Could not load a native texture.\");\n });\n };\n if (fromData && buffer) {\n if (buffer instanceof ArrayBuffer) {\n onload(new Uint8Array(buffer));\n }\n else if (ArrayBuffer.isView(buffer)) {\n onload(buffer);\n }\n else if (typeof buffer === \"string\") {\n onload(new Uint8Array(Tools.DecodeBase64(buffer)));\n }\n else {\n throw new Error(\"Unsupported buffer type\");\n }\n }\n else {\n if (isBase64) {\n onload(new Uint8Array(Tools.DecodeBase64(url)));\n }\n else {\n this._loadFile(url, (data) => onload(new Uint8Array(data)), undefined, undefined, true, (request, exception) => {\n onInternalError(\"Unable to load \" + (request ? request.responseURL : url, exception));\n });\n }\n }\n }\n return texture;\n }\n /**\n * Wraps an external native texture in a Babylon texture.\n * @param texture defines the external texture\n * @param hasMipMaps defines whether the external texture has mip maps\n * @param samplingMode defines the sampling mode for the external texture (default: 3)\n * @returns the babylon internal texture\n */\n wrapNativeTexture(texture, hasMipMaps = false, samplingMode = 3) {\n const hardwareTexture = new NativeHardwareTexture(texture, this._engine);\n const internalTexture = new InternalTexture(this, InternalTextureSource.Unknown, true);\n internalTexture._hardwareTexture = hardwareTexture;\n internalTexture.isReady = true;\n internalTexture.useMipMaps = hasMipMaps;\n this.updateTextureSamplingMode(samplingMode, internalTexture);\n return internalTexture;\n }\n /**\n * Wraps an external web gl texture in a Babylon texture.\n * @returns the babylon internal texture\n */\n wrapWebGLTexture() {\n throw new Error(\"wrapWebGLTexture is not supported, use wrapNativeTexture instead.\");\n }\n _createDepthStencilTexture(size, options, rtWrapper) {\n // TODO: options?\n const nativeRTWrapper = rtWrapper;\n const texture = new InternalTexture(this, InternalTextureSource.DepthStencil);\n const width = size.width || size;\n const height = size.height || size;\n const framebuffer = this._engine.createFrameBuffer(texture._hardwareTexture.underlyingResource, width, height, true, true);\n nativeRTWrapper._framebufferDepthStencil = framebuffer;\n return texture;\n }\n /**\n * @internal\n */\n _releaseFramebufferObjects(framebuffer) {\n if (framebuffer) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(framebuffer);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n }\n /**\n * @internal Engine abstraction for loading and creating an image bitmap from a given source string.\n * @param imageSource source to load the image from.\n * @param options An object that sets options for the image's extraction.\n * @returns ImageBitmap\n */\n _createImageBitmapFromSource(imageSource, options) {\n const promise = new Promise((resolve, reject) => {\n const image = this.createCanvasImage();\n image.onload = () => {\n try {\n const imageBitmap = this._engine.createImageBitmap(image);\n resolve(imageBitmap);\n }\n catch (error) {\n reject(`Error loading image ${image.src} with exception: ${error}`);\n }\n };\n image.onerror = (error) => {\n reject(`Error loading image ${image.src} with exception: ${error}`);\n };\n image.src = imageSource;\n });\n return promise;\n }\n /**\n * Engine abstraction for createImageBitmap\n * @param image source for image\n * @param options An object that sets options for the image's extraction.\n * @returns ImageBitmap\n */\n createImageBitmap(image, options) {\n return new Promise((resolve, reject) => {\n if (Array.isArray(image)) {\n const arr = image;\n if (arr.length) {\n const image = this._engine.createImageBitmap(arr[0]);\n if (image) {\n resolve(image);\n return;\n }\n }\n }\n reject(`Unsupported data for createImageBitmap.`);\n });\n }\n /**\n * Resize an image and returns the image data as an uint8array\n * @param image image to resize\n * @param bufferWidth destination buffer width\n * @param bufferHeight destination buffer height\n * @returns an uint8array containing RGBA values of bufferWidth * bufferHeight size\n */\n resizeImageBitmap(image, bufferWidth, bufferHeight) {\n return this._engine.resizeImageBitmap(image, bufferWidth, bufferHeight);\n }\n /**\n * Creates a cube texture\n * @param rootUrl defines the url where the files to load is located\n * @param scene defines the current scene\n * @param files defines the list of files to load (1 per face)\n * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)\n * @param onLoad defines an optional callback raised when the texture is loaded\n * @param onError defines an optional callback raised if there is an issue to load the texture\n * @param format defines the format of the data\n * @param forcedExtension defines the extension to use to pick the right loader\n * @param createPolynomials if a polynomial sphere should be created for the cube texture\n * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness\n * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness\n * @param fallback defines texture to use while falling back when (compressed) texture file not found.\n * @param loaderOptions options to be passed to the loader\n * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU).\n * @returns the cube texture as an InternalTexture\n */\n createCubeTexture(rootUrl, scene, files, noMipmap, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = false, lodScale = 0, lodOffset = 0, fallback = null, loaderOptions, useSRGBBuffer = false) {\n const texture = fallback ? fallback : new InternalTexture(this, InternalTextureSource.Cube);\n texture.isCube = true;\n texture.url = rootUrl;\n texture.generateMipMaps = !noMipmap;\n texture._lodGenerationScale = lodScale;\n texture._lodGenerationOffset = lodOffset;\n if (!this._doNotHandleContextLost) {\n texture._extension = forcedExtension;\n texture._files = files;\n }\n const lastDot = rootUrl.lastIndexOf(\".\");\n const extension = forcedExtension ? forcedExtension : lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : \"\";\n // TODO: use texture loader to load env files?\n if (extension === \".env\") {\n const onloaddata = (data) => {\n const info = GetEnvInfo(data);\n texture.width = info.width;\n texture.height = info.width;\n UploadEnvSpherical(texture, info);\n const specularInfo = info.specular;\n if (!specularInfo) {\n throw new Error(`Nothing else parsed so far`);\n }\n texture._lodGenerationScale = specularInfo.lodGenerationScale;\n const imageData = CreateImageDataArrayBufferViews(data, info);\n texture.format = 5;\n texture.type = 0;\n texture.generateMipMaps = true;\n texture.getEngine().updateTextureSamplingMode(Texture.TRILINEAR_SAMPLINGMODE, texture);\n texture._isRGBD = true;\n texture.invertY = true;\n this._engine.loadCubeTextureWithMips(texture._hardwareTexture.underlyingResource, imageData, false, useSRGBBuffer, () => {\n texture.isReady = true;\n if (onLoad) {\n onLoad();\n }\n }, () => {\n throw new Error(\"Could not load a native cube texture.\");\n });\n };\n if (files && files.length === 6) {\n throw new Error(`Multi-file loading not allowed on env files.`);\n }\n else {\n const onInternalError = (request, exception) => {\n if (onError && request) {\n onError(request.status + \" \" + request.statusText, exception);\n }\n };\n this._loadFile(rootUrl, (data) => onloaddata(new Uint8Array(data)), undefined, undefined, true, onInternalError);\n }\n }\n else {\n if (!files || files.length !== 6) {\n throw new Error(\"Cannot load cubemap because 6 files were not defined\");\n }\n // Reorder from [+X, +Y, +Z, -X, -Y, -Z] to [+X, -X, +Y, -Y, +Z, -Z].\n const reorderedFiles = [files[0], files[3], files[1], files[4], files[2], files[5]];\n Promise.all(reorderedFiles.map((file) => Tools.LoadFileAsync(file).then((data) => new Uint8Array(data))))\n .then((data) => {\n return new Promise((resolve, reject) => {\n this._engine.loadCubeTexture(texture._hardwareTexture.underlyingResource, data, !noMipmap, true, useSRGBBuffer, resolve, reject);\n });\n })\n .then(() => {\n texture.isReady = true;\n if (onLoad) {\n onLoad();\n }\n }, (error) => {\n if (onError) {\n onError(`Failed to load cubemap: ${error.message}`, error);\n }\n });\n }\n this._internalTexturesCache.push(texture);\n return texture;\n }\n /** @internal */\n _createHardwareTexture() {\n return new NativeHardwareTexture(this._createTexture(), this._engine);\n }\n /** @internal */\n _createHardwareRenderTargetWrapper(isMulti, isCube, size) {\n const rtWrapper = new NativeRenderTargetWrapper(isMulti, isCube, size, this);\n this._renderTargetWrapperCache.push(rtWrapper);\n return rtWrapper;\n }\n /** @internal */\n _createInternalTexture(size, options, _delayGPUTextureCreation = true, source = InternalTextureSource.Unknown) {\n var _a;\n let generateMipMaps = false;\n let type = 0;\n let samplingMode = 3;\n let format = 5;\n let useSRGBBuffer = false;\n let samples = 1;\n let label;\n if (options !== undefined && typeof options === \"object\") {\n generateMipMaps = !!options.generateMipMaps;\n type = options.type === undefined ? 0 : options.type;\n samplingMode = options.samplingMode === undefined ? 3 : options.samplingMode;\n format = options.format === undefined ? 5 : options.format;\n useSRGBBuffer = options.useSRGBBuffer === undefined ? false : options.useSRGBBuffer;\n samples = (_a = options.samples) !== null && _a !== void 0 ? _a : 1;\n label = options.label;\n }\n else {\n generateMipMaps = !!options;\n }\n useSRGBBuffer && (useSRGBBuffer = this._caps.supportSRGBBuffers && (this.webGLVersion > 1 || this.isWebGPU));\n if (type === 1 && !this._caps.textureFloatLinearFiltering) {\n // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE\n samplingMode = 1;\n }\n else if (type === 2 && !this._caps.textureHalfFloatLinearFiltering) {\n // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE\n samplingMode = 1;\n }\n if (type === 1 && !this._caps.textureFloat) {\n type = 0;\n Logger.Warn(\"Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE\");\n }\n const texture = new InternalTexture(this, source);\n const width = size.width || size;\n const height = size.height || size;\n const layers = size.layers || 0;\n if (layers !== 0) {\n throw new Error(\"Texture layers are not supported in Babylon Native\");\n }\n const nativeTexture = texture._hardwareTexture.underlyingResource;\n const nativeTextureFormat = this._getNativeTextureFormat(format, type);\n // REVIEW: We are always setting the renderTarget flag as we don't know whether the texture will be used as a render target.\n this._engine.initializeTexture(nativeTexture, width, height, generateMipMaps, nativeTextureFormat, true, useSRGBBuffer);\n this._setTextureSampling(nativeTexture, this._getNativeSamplingMode(samplingMode));\n texture._useSRGBBuffer = useSRGBBuffer;\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = width;\n texture.height = height;\n texture.depth = layers;\n texture.isReady = true;\n texture.samples = samples;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.type = type;\n texture.format = format;\n texture.label = label;\n this._internalTexturesCache.push(texture);\n return texture;\n }\n createRenderTargetTexture(size, options) {\n var _a, _b;\n const rtWrapper = this._createHardwareRenderTargetWrapper(false, false, size);\n let generateDepthBuffer = true;\n let generateStencilBuffer = false;\n let noColorAttachment = false;\n let colorAttachment = undefined;\n let samples = 1;\n if (options !== undefined && typeof options === \"object\") {\n generateDepthBuffer = (_a = options.generateDepthBuffer) !== null && _a !== void 0 ? _a : true;\n generateStencilBuffer = !!options.generateStencilBuffer;\n noColorAttachment = !!options.noColorAttachment;\n colorAttachment = options.colorAttachment;\n samples = (_b = options.samples) !== null && _b !== void 0 ? _b : 1;\n }\n const texture = colorAttachment || (noColorAttachment ? null : this._createInternalTexture(size, options, true, InternalTextureSource.RenderTarget));\n const width = size.width || size;\n const height = size.height || size;\n const framebuffer = this._engine.createFrameBuffer(texture ? texture._hardwareTexture.underlyingResource : null, width, height, generateStencilBuffer, generateDepthBuffer);\n rtWrapper._framebuffer = framebuffer;\n rtWrapper._generateDepthBuffer = generateDepthBuffer;\n rtWrapper._generateStencilBuffer = generateStencilBuffer;\n rtWrapper.setTextures(texture);\n this.updateRenderTargetTextureSampleCount(rtWrapper, samples);\n return rtWrapper;\n }\n // This function is being added for the sole purpose of overriding the ThinEngine version. The reason\n // for this is that the ThinEngine version of this function uses a WebGL2RenderingContext, which is not\n // available in Babylon Native. The return value is just a hard-coded value that is not used anywhere\n // in Babylon Native's code. This is effectively a hack/workaround so that Babylon Native doesn't crash\n // This function should be updated once the maxMSAASamples is updated as well.\n updateRenderTargetTextureSampleCount(rtWrapper, samples) {\n // TODO: Implement this function once the maxMSAASamples is updated.\n return 1;\n }\n updateTextureSamplingMode(samplingMode, texture) {\n if (texture._hardwareTexture) {\n const filter = this._getNativeSamplingMode(samplingMode);\n this._setTextureSampling(texture._hardwareTexture.underlyingResource, filter);\n }\n texture.samplingMode = samplingMode;\n }\n bindFramebuffer(texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {\n const nativeRTWrapper = texture;\n if (this._currentRenderTarget) {\n this.unBindFramebuffer(this._currentRenderTarget);\n }\n this._currentRenderTarget = texture;\n if (faceIndex) {\n throw new Error(\"Cuboid frame buffers are not yet supported in NativeEngine.\");\n }\n if (requiredWidth || requiredHeight) {\n throw new Error(\"Required width/height for frame buffers not yet supported in NativeEngine.\");\n }\n if (forceFullscreenViewport) {\n //Not supported yet but don't stop rendering\n }\n if (nativeRTWrapper._framebufferDepthStencil) {\n this._bindUnboundFramebuffer(nativeRTWrapper._framebufferDepthStencil);\n }\n else {\n this._bindUnboundFramebuffer(nativeRTWrapper._framebuffer);\n }\n }\n unBindFramebuffer(texture, disableGenerateMipMaps = false, onBeforeUnbind) {\n // NOTE: Disabling mipmap generation is not yet supported in NativeEngine.\n this._currentRenderTarget = null;\n if (onBeforeUnbind) {\n onBeforeUnbind();\n }\n this._bindUnboundFramebuffer(null);\n }\n createDynamicVertexBuffer(data) {\n return this.createVertexBuffer(data, true);\n }\n updateDynamicIndexBuffer(indexBuffer, indices, offset = 0) {\n const buffer = indexBuffer;\n const data = this._normalizeIndexData(indices);\n buffer.is32Bits = data.BYTES_PER_ELEMENT === 4;\n this._engine.updateDynamicIndexBuffer(buffer.nativeIndexBuffer, data.buffer, data.byteOffset, data.byteLength, offset);\n }\n updateDynamicVertexBuffer(vertexBuffer, verticies, byteOffset, byteLength) {\n const buffer = vertexBuffer;\n const data = ArrayBuffer.isView(verticies) ? verticies : new Float32Array(verticies);\n this._engine.updateDynamicVertexBuffer(buffer.nativeVertexBuffer, data.buffer, data.byteOffset + (byteOffset !== null && byteOffset !== void 0 ? byteOffset : 0), byteLength !== null && byteLength !== void 0 ? byteLength : data.byteLength);\n }\n // TODO: Refactor to share more logic with base Engine implementation.\n _setTexture(channel, texture, isPartOfTextureArray = false, depthStencilTexture = false) {\n const uniform = this._boundUniforms[channel];\n if (!uniform) {\n return false;\n }\n // Not ready?\n if (!texture) {\n if (this._boundTexturesCache[channel] != null) {\n this._activeChannel = channel;\n this._boundTexturesCache[channel] = null;\n }\n return false;\n }\n // Video\n if (texture.video) {\n this._activeChannel = channel;\n texture.update();\n }\n else if (texture.delayLoadState === 4) {\n // Delay loading\n texture.delayLoad();\n return false;\n }\n let internalTexture;\n if (depthStencilTexture) {\n internalTexture = texture.depthStencilTexture;\n }\n else if (texture.isReady()) {\n internalTexture = texture.getInternalTexture();\n }\n else if (texture.isCube) {\n internalTexture = this.emptyCubeTexture;\n }\n else if (texture.is3D) {\n internalTexture = this.emptyTexture3D;\n }\n else if (texture.is2DArray) {\n internalTexture = this.emptyTexture2DArray;\n }\n else {\n internalTexture = this.emptyTexture;\n }\n this._activeChannel = channel;\n if (!internalTexture || !internalTexture._hardwareTexture) {\n return false;\n }\n this._setTextureWrapMode(internalTexture._hardwareTexture.underlyingResource, this._getAddressMode(texture.wrapU), this._getAddressMode(texture.wrapV), this._getAddressMode(texture.wrapR));\n this._updateAnisotropicLevel(texture);\n this._setTextureCore(uniform, internalTexture._hardwareTexture.underlyingResource);\n return true;\n }\n // filter is a NativeFilter.XXXX value.\n _setTextureSampling(texture, filter) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(texture);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(filter);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n // addressModes are NativeAddressMode.XXXX values.\n _setTextureWrapMode(texture, addressModeU, addressModeV, addressModeW) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(texture);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(addressModeU);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(addressModeV);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(addressModeW);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n _setTextureCore(uniform, texture) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(texture);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n // TODO: Share more of this logic with the base implementation.\n // TODO: Rename to match naming in base implementation once refactoring allows different parameters.\n _updateAnisotropicLevel(texture) {\n const internalTexture = texture.getInternalTexture();\n const value = texture.anisotropicFilteringLevel;\n if (!internalTexture || !internalTexture._hardwareTexture) {\n return;\n }\n if (internalTexture._cachedAnisotropicFilteringLevel !== value) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(internalTexture._hardwareTexture.underlyingResource);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(value);\n this._commandBufferEncoder.finishEncodingCommand();\n internalTexture._cachedAnisotropicFilteringLevel = value;\n }\n }\n // Returns a NativeAddressMode.XXX value.\n _getAddressMode(wrapMode) {\n switch (wrapMode) {\n case 1:\n return _native.Engine.ADDRESS_MODE_WRAP;\n case 0:\n return _native.Engine.ADDRESS_MODE_CLAMP;\n case 2:\n return _native.Engine.ADDRESS_MODE_MIRROR;\n default:\n throw new Error(\"Unexpected wrap mode: \" + wrapMode + \".\");\n }\n }\n /**\n * @internal\n */\n _bindTexture(channel, texture) {\n const uniform = this._boundUniforms[channel];\n if (!uniform) {\n return;\n }\n if (texture && texture._hardwareTexture) {\n const underlyingResource = texture._hardwareTexture.underlyingResource;\n this._setTextureCore(uniform, underlyingResource);\n }\n }\n _deleteBuffer(buffer) {\n if (buffer.nativeIndexBuffer) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(buffer.nativeIndexBuffer);\n this._commandBufferEncoder.finishEncodingCommand();\n delete buffer.nativeIndexBuffer;\n }\n if (buffer.nativeVertexBuffer) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(buffer.nativeVertexBuffer);\n this._commandBufferEncoder.finishEncodingCommand();\n delete buffer.nativeVertexBuffer;\n }\n }\n /**\n * Create a canvas\n * @param width width\n * @param height height\n * @returns ICanvas interface\n */\n createCanvas(width, height) {\n if (!_native.Canvas) {\n throw new Error(\"Native Canvas plugin not available.\");\n }\n const canvas = new _native.Canvas();\n canvas.width = width;\n canvas.height = height;\n return canvas;\n }\n /**\n * Create an image to use with canvas\n * @returns IImage interface\n */\n createCanvasImage() {\n if (!_native.Canvas) {\n throw new Error(\"Native Canvas plugin not available.\");\n }\n const image = new _native.Image();\n return image;\n }\n /**\n * Update a portion of an internal texture\n * @param texture defines the texture to update\n * @param imageData defines the data to store into the texture\n * @param xOffset defines the x coordinates of the update rectangle\n * @param yOffset defines the y coordinates of the update rectangle\n * @param width defines the width of the update rectangle\n * @param height defines the height of the update rectangle\n * @param faceIndex defines the face index if texture is a cube (0 by default)\n * @param lod defines the lod level to update (0 by default)\n * @param generateMipMaps defines whether to generate mipmaps or not\n */\n updateTextureData(texture, imageData, xOffset, yOffset, width, height, faceIndex = 0, lod = 0, generateMipMaps = false) {\n throw new Error(\"updateTextureData not implemented.\");\n }\n /**\n * @internal\n */\n _uploadCompressedDataToTextureDirectly(texture, internalFormat, width, height, data, faceIndex = 0, lod = 0) {\n throw new Error(\"_uploadCompressedDataToTextureDirectly not implemented.\");\n }\n /**\n * @internal\n */\n _uploadDataToTextureDirectly(texture, imageData, faceIndex = 0, lod = 0) {\n throw new Error(\"_uploadDataToTextureDirectly not implemented.\");\n }\n /**\n * @internal\n */\n _uploadArrayBufferViewToTexture(texture, imageData, faceIndex = 0, lod = 0) {\n throw new Error(\"_uploadArrayBufferViewToTexture not implemented.\");\n }\n /**\n * @internal\n */\n _uploadImageToTexture(texture, image, faceIndex = 0, lod = 0) {\n throw new Error(\"_uploadArrayBufferViewToTexture not implemented.\");\n }\n // JavaScript-to-Native conversion helper functions.\n _getNativeSamplingMode(samplingMode) {\n switch (samplingMode) {\n case 1:\n return _native.Engine.TEXTURE_NEAREST_NEAREST;\n case 2:\n return _native.Engine.TEXTURE_LINEAR_LINEAR;\n case 3:\n return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR;\n case 4:\n return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;\n case 5:\n return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;\n case 6:\n return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;\n case 7:\n return _native.Engine.TEXTURE_NEAREST_LINEAR;\n case 8:\n return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR;\n case 9:\n return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;\n case 10:\n return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;\n case 11:\n return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST;\n case 12:\n return _native.Engine.TEXTURE_LINEAR_NEAREST;\n default:\n throw new Error(`Unsupported sampling mode: ${samplingMode}.`);\n }\n }\n _getStencilFunc(func) {\n switch (func) {\n case 513:\n return _native.Engine.STENCIL_TEST_LESS;\n case 515:\n return _native.Engine.STENCIL_TEST_LEQUAL;\n case 514:\n return _native.Engine.STENCIL_TEST_EQUAL;\n case 518:\n return _native.Engine.STENCIL_TEST_GEQUAL;\n case 516:\n return _native.Engine.STENCIL_TEST_GREATER;\n case 517:\n return _native.Engine.STENCIL_TEST_NOTEQUAL;\n case 512:\n return _native.Engine.STENCIL_TEST_NEVER;\n case 519:\n return _native.Engine.STENCIL_TEST_ALWAYS;\n default:\n throw new Error(`Unsupported stencil func mode: ${func}.`);\n }\n }\n _getStencilOpFail(opFail) {\n switch (opFail) {\n case 7680:\n return _native.Engine.STENCIL_OP_FAIL_S_KEEP;\n case 0:\n return _native.Engine.STENCIL_OP_FAIL_S_ZERO;\n case 7681:\n return _native.Engine.STENCIL_OP_FAIL_S_REPLACE;\n case 7682:\n return _native.Engine.STENCIL_OP_FAIL_S_INCR;\n case 7683:\n return _native.Engine.STENCIL_OP_FAIL_S_DECR;\n case 5386:\n return _native.Engine.STENCIL_OP_FAIL_S_INVERT;\n case 34055:\n return _native.Engine.STENCIL_OP_FAIL_S_INCRSAT;\n case 34056:\n return _native.Engine.STENCIL_OP_FAIL_S_DECRSAT;\n default:\n throw new Error(`Unsupported stencil OpFail mode: ${opFail}.`);\n }\n }\n _getStencilDepthFail(depthFail) {\n switch (depthFail) {\n case 7680:\n return _native.Engine.STENCIL_OP_FAIL_Z_KEEP;\n case 0:\n return _native.Engine.STENCIL_OP_FAIL_Z_ZERO;\n case 7681:\n return _native.Engine.STENCIL_OP_FAIL_Z_REPLACE;\n case 7682:\n return _native.Engine.STENCIL_OP_FAIL_Z_INCR;\n case 7683:\n return _native.Engine.STENCIL_OP_FAIL_Z_DECR;\n case 5386:\n return _native.Engine.STENCIL_OP_FAIL_Z_INVERT;\n case 34055:\n return _native.Engine.STENCIL_OP_FAIL_Z_INCRSAT;\n case 34056:\n return _native.Engine.STENCIL_OP_FAIL_Z_DECRSAT;\n default:\n throw new Error(`Unsupported stencil depthFail mode: ${depthFail}.`);\n }\n }\n _getStencilDepthPass(opPass) {\n switch (opPass) {\n case 7680:\n return _native.Engine.STENCIL_OP_PASS_Z_KEEP;\n case 0:\n return _native.Engine.STENCIL_OP_PASS_Z_ZERO;\n case 7681:\n return _native.Engine.STENCIL_OP_PASS_Z_REPLACE;\n case 7682:\n return _native.Engine.STENCIL_OP_PASS_Z_INCR;\n case 7683:\n return _native.Engine.STENCIL_OP_PASS_Z_DECR;\n case 5386:\n return _native.Engine.STENCIL_OP_PASS_Z_INVERT;\n case 34055:\n return _native.Engine.STENCIL_OP_PASS_Z_INCRSAT;\n case 34056:\n return _native.Engine.STENCIL_OP_PASS_Z_DECRSAT;\n default:\n throw new Error(`Unsupported stencil opPass mode: ${opPass}.`);\n }\n }\n _getNativeTextureFormat(format, type) {\n if (format == 4 && type == 0) {\n return _native.Engine.TEXTURE_FORMAT_RGB8;\n }\n else if (format == 5 && type == 0) {\n return _native.Engine.TEXTURE_FORMAT_RGBA8;\n }\n else if (format == 5 && type == 2) {\n return _native.Engine.TEXTURE_FORMAT_RGBA16F;\n }\n else if (format == 5 && type == 1) {\n return _native.Engine.TEXTURE_FORMAT_RGBA32F;\n }\n else {\n throw new RuntimeError(`Unsupported texture format or type: format ${format}, type ${type}.`, ErrorCodes.UnsupportedTextureError);\n }\n }\n _getNativeAlphaMode(mode) {\n switch (mode) {\n case 0:\n return _native.Engine.ALPHA_DISABLE;\n case 1:\n return _native.Engine.ALPHA_ADD;\n case 2:\n return _native.Engine.ALPHA_COMBINE;\n case 3:\n return _native.Engine.ALPHA_SUBTRACT;\n case 4:\n return _native.Engine.ALPHA_MULTIPLY;\n case 5:\n return _native.Engine.ALPHA_MAXIMIZED;\n case 6:\n return _native.Engine.ALPHA_ONEONE;\n case 7:\n return _native.Engine.ALPHA_PREMULTIPLIED;\n case 8:\n return _native.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;\n case 9:\n return _native.Engine.ALPHA_INTERPOLATE;\n case 10:\n return _native.Engine.ALPHA_SCREENMODE;\n default:\n throw new Error(`Unsupported alpha mode: ${mode}.`);\n }\n }\n _getNativeAttribType(type) {\n switch (type) {\n case VertexBuffer.BYTE:\n return _native.Engine.ATTRIB_TYPE_INT8;\n case VertexBuffer.UNSIGNED_BYTE:\n return _native.Engine.ATTRIB_TYPE_UINT8;\n case VertexBuffer.SHORT:\n return _native.Engine.ATTRIB_TYPE_INT16;\n case VertexBuffer.UNSIGNED_SHORT:\n return _native.Engine.ATTRIB_TYPE_UINT16;\n case VertexBuffer.FLOAT:\n return _native.Engine.ATTRIB_TYPE_FLOAT;\n default:\n throw new Error(`Unsupported attribute type: ${type}.`);\n }\n }\n getFontOffset(font) {\n // TODO\n const result = { ascent: 0, height: 0, descent: 0 };\n return result;\n }\n _readTexturePixels(texture, width, height, faceIndex, level, buffer, _flushRenderer, _noDataConversion, x, y) {\n var _a, _b, _c, _d;\n if (faceIndex !== undefined && faceIndex !== -1) {\n throw new Error(`Reading cubemap faces is not supported, but faceIndex is ${faceIndex}.`);\n }\n return this._engine\n .readTexture((_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource, level !== null && level !== void 0 ? level : 0, x !== null && x !== void 0 ? x : 0, y !== null && y !== void 0 ? y : 0, width, height, (_b = buffer === null || buffer === void 0 ? void 0 : buffer.buffer) !== null && _b !== void 0 ? _b : null, (_c = buffer === null || buffer === void 0 ? void 0 : buffer.byteOffset) !== null && _c !== void 0 ? _c : 0, (_d = buffer === null || buffer === void 0 ? void 0 : buffer.byteLength) !== null && _d !== void 0 ? _d : 0)\n .then((rawBuffer) => {\n if (!buffer) {\n buffer = new Uint8Array(rawBuffer);\n }\n return buffer;\n });\n }\n}\n// This must match the protocol version in NativeEngine.cpp\nNativeEngine.PROTOCOL_VERSION = 8;\n//# sourceMappingURL=nativeEngine.js.map","import { NativeEngine } from \"../nativeEngine.js\";\nimport { NativeDataStream } from \"./nativeDataStream.js\";\nNativeEngine._createNativeDataStream = function () {\n if (_native.NativeDataStream.VALIDATION_ENABLED) {\n return new ValidatedNativeDataStream();\n }\n else {\n return new NativeDataStream();\n }\n};\nexport class ValidatedNativeDataStream extends NativeDataStream {\n constructor() {\n super();\n }\n writeUint32(value) {\n super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32);\n super.writeUint32(value);\n }\n writeInt32(value) {\n super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32);\n super.writeInt32(value);\n }\n writeFloat32(value) {\n super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32);\n super.writeFloat32(value);\n }\n writeUint32Array(values) {\n super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32_ARRAY);\n super.writeUint32Array(values);\n }\n writeInt32Array(values) {\n super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32_ARRAY);\n super.writeInt32Array(values);\n }\n writeFloat32Array(values) {\n super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32_ARRAY);\n super.writeFloat32Array(values);\n }\n writeNativeData(handle) {\n super.writeUint32(_native.NativeDataStream.VALIDATION_NATIVE_DATA);\n super.writeNativeData(handle);\n }\n writeBoolean(value) {\n super.writeUint32(_native.NativeDataStream.VALIDATION_BOOLEAN);\n super.writeBoolean(value);\n }\n}\n//# sourceMappingURL=validatedNativeDataStream.js.map","export * from \"./nativeDataStream.js\";\nexport * from \"./validatedNativeDataStream.js\";\n//# sourceMappingURL=index.js.map","/** @internal */\n// eslint-disable-next-line import/export\nexport var PowerPreference;\n(function (PowerPreference) {\n PowerPreference[\"LowPower\"] = \"low-power\";\n PowerPreference[\"HighPerformance\"] = \"high-performance\";\n})(PowerPreference || (PowerPreference = {}));\n/** @internal */\nexport var FeatureName;\n(function (FeatureName) {\n FeatureName[\"DepthClipControl\"] = \"depth-clip-control\";\n FeatureName[\"Depth32FloatStencil8\"] = \"depth32float-stencil8\";\n FeatureName[\"TextureCompressionBC\"] = \"texture-compression-bc\";\n FeatureName[\"TextureCompressionETC2\"] = \"texture-compression-etc2\";\n FeatureName[\"TextureCompressionASTC\"] = \"texture-compression-astc\";\n FeatureName[\"TimestampQuery\"] = \"timestamp-query\";\n FeatureName[\"IndirectFirstInstance\"] = \"indirect-first-instance\";\n FeatureName[\"ShaderF16\"] = \"shader-f16\";\n FeatureName[\"RG11B10UFloatRenderable\"] = \"rg11b10ufloat-renderable\";\n FeatureName[\"BGRA8UnormStorage\"] = \"bgra8unorm-storage\";\n FeatureName[\"Float32Filterable\"] = \"float32-filterable\";\n})(FeatureName || (FeatureName = {}));\n/** @internal */\nexport var BufferMapState;\n(function (BufferMapState) {\n BufferMapState[\"Unmapped\"] = \"unmapped\";\n BufferMapState[\"Pending\"] = \"pending\";\n BufferMapState[\"Mapped\"] = \"mapped\";\n})(BufferMapState || (BufferMapState = {}));\n/** @internal */\nexport var BufferUsage;\n(function (BufferUsage) {\n BufferUsage[BufferUsage[\"MapRead\"] = 1] = \"MapRead\";\n BufferUsage[BufferUsage[\"MapWrite\"] = 2] = \"MapWrite\";\n BufferUsage[BufferUsage[\"CopySrc\"] = 4] = \"CopySrc\";\n BufferUsage[BufferUsage[\"CopyDst\"] = 8] = \"CopyDst\";\n BufferUsage[BufferUsage[\"Index\"] = 16] = \"Index\";\n BufferUsage[BufferUsage[\"Vertex\"] = 32] = \"Vertex\";\n BufferUsage[BufferUsage[\"Uniform\"] = 64] = \"Uniform\";\n BufferUsage[BufferUsage[\"Storage\"] = 128] = \"Storage\";\n BufferUsage[BufferUsage[\"Indirect\"] = 256] = \"Indirect\";\n BufferUsage[BufferUsage[\"QueryResolve\"] = 512] = \"QueryResolve\";\n})(BufferUsage || (BufferUsage = {}));\n/** @internal */\nexport var MapMode;\n(function (MapMode) {\n MapMode[MapMode[\"Read\"] = 1] = \"Read\";\n MapMode[MapMode[\"Write\"] = 2] = \"Write\";\n})(MapMode || (MapMode = {}));\n/** @internal */\nexport var TextureDimension;\n(function (TextureDimension) {\n TextureDimension[\"E1d\"] = \"1d\";\n TextureDimension[\"E2d\"] = \"2d\";\n TextureDimension[\"E3d\"] = \"3d\";\n})(TextureDimension || (TextureDimension = {}));\n/** @internal */\nexport var TextureUsage;\n(function (TextureUsage) {\n TextureUsage[TextureUsage[\"CopySrc\"] = 1] = \"CopySrc\";\n TextureUsage[TextureUsage[\"CopyDst\"] = 2] = \"CopyDst\";\n TextureUsage[TextureUsage[\"TextureBinding\"] = 4] = \"TextureBinding\";\n TextureUsage[TextureUsage[\"StorageBinding\"] = 8] = \"StorageBinding\";\n TextureUsage[TextureUsage[\"RenderAttachment\"] = 16] = \"RenderAttachment\";\n})(TextureUsage || (TextureUsage = {}));\n/** @internal */\nexport var TextureViewDimension;\n(function (TextureViewDimension) {\n TextureViewDimension[\"E1d\"] = \"1d\";\n TextureViewDimension[\"E2d\"] = \"2d\";\n TextureViewDimension[\"E2dArray\"] = \"2d-array\";\n TextureViewDimension[\"Cube\"] = \"cube\";\n TextureViewDimension[\"CubeArray\"] = \"cube-array\";\n TextureViewDimension[\"E3d\"] = \"3d\";\n})(TextureViewDimension || (TextureViewDimension = {}));\n/** @internal */\nexport var TextureAspect;\n(function (TextureAspect) {\n TextureAspect[\"All\"] = \"all\";\n TextureAspect[\"StencilOnly\"] = \"stencil-only\";\n TextureAspect[\"DepthOnly\"] = \"depth-only\";\n})(TextureAspect || (TextureAspect = {}));\n/**\n * Comments taken from https://github.com/gfx-rs/wgpu/blob/master/wgpu-types/src/lib.rs\n * @internal\n */\nexport var TextureFormat;\n(function (TextureFormat) {\n // 8-bit formats\n TextureFormat[\"R8Unorm\"] = \"r8unorm\";\n TextureFormat[\"R8Snorm\"] = \"r8snorm\";\n TextureFormat[\"R8Uint\"] = \"r8uint\";\n TextureFormat[\"R8Sint\"] = \"r8sint\";\n // 16-bit formats\n TextureFormat[\"R16Uint\"] = \"r16uint\";\n TextureFormat[\"R16Sint\"] = \"r16sint\";\n TextureFormat[\"R16Float\"] = \"r16float\";\n TextureFormat[\"RG8Unorm\"] = \"rg8unorm\";\n TextureFormat[\"RG8Snorm\"] = \"rg8snorm\";\n TextureFormat[\"RG8Uint\"] = \"rg8uint\";\n TextureFormat[\"RG8Sint\"] = \"rg8sint\";\n // 32-bit formats\n TextureFormat[\"R32Uint\"] = \"r32uint\";\n TextureFormat[\"R32Sint\"] = \"r32sint\";\n TextureFormat[\"R32Float\"] = \"r32float\";\n TextureFormat[\"RG16Uint\"] = \"rg16uint\";\n TextureFormat[\"RG16Sint\"] = \"rg16sint\";\n TextureFormat[\"RG16Float\"] = \"rg16float\";\n TextureFormat[\"RGBA8Unorm\"] = \"rgba8unorm\";\n TextureFormat[\"RGBA8UnormSRGB\"] = \"rgba8unorm-srgb\";\n TextureFormat[\"RGBA8Snorm\"] = \"rgba8snorm\";\n TextureFormat[\"RGBA8Uint\"] = \"rgba8uint\";\n TextureFormat[\"RGBA8Sint\"] = \"rgba8sint\";\n TextureFormat[\"BGRA8Unorm\"] = \"bgra8unorm\";\n TextureFormat[\"BGRA8UnormSRGB\"] = \"bgra8unorm-srgb\";\n // Packed 32-bit formats\n TextureFormat[\"RGB9E5UFloat\"] = \"rgb9e5ufloat\";\n TextureFormat[\"RGB10A2Unorm\"] = \"rgb10a2unorm\";\n TextureFormat[\"RG11B10UFloat\"] = \"rg11b10ufloat\";\n // 64-bit formats\n TextureFormat[\"RG32Uint\"] = \"rg32uint\";\n TextureFormat[\"RG32Sint\"] = \"rg32sint\";\n TextureFormat[\"RG32Float\"] = \"rg32float\";\n TextureFormat[\"RGBA16Uint\"] = \"rgba16uint\";\n TextureFormat[\"RGBA16Sint\"] = \"rgba16sint\";\n TextureFormat[\"RGBA16Float\"] = \"rgba16float\";\n // 128-bit formats\n TextureFormat[\"RGBA32Uint\"] = \"rgba32uint\";\n TextureFormat[\"RGBA32Sint\"] = \"rgba32sint\";\n TextureFormat[\"RGBA32Float\"] = \"rgba32float\";\n // Depth and stencil formats\n TextureFormat[\"Stencil8\"] = \"stencil8\";\n TextureFormat[\"Depth16Unorm\"] = \"depth16unorm\";\n TextureFormat[\"Depth24Plus\"] = \"depth24plus\";\n TextureFormat[\"Depth24PlusStencil8\"] = \"depth24plus-stencil8\";\n TextureFormat[\"Depth32Float\"] = \"depth32float\";\n // BC compressed formats usable if \"texture-compression-bc\" is both\n // supported by the device/user agent and enabled in requestDevice.\n TextureFormat[\"BC1RGBAUnorm\"] = \"bc1-rgba-unorm\";\n TextureFormat[\"BC1RGBAUnormSRGB\"] = \"bc1-rgba-unorm-srgb\";\n TextureFormat[\"BC2RGBAUnorm\"] = \"bc2-rgba-unorm\";\n TextureFormat[\"BC2RGBAUnormSRGB\"] = \"bc2-rgba-unorm-srgb\";\n TextureFormat[\"BC3RGBAUnorm\"] = \"bc3-rgba-unorm\";\n TextureFormat[\"BC3RGBAUnormSRGB\"] = \"bc3-rgba-unorm-srgb\";\n TextureFormat[\"BC4RUnorm\"] = \"bc4-r-unorm\";\n TextureFormat[\"BC4RSnorm\"] = \"bc4-r-snorm\";\n TextureFormat[\"BC5RGUnorm\"] = \"bc5-rg-unorm\";\n TextureFormat[\"BC5RGSnorm\"] = \"bc5-rg-snorm\";\n TextureFormat[\"BC6HRGBUFloat\"] = \"bc6h-rgb-ufloat\";\n TextureFormat[\"BC6HRGBFloat\"] = \"bc6h-rgb-float\";\n TextureFormat[\"BC7RGBAUnorm\"] = \"bc7-rgba-unorm\";\n TextureFormat[\"BC7RGBAUnormSRGB\"] = \"bc7-rgba-unorm-srgb\";\n // ETC2 compressed formats usable if \"texture-compression-etc2\" is both\n // supported by the device/user agent and enabled in requestDevice.\n TextureFormat[\"ETC2RGB8Unorm\"] = \"etc2-rgb8unorm\";\n TextureFormat[\"ETC2RGB8UnormSRGB\"] = \"etc2-rgb8unorm-srgb\";\n TextureFormat[\"ETC2RGB8A1Unorm\"] = \"etc2-rgb8a1unorm\";\n TextureFormat[\"ETC2RGB8A1UnormSRGB\"] = \"etc2-rgb8a1unorm-srgb\";\n TextureFormat[\"ETC2RGBA8Unorm\"] = \"etc2-rgba8unorm\";\n TextureFormat[\"ETC2RGBA8UnormSRGB\"] = \"etc2-rgba8unorm-srgb\";\n TextureFormat[\"EACR11Unorm\"] = \"eac-r11unorm\";\n TextureFormat[\"EACR11Snorm\"] = \"eac-r11snorm\";\n TextureFormat[\"EACRG11Unorm\"] = \"eac-rg11unorm\";\n TextureFormat[\"EACRG11Snorm\"] = \"eac-rg11snorm\";\n // ASTC compressed formats usable if \"texture-compression-astc\" is both\n // supported by the device/user agent and enabled in requestDevice.\n TextureFormat[\"ASTC4x4Unorm\"] = \"astc-4x4-unorm\";\n TextureFormat[\"ASTC4x4UnormSRGB\"] = \"astc-4x4-unorm-srgb\";\n TextureFormat[\"ASTC5x4Unorm\"] = \"astc-5x4-unorm\";\n TextureFormat[\"ASTC5x4UnormSRGB\"] = \"astc-5x4-unorm-srgb\";\n TextureFormat[\"ASTC5x5Unorm\"] = \"astc-5x5-unorm\";\n TextureFormat[\"ASTC5x5UnormSRGB\"] = \"astc-5x5-unorm-srgb\";\n TextureFormat[\"ASTC6x5Unorm\"] = \"astc-6x5-unorm\";\n TextureFormat[\"ASTC6x5UnormSRGB\"] = \"astc-6x5-unorm-srgb\";\n TextureFormat[\"ASTC6x6Unorm\"] = \"astc-6x6-unorm\";\n TextureFormat[\"ASTC6x6UnormSRGB\"] = \"astc-6x6-unorm-srgb\";\n TextureFormat[\"ASTC8x5Unorm\"] = \"astc-8x5-unorm\";\n TextureFormat[\"ASTC8x5UnormSRGB\"] = \"astc-8x5-unorm-srgb\";\n TextureFormat[\"ASTC8x6Unorm\"] = \"astc-8x6-unorm\";\n TextureFormat[\"ASTC8x6UnormSRGB\"] = \"astc-8x6-unorm-srgb\";\n TextureFormat[\"ASTC8x8Unorm\"] = \"astc-8x8-unorm\";\n TextureFormat[\"ASTC8x8UnormSRGB\"] = \"astc-8x8-unorm-srgb\";\n TextureFormat[\"ASTC10x5Unorm\"] = \"astc-10x5-unorm\";\n TextureFormat[\"ASTC10x5UnormSRGB\"] = \"astc-10x5-unorm-srgb\";\n TextureFormat[\"ASTC10x6Unorm\"] = \"astc-10x6-unorm\";\n TextureFormat[\"ASTC10x6UnormSRGB\"] = \"astc-10x6-unorm-srgb\";\n TextureFormat[\"ASTC10x8Unorm\"] = \"astc-10x8-unorm\";\n TextureFormat[\"ASTC10x8UnormSRGB\"] = \"astc-10x8-unorm-srgb\";\n TextureFormat[\"ASTC10x10Unorm\"] = \"astc-10x10-unorm\";\n TextureFormat[\"ASTC10x10UnormSRGB\"] = \"astc-10x10-unorm-srgb\";\n TextureFormat[\"ASTC12x10Unorm\"] = \"astc-12x10-unorm\";\n TextureFormat[\"ASTC12x10UnormSRGB\"] = \"astc-12x10-unorm-srgb\";\n TextureFormat[\"ASTC12x12Unorm\"] = \"astc-12x12-unorm\";\n TextureFormat[\"ASTC12x12UnormSRGB\"] = \"astc-12x12-unorm-srgb\";\n // \"depth24unorm-stencil8\" feature\n TextureFormat[\"Depth24UnormStencil8\"] = \"depth24unorm-stencil8\";\n // \"depth32float-stencil8\" feature\n TextureFormat[\"Depth32FloatStencil8\"] = \"depth32float-stencil8\";\n})(TextureFormat || (TextureFormat = {}));\n/** @internal */\nexport var AddressMode;\n(function (AddressMode) {\n AddressMode[\"ClampToEdge\"] = \"clamp-to-edge\";\n AddressMode[\"Repeat\"] = \"repeat\";\n AddressMode[\"MirrorRepeat\"] = \"mirror-repeat\";\n})(AddressMode || (AddressMode = {}));\n/** @internal */\nexport var FilterMode;\n(function (FilterMode) {\n FilterMode[\"Nearest\"] = \"nearest\";\n FilterMode[\"Linear\"] = \"linear\";\n})(FilterMode || (FilterMode = {}));\n/** @internal */\nexport var MipmapFilterMode;\n(function (MipmapFilterMode) {\n MipmapFilterMode[\"Nearest\"] = \"nearest\";\n MipmapFilterMode[\"Linear\"] = \"linear\";\n})(MipmapFilterMode || (MipmapFilterMode = {}));\n/** @internal */\nexport var CompareFunction;\n(function (CompareFunction) {\n CompareFunction[\"Never\"] = \"never\";\n CompareFunction[\"Less\"] = \"less\";\n CompareFunction[\"Equal\"] = \"equal\";\n CompareFunction[\"LessEqual\"] = \"less-equal\";\n CompareFunction[\"Greater\"] = \"greater\";\n CompareFunction[\"NotEqual\"] = \"not-equal\";\n CompareFunction[\"GreaterEqual\"] = \"greater-equal\";\n CompareFunction[\"Always\"] = \"always\";\n})(CompareFunction || (CompareFunction = {}));\n/** @internal */\nexport var ShaderStage;\n(function (ShaderStage) {\n ShaderStage[ShaderStage[\"Vertex\"] = 1] = \"Vertex\";\n ShaderStage[ShaderStage[\"Fragment\"] = 2] = \"Fragment\";\n ShaderStage[ShaderStage[\"Compute\"] = 4] = \"Compute\";\n})(ShaderStage || (ShaderStage = {}));\n/** @internal */\nexport var BufferBindingType;\n(function (BufferBindingType) {\n BufferBindingType[\"Uniform\"] = \"uniform\";\n BufferBindingType[\"Storage\"] = \"storage\";\n BufferBindingType[\"ReadOnlyStorage\"] = \"read-only-storage\";\n})(BufferBindingType || (BufferBindingType = {}));\n/** @internal */\nexport var SamplerBindingType;\n(function (SamplerBindingType) {\n SamplerBindingType[\"Filtering\"] = \"filtering\";\n SamplerBindingType[\"NonFiltering\"] = \"non-filtering\";\n SamplerBindingType[\"Comparison\"] = \"comparison\";\n})(SamplerBindingType || (SamplerBindingType = {}));\n/** @internal */\nexport var TextureSampleType;\n(function (TextureSampleType) {\n TextureSampleType[\"Float\"] = \"float\";\n TextureSampleType[\"UnfilterableFloat\"] = \"unfilterable-float\";\n TextureSampleType[\"Depth\"] = \"depth\";\n TextureSampleType[\"Sint\"] = \"sint\";\n TextureSampleType[\"Uint\"] = \"uint\";\n})(TextureSampleType || (TextureSampleType = {}));\n/** @internal */\nexport var StorageTextureAccess;\n(function (StorageTextureAccess) {\n StorageTextureAccess[\"WriteOnly\"] = \"write-only\";\n})(StorageTextureAccess || (StorageTextureAccess = {}));\n/** @internal */\nexport var CompilationMessageType;\n(function (CompilationMessageType) {\n CompilationMessageType[\"Error\"] = \"error\";\n CompilationMessageType[\"Warning\"] = \"warning\";\n CompilationMessageType[\"Info\"] = \"info\";\n})(CompilationMessageType || (CompilationMessageType = {}));\n/** @internal */\nexport var PipelineErrorReason;\n(function (PipelineErrorReason) {\n PipelineErrorReason[\"Validation\"] = \"validation\";\n PipelineErrorReason[\"Internal\"] = \"internal\";\n})(PipelineErrorReason || (PipelineErrorReason = {}));\n/** @internal */\nexport var AutoLayoutMode;\n(function (AutoLayoutMode) {\n AutoLayoutMode[\"Auto\"] = \"auto\";\n})(AutoLayoutMode || (AutoLayoutMode = {}));\n/** @internal */\nexport var PrimitiveTopology;\n(function (PrimitiveTopology) {\n PrimitiveTopology[\"PointList\"] = \"point-list\";\n PrimitiveTopology[\"LineList\"] = \"line-list\";\n PrimitiveTopology[\"LineStrip\"] = \"line-strip\";\n PrimitiveTopology[\"TriangleList\"] = \"triangle-list\";\n PrimitiveTopology[\"TriangleStrip\"] = \"triangle-strip\";\n})(PrimitiveTopology || (PrimitiveTopology = {}));\n/** @internal */\nexport var FrontFace;\n(function (FrontFace) {\n FrontFace[\"CCW\"] = \"ccw\";\n FrontFace[\"CW\"] = \"cw\";\n})(FrontFace || (FrontFace = {}));\n/** @internal */\nexport var CullMode;\n(function (CullMode) {\n CullMode[\"None\"] = \"none\";\n CullMode[\"Front\"] = \"front\";\n CullMode[\"Back\"] = \"back\";\n})(CullMode || (CullMode = {}));\n/** @internal */\nexport var ColorWriteFlags;\n(function (ColorWriteFlags) {\n ColorWriteFlags[ColorWriteFlags[\"Red\"] = 1] = \"Red\";\n ColorWriteFlags[ColorWriteFlags[\"Green\"] = 2] = \"Green\";\n ColorWriteFlags[ColorWriteFlags[\"Blue\"] = 4] = \"Blue\";\n ColorWriteFlags[ColorWriteFlags[\"Alpha\"] = 8] = \"Alpha\";\n ColorWriteFlags[ColorWriteFlags[\"All\"] = 15] = \"All\";\n})(ColorWriteFlags || (ColorWriteFlags = {}));\n/** @internal */\nexport var BlendFactor;\n(function (BlendFactor) {\n BlendFactor[\"Zero\"] = \"zero\";\n BlendFactor[\"One\"] = \"one\";\n BlendFactor[\"Src\"] = \"src\";\n BlendFactor[\"OneMinusSrc\"] = \"one-minus-src\";\n BlendFactor[\"SrcAlpha\"] = \"src-alpha\";\n BlendFactor[\"OneMinusSrcAlpha\"] = \"one-minus-src-alpha\";\n BlendFactor[\"Dst\"] = \"dst\";\n BlendFactor[\"OneMinusDst\"] = \"one-minus-dst\";\n BlendFactor[\"DstAlpha\"] = \"dst-alpha\";\n BlendFactor[\"OneMinusDstAlpha\"] = \"one-minus-dst-alpha\";\n BlendFactor[\"SrcAlphaSaturated\"] = \"src-alpha-saturated\";\n BlendFactor[\"Constant\"] = \"constant\";\n BlendFactor[\"OneMinusConstant\"] = \"one-minus-constant\";\n})(BlendFactor || (BlendFactor = {}));\n/** @internal */\nexport var BlendOperation;\n(function (BlendOperation) {\n BlendOperation[\"Add\"] = \"add\";\n BlendOperation[\"Subtract\"] = \"subtract\";\n BlendOperation[\"ReverseSubtract\"] = \"reverse-subtract\";\n BlendOperation[\"Min\"] = \"min\";\n BlendOperation[\"Max\"] = \"max\";\n})(BlendOperation || (BlendOperation = {}));\n/** @internal */\nexport var StencilOperation;\n(function (StencilOperation) {\n StencilOperation[\"Keep\"] = \"keep\";\n StencilOperation[\"Zero\"] = \"zero\";\n StencilOperation[\"Replace\"] = \"replace\";\n StencilOperation[\"Invert\"] = \"invert\";\n StencilOperation[\"IncrementClamp\"] = \"increment-clamp\";\n StencilOperation[\"DecrementClamp\"] = \"decrement-clamp\";\n StencilOperation[\"IncrementWrap\"] = \"increment-wrap\";\n StencilOperation[\"DecrementWrap\"] = \"decrement-wrap\";\n})(StencilOperation || (StencilOperation = {}));\n/** @internal */\nexport var IndexFormat;\n(function (IndexFormat) {\n IndexFormat[\"Uint16\"] = \"uint16\";\n IndexFormat[\"Uint32\"] = \"uint32\";\n})(IndexFormat || (IndexFormat = {}));\n/** @internal */\nexport var VertexFormat;\n(function (VertexFormat) {\n VertexFormat[\"Uint8x2\"] = \"uint8x2\";\n VertexFormat[\"Uint8x4\"] = \"uint8x4\";\n VertexFormat[\"Sint8x2\"] = \"sint8x2\";\n VertexFormat[\"Sint8x4\"] = \"sint8x4\";\n VertexFormat[\"Unorm8x2\"] = \"unorm8x2\";\n VertexFormat[\"Unorm8x4\"] = \"unorm8x4\";\n VertexFormat[\"Snorm8x2\"] = \"snorm8x2\";\n VertexFormat[\"Snorm8x4\"] = \"snorm8x4\";\n VertexFormat[\"Uint16x2\"] = \"uint16x2\";\n VertexFormat[\"Uint16x4\"] = \"uint16x4\";\n VertexFormat[\"Sint16x2\"] = \"sint16x2\";\n VertexFormat[\"Sint16x4\"] = \"sint16x4\";\n VertexFormat[\"Unorm16x2\"] = \"unorm16x2\";\n VertexFormat[\"Unorm16x4\"] = \"unorm16x4\";\n VertexFormat[\"Snorm16x2\"] = \"snorm16x2\";\n VertexFormat[\"Snorm16x4\"] = \"snorm16x4\";\n VertexFormat[\"Float16x2\"] = \"float16x2\";\n VertexFormat[\"Float16x4\"] = \"float16x4\";\n VertexFormat[\"Float32\"] = \"float32\";\n VertexFormat[\"Float32x2\"] = \"float32x2\";\n VertexFormat[\"Float32x3\"] = \"float32x3\";\n VertexFormat[\"Float32x4\"] = \"float32x4\";\n VertexFormat[\"Uint32\"] = \"uint32\";\n VertexFormat[\"Uint32x2\"] = \"uint32x2\";\n VertexFormat[\"Uint32x3\"] = \"uint32x3\";\n VertexFormat[\"Uint32x4\"] = \"uint32x4\";\n VertexFormat[\"Sint32\"] = \"sint32\";\n VertexFormat[\"Sint32x2\"] = \"sint32x2\";\n VertexFormat[\"Sint32x3\"] = \"sint32x3\";\n VertexFormat[\"Sint32x4\"] = \"sint32x4\";\n})(VertexFormat || (VertexFormat = {}));\n/** @internal */\nexport var InputStepMode;\n(function (InputStepMode) {\n InputStepMode[\"Vertex\"] = \"vertex\";\n InputStepMode[\"Instance\"] = \"instance\";\n})(InputStepMode || (InputStepMode = {}));\n/** @internal */\nexport var ComputePassTimestampLocation;\n(function (ComputePassTimestampLocation) {\n ComputePassTimestampLocation[\"Beginning\"] = \"beginning\";\n ComputePassTimestampLocation[\"End\"] = \"end\";\n})(ComputePassTimestampLocation || (ComputePassTimestampLocation = {}));\n/** @internal */\nexport var RenderPassTimestampLocation;\n(function (RenderPassTimestampLocation) {\n RenderPassTimestampLocation[\"Beginning\"] = \"beginning\";\n RenderPassTimestampLocation[\"End\"] = \"end\";\n})(RenderPassTimestampLocation || (RenderPassTimestampLocation = {}));\n/** @internal */\nexport var LoadOp;\n(function (LoadOp) {\n LoadOp[\"Load\"] = \"load\";\n LoadOp[\"Clear\"] = \"clear\";\n})(LoadOp || (LoadOp = {}));\n/** @internal */\nexport var StoreOp;\n(function (StoreOp) {\n StoreOp[\"Store\"] = \"store\";\n StoreOp[\"Discard\"] = \"discard\";\n})(StoreOp || (StoreOp = {}));\n/** @internal */\nexport var QueryType;\n(function (QueryType) {\n QueryType[\"Occlusion\"] = \"occlusion\";\n QueryType[\"Timestamp\"] = \"timestamp\";\n})(QueryType || (QueryType = {}));\n/** @internal */\nexport var CanvasAlphaMode;\n(function (CanvasAlphaMode) {\n CanvasAlphaMode[\"Opaque\"] = \"opaque\";\n CanvasAlphaMode[\"Premultiplied\"] = \"premultiplied\";\n})(CanvasAlphaMode || (CanvasAlphaMode = {}));\n/** @internal */\nexport var DeviceLostReason;\n(function (DeviceLostReason) {\n DeviceLostReason[\"Unknown\"] = \"unknown\";\n DeviceLostReason[\"Destroyed\"] = \"destroyed\";\n})(DeviceLostReason || (DeviceLostReason = {}));\n/** @internal */\nexport var ErrorFilter;\n(function (ErrorFilter) {\n ErrorFilter[\"Validation\"] = \"validation\";\n ErrorFilter[\"OutOfMemory\"] = \"out-of-memory\";\n ErrorFilter[\"Internal\"] = \"internal\";\n})(ErrorFilter || (ErrorFilter = {}));\n//# sourceMappingURL=webgpuConstants.js.map","import { ShaderLanguage } from \"../../Materials/shaderLanguage.js\";\nimport * as WebGPUConstants from \"./webgpuConstants.js\";\n/** @internal */\nexport class WebGPUShaderProcessor {\n constructor() {\n this.shaderLanguage = ShaderLanguage.GLSL;\n }\n _addUniformToLeftOverUBO(name, uniformType, preProcessors) {\n let length = 0;\n [name, uniformType, length] = this._getArraySize(name, uniformType, preProcessors);\n for (let i = 0; i < this._webgpuProcessingContext.leftOverUniforms.length; i++) {\n if (this._webgpuProcessingContext.leftOverUniforms[i].name === name) {\n return;\n }\n }\n this._webgpuProcessingContext.leftOverUniforms.push({\n name,\n type: uniformType,\n length,\n });\n }\n _buildLeftOverUBO() {\n if (!this._webgpuProcessingContext.leftOverUniforms.length) {\n return \"\";\n }\n const name = WebGPUShaderProcessor.LeftOvertUBOName;\n let availableUBO = this._webgpuProcessingContext.availableBuffers[name];\n if (!availableUBO) {\n availableUBO = {\n binding: this._webgpuProcessingContext.getNextFreeUBOBinding(),\n };\n this._webgpuProcessingContext.availableBuffers[name] = availableUBO;\n this._addBufferBindingDescription(name, availableUBO, WebGPUConstants.BufferBindingType.Uniform, true);\n this._addBufferBindingDescription(name, availableUBO, WebGPUConstants.BufferBindingType.Uniform, false);\n }\n return this._generateLeftOverUBOCode(name, availableUBO);\n }\n _collectBindingNames() {\n // collect all the binding names for faster processing in WebGPUCacheBindGroup\n for (let i = 0; i < this._webgpuProcessingContext.bindGroupLayoutEntries.length; i++) {\n const setDefinition = this._webgpuProcessingContext.bindGroupLayoutEntries[i];\n if (setDefinition === undefined) {\n this._webgpuProcessingContext.bindGroupLayoutEntries[i] = [];\n continue;\n }\n for (let j = 0; j < setDefinition.length; j++) {\n const entry = this._webgpuProcessingContext.bindGroupLayoutEntries[i][j];\n const name = this._webgpuProcessingContext.bindGroupLayoutEntryInfo[i][entry.binding].name;\n const nameInArrayOfTexture = this._webgpuProcessingContext.bindGroupLayoutEntryInfo[i][entry.binding].nameInArrayOfTexture;\n if (entry) {\n if (entry.texture || entry.externalTexture || entry.storageTexture) {\n this._webgpuProcessingContext.textureNames.push(nameInArrayOfTexture);\n }\n else if (entry.sampler) {\n this._webgpuProcessingContext.samplerNames.push(name);\n }\n else if (entry.buffer) {\n this._webgpuProcessingContext.bufferNames.push(name);\n }\n }\n }\n }\n }\n _preCreateBindGroupEntries() {\n const bindGroupEntries = this._webgpuProcessingContext.bindGroupEntries;\n for (let i = 0; i < this._webgpuProcessingContext.bindGroupLayoutEntries.length; i++) {\n const setDefinition = this._webgpuProcessingContext.bindGroupLayoutEntries[i];\n const entries = [];\n for (let j = 0; j < setDefinition.length; j++) {\n const entry = this._webgpuProcessingContext.bindGroupLayoutEntries[i][j];\n if (entry.sampler || entry.texture || entry.storageTexture || entry.externalTexture) {\n entries.push({\n binding: entry.binding,\n resource: undefined,\n });\n }\n else if (entry.buffer) {\n entries.push({\n binding: entry.binding,\n resource: {\n buffer: undefined,\n offset: 0,\n size: 0,\n },\n });\n }\n }\n bindGroupEntries[i] = entries;\n }\n }\n _addTextureBindingDescription(name, textureInfo, textureIndex, dimension, format, isVertex) {\n // eslint-disable-next-line prefer-const\n let { groupIndex, bindingIndex } = textureInfo.textures[textureIndex];\n if (!this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex]) {\n this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex] = [];\n this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex] = [];\n }\n if (!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex]) {\n let len;\n if (dimension === null) {\n len = this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex].push({\n binding: bindingIndex,\n visibility: 0,\n externalTexture: {},\n });\n }\n else if (format) {\n len = this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex].push({\n binding: bindingIndex,\n visibility: 0,\n storageTexture: {\n access: WebGPUConstants.StorageTextureAccess.WriteOnly,\n format,\n viewDimension: dimension,\n },\n });\n }\n else {\n len = this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex].push({\n binding: bindingIndex,\n visibility: 0,\n texture: {\n sampleType: textureInfo.sampleType,\n viewDimension: dimension,\n multisampled: false,\n },\n });\n }\n const textureName = textureInfo.isTextureArray ? name + textureIndex : name;\n this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex] = { name, index: len - 1, nameInArrayOfTexture: textureName };\n }\n bindingIndex = this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex].index;\n if (isVertex) {\n this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= WebGPUConstants.ShaderStage.Vertex;\n }\n else {\n this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= WebGPUConstants.ShaderStage.Fragment;\n }\n }\n _addSamplerBindingDescription(name, samplerInfo, isVertex) {\n // eslint-disable-next-line prefer-const\n let { groupIndex, bindingIndex } = samplerInfo.binding;\n if (!this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex]) {\n this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex] = [];\n this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex] = [];\n }\n if (!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex]) {\n const len = this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex].push({\n binding: bindingIndex,\n visibility: 0,\n sampler: {\n type: samplerInfo.type,\n },\n });\n this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex] = { name, index: len - 1 };\n }\n bindingIndex = this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex].index;\n if (isVertex) {\n this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= WebGPUConstants.ShaderStage.Vertex;\n }\n else {\n this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= WebGPUConstants.ShaderStage.Fragment;\n }\n }\n _addBufferBindingDescription(name, uniformBufferInfo, bufferType, isVertex) {\n // eslint-disable-next-line prefer-const\n let { groupIndex, bindingIndex } = uniformBufferInfo.binding;\n if (!this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex]) {\n this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex] = [];\n this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex] = [];\n }\n if (!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex]) {\n const len = this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex].push({\n binding: bindingIndex,\n visibility: 0,\n buffer: {\n type: bufferType,\n },\n });\n this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex] = { name, index: len - 1 };\n }\n bindingIndex = this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex].index;\n if (isVertex) {\n this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= WebGPUConstants.ShaderStage.Vertex;\n }\n else {\n this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= WebGPUConstants.ShaderStage.Fragment;\n }\n }\n _injectStartingAndEndingCode(code, mainFuncDecl, startingCode, endingCode) {\n let idx = code.indexOf(mainFuncDecl);\n if (idx < 0) {\n console.error(`No \"main\" function found in shader code! Processing aborted.`);\n return code;\n }\n if (startingCode) {\n // eslint-disable-next-line no-empty\n while (idx++ < code.length && code.charAt(idx) != \"{\") { }\n if (idx < code.length) {\n const part1 = code.substring(0, idx + 1);\n const part2 = code.substring(idx + 1);\n code = part1 + startingCode + part2;\n }\n }\n if (endingCode) {\n const lastClosingCurly = code.lastIndexOf(\"}\");\n code = code.substring(0, lastClosingCurly);\n code += endingCode + \"\\n}\";\n }\n return code;\n }\n}\nWebGPUShaderProcessor.AutoSamplerSuffix = \"Sampler\";\nWebGPUShaderProcessor.LeftOvertUBOName = \"LeftOver\";\nWebGPUShaderProcessor.InternalsUBOName = \"Internals\";\nWebGPUShaderProcessor.UniformSizes = {\n // GLSL types\n bool: 1,\n int: 1,\n float: 1,\n vec2: 2,\n ivec2: 2,\n vec3: 3,\n ivec3: 3,\n vec4: 4,\n ivec4: 4,\n mat2: 4,\n mat3: 12,\n mat4: 16,\n // WGSL types\n i32: 1,\n u32: 1,\n f32: 1,\n mat2x2: 4,\n mat3x3: 12,\n mat4x4: 16,\n};\n// eslint-disable-next-line @typescript-eslint/naming-convention\nWebGPUShaderProcessor._SamplerFunctionByWebGLSamplerType = {\n sampler2D: \"sampler2D\",\n sampler2DArray: \"sampler2DArray\",\n sampler2DShadow: \"sampler2DShadow\",\n sampler2DArrayShadow: \"sampler2DArrayShadow\",\n samplerCube: \"samplerCube\",\n sampler3D: \"sampler3D\",\n};\n// eslint-disable-next-line @typescript-eslint/naming-convention\nWebGPUShaderProcessor._TextureTypeByWebGLSamplerType = {\n sampler2D: \"texture2D\",\n sampler2DArray: \"texture2DArray\",\n sampler2DShadow: \"texture2D\",\n sampler2DArrayShadow: \"texture2DArray\",\n samplerCube: \"textureCube\",\n samplerCubeArray: \"textureCubeArray\",\n sampler3D: \"texture3D\",\n};\n// eslint-disable-next-line @typescript-eslint/naming-convention\nWebGPUShaderProcessor._GpuTextureViewDimensionByWebGPUTextureType = {\n textureCube: WebGPUConstants.TextureViewDimension.Cube,\n textureCubeArray: WebGPUConstants.TextureViewDimension.CubeArray,\n texture2D: WebGPUConstants.TextureViewDimension.E2d,\n texture2DArray: WebGPUConstants.TextureViewDimension.E2dArray,\n texture3D: WebGPUConstants.TextureViewDimension.E3d,\n};\n// if the webgl sampler type is not listed in this array, \"sampler\" is taken by default\n// eslint-disable-next-line @typescript-eslint/naming-convention\nWebGPUShaderProcessor._SamplerTypeByWebGLSamplerType = {\n sampler2DShadow: \"samplerShadow\",\n sampler2DArrayShadow: \"samplerShadow\",\n};\n// eslint-disable-next-line @typescript-eslint/naming-convention\nWebGPUShaderProcessor._IsComparisonSamplerByWebGPUSamplerType = {\n samplerShadow: true,\n samplerArrayShadow: true,\n sampler: false,\n};\n//# sourceMappingURL=webgpuShaderProcessor.js.map","import { UniformBuffer } from \"../../Materials/uniformBuffer.js\";\nimport { WebGPUShaderProcessor } from \"./webgpuShaderProcessor.js\";\n/** @internal */\nexport class WebGPUPipelineContext {\n get isAsync() {\n return false;\n }\n get isReady() {\n if (this.stages) {\n return true;\n }\n return false;\n }\n constructor(shaderProcessingContext, engine) {\n // The field is indexed by textureState. See @WebGPUMaterialContext.textureState for more information.\n this.bindGroupLayouts = {};\n this._name = \"unnamed\";\n this.shaderProcessingContext = shaderProcessingContext;\n this._leftOverUniformsByName = {};\n this.engine = engine;\n }\n _handlesSpectorRebuildCallback() {\n // Nothing to do yet for spector.\n }\n _fillEffectInformation(effect, uniformBuffersNames, uniformsNames, uniforms, samplerList, samplers, attributesNames, attributes) {\n const engine = this.engine;\n // Prevent Memory Leak by reducing the number of string, refer to the string instead of copy.\n effect._fragmentSourceCode = \"\";\n effect._vertexSourceCode = \"\";\n // this._fragmentSourceCodeOverride = \"\";\n // this._vertexSourceCodeOverride = \"\";\n const foundSamplers = this.shaderProcessingContext.availableTextures;\n let index;\n for (index = 0; index < samplerList.length; index++) {\n const name = samplerList[index];\n const sampler = foundSamplers[samplerList[index]];\n if (sampler == null || sampler == undefined) {\n samplerList.splice(index, 1);\n index--;\n }\n else {\n samplers[name] = index;\n }\n }\n for (const attr of engine.getAttributes(this, attributesNames)) {\n attributes.push(attr);\n }\n // Build the uniform layout for the left over uniforms.\n this.buildUniformLayout();\n const attributeNamesFromEffect = [];\n const attributeLocationsFromEffect = [];\n for (index = 0; index < attributesNames.length; index++) {\n const location = attributes[index];\n if (location >= 0) {\n attributeNamesFromEffect.push(attributesNames[index]);\n attributeLocationsFromEffect.push(location);\n }\n }\n this.shaderProcessingContext.attributeNamesFromEffect = attributeNamesFromEffect;\n this.shaderProcessingContext.attributeLocationsFromEffect = attributeLocationsFromEffect;\n }\n /** @internal */\n /**\n * Build the uniform buffer used in the material.\n */\n buildUniformLayout() {\n if (!this.shaderProcessingContext.leftOverUniforms.length) {\n return;\n }\n this.uniformBuffer = new UniformBuffer(this.engine, undefined, undefined, \"leftOver-\" + this._name);\n for (const leftOverUniform of this.shaderProcessingContext.leftOverUniforms) {\n const type = leftOverUniform.type.replace(/^(.*?)(<.*>)?$/, \"$1\");\n const size = WebGPUShaderProcessor.UniformSizes[type];\n this.uniformBuffer.addUniform(leftOverUniform.name, size, leftOverUniform.length);\n this._leftOverUniformsByName[leftOverUniform.name] = leftOverUniform.type;\n }\n this.uniformBuffer.create();\n }\n /**\n * Release all associated resources.\n **/\n dispose() {\n if (this.uniformBuffer) {\n this.uniformBuffer.dispose();\n }\n }\n /**\n * Sets an integer value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value Value to be set.\n */\n setInt(uniformName, value) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateInt(uniformName, value);\n }\n /**\n * Sets an int2 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First int in int2.\n * @param y Second int in int2.\n */\n setInt2(uniformName, x, y) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateInt2(uniformName, x, y);\n }\n /**\n * Sets an int3 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First int in int3.\n * @param y Second int in int3.\n * @param z Third int in int3.\n */\n setInt3(uniformName, x, y, z) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateInt3(uniformName, x, y, z);\n }\n /**\n * Sets an int4 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First int in int4.\n * @param y Second int in int4.\n * @param z Third int in int4.\n * @param w Fourth int in int4.\n */\n setInt4(uniformName, x, y, z, w) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateInt4(uniformName, x, y, z, w);\n }\n /**\n * Sets an int array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setIntArray(uniformName, array) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateIntArray(uniformName, array);\n }\n /**\n * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setIntArray2(uniformName, array) {\n this.setIntArray(uniformName, array);\n }\n /**\n * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setIntArray3(uniformName, array) {\n this.setIntArray(uniformName, array);\n }\n /**\n * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setIntArray4(uniformName, array) {\n this.setIntArray(uniformName, array);\n }\n /**\n * Sets an unsigned integer value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value Value to be set.\n */\n setUInt(uniformName, value) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateUInt(uniformName, value);\n }\n /**\n * Sets an unsigned int2 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First unsigned int in uint2.\n * @param y Second unsigned int in uint2.\n */\n setUInt2(uniformName, x, y) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateUInt2(uniformName, x, y);\n }\n /**\n * Sets an unsigned int3 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First unsigned int in uint3.\n * @param y Second unsigned int in uint3.\n * @param z Third unsigned int in uint3.\n */\n setUInt3(uniformName, x, y, z) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateUInt3(uniformName, x, y, z);\n }\n /**\n * Sets an unsigned int4 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First unsigned int in uint4.\n * @param y Second unsigned int in uint4.\n * @param z Third unsigned int in uint4.\n * @param w Fourth unsigned int in uint4.\n */\n setUInt4(uniformName, x, y, z, w) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateUInt4(uniformName, x, y, z, w);\n }\n /**\n * Sets an unsigned int array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setUIntArray(uniformName, array) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateUIntArray(uniformName, array);\n }\n /**\n * Sets an unsigned int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setUIntArray2(uniformName, array) {\n this.setUIntArray(uniformName, array);\n }\n /**\n * Sets an unsigned int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setUIntArray3(uniformName, array) {\n this.setUIntArray(uniformName, array);\n }\n /**\n * Sets an unsigned int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setUIntArray4(uniformName, array) {\n this.setUIntArray(uniformName, array);\n }\n /**\n * Sets an array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setArray(uniformName, array) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateArray(uniformName, array);\n }\n /**\n * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setArray2(uniformName, array) {\n this.setArray(uniformName, array);\n }\n /**\n * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setArray3(uniformName, array) {\n this.setArray(uniformName, array);\n }\n /**\n * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setArray4(uniformName, array) {\n this.setArray(uniformName, array);\n }\n /**\n * Sets matrices on a uniform variable.\n * @param uniformName Name of the variable.\n * @param matrices matrices to be set.\n */\n setMatrices(uniformName, matrices) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateMatrices(uniformName, matrices);\n }\n /**\n * Sets matrix on a uniform variable.\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n */\n setMatrix(uniformName, matrix) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateMatrix(uniformName, matrix);\n }\n /**\n * Sets a 3x3 matrix on a uniform variable. (Specified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n */\n setMatrix3x3(uniformName, matrix) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateMatrix3x3(uniformName, matrix);\n }\n /**\n * Sets a 2x2 matrix on a uniform variable. (Specified as [1,2,3,4] will result in [1,2][3,4] matrix)\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n */\n setMatrix2x2(uniformName, matrix) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateMatrix2x2(uniformName, matrix);\n }\n /**\n * Sets a float on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value value to be set.\n * @returns this effect.\n */\n setFloat(uniformName, value) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateFloat(uniformName, value);\n }\n /**\n * Sets a Vector2 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector2 vector2 to be set.\n */\n setVector2(uniformName, vector2) {\n this.setFloat2(uniformName, vector2.x, vector2.y);\n }\n /**\n * Sets a float2 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float2.\n * @param y Second float in float2.\n */\n setFloat2(uniformName, x, y) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateFloat2(uniformName, x, y);\n }\n /**\n * Sets a Vector3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector3 Value to be set.\n */\n setVector3(uniformName, vector3) {\n this.setFloat3(uniformName, vector3.x, vector3.y, vector3.z);\n }\n /**\n * Sets a float3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float3.\n * @param y Second float in float3.\n * @param z Third float in float3.\n */\n setFloat3(uniformName, x, y, z) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateFloat3(uniformName, x, y, z);\n }\n /**\n * Sets a Vector4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector4 Value to be set.\n */\n setVector4(uniformName, vector4) {\n this.setFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);\n }\n /**\n * Sets a Quaternion on a uniform variable.\n * @param uniformName Name of the variable.\n * @param quaternion Value to be set.\n */\n setQuaternion(uniformName, quaternion) {\n this.setFloat4(uniformName, quaternion.x, quaternion.y, quaternion.z, quaternion.w);\n }\n /**\n * Sets a float4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float4.\n * @param y Second float in float4.\n * @param z Third float in float4.\n * @param w Fourth float in float4.\n * @returns this effect.\n */\n setFloat4(uniformName, x, y, z, w) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateFloat4(uniformName, x, y, z, w);\n }\n /**\n * Sets a Color3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param color3 Value to be set.\n */\n setColor3(uniformName, color3) {\n this.setFloat3(uniformName, color3.r, color3.g, color3.b);\n }\n /**\n * Sets a Color4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param color3 Value to be set.\n * @param alpha Alpha value to be set.\n */\n setColor4(uniformName, color3, alpha) {\n this.setFloat4(uniformName, color3.r, color3.g, color3.b, alpha);\n }\n /**\n * Sets a Color4 on a uniform variable\n * @param uniformName defines the name of the variable\n * @param color4 defines the value to be set\n */\n setDirectColor4(uniformName, color4) {\n this.setFloat4(uniformName, color4.r, color4.g, color4.b, color4.a);\n }\n _getVertexShaderCode() {\n var _a;\n return (_a = this.sources) === null || _a === void 0 ? void 0 : _a.vertex;\n }\n _getFragmentShaderCode() {\n var _a;\n return (_a = this.sources) === null || _a === void 0 ? void 0 : _a.fragment;\n }\n}\n//# sourceMappingURL=webgpuPipelineContext.js.map","const _maxGroups = 4;\nconst _maxBindingsPerGroup = 1 << 16;\n// all types not listed are assumed to consume 1 location\nconst _typeToLocationSize = {\n // GLSL types\n mat2: 2,\n mat3: 3,\n mat4: 4,\n // WGSL types\n mat2x2: 2,\n mat3x3: 3,\n mat4x4: 4,\n};\n/**\n * @internal\n */\nexport class WebGPUShaderProcessingContext {\n static get KnownUBOs() {\n return WebGPUShaderProcessingContext._SimplifiedKnownBindings ? WebGPUShaderProcessingContext._SimplifiedKnownUBOs : WebGPUShaderProcessingContext._KnownUBOs;\n }\n constructor(shaderLanguage) {\n this.shaderLanguage = shaderLanguage;\n this._attributeNextLocation = 0;\n this._varyingNextLocation = 0;\n this.freeGroupIndex = 0;\n this.freeBindingIndex = 0;\n this.availableVaryings = {};\n this.availableAttributes = {};\n this.availableBuffers = {};\n this.availableTextures = {};\n this.availableSamplers = {};\n this.orderedAttributes = [];\n this.bindGroupLayoutEntries = [];\n this.bindGroupLayoutEntryInfo = [];\n this.bindGroupEntries = [];\n this.bufferNames = [];\n this.textureNames = [];\n this.samplerNames = [];\n this.leftOverUniforms = [];\n this._findStartingGroupBinding();\n }\n _findStartingGroupBinding() {\n const knownUBOs = WebGPUShaderProcessingContext.KnownUBOs;\n const groups = [];\n for (const name in knownUBOs) {\n const binding = knownUBOs[name].binding;\n if (binding.groupIndex === -1) {\n continue;\n }\n if (groups[binding.groupIndex] === undefined) {\n groups[binding.groupIndex] = binding.bindingIndex;\n }\n else {\n groups[binding.groupIndex] = Math.max(groups[binding.groupIndex], binding.bindingIndex);\n }\n }\n this.freeGroupIndex = groups.length - 1;\n if (this.freeGroupIndex === 0) {\n this.freeGroupIndex++;\n this.freeBindingIndex = 0;\n }\n else {\n this.freeBindingIndex = groups[groups.length - 1] + 1;\n }\n }\n getAttributeNextLocation(dataType, arrayLength = 0) {\n var _a;\n const index = this._attributeNextLocation;\n this._attributeNextLocation += ((_a = _typeToLocationSize[dataType]) !== null && _a !== void 0 ? _a : 1) * (arrayLength || 1);\n return index;\n }\n getVaryingNextLocation(dataType, arrayLength = 0) {\n var _a;\n const index = this._varyingNextLocation;\n this._varyingNextLocation += ((_a = _typeToLocationSize[dataType]) !== null && _a !== void 0 ? _a : 1) * (arrayLength || 1);\n return index;\n }\n getNextFreeUBOBinding() {\n return this._getNextFreeBinding(1);\n }\n _getNextFreeBinding(bindingCount) {\n if (this.freeBindingIndex > _maxBindingsPerGroup - bindingCount) {\n this.freeGroupIndex++;\n this.freeBindingIndex = 0;\n }\n if (this.freeGroupIndex === _maxGroups) {\n throw \"Too many textures or UBOs have been declared and it is not supported in WebGPU.\";\n }\n const returnValue = {\n groupIndex: this.freeGroupIndex,\n bindingIndex: this.freeBindingIndex,\n };\n this.freeBindingIndex += bindingCount;\n return returnValue;\n }\n}\n/** @internal */\nWebGPUShaderProcessingContext._SimplifiedKnownBindings = true; // if true, use only group=0,binding=0 as a known group/binding for the Scene ubo and use group=1,binding=X for all other bindings\n// if false, see _KnownUBOs for the known groups/bindings used\nWebGPUShaderProcessingContext._SimplifiedKnownUBOs = {\n Scene: { binding: { groupIndex: 0, bindingIndex: 0 } },\n Light0: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light1: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light2: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light3: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light4: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light5: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light6: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light7: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light8: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light9: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light10: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light11: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light12: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light13: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light14: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light15: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light16: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light17: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light18: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light19: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light20: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light21: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light22: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light23: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light24: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light25: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light26: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light27: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light28: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light29: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light30: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light31: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Material: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Mesh: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Internals: { binding: { groupIndex: -1, bindingIndex: -1 } },\n};\nWebGPUShaderProcessingContext._KnownUBOs = {\n Scene: { binding: { groupIndex: 0, bindingIndex: 0 } },\n Light0: { binding: { groupIndex: 1, bindingIndex: 0 } },\n Light1: { binding: { groupIndex: 1, bindingIndex: 1 } },\n Light2: { binding: { groupIndex: 1, bindingIndex: 2 } },\n Light3: { binding: { groupIndex: 1, bindingIndex: 3 } },\n Light4: { binding: { groupIndex: 1, bindingIndex: 4 } },\n Light5: { binding: { groupIndex: 1, bindingIndex: 5 } },\n Light6: { binding: { groupIndex: 1, bindingIndex: 6 } },\n Light7: { binding: { groupIndex: 1, bindingIndex: 7 } },\n Light8: { binding: { groupIndex: 1, bindingIndex: 8 } },\n Light9: { binding: { groupIndex: 1, bindingIndex: 9 } },\n Light10: { binding: { groupIndex: 1, bindingIndex: 10 } },\n Light11: { binding: { groupIndex: 1, bindingIndex: 11 } },\n Light12: { binding: { groupIndex: 1, bindingIndex: 12 } },\n Light13: { binding: { groupIndex: 1, bindingIndex: 13 } },\n Light14: { binding: { groupIndex: 1, bindingIndex: 14 } },\n Light15: { binding: { groupIndex: 1, bindingIndex: 15 } },\n Light16: { binding: { groupIndex: 1, bindingIndex: 16 } },\n Light17: { binding: { groupIndex: 1, bindingIndex: 17 } },\n Light18: { binding: { groupIndex: 1, bindingIndex: 18 } },\n Light19: { binding: { groupIndex: 1, bindingIndex: 19 } },\n Light20: { binding: { groupIndex: 1, bindingIndex: 20 } },\n Light21: { binding: { groupIndex: 1, bindingIndex: 21 } },\n Light22: { binding: { groupIndex: 1, bindingIndex: 22 } },\n Light23: { binding: { groupIndex: 1, bindingIndex: 23 } },\n Light24: { binding: { groupIndex: 1, bindingIndex: 24 } },\n Light25: { binding: { groupIndex: 1, bindingIndex: 25 } },\n Light26: { binding: { groupIndex: 1, bindingIndex: 26 } },\n Light27: { binding: { groupIndex: 1, bindingIndex: 27 } },\n Light28: { binding: { groupIndex: 1, bindingIndex: 28 } },\n Light29: { binding: { groupIndex: 1, bindingIndex: 29 } },\n Light30: { binding: { groupIndex: 1, bindingIndex: 30 } },\n Light31: { binding: { groupIndex: 1, bindingIndex: 31 } },\n Material: { binding: { groupIndex: 2, bindingIndex: 0 } },\n Mesh: { binding: { groupIndex: 2, bindingIndex: 1 } },\n Internals: { binding: { groupIndex: 2, bindingIndex: 2 } },\n};\n//# sourceMappingURL=webgpuShaderProcessingContext.js.map","import { WebGPUShaderProcessingContext } from \"./webgpuShaderProcessingContext.js\";\nimport * as WebGPUConstants from \"./webgpuConstants.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { WebGPUShaderProcessor } from \"./webgpuShaderProcessor.js\";\nimport { ShaderLanguage } from \"../../Materials/shaderLanguage.js\";\n/** @internal */\nexport class WebGPUShaderProcessorGLSL extends WebGPUShaderProcessor {\n constructor() {\n super(...arguments);\n this._missingVaryings = [];\n this._textureArrayProcessing = [];\n this._vertexIsGLES3 = false;\n this._fragmentIsGLES3 = false;\n this.shaderLanguage = ShaderLanguage.GLSL;\n this.parseGLES3 = true;\n }\n _getArraySize(name, type, preProcessors) {\n let length = 0;\n const startArray = name.indexOf(\"[\");\n const endArray = name.indexOf(\"]\");\n if (startArray > 0 && endArray > 0) {\n const lengthInString = name.substring(startArray + 1, endArray);\n length = +lengthInString;\n if (isNaN(length)) {\n length = +preProcessors[lengthInString.trim()];\n }\n name = name.substr(0, startArray);\n }\n return [name, type, length];\n }\n initializeShaders(processingContext) {\n this._webgpuProcessingContext = processingContext;\n this._missingVaryings.length = 0;\n this._textureArrayProcessing.length = 0;\n this.attributeKeywordName = undefined;\n this.varyingVertexKeywordName = undefined;\n this.varyingFragmentKeywordName = undefined;\n }\n preProcessShaderCode(code, isFragment) {\n const ubDeclaration = `// Internals UBO\\r\\nuniform ${WebGPUShaderProcessor.InternalsUBOName} {\\nfloat yFactor_;\\nfloat textureOutputHeight_;\\n};\\n`;\n const alreadyInjected = code.indexOf(\"// Internals UBO\") !== -1;\n if (isFragment) {\n this._fragmentIsGLES3 = code.indexOf(\"#version 3\") !== -1;\n if (this._fragmentIsGLES3) {\n this.varyingFragmentKeywordName = \"in\";\n }\n return alreadyInjected ? code : ubDeclaration + \"##INJECTCODE##\\n\" + code;\n }\n this._vertexIsGLES3 = code.indexOf(\"#version 3\") !== -1;\n if (this._vertexIsGLES3) {\n this.attributeKeywordName = \"in\";\n this.varyingVertexKeywordName = \"out\";\n }\n return alreadyInjected ? code : ubDeclaration + code;\n }\n varyingCheck(varying, isFragment) {\n const outRegex = /(flat\\s)?\\s*out/;\n const inRegex = /(flat\\s)?\\s*in/;\n const varyingRegex = /(flat\\s)?\\s*varying/;\n const regex = isFragment && this._fragmentIsGLES3 ? inRegex : !isFragment && this._vertexIsGLES3 ? outRegex : varyingRegex;\n return regex.test(varying);\n }\n varyingProcessor(varying, isFragment, preProcessors) {\n var _a;\n this._preProcessors = preProcessors;\n const outRegex = /\\s*(flat)?\\s*out\\s+(?:(?:highp)?|(?:lowp)?)\\s*(\\S+)\\s+(\\S+)\\s*;/gm;\n const inRegex = /\\s*(flat)?\\s*in\\s+(?:(?:highp)?|(?:lowp)?)\\s*(\\S+)\\s+(\\S+)\\s*;/gm;\n const varyingRegex = /\\s*(flat)?\\s*varying\\s+(?:(?:highp)?|(?:lowp)?)\\s*(\\S+)\\s+(\\S+)\\s*;/gm;\n const regex = isFragment && this._fragmentIsGLES3 ? inRegex : !isFragment && this._vertexIsGLES3 ? outRegex : varyingRegex;\n const match = regex.exec(varying);\n if (match !== null) {\n const interpolationQualifier = (_a = match[1]) !== null && _a !== void 0 ? _a : \"\";\n const varyingType = match[2];\n const name = match[3];\n let location;\n if (isFragment) {\n location = this._webgpuProcessingContext.availableVaryings[name];\n this._missingVaryings[location] = \"\";\n if (location === undefined) {\n Logger.Warn(`Invalid fragment shader: The varying named \"${name}\" is not declared in the vertex shader! This declaration will be ignored.`);\n }\n }\n else {\n location = this._webgpuProcessingContext.getVaryingNextLocation(varyingType, this._getArraySize(name, varyingType, preProcessors)[2]);\n this._webgpuProcessingContext.availableVaryings[name] = location;\n this._missingVaryings[location] = `layout(location = ${location}) ${interpolationQualifier} in ${varyingType} ${name};`;\n }\n varying = varying.replace(match[0], location === undefined ? \"\" : `layout(location = ${location}) ${interpolationQualifier} ${isFragment ? \"in\" : \"out\"} ${varyingType} ${name};`);\n }\n return varying;\n }\n attributeProcessor(attribute, preProcessors) {\n this._preProcessors = preProcessors;\n const inRegex = /\\s*in\\s+(\\S+)\\s+(\\S+)\\s*;/gm;\n const attribRegex = /\\s*attribute\\s+(\\S+)\\s+(\\S+)\\s*;/gm;\n const regex = this._vertexIsGLES3 ? inRegex : attribRegex;\n const match = regex.exec(attribute);\n if (match !== null) {\n const attributeType = match[1];\n const name = match[2];\n const location = this._webgpuProcessingContext.getAttributeNextLocation(attributeType, this._getArraySize(name, attributeType, preProcessors)[2]);\n this._webgpuProcessingContext.availableAttributes[name] = location;\n this._webgpuProcessingContext.orderedAttributes[location] = name;\n attribute = attribute.replace(match[0], `layout(location = ${location}) in ${attributeType} ${name};`);\n }\n return attribute;\n }\n uniformProcessor(uniform, isFragment, preProcessors) {\n var _a;\n this._preProcessors = preProcessors;\n const uniformRegex = /\\s*uniform\\s+(?:(?:highp)?|(?:lowp)?)\\s*(\\S+)\\s+(\\S+)\\s*;/gm;\n const match = uniformRegex.exec(uniform);\n if (match !== null) {\n let uniformType = match[1];\n let name = match[2];\n if (uniformType.indexOf(\"sampler\") === 0 || uniformType.indexOf(\"sampler\") === 1) {\n let arraySize = 0; // 0 means the texture is not declared as an array\n [name, uniformType, arraySize] = this._getArraySize(name, uniformType, preProcessors);\n let textureInfo = this._webgpuProcessingContext.availableTextures[name];\n if (!textureInfo) {\n textureInfo = {\n autoBindSampler: true,\n isTextureArray: arraySize > 0,\n isStorageTexture: false,\n textures: [],\n sampleType: WebGPUConstants.TextureSampleType.Float,\n };\n for (let i = 0; i < (arraySize || 1); ++i) {\n textureInfo.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding());\n }\n }\n const samplerType = (_a = WebGPUShaderProcessor._SamplerTypeByWebGLSamplerType[uniformType]) !== null && _a !== void 0 ? _a : \"sampler\";\n const isComparisonSampler = !!WebGPUShaderProcessor._IsComparisonSamplerByWebGPUSamplerType[samplerType];\n const samplerBindingType = isComparisonSampler ? WebGPUConstants.SamplerBindingType.Comparison : WebGPUConstants.SamplerBindingType.Filtering;\n const samplerName = name + WebGPUShaderProcessor.AutoSamplerSuffix;\n let samplerInfo = this._webgpuProcessingContext.availableSamplers[samplerName];\n if (!samplerInfo) {\n samplerInfo = {\n binding: this._webgpuProcessingContext.getNextFreeUBOBinding(),\n type: samplerBindingType,\n };\n }\n const componentType = uniformType.charAt(0) === \"u\" ? \"u\" : uniformType.charAt(0) === \"i\" ? \"i\" : \"\";\n if (componentType) {\n uniformType = uniformType.substr(1);\n }\n const sampleType = isComparisonSampler\n ? WebGPUConstants.TextureSampleType.Depth\n : componentType === \"u\"\n ? WebGPUConstants.TextureSampleType.Uint\n : componentType === \"i\"\n ? WebGPUConstants.TextureSampleType.Sint\n : WebGPUConstants.TextureSampleType.Float;\n textureInfo.sampleType = sampleType;\n const isTextureArray = arraySize > 0;\n const samplerGroupIndex = samplerInfo.binding.groupIndex;\n const samplerBindingIndex = samplerInfo.binding.bindingIndex;\n const samplerFunction = WebGPUShaderProcessor._SamplerFunctionByWebGLSamplerType[uniformType];\n const textureType = WebGPUShaderProcessor._TextureTypeByWebGLSamplerType[uniformType];\n const textureDimension = WebGPUShaderProcessor._GpuTextureViewDimensionByWebGPUTextureType[textureType];\n // Manage textures and samplers.\n if (!isTextureArray) {\n arraySize = 1;\n uniform = `layout(set = ${samplerGroupIndex}, binding = ${samplerBindingIndex}) uniform ${componentType}${samplerType} ${samplerName};\r\n layout(set = ${textureInfo.textures[0].groupIndex}, binding = ${textureInfo.textures[0].bindingIndex}) uniform ${textureType} ${name}Texture;\r\n #define ${name} ${componentType}${samplerFunction}(${name}Texture, ${samplerName})`;\n }\n else {\n const layouts = [];\n layouts.push(`layout(set = ${samplerGroupIndex}, binding = ${samplerBindingIndex}) uniform ${componentType}${samplerType} ${samplerName};`);\n uniform = `\\r\\n`;\n for (let i = 0; i < arraySize; ++i) {\n const textureSetIndex = textureInfo.textures[i].groupIndex;\n const textureBindingIndex = textureInfo.textures[i].bindingIndex;\n layouts.push(`layout(set = ${textureSetIndex}, binding = ${textureBindingIndex}) uniform ${textureType} ${name}Texture${i};`);\n uniform += `${i > 0 ? \"\\r\\n\" : \"\"}#define ${name}${i} ${componentType}${samplerFunction}(${name}Texture${i}, ${samplerName})`;\n }\n uniform = layouts.join(\"\\r\\n\") + uniform;\n this._textureArrayProcessing.push(name);\n }\n this._webgpuProcessingContext.availableTextures[name] = textureInfo;\n this._webgpuProcessingContext.availableSamplers[samplerName] = samplerInfo;\n this._addSamplerBindingDescription(samplerName, samplerInfo, !isFragment);\n for (let i = 0; i < arraySize; ++i) {\n this._addTextureBindingDescription(name, textureInfo, i, textureDimension, null, !isFragment);\n }\n }\n else {\n this._addUniformToLeftOverUBO(name, uniformType, preProcessors);\n uniform = \"\";\n }\n }\n return uniform;\n }\n uniformBufferProcessor(uniformBuffer, isFragment) {\n const uboRegex = /uniform\\s+(\\w+)/gm;\n const match = uboRegex.exec(uniformBuffer);\n if (match !== null) {\n const name = match[1];\n let uniformBufferInfo = this._webgpuProcessingContext.availableBuffers[name];\n if (!uniformBufferInfo) {\n const knownUBO = WebGPUShaderProcessingContext.KnownUBOs[name];\n let binding;\n if (knownUBO && knownUBO.binding.groupIndex !== -1) {\n binding = knownUBO.binding;\n }\n else {\n binding = this._webgpuProcessingContext.getNextFreeUBOBinding();\n }\n uniformBufferInfo = { binding };\n this._webgpuProcessingContext.availableBuffers[name] = uniformBufferInfo;\n }\n this._addBufferBindingDescription(name, uniformBufferInfo, WebGPUConstants.BufferBindingType.Uniform, !isFragment);\n uniformBuffer = uniformBuffer.replace(\"uniform\", `layout(set = ${uniformBufferInfo.binding.groupIndex}, binding = ${uniformBufferInfo.binding.bindingIndex}) uniform`);\n }\n return uniformBuffer;\n }\n postProcessor(code, defines, isFragment, processingContext, engine) {\n const hasDrawBuffersExtension = code.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;\n // Remove extensions\n const regex = /#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;\n code = code.replace(regex, \"\");\n // Replace instructions\n code = code.replace(/texture2D\\s*\\(/g, \"texture(\");\n if (isFragment) {\n const hasFragCoord = code.indexOf(\"gl_FragCoord\") >= 0;\n const fragCoordCode = `\r\n glFragCoord_ = gl_FragCoord;\r\n if (yFactor_ == 1.) {\r\n glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y;\r\n }\r\n `;\n const injectCode = hasFragCoord ? \"vec4 glFragCoord_;\\n\" : \"\";\n code = code.replace(/texture2DLodEXT\\s*\\(/g, \"textureLod(\");\n code = code.replace(/textureCubeLodEXT\\s*\\(/g, \"textureLod(\");\n code = code.replace(/textureCube\\s*\\(/g, \"texture(\");\n code = code.replace(/gl_FragDepthEXT/g, \"gl_FragDepth\");\n code = code.replace(/gl_FragColor/g, \"glFragColor\");\n code = code.replace(/gl_FragData/g, \"glFragData\");\n code = code.replace(/gl_FragCoord/g, \"glFragCoord_\");\n if (!this._fragmentIsGLES3) {\n code = code.replace(/void\\s+?main\\s*\\(/g, (hasDrawBuffersExtension ? \"\" : \"layout(location = 0) out vec4 glFragColor;\\n\") + \"void main(\");\n }\n else {\n const match = /^\\s*out\\s+\\S+\\s+\\S+\\s*;/gm.exec(code);\n if (match !== null) {\n code = code.substring(0, match.index) + \"layout(location = 0) \" + code.substring(match.index);\n }\n }\n code = code.replace(/dFdy/g, \"(-yFactor_)*dFdy\"); // will also handle dFdyCoarse and dFdyFine\n code = code.replace(\"##INJECTCODE##\", injectCode);\n if (hasFragCoord) {\n code = this._injectStartingAndEndingCode(code, \"void main\", fragCoordCode);\n }\n }\n else {\n code = code.replace(/gl_InstanceID/g, \"gl_InstanceIndex\");\n code = code.replace(/gl_VertexID/g, \"gl_VertexIndex\");\n const hasMultiviewExtension = defines.indexOf(\"#define MULTIVIEW\") !== -1;\n if (hasMultiviewExtension) {\n return \"#extension GL_OVR_multiview2 : require\\nlayout (num_views = 2) in;\\n\" + code;\n }\n }\n // Flip Y + convert z range from [-1,1] to [0,1]\n if (!isFragment) {\n const lastClosingCurly = code.lastIndexOf(\"}\");\n code = code.substring(0, lastClosingCurly);\n code += \"gl_Position.y *= yFactor_;\\n\";\n if (!engine.isNDCHalfZRange) {\n code += \"gl_Position.z = (gl_Position.z + gl_Position.w) / 2.0;\\n\";\n }\n code += \"}\";\n }\n return code;\n }\n _applyTextureArrayProcessing(code, name) {\n // Replaces the occurrences of name[XX] by nameXX\n const regex = new RegExp(name + \"\\\\s*\\\\[(.+)?\\\\]\", \"gm\");\n let match = regex.exec(code);\n while (match !== null) {\n const index = match[1];\n let iindex = +index;\n if (this._preProcessors && isNaN(iindex)) {\n iindex = +this._preProcessors[index.trim()];\n }\n code = code.replace(match[0], name + iindex);\n match = regex.exec(code);\n }\n return code;\n }\n _generateLeftOverUBOCode(name, uniformBufferDescription) {\n let ubo = `layout(set = ${uniformBufferDescription.binding.groupIndex}, binding = ${uniformBufferDescription.binding.bindingIndex}) uniform ${name} {\\n `;\n for (const leftOverUniform of this._webgpuProcessingContext.leftOverUniforms) {\n if (leftOverUniform.length > 0) {\n ubo += ` ${leftOverUniform.type} ${leftOverUniform.name}[${leftOverUniform.length}];\\n`;\n }\n else {\n ubo += ` ${leftOverUniform.type} ${leftOverUniform.name};\\n`;\n }\n }\n ubo += \"};\\n\\n\";\n return ubo;\n }\n finalizeShaders(vertexCode, fragmentCode) {\n // make replacements for texture names in the texture array case\n for (let i = 0; i < this._textureArrayProcessing.length; ++i) {\n const name = this._textureArrayProcessing[i];\n vertexCode = this._applyTextureArrayProcessing(vertexCode, name);\n fragmentCode = this._applyTextureArrayProcessing(fragmentCode, name);\n }\n // inject the missing varying in the fragment shader\n for (let i = 0; i < this._missingVaryings.length; ++i) {\n const decl = this._missingVaryings[i];\n if (decl && decl.length > 0) {\n fragmentCode = decl + \"\\n\" + fragmentCode;\n }\n }\n // Builds the leftover UBOs.\n const leftOverUBO = this._buildLeftOverUBO();\n vertexCode = leftOverUBO + vertexCode;\n fragmentCode = leftOverUBO + fragmentCode;\n this._collectBindingNames();\n this._preCreateBindGroupEntries();\n this._preProcessors = null;\n return { vertexCode, fragmentCode };\n }\n}\n//# sourceMappingURL=webgpuShaderProcessorsGLSL.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"bonesDeclaration\";\nconst shader = `#if NUM_BONE_INFLUENCERS>0\nattribute matricesIndices : vec4;\rattribute matricesWeights : vec4;\r#if NUM_BONE_INFLUENCERS>4\nattribute matricesIndicesExtra : vec4;\rattribute matricesWeightsExtra : vec4;\r#endif\n#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#ifdef BONETEXTURE\nvar boneSampler : texture_2d;\runiform boneTextureWidth : f32;\r#else\nuniform mBones : array;\r#ifdef BONES_VELOCITY_ENABLED\nuniform mPreviousBones : array;\r#endif\n#endif\n#ifdef BONETEXTURE\nfn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4\r{\rlet offset=i32(index) *4; \rlet m0=textureLoad(smp,vec2(offset+0,0),0);\rlet m1=textureLoad(smp,vec2(offset+1,0),0);\rlet m2=textureLoad(smp,vec2(offset+2,0),0);\rlet m3=textureLoad(smp,vec2(offset+3,0),0);\rreturn mat4x4(m0,m1,m2,m3);\r}\r#endif\n#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const bonesDeclaration = { name, shader };\n//# sourceMappingURL=bonesDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"bonesVertex\";\nconst shader = `#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#if NUM_BONE_INFLUENCERS>0\nvar influence : mat4x4;\r#ifdef BONETEXTURE\ninfluence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0];\r#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1];\r#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2];\r#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3];\r#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0];\r#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1];\r#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2];\r#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3];\r#endif \n#else \ninfluence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0];\r#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1];\r#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2];\r#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3];\r#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0];\r#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1];\r#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2];\r#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3];\r#endif \n#endif\nfinalWorld=finalWorld*influence;\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const bonesVertex = { name, shader };\n//# sourceMappingURL=bonesVertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"bakedVertexAnimationDeclaration\";\nconst shader = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\nuniform bakedVertexAnimationTime: f32;\runiform bakedVertexAnimationTextureSizeInverted: vec2;\runiform bakedVertexAnimationSettings: vec4;\rvar bakedVertexAnimationTexture : texture_2d;\r#ifdef INSTANCES\nattribute bakedVertexAnimationSettingsInstanced : vec4;\r#endif\nfn readMatrixFromRawSamplerVAT(smp : texture_2d,index : f32,frame : f32)->mat4x4\r{\rlet offset=i32(index)*4;\rlet frameUV=i32(frame);\rlet m0=textureLoad(smp,vec2(offset+0,frameUV),0);\rlet m1=textureLoad(smp,vec2(offset+1,frameUV),0);\rlet m2=textureLoad(smp,vec2(offset+2,frameUV),0);\rlet m3=textureLoad(smp,vec2(offset+3,frameUV),0);\rreturn mat4x4(m0,m1,m2,m3);\r}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const bakedVertexAnimationDeclaration = { name, shader };\n//# sourceMappingURL=bakedVertexAnimationDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"bakedVertexAnimation\";\nconst shader = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\n{\r#ifdef INSTANCES\nlet VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;\rlet VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;\rlet VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;\rlet VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w;\r#else\nlet VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;\rlet VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;\rlet VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;\rlet VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w;\r#endif\nlet totalFrames: f32=VATEndFrame-VATStartFrame+1.0;\rlet time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;\rlet frameCorrection: f32=select(1.0,0.0,time<1.0);\rlet numOfFrames: f32=totalFrames-frameCorrection;\rvar VATFrameNum: f32=fract(time)*numOfFrames;\rVATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;\rVATFrameNum=floor(VATFrameNum);\rVATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;\rvar VATInfluence : mat4x4;\rVATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0];\r#if NUM_BONE_INFLUENCERS>1\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1];\r#endif\n#if NUM_BONE_INFLUENCERS>2\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2];\r#endif\n#if NUM_BONE_INFLUENCERS>3\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3];\r#endif\n#if NUM_BONE_INFLUENCERS>4\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0];\r#endif\n#if NUM_BONE_INFLUENCERS>5\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1];\r#endif\n#if NUM_BONE_INFLUENCERS>6\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2];\r#endif\n#if NUM_BONE_INFLUENCERS>7\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3];\r#endif\nfinalWorld=finalWorld*VATInfluence;\r}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const bakedVertexAnimation = { name, shader };\n//# sourceMappingURL=bakedVertexAnimation.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"clipPlaneFragment\";\nconst shader = `#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nif (false) {}\r#endif\n#ifdef CLIPPLANE\nelse if (fragmentInputs.fClipDistance>0.0)\r{\rdiscard;\r}\r#endif\n#ifdef CLIPPLANE2\nelse if (fragmentInputs.fClipDistance2>0.0)\r{\rdiscard;\r}\r#endif\n#ifdef CLIPPLANE3\nelse if (fragmentInputs.fClipDistance3>0.0)\r{\rdiscard;\r}\r#endif\n#ifdef CLIPPLANE4\nelse if (fragmentInputs.fClipDistance4>0.0)\r{\rdiscard;\r}\r#endif\n#ifdef CLIPPLANE5\nelse if (fragmentInputs.fClipDistance5>0.0)\r{\rdiscard;\r}\r#endif\n#ifdef CLIPPLANE6\nelse if (fragmentInputs.fClipDistance6>0.0)\r{\rdiscard;\r}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const clipPlaneFragment = { name, shader };\n//# sourceMappingURL=clipPlaneFragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"clipPlaneFragmentDeclaration\";\nconst shader = `#ifdef CLIPPLANE\nvarying fClipDistance: f32;\r#endif\n#ifdef CLIPPLANE2\nvarying fClipDistance2: f32;\r#endif\n#ifdef CLIPPLANE3\nvarying fClipDistance3: f32;\r#endif\n#ifdef CLIPPLANE4\nvarying fClipDistance4: f32;\r#endif\n#ifdef CLIPPLANE5\nvarying fClipDistance5: f32;\r#endif\n#ifdef CLIPPLANE6\nvarying fClipDistance6: f32;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const clipPlaneFragmentDeclaration = { name, shader };\n//# sourceMappingURL=clipPlaneFragmentDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"clipPlaneVertex\";\nconst shader = `#ifdef CLIPPLANE\nvertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane);\r#endif\n#ifdef CLIPPLANE2\nvertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2);\r#endif\n#ifdef CLIPPLANE3\nvertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3);\r#endif\n#ifdef CLIPPLANE4\nvertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4);\r#endif\n#ifdef CLIPPLANE5\nvertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5);\r#endif\n#ifdef CLIPPLANE6\nvertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6);\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const clipPlaneVertex = { name, shader };\n//# sourceMappingURL=clipPlaneVertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"clipPlaneVertexDeclaration\";\nconst shader = `#ifdef CLIPPLANE\nuniform vClipPlane: vec4;\rvarying fClipDistance: f32;\r#endif\n#ifdef CLIPPLANE2\nuniform vClipPlane2: vec4;\rvarying fClipDistance2: f32;\r#endif\n#ifdef CLIPPLANE3\nuniform vClipPlane3: vec4;\rvarying fClipDistance3: f32;\r#endif\n#ifdef CLIPPLANE4\nuniform vClipPlane4: vec4;\rvarying fClipDistance4: f32;\r#endif\n#ifdef CLIPPLANE5\nuniform vClipPlane5: vec4;\rvarying fClipDistance5: f32;\r#endif\n#ifdef CLIPPLANE6\nuniform vClipPlane6: vec4;\rvarying fClipDistance6: f32;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const clipPlaneVertexDeclaration = { name, shader };\n//# sourceMappingURL=clipPlaneVertexDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"instancesDeclaration\";\nconst shader = `#ifdef INSTANCES\nattribute world0 : vec4;\rattribute world1 : vec4;\rattribute world2 : vec4;\rattribute world3 : vec4;\r#ifdef INSTANCESCOLOR\nattribute instanceColor : vec4;\r#endif\n#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)\nuniform world : mat4x4;\r#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nattribute previousWorld0 : vec4;\rattribute previousWorld1 : vec4;\rattribute previousWorld2 : vec4;\rattribute previousWorld3 : vec4;\r#ifdef THIN_INSTANCES\nuniform previousWorld : mat4x4;\r#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nuniform world : mat4x4;\r#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nuniform previousWorld : mat4x4;\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const instancesDeclaration = { name, shader };\n//# sourceMappingURL=instancesDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"instancesVertex\";\nconst shader = `#ifdef INSTANCES\nvar finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3);\r#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=mat4x4(previousWorld0,previousWorld1,previousWorld2,previousWorld3);\r#endif\n#ifdef THIN_INSTANCES\n#if !defined(WORLD_UBO)\nfinalWorld=uniforms.world*finalWorld;\r#else\nfinalWorld=mesh.world*finalWorld;\r#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nfinalPreviousWorld=previousWorld*finalPreviousWorld;\r#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nvar finalWorld=uniforms.world;\r#else\nvar finalWorld=mesh.world;\r#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=previousWorld;\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const instancesVertex = { name, shader };\n//# sourceMappingURL=instancesVertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"meshUboDeclaration\";\nconst shader = `struct Mesh {\rworld : mat4x4,\rvisibility : f32,\r};\rvar mesh : Mesh;\r#define WORLD_UBO\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const meshUboDeclaration = { name, shader };\n//# sourceMappingURL=meshUboDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"morphTargetsVertex\";\nconst shader = `#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE \nvertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;\rpositionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];\rvertexID=vertexID+1.0;\r#ifdef MORPHTARGETS_NORMAL\nnormalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];\rvertexID=vertexID+1.0;\r#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];\rvertexID=vertexID+1.0;\r#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\r#endif\n#else\npositionUpdated=positionUpdated+(position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];\r#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];\r#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\r#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];\r#endif\n#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const morphTargetsVertex = { name, shader };\n//# sourceMappingURL=morphTargetsVertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"morphTargetsVertexDeclaration\";\nconst shader = `#ifdef MORPHTARGETS\n#ifndef MORPHTARGETS_TEXTURE\nattribute position{X} : vec3;\r#ifdef MORPHTARGETS_NORMAL\nattribute normal{X} : vec3;\r#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute tangent{X} : vec3;\r#endif\n#ifdef MORPHTARGETS_UV\nattribute uv_{X} : vec2;\r#endif\n#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const morphTargetsVertexDeclaration = { name, shader };\n//# sourceMappingURL=morphTargetsVertexDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"morphTargetsVertexGlobal\";\nconst shader = `#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\nvar vertexID : f32;\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const morphTargetsVertexGlobal = { name, shader };\n//# sourceMappingURL=morphTargetsVertexGlobal.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"morphTargetsVertexGlobalDeclaration\";\nconst shader = `#ifdef MORPHTARGETS\nuniform morphTargetInfluences : array;\r#ifdef MORPHTARGETS_TEXTURE \nuniform morphTargetTextureIndices : array;\runiform morphTargetTextureInfo : vec3;\rvar morphTargets : texture_2d_array;\rvar morphTargetsSampler : sampler;\rfn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3\r{ \rlet y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);\rlet x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;\rlet textureUV=vec2((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);\rreturn textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;\r}\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const morphTargetsVertexGlobalDeclaration = { name, shader };\n//# sourceMappingURL=morphTargetsVertexGlobalDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"sceneUboDeclaration\";\nconst shader = `struct Scene {\rviewProjection : mat4x4,\r#ifdef MULTIVIEW\nviewProjectionR : mat4x4,\r#endif \nview : mat4x4,\rprojection : mat4x4,\rvEyePosition : vec4,\r};\rvar scene : Scene;\r`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const sceneUboDeclaration = { name, shader };\n//# sourceMappingURL=sceneUboDeclaration.js.map","import { WebGPUShaderProcessingContext } from \"./webgpuShaderProcessingContext.js\";\nimport * as WebGPUConstants from \"./webgpuConstants.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { WebGPUShaderProcessor } from \"./webgpuShaderProcessor.js\";\nimport { RemoveComments } from \"../../Misc/codeStringParsingTools.js\";\nimport \"../../ShadersWGSL/ShadersInclude/bonesDeclaration.js\";\nimport \"../../ShadersWGSL/ShadersInclude/bonesVertex.js\";\nimport \"../../ShadersWGSL/ShadersInclude/bakedVertexAnimationDeclaration.js\";\nimport \"../../ShadersWGSL/ShadersInclude/bakedVertexAnimation.js\";\nimport \"../../ShadersWGSL/ShadersInclude/clipPlaneFragment.js\";\nimport \"../../ShadersWGSL/ShadersInclude/clipPlaneFragmentDeclaration.js\";\nimport \"../../ShadersWGSL/ShadersInclude/clipPlaneVertex.js\";\nimport \"../../ShadersWGSL/ShadersInclude/clipPlaneVertexDeclaration.js\";\nimport \"../../ShadersWGSL/ShadersInclude/instancesDeclaration.js\";\nimport \"../../ShadersWGSL/ShadersInclude/instancesVertex.js\";\nimport \"../../ShadersWGSL/ShadersInclude/meshUboDeclaration.js\";\nimport \"../../ShadersWGSL/ShadersInclude/morphTargetsVertex.js\";\nimport \"../../ShadersWGSL/ShadersInclude/morphTargetsVertexDeclaration.js\";\nimport \"../../ShadersWGSL/ShadersInclude/morphTargetsVertexGlobal.js\";\nimport \"../../ShadersWGSL/ShadersInclude/morphTargetsVertexGlobalDeclaration.js\";\nimport \"../../ShadersWGSL/ShadersInclude/sceneUboDeclaration.js\";\nimport { ShaderLanguage } from \"../../Materials/shaderLanguage.js\";\nconst builtInName_frag_depth = \"fragmentOutputs.fragDepth\";\nconst leftOverVarName = \"uniforms\";\nconst internalsVarName = \"internals\";\nconst gpuTextureViewDimensionByWebGPUTextureFunction = {\n texture_1d: WebGPUConstants.TextureViewDimension.E1d,\n texture_2d: WebGPUConstants.TextureViewDimension.E2d,\n texture_2d_array: WebGPUConstants.TextureViewDimension.E2dArray,\n texture_3d: WebGPUConstants.TextureViewDimension.E3d,\n texture_cube: WebGPUConstants.TextureViewDimension.Cube,\n texture_cube_array: WebGPUConstants.TextureViewDimension.CubeArray,\n texture_multisampled_2d: WebGPUConstants.TextureViewDimension.E2d,\n texture_depth_2d: WebGPUConstants.TextureViewDimension.E2d,\n texture_depth_2d_array: WebGPUConstants.TextureViewDimension.E2dArray,\n texture_depth_cube: WebGPUConstants.TextureViewDimension.Cube,\n texture_depth_cube_array: WebGPUConstants.TextureViewDimension.CubeArray,\n texture_depth_multisampled_2d: WebGPUConstants.TextureViewDimension.E2d,\n texture_storage_1d: WebGPUConstants.TextureViewDimension.E1d,\n texture_storage_2d: WebGPUConstants.TextureViewDimension.E2d,\n texture_storage_2d_array: WebGPUConstants.TextureViewDimension.E2dArray,\n texture_storage_3d: WebGPUConstants.TextureViewDimension.E3d,\n texture_external: null,\n};\n/** @internal */\nexport class WebGPUShaderProcessorWGSL extends WebGPUShaderProcessor {\n constructor() {\n super(...arguments);\n this.shaderLanguage = ShaderLanguage.WGSL;\n this.uniformRegexp = /uniform\\s+(\\w+)\\s*:\\s*(.+)\\s*;/;\n this.textureRegexp = /var\\s+(\\w+)\\s*:\\s*((array<\\s*)?(texture_\\w+)\\s*(<\\s*(.+)\\s*>)?\\s*(,\\s*\\w+\\s*>\\s*)?);/;\n this.noPrecision = true;\n }\n _getArraySize(name, uniformType, preProcessors) {\n let length = 0;\n const endArray = uniformType.lastIndexOf(\">\");\n if (uniformType.indexOf(\"array\") >= 0 && endArray > 0) {\n let startArray = endArray;\n while (startArray > 0 && uniformType.charAt(startArray) !== \" \" && uniformType.charAt(startArray) !== \",\") {\n startArray--;\n }\n const lengthInString = uniformType.substring(startArray + 1, endArray);\n length = +lengthInString;\n if (isNaN(length)) {\n length = +preProcessors[lengthInString.trim()];\n }\n while (startArray > 0 && (uniformType.charAt(startArray) === \" \" || uniformType.charAt(startArray) === \",\")) {\n startArray--;\n }\n uniformType = uniformType.substring(uniformType.indexOf(\"<\") + 1, startArray + 1);\n }\n return [name, uniformType, length];\n }\n initializeShaders(processingContext) {\n this._webgpuProcessingContext = processingContext;\n this._attributesWGSL = [];\n this._varyingsWGSL = [];\n this._varyingNamesWGSL = [];\n this._stridedUniformArrays = [];\n }\n preProcessShaderCode(code) {\n return (`struct ${WebGPUShaderProcessor.InternalsUBOName} {\\n yFactor_: f32,\\n textureOutputHeight_: f32,\\n};\\nvar ${internalsVarName} : ${WebGPUShaderProcessor.InternalsUBOName};\\n` +\n RemoveComments(code));\n }\n varyingProcessor(varying, isFragment, preProcessors) {\n const varyingRegex = /\\s*varying\\s+(?:(?:highp)?|(?:lowp)?)\\s*(\\S+)\\s*:\\s*(.+)\\s*;/gm;\n const match = varyingRegex.exec(varying);\n if (match !== null) {\n const varyingType = match[2];\n const name = match[1];\n let location;\n if (isFragment) {\n location = this._webgpuProcessingContext.availableVaryings[name];\n if (location === undefined) {\n Logger.Warn(`Invalid fragment shader: The varying named \"${name}\" is not declared in the vertex shader! This declaration will be ignored.`);\n }\n }\n else {\n location = this._webgpuProcessingContext.getVaryingNextLocation(varyingType, this._getArraySize(name, varyingType, preProcessors)[2]);\n this._webgpuProcessingContext.availableVaryings[name] = location;\n this._varyingsWGSL.push(` @location(${location}) ${name} : ${varyingType},`);\n this._varyingNamesWGSL.push(name);\n }\n varying = \"\";\n }\n return varying;\n }\n attributeProcessor(attribute, preProcessors) {\n const attribRegex = /\\s*attribute\\s+(\\S+)\\s*:\\s*(.+)\\s*;/gm;\n const match = attribRegex.exec(attribute);\n if (match !== null) {\n const attributeType = match[2];\n const name = match[1];\n const location = this._webgpuProcessingContext.getAttributeNextLocation(attributeType, this._getArraySize(name, attributeType, preProcessors)[2]);\n this._webgpuProcessingContext.availableAttributes[name] = location;\n this._webgpuProcessingContext.orderedAttributes[location] = name;\n this._attributesWGSL.push(`@location(${location}) ${name} : ${attributeType},`);\n attribute = \"\";\n }\n return attribute;\n }\n uniformProcessor(uniform, isFragment, preProcessors) {\n const match = this.uniformRegexp.exec(uniform);\n if (match !== null) {\n const uniformType = match[2];\n const name = match[1];\n this._addUniformToLeftOverUBO(name, uniformType, preProcessors);\n uniform = \"\";\n }\n return uniform;\n }\n textureProcessor(texture, isFragment, preProcessors) {\n const match = this.textureRegexp.exec(texture);\n if (match !== null) {\n const name = match[1]; // name of the variable\n const type = match[2]; // texture_2d or array, 5> for eg\n const isArrayOfTexture = !!match[3];\n const textureFunc = match[4]; // texture_2d, texture_depth_2d, etc\n const isStorageTexture = textureFunc.indexOf(\"storage\") > 0;\n const componentType = match[6]; // f32 or i32 or u32 or undefined\n const storageTextureFormat = isStorageTexture ? componentType.substring(0, componentType.indexOf(\",\")).trim() : null;\n let arraySize = isArrayOfTexture ? this._getArraySize(name, type, preProcessors)[2] : 0;\n let textureInfo = this._webgpuProcessingContext.availableTextures[name];\n if (!textureInfo) {\n textureInfo = {\n isTextureArray: arraySize > 0,\n isStorageTexture,\n textures: [],\n sampleType: WebGPUConstants.TextureSampleType.Float,\n };\n arraySize = arraySize || 1;\n for (let i = 0; i < arraySize; ++i) {\n textureInfo.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding());\n }\n }\n else {\n arraySize = textureInfo.textures.length;\n }\n this._webgpuProcessingContext.availableTextures[name] = textureInfo;\n const isDepthTexture = textureFunc.indexOf(\"depth\") > 0;\n const textureDimension = gpuTextureViewDimensionByWebGPUTextureFunction[textureFunc];\n const sampleType = isDepthTexture\n ? WebGPUConstants.TextureSampleType.Depth\n : componentType === \"u32\"\n ? WebGPUConstants.TextureSampleType.Uint\n : componentType === \"i32\"\n ? WebGPUConstants.TextureSampleType.Sint\n : WebGPUConstants.TextureSampleType.Float;\n textureInfo.sampleType = sampleType;\n if (textureDimension === undefined) {\n throw `Can't get the texture dimension corresponding to the texture function \"${textureFunc}\"!`;\n }\n for (let i = 0; i < arraySize; ++i) {\n const { groupIndex, bindingIndex } = textureInfo.textures[i];\n if (i === 0) {\n texture = `@group(${groupIndex}) @binding(${bindingIndex}) ${texture}`;\n }\n this._addTextureBindingDescription(name, textureInfo, i, textureDimension, storageTextureFormat, !isFragment);\n }\n }\n return texture;\n }\n postProcessor(code) {\n return code;\n }\n finalizeShaders(vertexCode, fragmentCode) {\n const fragCoordCode = fragmentCode.indexOf(\"fragmentInputs.position\") >= 0\n ? `\r\n if (internals.yFactor_ == 1.) {\r\n fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y;\r\n }\r\n `\n : \"\";\n // Add the group/binding info to the sampler declaration (var xxx: sampler|sampler_comparison)\n vertexCode = this._processSamplers(vertexCode, true);\n fragmentCode = this._processSamplers(fragmentCode, false);\n // Add the group/binding info to the uniform/storage buffer declarations (var XXX:YYY or var XXX:YYY)\n vertexCode = this._processCustomBuffers(vertexCode, true);\n fragmentCode = this._processCustomBuffers(fragmentCode, false);\n // Builds the leftover UBOs.\n const leftOverUBO = this._buildLeftOverUBO();\n vertexCode = leftOverUBO + vertexCode;\n fragmentCode = leftOverUBO + fragmentCode;\n // Vertex code\n vertexCode = vertexCode.replace(/#define /g, \"//#define \");\n vertexCode = this._processStridedUniformArrays(vertexCode);\n let vertexInputs = \"struct VertexInputs {\\n @builtin(vertex_index) vertexIndex : u32,\\n @builtin(instance_index) instanceIndex : u32,\\n\";\n if (this._attributesWGSL.length > 0) {\n vertexInputs += this._attributesWGSL.join(\"\\n\");\n }\n vertexInputs += \"\\n};\\nvar vertexInputs : VertexInputs;\\n\";\n let vertexOutputs = \"struct FragmentInputs {\\n @builtin(position) position : vec4,\\n\";\n if (this._varyingsWGSL.length > 0) {\n vertexOutputs += this._varyingsWGSL.join(\"\\n\");\n }\n vertexOutputs += \"\\n};\\nvar vertexOutputs : FragmentInputs;\\n\";\n vertexCode = vertexInputs + vertexOutputs + vertexCode;\n const vertexMainStartingCode = `\\n vertexInputs = input;\\n`;\n const vertexMainEndingCode = ` vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_;\\n return vertexOutputs;`;\n vertexCode = this._injectStartingAndEndingCode(vertexCode, \"fn main\", vertexMainStartingCode, vertexMainEndingCode);\n // fragment code\n fragmentCode = fragmentCode.replace(/#define /g, \"//#define \");\n fragmentCode = this._processStridedUniformArrays(fragmentCode);\n fragmentCode = fragmentCode.replace(/dpdy/g, \"(-internals.yFactor_)*dpdy\"); // will also handle dpdyCoarse and dpdyFine\n let fragmentInputs = \"struct FragmentInputs {\\n @builtin(position) position : vec4,\\n @builtin(front_facing) frontFacing : bool,\\n\";\n if (this._varyingsWGSL.length > 0) {\n fragmentInputs += this._varyingsWGSL.join(\"\\n\");\n }\n fragmentInputs += \"\\n};\\nvar fragmentInputs : FragmentInputs;\\n\";\n let fragmentOutputs = \"struct FragmentOutputs {\\n @location(0) color : vec4,\\n\";\n let hasFragDepth = false;\n let idx = 0;\n while (!hasFragDepth) {\n idx = fragmentCode.indexOf(builtInName_frag_depth, idx);\n if (idx < 0) {\n break;\n }\n const saveIndex = idx;\n hasFragDepth = true;\n while (idx > 1 && fragmentCode.charAt(idx) !== \"\\n\") {\n if (fragmentCode.charAt(idx) === \"/\" && fragmentCode.charAt(idx - 1) === \"/\") {\n hasFragDepth = false;\n break;\n }\n idx--;\n }\n idx = saveIndex + builtInName_frag_depth.length;\n }\n if (hasFragDepth) {\n fragmentOutputs += \" @builtin(frag_depth) fragDepth: f32,\\n\";\n }\n fragmentOutputs += \"};\\nvar fragmentOutputs : FragmentOutputs;\\n\";\n fragmentCode = fragmentInputs + fragmentOutputs + fragmentCode;\n const fragmentStartingCode = \" fragmentInputs = input;\\n \" + fragCoordCode;\n const fragmentEndingCode = \" return fragmentOutputs;\";\n fragmentCode = this._injectStartingAndEndingCode(fragmentCode, \"fn main\", fragmentStartingCode, fragmentEndingCode);\n this._collectBindingNames();\n this._preCreateBindGroupEntries();\n return { vertexCode, fragmentCode };\n }\n _generateLeftOverUBOCode(name, uniformBufferDescription) {\n let stridedArrays = \"\";\n let ubo = `struct ${name} {\\n`;\n for (const leftOverUniform of this._webgpuProcessingContext.leftOverUniforms) {\n const type = leftOverUniform.type.replace(/^(.*?)(<.*>)?$/, \"$1\");\n const size = WebGPUShaderProcessor.UniformSizes[type];\n if (leftOverUniform.length > 0) {\n if (size <= 2) {\n const stridedArrayType = `${name}_${this._stridedUniformArrays.length}_strided_arr`;\n stridedArrays += `struct ${stridedArrayType} {\r\n @size(16)\r\n el: ${type},\r\n }`;\n this._stridedUniformArrays.push(leftOverUniform.name);\n ubo += ` @align(16) ${leftOverUniform.name} : array<${stridedArrayType}, ${leftOverUniform.length}>,\\n`;\n }\n else {\n ubo += ` ${leftOverUniform.name} : array<${leftOverUniform.type}, ${leftOverUniform.length}>,\\n`;\n }\n }\n else {\n ubo += ` ${leftOverUniform.name} : ${leftOverUniform.type},\\n`;\n }\n }\n ubo += \"};\\n\";\n ubo = `${stridedArrays}\\n${ubo}`;\n ubo += `@group(${uniformBufferDescription.binding.groupIndex}) @binding(${uniformBufferDescription.binding.bindingIndex}) var ${leftOverVarName} : ${name};\\n`;\n return ubo;\n }\n _processSamplers(code, isVertex) {\n const samplerRegexp = /var\\s+(\\w+Sampler)\\s*:\\s*(sampler|sampler_comparison)\\s*;/gm;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const match = samplerRegexp.exec(code);\n if (match === null) {\n break;\n }\n const name = match[1]; // name of the variable\n const samplerType = match[2]; // sampler or sampler_comparison\n const textureName = name.indexOf(WebGPUShaderProcessor.AutoSamplerSuffix) === name.length - WebGPUShaderProcessor.AutoSamplerSuffix.length\n ? name.substring(0, name.indexOf(WebGPUShaderProcessor.AutoSamplerSuffix))\n : null;\n const samplerBindingType = samplerType === \"sampler_comparison\" ? WebGPUConstants.SamplerBindingType.Comparison : WebGPUConstants.SamplerBindingType.Filtering;\n if (textureName) {\n const textureInfo = this._webgpuProcessingContext.availableTextures[textureName];\n if (textureInfo) {\n textureInfo.autoBindSampler = true;\n }\n }\n let samplerInfo = this._webgpuProcessingContext.availableSamplers[name];\n if (!samplerInfo) {\n samplerInfo = {\n binding: this._webgpuProcessingContext.getNextFreeUBOBinding(),\n type: samplerBindingType,\n };\n this._webgpuProcessingContext.availableSamplers[name] = samplerInfo;\n }\n this._addSamplerBindingDescription(name, samplerInfo, isVertex);\n const part1 = code.substring(0, match.index);\n const insertPart = `@group(${samplerInfo.binding.groupIndex}) @binding(${samplerInfo.binding.bindingIndex}) `;\n const part2 = code.substring(match.index);\n code = part1 + insertPart + part2;\n samplerRegexp.lastIndex += insertPart.length;\n }\n return code;\n }\n _processCustomBuffers(code, isVertex) {\n const instantiateBufferRegexp = /var<\\s*(uniform|storage)\\s*(,\\s*(read|read_write)\\s*)?>\\s+(\\S+)\\s*:\\s*(\\S+)\\s*;/gm;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const match = instantiateBufferRegexp.exec(code);\n if (match === null) {\n break;\n }\n const type = match[1];\n const decoration = match[3];\n let name = match[4];\n const structName = match[5];\n let bufferInfo = this._webgpuProcessingContext.availableBuffers[name];\n if (!bufferInfo) {\n const knownUBO = type === \"uniform\" ? WebGPUShaderProcessingContext.KnownUBOs[structName] : null;\n let binding;\n if (knownUBO) {\n name = structName;\n binding = knownUBO.binding;\n if (binding.groupIndex === -1) {\n binding = this._webgpuProcessingContext.getNextFreeUBOBinding();\n }\n }\n else {\n binding = this._webgpuProcessingContext.getNextFreeUBOBinding();\n }\n bufferInfo = { binding };\n this._webgpuProcessingContext.availableBuffers[name] = bufferInfo;\n }\n this._addBufferBindingDescription(name, this._webgpuProcessingContext.availableBuffers[name], decoration === \"read_write\"\n ? WebGPUConstants.BufferBindingType.Storage\n : type === \"storage\"\n ? WebGPUConstants.BufferBindingType.ReadOnlyStorage\n : WebGPUConstants.BufferBindingType.Uniform, isVertex);\n const groupIndex = bufferInfo.binding.groupIndex;\n const bindingIndex = bufferInfo.binding.bindingIndex;\n const part1 = code.substring(0, match.index);\n const insertPart = `@group(${groupIndex}) @binding(${bindingIndex}) `;\n const part2 = code.substring(match.index);\n code = part1 + insertPart + part2;\n instantiateBufferRegexp.lastIndex += insertPart.length;\n }\n return code;\n }\n _processStridedUniformArrays(code) {\n for (const uniformArrayName of this._stridedUniformArrays) {\n code = code.replace(new RegExp(`${uniformArrayName}\\\\s*\\\\[(.*)\\\\]`, \"g\"), `${uniformArrayName}[$1].el`);\n }\n return code;\n }\n}\n//# sourceMappingURL=webgpuShaderProcessorsWGSL.js.map","import { Scalar } from \"../../Maths/math.scalar.js\";\nimport * as WebGPUConstants from \"./webgpuConstants.js\";\n/** @internal */\nexport class WebGPUHardwareTexture {\n get underlyingResource() {\n return this._webgpuTexture;\n }\n getMSAATexture(index = 0) {\n var _a, _b;\n return (_b = (_a = this._webgpuMSAATexture) === null || _a === void 0 ? void 0 : _a[index]) !== null && _b !== void 0 ? _b : null;\n }\n setMSAATexture(texture, index = -1) {\n if (!this._webgpuMSAATexture) {\n this._webgpuMSAATexture = [];\n }\n if (index === -1) {\n index = this._webgpuMSAATexture.length;\n }\n this._webgpuMSAATexture[index] = texture;\n }\n releaseMSAATexture() {\n if (this._webgpuMSAATexture) {\n for (const texture of this._webgpuMSAATexture) {\n texture === null || texture === void 0 ? void 0 : texture.destroy();\n }\n this._webgpuMSAATexture = null;\n }\n }\n constructor(existingTexture = null) {\n this.format = WebGPUConstants.TextureFormat.RGBA8Unorm;\n this.textureUsages = 0;\n this.textureAdditionalUsages = 0;\n this._webgpuTexture = existingTexture;\n this._webgpuMSAATexture = null;\n this.view = null;\n this.viewForWriting = null;\n }\n set(hardwareTexture) {\n this._webgpuTexture = hardwareTexture;\n }\n setUsage(_textureSource, generateMipMaps, isCube, width, height) {\n this.createView({\n format: this.format,\n dimension: isCube ? WebGPUConstants.TextureViewDimension.Cube : WebGPUConstants.TextureViewDimension.E2d,\n mipLevelCount: generateMipMaps ? Scalar.ILog2(Math.max(width, height)) + 1 : 1,\n baseArrayLayer: 0,\n baseMipLevel: 0,\n arrayLayerCount: isCube ? 6 : 1,\n aspect: WebGPUConstants.TextureAspect.All,\n });\n }\n createView(descriptor, createViewForWriting = false) {\n this.view = this._webgpuTexture.createView(descriptor);\n if (createViewForWriting && descriptor) {\n const saveNumMipMaps = descriptor.mipLevelCount;\n descriptor.mipLevelCount = 1;\n this.viewForWriting = this._webgpuTexture.createView(descriptor);\n descriptor.mipLevelCount = saveNumMipMaps;\n }\n }\n reset() {\n this._webgpuTexture = null;\n this._webgpuMSAATexture = null;\n this.view = null;\n this.viewForWriting = null;\n }\n release() {\n var _a, _b;\n (_a = this._webgpuTexture) === null || _a === void 0 ? void 0 : _a.destroy();\n this.releaseMSAATexture();\n (_b = this._copyInvertYTempTexture) === null || _b === void 0 ? void 0 : _b.destroy();\n this.reset();\n }\n}\n//# sourceMappingURL=webgpuHardwareTexture.js.map","/* eslint-disable @typescript-eslint/naming-convention */\n// License for the mipmap generation code:\n//\n// Copyright 2020 Brandon Jones\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\nimport * as WebGPUConstants from \"./webgpuConstants.js\";\nimport { Scalar } from \"../../Maths/math.scalar.js\";\n\nimport { InternalTextureSource } from \"../../Materials/Textures/internalTexture.js\";\nimport { WebGPUHardwareTexture } from \"./webgpuHardwareTexture.js\";\n// TODO WEBGPU improve mipmap generation by using compute shaders\n// TODO WEBGPU use WGSL instead of GLSL\nconst mipmapVertexSource = `\r\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\r\n const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));\r\n\r\n layout(location = 0) out vec2 vTex;\r\n\r\n void main() {\r\n vTex = tex[gl_VertexIndex];\r\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\r\n }\r\n `;\nconst mipmapFragmentSource = `\r\n layout(set = 0, binding = 0) uniform sampler imgSampler;\r\n layout(set = 0, binding = 1) uniform texture2D img;\r\n\r\n layout(location = 0) in vec2 vTex;\r\n layout(location = 0) out vec4 outColor;\r\n\r\n void main() {\r\n outColor = texture(sampler2D(img, imgSampler), vTex);\r\n }\r\n `;\nconst invertYPreMultiplyAlphaVertexSource = `\r\n #extension GL_EXT_samplerless_texture_functions : enable\r\n\r\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\r\n const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));\r\n\r\n layout(set = 0, binding = 0) uniform texture2D img;\r\n\r\n #ifdef INVERTY\r\n layout(location = 0) out flat ivec2 vTextureSize;\r\n #endif\r\n\r\n void main() {\r\n #ifdef INVERTY\r\n vTextureSize = textureSize(img, 0);\r\n #endif\r\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\r\n }\r\n `;\nconst invertYPreMultiplyAlphaFragmentSource = `\r\n #extension GL_EXT_samplerless_texture_functions : enable\r\n\r\n layout(set = 0, binding = 0) uniform texture2D img;\r\n\r\n #ifdef INVERTY\r\n layout(location = 0) in flat ivec2 vTextureSize;\r\n #endif\r\n layout(location = 0) out vec4 outColor;\r\n\r\n void main() {\r\n #ifdef INVERTY\r\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0);\r\n #else\r\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\r\n #endif\r\n #ifdef PREMULTIPLYALPHA\r\n color.rgb *= color.a;\r\n #endif\r\n outColor = color;\r\n }\r\n `;\nconst invertYPreMultiplyAlphaWithOfstVertexSource = invertYPreMultiplyAlphaVertexSource;\nconst invertYPreMultiplyAlphaWithOfstFragmentSource = `\r\n #extension GL_EXT_samplerless_texture_functions : enable\r\n\r\n layout(set = 0, binding = 0) uniform texture2D img;\r\n layout(set = 0, binding = 1) uniform Params {\r\n float ofstX;\r\n float ofstY;\r\n float width;\r\n float height;\r\n };\r\n\r\n #ifdef INVERTY\r\n layout(location = 0) in flat ivec2 vTextureSize;\r\n #endif\r\n layout(location = 0) out vec4 outColor;\r\n\r\n void main() {\r\n if (gl_FragCoord.x < ofstX || gl_FragCoord.x >= ofstX + width) {\r\n discard;\r\n }\r\n if (gl_FragCoord.y < ofstY || gl_FragCoord.y >= ofstY + height) {\r\n discard;\r\n }\r\n #ifdef INVERTY\r\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, ofstY + height - (gl_FragCoord.y - ofstY)), 0);\r\n #else\r\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\r\n #endif\r\n #ifdef PREMULTIPLYALPHA\r\n color.rgb *= color.a;\r\n #endif\r\n outColor = color;\r\n }\r\n `;\nconst clearVertexSource = `\r\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\r\n\r\n void main() {\r\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\r\n }\r\n `;\nconst clearFragmentSource = `\r\n layout(set = 0, binding = 0) uniform Uniforms {\r\n uniform vec4 color;\r\n };\r\n\r\n layout(location = 0) out vec4 outColor;\r\n\r\n void main() {\r\n outColor = color;\r\n }\r\n `;\nconst copyVideoToTextureVertexSource = `\r\n struct VertexOutput {\r\n @builtin(position) Position : vec4,\r\n @location(0) fragUV : vec2\r\n }\r\n \r\n @vertex\r\n fn main(\r\n @builtin(vertex_index) VertexIndex : u32\r\n ) -> VertexOutput {\r\n var pos = array, 4>(\r\n vec2(-1.0, 1.0),\r\n vec2( 1.0, 1.0),\r\n vec2(-1.0, -1.0),\r\n vec2( 1.0, -1.0)\r\n );\r\n var tex = array, 4>(\r\n vec2(0.0, 0.0),\r\n vec2(1.0, 0.0),\r\n vec2(0.0, 1.0),\r\n vec2(1.0, 1.0)\r\n );\r\n\r\n var output: VertexOutput;\r\n\r\n output.Position = vec4(pos[VertexIndex], 0.0, 1.0);\r\n output.fragUV = tex[VertexIndex];\r\n\r\n return output;\r\n }\r\n `;\nconst copyVideoToTextureFragmentSource = `\r\n @group(0) @binding(0) var videoSampler: sampler;\r\n @group(0) @binding(1) var videoTexture: texture_external;\r\n\r\n @fragment\r\n fn main(\r\n @location(0) fragUV: vec2\r\n ) -> @location(0) vec4 {\r\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV);\r\n }\r\n `;\nconst copyVideoToTextureInvertYFragmentSource = `\r\n @group(0) @binding(0) var videoSampler: sampler;\r\n @group(0) @binding(1) var videoTexture: texture_external;\r\n\r\n @fragment\r\n fn main(\r\n @location(0) fragUV: vec2\r\n ) -> @location(0) vec4 {\r\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2(fragUV.x, 1.0 - fragUV.y));\r\n }\r\n `;\nvar PipelineType;\n(function (PipelineType) {\n PipelineType[PipelineType[\"MipMap\"] = 0] = \"MipMap\";\n PipelineType[PipelineType[\"InvertYPremultiplyAlpha\"] = 1] = \"InvertYPremultiplyAlpha\";\n PipelineType[PipelineType[\"Clear\"] = 2] = \"Clear\";\n PipelineType[PipelineType[\"InvertYPremultiplyAlphaWithOfst\"] = 3] = \"InvertYPremultiplyAlphaWithOfst\";\n})(PipelineType || (PipelineType = {}));\nvar VideoPipelineType;\n(function (VideoPipelineType) {\n VideoPipelineType[VideoPipelineType[\"DontInvertY\"] = 0] = \"DontInvertY\";\n VideoPipelineType[VideoPipelineType[\"InvertY\"] = 1] = \"InvertY\";\n})(VideoPipelineType || (VideoPipelineType = {}));\nconst shadersForPipelineType = [\n { vertex: mipmapVertexSource, fragment: mipmapFragmentSource },\n { vertex: invertYPreMultiplyAlphaVertexSource, fragment: invertYPreMultiplyAlphaFragmentSource },\n { vertex: clearVertexSource, fragment: clearFragmentSource },\n { vertex: invertYPreMultiplyAlphaWithOfstVertexSource, fragment: invertYPreMultiplyAlphaWithOfstFragmentSource },\n];\n/**\n * Map a (renderable) texture format (GPUTextureFormat) to an index for fast lookup (in caches for eg)\n */\nexport const renderableTextureFormatToIndex = {\n \"\": 0,\n r8unorm: 1,\n r8uint: 2,\n r8sint: 3,\n r16uint: 4,\n r16sint: 5,\n r16float: 6,\n rg8unorm: 7,\n rg8uint: 8,\n rg8sint: 9,\n r32uint: 10,\n r32sint: 11,\n r32float: 12,\n rg16uint: 13,\n rg16sint: 14,\n rg16float: 15,\n rgba8unorm: 16,\n \"rgba8unorm-srgb\": 17,\n rgba8uint: 18,\n rgba8sint: 19,\n bgra8unorm: 20,\n \"bgra8unorm-srgb\": 21,\n rgb10a2unorm: 22,\n rg32uint: 23,\n rg32sint: 24,\n rg32float: 25,\n rgba16uint: 26,\n rgba16sint: 27,\n rgba16float: 28,\n rgba32uint: 29,\n rgba32sint: 30,\n rgba32float: 31,\n stencil8: 32,\n depth16unorm: 33,\n depth24plus: 34,\n \"depth24plus-stencil8\": 35,\n depth32float: 36,\n \"depth32float-stencil8\": 37,\n};\n/** @internal */\nexport class WebGPUTextureHelper {\n static ComputeNumMipmapLevels(width, height) {\n return Scalar.ILog2(Math.max(width, height)) + 1;\n }\n //------------------------------------------------------------------------------\n // Initialization / Helpers\n //------------------------------------------------------------------------------\n constructor(device, glslang, tintWASM, bufferManager, enabledExtensions) {\n this._pipelines = {};\n this._compiledShaders = [];\n this._videoPipelines = {};\n this._videoCompiledShaders = [];\n this._deferredReleaseTextures = [];\n this._device = device;\n this._glslang = glslang;\n this._tintWASM = tintWASM;\n this._bufferManager = bufferManager;\n if (enabledExtensions.indexOf(WebGPUConstants.FeatureName.RG11B10UFloatRenderable) !== -1) {\n const keys = Object.keys(renderableTextureFormatToIndex);\n renderableTextureFormatToIndex[WebGPUConstants.TextureFormat.RG11B10UFloat] = renderableTextureFormatToIndex[keys[keys.length - 1]] + 1;\n }\n this._mipmapSampler = device.createSampler({ minFilter: WebGPUConstants.FilterMode.Linear });\n this._videoSampler = device.createSampler({ minFilter: WebGPUConstants.FilterMode.Linear });\n this._ubCopyWithOfst = this._bufferManager.createBuffer(4 * 4, WebGPUConstants.BufferUsage.Uniform | WebGPUConstants.BufferUsage.CopyDst).underlyingResource;\n this._getPipeline(WebGPUConstants.TextureFormat.RGBA8Unorm);\n this._getVideoPipeline(WebGPUConstants.TextureFormat.RGBA8Unorm);\n }\n _getPipeline(format, type = PipelineType.MipMap, params) {\n const index = type === PipelineType.MipMap\n ? 1 << 0\n : type === PipelineType.InvertYPremultiplyAlpha\n ? ((params.invertY ? 1 : 0) << 1) + ((params.premultiplyAlpha ? 1 : 0) << 2)\n : type === PipelineType.Clear\n ? 1 << 3\n : type === PipelineType.InvertYPremultiplyAlphaWithOfst\n ? ((params.invertY ? 1 : 0) << 4) + ((params.premultiplyAlpha ? 1 : 0) << 5)\n : 0;\n if (!this._pipelines[format]) {\n this._pipelines[format] = [];\n }\n let pipelineAndBGL = this._pipelines[format][index];\n if (!pipelineAndBGL) {\n let defines = \"#version 450\\r\\n\";\n if (type === PipelineType.InvertYPremultiplyAlpha || type === PipelineType.InvertYPremultiplyAlphaWithOfst) {\n if (params.invertY) {\n defines += \"#define INVERTY\\r\\n\";\n }\n if (params.premultiplyAlpha) {\n defines += \"#define PREMULTIPLYALPHA\\r\\n\";\n }\n }\n let modules = this._compiledShaders[index];\n if (!modules) {\n let vertexCode = this._glslang.compileGLSL(defines + shadersForPipelineType[type].vertex, \"vertex\");\n let fragmentCode = this._glslang.compileGLSL(defines + shadersForPipelineType[type].fragment, \"fragment\");\n if (this._tintWASM) {\n vertexCode = this._tintWASM.convertSpirV2WGSL(vertexCode);\n fragmentCode = this._tintWASM.convertSpirV2WGSL(fragmentCode);\n }\n const vertexModule = this._device.createShaderModule({\n code: vertexCode,\n });\n const fragmentModule = this._device.createShaderModule({\n code: fragmentCode,\n });\n modules = this._compiledShaders[index] = [vertexModule, fragmentModule];\n }\n const pipeline = this._device.createRenderPipeline({\n layout: WebGPUConstants.AutoLayoutMode.Auto,\n vertex: {\n module: modules[0],\n entryPoint: \"main\",\n },\n fragment: {\n module: modules[1],\n entryPoint: \"main\",\n targets: [\n {\n format,\n },\n ],\n },\n primitive: {\n topology: WebGPUConstants.PrimitiveTopology.TriangleStrip,\n stripIndexFormat: WebGPUConstants.IndexFormat.Uint16,\n },\n });\n pipelineAndBGL = this._pipelines[format][index] = [pipeline, pipeline.getBindGroupLayout(0)];\n }\n return pipelineAndBGL;\n }\n _getVideoPipeline(format, type = VideoPipelineType.DontInvertY) {\n const index = type === VideoPipelineType.InvertY ? 1 << 0 : 0;\n if (!this._videoPipelines[format]) {\n this._videoPipelines[format] = [];\n }\n let pipelineAndBGL = this._videoPipelines[format][index];\n if (!pipelineAndBGL) {\n let modules = this._videoCompiledShaders[index];\n if (!modules) {\n const vertexModule = this._device.createShaderModule({\n code: copyVideoToTextureVertexSource,\n });\n const fragmentModule = this._device.createShaderModule({\n code: index === 0 ? copyVideoToTextureFragmentSource : copyVideoToTextureInvertYFragmentSource,\n });\n modules = this._videoCompiledShaders[index] = [vertexModule, fragmentModule];\n }\n const pipeline = this._device.createRenderPipeline({\n label: `CopyVideoToTexture_${format}_${index === 0 ? \"DontInvertY\" : \"InvertY\"}`,\n layout: WebGPUConstants.AutoLayoutMode.Auto,\n vertex: {\n module: modules[0],\n entryPoint: \"main\",\n },\n fragment: {\n module: modules[1],\n entryPoint: \"main\",\n targets: [\n {\n format,\n },\n ],\n },\n primitive: {\n topology: WebGPUConstants.PrimitiveTopology.TriangleStrip,\n stripIndexFormat: WebGPUConstants.IndexFormat.Uint16,\n },\n });\n pipelineAndBGL = this._videoPipelines[format][index] = [pipeline, pipeline.getBindGroupLayout(0)];\n }\n return pipelineAndBGL;\n }\n static _GetTextureTypeFromFormat(format) {\n switch (format) {\n // One Component = 8 bits\n case WebGPUConstants.TextureFormat.R8Unorm:\n case WebGPUConstants.TextureFormat.R8Snorm:\n case WebGPUConstants.TextureFormat.R8Uint:\n case WebGPUConstants.TextureFormat.R8Sint:\n case WebGPUConstants.TextureFormat.RG8Unorm:\n case WebGPUConstants.TextureFormat.RG8Snorm:\n case WebGPUConstants.TextureFormat.RG8Uint:\n case WebGPUConstants.TextureFormat.RG8Sint:\n case WebGPUConstants.TextureFormat.RGBA8Unorm:\n case WebGPUConstants.TextureFormat.RGBA8UnormSRGB:\n case WebGPUConstants.TextureFormat.RGBA8Snorm:\n case WebGPUConstants.TextureFormat.RGBA8Uint:\n case WebGPUConstants.TextureFormat.RGBA8Sint:\n case WebGPUConstants.TextureFormat.BGRA8Unorm:\n case WebGPUConstants.TextureFormat.BGRA8UnormSRGB:\n case WebGPUConstants.TextureFormat.RGB10A2Unorm: // composite format - let's say it's byte...\n case WebGPUConstants.TextureFormat.RGB9E5UFloat: // composite format - let's say it's byte...\n case WebGPUConstants.TextureFormat.RG11B10UFloat: // composite format - let's say it's byte...\n case WebGPUConstants.TextureFormat.Depth24UnormStencil8: // composite format - let's say it's byte...\n case WebGPUConstants.TextureFormat.Depth32FloatStencil8: // composite format - let's say it's byte...\n case WebGPUConstants.TextureFormat.BC7RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC7RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.BC6HRGBUFloat:\n case WebGPUConstants.TextureFormat.BC6HRGBFloat:\n case WebGPUConstants.TextureFormat.BC5RGUnorm:\n case WebGPUConstants.TextureFormat.BC5RGSnorm:\n case WebGPUConstants.TextureFormat.BC3RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC3RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.BC2RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC2RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.BC4RUnorm:\n case WebGPUConstants.TextureFormat.BC4RSnorm:\n case WebGPUConstants.TextureFormat.BC1RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC1RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.ETC2RGB8Unorm:\n case WebGPUConstants.TextureFormat.ETC2RGB8UnormSRGB:\n case WebGPUConstants.TextureFormat.ETC2RGB8A1Unorm:\n case WebGPUConstants.TextureFormat.ETC2RGB8A1UnormSRGB:\n case WebGPUConstants.TextureFormat.ETC2RGBA8Unorm:\n case WebGPUConstants.TextureFormat.ETC2RGBA8UnormSRGB:\n case WebGPUConstants.TextureFormat.EACR11Unorm:\n case WebGPUConstants.TextureFormat.EACR11Snorm:\n case WebGPUConstants.TextureFormat.EACRG11Unorm:\n case WebGPUConstants.TextureFormat.EACRG11Snorm:\n case WebGPUConstants.TextureFormat.ASTC4x4Unorm:\n case WebGPUConstants.TextureFormat.ASTC4x4UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC5x4Unorm:\n case WebGPUConstants.TextureFormat.ASTC5x4UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC5x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC5x5UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC6x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC6x5UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC6x6Unorm:\n case WebGPUConstants.TextureFormat.ASTC6x6UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC8x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC8x5UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC8x6Unorm:\n case WebGPUConstants.TextureFormat.ASTC8x6UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC8x8Unorm:\n case WebGPUConstants.TextureFormat.ASTC8x8UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC10x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x5UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC10x6Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x6UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC10x8Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x8UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC10x10Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x10UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC12x10Unorm:\n case WebGPUConstants.TextureFormat.ASTC12x10UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC12x12Unorm:\n case WebGPUConstants.TextureFormat.ASTC12x12UnormSRGB:\n return 0;\n // One component = 16 bits\n case WebGPUConstants.TextureFormat.R16Uint:\n case WebGPUConstants.TextureFormat.R16Sint:\n case WebGPUConstants.TextureFormat.RG16Uint:\n case WebGPUConstants.TextureFormat.RG16Sint:\n case WebGPUConstants.TextureFormat.RGBA16Uint:\n case WebGPUConstants.TextureFormat.RGBA16Sint:\n case WebGPUConstants.TextureFormat.Depth16Unorm:\n return 5;\n case WebGPUConstants.TextureFormat.R16Float:\n case WebGPUConstants.TextureFormat.RG16Float:\n case WebGPUConstants.TextureFormat.RGBA16Float:\n return 2;\n // One component = 32 bits\n case WebGPUConstants.TextureFormat.R32Uint:\n case WebGPUConstants.TextureFormat.R32Sint:\n case WebGPUConstants.TextureFormat.RG32Uint:\n case WebGPUConstants.TextureFormat.RG32Sint:\n case WebGPUConstants.TextureFormat.RGBA32Uint:\n case WebGPUConstants.TextureFormat.RGBA32Sint:\n return 7;\n case WebGPUConstants.TextureFormat.R32Float:\n case WebGPUConstants.TextureFormat.RG32Float:\n case WebGPUConstants.TextureFormat.RGBA32Float:\n case WebGPUConstants.TextureFormat.Depth32Float:\n return 1;\n case WebGPUConstants.TextureFormat.Stencil8:\n throw \"No fixed size for Stencil8 format!\";\n case WebGPUConstants.TextureFormat.Depth24Plus:\n throw \"No fixed size for Depth24Plus format!\";\n case WebGPUConstants.TextureFormat.Depth24PlusStencil8:\n throw \"No fixed size for Depth24PlusStencil8 format!\";\n }\n return 0;\n }\n static _GetBlockInformationFromFormat(format) {\n switch (format) {\n // 8 bits formats\n case WebGPUConstants.TextureFormat.R8Unorm:\n case WebGPUConstants.TextureFormat.R8Snorm:\n case WebGPUConstants.TextureFormat.R8Uint:\n case WebGPUConstants.TextureFormat.R8Sint:\n return { width: 1, height: 1, length: 1 };\n // 16 bits formats\n case WebGPUConstants.TextureFormat.R16Uint:\n case WebGPUConstants.TextureFormat.R16Sint:\n case WebGPUConstants.TextureFormat.R16Float:\n case WebGPUConstants.TextureFormat.RG8Unorm:\n case WebGPUConstants.TextureFormat.RG8Snorm:\n case WebGPUConstants.TextureFormat.RG8Uint:\n case WebGPUConstants.TextureFormat.RG8Sint:\n return { width: 1, height: 1, length: 2 };\n // 32 bits formats\n case WebGPUConstants.TextureFormat.R32Uint:\n case WebGPUConstants.TextureFormat.R32Sint:\n case WebGPUConstants.TextureFormat.R32Float:\n case WebGPUConstants.TextureFormat.RG16Uint:\n case WebGPUConstants.TextureFormat.RG16Sint:\n case WebGPUConstants.TextureFormat.RG16Float:\n case WebGPUConstants.TextureFormat.RGBA8Unorm:\n case WebGPUConstants.TextureFormat.RGBA8UnormSRGB:\n case WebGPUConstants.TextureFormat.RGBA8Snorm:\n case WebGPUConstants.TextureFormat.RGBA8Uint:\n case WebGPUConstants.TextureFormat.RGBA8Sint:\n case WebGPUConstants.TextureFormat.BGRA8Unorm:\n case WebGPUConstants.TextureFormat.BGRA8UnormSRGB:\n case WebGPUConstants.TextureFormat.RGB9E5UFloat:\n case WebGPUConstants.TextureFormat.RGB10A2Unorm:\n case WebGPUConstants.TextureFormat.RG11B10UFloat:\n return { width: 1, height: 1, length: 4 };\n // 64 bits formats\n case WebGPUConstants.TextureFormat.RG32Uint:\n case WebGPUConstants.TextureFormat.RG32Sint:\n case WebGPUConstants.TextureFormat.RG32Float:\n case WebGPUConstants.TextureFormat.RGBA16Uint:\n case WebGPUConstants.TextureFormat.RGBA16Sint:\n case WebGPUConstants.TextureFormat.RGBA16Float:\n return { width: 1, height: 1, length: 8 };\n // 128 bits formats\n case WebGPUConstants.TextureFormat.RGBA32Uint:\n case WebGPUConstants.TextureFormat.RGBA32Sint:\n case WebGPUConstants.TextureFormat.RGBA32Float:\n return { width: 1, height: 1, length: 16 };\n // Depth and stencil formats\n case WebGPUConstants.TextureFormat.Stencil8:\n throw \"No fixed size for Stencil8 format!\";\n case WebGPUConstants.TextureFormat.Depth16Unorm:\n return { width: 1, height: 1, length: 2 };\n case WebGPUConstants.TextureFormat.Depth24Plus:\n throw \"No fixed size for Depth24Plus format!\";\n case WebGPUConstants.TextureFormat.Depth24PlusStencil8:\n throw \"No fixed size for Depth24PlusStencil8 format!\";\n case WebGPUConstants.TextureFormat.Depth32Float:\n return { width: 1, height: 1, length: 4 };\n case WebGPUConstants.TextureFormat.Depth24UnormStencil8:\n return { width: 1, height: 1, length: 4 };\n case WebGPUConstants.TextureFormat.Depth32FloatStencil8:\n return { width: 1, height: 1, length: 5 };\n // BC compressed formats usable if \"texture-compression-bc\" is both\n // supported by the device/user agent and enabled in requestDevice.\n case WebGPUConstants.TextureFormat.BC7RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC7RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.BC6HRGBUFloat:\n case WebGPUConstants.TextureFormat.BC6HRGBFloat:\n case WebGPUConstants.TextureFormat.BC5RGUnorm:\n case WebGPUConstants.TextureFormat.BC5RGSnorm:\n case WebGPUConstants.TextureFormat.BC3RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC3RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.BC2RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC2RGBAUnormSRGB:\n return { width: 4, height: 4, length: 16 };\n case WebGPUConstants.TextureFormat.BC4RUnorm:\n case WebGPUConstants.TextureFormat.BC4RSnorm:\n case WebGPUConstants.TextureFormat.BC1RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC1RGBAUnormSRGB:\n return { width: 4, height: 4, length: 8 };\n // ETC2 compressed formats usable if \"texture-compression-etc2\" is both\n // supported by the device/user agent and enabled in requestDevice.\n case WebGPUConstants.TextureFormat.ETC2RGB8Unorm:\n case WebGPUConstants.TextureFormat.ETC2RGB8UnormSRGB:\n case WebGPUConstants.TextureFormat.ETC2RGB8A1Unorm:\n case WebGPUConstants.TextureFormat.ETC2RGB8A1UnormSRGB:\n case WebGPUConstants.TextureFormat.EACR11Unorm:\n case WebGPUConstants.TextureFormat.EACR11Snorm:\n return { width: 4, height: 4, length: 8 };\n case WebGPUConstants.TextureFormat.ETC2RGBA8Unorm:\n case WebGPUConstants.TextureFormat.ETC2RGBA8UnormSRGB:\n case WebGPUConstants.TextureFormat.EACRG11Unorm:\n case WebGPUConstants.TextureFormat.EACRG11Snorm:\n return { width: 4, height: 4, length: 16 };\n // ASTC compressed formats usable if \"texture-compression-astc\" is both\n // supported by the device/user agent and enabled in requestDevice.\n case WebGPUConstants.TextureFormat.ASTC4x4Unorm:\n case WebGPUConstants.TextureFormat.ASTC4x4UnormSRGB:\n return { width: 4, height: 4, length: 16 };\n case WebGPUConstants.TextureFormat.ASTC5x4Unorm:\n case WebGPUConstants.TextureFormat.ASTC5x4UnormSRGB:\n return { width: 5, height: 4, length: 16 };\n case WebGPUConstants.TextureFormat.ASTC5x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC5x5UnormSRGB:\n return { width: 5, height: 5, length: 16 };\n case WebGPUConstants.TextureFormat.ASTC6x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC6x5UnormSRGB:\n return { width: 6, height: 5, length: 16 };\n case WebGPUConstants.TextureFormat.ASTC6x6Unorm:\n case WebGPUConstants.TextureFormat.ASTC6x6UnormSRGB:\n return { width: 6, height: 6, length: 16 };\n case WebGPUConstants.TextureFormat.ASTC8x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC8x5UnormSRGB:\n return { width: 8, height: 5, length: 16 };\n case WebGPUConstants.TextureFormat.ASTC8x6Unorm:\n case WebGPUConstants.TextureFormat.ASTC8x6UnormSRGB:\n return { width: 8, height: 6, length: 16 };\n case WebGPUConstants.TextureFormat.ASTC8x8Unorm:\n case WebGPUConstants.TextureFormat.ASTC8x8UnormSRGB:\n return { width: 8, height: 8, length: 16 };\n case WebGPUConstants.TextureFormat.ASTC10x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x5UnormSRGB:\n return { width: 10, height: 5, length: 16 };\n case WebGPUConstants.TextureFormat.ASTC10x6Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x6UnormSRGB:\n return { width: 10, height: 6, length: 16 };\n case WebGPUConstants.TextureFormat.ASTC10x8Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x8UnormSRGB:\n return { width: 10, height: 8, length: 16 };\n case WebGPUConstants.TextureFormat.ASTC10x10Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x10UnormSRGB:\n return { width: 10, height: 10, length: 16 };\n case WebGPUConstants.TextureFormat.ASTC12x10Unorm:\n case WebGPUConstants.TextureFormat.ASTC12x10UnormSRGB:\n return { width: 12, height: 10, length: 16 };\n case WebGPUConstants.TextureFormat.ASTC12x12Unorm:\n case WebGPUConstants.TextureFormat.ASTC12x12UnormSRGB:\n return { width: 12, height: 12, length: 16 };\n }\n return { width: 1, height: 1, length: 4 };\n }\n static _IsHardwareTexture(texture) {\n return !!texture.release;\n }\n static _IsInternalTexture(texture) {\n return !!texture.dispose;\n }\n static IsImageBitmap(imageBitmap) {\n return imageBitmap.close !== undefined;\n }\n static IsImageBitmapArray(imageBitmap) {\n return Array.isArray(imageBitmap) && imageBitmap[0].close !== undefined;\n }\n setCommandEncoder(encoder) {\n this._commandEncoderForCreation = encoder;\n }\n static IsCompressedFormat(format) {\n switch (format) {\n case WebGPUConstants.TextureFormat.BC7RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.BC7RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC6HRGBFloat:\n case WebGPUConstants.TextureFormat.BC6HRGBUFloat:\n case WebGPUConstants.TextureFormat.BC5RGSnorm:\n case WebGPUConstants.TextureFormat.BC5RGUnorm:\n case WebGPUConstants.TextureFormat.BC4RSnorm:\n case WebGPUConstants.TextureFormat.BC4RUnorm:\n case WebGPUConstants.TextureFormat.BC3RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.BC3RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC2RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.BC2RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC1RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.BC1RGBAUnorm:\n case WebGPUConstants.TextureFormat.ETC2RGB8Unorm:\n case WebGPUConstants.TextureFormat.ETC2RGB8UnormSRGB:\n case WebGPUConstants.TextureFormat.ETC2RGB8A1Unorm:\n case WebGPUConstants.TextureFormat.ETC2RGB8A1UnormSRGB:\n case WebGPUConstants.TextureFormat.ETC2RGBA8Unorm:\n case WebGPUConstants.TextureFormat.ETC2RGBA8UnormSRGB:\n case WebGPUConstants.TextureFormat.EACR11Unorm:\n case WebGPUConstants.TextureFormat.EACR11Snorm:\n case WebGPUConstants.TextureFormat.EACRG11Unorm:\n case WebGPUConstants.TextureFormat.EACRG11Snorm:\n case WebGPUConstants.TextureFormat.ASTC4x4Unorm:\n case WebGPUConstants.TextureFormat.ASTC4x4UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC5x4Unorm:\n case WebGPUConstants.TextureFormat.ASTC5x4UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC5x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC5x5UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC6x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC6x5UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC6x6Unorm:\n case WebGPUConstants.TextureFormat.ASTC6x6UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC8x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC8x5UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC8x6Unorm:\n case WebGPUConstants.TextureFormat.ASTC8x6UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC8x8Unorm:\n case WebGPUConstants.TextureFormat.ASTC8x8UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC10x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x5UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC10x6Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x6UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC10x8Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x8UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC10x10Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x10UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC12x10Unorm:\n case WebGPUConstants.TextureFormat.ASTC12x10UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC12x12Unorm:\n case WebGPUConstants.TextureFormat.ASTC12x12UnormSRGB:\n return true;\n }\n return false;\n }\n static GetWebGPUTextureFormat(type, format, useSRGBBuffer = false) {\n switch (format) {\n case 15:\n return WebGPUConstants.TextureFormat.Depth16Unorm;\n case 16:\n return WebGPUConstants.TextureFormat.Depth24Plus;\n case 13:\n return WebGPUConstants.TextureFormat.Depth24PlusStencil8;\n case 14:\n return WebGPUConstants.TextureFormat.Depth32Float;\n case 17:\n return WebGPUConstants.TextureFormat.Depth24UnormStencil8;\n case 18:\n return WebGPUConstants.TextureFormat.Depth32FloatStencil8;\n case 19:\n return WebGPUConstants.TextureFormat.Stencil8;\n case 36492:\n return useSRGBBuffer ? WebGPUConstants.TextureFormat.BC7RGBAUnormSRGB : WebGPUConstants.TextureFormat.BC7RGBAUnorm;\n case 36495:\n return WebGPUConstants.TextureFormat.BC6HRGBUFloat;\n case 36494:\n return WebGPUConstants.TextureFormat.BC6HRGBFloat;\n case 33779:\n return useSRGBBuffer ? WebGPUConstants.TextureFormat.BC3RGBAUnormSRGB : WebGPUConstants.TextureFormat.BC3RGBAUnorm;\n case 33778:\n return useSRGBBuffer ? WebGPUConstants.TextureFormat.BC2RGBAUnormSRGB : WebGPUConstants.TextureFormat.BC2RGBAUnorm;\n case 33777:\n case 33776:\n return useSRGBBuffer ? WebGPUConstants.TextureFormat.BC1RGBAUnormSRGB : WebGPUConstants.TextureFormat.BC1RGBAUnorm;\n case 37808:\n return useSRGBBuffer ? WebGPUConstants.TextureFormat.ASTC4x4UnormSRGB : WebGPUConstants.TextureFormat.ASTC4x4Unorm;\n case 36196:\n case 37492:\n return useSRGBBuffer ? WebGPUConstants.TextureFormat.ETC2RGB8UnormSRGB : WebGPUConstants.TextureFormat.ETC2RGB8Unorm;\n case 37496:\n return useSRGBBuffer ? WebGPUConstants.TextureFormat.ETC2RGBA8UnormSRGB : WebGPUConstants.TextureFormat.ETC2RGBA8Unorm;\n }\n switch (type) {\n case 3:\n switch (format) {\n case 6:\n return WebGPUConstants.TextureFormat.R8Snorm;\n case 7:\n return WebGPUConstants.TextureFormat.RG8Snorm;\n case 4:\n throw \"RGB format not supported in WebGPU\";\n case 8:\n return WebGPUConstants.TextureFormat.R8Sint;\n case 9:\n return WebGPUConstants.TextureFormat.RG8Sint;\n case 10:\n throw \"RGB_INTEGER format not supported in WebGPU\";\n case 11:\n return WebGPUConstants.TextureFormat.RGBA8Sint;\n default:\n return WebGPUConstants.TextureFormat.RGBA8Snorm;\n }\n case 0:\n switch (format) {\n case 6:\n return WebGPUConstants.TextureFormat.R8Unorm;\n case 7:\n return WebGPUConstants.TextureFormat.RG8Unorm;\n case 4:\n throw \"TEXTUREFORMAT_RGB format not supported in WebGPU\";\n case 5:\n return useSRGBBuffer ? WebGPUConstants.TextureFormat.RGBA8UnormSRGB : WebGPUConstants.TextureFormat.RGBA8Unorm;\n case 12:\n return useSRGBBuffer ? WebGPUConstants.TextureFormat.BGRA8UnormSRGB : WebGPUConstants.TextureFormat.BGRA8Unorm;\n case 8:\n return WebGPUConstants.TextureFormat.R8Uint;\n case 9:\n return WebGPUConstants.TextureFormat.RG8Uint;\n case 10:\n throw \"RGB_INTEGER format not supported in WebGPU\";\n case 11:\n return WebGPUConstants.TextureFormat.RGBA8Uint;\n case 0:\n throw \"TEXTUREFORMAT_ALPHA format not supported in WebGPU\";\n case 1:\n throw \"TEXTUREFORMAT_LUMINANCE format not supported in WebGPU\";\n case 2:\n throw \"TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU\";\n default:\n return WebGPUConstants.TextureFormat.RGBA8Unorm;\n }\n case 4:\n switch (format) {\n case 8:\n return WebGPUConstants.TextureFormat.R16Sint;\n case 9:\n return WebGPUConstants.TextureFormat.RG16Sint;\n case 10:\n throw \"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU\";\n case 11:\n return WebGPUConstants.TextureFormat.RGBA16Sint;\n default:\n return WebGPUConstants.TextureFormat.RGBA16Sint;\n }\n case 5:\n switch (format) {\n case 8:\n return WebGPUConstants.TextureFormat.R16Uint;\n case 9:\n return WebGPUConstants.TextureFormat.RG16Uint;\n case 10:\n throw \"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU\";\n case 11:\n return WebGPUConstants.TextureFormat.RGBA16Uint;\n default:\n return WebGPUConstants.TextureFormat.RGBA16Uint;\n }\n case 6:\n switch (format) {\n case 8:\n return WebGPUConstants.TextureFormat.R32Sint;\n case 9:\n return WebGPUConstants.TextureFormat.RG32Sint;\n case 10:\n throw \"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU\";\n case 11:\n return WebGPUConstants.TextureFormat.RGBA32Sint;\n default:\n return WebGPUConstants.TextureFormat.RGBA32Sint;\n }\n case 7: // Refers to UNSIGNED_INT\n switch (format) {\n case 8:\n return WebGPUConstants.TextureFormat.R32Uint;\n case 9:\n return WebGPUConstants.TextureFormat.RG32Uint;\n case 10:\n throw \"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU\";\n case 11:\n return WebGPUConstants.TextureFormat.RGBA32Uint;\n default:\n return WebGPUConstants.TextureFormat.RGBA32Uint;\n }\n case 1:\n switch (format) {\n case 6:\n return WebGPUConstants.TextureFormat.R32Float; // By default. Other possibility is R16Float.\n case 7:\n return WebGPUConstants.TextureFormat.RG32Float; // By default. Other possibility is RG16Float.\n case 4:\n throw \"TEXTUREFORMAT_RGB format not supported in WebGPU\";\n case 5:\n return WebGPUConstants.TextureFormat.RGBA32Float; // By default. Other possibility is RGBA16Float.\n default:\n return WebGPUConstants.TextureFormat.RGBA32Float;\n }\n case 2:\n switch (format) {\n case 6:\n return WebGPUConstants.TextureFormat.R16Float;\n case 7:\n return WebGPUConstants.TextureFormat.RG16Float;\n case 4:\n throw \"TEXTUREFORMAT_RGB format not supported in WebGPU\";\n case 5:\n return WebGPUConstants.TextureFormat.RGBA16Float;\n default:\n return WebGPUConstants.TextureFormat.RGBA16Float;\n }\n case 10:\n throw \"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU\";\n case 13:\n switch (format) {\n case 5:\n return WebGPUConstants.TextureFormat.RG11B10UFloat;\n case 11:\n throw \"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV\";\n default:\n return WebGPUConstants.TextureFormat.RG11B10UFloat;\n }\n case 14:\n switch (format) {\n case 5:\n return WebGPUConstants.TextureFormat.RGB9E5UFloat;\n case 11:\n throw \"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV\";\n default:\n return WebGPUConstants.TextureFormat.RGB9E5UFloat;\n }\n case 8:\n throw \"TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU\";\n case 9:\n throw \"TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU\";\n case 11:\n switch (format) {\n case 5:\n return WebGPUConstants.TextureFormat.RGB10A2Unorm;\n case 11:\n throw \"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV\";\n default:\n return WebGPUConstants.TextureFormat.RGB10A2Unorm;\n }\n }\n return useSRGBBuffer ? WebGPUConstants.TextureFormat.RGBA8UnormSRGB : WebGPUConstants.TextureFormat.RGBA8Unorm;\n }\n static GetNumChannelsFromWebGPUTextureFormat(format) {\n switch (format) {\n case WebGPUConstants.TextureFormat.R8Unorm:\n case WebGPUConstants.TextureFormat.R8Snorm:\n case WebGPUConstants.TextureFormat.R8Uint:\n case WebGPUConstants.TextureFormat.R8Sint:\n case WebGPUConstants.TextureFormat.BC4RUnorm:\n case WebGPUConstants.TextureFormat.BC4RSnorm:\n case WebGPUConstants.TextureFormat.R16Uint:\n case WebGPUConstants.TextureFormat.R16Sint:\n case WebGPUConstants.TextureFormat.Depth16Unorm:\n case WebGPUConstants.TextureFormat.R16Float:\n case WebGPUConstants.TextureFormat.R32Uint:\n case WebGPUConstants.TextureFormat.R32Sint:\n case WebGPUConstants.TextureFormat.R32Float:\n case WebGPUConstants.TextureFormat.Depth32Float:\n case WebGPUConstants.TextureFormat.Stencil8:\n case WebGPUConstants.TextureFormat.Depth24Plus:\n case WebGPUConstants.TextureFormat.EACR11Unorm:\n case WebGPUConstants.TextureFormat.EACR11Snorm:\n return 1;\n case WebGPUConstants.TextureFormat.RG8Unorm:\n case WebGPUConstants.TextureFormat.RG8Snorm:\n case WebGPUConstants.TextureFormat.RG8Uint:\n case WebGPUConstants.TextureFormat.RG8Sint:\n case WebGPUConstants.TextureFormat.Depth24UnormStencil8: // composite format - let's say it's byte...\n case WebGPUConstants.TextureFormat.Depth32FloatStencil8: // composite format - let's say it's byte...\n case WebGPUConstants.TextureFormat.BC5RGUnorm:\n case WebGPUConstants.TextureFormat.BC5RGSnorm:\n case WebGPUConstants.TextureFormat.RG16Uint:\n case WebGPUConstants.TextureFormat.RG16Sint:\n case WebGPUConstants.TextureFormat.RG16Float:\n case WebGPUConstants.TextureFormat.RG32Uint:\n case WebGPUConstants.TextureFormat.RG32Sint:\n case WebGPUConstants.TextureFormat.RG32Float:\n case WebGPUConstants.TextureFormat.Depth24PlusStencil8:\n case WebGPUConstants.TextureFormat.EACRG11Unorm:\n case WebGPUConstants.TextureFormat.EACRG11Snorm:\n return 2;\n case WebGPUConstants.TextureFormat.RGB9E5UFloat: // composite format - let's say it's byte...\n case WebGPUConstants.TextureFormat.RG11B10UFloat: // composite format - let's say it's byte...\n case WebGPUConstants.TextureFormat.BC6HRGBUFloat:\n case WebGPUConstants.TextureFormat.BC6HRGBFloat:\n case WebGPUConstants.TextureFormat.ETC2RGB8Unorm:\n case WebGPUConstants.TextureFormat.ETC2RGB8UnormSRGB:\n return 3;\n case WebGPUConstants.TextureFormat.RGBA8Unorm:\n case WebGPUConstants.TextureFormat.RGBA8UnormSRGB:\n case WebGPUConstants.TextureFormat.RGBA8Snorm:\n case WebGPUConstants.TextureFormat.RGBA8Uint:\n case WebGPUConstants.TextureFormat.RGBA8Sint:\n case WebGPUConstants.TextureFormat.BGRA8Unorm:\n case WebGPUConstants.TextureFormat.BGRA8UnormSRGB:\n case WebGPUConstants.TextureFormat.RGB10A2Unorm: // composite format - let's say it's byte...\n case WebGPUConstants.TextureFormat.BC7RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC7RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.BC3RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC3RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.BC2RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC2RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.BC1RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC1RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.RGBA16Uint:\n case WebGPUConstants.TextureFormat.RGBA16Sint:\n case WebGPUConstants.TextureFormat.RGBA16Float:\n case WebGPUConstants.TextureFormat.RGBA32Uint:\n case WebGPUConstants.TextureFormat.RGBA32Sint:\n case WebGPUConstants.TextureFormat.RGBA32Float:\n case WebGPUConstants.TextureFormat.ETC2RGB8A1Unorm:\n case WebGPUConstants.TextureFormat.ETC2RGB8A1UnormSRGB:\n case WebGPUConstants.TextureFormat.ETC2RGBA8Unorm:\n case WebGPUConstants.TextureFormat.ETC2RGBA8UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC4x4Unorm:\n case WebGPUConstants.TextureFormat.ASTC4x4UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC5x4Unorm:\n case WebGPUConstants.TextureFormat.ASTC5x4UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC5x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC5x5UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC6x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC6x5UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC6x6Unorm:\n case WebGPUConstants.TextureFormat.ASTC6x6UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC8x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC8x5UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC8x6Unorm:\n case WebGPUConstants.TextureFormat.ASTC8x6UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC8x8Unorm:\n case WebGPUConstants.TextureFormat.ASTC8x8UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC10x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x5UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC10x6Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x6UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC10x8Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x8UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC10x10Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x10UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC12x10Unorm:\n case WebGPUConstants.TextureFormat.ASTC12x10UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC12x12Unorm:\n case WebGPUConstants.TextureFormat.ASTC12x12UnormSRGB:\n return 4;\n }\n throw `Unknown format ${format}!`;\n }\n static HasStencilAspect(format) {\n switch (format) {\n case WebGPUConstants.TextureFormat.Stencil8:\n case WebGPUConstants.TextureFormat.Depth24UnormStencil8:\n case WebGPUConstants.TextureFormat.Depth32FloatStencil8:\n case WebGPUConstants.TextureFormat.Depth24PlusStencil8:\n return true;\n }\n return false;\n }\n static HasDepthAndStencilAspects(format) {\n switch (format) {\n case WebGPUConstants.TextureFormat.Depth24UnormStencil8:\n case WebGPUConstants.TextureFormat.Depth32FloatStencil8:\n case WebGPUConstants.TextureFormat.Depth24PlusStencil8:\n return true;\n }\n return false;\n }\n static GetDepthFormatOnly(format) {\n switch (format) {\n case WebGPUConstants.TextureFormat.Depth16Unorm:\n return WebGPUConstants.TextureFormat.Depth16Unorm;\n case WebGPUConstants.TextureFormat.Depth24Plus:\n return WebGPUConstants.TextureFormat.Depth24Plus;\n case WebGPUConstants.TextureFormat.Depth24PlusStencil8:\n return WebGPUConstants.TextureFormat.Depth24Plus;\n case WebGPUConstants.TextureFormat.Depth24UnormStencil8:\n return WebGPUConstants.TextureFormat.Depth24Plus;\n case WebGPUConstants.TextureFormat.Depth32Float:\n return WebGPUConstants.TextureFormat.Depth32Float;\n case WebGPUConstants.TextureFormat.Depth32FloatStencil8:\n return WebGPUConstants.TextureFormat.Depth32Float;\n }\n return format;\n }\n copyVideoToTexture(video, texture, format, invertY = false, commandEncoder) {\n var _a, _b, _c, _d;\n const useOwnCommandEncoder = commandEncoder === undefined;\n const [pipeline, bindGroupLayout] = this._getVideoPipeline(format, invertY ? VideoPipelineType.InvertY : VideoPipelineType.DontInvertY);\n if (useOwnCommandEncoder) {\n commandEncoder = this._device.createCommandEncoder({});\n }\n (_b = (_a = commandEncoder).pushDebugGroup) === null || _b === void 0 ? void 0 : _b.call(_a, `copy video to texture - invertY=${invertY}`);\n const webgpuHardwareTexture = texture._hardwareTexture;\n const renderPassDescriptor = {\n colorAttachments: [\n {\n view: webgpuHardwareTexture.underlyingResource.createView({\n format,\n dimension: WebGPUConstants.TextureViewDimension.E2d,\n mipLevelCount: 1,\n baseArrayLayer: 0,\n baseMipLevel: 0,\n arrayLayerCount: 1,\n aspect: WebGPUConstants.TextureAspect.All,\n }),\n loadOp: WebGPUConstants.LoadOp.Load,\n storeOp: WebGPUConstants.StoreOp.Store,\n },\n ],\n };\n const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);\n const descriptor = {\n layout: bindGroupLayout,\n entries: [\n {\n binding: 0,\n resource: this._videoSampler,\n },\n {\n binding: 1,\n resource: this._device.importExternalTexture({\n source: video.underlyingResource,\n }),\n },\n ],\n };\n const bindGroup = this._device.createBindGroup(descriptor);\n passEncoder.setPipeline(pipeline);\n passEncoder.setBindGroup(0, bindGroup);\n passEncoder.draw(4, 1, 0, 0);\n passEncoder.end();\n (_d = (_c = commandEncoder).popDebugGroup) === null || _d === void 0 ? void 0 : _d.call(_c);\n if (useOwnCommandEncoder) {\n this._device.queue.submit([commandEncoder.finish()]);\n commandEncoder = null;\n }\n }\n invertYPreMultiplyAlpha(gpuOrHdwTexture, width, height, format, invertY = false, premultiplyAlpha = false, faceIndex = 0, mipLevel = 0, layers = 1, ofstX = 0, ofstY = 0, rectWidth = 0, rectHeight = 0, commandEncoder, \n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n allowGPUOptimization) {\n var _a, _b, _c, _d, _e, _f;\n const useRect = rectWidth !== 0;\n const useOwnCommandEncoder = commandEncoder === undefined;\n const [pipeline, bindGroupLayout] = this._getPipeline(format, useRect ? PipelineType.InvertYPremultiplyAlphaWithOfst : PipelineType.InvertYPremultiplyAlpha, {\n invertY,\n premultiplyAlpha,\n });\n faceIndex = Math.max(faceIndex, 0);\n if (useOwnCommandEncoder) {\n commandEncoder = this._device.createCommandEncoder({});\n }\n (_b = (_a = commandEncoder).pushDebugGroup) === null || _b === void 0 ? void 0 : _b.call(_a, `internal process texture - invertY=${invertY} premultiplyAlpha=${premultiplyAlpha}`);\n let gpuTexture;\n if (WebGPUTextureHelper._IsHardwareTexture(gpuOrHdwTexture)) {\n gpuTexture = gpuOrHdwTexture.underlyingResource;\n if (!(invertY && !premultiplyAlpha && layers === 1 && faceIndex === 0)) {\n // we optimize only for the most likely case (invertY=true, premultiplyAlpha=false, layers=1, faceIndex=0) to avoid dealing with big caches\n gpuOrHdwTexture = undefined;\n }\n }\n else {\n gpuTexture = gpuOrHdwTexture;\n gpuOrHdwTexture = undefined;\n }\n if (!gpuTexture) {\n return;\n }\n if (useRect) {\n this._bufferManager.setRawData(this._ubCopyWithOfst, 0, new Float32Array([ofstX, ofstY, rectWidth, rectHeight]), 0, 4 * 4);\n }\n const webgpuHardwareTexture = gpuOrHdwTexture;\n const outputTexture = (_c = webgpuHardwareTexture === null || webgpuHardwareTexture === void 0 ? void 0 : webgpuHardwareTexture._copyInvertYTempTexture) !== null && _c !== void 0 ? _c : this.createTexture({ width, height, layers: 1 }, false, false, false, false, false, format, 1, commandEncoder, WebGPUConstants.TextureUsage.CopySrc | WebGPUConstants.TextureUsage.RenderAttachment | WebGPUConstants.TextureUsage.TextureBinding, undefined, \"TempTextureForCopyWithInvertY\");\n const renderPassDescriptor = (_d = webgpuHardwareTexture === null || webgpuHardwareTexture === void 0 ? void 0 : webgpuHardwareTexture._copyInvertYRenderPassDescr) !== null && _d !== void 0 ? _d : {\n colorAttachments: [\n {\n view: outputTexture.createView({\n format,\n dimension: WebGPUConstants.TextureViewDimension.E2d,\n baseMipLevel: 0,\n mipLevelCount: 1,\n arrayLayerCount: 1,\n baseArrayLayer: 0,\n }),\n loadOp: WebGPUConstants.LoadOp.Load,\n storeOp: WebGPUConstants.StoreOp.Store,\n },\n ],\n };\n const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);\n let bindGroup = useRect ? webgpuHardwareTexture === null || webgpuHardwareTexture === void 0 ? void 0 : webgpuHardwareTexture._copyInvertYBindGroupWithOfst : webgpuHardwareTexture === null || webgpuHardwareTexture === void 0 ? void 0 : webgpuHardwareTexture._copyInvertYBindGroup;\n if (!bindGroup) {\n const descriptor = {\n layout: bindGroupLayout,\n entries: [\n {\n binding: 0,\n resource: gpuTexture.createView({\n format,\n dimension: WebGPUConstants.TextureViewDimension.E2d,\n baseMipLevel: mipLevel,\n mipLevelCount: 1,\n arrayLayerCount: layers,\n baseArrayLayer: faceIndex,\n }),\n },\n ],\n };\n if (useRect) {\n descriptor.entries.push({\n binding: 1,\n resource: {\n buffer: this._ubCopyWithOfst,\n },\n });\n }\n bindGroup = this._device.createBindGroup(descriptor);\n }\n passEncoder.setPipeline(pipeline);\n passEncoder.setBindGroup(0, bindGroup);\n passEncoder.draw(4, 1, 0, 0);\n passEncoder.end();\n commandEncoder.copyTextureToTexture({\n texture: outputTexture,\n }, {\n texture: gpuTexture,\n mipLevel,\n origin: {\n x: 0,\n y: 0,\n z: faceIndex,\n },\n }, {\n width,\n height,\n depthOrArrayLayers: 1,\n });\n if (webgpuHardwareTexture) {\n webgpuHardwareTexture._copyInvertYTempTexture = outputTexture;\n webgpuHardwareTexture._copyInvertYRenderPassDescr = renderPassDescriptor;\n if (useRect) {\n webgpuHardwareTexture._copyInvertYBindGroupWithOfst = bindGroup;\n }\n else {\n webgpuHardwareTexture._copyInvertYBindGroup = bindGroup;\n }\n }\n else {\n this._deferredReleaseTextures.push([outputTexture, null]);\n }\n (_f = (_e = commandEncoder).popDebugGroup) === null || _f === void 0 ? void 0 : _f.call(_e);\n if (useOwnCommandEncoder) {\n this._device.queue.submit([commandEncoder.finish()]);\n commandEncoder = null;\n }\n }\n copyWithInvertY(srcTextureView, format, renderPassDescriptor, commandEncoder) {\n var _a, _b, _c, _d;\n const useOwnCommandEncoder = commandEncoder === undefined;\n const [pipeline, bindGroupLayout] = this._getPipeline(format, PipelineType.InvertYPremultiplyAlpha, { invertY: true, premultiplyAlpha: false });\n if (useOwnCommandEncoder) {\n commandEncoder = this._device.createCommandEncoder({});\n }\n (_b = (_a = commandEncoder).pushDebugGroup) === null || _b === void 0 ? void 0 : _b.call(_a, `internal copy texture with invertY`);\n const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);\n const bindGroup = this._device.createBindGroup({\n layout: bindGroupLayout,\n entries: [\n {\n binding: 0,\n resource: srcTextureView,\n },\n ],\n });\n passEncoder.setPipeline(pipeline);\n passEncoder.setBindGroup(0, bindGroup);\n passEncoder.draw(4, 1, 0, 0);\n passEncoder.end();\n (_d = (_c = commandEncoder).popDebugGroup) === null || _d === void 0 ? void 0 : _d.call(_c);\n if (useOwnCommandEncoder) {\n this._device.queue.submit([commandEncoder.finish()]);\n commandEncoder = null;\n }\n }\n //------------------------------------------------------------------------------\n // Creation\n //------------------------------------------------------------------------------\n createTexture(imageBitmap, hasMipmaps = false, generateMipmaps = false, invertY = false, premultiplyAlpha = false, is3D = false, format = WebGPUConstants.TextureFormat.RGBA8Unorm, sampleCount = 1, commandEncoder, usage = -1, additionalUsages = 0, label) {\n if (sampleCount > 1) {\n // WebGPU only supports 1 or 4\n sampleCount = 4;\n }\n const layerCount = imageBitmap.layers || 1;\n const textureSize = {\n width: imageBitmap.width,\n height: imageBitmap.height,\n depthOrArrayLayers: layerCount,\n };\n const renderAttachmentFlag = renderableTextureFormatToIndex[format] ? WebGPUConstants.TextureUsage.RenderAttachment : 0;\n const isCompressedFormat = WebGPUTextureHelper.IsCompressedFormat(format);\n const mipLevelCount = hasMipmaps ? WebGPUTextureHelper.ComputeNumMipmapLevels(imageBitmap.width, imageBitmap.height) : 1;\n const usages = usage >= 0 ? usage : WebGPUConstants.TextureUsage.CopySrc | WebGPUConstants.TextureUsage.CopyDst | WebGPUConstants.TextureUsage.TextureBinding;\n additionalUsages |= hasMipmaps && !isCompressedFormat ? WebGPUConstants.TextureUsage.CopySrc | renderAttachmentFlag : 0;\n if (!isCompressedFormat && !is3D) {\n // we don't know in advance if the texture will be updated with copyExternalImageToTexture (which requires to have those flags), so we need to force the flags all the times\n additionalUsages |= renderAttachmentFlag | WebGPUConstants.TextureUsage.CopyDst;\n }\n const gpuTexture = this._device.createTexture({\n label: `Texture${is3D ? \"3D\" : \"2D\"}_${label ? label + \"_\" : \"\"}${textureSize.width}x${textureSize.height}x${textureSize.depthOrArrayLayers}_${hasMipmaps ? \"wmips\" : \"womips\"}_${format}_samples${sampleCount}`,\n size: textureSize,\n dimension: is3D ? WebGPUConstants.TextureDimension.E3d : WebGPUConstants.TextureDimension.E2d,\n format,\n usage: usages | additionalUsages,\n sampleCount,\n mipLevelCount,\n });\n if (WebGPUTextureHelper.IsImageBitmap(imageBitmap)) {\n this.updateTexture(imageBitmap, gpuTexture, imageBitmap.width, imageBitmap.height, layerCount, format, 0, 0, invertY, premultiplyAlpha, 0, 0);\n if (hasMipmaps && generateMipmaps) {\n this.generateMipmaps(gpuTexture, format, mipLevelCount, 0, commandEncoder);\n }\n }\n return gpuTexture;\n }\n createCubeTexture(imageBitmaps, hasMipmaps = false, generateMipmaps = false, invertY = false, premultiplyAlpha = false, format = WebGPUConstants.TextureFormat.RGBA8Unorm, sampleCount = 1, commandEncoder, usage = -1, additionalUsages = 0, label) {\n if (sampleCount > 1) {\n // WebGPU only supports 1 or 4\n sampleCount = 4;\n }\n const width = WebGPUTextureHelper.IsImageBitmapArray(imageBitmaps) ? imageBitmaps[0].width : imageBitmaps.width;\n const height = WebGPUTextureHelper.IsImageBitmapArray(imageBitmaps) ? imageBitmaps[0].height : imageBitmaps.height;\n const renderAttachmentFlag = renderableTextureFormatToIndex[format] ? WebGPUConstants.TextureUsage.RenderAttachment : 0;\n const isCompressedFormat = WebGPUTextureHelper.IsCompressedFormat(format);\n const mipLevelCount = hasMipmaps ? WebGPUTextureHelper.ComputeNumMipmapLevels(width, height) : 1;\n const usages = usage >= 0 ? usage : WebGPUConstants.TextureUsage.CopySrc | WebGPUConstants.TextureUsage.CopyDst | WebGPUConstants.TextureUsage.TextureBinding;\n additionalUsages |= hasMipmaps && !isCompressedFormat ? WebGPUConstants.TextureUsage.CopySrc | renderAttachmentFlag : 0;\n if (!isCompressedFormat) {\n // we don't know in advance if the texture will be updated with copyExternalImageToTexture (which requires to have those flags), so we need to force the flags all the times\n additionalUsages |= renderAttachmentFlag | WebGPUConstants.TextureUsage.CopyDst;\n }\n const gpuTexture = this._device.createTexture({\n label: `TextureCube_${label ? label + \"_\" : \"\"}${width}x${height}x6_${hasMipmaps ? \"wmips\" : \"womips\"}_${format}_samples${sampleCount}`,\n size: {\n width,\n height,\n depthOrArrayLayers: 6,\n },\n dimension: WebGPUConstants.TextureDimension.E2d,\n format,\n usage: usages | additionalUsages,\n sampleCount,\n mipLevelCount,\n });\n if (WebGPUTextureHelper.IsImageBitmapArray(imageBitmaps)) {\n this.updateCubeTextures(imageBitmaps, gpuTexture, width, height, format, invertY, premultiplyAlpha, 0, 0);\n if (hasMipmaps && generateMipmaps) {\n this.generateCubeMipmaps(gpuTexture, format, mipLevelCount, commandEncoder);\n }\n }\n return gpuTexture;\n }\n generateCubeMipmaps(gpuTexture, format, mipLevelCount, commandEncoder) {\n var _a, _b, _c, _d;\n const useOwnCommandEncoder = commandEncoder === undefined;\n if (useOwnCommandEncoder) {\n commandEncoder = this._device.createCommandEncoder({});\n }\n (_b = (_a = commandEncoder).pushDebugGroup) === null || _b === void 0 ? void 0 : _b.call(_a, `create cube mipmaps - ${mipLevelCount} levels`);\n for (let f = 0; f < 6; ++f) {\n this.generateMipmaps(gpuTexture, format, mipLevelCount, f, commandEncoder);\n }\n (_d = (_c = commandEncoder).popDebugGroup) === null || _d === void 0 ? void 0 : _d.call(_c);\n if (useOwnCommandEncoder) {\n this._device.queue.submit([commandEncoder.finish()]);\n commandEncoder = null;\n }\n }\n generateMipmaps(gpuOrHdwTexture, format, mipLevelCount, faceIndex = 0, commandEncoder) {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n const useOwnCommandEncoder = commandEncoder === undefined;\n const [pipeline, bindGroupLayout] = this._getPipeline(format);\n faceIndex = Math.max(faceIndex, 0);\n if (useOwnCommandEncoder) {\n commandEncoder = this._device.createCommandEncoder({});\n }\n (_b = (_a = commandEncoder).pushDebugGroup) === null || _b === void 0 ? void 0 : _b.call(_a, `create mipmaps for face #${faceIndex} - ${mipLevelCount} levels`);\n let gpuTexture;\n if (WebGPUTextureHelper._IsHardwareTexture(gpuOrHdwTexture)) {\n gpuTexture = gpuOrHdwTexture.underlyingResource;\n gpuOrHdwTexture._mipmapGenRenderPassDescr = gpuOrHdwTexture._mipmapGenRenderPassDescr || [];\n gpuOrHdwTexture._mipmapGenBindGroup = gpuOrHdwTexture._mipmapGenBindGroup || [];\n }\n else {\n gpuTexture = gpuOrHdwTexture;\n gpuOrHdwTexture = undefined;\n }\n if (!gpuTexture) {\n return;\n }\n const webgpuHardwareTexture = gpuOrHdwTexture;\n for (let i = 1; i < mipLevelCount; ++i) {\n const renderPassDescriptor = (_d = (_c = webgpuHardwareTexture === null || webgpuHardwareTexture === void 0 ? void 0 : webgpuHardwareTexture._mipmapGenRenderPassDescr[faceIndex]) === null || _c === void 0 ? void 0 : _c[i - 1]) !== null && _d !== void 0 ? _d : {\n colorAttachments: [\n {\n view: gpuTexture.createView({\n format,\n dimension: WebGPUConstants.TextureViewDimension.E2d,\n baseMipLevel: i,\n mipLevelCount: 1,\n arrayLayerCount: 1,\n baseArrayLayer: faceIndex,\n }),\n loadOp: WebGPUConstants.LoadOp.Load,\n storeOp: WebGPUConstants.StoreOp.Store,\n },\n ],\n };\n if (webgpuHardwareTexture) {\n webgpuHardwareTexture._mipmapGenRenderPassDescr[faceIndex] = webgpuHardwareTexture._mipmapGenRenderPassDescr[faceIndex] || [];\n webgpuHardwareTexture._mipmapGenRenderPassDescr[faceIndex][i - 1] = renderPassDescriptor;\n }\n const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);\n const bindGroup = (_f = (_e = webgpuHardwareTexture === null || webgpuHardwareTexture === void 0 ? void 0 : webgpuHardwareTexture._mipmapGenBindGroup[faceIndex]) === null || _e === void 0 ? void 0 : _e[i - 1]) !== null && _f !== void 0 ? _f : this._device.createBindGroup({\n layout: bindGroupLayout,\n entries: [\n {\n binding: 0,\n resource: this._mipmapSampler,\n },\n {\n binding: 1,\n resource: gpuTexture.createView({\n format,\n dimension: WebGPUConstants.TextureViewDimension.E2d,\n baseMipLevel: i - 1,\n mipLevelCount: 1,\n arrayLayerCount: 1,\n baseArrayLayer: faceIndex,\n }),\n },\n ],\n });\n if (webgpuHardwareTexture) {\n webgpuHardwareTexture._mipmapGenBindGroup[faceIndex] = webgpuHardwareTexture._mipmapGenBindGroup[faceIndex] || [];\n webgpuHardwareTexture._mipmapGenBindGroup[faceIndex][i - 1] = bindGroup;\n }\n passEncoder.setPipeline(pipeline);\n passEncoder.setBindGroup(0, bindGroup);\n passEncoder.draw(4, 1, 0, 0);\n passEncoder.end();\n }\n (_h = (_g = commandEncoder).popDebugGroup) === null || _h === void 0 ? void 0 : _h.call(_g);\n if (useOwnCommandEncoder) {\n this._device.queue.submit([commandEncoder.finish()]);\n commandEncoder = null;\n }\n }\n createGPUTextureForInternalTexture(texture, width, height, depth, creationFlags) {\n if (!texture._hardwareTexture) {\n texture._hardwareTexture = new WebGPUHardwareTexture();\n }\n if (width === undefined) {\n width = texture.width;\n }\n if (height === undefined) {\n height = texture.height;\n }\n if (depth === undefined) {\n depth = texture.depth;\n }\n const gpuTextureWrapper = texture._hardwareTexture;\n const isStorageTexture = ((creationFlags !== null && creationFlags !== void 0 ? creationFlags : 0) & 1) !== 0;\n gpuTextureWrapper.format = WebGPUTextureHelper.GetWebGPUTextureFormat(texture.type, texture.format, texture._useSRGBBuffer);\n gpuTextureWrapper.textureUsages =\n texture._source === InternalTextureSource.RenderTarget || texture.source === InternalTextureSource.MultiRenderTarget\n ? WebGPUConstants.TextureUsage.TextureBinding | WebGPUConstants.TextureUsage.CopySrc | WebGPUConstants.TextureUsage.RenderAttachment\n : texture._source === InternalTextureSource.DepthStencil\n ? WebGPUConstants.TextureUsage.TextureBinding | WebGPUConstants.TextureUsage.RenderAttachment\n : -1;\n gpuTextureWrapper.textureAdditionalUsages = isStorageTexture ? WebGPUConstants.TextureUsage.StorageBinding : 0;\n const hasMipMaps = texture.generateMipMaps;\n const layerCount = depth || 1;\n let mipmapCount;\n if (texture._maxLodLevel !== null) {\n mipmapCount = texture._maxLodLevel;\n }\n else {\n mipmapCount = hasMipMaps ? WebGPUTextureHelper.ComputeNumMipmapLevels(width, height) : 1;\n }\n if (texture.isCube) {\n const gpuTexture = this.createCubeTexture({ width, height }, texture.generateMipMaps, texture.generateMipMaps, texture.invertY, false, gpuTextureWrapper.format, 1, this._commandEncoderForCreation, gpuTextureWrapper.textureUsages, gpuTextureWrapper.textureAdditionalUsages, texture.label);\n gpuTextureWrapper.set(gpuTexture);\n gpuTextureWrapper.createView({\n format: WebGPUTextureHelper.GetDepthFormatOnly(gpuTextureWrapper.format),\n dimension: WebGPUConstants.TextureViewDimension.Cube,\n mipLevelCount: mipmapCount,\n baseArrayLayer: 0,\n baseMipLevel: 0,\n arrayLayerCount: 6,\n aspect: WebGPUTextureHelper.HasDepthAndStencilAspects(gpuTextureWrapper.format) ? WebGPUConstants.TextureAspect.DepthOnly : WebGPUConstants.TextureAspect.All,\n }, isStorageTexture);\n }\n else {\n const gpuTexture = this.createTexture({ width, height, layers: layerCount }, texture.generateMipMaps, texture.generateMipMaps, texture.invertY, false, texture.is3D, gpuTextureWrapper.format, 1, this._commandEncoderForCreation, gpuTextureWrapper.textureUsages, gpuTextureWrapper.textureAdditionalUsages, texture.label);\n gpuTextureWrapper.set(gpuTexture);\n gpuTextureWrapper.createView({\n format: WebGPUTextureHelper.GetDepthFormatOnly(gpuTextureWrapper.format),\n dimension: texture.is2DArray\n ? WebGPUConstants.TextureViewDimension.E2dArray\n : texture.is3D\n ? WebGPUConstants.TextureDimension.E3d\n : WebGPUConstants.TextureViewDimension.E2d,\n mipLevelCount: mipmapCount,\n baseArrayLayer: 0,\n baseMipLevel: 0,\n arrayLayerCount: texture.is3D ? 1 : layerCount,\n aspect: WebGPUTextureHelper.HasDepthAndStencilAspects(gpuTextureWrapper.format) ? WebGPUConstants.TextureAspect.DepthOnly : WebGPUConstants.TextureAspect.All,\n }, isStorageTexture);\n }\n texture.width = texture.baseWidth = width;\n texture.height = texture.baseHeight = height;\n texture.depth = texture.baseDepth = depth;\n this.createMSAATexture(texture, texture.samples);\n return gpuTextureWrapper;\n }\n createMSAATexture(texture, samples, releaseExisting = true, index = -1) {\n const gpuTextureWrapper = texture._hardwareTexture;\n if (releaseExisting) {\n gpuTextureWrapper === null || gpuTextureWrapper === void 0 ? void 0 : gpuTextureWrapper.releaseMSAATexture();\n }\n if (!gpuTextureWrapper || (samples !== null && samples !== void 0 ? samples : 1) <= 1) {\n return;\n }\n const width = texture.width;\n const height = texture.height;\n const gpuMSAATexture = this.createTexture({ width, height, layers: 1 }, false, false, false, false, false, gpuTextureWrapper.format, samples, this._commandEncoderForCreation, WebGPUConstants.TextureUsage.RenderAttachment, 0, texture.label ? \"MSAA\" + texture.label : undefined);\n gpuTextureWrapper.setMSAATexture(gpuMSAATexture, index);\n }\n //------------------------------------------------------------------------------\n // Update\n //------------------------------------------------------------------------------\n updateCubeTextures(imageBitmaps, gpuTexture, width, height, format, invertY = false, premultiplyAlpha = false, offsetX = 0, offsetY = 0) {\n const faces = [0, 3, 1, 4, 2, 5];\n for (let f = 0; f < faces.length; ++f) {\n const imageBitmap = imageBitmaps[faces[f]];\n this.updateTexture(imageBitmap, gpuTexture, width, height, 1, format, f, 0, invertY, premultiplyAlpha, offsetX, offsetY);\n }\n }\n // TODO WEBGPU handle data source not being in the same format than the destination texture?\n updateTexture(imageBitmap, texture, width, height, layers, format, faceIndex = 0, mipLevel = 0, invertY = false, premultiplyAlpha = false, offsetX = 0, offsetY = 0, allowGPUOptimization) {\n const gpuTexture = WebGPUTextureHelper._IsInternalTexture(texture) ? texture._hardwareTexture.underlyingResource : texture;\n const blockInformation = WebGPUTextureHelper._GetBlockInformationFromFormat(format);\n const gpuOrHdwTexture = WebGPUTextureHelper._IsInternalTexture(texture) ? texture._hardwareTexture : texture;\n const textureCopyView = {\n texture: gpuTexture,\n origin: {\n x: offsetX,\n y: offsetY,\n z: Math.max(faceIndex, 0),\n },\n mipLevel: mipLevel,\n premultipliedAlpha: premultiplyAlpha,\n };\n const textureExtent = {\n width: Math.ceil(width / blockInformation.width) * blockInformation.width,\n height: Math.ceil(height / blockInformation.height) * blockInformation.height,\n depthOrArrayLayers: layers || 1,\n };\n if (imageBitmap.byteLength !== undefined) {\n imageBitmap = imageBitmap;\n const bytesPerRow = Math.ceil(width / blockInformation.width) * blockInformation.length;\n const aligned = Math.ceil(bytesPerRow / 256) * 256 === bytesPerRow;\n if (aligned) {\n const commandEncoder = this._device.createCommandEncoder({});\n const buffer = this._bufferManager.createRawBuffer(imageBitmap.byteLength, WebGPUConstants.BufferUsage.MapWrite | WebGPUConstants.BufferUsage.CopySrc, true);\n const arrayBuffer = buffer.getMappedRange();\n new Uint8Array(arrayBuffer).set(imageBitmap);\n buffer.unmap();\n commandEncoder.copyBufferToTexture({\n buffer: buffer,\n offset: 0,\n bytesPerRow,\n rowsPerImage: height,\n }, textureCopyView, textureExtent);\n this._device.queue.submit([commandEncoder.finish()]);\n this._bufferManager.releaseBuffer(buffer);\n }\n else {\n this._device.queue.writeTexture(textureCopyView, imageBitmap, {\n offset: 0,\n bytesPerRow,\n rowsPerImage: height,\n }, textureExtent);\n }\n if (invertY || premultiplyAlpha) {\n if (WebGPUTextureHelper._IsInternalTexture(texture)) {\n const dontUseRect = offsetX === 0 && offsetY === 0 && width === texture.width && height === texture.height;\n this.invertYPreMultiplyAlpha(gpuOrHdwTexture, texture.width, texture.height, format, invertY, premultiplyAlpha, faceIndex, mipLevel, layers || 1, offsetX, offsetY, dontUseRect ? 0 : width, dontUseRect ? 0 : height, undefined, allowGPUOptimization);\n }\n else {\n // we should never take this code path\n throw \"updateTexture: Can't process the texture data because a GPUTexture was provided instead of an InternalTexture!\";\n }\n }\n }\n else {\n imageBitmap = imageBitmap;\n if (invertY) {\n textureCopyView.premultipliedAlpha = false; // we are going to handle premultiplyAlpha ourselves\n // we must preprocess the image\n if (WebGPUTextureHelper._IsInternalTexture(texture) && offsetX === 0 && offsetY === 0 && width === texture.width && height === texture.height) {\n // optimization when the source image is the same size than the destination texture and offsets X/Y == 0:\n // we simply copy the source to the destination and we apply the preprocessing on the destination\n this._device.queue.copyExternalImageToTexture({ source: imageBitmap }, textureCopyView, textureExtent);\n this.invertYPreMultiplyAlpha(gpuOrHdwTexture, width, height, format, invertY, premultiplyAlpha, faceIndex, mipLevel, layers || 1, 0, 0, 0, 0, undefined, allowGPUOptimization);\n }\n else {\n // we must apply the preprocessing on the source image before copying it into the destination texture\n const commandEncoder = this._device.createCommandEncoder({});\n // create a temp texture and copy the image to it\n const srcTexture = this.createTexture({ width, height, layers: 1 }, false, false, false, false, false, format, 1, commandEncoder, WebGPUConstants.TextureUsage.CopySrc | WebGPUConstants.TextureUsage.TextureBinding, undefined, \"TempTextureForUpdateTexture\");\n this._deferredReleaseTextures.push([srcTexture, null]);\n textureExtent.depthOrArrayLayers = 1;\n this._device.queue.copyExternalImageToTexture({ source: imageBitmap }, { texture: srcTexture }, textureExtent);\n textureExtent.depthOrArrayLayers = layers || 1;\n // apply the preprocessing to this temp texture\n this.invertYPreMultiplyAlpha(srcTexture, width, height, format, invertY, premultiplyAlpha, faceIndex, mipLevel, layers || 1, 0, 0, 0, 0, commandEncoder, allowGPUOptimization);\n // copy the temp texture to the destination texture\n commandEncoder.copyTextureToTexture({ texture: srcTexture }, textureCopyView, textureExtent);\n this._device.queue.submit([commandEncoder.finish()]);\n }\n }\n else {\n // no preprocessing: direct copy to destination texture\n this._device.queue.copyExternalImageToTexture({ source: imageBitmap }, textureCopyView, textureExtent);\n }\n }\n }\n readPixels(texture, x, y, width, height, format, faceIndex = 0, mipLevel = 0, buffer = null, noDataConversion = false) {\n const blockInformation = WebGPUTextureHelper._GetBlockInformationFromFormat(format);\n const bytesPerRow = Math.ceil(width / blockInformation.width) * blockInformation.length;\n const bytesPerRowAligned = Math.ceil(bytesPerRow / 256) * 256;\n const size = bytesPerRowAligned * height;\n const gpuBuffer = this._bufferManager.createRawBuffer(size, WebGPUConstants.BufferUsage.MapRead | WebGPUConstants.BufferUsage.CopyDst);\n const commandEncoder = this._device.createCommandEncoder({});\n commandEncoder.copyTextureToBuffer({\n texture,\n mipLevel,\n origin: {\n x,\n y,\n z: Math.max(faceIndex, 0),\n },\n }, {\n buffer: gpuBuffer,\n offset: 0,\n bytesPerRow: bytesPerRowAligned,\n }, {\n width,\n height,\n depthOrArrayLayers: 1,\n });\n this._device.queue.submit([commandEncoder.finish()]);\n return this._bufferManager.readDataFromBuffer(gpuBuffer, size, width, height, bytesPerRow, bytesPerRowAligned, WebGPUTextureHelper._GetTextureTypeFromFormat(format), 0, buffer, true, noDataConversion);\n }\n //------------------------------------------------------------------------------\n // Dispose\n //------------------------------------------------------------------------------\n releaseTexture(texture) {\n if (WebGPUTextureHelper._IsInternalTexture(texture)) {\n const hardwareTexture = texture._hardwareTexture;\n const irradianceTexture = texture._irradianceTexture;\n // We can't destroy the objects just now because they could be used in the current frame - we delay the destroying after the end of the frame\n this._deferredReleaseTextures.push([hardwareTexture, irradianceTexture]);\n }\n else {\n this._deferredReleaseTextures.push([texture, null]);\n }\n }\n destroyDeferredTextures() {\n for (let i = 0; i < this._deferredReleaseTextures.length; ++i) {\n const [hardwareTexture, irradianceTexture] = this._deferredReleaseTextures[i];\n if (hardwareTexture) {\n if (WebGPUTextureHelper._IsHardwareTexture(hardwareTexture)) {\n hardwareTexture.release();\n }\n else {\n hardwareTexture.destroy();\n }\n }\n irradianceTexture === null || irradianceTexture === void 0 ? void 0 : irradianceTexture.dispose();\n }\n this._deferredReleaseTextures.length = 0;\n }\n}\n//# sourceMappingURL=webgpuTextureHelper.js.map","import { DataBuffer } from \"../../Buffers/dataBuffer.js\";\n/** @internal */\nexport class WebGPUDataBuffer extends DataBuffer {\n constructor(resource, capacity = 0) {\n super();\n this.capacity = capacity;\n this._buffer = resource;\n }\n get underlyingResource() {\n return this._buffer;\n }\n}\n//# sourceMappingURL=webgpuDataBuffer.js.map","import { WebGPUDataBuffer } from \"../../Meshes/WebGPU/webgpuDataBuffer.js\";\nimport { FromHalfFloat } from \"../../Misc/textureTools.js\";\n\nimport { allocateAndCopyTypedBuffer } from \"../Extensions/engine.readTexture.js\";\nimport * as WebGPUConstants from \"./webgpuConstants.js\";\n/** @internal */\nexport class WebGPUBufferManager {\n static _IsGPUBuffer(buffer) {\n return buffer.underlyingResource === undefined;\n }\n constructor(device) {\n this._deferredReleaseBuffers = [];\n this._device = device;\n }\n createRawBuffer(viewOrSize, flags, mappedAtCreation = false) {\n const alignedLength = viewOrSize.byteLength !== undefined ? (viewOrSize.byteLength + 3) & ~3 : (viewOrSize + 3) & ~3; // 4 bytes alignments (because of the upload which requires this)\n const verticesBufferDescriptor = {\n mappedAtCreation,\n size: alignedLength,\n usage: flags,\n };\n return this._device.createBuffer(verticesBufferDescriptor);\n }\n createBuffer(viewOrSize, flags) {\n const isView = viewOrSize.byteLength !== undefined;\n const buffer = this.createRawBuffer(viewOrSize, flags);\n const dataBuffer = new WebGPUDataBuffer(buffer);\n dataBuffer.references = 1;\n dataBuffer.capacity = isView ? viewOrSize.byteLength : viewOrSize;\n if (isView) {\n this.setSubData(dataBuffer, 0, viewOrSize);\n }\n return dataBuffer;\n }\n setRawData(buffer, dstByteOffset, src, srcByteOffset, byteLength) {\n this._device.queue.writeBuffer(buffer, dstByteOffset, src.buffer, srcByteOffset, byteLength);\n }\n setSubData(dataBuffer, dstByteOffset, src, srcByteOffset = 0, byteLength = 0) {\n const buffer = dataBuffer.underlyingResource;\n byteLength = byteLength || src.byteLength;\n byteLength = Math.min(byteLength, dataBuffer.capacity - dstByteOffset);\n // After Migration to Canary\n let chunkStart = src.byteOffset + srcByteOffset;\n let chunkEnd = chunkStart + byteLength;\n // 4 bytes alignments for upload\n const alignedLength = (byteLength + 3) & ~3;\n if (alignedLength !== byteLength) {\n const tempView = new Uint8Array(src.buffer.slice(chunkStart, chunkEnd));\n src = new Uint8Array(alignedLength);\n src.set(tempView);\n srcByteOffset = 0;\n chunkStart = 0;\n chunkEnd = alignedLength;\n byteLength = alignedLength;\n }\n // Chunk\n const maxChunk = 1024 * 1024 * 15;\n let offset = 0;\n while (chunkEnd - (chunkStart + offset) > maxChunk) {\n this._device.queue.writeBuffer(buffer, dstByteOffset + offset, src.buffer, chunkStart + offset, maxChunk);\n offset += maxChunk;\n }\n this._device.queue.writeBuffer(buffer, dstByteOffset + offset, src.buffer, chunkStart + offset, byteLength - offset);\n }\n _getHalfFloatAsFloatRGBAArrayBuffer(dataLength, arrayBuffer, destArray) {\n if (!destArray) {\n destArray = new Float32Array(dataLength);\n }\n const srcData = new Uint16Array(arrayBuffer);\n while (dataLength--) {\n destArray[dataLength] = FromHalfFloat(srcData[dataLength]);\n }\n return destArray;\n }\n readDataFromBuffer(gpuBuffer, size, width, height, bytesPerRow, bytesPerRowAligned, type = 0, offset = 0, buffer = null, destroyBuffer = true, noDataConversion = false) {\n const floatFormat = type === 1 ? 2 : type === 2 ? 1 : 0;\n return new Promise((resolve, reject) => {\n gpuBuffer.mapAsync(WebGPUConstants.MapMode.Read, offset, size).then(() => {\n const copyArrayBuffer = gpuBuffer.getMappedRange(offset, size);\n let data = buffer;\n if (noDataConversion) {\n if (data === null) {\n data = allocateAndCopyTypedBuffer(type, size, true, copyArrayBuffer);\n }\n else {\n data = allocateAndCopyTypedBuffer(type, data.buffer, undefined, copyArrayBuffer);\n }\n }\n else {\n if (data === null) {\n switch (floatFormat) {\n case 0: // byte format\n data = new Uint8Array(size);\n data.set(new Uint8Array(copyArrayBuffer));\n break;\n case 1: // half float\n // TODO WEBGPU use computer shaders (or render pass) to make the conversion?\n data = this._getHalfFloatAsFloatRGBAArrayBuffer(size / 2, copyArrayBuffer);\n break;\n case 2: // float\n data = new Float32Array(size / 4);\n data.set(new Float32Array(copyArrayBuffer));\n break;\n }\n }\n else {\n switch (floatFormat) {\n case 0: // byte format\n data = new Uint8Array(data.buffer);\n data.set(new Uint8Array(copyArrayBuffer));\n break;\n case 1: // half float\n // TODO WEBGPU use computer shaders (or render pass) to make the conversion?\n data = this._getHalfFloatAsFloatRGBAArrayBuffer(size / 2, copyArrayBuffer, buffer);\n break;\n case 2: // float\n data = new Float32Array(data.buffer);\n data.set(new Float32Array(copyArrayBuffer));\n break;\n }\n }\n }\n if (bytesPerRow !== bytesPerRowAligned) {\n // TODO WEBGPU use computer shaders (or render pass) to build the final buffer data?\n if (floatFormat === 1 && !noDataConversion) {\n // half float have been converted to float above\n bytesPerRow *= 2;\n bytesPerRowAligned *= 2;\n }\n const data2 = new Uint8Array(data.buffer);\n let offset = bytesPerRow, offset2 = 0;\n for (let y = 1; y < height; ++y) {\n offset2 = y * bytesPerRowAligned;\n for (let x = 0; x < bytesPerRow; ++x) {\n data2[offset++] = data2[offset2++];\n }\n }\n if (floatFormat !== 0 && !noDataConversion) {\n data = new Float32Array(data2.buffer, 0, offset / 4);\n }\n else {\n data = new Uint8Array(data2.buffer, 0, offset);\n }\n }\n gpuBuffer.unmap();\n if (destroyBuffer) {\n this.releaseBuffer(gpuBuffer);\n }\n resolve(data);\n }, (reason) => reject(reason));\n });\n }\n releaseBuffer(buffer) {\n if (WebGPUBufferManager._IsGPUBuffer(buffer)) {\n this._deferredReleaseBuffers.push(buffer);\n return true;\n }\n buffer.references--;\n if (buffer.references === 0) {\n this._deferredReleaseBuffers.push(buffer.underlyingResource);\n return true;\n }\n return false;\n }\n destroyDeferredBuffers() {\n for (let i = 0; i < this._deferredReleaseBuffers.length; ++i) {\n this._deferredReleaseBuffers[i].destroy();\n }\n this._deferredReleaseBuffers.length = 0;\n }\n}\n//# sourceMappingURL=webgpuBufferManager.js.map","/** @internal */\nexport class WebGPURenderPassWrapper {\n constructor() {\n this.colorAttachmentGPUTextures = [];\n this.reset();\n }\n reset(fullReset = false) {\n this.renderPass = null;\n if (fullReset) {\n this.renderPassDescriptor = null;\n this.colorAttachmentViewDescriptor = null;\n this.depthAttachmentViewDescriptor = null;\n this.colorAttachmentGPUTextures = [];\n this.depthTextureFormat = undefined;\n }\n }\n}\n//# sourceMappingURL=webgpuRenderPassWrapper.js.map","import * as WebGPUConstants from \"./webgpuConstants.js\";\n\nconst filterToBits = [\n 0 | (0 << 1) | (0 << 2),\n 0 | (0 << 1) | (0 << 2),\n 1 | (1 << 1) | (0 << 2),\n 1 | (1 << 1) | (1 << 2),\n 0 | (0 << 1) | (0 << 2),\n 0 | (1 << 1) | (0 << 2),\n 0 | (1 << 1) | (1 << 2),\n 0 | (1 << 1) | (0 << 2),\n 0 | (0 << 1) | (1 << 2),\n 1 | (0 << 1) | (0 << 2),\n 1 | (0 << 1) | (1 << 2),\n 1 | (1 << 1) | (0 << 2),\n 1 | (0 << 1) | (0 << 2), // TEXTURE_LINEAR_NEAREST\n];\n// subtract 0x01FF from the comparison function value before indexing this array!\nconst comparisonFunctionToBits = [\n (0 << 3) | (0 << 4) | (0 << 5) | (0 << 6),\n (0 << 3) | (0 << 4) | (0 << 5) | (1 << 6),\n (0 << 3) | (0 << 4) | (1 << 5) | (0 << 6),\n (0 << 3) | (0 << 4) | (1 << 5) | (1 << 6),\n (0 << 3) | (1 << 4) | (0 << 5) | (0 << 6),\n (0 << 3) | (1 << 4) | (0 << 5) | (1 << 6),\n (0 << 3) | (1 << 4) | (1 << 5) | (0 << 6),\n (0 << 3) | (1 << 4) | (1 << 5) | (1 << 6),\n (1 << 3) | (0 << 4) | (0 << 5) | (0 << 6), // ALWAYS\n];\nconst filterNoMipToBits = [\n 0 << 7,\n 1 << 7,\n 1 << 7,\n 0 << 7,\n 0 << 7,\n 0 << 7,\n 0 << 7,\n 1 << 7,\n 0 << 7,\n 0 << 7,\n 0 << 7,\n 0 << 7,\n 1 << 7, // TEXTURE_LINEAR_NEAREST\n];\n/** @internal */\nexport class WebGPUCacheSampler {\n constructor(device) {\n this._samplers = {};\n this._device = device;\n this.disabled = false;\n }\n static GetSamplerHashCode(sampler) {\n var _a, _b, _c;\n // The WebGPU spec currently only allows values 1 and 4 for anisotropy\n const anisotropy = sampler._cachedAnisotropicFilteringLevel && sampler._cachedAnisotropicFilteringLevel > 1 ? 4 : 1;\n const code = filterToBits[sampler.samplingMode] +\n comparisonFunctionToBits[(sampler._comparisonFunction || 0x0202) - 0x0200 + 1] +\n filterNoMipToBits[sampler.samplingMode] + // handle the lodMinClamp = lodMaxClamp = 0 case when no filter used for mip mapping\n (((_a = sampler._cachedWrapU) !== null && _a !== void 0 ? _a : 1) << 8) +\n (((_b = sampler._cachedWrapV) !== null && _b !== void 0 ? _b : 1) << 10) +\n (((_c = sampler._cachedWrapR) !== null && _c !== void 0 ? _c : 1) << 12) +\n ((sampler.useMipMaps ? 1 : 0) << 14) + // need to factor this in because _getSamplerFilterDescriptor depends on samplingMode AND useMipMaps!\n (anisotropy << 15);\n return code;\n }\n static _GetSamplerFilterDescriptor(sampler, anisotropy) {\n let magFilter, minFilter, mipmapFilter, lodMinClamp, lodMaxClamp;\n const useMipMaps = sampler.useMipMaps;\n switch (sampler.samplingMode) {\n case 11:\n magFilter = WebGPUConstants.FilterMode.Linear;\n minFilter = WebGPUConstants.FilterMode.Linear;\n mipmapFilter = WebGPUConstants.FilterMode.Nearest;\n if (!useMipMaps) {\n lodMinClamp = lodMaxClamp = 0;\n }\n break;\n case 3:\n case 3:\n magFilter = WebGPUConstants.FilterMode.Linear;\n minFilter = WebGPUConstants.FilterMode.Linear;\n if (!useMipMaps) {\n mipmapFilter = WebGPUConstants.FilterMode.Nearest;\n lodMinClamp = lodMaxClamp = 0;\n }\n else {\n mipmapFilter = WebGPUConstants.FilterMode.Linear;\n }\n break;\n case 8:\n magFilter = WebGPUConstants.FilterMode.Nearest;\n minFilter = WebGPUConstants.FilterMode.Nearest;\n if (!useMipMaps) {\n mipmapFilter = WebGPUConstants.FilterMode.Nearest;\n lodMinClamp = lodMaxClamp = 0;\n }\n else {\n mipmapFilter = WebGPUConstants.FilterMode.Linear;\n }\n break;\n case 4:\n magFilter = WebGPUConstants.FilterMode.Nearest;\n minFilter = WebGPUConstants.FilterMode.Nearest;\n mipmapFilter = WebGPUConstants.FilterMode.Nearest;\n if (!useMipMaps) {\n lodMinClamp = lodMaxClamp = 0;\n }\n break;\n case 5:\n magFilter = WebGPUConstants.FilterMode.Nearest;\n minFilter = WebGPUConstants.FilterMode.Linear;\n mipmapFilter = WebGPUConstants.FilterMode.Nearest;\n if (!useMipMaps) {\n lodMinClamp = lodMaxClamp = 0;\n }\n break;\n case 6:\n magFilter = WebGPUConstants.FilterMode.Nearest;\n minFilter = WebGPUConstants.FilterMode.Linear;\n if (!useMipMaps) {\n mipmapFilter = WebGPUConstants.FilterMode.Nearest;\n lodMinClamp = lodMaxClamp = 0;\n }\n else {\n mipmapFilter = WebGPUConstants.FilterMode.Linear;\n }\n break;\n case 7:\n magFilter = WebGPUConstants.FilterMode.Nearest;\n minFilter = WebGPUConstants.FilterMode.Linear;\n mipmapFilter = WebGPUConstants.FilterMode.Nearest;\n lodMinClamp = lodMaxClamp = 0;\n break;\n case 1:\n case 1:\n magFilter = WebGPUConstants.FilterMode.Nearest;\n minFilter = WebGPUConstants.FilterMode.Nearest;\n mipmapFilter = WebGPUConstants.FilterMode.Nearest;\n lodMinClamp = lodMaxClamp = 0;\n break;\n case 9:\n magFilter = WebGPUConstants.FilterMode.Linear;\n minFilter = WebGPUConstants.FilterMode.Nearest;\n mipmapFilter = WebGPUConstants.FilterMode.Nearest;\n if (!useMipMaps) {\n lodMinClamp = lodMaxClamp = 0;\n }\n break;\n case 10:\n magFilter = WebGPUConstants.FilterMode.Linear;\n minFilter = WebGPUConstants.FilterMode.Nearest;\n if (!useMipMaps) {\n mipmapFilter = WebGPUConstants.FilterMode.Nearest;\n lodMinClamp = lodMaxClamp = 0;\n }\n else {\n mipmapFilter = WebGPUConstants.FilterMode.Linear;\n }\n break;\n case 2:\n case 2:\n magFilter = WebGPUConstants.FilterMode.Linear;\n minFilter = WebGPUConstants.FilterMode.Linear;\n mipmapFilter = WebGPUConstants.FilterMode.Nearest;\n lodMinClamp = lodMaxClamp = 0;\n break;\n case 12:\n magFilter = WebGPUConstants.FilterMode.Linear;\n minFilter = WebGPUConstants.FilterMode.Nearest;\n mipmapFilter = WebGPUConstants.FilterMode.Nearest;\n lodMinClamp = lodMaxClamp = 0;\n break;\n default:\n magFilter = WebGPUConstants.FilterMode.Nearest;\n minFilter = WebGPUConstants.FilterMode.Nearest;\n mipmapFilter = WebGPUConstants.FilterMode.Nearest;\n lodMinClamp = lodMaxClamp = 0;\n break;\n }\n if (anisotropy > 1 && (lodMinClamp !== 0 || lodMaxClamp !== 0)) {\n return {\n magFilter: WebGPUConstants.FilterMode.Linear,\n minFilter: WebGPUConstants.FilterMode.Linear,\n mipmapFilter: WebGPUConstants.FilterMode.Linear,\n anisotropyEnabled: true,\n };\n }\n return {\n magFilter,\n minFilter,\n mipmapFilter,\n lodMinClamp,\n lodMaxClamp,\n };\n }\n static _GetWrappingMode(mode) {\n switch (mode) {\n case 1:\n return WebGPUConstants.AddressMode.Repeat;\n case 0:\n return WebGPUConstants.AddressMode.ClampToEdge;\n case 2:\n return WebGPUConstants.AddressMode.MirrorRepeat;\n }\n return WebGPUConstants.AddressMode.Repeat;\n }\n static _GetSamplerWrappingDescriptor(sampler) {\n return {\n addressModeU: this._GetWrappingMode(sampler._cachedWrapU),\n addressModeV: this._GetWrappingMode(sampler._cachedWrapV),\n addressModeW: this._GetWrappingMode(sampler._cachedWrapR),\n };\n }\n static _GetSamplerDescriptor(sampler) {\n // The WebGPU spec currently only allows values 1 and 4 for anisotropy\n const anisotropy = sampler.useMipMaps && sampler._cachedAnisotropicFilteringLevel && sampler._cachedAnisotropicFilteringLevel > 1 ? 4 : 1;\n const filterDescriptor = this._GetSamplerFilterDescriptor(sampler, anisotropy);\n return Object.assign(Object.assign(Object.assign({}, filterDescriptor), this._GetSamplerWrappingDescriptor(sampler)), { compare: sampler._comparisonFunction ? WebGPUCacheSampler.GetCompareFunction(sampler._comparisonFunction) : undefined, maxAnisotropy: filterDescriptor.anisotropyEnabled ? anisotropy : 1 });\n }\n static GetCompareFunction(compareFunction) {\n switch (compareFunction) {\n case 519:\n return WebGPUConstants.CompareFunction.Always;\n case 514:\n return WebGPUConstants.CompareFunction.Equal;\n case 516:\n return WebGPUConstants.CompareFunction.Greater;\n case 518:\n return WebGPUConstants.CompareFunction.GreaterEqual;\n case 513:\n return WebGPUConstants.CompareFunction.Less;\n case 515:\n return WebGPUConstants.CompareFunction.LessEqual;\n case 512:\n return WebGPUConstants.CompareFunction.Never;\n case 517:\n return WebGPUConstants.CompareFunction.NotEqual;\n default:\n return WebGPUConstants.CompareFunction.Less;\n }\n }\n getSampler(sampler, bypassCache = false, hash = 0) {\n if (this.disabled) {\n return this._device.createSampler(WebGPUCacheSampler._GetSamplerDescriptor(sampler));\n }\n if (bypassCache) {\n hash = 0;\n }\n else if (hash === 0) {\n hash = WebGPUCacheSampler.GetSamplerHashCode(sampler);\n }\n let gpuSampler = bypassCache ? undefined : this._samplers[hash];\n if (!gpuSampler) {\n gpuSampler = this._device.createSampler(WebGPUCacheSampler._GetSamplerDescriptor(sampler));\n if (!bypassCache) {\n this._samplers[hash] = gpuSampler;\n }\n }\n return gpuSampler;\n }\n}\n//# sourceMappingURL=webgpuCacheSampler.js.map","/* eslint-disable @typescript-eslint/naming-convention */\n\nimport * as WebGPUConstants from \"./webgpuConstants.js\";\nimport { VertexBuffer } from \"../../Buffers/buffer.js\";\nimport { WebGPUShaderProcessor } from \"./webgpuShaderProcessor.js\";\nimport { renderableTextureFormatToIndex, WebGPUTextureHelper } from \"./webgpuTextureHelper.js\";\nvar StatePosition;\n(function (StatePosition) {\n StatePosition[StatePosition[\"StencilReadMask\"] = 0] = \"StencilReadMask\";\n StatePosition[StatePosition[\"StencilWriteMask\"] = 1] = \"StencilWriteMask\";\n //DepthBiasClamp = 1, // not used, so remove it to improve perf\n StatePosition[StatePosition[\"DepthBias\"] = 2] = \"DepthBias\";\n StatePosition[StatePosition[\"DepthBiasSlopeScale\"] = 3] = \"DepthBiasSlopeScale\";\n StatePosition[StatePosition[\"DepthStencilState\"] = 4] = \"DepthStencilState\";\n StatePosition[StatePosition[\"MRTAttachments1\"] = 5] = \"MRTAttachments1\";\n StatePosition[StatePosition[\"MRTAttachments2\"] = 6] = \"MRTAttachments2\";\n StatePosition[StatePosition[\"RasterizationState\"] = 7] = \"RasterizationState\";\n StatePosition[StatePosition[\"ColorStates\"] = 8] = \"ColorStates\";\n StatePosition[StatePosition[\"ShaderStage\"] = 9] = \"ShaderStage\";\n StatePosition[StatePosition[\"TextureStage\"] = 10] = \"TextureStage\";\n StatePosition[StatePosition[\"VertexState\"] = 11] = \"VertexState\";\n StatePosition[StatePosition[\"NumStates\"] = 12] = \"NumStates\";\n})(StatePosition || (StatePosition = {}));\nconst alphaBlendFactorToIndex = {\n 0: 1,\n 1: 2,\n 0x0300: 3,\n 0x0301: 4,\n 0x0302: 5,\n 0x0303: 6,\n 0x0304: 7,\n 0x0305: 8,\n 0x0306: 9,\n 0x0307: 10,\n 0x0308: 11,\n 0x8001: 12,\n 0x8002: 13,\n 0x8003: 12,\n 0x8004: 13, // OneMinusBlendColor (alpha)\n};\nconst stencilOpToIndex = {\n 0x0000: 0,\n 0x1e00: 1,\n 0x1e01: 2,\n 0x1e02: 3,\n 0x1e03: 4,\n 0x150a: 5,\n 0x8507: 6,\n 0x8508: 7, // DECR_WRAP\n};\n/** @internal */\nexport class WebGPUCacheRenderPipeline {\n constructor(device, emptyVertexBuffer, useTextureStage) {\n this.mrtTextureCount = 0;\n this._device = device;\n this._useTextureStage = useTextureStage;\n this._states = new Array(30); // pre-allocate enough room so that no new allocation will take place afterwards\n this._statesLength = 0;\n this._stateDirtyLowestIndex = 0;\n this._emptyVertexBuffer = emptyVertexBuffer;\n this._mrtFormats = [];\n this._parameter = { token: undefined, pipeline: null };\n this.disabled = false;\n this.vertexBuffers = [];\n this._kMaxVertexBufferStride = device.limits.maxVertexBufferArrayStride || 2048;\n this.reset();\n }\n reset() {\n this._isDirty = true;\n this.vertexBuffers.length = 0;\n this.setAlphaToCoverage(false);\n this.resetDepthCullingState();\n this.setClampDepth(false);\n this.setDepthBias(0);\n //this.setDepthBiasClamp(0);\n this._webgpuColorFormat = [WebGPUConstants.TextureFormat.BGRA8Unorm];\n this.setColorFormat(WebGPUConstants.TextureFormat.BGRA8Unorm);\n this.setMRT([]);\n this.setAlphaBlendEnabled(false);\n this.setAlphaBlendFactors([null, null, null, null], [null, null]);\n this.setWriteMask(0xf);\n this.setDepthStencilFormat(WebGPUConstants.TextureFormat.Depth24PlusStencil8);\n this.setStencilEnabled(false);\n this.resetStencilState();\n this.setBuffers(null, null, null);\n this._setTextureState(0);\n }\n get colorFormats() {\n return this._mrtAttachments1 > 0 ? this._mrtFormats : this._webgpuColorFormat;\n }\n getRenderPipeline(fillMode, effect, sampleCount, textureState = 0) {\n if (sampleCount > 1) {\n // WebGPU only supports 1 or 4\n sampleCount = 4;\n }\n if (this.disabled) {\n const topology = WebGPUCacheRenderPipeline._GetTopology(fillMode);\n this._setVertexState(effect); // to fill this.vertexBuffers with correct data\n this._setTextureState(textureState);\n this._parameter.pipeline = this._createRenderPipeline(effect, topology, sampleCount);\n WebGPUCacheRenderPipeline.NumCacheMiss++;\n WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame++;\n return this._parameter.pipeline;\n }\n this._setShaderStage(effect.uniqueId);\n this._setRasterizationState(fillMode, sampleCount);\n this._setColorStates();\n this._setDepthStencilState();\n this._setVertexState(effect);\n this._setTextureState(textureState);\n this.lastStateDirtyLowestIndex = this._stateDirtyLowestIndex;\n if (!this._isDirty && this._parameter.pipeline) {\n this._stateDirtyLowestIndex = this._statesLength;\n WebGPUCacheRenderPipeline.NumCacheHitWithoutHash++;\n return this._parameter.pipeline;\n }\n this._getRenderPipeline(this._parameter);\n this._isDirty = false;\n this._stateDirtyLowestIndex = this._statesLength;\n if (this._parameter.pipeline) {\n WebGPUCacheRenderPipeline.NumCacheHitWithHash++;\n return this._parameter.pipeline;\n }\n const topology = WebGPUCacheRenderPipeline._GetTopology(fillMode);\n this._parameter.pipeline = this._createRenderPipeline(effect, topology, sampleCount);\n this._setRenderPipeline(this._parameter);\n WebGPUCacheRenderPipeline.NumCacheMiss++;\n WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame++;\n return this._parameter.pipeline;\n }\n endFrame() {\n WebGPUCacheRenderPipeline.NumPipelineCreationLastFrame = WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame;\n WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame = 0;\n }\n setAlphaToCoverage(enabled) {\n this._alphaToCoverageEnabled = enabled;\n }\n setFrontFace(frontFace) {\n this._frontFace = frontFace;\n }\n setCullEnabled(enabled) {\n this._cullEnabled = enabled;\n }\n setCullFace(cullFace) {\n this._cullFace = cullFace;\n }\n setClampDepth(clampDepth) {\n this._clampDepth = clampDepth;\n }\n resetDepthCullingState() {\n this.setDepthCullingState(false, 2, 1, 0, 0, true, true, 519);\n }\n setDepthCullingState(cullEnabled, frontFace, cullFace, zOffset, zOffsetUnits, depthTestEnabled, depthWriteEnabled, depthCompare) {\n this._depthWriteEnabled = depthWriteEnabled;\n this._depthTestEnabled = depthTestEnabled;\n this._depthCompare = (depthCompare !== null && depthCompare !== void 0 ? depthCompare : 519) - 0x0200;\n this._cullFace = cullFace;\n this._cullEnabled = cullEnabled;\n this._frontFace = frontFace;\n this.setDepthBiasSlopeScale(zOffset);\n this.setDepthBias(zOffsetUnits);\n }\n setDepthBias(depthBias) {\n if (this._depthBias !== depthBias) {\n this._depthBias = depthBias;\n this._states[StatePosition.DepthBias] = depthBias;\n this._isDirty = true;\n this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.DepthBias);\n }\n }\n /*public setDepthBiasClamp(depthBiasClamp: number): void {\n if (this._depthBiasClamp !== depthBiasClamp) {\n this._depthBiasClamp = depthBiasClamp;\n this._states[StatePosition.DepthBiasClamp] = depthBiasClamp.toString();\n this._isDirty = true;\n }\n }*/\n setDepthBiasSlopeScale(depthBiasSlopeScale) {\n if (this._depthBiasSlopeScale !== depthBiasSlopeScale) {\n this._depthBiasSlopeScale = depthBiasSlopeScale;\n this._states[StatePosition.DepthBiasSlopeScale] = depthBiasSlopeScale;\n this._isDirty = true;\n this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.DepthBiasSlopeScale);\n }\n }\n setColorFormat(format) {\n this._webgpuColorFormat[0] = format;\n this._colorFormat = renderableTextureFormatToIndex[format !== null && format !== void 0 ? format : \"\"];\n }\n setMRTAttachments(attachments) {\n this.mrtAttachments = attachments;\n let mask = 0;\n for (let i = 0; i < attachments.length; ++i) {\n if (attachments[i] !== 0) {\n mask += 1 << i;\n }\n }\n if (this._mrtEnabledMask !== mask) {\n this._mrtEnabledMask = mask;\n this._isDirty = true;\n this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.MRTAttachments1);\n }\n }\n setMRT(textureArray, textureCount) {\n var _a, _b;\n textureCount = textureCount !== null && textureCount !== void 0 ? textureCount : textureArray.length;\n if (textureCount > 10) {\n // If we want more than 10 attachments we need to change this method (and the StatePosition enum) but 10 seems plenty: note that WebGPU only supports 8 at the time (2021/12/13)!\n // As we need 39 different values we are using 6 bits to encode a texture format, meaning we can encode 5 texture formats in 32 bits\n // We are using 2x32 bit values to handle 10 textures\n throw \"Can't handle more than 10 attachments for a MRT in cache render pipeline!\";\n }\n this.mrtTextureArray = textureArray;\n this.mrtTextureCount = textureCount;\n this._mrtEnabledMask = 0xffff; // all textures are enabled at start (meaning we can write to them). Calls to setMRTAttachments may disable some\n const bits = [0, 0];\n let indexBits = 0, mask = 0, numRT = 0;\n for (let i = 0; i < textureCount; ++i) {\n const texture = textureArray[i];\n const gpuWrapper = texture === null || texture === void 0 ? void 0 : texture._hardwareTexture;\n this._mrtFormats[numRT] = (_a = gpuWrapper === null || gpuWrapper === void 0 ? void 0 : gpuWrapper.format) !== null && _a !== void 0 ? _a : this._webgpuColorFormat[0];\n bits[indexBits] += renderableTextureFormatToIndex[(_b = this._mrtFormats[numRT]) !== null && _b !== void 0 ? _b : \"\"] << mask;\n mask += 6;\n numRT++;\n if (mask >= 32) {\n mask = 0;\n indexBits++;\n }\n }\n this._mrtFormats.length = numRT;\n if (this._mrtAttachments1 !== bits[0] || this._mrtAttachments2 !== bits[1]) {\n this._mrtAttachments1 = bits[0];\n this._mrtAttachments2 = bits[1];\n this._states[StatePosition.MRTAttachments1] = bits[0];\n this._states[StatePosition.MRTAttachments2] = bits[1];\n this._isDirty = true;\n this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.MRTAttachments1);\n }\n }\n setAlphaBlendEnabled(enabled) {\n this._alphaBlendEnabled = enabled;\n }\n setAlphaBlendFactors(factors, operations) {\n this._alphaBlendFuncParams = factors;\n this._alphaBlendEqParams = operations;\n }\n setWriteMask(mask) {\n this._writeMask = mask;\n }\n setDepthStencilFormat(format) {\n this._webgpuDepthStencilFormat = format;\n this._depthStencilFormat = format === undefined ? 0 : renderableTextureFormatToIndex[format];\n }\n setDepthTestEnabled(enabled) {\n this._depthTestEnabled = enabled;\n }\n setDepthWriteEnabled(enabled) {\n this._depthWriteEnabled = enabled;\n }\n setDepthCompare(func) {\n this._depthCompare = (func !== null && func !== void 0 ? func : 519) - 0x0200;\n }\n setStencilEnabled(enabled) {\n this._stencilEnabled = enabled;\n }\n setStencilCompare(func) {\n this._stencilFrontCompare = (func !== null && func !== void 0 ? func : 519) - 0x0200;\n }\n setStencilDepthFailOp(op) {\n this._stencilFrontDepthFailOp = op === null ? 1 /* KEEP */ : stencilOpToIndex[op];\n }\n setStencilPassOp(op) {\n this._stencilFrontPassOp = op === null ? 2 /* REPLACE */ : stencilOpToIndex[op];\n }\n setStencilFailOp(op) {\n this._stencilFrontFailOp = op === null ? 1 /* KEEP */ : stencilOpToIndex[op];\n }\n setStencilReadMask(mask) {\n if (this._stencilReadMask !== mask) {\n this._stencilReadMask = mask;\n this._states[StatePosition.StencilReadMask] = mask;\n this._isDirty = true;\n this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.StencilReadMask);\n }\n }\n setStencilWriteMask(mask) {\n if (this._stencilWriteMask !== mask) {\n this._stencilWriteMask = mask;\n this._states[StatePosition.StencilWriteMask] = mask;\n this._isDirty = true;\n this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.StencilWriteMask);\n }\n }\n resetStencilState() {\n this.setStencilState(false, 519, 7680, 7681, 7680, 0xff, 0xff);\n }\n setStencilState(stencilEnabled, compare, depthFailOp, passOp, failOp, readMask, writeMask) {\n this._stencilEnabled = stencilEnabled;\n this._stencilFrontCompare = (compare !== null && compare !== void 0 ? compare : 519) - 0x0200;\n this._stencilFrontDepthFailOp = depthFailOp === null ? 1 /* KEEP */ : stencilOpToIndex[depthFailOp];\n this._stencilFrontPassOp = passOp === null ? 2 /* REPLACE */ : stencilOpToIndex[passOp];\n this._stencilFrontFailOp = failOp === null ? 1 /* KEEP */ : stencilOpToIndex[failOp];\n this.setStencilReadMask(readMask);\n this.setStencilWriteMask(writeMask);\n }\n setBuffers(vertexBuffers, indexBuffer, overrideVertexBuffers) {\n this._vertexBuffers = vertexBuffers;\n this._overrideVertexBuffers = overrideVertexBuffers;\n this._indexBuffer = indexBuffer;\n }\n static _GetTopology(fillMode) {\n switch (fillMode) {\n // Triangle views\n case 0:\n return WebGPUConstants.PrimitiveTopology.TriangleList;\n case 2:\n return WebGPUConstants.PrimitiveTopology.PointList;\n case 1:\n return WebGPUConstants.PrimitiveTopology.LineList;\n // Draw modes\n case 3:\n return WebGPUConstants.PrimitiveTopology.PointList;\n case 4:\n return WebGPUConstants.PrimitiveTopology.LineList;\n case 5:\n // return this._gl.LINE_LOOP;\n // TODO WEBGPU. Line Loop Mode Fallback at buffer load time.\n throw \"LineLoop is an unsupported fillmode in WebGPU\";\n case 6:\n return WebGPUConstants.PrimitiveTopology.LineStrip;\n case 7:\n return WebGPUConstants.PrimitiveTopology.TriangleStrip;\n case 8:\n // return this._gl.TRIANGLE_FAN;\n // TODO WEBGPU. Triangle Fan Mode Fallback at buffer load time.\n throw \"TriangleFan is an unsupported fillmode in WebGPU\";\n default:\n return WebGPUConstants.PrimitiveTopology.TriangleList;\n }\n }\n static _GetAphaBlendOperation(operation) {\n switch (operation) {\n case 32774:\n return WebGPUConstants.BlendOperation.Add;\n case 32778:\n return WebGPUConstants.BlendOperation.Subtract;\n case 32779:\n return WebGPUConstants.BlendOperation.ReverseSubtract;\n case 32775:\n return WebGPUConstants.BlendOperation.Min;\n case 32776:\n return WebGPUConstants.BlendOperation.Max;\n default:\n return WebGPUConstants.BlendOperation.Add;\n }\n }\n static _GetAphaBlendFactor(factor) {\n switch (factor) {\n case 0:\n return WebGPUConstants.BlendFactor.Zero;\n case 1:\n return WebGPUConstants.BlendFactor.One;\n case 768:\n return WebGPUConstants.BlendFactor.Src;\n case 769:\n return WebGPUConstants.BlendFactor.OneMinusSrc;\n case 770:\n return WebGPUConstants.BlendFactor.SrcAlpha;\n case 771:\n return WebGPUConstants.BlendFactor.OneMinusSrcAlpha;\n case 772:\n return WebGPUConstants.BlendFactor.DstAlpha;\n case 773:\n return WebGPUConstants.BlendFactor.OneMinusDstAlpha;\n case 774:\n return WebGPUConstants.BlendFactor.Dst;\n case 775:\n return WebGPUConstants.BlendFactor.OneMinusDst;\n case 776:\n return WebGPUConstants.BlendFactor.SrcAlphaSaturated;\n case 32769:\n return WebGPUConstants.BlendFactor.Constant;\n case 32770:\n return WebGPUConstants.BlendFactor.OneMinusConstant;\n case 32771:\n return WebGPUConstants.BlendFactor.Constant;\n case 32772:\n return WebGPUConstants.BlendFactor.OneMinusConstant;\n default:\n return WebGPUConstants.BlendFactor.One;\n }\n }\n static _GetCompareFunction(compareFunction) {\n switch (compareFunction) {\n case 0: // NEVER\n return WebGPUConstants.CompareFunction.Never;\n case 1: // LESS\n return WebGPUConstants.CompareFunction.Less;\n case 2: // EQUAL\n return WebGPUConstants.CompareFunction.Equal;\n case 3: // LEQUAL\n return WebGPUConstants.CompareFunction.LessEqual;\n case 4: // GREATER\n return WebGPUConstants.CompareFunction.Greater;\n case 5: // NOTEQUAL\n return WebGPUConstants.CompareFunction.NotEqual;\n case 6: // GEQUAL\n return WebGPUConstants.CompareFunction.GreaterEqual;\n case 7: // ALWAYS\n return WebGPUConstants.CompareFunction.Always;\n }\n return WebGPUConstants.CompareFunction.Never;\n }\n static _GetStencilOpFunction(operation) {\n switch (operation) {\n case 0:\n return WebGPUConstants.StencilOperation.Zero;\n case 1:\n return WebGPUConstants.StencilOperation.Keep;\n case 2:\n return WebGPUConstants.StencilOperation.Replace;\n case 3:\n return WebGPUConstants.StencilOperation.IncrementClamp;\n case 4:\n return WebGPUConstants.StencilOperation.DecrementClamp;\n case 5:\n return WebGPUConstants.StencilOperation.Invert;\n case 6:\n return WebGPUConstants.StencilOperation.IncrementWrap;\n case 7:\n return WebGPUConstants.StencilOperation.DecrementWrap;\n }\n return WebGPUConstants.StencilOperation.Keep;\n }\n static _GetVertexInputDescriptorFormat(vertexBuffer) {\n const type = vertexBuffer.type;\n const normalized = vertexBuffer.normalized;\n const size = vertexBuffer.getSize();\n switch (type) {\n case VertexBuffer.BYTE:\n switch (size) {\n case 1:\n case 2:\n return normalized ? WebGPUConstants.VertexFormat.Snorm8x2 : WebGPUConstants.VertexFormat.Sint8x2;\n case 3:\n case 4:\n return normalized ? WebGPUConstants.VertexFormat.Snorm8x4 : WebGPUConstants.VertexFormat.Sint8x4;\n }\n break;\n case VertexBuffer.UNSIGNED_BYTE:\n switch (size) {\n case 1:\n case 2:\n return normalized ? WebGPUConstants.VertexFormat.Unorm8x2 : WebGPUConstants.VertexFormat.Uint8x2;\n case 3:\n case 4:\n return normalized ? WebGPUConstants.VertexFormat.Unorm8x4 : WebGPUConstants.VertexFormat.Uint8x4;\n }\n break;\n case VertexBuffer.SHORT:\n switch (size) {\n case 1:\n case 2:\n return normalized ? WebGPUConstants.VertexFormat.Snorm16x2 : WebGPUConstants.VertexFormat.Sint16x2;\n case 3:\n case 4:\n return normalized ? WebGPUConstants.VertexFormat.Snorm16x4 : WebGPUConstants.VertexFormat.Sint16x4;\n }\n break;\n case VertexBuffer.UNSIGNED_SHORT:\n switch (size) {\n case 1:\n case 2:\n return normalized ? WebGPUConstants.VertexFormat.Unorm16x2 : WebGPUConstants.VertexFormat.Uint16x2;\n case 3:\n case 4:\n return normalized ? WebGPUConstants.VertexFormat.Unorm16x4 : WebGPUConstants.VertexFormat.Uint16x4;\n }\n break;\n case VertexBuffer.INT:\n switch (size) {\n case 1:\n return WebGPUConstants.VertexFormat.Sint32;\n case 2:\n return WebGPUConstants.VertexFormat.Sint32x2;\n case 3:\n return WebGPUConstants.VertexFormat.Sint32x3;\n case 4:\n return WebGPUConstants.VertexFormat.Sint32x4;\n }\n break;\n case VertexBuffer.UNSIGNED_INT:\n switch (size) {\n case 1:\n return WebGPUConstants.VertexFormat.Uint32;\n case 2:\n return WebGPUConstants.VertexFormat.Uint32x2;\n case 3:\n return WebGPUConstants.VertexFormat.Uint32x3;\n case 4:\n return WebGPUConstants.VertexFormat.Uint32x4;\n }\n break;\n case VertexBuffer.FLOAT:\n switch (size) {\n case 1:\n return WebGPUConstants.VertexFormat.Float32;\n case 2:\n return WebGPUConstants.VertexFormat.Float32x2;\n case 3:\n return WebGPUConstants.VertexFormat.Float32x3;\n case 4:\n return WebGPUConstants.VertexFormat.Float32x4;\n }\n break;\n }\n throw new Error(`Invalid Format '${vertexBuffer.getKind()}' - type=${type}, normalized=${normalized}, size=${size}`);\n }\n _getAphaBlendState() {\n if (!this._alphaBlendEnabled) {\n return null;\n }\n return {\n srcFactor: WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),\n dstFactor: WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),\n operation: WebGPUCacheRenderPipeline._GetAphaBlendOperation(this._alphaBlendEqParams[1]),\n };\n }\n _getColorBlendState() {\n if (!this._alphaBlendEnabled) {\n return null;\n }\n return {\n srcFactor: WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),\n dstFactor: WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),\n operation: WebGPUCacheRenderPipeline._GetAphaBlendOperation(this._alphaBlendEqParams[0]),\n };\n }\n _setShaderStage(id) {\n if (this._shaderId !== id) {\n this._shaderId = id;\n this._states[StatePosition.ShaderStage] = id;\n this._isDirty = true;\n this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.ShaderStage);\n }\n }\n _setRasterizationState(topology, sampleCount) {\n const frontFace = this._frontFace;\n const cullMode = this._cullEnabled ? this._cullFace : 0;\n const clampDepth = this._clampDepth ? 1 : 0;\n const alphaToCoverage = this._alphaToCoverageEnabled ? 1 : 0;\n const rasterizationState = frontFace - 1 + (cullMode << 1) + (clampDepth << 3) + (alphaToCoverage << 4) + (topology << 5) + (sampleCount << 8);\n if (this._rasterizationState !== rasterizationState) {\n this._rasterizationState = rasterizationState;\n this._states[StatePosition.RasterizationState] = this._rasterizationState;\n this._isDirty = true;\n this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.RasterizationState);\n }\n }\n _setColorStates() {\n let colorStates = ((this._writeMask ? 1 : 0) << 22) + (this._colorFormat << 23) + ((this._depthWriteEnabled ? 1 : 0) << 29); // this state has been moved from depthStencilState here because alpha and depth are related (generally when alpha is on, depth write is off and the other way around)\n if (this._alphaBlendEnabled) {\n colorStates +=\n ((this._alphaBlendFuncParams[0] === null ? 2 : alphaBlendFactorToIndex[this._alphaBlendFuncParams[0]]) << 0) +\n ((this._alphaBlendFuncParams[1] === null ? 2 : alphaBlendFactorToIndex[this._alphaBlendFuncParams[1]]) << 4) +\n ((this._alphaBlendFuncParams[2] === null ? 2 : alphaBlendFactorToIndex[this._alphaBlendFuncParams[2]]) << 8) +\n ((this._alphaBlendFuncParams[3] === null ? 2 : alphaBlendFactorToIndex[this._alphaBlendFuncParams[3]]) << 12) +\n ((this._alphaBlendEqParams[0] === null ? 1 : this._alphaBlendEqParams[0] - 0x8005) << 16) +\n ((this._alphaBlendEqParams[1] === null ? 1 : this._alphaBlendEqParams[1] - 0x8005) << 19);\n }\n if (colorStates !== this._colorStates) {\n this._colorStates = colorStates;\n this._states[StatePosition.ColorStates] = this._colorStates;\n this._isDirty = true;\n this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.ColorStates);\n }\n }\n _setDepthStencilState() {\n const stencilState = !this._stencilEnabled\n ? 7 /* ALWAYS */ + (1 /* KEEP */ << 3) + (1 /* KEEP */ << 6) + (1 /* KEEP */ << 9)\n : this._stencilFrontCompare + (this._stencilFrontDepthFailOp << 3) + (this._stencilFrontPassOp << 6) + (this._stencilFrontFailOp << 9);\n const depthStencilState = this._depthStencilFormat + ((this._depthTestEnabled ? this._depthCompare : 7) /* ALWAYS */ << 6) + (stencilState << 10); // stencil front - stencil back is the same\n if (this._depthStencilState !== depthStencilState) {\n this._depthStencilState = depthStencilState;\n this._states[StatePosition.DepthStencilState] = this._depthStencilState;\n this._isDirty = true;\n this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.DepthStencilState);\n }\n }\n _setVertexState(effect) {\n var _a, _b;\n const currStateLen = this._statesLength;\n let newNumStates = StatePosition.VertexState;\n const webgpuPipelineContext = effect._pipelineContext;\n const attributes = webgpuPipelineContext.shaderProcessingContext.attributeNamesFromEffect;\n const locations = webgpuPipelineContext.shaderProcessingContext.attributeLocationsFromEffect;\n let currentGPUBuffer;\n let numVertexBuffers = 0;\n for (let index = 0; index < attributes.length; index++) {\n const location = locations[index];\n let vertexBuffer = (_a = (this._overrideVertexBuffers && this._overrideVertexBuffers[attributes[index]])) !== null && _a !== void 0 ? _a : this._vertexBuffers[attributes[index]];\n if (!vertexBuffer) {\n // In WebGL it's valid to not bind a vertex buffer to an attribute, but it's not valid in WebGPU\n // So we must bind a dummy buffer when we are not given one for a specific attribute\n vertexBuffer = this._emptyVertexBuffer;\n }\n const buffer = (_b = vertexBuffer.getBuffer()) === null || _b === void 0 ? void 0 : _b.underlyingResource;\n // We optimize usage of GPUVertexBufferLayout: we will create a single GPUVertexBufferLayout for all the attributes which follow each other and which use the same GPU buffer\n // However, there are some constraints in the attribute.offset value range, so we must check for them before being able to reuse the same GPUVertexBufferLayout\n // See _getVertexInputDescriptor() below\n if (vertexBuffer._validOffsetRange === undefined) {\n const offset = vertexBuffer.byteOffset;\n const formatSize = vertexBuffer.getSize(true);\n const byteStride = vertexBuffer.byteStride;\n vertexBuffer._validOffsetRange = offset <= this._kMaxVertexBufferStride - formatSize && (byteStride === 0 || offset + formatSize <= byteStride);\n }\n if (!(currentGPUBuffer && currentGPUBuffer === buffer && vertexBuffer._validOffsetRange)) {\n // we can't combine the previous vertexBuffer with the current one\n this.vertexBuffers[numVertexBuffers++] = vertexBuffer;\n currentGPUBuffer = vertexBuffer._validOffsetRange ? buffer : null;\n }\n const vid = vertexBuffer.hashCode + (location << 7);\n this._isDirty = this._isDirty || this._states[newNumStates] !== vid;\n this._states[newNumStates++] = vid;\n }\n this.vertexBuffers.length = numVertexBuffers;\n this._statesLength = newNumStates;\n this._isDirty = this._isDirty || newNumStates !== currStateLen;\n if (this._isDirty) {\n this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.VertexState);\n }\n }\n _setTextureState(textureState) {\n if (this._textureState !== textureState) {\n this._textureState = textureState;\n this._states[StatePosition.TextureStage] = this._textureState;\n this._isDirty = true;\n this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.TextureStage);\n }\n }\n _createPipelineLayout(webgpuPipelineContext) {\n if (this._useTextureStage) {\n return this._createPipelineLayoutWithTextureStage(webgpuPipelineContext);\n }\n const bindGroupLayouts = [];\n const bindGroupLayoutEntries = webgpuPipelineContext.shaderProcessingContext.bindGroupLayoutEntries;\n for (let i = 0; i < bindGroupLayoutEntries.length; i++) {\n const setDefinition = bindGroupLayoutEntries[i];\n bindGroupLayouts[i] = this._device.createBindGroupLayout({\n entries: setDefinition,\n });\n }\n webgpuPipelineContext.bindGroupLayouts[0] = bindGroupLayouts;\n return this._device.createPipelineLayout({ bindGroupLayouts });\n }\n _createPipelineLayoutWithTextureStage(webgpuPipelineContext) {\n var _a;\n const shaderProcessingContext = webgpuPipelineContext.shaderProcessingContext;\n const bindGroupLayoutEntries = shaderProcessingContext.bindGroupLayoutEntries;\n let bitVal = 1;\n for (let i = 0; i < bindGroupLayoutEntries.length; i++) {\n const setDefinition = bindGroupLayoutEntries[i];\n for (let j = 0; j < setDefinition.length; j++) {\n const entry = bindGroupLayoutEntries[i][j];\n if (entry.texture) {\n const name = shaderProcessingContext.bindGroupLayoutEntryInfo[i][entry.binding].name;\n const textureInfo = shaderProcessingContext.availableTextures[name];\n const samplerInfo = textureInfo.autoBindSampler ? shaderProcessingContext.availableSamplers[name + WebGPUShaderProcessor.AutoSamplerSuffix] : null;\n let sampleType = textureInfo.sampleType;\n let samplerType = (_a = samplerInfo === null || samplerInfo === void 0 ? void 0 : samplerInfo.type) !== null && _a !== void 0 ? _a : WebGPUConstants.SamplerBindingType.Filtering;\n if (this._textureState & bitVal && sampleType !== WebGPUConstants.TextureSampleType.Depth) {\n // The texture is a 32 bits float texture but the system does not support linear filtering for them:\n // we set the sampler to \"non-filtering\" and the texture sample type to \"unfilterable-float\"\n if (textureInfo.autoBindSampler) {\n samplerType = WebGPUConstants.SamplerBindingType.NonFiltering;\n }\n sampleType = WebGPUConstants.TextureSampleType.UnfilterableFloat;\n }\n entry.texture.sampleType = sampleType;\n if (samplerInfo) {\n const binding = shaderProcessingContext.bindGroupLayoutEntryInfo[samplerInfo.binding.groupIndex][samplerInfo.binding.bindingIndex].index;\n bindGroupLayoutEntries[samplerInfo.binding.groupIndex][binding].sampler.type = samplerType;\n }\n bitVal = bitVal << 1;\n }\n }\n }\n const bindGroupLayouts = [];\n for (let i = 0; i < bindGroupLayoutEntries.length; ++i) {\n bindGroupLayouts[i] = this._device.createBindGroupLayout({\n entries: bindGroupLayoutEntries[i],\n });\n }\n webgpuPipelineContext.bindGroupLayouts[this._textureState] = bindGroupLayouts;\n return this._device.createPipelineLayout({ bindGroupLayouts });\n }\n _getVertexInputDescriptor(effect) {\n var _a, _b;\n const descriptors = [];\n const webgpuPipelineContext = effect._pipelineContext;\n const attributes = webgpuPipelineContext.shaderProcessingContext.attributeNamesFromEffect;\n const locations = webgpuPipelineContext.shaderProcessingContext.attributeLocationsFromEffect;\n let currentGPUBuffer;\n let currentGPUAttributes;\n for (let index = 0; index < attributes.length; index++) {\n const location = locations[index];\n let vertexBuffer = (_a = (this._overrideVertexBuffers && this._overrideVertexBuffers[attributes[index]])) !== null && _a !== void 0 ? _a : this._vertexBuffers[attributes[index]];\n if (!vertexBuffer) {\n // In WebGL it's valid to not bind a vertex buffer to an attribute, but it's not valid in WebGPU\n // So we must bind a dummy buffer when we are not given one for a specific attribute\n vertexBuffer = this._emptyVertexBuffer;\n }\n let buffer = (_b = vertexBuffer.getBuffer()) === null || _b === void 0 ? void 0 : _b.underlyingResource;\n // We reuse the same GPUVertexBufferLayout for all attributes that use the same underlying GPU buffer (and for attributes that follow each other in the attributes array)\n let offset = vertexBuffer.byteOffset;\n const invalidOffsetRange = !vertexBuffer._validOffsetRange;\n if (!(currentGPUBuffer && currentGPUAttributes && currentGPUBuffer === buffer) || invalidOffsetRange) {\n const vertexBufferDescriptor = {\n arrayStride: vertexBuffer.byteStride,\n stepMode: vertexBuffer.getIsInstanced() ? WebGPUConstants.InputStepMode.Instance : WebGPUConstants.InputStepMode.Vertex,\n attributes: [],\n };\n descriptors.push(vertexBufferDescriptor);\n currentGPUAttributes = vertexBufferDescriptor.attributes;\n if (invalidOffsetRange) {\n offset = 0; // the offset will be set directly in the setVertexBuffer call\n buffer = null; // buffer can't be reused\n }\n }\n currentGPUAttributes.push({\n shaderLocation: location,\n offset,\n format: WebGPUCacheRenderPipeline._GetVertexInputDescriptorFormat(vertexBuffer),\n });\n currentGPUBuffer = buffer;\n }\n return descriptors;\n }\n _createRenderPipeline(effect, topology, sampleCount) {\n var _a, _b, _c;\n const webgpuPipelineContext = effect._pipelineContext;\n const inputStateDescriptor = this._getVertexInputDescriptor(effect);\n const pipelineLayout = this._createPipelineLayout(webgpuPipelineContext);\n const colorStates = [];\n const alphaBlend = this._getAphaBlendState();\n const colorBlend = this._getColorBlendState();\n if (this._mrtAttachments1 > 0) {\n for (let i = 0; i < this._mrtFormats.length; ++i) {\n const format = this._mrtFormats[i];\n if (format) {\n const descr = {\n format,\n writeMask: (this._mrtEnabledMask & (1 << i)) !== 0 ? this._writeMask : 0,\n };\n if (alphaBlend && colorBlend) {\n descr.blend = {\n alpha: alphaBlend,\n color: colorBlend,\n };\n }\n colorStates.push(descr);\n }\n else {\n colorStates.push(null);\n }\n }\n }\n else {\n if (this._webgpuColorFormat[0]) {\n const descr = {\n format: this._webgpuColorFormat[0],\n writeMask: this._writeMask,\n };\n if (alphaBlend && colorBlend) {\n descr.blend = {\n alpha: alphaBlend,\n color: colorBlend,\n };\n }\n colorStates.push(descr);\n }\n else {\n colorStates.push(null);\n }\n }\n const stencilFrontBack = {\n compare: WebGPUCacheRenderPipeline._GetCompareFunction(this._stencilEnabled ? this._stencilFrontCompare : 7 /* ALWAYS */),\n depthFailOp: WebGPUCacheRenderPipeline._GetStencilOpFunction(this._stencilEnabled ? this._stencilFrontDepthFailOp : 1 /* KEEP */),\n failOp: WebGPUCacheRenderPipeline._GetStencilOpFunction(this._stencilEnabled ? this._stencilFrontFailOp : 1 /* KEEP */),\n passOp: WebGPUCacheRenderPipeline._GetStencilOpFunction(this._stencilEnabled ? this._stencilFrontPassOp : 1 /* KEEP */),\n };\n let stripIndexFormat = undefined;\n if (topology === WebGPUConstants.PrimitiveTopology.LineStrip || topology === WebGPUConstants.PrimitiveTopology.TriangleStrip) {\n stripIndexFormat = !this._indexBuffer || this._indexBuffer.is32Bits ? WebGPUConstants.IndexFormat.Uint32 : WebGPUConstants.IndexFormat.Uint16;\n }\n const depthStencilFormatHasStencil = this._webgpuDepthStencilFormat ? WebGPUTextureHelper.HasStencilAspect(this._webgpuDepthStencilFormat) : false;\n return this._device.createRenderPipeline({\n label: `RenderPipeline_${(_b = (_a = colorStates[0]) === null || _a === void 0 ? void 0 : _a.format) !== null && _b !== void 0 ? _b : \"nooutput\"}_${(_c = this._webgpuDepthStencilFormat) !== null && _c !== void 0 ? _c : \"nodepth\"}_samples${sampleCount}_textureState${this._textureState}`,\n layout: pipelineLayout,\n vertex: {\n module: webgpuPipelineContext.stages.vertexStage.module,\n entryPoint: webgpuPipelineContext.stages.vertexStage.entryPoint,\n buffers: inputStateDescriptor,\n },\n primitive: {\n topology,\n stripIndexFormat,\n frontFace: this._frontFace === 1 ? WebGPUConstants.FrontFace.CCW : WebGPUConstants.FrontFace.CW,\n cullMode: !this._cullEnabled ? WebGPUConstants.CullMode.None : this._cullFace === 2 ? WebGPUConstants.CullMode.Front : WebGPUConstants.CullMode.Back,\n },\n fragment: !webgpuPipelineContext.stages.fragmentStage\n ? undefined\n : {\n module: webgpuPipelineContext.stages.fragmentStage.module,\n entryPoint: webgpuPipelineContext.stages.fragmentStage.entryPoint,\n targets: colorStates,\n },\n multisample: {\n count: sampleCount,\n /*mask,\n alphaToCoverageEnabled,*/\n },\n depthStencil: this._webgpuDepthStencilFormat === undefined\n ? undefined\n : {\n depthWriteEnabled: this._depthWriteEnabled,\n depthCompare: this._depthTestEnabled ? WebGPUCacheRenderPipeline._GetCompareFunction(this._depthCompare) : WebGPUConstants.CompareFunction.Always,\n format: this._webgpuDepthStencilFormat,\n stencilFront: this._stencilEnabled && depthStencilFormatHasStencil ? stencilFrontBack : undefined,\n stencilBack: this._stencilEnabled && depthStencilFormatHasStencil ? stencilFrontBack : undefined,\n stencilReadMask: this._stencilEnabled && depthStencilFormatHasStencil ? this._stencilReadMask : undefined,\n stencilWriteMask: this._stencilEnabled && depthStencilFormatHasStencil ? this._stencilWriteMask : undefined,\n depthBias: this._depthBias,\n depthBiasClamp: this._depthBiasClamp,\n depthBiasSlopeScale: this._depthBiasSlopeScale,\n },\n });\n }\n}\nWebGPUCacheRenderPipeline.NumCacheHitWithoutHash = 0;\nWebGPUCacheRenderPipeline.NumCacheHitWithHash = 0;\nWebGPUCacheRenderPipeline.NumCacheMiss = 0;\nWebGPUCacheRenderPipeline.NumPipelineCreationLastFrame = 0;\nWebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame = 0;\n//# sourceMappingURL=webgpuCacheRenderPipeline.js.map","import { WebGPUCacheRenderPipeline } from \"./webgpuCacheRenderPipeline.js\";\n/** @internal */\nclass NodeState {\n constructor() {\n this.values = {};\n }\n count() {\n let countNode = 0, countPipeline = this.pipeline ? 1 : 0;\n for (const value in this.values) {\n const node = this.values[value];\n const [childCountNodes, childCoundPipeline] = node.count();\n countNode += childCountNodes;\n countPipeline += childCoundPipeline;\n countNode++;\n }\n return [countNode, countPipeline];\n }\n}\n/** @internal */\nexport class WebGPUCacheRenderPipelineTree extends WebGPUCacheRenderPipeline {\n static GetNodeCounts() {\n const counts = WebGPUCacheRenderPipelineTree._Cache.count();\n return { nodeCount: counts[0], pipelineCount: counts[1] };\n }\n static _GetPipelines(node, pipelines, curPath, curPathLen) {\n if (node.pipeline) {\n const path = curPath.slice();\n path.length = curPathLen;\n pipelines.push(path);\n }\n for (const value in node.values) {\n const nnode = node.values[value];\n curPath[curPathLen] = parseInt(value);\n WebGPUCacheRenderPipelineTree._GetPipelines(nnode, pipelines, curPath, curPathLen + 1);\n }\n }\n static GetPipelines() {\n const pipelines = [];\n WebGPUCacheRenderPipelineTree._GetPipelines(WebGPUCacheRenderPipelineTree._Cache, pipelines, [], 0);\n return pipelines;\n }\n constructor(device, emptyVertexBuffer, useTextureStage) {\n super(device, emptyVertexBuffer, useTextureStage);\n this._nodeStack = [];\n this._nodeStack[0] = WebGPUCacheRenderPipelineTree._Cache;\n }\n _getRenderPipeline(param) {\n let node = this._nodeStack[this._stateDirtyLowestIndex];\n for (let i = this._stateDirtyLowestIndex; i < this._statesLength; ++i) {\n let nn = node.values[this._states[i]];\n if (!nn) {\n nn = new NodeState();\n node.values[this._states[i]] = nn;\n }\n node = nn;\n this._nodeStack[i + 1] = node;\n }\n param.token = node;\n param.pipeline = node.pipeline;\n }\n _setRenderPipeline(param) {\n param.token.pipeline = param.pipeline;\n }\n}\nWebGPUCacheRenderPipelineTree._Cache = new NodeState();\n//# sourceMappingURL=webgpuCacheRenderPipelineTree.js.map","import { StencilStateComposer } from \"../../States/stencilStateComposer.js\";\n/**\n * @internal\n **/\nexport class WebGPUStencilStateComposer extends StencilStateComposer {\n constructor(cache) {\n super(false);\n this._cache = cache;\n this.reset();\n }\n get func() {\n return this._func;\n }\n set func(value) {\n if (this._func === value) {\n return;\n }\n this._func = value;\n this._cache.setStencilCompare(value);\n }\n get funcMask() {\n return this._funcMask;\n }\n set funcMask(value) {\n if (this._funcMask === value) {\n return;\n }\n this._funcMask = value;\n this._cache.setStencilReadMask(value);\n }\n get opStencilFail() {\n return this._opStencilFail;\n }\n set opStencilFail(value) {\n if (this._opStencilFail === value) {\n return;\n }\n this._opStencilFail = value;\n this._cache.setStencilFailOp(value);\n }\n get opDepthFail() {\n return this._opDepthFail;\n }\n set opDepthFail(value) {\n if (this._opDepthFail === value) {\n return;\n }\n this._opDepthFail = value;\n this._cache.setStencilDepthFailOp(value);\n }\n get opStencilDepthPass() {\n return this._opStencilDepthPass;\n }\n set opStencilDepthPass(value) {\n if (this._opStencilDepthPass === value) {\n return;\n }\n this._opStencilDepthPass = value;\n this._cache.setStencilPassOp(value);\n }\n get mask() {\n return this._mask;\n }\n set mask(value) {\n if (this._mask === value) {\n return;\n }\n this._mask = value;\n this._cache.setStencilWriteMask(value);\n }\n get enabled() {\n return this._enabled;\n }\n set enabled(value) {\n if (this._enabled === value) {\n return;\n }\n this._enabled = value;\n this._cache.setStencilEnabled(value);\n }\n reset() {\n super.reset();\n this._cache.resetStencilState();\n }\n apply() {\n var _a;\n const stencilMaterialEnabled = (_a = this.stencilMaterial) === null || _a === void 0 ? void 0 : _a.enabled;\n this.enabled = stencilMaterialEnabled ? this.stencilMaterial.enabled : this.stencilGlobal.enabled;\n if (!this.enabled) {\n return;\n }\n this.func = stencilMaterialEnabled ? this.stencilMaterial.func : this.stencilGlobal.func;\n this.funcRef = stencilMaterialEnabled ? this.stencilMaterial.funcRef : this.stencilGlobal.funcRef;\n this.funcMask = stencilMaterialEnabled ? this.stencilMaterial.funcMask : this.stencilGlobal.funcMask;\n this.opStencilFail = stencilMaterialEnabled ? this.stencilMaterial.opStencilFail : this.stencilGlobal.opStencilFail;\n this.opDepthFail = stencilMaterialEnabled ? this.stencilMaterial.opDepthFail : this.stencilGlobal.opDepthFail;\n this.opStencilDepthPass = stencilMaterialEnabled ? this.stencilMaterial.opStencilDepthPass : this.stencilGlobal.opStencilDepthPass;\n this.mask = stencilMaterialEnabled ? this.stencilMaterial.mask : this.stencilGlobal.mask;\n }\n}\n//# sourceMappingURL=webgpuStencilStateComposer.js.map","import { DepthCullingState } from \"../../States/depthCullingState.js\";\n/**\n * @internal\n **/\nexport class WebGPUDepthCullingState extends DepthCullingState {\n /**\n * Initializes the state.\n * @param cache\n */\n constructor(cache) {\n super(false);\n this._cache = cache;\n this.reset();\n }\n get zOffset() {\n return this._zOffset;\n }\n set zOffset(value) {\n if (this._zOffset === value) {\n return;\n }\n this._zOffset = value;\n this._isZOffsetDirty = true;\n this._cache.setDepthBiasSlopeScale(value);\n }\n get zOffsetUnits() {\n return this._zOffsetUnits;\n }\n set zOffsetUnits(value) {\n if (this._zOffsetUnits === value) {\n return;\n }\n this._zOffsetUnits = value;\n this._isZOffsetDirty = true;\n this._cache.setDepthBias(value);\n }\n get cullFace() {\n return this._cullFace;\n }\n set cullFace(value) {\n if (this._cullFace === value) {\n return;\n }\n this._cullFace = value;\n this._isCullFaceDirty = true;\n this._cache.setCullFace(value !== null && value !== void 0 ? value : 1);\n }\n get cull() {\n return this._cull;\n }\n set cull(value) {\n if (this._cull === value) {\n return;\n }\n this._cull = value;\n this._isCullDirty = true;\n this._cache.setCullEnabled(!!value);\n }\n get depthFunc() {\n return this._depthFunc;\n }\n set depthFunc(value) {\n if (this._depthFunc === value) {\n return;\n }\n this._depthFunc = value;\n this._isDepthFuncDirty = true;\n this._cache.setDepthCompare(value);\n }\n get depthMask() {\n return this._depthMask;\n }\n set depthMask(value) {\n if (this._depthMask === value) {\n return;\n }\n this._depthMask = value;\n this._isDepthMaskDirty = true;\n this._cache.setDepthWriteEnabled(value);\n }\n get depthTest() {\n return this._depthTest;\n }\n set depthTest(value) {\n if (this._depthTest === value) {\n return;\n }\n this._depthTest = value;\n this._isDepthTestDirty = true;\n this._cache.setDepthTestEnabled(value);\n }\n get frontFace() {\n return this._frontFace;\n }\n set frontFace(value) {\n if (this._frontFace === value) {\n return;\n }\n this._frontFace = value;\n this._isFrontFaceDirty = true;\n this._cache.setFrontFace(value !== null && value !== void 0 ? value : 2);\n }\n reset() {\n super.reset();\n this._cache.resetDepthCullingState();\n }\n apply() {\n // nothing to do\n }\n}\n//# sourceMappingURL=webgpuDepthCullingState.js.map","\nimport { InternalTexture } from \"./internalTexture.js\";\n/**\n * Class used to store an external texture (like GPUExternalTexture in WebGPU)\n */\nexport class ExternalTexture {\n /**\n * Checks if a texture is an external or internal texture\n * @param texture the external or internal texture\n * @returns true if the texture is an external texture, else false\n */\n static IsExternalTexture(texture) {\n return texture.underlyingResource !== undefined;\n }\n /**\n * Get the class name of the texture.\n * @returns \"ExternalTexture\"\n */\n getClassName() {\n return \"ExternalTexture\";\n }\n /**\n * Gets the underlying texture object\n */\n get underlyingResource() {\n return this._video;\n }\n /**\n * Constructs the texture\n * @param video The video the texture should be wrapped around\n */\n constructor(video) {\n /**\n * Gets a boolean indicating if the texture uses mipmaps\n */\n this.useMipMaps = false;\n /**\n * The type of the underlying texture is implementation dependent, so return \"UNDEFINED\" for the type\n */\n this.type = 16;\n this._video = video;\n this.uniqueId = InternalTexture._Counter++;\n }\n /**\n * Get if the texture is ready to be used (downloaded, converted, mip mapped...).\n * @returns true if fully ready\n */\n isReady() {\n return this._video.readyState >= this._video.HAVE_CURRENT_DATA;\n }\n /**\n * Dispose the texture and release its associated resources.\n */\n dispose() { }\n}\n//# sourceMappingURL=externalTexture.js.map","import { ExternalTexture } from \"../../Materials/Textures/externalTexture.js\";\n\nimport { WebGPUCacheSampler } from \"./webgpuCacheSampler.js\";\n/** @internal */\nexport class WebGPUMaterialContext {\n get forceBindGroupCreation() {\n // If there is at least one external texture to bind, we must recreate the bind groups each time\n // because we need to retrieve a new texture each frame (by calling device.importExternalTexture)\n return this._numExternalTextures > 0;\n }\n get hasFloatTextures() {\n return this._numFloatTextures > 0;\n }\n constructor() {\n this.uniqueId = WebGPUMaterialContext._Counter++;\n this.updateId = 0;\n this.textureState = 0;\n this.reset();\n }\n reset() {\n this.samplers = {};\n this.textures = {};\n this.isDirty = true;\n this._numFloatTextures = 0;\n this._numExternalTextures = 0;\n }\n setSampler(name, sampler) {\n let samplerCache = this.samplers[name];\n let currentHashCode = -1;\n if (!samplerCache) {\n this.samplers[name] = samplerCache = { sampler, hashCode: 0 };\n }\n else {\n currentHashCode = samplerCache.hashCode;\n }\n samplerCache.sampler = sampler;\n samplerCache.hashCode = sampler ? WebGPUCacheSampler.GetSamplerHashCode(sampler) : 0;\n const isDirty = currentHashCode !== samplerCache.hashCode;\n if (isDirty) {\n this.updateId++;\n }\n this.isDirty || (this.isDirty = isDirty);\n }\n setTexture(name, texture) {\n var _a, _b, _c;\n let textureCache = this.textures[name];\n let currentTextureId = -1;\n if (!textureCache) {\n this.textures[name] = textureCache = { texture, isFloatTexture: false, isExternalTexture: false };\n }\n else {\n currentTextureId = (_b = (_a = textureCache.texture) === null || _a === void 0 ? void 0 : _a.uniqueId) !== null && _b !== void 0 ? _b : -1;\n }\n if (textureCache.isExternalTexture) {\n this._numExternalTextures--;\n }\n if (textureCache.isFloatTexture) {\n this._numFloatTextures--;\n }\n if (texture) {\n textureCache.isFloatTexture = texture.type === 1;\n textureCache.isExternalTexture = ExternalTexture.IsExternalTexture(texture);\n if (textureCache.isFloatTexture) {\n this._numFloatTextures++;\n }\n if (textureCache.isExternalTexture) {\n this._numExternalTextures++;\n }\n }\n else {\n textureCache.isFloatTexture = false;\n textureCache.isExternalTexture = false;\n }\n textureCache.texture = texture;\n const isDirty = currentTextureId !== ((_c = texture === null || texture === void 0 ? void 0 : texture.uniqueId) !== null && _c !== void 0 ? _c : -1);\n if (isDirty) {\n this.updateId++;\n }\n this.isDirty || (this.isDirty = isDirty);\n }\n}\nWebGPUMaterialContext._Counter = 0;\n//# sourceMappingURL=webgpuMaterialContext.js.map","import * as WebGPUConstants from \"./webgpuConstants.js\";\n/** @internal */\nexport class WebGPUDrawContext {\n isDirty(materialContextUpdateId) {\n return this._isDirty || this._materialContextUpdateId !== materialContextUpdateId;\n }\n resetIsDirty(materialContextUpdateId) {\n this._isDirty = false;\n this._materialContextUpdateId = materialContextUpdateId;\n }\n get useInstancing() {\n return this._useInstancing;\n }\n set useInstancing(use) {\n if (this._useInstancing === use) {\n return;\n }\n if (!use) {\n if (this.indirectDrawBuffer) {\n this._bufferManager.releaseBuffer(this.indirectDrawBuffer);\n }\n this.indirectDrawBuffer = undefined;\n this._indirectDrawData = undefined;\n }\n else {\n this.indirectDrawBuffer = this._bufferManager.createRawBuffer(20, WebGPUConstants.BufferUsage.CopyDst | WebGPUConstants.BufferUsage.Indirect | WebGPUConstants.BufferUsage.Storage);\n this._indirectDrawData = new Uint32Array(5);\n this._indirectDrawData[3] = 0;\n this._indirectDrawData[4] = 0;\n }\n this._useInstancing = use;\n this._currentInstanceCount = -1;\n }\n constructor(bufferManager) {\n this._bufferManager = bufferManager;\n this.uniqueId = WebGPUDrawContext._Counter++;\n this._useInstancing = false;\n this._currentInstanceCount = 0;\n this.reset();\n }\n reset() {\n this.buffers = {};\n this._isDirty = true;\n this._materialContextUpdateId = 0;\n this.fastBundle = undefined;\n this.bindGroups = undefined;\n }\n setBuffer(name, buffer) {\n var _a;\n this._isDirty || (this._isDirty = (buffer === null || buffer === void 0 ? void 0 : buffer.uniqueId) !== ((_a = this.buffers[name]) === null || _a === void 0 ? void 0 : _a.uniqueId));\n this.buffers[name] = buffer;\n }\n setIndirectData(indexOrVertexCount, instanceCount, firstIndexOrVertex) {\n if (instanceCount === this._currentInstanceCount || !this.indirectDrawBuffer || !this._indirectDrawData) {\n // The current buffer is already up to date so do nothing\n // Note that we only check for instanceCount and not indexOrVertexCount nor firstIndexOrVertex because those values\n // are supposed to not change during the lifetime of a draw context\n return;\n }\n this._currentInstanceCount = instanceCount;\n this._indirectDrawData[0] = indexOrVertexCount;\n this._indirectDrawData[1] = instanceCount;\n this._indirectDrawData[2] = firstIndexOrVertex;\n this._bufferManager.setRawData(this.indirectDrawBuffer, 0, this._indirectDrawData, 0, 20);\n }\n dispose() {\n if (this.indirectDrawBuffer) {\n this._bufferManager.releaseBuffer(this.indirectDrawBuffer);\n this.indirectDrawBuffer = undefined;\n this._indirectDrawData = undefined;\n }\n this.fastBundle = undefined;\n this.bindGroups = undefined;\n this.buffers = undefined;\n }\n}\nWebGPUDrawContext._Counter = 0;\n//# sourceMappingURL=webgpuDrawContext.js.map","import { Logger } from \"../../Misc/logger.js\";\nclass WebGPUBindGroupCacheNode {\n constructor() {\n this.values = {};\n }\n}\n/** @internal */\nexport class WebGPUCacheBindGroups {\n static get Statistics() {\n return {\n totalCreated: WebGPUCacheBindGroups.NumBindGroupsCreatedTotal,\n lastFrameCreated: WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame,\n lookupLastFrame: WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame,\n noLookupLastFrame: WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame,\n };\n }\n constructor(device, cacheSampler, engine) {\n this.disabled = false;\n this._device = device;\n this._cacheSampler = cacheSampler;\n this._engine = engine;\n }\n endFrame() {\n WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame = WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame;\n WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame = WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame;\n WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame = WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame;\n WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame = 0;\n WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame = 0;\n WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame = 0;\n }\n /**\n * Cache is currently based on the uniform/storage buffers, samplers and textures used by the binding groups.\n * Note that all uniform buffers have an offset of 0 in Babylon and we don't have a use case where we would have the same buffer used with different capacity values:\n * that means we don't need to factor in the offset/size of the buffer in the cache, only the id\n * @param webgpuPipelineContext\n * @param drawContext\n * @param materialContext\n */\n getBindGroups(webgpuPipelineContext, drawContext, materialContext) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;\n let bindGroups = undefined;\n let node = WebGPUCacheBindGroups._Cache;\n const cacheIsDisabled = this.disabled || materialContext.forceBindGroupCreation;\n if (!cacheIsDisabled) {\n if (!drawContext.isDirty(materialContext.updateId) && !materialContext.isDirty) {\n WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame++;\n return drawContext.bindGroups;\n }\n for (const bufferName of webgpuPipelineContext.shaderProcessingContext.bufferNames) {\n const uboId = (_b = (_a = drawContext.buffers[bufferName]) === null || _a === void 0 ? void 0 : _a.uniqueId) !== null && _b !== void 0 ? _b : 0;\n let nextNode = node.values[uboId];\n if (!nextNode) {\n nextNode = new WebGPUBindGroupCacheNode();\n node.values[uboId] = nextNode;\n }\n node = nextNode;\n }\n for (const samplerName of webgpuPipelineContext.shaderProcessingContext.samplerNames) {\n const samplerHashCode = (_d = (_c = materialContext.samplers[samplerName]) === null || _c === void 0 ? void 0 : _c.hashCode) !== null && _d !== void 0 ? _d : 0;\n let nextNode = node.values[samplerHashCode];\n if (!nextNode) {\n nextNode = new WebGPUBindGroupCacheNode();\n node.values[samplerHashCode] = nextNode;\n }\n node = nextNode;\n }\n for (const textureName of webgpuPipelineContext.shaderProcessingContext.textureNames) {\n const textureId = (_g = (_f = (_e = materialContext.textures[textureName]) === null || _e === void 0 ? void 0 : _e.texture) === null || _f === void 0 ? void 0 : _f.uniqueId) !== null && _g !== void 0 ? _g : 0;\n let nextNode = node.values[textureId];\n if (!nextNode) {\n nextNode = new WebGPUBindGroupCacheNode();\n node.values[textureId] = nextNode;\n }\n node = nextNode;\n }\n bindGroups = node.bindGroups;\n }\n drawContext.resetIsDirty(materialContext.updateId);\n materialContext.isDirty = false;\n if (bindGroups) {\n drawContext.bindGroups = bindGroups;\n WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame++;\n return bindGroups;\n }\n bindGroups = [];\n drawContext.bindGroups = bindGroups;\n if (!cacheIsDisabled) {\n node.bindGroups = bindGroups;\n }\n WebGPUCacheBindGroups.NumBindGroupsCreatedTotal++;\n WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame++;\n const bindGroupLayouts = webgpuPipelineContext.bindGroupLayouts[materialContext.textureState];\n for (let i = 0; i < webgpuPipelineContext.shaderProcessingContext.bindGroupLayoutEntries.length; i++) {\n const setDefinition = webgpuPipelineContext.shaderProcessingContext.bindGroupLayoutEntries[i];\n const entries = webgpuPipelineContext.shaderProcessingContext.bindGroupEntries[i];\n for (let j = 0; j < setDefinition.length; j++) {\n const entry = webgpuPipelineContext.shaderProcessingContext.bindGroupLayoutEntries[i][j];\n const entryInfo = webgpuPipelineContext.shaderProcessingContext.bindGroupLayoutEntryInfo[i][entry.binding];\n const name = (_h = entryInfo.nameInArrayOfTexture) !== null && _h !== void 0 ? _h : entryInfo.name;\n if (entry.sampler) {\n const bindingInfo = materialContext.samplers[name];\n if (bindingInfo) {\n const sampler = bindingInfo.sampler;\n if (!sampler) {\n if (this._engine.dbgSanityChecks) {\n Logger.Error(`Trying to bind a null sampler! entry=${JSON.stringify(entry)}, name=${name}, bindingInfo=${JSON.stringify(bindingInfo, (key, value) => (key === \"texture\" ? \"\" : value))}, materialContext.uniqueId=${materialContext.uniqueId}`, 50);\n }\n continue;\n }\n entries[j].resource = this._cacheSampler.getSampler(sampler, false, bindingInfo.hashCode);\n }\n else {\n Logger.Error(`Sampler \"${name}\" could not be bound. entry=${JSON.stringify(entry)}, materialContext=${JSON.stringify(materialContext, (key, value) => key === \"texture\" || key === \"sampler\" ? \"\" : value)}`, 50);\n }\n }\n else if (entry.texture || entry.storageTexture) {\n const bindingInfo = materialContext.textures[name];\n if (bindingInfo) {\n if (this._engine.dbgSanityChecks && bindingInfo.texture === null) {\n Logger.Error(`Trying to bind a null texture! entry=${JSON.stringify(entry)}, bindingInfo=${JSON.stringify(bindingInfo, (key, value) => key === \"texture\" ? \"\" : value)}, materialContext.uniqueId=${materialContext.uniqueId}`, 50);\n continue;\n }\n const hardwareTexture = bindingInfo.texture._hardwareTexture;\n if (this._engine.dbgSanityChecks &&\n (!hardwareTexture || (entry.texture && !hardwareTexture.view) || (entry.storageTexture && !hardwareTexture.viewForWriting))) {\n Logger.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(entry)}, name=${name}, bindingInfo=${JSON.stringify(bindingInfo, (key, value) => (key === \"texture\" ? \"\" : value))}, isReady=${(_j = bindingInfo.texture) === null || _j === void 0 ? void 0 : _j.isReady}, materialContext.uniqueId=${materialContext.uniqueId}`, 50);\n continue;\n }\n entries[j].resource = entry.storageTexture ? hardwareTexture.viewForWriting : hardwareTexture.view;\n }\n else {\n Logger.Error(`Texture \"${name}\" could not be bound. entry=${JSON.stringify(entry)}, materialContext=${JSON.stringify(materialContext, (key, value) => key === \"texture\" || key === \"sampler\" ? \"\" : value)}`, 50);\n }\n }\n else if (entry.externalTexture) {\n const bindingInfo = materialContext.textures[name];\n if (bindingInfo) {\n if (this._engine.dbgSanityChecks && bindingInfo.texture === null) {\n Logger.Error(`Trying to bind a null external texture! entry=${JSON.stringify(entry)}, name=${name}, bindingInfo=${JSON.stringify(bindingInfo, (key, value) => (key === \"texture\" ? \"\" : value))}, materialContext.uniqueId=${materialContext.uniqueId}`, 50);\n continue;\n }\n const externalTexture = bindingInfo.texture.underlyingResource;\n if (this._engine.dbgSanityChecks && !externalTexture) {\n Logger.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(entry)}, name=${name}, bindingInfo=${JSON.stringify(bindingInfo, (key, value) => (key === \"texture\" ? \"\" : value))}, isReady=${(_k = bindingInfo.texture) === null || _k === void 0 ? void 0 : _k.isReady}, materialContext.uniqueId=${materialContext.uniqueId}`, 50);\n continue;\n }\n entries[j].resource = this._device.importExternalTexture({ source: externalTexture });\n }\n else {\n Logger.Error(`Texture \"${name}\" could not be bound. entry=${JSON.stringify(entry)}, materialContext=${JSON.stringify(materialContext, (key, value) => key === \"texture\" || key === \"sampler\" ? \"\" : value)}`, 50);\n }\n }\n else if (entry.buffer) {\n const dataBuffer = drawContext.buffers[name];\n if (dataBuffer) {\n const webgpuBuffer = dataBuffer.underlyingResource;\n entries[j].resource.buffer = webgpuBuffer;\n entries[j].resource.size = dataBuffer.capacity;\n }\n else {\n Logger.Error(`Can't find buffer \"${name}\". entry=${JSON.stringify(entry)}, buffers=${JSON.stringify(drawContext.buffers)}, drawContext.uniqueId=${drawContext.uniqueId}`, 50);\n }\n }\n }\n const groupLayout = bindGroupLayouts[i];\n bindGroups[i] = this._device.createBindGroup({\n layout: groupLayout,\n entries,\n });\n }\n return bindGroups;\n }\n}\nWebGPUCacheBindGroups.NumBindGroupsCreatedTotal = 0;\nWebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame = 0;\nWebGPUCacheBindGroups.NumBindGroupsLookupLastFrame = 0;\nWebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame = 0;\nWebGPUCacheBindGroups._Cache = new WebGPUBindGroupCacheNode();\nWebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame = 0;\nWebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame = 0;\nWebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame = 0;\n//# sourceMappingURL=webgpuCacheBindGroups.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"clearQuadVertexShader\";\nconst shader = `uniform float depthValue;\rconst vec2 pos[4]={\rvec2(-1.0,1.0),\rvec2(1.0,1.0),\rvec2(-1.0,-1.0),\rvec2(1.0,-1.0)\r};\r#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_VERTEX_MAIN_BEGIN\ngl_Position=vec4(pos[gl_VertexID],depthValue,1.0);\r#define CUSTOM_VERTEX_MAIN_END\n}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const clearQuadVertexShader = { name, shader };\n//# sourceMappingURL=clearQuad.vertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"clearQuadPixelShader\";\nconst shader = `uniform vec4 color;\rvoid main() {\rgl_FragColor=color;\r}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const clearQuadPixelShader = { name, shader };\n//# sourceMappingURL=clearQuad.fragment.js.map","\nimport { WebGPUCacheRenderPipelineTree } from \"./webgpuCacheRenderPipelineTree.js\";\nimport { WebGPUShaderProcessingContext } from \"./webgpuShaderProcessingContext.js\";\nimport { renderableTextureFormatToIndex, WebGPUTextureHelper } from \"./webgpuTextureHelper.js\";\nimport \"../../Shaders/clearQuad.vertex.js\";\nimport \"../../Shaders/clearQuad.fragment.js\";\n/** @internal */\nexport class WebGPUClearQuad {\n setDepthStencilFormat(format) {\n this._depthTextureFormat = format;\n this._cacheRenderPipeline.setDepthStencilFormat(format);\n }\n setColorFormat(format) {\n this._cacheRenderPipeline.setColorFormat(format);\n }\n setMRTAttachments(attachments, textureArray, textureCount) {\n this._cacheRenderPipeline.setMRT(textureArray, textureCount);\n this._cacheRenderPipeline.setMRTAttachments(attachments);\n }\n constructor(device, engine, emptyVertexBuffer) {\n this._bindGroups = {};\n this._bundleCache = {};\n this._keyTemp = [];\n this._device = device;\n this._engine = engine;\n this._cacheRenderPipeline = new WebGPUCacheRenderPipelineTree(this._device, emptyVertexBuffer, !engine._caps.textureFloatLinearFiltering);\n this._cacheRenderPipeline.setDepthTestEnabled(false);\n this._cacheRenderPipeline.setStencilReadMask(0xff);\n this._effect = engine.createEffect(\"clearQuad\", [], [\"color\", \"depthValue\"]);\n }\n clear(renderPass, clearColor, clearDepth, clearStencil, sampleCount = 1) {\n var _a, _b;\n let renderPass2;\n let bundle = null;\n let bundleKey;\n const isRTTPass = !!this._engine._currentRenderTarget;\n if (renderPass) {\n renderPass2 = renderPass;\n }\n else {\n let idx = 0;\n this._keyTemp.length = 0;\n for (let i = 0; i < this._cacheRenderPipeline.colorFormats.length; ++i) {\n this._keyTemp[idx++] = renderableTextureFormatToIndex[(_a = this._cacheRenderPipeline.colorFormats[i]) !== null && _a !== void 0 ? _a : \"\"];\n }\n const depthStencilFormatIndex = renderableTextureFormatToIndex[(_b = this._depthTextureFormat) !== null && _b !== void 0 ? _b : 0];\n this._keyTemp[idx] =\n (clearColor ? clearColor.r + clearColor.g * 256 + clearColor.b * 256 * 256 + clearColor.a * 256 * 256 * 256 : 0) +\n (clearDepth ? 2 ** 32 : 0) +\n (clearStencil ? 2 ** 33 : 0) +\n (this._engine.useReverseDepthBuffer ? 2 ** 34 : 0) +\n (isRTTPass ? 2 ** 35 : 0) +\n (sampleCount > 1 ? 2 ** 36 : 0) +\n depthStencilFormatIndex * 2 ** 37;\n bundleKey = this._keyTemp.join(\"_\");\n bundle = this._bundleCache[bundleKey];\n if (bundle) {\n return bundle;\n }\n renderPass2 = this._device.createRenderBundleEncoder({\n colorFormats: this._cacheRenderPipeline.colorFormats,\n depthStencilFormat: this._depthTextureFormat,\n sampleCount,\n });\n }\n this._cacheRenderPipeline.setDepthWriteEnabled(!!clearDepth);\n this._cacheRenderPipeline.setStencilEnabled(!!clearStencil && !!this._depthTextureFormat && WebGPUTextureHelper.HasStencilAspect(this._depthTextureFormat));\n this._cacheRenderPipeline.setStencilWriteMask(clearStencil ? 0xff : 0);\n this._cacheRenderPipeline.setStencilCompare(clearStencil ? 519 : 512);\n this._cacheRenderPipeline.setStencilPassOp(clearStencil ? 7681 : 7680);\n this._cacheRenderPipeline.setWriteMask(clearColor ? 0xf : 0);\n const pipeline = this._cacheRenderPipeline.getRenderPipeline(7, this._effect, sampleCount);\n const webgpuPipelineContext = this._effect._pipelineContext;\n if (clearColor) {\n this._effect.setDirectColor4(\"color\", clearColor);\n }\n this._effect.setFloat(\"depthValue\", this._engine.useReverseDepthBuffer ? this._engine._clearReverseDepthValue : this._engine._clearDepthValue);\n webgpuPipelineContext.uniformBuffer.update();\n const bufferInternals = isRTTPass ? this._engine._ubInvertY : this._engine._ubDontInvertY;\n const bufferLeftOver = webgpuPipelineContext.uniformBuffer.getBuffer();\n const key = bufferLeftOver.uniqueId + \"-\" + bufferInternals.uniqueId;\n let bindGroups = this._bindGroups[key];\n if (!bindGroups) {\n const bindGroupLayouts = webgpuPipelineContext.bindGroupLayouts[0];\n bindGroups = this._bindGroups[key] = [];\n bindGroups.push(this._device.createBindGroup({\n layout: bindGroupLayouts[0],\n entries: [],\n }));\n if (!WebGPUShaderProcessingContext._SimplifiedKnownBindings) {\n bindGroups.push(this._device.createBindGroup({\n layout: bindGroupLayouts[1],\n entries: [],\n }));\n }\n bindGroups.push(this._device.createBindGroup({\n layout: bindGroupLayouts[WebGPUShaderProcessingContext._SimplifiedKnownBindings ? 1 : 2],\n entries: [\n {\n binding: 0,\n resource: {\n buffer: bufferInternals.underlyingResource,\n size: bufferInternals.capacity,\n },\n },\n {\n binding: 1,\n resource: {\n buffer: bufferLeftOver.underlyingResource,\n size: bufferLeftOver.capacity,\n },\n },\n ],\n }));\n }\n renderPass2.setPipeline(pipeline);\n for (let i = 0; i < bindGroups.length; ++i) {\n renderPass2.setBindGroup(i, bindGroups[i]);\n }\n renderPass2.draw(4, 1, 0, 0);\n if (!renderPass) {\n bundle = renderPass2.finish();\n this._bundleCache[bundleKey] = bundle;\n }\n return bundle;\n }\n}\n//# sourceMappingURL=webgpuClearQuad.js.map","/** @internal */\nexport class WebGPURenderItemViewport {\n constructor(x, y, w, h) {\n this.x = Math.floor(x);\n this.y = Math.floor(y);\n this.w = Math.floor(w);\n this.h = Math.floor(h);\n }\n run(renderPass) {\n renderPass.setViewport(this.x, this.y, this.w, this.h, 0, 1);\n }\n clone() {\n return new WebGPURenderItemViewport(this.x, this.y, this.w, this.h);\n }\n}\n/** @internal */\nexport class WebGPURenderItemScissor {\n constructor(x, y, w, h) {\n this.x = x;\n this.y = y;\n this.w = w;\n this.h = h;\n }\n run(renderPass) {\n renderPass.setScissorRect(this.x, this.y, this.w, this.h);\n }\n clone() {\n return new WebGPURenderItemScissor(this.x, this.y, this.w, this.h);\n }\n}\n/** @internal */\nexport class WebGPURenderItemStencilRef {\n constructor(ref) {\n this.ref = ref;\n }\n run(renderPass) {\n renderPass.setStencilReference(this.ref);\n }\n clone() {\n return new WebGPURenderItemStencilRef(this.ref);\n }\n}\n/** @internal */\nexport class WebGPURenderItemBlendColor {\n constructor(color) {\n this.color = color;\n }\n run(renderPass) {\n renderPass.setBlendConstant(this.color);\n }\n clone() {\n return new WebGPURenderItemBlendColor(this.color);\n }\n}\n/** @internal */\nexport class WebGPURenderItemBeginOcclusionQuery {\n constructor(query) {\n this.query = query;\n }\n run(renderPass) {\n renderPass.beginOcclusionQuery(this.query);\n }\n clone() {\n return new WebGPURenderItemBeginOcclusionQuery(this.query);\n }\n}\n/** @internal */\nexport class WebGPURenderItemEndOcclusionQuery {\n constructor() { }\n run(renderPass) {\n renderPass.endOcclusionQuery();\n }\n clone() {\n return new WebGPURenderItemEndOcclusionQuery();\n }\n}\nclass WebGPURenderItemBundles {\n constructor() {\n this.bundles = [];\n }\n run(renderPass) {\n renderPass.executeBundles(this.bundles);\n }\n clone() {\n const cloned = new WebGPURenderItemBundles();\n cloned.bundles = this.bundles;\n return cloned;\n }\n}\n/** @internal */\nexport class WebGPUBundleList {\n constructor(device) {\n this.numDrawCalls = 0;\n this._device = device;\n this._list = new Array(10);\n this._listLength = 0;\n }\n addBundle(bundle) {\n if (!this._currentItemIsBundle) {\n const item = new WebGPURenderItemBundles();\n this._list[this._listLength++] = item;\n this._currentBundleList = item.bundles;\n this._currentItemIsBundle = true;\n }\n if (bundle) {\n this._currentBundleList.push(bundle);\n }\n }\n _finishBundle() {\n if (this._currentItemIsBundle && this._bundleEncoder) {\n this._currentBundleList.push(this._bundleEncoder.finish());\n this._bundleEncoder = undefined;\n this._currentItemIsBundle = false;\n }\n }\n addItem(item) {\n this._finishBundle();\n this._list[this._listLength++] = item;\n this._currentItemIsBundle = false;\n }\n getBundleEncoder(colorFormats, depthStencilFormat, sampleCount) {\n if (!this._currentItemIsBundle) {\n this.addBundle();\n this._bundleEncoder = this._device.createRenderBundleEncoder({\n colorFormats,\n depthStencilFormat,\n sampleCount,\n });\n }\n return this._bundleEncoder;\n }\n close() {\n this._finishBundle();\n }\n run(renderPass) {\n this.close();\n for (let i = 0; i < this._listLength; ++i) {\n this._list[i].run(renderPass);\n }\n }\n reset() {\n this._listLength = 0;\n this._currentItemIsBundle = false;\n this.numDrawCalls = 0;\n }\n clone() {\n this.close();\n const cloned = new WebGPUBundleList(this._device);\n cloned._list = new Array(this._listLength);\n cloned._listLength = this._listLength;\n cloned.numDrawCalls = this.numDrawCalls;\n for (let i = 0; i < this._listLength; ++i) {\n cloned._list[i] = this._list[i].clone();\n }\n return cloned;\n }\n}\n//# sourceMappingURL=webgpuBundleList.js.map","import * as WebGPUConstants from \"./webgpuConstants.js\";\n/** @internal */\nexport class WebGPUQuerySet {\n get querySet() {\n return this._querySet;\n }\n constructor(count, type, device, bufferManager, canUseMultipleBuffers = true) {\n this._dstBuffers = [];\n this._device = device;\n this._bufferManager = bufferManager;\n this._count = count;\n this._canUseMultipleBuffers = canUseMultipleBuffers;\n this._querySet = device.createQuerySet({\n type,\n count,\n });\n this._queryBuffer = bufferManager.createRawBuffer(8 * count, WebGPUConstants.BufferUsage.QueryResolve | WebGPUConstants.BufferUsage.CopySrc);\n if (!canUseMultipleBuffers) {\n this._dstBuffers.push(this._bufferManager.createRawBuffer(8 * this._count, WebGPUConstants.BufferUsage.MapRead | WebGPUConstants.BufferUsage.CopyDst));\n }\n }\n _getBuffer(firstQuery, queryCount) {\n if (!this._canUseMultipleBuffers && this._dstBuffers.length === 0) {\n return null;\n }\n const encoderResult = this._device.createCommandEncoder();\n let buffer;\n if (this._dstBuffers.length === 0) {\n buffer = this._bufferManager.createRawBuffer(8 * this._count, WebGPUConstants.BufferUsage.MapRead | WebGPUConstants.BufferUsage.CopyDst);\n }\n else {\n buffer = this._dstBuffers[this._dstBuffers.length - 1];\n this._dstBuffers.length--;\n }\n encoderResult.resolveQuerySet(this._querySet, firstQuery, queryCount, this._queryBuffer, 0);\n encoderResult.copyBufferToBuffer(this._queryBuffer, 0, buffer, 0, 8 * queryCount);\n this._device.queue.submit([encoderResult.finish()]);\n return buffer;\n }\n async readValues(firstQuery = 0, queryCount = 1) {\n const buffer = this._getBuffer(firstQuery, queryCount);\n if (buffer === null) {\n return null;\n }\n await buffer.mapAsync(WebGPUConstants.MapMode.Read);\n const arrayBuf = new BigUint64Array(buffer.getMappedRange()).slice();\n buffer.unmap();\n this._dstBuffers[this._dstBuffers.length] = buffer;\n return arrayBuf;\n }\n async readValue(firstQuery = 0) {\n const buffer = this._getBuffer(firstQuery, 1);\n if (buffer === null) {\n return null;\n }\n await buffer.mapAsync(WebGPUConstants.MapMode.Read);\n const arrayBuf = new BigUint64Array(buffer.getMappedRange());\n const value = Number(arrayBuf[0]);\n buffer.unmap();\n this._dstBuffers[this._dstBuffers.length] = buffer;\n return value;\n }\n async readTwoValuesAndSubtract(firstQuery = 0) {\n const buffer = this._getBuffer(firstQuery, 2);\n if (buffer === null) {\n return null;\n }\n await buffer.mapAsync(WebGPUConstants.MapMode.Read);\n const arrayBuf = new BigUint64Array(buffer.getMappedRange());\n const value = Number(arrayBuf[1] - arrayBuf[0]);\n buffer.unmap();\n this._dstBuffers[this._dstBuffers.length] = buffer;\n return value;\n }\n dispose() {\n this._querySet.destroy();\n this._bufferManager.releaseBuffer(this._queryBuffer);\n for (let i = 0; i < this._dstBuffers.length; ++i) {\n this._bufferManager.releaseBuffer(this._dstBuffers[i]);\n }\n }\n}\n//# sourceMappingURL=webgpuQuerySet.js.map","import * as WebGPUConstants from \"./webgpuConstants.js\";\nimport { PerfCounter } from \"../../Misc/perfCounter.js\";\nimport { WebGPUQuerySet } from \"./webgpuQuerySet.js\";\n/** @internal */\nexport class WebGPUTimestampQuery {\n get gpuFrameTimeCounter() {\n return this._gpuFrameTimeCounter;\n }\n constructor(device, bufferManager) {\n this._enabled = false;\n this._gpuFrameTimeCounter = new PerfCounter();\n this._measureDurationState = 0;\n this._device = device;\n this._bufferManager = bufferManager;\n }\n get enable() {\n return this._enabled;\n }\n set enable(value) {\n if (this._enabled === value) {\n return;\n }\n this._enabled = value;\n this._measureDurationState = 0;\n if (value) {\n this._measureDuration = new WebGPUDurationMeasure(this._device, this._bufferManager);\n }\n else {\n this._measureDuration.dispose();\n }\n }\n startFrame(commandEncoder) {\n if (this._enabled && this._measureDurationState === 0) {\n this._measureDuration.start(commandEncoder);\n this._measureDurationState = 1;\n }\n }\n endFrame(commandEncoder) {\n if (this._measureDurationState === 1) {\n this._measureDurationState = 2;\n this._measureDuration.stop(commandEncoder).then((duration) => {\n if (duration !== null && duration >= 0) {\n this._gpuFrameTimeCounter.fetchNewFrame();\n this._gpuFrameTimeCounter.addCount(duration, true);\n }\n this._measureDurationState = 0;\n });\n }\n }\n}\n/** @internal */\nexport class WebGPUDurationMeasure {\n constructor(device, bufferManager) {\n this._querySet = new WebGPUQuerySet(2, WebGPUConstants.QueryType.Timestamp, device, bufferManager);\n }\n start(encoder) {\n encoder.writeTimestamp(this._querySet.querySet, 0);\n }\n async stop(encoder) {\n encoder.writeTimestamp(this._querySet.querySet, 1);\n return this._querySet.readTwoValuesAndSubtract(0);\n }\n dispose() {\n this._querySet.dispose();\n }\n}\n//# sourceMappingURL=webgpuTimestampQuery.js.map","import * as WebGPUConstants from \"./webgpuConstants.js\";\nimport { WebGPUQuerySet } from \"./webgpuQuerySet.js\";\n/** @internal */\nexport class WebGPUOcclusionQuery {\n get querySet() {\n return this._querySet.querySet;\n }\n get hasQueries() {\n return this._currentTotalIndices !== this._availableIndices.length;\n }\n get canBeginQuery() {\n const passIndex = this._engine._getCurrentRenderPassIndex();\n switch (passIndex) {\n case 0: {\n return this._engine._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet !== undefined;\n }\n case 1: {\n return this._engine._rttRenderPassWrapper.renderPassDescriptor.occlusionQuerySet !== undefined;\n }\n }\n return false;\n }\n constructor(engine, device, bufferManager, startCount = 50, incrementCount = 100) {\n this._availableIndices = [];\n this._engine = engine;\n this._device = device;\n this._bufferManager = bufferManager;\n this._frameLastBuffer = -1;\n this._currentTotalIndices = 0;\n this._countIncrement = incrementCount;\n this._allocateNewIndices(startCount);\n }\n createQuery() {\n if (this._availableIndices.length === 0) {\n this._allocateNewIndices();\n }\n const index = this._availableIndices[this._availableIndices.length - 1];\n this._availableIndices.length--;\n return index;\n }\n deleteQuery(index) {\n this._availableIndices[this._availableIndices.length - 1] = index;\n }\n isQueryResultAvailable(index) {\n this._retrieveQueryBuffer();\n return !!this._lastBuffer && index < this._lastBuffer.length;\n }\n getQueryResult(index) {\n var _a, _b;\n return Number((_b = (_a = this._lastBuffer) === null || _a === void 0 ? void 0 : _a[index]) !== null && _b !== void 0 ? _b : -1);\n }\n _retrieveQueryBuffer() {\n if (this._lastBuffer && this._frameLastBuffer === this._engine.frameId) {\n return;\n }\n if (this._frameLastBuffer !== this._engine.frameId) {\n this._frameLastBuffer = this._engine.frameId;\n this._querySet.readValues(0, this._currentTotalIndices).then((arrayBuffer) => {\n this._lastBuffer = arrayBuffer;\n });\n }\n }\n _allocateNewIndices(numIndices) {\n numIndices = numIndices !== null && numIndices !== void 0 ? numIndices : this._countIncrement;\n this._delayQuerySetDispose();\n for (let i = 0; i < numIndices; ++i) {\n this._availableIndices.push(this._currentTotalIndices + i);\n }\n this._currentTotalIndices += numIndices;\n this._querySet = new WebGPUQuerySet(this._currentTotalIndices, WebGPUConstants.QueryType.Occlusion, this._device, this._bufferManager, false);\n }\n _delayQuerySetDispose() {\n const querySet = this._querySet;\n if (querySet) {\n // Wait a bit before disposing of the queryset, in case some queries are still running for it\n setTimeout(() => querySet.dispose, 1000);\n }\n }\n dispose() {\n var _a;\n (_a = this._querySet) === null || _a === void 0 ? void 0 : _a.dispose();\n this._availableIndices.length = 0;\n }\n}\n//# sourceMappingURL=webgpuOcclusionQuery.js.map","import { IsWindowObjectExist } from \"../../Misc/domManagement.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/** @internal */\nexport class WebGPUTintWASM {\n async initTwgsl(twgslOptions) {\n if (WebGPUTintWASM._twgsl) {\n return;\n }\n twgslOptions = twgslOptions || {};\n twgslOptions = Object.assign(Object.assign({}, WebGPUTintWASM._TWgslDefaultOptions), twgslOptions);\n if (twgslOptions.twgsl) {\n WebGPUTintWASM._twgsl = twgslOptions.twgsl;\n return Promise.resolve();\n }\n if (twgslOptions.jsPath && twgslOptions.wasmPath) {\n if (IsWindowObjectExist()) {\n await Tools.LoadScriptAsync(twgslOptions.jsPath);\n }\n else {\n importScripts(twgslOptions.jsPath);\n }\n }\n if (self.twgsl) {\n WebGPUTintWASM._twgsl = await self.twgsl(twgslOptions.wasmPath);\n return Promise.resolve();\n }\n return Promise.reject(\"twgsl is not available.\");\n }\n convertSpirV2WGSL(code, disableUniformityAnalysis = false) {\n const ccode = WebGPUTintWASM._twgsl.convertSpirV2WGSL(code);\n if (WebGPUTintWASM.ShowWGSLShaderCode) {\n console.log(ccode);\n console.log(\"***********************************************\");\n }\n return WebGPUTintWASM.DisableUniformityAnalysis || disableUniformityAnalysis ? \"diagnostic(off, derivative_uniformity);\\n\" + ccode : ccode;\n }\n}\n// Default twgsl options.\nWebGPUTintWASM._TWgslDefaultOptions = {\n jsPath: \"https://preview.babylonjs.com/twgsl/twgsl.js\",\n wasmPath: \"https://preview.babylonjs.com/twgsl/twgsl.wasm\",\n};\nWebGPUTintWASM.ShowWGSLShaderCode = false;\nWebGPUTintWASM.DisableUniformityAnalysis = false;\nWebGPUTintWASM._twgsl = null;\n//# sourceMappingURL=webgpuTintWASM.js.map","\n/** @internal */\nexport class WebGPUSnapshotRendering {\n constructor(engine, renderingMode, bundleList, bundleListRenderTarget) {\n this._record = false;\n this._play = false;\n this._mainPassBundleList = [];\n this._enabled = false;\n this._engine = engine;\n this._mode = renderingMode;\n this._bundleList = bundleList;\n this._bundleListRenderTarget = bundleListRenderTarget;\n }\n get enabled() {\n return this._enabled;\n }\n get play() {\n return this._play;\n }\n get record() {\n return this._record;\n }\n set enabled(activate) {\n this._mainPassBundleList.length = 0;\n this._record = this._enabled = activate;\n this._play = false;\n if (activate) {\n this._modeSaved = this._mode;\n this._mode = 0; // need to reset to standard for the recording pass to avoid some code being bypassed\n }\n }\n get mode() {\n return this._mode;\n }\n set mode(mode) {\n if (this._record) {\n this._modeSaved = mode;\n }\n else {\n this._mode = mode;\n }\n }\n endMainRenderPass() {\n if (this._record) {\n this._mainPassBundleList.push(this._bundleList.clone());\n }\n }\n endRenderTargetPass(currentRenderPass, gpuWrapper) {\n var _a, _b, _c, _d;\n if (this._play) {\n (_b = (_a = gpuWrapper._bundleLists) === null || _a === void 0 ? void 0 : _a[gpuWrapper._currentLayer]) === null || _b === void 0 ? void 0 : _b.run(currentRenderPass);\n if (this._mode === 1) {\n this._engine._reportDrawCall((_d = (_c = gpuWrapper._bundleLists) === null || _c === void 0 ? void 0 : _c[gpuWrapper._currentLayer]) === null || _d === void 0 ? void 0 : _d.numDrawCalls);\n }\n }\n else if (this._record) {\n if (!gpuWrapper._bundleLists) {\n gpuWrapper._bundleLists = [];\n }\n gpuWrapper._bundleLists[gpuWrapper._currentLayer] = this._bundleListRenderTarget.clone();\n gpuWrapper._bundleLists[gpuWrapper._currentLayer].run(currentRenderPass);\n this._bundleListRenderTarget.reset();\n }\n else {\n return false;\n }\n return true;\n }\n endFrame(mainRenderPass) {\n if (this._record) {\n this._mainPassBundleList.push(this._bundleList.clone());\n this._record = false;\n this._play = true;\n this._mode = this._modeSaved;\n }\n if (mainRenderPass !== null && this._play) {\n for (let i = 0; i < this._mainPassBundleList.length; ++i) {\n this._mainPassBundleList[i].run(mainRenderPass);\n if (this._mode === 1) {\n this._engine._reportDrawCall(this._mainPassBundleList[i].numDrawCalls);\n }\n }\n }\n }\n reset() {\n this.enabled = false;\n this.enabled = true;\n }\n}\n//# sourceMappingURL=webgpuSnapshotRendering.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"postprocessVertexShader\";\nconst shader = `attribute position: vec2;\runiform scale: vec2;\rvarying vUV: vec2;\rconst madd=vec2(0.5,0.5);\r#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\rfn main(input : VertexInputs)->FragmentInputs {\r#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;\rvertexOutputs.position=vec4(vertexInputs.position,0.0,1.0);\r#define CUSTOM_VERTEX_MAIN_END\n}\r`;\n// Sideeffect\nShaderStore.ShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const postprocessVertexShader = { name, shader };\n//# sourceMappingURL=postprocess.vertex.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { IsWindowObjectExist } from \"../Misc/domManagement.js\";\nimport { Color4 } from \"../Maths/math.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { InternalTexture, InternalTextureSource } from \"../Materials/Textures/internalTexture.js\";\nimport { Effect } from \"../Materials/effect.js\";\n\nimport * as WebGPUConstants from \"./WebGPU/webgpuConstants.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { WebGPUPipelineContext } from \"./WebGPU/webgpuPipelineContext.js\";\nimport { WebGPUShaderProcessorGLSL } from \"./WebGPU/webgpuShaderProcessorsGLSL.js\";\nimport { WebGPUShaderProcessorWGSL } from \"./WebGPU/webgpuShaderProcessorsWGSL.js\";\nimport { WebGPUShaderProcessingContext } from \"./WebGPU/webgpuShaderProcessingContext.js\";\nimport { Tools } from \"../Misc/tools.js\";\nimport { WebGPUTextureHelper } from \"./WebGPU/webgpuTextureHelper.js\";\nimport { WebGPUBufferManager } from \"./WebGPU/webgpuBufferManager.js\";\nimport { WebGPUHardwareTexture } from \"./WebGPU/webgpuHardwareTexture.js\";\nimport { UniformBuffer } from \"../Materials/uniformBuffer.js\";\nimport { WebGPURenderPassWrapper } from \"./WebGPU/webgpuRenderPassWrapper.js\";\nimport { WebGPUCacheSampler } from \"./WebGPU/webgpuCacheSampler.js\";\nimport { WebGPUCacheRenderPipelineTree } from \"./WebGPU/webgpuCacheRenderPipelineTree.js\";\nimport { WebGPUStencilStateComposer } from \"./WebGPU/webgpuStencilStateComposer.js\";\nimport { WebGPUDepthCullingState } from \"./WebGPU/webgpuDepthCullingState.js\";\nimport { DrawWrapper } from \"../Materials/drawWrapper.js\";\nimport { WebGPUMaterialContext } from \"./WebGPU/webgpuMaterialContext.js\";\nimport { WebGPUDrawContext } from \"./WebGPU/webgpuDrawContext.js\";\nimport { WebGPUCacheBindGroups } from \"./WebGPU/webgpuCacheBindGroups.js\";\nimport { WebGPUClearQuad } from \"./WebGPU/webgpuClearQuad.js\";\nimport { WebGPURenderItemBlendColor, WebGPURenderItemScissor, WebGPURenderItemStencilRef, WebGPURenderItemViewport, WebGPUBundleList } from \"./WebGPU/webgpuBundleList.js\";\nimport { WebGPUTimestampQuery } from \"./WebGPU/webgpuTimestampQuery.js\";\nimport { WebGPUOcclusionQuery } from \"./WebGPU/webgpuOcclusionQuery.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { ShaderCodeInliner } from \"./Processors/shaderCodeInliner.js\";\nimport { WebGPUTintWASM } from \"./WebGPU/webgpuTintWASM.js\";\nimport { WebGPUShaderProcessor } from \"./WebGPU/webgpuShaderProcessor.js\";\nimport { ShaderLanguage } from \"../Materials/shaderLanguage.js\";\nimport { WebGPUSnapshotRendering } from \"./WebGPU/webgpuSnapshotRendering.js\";\nimport \"../ShadersWGSL/postprocess.vertex.js\";\nconst viewDescriptorSwapChainAntialiasing = {\n label: `TextureView_SwapChain_ResolveTarget`,\n dimension: WebGPUConstants.TextureDimension.E2d,\n format: undefined,\n mipLevelCount: 1,\n arrayLayerCount: 1,\n};\nconst viewDescriptorSwapChain = {\n label: `TextureView_SwapChain`,\n dimension: WebGPUConstants.TextureDimension.E2d,\n format: undefined,\n mipLevelCount: 1,\n arrayLayerCount: 1,\n};\nconst disableUniformityAnalysisMarker = \"/* disable_uniformity_analysis */\";\n/**\n * The web GPU engine class provides support for WebGPU version of babylon.js.\n * @since 5.0.0\n */\nexport class WebGPUEngine extends Engine {\n /**\n * Gets or sets the snapshot rendering mode\n */\n get snapshotRenderingMode() {\n return this._snapshotRendering.mode;\n }\n set snapshotRenderingMode(mode) {\n this._snapshotRendering.mode = mode;\n }\n /**\n * Creates a new snapshot at the next frame using the current snapshotRenderingMode\n */\n snapshotRenderingReset() {\n this._snapshotRendering.reset();\n }\n /**\n * Enables or disables the snapshot rendering mode\n * Note that the WebGL engine does not support snapshot rendering so setting the value won't have any effect for this engine\n */\n get snapshotRendering() {\n return this._snapshotRendering.enabled;\n }\n set snapshotRendering(activate) {\n this._snapshotRendering.enabled = activate;\n }\n /**\n * Sets this to true to disable the cache for the samplers. You should do it only for testing purpose!\n */\n get disableCacheSamplers() {\n return this._cacheSampler ? this._cacheSampler.disabled : false;\n }\n set disableCacheSamplers(disable) {\n if (this._cacheSampler) {\n this._cacheSampler.disabled = disable;\n }\n }\n /**\n * Sets this to true to disable the cache for the render pipelines. You should do it only for testing purpose!\n */\n get disableCacheRenderPipelines() {\n return this._cacheRenderPipeline ? this._cacheRenderPipeline.disabled : false;\n }\n set disableCacheRenderPipelines(disable) {\n if (this._cacheRenderPipeline) {\n this._cacheRenderPipeline.disabled = disable;\n }\n }\n /**\n * Sets this to true to disable the cache for the bind groups. You should do it only for testing purpose!\n */\n get disableCacheBindGroups() {\n return this._cacheBindGroups ? this._cacheBindGroups.disabled : false;\n }\n set disableCacheBindGroups(disable) {\n if (this._cacheBindGroups) {\n this._cacheBindGroups.disabled = disable;\n }\n }\n /**\n * Gets a Promise indicating if the engine can be instantiated (ie. if a WebGPU context can be found)\n */\n static get IsSupportedAsync() {\n return !navigator.gpu\n ? Promise.resolve(false)\n : navigator.gpu\n .requestAdapter()\n .then((adapter) => !!adapter, () => false)\n .catch(() => false);\n }\n /**\n * Not supported by WebGPU, you should call IsSupportedAsync instead!\n */\n static get IsSupported() {\n Logger.Warn(\"You must call IsSupportedAsync for WebGPU!\");\n return false;\n }\n /**\n * Gets a boolean indicating that the engine supports uniform buffers\n */\n get supportsUniformBuffers() {\n return true;\n }\n /** Gets the supported extensions by the WebGPU adapter */\n get supportedExtensions() {\n return this._adapterSupportedExtensions;\n }\n /** Gets the currently enabled extensions on the WebGPU device */\n get enabledExtensions() {\n return this._deviceEnabledExtensions;\n }\n /** Gets the supported limits by the WebGPU adapter */\n get supportedLimits() {\n return this._adapterSupportedLimits;\n }\n /** Gets the current limits of the WebGPU device */\n get currentLimits() {\n return this._deviceLimits;\n }\n /**\n * Returns a string describing the current engine\n */\n get description() {\n const description = this.name + this.version;\n return description;\n }\n /**\n * Returns the version of the engine\n */\n get version() {\n return 1;\n }\n /**\n * Gets an object containing information about the current engine context\n * @returns an object containing the vendor, the renderer and the version of the current engine context\n */\n getInfo() {\n return {\n vendor: this._adapterInfo.vendor || \"unknown vendor\",\n renderer: this._adapterInfo.architecture || \"unknown renderer\",\n version: this._adapterInfo.description || \"unknown version\",\n };\n }\n /**\n * (WebGPU only) True (default) to be in compatibility mode, meaning rendering all existing scenes without artifacts (same rendering than WebGL).\n * Setting the property to false will improve performances but may not work in some scenes if some precautions are not taken.\n * See https://doc.babylonjs.com/setup/support/webGPU/webGPUOptimization/webGPUNonCompatibilityMode for more details\n */\n get compatibilityMode() {\n return this._compatibilityMode;\n }\n set compatibilityMode(mode) {\n this._compatibilityMode = mode;\n }\n /** @internal */\n get currentSampleCount() {\n return this._currentRenderTarget ? this._currentRenderTarget.samples : this._mainPassSampleCount;\n }\n /**\n * Create a new instance of the gpu engine asynchronously\n * @param canvas Defines the canvas to use to display the result\n * @param options Defines the options passed to the engine to create the GPU context dependencies\n * @returns a promise that resolves with the created engine\n */\n static CreateAsync(canvas, options = {}) {\n const engine = new WebGPUEngine(canvas, options);\n return new Promise((resolve) => {\n engine.initAsync(options.glslangOptions, options.twgslOptions).then(() => resolve(engine));\n });\n }\n /**\n * Create a new instance of the gpu engine.\n * @param canvas Defines the canvas to use to display the result\n * @param options Defines the options passed to the engine to create the GPU context dependencies\n */\n constructor(canvas, options = {}) {\n var _a, _b;\n super(null, (_a = options.antialias) !== null && _a !== void 0 ? _a : true, options);\n // Page Life cycle and constants\n this._uploadEncoderDescriptor = { label: \"upload\" };\n this._renderEncoderDescriptor = { label: \"render\" };\n this._renderTargetEncoderDescriptor = { label: \"renderTarget\" };\n /** @internal */\n this._clearDepthValue = 1;\n /** @internal */\n this._clearReverseDepthValue = 0;\n /** @internal */\n this._clearStencilValue = 0;\n this._defaultSampleCount = 4; // Only supported value for now.\n this._glslang = null;\n this._tintWASM = null;\n this._adapterInfo = {\n vendor: \"\",\n architecture: \"\",\n device: \"\",\n description: \"\",\n };\n /** @internal */\n this._compiledComputeEffects = {};\n /** @internal */\n this._counters = {\n numEnableEffects: 0,\n numEnableDrawWrapper: 0,\n numBundleCreationNonCompatMode: 0,\n numBundleReuseNonCompatMode: 0,\n };\n /**\n * Counters from last frame\n */\n this.countersLastFrame = {\n numEnableEffects: 0,\n numEnableDrawWrapper: 0,\n numBundleCreationNonCompatMode: 0,\n numBundleReuseNonCompatMode: 0,\n };\n /**\n * Max number of uncaptured error messages to log\n */\n this.numMaxUncapturedErrors = 20;\n this._commandBuffers = [null, null, null];\n // Frame Buffer Life Cycle (recreated for each render target pass)\n /** @internal */\n this._currentRenderPass = null;\n /** @internal */\n this._mainRenderPassWrapper = new WebGPURenderPassWrapper();\n /** @internal */\n this._rttRenderPassWrapper = new WebGPURenderPassWrapper();\n /** @internal */\n this._pendingDebugCommands = [];\n /** @internal */\n this._onAfterUnbindFrameBufferObservable = new Observable();\n this._currentOverrideVertexBuffers = null;\n this._currentIndexBuffer = null;\n this._colorWriteLocal = true;\n this._forceEnableEffect = false;\n // TODO WEBGPU remove those variables when code stabilized\n /** @internal */\n this.dbgShowShaderCode = false;\n /** @internal */\n this.dbgSanityChecks = true;\n /** @internal */\n this.dbgVerboseLogsForFirstFrames = false;\n /** @internal */\n this.dbgVerboseLogsNumFrames = 10;\n /** @internal */\n this.dbgLogIfNotDrawWrapper = true;\n /** @internal */\n this.dbgShowEmptyEnableEffectCalls = true;\n /**\n * Indicates if the z range in NDC space is 0..1 (value: true) or -1..1 (value: false)\n */\n this.isNDCHalfZRange = true;\n /**\n * Indicates that the origin of the texture/framebuffer space is the bottom left corner. If false, the origin is top left\n */\n this.hasOriginBottomLeft = false;\n //------------------------------------------------------------------------------\n // Dynamic WebGPU States\n //------------------------------------------------------------------------------\n // index 0 is for main render pass, 1 for RTT render pass\n this._viewportsCurrent = [\n { x: 0, y: 0, w: 0, h: 0 },\n { x: 0, y: 0, w: 0, h: 0 },\n ];\n this._scissorsCurrent = [\n { x: 0, y: 0, w: 0, h: 0 },\n { x: 0, y: 0, w: 0, h: 0 },\n ];\n this._scissorCached = { x: 0, y: 0, z: 0, w: 0 };\n this._stencilRefsCurrent = [-1, -1];\n this._blendColorsCurrent = [\n [null, null, null, null],\n [null, null, null, null],\n ];\n this._name = \"WebGPU\";\n options.deviceDescriptor = options.deviceDescriptor || {};\n options.enableGPUDebugMarkers = (_b = options.enableGPUDebugMarkers) !== null && _b !== void 0 ? _b : false;\n Logger.Log(`Babylon.js v${Engine.Version} - ${this.description} engine`);\n if (!navigator.gpu) {\n Logger.Error(\"WebGPU is not supported by your browser.\");\n return;\n }\n options.swapChainFormat = options.swapChainFormat || navigator.gpu.getPreferredCanvasFormat();\n this._isWebGPU = true;\n this._shaderPlatformName = \"WEBGPU\";\n this._renderingCanvas = canvas;\n this._options = options;\n this._mainPassSampleCount = options.antialias ? this._defaultSampleCount : 1;\n this._setupMobileChecks();\n this._sharedInit(canvas);\n this._shaderProcessor = new WebGPUShaderProcessorGLSL();\n this._shaderProcessorWGSL = new WebGPUShaderProcessorWGSL();\n }\n //------------------------------------------------------------------------------\n // Initialization\n //------------------------------------------------------------------------------\n /**\n * Initializes the WebGPU context and dependencies.\n * @param glslangOptions Defines the GLSLang compiler options if necessary\n * @param twgslOptions Defines the Twgsl compiler options if necessary\n * @returns a promise notifying the readiness of the engine.\n */\n initAsync(glslangOptions, twgslOptions) {\n var _a;\n return this._initGlslang(glslangOptions !== null && glslangOptions !== void 0 ? glslangOptions : (_a = this._options) === null || _a === void 0 ? void 0 : _a.glslangOptions)\n .then((glslang) => {\n var _a;\n this._glslang = glslang;\n this._tintWASM = WebGPUEngine.UseTWGSL ? new WebGPUTintWASM() : null;\n return this._tintWASM\n ? this._tintWASM.initTwgsl(twgslOptions !== null && twgslOptions !== void 0 ? twgslOptions : (_a = this._options) === null || _a === void 0 ? void 0 : _a.twgslOptions).then(() => {\n return navigator.gpu.requestAdapter(this._options);\n }, (msg) => {\n Logger.Error(\"Can not initialize twgsl!\");\n Logger.Error(msg);\n throw Error(\"WebGPU initializations stopped.\");\n })\n : navigator.gpu.requestAdapter(this._options);\n }, (msg) => {\n Logger.Error(\"Can not initialize glslang!\");\n Logger.Error(msg);\n throw Error(\"WebGPU initializations stopped.\");\n })\n .then((adapter) => {\n var _a, _b, _c;\n if (!adapter) {\n throw \"Could not retrieve a WebGPU adapter (adapter is null).\";\n }\n else {\n this._adapter = adapter;\n this._adapterSupportedExtensions = [];\n (_a = this._adapter.features) === null || _a === void 0 ? void 0 : _a.forEach((feature) => this._adapterSupportedExtensions.push(feature));\n this._adapterSupportedLimits = this._adapter.limits;\n this._adapter.requestAdapterInfo().then((adapterInfo) => {\n this._adapterInfo = adapterInfo;\n });\n const deviceDescriptor = (_b = this._options.deviceDescriptor) !== null && _b !== void 0 ? _b : {};\n const requiredFeatures = (_c = deviceDescriptor === null || deviceDescriptor === void 0 ? void 0 : deviceDescriptor.requiredFeatures) !== null && _c !== void 0 ? _c : (this._options.enableAllFeatures ? this._adapterSupportedExtensions : undefined);\n if (requiredFeatures) {\n const requestedExtensions = requiredFeatures;\n const validExtensions = [];\n for (const extension of requestedExtensions) {\n if (this._adapterSupportedExtensions.indexOf(extension) !== -1) {\n validExtensions.push(extension);\n }\n }\n deviceDescriptor.requiredFeatures = validExtensions;\n }\n if (this._options.setMaximumLimits && !deviceDescriptor.requiredLimits) {\n deviceDescriptor.requiredLimits = {};\n for (const name in this._adapterSupportedLimits) {\n deviceDescriptor.requiredLimits[name] = this._adapterSupportedLimits[name];\n }\n }\n return this._adapter.requestDevice(deviceDescriptor);\n }\n })\n .then((device) => {\n var _a, _b;\n this._device = device;\n this._deviceEnabledExtensions = [];\n (_a = this._device.features) === null || _a === void 0 ? void 0 : _a.forEach((feature) => this._deviceEnabledExtensions.push(feature));\n this._deviceLimits = device.limits;\n let numUncapturedErrors = -1;\n this._device.addEventListener(\"uncapturederror\", (event) => {\n if (++numUncapturedErrors < this.numMaxUncapturedErrors) {\n Logger.Warn(`WebGPU uncaptured error (${numUncapturedErrors + 1}): ${event.error} - ${event.error.message}`);\n }\n else if (numUncapturedErrors++ === this.numMaxUncapturedErrors) {\n Logger.Warn(`WebGPU uncaptured error: too many warnings (${this.numMaxUncapturedErrors}), no more warnings will be reported to the console for this engine.`);\n }\n });\n if (!this._doNotHandleContextLost) {\n (_b = this._device.lost) === null || _b === void 0 ? void 0 : _b.then((info) => {\n if (this._isDisposed) {\n return;\n }\n this._contextWasLost = true;\n Logger.Warn(\"WebGPU context lost. \" + info);\n this.onContextLostObservable.notifyObservers(this);\n this._restoreEngineAfterContextLost(this.initAsync.bind(this));\n });\n }\n }, (e) => {\n Logger.Error(\"Could not retrieve a WebGPU device.\");\n Logger.Error(e);\n })\n .then(() => {\n this._bufferManager = new WebGPUBufferManager(this._device);\n this._textureHelper = new WebGPUTextureHelper(this._device, this._glslang, this._tintWASM, this._bufferManager, this._deviceEnabledExtensions);\n this._cacheSampler = new WebGPUCacheSampler(this._device);\n this._cacheBindGroups = new WebGPUCacheBindGroups(this._device, this._cacheSampler, this);\n this._timestampQuery = new WebGPUTimestampQuery(this._device, this._bufferManager);\n this._occlusionQuery = this._device.createQuerySet ? new WebGPUOcclusionQuery(this, this._device, this._bufferManager) : undefined;\n this._bundleList = new WebGPUBundleList(this._device);\n this._bundleListRenderTarget = new WebGPUBundleList(this._device);\n this._snapshotRendering = new WebGPUSnapshotRendering(this, this._snapshotRenderingMode, this._bundleList, this._bundleListRenderTarget);\n this._ubInvertY = this._bufferManager.createBuffer(new Float32Array([-1, 0]), WebGPUConstants.BufferUsage.Uniform | WebGPUConstants.BufferUsage.CopyDst);\n this._ubDontInvertY = this._bufferManager.createBuffer(new Float32Array([1, 0]), WebGPUConstants.BufferUsage.Uniform | WebGPUConstants.BufferUsage.CopyDst);\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n console.log(\"%c frame #\" + this._count + \" - begin\", \"background: #ffff00\");\n }\n }\n this._uploadEncoder = this._device.createCommandEncoder(this._uploadEncoderDescriptor);\n this._renderEncoder = this._device.createCommandEncoder(this._renderEncoderDescriptor);\n this._renderTargetEncoder = this._device.createCommandEncoder(this._renderTargetEncoderDescriptor);\n this._emptyVertexBuffer = new VertexBuffer(this, [0], \"\", false, false, 1, false, 0, 1);\n this._initializeLimits();\n this._cacheRenderPipeline = new WebGPUCacheRenderPipelineTree(this._device, this._emptyVertexBuffer, !this._caps.textureFloatLinearFiltering);\n this._depthCullingState = new WebGPUDepthCullingState(this._cacheRenderPipeline);\n this._stencilStateComposer = new WebGPUStencilStateComposer(this._cacheRenderPipeline);\n this._stencilStateComposer.stencilGlobal = this._stencilState;\n this._depthCullingState.depthTest = true;\n this._depthCullingState.depthFunc = 515;\n this._depthCullingState.depthMask = true;\n this._textureHelper.setCommandEncoder(this._uploadEncoder);\n this._clearQuad = new WebGPUClearQuad(this._device, this, this._emptyVertexBuffer);\n this._defaultDrawContext = this.createDrawContext();\n this._currentDrawContext = this._defaultDrawContext;\n this._defaultMaterialContext = this.createMaterialContext();\n this._currentMaterialContext = this._defaultMaterialContext;\n this._initializeContextAndSwapChain();\n this._initializeMainAttachments();\n this.resize();\n })\n .catch((e) => {\n Logger.Error(\"Can not create WebGPU Device and/or context.\");\n Logger.Error(e);\n if (console.trace) {\n console.trace();\n }\n });\n }\n _initGlslang(glslangOptions) {\n glslangOptions = glslangOptions || {};\n glslangOptions = Object.assign(Object.assign({}, WebGPUEngine._GLSLslangDefaultOptions), glslangOptions);\n if (glslangOptions.glslang) {\n return Promise.resolve(glslangOptions.glslang);\n }\n if (self.glslang) {\n return self.glslang(glslangOptions.wasmPath);\n }\n if (glslangOptions.jsPath && glslangOptions.wasmPath) {\n if (IsWindowObjectExist()) {\n return Tools.LoadScriptAsync(glslangOptions.jsPath).then(() => {\n return self.glslang(glslangOptions.wasmPath);\n });\n }\n else {\n importScripts(glslangOptions.jsPath);\n return self.glslang(glslangOptions.wasmPath);\n }\n }\n return Promise.reject(\"gslang is not available.\");\n }\n _initializeLimits() {\n // Init caps\n // TODO WEBGPU Real Capability check once limits will be working.\n this._caps = {\n maxTexturesImageUnits: this._deviceLimits.maxSampledTexturesPerShaderStage,\n maxVertexTextureImageUnits: this._deviceLimits.maxSampledTexturesPerShaderStage,\n maxCombinedTexturesImageUnits: this._deviceLimits.maxSampledTexturesPerShaderStage * 2,\n maxTextureSize: this._deviceLimits.maxTextureDimension2D,\n maxCubemapTextureSize: this._deviceLimits.maxTextureDimension2D,\n maxRenderTextureSize: this._deviceLimits.maxTextureDimension2D,\n maxVertexAttribs: this._deviceLimits.maxVertexAttributes,\n maxVaryingVectors: this._deviceLimits.maxInterStageShaderVariables,\n maxFragmentUniformVectors: Math.floor(this._deviceLimits.maxUniformBufferBindingSize / 4),\n maxVertexUniformVectors: Math.floor(this._deviceLimits.maxUniformBufferBindingSize / 4),\n standardDerivatives: true,\n astc: (this._deviceEnabledExtensions.indexOf(WebGPUConstants.FeatureName.TextureCompressionASTC) >= 0 ? true : undefined),\n s3tc: (this._deviceEnabledExtensions.indexOf(WebGPUConstants.FeatureName.TextureCompressionBC) >= 0 ? true : undefined),\n pvrtc: null,\n etc1: null,\n etc2: (this._deviceEnabledExtensions.indexOf(WebGPUConstants.FeatureName.TextureCompressionETC2) >= 0 ? true : undefined),\n bptc: this._deviceEnabledExtensions.indexOf(WebGPUConstants.FeatureName.TextureCompressionBC) >= 0 ? true : undefined,\n maxAnisotropy: 16,\n uintIndices: true,\n fragmentDepthSupported: true,\n highPrecisionShaderSupported: true,\n colorBufferFloat: true,\n textureFloat: true,\n textureFloatLinearFiltering: this._deviceEnabledExtensions.indexOf(WebGPUConstants.FeatureName.Float32Filterable) >= 0,\n textureFloatRender: true,\n textureHalfFloat: true,\n textureHalfFloatLinearFiltering: true,\n textureHalfFloatRender: true,\n textureLOD: true,\n texelFetch: true,\n drawBuffersExtension: true,\n depthTextureExtension: true,\n vertexArrayObject: false,\n instancedArrays: true,\n timerQuery: typeof BigUint64Array !== \"undefined\" && this._deviceEnabledExtensions.indexOf(WebGPUConstants.FeatureName.TimestampQuery) !== -1 ? true : undefined,\n supportOcclusionQuery: typeof BigUint64Array !== \"undefined\",\n canUseTimestampForTimerQuery: true,\n multiview: false,\n oculusMultiview: false,\n parallelShaderCompile: undefined,\n blendMinMax: true,\n maxMSAASamples: 4,\n canUseGLInstanceID: true,\n canUseGLVertexID: true,\n supportComputeShaders: true,\n supportSRGBBuffers: true,\n supportTransformFeedbacks: false,\n textureMaxLevel: true,\n texture2DArrayMaxLayerCount: this._deviceLimits.maxTextureArrayLayers,\n disableMorphTargetTexture: false,\n };\n this._caps.parallelShaderCompile = null;\n this._features = {\n forceBitmapOverHTMLImageElement: true,\n supportRenderAndCopyToLodForFloatTextures: true,\n supportDepthStencilTexture: true,\n supportShadowSamplers: true,\n uniformBufferHardCheckMatrix: false,\n allowTexturePrefiltering: true,\n trackUbosInFrame: true,\n checkUbosContentBeforeUpload: true,\n supportCSM: true,\n basisNeedsPOT: false,\n support3DTextures: true,\n needTypeSuffixInShaderConstants: true,\n supportMSAA: true,\n supportSSAO2: true,\n supportExtendedTextureFormats: true,\n supportSwitchCaseInShader: true,\n supportSyncTextureRead: false,\n needsInvertingBitmap: false,\n useUBOBindingCache: false,\n needShaderCodeInlining: true,\n needToAlwaysBindUniformBuffers: true,\n supportRenderPasses: true,\n supportSpriteInstancing: true,\n _collectUbosUpdatedInFrame: false,\n };\n }\n _initializeContextAndSwapChain() {\n if (!this._renderingCanvas) {\n throw \"The rendering canvas has not been set!\";\n }\n this._context = this._renderingCanvas.getContext(\"webgpu\");\n this._configureContext();\n this._colorFormat = this._options.swapChainFormat;\n this._mainRenderPassWrapper.colorAttachmentGPUTextures = [new WebGPUHardwareTexture()];\n this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format = this._colorFormat;\n }\n // Set default values as WebGL with depth and stencil attachment for the broadest Compat.\n _initializeMainAttachments() {\n if (!this._bufferManager) {\n return;\n }\n this.flushFramebuffer(false);\n this._mainTextureExtends = {\n width: this.getRenderWidth(true),\n height: this.getRenderHeight(true),\n depthOrArrayLayers: 1,\n };\n const bufferDataUpdate = new Float32Array([this.getRenderHeight(true)]);\n this._bufferManager.setSubData(this._ubInvertY, 4, bufferDataUpdate);\n this._bufferManager.setSubData(this._ubDontInvertY, 4, bufferDataUpdate);\n let mainColorAttachments;\n if (this._options.antialias) {\n const mainTextureDescriptor = {\n label: `Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,\n size: this._mainTextureExtends,\n mipLevelCount: 1,\n sampleCount: this._mainPassSampleCount,\n dimension: WebGPUConstants.TextureDimension.E2d,\n format: this._options.swapChainFormat,\n usage: WebGPUConstants.TextureUsage.RenderAttachment,\n };\n if (this._mainTexture) {\n this._textureHelper.releaseTexture(this._mainTexture);\n }\n this._mainTexture = this._device.createTexture(mainTextureDescriptor);\n mainColorAttachments = [\n {\n view: this._mainTexture.createView({\n label: \"TextureView_MainColor_antialiasing\",\n dimension: WebGPUConstants.TextureDimension.E2d,\n format: this._options.swapChainFormat,\n mipLevelCount: 1,\n arrayLayerCount: 1,\n }),\n clearValue: new Color4(0, 0, 0, 1),\n loadOp: WebGPUConstants.LoadOp.Clear,\n storeOp: WebGPUConstants.StoreOp.Store, // don't use StoreOp.Discard, else using several cameras with different viewports or using scissors will fail because we call beginRenderPass / endPass several times for the same color attachment!\n },\n ];\n }\n else {\n mainColorAttachments = [\n {\n view: undefined,\n clearValue: new Color4(0, 0, 0, 1),\n loadOp: WebGPUConstants.LoadOp.Clear,\n storeOp: WebGPUConstants.StoreOp.Store,\n },\n ];\n }\n this._mainRenderPassWrapper.depthTextureFormat = this.isStencilEnable ? WebGPUConstants.TextureFormat.Depth24PlusStencil8 : WebGPUConstants.TextureFormat.Depth32Float;\n this._setDepthTextureFormat(this._mainRenderPassWrapper);\n const depthTextureDescriptor = {\n label: `Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,\n size: this._mainTextureExtends,\n mipLevelCount: 1,\n sampleCount: this._mainPassSampleCount,\n dimension: WebGPUConstants.TextureDimension.E2d,\n format: this._mainRenderPassWrapper.depthTextureFormat,\n usage: WebGPUConstants.TextureUsage.RenderAttachment,\n };\n if (this._depthTexture) {\n this._textureHelper.releaseTexture(this._depthTexture);\n }\n this._depthTexture = this._device.createTexture(depthTextureDescriptor);\n const mainDepthAttachment = {\n view: this._depthTexture.createView({\n label: `TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,\n dimension: WebGPUConstants.TextureDimension.E2d,\n format: this._depthTexture.format,\n mipLevelCount: 1,\n arrayLayerCount: 1,\n }),\n depthClearValue: this._clearDepthValue,\n depthLoadOp: WebGPUConstants.LoadOp.Clear,\n depthStoreOp: WebGPUConstants.StoreOp.Store,\n stencilClearValue: this._clearStencilValue,\n stencilLoadOp: !this.isStencilEnable ? undefined : WebGPUConstants.LoadOp.Clear,\n stencilStoreOp: !this.isStencilEnable ? undefined : WebGPUConstants.StoreOp.Store,\n };\n this._mainRenderPassWrapper.renderPassDescriptor = {\n colorAttachments: mainColorAttachments,\n depthStencilAttachment: mainDepthAttachment,\n };\n }\n _configureContext() {\n this._context.configure({\n device: this._device,\n format: this._options.swapChainFormat,\n usage: WebGPUConstants.TextureUsage.RenderAttachment | WebGPUConstants.TextureUsage.CopySrc,\n alphaMode: this.premultipliedAlpha ? WebGPUConstants.CanvasAlphaMode.Premultiplied : WebGPUConstants.CanvasAlphaMode.Opaque,\n });\n }\n /**\n * Force a specific size of the canvas\n * @param width defines the new canvas' width\n * @param height defines the new canvas' height\n * @param forceSetSize true to force setting the sizes of the underlying canvas\n * @returns true if the size was changed\n */\n setSize(width, height, forceSetSize = false) {\n if (!super.setSize(width, height, forceSetSize)) {\n return false;\n }\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n console.log(\"frame #\" + this._count + \" - setSize called -\", width, height);\n }\n }\n this._initializeMainAttachments();\n if (this.snapshotRendering) {\n // reset snapshot rendering so that the next frame will record a new list of bundles\n this.snapshotRenderingReset();\n }\n return true;\n }\n /**\n * @internal\n */\n _getShaderProcessor(shaderLanguage) {\n if (shaderLanguage === ShaderLanguage.WGSL) {\n return this._shaderProcessorWGSL;\n }\n return this._shaderProcessor;\n }\n /**\n * @internal\n */\n _getShaderProcessingContext(shaderLanguage) {\n return new WebGPUShaderProcessingContext(shaderLanguage);\n }\n //------------------------------------------------------------------------------\n // Static Pipeline WebGPU States\n //------------------------------------------------------------------------------\n /** @internal */\n applyStates() {\n this._stencilStateComposer.apply();\n this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend);\n }\n /**\n * Force the entire cache to be cleared\n * You should not have to use this function unless your engine needs to share the WebGPU context with another engine\n * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)\n */\n wipeCaches(bruteForce) {\n if (this.preventCacheWipeBetweenFrames && !bruteForce) {\n return;\n }\n //this._currentEffect = null; // can't reset _currentEffect, else some crashes can occur (for eg in ProceduralTexture which calls bindFrameBuffer (which calls wipeCaches) after having called enableEffect and before drawing into the texture)\n // _forceEnableEffect = true assumes the role of _currentEffect = null\n this._forceEnableEffect = true;\n this._currentIndexBuffer = null;\n this._currentOverrideVertexBuffers = null;\n this._cacheRenderPipeline.setBuffers(null, null, null);\n if (bruteForce) {\n this._stencilStateComposer.reset();\n this._depthCullingState.reset();\n this._depthCullingState.depthFunc = 515;\n this._alphaState.reset();\n this._alphaMode = 1;\n this._alphaEquation = 0;\n this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters, this._alphaState._blendEquationParameters);\n this._cacheRenderPipeline.setAlphaBlendEnabled(false);\n this.setColorWrite(true);\n }\n this._cachedVertexBuffers = null;\n this._cachedIndexBuffer = null;\n this._cachedEffectForVertexBuffers = null;\n }\n /**\n * Enable or disable color writing\n * @param enable defines the state to set\n */\n setColorWrite(enable) {\n this._colorWriteLocal = enable;\n this._cacheRenderPipeline.setWriteMask(enable ? 0xf : 0);\n }\n /**\n * Gets a boolean indicating if color writing is enabled\n * @returns the current color writing state\n */\n getColorWrite() {\n return this._colorWriteLocal;\n }\n _resetCurrentViewport(index) {\n this._viewportsCurrent[index].x = 0;\n this._viewportsCurrent[index].y = 0;\n this._viewportsCurrent[index].w = 0;\n this._viewportsCurrent[index].h = 0;\n }\n _mustUpdateViewport(renderPass) {\n const index = renderPass === this._mainRenderPassWrapper.renderPass ? 0 : 1;\n const x = this._viewportCached.x, y = this._viewportCached.y, w = this._viewportCached.z, h = this._viewportCached.w;\n const update = this._viewportsCurrent[index].x !== x || this._viewportsCurrent[index].y !== y || this._viewportsCurrent[index].w !== w || this._viewportsCurrent[index].h !== h;\n if (update) {\n this._viewportsCurrent[index].x = this._viewportCached.x;\n this._viewportsCurrent[index].y = this._viewportCached.y;\n this._viewportsCurrent[index].w = this._viewportCached.z;\n this._viewportsCurrent[index].h = this._viewportCached.w;\n }\n return update;\n }\n _applyViewport(renderPass) {\n let y = Math.floor(this._viewportCached.y);\n const h = Math.floor(this._viewportCached.w);\n if (!this._currentRenderTarget) {\n y = this.getRenderHeight(true) - y - h;\n }\n renderPass.setViewport(Math.floor(this._viewportCached.x), y, Math.floor(this._viewportCached.z), h, 0, 1);\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n console.log(\"frame #\" + this._count + \" - viewport applied - (\", this._viewportCached.x, this._viewportCached.y, this._viewportCached.z, this._viewportCached.w, \") current pass is main pass=\" + (renderPass === this._mainRenderPassWrapper.renderPass));\n }\n }\n }\n /**\n * @internal\n */\n _viewport(x, y, width, height) {\n this._viewportCached.x = x;\n this._viewportCached.y = y;\n this._viewportCached.z = width;\n this._viewportCached.w = height;\n }\n _resetCurrentScissor(index) {\n this._scissorsCurrent[index].x = 0;\n this._scissorsCurrent[index].y = 0;\n this._scissorsCurrent[index].w = 0;\n this._scissorsCurrent[index].h = 0;\n }\n _mustUpdateScissor(renderPass) {\n const index = renderPass === this._mainRenderPassWrapper.renderPass ? 0 : 1;\n const x = this._scissorCached.x, y = this._scissorCached.y, w = this._scissorCached.z, h = this._scissorCached.w;\n const update = this._scissorsCurrent[index].x !== x || this._scissorsCurrent[index].y !== y || this._scissorsCurrent[index].w !== w || this._scissorsCurrent[index].h !== h;\n if (update) {\n this._scissorsCurrent[index].x = this._scissorCached.x;\n this._scissorsCurrent[index].y = this._scissorCached.y;\n this._scissorsCurrent[index].w = this._scissorCached.z;\n this._scissorsCurrent[index].h = this._scissorCached.w;\n }\n return update;\n }\n _applyScissor(renderPass) {\n renderPass.setScissorRect(this._scissorCached.x, this._currentRenderTarget ? this._scissorCached.y : this.getRenderHeight() - this._scissorCached.w - this._scissorCached.y, this._scissorCached.z, this._scissorCached.w);\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n console.log(\"frame #\" + this._count + \" - scissor applied - (\", this._scissorCached.x, this._scissorCached.y, this._scissorCached.z, this._scissorCached.w, \") current pass is main pass=\" + (renderPass === this._mainRenderPassWrapper.renderPass));\n }\n }\n }\n _scissorIsActive() {\n return this._scissorCached.x !== 0 || this._scissorCached.y !== 0 || this._scissorCached.z !== 0 || this._scissorCached.w !== 0;\n }\n enableScissor(x, y, width, height) {\n this._scissorCached.x = x;\n this._scissorCached.y = y;\n this._scissorCached.z = width;\n this._scissorCached.w = height;\n }\n disableScissor() {\n this._scissorCached.x = 0;\n this._scissorCached.y = 0;\n this._scissorCached.z = 0;\n this._scissorCached.w = 0;\n this._resetCurrentScissor(0);\n this._resetCurrentScissor(1);\n }\n _resetCurrentStencilRef(index) {\n this._stencilRefsCurrent[index] = -1;\n }\n _mustUpdateStencilRef(renderPass) {\n const index = renderPass === this._mainRenderPassWrapper.renderPass ? 0 : 1;\n const update = this._stencilStateComposer.funcRef !== this._stencilRefsCurrent[index];\n if (update) {\n this._stencilRefsCurrent[index] = this._stencilStateComposer.funcRef;\n }\n return update;\n }\n /**\n * @internal\n */\n _applyStencilRef(renderPass) {\n var _a;\n renderPass.setStencilReference((_a = this._stencilStateComposer.funcRef) !== null && _a !== void 0 ? _a : 0);\n }\n _resetCurrentColorBlend(index) {\n this._blendColorsCurrent[index][0] = this._blendColorsCurrent[index][1] = this._blendColorsCurrent[index][2] = this._blendColorsCurrent[index][3] = null;\n }\n _mustUpdateBlendColor(renderPass) {\n const index = renderPass === this._mainRenderPassWrapper.renderPass ? 0 : 1;\n const colorBlend = this._alphaState._blendConstants;\n const update = colorBlend[0] !== this._blendColorsCurrent[index][0] ||\n colorBlend[1] !== this._blendColorsCurrent[index][1] ||\n colorBlend[2] !== this._blendColorsCurrent[index][2] ||\n colorBlend[3] !== this._blendColorsCurrent[index][3];\n if (update) {\n this._blendColorsCurrent[index][0] = colorBlend[0];\n this._blendColorsCurrent[index][1] = colorBlend[1];\n this._blendColorsCurrent[index][2] = colorBlend[2];\n this._blendColorsCurrent[index][3] = colorBlend[3];\n }\n return update;\n }\n _applyBlendColor(renderPass) {\n renderPass.setBlendConstant(this._alphaState._blendConstants);\n }\n /**\n * Clear the current render buffer or the current render target (if any is set up)\n * @param color defines the color to use\n * @param backBuffer defines if the back buffer must be cleared\n * @param depth defines if the depth buffer must be cleared\n * @param stencil defines if the stencil buffer must be cleared\n */\n clear(color, backBuffer, depth, stencil = false) {\n // Some PGs are using color3...\n if (color && color.a === undefined) {\n color.a = 1;\n }\n const hasScissor = this._scissorIsActive();\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n console.log(\"frame #\" + this._count + \" - clear called - backBuffer=\", backBuffer, \" depth=\", depth, \" stencil=\", stencil, \" scissor is active=\", hasScissor);\n }\n }\n // We need to recreate the render pass so that the new parameters for clear color / depth / stencil are taken into account\n if (this._currentRenderTarget) {\n if (hasScissor) {\n if (!this._rttRenderPassWrapper.renderPass) {\n this._startRenderTargetRenderPass(this._currentRenderTarget, false, backBuffer ? color : null, depth, stencil);\n }\n if (!this.compatibilityMode) {\n this._bundleListRenderTarget.addItem(new WebGPURenderItemScissor(this._scissorCached.x, this._scissorCached.y, this._scissorCached.z, this._scissorCached.w));\n }\n else {\n this._applyScissor(this._currentRenderPass);\n }\n this._clearFullQuad(backBuffer ? color : null, depth, stencil);\n }\n else {\n if (this._currentRenderPass) {\n this._endRenderTargetRenderPass();\n }\n this._startRenderTargetRenderPass(this._currentRenderTarget, true, backBuffer ? color : null, depth, stencil);\n }\n }\n else {\n if (!this._mainRenderPassWrapper.renderPass || !hasScissor) {\n this._startMainRenderPass(!hasScissor, backBuffer ? color : null, depth, stencil);\n }\n if (hasScissor) {\n if (!this.compatibilityMode) {\n this._bundleList.addItem(new WebGPURenderItemScissor(this._scissorCached.x, this._scissorCached.y, this._scissorCached.z, this._scissorCached.w));\n }\n else {\n this._applyScissor(this._currentRenderPass);\n }\n this._clearFullQuad(backBuffer ? color : null, depth, stencil);\n }\n }\n }\n _clearFullQuad(clearColor, clearDepth, clearStencil) {\n var _a, _b, _c;\n const renderPass = !this.compatibilityMode ? null : this._getCurrentRenderPass();\n const renderPassIndex = this._getCurrentRenderPassIndex();\n const bundleList = renderPassIndex === 0 ? this._bundleList : this._bundleListRenderTarget;\n this._clearQuad.setColorFormat(this._colorFormat);\n this._clearQuad.setDepthStencilFormat(this._depthTextureFormat);\n this._clearQuad.setMRTAttachments((_a = this._cacheRenderPipeline.mrtAttachments) !== null && _a !== void 0 ? _a : [], (_b = this._cacheRenderPipeline.mrtTextureArray) !== null && _b !== void 0 ? _b : [], this._cacheRenderPipeline.mrtTextureCount);\n if (!this.compatibilityMode) {\n bundleList.addItem(new WebGPURenderItemStencilRef(this._clearStencilValue));\n }\n else {\n renderPass.setStencilReference(this._clearStencilValue);\n }\n const bundle = this._clearQuad.clear(renderPass, clearColor, clearDepth, clearStencil, this.currentSampleCount);\n if (!this.compatibilityMode) {\n bundleList.addBundle(bundle);\n bundleList.addItem(new WebGPURenderItemStencilRef((_c = this._stencilStateComposer.funcRef) !== null && _c !== void 0 ? _c : 0));\n this._reportDrawCall();\n }\n else {\n this._applyStencilRef(renderPass);\n }\n }\n //------------------------------------------------------------------------------\n // Vertex/Index/Storage Buffers\n //------------------------------------------------------------------------------\n /**\n * Creates a vertex buffer\n * @param data the data for the vertex buffer\n * @returns the new buffer\n */\n createVertexBuffer(data) {\n let view;\n if (data instanceof Array) {\n view = new Float32Array(data);\n }\n else if (data instanceof ArrayBuffer) {\n view = new Uint8Array(data);\n }\n else {\n view = data;\n }\n const dataBuffer = this._bufferManager.createBuffer(view, WebGPUConstants.BufferUsage.Vertex | WebGPUConstants.BufferUsage.CopyDst);\n return dataBuffer;\n }\n /**\n * Creates a vertex buffer\n * @param data the data for the dynamic vertex buffer\n * @returns the new buffer\n */\n createDynamicVertexBuffer(data) {\n return this.createVertexBuffer(data);\n }\n /**\n * Creates a new index buffer\n * @param indices defines the content of the index buffer\n * @returns a new buffer\n */\n createIndexBuffer(indices) {\n let is32Bits = true;\n let view;\n if (indices instanceof Uint32Array || indices instanceof Int32Array) {\n view = indices;\n }\n else if (indices instanceof Uint16Array) {\n view = indices;\n is32Bits = false;\n }\n else {\n if (indices.length > 65535) {\n view = new Uint32Array(indices);\n }\n else {\n view = new Uint16Array(indices);\n is32Bits = false;\n }\n }\n const dataBuffer = this._bufferManager.createBuffer(view, WebGPUConstants.BufferUsage.Index | WebGPUConstants.BufferUsage.CopyDst);\n dataBuffer.is32Bits = is32Bits;\n return dataBuffer;\n }\n /**\n * @internal\n */\n _createBuffer(data, creationFlags) {\n let view;\n if (data instanceof Array) {\n view = new Float32Array(data);\n }\n else if (data instanceof ArrayBuffer) {\n view = new Uint8Array(data);\n }\n else {\n view = data;\n }\n let flags = 0;\n if (creationFlags & 1) {\n flags |= WebGPUConstants.BufferUsage.CopySrc;\n }\n if (creationFlags & 2) {\n flags |= WebGPUConstants.BufferUsage.CopyDst;\n }\n if (creationFlags & 4) {\n flags |= WebGPUConstants.BufferUsage.Uniform;\n }\n if (creationFlags & 8) {\n flags |= WebGPUConstants.BufferUsage.Vertex;\n }\n if (creationFlags & 16) {\n flags |= WebGPUConstants.BufferUsage.Index;\n }\n if (creationFlags & 32) {\n flags |= WebGPUConstants.BufferUsage.Storage;\n }\n return this._bufferManager.createBuffer(view, flags);\n }\n /**\n * @internal\n */\n bindBuffersDirectly() {\n throw \"Not implemented on WebGPU\";\n }\n /**\n * @internal\n */\n updateAndBindInstancesBuffer() {\n throw \"Not implemented on WebGPU\";\n }\n /**\n * Bind a list of vertex buffers with the engine\n * @param vertexBuffers defines the list of vertex buffers to bind\n * @param indexBuffer defines the index buffer to bind\n * @param effect defines the effect associated with the vertex buffers\n * @param overrideVertexBuffers defines optional list of avertex buffers that overrides the entries in vertexBuffers\n */\n bindBuffers(vertexBuffers, indexBuffer, effect, overrideVertexBuffers) {\n this._currentIndexBuffer = indexBuffer;\n this._currentOverrideVertexBuffers = overrideVertexBuffers !== null && overrideVertexBuffers !== void 0 ? overrideVertexBuffers : null;\n this._cacheRenderPipeline.setBuffers(vertexBuffers, indexBuffer, this._currentOverrideVertexBuffers);\n }\n /**\n * @internal\n */\n _releaseBuffer(buffer) {\n return this._bufferManager.releaseBuffer(buffer);\n }\n //------------------------------------------------------------------------------\n // Effects\n //------------------------------------------------------------------------------\n /**\n * Create a new effect (used to store vertex/fragment shaders)\n * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)\n * @param attributesNamesOrOptions defines either a list of attribute names or an IEffectCreationOptions object\n * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use\n * @param samplers defines an array of string used to represent textures\n * @param defines defines the string containing the defines to use to compile the shaders\n * @param fallbacks defines the list of potential fallbacks to use if shader compilation fails\n * @param onCompiled defines a function to call when the effect creation is successful\n * @param onError defines a function to call when the effect creation has failed\n * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)\n * @param shaderLanguage the language the shader is written in (default: GLSL)\n * @returns the new Effect\n */\n createEffect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters, shaderLanguage = ShaderLanguage.GLSL) {\n var _a;\n const vertex = baseName.vertexElement || baseName.vertex || baseName.vertexToken || baseName.vertexSource || baseName;\n const fragment = baseName.fragmentElement || baseName.fragment || baseName.fragmentToken || baseName.fragmentSource || baseName;\n const globalDefines = this._getGlobalDefines();\n let fullDefines = (_a = defines !== null && defines !== void 0 ? defines : attributesNamesOrOptions.defines) !== null && _a !== void 0 ? _a : \"\";\n if (globalDefines) {\n fullDefines += \"\\n\" + globalDefines;\n }\n const name = vertex + \"+\" + fragment + \"@\" + fullDefines;\n if (this._compiledEffects[name]) {\n const compiledEffect = this._compiledEffects[name];\n if (onCompiled && compiledEffect.isReady()) {\n onCompiled(compiledEffect);\n }\n return compiledEffect;\n }\n const effect = new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters, name, shaderLanguage);\n this._compiledEffects[name] = effect;\n return effect;\n }\n _compileRawShaderToSpirV(source, type) {\n return this._glslang.compileGLSL(source, type);\n }\n _compileShaderToSpirV(source, type, defines, shaderVersion) {\n return this._compileRawShaderToSpirV(shaderVersion + (defines ? defines + \"\\n\" : \"\") + source, type);\n }\n _getWGSLShader(source, type, defines) {\n if (defines) {\n defines = \"//\" + defines.split(\"\\n\").join(\"\\n//\") + \"\\n\";\n }\n else {\n defines = \"\";\n }\n return defines + source;\n }\n _createPipelineStageDescriptor(vertexShader, fragmentShader, shaderLanguage, disableUniformityAnalysisInVertex, disableUniformityAnalysisInFragment) {\n if (this._tintWASM && shaderLanguage === ShaderLanguage.GLSL) {\n vertexShader = this._tintWASM.convertSpirV2WGSL(vertexShader, disableUniformityAnalysisInVertex);\n fragmentShader = this._tintWASM.convertSpirV2WGSL(fragmentShader, disableUniformityAnalysisInFragment);\n }\n return {\n vertexStage: {\n module: this._device.createShaderModule({\n code: vertexShader,\n }),\n entryPoint: \"main\",\n },\n fragmentStage: {\n module: this._device.createShaderModule({\n code: fragmentShader,\n }),\n entryPoint: \"main\",\n },\n };\n }\n _compileRawPipelineStageDescriptor(vertexCode, fragmentCode, shaderLanguage) {\n const disableUniformityAnalysisInVertex = vertexCode.indexOf(disableUniformityAnalysisMarker) >= 0;\n const disableUniformityAnalysisInFragment = fragmentCode.indexOf(disableUniformityAnalysisMarker) >= 0;\n const vertexShader = shaderLanguage === ShaderLanguage.GLSL ? this._compileRawShaderToSpirV(vertexCode, \"vertex\") : vertexCode;\n const fragmentShader = shaderLanguage === ShaderLanguage.GLSL ? this._compileRawShaderToSpirV(fragmentCode, \"fragment\") : fragmentCode;\n return this._createPipelineStageDescriptor(vertexShader, fragmentShader, shaderLanguage, disableUniformityAnalysisInVertex, disableUniformityAnalysisInFragment);\n }\n _compilePipelineStageDescriptor(vertexCode, fragmentCode, defines, shaderLanguage) {\n this.onBeforeShaderCompilationObservable.notifyObservers(this);\n const disableUniformityAnalysisInVertex = vertexCode.indexOf(disableUniformityAnalysisMarker) >= 0;\n const disableUniformityAnalysisInFragment = fragmentCode.indexOf(disableUniformityAnalysisMarker) >= 0;\n const shaderVersion = \"#version 450\\n\";\n const vertexShader = shaderLanguage === ShaderLanguage.GLSL ? this._compileShaderToSpirV(vertexCode, \"vertex\", defines, shaderVersion) : this._getWGSLShader(vertexCode, \"vertex\", defines);\n const fragmentShader = shaderLanguage === ShaderLanguage.GLSL\n ? this._compileShaderToSpirV(fragmentCode, \"fragment\", defines, shaderVersion)\n : this._getWGSLShader(fragmentCode, \"fragment\", defines);\n const program = this._createPipelineStageDescriptor(vertexShader, fragmentShader, shaderLanguage, disableUniformityAnalysisInVertex, disableUniformityAnalysisInFragment);\n this.onAfterShaderCompilationObservable.notifyObservers(this);\n return program;\n }\n /**\n * @internal\n */\n createRawShaderProgram() {\n throw \"Not available on WebGPU\";\n }\n /**\n * @internal\n */\n createShaderProgram() {\n throw \"Not available on WebGPU\";\n }\n /**\n * Inline functions in shader code that are marked to be inlined\n * @param code code to inline\n * @returns inlined code\n */\n inlineShaderCode(code) {\n const sci = new ShaderCodeInliner(code);\n sci.debug = false;\n sci.processCode();\n return sci.code;\n }\n /**\n * Creates a new pipeline context\n * @param shaderProcessingContext defines the shader processing context used during the processing if available\n * @returns the new pipeline\n */\n createPipelineContext(shaderProcessingContext) {\n return new WebGPUPipelineContext(shaderProcessingContext, this);\n }\n /**\n * Creates a new material context\n * @returns the new context\n */\n createMaterialContext() {\n return new WebGPUMaterialContext();\n }\n /**\n * Creates a new draw context\n * @returns the new context\n */\n createDrawContext() {\n return new WebGPUDrawContext(this._bufferManager);\n }\n /**\n * @internal\n */\n _preparePipelineContext(pipelineContext, vertexSourceCode, fragmentSourceCode, createAsRaw, rawVertexSourceCode, rawFragmentSourceCode, rebuildRebind, defines) {\n const webGpuContext = pipelineContext;\n const shaderLanguage = webGpuContext.shaderProcessingContext.shaderLanguage;\n if (this.dbgShowShaderCode) {\n console.log(defines);\n console.log(vertexSourceCode);\n console.log(fragmentSourceCode);\n console.log(\"***********************************************\");\n }\n webGpuContext.sources = {\n fragment: fragmentSourceCode,\n vertex: vertexSourceCode,\n rawVertex: rawVertexSourceCode,\n rawFragment: rawFragmentSourceCode,\n };\n if (createAsRaw) {\n webGpuContext.stages = this._compileRawPipelineStageDescriptor(vertexSourceCode, fragmentSourceCode, shaderLanguage);\n }\n else {\n webGpuContext.stages = this._compilePipelineStageDescriptor(vertexSourceCode, fragmentSourceCode, defines, shaderLanguage);\n }\n }\n /**\n * Gets the list of active attributes for a given WebGPU program\n * @param pipelineContext defines the pipeline context to use\n * @param attributesNames defines the list of attribute names to get\n * @returns an array of indices indicating the offset of each attribute\n */\n getAttributes(pipelineContext, attributesNames) {\n const results = new Array(attributesNames.length);\n const gpuPipelineContext = pipelineContext;\n for (let i = 0; i < attributesNames.length; i++) {\n const attributeName = attributesNames[i];\n const attributeLocation = gpuPipelineContext.shaderProcessingContext.availableAttributes[attributeName];\n if (attributeLocation === undefined) {\n continue;\n }\n results[i] = attributeLocation;\n }\n return results;\n }\n /**\n * Activates an effect, making it the current one (ie. the one used for rendering)\n * @param effect defines the effect to activate\n */\n enableEffect(effect) {\n if (!effect) {\n return;\n }\n let isNewEffect = true;\n if (!DrawWrapper.IsWrapper(effect)) {\n isNewEffect = effect !== this._currentEffect;\n this._currentEffect = effect;\n this._currentMaterialContext = this._defaultMaterialContext;\n this._currentDrawContext = this._defaultDrawContext;\n this._counters.numEnableEffects++;\n if (this.dbgLogIfNotDrawWrapper) {\n Logger.Warn(`enableEffect has been called with an Effect and not a Wrapper! effect.uniqueId=${effect.uniqueId}, effect.name=${effect.name}, effect.name.vertex=${effect.name.vertex}, effect.name.fragment=${effect.name.fragment}`, 10);\n }\n }\n else if (!effect.effect ||\n (effect.effect === this._currentEffect &&\n effect.materialContext === this._currentMaterialContext &&\n effect.drawContext === this._currentDrawContext &&\n !this._forceEnableEffect)) {\n if (!effect.effect && this.dbgShowEmptyEnableEffectCalls) {\n console.error(\"drawWrapper=\", effect);\n throw \"Invalid call to enableEffect: the effect property is empty!\";\n }\n return;\n }\n else {\n isNewEffect = effect.effect !== this._currentEffect;\n this._currentEffect = effect.effect;\n this._currentMaterialContext = effect.materialContext;\n this._currentDrawContext = effect.drawContext;\n this._counters.numEnableDrawWrapper++;\n if (!this._currentMaterialContext) {\n console.error(\"drawWrapper=\", effect);\n throw `Invalid call to enableEffect: the materialContext property is empty!`;\n }\n }\n this._stencilStateComposer.stencilMaterial = undefined;\n this._forceEnableEffect = isNewEffect || this._forceEnableEffect ? false : this._forceEnableEffect;\n if (isNewEffect) {\n if (this._currentEffect.onBind) {\n this._currentEffect.onBind(this._currentEffect);\n }\n if (this._currentEffect._onBindObservable) {\n this._currentEffect._onBindObservable.notifyObservers(this._currentEffect);\n }\n }\n }\n /**\n * @internal\n */\n _releaseEffect(effect) {\n if (this._compiledEffects[effect._key]) {\n delete this._compiledEffects[effect._key];\n this._deletePipelineContext(effect.getPipelineContext());\n }\n }\n /**\n * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled\n */\n releaseEffects() {\n for (const name in this._compiledEffects) {\n const webGPUPipelineContext = this._compiledEffects[name].getPipelineContext();\n this._deletePipelineContext(webGPUPipelineContext);\n }\n this._compiledEffects = {};\n }\n _deletePipelineContext(pipelineContext) {\n const webgpuPipelineContext = pipelineContext;\n if (webgpuPipelineContext) {\n pipelineContext.dispose();\n }\n }\n //------------------------------------------------------------------------------\n // Textures\n //------------------------------------------------------------------------------\n /**\n * Gets a boolean indicating that only power of 2 textures are supported\n * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them\n */\n get needPOTTextures() {\n return false;\n }\n /** @internal */\n _createHardwareTexture() {\n return new WebGPUHardwareTexture();\n }\n /**\n * @internal\n */\n _releaseTexture(texture) {\n const index = this._internalTexturesCache.indexOf(texture);\n if (index !== -1) {\n this._internalTexturesCache.splice(index, 1);\n }\n this._textureHelper.releaseTexture(texture);\n }\n /**\n * @internal\n */\n _getRGBABufferInternalSizedFormat() {\n return 5;\n }\n updateTextureComparisonFunction(texture, comparisonFunction) {\n texture._comparisonFunction = comparisonFunction;\n }\n /**\n * Creates an internal texture without binding it to a framebuffer\n * @internal\n * @param size defines the size of the texture\n * @param options defines the options used to create the texture\n * @param delayGPUTextureCreation true to delay the texture creation the first time it is really needed. false to create it right away\n * @param source source type of the texture\n * @returns a new internal texture\n */\n _createInternalTexture(size, options, delayGPUTextureCreation = true, source = InternalTextureSource.Unknown) {\n var _a, _b, _c;\n const fullOptions = {};\n if (options !== undefined && typeof options === \"object\") {\n fullOptions.generateMipMaps = options.generateMipMaps;\n fullOptions.type = options.type === undefined ? 0 : options.type;\n fullOptions.samplingMode = options.samplingMode === undefined ? 3 : options.samplingMode;\n fullOptions.format = options.format === undefined ? 5 : options.format;\n fullOptions.samples = (_a = options.samples) !== null && _a !== void 0 ? _a : 1;\n fullOptions.creationFlags = (_b = options.creationFlags) !== null && _b !== void 0 ? _b : 0;\n fullOptions.useSRGBBuffer = (_c = options.useSRGBBuffer) !== null && _c !== void 0 ? _c : false;\n fullOptions.label = options.label;\n }\n else {\n fullOptions.generateMipMaps = options;\n fullOptions.type = 0;\n fullOptions.samplingMode = 3;\n fullOptions.format = 5;\n fullOptions.samples = 1;\n fullOptions.creationFlags = 0;\n fullOptions.useSRGBBuffer = false;\n }\n if (fullOptions.type === 1 && !this._caps.textureFloatLinearFiltering) {\n fullOptions.samplingMode = 1;\n }\n else if (fullOptions.type === 2 && !this._caps.textureHalfFloatLinearFiltering) {\n fullOptions.samplingMode = 1;\n }\n if (fullOptions.type === 1 && !this._caps.textureFloat) {\n fullOptions.type = 0;\n Logger.Warn(\"Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE\");\n }\n const texture = new InternalTexture(this, source);\n const width = size.width || size;\n const height = size.height || size;\n const layers = size.layers || 0;\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = width;\n texture.height = height;\n texture.depth = layers;\n texture.isReady = true;\n texture.samples = fullOptions.samples;\n texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;\n texture.samplingMode = fullOptions.samplingMode;\n texture.type = fullOptions.type;\n texture.format = fullOptions.format;\n texture.is2DArray = layers > 0;\n texture._cachedWrapU = 0;\n texture._cachedWrapV = 0;\n texture._useSRGBBuffer = fullOptions.useSRGBBuffer;\n texture.label = fullOptions.label;\n this._internalTexturesCache.push(texture);\n if (!delayGPUTextureCreation) {\n this._textureHelper.createGPUTextureForInternalTexture(texture, width, height, layers || 1, fullOptions.creationFlags);\n }\n return texture;\n }\n /**\n * Usually called from Texture.ts.\n * Passed information to create a hardware texture\n * @param url defines a value which contains one of the following:\n * * A conventional http URL, e.g. 'http://...' or 'file://...'\n * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'\n * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'\n * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file\n * @param invertY when true, image is flipped when loaded. You probably want true. Certain compressed textures may invert this if their default is inverted (eg. ktx)\n * @param scene needed for loading to the correct scene\n * @param samplingMode mode with should be used sample / access the texture (Default: Texture.TRILINEAR_SAMPLINGMODE)\n * @param onLoad optional callback to be called upon successful completion\n * @param onError optional callback to be called upon failure\n * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob\n * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities\n * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures\n * @param forcedExtension defines the extension to use to pick the right loader\n * @param mimeType defines an optional mime type\n * @param loaderOptions options to be passed to the loader\n * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)\n * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU).\n * @returns a InternalTexture for assignment back into BABYLON.Texture\n */\n createTexture(url, noMipmap, invertY, scene, samplingMode = 3, onLoad = null, onError = null, buffer = null, fallback = null, format = null, forcedExtension = null, mimeType, loaderOptions, creationFlags, useSRGBBuffer) {\n return this._createTextureBase(url, noMipmap, invertY, scene, samplingMode, onLoad, onError, (texture, extension, scene, img, invertY, noMipmap, isCompressed, processFunction) => {\n var _a;\n const imageBitmap = img; // we will never get an HTMLImageElement in WebGPU\n texture.baseWidth = imageBitmap.width;\n texture.baseHeight = imageBitmap.height;\n texture.width = imageBitmap.width;\n texture.height = imageBitmap.height;\n texture.format = format !== null && format !== void 0 ? format : -1;\n processFunction(texture.width, texture.height, imageBitmap, extension, texture, () => { });\n if (!((_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource)) {\n // the texture could have been created before reaching this point so don't recreate it if already existing\n const gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, imageBitmap.width, imageBitmap.height, undefined, creationFlags);\n if (WebGPUTextureHelper.IsImageBitmap(imageBitmap)) {\n this._textureHelper.updateTexture(imageBitmap, texture, imageBitmap.width, imageBitmap.height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, false, 0, 0);\n if (!noMipmap && !isCompressed) {\n this._generateMipmaps(texture, this._uploadEncoder);\n }\n }\n }\n else if (!noMipmap && !isCompressed) {\n this._generateMipmaps(texture, this._uploadEncoder);\n }\n if (scene) {\n scene.removePendingData(texture);\n }\n texture.isReady = true;\n texture.onLoadedObservable.notifyObservers(texture);\n texture.onLoadedObservable.clear();\n }, () => false, buffer, fallback, format, forcedExtension, mimeType, loaderOptions, useSRGBBuffer);\n }\n /**\n * Wraps an external web gpu texture in a Babylon texture.\n * @param texture defines the external texture\n * @returns the babylon internal texture\n */\n wrapWebGPUTexture(texture) {\n const hardwareTexture = new WebGPUHardwareTexture(texture);\n const internalTexture = new InternalTexture(this, InternalTextureSource.Unknown, true);\n internalTexture._hardwareTexture = hardwareTexture;\n internalTexture.isReady = true;\n return internalTexture;\n }\n /**\n * Wraps an external web gl texture in a Babylon texture.\n * @returns the babylon internal texture\n */\n wrapWebGLTexture() {\n throw new Error(\"wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.\");\n }\n generateMipMapsForCubemap(texture) {\n var _a;\n if (texture.generateMipMaps) {\n const gpuTexture = (_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource;\n if (!gpuTexture) {\n this._textureHelper.createGPUTextureForInternalTexture(texture);\n }\n this._generateMipmaps(texture, texture.source === InternalTextureSource.RenderTarget || texture.source === InternalTextureSource.MultiRenderTarget ? this._renderTargetEncoder : undefined);\n }\n }\n /**\n * Update the sampling mode of a given texture\n * @param samplingMode defines the required sampling mode\n * @param texture defines the texture to update\n * @param generateMipMaps defines whether to generate mipmaps for the texture\n */\n updateTextureSamplingMode(samplingMode, texture, generateMipMaps = false) {\n if (generateMipMaps) {\n texture.generateMipMaps = true;\n this._generateMipmaps(texture);\n }\n texture.samplingMode = samplingMode;\n }\n /**\n * Update the sampling mode of a given texture\n * @param texture defines the texture to update\n * @param wrapU defines the texture wrap mode of the u coordinates\n * @param wrapV defines the texture wrap mode of the v coordinates\n * @param wrapR defines the texture wrap mode of the r coordinates\n */\n updateTextureWrappingMode(texture, wrapU, wrapV = null, wrapR = null) {\n if (wrapU !== null) {\n texture._cachedWrapU = wrapU;\n }\n if (wrapV !== null) {\n texture._cachedWrapV = wrapV;\n }\n if ((texture.is2DArray || texture.is3D) && wrapR !== null) {\n texture._cachedWrapR = wrapR;\n }\n }\n /**\n * Update the dimensions of a texture\n * @param texture texture to update\n * @param width new width of the texture\n * @param height new height of the texture\n * @param depth new depth of the texture\n */\n updateTextureDimensions(texture, width, height, depth = 1) {\n if (!texture._hardwareTexture) {\n // the gpu texture is not created yet, so when it is it will be created with the right dimensions\n return;\n }\n if (texture.width === width && texture.height === height && texture.depth === depth) {\n return;\n }\n const additionalUsages = texture._hardwareTexture.textureAdditionalUsages;\n texture._hardwareTexture.release(); // don't defer the releasing! Else we will release at the end of this frame the gpu texture we are about to create in the next line...\n this._textureHelper.createGPUTextureForInternalTexture(texture, width, height, depth, additionalUsages);\n }\n /**\n * @internal\n */\n _setInternalTexture(name, texture, baseName) {\n baseName = baseName !== null && baseName !== void 0 ? baseName : name;\n if (this._currentEffect) {\n const webgpuPipelineContext = this._currentEffect._pipelineContext;\n const availableTexture = webgpuPipelineContext.shaderProcessingContext.availableTextures[baseName];\n this._currentMaterialContext.setTexture(name, texture);\n if (availableTexture && availableTexture.autoBindSampler) {\n const samplerName = baseName + WebGPUShaderProcessor.AutoSamplerSuffix;\n this._currentMaterialContext.setSampler(samplerName, texture); // we can safely cast to InternalTexture because ExternalTexture always has autoBindSampler = false\n }\n }\n }\n /**\n * Sets a texture to the according uniform.\n * @param channel The texture channel\n * @param unused unused parameter\n * @param texture The texture to apply\n * @param name The name of the uniform in the effect\n */\n setTexture(channel, unused, texture, name) {\n this._setTexture(channel, texture, false, false, name, name);\n }\n /**\n * Sets an array of texture to the WebGPU context\n * @param channel defines the channel where the texture array must be set\n * @param unused unused parameter\n * @param textures defines the array of textures to bind\n * @param name name of the channel\n */\n setTextureArray(channel, unused, textures, name) {\n for (let index = 0; index < textures.length; index++) {\n this._setTexture(-1, textures[index], true, false, name + index.toString(), name);\n }\n }\n _setTexture(channel, texture, \n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isPartOfTextureArray = false, depthStencilTexture = false, name = \"\", baseName) {\n // name == baseName for a texture that is not part of a texture array\n // Else, name is something like 'myTexture0' / 'myTexture1' / ... and baseName is 'myTexture'\n // baseName is used to look up the texture in the shaderProcessingContext.availableTextures map\n // name is used to look up the texture in the _currentMaterialContext.textures map\n baseName = baseName !== null && baseName !== void 0 ? baseName : name;\n if (this._currentEffect) {\n if (!texture) {\n this._currentMaterialContext.setTexture(name, null);\n return false;\n }\n // Video\n if (texture.video) {\n texture.update();\n }\n else if (texture.delayLoadState === 4) {\n // Delay loading\n texture.delayLoad();\n return false;\n }\n let internalTexture = null;\n if (depthStencilTexture) {\n internalTexture = texture.depthStencilTexture;\n }\n else if (texture.isReady()) {\n internalTexture = texture.getInternalTexture();\n }\n else if (texture.isCube) {\n internalTexture = this.emptyCubeTexture;\n }\n else if (texture.is3D) {\n internalTexture = this.emptyTexture3D;\n }\n else if (texture.is2DArray) {\n internalTexture = this.emptyTexture2DArray;\n }\n else {\n internalTexture = this.emptyTexture;\n }\n if (internalTexture && !internalTexture.isMultiview) {\n // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.\n if (internalTexture.isCube && internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {\n internalTexture._cachedCoordinatesMode = texture.coordinatesMode;\n const textureWrapMode = texture.coordinatesMode !== 3 && texture.coordinatesMode !== 5\n ? 1\n : 0;\n texture.wrapU = textureWrapMode;\n texture.wrapV = textureWrapMode;\n }\n internalTexture._cachedWrapU = texture.wrapU;\n internalTexture._cachedWrapV = texture.wrapV;\n if (internalTexture.is3D) {\n internalTexture._cachedWrapR = texture.wrapR;\n }\n this._setAnisotropicLevel(0, internalTexture, texture.anisotropicFilteringLevel);\n }\n this._setInternalTexture(name, internalTexture, baseName);\n }\n else {\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n console.log(\"frame #\" + this._count + \" - _setTexture called with a null _currentEffect! texture=\", texture);\n }\n }\n }\n return true;\n }\n /**\n * @internal\n */\n _setAnisotropicLevel(target, internalTexture, anisotropicFilteringLevel) {\n if (internalTexture._cachedAnisotropicFilteringLevel !== anisotropicFilteringLevel) {\n internalTexture._cachedAnisotropicFilteringLevel = Math.min(anisotropicFilteringLevel, this._caps.maxAnisotropy);\n }\n }\n /**\n * @internal\n */\n _bindTexture(channel, texture, name) {\n if (channel === undefined) {\n return;\n }\n this._setInternalTexture(name, texture);\n }\n /**\n * Generates the mipmaps for a texture\n * @param texture texture to generate the mipmaps for\n */\n generateMipmaps(texture) {\n this._generateMipmaps(texture, this._renderTargetEncoder);\n }\n /**\n * @internal\n */\n _generateMipmaps(texture, commandEncoder) {\n const gpuHardwareTexture = texture._hardwareTexture;\n if (!gpuHardwareTexture) {\n return;\n }\n // try as much as possible to use the command encoder corresponding to the current pass.\n // If not possible (because the pass is started - generateMipmaps itself creates a pass and it's not allowed to have a pass inside a pass), use _uploadEncoder\n commandEncoder =\n commandEncoder !== null && commandEncoder !== void 0 ? commandEncoder : (this._currentRenderTarget && !this._currentRenderPass ? this._renderTargetEncoder : !this._currentRenderPass ? this._renderEncoder : this._uploadEncoder);\n const format = texture._hardwareTexture.format;\n const mipmapCount = WebGPUTextureHelper.ComputeNumMipmapLevels(texture.width, texture.height);\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n console.log(\"frame #\" + this._count + \" - generate mipmaps called - width=\", texture.width, \"height=\", texture.height, \"isCube=\", texture.isCube);\n }\n }\n if (texture.isCube) {\n this._textureHelper.generateCubeMipmaps(gpuHardwareTexture, format, mipmapCount, commandEncoder);\n }\n else {\n this._textureHelper.generateMipmaps(gpuHardwareTexture, format, mipmapCount, 0, commandEncoder);\n }\n }\n /**\n * Update a portion of an internal texture\n * @param texture defines the texture to update\n * @param imageData defines the data to store into the texture\n * @param xOffset defines the x coordinates of the update rectangle\n * @param yOffset defines the y coordinates of the update rectangle\n * @param width defines the width of the update rectangle\n * @param height defines the height of the update rectangle\n * @param faceIndex defines the face index if texture is a cube (0 by default)\n * @param lod defines the lod level to update (0 by default)\n * @param generateMipMaps defines whether to generate mipmaps or not\n */\n updateTextureData(texture, imageData, xOffset, yOffset, width, height, faceIndex = 0, lod = 0, generateMipMaps = false) {\n var _a;\n let gpuTextureWrapper = texture._hardwareTexture;\n if (!((_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource)) {\n gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture);\n }\n const data = new Uint8Array(imageData.buffer, imageData.byteOffset, imageData.byteLength);\n this._textureHelper.updateTexture(data, texture, width, height, texture.depth, gpuTextureWrapper.format, faceIndex, lod, texture.invertY, false, xOffset, yOffset);\n if (generateMipMaps) {\n this._generateMipmaps(texture, this._renderTargetEncoder);\n }\n }\n /**\n * @internal\n */\n _uploadCompressedDataToTextureDirectly(texture, internalFormat, width, height, imageData, faceIndex = 0, lod = 0) {\n var _a;\n let gpuTextureWrapper = texture._hardwareTexture;\n if (!((_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource)) {\n texture.format = internalFormat;\n gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, width, height);\n }\n const data = new Uint8Array(imageData.buffer, imageData.byteOffset, imageData.byteLength);\n this._textureHelper.updateTexture(data, texture, width, height, texture.depth, gpuTextureWrapper.format, faceIndex, lod, false, false, 0, 0);\n }\n /**\n * @internal\n */\n _uploadDataToTextureDirectly(texture, imageData, faceIndex = 0, lod = 0, babylonInternalFormat, useTextureWidthAndHeight = false) {\n var _a;\n const lodMaxWidth = Math.round(Math.log(texture.width) * Math.LOG2E);\n const lodMaxHeight = Math.round(Math.log(texture.height) * Math.LOG2E);\n const width = useTextureWidthAndHeight ? texture.width : Math.pow(2, Math.max(lodMaxWidth - lod, 0));\n const height = useTextureWidthAndHeight ? texture.height : Math.pow(2, Math.max(lodMaxHeight - lod, 0));\n let gpuTextureWrapper = texture._hardwareTexture;\n if (!((_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource)) {\n gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, width, height);\n }\n const data = new Uint8Array(imageData.buffer, imageData.byteOffset, imageData.byteLength);\n this._textureHelper.updateTexture(data, texture, width, height, texture.depth, gpuTextureWrapper.format, faceIndex, lod, texture.invertY, false, 0, 0);\n }\n /**\n * @internal\n */\n _uploadArrayBufferViewToTexture(texture, imageData, faceIndex = 0, lod = 0) {\n this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);\n }\n /**\n * @internal\n */\n _uploadImageToTexture(texture, image, faceIndex = 0, lod = 0) {\n var _a;\n let gpuTextureWrapper = texture._hardwareTexture;\n if (!((_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource)) {\n gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture);\n }\n if (image instanceof HTMLImageElement) {\n throw \"WebGPU engine: HTMLImageElement not supported in _uploadImageToTexture!\";\n }\n const bitmap = image; // in WebGPU we will always get an ImageBitmap, not an HTMLImageElement\n const width = Math.ceil(texture.width / (1 << lod));\n const height = Math.ceil(texture.height / (1 << lod));\n this._textureHelper.updateTexture(bitmap, texture, width, height, texture.depth, gpuTextureWrapper.format, faceIndex, lod, texture.invertY, false, 0, 0);\n }\n /**\n * Reads pixels from the current frame buffer. Please note that this function can be slow\n * @param x defines the x coordinate of the rectangle where pixels must be read\n * @param y defines the y coordinate of the rectangle where pixels must be read\n * @param width defines the width of the rectangle where pixels must be read\n * @param height defines the height of the rectangle where pixels must be read\n * @param hasAlpha defines whether the output should have alpha or not (defaults to true)\n * @param flushRenderer true to flush the renderer from the pending commands before reading the pixels\n * @returns a ArrayBufferView promise (Uint8Array) containing RGBA colors\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n readPixels(x, y, width, height, hasAlpha = true, flushRenderer = true) {\n const renderPassWrapper = this._rttRenderPassWrapper.renderPass ? this._rttRenderPassWrapper : this._mainRenderPassWrapper;\n const hardwareTexture = renderPassWrapper.colorAttachmentGPUTextures[0];\n if (!hardwareTexture) {\n // we are calling readPixels for a render pass with no color texture bound\n return Promise.resolve(new Uint8Array(0));\n }\n const gpuTexture = hardwareTexture.underlyingResource;\n const gpuTextureFormat = hardwareTexture.format;\n if (!gpuTexture) {\n // we are calling readPixels before startMainRenderPass has been called and no RTT is bound, so swapChainTexture is not setup yet!\n return Promise.resolve(new Uint8Array(0));\n }\n if (flushRenderer) {\n this.flushFramebuffer();\n }\n return this._textureHelper.readPixels(gpuTexture, x, y, width, height, gpuTextureFormat);\n }\n //------------------------------------------------------------------------------\n // Frame management\n //------------------------------------------------------------------------------\n /**\n * Begin a new frame\n */\n beginFrame() {\n super.beginFrame();\n }\n /**\n * End the current frame\n */\n endFrame() {\n this._snapshotRendering.endFrame(this._mainRenderPassWrapper.renderPass);\n this._endMainRenderPass();\n this._timestampQuery.endFrame(this._renderEncoder);\n this.flushFramebuffer(false);\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n console.log(\"frame #\" + this._count + \" - counters\");\n }\n }\n this._textureHelper.destroyDeferredTextures();\n this._bufferManager.destroyDeferredBuffers();\n if (this._features._collectUbosUpdatedInFrame) {\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n const list = [];\n for (const name in UniformBuffer._UpdatedUbosInFrame) {\n list.push(name + \":\" + UniformBuffer._UpdatedUbosInFrame[name]);\n }\n console.log(\"frame #\" + this._count + \" - updated ubos -\", list.join(\", \"));\n }\n }\n UniformBuffer._UpdatedUbosInFrame = {};\n }\n this.countersLastFrame.numEnableEffects = this._counters.numEnableEffects;\n this.countersLastFrame.numEnableDrawWrapper = this._counters.numEnableDrawWrapper;\n this.countersLastFrame.numBundleCreationNonCompatMode = this._counters.numBundleCreationNonCompatMode;\n this.countersLastFrame.numBundleReuseNonCompatMode = this._counters.numBundleReuseNonCompatMode;\n this._counters.numEnableEffects = 0;\n this._counters.numEnableDrawWrapper = 0;\n this._counters.numBundleCreationNonCompatMode = 0;\n this._counters.numBundleReuseNonCompatMode = 0;\n this._cacheRenderPipeline.endFrame();\n this._cacheBindGroups.endFrame();\n this._pendingDebugCommands.length = 0;\n super.endFrame();\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (this._count < this.dbgVerboseLogsNumFrames) {\n console.log(\"%c frame #\" + this._count + \" - end\", \"background: #ffff00\");\n }\n if (this._count < this.dbgVerboseLogsNumFrames) {\n this._count++;\n if (this._count !== this.dbgVerboseLogsNumFrames) {\n console.log(\"%c frame #\" + this._count + \" - begin\", \"background: #ffff00\");\n }\n }\n }\n }\n /**\n * Force a WebGPU flush (ie. a flush of all waiting commands)\n * @param reopenPass true to reopen at the end of the function the pass that was active when entering the function\n */\n flushFramebuffer(reopenPass = true) {\n // we need to end the current render pass (main or rtt) if any as we are not allowed to submit the command buffers when being in a pass\n const currentRenderPassIsNULL = !this._currentRenderPass;\n let currentPasses = 0; // 0 if no pass, 1 for rtt, 2 for main pass\n if (this._currentRenderPass && this._currentRenderTarget) {\n currentPasses |= 1;\n this._endRenderTargetRenderPass();\n }\n if (this._mainRenderPassWrapper.renderPass) {\n currentPasses |= 2;\n this._endMainRenderPass();\n }\n this._commandBuffers[0] = this._uploadEncoder.finish();\n this._commandBuffers[1] = this._renderTargetEncoder.finish();\n this._commandBuffers[2] = this._renderEncoder.finish();\n this._device.queue.submit(this._commandBuffers);\n this._uploadEncoder = this._device.createCommandEncoder(this._uploadEncoderDescriptor);\n this._renderEncoder = this._device.createCommandEncoder(this._renderEncoderDescriptor);\n this._renderTargetEncoder = this._device.createCommandEncoder(this._renderTargetEncoderDescriptor);\n this._timestampQuery.startFrame(this._uploadEncoder);\n this._textureHelper.setCommandEncoder(this._uploadEncoder);\n this._bundleList.reset();\n this._bundleListRenderTarget.reset();\n // restart the render pass\n if (reopenPass) {\n if (currentPasses & 2) {\n this._startMainRenderPass(false);\n }\n if (currentPasses & 1) {\n this._startRenderTargetRenderPass(this._currentRenderTarget, false, null, false, false);\n }\n if (currentRenderPassIsNULL && this._currentRenderTarget) {\n this._currentRenderPass = null;\n }\n }\n }\n /** @internal */\n _currentFrameBufferIsDefaultFrameBuffer() {\n return this._currentRenderTarget === null;\n }\n //------------------------------------------------------------------------------\n // Render Pass\n //------------------------------------------------------------------------------\n _startRenderTargetRenderPass(renderTargetWrapper, setClearStates, clearColor, clearDepth, clearStencil) {\n var _a, _b, _c, _d, _e, _f, _g;\n const rtWrapper = renderTargetWrapper;\n const depthStencilTexture = rtWrapper._depthStencilTexture;\n const gpuDepthStencilWrapper = depthStencilTexture === null || depthStencilTexture === void 0 ? void 0 : depthStencilTexture._hardwareTexture;\n const gpuDepthStencilTexture = gpuDepthStencilWrapper === null || gpuDepthStencilWrapper === void 0 ? void 0 : gpuDepthStencilWrapper.underlyingResource;\n const gpuDepthStencilMSAATexture = gpuDepthStencilWrapper === null || gpuDepthStencilWrapper === void 0 ? void 0 : gpuDepthStencilWrapper.getMSAATexture();\n const depthTextureView = gpuDepthStencilTexture === null || gpuDepthStencilTexture === void 0 ? void 0 : gpuDepthStencilTexture.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor);\n const depthMSAATextureView = gpuDepthStencilMSAATexture === null || gpuDepthStencilMSAATexture === void 0 ? void 0 : gpuDepthStencilMSAATexture.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor);\n const depthTextureHasStencil = gpuDepthStencilWrapper ? WebGPUTextureHelper.HasStencilAspect(gpuDepthStencilWrapper.format) : false;\n const colorAttachments = [];\n if (this.useReverseDepthBuffer) {\n this.setDepthFunctionToGreaterOrEqual();\n }\n const mustClearColor = setClearStates && clearColor;\n const mustClearDepth = setClearStates && clearDepth;\n const mustClearStencil = setClearStates && clearStencil;\n if (rtWrapper._attachments && rtWrapper.isMulti) {\n // multi render targets\n if (!this._mrtAttachments || this._mrtAttachments.length === 0) {\n this._mrtAttachments = rtWrapper._defaultAttachments;\n }\n for (let i = 0; i < this._mrtAttachments.length; ++i) {\n const index = this._mrtAttachments[i]; // if index == 0 it means the texture should not be written to => at render pass creation time, it means we should not clear it\n const mrtTexture = rtWrapper.textures[i];\n const gpuMRTWrapper = mrtTexture === null || mrtTexture === void 0 ? void 0 : mrtTexture._hardwareTexture;\n const gpuMRTTexture = gpuMRTWrapper === null || gpuMRTWrapper === void 0 ? void 0 : gpuMRTWrapper.underlyingResource;\n if (gpuMRTWrapper && gpuMRTTexture) {\n const gpuMSAATexture = gpuMRTWrapper.getMSAATexture(i);\n const layerIndex = (_b = (_a = rtWrapper.layerIndices) === null || _a === void 0 ? void 0 : _a[i]) !== null && _b !== void 0 ? _b : 0;\n const faceIndex = (_d = (_c = rtWrapper.faceIndices) === null || _c === void 0 ? void 0 : _c[i]) !== null && _d !== void 0 ? _d : 0;\n const viewDescriptor = Object.assign(Object.assign({}, this._rttRenderPassWrapper.colorAttachmentViewDescriptor), { format: gpuMRTWrapper.format, baseArrayLayer: mrtTexture.isCube ? layerIndex * 6 + faceIndex : layerIndex });\n const msaaViewDescriptor = Object.assign(Object.assign({}, this._rttRenderPassWrapper.colorAttachmentViewDescriptor), { format: gpuMRTWrapper.format, baseArrayLayer: 0 });\n const colorTextureView = gpuMRTTexture.createView(viewDescriptor);\n const colorMSAATextureView = gpuMSAATexture === null || gpuMSAATexture === void 0 ? void 0 : gpuMSAATexture.createView(msaaViewDescriptor);\n colorAttachments.push({\n view: colorMSAATextureView ? colorMSAATextureView : colorTextureView,\n resolveTarget: gpuMSAATexture ? colorTextureView : undefined,\n clearValue: index !== 0 && mustClearColor ? clearColor : undefined,\n loadOp: index !== 0 && mustClearColor ? WebGPUConstants.LoadOp.Clear : WebGPUConstants.LoadOp.Load,\n storeOp: WebGPUConstants.StoreOp.Store,\n });\n }\n }\n this._cacheRenderPipeline.setMRT(rtWrapper.textures, this._mrtAttachments.length);\n this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments);\n }\n else {\n // single render target\n const internalTexture = rtWrapper.texture;\n if (internalTexture) {\n const gpuWrapper = internalTexture._hardwareTexture;\n const gpuTexture = gpuWrapper.underlyingResource;\n const gpuMSAATexture = gpuWrapper.getMSAATexture();\n const colorTextureView = gpuTexture.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor);\n const colorMSAATextureView = gpuMSAATexture === null || gpuMSAATexture === void 0 ? void 0 : gpuMSAATexture.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor);\n colorAttachments.push({\n view: colorMSAATextureView ? colorMSAATextureView : colorTextureView,\n resolveTarget: gpuMSAATexture ? colorTextureView : undefined,\n clearValue: mustClearColor ? clearColor : undefined,\n loadOp: mustClearColor ? WebGPUConstants.LoadOp.Clear : WebGPUConstants.LoadOp.Load,\n storeOp: WebGPUConstants.StoreOp.Store,\n });\n }\n else {\n colorAttachments.push(null);\n }\n }\n (_e = this._debugPushGroup) === null || _e === void 0 ? void 0 : _e.call(this, \"render target pass\", 1);\n this._rttRenderPassWrapper.renderPassDescriptor = {\n colorAttachments,\n depthStencilAttachment: depthStencilTexture && gpuDepthStencilTexture\n ? {\n view: depthMSAATextureView ? depthMSAATextureView : depthTextureView,\n depthClearValue: mustClearDepth ? (this.useReverseDepthBuffer ? this._clearReverseDepthValue : this._clearDepthValue) : undefined,\n depthLoadOp: mustClearDepth ? WebGPUConstants.LoadOp.Clear : WebGPUConstants.LoadOp.Load,\n depthStoreOp: WebGPUConstants.StoreOp.Store,\n stencilClearValue: rtWrapper._depthStencilTextureWithStencil && mustClearStencil ? this._clearStencilValue : undefined,\n stencilLoadOp: !depthTextureHasStencil\n ? undefined\n : rtWrapper._depthStencilTextureWithStencil && mustClearStencil\n ? WebGPUConstants.LoadOp.Clear\n : WebGPUConstants.LoadOp.Load,\n stencilStoreOp: !depthTextureHasStencil ? undefined : WebGPUConstants.StoreOp.Store,\n }\n : undefined,\n occlusionQuerySet: ((_f = this._occlusionQuery) === null || _f === void 0 ? void 0 : _f.hasQueries) ? this._occlusionQuery.querySet : undefined,\n };\n this._rttRenderPassWrapper.renderPass = this._renderTargetEncoder.beginRenderPass(this._rttRenderPassWrapper.renderPassDescriptor);\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n const internalTexture = rtWrapper.texture;\n console.log(\"frame #\" + this._count + \" - render target begin pass - internalTexture.uniqueId=\", internalTexture.uniqueId, \"width=\", internalTexture.width, \"height=\", internalTexture.height, this._rttRenderPassWrapper.renderPassDescriptor);\n }\n }\n this._currentRenderPass = this._rttRenderPassWrapper.renderPass;\n (_g = this._debugFlushPendingCommands) === null || _g === void 0 ? void 0 : _g.call(this);\n this._resetCurrentViewport(1);\n this._resetCurrentScissor(1);\n this._resetCurrentStencilRef(1);\n this._resetCurrentColorBlend(1);\n if (!gpuDepthStencilWrapper || !WebGPUTextureHelper.HasStencilAspect(gpuDepthStencilWrapper.format)) {\n this._stencilStateComposer.enabled = false;\n }\n }\n /** @internal */\n _endRenderTargetRenderPass() {\n var _a, _b, _c, _d;\n if (this._currentRenderPass) {\n const gpuWrapper = (_a = this._currentRenderTarget.texture) === null || _a === void 0 ? void 0 : _a._hardwareTexture;\n if (gpuWrapper && !this._snapshotRendering.endRenderTargetPass(this._currentRenderPass, gpuWrapper) && !this.compatibilityMode) {\n this._bundleListRenderTarget.run(this._currentRenderPass);\n this._bundleListRenderTarget.reset();\n }\n this._currentRenderPass.end();\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n console.log(\"frame #\" + this._count + \" - render target end pass - internalTexture.uniqueId=\", (_c = (_b = this._currentRenderTarget) === null || _b === void 0 ? void 0 : _b.texture) === null || _c === void 0 ? void 0 : _c.uniqueId);\n }\n }\n (_d = this._debugPopGroup) === null || _d === void 0 ? void 0 : _d.call(this, 1);\n this._resetCurrentViewport(1);\n this._viewport(0, 0, 0, 0);\n this._resetCurrentScissor(1);\n this._resetCurrentStencilRef(1);\n this._resetCurrentColorBlend(1);\n this._currentRenderPass = null;\n this._rttRenderPassWrapper.reset();\n }\n }\n _getCurrentRenderPass() {\n if (this._currentRenderTarget && !this._currentRenderPass) {\n // delayed creation of the render target pass, but we now need to create it as we are requested the render pass\n this._startRenderTargetRenderPass(this._currentRenderTarget, false, null, false, false);\n }\n else if (!this._currentRenderPass) {\n this._startMainRenderPass(false);\n }\n return this._currentRenderPass;\n }\n /** @internal */\n _getCurrentRenderPassIndex() {\n return this._currentRenderPass === null ? -1 : this._currentRenderPass === this._mainRenderPassWrapper.renderPass ? 0 : 1;\n }\n _startMainRenderPass(setClearStates, clearColor, clearDepth, clearStencil) {\n var _a, _b, _c;\n if (this._mainRenderPassWrapper.renderPass) {\n this.flushFramebuffer(false);\n }\n if (this.useReverseDepthBuffer) {\n this.setDepthFunctionToGreaterOrEqual();\n }\n const mustClearColor = setClearStates && clearColor;\n const mustClearDepth = setClearStates && clearDepth;\n const mustClearStencil = setClearStates && clearStencil;\n this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].clearValue = mustClearColor ? clearColor : undefined;\n this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].loadOp = mustClearColor ? WebGPUConstants.LoadOp.Clear : WebGPUConstants.LoadOp.Load;\n this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthClearValue = mustClearDepth\n ? this.useReverseDepthBuffer\n ? this._clearReverseDepthValue\n : this._clearDepthValue\n : undefined;\n this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthLoadOp = mustClearDepth ? WebGPUConstants.LoadOp.Clear : WebGPUConstants.LoadOp.Load;\n this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilClearValue = mustClearStencil ? this._clearStencilValue : undefined;\n this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilLoadOp = !this.isStencilEnable\n ? undefined\n : mustClearStencil\n ? WebGPUConstants.LoadOp.Clear\n : WebGPUConstants.LoadOp.Load;\n this._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet = ((_a = this._occlusionQuery) === null || _a === void 0 ? void 0 : _a.hasQueries) ? this._occlusionQuery.querySet : undefined;\n const swapChainTexture = this._context.getCurrentTexture();\n this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].set(swapChainTexture);\n // Resolve in case of MSAA\n if (this._options.antialias) {\n viewDescriptorSwapChainAntialiasing.format = swapChainTexture.format;\n this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].resolveTarget = swapChainTexture.createView(viewDescriptorSwapChainAntialiasing);\n }\n else {\n viewDescriptorSwapChain.format = swapChainTexture.format;\n this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].view = swapChainTexture.createView(viewDescriptorSwapChain);\n }\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n console.log(\"frame #\" + this._count + \" - main begin pass - texture width=\" + this._mainTextureExtends.width, \" height=\" + this._mainTextureExtends.height, this._mainRenderPassWrapper.renderPassDescriptor);\n }\n }\n (_b = this._debugPushGroup) === null || _b === void 0 ? void 0 : _b.call(this, \"main pass\", 0);\n this._currentRenderPass = this._renderEncoder.beginRenderPass(this._mainRenderPassWrapper.renderPassDescriptor);\n this._mainRenderPassWrapper.renderPass = this._currentRenderPass;\n (_c = this._debugFlushPendingCommands) === null || _c === void 0 ? void 0 : _c.call(this);\n this._resetCurrentViewport(0);\n this._resetCurrentScissor(0);\n this._resetCurrentStencilRef(0);\n this._resetCurrentColorBlend(0);\n if (!this._isStencilEnable) {\n this._stencilStateComposer.enabled = false;\n }\n }\n _endMainRenderPass() {\n var _a;\n if (this._mainRenderPassWrapper.renderPass !== null) {\n this._snapshotRendering.endMainRenderPass();\n if (!this.compatibilityMode && !this._snapshotRendering.play) {\n this._bundleList.run(this._mainRenderPassWrapper.renderPass);\n this._bundleList.reset();\n }\n this._mainRenderPassWrapper.renderPass.end();\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n console.log(\"frame #\" + this._count + \" - main end pass\");\n }\n }\n (_a = this._debugPopGroup) === null || _a === void 0 ? void 0 : _a.call(this, 0);\n this._resetCurrentViewport(0);\n this._resetCurrentScissor(0);\n this._resetCurrentStencilRef(0);\n this._resetCurrentColorBlend(0);\n if (this._mainRenderPassWrapper.renderPass === this._currentRenderPass) {\n this._currentRenderPass = null;\n }\n this._mainRenderPassWrapper.reset(false);\n }\n }\n /**\n * Binds the frame buffer to the specified texture.\n * @param texture The render target wrapper to render to\n * @param faceIndex The face of the texture to render to in case of cube texture\n * @param requiredWidth The width of the target to render to\n * @param requiredHeight The height of the target to render to\n * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true\n * @param lodLevel defines the lod level to bind to the frame buffer\n * @param layer defines the 2d array index to bind to frame buffer to\n */\n bindFramebuffer(texture, faceIndex = 0, requiredWidth, requiredHeight, forceFullscreenViewport, lodLevel = 0, layer = 0) {\n var _a, _b;\n const hardwareTexture = (_a = texture.texture) === null || _a === void 0 ? void 0 : _a._hardwareTexture;\n if (this._currentRenderTarget) {\n this.unBindFramebuffer(this._currentRenderTarget);\n }\n this._currentRenderTarget = texture;\n if (hardwareTexture) {\n hardwareTexture._currentLayer = texture.isCube ? layer * 6 + faceIndex : layer;\n }\n this._rttRenderPassWrapper.colorAttachmentGPUTextures[0] = hardwareTexture;\n this._rttRenderPassWrapper.depthTextureFormat = this._currentRenderTarget._depthStencilTexture\n ? WebGPUTextureHelper.GetWebGPUTextureFormat(-1, this._currentRenderTarget._depthStencilTexture.format)\n : undefined;\n this._setDepthTextureFormat(this._rttRenderPassWrapper);\n this._setColorFormat(this._rttRenderPassWrapper);\n this._rttRenderPassWrapper.colorAttachmentViewDescriptor = {\n format: this._colorFormat,\n dimension: WebGPUConstants.TextureViewDimension.E2d,\n mipLevelCount: 1,\n baseArrayLayer: texture.isCube ? layer * 6 + faceIndex : layer,\n baseMipLevel: lodLevel,\n arrayLayerCount: 1,\n aspect: WebGPUConstants.TextureAspect.All,\n };\n this._rttRenderPassWrapper.depthAttachmentViewDescriptor = {\n format: this._depthTextureFormat,\n dimension: WebGPUConstants.TextureViewDimension.E2d,\n mipLevelCount: 1,\n baseArrayLayer: texture.isCube ? layer * 6 + faceIndex : layer,\n baseMipLevel: 0,\n arrayLayerCount: 1,\n aspect: WebGPUConstants.TextureAspect.All,\n };\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n console.log(\"frame #\" + this._count + \" - bindFramebuffer called - internalTexture.uniqueId=\", (_b = texture.texture) === null || _b === void 0 ? void 0 : _b.uniqueId, \"face=\", faceIndex, \"lodLevel=\", lodLevel, \"layer=\", layer, this._rttRenderPassWrapper.colorAttachmentViewDescriptor, this._rttRenderPassWrapper.depthAttachmentViewDescriptor);\n }\n }\n this._currentRenderPass = null; // lazy creation of the render pass, hoping the render pass will be created by a call to clear()...\n if (this.snapshotRendering && this.snapshotRenderingMode === 1) {\n // force the creation of the render pass as we know in fast snapshot rendering mode clear() won't be called\n this._getCurrentRenderPass();\n }\n if (this._cachedViewport && !forceFullscreenViewport) {\n this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);\n }\n else {\n if (!requiredWidth) {\n requiredWidth = texture.width;\n if (lodLevel) {\n requiredWidth = requiredWidth / Math.pow(2, lodLevel);\n }\n }\n if (!requiredHeight) {\n requiredHeight = texture.height;\n if (lodLevel) {\n requiredHeight = requiredHeight / Math.pow(2, lodLevel);\n }\n }\n this._viewport(0, 0, requiredWidth, requiredHeight);\n }\n this.wipeCaches();\n }\n /**\n * Unbind the current render target texture from the WebGPU context\n * @param texture defines the render target wrapper to unbind\n * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated\n * @param onBeforeUnbind defines a function which will be called before the effective unbind\n */\n unBindFramebuffer(texture, disableGenerateMipMaps = false, onBeforeUnbind) {\n var _a, _b;\n const saveCRT = this._currentRenderTarget;\n this._currentRenderTarget = null; // to be iso with thinEngine, this._currentRenderTarget must be null when onBeforeUnbind is called\n if (onBeforeUnbind) {\n onBeforeUnbind();\n }\n this._currentRenderTarget = saveCRT;\n if (this._currentRenderPass && this._currentRenderPass !== this._mainRenderPassWrapper.renderPass) {\n this._endRenderTargetRenderPass();\n }\n if (((_a = texture.texture) === null || _a === void 0 ? void 0 : _a.generateMipMaps) && !disableGenerateMipMaps && !texture.isCube) {\n this._generateMipmaps(texture.texture);\n }\n this._currentRenderTarget = null;\n this._onAfterUnbindFrameBufferObservable.notifyObservers(this);\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n console.log(\"frame #\" + this._count + \" - unBindFramebuffer called - internalTexture.uniqueId=\", (_b = texture.texture) === null || _b === void 0 ? void 0 : _b.uniqueId);\n }\n }\n this._mrtAttachments = [];\n this._cacheRenderPipeline.setMRT([]);\n this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments);\n this._currentRenderPass = this._mainRenderPassWrapper.renderPass;\n this._setDepthTextureFormat(this._mainRenderPassWrapper);\n this._setColorFormat(this._mainRenderPassWrapper);\n }\n /**\n * Unbind the current render target and bind the default framebuffer\n */\n restoreDefaultFramebuffer() {\n if (this._currentRenderTarget) {\n this.unBindFramebuffer(this._currentRenderTarget);\n }\n else {\n this._currentRenderPass = this._mainRenderPassWrapper.renderPass;\n this._setDepthTextureFormat(this._mainRenderPassWrapper);\n this._setColorFormat(this._mainRenderPassWrapper);\n }\n if (this._currentRenderPass) {\n if (this._cachedViewport) {\n this.setViewport(this._cachedViewport);\n }\n }\n this.wipeCaches();\n }\n //------------------------------------------------------------------------------\n // Render\n //------------------------------------------------------------------------------\n /**\n * @internal\n */\n _setColorFormat(wrapper) {\n var _a, _b;\n const format = (_b = (_a = wrapper.colorAttachmentGPUTextures[0]) === null || _a === void 0 ? void 0 : _a.format) !== null && _b !== void 0 ? _b : null;\n this._cacheRenderPipeline.setColorFormat(format);\n if (this._colorFormat === format) {\n return;\n }\n this._colorFormat = format;\n }\n /**\n * @internal\n */\n _setDepthTextureFormat(wrapper) {\n this._cacheRenderPipeline.setDepthStencilFormat(wrapper.depthTextureFormat);\n if (this._depthTextureFormat === wrapper.depthTextureFormat) {\n return;\n }\n this._depthTextureFormat = wrapper.depthTextureFormat;\n }\n setDitheringState() {\n // Does not exist in WebGPU\n }\n setRasterizerState() {\n // Does not exist in WebGPU\n }\n /**\n * Set various states to the webGL context\n * @param culling defines culling state: true to enable culling, false to disable it\n * @param zOffset defines the value to apply to zOffset (0 by default)\n * @param force defines if states must be applied even if cache is up to date\n * @param reverseSide defines if culling must be reversed (CCW if false, CW if true)\n * @param cullBackFaces true to cull back faces, false to cull front faces (if culling is enabled)\n * @param stencil stencil states to set\n * @param zOffsetUnits defines the value to apply to zOffsetUnits (0 by default)\n */\n setState(culling, zOffset = 0, force, reverseSide = false, cullBackFaces, stencil, zOffsetUnits = 0) {\n var _a, _b;\n // Culling\n if (this._depthCullingState.cull !== culling || force) {\n this._depthCullingState.cull = culling;\n }\n // Cull face\n const cullFace = ((_b = (_a = this.cullBackFaces) !== null && _a !== void 0 ? _a : cullBackFaces) !== null && _b !== void 0 ? _b : true) ? 1 : 2;\n if (this._depthCullingState.cullFace !== cullFace || force) {\n this._depthCullingState.cullFace = cullFace;\n }\n // Z offset\n this.setZOffset(zOffset);\n this.setZOffsetUnits(zOffsetUnits);\n // Front face\n const frontFace = reverseSide ? (this._currentRenderTarget ? 1 : 2) : this._currentRenderTarget ? 2 : 1;\n if (this._depthCullingState.frontFace !== frontFace || force) {\n this._depthCullingState.frontFace = frontFace;\n }\n this._stencilStateComposer.stencilMaterial = stencil;\n }\n _applyRenderPassChanges(renderPass, bundleList) {\n var _a;\n const mustUpdateViewport = this._mustUpdateViewport(renderPass);\n const mustUpdateScissor = this._mustUpdateScissor(renderPass);\n const mustUpdateStencilRef = !this._stencilStateComposer.enabled ? false : this._mustUpdateStencilRef(renderPass);\n const mustUpdateBlendColor = !this._alphaState.alphaBlend ? false : this._mustUpdateBlendColor(renderPass);\n if (bundleList) {\n if (mustUpdateViewport) {\n bundleList.addItem(new WebGPURenderItemViewport(this._viewportCached.x, this._viewportCached.y, this._viewportCached.z, this._viewportCached.w));\n }\n if (mustUpdateScissor) {\n bundleList.addItem(new WebGPURenderItemScissor(this._scissorCached.x, this._scissorCached.y, this._scissorCached.z, this._scissorCached.w));\n }\n if (mustUpdateStencilRef) {\n bundleList.addItem(new WebGPURenderItemStencilRef((_a = this._stencilStateComposer.funcRef) !== null && _a !== void 0 ? _a : 0));\n }\n if (mustUpdateBlendColor) {\n bundleList.addItem(new WebGPURenderItemBlendColor(this._alphaState._blendConstants.slice()));\n }\n }\n else {\n if (mustUpdateViewport) {\n this._applyViewport(renderPass);\n }\n if (mustUpdateScissor) {\n this._applyScissor(renderPass);\n }\n if (mustUpdateStencilRef) {\n this._applyStencilRef(renderPass);\n }\n if (mustUpdateBlendColor) {\n this._applyBlendColor(renderPass);\n }\n }\n }\n _draw(drawType, fillMode, start, count, instancesCount) {\n var _a;\n const renderPass = this._getCurrentRenderPass();\n const renderPassIndex = this._getCurrentRenderPassIndex();\n const bundleList = renderPassIndex === 0 ? this._bundleList : this._bundleListRenderTarget;\n this.applyStates();\n const webgpuPipelineContext = this._currentEffect._pipelineContext;\n this.bindUniformBufferBase(this._currentRenderTarget ? this._ubInvertY : this._ubDontInvertY, 0, WebGPUShaderProcessor.InternalsUBOName);\n if (webgpuPipelineContext.uniformBuffer) {\n webgpuPipelineContext.uniformBuffer.update();\n this.bindUniformBufferBase(webgpuPipelineContext.uniformBuffer.getBuffer(), 0, WebGPUShaderProcessor.LeftOvertUBOName);\n }\n if (this._snapshotRendering.play) {\n this._reportDrawCall();\n return;\n }\n if (!this.compatibilityMode &&\n (this._currentDrawContext.isDirty(this._currentMaterialContext.updateId) || this._currentMaterialContext.isDirty || this._currentMaterialContext.forceBindGroupCreation)) {\n this._currentDrawContext.fastBundle = undefined;\n }\n const useFastPath = !this.compatibilityMode && this._currentDrawContext.fastBundle;\n let renderPass2 = renderPass;\n if (useFastPath || this._snapshotRendering.record) {\n this._applyRenderPassChanges(renderPass, bundleList);\n if (!this._snapshotRendering.record) {\n this._counters.numBundleReuseNonCompatMode++;\n if (this._currentDrawContext.indirectDrawBuffer) {\n this._currentDrawContext.setIndirectData(count, instancesCount || 1, start);\n }\n bundleList.addBundle(this._currentDrawContext.fastBundle);\n this._reportDrawCall();\n return;\n }\n renderPass2 = bundleList.getBundleEncoder(this._cacheRenderPipeline.colorFormats, this._depthTextureFormat, this.currentSampleCount); // for snapshot recording mode\n bundleList.numDrawCalls++;\n }\n let textureState = 0;\n if (!this._caps.textureFloatLinearFiltering && this._currentMaterialContext.hasFloatTextures) {\n let bitVal = 1;\n for (let i = 0; i < webgpuPipelineContext.shaderProcessingContext.textureNames.length; ++i) {\n const textureName = webgpuPipelineContext.shaderProcessingContext.textureNames[i];\n const texture = (_a = this._currentMaterialContext.textures[textureName]) === null || _a === void 0 ? void 0 : _a.texture;\n if ((texture === null || texture === void 0 ? void 0 : texture.type) === 1) {\n textureState |= bitVal;\n }\n bitVal = bitVal << 1;\n }\n }\n this._currentMaterialContext.textureState = textureState;\n const pipeline = this._cacheRenderPipeline.getRenderPipeline(fillMode, this._currentEffect, this.currentSampleCount, textureState);\n const bindGroups = this._cacheBindGroups.getBindGroups(webgpuPipelineContext, this._currentDrawContext, this._currentMaterialContext);\n if (!this._snapshotRendering.record) {\n this._applyRenderPassChanges(renderPass, !this.compatibilityMode ? bundleList : null);\n if (!this.compatibilityMode) {\n this._counters.numBundleCreationNonCompatMode++;\n renderPass2 = this._device.createRenderBundleEncoder({\n colorFormats: this._cacheRenderPipeline.colorFormats,\n depthStencilFormat: this._depthTextureFormat,\n sampleCount: this.currentSampleCount,\n });\n }\n }\n // bind pipeline\n renderPass2.setPipeline(pipeline);\n // bind index/vertex buffers\n if (this._currentIndexBuffer) {\n renderPass2.setIndexBuffer(this._currentIndexBuffer.underlyingResource, this._currentIndexBuffer.is32Bits ? WebGPUConstants.IndexFormat.Uint32 : WebGPUConstants.IndexFormat.Uint16, 0);\n }\n const vertexBuffers = this._cacheRenderPipeline.vertexBuffers;\n for (let index = 0; index < vertexBuffers.length; index++) {\n const vertexBuffer = vertexBuffers[index];\n const buffer = vertexBuffer.getBuffer();\n if (buffer) {\n renderPass2.setVertexBuffer(index, buffer.underlyingResource, vertexBuffer._validOffsetRange ? 0 : vertexBuffer.byteOffset);\n }\n }\n // bind bind groups\n for (let i = 0; i < bindGroups.length; i++) {\n renderPass2.setBindGroup(i, bindGroups[i]);\n }\n // draw\n const nonCompatMode = !this.compatibilityMode && !this._snapshotRendering.record;\n if (nonCompatMode && this._currentDrawContext.indirectDrawBuffer) {\n this._currentDrawContext.setIndirectData(count, instancesCount || 1, start);\n if (drawType === 0) {\n renderPass2.drawIndexedIndirect(this._currentDrawContext.indirectDrawBuffer, 0);\n }\n else {\n renderPass2.drawIndirect(this._currentDrawContext.indirectDrawBuffer, 0);\n }\n }\n else if (drawType === 0) {\n renderPass2.drawIndexed(count, instancesCount || 1, start, 0, 0);\n }\n else {\n renderPass2.draw(count, instancesCount || 1, start, 0);\n }\n if (nonCompatMode) {\n this._currentDrawContext.fastBundle = renderPass2.finish();\n bundleList.addBundle(this._currentDrawContext.fastBundle);\n }\n this._reportDrawCall();\n }\n /**\n * Draw a list of indexed primitives\n * @param fillMode defines the primitive to use\n * @param indexStart defines the starting index\n * @param indexCount defines the number of index to draw\n * @param instancesCount defines the number of instances to draw (if instantiation is enabled)\n */\n drawElementsType(fillMode, indexStart, indexCount, instancesCount = 1) {\n this._draw(0, fillMode, indexStart, indexCount, instancesCount);\n }\n /**\n * Draw a list of unindexed primitives\n * @param fillMode defines the primitive to use\n * @param verticesStart defines the index of first vertex to draw\n * @param verticesCount defines the count of vertices to draw\n * @param instancesCount defines the number of instances to draw (if instantiation is enabled)\n */\n drawArraysType(fillMode, verticesStart, verticesCount, instancesCount = 1) {\n this._currentIndexBuffer = null;\n this._draw(1, fillMode, verticesStart, verticesCount, instancesCount);\n }\n //------------------------------------------------------------------------------\n // Dispose\n //------------------------------------------------------------------------------\n /**\n * Dispose and release all associated resources\n */\n dispose() {\n var _a, _b;\n this._isDisposed = true;\n (_a = this._mainTexture) === null || _a === void 0 ? void 0 : _a.destroy();\n (_b = this._depthTexture) === null || _b === void 0 ? void 0 : _b.destroy();\n this._device.destroy();\n super.dispose();\n }\n //------------------------------------------------------------------------------\n // Misc\n //------------------------------------------------------------------------------\n /**\n * Gets the current render width\n * @param useScreen defines if screen size must be used (or the current render target if any)\n * @returns a number defining the current render width\n */\n getRenderWidth(useScreen = false) {\n var _a, _b;\n if (!useScreen && this._currentRenderTarget) {\n return this._currentRenderTarget.width;\n }\n return (_b = (_a = this._renderingCanvas) === null || _a === void 0 ? void 0 : _a.width) !== null && _b !== void 0 ? _b : 0;\n }\n /**\n * Gets the current render height\n * @param useScreen defines if screen size must be used (or the current render target if any)\n * @returns a number defining the current render height\n */\n getRenderHeight(useScreen = false) {\n var _a, _b;\n if (!useScreen && this._currentRenderTarget) {\n return this._currentRenderTarget.height;\n }\n return (_b = (_a = this._renderingCanvas) === null || _a === void 0 ? void 0 : _a.height) !== null && _b !== void 0 ? _b : 0;\n }\n //------------------------------------------------------------------------------\n // Errors\n //------------------------------------------------------------------------------\n /**\n * Get the current error code of the WebGPU context\n * @returns the error code\n */\n getError() {\n // TODO WEBGPU. from the webgpu errors.\n return 0;\n }\n //------------------------------------------------------------------------------\n // Unused WebGPU\n //------------------------------------------------------------------------------\n /**\n * @internal\n */\n bindSamplers() { }\n /**\n * @internal\n */\n _bindTextureDirectly() {\n return false;\n }\n /**\n * Gets a boolean indicating if all created effects are ready\n * @returns always true - No parallel shader compilation\n */\n areAllEffectsReady() {\n return true;\n }\n /**\n * @internal\n */\n _executeWhenRenderingStateIsCompiled(pipelineContext, action) {\n // No parallel shader compilation.\n // No Async, so direct launch\n action();\n }\n /**\n * @internal\n */\n _isRenderingStateCompiled() {\n // No parallel shader compilation.\n return true;\n }\n /** @internal */\n _getUnpackAlignement() {\n return 1;\n }\n /**\n * @internal\n */\n _unpackFlipY() { }\n /**\n * @internal\n */\n _bindUnboundFramebuffer() {\n throw \"_bindUnboundFramebuffer is not implementedin WebGPU! You probably want to use restoreDefaultFramebuffer or unBindFramebuffer instead\";\n }\n // TODO WEBGPU. All of the below should go once engine split with baseEngine.\n /**\n * @internal\n */\n _getSamplingParameters() {\n throw \"_getSamplingParameters is not available in WebGPU\";\n }\n /**\n * @internal\n */\n getUniforms() {\n return [];\n }\n /**\n * @internal\n */\n setIntArray() {\n return false;\n }\n /**\n * @internal\n */\n setIntArray2() {\n return false;\n }\n /**\n * @internal\n */\n setIntArray3() {\n return false;\n }\n /**\n * @internal\n */\n setIntArray4() {\n return false;\n }\n /**\n * @internal\n */\n setArray() {\n return false;\n }\n /**\n * @internal\n */\n setArray2() {\n return false;\n }\n /**\n * @internal\n */\n setArray3() {\n return false;\n }\n /**\n * @internal\n */\n setArray4() {\n return false;\n }\n /**\n * @internal\n */\n setMatrices() {\n return false;\n }\n /**\n * @internal\n */\n setMatrix3x3() {\n return false;\n }\n /**\n * @internal\n */\n setMatrix2x2() {\n return false;\n }\n /**\n * @internal\n */\n setFloat() {\n return false;\n }\n /**\n * @internal\n */\n setFloat2() {\n return false;\n }\n /**\n * @internal\n */\n setFloat3() {\n return false;\n }\n /**\n * @internal\n */\n setFloat4() {\n return false;\n }\n}\n// Default glslang options.\nWebGPUEngine._GLSLslangDefaultOptions = {\n jsPath: \"https://preview.babylonjs.com/glslang/glslang.js\",\n wasmPath: \"https://preview.babylonjs.com/glslang/glslang.wasm\",\n};\n/** true to enable using TintWASM to convert Spir-V to WGSL */\nWebGPUEngine.UseTWGSL = true;\n//# sourceMappingURL=webgpuEngine.js.map","\nimport { Engine } from \"../../engine.js\";\nimport { WebGPUEngine } from \"../../webgpuEngine.js\";\nWebGPUEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange = false) {\n if (this._alphaMode === mode && ((mode === 0 && !this._alphaState.alphaBlend) || (mode !== 0 && this._alphaState.alphaBlend))) {\n if (!noDepthWriteChange) {\n // Make sure we still have the correct depth mask according to the alpha mode (a transparent material could have forced writting to the depth buffer, for instance)\n const depthMask = mode === 0;\n if (this.depthCullingState.depthMask !== depthMask) {\n this.setDepthWrite(depthMask);\n this._cacheRenderPipeline.setDepthWriteEnabled(depthMask);\n }\n }\n return;\n }\n switch (mode) {\n case 0:\n this._alphaState.alphaBlend = false;\n break;\n case 7:\n this._alphaState.setAlphaBlendFunctionParameters(1, 771, 1, 1);\n this._alphaState.alphaBlend = true;\n break;\n case 8:\n this._alphaState.setAlphaBlendFunctionParameters(1, 771, 1, 771);\n this._alphaState.alphaBlend = true;\n break;\n case 2:\n this._alphaState.setAlphaBlendFunctionParameters(770, 771, 1, 1);\n this._alphaState.alphaBlend = true;\n break;\n case 6:\n this._alphaState.setAlphaBlendFunctionParameters(1, 1, 0, 1);\n this._alphaState.alphaBlend = true;\n break;\n case 1:\n this._alphaState.setAlphaBlendFunctionParameters(770, 1, 0, 1);\n this._alphaState.alphaBlend = true;\n break;\n case 3:\n this._alphaState.setAlphaBlendFunctionParameters(0, 769, 1, 1);\n this._alphaState.alphaBlend = true;\n break;\n case 4:\n this._alphaState.setAlphaBlendFunctionParameters(774, 0, 1, 1);\n this._alphaState.alphaBlend = true;\n break;\n case 5:\n this._alphaState.setAlphaBlendFunctionParameters(770, 769, 1, 1);\n this._alphaState.alphaBlend = true;\n break;\n case 9:\n this._alphaState.setAlphaBlendFunctionParameters(32769, 32770, 32771, 32772);\n this._alphaState.alphaBlend = true;\n break;\n case 10:\n this._alphaState.setAlphaBlendFunctionParameters(1, 769, 1, 771);\n this._alphaState.alphaBlend = true;\n break;\n case 11:\n this._alphaState.setAlphaBlendFunctionParameters(1, 1, 1, 1);\n this._alphaState.alphaBlend = true;\n break;\n case 12:\n this._alphaState.setAlphaBlendFunctionParameters(772, 1, 0, 0);\n this._alphaState.alphaBlend = true;\n break;\n case 13:\n this._alphaState.setAlphaBlendFunctionParameters(775, 769, 773, 771);\n this._alphaState.alphaBlend = true;\n break;\n case 14:\n this._alphaState.setAlphaBlendFunctionParameters(1, 771, 1, 771);\n this._alphaState.alphaBlend = true;\n break;\n case 15:\n this._alphaState.setAlphaBlendFunctionParameters(1, 1, 1, 0);\n this._alphaState.alphaBlend = true;\n break;\n case 16:\n this._alphaState.setAlphaBlendFunctionParameters(775, 769, 0, 1);\n this._alphaState.alphaBlend = true;\n break;\n case 17:\n // Same as ALPHA_COMBINE but accumulates (1 - alpha) values in the alpha channel for a later readout in order independant transparency\n this._alphaState.setAlphaBlendFunctionParameters(770, 771, 1, 771);\n this._alphaState.alphaBlend = true;\n break;\n }\n if (!noDepthWriteChange) {\n this.setDepthWrite(mode === Engine.ALPHA_DISABLE);\n this._cacheRenderPipeline.setDepthWriteEnabled(mode === Engine.ALPHA_DISABLE);\n }\n this._alphaMode = mode;\n this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend);\n this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters, this._alphaState._blendEquationParameters);\n};\nWebGPUEngine.prototype.setAlphaEquation = function (equation) {\n Engine.prototype.setAlphaEquation.call(this, equation);\n this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters, this._alphaState._blendEquationParameters);\n};\n//# sourceMappingURL=engine.alpha.js.map","import { Logger } from \"../../Misc/logger.js\";\nimport { ComputeBindingType } from \"../Extensions/engine.computeShader.js\";\nimport * as WebGPUConstants from \"./webgpuConstants.js\";\n/** @internal */\nexport class WebGPUComputeContext {\n getBindGroups(bindings, computePipeline, bindingsMapping) {\n if (!bindingsMapping) {\n throw new Error(\"WebGPUComputeContext.getBindGroups: bindingsMapping is required until browsers support reflection for wgsl shaders!\");\n }\n if (this._bindGroups.length === 0) {\n const bindGroupEntriesExist = this._bindGroupEntries.length > 0;\n for (const key in bindings) {\n const binding = bindings[key], location = bindingsMapping[key], group = location.group, index = location.binding, type = binding.type, object = binding.object;\n let indexInGroupEntries = binding.indexInGroupEntries;\n let entries = this._bindGroupEntries[group];\n if (!entries) {\n entries = this._bindGroupEntries[group] = [];\n }\n switch (type) {\n case ComputeBindingType.Sampler: {\n const sampler = object;\n if (indexInGroupEntries !== undefined && bindGroupEntriesExist) {\n entries[indexInGroupEntries].resource = this._cacheSampler.getSampler(sampler);\n }\n else {\n binding.indexInGroupEntries = entries.length;\n entries.push({\n binding: index,\n resource: this._cacheSampler.getSampler(sampler),\n });\n }\n break;\n }\n case ComputeBindingType.Texture:\n case ComputeBindingType.TextureWithoutSampler: {\n const texture = object;\n const hardwareTexture = texture._texture._hardwareTexture;\n if (indexInGroupEntries !== undefined && bindGroupEntriesExist) {\n if (type === ComputeBindingType.Texture) {\n entries[indexInGroupEntries++].resource = this._cacheSampler.getSampler(texture._texture);\n }\n entries[indexInGroupEntries].resource = hardwareTexture.view;\n }\n else {\n binding.indexInGroupEntries = entries.length;\n if (type === ComputeBindingType.Texture) {\n entries.push({\n binding: index - 1,\n resource: this._cacheSampler.getSampler(texture._texture),\n });\n }\n entries.push({\n binding: index,\n resource: hardwareTexture.view,\n });\n }\n break;\n }\n case ComputeBindingType.StorageTexture: {\n const texture = object;\n const hardwareTexture = texture._texture._hardwareTexture;\n if ((hardwareTexture.textureAdditionalUsages & WebGPUConstants.TextureUsage.StorageBinding) === 0) {\n Logger.Error(`computeDispatch: The texture (name=${texture.name}, uniqueId=${texture.uniqueId}) is not a storage texture!`, 50);\n }\n if (indexInGroupEntries !== undefined && bindGroupEntriesExist) {\n entries[indexInGroupEntries].resource = hardwareTexture.viewForWriting;\n }\n else {\n binding.indexInGroupEntries = entries.length;\n entries.push({\n binding: index,\n resource: hardwareTexture.viewForWriting,\n });\n }\n break;\n }\n case ComputeBindingType.UniformBuffer:\n case ComputeBindingType.StorageBuffer: {\n const buffer = type === ComputeBindingType.UniformBuffer ? object : object;\n const dataBuffer = buffer.getBuffer();\n const webgpuBuffer = dataBuffer.underlyingResource;\n if (indexInGroupEntries !== undefined && bindGroupEntriesExist) {\n entries[indexInGroupEntries].resource.buffer = webgpuBuffer;\n entries[indexInGroupEntries].resource.size = dataBuffer.capacity;\n }\n else {\n binding.indexInGroupEntries = entries.length;\n entries.push({\n binding: index,\n resource: {\n buffer: webgpuBuffer,\n offset: 0,\n size: dataBuffer.capacity,\n },\n });\n }\n break;\n }\n }\n }\n for (let i = 0; i < this._bindGroupEntries.length; ++i) {\n const entries = this._bindGroupEntries[i];\n if (!entries) {\n this._bindGroups[i] = undefined;\n continue;\n }\n this._bindGroups[i] = this._device.createBindGroup({\n layout: computePipeline.getBindGroupLayout(i),\n entries,\n });\n }\n this._bindGroups.length = this._bindGroupEntries.length;\n }\n return this._bindGroups;\n }\n constructor(device, cacheSampler) {\n this._device = device;\n this._cacheSampler = cacheSampler;\n this.uniqueId = WebGPUComputeContext._Counter++;\n this._bindGroupEntries = [];\n this.clear();\n }\n clear() {\n this._bindGroups = [];\n // Don't reset _bindGroupEntries if they have already been created, they are still ok even if we have to clear _bindGroups (the layout of the compute shader can't change once created)\n }\n}\nWebGPUComputeContext._Counter = 0;\n//# sourceMappingURL=webgpuComputeContext.js.map","/** @internal */\nexport class WebGPUComputePipelineContext {\n get isAsync() {\n return false;\n }\n get isReady() {\n if (this.stage) {\n return true;\n }\n return false;\n }\n constructor(engine) {\n this._name = \"unnamed\";\n this.engine = engine;\n }\n _getComputeShaderCode() {\n var _a;\n return (_a = this.sources) === null || _a === void 0 ? void 0 : _a.compute;\n }\n dispose() { }\n}\n//# sourceMappingURL=webgpuComputePipelineContext.js.map","import { ComputeEffect } from \"../../../Compute/computeEffect.js\";\nimport { WebGPUEngine } from \"../../webgpuEngine.js\";\nimport { WebGPUComputeContext } from \"../webgpuComputeContext.js\";\nimport { WebGPUComputePipelineContext } from \"../webgpuComputePipelineContext.js\";\nimport * as WebGPUConstants from \"../webgpuConstants.js\";\nWebGPUEngine.prototype.createComputeContext = function () {\n return new WebGPUComputeContext(this._device, this._cacheSampler);\n};\nWebGPUEngine.prototype.createComputeEffect = function (baseName, options) {\n const compute = baseName.computeElement || baseName.compute || baseName.computeToken || baseName.computeSource || baseName;\n const name = compute + \"@\" + options.defines;\n if (this._compiledComputeEffects[name]) {\n const compiledEffect = this._compiledComputeEffects[name];\n if (options.onCompiled && compiledEffect.isReady()) {\n options.onCompiled(compiledEffect);\n }\n return compiledEffect;\n }\n const effect = new ComputeEffect(baseName, options, this, name);\n this._compiledComputeEffects[name] = effect;\n return effect;\n};\nWebGPUEngine.prototype.createComputePipelineContext = function () {\n return new WebGPUComputePipelineContext(this);\n};\nWebGPUEngine.prototype.areAllComputeEffectsReady = function () {\n for (const key in this._compiledComputeEffects) {\n const effect = this._compiledComputeEffects[key];\n if (!effect.isReady()) {\n return false;\n }\n }\n return true;\n};\nWebGPUEngine.prototype.computeDispatch = function (effect, context, bindings, x, y, z, bindingsMapping) {\n if (this._currentRenderTarget) {\n // A render target pass is currently in effect (meaning beingRenderPass has been called on the command encoder this._renderTargetEncoder): we are not allowed to open\n // another pass on this command encoder (even if it's a compute pass) until endPass has been called, so we need to defer the compute pass for after the current render target pass is closed\n this._onAfterUnbindFrameBufferObservable.addOnce(() => {\n this.computeDispatch(effect, context, bindings, x, y, z, bindingsMapping);\n });\n return;\n }\n const contextPipeline = effect._pipelineContext;\n const computeContext = context;\n if (!contextPipeline.computePipeline) {\n contextPipeline.computePipeline = this._device.createComputePipeline({\n layout: WebGPUConstants.AutoLayoutMode.Auto,\n compute: contextPipeline.stage,\n });\n }\n const commandEncoder = this._renderTargetEncoder;\n const computePass = commandEncoder.beginComputePass();\n computePass.setPipeline(contextPipeline.computePipeline);\n const bindGroups = computeContext.getBindGroups(bindings, contextPipeline.computePipeline, bindingsMapping);\n for (let i = 0; i < bindGroups.length; ++i) {\n const bindGroup = bindGroups[i];\n if (!bindGroup) {\n continue;\n }\n computePass.setBindGroup(i, bindGroup);\n }\n computePass.dispatchWorkgroups(x, y, z);\n computePass.end();\n};\nWebGPUEngine.prototype.releaseComputeEffects = function () {\n for (const name in this._compiledComputeEffects) {\n const webGPUPipelineContextCompute = this._compiledComputeEffects[name].getPipelineContext();\n this._deleteComputePipelineContext(webGPUPipelineContextCompute);\n }\n this._compiledComputeEffects = {};\n};\nWebGPUEngine.prototype._prepareComputePipelineContext = function (pipelineContext, computeSourceCode, rawComputeSourceCode, defines, entryPoint) {\n const webGpuContext = pipelineContext;\n if (this.dbgShowShaderCode) {\n console.log(defines);\n console.log(computeSourceCode);\n }\n webGpuContext.sources = {\n compute: computeSourceCode,\n rawCompute: rawComputeSourceCode,\n };\n webGpuContext.stage = this._createComputePipelineStageDescriptor(computeSourceCode, defines, entryPoint);\n};\nWebGPUEngine.prototype._releaseComputeEffect = function (effect) {\n if (this._compiledComputeEffects[effect._key]) {\n delete this._compiledComputeEffects[effect._key];\n this._deleteComputePipelineContext(effect.getPipelineContext());\n }\n};\nWebGPUEngine.prototype._rebuildComputeEffects = function () {\n for (const key in this._compiledComputeEffects) {\n const effect = this._compiledComputeEffects[key];\n effect._pipelineContext = null;\n effect._wasPreviouslyReady = false;\n effect._prepareEffect();\n }\n};\nWebGPUEngine.prototype._deleteComputePipelineContext = function (pipelineContext) {\n const webgpuPipelineContext = pipelineContext;\n if (webgpuPipelineContext) {\n pipelineContext.dispose();\n }\n};\nWebGPUEngine.prototype._createComputePipelineStageDescriptor = function (computeShader, defines, entryPoint) {\n if (defines) {\n defines = \"//\" + defines.split(\"\\n\").join(\"\\n//\") + \"\\n\";\n }\n else {\n defines = \"\";\n }\n return {\n module: this._device.createShaderModule({\n code: defines + computeShader,\n }),\n entryPoint,\n };\n};\n//# sourceMappingURL=engine.computeShader.js.map","import { InternalTexture, InternalTextureSource } from \"../../../Materials/Textures/internalTexture.js\";\n\nimport { WebGPUEngine } from \"../../webgpuEngine.js\";\nWebGPUEngine.prototype._createDepthStencilCubeTexture = function (size, options) {\n const internalTexture = new InternalTexture(this, InternalTextureSource.DepthStencil);\n internalTexture.isCube = true;\n const internalOptions = Object.assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false, samples: 1 }, options);\n // TODO WEBGPU allow to choose the format?\n internalTexture.format = internalOptions.generateStencil ? 13 : 14;\n this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction, internalOptions.samples);\n this._textureHelper.createGPUTextureForInternalTexture(internalTexture);\n this._internalTexturesCache.push(internalTexture);\n return internalTexture;\n};\nWebGPUEngine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = false, lodScale = 0, lodOffset = 0, fallback = null, useSRGBBuffer = false) {\n return this.createCubeTextureBase(rootUrl, scene, files, !!noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback, null, (texture, imgs) => {\n const imageBitmaps = imgs; // we will always get an ImageBitmap array in WebGPU\n const width = imageBitmaps[0].width;\n const height = width;\n this._setCubeMapTextureParams(texture, !noMipmap);\n texture.format = format !== null && format !== void 0 ? format : -1;\n const gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, width, height);\n this._textureHelper.updateCubeTextures(imageBitmaps, gpuTextureWrapper.underlyingResource, width, height, gpuTextureWrapper.format, false, false, 0, 0);\n if (!noMipmap) {\n this._generateMipmaps(texture, this._uploadEncoder);\n }\n texture.isReady = true;\n texture.onLoadedObservable.notifyObservers(texture);\n texture.onLoadedObservable.clear();\n if (onLoad) {\n onLoad();\n }\n }, !!useSRGBBuffer);\n};\nWebGPUEngine.prototype._setCubeMapTextureParams = function (texture, loadMipmap, maxLevel) {\n texture.samplingMode = loadMipmap ? 3 : 2;\n texture._cachedWrapU = 0;\n texture._cachedWrapV = 0;\n if (maxLevel) {\n texture._maxLodLevel = maxLevel;\n }\n};\n//# sourceMappingURL=engine.cubeTexture.js.map","import { WebGPUEngine } from \"../../webgpuEngine.js\";\nWebGPUEngine.prototype._debugPushGroup = function (groupName, targetObject) {\n if (!this._options.enableGPUDebugMarkers) {\n return;\n }\n if (targetObject === 0 || targetObject === 1) {\n const encoder = targetObject === 0 ? this._renderEncoder : this._renderTargetEncoder;\n encoder.pushDebugGroup(groupName);\n }\n else if (this._currentRenderPass) {\n this._currentRenderPass.pushDebugGroup(groupName);\n }\n else {\n this._pendingDebugCommands.push([\"push\", groupName]);\n }\n};\nWebGPUEngine.prototype._debugPopGroup = function (targetObject) {\n if (!this._options.enableGPUDebugMarkers) {\n return;\n }\n if (targetObject === 0 || targetObject === 1) {\n const encoder = targetObject === 0 ? this._renderEncoder : this._renderTargetEncoder;\n encoder.popDebugGroup();\n }\n else if (this._currentRenderPass) {\n this._currentRenderPass.popDebugGroup();\n }\n else {\n this._pendingDebugCommands.push([\"pop\", null]);\n }\n};\nWebGPUEngine.prototype._debugInsertMarker = function (text, targetObject) {\n if (!this._options.enableGPUDebugMarkers) {\n return;\n }\n if (targetObject === 0 || targetObject === 1) {\n const encoder = targetObject === 0 ? this._renderEncoder : this._renderTargetEncoder;\n encoder.insertDebugMarker(text);\n }\n else if (this._currentRenderPass) {\n this._currentRenderPass.insertDebugMarker(text);\n }\n else {\n this._pendingDebugCommands.push([\"insert\", text]);\n }\n};\nWebGPUEngine.prototype._debugFlushPendingCommands = function () {\n for (let i = 0; i < this._pendingDebugCommands.length; ++i) {\n const [name, param] = this._pendingDebugCommands[i];\n switch (name) {\n case \"push\":\n this._debugPushGroup(param);\n break;\n case \"pop\":\n this._debugPopGroup();\n break;\n case \"insert\":\n this._debugInsertMarker(param);\n break;\n }\n }\n this._pendingDebugCommands.length = 0;\n};\n//# sourceMappingURL=engine.debugging.js.map","import { WebGPUEngine } from \"../../webgpuEngine.js\";\nWebGPUEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset = 0) {\n const gpuBuffer = indexBuffer;\n let view;\n if (indexBuffer.is32Bits) {\n view = indices instanceof Uint32Array ? indices : new Uint32Array(indices);\n }\n else {\n view = indices instanceof Uint16Array ? indices : new Uint16Array(indices);\n }\n this._bufferManager.setSubData(gpuBuffer, offset, view);\n};\nWebGPUEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {\n const dataBuffer = vertexBuffer;\n if (byteOffset === undefined) {\n byteOffset = 0;\n }\n let view;\n if (byteLength === undefined) {\n if (data instanceof Array) {\n view = new Float32Array(data);\n }\n else if (data instanceof ArrayBuffer) {\n view = new Uint8Array(data);\n }\n else {\n view = data;\n }\n byteLength = view.byteLength;\n }\n else {\n if (data instanceof Array) {\n view = new Float32Array(data);\n }\n else if (data instanceof ArrayBuffer) {\n view = new Uint8Array(data);\n }\n else {\n view = data;\n }\n }\n this._bufferManager.setSubData(dataBuffer, byteOffset, view, 0, byteLength);\n};\n//# sourceMappingURL=engine.dynamicBuffer.js.map","import { WebGPUEngine } from \"../../webgpuEngine.js\";\nWebGPUEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha = false, format, forceBindTexture, allowGPUOptimization) {\n var _a;\n if (!texture) {\n return;\n }\n const width = canvas.width, height = canvas.height;\n let gpuTextureWrapper = texture._hardwareTexture;\n if (!((_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource)) {\n gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, width, height);\n }\n this._textureHelper.updateTexture(canvas, texture, width, height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, premulAlpha, 0, 0, allowGPUOptimization);\n if (texture.generateMipMaps) {\n this._generateMipmaps(texture, this._uploadEncoder);\n }\n texture.isReady = true;\n};\n//# sourceMappingURL=engine.dynamicTexture.js.map","import { WebGPUEngine } from \"../../webgpuEngine.js\";\nimport { WebGPUExternalTexture } from \"../webgpuExternalTexture.js\";\nimport { Effect } from \"../../../Materials/effect.js\";\nEffect.prototype.setExternalTexture = function (name, texture) {\n this._engine.setExternalTexture(name, texture);\n};\nWebGPUEngine.prototype.createExternalTexture = function (video) {\n const texture = new WebGPUExternalTexture(video);\n return texture;\n};\nWebGPUEngine.prototype.setExternalTexture = function (name, texture) {\n if (!texture) {\n this._currentMaterialContext.setTexture(name, null);\n return;\n }\n this._setInternalTexture(name, texture);\n};\n//# sourceMappingURL=engine.externalTexture.js.map","import { ExternalTexture } from \"../../Materials/Textures/externalTexture.js\";\n/**\n * Nothing specific to WebGPU in this class, but the spec is not final yet so let's remove it later on\n * if it is not needed\n * @internal\n **/\nexport class WebGPUExternalTexture extends ExternalTexture {\n constructor(video) {\n super(video);\n }\n}\n//# sourceMappingURL=webgpuExternalTexture.js.map","import { InternalTexture, InternalTextureSource } from \"../../../Materials/Textures/internalTexture.js\";\nimport { Logger } from \"../../../Misc/logger.js\";\n\nimport { WebGPUEngine } from \"../../webgpuEngine.js\";\nWebGPUEngine.prototype.unBindMultiColorAttachmentFramebuffer = function (rtWrapper, disableGenerateMipMaps = false, onBeforeUnbind) {\n if (onBeforeUnbind) {\n onBeforeUnbind();\n }\n const attachments = rtWrapper._attachments;\n const count = attachments.length;\n if (this._currentRenderPass && this._currentRenderPass !== this._mainRenderPassWrapper.renderPass) {\n this._endRenderTargetRenderPass();\n }\n for (let i = 0; i < count; i++) {\n const texture = rtWrapper.textures[i];\n if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {\n this._generateMipmaps(texture);\n }\n }\n this._currentRenderTarget = null;\n this._mrtAttachments = [];\n this._cacheRenderPipeline.setMRT([]);\n this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments);\n this._currentRenderPass = this._mainRenderPassWrapper.renderPass;\n this._setDepthTextureFormat(this._mainRenderPassWrapper);\n this._setColorFormat(this._mainRenderPassWrapper);\n};\nWebGPUEngine.prototype.createMultipleRenderTarget = function (size, options, initializeBuffers) {\n var _a, _b;\n let generateMipMaps = false;\n let generateDepthBuffer = true;\n let generateStencilBuffer = false;\n let generateDepthTexture = false;\n let depthTextureFormat = 15;\n let textureCount = 1;\n const defaultType = 0;\n const defaultSamplingMode = 3;\n const defaultUseSRGBBuffer = false;\n const defaultFormat = 5;\n const defaultTarget = 3553;\n let types = new Array();\n let samplingModes = new Array();\n let useSRGBBuffers = new Array();\n let formats = new Array();\n let targets = new Array();\n let faceIndex = new Array();\n let layerIndex = new Array();\n let layers = new Array();\n const rtWrapper = this._createHardwareRenderTargetWrapper(true, false, size);\n if (options !== undefined) {\n generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;\n generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;\n generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;\n generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;\n textureCount = options.textureCount || 1;\n depthTextureFormat = (_a = options.depthTextureFormat) !== null && _a !== void 0 ? _a : 15;\n if (options.types) {\n types = options.types;\n }\n if (options.samplingModes) {\n samplingModes = options.samplingModes;\n }\n if (options.useSRGBBuffers) {\n useSRGBBuffers = options.useSRGBBuffers;\n }\n if (options.formats) {\n formats = options.formats;\n }\n if (options.targetTypes) {\n targets = options.targetTypes;\n }\n if (options.faceIndex) {\n faceIndex = options.faceIndex;\n }\n if (options.layerIndex) {\n layerIndex = options.layerIndex;\n }\n if (options.layerCounts) {\n layers = options.layerCounts;\n }\n }\n const width = size.width || size;\n const height = size.height || size;\n let depthStencilTexture = null;\n if (generateDepthBuffer || generateStencilBuffer || generateDepthTexture) {\n if (!generateDepthTexture) {\n // The caller doesn't want a depth texture, so we are free to use the depth texture format we want.\n // So, we will align with what the WebGL engine does\n if (generateDepthBuffer && generateStencilBuffer) {\n depthTextureFormat = 13;\n }\n else if (generateDepthBuffer) {\n depthTextureFormat = 14;\n }\n else {\n depthTextureFormat = 19;\n }\n }\n depthStencilTexture = rtWrapper.createDepthStencilTexture(0, false, generateStencilBuffer, 1, depthTextureFormat);\n }\n const textures = [];\n const attachments = [];\n const defaultAttachments = [];\n rtWrapper._generateDepthBuffer = generateDepthBuffer;\n rtWrapper._generateStencilBuffer = generateStencilBuffer;\n rtWrapper._attachments = attachments;\n rtWrapper._defaultAttachments = defaultAttachments;\n for (let i = 0; i < textureCount; i++) {\n let samplingMode = samplingModes[i] || defaultSamplingMode;\n let type = types[i] || defaultType;\n const format = formats[i] || defaultFormat;\n const useSRGBBuffer = (useSRGBBuffers[i] || defaultUseSRGBBuffer) && this._caps.supportSRGBBuffers;\n const target = targets[i] || defaultTarget;\n const layerCount = (_b = layers[i]) !== null && _b !== void 0 ? _b : 1;\n if (type === 1 && !this._caps.textureFloatLinearFiltering) {\n // if floating point linear (FLOAT) then force to NEAREST_SAMPLINGMODE\n samplingMode = 1;\n }\n else if (type === 2 && !this._caps.textureHalfFloatLinearFiltering) {\n // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE\n samplingMode = 1;\n }\n if (type === 1 && !this._caps.textureFloat) {\n type = 0;\n Logger.Warn(\"Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type\");\n }\n attachments.push(i + 1);\n defaultAttachments.push(initializeBuffers ? i + 1 : i === 0 ? 1 : 0);\n if (target === -1) {\n continue;\n }\n const texture = new InternalTexture(this, InternalTextureSource.MultiRenderTarget);\n textures[i] = texture;\n switch (target) {\n case 34067:\n texture.isCube = true;\n break;\n case 32879:\n texture.is3D = true;\n texture.baseDepth = texture.depth = layerCount;\n break;\n case 35866:\n texture.is2DArray = true;\n texture.baseDepth = texture.depth = layerCount;\n break;\n }\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = width;\n texture.height = height;\n texture.isReady = true;\n texture.samples = 1;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.type = type;\n texture._cachedWrapU = 0;\n texture._cachedWrapV = 0;\n texture._useSRGBBuffer = useSRGBBuffer;\n texture.format = format;\n this._internalTexturesCache.push(texture);\n this._textureHelper.createGPUTextureForInternalTexture(texture);\n }\n if (depthStencilTexture) {\n depthStencilTexture.incrementReferences();\n textures[textureCount] = depthStencilTexture;\n this._internalTexturesCache.push(depthStencilTexture);\n }\n rtWrapper.setTextures(textures);\n rtWrapper.setLayerAndFaceIndices(layerIndex, faceIndex);\n return rtWrapper;\n};\nWebGPUEngine.prototype.updateMultipleRenderTargetTextureSampleCount = function (rtWrapper, samples) {\n if (!rtWrapper || !rtWrapper.textures || rtWrapper.textures[0].samples === samples) {\n return samples;\n }\n const count = rtWrapper.textures.length;\n if (count === 0) {\n return 1;\n }\n samples = Math.min(samples, this.getCaps().maxMSAASamples);\n for (let i = 0; i < count; ++i) {\n const texture = rtWrapper.textures[i];\n const gpuTextureWrapper = texture._hardwareTexture;\n gpuTextureWrapper === null || gpuTextureWrapper === void 0 ? void 0 : gpuTextureWrapper.releaseMSAATexture();\n }\n // Note that rtWrapper.textures can't have null textures, lastTextureIsDepthTexture can't be true if rtWrapper._depthStencilTexture is null\n const lastTextureIsDepthTexture = rtWrapper._depthStencilTexture === rtWrapper.textures[count - 1];\n for (let i = 0; i < count; ++i) {\n const texture = rtWrapper.textures[i];\n this._textureHelper.createMSAATexture(texture, samples, false, i === count - 1 && lastTextureIsDepthTexture ? 0 : i);\n texture.samples = samples;\n }\n // Note that the last texture of textures is the depth texture if the depth texture has been generated by the MRT class and so the MSAA texture\n // will be recreated for this texture by the loop above: in that case, there's no need to create the MSAA texture for rtWrapper._depthStencilTexture\n // because rtWrapper._depthStencilTexture is the same texture than the depth texture\n if (rtWrapper._depthStencilTexture && !lastTextureIsDepthTexture) {\n this._textureHelper.createMSAATexture(rtWrapper._depthStencilTexture, samples);\n rtWrapper._depthStencilTexture.samples = samples;\n }\n return samples;\n};\nWebGPUEngine.prototype.bindAttachments = function (attachments) {\n if (attachments.length === 0 || !this._currentRenderTarget) {\n return;\n }\n this._mrtAttachments = attachments;\n if (this._currentRenderPass) {\n // the render pass has already been created, we need to call setMRTAttachments to update the state of the attachments\n this._cacheRenderPipeline.setMRTAttachments(attachments);\n }\n else {\n // the render pass is not created yet so we don't need to call setMRTAttachments: it will be called as part of the render pass creation (see WebGPUEngine._startRenderTargetRenderPass)\n }\n};\nWebGPUEngine.prototype.buildTextureLayout = function (textureStatus) {\n const result = [];\n for (let i = 0; i < textureStatus.length; i++) {\n if (textureStatus[i]) {\n result.push(i + 1);\n }\n else {\n result.push(0);\n }\n }\n return result;\n};\nWebGPUEngine.prototype.restoreSingleAttachment = function () {\n // not sure what to do, probably nothing... This function and restoreSingleAttachmentForRenderTarget are not called in Babylon.js so it's hard to know the use case\n};\nWebGPUEngine.prototype.restoreSingleAttachmentForRenderTarget = function () {\n // not sure what to do, probably nothing... This function and restoreSingleAttachment are not called in Babylon.js so it's hard to know the use case\n};\n//# sourceMappingURL=engine.multiRender.js.map","import { WebGPUEngine } from \"../../webgpuEngine.js\";\nimport { WebGPURenderItemBeginOcclusionQuery, WebGPURenderItemEndOcclusionQuery } from \"../webgpuBundleList.js\";\nWebGPUEngine.prototype.getGPUFrameTimeCounter = function () {\n return this._timestampQuery.gpuFrameTimeCounter;\n};\nWebGPUEngine.prototype.captureGPUFrameTime = function (value) {\n this._timestampQuery.enable = value && !!this._caps.timerQuery;\n};\nWebGPUEngine.prototype.createQuery = function () {\n return this._occlusionQuery.createQuery();\n};\nWebGPUEngine.prototype.deleteQuery = function (query) {\n this._occlusionQuery.deleteQuery(query);\n return this;\n};\nWebGPUEngine.prototype.isQueryResultAvailable = function (query) {\n return this._occlusionQuery.isQueryResultAvailable(query);\n};\nWebGPUEngine.prototype.getQueryResult = function (query) {\n return this._occlusionQuery.getQueryResult(query);\n};\nWebGPUEngine.prototype.beginOcclusionQuery = function (algorithmType, query) {\n var _a;\n if (this.compatibilityMode) {\n if (this._occlusionQuery.canBeginQuery) {\n (_a = this._currentRenderPass) === null || _a === void 0 ? void 0 : _a.beginOcclusionQuery(query);\n return true;\n }\n }\n else {\n const renderPassIndex = this._getCurrentRenderPassIndex();\n const bundleList = renderPassIndex === 0 ? this._bundleList : this._bundleListRenderTarget;\n bundleList.addItem(new WebGPURenderItemBeginOcclusionQuery(query));\n return true;\n }\n return false;\n};\nWebGPUEngine.prototype.endOcclusionQuery = function () {\n var _a;\n if (this.compatibilityMode) {\n (_a = this._currentRenderPass) === null || _a === void 0 ? void 0 : _a.endOcclusionQuery();\n }\n else {\n const renderPassIndex = this._getCurrentRenderPassIndex();\n const bundleList = renderPassIndex === 0 ? this._bundleList : this._bundleListRenderTarget;\n bundleList.addItem(new WebGPURenderItemEndOcclusionQuery());\n }\n return this;\n};\n//# sourceMappingURL=engine.query.js.map","import { InternalTexture, InternalTextureSource } from \"../../../Materials/Textures/internalTexture.js\";\n\nimport { WebGPUEngine } from \"../../webgpuEngine.js\";\nimport { Logger } from \"../../../Misc/logger.js\";\nWebGPUEngine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression = null, type = 0, creationFlags = 0, useSRGBBuffer = false) {\n const texture = new InternalTexture(this, InternalTextureSource.Raw);\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = width;\n texture.height = height;\n texture.format = format;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.invertY = invertY;\n texture._compression = compression;\n texture.type = type;\n texture._useSRGBBuffer = useSRGBBuffer;\n if (!this._doNotHandleContextLost) {\n texture._bufferView = data;\n }\n this._textureHelper.createGPUTextureForInternalTexture(texture, width, height, undefined, creationFlags);\n this.updateRawTexture(texture, data, format, invertY, compression, type, useSRGBBuffer);\n this._internalTexturesCache.push(texture);\n return texture;\n};\nWebGPUEngine.prototype.updateRawTexture = function (texture, bufferView, format, invertY, compression = null, type = 0, useSRGBBuffer = false) {\n if (!texture) {\n return;\n }\n if (!this._doNotHandleContextLost) {\n texture._bufferView = bufferView;\n texture.invertY = invertY;\n texture._compression = compression;\n texture._useSRGBBuffer = useSRGBBuffer;\n }\n if (bufferView) {\n const gpuTextureWrapper = texture._hardwareTexture;\n const needConversion = format === 4;\n if (needConversion) {\n bufferView = _convertRGBtoRGBATextureData(bufferView, texture.width, texture.height, type);\n }\n const data = new Uint8Array(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength);\n this._textureHelper.updateTexture(data, texture, texture.width, texture.height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, false, 0, 0);\n if (texture.generateMipMaps) {\n this._generateMipmaps(texture, this._uploadEncoder);\n }\n }\n texture.isReady = true;\n};\nWebGPUEngine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression = null) {\n const texture = new InternalTexture(this, InternalTextureSource.CubeRaw);\n if (type === 1 && !this._caps.textureFloatLinearFiltering) {\n generateMipMaps = false;\n samplingMode = 1;\n Logger.Warn(\"Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.\");\n }\n else if (type === 2 && !this._caps.textureHalfFloatLinearFiltering) {\n generateMipMaps = false;\n samplingMode = 1;\n Logger.Warn(\"Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.\");\n }\n else if (type === 1 && !this._caps.textureFloatRender) {\n generateMipMaps = false;\n Logger.Warn(\"Render to float textures is not supported. Mipmap generation forced to false.\");\n }\n else if (type === 2 && !this._caps.colorBufferFloat) {\n generateMipMaps = false;\n Logger.Warn(\"Render to half float textures is not supported. Mipmap generation forced to false.\");\n }\n texture.isCube = true;\n texture.format = format === 4 ? 5 : format;\n texture.type = type;\n texture.generateMipMaps = generateMipMaps;\n texture.width = size;\n texture.height = size;\n texture.samplingMode = samplingMode;\n if (!this._doNotHandleContextLost) {\n texture._bufferViewArray = data;\n }\n texture.invertY = invertY;\n texture._compression = compression;\n texture._cachedWrapU = 0;\n texture._cachedWrapV = 0;\n this._textureHelper.createGPUTextureForInternalTexture(texture);\n if (data) {\n this.updateRawCubeTexture(texture, data, format, type, invertY, compression);\n }\n texture.isReady = true;\n return texture;\n};\nWebGPUEngine.prototype.updateRawCubeTexture = function (texture, bufferView, format, type, invertY, compression = null) {\n texture._bufferViewArray = bufferView;\n texture.invertY = invertY;\n texture._compression = compression;\n const gpuTextureWrapper = texture._hardwareTexture;\n const needConversion = format === 4;\n const data = [];\n for (let i = 0; i < bufferView.length; ++i) {\n let faceData = bufferView[i];\n if (needConversion) {\n faceData = _convertRGBtoRGBATextureData(bufferView[i], texture.width, texture.height, type);\n }\n data.push(new Uint8Array(faceData.buffer, faceData.byteOffset, faceData.byteLength));\n }\n this._textureHelper.updateCubeTextures(data, gpuTextureWrapper.underlyingResource, texture.width, texture.height, gpuTextureWrapper.format, invertY, false, 0, 0);\n if (texture.generateMipMaps) {\n this._generateMipmaps(texture, this._uploadEncoder);\n }\n texture.isReady = true;\n};\nWebGPUEngine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad = null, onError = null, samplingMode = 3, invertY = false) {\n const texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode, null);\n scene === null || scene === void 0 ? void 0 : scene.addPendingData(texture);\n texture.url = url;\n this._internalTexturesCache.push(texture);\n const onerror = (request, exception) => {\n scene === null || scene === void 0 ? void 0 : scene.removePendingData(texture);\n if (onError && request) {\n onError(request.status + \" \" + request.statusText, exception);\n }\n };\n const internalCallback = (data) => {\n const width = texture.width;\n const faceDataArrays = callback(data);\n if (!faceDataArrays) {\n return;\n }\n const faces = [0, 2, 4, 1, 3, 5];\n if (mipmapGenerator) {\n const needConversion = format === 4;\n const mipData = mipmapGenerator(faceDataArrays);\n const gpuTextureWrapper = texture._hardwareTexture;\n const faces = [0, 1, 2, 3, 4, 5];\n for (let level = 0; level < mipData.length; level++) {\n const mipSize = width >> level;\n const allFaces = [];\n for (let faceIndex = 0; faceIndex < 6; faceIndex++) {\n let mipFaceData = mipData[level][faces[faceIndex]];\n if (needConversion) {\n mipFaceData = _convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);\n }\n allFaces.push(new Uint8Array(mipFaceData.buffer, mipFaceData.byteOffset, mipFaceData.byteLength));\n }\n this._textureHelper.updateCubeTextures(allFaces, gpuTextureWrapper.underlyingResource, mipSize, mipSize, gpuTextureWrapper.format, invertY, false, 0, 0);\n }\n }\n else {\n const allFaces = [];\n for (let faceIndex = 0; faceIndex < 6; faceIndex++) {\n allFaces.push(faceDataArrays[faces[faceIndex]]);\n }\n this.updateRawCubeTexture(texture, allFaces, format, type, invertY);\n }\n texture.isReady = true;\n scene === null || scene === void 0 ? void 0 : scene.removePendingData(texture);\n if (onLoad) {\n onLoad();\n }\n };\n this._loadFile(url, (data) => {\n internalCallback(data);\n }, undefined, scene === null || scene === void 0 ? void 0 : scene.offlineProvider, true, onerror);\n return texture;\n};\nWebGPUEngine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression = null, textureType = 0, creationFlags = 0) {\n const source = InternalTextureSource.Raw3D;\n const texture = new InternalTexture(this, source);\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.baseDepth = depth;\n texture.width = width;\n texture.height = height;\n texture.depth = depth;\n texture.format = format;\n texture.type = textureType;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.is3D = true;\n if (!this._doNotHandleContextLost) {\n texture._bufferView = data;\n }\n this._textureHelper.createGPUTextureForInternalTexture(texture, width, height, undefined, creationFlags);\n this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);\n this._internalTexturesCache.push(texture);\n return texture;\n};\nWebGPUEngine.prototype.updateRawTexture3D = function (texture, bufferView, format, invertY, compression = null, textureType = 0) {\n if (!this._doNotHandleContextLost) {\n texture._bufferView = bufferView;\n texture.format = format;\n texture.invertY = invertY;\n texture._compression = compression;\n }\n if (bufferView) {\n const gpuTextureWrapper = texture._hardwareTexture;\n const needConversion = format === 4;\n if (needConversion) {\n bufferView = _convertRGBtoRGBATextureData(bufferView, texture.width, texture.height, textureType);\n }\n const data = new Uint8Array(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength);\n this._textureHelper.updateTexture(data, texture, texture.width, texture.height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, false, 0, 0);\n if (texture.generateMipMaps) {\n this._generateMipmaps(texture, this._uploadEncoder);\n }\n }\n texture.isReady = true;\n};\nWebGPUEngine.prototype.createRawTexture2DArray = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression = null, textureType = 0, creationFlags = 0) {\n const source = InternalTextureSource.Raw2DArray;\n const texture = new InternalTexture(this, source);\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.baseDepth = depth;\n texture.width = width;\n texture.height = height;\n texture.depth = depth;\n texture.format = format;\n texture.type = textureType;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.is2DArray = true;\n if (!this._doNotHandleContextLost) {\n texture._bufferView = data;\n }\n this._textureHelper.createGPUTextureForInternalTexture(texture, width, height, depth, creationFlags);\n this.updateRawTexture2DArray(texture, data, format, invertY, compression, textureType);\n this._internalTexturesCache.push(texture);\n return texture;\n};\nWebGPUEngine.prototype.updateRawTexture2DArray = function (texture, bufferView, format, invertY, compression = null, textureType = 0) {\n if (!this._doNotHandleContextLost) {\n texture._bufferView = bufferView;\n texture.format = format;\n texture.invertY = invertY;\n texture._compression = compression;\n }\n if (bufferView) {\n const gpuTextureWrapper = texture._hardwareTexture;\n const needConversion = format === 4;\n if (needConversion) {\n bufferView = _convertRGBtoRGBATextureData(bufferView, texture.width, texture.height, textureType);\n }\n const data = new Uint8Array(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength);\n this._textureHelper.updateTexture(data, texture, texture.width, texture.height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, false, 0, 0);\n if (texture.generateMipMaps) {\n this._generateMipmaps(texture, this._uploadEncoder);\n }\n }\n texture.isReady = true;\n};\n/**\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nfunction _convertRGBtoRGBATextureData(rgbData, width, height, textureType) {\n // Create new RGBA data container.\n let rgbaData;\n let val1 = 1;\n if (textureType === 1) {\n rgbaData = new Float32Array(width * height * 4);\n }\n else if (textureType === 2) {\n rgbaData = new Uint16Array(width * height * 4);\n val1 = 15360; // 15360 is the encoding of 1 in half float\n }\n else if (textureType === 7) {\n rgbaData = new Uint32Array(width * height * 4);\n }\n else {\n rgbaData = new Uint8Array(width * height * 4);\n }\n // Convert each pixel.\n for (let x = 0; x < width; x++) {\n for (let y = 0; y < height; y++) {\n const index = (y * width + x) * 3;\n const newIndex = (y * width + x) * 4;\n // Map Old Value to new value.\n rgbaData[newIndex + 0] = rgbData[index + 0];\n rgbaData[newIndex + 1] = rgbData[index + 1];\n rgbaData[newIndex + 2] = rgbData[index + 2];\n // Add fully opaque alpha channel.\n rgbaData[newIndex + 3] = val1;\n }\n }\n return rgbaData;\n}\n//# sourceMappingURL=engine.rawTexture.js.map","import { RenderTargetWrapper } from \"../renderTargetWrapper.js\";\n/** @internal */\nexport class WebGPURenderTargetWrapper extends RenderTargetWrapper {\n}\n//# sourceMappingURL=webgpuRenderTargetWrapper.js.map","import { WebGPUEngine } from \"../../webgpuEngine.js\";\nWebGPUEngine.prototype._readTexturePixels = function (texture, width, height, faceIndex = -1, level = 0, buffer = null, flushRenderer = true, noDataConversion = false, x = 0, y = 0) {\n const gpuTextureWrapper = texture._hardwareTexture;\n if (flushRenderer) {\n this.flushFramebuffer();\n }\n return this._textureHelper.readPixels(gpuTextureWrapper.underlyingResource, x, y, width, height, gpuTextureWrapper.format, faceIndex, level, buffer, noDataConversion);\n};\nWebGPUEngine.prototype._readTexturePixelsSync = function () {\n throw \"_readTexturePixelsSync is unsupported in WebGPU!\";\n};\n//# sourceMappingURL=engine.readTexture.js.map","import { InternalTexture, InternalTextureSource } from \"../../../Materials/Textures/internalTexture.js\";\n\nimport { WebGPUEngine } from \"../../webgpuEngine.js\";\nimport { WebGPURenderTargetWrapper } from \"../webgpuRenderTargetWrapper.js\";\nWebGPUEngine.prototype._createHardwareRenderTargetWrapper = function (isMulti, isCube, size) {\n const rtWrapper = new WebGPURenderTargetWrapper(isMulti, isCube, size, this);\n this._renderTargetWrapperCache.push(rtWrapper);\n return rtWrapper;\n};\nWebGPUEngine.prototype.createRenderTargetTexture = function (size, options) {\n var _a, _b;\n const rtWrapper = this._createHardwareRenderTargetWrapper(false, false, size);\n const fullOptions = {};\n if (options !== undefined && typeof options === \"object\") {\n fullOptions.generateMipMaps = options.generateMipMaps;\n fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;\n fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;\n fullOptions.samplingMode = options.samplingMode === undefined ? 3 : options.samplingMode;\n fullOptions.creationFlags = (_a = options.creationFlags) !== null && _a !== void 0 ? _a : 0;\n fullOptions.noColorAttachment = !!options.noColorAttachment;\n fullOptions.samples = options.samples;\n fullOptions.label = options.label;\n }\n else {\n fullOptions.generateMipMaps = options;\n fullOptions.generateDepthBuffer = true;\n fullOptions.generateStencilBuffer = false;\n fullOptions.samplingMode = 3;\n fullOptions.creationFlags = 0;\n fullOptions.noColorAttachment = false;\n }\n const texture = fullOptions.noColorAttachment ? null : this._createInternalTexture(size, options, true, InternalTextureSource.RenderTarget);\n rtWrapper._samples = (_b = fullOptions.samples) !== null && _b !== void 0 ? _b : 1;\n rtWrapper._generateDepthBuffer = fullOptions.generateDepthBuffer;\n rtWrapper._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;\n rtWrapper.setTextures(texture);\n if (rtWrapper._generateDepthBuffer || rtWrapper._generateStencilBuffer) {\n rtWrapper.createDepthStencilTexture(0, this._caps.textureFloatLinearFiltering &&\n (fullOptions.samplingMode === undefined ||\n fullOptions.samplingMode === 2 ||\n fullOptions.samplingMode === 2 ||\n fullOptions.samplingMode === 3 ||\n fullOptions.samplingMode === 3 ||\n fullOptions.samplingMode === 5 ||\n fullOptions.samplingMode === 6 ||\n fullOptions.samplingMode === 7 ||\n fullOptions.samplingMode === 11), rtWrapper._generateStencilBuffer, rtWrapper.samples, fullOptions.generateStencilBuffer ? 13 : 14, fullOptions.label ? fullOptions.label + \"-DepthStencil\" : undefined);\n }\n if (texture) {\n if (options !== undefined && typeof options === \"object\" && options.createMipMaps && !fullOptions.generateMipMaps) {\n texture.generateMipMaps = true;\n }\n this._textureHelper.createGPUTextureForInternalTexture(texture, undefined, undefined, undefined, fullOptions.creationFlags);\n if (options !== undefined && typeof options === \"object\" && options.createMipMaps && !fullOptions.generateMipMaps) {\n texture.generateMipMaps = false;\n }\n }\n return rtWrapper;\n};\nWebGPUEngine.prototype._createDepthStencilTexture = function (size, options) {\n const internalTexture = new InternalTexture(this, InternalTextureSource.DepthStencil);\n internalTexture.label = options.label;\n const internalOptions = Object.assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false, samples: 1, depthTextureFormat: options.generateStencil ? 13 : 14 }, options);\n internalTexture.format = internalOptions.depthTextureFormat;\n this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction, internalOptions.samples);\n this._textureHelper.createGPUTextureForInternalTexture(internalTexture);\n this._internalTexturesCache.push(internalTexture);\n return internalTexture;\n};\nWebGPUEngine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction, samples = 1) {\n const width = size.width || size;\n const height = size.height || size;\n const layers = size.layers || 0;\n internalTexture.baseWidth = width;\n internalTexture.baseHeight = height;\n internalTexture.width = width;\n internalTexture.height = height;\n internalTexture.is2DArray = layers > 0;\n internalTexture.depth = layers;\n internalTexture.isReady = true;\n internalTexture.samples = samples;\n internalTexture.generateMipMaps = false;\n internalTexture.samplingMode = bilinearFiltering ? 2 : 1;\n internalTexture.type = 1;\n internalTexture._comparisonFunction = comparisonFunction;\n internalTexture._cachedWrapU = 0;\n internalTexture._cachedWrapV = 0;\n};\nWebGPUEngine.prototype.updateRenderTargetTextureSampleCount = function (rtWrapper, samples) {\n if (!rtWrapper || !rtWrapper.texture || rtWrapper.samples === samples) {\n return samples;\n }\n samples = Math.min(samples, this.getCaps().maxMSAASamples);\n this._textureHelper.createMSAATexture(rtWrapper.texture, samples);\n if (rtWrapper._depthStencilTexture) {\n this._textureHelper.createMSAATexture(rtWrapper._depthStencilTexture, samples);\n rtWrapper._depthStencilTexture.samples = samples;\n }\n rtWrapper._samples = samples;\n rtWrapper.texture.samples = samples;\n return samples;\n};\n//# sourceMappingURL=engine.renderTarget.js.map","import { InternalTexture, InternalTextureSource } from \"../../../Materials/Textures/internalTexture.js\";\n\nimport { WebGPUEngine } from \"../../webgpuEngine.js\";\nWebGPUEngine.prototype.createRenderTargetCubeTexture = function (size, options) {\n const rtWrapper = this._createHardwareRenderTargetWrapper(false, true, size);\n const fullOptions = Object.assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: 0, samplingMode: 3, format: 5, samples: 1 }, options);\n fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;\n rtWrapper._generateDepthBuffer = fullOptions.generateDepthBuffer;\n rtWrapper._generateStencilBuffer = fullOptions.generateStencilBuffer;\n const texture = new InternalTexture(this, InternalTextureSource.RenderTarget);\n texture.width = size;\n texture.height = size;\n texture.depth = 0;\n texture.isReady = true;\n texture.isCube = true;\n texture.samples = fullOptions.samples;\n texture.generateMipMaps = fullOptions.generateMipMaps;\n texture.samplingMode = fullOptions.samplingMode;\n texture.type = fullOptions.type;\n texture.format = fullOptions.format;\n this._internalTexturesCache.push(texture);\n rtWrapper.setTextures(texture);\n if (rtWrapper._generateDepthBuffer || rtWrapper._generateStencilBuffer) {\n rtWrapper.createDepthStencilTexture(0, fullOptions.samplingMode === undefined ||\n fullOptions.samplingMode === 2 ||\n fullOptions.samplingMode === 2 ||\n fullOptions.samplingMode === 3 ||\n fullOptions.samplingMode === 3 ||\n fullOptions.samplingMode === 5 ||\n fullOptions.samplingMode === 6 ||\n fullOptions.samplingMode === 7 ||\n fullOptions.samplingMode === 11, rtWrapper._generateStencilBuffer, rtWrapper.samples);\n }\n if (options && options.createMipMaps && !fullOptions.generateMipMaps) {\n texture.generateMipMaps = true;\n }\n this._textureHelper.createGPUTextureForInternalTexture(texture);\n if (options && options.createMipMaps && !fullOptions.generateMipMaps) {\n texture.generateMipMaps = false;\n }\n return rtWrapper;\n};\n//# sourceMappingURL=engine.renderTargetCube.js.map","import { WebGPUEngine } from \"../../webgpuEngine.js\";\nimport { Effect } from \"../../../Materials/effect.js\";\nEffect.prototype.setTextureSampler = function (name, sampler) {\n this._engine.setTextureSampler(name, sampler);\n};\nWebGPUEngine.prototype.setTextureSampler = function (name, sampler) {\n var _a;\n (_a = this._currentMaterialContext) === null || _a === void 0 ? void 0 : _a.setSampler(name, sampler);\n};\n//# sourceMappingURL=engine.textureSampler.js.map","\nimport { WebGPUEngine } from \"../../webgpuEngine.js\";\nimport * as WebGPUConstants from \"../webgpuConstants.js\";\nimport { Effect } from \"../../../Materials/effect.js\";\nEffect.prototype.setStorageBuffer = function (name, buffer) {\n this._engine.setStorageBuffer(name, buffer);\n};\nWebGPUEngine.prototype.createStorageBuffer = function (data, creationFlags) {\n return this._createBuffer(data, creationFlags | 32);\n};\nWebGPUEngine.prototype.updateStorageBuffer = function (buffer, data, byteOffset, byteLength) {\n const dataBuffer = buffer;\n if (byteOffset === undefined) {\n byteOffset = 0;\n }\n let view;\n if (byteLength === undefined) {\n if (data instanceof Array) {\n view = new Float32Array(data);\n }\n else if (data instanceof ArrayBuffer) {\n view = new Uint8Array(data);\n }\n else {\n view = data;\n }\n byteLength = view.byteLength;\n }\n else {\n if (data instanceof Array) {\n view = new Float32Array(data);\n }\n else if (data instanceof ArrayBuffer) {\n view = new Uint8Array(data);\n }\n else {\n view = data;\n }\n }\n this._bufferManager.setSubData(dataBuffer, byteOffset, view, 0, byteLength);\n};\nWebGPUEngine.prototype.readFromStorageBuffer = function (storageBuffer, offset, size, buffer) {\n size = size || storageBuffer.capacity;\n const gpuBuffer = this._bufferManager.createRawBuffer(size, WebGPUConstants.BufferUsage.MapRead | WebGPUConstants.BufferUsage.CopyDst);\n this._renderTargetEncoder.copyBufferToBuffer(storageBuffer.underlyingResource, offset !== null && offset !== void 0 ? offset : 0, gpuBuffer, 0, size);\n return new Promise((resolve, reject) => {\n // we are using onEndFrameObservable because we need to map the gpuBuffer AFTER the command buffers\n // have been submitted, else we get the error: \"Buffer used in a submit while mapped\"\n this.onEndFrameObservable.addOnce(() => {\n gpuBuffer.mapAsync(WebGPUConstants.MapMode.Read, 0, size).then(() => {\n const copyArrayBuffer = gpuBuffer.getMappedRange(0, size);\n let data = buffer;\n if (data === undefined) {\n data = new Uint8Array(size);\n data.set(new Uint8Array(copyArrayBuffer));\n }\n else {\n const ctor = data.constructor; // we want to create result data with the same type as buffer (Uint8Array, Float32Array, ...)\n data = new ctor(data.buffer);\n data.set(new ctor(copyArrayBuffer));\n }\n gpuBuffer.unmap();\n this._bufferManager.releaseBuffer(gpuBuffer);\n resolve(data);\n }, (reason) => reject(reason));\n });\n });\n};\nWebGPUEngine.prototype.setStorageBuffer = function (name, buffer) {\n var _a, _b;\n (_a = this._currentDrawContext) === null || _a === void 0 ? void 0 : _a.setBuffer(name, (_b = buffer === null || buffer === void 0 ? void 0 : buffer.getBuffer()) !== null && _b !== void 0 ? _b : null);\n};\n//# sourceMappingURL=engine.storageBuffer.js.map","import { WebGPUEngine } from \"../../webgpuEngine.js\";\nimport * as WebGPUConstants from \"../webgpuConstants.js\";\nWebGPUEngine.prototype.createUniformBuffer = function (elements) {\n let view;\n if (elements instanceof Array) {\n view = new Float32Array(elements);\n }\n else {\n view = elements;\n }\n const dataBuffer = this._bufferManager.createBuffer(view, WebGPUConstants.BufferUsage.Uniform | WebGPUConstants.BufferUsage.CopyDst);\n return dataBuffer;\n};\nWebGPUEngine.prototype.createDynamicUniformBuffer = function (elements) {\n return this.createUniformBuffer(elements);\n};\nWebGPUEngine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {\n if (offset === undefined) {\n offset = 0;\n }\n const dataBuffer = uniformBuffer;\n let view;\n if (count === undefined) {\n if (elements instanceof Float32Array) {\n view = elements;\n }\n else {\n view = new Float32Array(elements);\n }\n count = view.byteLength;\n }\n else {\n if (elements instanceof Float32Array) {\n view = elements;\n }\n else {\n view = new Float32Array(elements);\n }\n }\n this._bufferManager.setSubData(dataBuffer, offset, view, 0, count);\n};\nWebGPUEngine.prototype.bindUniformBufferBase = function (buffer, location, name) {\n this._currentDrawContext.setBuffer(name, buffer);\n};\nWebGPUEngine.prototype.bindUniformBlock = function () { };\n//# sourceMappingURL=engine.uniformBuffer.js.map","import { WebGPUEngine } from \"../../webgpuEngine.js\";\nfunction IsExternalTexture(texture) {\n return texture && texture.underlyingResource !== undefined ? true : false;\n}\nWebGPUEngine.prototype.updateVideoTexture = function (texture, video, invertY) {\n var _a;\n if (!texture || texture._isDisabled) {\n return;\n }\n if (this._videoTextureSupported === undefined) {\n this._videoTextureSupported = true;\n }\n let gpuTextureWrapper = texture._hardwareTexture;\n if (!((_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource)) {\n gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture);\n }\n if (IsExternalTexture(video)) {\n this._textureHelper.copyVideoToTexture(video, texture, gpuTextureWrapper.format, !invertY);\n if (texture.generateMipMaps) {\n this._generateMipmaps(texture, this._uploadEncoder);\n }\n texture.isReady = true;\n }\n else if (video) {\n this.createImageBitmap(video)\n .then((bitmap) => {\n this._textureHelper.updateTexture(bitmap, texture, texture.width, texture.height, texture.depth, gpuTextureWrapper.format, 0, 0, !invertY, false, 0, 0);\n if (texture.generateMipMaps) {\n this._generateMipmaps(texture, this._uploadEncoder);\n }\n texture.isReady = true;\n })\n .catch(() => {\n // Sometimes createImageBitmap(video) fails with \"Failed to execute 'createImageBitmap' on 'Window': The provided element's player has no current data.\"\n // Just keep going on\n texture.isReady = true;\n });\n }\n};\n//# sourceMappingURL=engine.videoTexture.js.map","import \"./engine.alpha.js\";\nimport \"./engine.computeShader.js\";\nimport \"./engine.cubeTexture.js\";\nimport \"./engine.debugging.js\";\nimport \"./engine.dynamicBuffer.js\";\nimport \"./engine.dynamicTexture.js\";\nimport \"./engine.externalTexture.js\";\nimport \"./engine.multiRender.js\";\nimport \"./engine.query.js\";\nimport \"./engine.rawTexture.js\";\nimport \"./engine.readTexture.js\";\nimport \"./engine.renderTarget.js\";\nimport \"./engine.renderTargetCube.js\";\nimport \"./engine.textureSampler.js\";\nimport \"./engine.storageBuffer.js\";\nimport \"./engine.uniformBuffer.js\";\nimport \"./engine.videoTexture.js\";\n//# sourceMappingURL=index.js.map","export {};\n//# sourceMappingURL=IPipelineContext.js.map","export {};\n//# sourceMappingURL=ICanvas.js.map","export {};\n//# sourceMappingURL=engineFeatures.js.map","import { Engine } from \"./engine.js\";\nimport { NullEngine } from \"./nullEngine.js\";\nimport { WebGPUEngine } from \"./webgpuEngine.js\";\n/**\n * Helper class to create the best engine depending on the current hardware\n */\nexport class EngineFactory {\n /**\n * Creates an engine based on the capabilities of the underlying hardware\n * @param canvas Defines the canvas to use to display the result\n * @param options Defines the options passed to the engine to create the context dependencies\n * @returns a promise that resolves with the created engine\n */\n static CreateAsync(canvas, options) {\n return WebGPUEngine.IsSupportedAsync.then((supported) => {\n if (supported) {\n return WebGPUEngine.CreateAsync(canvas, options);\n }\n else if (Engine.IsSupported) {\n return new Promise((resolve) => {\n resolve(new Engine(canvas, undefined, options));\n });\n }\n return new Promise((resolve) => {\n resolve(new NullEngine(options));\n });\n });\n }\n}\n//# sourceMappingURL=engineFactory.js.map","export {};\n//# sourceMappingURL=IMaterialContext.js.map","export {};\n//# sourceMappingURL=IDrawContext.js.map","export {};\n//# sourceMappingURL=iShaderProcessor.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./constants.js\";\nexport * from \"./engineCapabilities.js\";\nexport * from \"./instancingAttributeInfo.js\";\nexport * from \"./thinEngine.js\";\nexport * from \"./engine.js\";\nexport * from \"./engineStore.js\";\nexport * from \"./nullEngine.js\";\nexport * from \"./Extensions/index.js\";\nexport * from \"./Native/index.js\";\nexport * from \"./WebGPU/Extensions/index.js\";\nexport * from \"./IPipelineContext.js\";\nexport * from \"./ICanvas.js\";\nexport * from \"./WebGL/webGLPipelineContext.js\";\nexport * from \"./WebGL/webGLHardwareTexture.js\";\nexport * from \"./WebGPU/webgpuConstants.js\";\nexport * from \"./webgpuEngine.js\";\nexport * from \"./WebGPU/webgpuCacheRenderPipeline.js\";\nexport * from \"./WebGPU/webgpuCacheRenderPipelineTree.js\";\nexport * from \"./WebGPU/webgpuCacheBindGroups.js\";\nexport * from \"./WebGPU/webgpuCacheSampler.js\";\nexport * from \"./WebGPU/webgpuDrawContext.js\";\nexport * from \"./WebGPU/webgpuTintWASM.js\";\nexport * from \"./WebGL/webGL2ShaderProcessors.js\";\nexport * from \"./nativeEngine.js\";\nexport * from \"./Processors/shaderCodeInliner.js\";\nexport * from \"./performanceConfigurator.js\";\nexport * from \"./engineFeatures.js\";\nexport * from \"./engineFactory.js\";\nexport * from \"./IMaterialContext.js\";\nexport * from \"./IDrawContext.js\";\nexport * from \"./shaderStore.js\";\nexport * from \"./renderTargetWrapper.js\";\nexport * from \"./Processors/iShaderProcessor.js\";\n//# sourceMappingURL=index.js.map","/**\n * Gather the list of clipboard event types as constants.\n */\nexport class ClipboardEventTypes {\n}\n/**\n * The clipboard event is fired when a copy command is active (pressed).\n */\nClipboardEventTypes.COPY = 0x01; //\n/**\n * The clipboard event is fired when a cut command is active (pressed).\n */\nClipboardEventTypes.CUT = 0x02;\n/**\n * The clipboard event is fired when a paste command is active (pressed).\n */\nClipboardEventTypes.PASTE = 0x03;\n/**\n * This class is used to store clipboard related info for the onClipboardObservable event.\n */\nexport class ClipboardInfo {\n /**\n *Creates an instance of ClipboardInfo.\n * @param type Defines the type of event (BABYLON.ClipboardEventTypes)\n * @param event Defines the related dom event\n */\n constructor(\n /**\n * Defines the type of event (BABYLON.ClipboardEventTypes)\n */\n type, \n /**\n * Defines the related dom event\n */\n event) {\n this.type = type;\n this.event = event;\n }\n /**\n * Get the clipboard event's type from the keycode.\n * @param keyCode Defines the keyCode for the current keyboard event.\n * @returns {number}\n */\n static GetTypeFromCharacter(keyCode) {\n const charCode = keyCode;\n //TODO: add codes for extended ASCII\n switch (charCode) {\n case 67:\n return ClipboardEventTypes.COPY;\n case 86:\n return ClipboardEventTypes.PASTE;\n case 88:\n return ClipboardEventTypes.CUT;\n default:\n return -1;\n }\n }\n}\n//# sourceMappingURL=clipboardEvents.js.map","export * from \"./keyboardEvents.js\";\nexport * from \"./pointerEvents.js\";\nexport * from \"./clipboardEvents.js\";\nexport * from \"./deviceInputEvents.js\";\n//# sourceMappingURL=index.js.map","import { Logger } from \"../../Misc/logger.js\";\nimport { SceneLoader } from \"../../Loading/sceneLoader.js\";\nimport { WebVRController } from \"./webVRController.js\";\nimport { PoseEnabledControllerType, PoseEnabledControllerHelper } from \"./poseEnabledController.js\";\n/**\n * Google Daydream controller\n */\nexport class DaydreamController extends WebVRController {\n /**\n * Creates a new DaydreamController from a gamepad\n * @param vrGamepad the gamepad that the controller should be created from\n */\n constructor(vrGamepad) {\n super(vrGamepad);\n this.controllerType = PoseEnabledControllerType.DAYDREAM;\n }\n /**\n * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.\n * @param scene scene in which to add meshes\n * @param meshLoaded optional callback function that will be called if the mesh loads successfully.\n */\n initControllerMesh(scene, meshLoaded) {\n SceneLoader.ImportMesh(\"\", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, (newMeshes) => {\n this._defaultModel = newMeshes[1];\n this.attachToMesh(this._defaultModel);\n if (meshLoaded) {\n meshLoaded(this._defaultModel);\n }\n });\n }\n /**\n * Called once for each button that changed state since the last frame\n * @param buttonIdx Which button index changed\n * @param state New state of the button\n */\n _handleButtonChange(buttonIdx, state) {\n // Daydream controller only has 1 GamepadButton (on the trackpad).\n if (buttonIdx === 0) {\n const observable = this.onTriggerStateChangedObservable;\n if (observable) {\n observable.notifyObservers(state);\n }\n }\n else {\n // If the app or home buttons are ever made available\n Logger.Warn(`Unrecognized Daydream button index: ${buttonIdx}`);\n }\n }\n}\n/**\n * Base Url for the controller model.\n */\nDaydreamController.MODEL_BASE_URL = \"https://controllers.babylonjs.com/generic/\";\n/**\n * File name for the controller model.\n */\nDaydreamController.MODEL_FILENAME = \"generic.babylon\";\n/**\n * Gamepad Id prefix used to identify Daydream Controller.\n */\nDaydreamController.GAMEPAD_ID_PREFIX = \"Daydream\"; // id is 'Daydream Controller'\nPoseEnabledControllerHelper._ControllerFactories.push({\n canCreate: (gamepadInfo) => {\n return gamepadInfo.id.indexOf(DaydreamController.GAMEPAD_ID_PREFIX) === 0;\n },\n create: (gamepadInfo) => {\n return new DaydreamController(gamepadInfo);\n },\n});\n//# sourceMappingURL=daydreamController.js.map","import { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Mesh } from \"../../Meshes/mesh.js\";\nimport { SceneLoader } from \"../../Loading/sceneLoader.js\";\nimport { WebVRController } from \"./webVRController.js\";\nimport { PoseEnabledControllerType, PoseEnabledControllerHelper } from \"./poseEnabledController.js\";\n/**\n * Gear VR Controller\n */\nexport class GearVRController extends WebVRController {\n /**\n * Creates a new GearVRController from a gamepad\n * @param vrGamepad the gamepad that the controller should be created from\n */\n constructor(vrGamepad) {\n super(vrGamepad);\n this._buttonIndexToObservableNameMap = [\n \"onPadStateChangedObservable\",\n \"onTriggerStateChangedObservable\", // Trigger\n ];\n this.controllerType = PoseEnabledControllerType.GEAR_VR;\n // Initial starting position defaults to where hand would be (incase of only 3dof controller)\n this._calculatedPosition = new Vector3(this.hand == \"left\" ? -0.15 : 0.15, -0.5, 0.25);\n this._disableTrackPosition(this._calculatedPosition);\n }\n /**\n * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.\n * @param scene scene in which to add meshes\n * @param meshLoaded optional callback function that will be called if the mesh loads successfully.\n */\n initControllerMesh(scene, meshLoaded) {\n SceneLoader.ImportMesh(\"\", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, (newMeshes) => {\n // Offset the controller so it will rotate around the users wrist\n const mesh = new Mesh(\"\", scene);\n newMeshes[1].parent = mesh;\n newMeshes[1].position.z = -0.15;\n this._defaultModel = mesh;\n this.attachToMesh(this._defaultModel);\n if (meshLoaded) {\n meshLoaded(this._defaultModel);\n }\n });\n }\n /**\n * Called once for each button that changed state since the last frame\n * @param buttonIdx Which button index changed\n * @param state New state of the button\n */\n _handleButtonChange(buttonIdx, state) {\n if (buttonIdx < this._buttonIndexToObservableNameMap.length) {\n const observableName = this._buttonIndexToObservableNameMap[buttonIdx];\n // Only emit events for buttons that we know how to map from index to observable\n const observable = this[observableName];\n if (observable) {\n observable.notifyObservers(state);\n }\n }\n }\n}\n/**\n * Base Url for the controller model.\n */\nGearVRController.MODEL_BASE_URL = \"https://controllers.babylonjs.com/generic/\";\n/**\n * File name for the controller model.\n */\nGearVRController.MODEL_FILENAME = \"generic.babylon\";\n/**\n * Gamepad Id prefix used to identify this controller.\n */\nGearVRController.GAMEPAD_ID_PREFIX = \"Gear VR\"; // id is 'Gear VR Controller'\nPoseEnabledControllerHelper._ControllerFactories.push({\n canCreate: (gamepadInfo) => {\n return gamepadInfo.id.indexOf(GearVRController.GAMEPAD_ID_PREFIX) === 0 || gamepadInfo.id.indexOf(\"Oculus Go\") !== -1 || gamepadInfo.id.indexOf(\"Vive Focus\") !== -1;\n },\n create: (gamepadInfo) => {\n return new GearVRController(gamepadInfo);\n },\n});\n//# sourceMappingURL=gearVRController.js.map","import { SceneLoader } from \"../../Loading/sceneLoader.js\";\nimport { WebVRController } from \"./webVRController.js\";\nimport { PoseEnabledControllerHelper } from \"./poseEnabledController.js\";\n/**\n * Generic Controller\n */\nexport class GenericController extends WebVRController {\n /**\n * Creates a new GenericController from a gamepad\n * @param vrGamepad the gamepad that the controller should be created from\n */\n constructor(vrGamepad) {\n super(vrGamepad);\n }\n /**\n * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.\n * @param scene scene in which to add meshes\n * @param meshLoaded optional callback function that will be called if the mesh loads successfully.\n */\n initControllerMesh(scene, meshLoaded) {\n SceneLoader.ImportMesh(\"\", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, (newMeshes) => {\n this._defaultModel = newMeshes[1];\n this.attachToMesh(this._defaultModel);\n if (meshLoaded) {\n meshLoaded(this._defaultModel);\n }\n });\n }\n /**\n * Called once for each button that changed state since the last frame\n * @param buttonIdx Which button index changed\n * @param state New state of the button\n */\n _handleButtonChange(buttonIdx, state) {\n console.log(\"Button id: \" + buttonIdx + \"state: \");\n console.dir(state);\n }\n}\n/**\n * Base Url for the controller model.\n */\nGenericController.MODEL_BASE_URL = \"https://controllers.babylonjs.com/generic/\";\n/**\n * File name for the controller model.\n */\nGenericController.MODEL_FILENAME = \"generic.babylon\";\nPoseEnabledControllerHelper._DefaultControllerFactory = (gamepadInfo) => new GenericController(gamepadInfo);\n//# sourceMappingURL=genericController.js.map","import { Observable } from \"../../Misc/observable.js\";\nimport { SceneLoader } from \"../../Loading/sceneLoader.js\";\nimport { WebVRController } from \"./webVRController.js\";\nimport { PoseEnabledControllerType, PoseEnabledControllerHelper } from \"./poseEnabledController.js\";\nimport { EngineStore } from \"../../Engines/engineStore.js\";\n/**\n * Oculus Touch Controller\n */\nexport class OculusTouchController extends WebVRController {\n /**\n * Creates a new OculusTouchController from a gamepad\n * @param vrGamepad the gamepad that the controller should be created from\n */\n constructor(vrGamepad) {\n super(vrGamepad);\n /**\n * Fired when the secondary trigger on this controller is modified\n */\n this.onSecondaryTriggerStateChangedObservable = new Observable();\n /**\n * Fired when the thumb rest on this controller is modified\n */\n this.onThumbRestChangedObservable = new Observable();\n this.controllerType = PoseEnabledControllerType.OCULUS;\n }\n /**\n * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.\n * @param scene scene in which to add meshes\n * @param meshLoaded optional callback function that will be called if the mesh loads successfully.\n */\n initControllerMesh(scene, meshLoaded) {\n let meshName;\n // Hand\n if (this.hand === \"left\") {\n meshName = OculusTouchController.MODEL_LEFT_FILENAME;\n }\n else {\n // Right is the default if no hand is specified\n meshName = OculusTouchController.MODEL_RIGHT_FILENAME;\n }\n SceneLoader.ImportMesh(\"\", OculusTouchController._IsQuest ? OculusTouchController.QUEST_MODEL_BASE_URL : OculusTouchController.MODEL_BASE_URL, meshName, scene, (newMeshes) => {\n /*\n Parent Mesh name: oculus_touch_left\n - body\n - trigger\n - thumbstick\n - grip\n - button_y\n - button_x\n - button_enter\n */\n this._defaultModel = OculusTouchController._IsQuest ? newMeshes[0] : newMeshes[1];\n this.attachToMesh(this._defaultModel);\n if (meshLoaded) {\n meshLoaded(this._defaultModel);\n }\n });\n }\n /**\n * Fired when the A button on this controller is modified\n */\n get onAButtonStateChangedObservable() {\n if (this.hand === \"right\") {\n return this.onMainButtonStateChangedObservable;\n }\n else {\n throw new Error(\"No A button on left hand\");\n }\n }\n /**\n * Fired when the B button on this controller is modified\n */\n get onBButtonStateChangedObservable() {\n if (this.hand === \"right\") {\n return this.onSecondaryButtonStateChangedObservable;\n }\n else {\n throw new Error(\"No B button on left hand\");\n }\n }\n /**\n * Fired when the X button on this controller is modified\n */\n get onXButtonStateChangedObservable() {\n if (this.hand === \"left\") {\n return this.onMainButtonStateChangedObservable;\n }\n else {\n throw new Error(\"No X button on right hand\");\n }\n }\n /**\n * Fired when the Y button on this controller is modified\n */\n get onYButtonStateChangedObservable() {\n if (this.hand === \"left\") {\n return this.onSecondaryButtonStateChangedObservable;\n }\n else {\n throw new Error(\"No Y button on right hand\");\n }\n }\n /**\n * Called once for each button that changed state since the last frame\n * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick\n * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)\n * 2) secondary trigger (same)\n * 3) A (right) X (left), touch, pressed = value\n * 4) B / Y\n * 5) thumb rest\n * @param buttonIdx Which button index changed\n * @param state New state of the button\n */\n _handleButtonChange(buttonIdx, state) {\n const notifyObject = state; //{ state: state, changes: changes };\n const triggerDirection = this.hand === \"right\" ? -1 : 1;\n switch (buttonIdx) {\n case 0:\n this.onPadStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 1: // index trigger\n if (!OculusTouchController._IsQuest && this._defaultModel) {\n this._defaultModel.getChildren()[3].rotation.x = -notifyObject.value * 0.2;\n this._defaultModel.getChildren()[3].position.y = -notifyObject.value * 0.005;\n this._defaultModel.getChildren()[3].position.z = -notifyObject.value * 0.005;\n }\n this.onTriggerStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 2: // secondary trigger\n if (!OculusTouchController._IsQuest && this._defaultModel) {\n this._defaultModel.getChildren()[4].position.x = triggerDirection * notifyObject.value * 0.0035;\n }\n this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 3:\n if (!OculusTouchController._IsQuest && this._defaultModel) {\n if (notifyObject.pressed) {\n this._defaultModel.getChildren()[1].position.y = -0.001;\n }\n else {\n this._defaultModel.getChildren()[1].position.y = 0;\n }\n }\n this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 4:\n if (!OculusTouchController._IsQuest && this._defaultModel) {\n if (notifyObject.pressed) {\n this._defaultModel.getChildren()[2].position.y = -0.001;\n }\n else {\n this._defaultModel.getChildren()[2].position.y = 0;\n }\n }\n this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 5:\n this.onThumbRestChangedObservable.notifyObservers(notifyObject);\n return;\n }\n }\n}\n/**\n * Base Url for the controller model.\n */\nOculusTouchController.MODEL_BASE_URL = \"https://controllers.babylonjs.com/oculus/\";\n/**\n * File name for the left controller model.\n */\nOculusTouchController.MODEL_LEFT_FILENAME = \"left.babylon\";\n/**\n * File name for the right controller model.\n */\nOculusTouchController.MODEL_RIGHT_FILENAME = \"right.babylon\";\n/**\n * Base Url for the Quest controller model.\n */\nOculusTouchController.QUEST_MODEL_BASE_URL = \"https://controllers.babylonjs.com/oculusQuest/\";\n/**\n * @internal\n * If the controllers are running on a device that needs the updated Quest controller models\n */\nOculusTouchController._IsQuest = false;\nPoseEnabledControllerHelper._ControllerFactories.push({\n canCreate: (gamepadInfo) => {\n // If the headset reports being an Oculus Quest, use the Quest controller models\n if (EngineStore.LastCreatedEngine && EngineStore.LastCreatedEngine._vrDisplay && EngineStore.LastCreatedEngine._vrDisplay.displayName === \"Oculus Quest\") {\n OculusTouchController._IsQuest = true;\n }\n return gamepadInfo.id.indexOf(\"Oculus Touch\") !== -1;\n },\n create: (gamepadInfo) => {\n return new OculusTouchController(gamepadInfo);\n },\n});\n//# sourceMappingURL=oculusTouchController.js.map","import { SceneLoader } from \"../../Loading/sceneLoader.js\";\nimport { WebVRController } from \"./webVRController.js\";\nimport { PoseEnabledControllerType, PoseEnabledControllerHelper } from \"./poseEnabledController.js\";\n/**\n * Vive Controller\n */\nexport class ViveController extends WebVRController {\n /**\n * Creates a new ViveController from a gamepad\n * @param vrGamepad the gamepad that the controller should be created from\n */\n constructor(vrGamepad) {\n super(vrGamepad);\n this.controllerType = PoseEnabledControllerType.VIVE;\n this._invertLeftStickY = true;\n }\n /**\n * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.\n * @param scene scene in which to add meshes\n * @param meshLoaded optional callback function that will be called if the mesh loads successfully.\n */\n initControllerMesh(scene, meshLoaded) {\n SceneLoader.ImportMesh(\"\", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, (newMeshes) => {\n /*\n Parent Mesh name: ViveWand\n - body\n - r_gripper\n - l_gripper\n - menu_button\n - system_button\n - trackpad\n - trigger\n - LED\n */\n this._defaultModel = newMeshes[1];\n this.attachToMesh(this._defaultModel);\n if (meshLoaded) {\n meshLoaded(this._defaultModel);\n }\n });\n }\n /**\n * Fired when the left button on this controller is modified\n */\n get onLeftButtonStateChangedObservable() {\n return this.onMainButtonStateChangedObservable;\n }\n /**\n * Fired when the right button on this controller is modified\n */\n get onRightButtonStateChangedObservable() {\n return this.onMainButtonStateChangedObservable;\n }\n /**\n * Fired when the menu button on this controller is modified\n */\n get onMenuButtonStateChangedObservable() {\n return this.onSecondaryButtonStateChangedObservable;\n }\n /**\n * Called once for each button that changed state since the last frame\n * Vive mapping:\n * 0: touchpad\n * 1: trigger\n * 2: left AND right buttons\n * 3: menu button\n * @param buttonIdx Which button index changed\n * @param state New state of the button\n */\n _handleButtonChange(buttonIdx, state) {\n const notifyObject = state; //{ state: state, changes: changes };\n switch (buttonIdx) {\n case 0:\n this.onPadStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 1: // index trigger\n if (this._defaultModel) {\n this._defaultModel.getChildren()[6].rotation.x = -notifyObject.value * 0.15;\n }\n this.onTriggerStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 2: // left AND right button\n this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 3:\n if (this._defaultModel) {\n if (notifyObject.pressed) {\n this._defaultModel.getChildren()[2].position.y = -0.001;\n }\n else {\n this._defaultModel.getChildren()[2].position.y = 0;\n }\n }\n this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);\n return;\n }\n }\n}\n/**\n * Base Url for the controller model.\n */\nViveController.MODEL_BASE_URL = \"https://controllers.babylonjs.com/vive/\";\n/**\n * File name for the controller model.\n */\nViveController.MODEL_FILENAME = \"wand.babylon\";\nPoseEnabledControllerHelper._ControllerFactories.push({\n canCreate: (gamepadInfo) => {\n return gamepadInfo.id.toLowerCase().indexOf(\"openvr\") !== -1;\n },\n create: (gamepadInfo) => {\n return new ViveController(gamepadInfo);\n },\n});\n//# sourceMappingURL=viveController.js.map","import { Logger } from \"../../Misc/logger.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { Quaternion, Vector3 } from \"../../Maths/math.vector.js\";\nimport { Mesh } from \"../../Meshes/mesh.js\";\nimport { Ray } from \"../../Culling/ray.js\";\nimport { SceneLoader } from \"../../Loading/sceneLoader.js\";\nimport { WebVRController } from \"./webVRController.js\";\nimport { GenericController } from \"./genericController.js\";\nimport { PoseEnabledController, PoseEnabledControllerType, PoseEnabledControllerHelper } from \"./poseEnabledController.js\";\n/**\n * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh\n */\nclass LoadedMeshInfo {\n constructor() {\n /**\n * Map of the button meshes contained in the controller\n */\n this.buttonMeshes = {};\n /**\n * Map of the axis meshes contained in the controller\n */\n this.axisMeshes = {};\n }\n}\n/**\n * Defines the WindowsMotionController object that the state of the windows motion controller\n */\nexport class WindowsMotionController extends WebVRController {\n /**\n * Creates a new WindowsMotionController from a gamepad\n * @param vrGamepad the gamepad that the controller should be created from\n */\n constructor(vrGamepad) {\n super(vrGamepad);\n this._mapping = {\n // Semantic button names\n buttons: [\"thumbstick\", \"trigger\", \"grip\", \"menu\", \"trackpad\"],\n // trigger, grip, trackpad, thumbstick, menu\n // A mapping of the button name to glTF model node name\n // that should be transformed by button value.\n buttonMeshNames: {\n trigger: \"SELECT\",\n menu: \"MENU\",\n grip: \"GRASP\",\n thumbstick: \"THUMBSTICK_PRESS\",\n trackpad: \"TOUCHPAD_PRESS\",\n },\n // This mapping is used to translate from the Motion Controller to Babylon semantics\n buttonObservableNames: {\n trigger: \"onTriggerStateChangedObservable\",\n menu: \"onSecondaryButtonStateChangedObservable\",\n grip: \"onMainButtonStateChangedObservable\",\n thumbstick: \"onPadStateChangedObservable\",\n trackpad: \"onTrackpadChangedObservable\",\n },\n // A mapping of the axis name to glTF model node name\n // that should be transformed by axis value.\n // This array mirrors the browserGamepad.axes array, such that\n // the mesh corresponding to axis 0 is in this array index 0.\n axisMeshNames: [\"THUMBSTICK_X\", \"THUMBSTICK_Y\", \"TOUCHPAD_TOUCH_X\", \"TOUCHPAD_TOUCH_Y\"],\n // upside down in webxr\n pointingPoseMeshName: PoseEnabledController.POINTING_POSE,\n };\n /**\n * Fired when the trackpad on this controller is clicked\n */\n this.onTrackpadChangedObservable = new Observable();\n /**\n * Fired when the trackpad on this controller is modified\n */\n this.onTrackpadValuesChangedObservable = new Observable();\n /**\n * The current x and y values of this controller's trackpad\n */\n this.trackpad = { x: 0, y: 0 };\n this.controllerType = PoseEnabledControllerType.WINDOWS;\n this._loadedMeshInfo = null;\n }\n /**\n * Fired when the trigger on this controller is modified\n */\n get onTriggerButtonStateChangedObservable() {\n return this.onTriggerStateChangedObservable;\n }\n /**\n * Fired when the menu button on this controller is modified\n */\n get onMenuButtonStateChangedObservable() {\n return this.onSecondaryButtonStateChangedObservable;\n }\n /**\n * Fired when the grip button on this controller is modified\n */\n get onGripButtonStateChangedObservable() {\n return this.onMainButtonStateChangedObservable;\n }\n /**\n * Fired when the thumbstick button on this controller is modified\n */\n get onThumbstickButtonStateChangedObservable() {\n return this.onPadStateChangedObservable;\n }\n /**\n * Fired when the touchpad button on this controller is modified\n */\n get onTouchpadButtonStateChangedObservable() {\n return this.onTrackpadChangedObservable;\n }\n /**\n * Fired when the touchpad values on this controller are modified\n */\n get onTouchpadValuesChangedObservable() {\n return this.onTrackpadValuesChangedObservable;\n }\n _updateTrackpad() {\n if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {\n this.trackpad.x = this.browserGamepad[\"axes\"][this._mapping.axisMeshNames.indexOf(\"TOUCHPAD_TOUCH_X\")];\n this.trackpad.y = this.browserGamepad[\"axes\"][this._mapping.axisMeshNames.indexOf(\"TOUCHPAD_TOUCH_Y\")];\n this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);\n }\n }\n /**\n * Called once per frame by the engine.\n */\n update() {\n super.update();\n if (this.browserGamepad.axes) {\n this._updateTrackpad();\n // Only need to animate axes if there is a loaded mesh\n if (this._loadedMeshInfo) {\n for (let axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {\n this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);\n }\n }\n }\n }\n /**\n * Called once for each button that changed state since the last frame\n * @param buttonIdx Which button index changed\n * @param state New state of the button\n */\n _handleButtonChange(buttonIdx, state) {\n const buttonName = this._mapping.buttons[buttonIdx];\n if (!buttonName) {\n return;\n }\n // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames\n this._updateTrackpad();\n // Only emit events for buttons that we know how to map from index to name\n const observable = this[this._mapping.buttonObservableNames[buttonName]];\n if (observable) {\n observable.notifyObservers(state);\n }\n this._lerpButtonTransform(buttonName, state.value);\n }\n /**\n * Moves the buttons on the controller mesh based on their current state\n * @param buttonName the name of the button to move\n * @param buttonValue the value of the button which determines the buttons new position\n */\n _lerpButtonTransform(buttonName, buttonValue) {\n // If there is no loaded mesh, there is nothing to transform.\n if (!this._loadedMeshInfo) {\n return;\n }\n const meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];\n if (!meshInfo || !meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {\n return;\n }\n Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);\n Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);\n }\n /**\n * Moves the axis on the controller mesh based on its current state\n * @param axis the index of the axis\n * @param axisValue the value of the axis which determines the meshes new position\n * @internal\n */\n _lerpAxisTransform(axis, axisValue) {\n if (!this._loadedMeshInfo) {\n return;\n }\n const meshInfo = this._loadedMeshInfo.axisMeshes[axis];\n if (!meshInfo) {\n return;\n }\n if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {\n return;\n }\n // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)\n const lerpValue = axisValue * 0.5 + 0.5;\n Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);\n Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);\n }\n /**\n * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.\n * @param scene scene in which to add meshes\n * @param meshLoaded optional callback function that will be called if the mesh loads successfully.\n * @param forceDefault\n */\n initControllerMesh(scene, meshLoaded, forceDefault = false) {\n let path;\n let filename;\n // Checking if GLB loader is present\n if (SceneLoader.IsPluginForExtensionAvailable(\".glb\")) {\n // Determine the device specific folder based on the ID suffix\n let device = \"default\";\n if (this.id && !forceDefault) {\n const match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);\n device = (match && match[0]) || device;\n }\n // Hand\n if (this.hand === \"left\") {\n filename = WindowsMotionController.MODEL_LEFT_FILENAME;\n }\n else {\n // Right is the default if no hand is specified\n filename = WindowsMotionController.MODEL_RIGHT_FILENAME;\n }\n path = WindowsMotionController.MODEL_BASE_URL + device + \"/\";\n }\n else {\n Logger.Warn(\"You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models\");\n path = GenericController.MODEL_BASE_URL;\n filename = GenericController.MODEL_FILENAME;\n }\n SceneLoader.ImportMesh(\"\", path, filename, scene, (meshes) => {\n // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.\n this._loadedMeshInfo = this._processModel(scene, meshes);\n if (!this._loadedMeshInfo) {\n return;\n }\n this._defaultModel = this._loadedMeshInfo.rootNode;\n this.attachToMesh(this._defaultModel);\n if (meshLoaded) {\n meshLoaded(this._defaultModel);\n }\n }, null, (scene, message) => {\n Logger.Log(message);\n Logger.Warn(\"Failed to retrieve controller model from the remote server: \" + path + filename);\n if (!forceDefault) {\n this.initControllerMesh(scene, meshLoaded, true);\n }\n });\n }\n /**\n * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that\n * can be transformed by button presses and axes values, based on this._mapping.\n *\n * @param scene scene in which the meshes exist\n * @param meshes list of meshes that make up the controller model to process\n * @returns structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.\n */\n _processModel(scene, meshes) {\n let loadedMeshInfo = null;\n // Create a new mesh to contain the glTF hierarchy\n const parentMesh = new Mesh(this.id + \" \" + this.hand, scene);\n // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'\n let childMesh = null;\n for (let i = 0; i < meshes.length; i++) {\n const mesh = meshes[i];\n if (!mesh.parent) {\n // Exclude controller meshes from picking results\n mesh.isPickable = false;\n // Handle root node, attach to the new parentMesh\n childMesh = mesh;\n break;\n }\n }\n if (childMesh) {\n childMesh.setParent(parentMesh);\n // Create our mesh info. Note that this method will always return non-null.\n loadedMeshInfo = this._createMeshInfo(parentMesh);\n }\n else {\n Logger.Warn(\"Could not find root node in model file.\");\n }\n return loadedMeshInfo;\n }\n _createMeshInfo(rootNode) {\n const loadedMeshInfo = new LoadedMeshInfo();\n let i;\n loadedMeshInfo.rootNode = rootNode;\n // Reset the caches\n loadedMeshInfo.buttonMeshes = {};\n loadedMeshInfo.axisMeshes = {};\n // Button Meshes\n for (i = 0; i < this._mapping.buttons.length; i++) {\n const buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];\n if (!buttonMeshName) {\n Logger.Log(\"Skipping unknown button at index: \" + i + \" with mapped name: \" + this._mapping.buttons[i]);\n continue;\n }\n const buttonMesh = getChildByName(rootNode, buttonMeshName);\n if (!buttonMesh) {\n Logger.Warn(\"Missing button mesh with name: \" + buttonMeshName);\n continue;\n }\n const buttonMeshInfo = {\n index: i,\n value: getImmediateChildByName(buttonMesh, \"VALUE\"),\n pressed: getImmediateChildByName(buttonMesh, \"PRESSED\"),\n unpressed: getImmediateChildByName(buttonMesh, \"UNPRESSED\"),\n };\n if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {\n loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;\n }\n else {\n // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.\n Logger.Warn(\"Missing button submesh under mesh with name: \" +\n buttonMeshName +\n \"(VALUE: \" +\n !!buttonMeshInfo.value +\n \", PRESSED: \" +\n !!buttonMeshInfo.pressed +\n \", UNPRESSED:\" +\n !!buttonMeshInfo.unpressed +\n \")\");\n }\n }\n // Axis Meshes\n for (i = 0; i < this._mapping.axisMeshNames.length; i++) {\n const axisMeshName = this._mapping.axisMeshNames[i];\n if (!axisMeshName) {\n Logger.Log(\"Skipping unknown axis at index: \" + i);\n continue;\n }\n const axisMesh = getChildByName(rootNode, axisMeshName);\n if (!axisMesh) {\n Logger.Warn(\"Missing axis mesh with name: \" + axisMeshName);\n continue;\n }\n const axisMeshInfo = {\n index: i,\n value: getImmediateChildByName(axisMesh, \"VALUE\"),\n min: getImmediateChildByName(axisMesh, \"MIN\"),\n max: getImmediateChildByName(axisMesh, \"MAX\"),\n };\n if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {\n loadedMeshInfo.axisMeshes[i] = axisMeshInfo;\n }\n else {\n // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.\n Logger.Warn(\"Missing axis submesh under mesh with name: \" +\n axisMeshName +\n \"(VALUE: \" +\n !!axisMeshInfo.value +\n \", MIN: \" +\n !!axisMeshInfo.min +\n \", MAX:\" +\n !!axisMeshInfo.max +\n \")\");\n }\n }\n // Pointing Ray\n loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);\n if (!loadedMeshInfo.pointingPoseNode) {\n Logger.Warn(\"Missing pointing pose mesh with name: \" + this._mapping.pointingPoseMeshName);\n }\n else {\n this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;\n }\n return loadedMeshInfo;\n // Look through all children recursively. This will return null if no mesh exists with the given name.\n function getChildByName(node, name) {\n return node.getChildren((n) => n.name === name, false)[0];\n }\n // Look through only immediate children. This will return null if no mesh exists with the given name.\n function getImmediateChildByName(node, name) {\n return node.getChildren((n) => n.name == name, true)[0];\n }\n }\n /**\n * Gets the ray of the controller in the direction the controller is pointing\n * @param length the length the resulting ray should be\n * @returns a ray in the direction the controller is pointing\n */\n getForwardRay(length = 100) {\n if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {\n return super.getForwardRay(length);\n }\n const m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();\n const origin = m.getTranslation();\n const forward = new Vector3(0, 0, -1);\n const forwardWorld = Vector3.TransformNormal(forward, m);\n const direction = Vector3.Normalize(forwardWorld);\n return new Ray(origin, direction, length);\n }\n /**\n * Disposes of the controller\n */\n dispose() {\n super.dispose();\n this.onTrackpadChangedObservable.clear();\n this.onTrackpadValuesChangedObservable.clear();\n }\n}\n/**\n * The base url used to load the left and right controller models\n */\nWindowsMotionController.MODEL_BASE_URL = \"https://controllers.babylonjs.com/microsoft/\";\n/**\n * The name of the left controller model file\n */\nWindowsMotionController.MODEL_LEFT_FILENAME = \"left.glb\";\n/**\n * The name of the right controller model file\n */\nWindowsMotionController.MODEL_RIGHT_FILENAME = \"right.glb\";\n/**\n * The controller name prefix for this controller type\n */\nWindowsMotionController.GAMEPAD_ID_PREFIX = \"Spatial Controller (Spatial Interaction Source) \";\n/**\n * The controller id pattern for this controller type\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nWindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;\n/**\n * This class represents a new windows motion controller in XR.\n */\nexport class XRWindowsMotionController extends WindowsMotionController {\n /**\n * Construct a new XR-Based windows motion controller\n *\n * @param gamepadInfo the gamepad object from the browser\n */\n constructor(gamepadInfo) {\n super(gamepadInfo);\n /**\n * Changing the original WIndowsMotionController mapping to fir the new mapping\n */\n this._mapping = {\n // Semantic button names\n buttons: [\"trigger\", \"grip\", \"trackpad\", \"thumbstick\", \"menu\"],\n // trigger, grip, trackpad, thumbstick, menu\n // A mapping of the button name to glTF model node name\n // that should be transformed by button value.\n buttonMeshNames: {\n trigger: \"SELECT\",\n menu: \"MENU\",\n grip: \"GRASP\",\n thumbstick: \"THUMBSTICK_PRESS\",\n trackpad: \"TOUCHPAD_PRESS\",\n },\n // This mapping is used to translate from the Motion Controller to Babylon semantics\n buttonObservableNames: {\n trigger: \"onTriggerStateChangedObservable\",\n menu: \"onSecondaryButtonStateChangedObservable\",\n grip: \"onMainButtonStateChangedObservable\",\n thumbstick: \"onThumbstickStateChangedObservable\",\n trackpad: \"onTrackpadChangedObservable\",\n },\n // A mapping of the axis name to glTF model node name\n // that should be transformed by axis value.\n // This array mirrors the browserGamepad.axes array, such that\n // the mesh corresponding to axis 0 is in this array index 0.\n axisMeshNames: [\"TOUCHPAD_TOUCH_X\", \"TOUCHPAD_TOUCH_Y\", \"THUMBSTICK_X\", \"THUMBSTICK_Y\"],\n // upside down in webxr\n pointingPoseMeshName: PoseEnabledController.POINTING_POSE,\n };\n /**\n * holds the thumbstick values (X,Y)\n */\n this.thumbstickValues = { x: 0, y: 0 };\n /**\n * Fired when the thumbstick on this controller is clicked\n */\n this.onThumbstickStateChangedObservable = new Observable();\n /**\n * Fired when the thumbstick on this controller is modified\n */\n this.onThumbstickValuesChangedObservable = new Observable();\n /**\n * Fired when the touchpad button on this controller is modified\n */\n this.onTrackpadChangedObservable = this.onPadStateChangedObservable;\n /**\n * Fired when the touchpad values on this controller are modified\n */\n this.onTrackpadValuesChangedObservable = this.onPadValuesChangedObservable;\n }\n /**\n * Fired when the thumbstick button on this controller is modified\n * here to prevent breaking changes\n */\n get onThumbstickButtonStateChangedObservable() {\n return this.onThumbstickStateChangedObservable;\n }\n /**\n * updating the thumbstick(!) and not the trackpad.\n * This is named this way due to the difference between WebVR and XR and to avoid\n * changing the parent class.\n */\n _updateTrackpad() {\n if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.thumbstickValues.x || this.browserGamepad.axes[3] != this.thumbstickValues.y)) {\n this.trackpad.x = this.browserGamepad[\"axes\"][2];\n this.trackpad.y = this.browserGamepad[\"axes\"][3];\n this.onThumbstickValuesChangedObservable.notifyObservers(this.trackpad);\n }\n }\n /**\n * Disposes the class with joy\n */\n dispose() {\n super.dispose();\n this.onThumbstickStateChangedObservable.clear();\n this.onThumbstickValuesChangedObservable.clear();\n }\n}\nPoseEnabledControllerHelper._ControllerFactories.push({\n canCreate: (gamepadInfo) => {\n return gamepadInfo.id.indexOf(WindowsMotionController.GAMEPAD_ID_PREFIX) === 0;\n },\n create: (gamepadInfo) => {\n return new WindowsMotionController(gamepadInfo);\n },\n});\n//# sourceMappingURL=windowsMotionController.js.map","export * from \"./daydreamController.js\";\nexport * from \"./gearVRController.js\";\nexport * from \"./genericController.js\";\nexport * from \"./oculusTouchController.js\";\nexport * from \"./poseEnabledController.js\";\nexport * from \"./viveController.js\";\nexport * from \"./webVRController.js\";\nexport * from \"./windowsMotionController.js\";\n//# sourceMappingURL=index.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./Controllers/index.js\";\nexport * from \"./gamepad.js\";\nexport * from \"./gamepadManager.js\";\nexport * from \"./gamepadSceneComponent.js\";\nexport * from \"./xboxGamepad.js\";\nexport * from \"./dualShockGamepad.js\";\n//# sourceMappingURL=index.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { Vector3, Matrix, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { CreateBox } from \"../Meshes/Builders/boxBuilder.js\";\nimport { CreateCylinder } from \"../Meshes/Builders/cylinderBuilder.js\";\nimport { StandardMaterial } from \"../Materials/standardMaterial.js\";\nimport { PointerDragBehavior } from \"../Behaviors/Meshes/pointerDragBehavior.js\";\nimport { Gizmo } from \"./gizmo.js\";\nimport { UtilityLayerRenderer } from \"../Rendering/utilityLayerRenderer.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\n/**\n * Single axis scale gizmo\n */\nexport class AxisScaleGizmo extends Gizmo {\n /** Default material used to render when gizmo is not disabled or hovered */\n get coloredMaterial() {\n return this._coloredMaterial;\n }\n /** Material used to render when gizmo is hovered with mouse*/\n get hoverMaterial() {\n return this._hoverMaterial;\n }\n /** Material used to render when gizmo is disabled. typically grey.*/\n get disableMaterial() {\n return this._disableMaterial;\n }\n /**\n * Creates an AxisScaleGizmo\n * @param dragAxis The axis which the gizmo will be able to scale on\n * @param color The color of the gizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n * @param parent\n * @param thickness display gizmo axis thickness\n */\n constructor(dragAxis, color = Color3.Gray(), gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer, parent = null, thickness = 1) {\n var _a, _b, _c, _d, _e, _f, _g;\n super(gizmoLayer);\n this._pointerObserver = null;\n /**\n * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)\n */\n this.snapDistance = 0;\n /**\n * Event that fires each time the gizmo snaps to a new location.\n * * snapDistance is the the change in distance\n */\n this.onSnapObservable = new Observable();\n /**\n * If the scaling operation should be done on all axis (default: false)\n */\n this.uniformScaling = false;\n /**\n * Custom sensitivity value for the drag strength\n */\n this.sensitivity = 1;\n /**\n * The magnitude of the drag strength (scaling factor)\n */\n this.dragScale = 1;\n this._isEnabled = true;\n this._parent = null;\n this._dragging = false;\n this._tmpVector = new Vector3(0, 0, 0);\n this._parent = parent;\n // Create Material\n this._coloredMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._coloredMaterial.diffuseColor = color;\n this._coloredMaterial.specularColor = color.subtract(new Color3(0.1, 0.1, 0.1));\n this._hoverMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._hoverMaterial.diffuseColor = Color3.Yellow();\n this._disableMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._disableMaterial.diffuseColor = Color3.Gray();\n this._disableMaterial.alpha = 0.4;\n // Build mesh + Collider\n this._gizmoMesh = new Mesh(\"axis\", gizmoLayer.utilityLayerScene);\n const { arrowMesh, arrowTail } = this._createGizmoMesh(this._gizmoMesh, thickness);\n const collider = this._createGizmoMesh(this._gizmoMesh, thickness + 4, true);\n this._gizmoMesh.lookAt(this._rootMesh.position.add(dragAxis));\n this._rootMesh.addChild(this._gizmoMesh, Gizmo.PreserveScaling);\n this._gizmoMesh.scaling.scaleInPlace(1 / 3);\n // Closure of initial prop values for resetting\n const nodePosition = arrowMesh.position.clone();\n const linePosition = arrowTail.position.clone();\n const lineScale = arrowTail.scaling.clone();\n const increaseGizmoMesh = (dragDistance) => {\n const dragStrength = dragDistance * (3 / this._rootMesh.scaling.length()) * 6;\n arrowMesh.position.z += dragStrength / 3.5;\n arrowTail.scaling.y += dragStrength;\n this.dragScale = arrowTail.scaling.y;\n arrowTail.position.z = arrowMesh.position.z / 2;\n };\n const resetGizmoMesh = () => {\n arrowMesh.position.set(nodePosition.x, nodePosition.y, nodePosition.z);\n arrowTail.position.set(linePosition.x, linePosition.y, linePosition.z);\n arrowTail.scaling.set(lineScale.x, lineScale.y, lineScale.z);\n this.dragScale = arrowTail.scaling.y;\n this._dragging = false;\n };\n // Add drag behavior to handle events when the gizmo is dragged\n this.dragBehavior = new PointerDragBehavior({ dragAxis: dragAxis });\n this.dragBehavior.moveAttached = false;\n this.dragBehavior.updateDragPlane = false;\n this._rootMesh.addBehavior(this.dragBehavior);\n let currentSnapDragDistance = 0;\n const tmpSnapEvent = { snapDistance: 0 };\n this.dragBehavior.onDragObservable.add((event) => {\n if (this.attachedNode) {\n this._handlePivot();\n // Drag strength is modified by the scale of the gizmo (eg. for small objects like boombox the strength will be increased to match the behavior of larger objects)\n const dragStrength = this.sensitivity * event.dragDistance * ((this.scaleRatio * 3) / this._rootMesh.scaling.length());\n const tmpVector = this._tmpVector;\n // Snapping logic\n let snapped = false;\n let dragSteps = 0;\n if (this.uniformScaling) {\n tmpVector.setAll(0.57735); // 1 / sqrt(3)\n }\n else {\n tmpVector.copyFrom(dragAxis);\n }\n if (this.snapDistance == 0) {\n tmpVector.scaleToRef(dragStrength, tmpVector);\n }\n else {\n currentSnapDragDistance += dragStrength;\n if (Math.abs(currentSnapDragDistance) > this.snapDistance) {\n dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / this.snapDistance);\n if (currentSnapDragDistance < 0) {\n dragSteps *= -1;\n }\n currentSnapDragDistance = currentSnapDragDistance % this.snapDistance;\n tmpVector.scaleToRef(this.snapDistance * dragSteps, tmpVector);\n snapped = true;\n }\n else {\n tmpVector.scaleInPlace(0);\n }\n }\n Matrix.ScalingToRef(1 + tmpVector.x, 1 + tmpVector.y, 1 + tmpVector.z, TmpVectors.Matrix[2]);\n TmpVectors.Matrix[2].multiplyToRef(this.attachedNode.getWorldMatrix(), TmpVectors.Matrix[1]);\n const transformNode = this.attachedNode._isMesh ? this.attachedNode : undefined;\n TmpVectors.Matrix[1].decompose(TmpVectors.Vector3[1], undefined, undefined, Gizmo.PreserveScaling ? transformNode : undefined);\n const maxScale = 100000;\n if (Math.abs(TmpVectors.Vector3[1].x) < maxScale && Math.abs(TmpVectors.Vector3[1].y) < maxScale && Math.abs(TmpVectors.Vector3[1].z) < maxScale) {\n this.attachedNode.getWorldMatrix().copyFrom(TmpVectors.Matrix[1]);\n }\n if (snapped) {\n tmpSnapEvent.snapDistance = this.snapDistance * dragSteps;\n this.onSnapObservable.notifyObservers(tmpSnapEvent);\n }\n this._matrixChanged();\n }\n });\n // On Drag Listener: to move gizmo mesh with user action\n this.dragBehavior.onDragStartObservable.add(() => {\n this._dragging = true;\n });\n this.dragBehavior.onDragObservable.add((e) => increaseGizmoMesh(e.dragDistance));\n this.dragBehavior.onDragEndObservable.add(resetGizmoMesh);\n // Listeners for Universal Scalar\n (_c = (_b = (_a = parent === null || parent === void 0 ? void 0 : parent.uniformScaleGizmo) === null || _a === void 0 ? void 0 : _a.dragBehavior) === null || _b === void 0 ? void 0 : _b.onDragObservable) === null || _c === void 0 ? void 0 : _c.add((e) => increaseGizmoMesh(e.delta.y));\n (_f = (_e = (_d = parent === null || parent === void 0 ? void 0 : parent.uniformScaleGizmo) === null || _d === void 0 ? void 0 : _d.dragBehavior) === null || _e === void 0 ? void 0 : _e.onDragEndObservable) === null || _f === void 0 ? void 0 : _f.add(resetGizmoMesh);\n const cache = {\n gizmoMeshes: [arrowMesh, arrowTail],\n colliderMeshes: [collider.arrowMesh, collider.arrowTail],\n material: this._coloredMaterial,\n hoverMaterial: this._hoverMaterial,\n disableMaterial: this._disableMaterial,\n active: false,\n dragBehavior: this.dragBehavior,\n };\n (_g = this._parent) === null || _g === void 0 ? void 0 : _g.addToAxisCache(this._gizmoMesh, cache);\n this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add((pointerInfo) => {\n var _a;\n if (this._customMeshSet) {\n return;\n }\n this._isHovered = !!(cache.colliderMeshes.indexOf((_a = pointerInfo === null || pointerInfo === void 0 ? void 0 : pointerInfo.pickInfo) === null || _a === void 0 ? void 0 : _a.pickedMesh) != -1);\n if (!this._parent) {\n const material = this.dragBehavior.enabled ? (this._isHovered || this._dragging ? this._hoverMaterial : this._coloredMaterial) : this._disableMaterial;\n this._setGizmoMeshMaterial(cache.gizmoMeshes, material);\n }\n });\n this.dragBehavior.onEnabledObservable.add((newState) => {\n this._setGizmoMeshMaterial(cache.gizmoMeshes, newState ? this._coloredMaterial : this._disableMaterial);\n });\n const light = gizmoLayer._getSharedGizmoLight();\n light.includedOnlyMeshes = light.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes());\n }\n /**\n * Create Geometry for Gizmo\n * @param parentMesh\n * @param thickness\n * @param isCollider\n */\n _createGizmoMesh(parentMesh, thickness, isCollider = false) {\n const arrowMesh = CreateBox(\"yPosMesh\", { size: 0.4 * (1 + (thickness - 1) / 4) }, this.gizmoLayer.utilityLayerScene);\n const arrowTail = CreateCylinder(\"cylinder\", { diameterTop: 0.005 * thickness, height: 0.275, diameterBottom: 0.005 * thickness, tessellation: 96 }, this.gizmoLayer.utilityLayerScene);\n // Position arrow pointing in its drag axis\n arrowMesh.scaling.scaleInPlace(0.1);\n arrowMesh.material = this._coloredMaterial;\n arrowMesh.rotation.x = Math.PI / 2;\n arrowMesh.position.z += 0.3;\n arrowTail.material = this._coloredMaterial;\n arrowTail.position.z += 0.275 / 2;\n arrowTail.rotation.x = Math.PI / 2;\n if (isCollider) {\n arrowMesh.visibility = 0;\n arrowTail.visibility = 0;\n }\n parentMesh.addChild(arrowMesh);\n parentMesh.addChild(arrowTail);\n return { arrowMesh, arrowTail };\n }\n _attachedNodeChanged(value) {\n if (this.dragBehavior) {\n this.dragBehavior.enabled = value ? true : false;\n }\n }\n /**\n * If the gizmo is enabled\n */\n set isEnabled(value) {\n this._isEnabled = value;\n if (!value) {\n this.attachedMesh = null;\n this.attachedNode = null;\n }\n else {\n if (this._parent) {\n this.attachedMesh = this._parent.attachedMesh;\n this.attachedNode = this._parent.attachedNode;\n }\n }\n }\n get isEnabled() {\n return this._isEnabled;\n }\n /**\n * Disposes of the gizmo\n */\n dispose() {\n this.onSnapObservable.clear();\n this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);\n this.dragBehavior.detach();\n if (this._gizmoMesh) {\n this._gizmoMesh.dispose();\n }\n [this._coloredMaterial, this._hoverMaterial, this._disableMaterial].forEach((matl) => {\n if (matl) {\n matl.dispose();\n }\n });\n super.dispose();\n }\n /**\n * Disposes and replaces the current meshes in the gizmo with the specified mesh\n * @param mesh The mesh to replace the default mesh of the gizmo\n * @param useGizmoMaterial If the gizmo's default material should be used (default: false)\n */\n setCustomMesh(mesh, useGizmoMaterial = false) {\n super.setCustomMesh(mesh);\n if (useGizmoMaterial) {\n this._rootMesh.getChildMeshes().forEach((m) => {\n m.material = this._coloredMaterial;\n if (m.color) {\n m.color = this._coloredMaterial.diffuseColor;\n }\n });\n this._customMeshSet = false;\n }\n }\n}\n//# sourceMappingURL=axisScaleGizmo.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { Quaternion, Matrix, Vector3 } from \"../Maths/math.vector.js\";\nimport { AbstractMesh } from \"../Meshes/abstractMesh.js\";\nimport { CreateSphere } from \"../Meshes/Builders/sphereBuilder.js\";\nimport { CreateBox } from \"../Meshes/Builders/boxBuilder.js\";\nimport { CreateLines } from \"../Meshes/Builders/linesBuilder.js\";\nimport { PointerDragBehavior } from \"../Behaviors/Meshes/pointerDragBehavior.js\";\nimport { Gizmo } from \"./gizmo.js\";\nimport { UtilityLayerRenderer } from \"../Rendering/utilityLayerRenderer.js\";\nimport { StandardMaterial } from \"../Materials/standardMaterial.js\";\nimport { PivotTools } from \"../Misc/pivotTools.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { Epsilon } from \"../Maths/math.constants.js\";\n/**\n * Bounding box gizmo\n */\nexport class BoundingBoxGizmo extends Gizmo {\n /**\n * Sets the axis factor\n * @param factor the Vector3 value\n */\n set axisFactor(factor) {\n this._axisFactor = factor;\n // update scale cube visibility\n const scaleBoxes = this._scaleBoxesParent.getChildMeshes();\n let index = 0;\n for (let i = 0; i < 3; i++) {\n for (let j = 0; j < 3; j++) {\n for (let k = 0; k < 3; k++) {\n const zeroAxisCount = (i === 1 ? 1 : 0) + (j === 1 ? 1 : 0) + (k === 1 ? 1 : 0);\n if (zeroAxisCount === 1 || zeroAxisCount === 3) {\n continue;\n }\n if (scaleBoxes[index]) {\n const dragAxis = new Vector3(i - 1, j - 1, k - 1);\n dragAxis.multiplyInPlace(this._axisFactor);\n scaleBoxes[index].setEnabled(dragAxis.lengthSquared() > Epsilon);\n }\n index++;\n }\n }\n }\n }\n /**\n * Gets the axis factor\n * @returns the Vector3 factor value\n */\n get axisFactor() {\n return this._axisFactor;\n }\n /**\n * Sets scale drag speed value\n * @param value the new speed value\n */\n set scaleDragSpeed(value) {\n this._scaleDragSpeed = value;\n }\n /**\n * Gets scale drag speed\n * @returns the scale speed number\n */\n get scaleDragSpeed() {\n return this._scaleDragSpeed;\n }\n /** Default material used to render when gizmo is not disabled or hovered */\n get coloredMaterial() {\n return this._coloredMaterial;\n }\n /** Material used to render when gizmo is hovered with mouse*/\n get hoverMaterial() {\n return this._hoverColoredMaterial;\n }\n /**\n * Get the pointerDragBehavior\n */\n get pointerDragBehavior() {\n return this._pointerDragBehavior;\n }\n /**\n * Sets the color of the bounding box gizmo\n * @param color the color to set\n */\n setColor(color) {\n this._coloredMaterial.emissiveColor = color;\n this._hoverColoredMaterial.emissiveColor = color.clone().add(new Color3(0.3, 0.3, 0.3));\n this._lineBoundingBox.getChildren().forEach((l) => {\n if (l.color) {\n l.color = color;\n }\n });\n }\n /**\n * Creates an BoundingBoxGizmo\n * @param color The color of the gizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n */\n constructor(color = Color3.Gray(), gizmoLayer = UtilityLayerRenderer.DefaultKeepDepthUtilityLayer) {\n super(gizmoLayer);\n this._boundingDimensions = new Vector3(1, 1, 1);\n this._renderObserver = null;\n this._pointerObserver = null;\n this._scaleDragSpeed = 0.2;\n this._tmpQuaternion = new Quaternion();\n this._tmpVector = new Vector3(0, 0, 0);\n this._tmpRotationMatrix = new Matrix();\n /**\n * If child meshes should be ignored when calculating the bounding box. This should be set to true to avoid perf hits with heavily nested meshes (Default: false)\n */\n this.ignoreChildren = false;\n /**\n * Returns true if a descendant should be included when computing the bounding box. When null, all descendants are included. If ignoreChildren is set this will be ignored. (Default: null)\n */\n this.includeChildPredicate = null;\n /**\n * The size of the rotation spheres attached to the bounding box (Default: 0.1)\n */\n this.rotationSphereSize = 0.1;\n /**\n * The size of the scale boxes attached to the bounding box (Default: 0.1)\n */\n this.scaleBoxSize = 0.1;\n /**\n * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false)\n * Note : fixedDragMeshScreenSize takes precedence over fixedDragMeshBoundsSize if both are true\n */\n this.fixedDragMeshScreenSize = false;\n /**\n * If set, the rotation spheres and scale boxes will increase in size based on the size of the bounding box\n * Note : fixedDragMeshScreenSize takes precedence over fixedDragMeshBoundsSize if both are true\n */\n this.fixedDragMeshBoundsSize = false;\n /**\n * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)\n */\n this.fixedDragMeshScreenSizeDistanceFactor = 10;\n /**\n * Fired when a rotation sphere or scale box is dragged\n */\n this.onDragStartObservable = new Observable();\n /**\n * Fired when a scale box is dragged\n */\n this.onScaleBoxDragObservable = new Observable();\n /**\n * Fired when a scale box drag is ended\n */\n this.onScaleBoxDragEndObservable = new Observable();\n /**\n * Fired when a rotation sphere is dragged\n */\n this.onRotationSphereDragObservable = new Observable();\n /**\n * Fired when a rotation sphere drag is ended\n */\n this.onRotationSphereDragEndObservable = new Observable();\n /**\n * Relative bounding box pivot used when scaling the attached node. When null object with scale from the opposite corner. 0.5,0.5,0.5 for center and 0.5,0,0.5 for bottom (Default: null)\n */\n this.scalePivot = null;\n /**\n * Scale factor used for masking some axis\n */\n this._axisFactor = new Vector3(1, 1, 1);\n this._existingMeshScale = new Vector3();\n // Dragging\n this._dragMesh = null;\n this._pointerDragBehavior = new PointerDragBehavior();\n // Do not update the gizmo's scale so it has a fixed size to the object its attached to\n this.updateScale = false;\n this._anchorMesh = new AbstractMesh(\"anchor\", gizmoLayer.utilityLayerScene);\n // Create Materials\n this._coloredMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._coloredMaterial.disableLighting = true;\n this._hoverColoredMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._hoverColoredMaterial.disableLighting = true;\n // Build bounding box out of lines\n this._lineBoundingBox = new AbstractMesh(\"\", gizmoLayer.utilityLayerScene);\n this._lineBoundingBox.rotationQuaternion = new Quaternion();\n const lines = [];\n lines.push(CreateLines(\"lines\", { points: [new Vector3(0, 0, 0), new Vector3(this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));\n lines.push(CreateLines(\"lines\", { points: [new Vector3(0, 0, 0), new Vector3(0, this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));\n lines.push(CreateLines(\"lines\", { points: [new Vector3(0, 0, 0), new Vector3(0, 0, this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));\n lines.push(CreateLines(\"lines\", { points: [new Vector3(this._boundingDimensions.x, 0, 0), new Vector3(this._boundingDimensions.x, this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));\n lines.push(CreateLines(\"lines\", { points: [new Vector3(this._boundingDimensions.x, 0, 0), new Vector3(this._boundingDimensions.x, 0, this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));\n lines.push(CreateLines(\"lines\", { points: [new Vector3(0, this._boundingDimensions.y, 0), new Vector3(this._boundingDimensions.x, this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));\n lines.push(CreateLines(\"lines\", { points: [new Vector3(0, this._boundingDimensions.y, 0), new Vector3(0, this._boundingDimensions.y, this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));\n lines.push(CreateLines(\"lines\", { points: [new Vector3(0, 0, this._boundingDimensions.z), new Vector3(this._boundingDimensions.x, 0, this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));\n lines.push(CreateLines(\"lines\", { points: [new Vector3(0, 0, this._boundingDimensions.z), new Vector3(0, this._boundingDimensions.y, this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));\n lines.push(CreateLines(\"lines\", {\n points: [\n new Vector3(this._boundingDimensions.x, this._boundingDimensions.y, this._boundingDimensions.z),\n new Vector3(0, this._boundingDimensions.y, this._boundingDimensions.z),\n ],\n }, gizmoLayer.utilityLayerScene));\n lines.push(CreateLines(\"lines\", {\n points: [\n new Vector3(this._boundingDimensions.x, this._boundingDimensions.y, this._boundingDimensions.z),\n new Vector3(this._boundingDimensions.x, 0, this._boundingDimensions.z),\n ],\n }, gizmoLayer.utilityLayerScene));\n lines.push(CreateLines(\"lines\", {\n points: [\n new Vector3(this._boundingDimensions.x, this._boundingDimensions.y, this._boundingDimensions.z),\n new Vector3(this._boundingDimensions.x, this._boundingDimensions.y, 0),\n ],\n }, gizmoLayer.utilityLayerScene));\n lines.forEach((l) => {\n l.color = color;\n l.position.addInPlace(new Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));\n l.isPickable = false;\n this._lineBoundingBox.addChild(l);\n });\n this._rootMesh.addChild(this._lineBoundingBox);\n this.setColor(color);\n // Create rotation spheres\n this._rotateSpheresParent = new AbstractMesh(\"\", gizmoLayer.utilityLayerScene);\n this._rotateSpheresParent.rotationQuaternion = new Quaternion();\n for (let i = 0; i < 12; i++) {\n const sphere = CreateSphere(\"\", { diameter: 1 }, gizmoLayer.utilityLayerScene);\n sphere.rotationQuaternion = new Quaternion();\n sphere.material = this._coloredMaterial;\n sphere.isNearGrabbable = true;\n // Drag behavior\n const _dragBehavior = new PointerDragBehavior({});\n _dragBehavior.moveAttached = false;\n _dragBehavior.updateDragPlane = false;\n sphere.addBehavior(_dragBehavior);\n const startingTurnDirection = new Vector3(1, 0, 0);\n let totalTurnAmountOfDrag = 0;\n _dragBehavior.onDragStartObservable.add(() => {\n startingTurnDirection.copyFrom(sphere.forward);\n totalTurnAmountOfDrag = 0;\n });\n _dragBehavior.onDragObservable.add((event) => {\n this.onRotationSphereDragObservable.notifyObservers({});\n if (this.attachedMesh) {\n const originalParent = this.attachedMesh.parent;\n if (originalParent && originalParent.scaling && originalParent.scaling.isNonUniformWithinEpsilon(0.001)) {\n Logger.Warn(\"BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling\");\n return;\n }\n PivotTools._RemoveAndStorePivotPoint(this.attachedMesh);\n const worldDragDirection = startingTurnDirection;\n // Project the world right on to the drag plane\n const toSub = event.dragPlaneNormal.scale(Vector3.Dot(event.dragPlaneNormal, worldDragDirection));\n const dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();\n // project drag delta on to the resulting drag axis and rotate based on that\n let projectDist = Vector3.Dot(dragAxis, event.delta) < 0 ? Math.abs(event.delta.length()) : -Math.abs(event.delta.length());\n // Make rotation relative to size of mesh.\n projectDist = (projectDist / this._boundingDimensions.length()) * this._anchorMesh.scaling.length();\n // Rotate based on axis\n if (!this.attachedMesh.rotationQuaternion) {\n this.attachedMesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);\n }\n if (!this._anchorMesh.rotationQuaternion) {\n this._anchorMesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);\n }\n // Do not allow the object to turn more than a full circle\n totalTurnAmountOfDrag += projectDist;\n if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {\n if (i >= 8) {\n Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, this._tmpQuaternion);\n }\n else if (i >= 4) {\n Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, this._tmpQuaternion);\n }\n else {\n Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, this._tmpQuaternion);\n }\n // Rotate around center of bounding box\n this._anchorMesh.addChild(this.attachedMesh, Gizmo.PreserveScaling);\n if (this._anchorMesh.getScene().useRightHandedSystem) {\n this._tmpQuaternion.conjugateInPlace();\n }\n this._anchorMesh.rotationQuaternion.multiplyToRef(this._tmpQuaternion, this._anchorMesh.rotationQuaternion);\n this._anchorMesh.removeChild(this.attachedMesh, Gizmo.PreserveScaling);\n this.attachedMesh.setParent(originalParent, Gizmo.PreserveScaling);\n }\n this.updateBoundingBox();\n PivotTools._RestorePivotPoint(this.attachedMesh);\n }\n this._updateDummy();\n });\n // Selection/deselection\n _dragBehavior.onDragStartObservable.add(() => {\n this.onDragStartObservable.notifyObservers({});\n this._selectNode(sphere);\n });\n _dragBehavior.onDragEndObservable.add((event) => {\n this.onRotationSphereDragEndObservable.notifyObservers({});\n this._selectNode(null);\n this._updateDummy();\n this._unhoverMeshOnTouchUp(event.pointerInfo, sphere);\n });\n this._rotateSpheresParent.addChild(sphere);\n }\n this._rootMesh.addChild(this._rotateSpheresParent);\n // Create scale cubes\n this._scaleBoxesParent = new AbstractMesh(\"\", gizmoLayer.utilityLayerScene);\n this._scaleBoxesParent.rotationQuaternion = new Quaternion();\n for (let i = 0; i < 3; i++) {\n for (let j = 0; j < 3; j++) {\n for (let k = 0; k < 3; k++) {\n // create box for relevant axis\n const zeroAxisCount = (i === 1 ? 1 : 0) + (j === 1 ? 1 : 0) + (k === 1 ? 1 : 0);\n if (zeroAxisCount === 1 || zeroAxisCount === 3) {\n continue;\n }\n const box = CreateBox(\"\", { size: 1 }, gizmoLayer.utilityLayerScene);\n box.material = this._coloredMaterial;\n box._internalMetadata = zeroAxisCount === 2; // None homogenous scale handle\n box.isNearGrabbable = true;\n // Dragging logic\n const dragAxis = new Vector3(i - 1, j - 1, k - 1).normalize();\n const _dragBehavior = new PointerDragBehavior({ dragAxis: dragAxis });\n _dragBehavior.updateDragPlane = false;\n _dragBehavior.moveAttached = false;\n box.addBehavior(_dragBehavior);\n _dragBehavior.onDragObservable.add((event) => {\n this.onScaleBoxDragObservable.notifyObservers({});\n if (this.attachedMesh) {\n const originalParent = this.attachedMesh.parent;\n if (originalParent && originalParent.scaling && originalParent.scaling.isNonUniformWithinEpsilon(0.001)) {\n Logger.Warn(\"BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling\");\n return;\n }\n PivotTools._RemoveAndStorePivotPoint(this.attachedMesh);\n const relativeDragDistance = (event.dragDistance / this._boundingDimensions.length()) * this._anchorMesh.scaling.length();\n const deltaScale = new Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);\n if (zeroAxisCount === 2) {\n // scale on 1 axis when using the anchor box in the face middle\n deltaScale.x *= Math.abs(dragAxis.x);\n deltaScale.y *= Math.abs(dragAxis.y);\n deltaScale.z *= Math.abs(dragAxis.z);\n }\n deltaScale.scaleInPlace(this._scaleDragSpeed);\n deltaScale.multiplyInPlace(this._axisFactor);\n this.updateBoundingBox();\n if (this.scalePivot) {\n this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(this._tmpRotationMatrix);\n // Move anchor to desired pivot point (Bottom left corner + dimension/2)\n this._boundingDimensions.scaleToRef(0.5, this._tmpVector);\n Vector3.TransformCoordinatesToRef(this._tmpVector, this._tmpRotationMatrix, this._tmpVector);\n this._anchorMesh.position.subtractInPlace(this._tmpVector);\n this._boundingDimensions.multiplyToRef(this.scalePivot, this._tmpVector);\n Vector3.TransformCoordinatesToRef(this._tmpVector, this._tmpRotationMatrix, this._tmpVector);\n this._anchorMesh.position.addInPlace(this._tmpVector);\n }\n else {\n // Scale from the position of the opposite corner\n box.absolutePosition.subtractToRef(this._anchorMesh.position, this._tmpVector);\n this._anchorMesh.position.subtractInPlace(this._tmpVector);\n }\n this._anchorMesh.addChild(this.attachedMesh, Gizmo.PreserveScaling);\n this._anchorMesh.scaling.addInPlace(deltaScale);\n if (this._anchorMesh.scaling.x < 0 || this._anchorMesh.scaling.y < 0 || this._anchorMesh.scaling.z < 0) {\n this._anchorMesh.scaling.subtractInPlace(deltaScale);\n }\n this._anchorMesh.removeChild(this.attachedMesh, Gizmo.PreserveScaling);\n this.attachedMesh.setParent(originalParent, Gizmo.PreserveScaling);\n PivotTools._RestorePivotPoint(this.attachedMesh);\n }\n this._updateDummy();\n });\n // Selection/deselection\n _dragBehavior.onDragStartObservable.add(() => {\n this.onDragStartObservable.notifyObservers({});\n this._selectNode(box);\n });\n _dragBehavior.onDragEndObservable.add((event) => {\n this.onScaleBoxDragEndObservable.notifyObservers({});\n this._selectNode(null);\n this._updateDummy();\n this._unhoverMeshOnTouchUp(event.pointerInfo, box);\n });\n this._scaleBoxesParent.addChild(box);\n }\n }\n }\n this._rootMesh.addChild(this._scaleBoxesParent);\n // Hover color change\n const pointerIds = new Array();\n this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add((pointerInfo) => {\n if (!pointerIds[pointerInfo.event.pointerId]) {\n this._rotateSpheresParent\n .getChildMeshes()\n .concat(this._scaleBoxesParent.getChildMeshes())\n .forEach((mesh) => {\n if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {\n pointerIds[pointerInfo.event.pointerId] = mesh;\n mesh.material = this._hoverColoredMaterial;\n }\n });\n }\n else {\n if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {\n pointerIds[pointerInfo.event.pointerId].material = this._coloredMaterial;\n delete pointerIds[pointerInfo.event.pointerId];\n }\n }\n });\n // Update bounding box positions\n this._renderObserver = this.gizmoLayer.originalScene.onBeforeRenderObservable.add(() => {\n // Only update the bounding box if scaling has changed\n if (this.attachedMesh && !this._existingMeshScale.equals(this.attachedMesh.scaling)) {\n this.updateBoundingBox();\n }\n else if (this.fixedDragMeshScreenSize || this.fixedDragMeshBoundsSize) {\n this._updateRotationSpheres();\n this._updateScaleBoxes();\n }\n // If drag mesh is enabled and dragging, update the attached mesh pose to match the drag mesh\n if (this._dragMesh && this.attachedMesh && this._pointerDragBehavior.dragging) {\n this._lineBoundingBox.position.rotateByQuaternionToRef(this._rootMesh.rotationQuaternion, this._tmpVector);\n this.attachedMesh.setAbsolutePosition(this._dragMesh.position.add(this._tmpVector.scale(-1)));\n }\n });\n this.updateBoundingBox();\n }\n _attachedNodeChanged(value) {\n if (value) {\n // Reset anchor mesh to match attached mesh's scale\n // This is needed to avoid invalid box/sphere position on first drag\n this._anchorMesh.scaling.setAll(1);\n PivotTools._RemoveAndStorePivotPoint(value);\n const originalParent = value.parent;\n this._anchorMesh.addChild(value, Gizmo.PreserveScaling);\n this._anchorMesh.removeChild(value, Gizmo.PreserveScaling);\n value.setParent(originalParent, Gizmo.PreserveScaling);\n PivotTools._RestorePivotPoint(value);\n this.updateBoundingBox();\n value.getChildMeshes(false).forEach((m) => {\n m.markAsDirty(\"scaling\");\n });\n this.gizmoLayer.utilityLayerScene.onAfterRenderObservable.addOnce(() => {\n this._updateDummy();\n });\n }\n }\n _selectNode(selectedMesh) {\n this._rotateSpheresParent\n .getChildMeshes()\n .concat(this._scaleBoxesParent.getChildMeshes())\n .forEach((m) => {\n m.isVisible = !selectedMesh || m == selectedMesh;\n });\n }\n _unhoverMeshOnTouchUp(pointerInfo, selectedMesh) {\n // force unhover mesh if not a mouse event\n if ((pointerInfo === null || pointerInfo === void 0 ? void 0 : pointerInfo.event) instanceof PointerEvent && (pointerInfo === null || pointerInfo === void 0 ? void 0 : pointerInfo.event.pointerType) === \"touch\") {\n selectedMesh.material = this._coloredMaterial;\n }\n }\n /**\n * returns an array containing all boxes used for scaling (in increasing x, y and z orders)\n */\n getScaleBoxes() {\n return this._scaleBoxesParent.getChildMeshes();\n }\n /**\n * Updates the bounding box information for the Gizmo\n */\n updateBoundingBox() {\n if (this.attachedMesh) {\n PivotTools._RemoveAndStorePivotPoint(this.attachedMesh);\n // Store original parent\n const originalParent = this.attachedMesh.parent;\n this.attachedMesh.setParent(null, Gizmo.PreserveScaling);\n this._update();\n // Rotate based on axis\n if (!this.attachedMesh.rotationQuaternion) {\n this.attachedMesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);\n }\n if (!this._anchorMesh.rotationQuaternion) {\n this._anchorMesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);\n }\n this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);\n // Store original position and reset mesh to origin before computing the bounding box\n this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);\n this._tmpVector.copyFrom(this.attachedMesh.position);\n this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);\n this.attachedMesh.position.set(0, 0, 0);\n // Update bounding dimensions/positions\n const boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);\n boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);\n // Update gizmo to match bounding box scaling and rotation\n // The position set here is the offset from the origin for the boundingbox when the attached mesh is at the origin\n // The position of the gizmo is then set to the attachedMesh in gizmo._update\n this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);\n this._lineBoundingBox.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);\n this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);\n this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);\n this._lineBoundingBox.computeWorldMatrix();\n this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);\n // Restore position/rotation values\n this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);\n this.attachedMesh.position.copyFrom(this._tmpVector);\n // Restore original parent\n this.attachedMesh.setParent(originalParent, Gizmo.PreserveScaling);\n }\n this._updateRotationSpheres();\n this._updateScaleBoxes();\n if (this.attachedMesh) {\n this._existingMeshScale.copyFrom(this.attachedMesh.scaling);\n PivotTools._RestorePivotPoint(this.attachedMesh);\n }\n }\n _updateRotationSpheres() {\n const rotateSpheres = this._rotateSpheresParent.getChildMeshes();\n for (let i = 0; i < 3; i++) {\n for (let j = 0; j < 2; j++) {\n for (let k = 0; k < 2; k++) {\n const index = i * 4 + j * 2 + k;\n if (i == 0) {\n rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);\n rotateSpheres[index].position.addInPlace(new Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));\n rotateSpheres[index].lookAt(Vector3.Cross(rotateSpheres[index].position.normalizeToNew(), Vector3.Right()).normalizeToNew().add(rotateSpheres[index].position));\n }\n if (i == 1) {\n rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);\n rotateSpheres[index].position.addInPlace(new Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));\n rotateSpheres[index].lookAt(Vector3.Cross(rotateSpheres[index].position.normalizeToNew(), Vector3.Up()).normalizeToNew().add(rotateSpheres[index].position));\n }\n if (i == 2) {\n rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);\n rotateSpheres[index].position.addInPlace(new Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));\n rotateSpheres[index].lookAt(Vector3.Cross(rotateSpheres[index].position.normalizeToNew(), Vector3.Forward()).normalizeToNew().add(rotateSpheres[index].position));\n }\n if (this.fixedDragMeshScreenSize && this.gizmoLayer.utilityLayerScene.activeCamera) {\n rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);\n const distanceFromCamera = (this.rotationSphereSize * this._tmpVector.length()) / this.fixedDragMeshScreenSizeDistanceFactor;\n rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);\n }\n else if (this.fixedDragMeshBoundsSize) {\n rotateSpheres[index].scaling.set(this.rotationSphereSize * this._boundingDimensions.x, this.rotationSphereSize * this._boundingDimensions.y, this.rotationSphereSize * this._boundingDimensions.z);\n }\n else {\n rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);\n }\n }\n }\n }\n }\n _updateScaleBoxes() {\n const scaleBoxes = this._scaleBoxesParent.getChildMeshes();\n let index = 0;\n for (let i = 0; i < 3; i++) {\n for (let j = 0; j < 3; j++) {\n for (let k = 0; k < 3; k++) {\n const zeroAxisCount = (i === 1 ? 1 : 0) + (j === 1 ? 1 : 0) + (k === 1 ? 1 : 0);\n if (zeroAxisCount === 1 || zeroAxisCount === 3) {\n continue;\n }\n if (scaleBoxes[index]) {\n scaleBoxes[index].position.set(this._boundingDimensions.x * (i / 2), this._boundingDimensions.y * (j / 2), this._boundingDimensions.z * (k / 2));\n scaleBoxes[index].position.addInPlace(new Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));\n if (this.fixedDragMeshScreenSize && this.gizmoLayer.utilityLayerScene.activeCamera) {\n scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);\n const distanceFromCamera = (this.scaleBoxSize * this._tmpVector.length()) / this.fixedDragMeshScreenSizeDistanceFactor;\n scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);\n }\n else if (this.fixedDragMeshBoundsSize) {\n scaleBoxes[index].scaling.set(this.scaleBoxSize * this._boundingDimensions.x, this.scaleBoxSize * this._boundingDimensions.y, this.scaleBoxSize * this._boundingDimensions.z);\n }\n else {\n scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);\n }\n }\n index++;\n }\n }\n }\n }\n /**\n * Enables rotation on the specified axis and disables rotation on the others\n * @param axis The list of axis that should be enabled (eg. \"xy\" or \"xyz\")\n */\n setEnabledRotationAxis(axis) {\n this._rotateSpheresParent.getChildMeshes().forEach((m, i) => {\n if (i < 4) {\n m.setEnabled(axis.indexOf(\"x\") != -1);\n }\n else if (i < 8) {\n m.setEnabled(axis.indexOf(\"y\") != -1);\n }\n else {\n m.setEnabled(axis.indexOf(\"z\") != -1);\n }\n });\n }\n /**\n * Enables/disables scaling\n * @param enable if scaling should be enabled\n * @param homogeneousScaling defines if scaling should only be homogeneous\n */\n setEnabledScaling(enable, homogeneousScaling = false) {\n this._scaleBoxesParent.getChildMeshes().forEach((m) => {\n let enableMesh = enable;\n // Disable heterogeneous scale handles if requested.\n if (homogeneousScaling && m._internalMetadata === true) {\n enableMesh = false;\n }\n m.setEnabled(enableMesh);\n });\n }\n _updateDummy() {\n if (this._dragMesh) {\n this._dragMesh.position.copyFrom(this._lineBoundingBox.getAbsolutePosition());\n this._dragMesh.scaling.copyFrom(this._lineBoundingBox.scaling);\n this._dragMesh.rotationQuaternion.copyFrom(this._rootMesh.rotationQuaternion);\n }\n }\n /**\n * Enables a pointer drag behavior on the bounding box of the gizmo\n */\n enableDragBehavior() {\n this._dragMesh = CreateBox(\"dummy\", { size: 1 }, this.gizmoLayer.utilityLayerScene);\n this._dragMesh.visibility = 0;\n this._dragMesh.rotationQuaternion = new Quaternion();\n this._pointerDragBehavior.useObjectOrientationForDragging = false;\n this._dragMesh.addBehavior(this._pointerDragBehavior);\n }\n /**\n * Disposes of the gizmo\n */\n dispose() {\n this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);\n this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);\n this._lineBoundingBox.dispose();\n this._rotateSpheresParent.dispose();\n this._scaleBoxesParent.dispose();\n if (this._dragMesh) {\n this._dragMesh.dispose();\n }\n super.dispose();\n }\n /**\n * Makes a mesh not pickable and wraps the mesh inside of a bounding box mesh that is pickable. (This is useful to avoid picking within complex geometry)\n * @param mesh the mesh to wrap in the bounding box mesh and make not pickable\n * @returns the bounding box mesh with the passed in mesh as a child\n */\n static MakeNotPickableAndWrapInBoundingBox(mesh) {\n const makeNotPickable = (root) => {\n root.isPickable = false;\n root.getChildMeshes().forEach((c) => {\n makeNotPickable(c);\n });\n };\n makeNotPickable(mesh);\n // Reset position to get bounding box from origin with no rotation\n if (!mesh.rotationQuaternion) {\n mesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);\n }\n const oldPos = mesh.position.clone();\n const oldRot = mesh.rotationQuaternion.clone();\n mesh.rotationQuaternion.set(0, 0, 0, 1);\n mesh.position.set(0, 0, 0);\n // Update bounding dimensions/positions\n const box = CreateBox(\"box\", { size: 1 }, mesh.getScene());\n const boundingMinMax = mesh.getHierarchyBoundingVectors();\n boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);\n // Adjust scale to avoid undefined behavior when adding child\n if (box.scaling.y === 0) {\n box.scaling.y = Epsilon;\n }\n if (box.scaling.x === 0) {\n box.scaling.x = Epsilon;\n }\n if (box.scaling.z === 0) {\n box.scaling.z = Epsilon;\n }\n box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);\n // Restore original positions\n mesh.addChild(box);\n mesh.rotationQuaternion.copyFrom(oldRot);\n mesh.position.copyFrom(oldPos);\n // Reverse parenting\n mesh.removeChild(box);\n box.addChild(mesh);\n box.visibility = 0;\n return box;\n }\n /**\n * CustomMeshes are not supported by this gizmo\n */\n setCustomMesh() {\n Logger.Error(\"Custom meshes are not supported on this gizmo\");\n }\n}\n//# sourceMappingURL=boundingBoxGizmo.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { Quaternion, Matrix, Vector3, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport \"../Meshes/Builders/linesBuilder.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { PointerDragBehavior } from \"../Behaviors/Meshes/pointerDragBehavior.js\";\nimport { Gizmo } from \"./gizmo.js\";\nimport { UtilityLayerRenderer } from \"../Rendering/utilityLayerRenderer.js\";\nimport { StandardMaterial } from \"../Materials/standardMaterial.js\";\nimport { ShaderMaterial } from \"../Materials/shaderMaterial.js\";\nimport { Effect } from \"../Materials/effect.js\";\nimport { CreatePlane } from \"../Meshes/Builders/planeBuilder.js\";\nimport { CreateTorus } from \"../Meshes/Builders/torusBuilder.js\";\nimport { Epsilon } from \"../Maths/math.constants.js\";\nimport { Logger } from \"../Misc/logger.js\";\n/**\n * Single plane rotation gizmo\n */\nexport class PlaneRotationGizmo extends Gizmo {\n /** Default material used to render when gizmo is not disabled or hovered */\n get coloredMaterial() {\n return this._coloredMaterial;\n }\n /** Material used to render when gizmo is hovered with mouse*/\n get hoverMaterial() {\n return this._hoverMaterial;\n }\n /** Material used to render when gizmo is disabled. typically grey.*/\n get disableMaterial() {\n return this._disableMaterial;\n }\n /**\n * Creates a PlaneRotationGizmo\n * @param planeNormal The normal of the plane which the gizmo will be able to rotate on\n * @param color The color of the gizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n * @param tessellation Amount of tessellation to be used when creating rotation circles\n * @param parent\n * @param useEulerRotation Use and update Euler angle instead of quaternion\n * @param thickness display gizmo axis thickness\n */\n constructor(planeNormal, color = Color3.Gray(), gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer, tessellation = 32, parent = null, \n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n useEulerRotation = false, thickness = 1) {\n var _a;\n super(gizmoLayer);\n this._pointerObserver = null;\n /**\n * Rotation distance in radians that the gizmo will snap to (Default: 0)\n */\n this.snapDistance = 0;\n /**\n * Event that fires each time the gizmo snaps to a new location.\n * * snapDistance is the the change in distance\n */\n this.onSnapObservable = new Observable();\n /**\n * Accumulated relative angle value for rotation on the axis. Reset to 0 when a dragStart occurs\n */\n this.angle = 0;\n this._isEnabled = true;\n this._parent = null;\n this._dragging = false;\n this._angles = new Vector3();\n this._parent = parent;\n // Create Material\n this._coloredMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._coloredMaterial.diffuseColor = color;\n this._coloredMaterial.specularColor = color.subtract(new Color3(0.1, 0.1, 0.1));\n this._hoverMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._hoverMaterial.diffuseColor = Color3.Yellow();\n this._disableMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._disableMaterial.diffuseColor = Color3.Gray();\n this._disableMaterial.alpha = 0.4;\n // Build mesh on root node\n this._gizmoMesh = new Mesh(\"\", gizmoLayer.utilityLayerScene);\n const { rotationMesh, collider } = this._createGizmoMesh(this._gizmoMesh, thickness, tessellation);\n // Setup Rotation Circle\n this._rotationDisplayPlane = CreatePlane(\"rotationDisplay\", { size: 0.6, updatable: false }, this.gizmoLayer.utilityLayerScene);\n this._rotationDisplayPlane.rotation.z = Math.PI * 0.5;\n this._rotationDisplayPlane.parent = this._gizmoMesh;\n this._rotationDisplayPlane.setEnabled(false);\n Effect.ShadersStore[\"rotationGizmoVertexShader\"] = PlaneRotationGizmo._RotationGizmoVertexShader;\n Effect.ShadersStore[\"rotationGizmoFragmentShader\"] = PlaneRotationGizmo._RotationGizmoFragmentShader;\n this._rotationShaderMaterial = new ShaderMaterial(\"shader\", this.gizmoLayer.utilityLayerScene, {\n vertex: \"rotationGizmo\",\n fragment: \"rotationGizmo\",\n }, {\n attributes: [\"position\", \"uv\"],\n uniforms: [\"worldViewProjection\", \"angles\"],\n });\n this._rotationShaderMaterial.backFaceCulling = false;\n this._rotationDisplayPlane.material = this._rotationShaderMaterial;\n this._rotationDisplayPlane.visibility = 0.999;\n this._gizmoMesh.lookAt(this._rootMesh.position.add(planeNormal));\n this._rootMesh.addChild(this._gizmoMesh, Gizmo.PreserveScaling);\n this._gizmoMesh.scaling.scaleInPlace(1 / 3);\n // Add drag behavior to handle events when the gizmo is dragged\n this.dragBehavior = new PointerDragBehavior({ dragPlaneNormal: planeNormal });\n this.dragBehavior.moveAttached = false;\n this.dragBehavior.maxDragAngle = PlaneRotationGizmo.MaxDragAngle;\n this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;\n this._rootMesh.addBehavior(this.dragBehavior);\n // Closures for drag logic\n const lastDragPosition = new Vector3();\n const rotationMatrix = new Matrix();\n const planeNormalTowardsCamera = new Vector3();\n let localPlaneNormalTowardsCamera = new Vector3();\n this.dragBehavior.onDragStartObservable.add((e) => {\n if (this.attachedNode) {\n lastDragPosition.copyFrom(e.dragPlanePoint);\n this._rotationDisplayPlane.setEnabled(true);\n this._rotationDisplayPlane.getWorldMatrix().invertToRef(rotationMatrix);\n Vector3.TransformCoordinatesToRef(e.dragPlanePoint, rotationMatrix, lastDragPosition);\n this._angles.x = Math.atan2(lastDragPosition.y, lastDragPosition.x) + Math.PI;\n this._angles.y = 0;\n this._angles.z = this.updateGizmoRotationToMatchAttachedMesh ? 1 : 0;\n this._dragging = true;\n lastDragPosition.copyFrom(e.dragPlanePoint);\n this._rotationShaderMaterial.setVector3(\"angles\", this._angles);\n this.angle = 0;\n }\n });\n this.dragBehavior.onDragEndObservable.add(() => {\n this._dragging = false;\n this._rotationDisplayPlane.setEnabled(false);\n });\n const tmpSnapEvent = { snapDistance: 0 };\n let currentSnapDragDistance = 0;\n const tmpMatrix = new Matrix();\n const amountToRotate = new Quaternion();\n this.dragBehavior.onDragObservable.add((event) => {\n if (this.attachedNode) {\n // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)\n const nodeScale = new Vector3(1, 1, 1);\n const nodeQuaternion = new Quaternion(0, 0, 0, 1);\n const nodeTranslation = new Vector3(0, 0, 0);\n this._handlePivot();\n this.attachedNode.getWorldMatrix().decompose(nodeScale, nodeQuaternion, nodeTranslation);\n // uniform scaling of absolute value of components\n // (-1,1,1) is uniform but (1,1.001,1) is not\n const uniformScaling = Math.abs(Math.abs(nodeScale.x) - Math.abs(nodeScale.y)) <= Epsilon && Math.abs(Math.abs(nodeScale.x) - Math.abs(nodeScale.z)) <= Epsilon;\n if (!uniformScaling && this.updateGizmoRotationToMatchAttachedMesh) {\n Logger.Warn(\"Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false.\");\n return;\n }\n nodeQuaternion.normalize();\n const nodeTranslationForOperation = this.updateGizmoPositionToMatchAttachedMesh ? nodeTranslation : this._rootMesh.absolutePosition;\n const newVector = event.dragPlanePoint.subtract(nodeTranslationForOperation).normalize();\n const originalVector = lastDragPosition.subtract(nodeTranslationForOperation).normalize();\n const cross = Vector3.Cross(newVector, originalVector);\n const dot = Vector3.Dot(newVector, originalVector);\n let angle = Math.atan2(cross.length(), dot);\n planeNormalTowardsCamera.copyFrom(planeNormal);\n localPlaneNormalTowardsCamera.copyFrom(planeNormal);\n if (this.updateGizmoRotationToMatchAttachedMesh) {\n nodeQuaternion.toRotationMatrix(rotationMatrix);\n localPlaneNormalTowardsCamera = Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);\n }\n // Flip up vector depending on which side the camera is on\n let cameraFlipped = false;\n if (gizmoLayer.utilityLayerScene.activeCamera) {\n const camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(nodeTranslationForOperation).normalize();\n if (Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {\n planeNormalTowardsCamera.scaleInPlace(-1);\n localPlaneNormalTowardsCamera.scaleInPlace(-1);\n cameraFlipped = true;\n }\n }\n const halfCircleSide = Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;\n if (halfCircleSide) {\n angle = -angle;\n }\n // Snapping logic\n let snapped = false;\n if (this.snapDistance != 0) {\n currentSnapDragDistance += angle;\n if (Math.abs(currentSnapDragDistance) > this.snapDistance) {\n let dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / this.snapDistance);\n if (currentSnapDragDistance < 0) {\n dragSteps *= -1;\n }\n currentSnapDragDistance = currentSnapDragDistance % this.snapDistance;\n angle = this.snapDistance * dragSteps;\n snapped = true;\n }\n else {\n angle = 0;\n }\n }\n // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)\n const quaternionCoefficient = Math.sin(angle / 2);\n amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));\n // If the meshes local scale is inverted (eg. loaded gltf file parent with z scale of -1) the rotation needs to be inverted on the y axis\n if (tmpMatrix.determinant() > 0) {\n const tmpVector = new Vector3();\n amountToRotate.toEulerAnglesToRef(tmpVector);\n Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);\n }\n if (this.updateGizmoRotationToMatchAttachedMesh) {\n // Rotate selected mesh quaternion over fixed axis\n nodeQuaternion.multiplyToRef(amountToRotate, nodeQuaternion);\n // recompose matrix\n Matrix.ComposeToRef(nodeScale, nodeQuaternion, nodeTranslation, this.attachedNode.getWorldMatrix());\n }\n else {\n // Rotate selected mesh quaternion over rotated axis\n amountToRotate.toRotationMatrix(TmpVectors.Matrix[0]);\n const translation = this.attachedNode.getWorldMatrix().getTranslation();\n this.attachedNode.getWorldMatrix().multiplyToRef(TmpVectors.Matrix[0], this.attachedNode.getWorldMatrix());\n this.attachedNode.getWorldMatrix().setTranslation(translation);\n }\n lastDragPosition.copyFrom(event.dragPlanePoint);\n if (snapped) {\n tmpSnapEvent.snapDistance = angle;\n this.onSnapObservable.notifyObservers(tmpSnapEvent);\n }\n this._angles.y += angle;\n this.angle += cameraFlipped ? -angle : angle;\n this._rotationShaderMaterial.setVector3(\"angles\", this._angles);\n this._matrixChanged();\n }\n });\n const light = gizmoLayer._getSharedGizmoLight();\n light.includedOnlyMeshes = light.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(false));\n const cache = {\n colliderMeshes: [collider],\n gizmoMeshes: [rotationMesh],\n material: this._coloredMaterial,\n hoverMaterial: this._hoverMaterial,\n disableMaterial: this._disableMaterial,\n active: false,\n dragBehavior: this.dragBehavior,\n };\n (_a = this._parent) === null || _a === void 0 ? void 0 : _a.addToAxisCache(this._gizmoMesh, cache);\n this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add((pointerInfo) => {\n var _a;\n if (this._customMeshSet) {\n return;\n }\n // updating here the maxangle because ondragstart is too late (value already used) and the updated value is not taken into account\n this.dragBehavior.maxDragAngle = PlaneRotationGizmo.MaxDragAngle;\n this._isHovered = !!(cache.colliderMeshes.indexOf((_a = pointerInfo === null || pointerInfo === void 0 ? void 0 : pointerInfo.pickInfo) === null || _a === void 0 ? void 0 : _a.pickedMesh) != -1);\n if (!this._parent) {\n const material = cache.dragBehavior.enabled ? (this._isHovered || this._dragging ? this._hoverMaterial : this._coloredMaterial) : this._disableMaterial;\n this._setGizmoMeshMaterial(cache.gizmoMeshes, material);\n }\n });\n this.dragBehavior.onEnabledObservable.add((newState) => {\n this._setGizmoMeshMaterial(cache.gizmoMeshes, newState ? this._coloredMaterial : this._disableMaterial);\n });\n }\n /**\n * Create Geometry for Gizmo\n * @param parentMesh\n * @param thickness\n * @param tessellation\n */\n _createGizmoMesh(parentMesh, thickness, tessellation) {\n const collider = CreateTorus(\"ignore\", {\n diameter: 0.6,\n thickness: 0.03 * thickness,\n tessellation,\n }, this.gizmoLayer.utilityLayerScene);\n collider.visibility = 0;\n const rotationMesh = CreateTorus(\"\", {\n diameter: 0.6,\n thickness: 0.005 * thickness,\n tessellation,\n }, this.gizmoLayer.utilityLayerScene);\n rotationMesh.material = this._coloredMaterial;\n // Position arrow pointing in its drag axis\n rotationMesh.rotation.x = Math.PI / 2;\n collider.rotation.x = Math.PI / 2;\n parentMesh.addChild(rotationMesh, Gizmo.PreserveScaling);\n parentMesh.addChild(collider, Gizmo.PreserveScaling);\n return { rotationMesh, collider };\n }\n _attachedNodeChanged(value) {\n if (this.dragBehavior) {\n this.dragBehavior.enabled = value ? true : false;\n }\n }\n /**\n * If the gizmo is enabled\n */\n set isEnabled(value) {\n this._isEnabled = value;\n if (!value) {\n this.attachedMesh = null;\n }\n else {\n if (this._parent) {\n this.attachedMesh = this._parent.attachedMesh;\n }\n }\n }\n get isEnabled() {\n return this._isEnabled;\n }\n /**\n * Disposes of the gizmo\n */\n dispose() {\n this.onSnapObservable.clear();\n this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);\n this.dragBehavior.detach();\n if (this._gizmoMesh) {\n this._gizmoMesh.dispose();\n }\n if (this._rotationDisplayPlane) {\n this._rotationDisplayPlane.dispose();\n }\n if (this._rotationShaderMaterial) {\n this._rotationShaderMaterial.dispose();\n }\n [this._coloredMaterial, this._hoverMaterial, this._disableMaterial].forEach((matl) => {\n if (matl) {\n matl.dispose();\n }\n });\n super.dispose();\n }\n}\n/**\n * The maximum angle between the camera and the rotation allowed for interaction\n * If a rotation plane appears 'flat', a lower value allows interaction.\n */\nPlaneRotationGizmo.MaxDragAngle = (Math.PI * 9) / 20;\nPlaneRotationGizmo._RotationGizmoVertexShader = `\r\n precision highp float;\r\n attribute vec3 position;\r\n attribute vec2 uv;\r\n uniform mat4 worldViewProjection;\r\n varying vec3 vPosition;\r\n varying vec2 vUV;\r\n void main(void) {\r\n gl_Position = worldViewProjection * vec4(position, 1.0);\r\n vUV = uv;\r\n }`;\nPlaneRotationGizmo._RotationGizmoFragmentShader = `\r\n precision highp float;\r\n varying vec2 vUV;\r\n varying vec3 vPosition;\r\n uniform vec3 angles;\r\n #define twopi 6.283185307\r\n void main(void) {\r\n vec2 uv = vUV - vec2(0.5);\r\n float angle = atan(uv.y, uv.x) + 3.141592;\r\n float delta = gl_FrontFacing ? angles.y : -angles.y;\r\n float begin = angles.x - delta * angles.z;\r\n float start = (begin < (begin + delta)) ? begin : (begin + delta);\r\n float end = (begin > (begin + delta)) ? begin : (begin + delta);\r\n float len = sqrt(dot(uv,uv));\r\n float opacity = 1. - step(0.5, len);\r\n\r\n float base = abs(floor(start / twopi)) * twopi;\r\n start += base;\r\n end += base;\r\n\r\n float intensity = 0.;\r\n for (int i = 0; i < 5; i++)\r\n {\r\n intensity += max(step(start, angle) - step(end, angle), 0.);\r\n angle += twopi;\r\n }\r\n gl_FragColor = vec4(1.,1.,0., min(intensity * 0.25, 0.8)) * opacity;\r\n }`;\n//# sourceMappingURL=planeRotationGizmo.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { Gizmo } from \"./gizmo.js\";\nimport { PlaneRotationGizmo } from \"./planeRotationGizmo.js\";\nimport { UtilityLayerRenderer } from \"../Rendering/utilityLayerRenderer.js\";\n/**\n * Gizmo that enables rotating a mesh along 3 axis\n */\nexport class RotationGizmo extends Gizmo {\n get attachedMesh() {\n return this._meshAttached;\n }\n set attachedMesh(mesh) {\n this._meshAttached = mesh;\n this._nodeAttached = mesh;\n this._checkBillboardTransform();\n [this.xGizmo, this.yGizmo, this.zGizmo].forEach((gizmo) => {\n if (gizmo.isEnabled) {\n gizmo.attachedMesh = mesh;\n }\n else {\n gizmo.attachedMesh = null;\n }\n });\n }\n get attachedNode() {\n return this._nodeAttached;\n }\n set attachedNode(node) {\n this._meshAttached = null;\n this._nodeAttached = node;\n this._checkBillboardTransform();\n [this.xGizmo, this.yGizmo, this.zGizmo].forEach((gizmo) => {\n if (gizmo.isEnabled) {\n gizmo.attachedNode = node;\n }\n else {\n gizmo.attachedNode = null;\n }\n });\n }\n _checkBillboardTransform() {\n if (this._nodeAttached && this._nodeAttached.billboardMode) {\n console.log(\"Rotation Gizmo will not work with transforms in billboard mode.\");\n }\n }\n /**\n * True when the mouse pointer is hovering a gizmo mesh\n */\n get isHovered() {\n let hovered = false;\n [this.xGizmo, this.yGizmo, this.zGizmo].forEach((gizmo) => {\n hovered = hovered || gizmo.isHovered;\n });\n return hovered;\n }\n /**\n * Creates a RotationGizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n * @param tessellation Amount of tessellation to be used when creating rotation circles\n * @param useEulerRotation Use and update Euler angle instead of quaternion\n * @param thickness display gizmo axis thickness\n * @param gizmoManager Gizmo manager\n * @param options More options\n */\n constructor(gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer, tessellation = 32, useEulerRotation = false, thickness = 1, gizmoManager, options) {\n super(gizmoLayer);\n /** Fires an event when any of it's sub gizmos are dragged */\n this.onDragStartObservable = new Observable();\n /** Fires an event when any of it's sub gizmos are released from dragging */\n this.onDragEndObservable = new Observable();\n this._observables = [];\n /** Node Caching for quick lookup */\n this._gizmoAxisCache = new Map();\n const xColor = options && options.xOptions && options.xOptions.color ? options.xOptions.color : Color3.Red().scale(0.5);\n const yColor = options && options.yOptions && options.yOptions.color ? options.yOptions.color : Color3.Green().scale(0.5);\n const zColor = options && options.zOptions && options.zOptions.color ? options.zOptions.color : Color3.Blue().scale(0.5);\n this.xGizmo = new PlaneRotationGizmo(new Vector3(1, 0, 0), xColor, gizmoLayer, tessellation, this, useEulerRotation, thickness);\n this.yGizmo = new PlaneRotationGizmo(new Vector3(0, 1, 0), yColor, gizmoLayer, tessellation, this, useEulerRotation, thickness);\n this.zGizmo = new PlaneRotationGizmo(new Vector3(0, 0, 1), zColor, gizmoLayer, tessellation, this, useEulerRotation, thickness);\n // Relay drag events and set update scale\n [this.xGizmo, this.yGizmo, this.zGizmo].forEach((gizmo) => {\n //must set updateScale on each gizmo, as setting it on root RotationGizmo doesnt prevent individual gizmos from updating\n //currently updateScale is a property with no getter/setter, so no good way to override behavior at runtime, so we will at least set it on startup\n if (options && options.updateScale != undefined) {\n gizmo.updateScale = options.updateScale;\n }\n gizmo.dragBehavior.onDragStartObservable.add(() => {\n this.onDragStartObservable.notifyObservers({});\n });\n gizmo.dragBehavior.onDragEndObservable.add(() => {\n this.onDragEndObservable.notifyObservers({});\n });\n });\n this.attachedMesh = null;\n this.attachedNode = null;\n if (gizmoManager) {\n gizmoManager.addToAxisCache(this._gizmoAxisCache);\n }\n else {\n // Only subscribe to pointer event if gizmoManager isnt\n Gizmo.GizmoAxisPointerObserver(gizmoLayer, this._gizmoAxisCache);\n }\n }\n /**\n * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)\n * NOTE: This is only possible for meshes with uniform scaling, as otherwise it's not possible to decompose the rotation\n */\n set updateGizmoRotationToMatchAttachedMesh(value) {\n if (this.xGizmo) {\n this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;\n this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;\n this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;\n }\n }\n get updateGizmoRotationToMatchAttachedMesh() {\n return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;\n }\n set updateGizmoPositionToMatchAttachedMesh(value) {\n if (this.xGizmo) {\n this.xGizmo.updateGizmoPositionToMatchAttachedMesh = value;\n this.yGizmo.updateGizmoPositionToMatchAttachedMesh = value;\n this.zGizmo.updateGizmoPositionToMatchAttachedMesh = value;\n }\n }\n get updateGizmoPositionToMatchAttachedMesh() {\n return this.xGizmo.updateGizmoPositionToMatchAttachedMesh;\n }\n set anchorPoint(value) {\n this._anchorPoint = value;\n [this.xGizmo, this.yGizmo, this.zGizmo].forEach((gizmo) => {\n gizmo.anchorPoint = value;\n });\n }\n get anchorPoint() {\n return this._anchorPoint;\n }\n /**\n * Set the coordinate system to use. By default it's local.\n * But it's possible for a user to tweak so its local for translation and world for rotation.\n * In that case, setting the coordinate system will change `updateGizmoRotationToMatchAttachedMesh` and `updateGizmoPositionToMatchAttachedMesh`\n */\n set coordinatesMode(coordinatesMode) {\n [this.xGizmo, this.yGizmo, this.zGizmo].forEach((gizmo) => {\n gizmo.coordinatesMode = coordinatesMode;\n });\n }\n set updateScale(value) {\n if (this.xGizmo) {\n this.xGizmo.updateScale = value;\n this.yGizmo.updateScale = value;\n this.zGizmo.updateScale = value;\n }\n }\n get updateScale() {\n return this.xGizmo.updateScale;\n }\n /**\n * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)\n */\n set snapDistance(value) {\n if (this.xGizmo) {\n this.xGizmo.snapDistance = value;\n this.yGizmo.snapDistance = value;\n this.zGizmo.snapDistance = value;\n }\n }\n get snapDistance() {\n return this.xGizmo.snapDistance;\n }\n /**\n * Ratio for the scale of the gizmo (Default: 1)\n */\n set scaleRatio(value) {\n if (this.xGizmo) {\n this.xGizmo.scaleRatio = value;\n this.yGizmo.scaleRatio = value;\n this.zGizmo.scaleRatio = value;\n }\n }\n get scaleRatio() {\n return this.xGizmo.scaleRatio;\n }\n /**\n * Builds Gizmo Axis Cache to enable features such as hover state preservation and graying out other axis during manipulation\n * @param mesh Axis gizmo mesh\n * @param cache Gizmo axis definition used for reactive gizmo UI\n */\n addToAxisCache(mesh, cache) {\n this._gizmoAxisCache.set(mesh, cache);\n }\n /**\n * Disposes of the gizmo\n */\n dispose() {\n this.xGizmo.dispose();\n this.yGizmo.dispose();\n this.zGizmo.dispose();\n this.onDragStartObservable.clear();\n this.onDragEndObservable.clear();\n this._observables.forEach((obs) => {\n this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(obs);\n });\n }\n /**\n * CustomMeshes are not supported by this gizmo\n */\n setCustomMesh() {\n Logger.Error(\"Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)\");\n }\n}\n//# sourceMappingURL=rotationGizmo.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { TransformNode } from \"../Meshes/transformNode.js\";\nimport { CreatePlane } from \"../Meshes/Builders/planeBuilder.js\";\nimport { PointerDragBehavior } from \"../Behaviors/Meshes/pointerDragBehavior.js\";\nimport { Gizmo } from \"./gizmo.js\";\nimport { UtilityLayerRenderer } from \"../Rendering/utilityLayerRenderer.js\";\nimport { StandardMaterial } from \"../Materials/standardMaterial.js\";\n/**\n * Single plane drag gizmo\n */\nexport class PlaneDragGizmo extends Gizmo {\n /** Default material used to render when gizmo is not disabled or hovered */\n get coloredMaterial() {\n return this._coloredMaterial;\n }\n /** Material used to render when gizmo is hovered with mouse*/\n get hoverMaterial() {\n return this._hoverMaterial;\n }\n /** Material used to render when gizmo is disabled. typically grey.*/\n get disableMaterial() {\n return this._disableMaterial;\n }\n /**\n * @internal\n */\n static _CreatePlane(scene, material) {\n const plane = new TransformNode(\"plane\", scene);\n //make sure plane is double sided\n const dragPlane = CreatePlane(\"dragPlane\", { width: 0.1375, height: 0.1375, sideOrientation: 2 }, scene);\n dragPlane.material = material;\n dragPlane.parent = plane;\n return plane;\n }\n /**\n * Creates a PlaneDragGizmo\n * @param dragPlaneNormal The axis normal to which the gizmo will be able to drag on\n * @param color The color of the gizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n * @param parent\n */\n constructor(dragPlaneNormal, color = Color3.Gray(), gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer, parent = null) {\n var _a;\n super(gizmoLayer);\n this._pointerObserver = null;\n /**\n * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)\n */\n this.snapDistance = 0;\n /**\n * Event that fires each time the gizmo snaps to a new location.\n * * snapDistance is the the change in distance\n */\n this.onSnapObservable = new Observable();\n this._isEnabled = false;\n this._parent = null;\n this._dragging = false;\n this._parent = parent;\n // Create Material\n this._coloredMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._coloredMaterial.diffuseColor = color;\n this._coloredMaterial.specularColor = color.subtract(new Color3(0.1, 0.1, 0.1));\n this._hoverMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._hoverMaterial.diffuseColor = Color3.Yellow();\n this._disableMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._disableMaterial.diffuseColor = Color3.Gray();\n this._disableMaterial.alpha = 0.4;\n // Build plane mesh on root node\n this._gizmoMesh = PlaneDragGizmo._CreatePlane(gizmoLayer.utilityLayerScene, this._coloredMaterial);\n this._gizmoMesh.lookAt(this._rootMesh.position.add(dragPlaneNormal));\n this._gizmoMesh.scaling.scaleInPlace(1 / 3);\n this._gizmoMesh.parent = this._rootMesh;\n let currentSnapDragDistance = 0;\n const tmpVector = new Vector3();\n const tmpSnapEvent = { snapDistance: 0 };\n // Add dragPlaneNormal drag behavior to handle events when the gizmo is dragged\n this.dragBehavior = new PointerDragBehavior({ dragPlaneNormal: dragPlaneNormal });\n this.dragBehavior.moveAttached = false;\n this._rootMesh.addBehavior(this.dragBehavior);\n this.dragBehavior.onDragObservable.add((event) => {\n if (this.attachedNode) {\n this._handlePivot();\n // Keep world translation and use it to update world transform\n // if the node has parent, the local transform properties (position, rotation, scale)\n // will be recomputed in _matrixChanged function\n // Snapping logic\n if (this.snapDistance == 0) {\n this.attachedNode.getWorldMatrix().addTranslationFromFloats(event.delta.x, event.delta.y, event.delta.z);\n }\n else {\n currentSnapDragDistance += event.dragDistance;\n if (Math.abs(currentSnapDragDistance) > this.snapDistance) {\n const dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / this.snapDistance);\n currentSnapDragDistance = currentSnapDragDistance % this.snapDistance;\n event.delta.normalizeToRef(tmpVector);\n tmpVector.scaleInPlace(this.snapDistance * dragSteps);\n this.attachedNode.getWorldMatrix().addTranslationFromFloats(tmpVector.x, tmpVector.y, tmpVector.z);\n tmpSnapEvent.snapDistance = this.snapDistance * dragSteps;\n this.onSnapObservable.notifyObservers(tmpSnapEvent);\n }\n }\n this._matrixChanged();\n }\n });\n this.dragBehavior.onDragStartObservable.add(() => {\n this._dragging = true;\n });\n this.dragBehavior.onDragEndObservable.add(() => {\n this._dragging = false;\n });\n const light = gizmoLayer._getSharedGizmoLight();\n light.includedOnlyMeshes = light.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(false));\n const cache = {\n gizmoMeshes: this._gizmoMesh.getChildMeshes(),\n colliderMeshes: this._gizmoMesh.getChildMeshes(),\n material: this._coloredMaterial,\n hoverMaterial: this._hoverMaterial,\n disableMaterial: this._disableMaterial,\n active: false,\n dragBehavior: this.dragBehavior,\n };\n (_a = this._parent) === null || _a === void 0 ? void 0 : _a.addToAxisCache(this._gizmoMesh, cache);\n this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add((pointerInfo) => {\n var _a;\n if (this._customMeshSet) {\n return;\n }\n this._isHovered = !!(cache.colliderMeshes.indexOf((_a = pointerInfo === null || pointerInfo === void 0 ? void 0 : pointerInfo.pickInfo) === null || _a === void 0 ? void 0 : _a.pickedMesh) != -1);\n if (!this._parent) {\n const material = cache.dragBehavior.enabled ? (this._isHovered || this._dragging ? this._hoverMaterial : this._coloredMaterial) : this._disableMaterial;\n this._setGizmoMeshMaterial(cache.gizmoMeshes, material);\n }\n });\n this.dragBehavior.onEnabledObservable.add((newState) => {\n this._setGizmoMeshMaterial(cache.gizmoMeshes, newState ? this._coloredMaterial : this._disableMaterial);\n });\n }\n _attachedNodeChanged(value) {\n if (this.dragBehavior) {\n this.dragBehavior.enabled = value ? true : false;\n }\n }\n /**\n * If the gizmo is enabled\n */\n set isEnabled(value) {\n this._isEnabled = value;\n if (!value) {\n this.attachedNode = null;\n }\n else {\n if (this._parent) {\n this.attachedNode = this._parent.attachedNode;\n }\n }\n }\n get isEnabled() {\n return this._isEnabled;\n }\n /**\n * Disposes of the gizmo\n */\n dispose() {\n this.onSnapObservable.clear();\n this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);\n this.dragBehavior.detach();\n super.dispose();\n if (this._gizmoMesh) {\n this._gizmoMesh.dispose();\n }\n [this._coloredMaterial, this._hoverMaterial, this._disableMaterial].forEach((matl) => {\n if (matl) {\n matl.dispose();\n }\n });\n }\n}\n//# sourceMappingURL=planeDragGizmo.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { Gizmo } from \"./gizmo.js\";\nimport { AxisDragGizmo } from \"./axisDragGizmo.js\";\nimport { PlaneDragGizmo } from \"./planeDragGizmo.js\";\nimport { UtilityLayerRenderer } from \"../Rendering/utilityLayerRenderer.js\";\n/**\n * Gizmo that enables dragging a mesh along 3 axis\n */\nexport class PositionGizmo extends Gizmo {\n get attachedMesh() {\n return this._meshAttached;\n }\n set attachedMesh(mesh) {\n this._meshAttached = mesh;\n this._nodeAttached = mesh;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => {\n if (gizmo.isEnabled) {\n gizmo.attachedMesh = mesh;\n }\n else {\n gizmo.attachedMesh = null;\n }\n });\n }\n get attachedNode() {\n return this._nodeAttached;\n }\n set attachedNode(node) {\n this._meshAttached = null;\n this._nodeAttached = node;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => {\n if (gizmo.isEnabled) {\n gizmo.attachedNode = node;\n }\n else {\n gizmo.attachedNode = null;\n }\n });\n }\n /**\n * True when the mouse pointer is hovering a gizmo mesh\n */\n get isHovered() {\n let hovered = false;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => {\n hovered = hovered || gizmo.isHovered;\n });\n return hovered;\n }\n /**\n * Creates a PositionGizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n @param thickness display gizmo axis thickness\n * @param gizmoManager\n */\n constructor(gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer, thickness = 1, gizmoManager) {\n super(gizmoLayer);\n /**\n * protected variables\n */\n this._meshAttached = null;\n this._nodeAttached = null;\n this._observables = [];\n /** Node Caching for quick lookup */\n this._gizmoAxisCache = new Map();\n /** Fires an event when any of it's sub gizmos are dragged */\n this.onDragStartObservable = new Observable();\n /** Fires an event when any of it's sub gizmos are released from dragging */\n this.onDragEndObservable = new Observable();\n /**\n * If set to true, planar drag is enabled\n */\n this._planarGizmoEnabled = false;\n this.xGizmo = new AxisDragGizmo(new Vector3(1, 0, 0), Color3.Red().scale(0.5), gizmoLayer, this, thickness);\n this.yGizmo = new AxisDragGizmo(new Vector3(0, 1, 0), Color3.Green().scale(0.5), gizmoLayer, this, thickness);\n this.zGizmo = new AxisDragGizmo(new Vector3(0, 0, 1), Color3.Blue().scale(0.5), gizmoLayer, this, thickness);\n this.xPlaneGizmo = new PlaneDragGizmo(new Vector3(1, 0, 0), Color3.Red().scale(0.5), this.gizmoLayer, this);\n this.yPlaneGizmo = new PlaneDragGizmo(new Vector3(0, 1, 0), Color3.Green().scale(0.5), this.gizmoLayer, this);\n this.zPlaneGizmo = new PlaneDragGizmo(new Vector3(0, 0, 1), Color3.Blue().scale(0.5), this.gizmoLayer, this);\n // Relay drag events\n [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => {\n gizmo.dragBehavior.onDragStartObservable.add(() => {\n this.onDragStartObservable.notifyObservers({});\n });\n gizmo.dragBehavior.onDragEndObservable.add(() => {\n this.onDragEndObservable.notifyObservers({});\n });\n });\n this.attachedMesh = null;\n if (gizmoManager) {\n gizmoManager.addToAxisCache(this._gizmoAxisCache);\n }\n else {\n // Only subscribe to pointer event if gizmoManager isnt\n Gizmo.GizmoAxisPointerObserver(gizmoLayer, this._gizmoAxisCache);\n }\n }\n /**\n * If the planar drag gizmo is enabled\n * setting this will enable/disable XY, XZ and YZ planes regardless of individual gizmo settings.\n */\n set planarGizmoEnabled(value) {\n this._planarGizmoEnabled = value;\n [this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.isEnabled = value;\n if (value) {\n if (gizmo.attachedMesh) {\n gizmo.attachedMesh = this.attachedMesh;\n }\n else {\n gizmo.attachedNode = this.attachedNode;\n }\n }\n }\n }, this);\n }\n get planarGizmoEnabled() {\n return this._planarGizmoEnabled;\n }\n /**\n * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)\n * NOTE: This is only possible for meshes with uniform scaling, as otherwise it's not possible to decompose the rotation\n */\n set updateGizmoRotationToMatchAttachedMesh(value) {\n this._updateGizmoRotationToMatchAttachedMesh = value;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.updateGizmoRotationToMatchAttachedMesh = value;\n }\n });\n }\n get updateGizmoRotationToMatchAttachedMesh() {\n return this._updateGizmoRotationToMatchAttachedMesh;\n }\n set updateGizmoPositionToMatchAttachedMesh(value) {\n this._updateGizmoPositionToMatchAttachedMesh = value;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.updateGizmoPositionToMatchAttachedMesh = value;\n }\n });\n }\n get updateGizmoPositionToMatchAttachedMesh() {\n return this._updateGizmoPositionToMatchAttachedMesh;\n }\n set anchorPoint(value) {\n this._anchorPoint = value;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => {\n gizmo.anchorPoint = value;\n });\n }\n get anchorPoint() {\n return this._anchorPoint;\n }\n /**\n * Set the coordinate system to use. By default it's local.\n * But it's possible for a user to tweak so its local for translation and world for rotation.\n * In that case, setting the coordinate system will change `updateGizmoRotationToMatchAttachedMesh` and `updateGizmoPositionToMatchAttachedMesh`\n */\n set coordinatesMode(coordinatesMode) {\n [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => {\n gizmo.coordinatesMode = coordinatesMode;\n });\n }\n set updateScale(value) {\n if (this.xGizmo) {\n this.xGizmo.updateScale = value;\n this.yGizmo.updateScale = value;\n this.zGizmo.updateScale = value;\n }\n }\n get updateScale() {\n return this.xGizmo.updateScale;\n }\n /**\n * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)\n */\n set snapDistance(value) {\n this._snapDistance = value;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.snapDistance = value;\n }\n });\n }\n get snapDistance() {\n return this._snapDistance;\n }\n /**\n * Ratio for the scale of the gizmo (Default: 1)\n */\n set scaleRatio(value) {\n this._scaleRatio = value;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.scaleRatio = value;\n }\n });\n }\n get scaleRatio() {\n return this._scaleRatio;\n }\n /**\n * Builds Gizmo Axis Cache to enable features such as hover state preservation and graying out other axis during manipulation\n * @param mesh Axis gizmo mesh\n * @param cache Gizmo axis definition used for reactive gizmo UI\n */\n addToAxisCache(mesh, cache) {\n this._gizmoAxisCache.set(mesh, cache);\n }\n /**\n * Disposes of the gizmo\n */\n dispose() {\n [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.dispose();\n }\n });\n this._observables.forEach((obs) => {\n this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(obs);\n });\n this.onDragStartObservable.clear();\n this.onDragEndObservable.clear();\n }\n /**\n * CustomMeshes are not supported by this gizmo\n */\n setCustomMesh() {\n Logger.Error(\"Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo,gizmo.xPlaneGizmo, gizmo.yPlaneGizmo, gizmo.zPlaneGizmo)\");\n }\n}\n//# sourceMappingURL=positionGizmo.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { CreatePolyhedron } from \"../Meshes/Builders/polyhedronBuilder.js\";\nimport { Gizmo } from \"./gizmo.js\";\nimport { AxisScaleGizmo } from \"./axisScaleGizmo.js\";\nimport { UtilityLayerRenderer } from \"../Rendering/utilityLayerRenderer.js\";\nimport { StandardMaterial } from \"../Materials/standardMaterial.js\";\n/**\n * Gizmo that enables scaling a mesh along 3 axis\n */\nexport class ScaleGizmo extends Gizmo {\n /** Default material used to render when gizmo is not disabled or hovered */\n get coloredMaterial() {\n return this._coloredMaterial;\n }\n /** Material used to render when gizmo is hovered with mouse*/\n get hoverMaterial() {\n return this._hoverMaterial;\n }\n /** Material used to render when gizmo is disabled. typically grey.*/\n get disableMaterial() {\n return this._disableMaterial;\n }\n get attachedMesh() {\n return this._meshAttached;\n }\n set attachedMesh(mesh) {\n this._meshAttached = mesh;\n this._nodeAttached = mesh;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => {\n if (gizmo.isEnabled) {\n gizmo.attachedMesh = mesh;\n }\n else {\n gizmo.attachedMesh = null;\n }\n });\n }\n get attachedNode() {\n return this._nodeAttached;\n }\n set attachedNode(node) {\n this._meshAttached = null;\n this._nodeAttached = node;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => {\n if (gizmo.isEnabled) {\n gizmo.attachedNode = node;\n }\n else {\n gizmo.attachedNode = null;\n }\n });\n }\n set updateScale(value) {\n if (this.xGizmo) {\n this.xGizmo.updateScale = value;\n this.yGizmo.updateScale = value;\n this.zGizmo.updateScale = value;\n }\n }\n get updateScale() {\n return this.xGizmo.updateScale;\n }\n /**\n * True when the mouse pointer is hovering a gizmo mesh\n */\n get isHovered() {\n let hovered = false;\n [this.xGizmo, this.yGizmo, this.zGizmo].forEach((gizmo) => {\n hovered = hovered || gizmo.isHovered;\n });\n return hovered;\n }\n /**\n * Creates a ScaleGizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n * @param thickness display gizmo axis thickness\n * @param gizmoManager\n */\n constructor(gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer, thickness = 1, gizmoManager) {\n super(gizmoLayer);\n this._meshAttached = null;\n this._nodeAttached = null;\n this._sensitivity = 1;\n this._observables = [];\n /** Node Caching for quick lookup */\n this._gizmoAxisCache = new Map();\n /** Fires an event when any of it's sub gizmos are dragged */\n this.onDragStartObservable = new Observable();\n /** Fires an event when any of it's sub gizmos are released from dragging */\n this.onDragEndObservable = new Observable();\n this.uniformScaleGizmo = this._createUniformScaleMesh();\n this.xGizmo = new AxisScaleGizmo(new Vector3(1, 0, 0), Color3.Red().scale(0.5), gizmoLayer, this, thickness);\n this.yGizmo = new AxisScaleGizmo(new Vector3(0, 1, 0), Color3.Green().scale(0.5), gizmoLayer, this, thickness);\n this.zGizmo = new AxisScaleGizmo(new Vector3(0, 0, 1), Color3.Blue().scale(0.5), gizmoLayer, this, thickness);\n // Relay drag events\n [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => {\n gizmo.dragBehavior.onDragStartObservable.add(() => {\n this.onDragStartObservable.notifyObservers({});\n });\n gizmo.dragBehavior.onDragEndObservable.add(() => {\n this.onDragEndObservable.notifyObservers({});\n });\n });\n this.attachedMesh = null;\n this.attachedNode = null;\n if (gizmoManager) {\n gizmoManager.addToAxisCache(this._gizmoAxisCache);\n }\n else {\n // Only subscribe to pointer event if gizmoManager isnt\n Gizmo.GizmoAxisPointerObserver(gizmoLayer, this._gizmoAxisCache);\n }\n }\n /** Create Geometry for Gizmo */\n _createUniformScaleMesh() {\n this._coloredMaterial = new StandardMaterial(\"\", this.gizmoLayer.utilityLayerScene);\n this._coloredMaterial.diffuseColor = Color3.Gray();\n this._hoverMaterial = new StandardMaterial(\"\", this.gizmoLayer.utilityLayerScene);\n this._hoverMaterial.diffuseColor = Color3.Yellow();\n this._disableMaterial = new StandardMaterial(\"\", this.gizmoLayer.utilityLayerScene);\n this._disableMaterial.diffuseColor = Color3.Gray();\n this._disableMaterial.alpha = 0.4;\n const uniformScaleGizmo = new AxisScaleGizmo(new Vector3(0, 1, 0), Color3.Gray().scale(0.5), this.gizmoLayer, this);\n uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;\n uniformScaleGizmo.uniformScaling = true;\n this._uniformScalingMesh = CreatePolyhedron(\"uniform\", { type: 1 }, uniformScaleGizmo.gizmoLayer.utilityLayerScene);\n this._uniformScalingMesh.scaling.scaleInPlace(0.01);\n this._uniformScalingMesh.visibility = 0;\n this._octahedron = CreatePolyhedron(\"\", { type: 1 }, uniformScaleGizmo.gizmoLayer.utilityLayerScene);\n this._octahedron.scaling.scaleInPlace(0.007);\n this._uniformScalingMesh.addChild(this._octahedron);\n uniformScaleGizmo.setCustomMesh(this._uniformScalingMesh, true);\n const light = this.gizmoLayer._getSharedGizmoLight();\n light.includedOnlyMeshes = light.includedOnlyMeshes.concat(this._octahedron);\n const cache = {\n gizmoMeshes: [this._octahedron, this._uniformScalingMesh],\n colliderMeshes: [this._uniformScalingMesh],\n material: this._coloredMaterial,\n hoverMaterial: this._hoverMaterial,\n disableMaterial: this._disableMaterial,\n active: false,\n dragBehavior: uniformScaleGizmo.dragBehavior,\n };\n this.addToAxisCache(uniformScaleGizmo._rootMesh, cache);\n return uniformScaleGizmo;\n }\n set updateGizmoRotationToMatchAttachedMesh(value) {\n if (!value) {\n Logger.Warn(\"Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.\");\n }\n else {\n this._updateGizmoRotationToMatchAttachedMesh = value;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.updateGizmoRotationToMatchAttachedMesh = value;\n }\n });\n }\n }\n get updateGizmoRotationToMatchAttachedMesh() {\n return this._updateGizmoRotationToMatchAttachedMesh;\n }\n set anchorPoint(value) {\n this._anchorPoint = value;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.anchorPoint = value;\n }\n });\n }\n get anchorPoint() {\n return this._anchorPoint;\n }\n /**\n * Set the coordinate system to use. By default it's local.\n * But it's possible for a user to tweak so its local for translation and world for rotation.\n * In that case, setting the coordinate system will change `updateGizmoRotationToMatchAttachedMesh` and `updateGizmoPositionToMatchAttachedMesh`\n */\n set coordinatesMode(coordinatesMode) {\n [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => {\n gizmo.coordinatesMode = coordinatesMode;\n });\n }\n /**\n * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)\n */\n set snapDistance(value) {\n this._snapDistance = value;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.snapDistance = value;\n }\n });\n }\n get snapDistance() {\n return this._snapDistance;\n }\n /**\n * Ratio for the scale of the gizmo (Default: 1)\n */\n set scaleRatio(value) {\n this._scaleRatio = value;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.scaleRatio = value;\n }\n });\n }\n get scaleRatio() {\n return this._scaleRatio;\n }\n /**\n * Sensitivity factor for dragging (Default: 1)\n */\n set sensitivity(value) {\n this._sensitivity = value;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.sensitivity = value;\n }\n });\n }\n get sensitivity() {\n return this._sensitivity;\n }\n /**\n * Builds Gizmo Axis Cache to enable features such as hover state preservation and graying out other axis during manipulation\n * @param mesh Axis gizmo mesh\n * @param cache Gizmo axis definition used for reactive gizmo UI\n */\n addToAxisCache(mesh, cache) {\n this._gizmoAxisCache.set(mesh, cache);\n }\n /**\n * Disposes of the gizmo\n */\n dispose() {\n [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.dispose();\n }\n });\n this._observables.forEach((obs) => {\n this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(obs);\n });\n this.onDragStartObservable.clear();\n this.onDragEndObservable.clear();\n [this._uniformScalingMesh, this._octahedron].forEach((msh) => {\n if (msh) {\n msh.dispose();\n }\n });\n [this._coloredMaterial, this._hoverMaterial, this._disableMaterial].forEach((matl) => {\n if (matl) {\n matl.dispose();\n }\n });\n }\n}\n//# sourceMappingURL=scaleGizmo.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { PointerEventTypes } from \"../Events/pointerEvents.js\";\nimport { AbstractMesh } from \"../Meshes/abstractMesh.js\";\nimport { UtilityLayerRenderer } from \"../Rendering/utilityLayerRenderer.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { SixDofDragBehavior } from \"../Behaviors/Meshes/sixDofDragBehavior.js\";\nimport { Gizmo, GizmoCoordinatesMode } from \"./gizmo.js\";\nimport { RotationGizmo } from \"./rotationGizmo.js\";\nimport { PositionGizmo } from \"./positionGizmo.js\";\nimport { ScaleGizmo } from \"./scaleGizmo.js\";\nimport { BoundingBoxGizmo } from \"./boundingBoxGizmo.js\";\n/**\n * Helps setup gizmo's in the scene to rotate/scale/position nodes\n */\nexport class GizmoManager {\n /**\n * Utility layer that the bounding box gizmo belongs to\n */\n get keepDepthUtilityLayer() {\n return this._defaultKeepDepthUtilityLayer;\n }\n /**\n * Utility layer that all gizmos besides bounding box belong to\n */\n get utilityLayer() {\n return this._defaultUtilityLayer;\n }\n /**\n * True when the mouse pointer is hovering a gizmo mesh\n */\n get isHovered() {\n let hovered = false;\n for (const key in this.gizmos) {\n const gizmo = this.gizmos[key];\n if (gizmo && gizmo.isHovered) {\n hovered = true;\n break;\n }\n }\n return hovered;\n }\n /**\n * Ratio for the scale of the gizmo (Default: 1)\n */\n set scaleRatio(value) {\n this._scaleRatio = value;\n [this.gizmos.positionGizmo, this.gizmos.rotationGizmo, this.gizmos.scaleGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.scaleRatio = value;\n }\n });\n }\n get scaleRatio() {\n return this._scaleRatio;\n }\n /**\n * Set the coordinate system to use. By default it's local.\n * But it's possible for a user to tweak so its local for translation and world for rotation.\n * In that case, setting the coordinate system will change `updateGizmoRotationToMatchAttachedMesh` and `updateGizmoPositionToMatchAttachedMesh`\n */\n set coordinatesMode(coordinatesMode) {\n this._coordinatesMode = coordinatesMode;\n [this.gizmos.positionGizmo, this.gizmos.rotationGizmo, this.gizmos.scaleGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.coordinatesMode = coordinatesMode;\n }\n });\n }\n get coordinatesMode() {\n return this._coordinatesMode;\n }\n /**\n * Instantiates a gizmo manager\n * @param _scene the scene to overlay the gizmos on top of\n * @param thickness display gizmo axis thickness\n * @param utilityLayer the layer where gizmos are rendered\n * @param keepDepthUtilityLayer the layer where occluded gizmos are rendered\n */\n constructor(_scene, thickness = 1, utilityLayer = UtilityLayerRenderer.DefaultUtilityLayer, keepDepthUtilityLayer = UtilityLayerRenderer.DefaultKeepDepthUtilityLayer) {\n this._scene = _scene;\n /** When true, the gizmo will be detached from the current object when a pointer down occurs with an empty picked mesh */\n this.clearGizmoOnEmptyPointerEvent = false;\n /** When true (default), picking to attach a new mesh is enabled. This works in sync with inspector autopicking. */\n this.enableAutoPicking = true;\n /** Fires an event when the manager is attached to a mesh */\n this.onAttachedToMeshObservable = new Observable();\n /** Fires an event when the manager is attached to a node */\n this.onAttachedToNodeObservable = new Observable();\n this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };\n this._pointerObservers = [];\n this._attachedMesh = null;\n this._attachedNode = null;\n this._boundingBoxColor = Color3.FromHexString(\"#0984e3\");\n this._thickness = 1;\n this._scaleRatio = 1;\n this._coordinatesMode = GizmoCoordinatesMode.Local;\n /** Node Caching for quick lookup */\n this._gizmoAxisCache = new Map();\n /**\n * When bounding box gizmo is enabled, this can be used to track drag/end events\n */\n this.boundingBoxDragBehavior = new SixDofDragBehavior();\n /**\n * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)\n */\n this.attachableMeshes = null;\n /**\n * Array of nodes which will have the gizmo attached when a pointer selected them. If null, all nodes are attachable. (Default: null)\n */\n this.attachableNodes = null;\n /**\n * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh/attachToNode. (Default: true)\n */\n this.usePointerToAttachGizmos = true;\n this._defaultUtilityLayer = utilityLayer;\n this._defaultKeepDepthUtilityLayer = keepDepthUtilityLayer;\n this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;\n this._thickness = thickness;\n this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };\n const attachToMeshPointerObserver = this._attachToMeshPointerObserver(_scene);\n const gizmoAxisPointerObserver = Gizmo.GizmoAxisPointerObserver(this._defaultUtilityLayer, this._gizmoAxisCache);\n this._pointerObservers = [attachToMeshPointerObserver, gizmoAxisPointerObserver];\n }\n /**\n * Subscribes to pointer down events, for attaching and detaching mesh\n * @param scene The scene layer the observer will be added to\n */\n _attachToMeshPointerObserver(scene) {\n // Instantiate/dispose gizmos based on pointer actions\n const pointerObserver = scene.onPointerObservable.add((pointerInfo) => {\n if (!this.usePointerToAttachGizmos) {\n return;\n }\n if (pointerInfo.type == PointerEventTypes.POINTERDOWN) {\n if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {\n if (this.enableAutoPicking) {\n let node = pointerInfo.pickInfo.pickedMesh;\n if (this.attachableMeshes == null) {\n // Attach to the most parent node\n while (node && node.parent != null) {\n node = node.parent;\n }\n }\n else {\n // Attach to the parent node that is an attachableMesh\n let found = false;\n this.attachableMeshes.forEach((mesh) => {\n if (node && (node == mesh || node.isDescendantOf(mesh))) {\n node = mesh;\n found = true;\n }\n });\n if (!found) {\n node = null;\n }\n }\n if (node instanceof AbstractMesh) {\n if (this._attachedMesh != node) {\n this.attachToMesh(node);\n }\n }\n else {\n if (this.clearGizmoOnEmptyPointerEvent) {\n this.attachToMesh(null);\n }\n }\n }\n }\n else {\n if (this.clearGizmoOnEmptyPointerEvent) {\n this.attachToMesh(null);\n }\n }\n }\n });\n return pointerObserver;\n }\n /**\n * Attaches a set of gizmos to the specified mesh\n * @param mesh The mesh the gizmo's should be attached to\n */\n attachToMesh(mesh) {\n if (this._attachedMesh) {\n this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);\n }\n if (this._attachedNode) {\n this._attachedNode.removeBehavior(this.boundingBoxDragBehavior);\n }\n this._attachedMesh = mesh;\n this._attachedNode = null;\n for (const key in this.gizmos) {\n const gizmo = this.gizmos[key];\n if (gizmo && this._gizmosEnabled[key]) {\n gizmo.attachedMesh = mesh;\n }\n }\n if (this.boundingBoxGizmoEnabled && this._attachedMesh) {\n this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);\n }\n this.onAttachedToMeshObservable.notifyObservers(mesh);\n }\n /**\n * Attaches a set of gizmos to the specified node\n * @param node The node the gizmo's should be attached to\n */\n attachToNode(node) {\n if (this._attachedMesh) {\n this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);\n }\n if (this._attachedNode) {\n this._attachedNode.removeBehavior(this.boundingBoxDragBehavior);\n }\n this._attachedMesh = null;\n this._attachedNode = node;\n for (const key in this.gizmos) {\n const gizmo = this.gizmos[key];\n if (gizmo && this._gizmosEnabled[key]) {\n gizmo.attachedNode = node;\n }\n }\n if (this.boundingBoxGizmoEnabled && this._attachedNode) {\n this._attachedNode.addBehavior(this.boundingBoxDragBehavior);\n }\n this.onAttachedToNodeObservable.notifyObservers(node);\n }\n /**\n * If the position gizmo is enabled\n */\n set positionGizmoEnabled(value) {\n if (value) {\n if (!this.gizmos.positionGizmo) {\n this.gizmos.positionGizmo = new PositionGizmo(this._defaultUtilityLayer, this._thickness, this);\n }\n if (this._attachedNode) {\n this.gizmos.positionGizmo.attachedNode = this._attachedNode;\n }\n else {\n this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;\n }\n }\n else if (this.gizmos.positionGizmo) {\n this.gizmos.positionGizmo.attachedNode = null;\n }\n this._gizmosEnabled.positionGizmo = value;\n }\n get positionGizmoEnabled() {\n return this._gizmosEnabled.positionGizmo;\n }\n /**\n * If the rotation gizmo is enabled\n */\n set rotationGizmoEnabled(value) {\n if (value) {\n if (!this.gizmos.rotationGizmo) {\n this.gizmos.rotationGizmo = new RotationGizmo(this._defaultUtilityLayer, 32, false, this._thickness, this);\n }\n if (this._attachedNode) {\n this.gizmos.rotationGizmo.attachedNode = this._attachedNode;\n }\n else {\n this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;\n }\n }\n else if (this.gizmos.rotationGizmo) {\n this.gizmos.rotationGizmo.attachedNode = null;\n }\n this._gizmosEnabled.rotationGizmo = value;\n }\n get rotationGizmoEnabled() {\n return this._gizmosEnabled.rotationGizmo;\n }\n /**\n * If the scale gizmo is enabled\n */\n set scaleGizmoEnabled(value) {\n if (value) {\n this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new ScaleGizmo(this._defaultUtilityLayer, this._thickness, this);\n if (this._attachedNode) {\n this.gizmos.scaleGizmo.attachedNode = this._attachedNode;\n }\n else {\n this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;\n }\n }\n else if (this.gizmos.scaleGizmo) {\n this.gizmos.scaleGizmo.attachedNode = null;\n }\n this._gizmosEnabled.scaleGizmo = value;\n }\n get scaleGizmoEnabled() {\n return this._gizmosEnabled.scaleGizmo;\n }\n /**\n * If the boundingBox gizmo is enabled\n */\n set boundingBoxGizmoEnabled(value) {\n if (value) {\n this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BoundingBoxGizmo(this._boundingBoxColor, this._defaultKeepDepthUtilityLayer);\n if (this._attachedMesh) {\n this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;\n }\n else {\n this.gizmos.boundingBoxGizmo.attachedNode = this._attachedNode;\n }\n if (this._attachedMesh) {\n this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);\n this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);\n }\n else if (this._attachedNode) {\n this._attachedNode.removeBehavior(this.boundingBoxDragBehavior);\n this._attachedNode.addBehavior(this.boundingBoxDragBehavior);\n }\n }\n else if (this.gizmos.boundingBoxGizmo) {\n if (this._attachedMesh) {\n this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);\n }\n else if (this._attachedNode) {\n this._attachedNode.removeBehavior(this.boundingBoxDragBehavior);\n }\n this.gizmos.boundingBoxGizmo.attachedNode = null;\n }\n this._gizmosEnabled.boundingBoxGizmo = value;\n }\n get boundingBoxGizmoEnabled() {\n return this._gizmosEnabled.boundingBoxGizmo;\n }\n /**\n * Builds Gizmo Axis Cache to enable features such as hover state preservation and graying out other axis during manipulation\n * @param gizmoAxisCache Gizmo axis definition used for reactive gizmo UI\n */\n addToAxisCache(gizmoAxisCache) {\n if (gizmoAxisCache.size > 0) {\n gizmoAxisCache.forEach((v, k) => {\n this._gizmoAxisCache.set(k, v);\n });\n }\n }\n /**\n * Disposes of the gizmo manager\n */\n dispose() {\n var _a, _b;\n this._pointerObservers.forEach((observer) => {\n this._scene.onPointerObservable.remove(observer);\n });\n for (const key in this.gizmos) {\n const gizmo = this.gizmos[key];\n if (gizmo) {\n gizmo.dispose();\n }\n }\n if (this._defaultKeepDepthUtilityLayer !== UtilityLayerRenderer._DefaultKeepDepthUtilityLayer) {\n (_a = this._defaultKeepDepthUtilityLayer) === null || _a === void 0 ? void 0 : _a.dispose();\n }\n if (this._defaultUtilityLayer !== UtilityLayerRenderer._DefaultUtilityLayer) {\n (_b = this._defaultUtilityLayer) === null || _b === void 0 ? void 0 : _b.dispose();\n }\n this.boundingBoxDragBehavior.detach();\n this.onAttachedToMeshObservable.clear();\n }\n}\n//# sourceMappingURL=gizmoManager.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize, serializeAsTexture } from \"../Misc/decorators.js\";\nimport { Matrix, Vector3 } from \"../Maths/math.vector.js\";\nimport { Node } from \"../node.js\";\nimport { Light } from \"./light.js\";\nimport { ShadowLight } from \"./shadowLight.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nNode.AddNodeConstructor(\"Light_Type_2\", (name, scene) => {\n return () => new SpotLight(name, Vector3.Zero(), Vector3.Zero(), 0, 0, scene);\n});\n/**\n * A spot light is defined by a position, a direction, an angle, and an exponent.\n * These values define a cone of light starting from the position, emitting toward the direction.\n * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,\n * and the exponent defines the speed of the decay of the light with distance (reach).\n * Documentation: https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction\n */\nexport class SpotLight extends ShadowLight {\n /**\n * Gets the cone angle of the spot light in Radians.\n */\n get angle() {\n return this._angle;\n }\n /**\n * Sets the cone angle of the spot light in Radians.\n */\n set angle(value) {\n this._angle = value;\n this._cosHalfAngle = Math.cos(value * 0.5);\n this._projectionTextureProjectionLightDirty = true;\n this.forceProjectionMatrixCompute();\n this._computeAngleValues();\n }\n /**\n * Only used in gltf falloff mode, this defines the angle where\n * the directional falloff will start before cutting at angle which could be seen\n * as outer angle.\n */\n get innerAngle() {\n return this._innerAngle;\n }\n /**\n * Only used in gltf falloff mode, this defines the angle where\n * the directional falloff will start before cutting at angle which could be seen\n * as outer angle.\n */\n set innerAngle(value) {\n this._innerAngle = value;\n this._computeAngleValues();\n }\n /**\n * Allows scaling the angle of the light for shadow generation only.\n */\n get shadowAngleScale() {\n return this._shadowAngleScale;\n }\n /**\n * Allows scaling the angle of the light for shadow generation only.\n */\n set shadowAngleScale(value) {\n this._shadowAngleScale = value;\n this.forceProjectionMatrixCompute();\n }\n /**\n * Allows reading the projection texture\n */\n get projectionTextureMatrix() {\n return this._projectionTextureMatrix;\n }\n /**\n * Gets the near clip of the Spotlight for texture projection.\n */\n get projectionTextureLightNear() {\n return this._projectionTextureLightNear;\n }\n /**\n * Sets the near clip of the Spotlight for texture projection.\n */\n set projectionTextureLightNear(value) {\n this._projectionTextureLightNear = value;\n this._projectionTextureProjectionLightDirty = true;\n }\n /**\n * Gets the far clip of the Spotlight for texture projection.\n */\n get projectionTextureLightFar() {\n return this._projectionTextureLightFar;\n }\n /**\n * Sets the far clip of the Spotlight for texture projection.\n */\n set projectionTextureLightFar(value) {\n this._projectionTextureLightFar = value;\n this._projectionTextureProjectionLightDirty = true;\n }\n /**\n * Gets the Up vector of the Spotlight for texture projection.\n */\n get projectionTextureUpDirection() {\n return this._projectionTextureUpDirection;\n }\n /**\n * Sets the Up vector of the Spotlight for texture projection.\n */\n set projectionTextureUpDirection(value) {\n this._projectionTextureUpDirection = value;\n this._projectionTextureProjectionLightDirty = true;\n }\n /**\n * Gets the projection texture of the light.\n */\n get projectionTexture() {\n return this._projectionTexture;\n }\n /**\n * Sets the projection texture of the light.\n */\n set projectionTexture(value) {\n if (this._projectionTexture === value) {\n return;\n }\n this._projectionTexture = value;\n this._projectionTextureDirty = true;\n if (this._projectionTexture && !this._projectionTexture.isReady()) {\n if (SpotLight._IsProceduralTexture(this._projectionTexture)) {\n this._projectionTexture.getEffect().executeWhenCompiled(() => {\n this._markMeshesAsLightDirty();\n });\n }\n else if (SpotLight._IsTexture(this._projectionTexture)) {\n this._projectionTexture.onLoadObservable.addOnce(() => {\n this._markMeshesAsLightDirty();\n });\n }\n }\n }\n static _IsProceduralTexture(texture) {\n return texture.onGeneratedObservable !== undefined;\n }\n static _IsTexture(texture) {\n return texture.onLoadObservable !== undefined;\n }\n /**\n * Gets or sets the light projection matrix as used by the projection texture\n */\n get projectionTextureProjectionLightMatrix() {\n return this._projectionTextureProjectionLightMatrix;\n }\n set projectionTextureProjectionLightMatrix(projection) {\n this._projectionTextureProjectionLightMatrix = projection;\n this._projectionTextureProjectionLightDirty = false;\n this._projectionTextureDirty = true;\n }\n /**\n * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.\n * It can cast shadows.\n * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction\n * @param name The light friendly name\n * @param position The position of the spot light in the scene\n * @param direction The direction of the light in the scene\n * @param angle The cone angle of the light in Radians\n * @param exponent The light decay speed with the distance from the emission spot\n * @param scene The scene the lights belongs to\n */\n constructor(name, position, direction, angle, exponent, scene) {\n super(name, scene);\n this._innerAngle = 0;\n this._projectionTextureMatrix = Matrix.Zero();\n this._projectionTextureLightNear = 1e-6;\n this._projectionTextureLightFar = 1000.0;\n this._projectionTextureUpDirection = Vector3.Up();\n this._projectionTextureViewLightDirty = true;\n this._projectionTextureProjectionLightDirty = true;\n this._projectionTextureDirty = true;\n this._projectionTextureViewTargetVector = Vector3.Zero();\n this._projectionTextureViewLightMatrix = Matrix.Zero();\n this._projectionTextureProjectionLightMatrix = Matrix.Zero();\n this._projectionTextureScalingMatrix = Matrix.FromValues(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);\n this.position = position;\n this.direction = direction;\n this.angle = angle;\n this.exponent = exponent;\n }\n /**\n * Returns the string \"SpotLight\".\n * @returns the class name\n */\n getClassName() {\n return \"SpotLight\";\n }\n /**\n * Returns the integer 2.\n * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x\n */\n getTypeID() {\n return Light.LIGHTTYPEID_SPOTLIGHT;\n }\n /**\n * Overrides the direction setter to recompute the projection texture view light Matrix.\n * @param value\n */\n _setDirection(value) {\n super._setDirection(value);\n this._projectionTextureViewLightDirty = true;\n }\n /**\n * Overrides the position setter to recompute the projection texture view light Matrix.\n * @param value\n */\n _setPosition(value) {\n super._setPosition(value);\n this._projectionTextureViewLightDirty = true;\n }\n /**\n * Sets the passed matrix \"matrix\" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0.\n * Returns the SpotLight.\n * @param matrix\n * @param viewMatrix\n * @param renderList\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList) {\n const activeCamera = this.getScene().activeCamera;\n if (!activeCamera) {\n return;\n }\n this._shadowAngleScale = this._shadowAngleScale || 1;\n const angle = this._shadowAngleScale * this._angle;\n const minZ = this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;\n const maxZ = this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;\n const useReverseDepthBuffer = this.getScene().getEngine().useReverseDepthBuffer;\n Matrix.PerspectiveFovLHToRef(angle, 1.0, useReverseDepthBuffer ? maxZ : minZ, useReverseDepthBuffer ? minZ : maxZ, matrix, true, this._scene.getEngine().isNDCHalfZRange, undefined, useReverseDepthBuffer);\n }\n _computeProjectionTextureViewLightMatrix() {\n this._projectionTextureViewLightDirty = false;\n this._projectionTextureDirty = true;\n this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);\n Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);\n }\n _computeProjectionTextureProjectionLightMatrix() {\n this._projectionTextureProjectionLightDirty = false;\n this._projectionTextureDirty = true;\n const lightFar = this.projectionTextureLightFar;\n const lightNear = this.projectionTextureLightNear;\n const P = lightFar / (lightFar - lightNear);\n const Q = -P * lightNear;\n const S = 1.0 / Math.tan(this._angle / 2.0);\n const A = 1.0;\n Matrix.FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, this._projectionTextureProjectionLightMatrix);\n }\n /**\n * Main function for light texture projection matrix computing.\n */\n _computeProjectionTextureMatrix() {\n this._projectionTextureDirty = false;\n this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);\n if (this._projectionTexture instanceof Texture) {\n const u = this._projectionTexture.uScale / 2.0;\n const v = this._projectionTexture.vScale / 2.0;\n Matrix.FromValuesToRef(u, 0.0, 0.0, 0.0, 0.0, v, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0, this._projectionTextureScalingMatrix);\n }\n this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);\n }\n _buildUniformLayout() {\n this._uniformBuffer.addUniform(\"vLightData\", 4);\n this._uniformBuffer.addUniform(\"vLightDiffuse\", 4);\n this._uniformBuffer.addUniform(\"vLightSpecular\", 4);\n this._uniformBuffer.addUniform(\"vLightDirection\", 3);\n this._uniformBuffer.addUniform(\"vLightFalloff\", 4);\n this._uniformBuffer.addUniform(\"shadowsInfo\", 3);\n this._uniformBuffer.addUniform(\"depthValues\", 2);\n this._uniformBuffer.create();\n }\n _computeAngleValues() {\n this._lightAngleScale = 1.0 / Math.max(0.001, Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle);\n this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;\n }\n /**\n * Sets the passed Effect \"effect\" with the Light textures.\n * @param effect The effect to update\n * @param lightIndex The index of the light in the effect to update\n * @returns The light\n */\n transferTexturesToEffect(effect, lightIndex) {\n if (this.projectionTexture && this.projectionTexture.isReady()) {\n if (this._projectionTextureViewLightDirty) {\n this._computeProjectionTextureViewLightMatrix();\n }\n if (this._projectionTextureProjectionLightDirty) {\n this._computeProjectionTextureProjectionLightMatrix();\n }\n if (this._projectionTextureDirty) {\n this._computeProjectionTextureMatrix();\n }\n effect.setMatrix(\"textureProjectionMatrix\" + lightIndex, this._projectionTextureMatrix);\n effect.setTexture(\"projectionLightSampler\" + lightIndex, this.projectionTexture);\n }\n return this;\n }\n /**\n * Sets the passed Effect object with the SpotLight transformed position (or position if not parented) and normalized direction.\n * @param effect The effect to update\n * @param lightIndex The index of the light in the effect to update\n * @returns The spot light\n */\n transferToEffect(effect, lightIndex) {\n let normalizeDirection;\n if (this.computeTransformedInformation()) {\n this._uniformBuffer.updateFloat4(\"vLightData\", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);\n normalizeDirection = Vector3.Normalize(this.transformedDirection);\n }\n else {\n this._uniformBuffer.updateFloat4(\"vLightData\", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);\n normalizeDirection = Vector3.Normalize(this.direction);\n }\n this._uniformBuffer.updateFloat4(\"vLightDirection\", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);\n this._uniformBuffer.updateFloat4(\"vLightFalloff\", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);\n return this;\n }\n transferToNodeMaterialEffect(effect, lightDataUniformName) {\n let normalizeDirection;\n if (this.computeTransformedInformation()) {\n normalizeDirection = Vector3.Normalize(this.transformedDirection);\n }\n else {\n normalizeDirection = Vector3.Normalize(this.direction);\n }\n if (this.getScene().useRightHandedSystem) {\n effect.setFloat3(lightDataUniformName, -normalizeDirection.x, -normalizeDirection.y, -normalizeDirection.z);\n }\n else {\n effect.setFloat3(lightDataUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z);\n }\n return this;\n }\n /**\n * Disposes the light and the associated resources.\n */\n dispose() {\n super.dispose();\n if (this._projectionTexture) {\n this._projectionTexture.dispose();\n }\n }\n /**\n * Gets the minZ used for shadow according to both the scene and the light.\n * @param activeCamera The camera we are returning the min for\n * @returns the depth min z\n */\n getDepthMinZ(activeCamera) {\n const engine = this._scene.getEngine();\n const minZ = this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;\n return engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? minZ : this._scene.getEngine().isNDCHalfZRange ? 0 : minZ;\n }\n /**\n * Gets the maxZ used for shadow according to both the scene and the light.\n * @param activeCamera The camera we are returning the max for\n * @returns the depth max z\n */\n getDepthMaxZ(activeCamera) {\n const engine = this._scene.getEngine();\n const maxZ = this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;\n return engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : maxZ;\n }\n /**\n * Prepares the list of defines specific to the light type.\n * @param defines the list of defines\n * @param lightIndex defines the index of the light for the effect\n */\n prepareLightSpecificDefines(defines, lightIndex) {\n defines[\"SPOTLIGHT\" + lightIndex] = true;\n defines[\"PROJECTEDLIGHTTEXTURE\" + lightIndex] = this.projectionTexture && this.projectionTexture.isReady() ? true : false;\n }\n}\n__decorate([\n serialize()\n], SpotLight.prototype, \"angle\", null);\n__decorate([\n serialize()\n], SpotLight.prototype, \"innerAngle\", null);\n__decorate([\n serialize()\n], SpotLight.prototype, \"shadowAngleScale\", null);\n__decorate([\n serialize()\n], SpotLight.prototype, \"exponent\", void 0);\n__decorate([\n serialize()\n], SpotLight.prototype, \"projectionTextureLightNear\", null);\n__decorate([\n serialize()\n], SpotLight.prototype, \"projectionTextureLightFar\", null);\n__decorate([\n serialize()\n], SpotLight.prototype, \"projectionTextureUpDirection\", null);\n__decorate([\n serializeAsTexture(\"projectedLightTexture\")\n], SpotLight.prototype, \"_projectionTexture\", void 0);\n//# sourceMappingURL=spotLight.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize, serializeAsMatrix, SerializationHelper, serializeAsVector3 } from \"../../Misc/decorators.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nimport { Matrix, TmpVectors, Vector3 } from \"../../Maths/math.vector.js\";\nimport { BaseTexture } from \"../../Materials/Textures/baseTexture.js\";\nimport { Texture } from \"../../Materials/Textures/texture.js\";\n\nimport { GetClass, RegisterClass } from \"../../Misc/typeStore.js\";\nimport \"../../Engines/Extensions/engine.cubeTexture.js\";\nimport { Observable } from \"../../Misc/observable.js\";\n/**\n * Class for creating a cube texture\n */\nexport class CubeTexture extends BaseTexture {\n /**\n * Gets or sets the size of the bounding box associated with the cube texture\n * When defined, the cubemap will switch to local mode\n * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity\n * @example https://www.babylonjs-playground.com/#RNASML\n */\n set boundingBoxSize(value) {\n if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {\n return;\n }\n this._boundingBoxSize = value;\n const scene = this.getScene();\n if (scene) {\n scene.markAllMaterialsAsDirty(1);\n }\n }\n /**\n * Returns the bounding box size\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#using-local-cubemap-mode\n */\n get boundingBoxSize() {\n return this._boundingBoxSize;\n }\n /**\n * Sets texture matrix rotation angle around Y axis in radians.\n */\n set rotationY(value) {\n this._rotationY = value;\n this.setReflectionTextureMatrix(Matrix.RotationY(this._rotationY));\n }\n /**\n * Gets texture matrix rotation angle around Y axis radians.\n */\n get rotationY() {\n return this._rotationY;\n }\n /**\n * Are mip maps generated for this texture or not.\n */\n get noMipmap() {\n return this._noMipmap;\n }\n /**\n * Gets the forced extension (if any)\n */\n get forcedExtension() {\n return this._forcedExtension;\n }\n /**\n * Creates a cube texture from an array of image urls\n * @param files defines an array of image urls\n * @param scene defines the hosting scene\n * @param noMipmap specifies if mip maps are not used\n * @returns a cube texture\n */\n static CreateFromImages(files, scene, noMipmap) {\n let rootUrlKey = \"\";\n files.forEach((url) => (rootUrlKey += url));\n return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);\n }\n /**\n * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.\n * @param url defines the url of the prefiltered texture\n * @param scene defines the scene the texture is attached to\n * @param forcedExtension defines the extension of the file if different from the url\n * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary\n * @returns the prefiltered texture\n */\n static CreateFromPrefilteredData(url, scene, forcedExtension = null, createPolynomials = true) {\n const oldValue = scene.useDelayedTextureLoading;\n scene.useDelayedTextureLoading = false;\n const result = new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);\n scene.useDelayedTextureLoading = oldValue;\n return result;\n }\n /**\n * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well\n * as prefiltered data.\n * @param rootUrl defines the url of the texture or the root name of the six images\n * @param sceneOrEngine defines the scene or engine the texture is attached to\n * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...\n * @param noMipmap defines if mipmaps should be created or not\n * @param files defines the six files to load for the different faces in that order: px, py, pz, nx, ny, nz\n * @param onLoad defines a callback triggered at the end of the file load if no errors occurred\n * @param onError defines a callback triggered in case of error during load\n * @param format defines the internal format to use for the texture once loaded\n * @param prefiltered defines whether or not the texture is created from prefiltered data\n * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name\n * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary\n * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness\n * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness\n * @param loaderOptions options to be passed to the loader\n * @param useSRGBBuffer Defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU) (default: false)\n * @returns the cube texture\n */\n constructor(rootUrl, sceneOrEngine, extensions = null, noMipmap = false, files = null, onLoad = null, onError = null, format = 5, prefiltered = false, forcedExtension = null, createPolynomials = false, lodScale = 0.8, lodOffset = 0, loaderOptions, useSRGBBuffer) {\n var _a;\n super(sceneOrEngine);\n this._lodScale = 0.8;\n this._lodOffset = 0;\n /**\n * Observable triggered once the texture has been loaded.\n */\n this.onLoadObservable = new Observable();\n /**\n * Gets or sets the center of the bounding box associated with the cube texture.\n * It must define where the camera used to render the texture was set\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#using-local-cubemap-mode\n */\n this.boundingBoxPosition = Vector3.Zero();\n this._rotationY = 0;\n /** @internal */\n this._files = null;\n this._forcedExtension = null;\n this._extensions = null;\n this._textureMatrixRefraction = new Matrix();\n this.name = rootUrl;\n this.url = rootUrl;\n this._noMipmap = noMipmap;\n this.hasAlpha = false;\n this._format = format;\n this.isCube = true;\n this._textureMatrix = Matrix.Identity();\n this._createPolynomials = createPolynomials;\n this.coordinatesMode = Texture.CUBIC_MODE;\n this._extensions = extensions;\n this._files = files;\n this._forcedExtension = forcedExtension;\n this._loaderOptions = loaderOptions;\n this._useSRGBBuffer = useSRGBBuffer;\n this._lodScale = lodScale;\n this._lodOffset = lodOffset;\n if (!rootUrl && !files) {\n return;\n }\n this.updateURL(rootUrl, forcedExtension, onLoad, prefiltered, onError, extensions, (_a = this.getScene()) === null || _a === void 0 ? void 0 : _a.useDelayedTextureLoading, files);\n }\n /**\n * Get the current class name of the texture useful for serialization or dynamic coding.\n * @returns \"CubeTexture\"\n */\n getClassName() {\n return \"CubeTexture\";\n }\n /**\n * Update the url (and optional buffer) of this texture if url was null during construction.\n * @param url the url of the texture\n * @param forcedExtension defines the extension to use\n * @param onLoad callback called when the texture is loaded (defaults to null)\n * @param prefiltered Defines whether the updated texture is prefiltered or not\n * @param onError callback called if there was an error during the loading process (defaults to null)\n * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...\n * @param delayLoad defines if the texture should be loaded now (false by default)\n * @param files defines the six files to load for the different faces in that order: px, py, pz, nx, ny, nz\n */\n updateURL(url, forcedExtension, onLoad = null, prefiltered = false, onError = null, extensions = null, delayLoad = false, files = null) {\n if (!this.name || this.name.startsWith(\"data:\")) {\n this.name = url;\n }\n this.url = url;\n if (forcedExtension) {\n this._forcedExtension = forcedExtension;\n }\n const lastDot = url.lastIndexOf(\".\");\n const extension = forcedExtension ? forcedExtension : lastDot > -1 ? url.substring(lastDot).toLowerCase() : \"\";\n const isDDS = extension.indexOf(\".dds\") === 0;\n const isEnv = extension.indexOf(\".env\") === 0;\n const isBasis = extension.indexOf(\".basis\") === 0;\n if (isEnv) {\n this.gammaSpace = false;\n this._prefiltered = false;\n this.anisotropicFilteringLevel = 1;\n }\n else {\n this._prefiltered = prefiltered;\n if (prefiltered) {\n this.gammaSpace = false;\n this.anisotropicFilteringLevel = 1;\n }\n }\n if (files) {\n this._files = files;\n }\n else {\n if (!isBasis && !isEnv && !isDDS && !extensions) {\n extensions = [\"_px.jpg\", \"_py.jpg\", \"_pz.jpg\", \"_nx.jpg\", \"_ny.jpg\", \"_nz.jpg\"];\n }\n this._files = this._files || [];\n this._files.length = 0;\n if (extensions) {\n for (let index = 0; index < extensions.length; index++) {\n this._files.push(url + extensions[index]);\n }\n this._extensions = extensions;\n }\n }\n if (delayLoad) {\n this.delayLoadState = 4;\n this._delayedOnLoad = onLoad;\n this._delayedOnError = onError;\n }\n else {\n this._loadTexture(onLoad, onError);\n }\n }\n /**\n * Delays loading of the cube texture\n * @param forcedExtension defines the extension to use\n */\n delayLoad(forcedExtension) {\n if (this.delayLoadState !== 4) {\n return;\n }\n if (forcedExtension) {\n this._forcedExtension = forcedExtension;\n }\n this.delayLoadState = 1;\n this._loadTexture(this._delayedOnLoad, this._delayedOnError);\n }\n /**\n * Returns the reflection texture matrix\n * @returns the reflection texture matrix\n */\n getReflectionTextureMatrix() {\n return this._textureMatrix;\n }\n /**\n * Sets the reflection texture matrix\n * @param value Reflection texture matrix\n */\n setReflectionTextureMatrix(value) {\n var _a, _b;\n if (value.updateFlag === this._textureMatrix.updateFlag) {\n return;\n }\n if (value.isIdentity() !== this._textureMatrix.isIdentity()) {\n (_a = this.getScene()) === null || _a === void 0 ? void 0 : _a.markAllMaterialsAsDirty(1, (mat) => mat.getActiveTextures().indexOf(this) !== -1);\n }\n this._textureMatrix = value;\n if (!((_b = this.getScene()) === null || _b === void 0 ? void 0 : _b.useRightHandedSystem)) {\n return;\n }\n const scale = TmpVectors.Vector3[0];\n const quat = TmpVectors.Quaternion[0];\n const trans = TmpVectors.Vector3[1];\n this._textureMatrix.decompose(scale, quat, trans);\n quat.z *= -1; // these two operations correspond to negating the x and y euler angles\n quat.w *= -1;\n Matrix.ComposeToRef(scale, quat, trans, this._textureMatrixRefraction);\n }\n /**\n * Gets a suitable rotate/transform matrix when the texture is used for refraction.\n * There's a separate function from getReflectionTextureMatrix because refraction requires a special configuration of the matrix in right-handed mode.\n * @returns The refraction matrix\n */\n getRefractionTextureMatrix() {\n var _a;\n return ((_a = this.getScene()) === null || _a === void 0 ? void 0 : _a.useRightHandedSystem) ? this._textureMatrixRefraction : this._textureMatrix;\n }\n _loadTexture(onLoad = null, onError = null) {\n var _a;\n const scene = this.getScene();\n const oldTexture = this._texture;\n this._texture = this._getFromCache(this.url, this._noMipmap, undefined, undefined, this._useSRGBBuffer, this.isCube);\n const onLoadProcessing = () => {\n var _a;\n this.onLoadObservable.notifyObservers(this);\n if (oldTexture) {\n oldTexture.dispose();\n (_a = this.getScene()) === null || _a === void 0 ? void 0 : _a.markAllMaterialsAsDirty(1);\n }\n if (onLoad) {\n onLoad();\n }\n };\n const errorHandler = (message, exception) => {\n this._loadingError = true;\n this._errorObject = { message, exception };\n if (onError) {\n onError(message, exception);\n }\n Texture.OnTextureLoadErrorObservable.notifyObservers(this);\n };\n if (!this._texture) {\n if (this._prefiltered) {\n this._texture = this._getEngine().createPrefilteredCubeTexture(this.url, scene, this._lodScale, this._lodOffset, onLoad, errorHandler, this._format, this._forcedExtension, this._createPolynomials);\n }\n else {\n this._texture = this._getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, onLoad, errorHandler, this._format, this._forcedExtension, false, this._lodScale, this._lodOffset, null, this._loaderOptions, !!this._useSRGBBuffer);\n }\n (_a = this._texture) === null || _a === void 0 ? void 0 : _a.onLoadedObservable.add(() => this.onLoadObservable.notifyObservers(this));\n }\n else {\n if (this._texture.isReady) {\n Tools.SetImmediate(() => onLoadProcessing());\n }\n else {\n this._texture.onLoadedObservable.add(() => onLoadProcessing());\n }\n }\n }\n /**\n * Parses text to create a cube texture\n * @param parsedTexture define the serialized text to read from\n * @param scene defines the hosting scene\n * @param rootUrl defines the root url of the cube texture\n * @returns a cube texture\n */\n static Parse(parsedTexture, scene, rootUrl) {\n const texture = SerializationHelper.Parse(() => {\n var _a;\n let prefiltered = false;\n if (parsedTexture.prefiltered) {\n prefiltered = parsedTexture.prefiltered;\n }\n return new CubeTexture(rootUrl + ((_a = parsedTexture.url) !== null && _a !== void 0 ? _a : parsedTexture.name), scene, parsedTexture.extensions, false, parsedTexture.files || null, null, null, undefined, prefiltered, parsedTexture.forcedExtension);\n }, parsedTexture, scene);\n // Local Cubemaps\n if (parsedTexture.boundingBoxPosition) {\n texture.boundingBoxPosition = Vector3.FromArray(parsedTexture.boundingBoxPosition);\n }\n if (parsedTexture.boundingBoxSize) {\n texture.boundingBoxSize = Vector3.FromArray(parsedTexture.boundingBoxSize);\n }\n // Animations\n if (parsedTexture.animations) {\n for (let animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {\n const parsedAnimation = parsedTexture.animations[animationIndex];\n const internalClass = GetClass(\"BABYLON.Animation\");\n if (internalClass) {\n texture.animations.push(internalClass.Parse(parsedAnimation));\n }\n }\n }\n return texture;\n }\n /**\n * Makes a clone, or deep copy, of the cube texture\n * @returns a new cube texture\n */\n clone() {\n let uniqueId = 0;\n const newCubeTexture = SerializationHelper.Clone(() => {\n const cubeTexture = new CubeTexture(this.url, this.getScene() || this._getEngine(), this._extensions, this._noMipmap, this._files);\n uniqueId = cubeTexture.uniqueId;\n return cubeTexture;\n }, this);\n newCubeTexture.uniqueId = uniqueId;\n return newCubeTexture;\n }\n}\n__decorate([\n serialize()\n], CubeTexture.prototype, \"url\", void 0);\n__decorate([\n serializeAsVector3()\n], CubeTexture.prototype, \"boundingBoxPosition\", void 0);\n__decorate([\n serializeAsVector3()\n], CubeTexture.prototype, \"boundingBoxSize\", null);\n__decorate([\n serialize(\"rotationY\")\n], CubeTexture.prototype, \"rotationY\", null);\n__decorate([\n serialize(\"files\")\n], CubeTexture.prototype, \"_files\", void 0);\n__decorate([\n serialize(\"forcedExtension\")\n], CubeTexture.prototype, \"_forcedExtension\", void 0);\n__decorate([\n serialize(\"extensions\")\n], CubeTexture.prototype, \"_extensions\", void 0);\n__decorate([\n serializeAsMatrix(\"textureMatrix\")\n], CubeTexture.prototype, \"_textureMatrix\", void 0);\n__decorate([\n serializeAsMatrix(\"textureMatrixRefraction\")\n], CubeTexture.prototype, \"_textureMatrixRefraction\", void 0);\nTexture._CubeTextureParser = CubeTexture.Parse;\n// Some exporters relies on Tools.Instantiate\nRegisterClass(\"BABYLON.CubeTexture\", CubeTexture);\n//# sourceMappingURL=cubeTexture.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"backgroundFragmentDeclaration\";\nconst shader = `uniform vec4 vEyePosition;\runiform vec4 vPrimaryColor;\r#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\r#endif\nuniform float shadowLevel;\runiform float alpha;\r#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\r#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\runiform mat4 reflectionMatrix;\runiform vec3 vReflectionMicrosurfaceInfos;\r#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\r#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\r#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const backgroundFragmentDeclaration = { name, shader };\n//# sourceMappingURL=backgroundFragmentDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nimport \"./sceneUboDeclaration.js\";\nconst name = \"backgroundUboDeclaration\";\nconst shader = `layout(std140,column_major) uniform;\runiform Material\r{\runiform vec4 vPrimaryColor;\runiform vec4 vPrimaryColorShadow;\runiform vec2 vDiffuseInfos;\runiform vec2 vReflectionInfos;\runiform mat4 diffuseMatrix;\runiform mat4 reflectionMatrix;\runiform vec3 vReflectionMicrosurfaceInfos;\runiform float fFovMultiplier;\runiform float pointSize;\runiform float shadowLevel;\runiform float alpha;\r#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\r#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\r#endif\n};\r#include\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const backgroundUboDeclaration = { name, shader };\n//# sourceMappingURL=backgroundUboDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/backgroundFragmentDeclaration.js\";\nimport \"./ShadersInclude/backgroundUboDeclaration.js\";\nimport \"./ShadersInclude/helperFunctions.js\";\nimport \"./ShadersInclude/reflectionFunction.js\";\nimport \"./ShadersInclude/imageProcessingDeclaration.js\";\nimport \"./ShadersInclude/lightFragmentDeclaration.js\";\nimport \"./ShadersInclude/lightUboDeclaration.js\";\nimport \"./ShadersInclude/lightsFragmentFunctions.js\";\nimport \"./ShadersInclude/shadowsFragmentFunctions.js\";\nimport \"./ShadersInclude/imageProcessingFunctions.js\";\nimport \"./ShadersInclude/clipPlaneFragmentDeclaration.js\";\nimport \"./ShadersInclude/fogFragmentDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneFragment.js\";\nimport \"./ShadersInclude/lightFragment.js\";\nimport \"./ShadersInclude/fogFragment.js\";\nconst name = \"backgroundPixelShader\";\nconst shader = `#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\r#include<__decl__backgroundFragment>\n#include\n#define RECIPROCAL_PI2 0.15915494\nvarying vec3 vPositionW;\r#ifdef MAINUV1\nvarying vec2 vMainUV1;\r#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \r#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\r#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV==1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV==2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\r#endif\nuniform sampler2D diffuseSampler;\r#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\r#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\runiform samplerCube reflectionSamplerHigh;\r#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\r#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\runiform samplerCube reflectionSamplerHigh;\r#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\r#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\r#endif\n#endif\n#include\n#endif\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include\n#include\n#include\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\r{\rfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\rreturn reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));\r}\r#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\r#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\r#else\nvec3 normalW=vec3(0.0,1.0,0.0);\r#endif\nfloat shadow=1.;\rfloat globalShadow=0.;\rfloat shadowLightCount=0.;\r#include[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\r#else\nglobalShadow=1.0;\r#endif\n#ifndef BACKMAT_SHADOWONLY\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\r#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\r#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\r#endif\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\r#else\nvec2 reflectionCoords=reflectionVector.xy;\r#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\r#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\r#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\r#ifdef TEXTURELODSUPPORT\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\rreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\r#else\nfloat lodReflectionNormalized=saturate(reflectionLOD);\rfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\rvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\rif(lodReflectionNormalizedDoubled<1.0){\rreflectionColor=mix(\rsampleReflection(reflectionSamplerHigh,reflectionCoords),\rreflectionSpecularMid,\rlodReflectionNormalizedDoubled\r);\r} else {\rreflectionColor=mix(\rreflectionSpecularMid,\rsampleReflection(reflectionSamplerLow,reflectionCoords),\rlodReflectionNormalizedDoubled-1.0\r);\r}\r#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\rreflectionColor=reflectionSample;\r#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\r#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\r#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\r#endif\nreflectionColor.rgb*=vReflectionInfos.x;\r#endif\nvec3 diffuseColor=vec3(1.,1.,1.);\rfloat finalAlpha=alpha;\r#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\r#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\r#endif\ndiffuseMap.rgb*=vDiffuseInfos.y;\r#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\r#endif\ndiffuseColor=diffuseMap.rgb;\r#endif\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\r#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\r#endif\ncolorBase=max(colorBase,0.0);\r#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\r#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\r#else\nvec3 mainColor=vPrimaryColor.rgb;\r#endif\nvec3 finalColor=colorBase*mainColor;\r#endif\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\rvec3 reflectionReflectance0=vReflectionControl.yyy;\rvec3 reflectionReflectance90=vReflectionControl.zzz;\rfloat VdotN=dot(normalize(vEyePosition.xyz),normalW);\rvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);\rreflectionAmount*=planarReflectionFresnel;\r#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);\rreflectionDistanceFalloff*=reflectionDistanceFalloff;\rreflectionAmount*=reflectionDistanceFalloff;\r#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount));\r#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));\rconst float startAngle=0.1;\rfloat fadeFactor=saturate(viewAngleToFloor/startAngle);\rfinalAlpha*=fadeFactor*fadeFactor;\r#endif\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\r#endif\nvec4 color=vec4(finalColor,finalAlpha);\r#else\nvec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha);\r#endif\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n#if !defined(SKIPFINALCOLORCLAMP)\ncolor.rgb=clamp(color.rgb,0.,30.0);\r#endif\n#else\ncolor=applyImageProcessing(color);\r#endif\n#ifdef PREMULTIPLYALPHA\ncolor.rgb*=color.a;\r#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\rcolor=max(color,0.0);\r#endif\ngl_FragColor=color;\r#define CUSTOM_FRAGMENT_MAIN_END\n}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const backgroundPixelShader = { name, shader };\n//# sourceMappingURL=background.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"backgroundVertexDeclaration\";\nconst shader = `uniform mat4 view;\runiform mat4 viewProjection;\runiform float shadowLevel;\r#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\runiform vec2 vDiffuseInfos;\r#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\runiform mat4 reflectionMatrix;\runiform vec3 vReflectionMicrosurfaceInfos;\runiform float fFovMultiplier;\r#endif\n#ifdef POINTSIZE\nuniform float pointSize;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const backgroundVertexDeclaration = { name, shader };\n//# sourceMappingURL=backgroundVertexDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/backgroundVertexDeclaration.js\";\nimport \"./ShadersInclude/backgroundUboDeclaration.js\";\nimport \"./ShadersInclude/helperFunctions.js\";\nimport \"./ShadersInclude/bonesDeclaration.js\";\nimport \"./ShadersInclude/bakedVertexAnimationDeclaration.js\";\nimport \"./ShadersInclude/instancesDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneVertexDeclaration.js\";\nimport \"./ShadersInclude/fogVertexDeclaration.js\";\nimport \"./ShadersInclude/lightVxFragmentDeclaration.js\";\nimport \"./ShadersInclude/lightVxUboDeclaration.js\";\nimport \"./ShadersInclude/instancesVertex.js\";\nimport \"./ShadersInclude/bonesVertex.js\";\nimport \"./ShadersInclude/bakedVertexAnimation.js\";\nimport \"./ShadersInclude/clipPlaneVertex.js\";\nimport \"./ShadersInclude/fogVertex.js\";\nimport \"./ShadersInclude/shadowsVertex.js\";\nconst name = \"backgroundVertexShader\";\nconst shader = `precision highp float;\r#include<__decl__backgroundVertex>\n#include\nattribute vec3 position;\r#ifdef NORMAL\nattribute vec3 normal;\r#endif\n#include\n#include\n#include\nvarying vec3 vPositionW;\r#ifdef NORMAL\nvarying vec3 vNormalW;\r#endif\n#ifdef UV1\nattribute vec2 uv;\r#endif\n#ifdef UV2\nattribute vec2 uv2;\r#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\r#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\r#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nvarying vec2 vDiffuseUV;\r#endif\n#include\n#include\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\r#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\r#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_VERTEX_MAIN_BEGIN\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\r#endif\n#include\n#include\n#include\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {\rgl_Position=viewProjection*finalWorld*vec4(position,1.0);\r} else {\rgl_Position=viewProjectionR*finalWorld*vec4(position,1.0);\r}\r#else\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\r#endif\nvec4 worldPos=finalWorld*vec4(position,1.0);\rvPositionW=vec3(worldPos);\r#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\r#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\r#endif\nvNormalW=normalize(normalWorld*normal);\r#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\r#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\rvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\rif (fFovMultiplier<=1.0) {\rvDirectionW=normalize(segment);\r} else {\rvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\r}\r#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\r#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\r#endif\n#ifdef MAINUV1\nvMainUV1=uv;\r#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\r#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nif (vDiffuseInfos.x==0.)\r{\rvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\r}\relse\r{\rvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\r}\r#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\nvColor=color;\r#endif\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\r#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const backgroundVertexShader = { name, shader };\n//# sourceMappingURL=background.vertex.js.map","import { __decorate } from \"../../tslib.es6.js\";\n/* eslint-disable @typescript-eslint/naming-convention */\nimport { SerializationHelper, serialize, serializeAsColor3, expandToProperty, serializeAsTexture, serializeAsVector3, serializeAsImageProcessingConfiguration, } from \"../../Misc/decorators.js\";\nimport { SmartArray } from \"../../Misc/smartArray.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { Vector3, Vector4 } from \"../../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../../Buffers/buffer.js\";\nimport { MaterialHelper } from \"../../Materials/materialHelper.js\";\nimport { MaterialDefines } from \"../../Materials/materialDefines.js\";\nimport { PushMaterial } from \"../../Materials/pushMaterial.js\";\nimport { ImageProcessingConfiguration } from \"../../Materials/imageProcessingConfiguration.js\";\nimport { Texture } from \"../../Materials/Textures/texture.js\";\n\nimport { RegisterClass } from \"../../Misc/typeStore.js\";\nimport { MaterialFlags } from \"../materialFlags.js\";\nimport { Color3 } from \"../../Maths/math.color.js\";\nimport \"../../Shaders/background.fragment.js\";\nimport \"../../Shaders/background.vertex.js\";\nimport { EffectFallbacks } from \"../effectFallbacks.js\";\nimport { addClipPlaneUniforms, bindClipPlane } from \"../clipPlaneMaterialHelper.js\";\n/**\n * Background material defines definition.\n * @internal Mainly internal Use\n */\nclass BackgroundMaterialDefines extends MaterialDefines {\n /**\n * Constructor of the defines.\n */\n constructor() {\n super();\n /**\n * True if the diffuse texture is in use.\n */\n this.DIFFUSE = false;\n /**\n * The direct UV channel to use.\n */\n this.DIFFUSEDIRECTUV = 0;\n /**\n * True if the diffuse texture is in gamma space.\n */\n this.GAMMADIFFUSE = false;\n /**\n * True if the diffuse texture has opacity in the alpha channel.\n */\n this.DIFFUSEHASALPHA = false;\n /**\n * True if you want the material to fade to transparent at grazing angle.\n */\n this.OPACITYFRESNEL = false;\n /**\n * True if an extra blur needs to be added in the reflection.\n */\n this.REFLECTIONBLUR = false;\n /**\n * True if you want the material to fade to reflection at grazing angle.\n */\n this.REFLECTIONFRESNEL = false;\n /**\n * True if you want the material to falloff as far as you move away from the scene center.\n */\n this.REFLECTIONFALLOFF = false;\n /**\n * False if the current Webgl implementation does not support the texture lod extension.\n */\n this.TEXTURELODSUPPORT = false;\n /**\n * True to ensure the data are premultiplied.\n */\n this.PREMULTIPLYALPHA = false;\n /**\n * True if the texture contains cooked RGB values and not gray scaled multipliers.\n */\n this.USERGBCOLOR = false;\n /**\n * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color\n * stays aligned with the desired configuration.\n */\n this.USEHIGHLIGHTANDSHADOWCOLORS = false;\n /**\n * True if only shadows must be rendered\n */\n this.BACKMAT_SHADOWONLY = false;\n /**\n * True to add noise in order to reduce the banding effect.\n */\n this.NOISE = false;\n /**\n * is the reflection texture in BGR color scheme?\n * Mainly used to solve a bug in ios10 video tag\n */\n this.REFLECTIONBGR = false;\n this.IMAGEPROCESSING = false;\n this.VIGNETTE = false;\n this.VIGNETTEBLENDMODEMULTIPLY = false;\n this.VIGNETTEBLENDMODEOPAQUE = false;\n this.TONEMAPPING = false;\n this.TONEMAPPING_ACES = false;\n this.CONTRAST = false;\n this.COLORCURVES = false;\n this.COLORGRADING = false;\n this.COLORGRADING3D = false;\n this.SAMPLER3DGREENDEPTH = false;\n this.SAMPLER3DBGRMAP = false;\n this.DITHER = false;\n this.IMAGEPROCESSINGPOSTPROCESS = false;\n this.SKIPFINALCOLORCLAMP = false;\n this.EXPOSURE = false;\n this.MULTIVIEW = false;\n // Reflection.\n this.REFLECTION = false;\n this.REFLECTIONMAP_3D = false;\n this.REFLECTIONMAP_SPHERICAL = false;\n this.REFLECTIONMAP_PLANAR = false;\n this.REFLECTIONMAP_CUBIC = false;\n this.REFLECTIONMAP_PROJECTION = false;\n this.REFLECTIONMAP_SKYBOX = false;\n this.REFLECTIONMAP_EXPLICIT = false;\n this.REFLECTIONMAP_EQUIRECTANGULAR = false;\n this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;\n this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;\n this.INVERTCUBICMAP = false;\n this.REFLECTIONMAP_OPPOSITEZ = false;\n this.LODINREFLECTIONALPHA = false;\n this.GAMMAREFLECTION = false;\n this.RGBDREFLECTION = false;\n this.EQUIRECTANGULAR_RELFECTION_FOV = false;\n // Default BJS.\n this.MAINUV1 = false;\n this.MAINUV2 = false;\n this.UV1 = false;\n this.UV2 = false;\n this.CLIPPLANE = false;\n this.CLIPPLANE2 = false;\n this.CLIPPLANE3 = false;\n this.CLIPPLANE4 = false;\n this.CLIPPLANE5 = false;\n this.CLIPPLANE6 = false;\n this.POINTSIZE = false;\n this.FOG = false;\n this.NORMAL = false;\n this.NUM_BONE_INFLUENCERS = 0;\n this.BonesPerMesh = 0;\n this.INSTANCES = false;\n this.SHADOWFLOAT = false;\n this.LOGARITHMICDEPTH = false;\n this.NONUNIFORMSCALING = false;\n this.ALPHATEST = false;\n this.rebuild();\n }\n}\n/**\n * Background material used to create an efficient environment around your scene.\n */\nexport class BackgroundMaterial extends PushMaterial {\n /**\n * Experimental Internal Use Only.\n *\n * Key light Color in \"perceptual value\" meaning the color you would like to see on screen.\n * This acts as a helper to set the primary color to a more \"human friendly\" value.\n * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the\n * output color as close as possible from the chosen value.\n * (This does not account for contrast color grading and color curves as they are considered post effect and not directly\n * part of lighting setup.)\n */\n get _perceptualColor() {\n return this.__perceptualColor;\n }\n set _perceptualColor(value) {\n this.__perceptualColor = value;\n this._computePrimaryColorFromPerceptualColor();\n this._markAllSubMeshesAsLightsDirty();\n }\n /**\n * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.\n * The color opposite to the primary color is used at the level chosen to define what the black area would look.\n */\n get primaryColorShadowLevel() {\n return this._primaryColorShadowLevel;\n }\n set primaryColorShadowLevel(value) {\n this._primaryColorShadowLevel = value;\n this._computePrimaryColors();\n this._markAllSubMeshesAsLightsDirty();\n }\n /**\n * Defines the level of the highlights (highlight area of the reflection map) in order to help scaling the colors.\n * The primary color is used at the level chosen to define what the white area would look.\n */\n get primaryColorHighlightLevel() {\n return this._primaryColorHighlightLevel;\n }\n set primaryColorHighlightLevel(value) {\n this._primaryColorHighlightLevel = value;\n this._computePrimaryColors();\n this._markAllSubMeshesAsLightsDirty();\n }\n /**\n * Sets the reflection reflectance fresnel values according to the default standard\n * empirically know to work well :-)\n */\n set reflectionStandardFresnelWeight(value) {\n let reflectionWeight = value;\n if (reflectionWeight < 0.5) {\n reflectionWeight = reflectionWeight * 2.0;\n this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;\n this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;\n }\n else {\n reflectionWeight = reflectionWeight * 2.0 - 1.0;\n this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;\n this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;\n }\n }\n /**\n * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values \"zoom in\" and higher values \"zoom out\".\n * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.\n * Recommended to be keep at 1.0 except for special cases.\n */\n get fovMultiplier() {\n return this._fovMultiplier;\n }\n set fovMultiplier(value) {\n if (isNaN(value)) {\n value = 1.0;\n }\n this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));\n }\n /**\n * Attaches a new image processing configuration to the PBR Material.\n * @param configuration (if null the scene configuration will be use)\n */\n _attachImageProcessingConfiguration(configuration) {\n if (configuration === this._imageProcessingConfiguration) {\n return;\n }\n // Detaches observer.\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n // Pick the scene configuration if needed.\n if (!configuration) {\n this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;\n }\n else {\n this._imageProcessingConfiguration = configuration;\n }\n // Attaches observer.\n if (this._imageProcessingConfiguration) {\n this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => {\n this._computePrimaryColorFromPerceptualColor();\n this._markAllSubMeshesAsImageProcessingDirty();\n });\n }\n }\n /**\n * Gets the image processing configuration used either in this material.\n */\n get imageProcessingConfiguration() {\n return this._imageProcessingConfiguration;\n }\n /**\n * Sets the Default image processing configuration used either in the this material.\n *\n * If sets to null, the scene one is in use.\n */\n set imageProcessingConfiguration(value) {\n this._attachImageProcessingConfiguration(value);\n // Ensure the effect will be rebuilt.\n this._markAllSubMeshesAsTexturesDirty();\n }\n /**\n * Gets whether the color curves effect is enabled.\n */\n get cameraColorCurvesEnabled() {\n return this.imageProcessingConfiguration.colorCurvesEnabled;\n }\n /**\n * Sets whether the color curves effect is enabled.\n */\n set cameraColorCurvesEnabled(value) {\n this.imageProcessingConfiguration.colorCurvesEnabled = value;\n }\n /**\n * Gets whether the color grading effect is enabled.\n */\n get cameraColorGradingEnabled() {\n return this.imageProcessingConfiguration.colorGradingEnabled;\n }\n /**\n * Gets whether the color grading effect is enabled.\n */\n set cameraColorGradingEnabled(value) {\n this.imageProcessingConfiguration.colorGradingEnabled = value;\n }\n /**\n * Gets whether tonemapping is enabled or not.\n */\n get cameraToneMappingEnabled() {\n return this._imageProcessingConfiguration.toneMappingEnabled;\n }\n /**\n * Sets whether tonemapping is enabled or not\n */\n set cameraToneMappingEnabled(value) {\n this._imageProcessingConfiguration.toneMappingEnabled = value;\n }\n /**\n * The camera exposure used on this material.\n * This property is here and not in the camera to allow controlling exposure without full screen post process.\n * This corresponds to a photographic exposure.\n */\n get cameraExposure() {\n return this._imageProcessingConfiguration.exposure;\n }\n /**\n * The camera exposure used on this material.\n * This property is here and not in the camera to allow controlling exposure without full screen post process.\n * This corresponds to a photographic exposure.\n */\n set cameraExposure(value) {\n this._imageProcessingConfiguration.exposure = value;\n }\n /**\n * Gets The camera contrast used on this material.\n */\n get cameraContrast() {\n return this._imageProcessingConfiguration.contrast;\n }\n /**\n * Sets The camera contrast used on this material.\n */\n set cameraContrast(value) {\n this._imageProcessingConfiguration.contrast = value;\n }\n /**\n * Gets the Color Grading 2D Lookup Texture.\n */\n get cameraColorGradingTexture() {\n return this._imageProcessingConfiguration.colorGradingTexture;\n }\n /**\n * Sets the Color Grading 2D Lookup Texture.\n */\n set cameraColorGradingTexture(value) {\n this.imageProcessingConfiguration.colorGradingTexture = value;\n }\n /**\n * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\n get cameraColorCurves() {\n return this.imageProcessingConfiguration.colorCurves;\n }\n /**\n * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\n set cameraColorCurves(value) {\n this.imageProcessingConfiguration.colorCurves = value;\n }\n /**\n * Instantiates a Background Material in the given scene\n * @param name The friendly name of the material\n * @param scene The scene to add the material to\n */\n constructor(name, scene) {\n super(name, scene);\n /**\n * Key light Color (multiply against the environment texture)\n */\n this.primaryColor = Color3.White();\n this._primaryColorShadowLevel = 0;\n this._primaryColorHighlightLevel = 0;\n /**\n * Reflection Texture used in the material.\n * Should be author in a specific way for the best result (refer to the documentation).\n */\n this.reflectionTexture = null;\n /**\n * Reflection Texture level of blur.\n *\n * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the\n * texture twice.\n */\n this.reflectionBlur = 0;\n /**\n * Diffuse Texture used in the material.\n * Should be author in a specific way for the best result (refer to the documentation).\n */\n this.diffuseTexture = null;\n this._shadowLights = null;\n /**\n * Specify the list of lights casting shadow on the material.\n * All scene shadow lights will be included if null.\n */\n this.shadowLights = null;\n /**\n * Helps adjusting the shadow to a softer level if required.\n * 0 means black shadows and 1 means no shadows.\n */\n this.shadowLevel = 0;\n /**\n * In case of opacity Fresnel or reflection falloff, this is use as a scene center.\n * It is usually zero but might be interesting to modify according to your setup.\n */\n this.sceneCenter = Vector3.Zero();\n /**\n * This helps specifying that the material is falling off to the sky box at grazing angle.\n * This helps ensuring a nice transition when the camera goes under the ground.\n */\n this.opacityFresnel = true;\n /**\n * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.\n * This helps adding a mirror texture on the ground.\n */\n this.reflectionFresnel = false;\n /**\n * This helps specifying the falloff radius off the reflection texture from the sceneCenter.\n * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.\n */\n this.reflectionFalloffDistance = 0.0;\n /**\n * This specifies the weight of the reflection against the background in case of reflection Fresnel.\n */\n this.reflectionAmount = 1.0;\n /**\n * This specifies the weight of the reflection at grazing angle.\n */\n this.reflectionReflectance0 = 0.05;\n /**\n * This specifies the weight of the reflection at a perpendicular point of view.\n */\n this.reflectionReflectance90 = 0.5;\n /**\n * Helps to directly use the maps channels instead of their level.\n */\n this.useRGBColor = true;\n /**\n * This helps reducing the banding effect that could occur on the background.\n */\n this.enableNoise = false;\n this._fovMultiplier = 1.0;\n /**\n * Enable the FOV adjustment feature controlled by fovMultiplier.\n */\n this.useEquirectangularFOV = false;\n this._maxSimultaneousLights = 4;\n /**\n * Number of Simultaneous lights allowed on the material.\n */\n this.maxSimultaneousLights = 4;\n this._shadowOnly = false;\n /**\n * Make the material only render shadows\n */\n this.shadowOnly = false;\n /**\n * Keep track of the image processing observer to allow dispose and replace.\n */\n this._imageProcessingObserver = null;\n /**\n * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.\n * Setting this flag to true (not done automatically!) will convert it back to RGB.\n */\n this.switchToBGR = false;\n // Temp values kept as cache in the material.\n this._renderTargets = new SmartArray(16);\n this._reflectionControls = Vector4.Zero();\n this._white = Color3.White();\n this._primaryShadowColor = Color3.Black();\n this._primaryHighlightColor = Color3.Black();\n // Setup the default processing configuration to the scene.\n this._attachImageProcessingConfiguration(null);\n this.getRenderTargetTextures = () => {\n this._renderTargets.reset();\n if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {\n this._renderTargets.push(this._diffuseTexture);\n }\n if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {\n this._renderTargets.push(this._reflectionTexture);\n }\n return this._renderTargets;\n };\n }\n /**\n * Gets a boolean indicating that current material needs to register RTT\n */\n get hasRenderTargetTextures() {\n if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {\n return true;\n }\n if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {\n return true;\n }\n return false;\n }\n /**\n * The entire material has been created in order to prevent overdraw.\n * @returns false\n */\n needAlphaTesting() {\n return true;\n }\n /**\n * The entire material has been created in order to prevent overdraw.\n * @returns true if blending is enable\n */\n needAlphaBlending() {\n return this.alpha < 1 || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha) || this._shadowOnly;\n }\n /**\n * Checks whether the material is ready to be rendered for a given mesh.\n * @param mesh The mesh to render\n * @param subMesh The submesh to check against\n * @param useInstances Specify wether or not the material is used with instances\n * @returns true if all the dependencies are ready (Textures, Effects...)\n */\n isReadyForSubMesh(mesh, subMesh, useInstances = false) {\n if (subMesh.effect && this.isFrozen) {\n if (subMesh.effect._wasPreviouslyReady && subMesh.effect._wasPreviouslyUsingInstances === useInstances) {\n return true;\n }\n }\n if (!subMesh.materialDefines) {\n subMesh.materialDefines = new BackgroundMaterialDefines();\n }\n const scene = this.getScene();\n const defines = subMesh.materialDefines;\n if (this._isReadyForSubMesh(subMesh)) {\n return true;\n }\n const engine = scene.getEngine();\n // Lights\n MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);\n defines._needNormals = true;\n // Multiview\n MaterialHelper.PrepareDefinesForMultiview(scene, defines);\n // Textures\n if (defines._areTexturesDirty) {\n defines._needUVs = false;\n if (scene.texturesEnabled) {\n if (scene.getEngine().getCaps().textureLOD) {\n defines.TEXTURELODSUPPORT = true;\n }\n if (this._diffuseTexture && MaterialFlags.DiffuseTextureEnabled) {\n if (!this._diffuseTexture.isReadyOrNotBlocking()) {\n return false;\n }\n MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, \"DIFFUSE\");\n defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;\n defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;\n defines.OPACITYFRESNEL = this._opacityFresnel;\n }\n else {\n defines.DIFFUSE = false;\n defines.DIFFUSEDIRECTUV = 0;\n defines.DIFFUSEHASALPHA = false;\n defines.GAMMADIFFUSE = false;\n defines.OPACITYFRESNEL = false;\n }\n const reflectionTexture = this._reflectionTexture;\n if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {\n if (!reflectionTexture.isReadyOrNotBlocking()) {\n return false;\n }\n defines.REFLECTION = true;\n defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;\n defines.RGBDREFLECTION = reflectionTexture.isRGBD;\n defines.REFLECTIONBLUR = this._reflectionBlur > 0;\n defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;\n defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;\n defines.REFLECTIONBGR = this.switchToBGR;\n if (reflectionTexture.coordinatesMode === Texture.INVCUBIC_MODE) {\n defines.INVERTCUBICMAP = true;\n }\n defines.REFLECTIONMAP_3D = reflectionTexture.isCube;\n defines.REFLECTIONMAP_OPPOSITEZ = defines.REFLECTIONMAP_3D && this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;\n switch (reflectionTexture.coordinatesMode) {\n case Texture.EXPLICIT_MODE:\n defines.REFLECTIONMAP_EXPLICIT = true;\n break;\n case Texture.PLANAR_MODE:\n defines.REFLECTIONMAP_PLANAR = true;\n break;\n case Texture.PROJECTION_MODE:\n defines.REFLECTIONMAP_PROJECTION = true;\n break;\n case Texture.SKYBOX_MODE:\n defines.REFLECTIONMAP_SKYBOX = true;\n break;\n case Texture.SPHERICAL_MODE:\n defines.REFLECTIONMAP_SPHERICAL = true;\n break;\n case Texture.EQUIRECTANGULAR_MODE:\n defines.REFLECTIONMAP_EQUIRECTANGULAR = true;\n break;\n case Texture.FIXED_EQUIRECTANGULAR_MODE:\n defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;\n break;\n case Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:\n defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;\n break;\n case Texture.CUBIC_MODE:\n case Texture.INVCUBIC_MODE:\n default:\n defines.REFLECTIONMAP_CUBIC = true;\n break;\n }\n if (this.reflectionFresnel) {\n defines.REFLECTIONFRESNEL = true;\n defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;\n this._reflectionControls.x = this.reflectionAmount;\n this._reflectionControls.y = this.reflectionReflectance0;\n this._reflectionControls.z = this.reflectionReflectance90;\n this._reflectionControls.w = 1 / this.reflectionFalloffDistance;\n }\n else {\n defines.REFLECTIONFRESNEL = false;\n defines.REFLECTIONFALLOFF = false;\n }\n }\n else {\n defines.REFLECTION = false;\n defines.REFLECTIONFRESNEL = false;\n defines.REFLECTIONFALLOFF = false;\n defines.REFLECTIONBLUR = false;\n defines.REFLECTIONMAP_3D = false;\n defines.REFLECTIONMAP_SPHERICAL = false;\n defines.REFLECTIONMAP_PLANAR = false;\n defines.REFLECTIONMAP_CUBIC = false;\n defines.REFLECTIONMAP_PROJECTION = false;\n defines.REFLECTIONMAP_SKYBOX = false;\n defines.REFLECTIONMAP_EXPLICIT = false;\n defines.REFLECTIONMAP_EQUIRECTANGULAR = false;\n defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;\n defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;\n defines.INVERTCUBICMAP = false;\n defines.REFLECTIONMAP_OPPOSITEZ = false;\n defines.LODINREFLECTIONALPHA = false;\n defines.GAMMAREFLECTION = false;\n defines.RGBDREFLECTION = false;\n }\n }\n defines.PREMULTIPLYALPHA = this.alphaMode === 7 || this.alphaMode === 8;\n defines.USERGBCOLOR = this._useRGBColor;\n defines.NOISE = this._enableNoise;\n }\n if (defines._areLightsDirty) {\n defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);\n defines.BACKMAT_SHADOWONLY = this._shadowOnly;\n }\n if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {\n if (!this._imageProcessingConfiguration.isReady()) {\n return false;\n }\n this._imageProcessingConfiguration.prepareDefines(defines);\n }\n // Misc.\n MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);\n // Values that need to be evaluated on every frame\n MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, this, defines, useInstances, null, subMesh.getRenderingMesh().hasThinInstances);\n // Attribs\n if (MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {\n if (mesh) {\n if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {\n mesh.createNormals(true);\n Logger.Warn(\"BackgroundMaterial: Normals have been created for the mesh: \" + mesh.name);\n }\n }\n }\n // Get correct effect\n if (defines.isDirty) {\n defines.markAsProcessed();\n scene.resetCachedMaterial();\n // Fallbacks\n const fallbacks = new EffectFallbacks();\n if (defines.FOG) {\n fallbacks.addFallback(0, \"FOG\");\n }\n if (defines.POINTSIZE) {\n fallbacks.addFallback(1, \"POINTSIZE\");\n }\n if (defines.MULTIVIEW) {\n fallbacks.addFallback(0, \"MULTIVIEW\");\n }\n MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);\n //Attributes\n const attribs = [VertexBuffer.PositionKind];\n if (defines.NORMAL) {\n attribs.push(VertexBuffer.NormalKind);\n }\n if (defines.UV1) {\n attribs.push(VertexBuffer.UVKind);\n }\n if (defines.UV2) {\n attribs.push(VertexBuffer.UV2Kind);\n }\n MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);\n MaterialHelper.PrepareAttributesForInstances(attribs, defines);\n const uniforms = [\n \"world\",\n \"view\",\n \"viewProjection\",\n \"vEyePosition\",\n \"vLightsType\",\n \"vFogInfos\",\n \"vFogColor\",\n \"pointSize\",\n \"mBones\",\n \"vPrimaryColor\",\n \"vPrimaryColorShadow\",\n \"vReflectionInfos\",\n \"reflectionMatrix\",\n \"vReflectionMicrosurfaceInfos\",\n \"fFovMultiplier\",\n \"shadowLevel\",\n \"alpha\",\n \"vBackgroundCenter\",\n \"vReflectionControl\",\n \"vDiffuseInfos\",\n \"diffuseMatrix\",\n ];\n addClipPlaneUniforms(uniforms);\n const samplers = [\"diffuseSampler\", \"reflectionSampler\", \"reflectionSamplerLow\", \"reflectionSamplerHigh\"];\n const uniformBuffers = [\"Material\", \"Scene\"];\n if (ImageProcessingConfiguration) {\n ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);\n ImageProcessingConfiguration.PrepareSamplers(samplers, defines);\n }\n MaterialHelper.PrepareUniformsAndSamplersList({\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: defines,\n maxSimultaneousLights: this._maxSimultaneousLights,\n });\n const join = defines.toString();\n const effect = scene.getEngine().createEffect(\"background\", {\n attributes: attribs,\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: join,\n fallbacks: fallbacks,\n onCompiled: this.onCompiled,\n onError: this.onError,\n indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights },\n }, engine);\n subMesh.setEffect(effect, defines, this._materialContext);\n this.buildUniformLayout();\n }\n if (!subMesh.effect || !subMesh.effect.isReady()) {\n return false;\n }\n defines._renderId = scene.getRenderId();\n subMesh.effect._wasPreviouslyReady = true;\n subMesh.effect._wasPreviouslyUsingInstances = useInstances;\n this._checkScenePerformancePriority();\n return true;\n }\n /**\n * Compute the primary color according to the chosen perceptual color.\n */\n _computePrimaryColorFromPerceptualColor() {\n if (!this.__perceptualColor) {\n return;\n }\n this._primaryColor.copyFrom(this.__perceptualColor);\n // Revert gamma space.\n this._primaryColor.toLinearSpaceToRef(this._primaryColor, this.getScene().getEngine().useExactSrgbConversions);\n // Revert image processing configuration.\n if (this._imageProcessingConfiguration) {\n // Revert Exposure.\n this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);\n }\n this._computePrimaryColors();\n }\n /**\n * Compute the highlights and shadow colors according to their chosen levels.\n */\n _computePrimaryColors() {\n if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {\n return;\n }\n // Find the highlight color based on the configuration.\n this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);\n this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);\n // Find the shadow color based on the configuration.\n this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);\n this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);\n this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);\n }\n /**\n * Build the uniform buffer used in the material.\n */\n buildUniformLayout() {\n // Order is important !\n this._uniformBuffer.addUniform(\"vPrimaryColor\", 4);\n this._uniformBuffer.addUniform(\"vPrimaryColorShadow\", 4);\n this._uniformBuffer.addUniform(\"vDiffuseInfos\", 2);\n this._uniformBuffer.addUniform(\"vReflectionInfos\", 2);\n this._uniformBuffer.addUniform(\"diffuseMatrix\", 16);\n this._uniformBuffer.addUniform(\"reflectionMatrix\", 16);\n this._uniformBuffer.addUniform(\"vReflectionMicrosurfaceInfos\", 3);\n this._uniformBuffer.addUniform(\"fFovMultiplier\", 1);\n this._uniformBuffer.addUniform(\"pointSize\", 1);\n this._uniformBuffer.addUniform(\"shadowLevel\", 1);\n this._uniformBuffer.addUniform(\"alpha\", 1);\n this._uniformBuffer.addUniform(\"vBackgroundCenter\", 3);\n this._uniformBuffer.addUniform(\"vReflectionControl\", 4);\n this._uniformBuffer.create();\n }\n /**\n * Unbind the material.\n */\n unbind() {\n if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {\n this._uniformBuffer.setTexture(\"diffuseSampler\", null);\n }\n if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {\n this._uniformBuffer.setTexture(\"reflectionSampler\", null);\n }\n super.unbind();\n }\n /**\n * Bind only the world matrix to the material.\n * @param world The world matrix to bind.\n */\n bindOnlyWorldMatrix(world) {\n this._activeEffect.setMatrix(\"world\", world);\n }\n /**\n * Bind the material for a dedicated submeh (every used meshes will be considered opaque).\n * @param world The world matrix to bind.\n * @param mesh\n * @param subMesh The submesh to bind for.\n */\n bindForSubMesh(world, mesh, subMesh) {\n const scene = this.getScene();\n const defines = subMesh.materialDefines;\n if (!defines) {\n return;\n }\n const effect = subMesh.effect;\n if (!effect) {\n return;\n }\n this._activeEffect = effect;\n // Matrices\n this.bindOnlyWorldMatrix(world);\n // Bones\n MaterialHelper.BindBonesParameters(mesh, this._activeEffect);\n const mustRebind = this._mustRebind(scene, effect, mesh.visibility);\n if (mustRebind) {\n this._uniformBuffer.bindToEffect(effect, \"Material\");\n this.bindViewProjection(effect);\n const reflectionTexture = this._reflectionTexture;\n if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {\n // Texture uniforms\n if (scene.texturesEnabled) {\n if (this._diffuseTexture && MaterialFlags.DiffuseTextureEnabled) {\n this._uniformBuffer.updateFloat2(\"vDiffuseInfos\", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);\n MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, \"diffuse\");\n }\n if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {\n this._uniformBuffer.updateMatrix(\"reflectionMatrix\", reflectionTexture.getReflectionTextureMatrix());\n this._uniformBuffer.updateFloat2(\"vReflectionInfos\", reflectionTexture.level, this._reflectionBlur);\n this._uniformBuffer.updateFloat3(\"vReflectionMicrosurfaceInfos\", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);\n }\n }\n if (this.shadowLevel > 0) {\n this._uniformBuffer.updateFloat(\"shadowLevel\", this.shadowLevel);\n }\n this._uniformBuffer.updateFloat(\"alpha\", this.alpha);\n // Point size\n if (this.pointsCloud) {\n this._uniformBuffer.updateFloat(\"pointSize\", this.pointSize);\n }\n if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {\n this._uniformBuffer.updateColor4(\"vPrimaryColor\", this._primaryHighlightColor, 1.0);\n this._uniformBuffer.updateColor4(\"vPrimaryColorShadow\", this._primaryShadowColor, 1.0);\n }\n else {\n this._uniformBuffer.updateColor4(\"vPrimaryColor\", this._primaryColor, 1.0);\n }\n }\n this._uniformBuffer.updateFloat(\"fFovMultiplier\", this._fovMultiplier);\n // Textures\n if (scene.texturesEnabled) {\n if (this._diffuseTexture && MaterialFlags.DiffuseTextureEnabled) {\n this._uniformBuffer.setTexture(\"diffuseSampler\", this._diffuseTexture);\n }\n if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {\n if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {\n this._uniformBuffer.setTexture(\"reflectionSampler\", reflectionTexture);\n }\n else if (!defines.REFLECTIONBLUR) {\n this._uniformBuffer.setTexture(\"reflectionSampler\", reflectionTexture);\n }\n else {\n this._uniformBuffer.setTexture(\"reflectionSampler\", reflectionTexture._lodTextureMid || reflectionTexture);\n this._uniformBuffer.setTexture(\"reflectionSamplerLow\", reflectionTexture._lodTextureLow || reflectionTexture);\n this._uniformBuffer.setTexture(\"reflectionSamplerHigh\", reflectionTexture._lodTextureHigh || reflectionTexture);\n }\n if (defines.REFLECTIONFRESNEL) {\n this._uniformBuffer.updateFloat3(\"vBackgroundCenter\", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);\n this._uniformBuffer.updateFloat4(\"vReflectionControl\", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);\n }\n }\n }\n // Clip plane\n bindClipPlane(this._activeEffect, this, scene);\n scene.bindEyePosition(effect);\n }\n else if (scene.getEngine()._features.needToAlwaysBindUniformBuffers) {\n this._uniformBuffer.bindToEffect(effect, \"Material\");\n this._needToBindSceneUbo = true;\n }\n if (mustRebind || !this.isFrozen) {\n if (scene.lightsEnabled) {\n MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights);\n }\n // View\n this.bindView(effect);\n // Fog\n MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);\n // image processing\n if (this._imageProcessingConfiguration) {\n this._imageProcessingConfiguration.bind(this._activeEffect);\n }\n }\n this._afterBind(mesh, this._activeEffect);\n this._uniformBuffer.update();\n }\n /**\n * Checks to see if a texture is used in the material.\n * @param texture - Base texture to use.\n * @returns - Boolean specifying if a texture is used in the material.\n */\n hasTexture(texture) {\n if (super.hasTexture(texture)) {\n return true;\n }\n if (this._reflectionTexture === texture) {\n return true;\n }\n if (this._diffuseTexture === texture) {\n return true;\n }\n return false;\n }\n /**\n * Dispose the material.\n * @param forceDisposeEffect Force disposal of the associated effect.\n * @param forceDisposeTextures Force disposal of the associated textures.\n */\n dispose(forceDisposeEffect = false, forceDisposeTextures = false) {\n if (forceDisposeTextures) {\n if (this.diffuseTexture) {\n this.diffuseTexture.dispose();\n }\n if (this.reflectionTexture) {\n this.reflectionTexture.dispose();\n }\n }\n this._renderTargets.dispose();\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n super.dispose(forceDisposeEffect);\n }\n /**\n * Clones the material.\n * @param name The cloned name.\n * @returns The cloned material.\n */\n clone(name) {\n return SerializationHelper.Clone(() => new BackgroundMaterial(name, this.getScene()), this);\n }\n /**\n * Serializes the current material to its JSON representation.\n * @returns The JSON representation.\n */\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.customType = \"BABYLON.BackgroundMaterial\";\n return serializationObject;\n }\n /**\n * Gets the class name of the material\n * @returns \"BackgroundMaterial\"\n */\n getClassName() {\n return \"BackgroundMaterial\";\n }\n /**\n * Parse a JSON input to create back a background material.\n * @param source The JSON data to parse\n * @param scene The scene to create the parsed material in\n * @param rootUrl The root url of the assets the material depends upon\n * @returns the instantiated BackgroundMaterial.\n */\n static Parse(source, scene, rootUrl) {\n return SerializationHelper.Parse(() => new BackgroundMaterial(source.name, scene), source, scene, rootUrl);\n }\n}\n/**\n * Standard reflectance value at parallel view angle.\n */\nBackgroundMaterial.StandardReflectance0 = 0.05;\n/**\n * Standard reflectance value at grazing angle.\n */\nBackgroundMaterial.StandardReflectance90 = 0.5;\n__decorate([\n serializeAsColor3()\n], BackgroundMaterial.prototype, \"_primaryColor\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n], BackgroundMaterial.prototype, \"primaryColor\", void 0);\n__decorate([\n serializeAsColor3()\n], BackgroundMaterial.prototype, \"__perceptualColor\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_primaryColorShadowLevel\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_primaryColorHighlightLevel\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n], BackgroundMaterial.prototype, \"primaryColorHighlightLevel\", null);\n__decorate([\n serializeAsTexture()\n], BackgroundMaterial.prototype, \"_reflectionTexture\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"reflectionTexture\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_reflectionBlur\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"reflectionBlur\", void 0);\n__decorate([\n serializeAsTexture()\n], BackgroundMaterial.prototype, \"_diffuseTexture\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"diffuseTexture\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"shadowLights\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_shadowLevel\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"shadowLevel\", void 0);\n__decorate([\n serializeAsVector3()\n], BackgroundMaterial.prototype, \"_sceneCenter\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"sceneCenter\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_opacityFresnel\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"opacityFresnel\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_reflectionFresnel\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"reflectionFresnel\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_reflectionFalloffDistance\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"reflectionFalloffDistance\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_reflectionAmount\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"reflectionAmount\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_reflectionReflectance0\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"reflectionReflectance0\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_reflectionReflectance90\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"reflectionReflectance90\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_useRGBColor\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"useRGBColor\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_enableNoise\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"enableNoise\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_maxSimultaneousLights\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"maxSimultaneousLights\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_shadowOnly\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n], BackgroundMaterial.prototype, \"shadowOnly\", void 0);\n__decorate([\n serializeAsImageProcessingConfiguration()\n], BackgroundMaterial.prototype, \"_imageProcessingConfiguration\", void 0);\nRegisterClass(\"BABYLON.BackgroundMaterial\", BackgroundMaterial);\n//# sourceMappingURL=backgroundMaterial.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { ArcRotateCamera } from \"../Cameras/arcRotateCamera.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Color3, Color4 } from \"../Maths/math.color.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { BaseTexture } from \"../Materials/Textures/baseTexture.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { MirrorTexture } from \"../Materials/Textures/mirrorTexture.js\";\nimport { CubeTexture } from \"../Materials/Textures/cubeTexture.js\";\nimport { BackgroundMaterial } from \"../Materials/Background/backgroundMaterial.js\";\n\nimport { CreatePlane } from \"../Meshes/Builders/planeBuilder.js\";\nimport { CreateBox } from \"../Meshes/Builders/boxBuilder.js\";\nimport { Plane } from \"../Maths/math.plane.js\";\n/**\n * The EnvironmentHelper class can be used to add a fully featured non-expensive background to your scene.\n * It includes by default a skybox and a ground relying on the BackgroundMaterial.\n * It also helps with the default setup of your ImageProcessingConfiguration.\n */\nexport class EnvironmentHelper {\n /**\n * Creates the default options for the helper.\n * @param scene The scene the environment helper belongs to.\n */\n static _GetDefaultOptions(scene) {\n return {\n createGround: true,\n groundSize: 15,\n groundTexture: this._GroundTextureCDNUrl,\n groundColor: new Color3(0.2, 0.2, 0.3).toLinearSpace(scene.getEngine().useExactSrgbConversions).scale(3),\n groundOpacity: 0.9,\n enableGroundShadow: true,\n groundShadowLevel: 0.5,\n enableGroundMirror: false,\n groundMirrorSizeRatio: 0.3,\n groundMirrorBlurKernel: 64,\n groundMirrorAmount: 1,\n groundMirrorFresnelWeight: 1,\n groundMirrorFallOffDistance: 0,\n groundMirrorTextureType: 0,\n groundYBias: 0.00001,\n createSkybox: true,\n skyboxSize: 20,\n skyboxTexture: this._SkyboxTextureCDNUrl,\n skyboxColor: new Color3(0.2, 0.2, 0.3).toLinearSpace(scene.getEngine().useExactSrgbConversions).scale(3),\n backgroundYRotation: 0,\n sizeAuto: true,\n rootPosition: Vector3.Zero(),\n setupImageProcessing: true,\n environmentTexture: this._EnvironmentTextureCDNUrl,\n cameraExposure: 0.8,\n cameraContrast: 1.2,\n toneMappingEnabled: true,\n };\n }\n /**\n * Gets the root mesh created by the helper.\n */\n get rootMesh() {\n return this._rootMesh;\n }\n /**\n * Gets the skybox created by the helper.\n */\n get skybox() {\n return this._skybox;\n }\n /**\n * Gets the skybox texture created by the helper.\n */\n get skyboxTexture() {\n return this._skyboxTexture;\n }\n /**\n * Gets the skybox material created by the helper.\n */\n get skyboxMaterial() {\n return this._skyboxMaterial;\n }\n /**\n * Gets the ground mesh created by the helper.\n */\n get ground() {\n return this._ground;\n }\n /**\n * Gets the ground texture created by the helper.\n */\n get groundTexture() {\n return this._groundTexture;\n }\n /**\n * Gets the ground mirror created by the helper.\n */\n get groundMirror() {\n return this._groundMirror;\n }\n /**\n * Gets the ground mirror render list to helps pushing the meshes\n * you wish in the ground reflection.\n */\n get groundMirrorRenderList() {\n if (this._groundMirror) {\n return this._groundMirror.renderList;\n }\n return null;\n }\n /**\n * Gets the ground material created by the helper.\n */\n get groundMaterial() {\n return this._groundMaterial;\n }\n /**\n * constructor\n * @param options Defines the options we want to customize the helper\n * @param scene The scene to add the material to\n */\n constructor(options, scene) {\n this._errorHandler = (message, exception) => {\n this.onErrorObservable.notifyObservers({ message: message, exception: exception });\n };\n this._options = Object.assign(Object.assign({}, EnvironmentHelper._GetDefaultOptions(scene)), options);\n this._scene = scene;\n this.onErrorObservable = new Observable();\n this._setupBackground();\n this._setupImageProcessing();\n }\n /**\n * Updates the background according to the new options\n * @param options\n */\n updateOptions(options) {\n const newOptions = Object.assign(Object.assign({}, this._options), options);\n if (this._ground && !newOptions.createGround) {\n this._ground.dispose();\n this._ground = null;\n }\n if (this._groundMaterial && !newOptions.createGround) {\n this._groundMaterial.dispose();\n this._groundMaterial = null;\n }\n if (this._groundTexture) {\n if (this._options.groundTexture != newOptions.groundTexture) {\n this._groundTexture.dispose();\n this._groundTexture = null;\n }\n }\n if (this._skybox && !newOptions.createSkybox) {\n this._skybox.dispose();\n this._skybox = null;\n }\n if (this._skyboxMaterial && !newOptions.createSkybox) {\n this._skyboxMaterial.dispose();\n this._skyboxMaterial = null;\n }\n if (this._skyboxTexture) {\n if (this._options.skyboxTexture != newOptions.skyboxTexture) {\n this._skyboxTexture.dispose();\n this._skyboxTexture = null;\n }\n }\n if (this._groundMirror && !newOptions.enableGroundMirror) {\n this._groundMirror.dispose();\n this._groundMirror = null;\n }\n if (this._scene.environmentTexture) {\n if (this._options.environmentTexture != newOptions.environmentTexture) {\n this._scene.environmentTexture.dispose();\n }\n }\n this._options = newOptions;\n this._setupBackground();\n this._setupImageProcessing();\n }\n /**\n * Sets the primary color of all the available elements.\n * @param color the main color to affect to the ground and the background\n */\n setMainColor(color) {\n if (this.groundMaterial) {\n this.groundMaterial.primaryColor = color;\n }\n if (this.skyboxMaterial) {\n this.skyboxMaterial.primaryColor = color;\n }\n if (this.groundMirror) {\n this.groundMirror.clearColor = new Color4(color.r, color.g, color.b, 1.0);\n }\n }\n /**\n * Setup the image processing according to the specified options.\n */\n _setupImageProcessing() {\n if (this._options.setupImageProcessing) {\n this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;\n this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;\n this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;\n this._setupEnvironmentTexture();\n }\n }\n /**\n * Setup the environment texture according to the specified options.\n */\n _setupEnvironmentTexture() {\n if (this._scene.environmentTexture) {\n return;\n }\n if (this._options.environmentTexture instanceof BaseTexture) {\n this._scene.environmentTexture = this._options.environmentTexture;\n return;\n }\n const environmentTexture = CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);\n this._scene.environmentTexture = environmentTexture;\n }\n /**\n * Setup the background according to the specified options.\n */\n _setupBackground() {\n if (!this._rootMesh) {\n this._rootMesh = new Mesh(\"BackgroundHelper\", this._scene);\n }\n this._rootMesh.rotation.y = this._options.backgroundYRotation;\n const sceneSize = this._getSceneSize();\n if (this._options.createGround) {\n this._setupGround(sceneSize);\n this._setupGroundMaterial();\n this._setupGroundDiffuseTexture();\n if (this._options.enableGroundMirror) {\n this._setupGroundMirrorTexture(sceneSize);\n }\n this._setupMirrorInGroundMaterial();\n }\n if (this._options.createSkybox) {\n this._setupSkybox(sceneSize);\n this._setupSkyboxMaterial();\n this._setupSkyboxReflectionTexture();\n }\n this._rootMesh.position.x = sceneSize.rootPosition.x;\n this._rootMesh.position.z = sceneSize.rootPosition.z;\n this._rootMesh.position.y = sceneSize.rootPosition.y;\n }\n /**\n * Get the scene sizes according to the setup.\n */\n _getSceneSize() {\n let groundSize = this._options.groundSize;\n let skyboxSize = this._options.skyboxSize;\n let rootPosition = this._options.rootPosition;\n if (!this._scene.meshes || this._scene.meshes.length === 1) {\n // 1 only means the root of the helper.\n return { groundSize, skyboxSize, rootPosition };\n }\n const sceneExtends = this._scene.getWorldExtends((mesh) => {\n return mesh !== this._ground && mesh !== this._rootMesh && mesh !== this._skybox;\n });\n const sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);\n if (this._options.sizeAuto) {\n if (this._scene.activeCamera instanceof ArcRotateCamera && this._scene.activeCamera.upperRadiusLimit) {\n groundSize = this._scene.activeCamera.upperRadiusLimit * 2;\n skyboxSize = groundSize;\n }\n const sceneDiagonalLenght = sceneDiagonal.length();\n if (sceneDiagonalLenght > groundSize) {\n groundSize = sceneDiagonalLenght * 2;\n skyboxSize = groundSize;\n }\n // 10 % bigger.\n groundSize *= 1.1;\n skyboxSize *= 1.5;\n rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));\n rootPosition.y = sceneExtends.min.y - this._options.groundYBias;\n }\n return { groundSize, skyboxSize, rootPosition };\n }\n /**\n * Setup the ground according to the specified options.\n * @param sceneSize\n */\n _setupGround(sceneSize) {\n if (!this._ground || this._ground.isDisposed()) {\n this._ground = CreatePlane(\"BackgroundPlane\", { size: sceneSize.groundSize }, this._scene);\n this._ground.rotation.x = Math.PI / 2; // Face up by default.\n this._ground.parent = this._rootMesh;\n this._ground.onDisposeObservable.add(() => {\n this._ground = null;\n });\n }\n this._ground.receiveShadows = this._options.enableGroundShadow;\n }\n /**\n * Setup the ground material according to the specified options.\n */\n _setupGroundMaterial() {\n if (!this._groundMaterial) {\n this._groundMaterial = new BackgroundMaterial(\"BackgroundPlaneMaterial\", this._scene);\n }\n this._groundMaterial.alpha = this._options.groundOpacity;\n this._groundMaterial.alphaMode = 8;\n this._groundMaterial.shadowLevel = this._options.groundShadowLevel;\n this._groundMaterial.primaryColor = this._options.groundColor;\n this._groundMaterial.useRGBColor = false;\n this._groundMaterial.enableNoise = true;\n if (this._ground) {\n this._ground.material = this._groundMaterial;\n }\n }\n /**\n * Setup the ground diffuse texture according to the specified options.\n */\n _setupGroundDiffuseTexture() {\n if (!this._groundMaterial) {\n return;\n }\n if (this._groundTexture) {\n return;\n }\n if (this._options.groundTexture instanceof BaseTexture) {\n this._groundMaterial.diffuseTexture = this._options.groundTexture;\n return;\n }\n this._groundTexture = new Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);\n this._groundTexture.gammaSpace = false;\n this._groundTexture.hasAlpha = true;\n this._groundMaterial.diffuseTexture = this._groundTexture;\n }\n /**\n * Setup the ground mirror texture according to the specified options.\n * @param sceneSize\n */\n _setupGroundMirrorTexture(sceneSize) {\n const wrapping = Texture.CLAMP_ADDRESSMODE;\n if (!this._groundMirror) {\n this._groundMirror = new MirrorTexture(\"BackgroundPlaneMirrorTexture\", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, Texture.BILINEAR_SAMPLINGMODE, true);\n this._groundMirror.mirrorPlane = new Plane(0, -1, 0, sceneSize.rootPosition.y);\n this._groundMirror.anisotropicFilteringLevel = 1;\n this._groundMirror.wrapU = wrapping;\n this._groundMirror.wrapV = wrapping;\n if (this._groundMirror.renderList) {\n for (let i = 0; i < this._scene.meshes.length; i++) {\n const mesh = this._scene.meshes[i];\n if (mesh !== this._ground && mesh !== this._skybox && mesh !== this._rootMesh) {\n this._groundMirror.renderList.push(mesh);\n }\n }\n }\n }\n const gammaGround = this._options.groundColor.toGammaSpace(this._scene.getEngine().useExactSrgbConversions);\n this._groundMirror.clearColor = new Color4(gammaGround.r, gammaGround.g, gammaGround.b, 1);\n this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;\n }\n /**\n * Setup the ground to receive the mirror texture.\n */\n _setupMirrorInGroundMaterial() {\n if (this._groundMaterial) {\n this._groundMaterial.reflectionTexture = this._groundMirror;\n this._groundMaterial.reflectionFresnel = true;\n this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;\n this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;\n this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;\n }\n }\n /**\n * Setup the skybox according to the specified options.\n * @param sceneSize\n */\n _setupSkybox(sceneSize) {\n if (!this._skybox || this._skybox.isDisposed()) {\n this._skybox = CreateBox(\"BackgroundSkybox\", { size: sceneSize.skyboxSize, sideOrientation: Mesh.BACKSIDE }, this._scene);\n this._skybox.onDisposeObservable.add(() => {\n this._skybox = null;\n });\n }\n this._skybox.parent = this._rootMesh;\n }\n /**\n * Setup the skybox material according to the specified options.\n */\n _setupSkyboxMaterial() {\n if (!this._skybox) {\n return;\n }\n if (!this._skyboxMaterial) {\n this._skyboxMaterial = new BackgroundMaterial(\"BackgroundSkyboxMaterial\", this._scene);\n }\n this._skyboxMaterial.useRGBColor = false;\n this._skyboxMaterial.primaryColor = this._options.skyboxColor;\n this._skyboxMaterial.enableNoise = true;\n this._skybox.material = this._skyboxMaterial;\n }\n /**\n * Setup the skybox reflection texture according to the specified options.\n */\n _setupSkyboxReflectionTexture() {\n if (!this._skyboxMaterial) {\n return;\n }\n if (this._skyboxTexture) {\n return;\n }\n if (this._options.skyboxTexture instanceof BaseTexture) {\n this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;\n return;\n }\n this._skyboxTexture = new CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);\n this._skyboxTexture.coordinatesMode = Texture.SKYBOX_MODE;\n this._skyboxTexture.gammaSpace = false;\n this._skyboxMaterial.reflectionTexture = this._skyboxTexture;\n }\n /**\n * Dispose all the elements created by the Helper.\n */\n dispose() {\n if (this._groundMaterial) {\n this._groundMaterial.dispose(true, true);\n }\n if (this._skyboxMaterial) {\n this._skyboxMaterial.dispose(true, true);\n }\n this._rootMesh.dispose(false);\n }\n}\n/**\n * Default ground texture URL.\n */\nEnvironmentHelper._GroundTextureCDNUrl = \"https://assets.babylonjs.com/environments/backgroundGround.png\";\n/**\n * Default skybox texture URL.\n */\nEnvironmentHelper._SkyboxTextureCDNUrl = \"https://assets.babylonjs.com/environments/backgroundSkybox.dds\";\n/**\n * Default environment texture URL.\n */\nEnvironmentHelper._EnvironmentTextureCDNUrl = \"https://assets.babylonjs.com/environments/environmentSpecular.env\";\n//# sourceMappingURL=environmentHelper.js.map","import { TransformNode } from \"../Meshes/transformNode.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { BackgroundMaterial } from \"../Materials/Background/backgroundMaterial.js\";\nimport { CreateSphere } from \"../Meshes/Builders/sphereBuilder.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Axis } from \"../Maths/math.js\";\n/**\n * Display a 360/180 degree texture on an approximately spherical surface, useful for VR applications or skyboxes.\n * As a subclass of TransformNode, this allow parenting to the camera or multiple textures with different locations in the scene.\n * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.\n * Potential additions to this helper include zoom and and non-infinite distance rendering effects.\n */\nexport class TextureDome extends TransformNode {\n /**\n * Gets the texture being displayed on the sphere\n */\n get texture() {\n return this._texture;\n }\n /**\n * Sets the texture being displayed on the sphere\n */\n set texture(newTexture) {\n if (this._texture === newTexture) {\n return;\n }\n this._texture = newTexture;\n if (this._useDirectMapping) {\n this._texture.wrapU = Texture.CLAMP_ADDRESSMODE;\n this._texture.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._material.diffuseTexture = this._texture;\n }\n else {\n this._texture.coordinatesMode = Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation\n this._texture.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._material.reflectionTexture = this._texture;\n }\n this._changeTextureMode(this._textureMode);\n }\n /**\n * Gets the mesh used for the dome.\n */\n get mesh() {\n return this._mesh;\n }\n /**\n * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values \"zoom in\" and higher values \"zoom out\".\n * Also see the options.resolution property.\n */\n get fovMultiplier() {\n return this._material.fovMultiplier;\n }\n set fovMultiplier(value) {\n this._material.fovMultiplier = value;\n }\n /**\n * Gets or set the current texture mode for the texture. It can be:\n * * TextureDome.MODE_MONOSCOPIC : Define the texture source as a Monoscopic panoramic 360.\n * * TextureDome.MODE_TOPBOTTOM : Define the texture source as a Stereoscopic TopBottom/OverUnder panoramic 360.\n * * TextureDome.MODE_SIDEBYSIDE : Define the texture source as a Stereoscopic Side by Side panoramic 360.\n */\n get textureMode() {\n return this._textureMode;\n }\n /**\n * Sets the current texture mode for the texture. It can be:\n * * TextureDome.MODE_MONOSCOPIC : Define the texture source as a Monoscopic panoramic 360.\n * * TextureDome.MODE_TOPBOTTOM : Define the texture source as a Stereoscopic TopBottom/OverUnder panoramic 360.\n * * TextureDome.MODE_SIDEBYSIDE : Define the texture source as a Stereoscopic Side by Side panoramic 360.\n */\n set textureMode(value) {\n if (this._textureMode === value) {\n return;\n }\n this._changeTextureMode(value);\n }\n /**\n * Is it a 180 degrees dome (half dome) or 360 texture (full dome)\n */\n get halfDome() {\n return this._halfDome;\n }\n /**\n * Set the halfDome mode. If set, only the front (180 degrees) will be displayed and the back will be blacked out.\n */\n set halfDome(enabled) {\n this._halfDome = enabled;\n this._halfDomeMask.setEnabled(enabled);\n this._changeTextureMode(this._textureMode);\n }\n /**\n * Set the cross-eye mode. If set, images that can be seen when crossing eyes will render correctly\n */\n set crossEye(enabled) {\n this._crossEye = enabled;\n this._changeTextureMode(this._textureMode);\n }\n /**\n * Is it a cross-eye texture?\n */\n get crossEye() {\n return this._crossEye;\n }\n /**\n * The background material of this dome.\n */\n get material() {\n return this._material;\n }\n /**\n * Create an instance of this class and pass through the parameters to the relevant classes- Texture, StandardMaterial, and Mesh.\n * @param name Element's name, child elements will append suffixes for their own names.\n * @param textureUrlOrElement defines the url(s) or the (video) HTML element to use\n * @param options An object containing optional or exposed sub element properties\n * @param options.resolution\n * @param options.clickToPlay\n * @param options.autoPlay\n * @param options.loop\n * @param options.size\n * @param options.poster\n * @param options.faceForward\n * @param options.useDirectMapping\n * @param options.halfDomeMode\n * @param options.crossEyeMode\n * @param options.generateMipMaps\n * @param options.mesh\n * @param scene\n * @param onError\n */\n constructor(name, textureUrlOrElement, options, scene, \n // eslint-disable-next-line @typescript-eslint/naming-convention\n onError = null) {\n super(name, scene);\n this.onError = onError;\n this._halfDome = false;\n this._crossEye = false;\n this._useDirectMapping = false;\n this._textureMode = TextureDome.MODE_MONOSCOPIC;\n /**\n * Oberserver used in Stereoscopic VR Mode.\n */\n this._onBeforeCameraRenderObserver = null;\n /**\n * Observable raised when an error occurred while loading the texture\n */\n this.onLoadErrorObservable = new Observable();\n /**\n * Observable raised when the texture finished loading\n */\n this.onLoadObservable = new Observable();\n scene = this.getScene();\n // set defaults and manage values\n name = name || \"textureDome\";\n options.resolution = Math.abs(options.resolution) | 0 || 32;\n options.clickToPlay = Boolean(options.clickToPlay);\n options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);\n options.loop = options.loop === undefined ? true : Boolean(options.loop);\n options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);\n if (options.useDirectMapping === undefined) {\n this._useDirectMapping = true;\n }\n else {\n this._useDirectMapping = options.useDirectMapping;\n }\n if (options.faceForward === undefined) {\n options.faceForward = true;\n }\n this._setReady(false);\n if (!options.mesh) {\n this._mesh = CreateSphere(name + \"_mesh\", { segments: options.resolution, diameter: options.size, updatable: false, sideOrientation: Mesh.BACKSIDE }, scene);\n }\n else {\n this._mesh = options.mesh;\n }\n // configure material\n const material = (this._material = new BackgroundMaterial(name + \"_material\", scene));\n material.useEquirectangularFOV = true;\n material.fovMultiplier = 1.0;\n material.opacityFresnel = false;\n const texture = this._initTexture(textureUrlOrElement, scene, options);\n this.texture = texture;\n // configure mesh\n this._mesh.material = material;\n this._mesh.parent = this;\n // create a (disabled until needed) mask to cover unneeded segments of 180 texture.\n this._halfDomeMask = CreateSphere(\"\", { slice: 0.5, diameter: options.size * 0.98, segments: options.resolution * 2, sideOrientation: Mesh.BACKSIDE }, scene);\n this._halfDomeMask.rotate(Axis.X, -Math.PI / 2);\n // set the parent, so it will always be positioned correctly AND will be disposed when the main sphere is disposed\n this._halfDomeMask.parent = this._mesh;\n this._halfDome = !!options.halfDomeMode;\n // enable or disable according to the settings\n this._halfDomeMask.setEnabled(this._halfDome);\n this._crossEye = !!options.crossEyeMode;\n // create\n this._texture.anisotropicFilteringLevel = 1;\n this._texture.onLoadObservable.addOnce(() => {\n this._setReady(true);\n });\n // Initial rotation\n if (options.faceForward && scene.activeCamera) {\n const camera = scene.activeCamera;\n const forward = Vector3.Forward();\n const direction = Vector3.TransformNormal(forward, camera.getViewMatrix());\n direction.normalize();\n this.rotation.y = Math.acos(Vector3.Dot(forward, direction));\n }\n this._changeTextureMode(this._textureMode);\n }\n _changeTextureMode(value) {\n this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);\n this._textureMode = value;\n // Default Setup and Reset.\n this._texture.uScale = 1;\n this._texture.vScale = 1;\n this._texture.uOffset = 0;\n this._texture.vOffset = 0;\n this._texture.vAng = 0;\n switch (value) {\n case TextureDome.MODE_MONOSCOPIC:\n if (this._halfDome) {\n this._texture.uScale = 2;\n this._texture.uOffset = -1;\n }\n break;\n case TextureDome.MODE_SIDEBYSIDE: {\n // in half-dome mode the uScale should be double of 360 texture\n // Use 0.99999 to boost perf by not switching program\n this._texture.uScale = this._halfDome ? 0.99999 : 0.5;\n const rightOffset = this._halfDome ? 0.0 : 0.5;\n const leftOffset = this._halfDome ? -0.5 : 0.0;\n this._onBeforeCameraRenderObserver = this._scene.onBeforeCameraRenderObservable.add((camera) => {\n let isRightCamera = camera.isRightCamera;\n if (this._crossEye) {\n isRightCamera = !isRightCamera;\n }\n if (isRightCamera) {\n this._texture.uOffset = rightOffset;\n }\n else {\n this._texture.uOffset = leftOffset;\n }\n });\n break;\n }\n case TextureDome.MODE_TOPBOTTOM:\n // in half-dome mode the vScale should be double of 360 texture\n // Use 0.99999 to boost perf by not switching program\n this._texture.vScale = this._halfDome ? 0.99999 : 0.5;\n this._onBeforeCameraRenderObserver = this._scene.onBeforeCameraRenderObservable.add((camera) => {\n let isRightCamera = camera.isRightCamera;\n // allow \"cross-eye\" if left and right were switched in this mode\n if (this._crossEye) {\n isRightCamera = !isRightCamera;\n }\n this._texture.vOffset = isRightCamera ? 0.5 : 0.0;\n });\n break;\n }\n }\n /**\n * Releases resources associated with this node.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n dispose(doNotRecurse, disposeMaterialAndTextures = false) {\n this._texture.dispose();\n this._mesh.dispose();\n this._material.dispose();\n this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);\n this.onLoadErrorObservable.clear();\n this.onLoadObservable.clear();\n super.dispose(doNotRecurse, disposeMaterialAndTextures);\n }\n}\n/**\n * Define the source as a Monoscopic panoramic 360/180.\n */\nTextureDome.MODE_MONOSCOPIC = 0;\n/**\n * Define the source as a Stereoscopic TopBottom/OverUnder panoramic 360/180.\n */\nTextureDome.MODE_TOPBOTTOM = 1;\n/**\n * Define the source as a Stereoscopic Side by Side panoramic 360/180.\n */\nTextureDome.MODE_SIDEBYSIDE = 2;\n//# sourceMappingURL=textureDome.js.map","import { Texture } from \"../Materials/Textures/texture.js\";\nimport { TextureDome } from \"./textureDome.js\";\n/**\n * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.\n * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.\n * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.\n * Potential additions to this helper include zoom and and non-infinite distance rendering effects.\n */\nexport class PhotoDome extends TextureDome {\n /**\n * Gets or sets the texture being displayed on the sphere\n */\n get photoTexture() {\n return this.texture;\n }\n /**\n * sets the texture being displayed on the sphere\n */\n set photoTexture(value) {\n this.texture = value;\n }\n /**\n * Gets the current video mode for the video. It can be:\n * * TextureDome.MODE_MONOSCOPIC : Define the texture source as a Monoscopic panoramic 360.\n * * TextureDome.MODE_TOPBOTTOM : Define the texture source as a Stereoscopic TopBottom/OverUnder panoramic 360.\n * * TextureDome.MODE_SIDEBYSIDE : Define the texture source as a Stereoscopic Side by Side panoramic 360.\n */\n get imageMode() {\n return this.textureMode;\n }\n /**\n * Sets the current video mode for the video. It can be:\n * * TextureDome.MODE_MONOSCOPIC : Define the texture source as a Monoscopic panoramic 360.\n * * TextureDome.MODE_TOPBOTTOM : Define the texture source as a Stereoscopic TopBottom/OverUnder panoramic 360.\n * * TextureDome.MODE_SIDEBYSIDE : Define the texture source as a Stereoscopic Side by Side panoramic 360.\n */\n set imageMode(value) {\n this.textureMode = value;\n }\n _initTexture(urlsOrElement, scene, options) {\n return new Texture(urlsOrElement, scene, !options.generateMipMaps, !this._useDirectMapping, undefined, () => {\n this.onLoadObservable.notifyObservers();\n }, (message, exception) => {\n this.onLoadErrorObservable.notifyObservers(message || \"Unknown error occured\");\n if (this.onError) {\n this.onError(message, exception);\n }\n });\n }\n}\n/**\n * Define the image as a Monoscopic panoramic 360 image.\n */\nPhotoDome.MODE_MONOSCOPIC = TextureDome.MODE_MONOSCOPIC;\n/**\n * Define the image as a Stereoscopic TopBottom/OverUnder panoramic 360 image.\n */\nPhotoDome.MODE_TOPBOTTOM = TextureDome.MODE_TOPBOTTOM;\n/**\n * Define the image as a Stereoscopic Side by Side panoramic 360 image.\n */\nPhotoDome.MODE_SIDEBYSIDE = TextureDome.MODE_SIDEBYSIDE;\n//# sourceMappingURL=photoDome.js.map","import { Texture } from \"../Materials/Textures/texture.js\";\nimport { RGBDTextureTools } from \"./rgbdTextureTools.js\";\nimport { Tools } from \"./tools.js\";\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst _environmentBRDFBase64Texture = \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR42u29yY5tWXIlZnbuiSaTbZFUkZRKrCKhElASQA0EoQABgn6hJvoXzfUP+gP9hWb6Bg00IgRoQJaKqUxmZmTEe8/v0uB2u7Fm2T7HIyIrnz88uPvt3f2a2WrMbOvf/u3PvvzP/sUf/N6//i8vf/lv/3v5H//d//Sb//Uq/5u8yf8hV/m/5Cp/L1f5hVzlG7nKJ7mKyJuIXN/hPwqXI/g++zq6rPI5u8z+WqfLre+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EC6cqvqgi4OB5cpgLFYK/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==\";\nlet _instanceNumber = 0;\n/**\n * Gets a default environment BRDF for MS-BRDF Height Correlated BRDF\n * @param scene defines the hosting scene\n * @returns the environment BRDF texture\n */\nexport const GetEnvironmentBRDFTexture = (scene) => {\n if (!scene.environmentBRDFTexture) {\n // Forces Delayed Texture Loading to prevent undefined error whilst setting RGBD values.\n const useDelayedTextureLoading = scene.useDelayedTextureLoading;\n scene.useDelayedTextureLoading = false;\n const previousState = scene._blockEntityCollection;\n scene._blockEntityCollection = false;\n const texture = Texture.CreateFromBase64String(_environmentBRDFBase64Texture, \"EnvironmentBRDFTexture\" + _instanceNumber++, scene, true, false, Texture.BILINEAR_SAMPLINGMODE);\n scene._blockEntityCollection = previousState;\n // BRDF Texture should not be cached here due to pre processing and redundant scene caches.\n const texturesCache = scene.getEngine().getLoadedTexturesCache();\n const index = texturesCache.indexOf(texture.getInternalTexture());\n if (index !== -1) {\n texturesCache.splice(index, 1);\n }\n texture.isRGBD = true;\n texture.wrapU = Texture.CLAMP_ADDRESSMODE;\n texture.wrapV = Texture.CLAMP_ADDRESSMODE;\n scene.environmentBRDFTexture = texture;\n scene.useDelayedTextureLoading = useDelayedTextureLoading;\n RGBDTextureTools.ExpandRGBDTexture(texture);\n const observer = scene.getEngine().onContextRestoredObservable.add(() => {\n texture.isRGBD = true;\n const checkReady = () => {\n if (texture.isReady()) {\n RGBDTextureTools.ExpandRGBDTexture(texture);\n }\n else {\n Tools.SetImmediate(checkReady);\n }\n };\n checkReady();\n });\n scene.onDisposeObservable.add(() => {\n scene.getEngine().onContextRestoredObservable.remove(observer);\n });\n }\n return scene.environmentBRDFTexture;\n};\n/**\n * Class used to host texture specific utilities\n */\nexport const BRDFTextureTools = {\n /**\n * Gets a default environment BRDF for MS-BRDF Height Correlated BRDF\n * @param scene defines the hosting scene\n * @returns the environment BRDF texture\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n GetEnvironmentBRDFTexture,\n};\n//# sourceMappingURL=brdfTextureTools.js.map","import { __decorate } from \"../../tslib.es6.js\";\n/* eslint-disable @typescript-eslint/naming-convention */\n\nimport { serialize, expandToProperty } from \"../../Misc/decorators.js\";\nimport { MaterialDefines } from \"../materialDefines.js\";\nimport { MaterialPluginBase } from \"../materialPluginBase.js\";\n/**\n * @internal\n */\nexport class MaterialBRDFDefines extends MaterialDefines {\n constructor() {\n super(...arguments);\n this.BRDF_V_HEIGHT_CORRELATED = false;\n this.MS_BRDF_ENERGY_CONSERVATION = false;\n this.SPHERICAL_HARMONICS = false;\n this.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION = false;\n }\n}\n/**\n * Plugin that implements the BRDF component of the PBR material\n */\nexport class PBRBRDFConfiguration extends MaterialPluginBase {\n /** @internal */\n _markAllSubMeshesAsMiscDirty() {\n this._internalMarkAllSubMeshesAsMiscDirty();\n }\n constructor(material, addToPluginList = true) {\n super(material, \"PBRBRDF\", 90, new MaterialBRDFDefines(), addToPluginList);\n this._useEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION;\n /**\n * Defines if the material uses energy conservation.\n */\n this.useEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION;\n this._useSmithVisibilityHeightCorrelated = PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED;\n /**\n * LEGACY Mode set to false\n * Defines if the material uses height smith correlated visibility term.\n * If you intent to not use our default BRDF, you need to load a separate BRDF Texture for the PBR\n * You can either load https://assets.babylonjs.com/environments/uncorrelatedBRDF.png\n * or https://assets.babylonjs.com/environments/uncorrelatedBRDF.dds to have more precision\n * Not relying on height correlated will also disable energy conservation.\n */\n this.useSmithVisibilityHeightCorrelated = PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED;\n this._useSphericalHarmonics = PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS;\n /**\n * LEGACY Mode set to false\n * Defines if the material uses spherical harmonics vs spherical polynomials for the\n * diffuse part of the IBL.\n * The harmonics despite a tiny bigger cost has been proven to provide closer results\n * to the ground truth.\n */\n this.useSphericalHarmonics = PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS;\n this._useSpecularGlossinessInputEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION;\n /**\n * Defines if the material uses energy conservation, when the specular workflow is active.\n * If activated, the albedo color is multiplied with (1. - maxChannel(specular color)).\n * If deactivated, a material is only physically plausible, when (albedo color + specular color) < 1.\n * In the deactivated case, the material author has to ensure energy conservation, for a physically plausible rendering.\n */\n this.useSpecularGlossinessInputEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION;\n this._internalMarkAllSubMeshesAsMiscDirty = material._dirtyCallbacks[16];\n this._enable(true);\n }\n prepareDefines(defines) {\n defines.BRDF_V_HEIGHT_CORRELATED = this._useSmithVisibilityHeightCorrelated;\n defines.MS_BRDF_ENERGY_CONSERVATION = this._useEnergyConservation && this._useSmithVisibilityHeightCorrelated;\n defines.SPHERICAL_HARMONICS = this._useSphericalHarmonics;\n defines.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION = this._useSpecularGlossinessInputEnergyConservation;\n }\n getClassName() {\n return \"PBRBRDFConfiguration\";\n }\n}\n/**\n * Default value used for the energy conservation.\n * This should only be changed to adapt to the type of texture in scene.environmentBRDFTexture.\n */\nPBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION = true;\n/**\n * Default value used for the Smith Visibility Height Correlated mode.\n * This should only be changed to adapt to the type of texture in scene.environmentBRDFTexture.\n */\nPBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED = true;\n/**\n * Default value used for the IBL diffuse part.\n * This can help switching back to the polynomials mode globally which is a tiny bit\n * less GPU intensive at the drawback of a lower quality.\n */\nPBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS = true;\n/**\n * Default value used for activating energy conservation for the specular workflow.\n * If activated, the albedo color is multiplied with (1. - maxChannel(specular color)).\n * If deactivated, a material is only physically plausible, when (albedo color + specular color) < 1.\n */\nPBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION = true;\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsMiscDirty\")\n], PBRBRDFConfiguration.prototype, \"useEnergyConservation\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsMiscDirty\")\n], PBRBRDFConfiguration.prototype, \"useSmithVisibilityHeightCorrelated\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsMiscDirty\")\n], PBRBRDFConfiguration.prototype, \"useSphericalHarmonics\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsMiscDirty\")\n], PBRBRDFConfiguration.prototype, \"useSpecularGlossinessInputEnergyConservation\", void 0);\n//# sourceMappingURL=pbrBRDFConfiguration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nimport \"./decalFragmentDeclaration.js\";\nconst name = \"pbrFragmentDeclaration\";\nconst shader = `uniform vec4 vEyePosition;\runiform vec3 vReflectionColor;\runiform vec4 vAlbedoColor;\runiform vec4 vLightingIntensity;\runiform vec4 vReflectivityColor;\runiform vec4 vMetallicReflectanceFactors;\runiform vec3 vEmissiveColor;\runiform float visibility;\runiform vec3 vAmbientColor;\r#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\r#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\r#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\runiform vec2 vTangentSpaceParams;\r#endif\n#ifdef OPACITY\nuniform vec2 vOpacityInfos;\r#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\r#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\r#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\r#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\r#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS)\nuniform mat4 view;\r#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\r#ifdef REALTIME_FILTERING\nuniform vec2 vReflectionFilteringInfo;\r#endif\nuniform mat4 reflectionMatrix;\runiform vec3 vReflectionMicrosurfaceInfos;\r#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\runiform vec3 vReflectionSize; \r#endif\n#endif\n#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC)\nuniform vec3 vRefractionPosition;\runiform vec3 vRefractionSize; \r#endif\n#ifdef CLEARCOAT\nuniform vec2 vClearCoatParams;\runiform vec4 vClearCoatRefractionParams;\r#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform vec4 vClearCoatInfos;\r#endif\n#ifdef CLEARCOAT_TEXTURE\nuniform mat4 clearCoatMatrix;\r#endif\n#ifdef CLEARCOAT_TEXTURE_ROUGHNESS\nuniform mat4 clearCoatRoughnessMatrix;\r#endif\n#ifdef CLEARCOAT_BUMP\nuniform vec2 vClearCoatBumpInfos;\runiform vec2 vClearCoatTangentSpaceParams;\runiform mat4 clearCoatBumpMatrix;\r#endif\n#ifdef CLEARCOAT_TINT\nuniform vec4 vClearCoatTintParams;\runiform float clearCoatColorAtDistance;\r#ifdef CLEARCOAT_TINT_TEXTURE\nuniform vec2 vClearCoatTintInfos;\runiform mat4 clearCoatTintMatrix;\r#endif\n#endif\n#endif\n#ifdef IRIDESCENCE\nuniform vec4 vIridescenceParams;\r#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)\nuniform vec4 vIridescenceInfos;\r#endif\n#ifdef IRIDESCENCE_TEXTURE\nuniform mat4 iridescenceMatrix;\r#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nuniform mat4 iridescenceThicknessMatrix;\r#endif\n#endif\n#ifdef ANISOTROPIC\nuniform vec3 vAnisotropy;\r#ifdef ANISOTROPIC_TEXTURE\nuniform vec2 vAnisotropyInfos;\runiform mat4 anisotropyMatrix;\r#endif\n#endif\n#ifdef SHEEN\nuniform vec4 vSheenColor;\r#ifdef SHEEN_ROUGHNESS\nuniform float vSheenRoughness;\r#endif\n#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform vec4 vSheenInfos;\r#endif\n#ifdef SHEEN_TEXTURE\nuniform mat4 sheenMatrix;\r#endif\n#ifdef SHEEN_TEXTURE_ROUGHNESS\nuniform mat4 sheenRoughnessMatrix;\r#endif\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\nuniform vec4 vRefractionMicrosurfaceInfos;\runiform vec4 vRefractionInfos;\runiform mat4 refractionMatrix;\r#ifdef REALTIME_FILTERING\nuniform vec2 vRefractionFilteringInfo;\r#endif\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nuniform vec2 vThicknessInfos;\runiform mat4 thicknessMatrix;\r#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nuniform vec2 vRefractionIntensityInfos;\runiform mat4 refractionIntensityMatrix;\r#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nuniform vec2 vTranslucencyIntensityInfos;\runiform mat4 translucencyIntensityMatrix;\r#endif\nuniform vec2 vThicknessParam;\runiform vec3 vDiffusionDistance;\runiform vec4 vTintColor;\runiform vec3 vSubSurfaceIntensity;\r#endif\n#ifdef PREPASS\n#ifdef SS_SCATTERING\nuniform float scatteringDiffusionProfile;\r#endif\n#endif\n#if DEBUGMODE>0\nuniform vec2 vDebugMode;\r#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\r#endif\n#include\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nuniform vec3 vSphericalL00;\runiform vec3 vSphericalL1_1;\runiform vec3 vSphericalL10;\runiform vec3 vSphericalL11;\runiform vec3 vSphericalL2_2;\runiform vec3 vSphericalL2_1;\runiform vec3 vSphericalL20;\runiform vec3 vSphericalL21;\runiform vec3 vSphericalL22;\r#else\nuniform vec3 vSphericalX;\runiform vec3 vSphericalY;\runiform vec3 vSphericalZ;\runiform vec3 vSphericalXX_ZZ;\runiform vec3 vSphericalYY_ZZ;\runiform vec3 vSphericalZZ;\runiform vec3 vSphericalXY;\runiform vec3 vSphericalYZ;\runiform vec3 vSphericalZX;\r#endif\n#endif\n#define ADDITIONAL_FRAGMENT_DECLARATION\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrFragmentDeclaration = { name, shader };\n//# sourceMappingURL=pbrFragmentDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nimport \"./samplerFragmentDeclaration.js\";\nimport \"./samplerFragmentAlternateDeclaration.js\";\nconst name = \"pbrFragmentSamplersDeclaration\";\nconst shader = `#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL)\nuniform sampler2D clearCoatRoughnessSampler;\r#endif\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL)\nuniform sampler2D sheenRoughnessSampler;\r#endif\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy)\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\r#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\runiform samplerCube reflectionSamplerHigh;\r#endif\n#ifdef USEIRRADIANCEMAP\nuniform samplerCube irradianceSampler;\r#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\r#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D reflectionSamplerLow;\runiform sampler2D reflectionSamplerHigh;\r#endif\n#ifdef USEIRRADIANCEMAP\nuniform sampler2D irradianceSampler;\r#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\r#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\r#endif\n#endif\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\r#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\n#ifdef SS_REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\r#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\runiform samplerCube refractionSamplerHigh;\r#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\r#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D refractionSamplerLow;\runiform sampler2D refractionSamplerHigh;\r#endif\n#endif\n#endif\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrFragmentSamplersDeclaration = { name, shader };\n//# sourceMappingURL=pbrFragmentSamplersDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"subSurfaceScatteringFunctions\";\nconst shader = `bool testLightingForSSS(float diffusionProfile)\r{\rreturn diffusionProfile<1.;\r}`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const subSurfaceScatteringFunctions = { name, shader };\n//# sourceMappingURL=subSurfaceScatteringFunctions.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrHelperFunctions\";\nconst shader = `#define RECIPROCAL_PI2 0.15915494\n#define RECIPROCAL_PI 0.31830988618\n#define MINIMUMVARIANCE 0.0005\nfloat convertRoughnessToAverageSlope(float roughness)\r{\rreturn square(roughness)+MINIMUMVARIANCE;\r}\rfloat fresnelGrazingReflectance(float reflectance0) {\rfloat reflectance90=saturate(reflectance0*25.0);\rreturn reflectance90;\r}\rvec2 getAARoughnessFactors(vec3 normalVector) {\r#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalVector.xyz);\rvec3 nDfdy=dFdy(normalVector.xyz);\rfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\rfloat geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);\rfloat geometricAlphaGFactor=sqrt(slopeSquare);\rgeometricAlphaGFactor*=0.75;\rreturn vec2(geometricRoughnessFactor,geometricAlphaGFactor);\r#else\nreturn vec2(0.);\r#endif\n}\r#ifdef ANISOTROPIC\n#ifdef ANISOTROPIC_LEGACY\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {\rfloat alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);\rfloat alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);\rreturn vec2(alphaT,alphaB);\r}\rvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {\rvec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;\rvec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);\rvec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);\rvec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));\rreturn anisotropicNormal;\r}\r#else\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {\rfloat alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);\rfloat alphaB=max(alphaG,MINIMUMVARIANCE);\rreturn vec2(alphaT,alphaB);\r}\rvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {\rvec3 bentNormal=cross(B,V);\rbentNormal=normalize(cross(bentNormal,B));\rfloat a=square(square(1.0-anisotropy*(1.0-roughness)));\rbentNormal=normalize(mix(bentNormal,N,a));\rreturn bentNormal;\r}\r#endif\n#endif\n#if defined(CLEARCOAT) || defined(SS_REFRACTION)\nvec3 cocaLambert(vec3 alpha,float distance) {\rreturn exp(-alpha*distance);\r}\rvec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {\rreturn cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));\r}\rvec3 computeColorAtDistanceInMedia(vec3 color,float distance) {\rreturn -log(color)/distance;\r}\rvec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {\rvec3 clearCoatAbsorption=mix(vec3(1.0),\rcocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),\rclearCoatIntensity);\rreturn clearCoatAbsorption;\r}\r#endif\n#ifdef MICROSURFACEAUTOMATIC\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\r{\rconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\rfloat reflectivityLuminance=getLuminance(reflectivityColor);\rfloat reflectivityLuma=sqrt(reflectivityLuminance);\rmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\rreturn microSurface;\r}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrHelperFunctions = { name, shader };\n//# sourceMappingURL=pbrHelperFunctions.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"hdrFilteringFunctions\";\nconst shader = `#ifdef NUM_SAMPLES\n#if NUM_SAMPLES>0\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nfloat radicalInverse_VdC(uint bits) \r{\rbits=(bits<<16u) | (bits>>16u);\rbits=((bits & 0x55555555u)<<1u) | ((bits & 0xAAAAAAAAu)>>1u);\rbits=((bits & 0x33333333u)<<2u) | ((bits & 0xCCCCCCCCu)>>2u);\rbits=((bits & 0x0F0F0F0Fu)<<4u) | ((bits & 0xF0F0F0F0u)>>4u);\rbits=((bits & 0x00FF00FFu)<<8u) | ((bits & 0xFF00FF00u)>>8u);\rreturn float(bits)*2.3283064365386963e-10; \r}\rvec2 hammersley(uint i,uint N)\r{\rreturn vec2(float(i)/float(N),radicalInverse_VdC(i));\r}\r#else\nfloat vanDerCorpus(int n,int base)\r{\rfloat invBase=1.0/float(base);\rfloat denom =1.0;\rfloat result =0.0;\rfor(int i=0; i<32; ++i)\r{\rif(n>0)\r{\rdenom =mod(float(n),2.0);\rresult+=denom*invBase;\rinvBase=invBase/2.0;\rn =int(float(n)/2.0);\r}\r}\rreturn result;\r}\rvec2 hammersley(int i,int N)\r{\rreturn vec2(float(i)/float(N),vanDerCorpus(i,2));\r}\r#endif\nfloat log4(float x) {\rreturn log2(x)/2.;\r}\rconst float NUM_SAMPLES_FLOAT=float(NUM_SAMPLES);\rconst float NUM_SAMPLES_FLOAT_INVERSED=1./NUM_SAMPLES_FLOAT;\rconst float K=4.;\r#define inline\nvec3 irradiance(samplerCube inputTexture,vec3 inputN,vec2 filteringInfo)\r{\rvec3 n=normalize(inputN);\rvec3 result=vec3(0.0);\rvec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);\rtangent=normalize(cross(tangent,n));\rvec3 bitangent=cross(n,tangent);\rmat3 tbn=mat3(tangent,bitangent,n);\rfloat maxLevel=filteringInfo.y;\rfloat dim0=filteringInfo.x;\rfloat omegaP=(4.*PI)/(6.*dim0*dim0);\r#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nfor(uint i=0u; i0.) {\rfloat pdf_inversed=PI/NoL;\rfloat omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;\rfloat l=log4(omegaS)-log4(omegaP)+log4(K);\rfloat mipLevel=clamp(l,0.0,maxLevel);\rvec3 c=textureCubeLodEXT(inputTexture,tbn*Ls,mipLevel).rgb;\r#ifdef GAMMA_INPUT\nc=toLinearSpace(c);\r#endif\nresult+=c;\r}\r}\rresult=result*NUM_SAMPLES_FLOAT_INVERSED;\rreturn result;\r}\r#define inline\nvec3 radiance(float alphaG,samplerCube inputTexture,vec3 inputN,vec2 filteringInfo)\r{\rvec3 n=normalize(inputN);\rif (alphaG==0.) {\rvec3 c=textureCube(inputTexture,n).rgb;\r#ifdef GAMMA_INPUT\nc=toLinearSpace(c);\r#endif\nreturn c;\r} else {\rvec3 result=vec3(0.);\rvec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);\rtangent=normalize(cross(tangent,n));\rvec3 bitangent=cross(n,tangent);\rmat3 tbn=mat3(tangent,bitangent,n);\rfloat maxLevel=filteringInfo.y;\rfloat dim0=filteringInfo.x;\rfloat omegaP=(4.*PI)/(6.*dim0*dim0);\rfloat weight=0.;\r#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nfor(uint i=0u; i0.) {\rfloat pdf_inversed=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);\rfloat omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;\rfloat l=log4(omegaS)-log4(omegaP)+log4(K);\rfloat mipLevel=clamp(float(l),0.0,maxLevel);\rweight+=NoL;\rvec3 c=textureCubeLodEXT(inputTexture,tbn*L,mipLevel).rgb;\r#ifdef GAMMA_INPUT\nc=toLinearSpace(c);\r#endif\nresult+=c*NoL;\r}\r}\rresult=result/weight;\rreturn result;\r}\r}\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const hdrFilteringFunctions = { name, shader };\n//# sourceMappingURL=hdrFilteringFunctions.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrDirectLightingFunctions\";\nconst shader = `#define CLEARCOATREFLECTANCE90 1.0\nstruct lightingInfo\r{\rvec3 diffuse;\r#ifdef SPECULARTERM\nvec3 specular;\r#endif\n#ifdef CLEARCOAT\nvec4 clearCoat;\r#endif\n#ifdef SHEEN\nvec3 sheen;\r#endif\n};\rfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance) {\r#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\nfloat lightRoughness=lightRadius/lightDistance;\rfloat totalRoughness=saturate(lightRoughness+roughness);\rreturn totalRoughness;\r#else\nreturn roughness;\r#endif\n}\rvec3 computeHemisphericDiffuseLighting(preLightingInfo info,vec3 lightColor,vec3 groundColor) {\rreturn mix(groundColor,lightColor,info.NdotL);\r}\rvec3 computeDiffuseLighting(preLightingInfo info,vec3 lightColor) {\rfloat diffuseTerm=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);\rreturn diffuseTerm*info.attenuation*info.NdotL*lightColor;\r}\r#define inline\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\rvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\rstrq/=strq.w;\rvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\rreturn toLinearSpace(textureColor);\r}\r#ifdef SS_TRANSLUCENCY\nvec3 computeDiffuseAndTransmittedLighting(preLightingInfo info,vec3 lightColor,vec3 transmittance) {\rfloat NdotL=absEps(info.NdotLUnclamped);\rfloat wrapNdotL=computeWrappedDiffuseNdotL(NdotL,0.02);\rfloat trAdapt=step(0.,info.NdotLUnclamped);\rvec3 transmittanceNdotL=mix(transmittance*wrapNdotL,vec3(wrapNdotL),trAdapt);\rfloat diffuseTerm=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);\rreturn diffuseTerm*transmittanceNdotL*info.attenuation*lightColor;\r}\r#endif\n#ifdef SPECULARTERM\nvec3 computeSpecularLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {\rfloat NdotH=saturateEps(dot(N,info.H));\rfloat roughness=max(info.roughness,geometricRoughnessFactor);\rfloat alphaG=convertRoughnessToAverageSlope(roughness);\rvec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90);\r#ifdef IRIDESCENCE\nfresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);\r#endif\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\r#ifdef BRDF_V_HEIGHT_CORRELATED\nfloat smithVisibility=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG);\r#else\nfloat smithVisibility=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG);\r#endif\nvec3 specTerm=fresnel*distribution*smithVisibility;\rreturn specTerm*info.attenuation*info.NdotL*lightColor;\r}\r#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) {\rfloat NdotH=saturateEps(dot(N,info.H));\rfloat TdotH=dot(T,info.H);\rfloat BdotH=dot(B,info.H);\rfloat TdotV=dot(T,V);\rfloat BdotV=dot(B,V);\rfloat TdotL=dot(T,info.L);\rfloat BdotL=dot(B,info.L);\rfloat alphaG=convertRoughnessToAverageSlope(info.roughness);\rvec2 alphaTB=getAnisotropicRoughness(alphaG,anisotropy);\ralphaTB=max(alphaTB,square(geometricRoughnessFactor));\rvec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90);\r#ifdef IRIDESCENCE\nfresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);\r#endif\nfloat distribution=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);\rfloat smithVisibility=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);\rvec3 specTerm=fresnel*distribution*smithVisibility;\rreturn specTerm*info.attenuation*info.NdotL*lightColor;\r}\r#endif\n#ifdef CLEARCOAT\nvec4 computeClearCoatLighting(preLightingInfo info,vec3 Ncc,float geometricRoughnessFactor,float clearCoatIntensity,vec3 lightColor) {\rfloat NccdotL=saturateEps(dot(Ncc,info.L));\rfloat NccdotH=saturateEps(dot(Ncc,info.H));\rfloat clearCoatRoughness=max(info.roughness,geometricRoughnessFactor);\rfloat alphaG=convertRoughnessToAverageSlope(clearCoatRoughness);\rfloat fresnel=fresnelSchlickGGX(info.VdotH,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);\rfresnel*=clearCoatIntensity;\rfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);\rfloat kelemenVisibility=visibility_Kelemen(info.VdotH);\rfloat clearCoatTerm=fresnel*distribution*kelemenVisibility;\rreturn vec4(\rclearCoatTerm*info.attenuation*NccdotL*lightColor,\r1.0-fresnel\r);\r}\rvec3 computeClearCoatLightingAbsorption(float NdotVRefract,vec3 L,vec3 Ncc,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {\rvec3 LRefract=-refract(L,Ncc,vClearCoatRefractionParams.y);\rfloat NdotLRefract=saturateEps(dot(Ncc,LRefract));\rvec3 absorption=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);\rreturn absorption;\r}\r#endif\n#ifdef SHEEN\nvec3 computeSheenLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {\rfloat NdotH=saturateEps(dot(N,info.H));\rfloat roughness=max(info.roughness,geometricRoughnessFactor);\rfloat alphaG=convertRoughnessToAverageSlope(roughness);\rfloat fresnel=1.;\rfloat distribution=normalDistributionFunction_CharlieSheen(NdotH,alphaG);\r/*#ifdef SHEEN_SOFTER\rfloat visibility=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG);\r#else */\nfloat visibility=visibility_Ashikhmin(info.NdotL,info.NdotV);\r/* #endif */\rfloat sheenTerm=fresnel*distribution*visibility;\rreturn sheenTerm*info.attenuation*info.NdotL*lightColor;\r}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrDirectLightingFunctions = { name, shader };\n//# sourceMappingURL=pbrDirectLightingFunctions.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrIBLFunctions\";\nconst shader = `#if defined(REFLECTION) || defined(SS_REFRACTION)\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float microsurfaceAverageSlope) {\rfloat microsurfaceAverageSlopeTexels=cubeMapDimensionPixels*microsurfaceAverageSlope;\rfloat lod=log2(microsurfaceAverageSlopeTexels);\rreturn lod;\r}\rfloat getLinearLodFromRoughness(float cubeMapDimensionPixels,float roughness) {\rfloat lod=log2(cubeMapDimensionPixels)*roughness;\rreturn lod;\r}\r#endif\n#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION)\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\rfloat temp=NdotVUnclamped+ambientOcclusion;\rreturn saturate(square(temp)-1.0+ambientOcclusion);\r}\r#endif\n#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION)\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal,vec3 geometricNormal) {\rvec3 reflection=reflect(view,normal);\rfloat temp=saturate(1.0+1.1*dot(reflection,geometricNormal));\rreturn square(temp);\r}\r#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) {\rfloat microsurfaceAverageSlope=alphaG;\rmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\rreturn getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);\r}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrIBLFunctions = { name, shader };\n//# sourceMappingURL=pbrIBLFunctions.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nimport \"./decalFragment.js\";\nconst name = \"pbrBlockAlbedoOpacity\";\nconst shader = `struct albedoOpacityOutParams\r{\rvec3 surfaceAlbedo;\rfloat alpha;\r};\r#define pbr_inline\nvoid albedoOpacityBlock(\rin vec4 vAlbedoColor,\r#ifdef ALBEDO\nin vec4 albedoTexture,\rin vec2 albedoInfos,\r#endif\n#ifdef OPACITY\nin vec4 opacityMap,\rin vec2 vOpacityInfos,\r#endif\n#ifdef DETAIL\nin vec4 detailColor,\rin vec4 vDetailInfos,\r#endif\n#ifdef DECAL\nin vec4 decalColor,\rin vec4 vDecalInfos,\r#endif\nout albedoOpacityOutParams outParams\r)\r{\rvec3 surfaceAlbedo=vAlbedoColor.rgb;\rfloat alpha=vAlbedoColor.a;\r#ifdef ALBEDO\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\r#endif\n#ifdef GAMMAALBEDO\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\r#else\nsurfaceAlbedo*=albedoTexture.rgb;\r#endif\nsurfaceAlbedo*=albedoInfos.y;\r#endif\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nsurfaceAlbedo*=vColor.rgb;\r#endif\n#ifdef DETAIL\nfloat detailAlbedo=2.0*mix(0.5,detailColor.r,vDetailInfos.y);\rsurfaceAlbedo.rgb=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo; \r#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALBEDO\n#ifdef OPACITY\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\r#else\nalpha*=opacityMap.a;\r#endif\nalpha*=vOpacityInfos.y;\r#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\r#endif\n#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST \n#if DEBUGMODE != 88\nif (alpha0\nvec4 surfaceMetallicColorMap;\rvec4 surfaceReflectivityColorMap;\rvec2 metallicRoughness;\rvec3 metallicF0;\r#endif\n};\r#define pbr_inline\nvoid reflectivityBlock(\rin vec4 vReflectivityColor,\r#ifdef METALLICWORKFLOW\nin vec3 surfaceAlbedo,\rin vec4 metallicReflectanceFactors,\r#endif\n#ifdef REFLECTIVITY\nin vec3 reflectivityInfos,\rin vec4 surfaceMetallicOrReflectivityColorMap,\r#endif\n#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\nin vec3 ambientOcclusionColorIn,\r#endif\n#ifdef MICROSURFACEMAP\nin vec4 microSurfaceTexel,\r#endif\n#ifdef DETAIL\nin vec4 detailColor,\rin vec4 vDetailInfos,\r#endif\nout reflectivityOutParams outParams\r)\r{\rfloat microSurface=vReflectivityColor.a;\rvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\r#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\r#ifdef REFLECTIVITY\n#if DEBUGMODE>0\noutParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap;\r#endif\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);\routParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z);\r#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b;\r#else\nmetallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r;\r#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a;\r#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g;\r#endif\n#endif\n#endif\n#ifdef DETAIL\nfloat detailRoughness=mix(0.5,detailColor.b,vDetailInfos.w);\rfloat loLerp=mix(0.,metallicRoughness.g,detailRoughness*2.);\rfloat hiLerp=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);\rmetallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5));\r#endif\n#ifdef MICROSURFACEMAP\nmetallicRoughness.g*=microSurfaceTexel.r;\r#endif\n#if DEBUGMODE>0\noutParams.metallicRoughness=metallicRoughness;\r#endif\n#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS\nmicroSurface=1.0-metallicRoughness.g;\rvec3 baseColor=surfaceAlbedo;\r#ifdef FROSTBITE_REFLECTANCE\noutParams.surfaceAlbedo=baseColor.rgb*(1.0-metallicRoughness.r);\rsurfaceReflectivityColor=mix(0.16*reflectance*reflectance,baseColor,metallicRoughness.r);\r#else\nvec3 metallicF0=metallicReflectanceFactors.rgb;\r#if DEBUGMODE>0\noutParams.metallicF0=metallicF0;\r#endif\noutParams.surfaceAlbedo=mix(baseColor.rgb*(1.0-metallicF0),vec3(0.,0.,0.),metallicRoughness.r);\rsurfaceReflectivityColor=mix(metallicF0,baseColor,metallicRoughness.r);\r#endif\n#else\n#ifdef REFLECTIVITY\nsurfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb;\r#if DEBUGMODE>0\noutParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap;\r#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceMetallicOrReflectivityColorMap.a;\rmicroSurface*=reflectivityInfos.z;\r#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\r#endif\n#ifdef MICROSURFACEMAP\nmicroSurface*=microSurfaceTexel.r;\r#endif\n#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE\n#endif\n#endif\n#endif\nmicroSurface=saturate(microSurface);\rfloat roughness=1.-microSurface;\routParams.microSurface=microSurface;\routParams.roughness=roughness;\routParams.surfaceReflectivityColor=surfaceReflectivityColor;\r}\r`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockReflectivity = { name, shader };\n//# sourceMappingURL=pbrBlockReflectivity.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockAmbientOcclusion\";\nconst shader = `struct ambientOcclusionOutParams\r{\rvec3 ambientOcclusionColor;\r#if DEBUGMODE>0\nvec3 ambientOcclusionColorMap;\r#endif\n};\r#define pbr_inline\nvoid ambientOcclusionBlock(\r#ifdef AMBIENT\nin vec3 ambientOcclusionColorMap_,\rin vec4 vAmbientInfos,\r#endif\nout ambientOcclusionOutParams outParams\r)\r{\rvec3 ambientOcclusionColor=vec3(1.,1.,1.);\r#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=ambientOcclusionColorMap_*vAmbientInfos.y;\r#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\r#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\r#if DEBUGMODE>0\noutParams.ambientOcclusionColorMap=ambientOcclusionColorMap;\r#endif\n#endif\noutParams.ambientOcclusionColor=ambientOcclusionColor;\r}\r`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockAmbientOcclusion = { name, shader };\n//# sourceMappingURL=pbrBlockAmbientOcclusion.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockAlphaFresnel\";\nconst shader = `#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\nstruct alphaFresnelOutParams\r{\rfloat alpha;\r};\r#define pbr_inline\nvoid alphaFresnelBlock(\rin vec3 normalW,\rin vec3 viewDirectionW,\rin float alpha,\rin float microSurface,\rout alphaFresnelOutParams outParams\r)\r{\rfloat opacityPerceptual=alpha;\r#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\r#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\r#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\rvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\routParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\r#ifdef ALPHATEST\nif (outParams.alpha0\nvec3 anisotropyMapData;\r#endif\n};\r#define pbr_inline\nvoid anisotropicBlock(\rin vec3 vAnisotropy,\rin float roughness,\r#ifdef ANISOTROPIC_TEXTURE\nin vec3 anisotropyMapData,\r#endif\nin mat3 TBN,\rin vec3 normalW,\rin vec3 viewDirectionW,\rout anisotropicOutParams outParams\r)\r{\rfloat anisotropy=vAnisotropy.b;\rvec3 anisotropyDirection=vec3(vAnisotropy.xy,0.);\r#ifdef ANISOTROPIC_TEXTURE\nanisotropy*=anisotropyMapData.b;\r#if DEBUGMODE>0\noutParams.anisotropyMapData=anisotropyMapData;\r#endif\nanisotropyMapData.rg=anisotropyMapData.rg*2.0-1.0;\r#ifdef ANISOTROPIC_LEGACY\nanisotropyDirection.rg*=anisotropyMapData.rg;\r#else\nanisotropyDirection.xy=mat2(anisotropyDirection.x,anisotropyDirection.y,-anisotropyDirection.y,anisotropyDirection.x)*normalize(anisotropyMapData.rg);\r#endif\n#endif\nmat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));\rvec3 anisotropicTangent=normalize(anisoTBN*anisotropyDirection);\rvec3 anisotropicBitangent=normalize(cross(anisoTBN[2],anisotropicTangent));\routParams.anisotropy=anisotropy;\routParams.anisotropicTangent=anisotropicTangent;\routParams.anisotropicBitangent=anisotropicBitangent;\routParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy,roughness);\r}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockAnisotropic = { name, shader };\n//# sourceMappingURL=pbrBlockAnisotropic.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockReflection\";\nconst shader = `#ifdef REFLECTION\nstruct reflectionOutParams\r{\rvec4 environmentRadiance;\rvec3 environmentIrradiance;\r#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords;\r#else\nvec2 reflectionCoords;\r#endif\n#ifdef SS_TRANSLUCENCY\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\nvec3 irradianceVector;\r#endif\n#endif\n#endif\n};\r#define pbr_inline\nvoid createReflectionCoords(\rin vec3 vPositionW,\rin vec3 normalW,\r#ifdef ANISOTROPIC\nin anisotropicOutParams anisotropicOut,\r#endif\n#ifdef REFLECTIONMAP_3D\nout vec3 reflectionCoords\r#else\nout vec2 reflectionCoords\r#endif\n)\r{\r#ifdef ANISOTROPIC\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),anisotropicOut.anisotropicNormal);\r#else\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\r#endif\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\r#endif\n#ifdef REFLECTIONMAP_3D\nreflectionCoords=reflectionVector;\r#else\nreflectionCoords=reflectionVector.xy;\r#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\r#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\r#endif\n}\r#define pbr_inline\n#define inline\nvoid sampleReflectionTexture(\rin float alphaG,\rin vec3 vReflectionMicrosurfaceInfos,\rin vec2 vReflectionInfos,\rin vec3 vReflectionColor,\r#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nin float NdotVUnclamped,\r#endif\n#ifdef LINEARSPECULARREFLECTION\nin float roughness,\r#endif\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSampler,\rconst vec3 reflectionCoords,\r#else\nin sampler2D reflectionSampler,\rconst vec2 reflectionCoords,\r#endif\n#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSamplerLow,\rin samplerCube reflectionSamplerHigh,\r#else\nin sampler2D reflectionSamplerLow,\rin sampler2D reflectionSamplerHigh,\r#endif\n#endif\n#ifdef REALTIME_FILTERING\nin vec2 vReflectionFilteringInfo,\r#endif\nout vec4 environmentRadiance\r)\r{\r#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\r#elif defined(LINEARSPECULARREFLECTION)\nfloat reflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness);\r#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG);\r#endif\n#ifdef LODBASEDMICROSFURACE\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\r#ifdef LODINREFLECTIONALPHA\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\rfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\r#else\nfloat requestedReflectionLOD=reflectionLOD;\r#endif\n#ifdef REALTIME_FILTERING\nenvironmentRadiance=vec4(radiance(alphaG,reflectionSampler,reflectionCoords,vReflectionFilteringInfo),1.0);\r#else\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\r#endif\n#else\nfloat lodReflectionNormalized=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));\rfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\rvec4 environmentMid=sampleReflection(reflectionSampler,reflectionCoords);\rif (lodReflectionNormalizedDoubled<1.0){\renvironmentRadiance=mix(\rsampleReflection(reflectionSamplerHigh,reflectionCoords),\renvironmentMid,\rlodReflectionNormalizedDoubled\r);\r} else {\renvironmentRadiance=mix(\renvironmentMid,\rsampleReflection(reflectionSamplerLow,reflectionCoords),\rlodReflectionNormalizedDoubled-1.0\r);\r}\r#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\r#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\r#endif\nenvironmentRadiance.rgb*=vReflectionInfos.x;\renvironmentRadiance.rgb*=vReflectionColor.rgb;\r}\r#define pbr_inline\n#define inline\nvoid reflectionBlock(\rin vec3 vPositionW,\rin vec3 normalW,\rin float alphaG,\rin vec3 vReflectionMicrosurfaceInfos,\rin vec2 vReflectionInfos,\rin vec3 vReflectionColor,\r#ifdef ANISOTROPIC\nin anisotropicOutParams anisotropicOut,\r#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nin float NdotVUnclamped,\r#endif\n#ifdef LINEARSPECULARREFLECTION\nin float roughness,\r#endif\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSampler,\r#else\nin sampler2D reflectionSampler,\r#endif\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nin vec3 vEnvironmentIrradiance,\r#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\nin mat4 reflectionMatrix,\r#endif\n#endif\n#ifdef USEIRRADIANCEMAP\n#ifdef REFLECTIONMAP_3D\nin samplerCube irradianceSampler,\r#else\nin sampler2D irradianceSampler,\r#endif\n#endif\n#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSamplerLow,\rin samplerCube reflectionSamplerHigh,\r#else\nin sampler2D reflectionSamplerLow,\rin sampler2D reflectionSamplerHigh,\r#endif\n#endif\n#ifdef REALTIME_FILTERING\nin vec2 vReflectionFilteringInfo,\r#endif\nout reflectionOutParams outParams\r)\r{\rvec4 environmentRadiance=vec4(0.,0.,0.,0.);\r#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=vec3(0.);\r#else\nvec2 reflectionCoords=vec2(0.);\r#endif\ncreateReflectionCoords(\rvPositionW,\rnormalW,\r#ifdef ANISOTROPIC\nanisotropicOut,\r#endif\nreflectionCoords\r);\rsampleReflectionTexture(\ralphaG,\rvReflectionMicrosurfaceInfos,\rvReflectionInfos,\rvReflectionColor,\r#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nNdotVUnclamped,\r#endif\n#ifdef LINEARSPECULARREFLECTION\nroughness,\r#endif\n#ifdef REFLECTIONMAP_3D\nreflectionSampler,\rreflectionCoords,\r#else\nreflectionSampler,\rreflectionCoords,\r#endif\n#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\rreflectionSamplerHigh,\r#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\r#endif\nenvironmentRadiance\r);\rvec3 environmentIrradiance=vec3(0.,0.,0.);\r#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\r#else\n#ifdef ANISOTROPIC\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(anisotropicOut.anisotropicNormal,0)).xyz;\r#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\r#endif\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\r#endif\n#ifdef INVERTCUBICMAP\nirradianceVector.y*=-1.0;\r#endif\n#if defined(REALTIME_FILTERING)\nenvironmentIrradiance=irradiance(reflectionSampler,irradianceVector,vReflectionFilteringInfo);\r#else\nenvironmentIrradiance=computeEnvironmentIrradiance(irradianceVector);\r#endif\n#ifdef SS_TRANSLUCENCY\noutParams.irradianceVector=irradianceVector;\r#endif\n#endif\n#elif defined(USEIRRADIANCEMAP)\nvec4 environmentIrradiance4=sampleReflection(irradianceSampler,reflectionCoords);\renvironmentIrradiance=environmentIrradiance4.rgb;\r#ifdef RGBDREFLECTION\nenvironmentIrradiance.rgb=fromRGBD(environmentIrradiance4);\r#endif\n#ifdef GAMMAREFLECTION\nenvironmentIrradiance.rgb=toLinearSpace(environmentIrradiance.rgb);\r#endif\n#endif\nenvironmentIrradiance*=vReflectionColor.rgb;\routParams.environmentRadiance=environmentRadiance;\routParams.environmentIrradiance=environmentIrradiance;\routParams.reflectionCoords=reflectionCoords;\r}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockReflection = { name, shader };\n//# sourceMappingURL=pbrBlockReflection.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockSheen\";\nconst shader = `#ifdef SHEEN\nstruct sheenOutParams\r{\rfloat sheenIntensity;\rvec3 sheenColor;\rfloat sheenRoughness;\r#ifdef SHEEN_LINKWITHALBEDO\nvec3 surfaceAlbedo;\r#endif\n#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\nfloat sheenAlbedoScaling;\r#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nvec3 finalSheenRadianceScaled;\r#endif\n#if DEBUGMODE>0\nvec4 sheenMapData;\rvec3 sheenEnvironmentReflectance;\r#endif\n};\r#define pbr_inline\n#define inline\nvoid sheenBlock(\rin vec4 vSheenColor,\r#ifdef SHEEN_ROUGHNESS\nin float vSheenRoughness,\r#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)\nin vec4 sheenMapRoughnessData,\r#endif\n#endif\nin float roughness,\r#ifdef SHEEN_TEXTURE\nin vec4 sheenMapData,\rin float sheenMapLevel,\r#endif\nin float reflectance,\r#ifdef SHEEN_LINKWITHALBEDO\nin vec3 baseColor,\rin vec3 surfaceAlbedo,\r#endif\n#ifdef ENVIRONMENTBRDF\nin float NdotV,\rin vec3 environmentBrdf,\r#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nin vec2 AARoughnessFactors,\rin vec3 vReflectionMicrosurfaceInfos,\rin vec2 vReflectionInfos,\rin vec3 vReflectionColor,\rin vec4 vLightingIntensity,\r#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSampler,\rin vec3 reflectionCoords,\r#else\nin sampler2D reflectionSampler,\rin vec2 reflectionCoords,\r#endif\nin float NdotVUnclamped,\r#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSamplerLow,\rin samplerCube reflectionSamplerHigh,\r#else\nin sampler2D reflectionSamplerLow,\rin sampler2D reflectionSamplerHigh,\r#endif\n#endif\n#ifdef REALTIME_FILTERING\nin vec2 vReflectionFilteringInfo,\r#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)\nin float seo,\r#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)\nin float eho,\r#endif\n#endif\nout sheenOutParams outParams\r)\r{\rfloat sheenIntensity=vSheenColor.a;\r#ifdef SHEEN_TEXTURE\n#if DEBUGMODE>0\noutParams.sheenMapData=sheenMapData;\r#endif\n#endif\n#ifdef SHEEN_LINKWITHALBEDO\nfloat sheenFactor=pow5(1.0-sheenIntensity);\rvec3 sheenColor=baseColor.rgb*(1.0-sheenFactor);\rfloat sheenRoughness=sheenIntensity;\routParams.surfaceAlbedo=surfaceAlbedo*sheenFactor;\r#ifdef SHEEN_TEXTURE\nsheenIntensity*=sheenMapData.a;\r#endif\n#else\nvec3 sheenColor=vSheenColor.rgb;\r#ifdef SHEEN_TEXTURE\n#ifdef SHEEN_GAMMATEXTURE\nsheenColor.rgb*=toLinearSpace(sheenMapData.rgb);\r#else\nsheenColor.rgb*=sheenMapData.rgb;\r#endif\nsheenColor.rgb*=sheenMapLevel;\r#endif\n#ifdef SHEEN_ROUGHNESS\nfloat sheenRoughness=vSheenRoughness;\r#ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE\n#if defined(SHEEN_TEXTURE)\nsheenRoughness*=sheenMapData.a;\r#endif\n#elif defined(SHEEN_TEXTURE_ROUGHNESS)\n#ifdef SHEEN_TEXTURE_ROUGHNESS_IDENTICAL\nsheenRoughness*=sheenMapData.a;\r#else\nsheenRoughness*=sheenMapRoughnessData.a;\r#endif\n#endif\n#else\nfloat sheenRoughness=roughness;\r#ifdef SHEEN_TEXTURE\nsheenIntensity*=sheenMapData.a;\r#endif\n#endif\n#if !defined(SHEEN_ALBEDOSCALING)\nsheenIntensity*=(1.-reflectance);\r#endif\nsheenColor*=sheenIntensity;\r#endif\n#ifdef ENVIRONMENTBRDF\n/*#ifdef SHEEN_SOFTER\rvec3 environmentSheenBrdf=vec3(0.,0.,getBRDFLookupCharlieSheen(NdotV,sheenRoughness));\r#else*/\n#ifdef SHEEN_ROUGHNESS\nvec3 environmentSheenBrdf=getBRDFLookup(NdotV,sheenRoughness);\r#else\nvec3 environmentSheenBrdf=environmentBrdf;\r#endif\n/*#endif*/\r#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nfloat sheenAlphaG=convertRoughnessToAverageSlope(sheenRoughness);\r#ifdef SPECULARAA\nsheenAlphaG+=AARoughnessFactors.y;\r#endif\nvec4 environmentSheenRadiance=vec4(0.,0.,0.,0.);\rsampleReflectionTexture(\rsheenAlphaG,\rvReflectionMicrosurfaceInfos,\rvReflectionInfos,\rvReflectionColor,\r#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nNdotVUnclamped,\r#endif\n#ifdef LINEARSPECULARREFLECTION\nsheenRoughness,\r#endif\nreflectionSampler,\rreflectionCoords,\r#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\rreflectionSamplerHigh,\r#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\r#endif\nenvironmentSheenRadiance\r);\rvec3 sheenEnvironmentReflectance=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf);\r#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)\nsheenEnvironmentReflectance*=seo;\r#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)\nsheenEnvironmentReflectance*=eho;\r#endif\n#if DEBUGMODE>0\noutParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance;\r#endif\noutParams.finalSheenRadianceScaled=\renvironmentSheenRadiance.rgb *\rsheenEnvironmentReflectance *\rvLightingIntensity.z;\r#endif\n#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\noutParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b;\r#endif\noutParams.sheenIntensity=sheenIntensity;\routParams.sheenColor=sheenColor;\routParams.sheenRoughness=sheenRoughness;\r}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockSheen = { name, shader };\n//# sourceMappingURL=pbrBlockSheen.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockClearcoat\";\nconst shader = `struct clearcoatOutParams\r{\rvec3 specularEnvironmentR0;\rfloat conservationFactor;\rvec3 clearCoatNormalW;\rvec2 clearCoatAARoughnessFactors;\rfloat clearCoatIntensity;\rfloat clearCoatRoughness;\r#ifdef REFLECTION\nvec3 finalClearCoatRadianceScaled;\r#endif\n#ifdef CLEARCOAT_TINT\nvec3 absorption;\rfloat clearCoatNdotVRefract;\rvec3 clearCoatColor;\rfloat clearCoatThickness;\r#endif\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nvec3 energyConservationFactorClearCoat;\r#endif\n#if DEBUGMODE>0\nmat3 TBNClearCoat;\rvec2 clearCoatMapData;\rvec4 clearCoatTintMapData;\rvec4 environmentClearCoatRadiance;\rfloat clearCoatNdotV;\rvec3 clearCoatEnvironmentReflectance;\r#endif\n};\r#ifdef CLEARCOAT\n#define pbr_inline\n#define inline\nvoid clearcoatBlock(\rin vec3 vPositionW,\rin vec3 geometricNormalW,\rin vec3 viewDirectionW,\rin vec2 vClearCoatParams,\r#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\nin vec4 clearCoatMapRoughnessData,\r#endif\nin vec3 specularEnvironmentR0,\r#ifdef CLEARCOAT_TEXTURE\nin vec2 clearCoatMapData,\r#endif\n#ifdef CLEARCOAT_TINT\nin vec4 vClearCoatTintParams,\rin float clearCoatColorAtDistance,\rin vec4 vClearCoatRefractionParams,\r#ifdef CLEARCOAT_TINT_TEXTURE\nin vec4 clearCoatTintMapData,\r#endif\n#endif\n#ifdef CLEARCOAT_BUMP\nin vec2 vClearCoatBumpInfos,\rin vec4 clearCoatBumpMapData,\rin vec2 vClearCoatBumpUV,\r#if defined(TANGENT) && defined(NORMAL)\nin mat3 vTBN,\r#else\nin vec2 vClearCoatTangentSpaceParams,\r#endif\n#ifdef OBJECTSPACE_NORMALMAP\nin mat4 normalMatrix,\r#endif\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nin vec3 faceNormal,\r#endif\n#ifdef REFLECTION\nin vec3 vReflectionMicrosurfaceInfos,\rin vec2 vReflectionInfos,\rin vec3 vReflectionColor,\rin vec4 vLightingIntensity,\r#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSampler,\r#else\nin sampler2D reflectionSampler,\r#endif\n#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSamplerLow,\rin samplerCube reflectionSamplerHigh,\r#else\nin sampler2D reflectionSamplerLow,\rin sampler2D reflectionSamplerHigh,\r#endif\n#endif\n#ifdef REALTIME_FILTERING\nin vec2 vReflectionFilteringInfo,\r#endif\n#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n#ifdef RADIANCEOCCLUSION\nin float ambientMonochrome,\r#endif\n#endif\n#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)\nin float frontFacingMultiplier,\r#endif\nout clearcoatOutParams outParams\r)\r{\rfloat clearCoatIntensity=vClearCoatParams.x;\rfloat clearCoatRoughness=vClearCoatParams.y;\r#ifdef CLEARCOAT_TEXTURE\nclearCoatIntensity*=clearCoatMapData.x;\r#ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE\nclearCoatRoughness*=clearCoatMapData.y;\r#endif\n#if DEBUGMODE>0\noutParams.clearCoatMapData=clearCoatMapData;\r#endif\n#endif\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\n#ifdef CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL\nclearCoatRoughness*=clearCoatMapData.y;\r#else\nclearCoatRoughness*=clearCoatMapRoughnessData.y;\r#endif\n#endif\noutParams.clearCoatIntensity=clearCoatIntensity;\routParams.clearCoatRoughness=clearCoatRoughness;\r#ifdef CLEARCOAT_TINT\nvec3 clearCoatColor=vClearCoatTintParams.rgb;\rfloat clearCoatThickness=vClearCoatTintParams.a;\r#ifdef CLEARCOAT_TINT_TEXTURE\n#ifdef CLEARCOAT_TINT_GAMMATEXTURE\nclearCoatColor*=toLinearSpace(clearCoatTintMapData.rgb);\r#else\nclearCoatColor*=clearCoatTintMapData.rgb;\r#endif\nclearCoatThickness*=clearCoatTintMapData.a;\r#if DEBUGMODE>0\noutParams.clearCoatTintMapData=clearCoatTintMapData;\r#endif\n#endif\noutParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);\routParams.clearCoatThickness=clearCoatThickness;\r#endif\n#ifdef CLEARCOAT_REMAP_F0\nvec3 specularEnvironmentR0Updated=getR0RemappedForClearCoat(specularEnvironmentR0);\r#else\nvec3 specularEnvironmentR0Updated=specularEnvironmentR0;\r#endif\noutParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);\rvec3 clearCoatNormalW=geometricNormalW;\r#ifdef CLEARCOAT_BUMP\n#ifdef NORMALXYSCALE\nfloat clearCoatNormalScale=1.0;\r#else\nfloat clearCoatNormalScale=vClearCoatBumpInfos.y;\r#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBNClearCoat=vTBN;\r#else\nvec2 TBNClearCoatUV=vClearCoatBumpUV*frontFacingMultiplier;\rmat3 TBNClearCoat=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams);\r#endif\n#if DEBUGMODE>0\noutParams.TBNClearCoat=TBNClearCoat;\r#endif\n#ifdef OBJECTSPACE_NORMALMAP\nclearCoatNormalW=normalize(clearCoatBumpMapData.xyz *2.0-1.0);\rclearCoatNormalW=normalize(mat3(normalMatrix)*clearCoatNormalW);\r#else\nclearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y);\r#endif\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nclearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal));\r#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nclearCoatNormalW=clearCoatNormalW*frontFacingMultiplier;\r#endif\noutParams.clearCoatNormalW=clearCoatNormalW;\routParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);\rfloat clearCoatNdotVUnclamped=dot(clearCoatNormalW,viewDirectionW);\rfloat clearCoatNdotV=absEps(clearCoatNdotVUnclamped);\r#if DEBUGMODE>0\noutParams.clearCoatNdotV=clearCoatNdotV;\r#endif\n#ifdef CLEARCOAT_TINT\nvec3 clearCoatVRefract=refract(-viewDirectionW,clearCoatNormalW,vClearCoatRefractionParams.y);\routParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract));\r#endif\n#if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION))\nvec3 environmentClearCoatBrdf=getBRDFLookup(clearCoatNdotV,clearCoatRoughness);\r#endif\n#if defined(REFLECTION)\nfloat clearCoatAlphaG=convertRoughnessToAverageSlope(clearCoatRoughness);\r#ifdef SPECULARAA\nclearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y;\r#endif\nvec4 environmentClearCoatRadiance=vec4(0.,0.,0.,0.);\rvec3 clearCoatReflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),clearCoatNormalW);\r#ifdef REFLECTIONMAP_OPPOSITEZ\nclearCoatReflectionVector.z*=-1.0;\r#endif\n#ifdef REFLECTIONMAP_3D\nvec3 clearCoatReflectionCoords=clearCoatReflectionVector;\r#else\nvec2 clearCoatReflectionCoords=clearCoatReflectionVector.xy;\r#ifdef REFLECTIONMAP_PROJECTION\nclearCoatReflectionCoords/=clearCoatReflectionVector.z;\r#endif\nclearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y;\r#endif\nsampleReflectionTexture(\rclearCoatAlphaG,\rvReflectionMicrosurfaceInfos,\rvReflectionInfos,\rvReflectionColor,\r#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nclearCoatNdotVUnclamped,\r#endif\n#ifdef LINEARSPECULARREFLECTION\nclearCoatRoughness,\r#endif\nreflectionSampler,\rclearCoatReflectionCoords,\r#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\rreflectionSamplerHigh,\r#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\r#endif\nenvironmentClearCoatRadiance\r);\r#if DEBUGMODE>0\noutParams.environmentClearCoatRadiance=environmentClearCoatRadiance;\r#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\nvec3 clearCoatEnvironmentReflectance=getReflectanceFromBRDFLookup(vec3(vClearCoatRefractionParams.x),environmentClearCoatBrdf);\r#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat clearCoatEho=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);\rclearCoatEnvironmentReflectance*=clearCoatEho;\r#endif\n#endif\n#endif\n#else\nvec3 clearCoatEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV,vec3(1.),vec3(1.),sqrt(1.-clearCoatRoughness));\r#endif\nclearCoatEnvironmentReflectance*=clearCoatIntensity;\r#if DEBUGMODE>0\noutParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance;\r#endif\noutParams.finalClearCoatRadianceScaled=\renvironmentClearCoatRadiance.rgb *\rclearCoatEnvironmentReflectance *\rvLightingIntensity.z;\r#endif\n#if defined(CLEARCOAT_TINT)\noutParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity);\r#endif\nfloat fresnelIBLClearCoat=fresnelSchlickGGX(clearCoatNdotV,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);\rfresnelIBLClearCoat*=clearCoatIntensity;\routParams.conservationFactor=(1.-fresnelIBLClearCoat);\r#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\noutParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf);\r#endif\n}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockClearcoat = { name, shader };\n//# sourceMappingURL=pbrBlockClearcoat.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockIridescence\";\nconst shader = `struct iridescenceOutParams\r{\rfloat iridescenceIntensity;\rfloat iridescenceIOR;\rfloat iridescenceThickness;\rvec3 specularEnvironmentR0;\r};\r#ifdef IRIDESCENCE\n#define pbr_inline\n#define inline\nvoid iridescenceBlock(\rin vec4 vIridescenceParams,\rin float viewAngle,\rin vec3 specularEnvironmentR0,\r#ifdef IRIDESCENCE_TEXTURE\nin vec2 iridescenceMapData,\r#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nin vec2 iridescenceThicknessMapData,\r#endif\n#ifdef CLEARCOAT\nin float NdotVUnclamped,\r#ifdef CLEARCOAT_TEXTURE\nin vec2 clearCoatMapData,\r#endif\n#endif\nout iridescenceOutParams outParams\r)\r{\rfloat iridescenceIntensity=vIridescenceParams.x;\rfloat iridescenceIOR=vIridescenceParams.y;\rfloat iridescenceThicknessMin=vIridescenceParams.z;\rfloat iridescenceThicknessMax=vIridescenceParams.w;\rfloat iridescenceThicknessWeight=1.;\r#ifdef IRIDESCENCE_TEXTURE\niridescenceIntensity*=iridescenceMapData.x;\r#ifdef IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE\niridescenceThicknessWeight=iridescenceMapData.g;\r#endif\n#endif\n#if defined(IRIDESCENCE_THICKNESS_TEXTURE)\niridescenceThicknessWeight=iridescenceThicknessMapData.g;\r#endif\nfloat iridescenceThickness=mix(iridescenceThicknessMin,iridescenceThicknessMax,iridescenceThicknessWeight);\rfloat topIor=1.; \r#ifdef CLEARCOAT\nfloat clearCoatIntensity=vClearCoatParams.x;\r#ifdef CLEARCOAT_TEXTURE\nclearCoatIntensity*=clearCoatMapData.x;\r#endif\ntopIor=mix(1.0,vClearCoatRefractionParams.w-1.,clearCoatIntensity);\rviewAngle=sqrt(1.0+square(1.0/topIor)*(square(NdotVUnclamped)-1.0));\r#endif\nvec3 iridescenceFresnel=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);\routParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);\routParams.iridescenceIntensity=iridescenceIntensity;\routParams.iridescenceThickness=iridescenceThickness;\routParams.iridescenceIOR=iridescenceIOR;\r}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockIridescence = { name, shader };\n//# sourceMappingURL=pbrBlockIridescence.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockSubSurface\";\nconst shader = `struct subSurfaceOutParams\r{\rvec3 specularEnvironmentReflectance;\r#ifdef SS_REFRACTION\nvec3 finalRefraction;\rvec3 surfaceAlbedo;\r#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nfloat alpha;\r#endif\n#ifdef REFLECTION\nfloat refractionFactorForIrradiance;\r#endif\n#endif\n#ifdef SS_TRANSLUCENCY\nvec3 transmittance;\rfloat translucencyIntensity;\r#ifdef REFLECTION\nvec3 refractionIrradiance;\r#endif\n#endif\n#if DEBUGMODE>0\nvec4 thicknessMap;\rvec4 environmentRefraction;\rvec3 refractionTransmittance;\r#endif\n};\r#ifdef SUBSURFACE\n#define pbr_inline\n#define inline\nvoid subSurfaceBlock(\rin vec3 vSubSurfaceIntensity,\rin vec2 vThicknessParam,\rin vec4 vTintColor,\rin vec3 normalW,\rin vec3 specularEnvironmentReflectance,\r#ifdef SS_THICKNESSANDMASK_TEXTURE\nin vec4 thicknessMap,\r#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nin vec4 refractionIntensityMap,\r#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nin vec4 translucencyIntensityMap,\r#endif\n#ifdef REFLECTION\n#ifdef SS_TRANSLUCENCY\nin mat4 reflectionMatrix,\r#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\nin vec3 irradianceVector_,\r#endif\n#if defined(REALTIME_FILTERING)\nin samplerCube reflectionSampler,\rin vec2 vReflectionFilteringInfo,\r#endif\n#endif\n#ifdef USEIRRADIANCEMAP\n#ifdef REFLECTIONMAP_3D\nin samplerCube irradianceSampler,\r#else\nin sampler2D irradianceSampler,\r#endif\n#endif\n#endif\n#endif\n#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)\nin vec3 surfaceAlbedo,\r#endif\n#ifdef SS_REFRACTION\nin vec3 vPositionW,\rin vec3 viewDirectionW,\rin mat4 view,\rin vec4 vRefractionInfos,\rin mat4 refractionMatrix,\rin vec4 vRefractionMicrosurfaceInfos,\rin vec4 vLightingIntensity,\r#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nin float alpha,\r#endif\n#ifdef SS_LODINREFRACTIONALPHA\nin float NdotVUnclamped,\r#endif\n#ifdef SS_LINEARSPECULARREFRACTION\nin float roughness,\r#endif\nin float alphaG,\r#ifdef SS_REFRACTIONMAP_3D\nin samplerCube refractionSampler,\r#ifndef LODBASEDMICROSFURACE\nin samplerCube refractionSamplerLow,\rin samplerCube refractionSamplerHigh,\r#endif\n#else\nin sampler2D refractionSampler,\r#ifndef LODBASEDMICROSFURACE\nin sampler2D refractionSamplerLow,\rin sampler2D refractionSamplerHigh,\r#endif\n#endif\n#ifdef ANISOTROPIC\nin anisotropicOutParams anisotropicOut,\r#endif\n#ifdef REALTIME_FILTERING\nin vec2 vRefractionFilteringInfo,\r#endif\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\nin vec3 refractionPosition,\rin vec3 refractionSize,\r#endif\n#endif\n#ifdef SS_TRANSLUCENCY\nin vec3 vDiffusionDistance,\r#endif\nout subSurfaceOutParams outParams\r)\r{\routParams.specularEnvironmentReflectance=specularEnvironmentReflectance;\r#ifdef SS_REFRACTION\nfloat refractionIntensity=vSubSurfaceIntensity.x;\r#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nrefractionIntensity*=(1.0-alpha);\routParams.alpha=1.0;\r#endif\n#endif\n#ifdef SS_TRANSLUCENCY\nfloat translucencyIntensity=vSubSurfaceIntensity.y;\r#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\n#if defined(SS_USE_GLTF_TEXTURES)\nfloat thickness=thicknessMap.g*vThicknessParam.y+vThicknessParam.x;\r#else\nfloat thickness=thicknessMap.r*vThicknessParam.y+vThicknessParam.x;\r#endif\n#if DEBUGMODE>0\noutParams.thicknessMap=thicknessMap;\r#endif\n#ifdef SS_MASK_FROM_THICKNESS_TEXTURE\n#if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE)\n#if defined(SS_USE_GLTF_TEXTURES)\nrefractionIntensity*=thicknessMap.r;\r#else\nrefractionIntensity*=thicknessMap.g;\r#endif\n#endif\n#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE)\ntranslucencyIntensity*=thicknessMap.b;\r#endif\n#endif\n#else\nfloat thickness=vThicknessParam.y;\r#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\n#ifdef SS_USE_GLTF_TEXTURES\nrefractionIntensity*=refractionIntensityMap.r;\r#else\nrefractionIntensity*=refractionIntensityMap.g;\r#endif\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\ntranslucencyIntensity*=translucencyIntensityMap.b;\r#endif\n#ifdef SS_TRANSLUCENCY\nthickness=maxEps(thickness);\rvec3 transmittance=transmittanceBRDF_Burley(vTintColor.rgb,vDiffusionDistance,thickness);\rtransmittance*=translucencyIntensity;\routParams.transmittance=transmittance;\routParams.translucencyIntensity=translucencyIntensity;\r#endif\n#ifdef SS_REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\r#ifdef ANISOTROPIC\nvec3 refractionVector=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,vRefractionInfos.y);\r#else\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\r#endif\n#ifdef SS_REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\r#endif\n#ifdef SS_REFRACTIONMAP_3D\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\nrefractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition);\r#endif\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\rvec3 refractionCoords=refractionVector;\rrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\r#else\n#ifdef SS_USE_THICKNESS_AS_DEPTH\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*thickness,1.0)));\r#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\r#endif\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\rrefractionCoords.y=1.0-refractionCoords.y;\r#endif\n#ifdef SS_HAS_THICKNESS\nfloat ior=vRefractionInfos.y;\r#else\nfloat ior=vRefractionMicrosurfaceInfos.w;\r#endif\n#ifdef SS_LODINREFRACTIONALPHA\nfloat refractionAlphaG=alphaG;\rrefractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));\rfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped);\r#elif defined(SS_LINEARSPECULARREFRACTION)\nfloat refractionRoughness=alphaG;\rrefractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));\rfloat refractionLOD=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness);\r#else\nfloat refractionAlphaG=alphaG;\rrefractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));\rfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG);\r#endif\n#ifdef LODBASEDMICROSFURACE\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\r#ifdef SS_LODINREFRACTIONALPHA\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\rfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\r#else\nfloat requestedRefractionLOD=refractionLOD;\r#endif\n#if defined(REALTIME_FILTERING) && defined(SS_REFRACTIONMAP_3D)\nenvironmentRefraction=vec4(radiance(alphaG,refractionSampler,refractionCoords,vRefractionFilteringInfo),1.0);\r#else\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\r#endif\n#else\nfloat lodRefractionNormalized=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));\rfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\rvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\rif (lodRefractionNormalizedDoubled<1.0){\renvironmentRefraction=mix(\rsampleRefraction(refractionSamplerHigh,refractionCoords),\renvironmentRefractionMid,\rlodRefractionNormalizedDoubled\r);\r} else {\renvironmentRefraction=mix(\renvironmentRefractionMid,\rsampleRefraction(refractionSamplerLow,refractionCoords),\rlodRefractionNormalizedDoubled-1.0\r);\r}\r#endif\n#ifdef SS_RGBDREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\r#endif\n#ifdef SS_GAMMAREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\r#endif\nenvironmentRefraction.rgb*=vRefractionInfos.x;\r#endif\n#ifdef SS_REFRACTION\nvec3 refractionTransmittance=vec3(refractionIntensity);\r#ifdef SS_THICKNESSANDMASK_TEXTURE\nvec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);\rrefractionTransmittance*=cocaLambert(volumeAlbedo,thickness);\r#elif defined(SS_LINKREFRACTIONTOTRANSPARENCY)\nfloat maxChannel=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);\rvec3 volumeAlbedo=saturate(maxChannel*surfaceAlbedo);\renvironmentRefraction.rgb*=volumeAlbedo;\r#else\nvec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);\rrefractionTransmittance*=cocaLambert(volumeAlbedo,vThicknessParam.y);\r#endif\n#ifdef SS_ALBEDOFORREFRACTIONTINT\nenvironmentRefraction.rgb*=surfaceAlbedo.rgb;\r#endif\noutParams.surfaceAlbedo=surfaceAlbedo*(1.-refractionIntensity);\r#ifdef REFLECTION\noutParams.refractionFactorForIrradiance=(1.-refractionIntensity);\r#endif\n#ifdef UNUSED_MULTIPLEBOUNCES\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\routParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity);\r#endif\nrefractionTransmittance*=1.0-outParams.specularEnvironmentReflectance;\r#if DEBUGMODE>0\noutParams.refractionTransmittance=refractionTransmittance;\r#endif\noutParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z;\r#if DEBUGMODE>0\noutParams.environmentRefraction=environmentRefraction;\r#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;\r#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\r#endif\n#ifdef INVERTCUBICMAP\nirradianceVector.y*=-1.0;\r#endif\n#else\nvec3 irradianceVector=irradianceVector_;\r#endif\n#if defined(USESPHERICALFROMREFLECTIONMAP)\n#if defined(REALTIME_FILTERING)\nvec3 refractionIrradiance=irradiance(reflectionSampler,-irradianceVector,vReflectionFilteringInfo);\r#else\nvec3 refractionIrradiance=computeEnvironmentIrradiance(-irradianceVector);\r#endif\n#elif defined(USEIRRADIANCEMAP)\n#ifdef REFLECTIONMAP_3D\nvec3 irradianceCoords=irradianceVector;\r#else\nvec2 irradianceCoords=irradianceVector.xy;\r#ifdef REFLECTIONMAP_PROJECTION\nirradianceCoords/=irradianceVector.z;\r#endif\nirradianceCoords.y=1.0-irradianceCoords.y;\r#endif\nvec4 refractionIrradiance=sampleReflection(irradianceSampler,-irradianceCoords);\r#ifdef RGBDREFLECTION\nrefractionIrradiance.rgb=fromRGBD(refractionIrradiance);\r#endif\n#ifdef GAMMAREFLECTION\nrefractionIrradiance.rgb=toLinearSpace(refractionIrradiance.rgb);\r#endif\n#else\nvec4 refractionIrradiance=vec4(0.);\r#endif\nrefractionIrradiance.rgb*=transmittance;\r#ifdef SS_ALBEDOFORTRANSLUCENCYTINT\nrefractionIrradiance.rgb*=surfaceAlbedo.rgb;\r#endif\noutParams.refractionIrradiance=refractionIrradiance.rgb;\r#endif\n}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockSubSurface = { name, shader };\n//# sourceMappingURL=pbrBlockSubSurface.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockNormalGeometric\";\nconst shader = `vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\r#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\r#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\r#endif\nvec3 geometricNormalW=normalW;\r#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\ngeometricNormalW=gl_FrontFacing ? geometricNormalW : -geometricNormalW;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockNormalGeometric = { name, shader };\n//# sourceMappingURL=pbrBlockNormalGeometric.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockNormalFinal\";\nconst shader = `#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\r#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\r#endif\nnormalW*=sign(dot(normalW,faceNormal));\r#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockNormalFinal = { name, shader };\n//# sourceMappingURL=pbrBlockNormalFinal.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockLightmapInit\";\nconst shader = `#ifdef LIGHTMAP\nvec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset);\r#ifdef RGBDLIGHTMAP\nlightmapColor.rgb=fromRGBD(lightmapColor);\r#endif\n#ifdef GAMMALIGHTMAP\nlightmapColor.rgb=toLinearSpace(lightmapColor.rgb);\r#endif\nlightmapColor.rgb*=vLightmapInfos.y;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockLightmapInit = { name, shader };\n//# sourceMappingURL=pbrBlockLightmapInit.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockGeometryInfo\";\nconst shader = `float NdotVUnclamped=dot(normalW,viewDirectionW);\rfloat NdotV=absEps(NdotVUnclamped);\rfloat alphaG=convertRoughnessToAverageSlope(roughness);\rvec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz);\r#ifdef SPECULARAA\nalphaG+=AARoughnessFactors.y;\r#endif\n#if defined(ENVIRONMENTBRDF)\nvec3 environmentBrdf=getBRDFLookup(NdotV,roughness);\r#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=aoOut.ambientOcclusionColor.r;\r#else\nfloat ambientMonochrome=getLuminance(aoOut.ambientOcclusionColor);\r#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\r#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW);\r#endif\n#endif\n#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockGeometryInfo = { name, shader };\n//# sourceMappingURL=pbrBlockGeometryInfo.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockReflectance0\";\nconst shader = `float reflectance=max(max(reflectivityOut.surfaceReflectivityColor.r,reflectivityOut.surfaceReflectivityColor.g),reflectivityOut.surfaceReflectivityColor.b);\rvec3 specularEnvironmentR0=reflectivityOut.surfaceReflectivityColor.rgb;\r#ifdef METALLICWORKFLOW\nvec3 specularEnvironmentR90=vec3(metallicReflectanceFactors.a);\r#else \nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\r#endif\n#ifdef ALPHAFRESNEL\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\rspecularEnvironmentR90=specularEnvironmentR90*reflectance90;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockReflectance0 = { name, shader };\n//# sourceMappingURL=pbrBlockReflectance0.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockReflectance\";\nconst shader = `#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\nvec3 specularEnvironmentReflectance=getReflectanceFromBRDFLookup(clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,environmentBrdf);\r#ifdef RADIANCEOCCLUSION\nspecularEnvironmentReflectance*=seo;\r#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nspecularEnvironmentReflectance*=eho;\r#endif\n#endif\n#endif\n#else\nvec3 specularEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\r#endif\n#ifdef CLEARCOAT\nspecularEnvironmentReflectance*=clearcoatOut.conservationFactor;\r#if defined(CLEARCOAT_TINT)\nspecularEnvironmentReflectance*=clearcoatOut.absorption;\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockReflectance = { name, shader };\n//# sourceMappingURL=pbrBlockReflectance.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockDirectLighting\";\nconst shader = `vec3 diffuseBase=vec3(0.,0.,0.);\r#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\r#endif\n#ifdef CLEARCOAT\nvec3 clearCoatBase=vec3(0.,0.,0.);\r#endif\n#ifdef SHEEN\nvec3 sheenBase=vec3(0.,0.,0.);\r#endif\npreLightingInfo preInfo;\rlightingInfo info;\rfloat shadow=1.; \r#if defined(CLEARCOAT) && defined(CLEARCOAT_TINT)\nvec3 absorption=vec3(0.);\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockDirectLighting = { name, shader };\n//# sourceMappingURL=pbrBlockDirectLighting.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockFinalLitComponents\";\nconst shader = `#if defined(ENVIRONMENTBRDF)\n#ifdef MS_BRDF_ENERGY_CONSERVATION\nvec3 energyConservationFactor=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf);\r#endif\n#endif\n#ifndef METALLICWORKFLOW\n#ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\r#endif\n#endif\n#if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF)\nsurfaceAlbedo.rgb=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb;\r#endif\n#ifdef REFLECTION\nvec3 finalIrradiance=reflectionOut.environmentIrradiance;\r#if defined(CLEARCOAT)\nfinalIrradiance*=clearcoatOut.conservationFactor;\r#if defined(CLEARCOAT_TINT)\nfinalIrradiance*=clearcoatOut.absorption;\r#endif\n#endif\n#if defined(SS_REFRACTION)\nfinalIrradiance*=subSurfaceOut.refractionFactorForIrradiance;\r#endif\n#if defined(SS_TRANSLUCENCY)\nfinalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);\rfinalIrradiance+=subSurfaceOut.refractionIrradiance;\r#endif\nfinalIrradiance*=surfaceAlbedo.rgb;\rfinalIrradiance*=vLightingIntensity.z;\rfinalIrradiance*=aoOut.ambientOcclusionColor;\r#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\rfinalSpecular=max(finalSpecular,0.0);\rvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\r#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nfinalSpecularScaled*=energyConservationFactor;\r#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\nfinalSpecularScaled*=sheenOut.sheenAlbedoScaling;\r#endif\n#endif\n#ifdef REFLECTION\nvec3 finalRadiance=reflectionOut.environmentRadiance.rgb;\rfinalRadiance*=subSurfaceOut.specularEnvironmentReflectance;\rvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\r#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nfinalRadianceScaled*=energyConservationFactor;\r#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\nfinalRadianceScaled*=sheenOut.sheenAlbedoScaling;\r#endif\n#endif\n#ifdef SHEEN\nvec3 finalSheen=sheenBase*sheenOut.sheenColor;\rfinalSheen=max(finalSheen,0.0);\rvec3 finalSheenScaled=finalSheen*vLightingIntensity.x*vLightingIntensity.w;\r#if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nsheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor;\r#if defined(CLEARCOAT_TINT)\nsheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption;\r#endif\n#endif\n#endif\n#ifdef CLEARCOAT\nvec3 finalClearCoat=clearCoatBase;\rfinalClearCoat=max(finalClearCoat,0.0);\rvec3 finalClearCoatScaled=finalClearCoat*vLightingIntensity.x*vLightingIntensity.w;\r#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nfinalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat;\r#endif\n#ifdef SS_REFRACTION\nsubSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor;\r#ifdef CLEARCOAT_TINT\nsubSurfaceOut.finalRefraction*=clearcoatOut.absorption;\r#endif\n#endif\n#endif\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\r#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\r#if defined(CLEARCOAT)\nluminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled);\r#endif\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\r#endif\n#if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalClearCoatScaled);\r#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA)\nalpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha);\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockFinalLitComponents = { name, shader };\n//# sourceMappingURL=pbrBlockFinalLitComponents.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockFinalUnlitComponents\";\nconst shader = `vec3 finalDiffuse=diffuseBase;\rfinalDiffuse*=surfaceAlbedo.rgb;\rfinalDiffuse=max(finalDiffuse,0.0);\rfinalDiffuse*=vLightingIntensity.x;\rvec3 finalAmbient=vAmbientColor;\rfinalAmbient*=surfaceAlbedo.rgb;\rvec3 finalEmissive=vEmissiveColor;\r#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\r#ifdef GAMMAEMISSIVE\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\r#else\nfinalEmissive*=emissiveColorTex.rgb;\r#endif\nfinalEmissive*= vEmissiveInfos.y;\r#endif\nfinalEmissive*=vLightingIntensity.y;\r#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),aoOut.ambientOcclusionColor,vAmbientInfos.w);\r#else\nvec3 ambientOcclusionForDirectDiffuse=aoOut.ambientOcclusionColor;\r#endif\nfinalAmbient*=aoOut.ambientOcclusionColor;\rfinalDiffuse*=ambientOcclusionForDirectDiffuse;\r`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockFinalUnlitComponents = { name, shader };\n//# sourceMappingURL=pbrBlockFinalUnlitComponents.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockFinalColorComposition\";\nconst shader = `vec4 finalColor=vec4(\r#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance +\r#endif\n#ifdef SPECULARTERM\nfinalSpecularScaled +\r#endif\n#ifdef SHEEN\nfinalSheenScaled +\r#endif\n#ifdef CLEARCOAT\nfinalClearCoatScaled +\r#endif\n#ifdef REFLECTION\nfinalRadianceScaled +\r#if defined(SHEEN) && defined(ENVIRONMENTBRDF)\nsheenOut.finalSheenRadianceScaled +\r#endif\n#ifdef CLEARCOAT\nclearcoatOut.finalClearCoatRadianceScaled +\r#endif\n#endif\n#ifdef SS_REFRACTION\nsubSurfaceOut.finalRefraction +\r#endif\n#endif\nfinalAmbient +\rfinalDiffuse,\ralpha);\r#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor.rgb;\r#else\nfinalColor.rgb+=lightmapColor.rgb;\r#endif\n#endif\n#endif\nfinalColor.rgb+=finalEmissive;\r#define CUSTOM_FRAGMENT_BEFORE_FOG\nfinalColor=max(finalColor,0.0);\r`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockFinalColorComposition = { name, shader };\n//# sourceMappingURL=pbrBlockFinalColorComposition.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockImageProcessing\";\nconst shader = `#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING)\n#if !defined(SKIPFINALCOLORCLAMP)\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\r#endif\n#else\nfinalColor=applyImageProcessing(finalColor);\r#endif\nfinalColor.a*=visibility;\r#ifdef PREMULTIPLYALPHA\nfinalColor.rgb*=finalColor.a;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockImageProcessing = { name, shader };\n//# sourceMappingURL=pbrBlockImageProcessing.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrDebug\";\nconst shader = `#if DEBUGMODE>0\nif (vClipSpacePosition.x/vClipSpacePosition.w>=vDebugMode.x) {\r#if DEBUGMODE==1\ngl_FragColor.rgb=vPositionW.rgb;\r#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==2 && defined(NORMAL)\ngl_FragColor.rgb=vNormalW.rgb;\r#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==3 && defined(BUMP) || DEBUGMODE==3 && defined(PARALLAX) || DEBUGMODE==3 && defined(ANISOTROPIC)\ngl_FragColor.rgb=TBN[0];\r#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==4 && defined(BUMP) || DEBUGMODE==4 && defined(PARALLAX) || DEBUGMODE==4 && defined(ANISOTROPIC)\ngl_FragColor.rgb=TBN[1];\r#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==5\ngl_FragColor.rgb=normalW;\r#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==6 && defined(MAINUV1)\ngl_FragColor.rgb=vec3(vMainUV1,0.0);\r#elif DEBUGMODE==7 && defined(MAINUV2)\ngl_FragColor.rgb=vec3(vMainUV2,0.0);\r#elif DEBUGMODE==8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)\ngl_FragColor.rgb=clearcoatOut.TBNClearCoat[0];\r#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)\ngl_FragColor.rgb=clearcoatOut.TBNClearCoat[1];\r#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==10 && defined(CLEARCOAT)\ngl_FragColor.rgb=clearcoatOut.clearCoatNormalW;\r#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==11 && defined(ANISOTROPIC)\ngl_FragColor.rgb=anisotropicOut.anisotropicNormal;\r#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==12 && defined(ANISOTROPIC)\ngl_FragColor.rgb=anisotropicOut.anisotropicTangent;\r#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==13 && defined(ANISOTROPIC)\ngl_FragColor.rgb=anisotropicOut.anisotropicBitangent;\r#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==20 && defined(ALBEDO)\ngl_FragColor.rgb=albedoTexture.rgb;\r#elif DEBUGMODE==21 && defined(AMBIENT)\ngl_FragColor.rgb=aoOut.ambientOcclusionColorMap.rgb;\r#elif DEBUGMODE==22 && defined(OPACITY)\ngl_FragColor.rgb=opacityMap.rgb;\r#elif DEBUGMODE==23 && defined(EMISSIVE)\ngl_FragColor.rgb=emissiveColorTex.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==24 && defined(LIGHTMAP)\ngl_FragColor.rgb=lightmapColor.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW)\ngl_FragColor.rgb=reflectivityOut.surfaceMetallicColorMap.rgb;\r#elif DEBUGMODE==26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW)\ngl_FragColor.rgb=reflectivityOut.surfaceReflectivityColorMap.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE)\ngl_FragColor.rgb=vec3(clearcoatOut.clearCoatMapData.rg,0.0);\r#elif DEBUGMODE==28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)\ngl_FragColor.rgb=clearcoatOut.clearCoatTintMapData.rgb;\r#elif DEBUGMODE==29 && defined(SHEEN) && defined(SHEEN_TEXTURE)\ngl_FragColor.rgb=sheenOut.sheenMapData.rgb;\r#elif DEBUGMODE==30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE)\ngl_FragColor.rgb=anisotropicOut.anisotropyMapData.rgb;\r#elif DEBUGMODE==31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE)\ngl_FragColor.rgb=subSurfaceOut.thicknessMap.rgb;\r#elif DEBUGMODE==40 && defined(SS_REFRACTION)\ngl_FragColor.rgb=subSurfaceOut.environmentRefraction.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==41 && defined(REFLECTION)\ngl_FragColor.rgb=reflectionOut.environmentRadiance.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==42 && defined(CLEARCOAT) && defined(REFLECTION)\ngl_FragColor.rgb=clearcoatOut.environmentClearCoatRadiance.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==50\ngl_FragColor.rgb=diffuseBase.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==51 && defined(SPECULARTERM)\ngl_FragColor.rgb=specularBase.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==52 && defined(CLEARCOAT)\ngl_FragColor.rgb=clearCoatBase.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==53 && defined(SHEEN)\ngl_FragColor.rgb=sheenBase.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==54 && defined(REFLECTION)\ngl_FragColor.rgb=reflectionOut.environmentIrradiance.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==60\ngl_FragColor.rgb=surfaceAlbedo.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==61\ngl_FragColor.rgb=clearcoatOut.specularEnvironmentR0;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==62 && defined(METALLICWORKFLOW)\ngl_FragColor.rgb=vec3(reflectivityOut.metallicRoughness.r);\r#elif DEBUGMODE==71 && defined(METALLICWORKFLOW)\ngl_FragColor.rgb=reflectivityOut.metallicF0;\r#elif DEBUGMODE==63\ngl_FragColor.rgb=vec3(roughness);\r#elif DEBUGMODE==64\ngl_FragColor.rgb=vec3(alphaG);\r#elif DEBUGMODE==65\ngl_FragColor.rgb=vec3(NdotV);\r#elif DEBUGMODE==66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT)\ngl_FragColor.rgb=clearcoatOut.clearCoatColor.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==67 && defined(CLEARCOAT)\ngl_FragColor.rgb=vec3(clearcoatOut.clearCoatRoughness);\r#elif DEBUGMODE==68 && defined(CLEARCOAT)\ngl_FragColor.rgb=vec3(clearcoatOut.clearCoatNdotV);\r#elif DEBUGMODE==69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY)\ngl_FragColor.rgb=subSurfaceOut.transmittance;\r#elif DEBUGMODE==70 && defined(SUBSURFACE) && defined(SS_REFRACTION)\ngl_FragColor.rgb=subSurfaceOut.refractionTransmittance;\r#elif DEBUGMODE==72\ngl_FragColor.rgb=vec3(microSurface);\r#elif DEBUGMODE==73\ngl_FragColor.rgb=vAlbedoColor.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==74 && !defined(METALLICWORKFLOW)\ngl_FragColor.rgb=vReflectivityColor.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==75\ngl_FragColor.rgb=vEmissiveColor.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==80 && defined(RADIANCEOCCLUSION)\ngl_FragColor.rgb=vec3(seo);\r#elif DEBUGMODE==81 && defined(HORIZONOCCLUSION)\ngl_FragColor.rgb=vec3(eho);\r#elif DEBUGMODE==82 && defined(MS_BRDF_ENERGY_CONSERVATION)\ngl_FragColor.rgb=vec3(energyConservationFactor);\r#elif DEBUGMODE==83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\ngl_FragColor.rgb=specularEnvironmentReflectance;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\ngl_FragColor.rgb=clearcoatOut.clearCoatEnvironmentReflectance;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==85 && defined(SHEEN) && defined(REFLECTION)\ngl_FragColor.rgb=sheenOut.sheenEnvironmentReflectance;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==86 && defined(ALPHABLEND)\ngl_FragColor.rgb=vec3(luminanceOverAlpha);\r#elif DEBUGMODE==87\ngl_FragColor.rgb=vec3(alpha);\r#elif DEBUGMODE==88 && defined(ALBEDO)\ngl_FragColor.rgb=vec3(albedoTexture.a);\r#else\nfloat stripeWidth=30.;\rfloat stripePos=floor((gl_FragCoord.x+gl_FragCoord.y)/stripeWidth);\rfloat whichColor=mod(stripePos,2.);\rvec3 color1=vec3(.6,.2,.2);\rvec3 color2=vec3(.3,.1,.1);\rgl_FragColor.rgb=mix(color1,color2,whichColor);\r#endif\ngl_FragColor.rgb*=vDebugMode.y;\r#ifdef DEBUGMODE_NORMALIZE\ngl_FragColor.rgb=normalize(gl_FragColor.rgb)*0.5+0.5;\r#endif\n#ifdef DEBUGMODE_GAMMA\ngl_FragColor.rgb=toGammaSpace(gl_FragColor.rgb);\r#endif\ngl_FragColor.a=1.0;\r#ifdef PREPASS\ngl_FragData[0]=toLinearSpace(gl_FragColor); \rgl_FragData[1]=vec4(0.,0.,0.,0.); \r#endif\nreturn;\r}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrDebug = { name, shader };\n//# sourceMappingURL=pbrDebug.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/prePassDeclaration.js\";\nimport \"./ShadersInclude/oitDeclaration.js\";\nimport \"./ShadersInclude/pbrFragmentDeclaration.js\";\nimport \"./ShadersInclude/pbrUboDeclaration.js\";\nimport \"./ShadersInclude/pbrFragmentExtraDeclaration.js\";\nimport \"./ShadersInclude/lightFragmentDeclaration.js\";\nimport \"./ShadersInclude/lightUboDeclaration.js\";\nimport \"./ShadersInclude/pbrFragmentSamplersDeclaration.js\";\nimport \"./ShadersInclude/imageProcessingDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneFragmentDeclaration.js\";\nimport \"./ShadersInclude/logDepthDeclaration.js\";\nimport \"./ShadersInclude/fogFragmentDeclaration.js\";\nimport \"./ShadersInclude/helperFunctions.js\";\nimport \"./ShadersInclude/subSurfaceScatteringFunctions.js\";\nimport \"./ShadersInclude/importanceSampling.js\";\nimport \"./ShadersInclude/pbrHelperFunctions.js\";\nimport \"./ShadersInclude/imageProcessingFunctions.js\";\nimport \"./ShadersInclude/shadowsFragmentFunctions.js\";\nimport \"./ShadersInclude/harmonicsFunctions.js\";\nimport \"./ShadersInclude/pbrDirectLightingSetupFunctions.js\";\nimport \"./ShadersInclude/pbrDirectLightingFalloffFunctions.js\";\nimport \"./ShadersInclude/pbrBRDFFunctions.js\";\nimport \"./ShadersInclude/hdrFilteringFunctions.js\";\nimport \"./ShadersInclude/pbrDirectLightingFunctions.js\";\nimport \"./ShadersInclude/pbrIBLFunctions.js\";\nimport \"./ShadersInclude/bumpFragmentMainFunctions.js\";\nimport \"./ShadersInclude/bumpFragmentFunctions.js\";\nimport \"./ShadersInclude/reflectionFunction.js\";\nimport \"./ShadersInclude/pbrBlockAlbedoOpacity.js\";\nimport \"./ShadersInclude/pbrBlockReflectivity.js\";\nimport \"./ShadersInclude/pbrBlockAmbientOcclusion.js\";\nimport \"./ShadersInclude/pbrBlockAlphaFresnel.js\";\nimport \"./ShadersInclude/pbrBlockAnisotropic.js\";\nimport \"./ShadersInclude/pbrBlockReflection.js\";\nimport \"./ShadersInclude/pbrBlockSheen.js\";\nimport \"./ShadersInclude/pbrBlockClearcoat.js\";\nimport \"./ShadersInclude/pbrBlockIridescence.js\";\nimport \"./ShadersInclude/pbrBlockSubSurface.js\";\nimport \"./ShadersInclude/clipPlaneFragment.js\";\nimport \"./ShadersInclude/pbrBlockNormalGeometric.js\";\nimport \"./ShadersInclude/bumpFragment.js\";\nimport \"./ShadersInclude/pbrBlockNormalFinal.js\";\nimport \"./ShadersInclude/depthPrePass.js\";\nimport \"./ShadersInclude/pbrBlockLightmapInit.js\";\nimport \"./ShadersInclude/pbrBlockGeometryInfo.js\";\nimport \"./ShadersInclude/pbrBlockReflectance0.js\";\nimport \"./ShadersInclude/pbrBlockReflectance.js\";\nimport \"./ShadersInclude/pbrBlockDirectLighting.js\";\nimport \"./ShadersInclude/lightFragment.js\";\nimport \"./ShadersInclude/pbrBlockFinalLitComponents.js\";\nimport \"./ShadersInclude/pbrBlockFinalUnlitComponents.js\";\nimport \"./ShadersInclude/pbrBlockFinalColorComposition.js\";\nimport \"./ShadersInclude/logDepthFragment.js\";\nimport \"./ShadersInclude/fogFragment.js\";\nimport \"./ShadersInclude/pbrBlockImageProcessing.js\";\nimport \"./ShadersInclude/oitFragment.js\";\nimport \"./ShadersInclude/pbrDebug.js\";\nconst name = \"pbrPixelShader\";\nconst shader = `#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[SCENE_MRT_COUNT]\nprecision highp float;\r#include\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE\n#endif\n#include<__decl__pbrFragment>\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#ifdef REFLECTION\n#include\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\nvoid main(void) {\r#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#include\n#include\n#include\nalbedoOpacityOutParams albedoOpacityOut;\r#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\r#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\r#endif\n#ifdef DECAL\nvec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset);\r#endif\nalbedoOpacityBlock(\rvAlbedoColor,\r#ifdef ALBEDO\nalbedoTexture,\rvAlbedoInfos,\r#endif\n#ifdef OPACITY\nopacityMap,\rvOpacityInfos,\r#endif\n#ifdef DETAIL\ndetailColor,\rvDetailInfos,\r#endif\n#ifdef DECAL\ndecalColor,\rvDecalInfos,\r#endif\nalbedoOpacityOut\r);\rvec3 surfaceAlbedo=albedoOpacityOut.surfaceAlbedo;\rfloat alpha=albedoOpacityOut.alpha;\r#define CUSTOM_FRAGMENT_UPDATE_ALPHA\n#include\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\nambientOcclusionOutParams aoOut;\r#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb;\r#endif\nambientOcclusionBlock(\r#ifdef AMBIENT\nambientOcclusionColorMap,\rvAmbientInfos,\r#endif\naoOut\r);\r#include\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\r#else\nvec3 baseColor=surfaceAlbedo;\rreflectivityOutParams reflectivityOut;\r#if defined(REFLECTIVITY)\nvec4 surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\rvec4 baseReflectivity=surfaceMetallicOrReflectivityColorMap;\r#ifndef METALLICWORKFLOW\n#ifdef REFLECTIVITY_GAMMA\nsurfaceMetallicOrReflectivityColorMap=toLinearSpace(surfaceMetallicOrReflectivityColorMap);\r#endif\nsurfaceMetallicOrReflectivityColorMap.rgb*=vReflectivityInfos.y;\r#endif\n#endif\n#if defined(MICROSURFACEMAP)\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\r#endif\n#ifdef METALLICWORKFLOW\nvec4 metallicReflectanceFactors=vMetallicReflectanceFactors;\r#ifdef REFLECTANCE\nvec4 reflectanceFactorsMap=texture2D(reflectanceSampler,vReflectanceUV+uvOffset);\r#ifdef REFLECTANCE_GAMMA\nreflectanceFactorsMap=toLinearSpace(reflectanceFactorsMap);\r#endif\nmetallicReflectanceFactors.rgb*=reflectanceFactorsMap.rgb;\r#endif\n#ifdef METALLIC_REFLECTANCE\nvec4 metallicReflectanceFactorsMap=texture2D(metallicReflectanceSampler,vMetallicReflectanceUV+uvOffset);\r#ifdef METALLIC_REFLECTANCE_GAMMA\nmetallicReflectanceFactorsMap=toLinearSpace(metallicReflectanceFactorsMap);\r#endif\n#ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY\nmetallicReflectanceFactors.rgb*=metallicReflectanceFactorsMap.rgb;\r#endif\nmetallicReflectanceFactors*=metallicReflectanceFactorsMap.a;\r#endif\n#endif\nreflectivityBlock(\rvReflectivityColor,\r#ifdef METALLICWORKFLOW\nsurfaceAlbedo,\rmetallicReflectanceFactors,\r#endif\n#ifdef REFLECTIVITY\nvReflectivityInfos,\rsurfaceMetallicOrReflectivityColorMap,\r#endif\n#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\naoOut.ambientOcclusionColor,\r#endif\n#ifdef MICROSURFACEMAP\nmicroSurfaceTexel,\r#endif\n#ifdef DETAIL\ndetailColor,\rvDetailInfos,\r#endif\nreflectivityOut\r);\rfloat microSurface=reflectivityOut.microSurface;\rfloat roughness=reflectivityOut.roughness;\r#ifdef METALLICWORKFLOW\nsurfaceAlbedo=reflectivityOut.surfaceAlbedo;\r#endif\n#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\naoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor;\r#endif\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\nalphaFresnelOutParams alphaFresnelOut;\ralphaFresnelBlock(\rnormalW,\rviewDirectionW,\ralpha,\rmicroSurface,\ralphaFresnelOut\r);\ralpha=alphaFresnelOut.alpha;\r#endif\n#endif\n#include\n#ifdef ANISOTROPIC\nanisotropicOutParams anisotropicOut;\r#ifdef ANISOTROPIC_TEXTURE\nvec3 anisotropyMapData=texture2D(anisotropySampler,vAnisotropyUV+uvOffset).rgb*vAnisotropyInfos.y;\r#endif\nanisotropicBlock(\rvAnisotropy,\rroughness,\r#ifdef ANISOTROPIC_TEXTURE\nanisotropyMapData,\r#endif\nTBN,\rnormalW,\rviewDirectionW,\ranisotropicOut\r);\r#endif\n#ifdef REFLECTION\nreflectionOutParams reflectionOut;\r#ifndef USE_CUSTOM_REFLECTION\nreflectionBlock(\rvPositionW,\rnormalW,\ralphaG,\rvReflectionMicrosurfaceInfos,\rvReflectionInfos,\rvReflectionColor,\r#ifdef ANISOTROPIC\nanisotropicOut,\r#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nNdotVUnclamped,\r#endif\n#ifdef LINEARSPECULARREFLECTION\nroughness,\r#endif\nreflectionSampler,\r#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nvEnvironmentIrradiance,\r#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\nreflectionMatrix,\r#endif\n#endif\n#ifdef USEIRRADIANCEMAP\nirradianceSampler,\r#endif\n#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\rreflectionSamplerHigh,\r#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\r#endif\nreflectionOut\r);\r#else\n#define CUSTOM_REFLECTION\n#endif\n#endif\n#include\n#ifdef SHEEN\nsheenOutParams sheenOut;\r#ifdef SHEEN_TEXTURE\nvec4 sheenMapData=texture2D(sheenSampler,vSheenUV+uvOffset);\r#endif\n#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)\nvec4 sheenMapRoughnessData=texture2D(sheenRoughnessSampler,vSheenRoughnessUV+uvOffset)*vSheenInfos.w;\r#endif\nsheenBlock(\rvSheenColor,\r#ifdef SHEEN_ROUGHNESS\nvSheenRoughness,\r#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)\nsheenMapRoughnessData,\r#endif\n#endif\nroughness,\r#ifdef SHEEN_TEXTURE\nsheenMapData,\rvSheenInfos.y,\r#endif\nreflectance,\r#ifdef SHEEN_LINKWITHALBEDO\nbaseColor,\rsurfaceAlbedo,\r#endif\n#ifdef ENVIRONMENTBRDF\nNdotV,\renvironmentBrdf,\r#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nAARoughnessFactors,\rvReflectionMicrosurfaceInfos,\rvReflectionInfos,\rvReflectionColor,\rvLightingIntensity,\rreflectionSampler,\rreflectionOut.reflectionCoords,\rNdotVUnclamped,\r#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\rreflectionSamplerHigh,\r#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\r#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)\nseo,\r#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)\neho,\r#endif\n#endif\nsheenOut\r);\r#ifdef SHEEN_LINKWITHALBEDO\nsurfaceAlbedo=sheenOut.surfaceAlbedo;\r#endif\n#endif\n#ifdef CLEARCOAT\n#ifdef CLEARCOAT_TEXTURE\nvec2 clearCoatMapData=texture2D(clearCoatSampler,vClearCoatUV+uvOffset).rg*vClearCoatInfos.y;\r#endif\n#endif\n#ifdef IRIDESCENCE\niridescenceOutParams iridescenceOut;\r#ifdef IRIDESCENCE_TEXTURE\nvec2 iridescenceMapData=texture2D(iridescenceSampler,vIridescenceUV+uvOffset).rg*vIridescenceInfos.y;\r#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nvec2 iridescenceThicknessMapData=texture2D(iridescenceThicknessSampler,vIridescenceThicknessUV+uvOffset).rg*vIridescenceInfos.w;\r#endif\niridescenceBlock(\rvIridescenceParams,\rNdotV,\rspecularEnvironmentR0,\r#ifdef IRIDESCENCE_TEXTURE\niridescenceMapData,\r#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\niridescenceThicknessMapData,\r#endif\n#ifdef CLEARCOAT\nNdotVUnclamped,\r#ifdef CLEARCOAT_TEXTURE\nclearCoatMapData,\r#endif\n#endif\niridescenceOut\r);\rfloat iridescenceIntensity=iridescenceOut.iridescenceIntensity;\rspecularEnvironmentR0=iridescenceOut.specularEnvironmentR0;\r#endif\nclearcoatOutParams clearcoatOut;\r#ifdef CLEARCOAT\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\nvec4 clearCoatMapRoughnessData=texture2D(clearCoatRoughnessSampler,vClearCoatRoughnessUV+uvOffset)*vClearCoatInfos.w;\r#endif\n#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)\nvec4 clearCoatTintMapData=texture2D(clearCoatTintSampler,vClearCoatTintUV+uvOffset);\r#endif\n#ifdef CLEARCOAT_BUMP\nvec4 clearCoatBumpMapData=texture2D(clearCoatBumpSampler,vClearCoatBumpUV+uvOffset);\r#endif\nclearcoatBlock(\rvPositionW,\rgeometricNormalW,\rviewDirectionW,\rvClearCoatParams,\r#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\nclearCoatMapRoughnessData,\r#endif\nspecularEnvironmentR0,\r#ifdef CLEARCOAT_TEXTURE\nclearCoatMapData,\r#endif\n#ifdef CLEARCOAT_TINT\nvClearCoatTintParams,\rclearCoatColorAtDistance,\rvClearCoatRefractionParams,\r#ifdef CLEARCOAT_TINT_TEXTURE\nclearCoatTintMapData,\r#endif\n#endif\n#ifdef CLEARCOAT_BUMP\nvClearCoatBumpInfos,\rclearCoatBumpMapData,\rvClearCoatBumpUV,\r#if defined(TANGENT) && defined(NORMAL)\nvTBN,\r#else\nvClearCoatTangentSpaceParams,\r#endif\n#ifdef OBJECTSPACE_NORMALMAP\nnormalMatrix,\r#endif\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nfaceNormal,\r#endif\n#ifdef REFLECTION\nvReflectionMicrosurfaceInfos,\rvReflectionInfos,\rvReflectionColor,\rvLightingIntensity,\rreflectionSampler,\r#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\rreflectionSamplerHigh,\r#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\r#endif\n#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n#ifdef RADIANCEOCCLUSION\nambientMonochrome,\r#endif\n#endif\n#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)\n(gl_FrontFacing ? 1. : -1.),\r#endif\nclearcoatOut\r);\r#else\nclearcoatOut.specularEnvironmentR0=specularEnvironmentR0;\r#endif\n#include\nsubSurfaceOutParams subSurfaceOut;\r#ifdef SUBSURFACE\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nvec4 thicknessMap=texture2D(thicknessSampler,vThicknessUV+uvOffset);\r#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nvec4 refractionIntensityMap=texture2D(refractionIntensitySampler,vRefractionIntensityUV+uvOffset);\r#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nvec4 translucencyIntensityMap=texture2D(translucencyIntensitySampler,vTranslucencyIntensityUV+uvOffset);\r#endif\nsubSurfaceBlock(\rvSubSurfaceIntensity,\rvThicknessParam,\rvTintColor,\rnormalW,\rspecularEnvironmentReflectance,\r#ifdef SS_THICKNESSANDMASK_TEXTURE\nthicknessMap,\r#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nrefractionIntensityMap,\r#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\ntranslucencyIntensityMap,\r#endif\n#ifdef REFLECTION\n#ifdef SS_TRANSLUCENCY\nreflectionMatrix,\r#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\nreflectionOut.irradianceVector,\r#endif\n#if defined(REALTIME_FILTERING)\nreflectionSampler,\rvReflectionFilteringInfo,\r#endif\n#endif\n#ifdef USEIRRADIANCEMAP\nirradianceSampler,\r#endif\n#endif\n#endif\n#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)\nsurfaceAlbedo,\r#endif\n#ifdef SS_REFRACTION\nvPositionW,\rviewDirectionW,\rview,\rvRefractionInfos,\rrefractionMatrix,\rvRefractionMicrosurfaceInfos,\rvLightingIntensity,\r#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nalpha,\r#endif\n#ifdef SS_LODINREFRACTIONALPHA\nNdotVUnclamped,\r#endif\n#ifdef SS_LINEARSPECULARREFRACTION\nroughness,\r#endif\nalphaG,\rrefractionSampler,\r#ifndef LODBASEDMICROSFURACE\nrefractionSamplerLow,\rrefractionSamplerHigh,\r#endif\n#ifdef ANISOTROPIC\nanisotropicOut,\r#endif\n#ifdef REALTIME_FILTERING\nvRefractionFilteringInfo,\r#endif\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\nvRefractionPosition,\rvRefractionSize,\r#endif\n#endif\n#ifdef SS_TRANSLUCENCY\nvDiffusionDistance,\r#endif\nsubSurfaceOut\r);\r#ifdef SS_REFRACTION\nsurfaceAlbedo=subSurfaceOut.surfaceAlbedo;\r#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nalpha=subSurfaceOut.alpha;\r#endif\n#endif\n#else\nsubSurfaceOut.specularEnvironmentReflectance=specularEnvironmentReflectance;\r#endif\n#include\n#include[0..maxSimultaneousLights]\n#include\n#endif \n#include\n#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION\n#include\n#include\n#include(color,finalColor)\n#include\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\n#ifdef PREPASS\nfloat writeGeometryInfo=finalColor.a>0.4 ? 1.0 : 0.0;\r#ifdef PREPASS_POSITION\ngl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo);\r#endif\n#ifdef PREPASS_VELOCITY\nvec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;\rvec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;\rvec2 velocity=abs(a-b);\rvelocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;\rgl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo);\r#endif\n#ifdef PREPASS_ALBEDO_SQRT\nvec3 sqAlbedo=sqrt(surfaceAlbedo); \r#endif\n#ifdef PREPASS_IRRADIANCE\nvec3 irradiance=finalDiffuse;\r#ifndef UNLIT\n#ifdef REFLECTION\nirradiance+=finalIrradiance;\r#endif\n#endif\n#ifdef SS_SCATTERING\ngl_FragData[0]=vec4(finalColor.rgb-irradiance,finalColor.a); \rirradiance/=sqAlbedo;\r#else\ngl_FragData[0]=finalColor; \rfloat scatteringDiffusionProfile=255.;\r#endif\ngl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(clamp(irradiance,vec3(0.),vec3(1.)),writeGeometryInfo*scatteringDiffusionProfile/255.); \r#else\ngl_FragData[0]=vec4(finalColor.rgb,finalColor.a);\r#endif\n#ifdef PREPASS_DEPTH\ngl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); \r#endif\n#ifdef PREPASS_NORMAL\ngl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); \r#endif\n#ifdef PREPASS_ALBEDO_SQRT\ngl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqAlbedo,writeGeometryInfo); \r#endif\n#ifdef PREPASS_REFLECTIVITY\n#ifndef UNLIT\ngl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(specularEnvironmentR0,microSurface)*writeGeometryInfo;\r#else\ngl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4( 0.0,0.0,0.0,1.0 )*writeGeometryInfo;\r#endif\n#endif\n#endif\n#if !defined(PREPASS) || defined(WEBGL2)\ngl_FragColor=finalColor;\r#endif\n#include\n#if ORDER_INDEPENDENT_TRANSPARENCY\nif (fragDepth==nearestDepth) {\rfrontColor.rgb+=finalColor.rgb*finalColor.a*alphaMultiplier;\rfrontColor.a=1.0-alphaMultiplier*(1.0-finalColor.a);\r} else {\rbackColor+=finalColor;\r}\r#endif\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const pbrPixelShader = { name, shader };\n//# sourceMappingURL=pbr.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nimport \"./decalVertexDeclaration.js\";\nconst name = \"pbrVertexDeclaration\";\nconst shader = `uniform mat4 view;\runiform mat4 viewProjection;\r#ifdef ALBEDO\nuniform mat4 albedoMatrix;\runiform vec2 vAlbedoInfos;\r#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\runiform vec4 vAmbientInfos;\r#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\runiform vec2 vOpacityInfos;\r#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\runiform mat4 emissiveMatrix;\r#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\runiform mat4 lightmapMatrix;\r#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\runiform mat4 reflectivityMatrix;\r#endif\n#ifdef METALLIC_REFLECTANCE\nuniform vec2 vMetallicReflectanceInfos;\runiform mat4 metallicReflectanceMatrix;\r#endif\n#ifdef REFLECTANCE\nuniform vec2 vReflectanceInfos;\runiform mat4 reflectanceMatrix;\r#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\runiform mat4 microSurfaceSamplerMatrix;\r#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\runiform mat4 bumpMatrix;\r#endif\n#ifdef POINTSIZE\nuniform float pointSize;\r#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\runiform mat4 reflectionMatrix;\r#endif\n#ifdef CLEARCOAT\n#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform vec4 vClearCoatInfos;\r#endif\n#ifdef CLEARCOAT_TEXTURE\nuniform mat4 clearCoatMatrix;\r#endif\n#ifdef CLEARCOAT_TEXTURE_ROUGHNESS\nuniform mat4 clearCoatRoughnessMatrix;\r#endif\n#ifdef CLEARCOAT_BUMP\nuniform vec2 vClearCoatBumpInfos;\runiform mat4 clearCoatBumpMatrix;\r#endif\n#ifdef CLEARCOAT_TINT_TEXTURE\nuniform vec2 vClearCoatTintInfos;\runiform mat4 clearCoatTintMatrix;\r#endif\n#endif\n#ifdef IRIDESCENCE\n#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)\nuniform vec4 vIridescenceInfos;\r#endif\n#ifdef IRIDESCENCE_TEXTURE\nuniform mat4 iridescenceMatrix;\r#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nuniform mat4 iridescenceThicknessMatrix;\r#endif\n#endif\n#ifdef ANISOTROPIC\n#ifdef ANISOTROPIC_TEXTURE\nuniform vec2 vAnisotropyInfos;\runiform mat4 anisotropyMatrix;\r#endif\n#endif\n#ifdef SHEEN\n#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform vec4 vSheenInfos;\r#endif\n#ifdef SHEEN_TEXTURE\nuniform mat4 sheenMatrix;\r#endif\n#ifdef SHEEN_TEXTURE_ROUGHNESS\nuniform mat4 sheenRoughnessMatrix;\r#endif\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\nuniform vec4 vRefractionInfos;\runiform mat4 refractionMatrix;\r#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nuniform vec2 vThicknessInfos;\runiform mat4 thicknessMatrix;\r#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nuniform vec2 vRefractionIntensityInfos;\runiform mat4 refractionIntensityMatrix;\r#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nuniform vec2 vTranslucencyIntensityInfos;\runiform mat4 translucencyIntensityMatrix;\r#endif\n#endif\n#ifdef NORMAL\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nuniform vec3 vSphericalL00;\runiform vec3 vSphericalL1_1;\runiform vec3 vSphericalL10;\runiform vec3 vSphericalL11;\runiform vec3 vSphericalL2_2;\runiform vec3 vSphericalL2_1;\runiform vec3 vSphericalL20;\runiform vec3 vSphericalL21;\runiform vec3 vSphericalL22;\r#else\nuniform vec3 vSphericalX;\runiform vec3 vSphericalY;\runiform vec3 vSphericalZ;\runiform vec3 vSphericalXX_ZZ;\runiform vec3 vSphericalYY_ZZ;\runiform vec3 vSphericalZZ;\runiform vec3 vSphericalXY;\runiform vec3 vSphericalYZ;\runiform vec3 vSphericalZX;\r#endif\n#endif\n#endif\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\runiform mat4 detailMatrix;\r#endif\n#include\n#define ADDITIONAL_VERTEX_DECLARATION\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrVertexDeclaration = { name, shader };\n//# sourceMappingURL=pbrVertexDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/pbrVertexDeclaration.js\";\nimport \"./ShadersInclude/pbrUboDeclaration.js\";\nimport \"./ShadersInclude/uvAttributeDeclaration.js\";\nimport \"./ShadersInclude/mainUVVaryingDeclaration.js\";\nimport \"./ShadersInclude/helperFunctions.js\";\nimport \"./ShadersInclude/bonesDeclaration.js\";\nimport \"./ShadersInclude/bakedVertexAnimationDeclaration.js\";\nimport \"./ShadersInclude/instancesDeclaration.js\";\nimport \"./ShadersInclude/prePassVertexDeclaration.js\";\nimport \"./ShadersInclude/samplerVertexDeclaration.js\";\nimport \"./ShadersInclude/harmonicsFunctions.js\";\nimport \"./ShadersInclude/bumpVertexDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneVertexDeclaration.js\";\nimport \"./ShadersInclude/fogVertexDeclaration.js\";\nimport \"./ShadersInclude/lightVxFragmentDeclaration.js\";\nimport \"./ShadersInclude/lightVxUboDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexGlobalDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexDeclaration.js\";\nimport \"./ShadersInclude/logDepthDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexGlobal.js\";\nimport \"./ShadersInclude/morphTargetsVertex.js\";\nimport \"./ShadersInclude/instancesVertex.js\";\nimport \"./ShadersInclude/bonesVertex.js\";\nimport \"./ShadersInclude/bakedVertexAnimation.js\";\nimport \"./ShadersInclude/prePassVertex.js\";\nimport \"./ShadersInclude/uvVariableDeclaration.js\";\nimport \"./ShadersInclude/samplerVertexImplementation.js\";\nimport \"./ShadersInclude/bumpVertex.js\";\nimport \"./ShadersInclude/clipPlaneVertex.js\";\nimport \"./ShadersInclude/fogVertex.js\";\nimport \"./ShadersInclude/shadowsVertex.js\";\nimport \"./ShadersInclude/vertexColorMixing.js\";\nimport \"./ShadersInclude/logDepthVertex.js\";\nconst name = \"pbrVertexShader\";\nconst shader = `precision highp float;\r#include<__decl__pbrVertex>\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\r#ifdef NORMAL\nattribute vec3 normal;\r#endif\n#ifdef TANGENT\nattribute vec4 tangent;\r#endif\n#ifdef UV1\nattribute vec2 uv;\r#endif\n#include[2..7]\n#include[1..7]\n#ifdef VERTEXCOLOR\nattribute vec4 color;\r#endif\n#include\n#include\n#include\n#include\n#include\n#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance)\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy)\n#endif\n#ifdef SUBSURFACE\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity)\n#endif\nvarying vec3 vPositionW;\r#if DEBUGMODE>0\nvarying vec4 vClipSpacePosition;\r#endif\n#ifdef NORMAL\nvarying vec3 vNormalW;\r#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\r#include\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\r#endif\n#include\n#include\n#include\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\r#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\r#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\r#ifdef NORMAL\nvec3 normalUpdated=normal;\r#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\r#endif\n#ifdef UV1\nvec2 uvUpdated=uv;\r#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\r#endif\n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include\n#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\rvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\r#endif\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\rvPositionW=vec3(worldPos);\r#include\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\r#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));\rvNormalW=normalize(normalWorld*vNormalW);\r#else\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\r#endif\nvNormalW=normalize(normalWorld*normalUpdated);\r#endif\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\r#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\r#endif\nvEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector);\r#endif\n#endif\n#define CUSTOM_VERTEX_UPDATE_WORLDPOS\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {\rgl_Position=viewProjection*worldPos;\r} else {\rgl_Position=viewProjectionR*worldPos;\r}\r#else\ngl_Position=viewProjection*worldPos;\r#endif\n#if DEBUGMODE>0\nvClipSpacePosition=gl_Position;\r#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\r#endif\n#ifndef UV1\nvec2 uvUpdated=vec2(0.,0.);\r#endif\n#ifdef MAINUV1\nvMainUV1=uvUpdated;\r#endif\n#include[2..7]\n#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x)\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z)\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.z)\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x)\n#endif\n#ifdef SUBSURFACE\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x)\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\r#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const pbrVertexShader = { name, shader };\n//# sourceMappingURL=pbr.vertex.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize, serializeAsTexture, expandToProperty, serializeAsColor3 } from \"../../Misc/decorators.js\";\nimport { Color3 } from \"../../Maths/math.color.js\";\nimport { MaterialFlags } from \"../materialFlags.js\";\nimport { MaterialHelper } from \"../../Materials/materialHelper.js\";\n\nimport { MaterialPluginBase } from \"../materialPluginBase.js\";\nimport { MaterialDefines } from \"../materialDefines.js\";\n/**\n * @internal\n */\nexport class MaterialClearCoatDefines extends MaterialDefines {\n constructor() {\n super(...arguments);\n this.CLEARCOAT = false;\n this.CLEARCOAT_DEFAULTIOR = false;\n this.CLEARCOAT_TEXTURE = false;\n this.CLEARCOAT_TEXTURE_ROUGHNESS = false;\n this.CLEARCOAT_TEXTUREDIRECTUV = 0;\n this.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV = 0;\n this.CLEARCOAT_BUMP = false;\n this.CLEARCOAT_BUMPDIRECTUV = 0;\n this.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE = false;\n this.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL = false;\n this.CLEARCOAT_REMAP_F0 = false;\n this.CLEARCOAT_TINT = false;\n this.CLEARCOAT_TINT_TEXTURE = false;\n this.CLEARCOAT_TINT_TEXTUREDIRECTUV = 0;\n this.CLEARCOAT_TINT_GAMMATEXTURE = false;\n }\n}\n/**\n * Plugin that implements the clear coat component of the PBR material\n */\nexport class PBRClearCoatConfiguration extends MaterialPluginBase {\n /** @internal */\n _markAllSubMeshesAsTexturesDirty() {\n this._enable(this._isEnabled);\n this._internalMarkAllSubMeshesAsTexturesDirty();\n }\n constructor(material, addToPluginList = true) {\n super(material, \"PBRClearCoat\", 100, new MaterialClearCoatDefines(), addToPluginList);\n this._isEnabled = false;\n /**\n * Defines if the clear coat is enabled in the material.\n */\n this.isEnabled = false;\n /**\n * Defines the clear coat layer strength (between 0 and 1) it defaults to 1.\n */\n this.intensity = 1;\n /**\n * Defines the clear coat layer roughness.\n */\n this.roughness = 0;\n this._indexOfRefraction = PBRClearCoatConfiguration._DefaultIndexOfRefraction;\n /**\n * Defines the index of refraction of the clear coat.\n * This defaults to 1.5 corresponding to a 0.04 f0 or a 4% reflectance at normal incidence\n * The default fits with a polyurethane material.\n * Changing the default value is more performance intensive.\n */\n this.indexOfRefraction = PBRClearCoatConfiguration._DefaultIndexOfRefraction;\n this._texture = null;\n /**\n * Stores the clear coat values in a texture (red channel is intensity and green channel is roughness)\n * If useRoughnessFromMainTexture is false, the green channel of texture is not used and the green channel of textureRoughness is used instead\n * if textureRoughness is not empty, else no texture roughness is used\n */\n this.texture = null;\n this._useRoughnessFromMainTexture = true;\n /**\n * Indicates that the green channel of the texture property will be used for roughness (default: true)\n * If false, the green channel from textureRoughness is used for roughness\n */\n this.useRoughnessFromMainTexture = true;\n this._textureRoughness = null;\n /**\n * Stores the clear coat roughness in a texture (green channel)\n * Not used if useRoughnessFromMainTexture is true\n */\n this.textureRoughness = null;\n this._remapF0OnInterfaceChange = true;\n /**\n * Defines if the F0 value should be remapped to account for the interface change in the material.\n */\n this.remapF0OnInterfaceChange = true;\n this._bumpTexture = null;\n /**\n * Define the clear coat specific bump texture.\n */\n this.bumpTexture = null;\n this._isTintEnabled = false;\n /**\n * Defines if the clear coat tint is enabled in the material.\n */\n this.isTintEnabled = false;\n /**\n * Defines the clear coat tint of the material.\n * This is only use if tint is enabled\n */\n this.tintColor = Color3.White();\n /**\n * Defines the distance at which the tint color should be found in the\n * clear coat media.\n * This is only use if tint is enabled\n */\n this.tintColorAtDistance = 1;\n /**\n * Defines the clear coat layer thickness.\n * This is only use if tint is enabled\n */\n this.tintThickness = 1;\n this._tintTexture = null;\n /**\n * Stores the clear tint values in a texture.\n * rgb is tint\n * a is a thickness factor\n */\n this.tintTexture = null;\n this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];\n }\n isReadyForSubMesh(defines, scene, engine) {\n if (!this._isEnabled) {\n return true;\n }\n const disableBumpMap = this._material._disableBumpMap;\n if (defines._areTexturesDirty) {\n if (scene.texturesEnabled) {\n if (this._texture && MaterialFlags.ClearCoatTextureEnabled) {\n if (!this._texture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._textureRoughness && MaterialFlags.ClearCoatTextureEnabled) {\n if (!this._textureRoughness.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (engine.getCaps().standardDerivatives && this._bumpTexture && MaterialFlags.ClearCoatBumpTextureEnabled && !disableBumpMap) {\n // Bump texture cannot be not blocking.\n if (!this._bumpTexture.isReady()) {\n return false;\n }\n }\n if (this._isTintEnabled && this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled) {\n if (!this._tintTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n }\n }\n return true;\n }\n prepareDefinesBeforeAttributes(defines, scene) {\n var _a;\n if (this._isEnabled) {\n defines.CLEARCOAT = true;\n defines.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE = this._useRoughnessFromMainTexture;\n defines.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL =\n this._texture !== null && this._texture._texture === ((_a = this._textureRoughness) === null || _a === void 0 ? void 0 : _a._texture) && this._texture.checkTransformsAreIdentical(this._textureRoughness);\n defines.CLEARCOAT_REMAP_F0 = this._remapF0OnInterfaceChange;\n if (defines._areTexturesDirty) {\n if (scene.texturesEnabled) {\n if (this._texture && MaterialFlags.ClearCoatTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._texture, defines, \"CLEARCOAT_TEXTURE\");\n }\n else {\n defines.CLEARCOAT_TEXTURE = false;\n }\n if (this._textureRoughness && MaterialFlags.ClearCoatTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._textureRoughness, defines, \"CLEARCOAT_TEXTURE_ROUGHNESS\");\n }\n else {\n defines.CLEARCOAT_TEXTURE_ROUGHNESS = false;\n }\n if (this._bumpTexture && MaterialFlags.ClearCoatBumpTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, \"CLEARCOAT_BUMP\");\n }\n else {\n defines.CLEARCOAT_BUMP = false;\n }\n defines.CLEARCOAT_DEFAULTIOR = this._indexOfRefraction === PBRClearCoatConfiguration._DefaultIndexOfRefraction;\n if (this._isTintEnabled) {\n defines.CLEARCOAT_TINT = true;\n if (this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._tintTexture, defines, \"CLEARCOAT_TINT_TEXTURE\");\n defines.CLEARCOAT_TINT_GAMMATEXTURE = this._tintTexture.gammaSpace;\n }\n else {\n defines.CLEARCOAT_TINT_TEXTURE = false;\n }\n }\n else {\n defines.CLEARCOAT_TINT = false;\n defines.CLEARCOAT_TINT_TEXTURE = false;\n }\n }\n }\n }\n else {\n defines.CLEARCOAT = false;\n defines.CLEARCOAT_TEXTURE = false;\n defines.CLEARCOAT_TEXTURE_ROUGHNESS = false;\n defines.CLEARCOAT_BUMP = false;\n defines.CLEARCOAT_TINT = false;\n defines.CLEARCOAT_TINT_TEXTURE = false;\n defines.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE = false;\n defines.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL = false;\n defines.CLEARCOAT_DEFAULTIOR = false;\n defines.CLEARCOAT_TEXTUREDIRECTUV = 0;\n defines.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV = 0;\n defines.CLEARCOAT_BUMPDIRECTUV = 0;\n defines.CLEARCOAT_REMAP_F0 = false;\n defines.CLEARCOAT_TINT_TEXTUREDIRECTUV = 0;\n defines.CLEARCOAT_TINT_GAMMATEXTURE = false;\n }\n }\n bindForSubMesh(uniformBuffer, scene, engine, subMesh) {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n if (!this._isEnabled) {\n return;\n }\n const defines = subMesh.materialDefines;\n const isFrozen = this._material.isFrozen;\n const disableBumpMap = this._material._disableBumpMap;\n const invertNormalMapX = this._material._invertNormalMapX;\n const invertNormalMapY = this._material._invertNormalMapY;\n const identicalTextures = defines.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL;\n if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {\n if (identicalTextures && MaterialFlags.ClearCoatTextureEnabled) {\n uniformBuffer.updateFloat4(\"vClearCoatInfos\", this._texture.coordinatesIndex, this._texture.level, -1, -1);\n MaterialHelper.BindTextureMatrix(this._texture, uniformBuffer, \"clearCoat\");\n }\n else if ((this._texture || this._textureRoughness) && MaterialFlags.ClearCoatTextureEnabled) {\n uniformBuffer.updateFloat4(\"vClearCoatInfos\", (_b = (_a = this._texture) === null || _a === void 0 ? void 0 : _a.coordinatesIndex) !== null && _b !== void 0 ? _b : 0, (_d = (_c = this._texture) === null || _c === void 0 ? void 0 : _c.level) !== null && _d !== void 0 ? _d : 0, (_f = (_e = this._textureRoughness) === null || _e === void 0 ? void 0 : _e.coordinatesIndex) !== null && _f !== void 0 ? _f : 0, (_h = (_g = this._textureRoughness) === null || _g === void 0 ? void 0 : _g.level) !== null && _h !== void 0 ? _h : 0);\n if (this._texture) {\n MaterialHelper.BindTextureMatrix(this._texture, uniformBuffer, \"clearCoat\");\n }\n if (this._textureRoughness && !identicalTextures && !defines.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) {\n MaterialHelper.BindTextureMatrix(this._textureRoughness, uniformBuffer, \"clearCoatRoughness\");\n }\n }\n if (this._bumpTexture && engine.getCaps().standardDerivatives && MaterialFlags.ClearCoatTextureEnabled && !disableBumpMap) {\n uniformBuffer.updateFloat2(\"vClearCoatBumpInfos\", this._bumpTexture.coordinatesIndex, this._bumpTexture.level);\n MaterialHelper.BindTextureMatrix(this._bumpTexture, uniformBuffer, \"clearCoatBump\");\n if (scene._mirroredCameraPosition) {\n uniformBuffer.updateFloat2(\"vClearCoatTangentSpaceParams\", invertNormalMapX ? 1.0 : -1.0, invertNormalMapY ? 1.0 : -1.0);\n }\n else {\n uniformBuffer.updateFloat2(\"vClearCoatTangentSpaceParams\", invertNormalMapX ? -1.0 : 1.0, invertNormalMapY ? -1.0 : 1.0);\n }\n }\n if (this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled) {\n uniformBuffer.updateFloat2(\"vClearCoatTintInfos\", this._tintTexture.coordinatesIndex, this._tintTexture.level);\n MaterialHelper.BindTextureMatrix(this._tintTexture, uniformBuffer, \"clearCoatTint\");\n }\n // Clear Coat General params\n uniformBuffer.updateFloat2(\"vClearCoatParams\", this.intensity, this.roughness);\n // Clear Coat Refraction params\n const a = 1 - this._indexOfRefraction;\n const b = 1 + this._indexOfRefraction;\n const f0 = Math.pow(-a / b, 2); // Schlicks approx: (ior1 - ior2) / (ior1 + ior2) where ior2 for air is close to vacuum = 1.\n const eta = 1 / this._indexOfRefraction;\n uniformBuffer.updateFloat4(\"vClearCoatRefractionParams\", f0, eta, a, b);\n if (this._isTintEnabled) {\n uniformBuffer.updateFloat4(\"vClearCoatTintParams\", this.tintColor.r, this.tintColor.g, this.tintColor.b, Math.max(0.00001, this.tintThickness));\n uniformBuffer.updateFloat(\"clearCoatColorAtDistance\", Math.max(0.00001, this.tintColorAtDistance));\n }\n }\n // Textures\n if (scene.texturesEnabled) {\n if (this._texture && MaterialFlags.ClearCoatTextureEnabled) {\n uniformBuffer.setTexture(\"clearCoatSampler\", this._texture);\n }\n if (this._textureRoughness && !identicalTextures && !defines.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE && MaterialFlags.ClearCoatTextureEnabled) {\n uniformBuffer.setTexture(\"clearCoatRoughnessSampler\", this._textureRoughness);\n }\n if (this._bumpTexture && engine.getCaps().standardDerivatives && MaterialFlags.ClearCoatBumpTextureEnabled && !disableBumpMap) {\n uniformBuffer.setTexture(\"clearCoatBumpSampler\", this._bumpTexture);\n }\n if (this._isTintEnabled && this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled) {\n uniformBuffer.setTexture(\"clearCoatTintSampler\", this._tintTexture);\n }\n }\n }\n hasTexture(texture) {\n if (this._texture === texture) {\n return true;\n }\n if (this._textureRoughness === texture) {\n return true;\n }\n if (this._bumpTexture === texture) {\n return true;\n }\n if (this._tintTexture === texture) {\n return true;\n }\n return false;\n }\n getActiveTextures(activeTextures) {\n if (this._texture) {\n activeTextures.push(this._texture);\n }\n if (this._textureRoughness) {\n activeTextures.push(this._textureRoughness);\n }\n if (this._bumpTexture) {\n activeTextures.push(this._bumpTexture);\n }\n if (this._tintTexture) {\n activeTextures.push(this._tintTexture);\n }\n }\n getAnimatables(animatables) {\n if (this._texture && this._texture.animations && this._texture.animations.length > 0) {\n animatables.push(this._texture);\n }\n if (this._textureRoughness && this._textureRoughness.animations && this._textureRoughness.animations.length > 0) {\n animatables.push(this._textureRoughness);\n }\n if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {\n animatables.push(this._bumpTexture);\n }\n if (this._tintTexture && this._tintTexture.animations && this._tintTexture.animations.length > 0) {\n animatables.push(this._tintTexture);\n }\n }\n dispose(forceDisposeTextures) {\n var _a, _b, _c, _d;\n if (forceDisposeTextures) {\n (_a = this._texture) === null || _a === void 0 ? void 0 : _a.dispose();\n (_b = this._textureRoughness) === null || _b === void 0 ? void 0 : _b.dispose();\n (_c = this._bumpTexture) === null || _c === void 0 ? void 0 : _c.dispose();\n (_d = this._tintTexture) === null || _d === void 0 ? void 0 : _d.dispose();\n }\n }\n getClassName() {\n return \"PBRClearCoatConfiguration\";\n }\n addFallbacks(defines, fallbacks, currentRank) {\n if (defines.CLEARCOAT_BUMP) {\n fallbacks.addFallback(currentRank++, \"CLEARCOAT_BUMP\");\n }\n if (defines.CLEARCOAT_TINT) {\n fallbacks.addFallback(currentRank++, \"CLEARCOAT_TINT\");\n }\n if (defines.CLEARCOAT) {\n fallbacks.addFallback(currentRank++, \"CLEARCOAT\");\n }\n return currentRank;\n }\n getSamplers(samplers) {\n samplers.push(\"clearCoatSampler\", \"clearCoatRoughnessSampler\", \"clearCoatBumpSampler\", \"clearCoatTintSampler\");\n }\n getUniforms() {\n return {\n ubo: [\n { name: \"vClearCoatParams\", size: 2, type: \"vec2\" },\n { name: \"vClearCoatRefractionParams\", size: 4, type: \"vec4\" },\n { name: \"vClearCoatInfos\", size: 4, type: \"vec4\" },\n { name: \"clearCoatMatrix\", size: 16, type: \"mat4\" },\n { name: \"clearCoatRoughnessMatrix\", size: 16, type: \"mat4\" },\n { name: \"vClearCoatBumpInfos\", size: 2, type: \"vec2\" },\n { name: \"vClearCoatTangentSpaceParams\", size: 2, type: \"vec2\" },\n { name: \"clearCoatBumpMatrix\", size: 16, type: \"mat4\" },\n { name: \"vClearCoatTintParams\", size: 4, type: \"vec4\" },\n { name: \"clearCoatColorAtDistance\", size: 1, type: \"float\" },\n { name: \"vClearCoatTintInfos\", size: 2, type: \"vec2\" },\n { name: \"clearCoatTintMatrix\", size: 16, type: \"mat4\" },\n ],\n };\n }\n}\n/**\n * This defaults to 1.5 corresponding to a 0.04 f0 or a 4% reflectance at normal incidence\n * The default fits with a polyurethane material.\n * @internal\n */\nPBRClearCoatConfiguration._DefaultIndexOfRefraction = 1.5;\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRClearCoatConfiguration.prototype, \"isEnabled\", void 0);\n__decorate([\n serialize()\n], PBRClearCoatConfiguration.prototype, \"intensity\", void 0);\n__decorate([\n serialize()\n], PBRClearCoatConfiguration.prototype, \"roughness\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRClearCoatConfiguration.prototype, \"indexOfRefraction\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRClearCoatConfiguration.prototype, \"texture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRClearCoatConfiguration.prototype, \"useRoughnessFromMainTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRClearCoatConfiguration.prototype, \"textureRoughness\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRClearCoatConfiguration.prototype, \"remapF0OnInterfaceChange\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRClearCoatConfiguration.prototype, \"bumpTexture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRClearCoatConfiguration.prototype, \"isTintEnabled\", void 0);\n__decorate([\n serializeAsColor3()\n], PBRClearCoatConfiguration.prototype, \"tintColor\", void 0);\n__decorate([\n serialize()\n], PBRClearCoatConfiguration.prototype, \"tintColorAtDistance\", void 0);\n__decorate([\n serialize()\n], PBRClearCoatConfiguration.prototype, \"tintThickness\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRClearCoatConfiguration.prototype, \"tintTexture\", void 0);\n//# sourceMappingURL=pbrClearCoatConfiguration.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize, serializeAsTexture, expandToProperty } from \"../../Misc/decorators.js\";\nimport { MaterialFlags } from \"../materialFlags.js\";\nimport { MaterialHelper } from \"../../Materials/materialHelper.js\";\n\nimport { MaterialPluginBase } from \"../materialPluginBase.js\";\nimport { MaterialDefines } from \"../materialDefines.js\";\n/**\n * @internal\n */\nexport class MaterialIridescenceDefines extends MaterialDefines {\n constructor() {\n super(...arguments);\n this.IRIDESCENCE = false;\n this.IRIDESCENCE_TEXTURE = false;\n this.IRIDESCENCE_TEXTUREDIRECTUV = 0;\n this.IRIDESCENCE_THICKNESS_TEXTURE = false;\n this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV = 0;\n this.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE = false;\n }\n}\n/**\n * Plugin that implements the iridescence (thin film) component of the PBR material\n */\nexport class PBRIridescenceConfiguration extends MaterialPluginBase {\n /** @internal */\n _markAllSubMeshesAsTexturesDirty() {\n this._enable(this._isEnabled);\n this._internalMarkAllSubMeshesAsTexturesDirty();\n }\n constructor(material, addToPluginList = true) {\n super(material, \"PBRIridescence\", 110, new MaterialIridescenceDefines(), addToPluginList);\n this._isEnabled = false;\n /**\n * Defines if the iridescence is enabled in the material.\n */\n this.isEnabled = false;\n /**\n * Defines the iridescence layer strength (between 0 and 1) it defaults to 1.\n */\n this.intensity = 1;\n /**\n * Defines the minimum thickness of the thin-film layer given in nanometers (nm).\n */\n this.minimumThickness = PBRIridescenceConfiguration._DefaultMinimumThickness;\n /**\n * Defines the maximum thickness of the thin-film layer given in nanometers (nm). This will be the thickness used if not thickness texture has been set.\n */\n this.maximumThickness = PBRIridescenceConfiguration._DefaultMaximumThickness;\n /**\n * Defines the maximum thickness of the thin-film layer given in nanometers (nm).\n */\n this.indexOfRefraction = PBRIridescenceConfiguration._DefaultIndexOfRefraction;\n this._texture = null;\n /**\n * Stores the iridescence intensity in a texture (red channel)\n */\n this.texture = null;\n this._thicknessTexture = null;\n /**\n * Stores the iridescence thickness in a texture (green channel)\n */\n this.thicknessTexture = null;\n this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];\n }\n isReadyForSubMesh(defines, scene) {\n if (!this._isEnabled) {\n return true;\n }\n if (defines._areTexturesDirty) {\n if (scene.texturesEnabled) {\n if (this._texture && MaterialFlags.IridescenceTextureEnabled) {\n if (!this._texture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._thicknessTexture && MaterialFlags.IridescenceTextureEnabled) {\n if (!this._thicknessTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n }\n }\n return true;\n }\n prepareDefinesBeforeAttributes(defines, scene) {\n var _a;\n if (this._isEnabled) {\n defines.IRIDESCENCE = true;\n defines.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE =\n this._texture !== null && this._texture._texture === ((_a = this._thicknessTexture) === null || _a === void 0 ? void 0 : _a._texture) && this._texture.checkTransformsAreIdentical(this._thicknessTexture);\n if (defines._areTexturesDirty) {\n if (scene.texturesEnabled) {\n if (this._texture && MaterialFlags.IridescenceTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._texture, defines, \"IRIDESCENCE_TEXTURE\");\n }\n else {\n defines.IRIDESCENCE_TEXTURE = false;\n }\n if (!defines.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE && this._thicknessTexture && MaterialFlags.IridescenceTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._thicknessTexture, defines, \"IRIDESCENCE_THICKNESS_TEXTURE\");\n }\n else {\n defines.IRIDESCENCE_THICKNESS_TEXTURE = false;\n }\n }\n }\n }\n else {\n defines.IRIDESCENCE = false;\n defines.IRIDESCENCE_TEXTURE = false;\n defines.IRIDESCENCE_THICKNESS_TEXTURE = false;\n defines.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE = false;\n defines.IRIDESCENCE_TEXTUREDIRECTUV = 0;\n defines.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV = 0;\n }\n }\n bindForSubMesh(uniformBuffer, scene, engine, subMesh) {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n if (!this._isEnabled) {\n return;\n }\n const defines = subMesh.materialDefines;\n const isFrozen = this._material.isFrozen;\n const identicalTextures = defines.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE;\n if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {\n if (identicalTextures && MaterialFlags.IridescenceTextureEnabled) {\n uniformBuffer.updateFloat4(\"vIridescenceInfos\", this._texture.coordinatesIndex, this._texture.level, -1, -1);\n MaterialHelper.BindTextureMatrix(this._texture, uniformBuffer, \"iridescence\");\n }\n else if ((this._texture || this._thicknessTexture) && MaterialFlags.IridescenceTextureEnabled) {\n uniformBuffer.updateFloat4(\"vIridescenceInfos\", (_b = (_a = this._texture) === null || _a === void 0 ? void 0 : _a.coordinatesIndex) !== null && _b !== void 0 ? _b : 0, (_d = (_c = this._texture) === null || _c === void 0 ? void 0 : _c.level) !== null && _d !== void 0 ? _d : 0, (_f = (_e = this._thicknessTexture) === null || _e === void 0 ? void 0 : _e.coordinatesIndex) !== null && _f !== void 0 ? _f : 0, (_h = (_g = this._thicknessTexture) === null || _g === void 0 ? void 0 : _g.level) !== null && _h !== void 0 ? _h : 0);\n if (this._texture) {\n MaterialHelper.BindTextureMatrix(this._texture, uniformBuffer, \"iridescence\");\n }\n if (this._thicknessTexture && !identicalTextures && !defines.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE) {\n MaterialHelper.BindTextureMatrix(this._thicknessTexture, uniformBuffer, \"iridescenceThickness\");\n }\n }\n // Clear Coat General params\n uniformBuffer.updateFloat4(\"vIridescenceParams\", this.intensity, this.indexOfRefraction, this.minimumThickness, this.maximumThickness);\n }\n // Textures\n if (scene.texturesEnabled) {\n if (this._texture && MaterialFlags.IridescenceTextureEnabled) {\n uniformBuffer.setTexture(\"iridescenceSampler\", this._texture);\n }\n if (this._thicknessTexture && !identicalTextures && !defines.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE && MaterialFlags.IridescenceTextureEnabled) {\n uniformBuffer.setTexture(\"iridescenceThicknessSampler\", this._thicknessTexture);\n }\n }\n }\n hasTexture(texture) {\n if (this._texture === texture) {\n return true;\n }\n if (this._thicknessTexture === texture) {\n return true;\n }\n return false;\n }\n getActiveTextures(activeTextures) {\n if (this._texture) {\n activeTextures.push(this._texture);\n }\n if (this._thicknessTexture) {\n activeTextures.push(this._thicknessTexture);\n }\n }\n getAnimatables(animatables) {\n if (this._texture && this._texture.animations && this._texture.animations.length > 0) {\n animatables.push(this._texture);\n }\n if (this._thicknessTexture && this._thicknessTexture.animations && this._thicknessTexture.animations.length > 0) {\n animatables.push(this._thicknessTexture);\n }\n }\n dispose(forceDisposeTextures) {\n var _a, _b;\n if (forceDisposeTextures) {\n (_a = this._texture) === null || _a === void 0 ? void 0 : _a.dispose();\n (_b = this._thicknessTexture) === null || _b === void 0 ? void 0 : _b.dispose();\n }\n }\n getClassName() {\n return \"PBRIridescenceConfiguration\";\n }\n addFallbacks(defines, fallbacks, currentRank) {\n if (defines.IRIDESCENCE) {\n fallbacks.addFallback(currentRank++, \"IRIDESCENCE\");\n }\n return currentRank;\n }\n getSamplers(samplers) {\n samplers.push(\"iridescenceSampler\", \"iridescenceThicknessSampler\");\n }\n getUniforms() {\n return {\n ubo: [\n { name: \"vIridescenceParams\", size: 4, type: \"vec4\" },\n { name: \"vIridescenceInfos\", size: 4, type: \"vec4\" },\n { name: \"iridescenceMatrix\", size: 16, type: \"mat4\" },\n { name: \"iridescenceThicknessMatrix\", size: 16, type: \"mat4\" },\n ],\n };\n }\n}\n/**\n * The default minimum thickness of the thin-film layer given in nanometers (nm).\n * Defaults to 100 nm.\n * @internal\n */\nPBRIridescenceConfiguration._DefaultMinimumThickness = 100;\n/**\n * The default maximum thickness of the thin-film layer given in nanometers (nm).\n * Defaults to 400 nm.\n * @internal\n */\nPBRIridescenceConfiguration._DefaultMaximumThickness = 400;\n/**\n * The default index of refraction of the thin-film layer.\n * Defaults to 1.3\n * @internal\n */\nPBRIridescenceConfiguration._DefaultIndexOfRefraction = 1.3;\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRIridescenceConfiguration.prototype, \"isEnabled\", void 0);\n__decorate([\n serialize()\n], PBRIridescenceConfiguration.prototype, \"intensity\", void 0);\n__decorate([\n serialize()\n], PBRIridescenceConfiguration.prototype, \"minimumThickness\", void 0);\n__decorate([\n serialize()\n], PBRIridescenceConfiguration.prototype, \"maximumThickness\", void 0);\n__decorate([\n serialize()\n], PBRIridescenceConfiguration.prototype, \"indexOfRefraction\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRIridescenceConfiguration.prototype, \"texture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRIridescenceConfiguration.prototype, \"thicknessTexture\", void 0);\n//# sourceMappingURL=pbrIridescenceConfiguration.js.map","import { __decorate } from \"../../tslib.es6.js\";\n/* eslint-disable @typescript-eslint/naming-convention */\nimport { serialize, expandToProperty, serializeAsVector2, serializeAsTexture } from \"../../Misc/decorators.js\";\nimport { VertexBuffer } from \"../../Buffers/buffer.js\";\nimport { Vector2 } from \"../../Maths/math.vector.js\";\nimport { MaterialFlags } from \"../../Materials/materialFlags.js\";\nimport { MaterialHelper } from \"../../Materials/materialHelper.js\";\nimport { MaterialPluginBase } from \"../materialPluginBase.js\";\n\nimport { MaterialDefines } from \"../materialDefines.js\";\n/**\n * @internal\n */\nexport class MaterialAnisotropicDefines extends MaterialDefines {\n constructor() {\n super(...arguments);\n this.ANISOTROPIC = false;\n this.ANISOTROPIC_TEXTURE = false;\n this.ANISOTROPIC_TEXTUREDIRECTUV = 0;\n this.ANISOTROPIC_LEGACY = false;\n this.MAINUV1 = false;\n }\n}\n/**\n * Plugin that implements the anisotropic component of the PBR material\n */\nexport class PBRAnisotropicConfiguration extends MaterialPluginBase {\n /**\n * Sets the anisotropy direction as an angle.\n */\n set angle(value) {\n this.direction.x = Math.cos(value);\n this.direction.y = Math.sin(value);\n }\n /**\n * Gets the anisotropy angle value in radians.\n * @returns the anisotropy angle value in radians.\n */\n get angle() {\n return Math.atan2(this.direction.y, this.direction.x);\n }\n /** @internal */\n _markAllSubMeshesAsTexturesDirty() {\n this._enable(this._isEnabled);\n this._internalMarkAllSubMeshesAsTexturesDirty();\n }\n /** @internal */\n _markAllSubMeshesAsMiscDirty() {\n this._enable(this._isEnabled);\n this._internalMarkAllSubMeshesAsMiscDirty();\n }\n constructor(material, addToPluginList = true) {\n super(material, \"PBRAnisotropic\", 110, new MaterialAnisotropicDefines(), addToPluginList);\n this._isEnabled = false;\n /**\n * Defines if the anisotropy is enabled in the material.\n */\n this.isEnabled = false;\n /**\n * Defines the anisotropy strength (between 0 and 1) it defaults to 1.\n */\n this.intensity = 1;\n /**\n * Defines if the effect is along the tangents, bitangents or in between.\n * By default, the effect is \"stretching\" the highlights along the tangents.\n */\n this.direction = new Vector2(1, 0);\n this._texture = null;\n /**\n * Stores the anisotropy values in a texture.\n * rg is direction (like normal from -1 to 1)\n * b is a intensity\n */\n this.texture = null;\n this._legacy = false;\n /**\n * Defines if the anisotropy is in legacy mode for backwards compatibility before 6.4.0.\n */\n this.legacy = false;\n this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];\n this._internalMarkAllSubMeshesAsMiscDirty = material._dirtyCallbacks[16];\n }\n isReadyForSubMesh(defines, scene) {\n if (!this._isEnabled) {\n return true;\n }\n if (defines._areTexturesDirty) {\n if (scene.texturesEnabled) {\n if (this._texture && MaterialFlags.AnisotropicTextureEnabled) {\n if (!this._texture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n }\n }\n return true;\n }\n prepareDefinesBeforeAttributes(defines, scene, mesh) {\n if (this._isEnabled) {\n defines.ANISOTROPIC = this._isEnabled;\n if (this._isEnabled && !mesh.isVerticesDataPresent(VertexBuffer.TangentKind)) {\n defines._needUVs = true;\n defines.MAINUV1 = true;\n }\n if (defines._areTexturesDirty) {\n if (scene.texturesEnabled) {\n if (this._texture && MaterialFlags.AnisotropicTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._texture, defines, \"ANISOTROPIC_TEXTURE\");\n }\n else {\n defines.ANISOTROPIC_TEXTURE = false;\n }\n }\n }\n if (defines._areMiscDirty) {\n defines.ANISOTROPIC_LEGACY = this._legacy;\n }\n }\n else {\n defines.ANISOTROPIC = false;\n defines.ANISOTROPIC_TEXTURE = false;\n defines.ANISOTROPIC_TEXTUREDIRECTUV = 0;\n defines.ANISOTROPIC_LEGACY = false;\n }\n }\n bindForSubMesh(uniformBuffer, scene) {\n if (!this._isEnabled) {\n return;\n }\n const isFrozen = this._material.isFrozen;\n if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {\n if (this._texture && MaterialFlags.AnisotropicTextureEnabled) {\n uniformBuffer.updateFloat2(\"vAnisotropyInfos\", this._texture.coordinatesIndex, this._texture.level);\n MaterialHelper.BindTextureMatrix(this._texture, uniformBuffer, \"anisotropy\");\n }\n // Anisotropy\n uniformBuffer.updateFloat3(\"vAnisotropy\", this.direction.x, this.direction.y, this.intensity);\n }\n // Textures\n if (scene.texturesEnabled) {\n if (this._texture && MaterialFlags.AnisotropicTextureEnabled) {\n uniformBuffer.setTexture(\"anisotropySampler\", this._texture);\n }\n }\n }\n hasTexture(texture) {\n if (this._texture === texture) {\n return true;\n }\n return false;\n }\n getActiveTextures(activeTextures) {\n if (this._texture) {\n activeTextures.push(this._texture);\n }\n }\n getAnimatables(animatables) {\n if (this._texture && this._texture.animations && this._texture.animations.length > 0) {\n animatables.push(this._texture);\n }\n }\n dispose(forceDisposeTextures) {\n if (forceDisposeTextures) {\n if (this._texture) {\n this._texture.dispose();\n }\n }\n }\n getClassName() {\n return \"PBRAnisotropicConfiguration\";\n }\n addFallbacks(defines, fallbacks, currentRank) {\n if (defines.ANISOTROPIC) {\n fallbacks.addFallback(currentRank++, \"ANISOTROPIC\");\n }\n return currentRank;\n }\n getSamplers(samplers) {\n samplers.push(\"anisotropySampler\");\n }\n getUniforms() {\n return {\n ubo: [\n { name: \"vAnisotropy\", size: 3, type: \"vec3\" },\n { name: \"vAnisotropyInfos\", size: 2, type: \"vec2\" },\n { name: \"anisotropyMatrix\", size: 16, type: \"mat4\" },\n ],\n };\n }\n /**\n * Parses a anisotropy Configuration from a serialized object.\n * @param source - Serialized object.\n * @param scene Defines the scene we are parsing for\n * @param rootUrl Defines the rootUrl to load from\n */\n parse(source, scene, rootUrl) {\n super.parse(source, scene, rootUrl);\n // Backward compatibility\n if (source.legacy === undefined) {\n this.legacy = true;\n }\n }\n}\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRAnisotropicConfiguration.prototype, \"isEnabled\", void 0);\n__decorate([\n serialize()\n], PBRAnisotropicConfiguration.prototype, \"intensity\", void 0);\n__decorate([\n serializeAsVector2()\n], PBRAnisotropicConfiguration.prototype, \"direction\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRAnisotropicConfiguration.prototype, \"texture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsMiscDirty\")\n], PBRAnisotropicConfiguration.prototype, \"legacy\", void 0);\n//# sourceMappingURL=pbrAnisotropicConfiguration.js.map","import { __decorate } from \"../../tslib.es6.js\";\n/* eslint-disable @typescript-eslint/naming-convention */\nimport { serialize, expandToProperty, serializeAsColor3, serializeAsTexture } from \"../../Misc/decorators.js\";\nimport { Color3 } from \"../../Maths/math.color.js\";\nimport { MaterialFlags } from \"../../Materials/materialFlags.js\";\nimport { MaterialHelper } from \"../../Materials/materialHelper.js\";\n\nimport { MaterialPluginBase } from \"../materialPluginBase.js\";\nimport { MaterialDefines } from \"../materialDefines.js\";\n/**\n * @internal\n */\nexport class MaterialSheenDefines extends MaterialDefines {\n constructor() {\n super(...arguments);\n this.SHEEN = false;\n this.SHEEN_TEXTURE = false;\n this.SHEEN_GAMMATEXTURE = false;\n this.SHEEN_TEXTURE_ROUGHNESS = false;\n this.SHEEN_TEXTUREDIRECTUV = 0;\n this.SHEEN_TEXTURE_ROUGHNESSDIRECTUV = 0;\n this.SHEEN_LINKWITHALBEDO = false;\n this.SHEEN_ROUGHNESS = false;\n this.SHEEN_ALBEDOSCALING = false;\n this.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE = false;\n this.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL = false;\n }\n}\n/**\n * Plugin that implements the sheen component of the PBR material.\n */\nexport class PBRSheenConfiguration extends MaterialPluginBase {\n /** @internal */\n _markAllSubMeshesAsTexturesDirty() {\n this._enable(this._isEnabled);\n this._internalMarkAllSubMeshesAsTexturesDirty();\n }\n constructor(material, addToPluginList = true) {\n super(material, \"Sheen\", 120, new MaterialSheenDefines(), addToPluginList);\n this._isEnabled = false;\n /**\n * Defines if the material uses sheen.\n */\n this.isEnabled = false;\n this._linkSheenWithAlbedo = false;\n /**\n * Defines if the sheen is linked to the sheen color.\n */\n this.linkSheenWithAlbedo = false;\n /**\n * Defines the sheen intensity.\n */\n this.intensity = 1;\n /**\n * Defines the sheen color.\n */\n this.color = Color3.White();\n this._texture = null;\n /**\n * Stores the sheen tint values in a texture.\n * rgb is tint\n * a is a intensity or roughness if the roughness property has been defined and useRoughnessFromTexture is true (in that case, textureRoughness won't be used)\n * If the roughness property has been defined and useRoughnessFromTexture is false then the alpha channel is not used to modulate roughness\n */\n this.texture = null;\n this._useRoughnessFromMainTexture = true;\n /**\n * Indicates that the alpha channel of the texture property will be used for roughness.\n * Has no effect if the roughness (and texture!) property is not defined\n */\n this.useRoughnessFromMainTexture = true;\n this._roughness = null;\n /**\n * Defines the sheen roughness.\n * It is not taken into account if linkSheenWithAlbedo is true.\n * To stay backward compatible, material roughness is used instead if sheen roughness = null\n */\n this.roughness = null;\n this._textureRoughness = null;\n /**\n * Stores the sheen roughness in a texture.\n * alpha channel is the roughness. This texture won't be used if the texture property is not empty and useRoughnessFromTexture is true\n */\n this.textureRoughness = null;\n this._albedoScaling = false;\n /**\n * If true, the sheen effect is layered above the base BRDF with the albedo-scaling technique.\n * It allows the strength of the sheen effect to not depend on the base color of the material,\n * making it easier to setup and tweak the effect\n */\n this.albedoScaling = false;\n this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];\n }\n isReadyForSubMesh(defines, scene) {\n if (!this._isEnabled) {\n return true;\n }\n if (defines._areTexturesDirty) {\n if (scene.texturesEnabled) {\n if (this._texture && MaterialFlags.SheenTextureEnabled) {\n if (!this._texture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._textureRoughness && MaterialFlags.SheenTextureEnabled) {\n if (!this._textureRoughness.isReadyOrNotBlocking()) {\n return false;\n }\n }\n }\n }\n return true;\n }\n prepareDefinesBeforeAttributes(defines, scene) {\n var _a;\n if (this._isEnabled) {\n defines.SHEEN = true;\n defines.SHEEN_LINKWITHALBEDO = this._linkSheenWithAlbedo;\n defines.SHEEN_ROUGHNESS = this._roughness !== null;\n defines.SHEEN_ALBEDOSCALING = this._albedoScaling;\n defines.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE = this._useRoughnessFromMainTexture;\n defines.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL =\n this._texture !== null && this._texture._texture === ((_a = this._textureRoughness) === null || _a === void 0 ? void 0 : _a._texture) && this._texture.checkTransformsAreIdentical(this._textureRoughness);\n if (defines._areTexturesDirty) {\n if (scene.texturesEnabled) {\n if (this._texture && MaterialFlags.SheenTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._texture, defines, \"SHEEN_TEXTURE\");\n defines.SHEEN_GAMMATEXTURE = this._texture.gammaSpace;\n }\n else {\n defines.SHEEN_TEXTURE = false;\n }\n if (this._textureRoughness && MaterialFlags.SheenTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._textureRoughness, defines, \"SHEEN_TEXTURE_ROUGHNESS\");\n }\n else {\n defines.SHEEN_TEXTURE_ROUGHNESS = false;\n }\n }\n }\n }\n else {\n defines.SHEEN = false;\n defines.SHEEN_TEXTURE = false;\n defines.SHEEN_TEXTURE_ROUGHNESS = false;\n defines.SHEEN_LINKWITHALBEDO = false;\n defines.SHEEN_ROUGHNESS = false;\n defines.SHEEN_ALBEDOSCALING = false;\n defines.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE = false;\n defines.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL = false;\n defines.SHEEN_GAMMATEXTURE = false;\n defines.SHEEN_TEXTUREDIRECTUV = 0;\n defines.SHEEN_TEXTURE_ROUGHNESSDIRECTUV = 0;\n }\n }\n bindForSubMesh(uniformBuffer, scene, engine, subMesh) {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n if (!this._isEnabled) {\n return;\n }\n const defines = subMesh.materialDefines;\n const isFrozen = this._material.isFrozen;\n const identicalTextures = defines.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL;\n if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {\n if (identicalTextures && MaterialFlags.SheenTextureEnabled) {\n uniformBuffer.updateFloat4(\"vSheenInfos\", this._texture.coordinatesIndex, this._texture.level, -1, -1);\n MaterialHelper.BindTextureMatrix(this._texture, uniformBuffer, \"sheen\");\n }\n else if ((this._texture || this._textureRoughness) && MaterialFlags.SheenTextureEnabled) {\n uniformBuffer.updateFloat4(\"vSheenInfos\", (_b = (_a = this._texture) === null || _a === void 0 ? void 0 : _a.coordinatesIndex) !== null && _b !== void 0 ? _b : 0, (_d = (_c = this._texture) === null || _c === void 0 ? void 0 : _c.level) !== null && _d !== void 0 ? _d : 0, (_f = (_e = this._textureRoughness) === null || _e === void 0 ? void 0 : _e.coordinatesIndex) !== null && _f !== void 0 ? _f : 0, (_h = (_g = this._textureRoughness) === null || _g === void 0 ? void 0 : _g.level) !== null && _h !== void 0 ? _h : 0);\n if (this._texture) {\n MaterialHelper.BindTextureMatrix(this._texture, uniformBuffer, \"sheen\");\n }\n if (this._textureRoughness && !identicalTextures && !defines.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) {\n MaterialHelper.BindTextureMatrix(this._textureRoughness, uniformBuffer, \"sheenRoughness\");\n }\n }\n // Sheen\n uniformBuffer.updateFloat4(\"vSheenColor\", this.color.r, this.color.g, this.color.b, this.intensity);\n if (this._roughness !== null) {\n uniformBuffer.updateFloat(\"vSheenRoughness\", this._roughness);\n }\n }\n // Textures\n if (scene.texturesEnabled) {\n if (this._texture && MaterialFlags.SheenTextureEnabled) {\n uniformBuffer.setTexture(\"sheenSampler\", this._texture);\n }\n if (this._textureRoughness && !identicalTextures && !defines.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE && MaterialFlags.SheenTextureEnabled) {\n uniformBuffer.setTexture(\"sheenRoughnessSampler\", this._textureRoughness);\n }\n }\n }\n hasTexture(texture) {\n if (this._texture === texture) {\n return true;\n }\n if (this._textureRoughness === texture) {\n return true;\n }\n return false;\n }\n getActiveTextures(activeTextures) {\n if (this._texture) {\n activeTextures.push(this._texture);\n }\n if (this._textureRoughness) {\n activeTextures.push(this._textureRoughness);\n }\n }\n getAnimatables(animatables) {\n if (this._texture && this._texture.animations && this._texture.animations.length > 0) {\n animatables.push(this._texture);\n }\n if (this._textureRoughness && this._textureRoughness.animations && this._textureRoughness.animations.length > 0) {\n animatables.push(this._textureRoughness);\n }\n }\n dispose(forceDisposeTextures) {\n var _a, _b;\n if (forceDisposeTextures) {\n (_a = this._texture) === null || _a === void 0 ? void 0 : _a.dispose();\n (_b = this._textureRoughness) === null || _b === void 0 ? void 0 : _b.dispose();\n }\n }\n getClassName() {\n return \"PBRSheenConfiguration\";\n }\n addFallbacks(defines, fallbacks, currentRank) {\n if (defines.SHEEN) {\n fallbacks.addFallback(currentRank++, \"SHEEN\");\n }\n return currentRank;\n }\n getSamplers(samplers) {\n samplers.push(\"sheenSampler\", \"sheenRoughnessSampler\");\n }\n getUniforms() {\n return {\n ubo: [\n { name: \"vSheenColor\", size: 4, type: \"vec4\" },\n { name: \"vSheenRoughness\", size: 1, type: \"float\" },\n { name: \"vSheenInfos\", size: 4, type: \"vec4\" },\n { name: \"sheenMatrix\", size: 16, type: \"mat4\" },\n { name: \"sheenRoughnessMatrix\", size: 16, type: \"mat4\" },\n ],\n };\n }\n}\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSheenConfiguration.prototype, \"isEnabled\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSheenConfiguration.prototype, \"linkSheenWithAlbedo\", void 0);\n__decorate([\n serialize()\n], PBRSheenConfiguration.prototype, \"intensity\", void 0);\n__decorate([\n serializeAsColor3()\n], PBRSheenConfiguration.prototype, \"color\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSheenConfiguration.prototype, \"texture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSheenConfiguration.prototype, \"useRoughnessFromMainTexture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSheenConfiguration.prototype, \"roughness\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSheenConfiguration.prototype, \"textureRoughness\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSheenConfiguration.prototype, \"albedoScaling\", void 0);\n//# sourceMappingURL=pbrSheenConfiguration.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize, serializeAsTexture, expandToProperty, serializeAsColor3 } from \"../../Misc/decorators.js\";\nimport { Color3 } from \"../../Maths/math.color.js\";\nimport { MaterialFlags } from \"../materialFlags.js\";\nimport { MaterialHelper } from \"../../Materials/materialHelper.js\";\nimport { Scalar } from \"../../Maths/math.scalar.js\";\nimport { TmpVectors } from \"../../Maths/math.vector.js\";\nimport { MaterialPluginBase } from \"../materialPluginBase.js\";\n\nimport { MaterialDefines } from \"../materialDefines.js\";\n/**\n * @internal\n */\nexport class MaterialSubSurfaceDefines extends MaterialDefines {\n constructor() {\n super(...arguments);\n this.SUBSURFACE = false;\n this.SS_REFRACTION = false;\n this.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE = false;\n this.SS_TRANSLUCENCY = false;\n this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE = false;\n this.SS_SCATTERING = false;\n this.SS_THICKNESSANDMASK_TEXTURE = false;\n this.SS_THICKNESSANDMASK_TEXTUREDIRECTUV = 0;\n this.SS_HAS_THICKNESS = false;\n this.SS_REFRACTIONINTENSITY_TEXTURE = false;\n this.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV = 0;\n this.SS_TRANSLUCENCYINTENSITY_TEXTURE = false;\n this.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV = 0;\n this.SS_REFRACTIONMAP_3D = false;\n this.SS_REFRACTIONMAP_OPPOSITEZ = false;\n this.SS_LODINREFRACTIONALPHA = false;\n this.SS_GAMMAREFRACTION = false;\n this.SS_RGBDREFRACTION = false;\n this.SS_LINEARSPECULARREFRACTION = false;\n this.SS_LINKREFRACTIONTOTRANSPARENCY = false;\n this.SS_ALBEDOFORREFRACTIONTINT = false;\n this.SS_ALBEDOFORTRANSLUCENCYTINT = false;\n this.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = false;\n this.SS_USE_THICKNESS_AS_DEPTH = false;\n this.SS_MASK_FROM_THICKNESS_TEXTURE = false;\n this.SS_USE_GLTF_TEXTURES = false;\n }\n}\n/**\n * Plugin that implements the sub surface component of the PBR material\n */\nexport class PBRSubSurfaceConfiguration extends MaterialPluginBase {\n /**\n * Diffusion profile for subsurface scattering.\n * Useful for better scattering in the skins or foliages.\n */\n get scatteringDiffusionProfile() {\n if (!this._scene.subSurfaceConfiguration) {\n return null;\n }\n return this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex];\n }\n set scatteringDiffusionProfile(c) {\n if (!this._scene.enableSubSurfaceForPrePass()) {\n // Not supported\n return;\n }\n // addDiffusionProfile automatically checks for doubles\n if (c) {\n this._scatteringDiffusionProfileIndex = this._scene.subSurfaceConfiguration.addDiffusionProfile(c);\n }\n }\n /**\n * Index of refraction of the material's volume.\n * https://en.wikipedia.org/wiki/List_of_refractive_indices\n *\n * This ONLY impacts refraction. If not provided or given a non-valid value,\n * the volume will use the same IOR as the surface.\n */\n get volumeIndexOfRefraction() {\n if (this._volumeIndexOfRefraction >= 1.0) {\n return this._volumeIndexOfRefraction;\n }\n return this._indexOfRefraction;\n }\n set volumeIndexOfRefraction(value) {\n if (value >= 1.0) {\n this._volumeIndexOfRefraction = value;\n }\n else {\n this._volumeIndexOfRefraction = -1.0;\n }\n }\n /** @internal */\n _markAllSubMeshesAsTexturesDirty() {\n this._enable(this._isRefractionEnabled || this._isTranslucencyEnabled || this._isScatteringEnabled);\n this._internalMarkAllSubMeshesAsTexturesDirty();\n }\n /** @internal */\n _markScenePrePassDirty() {\n this._internalMarkAllSubMeshesAsTexturesDirty();\n this._internalMarkScenePrePassDirty();\n }\n constructor(material, addToPluginList = true) {\n super(material, \"PBRSubSurface\", 130, new MaterialSubSurfaceDefines(), addToPluginList);\n this._isRefractionEnabled = false;\n /**\n * Defines if the refraction is enabled in the material.\n */\n this.isRefractionEnabled = false;\n this._isTranslucencyEnabled = false;\n /**\n * Defines if the translucency is enabled in the material.\n */\n this.isTranslucencyEnabled = false;\n this._isScatteringEnabled = false;\n /**\n * Defines if the sub surface scattering is enabled in the material.\n */\n this.isScatteringEnabled = false;\n this._scatteringDiffusionProfileIndex = 0;\n /**\n * Defines the refraction intensity of the material.\n * The refraction when enabled replaces the Diffuse part of the material.\n * The intensity helps transitioning between diffuse and refraction.\n */\n this.refractionIntensity = 1;\n /**\n * Defines the translucency intensity of the material.\n * When translucency has been enabled, this defines how much of the \"translucency\"\n * is added to the diffuse part of the material.\n */\n this.translucencyIntensity = 1;\n /**\n * When enabled, transparent surfaces will be tinted with the albedo colour (independent of thickness)\n */\n this.useAlbedoToTintRefraction = false;\n /**\n * When enabled, translucent surfaces will be tinted with the albedo colour (independent of thickness)\n */\n this.useAlbedoToTintTranslucency = false;\n this._thicknessTexture = null;\n /**\n * Stores the average thickness of a mesh in a texture (The texture is holding the values linearly).\n * The red (or green if useGltfStyleTextures=true) channel of the texture should contain the thickness remapped between 0 and 1.\n * 0 would mean minimumThickness\n * 1 would mean maximumThickness\n * The other channels might be use as a mask to vary the different effects intensity.\n */\n this.thicknessTexture = null;\n this._refractionTexture = null;\n /**\n * Defines the texture to use for refraction.\n */\n this.refractionTexture = null;\n /** @internal */\n this._indexOfRefraction = 1.5;\n /**\n * Index of refraction of the material base layer.\n * https://en.wikipedia.org/wiki/List_of_refractive_indices\n *\n * This does not only impact refraction but also the Base F0 of Dielectric Materials.\n *\n * From dielectric fresnel rules: F0 = square((iorT - iorI) / (iorT + iorI))\n */\n this.indexOfRefraction = 1.5;\n this._volumeIndexOfRefraction = -1.0;\n this._invertRefractionY = false;\n /**\n * Controls if refraction needs to be inverted on Y. This could be useful for procedural texture.\n */\n this.invertRefractionY = false;\n /** @internal */\n this._linkRefractionWithTransparency = false;\n /**\n * This parameters will make the material used its opacity to control how much it is refracting against not.\n * Materials half opaque for instance using refraction could benefit from this control.\n */\n this.linkRefractionWithTransparency = false;\n /**\n * Defines the minimum thickness stored in the thickness map.\n * If no thickness map is defined, this value will be used to simulate thickness.\n */\n this.minimumThickness = 0;\n /**\n * Defines the maximum thickness stored in the thickness map.\n */\n this.maximumThickness = 1;\n /**\n * Defines that the thickness should be used as a measure of the depth volume.\n */\n this.useThicknessAsDepth = false;\n /**\n * Defines the volume tint of the material.\n * This is used for both translucency and scattering.\n */\n this.tintColor = Color3.White();\n /**\n * Defines the distance at which the tint color should be found in the media.\n * This is used for refraction only.\n */\n this.tintColorAtDistance = 1;\n /**\n * Defines how far each channel transmit through the media.\n * It is defined as a color to simplify it selection.\n */\n this.diffusionDistance = Color3.White();\n this._useMaskFromThicknessTexture = false;\n /**\n * Stores the intensity of the different subsurface effects in the thickness texture.\n * Note that if refractionIntensityTexture and/or translucencyIntensityTexture is provided it takes precedence over thicknessTexture + useMaskFromThicknessTexture\n * * the green (red if useGltfStyleTextures = true) channel is the refraction intensity.\n * * the blue channel is the translucency intensity.\n */\n this.useMaskFromThicknessTexture = false;\n this._refractionIntensityTexture = null;\n /**\n * Stores the intensity of the refraction. If provided, it takes precedence over thicknessTexture + useMaskFromThicknessTexture\n * * the green (red if useGltfStyleTextures = true) channel is the refraction intensity.\n */\n this.refractionIntensityTexture = null;\n this._translucencyIntensityTexture = null;\n /**\n * Stores the intensity of the translucency. If provided, it takes precedence over thicknessTexture + useMaskFromThicknessTexture\n * * the blue channel is the translucency intensity.\n */\n this.translucencyIntensityTexture = null;\n this._useGltfStyleTextures = false;\n /**\n * Use channels layout used by glTF:\n * * thicknessTexture: the green (instead of red) channel is the thickness\n * * thicknessTexture/refractionIntensityTexture: the red (instead of green) channel is the refraction intensity\n * * thicknessTexture/translucencyIntensityTexture: no change, use the blue channel for the translucency intensity\n */\n this.useGltfStyleTextures = false;\n this._scene = material.getScene();\n this.registerForExtraEvents = true;\n this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];\n this._internalMarkScenePrePassDirty = material._dirtyCallbacks[32];\n }\n isReadyForSubMesh(defines, scene) {\n if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled) {\n return true;\n }\n if (defines._areTexturesDirty) {\n if (scene.texturesEnabled) {\n if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) {\n if (!this._thicknessTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n const refractionTexture = this._getRefractionTexture(scene);\n if (refractionTexture && MaterialFlags.RefractionTextureEnabled) {\n if (!refractionTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n }\n }\n return true;\n }\n prepareDefinesBeforeAttributes(defines, scene) {\n if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled) {\n defines.SUBSURFACE = false;\n defines.SS_TRANSLUCENCY = false;\n defines.SS_SCATTERING = false;\n defines.SS_REFRACTION = false;\n defines.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE = false;\n defines.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE = false;\n defines.SS_THICKNESSANDMASK_TEXTURE = false;\n defines.SS_THICKNESSANDMASK_TEXTUREDIRECTUV = 0;\n defines.SS_HAS_THICKNESS = false;\n defines.SS_REFRACTIONINTENSITY_TEXTURE = false;\n defines.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV = 0;\n defines.SS_TRANSLUCENCYINTENSITY_TEXTURE = false;\n defines.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV = 0;\n defines.SS_REFRACTIONMAP_3D = false;\n defines.SS_REFRACTIONMAP_OPPOSITEZ = false;\n defines.SS_LODINREFRACTIONALPHA = false;\n defines.SS_GAMMAREFRACTION = false;\n defines.SS_RGBDREFRACTION = false;\n defines.SS_LINEARSPECULARREFRACTION = false;\n defines.SS_LINKREFRACTIONTOTRANSPARENCY = false;\n defines.SS_ALBEDOFORREFRACTIONTINT = false;\n defines.SS_ALBEDOFORTRANSLUCENCYTINT = false;\n defines.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = false;\n defines.SS_USE_THICKNESS_AS_DEPTH = false;\n defines.SS_MASK_FROM_THICKNESS_TEXTURE = false;\n defines.SS_USE_GLTF_TEXTURES = false;\n return;\n }\n if (defines._areTexturesDirty) {\n defines.SUBSURFACE = true;\n defines.SS_TRANSLUCENCY = this._isTranslucencyEnabled;\n defines.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE = false;\n defines.SS_SCATTERING = this._isScatteringEnabled;\n defines.SS_THICKNESSANDMASK_TEXTURE = false;\n defines.SS_REFRACTIONINTENSITY_TEXTURE = false;\n defines.SS_TRANSLUCENCYINTENSITY_TEXTURE = false;\n defines.SS_HAS_THICKNESS = false;\n defines.SS_MASK_FROM_THICKNESS_TEXTURE = false;\n defines.SS_USE_GLTF_TEXTURES = false;\n defines.SS_REFRACTION = false;\n defines.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE = false;\n defines.SS_REFRACTIONMAP_3D = false;\n defines.SS_GAMMAREFRACTION = false;\n defines.SS_RGBDREFRACTION = false;\n defines.SS_LINEARSPECULARREFRACTION = false;\n defines.SS_REFRACTIONMAP_OPPOSITEZ = false;\n defines.SS_LODINREFRACTIONALPHA = false;\n defines.SS_LINKREFRACTIONTOTRANSPARENCY = false;\n defines.SS_ALBEDOFORREFRACTIONTINT = false;\n defines.SS_ALBEDOFORTRANSLUCENCYTINT = false;\n defines.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = false;\n defines.SS_USE_THICKNESS_AS_DEPTH = false;\n const refractionIntensityTextureIsThicknessTexture = !!this._thicknessTexture &&\n !!this._refractionIntensityTexture &&\n this._refractionIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture) &&\n this._refractionIntensityTexture._texture === this._thicknessTexture._texture;\n const translucencyIntensityTextureIsThicknessTexture = !!this._thicknessTexture &&\n !!this._translucencyIntensityTexture &&\n this._translucencyIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture) &&\n this._translucencyIntensityTexture._texture === this._thicknessTexture._texture;\n // if true, it means the refraction/translucency textures are the same than the thickness texture so there's no need to pass them to the shader, only thicknessTexture\n const useOnlyThicknessTexture = (refractionIntensityTextureIsThicknessTexture || !this._refractionIntensityTexture) &&\n (translucencyIntensityTextureIsThicknessTexture || !this._translucencyIntensityTexture);\n if (defines._areTexturesDirty) {\n if (scene.texturesEnabled) {\n if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._thicknessTexture, defines, \"SS_THICKNESSANDMASK_TEXTURE\");\n }\n if (this._refractionIntensityTexture && MaterialFlags.RefractionIntensityTextureEnabled && !useOnlyThicknessTexture) {\n MaterialHelper.PrepareDefinesForMergedUV(this._refractionIntensityTexture, defines, \"SS_REFRACTIONINTENSITY_TEXTURE\");\n }\n if (this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled && !useOnlyThicknessTexture) {\n MaterialHelper.PrepareDefinesForMergedUV(this._translucencyIntensityTexture, defines, \"SS_TRANSLUCENCYINTENSITY_TEXTURE\");\n }\n }\n }\n defines.SS_HAS_THICKNESS = this.maximumThickness - this.minimumThickness !== 0.0;\n defines.SS_MASK_FROM_THICKNESS_TEXTURE =\n (this._useMaskFromThicknessTexture || !!this._refractionIntensityTexture || !!this._translucencyIntensityTexture) && useOnlyThicknessTexture;\n defines.SS_USE_GLTF_TEXTURES = this._useGltfStyleTextures;\n defines.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE = (this._useMaskFromThicknessTexture || !!this._refractionIntensityTexture) && useOnlyThicknessTexture;\n defines.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE = (this._useMaskFromThicknessTexture || !!this._translucencyIntensityTexture) && useOnlyThicknessTexture;\n if (this._isRefractionEnabled) {\n if (scene.texturesEnabled) {\n const refractionTexture = this._getRefractionTexture(scene);\n if (refractionTexture && MaterialFlags.RefractionTextureEnabled) {\n defines.SS_REFRACTION = true;\n defines.SS_REFRACTIONMAP_3D = refractionTexture.isCube;\n defines.SS_GAMMAREFRACTION = refractionTexture.gammaSpace;\n defines.SS_RGBDREFRACTION = refractionTexture.isRGBD;\n defines.SS_LINEARSPECULARREFRACTION = refractionTexture.linearSpecularLOD;\n defines.SS_REFRACTIONMAP_OPPOSITEZ = this._scene.useRightHandedSystem && refractionTexture.isCube ? !refractionTexture.invertZ : refractionTexture.invertZ;\n defines.SS_LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;\n defines.SS_LINKREFRACTIONTOTRANSPARENCY = this._linkRefractionWithTransparency;\n defines.SS_ALBEDOFORREFRACTIONTINT = this.useAlbedoToTintRefraction;\n defines.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = refractionTexture.isCube && refractionTexture.boundingBoxSize;\n defines.SS_USE_THICKNESS_AS_DEPTH = this.useThicknessAsDepth;\n }\n }\n }\n if (this._isTranslucencyEnabled) {\n defines.SS_ALBEDOFORTRANSLUCENCYTINT = this.useAlbedoToTintTranslucency;\n }\n }\n }\n /**\n * Binds the material data (this function is called even if mustRebind() returns false)\n * @param uniformBuffer defines the Uniform buffer to fill in.\n * @param scene defines the scene the material belongs to.\n * @param engine defines the engine the material belongs to.\n * @param subMesh the submesh to bind data for\n */\n hardBindForSubMesh(uniformBuffer, scene, engine, subMesh) {\n if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled) {\n return;\n }\n subMesh.getRenderingMesh().getWorldMatrix().decompose(TmpVectors.Vector3[0]);\n const thicknessScale = Math.max(Math.abs(TmpVectors.Vector3[0].x), Math.abs(TmpVectors.Vector3[0].y), Math.abs(TmpVectors.Vector3[0].z));\n uniformBuffer.updateFloat2(\"vThicknessParam\", this.minimumThickness * thicknessScale, (this.maximumThickness - this.minimumThickness) * thicknessScale);\n }\n bindForSubMesh(uniformBuffer, scene, engine, subMesh) {\n if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled) {\n return;\n }\n const defines = subMesh.materialDefines;\n const isFrozen = this._material.isFrozen;\n const realTimeFiltering = this._material.realTimeFiltering;\n const lodBasedMicrosurface = defines.LODBASEDMICROSFURACE;\n const refractionTexture = this._getRefractionTexture(scene);\n if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {\n if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) {\n uniformBuffer.updateFloat2(\"vThicknessInfos\", this._thicknessTexture.coordinatesIndex, this._thicknessTexture.level);\n MaterialHelper.BindTextureMatrix(this._thicknessTexture, uniformBuffer, \"thickness\");\n }\n if (this._refractionIntensityTexture && MaterialFlags.RefractionIntensityTextureEnabled && defines.SS_REFRACTIONINTENSITY_TEXTURE) {\n uniformBuffer.updateFloat2(\"vRefractionIntensityInfos\", this._refractionIntensityTexture.coordinatesIndex, this._refractionIntensityTexture.level);\n MaterialHelper.BindTextureMatrix(this._refractionIntensityTexture, uniformBuffer, \"refractionIntensity\");\n }\n if (this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled && defines.SS_TRANSLUCENCYINTENSITY_TEXTURE) {\n uniformBuffer.updateFloat2(\"vTranslucencyIntensityInfos\", this._translucencyIntensityTexture.coordinatesIndex, this._translucencyIntensityTexture.level);\n MaterialHelper.BindTextureMatrix(this._translucencyIntensityTexture, uniformBuffer, \"translucencyIntensity\");\n }\n if (refractionTexture && MaterialFlags.RefractionTextureEnabled) {\n uniformBuffer.updateMatrix(\"refractionMatrix\", refractionTexture.getRefractionTextureMatrix());\n let depth = 1.0;\n if (!refractionTexture.isCube) {\n if (refractionTexture.depth) {\n depth = refractionTexture.depth;\n }\n }\n const width = refractionTexture.getSize().width;\n const refractionIor = this.volumeIndexOfRefraction;\n uniformBuffer.updateFloat4(\"vRefractionInfos\", refractionTexture.level, 1 / refractionIor, depth, this._invertRefractionY ? -1 : 1);\n uniformBuffer.updateFloat4(\"vRefractionMicrosurfaceInfos\", width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset, 1.0 / this.indexOfRefraction);\n if (realTimeFiltering) {\n uniformBuffer.updateFloat2(\"vRefractionFilteringInfo\", width, Scalar.Log2(width));\n }\n if (refractionTexture.boundingBoxSize) {\n const cubeTexture = refractionTexture;\n uniformBuffer.updateVector3(\"vRefractionPosition\", cubeTexture.boundingBoxPosition);\n uniformBuffer.updateVector3(\"vRefractionSize\", cubeTexture.boundingBoxSize);\n }\n }\n if (this._isScatteringEnabled) {\n uniformBuffer.updateFloat(\"scatteringDiffusionProfile\", this._scatteringDiffusionProfileIndex);\n }\n uniformBuffer.updateColor3(\"vDiffusionDistance\", this.diffusionDistance);\n uniformBuffer.updateFloat4(\"vTintColor\", this.tintColor.r, this.tintColor.g, this.tintColor.b, Math.max(0.00001, this.tintColorAtDistance));\n uniformBuffer.updateFloat3(\"vSubSurfaceIntensity\", this.refractionIntensity, this.translucencyIntensity, 0);\n }\n // Textures\n if (scene.texturesEnabled) {\n if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) {\n uniformBuffer.setTexture(\"thicknessSampler\", this._thicknessTexture);\n }\n if (this._refractionIntensityTexture && MaterialFlags.RefractionIntensityTextureEnabled && defines.SS_REFRACTIONINTENSITY_TEXTURE) {\n uniformBuffer.setTexture(\"refractionIntensitySampler\", this._refractionIntensityTexture);\n }\n if (this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled && defines.SS_TRANSLUCENCYINTENSITY_TEXTURE) {\n uniformBuffer.setTexture(\"translucencyIntensitySampler\", this._translucencyIntensityTexture);\n }\n if (refractionTexture && MaterialFlags.RefractionTextureEnabled) {\n if (lodBasedMicrosurface) {\n uniformBuffer.setTexture(\"refractionSampler\", refractionTexture);\n }\n else {\n uniformBuffer.setTexture(\"refractionSampler\", refractionTexture._lodTextureMid || refractionTexture);\n uniformBuffer.setTexture(\"refractionSamplerLow\", refractionTexture._lodTextureLow || refractionTexture);\n uniformBuffer.setTexture(\"refractionSamplerHigh\", refractionTexture._lodTextureHigh || refractionTexture);\n }\n }\n }\n }\n /**\n * Returns the texture used for refraction or null if none is used.\n * @param scene defines the scene the material belongs to.\n * @returns - Refraction texture if present. If no refraction texture and refraction\n * is linked with transparency, returns environment texture. Otherwise, returns null.\n */\n _getRefractionTexture(scene) {\n if (this._refractionTexture) {\n return this._refractionTexture;\n }\n if (this._isRefractionEnabled) {\n return scene.environmentTexture;\n }\n return null;\n }\n /**\n * Returns true if alpha blending should be disabled.\n */\n get disableAlphaBlending() {\n return this._isRefractionEnabled && this._linkRefractionWithTransparency;\n }\n /**\n * Fills the list of render target textures.\n * @param renderTargets the list of render targets to update\n */\n fillRenderTargetTextures(renderTargets) {\n if (MaterialFlags.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {\n renderTargets.push(this._refractionTexture);\n }\n }\n hasTexture(texture) {\n if (this._thicknessTexture === texture) {\n return true;\n }\n if (this._refractionTexture === texture) {\n return true;\n }\n return false;\n }\n hasRenderTargetTextures() {\n if (MaterialFlags.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {\n return true;\n }\n return false;\n }\n getActiveTextures(activeTextures) {\n if (this._thicknessTexture) {\n activeTextures.push(this._thicknessTexture);\n }\n if (this._refractionTexture) {\n activeTextures.push(this._refractionTexture);\n }\n }\n getAnimatables(animatables) {\n if (this._thicknessTexture && this._thicknessTexture.animations && this._thicknessTexture.animations.length > 0) {\n animatables.push(this._thicknessTexture);\n }\n if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {\n animatables.push(this._refractionTexture);\n }\n }\n dispose(forceDisposeTextures) {\n if (forceDisposeTextures) {\n if (this._thicknessTexture) {\n this._thicknessTexture.dispose();\n }\n if (this._refractionTexture) {\n this._refractionTexture.dispose();\n }\n }\n }\n getClassName() {\n return \"PBRSubSurfaceConfiguration\";\n }\n addFallbacks(defines, fallbacks, currentRank) {\n if (defines.SS_SCATTERING) {\n fallbacks.addFallback(currentRank++, \"SS_SCATTERING\");\n }\n if (defines.SS_TRANSLUCENCY) {\n fallbacks.addFallback(currentRank++, \"SS_TRANSLUCENCY\");\n }\n return currentRank;\n }\n getSamplers(samplers) {\n samplers.push(\"thicknessSampler\", \"refractionIntensitySampler\", \"translucencyIntensitySampler\", \"refractionSampler\", \"refractionSamplerLow\", \"refractionSamplerHigh\");\n }\n getUniforms() {\n return {\n ubo: [\n { name: \"vRefractionMicrosurfaceInfos\", size: 4, type: \"vec4\" },\n { name: \"vRefractionFilteringInfo\", size: 2, type: \"vec2\" },\n { name: \"vTranslucencyIntensityInfos\", size: 2, type: \"vec2\" },\n { name: \"vRefractionInfos\", size: 4, type: \"vec4\" },\n { name: \"refractionMatrix\", size: 16, type: \"mat4\" },\n { name: \"vThicknessInfos\", size: 2, type: \"vec2\" },\n { name: \"vRefractionIntensityInfos\", size: 2, type: \"vec2\" },\n { name: \"thicknessMatrix\", size: 16, type: \"mat4\" },\n { name: \"refractionIntensityMatrix\", size: 16, type: \"mat4\" },\n { name: \"translucencyIntensityMatrix\", size: 16, type: \"mat4\" },\n { name: \"vThicknessParam\", size: 2, type: \"vec2\" },\n { name: \"vDiffusionDistance\", size: 3, type: \"vec3\" },\n { name: \"vTintColor\", size: 4, type: \"vec4\" },\n { name: \"vSubSurfaceIntensity\", size: 3, type: \"vec3\" },\n { name: \"vRefractionPosition\", size: 3, type: \"vec3\" },\n { name: \"vRefractionSize\", size: 3, type: \"vec3\" },\n { name: \"scatteringDiffusionProfile\", size: 1, type: \"float\" },\n ],\n };\n }\n}\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSubSurfaceConfiguration.prototype, \"isRefractionEnabled\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSubSurfaceConfiguration.prototype, \"isTranslucencyEnabled\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markScenePrePassDirty\")\n], PBRSubSurfaceConfiguration.prototype, \"isScatteringEnabled\", void 0);\n__decorate([\n serialize()\n], PBRSubSurfaceConfiguration.prototype, \"_scatteringDiffusionProfileIndex\", void 0);\n__decorate([\n serialize()\n], PBRSubSurfaceConfiguration.prototype, \"refractionIntensity\", void 0);\n__decorate([\n serialize()\n], PBRSubSurfaceConfiguration.prototype, \"translucencyIntensity\", void 0);\n__decorate([\n serialize()\n], PBRSubSurfaceConfiguration.prototype, \"useAlbedoToTintRefraction\", void 0);\n__decorate([\n serialize()\n], PBRSubSurfaceConfiguration.prototype, \"useAlbedoToTintTranslucency\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSubSurfaceConfiguration.prototype, \"thicknessTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSubSurfaceConfiguration.prototype, \"refractionTexture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSubSurfaceConfiguration.prototype, \"indexOfRefraction\", void 0);\n__decorate([\n serialize()\n], PBRSubSurfaceConfiguration.prototype, \"_volumeIndexOfRefraction\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSubSurfaceConfiguration.prototype, \"volumeIndexOfRefraction\", null);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSubSurfaceConfiguration.prototype, \"invertRefractionY\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSubSurfaceConfiguration.prototype, \"linkRefractionWithTransparency\", void 0);\n__decorate([\n serialize()\n], PBRSubSurfaceConfiguration.prototype, \"minimumThickness\", void 0);\n__decorate([\n serialize()\n], PBRSubSurfaceConfiguration.prototype, \"maximumThickness\", void 0);\n__decorate([\n serialize()\n], PBRSubSurfaceConfiguration.prototype, \"useThicknessAsDepth\", void 0);\n__decorate([\n serializeAsColor3()\n], PBRSubSurfaceConfiguration.prototype, \"tintColor\", void 0);\n__decorate([\n serialize()\n], PBRSubSurfaceConfiguration.prototype, \"tintColorAtDistance\", void 0);\n__decorate([\n serializeAsColor3()\n], PBRSubSurfaceConfiguration.prototype, \"diffusionDistance\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSubSurfaceConfiguration.prototype, \"useMaskFromThicknessTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSubSurfaceConfiguration.prototype, \"refractionIntensityTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSubSurfaceConfiguration.prototype, \"translucencyIntensityTexture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSubSurfaceConfiguration.prototype, \"useGltfStyleTextures\", void 0);\n//# sourceMappingURL=pbrSubSurfaceConfiguration.js.map","import { __decorate } from \"../../tslib.es6.js\";\n/* eslint-disable @typescript-eslint/naming-convention */\nimport { serialize, serializeAsImageProcessingConfiguration, expandToProperty } from \"../../Misc/decorators.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { SmartArray } from \"../../Misc/smartArray.js\";\nimport { GetEnvironmentBRDFTexture } from \"../../Misc/brdfTextureTools.js\";\nimport { Scene } from \"../../scene.js\";\nimport { Vector4 } from \"../../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../../Buffers/buffer.js\";\nimport { PBRBRDFConfiguration } from \"./pbrBRDFConfiguration.js\";\nimport { PrePassConfiguration } from \"../prePassConfiguration.js\";\nimport { Color3, TmpColors } from \"../../Maths/math.color.js\";\nimport { Scalar } from \"../../Maths/math.scalar.js\";\nimport { ImageProcessingConfiguration } from \"../../Materials/imageProcessingConfiguration.js\";\nimport { Material } from \"../../Materials/material.js\";\nimport { MaterialPluginEvent } from \"../materialPluginEvent.js\";\nimport { MaterialDefines } from \"../../Materials/materialDefines.js\";\nimport { PushMaterial } from \"../../Materials/pushMaterial.js\";\nimport { MaterialHelper } from \"../../Materials/materialHelper.js\";\nimport { Texture } from \"../../Materials/Textures/texture.js\";\nimport { MaterialFlags } from \"../materialFlags.js\";\n\nimport \"../../Materials/Textures/baseTexture.polynomial.js\";\nimport \"../../Shaders/pbr.fragment.js\";\nimport \"../../Shaders/pbr.vertex.js\";\nimport { EffectFallbacks } from \"../effectFallbacks.js\";\nimport { PBRClearCoatConfiguration } from \"./pbrClearCoatConfiguration.js\";\nimport { PBRIridescenceConfiguration } from \"./pbrIridescenceConfiguration.js\";\nimport { PBRAnisotropicConfiguration } from \"./pbrAnisotropicConfiguration.js\";\nimport { PBRSheenConfiguration } from \"./pbrSheenConfiguration.js\";\nimport { PBRSubSurfaceConfiguration } from \"./pbrSubSurfaceConfiguration.js\";\nimport { DetailMapConfiguration } from \"../material.detailMapConfiguration.js\";\nimport { addClipPlaneUniforms, bindClipPlane } from \"../clipPlaneMaterialHelper.js\";\nconst onCreatedEffectParameters = { effect: null, subMesh: null };\n/**\n * Manages the defines for the PBR Material.\n * @internal\n */\nexport class PBRMaterialDefines extends MaterialDefines {\n /**\n * Initializes the PBR Material defines.\n * @param externalProperties The external properties\n */\n constructor(externalProperties) {\n super(externalProperties);\n this.PBR = true;\n this.NUM_SAMPLES = \"0\";\n this.REALTIME_FILTERING = false;\n this.MAINUV1 = false;\n this.MAINUV2 = false;\n this.MAINUV3 = false;\n this.MAINUV4 = false;\n this.MAINUV5 = false;\n this.MAINUV6 = false;\n this.UV1 = false;\n this.UV2 = false;\n this.UV3 = false;\n this.UV4 = false;\n this.UV5 = false;\n this.UV6 = false;\n this.ALBEDO = false;\n this.GAMMAALBEDO = false;\n this.ALBEDODIRECTUV = 0;\n this.VERTEXCOLOR = false;\n this.BAKED_VERTEX_ANIMATION_TEXTURE = false;\n this.AMBIENT = false;\n this.AMBIENTDIRECTUV = 0;\n this.AMBIENTINGRAYSCALE = false;\n this.OPACITY = false;\n this.VERTEXALPHA = false;\n this.OPACITYDIRECTUV = 0;\n this.OPACITYRGB = false;\n this.ALPHATEST = false;\n this.DEPTHPREPASS = false;\n this.ALPHABLEND = false;\n this.ALPHAFROMALBEDO = false;\n this.ALPHATESTVALUE = \"0.5\";\n this.SPECULAROVERALPHA = false;\n this.RADIANCEOVERALPHA = false;\n this.ALPHAFRESNEL = false;\n this.LINEARALPHAFRESNEL = false;\n this.PREMULTIPLYALPHA = false;\n this.EMISSIVE = false;\n this.EMISSIVEDIRECTUV = 0;\n this.GAMMAEMISSIVE = false;\n this.REFLECTIVITY = false;\n this.REFLECTIVITY_GAMMA = false;\n this.REFLECTIVITYDIRECTUV = 0;\n this.SPECULARTERM = false;\n this.MICROSURFACEFROMREFLECTIVITYMAP = false;\n this.MICROSURFACEAUTOMATIC = false;\n this.LODBASEDMICROSFURACE = false;\n this.MICROSURFACEMAP = false;\n this.MICROSURFACEMAPDIRECTUV = 0;\n this.METALLICWORKFLOW = false;\n this.ROUGHNESSSTOREINMETALMAPALPHA = false;\n this.ROUGHNESSSTOREINMETALMAPGREEN = false;\n this.METALLNESSSTOREINMETALMAPBLUE = false;\n this.AOSTOREINMETALMAPRED = false;\n this.METALLIC_REFLECTANCE = false;\n this.METALLIC_REFLECTANCE_GAMMA = false;\n this.METALLIC_REFLECTANCEDIRECTUV = 0;\n this.METALLIC_REFLECTANCE_USE_ALPHA_ONLY = false;\n this.REFLECTANCE = false;\n this.REFLECTANCE_GAMMA = false;\n this.REFLECTANCEDIRECTUV = 0;\n this.ENVIRONMENTBRDF = false;\n this.ENVIRONMENTBRDF_RGBD = false;\n this.NORMAL = false;\n this.TANGENT = false;\n this.BUMP = false;\n this.BUMPDIRECTUV = 0;\n this.OBJECTSPACE_NORMALMAP = false;\n this.PARALLAX = false;\n this.PARALLAXOCCLUSION = false;\n this.NORMALXYSCALE = true;\n this.LIGHTMAP = false;\n this.LIGHTMAPDIRECTUV = 0;\n this.USELIGHTMAPASSHADOWMAP = false;\n this.GAMMALIGHTMAP = false;\n this.RGBDLIGHTMAP = false;\n this.REFLECTION = false;\n this.REFLECTIONMAP_3D = false;\n this.REFLECTIONMAP_SPHERICAL = false;\n this.REFLECTIONMAP_PLANAR = false;\n this.REFLECTIONMAP_CUBIC = false;\n this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;\n this.REFLECTIONMAP_PROJECTION = false;\n this.REFLECTIONMAP_SKYBOX = false;\n this.REFLECTIONMAP_EXPLICIT = false;\n this.REFLECTIONMAP_EQUIRECTANGULAR = false;\n this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;\n this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;\n this.INVERTCUBICMAP = false;\n this.USESPHERICALFROMREFLECTIONMAP = false;\n this.USEIRRADIANCEMAP = false;\n this.USESPHERICALINVERTEX = false;\n this.REFLECTIONMAP_OPPOSITEZ = false;\n this.LODINREFLECTIONALPHA = false;\n this.GAMMAREFLECTION = false;\n this.RGBDREFLECTION = false;\n this.LINEARSPECULARREFLECTION = false;\n this.RADIANCEOCCLUSION = false;\n this.HORIZONOCCLUSION = false;\n this.INSTANCES = false;\n this.THIN_INSTANCES = false;\n this.INSTANCESCOLOR = false;\n this.PREPASS = false;\n this.PREPASS_IRRADIANCE = false;\n this.PREPASS_IRRADIANCE_INDEX = -1;\n this.PREPASS_ALBEDO_SQRT = false;\n this.PREPASS_ALBEDO_SQRT_INDEX = -1;\n this.PREPASS_DEPTH = false;\n this.PREPASS_DEPTH_INDEX = -1;\n this.PREPASS_NORMAL = false;\n this.PREPASS_NORMAL_INDEX = -1;\n this.PREPASS_POSITION = false;\n this.PREPASS_POSITION_INDEX = -1;\n this.PREPASS_VELOCITY = false;\n this.PREPASS_VELOCITY_INDEX = -1;\n this.PREPASS_REFLECTIVITY = false;\n this.PREPASS_REFLECTIVITY_INDEX = -1;\n this.SCENE_MRT_COUNT = 0;\n this.NUM_BONE_INFLUENCERS = 0;\n this.BonesPerMesh = 0;\n this.BONETEXTURE = false;\n this.BONES_VELOCITY_ENABLED = false;\n this.NONUNIFORMSCALING = false;\n this.MORPHTARGETS = false;\n this.MORPHTARGETS_NORMAL = false;\n this.MORPHTARGETS_TANGENT = false;\n this.MORPHTARGETS_UV = false;\n this.NUM_MORPH_INFLUENCERS = 0;\n this.MORPHTARGETS_TEXTURE = false;\n this.IMAGEPROCESSING = false;\n this.VIGNETTE = false;\n this.VIGNETTEBLENDMODEMULTIPLY = false;\n this.VIGNETTEBLENDMODEOPAQUE = false;\n this.TONEMAPPING = false;\n this.TONEMAPPING_ACES = false;\n this.CONTRAST = false;\n this.COLORCURVES = false;\n this.COLORGRADING = false;\n this.COLORGRADING3D = false;\n this.SAMPLER3DGREENDEPTH = false;\n this.SAMPLER3DBGRMAP = false;\n this.DITHER = false;\n this.IMAGEPROCESSINGPOSTPROCESS = false;\n this.SKIPFINALCOLORCLAMP = false;\n this.EXPOSURE = false;\n this.MULTIVIEW = false;\n this.ORDER_INDEPENDENT_TRANSPARENCY = false;\n this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS = false;\n this.USEPHYSICALLIGHTFALLOFF = false;\n this.USEGLTFLIGHTFALLOFF = false;\n this.TWOSIDEDLIGHTING = false;\n this.SHADOWFLOAT = false;\n this.CLIPPLANE = false;\n this.CLIPPLANE2 = false;\n this.CLIPPLANE3 = false;\n this.CLIPPLANE4 = false;\n this.CLIPPLANE5 = false;\n this.CLIPPLANE6 = false;\n this.POINTSIZE = false;\n this.FOG = false;\n this.LOGARITHMICDEPTH = false;\n this.CAMERA_ORTHOGRAPHIC = false;\n this.CAMERA_PERSPECTIVE = false;\n this.FORCENORMALFORWARD = false;\n this.SPECULARAA = false;\n this.UNLIT = false;\n this.DEBUGMODE = 0;\n this.rebuild();\n }\n /**\n * Resets the PBR Material defines.\n */\n reset() {\n super.reset();\n this.ALPHATESTVALUE = \"0.5\";\n this.PBR = true;\n this.NORMALXYSCALE = true;\n }\n}\n/**\n * The Physically based material base class of BJS.\n *\n * This offers the main features of a standard PBR material.\n * For more information, please refer to the documentation :\n * https://doc.babylonjs.com/features/featuresDeepDive/materials/using/introToPBR\n */\nexport class PBRBaseMaterial extends PushMaterial {\n /**\n * Enables realtime filtering on the texture.\n */\n get realTimeFiltering() {\n return this._realTimeFiltering;\n }\n set realTimeFiltering(b) {\n this._realTimeFiltering = b;\n this.markAsDirty(1);\n }\n /**\n * Quality switch for realtime filtering\n */\n get realTimeFilteringQuality() {\n return this._realTimeFilteringQuality;\n }\n set realTimeFilteringQuality(n) {\n this._realTimeFilteringQuality = n;\n this.markAsDirty(1);\n }\n /**\n * Can this material render to several textures at once\n */\n get canRenderToMRT() {\n return true;\n }\n /**\n * Attaches a new image processing configuration to the PBR Material.\n * @param configuration\n */\n _attachImageProcessingConfiguration(configuration) {\n if (configuration === this._imageProcessingConfiguration) {\n return;\n }\n // Detaches observer.\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n // Pick the scene configuration if needed.\n if (!configuration) {\n this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;\n }\n else {\n this._imageProcessingConfiguration = configuration;\n }\n // Attaches observer.\n if (this._imageProcessingConfiguration) {\n this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => {\n this._markAllSubMeshesAsImageProcessingDirty();\n });\n }\n }\n /**\n * Instantiates a new PBRMaterial instance.\n *\n * @param name The material name\n * @param scene The scene the material will be use in.\n */\n constructor(name, scene) {\n super(name, scene);\n /**\n * Intensity of the direct lights e.g. the four lights available in your scene.\n * This impacts both the direct diffuse and specular highlights.\n * @internal\n */\n this._directIntensity = 1.0;\n /**\n * Intensity of the emissive part of the material.\n * This helps controlling the emissive effect without modifying the emissive color.\n * @internal\n */\n this._emissiveIntensity = 1.0;\n /**\n * Intensity of the environment e.g. how much the environment will light the object\n * either through harmonics for rough material or through the reflection for shiny ones.\n * @internal\n */\n this._environmentIntensity = 1.0;\n /**\n * This is a special control allowing the reduction of the specular highlights coming from the\n * four lights of the scene. Those highlights may not be needed in full environment lighting.\n * @internal\n */\n this._specularIntensity = 1.0;\n /**\n * This stores the direct, emissive, environment, and specular light intensities into a Vector4.\n */\n this._lightingInfos = new Vector4(this._directIntensity, this._emissiveIntensity, this._environmentIntensity, this._specularIntensity);\n /**\n * Debug Control allowing disabling the bump map on this material.\n * @internal\n */\n this._disableBumpMap = false;\n /**\n * AKA Diffuse Texture in standard nomenclature.\n * @internal\n */\n this._albedoTexture = null;\n /**\n * AKA Occlusion Texture in other nomenclature.\n * @internal\n */\n this._ambientTexture = null;\n /**\n * AKA Occlusion Texture Intensity in other nomenclature.\n * @internal\n */\n this._ambientTextureStrength = 1.0;\n /**\n * Defines how much the AO map is occluding the analytical lights (point spot...).\n * 1 means it completely occludes it\n * 0 mean it has no impact\n * @internal\n */\n this._ambientTextureImpactOnAnalyticalLights = PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;\n /**\n * Stores the alpha values in a texture.\n * @internal\n */\n this._opacityTexture = null;\n /**\n * Stores the reflection values in a texture.\n * @internal\n */\n this._reflectionTexture = null;\n /**\n * Stores the emissive values in a texture.\n * @internal\n */\n this._emissiveTexture = null;\n /**\n * AKA Specular texture in other nomenclature.\n * @internal\n */\n this._reflectivityTexture = null;\n /**\n * Used to switch from specular/glossiness to metallic/roughness workflow.\n * @internal\n */\n this._metallicTexture = null;\n /**\n * Specifies the metallic scalar of the metallic/roughness workflow.\n * Can also be used to scale the metalness values of the metallic texture.\n * @internal\n */\n this._metallic = null;\n /**\n * Specifies the roughness scalar of the metallic/roughness workflow.\n * Can also be used to scale the roughness values of the metallic texture.\n * @internal\n */\n this._roughness = null;\n /**\n * In metallic workflow, specifies an F0 factor to help configuring the material F0.\n * By default the indexOfrefraction is used to compute F0;\n *\n * This is used as a factor against the default reflectance at normal incidence to tweak it.\n *\n * F0 = defaultF0 * metallicF0Factor * metallicReflectanceColor;\n * F90 = metallicReflectanceColor;\n * @internal\n */\n this._metallicF0Factor = 1;\n /**\n * In metallic workflow, specifies an F90 color to help configuring the material F90.\n * By default the F90 is always 1;\n *\n * Please note that this factor is also used as a factor against the default reflectance at normal incidence.\n *\n * F0 = defaultF0 * metallicF0Factor * metallicReflectanceColor\n * F90 = metallicReflectanceColor;\n * @internal\n */\n this._metallicReflectanceColor = Color3.White();\n /**\n * Specifies that only the A channel from _metallicReflectanceTexture should be used.\n * If false, both RGB and A channels will be used\n * @internal\n */\n this._useOnlyMetallicFromMetallicReflectanceTexture = false;\n /**\n * Defines to store metallicReflectanceColor in RGB and metallicF0Factor in A\n * This is multiply against the scalar values defined in the material.\n * @internal\n */\n this._metallicReflectanceTexture = null;\n /**\n * Defines to store reflectanceColor in RGB\n * This is multiplied against the scalar values defined in the material.\n * If both _reflectanceTexture and _metallicReflectanceTexture textures are provided and _useOnlyMetallicFromMetallicReflectanceTexture\n * is false, _metallicReflectanceTexture takes precedence and _reflectanceTexture is not used\n * @internal\n */\n this._reflectanceTexture = null;\n /**\n * Used to enable roughness/glossiness fetch from a separate channel depending on the current mode.\n * Gray Scale represents roughness in metallic mode and glossiness in specular mode.\n * @internal\n */\n this._microSurfaceTexture = null;\n /**\n * Stores surface normal data used to displace a mesh in a texture.\n * @internal\n */\n this._bumpTexture = null;\n /**\n * Stores the pre-calculated light information of a mesh in a texture.\n * @internal\n */\n this._lightmapTexture = null;\n /**\n * The color of a material in ambient lighting.\n * @internal\n */\n this._ambientColor = new Color3(0, 0, 0);\n /**\n * AKA Diffuse Color in other nomenclature.\n * @internal\n */\n this._albedoColor = new Color3(1, 1, 1);\n /**\n * AKA Specular Color in other nomenclature.\n * @internal\n */\n this._reflectivityColor = new Color3(1, 1, 1);\n /**\n * The color applied when light is reflected from a material.\n * @internal\n */\n this._reflectionColor = new Color3(1, 1, 1);\n /**\n * The color applied when light is emitted from a material.\n * @internal\n */\n this._emissiveColor = new Color3(0, 0, 0);\n /**\n * AKA Glossiness in other nomenclature.\n * @internal\n */\n this._microSurface = 0.9;\n /**\n * Specifies that the material will use the light map as a show map.\n * @internal\n */\n this._useLightmapAsShadowmap = false;\n /**\n * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal\n * makes the reflect vector face the model (under horizon).\n * @internal\n */\n this._useHorizonOcclusion = true;\n /**\n * This parameters will enable/disable radiance occlusion by preventing the radiance to lit\n * too much the area relying on ambient texture to define their ambient occlusion.\n * @internal\n */\n this._useRadianceOcclusion = true;\n /**\n * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.\n * @internal\n */\n this._useAlphaFromAlbedoTexture = false;\n /**\n * Specifies that the material will keeps the specular highlights over a transparent surface (only the most luminous ones).\n * A car glass is a good example of that. When sun reflects on it you can not see what is behind.\n * @internal\n */\n this._useSpecularOverAlpha = true;\n /**\n * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.\n * @internal\n */\n this._useMicroSurfaceFromReflectivityMapAlpha = false;\n /**\n * Specifies if the metallic texture contains the roughness information in its alpha channel.\n * @internal\n */\n this._useRoughnessFromMetallicTextureAlpha = true;\n /**\n * Specifies if the metallic texture contains the roughness information in its green channel.\n * @internal\n */\n this._useRoughnessFromMetallicTextureGreen = false;\n /**\n * Specifies if the metallic texture contains the metallness information in its blue channel.\n * @internal\n */\n this._useMetallnessFromMetallicTextureBlue = false;\n /**\n * Specifies if the metallic texture contains the ambient occlusion information in its red channel.\n * @internal\n */\n this._useAmbientOcclusionFromMetallicTextureRed = false;\n /**\n * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.\n * @internal\n */\n this._useAmbientInGrayScale = false;\n /**\n * In case the reflectivity map does not contain the microsurface information in its alpha channel,\n * The material will try to infer what glossiness each pixel should be.\n * @internal\n */\n this._useAutoMicroSurfaceFromReflectivityMap = false;\n /**\n * Defines the falloff type used in this material.\n * It by default is Physical.\n * @internal\n */\n this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;\n /**\n * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most luminous ones).\n * A car glass is a good example of that. When the street lights reflects on it you can not see what is behind.\n * @internal\n */\n this._useRadianceOverAlpha = true;\n /**\n * Allows using an object space normal map (instead of tangent space).\n * @internal\n */\n this._useObjectSpaceNormalMap = false;\n /**\n * Allows using the bump map in parallax mode.\n * @internal\n */\n this._useParallax = false;\n /**\n * Allows using the bump map in parallax occlusion mode.\n * @internal\n */\n this._useParallaxOcclusion = false;\n /**\n * Controls the scale bias of the parallax mode.\n * @internal\n */\n this._parallaxScaleBias = 0.05;\n /**\n * If sets to true, disables all the lights affecting the material.\n * @internal\n */\n this._disableLighting = false;\n /**\n * Number of Simultaneous lights allowed on the material.\n * @internal\n */\n this._maxSimultaneousLights = 4;\n /**\n * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).\n * @internal\n */\n this._invertNormalMapX = false;\n /**\n * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).\n * @internal\n */\n this._invertNormalMapY = false;\n /**\n * If sets to true and backfaceCulling is false, normals will be flipped on the backside.\n * @internal\n */\n this._twoSidedLighting = false;\n /**\n * Defines the alpha limits in alpha test mode.\n * @internal\n */\n this._alphaCutOff = 0.4;\n /**\n * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.\n * @internal\n */\n this._forceAlphaTest = false;\n /**\n * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.\n * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)\n * @internal\n */\n this._useAlphaFresnel = false;\n /**\n * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.\n * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)\n * @internal\n */\n this._useLinearAlphaFresnel = false;\n /**\n * Specifies the environment BRDF texture used to compute the scale and offset roughness values\n * from cos theta and roughness:\n * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf\n * @internal\n */\n this._environmentBRDFTexture = null;\n /**\n * Force the shader to compute irradiance in the fragment shader in order to take bump in account.\n * @internal\n */\n this._forceIrradianceInFragment = false;\n this._realTimeFiltering = false;\n this._realTimeFilteringQuality = 8;\n /**\n * Force normal to face away from face.\n * @internal\n */\n this._forceNormalForward = false;\n /**\n * Enables specular anti aliasing in the PBR shader.\n * It will both interacts on the Geometry for analytical and IBL lighting.\n * It also prefilter the roughness map based on the bump values.\n * @internal\n */\n this._enableSpecularAntiAliasing = false;\n /**\n * Keep track of the image processing observer to allow dispose and replace.\n */\n this._imageProcessingObserver = null;\n /**\n * Stores the available render targets.\n */\n this._renderTargets = new SmartArray(16);\n /**\n * Sets the global ambient color for the material used in lighting calculations.\n */\n this._globalAmbientColor = new Color3(0, 0, 0);\n /**\n * Enables the use of logarithmic depth buffers, which is good for wide depth buffers.\n */\n this._useLogarithmicDepth = false;\n /**\n * If set to true, no lighting calculations will be applied.\n */\n this._unlit = false;\n this._debugMode = 0;\n /**\n * @internal\n * This is reserved for the inspector.\n * Defines the material debug mode.\n * It helps seeing only some components of the material while troubleshooting.\n */\n this.debugMode = 0;\n /**\n * @internal\n * This is reserved for the inspector.\n * Specify from where on screen the debug mode should start.\n * The value goes from -1 (full screen) to 1 (not visible)\n * It helps with side by side comparison against the final render\n * This defaults to -1\n */\n this.debugLimit = -1;\n /**\n * @internal\n * This is reserved for the inspector.\n * As the default viewing range might not be enough (if the ambient is really small for instance)\n * You can use the factor to better multiply the final value.\n */\n this.debugFactor = 1;\n this._cacheHasRenderTargetTextures = false;\n this.brdf = new PBRBRDFConfiguration(this);\n this.clearCoat = new PBRClearCoatConfiguration(this);\n this.iridescence = new PBRIridescenceConfiguration(this);\n this.anisotropy = new PBRAnisotropicConfiguration(this);\n this.sheen = new PBRSheenConfiguration(this);\n this.subSurface = new PBRSubSurfaceConfiguration(this);\n this.detailMap = new DetailMapConfiguration(this);\n // Setup the default processing configuration to the scene.\n this._attachImageProcessingConfiguration(null);\n this.getRenderTargetTextures = () => {\n this._renderTargets.reset();\n if (MaterialFlags.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {\n this._renderTargets.push(this._reflectionTexture);\n }\n this._eventInfo.renderTargets = this._renderTargets;\n this._callbackPluginEventFillRenderTargetTextures(this._eventInfo);\n return this._renderTargets;\n };\n this._environmentBRDFTexture = GetEnvironmentBRDFTexture(this.getScene());\n this.prePassConfiguration = new PrePassConfiguration();\n }\n /**\n * Gets a boolean indicating that current material needs to register RTT\n */\n get hasRenderTargetTextures() {\n if (MaterialFlags.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {\n return true;\n }\n return this._cacheHasRenderTargetTextures;\n }\n /**\n * Can this material render to prepass\n */\n get isPrePassCapable() {\n return !this.disableDepthWrite;\n }\n /**\n * Gets the name of the material class.\n */\n getClassName() {\n return \"PBRBaseMaterial\";\n }\n /**\n * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.\n */\n get useLogarithmicDepth() {\n return this._useLogarithmicDepth;\n }\n /**\n * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.\n */\n set useLogarithmicDepth(value) {\n this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;\n }\n /**\n * Returns true if alpha blending should be disabled.\n */\n get _disableAlphaBlending() {\n var _a;\n return (this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_OPAQUE ||\n this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_ALPHATEST ||\n ((_a = this.subSurface) === null || _a === void 0 ? void 0 : _a.disableAlphaBlending));\n }\n /**\n * Specifies whether or not this material should be rendered in alpha blend mode.\n */\n needAlphaBlending() {\n if (this._disableAlphaBlending) {\n return false;\n }\n return this.alpha < 1.0 || this._opacityTexture != null || this._shouldUseAlphaFromAlbedoTexture();\n }\n /**\n * Specifies whether or not this material should be rendered in alpha test mode.\n */\n needAlphaTesting() {\n var _a;\n if (this._forceAlphaTest) {\n return true;\n }\n if ((_a = this.subSurface) === null || _a === void 0 ? void 0 : _a.disableAlphaBlending) {\n return false;\n }\n return this._hasAlphaChannel() && (this._transparencyMode == null || this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_ALPHATEST);\n }\n /**\n * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.\n */\n _shouldUseAlphaFromAlbedoTexture() {\n return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== PBRBaseMaterial.PBRMATERIAL_OPAQUE;\n }\n /**\n * Specifies whether or not there is a usable alpha channel for transparency.\n */\n _hasAlphaChannel() {\n return (this._albedoTexture != null && this._albedoTexture.hasAlpha) || this._opacityTexture != null;\n }\n /**\n * Gets the texture used for the alpha test.\n */\n getAlphaTestTexture() {\n return this._albedoTexture;\n }\n /**\n * Specifies that the submesh is ready to be used.\n * @param mesh - BJS mesh.\n * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.\n * @param useInstances - Specifies that instances should be used.\n * @returns - boolean indicating that the submesh is ready or not.\n */\n isReadyForSubMesh(mesh, subMesh, useInstances) {\n var _a;\n if (!this._uniformBufferLayoutBuilt) {\n this.buildUniformLayout();\n }\n if (subMesh.effect && this.isFrozen) {\n if (subMesh.effect._wasPreviouslyReady && subMesh.effect._wasPreviouslyUsingInstances === useInstances) {\n return true;\n }\n }\n if (!subMesh.materialDefines) {\n this._callbackPluginEventGeneric(MaterialPluginEvent.GetDefineNames, this._eventInfo);\n subMesh.materialDefines = new PBRMaterialDefines(this._eventInfo.defineNames);\n }\n const defines = subMesh.materialDefines;\n if (this._isReadyForSubMesh(subMesh)) {\n return true;\n }\n const scene = this.getScene();\n const engine = scene.getEngine();\n if (defines._areTexturesDirty) {\n this._eventInfo.hasRenderTargetTextures = false;\n this._callbackPluginEventHasRenderTargetTextures(this._eventInfo);\n this._cacheHasRenderTargetTextures = this._eventInfo.hasRenderTargetTextures;\n if (scene.texturesEnabled) {\n if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) {\n if (!this._albedoTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) {\n if (!this._ambientTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) {\n if (!this._opacityTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n const reflectionTexture = this._getReflectionTexture();\n if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {\n if (!reflectionTexture.isReadyOrNotBlocking()) {\n return false;\n }\n if (reflectionTexture.irradianceTexture) {\n if (!reflectionTexture.irradianceTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n else {\n // Not ready until spherical are ready too.\n if (!reflectionTexture.sphericalPolynomial && ((_a = reflectionTexture.getInternalTexture()) === null || _a === void 0 ? void 0 : _a._sphericalPolynomialPromise)) {\n return false;\n }\n }\n }\n if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) {\n if (!this._lightmapTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) {\n if (!this._emissiveTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (MaterialFlags.SpecularTextureEnabled) {\n if (this._metallicTexture) {\n if (!this._metallicTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n else if (this._reflectivityTexture) {\n if (!this._reflectivityTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._metallicReflectanceTexture) {\n if (!this._metallicReflectanceTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._reflectanceTexture) {\n if (!this._reflectanceTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._microSurfaceTexture) {\n if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n }\n if (engine.getCaps().standardDerivatives && this._bumpTexture && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) {\n // Bump texture cannot be not blocking.\n if (!this._bumpTexture.isReady()) {\n return false;\n }\n }\n if (this._environmentBRDFTexture && MaterialFlags.ReflectionTextureEnabled) {\n // This is blocking.\n if (!this._environmentBRDFTexture.isReady()) {\n return false;\n }\n }\n }\n }\n this._eventInfo.isReadyForSubMesh = true;\n this._eventInfo.defines = defines;\n this._eventInfo.subMesh = subMesh;\n this._callbackPluginEventIsReadyForSubMesh(this._eventInfo);\n if (!this._eventInfo.isReadyForSubMesh) {\n return false;\n }\n if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {\n if (!this._imageProcessingConfiguration.isReady()) {\n return false;\n }\n }\n if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {\n mesh.createNormals(true);\n Logger.Warn(\"PBRMaterial: Normals have been created for the mesh: \" + mesh.name);\n }\n const previousEffect = subMesh.effect;\n const lightDisposed = defines._areLightsDisposed;\n let effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances, null, subMesh.getRenderingMesh().hasThinInstances);\n let forceWasNotReadyPreviously = false;\n if (effect) {\n if (this._onEffectCreatedObservable) {\n onCreatedEffectParameters.effect = effect;\n onCreatedEffectParameters.subMesh = subMesh;\n this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters);\n }\n // Use previous effect while new one is compiling\n if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {\n effect = previousEffect;\n defines.markAsUnprocessed();\n forceWasNotReadyPreviously = this.isFrozen;\n if (lightDisposed) {\n // re register in case it takes more than one frame.\n defines._areLightsDisposed = true;\n return false;\n }\n }\n else {\n scene.resetCachedMaterial();\n subMesh.setEffect(effect, defines, this._materialContext);\n }\n }\n if (!subMesh.effect || !subMesh.effect.isReady()) {\n return false;\n }\n defines._renderId = scene.getRenderId();\n subMesh.effect._wasPreviouslyReady = forceWasNotReadyPreviously ? false : true;\n subMesh.effect._wasPreviouslyUsingInstances = !!useInstances;\n this._checkScenePerformancePriority();\n return true;\n }\n /**\n * Specifies if the material uses metallic roughness workflow.\n * @returns boolean specifying if the material uses metallic roughness workflow.\n */\n isMetallicWorkflow() {\n if (this._metallic != null || this._roughness != null || this._metallicTexture) {\n return true;\n }\n return false;\n }\n _prepareEffect(mesh, defines, onCompiled = null, onError = null, useInstances = null, useClipPlane = null, useThinInstances) {\n this._prepareDefines(mesh, defines, useInstances, useClipPlane, useThinInstances);\n if (!defines.isDirty) {\n return null;\n }\n defines.markAsProcessed();\n const scene = this.getScene();\n const engine = scene.getEngine();\n // Fallbacks\n const fallbacks = new EffectFallbacks();\n let fallbackRank = 0;\n if (defines.USESPHERICALINVERTEX) {\n fallbacks.addFallback(fallbackRank++, \"USESPHERICALINVERTEX\");\n }\n if (defines.FOG) {\n fallbacks.addFallback(fallbackRank, \"FOG\");\n }\n if (defines.SPECULARAA) {\n fallbacks.addFallback(fallbackRank, \"SPECULARAA\");\n }\n if (defines.POINTSIZE) {\n fallbacks.addFallback(fallbackRank, \"POINTSIZE\");\n }\n if (defines.LOGARITHMICDEPTH) {\n fallbacks.addFallback(fallbackRank, \"LOGARITHMICDEPTH\");\n }\n if (defines.PARALLAX) {\n fallbacks.addFallback(fallbackRank, \"PARALLAX\");\n }\n if (defines.PARALLAXOCCLUSION) {\n fallbacks.addFallback(fallbackRank++, \"PARALLAXOCCLUSION\");\n }\n if (defines.ENVIRONMENTBRDF) {\n fallbacks.addFallback(fallbackRank++, \"ENVIRONMENTBRDF\");\n }\n if (defines.TANGENT) {\n fallbacks.addFallback(fallbackRank++, \"TANGENT\");\n }\n if (defines.BUMP) {\n fallbacks.addFallback(fallbackRank++, \"BUMP\");\n }\n fallbackRank = MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);\n if (defines.SPECULARTERM) {\n fallbacks.addFallback(fallbackRank++, \"SPECULARTERM\");\n }\n if (defines.USESPHERICALFROMREFLECTIONMAP) {\n fallbacks.addFallback(fallbackRank++, \"USESPHERICALFROMREFLECTIONMAP\");\n }\n if (defines.USEIRRADIANCEMAP) {\n fallbacks.addFallback(fallbackRank++, \"USEIRRADIANCEMAP\");\n }\n if (defines.LIGHTMAP) {\n fallbacks.addFallback(fallbackRank++, \"LIGHTMAP\");\n }\n if (defines.NORMAL) {\n fallbacks.addFallback(fallbackRank++, \"NORMAL\");\n }\n if (defines.AMBIENT) {\n fallbacks.addFallback(fallbackRank++, \"AMBIENT\");\n }\n if (defines.EMISSIVE) {\n fallbacks.addFallback(fallbackRank++, \"EMISSIVE\");\n }\n if (defines.VERTEXCOLOR) {\n fallbacks.addFallback(fallbackRank++, \"VERTEXCOLOR\");\n }\n if (defines.MORPHTARGETS) {\n fallbacks.addFallback(fallbackRank++, \"MORPHTARGETS\");\n }\n if (defines.MULTIVIEW) {\n fallbacks.addFallback(0, \"MULTIVIEW\");\n }\n //Attributes\n const attribs = [VertexBuffer.PositionKind];\n if (defines.NORMAL) {\n attribs.push(VertexBuffer.NormalKind);\n }\n if (defines.TANGENT) {\n attribs.push(VertexBuffer.TangentKind);\n }\n for (let i = 1; i <= 6; ++i) {\n if (defines[\"UV\" + i]) {\n attribs.push(`uv${i === 1 ? \"\" : i}`);\n }\n }\n if (defines.VERTEXCOLOR) {\n attribs.push(VertexBuffer.ColorKind);\n }\n if (defines.INSTANCESCOLOR) {\n attribs.push(VertexBuffer.ColorInstanceKind);\n }\n MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);\n MaterialHelper.PrepareAttributesForInstances(attribs, defines);\n MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);\n MaterialHelper.PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines);\n let shaderName = \"pbr\";\n const uniforms = [\n \"world\",\n \"view\",\n \"viewProjection\",\n \"vEyePosition\",\n \"vLightsType\",\n \"vAmbientColor\",\n \"vAlbedoColor\",\n \"vReflectivityColor\",\n \"vMetallicReflectanceFactors\",\n \"vEmissiveColor\",\n \"visibility\",\n \"vReflectionColor\",\n \"vFogInfos\",\n \"vFogColor\",\n \"pointSize\",\n \"vAlbedoInfos\",\n \"vAmbientInfos\",\n \"vOpacityInfos\",\n \"vReflectionInfos\",\n \"vReflectionPosition\",\n \"vReflectionSize\",\n \"vEmissiveInfos\",\n \"vReflectivityInfos\",\n \"vReflectionFilteringInfo\",\n \"vMetallicReflectanceInfos\",\n \"vReflectanceInfos\",\n \"vMicroSurfaceSamplerInfos\",\n \"vBumpInfos\",\n \"vLightmapInfos\",\n \"mBones\",\n \"albedoMatrix\",\n \"ambientMatrix\",\n \"opacityMatrix\",\n \"reflectionMatrix\",\n \"emissiveMatrix\",\n \"reflectivityMatrix\",\n \"normalMatrix\",\n \"microSurfaceSamplerMatrix\",\n \"bumpMatrix\",\n \"lightmapMatrix\",\n \"metallicReflectanceMatrix\",\n \"reflectanceMatrix\",\n \"vLightingIntensity\",\n \"logarithmicDepthConstant\",\n \"vSphericalX\",\n \"vSphericalY\",\n \"vSphericalZ\",\n \"vSphericalXX_ZZ\",\n \"vSphericalYY_ZZ\",\n \"vSphericalZZ\",\n \"vSphericalXY\",\n \"vSphericalYZ\",\n \"vSphericalZX\",\n \"vSphericalL00\",\n \"vSphericalL1_1\",\n \"vSphericalL10\",\n \"vSphericalL11\",\n \"vSphericalL2_2\",\n \"vSphericalL2_1\",\n \"vSphericalL20\",\n \"vSphericalL21\",\n \"vSphericalL22\",\n \"vReflectionMicrosurfaceInfos\",\n \"vTangentSpaceParams\",\n \"boneTextureWidth\",\n \"vDebugMode\",\n \"morphTargetTextureInfo\",\n \"morphTargetTextureIndices\",\n ];\n const samplers = [\n \"albedoSampler\",\n \"reflectivitySampler\",\n \"ambientSampler\",\n \"emissiveSampler\",\n \"bumpSampler\",\n \"lightmapSampler\",\n \"opacitySampler\",\n \"reflectionSampler\",\n \"reflectionSamplerLow\",\n \"reflectionSamplerHigh\",\n \"irradianceSampler\",\n \"microSurfaceSampler\",\n \"environmentBrdfSampler\",\n \"boneSampler\",\n \"metallicReflectanceSampler\",\n \"reflectanceSampler\",\n \"morphTargets\",\n \"oitDepthSampler\",\n \"oitFrontColorSampler\",\n ];\n const uniformBuffers = [\"Material\", \"Scene\", \"Mesh\"];\n this._eventInfo.fallbacks = fallbacks;\n this._eventInfo.fallbackRank = fallbackRank;\n this._eventInfo.defines = defines;\n this._eventInfo.uniforms = uniforms;\n this._eventInfo.attributes = attribs;\n this._eventInfo.samplers = samplers;\n this._eventInfo.uniformBuffersNames = uniformBuffers;\n this._eventInfo.customCode = undefined;\n this._eventInfo.mesh = mesh;\n this._callbackPluginEventGeneric(MaterialPluginEvent.PrepareEffect, this._eventInfo);\n PrePassConfiguration.AddUniforms(uniforms);\n PrePassConfiguration.AddSamplers(samplers);\n addClipPlaneUniforms(uniforms);\n if (ImageProcessingConfiguration) {\n ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);\n ImageProcessingConfiguration.PrepareSamplers(samplers, defines);\n }\n MaterialHelper.PrepareUniformsAndSamplersList({\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: defines,\n maxSimultaneousLights: this._maxSimultaneousLights,\n });\n const csnrOptions = {};\n if (this.customShaderNameResolve) {\n shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines, attribs, csnrOptions);\n }\n const join = defines.toString();\n const effect = engine.createEffect(shaderName, {\n attributes: attribs,\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: join,\n fallbacks: fallbacks,\n onCompiled: onCompiled,\n onError: onError,\n indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS },\n processFinalCode: csnrOptions.processFinalCode,\n processCodeAfterIncludes: this._eventInfo.customCode,\n multiTarget: defines.PREPASS,\n }, engine);\n this._eventInfo.customCode = undefined;\n return effect;\n }\n _prepareDefines(mesh, defines, useInstances = null, useClipPlane = null, useThinInstances = false) {\n var _a;\n const scene = this.getScene();\n const engine = scene.getEngine();\n // Lights\n MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);\n defines._needNormals = true;\n // Multiview\n MaterialHelper.PrepareDefinesForMultiview(scene, defines);\n // PrePass\n const oit = this.needAlphaBlendingForMesh(mesh) && this.getScene().useOrderIndependentTransparency;\n MaterialHelper.PrepareDefinesForPrePass(scene, defines, this.canRenderToMRT && !oit);\n // Order independant transparency\n MaterialHelper.PrepareDefinesForOIT(scene, defines, oit);\n // Textures\n defines.METALLICWORKFLOW = this.isMetallicWorkflow();\n if (defines._areTexturesDirty) {\n defines._needUVs = false;\n for (let i = 1; i <= 6; ++i) {\n defines[\"MAINUV\" + i] = false;\n }\n if (scene.texturesEnabled) {\n defines.ALBEDODIRECTUV = 0;\n defines.AMBIENTDIRECTUV = 0;\n defines.OPACITYDIRECTUV = 0;\n defines.EMISSIVEDIRECTUV = 0;\n defines.REFLECTIVITYDIRECTUV = 0;\n defines.MICROSURFACEMAPDIRECTUV = 0;\n defines.METALLIC_REFLECTANCEDIRECTUV = 0;\n defines.REFLECTANCEDIRECTUV = 0;\n defines.BUMPDIRECTUV = 0;\n defines.LIGHTMAPDIRECTUV = 0;\n if (engine.getCaps().textureLOD) {\n defines.LODBASEDMICROSFURACE = true;\n }\n if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, \"ALBEDO\");\n defines.GAMMAALBEDO = this._albedoTexture.gammaSpace;\n }\n else {\n defines.ALBEDO = false;\n }\n if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, \"AMBIENT\");\n defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;\n }\n else {\n defines.AMBIENT = false;\n }\n if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, \"OPACITY\");\n defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;\n }\n else {\n defines.OPACITY = false;\n }\n const reflectionTexture = this._getReflectionTexture();\n if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {\n defines.REFLECTION = true;\n defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;\n defines.RGBDREFLECTION = reflectionTexture.isRGBD;\n defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;\n defines.LINEARSPECULARREFLECTION = reflectionTexture.linearSpecularLOD;\n if (this.realTimeFiltering && this.realTimeFilteringQuality > 0) {\n defines.NUM_SAMPLES = \"\" + this.realTimeFilteringQuality;\n if (engine._features.needTypeSuffixInShaderConstants) {\n defines.NUM_SAMPLES = defines.NUM_SAMPLES + \"u\";\n }\n defines.REALTIME_FILTERING = true;\n }\n else {\n defines.REALTIME_FILTERING = false;\n }\n defines.INVERTCUBICMAP = reflectionTexture.coordinatesMode === Texture.INVCUBIC_MODE;\n defines.REFLECTIONMAP_3D = reflectionTexture.isCube;\n defines.REFLECTIONMAP_OPPOSITEZ = defines.REFLECTIONMAP_3D && this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;\n defines.REFLECTIONMAP_CUBIC = false;\n defines.REFLECTIONMAP_EXPLICIT = false;\n defines.REFLECTIONMAP_PLANAR = false;\n defines.REFLECTIONMAP_PROJECTION = false;\n defines.REFLECTIONMAP_SKYBOX = false;\n defines.REFLECTIONMAP_SPHERICAL = false;\n defines.REFLECTIONMAP_EQUIRECTANGULAR = false;\n defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;\n defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;\n switch (reflectionTexture.coordinatesMode) {\n case Texture.EXPLICIT_MODE:\n defines.REFLECTIONMAP_EXPLICIT = true;\n break;\n case Texture.PLANAR_MODE:\n defines.REFLECTIONMAP_PLANAR = true;\n break;\n case Texture.PROJECTION_MODE:\n defines.REFLECTIONMAP_PROJECTION = true;\n break;\n case Texture.SKYBOX_MODE:\n defines.REFLECTIONMAP_SKYBOX = true;\n break;\n case Texture.SPHERICAL_MODE:\n defines.REFLECTIONMAP_SPHERICAL = true;\n break;\n case Texture.EQUIRECTANGULAR_MODE:\n defines.REFLECTIONMAP_EQUIRECTANGULAR = true;\n break;\n case Texture.FIXED_EQUIRECTANGULAR_MODE:\n defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;\n break;\n case Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:\n defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;\n break;\n case Texture.CUBIC_MODE:\n case Texture.INVCUBIC_MODE:\n default:\n defines.REFLECTIONMAP_CUBIC = true;\n defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;\n break;\n }\n if (reflectionTexture.coordinatesMode !== Texture.SKYBOX_MODE) {\n if (reflectionTexture.irradianceTexture) {\n defines.USEIRRADIANCEMAP = true;\n defines.USESPHERICALFROMREFLECTIONMAP = false;\n }\n // Assume using spherical polynomial if the reflection texture is a cube map\n else if (reflectionTexture.isCube) {\n defines.USESPHERICALFROMREFLECTIONMAP = true;\n defines.USEIRRADIANCEMAP = false;\n if (this._forceIrradianceInFragment || this.realTimeFiltering || engine.getCaps().maxVaryingVectors <= 8) {\n defines.USESPHERICALINVERTEX = false;\n }\n else {\n defines.USESPHERICALINVERTEX = true;\n }\n }\n }\n }\n else {\n defines.REFLECTION = false;\n defines.REFLECTIONMAP_3D = false;\n defines.REFLECTIONMAP_SPHERICAL = false;\n defines.REFLECTIONMAP_PLANAR = false;\n defines.REFLECTIONMAP_CUBIC = false;\n defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;\n defines.REFLECTIONMAP_PROJECTION = false;\n defines.REFLECTIONMAP_SKYBOX = false;\n defines.REFLECTIONMAP_EXPLICIT = false;\n defines.REFLECTIONMAP_EQUIRECTANGULAR = false;\n defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;\n defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;\n defines.INVERTCUBICMAP = false;\n defines.USESPHERICALFROMREFLECTIONMAP = false;\n defines.USEIRRADIANCEMAP = false;\n defines.USESPHERICALINVERTEX = false;\n defines.REFLECTIONMAP_OPPOSITEZ = false;\n defines.LODINREFLECTIONALPHA = false;\n defines.GAMMAREFLECTION = false;\n defines.RGBDREFLECTION = false;\n defines.LINEARSPECULARREFLECTION = false;\n }\n if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, \"LIGHTMAP\");\n defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;\n defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;\n defines.RGBDLIGHTMAP = this._lightmapTexture.isRGBD;\n }\n else {\n defines.LIGHTMAP = false;\n }\n if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, \"EMISSIVE\");\n defines.GAMMAEMISSIVE = this._emissiveTexture.gammaSpace;\n }\n else {\n defines.EMISSIVE = false;\n }\n if (MaterialFlags.SpecularTextureEnabled) {\n if (this._metallicTexture) {\n MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, \"REFLECTIVITY\");\n defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;\n defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;\n defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;\n defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;\n defines.REFLECTIVITY_GAMMA = false;\n }\n else if (this._reflectivityTexture) {\n MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, \"REFLECTIVITY\");\n defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;\n defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;\n defines.REFLECTIVITY_GAMMA = this._reflectivityTexture.gammaSpace;\n }\n else {\n defines.REFLECTIVITY = false;\n }\n if (this._metallicReflectanceTexture || this._reflectanceTexture) {\n const identicalTextures = this._metallicReflectanceTexture !== null &&\n this._metallicReflectanceTexture._texture === ((_a = this._reflectanceTexture) === null || _a === void 0 ? void 0 : _a._texture) &&\n this._metallicReflectanceTexture.checkTransformsAreIdentical(this._reflectanceTexture);\n defines.METALLIC_REFLECTANCE_USE_ALPHA_ONLY = this._useOnlyMetallicFromMetallicReflectanceTexture && !identicalTextures;\n if (this._metallicReflectanceTexture) {\n MaterialHelper.PrepareDefinesForMergedUV(this._metallicReflectanceTexture, defines, \"METALLIC_REFLECTANCE\");\n defines.METALLIC_REFLECTANCE_GAMMA = this._metallicReflectanceTexture.gammaSpace;\n }\n else {\n defines.METALLIC_REFLECTANCE = false;\n }\n if (this._reflectanceTexture &&\n !identicalTextures &&\n (!this._metallicReflectanceTexture || (this._metallicReflectanceTexture && this._useOnlyMetallicFromMetallicReflectanceTexture))) {\n MaterialHelper.PrepareDefinesForMergedUV(this._reflectanceTexture, defines, \"REFLECTANCE\");\n defines.REFLECTANCE_GAMMA = this._reflectanceTexture.gammaSpace;\n }\n else {\n defines.REFLECTANCE = false;\n }\n }\n else {\n defines.METALLIC_REFLECTANCE = false;\n defines.REFLECTANCE = false;\n }\n if (this._microSurfaceTexture) {\n MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, \"MICROSURFACEMAP\");\n }\n else {\n defines.MICROSURFACEMAP = false;\n }\n }\n else {\n defines.REFLECTIVITY = false;\n defines.MICROSURFACEMAP = false;\n }\n if (engine.getCaps().standardDerivatives && this._bumpTexture && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) {\n MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, \"BUMP\");\n if (this._useParallax && this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) {\n defines.PARALLAX = true;\n defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;\n }\n else {\n defines.PARALLAX = false;\n }\n defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;\n }\n else {\n defines.BUMP = false;\n defines.PARALLAX = false;\n defines.PARALLAXOCCLUSION = false;\n defines.OBJECTSPACE_NORMALMAP = false;\n }\n if (this._environmentBRDFTexture && MaterialFlags.ReflectionTextureEnabled) {\n defines.ENVIRONMENTBRDF = true;\n defines.ENVIRONMENTBRDF_RGBD = this._environmentBRDFTexture.isRGBD;\n }\n else {\n defines.ENVIRONMENTBRDF = false;\n defines.ENVIRONMENTBRDF_RGBD = false;\n }\n if (this._shouldUseAlphaFromAlbedoTexture()) {\n defines.ALPHAFROMALBEDO = true;\n }\n else {\n defines.ALPHAFROMALBEDO = false;\n }\n }\n defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;\n if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {\n defines.USEPHYSICALLIGHTFALLOFF = false;\n defines.USEGLTFLIGHTFALLOFF = false;\n }\n else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {\n defines.USEPHYSICALLIGHTFALLOFF = false;\n defines.USEGLTFLIGHTFALLOFF = true;\n }\n else {\n defines.USEPHYSICALLIGHTFALLOFF = true;\n defines.USEGLTFLIGHTFALLOFF = false;\n }\n defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;\n if (!this.backFaceCulling && this._twoSidedLighting) {\n defines.TWOSIDEDLIGHTING = true;\n }\n else {\n defines.TWOSIDEDLIGHTING = false;\n }\n defines.SPECULARAA = engine.getCaps().standardDerivatives && this._enableSpecularAntiAliasing;\n }\n if (defines._areTexturesDirty || defines._areMiscDirty) {\n defines.ALPHATESTVALUE = `${this._alphaCutOff}${this._alphaCutOff % 1 === 0 ? \".\" : \"\"}`;\n defines.PREMULTIPLYALPHA = this.alphaMode === 7 || this.alphaMode === 8;\n defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);\n defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;\n defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;\n }\n if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {\n this._imageProcessingConfiguration.prepareDefines(defines);\n }\n defines.FORCENORMALFORWARD = this._forceNormalForward;\n defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;\n defines.HORIZONOCCLUSION = this._useHorizonOcclusion;\n // Misc.\n if (defines._areMiscDirty) {\n MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);\n defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(VertexBuffer.NormalKind));\n defines.DEBUGMODE = this._debugMode;\n }\n // Values that need to be evaluated on every frame\n MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, this, defines, useInstances ? true : false, useClipPlane, useThinInstances);\n // External config\n this._eventInfo.defines = defines;\n this._eventInfo.mesh = mesh;\n this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo);\n // Attribs\n MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== PBRBaseMaterial.PBRMATERIAL_OPAQUE);\n // External config\n this._callbackPluginEventPrepareDefines(this._eventInfo);\n }\n /**\n * Force shader compilation\n * @param mesh\n * @param onCompiled\n * @param options\n */\n forceCompilation(mesh, onCompiled, options) {\n const localOptions = Object.assign({ clipPlane: false, useInstances: false }, options);\n if (!this._uniformBufferLayoutBuilt) {\n this.buildUniformLayout();\n }\n this._callbackPluginEventGeneric(MaterialPluginEvent.GetDefineNames, this._eventInfo);\n const defines = new PBRMaterialDefines(this._eventInfo.defineNames);\n const effect = this._prepareEffect(mesh, defines, undefined, undefined, localOptions.useInstances, localOptions.clipPlane, mesh.hasThinInstances);\n if (this._onEffectCreatedObservable) {\n onCreatedEffectParameters.effect = effect;\n onCreatedEffectParameters.subMesh = null;\n this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters);\n }\n if (effect.isReady()) {\n if (onCompiled) {\n onCompiled(this);\n }\n }\n else {\n effect.onCompileObservable.add(() => {\n if (onCompiled) {\n onCompiled(this);\n }\n });\n }\n }\n /**\n * Initializes the uniform buffer layout for the shader.\n */\n buildUniformLayout() {\n // Order is important !\n const ubo = this._uniformBuffer;\n ubo.addUniform(\"vAlbedoInfos\", 2);\n ubo.addUniform(\"vAmbientInfos\", 4);\n ubo.addUniform(\"vOpacityInfos\", 2);\n ubo.addUniform(\"vEmissiveInfos\", 2);\n ubo.addUniform(\"vLightmapInfos\", 2);\n ubo.addUniform(\"vReflectivityInfos\", 3);\n ubo.addUniform(\"vMicroSurfaceSamplerInfos\", 2);\n ubo.addUniform(\"vReflectionInfos\", 2);\n ubo.addUniform(\"vReflectionFilteringInfo\", 2);\n ubo.addUniform(\"vReflectionPosition\", 3);\n ubo.addUniform(\"vReflectionSize\", 3);\n ubo.addUniform(\"vBumpInfos\", 3);\n ubo.addUniform(\"albedoMatrix\", 16);\n ubo.addUniform(\"ambientMatrix\", 16);\n ubo.addUniform(\"opacityMatrix\", 16);\n ubo.addUniform(\"emissiveMatrix\", 16);\n ubo.addUniform(\"lightmapMatrix\", 16);\n ubo.addUniform(\"reflectivityMatrix\", 16);\n ubo.addUniform(\"microSurfaceSamplerMatrix\", 16);\n ubo.addUniform(\"bumpMatrix\", 16);\n ubo.addUniform(\"vTangentSpaceParams\", 2);\n ubo.addUniform(\"reflectionMatrix\", 16);\n ubo.addUniform(\"vReflectionColor\", 3);\n ubo.addUniform(\"vAlbedoColor\", 4);\n ubo.addUniform(\"vLightingIntensity\", 4);\n ubo.addUniform(\"vReflectionMicrosurfaceInfos\", 3);\n ubo.addUniform(\"pointSize\", 1);\n ubo.addUniform(\"vReflectivityColor\", 4);\n ubo.addUniform(\"vEmissiveColor\", 3);\n ubo.addUniform(\"vAmbientColor\", 3);\n ubo.addUniform(\"vDebugMode\", 2);\n ubo.addUniform(\"vMetallicReflectanceFactors\", 4);\n ubo.addUniform(\"vMetallicReflectanceInfos\", 2);\n ubo.addUniform(\"metallicReflectanceMatrix\", 16);\n ubo.addUniform(\"vReflectanceInfos\", 2);\n ubo.addUniform(\"reflectanceMatrix\", 16);\n ubo.addUniform(\"vSphericalL00\", 3);\n ubo.addUniform(\"vSphericalL1_1\", 3);\n ubo.addUniform(\"vSphericalL10\", 3);\n ubo.addUniform(\"vSphericalL11\", 3);\n ubo.addUniform(\"vSphericalL2_2\", 3);\n ubo.addUniform(\"vSphericalL2_1\", 3);\n ubo.addUniform(\"vSphericalL20\", 3);\n ubo.addUniform(\"vSphericalL21\", 3);\n ubo.addUniform(\"vSphericalL22\", 3);\n ubo.addUniform(\"vSphericalX\", 3);\n ubo.addUniform(\"vSphericalY\", 3);\n ubo.addUniform(\"vSphericalZ\", 3);\n ubo.addUniform(\"vSphericalXX_ZZ\", 3);\n ubo.addUniform(\"vSphericalYY_ZZ\", 3);\n ubo.addUniform(\"vSphericalZZ\", 3);\n ubo.addUniform(\"vSphericalXY\", 3);\n ubo.addUniform(\"vSphericalYZ\", 3);\n ubo.addUniform(\"vSphericalZX\", 3);\n super.buildUniformLayout();\n }\n /**\n * Binds the submesh data.\n * @param world - The world matrix.\n * @param mesh - The BJS mesh.\n * @param subMesh - A submesh of the BJS mesh.\n */\n bindForSubMesh(world, mesh, subMesh) {\n var _a, _b, _c, _d;\n const scene = this.getScene();\n const defines = subMesh.materialDefines;\n if (!defines) {\n return;\n }\n const effect = subMesh.effect;\n if (!effect) {\n return;\n }\n this._activeEffect = effect;\n // Matrices Mesh.\n mesh.getMeshUniformBuffer().bindToEffect(effect, \"Mesh\");\n mesh.transferToEffect(world);\n const engine = scene.getEngine();\n // Binding unconditionally\n this._uniformBuffer.bindToEffect(effect, \"Material\");\n this.prePassConfiguration.bindForSubMesh(this._activeEffect, scene, mesh, world, this.isFrozen);\n this._eventInfo.subMesh = subMesh;\n this._callbackPluginEventHardBindForSubMesh(this._eventInfo);\n // Normal Matrix\n if (defines.OBJECTSPACE_NORMALMAP) {\n world.toNormalMatrix(this._normalMatrix);\n this.bindOnlyNormalMatrix(this._normalMatrix);\n }\n const mustRebind = effect._forceRebindOnNextCall || this._mustRebind(scene, effect, mesh.visibility);\n // Bones\n MaterialHelper.BindBonesParameters(mesh, this._activeEffect, this.prePassConfiguration);\n let reflectionTexture = null;\n const ubo = this._uniformBuffer;\n if (mustRebind) {\n this.bindViewProjection(effect);\n reflectionTexture = this._getReflectionTexture();\n if (!ubo.useUbo || !this.isFrozen || !ubo.isSync || effect._forceRebindOnNextCall) {\n // Texture uniforms\n if (scene.texturesEnabled) {\n if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) {\n ubo.updateFloat2(\"vAlbedoInfos\", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);\n MaterialHelper.BindTextureMatrix(this._albedoTexture, ubo, \"albedo\");\n }\n if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) {\n ubo.updateFloat4(\"vAmbientInfos\", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);\n MaterialHelper.BindTextureMatrix(this._ambientTexture, ubo, \"ambient\");\n }\n if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) {\n ubo.updateFloat2(\"vOpacityInfos\", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);\n MaterialHelper.BindTextureMatrix(this._opacityTexture, ubo, \"opacity\");\n }\n if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {\n ubo.updateMatrix(\"reflectionMatrix\", reflectionTexture.getReflectionTextureMatrix());\n ubo.updateFloat2(\"vReflectionInfos\", reflectionTexture.level, 0);\n if (reflectionTexture.boundingBoxSize) {\n const cubeTexture = reflectionTexture;\n ubo.updateVector3(\"vReflectionPosition\", cubeTexture.boundingBoxPosition);\n ubo.updateVector3(\"vReflectionSize\", cubeTexture.boundingBoxSize);\n }\n if (this.realTimeFiltering) {\n const width = reflectionTexture.getSize().width;\n ubo.updateFloat2(\"vReflectionFilteringInfo\", width, Scalar.Log2(width));\n }\n if (!defines.USEIRRADIANCEMAP) {\n const polynomials = reflectionTexture.sphericalPolynomial;\n if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {\n if (defines.SPHERICAL_HARMONICS) {\n const preScaledHarmonics = polynomials.preScaledHarmonics;\n ubo.updateVector3(\"vSphericalL00\", preScaledHarmonics.l00);\n ubo.updateVector3(\"vSphericalL1_1\", preScaledHarmonics.l1_1);\n ubo.updateVector3(\"vSphericalL10\", preScaledHarmonics.l10);\n ubo.updateVector3(\"vSphericalL11\", preScaledHarmonics.l11);\n ubo.updateVector3(\"vSphericalL2_2\", preScaledHarmonics.l2_2);\n ubo.updateVector3(\"vSphericalL2_1\", preScaledHarmonics.l2_1);\n ubo.updateVector3(\"vSphericalL20\", preScaledHarmonics.l20);\n ubo.updateVector3(\"vSphericalL21\", preScaledHarmonics.l21);\n ubo.updateVector3(\"vSphericalL22\", preScaledHarmonics.l22);\n }\n else {\n ubo.updateFloat3(\"vSphericalX\", polynomials.x.x, polynomials.x.y, polynomials.x.z);\n ubo.updateFloat3(\"vSphericalY\", polynomials.y.x, polynomials.y.y, polynomials.y.z);\n ubo.updateFloat3(\"vSphericalZ\", polynomials.z.x, polynomials.z.y, polynomials.z.z);\n ubo.updateFloat3(\"vSphericalXX_ZZ\", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);\n ubo.updateFloat3(\"vSphericalYY_ZZ\", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);\n ubo.updateFloat3(\"vSphericalZZ\", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);\n ubo.updateFloat3(\"vSphericalXY\", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);\n ubo.updateFloat3(\"vSphericalYZ\", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);\n ubo.updateFloat3(\"vSphericalZX\", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);\n }\n }\n }\n ubo.updateFloat3(\"vReflectionMicrosurfaceInfos\", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);\n }\n if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) {\n ubo.updateFloat2(\"vEmissiveInfos\", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);\n MaterialHelper.BindTextureMatrix(this._emissiveTexture, ubo, \"emissive\");\n }\n if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) {\n ubo.updateFloat2(\"vLightmapInfos\", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);\n MaterialHelper.BindTextureMatrix(this._lightmapTexture, ubo, \"lightmap\");\n }\n if (MaterialFlags.SpecularTextureEnabled) {\n if (this._metallicTexture) {\n ubo.updateFloat3(\"vReflectivityInfos\", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);\n MaterialHelper.BindTextureMatrix(this._metallicTexture, ubo, \"reflectivity\");\n }\n else if (this._reflectivityTexture) {\n ubo.updateFloat3(\"vReflectivityInfos\", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);\n MaterialHelper.BindTextureMatrix(this._reflectivityTexture, ubo, \"reflectivity\");\n }\n if (this._metallicReflectanceTexture) {\n ubo.updateFloat2(\"vMetallicReflectanceInfos\", this._metallicReflectanceTexture.coordinatesIndex, this._metallicReflectanceTexture.level);\n MaterialHelper.BindTextureMatrix(this._metallicReflectanceTexture, ubo, \"metallicReflectance\");\n }\n if (this._reflectanceTexture && defines.REFLECTANCE) {\n ubo.updateFloat2(\"vReflectanceInfos\", this._reflectanceTexture.coordinatesIndex, this._reflectanceTexture.level);\n MaterialHelper.BindTextureMatrix(this._reflectanceTexture, ubo, \"reflectance\");\n }\n if (this._microSurfaceTexture) {\n ubo.updateFloat2(\"vMicroSurfaceSamplerInfos\", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);\n MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, ubo, \"microSurfaceSampler\");\n }\n }\n if (this._bumpTexture && engine.getCaps().standardDerivatives && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) {\n ubo.updateFloat3(\"vBumpInfos\", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);\n MaterialHelper.BindTextureMatrix(this._bumpTexture, ubo, \"bump\");\n if (scene._mirroredCameraPosition) {\n ubo.updateFloat2(\"vTangentSpaceParams\", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);\n }\n else {\n ubo.updateFloat2(\"vTangentSpaceParams\", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);\n }\n }\n }\n // Point size\n if (this.pointsCloud) {\n ubo.updateFloat(\"pointSize\", this.pointSize);\n }\n // Colors\n if (defines.METALLICWORKFLOW) {\n TmpColors.Color3[0].r = this._metallic === undefined || this._metallic === null ? 1 : this._metallic;\n TmpColors.Color3[0].g = this._roughness === undefined || this._roughness === null ? 1 : this._roughness;\n ubo.updateColor4(\"vReflectivityColor\", TmpColors.Color3[0], 1);\n const ior = (_b = (_a = this.subSurface) === null || _a === void 0 ? void 0 : _a._indexOfRefraction) !== null && _b !== void 0 ? _b : 1.5;\n const outsideIOR = 1; // consider air as clear coat and other layers would remap in the shader.\n // We are here deriving our default reflectance from a common value for none metallic surface.\n // Based of the schlick fresnel approximation model\n // for dielectrics.\n const f0 = Math.pow((ior - outsideIOR) / (ior + outsideIOR), 2);\n // Tweak the default F0 and F90 based on our given setup\n this._metallicReflectanceColor.scaleToRef(f0 * this._metallicF0Factor, TmpColors.Color3[0]);\n const metallicF90 = this._metallicF0Factor;\n ubo.updateColor4(\"vMetallicReflectanceFactors\", TmpColors.Color3[0], metallicF90);\n }\n else {\n ubo.updateColor4(\"vReflectivityColor\", this._reflectivityColor, this._microSurface);\n }\n ubo.updateColor3(\"vEmissiveColor\", MaterialFlags.EmissiveTextureEnabled ? this._emissiveColor : Color3.BlackReadOnly);\n ubo.updateColor3(\"vReflectionColor\", this._reflectionColor);\n if (!defines.SS_REFRACTION && ((_c = this.subSurface) === null || _c === void 0 ? void 0 : _c._linkRefractionWithTransparency)) {\n ubo.updateColor4(\"vAlbedoColor\", this._albedoColor, 1);\n }\n else {\n ubo.updateColor4(\"vAlbedoColor\", this._albedoColor, this.alpha);\n }\n // Misc\n this._lightingInfos.x = this._directIntensity;\n this._lightingInfos.y = this._emissiveIntensity;\n this._lightingInfos.z = this._environmentIntensity * scene.environmentIntensity;\n this._lightingInfos.w = this._specularIntensity;\n ubo.updateVector4(\"vLightingIntensity\", this._lightingInfos);\n // Colors\n scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);\n ubo.updateColor3(\"vAmbientColor\", this._globalAmbientColor);\n ubo.updateFloat2(\"vDebugMode\", this.debugLimit, this.debugFactor);\n }\n // Textures\n if (scene.texturesEnabled) {\n if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) {\n ubo.setTexture(\"albedoSampler\", this._albedoTexture);\n }\n if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) {\n ubo.setTexture(\"ambientSampler\", this._ambientTexture);\n }\n if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) {\n ubo.setTexture(\"opacitySampler\", this._opacityTexture);\n }\n if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {\n if (defines.LODBASEDMICROSFURACE) {\n ubo.setTexture(\"reflectionSampler\", reflectionTexture);\n }\n else {\n ubo.setTexture(\"reflectionSampler\", reflectionTexture._lodTextureMid || reflectionTexture);\n ubo.setTexture(\"reflectionSamplerLow\", reflectionTexture._lodTextureLow || reflectionTexture);\n ubo.setTexture(\"reflectionSamplerHigh\", reflectionTexture._lodTextureHigh || reflectionTexture);\n }\n if (defines.USEIRRADIANCEMAP) {\n ubo.setTexture(\"irradianceSampler\", reflectionTexture.irradianceTexture);\n }\n }\n if (defines.ENVIRONMENTBRDF) {\n ubo.setTexture(\"environmentBrdfSampler\", this._environmentBRDFTexture);\n }\n if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) {\n ubo.setTexture(\"emissiveSampler\", this._emissiveTexture);\n }\n if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) {\n ubo.setTexture(\"lightmapSampler\", this._lightmapTexture);\n }\n if (MaterialFlags.SpecularTextureEnabled) {\n if (this._metallicTexture) {\n ubo.setTexture(\"reflectivitySampler\", this._metallicTexture);\n }\n else if (this._reflectivityTexture) {\n ubo.setTexture(\"reflectivitySampler\", this._reflectivityTexture);\n }\n if (this._metallicReflectanceTexture) {\n ubo.setTexture(\"metallicReflectanceSampler\", this._metallicReflectanceTexture);\n }\n if (this._reflectanceTexture && defines.REFLECTANCE) {\n ubo.setTexture(\"reflectanceSampler\", this._reflectanceTexture);\n }\n if (this._microSurfaceTexture) {\n ubo.setTexture(\"microSurfaceSampler\", this._microSurfaceTexture);\n }\n }\n if (this._bumpTexture && engine.getCaps().standardDerivatives && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) {\n ubo.setTexture(\"bumpSampler\", this._bumpTexture);\n }\n }\n // OIT with depth peeling\n if (this.getScene().useOrderIndependentTransparency && this.needAlphaBlendingForMesh(mesh)) {\n this.getScene().depthPeelingRenderer.bind(effect);\n }\n this._eventInfo.subMesh = subMesh;\n this._callbackPluginEventBindForSubMesh(this._eventInfo);\n // Clip plane\n bindClipPlane(this._activeEffect, this, scene);\n this.bindEyePosition(effect);\n }\n else if (scene.getEngine()._features.needToAlwaysBindUniformBuffers) {\n this._needToBindSceneUbo = true;\n }\n if (mustRebind || !this.isFrozen) {\n // Lights\n if (scene.lightsEnabled && !this._disableLighting) {\n MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights);\n }\n // View\n if ((scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) || reflectionTexture || mesh.receiveShadows || defines.PREPASS) {\n this.bindView(effect);\n }\n // Fog\n MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);\n // Morph targets\n if (defines.NUM_MORPH_INFLUENCERS) {\n MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);\n }\n if (defines.BAKED_VERTEX_ANIMATION_TEXTURE) {\n (_d = mesh.bakedVertexAnimationManager) === null || _d === void 0 ? void 0 : _d.bind(effect, defines.INSTANCES);\n }\n // image processing\n this._imageProcessingConfiguration.bind(this._activeEffect);\n // Log. depth\n MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);\n }\n this._afterBind(mesh, this._activeEffect);\n ubo.update();\n }\n /**\n * Returns the animatable textures.\n * If material have animatable metallic texture, then reflectivity texture will not be returned, even if it has animations.\n * @returns - Array of animatable textures.\n */\n getAnimatables() {\n const results = super.getAnimatables();\n if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {\n results.push(this._albedoTexture);\n }\n if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {\n results.push(this._ambientTexture);\n }\n if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {\n results.push(this._opacityTexture);\n }\n if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {\n results.push(this._reflectionTexture);\n }\n if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {\n results.push(this._emissiveTexture);\n }\n if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {\n results.push(this._metallicTexture);\n }\n else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {\n results.push(this._reflectivityTexture);\n }\n if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {\n results.push(this._bumpTexture);\n }\n if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {\n results.push(this._lightmapTexture);\n }\n if (this._metallicReflectanceTexture && this._metallicReflectanceTexture.animations && this._metallicReflectanceTexture.animations.length > 0) {\n results.push(this._metallicReflectanceTexture);\n }\n if (this._reflectanceTexture && this._reflectanceTexture.animations && this._reflectanceTexture.animations.length > 0) {\n results.push(this._reflectanceTexture);\n }\n if (this._microSurfaceTexture && this._microSurfaceTexture.animations && this._microSurfaceTexture.animations.length > 0) {\n results.push(this._microSurfaceTexture);\n }\n return results;\n }\n /**\n * Returns the texture used for reflections.\n * @returns - Reflection texture if present. Otherwise, returns the environment texture.\n */\n _getReflectionTexture() {\n if (this._reflectionTexture) {\n return this._reflectionTexture;\n }\n return this.getScene().environmentTexture;\n }\n /**\n * Returns an array of the actively used textures.\n * @returns - Array of BaseTextures\n */\n getActiveTextures() {\n const activeTextures = super.getActiveTextures();\n if (this._albedoTexture) {\n activeTextures.push(this._albedoTexture);\n }\n if (this._ambientTexture) {\n activeTextures.push(this._ambientTexture);\n }\n if (this._opacityTexture) {\n activeTextures.push(this._opacityTexture);\n }\n if (this._reflectionTexture) {\n activeTextures.push(this._reflectionTexture);\n }\n if (this._emissiveTexture) {\n activeTextures.push(this._emissiveTexture);\n }\n if (this._reflectivityTexture) {\n activeTextures.push(this._reflectivityTexture);\n }\n if (this._metallicTexture) {\n activeTextures.push(this._metallicTexture);\n }\n if (this._metallicReflectanceTexture) {\n activeTextures.push(this._metallicReflectanceTexture);\n }\n if (this._reflectanceTexture) {\n activeTextures.push(this._reflectanceTexture);\n }\n if (this._microSurfaceTexture) {\n activeTextures.push(this._microSurfaceTexture);\n }\n if (this._bumpTexture) {\n activeTextures.push(this._bumpTexture);\n }\n if (this._lightmapTexture) {\n activeTextures.push(this._lightmapTexture);\n }\n return activeTextures;\n }\n /**\n * Checks to see if a texture is used in the material.\n * @param texture - Base texture to use.\n * @returns - Boolean specifying if a texture is used in the material.\n */\n hasTexture(texture) {\n if (super.hasTexture(texture)) {\n return true;\n }\n if (this._albedoTexture === texture) {\n return true;\n }\n if (this._ambientTexture === texture) {\n return true;\n }\n if (this._opacityTexture === texture) {\n return true;\n }\n if (this._reflectionTexture === texture) {\n return true;\n }\n if (this._emissiveTexture === texture) {\n return true;\n }\n if (this._reflectivityTexture === texture) {\n return true;\n }\n if (this._metallicTexture === texture) {\n return true;\n }\n if (this._metallicReflectanceTexture === texture) {\n return true;\n }\n if (this._reflectanceTexture === texture) {\n return true;\n }\n if (this._microSurfaceTexture === texture) {\n return true;\n }\n if (this._bumpTexture === texture) {\n return true;\n }\n if (this._lightmapTexture === texture) {\n return true;\n }\n return false;\n }\n /**\n * Sets the required values to the prepass renderer.\n * It can't be sets when subsurface scattering of this material is disabled.\n * When scene have ability to enable subsurface prepass effect, it will enable.\n */\n setPrePassRenderer() {\n var _a;\n if (!((_a = this.subSurface) === null || _a === void 0 ? void 0 : _a.isScatteringEnabled)) {\n return false;\n }\n const subSurfaceConfiguration = this.getScene().enableSubSurfaceForPrePass();\n if (subSurfaceConfiguration) {\n subSurfaceConfiguration.enabled = true;\n }\n return true;\n }\n /**\n * Disposes the resources of the material.\n * @param forceDisposeEffect - Forces the disposal of effects.\n * @param forceDisposeTextures - Forces the disposal of all textures.\n */\n dispose(forceDisposeEffect, forceDisposeTextures) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;\n if (forceDisposeTextures) {\n if (this._environmentBRDFTexture && this.getScene().environmentBRDFTexture !== this._environmentBRDFTexture) {\n this._environmentBRDFTexture.dispose();\n }\n (_a = this._albedoTexture) === null || _a === void 0 ? void 0 : _a.dispose();\n (_b = this._ambientTexture) === null || _b === void 0 ? void 0 : _b.dispose();\n (_c = this._opacityTexture) === null || _c === void 0 ? void 0 : _c.dispose();\n (_d = this._reflectionTexture) === null || _d === void 0 ? void 0 : _d.dispose();\n (_e = this._emissiveTexture) === null || _e === void 0 ? void 0 : _e.dispose();\n (_f = this._metallicTexture) === null || _f === void 0 ? void 0 : _f.dispose();\n (_g = this._reflectivityTexture) === null || _g === void 0 ? void 0 : _g.dispose();\n (_h = this._bumpTexture) === null || _h === void 0 ? void 0 : _h.dispose();\n (_j = this._lightmapTexture) === null || _j === void 0 ? void 0 : _j.dispose();\n (_k = this._metallicReflectanceTexture) === null || _k === void 0 ? void 0 : _k.dispose();\n (_l = this._reflectanceTexture) === null || _l === void 0 ? void 0 : _l.dispose();\n (_m = this._microSurfaceTexture) === null || _m === void 0 ? void 0 : _m.dispose();\n }\n this._renderTargets.dispose();\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n super.dispose(forceDisposeEffect, forceDisposeTextures);\n }\n}\n/**\n * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.\n */\nPBRBaseMaterial.PBRMATERIAL_OPAQUE = Material.MATERIAL_OPAQUE;\n/**\n * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.\n */\nPBRBaseMaterial.PBRMATERIAL_ALPHATEST = Material.MATERIAL_ALPHATEST;\n/**\n * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.\n */\nPBRBaseMaterial.PBRMATERIAL_ALPHABLEND = Material.MATERIAL_ALPHABLEND;\n/**\n * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.\n * They are also discarded below the alpha cutoff threshold to improve performances.\n */\nPBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND = Material.MATERIAL_ALPHATESTANDBLEND;\n/**\n * Defines the default value of how much AO map is occluding the analytical lights\n * (point spot...).\n */\nPBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 0;\n/**\n * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.\n */\nPBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;\n/**\n * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document\n * to enhance interoperability with other engines.\n */\nPBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;\n/**\n * PBRMaterialLightFalloff Standard: light is falling off like in the standard material\n * to enhance interoperability with other materials.\n */\nPBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;\n__decorate([\n serializeAsImageProcessingConfiguration()\n], PBRBaseMaterial.prototype, \"_imageProcessingConfiguration\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsMiscDirty\")\n], PBRBaseMaterial.prototype, \"debugMode\", void 0);\n__decorate([\n serialize()\n], PBRBaseMaterial.prototype, \"useLogarithmicDepth\", null);\n//# sourceMappingURL=pbrBaseMaterial.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize, SerializationHelper, serializeAsColor3, expandToProperty, serializeAsTexture } from \"../../Misc/decorators.js\";\nimport { GetEnvironmentBRDFTexture } from \"../../Misc/brdfTextureTools.js\";\nimport { Color3 } from \"../../Maths/math.color.js\";\nimport { PBRBaseMaterial } from \"./pbrBaseMaterial.js\";\nimport { RegisterClass } from \"../../Misc/typeStore.js\";\nimport { Material } from \"../material.js\";\n/**\n * The Physically based material of BJS.\n *\n * This offers the main features of a standard PBR material.\n * For more information, please refer to the documentation :\n * https://doc.babylonjs.com/features/featuresDeepDive/materials/using/introToPBR\n */\nexport class PBRMaterial extends PBRBaseMaterial {\n /**\n * Stores the refracted light information in a texture.\n */\n get refractionTexture() {\n return this.subSurface.refractionTexture;\n }\n set refractionTexture(value) {\n this.subSurface.refractionTexture = value;\n if (value) {\n this.subSurface.isRefractionEnabled = true;\n }\n else if (!this.subSurface.linkRefractionWithTransparency) {\n this.subSurface.isRefractionEnabled = false;\n }\n }\n /**\n * Index of refraction of the material base layer.\n * https://en.wikipedia.org/wiki/List_of_refractive_indices\n *\n * This does not only impact refraction but also the Base F0 of Dielectric Materials.\n *\n * From dielectric fresnel rules: F0 = square((iorT - iorI) / (iorT + iorI))\n */\n get indexOfRefraction() {\n return this.subSurface.indexOfRefraction;\n }\n set indexOfRefraction(value) {\n this.subSurface.indexOfRefraction = value;\n }\n /**\n * Controls if refraction needs to be inverted on Y. This could be useful for procedural texture.\n */\n get invertRefractionY() {\n return this.subSurface.invertRefractionY;\n }\n set invertRefractionY(value) {\n this.subSurface.invertRefractionY = value;\n }\n /**\n * This parameters will make the material used its opacity to control how much it is refracting against not.\n * Materials half opaque for instance using refraction could benefit from this control.\n */\n get linkRefractionWithTransparency() {\n return this.subSurface.linkRefractionWithTransparency;\n }\n set linkRefractionWithTransparency(value) {\n this.subSurface.linkRefractionWithTransparency = value;\n if (value) {\n this.subSurface.isRefractionEnabled = true;\n }\n }\n /**\n * BJS is using an hardcoded light falloff based on a manually sets up range.\n * In PBR, one way to represents the falloff is to use the inverse squared root algorithm.\n * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.\n */\n get usePhysicalLightFalloff() {\n return this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;\n }\n /**\n * BJS is using an hardcoded light falloff based on a manually sets up range.\n * In PBR, one way to represents the falloff is to use the inverse squared root algorithm.\n * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.\n */\n set usePhysicalLightFalloff(value) {\n if (value !== this.usePhysicalLightFalloff) {\n // Ensure the effect will be rebuilt.\n this._markAllSubMeshesAsTexturesDirty();\n if (value) {\n this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;\n }\n else {\n this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_STANDARD;\n }\n }\n }\n /**\n * In order to support the falloff compatibility with gltf, a special mode has been added\n * to reproduce the gltf light falloff.\n */\n get useGLTFLightFalloff() {\n return this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF;\n }\n /**\n * In order to support the falloff compatibility with gltf, a special mode has been added\n * to reproduce the gltf light falloff.\n */\n set useGLTFLightFalloff(value) {\n if (value !== this.useGLTFLightFalloff) {\n // Ensure the effect will be rebuilt.\n this._markAllSubMeshesAsTexturesDirty();\n if (value) {\n this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_GLTF;\n }\n else {\n this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_STANDARD;\n }\n }\n }\n /**\n * Gets the image processing configuration used either in this material.\n */\n get imageProcessingConfiguration() {\n return this._imageProcessingConfiguration;\n }\n /**\n * Sets the Default image processing configuration used either in the this material.\n *\n * If sets to null, the scene one is in use.\n */\n set imageProcessingConfiguration(value) {\n this._attachImageProcessingConfiguration(value);\n // Ensure the effect will be rebuilt.\n this._markAllSubMeshesAsTexturesDirty();\n }\n /**\n * Gets whether the color curves effect is enabled.\n */\n get cameraColorCurvesEnabled() {\n return this.imageProcessingConfiguration.colorCurvesEnabled;\n }\n /**\n * Sets whether the color curves effect is enabled.\n */\n set cameraColorCurvesEnabled(value) {\n this.imageProcessingConfiguration.colorCurvesEnabled = value;\n }\n /**\n * Gets whether the color grading effect is enabled.\n */\n get cameraColorGradingEnabled() {\n return this.imageProcessingConfiguration.colorGradingEnabled;\n }\n /**\n * Gets whether the color grading effect is enabled.\n */\n set cameraColorGradingEnabled(value) {\n this.imageProcessingConfiguration.colorGradingEnabled = value;\n }\n /**\n * Gets whether tonemapping is enabled or not.\n */\n get cameraToneMappingEnabled() {\n return this._imageProcessingConfiguration.toneMappingEnabled;\n }\n /**\n * Sets whether tonemapping is enabled or not\n */\n set cameraToneMappingEnabled(value) {\n this._imageProcessingConfiguration.toneMappingEnabled = value;\n }\n /**\n * The camera exposure used on this material.\n * This property is here and not in the camera to allow controlling exposure without full screen post process.\n * This corresponds to a photographic exposure.\n */\n get cameraExposure() {\n return this._imageProcessingConfiguration.exposure;\n }\n /**\n * The camera exposure used on this material.\n * This property is here and not in the camera to allow controlling exposure without full screen post process.\n * This corresponds to a photographic exposure.\n */\n set cameraExposure(value) {\n this._imageProcessingConfiguration.exposure = value;\n }\n /**\n * Gets The camera contrast used on this material.\n */\n get cameraContrast() {\n return this._imageProcessingConfiguration.contrast;\n }\n /**\n * Sets The camera contrast used on this material.\n */\n set cameraContrast(value) {\n this._imageProcessingConfiguration.contrast = value;\n }\n /**\n * Gets the Color Grading 2D Lookup Texture.\n */\n get cameraColorGradingTexture() {\n return this._imageProcessingConfiguration.colorGradingTexture;\n }\n /**\n * Sets the Color Grading 2D Lookup Texture.\n */\n set cameraColorGradingTexture(value) {\n this._imageProcessingConfiguration.colorGradingTexture = value;\n }\n /**\n * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\n get cameraColorCurves() {\n return this._imageProcessingConfiguration.colorCurves;\n }\n /**\n * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\n set cameraColorCurves(value) {\n this._imageProcessingConfiguration.colorCurves = value;\n }\n /**\n * Instantiates a new PBRMaterial instance.\n *\n * @param name The material name\n * @param scene The scene the material will be use in.\n */\n constructor(name, scene) {\n super(name, scene);\n /**\n * Intensity of the direct lights e.g. the four lights available in your scene.\n * This impacts both the direct diffuse and specular highlights.\n */\n this.directIntensity = 1.0;\n /**\n * Intensity of the emissive part of the material.\n * This helps controlling the emissive effect without modifying the emissive color.\n */\n this.emissiveIntensity = 1.0;\n /**\n * Intensity of the environment e.g. how much the environment will light the object\n * either through harmonics for rough material or through the reflection for shiny ones.\n */\n this.environmentIntensity = 1.0;\n /**\n * This is a special control allowing the reduction of the specular highlights coming from the\n * four lights of the scene. Those highlights may not be needed in full environment lighting.\n */\n this.specularIntensity = 1.0;\n /**\n * Debug Control allowing disabling the bump map on this material.\n */\n this.disableBumpMap = false;\n /**\n * AKA Occlusion Texture Intensity in other nomenclature.\n */\n this.ambientTextureStrength = 1.0;\n /**\n * Defines how much the AO map is occluding the analytical lights (point spot...).\n * 1 means it completely occludes it\n * 0 mean it has no impact\n */\n this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;\n /**\n * In metallic workflow, specifies an F0 factor to help configuring the material F0.\n * By default the indexOfrefraction is used to compute F0;\n *\n * This is used as a factor against the default reflectance at normal incidence to tweak it.\n *\n * F0 = defaultF0 * metallicF0Factor * metallicReflectanceColor;\n * F90 = metallicReflectanceColor;\n */\n this.metallicF0Factor = 1;\n /**\n * In metallic workflow, specifies an F90 color to help configuring the material F90.\n * By default the F90 is always 1;\n *\n * Please note that this factor is also used as a factor against the default reflectance at normal incidence.\n *\n * F0 = defaultF0 * metallicF0Factor * metallicReflectanceColor\n * F90 = metallicReflectanceColor;\n */\n this.metallicReflectanceColor = Color3.White();\n /**\n * Specifies that only the A channel from metallicReflectanceTexture should be used.\n * If false, both RGB and A channels will be used\n */\n this.useOnlyMetallicFromMetallicReflectanceTexture = false;\n /**\n * The color of a material in ambient lighting.\n */\n this.ambientColor = new Color3(0, 0, 0);\n /**\n * AKA Diffuse Color in other nomenclature.\n */\n this.albedoColor = new Color3(1, 1, 1);\n /**\n * AKA Specular Color in other nomenclature.\n */\n this.reflectivityColor = new Color3(1, 1, 1);\n /**\n * The color reflected from the material.\n */\n this.reflectionColor = new Color3(1.0, 1.0, 1.0);\n /**\n * The color emitted from the material.\n */\n this.emissiveColor = new Color3(0, 0, 0);\n /**\n * AKA Glossiness in other nomenclature.\n */\n this.microSurface = 1.0;\n /**\n * If true, the light map contains occlusion information instead of lighting info.\n */\n this.useLightmapAsShadowmap = false;\n /**\n * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.\n */\n this.useAlphaFromAlbedoTexture = false;\n /**\n * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.\n */\n this.forceAlphaTest = false;\n /**\n * Defines the alpha limits in alpha test mode.\n */\n this.alphaCutOff = 0.4;\n /**\n * Specifies that the material will keep the specular highlights over a transparent surface (only the most luminous ones).\n * A car glass is a good example of that. When sun reflects on it you can not see what is behind.\n */\n this.useSpecularOverAlpha = true;\n /**\n * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.\n */\n this.useMicroSurfaceFromReflectivityMapAlpha = false;\n /**\n * Specifies if the metallic texture contains the roughness information in its alpha channel.\n */\n this.useRoughnessFromMetallicTextureAlpha = true;\n /**\n * Specifies if the metallic texture contains the roughness information in its green channel.\n */\n this.useRoughnessFromMetallicTextureGreen = false;\n /**\n * Specifies if the metallic texture contains the metallness information in its blue channel.\n */\n this.useMetallnessFromMetallicTextureBlue = false;\n /**\n * Specifies if the metallic texture contains the ambient occlusion information in its red channel.\n */\n this.useAmbientOcclusionFromMetallicTextureRed = false;\n /**\n * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.\n */\n this.useAmbientInGrayScale = false;\n /**\n * In case the reflectivity map does not contain the microsurface information in its alpha channel,\n * The material will try to infer what glossiness each pixel should be.\n */\n this.useAutoMicroSurfaceFromReflectivityMap = false;\n /**\n * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most luminous ones).\n * A car glass is a good example of that. When the street lights reflects on it you can not see what is behind.\n */\n this.useRadianceOverAlpha = true;\n /**\n * Allows using an object space normal map (instead of tangent space).\n */\n this.useObjectSpaceNormalMap = false;\n /**\n * Allows using the bump map in parallax mode.\n */\n this.useParallax = false;\n /**\n * Allows using the bump map in parallax occlusion mode.\n */\n this.useParallaxOcclusion = false;\n /**\n * Controls the scale bias of the parallax mode.\n */\n this.parallaxScaleBias = 0.05;\n /**\n * If sets to true, disables all the lights affecting the material.\n */\n this.disableLighting = false;\n /**\n * Force the shader to compute irradiance in the fragment shader in order to take bump in account.\n */\n this.forceIrradianceInFragment = false;\n /**\n * Number of Simultaneous lights allowed on the material.\n */\n this.maxSimultaneousLights = 4;\n /**\n * If sets to true, x component of normal map value will invert (x = 1.0 - x).\n */\n this.invertNormalMapX = false;\n /**\n * If sets to true, y component of normal map value will invert (y = 1.0 - y).\n */\n this.invertNormalMapY = false;\n /**\n * If sets to true and backfaceCulling is false, normals will be flipped on the backside.\n */\n this.twoSidedLighting = false;\n /**\n * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.\n * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)\n */\n this.useAlphaFresnel = false;\n /**\n * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.\n * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)\n */\n this.useLinearAlphaFresnel = false;\n /**\n * Let user defines the brdf lookup texture used for IBL.\n * A default 8bit version is embedded but you could point at :\n * * Default texture: https://assets.babylonjs.com/environments/correlatedMSBRDF_RGBD.png\n * * Default 16bit pixel depth texture: https://assets.babylonjs.com/environments/correlatedMSBRDF.dds\n * * LEGACY Default None correlated https://assets.babylonjs.com/environments/uncorrelatedBRDF_RGBD.png\n * * LEGACY Default None correlated 16bit pixel depth https://assets.babylonjs.com/environments/uncorrelatedBRDF.dds\n */\n this.environmentBRDFTexture = null;\n /**\n * Force normal to face away from face.\n */\n this.forceNormalForward = false;\n /**\n * Enables specular anti aliasing in the PBR shader.\n * It will both interacts on the Geometry for analytical and IBL lighting.\n * It also prefilter the roughness map based on the bump values.\n */\n this.enableSpecularAntiAliasing = false;\n /**\n * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal\n * makes the reflect vector face the model (under horizon).\n */\n this.useHorizonOcclusion = true;\n /**\n * This parameters will enable/disable radiance occlusion by preventing the radiance to lit\n * too much the area relying on ambient texture to define their ambient occlusion.\n */\n this.useRadianceOcclusion = true;\n /**\n * If set to true, no lighting calculations will be applied.\n */\n this.unlit = false;\n this._environmentBRDFTexture = GetEnvironmentBRDFTexture(this.getScene());\n }\n /**\n * Returns the name of this material class.\n */\n getClassName() {\n return \"PBRMaterial\";\n }\n /**\n * Makes a duplicate of the current material.\n * @param name - name to use for the new material.\n * @param cloneTexturesOnlyOnce - if a texture is used in more than one channel (e.g diffuse and opacity), only clone it once and reuse it on the other channels. Default false.\n * @param rootUrl defines the root URL to use to load textures\n */\n clone(name, cloneTexturesOnlyOnce = true, rootUrl = \"\") {\n const clone = SerializationHelper.Clone(() => new PBRMaterial(name, this.getScene()), this, { cloneTexturesOnlyOnce });\n clone.id = name;\n clone.name = name;\n this.stencil.copyTo(clone.stencil);\n this._clonePlugins(clone, rootUrl);\n return clone;\n }\n /**\n * Serializes this PBR Material.\n * @returns - An object with the serialized material.\n */\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.customType = \"BABYLON.PBRMaterial\";\n return serializationObject;\n }\n // Statics\n /**\n * Parses a PBR Material from a serialized object.\n * @param source - Serialized object.\n * @param scene - BJS scene instance.\n * @param rootUrl - url for the scene object\n * @returns - PBRMaterial\n */\n static Parse(source, scene, rootUrl) {\n const material = SerializationHelper.Parse(() => new PBRMaterial(source.name, scene), source, scene, rootUrl);\n if (source.stencil) {\n material.stencil.parse(source.stencil, scene, rootUrl);\n }\n Material._parsePlugins(source, material, scene, rootUrl);\n // The code block below ensures backward compatibility with serialized materials before plugins are automatically serialized.\n if (source.clearCoat) {\n material.clearCoat.parse(source.clearCoat, scene, rootUrl);\n }\n if (source.anisotropy) {\n material.anisotropy.parse(source.anisotropy, scene, rootUrl);\n }\n if (source.brdf) {\n material.brdf.parse(source.brdf, scene, rootUrl);\n }\n if (source.sheen) {\n material.sheen.parse(source.sheen, scene, rootUrl);\n }\n if (source.subSurface) {\n material.subSurface.parse(source.subSurface, scene, rootUrl);\n }\n if (source.iridescence) {\n material.iridescence.parse(source.iridescence, scene, rootUrl);\n }\n return material;\n }\n}\n/**\n * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.\n */\nPBRMaterial.PBRMATERIAL_OPAQUE = PBRBaseMaterial.PBRMATERIAL_OPAQUE;\n/**\n * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.\n */\nPBRMaterial.PBRMATERIAL_ALPHATEST = PBRBaseMaterial.PBRMATERIAL_ALPHATEST;\n/**\n * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.\n */\nPBRMaterial.PBRMATERIAL_ALPHABLEND = PBRBaseMaterial.PBRMATERIAL_ALPHABLEND;\n/**\n * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.\n * They are also discarded below the alpha cutoff threshold to improve performances.\n */\nPBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = PBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND;\n/**\n * Defines the default value of how much AO map is occluding the analytical lights\n * (point spot...).\n */\nPBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"directIntensity\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"emissiveIntensity\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"environmentIntensity\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"specularIntensity\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"disableBumpMap\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"albedoTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"ambientTexture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"ambientTextureStrength\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"ambientTextureImpactOnAnalyticalLights\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesAndMiscDirty\")\n], PBRMaterial.prototype, \"opacityTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"reflectionTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"emissiveTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"reflectivityTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"metallicTexture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"metallic\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"roughness\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"metallicF0Factor\", void 0);\n__decorate([\n serializeAsColor3(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"metallicReflectanceColor\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useOnlyMetallicFromMetallicReflectanceTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"metallicReflectanceTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"reflectanceTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"microSurfaceTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"bumpTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", null)\n], PBRMaterial.prototype, \"lightmapTexture\", void 0);\n__decorate([\n serializeAsColor3(\"ambient\"),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"ambientColor\", void 0);\n__decorate([\n serializeAsColor3(\"albedo\"),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"albedoColor\", void 0);\n__decorate([\n serializeAsColor3(\"reflectivity\"),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"reflectivityColor\", void 0);\n__decorate([\n serializeAsColor3(\"reflection\"),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"reflectionColor\", void 0);\n__decorate([\n serializeAsColor3(\"emissive\"),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"emissiveColor\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"microSurface\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useLightmapAsShadowmap\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesAndMiscDirty\")\n], PBRMaterial.prototype, \"useAlphaFromAlbedoTexture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesAndMiscDirty\")\n], PBRMaterial.prototype, \"forceAlphaTest\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesAndMiscDirty\")\n], PBRMaterial.prototype, \"alphaCutOff\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useSpecularOverAlpha\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useMicroSurfaceFromReflectivityMapAlpha\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useRoughnessFromMetallicTextureAlpha\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useRoughnessFromMetallicTextureGreen\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useMetallnessFromMetallicTextureBlue\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useAmbientOcclusionFromMetallicTextureRed\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useAmbientInGrayScale\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useAutoMicroSurfaceFromReflectivityMap\", void 0);\n__decorate([\n serialize()\n], PBRMaterial.prototype, \"usePhysicalLightFalloff\", null);\n__decorate([\n serialize()\n], PBRMaterial.prototype, \"useGLTFLightFalloff\", null);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useRadianceOverAlpha\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useObjectSpaceNormalMap\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useParallax\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useParallaxOcclusion\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"parallaxScaleBias\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n], PBRMaterial.prototype, \"disableLighting\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"forceIrradianceInFragment\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n], PBRMaterial.prototype, \"maxSimultaneousLights\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"invertNormalMapX\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"invertNormalMapY\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"twoSidedLighting\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useAlphaFresnel\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useLinearAlphaFresnel\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"environmentBRDFTexture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"forceNormalForward\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"enableSpecularAntiAliasing\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useHorizonOcclusion\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useRadianceOcclusion\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsMiscDirty\")\n], PBRMaterial.prototype, \"unlit\", void 0);\nRegisterClass(\"BABYLON.PBRMaterial\", PBRMaterial);\n//# sourceMappingURL=pbrMaterial.js.map","/* eslint-disable @typescript-eslint/naming-convention */\nimport { Scalar } from \"../Maths/math.scalar.js\";\nimport { SphericalPolynomial } from \"../Maths/sphericalPolynomial.js\";\n\nimport { InternalTexture, InternalTextureSource } from \"../Materials/Textures/internalTexture.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { CubeMapToSphericalPolynomialTools } from \"../Misc/HighDynamicRange/cubemapToSphericalPolynomial.js\";\nimport { BaseTexture } from \"../Materials/Textures/baseTexture.js\";\nimport { ThinEngine } from \"../Engines/thinEngine.js\";\nimport { FromHalfFloat, ToHalfFloat } from \"./textureTools.js\";\nimport \"../Engines/Extensions/engine.cubeTexture.js\";\n// Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html\n// All values and structures referenced from:\n// http://msdn.microsoft.com/en-us/library/bb943991.aspx/\nconst DDS_MAGIC = 0x20534444;\nconst //DDSD_CAPS = 0x1,\n//DDSD_HEIGHT = 0x2,\n//DDSD_WIDTH = 0x4,\n//DDSD_PITCH = 0x8,\n//DDSD_PIXELFORMAT = 0x1000,\nDDSD_MIPMAPCOUNT = 0x20000;\n//DDSD_LINEARSIZE = 0x80000,\n//DDSD_DEPTH = 0x800000;\n// var DDSCAPS_COMPLEX = 0x8,\n// DDSCAPS_MIPMAP = 0x400000,\n// DDSCAPS_TEXTURE = 0x1000;\nconst DDSCAPS2_CUBEMAP = 0x200;\n// DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,\n// DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,\n// DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,\n// DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,\n// DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,\n// DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,\n// DDSCAPS2_VOLUME = 0x200000;\nconst //DDPF_ALPHAPIXELS = 0x1,\n//DDPF_ALPHA = 0x2,\nDDPF_FOURCC = 0x4, DDPF_RGB = 0x40, \n//DDPF_YUV = 0x200,\nDDPF_LUMINANCE = 0x20000;\nfunction FourCCToInt32(value) {\n return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);\n}\nfunction Int32ToFourCC(value) {\n return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);\n}\nconst FOURCC_DXT1 = FourCCToInt32(\"DXT1\");\nconst FOURCC_DXT3 = FourCCToInt32(\"DXT3\");\nconst FOURCC_DXT5 = FourCCToInt32(\"DXT5\");\nconst FOURCC_DX10 = FourCCToInt32(\"DX10\");\nconst FOURCC_D3DFMT_R16G16B16A16F = 113;\nconst FOURCC_D3DFMT_R32G32B32A32F = 116;\nconst DXGI_FORMAT_R32G32B32A32_FLOAT = 2;\nconst DXGI_FORMAT_R16G16B16A16_FLOAT = 10;\nconst DXGI_FORMAT_B8G8R8X8_UNORM = 88;\nconst headerLengthInt = 31; // The header length in 32 bit ints\n// Offsets into the header array\nconst off_magic = 0;\nconst off_size = 1;\nconst off_flags = 2;\nconst off_height = 3;\nconst off_width = 4;\nconst off_mipmapCount = 7;\nconst off_pfFlags = 20;\nconst off_pfFourCC = 21;\nconst off_RGBbpp = 22;\nconst off_RMask = 23;\nconst off_GMask = 24;\nconst off_BMask = 25;\nconst off_AMask = 26;\n// var off_caps1 = 27;\nconst off_caps2 = 28;\n// var off_caps3 = 29;\n// var off_caps4 = 30;\nconst off_dxgiFormat = 32;\n/**\n * Class used to provide DDS decompression tools\n */\nexport class DDSTools {\n /**\n * Gets DDS information from an array buffer\n * @param data defines the array buffer view to read data from\n * @returns the DDS information\n */\n static GetDDSInfo(data) {\n const header = new Int32Array(data.buffer, data.byteOffset, headerLengthInt);\n const extendedHeader = new Int32Array(data.buffer, data.byteOffset, headerLengthInt + 4);\n let mipmapCount = 1;\n if (header[off_flags] & DDSD_MIPMAPCOUNT) {\n mipmapCount = Math.max(1, header[off_mipmapCount]);\n }\n const fourCC = header[off_pfFourCC];\n const dxgiFormat = fourCC === FOURCC_DX10 ? extendedHeader[off_dxgiFormat] : 0;\n let textureType = 0;\n switch (fourCC) {\n case FOURCC_D3DFMT_R16G16B16A16F:\n textureType = 2;\n break;\n case FOURCC_D3DFMT_R32G32B32A32F:\n textureType = 1;\n break;\n case FOURCC_DX10:\n if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {\n textureType = 2;\n break;\n }\n if (dxgiFormat === DXGI_FORMAT_R32G32B32A32_FLOAT) {\n textureType = 1;\n break;\n }\n }\n return {\n width: header[off_width],\n height: header[off_height],\n mipmapCount: mipmapCount,\n isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,\n isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,\n isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,\n isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,\n isCompressed: fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5,\n dxgiFormat: dxgiFormat,\n textureType: textureType,\n };\n }\n static _GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) {\n const destArray = new Float32Array(dataLength);\n const srcData = new Uint16Array(arrayBuffer, dataOffset);\n let index = 0;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const srcPos = (x + y * width) * 4;\n destArray[index] = FromHalfFloat(srcData[srcPos]);\n destArray[index + 1] = FromHalfFloat(srcData[srcPos + 1]);\n destArray[index + 2] = FromHalfFloat(srcData[srcPos + 2]);\n if (DDSTools.StoreLODInAlphaChannel) {\n destArray[index + 3] = lod;\n }\n else {\n destArray[index + 3] = FromHalfFloat(srcData[srcPos + 3]);\n }\n index += 4;\n }\n }\n return destArray;\n }\n static _GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) {\n if (DDSTools.StoreLODInAlphaChannel) {\n const destArray = new Uint16Array(dataLength);\n const srcData = new Uint16Array(arrayBuffer, dataOffset);\n let index = 0;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const srcPos = (x + y * width) * 4;\n destArray[index] = srcData[srcPos];\n destArray[index + 1] = srcData[srcPos + 1];\n destArray[index + 2] = srcData[srcPos + 2];\n destArray[index + 3] = ToHalfFloat(lod);\n index += 4;\n }\n }\n return destArray;\n }\n return new Uint16Array(arrayBuffer, dataOffset, dataLength);\n }\n static _GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) {\n if (DDSTools.StoreLODInAlphaChannel) {\n const destArray = new Float32Array(dataLength);\n const srcData = new Float32Array(arrayBuffer, dataOffset);\n let index = 0;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const srcPos = (x + y * width) * 4;\n destArray[index] = srcData[srcPos];\n destArray[index + 1] = srcData[srcPos + 1];\n destArray[index + 2] = srcData[srcPos + 2];\n destArray[index + 3] = lod;\n index += 4;\n }\n }\n return destArray;\n }\n return new Float32Array(arrayBuffer, dataOffset, dataLength);\n }\n static _GetFloatAsHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) {\n const destArray = new Uint16Array(dataLength);\n const srcData = new Float32Array(arrayBuffer, dataOffset);\n let index = 0;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n destArray[index] = ToHalfFloat(srcData[index]);\n destArray[index + 1] = ToHalfFloat(srcData[index + 1]);\n destArray[index + 2] = ToHalfFloat(srcData[index + 2]);\n if (DDSTools.StoreLODInAlphaChannel) {\n destArray[index + 3] = ToHalfFloat(lod);\n }\n else {\n destArray[index + 3] = ToHalfFloat(srcData[index + 3]);\n }\n index += 4;\n }\n }\n return destArray;\n }\n static _GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) {\n const destArray = new Uint8Array(dataLength);\n const srcData = new Float32Array(arrayBuffer, dataOffset);\n let index = 0;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const srcPos = (x + y * width) * 4;\n destArray[index] = Scalar.Clamp(srcData[srcPos]) * 255;\n destArray[index + 1] = Scalar.Clamp(srcData[srcPos + 1]) * 255;\n destArray[index + 2] = Scalar.Clamp(srcData[srcPos + 2]) * 255;\n if (DDSTools.StoreLODInAlphaChannel) {\n destArray[index + 3] = lod;\n }\n else {\n destArray[index + 3] = Scalar.Clamp(srcData[srcPos + 3]) * 255;\n }\n index += 4;\n }\n }\n return destArray;\n }\n static _GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) {\n const destArray = new Uint8Array(dataLength);\n const srcData = new Uint16Array(arrayBuffer, dataOffset);\n let index = 0;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const srcPos = (x + y * width) * 4;\n destArray[index] = Scalar.Clamp(FromHalfFloat(srcData[srcPos])) * 255;\n destArray[index + 1] = Scalar.Clamp(FromHalfFloat(srcData[srcPos + 1])) * 255;\n destArray[index + 2] = Scalar.Clamp(FromHalfFloat(srcData[srcPos + 2])) * 255;\n if (DDSTools.StoreLODInAlphaChannel) {\n destArray[index + 3] = lod;\n }\n else {\n destArray[index + 3] = Scalar.Clamp(FromHalfFloat(srcData[srcPos + 3])) * 255;\n }\n index += 4;\n }\n }\n return destArray;\n }\n static _GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {\n const byteArray = new Uint8Array(dataLength);\n const srcData = new Uint8Array(arrayBuffer, dataOffset);\n let index = 0;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const srcPos = (x + y * width) * 4;\n byteArray[index] = srcData[srcPos + rOffset];\n byteArray[index + 1] = srcData[srcPos + gOffset];\n byteArray[index + 2] = srcData[srcPos + bOffset];\n byteArray[index + 3] = srcData[srcPos + aOffset];\n index += 4;\n }\n }\n return byteArray;\n }\n static _ExtractLongWordOrder(value) {\n if (value === 0 || value === 255 || value === -16777216) {\n return 0;\n }\n return 1 + DDSTools._ExtractLongWordOrder(value >> 8);\n }\n static _GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {\n const byteArray = new Uint8Array(dataLength);\n const srcData = new Uint8Array(arrayBuffer, dataOffset);\n let index = 0;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const srcPos = (x + y * width) * 3;\n byteArray[index] = srcData[srcPos + rOffset];\n byteArray[index + 1] = srcData[srcPos + gOffset];\n byteArray[index + 2] = srcData[srcPos + bOffset];\n index += 3;\n }\n }\n return byteArray;\n }\n static _GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer) {\n const byteArray = new Uint8Array(dataLength);\n const srcData = new Uint8Array(arrayBuffer, dataOffset);\n let index = 0;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const srcPos = x + y * width;\n byteArray[index] = srcData[srcPos];\n index++;\n }\n }\n return byteArray;\n }\n /**\n * Uploads DDS Levels to a Babylon Texture\n * @internal\n */\n static UploadDDSLevels(engine, texture, data, info, loadMipmaps, faces, lodIndex = -1, currentFace, destTypeMustBeFilterable = true) {\n let sphericalPolynomialFaces = null;\n if (info.sphericalPolynomial) {\n sphericalPolynomialFaces = new Array();\n }\n const ext = !!engine.getCaps().s3tc;\n // TODO WEBGPU Once generateMipMaps is split into generateMipMaps + hasMipMaps in InternalTexture this line can be removed\n texture.generateMipMaps = loadMipmaps;\n const header = new Int32Array(data.buffer, data.byteOffset, headerLengthInt);\n let fourCC, width, height, dataLength = 0, dataOffset;\n let byteArray, mipmapCount, mip;\n let internalCompressedFormat = 0;\n let blockBytes = 1;\n if (header[off_magic] !== DDS_MAGIC) {\n Logger.Error(\"Invalid magic number in DDS header\");\n return;\n }\n if (!info.isFourCC && !info.isRGB && !info.isLuminance) {\n Logger.Error(\"Unsupported format, must contain a FourCC, RGB or LUMINANCE code\");\n return;\n }\n if (info.isCompressed && !ext) {\n Logger.Error(\"Compressed textures are not supported on this platform.\");\n return;\n }\n let bpp = header[off_RGBbpp];\n dataOffset = header[off_size] + 4;\n let computeFormats = false;\n if (info.isFourCC) {\n fourCC = header[off_pfFourCC];\n switch (fourCC) {\n case FOURCC_DXT1:\n blockBytes = 8;\n internalCompressedFormat = 33777;\n break;\n case FOURCC_DXT3:\n blockBytes = 16;\n internalCompressedFormat = 33778;\n break;\n case FOURCC_DXT5:\n blockBytes = 16;\n internalCompressedFormat = 33779;\n break;\n case FOURCC_D3DFMT_R16G16B16A16F:\n computeFormats = true;\n bpp = 64;\n break;\n case FOURCC_D3DFMT_R32G32B32A32F:\n computeFormats = true;\n bpp = 128;\n break;\n case FOURCC_DX10: {\n // There is an additionnal header so dataOffset need to be changed\n dataOffset += 5 * 4; // 5 uints\n let supported = false;\n switch (info.dxgiFormat) {\n case DXGI_FORMAT_R16G16B16A16_FLOAT:\n computeFormats = true;\n bpp = 64;\n supported = true;\n break;\n case DXGI_FORMAT_R32G32B32A32_FLOAT:\n computeFormats = true;\n bpp = 128;\n supported = true;\n break;\n case DXGI_FORMAT_B8G8R8X8_UNORM:\n info.isRGB = true;\n info.isFourCC = false;\n bpp = 32;\n supported = true;\n break;\n }\n if (supported) {\n break;\n }\n }\n // eslint-disable-next-line no-fallthrough\n default:\n console.error(\"Unsupported FourCC code:\", Int32ToFourCC(fourCC));\n return;\n }\n }\n const rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);\n const gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);\n const bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);\n const aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);\n if (computeFormats) {\n internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);\n }\n mipmapCount = 1;\n if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {\n mipmapCount = Math.max(1, header[off_mipmapCount]);\n }\n const startFace = currentFace || 0;\n const caps = engine.getCaps();\n for (let face = startFace; face < faces; face++) {\n width = header[off_width];\n height = header[off_height];\n for (mip = 0; mip < mipmapCount; ++mip) {\n if (lodIndex === -1 || lodIndex === mip) {\n // In case of fixed LOD, if the lod has just been uploaded, early exit.\n const i = lodIndex === -1 ? mip : 0;\n if (!info.isCompressed && info.isFourCC) {\n texture.format = 5;\n dataLength = width * height * 4;\n let floatArray = null;\n if (engine._badOS || engine._badDesktopOS || (!caps.textureHalfFloat && !caps.textureFloat)) {\n // Required because iOS has many issues with float and half float generation\n if (bpp === 128) {\n floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i);\n if (sphericalPolynomialFaces && i == 0) {\n sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i));\n }\n }\n else if (bpp === 64) {\n floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i);\n if (sphericalPolynomialFaces && i == 0) {\n sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i));\n }\n }\n texture.type = 0;\n }\n else {\n const floatAvailable = caps.textureFloat && ((destTypeMustBeFilterable && caps.textureFloatLinearFiltering) || !destTypeMustBeFilterable);\n const halfFloatAvailable = caps.textureHalfFloat && ((destTypeMustBeFilterable && caps.textureHalfFloatLinearFiltering) || !destTypeMustBeFilterable);\n const destType = (bpp === 128 || (bpp === 64 && !halfFloatAvailable)) && floatAvailable\n ? 1\n : (bpp === 64 || (bpp === 128 && !floatAvailable)) && halfFloatAvailable\n ? 2\n : 0;\n let dataGetter;\n let dataGetterPolynomial = null;\n switch (bpp) {\n case 128: {\n switch (destType) {\n case 1:\n dataGetter = DDSTools._GetFloatRGBAArrayBuffer;\n dataGetterPolynomial = null;\n break;\n case 2:\n dataGetter = DDSTools._GetFloatAsHalfFloatRGBAArrayBuffer;\n dataGetterPolynomial = DDSTools._GetFloatRGBAArrayBuffer;\n break;\n case 0:\n dataGetter = DDSTools._GetFloatAsUIntRGBAArrayBuffer;\n dataGetterPolynomial = DDSTools._GetFloatRGBAArrayBuffer;\n break;\n }\n break;\n }\n default: {\n // 64 bpp\n switch (destType) {\n case 1:\n dataGetter = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer;\n dataGetterPolynomial = null;\n break;\n case 2:\n dataGetter = DDSTools._GetHalfFloatRGBAArrayBuffer;\n dataGetterPolynomial = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer;\n break;\n case 0:\n dataGetter = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer;\n dataGetterPolynomial = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer;\n break;\n }\n break;\n }\n }\n texture.type = destType;\n floatArray = dataGetter(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i);\n if (sphericalPolynomialFaces && i == 0) {\n sphericalPolynomialFaces.push(dataGetterPolynomial ? dataGetterPolynomial(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i) : floatArray);\n }\n }\n if (floatArray) {\n engine._uploadDataToTextureDirectly(texture, floatArray, face, i);\n }\n }\n else if (info.isRGB) {\n texture.type = 0;\n if (bpp === 24) {\n texture.format = 4;\n dataLength = width * height * 3;\n byteArray = DDSTools._GetRGBArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, rOffset, gOffset, bOffset);\n engine._uploadDataToTextureDirectly(texture, byteArray, face, i);\n }\n else {\n // 32\n texture.format = 5;\n dataLength = width * height * 4;\n byteArray = DDSTools._GetRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, rOffset, gOffset, bOffset, aOffset);\n engine._uploadDataToTextureDirectly(texture, byteArray, face, i);\n }\n }\n else if (info.isLuminance) {\n const unpackAlignment = engine._getUnpackAlignement();\n const unpaddedRowSize = width;\n const paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;\n dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;\n byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer);\n texture.format = 1;\n texture.type = 0;\n engine._uploadDataToTextureDirectly(texture, byteArray, face, i);\n }\n else {\n dataLength = (((Math.max(4, width) / 4) * Math.max(4, height)) / 4) * blockBytes;\n byteArray = new Uint8Array(data.buffer, data.byteOffset + dataOffset, dataLength);\n texture.type = 0;\n engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);\n }\n }\n dataOffset += bpp ? width * height * (bpp / 8) : dataLength;\n width *= 0.5;\n height *= 0.5;\n width = Math.max(1.0, width);\n height = Math.max(1.0, height);\n }\n if (currentFace !== undefined) {\n // Loading a single face\n break;\n }\n }\n if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {\n info.sphericalPolynomial = CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({\n size: header[off_width],\n right: sphericalPolynomialFaces[0],\n left: sphericalPolynomialFaces[1],\n up: sphericalPolynomialFaces[2],\n down: sphericalPolynomialFaces[3],\n front: sphericalPolynomialFaces[4],\n back: sphericalPolynomialFaces[5],\n format: 5,\n type: 1,\n gammaSpace: false,\n });\n }\n else {\n info.sphericalPolynomial = undefined;\n }\n }\n}\n/**\n * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default)\n */\nDDSTools.StoreLODInAlphaChannel = false;\n/**\n * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)\n * @param rootUrl defines the url where the file to load is located\n * @param scene defines the current scene\n * @param lodScale defines scale to apply to the mip map selection\n * @param lodOffset defines offset to apply to the mip map selection\n * @param onLoad defines an optional callback raised when the texture is loaded\n * @param onError defines an optional callback raised if there is an issue to load the texture\n * @param format defines the format of the data\n * @param forcedExtension defines the extension to use to pick the right loader\n * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture\n * @returns the cube texture as an InternalTexture\n */\nThinEngine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = true) {\n const callback = (loadData) => {\n if (!loadData) {\n if (onLoad) {\n onLoad(null);\n }\n return;\n }\n const texture = loadData.texture;\n if (!createPolynomials) {\n texture._sphericalPolynomial = new SphericalPolynomial();\n }\n else if (loadData.info.sphericalPolynomial) {\n texture._sphericalPolynomial = loadData.info.sphericalPolynomial;\n }\n texture._source = InternalTextureSource.CubePrefiltered;\n if (this.getCaps().textureLOD) {\n // Do not add extra process if texture lod is supported.\n if (onLoad) {\n onLoad(texture);\n }\n return;\n }\n const mipSlices = 3;\n const gl = this._gl;\n const width = loadData.width;\n if (!width) {\n return;\n }\n const textures = [];\n for (let i = 0; i < mipSlices; i++) {\n //compute LOD from even spacing in smoothness (matching shader calculation)\n const smoothness = i / (mipSlices - 1);\n const roughness = 1 - smoothness;\n const minLODIndex = lodOffset; // roughness = 0\n const maxLODIndex = Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1\n const lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;\n const mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));\n const glTextureFromLod = new InternalTexture(this, InternalTextureSource.Temp);\n glTextureFromLod.type = texture.type;\n glTextureFromLod.format = texture.format;\n glTextureFromLod.width = Math.pow(2, Math.max(Scalar.Log2(width) - mipmapIndex, 0));\n glTextureFromLod.height = glTextureFromLod.width;\n glTextureFromLod.isCube = true;\n glTextureFromLod._cachedWrapU = 0;\n glTextureFromLod._cachedWrapV = 0;\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);\n glTextureFromLod.samplingMode = 2;\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n if (loadData.isDDS) {\n const info = loadData.info;\n const data = loadData.data;\n this._unpackFlipY(info.isCompressed);\n DDSTools.UploadDDSLevels(this, glTextureFromLod, data, info, true, 6, mipmapIndex);\n }\n else {\n Logger.Warn(\"DDS is the only prefiltered cube map supported so far.\");\n }\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n // Wrap in a base texture for easy binding.\n const lodTexture = new BaseTexture(scene);\n lodTexture._isCube = true;\n lodTexture._texture = glTextureFromLod;\n glTextureFromLod.isReady = true;\n textures.push(lodTexture);\n }\n texture._lodTextureHigh = textures[2];\n texture._lodTextureMid = textures[1];\n texture._lodTextureLow = textures[0];\n if (onLoad) {\n onLoad(texture);\n }\n };\n return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);\n};\n//# sourceMappingURL=dds.js.map","import { SphericalPolynomial } from \"../../../Maths/sphericalPolynomial.js\";\nimport { Engine } from \"../../../Engines/engine.js\";\nimport { DDSTools } from \"../../../Misc/dds.js\";\n/**\n * Implementation of the DDS Texture Loader.\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class _DDSTextureLoader {\n constructor() {\n /**\n * Defines whether the loader supports cascade loading the different faces.\n */\n this.supportCascades = true;\n }\n /**\n * This returns if the loader support the current file information.\n * @param extension defines the file extension of the file being loaded\n * @returns true if the loader can load the specified file\n */\n canLoad(extension) {\n return extension.endsWith(\".dds\");\n }\n /**\n * Uploads the cube texture data to the WebGL texture. It has already been bound.\n * @param imgs contains the cube maps\n * @param texture defines the BabylonJS internal texture\n * @param createPolynomials will be true if polynomials have been requested\n * @param onLoad defines the callback to trigger once the texture is ready\n */\n loadCubeData(imgs, texture, createPolynomials, onLoad) {\n const engine = texture.getEngine();\n let info;\n let loadMipmap = false;\n let maxLevel = 1000;\n if (Array.isArray(imgs)) {\n for (let index = 0; index < imgs.length; index++) {\n const data = imgs[index];\n info = DDSTools.GetDDSInfo(data);\n texture.width = info.width;\n texture.height = info.height;\n loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;\n engine._unpackFlipY(info.isCompressed);\n DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6, -1, index);\n if (!info.isFourCC && info.mipmapCount === 1) {\n engine.generateMipMapsForCubemap(texture);\n }\n else {\n maxLevel = info.mipmapCount - 1;\n }\n }\n }\n else {\n const data = imgs;\n info = DDSTools.GetDDSInfo(data);\n texture.width = info.width;\n texture.height = info.height;\n if (createPolynomials) {\n info.sphericalPolynomial = new SphericalPolynomial();\n }\n loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;\n engine._unpackFlipY(info.isCompressed);\n DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);\n if (!info.isFourCC && info.mipmapCount === 1) {\n // Do not unbind as we still need to set the parameters.\n engine.generateMipMapsForCubemap(texture, false);\n }\n else {\n maxLevel = info.mipmapCount - 1;\n }\n }\n engine._setCubeMapTextureParams(texture, loadMipmap, maxLevel);\n texture.isReady = true;\n texture.onLoadedObservable.notifyObservers(texture);\n texture.onLoadedObservable.clear();\n if (onLoad) {\n onLoad({ isDDS: true, width: texture.width, info, data: imgs, texture });\n }\n }\n /**\n * Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param callback defines the method to call once ready to upload\n */\n loadData(data, texture, callback) {\n const info = DDSTools.GetDDSInfo(data);\n const loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && info.width >> (info.mipmapCount - 1) === 1;\n callback(info.width, info.height, loadMipmap, info.isFourCC, () => {\n DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);\n });\n }\n}\n// Register the loader.\nEngine._TextureLoaders.push(new _DDSTextureLoader());\n//# sourceMappingURL=ddsTextureLoader.js.map","import { GetEnvInfo, UploadEnvLevelsAsync, UploadEnvSpherical } from \"../../../Misc/environmentTextureTools.js\";\nimport { Engine } from \"../../../Engines/engine.js\";\n/**\n * Implementation of the ENV Texture Loader.\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class _ENVTextureLoader {\n constructor() {\n /**\n * Defines whether the loader supports cascade loading the different faces.\n */\n this.supportCascades = false;\n }\n /**\n * This returns if the loader support the current file information.\n * @param extension defines the file extension of the file being loaded\n * @returns true if the loader can load the specified file\n */\n canLoad(extension) {\n return extension.endsWith(\".env\");\n }\n /**\n * Uploads the cube texture data to the WebGL texture. It has already been bound.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param createPolynomials will be true if polynomials have been requested\n * @param onLoad defines the callback to trigger once the texture is ready\n * @param onError defines the callback to trigger in case of error\n */\n loadCubeData(data, texture, createPolynomials, onLoad, onError) {\n if (Array.isArray(data)) {\n return;\n }\n const info = GetEnvInfo(data);\n if (info) {\n texture.width = info.width;\n texture.height = info.width;\n try {\n UploadEnvSpherical(texture, info);\n UploadEnvLevelsAsync(texture, data, info).then(() => {\n texture.isReady = true;\n texture.onLoadedObservable.notifyObservers(texture);\n texture.onLoadedObservable.clear();\n if (onLoad) {\n onLoad();\n }\n }, (reason) => {\n onError === null || onError === void 0 ? void 0 : onError(\"Can not upload environment levels\", reason);\n });\n }\n catch (e) {\n onError === null || onError === void 0 ? void 0 : onError(\"Can not upload environment file\", e);\n }\n }\n else if (onError) {\n onError(\"Can not parse the environment file\", null);\n }\n }\n /**\n * Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback.\n */\n loadData() {\n throw \".env not supported in 2d.\";\n }\n}\n// Register the loader.\nEngine._TextureLoaders.push(new _ENVTextureLoader());\n//# sourceMappingURL=envTextureLoader.js.map","/* eslint-disable @typescript-eslint/naming-convention */\nimport { Logger } from \"../Misc/logger.js\";\n/**\n * for description see https://www.khronos.org/opengles/sdk/tools/KTX/\n * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/\n */\nexport class KhronosTextureContainer {\n /**\n * Creates a new KhronosTextureContainer\n * @param data contents of the KTX container file\n * @param facesExpected should be either 1 or 6, based whether a cube texture or or\n */\n constructor(\n /** contents of the KTX container file */\n data, facesExpected) {\n this.data = data;\n /**\n * If the container has been made invalid (eg. constructor failed to correctly load array buffer)\n */\n this.isInvalid = false;\n if (!KhronosTextureContainer.IsValid(data)) {\n this.isInvalid = true;\n Logger.Error(\"texture missing KTX identifier\");\n return;\n }\n // load the reset of the header in native 32 bit uint\n const dataSize = Uint32Array.BYTES_PER_ELEMENT;\n const headerDataView = new DataView(this.data.buffer, this.data.byteOffset + 12, 13 * dataSize);\n const endianness = headerDataView.getUint32(0, true);\n const littleEndian = endianness === 0x04030201;\n this.glType = headerDataView.getUint32(1 * dataSize, littleEndian); // must be 0 for compressed textures\n this.glTypeSize = headerDataView.getUint32(2 * dataSize, littleEndian); // must be 1 for compressed textures\n this.glFormat = headerDataView.getUint32(3 * dataSize, littleEndian); // must be 0 for compressed textures\n this.glInternalFormat = headerDataView.getUint32(4 * dataSize, littleEndian); // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)\n this.glBaseInternalFormat = headerDataView.getUint32(5 * dataSize, littleEndian); // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)\n this.pixelWidth = headerDataView.getUint32(6 * dataSize, littleEndian); // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)\n this.pixelHeight = headerDataView.getUint32(7 * dataSize, littleEndian); // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)\n this.pixelDepth = headerDataView.getUint32(8 * dataSize, littleEndian); // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)\n this.numberOfArrayElements = headerDataView.getUint32(9 * dataSize, littleEndian); // used for texture arrays\n this.numberOfFaces = headerDataView.getUint32(10 * dataSize, littleEndian); // used for cubemap textures, should either be 1 or 6\n this.numberOfMipmapLevels = headerDataView.getUint32(11 * dataSize, littleEndian); // number of levels; disregard possibility of 0 for compressed textures\n this.bytesOfKeyValueData = headerDataView.getUint32(12 * dataSize, littleEndian); // the amount of space after the header for meta-data\n // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.\n if (this.glType !== 0) {\n Logger.Error(\"only compressed formats currently supported\");\n this.isInvalid = true;\n return;\n }\n else {\n // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.\n this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);\n }\n if (this.pixelHeight === 0 || this.pixelDepth !== 0) {\n Logger.Error(\"only 2D textures currently supported\");\n this.isInvalid = true;\n return;\n }\n if (this.numberOfArrayElements !== 0) {\n Logger.Error(\"texture arrays not currently supported\");\n this.isInvalid = true;\n return;\n }\n if (this.numberOfFaces !== facesExpected) {\n Logger.Error(\"number of faces expected\" + facesExpected + \", but found \" + this.numberOfFaces);\n this.isInvalid = true;\n return;\n }\n // we now have a completely validated file, so could use existence of loadType as success\n // would need to make this more elaborate & adjust checks above to support more than one load type\n this.loadType = KhronosTextureContainer.COMPRESSED_2D;\n }\n /**\n * Uploads KTX content to a Babylon Texture.\n * It is assumed that the texture has already been created & is currently bound\n * @internal\n */\n uploadLevels(texture, loadMipmaps) {\n switch (this.loadType) {\n case KhronosTextureContainer.COMPRESSED_2D:\n this._upload2DCompressedLevels(texture, loadMipmaps);\n break;\n case KhronosTextureContainer.TEX_2D:\n case KhronosTextureContainer.COMPRESSED_3D:\n case KhronosTextureContainer.TEX_3D:\n }\n }\n _upload2DCompressedLevels(texture, loadMipmaps) {\n // initialize width & height for level 1\n let dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;\n let width = this.pixelWidth;\n let height = this.pixelHeight;\n const mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;\n for (let level = 0; level < mipmapCount; level++) {\n const imageSize = new Int32Array(this.data.buffer, this.data.byteOffset + dataOffset, 1)[0]; // size per face, since not supporting array cubemaps\n dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.\n for (let face = 0; face < this.numberOfFaces; face++) {\n const byteArray = new Uint8Array(this.data.buffer, this.data.byteOffset + dataOffset, imageSize);\n const engine = texture.getEngine();\n engine._uploadCompressedDataToTextureDirectly(texture, texture.format, width, height, byteArray, face, level);\n dataOffset += imageSize; // add size of the image for the next face/mipmap\n dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image\n }\n width = Math.max(1.0, width * 0.5);\n height = Math.max(1.0, height * 0.5);\n }\n }\n /**\n * Checks if the given data starts with a KTX file identifier.\n * @param data the data to check\n * @returns true if the data is a KTX file or false otherwise\n */\n static IsValid(data) {\n if (data.byteLength >= 12) {\n // '«', 'K', 'T', 'X', ' ', '1', '1', '»', '\\r', '\\n', '\\x1A', '\\n'\n const identifier = new Uint8Array(data.buffer, data.byteOffset, 12);\n if (identifier[0] === 0xab &&\n identifier[1] === 0x4b &&\n identifier[2] === 0x54 &&\n identifier[3] === 0x58 &&\n identifier[4] === 0x20 &&\n identifier[5] === 0x31 &&\n identifier[6] === 0x31 &&\n identifier[7] === 0xbb &&\n identifier[8] === 0x0d &&\n identifier[9] === 0x0a &&\n identifier[10] === 0x1a &&\n identifier[11] === 0x0a) {\n return true;\n }\n }\n return false;\n }\n}\nKhronosTextureContainer.HEADER_LEN = 12 + 13 * 4; // identifier + header elements (not including key value meta-data pairs)\n// load types\nKhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()\nKhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()\nKhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()\nKhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()\n//# sourceMappingURL=khronosTextureContainer.js.map","/**\n * Helper class to push actions to a pool of workers.\n */\nexport class WorkerPool {\n /**\n * Constructor\n * @param workers Array of workers to use for actions\n */\n constructor(workers) {\n this._pendingActions = new Array();\n this._workerInfos = workers.map((worker) => ({\n workerPromise: Promise.resolve(worker),\n idle: true,\n }));\n }\n /**\n * Terminates all workers and clears any pending actions.\n */\n dispose() {\n for (const workerInfo of this._workerInfos) {\n workerInfo.workerPromise.then((worker) => {\n worker.terminate();\n });\n }\n this._workerInfos.length = 0;\n this._pendingActions.length = 0;\n }\n /**\n * Pushes an action to the worker pool. If all the workers are active, the action will be\n * pended until a worker has completed its action.\n * @param action The action to perform. Call onComplete when the action is complete.\n */\n push(action) {\n if (!this._executeOnIdleWorker(action)) {\n this._pendingActions.push(action);\n }\n }\n _executeOnIdleWorker(action) {\n for (const workerInfo of this._workerInfos) {\n if (workerInfo.idle) {\n this._execute(workerInfo, action);\n return true;\n }\n }\n return false;\n }\n _execute(workerInfo, action) {\n workerInfo.idle = false;\n workerInfo.workerPromise.then((worker) => {\n action(worker, () => {\n const nextAction = this._pendingActions.shift();\n if (nextAction) {\n this._execute(workerInfo, nextAction);\n }\n else {\n workerInfo.idle = true;\n }\n });\n });\n }\n}\n/**\n * Similar to the WorkerPool class except it creates and destroys workers automatically with a maximum of `maxWorkers` workers.\n * Workers are terminated when it is idle for at least `idleTimeElapsedBeforeRelease` milliseconds.\n */\nexport class AutoReleaseWorkerPool extends WorkerPool {\n constructor(maxWorkers, createWorkerAsync, options = AutoReleaseWorkerPool.DefaultOptions) {\n super([]);\n this._maxWorkers = maxWorkers;\n this._createWorkerAsync = createWorkerAsync;\n this._options = options;\n }\n push(action) {\n if (!this._executeOnIdleWorker(action)) {\n if (this._workerInfos.length < this._maxWorkers) {\n const workerInfo = {\n workerPromise: this._createWorkerAsync(),\n idle: false,\n };\n this._workerInfos.push(workerInfo);\n this._execute(workerInfo, action);\n }\n else {\n this._pendingActions.push(action);\n }\n }\n }\n _execute(workerInfo, action) {\n // Reset the idle timeout.\n if (workerInfo.timeoutId) {\n clearTimeout(workerInfo.timeoutId);\n delete workerInfo.timeoutId;\n }\n super._execute(workerInfo, (worker, onComplete) => {\n action(worker, () => {\n onComplete();\n if (workerInfo.idle) {\n // Schedule the worker to be terminated after the elapsed time.\n workerInfo.timeoutId = setTimeout(() => {\n workerInfo.workerPromise.then((worker) => {\n worker.terminate();\n });\n const indexOf = this._workerInfos.indexOf(workerInfo);\n if (indexOf !== -1) {\n this._workerInfos.splice(indexOf, 1);\n }\n }, this._options.idleTimeElapsedBeforeRelease);\n }\n });\n });\n }\n}\n/**\n * Default options for the constructor.\n * Override to change the defaults.\n */\nAutoReleaseWorkerPool.DefaultOptions = {\n idleTimeElapsedBeforeRelease: 1000,\n};\n//# sourceMappingURL=workerPool.js.map","export var SourceTextureFormat;\n(function (SourceTextureFormat) {\n SourceTextureFormat[SourceTextureFormat[\"ETC1S\"] = 0] = \"ETC1S\";\n SourceTextureFormat[SourceTextureFormat[\"UASTC4x4\"] = 1] = \"UASTC4x4\";\n})(SourceTextureFormat || (SourceTextureFormat = {}));\nexport var TranscodeTarget;\n(function (TranscodeTarget) {\n TranscodeTarget[TranscodeTarget[\"ASTC_4X4_RGBA\"] = 0] = \"ASTC_4X4_RGBA\";\n TranscodeTarget[TranscodeTarget[\"BC7_RGBA\"] = 1] = \"BC7_RGBA\";\n TranscodeTarget[TranscodeTarget[\"BC3_RGBA\"] = 2] = \"BC3_RGBA\";\n TranscodeTarget[TranscodeTarget[\"BC1_RGB\"] = 3] = \"BC1_RGB\";\n TranscodeTarget[TranscodeTarget[\"PVRTC1_4_RGBA\"] = 4] = \"PVRTC1_4_RGBA\";\n TranscodeTarget[TranscodeTarget[\"PVRTC1_4_RGB\"] = 5] = \"PVRTC1_4_RGB\";\n TranscodeTarget[TranscodeTarget[\"ETC2_RGBA\"] = 6] = \"ETC2_RGBA\";\n TranscodeTarget[TranscodeTarget[\"ETC1_RGB\"] = 7] = \"ETC1_RGB\";\n TranscodeTarget[TranscodeTarget[\"RGBA32\"] = 8] = \"RGBA32\";\n TranscodeTarget[TranscodeTarget[\"R8\"] = 9] = \"R8\";\n TranscodeTarget[TranscodeTarget[\"RG8\"] = 10] = \"RG8\";\n})(TranscodeTarget || (TranscodeTarget = {}));\nexport var EngineFormat;\n(function (EngineFormat) {\n EngineFormat[EngineFormat[\"COMPRESSED_RGBA_BPTC_UNORM_EXT\"] = 36492] = \"COMPRESSED_RGBA_BPTC_UNORM_EXT\";\n EngineFormat[EngineFormat[\"COMPRESSED_RGBA_ASTC_4X4_KHR\"] = 37808] = \"COMPRESSED_RGBA_ASTC_4X4_KHR\";\n EngineFormat[EngineFormat[\"COMPRESSED_RGB_S3TC_DXT1_EXT\"] = 33776] = \"COMPRESSED_RGB_S3TC_DXT1_EXT\";\n EngineFormat[EngineFormat[\"COMPRESSED_RGBA_S3TC_DXT5_EXT\"] = 33779] = \"COMPRESSED_RGBA_S3TC_DXT5_EXT\";\n EngineFormat[EngineFormat[\"COMPRESSED_RGBA_PVRTC_4BPPV1_IMG\"] = 35842] = \"COMPRESSED_RGBA_PVRTC_4BPPV1_IMG\";\n EngineFormat[EngineFormat[\"COMPRESSED_RGB_PVRTC_4BPPV1_IMG\"] = 35840] = \"COMPRESSED_RGB_PVRTC_4BPPV1_IMG\";\n EngineFormat[EngineFormat[\"COMPRESSED_RGBA8_ETC2_EAC\"] = 37496] = \"COMPRESSED_RGBA8_ETC2_EAC\";\n EngineFormat[EngineFormat[\"COMPRESSED_RGB8_ETC2\"] = 37492] = \"COMPRESSED_RGB8_ETC2\";\n EngineFormat[EngineFormat[\"COMPRESSED_RGB_ETC1_WEBGL\"] = 36196] = \"COMPRESSED_RGB_ETC1_WEBGL\";\n EngineFormat[EngineFormat[\"RGBA8Format\"] = 32856] = \"RGBA8Format\";\n EngineFormat[EngineFormat[\"R8Format\"] = 33321] = \"R8Format\";\n EngineFormat[EngineFormat[\"RG8Format\"] = 33323] = \"RG8Format\";\n})(EngineFormat || (EngineFormat = {}));\n//# sourceMappingURL=ktx2decoderTypes.js.map","\nimport { AutoReleaseWorkerPool } from \"./workerPool.js\";\nimport { Tools } from \"./tools.js\";\nimport { EngineFormat, TranscodeTarget } from \"../Materials/Textures/ktx2decoderTypes.js\";\nfunction getAbsoluteUrlOrNull(url) {\n return url ? Tools.GetAbsoluteUrl(url) : null;\n}\nfunction applyConfig(urls) {\n if (urls.wasmUASTCToASTC !== null) {\n KTX2DECODER.LiteTranscoder_UASTC_ASTC.WasmModuleURL = urls.wasmUASTCToASTC;\n }\n if (urls.wasmUASTCToBC7 !== null) {\n KTX2DECODER.LiteTranscoder_UASTC_BC7.WasmModuleURL = urls.wasmUASTCToBC7;\n }\n if (urls.wasmUASTCToRGBA_UNORM !== null) {\n KTX2DECODER.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL = urls.wasmUASTCToRGBA_UNORM;\n }\n if (urls.wasmUASTCToRGBA_SRGB !== null) {\n KTX2DECODER.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL = urls.wasmUASTCToRGBA_SRGB;\n }\n if (urls.wasmUASTCToR8_UNORM !== null) {\n KTX2DECODER.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL = urls.wasmUASTCToR8_UNORM;\n }\n if (urls.wasmUASTCToRG8_UNORM !== null) {\n KTX2DECODER.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL = urls.wasmUASTCToRG8_UNORM;\n }\n if (urls.jsMSCTranscoder !== null) {\n KTX2DECODER.MSCTranscoder.JSModuleURL = urls.jsMSCTranscoder;\n }\n if (urls.wasmMSCTranscoder !== null) {\n KTX2DECODER.MSCTranscoder.WasmModuleURL = urls.wasmMSCTranscoder;\n }\n if (urls.wasmZSTDDecoder !== null) {\n KTX2DECODER.ZSTDDecoder.WasmModuleURL = urls.wasmZSTDDecoder;\n }\n}\n/**\n * Class that defines the default KTX2 decoder options.\n *\n * This class is useful for providing options to the KTX2 decoder to control how the source data is transcoded.\n */\nexport class DefaultKTX2DecoderOptions {\n constructor() {\n this._isDirty = true;\n this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC = true;\n this._ktx2DecoderOptions = {};\n }\n /**\n * Gets the dirty flag\n */\n get isDirty() {\n return this._isDirty;\n }\n /**\n * force a (uncompressed) RGBA transcoded format if transcoding a UASTC source format and ASTC + BC7 are not available as a compressed transcoded format\n */\n get useRGBAIfASTCBC7NotAvailableWhenUASTC() {\n return this._useRGBAIfASTCBC7NotAvailableWhenUASTC;\n }\n set useRGBAIfASTCBC7NotAvailableWhenUASTC(value) {\n if (this._useRGBAIfASTCBC7NotAvailableWhenUASTC === value) {\n return;\n }\n this._useRGBAIfASTCBC7NotAvailableWhenUASTC = value;\n this._isDirty = true;\n }\n /**\n * force a (uncompressed) RGBA transcoded format if transcoding a UASTC source format and only BC1 or BC3 are available as a compressed transcoded format.\n * This property is true by default to favor speed over memory, because currently transcoding from UASTC to BC1/3 is slow because the transcoder transcodes\n * to uncompressed and then recompresses the texture\n */\n get useRGBAIfOnlyBC1BC3AvailableWhenUASTC() {\n return this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC;\n }\n set useRGBAIfOnlyBC1BC3AvailableWhenUASTC(value) {\n if (this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC === value) {\n return;\n }\n this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC = value;\n this._isDirty = true;\n }\n /**\n * force to always use (uncompressed) RGBA for transcoded format\n */\n get forceRGBA() {\n return this._forceRGBA;\n }\n set forceRGBA(value) {\n if (this._forceRGBA === value) {\n return;\n }\n this._forceRGBA = value;\n this._isDirty = true;\n }\n /**\n * force to always use (uncompressed) R8 for transcoded format\n */\n get forceR8() {\n return this._forceR8;\n }\n set forceR8(value) {\n if (this._forceR8 === value) {\n return;\n }\n this._forceR8 = value;\n this._isDirty = true;\n }\n /**\n * force to always use (uncompressed) RG8 for transcoded format\n */\n get forceRG8() {\n return this._forceRG8;\n }\n set forceRG8(value) {\n if (this._forceRG8 === value) {\n return;\n }\n this._forceRG8 = value;\n this._isDirty = true;\n }\n /**\n * list of transcoders to bypass when looking for a suitable transcoder. The available transcoders are:\n * UniversalTranscoder_UASTC_ASTC\n * UniversalTranscoder_UASTC_BC7\n * UniversalTranscoder_UASTC_RGBA_UNORM\n * UniversalTranscoder_UASTC_RGBA_SRGB\n * UniversalTranscoder_UASTC_R8_UNORM\n * UniversalTranscoder_UASTC_RG8_UNORM\n * MSCTranscoder\n */\n get bypassTranscoders() {\n return this._bypassTranscoders;\n }\n set bypassTranscoders(value) {\n if (this._bypassTranscoders === value) {\n return;\n }\n this._bypassTranscoders = value;\n this._isDirty = true;\n }\n /** @internal */\n _getKTX2DecoderOptions() {\n if (!this._isDirty) {\n return this._ktx2DecoderOptions;\n }\n this._isDirty = false;\n const options = {\n useRGBAIfASTCBC7NotAvailableWhenUASTC: this._useRGBAIfASTCBC7NotAvailableWhenUASTC,\n forceRGBA: this._forceRGBA,\n forceR8: this._forceR8,\n forceRG8: this._forceRG8,\n bypassTranscoders: this._bypassTranscoders,\n };\n if (this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC) {\n options.transcodeFormatDecisionTree = {\n UASTC: {\n transcodeFormat: [TranscodeTarget.BC1_RGB, TranscodeTarget.BC3_RGBA],\n yes: {\n transcodeFormat: TranscodeTarget.RGBA32,\n engineFormat: EngineFormat.RGBA8Format,\n roundToMultiple4: false,\n },\n },\n };\n }\n this._ktx2DecoderOptions = options;\n return options;\n }\n}\n/**\n * Class for loading KTX2 files\n */\nexport class KhronosTextureContainer2 {\n static GetDefaultNumWorkers() {\n if (typeof navigator !== \"object\" || !navigator.hardwareConcurrency) {\n return 1;\n }\n // Use 50% of the available logical processors but capped at 4.\n return Math.min(Math.floor(navigator.hardwareConcurrency * 0.5), 4);\n }\n static _Initialize(numWorkers) {\n if (KhronosTextureContainer2._WorkerPoolPromise || KhronosTextureContainer2._DecoderModulePromise) {\n return;\n }\n const urls = {\n jsDecoderModule: Tools.GetAbsoluteUrl(this.URLConfig.jsDecoderModule),\n wasmUASTCToASTC: getAbsoluteUrlOrNull(this.URLConfig.wasmUASTCToASTC),\n wasmUASTCToBC7: getAbsoluteUrlOrNull(this.URLConfig.wasmUASTCToBC7),\n wasmUASTCToRGBA_UNORM: getAbsoluteUrlOrNull(this.URLConfig.wasmUASTCToRGBA_UNORM),\n wasmUASTCToRGBA_SRGB: getAbsoluteUrlOrNull(this.URLConfig.wasmUASTCToRGBA_SRGB),\n wasmUASTCToR8_UNORM: getAbsoluteUrlOrNull(this.URLConfig.wasmUASTCToR8_UNORM),\n wasmUASTCToRG8_UNORM: getAbsoluteUrlOrNull(this.URLConfig.wasmUASTCToRG8_UNORM),\n jsMSCTranscoder: getAbsoluteUrlOrNull(this.URLConfig.jsMSCTranscoder),\n wasmMSCTranscoder: getAbsoluteUrlOrNull(this.URLConfig.wasmMSCTranscoder),\n wasmZSTDDecoder: getAbsoluteUrlOrNull(this.URLConfig.wasmZSTDDecoder),\n };\n if (numWorkers && typeof Worker === \"function\" && typeof URL !== \"undefined\") {\n KhronosTextureContainer2._WorkerPoolPromise = new Promise((resolve) => {\n const workerContent = `${applyConfig}(${workerFunc})()`;\n const workerBlobUrl = URL.createObjectURL(new Blob([workerContent], { type: \"application/javascript\" }));\n resolve(new AutoReleaseWorkerPool(numWorkers, () => new Promise((resolve, reject) => {\n const worker = new Worker(workerBlobUrl);\n const onError = (error) => {\n worker.removeEventListener(\"error\", onError);\n worker.removeEventListener(\"message\", onMessage);\n reject(error);\n };\n const onMessage = (message) => {\n if (message.data.action === \"init\") {\n worker.removeEventListener(\"error\", onError);\n worker.removeEventListener(\"message\", onMessage);\n resolve(worker);\n }\n };\n worker.addEventListener(\"error\", onError);\n worker.addEventListener(\"message\", onMessage);\n worker.postMessage({\n action: \"init\",\n urls: urls,\n });\n })));\n });\n }\n else if (typeof KTX2DECODER === \"undefined\") {\n KhronosTextureContainer2._DecoderModulePromise = Tools.LoadScriptAsync(urls.jsDecoderModule).then(() => {\n KTX2DECODER.MSCTranscoder.UseFromWorkerThread = false;\n KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread = true;\n applyConfig(urls);\n return new KTX2DECODER.KTX2Decoder();\n });\n }\n else {\n KTX2DECODER.MSCTranscoder.UseFromWorkerThread = false;\n KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread = true;\n KhronosTextureContainer2._DecoderModulePromise = Promise.resolve(new KTX2DECODER.KTX2Decoder());\n }\n }\n /**\n * Constructor\n * @param engine The engine to use\n * @param numWorkers The number of workers for async operations. Specify `0` to disable web workers and run synchronously in the current context.\n */\n constructor(engine, numWorkers = KhronosTextureContainer2.DefaultNumWorkers) {\n this._engine = engine;\n KhronosTextureContainer2._Initialize(numWorkers);\n }\n /**\n * @internal\n */\n uploadAsync(data, internalTexture, options) {\n const caps = this._engine.getCaps();\n const compressedTexturesCaps = {\n astc: !!caps.astc,\n bptc: !!caps.bptc,\n s3tc: !!caps.s3tc,\n pvrtc: !!caps.pvrtc,\n etc2: !!caps.etc2,\n etc1: !!caps.etc1,\n };\n if (KhronosTextureContainer2._WorkerPoolPromise) {\n return KhronosTextureContainer2._WorkerPoolPromise.then((workerPool) => {\n return new Promise((resolve, reject) => {\n workerPool.push((worker, onComplete) => {\n const onError = (error) => {\n worker.removeEventListener(\"error\", onError);\n worker.removeEventListener(\"message\", onMessage);\n reject(error);\n onComplete();\n };\n const onMessage = (message) => {\n if (message.data.action === \"decoded\") {\n worker.removeEventListener(\"error\", onError);\n worker.removeEventListener(\"message\", onMessage);\n if (!message.data.success) {\n reject({ message: message.data.msg });\n }\n else {\n try {\n this._createTexture(message.data.decodedData, internalTexture, options);\n resolve();\n }\n catch (err) {\n reject({ message: err });\n }\n }\n onComplete();\n }\n };\n worker.addEventListener(\"error\", onError);\n worker.addEventListener(\"message\", onMessage);\n worker.postMessage({ action: \"setDefaultDecoderOptions\", options: KhronosTextureContainer2.DefaultDecoderOptions._getKTX2DecoderOptions() });\n const dataCopy = new Uint8Array(data.byteLength);\n dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));\n worker.postMessage({ action: \"decode\", data: dataCopy, caps: compressedTexturesCaps, options }, [dataCopy.buffer]);\n });\n });\n });\n }\n else if (KhronosTextureContainer2._DecoderModulePromise) {\n return KhronosTextureContainer2._DecoderModulePromise.then((decoder) => {\n if (KhronosTextureContainer2.DefaultDecoderOptions.isDirty) {\n KTX2DECODER.KTX2Decoder.DefaultDecoderOptions = KhronosTextureContainer2.DefaultDecoderOptions._getKTX2DecoderOptions();\n }\n return new Promise((resolve, reject) => {\n decoder\n .decode(data, caps)\n .then((data) => {\n this._createTexture(data, internalTexture);\n resolve();\n })\n .catch((reason) => {\n reject({ message: reason });\n });\n });\n });\n }\n throw new Error(\"KTX2 decoder module is not available\");\n }\n _createTexture(data, internalTexture, options) {\n const oglTexture2D = 3553; // gl.TEXTURE_2D\n this._engine._bindTextureDirectly(oglTexture2D, internalTexture);\n if (options) {\n // return back some information about the decoded data\n options.transcodedFormat = data.transcodedFormat;\n options.isInGammaSpace = data.isInGammaSpace;\n options.hasAlpha = data.hasAlpha;\n options.transcoderName = data.transcoderName;\n }\n let isUncompressedFormat = true;\n switch (data.transcodedFormat) {\n case 0x8058 /* RGBA8 */:\n internalTexture.type = 0;\n internalTexture.format = 5;\n break;\n case 0x8229 /* R8 */:\n internalTexture.type = 0;\n internalTexture.format = 6;\n break;\n case 0x822b /* RG8 */:\n internalTexture.type = 0;\n internalTexture.format = 7;\n break;\n default:\n internalTexture.format = data.transcodedFormat;\n isUncompressedFormat = false;\n break;\n }\n internalTexture._gammaSpace = data.isInGammaSpace;\n internalTexture.generateMipMaps = data.mipmaps.length > 1;\n if (data.errors) {\n throw new Error(\"KTX2 container - could not transcode the data. \" + data.errors);\n }\n for (let t = 0; t < data.mipmaps.length; ++t) {\n const mipmap = data.mipmaps[t];\n if (!mipmap || !mipmap.data) {\n throw new Error(\"KTX2 container - could not transcode one of the image\");\n }\n if (isUncompressedFormat) {\n // uncompressed RGBA / R8 / RG8\n internalTexture.width = mipmap.width; // need to set width/height so that the call to _uploadDataToTextureDirectly uses the right dimensions\n internalTexture.height = mipmap.height;\n this._engine._uploadDataToTextureDirectly(internalTexture, mipmap.data, 0, t, undefined, true);\n }\n else {\n this._engine._uploadCompressedDataToTextureDirectly(internalTexture, data.transcodedFormat, mipmap.width, mipmap.height, mipmap.data, 0, t);\n }\n }\n internalTexture._extension = \".ktx2\";\n internalTexture.width = data.mipmaps[0].width;\n internalTexture.height = data.mipmaps[0].height;\n internalTexture.isReady = true;\n this._engine._bindTextureDirectly(oglTexture2D, null);\n }\n /**\n * Checks if the given data starts with a KTX2 file identifier.\n * @param data the data to check\n * @returns true if the data is a KTX2 file or false otherwise\n */\n static IsValid(data) {\n if (data.byteLength >= 12) {\n // '«', 'K', 'T', 'X', ' ', '2', '0', '»', '\\r', '\\n', '\\x1A', '\\n'\n const identifier = new Uint8Array(data.buffer, data.byteOffset, 12);\n if (identifier[0] === 0xab &&\n identifier[1] === 0x4b &&\n identifier[2] === 0x54 &&\n identifier[3] === 0x58 &&\n identifier[4] === 0x20 &&\n identifier[5] === 0x32 &&\n identifier[6] === 0x30 &&\n identifier[7] === 0xbb &&\n identifier[8] === 0x0d &&\n identifier[9] === 0x0a &&\n identifier[10] === 0x1a &&\n identifier[11] === 0x0a) {\n return true;\n }\n }\n return false;\n }\n}\n/**\n * URLs to use when loading the KTX2 decoder module as well as its dependencies\n * If a url is null, the default url is used (pointing to https://preview.babylonjs.com)\n * Note that jsDecoderModule can't be null and that the other dependencies will only be loaded if necessary\n * Urls you can change:\n * URLConfig.jsDecoderModule\n * URLConfig.wasmUASTCToASTC\n * URLConfig.wasmUASTCToBC7\n * URLConfig.wasmUASTCToRGBA_UNORM\n * URLConfig.wasmUASTCToRGBA_SRGB\n * URLConfig.wasmUASTCToR8_UNORM\n * URLConfig.wasmUASTCToRG8_UNORM\n * URLConfig.jsMSCTranscoder\n * URLConfig.wasmMSCTranscoder\n * URLConfig.wasmZSTDDecoder\n * You can see their default values in this PG: https://playground.babylonjs.com/#EIJH8L#29\n */\nKhronosTextureContainer2.URLConfig = {\n jsDecoderModule: \"https://preview.babylonjs.com/babylon.ktx2Decoder.js\",\n wasmUASTCToASTC: null,\n wasmUASTCToBC7: null,\n wasmUASTCToRGBA_UNORM: null,\n wasmUASTCToRGBA_SRGB: null,\n wasmUASTCToR8_UNORM: null,\n wasmUASTCToRG8_UNORM: null,\n jsMSCTranscoder: null,\n wasmMSCTranscoder: null,\n wasmZSTDDecoder: null,\n};\n/**\n * Default number of workers used to handle data decoding\n */\nKhronosTextureContainer2.DefaultNumWorkers = KhronosTextureContainer2.GetDefaultNumWorkers();\n/**\n * Default configuration for the KTX2 decoder.\n * The options defined in this way have priority over those passed when creating a KTX2 texture with new Texture(...).\n */\nKhronosTextureContainer2.DefaultDecoderOptions = new DefaultKTX2DecoderOptions();\nfunction workerFunc() {\n let ktx2Decoder;\n onmessage = (event) => {\n if (!event.data) {\n return;\n }\n switch (event.data.action) {\n case \"init\": {\n const urls = event.data.urls;\n importScripts(urls.jsDecoderModule);\n applyConfig(urls);\n ktx2Decoder = new KTX2DECODER.KTX2Decoder();\n postMessage({ action: \"init\" });\n break;\n }\n case \"setDefaultDecoderOptions\": {\n KTX2DECODER.KTX2Decoder.DefaultDecoderOptions = event.data.options;\n break;\n }\n case \"decode\":\n ktx2Decoder\n .decode(event.data.data, event.data.caps, event.data.options)\n .then((data) => {\n const buffers = [];\n for (let mip = 0; mip < data.mipmaps.length; ++mip) {\n const mipmap = data.mipmaps[mip];\n if (mipmap && mipmap.data) {\n buffers.push(mipmap.data.buffer);\n }\n }\n postMessage({ action: \"decoded\", success: true, decodedData: data }, buffers);\n })\n .catch((reason) => {\n postMessage({ action: \"decoded\", success: false, msg: reason });\n });\n break;\n }\n };\n}\n//# sourceMappingURL=khronosTextureContainer2.js.map","import { KhronosTextureContainer } from \"../../../Misc/khronosTextureContainer.js\";\nimport { KhronosTextureContainer2 } from \"../../../Misc/khronosTextureContainer2.js\";\nimport { Engine } from \"../../../Engines/engine.js\";\nimport { Logger } from \"../../../Misc/logger.js\";\n\nfunction mapSRGBToLinear(format) {\n switch (format) {\n case 35916:\n return 33776;\n case 35918:\n return 33778;\n case 35919:\n return 33779;\n case 37493:\n return 37492;\n case 37497:\n return 37496;\n case 37495:\n return 37494;\n case 37840:\n return 37808;\n case 36493:\n return 36492;\n }\n return null;\n}\n/**\n * Implementation of the KTX Texture Loader.\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class _KTXTextureLoader {\n constructor() {\n /**\n * Defines whether the loader supports cascade loading the different faces.\n */\n this.supportCascades = false;\n }\n /**\n * This returns if the loader support the current file information.\n * @param extension defines the file extension of the file being loaded\n * @param mimeType defines the optional mime type of the file being loaded\n * @returns true if the loader can load the specified file\n */\n canLoad(extension, mimeType) {\n // The \".ktx2\" file extension is still up for debate: https://github.com/KhronosGroup/KTX-Specification/issues/18\n return extension.endsWith(\".ktx\") || extension.endsWith(\".ktx2\") || mimeType === \"image/ktx\" || mimeType === \"image/ktx2\";\n }\n /**\n * Uploads the cube texture data to the WebGL texture. It has already been bound.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param createPolynomials will be true if polynomials have been requested\n * @param onLoad defines the callback to trigger once the texture is ready\n */\n loadCubeData(data, texture, createPolynomials, onLoad) {\n if (Array.isArray(data)) {\n return;\n }\n // Need to invert vScale as invertY via UNPACK_FLIP_Y_WEBGL is not supported by compressed texture\n texture._invertVScale = !texture.invertY;\n const engine = texture.getEngine();\n const ktx = new KhronosTextureContainer(data, 6);\n const loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;\n engine._unpackFlipY(true);\n ktx.uploadLevels(texture, texture.generateMipMaps);\n texture.width = ktx.pixelWidth;\n texture.height = ktx.pixelHeight;\n engine._setCubeMapTextureParams(texture, loadMipmap, ktx.numberOfMipmapLevels - 1);\n texture.isReady = true;\n texture.onLoadedObservable.notifyObservers(texture);\n texture.onLoadedObservable.clear();\n if (onLoad) {\n onLoad();\n }\n }\n /**\n * Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param callback defines the method to call once ready to upload\n * @param options\n */\n loadData(data, texture, callback, options) {\n if (KhronosTextureContainer.IsValid(data)) {\n // Need to invert vScale as invertY via UNPACK_FLIP_Y_WEBGL is not supported by compressed texture\n texture._invertVScale = !texture.invertY;\n const ktx = new KhronosTextureContainer(data, 1);\n const mappedFormat = mapSRGBToLinear(ktx.glInternalFormat);\n if (mappedFormat) {\n texture.format = mappedFormat;\n texture._useSRGBBuffer = texture.getEngine()._getUseSRGBBuffer(true, texture.generateMipMaps);\n texture._gammaSpace = true;\n }\n else {\n texture.format = ktx.glInternalFormat;\n }\n callback(ktx.pixelWidth, ktx.pixelHeight, texture.generateMipMaps, true, () => {\n ktx.uploadLevels(texture, texture.generateMipMaps);\n }, ktx.isInvalid);\n }\n else if (KhronosTextureContainer2.IsValid(data)) {\n const ktx2 = new KhronosTextureContainer2(texture.getEngine());\n ktx2.uploadAsync(data, texture, options).then(() => {\n callback(texture.width, texture.height, texture.generateMipMaps, true, () => { }, false);\n }, (error) => {\n Logger.Warn(`Failed to load KTX2 texture data: ${error.message}`);\n callback(0, 0, false, false, () => { }, true);\n });\n }\n else {\n Logger.Error(\"texture missing KTX identifier\");\n callback(0, 0, false, false, () => { }, true);\n }\n }\n}\n// Register the loader.\nEngine._TextureLoaders.unshift(new _KTXTextureLoader());\n//# sourceMappingURL=ktxTextureLoader.js.map","import { Vector3, Matrix, Quaternion, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Camera } from \"../Cameras/camera.js\";\nimport { FreeCamera } from \"../Cameras/freeCamera.js\";\nimport { TargetCamera } from \"../Cameras/targetCamera.js\";\nimport { Viewport } from \"../Maths/math.viewport.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { WebXRTrackingState } from \"./webXRTypes.js\";\n/**\n * WebXR Camera which holds the views for the xrSession\n * @see https://doc.babylonjs.com/features/featuresDeepDive/webXR/webXRCamera\n */\nexport class WebXRCamera extends FreeCamera {\n /**\n * Creates a new webXRCamera, this should only be set at the camera after it has been updated by the xrSessionManager\n * @param name the name of the camera\n * @param scene the scene to add the camera to\n * @param _xrSessionManager a constructed xr session manager\n */\n constructor(name, scene, _xrSessionManager) {\n super(name, Vector3.Zero(), scene);\n this._xrSessionManager = _xrSessionManager;\n this._firstFrame = false;\n this._referenceQuaternion = Quaternion.Identity();\n this._referencedPosition = new Vector3();\n this._trackingState = WebXRTrackingState.NOT_TRACKING;\n /**\n * Observable raised before camera teleportation\n */\n this.onBeforeCameraTeleport = new Observable();\n /**\n * Observable raised after camera teleportation\n */\n this.onAfterCameraTeleport = new Observable();\n /**\n * Notifies when the camera's tracking state has changed.\n * Notice - will also be triggered when tracking has started (at the beginning of the session)\n */\n this.onTrackingStateChanged = new Observable();\n /**\n * Should position compensation execute on first frame.\n * This is used when copying the position from a native (non XR) camera\n */\n this.compensateOnFirstFrame = true;\n this._rotate180 = new Quaternion(0, 1, 0, 0);\n // Initial camera configuration\n this.minZ = 0.1;\n this.rotationQuaternion = new Quaternion();\n this.cameraRigMode = Camera.RIG_MODE_CUSTOM;\n this.updateUpVectorFromRotation = true;\n this._updateNumberOfRigCameras(1);\n // freeze projection matrix, which will be copied later\n this.freezeProjectionMatrix();\n this._xrSessionManager.onXRSessionInit.add(() => {\n this._referencedPosition.copyFromFloats(0, 0, 0);\n this._referenceQuaternion.copyFromFloats(0, 0, 0, 1);\n // first frame - camera's y position should be 0 for the correct offset\n this._firstFrame = this.compensateOnFirstFrame;\n });\n // Check transformation changes on each frame. Callback is added to be first so that the transformation will be\n // applied to the rest of the elements using the referenceSpace object\n this._xrSessionManager.onXRFrameObservable.add(() => {\n if (this._firstFrame) {\n this._updateFromXRSession();\n }\n this._updateReferenceSpace();\n this._updateFromXRSession();\n }, undefined, true);\n }\n /**\n * Get the current XR tracking state of the camera\n */\n get trackingState() {\n return this._trackingState;\n }\n _setTrackingState(newState) {\n if (this._trackingState !== newState) {\n this._trackingState = newState;\n this.onTrackingStateChanged.notifyObservers(newState);\n }\n }\n /**\n * Return the user's height, unrelated to the current ground.\n * This will be the y position of this camera, when ground level is 0.\n */\n get realWorldHeight() {\n const basePose = this._xrSessionManager.currentFrame && this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace);\n if (basePose && basePose.transform) {\n return basePose.transform.position.y;\n }\n else {\n return 0;\n }\n }\n /** @internal */\n _updateForDualEyeDebugging( /*pupilDistance = 0.01*/) {\n // Create initial camera rigs\n this._updateNumberOfRigCameras(2);\n this.rigCameras[0].viewport = new Viewport(0, 0, 0.5, 1.0);\n // this.rigCameras[0].position.x = -pupilDistance / 2;\n this.rigCameras[0].outputRenderTarget = null;\n this.rigCameras[1].viewport = new Viewport(0.5, 0, 0.5, 1.0);\n // this.rigCameras[1].position.x = pupilDistance / 2;\n this.rigCameras[1].outputRenderTarget = null;\n }\n /**\n * Sets this camera's transformation based on a non-vr camera\n * @param otherCamera the non-vr camera to copy the transformation from\n * @param resetToBaseReferenceSpace should XR reset to the base reference space\n */\n setTransformationFromNonVRCamera(otherCamera = this.getScene().activeCamera, resetToBaseReferenceSpace = true) {\n if (!otherCamera || otherCamera === this) {\n return;\n }\n const mat = otherCamera.computeWorldMatrix();\n mat.decompose(undefined, this.rotationQuaternion, this.position);\n // set the ground level\n this.position.y = 0;\n Quaternion.FromEulerAnglesToRef(0, this.rotationQuaternion.toEulerAngles().y, 0, this.rotationQuaternion);\n this._firstFrame = true;\n if (resetToBaseReferenceSpace) {\n this._xrSessionManager.resetReferenceSpace();\n }\n }\n /**\n * Gets the current instance class name (\"WebXRCamera\").\n * @returns the class name\n */\n getClassName() {\n return \"WebXRCamera\";\n }\n /**\n * Set the target for the camera to look at.\n * Note that this only rotates around the Y axis, as opposed to the default behavior of other cameras\n * @param target the target to set the camera to look at\n */\n setTarget(target) {\n // only rotate around the y axis!\n const tmpVector = TmpVectors.Vector3[1];\n target.subtractToRef(this.position, tmpVector);\n tmpVector.y = 0;\n tmpVector.normalize();\n const yRotation = Math.atan2(tmpVector.x, tmpVector.z);\n this.rotationQuaternion.toEulerAnglesToRef(tmpVector);\n Quaternion.FromEulerAnglesToRef(tmpVector.x, yRotation, tmpVector.z, this.rotationQuaternion);\n }\n dispose() {\n super.dispose();\n this._lastXRViewerPose = undefined;\n }\n _updateFromXRSession() {\n const pose = this._xrSessionManager.currentFrame && this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);\n this._lastXRViewerPose = pose || undefined;\n if (!pose) {\n this._setTrackingState(WebXRTrackingState.NOT_TRACKING);\n return;\n }\n // Set the tracking state. if it didn't change it is a no-op\n const trackingState = pose.emulatedPosition ? WebXRTrackingState.TRACKING_LOST : WebXRTrackingState.TRACKING;\n this._setTrackingState(trackingState);\n // check min/max Z and update if not the same as in cache\n if (this.minZ !== this._cache.minZ || this.maxZ !== this._cache.maxZ) {\n const xrRenderState = {\n // if maxZ is 0 it should be \"Infinity\", but it doesn't work with the WebXR API. Setting to a large number.\n depthFar: this.maxZ || 10000,\n depthNear: this.minZ,\n };\n this._xrSessionManager.updateRenderState(xrRenderState);\n this._cache.minZ = this.minZ;\n this._cache.maxZ = this.maxZ;\n }\n if (pose.transform) {\n const orientation = pose.transform.orientation;\n if (pose.transform.orientation.x === undefined) {\n // Babylon native polyfill can return an undefined orientation value\n // When not initialized\n return;\n }\n const pos = pose.transform.position;\n this._referencedPosition.set(pos.x, pos.y, pos.z);\n this._referenceQuaternion.set(orientation.x, orientation.y, orientation.z, orientation.w);\n if (!this._scene.useRightHandedSystem) {\n this._referencedPosition.z *= -1;\n this._referenceQuaternion.z *= -1;\n this._referenceQuaternion.w *= -1;\n }\n if (this._firstFrame) {\n this._firstFrame = false;\n // we have the XR reference, now use this to find the offset to get the camera to be\n // in the right position\n // set the height to correlate to the current height\n this.position.y += this._referencedPosition.y;\n // avoid using the head rotation on the first frame.\n this._referenceQuaternion.copyFromFloats(0, 0, 0, 1);\n }\n else {\n // update position and rotation as reference\n this.rotationQuaternion.copyFrom(this._referenceQuaternion);\n this.position.copyFrom(this._referencedPosition);\n }\n }\n // Update camera rigs\n if (this.rigCameras.length !== pose.views.length) {\n this._updateNumberOfRigCameras(pose.views.length);\n }\n pose.views.forEach((view, i) => {\n var _a;\n const currentRig = this.rigCameras[i];\n // update right and left, where applicable\n if (!currentRig.isLeftCamera && !currentRig.isRightCamera) {\n if (view.eye === \"right\") {\n currentRig._isRightCamera = true;\n }\n else if (view.eye === \"left\") {\n currentRig._isLeftCamera = true;\n }\n }\n // Update view/projection matrix\n const pos = view.transform.position;\n const orientation = view.transform.orientation;\n currentRig.parent = this.parent;\n currentRig.position.set(pos.x, pos.y, pos.z);\n currentRig.rotationQuaternion.set(orientation.x, orientation.y, orientation.z, orientation.w);\n if (!this._scene.useRightHandedSystem) {\n currentRig.position.z *= -1;\n currentRig.rotationQuaternion.z *= -1;\n currentRig.rotationQuaternion.w *= -1;\n }\n else {\n currentRig.rotationQuaternion.multiplyInPlace(this._rotate180);\n }\n Matrix.FromFloat32ArrayToRefScaled(view.projectionMatrix, 0, 1, currentRig._projectionMatrix);\n if (!this._scene.useRightHandedSystem) {\n currentRig._projectionMatrix.toggleProjectionMatrixHandInPlace();\n }\n // first camera?\n if (i === 0) {\n this._projectionMatrix.copyFrom(currentRig._projectionMatrix);\n }\n const renderTargetTexture = this._xrSessionManager.getRenderTargetTextureForView(view);\n this._renderingMultiview = ((_a = renderTargetTexture === null || renderTargetTexture === void 0 ? void 0 : renderTargetTexture._texture) === null || _a === void 0 ? void 0 : _a.isMultiview) || false;\n if (this._renderingMultiview) {\n // For multiview, the render target texture is the same per-view (just the slice index is different),\n // so we only need to set the output render target once for the rig parent.\n if (i == 0) {\n this._xrSessionManager.trySetViewportForView(this.viewport, view);\n this.outputRenderTarget = renderTargetTexture;\n }\n }\n else {\n // Update viewport\n this._xrSessionManager.trySetViewportForView(currentRig.viewport, view);\n // Set cameras to render to the session's render target\n currentRig.outputRenderTarget = renderTargetTexture || this._xrSessionManager.getRenderTargetTextureForView(view);\n }\n // Replicate parent rig camera behavior\n currentRig.layerMask = this.layerMask;\n });\n }\n _updateNumberOfRigCameras(viewCount = 1) {\n while (this.rigCameras.length < viewCount) {\n const newCamera = new TargetCamera(\"XR-RigCamera: \" + this.rigCameras.length, Vector3.Zero(), this.getScene());\n newCamera.minZ = 0.1;\n newCamera.rotationQuaternion = new Quaternion();\n newCamera.updateUpVectorFromRotation = true;\n newCamera.isRigCamera = true;\n newCamera.rigParent = this;\n // do not compute projection matrix, provided by XR\n newCamera.freezeProjectionMatrix();\n this.rigCameras.push(newCamera);\n }\n while (this.rigCameras.length > viewCount) {\n const removedCamera = this.rigCameras.pop();\n if (removedCamera) {\n removedCamera.dispose();\n }\n }\n }\n _updateReferenceSpace() {\n // were position & rotation updated OUTSIDE of the xr update loop\n if (!this.position.equals(this._referencedPosition) || !this.rotationQuaternion.equals(this._referenceQuaternion)) {\n const referencedMat = TmpVectors.Matrix[0];\n const poseMat = TmpVectors.Matrix[1];\n const transformMat = TmpVectors.Matrix[2];\n Matrix.ComposeToRef(WebXRCamera._ScaleReadOnly, this._referenceQuaternion, this._referencedPosition, referencedMat);\n Matrix.ComposeToRef(WebXRCamera._ScaleReadOnly, this.rotationQuaternion, this.position, poseMat);\n referencedMat.invert().multiplyToRef(poseMat, transformMat);\n transformMat.invert();\n if (!this._scene.useRightHandedSystem) {\n transformMat.toggleModelMatrixHandInPlace();\n }\n transformMat.decompose(undefined, this._referenceQuaternion, this._referencedPosition);\n const transform = new XRRigidTransform({\n x: this._referencedPosition.x,\n y: this._referencedPosition.y,\n z: this._referencedPosition.z,\n }, {\n x: this._referenceQuaternion.x,\n y: this._referenceQuaternion.y,\n z: this._referenceQuaternion.z,\n w: this._referenceQuaternion.w,\n });\n this._xrSessionManager.referenceSpace = this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(transform);\n }\n }\n}\nWebXRCamera._ScaleReadOnly = Vector3.One();\n//# sourceMappingURL=webXRCamera.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { WebXRSessionManager } from \"./webXRSessionManager.js\";\nimport { WebXRCamera } from \"./webXRCamera.js\";\nimport { WebXRState } from \"./webXRTypes.js\";\nimport { WebXRFeatureName, WebXRFeaturesManager } from \"./webXRFeaturesManager.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { UniversalCamera } from \"../Cameras/universalCamera.js\";\nimport { Quaternion, Vector3 } from \"../Maths/math.vector.js\";\n/**\n * Base set of functionality needed to create an XR experience (WebXRSessionManager, Camera, StateManagement, etc.)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/webXR/webXRExperienceHelpers\n */\nexport class WebXRExperienceHelper {\n /**\n * Creates a WebXRExperienceHelper\n * @param _scene The scene the helper should be created in\n */\n constructor(_scene) {\n this._scene = _scene;\n this._nonVRCamera = null;\n this._attachedToElement = false;\n this._spectatorCamera = null;\n this._originalSceneAutoClear = true;\n this._supported = false;\n this._spectatorMode = false;\n this._lastTimestamp = 0;\n /**\n * Observers registered here will be triggered after the camera's initial transformation is set\n * This can be used to set a different ground level or an extra rotation.\n *\n * Note that ground level is considered to be at 0. The height defined by the XR camera will be added\n * to the position set after this observable is done executing.\n */\n this.onInitialXRPoseSetObservable = new Observable();\n /**\n * Fires when the state of the experience helper has changed\n */\n this.onStateChangedObservable = new Observable();\n /**\n * The current state of the XR experience (eg. transitioning, in XR or not in XR)\n */\n this.state = WebXRState.NOT_IN_XR;\n this.sessionManager = new WebXRSessionManager(_scene);\n this.camera = new WebXRCamera(\"webxr\", _scene, this.sessionManager);\n this.featuresManager = new WebXRFeaturesManager(this.sessionManager);\n _scene.onDisposeObservable.addOnce(() => {\n this.dispose();\n });\n }\n /**\n * Creates the experience helper\n * @param scene the scene to attach the experience helper to\n * @returns a promise for the experience helper\n */\n static CreateAsync(scene) {\n const helper = new WebXRExperienceHelper(scene);\n return helper.sessionManager\n .initializeAsync()\n .then(() => {\n helper._supported = true;\n return helper;\n })\n .catch((e) => {\n helper._setState(WebXRState.NOT_IN_XR);\n helper.dispose();\n throw e;\n });\n }\n /**\n * Disposes of the experience helper\n */\n dispose() {\n var _a;\n this.exitXRAsync();\n this.camera.dispose();\n this.onStateChangedObservable.clear();\n this.onInitialXRPoseSetObservable.clear();\n this.sessionManager.dispose();\n (_a = this._spectatorCamera) === null || _a === void 0 ? void 0 : _a.dispose();\n if (this._nonVRCamera) {\n this._scene.activeCamera = this._nonVRCamera;\n }\n }\n /**\n * Enters XR mode (This must be done within a user interaction in most browsers eg. button click)\n * @param sessionMode options for the XR session\n * @param referenceSpaceType frame of reference of the XR session\n * @param renderTarget the output canvas that will be used to enter XR mode\n * @param sessionCreationOptions optional XRSessionInit object to init the session with\n * @returns promise that resolves after xr mode has entered\n */\n async enterXRAsync(sessionMode, referenceSpaceType, renderTarget = this.sessionManager.getWebXRRenderTarget(), sessionCreationOptions = {}) {\n var _a, _b, _c;\n if (!this._supported) {\n throw \"WebXR not supported in this browser or environment\";\n }\n this._setState(WebXRState.ENTERING_XR);\n if (referenceSpaceType !== \"viewer\" && referenceSpaceType !== \"local\") {\n sessionCreationOptions.optionalFeatures = sessionCreationOptions.optionalFeatures || [];\n sessionCreationOptions.optionalFeatures.push(referenceSpaceType);\n }\n sessionCreationOptions = await this.featuresManager._extendXRSessionInitObject(sessionCreationOptions);\n // we currently recommend \"unbounded\" space in AR (#7959)\n if (sessionMode === \"immersive-ar\" && referenceSpaceType !== \"unbounded\") {\n Logger.Warn(\"We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode\");\n }\n // make sure that the session mode is supported\n try {\n await this.sessionManager.initializeSessionAsync(sessionMode, sessionCreationOptions);\n await this.sessionManager.setReferenceSpaceTypeAsync(referenceSpaceType);\n const baseLayer = await renderTarget.initializeXRLayerAsync(this.sessionManager.session);\n const xrRenderState = {\n // if maxZ is 0 it should be \"Infinity\", but it doesn't work with the WebXR API. Setting to a large number.\n depthFar: this.camera.maxZ || 10000,\n depthNear: this.camera.minZ,\n };\n // The layers feature will have already initialized the xr session's layers on session init.\n if (!this.featuresManager.getEnabledFeature(WebXRFeatureName.LAYERS)) {\n xrRenderState.baseLayer = baseLayer;\n }\n this.sessionManager.updateRenderState(xrRenderState);\n // run the render loop\n this.sessionManager.runXRRenderLoop();\n // Cache pre xr scene settings\n this._originalSceneAutoClear = this._scene.autoClear;\n this._nonVRCamera = this._scene.activeCamera;\n this._attachedToElement = !!((_b = (_a = this._nonVRCamera) === null || _a === void 0 ? void 0 : _a.inputs) === null || _b === void 0 ? void 0 : _b.attachedToElement);\n (_c = this._nonVRCamera) === null || _c === void 0 ? void 0 : _c.detachControl();\n this._scene.activeCamera = this.camera;\n // do not compensate when AR session is used\n if (sessionMode !== \"immersive-ar\") {\n this._nonXRToXRCamera();\n }\n else {\n // Kept here, TODO - check if needed\n this._scene.autoClear = false;\n this.camera.compensateOnFirstFrame = false;\n // reset the camera's position to the origin\n this.camera.position.set(0, 0, 0);\n this.camera.rotationQuaternion.set(0, 0, 0, 1);\n this.onInitialXRPoseSetObservable.notifyObservers(this.camera);\n }\n this.sessionManager.onXRSessionEnded.addOnce(() => {\n // when using the back button and not the exit button (default on mobile), the session is ending but the EXITING state was not set\n if (this.state !== WebXRState.EXITING_XR) {\n this._setState(WebXRState.EXITING_XR);\n }\n // Reset camera rigs output render target to ensure sessions render target is not drawn after it ends\n this.camera.rigCameras.forEach((c) => {\n c.outputRenderTarget = null;\n });\n // Restore scene settings\n this._scene.autoClear = this._originalSceneAutoClear;\n this._scene.activeCamera = this._nonVRCamera;\n if (this._attachedToElement && this._nonVRCamera) {\n this._nonVRCamera.attachControl(!!this._nonVRCamera.inputs.noPreventDefault);\n }\n if (sessionMode !== \"immersive-ar\" && this.camera.compensateOnFirstFrame) {\n if (this._nonVRCamera.setPosition) {\n this._nonVRCamera.setPosition(this.camera.position);\n }\n else {\n this._nonVRCamera.position.copyFrom(this.camera.position);\n }\n }\n this._setState(WebXRState.NOT_IN_XR);\n });\n // Wait until the first frame arrives before setting state to in xr\n this.sessionManager.onXRFrameObservable.addOnce(() => {\n this._setState(WebXRState.IN_XR);\n });\n return this.sessionManager;\n }\n catch (e) {\n console.log(e);\n console.log(e.message);\n this._setState(WebXRState.NOT_IN_XR);\n throw e;\n }\n }\n /**\n * Exits XR mode and returns the scene to its original state\n * @returns promise that resolves after xr mode has exited\n */\n exitXRAsync() {\n // only exit if state is IN_XR\n if (this.state !== WebXRState.IN_XR) {\n return Promise.resolve();\n }\n this._setState(WebXRState.EXITING_XR);\n return this.sessionManager.exitXRAsync();\n }\n /**\n * Enable spectator mode for desktop VR experiences.\n * When spectator mode is enabled a camera will be attached to the desktop canvas and will\n * display the first rig camera's view on the desktop canvas.\n * Please note that this will degrade performance, as it requires another camera render.\n * It is also not recommended to enable this in devices like the quest, as it brings no benefit there.\n * @param options giving WebXRSpectatorModeOption for specutator camera to setup when the spectator mode is enabled.\n */\n enableSpectatorMode(options) {\n if (!this._spectatorMode) {\n this._spectatorMode = true;\n this._switchSpectatorMode(options);\n }\n }\n /**\n * Disable spectator mode for desktop VR experiences.\n */\n disableSpecatatorMode() {\n if (this._spectatorMode) {\n this._spectatorMode = false;\n this._switchSpectatorMode();\n }\n }\n _switchSpectatorMode(options) {\n const fps = (options === null || options === void 0 ? void 0 : options.fps) ? options.fps : 1000.0;\n const refreshRate = (1.0 / fps) * 1000.0;\n const cameraIndex = (options === null || options === void 0 ? void 0 : options.preferredCameraIndex) ? options === null || options === void 0 ? void 0 : options.preferredCameraIndex : 0;\n const updateSpectatorCamera = () => {\n if (this._spectatorCamera) {\n const delta = this.sessionManager.currentTimestamp - this._lastTimestamp;\n if (delta >= refreshRate) {\n this._lastTimestamp = this.sessionManager.currentTimestamp;\n this._spectatorCamera.position.copyFrom(this.camera.rigCameras[cameraIndex].globalPosition);\n this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[cameraIndex].absoluteRotation);\n }\n }\n };\n if (this._spectatorMode) {\n if (cameraIndex >= this.camera.rigCameras.length) {\n throw new Error(\"the preferred camera index is beyond the length of rig camera array.\");\n }\n const onStateChanged = () => {\n if (this.state === WebXRState.IN_XR) {\n this._spectatorCamera = new UniversalCamera(\"webxr-spectator\", Vector3.Zero(), this._scene);\n this._spectatorCamera.rotationQuaternion = new Quaternion();\n this._scene.activeCameras = [this.camera, this._spectatorCamera];\n this.sessionManager.onXRFrameObservable.add(updateSpectatorCamera);\n this._scene.onAfterRenderCameraObservable.add((camera) => {\n if (camera === this.camera) {\n // reset the dimensions object for correct resizing\n this._scene.getEngine().framebufferDimensionsObject = null;\n }\n });\n }\n else if (this.state === WebXRState.EXITING_XR) {\n this.sessionManager.onXRFrameObservable.removeCallback(updateSpectatorCamera);\n this._scene.activeCameras = null;\n }\n };\n this.onStateChangedObservable.add(onStateChanged);\n onStateChanged();\n }\n else {\n this.sessionManager.onXRFrameObservable.removeCallback(updateSpectatorCamera);\n this._scene.activeCameras = [this.camera];\n }\n }\n _nonXRToXRCamera() {\n this.camera.setTransformationFromNonVRCamera(this._nonVRCamera);\n this.onInitialXRPoseSetObservable.notifyObservers(this.camera);\n }\n _setState(val) {\n if (this.state === val) {\n return;\n }\n this.state = val;\n this.onStateChangedObservable.notifyObservers(this.state);\n }\n}\n//# sourceMappingURL=webXRExperienceHelper.js.map","import { Observable } from \"../../Misc/observable.js\";\n/**\n * This class represents a single component (for example button or thumbstick) of a motion controller\n */\nexport class WebXRControllerComponent {\n /**\n * Creates a new component for a motion controller.\n * It is created by the motion controller itself\n *\n * @param id the id of this component\n * @param type the type of the component\n * @param _buttonIndex index in the buttons array of the gamepad\n * @param _axesIndices indices of the values in the axes array of the gamepad\n */\n constructor(\n /**\n * the id of this component\n */\n id, \n /**\n * the type of the component\n */\n type, _buttonIndex = -1, _axesIndices = []) {\n this.id = id;\n this.type = type;\n this._buttonIndex = _buttonIndex;\n this._axesIndices = _axesIndices;\n this._axes = {\n x: 0,\n y: 0,\n };\n this._changes = {};\n this._currentValue = 0;\n this._hasChanges = false;\n this._pressed = false;\n this._touched = false;\n /**\n * If axes are available for this component (like a touchpad or thumbstick) the observers will be notified when\n * the axes data changes\n */\n this.onAxisValueChangedObservable = new Observable();\n /**\n * Observers registered here will be triggered when the state of a button changes\n * State change is either pressed / touched / value\n */\n this.onButtonStateChangedObservable = new Observable();\n }\n /**\n * The current axes data. If this component has no axes it will still return an object { x: 0, y: 0 }\n */\n get axes() {\n return this._axes;\n }\n /**\n * Get the changes. Elements will be populated only if they changed with their previous and current value\n */\n get changes() {\n return this._changes;\n }\n /**\n * Return whether or not the component changed the last frame\n */\n get hasChanges() {\n return this._hasChanges;\n }\n /**\n * is the button currently pressed\n */\n get pressed() {\n return this._pressed;\n }\n /**\n * is the button currently touched\n */\n get touched() {\n return this._touched;\n }\n /**\n * Get the current value of this component\n */\n get value() {\n return this._currentValue;\n }\n /**\n * Dispose this component\n */\n dispose() {\n this.onAxisValueChangedObservable.clear();\n this.onButtonStateChangedObservable.clear();\n }\n /**\n * Are there axes correlating to this component\n * @returns true is axes data is available\n */\n isAxes() {\n return this._axesIndices.length !== 0;\n }\n /**\n * Is this component a button (hence - pressable)\n * @returns true if can be pressed\n */\n isButton() {\n return this._buttonIndex !== -1;\n }\n /**\n * update this component using the gamepad object it is in. Called on every frame\n * @param nativeController the native gamepad controller object\n */\n update(nativeController) {\n let buttonUpdated = false;\n let axesUpdate = false;\n this._hasChanges = false;\n this._changes = {};\n if (this.isButton()) {\n const button = nativeController.buttons[this._buttonIndex];\n // defensive, in case a profile was forced\n if (!button) {\n return;\n }\n if (this._currentValue !== button.value) {\n this.changes.value = {\n current: button.value,\n previous: this._currentValue,\n };\n buttonUpdated = true;\n this._currentValue = button.value;\n }\n if (this._touched !== button.touched) {\n this.changes.touched = {\n current: button.touched,\n previous: this._touched,\n };\n buttonUpdated = true;\n this._touched = button.touched;\n }\n if (this._pressed !== button.pressed) {\n this.changes.pressed = {\n current: button.pressed,\n previous: this._pressed,\n };\n buttonUpdated = true;\n this._pressed = button.pressed;\n }\n }\n if (this.isAxes()) {\n if (this._axes.x !== nativeController.axes[this._axesIndices[0]]) {\n this.changes.axes = {\n current: {\n x: nativeController.axes[this._axesIndices[0]],\n y: this._axes.y,\n },\n previous: {\n x: this._axes.x,\n y: this._axes.y,\n },\n };\n this._axes.x = nativeController.axes[this._axesIndices[0]];\n axesUpdate = true;\n }\n if (this._axes.y !== nativeController.axes[this._axesIndices[1]]) {\n if (this.changes.axes) {\n this.changes.axes.current.y = nativeController.axes[this._axesIndices[1]];\n }\n else {\n this.changes.axes = {\n current: {\n x: this._axes.x,\n y: nativeController.axes[this._axesIndices[1]],\n },\n previous: {\n x: this._axes.x,\n y: this._axes.y,\n },\n };\n }\n this._axes.y = nativeController.axes[this._axesIndices[1]];\n axesUpdate = true;\n }\n }\n if (buttonUpdated) {\n this._hasChanges = true;\n this.onButtonStateChangedObservable.notifyObservers(this);\n }\n if (axesUpdate) {\n this._hasChanges = true;\n this.onAxisValueChangedObservable.notifyObservers(this._axes);\n }\n }\n}\n/**\n * button component type\n */\nWebXRControllerComponent.BUTTON_TYPE = \"button\";\n/**\n * squeeze component type\n */\nWebXRControllerComponent.SQUEEZE_TYPE = \"squeeze\";\n/**\n * Thumbstick component type\n */\nWebXRControllerComponent.THUMBSTICK_TYPE = \"thumbstick\";\n/**\n * Touchpad component type\n */\nWebXRControllerComponent.TOUCHPAD_TYPE = \"touchpad\";\n/**\n * trigger component type\n */\nWebXRControllerComponent.TRIGGER_TYPE = \"trigger\";\n//# sourceMappingURL=webXRControllerComponent.js.map","import { WebXRControllerComponent } from \"./webXRControllerComponent.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { SceneLoader } from \"../../Loading/sceneLoader.js\";\nimport { Quaternion, Vector3 } from \"../../Maths/math.vector.js\";\nimport { Mesh } from \"../../Meshes/mesh.js\";\n/**\n * An Abstract Motion controller\n * This class receives an xrInput and a profile layout and uses those to initialize the components\n * Each component has an observable to check for changes in value and state\n */\nexport class WebXRAbstractMotionController {\n /**\n * constructs a new abstract motion controller\n * @param scene the scene to which the model of the controller will be added\n * @param layout The profile layout to load\n * @param gamepadObject The gamepad object correlating to this controller\n * @param handedness handedness (left/right/none) of this controller\n * @param _doNotLoadControllerMesh set this flag to ignore the mesh loading\n * @param _controllerCache a cache holding controller models already loaded in this session\n */\n constructor(\n // eslint-disable-next-line @typescript-eslint/naming-convention\n scene, \n // eslint-disable-next-line @typescript-eslint/naming-convention\n layout, \n /**\n * The gamepad object correlating to this controller\n */\n gamepadObject, \n /**\n * handedness (left/right/none) of this controller\n */\n handedness, \n /**\n * @internal\n */\n _doNotLoadControllerMesh = false, _controllerCache) {\n this.scene = scene;\n this.layout = layout;\n this.gamepadObject = gamepadObject;\n this.handedness = handedness;\n this._doNotLoadControllerMesh = _doNotLoadControllerMesh;\n this._controllerCache = _controllerCache;\n this._initComponent = (id) => {\n if (!id) {\n return;\n }\n const componentDef = this.layout.components[id];\n const type = componentDef.type;\n const buttonIndex = componentDef.gamepadIndices.button;\n // search for axes\n const axes = [];\n if (componentDef.gamepadIndices.xAxis !== undefined && componentDef.gamepadIndices.yAxis !== undefined) {\n axes.push(componentDef.gamepadIndices.xAxis, componentDef.gamepadIndices.yAxis);\n }\n this.components[id] = new WebXRControllerComponent(id, type, buttonIndex, axes);\n };\n this._modelReady = false;\n /**\n * A map of components (WebXRControllerComponent) in this motion controller\n * Components have a ComponentType and can also have both button and axis definitions\n */\n this.components = {};\n /**\n * Disable the model's animation. Can be set at any time.\n */\n this.disableAnimation = false;\n /**\n * Observers registered here will be triggered when the model of this controller is done loading\n */\n this.onModelLoadedObservable = new Observable();\n // initialize the components\n if (layout.components) {\n Object.keys(layout.components).forEach(this._initComponent);\n }\n // Model is loaded in WebXRInput\n }\n /**\n * Dispose this controller, the model mesh and all its components\n */\n dispose() {\n this.getComponentIds().forEach((id) => this.getComponent(id).dispose());\n if (this.rootMesh) {\n this.rootMesh.getChildren(undefined, true).forEach((node) => {\n node.setEnabled(false);\n });\n this.rootMesh.dispose(!!this._controllerCache, !this._controllerCache);\n }\n }\n /**\n * Returns all components of specific type\n * @param type the type to search for\n * @returns an array of components with this type\n */\n getAllComponentsOfType(type) {\n return this.getComponentIds()\n .map((id) => this.components[id])\n .filter((component) => component.type === type);\n }\n /**\n * get a component based an its component id as defined in layout.components\n * @param id the id of the component\n * @returns the component correlates to the id or undefined if not found\n */\n getComponent(id) {\n return this.components[id];\n }\n /**\n * Get the list of components available in this motion controller\n * @returns an array of strings correlating to available components\n */\n getComponentIds() {\n return Object.keys(this.components);\n }\n /**\n * Get the first component of specific type\n * @param type type of component to find\n * @returns a controller component or null if not found\n */\n getComponentOfType(type) {\n return this.getAllComponentsOfType(type)[0] || null;\n }\n /**\n * Get the main (Select) component of this controller as defined in the layout\n * @returns the main component of this controller\n */\n getMainComponent() {\n return this.getComponent(this.layout.selectComponentId);\n }\n /**\n * Loads the model correlating to this controller\n * When the mesh is loaded, the onModelLoadedObservable will be triggered\n * @returns A promise fulfilled with the result of the model loading\n */\n async loadModel() {\n const useGeneric = !this._getModelLoadingConstraints();\n let loadingParams = this._getGenericFilenameAndPath();\n // Checking if GLB loader is present\n if (useGeneric) {\n Logger.Warn(\"Falling back to generic models\");\n }\n else {\n loadingParams = this._getFilenameAndPath();\n }\n return new Promise((resolve, reject) => {\n const meshesLoaded = (meshes) => {\n if (useGeneric) {\n this._getGenericParentMesh(meshes);\n }\n else {\n this._setRootMesh(meshes);\n }\n this._processLoadedModel(meshes);\n this._modelReady = true;\n this.onModelLoadedObservable.notifyObservers(this);\n resolve(true);\n };\n if (this._controllerCache) {\n // look for it in the cache\n const found = this._controllerCache.filter((c) => {\n return c.filename === loadingParams.filename && c.path === loadingParams.path;\n });\n if (found[0]) {\n found[0].meshes.forEach((mesh) => mesh.setEnabled(true));\n meshesLoaded(found[0].meshes);\n return;\n // found, don't continue to load\n }\n }\n SceneLoader.ImportMesh(\"\", loadingParams.path, loadingParams.filename, this.scene, (meshes) => {\n if (this._controllerCache) {\n this._controllerCache.push(Object.assign(Object.assign({}, loadingParams), { meshes }));\n }\n meshesLoaded(meshes);\n }, null, (_scene, message) => {\n Logger.Log(message);\n Logger.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${loadingParams.path}${loadingParams.filename}`);\n reject(message);\n });\n });\n }\n /**\n * Update this model using the current XRFrame\n * @param xrFrame the current xr frame to use and update the model\n */\n updateFromXRFrame(xrFrame) {\n this.getComponentIds().forEach((id) => this.getComponent(id).update(this.gamepadObject));\n this.updateModel(xrFrame);\n }\n /**\n * Backwards compatibility due to a deeply-integrated typo\n */\n get handness() {\n return this.handedness;\n }\n /**\n * Pulse (vibrate) this controller\n * If the controller does not support pulses, this function will fail silently and return Promise directly after called\n * Consecutive calls to this function will cancel the last pulse call\n *\n * @param value the strength of the pulse in 0.0...1.0 range\n * @param duration Duration of the pulse in milliseconds\n * @param hapticActuatorIndex optional index of actuator (will usually be 0)\n * @returns a promise that will send true when the pulse has ended and false if the device doesn't support pulse or an error accrued\n */\n pulse(value, duration, hapticActuatorIndex = 0) {\n if (this.gamepadObject.hapticActuators && this.gamepadObject.hapticActuators[hapticActuatorIndex]) {\n return this.gamepadObject.hapticActuators[hapticActuatorIndex].pulse(value, duration);\n }\n else {\n return Promise.resolve(false);\n }\n }\n // Look through all children recursively. This will return null if no mesh exists with the given name.\n _getChildByName(node, name) {\n return node.getChildren((n) => n.name === name, false)[0];\n }\n // Look through only immediate children. This will return null if no mesh exists with the given name.\n _getImmediateChildByName(node, name) {\n return node.getChildren((n) => n.name == name, true)[0];\n }\n /**\n * Moves the axis on the controller mesh based on its current state\n * @param axisMap\n * @param axisValue the value of the axis which determines the meshes new position\n * @internal\n */\n _lerpTransform(axisMap, axisValue, fixValueCoordinates) {\n if (!axisMap.minMesh || !axisMap.maxMesh || !axisMap.valueMesh) {\n return;\n }\n if (!axisMap.minMesh.rotationQuaternion || !axisMap.maxMesh.rotationQuaternion || !axisMap.valueMesh.rotationQuaternion) {\n return;\n }\n // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)\n const lerpValue = fixValueCoordinates ? axisValue * 0.5 + 0.5 : axisValue;\n Quaternion.SlerpToRef(axisMap.minMesh.rotationQuaternion, axisMap.maxMesh.rotationQuaternion, lerpValue, axisMap.valueMesh.rotationQuaternion);\n Vector3.LerpToRef(axisMap.minMesh.position, axisMap.maxMesh.position, lerpValue, axisMap.valueMesh.position);\n }\n /**\n * Update the model itself with the current frame data\n * @param xrFrame the frame to use for updating the model mesh\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n updateModel(xrFrame) {\n if (!this._modelReady) {\n return;\n }\n this._updateModel(xrFrame);\n }\n _getGenericFilenameAndPath() {\n return {\n filename: \"generic.babylon\",\n path: \"https://controllers.babylonjs.com/generic/\",\n };\n }\n _getGenericParentMesh(meshes) {\n this.rootMesh = new Mesh(this.profileId + \" \" + this.handedness, this.scene);\n meshes.forEach((mesh) => {\n if (!mesh.parent) {\n mesh.isPickable = false;\n mesh.setParent(this.rootMesh);\n }\n });\n this.rootMesh.rotationQuaternion = Quaternion.FromEulerAngles(0, Math.PI, 0);\n }\n}\n//# sourceMappingURL=webXRAbstractMotionController.js.map","import { WebXRAbstractMotionController } from \"./webXRAbstractMotionController.js\";\nimport { Mesh } from \"../../Meshes/mesh.js\";\nimport { Quaternion } from \"../../Maths/math.vector.js\";\n/**\n * A generic trigger-only motion controller for WebXR\n */\nexport class WebXRGenericTriggerMotionController extends WebXRAbstractMotionController {\n constructor(scene, gamepadObject, handedness) {\n super(scene, GenericTriggerLayout[handedness], gamepadObject, handedness);\n this.profileId = WebXRGenericTriggerMotionController.ProfileId;\n }\n _getFilenameAndPath() {\n return {\n filename: \"generic.babylon\",\n path: \"https://controllers.babylonjs.com/generic/\",\n };\n }\n _getModelLoadingConstraints() {\n return true;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _processLoadedModel(meshes) {\n // nothing to do\n }\n _setRootMesh(meshes) {\n this.rootMesh = new Mesh(this.profileId + \" \" + this.handedness, this.scene);\n meshes.forEach((mesh) => {\n mesh.isPickable = false;\n if (!mesh.parent) {\n mesh.setParent(this.rootMesh);\n }\n });\n this.rootMesh.rotationQuaternion = Quaternion.FromEulerAngles(0, Math.PI, 0);\n }\n _updateModel() {\n // no-op\n }\n}\n/**\n * Static version of the profile id of this controller\n */\nWebXRGenericTriggerMotionController.ProfileId = \"generic-trigger\";\n// https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/generic/generic-trigger-touchpad-thumbstick.json\nconst GenericTriggerLayout = {\n left: {\n selectComponentId: \"xr-standard-trigger\",\n components: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n \"xr-standard-trigger\": {\n type: \"trigger\",\n gamepadIndices: {\n button: 0,\n },\n rootNodeName: \"xr_standard_trigger\",\n visualResponses: {},\n },\n },\n gamepadMapping: \"xr-standard\",\n rootNodeName: \"generic-trigger-left\",\n assetPath: \"left.glb\",\n },\n right: {\n selectComponentId: \"xr-standard-trigger\",\n components: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n \"xr-standard-trigger\": {\n type: \"trigger\",\n gamepadIndices: {\n button: 0,\n },\n rootNodeName: \"xr_standard_trigger\",\n visualResponses: {},\n },\n },\n gamepadMapping: \"xr-standard\",\n rootNodeName: \"generic-trigger-right\",\n assetPath: \"right.glb\",\n },\n none: {\n selectComponentId: \"xr-standard-trigger\",\n components: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n \"xr-standard-trigger\": {\n type: \"trigger\",\n gamepadIndices: {\n button: 0,\n },\n rootNodeName: \"xr_standard_trigger\",\n visualResponses: {},\n },\n },\n gamepadMapping: \"xr-standard\",\n rootNodeName: \"generic-trigger-none\",\n assetPath: \"none.glb\",\n },\n};\n//# sourceMappingURL=webXRGenericMotionController.js.map","import { WebXRAbstractMotionController } from \"./webXRAbstractMotionController.js\";\nimport { SceneLoader } from \"../../Loading/sceneLoader.js\";\nimport { Mesh } from \"../../Meshes/mesh.js\";\nimport { Axis, Space } from \"../../Maths/math.axis.js\";\nimport { Color3 } from \"../../Maths/math.color.js\";\nimport { WebXRControllerComponent } from \"./webXRControllerComponent.js\";\nimport { CreateSphere } from \"../../Meshes/Builders/sphereBuilder.js\";\nimport { StandardMaterial } from \"../../Materials/standardMaterial.js\";\nimport { Logger } from \"../../Misc/logger.js\";\n/**\n * A profiled motion controller has its profile loaded from an online repository.\n * The class is responsible of loading the model, mapping the keys and enabling model-animations\n */\nexport class WebXRProfiledMotionController extends WebXRAbstractMotionController {\n constructor(scene, xrInput, _profile, _repositoryUrl, \n // eslint-disable-next-line @typescript-eslint/naming-convention\n controllerCache) {\n super(scene, _profile.layouts[xrInput.handedness || \"none\"], xrInput.gamepad, xrInput.handedness, undefined, controllerCache);\n this._repositoryUrl = _repositoryUrl;\n this.controllerCache = controllerCache;\n this._buttonMeshMapping = {};\n this._touchDots = {};\n this.profileId = _profile.profileId;\n }\n dispose() {\n super.dispose();\n if (!this.controllerCache) {\n Object.keys(this._touchDots).forEach((visResKey) => {\n this._touchDots[visResKey].dispose();\n });\n }\n }\n _getFilenameAndPath() {\n return {\n filename: this.layout.assetPath,\n path: `${this._repositoryUrl}/profiles/${this.profileId}/`,\n };\n }\n _getModelLoadingConstraints() {\n const glbLoaded = SceneLoader.IsPluginForExtensionAvailable(\".glb\");\n if (!glbLoaded) {\n Logger.Warn(\"glTF / glb loader was not registered, using generic controller instead\");\n }\n return glbLoaded;\n }\n _processLoadedModel(_meshes) {\n this.getComponentIds().forEach((type) => {\n const componentInLayout = this.layout.components[type];\n this._buttonMeshMapping[type] = {\n mainMesh: this._getChildByName(this.rootMesh, componentInLayout.rootNodeName),\n states: {},\n };\n Object.keys(componentInLayout.visualResponses).forEach((visualResponseKey) => {\n const visResponse = componentInLayout.visualResponses[visualResponseKey];\n if (visResponse.valueNodeProperty === \"transform\") {\n this._buttonMeshMapping[type].states[visualResponseKey] = {\n valueMesh: this._getChildByName(this.rootMesh, visResponse.valueNodeName),\n minMesh: this._getChildByName(this.rootMesh, visResponse.minNodeName),\n maxMesh: this._getChildByName(this.rootMesh, visResponse.maxNodeName),\n };\n }\n else {\n // visibility, usually for touchpads\n const nameOfMesh = componentInLayout.type === WebXRControllerComponent.TOUCHPAD_TYPE && componentInLayout.touchPointNodeName\n ? componentInLayout.touchPointNodeName\n : visResponse.valueNodeName;\n this._buttonMeshMapping[type].states[visualResponseKey] = {\n valueMesh: this._getChildByName(this.rootMesh, nameOfMesh),\n };\n if (componentInLayout.type === WebXRControllerComponent.TOUCHPAD_TYPE && !this._touchDots[visualResponseKey]) {\n const dot = CreateSphere(visualResponseKey + \"dot\", {\n diameter: 0.0015,\n segments: 8,\n }, this.scene);\n dot.material = new StandardMaterial(visualResponseKey + \"mat\", this.scene);\n dot.material.diffuseColor = Color3.Red();\n dot.parent = this._buttonMeshMapping[type].states[visualResponseKey].valueMesh || null;\n dot.isVisible = false;\n this._touchDots[visualResponseKey] = dot;\n }\n }\n });\n });\n }\n _setRootMesh(meshes) {\n this.rootMesh = new Mesh(this.profileId + \"-\" + this.handedness, this.scene);\n this.rootMesh.isPickable = false;\n let rootMesh;\n // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'\n for (let i = 0; i < meshes.length; i++) {\n const mesh = meshes[i];\n mesh.isPickable = false;\n if (!mesh.parent) {\n // Handle root node, attach to the new parentMesh\n rootMesh = mesh;\n }\n }\n if (rootMesh) {\n rootMesh.setParent(this.rootMesh);\n }\n if (!this.scene.useRightHandedSystem) {\n this.rootMesh.rotate(Axis.Y, Math.PI, Space.WORLD);\n }\n }\n _updateModel(_xrFrame) {\n if (this.disableAnimation) {\n return;\n }\n this.getComponentIds().forEach((id) => {\n const component = this.getComponent(id);\n if (!component.hasChanges) {\n return;\n }\n const meshes = this._buttonMeshMapping[id];\n const componentInLayout = this.layout.components[id];\n Object.keys(componentInLayout.visualResponses).forEach((visualResponseKey) => {\n const visResponse = componentInLayout.visualResponses[visualResponseKey];\n let value = component.value;\n if (visResponse.componentProperty === \"xAxis\") {\n value = component.axes.x;\n }\n else if (visResponse.componentProperty === \"yAxis\") {\n value = component.axes.y;\n }\n if (visResponse.valueNodeProperty === \"transform\") {\n this._lerpTransform(meshes.states[visualResponseKey], value, visResponse.componentProperty !== \"button\");\n }\n else {\n // visibility\n const valueMesh = meshes.states[visualResponseKey].valueMesh;\n if (valueMesh) {\n valueMesh.isVisible = component.touched || component.pressed;\n }\n if (this._touchDots[visualResponseKey]) {\n this._touchDots[visualResponseKey].isVisible = component.touched || component.pressed;\n }\n }\n });\n });\n }\n}\n//# sourceMappingURL=webXRProfiledMotionController.js.map","import { WebXRGenericTriggerMotionController } from \"./webXRGenericMotionController.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nimport { WebXRProfiledMotionController } from \"./webXRProfiledMotionController.js\";\n/**\n * The MotionController Manager manages all registered motion controllers and loads the right one when needed.\n *\n * When this repository is complete: https://github.com/immersive-web/webxr-input-profiles/tree/master/packages/assets\n * it should be replaced with auto-loaded controllers.\n *\n * When using a model try to stay as generic as possible. Eventually there will be no need in any of the controller classes\n */\nconst controllerCache = [];\n/**\n * Motion controller manager is managing the different webxr profiles and makes sure the right\n * controller is being loaded.\n */\nexport class WebXRMotionControllerManager {\n /**\n * Clear the cache used for profile loading and reload when requested again\n */\n static ClearProfilesCache() {\n this._ProfilesList = null;\n this._ProfileLoadingPromises = {};\n }\n /**\n * Register the default fallbacks.\n * This function is called automatically when this file is imported.\n */\n static DefaultFallbacks() {\n this.RegisterFallbacksForProfileId(\"google-daydream\", [\"generic-touchpad\"]);\n this.RegisterFallbacksForProfileId(\"htc-vive-focus\", [\"generic-trigger-touchpad\"]);\n this.RegisterFallbacksForProfileId(\"htc-vive\", [\"generic-trigger-squeeze-touchpad\"]);\n this.RegisterFallbacksForProfileId(\"magicleap-one\", [\"generic-trigger-squeeze-touchpad\"]);\n this.RegisterFallbacksForProfileId(\"windows-mixed-reality\", [\"generic-trigger-squeeze-touchpad-thumbstick\"]);\n this.RegisterFallbacksForProfileId(\"microsoft-mixed-reality\", [\"windows-mixed-reality\", \"generic-trigger-squeeze-touchpad-thumbstick\"]);\n this.RegisterFallbacksForProfileId(\"oculus-go\", [\"generic-trigger-touchpad\"]);\n this.RegisterFallbacksForProfileId(\"oculus-touch-v2\", [\"oculus-touch\", \"generic-trigger-squeeze-thumbstick\"]);\n this.RegisterFallbacksForProfileId(\"oculus-touch\", [\"generic-trigger-squeeze-thumbstick\"]);\n this.RegisterFallbacksForProfileId(\"samsung-gearvr\", [\"windows-mixed-reality\", \"generic-trigger-squeeze-touchpad-thumbstick\"]);\n this.RegisterFallbacksForProfileId(\"samsung-odyssey\", [\"generic-touchpad\"]);\n this.RegisterFallbacksForProfileId(\"valve-index\", [\"generic-trigger-squeeze-touchpad-thumbstick\"]);\n this.RegisterFallbacksForProfileId(\"generic-hand-select\", [\"generic-trigger\"]);\n }\n /**\n * Find a fallback profile if the profile was not found. There are a few predefined generic profiles.\n * @param profileId the profile to which a fallback needs to be found\n * @returns an array with corresponding fallback profiles\n */\n static FindFallbackWithProfileId(profileId) {\n const returnArray = this._Fallbacks[profileId] || [];\n returnArray.unshift(profileId);\n return returnArray;\n }\n /**\n * When acquiring a new xrInput object (usually by the WebXRInput class), match it with the correct profile.\n * The order of search:\n *\n * 1) Iterate the profiles array of the xr input and try finding a corresponding motion controller\n * 2) (If not found) search in the gamepad id and try using it (legacy versions only)\n * 3) search for registered fallbacks (should be redundant, nonetheless it makes sense to check)\n * 4) return the generic trigger controller if none were found\n *\n * @param xrInput the xrInput to which a new controller is initialized\n * @param scene the scene to which the model will be added\n * @param forceProfile force a certain profile for this controller\n * @returns A promise that fulfils with the motion controller class for this profile id or the generic standard class if none was found\n */\n static GetMotionControllerWithXRInput(xrInput, scene, forceProfile) {\n const profileArray = [];\n if (forceProfile) {\n profileArray.push(forceProfile);\n }\n profileArray.push(...(xrInput.profiles || []));\n // emulator support\n if (profileArray.length && !profileArray[0]) {\n // remove the first \"undefined\" that the emulator is adding\n profileArray.pop();\n }\n // legacy support - try using the gamepad id\n if (xrInput.gamepad && xrInput.gamepad.id) {\n switch (xrInput.gamepad.id) {\n case xrInput.gamepad.id.match(/oculus touch/gi) ? xrInput.gamepad.id : undefined:\n // oculus in gamepad id\n profileArray.push(\"oculus-touch-v2\");\n break;\n }\n }\n // make sure microsoft/windows mixed reality works correctly\n const windowsMRIdx = profileArray.indexOf(\"windows-mixed-reality\");\n if (windowsMRIdx !== -1) {\n profileArray.splice(windowsMRIdx, 0, \"microsoft-mixed-reality\");\n }\n if (!profileArray.length) {\n profileArray.push(\"generic-trigger\");\n }\n if (this.UseOnlineRepository) {\n const firstFunction = this.PrioritizeOnlineRepository ? this._LoadProfileFromRepository : this._LoadProfilesFromAvailableControllers;\n const secondFunction = this.PrioritizeOnlineRepository ? this._LoadProfilesFromAvailableControllers : this._LoadProfileFromRepository;\n return firstFunction.call(this, profileArray, xrInput, scene).catch(() => {\n return secondFunction.call(this, profileArray, xrInput, scene);\n });\n }\n else {\n // use only available functions\n return this._LoadProfilesFromAvailableControllers(profileArray, xrInput, scene);\n }\n }\n /**\n * Register a new controller based on its profile. This function will be called by the controller classes themselves.\n *\n * If you are missing a profile, make sure it is imported in your source, otherwise it will not register.\n *\n * @param type the profile type to register\n * @param constructFunction the function to be called when loading this profile\n */\n static RegisterController(type, constructFunction) {\n this._AvailableControllers[type] = constructFunction;\n }\n /**\n * Register a fallback to a specific profile.\n * @param profileId the profileId that will receive the fallbacks\n * @param fallbacks A list of fallback profiles\n */\n static RegisterFallbacksForProfileId(profileId, fallbacks) {\n if (this._Fallbacks[profileId]) {\n this._Fallbacks[profileId].push(...fallbacks);\n }\n else {\n this._Fallbacks[profileId] = fallbacks;\n }\n }\n /**\n * Will update the list of profiles available in the repository\n * @returns a promise that resolves to a map of profiles available online\n */\n static UpdateProfilesList() {\n this._ProfilesList = Tools.LoadFileAsync(this.BaseRepositoryUrl + \"/profiles/profilesList.json\", false).then((data) => {\n return JSON.parse(data.toString());\n });\n return this._ProfilesList;\n }\n /**\n * Clear the controller's cache (usually happens at the end of a session)\n */\n static ClearControllerCache() {\n controllerCache.forEach((cacheItem) => {\n cacheItem.meshes.forEach((mesh) => {\n mesh.dispose(false, true);\n });\n });\n controllerCache.length = 0;\n }\n static _LoadProfileFromRepository(profileArray, xrInput, scene) {\n return Promise.resolve()\n .then(() => {\n if (!this._ProfilesList) {\n return this.UpdateProfilesList();\n }\n else {\n return this._ProfilesList;\n }\n })\n .then((profilesList) => {\n // load the right profile\n for (let i = 0; i < profileArray.length; ++i) {\n // defensive\n if (!profileArray[i]) {\n continue;\n }\n if (profilesList[profileArray[i]]) {\n return profileArray[i];\n }\n }\n throw new Error(`neither controller ${profileArray[0]} nor all fallbacks were found in the repository,`);\n })\n .then((profileToLoad) => {\n // load the profile\n if (!this._ProfileLoadingPromises[profileToLoad]) {\n this._ProfileLoadingPromises[profileToLoad] = Tools.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${profileToLoad}/profile.json`, false).then((data) => JSON.parse(data));\n }\n return this._ProfileLoadingPromises[profileToLoad];\n })\n .then((profile) => {\n return new WebXRProfiledMotionController(scene, xrInput, profile, this.BaseRepositoryUrl, this.DisableControllerCache ? undefined : controllerCache);\n });\n }\n static _LoadProfilesFromAvailableControllers(profileArray, xrInput, scene) {\n // check fallbacks\n for (let i = 0; i < profileArray.length; ++i) {\n // defensive\n if (!profileArray[i]) {\n continue;\n }\n const fallbacks = this.FindFallbackWithProfileId(profileArray[i]);\n for (let j = 0; j < fallbacks.length; ++j) {\n const constructionFunction = this._AvailableControllers[fallbacks[j]];\n if (constructionFunction) {\n return Promise.resolve(constructionFunction(xrInput, scene));\n }\n }\n }\n throw new Error(`no controller requested was found in the available controllers list`);\n }\n}\nWebXRMotionControllerManager._AvailableControllers = {};\nWebXRMotionControllerManager._Fallbacks = {};\n// cache for loading\nWebXRMotionControllerManager._ProfileLoadingPromises = {};\n/**\n * The base URL of the online controller repository. Can be changed at any time.\n */\nWebXRMotionControllerManager.BaseRepositoryUrl = \"https://immersive-web.github.io/webxr-input-profiles/packages/viewer/dist\";\n/**\n * Which repository gets priority - local or online\n */\nWebXRMotionControllerManager.PrioritizeOnlineRepository = true;\n/**\n * Use the online repository, or use only locally-defined controllers\n */\nWebXRMotionControllerManager.UseOnlineRepository = true;\n/**\n * Disable the controller cache and load the models each time a new WebXRProfileMotionController is loaded.\n * Defaults to true.\n */\nWebXRMotionControllerManager.DisableControllerCache = true;\n// register the generic profile(s) here so we will at least have them\nWebXRMotionControllerManager.RegisterController(WebXRGenericTriggerMotionController.ProfileId, (xrInput, scene) => {\n return new WebXRGenericTriggerMotionController(scene, xrInput.gamepad, xrInput.handedness);\n});\n// register fallbacks\nWebXRMotionControllerManager.DefaultFallbacks();\n//# sourceMappingURL=webXRMotionControllerManager.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { AbstractMesh } from \"../Meshes/abstractMesh.js\";\nimport { Quaternion, Vector3 } from \"../Maths/math.vector.js\";\nimport { WebXRMotionControllerManager } from \"./motionController/webXRMotionControllerManager.js\";\nimport { Tools } from \"../Misc/tools.js\";\nlet idCount = 0;\n/**\n * Represents an XR controller\n */\nexport class WebXRInputSource {\n /**\n * Creates the input source object\n * @see https://doc.babylonjs.com/features/featuresDeepDive/webXR/webXRInputControllerSupport\n * @param _scene the scene which the controller should be associated to\n * @param inputSource the underlying input source for the controller\n * @param _options options for this controller creation\n */\n constructor(_scene, \n /** The underlying input source for the controller */\n inputSource, _options = {}) {\n this._scene = _scene;\n this.inputSource = inputSource;\n this._options = _options;\n this._tmpVector = new Vector3();\n this._disposed = false;\n /**\n * Event that fires when the controller is removed/disposed.\n * The object provided as event data is this controller, after associated assets were disposed.\n * uniqueId is still available.\n */\n this.onDisposeObservable = new Observable();\n /**\n * Will be triggered when the mesh associated with the motion controller is done loading.\n * It is also possible that this will never trigger (!) if no mesh was loaded, or if the developer decides to load a different mesh\n * A shortened version of controller -> motion controller -> on mesh loaded.\n */\n this.onMeshLoadedObservable = new Observable();\n /**\n * Observers registered here will trigger when a motion controller profile was assigned to this xr controller\n */\n this.onMotionControllerInitObservable = new Observable();\n this._uniqueId = `controller-${idCount++}-${inputSource.targetRayMode}-${inputSource.handedness}`;\n this.pointer = new AbstractMesh(`${this._uniqueId}-pointer`, _scene);\n this.pointer.rotationQuaternion = new Quaternion();\n if (this.inputSource.gripSpace) {\n this.grip = new AbstractMesh(`${this._uniqueId}-grip`, this._scene);\n this.grip.rotationQuaternion = new Quaternion();\n }\n this._tmpVector.set(0, 0, this._scene.useRightHandedSystem ? -1.0 : 1.0);\n // for now only load motion controllers if gamepad object available\n if (this.inputSource.gamepad && this.inputSource.targetRayMode === \"tracked-pointer\") {\n WebXRMotionControllerManager.GetMotionControllerWithXRInput(inputSource, _scene, this._options.forceControllerProfile).then((motionController) => {\n this.motionController = motionController;\n this.onMotionControllerInitObservable.notifyObservers(motionController);\n // should the model be loaded?\n if (!this._options.doNotLoadControllerMesh && !this.motionController._doNotLoadControllerMesh) {\n this.motionController.loadModel().then((success) => {\n var _a;\n if (success && this.motionController && this.motionController.rootMesh) {\n if (this._options.renderingGroupId) {\n // anything other than 0?\n this.motionController.rootMesh.renderingGroupId = this._options.renderingGroupId;\n this.motionController.rootMesh.getChildMeshes(false).forEach((mesh) => (mesh.renderingGroupId = this._options.renderingGroupId));\n }\n this.onMeshLoadedObservable.notifyObservers(this.motionController.rootMesh);\n this.motionController.rootMesh.parent = this.grip || this.pointer;\n this.motionController.disableAnimation = !!this._options.disableMotionControllerAnimation;\n }\n // make sure to dispose is the controller is already disposed\n if (this._disposed) {\n (_a = this.motionController) === null || _a === void 0 ? void 0 : _a.dispose();\n }\n });\n }\n }, () => {\n Tools.Warn(`Could not find a matching motion controller for the registered input source`);\n });\n }\n }\n /**\n * Get this controllers unique id\n */\n get uniqueId() {\n return this._uniqueId;\n }\n /**\n * Disposes of the object\n */\n dispose() {\n if (this.grip) {\n this.grip.dispose(true);\n }\n if (this.motionController) {\n this.motionController.dispose();\n }\n this.pointer.dispose(true);\n this.onMotionControllerInitObservable.clear();\n this.onMeshLoadedObservable.clear();\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n this._disposed = true;\n }\n /**\n * Gets a world space ray coming from the pointer or grip\n * @param result the resulting ray\n * @param gripIfAvailable use the grip mesh instead of the pointer, if available\n */\n getWorldPointerRayToRef(result, gripIfAvailable = false) {\n const object = gripIfAvailable && this.grip ? this.grip : this.pointer;\n Vector3.TransformNormalToRef(this._tmpVector, object.getWorldMatrix(), result.direction);\n result.direction.normalize();\n result.origin.copyFrom(object.absolutePosition);\n result.length = 1000;\n }\n /**\n * Updates the controller pose based on the given XRFrame\n * @param xrFrame xr frame to update the pose with\n * @param referenceSpace reference space to use\n * @param xrCamera the xr camera, used for parenting\n */\n updateFromXRFrame(xrFrame, referenceSpace, xrCamera) {\n const pose = xrFrame.getPose(this.inputSource.targetRaySpace, referenceSpace);\n this._lastXRPose = pose;\n // Update the pointer mesh\n if (pose) {\n const pos = pose.transform.position;\n this.pointer.position.set(pos.x, pos.y, pos.z);\n const orientation = pose.transform.orientation;\n this.pointer.rotationQuaternion.set(orientation.x, orientation.y, orientation.z, orientation.w);\n if (!this._scene.useRightHandedSystem) {\n this.pointer.position.z *= -1;\n this.pointer.rotationQuaternion.z *= -1;\n this.pointer.rotationQuaternion.w *= -1;\n }\n this.pointer.parent = xrCamera.parent;\n }\n // Update the grip mesh if it exists\n if (this.inputSource.gripSpace && this.grip) {\n const pose = xrFrame.getPose(this.inputSource.gripSpace, referenceSpace);\n if (pose) {\n const pos = pose.transform.position;\n const orientation = pose.transform.orientation;\n this.grip.position.set(pos.x, pos.y, pos.z);\n this.grip.rotationQuaternion.set(orientation.x, orientation.y, orientation.z, orientation.w);\n if (!this._scene.useRightHandedSystem) {\n this.grip.position.z *= -1;\n this.grip.rotationQuaternion.z *= -1;\n this.grip.rotationQuaternion.w *= -1;\n }\n }\n this.grip.parent = xrCamera.parent;\n }\n if (this.motionController) {\n // either update buttons only or also position, if in gamepad mode\n this.motionController.updateFromXRFrame(xrFrame);\n }\n }\n}\n//# sourceMappingURL=webXRInputSource.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { WebXRInputSource } from \"./webXRInputSource.js\";\nimport { WebXRMotionControllerManager } from \"./motionController/webXRMotionControllerManager.js\";\n/**\n * XR input used to track XR inputs such as controllers/rays\n */\nexport class WebXRInput {\n /**\n * Initializes the WebXRInput\n * @param xrSessionManager the xr session manager for this session\n * @param xrCamera the WebXR camera for this session. Mainly used for teleportation\n * @param _options = initialization options for this xr input\n */\n constructor(\n /**\n * the xr session manager for this session\n */\n xrSessionManager, \n /**\n * the WebXR camera for this session. Mainly used for teleportation\n */\n xrCamera, _options = {}) {\n this.xrSessionManager = xrSessionManager;\n this.xrCamera = xrCamera;\n this._options = _options;\n /**\n * XR controllers being tracked\n */\n this.controllers = [];\n /**\n * Event when a controller has been connected/added\n */\n this.onControllerAddedObservable = new Observable();\n /**\n * Event when a controller has been removed/disconnected\n */\n this.onControllerRemovedObservable = new Observable();\n this._onInputSourcesChange = (event) => {\n this._addAndRemoveControllers(event.added, event.removed);\n };\n // Remove controllers when exiting XR\n this._sessionEndedObserver = this.xrSessionManager.onXRSessionEnded.add(() => {\n this._addAndRemoveControllers([], this.controllers.map((c) => {\n return c.inputSource;\n }));\n });\n this._sessionInitObserver = this.xrSessionManager.onXRSessionInit.add((session) => {\n session.addEventListener(\"inputsourceschange\", this._onInputSourcesChange);\n });\n this._frameObserver = this.xrSessionManager.onXRFrameObservable.add((frame) => {\n // Update controller pose info\n this.controllers.forEach((controller) => {\n controller.updateFromXRFrame(frame, this.xrSessionManager.referenceSpace, this.xrCamera);\n });\n });\n if (this._options.customControllersRepositoryURL) {\n WebXRMotionControllerManager.BaseRepositoryUrl = this._options.customControllersRepositoryURL;\n }\n WebXRMotionControllerManager.UseOnlineRepository = !this._options.disableOnlineControllerRepository;\n if (WebXRMotionControllerManager.UseOnlineRepository) {\n // pre-load the profiles list to load the controllers quicker afterwards\n try {\n WebXRMotionControllerManager.UpdateProfilesList().catch(() => {\n WebXRMotionControllerManager.UseOnlineRepository = false;\n });\n }\n catch (e) {\n WebXRMotionControllerManager.UseOnlineRepository = false;\n }\n }\n }\n _addAndRemoveControllers(addInputs, removeInputs) {\n // Add controllers if they don't already exist\n const sources = this.controllers.map((c) => {\n return c.inputSource;\n });\n for (const input of addInputs) {\n if (sources.indexOf(input) === -1) {\n const controller = new WebXRInputSource(this.xrSessionManager.scene, input, Object.assign(Object.assign({}, (this._options.controllerOptions || {})), { forceControllerProfile: this._options.forceInputProfile, doNotLoadControllerMesh: this._options.doNotLoadControllerMeshes, disableMotionControllerAnimation: this._options.disableControllerAnimation }));\n this.controllers.push(controller);\n this.onControllerAddedObservable.notifyObservers(controller);\n }\n }\n // Remove and dispose of controllers to be disposed\n const keepControllers = [];\n const removedControllers = [];\n this.controllers.forEach((c) => {\n if (removeInputs.indexOf(c.inputSource) === -1) {\n keepControllers.push(c);\n }\n else {\n removedControllers.push(c);\n }\n });\n this.controllers = keepControllers;\n removedControllers.forEach((c) => {\n this.onControllerRemovedObservable.notifyObservers(c);\n c.dispose();\n });\n }\n /**\n * Disposes of the object\n */\n dispose() {\n this.controllers.forEach((c) => {\n c.dispose();\n });\n this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver);\n this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver);\n this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver);\n this.onControllerAddedObservable.clear();\n this.onControllerRemovedObservable.clear();\n // clear the controller cache\n WebXRMotionControllerManager.ClearControllerCache();\n }\n}\n//# sourceMappingURL=webXRInput.js.map","import { WebXRFeaturesManager, WebXRFeatureName } from \"../webXRFeaturesManager.js\";\nimport { Matrix, Vector3 } from \"../../Maths/math.vector.js\";\nimport { Color3 } from \"../../Maths/math.color.js\";\nimport { Axis } from \"../../Maths/math.axis.js\";\nimport { StandardMaterial } from \"../../Materials/standardMaterial.js\";\nimport { CreateCylinder } from \"../../Meshes/Builders/cylinderBuilder.js\";\nimport { CreateTorus } from \"../../Meshes/Builders/torusBuilder.js\";\nimport { Ray } from \"../../Culling/ray.js\";\nimport { PickingInfo } from \"../../Collisions/pickingInfo.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nimport { UtilityLayerRenderer } from \"../../Rendering/utilityLayerRenderer.js\";\nimport { Viewport } from \"../../Maths/math.viewport.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * A module that will enable pointer selection for motion controllers of XR Input Sources\n */\nexport class WebXRControllerPointerSelection extends WebXRAbstractFeature {\n /**\n * constructs a new background remover module\n * @param _xrSessionManager the session manager for this module\n * @param _options read-only options to be used in this module\n */\n constructor(_xrSessionManager, _options) {\n super(_xrSessionManager);\n this._options = _options;\n this._attachController = (xrController) => {\n if (this._controllers[xrController.uniqueId]) {\n // already attached\n return;\n }\n const { laserPointer, selectionMesh } = this._generateNewMeshPair(xrController.pointer);\n // get two new meshes\n this._controllers[xrController.uniqueId] = {\n xrController,\n laserPointer,\n selectionMesh,\n meshUnderPointer: null,\n pick: null,\n tmpRay: new Ray(new Vector3(), new Vector3()),\n disabledByNearInteraction: false,\n id: WebXRControllerPointerSelection._IdCounter++,\n };\n if (this._attachedController) {\n if (!this._options.enablePointerSelectionOnAllControllers &&\n this._options.preferredHandedness &&\n xrController.inputSource.handedness === this._options.preferredHandedness) {\n this._attachedController = xrController.uniqueId;\n }\n }\n else {\n if (!this._options.enablePointerSelectionOnAllControllers) {\n this._attachedController = xrController.uniqueId;\n }\n }\n switch (xrController.inputSource.targetRayMode) {\n case \"tracked-pointer\":\n return this._attachTrackedPointerRayMode(xrController);\n case \"gaze\":\n return this._attachGazeMode(xrController);\n case \"screen\":\n return this._attachScreenRayMode(xrController);\n }\n };\n this._controllers = {};\n this._tmpVectorForPickCompare = new Vector3();\n /**\n * Disable lighting on the laser pointer (so it will always be visible)\n */\n this.disablePointerLighting = true;\n /**\n * Disable lighting on the selection mesh (so it will always be visible)\n */\n this.disableSelectionMeshLighting = true;\n /**\n * Should the laser pointer be displayed\n */\n this.displayLaserPointer = true;\n /**\n * Should the selection mesh be displayed (The ring at the end of the laser pointer)\n */\n this.displaySelectionMesh = true;\n /**\n * This color will be set to the laser pointer when selection is triggered\n */\n this.laserPointerPickedColor = new Color3(0.9, 0.9, 0.9);\n /**\n * Default color of the laser pointer\n */\n this.laserPointerDefaultColor = new Color3(0.7, 0.7, 0.7);\n /**\n * default color of the selection ring\n */\n this.selectionMeshDefaultColor = new Color3(0.8, 0.8, 0.8);\n /**\n * This color will be applied to the selection ring when selection is triggered\n */\n this.selectionMeshPickedColor = new Color3(0.3, 0.3, 1.0);\n this._identityMatrix = Matrix.Identity();\n this._screenCoordinatesRef = Vector3.Zero();\n this._viewportRef = new Viewport(0, 0, 0, 0);\n this._scene = this._xrSessionManager.scene;\n }\n /**\n * attach this feature\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n attach() {\n if (!super.attach()) {\n return false;\n }\n this._options.xrInput.controllers.forEach(this._attachController);\n this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController);\n this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, (controller) => {\n // REMOVE the controller\n this._detachController(controller.uniqueId);\n });\n this._scene.constantlyUpdateMeshUnderPointer = true;\n if (this._options.gazeCamera) {\n const webXRCamera = this._options.gazeCamera;\n const { laserPointer, selectionMesh } = this._generateNewMeshPair(webXRCamera);\n this._controllers[\"camera\"] = {\n webXRCamera,\n laserPointer,\n selectionMesh,\n meshUnderPointer: null,\n pick: null,\n tmpRay: new Ray(new Vector3(), new Vector3()),\n disabledByNearInteraction: false,\n id: WebXRControllerPointerSelection._IdCounter++,\n };\n this._attachGazeMode();\n }\n return true;\n }\n /**\n * detach this feature.\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n detach() {\n if (!super.detach()) {\n return false;\n }\n Object.keys(this._controllers).forEach((controllerId) => {\n this._detachController(controllerId);\n });\n return true;\n }\n /**\n * Will get the mesh under a specific pointer.\n * `scene.meshUnderPointer` will only return one mesh - either left or right.\n * @param controllerId the controllerId to check\n * @returns The mesh under pointer or null if no mesh is under the pointer\n */\n getMeshUnderPointer(controllerId) {\n if (this._controllers[controllerId]) {\n return this._controllers[controllerId].meshUnderPointer;\n }\n else {\n return null;\n }\n }\n /**\n * Get the xr controller that correlates to the pointer id in the pointer event\n *\n * @param id the pointer id to search for\n * @returns the controller that correlates to this id or null if not found\n */\n getXRControllerByPointerId(id) {\n const keys = Object.keys(this._controllers);\n for (let i = 0; i < keys.length; ++i) {\n if (this._controllers[keys[i]].id === id) {\n return this._controllers[keys[i]].xrController || null;\n }\n }\n return null;\n }\n /**\n * @internal\n */\n _getPointerSelectionDisabledByPointerId(id) {\n const keys = Object.keys(this._controllers);\n for (let i = 0; i < keys.length; ++i) {\n if (this._controllers[keys[i]].id === id) {\n return this._controllers[keys[i]].disabledByNearInteraction;\n }\n }\n return true;\n }\n /**\n * @internal\n */\n _setPointerSelectionDisabledByPointerId(id, state) {\n const keys = Object.keys(this._controllers);\n for (let i = 0; i < keys.length; ++i) {\n if (this._controllers[keys[i]].id === id) {\n this._controllers[keys[i]].disabledByNearInteraction = state;\n return;\n }\n }\n }\n _onXRFrame(_xrFrame) {\n Object.keys(this._controllers).forEach((id) => {\n // only do this for the selected pointer\n const controllerData = this._controllers[id];\n if ((!this._options.enablePointerSelectionOnAllControllers && id !== this._attachedController) || controllerData.disabledByNearInteraction) {\n controllerData.selectionMesh.isVisible = false;\n controllerData.laserPointer.isVisible = false;\n controllerData.pick = null;\n return;\n }\n controllerData.laserPointer.isVisible = this.displayLaserPointer;\n let controllerGlobalPosition;\n // Every frame check collisions/input\n if (controllerData.xrController) {\n controllerGlobalPosition = controllerData.xrController.pointer.position;\n controllerData.xrController.getWorldPointerRayToRef(controllerData.tmpRay);\n }\n else if (controllerData.webXRCamera) {\n controllerGlobalPosition = controllerData.webXRCamera.position;\n controllerData.webXRCamera.getForwardRayToRef(controllerData.tmpRay);\n }\n else {\n return;\n }\n if (this._options.maxPointerDistance) {\n controllerData.tmpRay.length = this._options.maxPointerDistance;\n }\n // update pointerX and pointerY of the scene. Only if the flag is set to true!\n if (!this._options.disableScenePointerVectorUpdate && controllerGlobalPosition) {\n const scene = this._xrSessionManager.scene;\n const camera = this._options.xrInput.xrCamera;\n if (camera) {\n camera.viewport.toGlobalToRef(scene.getEngine().getRenderWidth(), scene.getEngine().getRenderHeight(), this._viewportRef);\n Vector3.ProjectToRef(controllerGlobalPosition, this._identityMatrix, scene.getTransformMatrix(), this._viewportRef, this._screenCoordinatesRef);\n // stay safe\n if (typeof this._screenCoordinatesRef.x === \"number\" &&\n typeof this._screenCoordinatesRef.y === \"number\" &&\n !isNaN(this._screenCoordinatesRef.x) &&\n !isNaN(this._screenCoordinatesRef.y)) {\n scene.pointerX = this._screenCoordinatesRef.x;\n scene.pointerY = this._screenCoordinatesRef.y;\n controllerData.screenCoordinates = {\n x: this._screenCoordinatesRef.x,\n y: this._screenCoordinatesRef.y,\n };\n }\n }\n }\n let utilityScenePick = null;\n if (this._utilityLayerScene) {\n utilityScenePick = this._utilityLayerScene.pickWithRay(controllerData.tmpRay, this._utilityLayerScene.pointerMovePredicate || this.raySelectionPredicate);\n }\n const originalScenePick = this._scene.pickWithRay(controllerData.tmpRay, this._scene.pointerMovePredicate || this.raySelectionPredicate);\n if (!utilityScenePick || !utilityScenePick.hit) {\n // No hit in utility scene\n controllerData.pick = originalScenePick;\n }\n else if (!originalScenePick || !originalScenePick.hit) {\n // No hit in original scene\n controllerData.pick = utilityScenePick;\n }\n else if (utilityScenePick.distance < originalScenePick.distance) {\n // Hit is closer in utility scene\n controllerData.pick = utilityScenePick;\n }\n else {\n // Hit is closer in original scene\n controllerData.pick = originalScenePick;\n }\n if (controllerData.pick && controllerData.xrController) {\n controllerData.pick.aimTransform = controllerData.xrController.pointer;\n controllerData.pick.gripTransform = controllerData.xrController.grip || null;\n }\n const pick = controllerData.pick;\n if (pick && pick.pickedPoint && pick.hit) {\n // Update laser state\n this._updatePointerDistance(controllerData.laserPointer, pick.distance);\n // Update cursor state\n controllerData.selectionMesh.position.copyFrom(pick.pickedPoint);\n controllerData.selectionMesh.scaling.x = Math.sqrt(pick.distance);\n controllerData.selectionMesh.scaling.y = Math.sqrt(pick.distance);\n controllerData.selectionMesh.scaling.z = Math.sqrt(pick.distance);\n // To avoid z-fighting\n const pickNormal = this._convertNormalToDirectionOfRay(pick.getNormal(true), controllerData.tmpRay);\n const deltaFighting = 0.001;\n controllerData.selectionMesh.position.copyFrom(pick.pickedPoint);\n if (pickNormal) {\n const axis1 = Vector3.Cross(Axis.Y, pickNormal);\n const axis2 = Vector3.Cross(pickNormal, axis1);\n Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, controllerData.selectionMesh.rotation);\n controllerData.selectionMesh.position.addInPlace(pickNormal.scale(deltaFighting));\n }\n controllerData.selectionMesh.isVisible = true && this.displaySelectionMesh;\n controllerData.meshUnderPointer = pick.pickedMesh;\n }\n else {\n controllerData.selectionMesh.isVisible = false;\n this._updatePointerDistance(controllerData.laserPointer, 1);\n controllerData.meshUnderPointer = null;\n }\n });\n }\n get _utilityLayerScene() {\n return this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene;\n }\n _attachGazeMode(xrController) {\n const controllerData = this._controllers[(xrController && xrController.uniqueId) || \"camera\"];\n // attached when touched, detaches when raised\n const timeToSelect = this._options.timeToSelect || 3000;\n const sceneToRenderTo = this._options.useUtilityLayer ? this._utilityLayerScene : this._scene;\n let oldPick = new PickingInfo();\n const discMesh = CreateTorus(\"selection\", {\n diameter: 0.0035 * 15,\n thickness: 0.0025 * 6,\n tessellation: 20,\n }, sceneToRenderTo);\n discMesh.isVisible = false;\n discMesh.isPickable = false;\n discMesh.parent = controllerData.selectionMesh;\n let timer = 0;\n let downTriggered = false;\n const pointerEventInit = {\n pointerId: controllerData.id,\n pointerType: \"xr\",\n };\n controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {\n if (!controllerData.pick) {\n return;\n }\n this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates);\n controllerData.laserPointer.material.alpha = 0;\n discMesh.isVisible = false;\n if (controllerData.pick.hit) {\n if (!this._pickingMoved(oldPick, controllerData.pick)) {\n if (timer > timeToSelect / 10) {\n discMesh.isVisible = true;\n }\n timer += this._scene.getEngine().getDeltaTime();\n if (timer >= timeToSelect) {\n this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);\n // this pointerdown event is not setting the controllerData.pointerDownTriggered to avoid a pointerUp event when this feature is detached\n downTriggered = true;\n // pointer up right after down, if disable on touch out\n if (this._options.disablePointerUpOnTouchOut) {\n this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);\n }\n discMesh.isVisible = false;\n }\n else {\n const scaleFactor = 1 - timer / timeToSelect;\n discMesh.scaling.set(scaleFactor, scaleFactor, scaleFactor);\n }\n }\n else {\n if (downTriggered) {\n if (!this._options.disablePointerUpOnTouchOut) {\n this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);\n }\n }\n downTriggered = false;\n timer = 0;\n }\n }\n else {\n downTriggered = false;\n timer = 0;\n }\n this._scene.simulatePointerMove(controllerData.pick, pointerEventInit);\n oldPick = controllerData.pick;\n });\n if (this._options.renderingGroupId !== undefined) {\n discMesh.renderingGroupId = this._options.renderingGroupId;\n }\n if (xrController) {\n xrController.onDisposeObservable.addOnce(() => {\n if (controllerData.pick && !this._options.disablePointerUpOnTouchOut && downTriggered) {\n this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);\n controllerData.finalPointerUpTriggered = true;\n }\n discMesh.dispose();\n });\n }\n }\n _attachScreenRayMode(xrController) {\n const controllerData = this._controllers[xrController.uniqueId];\n let downTriggered = false;\n const pointerEventInit = {\n pointerId: controllerData.id,\n pointerType: \"xr\",\n };\n controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {\n this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates);\n if (!controllerData.pick || (this._options.disablePointerUpOnTouchOut && downTriggered)) {\n return;\n }\n if (!downTriggered) {\n this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);\n controllerData.pointerDownTriggered = true;\n downTriggered = true;\n if (this._options.disablePointerUpOnTouchOut) {\n this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);\n }\n }\n else {\n this._scene.simulatePointerMove(controllerData.pick, pointerEventInit);\n }\n });\n xrController.onDisposeObservable.addOnce(() => {\n this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates);\n this._xrSessionManager.runInXRFrame(() => {\n if (controllerData.pick && !controllerData.finalPointerUpTriggered && downTriggered && !this._options.disablePointerUpOnTouchOut) {\n this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);\n controllerData.finalPointerUpTriggered = true;\n }\n });\n });\n }\n _attachTrackedPointerRayMode(xrController) {\n const controllerData = this._controllers[xrController.uniqueId];\n if (this._options.forceGazeMode) {\n return this._attachGazeMode(xrController);\n }\n const pointerEventInit = {\n pointerId: controllerData.id,\n pointerType: \"xr\",\n };\n controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {\n controllerData.laserPointer.material.disableLighting = this.disablePointerLighting;\n controllerData.selectionMesh.material.disableLighting = this.disableSelectionMeshLighting;\n if (controllerData.pick) {\n this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates);\n this._scene.simulatePointerMove(controllerData.pick, pointerEventInit);\n }\n });\n if (xrController.inputSource.gamepad) {\n const init = (motionController) => {\n if (this._options.overrideButtonId) {\n controllerData.selectionComponent = motionController.getComponent(this._options.overrideButtonId);\n }\n if (!controllerData.selectionComponent) {\n controllerData.selectionComponent = motionController.getMainComponent();\n }\n controllerData.onButtonChangedObserver = controllerData.selectionComponent.onButtonStateChangedObservable.add((component) => {\n if (component.changes.pressed) {\n const pressed = component.changes.pressed.current;\n if (controllerData.pick) {\n if (this._options.enablePointerSelectionOnAllControllers || xrController.uniqueId === this._attachedController) {\n this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates);\n if (pressed) {\n this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);\n controllerData.pointerDownTriggered = true;\n controllerData.selectionMesh.material.emissiveColor = this.selectionMeshPickedColor;\n controllerData.laserPointer.material.emissiveColor = this.laserPointerPickedColor;\n }\n else {\n this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);\n controllerData.selectionMesh.material.emissiveColor = this.selectionMeshDefaultColor;\n controllerData.laserPointer.material.emissiveColor = this.laserPointerDefaultColor;\n }\n }\n }\n else {\n if (pressed && !this._options.enablePointerSelectionOnAllControllers && !this._options.disableSwitchOnClick) {\n this._attachedController = xrController.uniqueId;\n }\n }\n }\n });\n };\n if (xrController.motionController) {\n init(xrController.motionController);\n }\n else {\n xrController.onMotionControllerInitObservable.add(init);\n }\n }\n else {\n // use the select and squeeze events\n const selectStartListener = (event) => {\n this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates);\n if (controllerData.xrController && event.inputSource === controllerData.xrController.inputSource && controllerData.pick) {\n this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);\n controllerData.pointerDownTriggered = true;\n controllerData.selectionMesh.material.emissiveColor = this.selectionMeshPickedColor;\n controllerData.laserPointer.material.emissiveColor = this.laserPointerPickedColor;\n }\n };\n const selectEndListener = (event) => {\n this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates);\n if (controllerData.xrController && event.inputSource === controllerData.xrController.inputSource && controllerData.pick) {\n this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);\n controllerData.selectionMesh.material.emissiveColor = this.selectionMeshDefaultColor;\n controllerData.laserPointer.material.emissiveColor = this.laserPointerDefaultColor;\n }\n };\n controllerData.eventListeners = {\n selectend: selectEndListener,\n selectstart: selectStartListener,\n };\n this._xrSessionManager.session.addEventListener(\"selectstart\", selectStartListener);\n this._xrSessionManager.session.addEventListener(\"selectend\", selectEndListener);\n }\n }\n _convertNormalToDirectionOfRay(normal, ray) {\n if (normal) {\n const angle = Math.acos(Vector3.Dot(normal, ray.direction));\n if (angle < Math.PI / 2) {\n normal.scaleInPlace(-1);\n }\n }\n return normal;\n }\n _detachController(xrControllerUniqueId) {\n const controllerData = this._controllers[xrControllerUniqueId];\n if (!controllerData) {\n return;\n }\n if (controllerData.selectionComponent) {\n if (controllerData.onButtonChangedObserver) {\n controllerData.selectionComponent.onButtonStateChangedObservable.remove(controllerData.onButtonChangedObserver);\n }\n }\n if (controllerData.onFrameObserver) {\n this._xrSessionManager.onXRFrameObservable.remove(controllerData.onFrameObserver);\n }\n if (controllerData.eventListeners) {\n Object.keys(controllerData.eventListeners).forEach((eventName) => {\n const func = controllerData.eventListeners && controllerData.eventListeners[eventName];\n if (func) {\n // For future reference - this is an issue in the WebXR typings.\n this._xrSessionManager.session.removeEventListener(eventName, func);\n }\n });\n }\n if (!controllerData.finalPointerUpTriggered && controllerData.pointerDownTriggered) {\n // Stay safe and fire a pointerup, in case it wasn't already triggered\n const pointerEventInit = {\n pointerId: controllerData.id,\n pointerType: \"xr\",\n };\n this._xrSessionManager.runInXRFrame(() => {\n this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates);\n this._scene.simulatePointerUp(controllerData.pick || new PickingInfo(), pointerEventInit);\n controllerData.finalPointerUpTriggered = true;\n });\n }\n this._xrSessionManager.scene.onBeforeRenderObservable.addOnce(() => {\n try {\n controllerData.selectionMesh.dispose();\n controllerData.laserPointer.dispose();\n // remove from the map\n delete this._controllers[xrControllerUniqueId];\n if (this._attachedController === xrControllerUniqueId) {\n // check for other controllers\n const keys = Object.keys(this._controllers);\n if (keys.length) {\n this._attachedController = keys[0];\n }\n else {\n this._attachedController = \"\";\n }\n }\n }\n catch (e) {\n Tools.Warn(\"controller already detached.\");\n }\n });\n }\n _generateNewMeshPair(meshParent) {\n const sceneToRenderTo = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._scene;\n const laserPointer = this._options.customLasterPointerMeshGenerator\n ? this._options.customLasterPointerMeshGenerator()\n : CreateCylinder(\"laserPointer\", {\n height: 1,\n diameterTop: 0.0002,\n diameterBottom: 0.004,\n tessellation: 20,\n subdivisions: 1,\n }, sceneToRenderTo);\n laserPointer.parent = meshParent;\n const laserPointerMaterial = new StandardMaterial(\"laserPointerMat\", sceneToRenderTo);\n laserPointerMaterial.emissiveColor = this.laserPointerDefaultColor;\n laserPointerMaterial.alpha = 0.7;\n laserPointer.material = laserPointerMaterial;\n laserPointer.rotation.x = Math.PI / 2;\n this._updatePointerDistance(laserPointer, 1);\n laserPointer.isPickable = false;\n laserPointer.isVisible = false;\n // Create a gaze tracker for the XR controller\n const selectionMesh = this._options.customSelectionMeshGenerator\n ? this._options.customSelectionMeshGenerator()\n : CreateTorus(\"gazeTracker\", {\n diameter: 0.0035 * 3,\n thickness: 0.0025 * 3,\n tessellation: 20,\n }, sceneToRenderTo);\n selectionMesh.bakeCurrentTransformIntoVertices();\n selectionMesh.isPickable = false;\n selectionMesh.isVisible = false;\n const targetMat = new StandardMaterial(\"targetMat\", sceneToRenderTo);\n targetMat.specularColor = Color3.Black();\n targetMat.emissiveColor = this.selectionMeshDefaultColor;\n targetMat.backFaceCulling = false;\n selectionMesh.material = targetMat;\n if (this._options.renderingGroupId !== undefined) {\n laserPointer.renderingGroupId = this._options.renderingGroupId;\n selectionMesh.renderingGroupId = this._options.renderingGroupId;\n }\n return {\n laserPointer,\n selectionMesh,\n };\n }\n _pickingMoved(oldPick, newPick) {\n var _a;\n if (!oldPick.hit || !newPick.hit) {\n return true;\n }\n if (!oldPick.pickedMesh || !oldPick.pickedPoint || !newPick.pickedMesh || !newPick.pickedPoint) {\n return true;\n }\n if (oldPick.pickedMesh !== newPick.pickedMesh) {\n return true;\n }\n (_a = oldPick.pickedPoint) === null || _a === void 0 ? void 0 : _a.subtractToRef(newPick.pickedPoint, this._tmpVectorForPickCompare);\n this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x), Math.abs(this._tmpVectorForPickCompare.y), Math.abs(this._tmpVectorForPickCompare.z));\n const delta = (this._options.gazeModePointerMovedFactor || 1) * 0.01 * newPick.distance;\n const length = this._tmpVectorForPickCompare.length();\n if (length > delta) {\n return true;\n }\n return false;\n }\n _updatePointerDistance(_laserPointer, distance = 100) {\n _laserPointer.scaling.y = distance;\n // a bit of distance from the controller\n if (this._scene.useRightHandedSystem) {\n distance *= -1;\n }\n _laserPointer.position.z = distance / 2 + 0.05;\n }\n _augmentPointerInit(pointerEventInit, id, screenCoordinates) {\n pointerEventInit.pointerId = id;\n pointerEventInit.pointerType = \"xr\";\n if (screenCoordinates) {\n pointerEventInit.screenX = screenCoordinates.x;\n pointerEventInit.screenY = screenCoordinates.y;\n }\n }\n /** @internal */\n get lasterPointerDefaultColor() {\n // here due to a typo\n return this.laserPointerDefaultColor;\n }\n}\nWebXRControllerPointerSelection._IdCounter = 200;\n/**\n * The module's name\n */\nWebXRControllerPointerSelection.Name = WebXRFeatureName.POINTER_SELECTION;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRControllerPointerSelection.Version = 1;\n//register the plugin\nWebXRFeaturesManager.AddWebXRFeature(WebXRControllerPointerSelection.Name, (xrSessionManager, options) => {\n return () => new WebXRControllerPointerSelection(xrSessionManager, options);\n}, WebXRControllerPointerSelection.Version, true);\n//# sourceMappingURL=WebXRControllerPointerSelection.js.map","\nimport { TmpVectors, Vector3 } from \"../Maths/math.vector.js\";\nimport { SubMesh } from \"./subMesh.js\";\n/**\n * @internal\n */\nSubMesh.prototype._projectOnTrianglesToRef = function (vector, positions, indices, step, checkStopper, ref) {\n // Triangles test\n const proj = TmpVectors.Vector3[0];\n const tmp = TmpVectors.Vector3[1];\n let distance = +Infinity;\n for (let index = this.indexStart; index < this.indexStart + this.indexCount - (3 - step); index += step) {\n const indexA = indices[index];\n const indexB = indices[index + 1];\n const indexC = indices[index + 2];\n if (checkStopper && indexC === 0xffffffff) {\n index += 2;\n continue;\n }\n const p0 = positions[indexA];\n const p1 = positions[indexB];\n const p2 = positions[indexC];\n // stay defensive and don't check against undefined positions.\n if (!p0 || !p1 || !p2) {\n continue;\n }\n const tmpDist = Vector3.ProjectOnTriangleToRef(vector, p0, p1, p2, tmp);\n if (tmpDist < distance) {\n proj.copyFrom(tmp);\n distance = tmpDist;\n }\n }\n ref.copyFrom(proj);\n return distance;\n};\n/**\n * @internal\n */\nSubMesh.prototype._projectOnUnIndexedTrianglesToRef = function (vector, positions, indices, ref) {\n // Triangles test\n const proj = TmpVectors.Vector3[0];\n const tmp = TmpVectors.Vector3[1];\n let distance = +Infinity;\n for (let index = this.verticesStart; index < this.verticesStart + this.verticesCount; index += 3) {\n const p0 = positions[index];\n const p1 = positions[index + 1];\n const p2 = positions[index + 2];\n const tmpDist = Vector3.ProjectOnTriangleToRef(vector, p0, p1, p2, tmp);\n if (tmpDist < distance) {\n proj.copyFrom(tmp);\n distance = tmpDist;\n }\n }\n ref.copyFrom(proj);\n return distance;\n};\nSubMesh.prototype.projectToRef = function (vector, positions, indices, ref) {\n const material = this.getMaterial();\n if (!material) {\n return -1;\n }\n let step = 3;\n let checkStopper = false;\n switch (material.fillMode) {\n case 3:\n case 5:\n case 6:\n case 8:\n return -1;\n case 7:\n step = 1;\n checkStopper = true;\n break;\n default:\n break;\n }\n // LineMesh first as it's also a Mesh...\n if (material.fillMode === 4) {\n return -1;\n }\n else {\n // Check if mesh is unindexed\n if (!indices.length && this._mesh._unIndexed) {\n return this._projectOnUnIndexedTrianglesToRef(vector, positions, indices, ref);\n }\n return this._projectOnTrianglesToRef(vector, positions, indices, step, checkStopper, ref);\n }\n};\n//# sourceMappingURL=subMesh.project.js.map","import { WebXRFeaturesManager, WebXRFeatureName } from \"../webXRFeaturesManager.js\";\nimport { CreateSphere } from \"../../Meshes/Builders/sphereBuilder.js\";\nimport { Vector3, Quaternion, TmpVectors } from \"../../Maths/math.vector.js\";\nimport { Ray } from \"../../Culling/ray.js\";\nimport { PickingInfo } from \"../../Collisions/pickingInfo.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nimport { UtilityLayerRenderer } from \"../../Rendering/utilityLayerRenderer.js\";\nimport { BoundingSphere } from \"../../Culling/boundingSphere.js\";\nimport { StandardMaterial } from \"../../Materials/standardMaterial.js\";\nimport { Color3 } from \"../../Maths/math.color.js\";\nimport { NodeMaterial } from \"../../Materials/Node/nodeMaterial.js\";\nimport { Animation } from \"../../Animations/animation.js\";\nimport { QuadraticEase, EasingFunction } from \"../../Animations/easing.js\";\n// side effects\nimport \"../../Meshes/subMesh.project.js\";\n// Tracks the interaction animation state when using a motion controller with a near interaction orb\nvar ControllerOrbAnimationState;\n(function (ControllerOrbAnimationState) {\n /**\n * Orb is invisible\n */\n ControllerOrbAnimationState[ControllerOrbAnimationState[\"DEHYDRATED\"] = 0] = \"DEHYDRATED\";\n /**\n * Orb is visible and inside the hover range\n */\n ControllerOrbAnimationState[ControllerOrbAnimationState[\"HOVER\"] = 1] = \"HOVER\";\n /**\n * Orb is visible and touching a near interaction target\n */\n ControllerOrbAnimationState[ControllerOrbAnimationState[\"TOUCH\"] = 2] = \"TOUCH\";\n})(ControllerOrbAnimationState || (ControllerOrbAnimationState = {}));\n/**\n * Where should the near interaction mesh be attached to when using a motion controller for near interaction\n */\nexport var WebXRNearControllerMode;\n(function (WebXRNearControllerMode) {\n /**\n * Motion controllers will not support near interaction\n */\n WebXRNearControllerMode[WebXRNearControllerMode[\"DISABLED\"] = 0] = \"DISABLED\";\n /**\n * The interaction point for motion controllers will be inside of them\n */\n WebXRNearControllerMode[WebXRNearControllerMode[\"CENTERED_ON_CONTROLLER\"] = 1] = \"CENTERED_ON_CONTROLLER\";\n /**\n * The interaction point for motion controllers will be in front of the controller\n */\n WebXRNearControllerMode[WebXRNearControllerMode[\"CENTERED_IN_FRONT\"] = 2] = \"CENTERED_IN_FRONT\";\n})(WebXRNearControllerMode || (WebXRNearControllerMode = {}));\n/**\n * A module that will enable near interaction near interaction for hands and motion controllers of XR Input Sources\n */\nexport class WebXRNearInteraction extends WebXRAbstractFeature {\n /**\n * constructs a new background remover module\n * @param _xrSessionManager the session manager for this module\n * @param _options read-only options to be used in this module\n */\n constructor(_xrSessionManager, _options) {\n super(_xrSessionManager);\n this._options = _options;\n this._tmpRay = new Ray(new Vector3(), new Vector3());\n this._attachController = (xrController) => {\n if (this._controllers[xrController.uniqueId]) {\n // already attached\n return;\n }\n // get two new meshes\n const { touchCollisionMesh, touchCollisionMeshFunction, hydrateCollisionMeshFunction } = this._generateNewTouchPointMesh();\n const selectionMesh = this._generateVisualCue();\n this._controllers[xrController.uniqueId] = {\n xrController,\n meshUnderPointer: null,\n nearInteractionTargetMesh: null,\n pick: null,\n stalePick: null,\n touchCollisionMesh,\n touchCollisionMeshFunction: touchCollisionMeshFunction,\n hydrateCollisionMeshFunction: hydrateCollisionMeshFunction,\n currentAnimationState: ControllerOrbAnimationState.DEHYDRATED,\n grabRay: new Ray(new Vector3(), new Vector3()),\n hoverInteraction: false,\n nearInteraction: false,\n grabInteraction: false,\n id: WebXRNearInteraction._IdCounter++,\n pickedPointVisualCue: selectionMesh,\n };\n if (this._attachedController) {\n if (!this._options.enableNearInteractionOnAllControllers &&\n this._options.preferredHandedness &&\n xrController.inputSource.handedness === this._options.preferredHandedness) {\n this._attachedController = xrController.uniqueId;\n }\n }\n else {\n if (!this._options.enableNearInteractionOnAllControllers) {\n this._attachedController = xrController.uniqueId;\n }\n }\n switch (xrController.inputSource.targetRayMode) {\n case \"tracked-pointer\":\n return this._attachNearInteractionMode(xrController);\n case \"gaze\":\n return null;\n case \"screen\":\n return null;\n }\n };\n this._controllers = {};\n this._farInteractionFeature = null;\n /**\n * default color of the selection ring\n */\n this.selectionMeshDefaultColor = new Color3(0.8, 0.8, 0.8);\n /**\n * This color will be applied to the selection ring when selection is triggered\n */\n this.selectionMeshPickedColor = new Color3(0.3, 0.3, 1.0);\n this._hoverRadius = 0.1;\n this._pickRadius = 0.02;\n this._controllerPickRadius = 0.03; // The radius is slightly larger here to make it easier to manipulate since it's not tied to the hand position\n this._nearGrabLengthScale = 5;\n this._scene = this._xrSessionManager.scene;\n if (this._options.nearInteractionControllerMode === undefined) {\n this._options.nearInteractionControllerMode = WebXRNearControllerMode.CENTERED_IN_FRONT;\n }\n if (this._options.farInteractionFeature) {\n this._farInteractionFeature = this._options.farInteractionFeature;\n }\n }\n /**\n * Attach this feature\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n attach() {\n if (!super.attach()) {\n return false;\n }\n this._options.xrInput.controllers.forEach(this._attachController);\n this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController);\n this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, (controller) => {\n // REMOVE the controller\n this._detachController(controller.uniqueId);\n });\n this._scene.constantlyUpdateMeshUnderPointer = true;\n return true;\n }\n /**\n * Detach this feature.\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n detach() {\n if (!super.detach()) {\n return false;\n }\n Object.keys(this._controllers).forEach((controllerId) => {\n this._detachController(controllerId);\n });\n return true;\n }\n /**\n * Will get the mesh under a specific pointer.\n * `scene.meshUnderPointer` will only return one mesh - either left or right.\n * @param controllerId the controllerId to check\n * @returns The mesh under pointer or null if no mesh is under the pointer\n */\n getMeshUnderPointer(controllerId) {\n if (this._controllers[controllerId]) {\n return this._controllers[controllerId].meshUnderPointer;\n }\n else {\n return null;\n }\n }\n /**\n * Get the xr controller that correlates to the pointer id in the pointer event\n *\n * @param id the pointer id to search for\n * @returns the controller that correlates to this id or null if not found\n */\n getXRControllerByPointerId(id) {\n const keys = Object.keys(this._controllers);\n for (let i = 0; i < keys.length; ++i) {\n if (this._controllers[keys[i]].id === id) {\n return this._controllers[keys[i]].xrController || null;\n }\n }\n return null;\n }\n /**\n * This function sets webXRControllerPointerSelection feature that will be disabled when\n * the hover range is reached for a mesh and will be reattached when not in hover range.\n * This is used to remove the selection rays when moving.\n * @param farInteractionFeature the feature to disable when finger is in hover range for a mesh\n */\n setFarInteractionFeature(farInteractionFeature) {\n this._farInteractionFeature = farInteractionFeature;\n }\n /**\n * Filter used for near interaction pick and hover\n * @param mesh\n */\n _nearPickPredicate(mesh) {\n return mesh.isEnabled() && mesh.isVisible && mesh.isPickable && mesh.isNearPickable;\n }\n /**\n * Filter used for near interaction grab\n * @param mesh\n */\n _nearGrabPredicate(mesh) {\n return mesh.isEnabled() && mesh.isVisible && mesh.isPickable && mesh.isNearGrabbable;\n }\n /**\n * Filter used for any near interaction\n * @param mesh\n */\n _nearInteractionPredicate(mesh) {\n return mesh.isEnabled() && mesh.isVisible && mesh.isPickable && (mesh.isNearPickable || mesh.isNearGrabbable);\n }\n _controllerAvailablePredicate(mesh, controllerId) {\n let parent = mesh;\n while (parent) {\n if (parent.reservedDataStore && parent.reservedDataStore.nearInteraction && parent.reservedDataStore.nearInteraction.excludedControllerId === controllerId) {\n return false;\n }\n parent = parent.parent;\n }\n return true;\n }\n _handleTransitionAnimation(controllerData, newState) {\n var _a;\n if (controllerData.currentAnimationState === newState ||\n this._options.nearInteractionControllerMode !== WebXRNearControllerMode.CENTERED_IN_FRONT ||\n !!((_a = controllerData.xrController) === null || _a === void 0 ? void 0 : _a.inputSource.hand)) {\n return;\n }\n // Don't always break to allow for animation fallthrough on rare cases of multi-transitions\n if (newState > controllerData.currentAnimationState) {\n switch (controllerData.currentAnimationState) {\n case ControllerOrbAnimationState.DEHYDRATED: {\n controllerData.hydrateCollisionMeshFunction(true);\n if (newState === ControllerOrbAnimationState.HOVER) {\n break;\n }\n }\n // eslint-disable-next-line no-fallthrough\n case ControllerOrbAnimationState.HOVER: {\n controllerData.touchCollisionMeshFunction(true);\n if (newState === ControllerOrbAnimationState.TOUCH) {\n break;\n }\n }\n }\n }\n else {\n switch (controllerData.currentAnimationState) {\n case ControllerOrbAnimationState.TOUCH: {\n controllerData.touchCollisionMeshFunction(false);\n if (newState === ControllerOrbAnimationState.HOVER) {\n break;\n }\n }\n // eslint-disable-next-line no-fallthrough\n case ControllerOrbAnimationState.HOVER: {\n controllerData.hydrateCollisionMeshFunction(false);\n if (newState === ControllerOrbAnimationState.DEHYDRATED) {\n break;\n }\n }\n }\n }\n controllerData.currentAnimationState = newState;\n }\n _processTouchPoint(id, position, orientation) {\n var _a;\n const controllerData = this._controllers[id];\n // Position and orientation could be temporary values, se we take care of them before calling any functions that use temporary vectors/quaternions\n controllerData.grabRay.origin.copyFrom(position);\n orientation.toEulerAnglesToRef(TmpVectors.Vector3[0]);\n controllerData.grabRay.direction.copyFrom(TmpVectors.Vector3[0]);\n if (this._options.nearInteractionControllerMode === WebXRNearControllerMode.CENTERED_IN_FRONT && !((_a = controllerData.xrController) === null || _a === void 0 ? void 0 : _a.inputSource.hand)) {\n // offset the touch point in the direction the transform is facing\n controllerData.xrController.getWorldPointerRayToRef(this._tmpRay);\n controllerData.grabRay.origin.addInPlace(this._tmpRay.direction.scale(0.05));\n }\n controllerData.grabRay.length = this._nearGrabLengthScale * this._hoverRadius;\n controllerData.touchCollisionMesh.position.copyFrom(controllerData.grabRay.origin);\n }\n _onXRFrame(_xrFrame) {\n Object.keys(this._controllers).forEach((id) => {\n var _a;\n // only do this for the selected pointer\n const controllerData = this._controllers[id];\n const handData = (_a = controllerData.xrController) === null || _a === void 0 ? void 0 : _a.inputSource.hand;\n // If near interaction is not enabled/available for this controller, return early\n if ((!this._options.enableNearInteractionOnAllControllers && id !== this._attachedController) ||\n !controllerData.xrController ||\n (!handData && (!this._options.nearInteractionControllerMode || !controllerData.xrController.inputSource.gamepad))) {\n controllerData.pick = null;\n return;\n }\n controllerData.hoverInteraction = false;\n controllerData.nearInteraction = false;\n // Every frame check collisions/input\n if (controllerData.xrController) {\n if (handData) {\n const xrIndexTip = handData.get(\"index-finger-tip\");\n if (xrIndexTip) {\n const indexTipPose = _xrFrame.getJointPose(xrIndexTip, this._xrSessionManager.referenceSpace);\n if (indexTipPose && indexTipPose.transform) {\n const axisRHSMultiplier = this._scene.useRightHandedSystem ? 1 : -1;\n TmpVectors.Vector3[0].set(indexTipPose.transform.position.x, indexTipPose.transform.position.y, indexTipPose.transform.position.z * axisRHSMultiplier);\n TmpVectors.Quaternion[0].set(indexTipPose.transform.orientation.x, indexTipPose.transform.orientation.y, indexTipPose.transform.orientation.z * axisRHSMultiplier, indexTipPose.transform.orientation.w * axisRHSMultiplier);\n this._processTouchPoint(id, TmpVectors.Vector3[0], TmpVectors.Quaternion[0]);\n }\n }\n }\n else if (controllerData.xrController.inputSource.gamepad && this._options.nearInteractionControllerMode !== WebXRNearControllerMode.DISABLED) {\n let controllerPose = controllerData.xrController.pointer;\n if (controllerData.xrController.grip && this._options.nearInteractionControllerMode === WebXRNearControllerMode.CENTERED_ON_CONTROLLER) {\n controllerPose = controllerData.xrController.grip;\n }\n this._processTouchPoint(id, controllerPose.position, controllerPose.rotationQuaternion);\n }\n }\n else {\n return;\n }\n const accuratePickInfo = (originalScenePick, utilityScenePick) => {\n let pick = null;\n if (!utilityScenePick || !utilityScenePick.hit) {\n // No hit in utility scene\n pick = originalScenePick;\n }\n else if (!originalScenePick || !originalScenePick.hit) {\n // No hit in original scene\n pick = utilityScenePick;\n }\n else if (utilityScenePick.distance < originalScenePick.distance) {\n // Hit is closer in utility scene\n pick = utilityScenePick;\n }\n else {\n // Hit is closer in original scene\n pick = originalScenePick;\n }\n return pick;\n };\n const populateNearInteractionInfo = (nearInteractionInfo) => {\n let result = new PickingInfo();\n let nearInteractionAtOrigin = false;\n const nearInteraction = nearInteractionInfo && nearInteractionInfo.pickedPoint && nearInteractionInfo.hit;\n if (nearInteractionInfo === null || nearInteractionInfo === void 0 ? void 0 : nearInteractionInfo.pickedPoint) {\n nearInteractionAtOrigin = nearInteractionInfo.pickedPoint.x === 0 && nearInteractionInfo.pickedPoint.y === 0 && nearInteractionInfo.pickedPoint.z === 0;\n }\n if (nearInteraction && !nearInteractionAtOrigin) {\n result = nearInteractionInfo;\n }\n return result;\n };\n // Don't perform touch logic while grabbing, to prevent triggering touch interactions while in the middle of a grab interaction\n // Dont update cursor logic either - the cursor should already be visible for the grab to be in range,\n // and in order to maintain its position on the target mesh it is parented for the duration of the grab.\n if (!controllerData.grabInteraction) {\n let pick = null;\n // near interaction hover\n let utilitySceneHoverPick = null;\n if (this._options.useUtilityLayer && this._utilityLayerScene) {\n utilitySceneHoverPick = this._pickWithSphere(controllerData, this._hoverRadius, this._utilityLayerScene, (mesh) => this._nearInteractionPredicate(mesh));\n }\n const originalSceneHoverPick = this._pickWithSphere(controllerData, this._hoverRadius, this._scene, (mesh) => this._nearInteractionPredicate(mesh));\n const hoverPickInfo = accuratePickInfo(originalSceneHoverPick, utilitySceneHoverPick);\n if (hoverPickInfo && hoverPickInfo.hit) {\n pick = populateNearInteractionInfo(hoverPickInfo);\n if (pick.hit) {\n controllerData.hoverInteraction = true;\n }\n }\n // near interaction pick\n if (controllerData.hoverInteraction) {\n let utilitySceneNearPick = null;\n const radius = handData ? this._pickRadius : this._controllerPickRadius;\n if (this._options.useUtilityLayer && this._utilityLayerScene) {\n utilitySceneNearPick = this._pickWithSphere(controllerData, radius, this._utilityLayerScene, (mesh) => this._nearPickPredicate(mesh));\n }\n const originalSceneNearPick = this._pickWithSphere(controllerData, radius, this._scene, (mesh) => this._nearPickPredicate(mesh));\n const pickInfo = accuratePickInfo(originalSceneNearPick, utilitySceneNearPick);\n const nearPick = populateNearInteractionInfo(pickInfo);\n if (nearPick.hit) {\n // Near pick takes precedence over hover interaction\n pick = nearPick;\n controllerData.nearInteraction = true;\n }\n }\n controllerData.stalePick = controllerData.pick;\n controllerData.pick = pick;\n // Update mesh under pointer\n if (controllerData.pick && controllerData.pick.pickedPoint && controllerData.pick.hit) {\n controllerData.meshUnderPointer = controllerData.pick.pickedMesh;\n controllerData.pickedPointVisualCue.position.copyFrom(controllerData.pick.pickedPoint);\n controllerData.pickedPointVisualCue.isVisible = true;\n if (this._farInteractionFeature && this._farInteractionFeature.attached) {\n this._farInteractionFeature._setPointerSelectionDisabledByPointerId(controllerData.id, true);\n }\n }\n else {\n controllerData.meshUnderPointer = null;\n controllerData.pickedPointVisualCue.isVisible = false;\n if (this._farInteractionFeature && this._farInteractionFeature.attached) {\n this._farInteractionFeature._setPointerSelectionDisabledByPointerId(controllerData.id, false);\n }\n }\n }\n // Update the interaction animation. Only updates if the visible touch mesh is active\n let state = ControllerOrbAnimationState.DEHYDRATED;\n if (controllerData.grabInteraction || controllerData.nearInteraction) {\n state = ControllerOrbAnimationState.TOUCH;\n }\n else if (controllerData.hoverInteraction) {\n state = ControllerOrbAnimationState.HOVER;\n }\n this._handleTransitionAnimation(controllerData, state);\n });\n }\n get _utilityLayerScene() {\n return this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene;\n }\n _generateVisualCue() {\n const sceneToRenderTo = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._scene;\n const selectionMesh = CreateSphere(\"nearInteraction\", {\n diameter: 0.0035 * 3,\n }, sceneToRenderTo);\n selectionMesh.bakeCurrentTransformIntoVertices();\n selectionMesh.isPickable = false;\n selectionMesh.isVisible = false;\n selectionMesh.rotationQuaternion = Quaternion.Identity();\n const targetMat = new StandardMaterial(\"targetMat\", sceneToRenderTo);\n targetMat.specularColor = Color3.Black();\n targetMat.emissiveColor = this.selectionMeshDefaultColor;\n targetMat.backFaceCulling = false;\n selectionMesh.material = targetMat;\n return selectionMesh;\n }\n _isControllerReadyForNearInteraction(id) {\n if (this._farInteractionFeature) {\n return this._farInteractionFeature._getPointerSelectionDisabledByPointerId(id);\n }\n return true;\n }\n _attachNearInteractionMode(xrController) {\n const controllerData = this._controllers[xrController.uniqueId];\n const pointerEventInit = {\n pointerId: controllerData.id,\n pointerType: \"xr-near\",\n };\n controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {\n if ((!this._options.enableNearInteractionOnAllControllers && xrController.uniqueId !== this._attachedController) ||\n !controllerData.xrController ||\n (!controllerData.xrController.inputSource.hand && (!this._options.nearInteractionControllerMode || !controllerData.xrController.inputSource.gamepad))) {\n return;\n }\n if (controllerData.pick) {\n controllerData.pick.ray = controllerData.grabRay;\n }\n if (controllerData.pick && this._isControllerReadyForNearInteraction(controllerData.id)) {\n this._scene.simulatePointerMove(controllerData.pick, pointerEventInit);\n }\n // Near pick pointer event\n if (controllerData.nearInteraction && controllerData.pick && controllerData.pick.hit) {\n if (!controllerData.nearInteractionTargetMesh) {\n this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);\n controllerData.nearInteractionTargetMesh = controllerData.meshUnderPointer;\n }\n }\n else if (controllerData.nearInteractionTargetMesh && controllerData.stalePick) {\n this._scene.simulatePointerUp(controllerData.stalePick, pointerEventInit);\n controllerData.nearInteractionTargetMesh = null;\n }\n });\n const grabCheck = (pressed) => {\n if (this._options.enableNearInteractionOnAllControllers ||\n (xrController.uniqueId === this._attachedController && this._isControllerReadyForNearInteraction(controllerData.id))) {\n if (controllerData.pick) {\n controllerData.pick.ray = controllerData.grabRay;\n }\n if (pressed && controllerData.pick && controllerData.meshUnderPointer && this._nearGrabPredicate(controllerData.meshUnderPointer)) {\n controllerData.grabInteraction = true;\n controllerData.pickedPointVisualCue.isVisible = false;\n this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);\n }\n else if (!pressed && controllerData.pick && controllerData.grabInteraction) {\n this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);\n controllerData.grabInteraction = false;\n controllerData.pickedPointVisualCue.isVisible = true;\n }\n }\n else {\n if (pressed && !this._options.enableNearInteractionOnAllControllers && !this._options.disableSwitchOnClick) {\n this._attachedController = xrController.uniqueId;\n }\n }\n };\n if (xrController.inputSource.gamepad) {\n const init = (motionController) => {\n controllerData.squeezeComponent = motionController.getComponent(\"grasp\");\n if (controllerData.squeezeComponent) {\n controllerData.onSqueezeButtonChangedObserver = controllerData.squeezeComponent.onButtonStateChangedObservable.add((component) => {\n if (component.changes.pressed) {\n const pressed = component.changes.pressed.current;\n grabCheck(pressed);\n }\n });\n }\n else {\n controllerData.selectionComponent = motionController.getMainComponent();\n controllerData.onButtonChangedObserver = controllerData.selectionComponent.onButtonStateChangedObservable.add((component) => {\n if (component.changes.pressed) {\n const pressed = component.changes.pressed.current;\n grabCheck(pressed);\n }\n });\n }\n };\n if (xrController.motionController) {\n init(xrController.motionController);\n }\n else {\n xrController.onMotionControllerInitObservable.add(init);\n }\n }\n else {\n // use the select and squeeze events\n const selectStartListener = (event) => {\n if (controllerData.xrController &&\n event.inputSource === controllerData.xrController.inputSource &&\n controllerData.pick &&\n this._isControllerReadyForNearInteraction(controllerData.id) &&\n controllerData.meshUnderPointer &&\n this._nearGrabPredicate(controllerData.meshUnderPointer)) {\n controllerData.grabInteraction = true;\n controllerData.pickedPointVisualCue.isVisible = false;\n this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);\n }\n };\n const selectEndListener = (event) => {\n if (controllerData.xrController &&\n event.inputSource === controllerData.xrController.inputSource &&\n controllerData.pick &&\n this._isControllerReadyForNearInteraction(controllerData.id)) {\n this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);\n controllerData.grabInteraction = false;\n controllerData.pickedPointVisualCue.isVisible = true;\n }\n };\n controllerData.eventListeners = {\n selectend: selectEndListener,\n selectstart: selectStartListener,\n };\n this._xrSessionManager.session.addEventListener(\"selectstart\", selectStartListener);\n this._xrSessionManager.session.addEventListener(\"selectend\", selectEndListener);\n }\n }\n _detachController(xrControllerUniqueId) {\n const controllerData = this._controllers[xrControllerUniqueId];\n if (!controllerData) {\n return;\n }\n if (controllerData.squeezeComponent) {\n if (controllerData.onSqueezeButtonChangedObserver) {\n controllerData.squeezeComponent.onButtonStateChangedObservable.remove(controllerData.onSqueezeButtonChangedObserver);\n }\n }\n if (controllerData.selectionComponent) {\n if (controllerData.onButtonChangedObserver) {\n controllerData.selectionComponent.onButtonStateChangedObservable.remove(controllerData.onButtonChangedObserver);\n }\n }\n if (controllerData.onFrameObserver) {\n this._xrSessionManager.onXRFrameObservable.remove(controllerData.onFrameObserver);\n }\n if (controllerData.eventListeners) {\n Object.keys(controllerData.eventListeners).forEach((eventName) => {\n const func = controllerData.eventListeners && controllerData.eventListeners[eventName];\n if (func) {\n this._xrSessionManager.session.removeEventListener(eventName, func);\n }\n });\n }\n controllerData.touchCollisionMesh.dispose();\n controllerData.pickedPointVisualCue.dispose();\n this._xrSessionManager.runInXRFrame(() => {\n // Fire a pointerup\n const pointerEventInit = {\n pointerId: controllerData.id,\n pointerType: \"xr-near\",\n };\n this._scene.simulatePointerUp(new PickingInfo(), pointerEventInit);\n });\n // remove from the map\n delete this._controllers[xrControllerUniqueId];\n if (this._attachedController === xrControllerUniqueId) {\n // check for other controllers\n const keys = Object.keys(this._controllers);\n if (keys.length) {\n this._attachedController = keys[0];\n }\n else {\n this._attachedController = \"\";\n }\n }\n }\n _generateNewTouchPointMesh() {\n // populate information for near hover, pick and pinch\n const meshCreationScene = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._scene;\n const touchCollisionMesh = CreateSphere(\"PickSphere\", { diameter: 1 }, meshCreationScene);\n touchCollisionMesh.isVisible = false;\n // Generate the material for the touch mesh visuals\n if (this._options.motionControllerOrbMaterial) {\n touchCollisionMesh.material = this._options.motionControllerOrbMaterial;\n }\n else {\n NodeMaterial.ParseFromSnippetAsync(\"8RUNKL#3\", meshCreationScene).then((nodeMaterial) => {\n touchCollisionMesh.material = nodeMaterial;\n });\n }\n const easingFunction = new QuadraticEase();\n easingFunction.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT);\n // Adjust the visual size based off of the size of the touch collision orb.\n // Having the size perfectly match for hover gives a more accurate tell for when the user will start interacting with the target\n // Sizes for other states are somewhat arbitrary, as they are based on what feels nice during an interaction\n const hoverSizeVec = new Vector3(this._controllerPickRadius, this._controllerPickRadius, this._controllerPickRadius);\n const touchSize = this._controllerPickRadius * (4 / 3);\n const touchSizeVec = new Vector3(touchSize, touchSize, touchSize);\n const hydrateTransitionSize = this._controllerPickRadius * (7 / 6);\n const hydrateTransitionSizeVec = new Vector3(hydrateTransitionSize, hydrateTransitionSize, hydrateTransitionSize);\n const touchHoverTransitionSize = this._controllerPickRadius * (4 / 5);\n const touchHoverTransitionSizeVec = new Vector3(touchHoverTransitionSize, touchHoverTransitionSize, touchHoverTransitionSize);\n const hoverTouchTransitionSize = this._controllerPickRadius * (3 / 2);\n const hoverTouchTransitionSizeVec = new Vector3(hoverTouchTransitionSize, hoverTouchTransitionSize, hoverTouchTransitionSize);\n const touchKeys = [\n { frame: 0, value: hoverSizeVec },\n { frame: 10, value: hoverTouchTransitionSizeVec },\n { frame: 18, value: touchSizeVec },\n ];\n const releaseKeys = [\n { frame: 0, value: touchSizeVec },\n { frame: 10, value: touchHoverTransitionSizeVec },\n { frame: 18, value: hoverSizeVec },\n ];\n const hydrateKeys = [\n { frame: 0, value: Vector3.ZeroReadOnly },\n { frame: 12, value: hydrateTransitionSizeVec },\n { frame: 15, value: hoverSizeVec },\n ];\n const dehydrateKeys = [\n { frame: 0, value: hoverSizeVec },\n { frame: 10, value: Vector3.ZeroReadOnly },\n { frame: 15, value: Vector3.ZeroReadOnly },\n ];\n const touchAction = new Animation(\"touch\", \"scaling\", 60, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT);\n const releaseAction = new Animation(\"release\", \"scaling\", 60, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT);\n const hydrateAction = new Animation(\"hydrate\", \"scaling\", 60, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT);\n const dehydrateAction = new Animation(\"dehydrate\", \"scaling\", 60, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT);\n touchAction.setEasingFunction(easingFunction);\n releaseAction.setEasingFunction(easingFunction);\n hydrateAction.setEasingFunction(easingFunction);\n dehydrateAction.setEasingFunction(easingFunction);\n touchAction.setKeys(touchKeys);\n releaseAction.setKeys(releaseKeys);\n hydrateAction.setKeys(hydrateKeys);\n dehydrateAction.setKeys(dehydrateKeys);\n const touchCollisionMeshFunction = (isTouch) => {\n const action = isTouch ? touchAction : releaseAction;\n meshCreationScene.beginDirectAnimation(touchCollisionMesh, [action], 0, 18, false, 1);\n };\n const hydrateCollisionMeshFunction = (isHydration) => {\n const action = isHydration ? hydrateAction : dehydrateAction;\n if (isHydration) {\n touchCollisionMesh.isVisible = true;\n }\n meshCreationScene.beginDirectAnimation(touchCollisionMesh, [action], 0, 15, false, 1, () => {\n if (!isHydration) {\n touchCollisionMesh.isVisible = false;\n }\n });\n };\n return { touchCollisionMesh, touchCollisionMeshFunction, hydrateCollisionMeshFunction };\n }\n _pickWithSphere(controllerData, radius, sceneToUse, predicate) {\n const pickingInfo = new PickingInfo();\n pickingInfo.distance = +Infinity;\n if (controllerData.touchCollisionMesh && controllerData.xrController) {\n const position = controllerData.touchCollisionMesh.position;\n const sphere = BoundingSphere.CreateFromCenterAndRadius(position, radius);\n for (let meshIndex = 0; meshIndex < sceneToUse.meshes.length; meshIndex++) {\n const mesh = sceneToUse.meshes[meshIndex];\n if (!predicate(mesh) || !this._controllerAvailablePredicate(mesh, controllerData.xrController.uniqueId)) {\n continue;\n }\n const result = WebXRNearInteraction.PickMeshWithSphere(mesh, sphere);\n if (result && result.hit && result.distance < pickingInfo.distance) {\n pickingInfo.hit = result.hit;\n pickingInfo.pickedMesh = mesh;\n pickingInfo.pickedPoint = result.pickedPoint;\n pickingInfo.aimTransform = controllerData.xrController.pointer;\n pickingInfo.gripTransform = controllerData.xrController.grip || null;\n pickingInfo.originMesh = controllerData.touchCollisionMesh;\n pickingInfo.distance = result.distance;\n }\n }\n }\n return pickingInfo;\n }\n /**\n * Picks a mesh with a sphere\n * @param mesh the mesh to pick\n * @param sphere picking sphere in world coordinates\n * @param skipBoundingInfo a boolean indicating if we should skip the bounding info check\n * @returns the picking info\n */\n static PickMeshWithSphere(mesh, sphere, skipBoundingInfo = false) {\n const subMeshes = mesh.subMeshes;\n const pi = new PickingInfo();\n const boundingInfo = mesh.getBoundingInfo();\n if (!mesh._generatePointsArray()) {\n return pi;\n }\n if (!mesh.subMeshes || !boundingInfo) {\n return pi;\n }\n if (!skipBoundingInfo && !BoundingSphere.Intersects(boundingInfo.boundingSphere, sphere)) {\n return pi;\n }\n const result = TmpVectors.Vector3[0];\n const tmpVec = TmpVectors.Vector3[1];\n let distance = +Infinity;\n let tmp, tmpDistanceSphereToCenter, tmpDistanceSurfaceToCenter;\n const center = TmpVectors.Vector3[2];\n const worldToMesh = TmpVectors.Matrix[0];\n worldToMesh.copyFrom(mesh.getWorldMatrix());\n worldToMesh.invert();\n Vector3.TransformCoordinatesToRef(sphere.center, worldToMesh, center);\n for (let index = 0; index < subMeshes.length; index++) {\n const subMesh = subMeshes[index];\n subMesh.projectToRef(center, mesh._positions, mesh.getIndices(), tmpVec);\n Vector3.TransformCoordinatesToRef(tmpVec, mesh.getWorldMatrix(), tmpVec);\n tmp = Vector3.Distance(tmpVec, sphere.center);\n // Check for finger inside of mesh\n tmpDistanceSurfaceToCenter = Vector3.Distance(tmpVec, mesh.getAbsolutePosition());\n tmpDistanceSphereToCenter = Vector3.Distance(sphere.center, mesh.getAbsolutePosition());\n if (tmpDistanceSphereToCenter !== -1 && tmpDistanceSurfaceToCenter !== -1 && tmpDistanceSurfaceToCenter > tmpDistanceSphereToCenter) {\n tmp = 0;\n tmpVec.copyFrom(sphere.center);\n }\n if (tmp !== -1 && tmp < distance) {\n distance = tmp;\n result.copyFrom(tmpVec);\n }\n }\n if (distance < sphere.radius) {\n pi.hit = true;\n pi.distance = distance;\n pi.pickedMesh = mesh;\n pi.pickedPoint = result.clone();\n }\n return pi;\n }\n}\nWebXRNearInteraction._IdCounter = 200;\n/**\n * The module's name\n */\nWebXRNearInteraction.Name = WebXRFeatureName.NEAR_INTERACTION;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRNearInteraction.Version = 1;\n//Register the plugin\nWebXRFeaturesManager.AddWebXRFeature(WebXRNearInteraction.Name, (xrSessionManager, options) => {\n return () => new WebXRNearInteraction(xrSessionManager, options);\n}, WebXRNearInteraction.Version, true);\n//# sourceMappingURL=WebXRNearInteraction.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { WebXRState } from \"./webXRTypes.js\";\nimport { Tools } from \"../Misc/tools.js\";\n/**\n * Button which can be used to enter a different mode of XR\n */\nexport class WebXREnterExitUIButton {\n /**\n * Creates a WebXREnterExitUIButton\n * @param element button element\n * @param sessionMode XR initialization session mode\n * @param referenceSpaceType the type of reference space to be used\n */\n constructor(\n /** button element */\n element, \n /** XR initialization options for the button */\n sessionMode, \n /** Reference space type */\n referenceSpaceType) {\n this.element = element;\n this.sessionMode = sessionMode;\n this.referenceSpaceType = referenceSpaceType;\n }\n /**\n * Extendable function which can be used to update the button's visuals when the state changes\n * @param activeButton the current active button in the UI\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n update(activeButton) { }\n}\n/**\n * Options to create the webXR UI\n */\nexport class WebXREnterExitUIOptions {\n}\n/**\n * UI to allow the user to enter/exit XR mode\n */\nexport class WebXREnterExitUI {\n /**\n * Construct a new EnterExit UI class\n *\n * @param _scene babylon scene object to use\n * @param options (read-only) version of the options passed to this UI\n */\n constructor(_scene, \n /** version of the options passed to this UI */\n options) {\n this._scene = _scene;\n this.options = options;\n this._activeButton = null;\n this._buttons = [];\n /**\n * Fired every time the active button is changed.\n *\n * When xr is entered via a button that launches xr that button will be the callback parameter\n *\n * When exiting xr the callback parameter will be null)\n */\n this.activeButtonChangedObservable = new Observable();\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this._onSessionGranted = (evt) => {\n // This section is for future reference.\n // As per specs, evt.session.mode should have the supported session mode, but no browser supports it for now.\n // // check if the session granted is the same as the one requested\n // const grantedMode = (evt.session as any).mode;\n // if (grantedMode) {\n // this._buttons.some((btn, idx) => {\n // if (btn.sessionMode === grantedMode) {\n // this._enterXRWithButtonIndex(idx);\n // return true;\n // }\n // return false;\n // });\n // } else\n if (this._helper) {\n this._enterXRWithButtonIndex(0);\n }\n };\n this.overlay = document.createElement(\"div\");\n this.overlay.classList.add(\"xr-button-overlay\");\n // prepare for session granted event\n if (!options.ignoreSessionGrantedEvent && navigator.xr) {\n navigator.xr.addEventListener(\"sessiongranted\", this._onSessionGranted);\n }\n // if served over HTTP, warn people.\n // Hopefully the browsers will catch up\n if (typeof window !== \"undefined\") {\n if (window.location && window.location.protocol === \"http:\" && window.location.hostname !== \"localhost\") {\n Tools.Warn(\"WebXR can only be served over HTTPS\");\n throw new Error(\"WebXR can only be served over HTTPS\");\n }\n }\n if (options.customButtons) {\n this._buttons = options.customButtons;\n }\n else {\n this.overlay.style.cssText = \"z-index:11;position: absolute; right: 20px;bottom: 50px;\";\n const sessionMode = options.sessionMode || \"immersive-vr\";\n const referenceSpaceType = options.referenceSpaceType || \"local-floor\";\n const url = typeof SVGSVGElement === \"undefined\"\n ? \"https://cdn.babylonjs.com/Assets/vrButton.png\"\n : \"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A\";\n let css = \".babylonVRicon { color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(\" +\n url +\n \"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }\";\n css += '.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: \"EXIT\"} .xr-error::after { content: \"ERROR\"}';\n const style = document.createElement(\"style\");\n style.appendChild(document.createTextNode(css));\n document.getElementsByTagName(\"head\")[0].appendChild(style);\n const hmdBtn = document.createElement(\"button\");\n hmdBtn.className = \"babylonVRicon\";\n hmdBtn.title = `${sessionMode} - ${referenceSpaceType}`;\n this._buttons.push(new WebXREnterExitUIButton(hmdBtn, sessionMode, referenceSpaceType));\n this._buttons[this._buttons.length - 1].update = function (activeButton) {\n this.element.style.display = activeButton === null || activeButton === this ? \"\" : \"none\";\n hmdBtn.className = \"babylonVRicon\" + (activeButton === this ? \" vrdisplaypresenting\" : \"\");\n };\n this._updateButtons(null);\n }\n const renderCanvas = _scene.getEngine().getInputElement();\n if (renderCanvas && renderCanvas.parentNode) {\n renderCanvas.parentNode.appendChild(this.overlay);\n _scene.onDisposeObservable.addOnce(() => {\n this.dispose();\n });\n }\n }\n /**\n * Set the helper to be used with this UI component.\n * The UI is bound to an experience helper. If not provided the UI can still be used but the events should be registered by the developer.\n *\n * @param helper the experience helper to attach\n * @param renderTarget an optional render target (in case it is created outside of the helper scope)\n * @returns a promise that resolves when the ui is ready\n */\n async setHelperAsync(helper, renderTarget) {\n this._helper = helper;\n this._renderTarget = renderTarget;\n const supportedPromises = this._buttons.map((btn) => {\n return helper.sessionManager.isSessionSupportedAsync(btn.sessionMode);\n });\n helper.onStateChangedObservable.add((state) => {\n if (state == WebXRState.NOT_IN_XR) {\n this._updateButtons(null);\n }\n });\n const results = await Promise.all(supportedPromises);\n results.forEach((supported, i) => {\n if (supported) {\n this.overlay.appendChild(this._buttons[i].element);\n this._buttons[i].element.onclick = this._enterXRWithButtonIndex.bind(this, i);\n }\n else {\n Tools.Warn(`Session mode \"${this._buttons[i].sessionMode}\" not supported in browser`);\n }\n });\n }\n /**\n * Creates UI to allow the user to enter/exit XR mode\n * @param scene the scene to add the ui to\n * @param helper the xr experience helper to enter/exit xr with\n * @param options options to configure the UI\n * @returns the created ui\n */\n static async CreateAsync(scene, helper, options) {\n const ui = new WebXREnterExitUI(scene, options);\n await ui.setHelperAsync(helper, options.renderTarget || undefined);\n return ui;\n }\n async _enterXRWithButtonIndex(idx = 0) {\n if (this._helper.state == WebXRState.IN_XR) {\n await this._helper.exitXRAsync();\n this._updateButtons(null);\n }\n else if (this._helper.state == WebXRState.NOT_IN_XR) {\n try {\n await this._helper.enterXRAsync(this._buttons[idx].sessionMode, this._buttons[idx].referenceSpaceType, this._renderTarget, {\n optionalFeatures: this.options.optionalFeatures,\n requiredFeatures: this.options.requiredFeatures,\n });\n this._updateButtons(this._buttons[idx]);\n }\n catch (e) {\n // make sure button is visible\n this._updateButtons(null);\n const element = this._buttons[idx].element;\n const prevTitle = element.title;\n element.title = \"Error entering XR session : \" + prevTitle;\n element.classList.add(\"xr-error\");\n if (this.options.onError) {\n this.options.onError(e);\n }\n }\n }\n }\n /**\n * Disposes of the XR UI component\n */\n dispose() {\n const renderCanvas = this._scene.getEngine().getInputElement();\n if (renderCanvas && renderCanvas.parentNode && renderCanvas.parentNode.contains(this.overlay)) {\n renderCanvas.parentNode.removeChild(this.overlay);\n }\n this.activeButtonChangedObservable.clear();\n navigator.xr.removeEventListener(\"sessiongranted\", this._onSessionGranted);\n }\n _updateButtons(activeButton) {\n this._activeButton = activeButton;\n this._buttons.forEach((b) => {\n b.update(this._activeButton);\n });\n this.activeButtonChangedObservable.notifyObservers(this._activeButton);\n }\n}\n//# sourceMappingURL=webXREnterExitUI.js.map","import { Observable } from \"../Misc/observable.js\";\n/**\n * The current state of the timer\n */\nexport var TimerState;\n(function (TimerState) {\n /**\n * Timer initialized, not yet started\n */\n TimerState[TimerState[\"INIT\"] = 0] = \"INIT\";\n /**\n * Timer started and counting\n */\n TimerState[TimerState[\"STARTED\"] = 1] = \"STARTED\";\n /**\n * Timer ended (whether aborted or time reached)\n */\n TimerState[TimerState[\"ENDED\"] = 2] = \"ENDED\";\n})(TimerState || (TimerState = {}));\n/**\n * A simple version of the timer. Will take options and start the timer immediately after calling it\n *\n * @param options options with which to initialize this timer\n */\nexport function setAndStartTimer(options) {\n var _a;\n let timer = 0;\n const startTime = Date.now();\n options.observableParameters = (_a = options.observableParameters) !== null && _a !== void 0 ? _a : {};\n const observer = options.contextObservable.add((payload) => {\n const now = Date.now();\n timer = now - startTime;\n const data = {\n startTime,\n currentTime: now,\n deltaTime: timer,\n completeRate: timer / options.timeout,\n payload,\n };\n options.onTick && options.onTick(data);\n if (options.breakCondition && options.breakCondition()) {\n options.contextObservable.remove(observer);\n options.onAborted && options.onAborted(data);\n }\n if (timer >= options.timeout) {\n options.contextObservable.remove(observer);\n options.onEnded && options.onEnded(data);\n }\n }, options.observableParameters.mask, options.observableParameters.insertFirst, options.observableParameters.scope);\n return observer;\n}\n/**\n * An advanced implementation of a timer class\n */\nexport class AdvancedTimer {\n /**\n * Will construct a new advanced timer based on the options provided. Timer will not start until start() is called.\n * @param options construction options for this advanced timer\n */\n constructor(options) {\n var _a, _b;\n /**\n * Will notify each time the timer calculates the remaining time\n */\n this.onEachCountObservable = new Observable();\n /**\n * Will trigger when the timer was aborted due to the break condition\n */\n this.onTimerAbortedObservable = new Observable();\n /**\n * Will trigger when the timer ended successfully\n */\n this.onTimerEndedObservable = new Observable();\n /**\n * Will trigger when the timer state has changed\n */\n this.onStateChangedObservable = new Observable();\n this._observer = null;\n this._breakOnNextTick = false;\n this._tick = (payload) => {\n const now = Date.now();\n this._timer = now - this._startTime;\n const data = {\n startTime: this._startTime,\n currentTime: now,\n deltaTime: this._timer,\n completeRate: this._timer / this._timeToEnd,\n payload,\n };\n const shouldBreak = this._breakOnNextTick || this._breakCondition(data);\n if (shouldBreak || this._timer >= this._timeToEnd) {\n this._stop(data, shouldBreak);\n }\n else {\n this.onEachCountObservable.notifyObservers(data);\n }\n };\n this._setState(TimerState.INIT);\n this._contextObservable = options.contextObservable;\n this._observableParameters = (_a = options.observableParameters) !== null && _a !== void 0 ? _a : {};\n this._breakCondition = (_b = options.breakCondition) !== null && _b !== void 0 ? _b : (() => false);\n this._timeToEnd = options.timeout;\n if (options.onEnded) {\n this.onTimerEndedObservable.add(options.onEnded);\n }\n if (options.onTick) {\n this.onEachCountObservable.add(options.onTick);\n }\n if (options.onAborted) {\n this.onTimerAbortedObservable.add(options.onAborted);\n }\n }\n /**\n * set a breaking condition for this timer. Default is to never break during count\n * @param predicate the new break condition. Returns true to break, false otherwise\n */\n set breakCondition(predicate) {\n this._breakCondition = predicate;\n }\n /**\n * Reset ALL associated observables in this advanced timer\n */\n clearObservables() {\n this.onEachCountObservable.clear();\n this.onTimerAbortedObservable.clear();\n this.onTimerEndedObservable.clear();\n this.onStateChangedObservable.clear();\n }\n /**\n * Will start a new iteration of this timer. Only one instance of this timer can run at a time.\n *\n * @param timeToEnd how much time to measure until timer ended\n */\n start(timeToEnd = this._timeToEnd) {\n if (this._state === TimerState.STARTED) {\n throw new Error(\"Timer already started. Please stop it before starting again\");\n }\n this._timeToEnd = timeToEnd;\n this._startTime = Date.now();\n this._timer = 0;\n this._observer = this._contextObservable.add(this._tick, this._observableParameters.mask, this._observableParameters.insertFirst, this._observableParameters.scope);\n this._setState(TimerState.STARTED);\n }\n /**\n * Will force a stop on the next tick.\n */\n stop() {\n if (this._state !== TimerState.STARTED) {\n return;\n }\n this._breakOnNextTick = true;\n }\n /**\n * Dispose this timer, clearing all resources\n */\n dispose() {\n if (this._observer) {\n this._contextObservable.remove(this._observer);\n }\n this.clearObservables();\n }\n _setState(newState) {\n this._state = newState;\n this.onStateChangedObservable.notifyObservers(this._state);\n }\n _stop(data, aborted = false) {\n this._contextObservable.remove(this._observer);\n this._setState(TimerState.ENDED);\n if (aborted) {\n this.onTimerAbortedObservable.notifyObservers(data);\n }\n else {\n this.onTimerEndedObservable.notifyObservers(data);\n }\n }\n}\n//# sourceMappingURL=timer.js.map","import { WebXRFeaturesManager, WebXRFeatureName } from \"../webXRFeaturesManager.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { WebXRControllerComponent } from \"../motionController/webXRControllerComponent.js\";\nimport { Vector3, Quaternion } from \"../../Maths/math.vector.js\";\nimport { Ray } from \"../../Culling/ray.js\";\nimport { DynamicTexture } from \"../../Materials/Textures/dynamicTexture.js\";\nimport { CreateCylinder } from \"../../Meshes/Builders/cylinderBuilder.js\";\nimport { SineEase, EasingFunction } from \"../../Animations/easing.js\";\nimport { Animation } from \"../../Animations/animation.js\";\nimport { Axis } from \"../../Maths/math.axis.js\";\nimport { StandardMaterial } from \"../../Materials/standardMaterial.js\";\nimport { CreateGround } from \"../../Meshes/Builders/groundBuilder.js\";\nimport { CreateTorus } from \"../../Meshes/Builders/torusBuilder.js\";\nimport { Curve3 } from \"../../Maths/math.path.js\";\nimport { CreateLines } from \"../../Meshes/Builders/linesBuilder.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nimport { Color3, Color4 } from \"../../Maths/math.color.js\";\nimport { UtilityLayerRenderer } from \"../../Rendering/utilityLayerRenderer.js\";\nimport { PointerEventTypes } from \"../../Events/pointerEvents.js\";\nimport { setAndStartTimer } from \"../../Misc/timer.js\";\n/**\n * This is a teleportation feature to be used with WebXR-enabled motion controllers.\n * When enabled and attached, the feature will allow a user to move around and rotate in the scene using\n * the input of the attached controllers.\n */\nexport class WebXRMotionControllerTeleportation extends WebXRAbstractFeature {\n /**\n * Is rotation enabled when moving forward?\n * Disabling this feature will prevent the user from deciding the direction when teleporting\n */\n get rotationEnabled() {\n return this._rotationEnabled;\n }\n /**\n * Sets whether rotation is enabled or not\n * @param enabled is rotation enabled when teleportation is shown\n */\n set rotationEnabled(enabled) {\n this._rotationEnabled = enabled;\n if (this._options.teleportationTargetMesh) {\n const children = this._options.teleportationTargetMesh.getChildMeshes(false, (node) => node.name === \"rotationCone\");\n if (children[0]) {\n children[0].setEnabled(enabled);\n }\n }\n }\n /**\n * Exposes the currently set teleportation target mesh.\n */\n get teleportationTargetMesh() {\n return this._options.teleportationTargetMesh || null;\n }\n /**\n * constructs a new teleportation system\n * @param _xrSessionManager an instance of WebXRSessionManager\n * @param _options configuration object for this feature\n */\n constructor(_xrSessionManager, _options) {\n super(_xrSessionManager);\n this._options = _options;\n this._controllers = {};\n this._snappedToPoint = false;\n this._cachedColor4White = new Color4(1, 1, 1, 1);\n this._tmpRay = new Ray(new Vector3(), new Vector3());\n this._tmpVector = new Vector3();\n this._tmpQuaternion = new Quaternion();\n /**\n * Skip the next teleportation. This can be controlled by the user to prevent the user from teleportation\n * to sections that are not yet \"unlocked\", but should still show the teleportation mesh.\n */\n this.skipNextTeleportation = false;\n /**\n * Is movement backwards enabled\n */\n this.backwardsMovementEnabled = true;\n /**\n * Distance to travel when moving backwards\n */\n this.backwardsTeleportationDistance = 0.7;\n /**\n * The distance from the user to the inspection point in the direction of the controller\n * A higher number will allow the user to move further\n * defaults to 5 (meters, in xr units)\n */\n this.parabolicCheckRadius = 5;\n /**\n * Should the module support parabolic ray on top of direct ray\n * If enabled, the user will be able to point \"at the sky\" and move according to predefined radius distance\n * Very helpful when moving between floors / different heights\n */\n this.parabolicRayEnabled = true;\n /**\n * The second type of ray - straight line.\n * Should it be enabled or should the parabolic line be the only one.\n */\n this.straightRayEnabled = true;\n /**\n * How much rotation should be applied when rotating right and left\n */\n this.rotationAngle = Math.PI / 8;\n /**\n * This observable will notify when the target mesh position was updated.\n * The picking info it provides contains the point to which the target mesh will move ()\n */\n this.onTargetMeshPositionUpdatedObservable = new Observable();\n /**\n * Is teleportation enabled. Can be used to allow rotation only.\n */\n this.teleportationEnabled = true;\n this._rotationEnabled = true;\n this._attachController = (xrController) => {\n if (this._controllers[xrController.uniqueId] || (this._options.forceHandedness && xrController.inputSource.handedness !== this._options.forceHandedness)) {\n // already attached\n return;\n }\n this._controllers[xrController.uniqueId] = {\n xrController,\n teleportationState: {\n forward: false,\n backwards: false,\n rotating: false,\n currentRotation: 0,\n baseRotation: 0,\n blocked: false,\n },\n };\n const controllerData = this._controllers[xrController.uniqueId];\n // motion controller only available to gamepad-enabled input sources.\n if (controllerData.xrController.inputSource.targetRayMode === \"tracked-pointer\" && controllerData.xrController.inputSource.gamepad) {\n // motion controller support\n const initMotionController = () => {\n if (xrController.motionController) {\n const movementController = xrController.motionController.getComponentOfType(WebXRControllerComponent.THUMBSTICK_TYPE) ||\n xrController.motionController.getComponentOfType(WebXRControllerComponent.TOUCHPAD_TYPE);\n if (!movementController || this._options.useMainComponentOnly) {\n // use trigger to move on long press\n const mainComponent = xrController.motionController.getMainComponent();\n if (!mainComponent) {\n return;\n }\n controllerData.teleportationComponent = mainComponent;\n controllerData.onButtonChangedObserver = mainComponent.onButtonStateChangedObservable.add(() => {\n if (!this.teleportationEnabled) {\n return;\n }\n // did \"pressed\" changed?\n if (mainComponent.changes.pressed) {\n if (mainComponent.changes.pressed.current) {\n // simulate \"forward\" thumbstick push\n controllerData.teleportationState.forward = true;\n this._currentTeleportationControllerId = controllerData.xrController.uniqueId;\n controllerData.teleportationState.baseRotation = this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y;\n controllerData.teleportationState.currentRotation = 0;\n const timeToSelect = this._options.timeToTeleport || 3000;\n setAndStartTimer({\n timeout: timeToSelect,\n contextObservable: this._xrSessionManager.onXRFrameObservable,\n breakCondition: () => !mainComponent.pressed,\n onEnded: () => {\n if (this._currentTeleportationControllerId === controllerData.xrController.uniqueId && controllerData.teleportationState.forward) {\n this._teleportForward(xrController.uniqueId);\n }\n },\n });\n }\n else {\n controllerData.teleportationState.forward = false;\n this._currentTeleportationControllerId = \"\";\n }\n }\n });\n }\n else {\n controllerData.teleportationComponent = movementController;\n // use thumbstick (or touchpad if thumbstick not available)\n controllerData.onAxisChangedObserver = movementController.onAxisValueChangedObservable.add((axesData) => {\n if (axesData.y <= 0.7 && controllerData.teleportationState.backwards) {\n controllerData.teleportationState.backwards = false;\n }\n if (axesData.y > 0.7 && !controllerData.teleportationState.forward && this.backwardsMovementEnabled && !this.snapPointsOnly) {\n // teleport backwards\n // General gist: Go Back N units, cast a ray towards the floor. If collided, move.\n if (!controllerData.teleportationState.backwards) {\n controllerData.teleportationState.backwards = true;\n // teleport backwards ONCE\n this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion);\n this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector);\n // get only the y rotation\n this._tmpVector.x = 0;\n this._tmpVector.z = 0;\n // get the quaternion\n Quaternion.FromEulerVectorToRef(this._tmpVector, this._tmpQuaternion);\n this._tmpVector.set(0, 0, this.backwardsTeleportationDistance * (this._xrSessionManager.scene.useRightHandedSystem ? 1.0 : -1.0));\n this._tmpVector.rotateByQuaternionToRef(this._tmpQuaternion, this._tmpVector);\n this._tmpVector.addInPlace(this._options.xrInput.xrCamera.position);\n this._tmpRay.origin.copyFrom(this._tmpVector);\n // This will prevent the user from \"falling\" to a lower platform!\n // TODO - should this be a flag? 'allow falling to lower platforms'?\n this._tmpRay.length = this._options.xrInput.xrCamera.realWorldHeight + 0.1;\n // Right handed system had here \"1\" instead of -1. This is unneeded.\n this._tmpRay.direction.set(0, -1, 0);\n const pick = this._xrSessionManager.scene.pickWithRay(this._tmpRay, (o) => {\n return this._floorMeshes.indexOf(o) !== -1;\n });\n // pick must exist, but stay safe\n if (pick && pick.pickedPoint) {\n // Teleport the users feet to where they targeted. Ignore the Y axis.\n // If the \"falling to lower platforms\" feature is implemented the Y axis should be set here as well\n this._options.xrInput.xrCamera.position.x = pick.pickedPoint.x;\n this._options.xrInput.xrCamera.position.z = pick.pickedPoint.z;\n }\n }\n }\n if (axesData.y < -0.7 && !this._currentTeleportationControllerId && !controllerData.teleportationState.rotating && this.teleportationEnabled) {\n controllerData.teleportationState.forward = true;\n this._currentTeleportationControllerId = controllerData.xrController.uniqueId;\n controllerData.teleportationState.baseRotation = this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y;\n }\n if (axesData.x) {\n if (!controllerData.teleportationState.forward) {\n if (!controllerData.teleportationState.rotating && Math.abs(axesData.x) > 0.7) {\n // rotate in the right direction positive is right\n controllerData.teleportationState.rotating = true;\n const rotation = this.rotationAngle * (axesData.x > 0 ? 1 : -1) * (this._xrSessionManager.scene.useRightHandedSystem ? -1 : 1);\n Quaternion.FromEulerAngles(0, rotation, 0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion, this._options.xrInput.xrCamera.rotationQuaternion);\n }\n }\n else {\n if (this._currentTeleportationControllerId === controllerData.xrController.uniqueId) {\n // set the rotation of the forward movement\n if (this.rotationEnabled) {\n setTimeout(() => {\n controllerData.teleportationState.currentRotation = Math.atan2(axesData.x, axesData.y * (this._xrSessionManager.scene.useRightHandedSystem ? 1 : -1));\n });\n }\n else {\n controllerData.teleportationState.currentRotation = 0;\n }\n }\n }\n }\n else {\n controllerData.teleportationState.rotating = false;\n }\n if (axesData.x === 0 && axesData.y === 0) {\n if (controllerData.teleportationState.blocked) {\n controllerData.teleportationState.blocked = false;\n this._setTargetMeshVisibility(false);\n }\n if (controllerData.teleportationState.forward) {\n this._teleportForward(xrController.uniqueId);\n }\n }\n });\n }\n }\n };\n if (xrController.motionController) {\n initMotionController();\n }\n else {\n xrController.onMotionControllerInitObservable.addOnce(() => {\n initMotionController();\n });\n }\n }\n else {\n this._xrSessionManager.scene.onPointerObservable.add((pointerInfo) => {\n if (pointerInfo.type === PointerEventTypes.POINTERDOWN) {\n controllerData.teleportationState.forward = true;\n this._currentTeleportationControllerId = controllerData.xrController.uniqueId;\n controllerData.teleportationState.baseRotation = this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y;\n controllerData.teleportationState.currentRotation = 0;\n const timeToSelect = this._options.timeToTeleport || 3000;\n setAndStartTimer({\n timeout: timeToSelect,\n contextObservable: this._xrSessionManager.onXRFrameObservable,\n onEnded: () => {\n if (this._currentTeleportationControllerId === controllerData.xrController.uniqueId && controllerData.teleportationState.forward) {\n this._teleportForward(xrController.uniqueId);\n }\n },\n });\n }\n else if (pointerInfo.type === PointerEventTypes.POINTERUP) {\n controllerData.teleportationState.forward = false;\n this._currentTeleportationControllerId = \"\";\n }\n });\n }\n };\n // create default mesh if not provided\n if (!this._options.teleportationTargetMesh) {\n this._createDefaultTargetMesh();\n }\n this._floorMeshes = this._options.floorMeshes || [];\n this._snapToPositions = this._options.snapPositions || [];\n this._blockedRayColor = this._options.blockedRayColor || new Color4(1, 0, 0, 0.75);\n this._setTargetMeshVisibility(false);\n }\n /**\n * Get the snapPointsOnly flag\n */\n get snapPointsOnly() {\n return !!this._options.snapPointsOnly;\n }\n /**\n * Sets the snapPointsOnly flag\n * @param snapToPoints should teleportation be exclusively to snap points\n */\n set snapPointsOnly(snapToPoints) {\n this._options.snapPointsOnly = snapToPoints;\n }\n /**\n * Add a new mesh to the floor meshes array\n * @param mesh the mesh to use as floor mesh\n */\n addFloorMesh(mesh) {\n this._floorMeshes.push(mesh);\n }\n /**\n * Add a mesh to the list of meshes blocking the teleportation ray\n * @param mesh The mesh to add to the teleportation-blocking meshes\n */\n addBlockerMesh(mesh) {\n this._options.pickBlockerMeshes = this._options.pickBlockerMeshes || [];\n this._options.pickBlockerMeshes.push(mesh);\n }\n /**\n * Add a new snap-to point to fix teleportation to this position\n * @param newSnapPoint The new Snap-To point\n */\n addSnapPoint(newSnapPoint) {\n this._snapToPositions.push(newSnapPoint);\n }\n attach() {\n if (!super.attach()) {\n return false;\n }\n // Safety reset\n this._currentTeleportationControllerId = \"\";\n this._options.xrInput.controllers.forEach(this._attachController);\n this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController);\n this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, (controller) => {\n // REMOVE the controller\n this._detachController(controller.uniqueId);\n });\n return true;\n }\n detach() {\n if (!super.detach()) {\n return false;\n }\n Object.keys(this._controllers).forEach((controllerId) => {\n this._detachController(controllerId);\n });\n this._setTargetMeshVisibility(false);\n this._currentTeleportationControllerId = \"\";\n this._controllers = {};\n return true;\n }\n dispose() {\n super.dispose();\n this._options.teleportationTargetMesh && this._options.teleportationTargetMesh.dispose(false, true);\n }\n /**\n * Remove a mesh from the floor meshes array\n * @param mesh the mesh to remove\n */\n removeFloorMesh(mesh) {\n const index = this._floorMeshes.indexOf(mesh);\n if (index !== -1) {\n this._floorMeshes.splice(index, 1);\n }\n }\n /**\n * Remove a mesh from the blocker meshes array\n * @param mesh the mesh to remove\n */\n removeBlockerMesh(mesh) {\n this._options.pickBlockerMeshes = this._options.pickBlockerMeshes || [];\n const index = this._options.pickBlockerMeshes.indexOf(mesh);\n if (index !== -1) {\n this._options.pickBlockerMeshes.splice(index, 1);\n }\n }\n /**\n * Remove a mesh from the floor meshes array using its name\n * @param name the mesh name to remove\n */\n removeFloorMeshByName(name) {\n const mesh = this._xrSessionManager.scene.getMeshByName(name);\n if (mesh) {\n this.removeFloorMesh(mesh);\n }\n }\n /**\n * This function will iterate through the array, searching for this point or equal to it. It will then remove it from the snap-to array\n * @param snapPointToRemove the point (or a clone of it) to be removed from the array\n * @returns was the point found and removed or not\n */\n removeSnapPoint(snapPointToRemove) {\n // check if the object is in the array\n let index = this._snapToPositions.indexOf(snapPointToRemove);\n // if not found as an object, compare to the points\n if (index === -1) {\n for (let i = 0; i < this._snapToPositions.length; ++i) {\n // equals? index is i, break the loop\n if (this._snapToPositions[i].equals(snapPointToRemove)) {\n index = i;\n break;\n }\n }\n }\n // index is not -1? remove the object\n if (index !== -1) {\n this._snapToPositions.splice(index, 1);\n return true;\n }\n return false;\n }\n /**\n * This function sets a selection feature that will be disabled when\n * the forward ray is shown and will be reattached when hidden.\n * This is used to remove the selection rays when moving.\n * @param selectionFeature the feature to disable when forward movement is enabled\n */\n setSelectionFeature(selectionFeature) {\n this._selectionFeature = selectionFeature;\n }\n _onXRFrame(_xrFrame) {\n const frame = this._xrSessionManager.currentFrame;\n const scene = this._xrSessionManager.scene;\n if (!this.attach || !frame) {\n return;\n }\n // render target if needed\n const targetMesh = this._options.teleportationTargetMesh;\n if (this._currentTeleportationControllerId) {\n if (!targetMesh) {\n return;\n }\n targetMesh.rotationQuaternion = targetMesh.rotationQuaternion || new Quaternion();\n const controllerData = this._controllers[this._currentTeleportationControllerId];\n if (controllerData && controllerData.teleportationState.forward) {\n // set the rotation\n Quaternion.RotationYawPitchRollToRef(controllerData.teleportationState.currentRotation + controllerData.teleportationState.baseRotation, 0, 0, targetMesh.rotationQuaternion);\n // set the ray and position\n let hitPossible = false;\n controllerData.xrController.getWorldPointerRayToRef(this._tmpRay);\n if (this.straightRayEnabled) {\n // first check if direct ray possible\n // pick grounds that are LOWER only. upper will use parabolic path\n const pick = scene.pickWithRay(this._tmpRay, (o) => {\n // check for mesh-blockers\n if (this._options.pickBlockerMeshes && this._options.pickBlockerMeshes.indexOf(o) !== -1) {\n return true;\n }\n const index = this._floorMeshes.indexOf(o);\n if (index === -1) {\n return false;\n }\n return this._floorMeshes[index].absolutePosition.y < this._options.xrInput.xrCamera.globalPosition.y;\n });\n if (pick && pick.pickedMesh && this._options.pickBlockerMeshes && this._options.pickBlockerMeshes.indexOf(pick.pickedMesh) !== -1) {\n controllerData.teleportationState.blocked = true;\n this._setTargetMeshVisibility(false);\n this._showParabolicPath(pick);\n return;\n }\n else if (pick && pick.pickedPoint) {\n controllerData.teleportationState.blocked = false;\n hitPossible = true;\n this._setTargetMeshPosition(pick);\n this._setTargetMeshVisibility(true);\n this._showParabolicPath(pick);\n }\n }\n // straight ray is still the main ray, but disabling the straight line will force parabolic line.\n if (this.parabolicRayEnabled && !hitPossible) {\n // radius compensation according to pointer rotation around X\n const xRotation = controllerData.xrController.pointer.rotationQuaternion.toEulerAngles().x;\n const compensation = 1 + (Math.PI / 2 - Math.abs(xRotation));\n // check parabolic ray\n const radius = this.parabolicCheckRadius * compensation;\n this._tmpRay.origin.addToRef(this._tmpRay.direction.scale(radius * 2), this._tmpVector);\n this._tmpVector.y = this._tmpRay.origin.y;\n this._tmpRay.origin.addInPlace(this._tmpRay.direction.scale(radius));\n this._tmpVector.subtractToRef(this._tmpRay.origin, this._tmpRay.direction);\n this._tmpRay.direction.normalize();\n const pick = scene.pickWithRay(this._tmpRay, (o) => {\n // check for mesh-blockers\n if (this._options.pickBlockerMeshes && this._options.pickBlockerMeshes.indexOf(o) !== -1) {\n return true;\n }\n return this._floorMeshes.indexOf(o) !== -1;\n });\n if (pick && pick.pickedMesh && this._options.pickBlockerMeshes && this._options.pickBlockerMeshes.indexOf(pick.pickedMesh) !== -1) {\n controllerData.teleportationState.blocked = true;\n this._setTargetMeshVisibility(false);\n this._showParabolicPath(pick);\n return;\n }\n else if (pick && pick.pickedPoint) {\n controllerData.teleportationState.blocked = false;\n hitPossible = true;\n this._setTargetMeshPosition(pick);\n this._setTargetMeshVisibility(true);\n this._showParabolicPath(pick);\n }\n }\n // if needed, set visible:\n this._setTargetMeshVisibility(hitPossible);\n }\n else {\n this._setTargetMeshVisibility(false);\n }\n }\n else {\n this._disposeBezierCurve();\n this._setTargetMeshVisibility(false);\n }\n }\n _createDefaultTargetMesh() {\n // set defaults\n this._options.defaultTargetMeshOptions = this._options.defaultTargetMeshOptions || {};\n const sceneToRenderTo = this._options.useUtilityLayer\n ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene\n : this._xrSessionManager.scene;\n const teleportationTarget = CreateGround(\"teleportationTarget\", { width: 2, height: 2, subdivisions: 2 }, sceneToRenderTo);\n teleportationTarget.isPickable = false;\n if (this._options.defaultTargetMeshOptions.teleportationCircleMaterial) {\n teleportationTarget.material = this._options.defaultTargetMeshOptions.teleportationCircleMaterial;\n }\n else {\n const length = 512;\n const dynamicTexture = new DynamicTexture(\"teleportationPlaneDynamicTexture\", length, sceneToRenderTo, true);\n dynamicTexture.hasAlpha = true;\n const context = dynamicTexture.getContext();\n const centerX = length / 2;\n const centerY = length / 2;\n const radius = 200;\n context.beginPath();\n context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);\n context.fillStyle = this._options.defaultTargetMeshOptions.teleportationFillColor || \"#444444\";\n context.fill();\n context.lineWidth = 10;\n context.strokeStyle = this._options.defaultTargetMeshOptions.teleportationBorderColor || \"#FFFFFF\";\n context.stroke();\n context.closePath();\n dynamicTexture.update();\n const teleportationCircleMaterial = new StandardMaterial(\"teleportationPlaneMaterial\", sceneToRenderTo);\n teleportationCircleMaterial.diffuseTexture = dynamicTexture;\n teleportationTarget.material = teleportationCircleMaterial;\n }\n const torus = CreateTorus(\"torusTeleportation\", {\n diameter: 0.75,\n thickness: 0.1,\n tessellation: 20,\n }, sceneToRenderTo);\n torus.isPickable = false;\n torus.parent = teleportationTarget;\n if (!this._options.defaultTargetMeshOptions.disableAnimation) {\n const animationInnerCircle = new Animation(\"animationInnerCircle\", \"position.y\", 30, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CYCLE);\n const keys = [];\n keys.push({\n frame: 0,\n value: 0,\n });\n keys.push({\n frame: 30,\n value: 0.4,\n });\n keys.push({\n frame: 60,\n value: 0,\n });\n animationInnerCircle.setKeys(keys);\n const easingFunction = new SineEase();\n easingFunction.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT);\n animationInnerCircle.setEasingFunction(easingFunction);\n torus.animations = [];\n torus.animations.push(animationInnerCircle);\n sceneToRenderTo.beginAnimation(torus, 0, 60, true);\n }\n const cone = CreateCylinder(\"rotationCone\", { diameterTop: 0, tessellation: 4 }, sceneToRenderTo);\n cone.isPickable = false;\n cone.scaling.set(0.5, 0.12, 0.2);\n cone.rotate(Axis.X, Math.PI / 2);\n cone.position.z = 0.6;\n cone.parent = torus;\n if (this._options.defaultTargetMeshOptions.torusArrowMaterial) {\n torus.material = this._options.defaultTargetMeshOptions.torusArrowMaterial;\n cone.material = this._options.defaultTargetMeshOptions.torusArrowMaterial;\n }\n else {\n const torusConeMaterial = new StandardMaterial(\"torusConsMat\", sceneToRenderTo);\n torusConeMaterial.disableLighting = !!this._options.defaultTargetMeshOptions.disableLighting;\n if (torusConeMaterial.disableLighting) {\n torusConeMaterial.emissiveColor = new Color3(0.3, 0.3, 1.0);\n }\n else {\n torusConeMaterial.diffuseColor = new Color3(0.3, 0.3, 1.0);\n }\n torusConeMaterial.alpha = 0.9;\n torus.material = torusConeMaterial;\n cone.material = torusConeMaterial;\n this._teleportationRingMaterial = torusConeMaterial;\n }\n if (this._options.renderingGroupId !== undefined) {\n teleportationTarget.renderingGroupId = this._options.renderingGroupId;\n torus.renderingGroupId = this._options.renderingGroupId;\n cone.renderingGroupId = this._options.renderingGroupId;\n }\n this._options.teleportationTargetMesh = teleportationTarget;\n // hide the teleportation target mesh right after creating it.\n this._setTargetMeshVisibility(false);\n }\n _detachController(xrControllerUniqueId) {\n const controllerData = this._controllers[xrControllerUniqueId];\n if (!controllerData) {\n return;\n }\n if (controllerData.teleportationComponent) {\n if (controllerData.onAxisChangedObserver) {\n controllerData.teleportationComponent.onAxisValueChangedObservable.remove(controllerData.onAxisChangedObserver);\n }\n if (controllerData.onButtonChangedObserver) {\n controllerData.teleportationComponent.onButtonStateChangedObservable.remove(controllerData.onButtonChangedObserver);\n }\n }\n // remove from the map\n delete this._controllers[xrControllerUniqueId];\n }\n _findClosestSnapPointWithRadius(realPosition, radius = this._options.snapToPositionRadius || 0.8) {\n let closestPoint = null;\n let closestDistance = Number.MAX_VALUE;\n if (this._snapToPositions.length) {\n const radiusSquared = radius * radius;\n this._snapToPositions.forEach((position) => {\n const dist = Vector3.DistanceSquared(position, realPosition);\n if (dist <= radiusSquared && dist < closestDistance) {\n closestDistance = dist;\n closestPoint = position;\n }\n });\n }\n return closestPoint;\n }\n _setTargetMeshPosition(pickInfo) {\n const newPosition = pickInfo.pickedPoint;\n if (!this._options.teleportationTargetMesh || !newPosition) {\n return;\n }\n const snapPosition = this._findClosestSnapPointWithRadius(newPosition);\n this._snappedToPoint = !!snapPosition;\n if (this.snapPointsOnly && !this._snappedToPoint && this._teleportationRingMaterial) {\n this._teleportationRingMaterial.diffuseColor.set(1.0, 0.3, 0.3);\n }\n else if (this.snapPointsOnly && this._snappedToPoint && this._teleportationRingMaterial) {\n this._teleportationRingMaterial.diffuseColor.set(0.3, 0.3, 1.0);\n }\n this._options.teleportationTargetMesh.position.copyFrom(snapPosition || newPosition);\n this._options.teleportationTargetMesh.position.y += 0.01;\n this.onTargetMeshPositionUpdatedObservable.notifyObservers(pickInfo);\n }\n _setTargetMeshVisibility(visible, force) {\n if (!this._options.teleportationTargetMesh) {\n return;\n }\n if (this._options.teleportationTargetMesh.isVisible === visible && !force) {\n return;\n }\n this._options.teleportationTargetMesh.isVisible = visible;\n this._options.teleportationTargetMesh.getChildren(undefined, false).forEach((m) => {\n m.isVisible = visible;\n });\n if (!visible) {\n if (this._quadraticBezierCurve) {\n this._quadraticBezierCurve.dispose();\n this._quadraticBezierCurve = null;\n }\n if (this._selectionFeature) {\n this._selectionFeature.attach();\n }\n }\n else {\n if (this._selectionFeature) {\n this._selectionFeature.detach();\n }\n }\n }\n _disposeBezierCurve() {\n if (this._quadraticBezierCurve) {\n this._quadraticBezierCurve.dispose();\n this._quadraticBezierCurve = null;\n }\n }\n _showParabolicPath(pickInfo) {\n if (!pickInfo.pickedPoint || !this._currentTeleportationControllerId) {\n return;\n }\n const sceneToRenderTo = this._options.useUtilityLayer\n ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene\n : this._xrSessionManager.scene;\n const controllerData = this._controllers[this._currentTeleportationControllerId];\n const quadraticBezierVectors = Curve3.CreateQuadraticBezier(controllerData.xrController.pointer.absolutePosition, pickInfo.ray.origin, pickInfo.pickedPoint, 25);\n const color = controllerData.teleportationState.blocked ? this._blockedRayColor : undefined;\n const colorsArray = new Array(26).fill(color || this._cachedColor4White);\n if (!this._options.generateRayPathMesh) {\n this._quadraticBezierCurve = CreateLines(\"teleportation path line\", { points: quadraticBezierVectors.getPoints(), instance: this._quadraticBezierCurve, updatable: true, colors: colorsArray }, sceneToRenderTo);\n }\n else {\n this._quadraticBezierCurve = this._options.generateRayPathMesh(quadraticBezierVectors.getPoints(), pickInfo);\n }\n this._quadraticBezierCurve.isPickable = false;\n if (this._options.renderingGroupId !== undefined) {\n this._quadraticBezierCurve.renderingGroupId = this._options.renderingGroupId;\n }\n }\n _teleportForward(controllerId) {\n const controllerData = this._controllers[controllerId];\n if (!controllerData || !controllerData.teleportationState.forward || !this.teleportationEnabled) {\n return;\n }\n controllerData.teleportationState.forward = false;\n this._currentTeleportationControllerId = \"\";\n if (this.snapPointsOnly && !this._snappedToPoint) {\n return;\n }\n if (this.skipNextTeleportation) {\n this.skipNextTeleportation = false;\n return;\n }\n // do the movement forward here\n if (this._options.teleportationTargetMesh && this._options.teleportationTargetMesh.isVisible) {\n const height = this._options.xrInput.xrCamera.realWorldHeight;\n this._options.xrInput.xrCamera.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position);\n this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position);\n this._options.xrInput.xrCamera.position.y += height;\n Quaternion.FromEulerAngles(0, controllerData.teleportationState.currentRotation - (this._xrSessionManager.scene.useRightHandedSystem ? Math.PI : 0), 0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion, this._options.xrInput.xrCamera.rotationQuaternion);\n this._options.xrInput.xrCamera.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position);\n }\n }\n}\n/**\n * The module's name\n */\nWebXRMotionControllerTeleportation.Name = WebXRFeatureName.TELEPORTATION;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the webxr specs version\n */\nWebXRMotionControllerTeleportation.Version = 1;\nWebXRFeaturesManager.AddWebXRFeature(WebXRMotionControllerTeleportation.Name, (xrSessionManager, options) => {\n return () => new WebXRMotionControllerTeleportation(xrSessionManager, options);\n}, WebXRMotionControllerTeleportation.Version, true);\n//# sourceMappingURL=WebXRControllerTeleportation.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { Scene } from \"../scene.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { StandardMaterial } from \"../Materials/standardMaterial.js\";\nimport { PBRMaterial } from \"../Materials/PBR/pbrMaterial.js\";\nimport { HemisphericLight } from \"../Lights/hemisphericLight.js\";\nimport { EnvironmentHelper } from \"./environmentHelper.js\";\nimport { FreeCamera } from \"../Cameras/freeCamera.js\";\nimport { ArcRotateCamera } from \"../Cameras/arcRotateCamera.js\";\nimport { VRExperienceHelper } from \"../Cameras/VR/vrExperienceHelper.js\";\nimport \"../Materials/Textures/Loaders/ddsTextureLoader.js\";\nimport \"../Materials/Textures/Loaders/envTextureLoader.js\";\nimport \"../Materials/Textures/Loaders/ktxTextureLoader.js\";\nimport { CreateBox } from \"../Meshes/Builders/boxBuilder.js\";\nimport { WebXRDefaultExperience } from \"../XR/webXRDefaultExperience.js\";\n/** @internal */\n// eslint-disable-next-line no-var\nexport var _forceSceneHelpersToBundle = true;\nScene.prototype.createDefaultLight = function (replace = false) {\n // Dispose existing light in replace mode.\n if (replace) {\n if (this.lights) {\n for (let i = 0; i < this.lights.length; i++) {\n this.lights[i].dispose();\n }\n }\n }\n // Light\n if (this.lights.length === 0) {\n new HemisphericLight(\"default light\", Vector3.Up(), this);\n }\n};\nScene.prototype.createDefaultCamera = function (createArcRotateCamera = false, replace = false, attachCameraControls = false) {\n // Dispose existing camera in replace mode.\n if (replace) {\n if (this.activeCamera) {\n this.activeCamera.dispose();\n this.activeCamera = null;\n }\n }\n // Camera\n if (!this.activeCamera) {\n const worldExtends = this.getWorldExtends((mesh) => mesh.isVisible && mesh.isEnabled());\n const worldSize = worldExtends.max.subtract(worldExtends.min);\n const worldCenter = worldExtends.min.add(worldSize.scale(0.5));\n let camera;\n let radius = worldSize.length() * 1.5;\n // empty scene scenario!\n if (!isFinite(radius)) {\n radius = 1;\n worldCenter.copyFromFloats(0, 0, 0);\n }\n if (createArcRotateCamera) {\n const arcRotateCamera = new ArcRotateCamera(\"default camera\", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);\n arcRotateCamera.lowerRadiusLimit = radius * 0.01;\n arcRotateCamera.wheelPrecision = 100 / radius;\n camera = arcRotateCamera;\n }\n else {\n const freeCamera = new FreeCamera(\"default camera\", new Vector3(worldCenter.x, worldCenter.y, -radius), this);\n freeCamera.setTarget(worldCenter);\n camera = freeCamera;\n }\n camera.minZ = radius * 0.01;\n camera.maxZ = radius * 1000;\n camera.speed = radius * 0.2;\n this.activeCamera = camera;\n if (attachCameraControls) {\n camera.attachControl();\n }\n }\n};\nScene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera = false, replace = false, attachCameraControls = false) {\n this.createDefaultLight(replace);\n this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);\n};\nScene.prototype.createDefaultSkybox = function (environmentTexture, pbr = false, scale = 1000, blur = 0, setGlobalEnvTexture = true) {\n if (!environmentTexture) {\n Logger.Warn(\"Can not create default skybox without environment texture.\");\n return null;\n }\n if (setGlobalEnvTexture) {\n if (environmentTexture) {\n this.environmentTexture = environmentTexture;\n }\n }\n // Skybox\n const hdrSkybox = CreateBox(\"hdrSkyBox\", { size: scale }, this);\n if (pbr) {\n const hdrSkyboxMaterial = new PBRMaterial(\"skyBox\", this);\n hdrSkyboxMaterial.backFaceCulling = false;\n hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();\n if (hdrSkyboxMaterial.reflectionTexture) {\n hdrSkyboxMaterial.reflectionTexture.coordinatesMode = Texture.SKYBOX_MODE;\n }\n hdrSkyboxMaterial.microSurface = 1.0 - blur;\n hdrSkyboxMaterial.disableLighting = true;\n hdrSkyboxMaterial.twoSidedLighting = true;\n hdrSkybox.material = hdrSkyboxMaterial;\n }\n else {\n const skyboxMaterial = new StandardMaterial(\"skyBox\", this);\n skyboxMaterial.backFaceCulling = false;\n skyboxMaterial.reflectionTexture = environmentTexture.clone();\n if (skyboxMaterial.reflectionTexture) {\n skyboxMaterial.reflectionTexture.coordinatesMode = Texture.SKYBOX_MODE;\n }\n skyboxMaterial.disableLighting = true;\n hdrSkybox.material = skyboxMaterial;\n }\n hdrSkybox.isPickable = false;\n hdrSkybox.infiniteDistance = true;\n hdrSkybox.ignoreCameraMaxZ = true;\n return hdrSkybox;\n};\nScene.prototype.createDefaultEnvironment = function (options) {\n if (EnvironmentHelper) {\n return new EnvironmentHelper(options, this);\n }\n return null;\n};\nScene.prototype.createDefaultVRExperience = function (webVROptions = {}) {\n return new VRExperienceHelper(this, webVROptions);\n};\nScene.prototype.createDefaultXRExperienceAsync = function (options = {}) {\n return WebXRDefaultExperience.CreateAsync(this, options).then((helper) => {\n return helper;\n });\n};\n//# sourceMappingURL=sceneHelpers.js.map","import { WebXRExperienceHelper } from \"./webXRExperienceHelper.js\";\nimport { WebXRInput } from \"./webXRInput.js\";\nimport { WebXRControllerPointerSelection } from \"./features/WebXRControllerPointerSelection.js\";\nimport { WebXRNearInteraction } from \"./features/WebXRNearInteraction.js\";\nimport { WebXREnterExitUI } from \"./webXREnterExitUI.js\";\nimport { WebXRMotionControllerTeleportation } from \"./features/WebXRControllerTeleportation.js\";\nimport { Logger } from \"../Misc/logger.js\";\n/**\n * Options for the default xr helper\n */\nexport class WebXRDefaultExperienceOptions {\n}\n/**\n * Default experience which provides a similar setup to the previous webVRExperience\n */\nexport class WebXRDefaultExperience {\n constructor() { }\n /**\n * Creates the default xr experience\n * @param scene scene\n * @param options options for basic configuration\n * @returns resulting WebXRDefaultExperience\n */\n static CreateAsync(scene, options = {}) {\n const result = new WebXRDefaultExperience();\n scene.onDisposeObservable.addOnce(() => {\n result.dispose();\n });\n // init the UI right after construction\n if (!options.disableDefaultUI) {\n const uiOptions = Object.assign({ renderTarget: result.renderTarget }, (options.uiOptions || {}));\n if (options.optionalFeatures) {\n if (typeof options.optionalFeatures === \"boolean\") {\n uiOptions.optionalFeatures = [\"hit-test\", \"anchors\", \"plane-detection\", \"hand-tracking\"];\n }\n else {\n uiOptions.optionalFeatures = options.optionalFeatures;\n }\n }\n result.enterExitUI = new WebXREnterExitUI(scene, uiOptions);\n }\n // Create base experience\n return WebXRExperienceHelper.CreateAsync(scene)\n .then((xrHelper) => {\n result.baseExperience = xrHelper;\n if (options.ignoreNativeCameraTransformation) {\n result.baseExperience.camera.compensateOnFirstFrame = false;\n }\n // Add controller support\n result.input = new WebXRInput(xrHelper.sessionManager, xrHelper.camera, Object.assign({ controllerOptions: {\n renderingGroupId: options.renderingGroupId,\n } }, (options.inputOptions || {})));\n if (!options.disablePointerSelection) {\n // Add default pointer selection\n const pointerSelectionOptions = Object.assign(Object.assign({}, options.pointerSelectionOptions), { xrInput: result.input, renderingGroupId: options.renderingGroupId });\n result.pointerSelection = (result.baseExperience.featuresManager.enableFeature(WebXRControllerPointerSelection.Name, options.useStablePlugins ? \"stable\" : \"latest\", pointerSelectionOptions));\n if (!options.disableTeleportation) {\n // Add default teleportation, including rotation\n result.teleportation = result.baseExperience.featuresManager.enableFeature(WebXRMotionControllerTeleportation.Name, options.useStablePlugins ? \"stable\" : \"latest\", Object.assign({ floorMeshes: options.floorMeshes, xrInput: result.input, renderingGroupId: options.renderingGroupId }, options.teleportationOptions));\n result.teleportation.setSelectionFeature(result.pointerSelection);\n }\n }\n if (!options.disableNearInteraction) {\n // Add default pointer selection\n result.nearInteraction = result.baseExperience.featuresManager.enableFeature(WebXRNearInteraction.Name, options.useStablePlugins ? \"stable\" : \"latest\", Object.assign({ xrInput: result.input, farInteractionFeature: result.pointerSelection, renderingGroupId: options.renderingGroupId, useUtilityLayer: true, enableNearInteractionOnAllControllers: true }, options.nearInteractionOptions));\n }\n // Create the WebXR output target\n result.renderTarget = result.baseExperience.sessionManager.getWebXRRenderTarget(options.outputCanvasOptions);\n if (!options.disableDefaultUI) {\n // Create ui for entering/exiting xr\n return result.enterExitUI.setHelperAsync(result.baseExperience, result.renderTarget);\n }\n else {\n return;\n }\n })\n .then(() => {\n return result;\n })\n .catch((error) => {\n Logger.Error(\"Error initializing XR\");\n Logger.Error(error);\n return result;\n });\n }\n /**\n * Disposes of the experience helper\n */\n dispose() {\n if (this.baseExperience) {\n this.baseExperience.dispose();\n }\n if (this.input) {\n this.input.dispose();\n }\n if (this.enterExitUI) {\n this.enterExitUI.dispose();\n }\n if (this.renderTarget) {\n this.renderTarget.dispose();\n }\n }\n}\n//# sourceMappingURL=webXRDefaultExperience.js.map","import { Observable } from \"../../Misc/observable.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { Texture } from \"../../Materials/Textures/texture.js\";\n\nimport \"../../Engines/Extensions/engine.videoTexture.js\";\nimport \"../../Engines/Extensions/engine.dynamicTexture.js\";\nfunction removeSource(video) {\n // Remove any elements, etc.\n while (video.firstChild) {\n video.removeChild(video.firstChild);\n }\n // detach srcObject\n video.srcObject = null;\n // Set a blank src (https://html.spec.whatwg.org/multipage/media.html#best-practices-for-authors-using-media-elements)\n video.src = \"\";\n // Prevent non-important errors maybe (https://twitter.com/beraliv/status/1205214277956775936)\n video.removeAttribute(\"src\");\n}\n/**\n * If you want to display a video in your scene, this is the special texture for that.\n * This special texture works similar to other textures, with the exception of a few parameters.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/videoTexture\n */\nexport class VideoTexture extends Texture {\n /**\n * Event triggered when a dom action is required by the user to play the video.\n * This happens due to recent changes in browser policies preventing video to auto start.\n */\n get onUserActionRequestedObservable() {\n if (!this._onUserActionRequestedObservable) {\n this._onUserActionRequestedObservable = new Observable();\n }\n return this._onUserActionRequestedObservable;\n }\n _processError(reason) {\n this._errorFound = true;\n if (this._onError) {\n this._onError(reason === null || reason === void 0 ? void 0 : reason.message);\n }\n else {\n Logger.Error(reason === null || reason === void 0 ? void 0 : reason.message);\n }\n }\n _handlePlay() {\n this._errorFound = false;\n this.video.play().catch((reason) => {\n if ((reason === null || reason === void 0 ? void 0 : reason.name) === \"NotAllowedError\") {\n if (this._onUserActionRequestedObservable && this._onUserActionRequestedObservable.hasObservers()) {\n this._onUserActionRequestedObservable.notifyObservers(this);\n return;\n }\n else if (!this.video.muted) {\n Logger.Warn(\"Unable to autoplay a video with sound. Trying again with muted turned true\");\n this.video.muted = true;\n this._errorFound = false;\n this.video.play().catch((otherReason) => {\n this._processError(otherReason);\n });\n return;\n }\n }\n this._processError(reason);\n });\n }\n /**\n * Creates a video texture.\n * If you want to display a video in your scene, this is the special texture for that.\n * This special texture works similar to other textures, with the exception of a few parameters.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/videoTexture\n * @param name optional name, will detect from video source, if not defined\n * @param src can be used to provide an url, array of urls or an already setup HTML video element.\n * @param scene is obviously the current scene.\n * @param generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).\n * @param invertY is false by default but can be used to invert video on Y axis\n * @param samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default\n * @param settings allows finer control over video usage\n * @param onError defines a callback triggered when an error occurred during the loading session\n * @param format defines the texture format to use (Engine.TEXTUREFORMAT_RGBA by default)\n */\n constructor(name, src, scene, generateMipMaps = false, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, settings = {}, onError, format = 5) {\n var _a, _b;\n super(null, scene, !generateMipMaps, invertY);\n this._onUserActionRequestedObservable = null;\n this._stillImageCaptured = false;\n this._displayingPosterTexture = false;\n this._frameId = -1;\n this._currentSrc = null;\n this._errorFound = false;\n this._resizeInternalTexture = () => {\n var _a;\n // Cleanup the old texture before replacing it\n if (this._texture != null) {\n this._texture.dispose();\n }\n if (!this._getEngine().needPOTTextures || (Tools.IsExponentOfTwo(this.video.videoWidth) && Tools.IsExponentOfTwo(this.video.videoHeight))) {\n this.wrapU = Texture.WRAP_ADDRESSMODE;\n this.wrapV = Texture.WRAP_ADDRESSMODE;\n }\n else {\n this.wrapU = Texture.CLAMP_ADDRESSMODE;\n this.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._generateMipMaps = false;\n }\n this._texture = this._getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this.samplingMode);\n this._texture.format = (_a = this._format) !== null && _a !== void 0 ? _a : 5;\n // Reset the frame ID and update the new texture to ensure it pulls in the current video frame\n this._frameId = -1;\n this._updateInternalTexture();\n };\n this._createInternalTexture = () => {\n if (this._texture != null) {\n if (this._displayingPosterTexture) {\n this._displayingPosterTexture = false;\n }\n else {\n return;\n }\n }\n this.video.addEventListener(\"resize\", this._resizeInternalTexture);\n this._resizeInternalTexture();\n if (!this.video.autoplay && !this._settings.poster && !this._settings.independentVideoSource) {\n const oldHandler = this.video.onplaying;\n const oldMuted = this.video.muted;\n this.video.muted = true;\n this.video.onplaying = () => {\n this.video.muted = oldMuted;\n this.video.onplaying = oldHandler;\n this._updateInternalTexture();\n if (!this._errorFound) {\n this.video.pause();\n }\n if (this.onLoadObservable.hasObservers()) {\n this.onLoadObservable.notifyObservers(this);\n }\n };\n this._handlePlay();\n }\n else {\n this._updateInternalTexture();\n if (this.onLoadObservable.hasObservers()) {\n this.onLoadObservable.notifyObservers(this);\n }\n }\n };\n this._reset = () => {\n if (this._texture == null) {\n return;\n }\n if (!this._displayingPosterTexture) {\n this._texture.dispose();\n this._texture = null;\n }\n };\n this._updateInternalTexture = () => {\n if (this._texture == null) {\n return;\n }\n if (this.video.readyState < this.video.HAVE_CURRENT_DATA) {\n return;\n }\n if (this._displayingPosterTexture) {\n return;\n }\n const frameId = this.getScene().getFrameId();\n if (this._frameId === frameId) {\n return;\n }\n this._frameId = frameId;\n this._getEngine().updateVideoTexture(this._texture, this._externalTexture ? this._externalTexture : this.video, this._invertY);\n };\n this._settings = Object.assign({ autoPlay: true, loop: true, autoUpdateTexture: true }, settings);\n this._onError = onError;\n this._generateMipMaps = generateMipMaps;\n this._initialSamplingMode = samplingMode;\n this.autoUpdateTexture = this._settings.autoUpdateTexture;\n this._currentSrc = src;\n this.name = name || this._getName(src);\n this.video = this._getVideo(src);\n this._externalTexture = (_b = (_a = this._engine) === null || _a === void 0 ? void 0 : _a.createExternalTexture(this.video)) !== null && _b !== void 0 ? _b : null;\n if (!this._settings.independentVideoSource) {\n if (this._settings.poster) {\n this.video.poster = this._settings.poster;\n }\n if (this._settings.autoPlay !== undefined) {\n this.video.autoplay = this._settings.autoPlay;\n }\n if (this._settings.loop !== undefined) {\n this.video.loop = this._settings.loop;\n }\n if (this._settings.muted !== undefined) {\n this.video.muted = this._settings.muted;\n }\n this.video.setAttribute(\"playsinline\", \"\");\n this.video.addEventListener(\"paused\", this._updateInternalTexture);\n this.video.addEventListener(\"seeked\", this._updateInternalTexture);\n this.video.addEventListener(\"emptied\", this._reset);\n if (this._settings.autoPlay) {\n this._handlePlay();\n }\n }\n this._createInternalTextureOnEvent = this._settings.poster && !this._settings.autoPlay ? \"play\" : \"canplay\";\n this.video.addEventListener(this._createInternalTextureOnEvent, this._createInternalTexture);\n this._format = format;\n const videoHasEnoughData = this.video.readyState >= this.video.HAVE_CURRENT_DATA;\n if (this._settings.poster && (!this._settings.autoPlay || !videoHasEnoughData)) {\n this._texture = this._getEngine().createTexture(this._settings.poster, false, !this.invertY, scene);\n this._displayingPosterTexture = true;\n }\n else if (videoHasEnoughData) {\n this._createInternalTexture();\n }\n }\n /**\n * Get the current class name of the video texture useful for serialization or dynamic coding.\n * @returns \"VideoTexture\"\n */\n getClassName() {\n return \"VideoTexture\";\n }\n _getName(src) {\n if (src instanceof HTMLVideoElement) {\n return src.currentSrc;\n }\n if (typeof src === \"object\") {\n return src.toString();\n }\n return src;\n }\n _getVideo(src) {\n if (src.isNative) {\n return src;\n }\n if (src instanceof HTMLVideoElement) {\n Tools.SetCorsBehavior(src.currentSrc, src);\n return src;\n }\n const video = document.createElement(\"video\");\n if (typeof src === \"string\") {\n Tools.SetCorsBehavior(src, video);\n video.src = src;\n }\n else {\n Tools.SetCorsBehavior(src[0], video);\n src.forEach((url) => {\n const source = document.createElement(\"source\");\n source.src = url;\n video.appendChild(source);\n });\n }\n this.onDisposeObservable.addOnce(() => {\n removeSource(video);\n });\n return video;\n }\n /**\n * @internal Internal method to initiate `update`.\n */\n _rebuild() {\n this.update();\n }\n /**\n * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.\n */\n update() {\n if (!this.autoUpdateTexture) {\n // Expecting user to call `updateTexture` manually\n return;\n }\n this.updateTexture(true);\n }\n /**\n * Update Texture in `manual` mode. Does not do anything if not visible or paused.\n * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or otherwise.\n */\n updateTexture(isVisible) {\n if (!isVisible) {\n return;\n }\n if (this.video.paused && this._stillImageCaptured) {\n return;\n }\n this._stillImageCaptured = true;\n this._updateInternalTexture();\n }\n /**\n * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.\n * @param url New url.\n */\n updateURL(url) {\n this.video.src = url;\n this._currentSrc = url;\n }\n /**\n * Clones the texture.\n * @returns the cloned texture\n */\n clone() {\n return new VideoTexture(this.name, this._currentSrc, this.getScene(), this._generateMipMaps, this.invertY, this.samplingMode, this._settings);\n }\n /**\n * Dispose the texture and release its associated resources.\n */\n dispose() {\n var _a;\n super.dispose();\n this._currentSrc = null;\n if (this._onUserActionRequestedObservable) {\n this._onUserActionRequestedObservable.clear();\n this._onUserActionRequestedObservable = null;\n }\n this.video.removeEventListener(this._createInternalTextureOnEvent, this._createInternalTexture);\n if (!this._settings.independentVideoSource) {\n this.video.removeEventListener(\"paused\", this._updateInternalTexture);\n this.video.removeEventListener(\"seeked\", this._updateInternalTexture);\n this.video.removeEventListener(\"emptied\", this._reset);\n this.video.removeEventListener(\"resize\", this._resizeInternalTexture);\n this.video.pause();\n }\n (_a = this._externalTexture) === null || _a === void 0 ? void 0 : _a.dispose();\n }\n /**\n * Creates a video texture straight from a stream.\n * @param scene Define the scene the texture should be created in\n * @param stream Define the stream the texture should be created from\n * @param constraints video constraints\n * @param invertY Defines if the video should be stored with invert Y set to true (true by default)\n * @returns The created video texture as a promise\n */\n static CreateFromStreamAsync(scene, stream, constraints, invertY = true) {\n const video = scene.getEngine().createVideoElement(constraints);\n if (scene.getEngine()._badOS) {\n // Yes... I know and I hope to remove it soon...\n document.body.appendChild(video);\n video.style.transform = \"scale(0.0001, 0.0001)\";\n video.style.opacity = \"0\";\n video.style.position = \"fixed\";\n video.style.bottom = \"0px\";\n video.style.right = \"0px\";\n }\n video.setAttribute(\"autoplay\", \"\");\n video.setAttribute(\"muted\", \"true\");\n video.setAttribute(\"playsinline\", \"\");\n video.muted = true;\n if (video.isNative) {\n // No additional configuration needed for native\n }\n else if (video.mozSrcObject !== undefined) {\n // hack for Firefox < 19\n video.mozSrcObject = stream;\n }\n else {\n if (typeof video.srcObject == \"object\") {\n video.srcObject = stream;\n }\n else {\n // older API. See https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL#using_object_urls_for_media_streams\n video.src = window.URL && window.URL.createObjectURL(stream);\n }\n }\n return new Promise((resolve) => {\n const onPlaying = () => {\n const videoTexture = new VideoTexture(\"video\", video, scene, true, invertY, undefined, undefined, undefined, 4);\n if (scene.getEngine()._badOS) {\n videoTexture.onDisposeObservable.addOnce(() => {\n video.remove();\n });\n }\n videoTexture.onDisposeObservable.addOnce(() => {\n removeSource(video);\n });\n resolve(videoTexture);\n video.removeEventListener(\"playing\", onPlaying);\n };\n video.addEventListener(\"playing\", onPlaying);\n video.play();\n });\n }\n /**\n * Creates a video texture straight from your WebCam video feed.\n * @param scene Define the scene the texture should be created in\n * @param constraints Define the constraints to use to create the web cam feed from WebRTC\n * @param audioConstaints Define the audio constraints to use to create the web cam feed from WebRTC\n * @param invertY Defines if the video should be stored with invert Y set to true (true by default)\n * @returns The created video texture as a promise\n */\n static async CreateFromWebCamAsync(scene, constraints, audioConstaints = false, invertY = true) {\n if (navigator.mediaDevices) {\n const stream = await navigator.mediaDevices.getUserMedia({\n video: constraints,\n audio: audioConstaints,\n });\n const videoTexture = await this.CreateFromStreamAsync(scene, stream, constraints, invertY);\n videoTexture.onDisposeObservable.addOnce(() => {\n stream.getTracks().forEach((track) => {\n track.stop();\n });\n });\n return videoTexture;\n }\n return Promise.reject(\"No support for userMedia on this device\");\n }\n /**\n * Creates a video texture straight from your WebCam video feed.\n * @param scene Defines the scene the texture should be created in\n * @param onReady Defines a callback to triggered once the texture will be ready\n * @param constraints Defines the constraints to use to create the web cam feed from WebRTC\n * @param audioConstaints Defines the audio constraints to use to create the web cam feed from WebRTC\n * @param invertY Defines if the video should be stored with invert Y set to true (true by default)\n */\n static CreateFromWebCam(scene, onReady, constraints, audioConstaints = false, invertY = true) {\n this.CreateFromWebCamAsync(scene, constraints, audioConstaints, invertY)\n .then(function (videoTexture) {\n if (onReady) {\n onReady(videoTexture);\n }\n })\n .catch(function (err) {\n Logger.Error(err.name);\n });\n }\n}\n//# sourceMappingURL=videoTexture.js.map","import { Texture } from \"../Materials/Textures/texture.js\";\nimport { VideoTexture } from \"../Materials/Textures/videoTexture.js\";\nimport { TextureDome } from \"./textureDome.js\";\nimport { PointerEventTypes } from \"../Events/pointerEvents.js\";\n/**\n * Display a 360/180 degree video on an approximately spherical surface, useful for VR applications or skyboxes.\n * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.\n * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.\n * Potential additions to this helper include zoom and and non-infinite distance rendering effects.\n */\nexport class VideoDome extends TextureDome {\n /**\n * Get the video texture associated with this video dome\n */\n get videoTexture() {\n return this._texture;\n }\n /**\n * Get the video mode of this dome\n */\n get videoMode() {\n return this.textureMode;\n }\n /**\n * Set the video mode of this dome.\n * @see textureMode\n */\n set videoMode(value) {\n this.textureMode = value;\n }\n _initTexture(urlsOrElement, scene, options) {\n const tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };\n const texture = new VideoTexture((this.name || \"videoDome\") + \"_texture\", urlsOrElement, scene, options.generateMipMaps, this._useDirectMapping, Texture.TRILINEAR_SAMPLINGMODE, tempOptions);\n // optional configuration\n if (options.clickToPlay) {\n this._pointerObserver = scene.onPointerObservable.add((data) => {\n var _a;\n ((_a = data.pickInfo) === null || _a === void 0 ? void 0 : _a.pickedMesh) === this.mesh && this._texture.video.play();\n }, PointerEventTypes.POINTERDOWN);\n }\n this._textureObserver = texture.onLoadObservable.add(() => {\n this.onLoadObservable.notifyObservers();\n });\n return texture;\n }\n /**\n * Releases resources associated with this node.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n dispose(doNotRecurse, disposeMaterialAndTextures = false) {\n this._texture.onLoadObservable.remove(this._textureObserver);\n this._scene.onPointerObservable.remove(this._pointerObserver);\n super.dispose(doNotRecurse, disposeMaterialAndTextures);\n }\n}\n/**\n * Define the video source as a Monoscopic panoramic 360 video.\n */\nVideoDome.MODE_MONOSCOPIC = TextureDome.MODE_MONOSCOPIC;\n/**\n * Define the video source as a Stereoscopic TopBottom/OverUnder panoramic 360 video.\n */\nVideoDome.MODE_TOPBOTTOM = TextureDome.MODE_TOPBOTTOM;\n/**\n * Define the video source as a Stereoscopic Side by Side panoramic 360 video.\n */\nVideoDome.MODE_SIDEBYSIDE = TextureDome.MODE_SIDEBYSIDE;\n//# sourceMappingURL=videoDome.js.map","export * from \"./environmentHelper.js\";\nexport * from \"./photoDome.js\";\nexport * from \"./sceneHelpers.js\";\nexport * from \"./videoDome.js\";\n//# sourceMappingURL=index.js.map","import { PerfCounter } from \"../Misc/perfCounter.js\";\n/**\n * This class can be used to get instrumentation data from a Babylon engine\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#engineinstrumentation\n */\nexport class EngineInstrumentation {\n // Properties\n /**\n * Gets the perf counter used for GPU frame time\n */\n get gpuFrameTimeCounter() {\n return this.engine.getGPUFrameTimeCounter();\n }\n /**\n * Gets the GPU frame time capture status\n */\n get captureGPUFrameTime() {\n return this._captureGPUFrameTime;\n }\n /**\n * Enable or disable the GPU frame time capture\n */\n set captureGPUFrameTime(value) {\n if (value === this._captureGPUFrameTime) {\n return;\n }\n this._captureGPUFrameTime = value;\n this.engine.captureGPUFrameTime(value);\n }\n /**\n * Gets the perf counter used for shader compilation time\n */\n get shaderCompilationTimeCounter() {\n return this._shaderCompilationTime;\n }\n /**\n * Gets the shader compilation time capture status\n */\n get captureShaderCompilationTime() {\n return this._captureShaderCompilationTime;\n }\n /**\n * Enable or disable the shader compilation time capture\n */\n set captureShaderCompilationTime(value) {\n if (value === this._captureShaderCompilationTime) {\n return;\n }\n this._captureShaderCompilationTime = value;\n if (value) {\n this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(() => {\n this._shaderCompilationTime.fetchNewFrame();\n this._shaderCompilationTime.beginMonitoring();\n });\n this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(() => {\n this._shaderCompilationTime.endMonitoring();\n });\n }\n else {\n this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);\n this._onBeforeShaderCompilationObserver = null;\n this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);\n this._onAfterShaderCompilationObserver = null;\n }\n }\n /**\n * Instantiates a new engine instrumentation.\n * This class can be used to get instrumentation data from a Babylon engine\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#engineinstrumentation\n * @param engine Defines the engine to instrument\n */\n constructor(\n /**\n * Define the instrumented engine.\n */\n engine) {\n this.engine = engine;\n this._captureGPUFrameTime = false;\n this._captureShaderCompilationTime = false;\n this._shaderCompilationTime = new PerfCounter();\n // Observers\n this._onBeginFrameObserver = null;\n this._onEndFrameObserver = null;\n this._onBeforeShaderCompilationObserver = null;\n this._onAfterShaderCompilationObserver = null;\n }\n /**\n * Dispose and release associated resources.\n */\n dispose() {\n this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);\n this._onBeginFrameObserver = null;\n this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);\n this._onEndFrameObserver = null;\n this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);\n this._onBeforeShaderCompilationObserver = null;\n this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);\n this._onAfterShaderCompilationObserver = null;\n this.engine = null;\n }\n}\n//# sourceMappingURL=engineInstrumentation.js.map","import { Tools } from \"../Misc/tools.js\";\nimport { PerfCounter } from \"../Misc/perfCounter.js\";\n/**\n * This class can be used to get instrumentation data from a Babylon engine\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#sceneinstrumentation\n */\nexport class SceneInstrumentation {\n // Properties\n /**\n * Gets the perf counter used for active meshes evaluation time\n */\n get activeMeshesEvaluationTimeCounter() {\n return this._activeMeshesEvaluationTime;\n }\n /**\n * Gets the active meshes evaluation time capture status\n */\n get captureActiveMeshesEvaluationTime() {\n return this._captureActiveMeshesEvaluationTime;\n }\n /**\n * Enable or disable the active meshes evaluation time capture\n */\n set captureActiveMeshesEvaluationTime(value) {\n if (value === this._captureActiveMeshesEvaluationTime) {\n return;\n }\n this._captureActiveMeshesEvaluationTime = value;\n if (value) {\n this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(() => {\n Tools.StartPerformanceCounter(\"Active meshes evaluation\");\n this._activeMeshesEvaluationTime.beginMonitoring();\n });\n this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(() => {\n Tools.EndPerformanceCounter(\"Active meshes evaluation\");\n this._activeMeshesEvaluationTime.endMonitoring(false);\n });\n }\n else {\n this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);\n this._onBeforeActiveMeshesEvaluationObserver = null;\n this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);\n this._onAfterActiveMeshesEvaluationObserver = null;\n }\n }\n /**\n * Gets the perf counter used for render targets render time\n */\n get renderTargetsRenderTimeCounter() {\n return this._renderTargetsRenderTime;\n }\n /**\n * Gets the render targets render time capture status\n */\n get captureRenderTargetsRenderTime() {\n return this._captureRenderTargetsRenderTime;\n }\n /**\n * Enable or disable the render targets render time capture\n */\n set captureRenderTargetsRenderTime(value) {\n if (value === this._captureRenderTargetsRenderTime) {\n return;\n }\n this._captureRenderTargetsRenderTime = value;\n if (value) {\n this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(() => {\n Tools.StartPerformanceCounter(\"Render targets rendering\");\n this._renderTargetsRenderTime.beginMonitoring();\n });\n this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(() => {\n Tools.EndPerformanceCounter(\"Render targets rendering\");\n this._renderTargetsRenderTime.endMonitoring(false);\n });\n }\n else {\n this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);\n this._onBeforeRenderTargetsRenderObserver = null;\n this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);\n this._onAfterRenderTargetsRenderObserver = null;\n }\n }\n /**\n * Gets the perf counter used for particles render time\n */\n get particlesRenderTimeCounter() {\n return this._particlesRenderTime;\n }\n /**\n * Gets the particles render time capture status\n */\n get captureParticlesRenderTime() {\n return this._captureParticlesRenderTime;\n }\n /**\n * Enable or disable the particles render time capture\n */\n set captureParticlesRenderTime(value) {\n if (value === this._captureParticlesRenderTime) {\n return;\n }\n this._captureParticlesRenderTime = value;\n if (value) {\n this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(() => {\n Tools.StartPerformanceCounter(\"Particles\");\n this._particlesRenderTime.beginMonitoring();\n });\n this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(() => {\n Tools.EndPerformanceCounter(\"Particles\");\n this._particlesRenderTime.endMonitoring(false);\n });\n }\n else {\n this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);\n this._onBeforeParticlesRenderingObserver = null;\n this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);\n this._onAfterParticlesRenderingObserver = null;\n }\n }\n /**\n * Gets the perf counter used for sprites render time\n */\n get spritesRenderTimeCounter() {\n return this._spritesRenderTime;\n }\n /**\n * Gets the sprites render time capture status\n */\n get captureSpritesRenderTime() {\n return this._captureSpritesRenderTime;\n }\n /**\n * Enable or disable the sprites render time capture\n */\n set captureSpritesRenderTime(value) {\n if (value === this._captureSpritesRenderTime) {\n return;\n }\n this._captureSpritesRenderTime = value;\n if (!this.scene.spriteManagers) {\n return;\n }\n if (value) {\n this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(() => {\n Tools.StartPerformanceCounter(\"Sprites\");\n this._spritesRenderTime.beginMonitoring();\n });\n this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(() => {\n Tools.EndPerformanceCounter(\"Sprites\");\n this._spritesRenderTime.endMonitoring(false);\n });\n }\n else {\n this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);\n this._onBeforeSpritesRenderingObserver = null;\n this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);\n this._onAfterSpritesRenderingObserver = null;\n }\n }\n /**\n * Gets the perf counter used for physics time\n */\n get physicsTimeCounter() {\n return this._physicsTime;\n }\n /**\n * Gets the physics time capture status\n */\n get capturePhysicsTime() {\n return this._capturePhysicsTime;\n }\n /**\n * Enable or disable the physics time capture\n */\n set capturePhysicsTime(value) {\n if (value === this._capturePhysicsTime) {\n return;\n }\n if (!this.scene.onBeforePhysicsObservable) {\n return;\n }\n this._capturePhysicsTime = value;\n if (value) {\n this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(() => {\n Tools.StartPerformanceCounter(\"Physics\");\n this._physicsTime.beginMonitoring();\n });\n this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(() => {\n Tools.EndPerformanceCounter(\"Physics\");\n this._physicsTime.endMonitoring();\n });\n }\n else {\n this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);\n this._onBeforePhysicsObserver = null;\n this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);\n this._onAfterPhysicsObserver = null;\n }\n }\n /**\n * Gets the perf counter used for animations time\n */\n get animationsTimeCounter() {\n return this._animationsTime;\n }\n /**\n * Gets the animations time capture status\n */\n get captureAnimationsTime() {\n return this._captureAnimationsTime;\n }\n /**\n * Enable or disable the animations time capture\n */\n set captureAnimationsTime(value) {\n if (value === this._captureAnimationsTime) {\n return;\n }\n this._captureAnimationsTime = value;\n if (value) {\n this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(() => {\n this._animationsTime.endMonitoring();\n });\n }\n else {\n this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);\n this._onAfterAnimationsObserver = null;\n }\n }\n /**\n * Gets the perf counter used for frame time capture\n */\n get frameTimeCounter() {\n return this._frameTime;\n }\n /**\n * Gets the frame time capture status\n */\n get captureFrameTime() {\n return this._captureFrameTime;\n }\n /**\n * Enable or disable the frame time capture\n */\n set captureFrameTime(value) {\n this._captureFrameTime = value;\n }\n /**\n * Gets the perf counter used for inter-frames time capture\n */\n get interFrameTimeCounter() {\n return this._interFrameTime;\n }\n /**\n * Gets the inter-frames time capture status\n */\n get captureInterFrameTime() {\n return this._captureInterFrameTime;\n }\n /**\n * Enable or disable the inter-frames time capture\n */\n set captureInterFrameTime(value) {\n this._captureInterFrameTime = value;\n }\n /**\n * Gets the perf counter used for render time capture\n */\n get renderTimeCounter() {\n return this._renderTime;\n }\n /**\n * Gets the render time capture status\n */\n get captureRenderTime() {\n return this._captureRenderTime;\n }\n /**\n * Enable or disable the render time capture\n */\n set captureRenderTime(value) {\n if (value === this._captureRenderTime) {\n return;\n }\n this._captureRenderTime = value;\n if (value) {\n this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(() => {\n this._renderTime.beginMonitoring();\n Tools.StartPerformanceCounter(\"Main render\");\n });\n this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(() => {\n this._renderTime.endMonitoring(false);\n Tools.EndPerformanceCounter(\"Main render\");\n });\n }\n else {\n this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);\n this._onBeforeDrawPhaseObserver = null;\n this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);\n this._onAfterDrawPhaseObserver = null;\n }\n }\n /**\n * Gets the perf counter used for camera render time capture\n */\n get cameraRenderTimeCounter() {\n return this._cameraRenderTime;\n }\n /**\n * Gets the camera render time capture status\n */\n get captureCameraRenderTime() {\n return this._captureCameraRenderTime;\n }\n /**\n * Enable or disable the camera render time capture\n */\n set captureCameraRenderTime(value) {\n if (value === this._captureCameraRenderTime) {\n return;\n }\n this._captureCameraRenderTime = value;\n if (value) {\n this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add((camera) => {\n this._cameraRenderTime.beginMonitoring();\n Tools.StartPerformanceCounter(`Rendering camera ${camera.name}`);\n });\n this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add((camera) => {\n this._cameraRenderTime.endMonitoring(false);\n Tools.EndPerformanceCounter(`Rendering camera ${camera.name}`);\n });\n }\n else {\n this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);\n this._onBeforeCameraRenderObserver = null;\n this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);\n this._onAfterCameraRenderObserver = null;\n }\n }\n /**\n * Gets the perf counter used for draw calls\n */\n get drawCallsCounter() {\n return this.scene.getEngine()._drawCalls;\n }\n /**\n * Instantiates a new scene instrumentation.\n * This class can be used to get instrumentation data from a Babylon engine\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#sceneinstrumentation\n * @param scene Defines the scene to instrument\n */\n constructor(\n /**\n * Defines the scene to instrument\n */\n scene) {\n this.scene = scene;\n this._captureActiveMeshesEvaluationTime = false;\n this._activeMeshesEvaluationTime = new PerfCounter();\n this._captureRenderTargetsRenderTime = false;\n this._renderTargetsRenderTime = new PerfCounter();\n this._captureFrameTime = false;\n this._frameTime = new PerfCounter();\n this._captureRenderTime = false;\n this._renderTime = new PerfCounter();\n this._captureInterFrameTime = false;\n this._interFrameTime = new PerfCounter();\n this._captureParticlesRenderTime = false;\n this._particlesRenderTime = new PerfCounter();\n this._captureSpritesRenderTime = false;\n this._spritesRenderTime = new PerfCounter();\n this._capturePhysicsTime = false;\n this._physicsTime = new PerfCounter();\n this._captureAnimationsTime = false;\n this._animationsTime = new PerfCounter();\n this._captureCameraRenderTime = false;\n this._cameraRenderTime = new PerfCounter();\n // Observers\n this._onBeforeActiveMeshesEvaluationObserver = null;\n this._onAfterActiveMeshesEvaluationObserver = null;\n this._onBeforeRenderTargetsRenderObserver = null;\n this._onAfterRenderTargetsRenderObserver = null;\n this._onAfterRenderObserver = null;\n this._onBeforeDrawPhaseObserver = null;\n this._onAfterDrawPhaseObserver = null;\n this._onBeforeAnimationsObserver = null;\n this._onBeforeParticlesRenderingObserver = null;\n this._onAfterParticlesRenderingObserver = null;\n this._onBeforeSpritesRenderingObserver = null;\n this._onAfterSpritesRenderingObserver = null;\n this._onBeforePhysicsObserver = null;\n this._onAfterPhysicsObserver = null;\n this._onAfterAnimationsObserver = null;\n this._onBeforeCameraRenderObserver = null;\n this._onAfterCameraRenderObserver = null;\n // Before render\n this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(() => {\n if (this._captureActiveMeshesEvaluationTime) {\n this._activeMeshesEvaluationTime.fetchNewFrame();\n }\n if (this._captureRenderTargetsRenderTime) {\n this._renderTargetsRenderTime.fetchNewFrame();\n }\n if (this._captureFrameTime) {\n Tools.StartPerformanceCounter(\"Scene rendering\");\n this._frameTime.beginMonitoring();\n }\n if (this._captureInterFrameTime) {\n this._interFrameTime.endMonitoring();\n }\n if (this._captureParticlesRenderTime) {\n this._particlesRenderTime.fetchNewFrame();\n }\n if (this._captureSpritesRenderTime) {\n this._spritesRenderTime.fetchNewFrame();\n }\n if (this._captureAnimationsTime) {\n this._animationsTime.beginMonitoring();\n }\n if (this._captureRenderTime) {\n this._renderTime.fetchNewFrame();\n }\n if (this._captureCameraRenderTime) {\n this._cameraRenderTime.fetchNewFrame();\n }\n this.scene.getEngine()._drawCalls.fetchNewFrame();\n });\n // After render\n this._onAfterRenderObserver = scene.onAfterRenderObservable.add(() => {\n if (this._captureFrameTime) {\n Tools.EndPerformanceCounter(\"Scene rendering\");\n this._frameTime.endMonitoring();\n }\n if (this._captureRenderTime) {\n this._renderTime.endMonitoring(false);\n }\n if (this._captureInterFrameTime) {\n this._interFrameTime.beginMonitoring();\n }\n if (this._captureActiveMeshesEvaluationTime) {\n this._activeMeshesEvaluationTime.endFrame();\n }\n if (this._captureRenderTargetsRenderTime) {\n this._renderTargetsRenderTime.endFrame();\n }\n if (this._captureParticlesRenderTime) {\n this._particlesRenderTime.endFrame();\n }\n if (this._captureSpritesRenderTime) {\n this._spritesRenderTime.endFrame();\n }\n if (this._captureRenderTime) {\n this._renderTime.endFrame();\n }\n if (this._captureCameraRenderTime) {\n this._cameraRenderTime.endFrame();\n }\n });\n }\n /**\n * Dispose and release associated resources.\n */\n dispose() {\n this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);\n this._onAfterRenderObserver = null;\n this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);\n this._onBeforeActiveMeshesEvaluationObserver = null;\n this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);\n this._onAfterActiveMeshesEvaluationObserver = null;\n this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);\n this._onBeforeRenderTargetsRenderObserver = null;\n this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);\n this._onAfterRenderTargetsRenderObserver = null;\n this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);\n this._onBeforeAnimationsObserver = null;\n this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);\n this._onBeforeParticlesRenderingObserver = null;\n this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);\n this._onAfterParticlesRenderingObserver = null;\n if (this._onBeforeSpritesRenderingObserver) {\n this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);\n this._onBeforeSpritesRenderingObserver = null;\n }\n if (this._onAfterSpritesRenderingObserver) {\n this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);\n this._onAfterSpritesRenderingObserver = null;\n }\n this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);\n this._onBeforeDrawPhaseObserver = null;\n this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);\n this._onAfterDrawPhaseObserver = null;\n if (this._onBeforePhysicsObserver) {\n this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);\n this._onBeforePhysicsObserver = null;\n }\n if (this._onAfterPhysicsObserver) {\n this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);\n this._onAfterPhysicsObserver = null;\n }\n this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);\n this._onAfterAnimationsObserver = null;\n this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);\n this._onBeforeCameraRenderObserver = null;\n this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);\n this._onAfterCameraRenderObserver = null;\n this.scene = null;\n }\n}\n//# sourceMappingURL=sceneInstrumentation.js.map","export * from \"./engineInstrumentation.js\";\nexport * from \"./sceneInstrumentation.js\";\nexport * from \"./timeToken.js\";\n//# sourceMappingURL=index.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/helperFunctions.js\";\nimport \"./ShadersInclude/clipPlaneFragmentDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneFragment.js\";\nconst name = \"glowMapGenerationPixelShader\";\nconst shader = `#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)\n#include\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;\runiform sampler2D diffuseSampler;\r#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;\runiform sampler2D opacitySampler;\runiform float opacityIntensity;\r#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\runiform sampler2D emissiveSampler;\r#endif\n#ifdef VERTEXALPHA\nvarying vec4 vColor;\r#endif\nuniform vec4 glowColor;\runiform float glowIntensity;\r#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\r{\r#include\nvec4 finalColor=glowColor;\r#ifdef DIFFUSE\nvec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse);\r#ifdef DIFFUSE_ISLINEAR\nalbedoTexture=toGammaSpace(albedoTexture);\r#endif\n#ifdef GLOW\nfinalColor.a*=albedoTexture.a;\r#endif\n#ifdef HIGHLIGHT\nfinalColor.a=albedoTexture.a;\r#endif\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vUVOpacity);\r#ifdef OPACITYRGB\nfinalColor.a*=getLuminance(opacityMap.rgb);\r#else\nfinalColor.a*=opacityMap.a;\r#endif\nfinalColor.a*=opacityIntensity;\r#endif\n#ifdef VERTEXALPHA\nfinalColor.a*=vColor.a;\r#endif\n#ifdef ALPHATEST\nif (finalColor.a\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform mat4 viewProjection;\rvarying vec4 vPosition;\r#ifdef UV1\nattribute vec2 uv;\r#endif\n#ifdef UV2\nattribute vec2 uv2;\r#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;\runiform mat4 diffuseMatrix;\r#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;\runiform mat4 opacityMatrix;\r#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\runiform mat4 emissiveMatrix;\r#endif\n#ifdef VERTEXALPHA\nattribute vec4 color;\rvarying vec4 vColor;\r#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\r{\rvec3 positionUpdated=position;\r#ifdef UV1\nvec2 uvUpdated=uv;\r#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\r#ifdef CUBEMAP\nvPosition=worldPos;\rgl_Position=viewProjection*finalWorld*vec4(position,1.0);\r#else\nvPosition=viewProjection*worldPos;\rgl_Position=vPosition;\r#endif\n#ifdef DIFFUSE\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\r#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\r#endif\n#endif\n#ifdef OPACITY\n#ifdef OPACITYUV1\nvUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0));\r#endif\n#ifdef OPACITYUV2\nvUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\r#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0));\r#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\r#endif\n#endif\n#ifdef VERTEXALPHA\nvColor=color;\r#endif\n#include\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const glowMapGenerationVertexShader = { name, shader };\n//# sourceMappingURL=glowMapGeneration.vertex.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize, serializeAsColor4, serializeAsCameraReference } from \"../Misc/decorators.js\";\nimport { Tools } from \"../Misc/tools.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { RenderTargetTexture } from \"../Materials/Textures/renderTargetTexture.js\";\nimport { Material } from \"../Materials/material.js\";\nimport { MaterialHelper } from \"../Materials/materialHelper.js\";\n\nimport \"../Shaders/glowMapGeneration.fragment.js\";\nimport \"../Shaders/glowMapGeneration.vertex.js\";\nimport { _WarnImport } from \"../Misc/devTools.js\";\nimport { EffectFallbacks } from \"../Materials/effectFallbacks.js\";\nimport { DrawWrapper } from \"../Materials/drawWrapper.js\";\nimport { addClipPlaneUniforms, bindClipPlane, prepareStringDefinesForClipPlanes } from \"../Materials/clipPlaneMaterialHelper.js\";\n/**\n * The effect layer Helps adding post process effect blended with the main pass.\n *\n * This can be for instance use to generate glow or highlight effects on the scene.\n *\n * The effect layer class can not be used directly and is intented to inherited from to be\n * customized per effects.\n */\nexport class EffectLayer {\n /**\n * Gets the camera attached to the layer.\n */\n get camera() {\n return this._effectLayerOptions.camera;\n }\n /**\n * Gets the rendering group id the layer should render in.\n */\n get renderingGroupId() {\n return this._effectLayerOptions.renderingGroupId;\n }\n set renderingGroupId(renderingGroupId) {\n this._effectLayerOptions.renderingGroupId = renderingGroupId;\n }\n /**\n * Gets the main texture where the effect is rendered\n */\n get mainTexture() {\n return this._mainTexture;\n }\n /**\n * Sets a specific material to be used to render a mesh/a list of meshes in the layer\n * @param mesh mesh or array of meshes\n * @param material material to use by the layer when rendering the mesh(es). If undefined is passed, the specific material created by the layer will be used.\n */\n setMaterialForRendering(mesh, material) {\n this._mainTexture.setMaterialForRendering(mesh, material);\n if (Array.isArray(mesh)) {\n for (let i = 0; i < mesh.length; ++i) {\n const currentMesh = mesh[i];\n if (!material) {\n delete this._materialForRendering[currentMesh.uniqueId];\n }\n else {\n this._materialForRendering[currentMesh.uniqueId] = [currentMesh, material];\n }\n }\n }\n else {\n if (!material) {\n delete this._materialForRendering[mesh.uniqueId];\n }\n else {\n this._materialForRendering[mesh.uniqueId] = [mesh, material];\n }\n }\n }\n /**\n * Gets the intensity of the effect for a specific mesh.\n * @param mesh The mesh to get the effect intensity for\n * @returns The intensity of the effect for the mesh\n */\n getEffectIntensity(mesh) {\n var _a;\n return (_a = this._effectIntensity[mesh.uniqueId]) !== null && _a !== void 0 ? _a : 1;\n }\n /**\n * Sets the intensity of the effect for a specific mesh.\n * @param mesh The mesh to set the effect intensity for\n * @param intensity The intensity of the effect for the mesh\n */\n setEffectIntensity(mesh, intensity) {\n this._effectIntensity[mesh.uniqueId] = intensity;\n }\n /**\n * Instantiates a new effect Layer and references it in the scene.\n * @param name The name of the layer\n * @param scene The scene to use the layer in\n */\n constructor(\n /** The Friendly of the effect in the scene */\n name, scene) {\n this._vertexBuffers = {};\n this._maxSize = 0;\n this._mainTextureDesiredSize = { width: 0, height: 0 };\n this._shouldRender = true;\n this._postProcesses = [];\n this._textures = [];\n this._emissiveTextureAndColor = { texture: null, color: new Color4() };\n this._effectIntensity = {};\n /**\n * The clear color of the texture used to generate the glow map.\n */\n this.neutralColor = new Color4();\n /**\n * Specifies whether the highlight layer is enabled or not.\n */\n this.isEnabled = true;\n /**\n * Specifies if the bounding boxes should be rendered normally or if they should undergo the effect of the layer\n */\n this.disableBoundingBoxesFromEffectLayer = false;\n /**\n * An event triggered when the effect layer has been disposed.\n */\n this.onDisposeObservable = new Observable();\n /**\n * An event triggered when the effect layer is about rendering the main texture with the glowy parts.\n */\n this.onBeforeRenderMainTextureObservable = new Observable();\n /**\n * An event triggered when the generated texture is being merged in the scene.\n */\n this.onBeforeComposeObservable = new Observable();\n /**\n * An event triggered when the mesh is rendered into the effect render target.\n */\n this.onBeforeRenderMeshToEffect = new Observable();\n /**\n * An event triggered after the mesh has been rendered into the effect render target.\n */\n this.onAfterRenderMeshToEffect = new Observable();\n /**\n * An event triggered when the generated texture has been merged in the scene.\n */\n this.onAfterComposeObservable = new Observable();\n /**\n * An event triggered when the effect layer changes its size.\n */\n this.onSizeChangedObservable = new Observable();\n this._materialForRendering = {};\n this.name = name;\n this._scene = scene || EngineStore.LastCreatedScene;\n EffectLayer._SceneComponentInitialization(this._scene);\n this._engine = this._scene.getEngine();\n this._maxSize = this._engine.getCaps().maxTextureSize;\n this._scene.effectLayers.push(this);\n this._mergeDrawWrapper = [];\n // Generate Buffers\n this._generateIndexBuffer();\n this._generateVertexBuffer();\n }\n /**\n * Number of times _internalRender will be called. Some effect layers need to render the mesh several times, so they should override this method with the number of times the mesh should be rendered\n * @returns Number of times a mesh must be rendered in the layer\n */\n _numInternalDraws() {\n return 1;\n }\n /**\n * Initializes the effect layer with the required options.\n * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)\n */\n _init(options) {\n // Adapt options\n this._effectLayerOptions = Object.assign({ mainTextureRatio: 0.5, alphaBlendingMode: 2, camera: null, renderingGroupId: -1, mainTextureType: 0 }, options);\n this._setMainTextureSize();\n this._createMainTexture();\n this._createTextureAndPostProcesses();\n }\n /**\n * Generates the index buffer of the full screen quad blending to the main canvas.\n */\n _generateIndexBuffer() {\n // Indices\n const indices = [];\n indices.push(0);\n indices.push(1);\n indices.push(2);\n indices.push(0);\n indices.push(2);\n indices.push(3);\n this._indexBuffer = this._engine.createIndexBuffer(indices);\n }\n /**\n * Generates the vertex buffer of the full screen quad blending to the main canvas.\n */\n _generateVertexBuffer() {\n // VBO\n const vertices = [];\n vertices.push(1, 1);\n vertices.push(-1, 1);\n vertices.push(-1, -1);\n vertices.push(1, -1);\n const vertexBuffer = new VertexBuffer(this._engine, vertices, VertexBuffer.PositionKind, false, false, 2);\n this._vertexBuffers[VertexBuffer.PositionKind] = vertexBuffer;\n }\n /**\n * Sets the main texture desired size which is the closest power of two\n * of the engine canvas size.\n */\n _setMainTextureSize() {\n if (this._effectLayerOptions.mainTextureFixedSize) {\n this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;\n this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;\n }\n else {\n this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;\n this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;\n this._mainTextureDesiredSize.width = this._engine.needPOTTextures\n ? Engine.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize)\n : this._mainTextureDesiredSize.width;\n this._mainTextureDesiredSize.height = this._engine.needPOTTextures\n ? Engine.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize)\n : this._mainTextureDesiredSize.height;\n }\n this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);\n this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);\n }\n /**\n * Creates the main texture for the effect layer.\n */\n _createMainTexture() {\n this._mainTexture = new RenderTargetTexture(\"EffectLayerMainRTT\", {\n width: this._mainTextureDesiredSize.width,\n height: this._mainTextureDesiredSize.height,\n }, this._scene, false, true, this._effectLayerOptions.mainTextureType);\n this._mainTexture.activeCamera = this._effectLayerOptions.camera;\n this._mainTexture.wrapU = Texture.CLAMP_ADDRESSMODE;\n this._mainTexture.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._mainTexture.anisotropicFilteringLevel = 1;\n this._mainTexture.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);\n this._mainTexture.renderParticles = false;\n this._mainTexture.renderList = null;\n this._mainTexture.ignoreCameraViewport = true;\n for (const id in this._materialForRendering) {\n const [mesh, material] = this._materialForRendering[id];\n this._mainTexture.setMaterialForRendering(mesh, material);\n }\n this._mainTexture.customIsReadyFunction = (mesh, refreshRate, preWarm) => {\n if ((preWarm || refreshRate === 0) && mesh.subMeshes) {\n for (let i = 0; i < mesh.subMeshes.length; ++i) {\n const subMesh = mesh.subMeshes[i];\n const material = subMesh.getMaterial();\n const renderingMesh = subMesh.getRenderingMesh();\n if (!material) {\n continue;\n }\n const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());\n const hardwareInstancedRendering = batch.hardwareInstancedRendering[subMesh._id] || renderingMesh.hasThinInstances;\n this._setEmissiveTextureAndColor(renderingMesh, subMesh, material);\n if (!this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {\n return false;\n }\n }\n }\n return true;\n };\n // Custom render function\n this._mainTexture.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => {\n this.onBeforeRenderMainTextureObservable.notifyObservers(this);\n let index;\n const engine = this._scene.getEngine();\n if (depthOnlySubMeshes.length) {\n engine.setColorWrite(false);\n for (index = 0; index < depthOnlySubMeshes.length; index++) {\n this._renderSubMesh(depthOnlySubMeshes.data[index]);\n }\n engine.setColorWrite(true);\n }\n for (index = 0; index < opaqueSubMeshes.length; index++) {\n this._renderSubMesh(opaqueSubMeshes.data[index]);\n }\n for (index = 0; index < alphaTestSubMeshes.length; index++) {\n this._renderSubMesh(alphaTestSubMeshes.data[index]);\n }\n const previousAlphaMode = engine.getAlphaMode();\n for (index = 0; index < transparentSubMeshes.length; index++) {\n this._renderSubMesh(transparentSubMeshes.data[index], true);\n }\n engine.setAlphaMode(previousAlphaMode);\n };\n this._mainTexture.onClearObservable.add((engine) => {\n engine.clear(this.neutralColor, true, true, true);\n });\n // Prevent package size in es6 (getBoundingBoxRenderer might not be present)\n if (this._scene.getBoundingBoxRenderer) {\n const boundingBoxRendererEnabled = this._scene.getBoundingBoxRenderer().enabled;\n this._mainTexture.onBeforeBindObservable.add(() => {\n this._scene.getBoundingBoxRenderer().enabled = !this.disableBoundingBoxesFromEffectLayer && boundingBoxRendererEnabled;\n });\n this._mainTexture.onAfterUnbindObservable.add(() => {\n this._scene.getBoundingBoxRenderer().enabled = boundingBoxRendererEnabled;\n });\n }\n }\n /**\n * Adds specific effects defines.\n * @param defines The defines to add specifics to.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _addCustomEffectDefines(defines) {\n // Nothing to add by default.\n }\n /**\n * Checks for the readiness of the element composing the layer.\n * @param subMesh the mesh to check for\n * @param useInstances specify whether or not to use instances to render the mesh\n * @param emissiveTexture the associated emissive texture used to generate the glow\n * @returns true if ready otherwise, false\n */\n _isReady(subMesh, useInstances, emissiveTexture) {\n var _a;\n const engine = this._scene.getEngine();\n const mesh = subMesh.getMesh();\n const renderingMaterial = (_a = mesh._internalAbstractMeshDataInfo._materialForRenderPass) === null || _a === void 0 ? void 0 : _a[engine.currentRenderPassId];\n if (renderingMaterial) {\n return renderingMaterial.isReadyForSubMesh(mesh, subMesh, useInstances);\n }\n const material = subMesh.getMaterial();\n if (!material) {\n return false;\n }\n if (this._useMeshMaterial(subMesh.getRenderingMesh())) {\n return material.isReadyForSubMesh(subMesh.getMesh(), subMesh, useInstances);\n }\n const defines = [];\n const attribs = [VertexBuffer.PositionKind];\n let uv1 = false;\n let uv2 = false;\n // Diffuse\n if (material) {\n const needAlphaTest = material.needAlphaTesting();\n const diffuseTexture = material.getAlphaTestTexture();\n const needAlphaBlendFromDiffuse = diffuseTexture && diffuseTexture.hasAlpha && (material.useAlphaFromDiffuseTexture || material._useAlphaFromAlbedoTexture);\n if (diffuseTexture && (needAlphaTest || needAlphaBlendFromDiffuse)) {\n defines.push(\"#define DIFFUSE\");\n if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) && diffuseTexture.coordinatesIndex === 1) {\n defines.push(\"#define DIFFUSEUV2\");\n uv2 = true;\n }\n else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {\n defines.push(\"#define DIFFUSEUV1\");\n uv1 = true;\n }\n if (needAlphaTest) {\n defines.push(\"#define ALPHATEST\");\n defines.push(\"#define ALPHATESTVALUE 0.4\");\n }\n if (!diffuseTexture.gammaSpace) {\n defines.push(\"#define DIFFUSE_ISLINEAR\");\n }\n }\n const opacityTexture = material.opacityTexture;\n if (opacityTexture) {\n defines.push(\"#define OPACITY\");\n if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) && opacityTexture.coordinatesIndex === 1) {\n defines.push(\"#define OPACITYUV2\");\n uv2 = true;\n }\n else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {\n defines.push(\"#define OPACITYUV1\");\n uv1 = true;\n }\n }\n }\n // Emissive\n if (emissiveTexture) {\n defines.push(\"#define EMISSIVE\");\n if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) && emissiveTexture.coordinatesIndex === 1) {\n defines.push(\"#define EMISSIVEUV2\");\n uv2 = true;\n }\n else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {\n defines.push(\"#define EMISSIVEUV1\");\n uv1 = true;\n }\n if (!emissiveTexture.gammaSpace) {\n defines.push(\"#define EMISSIVE_ISLINEAR\");\n }\n }\n // Vertex\n if (mesh.useVertexColors && mesh.isVerticesDataPresent(VertexBuffer.ColorKind) && mesh.hasVertexAlpha && material.transparencyMode !== Material.MATERIAL_OPAQUE) {\n attribs.push(VertexBuffer.ColorKind);\n defines.push(\"#define VERTEXALPHA\");\n }\n if (uv1) {\n attribs.push(VertexBuffer.UVKind);\n defines.push(\"#define UV1\");\n }\n if (uv2) {\n attribs.push(VertexBuffer.UV2Kind);\n defines.push(\"#define UV2\");\n }\n // Bones\n const fallbacks = new EffectFallbacks();\n if (mesh.useBones && mesh.computeBonesUsingShaders) {\n attribs.push(VertexBuffer.MatricesIndicesKind);\n attribs.push(VertexBuffer.MatricesWeightsKind);\n if (mesh.numBoneInfluencers > 4) {\n attribs.push(VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(VertexBuffer.MatricesWeightsExtraKind);\n }\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n const skeleton = mesh.skeleton;\n if (skeleton && skeleton.isUsingTextureForMatrices) {\n defines.push(\"#define BONETEXTURE\");\n }\n else {\n defines.push(\"#define BonesPerMesh \" + (skeleton ? skeleton.bones.length + 1 : 0));\n }\n if (mesh.numBoneInfluencers > 0) {\n fallbacks.addCPUSkinningFallback(0, mesh);\n }\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Morph targets\n const manager = mesh.morphTargetManager;\n let morphInfluencers = 0;\n if (manager) {\n if (manager.numInfluencers > 0) {\n defines.push(\"#define MORPHTARGETS\");\n morphInfluencers = manager.numInfluencers;\n defines.push(\"#define NUM_MORPH_INFLUENCERS \" + morphInfluencers);\n if (manager.isUsingTextureForTargets) {\n defines.push(\"#define MORPHTARGETS_TEXTURE\");\n }\n MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, morphInfluencers);\n }\n }\n // Instances\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n MaterialHelper.PushAttributesForInstances(attribs);\n if (subMesh.getRenderingMesh().hasThinInstances) {\n defines.push(\"#define THIN_INSTANCES\");\n }\n }\n // ClipPlanes\n prepareStringDefinesForClipPlanes(material, this._scene, defines);\n this._addCustomEffectDefines(defines);\n // Get correct effect\n const drawWrapper = subMesh._getDrawWrapper(undefined, true);\n const cachedDefines = drawWrapper.defines;\n const join = defines.join(\"\\n\");\n if (cachedDefines !== join) {\n const uniforms = [\n \"world\",\n \"mBones\",\n \"viewProjection\",\n \"glowColor\",\n \"morphTargetInfluences\",\n \"boneTextureWidth\",\n \"diffuseMatrix\",\n \"emissiveMatrix\",\n \"opacityMatrix\",\n \"opacityIntensity\",\n \"morphTargetTextureInfo\",\n \"morphTargetTextureIndices\",\n \"glowIntensity\",\n ];\n addClipPlaneUniforms(uniforms);\n drawWrapper.setEffect(this._engine.createEffect(\"glowMapGeneration\", attribs, uniforms, [\"diffuseSampler\", \"emissiveSampler\", \"opacitySampler\", \"boneSampler\", \"morphTargets\"], join, fallbacks, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers }), join);\n }\n return drawWrapper.effect.isReady();\n }\n /**\n * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.\n */\n render() {\n for (let i = 0; i < this._postProcesses.length; i++) {\n if (!this._postProcesses[i].isReady()) {\n return;\n }\n }\n const engine = this._scene.getEngine();\n const numDraws = this._numInternalDraws();\n // Check\n let isReady = true;\n for (let i = 0; i < numDraws; ++i) {\n let currentEffect = this._mergeDrawWrapper[i];\n if (!currentEffect) {\n currentEffect = this._mergeDrawWrapper[i] = new DrawWrapper(this._engine);\n currentEffect.setEffect(this._createMergeEffect());\n }\n isReady = isReady && currentEffect.effect.isReady();\n }\n if (!isReady) {\n return;\n }\n this.onBeforeComposeObservable.notifyObservers(this);\n const previousAlphaMode = engine.getAlphaMode();\n for (let i = 0; i < numDraws; ++i) {\n const currentEffect = this._mergeDrawWrapper[i];\n // Render\n engine.enableEffect(currentEffect);\n engine.setState(false);\n // VBOs\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect.effect);\n // Go Blend.\n engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);\n // Blends the map on the main canvas.\n this._internalRender(currentEffect.effect, i);\n }\n // Restore Alpha\n engine.setAlphaMode(previousAlphaMode);\n this.onAfterComposeObservable.notifyObservers(this);\n // Handle size changes.\n const size = this._mainTexture.getSize();\n this._setMainTextureSize();\n if ((size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) &&\n this._mainTextureDesiredSize.width !== 0 &&\n this._mainTextureDesiredSize.height !== 0) {\n // Recreate RTT and post processes on size change.\n this.onSizeChangedObservable.notifyObservers(this);\n this._disposeTextureAndPostProcesses();\n this._createMainTexture();\n this._createTextureAndPostProcesses();\n }\n }\n /**\n * Determine if a given mesh will be used in the current effect.\n * @param mesh mesh to test\n * @returns true if the mesh will be used\n */\n hasMesh(mesh) {\n if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {\n return true;\n }\n return false;\n }\n /**\n * Returns true if the layer contains information to display, otherwise false.\n * @returns true if the glow layer should be rendered\n */\n shouldRender() {\n return this.isEnabled && this._shouldRender;\n }\n /**\n * Returns true if the mesh should render, otherwise false.\n * @param mesh The mesh to render\n * @returns true if it should render otherwise false\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _shouldRenderMesh(mesh) {\n return true;\n }\n /**\n * Returns true if the mesh can be rendered, otherwise false.\n * @param mesh The mesh to render\n * @param material The material used on the mesh\n * @returns true if it can be rendered otherwise false\n */\n _canRenderMesh(mesh, material) {\n return !material.needAlphaBlendingForMesh(mesh);\n }\n /**\n * Returns true if the mesh should render, otherwise false.\n * @returns true if it should render otherwise false\n */\n _shouldRenderEmissiveTextureForMesh() {\n return true;\n }\n /**\n * Renders the submesh passed in parameter to the generation map.\n * @param subMesh\n * @param enableAlphaMode\n */\n _renderSubMesh(subMesh, enableAlphaMode = false) {\n var _a, _b;\n if (!this.shouldRender()) {\n return;\n }\n const material = subMesh.getMaterial();\n const ownerMesh = subMesh.getMesh();\n const replacementMesh = subMesh.getReplacementMesh();\n const renderingMesh = subMesh.getRenderingMesh();\n const effectiveMesh = subMesh.getEffectiveMesh();\n const scene = this._scene;\n const engine = scene.getEngine();\n effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;\n if (!material) {\n return;\n }\n // Do not block in blend mode.\n if (!this._canRenderMesh(renderingMesh, material)) {\n return;\n }\n // Culling\n let sideOrientation = (_a = renderingMesh.overrideMaterialSideOrientation) !== null && _a !== void 0 ? _a : material.sideOrientation;\n const mainDeterminant = effectiveMesh._getWorldMatrixDeterminant();\n if (mainDeterminant < 0) {\n sideOrientation = sideOrientation === Material.ClockWiseSideOrientation ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation;\n }\n const reverse = sideOrientation === Material.ClockWiseSideOrientation;\n engine.setState(material.backFaceCulling, material.zOffset, undefined, reverse, material.cullBackFaces, undefined, material.zOffsetUnits);\n // Managing instances\n const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!replacementMesh);\n if (batch.mustReturn) {\n return;\n }\n // Early Exit per mesh\n if (!this._shouldRenderMesh(renderingMesh)) {\n return;\n }\n const hardwareInstancedRendering = batch.hardwareInstancedRendering[subMesh._id] || renderingMesh.hasThinInstances;\n this._setEmissiveTextureAndColor(renderingMesh, subMesh, material);\n this.onBeforeRenderMeshToEffect.notifyObservers(ownerMesh);\n if (this._useMeshMaterial(renderingMesh)) {\n renderingMesh.render(subMesh, enableAlphaMode, replacementMesh || undefined);\n }\n else if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {\n const renderingMaterial = (_b = effectiveMesh._internalAbstractMeshDataInfo._materialForRenderPass) === null || _b === void 0 ? void 0 : _b[engine.currentRenderPassId];\n let drawWrapper = subMesh._getDrawWrapper();\n if (!drawWrapper && renderingMaterial) {\n drawWrapper = renderingMaterial._getDrawWrapper();\n }\n if (!drawWrapper) {\n return;\n }\n const effect = drawWrapper.effect;\n engine.enableEffect(drawWrapper);\n if (!hardwareInstancedRendering) {\n renderingMesh._bind(subMesh, effect, material.fillMode);\n }\n if (!renderingMaterial) {\n effect.setMatrix(\"viewProjection\", scene.getTransformMatrix());\n effect.setMatrix(\"world\", effectiveMesh.getWorldMatrix());\n effect.setFloat4(\"glowColor\", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);\n }\n else {\n renderingMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), effectiveMesh, subMesh);\n }\n if (!renderingMaterial) {\n const needAlphaTest = material.needAlphaTesting();\n const diffuseTexture = material.getAlphaTestTexture();\n const needAlphaBlendFromDiffuse = diffuseTexture && diffuseTexture.hasAlpha && (material.useAlphaFromDiffuseTexture || material._useAlphaFromAlbedoTexture);\n if (diffuseTexture && (needAlphaTest || needAlphaBlendFromDiffuse)) {\n effect.setTexture(\"diffuseSampler\", diffuseTexture);\n const textureMatrix = diffuseTexture.getTextureMatrix();\n if (textureMatrix) {\n effect.setMatrix(\"diffuseMatrix\", textureMatrix);\n }\n }\n const opacityTexture = material.opacityTexture;\n if (opacityTexture) {\n effect.setTexture(\"opacitySampler\", opacityTexture);\n effect.setFloat(\"opacityIntensity\", opacityTexture.level);\n const textureMatrix = opacityTexture.getTextureMatrix();\n if (textureMatrix) {\n effect.setMatrix(\"opacityMatrix\", textureMatrix);\n }\n }\n // Glow emissive only\n if (this._emissiveTextureAndColor.texture) {\n effect.setTexture(\"emissiveSampler\", this._emissiveTextureAndColor.texture);\n effect.setMatrix(\"emissiveMatrix\", this._emissiveTextureAndColor.texture.getTextureMatrix());\n }\n // Bones\n if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) {\n const skeleton = renderingMesh.skeleton;\n if (skeleton.isUsingTextureForMatrices) {\n const boneTexture = skeleton.getTransformMatrixTexture(renderingMesh);\n if (!boneTexture) {\n return;\n }\n effect.setTexture(\"boneSampler\", boneTexture);\n effect.setFloat(\"boneTextureWidth\", 4.0 * (skeleton.bones.length + 1));\n }\n else {\n effect.setMatrices(\"mBones\", skeleton.getTransformMatrices(renderingMesh));\n }\n }\n // Morph targets\n MaterialHelper.BindMorphTargetParameters(renderingMesh, effect);\n if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) {\n renderingMesh.morphTargetManager._bind(effect);\n }\n // Alpha mode\n if (enableAlphaMode) {\n engine.setAlphaMode(material.alphaMode);\n }\n // Intensity of effect\n effect.setFloat(\"glowIntensity\", this.getEffectIntensity(renderingMesh));\n // Clip planes\n bindClipPlane(effect, material, scene);\n }\n // Draw\n renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, world) => effect.setMatrix(\"world\", world));\n }\n else {\n // Need to reset refresh rate of the main map\n this._mainTexture.resetRefreshCounter();\n }\n this.onAfterRenderMeshToEffect.notifyObservers(ownerMesh);\n }\n /**\n * Defines whether the current material of the mesh should be use to render the effect.\n * @param mesh defines the current mesh to render\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _useMeshMaterial(mesh) {\n return false;\n }\n /**\n * Rebuild the required buffers.\n * @internal Internal use only.\n */\n _rebuild() {\n const vb = this._vertexBuffers[VertexBuffer.PositionKind];\n if (vb) {\n vb._rebuild();\n }\n this._generateIndexBuffer();\n }\n /**\n * Dispose only the render target textures and post process.\n */\n _disposeTextureAndPostProcesses() {\n this._mainTexture.dispose();\n for (let i = 0; i < this._postProcesses.length; i++) {\n if (this._postProcesses[i]) {\n this._postProcesses[i].dispose();\n }\n }\n this._postProcesses = [];\n for (let i = 0; i < this._textures.length; i++) {\n if (this._textures[i]) {\n this._textures[i].dispose();\n }\n }\n this._textures = [];\n }\n /**\n * Dispose the highlight layer and free resources.\n */\n dispose() {\n const vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];\n if (vertexBuffer) {\n vertexBuffer.dispose();\n this._vertexBuffers[VertexBuffer.PositionKind] = null;\n }\n if (this._indexBuffer) {\n this._scene.getEngine()._releaseBuffer(this._indexBuffer);\n this._indexBuffer = null;\n }\n for (const drawWrapper of this._mergeDrawWrapper) {\n drawWrapper.dispose();\n }\n this._mergeDrawWrapper = [];\n // Clean textures and post processes\n this._disposeTextureAndPostProcesses();\n // Remove from scene\n const index = this._scene.effectLayers.indexOf(this, 0);\n if (index > -1) {\n this._scene.effectLayers.splice(index, 1);\n }\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n this.onBeforeRenderMainTextureObservable.clear();\n this.onBeforeComposeObservable.clear();\n this.onBeforeRenderMeshToEffect.clear();\n this.onAfterRenderMeshToEffect.clear();\n this.onAfterComposeObservable.clear();\n this.onSizeChangedObservable.clear();\n }\n /**\n * Gets the class name of the effect layer\n * @returns the string with the class name of the effect layer\n */\n getClassName() {\n return \"EffectLayer\";\n }\n /**\n * Creates an effect layer from parsed effect layer data\n * @param parsedEffectLayer defines effect layer data\n * @param scene defines the current scene\n * @param rootUrl defines the root URL containing the effect layer information\n * @returns a parsed effect Layer\n */\n static Parse(parsedEffectLayer, scene, rootUrl) {\n const effectLayerType = Tools.Instantiate(parsedEffectLayer.customType);\n return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);\n }\n}\n/**\n * @internal\n */\nEffectLayer._SceneComponentInitialization = (_) => {\n throw _WarnImport(\"EffectLayerSceneComponent\");\n};\n__decorate([\n serialize()\n], EffectLayer.prototype, \"name\", void 0);\n__decorate([\n serializeAsColor4()\n], EffectLayer.prototype, \"neutralColor\", void 0);\n__decorate([\n serialize()\n], EffectLayer.prototype, \"isEnabled\", void 0);\n__decorate([\n serializeAsCameraReference()\n], EffectLayer.prototype, \"camera\", null);\n__decorate([\n serialize()\n], EffectLayer.prototype, \"renderingGroupId\", null);\n__decorate([\n serialize()\n], EffectLayer.prototype, \"disableBoundingBoxesFromEffectLayer\", void 0);\n//# sourceMappingURL=effectLayer.js.map","import { Camera } from \"../Cameras/camera.js\";\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { EffectLayer } from \"./effectLayer.js\";\nimport { AbstractScene } from \"../abstractScene.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n// Adds the parser to the scene parsers.\nAbstractScene.AddParser(SceneComponentConstants.NAME_EFFECTLAYER, (parsedData, scene, container, rootUrl) => {\n if (parsedData.effectLayers) {\n if (!container.effectLayers) {\n container.effectLayers = new Array();\n }\n for (let index = 0; index < parsedData.effectLayers.length; index++) {\n const effectLayer = EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);\n container.effectLayers.push(effectLayer);\n }\n }\n});\nAbstractScene.prototype.removeEffectLayer = function (toRemove) {\n const index = this.effectLayers.indexOf(toRemove);\n if (index !== -1) {\n this.effectLayers.splice(index, 1);\n }\n return index;\n};\nAbstractScene.prototype.addEffectLayer = function (newEffectLayer) {\n this.effectLayers.push(newEffectLayer);\n};\n/**\n * Defines the layer scene component responsible to manage any effect layers\n * in a given scene.\n */\nexport class EffectLayerSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpful to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_EFFECTLAYER;\n this._renderEffects = false;\n this._needStencil = false;\n this._previousStencilState = false;\n this.scene = scene || EngineStore.LastCreatedScene;\n if (!this.scene) {\n return;\n }\n this._engine = this.scene.getEngine();\n this.scene.effectLayers = new Array();\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene._isReadyForMeshStage.registerStep(SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);\n this.scene._cameraDrawRenderTargetStage.registerStep(SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);\n this.scene._beforeCameraDrawStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);\n this.scene._afterRenderingGroupDrawStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);\n this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);\n this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n const layers = this.scene.effectLayers;\n for (const effectLayer of layers) {\n effectLayer._rebuild();\n }\n }\n /**\n * Serializes the component data to the specified json object\n * @param serializationObject The object to serialize to\n */\n serialize(serializationObject) {\n // Effect layers\n serializationObject.effectLayers = [];\n const layers = this.scene.effectLayers;\n for (const effectLayer of layers) {\n if (effectLayer.serialize) {\n serializationObject.effectLayers.push(effectLayer.serialize());\n }\n }\n }\n /**\n * Adds all the elements from the container to the scene\n * @param container the container holding the elements\n */\n addFromContainer(container) {\n if (!container.effectLayers) {\n return;\n }\n container.effectLayers.forEach((o) => {\n this.scene.addEffectLayer(o);\n });\n }\n /**\n * Removes all the elements in the container from the scene\n * @param container contains the elements to remove\n * @param dispose if the removed element should be disposed (default: false)\n */\n removeFromContainer(container, dispose) {\n if (!container.effectLayers) {\n return;\n }\n container.effectLayers.forEach((o) => {\n this.scene.removeEffectLayer(o);\n if (dispose) {\n o.dispose();\n }\n });\n }\n /**\n * Disposes the component and the associated resources.\n */\n dispose() {\n const layers = this.scene.effectLayers;\n while (layers.length) {\n layers[0].dispose();\n }\n }\n _isReadyForMesh(mesh, hardwareInstancedRendering) {\n const currentRenderPassId = this._engine.currentRenderPassId;\n const layers = this.scene.effectLayers;\n for (const layer of layers) {\n if (!layer.hasMesh(mesh)) {\n continue;\n }\n const renderTarget = layer._mainTexture;\n this._engine.currentRenderPassId = renderTarget.renderPassId;\n for (const subMesh of mesh.subMeshes) {\n if (!layer.isReady(subMesh, hardwareInstancedRendering)) {\n this._engine.currentRenderPassId = currentRenderPassId;\n return false;\n }\n }\n }\n this._engine.currentRenderPassId = currentRenderPassId;\n return true;\n }\n _renderMainTexture(camera) {\n this._renderEffects = false;\n this._needStencil = false;\n let needRebind = false;\n const layers = this.scene.effectLayers;\n if (layers && layers.length > 0) {\n this._previousStencilState = this._engine.getStencilBuffer();\n for (const effectLayer of layers) {\n if (effectLayer.shouldRender() &&\n (!effectLayer.camera ||\n (effectLayer.camera.cameraRigMode === Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||\n (effectLayer.camera.cameraRigMode !== Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {\n this._renderEffects = true;\n this._needStencil = this._needStencil || effectLayer.needStencil();\n const renderTarget = effectLayer._mainTexture;\n if (renderTarget._shouldRender()) {\n this.scene.incrementRenderId();\n renderTarget.render(false, false);\n needRebind = true;\n }\n }\n }\n this.scene.incrementRenderId();\n }\n return needRebind;\n }\n _setStencil() {\n // Activate effect Layer stencil\n if (this._needStencil) {\n this._engine.setStencilBuffer(true);\n }\n }\n _setStencilBack() {\n // Restore effect Layer stencil\n if (this._needStencil) {\n this._engine.setStencilBuffer(this._previousStencilState);\n }\n }\n _draw(renderingGroupId) {\n if (this._renderEffects) {\n this._engine.setDepthBuffer(false);\n const layers = this.scene.effectLayers;\n for (let i = 0; i < layers.length; i++) {\n const effectLayer = layers[i];\n if (effectLayer.renderingGroupId === renderingGroupId) {\n if (effectLayer.shouldRender()) {\n effectLayer.render();\n }\n }\n }\n this._engine.setDepthBuffer(true);\n }\n }\n _drawCamera() {\n if (this._renderEffects) {\n this._draw(-1);\n }\n }\n _drawRenderingGroup(index) {\n if (!this.scene._isInIntermediateRendering() && this._renderEffects) {\n this._draw(index);\n }\n }\n}\nEffectLayer._SceneComponentInitialization = (scene) => {\n let component = scene._getComponent(SceneComponentConstants.NAME_EFFECTLAYER);\n if (!component) {\n component = new EffectLayerSceneComponent(scene);\n scene._addComponent(component);\n }\n};\n//# sourceMappingURL=effectLayerSceneComponent.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"glowMapMergePixelShader\";\nconst shader = `varying vec2 vUV;\runiform sampler2D textureSampler;\r#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\r#endif\nuniform float offset;\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\r#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\rbaseColor*=offset;\r#else\nbaseColor.a=abs(offset-baseColor.a);\r#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\rbaseColor.a=alpha;\rbaseColor.rgb=baseColor.rgb*alpha;\r#endif\n#endif\n#if LDR\nbaseColor=clamp(baseColor,0.,1.0);\r#endif\ngl_FragColor=baseColor;\r#define CUSTOM_FRAGMENT_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const glowMapMergePixelShader = { name, shader };\n//# sourceMappingURL=glowMapMerge.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"glowMapMergeVertexShader\";\nconst shader = `attribute vec2 position;\rvarying vec2 vUV;\rconst vec2 madd=vec2(0.5,0.5);\r#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=position*madd+madd;\rgl_Position=vec4(position,0.0,1.0);\r#define CUSTOM_VERTEX_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const glowMapMergeVertexShader = { name, shader };\n//# sourceMappingURL=glowMapMerge.vertex.js.map","import { __decorate } from \"../tslib.es6.js\";\n/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { serialize, SerializationHelper } from \"../Misc/decorators.js\";\nimport { Vector2 } from \"../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { RenderTargetTexture } from \"../Materials/Textures/renderTargetTexture.js\";\nimport { Material } from \"../Materials/material.js\";\nimport { BlurPostProcess } from \"../PostProcesses/blurPostProcess.js\";\nimport { EffectLayer } from \"./effectLayer.js\";\nimport { AbstractScene } from \"../abstractScene.js\";\n\nimport { RegisterClass } from \"../Misc/typeStore.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport \"../Shaders/glowMapMerge.fragment.js\";\nimport \"../Shaders/glowMapMerge.vertex.js\";\nimport \"../Layers/effectLayerSceneComponent.js\";\nAbstractScene.prototype.getGlowLayerByName = function (name) {\n var _a;\n for (let index = 0; index < ((_a = this.effectLayers) === null || _a === void 0 ? void 0 : _a.length); index++) {\n if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {\n return this.effectLayers[index];\n }\n }\n return null;\n};\n/**\n * The glow layer Helps adding a glow effect around the emissive parts of a mesh.\n *\n * Once instantiated in a scene, by default, all the emissive meshes will glow.\n *\n * Documentation: https://doc.babylonjs.com/features/featuresDeepDive/mesh/glowLayer\n */\nexport class GlowLayer extends EffectLayer {\n /**\n * Sets the kernel size of the blur.\n */\n set blurKernelSize(value) {\n if (value === this._options.blurKernelSize) {\n return;\n }\n this._options.blurKernelSize = value;\n const effectiveKernel = this._getEffectiveBlurKernelSize();\n this._horizontalBlurPostprocess1.kernel = effectiveKernel;\n this._verticalBlurPostprocess1.kernel = effectiveKernel;\n this._horizontalBlurPostprocess2.kernel = effectiveKernel;\n this._verticalBlurPostprocess2.kernel = effectiveKernel;\n }\n /**\n * Gets the kernel size of the blur.\n */\n get blurKernelSize() {\n return this._options.blurKernelSize;\n }\n /**\n * Sets the glow intensity.\n */\n set intensity(value) {\n this._intensity = value;\n }\n /**\n * Gets the glow intensity.\n */\n get intensity() {\n return this._intensity;\n }\n /**\n * Instantiates a new glow Layer and references it to the scene.\n * @param name The name of the layer\n * @param scene The scene to use the layer in\n * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)\n */\n constructor(name, scene, options) {\n super(name, scene);\n this._intensity = 1.0;\n this._includedOnlyMeshes = [];\n this._excludedMeshes = [];\n this._meshesUsingTheirOwnMaterials = [];\n this.neutralColor = new Color4(0, 0, 0, 1);\n // Adapt options\n this._options = Object.assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1, ldrMerge: false, alphaBlendingMode: 1, mainTextureType: 0 }, options);\n // Initialize the layer\n this._init({\n alphaBlendingMode: this._options.alphaBlendingMode,\n camera: this._options.camera,\n mainTextureFixedSize: this._options.mainTextureFixedSize,\n mainTextureRatio: this._options.mainTextureRatio,\n renderingGroupId: this._options.renderingGroupId,\n mainTextureType: this._options.mainTextureType,\n });\n }\n /**\n * Get the effect name of the layer.\n * @returns The effect name\n */\n getEffectName() {\n return GlowLayer.EffectName;\n }\n /**\n * Create the merge effect. This is the shader use to blit the information back\n * to the main canvas at the end of the scene rendering.\n */\n _createMergeEffect() {\n let defines = \"#define EMISSIVE \\n\";\n if (this._options.ldrMerge) {\n defines += \"#define LDR \\n\";\n }\n // Effect\n return this._engine.createEffect(\"glowMapMerge\", [VertexBuffer.PositionKind], [\"offset\"], [\"textureSampler\", \"textureSampler2\"], defines);\n }\n /**\n * Creates the render target textures and post processes used in the glow layer.\n */\n _createTextureAndPostProcesses() {\n let blurTextureWidth = this._mainTextureDesiredSize.width;\n let blurTextureHeight = this._mainTextureDesiredSize.height;\n blurTextureWidth = this._engine.needPOTTextures ? Engine.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;\n blurTextureHeight = this._engine.needPOTTextures ? Engine.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;\n let textureType = 0;\n if (this._engine.getCaps().textureHalfFloatRender) {\n textureType = 2;\n }\n else {\n textureType = 0;\n }\n this._blurTexture1 = new RenderTargetTexture(\"GlowLayerBlurRTT\", {\n width: blurTextureWidth,\n height: blurTextureHeight,\n }, this._scene, false, true, textureType);\n this._blurTexture1.wrapU = Texture.CLAMP_ADDRESSMODE;\n this._blurTexture1.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._blurTexture1.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);\n this._blurTexture1.renderParticles = false;\n this._blurTexture1.ignoreCameraViewport = true;\n const blurTextureWidth2 = Math.floor(blurTextureWidth / 2);\n const blurTextureHeight2 = Math.floor(blurTextureHeight / 2);\n this._blurTexture2 = new RenderTargetTexture(\"GlowLayerBlurRTT2\", {\n width: blurTextureWidth2,\n height: blurTextureHeight2,\n }, this._scene, false, true, textureType);\n this._blurTexture2.wrapU = Texture.CLAMP_ADDRESSMODE;\n this._blurTexture2.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._blurTexture2.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);\n this._blurTexture2.renderParticles = false;\n this._blurTexture2.ignoreCameraViewport = true;\n this._textures = [this._blurTexture1, this._blurTexture2];\n const effectiveKernel = this._getEffectiveBlurKernelSize();\n this._horizontalBlurPostprocess1 = new BlurPostProcess(\"GlowLayerHBP1\", new Vector2(1.0, 0), effectiveKernel, {\n width: blurTextureWidth,\n height: blurTextureHeight,\n }, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);\n this._horizontalBlurPostprocess1.width = blurTextureWidth;\n this._horizontalBlurPostprocess1.height = blurTextureHeight;\n this._horizontalBlurPostprocess1.externalTextureSamplerBinding = true;\n this._horizontalBlurPostprocess1.onApplyObservable.add((effect) => {\n effect.setTexture(\"textureSampler\", this._mainTexture);\n });\n this._verticalBlurPostprocess1 = new BlurPostProcess(\"GlowLayerVBP1\", new Vector2(0, 1.0), effectiveKernel, {\n width: blurTextureWidth,\n height: blurTextureHeight,\n }, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);\n this._horizontalBlurPostprocess2 = new BlurPostProcess(\"GlowLayerHBP2\", new Vector2(1.0, 0), effectiveKernel, {\n width: blurTextureWidth2,\n height: blurTextureHeight2,\n }, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);\n this._horizontalBlurPostprocess2.width = blurTextureWidth2;\n this._horizontalBlurPostprocess2.height = blurTextureHeight2;\n this._horizontalBlurPostprocess2.externalTextureSamplerBinding = true;\n this._horizontalBlurPostprocess2.onApplyObservable.add((effect) => {\n effect.setTexture(\"textureSampler\", this._blurTexture1);\n });\n this._verticalBlurPostprocess2 = new BlurPostProcess(\"GlowLayerVBP2\", new Vector2(0, 1.0), effectiveKernel, {\n width: blurTextureWidth2,\n height: blurTextureHeight2,\n }, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);\n this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];\n this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];\n this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];\n this._mainTexture.samples = this._options.mainTextureSamples;\n this._mainTexture.onAfterUnbindObservable.add(() => {\n const internalTexture = this._blurTexture1.renderTarget;\n if (internalTexture) {\n this._scene.postProcessManager.directRender(this._postProcesses1, internalTexture, true);\n const internalTexture2 = this._blurTexture2.renderTarget;\n if (internalTexture2) {\n this._scene.postProcessManager.directRender(this._postProcesses2, internalTexture2, true);\n }\n this._engine.unBindFramebuffer(internalTexture2 !== null && internalTexture2 !== void 0 ? internalTexture2 : internalTexture, true);\n }\n });\n // Prevent autoClear.\n this._postProcesses.map((pp) => {\n pp.autoClear = false;\n });\n }\n /**\n * @returns The blur kernel size used by the glow.\n * Note: The value passed in the options is divided by 2 for back compatibility.\n */\n _getEffectiveBlurKernelSize() {\n return this._options.blurKernelSize / 2;\n }\n /**\n * Checks for the readiness of the element composing the layer.\n * @param subMesh the mesh to check for\n * @param useInstances specify whether or not to use instances to render the mesh\n * @returns true if ready otherwise, false\n */\n isReady(subMesh, useInstances) {\n const material = subMesh.getMaterial();\n const mesh = subMesh.getRenderingMesh();\n if (!material || !mesh) {\n return false;\n }\n const emissiveTexture = material.emissiveTexture;\n return super._isReady(subMesh, useInstances, emissiveTexture);\n }\n /**\n * Returns whether or not the layer needs stencil enabled during the mesh rendering.\n */\n needStencil() {\n return false;\n }\n /**\n * Returns true if the mesh can be rendered, otherwise false.\n * @param mesh The mesh to render\n * @param material The material used on the mesh\n * @returns true if it can be rendered otherwise false\n */\n _canRenderMesh(mesh, material) {\n return true;\n }\n /**\n * Implementation specific of rendering the generating effect on the main canvas.\n * @param effect The effect used to render through\n */\n _internalRender(effect) {\n // Texture\n effect.setTexture(\"textureSampler\", this._blurTexture1);\n effect.setTexture(\"textureSampler2\", this._blurTexture2);\n effect.setFloat(\"offset\", this._intensity);\n // Cache\n const engine = this._engine;\n const previousStencilBuffer = engine.getStencilBuffer();\n // Draw order\n engine.setStencilBuffer(false);\n engine.drawElementsType(Material.TriangleFillMode, 0, 6);\n // Draw order\n engine.setStencilBuffer(previousStencilBuffer);\n }\n /**\n * Sets the required values for both the emissive texture and and the main color.\n * @param mesh\n * @param subMesh\n * @param material\n */\n _setEmissiveTextureAndColor(mesh, subMesh, material) {\n var _a;\n let textureLevel = 1.0;\n if (this.customEmissiveTextureSelector) {\n this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);\n }\n else {\n if (material) {\n this._emissiveTextureAndColor.texture = material.emissiveTexture;\n if (this._emissiveTextureAndColor.texture) {\n textureLevel = this._emissiveTextureAndColor.texture.level;\n }\n }\n else {\n this._emissiveTextureAndColor.texture = null;\n }\n }\n if (this.customEmissiveColorSelector) {\n this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);\n }\n else {\n if (material.emissiveColor) {\n const emissiveIntensity = (_a = material.emissiveIntensity) !== null && _a !== void 0 ? _a : 1;\n textureLevel *= emissiveIntensity;\n this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, material.alpha);\n }\n else {\n this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);\n }\n }\n }\n /**\n * Returns true if the mesh should render, otherwise false.\n * @param mesh The mesh to render\n * @returns true if it should render otherwise false\n */\n _shouldRenderMesh(mesh) {\n return this.hasMesh(mesh);\n }\n /**\n * Adds specific effects defines.\n * @param defines The defines to add specifics to.\n */\n _addCustomEffectDefines(defines) {\n defines.push(\"#define GLOW\");\n }\n /**\n * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.\n * @param mesh The mesh to exclude from the glow layer\n */\n addExcludedMesh(mesh) {\n if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {\n this._excludedMeshes.push(mesh.uniqueId);\n }\n }\n /**\n * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.\n * @param mesh The mesh to remove\n */\n removeExcludedMesh(mesh) {\n const index = this._excludedMeshes.indexOf(mesh.uniqueId);\n if (index !== -1) {\n this._excludedMeshes.splice(index, 1);\n }\n }\n /**\n * Add a mesh in the inclusion list to impact or being impacted by the glow layer.\n * @param mesh The mesh to include in the glow layer\n */\n addIncludedOnlyMesh(mesh) {\n if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {\n this._includedOnlyMeshes.push(mesh.uniqueId);\n }\n }\n /**\n * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.\n * @param mesh The mesh to remove\n */\n removeIncludedOnlyMesh(mesh) {\n const index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);\n if (index !== -1) {\n this._includedOnlyMeshes.splice(index, 1);\n }\n }\n /**\n * Determine if a given mesh will be used in the glow layer\n * @param mesh The mesh to test\n * @returns true if the mesh will be highlighted by the current glow layer\n */\n hasMesh(mesh) {\n if (!super.hasMesh(mesh)) {\n return false;\n }\n // Included Mesh\n if (this._includedOnlyMeshes.length) {\n return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;\n }\n // Excluded Mesh\n if (this._excludedMeshes.length) {\n return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;\n }\n return true;\n }\n /**\n * Defines whether the current material of the mesh should be use to render the effect.\n * @param mesh defines the current mesh to render\n */\n _useMeshMaterial(mesh) {\n if (this._meshesUsingTheirOwnMaterials.length == 0) {\n return false;\n }\n return this._meshesUsingTheirOwnMaterials.indexOf(mesh.uniqueId) > -1;\n }\n /**\n * Add a mesh to be rendered through its own material and not with emissive only.\n * @param mesh The mesh for which we need to use its material\n */\n referenceMeshToUseItsOwnMaterial(mesh) {\n mesh.resetDrawCache(this._mainTexture.renderPassId);\n this._meshesUsingTheirOwnMaterials.push(mesh.uniqueId);\n mesh.onDisposeObservable.add(() => {\n this._disposeMesh(mesh);\n });\n }\n /**\n * Remove a mesh from being rendered through its own material and not with emissive only.\n * @param mesh The mesh for which we need to not use its material\n */\n unReferenceMeshFromUsingItsOwnMaterial(mesh) {\n let index = this._meshesUsingTheirOwnMaterials.indexOf(mesh.uniqueId);\n while (index >= 0) {\n this._meshesUsingTheirOwnMaterials.splice(index, 1);\n index = this._meshesUsingTheirOwnMaterials.indexOf(mesh.uniqueId);\n }\n mesh.resetDrawCache(this._mainTexture.renderPassId);\n }\n /**\n * Free any resources and references associated to a mesh.\n * Internal use\n * @param mesh The mesh to free.\n * @internal\n */\n _disposeMesh(mesh) {\n this.removeIncludedOnlyMesh(mesh);\n this.removeExcludedMesh(mesh);\n }\n /**\n * Gets the class name of the effect layer\n * @returns the string with the class name of the effect layer\n */\n getClassName() {\n return \"GlowLayer\";\n }\n /**\n * Serializes this glow layer\n * @returns a serialized glow layer object\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this);\n serializationObject.customType = \"BABYLON.GlowLayer\";\n let index;\n // Included meshes\n serializationObject.includedMeshes = [];\n if (this._includedOnlyMeshes.length) {\n for (index = 0; index < this._includedOnlyMeshes.length; index++) {\n const mesh = this._scene.getMeshByUniqueId(this._includedOnlyMeshes[index]);\n if (mesh) {\n serializationObject.includedMeshes.push(mesh.id);\n }\n }\n }\n // Excluded meshes\n serializationObject.excludedMeshes = [];\n if (this._excludedMeshes.length) {\n for (index = 0; index < this._excludedMeshes.length; index++) {\n const mesh = this._scene.getMeshByUniqueId(this._excludedMeshes[index]);\n if (mesh) {\n serializationObject.excludedMeshes.push(mesh.id);\n }\n }\n }\n return serializationObject;\n }\n /**\n * Creates a Glow Layer from parsed glow layer data\n * @param parsedGlowLayer defines glow layer data\n * @param scene defines the current scene\n * @param rootUrl defines the root URL containing the glow layer information\n * @returns a parsed Glow Layer\n */\n static Parse(parsedGlowLayer, scene, rootUrl) {\n const gl = SerializationHelper.Parse(() => new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options), parsedGlowLayer, scene, rootUrl);\n let index;\n // Excluded meshes\n for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {\n const mesh = scene.getMeshById(parsedGlowLayer.excludedMeshes[index]);\n if (mesh) {\n gl.addExcludedMesh(mesh);\n }\n }\n // Included meshes\n for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {\n const mesh = scene.getMeshById(parsedGlowLayer.includedMeshes[index]);\n if (mesh) {\n gl.addIncludedOnlyMesh(mesh);\n }\n }\n return gl;\n }\n}\n/**\n * Effect Name of the layer.\n */\nGlowLayer.EffectName = \"GlowLayer\";\n/**\n * The default blur kernel size used for the glow.\n */\nGlowLayer.DefaultBlurKernelSize = 32;\n/**\n * The default texture size ratio used for the glow.\n */\nGlowLayer.DefaultTextureRatio = 0.5;\n__decorate([\n serialize()\n], GlowLayer.prototype, \"blurKernelSize\", null);\n__decorate([\n serialize()\n], GlowLayer.prototype, \"intensity\", null);\n__decorate([\n serialize(\"options\")\n], GlowLayer.prototype, \"_options\", void 0);\nRegisterClass(\"BABYLON.GlowLayer\", GlowLayer);\n//# sourceMappingURL=glowLayer.js.map","import { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n/**\n * Defines the layer scene component responsible to manage any layers\n * in a given scene.\n */\nexport class LayerSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpful to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_LAYER;\n this.scene = scene || EngineStore.LastCreatedScene;\n if (!this.scene) {\n return;\n }\n this._engine = this.scene.getEngine();\n this.scene.layers = new Array();\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene._beforeCameraDrawStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawCameraBackground);\n this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawCameraForegroundWithPostProcessing);\n this.scene._afterCameraPostProcessStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERAPOSTPROCESS_LAYER, this, this._drawCameraForegroundWithoutPostProcessing);\n this.scene._beforeRenderTargetDrawStage.registerStep(SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_LAYER, this, this._drawRenderTargetBackground);\n this.scene._afterRenderTargetDrawStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_LAYER, this, this._drawRenderTargetForegroundWithPostProcessing);\n this.scene._afterRenderTargetPostProcessStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER, this, this._drawRenderTargetForegroundWithoutPostProcessing);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n const layers = this.scene.layers;\n for (const layer of layers) {\n layer._rebuild();\n }\n }\n /**\n * Disposes the component and the associated resources.\n */\n dispose() {\n const layers = this.scene.layers;\n while (layers.length) {\n layers[0].dispose();\n }\n }\n _draw(predicate) {\n const layers = this.scene.layers;\n if (layers.length) {\n this._engine.setDepthBuffer(false);\n for (const layer of layers) {\n if (predicate(layer)) {\n layer.render();\n }\n }\n this._engine.setDepthBuffer(true);\n }\n }\n _drawCameraPredicate(layer, isBackground, applyPostProcess, cameraLayerMask) {\n return (!layer.renderOnlyInRenderTargetTextures &&\n layer.isBackground === isBackground &&\n layer.applyPostProcess === applyPostProcess &&\n (layer.layerMask & cameraLayerMask) !== 0);\n }\n _drawCameraBackground(camera) {\n this._draw((layer) => {\n return this._drawCameraPredicate(layer, true, true, camera.layerMask);\n });\n }\n _drawCameraForegroundWithPostProcessing(camera) {\n this._draw((layer) => {\n return this._drawCameraPredicate(layer, false, true, camera.layerMask);\n });\n }\n _drawCameraForegroundWithoutPostProcessing(camera) {\n this._draw((layer) => {\n return this._drawCameraPredicate(layer, false, false, camera.layerMask);\n });\n }\n _drawRenderTargetPredicate(layer, isBackground, applyPostProcess, cameraLayerMask, renderTargetTexture) {\n return (layer.renderTargetTextures.length > 0 &&\n layer.isBackground === isBackground &&\n layer.applyPostProcess === applyPostProcess &&\n layer.renderTargetTextures.indexOf(renderTargetTexture) > -1 &&\n (layer.layerMask & cameraLayerMask) !== 0);\n }\n _drawRenderTargetBackground(renderTarget) {\n this._draw((layer) => {\n return this._drawRenderTargetPredicate(layer, true, true, this.scene.activeCamera.layerMask, renderTarget);\n });\n }\n _drawRenderTargetForegroundWithPostProcessing(renderTarget) {\n this._draw((layer) => {\n return this._drawRenderTargetPredicate(layer, false, true, this.scene.activeCamera.layerMask, renderTarget);\n });\n }\n _drawRenderTargetForegroundWithoutPostProcessing(renderTarget) {\n this._draw((layer) => {\n return this._drawRenderTargetPredicate(layer, false, false, this.scene.activeCamera.layerMask, renderTarget);\n });\n }\n /**\n * Adds all the elements from the container to the scene\n * @param container the container holding the elements\n */\n addFromContainer(container) {\n if (!container.layers) {\n return;\n }\n container.layers.forEach((layer) => {\n this.scene.layers.push(layer);\n });\n }\n /**\n * Removes all the elements in the container from the scene\n * @param container contains the elements to remove\n * @param dispose if the removed element should be disposed (default: false)\n */\n removeFromContainer(container, dispose = false) {\n if (!container.layers) {\n return;\n }\n container.layers.forEach((layer) => {\n const index = this.scene.layers.indexOf(layer);\n if (index !== -1) {\n this.scene.layers.splice(index, 1);\n }\n if (dispose) {\n layer.dispose();\n }\n });\n }\n}\n//# sourceMappingURL=layerSceneComponent.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"glowBlurPostProcessPixelShader\";\nconst shader = `varying vec2 vUV;\runiform sampler2D textureSampler;\runiform vec2 screenSize;\runiform vec2 direction;\runiform float blurWidth;\rfloat getLuminance(vec3 color)\r{\rreturn dot(color,vec3(0.2126,0.7152,0.0722));\r}\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\r{\rfloat weights[7];\rweights[0]=0.05;\rweights[1]=0.1;\rweights[2]=0.2;\rweights[3]=0.3;\rweights[4]=0.2;\rweights[5]=0.1;\rweights[6]=0.05;\rvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\rvec2 texelStep=texelSize*direction*blurWidth;\rvec2 start=vUV-3.0*texelStep;\rvec4 baseColor=vec4(0.,0.,0.,0.);\rvec2 texelOffset=vec2(0.,0.);\rfor (int i=0; i<7; i++)\r{\rvec4 texel=texture2D(textureSampler,start+texelOffset);\rbaseColor.a+=texel.a*weights[i];\rfloat luminance=getLuminance(baseColor.rgb);\rfloat luminanceTexel=getLuminance(texel.rgb);\rfloat choice=step(luminanceTexel,luminance);\rbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\rtexelOffset+=texelStep;\r}\rgl_FragColor=baseColor;\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const glowBlurPostProcessPixelShader = { name, shader };\n//# sourceMappingURL=glowBlurPostProcess.fragment.js.map","import { __decorate } from \"../tslib.es6.js\";\n/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { serialize, SerializationHelper } from \"../Misc/decorators.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Vector2 } from \"../Maths/math.vector.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Material } from \"../Materials/material.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { RenderTargetTexture } from \"../Materials/Textures/renderTargetTexture.js\";\nimport { PostProcess } from \"../PostProcesses/postProcess.js\";\nimport { PassPostProcess } from \"../PostProcesses/passPostProcess.js\";\nimport { BlurPostProcess } from \"../PostProcesses/blurPostProcess.js\";\nimport { EffectLayer } from \"./effectLayer.js\";\nimport { AbstractScene } from \"../abstractScene.js\";\n\nimport { Logger } from \"../Misc/logger.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\nimport { Color4, Color3 } from \"../Maths/math.color.js\";\nimport \"../Shaders/glowMapMerge.fragment.js\";\nimport \"../Shaders/glowMapMerge.vertex.js\";\nimport \"../Shaders/glowBlurPostProcess.fragment.js\";\nimport \"../Layers/effectLayerSceneComponent.js\";\nAbstractScene.prototype.getHighlightLayerByName = function (name) {\n var _a;\n for (let index = 0; index < ((_a = this.effectLayers) === null || _a === void 0 ? void 0 : _a.length); index++) {\n if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {\n return this.effectLayers[index];\n }\n }\n return null;\n};\n/**\n * Special Glow Blur post process only blurring the alpha channel\n * It enforces keeping the most luminous color in the color channel.\n */\nclass GlowBlurPostProcess extends PostProcess {\n constructor(name, direction, kernel, options, camera, samplingMode = Texture.BILINEAR_SAMPLINGMODE, engine, reusable) {\n super(name, \"glowBlurPostProcess\", [\"screenSize\", \"direction\", \"blurWidth\"], null, options, camera, samplingMode, engine, reusable);\n this.direction = direction;\n this.kernel = kernel;\n this.onApplyObservable.add((effect) => {\n effect.setFloat2(\"screenSize\", this.width, this.height);\n effect.setVector2(\"direction\", this.direction);\n effect.setFloat(\"blurWidth\", this.kernel);\n });\n }\n}\n/**\n * The highlight layer Helps adding a glow effect around a mesh.\n *\n * Once instantiated in a scene, simply use the addMesh or removeMesh method to add or remove\n * glowy meshes to your scene.\n *\n * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!\n */\nexport class HighlightLayer extends EffectLayer {\n /**\n * Specifies the horizontal size of the blur.\n */\n set blurHorizontalSize(value) {\n this._horizontalBlurPostprocess.kernel = value;\n this._options.blurHorizontalSize = value;\n }\n /**\n * Specifies the vertical size of the blur.\n */\n set blurVerticalSize(value) {\n this._verticalBlurPostprocess.kernel = value;\n this._options.blurVerticalSize = value;\n }\n /**\n * Gets the horizontal size of the blur.\n */\n get blurHorizontalSize() {\n return this._horizontalBlurPostprocess.kernel;\n }\n /**\n * Gets the vertical size of the blur.\n */\n get blurVerticalSize() {\n return this._verticalBlurPostprocess.kernel;\n }\n /**\n * Instantiates a new highlight Layer and references it to the scene..\n * @param name The name of the layer\n * @param scene The scene to use the layer in\n * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)\n */\n constructor(name, scene, options) {\n super(name, scene);\n this.name = name;\n /**\n * Specifies whether or not the inner glow is ACTIVE in the layer.\n */\n this.innerGlow = true;\n /**\n * Specifies whether or not the outer glow is ACTIVE in the layer.\n */\n this.outerGlow = true;\n /**\n * An event triggered when the highlight layer is being blurred.\n */\n this.onBeforeBlurObservable = new Observable();\n /**\n * An event triggered when the highlight layer has been blurred.\n */\n this.onAfterBlurObservable = new Observable();\n this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;\n this._meshes = {};\n this._excludedMeshes = {};\n this.neutralColor = HighlightLayer.NeutralColor;\n // Warn on stencil\n if (!this._engine.isStencilEnable) {\n Logger.Warn(\"Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }\");\n }\n // Adapt options\n this._options = Object.assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: 2, camera: null, renderingGroupId: -1, mainTextureType: 0 }, options);\n // Initialize the layer\n this._init({\n alphaBlendingMode: this._options.alphaBlendingMode,\n camera: this._options.camera,\n mainTextureFixedSize: this._options.mainTextureFixedSize,\n mainTextureRatio: this._options.mainTextureRatio,\n renderingGroupId: this._options.renderingGroupId,\n mainTextureType: this._options.mainTextureType,\n });\n // Do not render as long as no meshes have been added\n this._shouldRender = false;\n }\n /**\n * Get the effect name of the layer.\n * @returns The effect name\n */\n getEffectName() {\n return HighlightLayer.EffectName;\n }\n _numInternalDraws() {\n return 2; // we need two rendering, one for the inner glow and the other for the outer glow\n }\n /**\n * Create the merge effect. This is the shader use to blit the information back\n * to the main canvas at the end of the scene rendering.\n */\n _createMergeEffect() {\n // Effect\n return this._engine.createEffect(\"glowMapMerge\", [VertexBuffer.PositionKind], [\"offset\"], [\"textureSampler\"], this._options.isStroke ? \"#define STROKE \\n\" : undefined);\n }\n /**\n * Creates the render target textures and post processes used in the highlight layer.\n */\n _createTextureAndPostProcesses() {\n let blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;\n let blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;\n blurTextureWidth = this._engine.needPOTTextures ? Engine.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;\n blurTextureHeight = this._engine.needPOTTextures ? Engine.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;\n let textureType = 0;\n if (this._engine.getCaps().textureHalfFloatRender) {\n textureType = 2;\n }\n else {\n textureType = 0;\n }\n this._blurTexture = new RenderTargetTexture(\"HighlightLayerBlurRTT\", {\n width: blurTextureWidth,\n height: blurTextureHeight,\n }, this._scene, false, true, textureType);\n this._blurTexture.wrapU = Texture.CLAMP_ADDRESSMODE;\n this._blurTexture.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._blurTexture.anisotropicFilteringLevel = 16;\n this._blurTexture.updateSamplingMode(Texture.TRILINEAR_SAMPLINGMODE);\n this._blurTexture.renderParticles = false;\n this._blurTexture.ignoreCameraViewport = true;\n this._textures = [this._blurTexture];\n if (this._options.alphaBlendingMode === 2) {\n this._downSamplePostprocess = new PassPostProcess(\"HighlightLayerPPP\", this._options.blurTextureSizeRatio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());\n this._downSamplePostprocess.externalTextureSamplerBinding = true;\n this._downSamplePostprocess.onApplyObservable.add((effect) => {\n effect.setTexture(\"textureSampler\", this._mainTexture);\n });\n this._horizontalBlurPostprocess = new GlowBlurPostProcess(\"HighlightLayerHBP\", new Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());\n this._horizontalBlurPostprocess.onApplyObservable.add((effect) => {\n effect.setFloat2(\"screenSize\", blurTextureWidth, blurTextureHeight);\n });\n this._verticalBlurPostprocess = new GlowBlurPostProcess(\"HighlightLayerVBP\", new Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());\n this._verticalBlurPostprocess.onApplyObservable.add((effect) => {\n effect.setFloat2(\"screenSize\", blurTextureWidth, blurTextureHeight);\n });\n this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];\n }\n else {\n this._horizontalBlurPostprocess = new BlurPostProcess(\"HighlightLayerHBP\", new Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {\n width: blurTextureWidth,\n height: blurTextureHeight,\n }, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);\n this._horizontalBlurPostprocess.width = blurTextureWidth;\n this._horizontalBlurPostprocess.height = blurTextureHeight;\n this._horizontalBlurPostprocess.externalTextureSamplerBinding = true;\n this._horizontalBlurPostprocess.onApplyObservable.add((effect) => {\n effect.setTexture(\"textureSampler\", this._mainTexture);\n });\n this._verticalBlurPostprocess = new BlurPostProcess(\"HighlightLayerVBP\", new Vector2(0, 1.0), this._options.blurVerticalSize / 2, {\n width: blurTextureWidth,\n height: blurTextureHeight,\n }, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);\n this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];\n }\n this._mainTexture.onAfterUnbindObservable.add(() => {\n this.onBeforeBlurObservable.notifyObservers(this);\n const internalTexture = this._blurTexture.renderTarget;\n if (internalTexture) {\n this._scene.postProcessManager.directRender(this._postProcesses, internalTexture, true);\n this._engine.unBindFramebuffer(internalTexture, true);\n }\n this.onAfterBlurObservable.notifyObservers(this);\n });\n // Prevent autoClear.\n this._postProcesses.map((pp) => {\n pp.autoClear = false;\n });\n }\n /**\n * Returns whether or not the layer needs stencil enabled during the mesh rendering.\n */\n needStencil() {\n return true;\n }\n /**\n * Checks for the readiness of the element composing the layer.\n * @param subMesh the mesh to check for\n * @param useInstances specify whether or not to use instances to render the mesh\n * @returns true if ready otherwise, false\n */\n isReady(subMesh, useInstances) {\n const material = subMesh.getMaterial();\n const mesh = subMesh.getRenderingMesh();\n if (!material || !mesh || !this._meshes) {\n return false;\n }\n let emissiveTexture = null;\n const highlightLayerMesh = this._meshes[mesh.uniqueId];\n if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {\n emissiveTexture = material.emissiveTexture;\n }\n return super._isReady(subMesh, useInstances, emissiveTexture);\n }\n /**\n * Implementation specific of rendering the generating effect on the main canvas.\n * @param effect The effect used to render through\n * @param renderIndex\n */\n _internalRender(effect, renderIndex) {\n // Texture\n effect.setTexture(\"textureSampler\", this._blurTexture);\n // Cache\n const engine = this._engine;\n engine.cacheStencilState();\n // Stencil operations\n engine.setStencilOperationPass(7681);\n engine.setStencilOperationFail(7680);\n engine.setStencilOperationDepthFail(7680);\n // Draw order\n engine.setStencilMask(0x00);\n engine.setStencilBuffer(true);\n engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);\n // 2 passes inner outer\n if (this.outerGlow && renderIndex === 0) {\n // the outer glow is rendered the first time _internalRender is called, so when renderIndex == 0 (and only if outerGlow is enabled)\n effect.setFloat(\"offset\", 0);\n engine.setStencilFunction(517);\n engine.drawElementsType(Material.TriangleFillMode, 0, 6);\n }\n if (this.innerGlow && renderIndex === 1) {\n // the inner glow is rendered the second time _internalRender is called, so when renderIndex == 1 (and only if innerGlow is enabled)\n effect.setFloat(\"offset\", 1);\n engine.setStencilFunction(514);\n engine.drawElementsType(Material.TriangleFillMode, 0, 6);\n }\n // Restore Cache\n engine.restoreStencilState();\n }\n /**\n * Returns true if the layer contains information to display, otherwise false.\n */\n shouldRender() {\n if (super.shouldRender()) {\n return this._meshes ? true : false;\n }\n return false;\n }\n /**\n * Returns true if the mesh should render, otherwise false.\n * @param mesh The mesh to render\n * @returns true if it should render otherwise false\n */\n _shouldRenderMesh(mesh) {\n // Excluded Mesh\n if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {\n return false;\n }\n if (!super.hasMesh(mesh)) {\n return false;\n }\n return true;\n }\n /**\n * Returns true if the mesh can be rendered, otherwise false.\n * @param mesh The mesh to render\n * @param material The material used on the mesh\n * @returns true if it can be rendered otherwise false\n */\n _canRenderMesh(mesh, material) {\n // all meshes can be rendered in the highlight layer, even transparent ones\n return true;\n }\n /**\n * Adds specific effects defines.\n * @param defines The defines to add specifics to.\n */\n _addCustomEffectDefines(defines) {\n defines.push(\"#define HIGHLIGHT\");\n }\n /**\n * Sets the required values for both the emissive texture and and the main color.\n * @param mesh\n * @param subMesh\n * @param material\n */\n _setEmissiveTextureAndColor(mesh, subMesh, material) {\n const highlightLayerMesh = this._meshes[mesh.uniqueId];\n if (highlightLayerMesh) {\n this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);\n }\n else {\n this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);\n }\n if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {\n this._emissiveTextureAndColor.texture = material.emissiveTexture;\n this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);\n }\n else {\n this._emissiveTextureAndColor.texture = null;\n }\n }\n /**\n * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.\n * @param mesh The mesh to exclude from the highlight layer\n */\n addExcludedMesh(mesh) {\n if (!this._excludedMeshes) {\n return;\n }\n const meshExcluded = this._excludedMeshes[mesh.uniqueId];\n if (!meshExcluded) {\n const obj = {\n mesh: mesh,\n beforeBind: null,\n afterRender: null,\n stencilState: false,\n };\n obj.beforeBind = mesh.onBeforeBindObservable.add((mesh) => {\n obj.stencilState = mesh.getEngine().getStencilBuffer();\n mesh.getEngine().setStencilBuffer(false);\n });\n obj.afterRender = mesh.onAfterRenderObservable.add((mesh) => {\n mesh.getEngine().setStencilBuffer(obj.stencilState);\n });\n this._excludedMeshes[mesh.uniqueId] = obj;\n }\n }\n /**\n * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.\n * @param mesh The mesh to highlight\n */\n removeExcludedMesh(mesh) {\n if (!this._excludedMeshes) {\n return;\n }\n const meshExcluded = this._excludedMeshes[mesh.uniqueId];\n if (meshExcluded) {\n if (meshExcluded.beforeBind) {\n mesh.onBeforeBindObservable.remove(meshExcluded.beforeBind);\n }\n if (meshExcluded.afterRender) {\n mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);\n }\n }\n this._excludedMeshes[mesh.uniqueId] = null;\n }\n /**\n * Determine if a given mesh will be highlighted by the current HighlightLayer\n * @param mesh mesh to test\n * @returns true if the mesh will be highlighted by the current HighlightLayer\n */\n hasMesh(mesh) {\n if (!this._meshes) {\n return false;\n }\n if (!super.hasMesh(mesh)) {\n return false;\n }\n return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;\n }\n /**\n * Add a mesh in the highlight layer in order to make it glow with the chosen color.\n * @param mesh The mesh to highlight\n * @param color The color of the highlight\n * @param glowEmissiveOnly Extract the glow from the emissive texture\n */\n addMesh(mesh, color, glowEmissiveOnly = false) {\n if (!this._meshes) {\n return;\n }\n const meshHighlight = this._meshes[mesh.uniqueId];\n if (meshHighlight) {\n meshHighlight.color = color;\n }\n else {\n this._meshes[mesh.uniqueId] = {\n mesh: mesh,\n color: color,\n // Lambda required for capture due to Observable this context\n observerHighlight: mesh.onBeforeBindObservable.add((mesh) => {\n if (this.isEnabled) {\n if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {\n this._defaultStencilReference(mesh);\n }\n else {\n mesh.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference);\n }\n }\n }),\n observerDefault: mesh.onAfterRenderObservable.add((mesh) => {\n if (this.isEnabled) {\n this._defaultStencilReference(mesh);\n }\n }),\n glowEmissiveOnly: glowEmissiveOnly,\n };\n mesh.onDisposeObservable.add(() => {\n this._disposeMesh(mesh);\n });\n }\n this._shouldRender = true;\n }\n /**\n * Remove a mesh from the highlight layer in order to make it stop glowing.\n * @param mesh The mesh to highlight\n */\n removeMesh(mesh) {\n if (!this._meshes) {\n return;\n }\n const meshHighlight = this._meshes[mesh.uniqueId];\n if (meshHighlight) {\n if (meshHighlight.observerHighlight) {\n mesh.onBeforeBindObservable.remove(meshHighlight.observerHighlight);\n }\n if (meshHighlight.observerDefault) {\n mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);\n }\n delete this._meshes[mesh.uniqueId];\n }\n this._shouldRender = false;\n for (const meshHighlightToCheck in this._meshes) {\n if (this._meshes[meshHighlightToCheck]) {\n this._shouldRender = true;\n break;\n }\n }\n }\n /**\n * Remove all the meshes currently referenced in the highlight layer\n */\n removeAllMeshes() {\n if (!this._meshes) {\n return;\n }\n for (const uniqueId in this._meshes) {\n if (Object.prototype.hasOwnProperty.call(this._meshes, uniqueId)) {\n const mesh = this._meshes[uniqueId];\n if (mesh) {\n this.removeMesh(mesh.mesh);\n }\n }\n }\n }\n /**\n * Force the stencil to the normal expected value for none glowing parts\n * @param mesh\n */\n _defaultStencilReference(mesh) {\n mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);\n }\n /**\n * Free any resources and references associated to a mesh.\n * Internal use\n * @param mesh The mesh to free.\n * @internal\n */\n _disposeMesh(mesh) {\n this.removeMesh(mesh);\n this.removeExcludedMesh(mesh);\n }\n /**\n * Dispose the highlight layer and free resources.\n */\n dispose() {\n if (this._meshes) {\n // Clean mesh references\n for (const id in this._meshes) {\n const meshHighlight = this._meshes[id];\n if (meshHighlight && meshHighlight.mesh) {\n if (meshHighlight.observerHighlight) {\n meshHighlight.mesh.onBeforeBindObservable.remove(meshHighlight.observerHighlight);\n }\n if (meshHighlight.observerDefault) {\n meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);\n }\n }\n }\n this._meshes = null;\n }\n if (this._excludedMeshes) {\n for (const id in this._excludedMeshes) {\n const meshHighlight = this._excludedMeshes[id];\n if (meshHighlight) {\n if (meshHighlight.beforeBind) {\n meshHighlight.mesh.onBeforeBindObservable.remove(meshHighlight.beforeBind);\n }\n if (meshHighlight.afterRender) {\n meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);\n }\n }\n }\n this._excludedMeshes = null;\n }\n super.dispose();\n }\n /**\n * Gets the class name of the effect layer\n * @returns the string with the class name of the effect layer\n */\n getClassName() {\n return \"HighlightLayer\";\n }\n /**\n * Serializes this Highlight layer\n * @returns a serialized Highlight layer object\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this);\n serializationObject.customType = \"BABYLON.HighlightLayer\";\n // Highlighted meshes\n serializationObject.meshes = [];\n if (this._meshes) {\n for (const m in this._meshes) {\n const mesh = this._meshes[m];\n if (mesh) {\n serializationObject.meshes.push({\n glowEmissiveOnly: mesh.glowEmissiveOnly,\n color: mesh.color.asArray(),\n meshId: mesh.mesh.id,\n });\n }\n }\n }\n // Excluded meshes\n serializationObject.excludedMeshes = [];\n if (this._excludedMeshes) {\n for (const e in this._excludedMeshes) {\n const excludedMesh = this._excludedMeshes[e];\n if (excludedMesh) {\n serializationObject.excludedMeshes.push(excludedMesh.mesh.id);\n }\n }\n }\n return serializationObject;\n }\n /**\n * Creates a Highlight layer from parsed Highlight layer data\n * @param parsedHightlightLayer defines the Highlight layer data\n * @param scene defines the current scene\n * @param rootUrl defines the root URL containing the Highlight layer information\n * @returns a parsed Highlight layer\n */\n static Parse(parsedHightlightLayer, scene, rootUrl) {\n const hl = SerializationHelper.Parse(() => new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options), parsedHightlightLayer, scene, rootUrl);\n let index;\n // Excluded meshes\n for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {\n const mesh = scene.getMeshById(parsedHightlightLayer.excludedMeshes[index]);\n if (mesh) {\n hl.addExcludedMesh(mesh);\n }\n }\n // Included meshes\n for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {\n const highlightedMesh = parsedHightlightLayer.meshes[index];\n const mesh = scene.getMeshById(highlightedMesh.meshId);\n if (mesh) {\n hl.addMesh(mesh, Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);\n }\n }\n return hl;\n }\n}\n/**\n * Effect Name of the highlight layer.\n */\nHighlightLayer.EffectName = \"HighlightLayer\";\n/**\n * The neutral color used during the preparation of the glow effect.\n * This is black by default as the blend operation is a blend operation.\n */\nHighlightLayer.NeutralColor = new Color4(0, 0, 0, 0);\n/**\n * Stencil value used for glowing meshes.\n */\nHighlightLayer.GlowingMeshStencilReference = 0x02;\n/**\n * Stencil value used for the other meshes in the scene.\n */\nHighlightLayer.NormalMeshStencilReference = 0x01;\n__decorate([\n serialize()\n], HighlightLayer.prototype, \"innerGlow\", void 0);\n__decorate([\n serialize()\n], HighlightLayer.prototype, \"outerGlow\", void 0);\n__decorate([\n serialize()\n], HighlightLayer.prototype, \"blurHorizontalSize\", null);\n__decorate([\n serialize()\n], HighlightLayer.prototype, \"blurVerticalSize\", null);\n__decorate([\n serialize(\"options\")\n], HighlightLayer.prototype, \"_options\", void 0);\nRegisterClass(\"BABYLON.HighlightLayer\", HighlightLayer);\n//# sourceMappingURL=highlightLayer.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { Vector2 } from \"../Maths/math.vector.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Material } from \"../Materials/material.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { LayerSceneComponent } from \"./layerSceneComponent.js\";\n\nimport { DrawWrapper } from \"../Materials/drawWrapper.js\";\nimport \"../Shaders/layer.fragment.js\";\nimport \"../Shaders/layer.vertex.js\";\n/**\n * This represents a full screen 2d layer.\n * This can be useful to display a picture in the background of your scene for instance.\n * @see https://www.babylonjs-playground.com/#08A2BS#1\n */\nexport class Layer {\n /**\n * Determines if the layer is drawn before (true) or after (false) post-processing.\n * If the layer is background, it is always before.\n */\n set applyPostProcess(value) {\n this._applyPostProcess = value;\n }\n get applyPostProcess() {\n return this.isBackground || this._applyPostProcess;\n }\n /**\n * Back compatibility with callback before the onDisposeObservable existed.\n * The set callback will be triggered when the layer has been disposed.\n */\n set onDispose(callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n }\n /**\n * Back compatibility with callback before the onBeforeRenderObservable existed.\n * The set callback will be triggered just before rendering the layer.\n */\n set onBeforeRender(callback) {\n if (this._onBeforeRenderObserver) {\n this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);\n }\n this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);\n }\n /**\n * Back compatibility with callback before the onAfterRenderObservable existed.\n * The set callback will be triggered just after rendering the layer.\n */\n set onAfterRender(callback) {\n if (this._onAfterRenderObserver) {\n this.onAfterRenderObservable.remove(this._onAfterRenderObserver);\n }\n this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);\n }\n /**\n * Instantiates a new layer.\n * This represents a full screen 2d layer.\n * This can be useful to display a picture in the background of your scene for instance.\n * @see https://www.babylonjs-playground.com/#08A2BS#1\n * @param name Define the name of the layer in the scene\n * @param imgUrl Define the url of the texture to display in the layer\n * @param scene Define the scene the layer belongs to\n * @param isBackground Defines whether the layer is displayed in front or behind the scene\n * @param color Defines a color for the layer\n */\n constructor(\n /**\n * Define the name of the layer.\n */\n name, imgUrl, scene, isBackground, color) {\n this.name = name;\n this._applyPostProcess = true;\n /**\n * Define the scale of the layer in order to zoom in out of the texture.\n */\n this.scale = new Vector2(1, 1);\n /**\n * Define an offset for the layer in order to shift the texture.\n */\n this.offset = new Vector2(0, 0);\n /**\n * Define the alpha blending mode used in the layer in case the texture or color has an alpha.\n */\n this.alphaBlendingMode = 2;\n /**\n * Define a mask to restrict the layer to only some of the scene cameras.\n */\n this.layerMask = 0x0fffffff;\n /**\n * Define the list of render target the layer is visible into.\n */\n this.renderTargetTextures = [];\n /**\n * Define if the layer is only used in renderTarget or if it also\n * renders in the main frame buffer of the canvas.\n */\n this.renderOnlyInRenderTargetTextures = false;\n /**\n * Define if the layer is enabled (ie. should be displayed). Default: true\n */\n this.isEnabled = true;\n this._vertexBuffers = {};\n /**\n * An event triggered when the layer is disposed.\n */\n this.onDisposeObservable = new Observable();\n /**\n * An event triggered before rendering the scene\n */\n this.onBeforeRenderObservable = new Observable();\n /**\n * An event triggered after rendering the scene\n */\n this.onAfterRenderObservable = new Observable();\n this.texture = imgUrl ? new Texture(imgUrl, scene, true) : null;\n this.isBackground = isBackground === undefined ? true : isBackground;\n this.color = color === undefined ? new Color4(1, 1, 1, 1) : color;\n this._scene = (scene || EngineStore.LastCreatedScene);\n let layerComponent = this._scene._getComponent(SceneComponentConstants.NAME_LAYER);\n if (!layerComponent) {\n layerComponent = new LayerSceneComponent(this._scene);\n this._scene._addComponent(layerComponent);\n }\n this._scene.layers.push(this);\n const engine = this._scene.getEngine();\n this._drawWrapper = new DrawWrapper(engine);\n // VBO\n const vertices = [];\n vertices.push(1, 1);\n vertices.push(-1, 1);\n vertices.push(-1, -1);\n vertices.push(1, -1);\n const vertexBuffer = new VertexBuffer(engine, vertices, VertexBuffer.PositionKind, false, false, 2);\n this._vertexBuffers[VertexBuffer.PositionKind] = vertexBuffer;\n this._createIndexBuffer();\n }\n _createIndexBuffer() {\n const engine = this._scene.getEngine();\n // Indices\n const indices = [];\n indices.push(0);\n indices.push(1);\n indices.push(2);\n indices.push(0);\n indices.push(2);\n indices.push(3);\n this._indexBuffer = engine.createIndexBuffer(indices);\n }\n /** @internal */\n _rebuild() {\n const vb = this._vertexBuffers[VertexBuffer.PositionKind];\n if (vb) {\n vb._rebuild();\n }\n this._createIndexBuffer();\n }\n /**\n * Checks if the layer is ready to be rendered\n * @returns true if the layer is ready. False otherwise.\n */\n isReady() {\n var _a;\n const engine = this._scene.getEngine();\n let defines = \"\";\n if (this.alphaTest) {\n defines = \"#define ALPHATEST\";\n }\n if (this.texture && !this.texture.gammaSpace) {\n defines += \"\\r\\n#define LINEAR\";\n }\n if (this._previousDefines !== defines) {\n this._previousDefines = defines;\n this._drawWrapper.effect = engine.createEffect(\"layer\", [VertexBuffer.PositionKind], [\"textureMatrix\", \"color\", \"scale\", \"offset\"], [\"textureSampler\"], defines);\n }\n const currentEffect = this._drawWrapper.effect;\n return (currentEffect === null || currentEffect === void 0 ? void 0 : currentEffect.isReady()) && ((_a = this.texture) === null || _a === void 0 ? void 0 : _a.isReady());\n }\n /**\n * Renders the layer in the scene.\n */\n render() {\n if (!this.isEnabled) {\n return;\n }\n const engine = this._scene.getEngine();\n // Check\n if (!this.isReady()) {\n return;\n }\n const currentEffect = this._drawWrapper.effect;\n this.onBeforeRenderObservable.notifyObservers(this);\n // Render\n engine.enableEffect(this._drawWrapper);\n engine.setState(false);\n // Texture\n currentEffect.setTexture(\"textureSampler\", this.texture);\n currentEffect.setMatrix(\"textureMatrix\", this.texture.getTextureMatrix());\n // Color\n currentEffect.setFloat4(\"color\", this.color.r, this.color.g, this.color.b, this.color.a);\n // Scale / offset\n currentEffect.setVector2(\"offset\", this.offset);\n currentEffect.setVector2(\"scale\", this.scale);\n // VBOs\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);\n // Draw order\n if (!this.alphaTest) {\n engine.setAlphaMode(this.alphaBlendingMode);\n engine.drawElementsType(Material.TriangleFillMode, 0, 6);\n engine.setAlphaMode(0);\n }\n else {\n engine.drawElementsType(Material.TriangleFillMode, 0, 6);\n }\n this.onAfterRenderObservable.notifyObservers(this);\n }\n /**\n * Disposes and releases the associated resources.\n */\n dispose() {\n const vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];\n if (vertexBuffer) {\n vertexBuffer.dispose();\n this._vertexBuffers[VertexBuffer.PositionKind] = null;\n }\n if (this._indexBuffer) {\n this._scene.getEngine()._releaseBuffer(this._indexBuffer);\n this._indexBuffer = null;\n }\n if (this.texture) {\n this.texture.dispose();\n this.texture = null;\n }\n // Clean RTT list\n this.renderTargetTextures = [];\n // Remove from scene\n const index = this._scene.layers.indexOf(this);\n this._scene.layers.splice(index, 1);\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n this.onAfterRenderObservable.clear();\n this.onBeforeRenderObservable.clear();\n }\n}\n//# sourceMappingURL=layer.js.map","export * from \"./effectLayer.js\";\nexport * from \"./effectLayerSceneComponent.js\";\nexport * from \"./glowLayer.js\";\nexport * from \"./highlightLayer.js\";\nexport * from \"./layer.js\";\nexport * from \"./layerSceneComponent.js\";\n//# sourceMappingURL=index.js.map","import { Color3 } from \"../Maths/math.color.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\n\nimport { DrawWrapper } from \"../Materials/drawWrapper.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\n/**\n * This represents one of the lens effect in a `lensFlareSystem`.\n * It controls one of the individual texture used in the effect.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare\n */\nexport class LensFlare {\n /**\n * Creates a new Lens Flare.\n * This represents one of the lens effect in a `lensFlareSystem`.\n * It controls one of the individual texture used in the effect.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare\n * @param size Define the size of the lens flare (a floating value between 0 and 1)\n * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.\n * @param color Define the lens color\n * @param imgUrl Define the lens texture url\n * @param system Define the `lensFlareSystem` this flare is part of\n * @returns The newly created Lens Flare\n */\n static AddFlare(size, position, color, imgUrl, system) {\n return new LensFlare(size, position, color, imgUrl, system);\n }\n /**\n * Instantiates a new Lens Flare.\n * This represents one of the lens effect in a `lensFlareSystem`.\n * It controls one of the individual texture used in the effect.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare\n * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)\n * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.\n * @param color Define the lens color\n * @param imgUrl Define the lens texture url\n * @param system Define the `lensFlareSystem` this flare is part of\n */\n constructor(\n /**\n * Define the size of the lens flare in the system (a floating value between 0 and 1)\n */\n size, \n /**\n * Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.\n */\n position, color, imgUrl, system) {\n this.size = size;\n this.position = position;\n /**\n * Define the alpha mode to render this particular lens.\n */\n this.alphaMode = 6;\n this.color = color || new Color3(1, 1, 1);\n this.texture = imgUrl ? new Texture(imgUrl, system.getScene(), true) : null;\n this._system = system;\n const engine = system.scene.getEngine();\n this._drawWrapper = new DrawWrapper(engine);\n this._drawWrapper.effect = engine.createEffect(\"lensFlare\", [VertexBuffer.PositionKind], [\"color\", \"viewportMatrix\"], [\"textureSampler\"], \"\");\n system.lensFlares.push(this);\n }\n /**\n * Dispose and release the lens flare with its associated resources.\n */\n dispose() {\n if (this.texture) {\n this.texture.dispose();\n }\n // Remove from scene\n const index = this._system.lensFlares.indexOf(this);\n this._system.lensFlares.splice(index, 1);\n }\n}\n//# sourceMappingURL=lensFlare.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"lensFlarePixelShader\";\nconst shader = `varying vec2 vUV;\runiform sampler2D textureSampler;\runiform vec4 color;\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\rgl_FragColor=baseColor*color;\r#define CUSTOM_FRAGMENT_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const lensFlarePixelShader = { name, shader };\n//# sourceMappingURL=lensFlare.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"lensFlareVertexShader\";\nconst shader = `attribute vec2 position;\runiform mat4 viewportMatrix;\rvarying vec2 vUV;\rconst vec2 madd=vec2(0.5,0.5);\r#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=position*madd+madd;\rgl_Position=viewportMatrix*vec4(position,0.0,1.0);\r#define CUSTOM_VERTEX_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const lensFlareVertexShader = { name, shader };\n//# sourceMappingURL=lensFlare.vertex.js.map","import { Tools } from \"../Misc/tools.js\";\nimport { Matrix, Vector3 } from \"../Maths/math.vector.js\";\nimport { Scalar } from \"../Maths/math.scalar.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Ray } from \"../Culling/ray.js\";\nimport { Material } from \"../Materials/material.js\";\nimport { LensFlare } from \"./lensFlare.js\";\n\nimport \"../Shaders/lensFlare.fragment.js\";\nimport \"../Shaders/lensFlare.vertex.js\";\nimport { _WarnImport } from \"../Misc/devTools.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\n/**\n * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.\n * It is usually composed of several `lensFlare`.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare\n */\nexport class LensFlareSystem {\n /** Gets the scene */\n get scene() {\n return this._scene;\n }\n /**\n * Instantiates a lens flare system.\n * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.\n * It is usually composed of several `lensFlare`.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare\n * @param name Define the name of the lens flare system in the scene\n * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).\n * @param scene Define the scene the lens flare system belongs to\n */\n constructor(\n /**\n * Define the name of the lens flare system\n */\n name, emitter, scene) {\n this.name = name;\n /**\n * List of lens flares used in this system.\n */\n this.lensFlares = new Array();\n /**\n * Define a limit from the border the lens flare can be visible.\n */\n this.borderLimit = 300;\n /**\n * Define a viewport border we do not want to see the lens flare in.\n */\n this.viewportBorder = 0;\n /**\n * Restricts the rendering of the effect to only the camera rendering this layer mask.\n */\n this.layerMask = 0x0fffffff;\n this._vertexBuffers = {};\n this._isEnabled = true;\n this._scene = scene || EngineStore.LastCreatedScene;\n LensFlareSystem._SceneComponentInitialization(this._scene);\n this._emitter = emitter;\n this.id = name;\n scene.lensFlareSystems.push(this);\n this.meshesSelectionPredicate = (m) => (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && (m.layerMask & scene.activeCamera.layerMask) != 0);\n const engine = scene.getEngine();\n // VBO\n const vertices = [];\n vertices.push(1, 1);\n vertices.push(-1, 1);\n vertices.push(-1, -1);\n vertices.push(1, -1);\n this._vertexBuffers[VertexBuffer.PositionKind] = new VertexBuffer(engine, vertices, VertexBuffer.PositionKind, false, false, 2);\n // Indices\n this._createIndexBuffer();\n }\n _createIndexBuffer() {\n const indices = [];\n indices.push(0);\n indices.push(1);\n indices.push(2);\n indices.push(0);\n indices.push(2);\n indices.push(3);\n this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);\n }\n /**\n * Define if the lens flare system is enabled.\n */\n get isEnabled() {\n return this._isEnabled;\n }\n set isEnabled(value) {\n this._isEnabled = value;\n }\n /**\n * Get the scene the effects belongs to.\n * @returns the scene holding the lens flare system\n */\n getScene() {\n return this._scene;\n }\n /**\n * Get the emitter of the lens flare system.\n * It defines the source of the lens flares (it can be a camera, a light or a mesh).\n * @returns the emitter of the lens flare system\n */\n getEmitter() {\n return this._emitter;\n }\n /**\n * Set the emitter of the lens flare system.\n * It defines the source of the lens flares (it can be a camera, a light or a mesh).\n * @param newEmitter Define the new emitter of the system\n */\n setEmitter(newEmitter) {\n this._emitter = newEmitter;\n }\n /**\n * Get the lens flare system emitter position.\n * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).\n * @returns the position\n */\n getEmitterPosition() {\n return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;\n }\n /**\n * @internal\n */\n computeEffectivePosition(globalViewport) {\n let position = this.getEmitterPosition();\n position = Vector3.Project(position, Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);\n this._positionX = position.x;\n this._positionY = position.y;\n position = Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());\n if (this.viewportBorder > 0) {\n globalViewport.x -= this.viewportBorder;\n globalViewport.y -= this.viewportBorder;\n globalViewport.width += this.viewportBorder * 2;\n globalViewport.height += this.viewportBorder * 2;\n position.x += this.viewportBorder;\n position.y += this.viewportBorder;\n this._positionX += this.viewportBorder;\n this._positionY += this.viewportBorder;\n }\n const rhs = this._scene.useRightHandedSystem;\n const okZ = (position.z > 0 && !rhs) || (position.z < 0 && rhs);\n if (okZ) {\n if (this._positionX > globalViewport.x && this._positionX < globalViewport.x + globalViewport.width) {\n if (this._positionY > globalViewport.y && this._positionY < globalViewport.y + globalViewport.height) {\n return true;\n }\n }\n return true;\n }\n return false;\n }\n /** @internal */\n _isVisible() {\n if (!this._isEnabled || !this._scene.activeCamera) {\n return false;\n }\n const emitterPosition = this.getEmitterPosition();\n const direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);\n const distance = direction.length();\n direction.normalize();\n const ray = new Ray(this._scene.activeCamera.globalPosition, direction);\n const pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);\n return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;\n }\n /**\n * @internal\n */\n render() {\n if (!this._scene.activeCamera) {\n return false;\n }\n const engine = this._scene.getEngine();\n const viewport = this._scene.activeCamera.viewport;\n const globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));\n // Position\n if (!this.computeEffectivePosition(globalViewport)) {\n return false;\n }\n // Visibility\n if (!this._isVisible()) {\n return false;\n }\n // Intensity\n let awayX;\n let awayY;\n if (this._positionX < this.borderLimit + globalViewport.x) {\n awayX = this.borderLimit + globalViewport.x - this._positionX;\n }\n else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {\n awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;\n }\n else {\n awayX = 0;\n }\n if (this._positionY < this.borderLimit + globalViewport.y) {\n awayY = this.borderLimit + globalViewport.y - this._positionY;\n }\n else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {\n awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;\n }\n else {\n awayY = 0;\n }\n let away = awayX > awayY ? awayX : awayY;\n away -= this.viewportBorder;\n if (away > this.borderLimit) {\n away = this.borderLimit;\n }\n let intensity = 1.0 - Scalar.Clamp(away / this.borderLimit, 0, 1);\n if (intensity < 0) {\n return false;\n }\n if (intensity > 1.0) {\n intensity = 1.0;\n }\n if (this.viewportBorder > 0) {\n globalViewport.x += this.viewportBorder;\n globalViewport.y += this.viewportBorder;\n globalViewport.width -= this.viewportBorder * 2;\n globalViewport.height -= this.viewportBorder * 2;\n this._positionX -= this.viewportBorder;\n this._positionY -= this.viewportBorder;\n }\n // Position\n const centerX = globalViewport.x + globalViewport.width / 2;\n const centerY = globalViewport.y + globalViewport.height / 2;\n const distX = centerX - this._positionX;\n const distY = centerY - this._positionY;\n // Effects\n engine.setState(false);\n engine.setDepthBuffer(false);\n // Flares\n for (let index = 0; index < this.lensFlares.length; index++) {\n const flare = this.lensFlares[index];\n if (!flare._drawWrapper.effect.isReady() || (flare.texture && !flare.texture.isReady())) {\n continue;\n }\n engine.enableEffect(flare._drawWrapper);\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, flare._drawWrapper.effect);\n engine.setAlphaMode(flare.alphaMode);\n const x = centerX - distX * flare.position;\n const y = centerY - distY * flare.position;\n const cw = flare.size;\n const ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);\n const cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;\n const cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));\n const viewportMatrix = Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);\n flare._drawWrapper.effect.setMatrix(\"viewportMatrix\", viewportMatrix);\n // Texture\n flare._drawWrapper.effect.setTexture(\"textureSampler\", flare.texture);\n // Color\n flare._drawWrapper.effect.setFloat4(\"color\", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);\n // Draw order\n engine.drawElementsType(Material.TriangleFillMode, 0, 6);\n }\n engine.setDepthBuffer(true);\n engine.setAlphaMode(0);\n return true;\n }\n /**\n * Rebuilds the lens flare system\n */\n rebuild() {\n var _a;\n this._createIndexBuffer();\n for (const key in this._vertexBuffers) {\n (_a = this._vertexBuffers[key]) === null || _a === void 0 ? void 0 : _a._rebuild();\n }\n }\n /**\n * Dispose and release the lens flare with its associated resources.\n */\n dispose() {\n const vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];\n if (vertexBuffer) {\n vertexBuffer.dispose();\n this._vertexBuffers[VertexBuffer.PositionKind] = null;\n }\n if (this._indexBuffer) {\n this._scene.getEngine()._releaseBuffer(this._indexBuffer);\n this._indexBuffer = null;\n }\n while (this.lensFlares.length) {\n this.lensFlares[0].dispose();\n }\n // Remove from scene\n const index = this._scene.lensFlareSystems.indexOf(this);\n this._scene.lensFlareSystems.splice(index, 1);\n }\n /**\n * Parse a lens flare system from a JSON representation\n * @param parsedLensFlareSystem Define the JSON to parse\n * @param scene Define the scene the parsed system should be instantiated in\n * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures\n * @returns the parsed system\n */\n static Parse(parsedLensFlareSystem, scene, rootUrl) {\n const emitter = scene.getLastEntryById(parsedLensFlareSystem.emitterId);\n const name = parsedLensFlareSystem.name || \"lensFlareSystem#\" + parsedLensFlareSystem.emitterId;\n const lensFlareSystem = new LensFlareSystem(name, emitter, scene);\n lensFlareSystem.id = parsedLensFlareSystem.id || name;\n lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;\n for (let index = 0; index < parsedLensFlareSystem.flares.length; index++) {\n const parsedFlare = parsedLensFlareSystem.flares[index];\n LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : \"\", lensFlareSystem);\n }\n return lensFlareSystem;\n }\n /**\n * Serialize the current Lens Flare System into a JSON representation.\n * @returns the serialized JSON\n */\n serialize() {\n const serializationObject = {};\n serializationObject.id = this.id;\n serializationObject.name = this.name;\n serializationObject.emitterId = this.getEmitter().id;\n serializationObject.borderLimit = this.borderLimit;\n serializationObject.flares = [];\n for (let index = 0; index < this.lensFlares.length; index++) {\n const flare = this.lensFlares[index];\n serializationObject.flares.push({\n size: flare.size,\n position: flare.position,\n color: flare.color.asArray(),\n textureName: Tools.GetFilename(flare.texture ? flare.texture.name : \"\"),\n });\n }\n return serializationObject;\n }\n}\n/**\n * @internal\n */\nLensFlareSystem._SceneComponentInitialization = (_) => {\n throw _WarnImport(\"LensFlareSystemSceneComponent\");\n};\n//# sourceMappingURL=lensFlareSystem.js.map","import { Tools } from \"../Misc/tools.js\";\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { AbstractScene } from \"../abstractScene.js\";\nimport { LensFlareSystem } from \"./lensFlareSystem.js\";\n// Adds the parser to the scene parsers.\nAbstractScene.AddParser(SceneComponentConstants.NAME_LENSFLARESYSTEM, (parsedData, scene, container, rootUrl) => {\n // Lens flares\n if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {\n if (!container.lensFlareSystems) {\n container.lensFlareSystems = new Array();\n }\n for (let index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {\n const parsedLensFlareSystem = parsedData.lensFlareSystems[index];\n const lf = LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);\n container.lensFlareSystems.push(lf);\n }\n }\n});\nAbstractScene.prototype.getLensFlareSystemByName = function (name) {\n for (let index = 0; index < this.lensFlareSystems.length; index++) {\n if (this.lensFlareSystems[index].name === name) {\n return this.lensFlareSystems[index];\n }\n }\n return null;\n};\nAbstractScene.prototype.getLensFlareSystemById = function (id) {\n for (let index = 0; index < this.lensFlareSystems.length; index++) {\n if (this.lensFlareSystems[index].id === id) {\n return this.lensFlareSystems[index];\n }\n }\n return null;\n};\nAbstractScene.prototype.getLensFlareSystemByID = function (id) {\n return this.getLensFlareSystemById(id);\n};\nAbstractScene.prototype.removeLensFlareSystem = function (toRemove) {\n const index = this.lensFlareSystems.indexOf(toRemove);\n if (index !== -1) {\n this.lensFlareSystems.splice(index, 1);\n }\n return index;\n};\nAbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {\n this.lensFlareSystems.push(newLensFlareSystem);\n};\n/**\n * Defines the lens flare scene component responsible to manage any lens flares\n * in a given scene.\n */\nexport class LensFlareSystemSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpful to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_LENSFLARESYSTEM;\n this.scene = scene;\n scene.lensFlareSystems = new Array();\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n for (let index = 0; index < this.scene.lensFlareSystems.length; index++) {\n this.scene.lensFlareSystems[index].rebuild();\n }\n }\n /**\n * Adds all the elements from the container to the scene\n * @param container the container holding the elements\n */\n addFromContainer(container) {\n if (!container.lensFlareSystems) {\n return;\n }\n container.lensFlareSystems.forEach((o) => {\n this.scene.addLensFlareSystem(o);\n });\n }\n /**\n * Removes all the elements in the container from the scene\n * @param container contains the elements to remove\n * @param dispose if the removed element should be disposed (default: false)\n */\n removeFromContainer(container, dispose) {\n if (!container.lensFlareSystems) {\n return;\n }\n container.lensFlareSystems.forEach((o) => {\n this.scene.removeLensFlareSystem(o);\n if (dispose) {\n o.dispose();\n }\n });\n }\n /**\n * Serializes the component data to the specified json object\n * @param serializationObject The object to serialize to\n */\n serialize(serializationObject) {\n // Lens flares\n serializationObject.lensFlareSystems = [];\n const lensFlareSystems = this.scene.lensFlareSystems;\n for (const lensFlareSystem of lensFlareSystems) {\n serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());\n }\n }\n /**\n * Disposes the component and the associated resources.\n */\n dispose() {\n const lensFlareSystems = this.scene.lensFlareSystems;\n while (lensFlareSystems.length) {\n lensFlareSystems[0].dispose();\n }\n }\n _draw(camera) {\n // Lens flares\n if (this.scene.lensFlaresEnabled) {\n const lensFlareSystems = this.scene.lensFlareSystems;\n Tools.StartPerformanceCounter(\"Lens flares\", lensFlareSystems.length > 0);\n for (const lensFlareSystem of lensFlareSystems) {\n if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {\n lensFlareSystem.render();\n }\n }\n Tools.EndPerformanceCounter(\"Lens flares\", lensFlareSystems.length > 0);\n }\n }\n}\nLensFlareSystem._SceneComponentInitialization = (scene) => {\n let component = scene._getComponent(SceneComponentConstants.NAME_LENSFLARESYSTEM);\n if (!component) {\n component = new LensFlareSystemSceneComponent(scene);\n scene._addComponent(component);\n }\n};\n//# sourceMappingURL=lensFlareSystemSceneComponent.js.map","export * from \"./lensFlare.js\";\nexport * from \"./lensFlareSystem.js\";\nexport * from \"./lensFlareSystemSceneComponent.js\";\n//# sourceMappingURL=index.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"bayerDitherFunctions\";\nconst shader = `float bayerDither2(vec2 _P) {\rreturn mod(2.0*_P.y+_P.x+1.0,4.0);\r}\rfloat bayerDither4(vec2 _P) {\rvec2 P1=mod(_P,2.0); \rvec2 P2=floor(0.5*mod(_P,4.0)); \rreturn 4.0*bayerDither2(P1)+bayerDither2(P2);\r}\rfloat bayerDither8(vec2 _P) {\rvec2 P1=mod(_P,2.0); \rvec2 P2=floor(0.5 *mod(_P,4.0)); \rvec2 P4=floor(0.25*mod(_P,8.0)); \rreturn 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);\r}\r`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const bayerDitherFunctions = { name, shader };\n//# sourceMappingURL=bayerDitherFunctions.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nimport \"./packingFunctions.js\";\nimport \"./bayerDitherFunctions.js\";\nconst name = \"shadowMapFragmentExtraDeclaration\";\nconst shader = `#if SM_FLOAT==0\n#include\n#endif\n#if SM_SOFTTRANSPARENTSHADOW==1\n#include\nuniform float softTransparentShadowSM;\r#endif\nvarying float vDepthMetricSM;\r#if SM_USEDISTANCE==1\nuniform vec3 lightDataSM;\rvarying vec3 vPositionWSM;\r#endif\nuniform vec3 biasAndScaleSM;\runiform vec2 depthValuesSM;\r#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const shadowMapFragmentExtraDeclaration = { name, shader };\n//# sourceMappingURL=shadowMapFragmentExtraDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"shadowMapVertexNormalBias\";\nconst shader = `#if SM_NORMALBIAS==1\n#if SM_DIRECTIONINLIGHTDATA==1\nvec3 worldLightDirSM=normalize(-lightDataSM.xyz);\r#else\nvec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;\rvec3 worldLightDirSM=normalize(directionToLightSM);\r#endif\nfloat ndlSM=dot(vNormalW,worldLightDirSM);\rfloat sinNLSM=sqrt(1.0-ndlSM*ndlSM);\rfloat normalBiasSM=biasAndScaleSM.y*sinNLSM;\rworldPos.xyz-=vNormalW*normalBiasSM;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const shadowMapVertexNormalBias = { name, shader };\n//# sourceMappingURL=shadowMapVertexNormalBias.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"shadowMapVertexMetric\";\nconst shader = `#if SM_USEDISTANCE==1\nvPositionWSM=worldPos.xyz;\r#endif\n#if SM_DEPTHTEXTURE==1\n#ifdef IS_NDC_HALF_ZRANGE\n#define BIASFACTOR 0.5\n#else\n#define BIASFACTOR 1.0\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\r#else\ngl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\r#endif\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nzSM=gl_Position.z;\rgl_Position.z=0.0;\r#elif SM_USEDISTANCE==0\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\r#else\nvDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const shadowMapVertexMetric = { name, shader };\n//# sourceMappingURL=shadowMapVertexMetric.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"shadowMapFragment\";\nconst shader = `float depthSM=vDepthMetricSM;\r#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\n#if SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\r#else\n#ifdef USE_REVERSE_DEPTHBUFFER\ndepthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\r#else\ndepthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\r#endif\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_FragDepth=clamp(1.0-depthSM,0.0,1.0);\r#else\ngl_FragDepth=clamp(depthSM,0.0,1.0); \r#endif\n#elif SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\r#endif\n#if SM_ESM==1\ndepthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.);\r#endif\n#if SM_FLOAT==1\ngl_FragColor=vec4(depthSM,1.0,1.0,1.0);\r#else\ngl_FragColor=pack(depthSM);\r#endif\nreturn;`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const shadowMapFragment = { name, shader };\n//# sourceMappingURL=shadowMapFragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/shadowMapFragmentExtraDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneFragmentDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneFragment.js\";\nimport \"./ShadersInclude/shadowMapFragment.js\";\nconst name = \"shadowMapPixelShader\";\nconst shader = `#include\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;\runiform sampler2D diffuseSampler;\r#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\r{\r#include\n#ifdef ALPHATEXTURE\nfloat alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a;\r#ifdef ALPHATESTVALUE\nif (alphaFromAlphaTexture=softTransparentShadowSM*alphaFromAlphaTexture) discard;\r#else\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM) discard;\r#endif\n#endif\n#include\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const shadowMapPixelShader = { name, shader };\n//# sourceMappingURL=shadowMap.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"sceneVertexDeclaration\";\nconst shader = `uniform mat4 viewProjection;\r#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\r#endif\nuniform mat4 view;\runiform mat4 projection;\runiform vec4 vEyePosition;\r`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const sceneVertexDeclaration = { name, shader };\n//# sourceMappingURL=sceneVertexDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"meshVertexDeclaration\";\nconst shader = `uniform mat4 world;\runiform float visibility;\r`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const meshVertexDeclaration = { name, shader };\n//# sourceMappingURL=meshVertexDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nimport \"./sceneVertexDeclaration.js\";\nimport \"./meshVertexDeclaration.js\";\nconst name = \"shadowMapVertexDeclaration\";\nconst shader = `#include\n#include\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const shadowMapVertexDeclaration = { name, shader };\n//# sourceMappingURL=shadowMapVertexDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nimport \"./sceneUboDeclaration.js\";\nimport \"./meshUboDeclaration.js\";\nconst name = \"shadowMapUboDeclaration\";\nconst shader = `layout(std140,column_major) uniform;\r#include\n#include\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const shadowMapUboDeclaration = { name, shader };\n//# sourceMappingURL=shadowMapUboDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"shadowMapVertexExtraDeclaration\";\nconst shader = `#if SM_NORMALBIAS==1\nuniform vec3 lightDataSM;\r#endif\nuniform vec3 biasAndScaleSM;\runiform vec2 depthValuesSM;\rvarying float vDepthMetricSM;\r#if SM_USEDISTANCE==1\nvarying vec3 vPositionWSM;\r#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const shadowMapVertexExtraDeclaration = { name, shader };\n//# sourceMappingURL=shadowMapVertexExtraDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/bonesDeclaration.js\";\nimport \"./ShadersInclude/bakedVertexAnimationDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexGlobalDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexDeclaration.js\";\nimport \"./ShadersInclude/helperFunctions.js\";\nimport \"./ShadersInclude/shadowMapVertexDeclaration.js\";\nimport \"./ShadersInclude/shadowMapUboDeclaration.js\";\nimport \"./ShadersInclude/shadowMapVertexExtraDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneVertexDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexGlobal.js\";\nimport \"./ShadersInclude/morphTargetsVertex.js\";\nimport \"./ShadersInclude/instancesVertex.js\";\nimport \"./ShadersInclude/bonesVertex.js\";\nimport \"./ShadersInclude/bakedVertexAnimation.js\";\nimport \"./ShadersInclude/shadowMapVertexNormalBias.js\";\nimport \"./ShadersInclude/shadowMapVertexMetric.js\";\nimport \"./ShadersInclude/clipPlaneVertex.js\";\nconst name = \"shadowMapVertexShader\";\nconst shader = `attribute vec3 position;\r#ifdef NORMAL\nattribute vec3 normal;\r#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef INSTANCES\nattribute vec4 world0;\rattribute vec4 world1;\rattribute vec4 world2;\rattribute vec4 world3;\r#endif\n#include\n#include<__decl__shadowMapVertex>\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;\runiform mat4 diffuseMatrix;\r#ifdef UV1\nattribute vec2 uv;\r#endif\n#ifdef UV2\nattribute vec2 uv2;\r#endif\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\r{\rvec3 positionUpdated=position;\r#ifdef UV1\nvec2 uvUpdated=uv;\r#endif\n#ifdef NORMAL\nvec3 normalUpdated=normal;\r#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\r#ifdef NORMAL\nmat3 normWorldSM=mat3(finalWorld);\r#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));\rvNormalW=normalize(normWorldSM*vNormalW);\r#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\r#endif\nvec3 vNormalW=normalize(normWorldSM*normalUpdated);\r#endif\n#endif\n#include\ngl_Position=viewProjection*worldPos;\r#include\n#ifdef ALPHATEXTURE\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\r#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\r#endif\n#endif\n#include\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const shadowMapVertexShader = { name, shader };\n//# sourceMappingURL=shadowMap.vertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"depthBoxBlurPixelShader\";\nconst shader = `varying vec2 vUV;\runiform sampler2D textureSampler;\runiform vec2 screenSize;\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\r{\rvec4 colorDepth=vec4(0.0);\rfor (int x=-OFFSET; x<=OFFSET; x++)\rfor (int y=-OFFSET; y<=OFFSET; y++)\rcolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\rgl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const depthBoxBlurPixelShader = { name, shader };\n//# sourceMappingURL=depthBoxBlur.fragment.js.map","import { Matrix, Vector3, Vector2 } from \"../../Maths/math.vector.js\";\nimport { Color4 } from \"../../Maths/math.color.js\";\nimport { VertexBuffer } from \"../../Buffers/buffer.js\";\nimport { Light } from \"../../Lights/light.js\";\nimport { MaterialHelper } from \"../../Materials/materialHelper.js\";\nimport { Texture } from \"../../Materials/Textures/texture.js\";\nimport { RenderTargetTexture } from \"../../Materials/Textures/renderTargetTexture.js\";\nimport { PostProcess } from \"../../PostProcesses/postProcess.js\";\nimport { BlurPostProcess } from \"../../PostProcesses/blurPostProcess.js\";\n\nimport { Observable } from \"../../Misc/observable.js\";\nimport { _WarnImport } from \"../../Misc/devTools.js\";\nimport { EffectFallbacks } from \"../../Materials/effectFallbacks.js\";\nimport { RenderingManager } from \"../../Rendering/renderingManager.js\";\nimport { DrawWrapper } from \"../../Materials/drawWrapper.js\";\nimport \"../../Shaders/shadowMap.fragment.js\";\nimport \"../../Shaders/shadowMap.vertex.js\";\nimport \"../../Shaders/depthBoxBlur.fragment.js\";\nimport \"../../Shaders/ShadersInclude/shadowMapFragmentSoftTransparentShadow.js\";\nimport { addClipPlaneUniforms, bindClipPlane, prepareStringDefinesForClipPlanes } from \"../../Materials/clipPlaneMaterialHelper.js\";\n/**\n * Default implementation IShadowGenerator.\n * This is the main object responsible of generating shadows in the framework.\n * Documentation: https://doc.babylonjs.com/features/featuresDeepDive/lights/shadows\n */\nexport class ShadowGenerator {\n /**\n * Gets the bias: offset applied on the depth preventing acnea (in light direction).\n */\n get bias() {\n return this._bias;\n }\n /**\n * Sets the bias: offset applied on the depth preventing acnea (in light direction).\n */\n set bias(bias) {\n this._bias = bias;\n }\n /**\n * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportional to the light/normal angle).\n */\n get normalBias() {\n return this._normalBias;\n }\n /**\n * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportional to the light/normal angle).\n */\n set normalBias(normalBias) {\n this._normalBias = normalBias;\n }\n /**\n * Gets the blur box offset: offset applied during the blur pass.\n * Only useful if useKernelBlur = false\n */\n get blurBoxOffset() {\n return this._blurBoxOffset;\n }\n /**\n * Sets the blur box offset: offset applied during the blur pass.\n * Only useful if useKernelBlur = false\n */\n set blurBoxOffset(value) {\n if (this._blurBoxOffset === value) {\n return;\n }\n this._blurBoxOffset = value;\n this._disposeBlurPostProcesses();\n }\n /**\n * Gets the blur scale: scale of the blurred texture compared to the main shadow map.\n * 2 means half of the size.\n */\n get blurScale() {\n return this._blurScale;\n }\n /**\n * Sets the blur scale: scale of the blurred texture compared to the main shadow map.\n * 2 means half of the size.\n */\n set blurScale(value) {\n if (this._blurScale === value) {\n return;\n }\n this._blurScale = value;\n this._disposeBlurPostProcesses();\n }\n /**\n * Gets the blur kernel: kernel size of the blur pass.\n * Only useful if useKernelBlur = true\n */\n get blurKernel() {\n return this._blurKernel;\n }\n /**\n * Sets the blur kernel: kernel size of the blur pass.\n * Only useful if useKernelBlur = true\n */\n set blurKernel(value) {\n if (this._blurKernel === value) {\n return;\n }\n this._blurKernel = value;\n this._disposeBlurPostProcesses();\n }\n /**\n * Gets whether the blur pass is a kernel blur (if true) or box blur.\n * Only useful in filtered mode (useBlurExponentialShadowMap...)\n */\n get useKernelBlur() {\n return this._useKernelBlur;\n }\n /**\n * Sets whether the blur pass is a kernel blur (if true) or box blur.\n * Only useful in filtered mode (useBlurExponentialShadowMap...)\n */\n set useKernelBlur(value) {\n if (this._useKernelBlur === value) {\n return;\n }\n this._useKernelBlur = value;\n this._disposeBlurPostProcesses();\n }\n /**\n * Gets the depth scale used in ESM mode.\n */\n get depthScale() {\n return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();\n }\n /**\n * Sets the depth scale used in ESM mode.\n * This can override the scale stored on the light.\n */\n set depthScale(value) {\n this._depthScale = value;\n }\n _validateFilter(filter) {\n return filter;\n }\n /**\n * Gets the current mode of the shadow generator (normal, PCF, ESM...).\n * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE\n */\n get filter() {\n return this._filter;\n }\n /**\n * Sets the current mode of the shadow generator (normal, PCF, ESM...).\n * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE\n */\n set filter(value) {\n value = this._validateFilter(value);\n // Blurring the cubemap is going to be too expensive. Reverting to unblurred version\n if (this._light.needCube()) {\n if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {\n this.useExponentialShadowMap = true;\n return;\n }\n else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {\n this.useCloseExponentialShadowMap = true;\n return;\n }\n // PCF on cubemap would also be expensive\n else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {\n this.usePoissonSampling = true;\n return;\n }\n }\n // Weblg1 fallback for PCF.\n if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {\n if (!this._scene.getEngine()._features.supportShadowSamplers) {\n this.usePoissonSampling = true;\n return;\n }\n }\n if (this._filter === value) {\n return;\n }\n this._filter = value;\n this._disposeBlurPostProcesses();\n this._applyFilterValues();\n this._light._markMeshesAsLightDirty();\n }\n /**\n * Gets if the current filter is set to Poisson Sampling.\n */\n get usePoissonSampling() {\n return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;\n }\n /**\n * Sets the current filter to Poisson Sampling.\n */\n set usePoissonSampling(value) {\n const filter = this._validateFilter(ShadowGenerator.FILTER_POISSONSAMPLING);\n if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {\n return;\n }\n this.filter = value ? filter : ShadowGenerator.FILTER_NONE;\n }\n /**\n * Gets if the current filter is set to ESM.\n */\n get useExponentialShadowMap() {\n return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;\n }\n /**\n * Sets the current filter is to ESM.\n */\n set useExponentialShadowMap(value) {\n const filter = this._validateFilter(ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP);\n if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {\n return;\n }\n this.filter = value ? filter : ShadowGenerator.FILTER_NONE;\n }\n /**\n * Gets if the current filter is set to filtered ESM.\n */\n get useBlurExponentialShadowMap() {\n return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;\n }\n /**\n * Gets if the current filter is set to filtered ESM.\n */\n set useBlurExponentialShadowMap(value) {\n const filter = this._validateFilter(ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP);\n if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {\n return;\n }\n this.filter = value ? filter : ShadowGenerator.FILTER_NONE;\n }\n /**\n * Gets if the current filter is set to \"close ESM\" (using the inverse of the\n * exponential to prevent steep falloff artifacts).\n */\n get useCloseExponentialShadowMap() {\n return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;\n }\n /**\n * Sets the current filter to \"close ESM\" (using the inverse of the\n * exponential to prevent steep falloff artifacts).\n */\n set useCloseExponentialShadowMap(value) {\n const filter = this._validateFilter(ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP);\n if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {\n return;\n }\n this.filter = value ? filter : ShadowGenerator.FILTER_NONE;\n }\n /**\n * Gets if the current filter is set to filtered \"close ESM\" (using the inverse of the\n * exponential to prevent steep falloff artifacts).\n */\n get useBlurCloseExponentialShadowMap() {\n return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;\n }\n /**\n * Sets the current filter to filtered \"close ESM\" (using the inverse of the\n * exponential to prevent steep falloff artifacts).\n */\n set useBlurCloseExponentialShadowMap(value) {\n const filter = this._validateFilter(ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);\n if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {\n return;\n }\n this.filter = value ? filter : ShadowGenerator.FILTER_NONE;\n }\n /**\n * Gets if the current filter is set to \"PCF\" (percentage closer filtering).\n */\n get usePercentageCloserFiltering() {\n return this.filter === ShadowGenerator.FILTER_PCF;\n }\n /**\n * Sets the current filter to \"PCF\" (percentage closer filtering).\n */\n set usePercentageCloserFiltering(value) {\n const filter = this._validateFilter(ShadowGenerator.FILTER_PCF);\n if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {\n return;\n }\n this.filter = value ? filter : ShadowGenerator.FILTER_NONE;\n }\n /**\n * Gets the PCF or PCSS Quality.\n * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.\n */\n get filteringQuality() {\n return this._filteringQuality;\n }\n /**\n * Sets the PCF or PCSS Quality.\n * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.\n */\n set filteringQuality(filteringQuality) {\n if (this._filteringQuality === filteringQuality) {\n return;\n }\n this._filteringQuality = filteringQuality;\n this._disposeBlurPostProcesses();\n this._applyFilterValues();\n this._light._markMeshesAsLightDirty();\n }\n /**\n * Gets if the current filter is set to \"PCSS\" (contact hardening).\n */\n get useContactHardeningShadow() {\n return this.filter === ShadowGenerator.FILTER_PCSS;\n }\n /**\n * Sets the current filter to \"PCSS\" (contact hardening).\n */\n set useContactHardeningShadow(value) {\n const filter = this._validateFilter(ShadowGenerator.FILTER_PCSS);\n if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {\n return;\n }\n this.filter = value ? filter : ShadowGenerator.FILTER_NONE;\n }\n /**\n * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.\n * Using a ratio helps keeping shape stability independently of the map size.\n *\n * It does not account for the light projection as it was having too much\n * instability during the light setup or during light position changes.\n *\n * Only valid if useContactHardeningShadow is true.\n */\n get contactHardeningLightSizeUVRatio() {\n return this._contactHardeningLightSizeUVRatio;\n }\n /**\n * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.\n * Using a ratio helps keeping shape stability independently of the map size.\n *\n * It does not account for the light projection as it was having too much\n * instability during the light setup or during light position changes.\n *\n * Only valid if useContactHardeningShadow is true.\n */\n set contactHardeningLightSizeUVRatio(contactHardeningLightSizeUVRatio) {\n this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;\n }\n /** Gets or sets the actual darkness of a shadow */\n get darkness() {\n return this._darkness;\n }\n set darkness(value) {\n this.setDarkness(value);\n }\n /**\n * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.\n * 0 means strongest and 1 would means no shadow.\n * @returns the darkness.\n */\n getDarkness() {\n return this._darkness;\n }\n /**\n * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.\n * @param darkness The darkness value 0 means strongest and 1 would means no shadow.\n * @returns the shadow generator allowing fluent coding.\n */\n setDarkness(darkness) {\n if (darkness >= 1.0) {\n this._darkness = 1.0;\n }\n else if (darkness <= 0.0) {\n this._darkness = 0.0;\n }\n else {\n this._darkness = darkness;\n }\n return this;\n }\n /** Gets or sets the ability to have transparent shadow */\n get transparencyShadow() {\n return this._transparencyShadow;\n }\n set transparencyShadow(value) {\n this.setTransparencyShadow(value);\n }\n /**\n * Sets the ability to have transparent shadow (boolean).\n * @param transparent True if transparent else False\n * @returns the shadow generator allowing fluent coding\n */\n setTransparencyShadow(transparent) {\n this._transparencyShadow = transparent;\n return this;\n }\n /**\n * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).\n * @returns The render target texture if present otherwise, null\n */\n getShadowMap() {\n return this._shadowMap;\n }\n /**\n * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).\n * @returns The render target texture if the shadow map is present otherwise, null\n */\n getShadowMapForRendering() {\n if (this._shadowMap2) {\n return this._shadowMap2;\n }\n return this._shadowMap;\n }\n /**\n * Gets the class name of that object\n * @returns \"ShadowGenerator\"\n */\n getClassName() {\n return ShadowGenerator.CLASSNAME;\n }\n /**\n * Helper function to add a mesh and its descendants to the list of shadow casters.\n * @param mesh Mesh to add\n * @param includeDescendants boolean indicating if the descendants should be added. Default to true\n * @returns the Shadow Generator itself\n */\n addShadowCaster(mesh, includeDescendants = true) {\n if (!this._shadowMap) {\n return this;\n }\n if (!this._shadowMap.renderList) {\n this._shadowMap.renderList = [];\n }\n if (this._shadowMap.renderList.indexOf(mesh) === -1) {\n this._shadowMap.renderList.push(mesh);\n }\n if (includeDescendants) {\n for (const childMesh of mesh.getChildMeshes()) {\n if (this._shadowMap.renderList.indexOf(childMesh) === -1) {\n this._shadowMap.renderList.push(childMesh);\n }\n }\n }\n return this;\n }\n /**\n * Helper function to remove a mesh and its descendants from the list of shadow casters\n * @param mesh Mesh to remove\n * @param includeDescendants boolean indicating if the descendants should be removed. Default to true\n * @returns the Shadow Generator itself\n */\n removeShadowCaster(mesh, includeDescendants = true) {\n if (!this._shadowMap || !this._shadowMap.renderList) {\n return this;\n }\n const index = this._shadowMap.renderList.indexOf(mesh);\n if (index !== -1) {\n this._shadowMap.renderList.splice(index, 1);\n }\n if (includeDescendants) {\n for (const child of mesh.getChildren()) {\n this.removeShadowCaster(child);\n }\n }\n return this;\n }\n /**\n * Returns the associated light object.\n * @returns the light generating the shadow\n */\n getLight() {\n return this._light;\n }\n _getCamera() {\n var _a;\n return (_a = this._camera) !== null && _a !== void 0 ? _a : this._scene.activeCamera;\n }\n /**\n * Gets or sets the size of the texture what stores the shadows\n */\n get mapSize() {\n return this._mapSize;\n }\n set mapSize(size) {\n this._mapSize = size;\n this._light._markMeshesAsLightDirty();\n this.recreateShadowMap();\n }\n /**\n * Creates a ShadowGenerator object.\n * A ShadowGenerator is the required tool to use the shadows.\n * Each light casting shadows needs to use its own ShadowGenerator.\n * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/shadows\n * @param mapSize The size of the texture what stores the shadows. Example : 1024.\n * @param light The light object generating the shadows.\n * @param usefullFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.\n * @param camera Camera associated with this shadow generator (default: null). If null, takes the scene active camera at the time we need to access it\n */\n constructor(mapSize, light, usefullFloatFirst, camera) {\n /**\n * Observable triggered before the shadow is rendered. Can be used to update internal effect state\n */\n this.onBeforeShadowMapRenderObservable = new Observable();\n /**\n * Observable triggered after the shadow is rendered. Can be used to restore internal effect state\n */\n this.onAfterShadowMapRenderObservable = new Observable();\n /**\n * Observable triggered before a mesh is rendered in the shadow map.\n * Can be used to update internal effect state (that you can get from the onBeforeShadowMapRenderObservable)\n */\n this.onBeforeShadowMapRenderMeshObservable = new Observable();\n /**\n * Observable triggered after a mesh is rendered in the shadow map.\n * Can be used to update internal effect state (that you can get from the onAfterShadowMapRenderObservable)\n */\n this.onAfterShadowMapRenderMeshObservable = new Observable();\n this._bias = 0.00005;\n this._normalBias = 0;\n this._blurBoxOffset = 1;\n this._blurScale = 2;\n this._blurKernel = 1;\n this._useKernelBlur = false;\n this._filter = ShadowGenerator.FILTER_NONE;\n this._filteringQuality = ShadowGenerator.QUALITY_HIGH;\n this._contactHardeningLightSizeUVRatio = 0.1;\n this._darkness = 0;\n this._transparencyShadow = false;\n /**\n * Enables or disables shadows with varying strength based on the transparency\n * When it is enabled, the strength of the shadow is taken equal to mesh.visibility\n * If you enabled an alpha texture on your material, the alpha value red from the texture is also combined to compute the strength:\n * mesh.visibility * alphaTexture.a\n * The texture used is the diffuse by default, but it can be set to the opacity by setting useOpacityTextureForTransparentShadow\n * Note that by definition transparencyShadow must be set to true for enableSoftTransparentShadow to work!\n */\n this.enableSoftTransparentShadow = false;\n /**\n * If this is true, use the opacity texture's alpha channel for transparent shadows instead of the diffuse one\n */\n this.useOpacityTextureForTransparentShadow = false;\n /**\n * Controls the extent to which the shadows fade out at the edge of the frustum\n */\n this.frustumEdgeFalloff = 0;\n /**\n * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.\n * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.\n * It might on the other hand introduce peter panning.\n */\n this.forceBackFacesOnly = false;\n this._lightDirection = Vector3.Zero();\n this._viewMatrix = Matrix.Zero();\n this._projectionMatrix = Matrix.Zero();\n this._transformMatrix = Matrix.Zero();\n this._cachedPosition = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._cachedDirection = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._currentFaceIndex = 0;\n this._currentFaceIndexCache = 0;\n this._defaultTextureMatrix = Matrix.Identity();\n this._mapSize = mapSize;\n this._light = light;\n this._scene = light.getScene();\n this._camera = camera !== null && camera !== void 0 ? camera : null;\n let shadowGenerators = light._shadowGenerators;\n if (!shadowGenerators) {\n shadowGenerators = light._shadowGenerators = new Map();\n }\n shadowGenerators.set(this._camera, this);\n this.id = light.id;\n this._useUBO = this._scene.getEngine().supportsUniformBuffers;\n if (this._useUBO) {\n this._sceneUBOs = [];\n this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light \"${this._light.name}\")`));\n }\n ShadowGenerator._SceneComponentInitialization(this._scene);\n // Texture type fallback from float to int if not supported.\n const caps = this._scene.getEngine().getCaps();\n if (!usefullFloatFirst) {\n if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {\n this._textureType = 2;\n }\n else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {\n this._textureType = 1;\n }\n else {\n this._textureType = 0;\n }\n }\n else {\n if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {\n this._textureType = 1;\n }\n else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {\n this._textureType = 2;\n }\n else {\n this._textureType = 0;\n }\n }\n this._initializeGenerator();\n this._applyFilterValues();\n }\n _initializeGenerator() {\n this._light._markMeshesAsLightDirty();\n this._initializeShadowMap();\n }\n _createTargetRenderTexture() {\n const engine = this._scene.getEngine();\n if (engine._features.supportDepthStencilTexture) {\n this._shadowMap = new RenderTargetTexture(this._light.name + \"_shadowMap\", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);\n this._shadowMap.createDepthStencilTexture(engine.useReverseDepthBuffer ? 516 : 513, true);\n }\n else {\n this._shadowMap = new RenderTargetTexture(this._light.name + \"_shadowMap\", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());\n }\n this._shadowMap.noPrePassRenderer = true;\n }\n _initializeShadowMap() {\n this._createTargetRenderTexture();\n if (this._shadowMap === null) {\n return;\n }\n this._shadowMap.wrapU = Texture.CLAMP_ADDRESSMODE;\n this._shadowMap.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._shadowMap.anisotropicFilteringLevel = 1;\n this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);\n this._shadowMap.renderParticles = false;\n this._shadowMap.ignoreCameraViewport = true;\n if (this._storedUniqueId) {\n this._shadowMap.uniqueId = this._storedUniqueId;\n }\n // Custom render function.\n this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);\n // Force the mesh is ready function to true as we are double checking it\n // in the custom render function. Also it prevents side effects and useless\n // shader variations in DEPTHPREPASS mode.\n this._shadowMap.customIsReadyFunction = () => {\n return true;\n };\n const engine = this._scene.getEngine();\n this._shadowMap.onBeforeBindObservable.add(() => {\n var _a;\n this._currentSceneUBO = this._scene.getSceneUniformBuffer();\n (_a = engine._debugPushGroup) === null || _a === void 0 ? void 0 : _a.call(engine, `shadow map generation for pass id ${engine.currentRenderPassId}`, 1);\n });\n // Record Face Index before render.\n this._shadowMap.onBeforeRenderObservable.add((faceIndex) => {\n if (this._sceneUBOs) {\n this._scene.setSceneUniformBuffer(this._sceneUBOs[0]);\n }\n this._currentFaceIndex = faceIndex;\n if (this._filter === ShadowGenerator.FILTER_PCF) {\n engine.setColorWrite(false);\n }\n this.getTransformMatrix(); // generate the view/projection matrix\n this._scene.setTransformMatrix(this._viewMatrix, this._projectionMatrix);\n if (this._useUBO) {\n this._scene.getSceneUniformBuffer().unbindEffect();\n this._scene.finalizeSceneUbo();\n }\n });\n // Blur if required after render.\n this._shadowMap.onAfterUnbindObservable.add(() => {\n var _a, _b;\n if (this._sceneUBOs) {\n this._scene.setSceneUniformBuffer(this._currentSceneUBO);\n }\n this._scene.updateTransformMatrix(); // restore the view/projection matrices of the active camera\n if (this._filter === ShadowGenerator.FILTER_PCF) {\n engine.setColorWrite(true);\n }\n if (!this.useBlurExponentialShadowMap && !this.useBlurCloseExponentialShadowMap) {\n (_a = engine._debugPopGroup) === null || _a === void 0 ? void 0 : _a.call(engine, 1);\n return;\n }\n const shadowMap = this.getShadowMapForRendering();\n if (shadowMap) {\n this._scene.postProcessManager.directRender(this._blurPostProcesses, shadowMap.renderTarget, true);\n engine.unBindFramebuffer(shadowMap.renderTarget, true);\n (_b = engine._debugPopGroup) === null || _b === void 0 ? void 0 : _b.call(engine, 1);\n }\n });\n // Clear according to the chosen filter.\n const clearZero = new Color4(0, 0, 0, 0);\n const clearOne = new Color4(1.0, 1.0, 1.0, 1.0);\n this._shadowMap.onClearObservable.add((engine) => {\n if (this._filter === ShadowGenerator.FILTER_PCF) {\n engine.clear(clearOne, false, true, false);\n }\n else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {\n engine.clear(clearZero, true, true, false);\n }\n else {\n engine.clear(clearOne, true, true, false);\n }\n });\n // Recreate on resize.\n this._shadowMap.onResizeObservable.add((rtt) => {\n this._storedUniqueId = this._shadowMap.uniqueId;\n this._mapSize = rtt.getRenderSize();\n this._light._markMeshesAsLightDirty();\n this.recreateShadowMap();\n });\n // Ensures rendering groupids do not erase the depth buffer\n // or we would lose the shadows information.\n for (let i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {\n this._shadowMap.setRenderingAutoClearDepthStencil(i, false);\n }\n }\n _initializeBlurRTTAndPostProcesses() {\n const engine = this._scene.getEngine();\n const targetSize = this._mapSize / this.blurScale;\n if (!this.useKernelBlur || this.blurScale !== 1.0) {\n this._shadowMap2 = new RenderTargetTexture(this._light.name + \"_shadowMap2\", targetSize, this._scene, false, true, this._textureType, undefined, undefined, false);\n this._shadowMap2.wrapU = Texture.CLAMP_ADDRESSMODE;\n this._shadowMap2.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._shadowMap2.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);\n }\n if (this.useKernelBlur) {\n this._kernelBlurXPostprocess = new BlurPostProcess(this._light.name + \"KernelBlurX\", new Vector2(1, 0), this.blurKernel, 1.0, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);\n this._kernelBlurXPostprocess.width = targetSize;\n this._kernelBlurXPostprocess.height = targetSize;\n this._kernelBlurXPostprocess.externalTextureSamplerBinding = true;\n this._kernelBlurXPostprocess.onApplyObservable.add((effect) => {\n effect.setTexture(\"textureSampler\", this._shadowMap);\n });\n this._kernelBlurYPostprocess = new BlurPostProcess(this._light.name + \"KernelBlurY\", new Vector2(0, 1), this.blurKernel, 1.0, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);\n this._kernelBlurXPostprocess.autoClear = false;\n this._kernelBlurYPostprocess.autoClear = false;\n if (this._textureType === 0) {\n this._kernelBlurXPostprocess.packedFloat = true;\n this._kernelBlurYPostprocess.packedFloat = true;\n }\n this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];\n }\n else {\n this._boxBlurPostprocess = new PostProcess(this._light.name + \"DepthBoxBlur\", \"depthBoxBlur\", [\"screenSize\", \"boxOffset\"], [], 1.0, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, \"#define OFFSET \" + this._blurBoxOffset, this._textureType);\n this._boxBlurPostprocess.externalTextureSamplerBinding = true;\n this._boxBlurPostprocess.onApplyObservable.add((effect) => {\n effect.setFloat2(\"screenSize\", targetSize, targetSize);\n effect.setTexture(\"textureSampler\", this._shadowMap);\n });\n this._boxBlurPostprocess.autoClear = false;\n this._blurPostProcesses = [this._boxBlurPostprocess];\n }\n }\n _renderForShadowMap(opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {\n let index;\n if (depthOnlySubMeshes.length) {\n for (index = 0; index < depthOnlySubMeshes.length; index++) {\n this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);\n }\n }\n for (index = 0; index < opaqueSubMeshes.length; index++) {\n this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);\n }\n for (index = 0; index < alphaTestSubMeshes.length; index++) {\n this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);\n }\n if (this._transparencyShadow) {\n for (index = 0; index < transparentSubMeshes.length; index++) {\n this._renderSubMeshForShadowMap(transparentSubMeshes.data[index], true);\n }\n }\n else {\n for (index = 0; index < transparentSubMeshes.length; index++) {\n transparentSubMeshes.data[index].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate = false;\n }\n }\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _bindCustomEffectForRenderSubMeshForShadowMap(subMesh, effect, mesh) {\n effect.setMatrix(\"viewProjection\", this.getTransformMatrix());\n }\n _renderSubMeshForShadowMap(subMesh, isTransparent = false) {\n var _a, _b;\n const renderingMesh = subMesh.getRenderingMesh();\n const effectiveMesh = subMesh.getEffectiveMesh();\n const scene = this._scene;\n const engine = scene.getEngine();\n const material = subMesh.getMaterial();\n effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;\n if (!material || subMesh.verticesCount === 0 || subMesh._renderId === scene.getRenderId()) {\n return;\n }\n // Culling\n const detNeg = effectiveMesh._getWorldMatrixDeterminant() < 0;\n let sideOrientation = (_a = renderingMesh.overrideMaterialSideOrientation) !== null && _a !== void 0 ? _a : material.sideOrientation;\n if (detNeg) {\n sideOrientation =\n sideOrientation === 0 ? 1 : 0;\n }\n const reverseSideOrientation = sideOrientation === 0;\n engine.setState(material.backFaceCulling, undefined, undefined, reverseSideOrientation, material.cullBackFaces);\n // Managing instances\n const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());\n if (batch.mustReturn) {\n return;\n }\n const hardwareInstancedRendering = engine.getCaps().instancedArrays &&\n ((batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined) || renderingMesh.hasThinInstances);\n if (this.customAllowRendering && !this.customAllowRendering(subMesh)) {\n return;\n }\n if (this.isReady(subMesh, hardwareInstancedRendering, isTransparent)) {\n subMesh._renderId = scene.getRenderId();\n const shadowDepthWrapper = material.shadowDepthWrapper;\n const drawWrapper = (_b = shadowDepthWrapper === null || shadowDepthWrapper === void 0 ? void 0 : shadowDepthWrapper.getEffect(subMesh, this, engine.currentRenderPassId)) !== null && _b !== void 0 ? _b : subMesh._getDrawWrapper();\n const effect = DrawWrapper.GetEffect(drawWrapper);\n engine.enableEffect(drawWrapper);\n if (!hardwareInstancedRendering) {\n renderingMesh._bind(subMesh, effect, material.fillMode);\n }\n this.getTransformMatrix(); // make sure _cachedDirection et _cachedPosition are up to date\n effect.setFloat3(\"biasAndScaleSM\", this.bias, this.normalBias, this.depthScale);\n if (this.getLight().getTypeID() === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {\n effect.setVector3(\"lightDataSM\", this._cachedDirection);\n }\n else {\n effect.setVector3(\"lightDataSM\", this._cachedPosition);\n }\n const camera = this._getCamera();\n if (camera) {\n effect.setFloat2(\"depthValuesSM\", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera));\n }\n if (isTransparent && this.enableSoftTransparentShadow) {\n effect.setFloat(\"softTransparentShadowSM\", effectiveMesh.visibility * material.alpha);\n }\n if (shadowDepthWrapper) {\n subMesh._setMainDrawWrapperOverride(drawWrapper);\n if (shadowDepthWrapper.standalone) {\n shadowDepthWrapper.baseMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), renderingMesh, subMesh);\n }\n else {\n material.bindForSubMesh(effectiveMesh.getWorldMatrix(), renderingMesh, subMesh);\n }\n subMesh._setMainDrawWrapperOverride(null);\n }\n else {\n // Alpha test\n if (this._opacityTexture) {\n effect.setTexture(\"diffuseSampler\", this._opacityTexture);\n effect.setMatrix(\"diffuseMatrix\", this._opacityTexture.getTextureMatrix() || this._defaultTextureMatrix);\n }\n // Bones\n if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) {\n const skeleton = renderingMesh.skeleton;\n if (skeleton.isUsingTextureForMatrices) {\n const boneTexture = skeleton.getTransformMatrixTexture(renderingMesh);\n if (!boneTexture) {\n return;\n }\n effect.setTexture(\"boneSampler\", boneTexture);\n effect.setFloat(\"boneTextureWidth\", 4.0 * (skeleton.bones.length + 1));\n }\n else {\n effect.setMatrices(\"mBones\", skeleton.getTransformMatrices(renderingMesh));\n }\n }\n // Morph targets\n MaterialHelper.BindMorphTargetParameters(renderingMesh, effect);\n if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) {\n renderingMesh.morphTargetManager._bind(effect);\n }\n // Clip planes\n bindClipPlane(effect, material, scene);\n }\n if (!this._useUBO && !shadowDepthWrapper) {\n this._bindCustomEffectForRenderSubMeshForShadowMap(subMesh, effect, effectiveMesh);\n }\n MaterialHelper.BindSceneUniformBuffer(effect, this._scene.getSceneUniformBuffer());\n this._scene.getSceneUniformBuffer().bindUniformBuffer();\n const world = effectiveMesh.getWorldMatrix();\n // In the non hardware instanced mode, the Mesh ubo update is done by the callback passed to renderingMesh._processRendering (see below)\n if (hardwareInstancedRendering) {\n effectiveMesh.getMeshUniformBuffer().bindToEffect(effect, \"Mesh\");\n effectiveMesh.transferToEffect(world);\n }\n if (this.forceBackFacesOnly) {\n engine.setState(true, 0, false, true, material.cullBackFaces);\n }\n // Observables\n this.onBeforeShadowMapRenderMeshObservable.notifyObservers(renderingMesh);\n this.onBeforeShadowMapRenderObservable.notifyObservers(effect);\n // Draw\n renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, worldOverride) => {\n if (effectiveMesh !== renderingMesh && !isInstance) {\n renderingMesh.getMeshUniformBuffer().bindToEffect(effect, \"Mesh\");\n renderingMesh.transferToEffect(worldOverride);\n }\n else {\n effectiveMesh.getMeshUniformBuffer().bindToEffect(effect, \"Mesh\");\n effectiveMesh.transferToEffect(isInstance ? worldOverride : world);\n }\n });\n if (this.forceBackFacesOnly) {\n engine.setState(true, 0, false, false, material.cullBackFaces);\n }\n // Observables\n this.onAfterShadowMapRenderObservable.notifyObservers(effect);\n this.onAfterShadowMapRenderMeshObservable.notifyObservers(renderingMesh);\n }\n else {\n // Need to reset refresh rate of the shadowMap\n if (this._shadowMap) {\n this._shadowMap.resetRefreshCounter();\n }\n }\n }\n _applyFilterValues() {\n if (!this._shadowMap) {\n return;\n }\n if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {\n this._shadowMap.updateSamplingMode(Texture.NEAREST_SAMPLINGMODE);\n }\n else {\n this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);\n }\n }\n /**\n * Forces all the attached effect to compile to enable rendering only once ready vs. lazily compiling effects.\n * @param onCompiled Callback triggered at the and of the effects compilation\n * @param options Sets of optional options forcing the compilation with different modes\n */\n forceCompilation(onCompiled, options) {\n const localOptions = Object.assign({ useInstances: false }, options);\n const shadowMap = this.getShadowMap();\n if (!shadowMap) {\n if (onCompiled) {\n onCompiled(this);\n }\n return;\n }\n const renderList = shadowMap.renderList;\n if (!renderList) {\n if (onCompiled) {\n onCompiled(this);\n }\n return;\n }\n const subMeshes = new Array();\n for (const mesh of renderList) {\n subMeshes.push(...mesh.subMeshes);\n }\n if (subMeshes.length === 0) {\n if (onCompiled) {\n onCompiled(this);\n }\n return;\n }\n let currentIndex = 0;\n const checkReady = () => {\n var _a, _b;\n if (!this._scene || !this._scene.getEngine()) {\n return;\n }\n while (this.isReady(subMeshes[currentIndex], localOptions.useInstances, (_b = (_a = subMeshes[currentIndex].getMaterial()) === null || _a === void 0 ? void 0 : _a.needAlphaBlendingForMesh(subMeshes[currentIndex].getMesh())) !== null && _b !== void 0 ? _b : false)) {\n currentIndex++;\n if (currentIndex >= subMeshes.length) {\n if (onCompiled) {\n onCompiled(this);\n }\n return;\n }\n }\n setTimeout(checkReady, 16);\n };\n checkReady();\n }\n /**\n * Forces all the attached effect to compile to enable rendering only once ready vs. lazily compiling effects.\n * @param options Sets of optional options forcing the compilation with different modes\n * @returns A promise that resolves when the compilation completes\n */\n forceCompilationAsync(options) {\n return new Promise((resolve) => {\n this.forceCompilation(() => {\n resolve();\n }, options);\n });\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _isReadyCustomDefines(defines, subMesh, useInstances) { }\n _prepareShadowDefines(subMesh, useInstances, defines, isTransparent) {\n defines.push(\"#define SM_LIGHTTYPE_\" + this._light.getClassName().toUpperCase());\n defines.push(\"#define SM_FLOAT \" + (this._textureType !== 0 ? \"1\" : \"0\"));\n defines.push(\"#define SM_ESM \" + (this.useExponentialShadowMap || this.useBlurExponentialShadowMap ? \"1\" : \"0\"));\n defines.push(\"#define SM_DEPTHTEXTURE \" + (this.usePercentageCloserFiltering || this.useContactHardeningShadow ? \"1\" : \"0\"));\n const mesh = subMesh.getMesh();\n // Normal bias.\n defines.push(\"#define SM_NORMALBIAS \" + (this.normalBias && mesh.isVerticesDataPresent(VertexBuffer.NormalKind) ? \"1\" : \"0\"));\n defines.push(\"#define SM_DIRECTIONINLIGHTDATA \" + (this.getLight().getTypeID() === Light.LIGHTTYPEID_DIRECTIONALLIGHT ? \"1\" : \"0\"));\n // Point light\n defines.push(\"#define SM_USEDISTANCE \" + (this._light.needCube() ? \"1\" : \"0\"));\n // Soft transparent shadows\n defines.push(\"#define SM_SOFTTRANSPARENTSHADOW \" + (this.enableSoftTransparentShadow && isTransparent ? \"1\" : \"0\"));\n this._isReadyCustomDefines(defines, subMesh, useInstances);\n return defines;\n }\n /**\n * Determine whether the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).\n * @param subMesh The submesh we want to render in the shadow map\n * @param useInstances Defines whether will draw in the map using instances\n * @param isTransparent Indicates that isReady is called for a transparent subMesh\n * @returns true if ready otherwise, false\n */\n isReady(subMesh, useInstances, isTransparent) {\n var _a;\n const material = subMesh.getMaterial(), shadowDepthWrapper = material === null || material === void 0 ? void 0 : material.shadowDepthWrapper;\n this._opacityTexture = null;\n if (!material) {\n return false;\n }\n const defines = [];\n this._prepareShadowDefines(subMesh, useInstances, defines, isTransparent);\n if (shadowDepthWrapper) {\n if (!shadowDepthWrapper.isReadyForSubMesh(subMesh, defines, this, useInstances, this._scene.getEngine().currentRenderPassId)) {\n return false;\n }\n }\n else {\n const subMeshEffect = subMesh._getDrawWrapper(undefined, true);\n let effect = subMeshEffect.effect;\n let cachedDefines = subMeshEffect.defines;\n const attribs = [VertexBuffer.PositionKind];\n const mesh = subMesh.getMesh();\n // Normal bias.\n if (this.normalBias && mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {\n attribs.push(VertexBuffer.NormalKind);\n defines.push(\"#define NORMAL\");\n if (mesh.nonUniformScaling) {\n defines.push(\"#define NONUNIFORMSCALING\");\n }\n }\n // Alpha test\n const needAlphaTesting = material.needAlphaTesting();\n if (needAlphaTesting || material.needAlphaBlending()) {\n if (this.useOpacityTextureForTransparentShadow) {\n this._opacityTexture = material.opacityTexture;\n }\n else {\n this._opacityTexture = material.getAlphaTestTexture();\n }\n if (this._opacityTexture) {\n if (!this._opacityTexture.isReady()) {\n return false;\n }\n const alphaCutOff = (_a = material.alphaCutOff) !== null && _a !== void 0 ? _a : ShadowGenerator.DEFAULT_ALPHA_CUTOFF;\n defines.push(\"#define ALPHATEXTURE\");\n if (needAlphaTesting) {\n defines.push(`#define ALPHATESTVALUE ${alphaCutOff}${alphaCutOff % 1 === 0 ? \".\" : \"\"}`);\n }\n if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {\n attribs.push(VertexBuffer.UVKind);\n defines.push(\"#define UV1\");\n }\n if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {\n if (this._opacityTexture.coordinatesIndex === 1) {\n attribs.push(VertexBuffer.UV2Kind);\n defines.push(\"#define UV2\");\n }\n }\n }\n }\n // Bones\n const fallbacks = new EffectFallbacks();\n if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {\n attribs.push(VertexBuffer.MatricesIndicesKind);\n attribs.push(VertexBuffer.MatricesWeightsKind);\n if (mesh.numBoneInfluencers > 4) {\n attribs.push(VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(VertexBuffer.MatricesWeightsExtraKind);\n }\n const skeleton = mesh.skeleton;\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n if (mesh.numBoneInfluencers > 0) {\n fallbacks.addCPUSkinningFallback(0, mesh);\n }\n if (skeleton.isUsingTextureForMatrices) {\n defines.push(\"#define BONETEXTURE\");\n }\n else {\n defines.push(\"#define BonesPerMesh \" + (skeleton.bones.length + 1));\n }\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Morph targets\n const manager = mesh.morphTargetManager;\n let morphInfluencers = 0;\n if (manager) {\n if (manager.numInfluencers > 0) {\n defines.push(\"#define MORPHTARGETS\");\n morphInfluencers = manager.numInfluencers;\n defines.push(\"#define NUM_MORPH_INFLUENCERS \" + morphInfluencers);\n if (manager.isUsingTextureForTargets) {\n defines.push(\"#define MORPHTARGETS_TEXTURE\");\n }\n MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, morphInfluencers);\n }\n }\n // ClipPlanes\n prepareStringDefinesForClipPlanes(material, this._scene, defines);\n // Instances\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n MaterialHelper.PushAttributesForInstances(attribs);\n if (subMesh.getRenderingMesh().hasThinInstances) {\n defines.push(\"#define THIN_INSTANCES\");\n }\n }\n if (this.customShaderOptions) {\n if (this.customShaderOptions.defines) {\n for (const define of this.customShaderOptions.defines) {\n if (defines.indexOf(define) === -1) {\n defines.push(define);\n }\n }\n }\n }\n // Get correct effect\n const join = defines.join(\"\\n\");\n if (cachedDefines !== join) {\n cachedDefines = join;\n let shaderName = \"shadowMap\";\n const uniforms = [\n \"world\",\n \"mBones\",\n \"viewProjection\",\n \"diffuseMatrix\",\n \"lightDataSM\",\n \"depthValuesSM\",\n \"biasAndScaleSM\",\n \"morphTargetInfluences\",\n \"boneTextureWidth\",\n \"softTransparentShadowSM\",\n \"morphTargetTextureInfo\",\n \"morphTargetTextureIndices\",\n ];\n const samplers = [\"diffuseSampler\", \"boneSampler\", \"morphTargets\"];\n const uniformBuffers = [\"Scene\", \"Mesh\"];\n addClipPlaneUniforms(uniforms);\n // Custom shader?\n if (this.customShaderOptions) {\n shaderName = this.customShaderOptions.shaderName;\n if (this.customShaderOptions.attributes) {\n for (const attrib of this.customShaderOptions.attributes) {\n if (attribs.indexOf(attrib) === -1) {\n attribs.push(attrib);\n }\n }\n }\n if (this.customShaderOptions.uniforms) {\n for (const uniform of this.customShaderOptions.uniforms) {\n if (uniforms.indexOf(uniform) === -1) {\n uniforms.push(uniform);\n }\n }\n }\n if (this.customShaderOptions.samplers) {\n for (const sampler of this.customShaderOptions.samplers) {\n if (samplers.indexOf(sampler) === -1) {\n samplers.push(sampler);\n }\n }\n }\n }\n const engine = this._scene.getEngine();\n effect = engine.createEffect(shaderName, {\n attributes: attribs,\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: join,\n fallbacks: fallbacks,\n onCompiled: null,\n onError: null,\n indexParameters: { maxSimultaneousMorphTargets: morphInfluencers },\n }, engine);\n subMeshEffect.setEffect(effect, cachedDefines);\n }\n if (!effect.isReady()) {\n return false;\n }\n }\n if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {\n if (!this._blurPostProcesses || !this._blurPostProcesses.length) {\n this._initializeBlurRTTAndPostProcesses();\n }\n }\n if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {\n return false;\n }\n if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {\n return false;\n }\n if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {\n return false;\n }\n return true;\n }\n /**\n * Prepare all the defines in a material relying on a shadow map at the specified light index.\n * @param defines Defines of the material we want to update\n * @param lightIndex Index of the light in the enabled light list of the material\n */\n prepareDefines(defines, lightIndex) {\n const scene = this._scene;\n const light = this._light;\n if (!scene.shadowsEnabled || !light.shadowEnabled) {\n return;\n }\n defines[\"SHADOW\" + lightIndex] = true;\n if (this.useContactHardeningShadow) {\n defines[\"SHADOWPCSS\" + lightIndex] = true;\n if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {\n defines[\"SHADOWLOWQUALITY\" + lightIndex] = true;\n }\n else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {\n defines[\"SHADOWMEDIUMQUALITY\" + lightIndex] = true;\n }\n // else default to high.\n }\n else if (this.usePercentageCloserFiltering) {\n defines[\"SHADOWPCF\" + lightIndex] = true;\n if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {\n defines[\"SHADOWLOWQUALITY\" + lightIndex] = true;\n }\n else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {\n defines[\"SHADOWMEDIUMQUALITY\" + lightIndex] = true;\n }\n // else default to high.\n }\n else if (this.usePoissonSampling) {\n defines[\"SHADOWPOISSON\" + lightIndex] = true;\n }\n else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {\n defines[\"SHADOWESM\" + lightIndex] = true;\n }\n else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {\n defines[\"SHADOWCLOSEESM\" + lightIndex] = true;\n }\n if (light.needCube()) {\n defines[\"SHADOWCUBE\" + lightIndex] = true;\n }\n }\n /**\n * Binds the shadow related information inside of an effect (information like near, far, darkness...\n * defined in the generator but impacting the effect).\n * @param lightIndex Index of the light in the enabled light list of the material owning the effect\n * @param effect The effect we are binding the information for\n */\n bindShadowLight(lightIndex, effect) {\n const light = this._light;\n const scene = this._scene;\n if (!scene.shadowsEnabled || !light.shadowEnabled) {\n return;\n }\n const camera = this._getCamera();\n if (!camera) {\n return;\n }\n const shadowMap = this.getShadowMap();\n if (!shadowMap) {\n return;\n }\n if (!light.needCube()) {\n effect.setMatrix(\"lightMatrix\" + lightIndex, this.getTransformMatrix());\n }\n // Only PCF uses depth stencil texture.\n if (this._filter === ShadowGenerator.FILTER_PCF) {\n effect.setDepthStencilTexture(\"shadowSampler\" + lightIndex, this.getShadowMapForRendering());\n light._uniformBuffer.updateFloat4(\"shadowsInfo\", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);\n }\n else if (this._filter === ShadowGenerator.FILTER_PCSS) {\n effect.setDepthStencilTexture(\"shadowSampler\" + lightIndex, this.getShadowMapForRendering());\n effect.setTexture(\"depthSampler\" + lightIndex, this.getShadowMapForRendering());\n light._uniformBuffer.updateFloat4(\"shadowsInfo\", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);\n }\n else {\n effect.setTexture(\"shadowSampler\" + lightIndex, this.getShadowMapForRendering());\n light._uniformBuffer.updateFloat4(\"shadowsInfo\", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);\n }\n light._uniformBuffer.updateFloat2(\"depthValues\", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);\n }\n /**\n * Gets the transformation matrix used to project the meshes into the map from the light point of view.\n * (eq to shadow projection matrix * light transform matrix)\n * @returns The transform matrix used to create the shadow map\n */\n getTransformMatrix() {\n const scene = this._scene;\n if (this._currentRenderId === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {\n return this._transformMatrix;\n }\n this._currentRenderId = scene.getRenderId();\n this._currentFaceIndexCache = this._currentFaceIndex;\n let lightPosition = this._light.position;\n if (this._light.computeTransformedInformation()) {\n lightPosition = this._light.transformedPosition;\n }\n Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);\n if (Math.abs(Vector3.Dot(this._lightDirection, Vector3.Up())) === 1.0) {\n this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light\n }\n if (this._light.needProjectionMatrixCompute() ||\n !this._cachedPosition ||\n !this._cachedDirection ||\n !lightPosition.equals(this._cachedPosition) ||\n !this._lightDirection.equals(this._cachedDirection)) {\n this._cachedPosition.copyFrom(lightPosition);\n this._cachedDirection.copyFrom(this._lightDirection);\n Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), Vector3.Up(), this._viewMatrix);\n const shadowMap = this.getShadowMap();\n if (shadowMap) {\n const renderList = shadowMap.renderList;\n if (renderList) {\n this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);\n }\n }\n this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);\n }\n return this._transformMatrix;\n }\n /**\n * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between\n * Cube and 2D textures for instance.\n */\n recreateShadowMap() {\n const shadowMap = this._shadowMap;\n if (!shadowMap) {\n return;\n }\n // Track render list.\n const renderList = shadowMap.renderList;\n // Clean up existing data.\n this._disposeRTTandPostProcesses();\n // Reinitializes.\n this._initializeGenerator();\n // Reaffect the filter to ensure a correct fallback if necessary.\n this.filter = this._filter;\n // Reaffect the filter.\n this._applyFilterValues();\n // Reaffect Render List.\n if (renderList) {\n // Note: don't do this._shadowMap!.renderList = renderList;\n // The renderList hooked array is accessing the old RenderTargetTexture (see RenderTargetTexture._hookArray), which is disposed at this point (by the call to _disposeRTTandPostProcesses)\n if (!this._shadowMap.renderList) {\n this._shadowMap.renderList = [];\n }\n for (const mesh of renderList) {\n this._shadowMap.renderList.push(mesh);\n }\n }\n else {\n this._shadowMap.renderList = null;\n }\n }\n _disposeBlurPostProcesses() {\n if (this._shadowMap2) {\n this._shadowMap2.dispose();\n this._shadowMap2 = null;\n }\n if (this._boxBlurPostprocess) {\n this._boxBlurPostprocess.dispose();\n this._boxBlurPostprocess = null;\n }\n if (this._kernelBlurXPostprocess) {\n this._kernelBlurXPostprocess.dispose();\n this._kernelBlurXPostprocess = null;\n }\n if (this._kernelBlurYPostprocess) {\n this._kernelBlurYPostprocess.dispose();\n this._kernelBlurYPostprocess = null;\n }\n this._blurPostProcesses = [];\n }\n _disposeRTTandPostProcesses() {\n if (this._shadowMap) {\n this._shadowMap.dispose();\n this._shadowMap = null;\n }\n this._disposeBlurPostProcesses();\n }\n _disposeSceneUBOs() {\n if (this._sceneUBOs) {\n for (const ubo of this._sceneUBOs) {\n ubo.dispose();\n }\n this._sceneUBOs = [];\n }\n }\n /**\n * Disposes the ShadowGenerator.\n * Returns nothing.\n */\n dispose() {\n this._disposeRTTandPostProcesses();\n this._disposeSceneUBOs();\n if (this._light) {\n if (this._light._shadowGenerators) {\n const iterator = this._light._shadowGenerators.entries();\n for (let entry = iterator.next(); entry.done !== true; entry = iterator.next()) {\n const [camera, shadowGenerator] = entry.value;\n if (shadowGenerator === this) {\n this._light._shadowGenerators.delete(camera);\n }\n }\n if (this._light._shadowGenerators.size === 0) {\n this._light._shadowGenerators = null;\n }\n }\n this._light._markMeshesAsLightDirty();\n }\n this.onBeforeShadowMapRenderMeshObservable.clear();\n this.onBeforeShadowMapRenderObservable.clear();\n this.onAfterShadowMapRenderMeshObservable.clear();\n this.onAfterShadowMapRenderObservable.clear();\n }\n /**\n * Serializes the shadow generator setup to a json object.\n * @returns The serialized JSON object\n */\n serialize() {\n var _a;\n const serializationObject = {};\n const shadowMap = this.getShadowMap();\n if (!shadowMap) {\n return serializationObject;\n }\n serializationObject.className = this.getClassName();\n serializationObject.lightId = this._light.id;\n serializationObject.cameraId = (_a = this._camera) === null || _a === void 0 ? void 0 : _a.id;\n serializationObject.id = this.id;\n serializationObject.mapSize = shadowMap.getRenderSize();\n serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;\n serializationObject.darkness = this.getDarkness();\n serializationObject.transparencyShadow = this._transparencyShadow;\n serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;\n serializationObject.bias = this.bias;\n serializationObject.normalBias = this.normalBias;\n serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;\n serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;\n serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;\n serializationObject.filteringQuality = this.filteringQuality;\n serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;\n serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;\n serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;\n serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;\n serializationObject.usePoissonSampling = this.usePoissonSampling;\n serializationObject.depthScale = this.depthScale;\n serializationObject.blurBoxOffset = this.blurBoxOffset;\n serializationObject.blurKernel = this.blurKernel;\n serializationObject.blurScale = this.blurScale;\n serializationObject.useKernelBlur = this.useKernelBlur;\n serializationObject.renderList = [];\n if (shadowMap.renderList) {\n for (let meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {\n const mesh = shadowMap.renderList[meshIndex];\n serializationObject.renderList.push(mesh.id);\n }\n }\n return serializationObject;\n }\n /**\n * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.\n * @param parsedShadowGenerator The JSON object to parse\n * @param scene The scene to create the shadow map for\n * @param constr A function that builds a shadow generator or undefined to create an instance of the default shadow generator\n * @returns The parsed shadow generator\n */\n static Parse(parsedShadowGenerator, scene, constr) {\n const light = scene.getLightById(parsedShadowGenerator.lightId);\n const camera = parsedShadowGenerator.cameraId !== undefined ? scene.getCameraById(parsedShadowGenerator.cameraId) : null;\n const shadowGenerator = constr ? constr(parsedShadowGenerator.mapSize, light, camera) : new ShadowGenerator(parsedShadowGenerator.mapSize, light, undefined, camera);\n const shadowMap = shadowGenerator.getShadowMap();\n for (let meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {\n const meshes = scene.getMeshesById(parsedShadowGenerator.renderList[meshIndex]);\n meshes.forEach(function (mesh) {\n if (!shadowMap) {\n return;\n }\n if (!shadowMap.renderList) {\n shadowMap.renderList = [];\n }\n shadowMap.renderList.push(mesh);\n });\n }\n if (parsedShadowGenerator.id !== undefined) {\n shadowGenerator.id = parsedShadowGenerator.id;\n }\n shadowGenerator.forceBackFacesOnly = !!parsedShadowGenerator.forceBackFacesOnly;\n if (parsedShadowGenerator.darkness !== undefined) {\n shadowGenerator.setDarkness(parsedShadowGenerator.darkness);\n }\n if (parsedShadowGenerator.transparencyShadow) {\n shadowGenerator.setTransparencyShadow(true);\n }\n if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {\n shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;\n }\n if (parsedShadowGenerator.bias !== undefined) {\n shadowGenerator.bias = parsedShadowGenerator.bias;\n }\n if (parsedShadowGenerator.normalBias !== undefined) {\n shadowGenerator.normalBias = parsedShadowGenerator.normalBias;\n }\n if (parsedShadowGenerator.usePercentageCloserFiltering) {\n shadowGenerator.usePercentageCloserFiltering = true;\n }\n else if (parsedShadowGenerator.useContactHardeningShadow) {\n shadowGenerator.useContactHardeningShadow = true;\n }\n else if (parsedShadowGenerator.usePoissonSampling) {\n shadowGenerator.usePoissonSampling = true;\n }\n else if (parsedShadowGenerator.useExponentialShadowMap) {\n shadowGenerator.useExponentialShadowMap = true;\n }\n else if (parsedShadowGenerator.useBlurExponentialShadowMap) {\n shadowGenerator.useBlurExponentialShadowMap = true;\n }\n else if (parsedShadowGenerator.useCloseExponentialShadowMap) {\n shadowGenerator.useCloseExponentialShadowMap = true;\n }\n else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {\n shadowGenerator.useBlurCloseExponentialShadowMap = true;\n }\n // Backward compat\n else if (parsedShadowGenerator.useVarianceShadowMap) {\n shadowGenerator.useExponentialShadowMap = true;\n }\n else if (parsedShadowGenerator.useBlurVarianceShadowMap) {\n shadowGenerator.useBlurExponentialShadowMap = true;\n }\n if (parsedShadowGenerator.contactHardeningLightSizeUVRatio !== undefined) {\n shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;\n }\n if (parsedShadowGenerator.filteringQuality !== undefined) {\n shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;\n }\n if (parsedShadowGenerator.depthScale) {\n shadowGenerator.depthScale = parsedShadowGenerator.depthScale;\n }\n if (parsedShadowGenerator.blurScale) {\n shadowGenerator.blurScale = parsedShadowGenerator.blurScale;\n }\n if (parsedShadowGenerator.blurBoxOffset) {\n shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;\n }\n if (parsedShadowGenerator.useKernelBlur) {\n shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;\n }\n if (parsedShadowGenerator.blurKernel) {\n shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;\n }\n return shadowGenerator;\n }\n}\n/**\n * Name of the shadow generator class\n */\nShadowGenerator.CLASSNAME = \"ShadowGenerator\";\n/**\n * Shadow generator mode None: no filtering applied.\n */\nShadowGenerator.FILTER_NONE = 0;\n/**\n * Shadow generator mode ESM: Exponential Shadow Mapping.\n * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)\n */\nShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;\n/**\n * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.\n * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)\n */\nShadowGenerator.FILTER_POISSONSAMPLING = 2;\n/**\n * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.\n * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)\n */\nShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;\n/**\n * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing\n * edge artifacts on steep falloff.\n * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)\n */\nShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;\n/**\n * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing\n * edge artifacts on steep falloff.\n * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)\n */\nShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;\n/**\n * Shadow generator mode PCF: Percentage Closer Filtering\n * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1\n * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)\n */\nShadowGenerator.FILTER_PCF = 6;\n/**\n * Shadow generator mode PCSS: Percentage Closering Soft Shadow.\n * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1\n * Contact Hardening\n */\nShadowGenerator.FILTER_PCSS = 7;\n/**\n * Reserved for PCF and PCSS\n * Highest Quality.\n *\n * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.\n *\n * Execute PCSS with 32 taps blocker search and 64 taps PCF.\n */\nShadowGenerator.QUALITY_HIGH = 0;\n/**\n * Reserved for PCF and PCSS\n * Good tradeoff for quality/perf cross devices\n *\n * Execute PCF on a 3*3 kernel.\n *\n * Execute PCSS with 16 taps blocker search and 32 taps PCF.\n */\nShadowGenerator.QUALITY_MEDIUM = 1;\n/**\n * Reserved for PCF and PCSS\n * The lowest quality but the fastest.\n *\n * Execute PCF on a 1*1 kernel.\n *\n * Execute PCSS with 16 taps blocker search and 16 taps PCF.\n */\nShadowGenerator.QUALITY_LOW = 2;\n/**\n * Defines the default alpha cutoff value used for transparent alpha tested materials.\n */\nShadowGenerator.DEFAULT_ALPHA_CUTOFF = 0.5;\n/**\n * @internal\n */\nShadowGenerator._SceneComponentInitialization = (_) => {\n throw _WarnImport(\"ShadowGeneratorSceneComponent\");\n};\n//# sourceMappingURL=shadowGenerator.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"shadowMapFragmentSoftTransparentShadow\";\nconst shader = `#if SM_SOFTTRANSPARENTSHADOW==1\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const shadowMapFragmentSoftTransparentShadow = { name, shader };\n//# sourceMappingURL=shadowMapFragmentSoftTransparentShadow.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/clipPlaneFragmentDeclaration.js\";\nimport \"./ShadersInclude/packingFunctions.js\";\nimport \"./ShadersInclude/clipPlaneFragment.js\";\nconst name = \"depthPixelShader\";\nconst shader = `#ifdef ALPHATEST\nvarying vec2 vUV;\runiform sampler2D diffuseSampler;\r#endif\n#include\nvarying float vDepthMetric;\r#ifdef PACKED\n#include\n#endif\n#ifdef STORE_CAMERASPACE_Z\nvarying vec4 vViewPos;\r#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\r{\r#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\rdiscard;\r#endif\n#ifdef STORE_CAMERASPACE_Z\n#ifdef PACKED\ngl_FragColor=pack(vViewPos.z);\r#else\ngl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0);\r#endif\n#else\n#ifdef NONLINEARDEPTH\n#ifdef PACKED\ngl_FragColor=pack(gl_FragCoord.z);\r#else\ngl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0);\r#endif\n#else\n#ifdef PACKED\ngl_FragColor=pack(vDepthMetric);\r#else\ngl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0);\r#endif\n#endif\n#endif\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const depthPixelShader = { name, shader };\n//# sourceMappingURL=depth.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/bonesDeclaration.js\";\nimport \"./ShadersInclude/bakedVertexAnimationDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexGlobalDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneVertexDeclaration.js\";\nimport \"./ShadersInclude/instancesDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexGlobal.js\";\nimport \"./ShadersInclude/morphTargetsVertex.js\";\nimport \"./ShadersInclude/instancesVertex.js\";\nimport \"./ShadersInclude/bonesVertex.js\";\nimport \"./ShadersInclude/bakedVertexAnimation.js\";\nimport \"./ShadersInclude/clipPlaneVertex.js\";\nconst name = \"depthVertexShader\";\nconst shader = `attribute vec3 position;\r#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform mat4 viewProjection;\runiform vec2 depthValues;\r#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\runiform mat4 diffuseMatrix;\r#ifdef UV1\nattribute vec2 uv;\r#endif\n#ifdef UV2\nattribute vec2 uv2;\r#endif\n#endif\n#ifdef STORE_CAMERASPACE_Z\nuniform mat4 view;\rvarying vec4 vViewPos;\r#endif\nvarying float vDepthMetric;\r#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\r{\rvec3 positionUpdated=position;\r#ifdef UV1\nvec2 uvUpdated=uv;\r#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\r#include\ngl_Position=viewProjection*worldPos;\r#ifdef STORE_CAMERASPACE_Z\nvViewPos=view*worldPos;\r#else\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y));\r#else\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\r#endif\n#endif\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\r#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\r#endif\n#endif\n}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const depthVertexShader = { name, shader };\n//# sourceMappingURL=depth.vertex.js.map","import { Color4 } from \"../Maths/math.color.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { RenderTargetTexture } from \"../Materials/Textures/renderTargetTexture.js\";\nimport { MaterialHelper } from \"../Materials/materialHelper.js\";\nimport { Camera } from \"../Cameras/camera.js\";\n\nimport \"../Shaders/depth.fragment.js\";\nimport \"../Shaders/depth.vertex.js\";\nimport { _WarnImport } from \"../Misc/devTools.js\";\nimport { addClipPlaneUniforms, bindClipPlane, prepareStringDefinesForClipPlanes } from \"../Materials/clipPlaneMaterialHelper.js\";\n/**\n * This represents a depth renderer in Babylon.\n * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing\n */\nexport class DepthRenderer {\n /**\n * Sets a specific material to be used to render a mesh/a list of meshes by the depth renderer\n * @param mesh mesh or array of meshes\n * @param material material to use by the depth render when rendering the mesh(es). If undefined is passed, the specific material created by the depth renderer will be used.\n */\n setMaterialForRendering(mesh, material) {\n this._depthMap.setMaterialForRendering(mesh, material);\n }\n /**\n * Instantiates a depth renderer\n * @param scene The scene the renderer belongs to\n * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)\n * @param camera The camera to be used to render the depth map (default: scene's active camera)\n * @param storeNonLinearDepth Defines whether the depth is stored linearly like in Babylon Shadows or directly like glFragCoord.z\n * @param samplingMode The sampling mode to be used with the render target (Linear, Nearest...) (default: TRILINEAR_SAMPLINGMODE)\n * @param storeCameraSpaceZ Defines whether the depth stored is the Z coordinate in camera space. If true, storeNonLinearDepth has no effect. (Default: false)\n * @param name Name of the render target (default: DepthRenderer)\n */\n constructor(scene, type = 1, camera = null, storeNonLinearDepth = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, storeCameraSpaceZ = false, name) {\n /** Enable or disable the depth renderer. When disabled, the depth texture is not updated */\n this.enabled = true;\n /** Force writing the transparent objects into the depth map */\n this.forceDepthWriteTransparentMeshes = false;\n /**\n * Specifies that the depth renderer will only be used within\n * the camera it is created for.\n * This can help forcing its rendering during the camera processing.\n */\n this.useOnlyInActiveCamera = false;\n /** If true, reverse the culling of materials before writing to the depth texture.\n * So, basically, when \"true\", back facing instead of front facing faces are rasterized into the texture\n */\n this.reverseCulling = false;\n this._scene = scene;\n this._storeNonLinearDepth = storeNonLinearDepth;\n this._storeCameraSpaceZ = storeCameraSpaceZ;\n this.isPacked = type === 0;\n if (this.isPacked) {\n this.clearColor = new Color4(1.0, 1.0, 1.0, 1.0);\n }\n else {\n this.clearColor = new Color4(storeCameraSpaceZ ? 1e8 : 1.0, 0.0, 0.0, 1.0);\n }\n DepthRenderer._SceneComponentInitialization(this._scene);\n const engine = scene.getEngine();\n this._camera = camera;\n if (samplingMode !== Texture.NEAREST_SAMPLINGMODE) {\n if (type === 1 && !engine._caps.textureFloatLinearFiltering) {\n samplingMode = Texture.NEAREST_SAMPLINGMODE;\n }\n if (type === 2 && !engine._caps.textureHalfFloatLinearFiltering) {\n samplingMode = Texture.NEAREST_SAMPLINGMODE;\n }\n }\n // Render target\n const format = this.isPacked || !engine._features.supportExtendedTextureFormats ? 5 : 6;\n this._depthMap = new RenderTargetTexture(name !== null && name !== void 0 ? name : \"DepthRenderer\", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type, false, samplingMode, undefined, undefined, undefined, format);\n this._depthMap.wrapU = Texture.CLAMP_ADDRESSMODE;\n this._depthMap.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._depthMap.refreshRate = 1;\n this._depthMap.renderParticles = false;\n this._depthMap.renderList = null;\n this._depthMap.noPrePassRenderer = true;\n // Camera to get depth map from to support multiple concurrent cameras\n this._depthMap.activeCamera = this._camera;\n this._depthMap.ignoreCameraViewport = true;\n this._depthMap.useCameraPostProcesses = false;\n // set default depth value to 1.0 (far away)\n this._depthMap.onClearObservable.add((engine) => {\n engine.clear(this.clearColor, true, true, true);\n });\n this._depthMap.onBeforeBindObservable.add(() => {\n var _a;\n (_a = engine._debugPushGroup) === null || _a === void 0 ? void 0 : _a.call(engine, \"depth renderer\", 1);\n });\n this._depthMap.onAfterUnbindObservable.add(() => {\n var _a;\n (_a = engine._debugPopGroup) === null || _a === void 0 ? void 0 : _a.call(engine, 1);\n });\n this._depthMap.customIsReadyFunction = (mesh, refreshRate, preWarm) => {\n if ((preWarm || refreshRate === 0) && mesh.subMeshes) {\n for (let i = 0; i < mesh.subMeshes.length; ++i) {\n const subMesh = mesh.subMeshes[i];\n const renderingMesh = subMesh.getRenderingMesh();\n const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());\n const hardwareInstancedRendering = engine.getCaps().instancedArrays &&\n ((batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined) || renderingMesh.hasThinInstances);\n if (!this.isReady(subMesh, hardwareInstancedRendering)) {\n return false;\n }\n }\n }\n return true;\n };\n // Custom render function\n const renderSubMesh = (subMesh) => {\n var _a, _b;\n const renderingMesh = subMesh.getRenderingMesh();\n const effectiveMesh = subMesh.getEffectiveMesh();\n const scene = this._scene;\n const engine = scene.getEngine();\n const material = subMesh.getMaterial();\n effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;\n if (!material || effectiveMesh.infiniteDistance || material.disableDepthWrite || subMesh.verticesCount === 0 || subMesh._renderId === scene.getRenderId()) {\n return;\n }\n // Culling\n const detNeg = effectiveMesh._getWorldMatrixDeterminant() < 0;\n let sideOrientation = (_a = renderingMesh.overrideMaterialSideOrientation) !== null && _a !== void 0 ? _a : material.sideOrientation;\n if (detNeg) {\n sideOrientation =\n sideOrientation === 0\n ? 1\n : 0;\n }\n const reverseSideOrientation = sideOrientation === 0;\n engine.setState(material.backFaceCulling, 0, false, reverseSideOrientation, this.reverseCulling ? !material.cullBackFaces : material.cullBackFaces);\n // Managing instances\n const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());\n if (batch.mustReturn) {\n return;\n }\n const hardwareInstancedRendering = engine.getCaps().instancedArrays &&\n ((batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined) || renderingMesh.hasThinInstances);\n const camera = this._camera || scene.activeCamera;\n if (this.isReady(subMesh, hardwareInstancedRendering) && camera) {\n subMesh._renderId = scene.getRenderId();\n const renderingMaterial = (_b = effectiveMesh._internalAbstractMeshDataInfo._materialForRenderPass) === null || _b === void 0 ? void 0 : _b[engine.currentRenderPassId];\n let drawWrapper = subMesh._getDrawWrapper();\n if (!drawWrapper && renderingMaterial) {\n drawWrapper = renderingMaterial._getDrawWrapper();\n }\n const cameraIsOrtho = camera.mode === Camera.ORTHOGRAPHIC_CAMERA;\n if (!drawWrapper) {\n return;\n }\n const effect = drawWrapper.effect;\n engine.enableEffect(drawWrapper);\n if (!hardwareInstancedRendering) {\n renderingMesh._bind(subMesh, effect, material.fillMode);\n }\n if (!renderingMaterial) {\n effect.setMatrix(\"viewProjection\", scene.getTransformMatrix());\n effect.setMatrix(\"world\", effectiveMesh.getWorldMatrix());\n if (this._storeCameraSpaceZ) {\n effect.setMatrix(\"view\", scene.getViewMatrix());\n }\n }\n else {\n renderingMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), effectiveMesh, subMesh);\n }\n let minZ, maxZ;\n if (cameraIsOrtho) {\n minZ = !engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : 1;\n maxZ = engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : 1;\n }\n else {\n minZ = engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? camera.minZ : engine.isNDCHalfZRange ? 0 : camera.minZ;\n maxZ = engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : camera.maxZ;\n }\n effect.setFloat2(\"depthValues\", minZ, minZ + maxZ);\n if (!renderingMaterial) {\n // Alpha test\n if (material.needAlphaTesting()) {\n const alphaTexture = material.getAlphaTestTexture();\n if (alphaTexture) {\n effect.setTexture(\"diffuseSampler\", alphaTexture);\n effect.setMatrix(\"diffuseMatrix\", alphaTexture.getTextureMatrix());\n }\n }\n // Bones\n if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) {\n const skeleton = renderingMesh.skeleton;\n if (skeleton.isUsingTextureForMatrices) {\n const boneTexture = skeleton.getTransformMatrixTexture(renderingMesh);\n if (!boneTexture) {\n return;\n }\n effect.setTexture(\"boneSampler\", boneTexture);\n effect.setFloat(\"boneTextureWidth\", 4.0 * (skeleton.bones.length + 1));\n }\n else {\n effect.setMatrices(\"mBones\", skeleton.getTransformMatrices(renderingMesh));\n }\n }\n // Clip planes\n bindClipPlane(effect, material, scene);\n // Morph targets\n MaterialHelper.BindMorphTargetParameters(renderingMesh, effect);\n if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) {\n renderingMesh.morphTargetManager._bind(effect);\n }\n }\n // Draw\n renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, world) => effect.setMatrix(\"world\", world));\n }\n };\n this._depthMap.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => {\n let index;\n if (depthOnlySubMeshes.length) {\n for (index = 0; index < depthOnlySubMeshes.length; index++) {\n renderSubMesh(depthOnlySubMeshes.data[index]);\n }\n }\n for (index = 0; index < opaqueSubMeshes.length; index++) {\n renderSubMesh(opaqueSubMeshes.data[index]);\n }\n for (index = 0; index < alphaTestSubMeshes.length; index++) {\n renderSubMesh(alphaTestSubMeshes.data[index]);\n }\n if (this.forceDepthWriteTransparentMeshes) {\n for (index = 0; index < transparentSubMeshes.length; index++) {\n renderSubMesh(transparentSubMeshes.data[index]);\n }\n }\n else {\n for (index = 0; index < transparentSubMeshes.length; index++) {\n transparentSubMeshes.data[index].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate = false;\n }\n }\n };\n }\n /**\n * Creates the depth rendering effect and checks if the effect is ready.\n * @param subMesh The submesh to be used to render the depth map of\n * @param useInstances If multiple world instances should be used\n * @returns if the depth renderer is ready to render the depth map\n */\n isReady(subMesh, useInstances) {\n var _a;\n const engine = this._scene.getEngine();\n const mesh = subMesh.getMesh();\n const scene = mesh.getScene();\n const renderingMaterial = (_a = mesh._internalAbstractMeshDataInfo._materialForRenderPass) === null || _a === void 0 ? void 0 : _a[engine.currentRenderPassId];\n if (renderingMaterial) {\n return renderingMaterial.isReadyForSubMesh(mesh, subMesh, useInstances);\n }\n const material = subMesh.getMaterial();\n if (!material || material.disableDepthWrite) {\n return false;\n }\n const defines = [];\n const attribs = [VertexBuffer.PositionKind];\n // Alpha test\n if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {\n defines.push(\"#define ALPHATEST\");\n if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {\n attribs.push(VertexBuffer.UVKind);\n defines.push(\"#define UV1\");\n }\n if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {\n attribs.push(VertexBuffer.UV2Kind);\n defines.push(\"#define UV2\");\n }\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders) {\n attribs.push(VertexBuffer.MatricesIndicesKind);\n attribs.push(VertexBuffer.MatricesWeightsKind);\n if (mesh.numBoneInfluencers > 4) {\n attribs.push(VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(VertexBuffer.MatricesWeightsExtraKind);\n }\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n defines.push(\"#define BonesPerMesh \" + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));\n const skeleton = subMesh.getRenderingMesh().skeleton;\n if (skeleton === null || skeleton === void 0 ? void 0 : skeleton.isUsingTextureForMatrices) {\n defines.push(\"#define BONETEXTURE\");\n }\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Morph targets\n const morphTargetManager = mesh.morphTargetManager;\n let numMorphInfluencers = 0;\n if (morphTargetManager) {\n if (morphTargetManager.numInfluencers > 0) {\n numMorphInfluencers = morphTargetManager.numInfluencers;\n defines.push(\"#define MORPHTARGETS\");\n defines.push(\"#define NUM_MORPH_INFLUENCERS \" + numMorphInfluencers);\n if (morphTargetManager.isUsingTextureForTargets) {\n defines.push(\"#define MORPHTARGETS_TEXTURE\");\n }\n MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, numMorphInfluencers);\n }\n }\n // Instances\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n MaterialHelper.PushAttributesForInstances(attribs);\n if (subMesh.getRenderingMesh().hasThinInstances) {\n defines.push(\"#define THIN_INSTANCES\");\n }\n }\n // None linear depth\n if (this._storeNonLinearDepth) {\n defines.push(\"#define NONLINEARDEPTH\");\n }\n // Store camera space Z coordinate instead of NDC Z\n if (this._storeCameraSpaceZ) {\n defines.push(\"#define STORE_CAMERASPACE_Z\");\n }\n // Float Mode\n if (this.isPacked) {\n defines.push(\"#define PACKED\");\n }\n // Clip planes\n prepareStringDefinesForClipPlanes(material, scene, defines);\n // Get correct effect\n const drawWrapper = subMesh._getDrawWrapper(undefined, true);\n const cachedDefines = drawWrapper.defines;\n const join = defines.join(\"\\n\");\n if (cachedDefines !== join) {\n const uniforms = [\n \"world\",\n \"mBones\",\n \"boneTextureWidth\",\n \"viewProjection\",\n \"view\",\n \"diffuseMatrix\",\n \"depthValues\",\n \"morphTargetInfluences\",\n \"morphTargetTextureInfo\",\n \"morphTargetTextureIndices\",\n ];\n addClipPlaneUniforms(uniforms);\n drawWrapper.setEffect(engine.createEffect(\"depth\", attribs, uniforms, [\"diffuseSampler\", \"morphTargets\", \"boneSampler\"], join, undefined, undefined, undefined, {\n maxSimultaneousMorphTargets: numMorphInfluencers,\n }), join);\n }\n return drawWrapper.effect.isReady();\n }\n /**\n * Gets the texture which the depth map will be written to.\n * @returns The depth map texture\n */\n getDepthMap() {\n return this._depthMap;\n }\n /**\n * Disposes of the depth renderer.\n */\n dispose() {\n const keysToDelete = [];\n for (const key in this._scene._depthRenderer) {\n const depthRenderer = this._scene._depthRenderer[key];\n if (depthRenderer === this) {\n keysToDelete.push(key);\n }\n }\n if (keysToDelete.length > 0) {\n this._depthMap.dispose();\n for (const key of keysToDelete) {\n delete this._scene._depthRenderer[key];\n }\n }\n }\n}\n/**\n * @internal\n */\nDepthRenderer._SceneComponentInitialization = (_) => {\n throw _WarnImport(\"DepthRendererSceneComponent\");\n};\n//# sourceMappingURL=depthRenderer.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"minmaxReduxPixelShader\";\nconst shader = `varying vec2 vUV;\runiform sampler2D textureSampler;\r#if defined(INITIAL)\nuniform sampler2D sourceTexture;\runiform vec2 texSize;\rvoid main(void)\r{\rivec2 coord=ivec2(vUV*(texSize-1.0));\rfloat f1=texelFetch(sourceTexture,coord,0).r;\rfloat f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;\rfloat f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;\rfloat f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;\rfloat minz=min(min(min(f1,f2),f3),f4);\r#ifdef DEPTH_REDUX\nfloat maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);\r#else\nfloat maxz=max(max(max(f1,f2),f3),f4);\r#endif\nglFragColor=vec4(minz,maxz,0.,0.);\r}\r#elif defined(MAIN)\nuniform vec2 texSize;\rvoid main(void)\r{\rivec2 coord=ivec2(vUV*(texSize-1.0));\rvec2 f1=texelFetch(textureSampler,coord,0).rg;\rvec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;\rvec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;\rvec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;\rfloat minz=min(min(min(f1.x,f2.x),f3.x),f4.x);\rfloat maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);\rglFragColor=vec4(minz,maxz,0.,0.);\r}\r#elif defined(ONEBEFORELAST)\nuniform ivec2 texSize;\rvoid main(void)\r{\rivec2 coord=ivec2(vUV*vec2(texSize-1));\rvec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;\rvec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;\rvec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;\rvec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;\rfloat minz=min(f1.x,f2.x);\rfloat maxz=max(f1.y,f2.y);\rglFragColor=vec4(minz,maxz,0.,0.);\r}\r#elif defined(LAST)\nvoid main(void)\r{\rglFragColor=vec4(0.);\rif (true) { \rdiscard;\r}\r}\r#endif\n`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const minmaxReduxPixelShader = { name, shader };\n//# sourceMappingURL=minmaxRedux.fragment.js.map","\nimport { Observable } from \"./observable.js\";\nimport { PostProcess } from \"../PostProcesses/postProcess.js\";\nimport { PostProcessManager } from \"../PostProcesses/postProcessManager.js\";\nimport \"../Shaders/minmaxRedux.fragment.js\";\n/**\n * This class computes a min/max reduction from a texture: it means it computes the minimum\n * and maximum values from all values of the texture.\n * It is performed on the GPU for better performances, thanks to a succession of post processes.\n * The source values are read from the red channel of the texture.\n */\nexport class MinMaxReducer {\n /**\n * Creates a min/max reducer\n * @param camera The camera to use for the post processes\n */\n constructor(camera) {\n /**\n * Observable triggered when the computation has been performed\n */\n this.onAfterReductionPerformed = new Observable();\n this._forceFullscreenViewport = true;\n this._activated = false;\n this._camera = camera;\n this._postProcessManager = new PostProcessManager(camera.getScene());\n this._onContextRestoredObserver = camera.getEngine().onContextRestoredObservable.add(() => {\n this._postProcessManager._rebuild();\n });\n }\n /**\n * Gets the texture used to read the values from.\n */\n get sourceTexture() {\n return this._sourceTexture;\n }\n /**\n * Sets the source texture to read the values from.\n * One must indicate if the texture is a depth texture or not through the depthRedux parameter\n * because in such textures '1' value must not be taken into account to compute the maximum\n * as this value is used to clear the texture.\n * Note that the computation is not activated by calling this function, you must call activate() for that!\n * @param sourceTexture The texture to read the values from. The values should be in the red channel.\n * @param depthRedux Indicates if the texture is a depth texture or not\n * @param type The type of the textures created for the reduction (defaults to TEXTURETYPE_HALF_FLOAT)\n * @param forceFullscreenViewport Forces the post processes used for the reduction to be applied without taking into account viewport (defaults to true)\n */\n setSourceTexture(sourceTexture, depthRedux, type = 2, forceFullscreenViewport = true) {\n if (sourceTexture === this._sourceTexture) {\n return;\n }\n this.dispose(false);\n this._sourceTexture = sourceTexture;\n this._reductionSteps = [];\n this._forceFullscreenViewport = forceFullscreenViewport;\n const scene = this._camera.getScene();\n // create the first step\n const reductionInitial = new PostProcess(\"Initial reduction phase\", \"minmaxRedux\", // shader\n [\"texSize\"], [\"sourceTexture\"], // textures\n 1.0, // options\n null, // camera\n 1, // sampling\n scene.getEngine(), // engine\n false, // reusable\n \"#define INITIAL\" + (depthRedux ? \"\\n#define DEPTH_REDUX\" : \"\"), // defines\n type, undefined, undefined, undefined, 7);\n reductionInitial.autoClear = false;\n reductionInitial.forceFullscreenViewport = forceFullscreenViewport;\n let w = this._sourceTexture.getRenderWidth(), h = this._sourceTexture.getRenderHeight();\n reductionInitial.onApply = ((w, h) => {\n return (effect) => {\n effect.setTexture(\"sourceTexture\", this._sourceTexture);\n effect.setFloat2(\"texSize\", w, h);\n };\n })(w, h);\n this._reductionSteps.push(reductionInitial);\n let index = 1;\n // create the additional steps\n while (w > 1 || h > 1) {\n w = Math.max(Math.round(w / 2), 1);\n h = Math.max(Math.round(h / 2), 1);\n const reduction = new PostProcess(\"Reduction phase \" + index, \"minmaxRedux\", // shader\n [\"texSize\"], null, { width: w, height: h }, // options\n null, // camera\n 1, // sampling\n scene.getEngine(), // engine\n false, // reusable\n \"#define \" + (w == 1 && h == 1 ? \"LAST\" : w == 1 || h == 1 ? \"ONEBEFORELAST\" : \"MAIN\"), // defines\n type, undefined, undefined, undefined, 7);\n reduction.autoClear = false;\n reduction.forceFullscreenViewport = forceFullscreenViewport;\n reduction.onApply = ((w, h) => {\n return (effect) => {\n if (w == 1 || h == 1) {\n effect.setInt2(\"texSize\", w, h);\n }\n else {\n effect.setFloat2(\"texSize\", w, h);\n }\n };\n })(w, h);\n this._reductionSteps.push(reduction);\n index++;\n if (w == 1 && h == 1) {\n const func = (w, h, reduction) => {\n const buffer = new Float32Array(4 * w * h), minmax = { min: 0, max: 0 };\n return () => {\n scene.getEngine()._readTexturePixels(reduction.inputTexture.texture, w, h, -1, 0, buffer, false);\n minmax.min = buffer[0];\n minmax.max = buffer[1];\n this.onAfterReductionPerformed.notifyObservers(minmax);\n };\n };\n reduction.onAfterRenderObservable.add(func(w, h, reduction));\n }\n }\n }\n /**\n * Defines the refresh rate of the computation.\n * Use 0 to compute just once, 1 to compute on every frame, 2 to compute every two frames and so on...\n */\n get refreshRate() {\n return this._sourceTexture ? this._sourceTexture.refreshRate : -1;\n }\n set refreshRate(value) {\n if (this._sourceTexture) {\n this._sourceTexture.refreshRate = value;\n }\n }\n /**\n * Gets the activation status of the reducer\n */\n get activated() {\n return this._activated;\n }\n /**\n * Activates the reduction computation.\n * When activated, the observers registered in onAfterReductionPerformed are\n * called after the computation is performed\n */\n activate() {\n if (this._onAfterUnbindObserver || !this._sourceTexture) {\n return;\n }\n this._onAfterUnbindObserver = this._sourceTexture.onAfterUnbindObservable.add(() => {\n var _a, _b;\n const engine = this._camera.getScene().getEngine();\n (_a = engine._debugPushGroup) === null || _a === void 0 ? void 0 : _a.call(engine, `min max reduction`, 1);\n this._reductionSteps[0].activate(this._camera);\n this._postProcessManager.directRender(this._reductionSteps, this._reductionSteps[0].inputTexture, this._forceFullscreenViewport);\n engine.unBindFramebuffer(this._reductionSteps[0].inputTexture, false);\n (_b = engine._debugPopGroup) === null || _b === void 0 ? void 0 : _b.call(engine, 1);\n });\n this._activated = true;\n }\n /**\n * Deactivates the reduction computation.\n */\n deactivate() {\n if (!this._onAfterUnbindObserver || !this._sourceTexture) {\n return;\n }\n this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);\n this._onAfterUnbindObserver = null;\n this._activated = false;\n }\n /**\n * Disposes the min/max reducer\n * @param disposeAll true to dispose all the resources. You should always call this function with true as the parameter (or without any parameter as it is the default one). This flag is meant to be used internally.\n */\n dispose(disposeAll = true) {\n if (disposeAll) {\n this.onAfterReductionPerformed.clear();\n if (this._onContextRestoredObserver) {\n this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver);\n this._onContextRestoredObserver = null;\n }\n }\n this.deactivate();\n if (this._reductionSteps) {\n for (let i = 0; i < this._reductionSteps.length; ++i) {\n this._reductionSteps[i].dispose();\n }\n this._reductionSteps = null;\n }\n if (this._postProcessManager && disposeAll) {\n this._postProcessManager.dispose();\n }\n this._sourceTexture = null;\n }\n}\n//# sourceMappingURL=minMaxReducer.js.map","\nimport { DepthRenderer } from \"../Rendering/depthRenderer.js\";\nimport { MinMaxReducer } from \"./minMaxReducer.js\";\n/**\n * This class is a small wrapper around the MinMaxReducer class to compute the min/max values of a depth texture\n */\nexport class DepthReducer extends MinMaxReducer {\n /**\n * Gets the depth renderer used for the computation.\n * Note that the result is null if you provide your own renderer when calling setDepthRenderer.\n */\n get depthRenderer() {\n return this._depthRenderer;\n }\n /**\n * Creates a depth reducer\n * @param camera The camera used to render the depth texture\n */\n constructor(camera) {\n super(camera);\n }\n /**\n * Sets the depth renderer to use to generate the depth map\n * @param depthRenderer The depth renderer to use. If not provided, a new one will be created automatically\n * @param type The texture type of the depth map (default: TEXTURETYPE_HALF_FLOAT)\n * @param forceFullscreenViewport Forces the post processes used for the reduction to be applied without taking into account viewport (defaults to true)\n */\n setDepthRenderer(depthRenderer = null, type = 2, forceFullscreenViewport = true) {\n const scene = this._camera.getScene();\n if (this._depthRenderer) {\n delete scene._depthRenderer[this._depthRendererId];\n this._depthRenderer.dispose();\n this._depthRenderer = null;\n }\n if (depthRenderer === null) {\n if (!scene._depthRenderer) {\n scene._depthRenderer = {};\n }\n depthRenderer = this._depthRenderer = new DepthRenderer(scene, type, this._camera, false, 1);\n depthRenderer.enabled = false;\n this._depthRendererId = \"minmax\" + this._camera.id;\n scene._depthRenderer[this._depthRendererId] = depthRenderer;\n }\n super.setSourceTexture(depthRenderer.getDepthMap(), true, type, forceFullscreenViewport);\n }\n /**\n * @internal\n */\n setSourceTexture(sourceTexture, depthRedux, type = 2, forceFullscreenViewport = true) {\n super.setSourceTexture(sourceTexture, depthRedux, type, forceFullscreenViewport);\n }\n /**\n * Activates the reduction computation.\n * When activated, the observers registered in onAfterReductionPerformed are\n * called after the computation is performed\n */\n activate() {\n if (this._depthRenderer) {\n this._depthRenderer.enabled = true;\n }\n super.activate();\n }\n /**\n * Deactivates the reduction computation.\n */\n deactivate() {\n super.deactivate();\n if (this._depthRenderer) {\n this._depthRenderer.enabled = false;\n }\n }\n /**\n * Disposes the depth reducer\n * @param disposeAll true to dispose all the resources. You should always call this function with true as the parameter (or without any parameter as it is the default one). This flag is meant to be used internally.\n */\n dispose(disposeAll = true) {\n super.dispose(disposeAll);\n if (this._depthRenderer && disposeAll) {\n const scene = this._depthRenderer.getDepthMap().getScene();\n if (scene) {\n delete scene._depthRenderer[this._depthRendererId];\n }\n this._depthRenderer.dispose();\n this._depthRenderer = null;\n }\n }\n}\n//# sourceMappingURL=depthReducer.js.map","import { Matrix, Vector3 } from \"../../Maths/math.vector.js\";\nimport { RenderTargetTexture } from \"../../Materials/Textures/renderTargetTexture.js\";\n\nimport \"../../Shaders/shadowMap.fragment.js\";\nimport \"../../Shaders/shadowMap.vertex.js\";\nimport \"../../Shaders/depthBoxBlur.fragment.js\";\nimport { _WarnImport } from \"../../Misc/devTools.js\";\nimport { ShadowGenerator } from \"./shadowGenerator.js\";\nimport { BoundingInfo } from \"../../Culling/boundingInfo.js\";\nimport { DepthReducer } from \"../../Misc/depthReducer.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { EngineStore } from \"../../Engines/engineStore.js\";\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst UpDir = Vector3.Up();\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst ZeroVec = Vector3.Zero();\nconst tmpv1 = new Vector3(), tmpv2 = new Vector3(), tmpMatrix = new Matrix();\n/**\n * A CSM implementation allowing casting shadows on large scenes.\n * Documentation : https://doc.babylonjs.com/babylon101/cascadedShadows\n * Based on: https://github.com/TheRealMJP/Shadows and https://johanmedestrom.wordpress.com/2016/03/18/opengl-cascaded-shadow-maps/\n */\nexport class CascadedShadowGenerator extends ShadowGenerator {\n _validateFilter(filter) {\n if (filter === ShadowGenerator.FILTER_NONE || filter === ShadowGenerator.FILTER_PCF || filter === ShadowGenerator.FILTER_PCSS) {\n return filter;\n }\n console.error('Unsupported filter \"' + filter + '\"!');\n return ShadowGenerator.FILTER_NONE;\n }\n /**\n * Gets or set the number of cascades used by the CSM.\n */\n get numCascades() {\n return this._numCascades;\n }\n set numCascades(value) {\n value = Math.min(Math.max(value, CascadedShadowGenerator.MIN_CASCADES_COUNT), CascadedShadowGenerator.MAX_CASCADES_COUNT);\n if (value === this._numCascades) {\n return;\n }\n this._numCascades = value;\n this.recreateShadowMap();\n this._recreateSceneUBOs();\n }\n /**\n * Enables or disables the shadow casters bounding info computation.\n * If your shadow casters don't move, you can disable this feature.\n * If it is enabled, the bounding box computation is done every frame.\n */\n get freezeShadowCastersBoundingInfo() {\n return this._freezeShadowCastersBoundingInfo;\n }\n set freezeShadowCastersBoundingInfo(freeze) {\n if (this._freezeShadowCastersBoundingInfoObservable && freeze) {\n this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable);\n this._freezeShadowCastersBoundingInfoObservable = null;\n }\n if (!this._freezeShadowCastersBoundingInfoObservable && !freeze) {\n this._freezeShadowCastersBoundingInfoObservable = this._scene.onBeforeRenderObservable.add(this._computeShadowCastersBoundingInfo.bind(this));\n }\n this._freezeShadowCastersBoundingInfo = freeze;\n if (freeze) {\n this._computeShadowCastersBoundingInfo();\n }\n }\n _computeShadowCastersBoundingInfo() {\n this._scbiMin.copyFromFloats(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._scbiMax.copyFromFloats(Number.MIN_VALUE, Number.MIN_VALUE, Number.MIN_VALUE);\n if (this._shadowMap && this._shadowMap.renderList) {\n const renderList = this._shadowMap.renderList;\n for (let meshIndex = 0; meshIndex < renderList.length; meshIndex++) {\n const mesh = renderList[meshIndex];\n if (!mesh) {\n continue;\n }\n const boundingInfo = mesh.getBoundingInfo(), boundingBox = boundingInfo.boundingBox;\n this._scbiMin.minimizeInPlace(boundingBox.minimumWorld);\n this._scbiMax.maximizeInPlace(boundingBox.maximumWorld);\n }\n const meshes = this._scene.meshes;\n for (let meshIndex = 0; meshIndex < meshes.length; meshIndex++) {\n const mesh = meshes[meshIndex];\n if (!mesh || !mesh.isVisible || !mesh.isEnabled || !mesh.receiveShadows) {\n continue;\n }\n const boundingInfo = mesh.getBoundingInfo(), boundingBox = boundingInfo.boundingBox;\n this._scbiMin.minimizeInPlace(boundingBox.minimumWorld);\n this._scbiMax.maximizeInPlace(boundingBox.maximumWorld);\n }\n }\n this._shadowCastersBoundingInfo.reConstruct(this._scbiMin, this._scbiMax);\n }\n /**\n * Gets or sets the shadow casters bounding info.\n * If you provide your own shadow casters bounding info, first enable freezeShadowCastersBoundingInfo\n * so that the system won't overwrite the bounds you provide\n */\n get shadowCastersBoundingInfo() {\n return this._shadowCastersBoundingInfo;\n }\n set shadowCastersBoundingInfo(boundingInfo) {\n this._shadowCastersBoundingInfo = boundingInfo;\n }\n /**\n * Sets the minimal and maximal distances to use when computing the cascade breaks.\n *\n * The values of min / max are typically the depth zmin and zmax values of your scene, for a given frame.\n * If you don't know these values, simply leave them to their defaults and don't call this function.\n * @param min minimal distance for the breaks (default to 0.)\n * @param max maximal distance for the breaks (default to 1.)\n */\n setMinMaxDistance(min, max) {\n if (this._minDistance === min && this._maxDistance === max) {\n return;\n }\n if (min > max) {\n min = 0;\n max = 1;\n }\n if (min < 0) {\n min = 0;\n }\n if (max > 1) {\n max = 1;\n }\n this._minDistance = min;\n this._maxDistance = max;\n this._breaksAreDirty = true;\n }\n /** Gets the minimal distance used in the cascade break computation */\n get minDistance() {\n return this._minDistance;\n }\n /** Gets the maximal distance used in the cascade break computation */\n get maxDistance() {\n return this._maxDistance;\n }\n /**\n * Gets the class name of that object\n * @returns \"CascadedShadowGenerator\"\n */\n getClassName() {\n return CascadedShadowGenerator.CLASSNAME;\n }\n /**\n * Gets a cascade minimum extents\n * @param cascadeIndex index of the cascade\n * @returns the minimum cascade extents\n */\n getCascadeMinExtents(cascadeIndex) {\n return cascadeIndex >= 0 && cascadeIndex < this._numCascades ? this._cascadeMinExtents[cascadeIndex] : null;\n }\n /**\n * Gets a cascade maximum extents\n * @param cascadeIndex index of the cascade\n * @returns the maximum cascade extents\n */\n getCascadeMaxExtents(cascadeIndex) {\n return cascadeIndex >= 0 && cascadeIndex < this._numCascades ? this._cascadeMaxExtents[cascadeIndex] : null;\n }\n /**\n * Gets the shadow max z distance. It's the limit beyond which shadows are not displayed.\n * It defaults to camera.maxZ\n */\n get shadowMaxZ() {\n if (!this._getCamera()) {\n return 0;\n }\n return this._shadowMaxZ;\n }\n /**\n * Sets the shadow max z distance.\n */\n set shadowMaxZ(value) {\n const camera = this._getCamera();\n if (!camera) {\n this._shadowMaxZ = value;\n return;\n }\n if (this._shadowMaxZ === value || value < camera.minZ || value > camera.maxZ) {\n return;\n }\n this._shadowMaxZ = value;\n this._light._markMeshesAsLightDirty();\n this._breaksAreDirty = true;\n }\n /**\n * Gets or sets the debug flag.\n * When enabled, the cascades are materialized by different colors on the screen.\n */\n get debug() {\n return this._debug;\n }\n set debug(dbg) {\n this._debug = dbg;\n this._light._markMeshesAsLightDirty();\n }\n /**\n * Gets or sets the depth clamping value.\n *\n * When enabled, it improves the shadow quality because the near z plane of the light frustum don't need to be adjusted\n * to account for the shadow casters far away.\n *\n * Note that this property is incompatible with PCSS filtering, so it won't be used in that case.\n */\n get depthClamp() {\n return this._depthClamp;\n }\n set depthClamp(value) {\n this._depthClamp = value;\n }\n /**\n * Gets or sets the percentage of blending between two cascades (value between 0. and 1.).\n * It defaults to 0.1 (10% blending).\n */\n get cascadeBlendPercentage() {\n return this._cascadeBlendPercentage;\n }\n set cascadeBlendPercentage(value) {\n this._cascadeBlendPercentage = value;\n this._light._markMeshesAsLightDirty();\n }\n /**\n * Gets or set the lambda parameter.\n * This parameter is used to split the camera frustum and create the cascades.\n * It's a value between 0. and 1.: If 0, the split is a uniform split of the frustum, if 1 it is a logarithmic split.\n * For all values in-between, it's a linear combination of the uniform and logarithm split algorithm.\n */\n get lambda() {\n return this._lambda;\n }\n set lambda(value) {\n const lambda = Math.min(Math.max(value, 0), 1);\n if (this._lambda == lambda) {\n return;\n }\n this._lambda = lambda;\n this._breaksAreDirty = true;\n }\n /**\n * Gets the view matrix corresponding to a given cascade\n * @param cascadeNum cascade to retrieve the view matrix from\n * @returns the cascade view matrix\n */\n getCascadeViewMatrix(cascadeNum) {\n return cascadeNum >= 0 && cascadeNum < this._numCascades ? this._viewMatrices[cascadeNum] : null;\n }\n /**\n * Gets the projection matrix corresponding to a given cascade\n * @param cascadeNum cascade to retrieve the projection matrix from\n * @returns the cascade projection matrix\n */\n getCascadeProjectionMatrix(cascadeNum) {\n return cascadeNum >= 0 && cascadeNum < this._numCascades ? this._projectionMatrices[cascadeNum] : null;\n }\n /**\n * Gets the transformation matrix corresponding to a given cascade\n * @param cascadeNum cascade to retrieve the transformation matrix from\n * @returns the cascade transformation matrix\n */\n getCascadeTransformMatrix(cascadeNum) {\n return cascadeNum >= 0 && cascadeNum < this._numCascades ? this._transformMatrices[cascadeNum] : null;\n }\n /**\n * Sets the depth renderer to use when autoCalcDepthBounds is enabled.\n *\n * Note that if no depth renderer is set, a new one will be automatically created internally when necessary.\n *\n * You should call this function if you already have a depth renderer enabled in your scene, to avoid\n * doing multiple depth rendering each frame. If you provide your own depth renderer, make sure it stores linear depth!\n * @param depthRenderer The depth renderer to use when autoCalcDepthBounds is enabled. If you pass null or don't call this function at all, a depth renderer will be automatically created\n */\n setDepthRenderer(depthRenderer) {\n this._depthRenderer = depthRenderer;\n if (this._depthReducer) {\n this._depthReducer.setDepthRenderer(this._depthRenderer);\n }\n }\n /**\n * Gets or sets the autoCalcDepthBounds property.\n *\n * When enabled, a depth rendering pass is first performed (with an internally created depth renderer or with the one\n * you provide by calling setDepthRenderer). Then, a min/max reducing is applied on the depth map to compute the\n * minimal and maximal depth of the map and those values are used as inputs for the setMinMaxDistance() function.\n * It can greatly enhance the shadow quality, at the expense of more GPU works.\n * When using this option, you should increase the value of the lambda parameter, and even set it to 1 for best results.\n */\n get autoCalcDepthBounds() {\n return this._autoCalcDepthBounds;\n }\n set autoCalcDepthBounds(value) {\n const camera = this._getCamera();\n if (!camera) {\n return;\n }\n this._autoCalcDepthBounds = value;\n if (!value) {\n if (this._depthReducer) {\n this._depthReducer.deactivate();\n }\n this.setMinMaxDistance(0, 1);\n return;\n }\n if (!this._depthReducer) {\n this._depthReducer = new DepthReducer(camera);\n this._depthReducer.onAfterReductionPerformed.add((minmax) => {\n let min = minmax.min, max = minmax.max;\n if (min >= max) {\n min = 0;\n max = 1;\n }\n if (min != this._minDistance || max != this._maxDistance) {\n this.setMinMaxDistance(min, max);\n }\n });\n this._depthReducer.setDepthRenderer(this._depthRenderer);\n }\n this._depthReducer.activate();\n }\n /**\n * Defines the refresh rate of the min/max computation used when autoCalcDepthBounds is set to true\n * Use 0 to compute just once, 1 to compute on every frame, 2 to compute every two frames and so on...\n * Note that if you provided your own depth renderer through a call to setDepthRenderer, you are responsible\n * for setting the refresh rate on the renderer yourself!\n */\n get autoCalcDepthBoundsRefreshRate() {\n var _a, _b, _c;\n return (_c = (_b = (_a = this._depthReducer) === null || _a === void 0 ? void 0 : _a.depthRenderer) === null || _b === void 0 ? void 0 : _b.getDepthMap().refreshRate) !== null && _c !== void 0 ? _c : -1;\n }\n set autoCalcDepthBoundsRefreshRate(value) {\n var _a;\n if ((_a = this._depthReducer) === null || _a === void 0 ? void 0 : _a.depthRenderer) {\n this._depthReducer.depthRenderer.getDepthMap().refreshRate = value;\n }\n }\n /**\n * Create the cascade breaks according to the lambda, shadowMaxZ and min/max distance properties, as well as the camera near and far planes.\n * This function is automatically called when updating lambda, shadowMaxZ and min/max distances, however you should call it yourself if\n * you change the camera near/far planes!\n */\n splitFrustum() {\n this._breaksAreDirty = true;\n }\n _splitFrustum() {\n const camera = this._getCamera();\n if (!camera) {\n return;\n }\n const near = camera.minZ, far = camera.maxZ || this._shadowMaxZ, // account for infinite far plane (ie. maxZ = 0)\n cameraRange = far - near, minDistance = this._minDistance, maxDistance = this._shadowMaxZ < far && this._shadowMaxZ >= near ? Math.min((this._shadowMaxZ - near) / (far - near), this._maxDistance) : this._maxDistance;\n const minZ = near + minDistance * cameraRange, maxZ = near + maxDistance * cameraRange;\n const range = maxZ - minZ, ratio = maxZ / minZ;\n for (let cascadeIndex = 0; cascadeIndex < this._cascades.length; ++cascadeIndex) {\n const p = (cascadeIndex + 1) / this._numCascades, log = minZ * ratio ** p, uniform = minZ + range * p;\n const d = this._lambda * (log - uniform) + uniform;\n this._cascades[cascadeIndex].prevBreakDistance = cascadeIndex === 0 ? minDistance : this._cascades[cascadeIndex - 1].breakDistance;\n this._cascades[cascadeIndex].breakDistance = (d - near) / cameraRange;\n this._viewSpaceFrustumsZ[cascadeIndex] = d;\n this._frustumLengths[cascadeIndex] = (this._cascades[cascadeIndex].breakDistance - this._cascades[cascadeIndex].prevBreakDistance) * cameraRange;\n }\n this._breaksAreDirty = false;\n }\n _computeMatrices() {\n const scene = this._scene;\n const camera = this._getCamera();\n if (!camera) {\n return;\n }\n Vector3.NormalizeToRef(this._light.getShadowDirection(0), this._lightDirection);\n if (Math.abs(Vector3.Dot(this._lightDirection, Vector3.Up())) === 1.0) {\n this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light\n }\n this._cachedDirection.copyFrom(this._lightDirection);\n const useReverseDepthBuffer = scene.getEngine().useReverseDepthBuffer;\n for (let cascadeIndex = 0; cascadeIndex < this._numCascades; ++cascadeIndex) {\n this._computeFrustumInWorldSpace(cascadeIndex);\n this._computeCascadeFrustum(cascadeIndex);\n this._cascadeMaxExtents[cascadeIndex].subtractToRef(this._cascadeMinExtents[cascadeIndex], tmpv1); // tmpv1 = cascadeExtents\n // Get position of the shadow camera\n this._frustumCenter[cascadeIndex].addToRef(this._lightDirection.scale(this._cascadeMinExtents[cascadeIndex].z), this._shadowCameraPos[cascadeIndex]);\n // Come up with a new orthographic camera for the shadow caster\n Matrix.LookAtLHToRef(this._shadowCameraPos[cascadeIndex], this._frustumCenter[cascadeIndex], UpDir, this._viewMatrices[cascadeIndex]);\n let minZ = 0, maxZ = tmpv1.z;\n // Try to tighten minZ and maxZ based on the bounding box of the shadow casters\n const boundingInfo = this._shadowCastersBoundingInfo;\n boundingInfo.update(this._viewMatrices[cascadeIndex]);\n maxZ = Math.min(maxZ, boundingInfo.boundingBox.maximumWorld.z);\n if (!this._depthClamp || this.filter === ShadowGenerator.FILTER_PCSS) {\n // If we don't use depth clamping, we must set minZ so that all shadow casters are in the light frustum\n minZ = Math.min(minZ, boundingInfo.boundingBox.minimumWorld.z);\n }\n else {\n // If using depth clamping, we can adjust minZ to reduce the [minZ, maxZ] range (and get some additional precision in the shadow map)\n minZ = Math.max(minZ, boundingInfo.boundingBox.minimumWorld.z);\n }\n Matrix.OrthoOffCenterLHToRef(this._cascadeMinExtents[cascadeIndex].x, this._cascadeMaxExtents[cascadeIndex].x, this._cascadeMinExtents[cascadeIndex].y, this._cascadeMaxExtents[cascadeIndex].y, useReverseDepthBuffer ? maxZ : minZ, useReverseDepthBuffer ? minZ : maxZ, this._projectionMatrices[cascadeIndex], scene.getEngine().isNDCHalfZRange);\n this._cascadeMinExtents[cascadeIndex].z = minZ;\n this._cascadeMaxExtents[cascadeIndex].z = maxZ;\n this._viewMatrices[cascadeIndex].multiplyToRef(this._projectionMatrices[cascadeIndex], this._transformMatrices[cascadeIndex]);\n // Create the rounding matrix, by projecting the world-space origin and determining\n // the fractional offset in texel space\n Vector3.TransformCoordinatesToRef(ZeroVec, this._transformMatrices[cascadeIndex], tmpv1); // tmpv1 = shadowOrigin\n tmpv1.scaleInPlace(this._mapSize / 2);\n tmpv2.copyFromFloats(Math.round(tmpv1.x), Math.round(tmpv1.y), Math.round(tmpv1.z)); // tmpv2 = roundedOrigin\n tmpv2.subtractInPlace(tmpv1).scaleInPlace(2 / this._mapSize); // tmpv2 = roundOffset\n Matrix.TranslationToRef(tmpv2.x, tmpv2.y, 0.0, tmpMatrix);\n this._projectionMatrices[cascadeIndex].multiplyToRef(tmpMatrix, this._projectionMatrices[cascadeIndex]);\n this._viewMatrices[cascadeIndex].multiplyToRef(this._projectionMatrices[cascadeIndex], this._transformMatrices[cascadeIndex]);\n this._transformMatrices[cascadeIndex].copyToArray(this._transformMatricesAsArray, cascadeIndex * 16);\n }\n }\n // Get the 8 points of the view frustum in world space\n _computeFrustumInWorldSpace(cascadeIndex) {\n const camera = this._getCamera();\n if (!camera) {\n return;\n }\n const prevSplitDist = this._cascades[cascadeIndex].prevBreakDistance, splitDist = this._cascades[cascadeIndex].breakDistance;\n const isNDCHalfZRange = this._scene.getEngine().isNDCHalfZRange;\n camera.getViewMatrix(); // make sure the transformation matrix we get when calling 'getTransformationMatrix()' is calculated with an up to date view matrix\n const cameraInfiniteFarPlane = camera.maxZ === 0;\n const saveCameraMaxZ = camera.maxZ;\n if (cameraInfiniteFarPlane) {\n camera.maxZ = this._shadowMaxZ;\n camera.getProjectionMatrix(true);\n }\n const invViewProj = Matrix.Invert(camera.getTransformationMatrix());\n if (cameraInfiniteFarPlane) {\n camera.maxZ = saveCameraMaxZ;\n camera.getProjectionMatrix(true);\n }\n const cornerIndexOffset = this._scene.getEngine().useReverseDepthBuffer ? 4 : 0;\n for (let cornerIndex = 0; cornerIndex < CascadedShadowGenerator._FrustumCornersNDCSpace.length; ++cornerIndex) {\n tmpv1.copyFrom(CascadedShadowGenerator._FrustumCornersNDCSpace[(cornerIndex + cornerIndexOffset) % CascadedShadowGenerator._FrustumCornersNDCSpace.length]);\n if (isNDCHalfZRange && tmpv1.z === -1) {\n tmpv1.z = 0;\n }\n Vector3.TransformCoordinatesToRef(tmpv1, invViewProj, this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]);\n }\n // Get the corners of the current cascade slice of the view frustum\n for (let cornerIndex = 0; cornerIndex < CascadedShadowGenerator._FrustumCornersNDCSpace.length / 2; ++cornerIndex) {\n tmpv1.copyFrom(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex + 4]).subtractInPlace(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]);\n tmpv2.copyFrom(tmpv1).scaleInPlace(prevSplitDist); // near corner ray\n tmpv1.scaleInPlace(splitDist); // far corner ray\n tmpv1.addInPlace(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]);\n this._frustumCornersWorldSpace[cascadeIndex][cornerIndex + 4].copyFrom(tmpv1);\n this._frustumCornersWorldSpace[cascadeIndex][cornerIndex].addInPlace(tmpv2);\n }\n }\n _computeCascadeFrustum(cascadeIndex) {\n this._cascadeMinExtents[cascadeIndex].copyFromFloats(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._cascadeMaxExtents[cascadeIndex].copyFromFloats(Number.MIN_VALUE, Number.MIN_VALUE, Number.MIN_VALUE);\n this._frustumCenter[cascadeIndex].copyFromFloats(0, 0, 0);\n const camera = this._getCamera();\n if (!camera) {\n return;\n }\n // Calculate the centroid of the view frustum slice\n for (let cornerIndex = 0; cornerIndex < this._frustumCornersWorldSpace[cascadeIndex].length; ++cornerIndex) {\n this._frustumCenter[cascadeIndex].addInPlace(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]);\n }\n this._frustumCenter[cascadeIndex].scaleInPlace(1 / this._frustumCornersWorldSpace[cascadeIndex].length);\n if (this.stabilizeCascades) {\n // Calculate the radius of a bounding sphere surrounding the frustum corners\n let sphereRadius = 0;\n for (let cornerIndex = 0; cornerIndex < this._frustumCornersWorldSpace[cascadeIndex].length; ++cornerIndex) {\n const dist = this._frustumCornersWorldSpace[cascadeIndex][cornerIndex].subtractToRef(this._frustumCenter[cascadeIndex], tmpv1).length();\n sphereRadius = Math.max(sphereRadius, dist);\n }\n sphereRadius = Math.ceil(sphereRadius * 16) / 16;\n this._cascadeMaxExtents[cascadeIndex].copyFromFloats(sphereRadius, sphereRadius, sphereRadius);\n this._cascadeMinExtents[cascadeIndex].copyFromFloats(-sphereRadius, -sphereRadius, -sphereRadius);\n }\n else {\n // Create a temporary view matrix for the light\n const lightCameraPos = this._frustumCenter[cascadeIndex];\n this._frustumCenter[cascadeIndex].addToRef(this._lightDirection, tmpv1); // tmpv1 = look at\n Matrix.LookAtLHToRef(lightCameraPos, tmpv1, UpDir, tmpMatrix); // matrix = lightView\n // Calculate an AABB around the frustum corners\n for (let cornerIndex = 0; cornerIndex < this._frustumCornersWorldSpace[cascadeIndex].length; ++cornerIndex) {\n Vector3.TransformCoordinatesToRef(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex], tmpMatrix, tmpv1);\n this._cascadeMinExtents[cascadeIndex].minimizeInPlace(tmpv1);\n this._cascadeMaxExtents[cascadeIndex].maximizeInPlace(tmpv1);\n }\n }\n }\n _recreateSceneUBOs() {\n this._disposeSceneUBOs();\n if (this._sceneUBOs) {\n for (let i = 0; i < this._numCascades; ++i) {\n this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for CSM Shadow Generator (light \"${this._light.name}\" cascade #${i})`));\n }\n }\n }\n /**\n * Support test.\n */\n static get IsSupported() {\n const engine = EngineStore.LastCreatedEngine;\n if (!engine) {\n return false;\n }\n return engine._features.supportCSM;\n }\n /**\n * Creates a Cascaded Shadow Generator object.\n * A ShadowGenerator is the required tool to use the shadows.\n * Each directional light casting shadows needs to use its own ShadowGenerator.\n * Documentation : https://doc.babylonjs.com/babylon101/cascadedShadows\n * @param mapSize The size of the texture what stores the shadows. Example : 1024.\n * @param light The directional light object generating the shadows.\n * @param usefulFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.\n * @param camera Camera associated with this shadow generator (default: null). If null, takes the scene active camera at the time we need to access it\n */\n constructor(mapSize, light, usefulFloatFirst, camera) {\n if (!CascadedShadowGenerator.IsSupported) {\n Logger.Error(\"CascadedShadowMap is not supported by the current engine.\");\n return;\n }\n super(mapSize, light, usefulFloatFirst, camera);\n this.usePercentageCloserFiltering = true;\n }\n _initializeGenerator() {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v;\n this.penumbraDarkness = (_a = this.penumbraDarkness) !== null && _a !== void 0 ? _a : 1.0;\n this._numCascades = (_b = this._numCascades) !== null && _b !== void 0 ? _b : CascadedShadowGenerator.DEFAULT_CASCADES_COUNT;\n this.stabilizeCascades = (_c = this.stabilizeCascades) !== null && _c !== void 0 ? _c : false;\n this._freezeShadowCastersBoundingInfoObservable = (_d = this._freezeShadowCastersBoundingInfoObservable) !== null && _d !== void 0 ? _d : null;\n this.freezeShadowCastersBoundingInfo = (_e = this.freezeShadowCastersBoundingInfo) !== null && _e !== void 0 ? _e : false;\n this._scbiMin = (_f = this._scbiMin) !== null && _f !== void 0 ? _f : new Vector3(0, 0, 0);\n this._scbiMax = (_g = this._scbiMax) !== null && _g !== void 0 ? _g : new Vector3(0, 0, 0);\n this._shadowCastersBoundingInfo = (_h = this._shadowCastersBoundingInfo) !== null && _h !== void 0 ? _h : new BoundingInfo(new Vector3(0, 0, 0), new Vector3(0, 0, 0));\n this._breaksAreDirty = (_j = this._breaksAreDirty) !== null && _j !== void 0 ? _j : true;\n this._minDistance = (_k = this._minDistance) !== null && _k !== void 0 ? _k : 0;\n this._maxDistance = (_l = this._maxDistance) !== null && _l !== void 0 ? _l : 1;\n this._currentLayer = (_m = this._currentLayer) !== null && _m !== void 0 ? _m : 0;\n this._shadowMaxZ = (_q = (_o = this._shadowMaxZ) !== null && _o !== void 0 ? _o : (_p = this._getCamera()) === null || _p === void 0 ? void 0 : _p.maxZ) !== null && _q !== void 0 ? _q : 10000;\n this._debug = (_r = this._debug) !== null && _r !== void 0 ? _r : false;\n this._depthClamp = (_s = this._depthClamp) !== null && _s !== void 0 ? _s : true;\n this._cascadeBlendPercentage = (_t = this._cascadeBlendPercentage) !== null && _t !== void 0 ? _t : 0.1;\n this._lambda = (_u = this._lambda) !== null && _u !== void 0 ? _u : 0.5;\n this._autoCalcDepthBounds = (_v = this._autoCalcDepthBounds) !== null && _v !== void 0 ? _v : false;\n this._recreateSceneUBOs();\n super._initializeGenerator();\n }\n _createTargetRenderTexture() {\n const engine = this._scene.getEngine();\n const size = { width: this._mapSize, height: this._mapSize, layers: this.numCascades };\n this._shadowMap = new RenderTargetTexture(this._light.name + \"_CSMShadowMap\", size, this._scene, false, true, this._textureType, false, undefined, false, false, undefined /*, 6*/);\n this._shadowMap.createDepthStencilTexture(engine.useReverseDepthBuffer ? 516 : 513, true);\n this._shadowMap.noPrePassRenderer = true;\n }\n _initializeShadowMap() {\n super._initializeShadowMap();\n if (this._shadowMap === null) {\n return;\n }\n this._transformMatricesAsArray = new Float32Array(this._numCascades * 16);\n this._viewSpaceFrustumsZ = new Array(this._numCascades);\n this._frustumLengths = new Array(this._numCascades);\n this._lightSizeUVCorrection = new Array(this._numCascades * 2);\n this._depthCorrection = new Array(this._numCascades);\n this._cascades = [];\n this._viewMatrices = [];\n this._projectionMatrices = [];\n this._transformMatrices = [];\n this._cascadeMinExtents = [];\n this._cascadeMaxExtents = [];\n this._frustumCenter = [];\n this._shadowCameraPos = [];\n this._frustumCornersWorldSpace = [];\n for (let cascadeIndex = 0; cascadeIndex < this._numCascades; ++cascadeIndex) {\n this._cascades[cascadeIndex] = {\n prevBreakDistance: 0,\n breakDistance: 0,\n };\n this._viewMatrices[cascadeIndex] = Matrix.Zero();\n this._projectionMatrices[cascadeIndex] = Matrix.Zero();\n this._transformMatrices[cascadeIndex] = Matrix.Zero();\n this._cascadeMinExtents[cascadeIndex] = new Vector3();\n this._cascadeMaxExtents[cascadeIndex] = new Vector3();\n this._frustumCenter[cascadeIndex] = new Vector3();\n this._shadowCameraPos[cascadeIndex] = new Vector3();\n this._frustumCornersWorldSpace[cascadeIndex] = new Array(CascadedShadowGenerator._FrustumCornersNDCSpace.length);\n for (let i = 0; i < CascadedShadowGenerator._FrustumCornersNDCSpace.length; ++i) {\n this._frustumCornersWorldSpace[cascadeIndex][i] = new Vector3();\n }\n }\n const engine = this._scene.getEngine();\n this._shadowMap.onBeforeBindObservable.clear();\n this._shadowMap.onBeforeRenderObservable.clear();\n this._shadowMap.onBeforeRenderObservable.add((layer) => {\n if (this._sceneUBOs) {\n this._scene.setSceneUniformBuffer(this._sceneUBOs[layer]);\n }\n this._currentLayer = layer;\n if (this._filter === ShadowGenerator.FILTER_PCF) {\n engine.setColorWrite(false);\n }\n this._scene.setTransformMatrix(this.getCascadeViewMatrix(layer), this.getCascadeProjectionMatrix(layer));\n if (this._useUBO) {\n this._scene.getSceneUniformBuffer().unbindEffect();\n this._scene.finalizeSceneUbo();\n }\n });\n this._shadowMap.onBeforeBindObservable.add(() => {\n var _a;\n this._currentSceneUBO = this._scene.getSceneUniformBuffer();\n (_a = engine._debugPushGroup) === null || _a === void 0 ? void 0 : _a.call(engine, `cascaded shadow map generation for pass id ${engine.currentRenderPassId}`, 1);\n if (this._breaksAreDirty) {\n this._splitFrustum();\n }\n this._computeMatrices();\n });\n this._splitFrustum();\n }\n _bindCustomEffectForRenderSubMeshForShadowMap(subMesh, effect) {\n effect.setMatrix(\"viewProjection\", this.getCascadeTransformMatrix(this._currentLayer));\n }\n _isReadyCustomDefines(defines) {\n defines.push(\"#define SM_DEPTHCLAMP \" + (this._depthClamp && this._filter !== ShadowGenerator.FILTER_PCSS ? \"1\" : \"0\"));\n }\n /**\n * Prepare all the defines in a material relying on a shadow map at the specified light index.\n * @param defines Defines of the material we want to update\n * @param lightIndex Index of the light in the enabled light list of the material\n */\n prepareDefines(defines, lightIndex) {\n super.prepareDefines(defines, lightIndex);\n const scene = this._scene;\n const light = this._light;\n if (!scene.shadowsEnabled || !light.shadowEnabled) {\n return;\n }\n defines[\"SHADOWCSM\" + lightIndex] = true;\n defines[\"SHADOWCSMDEBUG\" + lightIndex] = this.debug;\n defines[\"SHADOWCSMNUM_CASCADES\" + lightIndex] = this.numCascades;\n defines[\"SHADOWCSM_RIGHTHANDED\" + lightIndex] = scene.useRightHandedSystem;\n const camera = this._getCamera();\n if (camera && this._shadowMaxZ <= (camera.maxZ || this._shadowMaxZ)) {\n defines[\"SHADOWCSMUSESHADOWMAXZ\" + lightIndex] = true;\n }\n if (this.cascadeBlendPercentage === 0) {\n defines[\"SHADOWCSMNOBLEND\" + lightIndex] = true;\n }\n }\n /**\n * Binds the shadow related information inside of an effect (information like near, far, darkness...\n * defined in the generator but impacting the effect).\n * @param lightIndex Index of the light in the enabled light list of the material owning the effect\n * @param effect The effect we are binfing the information for\n */\n bindShadowLight(lightIndex, effect) {\n const light = this._light;\n const scene = this._scene;\n if (!scene.shadowsEnabled || !light.shadowEnabled) {\n return;\n }\n const camera = this._getCamera();\n if (!camera) {\n return;\n }\n const shadowMap = this.getShadowMap();\n if (!shadowMap) {\n return;\n }\n const width = shadowMap.getSize().width;\n effect.setMatrices(\"lightMatrix\" + lightIndex, this._transformMatricesAsArray);\n effect.setArray(\"viewFrustumZ\" + lightIndex, this._viewSpaceFrustumsZ);\n effect.setFloat(\"cascadeBlendFactor\" + lightIndex, this.cascadeBlendPercentage === 0 ? 10000 : 1 / this.cascadeBlendPercentage);\n effect.setArray(\"frustumLengths\" + lightIndex, this._frustumLengths);\n // Only PCF uses depth stencil texture.\n if (this._filter === ShadowGenerator.FILTER_PCF) {\n effect.setDepthStencilTexture(\"shadowSampler\" + lightIndex, shadowMap);\n light._uniformBuffer.updateFloat4(\"shadowsInfo\", this.getDarkness(), width, 1 / width, this.frustumEdgeFalloff, lightIndex);\n }\n else if (this._filter === ShadowGenerator.FILTER_PCSS) {\n for (let cascadeIndex = 0; cascadeIndex < this._numCascades; ++cascadeIndex) {\n this._lightSizeUVCorrection[cascadeIndex * 2 + 0] =\n cascadeIndex === 0\n ? 1\n : (this._cascadeMaxExtents[0].x - this._cascadeMinExtents[0].x) / (this._cascadeMaxExtents[cascadeIndex].x - this._cascadeMinExtents[cascadeIndex].x); // x correction\n this._lightSizeUVCorrection[cascadeIndex * 2 + 1] =\n cascadeIndex === 0\n ? 1\n : (this._cascadeMaxExtents[0].y - this._cascadeMinExtents[0].y) / (this._cascadeMaxExtents[cascadeIndex].y - this._cascadeMinExtents[cascadeIndex].y); // y correction\n this._depthCorrection[cascadeIndex] =\n cascadeIndex === 0\n ? 1\n : (this._cascadeMaxExtents[cascadeIndex].z - this._cascadeMinExtents[cascadeIndex].z) / (this._cascadeMaxExtents[0].z - this._cascadeMinExtents[0].z);\n }\n effect.setDepthStencilTexture(\"shadowSampler\" + lightIndex, shadowMap);\n effect.setTexture(\"depthSampler\" + lightIndex, shadowMap);\n effect.setArray2(\"lightSizeUVCorrection\" + lightIndex, this._lightSizeUVCorrection);\n effect.setArray(\"depthCorrection\" + lightIndex, this._depthCorrection);\n effect.setFloat(\"penumbraDarkness\" + lightIndex, this.penumbraDarkness);\n light._uniformBuffer.updateFloat4(\"shadowsInfo\", this.getDarkness(), 1 / width, this._contactHardeningLightSizeUVRatio * width, this.frustumEdgeFalloff, lightIndex);\n }\n else {\n effect.setTexture(\"shadowSampler\" + lightIndex, shadowMap);\n light._uniformBuffer.updateFloat4(\"shadowsInfo\", this.getDarkness(), width, 1 / width, this.frustumEdgeFalloff, lightIndex);\n }\n light._uniformBuffer.updateFloat2(\"depthValues\", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);\n }\n /**\n * Gets the transformation matrix of the first cascade used to project the meshes into the map from the light point of view.\n * (eq to view projection * shadow projection matrices)\n * @returns The transform matrix used to create the shadow map\n */\n getTransformMatrix() {\n return this.getCascadeTransformMatrix(0);\n }\n /**\n * Disposes the ShadowGenerator.\n * Returns nothing.\n */\n dispose() {\n super.dispose();\n if (this._freezeShadowCastersBoundingInfoObservable) {\n this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable);\n this._freezeShadowCastersBoundingInfoObservable = null;\n }\n if (this._depthReducer) {\n this._depthReducer.dispose();\n this._depthReducer = null;\n }\n }\n /**\n * Serializes the shadow generator setup to a json object.\n * @returns The serialized JSON object\n */\n serialize() {\n const serializationObject = super.serialize();\n const shadowMap = this.getShadowMap();\n if (!shadowMap) {\n return serializationObject;\n }\n serializationObject.numCascades = this._numCascades;\n serializationObject.debug = this._debug;\n serializationObject.stabilizeCascades = this.stabilizeCascades;\n serializationObject.lambda = this._lambda;\n serializationObject.cascadeBlendPercentage = this.cascadeBlendPercentage;\n serializationObject.depthClamp = this._depthClamp;\n serializationObject.autoCalcDepthBounds = this.autoCalcDepthBounds;\n serializationObject.shadowMaxZ = this._shadowMaxZ;\n serializationObject.penumbraDarkness = this.penumbraDarkness;\n serializationObject.freezeShadowCastersBoundingInfo = this._freezeShadowCastersBoundingInfo;\n serializationObject.minDistance = this.minDistance;\n serializationObject.maxDistance = this.maxDistance;\n serializationObject.renderList = [];\n if (shadowMap.renderList) {\n for (let meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {\n const mesh = shadowMap.renderList[meshIndex];\n serializationObject.renderList.push(mesh.id);\n }\n }\n return serializationObject;\n }\n /**\n * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.\n * @param parsedShadowGenerator The JSON object to parse\n * @param scene The scene to create the shadow map for\n * @returns The parsed shadow generator\n */\n static Parse(parsedShadowGenerator, scene) {\n const shadowGenerator = ShadowGenerator.Parse(parsedShadowGenerator, scene, (mapSize, light, camera) => new CascadedShadowGenerator(mapSize, light, undefined, camera));\n if (parsedShadowGenerator.numCascades !== undefined) {\n shadowGenerator.numCascades = parsedShadowGenerator.numCascades;\n }\n if (parsedShadowGenerator.debug !== undefined) {\n shadowGenerator.debug = parsedShadowGenerator.debug;\n }\n if (parsedShadowGenerator.stabilizeCascades !== undefined) {\n shadowGenerator.stabilizeCascades = parsedShadowGenerator.stabilizeCascades;\n }\n if (parsedShadowGenerator.lambda !== undefined) {\n shadowGenerator.lambda = parsedShadowGenerator.lambda;\n }\n if (parsedShadowGenerator.cascadeBlendPercentage !== undefined) {\n shadowGenerator.cascadeBlendPercentage = parsedShadowGenerator.cascadeBlendPercentage;\n }\n if (parsedShadowGenerator.depthClamp !== undefined) {\n shadowGenerator.depthClamp = parsedShadowGenerator.depthClamp;\n }\n if (parsedShadowGenerator.autoCalcDepthBounds !== undefined) {\n shadowGenerator.autoCalcDepthBounds = parsedShadowGenerator.autoCalcDepthBounds;\n }\n if (parsedShadowGenerator.shadowMaxZ !== undefined) {\n shadowGenerator.shadowMaxZ = parsedShadowGenerator.shadowMaxZ;\n }\n if (parsedShadowGenerator.penumbraDarkness !== undefined) {\n shadowGenerator.penumbraDarkness = parsedShadowGenerator.penumbraDarkness;\n }\n if (parsedShadowGenerator.freezeShadowCastersBoundingInfo !== undefined) {\n shadowGenerator.freezeShadowCastersBoundingInfo = parsedShadowGenerator.freezeShadowCastersBoundingInfo;\n }\n if (parsedShadowGenerator.minDistance !== undefined && parsedShadowGenerator.maxDistance !== undefined) {\n shadowGenerator.setMinMaxDistance(parsedShadowGenerator.minDistance, parsedShadowGenerator.maxDistance);\n }\n return shadowGenerator;\n }\n}\nCascadedShadowGenerator._FrustumCornersNDCSpace = [\n new Vector3(-1.0, +1.0, -1.0),\n new Vector3(+1.0, +1.0, -1.0),\n new Vector3(+1.0, -1.0, -1.0),\n new Vector3(-1.0, -1.0, -1.0),\n new Vector3(-1.0, +1.0, +1.0),\n new Vector3(+1.0, +1.0, +1.0),\n new Vector3(+1.0, -1.0, +1.0),\n new Vector3(-1.0, -1.0, +1.0),\n];\n/**\n * Name of the CSM class\n */\nCascadedShadowGenerator.CLASSNAME = \"CascadedShadowGenerator\";\n/**\n * Defines the default number of cascades used by the CSM.\n */\nCascadedShadowGenerator.DEFAULT_CASCADES_COUNT = 4;\n/**\n * Defines the minimum number of cascades used by the CSM.\n */\nCascadedShadowGenerator.MIN_CASCADES_COUNT = 2;\n/**\n * Defines the maximum number of cascades used by the CSM.\n */\nCascadedShadowGenerator.MAX_CASCADES_COUNT = 4;\n/**\n * @internal\n */\nCascadedShadowGenerator._SceneComponentInitialization = (_) => {\n throw _WarnImport(\"ShadowGeneratorSceneComponent\");\n};\n//# sourceMappingURL=cascadedShadowGenerator.js.map","import { ShadowGenerator } from \"./shadowGenerator.js\";\nimport { CascadedShadowGenerator } from \"./cascadedShadowGenerator.js\";\nimport { SceneComponentConstants } from \"../../sceneComponent.js\";\nimport { AbstractScene } from \"../../abstractScene.js\";\n// Adds the parser to the scene parsers.\nAbstractScene.AddParser(SceneComponentConstants.NAME_SHADOWGENERATOR, (parsedData, scene) => {\n // Shadows\n if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {\n for (let index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {\n const parsedShadowGenerator = parsedData.shadowGenerators[index];\n if (parsedShadowGenerator.className === CascadedShadowGenerator.CLASSNAME) {\n CascadedShadowGenerator.Parse(parsedShadowGenerator, scene);\n }\n else {\n ShadowGenerator.Parse(parsedShadowGenerator, scene);\n }\n // SG would be available on their associated lights\n }\n }\n});\n/**\n * Defines the shadow generator component responsible to manage any shadow generators\n * in a given scene.\n */\nexport class ShadowGeneratorSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpful to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_SHADOWGENERATOR;\n this.scene = scene;\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene._gatherRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n // Nothing To Do Here.\n }\n /**\n * Serializes the component data to the specified json object\n * @param serializationObject The object to serialize to\n */\n serialize(serializationObject) {\n // Shadows\n serializationObject.shadowGenerators = [];\n const lights = this.scene.lights;\n for (const light of lights) {\n const shadowGenerators = light.getShadowGenerators();\n if (shadowGenerators) {\n const iterator = shadowGenerators.values();\n for (let key = iterator.next(); key.done !== true; key = iterator.next()) {\n const shadowGenerator = key.value;\n serializationObject.shadowGenerators.push(shadowGenerator.serialize());\n }\n }\n }\n }\n /**\n * Adds all the elements from the container to the scene\n * @param container the container holding the elements\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n addFromContainer(container) {\n // Nothing To Do Here. (directly attached to a light)\n }\n /**\n * Removes all the elements in the container from the scene\n * @param container contains the elements to remove\n * @param dispose if the removed element should be disposed (default: false)\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n removeFromContainer(container, dispose) {\n // Nothing To Do Here. (directly attached to a light)\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n dispose() {\n // Nothing To Do Here.\n }\n _gatherRenderTargets(renderTargets) {\n // Shadows\n const scene = this.scene;\n if (this.scene.shadowsEnabled) {\n for (let lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {\n const light = scene.lights[lightIndex];\n const shadowGenerators = light.getShadowGenerators();\n if (light.isEnabled() && light.shadowEnabled && shadowGenerators) {\n const iterator = shadowGenerators.values();\n for (let key = iterator.next(); key.done !== true; key = iterator.next()) {\n const shadowGenerator = key.value;\n const shadowMap = shadowGenerator.getShadowMap();\n if (scene.textures.indexOf(shadowMap) !== -1) {\n renderTargets.push(shadowMap);\n }\n }\n }\n }\n }\n }\n}\nShadowGenerator._SceneComponentInitialization = (scene) => {\n let component = scene._getComponent(SceneComponentConstants.NAME_SHADOWGENERATOR);\n if (!component) {\n component = new ShadowGeneratorSceneComponent(scene);\n scene._addComponent(component);\n }\n};\n//# sourceMappingURL=shadowGeneratorSceneComponent.js.map","export * from \"./shadowGenerator.js\";\nexport * from \"./cascadedShadowGenerator.js\";\nexport * from \"./shadowGeneratorSceneComponent.js\";\n//# sourceMappingURL=index.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize } from \"../Misc/decorators.js\";\nimport { Matrix, Vector3 } from \"../Maths/math.vector.js\";\nimport { Node } from \"../node.js\";\nimport { Light } from \"./light.js\";\nimport { ShadowLight } from \"./shadowLight.js\";\nNode.AddNodeConstructor(\"Light_Type_0\", (name, scene) => {\n return () => new PointLight(name, Vector3.Zero(), scene);\n});\n/**\n * A point light is a light defined by an unique point in world space.\n * The light is emitted in every direction from this point.\n * A good example of a point light is a standard light bulb.\n * Documentation: https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction\n */\nexport class PointLight extends ShadowLight {\n /**\n * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback\n * This specifies what angle the shadow will use to be created.\n *\n * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.\n */\n get shadowAngle() {\n return this._shadowAngle;\n }\n /**\n * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback\n * This specifies what angle the shadow will use to be created.\n *\n * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.\n */\n set shadowAngle(value) {\n this._shadowAngle = value;\n this.forceProjectionMatrixCompute();\n }\n /**\n * Gets the direction if it has been set.\n * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback\n */\n get direction() {\n return this._direction;\n }\n /**\n * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback\n */\n set direction(value) {\n const previousNeedCube = this.needCube();\n this._direction = value;\n if (this.needCube() !== previousNeedCube && this._shadowGenerators) {\n const iterator = this._shadowGenerators.values();\n for (let key = iterator.next(); key.done !== true; key = iterator.next()) {\n const shadowGenerator = key.value;\n shadowGenerator.recreateShadowMap();\n }\n }\n }\n /**\n * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.\n * A PointLight emits the light in every direction.\n * It can cast shadows.\n * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :\n * ```javascript\n * var pointLight = new PointLight(\"pl\", camera.position, scene);\n * ```\n * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction\n * @param name The light friendly name\n * @param position The position of the point light in the scene\n * @param scene The scene the lights belongs to\n */\n constructor(name, position, scene) {\n super(name, scene);\n this._shadowAngle = Math.PI / 2;\n this.position = position;\n }\n /**\n * Returns the string \"PointLight\"\n * @returns the class name\n */\n getClassName() {\n return \"PointLight\";\n }\n /**\n * Returns the integer 0.\n * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x\n */\n getTypeID() {\n return Light.LIGHTTYPEID_POINTLIGHT;\n }\n /**\n * Specifies whether or not the shadowmap should be a cube texture.\n * @returns true if the shadowmap needs to be a cube texture.\n */\n needCube() {\n return !this.direction;\n }\n /**\n * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).\n * @param faceIndex The index of the face we are computed the direction to generate shadow\n * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true\n */\n getShadowDirection(faceIndex) {\n if (this.direction) {\n return super.getShadowDirection(faceIndex);\n }\n else {\n switch (faceIndex) {\n case 0:\n return new Vector3(1.0, 0.0, 0.0);\n case 1:\n return new Vector3(-1.0, 0.0, 0.0);\n case 2:\n return new Vector3(0.0, -1.0, 0.0);\n case 3:\n return new Vector3(0.0, 1.0, 0.0);\n case 4:\n return new Vector3(0.0, 0.0, 1.0);\n case 5:\n return new Vector3(0.0, 0.0, -1.0);\n }\n }\n return Vector3.Zero();\n }\n /**\n * Sets the passed matrix \"matrix\" as a left-handed perspective projection matrix with the following settings :\n * - fov = PI / 2\n * - aspect ratio : 1.0\n * - z-near and far equal to the active camera minZ and maxZ.\n * Returns the PointLight.\n * @param matrix\n * @param viewMatrix\n * @param renderList\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList) {\n const activeCamera = this.getScene().activeCamera;\n if (!activeCamera) {\n return;\n }\n const minZ = this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;\n const maxZ = this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;\n const useReverseDepthBuffer = this.getScene().getEngine().useReverseDepthBuffer;\n Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, useReverseDepthBuffer ? maxZ : minZ, useReverseDepthBuffer ? minZ : maxZ, matrix, true, this._scene.getEngine().isNDCHalfZRange, undefined, useReverseDepthBuffer);\n }\n _buildUniformLayout() {\n this._uniformBuffer.addUniform(\"vLightData\", 4);\n this._uniformBuffer.addUniform(\"vLightDiffuse\", 4);\n this._uniformBuffer.addUniform(\"vLightSpecular\", 4);\n this._uniformBuffer.addUniform(\"vLightFalloff\", 4);\n this._uniformBuffer.addUniform(\"shadowsInfo\", 3);\n this._uniformBuffer.addUniform(\"depthValues\", 2);\n this._uniformBuffer.create();\n }\n /**\n * Sets the passed Effect \"effect\" with the PointLight transformed position (or position, if none) and passed name (string).\n * @param effect The effect to update\n * @param lightIndex The index of the light in the effect to update\n * @returns The point light\n */\n transferToEffect(effect, lightIndex) {\n if (this.computeTransformedInformation()) {\n this._uniformBuffer.updateFloat4(\"vLightData\", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);\n }\n else {\n this._uniformBuffer.updateFloat4(\"vLightData\", this.position.x, this.position.y, this.position.z, 0, lightIndex);\n }\n this._uniformBuffer.updateFloat4(\"vLightFalloff\", this.range, this._inverseSquaredRange, 0, 0, lightIndex);\n return this;\n }\n transferToNodeMaterialEffect(effect, lightDataUniformName) {\n if (this.computeTransformedInformation()) {\n effect.setFloat3(lightDataUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z);\n }\n else {\n effect.setFloat3(lightDataUniformName, this.position.x, this.position.y, this.position.z);\n }\n return this;\n }\n /**\n * Prepares the list of defines specific to the light type.\n * @param defines the list of defines\n * @param lightIndex defines the index of the light for the effect\n */\n prepareLightSpecificDefines(defines, lightIndex) {\n defines[\"POINTLIGHT\" + lightIndex] = true;\n }\n}\n__decorate([\n serialize()\n], PointLight.prototype, \"shadowAngle\", null);\n//# sourceMappingURL=pointLight.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./light.js\";\nexport * from \"./shadowLight.js\";\nexport * from \"./Shadows/index.js\";\nexport * from \"./directionalLight.js\";\nexport * from \"./hemisphericLight.js\";\nexport * from \"./pointLight.js\";\nexport * from \"./spotLight.js\";\n//# sourceMappingURL=index.js.map","import { Engine } from \"../Engines/engine.js\";\n/**\n * Class used for the default loading screen\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen\n */\nexport class DefaultLoadingScreen {\n /**\n * Creates a new default loading screen\n * @param _renderingCanvas defines the canvas used to render the scene\n * @param _loadingText defines the default text to display\n * @param _loadingDivBackgroundColor defines the default background color\n */\n constructor(_renderingCanvas, _loadingText = \"\", _loadingDivBackgroundColor = \"black\") {\n this._renderingCanvas = _renderingCanvas;\n this._loadingText = _loadingText;\n this._loadingDivBackgroundColor = _loadingDivBackgroundColor;\n // Resize\n this._resizeLoadingUI = () => {\n const canvasRect = this._renderingCanvas.getBoundingClientRect();\n const canvasPositioning = window.getComputedStyle(this._renderingCanvas).position;\n if (!this._loadingDiv) {\n return;\n }\n this._loadingDiv.style.position = canvasPositioning === \"fixed\" ? \"fixed\" : \"absolute\";\n this._loadingDiv.style.left = canvasRect.left + \"px\";\n this._loadingDiv.style.top = canvasRect.top + \"px\";\n this._loadingDiv.style.width = canvasRect.width + \"px\";\n this._loadingDiv.style.height = canvasRect.height + \"px\";\n };\n }\n /**\n * Function called to display the loading screen\n */\n displayLoadingUI() {\n if (this._loadingDiv) {\n // Do not add a loading screen if there is already one\n return;\n }\n this._loadingDiv = document.createElement(\"div\");\n this._loadingDiv.id = \"babylonjsLoadingDiv\";\n this._loadingDiv.style.opacity = \"0\";\n this._loadingDiv.style.transition = \"opacity 1.5s ease\";\n this._loadingDiv.style.pointerEvents = \"none\";\n this._loadingDiv.style.display = \"grid\";\n this._loadingDiv.style.gridTemplateRows = \"100%\";\n this._loadingDiv.style.gridTemplateColumns = \"100%\";\n this._loadingDiv.style.justifyItems = \"center\";\n this._loadingDiv.style.alignItems = \"center\";\n // Loading text\n this._loadingTextDiv = document.createElement(\"div\");\n this._loadingTextDiv.style.position = \"absolute\";\n this._loadingTextDiv.style.left = \"0\";\n this._loadingTextDiv.style.top = \"50%\";\n this._loadingTextDiv.style.marginTop = \"80px\";\n this._loadingTextDiv.style.width = \"100%\";\n this._loadingTextDiv.style.height = \"20px\";\n this._loadingTextDiv.style.fontFamily = \"Arial\";\n this._loadingTextDiv.style.fontSize = \"14px\";\n this._loadingTextDiv.style.color = \"white\";\n this._loadingTextDiv.style.textAlign = \"center\";\n this._loadingTextDiv.style.zIndex = \"1\";\n this._loadingTextDiv.innerHTML = \"Loading\";\n this._loadingDiv.appendChild(this._loadingTextDiv);\n //set the predefined text\n this._loadingTextDiv.innerHTML = this._loadingText;\n // Generating keyframes\n this._style = document.createElement(\"style\");\n this._style.type = \"text/css\";\n const keyFrames = `@-webkit-keyframes spin1 {\\\r\n 0% { -webkit-transform: rotate(0deg);}\r\n 100% { -webkit-transform: rotate(360deg);}\r\n }\\\r\n @keyframes spin1 {\\\r\n 0% { transform: rotate(0deg);}\r\n 100% { transform: rotate(360deg);}\r\n }`;\n this._style.innerHTML = keyFrames;\n document.getElementsByTagName(\"head\")[0].appendChild(this._style);\n const svgSupport = !!window.SVGSVGElement;\n // Loading img\n const imgBack = new Image();\n if (!DefaultLoadingScreen.DefaultLogoUrl) {\n imgBack.src = !svgSupport\n ? \"https://cdn.babylonjs.com/Assets/babylonLogo.png\"\n : `data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+`;\n }\n else {\n imgBack.src = DefaultLoadingScreen.DefaultLogoUrl;\n }\n imgBack.style.width = \"150px\";\n imgBack.style.gridColumn = \"1\";\n imgBack.style.gridRow = \"1\";\n imgBack.style.top = \"50%\";\n imgBack.style.left = \"50%\";\n imgBack.style.transform = \"translate(-50%, -50%)\";\n imgBack.style.position = \"absolute\";\n const imageSpinnerContainer = document.createElement(\"div\");\n imageSpinnerContainer.style.width = \"300px\";\n imageSpinnerContainer.style.gridColumn = \"1\";\n imageSpinnerContainer.style.gridRow = \"1\";\n imageSpinnerContainer.style.top = \"50%\";\n imageSpinnerContainer.style.left = \"50%\";\n imageSpinnerContainer.style.transform = \"translate(-50%, -50%)\";\n imageSpinnerContainer.style.position = \"absolute\";\n // Loading spinner\n const imgSpinner = new Image();\n if (!DefaultLoadingScreen.DefaultSpinnerUrl) {\n imgSpinner.src = !svgSupport\n ? \"https://cdn.babylonjs.com/Assets/loadingIcon.png\"\n : `data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==`;\n }\n else {\n imgSpinner.src = DefaultLoadingScreen.DefaultSpinnerUrl;\n }\n imgSpinner.style.animation = \"spin1 0.75s infinite linear\";\n imgSpinner.style.webkitAnimation = \"spin1 0.75s infinite linear\";\n imgSpinner.style.transformOrigin = \"50% 50%\";\n imgSpinner.style.webkitTransformOrigin = \"50% 50%\";\n if (!svgSupport) {\n const logoSize = { w: 16, h: 18.5 };\n const loadingSize = { w: 30, h: 30 };\n // set styling correctly\n imgBack.style.width = `${logoSize.w}vh`;\n imgBack.style.height = `${logoSize.h}vh`;\n imgBack.style.left = `calc(50% - ${logoSize.w / 2}vh)`;\n imgBack.style.top = `calc(50% - ${logoSize.h / 2}vh)`;\n imgSpinner.style.width = `${loadingSize.w}vh`;\n imgSpinner.style.height = `${loadingSize.h}vh`;\n imgSpinner.style.left = `calc(50% - ${loadingSize.w / 2}vh)`;\n imgSpinner.style.top = `calc(50% - ${loadingSize.h / 2}vh)`;\n }\n imageSpinnerContainer.appendChild(imgSpinner);\n this._loadingDiv.appendChild(imgBack);\n this._loadingDiv.appendChild(imageSpinnerContainer);\n this._resizeLoadingUI();\n window.addEventListener(\"resize\", this._resizeLoadingUI);\n this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;\n document.body.appendChild(this._loadingDiv);\n this._loadingDiv.style.opacity = \"1\";\n }\n /**\n * Function called to hide the loading screen\n */\n hideLoadingUI() {\n if (!this._loadingDiv) {\n return;\n }\n const onTransitionEnd = () => {\n if (this._loadingTextDiv) {\n this._loadingTextDiv.remove();\n this._loadingTextDiv = null;\n }\n if (this._loadingDiv) {\n this._loadingDiv.remove();\n this._loadingDiv = null;\n }\n if (this._style) {\n this._style.remove();\n this._style = null;\n }\n window.removeEventListener(\"resize\", this._resizeLoadingUI);\n };\n this._loadingDiv.style.opacity = \"0\";\n this._loadingDiv.addEventListener(\"transitionend\", onTransitionEnd);\n }\n /**\n * Gets or sets the text to display while loading\n */\n set loadingUIText(text) {\n this._loadingText = text;\n if (this._loadingTextDiv) {\n this._loadingTextDiv.innerHTML = this._loadingText;\n }\n }\n get loadingUIText() {\n return this._loadingText;\n }\n /**\n * Gets or sets the color to use for the background\n */\n get loadingUIBackgroundColor() {\n return this._loadingDivBackgroundColor;\n }\n set loadingUIBackgroundColor(color) {\n this._loadingDivBackgroundColor = color;\n if (!this._loadingDiv) {\n return;\n }\n this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;\n }\n}\n/** Gets or sets the logo url to use for the default loading screen */\nDefaultLoadingScreen.DefaultLogoUrl = \"\";\n/** Gets or sets the spinner url to use for the default loading screen */\nDefaultLoadingScreen.DefaultSpinnerUrl = \"\";\nEngine.DefaultLoadingScreenFactory = (canvas) => {\n return new DefaultLoadingScreen(canvas);\n};\n//# sourceMappingURL=loadingScreen.js.map","import { Vector3 } from \"../../Maths/math.vector.js\";\n\n/**\n * Helper class useful to convert panorama picture to their cubemap representation in 6 faces.\n */\nexport class PanoramaToCubeMapTools {\n /**\n * Converts a panorama stored in RGB right to left up to down format into a cubemap (6 faces).\n *\n * @param float32Array The source data.\n * @param inputWidth The width of the input panorama.\n * @param inputHeight The height of the input panorama.\n * @param size The willing size of the generated cubemap (each faces will be size * size pixels)\n * @returns The cubemap data\n */\n static ConvertPanoramaToCubemap(float32Array, inputWidth, inputHeight, size, supersample = false) {\n if (!float32Array) {\n throw \"ConvertPanoramaToCubemap: input cannot be null\";\n }\n if (float32Array.length != inputWidth * inputHeight * 3) {\n throw \"ConvertPanoramaToCubemap: input size is wrong\";\n }\n const textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight, supersample);\n const textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight, supersample);\n const textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight, supersample);\n const textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight, supersample);\n const textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight, supersample);\n const textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight, supersample);\n return {\n front: textureFront,\n back: textureBack,\n left: textureLeft,\n right: textureRight,\n up: textureUp,\n down: textureDown,\n size: size,\n type: 1,\n format: 4,\n gammaSpace: false,\n };\n }\n static CreateCubemapTexture(texSize, faceData, float32Array, inputWidth, inputHeight, supersample = false) {\n const buffer = new ArrayBuffer(texSize * texSize * 4 * 3);\n const textureArray = new Float32Array(buffer);\n // If supersampling, determine number of samples needed when source texture width is divided for 4 cube faces\n const samples = supersample ? Math.max(1, Math.round(inputWidth / 4 / texSize)) : 1;\n const sampleFactor = 1 / samples;\n const sampleFactorSqr = sampleFactor * sampleFactor;\n const rotDX1 = faceData[1].subtract(faceData[0]).scale(sampleFactor / texSize);\n const rotDX2 = faceData[3].subtract(faceData[2]).scale(sampleFactor / texSize);\n const dy = 1 / texSize;\n let fy = 0;\n for (let y = 0; y < texSize; y++) {\n for (let sy = 0; sy < samples; sy++) {\n let xv1 = faceData[0];\n let xv2 = faceData[2];\n for (let x = 0; x < texSize; x++) {\n for (let sx = 0; sx < samples; sx++) {\n const v = xv2.subtract(xv1).scale(fy).add(xv1);\n v.normalize();\n const color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);\n // 3 channels per pixels\n textureArray[y * texSize * 3 + x * 3 + 0] += color.r * sampleFactorSqr;\n textureArray[y * texSize * 3 + x * 3 + 1] += color.g * sampleFactorSqr;\n textureArray[y * texSize * 3 + x * 3 + 2] += color.b * sampleFactorSqr;\n xv1 = xv1.add(rotDX1);\n xv2 = xv2.add(rotDX2);\n }\n }\n fy += dy * sampleFactor;\n }\n }\n return textureArray;\n }\n static CalcProjectionSpherical(vDir, float32Array, inputWidth, inputHeight) {\n let theta = Math.atan2(vDir.z, vDir.x);\n const phi = Math.acos(vDir.y);\n while (theta < -Math.PI) {\n theta += 2 * Math.PI;\n }\n while (theta > Math.PI) {\n theta -= 2 * Math.PI;\n }\n let dx = theta / Math.PI;\n const dy = phi / Math.PI;\n // recenter.\n dx = dx * 0.5 + 0.5;\n let px = Math.round(dx * inputWidth);\n if (px < 0) {\n px = 0;\n }\n else if (px >= inputWidth) {\n px = inputWidth - 1;\n }\n let py = Math.round(dy * inputHeight);\n if (py < 0) {\n py = 0;\n }\n else if (py >= inputHeight) {\n py = inputHeight - 1;\n }\n const inputY = inputHeight - py - 1;\n const r = float32Array[inputY * inputWidth * 3 + px * 3 + 0];\n const g = float32Array[inputY * inputWidth * 3 + px * 3 + 1];\n const b = float32Array[inputY * inputWidth * 3 + px * 3 + 2];\n return {\n r: r,\n g: g,\n b: b,\n };\n }\n}\nPanoramaToCubeMapTools.FACE_LEFT = [new Vector3(-1.0, -1.0, -1.0), new Vector3(1.0, -1.0, -1.0), new Vector3(-1.0, 1.0, -1.0), new Vector3(1.0, 1.0, -1.0)];\nPanoramaToCubeMapTools.FACE_RIGHT = [new Vector3(1.0, -1.0, 1.0), new Vector3(-1.0, -1.0, 1.0), new Vector3(1.0, 1.0, 1.0), new Vector3(-1.0, 1.0, 1.0)];\nPanoramaToCubeMapTools.FACE_FRONT = [new Vector3(1.0, -1.0, -1.0), new Vector3(1.0, -1.0, 1.0), new Vector3(1.0, 1.0, -1.0), new Vector3(1.0, 1.0, 1.0)];\nPanoramaToCubeMapTools.FACE_BACK = [new Vector3(-1.0, -1.0, 1.0), new Vector3(-1.0, -1.0, -1.0), new Vector3(-1.0, 1.0, 1.0), new Vector3(-1.0, 1.0, -1.0)];\nPanoramaToCubeMapTools.FACE_DOWN = [new Vector3(1.0, 1.0, -1.0), new Vector3(1.0, 1.0, 1.0), new Vector3(-1.0, 1.0, -1.0), new Vector3(-1.0, 1.0, 1.0)];\nPanoramaToCubeMapTools.FACE_UP = [new Vector3(-1.0, -1.0, -1.0), new Vector3(-1.0, -1.0, 1.0), new Vector3(1.0, -1.0, -1.0), new Vector3(1.0, -1.0, 1.0)];\n//# sourceMappingURL=panoramaToCubemap.js.map","import { PanoramaToCubeMapTools } from \"./panoramaToCubemap.js\";\n/**\n * This groups tools to convert HDR texture to native colors array.\n */\nexport class HDRTools {\n static _Ldexp(mantissa, exponent) {\n if (exponent > 1023) {\n return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);\n }\n if (exponent < -1074) {\n return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);\n }\n return mantissa * Math.pow(2, exponent);\n }\n static _Rgbe2float(float32array, red, green, blue, exponent, index) {\n if (exponent > 0) {\n /*nonzero pixel*/\n exponent = this._Ldexp(1.0, exponent - (128 + 8));\n float32array[index + 0] = red * exponent;\n float32array[index + 1] = green * exponent;\n float32array[index + 2] = blue * exponent;\n }\n else {\n float32array[index + 0] = 0;\n float32array[index + 1] = 0;\n float32array[index + 2] = 0;\n }\n }\n static _ReadStringLine(uint8array, startIndex) {\n let line = \"\";\n let character = \"\";\n for (let i = startIndex; i < uint8array.length - startIndex; i++) {\n character = String.fromCharCode(uint8array[i]);\n if (character == \"\\n\") {\n break;\n }\n line += character;\n }\n return line;\n }\n /**\n * Reads header information from an RGBE texture stored in a native array.\n * More information on this format are available here:\n * https://en.wikipedia.org/wiki/RGBE_image_format\n *\n * @param uint8array The binary file stored in native array.\n * @returns The header information.\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static RGBE_ReadHeader(uint8array) {\n let height = 0;\n let width = 0;\n let line = this._ReadStringLine(uint8array, 0);\n if (line[0] != \"#\" || line[1] != \"?\") {\n throw \"Bad HDR Format.\";\n }\n let endOfHeader = false;\n let findFormat = false;\n let lineIndex = 0;\n do {\n lineIndex += line.length + 1;\n line = this._ReadStringLine(uint8array, lineIndex);\n if (line == \"FORMAT=32-bit_rle_rgbe\") {\n findFormat = true;\n }\n else if (line.length == 0) {\n endOfHeader = true;\n }\n } while (!endOfHeader);\n if (!findFormat) {\n throw \"HDR Bad header format, unsupported FORMAT\";\n }\n lineIndex += line.length + 1;\n line = this._ReadStringLine(uint8array, lineIndex);\n const sizeRegexp = /^-Y (.*) \\+X (.*)$/g;\n const match = sizeRegexp.exec(line);\n // TODO. Support +Y and -X if needed.\n if (!match || match.length < 3) {\n throw \"HDR Bad header format, no size\";\n }\n width = parseInt(match[2]);\n height = parseInt(match[1]);\n if (width < 8 || width > 0x7fff) {\n throw \"HDR Bad header format, unsupported size\";\n }\n lineIndex += line.length + 1;\n return {\n height: height,\n width: width,\n dataPosition: lineIndex,\n };\n }\n /**\n * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.\n * This RGBE texture needs to store the information as a panorama.\n *\n * More information on this format are available here:\n * https://en.wikipedia.org/wiki/RGBE_image_format\n *\n * @param buffer The binary file stored in an array buffer.\n * @param size The expected size of the extracted cubemap.\n * @returns The Cube Map information.\n */\n static GetCubeMapTextureData(buffer, size, supersample = false) {\n const uint8array = new Uint8Array(buffer);\n const hdrInfo = this.RGBE_ReadHeader(uint8array);\n const data = this.RGBE_ReadPixels(uint8array, hdrInfo);\n const cubeMapData = PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size, supersample);\n return cubeMapData;\n }\n /**\n * Returns the pixels data extracted from an RGBE texture.\n * This pixels will be stored left to right up to down in the R G B order in one array.\n *\n * More information on this format are available here:\n * https://en.wikipedia.org/wiki/RGBE_image_format\n *\n * @param uint8array The binary file stored in an array buffer.\n * @param hdrInfo The header information of the file.\n * @returns The pixels data in RGB right to left up to down order.\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static RGBE_ReadPixels(uint8array, hdrInfo) {\n return this._RGBEReadPixelsRLE(uint8array, hdrInfo);\n }\n static _RGBEReadPixelsRLE(uint8array, hdrInfo) {\n let num_scanlines = hdrInfo.height;\n const scanline_width = hdrInfo.width;\n let a, b, c, d, count;\n let dataIndex = hdrInfo.dataPosition;\n let index = 0, endIndex = 0, i = 0;\n const scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E\n const scanLineArray = new Uint8Array(scanLineArrayBuffer);\n // 3 channels of 4 bytes per pixel in float.\n const resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);\n const resultArray = new Float32Array(resultBuffer);\n // read in each successive scanline\n while (num_scanlines > 0) {\n a = uint8array[dataIndex++];\n b = uint8array[dataIndex++];\n c = uint8array[dataIndex++];\n d = uint8array[dataIndex++];\n if (a != 2 || b != 2 || c & 0x80 || hdrInfo.width < 8 || hdrInfo.width > 32767) {\n return this._RGBEReadPixelsNOTRLE(uint8array, hdrInfo);\n }\n if (((c << 8) | d) != scanline_width) {\n throw \"HDR Bad header format, wrong scan line width\";\n }\n index = 0;\n // read each of the four channels for the scanline into the buffer\n for (i = 0; i < 4; i++) {\n endIndex = (i + 1) * scanline_width;\n while (index < endIndex) {\n a = uint8array[dataIndex++];\n b = uint8array[dataIndex++];\n if (a > 128) {\n // a run of the same value\n count = a - 128;\n if (count == 0 || count > endIndex - index) {\n throw \"HDR Bad Format, bad scanline data (run)\";\n }\n while (count-- > 0) {\n scanLineArray[index++] = b;\n }\n }\n else {\n // a non-run\n count = a;\n if (count == 0 || count > endIndex - index) {\n throw \"HDR Bad Format, bad scanline data (non-run)\";\n }\n scanLineArray[index++] = b;\n if (--count > 0) {\n for (let j = 0; j < count; j++) {\n scanLineArray[index++] = uint8array[dataIndex++];\n }\n }\n }\n }\n }\n // now convert data from buffer into floats\n for (i = 0; i < scanline_width; i++) {\n a = scanLineArray[i];\n b = scanLineArray[i + scanline_width];\n c = scanLineArray[i + 2 * scanline_width];\n d = scanLineArray[i + 3 * scanline_width];\n this._Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);\n }\n num_scanlines--;\n }\n return resultArray;\n }\n static _RGBEReadPixelsNOTRLE(uint8array, hdrInfo) {\n // this file is not run length encoded\n // read values sequentially\n let num_scanlines = hdrInfo.height;\n const scanline_width = hdrInfo.width;\n let a, b, c, d, i;\n let dataIndex = hdrInfo.dataPosition;\n // 3 channels of 4 bytes per pixel in float.\n const resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);\n const resultArray = new Float32Array(resultBuffer);\n // read in each successive scanline\n while (num_scanlines > 0) {\n for (i = 0; i < hdrInfo.width; i++) {\n a = uint8array[dataIndex++];\n b = uint8array[dataIndex++];\n c = uint8array[dataIndex++];\n d = uint8array[dataIndex++];\n this._Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);\n }\n num_scanlines--;\n }\n return resultArray;\n }\n}\n//# sourceMappingURL=hdr.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"hdrFilteringVertexShader\";\nconst shader = `attribute vec2 position;\rvarying vec3 direction;\runiform vec3 up;\runiform vec3 right;\runiform vec3 front;\r#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_VERTEX_MAIN_BEGIN\nmat3 view=mat3(up,right,front);\rdirection=view*vec3(position,1.0);\rgl_Position=vec4(position,0.0,1.0);\r#define CUSTOM_VERTEX_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const hdrFilteringVertexShader = { name, shader };\n//# sourceMappingURL=hdrFiltering.vertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/helperFunctions.js\";\nimport \"./ShadersInclude/importanceSampling.js\";\nimport \"./ShadersInclude/pbrBRDFFunctions.js\";\nimport \"./ShadersInclude/hdrFilteringFunctions.js\";\nconst name = \"hdrFilteringPixelShader\";\nconst shader = `#include\n#include\n#include\n#include\nuniform float alphaG;\runiform samplerCube inputTexture;\runiform vec2 vFilteringInfo;\runiform float hdrScale;\rvarying vec3 direction;\rvoid main() {\rvec3 color=radiance(alphaG,inputTexture,direction,vFilteringInfo);\rgl_FragColor=vec4(color*hdrScale,1.0);\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const hdrFilteringPixelShader = { name, shader };\n//# sourceMappingURL=hdrFiltering.fragment.js.map","import { Vector3 } from \"../../../Maths/math.js\";\nimport { Scalar } from \"../../../Maths/math.scalar.js\";\n\nimport { EffectWrapper, EffectRenderer } from \"../../../Materials/effectRenderer.js\";\nimport \"../../../Shaders/hdrFiltering.vertex.js\";\nimport \"../../../Shaders/hdrFiltering.fragment.js\";\nimport { Logger } from \"../../../Misc/logger.js\";\n/**\n * Filters HDR maps to get correct renderings of PBR reflections\n */\nexport class HDRFiltering {\n /**\n * Instantiates HDR filter for reflection maps\n *\n * @param engine Thin engine\n * @param options Options\n */\n constructor(engine, options = {}) {\n this._lodGenerationOffset = 0;\n this._lodGenerationScale = 0.8;\n /**\n * Quality switch for prefiltering. Should be set to `4096` unless\n * you care about baking speed.\n */\n this.quality = 4096;\n /**\n * Scales pixel intensity for the input HDR map.\n */\n this.hdrScale = 1;\n // pass\n this._engine = engine;\n this.hdrScale = options.hdrScale || this.hdrScale;\n this.quality = options.quality || this.quality;\n }\n _createRenderTarget(size) {\n let textureType = 0;\n if (this._engine.getCaps().textureHalfFloatRender) {\n textureType = 2;\n }\n else if (this._engine.getCaps().textureFloatRender) {\n textureType = 1;\n }\n const rtWrapper = this._engine.createRenderTargetCubeTexture(size, {\n format: 5,\n type: textureType,\n createMipMaps: true,\n generateMipMaps: false,\n generateDepthBuffer: false,\n generateStencilBuffer: false,\n samplingMode: 1,\n });\n this._engine.updateTextureWrappingMode(rtWrapper.texture, 0, 0, 0);\n this._engine.updateTextureSamplingMode(3, rtWrapper.texture, true);\n return rtWrapper;\n }\n _prefilterInternal(texture) {\n const width = texture.getSize().width;\n const mipmapsCount = Scalar.ILog2(width) + 1;\n const effect = this._effectWrapper.effect;\n const outputTexture = this._createRenderTarget(width);\n this._effectRenderer.setViewport();\n const intTexture = texture.getInternalTexture();\n if (intTexture) {\n // Just in case generate fresh clean mips.\n this._engine.updateTextureSamplingMode(3, intTexture, true);\n }\n this._effectRenderer.applyEffectWrapper(this._effectWrapper);\n const directions = [\n [new Vector3(0, 0, -1), new Vector3(0, -1, 0), new Vector3(1, 0, 0)],\n [new Vector3(0, 0, 1), new Vector3(0, -1, 0), new Vector3(-1, 0, 0)],\n [new Vector3(1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 1, 0)],\n [new Vector3(1, 0, 0), new Vector3(0, 0, -1), new Vector3(0, -1, 0)],\n [new Vector3(1, 0, 0), new Vector3(0, -1, 0), new Vector3(0, 0, 1)],\n [new Vector3(-1, 0, 0), new Vector3(0, -1, 0), new Vector3(0, 0, -1)], // NegativeZ\n ];\n effect.setFloat(\"hdrScale\", this.hdrScale);\n effect.setFloat2(\"vFilteringInfo\", texture.getSize().width, mipmapsCount);\n effect.setTexture(\"inputTexture\", texture);\n for (let face = 0; face < 6; face++) {\n effect.setVector3(\"up\", directions[face][0]);\n effect.setVector3(\"right\", directions[face][1]);\n effect.setVector3(\"front\", directions[face][2]);\n for (let lod = 0; lod < mipmapsCount; lod++) {\n this._engine.bindFramebuffer(outputTexture, face, undefined, undefined, true, lod);\n this._effectRenderer.applyEffectWrapper(this._effectWrapper);\n let alpha = Math.pow(2, (lod - this._lodGenerationOffset) / this._lodGenerationScale) / width;\n if (lod === 0) {\n alpha = 0;\n }\n effect.setFloat(\"alphaG\", alpha);\n this._effectRenderer.draw();\n }\n }\n // Cleanup\n this._effectRenderer.restoreStates();\n this._engine.restoreDefaultFramebuffer();\n this._engine._releaseTexture(texture._texture);\n // Internal Swap\n const type = outputTexture.texture.type;\n const format = outputTexture.texture.format;\n outputTexture._swapAndDie(texture._texture);\n texture._texture.type = type;\n texture._texture.format = format;\n // New settings\n texture.gammaSpace = false;\n texture.lodGenerationOffset = this._lodGenerationOffset;\n texture.lodGenerationScale = this._lodGenerationScale;\n texture._prefiltered = true;\n return texture;\n }\n _createEffect(texture, onCompiled) {\n const defines = [];\n if (texture.gammaSpace) {\n defines.push(\"#define GAMMA_INPUT\");\n }\n defines.push(\"#define NUM_SAMPLES \" + this.quality + \"u\"); // unsigned int\n const effectWrapper = new EffectWrapper({\n engine: this._engine,\n name: \"hdrFiltering\",\n vertexShader: \"hdrFiltering\",\n fragmentShader: \"hdrFiltering\",\n samplerNames: [\"inputTexture\"],\n uniformNames: [\"vSampleDirections\", \"vWeights\", \"up\", \"right\", \"front\", \"vFilteringInfo\", \"hdrScale\", \"alphaG\"],\n useShaderStore: true,\n defines,\n onCompiled: onCompiled,\n });\n return effectWrapper;\n }\n /**\n * Get a value indicating if the filter is ready to be used\n * @param texture Texture to filter\n * @returns true if the filter is ready\n */\n isReady(texture) {\n return texture.isReady() && this._effectWrapper.effect.isReady();\n }\n /**\n * Prefilters a cube texture to have mipmap levels representing roughness values.\n * Prefiltering will be invoked at the end of next rendering pass.\n * This has to be done once the map is loaded, and has not been prefiltered by a third party software.\n * See http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf for more information\n * @param texture Texture to filter\n * @param onFinished Callback when filtering is done\n * @returns Promise called when prefiltering is done\n */\n prefilter(texture, onFinished = null) {\n if (!this._engine._features.allowTexturePrefiltering) {\n Logger.Warn(\"HDR prefiltering is not available in WebGL 1., you can use real time filtering instead.\");\n return Promise.reject(\"HDR prefiltering is not available in WebGL 1., you can use real time filtering instead.\");\n }\n return new Promise((resolve) => {\n this._effectRenderer = new EffectRenderer(this._engine);\n this._effectWrapper = this._createEffect(texture);\n this._effectWrapper.effect.executeWhenCompiled(() => {\n this._prefilterInternal(texture);\n this._effectRenderer.dispose();\n this._effectWrapper.dispose();\n resolve();\n if (onFinished) {\n onFinished();\n }\n });\n });\n }\n}\n//# sourceMappingURL=hdrFiltering.js.map","import { Matrix, Vector3 } from \"../../Maths/math.vector.js\";\nimport { BaseTexture } from \"../../Materials/Textures/baseTexture.js\";\nimport { Texture } from \"../../Materials/Textures/texture.js\";\n\nimport { HDRTools } from \"../../Misc/HighDynamicRange/hdr.js\";\nimport { CubeMapToSphericalPolynomialTools } from \"../../Misc/HighDynamicRange/cubemapToSphericalPolynomial.js\";\nimport { RegisterClass } from \"../../Misc/typeStore.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nimport { ToGammaSpace } from \"../../Maths/math.constants.js\";\nimport { HDRFiltering } from \"../../Materials/Textures/Filtering/hdrFiltering.js\";\nimport { ToHalfFloat } from \"../../Misc/textureTools.js\";\nimport \"../../Engines/Extensions/engine.rawTexture.js\";\nimport \"../../Materials/Textures/baseTexture.polynomial.js\";\n/**\n * This represents a texture coming from an HDR input.\n *\n * The only supported format is currently panorama picture stored in RGBE format.\n * Example of such files can be found on Poly Haven: https://polyhaven.com/hdris\n */\nexport class HDRCubeTexture extends BaseTexture {\n /**\n * Sets whether or not the texture is blocking during loading.\n */\n set isBlocking(value) {\n this._isBlocking = value;\n }\n /**\n * Gets whether or not the texture is blocking during loading.\n */\n get isBlocking() {\n return this._isBlocking;\n }\n /**\n * Sets texture matrix rotation angle around Y axis in radians.\n */\n set rotationY(value) {\n this._rotationY = value;\n this.setReflectionTextureMatrix(Matrix.RotationY(this._rotationY));\n }\n /**\n * Gets texture matrix rotation angle around Y axis radians.\n */\n get rotationY() {\n return this._rotationY;\n }\n /**\n * Gets or sets the size of the bounding box associated with the cube texture\n * When defined, the cubemap will switch to local mode\n * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity\n * @example https://www.babylonjs-playground.com/#RNASML\n */\n set boundingBoxSize(value) {\n if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {\n return;\n }\n this._boundingBoxSize = value;\n const scene = this.getScene();\n if (scene) {\n scene.markAllMaterialsAsDirty(1);\n }\n }\n get boundingBoxSize() {\n return this._boundingBoxSize;\n }\n /**\n * Instantiates an HDRTexture from the following parameters.\n *\n * @param url The location of the HDR raw data (Panorama stored in RGBE format)\n * @param sceneOrEngine The scene or engine the texture will be used in\n * @param size The cubemap desired size (the more it increases the longer the generation will be)\n * @param noMipmap Forces to not generate the mipmap if true\n * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process\n * @param gammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)\n * @param prefilterOnLoad Prefilters HDR texture to allow use of this texture as a PBR reflection texture.\n * @param onLoad\n * @param onError\n */\n constructor(url, sceneOrEngine, size, noMipmap = false, generateHarmonics = true, gammaSpace = false, prefilterOnLoad = false, onLoad = null, onError = null, supersample = false) {\n var _a;\n super(sceneOrEngine);\n this._generateHarmonics = true;\n this._onError = null;\n this._isBlocking = true;\n this._rotationY = 0;\n /**\n * Gets or sets the center of the bounding box associated with the cube texture\n * It must define where the camera used to render the texture was set\n */\n this.boundingBoxPosition = Vector3.Zero();\n /**\n * Observable triggered once the texture has been loaded.\n */\n this.onLoadObservable = new Observable();\n if (!url) {\n return;\n }\n this._coordinatesMode = Texture.CUBIC_MODE;\n this.name = url;\n this.url = url;\n this.hasAlpha = false;\n this.isCube = true;\n this._textureMatrix = Matrix.Identity();\n this._prefilterOnLoad = prefilterOnLoad;\n this._onLoad = () => {\n this.onLoadObservable.notifyObservers(this);\n if (onLoad) {\n onLoad();\n }\n };\n this._onError = onError;\n this.gammaSpace = gammaSpace;\n this._noMipmap = noMipmap;\n this._size = size;\n this._supersample = supersample;\n this._generateHarmonics = generateHarmonics;\n this._texture = this._getFromCache(url, this._noMipmap, undefined, undefined, undefined, this.isCube);\n if (!this._texture) {\n if (!((_a = this.getScene()) === null || _a === void 0 ? void 0 : _a.useDelayedTextureLoading)) {\n this._loadTexture();\n }\n else {\n this.delayLoadState = 4;\n }\n }\n else {\n if (this._texture.isReady) {\n Tools.SetImmediate(() => this._onLoad());\n }\n else {\n this._texture.onLoadedObservable.add(this._onLoad);\n }\n }\n }\n /**\n * Get the current class name of the texture useful for serialization or dynamic coding.\n * @returns \"HDRCubeTexture\"\n */\n getClassName() {\n return \"HDRCubeTexture\";\n }\n /**\n * Occurs when the file is raw .hdr file.\n */\n _loadTexture() {\n const engine = this._getEngine();\n const caps = engine.getCaps();\n let textureType = 0;\n if (caps.textureFloat && caps.textureFloatLinearFiltering) {\n textureType = 1;\n }\n else if (caps.textureHalfFloat && caps.textureHalfFloatLinearFiltering) {\n textureType = 2;\n }\n const callback = (buffer) => {\n this.lodGenerationOffset = 0.0;\n this.lodGenerationScale = 0.8;\n // Extract the raw linear data.\n const data = HDRTools.GetCubeMapTextureData(buffer, this._size, this._supersample);\n // Generate harmonics if needed.\n if (this._generateHarmonics) {\n const sphericalPolynomial = CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);\n this.sphericalPolynomial = sphericalPolynomial;\n }\n const results = [];\n let byteArray = null;\n let shortArray = null;\n // Push each faces.\n for (let j = 0; j < 6; j++) {\n // Create fallback array\n if (textureType === 2) {\n shortArray = new Uint16Array(this._size * this._size * 3);\n }\n else if (textureType === 0) {\n // 3 channels of 1 bytes per pixel in bytes.\n byteArray = new Uint8Array(this._size * this._size * 3);\n }\n const dataFace = data[HDRCubeTexture._FacesMapping[j]];\n // If special cases.\n if (this.gammaSpace || shortArray || byteArray) {\n for (let i = 0; i < this._size * this._size; i++) {\n // Put in gamma space if requested.\n if (this.gammaSpace) {\n dataFace[i * 3 + 0] = Math.pow(dataFace[i * 3 + 0], ToGammaSpace);\n dataFace[i * 3 + 1] = Math.pow(dataFace[i * 3 + 1], ToGammaSpace);\n dataFace[i * 3 + 2] = Math.pow(dataFace[i * 3 + 2], ToGammaSpace);\n }\n // Convert to half float texture for fallback.\n if (shortArray) {\n shortArray[i * 3 + 0] = ToHalfFloat(dataFace[i * 3 + 0]);\n shortArray[i * 3 + 1] = ToHalfFloat(dataFace[i * 3 + 1]);\n shortArray[i * 3 + 2] = ToHalfFloat(dataFace[i * 3 + 2]);\n }\n // Convert to int texture for fallback.\n if (byteArray) {\n let r = Math.max(dataFace[i * 3 + 0] * 255, 0);\n let g = Math.max(dataFace[i * 3 + 1] * 255, 0);\n let b = Math.max(dataFace[i * 3 + 2] * 255, 0);\n // May use luminance instead if the result is not accurate.\n const max = Math.max(Math.max(r, g), b);\n if (max > 255) {\n const scale = 255 / max;\n r *= scale;\n g *= scale;\n b *= scale;\n }\n byteArray[i * 3 + 0] = r;\n byteArray[i * 3 + 1] = g;\n byteArray[i * 3 + 2] = b;\n }\n }\n }\n if (shortArray) {\n results.push(shortArray);\n }\n else if (byteArray) {\n results.push(byteArray);\n }\n else {\n results.push(dataFace);\n }\n }\n return results;\n };\n if (engine._features.allowTexturePrefiltering && this._prefilterOnLoad) {\n const previousOnLoad = this._onLoad;\n const hdrFiltering = new HDRFiltering(engine);\n this._onLoad = () => {\n hdrFiltering.prefilter(this, previousOnLoad);\n };\n }\n this._texture = engine.createRawCubeTextureFromUrl(this.url, this.getScene(), this._size, 4, textureType, this._noMipmap, callback, null, this._onLoad, this._onError);\n }\n clone() {\n const newTexture = new HDRCubeTexture(this.url, this.getScene() || this._getEngine(), this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);\n // Base texture\n newTexture.level = this.level;\n newTexture.wrapU = this.wrapU;\n newTexture.wrapV = this.wrapV;\n newTexture.coordinatesIndex = this.coordinatesIndex;\n newTexture.coordinatesMode = this.coordinatesMode;\n return newTexture;\n }\n // Methods\n delayLoad() {\n if (this.delayLoadState !== 4) {\n return;\n }\n this.delayLoadState = 1;\n this._texture = this._getFromCache(this.url, this._noMipmap);\n if (!this._texture) {\n this._loadTexture();\n }\n }\n /**\n * Get the texture reflection matrix used to rotate/transform the reflection.\n * @returns the reflection matrix\n */\n getReflectionTextureMatrix() {\n return this._textureMatrix;\n }\n /**\n * Set the texture reflection matrix used to rotate/transform the reflection.\n * @param value Define the reflection matrix to set\n */\n setReflectionTextureMatrix(value) {\n var _a;\n this._textureMatrix = value;\n if (value.updateFlag === this._textureMatrix.updateFlag) {\n return;\n }\n if (value.isIdentity() !== this._textureMatrix.isIdentity()) {\n (_a = this.getScene()) === null || _a === void 0 ? void 0 : _a.markAllMaterialsAsDirty(1, (mat) => mat.getActiveTextures().indexOf(this) !== -1);\n }\n }\n /**\n * Dispose the texture and release its associated resources.\n */\n dispose() {\n this.onLoadObservable.clear();\n super.dispose();\n }\n /**\n * Parses a JSON representation of an HDR Texture in order to create the texture\n * @param parsedTexture Define the JSON representation\n * @param scene Define the scene the texture should be created in\n * @param rootUrl Define the root url in case we need to load relative dependencies\n * @returns the newly created texture after parsing\n */\n static Parse(parsedTexture, scene, rootUrl) {\n let texture = null;\n if (parsedTexture.name && !parsedTexture.isRenderTarget) {\n texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);\n texture.name = parsedTexture.name;\n texture.hasAlpha = parsedTexture.hasAlpha;\n texture.level = parsedTexture.level;\n texture.coordinatesMode = parsedTexture.coordinatesMode;\n texture.isBlocking = parsedTexture.isBlocking;\n }\n if (texture) {\n if (parsedTexture.boundingBoxPosition) {\n texture.boundingBoxPosition = Vector3.FromArray(parsedTexture.boundingBoxPosition);\n }\n if (parsedTexture.boundingBoxSize) {\n texture.boundingBoxSize = Vector3.FromArray(parsedTexture.boundingBoxSize);\n }\n if (parsedTexture.rotationY) {\n texture.rotationY = parsedTexture.rotationY;\n }\n }\n return texture;\n }\n serialize() {\n if (!this.name) {\n return null;\n }\n const serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.hasAlpha = this.hasAlpha;\n serializationObject.isCube = true;\n serializationObject.level = this.level;\n serializationObject.size = this._size;\n serializationObject.coordinatesMode = this.coordinatesMode;\n serializationObject.useInGammaSpace = this.gammaSpace;\n serializationObject.generateHarmonics = this._generateHarmonics;\n serializationObject.customType = \"BABYLON.HDRCubeTexture\";\n serializationObject.noMipmap = this._noMipmap;\n serializationObject.isBlocking = this._isBlocking;\n serializationObject.rotationY = this._rotationY;\n return serializationObject;\n }\n}\nHDRCubeTexture._FacesMapping = [\"right\", \"left\", \"up\", \"down\", \"front\", \"back\"];\nRegisterClass(\"BABYLON.HDRCubeTexture\", HDRCubeTexture);\n//# sourceMappingURL=hdrCubeTexture.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { serialize, SerializationHelper } from \"../Misc/decorators.js\";\nimport { GetClass } from \"../Misc/typeStore.js\";\n/**\n * Defines a target to use with MorphTargetManager\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/morphTargets\n */\nexport class MorphTarget {\n /**\n * Gets or sets the influence of this target (ie. its weight in the overall morphing)\n */\n get influence() {\n return this._influence;\n }\n set influence(influence) {\n if (this._influence === influence) {\n return;\n }\n const previous = this._influence;\n this._influence = influence;\n if (this.onInfluenceChanged.hasObservers()) {\n this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);\n }\n }\n /**\n * Gets or sets the animation properties override\n */\n get animationPropertiesOverride() {\n if (!this._animationPropertiesOverride && this._scene) {\n return this._scene.animationPropertiesOverride;\n }\n return this._animationPropertiesOverride;\n }\n set animationPropertiesOverride(value) {\n this._animationPropertiesOverride = value;\n }\n /**\n * Creates a new MorphTarget\n * @param name defines the name of the target\n * @param influence defines the influence to use\n * @param scene defines the scene the morphtarget belongs to\n */\n constructor(\n /** defines the name of the target */\n name, influence = 0, scene = null) {\n this.name = name;\n /**\n * Gets or sets the list of animations\n */\n this.animations = new Array();\n this._positions = null;\n this._normals = null;\n this._tangents = null;\n this._uvs = null;\n this._uniqueId = 0;\n /**\n * Observable raised when the influence changes\n */\n this.onInfluenceChanged = new Observable();\n /** @internal */\n this._onDataLayoutChanged = new Observable();\n this._animationPropertiesOverride = null;\n this._scene = scene || EngineStore.LastCreatedScene;\n this.influence = influence;\n if (this._scene) {\n this._uniqueId = this._scene.getUniqueId();\n }\n }\n /**\n * Gets the unique ID of this manager\n */\n get uniqueId() {\n return this._uniqueId;\n }\n /**\n * Gets a boolean defining if the target contains position data\n */\n get hasPositions() {\n return !!this._positions;\n }\n /**\n * Gets a boolean defining if the target contains normal data\n */\n get hasNormals() {\n return !!this._normals;\n }\n /**\n * Gets a boolean defining if the target contains tangent data\n */\n get hasTangents() {\n return !!this._tangents;\n }\n /**\n * Gets a boolean defining if the target contains texture coordinates data\n */\n get hasUVs() {\n return !!this._uvs;\n }\n /**\n * Affects position data to this target\n * @param data defines the position data to use\n */\n setPositions(data) {\n const hadPositions = this.hasPositions;\n this._positions = data;\n if (hadPositions !== this.hasPositions) {\n this._onDataLayoutChanged.notifyObservers(undefined);\n }\n }\n /**\n * Gets the position data stored in this target\n * @returns a FloatArray containing the position data (or null if not present)\n */\n getPositions() {\n return this._positions;\n }\n /**\n * Affects normal data to this target\n * @param data defines the normal data to use\n */\n setNormals(data) {\n const hadNormals = this.hasNormals;\n this._normals = data;\n if (hadNormals !== this.hasNormals) {\n this._onDataLayoutChanged.notifyObservers(undefined);\n }\n }\n /**\n * Gets the normal data stored in this target\n * @returns a FloatArray containing the normal data (or null if not present)\n */\n getNormals() {\n return this._normals;\n }\n /**\n * Affects tangent data to this target\n * @param data defines the tangent data to use\n */\n setTangents(data) {\n const hadTangents = this.hasTangents;\n this._tangents = data;\n if (hadTangents !== this.hasTangents) {\n this._onDataLayoutChanged.notifyObservers(undefined);\n }\n }\n /**\n * Gets the tangent data stored in this target\n * @returns a FloatArray containing the tangent data (or null if not present)\n */\n getTangents() {\n return this._tangents;\n }\n /**\n * Affects texture coordinates data to this target\n * @param data defines the texture coordinates data to use\n */\n setUVs(data) {\n const hadUVs = this.hasUVs;\n this._uvs = data;\n if (hadUVs !== this.hasUVs) {\n this._onDataLayoutChanged.notifyObservers(undefined);\n }\n }\n /**\n * Gets the texture coordinates data stored in this target\n * @returns a FloatArray containing the texture coordinates data (or null if not present)\n */\n getUVs() {\n return this._uvs;\n }\n /**\n * Clone the current target\n * @returns a new MorphTarget\n */\n clone() {\n const newOne = SerializationHelper.Clone(() => new MorphTarget(this.name, this.influence, this._scene), this);\n newOne._positions = this._positions;\n newOne._normals = this._normals;\n newOne._tangents = this._tangents;\n newOne._uvs = this._uvs;\n return newOne;\n }\n /**\n * Serializes the current target into a Serialization object\n * @returns the serialized object\n */\n serialize() {\n const serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.influence = this.influence;\n serializationObject.positions = Array.prototype.slice.call(this.getPositions());\n if (this.id != null) {\n serializationObject.id = this.id;\n }\n if (this.hasNormals) {\n serializationObject.normals = Array.prototype.slice.call(this.getNormals());\n }\n if (this.hasTangents) {\n serializationObject.tangents = Array.prototype.slice.call(this.getTangents());\n }\n if (this.hasUVs) {\n serializationObject.uvs = Array.prototype.slice.call(this.getUVs());\n }\n // Animations\n SerializationHelper.AppendSerializedAnimations(this, serializationObject);\n return serializationObject;\n }\n /**\n * Returns the string \"MorphTarget\"\n * @returns \"MorphTarget\"\n */\n getClassName() {\n return \"MorphTarget\";\n }\n // Statics\n /**\n * Creates a new target from serialized data\n * @param serializationObject defines the serialized data to use\n * @param scene defines the hosting scene\n * @returns a new MorphTarget\n */\n static Parse(serializationObject, scene) {\n const result = new MorphTarget(serializationObject.name, serializationObject.influence);\n result.setPositions(serializationObject.positions);\n if (serializationObject.id != null) {\n result.id = serializationObject.id;\n }\n if (serializationObject.normals) {\n result.setNormals(serializationObject.normals);\n }\n if (serializationObject.tangents) {\n result.setTangents(serializationObject.tangents);\n }\n if (serializationObject.uvs) {\n result.setUVs(serializationObject.uvs);\n }\n // Animations\n if (serializationObject.animations) {\n for (let animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {\n const parsedAnimation = serializationObject.animations[animationIndex];\n const internalClass = GetClass(\"BABYLON.Animation\");\n if (internalClass) {\n result.animations.push(internalClass.Parse(parsedAnimation));\n }\n }\n if (serializationObject.autoAnimate && scene) {\n scene.beginAnimation(result, serializationObject.autoAnimateFrom, serializationObject.autoAnimateTo, serializationObject.autoAnimateLoop, serializationObject.autoAnimateSpeed || 1.0);\n }\n }\n return result;\n }\n /**\n * Creates a MorphTarget from mesh data\n * @param mesh defines the source mesh\n * @param name defines the name to use for the new target\n * @param influence defines the influence to attach to the target\n * @returns a new MorphTarget\n */\n static FromMesh(mesh, name, influence) {\n if (!name) {\n name = mesh.name;\n }\n const result = new MorphTarget(name, influence, mesh.getScene());\n result.setPositions(mesh.getVerticesData(VertexBuffer.PositionKind));\n if (mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {\n result.setNormals(mesh.getVerticesData(VertexBuffer.NormalKind));\n }\n if (mesh.isVerticesDataPresent(VertexBuffer.TangentKind)) {\n result.setTangents(mesh.getVerticesData(VertexBuffer.TangentKind));\n }\n if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {\n result.setUVs(mesh.getVerticesData(VertexBuffer.UVKind));\n }\n return result;\n }\n}\n__decorate([\n serialize()\n], MorphTarget.prototype, \"id\", void 0);\n//# sourceMappingURL=morphTarget.js.map","import { Texture } from \"./texture.js\";\n\nimport \"../../Engines/Extensions/engine.rawTexture.js\";\n/**\n * Class used to store 2D array textures containing user data\n */\nexport class RawTexture2DArray extends Texture {\n /**\n * Gets the number of layers of the texture\n */\n get depth() {\n return this._depth;\n }\n /**\n * Create a new RawTexture2DArray\n * @param data defines the data of the texture\n * @param width defines the width of the texture\n * @param height defines the height of the texture\n * @param depth defines the number of layers of the texture\n * @param format defines the texture format to use\n * @param scene defines the hosting scene\n * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)\n * @param invertY defines if texture must be stored with Y axis inverted\n * @param samplingMode defines the sampling mode to use (Texture.TRILINEAR_SAMPLINGMODE by default)\n * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)\n */\n constructor(data, width, height, depth, \n /** Gets or sets the texture format to use */\n format, scene, generateMipMaps = true, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, textureType = 0) {\n super(null, scene, !generateMipMaps, invertY);\n this.format = format;\n this._texture = scene.getEngine().createRawTexture2DArray(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, null, textureType);\n this._depth = depth;\n this.is2DArray = true;\n }\n /**\n * Update the texture with new data\n * @param data defines the data to store in the texture\n */\n update(data) {\n if (!this._texture) {\n return;\n }\n this._getEngine().updateRawTexture2DArray(this._texture, data, this._texture.format, this._texture.invertY, null, this._texture.type);\n }\n /**\n * Creates a RGBA texture from some data.\n * @param data Define the texture data\n * @param width Define the width of the texture\n * @param height Define the height of the texture\n * @param depth defines the number of layers of the texture\n * @param scene defines the scene the texture will belong to\n * @param generateMipMaps Define whether or not to create mip maps for the texture\n * @param invertY define if the data should be flipped on Y when uploaded to the GPU\n * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)\n * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)\n * @returns the RGBA texture\n */\n static CreateRGBATexture(data, width, height, depth, scene, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0) {\n return new RawTexture2DArray(data, width, height, depth, 5, scene, generateMipMaps, invertY, samplingMode, type);\n }\n}\n//# sourceMappingURL=rawTexture2DArray.js.map","import { SmartArray } from \"../Misc/smartArray.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { MorphTarget } from \"./morphTarget.js\";\n\nimport { RawTexture2DArray } from \"../Materials/Textures/rawTexture2DArray.js\";\n/**\n * This class is used to deform meshes using morphing between different targets\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/morphTargets\n */\nexport class MorphTargetManager {\n /**\n * Sets a boolean indicating that adding new target or updating an existing target will not update the underlying data buffers\n */\n set areUpdatesFrozen(block) {\n if (block) {\n this._blockCounter++;\n }\n else {\n this._blockCounter--;\n if (this._blockCounter <= 0) {\n this._blockCounter = 0;\n this._syncActiveTargets(true);\n }\n }\n }\n get areUpdatesFrozen() {\n return this._blockCounter > 0;\n }\n /**\n * Creates a new MorphTargetManager\n * @param scene defines the current scene\n */\n constructor(scene = null) {\n this._targets = new Array();\n this._targetInfluenceChangedObservers = new Array();\n this._targetDataLayoutChangedObservers = new Array();\n this._activeTargets = new SmartArray(16);\n this._supportsNormals = false;\n this._supportsTangents = false;\n this._supportsUVs = false;\n this._vertexCount = 0;\n this._textureVertexStride = 0;\n this._textureWidth = 0;\n this._textureHeight = 1;\n this._uniqueId = 0;\n this._tempInfluences = new Array();\n this._canUseTextureForTargets = false;\n this._blockCounter = 0;\n /** @internal */\n this._parentContainer = null;\n /**\n * Gets or sets a boolean indicating if influencers must be optimized (eg. recompiling the shader if less influencers are used)\n */\n this.optimizeInfluencers = true;\n /**\n * Gets or sets a boolean indicating if normals must be morphed\n */\n this.enableNormalMorphing = true;\n /**\n * Gets or sets a boolean indicating if tangents must be morphed\n */\n this.enableTangentMorphing = true;\n /**\n * Gets or sets a boolean indicating if UV must be morphed\n */\n this.enableUVMorphing = true;\n this._useTextureToStoreTargets = true;\n if (!scene) {\n scene = EngineStore.LastCreatedScene;\n }\n this._scene = scene;\n if (this._scene) {\n this._scene.addMorphTargetManager(this);\n this._uniqueId = this._scene.getUniqueId();\n const engineCaps = this._scene.getEngine().getCaps();\n this._canUseTextureForTargets =\n engineCaps.canUseGLVertexID && engineCaps.textureFloat && engineCaps.maxVertexTextureImageUnits > 0 && engineCaps.texture2DArrayMaxLayerCount > 1;\n }\n }\n /**\n * Gets the unique ID of this manager\n */\n get uniqueId() {\n return this._uniqueId;\n }\n /**\n * Gets the number of vertices handled by this manager\n */\n get vertexCount() {\n return this._vertexCount;\n }\n /**\n * Gets a boolean indicating if this manager supports morphing of normals\n */\n get supportsNormals() {\n return this._supportsNormals && this.enableNormalMorphing;\n }\n /**\n * Gets a boolean indicating if this manager supports morphing of tangents\n */\n get supportsTangents() {\n return this._supportsTangents && this.enableTangentMorphing;\n }\n /**\n * Gets a boolean indicating if this manager supports morphing of texture coordinates\n */\n get supportsUVs() {\n return this._supportsUVs && this.enableUVMorphing;\n }\n /**\n * Gets the number of targets stored in this manager\n */\n get numTargets() {\n return this._targets.length;\n }\n /**\n * Gets the number of influencers (ie. the number of targets with influences > 0)\n */\n get numInfluencers() {\n return this._activeTargets.length;\n }\n /**\n * Gets the list of influences (one per target)\n */\n get influences() {\n return this._influences;\n }\n /**\n * Gets or sets a boolean indicating that targets should be stored as a texture instead of using vertex attributes (default is true).\n * Please note that this option is not available if the hardware does not support it\n */\n get useTextureToStoreTargets() {\n return this._useTextureToStoreTargets;\n }\n set useTextureToStoreTargets(value) {\n this._useTextureToStoreTargets = value;\n }\n /**\n * Gets a boolean indicating that the targets are stored into a texture (instead of as attributes)\n */\n get isUsingTextureForTargets() {\n var _a;\n return (MorphTargetManager.EnableTextureStorage &&\n this.useTextureToStoreTargets &&\n this._canUseTextureForTargets &&\n !((_a = this._scene) === null || _a === void 0 ? void 0 : _a.getEngine().getCaps().disableMorphTargetTexture));\n }\n /**\n * Gets the active target at specified index. An active target is a target with an influence > 0\n * @param index defines the index to check\n * @returns the requested target\n */\n getActiveTarget(index) {\n return this._activeTargets.data[index];\n }\n /**\n * Gets the target at specified index\n * @param index defines the index to check\n * @returns the requested target\n */\n getTarget(index) {\n return this._targets[index];\n }\n /**\n * Add a new target to this manager\n * @param target defines the target to add\n */\n addTarget(target) {\n this._targets.push(target);\n this._targetInfluenceChangedObservers.push(target.onInfluenceChanged.add((needUpdate) => {\n this._syncActiveTargets(needUpdate);\n }));\n this._targetDataLayoutChangedObservers.push(target._onDataLayoutChanged.add(() => {\n this._syncActiveTargets(true);\n }));\n this._syncActiveTargets(true);\n }\n /**\n * Removes a target from the manager\n * @param target defines the target to remove\n */\n removeTarget(target) {\n const index = this._targets.indexOf(target);\n if (index >= 0) {\n this._targets.splice(index, 1);\n target.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(index, 1)[0]);\n target._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(index, 1)[0]);\n this._syncActiveTargets(true);\n }\n if (this._scene) {\n this._scene.stopAnimation(target);\n }\n }\n /**\n * @internal\n */\n _bind(effect) {\n effect.setFloat3(\"morphTargetTextureInfo\", this._textureVertexStride, this._textureWidth, this._textureHeight);\n effect.setFloatArray(\"morphTargetTextureIndices\", this._morphTargetTextureIndices);\n effect.setTexture(\"morphTargets\", this._targetStoreTexture);\n }\n /**\n * Clone the current manager\n * @returns a new MorphTargetManager\n */\n clone() {\n const copy = new MorphTargetManager(this._scene);\n for (const target of this._targets) {\n copy.addTarget(target.clone());\n }\n copy.enableNormalMorphing = this.enableNormalMorphing;\n copy.enableTangentMorphing = this.enableTangentMorphing;\n copy.enableUVMorphing = this.enableUVMorphing;\n return copy;\n }\n /**\n * Serializes the current manager into a Serialization object\n * @returns the serialized object\n */\n serialize() {\n const serializationObject = {};\n serializationObject.id = this.uniqueId;\n serializationObject.targets = [];\n for (const target of this._targets) {\n serializationObject.targets.push(target.serialize());\n }\n return serializationObject;\n }\n _syncActiveTargets(needUpdate) {\n if (this.areUpdatesFrozen) {\n return;\n }\n let influenceCount = 0;\n this._activeTargets.reset();\n this._supportsNormals = true;\n this._supportsTangents = true;\n this._supportsUVs = true;\n this._vertexCount = 0;\n if (this._scene && this._targets.length > this._scene.getEngine().getCaps().texture2DArrayMaxLayerCount) {\n this.useTextureToStoreTargets = false;\n }\n if (!this._morphTargetTextureIndices || this._morphTargetTextureIndices.length !== this._targets.length) {\n this._morphTargetTextureIndices = new Float32Array(this._targets.length);\n }\n let targetIndex = -1;\n for (const target of this._targets) {\n targetIndex++;\n if (target.influence === 0 && this.optimizeInfluencers) {\n continue;\n }\n if (this._activeTargets.length >= MorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode && !this.isUsingTextureForTargets) {\n break;\n }\n this._activeTargets.push(target);\n this._morphTargetTextureIndices[influenceCount] = targetIndex;\n this._tempInfluences[influenceCount++] = target.influence;\n this._supportsNormals = this._supportsNormals && target.hasNormals;\n this._supportsTangents = this._supportsTangents && target.hasTangents;\n this._supportsUVs = this._supportsUVs && target.hasUVs;\n const positions = target.getPositions();\n if (positions) {\n const vertexCount = positions.length / 3;\n if (this._vertexCount === 0) {\n this._vertexCount = vertexCount;\n }\n else if (this._vertexCount !== vertexCount) {\n Logger.Error(\"Incompatible target. Targets must all have the same vertices count.\");\n return;\n }\n }\n }\n if (this._morphTargetTextureIndices.length !== influenceCount) {\n this._morphTargetTextureIndices = this._morphTargetTextureIndices.slice(0, influenceCount);\n }\n if (!this._influences || this._influences.length !== influenceCount) {\n this._influences = new Float32Array(influenceCount);\n }\n for (let index = 0; index < influenceCount; index++) {\n this._influences[index] = this._tempInfluences[index];\n }\n if (needUpdate) {\n this.synchronize();\n }\n }\n /**\n * Synchronize the targets with all the meshes using this morph target manager\n */\n synchronize() {\n if (!this._scene || this.areUpdatesFrozen) {\n return;\n }\n if (this.isUsingTextureForTargets && this._vertexCount) {\n this._textureVertexStride = 1;\n if (this._supportsNormals) {\n this._textureVertexStride++;\n }\n if (this._supportsTangents) {\n this._textureVertexStride++;\n }\n if (this._supportsUVs) {\n this._textureVertexStride++;\n }\n this._textureWidth = this._vertexCount * this._textureVertexStride;\n this._textureHeight = 1;\n const maxTextureSize = this._scene.getEngine().getCaps().maxTextureSize;\n if (this._textureWidth > maxTextureSize) {\n this._textureHeight = Math.ceil(this._textureWidth / maxTextureSize);\n this._textureWidth = maxTextureSize;\n }\n let mustUpdateTexture = true;\n if (this._targetStoreTexture) {\n const textureSize = this._targetStoreTexture.getSize();\n if (textureSize.width === this._textureWidth && textureSize.height === this._textureHeight && this._targetStoreTexture.depth === this._targets.length) {\n mustUpdateTexture = false;\n }\n }\n if (mustUpdateTexture) {\n if (this._targetStoreTexture) {\n this._targetStoreTexture.dispose();\n }\n const targetCount = this._targets.length;\n const data = new Float32Array(targetCount * this._textureWidth * this._textureHeight * 4);\n let offset = 0;\n for (let index = 0; index < targetCount; index++) {\n const target = this._targets[index];\n const positions = target.getPositions();\n const normals = target.getNormals();\n const uvs = target.getUVs();\n const tangents = target.getTangents();\n if (!positions) {\n if (index === 0) {\n Logger.Error(\"Invalid morph target. Target must have positions.\");\n }\n return;\n }\n offset = index * this._textureWidth * this._textureHeight * 4;\n for (let vertex = 0; vertex < this._vertexCount; vertex++) {\n data[offset] = positions[vertex * 3];\n data[offset + 1] = positions[vertex * 3 + 1];\n data[offset + 2] = positions[vertex * 3 + 2];\n offset += 4;\n if (normals) {\n data[offset] = normals[vertex * 3];\n data[offset + 1] = normals[vertex * 3 + 1];\n data[offset + 2] = normals[vertex * 3 + 2];\n offset += 4;\n }\n if (uvs) {\n data[offset] = uvs[vertex * 2];\n data[offset + 1] = uvs[vertex * 2 + 1];\n offset += 4;\n }\n if (tangents) {\n data[offset] = tangents[vertex * 3];\n data[offset + 1] = tangents[vertex * 3 + 1];\n data[offset + 2] = tangents[vertex * 3 + 2];\n offset += 4;\n }\n }\n }\n this._targetStoreTexture = RawTexture2DArray.CreateRGBATexture(data, this._textureWidth, this._textureHeight, targetCount, this._scene, false, false, 1, 1);\n }\n }\n // Flag meshes as dirty to resync with the active targets\n for (const mesh of this._scene.meshes) {\n if (mesh.morphTargetManager === this) {\n mesh._syncGeometryWithMorphTargetManager();\n }\n }\n }\n /**\n * Release all resources\n */\n dispose() {\n if (this._targetStoreTexture) {\n this._targetStoreTexture.dispose();\n }\n this._targetStoreTexture = null;\n // Remove from scene\n if (this._scene) {\n this._scene.removeMorphTargetManager(this);\n if (this._parentContainer) {\n const index = this._parentContainer.morphTargetManagers.indexOf(this);\n if (index > -1) {\n this._parentContainer.morphTargetManagers.splice(index, 1);\n }\n this._parentContainer = null;\n }\n for (const morph of this._targets) {\n this._scene.stopAnimation(morph);\n }\n }\n }\n // Statics\n /**\n * Creates a new MorphTargetManager from serialized data\n * @param serializationObject defines the serialized data\n * @param scene defines the hosting scene\n * @returns the new MorphTargetManager\n */\n static Parse(serializationObject, scene) {\n const result = new MorphTargetManager(scene);\n result._uniqueId = serializationObject.id;\n for (const targetData of serializationObject.targets) {\n result.addTarget(MorphTarget.Parse(targetData, scene));\n }\n return result;\n }\n}\n/** Enable storing morph target data into textures when set to true (true by default) */\nMorphTargetManager.EnableTextureStorage = true;\n/** Maximum number of active morph targets supported in the \"vertex attribute\" mode (i.e., not the \"texture\" mode) */\nMorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode = 8;\n//# sourceMappingURL=morphTargetManager.js.map","import { Vector3 } from \"../Maths/math.vector.js\";\n/**\n * Holds the data for the raycast result\n * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine\n */\nexport class PhysicsRaycastResult {\n constructor() {\n this._hasHit = false;\n this._hitDistance = 0;\n this._hitNormalWorld = Vector3.Zero();\n this._hitPointWorld = Vector3.Zero();\n this._rayFromWorld = Vector3.Zero();\n this._rayToWorld = Vector3.Zero();\n this._triangleIndex = -1;\n }\n /**\n * Gets if there was a hit\n */\n get hasHit() {\n return this._hasHit;\n }\n /**\n * Gets the distance from the hit\n */\n get hitDistance() {\n return this._hitDistance;\n }\n /**\n * Gets the hit normal/direction in the world\n */\n get hitNormalWorld() {\n return this._hitNormalWorld;\n }\n /**\n * Gets the hit point in the world\n */\n get hitPointWorld() {\n return this._hitPointWorld;\n }\n /**\n * Gets the ray \"start point\" of the ray in the world\n */\n get rayFromWorld() {\n return this._rayFromWorld;\n }\n /**\n * Gets the ray \"end point\" of the ray in the world\n */\n get rayToWorld() {\n return this._rayToWorld;\n }\n /*\n * The index of the original triangle which was hit. Will be -1 if contact point is not on a mesh shape\n */\n get triangleIndex() {\n return this._triangleIndex;\n }\n /**\n * Sets the hit data (normal & point in world space)\n * @param hitNormalWorld defines the normal in world space\n * @param hitPointWorld defines the point in world space\n */\n setHitData(hitNormalWorld, hitPointWorld, triangleIndex) {\n this._hasHit = true;\n this._hitNormalWorld.set(hitNormalWorld.x, hitNormalWorld.y, hitNormalWorld.z);\n this._hitPointWorld.set(hitPointWorld.x, hitPointWorld.y, hitPointWorld.z);\n this._triangleIndex = triangleIndex !== null && triangleIndex !== void 0 ? triangleIndex : -1;\n }\n /**\n * Sets the distance from the start point to the hit point\n * @param distance\n */\n setHitDistance(distance) {\n this._hitDistance = distance;\n }\n /**\n * Calculates the distance manually\n */\n calculateHitDistance() {\n this._hitDistance = Vector3.Distance(this._rayFromWorld, this._hitPointWorld);\n }\n /**\n * Resets all the values to default\n * @param from The from point on world space\n * @param to The to point on world space\n */\n reset(from = Vector3.Zero(), to = Vector3.Zero()) {\n this._rayFromWorld.copyFrom(from);\n this._rayToWorld.copyFrom(to);\n this._hasHit = false;\n this._hitDistance = 0;\n this._hitNormalWorld.setAll(0);\n this._hitPointWorld.setAll(0);\n this._triangleIndex = -1;\n }\n}\n//# sourceMappingURL=physicsRaycastResult.js.map","import { Vector3 } from \"../../Maths/math.vector.js\";\nimport { _WarnImport } from \"../../Misc/devTools.js\";\n/**\n * Class used to control physics engine\n * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine\n */\nexport class PhysicsEngine {\n /**\n *\n * @returns version\n */\n getPluginVersion() {\n return this._physicsPlugin.getPluginVersion();\n }\n /**\n * Factory used to create the default physics plugin.\n * @returns The default physics plugin\n */\n static DefaultPluginFactory() {\n throw _WarnImport(\"CannonJSPlugin\");\n }\n /**\n * Creates a new Physics Engine\n * @param gravity defines the gravity vector used by the simulation\n * @param _physicsPlugin defines the plugin to use (CannonJS by default)\n */\n constructor(gravity, _physicsPlugin = PhysicsEngine.DefaultPluginFactory()) {\n this._physicsPlugin = _physicsPlugin;\n /**\n * Global value used to control the smallest number supported by the simulation\n */\n this._impostors = [];\n this._joints = [];\n this._subTimeStep = 0;\n this._uniqueIdCounter = 0;\n if (!this._physicsPlugin.isSupported()) {\n throw new Error(\"Physics Engine \" + this._physicsPlugin.name + \" cannot be found. \" + \"Please make sure it is included.\");\n }\n gravity = gravity || new Vector3(0, -9.807, 0);\n this.setGravity(gravity);\n this.setTimeStep();\n }\n /**\n * Sets the gravity vector used by the simulation\n * @param gravity defines the gravity vector to use\n */\n setGravity(gravity) {\n this.gravity = gravity;\n this._physicsPlugin.setGravity(this.gravity);\n }\n /**\n * Set the time step of the physics engine.\n * Default is 1/60.\n * To slow it down, enter 1/600 for example.\n * To speed it up, 1/30\n * @param newTimeStep defines the new timestep to apply to this world.\n */\n setTimeStep(newTimeStep = 1 / 60) {\n this._physicsPlugin.setTimeStep(newTimeStep);\n }\n /**\n * Get the time step of the physics engine.\n * @returns the current time step\n */\n getTimeStep() {\n return this._physicsPlugin.getTimeStep();\n }\n /**\n * Set the sub time step of the physics engine.\n * Default is 0 meaning there is no sub steps\n * To increase physics resolution precision, set a small value (like 1 ms)\n * @param subTimeStep defines the new sub timestep used for physics resolution.\n */\n setSubTimeStep(subTimeStep = 0) {\n this._subTimeStep = subTimeStep;\n }\n /**\n * Get the sub time step of the physics engine.\n * @returns the current sub time step\n */\n getSubTimeStep() {\n return this._subTimeStep;\n }\n /**\n * Release all resources\n */\n dispose() {\n this._impostors.forEach(function (impostor) {\n impostor.dispose();\n });\n this._physicsPlugin.dispose();\n }\n /**\n * Gets the name of the current physics plugin\n * @returns the name of the plugin\n */\n getPhysicsPluginName() {\n return this._physicsPlugin.name;\n }\n /**\n * Adding a new impostor for the impostor tracking.\n * This will be done by the impostor itself.\n * @param impostor the impostor to add\n */\n addImpostor(impostor) {\n this._impostors.push(impostor);\n impostor.uniqueId = this._uniqueIdCounter++;\n //if no parent, generate the body\n if (!impostor.parent) {\n this._physicsPlugin.generatePhysicsBody(impostor);\n }\n }\n /**\n * Remove an impostor from the engine.\n * This impostor and its mesh will not longer be updated by the physics engine.\n * @param impostor the impostor to remove\n */\n removeImpostor(impostor) {\n const index = this._impostors.indexOf(impostor);\n if (index > -1) {\n const removed = this._impostors.splice(index, 1);\n //Is it needed?\n if (removed.length) {\n this.getPhysicsPlugin().removePhysicsBody(impostor);\n }\n }\n }\n /**\n * Add a joint to the physics engine\n * @param mainImpostor defines the main impostor to which the joint is added.\n * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint\n * @param joint defines the joint that will connect both impostors.\n */\n addJoint(mainImpostor, connectedImpostor, joint) {\n const impostorJoint = {\n mainImpostor: mainImpostor,\n connectedImpostor: connectedImpostor,\n joint: joint,\n };\n joint.physicsPlugin = this._physicsPlugin;\n this._joints.push(impostorJoint);\n this._physicsPlugin.generateJoint(impostorJoint);\n }\n /**\n * Removes a joint from the simulation\n * @param mainImpostor defines the impostor used with the joint\n * @param connectedImpostor defines the other impostor connected to the main one by the joint\n * @param joint defines the joint to remove\n */\n removeJoint(mainImpostor, connectedImpostor, joint) {\n const matchingJoints = this._joints.filter(function (impostorJoint) {\n return impostorJoint.connectedImpostor === connectedImpostor && impostorJoint.joint === joint && impostorJoint.mainImpostor === mainImpostor;\n });\n if (matchingJoints.length) {\n this._physicsPlugin.removeJoint(matchingJoints[0]);\n //TODO remove it from the list as well\n }\n }\n /**\n * Called by the scene. No need to call it.\n * @param delta defines the timespan between frames\n */\n _step(delta) {\n //check if any mesh has no body / requires an update\n this._impostors.forEach((impostor) => {\n if (impostor.isBodyInitRequired()) {\n this._physicsPlugin.generatePhysicsBody(impostor);\n }\n });\n if (delta > 0.1) {\n delta = 0.1;\n }\n else if (delta <= 0) {\n delta = 1.0 / 60.0;\n }\n this._physicsPlugin.executeStep(delta, this._impostors);\n }\n /**\n * Gets the current plugin used to run the simulation\n * @returns current plugin\n */\n getPhysicsPlugin() {\n return this._physicsPlugin;\n }\n /**\n * Gets the list of physic impostors\n * @returns an array of PhysicsImpostor\n */\n getImpostors() {\n return this._impostors;\n }\n /**\n * Gets the impostor for a physics enabled object\n * @param object defines the object impersonated by the impostor\n * @returns the PhysicsImpostor or null if not found\n */\n getImpostorForPhysicsObject(object) {\n for (let i = 0; i < this._impostors.length; ++i) {\n if (this._impostors[i].object === object) {\n return this._impostors[i];\n }\n }\n return null;\n }\n /**\n * Gets the impostor for a physics body object\n * @param body defines physics body used by the impostor\n * @returns the PhysicsImpostor or null if not found\n */\n getImpostorWithPhysicsBody(body) {\n for (let i = 0; i < this._impostors.length; ++i) {\n if (this._impostors[i].physicsBody === body) {\n return this._impostors[i];\n }\n }\n return null;\n }\n /**\n * Does a raycast in the physics world\n * @param from when should the ray start?\n * @param to when should the ray end?\n * @returns PhysicsRaycastResult\n */\n raycast(from, to) {\n return this._physicsPlugin.raycast(from, to);\n }\n /**\n * Does a raycast in the physics world\n * @param from when should the ray start?\n * @param to when should the ray end?\n * @param result resulting PhysicsRaycastResult\n */\n raycastToRef(from, to, result) {\n return this._physicsPlugin.raycastToRef(from, to, result);\n }\n}\n//# sourceMappingURL=physicsEngine.js.map","import { Logger } from \"../../../Misc/logger.js\";\nimport { Vector3, Matrix, Quaternion } from \"../../../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../../../Buffers/buffer.js\";\nimport { PhysicsImpostor } from \"..//physicsImpostor.js\";\nimport { PhysicsJoint } from \"../physicsJoint.js\";\nimport { PhysicsRaycastResult } from \"../../physicsRaycastResult.js\";\nimport { PhysicsEngine } from \"../physicsEngine.js\";\nimport { Epsilon } from \"../../../Maths/math.constants.js\";\n/** @internal */\nexport class CannonJSPlugin {\n constructor(_useDeltaForWorldStep = true, iterations = 10, cannonInjection = CANNON) {\n this._useDeltaForWorldStep = _useDeltaForWorldStep;\n this.name = \"CannonJSPlugin\";\n this._physicsMaterials = new Array();\n this._fixedTimeStep = 1 / 60;\n this._physicsBodiesToRemoveAfterStep = new Array();\n this._firstFrame = true;\n this._tmpQuaternion = new Quaternion();\n this._minus90X = new Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);\n this._plus90X = new Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);\n this._tmpPosition = Vector3.Zero();\n this._tmpDeltaPosition = Vector3.Zero();\n this._tmpUnityRotation = new Quaternion();\n this.BJSCANNON = cannonInjection;\n if (!this.isSupported()) {\n Logger.Error(\"CannonJS is not available. Please make sure you included the js file.\");\n return;\n }\n this._extendNamespace();\n this.world = new this.BJSCANNON.World();\n this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();\n this.world.solver.iterations = iterations;\n this._cannonRaycastResult = new this.BJSCANNON.RaycastResult();\n this._raycastResult = new PhysicsRaycastResult();\n }\n /**\n *\n * @returns plugin version\n */\n getPluginVersion() {\n return 1;\n }\n setGravity(gravity) {\n const vec = gravity;\n this.world.gravity.set(vec.x, vec.y, vec.z);\n }\n setTimeStep(timeStep) {\n this._fixedTimeStep = timeStep;\n }\n getTimeStep() {\n return this._fixedTimeStep;\n }\n executeStep(delta, impostors) {\n // due to cannon's architecture, the first frame's before-step is skipped.\n if (this._firstFrame) {\n this._firstFrame = false;\n for (const impostor of impostors) {\n if (!(impostor.type == PhysicsImpostor.HeightmapImpostor || impostor.type === PhysicsImpostor.PlaneImpostor)) {\n impostor.beforeStep();\n }\n }\n }\n this.world.step(this._useDeltaForWorldStep ? delta : this._fixedTimeStep);\n this._removeMarkedPhysicsBodiesFromWorld();\n }\n _removeMarkedPhysicsBodiesFromWorld() {\n if (this._physicsBodiesToRemoveAfterStep.length > 0) {\n this._physicsBodiesToRemoveAfterStep.forEach((physicsBody) => {\n if (typeof this.world.removeBody === \"function\") {\n this.world.removeBody(physicsBody);\n }\n else {\n this.world.remove(physicsBody);\n }\n });\n this._physicsBodiesToRemoveAfterStep.length = 0;\n }\n }\n applyImpulse(impostor, force, contactPoint) {\n const worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);\n const impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);\n impostor.physicsBody.applyImpulse(impulse, worldPoint);\n }\n applyForce(impostor, force, contactPoint) {\n const worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);\n const impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);\n impostor.physicsBody.applyForce(impulse, worldPoint);\n }\n generatePhysicsBody(impostor) {\n // When calling forceUpdate generatePhysicsBody is called again, ensure that the updated body does not instantly collide with removed body\n this._removeMarkedPhysicsBodiesFromWorld();\n //parent-child relationship. Does this impostor have a parent impostor?\n if (impostor.parent) {\n if (impostor.physicsBody) {\n this.removePhysicsBody(impostor);\n //TODO is that needed?\n impostor.forceUpdate();\n }\n return;\n }\n //should a new body be created for this impostor?\n if (impostor.isBodyInitRequired()) {\n const shape = this._createShape(impostor);\n if (!shape) {\n Logger.Warn(\"It was not possible to create a physics body for this object.\");\n return;\n }\n //unregister events if body is being changed\n const oldBody = impostor.physicsBody;\n if (oldBody) {\n this.removePhysicsBody(impostor);\n }\n //create the body and material\n const material = this._addMaterial(\"mat-\" + impostor.uniqueId, impostor.getParam(\"friction\"), impostor.getParam(\"restitution\"));\n const bodyCreationObject = {\n mass: impostor.getParam(\"mass\"),\n material: material,\n };\n // A simple extend, in case native options were used.\n const nativeOptions = impostor.getParam(\"nativeOptions\");\n for (const key in nativeOptions) {\n if (Object.prototype.hasOwnProperty.call(nativeOptions, key)) {\n bodyCreationObject[key] = nativeOptions[key];\n }\n }\n impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);\n impostor.physicsBody.addEventListener(\"collide\", impostor.onCollide);\n this.world.addEventListener(\"preStep\", impostor.beforeStep);\n this.world.addEventListener(\"postStep\", impostor.afterStep);\n impostor.physicsBody.addShape(shape);\n if (typeof this.world.addBody === \"function\") {\n this.world.addBody(impostor.physicsBody);\n }\n else {\n this.world.add(impostor.physicsBody);\n }\n //try to keep the body moving in the right direction by taking old properties.\n //Should be tested!\n if (oldBody) {\n [\"force\", \"torque\", \"velocity\", \"angularVelocity\"].forEach(function (param) {\n const vec = oldBody[param];\n impostor.physicsBody[param].set(vec.x, vec.y, vec.z);\n });\n }\n this._processChildMeshes(impostor);\n }\n //now update the body's transformation\n this._updatePhysicsBodyTransformation(impostor);\n }\n _processChildMeshes(mainImpostor) {\n const meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];\n const mainRotation = mainImpostor.object.rotationQuaternion;\n if (mainRotation) {\n mainRotation.conjugateToRef(this._tmpQuaternion);\n }\n else {\n this._tmpQuaternion.set(0, 0, 0, 1);\n }\n if (meshChildren.length) {\n const processMesh = (mesh) => {\n if (!mesh.rotationQuaternion) {\n return;\n }\n const childImpostor = mesh.getPhysicsImpostor();\n if (childImpostor) {\n const parent = childImpostor.parent;\n if (parent !== mainImpostor && mesh.parent) {\n const pPosition = mesh.getAbsolutePosition().subtract(mesh.parent.getAbsolutePosition());\n const q = mesh.rotationQuaternion.multiply(this._tmpQuaternion);\n if (childImpostor.physicsBody) {\n this.removePhysicsBody(childImpostor);\n childImpostor.physicsBody = null;\n }\n childImpostor.parent = mainImpostor;\n childImpostor.resetUpdateFlags();\n mainImpostor.physicsBody.addShape(this._createShape(childImpostor), new this.BJSCANNON.Vec3(pPosition.x, pPosition.y, pPosition.z), new this.BJSCANNON.Quaternion(q.x, q.y, q.z, q.w));\n //Add the mass of the children.\n mainImpostor.physicsBody.mass += childImpostor.getParam(\"mass\");\n }\n }\n mesh.getChildMeshes(true)\n .filter((m) => !!m.physicsImpostor)\n .forEach(processMesh);\n };\n meshChildren.filter((m) => !!m.physicsImpostor).forEach(processMesh);\n }\n }\n removePhysicsBody(impostor) {\n impostor.physicsBody.removeEventListener(\"collide\", impostor.onCollide);\n this.world.removeEventListener(\"preStep\", impostor.beforeStep);\n this.world.removeEventListener(\"postStep\", impostor.afterStep);\n // Only remove the physics body after the physics step to avoid disrupting cannon's internal state\n if (this._physicsBodiesToRemoveAfterStep.indexOf(impostor.physicsBody) === -1) {\n this._physicsBodiesToRemoveAfterStep.push(impostor.physicsBody);\n }\n }\n generateJoint(impostorJoint) {\n const mainBody = impostorJoint.mainImpostor.physicsBody;\n const connectedBody = impostorJoint.connectedImpostor.physicsBody;\n if (!mainBody || !connectedBody) {\n return;\n }\n let constraint;\n const jointData = impostorJoint.joint.jointData;\n //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html\n const constraintData = {\n pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().set(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z) : null,\n pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().set(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z) : null,\n axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().set(jointData.mainAxis.x, jointData.mainAxis.y, jointData.mainAxis.z) : null,\n axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().set(jointData.connectedAxis.x, jointData.connectedAxis.y, jointData.connectedAxis.z) : null,\n maxForce: jointData.nativeParams.maxForce,\n collideConnected: !!jointData.collision,\n };\n switch (impostorJoint.joint.type) {\n case PhysicsJoint.HingeJoint:\n case PhysicsJoint.Hinge2Joint:\n constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);\n break;\n case PhysicsJoint.DistanceJoint:\n constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);\n break;\n case PhysicsJoint.SpringJoint: {\n const springData = jointData;\n constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {\n restLength: springData.length,\n stiffness: springData.stiffness,\n damping: springData.damping,\n localAnchorA: constraintData.pivotA,\n localAnchorB: constraintData.pivotB,\n });\n break;\n }\n case PhysicsJoint.LockJoint:\n constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);\n break;\n case PhysicsJoint.PointToPointJoint:\n case PhysicsJoint.BallAndSocketJoint:\n default:\n constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotB, constraintData.maxForce);\n break;\n }\n //set the collideConnected flag after the creation, since DistanceJoint ignores it.\n constraint.collideConnected = !!jointData.collision;\n impostorJoint.joint.physicsJoint = constraint;\n //don't add spring as constraint, as it is not one.\n if (impostorJoint.joint.type !== PhysicsJoint.SpringJoint) {\n this.world.addConstraint(constraint);\n }\n else {\n impostorJoint.joint.jointData.forceApplicationCallback =\n impostorJoint.joint.jointData.forceApplicationCallback ||\n function () {\n constraint.applyForce();\n };\n impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);\n }\n }\n removeJoint(impostorJoint) {\n if (impostorJoint.joint.type !== PhysicsJoint.SpringJoint) {\n this.world.removeConstraint(impostorJoint.joint.physicsJoint);\n }\n else {\n impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);\n }\n }\n _addMaterial(name, friction, restitution) {\n let index;\n let mat;\n for (index = 0; index < this._physicsMaterials.length; index++) {\n mat = this._physicsMaterials[index];\n if (mat.friction === friction && mat.restitution === restitution) {\n return mat;\n }\n }\n const currentMat = new this.BJSCANNON.Material(name);\n currentMat.friction = friction;\n currentMat.restitution = restitution;\n this._physicsMaterials.push(currentMat);\n return currentMat;\n }\n _checkWithEpsilon(value) {\n return value < Epsilon ? Epsilon : value;\n }\n _createShape(impostor) {\n const object = impostor.object;\n let returnValue;\n const impostorExtents = impostor.getObjectExtents();\n switch (impostor.type) {\n case PhysicsImpostor.SphereImpostor: {\n const radiusX = impostorExtents.x;\n const radiusY = impostorExtents.y;\n const radiusZ = impostorExtents.z;\n returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);\n break;\n }\n //TMP also for cylinder - TODO Cannon supports cylinder natively.\n case PhysicsImpostor.CylinderImpostor: {\n let nativeParams = impostor.getParam(\"nativeOptions\");\n if (!nativeParams) {\n nativeParams = {};\n }\n const radiusTop = nativeParams.radiusTop !== undefined ? nativeParams.radiusTop : this._checkWithEpsilon(impostorExtents.x) / 2;\n const radiusBottom = nativeParams.radiusBottom !== undefined ? nativeParams.radiusBottom : this._checkWithEpsilon(impostorExtents.x) / 2;\n const height = nativeParams.height !== undefined ? nativeParams.height : this._checkWithEpsilon(impostorExtents.y);\n const numSegments = nativeParams.numSegments !== undefined ? nativeParams.numSegments : 16;\n returnValue = new this.BJSCANNON.Cylinder(radiusTop, radiusBottom, height, numSegments);\n // Rotate 90 degrees as this shape is horizontal in cannon\n const quat = new this.BJSCANNON.Quaternion();\n quat.setFromAxisAngle(new this.BJSCANNON.Vec3(1, 0, 0), -Math.PI / 2);\n const translation = new this.BJSCANNON.Vec3(0, 0, 0);\n returnValue.transformAllPoints(translation, quat);\n break;\n }\n case PhysicsImpostor.BoxImpostor: {\n const box = impostorExtents.scale(0.5);\n returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));\n break;\n }\n case PhysicsImpostor.PlaneImpostor:\n Logger.Warn(\"Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead\");\n returnValue = new this.BJSCANNON.Plane();\n break;\n case PhysicsImpostor.MeshImpostor: {\n // should transform the vertex data to world coordinates!!\n const rawVerts = object.getVerticesData ? object.getVerticesData(VertexBuffer.PositionKind) : [];\n const rawFaces = object.getIndices ? object.getIndices() : [];\n if (!rawVerts) {\n Logger.Warn(\"Tried to create a MeshImpostor for an object without vertices. This will fail.\");\n return;\n }\n // get only scale! so the object could transform correctly.\n const oldPosition = object.position.clone();\n const oldRotation = object.rotation && object.rotation.clone();\n const oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();\n object.position.copyFromFloats(0, 0, 0);\n object.rotation && object.rotation.copyFromFloats(0, 0, 0);\n object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());\n object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();\n const transform = object.computeWorldMatrix(true);\n // convert rawVerts to object space\n const transformedVertices = new Array();\n let index;\n for (index = 0; index < rawVerts.length; index += 3) {\n Vector3.TransformCoordinates(Vector3.FromArray(rawVerts, index), transform).toArray(transformedVertices, index);\n }\n Logger.Warn(\"MeshImpostor only collides against spheres.\");\n returnValue = new this.BJSCANNON.Trimesh(transformedVertices, rawFaces);\n //now set back the transformation!\n object.position.copyFrom(oldPosition);\n oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);\n oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);\n break;\n }\n case PhysicsImpostor.HeightmapImpostor: {\n const oldPosition2 = object.position.clone();\n const oldRotation2 = object.rotation && object.rotation.clone();\n const oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();\n object.position.copyFromFloats(0, 0, 0);\n object.rotation && object.rotation.copyFromFloats(0, 0, 0);\n object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());\n object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();\n object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);\n returnValue = this._createHeightmap(object);\n object.position.copyFrom(oldPosition2);\n oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);\n oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);\n object.computeWorldMatrix(true);\n break;\n }\n case PhysicsImpostor.ParticleImpostor:\n returnValue = new this.BJSCANNON.Particle();\n break;\n case PhysicsImpostor.NoImpostor:\n returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(0, 0, 0));\n break;\n }\n return returnValue;\n }\n _createHeightmap(object, pointDepth) {\n let pos = object.getVerticesData(VertexBuffer.PositionKind);\n const transform = object.computeWorldMatrix(true);\n // convert rawVerts to object space\n const transformedVertices = new Array();\n let index;\n for (index = 0; index < pos.length; index += 3) {\n Vector3.TransformCoordinates(Vector3.FromArray(pos, index), transform).toArray(transformedVertices, index);\n }\n pos = transformedVertices;\n const matrix = new Array();\n //For now pointDepth will not be used and will be automatically calculated.\n //Future reference - try and find the best place to add a reference to the pointDepth variable.\n const arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);\n const boundingInfo = object.getBoundingInfo();\n const dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);\n const minY = boundingInfo.boundingBox.extendSizeWorld.z;\n const elementSize = (dim * 2) / arraySize;\n for (let i = 0; i < pos.length; i = i + 3) {\n const x = Math.round(pos[i + 0] / elementSize + arraySize / 2);\n const z = Math.round((pos[i + 1] / elementSize - arraySize / 2) * -1);\n const y = -pos[i + 2] + minY;\n if (!matrix[x]) {\n matrix[x] = [];\n }\n if (!matrix[x][z]) {\n matrix[x][z] = y;\n }\n matrix[x][z] = Math.max(y, matrix[x][z]);\n }\n for (let x = 0; x <= arraySize; ++x) {\n if (!matrix[x]) {\n let loc = 1;\n while (!matrix[(x + loc) % arraySize]) {\n loc++;\n }\n matrix[x] = matrix[(x + loc) % arraySize].slice();\n //console.log(\"missing x\", x);\n }\n for (let z = 0; z <= arraySize; ++z) {\n if (!matrix[x][z]) {\n let loc = 1;\n let newValue;\n while (newValue === undefined) {\n newValue = matrix[x][(z + loc++) % arraySize];\n }\n matrix[x][z] = newValue;\n }\n }\n }\n const shape = new this.BJSCANNON.Heightfield(matrix, {\n elementSize: elementSize,\n });\n //For future reference, needed for body transformation\n shape.minY = minY;\n return shape;\n }\n _updatePhysicsBodyTransformation(impostor) {\n const object = impostor.object;\n //make sure it is updated...\n object.computeWorldMatrix && object.computeWorldMatrix(true);\n if (!object.getBoundingInfo()) {\n return;\n }\n const center = impostor.getObjectCenter();\n //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)\n // The delta between the mesh position and the mesh bounding box center\n this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));\n this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);\n this._tmpPosition.copyFrom(center);\n let quaternion = object.rotationQuaternion;\n if (!quaternion) {\n return;\n }\n //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.\n //ideally these would be rotated at time of creation like cylinder but they dont extend ConvexPolyhedron\n if (impostor.type === PhysicsImpostor.PlaneImpostor || impostor.type === PhysicsImpostor.HeightmapImpostor) {\n //-90 DEG in X, precalculated\n quaternion = quaternion.multiply(this._minus90X);\n //Invert! (Precalculated, 90 deg in X)\n //No need to clone. this will never change.\n impostor.setDeltaRotation(this._plus90X);\n }\n //If it is a heightfield, if should be centered.\n if (impostor.type === PhysicsImpostor.HeightmapImpostor) {\n const mesh = object;\n let boundingInfo = mesh.getBoundingInfo();\n //calculate the correct body position:\n const rotationQuaternion = mesh.rotationQuaternion;\n mesh.rotationQuaternion = this._tmpUnityRotation;\n mesh.computeWorldMatrix(true);\n //get original center with no rotation\n const c = center.clone();\n let oldPivot = mesh.getPivotMatrix();\n if (oldPivot) {\n // create a copy the pivot Matrix as it is modified in place\n oldPivot = oldPivot.clone();\n }\n else {\n oldPivot = Matrix.Identity();\n }\n //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)\n const p = Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);\n mesh.setPreTransformMatrix(p);\n mesh.computeWorldMatrix(true);\n // force bounding box recomputation\n boundingInfo = mesh.getBoundingInfo();\n //calculate the translation\n const translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();\n this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);\n //add it inverted to the delta\n this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));\n this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;\n //rotation is back\n mesh.rotationQuaternion = rotationQuaternion;\n mesh.setPreTransformMatrix(oldPivot);\n mesh.computeWorldMatrix(true);\n }\n else if (impostor.type === PhysicsImpostor.MeshImpostor) {\n this._tmpDeltaPosition.copyFromFloats(0, 0, 0);\n }\n impostor.setDeltaPosition(this._tmpDeltaPosition);\n //Now update the impostor object\n impostor.physicsBody.position.set(this._tmpPosition.x, this._tmpPosition.y, this._tmpPosition.z);\n impostor.physicsBody.quaternion.set(quaternion.x, quaternion.y, quaternion.z, quaternion.w);\n }\n setTransformationFromPhysicsBody(impostor) {\n impostor.object.position.set(impostor.physicsBody.position.x, impostor.physicsBody.position.y, impostor.physicsBody.position.z);\n if (impostor.object.rotationQuaternion) {\n const q = impostor.physicsBody.quaternion;\n impostor.object.rotationQuaternion.set(q.x, q.y, q.z, q.w);\n }\n }\n setPhysicsBodyTransformation(impostor, newPosition, newRotation) {\n impostor.physicsBody.position.set(newPosition.x, newPosition.y, newPosition.z);\n impostor.physicsBody.quaternion.set(newRotation.x, newRotation.y, newRotation.z, newRotation.w);\n }\n isSupported() {\n return this.BJSCANNON !== undefined;\n }\n setLinearVelocity(impostor, velocity) {\n impostor.physicsBody.velocity.set(velocity.x, velocity.y, velocity.z);\n }\n setAngularVelocity(impostor, velocity) {\n impostor.physicsBody.angularVelocity.set(velocity.x, velocity.y, velocity.z);\n }\n getLinearVelocity(impostor) {\n const v = impostor.physicsBody.velocity;\n if (!v) {\n return null;\n }\n return new Vector3(v.x, v.y, v.z);\n }\n getAngularVelocity(impostor) {\n const v = impostor.physicsBody.angularVelocity;\n if (!v) {\n return null;\n }\n return new Vector3(v.x, v.y, v.z);\n }\n setBodyMass(impostor, mass) {\n impostor.physicsBody.mass = mass;\n impostor.physicsBody.updateMassProperties();\n }\n getBodyMass(impostor) {\n return impostor.physicsBody.mass;\n }\n getBodyFriction(impostor) {\n return impostor.physicsBody.material.friction;\n }\n setBodyFriction(impostor, friction) {\n impostor.physicsBody.material.friction = friction;\n }\n getBodyRestitution(impostor) {\n return impostor.physicsBody.material.restitution;\n }\n setBodyRestitution(impostor, restitution) {\n impostor.physicsBody.material.restitution = restitution;\n }\n sleepBody(impostor) {\n impostor.physicsBody.sleep();\n }\n wakeUpBody(impostor) {\n impostor.physicsBody.wakeUp();\n }\n updateDistanceJoint(joint, maxDistance) {\n joint.physicsJoint.distance = maxDistance;\n }\n setMotor(joint, speed, maxForce, motorIndex) {\n if (!motorIndex) {\n joint.physicsJoint.enableMotor();\n joint.physicsJoint.setMotorSpeed(speed);\n if (maxForce) {\n this.setLimit(joint, maxForce);\n }\n }\n }\n setLimit(joint, minForce, maxForce) {\n joint.physicsJoint.motorEquation.maxForce = maxForce;\n joint.physicsJoint.motorEquation.minForce = minForce === void 0 ? -minForce : minForce;\n }\n syncMeshWithImpostor(mesh, impostor) {\n const body = impostor.physicsBody;\n mesh.position.x = body.position.x;\n mesh.position.y = body.position.y;\n mesh.position.z = body.position.z;\n if (mesh.rotationQuaternion) {\n mesh.rotationQuaternion.x = body.quaternion.x;\n mesh.rotationQuaternion.y = body.quaternion.y;\n mesh.rotationQuaternion.z = body.quaternion.z;\n mesh.rotationQuaternion.w = body.quaternion.w;\n }\n }\n getRadius(impostor) {\n const shape = impostor.physicsBody.shapes[0];\n return shape.boundingSphereRadius;\n }\n getBoxSizeToRef(impostor, result) {\n const shape = impostor.physicsBody.shapes[0];\n result.x = shape.halfExtents.x * 2;\n result.y = shape.halfExtents.y * 2;\n result.z = shape.halfExtents.z * 2;\n }\n dispose() { }\n _extendNamespace() {\n //this will force cannon to execute at least one step when using interpolation\n const step_tmp1 = new this.BJSCANNON.Vec3();\n const engine = this.BJSCANNON;\n this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {\n maxSubSteps = maxSubSteps || 10;\n timeSinceLastCalled = timeSinceLastCalled || 0;\n if (timeSinceLastCalled === 0) {\n this.internalStep(dt);\n this.time += dt;\n }\n else {\n let internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);\n internalSteps = Math.min(internalSteps, maxSubSteps) || 1;\n const t0 = performance.now();\n for (let i = 0; i !== internalSteps; i++) {\n this.internalStep(dt);\n if (performance.now() - t0 > dt * 1000) {\n break;\n }\n }\n this.time += timeSinceLastCalled;\n const h = this.time % dt;\n const h_div_dt = h / dt;\n const interpvelo = step_tmp1;\n const bodies = this.bodies;\n for (let j = 0; j !== bodies.length; j++) {\n const b = bodies[j];\n if (b.type !== engine.Body.STATIC && b.sleepState !== engine.Body.SLEEPING) {\n b.position.vsub(b.previousPosition, interpvelo);\n interpvelo.scale(h_div_dt, interpvelo);\n b.position.vadd(interpvelo, b.interpolatedPosition);\n }\n else {\n b.interpolatedPosition.set(b.position.x, b.position.y, b.position.z);\n b.interpolatedQuaternion.set(b.quaternion.x, b.quaternion.y, b.quaternion.z, b.quaternion.w);\n }\n }\n }\n };\n }\n /**\n * Does a raycast in the physics world\n * @param from when should the ray start?\n * @param to when should the ray end?\n * @returns PhysicsRaycastResult\n */\n raycast(from, to) {\n this._raycastResult.reset(from, to);\n this.raycastToRef(from, to, this._raycastResult);\n return this._raycastResult;\n }\n /**\n * Does a raycast in the physics world\n * @param from when should the ray start?\n * @param to when should the ray end?\n * @param result resulting PhysicsRaycastResult\n */\n raycastToRef(from, to, result) {\n this._cannonRaycastResult.reset();\n this.world.raycastClosest(from, to, {}, this._cannonRaycastResult);\n result.reset(from, to);\n if (this._cannonRaycastResult.hasHit) {\n // TODO: do we also want to get the body it hit?\n result.setHitData({\n x: this._cannonRaycastResult.hitNormalWorld.x,\n y: this._cannonRaycastResult.hitNormalWorld.y,\n z: this._cannonRaycastResult.hitNormalWorld.z,\n }, {\n x: this._cannonRaycastResult.hitPointWorld.x,\n y: this._cannonRaycastResult.hitPointWorld.y,\n z: this._cannonRaycastResult.hitPointWorld.z,\n });\n result.setHitDistance(this._cannonRaycastResult.distance);\n }\n }\n}\nPhysicsEngine.DefaultPluginFactory = () => {\n return new CannonJSPlugin();\n};\n//# sourceMappingURL=cannonJSPlugin.js.map","import { PhysicsImpostor } from \"../physicsImpostor.js\";\nimport { PhysicsJoint } from \"../physicsJoint.js\";\nimport { Vector3, Quaternion } from \"../../../Maths/math.vector.js\";\nimport { Logger } from \"../../../Misc/logger.js\";\nimport { PhysicsRaycastResult } from \"../../physicsRaycastResult.js\";\nimport { Epsilon } from \"../../../Maths/math.constants.js\";\n/** @internal */\nexport class OimoJSPlugin {\n constructor(_useDeltaForWorldStep = true, iterations, oimoInjection = OIMO) {\n this._useDeltaForWorldStep = _useDeltaForWorldStep;\n this.name = \"OimoJSPlugin\";\n this._fixedTimeStep = 1 / 60;\n this._tmpImpostorsArray = [];\n this._tmpPositionVector = Vector3.Zero();\n this.BJSOIMO = oimoInjection;\n this.world = new this.BJSOIMO.World({\n iterations: iterations,\n });\n this.world.clear();\n this._raycastResult = new PhysicsRaycastResult();\n }\n /**\n *\n * @returns plugin version\n */\n getPluginVersion() {\n return 1;\n }\n setGravity(gravity) {\n this.world.gravity.set(gravity.x, gravity.y, gravity.z);\n }\n setTimeStep(timeStep) {\n this.world.timeStep = timeStep;\n }\n getTimeStep() {\n return this.world.timeStep;\n }\n executeStep(delta, impostors) {\n impostors.forEach(function (impostor) {\n impostor.beforeStep();\n });\n this.world.timeStep = this._useDeltaForWorldStep ? delta : this._fixedTimeStep;\n this.world.step();\n impostors.forEach((impostor) => {\n impostor.afterStep();\n //update the ordered impostors array\n this._tmpImpostorsArray[impostor.uniqueId] = impostor;\n });\n //check for collisions\n let contact = this.world.contacts;\n while (contact !== null) {\n if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {\n contact = contact.next;\n continue;\n }\n //is this body colliding with any other? get the impostor\n const mainImpostor = this._tmpImpostorsArray[+contact.body1.name];\n const collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];\n if (!mainImpostor || !collidingImpostor) {\n contact = contact.next;\n continue;\n }\n mainImpostor.onCollide({ body: collidingImpostor.physicsBody, point: null, distance: 0, impulse: 0, normal: null });\n collidingImpostor.onCollide({ body: mainImpostor.physicsBody, point: null, distance: 0, impulse: 0, normal: null });\n contact = contact.next;\n }\n }\n applyImpulse(impostor, force, contactPoint) {\n const mass = impostor.physicsBody.mass;\n impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));\n }\n applyForce(impostor, force, contactPoint) {\n Logger.Warn(\"Oimo doesn't support applying force. Using impulse instead.\");\n this.applyImpulse(impostor, force, contactPoint);\n }\n generatePhysicsBody(impostor) {\n //parent-child relationship. Does this impostor has a parent impostor?\n if (impostor.parent) {\n if (impostor.physicsBody) {\n this.removePhysicsBody(impostor);\n //TODO is that needed?\n impostor.forceUpdate();\n }\n return;\n }\n if (impostor.isBodyInitRequired()) {\n const bodyConfig = {\n name: impostor.uniqueId,\n //Oimo must have mass, also for static objects.\n config: [impostor.getParam(\"mass\") || 0.001, impostor.getParam(\"friction\"), impostor.getParam(\"restitution\")],\n size: [],\n type: [],\n pos: [],\n posShape: [],\n rot: [],\n rotShape: [],\n move: impostor.getParam(\"mass\") !== 0,\n density: impostor.getParam(\"mass\"),\n friction: impostor.getParam(\"friction\"),\n restitution: impostor.getParam(\"restitution\"),\n //Supporting older versions of Oimo\n world: this.world,\n };\n const impostors = [impostor];\n const addToArray = (parent) => {\n if (!parent.getChildMeshes) {\n return;\n }\n parent.getChildMeshes().forEach(function (m) {\n if (m.physicsImpostor) {\n impostors.push(m.physicsImpostor);\n //m.physicsImpostor._init();\n }\n });\n };\n addToArray(impostor.object);\n const checkWithEpsilon = (value) => {\n return Math.max(value, Epsilon);\n };\n const globalQuaternion = new Quaternion();\n impostors.forEach((i) => {\n if (!i.object.rotationQuaternion) {\n return;\n }\n //get the correct bounding box\n const oldQuaternion = i.object.rotationQuaternion;\n globalQuaternion.copyFrom(oldQuaternion);\n i.object.rotationQuaternion.set(0, 0, 0, 1);\n i.object.computeWorldMatrix(true);\n const rot = globalQuaternion.toEulerAngles();\n const impostorExtents = i.getObjectExtents();\n // eslint-disable-next-line no-loss-of-precision\n const radToDeg = 57.295779513082320876;\n if (i === impostor) {\n const center = impostor.getObjectCenter();\n impostor.object.getAbsolutePivotPoint().subtractToRef(center, this._tmpPositionVector);\n this._tmpPositionVector.divideInPlace(impostor.object.scaling);\n //Can also use Array.prototype.push.apply\n bodyConfig.pos.push(center.x);\n bodyConfig.pos.push(center.y);\n bodyConfig.pos.push(center.z);\n bodyConfig.posShape.push(0, 0, 0);\n bodyConfig.rotShape.push(0, 0, 0);\n }\n else {\n const localPosition = i.object.position.clone();\n bodyConfig.posShape.push(localPosition.x);\n bodyConfig.posShape.push(localPosition.y);\n bodyConfig.posShape.push(localPosition.z);\n // bodyConfig.pos.push(0, 0, 0);\n bodyConfig.rotShape.push(rot.x * radToDeg, rot.y * radToDeg, rot.z * radToDeg);\n }\n i.object.rotationQuaternion.copyFrom(globalQuaternion);\n // register mesh\n switch (i.type) {\n case PhysicsImpostor.ParticleImpostor:\n Logger.Warn(\"No Particle support in OIMO.js. using SphereImpostor instead\");\n // eslint-disable-next-line no-fallthrough\n case PhysicsImpostor.SphereImpostor: {\n const radiusX = impostorExtents.x;\n const radiusY = impostorExtents.y;\n const radiusZ = impostorExtents.z;\n const size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;\n bodyConfig.type.push(\"sphere\");\n //due to the way oimo works with compounds, add 3 times\n bodyConfig.size.push(size);\n bodyConfig.size.push(size);\n bodyConfig.size.push(size);\n break;\n }\n case PhysicsImpostor.CylinderImpostor: {\n const sizeX = checkWithEpsilon(impostorExtents.x) / 2;\n const sizeY = checkWithEpsilon(impostorExtents.y);\n bodyConfig.type.push(\"cylinder\");\n bodyConfig.size.push(sizeX);\n bodyConfig.size.push(sizeY);\n //due to the way oimo works with compounds, add one more value.\n bodyConfig.size.push(sizeY);\n break;\n }\n case PhysicsImpostor.PlaneImpostor:\n case PhysicsImpostor.BoxImpostor:\n default: {\n const sizeX = checkWithEpsilon(impostorExtents.x);\n const sizeY = checkWithEpsilon(impostorExtents.y);\n const sizeZ = checkWithEpsilon(impostorExtents.z);\n bodyConfig.type.push(\"box\");\n //if (i === impostor) {\n bodyConfig.size.push(sizeX);\n bodyConfig.size.push(sizeY);\n bodyConfig.size.push(sizeZ);\n //} else {\n // bodyConfig.size.push(0,0,0);\n //}\n break;\n }\n }\n //actually not needed, but hey...\n i.object.rotationQuaternion = oldQuaternion;\n });\n impostor.physicsBody = this.world.add(bodyConfig);\n // set the quaternion, ignoring the previously defined (euler) rotation\n impostor.physicsBody.resetQuaternion(globalQuaternion);\n // update with delta 0, so the body will receive the new rotation.\n impostor.physicsBody.updatePosition(0);\n }\n else {\n this._tmpPositionVector.copyFromFloats(0, 0, 0);\n }\n impostor.setDeltaPosition(this._tmpPositionVector);\n //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);\n //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);\n }\n removePhysicsBody(impostor) {\n //impostor.physicsBody.dispose();\n this.world.removeRigidBody(impostor.physicsBody);\n }\n generateJoint(impostorJoint) {\n const mainBody = impostorJoint.mainImpostor.physicsBody;\n const connectedBody = impostorJoint.connectedImpostor.physicsBody;\n if (!mainBody || !connectedBody) {\n return;\n }\n const jointData = impostorJoint.joint.jointData;\n const options = jointData.nativeParams || {};\n let type;\n const nativeJointData = {\n body1: mainBody,\n body2: connectedBody,\n axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),\n axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),\n pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),\n pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),\n min: options.min,\n max: options.max,\n collision: options.collision || jointData.collision,\n spring: options.spring,\n //supporting older version of Oimo\n world: this.world,\n };\n switch (impostorJoint.joint.type) {\n case PhysicsJoint.BallAndSocketJoint:\n type = \"jointBall\";\n break;\n case PhysicsJoint.SpringJoint: {\n Logger.Warn(\"OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead\");\n const springData = jointData;\n nativeJointData.min = springData.length || nativeJointData.min;\n //Max should also be set, just make sure it is at least min\n nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);\n }\n // eslint-disable-next-line no-fallthrough\n case PhysicsJoint.DistanceJoint:\n type = \"jointDistance\";\n nativeJointData.max = jointData.maxDistance;\n break;\n case PhysicsJoint.PrismaticJoint:\n type = \"jointPrisme\";\n break;\n case PhysicsJoint.SliderJoint:\n type = \"jointSlide\";\n break;\n case PhysicsJoint.WheelJoint:\n type = \"jointWheel\";\n break;\n case PhysicsJoint.HingeJoint:\n default:\n type = \"jointHinge\";\n break;\n }\n nativeJointData.type = type;\n impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);\n }\n removeJoint(impostorJoint) {\n //Bug in Oimo prevents us from disposing a joint in the playground\n //joint.joint.physicsJoint.dispose();\n //So we will bruteforce it!\n try {\n this.world.removeJoint(impostorJoint.joint.physicsJoint);\n }\n catch (e) {\n Logger.Warn(e);\n }\n }\n isSupported() {\n return this.BJSOIMO !== undefined;\n }\n setTransformationFromPhysicsBody(impostor) {\n if (!impostor.physicsBody.sleeping) {\n if (impostor.physicsBody.shapes.next) {\n let parent = impostor.physicsBody.shapes;\n while (parent.next) {\n parent = parent.next;\n }\n impostor.object.position.set(parent.position.x, parent.position.y, parent.position.z);\n }\n else {\n const pos = impostor.physicsBody.getPosition();\n impostor.object.position.set(pos.x, pos.y, pos.z);\n }\n if (impostor.object.rotationQuaternion) {\n const quat = impostor.physicsBody.getQuaternion();\n impostor.object.rotationQuaternion.set(quat.x, quat.y, quat.z, quat.w);\n }\n }\n }\n setPhysicsBodyTransformation(impostor, newPosition, newRotation) {\n const body = impostor.physicsBody;\n // disable bidirectional for compound meshes\n if (impostor.physicsBody.shapes.next) {\n return;\n }\n body.position.set(newPosition.x, newPosition.y, newPosition.z);\n body.orientation.set(newRotation.x, newRotation.y, newRotation.z, newRotation.w);\n body.syncShapes();\n body.awake();\n }\n /*private _getLastShape(body: any): any {\n var lastShape = body.shapes;\n while (lastShape.next) {\n lastShape = lastShape.next;\n }\n return lastShape;\n }*/\n setLinearVelocity(impostor, velocity) {\n impostor.physicsBody.linearVelocity.set(velocity.x, velocity.y, velocity.z);\n }\n setAngularVelocity(impostor, velocity) {\n impostor.physicsBody.angularVelocity.set(velocity.x, velocity.y, velocity.z);\n }\n getLinearVelocity(impostor) {\n const v = impostor.physicsBody.linearVelocity;\n if (!v) {\n return null;\n }\n return new Vector3(v.x, v.y, v.z);\n }\n getAngularVelocity(impostor) {\n const v = impostor.physicsBody.angularVelocity;\n if (!v) {\n return null;\n }\n return new Vector3(v.x, v.y, v.z);\n }\n setBodyMass(impostor, mass) {\n const staticBody = mass === 0;\n //this will actually set the body's density and not its mass.\n //But this is how oimo treats the mass variable.\n impostor.physicsBody.shapes.density = staticBody ? 1 : mass;\n impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);\n }\n getBodyMass(impostor) {\n return impostor.physicsBody.shapes.density;\n }\n getBodyFriction(impostor) {\n return impostor.physicsBody.shapes.friction;\n }\n setBodyFriction(impostor, friction) {\n impostor.physicsBody.shapes.friction = friction;\n }\n getBodyRestitution(impostor) {\n return impostor.physicsBody.shapes.restitution;\n }\n setBodyRestitution(impostor, restitution) {\n impostor.physicsBody.shapes.restitution = restitution;\n }\n sleepBody(impostor) {\n impostor.physicsBody.sleep();\n }\n wakeUpBody(impostor) {\n impostor.physicsBody.awake();\n }\n updateDistanceJoint(joint, maxDistance, minDistance) {\n joint.physicsJoint.limitMotor.upperLimit = maxDistance;\n if (minDistance !== void 0) {\n joint.physicsJoint.limitMotor.lowerLimit = minDistance;\n }\n }\n setMotor(joint, speed, force, motorIndex) {\n if (force !== undefined) {\n Logger.Warn(\"OimoJS plugin currently has unexpected behavior when using setMotor with force parameter\");\n }\n else {\n force = 1e6;\n }\n speed *= -1;\n //TODO separate rotational and transational motors.\n const motor = motorIndex\n ? joint.physicsJoint.rotationalLimitMotor2\n : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;\n if (motor) {\n motor.setMotor(speed, force);\n }\n }\n setLimit(joint, upperLimit, lowerLimit, motorIndex) {\n //TODO separate rotational and transational motors.\n const motor = motorIndex\n ? joint.physicsJoint.rotationalLimitMotor2\n : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;\n if (motor) {\n motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);\n }\n }\n syncMeshWithImpostor(mesh, impostor) {\n const body = impostor.physicsBody;\n mesh.position.x = body.position.x;\n mesh.position.y = body.position.y;\n mesh.position.z = body.position.z;\n if (mesh.rotationQuaternion) {\n mesh.rotationQuaternion.x = body.orientation.x;\n mesh.rotationQuaternion.y = body.orientation.y;\n mesh.rotationQuaternion.z = body.orientation.z;\n mesh.rotationQuaternion.w = body.orientation.w;\n }\n }\n getRadius(impostor) {\n return impostor.physicsBody.shapes.radius;\n }\n getBoxSizeToRef(impostor, result) {\n const shape = impostor.physicsBody.shapes;\n result.x = shape.halfWidth * 2;\n result.y = shape.halfHeight * 2;\n result.z = shape.halfDepth * 2;\n }\n dispose() {\n this.world.clear();\n }\n /**\n * Does a raycast in the physics world\n * @param from when should the ray start?\n * @param to when should the ray end?\n * @returns PhysicsRaycastResult\n */\n raycast(from, to) {\n Logger.Warn(\"raycast is not currently supported by the Oimo physics plugin\");\n this._raycastResult.reset(from, to);\n return this._raycastResult;\n }\n /**\n * Does a raycast in the physics world\n * @param from when should the ray start?\n * @param to when should the ray end?\n * @param result resulting PhysicsRaycastResult\n */\n raycastToRef(from, to, result) {\n Logger.Warn(\"raycast is not currently supported by the Oimo physics plugin\");\n result.reset(from, to);\n }\n}\n//# sourceMappingURL=oimoJSPlugin.js.map","import { Quaternion, Vector3, Matrix } from \"../../../Maths/math.vector.js\";\nimport { Logger } from \"../../../Misc/logger.js\";\nimport { PhysicsImpostor } from \"../physicsImpostor.js\";\nimport { PhysicsJoint } from \"../physicsJoint.js\";\nimport { VertexBuffer } from \"../../../Buffers/buffer.js\";\nimport { VertexData } from \"../../../Meshes/mesh.vertexData.js\";\nimport { ExtrudeShape } from \"../../../Meshes/Builders/shapeBuilder.js\";\nimport { CreateLines } from \"../../../Meshes/Builders/linesBuilder.js\";\nimport { PhysicsRaycastResult } from \"../../physicsRaycastResult.js\";\nimport { Scalar } from \"../../../Maths/math.scalar.js\";\nimport { Epsilon } from \"../../../Maths/math.constants.js\";\n/**\n * AmmoJS Physics plugin\n * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine\n * @see https://github.com/kripken/ammo.js/\n */\nexport class AmmoJSPlugin {\n /**\n * Initializes the ammoJS plugin\n * @param _useDeltaForWorldStep if the time between frames should be used when calculating physics steps (Default: true)\n * @param ammoInjection can be used to inject your own ammo reference\n * @param overlappingPairCache can be used to specify your own overlapping pair cache\n */\n constructor(_useDeltaForWorldStep = true, ammoInjection = Ammo, overlappingPairCache = null) {\n this._useDeltaForWorldStep = _useDeltaForWorldStep;\n /**\n * Reference to the Ammo library\n */\n this.bjsAMMO = {};\n /**\n * Name of the plugin\n */\n this.name = \"AmmoJSPlugin\";\n this._timeStep = 1 / 60;\n this._fixedTimeStep = 1 / 60;\n this._maxSteps = 5;\n this._tmpQuaternion = new Quaternion();\n this._tmpContactCallbackResult = false;\n this._tmpContactPoint = new Vector3();\n this._tmpContactNormal = new Vector3();\n this._tmpVec3 = new Vector3();\n this._tmpMatrix = new Matrix();\n if (typeof ammoInjection === \"function\") {\n Logger.Error(\"AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.\");\n return;\n }\n else {\n this.bjsAMMO = ammoInjection;\n }\n if (!this.isSupported()) {\n Logger.Error(\"AmmoJS is not available. Please make sure you included the js file.\");\n return;\n }\n // Initialize the physics world\n this._collisionConfiguration = new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration();\n this._dispatcher = new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration);\n this._overlappingPairCache = overlappingPairCache || new this.bjsAMMO.btDbvtBroadphase();\n this._solver = new this.bjsAMMO.btSequentialImpulseConstraintSolver();\n this._softBodySolver = new this.bjsAMMO.btDefaultSoftBodySolver();\n this.world = new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher, this._overlappingPairCache, this._solver, this._collisionConfiguration, this._softBodySolver);\n this._tmpAmmoConcreteContactResultCallback = new this.bjsAMMO.ConcreteContactResultCallback();\n this._tmpAmmoConcreteContactResultCallback.addSingleResult = (contactPoint) => {\n contactPoint = this.bjsAMMO.wrapPointer(contactPoint, this.bjsAMMO.btManifoldPoint);\n const worldPoint = contactPoint.getPositionWorldOnA();\n const worldNormal = contactPoint.m_normalWorldOnB;\n this._tmpContactPoint.x = worldPoint.x();\n this._tmpContactPoint.y = worldPoint.y();\n this._tmpContactPoint.z = worldPoint.z();\n this._tmpContactNormal.x = worldNormal.x();\n this._tmpContactNormal.y = worldNormal.y();\n this._tmpContactNormal.z = worldNormal.z();\n this._tmpContactImpulse = contactPoint.getAppliedImpulse();\n this._tmpContactDistance = contactPoint.getDistance();\n this._tmpContactCallbackResult = true;\n };\n this._raycastResult = new PhysicsRaycastResult();\n // Create temp ammo variables\n this._tmpAmmoTransform = new this.bjsAMMO.btTransform();\n this._tmpAmmoTransform.setIdentity();\n this._tmpAmmoQuaternion = new this.bjsAMMO.btQuaternion(0, 0, 0, 1);\n this._tmpAmmoVectorA = new this.bjsAMMO.btVector3(0, 0, 0);\n this._tmpAmmoVectorB = new this.bjsAMMO.btVector3(0, 0, 0);\n this._tmpAmmoVectorC = new this.bjsAMMO.btVector3(0, 0, 0);\n this._tmpAmmoVectorD = new this.bjsAMMO.btVector3(0, 0, 0);\n }\n /**\n *\n * @returns plugin version\n */\n getPluginVersion() {\n return 1;\n }\n /**\n * Sets the gravity of the physics world (m/(s^2))\n * @param gravity Gravity to set\n */\n setGravity(gravity) {\n this._tmpAmmoVectorA.setValue(gravity.x, gravity.y, gravity.z);\n this.world.setGravity(this._tmpAmmoVectorA);\n this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA);\n }\n /**\n * Amount of time to step forward on each frame (only used if useDeltaForWorldStep is false in the constructor)\n * @param timeStep timestep to use in seconds\n */\n setTimeStep(timeStep) {\n this._timeStep = timeStep;\n }\n /**\n * Increment to step forward in the physics engine (If timeStep is set to 1/60 and fixedTimeStep is set to 1/120 the physics engine should run 2 steps per frame) (Default: 1/60)\n * @param fixedTimeStep fixedTimeStep to use in seconds\n */\n setFixedTimeStep(fixedTimeStep) {\n this._fixedTimeStep = fixedTimeStep;\n }\n /**\n * Sets the maximum number of steps by the physics engine per frame (Default: 5)\n * @param maxSteps the maximum number of steps by the physics engine per frame\n */\n setMaxSteps(maxSteps) {\n this._maxSteps = maxSteps;\n }\n /**\n * Gets the current timestep (only used if useDeltaForWorldStep is false in the constructor)\n * @returns the current timestep in seconds\n */\n getTimeStep() {\n return this._timeStep;\n }\n // Ammo's contactTest and contactPairTest take a callback that runs synchronously, wrap them so that they are easier to consume\n _isImpostorInContact(impostor) {\n this._tmpContactCallbackResult = false;\n this.world.contactTest(impostor.physicsBody, this._tmpAmmoConcreteContactResultCallback);\n return this._tmpContactCallbackResult;\n }\n // Ammo's collision events have some weird quirks\n // contactPairTest fires too many events as it fires events even when objects are close together but contactTest does not\n // so only fire event if both contactTest and contactPairTest have a hit\n _isImpostorPairInContact(impostorA, impostorB) {\n this._tmpContactCallbackResult = false;\n this.world.contactPairTest(impostorA.physicsBody, impostorB.physicsBody, this._tmpAmmoConcreteContactResultCallback);\n return this._tmpContactCallbackResult;\n }\n // Ammo's behavior when maxSteps > 0 does not behave as described in docs\n // @see http://www.bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World\n //\n // When maxSteps is 0 do the entire simulation in one step\n // When maxSteps is > 0, run up to maxStep times, if on the last step the (remaining step - fixedTimeStep) is < fixedTimeStep, the remainder will be used for the step. (eg. if remainder is 1.001 and fixedTimeStep is 1 the last step will be 1.001, if instead it did 2 steps (1, 0.001) issues occuered when having a tiny step in ammo)\n // Note: To get deterministic physics, timeStep would always need to be divisible by fixedTimeStep\n _stepSimulation(timeStep = 1 / 60, maxSteps = 10, fixedTimeStep = 1 / 60) {\n if (maxSteps == 0) {\n this.world.stepSimulation(timeStep, 0);\n }\n else {\n while (maxSteps > 0 && timeStep > 0) {\n if (timeStep - fixedTimeStep < fixedTimeStep) {\n this.world.stepSimulation(timeStep, 0);\n timeStep = 0;\n }\n else {\n timeStep -= fixedTimeStep;\n this.world.stepSimulation(fixedTimeStep, 0);\n }\n maxSteps--;\n }\n }\n }\n /**\n * Moves the physics simulation forward delta seconds and updates the given physics imposters\n * Prior to the step the imposters physics location is set to the position of the babylon meshes\n * After the step the babylon meshes are set to the position of the physics imposters\n * @param delta amount of time to step forward\n * @param impostors array of imposters to update before/after the step\n */\n executeStep(delta, impostors) {\n for (const impostor of impostors) {\n // Update physics world objects to match babylon world\n if (!impostor.soft) {\n impostor.beforeStep();\n }\n }\n this._stepSimulation(this._useDeltaForWorldStep ? delta : this._timeStep, this._maxSteps, this._fixedTimeStep);\n for (const mainImpostor of impostors) {\n // After physics update make babylon world objects match physics world objects\n if (mainImpostor.soft) {\n this._afterSoftStep(mainImpostor);\n }\n else {\n mainImpostor.afterStep();\n }\n // Handle collision event\n if (mainImpostor._onPhysicsCollideCallbacks.length > 0) {\n if (this._isImpostorInContact(mainImpostor)) {\n for (const collideCallback of mainImpostor._onPhysicsCollideCallbacks) {\n for (const otherImpostor of collideCallback.otherImpostors) {\n if (mainImpostor.physicsBody.isActive() || otherImpostor.physicsBody.isActive()) {\n if (this._isImpostorPairInContact(mainImpostor, otherImpostor)) {\n mainImpostor.onCollide({\n body: otherImpostor.physicsBody,\n point: this._tmpContactPoint,\n distance: this._tmpContactDistance,\n impulse: this._tmpContactImpulse,\n normal: this._tmpContactNormal,\n });\n otherImpostor.onCollide({\n body: mainImpostor.physicsBody,\n point: this._tmpContactPoint,\n distance: this._tmpContactDistance,\n impulse: this._tmpContactImpulse,\n normal: this._tmpContactNormal,\n });\n }\n }\n }\n }\n }\n }\n }\n }\n /**\n * Update babylon mesh to match physics world object\n * @param impostor imposter to match\n */\n _afterSoftStep(impostor) {\n if (impostor.type === PhysicsImpostor.RopeImpostor) {\n this._ropeStep(impostor);\n }\n else {\n this._softbodyOrClothStep(impostor);\n }\n }\n /**\n * Update babylon mesh vertices vertices to match physics world softbody or cloth\n * @param impostor imposter to match\n */\n _ropeStep(impostor) {\n const bodyVertices = impostor.physicsBody.get_m_nodes();\n const nbVertices = bodyVertices.size();\n let node;\n let nodePositions;\n let x, y, z;\n const path = new Array();\n for (let n = 0; n < nbVertices; n++) {\n node = bodyVertices.at(n);\n nodePositions = node.get_m_x();\n x = nodePositions.x();\n y = nodePositions.y();\n z = nodePositions.z();\n path.push(new Vector3(x, y, z));\n }\n const object = impostor.object;\n const shape = impostor.getParam(\"shape\");\n if (impostor._isFromLine) {\n impostor.object = CreateLines(\"lines\", { points: path, instance: object });\n }\n else {\n impostor.object = ExtrudeShape(\"ext\", { shape: shape, path: path, instance: object });\n }\n }\n /**\n * Update babylon mesh vertices vertices to match physics world softbody or cloth\n * @param impostor imposter to match\n */\n _softbodyOrClothStep(impostor) {\n const normalDirection = impostor.type === PhysicsImpostor.ClothImpostor ? 1 : -1;\n const object = impostor.object;\n let vertexPositions = object.getVerticesData(VertexBuffer.PositionKind);\n if (!vertexPositions) {\n vertexPositions = [];\n }\n let vertexNormals = object.getVerticesData(VertexBuffer.NormalKind);\n if (!vertexNormals) {\n vertexNormals = [];\n }\n const nbVertices = vertexPositions.length / 3;\n const bodyVertices = impostor.physicsBody.get_m_nodes();\n let node;\n let nodePositions;\n let x, y, z;\n let nx, ny, nz;\n for (let n = 0; n < nbVertices; n++) {\n node = bodyVertices.at(n);\n nodePositions = node.get_m_x();\n x = nodePositions.x();\n y = nodePositions.y();\n z = nodePositions.z() * normalDirection;\n const nodeNormals = node.get_m_n();\n nx = nodeNormals.x();\n ny = nodeNormals.y();\n nz = nodeNormals.z() * normalDirection;\n vertexPositions[3 * n] = x;\n vertexPositions[3 * n + 1] = y;\n vertexPositions[3 * n + 2] = z;\n vertexNormals[3 * n] = nx;\n vertexNormals[3 * n + 1] = ny;\n vertexNormals[3 * n + 2] = nz;\n }\n const vertex_data = new VertexData();\n vertex_data.positions = vertexPositions;\n vertex_data.normals = vertexNormals;\n vertex_data.uvs = object.getVerticesData(VertexBuffer.UVKind);\n vertex_data.colors = object.getVerticesData(VertexBuffer.ColorKind);\n if (object && object.getIndices) {\n vertex_data.indices = object.getIndices();\n }\n vertex_data.applyToMesh(object);\n }\n /**\n * Applies an impulse on the imposter\n * @param impostor imposter to apply impulse to\n * @param force amount of force to be applied to the imposter\n * @param contactPoint the location to apply the impulse on the imposter\n */\n applyImpulse(impostor, force, contactPoint) {\n if (!impostor.soft) {\n impostor.physicsBody.activate();\n const worldPoint = this._tmpAmmoVectorA;\n const impulse = this._tmpAmmoVectorB;\n // Convert contactPoint relative to center of mass\n if (impostor.object && impostor.object.getWorldMatrix) {\n contactPoint.subtractInPlace(impostor.object.getWorldMatrix().getTranslation());\n }\n worldPoint.setValue(contactPoint.x, contactPoint.y, contactPoint.z);\n impulse.setValue(force.x, force.y, force.z);\n impostor.physicsBody.applyImpulse(impulse, worldPoint);\n }\n else {\n Logger.Warn(\"Cannot be applied to a soft body\");\n }\n }\n /**\n * Applies a force on the imposter\n * @param impostor imposter to apply force\n * @param force amount of force to be applied to the imposter\n * @param contactPoint the location to apply the force on the imposter\n */\n applyForce(impostor, force, contactPoint) {\n if (!impostor.soft) {\n impostor.physicsBody.activate();\n const worldPoint = this._tmpAmmoVectorA;\n const impulse = this._tmpAmmoVectorB;\n // Convert contactPoint relative to center of mass\n if (impostor.object && impostor.object.getWorldMatrix) {\n const localTranslation = impostor.object.getWorldMatrix().getTranslation();\n worldPoint.setValue(contactPoint.x - localTranslation.x, contactPoint.y - localTranslation.y, contactPoint.z - localTranslation.z);\n }\n else {\n worldPoint.setValue(contactPoint.x, contactPoint.y, contactPoint.z);\n }\n impulse.setValue(force.x, force.y, force.z);\n impostor.physicsBody.applyForce(impulse, worldPoint);\n }\n else {\n Logger.Warn(\"Cannot be applied to a soft body\");\n }\n }\n /**\n * Creates a physics body using the plugin\n * @param impostor the imposter to create the physics body on\n */\n generatePhysicsBody(impostor) {\n // Note: this method will not be called on child imposotrs for compound impostors\n impostor._pluginData.toDispose = [];\n //parent-child relationship\n if (impostor.parent) {\n if (impostor.physicsBody) {\n this.removePhysicsBody(impostor);\n impostor.forceUpdate();\n }\n return;\n }\n if (impostor.isBodyInitRequired()) {\n const colShape = this._createShape(impostor);\n const mass = impostor.getParam(\"mass\");\n impostor._pluginData.mass = mass;\n if (impostor.soft) {\n colShape.get_m_cfg().set_collisions(0x11);\n colShape.get_m_cfg().set_kDP(impostor.getParam(\"damping\"));\n this.bjsAMMO.castObject(colShape, this.bjsAMMO.btCollisionObject).getCollisionShape().setMargin(impostor.getParam(\"margin\"));\n colShape.setActivationState(AmmoJSPlugin._DISABLE_DEACTIVATION_FLAG);\n this.world.addSoftBody(colShape, 1, -1);\n impostor.physicsBody = colShape;\n impostor._pluginData.toDispose.push(colShape);\n this.setBodyPressure(impostor, 0);\n if (impostor.type === PhysicsImpostor.SoftbodyImpostor) {\n this.setBodyPressure(impostor, impostor.getParam(\"pressure\"));\n }\n this.setBodyStiffness(impostor, impostor.getParam(\"stiffness\"));\n this.setBodyVelocityIterations(impostor, impostor.getParam(\"velocityIterations\"));\n this.setBodyPositionIterations(impostor, impostor.getParam(\"positionIterations\"));\n }\n else {\n const localInertia = new this.bjsAMMO.btVector3(0, 0, 0);\n const startTransform = new this.bjsAMMO.btTransform();\n impostor.object.computeWorldMatrix(true);\n startTransform.setIdentity();\n if (mass !== 0) {\n colShape.calculateLocalInertia(mass, localInertia);\n }\n this._tmpAmmoVectorA.setValue(impostor.object.position.x, impostor.object.position.y, impostor.object.position.z);\n this._tmpAmmoQuaternion.setValue(impostor.object.rotationQuaternion.x, impostor.object.rotationQuaternion.y, impostor.object.rotationQuaternion.z, impostor.object.rotationQuaternion.w);\n startTransform.setOrigin(this._tmpAmmoVectorA);\n startTransform.setRotation(this._tmpAmmoQuaternion);\n const myMotionState = new this.bjsAMMO.btDefaultMotionState(startTransform);\n const rbInfo = new this.bjsAMMO.btRigidBodyConstructionInfo(mass, myMotionState, colShape, localInertia);\n const body = new this.bjsAMMO.btRigidBody(rbInfo);\n // Make objects kinematic if it's mass is 0\n if (mass === 0) {\n body.setCollisionFlags(body.getCollisionFlags() | AmmoJSPlugin._KINEMATIC_FLAG);\n body.setActivationState(AmmoJSPlugin._DISABLE_DEACTIVATION_FLAG);\n }\n // Disable collision if NoImpostor, but keep collision if shape is btCompoundShape\n if (impostor.type == PhysicsImpostor.NoImpostor && !colShape.getChildShape) {\n body.setCollisionFlags(body.getCollisionFlags() | AmmoJSPlugin._DISABLE_COLLISION_FLAG);\n }\n // compute delta position: compensate the difference between shape center and mesh origin\n if (impostor.type !== PhysicsImpostor.MeshImpostor && impostor.type !== PhysicsImpostor.NoImpostor) {\n const boundingInfo = impostor.object.getBoundingInfo();\n this._tmpVec3.copyFrom(impostor.object.getAbsolutePosition());\n this._tmpVec3.subtractInPlace(boundingInfo.boundingBox.centerWorld);\n this._tmpVec3.x /= impostor.object.scaling.x;\n this._tmpVec3.y /= impostor.object.scaling.y;\n this._tmpVec3.z /= impostor.object.scaling.z;\n impostor.setDeltaPosition(this._tmpVec3);\n }\n const group = impostor.getParam(\"group\");\n const mask = impostor.getParam(\"mask\");\n if (group && mask) {\n this.world.addRigidBody(body, group, mask);\n }\n else {\n this.world.addRigidBody(body);\n }\n impostor.physicsBody = body;\n impostor._pluginData.toDispose = impostor._pluginData.toDispose.concat([body, rbInfo, myMotionState, startTransform, localInertia, colShape]);\n }\n this.setBodyRestitution(impostor, impostor.getParam(\"restitution\"));\n this.setBodyFriction(impostor, impostor.getParam(\"friction\"));\n }\n }\n /**\n * Removes the physics body from the imposter and disposes of the body's memory\n * @param impostor imposter to remove the physics body from\n */\n removePhysicsBody(impostor) {\n if (this.world) {\n if (impostor.soft) {\n this.world.removeSoftBody(impostor.physicsBody);\n }\n else {\n this.world.removeRigidBody(impostor.physicsBody);\n }\n if (impostor._pluginData) {\n impostor._pluginData.toDispose.forEach((d) => {\n this.bjsAMMO.destroy(d);\n });\n impostor._pluginData.toDispose = [];\n }\n }\n }\n /**\n * Generates a joint\n * @param impostorJoint the imposter joint to create the joint with\n */\n generateJoint(impostorJoint) {\n const mainBody = impostorJoint.mainImpostor.physicsBody;\n const connectedBody = impostorJoint.connectedImpostor.physicsBody;\n if (!mainBody || !connectedBody) {\n return;\n }\n const jointData = impostorJoint.joint.jointData;\n if (!jointData.mainPivot) {\n jointData.mainPivot = new Vector3(0, 0, 0);\n }\n if (!jointData.connectedPivot) {\n jointData.connectedPivot = new Vector3(0, 0, 0);\n }\n let joint;\n switch (impostorJoint.joint.type) {\n case PhysicsJoint.DistanceJoint: {\n const distance = jointData.maxDistance;\n if (distance) {\n jointData.mainPivot = new Vector3(0, -distance / 2, 0);\n jointData.connectedPivot = new Vector3(0, distance / 2, 0);\n }\n joint = new this.bjsAMMO.btPoint2PointConstraint(mainBody, connectedBody, new this.bjsAMMO.btVector3(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z), new this.bjsAMMO.btVector3(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z));\n break;\n }\n case PhysicsJoint.HingeJoint: {\n if (!jointData.mainAxis) {\n jointData.mainAxis = new Vector3(0, 0, 0);\n }\n if (!jointData.connectedAxis) {\n jointData.connectedAxis = new Vector3(0, 0, 0);\n }\n const mainAxis = new this.bjsAMMO.btVector3(jointData.mainAxis.x, jointData.mainAxis.y, jointData.mainAxis.z);\n const connectedAxis = new this.bjsAMMO.btVector3(jointData.connectedAxis.x, jointData.connectedAxis.y, jointData.connectedAxis.z);\n joint = new this.bjsAMMO.btHingeConstraint(mainBody, connectedBody, new this.bjsAMMO.btVector3(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z), new this.bjsAMMO.btVector3(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z), mainAxis, connectedAxis);\n break;\n }\n case PhysicsJoint.BallAndSocketJoint:\n joint = new this.bjsAMMO.btPoint2PointConstraint(mainBody, connectedBody, new this.bjsAMMO.btVector3(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z), new this.bjsAMMO.btVector3(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z));\n break;\n default:\n Logger.Warn(\"JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint\");\n joint = new this.bjsAMMO.btPoint2PointConstraint(mainBody, connectedBody, new this.bjsAMMO.btVector3(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z), new this.bjsAMMO.btVector3(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z));\n break;\n }\n this.world.addConstraint(joint, !impostorJoint.joint.jointData.collision);\n impostorJoint.joint.physicsJoint = joint;\n }\n /**\n * Removes a joint\n * @param impostorJoint the imposter joint to remove the joint from\n */\n removeJoint(impostorJoint) {\n if (this.world) {\n this.world.removeConstraint(impostorJoint.joint.physicsJoint);\n }\n }\n // adds all verticies (including child verticies) to the triangle mesh\n _addMeshVerts(btTriangleMesh, topLevelObject, object) {\n let triangleCount = 0;\n if (object && object.getIndices && object.getWorldMatrix && object.getChildMeshes) {\n let indices = object.getIndices();\n if (!indices) {\n indices = [];\n }\n let vertexPositions = object.getVerticesData(VertexBuffer.PositionKind);\n if (!vertexPositions) {\n vertexPositions = [];\n }\n let localMatrix;\n if (topLevelObject && topLevelObject !== object) {\n // top level matrix used for shape transform doesn't take scale into account.\n // Moreover, every children vertex position must be in that space.\n // So, each vertex position here is transform by (mesh world matrix * toplevelMatrix -1)\n let topLevelQuaternion;\n if (topLevelObject.rotationQuaternion) {\n topLevelQuaternion = topLevelObject.rotationQuaternion;\n }\n else if (topLevelObject.rotation) {\n topLevelQuaternion = Quaternion.FromEulerAngles(topLevelObject.rotation.x, topLevelObject.rotation.y, topLevelObject.rotation.z);\n }\n else {\n topLevelQuaternion = Quaternion.Identity();\n }\n const topLevelMatrix = Matrix.Compose(Vector3.One(), topLevelQuaternion, topLevelObject.position);\n topLevelMatrix.invertToRef(this._tmpMatrix);\n const wm = object.computeWorldMatrix(false);\n localMatrix = wm.multiply(this._tmpMatrix);\n }\n else {\n // current top level is same as object level -> only use local scaling\n Matrix.ScalingToRef(object.scaling.x, object.scaling.y, object.scaling.z, this._tmpMatrix);\n localMatrix = this._tmpMatrix;\n }\n const faceCount = indices.length / 3;\n for (let i = 0; i < faceCount; i++) {\n const triPoints = [];\n for (let point = 0; point < 3; point++) {\n let v = new Vector3(vertexPositions[indices[i * 3 + point] * 3 + 0], vertexPositions[indices[i * 3 + point] * 3 + 1], vertexPositions[indices[i * 3 + point] * 3 + 2]);\n v = Vector3.TransformCoordinates(v, localMatrix);\n let vec;\n if (point == 0) {\n vec = this._tmpAmmoVectorA;\n }\n else if (point == 1) {\n vec = this._tmpAmmoVectorB;\n }\n else {\n vec = this._tmpAmmoVectorC;\n }\n vec.setValue(v.x, v.y, v.z);\n triPoints.push(vec);\n }\n btTriangleMesh.addTriangle(triPoints[0], triPoints[1], triPoints[2]);\n triangleCount++;\n }\n object.getChildMeshes().forEach((m) => {\n triangleCount += this._addMeshVerts(btTriangleMesh, topLevelObject, m);\n });\n }\n return triangleCount;\n }\n /**\n * Initialise the soft body vertices to match its object's (mesh) vertices\n * Softbody vertices (nodes) are in world space and to match this\n * The object's position and rotation is set to zero and so its vertices are also then set in world space\n * @param impostor to create the softbody for\n */\n _softVertexData(impostor) {\n const object = impostor.object;\n if (object && object.getIndices && object.getWorldMatrix && object.getChildMeshes) {\n let indices = object.getIndices();\n if (!indices) {\n indices = [];\n }\n let vertexPositions = object.getVerticesData(VertexBuffer.PositionKind);\n if (!vertexPositions) {\n vertexPositions = [];\n }\n let vertexNormals = object.getVerticesData(VertexBuffer.NormalKind);\n if (!vertexNormals) {\n vertexNormals = [];\n }\n object.computeWorldMatrix(false);\n const newPoints = [];\n const newNorms = [];\n for (let i = 0; i < vertexPositions.length; i += 3) {\n let v = new Vector3(vertexPositions[i], vertexPositions[i + 1], vertexPositions[i + 2]);\n let n = new Vector3(vertexNormals[i], vertexNormals[i + 1], vertexNormals[i + 2]);\n v = Vector3.TransformCoordinates(v, object.getWorldMatrix());\n n = Vector3.TransformNormal(n, object.getWorldMatrix());\n newPoints.push(v.x, v.y, v.z);\n newNorms.push(n.x, n.y, n.z);\n }\n const vertex_data = new VertexData();\n vertex_data.positions = newPoints;\n vertex_data.normals = newNorms;\n vertex_data.uvs = object.getVerticesData(VertexBuffer.UVKind);\n vertex_data.colors = object.getVerticesData(VertexBuffer.ColorKind);\n if (object && object.getIndices) {\n vertex_data.indices = object.getIndices();\n }\n vertex_data.applyToMesh(object);\n object.position = Vector3.Zero();\n object.rotationQuaternion = null;\n object.rotation = Vector3.Zero();\n object.computeWorldMatrix(true);\n return vertex_data;\n }\n return VertexData.ExtractFromMesh(object);\n }\n /**\n * Create an impostor's soft body\n * @param impostor to create the softbody for\n */\n _createSoftbody(impostor) {\n const object = impostor.object;\n if (object && object.getIndices) {\n let indices = object.getIndices();\n if (!indices) {\n indices = [];\n }\n const vertex_data = this._softVertexData(impostor);\n const vertexPositions = vertex_data.positions;\n const vertexNormals = vertex_data.normals;\n if (vertexPositions === null || vertexNormals === null) {\n return new this.bjsAMMO.btCompoundShape();\n }\n else {\n const triPoints = [];\n const triNorms = [];\n for (let i = 0; i < vertexPositions.length; i += 3) {\n const v = new Vector3(vertexPositions[i], vertexPositions[i + 1], vertexPositions[i + 2]);\n const n = new Vector3(vertexNormals[i], vertexNormals[i + 1], vertexNormals[i + 2]);\n triPoints.push(v.x, v.y, -v.z);\n triNorms.push(n.x, n.y, -n.z);\n }\n const softBody = new this.bjsAMMO.btSoftBodyHelpers().CreateFromTriMesh(this.world.getWorldInfo(), triPoints, object.getIndices(), indices.length / 3, true);\n const nbVertices = vertexPositions.length / 3;\n const bodyVertices = softBody.get_m_nodes();\n let node;\n let nodeNormals;\n for (let i = 0; i < nbVertices; i++) {\n node = bodyVertices.at(i);\n nodeNormals = node.get_m_n();\n nodeNormals.setX(triNorms[3 * i]);\n nodeNormals.setY(triNorms[3 * i + 1]);\n nodeNormals.setZ(triNorms[3 * i + 2]);\n }\n return softBody;\n }\n }\n }\n /**\n * Create cloth for an impostor\n * @param impostor to create the softbody for\n */\n _createCloth(impostor) {\n const object = impostor.object;\n if (object && object.getIndices) {\n let indices = object.getIndices();\n if (!indices) {\n indices = [];\n }\n const vertex_data = this._softVertexData(impostor);\n const vertexPositions = vertex_data.positions;\n const vertexNormals = vertex_data.normals;\n if (vertexPositions === null || vertexNormals === null) {\n return new this.bjsAMMO.btCompoundShape();\n }\n else {\n const len = vertexPositions.length;\n const segments = Math.sqrt(len / 3);\n impostor.segments = segments;\n const segs = segments - 1;\n this._tmpAmmoVectorA.setValue(vertexPositions[0], vertexPositions[1], vertexPositions[2]);\n this._tmpAmmoVectorB.setValue(vertexPositions[3 * segs], vertexPositions[3 * segs + 1], vertexPositions[3 * segs + 2]);\n this._tmpAmmoVectorD.setValue(vertexPositions[len - 3], vertexPositions[len - 2], vertexPositions[len - 1]);\n this._tmpAmmoVectorC.setValue(vertexPositions[len - 3 - 3 * segs], vertexPositions[len - 2 - 3 * segs], vertexPositions[len - 1 - 3 * segs]);\n const clothBody = new this.bjsAMMO.btSoftBodyHelpers().CreatePatch(this.world.getWorldInfo(), this._tmpAmmoVectorA, this._tmpAmmoVectorB, this._tmpAmmoVectorC, this._tmpAmmoVectorD, segments, segments, impostor.getParam(\"fixedPoints\"), true);\n return clothBody;\n }\n }\n }\n /**\n * Create rope for an impostor\n * @param impostor to create the softbody for\n */\n _createRope(impostor) {\n let len;\n let segments;\n const vertex_data = this._softVertexData(impostor);\n const vertexPositions = vertex_data.positions;\n const vertexNormals = vertex_data.normals;\n if (vertexPositions === null || vertexNormals === null) {\n return new this.bjsAMMO.btCompoundShape();\n }\n //force the mesh to be updatable\n vertex_data.applyToMesh(impostor.object, true);\n impostor._isFromLine = true;\n // If in lines mesh all normals will be zero\n const vertexSquared = vertexNormals.map((x) => x * x);\n const reducer = (accumulator, currentValue) => accumulator + currentValue;\n const reduced = vertexSquared.reduce(reducer);\n if (reduced === 0) {\n // line mesh\n len = vertexPositions.length;\n segments = len / 3 - 1;\n this._tmpAmmoVectorA.setValue(vertexPositions[0], vertexPositions[1], vertexPositions[2]);\n this._tmpAmmoVectorB.setValue(vertexPositions[len - 3], vertexPositions[len - 2], vertexPositions[len - 1]);\n }\n else {\n //extruded mesh\n impostor._isFromLine = false;\n const pathVectors = impostor.getParam(\"path\");\n const shape = impostor.getParam(\"shape\");\n if (shape === null) {\n Logger.Warn(\"No shape available for extruded mesh\");\n return new this.bjsAMMO.btCompoundShape();\n }\n len = pathVectors.length;\n segments = len - 1;\n this._tmpAmmoVectorA.setValue(pathVectors[0].x, pathVectors[0].y, pathVectors[0].z);\n this._tmpAmmoVectorB.setValue(pathVectors[len - 1].x, pathVectors[len - 1].y, pathVectors[len - 1].z);\n }\n impostor.segments = segments;\n let fixedPoints = impostor.getParam(\"fixedPoints\");\n fixedPoints = fixedPoints > 3 ? 3 : fixedPoints;\n const ropeBody = new this.bjsAMMO.btSoftBodyHelpers().CreateRope(this.world.getWorldInfo(), this._tmpAmmoVectorA, this._tmpAmmoVectorB, segments - 1, fixedPoints);\n ropeBody.get_m_cfg().set_collisions(0x11);\n return ropeBody;\n }\n /**\n * Create a custom physics impostor shape using the plugin's onCreateCustomShape handler\n * @param impostor to create the custom physics shape for\n */\n _createCustom(impostor) {\n let returnValue = null;\n if (this.onCreateCustomShape) {\n returnValue = this.onCreateCustomShape(impostor);\n }\n if (returnValue == null) {\n returnValue = new this.bjsAMMO.btCompoundShape();\n }\n return returnValue;\n }\n // adds all verticies (including child verticies) to the convex hull shape\n _addHullVerts(btConvexHullShape, topLevelObject, object) {\n let triangleCount = 0;\n if (object && object.getIndices && object.getWorldMatrix && object.getChildMeshes) {\n let indices = object.getIndices();\n if (!indices) {\n indices = [];\n }\n let vertexPositions = object.getVerticesData(VertexBuffer.PositionKind);\n if (!vertexPositions) {\n vertexPositions = [];\n }\n object.computeWorldMatrix(false);\n const faceCount = indices.length / 3;\n for (let i = 0; i < faceCount; i++) {\n const triPoints = [];\n for (let point = 0; point < 3; point++) {\n let v = new Vector3(vertexPositions[indices[i * 3 + point] * 3 + 0], vertexPositions[indices[i * 3 + point] * 3 + 1], vertexPositions[indices[i * 3 + point] * 3 + 2]);\n // Adjust for initial scaling\n Matrix.ScalingToRef(object.scaling.x, object.scaling.y, object.scaling.z, this._tmpMatrix);\n v = Vector3.TransformCoordinates(v, this._tmpMatrix);\n let vec;\n if (point == 0) {\n vec = this._tmpAmmoVectorA;\n }\n else if (point == 1) {\n vec = this._tmpAmmoVectorB;\n }\n else {\n vec = this._tmpAmmoVectorC;\n }\n vec.setValue(v.x, v.y, v.z);\n triPoints.push(vec);\n }\n btConvexHullShape.addPoint(triPoints[0], true);\n btConvexHullShape.addPoint(triPoints[1], true);\n btConvexHullShape.addPoint(triPoints[2], true);\n triangleCount++;\n }\n object.getChildMeshes().forEach((m) => {\n triangleCount += this._addHullVerts(btConvexHullShape, topLevelObject, m);\n });\n }\n return triangleCount;\n }\n _createShape(impostor, ignoreChildren = false) {\n const object = impostor.object;\n let returnValue;\n const impostorExtents = impostor.getObjectExtents();\n if (!ignoreChildren) {\n const meshChildren = impostor.object.getChildMeshes ? impostor.object.getChildMeshes(true) : [];\n returnValue = new this.bjsAMMO.btCompoundShape();\n // Add shape of all children to the compound shape\n let childrenAdded = 0;\n meshChildren.forEach((childMesh) => {\n const childImpostor = childMesh.getPhysicsImpostor();\n if (childImpostor) {\n if (childImpostor.type == PhysicsImpostor.MeshImpostor) {\n throw \"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)\";\n }\n const shape = this._createShape(childImpostor);\n // Position needs to be scaled based on parent's scaling\n const parentMat = childMesh.parent.getWorldMatrix().clone();\n const s = new Vector3();\n parentMat.decompose(s);\n this._tmpAmmoTransform.getOrigin().setValue(childMesh.position.x * s.x, childMesh.position.y * s.y, childMesh.position.z * s.z);\n this._tmpAmmoQuaternion.setValue(childMesh.rotationQuaternion.x, childMesh.rotationQuaternion.y, childMesh.rotationQuaternion.z, childMesh.rotationQuaternion.w);\n this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion);\n returnValue.addChildShape(this._tmpAmmoTransform, shape);\n childImpostor.dispose();\n childrenAdded++;\n }\n });\n if (childrenAdded > 0) {\n // Add parents shape as a child if present\n if (impostor.type != PhysicsImpostor.NoImpostor) {\n const shape = this._createShape(impostor, true);\n if (shape) {\n this._tmpAmmoTransform.getOrigin().setValue(0, 0, 0);\n this._tmpAmmoQuaternion.setValue(0, 0, 0, 1);\n this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion);\n returnValue.addChildShape(this._tmpAmmoTransform, shape);\n }\n }\n return returnValue;\n }\n else {\n // If no children with impostors create the actual shape below instead\n this.bjsAMMO.destroy(returnValue);\n returnValue = null;\n }\n }\n switch (impostor.type) {\n case PhysicsImpostor.SphereImpostor:\n // Is there a better way to compare floats number? With an epsilon or with a Math function\n if (Scalar.WithinEpsilon(impostorExtents.x, impostorExtents.y, 0.0001) && Scalar.WithinEpsilon(impostorExtents.x, impostorExtents.z, 0.0001)) {\n returnValue = new this.bjsAMMO.btSphereShape(impostorExtents.x / 2);\n }\n else {\n // create a btMultiSphereShape because it's not possible to set a local scaling on a btSphereShape\n const positions = [new this.bjsAMMO.btVector3(0, 0, 0)];\n const radii = [1];\n returnValue = new this.bjsAMMO.btMultiSphereShape(positions, radii, 1);\n returnValue.setLocalScaling(new this.bjsAMMO.btVector3(impostorExtents.x / 2, impostorExtents.y / 2, impostorExtents.z / 2));\n }\n break;\n case PhysicsImpostor.CapsuleImpostor:\n {\n // https://pybullet.org/Bullet/BulletFull/classbtCapsuleShape.html#details\n // Height is just the height between the center of each 'sphere' of the capsule caps\n const capRadius = impostorExtents.x / 2;\n returnValue = new this.bjsAMMO.btCapsuleShape(capRadius, impostorExtents.y - capRadius * 2);\n }\n break;\n case PhysicsImpostor.CylinderImpostor:\n this._tmpAmmoVectorA.setValue(impostorExtents.x / 2, impostorExtents.y / 2, impostorExtents.z / 2);\n returnValue = new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);\n break;\n case PhysicsImpostor.PlaneImpostor:\n case PhysicsImpostor.BoxImpostor:\n this._tmpAmmoVectorA.setValue(impostorExtents.x / 2, impostorExtents.y / 2, impostorExtents.z / 2);\n returnValue = new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);\n break;\n case PhysicsImpostor.MeshImpostor: {\n if (impostor.getParam(\"mass\") == 0) {\n // Only create btBvhTriangleMeshShape if the impostor is static\n // See https://pybullet.org/Bullet/phpBB3/viewtopic.php?t=7283\n if (this.onCreateCustomMeshImpostor) {\n returnValue = this.onCreateCustomMeshImpostor(impostor);\n }\n else {\n const triMesh = new this.bjsAMMO.btTriangleMesh();\n impostor._pluginData.toDispose.push(triMesh);\n const triangleCount = this._addMeshVerts(triMesh, object, object);\n if (triangleCount == 0) {\n returnValue = new this.bjsAMMO.btCompoundShape();\n }\n else {\n returnValue = new this.bjsAMMO.btBvhTriangleMeshShape(triMesh);\n }\n }\n break;\n }\n }\n // Otherwise create convexHullImpostor\n // eslint-disable-next-line no-fallthrough\n case PhysicsImpostor.ConvexHullImpostor: {\n if (this.onCreateCustomConvexHullImpostor) {\n returnValue = this.onCreateCustomConvexHullImpostor(impostor);\n }\n else {\n const convexHull = new this.bjsAMMO.btConvexHullShape();\n const triangleCount = this._addHullVerts(convexHull, object, object);\n if (triangleCount == 0) {\n // Cleanup Unused Convex Hull Shape\n impostor._pluginData.toDispose.push(convexHull);\n returnValue = new this.bjsAMMO.btCompoundShape();\n }\n else {\n returnValue = convexHull;\n }\n }\n break;\n }\n case PhysicsImpostor.NoImpostor:\n // Fill with sphere but collision is disabled on the rigid body in generatePhysicsBody, using an empty shape caused unexpected movement with joints\n returnValue = new this.bjsAMMO.btSphereShape(impostorExtents.x / 2);\n break;\n case PhysicsImpostor.CustomImpostor:\n // Only usable when the plugin's onCreateCustomShape is set\n returnValue = this._createCustom(impostor);\n break;\n case PhysicsImpostor.SoftbodyImpostor:\n // Only usable with a mesh that has sufficient and shared vertices\n returnValue = this._createSoftbody(impostor);\n break;\n case PhysicsImpostor.ClothImpostor:\n // Only usable with a ground mesh that has sufficient and shared vertices\n returnValue = this._createCloth(impostor);\n break;\n case PhysicsImpostor.RopeImpostor:\n // Only usable with a line mesh or an extruded mesh that is updatable\n returnValue = this._createRope(impostor);\n break;\n default:\n Logger.Warn(\"The impostor type is not currently supported by the ammo plugin.\");\n break;\n }\n return returnValue;\n }\n /**\n * Sets the mesh body position/rotation from the babylon impostor\n * @param impostor imposter containing the physics body and babylon object\n */\n setTransformationFromPhysicsBody(impostor) {\n impostor.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform);\n impostor.object.position.set(this._tmpAmmoTransform.getOrigin().x(), this._tmpAmmoTransform.getOrigin().y(), this._tmpAmmoTransform.getOrigin().z());\n if (!impostor.object.rotationQuaternion) {\n if (impostor.object.rotation) {\n this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(), this._tmpAmmoTransform.getRotation().y(), this._tmpAmmoTransform.getRotation().z(), this._tmpAmmoTransform.getRotation().w());\n this._tmpQuaternion.toEulerAnglesToRef(impostor.object.rotation);\n }\n }\n else {\n impostor.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(), this._tmpAmmoTransform.getRotation().y(), this._tmpAmmoTransform.getRotation().z(), this._tmpAmmoTransform.getRotation().w());\n }\n }\n /**\n * Sets the babylon object's position/rotation from the physics body's position/rotation\n * @param impostor imposter containing the physics body and babylon object\n * @param newPosition new position\n * @param newRotation new rotation\n */\n setPhysicsBodyTransformation(impostor, newPosition, newRotation) {\n const trans = impostor.physicsBody.getWorldTransform();\n // If rotation/position has changed update and activate rigged body\n if (Math.abs(trans.getOrigin().x() - newPosition.x) > Epsilon ||\n Math.abs(trans.getOrigin().y() - newPosition.y) > Epsilon ||\n Math.abs(trans.getOrigin().z() - newPosition.z) > Epsilon ||\n Math.abs(trans.getRotation().x() - newRotation.x) > Epsilon ||\n Math.abs(trans.getRotation().y() - newRotation.y) > Epsilon ||\n Math.abs(trans.getRotation().z() - newRotation.z) > Epsilon ||\n Math.abs(trans.getRotation().w() - newRotation.w) > Epsilon) {\n this._tmpAmmoVectorA.setValue(newPosition.x, newPosition.y, newPosition.z);\n trans.setOrigin(this._tmpAmmoVectorA);\n this._tmpAmmoQuaternion.setValue(newRotation.x, newRotation.y, newRotation.z, newRotation.w);\n trans.setRotation(this._tmpAmmoQuaternion);\n impostor.physicsBody.setWorldTransform(trans);\n if (impostor.mass == 0) {\n // Kinematic objects must be updated using motion state\n const motionState = impostor.physicsBody.getMotionState();\n if (motionState) {\n motionState.setWorldTransform(trans);\n }\n }\n else {\n impostor.physicsBody.activate();\n }\n }\n }\n /**\n * If this plugin is supported\n * @returns true if its supported\n */\n isSupported() {\n return this.bjsAMMO !== undefined;\n }\n /**\n * Sets the linear velocity of the physics body\n * @param impostor imposter to set the velocity on\n * @param velocity velocity to set\n */\n setLinearVelocity(impostor, velocity) {\n this._tmpAmmoVectorA.setValue(velocity.x, velocity.y, velocity.z);\n if (impostor.soft) {\n impostor.physicsBody.linearVelocity(this._tmpAmmoVectorA);\n }\n else {\n impostor.physicsBody.setLinearVelocity(this._tmpAmmoVectorA);\n }\n }\n /**\n * Sets the angular velocity of the physics body\n * @param impostor imposter to set the velocity on\n * @param velocity velocity to set\n */\n setAngularVelocity(impostor, velocity) {\n this._tmpAmmoVectorA.setValue(velocity.x, velocity.y, velocity.z);\n if (impostor.soft) {\n impostor.physicsBody.angularVelocity(this._tmpAmmoVectorA);\n }\n else {\n impostor.physicsBody.setAngularVelocity(this._tmpAmmoVectorA);\n }\n }\n /**\n * gets the linear velocity\n * @param impostor imposter to get linear velocity from\n * @returns linear velocity\n */\n getLinearVelocity(impostor) {\n let v;\n if (impostor.soft) {\n v = impostor.physicsBody.linearVelocity();\n }\n else {\n v = impostor.physicsBody.getLinearVelocity();\n }\n if (!v) {\n return null;\n }\n const result = new Vector3(v.x(), v.y(), v.z());\n this.bjsAMMO.destroy(v);\n return result;\n }\n /**\n * gets the angular velocity\n * @param impostor imposter to get angular velocity from\n * @returns angular velocity\n */\n getAngularVelocity(impostor) {\n let v;\n if (impostor.soft) {\n v = impostor.physicsBody.angularVelocity();\n }\n else {\n v = impostor.physicsBody.getAngularVelocity();\n }\n if (!v) {\n return null;\n }\n const result = new Vector3(v.x(), v.y(), v.z());\n this.bjsAMMO.destroy(v);\n return result;\n }\n /**\n * Sets the mass of physics body\n * @param impostor imposter to set the mass on\n * @param mass mass to set\n */\n setBodyMass(impostor, mass) {\n if (impostor.soft) {\n impostor.physicsBody.setTotalMass(mass, false);\n }\n else {\n impostor.physicsBody.setMassProps(mass);\n }\n impostor._pluginData.mass = mass;\n }\n /**\n * Gets the mass of the physics body\n * @param impostor imposter to get the mass from\n * @returns mass\n */\n getBodyMass(impostor) {\n return impostor._pluginData.mass || 0;\n }\n /**\n * Gets friction of the impostor\n * @param impostor impostor to get friction from\n * @returns friction value\n */\n getBodyFriction(impostor) {\n return impostor._pluginData.friction || 0;\n }\n /**\n * Sets friction of the impostor\n * @param impostor impostor to set friction on\n * @param friction friction value\n */\n setBodyFriction(impostor, friction) {\n if (impostor.soft) {\n impostor.physicsBody.get_m_cfg().set_kDF(friction);\n }\n else {\n impostor.physicsBody.setFriction(friction);\n }\n impostor._pluginData.friction = friction;\n }\n /**\n * Gets restitution of the impostor\n * @param impostor impostor to get restitution from\n * @returns restitution value\n */\n getBodyRestitution(impostor) {\n return impostor._pluginData.restitution || 0;\n }\n /**\n * Sets restitution of the impostor\n * @param impostor impostor to set resitution on\n * @param restitution resitution value\n */\n setBodyRestitution(impostor, restitution) {\n impostor.physicsBody.setRestitution(restitution);\n impostor._pluginData.restitution = restitution;\n }\n /**\n * Gets pressure inside the impostor\n * @param impostor impostor to get pressure from\n * @returns pressure value\n */\n getBodyPressure(impostor) {\n if (!impostor.soft) {\n Logger.Warn(\"Pressure is not a property of a rigid body\");\n return 0;\n }\n return impostor._pluginData.pressure || 0;\n }\n /**\n * Sets pressure inside a soft body impostor\n * Cloth and rope must remain 0 pressure\n * @param impostor impostor to set pressure on\n * @param pressure pressure value\n */\n setBodyPressure(impostor, pressure) {\n if (impostor.soft) {\n if (impostor.type === PhysicsImpostor.SoftbodyImpostor) {\n impostor.physicsBody.get_m_cfg().set_kPR(pressure);\n impostor._pluginData.pressure = pressure;\n }\n else {\n impostor.physicsBody.get_m_cfg().set_kPR(0);\n impostor._pluginData.pressure = 0;\n }\n }\n else {\n Logger.Warn(\"Pressure can only be applied to a softbody\");\n }\n }\n /**\n * Gets stiffness of the impostor\n * @param impostor impostor to get stiffness from\n * @returns pressure value\n */\n getBodyStiffness(impostor) {\n if (!impostor.soft) {\n Logger.Warn(\"Stiffness is not a property of a rigid body\");\n return 0;\n }\n return impostor._pluginData.stiffness || 0;\n }\n /**\n * Sets stiffness of the impostor\n * @param impostor impostor to set stiffness on\n * @param stiffness stiffness value from 0 to 1\n */\n setBodyStiffness(impostor, stiffness) {\n if (impostor.soft) {\n stiffness = stiffness < 0 ? 0 : stiffness;\n stiffness = stiffness > 1 ? 1 : stiffness;\n impostor.physicsBody.get_m_materials().at(0).set_m_kLST(stiffness);\n impostor._pluginData.stiffness = stiffness;\n }\n else {\n Logger.Warn(\"Stiffness cannot be applied to a rigid body\");\n }\n }\n /**\n * Gets velocityIterations of the impostor\n * @param impostor impostor to get velocity iterations from\n * @returns velocityIterations value\n */\n getBodyVelocityIterations(impostor) {\n if (!impostor.soft) {\n Logger.Warn(\"Velocity iterations is not a property of a rigid body\");\n return 0;\n }\n return impostor._pluginData.velocityIterations || 0;\n }\n /**\n * Sets velocityIterations of the impostor\n * @param impostor impostor to set velocity iterations on\n * @param velocityIterations velocityIterations value\n */\n setBodyVelocityIterations(impostor, velocityIterations) {\n if (impostor.soft) {\n velocityIterations = velocityIterations < 0 ? 0 : velocityIterations;\n impostor.physicsBody.get_m_cfg().set_viterations(velocityIterations);\n impostor._pluginData.velocityIterations = velocityIterations;\n }\n else {\n Logger.Warn(\"Velocity iterations cannot be applied to a rigid body\");\n }\n }\n /**\n * Gets positionIterations of the impostor\n * @param impostor impostor to get position iterations from\n * @returns positionIterations value\n */\n getBodyPositionIterations(impostor) {\n if (!impostor.soft) {\n Logger.Warn(\"Position iterations is not a property of a rigid body\");\n return 0;\n }\n return impostor._pluginData.positionIterations || 0;\n }\n /**\n * Sets positionIterations of the impostor\n * @param impostor impostor to set position on\n * @param positionIterations positionIterations value\n */\n setBodyPositionIterations(impostor, positionIterations) {\n if (impostor.soft) {\n positionIterations = positionIterations < 0 ? 0 : positionIterations;\n impostor.physicsBody.get_m_cfg().set_piterations(positionIterations);\n impostor._pluginData.positionIterations = positionIterations;\n }\n else {\n Logger.Warn(\"Position iterations cannot be applied to a rigid body\");\n }\n }\n /**\n * Append an anchor to a cloth object\n * @param impostor is the cloth impostor to add anchor to\n * @param otherImpostor is the rigid impostor to anchor to\n * @param width ratio across width from 0 to 1\n * @param height ratio up height from 0 to 1\n * @param influence the elasticity between cloth impostor and anchor from 0, very stretchy to 1, little stretch\n * @param noCollisionBetweenLinkedBodies when true collisions between soft impostor and anchor are ignored; default false\n */\n appendAnchor(impostor, otherImpostor, width, height, influence = 1, noCollisionBetweenLinkedBodies = false) {\n const segs = impostor.segments;\n const nbAcross = Math.round((segs - 1) * width);\n const nbUp = Math.round((segs - 1) * height);\n const nbDown = segs - 1 - nbUp;\n const node = nbAcross + segs * nbDown;\n impostor.physicsBody.appendAnchor(node, otherImpostor.physicsBody, noCollisionBetweenLinkedBodies, influence);\n }\n /**\n * Append an hook to a rope object\n * @param impostor is the rope impostor to add hook to\n * @param otherImpostor is the rigid impostor to hook to\n * @param length ratio along the rope from 0 to 1\n * @param influence the elasticity between soft impostor and anchor from 0, very stretchy to 1, little stretch\n * @param noCollisionBetweenLinkedBodies when true collisions between soft impostor and anchor are ignored; default false\n */\n appendHook(impostor, otherImpostor, length, influence = 1, noCollisionBetweenLinkedBodies = false) {\n const node = Math.round(impostor.segments * length);\n impostor.physicsBody.appendAnchor(node, otherImpostor.physicsBody, noCollisionBetweenLinkedBodies, influence);\n }\n /**\n * Sleeps the physics body and stops it from being active\n * @param impostor impostor to sleep\n */\n sleepBody(impostor) {\n impostor.physicsBody.forceActivationState(0);\n }\n /**\n * Activates the physics body\n * @param impostor impostor to activate\n */\n wakeUpBody(impostor) {\n impostor.physicsBody.activate();\n }\n /**\n * Updates the distance parameters of the joint\n */\n updateDistanceJoint() {\n Logger.Warn(\"updateDistanceJoint is not currently supported by the Ammo physics plugin\");\n }\n /**\n * Sets a motor on the joint\n * @param joint joint to set motor on\n * @param speed speed of the motor\n * @param maxForce maximum force of the motor\n */\n setMotor(joint, speed, maxForce) {\n joint.physicsJoint.enableAngularMotor(true, speed, maxForce);\n }\n /**\n * Sets the motors limit\n */\n setLimit() {\n Logger.Warn(\"setLimit is not currently supported by the Ammo physics plugin\");\n }\n /**\n * Syncs the position and rotation of a mesh with the impostor\n * @param mesh mesh to sync\n * @param impostor impostor to update the mesh with\n */\n syncMeshWithImpostor(mesh, impostor) {\n const body = impostor.physicsBody;\n body.getMotionState().getWorldTransform(this._tmpAmmoTransform);\n mesh.position.x = this._tmpAmmoTransform.getOrigin().x();\n mesh.position.y = this._tmpAmmoTransform.getOrigin().y();\n mesh.position.z = this._tmpAmmoTransform.getOrigin().z();\n if (mesh.rotationQuaternion) {\n mesh.rotationQuaternion.x = this._tmpAmmoTransform.getRotation().x();\n mesh.rotationQuaternion.y = this._tmpAmmoTransform.getRotation().y();\n mesh.rotationQuaternion.z = this._tmpAmmoTransform.getRotation().z();\n mesh.rotationQuaternion.w = this._tmpAmmoTransform.getRotation().w();\n }\n }\n /**\n * Gets the radius of the impostor\n * @param impostor impostor to get radius from\n * @returns the radius\n */\n getRadius(impostor) {\n const extents = impostor.getObjectExtents();\n return extents.x / 2;\n }\n /**\n * Gets the box size of the impostor\n * @param impostor impostor to get box size from\n * @param result the resulting box size\n */\n getBoxSizeToRef(impostor, result) {\n const extents = impostor.getObjectExtents();\n result.x = extents.x;\n result.y = extents.y;\n result.z = extents.z;\n }\n /**\n * Disposes of the impostor\n */\n dispose() {\n // Dispose of world\n this.bjsAMMO.destroy(this.world);\n this.bjsAMMO.destroy(this._solver);\n this.bjsAMMO.destroy(this._overlappingPairCache);\n this.bjsAMMO.destroy(this._dispatcher);\n this.bjsAMMO.destroy(this._collisionConfiguration);\n // Dispose of temp variables\n this.bjsAMMO.destroy(this._tmpAmmoVectorA);\n this.bjsAMMO.destroy(this._tmpAmmoVectorB);\n this.bjsAMMO.destroy(this._tmpAmmoVectorC);\n this.bjsAMMO.destroy(this._tmpAmmoTransform);\n this.bjsAMMO.destroy(this._tmpAmmoQuaternion);\n this.bjsAMMO.destroy(this._tmpAmmoConcreteContactResultCallback);\n this.world = null;\n }\n /**\n * Does a raycast in the physics world\n * @param from where should the ray start?\n * @param to where should the ray end?\n * @returns PhysicsRaycastResult\n */\n raycast(from, to) {\n this.raycastToRef(from, to, this._raycastResult);\n return this._raycastResult;\n }\n /**\n * Does a raycast in the physics world\n * @param from when should the ray start?\n * @param to when should the ray end?\n * @param result resulting PhysicsRaycastResult\n */\n raycastToRef(from, to, result) {\n this._tmpAmmoVectorRCA = new this.bjsAMMO.btVector3(from.x, from.y, from.z);\n this._tmpAmmoVectorRCB = new this.bjsAMMO.btVector3(to.x, to.y, to.z);\n const rayCallback = new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA, this._tmpAmmoVectorRCB);\n this.world.rayTest(this._tmpAmmoVectorRCA, this._tmpAmmoVectorRCB, rayCallback);\n result.reset(from, to);\n if (rayCallback.hasHit()) {\n // TODO: do we want/need the body? If so, set all the data\n /*\n var rigidBody = this.bjsAMMO.btRigidBody.prototype.upcast(\n rayCallback.get_m_collisionObject()\n );\n var body = {};\n */\n result.setHitData({\n x: rayCallback.get_m_hitNormalWorld().x(),\n y: rayCallback.get_m_hitNormalWorld().y(),\n z: rayCallback.get_m_hitNormalWorld().z(),\n }, {\n x: rayCallback.get_m_hitPointWorld().x(),\n y: rayCallback.get_m_hitPointWorld().y(),\n z: rayCallback.get_m_hitPointWorld().z(),\n });\n result.calculateHitDistance();\n }\n this.bjsAMMO.destroy(rayCallback);\n this.bjsAMMO.destroy(this._tmpAmmoVectorRCA);\n this.bjsAMMO.destroy(this._tmpAmmoVectorRCB);\n }\n}\nAmmoJSPlugin._DISABLE_COLLISION_FLAG = 4;\nAmmoJSPlugin._KINEMATIC_FLAG = 2;\nAmmoJSPlugin._DISABLE_DEACTIVATION_FLAG = 4;\n//# sourceMappingURL=ammoJSPlugin.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serializeAsMeshReference, serializeAsVector3, SerializationHelper } from \"../Misc/decorators.js\";\nimport { RenderTargetTexture } from \"../Materials/Textures/renderTargetTexture.js\";\nimport { Matrix, Vector3 } from \"../Maths/math.vector.js\";\nimport { AbstractScene } from \"../abstractScene.js\";\n\nAbstractScene.prototype.removeReflectionProbe = function (toRemove) {\n if (!this.reflectionProbes) {\n return -1;\n }\n const index = this.reflectionProbes.indexOf(toRemove);\n if (index !== -1) {\n this.reflectionProbes.splice(index, 1);\n }\n return index;\n};\nAbstractScene.prototype.addReflectionProbe = function (newReflectionProbe) {\n if (!this.reflectionProbes) {\n this.reflectionProbes = [];\n }\n this.reflectionProbes.push(newReflectionProbe);\n};\n/**\n * Class used to generate realtime reflection / refraction cube textures\n * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/reflectionProbes\n */\nexport class ReflectionProbe {\n /**\n * Creates a new reflection probe\n * @param name defines the name of the probe\n * @param size defines the texture resolution (for each face)\n * @param scene defines the hosting scene\n * @param generateMipMaps defines if mip maps should be generated automatically (true by default)\n * @param useFloat defines if HDR data (float data) should be used to store colors (false by default)\n * @param linearSpace defines if the probe should be generated in linear space or not (false by default)\n */\n constructor(\n /** defines the name of the probe */\n name, size, scene, generateMipMaps = true, useFloat = false, linearSpace = false) {\n this.name = name;\n this._viewMatrix = Matrix.Identity();\n this._target = Vector3.Zero();\n this._add = Vector3.Zero();\n this._invertYAxis = false;\n /** Gets or sets probe position (center of the cube map) */\n this.position = Vector3.Zero();\n /**\n * Gets or sets an object used to store user defined information for the reflection probe.\n */\n this.metadata = null;\n /** @internal */\n this._parentContainer = null;\n this._scene = scene;\n if (scene.getEngine().supportsUniformBuffers) {\n this._sceneUBOs = [];\n for (let i = 0; i < 6; ++i) {\n this._sceneUBOs.push(scene.createSceneUniformBuffer(`Scene for Reflection Probe (name \"${name}\") face #${i}`));\n }\n }\n // Create the scene field if not exist.\n if (!this._scene.reflectionProbes) {\n this._scene.reflectionProbes = new Array();\n }\n this._scene.reflectionProbes.push(this);\n let textureType = 0;\n if (useFloat) {\n const caps = this._scene.getEngine().getCaps();\n if (caps.textureHalfFloatRender) {\n textureType = 2;\n }\n else if (caps.textureFloatRender) {\n textureType = 1;\n }\n }\n this._renderTargetTexture = new RenderTargetTexture(name, size, scene, generateMipMaps, true, textureType, true);\n this._renderTargetTexture.gammaSpace = !linearSpace;\n this._renderTargetTexture.invertZ = scene.useRightHandedSystem;\n const useReverseDepthBuffer = scene.getEngine().useReverseDepthBuffer;\n this._renderTargetTexture.onBeforeRenderObservable.add((faceIndex) => {\n if (this._sceneUBOs) {\n scene.setSceneUniformBuffer(this._sceneUBOs[faceIndex]);\n scene.getSceneUniformBuffer().unbindEffect();\n }\n switch (faceIndex) {\n case 0:\n this._add.copyFromFloats(1, 0, 0);\n break;\n case 1:\n this._add.copyFromFloats(-1, 0, 0);\n break;\n case 2:\n this._add.copyFromFloats(0, this._invertYAxis ? 1 : -1, 0);\n break;\n case 3:\n this._add.copyFromFloats(0, this._invertYAxis ? -1 : 1, 0);\n break;\n case 4:\n this._add.copyFromFloats(0, 0, scene.useRightHandedSystem ? -1 : 1);\n break;\n case 5:\n this._add.copyFromFloats(0, 0, scene.useRightHandedSystem ? 1 : -1);\n break;\n }\n if (this._attachedMesh) {\n this.position.copyFrom(this._attachedMesh.getAbsolutePosition());\n }\n this.position.addToRef(this._add, this._target);\n const lookAtFunction = scene.useRightHandedSystem ? Matrix.LookAtRHToRef : Matrix.LookAtLHToRef;\n const perspectiveFunction = scene.useRightHandedSystem ? Matrix.PerspectiveFovRH : Matrix.PerspectiveFovLH;\n lookAtFunction(this.position, this._target, Vector3.Up(), this._viewMatrix);\n if (scene.activeCamera) {\n this._projectionMatrix = perspectiveFunction(Math.PI / 2, 1, useReverseDepthBuffer ? scene.activeCamera.maxZ : scene.activeCamera.minZ, useReverseDepthBuffer ? scene.activeCamera.minZ : scene.activeCamera.maxZ, this._scene.getEngine().isNDCHalfZRange);\n scene.setTransformMatrix(this._viewMatrix, this._projectionMatrix);\n if (scene.activeCamera.isRigCamera && !this._renderTargetTexture.activeCamera) {\n this._renderTargetTexture.activeCamera = scene.activeCamera.rigParent || null;\n }\n }\n scene._forcedViewPosition = this.position;\n });\n let currentApplyByPostProcess;\n this._renderTargetTexture.onBeforeBindObservable.add(() => {\n var _a, _b;\n this._currentSceneUBO = scene.getSceneUniformBuffer();\n (_b = (_a = scene.getEngine())._debugPushGroup) === null || _b === void 0 ? void 0 : _b.call(_a, `reflection probe generation for ${name}`, 1);\n currentApplyByPostProcess = this._scene.imageProcessingConfiguration.applyByPostProcess;\n if (linearSpace) {\n scene.imageProcessingConfiguration.applyByPostProcess = true;\n }\n });\n this._renderTargetTexture.onAfterUnbindObservable.add(() => {\n var _a, _b;\n scene.imageProcessingConfiguration.applyByPostProcess = currentApplyByPostProcess;\n scene._forcedViewPosition = null;\n if (this._sceneUBOs) {\n scene.setSceneUniformBuffer(this._currentSceneUBO);\n }\n scene.updateTransformMatrix(true);\n (_b = (_a = scene.getEngine())._debugPopGroup) === null || _b === void 0 ? void 0 : _b.call(_a, 1);\n });\n }\n /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */\n get samples() {\n return this._renderTargetTexture.samples;\n }\n set samples(value) {\n this._renderTargetTexture.samples = value;\n }\n /** Gets or sets the refresh rate to use (on every frame by default) */\n get refreshRate() {\n return this._renderTargetTexture.refreshRate;\n }\n set refreshRate(value) {\n this._renderTargetTexture.refreshRate = value;\n }\n /**\n * Gets the hosting scene\n * @returns a Scene\n */\n getScene() {\n return this._scene;\n }\n /** Gets the internal CubeTexture used to render to */\n get cubeTexture() {\n return this._renderTargetTexture;\n }\n /** Gets the list of meshes to render */\n get renderList() {\n return this._renderTargetTexture.renderList;\n }\n /**\n * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)\n * @param mesh defines the mesh to attach to\n */\n attachToMesh(mesh) {\n this._attachedMesh = mesh;\n }\n /**\n * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups\n * @param renderingGroupId The rendering group id corresponding to its index\n * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.\n */\n setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil) {\n this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);\n }\n /**\n * Clean all associated resources\n */\n dispose() {\n const index = this._scene.reflectionProbes.indexOf(this);\n if (index !== -1) {\n // Remove from the scene if found\n this._scene.reflectionProbes.splice(index, 1);\n }\n if (this._parentContainer) {\n const index = this._parentContainer.reflectionProbes.indexOf(this);\n if (index > -1) {\n this._parentContainer.reflectionProbes.splice(index, 1);\n }\n this._parentContainer = null;\n }\n if (this._renderTargetTexture) {\n this._renderTargetTexture.dispose();\n this._renderTargetTexture = null;\n }\n if (this._sceneUBOs) {\n for (const ubo of this._sceneUBOs) {\n ubo.dispose();\n }\n this._sceneUBOs = [];\n }\n }\n /**\n * Converts the reflection probe information to a readable string for debug purpose.\n * @param fullDetails Supports for multiple levels of logging within scene loading\n * @returns the human readable reflection probe info\n */\n toString(fullDetails) {\n let ret = \"Name: \" + this.name;\n if (fullDetails) {\n ret += \", position: \" + this.position.toString();\n if (this._attachedMesh) {\n ret += \", attached mesh: \" + this._attachedMesh.name;\n }\n }\n return ret;\n }\n /**\n * Get the class name of the refection probe.\n * @returns \"ReflectionProbe\"\n */\n getClassName() {\n return \"ReflectionProbe\";\n }\n /**\n * Serialize the reflection probe to a JSON representation we can easily use in the respective Parse function.\n * @returns The JSON representation of the texture\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this, this._renderTargetTexture.serialize());\n serializationObject.isReflectionProbe = true;\n serializationObject.metadata = this.metadata;\n return serializationObject;\n }\n /**\n * Parse the JSON representation of a reflection probe in order to recreate the reflection probe in the given scene.\n * @param parsedReflectionProbe Define the JSON representation of the reflection probe\n * @param scene Define the scene the parsed reflection probe should be instantiated in\n * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies\n * @returns The parsed reflection probe if successful\n */\n static Parse(parsedReflectionProbe, scene, rootUrl) {\n let reflectionProbe = null;\n if (scene.reflectionProbes) {\n for (let index = 0; index < scene.reflectionProbes.length; index++) {\n const rp = scene.reflectionProbes[index];\n if (rp.name === parsedReflectionProbe.name) {\n reflectionProbe = rp;\n break;\n }\n }\n }\n reflectionProbe = SerializationHelper.Parse(() => reflectionProbe || new ReflectionProbe(parsedReflectionProbe.name, parsedReflectionProbe.renderTargetSize, scene, parsedReflectionProbe._generateMipMaps), parsedReflectionProbe, scene, rootUrl);\n reflectionProbe.cubeTexture._waitingRenderList = parsedReflectionProbe.renderList;\n if (parsedReflectionProbe._attachedMesh) {\n reflectionProbe.attachToMesh(scene.getMeshById(parsedReflectionProbe._attachedMesh));\n }\n if (parsedReflectionProbe.metadata) {\n reflectionProbe.metadata = parsedReflectionProbe.metadata;\n }\n return reflectionProbe;\n }\n}\n__decorate([\n serializeAsMeshReference()\n], ReflectionProbe.prototype, \"_attachedMesh\", void 0);\n__decorate([\n serializeAsVector3()\n], ReflectionProbe.prototype, \"position\", void 0);\n//# sourceMappingURL=reflectionProbe.js.map","import { Logger } from \"../../Misc/logger.js\";\nimport { Camera } from \"../../Cameras/camera.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Color3, Color4 } from \"../../Maths/math.color.js\";\nimport { Mesh } from \"../../Meshes/mesh.js\";\nimport { Geometry } from \"../../Meshes/geometry.js\";\nimport { TransformNode } from \"../../Meshes/transformNode.js\";\nimport { Material } from \"../../Materials/material.js\";\nimport { MultiMaterial } from \"../../Materials/multiMaterial.js\";\nimport { CubeTexture } from \"../../Materials/Textures/cubeTexture.js\";\nimport { HDRCubeTexture } from \"../../Materials/Textures/hdrCubeTexture.js\";\nimport { AnimationGroup } from \"../../Animations/animationGroup.js\";\nimport { Light } from \"../../Lights/light.js\";\nimport { SceneComponentConstants } from \"../../sceneComponent.js\";\nimport { SceneLoader } from \"../../Loading/sceneLoader.js\";\nimport { AbstractScene } from \"../../abstractScene.js\";\nimport { AssetContainer } from \"../../assetContainer.js\";\nimport { ActionManager } from \"../../Actions/actionManager.js\";\nimport { Skeleton } from \"../../Bones/skeleton.js\";\nimport { MorphTargetManager } from \"../../Morph/morphTargetManager.js\";\nimport { CannonJSPlugin } from \"../../Physics/v1/Plugins/cannonJSPlugin.js\";\nimport { OimoJSPlugin } from \"../../Physics/v1/Plugins/oimoJSPlugin.js\";\nimport { AmmoJSPlugin } from \"../../Physics/v1/Plugins/ammoJSPlugin.js\";\nimport { ReflectionProbe } from \"../../Probes/reflectionProbe.js\";\nimport { GetClass } from \"../../Misc/typeStore.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nimport { PostProcess } from \"../../PostProcesses/postProcess.js\";\n/** @internal */\n// eslint-disable-next-line @typescript-eslint/naming-convention, no-var\nexport var _BabylonLoaderRegistered = true;\n/**\n * Helps setting up some configuration for the babylon file loader.\n */\nexport class BabylonFileLoaderConfiguration {\n}\n/**\n * The loader does not allow injecting custom physics engine into the plugins.\n * Unfortunately in ES6, we need to manually inject them into the plugin.\n * So you could set this variable to your engine import to make it work.\n */\nBabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine = undefined;\nlet tempIndexContainer = {};\nlet tempMaterialIndexContainer = {};\nconst parseMaterialByPredicate = (predicate, parsedData, scene, rootUrl) => {\n if (!parsedData.materials) {\n return null;\n }\n for (let index = 0, cache = parsedData.materials.length; index < cache; index++) {\n const parsedMaterial = parsedData.materials[index];\n if (predicate(parsedMaterial)) {\n return { parsedMaterial, material: Material.Parse(parsedMaterial, scene, rootUrl) };\n }\n }\n return null;\n};\nconst isDescendantOf = (mesh, names, hierarchyIds) => {\n for (const i in names) {\n if (mesh.name === names[i]) {\n hierarchyIds.push(mesh.id);\n return true;\n }\n }\n if (mesh.parentId !== undefined && hierarchyIds.indexOf(mesh.parentId) !== -1) {\n hierarchyIds.push(mesh.id);\n return true;\n }\n return false;\n};\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst logOperation = (operation, producer) => {\n return (operation +\n \" of \" +\n (producer ? producer.file + \" from \" + producer.name + \" version: \" + producer.version + \", exporter version: \" + producer.exporter_version : \"unknown\"));\n};\nconst loadDetailLevels = (scene, mesh) => {\n const mastermesh = mesh;\n // Every value specified in the ids array of the lod data points to another mesh which should be used as the lower LOD level.\n // The distances (or coverages) array values specified are used along with the lod mesh ids as a hint to determine the switching threshold for the various LODs.\n if (mesh._waitingData.lods) {\n if (mesh._waitingData.lods.ids && mesh._waitingData.lods.ids.length > 0) {\n const lodmeshes = mesh._waitingData.lods.ids;\n const wasenabled = mastermesh.isEnabled(false);\n if (mesh._waitingData.lods.distances) {\n const distances = mesh._waitingData.lods.distances;\n if (distances.length >= lodmeshes.length) {\n const culling = distances.length > lodmeshes.length ? distances[distances.length - 1] : 0;\n mastermesh.setEnabled(false);\n for (let index = 0; index < lodmeshes.length; index++) {\n const lodid = lodmeshes[index];\n const lodmesh = scene.getMeshById(lodid);\n if (lodmesh != null) {\n mastermesh.addLODLevel(distances[index], lodmesh);\n }\n }\n if (culling > 0) {\n mastermesh.addLODLevel(culling, null);\n }\n if (wasenabled === true) {\n mastermesh.setEnabled(true);\n }\n }\n else {\n Tools.Warn(\"Invalid level of detail distances for \" + mesh.name);\n }\n }\n }\n mesh._waitingData.lods = null;\n }\n};\nconst findParent = (parentId, parentInstanceIndex, scene) => {\n if (typeof parentId !== \"number\") {\n const parentEntry = scene.getLastEntryById(parentId);\n if (parentEntry && parentInstanceIndex !== undefined && parentInstanceIndex !== null) {\n const instance = parentEntry.instances[parseInt(parentInstanceIndex)];\n return instance;\n }\n return parentEntry;\n }\n const parent = tempIndexContainer[parentId];\n if (parent && parentInstanceIndex !== undefined && parentInstanceIndex !== null) {\n const instance = parent.instances[parseInt(parentInstanceIndex)];\n return instance;\n }\n return parent;\n};\nconst findMaterial = (materialId, scene) => {\n if (typeof materialId !== \"number\") {\n return scene.getLastMaterialById(materialId, true);\n }\n return tempMaterialIndexContainer[materialId];\n};\nconst loadAssetContainer = (scene, data, rootUrl, onError, addToScene = false) => {\n const container = new AssetContainer(scene);\n // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details\n // when SceneLoader.debugLogging = true (default), or exception encountered.\n // Everything stored in var log instead of writing separate lines to support only writing in exception,\n // and avoid problems with multiple concurrent .babylon loads.\n let log = \"importScene has failed JSON parse\";\n try {\n // eslint-disable-next-line no-var\n var parsedData = JSON.parse(data);\n log = \"\";\n const fullDetails = SceneLoader.loggingLevel === SceneLoader.DETAILED_LOGGING;\n let index;\n let cache;\n // Environment texture\n if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {\n // PBR needed for both HDR texture (gamma space) & a sky box\n const isPBR = parsedData.isPBR !== undefined ? parsedData.isPBR : true;\n if (parsedData.environmentTextureType && parsedData.environmentTextureType === \"BABYLON.HDRCubeTexture\") {\n const hdrSize = parsedData.environmentTextureSize ? parsedData.environmentTextureSize : 128;\n const hdrTexture = new HDRCubeTexture((parsedData.environmentTexture.match(/https?:\\/\\//g) ? \"\" : rootUrl) + parsedData.environmentTexture, scene, hdrSize, true, !isPBR, undefined, parsedData.environmentTexturePrefilterOnLoad);\n if (parsedData.environmentTextureRotationY) {\n hdrTexture.rotationY = parsedData.environmentTextureRotationY;\n }\n scene.environmentTexture = hdrTexture;\n }\n else {\n if (typeof parsedData.environmentTexture === \"object\") {\n const environmentTexture = CubeTexture.Parse(parsedData.environmentTexture, scene, rootUrl);\n scene.environmentTexture = environmentTexture;\n }\n else if (parsedData.environmentTexture.endsWith(\".env\")) {\n const compressedTexture = new CubeTexture((parsedData.environmentTexture.match(/https?:\\/\\//g) ? \"\" : rootUrl) + parsedData.environmentTexture, scene, parsedData.environmentTextureForcedExtension);\n if (parsedData.environmentTextureRotationY) {\n compressedTexture.rotationY = parsedData.environmentTextureRotationY;\n }\n scene.environmentTexture = compressedTexture;\n }\n else {\n const cubeTexture = CubeTexture.CreateFromPrefilteredData((parsedData.environmentTexture.match(/https?:\\/\\//g) ? \"\" : rootUrl) + parsedData.environmentTexture, scene, parsedData.environmentTextureForcedExtension);\n if (parsedData.environmentTextureRotationY) {\n cubeTexture.rotationY = parsedData.environmentTextureRotationY;\n }\n scene.environmentTexture = cubeTexture;\n }\n }\n if (parsedData.createDefaultSkybox === true) {\n const skyboxScale = scene.activeCamera !== undefined && scene.activeCamera !== null ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;\n const skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;\n scene.createDefaultSkybox(scene.environmentTexture, isPBR, skyboxScale, skyboxBlurLevel);\n }\n container.environmentTexture = scene.environmentTexture;\n }\n // Environment Intensity\n if (parsedData.environmentIntensity !== undefined && parsedData.environmentIntensity !== null) {\n scene.environmentIntensity = parsedData.environmentIntensity;\n }\n // Lights\n if (parsedData.lights !== undefined && parsedData.lights !== null) {\n for (index = 0, cache = parsedData.lights.length; index < cache; index++) {\n const parsedLight = parsedData.lights[index];\n const light = Light.Parse(parsedLight, scene);\n if (light) {\n tempIndexContainer[parsedLight.uniqueId] = light;\n container.lights.push(light);\n light._parentContainer = container;\n log += index === 0 ? \"\\n\\tLights:\" : \"\";\n log += \"\\n\\t\\t\" + light.toString(fullDetails);\n }\n }\n }\n // Reflection probes\n if (parsedData.reflectionProbes !== undefined && parsedData.reflectionProbes !== null) {\n for (index = 0, cache = parsedData.reflectionProbes.length; index < cache; index++) {\n const parsedReflectionProbe = parsedData.reflectionProbes[index];\n const reflectionProbe = ReflectionProbe.Parse(parsedReflectionProbe, scene, rootUrl);\n if (reflectionProbe) {\n container.reflectionProbes.push(reflectionProbe);\n reflectionProbe._parentContainer = container;\n log += index === 0 ? \"\\n\\tReflection Probes:\" : \"\";\n log += \"\\n\\t\\t\" + reflectionProbe.toString(fullDetails);\n }\n }\n }\n // Animations\n if (parsedData.animations !== undefined && parsedData.animations !== null) {\n for (index = 0, cache = parsedData.animations.length; index < cache; index++) {\n const parsedAnimation = parsedData.animations[index];\n const internalClass = GetClass(\"BABYLON.Animation\");\n if (internalClass) {\n const animation = internalClass.Parse(parsedAnimation);\n scene.animations.push(animation);\n container.animations.push(animation);\n log += index === 0 ? \"\\n\\tAnimations:\" : \"\";\n log += \"\\n\\t\\t\" + animation.toString(fullDetails);\n }\n }\n }\n // Materials\n if (parsedData.materials !== undefined && parsedData.materials !== null) {\n for (index = 0, cache = parsedData.materials.length; index < cache; index++) {\n const parsedMaterial = parsedData.materials[index];\n const mat = Material.Parse(parsedMaterial, scene, rootUrl);\n if (mat) {\n tempMaterialIndexContainer[parsedMaterial.uniqueId || parsedMaterial.id] = mat;\n container.materials.push(mat);\n mat._parentContainer = container;\n log += index === 0 ? \"\\n\\tMaterials:\" : \"\";\n log += \"\\n\\t\\t\" + mat.toString(fullDetails);\n // Textures\n const textures = mat.getActiveTextures();\n textures.forEach((t) => {\n if (container.textures.indexOf(t) == -1) {\n container.textures.push(t);\n t._parentContainer = container;\n }\n });\n }\n }\n }\n if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {\n for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {\n const parsedMultiMaterial = parsedData.multiMaterials[index];\n const mmat = MultiMaterial.ParseMultiMaterial(parsedMultiMaterial, scene);\n tempMaterialIndexContainer[parsedMultiMaterial.uniqueId || parsedMultiMaterial.id] = mmat;\n container.multiMaterials.push(mmat);\n mmat._parentContainer = container;\n log += index === 0 ? \"\\n\\tMultiMaterials:\" : \"\";\n log += \"\\n\\t\\t\" + mmat.toString(fullDetails);\n // Textures\n const textures = mmat.getActiveTextures();\n textures.forEach((t) => {\n if (container.textures.indexOf(t) == -1) {\n container.textures.push(t);\n t._parentContainer = container;\n }\n });\n }\n }\n // Morph targets\n if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {\n for (const managerData of parsedData.morphTargetManagers) {\n const manager = MorphTargetManager.Parse(managerData, scene);\n container.morphTargetManagers.push(manager);\n manager._parentContainer = container;\n }\n }\n // Skeletons\n if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {\n for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {\n const parsedSkeleton = parsedData.skeletons[index];\n const skeleton = Skeleton.Parse(parsedSkeleton, scene);\n container.skeletons.push(skeleton);\n skeleton._parentContainer = container;\n log += index === 0 ? \"\\n\\tSkeletons:\" : \"\";\n log += \"\\n\\t\\t\" + skeleton.toString(fullDetails);\n }\n }\n // Geometries\n const geometries = parsedData.geometries;\n if (geometries !== undefined && geometries !== null) {\n const addedGeometry = new Array();\n // VertexData\n const vertexData = geometries.vertexData;\n if (vertexData !== undefined && vertexData !== null) {\n for (index = 0, cache = vertexData.length; index < cache; index++) {\n const parsedVertexData = vertexData[index];\n addedGeometry.push(Geometry.Parse(parsedVertexData, scene, rootUrl));\n }\n }\n addedGeometry.forEach((g) => {\n if (g) {\n container.geometries.push(g);\n g._parentContainer = container;\n }\n });\n }\n // Transform nodes\n if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {\n for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {\n const parsedTransformNode = parsedData.transformNodes[index];\n const node = TransformNode.Parse(parsedTransformNode, scene, rootUrl);\n tempIndexContainer[parsedTransformNode.uniqueId] = node;\n container.transformNodes.push(node);\n node._parentContainer = container;\n }\n }\n // Meshes\n if (parsedData.meshes !== undefined && parsedData.meshes !== null) {\n for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {\n const parsedMesh = parsedData.meshes[index];\n const mesh = Mesh.Parse(parsedMesh, scene, rootUrl);\n tempIndexContainer[parsedMesh.uniqueId] = mesh;\n container.meshes.push(mesh);\n mesh._parentContainer = container;\n if (mesh.hasInstances) {\n for (const instance of mesh.instances) {\n container.meshes.push(instance);\n instance._parentContainer = container;\n }\n }\n log += index === 0 ? \"\\n\\tMeshes:\" : \"\";\n log += \"\\n\\t\\t\" + mesh.toString(fullDetails);\n }\n }\n // Cameras\n if (parsedData.cameras !== undefined && parsedData.cameras !== null) {\n for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {\n const parsedCamera = parsedData.cameras[index];\n const camera = Camera.Parse(parsedCamera, scene);\n tempIndexContainer[parsedCamera.uniqueId] = camera;\n container.cameras.push(camera);\n camera._parentContainer = container;\n log += index === 0 ? \"\\n\\tCameras:\" : \"\";\n log += \"\\n\\t\\t\" + camera.toString(fullDetails);\n }\n }\n // Postprocesses\n if (parsedData.postProcesses !== undefined && parsedData.postProcesses !== null) {\n for (index = 0, cache = parsedData.postProcesses.length; index < cache; index++) {\n const parsedPostProcess = parsedData.postProcesses[index];\n const postProcess = PostProcess.Parse(parsedPostProcess, scene, rootUrl);\n if (postProcess) {\n container.postProcesses.push(postProcess);\n postProcess._parentContainer = container;\n log += index === 0 ? \"\\nPostprocesses:\" : \"\";\n log += \"\\n\\t\\t\" + postProcess.toString();\n }\n }\n }\n // Animation Groups\n if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {\n for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {\n const parsedAnimationGroup = parsedData.animationGroups[index];\n const animationGroup = AnimationGroup.Parse(parsedAnimationGroup, scene);\n container.animationGroups.push(animationGroup);\n animationGroup._parentContainer = container;\n log += index === 0 ? \"\\n\\tAnimationGroups:\" : \"\";\n log += \"\\n\\t\\t\" + animationGroup.toString(fullDetails);\n }\n }\n // Browsing all the graph to connect the dots\n for (index = 0, cache = scene.cameras.length; index < cache; index++) {\n const camera = scene.cameras[index];\n if (camera._waitingParentId !== null) {\n camera.parent = findParent(camera._waitingParentId, camera._waitingParentInstanceIndex, scene);\n camera._waitingParentId = null;\n camera._waitingParentInstanceIndex = null;\n }\n }\n for (index = 0, cache = scene.lights.length; index < cache; index++) {\n const light = scene.lights[index];\n if (light && light._waitingParentId !== null) {\n light.parent = findParent(light._waitingParentId, light._waitingParentInstanceIndex, scene);\n light._waitingParentId = null;\n light._waitingParentInstanceIndex = null;\n }\n }\n // Connect parents & children and parse actions and lods\n for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {\n const transformNode = scene.transformNodes[index];\n if (transformNode._waitingParentId !== null) {\n transformNode.parent = findParent(transformNode._waitingParentId, transformNode._waitingParentInstanceIndex, scene);\n transformNode._waitingParentId = null;\n transformNode._waitingParentInstanceIndex = null;\n }\n }\n for (index = 0, cache = scene.meshes.length; index < cache; index++) {\n const mesh = scene.meshes[index];\n if (mesh._waitingParentId !== null) {\n mesh.parent = findParent(mesh._waitingParentId, mesh._waitingParentInstanceIndex, scene);\n mesh._waitingParentId = null;\n mesh._waitingParentInstanceIndex = null;\n }\n if (mesh._waitingData.lods) {\n loadDetailLevels(scene, mesh);\n }\n }\n // link multimats with materials\n scene.multiMaterials.forEach((multimat) => {\n multimat._waitingSubMaterialsUniqueIds.forEach((subMaterial) => {\n multimat.subMaterials.push(findMaterial(subMaterial, scene));\n });\n multimat._waitingSubMaterialsUniqueIds = [];\n });\n // link meshes with materials\n scene.meshes.forEach((mesh) => {\n if (mesh._waitingMaterialId !== null) {\n mesh.material = findMaterial(mesh._waitingMaterialId, scene);\n mesh._waitingMaterialId = null;\n }\n });\n // link skeleton transform nodes\n for (index = 0, cache = scene.skeletons.length; index < cache; index++) {\n const skeleton = scene.skeletons[index];\n if (skeleton._hasWaitingData) {\n if (skeleton.bones != null) {\n skeleton.bones.forEach((bone) => {\n if (bone._waitingTransformNodeId) {\n const linkTransformNode = scene.getLastEntryById(bone._waitingTransformNodeId);\n if (linkTransformNode) {\n bone.linkTransformNode(linkTransformNode);\n }\n bone._waitingTransformNodeId = null;\n }\n });\n }\n skeleton._hasWaitingData = null;\n }\n }\n // freeze world matrix application\n for (index = 0, cache = scene.meshes.length; index < cache; index++) {\n const currentMesh = scene.meshes[index];\n if (currentMesh._waitingData.freezeWorldMatrix) {\n currentMesh.freezeWorldMatrix();\n currentMesh._waitingData.freezeWorldMatrix = null;\n }\n else {\n currentMesh.computeWorldMatrix(true);\n }\n }\n // Lights exclusions / inclusions\n for (index = 0, cache = scene.lights.length; index < cache; index++) {\n const light = scene.lights[index];\n // Excluded check\n if (light._excludedMeshesIds.length > 0) {\n for (let excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {\n const excludedMesh = scene.getMeshById(light._excludedMeshesIds[excludedIndex]);\n if (excludedMesh) {\n light.excludedMeshes.push(excludedMesh);\n }\n }\n light._excludedMeshesIds = [];\n }\n // Included check\n if (light._includedOnlyMeshesIds.length > 0) {\n for (let includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {\n const includedOnlyMesh = scene.getMeshById(light._includedOnlyMeshesIds[includedOnlyIndex]);\n if (includedOnlyMesh) {\n light.includedOnlyMeshes.push(includedOnlyMesh);\n }\n }\n light._includedOnlyMeshesIds = [];\n }\n }\n scene.geometries.forEach((g) => {\n g._loadedUniqueId = \"\";\n });\n AbstractScene.Parse(parsedData, scene, container, rootUrl);\n // Actions (scene) Done last as it can access other objects.\n for (index = 0, cache = scene.meshes.length; index < cache; index++) {\n const mesh = scene.meshes[index];\n if (mesh._waitingData.actions) {\n ActionManager.Parse(mesh._waitingData.actions, mesh, scene);\n mesh._waitingData.actions = null;\n }\n }\n if (parsedData.actions !== undefined && parsedData.actions !== null) {\n ActionManager.Parse(parsedData.actions, null, scene);\n }\n }\n catch (err) {\n const msg = logOperation(\"loadAssets\", parsedData ? parsedData.producer : \"Unknown\") + log;\n if (onError) {\n onError(msg, err);\n }\n else {\n Logger.Log(msg);\n throw err;\n }\n }\n finally {\n tempIndexContainer = {};\n tempMaterialIndexContainer = {};\n if (!addToScene) {\n container.removeAllFromScene();\n }\n if (log !== null && SceneLoader.loggingLevel !== SceneLoader.NO_LOGGING) {\n Logger.Log(logOperation(\"loadAssets\", parsedData ? parsedData.producer : \"Unknown\") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? log : \"\"));\n }\n }\n return container;\n};\nSceneLoader.RegisterPlugin({\n name: \"babylon.js\",\n extensions: \".babylon\",\n canDirectLoad: (data) => {\n if (data.indexOf(\"babylon\") !== -1) {\n // We consider that the producer string is filled\n return true;\n }\n return false;\n },\n importMesh: (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) => {\n var _a;\n // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details\n // when SceneLoader.debugLogging = true (default), or exception encountered.\n // Everything stored in var log instead of writing separate lines to support only writing in exception,\n // and avoid problems with multiple concurrent .babylon loads.\n let log = \"importMesh has failed JSON parse\";\n try {\n // eslint-disable-next-line no-var\n var parsedData = JSON.parse(data);\n log = \"\";\n const fullDetails = SceneLoader.loggingLevel === SceneLoader.DETAILED_LOGGING;\n if (!meshesNames) {\n meshesNames = null;\n }\n else if (!Array.isArray(meshesNames)) {\n meshesNames = [meshesNames];\n }\n const hierarchyIds = new Array();\n const parsedIdToNodeMap = new Map();\n // Transform nodes (the overall idea is to load all of them as this is super fast and then get rid of the ones we don't need)\n const loadedTransformNodes = [];\n if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {\n for (let index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {\n const parsedJSONTransformNode = parsedData.transformNodes[index];\n const parsedTransformNode = TransformNode.Parse(parsedJSONTransformNode, scene, rootUrl);\n loadedTransformNodes.push(parsedTransformNode);\n parsedIdToNodeMap.set(parsedTransformNode._waitingParsedUniqueId, parsedTransformNode);\n parsedTransformNode._waitingParsedUniqueId = null;\n }\n }\n if (parsedData.meshes !== undefined && parsedData.meshes !== null) {\n const loadedSkeletonsIds = [];\n const loadedMaterialsIds = [];\n const loadedMaterialsUniqueIds = [];\n const loadedMorphTargetsIds = [];\n for (let index = 0, cache = parsedData.meshes.length; index < cache; index++) {\n const parsedMesh = parsedData.meshes[index];\n if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {\n if (meshesNames !== null) {\n // Remove found mesh name from list.\n delete meshesNames[meshesNames.indexOf(parsedMesh.name)];\n }\n //Geometry?\n if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {\n //does the file contain geometries?\n if (parsedData.geometries !== undefined && parsedData.geometries !== null) {\n //find the correct geometry and add it to the scene\n let found = false;\n [\"boxes\", \"spheres\", \"cylinders\", \"toruses\", \"grounds\", \"planes\", \"torusKnots\", \"vertexData\"].forEach((geometryType) => {\n if (found === true || !parsedData.geometries[geometryType] || !Array.isArray(parsedData.geometries[geometryType])) {\n return;\n }\n else {\n parsedData.geometries[geometryType].forEach((parsedGeometryData) => {\n if (parsedGeometryData.id === parsedMesh.geometryId) {\n switch (geometryType) {\n case \"vertexData\":\n Geometry.Parse(parsedGeometryData, scene, rootUrl);\n break;\n }\n found = true;\n }\n });\n }\n });\n if (found === false) {\n Logger.Warn(\"Geometry not found for mesh \" + parsedMesh.id);\n }\n }\n }\n // Material ?\n if (parsedMesh.materialUniqueId || parsedMesh.materialId) {\n // if we have a unique ID, look up and store in loadedMaterialsUniqueIds, else use loadedMaterialsIds\n const materialArray = parsedMesh.materialUniqueId ? loadedMaterialsUniqueIds : loadedMaterialsIds;\n let materialFound = materialArray.indexOf(parsedMesh.materialUniqueId || parsedMesh.materialId) !== -1;\n if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {\n // Loads a submaterial of a multimaterial\n const loadSubMaterial = (subMatId, predicate) => {\n materialArray.push(subMatId);\n const mat = parseMaterialByPredicate(predicate, parsedData, scene, rootUrl);\n if (mat && mat.material) {\n tempMaterialIndexContainer[mat.parsedMaterial.uniqueId || mat.parsedMaterial.id] = mat.material;\n log += \"\\n\\tMaterial \" + mat.material.toString(fullDetails);\n }\n };\n for (let multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {\n const parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];\n if ((parsedMesh.materialUniqueId && parsedMultiMaterial.uniqueId === parsedMesh.materialUniqueId) ||\n parsedMultiMaterial.id === parsedMesh.materialId) {\n if (parsedMultiMaterial.materialsUniqueIds) {\n // if the materials inside the multimat are stored by unique id\n parsedMultiMaterial.materialsUniqueIds.forEach((subMatId) => loadSubMaterial(subMatId, (parsedMaterial) => parsedMaterial.uniqueId === subMatId));\n }\n else {\n // if the mats are stored by id instead\n parsedMultiMaterial.materials.forEach((subMatId) => loadSubMaterial(subMatId, (parsedMaterial) => parsedMaterial.id === subMatId));\n }\n materialArray.push(parsedMultiMaterial.uniqueId || parsedMultiMaterial.id);\n const mmat = MultiMaterial.ParseMultiMaterial(parsedMultiMaterial, scene);\n tempMaterialIndexContainer[parsedMultiMaterial.uniqueId || parsedMultiMaterial.id] = mmat;\n if (mmat) {\n materialFound = true;\n log += \"\\n\\tMulti-Material \" + mmat.toString(fullDetails);\n }\n break;\n }\n }\n }\n if (materialFound === false) {\n materialArray.push(parsedMesh.materialUniqueId || parsedMesh.materialId);\n const mat = parseMaterialByPredicate((parsedMaterial) => (parsedMesh.materialUniqueId && parsedMaterial.uniqueId === parsedMesh.materialUniqueId) || parsedMaterial.id === parsedMesh.materialId, parsedData, scene, rootUrl);\n if (!mat || !mat.material) {\n Logger.Warn(\"Material not found for mesh \" + parsedMesh.id);\n }\n else {\n tempMaterialIndexContainer[mat.parsedMaterial.uniqueId || mat.parsedMaterial.id] = mat.material;\n log += \"\\n\\tMaterial \" + mat.material.toString(fullDetails);\n }\n }\n }\n // Skeleton ?\n if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {\n const skeletonAlreadyLoaded = loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1;\n if (!skeletonAlreadyLoaded) {\n for (let skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {\n const parsedSkeleton = parsedData.skeletons[skeletonIndex];\n if (parsedSkeleton.id === parsedMesh.skeletonId) {\n const skeleton = Skeleton.Parse(parsedSkeleton, scene);\n skeletons.push(skeleton);\n loadedSkeletonsIds.push(parsedSkeleton.id);\n log += \"\\n\\tSkeleton \" + skeleton.toString(fullDetails);\n }\n }\n }\n }\n // Morph targets ?\n if (parsedMesh.morphTargetManagerId > -1 && parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {\n const morphTargetAlreadyLoaded = loadedMorphTargetsIds.indexOf(parsedMesh.morphTargetManagerId) > -1;\n if (!morphTargetAlreadyLoaded) {\n for (let morphTargetIndex = 0, morphTargetCache = parsedData.morphTargetManagers.length; morphTargetIndex < morphTargetCache; morphTargetIndex++) {\n const parsedMorphTarget = parsedData.morphTargetManagers[morphTargetIndex];\n if (parsedMorphTarget.id === parsedMesh.morphTargetManagerId) {\n const morphTarget = MorphTargetManager.Parse(parsedMorphTarget, scene);\n loadedMorphTargetsIds.push(morphTarget.uniqueId);\n log += \"\\nMorph target \" + morphTarget.toString();\n }\n }\n }\n }\n const mesh = Mesh.Parse(parsedMesh, scene, rootUrl);\n meshes.push(mesh);\n parsedIdToNodeMap.set(mesh._waitingParsedUniqueId, mesh);\n mesh._waitingParsedUniqueId = null;\n log += \"\\n\\tMesh \" + mesh.toString(fullDetails);\n }\n }\n // link multimats with materials\n scene.multiMaterials.forEach((multimat) => {\n multimat._waitingSubMaterialsUniqueIds.forEach((subMaterial) => {\n multimat.subMaterials.push(findMaterial(subMaterial, scene));\n });\n multimat._waitingSubMaterialsUniqueIds = [];\n });\n // link meshes with materials\n scene.meshes.forEach((mesh) => {\n if (mesh._waitingMaterialId !== null) {\n mesh.material = findMaterial(mesh._waitingMaterialId, scene);\n mesh._waitingMaterialId = null;\n }\n });\n // Connecting parents and lods\n for (let index = 0, cache = scene.transformNodes.length; index < cache; index++) {\n const transformNode = scene.transformNodes[index];\n if (transformNode._waitingParentId !== null) {\n let parent = parsedIdToNodeMap.get(parseInt(transformNode._waitingParentId)) || null;\n if (parent === null) {\n parent = scene.getLastEntryById(transformNode._waitingParentId);\n }\n let parentNode = parent;\n if (transformNode._waitingParentInstanceIndex) {\n parentNode = parent.instances[parseInt(transformNode._waitingParentInstanceIndex)];\n transformNode._waitingParentInstanceIndex = null;\n }\n transformNode.parent = parentNode;\n transformNode._waitingParentId = null;\n }\n }\n let currentMesh;\n for (let index = 0, cache = scene.meshes.length; index < cache; index++) {\n currentMesh = scene.meshes[index];\n if (currentMesh._waitingParentId) {\n let parent = parsedIdToNodeMap.get(parseInt(currentMesh._waitingParentId)) || null;\n if (parent === null) {\n parent = scene.getLastEntryById(currentMesh._waitingParentId);\n }\n let parentNode = parent;\n if (currentMesh._waitingParentInstanceIndex) {\n parentNode = parent.instances[parseInt(currentMesh._waitingParentInstanceIndex)];\n currentMesh._waitingParentInstanceIndex = null;\n }\n currentMesh.parent = parentNode;\n if (((_a = currentMesh.parent) === null || _a === void 0 ? void 0 : _a.getClassName()) === \"TransformNode\") {\n const loadedTransformNodeIndex = loadedTransformNodes.indexOf(currentMesh.parent);\n if (loadedTransformNodeIndex > -1) {\n loadedTransformNodes.splice(loadedTransformNodeIndex, 1);\n }\n }\n currentMesh._waitingParentId = null;\n }\n if (currentMesh._waitingData.lods) {\n loadDetailLevels(scene, currentMesh);\n }\n }\n // Remove unused transform nodes\n for (const transformNode of loadedTransformNodes) {\n transformNode.dispose();\n }\n // link skeleton transform nodes\n for (let index = 0, cache = scene.skeletons.length; index < cache; index++) {\n const skeleton = scene.skeletons[index];\n if (skeleton._hasWaitingData) {\n if (skeleton.bones != null) {\n skeleton.bones.forEach((bone) => {\n if (bone._waitingTransformNodeId) {\n const linkTransformNode = scene.getLastEntryById(bone._waitingTransformNodeId);\n if (linkTransformNode) {\n bone.linkTransformNode(linkTransformNode);\n }\n bone._waitingTransformNodeId = null;\n }\n });\n }\n skeleton._hasWaitingData = null;\n }\n }\n // freeze and compute world matrix application\n for (let index = 0, cache = scene.meshes.length; index < cache; index++) {\n currentMesh = scene.meshes[index];\n if (currentMesh._waitingData.freezeWorldMatrix) {\n currentMesh.freezeWorldMatrix();\n currentMesh._waitingData.freezeWorldMatrix = null;\n }\n else {\n currentMesh.computeWorldMatrix(true);\n }\n }\n }\n // Particles\n if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {\n const parser = AbstractScene.GetIndividualParser(SceneComponentConstants.NAME_PARTICLESYSTEM);\n if (parser) {\n for (let index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {\n const parsedParticleSystem = parsedData.particleSystems[index];\n if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {\n particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));\n }\n }\n }\n }\n scene.geometries.forEach((g) => {\n g._loadedUniqueId = \"\";\n });\n return true;\n }\n catch (err) {\n const msg = logOperation(\"importMesh\", parsedData ? parsedData.producer : \"Unknown\") + log;\n if (onError) {\n onError(msg, err);\n }\n else {\n Logger.Log(msg);\n throw err;\n }\n }\n finally {\n if (log !== null && SceneLoader.loggingLevel !== SceneLoader.NO_LOGGING) {\n Logger.Log(logOperation(\"importMesh\", parsedData ? parsedData.producer : \"Unknown\") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? log : \"\"));\n }\n tempMaterialIndexContainer = {};\n }\n return false;\n },\n load: (scene, data, rootUrl, onError) => {\n // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details\n // when SceneLoader.debugLogging = true (default), or exception encountered.\n // Everything stored in var log instead of writing separate lines to support only writing in exception,\n // and avoid problems with multiple concurrent .babylon loads.\n let log = \"importScene has failed JSON parse\";\n try {\n // eslint-disable-next-line no-var\n var parsedData = JSON.parse(data);\n log = \"\";\n // Scene\n if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {\n scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !SceneLoader.ForceFullSceneLoadingForIncremental;\n }\n if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {\n scene.autoClear = parsedData.autoClear;\n }\n if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {\n scene.clearColor = Color4.FromArray(parsedData.clearColor);\n }\n if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {\n scene.ambientColor = Color3.FromArray(parsedData.ambientColor);\n }\n if (parsedData.gravity !== undefined && parsedData.gravity !== null) {\n scene.gravity = Vector3.FromArray(parsedData.gravity);\n }\n if (parsedData.useRightHandedSystem !== undefined) {\n scene.useRightHandedSystem = !!parsedData.useRightHandedSystem;\n }\n // Fog\n if (parsedData.fogMode && parsedData.fogMode !== 0) {\n scene.fogMode = parsedData.fogMode;\n scene.fogColor = Color3.FromArray(parsedData.fogColor);\n scene.fogStart = parsedData.fogStart;\n scene.fogEnd = parsedData.fogEnd;\n scene.fogDensity = parsedData.fogDensity;\n log += \"\\tFog mode for scene: \";\n switch (scene.fogMode) {\n // getters not compiling, so using hardcoded\n case 1:\n log += \"exp\\n\";\n break;\n case 2:\n log += \"exp2\\n\";\n break;\n case 3:\n log += \"linear\\n\";\n break;\n }\n }\n //Physics\n if (parsedData.physicsEnabled) {\n let physicsPlugin;\n if (parsedData.physicsEngine === \"cannon\" || parsedData.physicsEngine === CannonJSPlugin.name) {\n physicsPlugin = new CannonJSPlugin(undefined, undefined, BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine);\n }\n else if (parsedData.physicsEngine === \"oimo\" || parsedData.physicsEngine === OimoJSPlugin.name) {\n physicsPlugin = new OimoJSPlugin(undefined, BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine);\n }\n else if (parsedData.physicsEngine === \"ammo\" || parsedData.physicsEngine === AmmoJSPlugin.name) {\n physicsPlugin = new AmmoJSPlugin(undefined, BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine, undefined);\n }\n log = \"\\tPhysics engine \" + (parsedData.physicsEngine ? parsedData.physicsEngine : \"oimo\") + \" enabled\\n\";\n //else - default engine, which is currently oimo\n const physicsGravity = parsedData.physicsGravity ? Vector3.FromArray(parsedData.physicsGravity) : null;\n scene.enablePhysics(physicsGravity, physicsPlugin);\n }\n // Metadata\n if (parsedData.metadata !== undefined && parsedData.metadata !== null) {\n scene.metadata = parsedData.metadata;\n }\n //collisions, if defined. otherwise, default is true\n if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {\n scene.collisionsEnabled = parsedData.collisionsEnabled;\n }\n const container = loadAssetContainer(scene, data, rootUrl, onError, true);\n if (!container) {\n return false;\n }\n if (parsedData.autoAnimate) {\n scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);\n }\n if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {\n scene.setActiveCameraById(parsedData.activeCameraID);\n }\n // Finish\n return true;\n }\n catch (err) {\n const msg = logOperation(\"importScene\", parsedData ? parsedData.producer : \"Unknown\") + log;\n if (onError) {\n onError(msg, err);\n }\n else {\n Logger.Log(msg);\n throw err;\n }\n }\n finally {\n if (log !== null && SceneLoader.loggingLevel !== SceneLoader.NO_LOGGING) {\n Logger.Log(logOperation(\"importScene\", parsedData ? parsedData.producer : \"Unknown\") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? log : \"\"));\n }\n }\n return false;\n },\n loadAssetContainer: (scene, data, rootUrl, onError) => {\n const container = loadAssetContainer(scene, data, rootUrl, onError);\n return container;\n },\n});\n//# sourceMappingURL=babylonFileLoader.js.map","export {};\n//# sourceMappingURL=iEffectFallbacks.js.map","import { DeepCopier } from \"../Misc/deepCopier.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { SerializationHelper } from \"../Misc/decorators.js\";\n\n/**\n * This represents all the required information to add a fresnel effect on a material:\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/fresnelParameters\n */\nexport class FresnelParameters {\n /**\n * Define if the fresnel effect is enable or not.\n */\n get isEnabled() {\n return this._isEnabled;\n }\n set isEnabled(value) {\n if (this._isEnabled === value) {\n return;\n }\n this._isEnabled = value;\n Engine.MarkAllMaterialsAsDirty(4 | 16);\n }\n /**\n * Creates a new FresnelParameters object.\n *\n * @param options provide your own settings to optionally to override defaults\n */\n constructor(options = {}) {\n this._isEnabled = true;\n this.bias = options.bias === undefined ? 0 : options.bias;\n this.power = options.power === undefined ? 1 : options.power;\n this.leftColor = options.leftColor || Color3.White();\n this.rightColor = options.rightColor || Color3.Black();\n if (options.isEnabled === false) {\n this.isEnabled = false;\n }\n }\n /**\n * Clones the current fresnel and its values\n * @returns a clone fresnel configuration\n */\n clone() {\n const newFresnelParameters = new FresnelParameters();\n DeepCopier.DeepCopy(this, newFresnelParameters);\n return newFresnelParameters;\n }\n /**\n * Determines equality between FresnelParameters objects\n * @param otherFresnelParameters defines the second operand\n * @returns true if the power, bias, leftColor, rightColor and isEnabled values are equal to the given ones\n */\n equals(otherFresnelParameters) {\n return (otherFresnelParameters &&\n this.bias === otherFresnelParameters.bias &&\n this.power === otherFresnelParameters.power &&\n this.leftColor.equals(otherFresnelParameters.leftColor) &&\n this.rightColor.equals(otherFresnelParameters.rightColor) &&\n this.isEnabled === otherFresnelParameters.isEnabled);\n }\n /**\n * Serializes the current fresnel parameters to a JSON representation.\n * @returns the JSON serialization\n */\n serialize() {\n return {\n isEnabled: this.isEnabled,\n leftColor: this.leftColor.asArray(),\n rightColor: this.rightColor.asArray(),\n bias: this.bias,\n power: this.power,\n };\n }\n /**\n * Parse a JSON object and deserialize it to a new Fresnel parameter object.\n * @param parsedFresnelParameters Define the JSON representation\n * @returns the parsed parameters\n */\n static Parse(parsedFresnelParameters) {\n return new FresnelParameters({\n isEnabled: parsedFresnelParameters.isEnabled,\n leftColor: Color3.FromArray(parsedFresnelParameters.leftColor),\n rightColor: Color3.FromArray(parsedFresnelParameters.rightColor),\n bias: parsedFresnelParameters.bias,\n power: parsedFresnelParameters.power || 1.0,\n });\n }\n}\n// References the dependencies.\nSerializationHelper._FresnelParametersParser = FresnelParameters.Parse;\n//# sourceMappingURL=fresnelParameters.js.map","export * from \"./babylonFileLoader.js\";\n//# sourceMappingURL=index.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./loadingScreen.js\";\nexport * from \"./Plugins/index.js\";\nexport * from \"./sceneLoader.js\";\nexport * from \"./sceneLoaderFlags.js\";\n//# sourceMappingURL=index.js.map","export * from \"./backgroundMaterial.js\";\n//# sourceMappingURL=index.js.map","import { Color4 } from \"../../Maths/math.color.js\";\nimport { ShaderMaterial } from \"../shaderMaterial.js\";\nimport \"../../Shaders/color.fragment.js\";\nimport \"../../Shaders/color.vertex.js\";\n/**\n * A material to use for fast depth-only rendering.\n * @since 5.0.0\n */\nexport class OcclusionMaterial extends ShaderMaterial {\n constructor(name, scene) {\n super(name, scene, \"color\", {\n attributes: [\"position\"],\n uniforms: [\"world\", \"viewProjection\", \"color\"],\n });\n this.disableColorWrite = true;\n this.forceDepthWrite = true;\n this.setColor4(\"color\", new Color4(0, 0, 0, 1));\n }\n}\n//# sourceMappingURL=occlusionMaterial.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize, serializeAsColor3, expandToProperty, serializeAsTexture } from \"../../Misc/decorators.js\";\nimport { Color3 } from \"../../Maths/math.color.js\";\nimport { PBRBaseMaterial } from \"./pbrBaseMaterial.js\";\n/**\n * The Physically based simple base material of BJS.\n *\n * This enables better naming and convention enforcements on top of the pbrMaterial.\n * It is used as the base class for both the specGloss and metalRough conventions.\n */\nexport class PBRBaseSimpleMaterial extends PBRBaseMaterial {\n /**\n * Gets the current double sided mode.\n */\n get doubleSided() {\n return this._twoSidedLighting;\n }\n /**\n * If sets to true and backfaceCulling is false, normals will be flipped on the backside.\n */\n set doubleSided(value) {\n if (this._twoSidedLighting === value) {\n return;\n }\n this._twoSidedLighting = value;\n this.backFaceCulling = !value;\n this._markAllSubMeshesAsTexturesDirty();\n }\n /**\n * Instantiates a new PBRMaterial instance.\n *\n * @param name The material name\n * @param scene The scene the material will be use in.\n */\n constructor(name, scene) {\n super(name, scene);\n /**\n * Number of Simultaneous lights allowed on the material.\n */\n this.maxSimultaneousLights = 4;\n /**\n * If sets to true, disables all the lights affecting the material.\n */\n this.disableLighting = false;\n /**\n * If sets to true, x component of normal map value will invert (x = 1.0 - x).\n */\n this.invertNormalMapX = false;\n /**\n * If sets to true, y component of normal map value will invert (y = 1.0 - y).\n */\n this.invertNormalMapY = false;\n /**\n * Emissivie color used to self-illuminate the model.\n */\n this.emissiveColor = new Color3(0, 0, 0);\n /**\n * Occlusion Channel Strength.\n */\n this.occlusionStrength = 1.0;\n /**\n * If true, the light map contains occlusion information instead of lighting info.\n */\n this.useLightmapAsShadowmap = false;\n this._useAlphaFromAlbedoTexture = true;\n this._useAmbientInGrayScale = true;\n }\n getClassName() {\n return \"PBRBaseSimpleMaterial\";\n }\n}\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n], PBRBaseSimpleMaterial.prototype, \"maxSimultaneousLights\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n], PBRBaseSimpleMaterial.prototype, \"disableLighting\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_reflectionTexture\")\n], PBRBaseSimpleMaterial.prototype, \"environmentTexture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRBaseSimpleMaterial.prototype, \"invertNormalMapX\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRBaseSimpleMaterial.prototype, \"invertNormalMapY\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_bumpTexture\")\n], PBRBaseSimpleMaterial.prototype, \"normalTexture\", void 0);\n__decorate([\n serializeAsColor3(\"emissive\"),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRBaseSimpleMaterial.prototype, \"emissiveColor\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRBaseSimpleMaterial.prototype, \"emissiveTexture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_ambientTextureStrength\")\n], PBRBaseSimpleMaterial.prototype, \"occlusionStrength\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_ambientTexture\")\n], PBRBaseSimpleMaterial.prototype, \"occlusionTexture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_alphaCutOff\")\n], PBRBaseSimpleMaterial.prototype, \"alphaCutOff\", void 0);\n__decorate([\n serialize()\n], PBRBaseSimpleMaterial.prototype, \"doubleSided\", null);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", null)\n], PBRBaseSimpleMaterial.prototype, \"lightmapTexture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRBaseSimpleMaterial.prototype, \"useLightmapAsShadowmap\", void 0);\n//# sourceMappingURL=pbrBaseSimpleMaterial.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize, SerializationHelper, serializeAsColor3, expandToProperty, serializeAsTexture } from \"../../Misc/decorators.js\";\nimport { PBRBaseSimpleMaterial } from \"./pbrBaseSimpleMaterial.js\";\nimport { RegisterClass } from \"../../Misc/typeStore.js\";\n/**\n * The PBR material of BJS following the metal roughness convention.\n *\n * This fits to the PBR convention in the GLTF definition:\n * https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Archived/KHR_materials_pbrSpecularGlossiness/README.md\n */\nexport class PBRMetallicRoughnessMaterial extends PBRBaseSimpleMaterial {\n /**\n * Instantiates a new PBRMetalRoughnessMaterial instance.\n *\n * @param name The material name\n * @param scene The scene the material will be use in.\n */\n constructor(name, scene) {\n super(name, scene);\n this._useRoughnessFromMetallicTextureAlpha = false;\n this._useRoughnessFromMetallicTextureGreen = true;\n this._useMetallnessFromMetallicTextureBlue = true;\n this.metallic = 1.0;\n this.roughness = 1.0;\n }\n /**\n * Return the current class name of the material.\n */\n getClassName() {\n return \"PBRMetallicRoughnessMaterial\";\n }\n /**\n * Makes a duplicate of the current material.\n * @param name - name to use for the new material.\n */\n clone(name) {\n const clone = SerializationHelper.Clone(() => new PBRMetallicRoughnessMaterial(name, this.getScene()), this);\n clone.id = name;\n clone.name = name;\n this.clearCoat.copyTo(clone.clearCoat);\n this.anisotropy.copyTo(clone.anisotropy);\n this.brdf.copyTo(clone.brdf);\n this.sheen.copyTo(clone.sheen);\n this.subSurface.copyTo(clone.subSurface);\n return clone;\n }\n /**\n * Serialize the material to a parsable JSON object.\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this);\n serializationObject.customType = \"BABYLON.PBRMetallicRoughnessMaterial\";\n serializationObject.clearCoat = this.clearCoat.serialize();\n serializationObject.anisotropy = this.anisotropy.serialize();\n serializationObject.brdf = this.brdf.serialize();\n serializationObject.sheen = this.sheen.serialize();\n serializationObject.subSurface = this.subSurface.serialize();\n serializationObject.iridescence = this.iridescence.serialize();\n return serializationObject;\n }\n /**\n * Parses a JSON object corresponding to the serialize function.\n * @param source\n * @param scene\n * @param rootUrl\n */\n static Parse(source, scene, rootUrl) {\n const material = SerializationHelper.Parse(() => new PBRMetallicRoughnessMaterial(source.name, scene), source, scene, rootUrl);\n if (source.clearCoat) {\n material.clearCoat.parse(source.clearCoat, scene, rootUrl);\n }\n if (source.anisotropy) {\n material.anisotropy.parse(source.anisotropy, scene, rootUrl);\n }\n if (source.brdf) {\n material.brdf.parse(source.brdf, scene, rootUrl);\n }\n if (source.sheen) {\n material.sheen.parse(source.sheen, scene, rootUrl);\n }\n if (source.subSurface) {\n material.subSurface.parse(source.subSurface, scene, rootUrl);\n }\n if (source.iridescence) {\n material.iridescence.parse(source.iridescence, scene, rootUrl);\n }\n return material;\n }\n}\n__decorate([\n serializeAsColor3(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_albedoColor\")\n], PBRMetallicRoughnessMaterial.prototype, \"baseColor\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_albedoTexture\")\n], PBRMetallicRoughnessMaterial.prototype, \"baseTexture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMetallicRoughnessMaterial.prototype, \"metallic\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMetallicRoughnessMaterial.prototype, \"roughness\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_metallicTexture\")\n], PBRMetallicRoughnessMaterial.prototype, \"metallicRoughnessTexture\", void 0);\nRegisterClass(\"BABYLON.PBRMetallicRoughnessMaterial\", PBRMetallicRoughnessMaterial);\n//# sourceMappingURL=pbrMetallicRoughnessMaterial.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize, SerializationHelper, serializeAsColor3, expandToProperty, serializeAsTexture } from \"../../Misc/decorators.js\";\nimport { PBRBaseSimpleMaterial } from \"./pbrBaseSimpleMaterial.js\";\nimport { RegisterClass } from \"../../Misc/typeStore.js\";\n/**\n * The PBR material of BJS following the specular glossiness convention.\n *\n * This fits to the PBR convention in the GLTF definition:\n * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness\n */\nexport class PBRSpecularGlossinessMaterial extends PBRBaseSimpleMaterial {\n /**\n * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.\n */\n get useMicroSurfaceFromReflectivityMapAlpha() {\n return this._useMicroSurfaceFromReflectivityMapAlpha;\n }\n /**\n * Instantiates a new PBRSpecularGlossinessMaterial instance.\n *\n * @param name The material name\n * @param scene The scene the material will be use in.\n */\n constructor(name, scene) {\n super(name, scene);\n this._useMicroSurfaceFromReflectivityMapAlpha = true;\n }\n /**\n * Return the current class name of the material.\n */\n getClassName() {\n return \"PBRSpecularGlossinessMaterial\";\n }\n /**\n * Makes a duplicate of the current material.\n * @param name - name to use for the new material.\n */\n clone(name) {\n const clone = SerializationHelper.Clone(() => new PBRSpecularGlossinessMaterial(name, this.getScene()), this);\n clone.id = name;\n clone.name = name;\n this.clearCoat.copyTo(clone.clearCoat);\n this.anisotropy.copyTo(clone.anisotropy);\n this.brdf.copyTo(clone.brdf);\n this.sheen.copyTo(clone.sheen);\n this.subSurface.copyTo(clone.subSurface);\n return clone;\n }\n /**\n * Serialize the material to a parsable JSON object.\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this);\n serializationObject.customType = \"BABYLON.PBRSpecularGlossinessMaterial\";\n serializationObject.clearCoat = this.clearCoat.serialize();\n serializationObject.anisotropy = this.anisotropy.serialize();\n serializationObject.brdf = this.brdf.serialize();\n serializationObject.sheen = this.sheen.serialize();\n serializationObject.subSurface = this.subSurface.serialize();\n serializationObject.iridescence = this.iridescence.serialize();\n return serializationObject;\n }\n /**\n * Parses a JSON object corresponding to the serialize function.\n * @param source\n * @param scene\n * @param rootUrl\n */\n static Parse(source, scene, rootUrl) {\n const material = SerializationHelper.Parse(() => new PBRSpecularGlossinessMaterial(source.name, scene), source, scene, rootUrl);\n if (source.clearCoat) {\n material.clearCoat.parse(source.clearCoat, scene, rootUrl);\n }\n if (source.anisotropy) {\n material.anisotropy.parse(source.anisotropy, scene, rootUrl);\n }\n if (source.brdf) {\n material.brdf.parse(source.brdf, scene, rootUrl);\n }\n if (source.sheen) {\n material.sheen.parse(source.sheen, scene, rootUrl);\n }\n if (source.subSurface) {\n material.subSurface.parse(source.subSurface, scene, rootUrl);\n }\n if (source.iridescence) {\n material.iridescence.parse(source.iridescence, scene, rootUrl);\n }\n return material;\n }\n}\n__decorate([\n serializeAsColor3(\"diffuse\"),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_albedoColor\")\n], PBRSpecularGlossinessMaterial.prototype, \"diffuseColor\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_albedoTexture\")\n], PBRSpecularGlossinessMaterial.prototype, \"diffuseTexture\", void 0);\n__decorate([\n serializeAsColor3(\"specular\"),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_reflectivityColor\")\n], PBRSpecularGlossinessMaterial.prototype, \"specularColor\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_microSurface\")\n], PBRSpecularGlossinessMaterial.prototype, \"glossiness\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_reflectivityTexture\")\n], PBRSpecularGlossinessMaterial.prototype, \"specularGlossinessTexture\", void 0);\nRegisterClass(\"BABYLON.PBRSpecularGlossinessMaterial\", PBRSpecularGlossinessMaterial);\n//# sourceMappingURL=pbrSpecularGlossinessMaterial.js.map","export * from \"./pbrAnisotropicConfiguration.js\";\nexport * from \"./pbrBaseMaterial.js\";\nexport * from \"./pbrBaseSimpleMaterial.js\";\nexport * from \"./pbrClearCoatConfiguration.js\";\nexport * from \"./pbrIridescenceConfiguration.js\";\nexport * from \"./pbrMaterial.js\";\nexport * from \"./pbrMetallicRoughnessMaterial.js\";\nexport * from \"./pbrSpecularGlossinessMaterial.js\";\nexport * from \"./pbrSheenConfiguration.js\";\nexport * from \"./pbrSubSurfaceConfiguration.js\";\n//# sourceMappingURL=index.js.map","import { Matrix } from \"../../Maths/math.vector.js\";\nimport { BaseTexture } from \"../../Materials/Textures/baseTexture.js\";\n\nimport { RegisterClass } from \"../../Misc/typeStore.js\";\n// Ensures Raw texture are included\nimport \"../../Engines/Extensions/engine.rawTexture.js\";\n/**\n * This represents a color grading texture. This acts as a lookup table LUT, useful during post process\n * It can help converting any input color in a desired output one. This can then be used to create effects\n * from sepia, black and white to sixties or futuristic rendering...\n *\n * The only supported format is currently 3dl.\n * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table\n */\nexport class ColorGradingTexture extends BaseTexture {\n /**\n * Instantiates a ColorGradingTexture from the following parameters.\n *\n * @param url The location of the color grading data (currently only supporting 3dl)\n * @param sceneOrEngine The scene or engine the texture will be used in\n * @param onLoad defines a callback triggered when the texture has been loaded\n */\n constructor(url, sceneOrEngine, onLoad = null) {\n super(sceneOrEngine);\n if (!url) {\n return;\n }\n this._textureMatrix = Matrix.Identity();\n this.name = url;\n this.url = url;\n this._onLoad = onLoad;\n this._texture = this._getFromCache(url, true);\n if (!this._texture) {\n const scene = this.getScene();\n if (scene) {\n if (!scene.useDelayedTextureLoading) {\n this._loadTexture();\n }\n else {\n this.delayLoadState = 4;\n }\n }\n else {\n this._loadTexture();\n }\n }\n else {\n this._triggerOnLoad();\n }\n }\n /**\n * Fires the onload event from the constructor if requested.\n */\n _triggerOnLoad() {\n if (this._onLoad) {\n this._onLoad();\n }\n }\n /**\n * Returns the texture matrix used in most of the material.\n * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).\n */\n getTextureMatrix() {\n return this._textureMatrix;\n }\n /**\n * Occurs when the file being loaded is a .3dl LUT file.\n */\n _load3dlTexture() {\n const engine = this._getEngine();\n let texture;\n if (!engine._features.support3DTextures) {\n texture = engine.createRawTexture(null, 1, 1, 5, false, false, 2, null, 0);\n }\n else {\n texture = engine.createRawTexture3D(null, 1, 1, 1, 5, false, false, 2, null, 0);\n }\n this._texture = texture;\n this._texture.isReady = false;\n this.isCube = false;\n this.is3D = engine._features.support3DTextures;\n this.wrapU = 0;\n this.wrapV = 0;\n this.wrapR = 0;\n this.anisotropicFilteringLevel = 1;\n const callback = (text) => {\n if (typeof text !== \"string\") {\n return;\n }\n let data = null;\n let tempData = null;\n let line;\n const lines = text.split(\"\\n\");\n let size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;\n let maxColor = 0;\n for (let i = 0; i < lines.length; i++) {\n line = lines[i];\n if (!ColorGradingTexture._NoneEmptyLineRegex.test(line)) {\n continue;\n }\n if (line.indexOf(\"#\") === 0) {\n continue;\n }\n const words = line.split(\" \");\n if (size === 0) {\n // Number of space + one\n size = words.length;\n data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8\n tempData = new Float32Array(size * size * size * 4);\n continue;\n }\n if (size != 0) {\n const r = Math.max(parseInt(words[0]), 0);\n const g = Math.max(parseInt(words[1]), 0);\n const b = Math.max(parseInt(words[2]), 0);\n maxColor = Math.max(r, maxColor);\n maxColor = Math.max(g, maxColor);\n maxColor = Math.max(b, maxColor);\n const pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;\n if (tempData) {\n tempData[pixelStorageIndex + 0] = r;\n tempData[pixelStorageIndex + 1] = g;\n tempData[pixelStorageIndex + 2] = b;\n }\n // Keep for reference in case of back compat problems.\n // pixelIndexSlice++;\n // if (pixelIndexSlice % size == 0) {\n // pixelIndexH++;\n // pixelIndexSlice = 0;\n // if (pixelIndexH % size == 0) {\n // pixelIndexW++;\n // pixelIndexH = 0;\n // }\n // }\n pixelIndexH++;\n if (pixelIndexH % size == 0) {\n pixelIndexSlice++;\n pixelIndexH = 0;\n if (pixelIndexSlice % size == 0) {\n pixelIndexW++;\n pixelIndexSlice = 0;\n }\n }\n }\n }\n if (tempData && data) {\n for (let i = 0; i < tempData.length; i++) {\n if (i > 0 && (i + 1) % 4 === 0) {\n data[i] = 255;\n }\n else {\n const value = tempData[i];\n data[i] = (value / maxColor) * 255;\n }\n }\n }\n if (texture.is3D) {\n texture.updateSize(size, size, size);\n engine.updateRawTexture3D(texture, data, 5, false);\n }\n else {\n texture.updateSize(size * size, size);\n engine.updateRawTexture(texture, data, 5, false);\n }\n texture.isReady = true;\n this._triggerOnLoad();\n };\n const scene = this.getScene();\n if (scene) {\n scene._loadFile(this.url, callback);\n }\n else {\n engine._loadFile(this.url, callback);\n }\n return this._texture;\n }\n /**\n * Starts the loading process of the texture.\n */\n _loadTexture() {\n if (this.url && this.url.toLocaleLowerCase().indexOf(\".3dl\") == this.url.length - 4) {\n this._load3dlTexture();\n }\n }\n /**\n * Clones the color grading texture.\n */\n clone() {\n const newTexture = new ColorGradingTexture(this.url, this.getScene() || this._getEngine());\n // Base texture\n newTexture.level = this.level;\n return newTexture;\n }\n /**\n * Called during delayed load for textures.\n */\n delayLoad() {\n if (this.delayLoadState !== 4) {\n return;\n }\n this.delayLoadState = 1;\n this._texture = this._getFromCache(this.url, true);\n if (!this._texture) {\n this._loadTexture();\n }\n }\n /**\n * Parses a color grading texture serialized by Babylon.\n * @param parsedTexture The texture information being parsedTexture\n * @param scene The scene to load the texture in\n * @returns A color grading texture\n */\n static Parse(parsedTexture, scene) {\n let texture = null;\n if (parsedTexture.name && !parsedTexture.isRenderTarget) {\n texture = new ColorGradingTexture(parsedTexture.name, scene);\n texture.name = parsedTexture.name;\n texture.level = parsedTexture.level;\n }\n return texture;\n }\n /**\n * Serializes the LUT texture to json format.\n */\n serialize() {\n if (!this.name) {\n return null;\n }\n const serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.level = this.level;\n serializationObject.customType = \"BABYLON.ColorGradingTexture\";\n return serializationObject;\n }\n}\n/**\n * Empty line regex stored for GC.\n */\nColorGradingTexture._NoneEmptyLineRegex = /\\S+/;\nRegisterClass(\"BABYLON.ColorGradingTexture\", ColorGradingTexture);\n//# sourceMappingURL=colorGradingTexture.js.map","import { PanoramaToCubeMapTools } from \"../../Misc/HighDynamicRange/panoramaToCubemap.js\";\nimport { BaseTexture } from \"./baseTexture.js\";\nimport { Texture } from \"./texture.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nimport \"../../Engines/Extensions/engine.rawTexture.js\";\n\nimport { LoadImage } from \"../../Misc/fileTools.js\";\n/**\n * This represents a texture coming from an equirectangular image supported by the web browser canvas.\n */\nexport class EquiRectangularCubeTexture extends BaseTexture {\n /**\n * Instantiates an EquiRectangularCubeTexture from the following parameters.\n * @param url The location of the image\n * @param scene The scene the texture will be used in\n * @param size The cubemap desired size (the more it increases the longer the generation will be)\n * @param noMipmap Forces to not generate the mipmap if true\n * @param gammaSpace Specifies if the texture will be used in gamma or linear space\n * (the PBR material requires those textures in linear space, but the standard material would require them in Gamma space)\n * @param onLoad — defines a callback called when texture is loaded\n * @param onError — defines a callback called if there is an error\n */\n constructor(url, scene, size, noMipmap = false, gammaSpace = true, onLoad = null, onError = null, supersample = false) {\n super(scene);\n this._onLoad = null;\n this._onError = null;\n if (!url) {\n throw new Error(\"Image url is not set\");\n }\n this._coordinatesMode = Texture.CUBIC_MODE;\n this.name = url;\n this.url = url;\n this._size = size;\n this._supersample = supersample;\n this._noMipmap = noMipmap;\n this.gammaSpace = gammaSpace;\n this._onLoad = onLoad;\n this._onError = onError;\n this.hasAlpha = false;\n this.isCube = true;\n this._texture = this._getFromCache(url, this._noMipmap, undefined, undefined, undefined, this.isCube);\n if (!this._texture) {\n if (!scene.useDelayedTextureLoading) {\n this._loadImage(this._loadTexture.bind(this), this._onError);\n }\n else {\n this.delayLoadState = 4;\n }\n }\n else if (onLoad) {\n if (this._texture.isReady) {\n Tools.SetImmediate(() => onLoad());\n }\n else {\n this._texture.onLoadedObservable.add(onLoad);\n }\n }\n }\n /**\n * Load the image data, by putting the image on a canvas and extracting its buffer.\n * @param loadTextureCallback\n * @param onError\n */\n _loadImage(loadTextureCallback, onError) {\n const canvas = document.createElement(\"canvas\");\n LoadImage(this.url, (image) => {\n this._width = image.width;\n this._height = image.height;\n canvas.width = this._width;\n canvas.height = this._height;\n const ctx = canvas.getContext(\"2d\");\n ctx.drawImage(image, 0, 0);\n const imageData = ctx.getImageData(0, 0, image.width, image.height);\n this._buffer = imageData.data.buffer;\n canvas.remove();\n loadTextureCallback();\n }, (_, e) => {\n if (onError) {\n onError(`${this.getClassName()} could not be loaded`, e);\n }\n }, null);\n }\n /**\n * Convert the image buffer into a cubemap and create a CubeTexture.\n */\n _loadTexture() {\n const scene = this.getScene();\n const callback = () => {\n const imageData = this._getFloat32ArrayFromArrayBuffer(this._buffer);\n // Extract the raw linear data.\n const data = PanoramaToCubeMapTools.ConvertPanoramaToCubemap(imageData, this._width, this._height, this._size, this._supersample);\n const results = [];\n // Push each faces.\n for (let i = 0; i < 6; i++) {\n const dataFace = data[EquiRectangularCubeTexture._FacesMapping[i]];\n results.push(dataFace);\n }\n return results;\n };\n if (!scene) {\n return;\n }\n this._texture = scene\n .getEngine()\n .createRawCubeTextureFromUrl(this.url, scene, this._size, 4, scene.getEngine().getCaps().textureFloat ? 1 : 7, this._noMipmap, callback, null, this._onLoad, this._onError);\n }\n /**\n * Convert the ArrayBuffer into a Float32Array and drop the transparency channel.\n * @param buffer The ArrayBuffer that should be converted.\n * @returns The buffer as Float32Array.\n */\n _getFloat32ArrayFromArrayBuffer(buffer) {\n const dataView = new DataView(buffer);\n const floatImageData = new Float32Array((buffer.byteLength * 3) / 4);\n let k = 0;\n for (let i = 0; i < buffer.byteLength; i++) {\n // We drop the transparency channel, because we do not need/want it\n if ((i + 1) % 4 !== 0) {\n floatImageData[k++] = dataView.getUint8(i) / 255;\n }\n }\n return floatImageData;\n }\n /**\n * Get the current class name of the texture useful for serialization or dynamic coding.\n * @returns \"EquiRectangularCubeTexture\"\n */\n getClassName() {\n return \"EquiRectangularCubeTexture\";\n }\n /**\n * Create a clone of the current EquiRectangularCubeTexture and return it.\n * @returns A clone of the current EquiRectangularCubeTexture.\n */\n clone() {\n const scene = this.getScene();\n if (!scene) {\n return this;\n }\n const newTexture = new EquiRectangularCubeTexture(this.url, scene, this._size, this._noMipmap, this.gammaSpace);\n // Base texture\n newTexture.level = this.level;\n newTexture.wrapU = this.wrapU;\n newTexture.wrapV = this.wrapV;\n newTexture.coordinatesIndex = this.coordinatesIndex;\n newTexture.coordinatesMode = this.coordinatesMode;\n return newTexture;\n }\n}\n/** The six faces of the cube. */\nEquiRectangularCubeTexture._FacesMapping = [\"right\", \"left\", \"up\", \"down\", \"front\", \"back\"];\n//# sourceMappingURL=equiRectangularCubeTexture.js.map","import { BaseTexture } from \"../../Materials/Textures/baseTexture.js\";\n\nimport { Matrix } from \"../../Maths/math.vector.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport \"../../Engines/Extensions/engine.dynamicTexture.js\";\nimport \"../../Engines/Extensions/engine.videoTexture.js\";\nimport \"../../Engines/Extensions/engine.externalTexture.js\";\n/**\n * This represents the smallest workload to use an already existing element (Canvas or Video) as a texture.\n * To be as efficient as possible depending on your constraints nothing aside the first upload\n * is automatically managed.\n * It is a cheap VideoTexture or DynamicTexture if you prefer to keep full control of the elements\n * in your application.\n *\n * As the update is not automatic, you need to call them manually.\n */\nexport class HtmlElementTexture extends BaseTexture {\n /**\n * Instantiates a HtmlElementTexture from the following parameters.\n *\n * @param name Defines the name of the texture\n * @param element Defines the video or canvas the texture is filled with\n * @param options Defines the other none mandatory texture creation options\n */\n constructor(name, element, options) {\n var _a, _b;\n super(options.scene || options.engine);\n /**\n * Observable triggered once the texture has been loaded.\n */\n this.onLoadObservable = new Observable();\n if (!element || (!options.engine && !options.scene)) {\n return;\n }\n options = Object.assign(Object.assign({}, HtmlElementTexture._DefaultOptions), options);\n this._generateMipMaps = options.generateMipMaps;\n this._samplingMode = options.samplingMode;\n this._textureMatrix = Matrix.Identity();\n this._format = options.format;\n this.name = name;\n this.element = element;\n this._isVideo = !!element.getVideoPlaybackQuality;\n this._externalTexture = this._isVideo ? (_b = (_a = this._engine) === null || _a === void 0 ? void 0 : _a.createExternalTexture(element)) !== null && _b !== void 0 ? _b : null : null;\n this.anisotropicFilteringLevel = 1;\n this._createInternalTexture();\n }\n _createInternalTexture() {\n let width = 0;\n let height = 0;\n if (this._isVideo) {\n width = this.element.videoWidth;\n height = this.element.videoHeight;\n }\n else {\n width = this.element.width;\n height = this.element.height;\n }\n const engine = this._getEngine();\n if (engine) {\n this._texture = engine.createDynamicTexture(width, height, this._generateMipMaps, this._samplingMode);\n this._texture.format = this._format;\n }\n this.update();\n }\n /**\n * Returns the texture matrix used in most of the material.\n */\n getTextureMatrix() {\n return this._textureMatrix;\n }\n /**\n * Updates the content of the texture.\n * @param invertY Defines whether the texture should be inverted on Y (false by default on video and true on canvas)\n */\n update(invertY = null) {\n const engine = this._getEngine();\n if (this._texture == null || engine == null) {\n return;\n }\n const wasReady = this.isReady();\n if (this._isVideo) {\n const videoElement = this.element;\n if (videoElement.readyState < videoElement.HAVE_CURRENT_DATA) {\n return;\n }\n engine.updateVideoTexture(this._texture, this._externalTexture ? this._externalTexture : videoElement, invertY === null ? true : invertY);\n }\n else {\n const canvasElement = this.element;\n engine.updateDynamicTexture(this._texture, canvasElement, invertY === null ? true : invertY, false, this._format);\n }\n if (!wasReady && this.isReady()) {\n this.onLoadObservable.notifyObservers(this);\n }\n }\n /**\n * Dispose the texture and release its associated resources.\n */\n dispose() {\n this.onLoadObservable.clear();\n super.dispose();\n }\n}\nHtmlElementTexture._DefaultOptions = {\n generateMipMaps: false,\n samplingMode: 2,\n format: 5,\n engine: null,\n scene: null,\n};\n//# sourceMappingURL=htmlElementTexture.js.map","export {};\n//# sourceMappingURL=internalTextureLoader.js.map","import { Logger } from \"../Misc/logger.js\";\n//private static _TYPE_NO_DATA = 0;\nconst _TYPE_INDEXED = 1;\nconst _TYPE_RGB = 2;\nconst _TYPE_GREY = 3;\nconst _TYPE_RLE_INDEXED = 9;\nconst _TYPE_RLE_RGB = 10;\nconst _TYPE_RLE_GREY = 11;\nconst _ORIGIN_MASK = 0x30;\nconst _ORIGIN_SHIFT = 0x04;\nconst _ORIGIN_BL = 0x00;\nconst _ORIGIN_BR = 0x01;\nconst _ORIGIN_UL = 0x02;\nconst _ORIGIN_UR = 0x03;\n/**\n * Gets the header of a TGA file\n * @param data defines the TGA data\n * @returns the header\n */\nexport function GetTGAHeader(data) {\n let offset = 0;\n const header = {\n id_length: data[offset++],\n colormap_type: data[offset++],\n image_type: data[offset++],\n colormap_index: data[offset++] | (data[offset++] << 8),\n colormap_length: data[offset++] | (data[offset++] << 8),\n colormap_size: data[offset++],\n origin: [data[offset++] | (data[offset++] << 8), data[offset++] | (data[offset++] << 8)],\n width: data[offset++] | (data[offset++] << 8),\n height: data[offset++] | (data[offset++] << 8),\n pixel_size: data[offset++],\n flags: data[offset++],\n };\n return header;\n}\n/**\n * Uploads TGA content to a Babylon Texture\n * @internal\n */\nexport function UploadContent(texture, data) {\n // Not enough data to contain header ?\n if (data.length < 19) {\n Logger.Error(\"Unable to load TGA file - Not enough data to contain header\");\n return;\n }\n // Read Header\n let offset = 18;\n const header = GetTGAHeader(data);\n // Assume it's a valid Targa file.\n if (header.id_length + offset > data.length) {\n Logger.Error(\"Unable to load TGA file - Not enough data\");\n return;\n }\n // Skip not needed data\n offset += header.id_length;\n let use_rle = false;\n let use_pal = false;\n let use_grey = false;\n // Get some informations.\n switch (header.image_type) {\n case _TYPE_RLE_INDEXED:\n use_rle = true;\n // eslint-disable-next-line no-fallthrough\n case _TYPE_INDEXED:\n use_pal = true;\n break;\n case _TYPE_RLE_RGB:\n use_rle = true;\n // eslint-disable-next-line no-fallthrough\n case _TYPE_RGB:\n // use_rgb = true;\n break;\n case _TYPE_RLE_GREY:\n use_rle = true;\n // eslint-disable-next-line no-fallthrough\n case _TYPE_GREY:\n use_grey = true;\n break;\n }\n let pixel_data;\n // var numAlphaBits = header.flags & 0xf;\n const pixel_size = header.pixel_size >> 3;\n const pixel_total = header.width * header.height * pixel_size;\n // Read palettes\n let palettes;\n if (use_pal) {\n palettes = data.subarray(offset, (offset += header.colormap_length * (header.colormap_size >> 3)));\n }\n // Read LRE\n if (use_rle) {\n pixel_data = new Uint8Array(pixel_total);\n let c, count, i;\n let localOffset = 0;\n const pixels = new Uint8Array(pixel_size);\n while (offset < pixel_total && localOffset < pixel_total) {\n c = data[offset++];\n count = (c & 0x7f) + 1;\n // RLE pixels\n if (c & 0x80) {\n // Bind pixel tmp array\n for (i = 0; i < pixel_size; ++i) {\n pixels[i] = data[offset++];\n }\n // Copy pixel array\n for (i = 0; i < count; ++i) {\n pixel_data.set(pixels, localOffset + i * pixel_size);\n }\n localOffset += pixel_size * count;\n }\n // Raw pixels\n else {\n count *= pixel_size;\n for (i = 0; i < count; ++i) {\n pixel_data[localOffset + i] = data[offset++];\n }\n localOffset += count;\n }\n }\n }\n // RAW Pixels\n else {\n pixel_data = data.subarray(offset, (offset += use_pal ? header.width * header.height : pixel_total));\n }\n // Load to texture\n let x_start, y_start, x_step, y_step, y_end, x_end;\n switch ((header.flags & _ORIGIN_MASK) >> _ORIGIN_SHIFT) {\n default:\n case _ORIGIN_UL:\n x_start = 0;\n x_step = 1;\n x_end = header.width;\n y_start = 0;\n y_step = 1;\n y_end = header.height;\n break;\n case _ORIGIN_BL:\n x_start = 0;\n x_step = 1;\n x_end = header.width;\n y_start = header.height - 1;\n y_step = -1;\n y_end = -1;\n break;\n case _ORIGIN_UR:\n x_start = header.width - 1;\n x_step = -1;\n x_end = -1;\n y_start = 0;\n y_step = 1;\n y_end = header.height;\n break;\n case _ORIGIN_BR:\n x_start = header.width - 1;\n x_step = -1;\n x_end = -1;\n y_start = header.height - 1;\n y_step = -1;\n y_end = -1;\n break;\n }\n // Load the specify method\n const func = \"_getImageData\" + (use_grey ? \"Grey\" : \"\") + header.pixel_size + \"bits\";\n const imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);\n const engine = texture.getEngine();\n engine._uploadDataToTextureDirectly(texture, imageData);\n}\n/**\n * @internal\n */\nfunction _getImageData8bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {\n const image = pixel_data, colormap = palettes;\n const width = header.width, height = header.height;\n let color, i = 0, x, y;\n const imageData = new Uint8Array(width * height * 4);\n for (y = y_start; y !== y_end; y += y_step) {\n for (x = x_start; x !== x_end; x += x_step, i++) {\n color = image[i];\n imageData[(x + width * y) * 4 + 3] = 255;\n imageData[(x + width * y) * 4 + 2] = colormap[color * 3 + 0];\n imageData[(x + width * y) * 4 + 1] = colormap[color * 3 + 1];\n imageData[(x + width * y) * 4 + 0] = colormap[color * 3 + 2];\n }\n }\n return imageData;\n}\n/**\n * @internal\n */\nfunction _getImageData16bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {\n const image = pixel_data;\n const width = header.width, height = header.height;\n let color, i = 0, x, y;\n const imageData = new Uint8Array(width * height * 4);\n for (y = y_start; y !== y_end; y += y_step) {\n for (x = x_start; x !== x_end; x += x_step, i += 2) {\n color = image[i + 0] + (image[i + 1] << 8); // Inversed ?\n const r = ((((color & 0x7c00) >> 10) * 255) / 0x1f) | 0;\n const g = ((((color & 0x03e0) >> 5) * 255) / 0x1f) | 0;\n const b = (((color & 0x001f) * 255) / 0x1f) | 0;\n imageData[(x + width * y) * 4 + 0] = r;\n imageData[(x + width * y) * 4 + 1] = g;\n imageData[(x + width * y) * 4 + 2] = b;\n imageData[(x + width * y) * 4 + 3] = color & 0x8000 ? 0 : 255;\n }\n }\n return imageData;\n}\n/**\n * @internal\n */\nfunction _getImageData24bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {\n const image = pixel_data;\n const width = header.width, height = header.height;\n let i = 0, x, y;\n const imageData = new Uint8Array(width * height * 4);\n for (y = y_start; y !== y_end; y += y_step) {\n for (x = x_start; x !== x_end; x += x_step, i += 3) {\n imageData[(x + width * y) * 4 + 3] = 255;\n imageData[(x + width * y) * 4 + 2] = image[i + 0];\n imageData[(x + width * y) * 4 + 1] = image[i + 1];\n imageData[(x + width * y) * 4 + 0] = image[i + 2];\n }\n }\n return imageData;\n}\n/**\n * @internal\n */\nfunction _getImageData32bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {\n const image = pixel_data;\n const width = header.width, height = header.height;\n let i = 0, x, y;\n const imageData = new Uint8Array(width * height * 4);\n for (y = y_start; y !== y_end; y += y_step) {\n for (x = x_start; x !== x_end; x += x_step, i += 4) {\n imageData[(x + width * y) * 4 + 2] = image[i + 0];\n imageData[(x + width * y) * 4 + 1] = image[i + 1];\n imageData[(x + width * y) * 4 + 0] = image[i + 2];\n imageData[(x + width * y) * 4 + 3] = image[i + 3];\n }\n }\n return imageData;\n}\n/**\n * @internal\n */\nfunction _getImageDataGrey8bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {\n const image = pixel_data;\n const width = header.width, height = header.height;\n let color, i = 0, x, y;\n const imageData = new Uint8Array(width * height * 4);\n for (y = y_start; y !== y_end; y += y_step) {\n for (x = x_start; x !== x_end; x += x_step, i++) {\n color = image[i];\n imageData[(x + width * y) * 4 + 0] = color;\n imageData[(x + width * y) * 4 + 1] = color;\n imageData[(x + width * y) * 4 + 2] = color;\n imageData[(x + width * y) * 4 + 3] = 255;\n }\n }\n return imageData;\n}\n/**\n * @internal\n */\nfunction _getImageDataGrey16bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {\n const image = pixel_data;\n const width = header.width, height = header.height;\n let i = 0, x, y;\n const imageData = new Uint8Array(width * height * 4);\n for (y = y_start; y !== y_end; y += y_step) {\n for (x = x_start; x !== x_end; x += x_step, i += 2) {\n imageData[(x + width * y) * 4 + 0] = image[i + 0];\n imageData[(x + width * y) * 4 + 1] = image[i + 0];\n imageData[(x + width * y) * 4 + 2] = image[i + 0];\n imageData[(x + width * y) * 4 + 3] = image[i + 1];\n }\n }\n return imageData;\n}\n/**\n * Based on jsTGALoader - Javascript loader for TGA file\n * By Vincent Thibault\n * @see http://blog.robrowser.com/javascript-tga-loader.html\n */\nexport const TGATools = {\n /**\n * Gets the header of a TGA file\n * @param data defines the TGA data\n * @returns the header\n */\n GetTGAHeader,\n /**\n * Uploads TGA content to a Babylon Texture\n * @internal\n */\n UploadContent,\n /** @internal */\n _getImageData8bits,\n /** @internal */\n _getImageData16bits,\n /** @internal */\n _getImageData24bits,\n /** @internal */\n _getImageData32bits,\n /** @internal */\n _getImageDataGrey8bits,\n /** @internal */\n _getImageDataGrey16bits,\n};\n//# sourceMappingURL=tga.js.map","import { GetTGAHeader, UploadContent } from \"../../../Misc/tga.js\";\nimport { Engine } from \"../../../Engines/engine.js\";\n/**\n * Implementation of the TGA Texture Loader.\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class _TGATextureLoader {\n constructor() {\n /**\n * Defines whether the loader supports cascade loading the different faces.\n */\n this.supportCascades = false;\n }\n /**\n * This returns if the loader support the current file information.\n * @param extension defines the file extension of the file being loaded\n * @returns true if the loader can load the specified file\n */\n canLoad(extension) {\n return extension.endsWith(\".tga\");\n }\n /**\n * Uploads the cube texture data to the WebGL texture. It has already been bound.\n */\n loadCubeData() {\n throw \".env not supported in Cube.\";\n }\n /**\n * Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param callback defines the method to call once ready to upload\n */\n loadData(data, texture, callback) {\n const bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n const header = GetTGAHeader(bytes);\n callback(header.width, header.height, texture.generateMipMaps, false, () => {\n UploadContent(texture, bytes);\n });\n }\n}\n// Register the loader.\nEngine._TextureLoaders.push(new _TGATextureLoader());\n//# sourceMappingURL=tgaTextureLoader.js.map","import { HDRTools } from \"../../../Misc/HighDynamicRange/hdr.js\";\nimport { Engine } from \"../../../Engines/engine.js\";\n\n/**\n * Implementation of the HDR Texture Loader.\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class _HDRTextureLoader {\n constructor() {\n /**\n * Defines whether the loader supports cascade loading the different faces.\n */\n this.supportCascades = false;\n }\n /**\n * This returns if the loader support the current file information.\n * @param extension defines the file extension of the file being loaded\n * @returns true if the loader can load the specified file\n */\n canLoad(extension) {\n return extension.endsWith(\".hdr\");\n }\n /**\n * Uploads the cube texture data to the WebGL texture. It has already been bound.\n */\n loadCubeData() {\n throw \".env not supported in Cube.\";\n }\n /**\n * Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param callback defines the method to call once ready to upload\n */\n loadData(data, texture, callback) {\n const uint8array = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n const hdrInfo = HDRTools.RGBE_ReadHeader(uint8array);\n const pixelsDataRGB32 = HDRTools.RGBE_ReadPixels(uint8array, hdrInfo);\n const pixels = hdrInfo.width * hdrInfo.height;\n const pixelsDataRGBA32 = new Float32Array(pixels * 4);\n for (let i = 0; i < pixels; i += 1) {\n pixelsDataRGBA32[i * 4] = pixelsDataRGB32[i * 3];\n pixelsDataRGBA32[i * 4 + 1] = pixelsDataRGB32[i * 3 + 1];\n pixelsDataRGBA32[i * 4 + 2] = pixelsDataRGB32[i * 3 + 2];\n pixelsDataRGBA32[i * 4 + 3] = 1;\n }\n callback(hdrInfo.width, hdrInfo.height, texture.generateMipMaps, false, () => {\n const engine = texture.getEngine();\n texture.type = 1;\n texture.format = 5;\n texture._gammaSpace = false;\n engine._uploadDataToTextureDirectly(texture, pixelsDataRGBA32);\n });\n }\n}\n// Register the loader.\nEngine._TextureLoaders.push(new _HDRTextureLoader());\n//# sourceMappingURL=hdrTextureLoader.js.map","import { Tools } from \"./tools.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { InternalTexture, InternalTextureSource } from \"../Materials/Textures/internalTexture.js\";\nimport { Scalar } from \"../Maths/math.scalar.js\";\n\n/**\n * Info about the .basis files\n */\nclass BasisFileInfo {\n}\n/**\n * Result of transcoding a basis file\n */\nclass TranscodeResult {\n}\n/**\n * Configuration options for the Basis transcoder\n */\nexport class BasisTranscodeConfiguration {\n}\n/**\n * @internal\n * Enum of basis transcoder formats\n */\nvar BASIS_FORMATS;\n(function (BASIS_FORMATS) {\n BASIS_FORMATS[BASIS_FORMATS[\"cTFETC1\"] = 0] = \"cTFETC1\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFETC2\"] = 1] = \"cTFETC2\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFBC1\"] = 2] = \"cTFBC1\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFBC3\"] = 3] = \"cTFBC3\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFBC4\"] = 4] = \"cTFBC4\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFBC5\"] = 5] = \"cTFBC5\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFBC7\"] = 6] = \"cTFBC7\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFPVRTC1_4_RGB\"] = 8] = \"cTFPVRTC1_4_RGB\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFPVRTC1_4_RGBA\"] = 9] = \"cTFPVRTC1_4_RGBA\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFASTC_4x4\"] = 10] = \"cTFASTC_4x4\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFATC_RGB\"] = 11] = \"cTFATC_RGB\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFATC_RGBA_INTERPOLATED_ALPHA\"] = 12] = \"cTFATC_RGBA_INTERPOLATED_ALPHA\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFRGBA32\"] = 13] = \"cTFRGBA32\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFRGB565\"] = 14] = \"cTFRGB565\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFBGR565\"] = 15] = \"cTFBGR565\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFRGBA4444\"] = 16] = \"cTFRGBA4444\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFFXT1_RGB\"] = 17] = \"cTFFXT1_RGB\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFPVRTC2_4_RGB\"] = 18] = \"cTFPVRTC2_4_RGB\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFPVRTC2_4_RGBA\"] = 19] = \"cTFPVRTC2_4_RGBA\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFETC2_EAC_R11\"] = 20] = \"cTFETC2_EAC_R11\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFETC2_EAC_RG11\"] = 21] = \"cTFETC2_EAC_RG11\";\n})(BASIS_FORMATS || (BASIS_FORMATS = {}));\n/**\n * Used to load .Basis files\n * See https://github.com/BinomialLLC/basis_universal/tree/master/webgl\n */\nexport const BasisToolsOptions = {\n /**\n * URL to use when loading the basis transcoder\n */\n JSModuleURL: \"https://cdn.babylonjs.com/basisTranscoder/1/basis_transcoder.js\",\n /**\n * URL to use when loading the wasm module for the transcoder\n */\n WasmModuleURL: \"https://cdn.babylonjs.com/basisTranscoder/1/basis_transcoder.wasm\",\n};\n/**\n * Get the internal format to be passed to texImage2D corresponding to the .basis format value\n * @param basisFormat format chosen from GetSupportedTranscodeFormat\n * @param engine\n * @returns internal format corresponding to the Basis format\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport const GetInternalFormatFromBasisFormat = (basisFormat, engine) => {\n let format;\n switch (basisFormat) {\n case BASIS_FORMATS.cTFETC1:\n format = 36196;\n break;\n case BASIS_FORMATS.cTFBC1:\n format = 33776;\n break;\n case BASIS_FORMATS.cTFBC4:\n format = 33779;\n break;\n case BASIS_FORMATS.cTFASTC_4x4:\n format = 37808;\n break;\n case BASIS_FORMATS.cTFETC2:\n format = 37496;\n break;\n case BASIS_FORMATS.cTFBC7:\n format = 36492;\n break;\n }\n if (format === undefined) {\n throw \"The chosen Basis transcoder format is not currently supported\";\n }\n return format;\n};\nlet _WorkerPromise = null;\nlet _Worker = null;\nlet _actionId = 0;\nconst _IgnoreSupportedFormats = false;\nconst _CreateWorkerAsync = () => {\n if (!_WorkerPromise) {\n _WorkerPromise = new Promise((res, reject) => {\n if (_Worker) {\n res(_Worker);\n }\n else {\n Tools.LoadFileAsync(BasisToolsOptions.WasmModuleURL)\n .then((wasmBinary) => {\n if (typeof URL !== \"function\") {\n return reject(\"Basis transcoder requires an environment with a URL constructor\");\n }\n const workerBlobUrl = URL.createObjectURL(new Blob([`(${workerFunc})()`], { type: \"application/javascript\" }));\n _Worker = new Worker(workerBlobUrl);\n const initHandler = (msg) => {\n if (msg.data.action === \"init\") {\n _Worker.removeEventListener(\"message\", initHandler);\n res(_Worker);\n }\n else if (msg.data.action === \"error\") {\n reject(msg.data.error || \"error initializing worker\");\n }\n };\n _Worker.addEventListener(\"message\", initHandler);\n _Worker.postMessage({ action: \"init\", url: BasisToolsOptions.JSModuleURL, wasmBinary: wasmBinary });\n })\n .catch(reject);\n }\n });\n }\n return _WorkerPromise;\n};\n/**\n * Transcodes a loaded image file to compressed pixel data\n * @param data image data to transcode\n * @param config configuration options for the transcoding\n * @returns a promise resulting in the transcoded image\n */\nexport const TranscodeAsync = (data, config) => {\n const dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;\n return new Promise((res, rej) => {\n _CreateWorkerAsync().then(() => {\n const actionId = _actionId++;\n const messageHandler = (msg) => {\n if (msg.data.action === \"transcode\" && msg.data.id === actionId) {\n _Worker.removeEventListener(\"message\", messageHandler);\n if (!msg.data.success) {\n rej(\"Transcode is not supported on this device\");\n }\n else {\n res(msg.data);\n }\n }\n };\n _Worker.addEventListener(\"message\", messageHandler);\n const dataViewCopy = new Uint8Array(dataView.byteLength);\n dataViewCopy.set(new Uint8Array(dataView.buffer, dataView.byteOffset, dataView.byteLength));\n _Worker.postMessage({ action: \"transcode\", id: actionId, imageData: dataViewCopy, config: config, ignoreSupportedFormats: _IgnoreSupportedFormats }, [\n dataViewCopy.buffer,\n ]);\n }, (error) => {\n rej(error);\n });\n });\n};\n/**\n * Binds a texture according to its underlying target.\n * @param texture texture to bind\n * @param engine the engine to bind the texture in\n */\nconst BindTexture = (texture, engine) => {\n var _a, _b;\n let target = (_a = engine._gl) === null || _a === void 0 ? void 0 : _a.TEXTURE_2D;\n if (texture.isCube) {\n target = (_b = engine._gl) === null || _b === void 0 ? void 0 : _b.TEXTURE_CUBE_MAP;\n }\n engine._bindTextureDirectly(target, texture, true);\n};\n/**\n * Loads a texture from the transcode result\n * @param texture texture load to\n * @param transcodeResult the result of transcoding the basis file to load from\n */\nexport const LoadTextureFromTranscodeResult = (texture, transcodeResult) => {\n const engine = texture.getEngine();\n for (let i = 0; i < transcodeResult.fileInfo.images.length; i++) {\n const rootImage = transcodeResult.fileInfo.images[i].levels[0];\n texture._invertVScale = texture.invertY;\n if (transcodeResult.format === -1 || transcodeResult.format === BASIS_FORMATS.cTFRGB565) {\n // No compatable compressed format found, fallback to RGB\n texture.type = 10;\n texture.format = 4;\n if (engine._features.basisNeedsPOT && (Scalar.Log2(rootImage.width) % 1 !== 0 || Scalar.Log2(rootImage.height) % 1 !== 0)) {\n // Create non power of two texture\n const source = new InternalTexture(engine, InternalTextureSource.Temp);\n texture._invertVScale = texture.invertY;\n source.type = 10;\n source.format = 4;\n // Fallback requires aligned width/height\n source.width = (rootImage.width + 3) & ~3;\n source.height = (rootImage.height + 3) & ~3;\n BindTexture(source, engine);\n engine._uploadDataToTextureDirectly(source, new Uint16Array(rootImage.transcodedPixels.buffer), i, 0, 4, true);\n // Resize to power of two\n engine._rescaleTexture(source, texture, engine.scenes[0], engine._getInternalFormat(4), () => {\n engine._releaseTexture(source);\n BindTexture(texture, engine);\n });\n }\n else {\n // Fallback is already inverted\n texture._invertVScale = !texture.invertY;\n // Upload directly\n texture.width = (rootImage.width + 3) & ~3;\n texture.height = (rootImage.height + 3) & ~3;\n texture.samplingMode = 2;\n BindTexture(texture, engine);\n engine._uploadDataToTextureDirectly(texture, new Uint16Array(rootImage.transcodedPixels.buffer), i, 0, 4, true);\n }\n }\n else {\n texture.width = rootImage.width;\n texture.height = rootImage.height;\n texture.generateMipMaps = transcodeResult.fileInfo.images[i].levels.length > 1;\n const format = BasisTools.GetInternalFormatFromBasisFormat(transcodeResult.format, engine);\n texture.format = format;\n BindTexture(texture, engine);\n // Upload all mip levels in the file\n transcodeResult.fileInfo.images[i].levels.forEach((level, index) => {\n engine._uploadCompressedDataToTextureDirectly(texture, format, level.width, level.height, level.transcodedPixels, i, index);\n });\n if (engine._features.basisNeedsPOT && (Scalar.Log2(texture.width) % 1 !== 0 || Scalar.Log2(texture.height) % 1 !== 0)) {\n Tools.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.\");\n texture._cachedWrapU = Texture.CLAMP_ADDRESSMODE;\n texture._cachedWrapV = Texture.CLAMP_ADDRESSMODE;\n }\n }\n }\n};\n/**\n * Used to load .Basis files\n * See https://github.com/BinomialLLC/basis_universal/tree/master/webgl\n */\nexport const BasisTools = {\n /**\n * URL to use when loading the basis transcoder\n */\n JSModuleURL: BasisToolsOptions.JSModuleURL,\n /**\n * URL to use when loading the wasm module for the transcoder\n */\n WasmModuleURL: BasisToolsOptions.WasmModuleURL,\n /**\n * Get the internal format to be passed to texImage2D corresponding to the .basis format value\n * @param basisFormat format chosen from GetSupportedTranscodeFormat\n * @returns internal format corresponding to the Basis format\n */\n GetInternalFormatFromBasisFormat,\n /**\n * Transcodes a loaded image file to compressed pixel data\n * @param data image data to transcode\n * @param config configuration options for the transcoding\n * @returns a promise resulting in the transcoded image\n */\n TranscodeAsync,\n /**\n * Loads a texture from the transcode result\n * @param texture texture load to\n * @param transcodeResult the result of transcoding the basis file to load from\n */\n LoadTextureFromTranscodeResult,\n};\nfunction workerFunc() {\n const _BASIS_FORMAT = {\n cTFETC1: 0,\n cTFETC2: 1,\n cTFBC1: 2,\n cTFBC3: 3,\n cTFBC4: 4,\n cTFBC5: 5,\n cTFBC7: 6,\n cTFPVRTC1_4_RGB: 8,\n cTFPVRTC1_4_RGBA: 9,\n cTFASTC_4x4: 10,\n cTFATC_RGB: 11,\n cTFATC_RGBA_INTERPOLATED_ALPHA: 12,\n cTFRGBA32: 13,\n cTFRGB565: 14,\n cTFBGR565: 15,\n cTFRGBA4444: 16,\n cTFFXT1_RGB: 17,\n cTFPVRTC2_4_RGB: 18,\n cTFPVRTC2_4_RGBA: 19,\n cTFETC2_EAC_R11: 20,\n cTFETC2_EAC_RG11: 21,\n };\n let transcoderModulePromise = null;\n onmessage = (event) => {\n if (event.data.action === \"init\") {\n // Load the transcoder if it hasn't been yet\n if (!transcoderModulePromise) {\n // make sure we loaded the script correctly\n try {\n importScripts(event.data.url);\n }\n catch (e) {\n postMessage({ action: \"error\", error: e });\n }\n transcoderModulePromise = BASIS({\n // Override wasm binary\n wasmBinary: event.data.wasmBinary,\n });\n }\n if (transcoderModulePromise !== null) {\n transcoderModulePromise.then((m) => {\n BASIS = m;\n m.initializeBasis();\n postMessage({ action: \"init\" });\n });\n }\n }\n else if (event.data.action === \"transcode\") {\n // Transcode the basis image and return the resulting pixels\n const config = event.data.config;\n const imgData = event.data.imageData;\n const loadedFile = new BASIS.BasisFile(imgData);\n const fileInfo = GetFileInfo(loadedFile);\n let format = event.data.ignoreSupportedFormats ? null : GetSupportedTranscodeFormat(event.data.config, fileInfo);\n let needsConversion = false;\n if (format === null) {\n needsConversion = true;\n format = fileInfo.hasAlpha ? _BASIS_FORMAT.cTFBC3 : _BASIS_FORMAT.cTFBC1;\n }\n // Begin transcode\n let success = true;\n if (!loadedFile.startTranscoding()) {\n success = false;\n }\n const buffers = [];\n for (let imageIndex = 0; imageIndex < fileInfo.images.length; imageIndex++) {\n if (!success) {\n break;\n }\n const image = fileInfo.images[imageIndex];\n if (config.loadSingleImage === undefined || config.loadSingleImage === imageIndex) {\n let mipCount = image.levels.length;\n if (config.loadMipmapLevels === false) {\n mipCount = 1;\n }\n for (let levelIndex = 0; levelIndex < mipCount; levelIndex++) {\n const levelInfo = image.levels[levelIndex];\n const pixels = TranscodeLevel(loadedFile, imageIndex, levelIndex, format, needsConversion);\n if (!pixels) {\n success = false;\n break;\n }\n levelInfo.transcodedPixels = pixels;\n buffers.push(levelInfo.transcodedPixels.buffer);\n }\n }\n }\n // Close file\n loadedFile.close();\n loadedFile.delete();\n if (needsConversion) {\n format = -1;\n }\n if (!success) {\n postMessage({ action: \"transcode\", success: success, id: event.data.id });\n }\n else {\n postMessage({ action: \"transcode\", success: success, id: event.data.id, fileInfo: fileInfo, format: format }, buffers);\n }\n }\n };\n /**\n * Detects the supported transcode format for the file\n * @param config transcode config\n * @param fileInfo info about the file\n * @returns the chosed format or null if none are supported\n */\n function GetSupportedTranscodeFormat(config, fileInfo) {\n let format = null;\n if (config.supportedCompressionFormats) {\n if (config.supportedCompressionFormats.astc) {\n format = _BASIS_FORMAT.cTFASTC_4x4;\n }\n else if (config.supportedCompressionFormats.bc7) {\n format = _BASIS_FORMAT.cTFBC7;\n }\n else if (config.supportedCompressionFormats.s3tc) {\n format = fileInfo.hasAlpha ? _BASIS_FORMAT.cTFBC3 : _BASIS_FORMAT.cTFBC1;\n }\n else if (config.supportedCompressionFormats.pvrtc) {\n format = fileInfo.hasAlpha ? _BASIS_FORMAT.cTFPVRTC1_4_RGBA : _BASIS_FORMAT.cTFPVRTC1_4_RGB;\n }\n else if (config.supportedCompressionFormats.etc2) {\n format = _BASIS_FORMAT.cTFETC2;\n }\n else if (config.supportedCompressionFormats.etc1) {\n format = _BASIS_FORMAT.cTFETC1;\n }\n else {\n format = _BASIS_FORMAT.cTFRGB565;\n }\n }\n return format;\n }\n /**\n * Retrieves information about the basis file eg. dimensions\n * @param basisFile the basis file to get the info from\n * @returns information about the basis file\n */\n function GetFileInfo(basisFile) {\n const hasAlpha = basisFile.getHasAlpha();\n const imageCount = basisFile.getNumImages();\n const images = [];\n for (let i = 0; i < imageCount; i++) {\n const imageInfo = {\n levels: [],\n };\n const levelCount = basisFile.getNumLevels(i);\n for (let level = 0; level < levelCount; level++) {\n const levelInfo = {\n width: basisFile.getImageWidth(i, level),\n height: basisFile.getImageHeight(i, level),\n };\n imageInfo.levels.push(levelInfo);\n }\n images.push(imageInfo);\n }\n const info = { hasAlpha, images };\n return info;\n }\n function TranscodeLevel(loadedFile, imageIndex, levelIndex, format, convertToRgb565) {\n const dstSize = loadedFile.getImageTranscodedSizeInBytes(imageIndex, levelIndex, format);\n let dst = new Uint8Array(dstSize);\n if (!loadedFile.transcodeImage(dst, imageIndex, levelIndex, format, 1, 0)) {\n return null;\n }\n // If no supported format is found, load as dxt and convert to rgb565\n if (convertToRgb565) {\n const alignedWidth = (loadedFile.getImageWidth(imageIndex, levelIndex) + 3) & ~3;\n const alignedHeight = (loadedFile.getImageHeight(imageIndex, levelIndex) + 3) & ~3;\n dst = ConvertDxtToRgb565(dst, 0, alignedWidth, alignedHeight);\n }\n return dst;\n }\n /**\n * From https://github.com/BinomialLLC/basis_universal/blob/master/webgl/texture/dxt-to-rgb565.js\n * An unoptimized version of dxtToRgb565. Also, the floating\n * point math used to compute the colors actually results in\n * slightly different colors compared to hardware DXT decoders.\n * @param src dxt src pixels\n * @param srcByteOffset offset for the start of src\n * @param width aligned width of the image\n * @param height aligned height of the image\n * @returns the converted pixels\n */\n function ConvertDxtToRgb565(src, srcByteOffset, width, height) {\n const c = new Uint16Array(4);\n const dst = new Uint16Array(width * height);\n const blockWidth = width / 4;\n const blockHeight = height / 4;\n for (let blockY = 0; blockY < blockHeight; blockY++) {\n for (let blockX = 0; blockX < blockWidth; blockX++) {\n const i = srcByteOffset + 8 * (blockY * blockWidth + blockX);\n c[0] = src[i] | (src[i + 1] << 8);\n c[1] = src[i + 2] | (src[i + 3] << 8);\n c[2] =\n ((2 * (c[0] & 0x1f) + 1 * (c[1] & 0x1f)) / 3) |\n (((2 * (c[0] & 0x7e0) + 1 * (c[1] & 0x7e0)) / 3) & 0x7e0) |\n (((2 * (c[0] & 0xf800) + 1 * (c[1] & 0xf800)) / 3) & 0xf800);\n c[3] =\n ((2 * (c[1] & 0x1f) + 1 * (c[0] & 0x1f)) / 3) |\n (((2 * (c[1] & 0x7e0) + 1 * (c[0] & 0x7e0)) / 3) & 0x7e0) |\n (((2 * (c[1] & 0xf800) + 1 * (c[0] & 0xf800)) / 3) & 0xf800);\n for (let row = 0; row < 4; row++) {\n const m = src[i + 4 + row];\n let dstI = (blockY * 4 + row) * width + blockX * 4;\n dst[dstI++] = c[m & 0x3];\n dst[dstI++] = c[(m >> 2) & 0x3];\n dst[dstI++] = c[(m >> 4) & 0x3];\n dst[dstI++] = c[(m >> 6) & 0x3];\n }\n }\n }\n return dst;\n }\n}\nObject.defineProperty(BasisTools, \"JSModuleURL\", {\n get: function () {\n return BasisToolsOptions.JSModuleURL;\n },\n set: function (value) {\n BasisToolsOptions.JSModuleURL = value;\n },\n});\nObject.defineProperty(BasisTools, \"WasmModuleURL\", {\n get: function () {\n return BasisToolsOptions.WasmModuleURL;\n },\n set: function (value) {\n BasisToolsOptions.WasmModuleURL = value;\n },\n});\n//# sourceMappingURL=basis.js.map","import { Engine } from \"../../../Engines/engine.js\";\nimport { LoadTextureFromTranscodeResult, TranscodeAsync } from \"../../../Misc/basis.js\";\nimport { Tools } from \"../../../Misc/tools.js\";\n/**\n * Loader for .basis file format\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class _BasisTextureLoader {\n constructor() {\n /**\n * Defines whether the loader supports cascade loading the different faces.\n */\n this.supportCascades = false;\n }\n /**\n * This returns if the loader support the current file information.\n * @param extension defines the file extension of the file being loaded\n * @returns true if the loader can load the specified file\n */\n canLoad(extension) {\n return extension.endsWith(\".basis\");\n }\n /**\n * Uploads the cube texture data to the WebGL texture. It has already been bound.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param createPolynomials will be true if polynomials have been requested\n * @param onLoad defines the callback to trigger once the texture is ready\n * @param onError defines the callback to trigger in case of error\n */\n loadCubeData(data, texture, createPolynomials, onLoad, onError) {\n if (Array.isArray(data)) {\n return;\n }\n const caps = texture.getEngine().getCaps();\n const transcodeConfig = {\n supportedCompressionFormats: {\n etc1: caps.etc1 ? true : false,\n s3tc: caps.s3tc ? true : false,\n pvrtc: caps.pvrtc ? true : false,\n etc2: caps.etc2 ? true : false,\n astc: caps.astc ? true : false,\n bc7: caps.bptc ? true : false,\n },\n };\n TranscodeAsync(data, transcodeConfig)\n .then((result) => {\n const hasMipmap = result.fileInfo.images[0].levels.length > 1 && texture.generateMipMaps;\n LoadTextureFromTranscodeResult(texture, result);\n texture.getEngine()._setCubeMapTextureParams(texture, hasMipmap);\n texture.isReady = true;\n texture.onLoadedObservable.notifyObservers(texture);\n texture.onLoadedObservable.clear();\n if (onLoad) {\n onLoad();\n }\n })\n .catch((err) => {\n const errorMessage = \"Failed to transcode Basis file, transcoding may not be supported on this device\";\n Tools.Warn(errorMessage);\n texture.isReady = true;\n if (onError) {\n onError(err);\n }\n });\n }\n /**\n * Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param callback defines the method to call once ready to upload\n */\n loadData(data, texture, callback) {\n const caps = texture.getEngine().getCaps();\n const transcodeConfig = {\n supportedCompressionFormats: {\n etc1: caps.etc1 ? true : false,\n s3tc: caps.s3tc ? true : false,\n pvrtc: caps.pvrtc ? true : false,\n etc2: caps.etc2 ? true : false,\n astc: caps.astc ? true : false,\n bc7: caps.bptc ? true : false,\n },\n };\n TranscodeAsync(data, transcodeConfig)\n .then((result) => {\n const rootImage = result.fileInfo.images[0].levels[0];\n const hasMipmap = result.fileInfo.images[0].levels.length > 1 && texture.generateMipMaps;\n callback(rootImage.width, rootImage.height, hasMipmap, result.format !== -1, () => {\n LoadTextureFromTranscodeResult(texture, result);\n });\n })\n .catch((err) => {\n Tools.Warn(\"Failed to transcode Basis file, transcoding may not be supported on this device\");\n Tools.Warn(`Failed to transcode Basis file: ${err}`);\n callback(0, 0, false, false, () => { }, true);\n });\n }\n}\n// Register the loader.\nEngine._TextureLoaders.push(new _BasisTextureLoader());\n//# sourceMappingURL=basisTextureLoader.js.map","export * from \"./ddsTextureLoader.js\";\nexport * from \"./envTextureLoader.js\";\nexport * from \"./ktxTextureLoader.js\";\nexport * from \"./tgaTextureLoader.js\";\nexport * from \"./hdrTextureLoader.js\";\nexport * from \"./basisTextureLoader.js\";\n//# sourceMappingURL=index.js.map","import { Texture } from \"../../Materials/Textures/texture.js\";\nimport { RenderTargetTexture } from \"../../Materials/Textures/renderTargetTexture.js\";\n\nimport \"../../Engines/Extensions/engine.multiRender.js\";\n/**\n * A multi render target, like a render target provides the ability to render to a texture.\n * Unlike the render target, it can render to several draw buffers in one draw.\n * This is specially interesting in deferred rendering or for any effects requiring more than\n * just one color from a single pass.\n */\nexport class MultiRenderTarget extends RenderTargetTexture {\n /**\n * Get if draw buffers are currently supported by the used hardware and browser.\n */\n get isSupported() {\n var _a, _b;\n return (_b = (_a = this._engine) === null || _a === void 0 ? void 0 : _a.getCaps().drawBuffersExtension) !== null && _b !== void 0 ? _b : false;\n }\n /**\n * Get the list of textures generated by the multi render target.\n */\n get textures() {\n return this._textures;\n }\n /**\n * Gets the number of textures in this MRT. This number can be different from `_textures.length` in case a depth texture is generated.\n */\n get count() {\n return this._count;\n }\n /**\n * Get the depth texture generated by the multi render target if options.generateDepthTexture has been set\n */\n get depthTexture() {\n return this._textures[this._textures.length - 1];\n }\n /**\n * Set the wrapping mode on U of all the textures we are rendering to.\n * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)\n */\n set wrapU(wrap) {\n if (this._textures) {\n for (let i = 0; i < this._textures.length; i++) {\n this._textures[i].wrapU = wrap;\n }\n }\n }\n /**\n * Set the wrapping mode on V of all the textures we are rendering to.\n * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)\n */\n set wrapV(wrap) {\n if (this._textures) {\n for (let i = 0; i < this._textures.length; i++) {\n this._textures[i].wrapV = wrap;\n }\n }\n }\n /**\n * Instantiate a new multi render target texture.\n * A multi render target, like a render target provides the ability to render to a texture.\n * Unlike the render target, it can render to several draw buffers in one draw.\n * This is specially interesting in deferred rendering or for any effects requiring more than\n * just one color from a single pass.\n * @param name Define the name of the texture\n * @param size Define the size of the buffers to render to\n * @param count Define the number of target we are rendering into\n * @param scene Define the scene the texture belongs to\n * @param options Define the options used to create the multi render target\n * @param textureNames Define the names to set to the textures (if count > 0 - optional)\n */\n constructor(name, size, count, scene, options, textureNames) {\n const generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;\n const generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;\n const depthTextureFormat = options && options.depthTextureFormat ? options.depthTextureFormat : 15;\n const doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;\n const drawOnlyOnFirstAttachmentByDefault = options && options.drawOnlyOnFirstAttachmentByDefault ? options.drawOnlyOnFirstAttachmentByDefault : false;\n super(name, size, scene, generateMipMaps, doNotChangeAspectRatio, undefined, undefined, undefined, undefined, undefined, undefined, undefined, true);\n if (!this.isSupported) {\n this.dispose();\n return;\n }\n this._textureNames = textureNames;\n const types = [];\n const samplingModes = [];\n const useSRGBBuffers = [];\n const formats = [];\n const targetTypes = [];\n const faceIndex = [];\n const layerIndex = [];\n const layerCounts = [];\n this._initTypes(count, types, samplingModes, useSRGBBuffers, formats, targetTypes, faceIndex, layerIndex, layerCounts, options);\n const generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;\n const generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;\n this._multiRenderTargetOptions = {\n samplingModes: samplingModes,\n generateMipMaps: generateMipMaps,\n generateDepthBuffer: generateDepthBuffer,\n generateStencilBuffer: generateStencilBuffer,\n generateDepthTexture: generateDepthTexture,\n depthTextureFormat: depthTextureFormat,\n types: types,\n textureCount: count,\n useSRGBBuffers: useSRGBBuffers,\n formats: formats,\n targetTypes: targetTypes,\n faceIndex: faceIndex,\n layerIndex: layerIndex,\n layerCounts: layerCounts,\n };\n this._count = count;\n this._drawOnlyOnFirstAttachmentByDefault = drawOnlyOnFirstAttachmentByDefault;\n if (count > 0) {\n this._createInternalTextures();\n this._createTextures(textureNames);\n }\n }\n _initTypes(count, types, samplingModes, useSRGBBuffers, formats, targets, faceIndex, layerIndex, layerCounts, options) {\n for (let i = 0; i < count; i++) {\n if (options && options.types && options.types[i] !== undefined) {\n types.push(options.types[i]);\n }\n else {\n types.push(options && options.defaultType ? options.defaultType : 0);\n }\n if (options && options.samplingModes && options.samplingModes[i] !== undefined) {\n samplingModes.push(options.samplingModes[i]);\n }\n else {\n samplingModes.push(Texture.BILINEAR_SAMPLINGMODE);\n }\n if (options && options.useSRGBBuffers && options.useSRGBBuffers[i] !== undefined) {\n useSRGBBuffers.push(options.useSRGBBuffers[i]);\n }\n else {\n useSRGBBuffers.push(false);\n }\n if (options && options.formats && options.formats[i] !== undefined) {\n formats.push(options.formats[i]);\n }\n else {\n formats.push(5);\n }\n if (options && options.targetTypes && options.targetTypes[i] !== undefined) {\n targets.push(options.targetTypes[i]);\n }\n else {\n targets.push(3553);\n }\n if (options && options.faceIndex && options.faceIndex[i] !== undefined) {\n faceIndex.push(options.faceIndex[i]);\n }\n else {\n faceIndex.push(0);\n }\n if (options && options.layerIndex && options.layerIndex[i] !== undefined) {\n layerIndex.push(options.layerIndex[i]);\n }\n else {\n layerIndex.push(0);\n }\n if (options && options.layerCounts && options.layerCounts[i] !== undefined) {\n layerCounts.push(options.layerCounts[i]);\n }\n else {\n layerCounts.push(1);\n }\n }\n }\n _createInternaTextureIndexMapping() {\n const mapMainInternalTexture2Index = {};\n const mapInternalTexture2MainIndex = [];\n if (!this._renderTarget) {\n return mapInternalTexture2MainIndex;\n }\n const internalTextures = this._renderTarget.textures;\n for (let i = 0; i < internalTextures.length; i++) {\n const texture = internalTextures[i];\n if (!texture) {\n continue;\n }\n const mainIndex = mapMainInternalTexture2Index[texture.uniqueId];\n if (mainIndex !== undefined) {\n mapInternalTexture2MainIndex[i] = mainIndex;\n }\n else {\n mapMainInternalTexture2Index[texture.uniqueId] = i;\n }\n }\n return mapInternalTexture2MainIndex;\n }\n /**\n * @internal\n */\n _rebuild(forceFullRebuild = false, textureNames) {\n if (this._count < 1) {\n return;\n }\n const mapInternalTexture2MainIndex = this._createInternaTextureIndexMapping();\n this.releaseInternalTextures();\n this._createInternalTextures();\n if (forceFullRebuild) {\n this._releaseTextures();\n this._createTextures(textureNames);\n }\n const internalTextures = this._renderTarget.textures;\n for (let i = 0; i < internalTextures.length; i++) {\n const texture = this._textures[i];\n if (mapInternalTexture2MainIndex[i] !== undefined) {\n this._renderTarget.setTexture(internalTextures[mapInternalTexture2MainIndex[i]], i);\n }\n texture._texture = internalTextures[i];\n if (texture._texture) {\n texture._noMipmap = !texture._texture.useMipMaps;\n texture._useSRGBBuffer = texture._texture._useSRGBBuffer;\n }\n }\n if (this.samples !== 1) {\n this._renderTarget.setSamples(this.samples, !this._drawOnlyOnFirstAttachmentByDefault, true);\n }\n }\n _createInternalTextures() {\n this._renderTarget = this._getEngine().createMultipleRenderTarget(this._size, this._multiRenderTargetOptions, !this._drawOnlyOnFirstAttachmentByDefault);\n this._texture = this._renderTarget.texture;\n }\n _releaseTextures() {\n if (this._textures) {\n for (let i = 0; i < this._textures.length; i++) {\n this._textures[i]._texture = null; // internal textures are released by a call to releaseInternalTextures()\n this._textures[i].dispose();\n }\n }\n }\n _createTextures(textureNames) {\n const internalTextures = this._renderTarget.textures;\n this._textures = [];\n for (let i = 0; i < internalTextures.length; i++) {\n const texture = new Texture(null, this.getScene());\n if (textureNames === null || textureNames === void 0 ? void 0 : textureNames[i]) {\n texture.name = textureNames[i];\n }\n texture._texture = internalTextures[i];\n if (texture._texture) {\n texture._noMipmap = !texture._texture.useMipMaps;\n texture._useSRGBBuffer = texture._texture._useSRGBBuffer;\n }\n this._textures.push(texture);\n }\n }\n /**\n * Replaces an internal texture within the MRT. Useful to share textures between MultiRenderTarget.\n * @param texture The new texture to set in the MRT\n * @param index The index of the texture to replace\n * @param disposePrevious Set to true if the previous internal texture should be disposed\n */\n setInternalTexture(texture, index, disposePrevious = true) {\n var _a, _b;\n if (!this.renderTarget) {\n return;\n }\n if (index === 0) {\n this._texture = texture;\n }\n this.renderTarget.setTexture(texture, index, disposePrevious);\n if (!this.textures[index]) {\n this.textures[index] = new Texture(null, this.getScene());\n this.textures[index].name = (_b = (_a = this._textureNames) === null || _a === void 0 ? void 0 : _a[index]) !== null && _b !== void 0 ? _b : this.textures[index].name;\n }\n this.textures[index]._texture = texture;\n this.textures[index]._noMipmap = !texture.useMipMaps;\n this.textures[index]._useSRGBBuffer = texture._useSRGBBuffer;\n this._count = this.renderTarget.textures ? this.renderTarget.textures.length : 0;\n if (this._multiRenderTargetOptions.types) {\n this._multiRenderTargetOptions.types[index] = texture.type;\n }\n if (this._multiRenderTargetOptions.samplingModes) {\n this._multiRenderTargetOptions.samplingModes[index] = texture.samplingMode;\n }\n if (this._multiRenderTargetOptions.useSRGBBuffers) {\n this._multiRenderTargetOptions.useSRGBBuffers[index] = texture._useSRGBBuffer;\n }\n if (this._multiRenderTargetOptions.targetTypes && this._multiRenderTargetOptions.targetTypes[index] !== -1) {\n let target = 0;\n if (texture.is2DArray) {\n target = 35866;\n }\n else if (texture.isCube) {\n target = 34067;\n } /*else if (texture.isCubeArray) {\n target = 3735928559;\n }*/\n else if (texture.is3D) {\n target = 32879;\n }\n else {\n target = 3553;\n }\n this._multiRenderTargetOptions.targetTypes[index] = target;\n }\n }\n /**\n * Changes an attached texture's face index or layer.\n * @param index The index of the texture to modify the attachment of\n * @param layerIndex The layer index of the texture to be attached to the framebuffer\n * @param faceIndex The face index of the texture to be attached to the framebuffer\n */\n setLayerAndFaceIndex(index, layerIndex = -1, faceIndex = -1) {\n if (!this.textures[index] || !this.renderTarget) {\n return;\n }\n if (this._multiRenderTargetOptions.layerIndex) {\n this._multiRenderTargetOptions.layerIndex[index] = layerIndex;\n }\n if (this._multiRenderTargetOptions.faceIndex) {\n this._multiRenderTargetOptions.faceIndex[index] = faceIndex;\n }\n this.renderTarget.setLayerAndFaceIndex(index, layerIndex, faceIndex);\n }\n /**\n * Changes every attached texture's face index or layer.\n * @param layerIndices The layer indices of the texture to be attached to the framebuffer\n * @param faceIndices The face indices of the texture to be attached to the framebuffer\n */\n setLayerAndFaceIndices(layerIndices, faceIndices) {\n if (!this.renderTarget) {\n return;\n }\n this._multiRenderTargetOptions.layerIndex = layerIndices;\n this._multiRenderTargetOptions.faceIndex = faceIndices;\n this.renderTarget.setLayerAndFaceIndices(layerIndices, faceIndices);\n }\n /**\n * Define the number of samples used if MSAA is enabled.\n */\n get samples() {\n return this._samples;\n }\n set samples(value) {\n if (this._renderTarget) {\n this._samples = this._renderTarget.setSamples(value);\n }\n else {\n // In case samples are set with 0 textures created, we must save the desired samples value\n this._samples = value;\n }\n }\n /**\n * Resize all the textures in the multi render target.\n * Be careful as it will recreate all the data in the new texture.\n * @param size Define the new size\n */\n resize(size) {\n this._processSizeParameter(size, false);\n this._rebuild(undefined, this._textureNames);\n }\n /**\n * Changes the number of render targets in this MRT\n * Be careful as it will recreate all the data in the new texture.\n * @param count new texture count\n * @param options Specifies texture types and sampling modes for new textures\n * @param textureNames Specifies the names of the textures (optional)\n */\n updateCount(count, options, textureNames) {\n this._multiRenderTargetOptions.textureCount = count;\n this._count = count;\n const types = [];\n const samplingModes = [];\n const useSRGBBuffers = [];\n const formats = [];\n const targetTypes = [];\n const faceIndex = [];\n const layerIndex = [];\n const layerCounts = [];\n this._textureNames = textureNames;\n this._initTypes(count, types, samplingModes, useSRGBBuffers, formats, targetTypes, faceIndex, layerIndex, layerCounts, options);\n this._multiRenderTargetOptions.types = types;\n this._multiRenderTargetOptions.samplingModes = samplingModes;\n this._multiRenderTargetOptions.useSRGBBuffers = useSRGBBuffers;\n this._multiRenderTargetOptions.formats = formats;\n this._multiRenderTargetOptions.targetTypes = targetTypes;\n this._multiRenderTargetOptions.faceIndex = faceIndex;\n this._multiRenderTargetOptions.layerIndex = layerIndex;\n this._multiRenderTargetOptions.layerCounts = layerCounts;\n this._rebuild(true, textureNames);\n }\n _unbindFrameBuffer(engine, faceIndex) {\n if (this._renderTarget) {\n engine.unBindMultiColorAttachmentFramebuffer(this._renderTarget, this.isCube, () => {\n this.onAfterRenderObservable.notifyObservers(faceIndex);\n });\n }\n }\n /**\n * Dispose the render targets and their associated resources\n * @param doNotDisposeInternalTextures\n */\n dispose(doNotDisposeInternalTextures = false) {\n this._releaseTextures();\n if (!doNotDisposeInternalTextures) {\n this.releaseInternalTextures();\n }\n else {\n // Prevent internal texture dispose in super.dispose\n this._texture = null;\n }\n super.dispose();\n }\n /**\n * Release all the underlying texture used as draw buffers.\n */\n releaseInternalTextures() {\n var _a, _b;\n const internalTextures = (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.textures;\n if (!internalTextures) {\n return;\n }\n for (let i = internalTextures.length - 1; i >= 0; i--) {\n this._textures[i]._texture = null;\n }\n (_b = this._renderTarget) === null || _b === void 0 ? void 0 : _b.dispose();\n this._renderTarget = null;\n }\n}\n//# sourceMappingURL=multiRenderTarget.js.map","/**\n * This is a support class for frame Data on texture packer sets.\n */\nexport class TexturePackerFrame {\n /**\n * Initializes a texture package frame.\n * @param id The numerical frame identifier\n * @param scale Scalar Vector2 for UV frame\n * @param offset Vector2 for the frame position in UV units.\n * @returns TexturePackerFrame\n */\n constructor(id, scale, offset) {\n this.id = id;\n this.scale = scale;\n this.offset = offset;\n }\n}\n//# sourceMappingURL=frame.js.map","import { Engine } from \"../../../Engines/engine.js\";\nimport { VertexBuffer } from \"../../../Buffers/buffer.js\";\nimport { Texture } from \"../texture.js\";\nimport { DynamicTexture } from \"../dynamicTexture.js\";\nimport { Vector2 } from \"../../../Maths/math.vector.js\";\nimport { Color3, Color4 } from \"../../../Maths/math.color.js\";\nimport { TexturePackerFrame } from \"./frame.js\";\nimport { Logger } from \"../../../Misc/logger.js\";\nimport { Tools } from \"../../../Misc/tools.js\";\n/**\n * This is a support class that generates a series of packed texture sets.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction\n */\nexport class TexturePacker {\n /**\n * Initializes a texture package series from an array of meshes or a single mesh.\n * @param name The name of the package\n * @param meshes The target meshes to compose the package from\n * @param options The arguments that texture packer should follow while building.\n * @param scene The scene which the textures are scoped to.\n * @returns TexturePacker\n */\n constructor(name, meshes, options, scene) {\n var _b, _c, _d, _e, _g, _h, _j, _k, _l, _m, _o, _p, _q;\n this.name = name;\n this.meshes = meshes;\n this.scene = scene;\n /**\n * Run through the options and set what ever defaults are needed that where not declared.\n */\n this.options = options;\n this.options.map = (_b = this.options.map) !== null && _b !== void 0 ? _b : [\n \"ambientTexture\",\n \"bumpTexture\",\n \"diffuseTexture\",\n \"emissiveTexture\",\n \"lightmapTexture\",\n \"opacityTexture\",\n \"reflectionTexture\",\n \"refractionTexture\",\n \"specularTexture\",\n ];\n this.options.uvsIn = (_c = this.options.uvsIn) !== null && _c !== void 0 ? _c : VertexBuffer.UVKind;\n this.options.uvsOut = (_d = this.options.uvsOut) !== null && _d !== void 0 ? _d : VertexBuffer.UVKind;\n this.options.layout = (_e = this.options.layout) !== null && _e !== void 0 ? _e : TexturePacker.LAYOUT_STRIP;\n if (this.options.layout === TexturePacker.LAYOUT_COLNUM) {\n this.options.colnum = (_g = this.options.colnum) !== null && _g !== void 0 ? _g : 8;\n }\n this.options.updateInputMeshes = (_h = this.options.updateInputMeshes) !== null && _h !== void 0 ? _h : true;\n this.options.disposeSources = (_j = this.options.disposeSources) !== null && _j !== void 0 ? _j : true;\n this._expecting = 0;\n this.options.fillBlanks = (_k = this.options.fillBlanks) !== null && _k !== void 0 ? _k : true;\n if (this.options.fillBlanks === true) {\n this.options.customFillColor = (_l = this.options.customFillColor) !== null && _l !== void 0 ? _l : \"black\";\n }\n this.options.frameSize = (_m = this.options.frameSize) !== null && _m !== void 0 ? _m : 256;\n this.options.paddingRatio = (_o = this.options.paddingRatio) !== null && _o !== void 0 ? _o : 0.0115;\n this._paddingValue = Math.ceil(this.options.frameSize * this.options.paddingRatio);\n //Make it an even padding Number.\n if (this._paddingValue % 2 !== 0) {\n this._paddingValue++;\n }\n this.options.paddingMode = (_p = this.options.paddingMode) !== null && _p !== void 0 ? _p : TexturePacker.SUBUV_WRAP;\n if (this.options.paddingMode === TexturePacker.SUBUV_COLOR) {\n this.options.paddingColor = (_q = this.options.paddingColor) !== null && _q !== void 0 ? _q : new Color4(0, 0, 0, 1.0);\n }\n this.sets = {};\n this.frames = [];\n return this;\n }\n /**\n * Starts the package process\n * @param resolve The promises resolution function\n * @returns TexturePacker\n */\n _createFrames(resolve) {\n const dtSize = this._calculateSize();\n const dtUnits = new Vector2(1, 1).divide(dtSize);\n let doneCount = 0;\n const expecting = this._expecting;\n const meshLength = this.meshes.length;\n const sKeys = Object.keys(this.sets);\n for (let i = 0; i < sKeys.length; i++) {\n const setName = sKeys[i];\n const dt = new DynamicTexture(this.name + \".TexturePack.\" + setName + \"Set\", { width: dtSize.x, height: dtSize.y }, this.scene, true, //Generate Mips\n Texture.TRILINEAR_SAMPLINGMODE, Engine.TEXTUREFORMAT_RGBA);\n const dtx = dt.getContext();\n dtx.fillStyle = \"rgba(0,0,0,0)\";\n dtx.fillRect(0, 0, dtSize.x, dtSize.y);\n dt.update(false);\n this.sets[setName] = dt;\n }\n const baseSize = this.options.frameSize || 256;\n const padding = this._paddingValue;\n const tcs = baseSize + 2 * padding;\n const done = () => {\n this._calculateMeshUVFrames(baseSize, padding, dtSize, dtUnits, this.options.updateInputMeshes || false);\n };\n //Update the Textures\n for (let i = 0; i < meshLength; i++) {\n const m = this.meshes[i];\n const mat = m.material;\n //Check if the material has the texture\n //Create a temporary canvas the same size as 1 frame\n //Then apply the texture to the center and the 8 offsets\n //Copy the Context and place in the correct frame on the DT\n for (let j = 0; j < sKeys.length; j++) {\n const tempTexture = new DynamicTexture(\"temp\", tcs, this.scene, true);\n const tcx = tempTexture.getContext();\n const offset = this._getFrameOffset(i);\n const updateDt = () => {\n doneCount++;\n tempTexture.update(false);\n const iDat = tcx.getImageData(0, 0, tcs, tcs);\n //Update Set\n const dt = this.sets[setName];\n const dtx = dt.getContext();\n dtx.putImageData(iDat, dtSize.x * offset.x, dtSize.y * offset.y);\n tempTexture.dispose();\n dt.update(false);\n if (doneCount == expecting) {\n done();\n resolve();\n return;\n }\n };\n const setName = sKeys[j] || \"_blank\";\n if (!mat || mat[setName] === null) {\n tcx.fillStyle = \"rgba(0,0,0,0)\";\n if (this.options.fillBlanks) {\n tcx.fillStyle = this.options.customFillColor;\n }\n tcx.fillRect(0, 0, tcs, tcs);\n updateDt();\n }\n else {\n const setTexture = mat[setName];\n const img = new Image();\n if (setTexture instanceof DynamicTexture) {\n img.src = setTexture.getContext().canvas.toDataURL(\"image/png\");\n }\n else {\n img.src = setTexture.url;\n }\n Tools.SetCorsBehavior(img.src, img);\n img.onload = () => {\n tcx.fillStyle = \"rgba(0,0,0,0)\";\n tcx.fillRect(0, 0, tcs, tcs);\n tempTexture.update(false);\n tcx.setTransform(1, 0, 0, -1, 0, 0);\n const cellOffsets = [0, 0, 1, 0, 1, 1, 0, 1, -1, 1, -1, 0, -1 - 1, 0, -1, 1, -1];\n switch (this.options.paddingMode) {\n //Wrap Mode\n case 0:\n for (let i = 0; i < 9; i++) {\n tcx.drawImage(img, 0, 0, img.width, img.height, padding + baseSize * cellOffsets[i], padding + baseSize * cellOffsets[i + 1] - tcs, baseSize, baseSize);\n }\n break;\n //Extend Mode\n case 1:\n for (let i = 0; i < padding; i++) {\n tcx.drawImage(img, 0, 0, img.width, img.height, i + baseSize * cellOffsets[0], padding - tcs, baseSize, baseSize);\n tcx.drawImage(img, 0, 0, img.width, img.height, padding * 2 - i, padding - tcs, baseSize, baseSize);\n tcx.drawImage(img, 0, 0, img.width, img.height, padding, i - tcs, baseSize, baseSize);\n tcx.drawImage(img, 0, 0, img.width, img.height, padding, padding * 2 - i - tcs, baseSize, baseSize);\n }\n tcx.drawImage(img, 0, 0, img.width, img.height, padding + baseSize * cellOffsets[0], padding + baseSize * cellOffsets[1] - tcs, baseSize, baseSize);\n break;\n //Color Mode\n case 2:\n tcx.fillStyle = (this.options.paddingColor || Color3.Black()).toHexString();\n tcx.fillRect(0, 0, tcs, -tcs);\n tcx.clearRect(padding, padding, baseSize, baseSize);\n tcx.drawImage(img, 0, 0, img.width, img.height, padding + baseSize * cellOffsets[0], padding + baseSize * cellOffsets[1] - tcs, baseSize, baseSize);\n break;\n }\n tcx.setTransform(1, 0, 0, 1, 0, 0);\n updateDt();\n };\n }\n }\n }\n }\n /**\n * Calculates the Size of the Channel Sets\n * @returns Vector2\n */\n _calculateSize() {\n const meshLength = this.meshes.length || 0;\n const baseSize = this.options.frameSize || 0;\n const padding = this._paddingValue || 0;\n switch (this.options.layout) {\n case 0: {\n //STRIP_LAYOUT\n return new Vector2(baseSize * meshLength + 2 * padding * meshLength, baseSize + 2 * padding);\n }\n case 1: {\n //POWER2\n const sqrtCount = Math.max(2, Math.ceil(Math.sqrt(meshLength)));\n const size = baseSize * sqrtCount + 2 * padding * sqrtCount;\n return new Vector2(size, size);\n }\n case 2: {\n //COLNUM\n const cols = this.options.colnum || 1;\n const rowCnt = Math.max(1, Math.ceil(meshLength / cols));\n return new Vector2(baseSize * cols + 2 * padding * cols, baseSize * rowCnt + 2 * padding * rowCnt);\n }\n }\n return Vector2.Zero();\n }\n /**\n * Calculates the UV data for the frames.\n * @param baseSize the base frameSize\n * @param padding the base frame padding\n * @param dtSize size of the Dynamic Texture for that channel\n * @param dtUnits is 1/dtSize\n * @param update flag to update the input meshes\n */\n _calculateMeshUVFrames(baseSize, padding, dtSize, dtUnits, update) {\n const meshLength = this.meshes.length;\n for (let i = 0; i < meshLength; i++) {\n const m = this.meshes[i];\n const scale = new Vector2(baseSize / dtSize.x, baseSize / dtSize.y);\n const pOffset = dtUnits.clone().scale(padding);\n const frameOffset = this._getFrameOffset(i);\n const offset = frameOffset.add(pOffset);\n const frame = new TexturePackerFrame(i, scale, offset);\n this.frames.push(frame);\n //Update Output UVs\n if (update) {\n this._updateMeshUV(m, i);\n this._updateTextureReferences(m);\n }\n }\n }\n /**\n * Calculates the frames Offset.\n * @param index of the frame\n * @returns Vector2\n */\n _getFrameOffset(index) {\n const meshLength = this.meshes.length;\n let uvStep, yStep, xStep;\n switch (this.options.layout) {\n case 0: {\n //STRIP_LAYOUT\n uvStep = 1 / meshLength;\n return new Vector2(index * uvStep, 0);\n }\n case 1: {\n //POWER2\n const sqrtCount = Math.max(2, Math.ceil(Math.sqrt(meshLength)));\n yStep = Math.floor(index / sqrtCount);\n xStep = index - yStep * sqrtCount;\n uvStep = 1 / sqrtCount;\n return new Vector2(xStep * uvStep, yStep * uvStep);\n }\n case 2: {\n //COLNUM\n const cols = this.options.colnum || 1;\n const rowCnt = Math.max(1, Math.ceil(meshLength / cols));\n xStep = Math.floor(index / rowCnt);\n yStep = index - xStep * rowCnt;\n uvStep = new Vector2(1 / cols, 1 / rowCnt);\n return new Vector2(xStep * uvStep.x, yStep * uvStep.y);\n }\n }\n return Vector2.Zero();\n }\n /**\n * Updates a Mesh to the frame data\n * @param mesh that is the target\n * @param frameID or the frame index\n */\n _updateMeshUV(mesh, frameID) {\n const frame = this.frames[frameID];\n const uvIn = mesh.getVerticesData(this.options.uvsIn || VertexBuffer.UVKind);\n const uvOut = [];\n let toCount = 0;\n if (uvIn.length) {\n toCount = uvIn.length || 0;\n }\n for (let i = 0; i < toCount; i += 2) {\n uvOut.push(uvIn[i] * frame.scale.x + frame.offset.x, uvIn[i + 1] * frame.scale.y + frame.offset.y);\n }\n mesh.setVerticesData(this.options.uvsOut || VertexBuffer.UVKind, uvOut);\n }\n /**\n * Updates a Meshes materials to use the texture packer channels\n * @param m is the mesh to target\n * @param force all channels on the packer to be set.\n */\n _updateTextureReferences(m, force = false) {\n const mat = m.material;\n const sKeys = Object.keys(this.sets);\n const _dispose = (_t) => {\n if (_t.dispose) {\n _t.dispose();\n }\n };\n for (let i = 0; i < sKeys.length; i++) {\n const setName = sKeys[i];\n if (!force) {\n if (!mat) {\n return;\n }\n if (mat[setName] !== null) {\n _dispose(mat[setName]);\n mat[setName] = this.sets[setName];\n }\n }\n else {\n if (mat[setName] !== null) {\n _dispose(mat[setName]);\n }\n mat[setName] = this.sets[setName];\n }\n }\n }\n /**\n * Public method to set a Mesh to a frame\n * @param m that is the target\n * @param frameID or the frame index\n * @param updateMaterial trigger for if the Meshes attached Material be updated?\n */\n setMeshToFrame(m, frameID, updateMaterial = false) {\n this._updateMeshUV(m, frameID);\n if (updateMaterial) {\n this._updateTextureReferences(m, true);\n }\n }\n /**\n * Starts the async promise to compile the texture packer.\n * @returns Promise\n */\n processAsync() {\n return new Promise((resolve, reject) => {\n try {\n if (this.meshes.length === 0) {\n //Must be a JSON load!\n resolve();\n return;\n }\n let done = 0;\n const doneCheck = (mat) => {\n done++;\n //Check Status of all Textures on all meshes, till they are ready.\n if (this.options.map) {\n for (let j = 0; j < this.options.map.length; j++) {\n const index = this.options.map[j];\n const t = mat[index];\n if (t !== null) {\n if (!this.sets[this.options.map[j]]) {\n this.sets[this.options.map[j]] = true;\n }\n this._expecting++;\n }\n }\n if (done === this.meshes.length) {\n this._createFrames(resolve);\n }\n }\n };\n for (let i = 0; i < this.meshes.length; i++) {\n const mesh = this.meshes[i];\n const material = mesh.material;\n if (!material) {\n done++;\n if (done === this.meshes.length) {\n return this._createFrames(resolve);\n }\n continue;\n }\n material.forceCompilationAsync(mesh).then(() => {\n doneCheck(material);\n });\n }\n }\n catch (e) {\n return reject(e);\n }\n });\n }\n /**\n * Disposes all textures associated with this packer\n */\n dispose() {\n const sKeys = Object.keys(this.sets);\n for (let i = 0; i < sKeys.length; i++) {\n const channel = sKeys[i];\n this.sets[channel].dispose();\n }\n }\n /**\n * Starts the download process for all the channels converting them to base64 data and embedding it all in a JSON file.\n * @param imageType is the image type to use.\n * @param quality of the image if downloading as jpeg, Ranges from >0 to 1.\n */\n download(imageType = \"png\", quality = 1) {\n setTimeout(() => {\n const pack = {\n name: this.name,\n sets: {},\n options: {},\n frames: [],\n };\n const sKeys = Object.keys(this.sets);\n const oKeys = Object.keys(this.options);\n try {\n for (let i = 0; i < sKeys.length; i++) {\n const channel = sKeys[i];\n const dt = this.sets[channel];\n pack.sets[channel] = dt.getContext().canvas.toDataURL(\"image/\" + imageType, quality);\n }\n for (let i = 0; i < oKeys.length; i++) {\n const opt = oKeys[i];\n pack.options[opt] = this.options[opt];\n }\n for (let i = 0; i < this.frames.length; i++) {\n const _f = this.frames[i];\n pack.frames.push(_f.scale.x, _f.scale.y, _f.offset.x, _f.offset.y);\n }\n }\n catch (err) {\n Logger.Warn(\"Unable to download: \" + err);\n return;\n }\n const data = \"data:text/json;charset=utf-8,\" + encodeURIComponent(JSON.stringify(pack, null, 4));\n const _a = document.createElement(\"a\");\n _a.setAttribute(\"href\", data);\n _a.setAttribute(\"download\", this.name + \"_texurePackage.json\");\n document.body.appendChild(_a);\n _a.click();\n _a.remove();\n }, 0);\n }\n /**\n * Public method to load a texturePacker JSON file.\n * @param data of the JSON file in string format.\n */\n updateFromJSON(data) {\n try {\n const parsedData = JSON.parse(data);\n this.name = parsedData.name;\n const _options = Object.keys(parsedData.options);\n for (let i = 0; i < _options.length; i++) {\n this.options[_options[i]] = parsedData.options[_options[i]];\n }\n for (let i = 0; i < parsedData.frames.length; i += 4) {\n const frame = new TexturePackerFrame(i / 4, new Vector2(parsedData.frames[i], parsedData.frames[i + 1]), new Vector2(parsedData.frames[i + 2], parsedData.frames[i + 3]));\n this.frames.push(frame);\n }\n const channels = Object.keys(parsedData.sets);\n for (let i = 0; i < channels.length; i++) {\n const _t = new Texture(parsedData.sets[channels[i]], this.scene, false, false);\n this.sets[channels[i]] = _t;\n }\n }\n catch (err) {\n Logger.Warn(\"Unable to update from JSON: \" + err);\n }\n }\n}\n/** Packer Layout Constant 0 */\nTexturePacker.LAYOUT_STRIP = 0;\n/** Packer Layout Constant 1 */\nTexturePacker.LAYOUT_POWER2 = 1;\n/** Packer Layout Constant 2 */\nTexturePacker.LAYOUT_COLNUM = 2;\n/** Packer Layout Constant 0 */\nTexturePacker.SUBUV_WRAP = 0;\n/** Packer Layout Constant 1 */\nTexturePacker.SUBUV_EXTEND = 1;\n/** Packer Layout Constant 2 */\nTexturePacker.SUBUV_COLOR = 2;\n//# sourceMappingURL=packer.js.map","export * from \"./packer.js\";\nexport * from \"./frame.js\";\n//# sourceMappingURL=index.js.map","import { Logger } from \"../../../Misc/logger.js\";\nimport { Vector3, Vector2 } from \"../../../Maths/math.vector.js\";\nimport { Color4, Color3 } from \"../../../Maths/math.color.js\";\nimport { Texture } from \"../../../Materials/Textures/texture.js\";\nimport { ProceduralTexture } from \"./proceduralTexture.js\";\nimport { WebRequest } from \"../../../Misc/webRequest.js\";\n/**\n * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.\n * Custom Procedural textures are the easiest way to create your own procedural in your application.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/proceduralTextures#creating-custom-procedural-textures\n */\nexport class CustomProceduralTexture extends ProceduralTexture {\n /**\n * Instantiates a new Custom Procedural Texture.\n * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.\n * Custom Procedural textures are the easiest way to create your own procedural in your application.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/proceduralTextures#creating-custom-procedural-textures\n * @param name Define the name of the texture\n * @param texturePath Define the folder path containing all the custom texture related files (config, shaders...)\n * @param size Define the size of the texture to create\n * @param scene Define the scene the texture belongs to\n * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture\n * @param generateMipMaps Define if the texture should creates mip maps or not\n * @param skipJson Define a boolena indicating that there is no json config file to load\n */\n constructor(name, texturePath, size, scene, fallbackTexture, generateMipMaps, skipJson) {\n super(name, size, null, scene, fallbackTexture, generateMipMaps);\n this._animate = true;\n this._time = 0;\n this._texturePath = texturePath;\n if (!skipJson) {\n //Try to load json\n this._loadJson(texturePath);\n }\n else {\n this.setFragment(this._texturePath);\n }\n this.refreshRate = 1;\n }\n _loadJson(jsonUrl) {\n const noConfigFile = () => {\n try {\n this.setFragment(this._texturePath);\n }\n catch (ex) {\n Logger.Log(\"No json or ShaderStore or DOM element found for CustomProceduralTexture\");\n }\n };\n const configFileUrl = jsonUrl + \"/config.json\";\n const xhr = new WebRequest();\n xhr.open(\"GET\", configFileUrl);\n xhr.addEventListener(\"load\", () => {\n if (xhr.status === 200 || (xhr.responseText && xhr.responseText.length > 0)) {\n try {\n this._config = JSON.parse(xhr.response);\n this.updateShaderUniforms();\n this.updateTextures();\n this.setFragment(this._texturePath + \"/custom\");\n this._animate = this._config.animate;\n this.refreshRate = this._config.refreshrate;\n }\n catch (ex) {\n noConfigFile();\n }\n }\n else {\n noConfigFile();\n }\n }, false);\n xhr.addEventListener(\"error\", () => {\n noConfigFile();\n }, false);\n try {\n xhr.send();\n }\n catch (ex) {\n Logger.Error(\"CustomProceduralTexture: Error on XHR send request.\");\n }\n }\n /**\n * Is the texture ready to be used ? (rendered at least once)\n * @returns true if ready, otherwise, false.\n */\n isReady() {\n if (!super.isReady()) {\n return false;\n }\n for (const name in this._textures) {\n const texture = this._textures[name];\n if (!texture.isReady()) {\n return false;\n }\n }\n return true;\n }\n /**\n * Render the texture to its associated render target.\n * @param useCameraPostProcess Define if camera post process should be applied to the texture\n */\n render(useCameraPostProcess) {\n const scene = this.getScene();\n if (this._animate && scene) {\n this._time += scene.getAnimationRatio() * 0.03;\n this.updateShaderUniforms();\n }\n super.render(useCameraPostProcess);\n }\n /**\n * Update the list of dependant textures samplers in the shader.\n */\n updateTextures() {\n for (let i = 0; i < this._config.sampler2Ds.length; i++) {\n this.setTexture(this._config.sampler2Ds[i].sample2Dname, new Texture(this._texturePath + \"/\" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));\n }\n }\n /**\n * Update the uniform values of the procedural texture in the shader.\n */\n updateShaderUniforms() {\n if (this._config) {\n for (let j = 0; j < this._config.uniforms.length; j++) {\n const uniform = this._config.uniforms[j];\n switch (uniform.type) {\n case \"float\":\n this.setFloat(uniform.name, uniform.value);\n break;\n case \"color3\":\n this.setColor3(uniform.name, new Color3(uniform.r, uniform.g, uniform.b));\n break;\n case \"color4\":\n this.setColor4(uniform.name, new Color4(uniform.r, uniform.g, uniform.b, uniform.a));\n break;\n case \"vector2\":\n this.setVector2(uniform.name, new Vector2(uniform.x, uniform.y));\n break;\n case \"vector3\":\n this.setVector3(uniform.name, new Vector3(uniform.x, uniform.y, uniform.z));\n break;\n }\n }\n }\n this.setFloat(\"time\", this._time);\n }\n /**\n * Define if the texture animates or not.\n */\n get animate() {\n return this._animate;\n }\n set animate(value) {\n this._animate = value;\n }\n}\n//# sourceMappingURL=customProceduralTexture.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"noisePixelShader\";\nconst shader = `uniform float brightness;\runiform float persistence;\runiform float timeScale;\rvarying vec2 vUV;\rvec2 hash22(vec2 p)\r{\rp=p*mat2(127.1,311.7,269.5,183.3);\rp=-1.0+2.0*fract(sin(p)*43758.5453123);\rreturn sin(p*6.283+timeScale);\r}\rfloat interpolationNoise(vec2 p)\r{\rvec2 pi=floor(p);\rvec2 pf=p-pi;\rvec2 w=pf*pf*(3.-2.*pf);\rfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\rfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\rfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\rfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\rfloat xm1=mix(f00,f10,w.x);\rfloat xm2=mix(f01,f11,w.x);\rfloat ym=mix(xm1,xm2,w.y); \rreturn ym;\r}\rfloat perlinNoise2D(float x,float y)\r{\rfloat sum=0.0;\rfloat frequency=0.0;\rfloat amplitude=0.0;\rfor(int i=0; i { });\n }\n /**\n * Clones the raw cube texture.\n * @returns a new cube texture\n */\n clone() {\n return SerializationHelper.Clone(() => {\n const scene = this.getScene();\n const internalTexture = this._texture;\n const texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);\n if (internalTexture.source === InternalTextureSource.CubeRawRGBD) {\n texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);\n }\n return texture;\n }, this);\n }\n}\n//# sourceMappingURL=rawCubeTexture.js.map","import { Texture } from \"./texture.js\";\n\nimport \"../../Engines/Extensions/engine.rawTexture.js\";\n/**\n * Class used to store 3D textures containing user data\n */\nexport class RawTexture3D extends Texture {\n /**\n * Create a new RawTexture3D\n * @param data defines the data of the texture\n * @param width defines the width of the texture\n * @param height defines the height of the texture\n * @param depth defines the depth of the texture\n * @param format defines the texture format to use\n * @param scene defines the hosting scene\n * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)\n * @param invertY defines if texture must be stored with Y axis inverted\n * @param samplingMode defines the sampling mode to use (Texture.TRILINEAR_SAMPLINGMODE by default)\n * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)\n */\n constructor(data, width, height, depth, \n /** Gets or sets the texture format to use */\n format, scene, generateMipMaps = true, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, textureType = 0) {\n super(null, scene, !generateMipMaps, invertY);\n this.format = format;\n this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, null, textureType);\n this.is3D = true;\n }\n /**\n * Update the texture with new data\n * @param data defines the data to store in the texture\n */\n update(data) {\n if (!this._texture) {\n return;\n }\n this._getEngine().updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, null, this._texture.type);\n }\n}\n//# sourceMappingURL=rawTexture3D.js.map","import { Plane } from \"../../Maths/math.plane.js\";\nimport { RenderTargetTexture } from \"../../Materials/Textures/renderTargetTexture.js\";\n/**\n * Creates a refraction texture used by refraction channel of the standard material.\n * It is like a mirror but to see through a material.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#refractiontexture\n */\nexport class RefractionTexture extends RenderTargetTexture {\n /**\n * Creates a refraction texture used by refraction channel of the standard material.\n * It is like a mirror but to see through a material.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#refraction\n * @param name Define the texture name\n * @param size Define the size of the underlying texture\n * @param scene Define the scene the refraction belongs to\n * @param generateMipMaps Define if we need to generate mips level for the refraction\n */\n constructor(name, size, scene, generateMipMaps) {\n super(name, size, scene, generateMipMaps, true);\n /**\n * Define the reflection plane we want to use. The refractionPlane is usually set to the constructed refractor.\n * It is possible to directly set the refractionPlane by directly using a Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the refractionPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the refractor as stated in the doc.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#refraction\n */\n this.refractionPlane = new Plane(0, 1, 0, 1);\n /**\n * Define how deep under the surface we should see.\n */\n this.depth = 2.0;\n this.onBeforeRenderObservable.add(() => {\n this.getScene().clipPlane = this.refractionPlane;\n });\n this.onAfterRenderObservable.add(() => {\n this.getScene().clipPlane = null;\n });\n }\n /**\n * Clone the refraction texture.\n * @returns the cloned texture\n */\n clone() {\n const scene = this.getScene();\n if (!scene) {\n return this;\n }\n const textureSize = this.getSize();\n const newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);\n // Base texture\n newTexture.hasAlpha = this.hasAlpha;\n newTexture.level = this.level;\n // Refraction Texture\n newTexture.refractionPlane = this.refractionPlane.clone();\n if (this.renderList) {\n newTexture.renderList = this.renderList.slice(0);\n }\n newTexture.depth = this.depth;\n return newTexture;\n }\n /**\n * Serialize the texture to a JSON representation you could use in Parse later on\n * @returns the serialized JSON representation\n */\n serialize() {\n if (!this.name) {\n return null;\n }\n const serializationObject = super.serialize();\n serializationObject.mirrorPlane = this.refractionPlane.asArray();\n serializationObject.depth = this.depth;\n return serializationObject;\n }\n}\n//# sourceMappingURL=refractionTexture.js.map","import { ThinTexture } from \"./thinTexture.js\";\n/**\n * This is a tiny helper class to wrap a RenderTargetWrapper in a texture\n * usable as the input of an effect.\n */\nexport class ThinRenderTargetTexture extends ThinTexture {\n /**\n * Gets the render target wrapper associated with this render target\n */\n get renderTarget() {\n return this._renderTarget;\n }\n /**\n * Instantiates a new ThinRenderTargetTexture.\n * Tiny helper class to wrap a RenderTargetWrapper in a texture.\n * This can be used as an internal texture wrapper in ThinEngine to benefit from the cache and to hold on the associated RTT\n * @param engine Define the internalTexture to wrap\n * @param size Define the size of the RTT to create\n * @param options Define rendertarget options\n */\n constructor(engine, size, options) {\n super(null);\n this._renderTarget = null;\n this._engine = engine;\n this._renderTargetOptions = options;\n this.resize(size);\n }\n /**\n * Resize the texture to a new desired size.\n * Be careful as it will recreate all the data in the new texture.\n * @param size Define the new size. It can be:\n * - a number for squared texture,\n * - an object containing { width: number, height: number }\n */\n resize(size) {\n var _a;\n (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.dispose();\n this._renderTarget = null;\n this._texture = null;\n this._size = size;\n if (this._engine) {\n this._renderTarget = this._engine.createRenderTargetTexture(this._size, this._renderTargetOptions);\n }\n this._texture = this.renderTarget.texture;\n }\n /**\n * Get the underlying lower level texture from Babylon.\n * @returns the internal texture\n */\n getInternalTexture() {\n return this._texture;\n }\n /**\n * Get the class name of the texture.\n * @returns \"ThinRenderTargetTexture\"\n */\n getClassName() {\n return \"ThinRenderTargetTexture\";\n }\n /**\n * Dispose the texture and release its associated resources.\n * @param disposeOnlyFramebuffers\n */\n dispose(disposeOnlyFramebuffers = false) {\n var _a;\n (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.dispose(true);\n this._renderTarget = null;\n if (!disposeOnlyFramebuffers) {\n super.dispose();\n }\n }\n}\n//# sourceMappingURL=thinRenderTargetTexture.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./baseTexture.js\";\n// eslint-disable-next-line import/export\nexport * from \"./baseTexture.polynomial.js\";\nexport * from \"./colorGradingTexture.js\";\nexport * from \"./cubeTexture.js\";\nexport * from \"./dynamicTexture.js\";\nexport * from \"./equiRectangularCubeTexture.js\";\nexport * from \"./externalTexture.js\";\nexport * from \"./Filtering/hdrFiltering.js\";\nexport * from \"./hdrCubeTexture.js\";\nexport * from \"./htmlElementTexture.js\";\nexport * from \"./internalTexture.js\";\nexport * from \"./internalTextureLoader.js\";\nexport * from \"./Loaders/index.js\";\nexport * from \"./mirrorTexture.js\";\nexport * from \"./multiRenderTarget.js\";\nexport * from \"./Packer/index.js\";\nexport * from \"./Procedurals/index.js\";\nexport * from \"./rawCubeTexture.js\";\nexport * from \"./rawTexture.js\";\nexport * from \"./rawTexture2DArray.js\";\nexport * from \"./rawTexture3D.js\";\nexport * from \"./refractionTexture.js\";\nexport * from \"./renderTargetTexture.js\";\nexport * from \"./textureSampler.js\";\nexport * from \"./texture.js\";\nexport * from \"./thinTexture.js\";\nexport * from \"./thinRenderTargetTexture.js\";\nexport * from \"./videoTexture.js\";\nexport * from \"./ktx2decoderTypes.js\";\n//# sourceMappingURL=index.js.map","export * from \"./nodeMaterialBlockTargets.js\";\nexport * from \"./nodeMaterialBlockConnectionPointTypes.js\";\nexport * from \"./nodeMaterialBlockConnectionPointMode.js\";\nexport * from \"./nodeMaterialSystemValues.js\";\nexport * from \"./nodeMaterialModes.js\";\n//# sourceMappingURL=index.js.map","import { NodeMaterialConnectionPoint, NodeMaterialConnectionPointCompatibilityStates } from \"./nodeMaterialBlockConnectionPoint.js\";\n/**\n * Defines a connection point to be used for points with a custom object type\n */\nexport class NodeMaterialConnectionPointCustomObject extends NodeMaterialConnectionPoint {\n /**\n * Creates a new connection point\n * @param name defines the connection point name\n * @param ownerBlock defines the block hosting this connection point\n * @param direction defines the direction of the connection point\n * @param _blockType\n * @param _blockName\n */\n constructor(name, ownerBlock, direction, \n // @internal\n _blockType, _blockName) {\n super(name, ownerBlock, direction);\n this._blockType = _blockType;\n this._blockName = _blockName;\n this.needDualDirectionValidation = true;\n }\n /**\n * Gets a number indicating if the current point can be connected to another point\n * @param connectionPoint defines the other connection point\n * @returns a number defining the compatibility state\n */\n checkCompatibilityState(connectionPoint) {\n return connectionPoint instanceof NodeMaterialConnectionPointCustomObject && connectionPoint._blockName === this._blockName\n ? NodeMaterialConnectionPointCompatibilityStates.Compatible\n : NodeMaterialConnectionPointCompatibilityStates.TypeIncompatible;\n }\n /**\n * Creates a block suitable to be used as an input for this input point.\n * If null is returned, a block based on the point type will be created.\n * @returns The returned string parameter is the name of the output point of NodeMaterialBlock (first parameter of the returned array) that can be connected to the input\n */\n createCustomInputBlock() {\n return [new this._blockType(this._blockName), this.name];\n }\n}\n//# sourceMappingURL=nodeMaterialConnectionPointCustomObject.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialSystemValues } from \"../../Enums/nodeMaterialSystemValues.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { MaterialHelper } from \"../../../materialHelper.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport \"../../../../Shaders/ShadersInclude/bonesDeclaration.js\";\nimport \"../../../../Shaders/ShadersInclude/bonesVertex.js\";\n/**\n * Block used to add support for vertex skinning (bones)\n */\nexport class BonesBlock extends NodeMaterialBlock {\n /**\n * Creates a new BonesBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Vertex);\n this.registerInput(\"matricesIndices\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerInput(\"matricesWeights\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerInput(\"matricesIndicesExtra\", NodeMaterialBlockConnectionPointTypes.Vector4, true);\n this.registerInput(\"matricesWeightsExtra\", NodeMaterialBlockConnectionPointTypes.Vector4, true);\n this.registerInput(\"world\", NodeMaterialBlockConnectionPointTypes.Matrix);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Matrix);\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"boneSampler\");\n state._excludeVariableName(\"boneTextureWidth\");\n state._excludeVariableName(\"mBones\");\n state._excludeVariableName(\"BonesPerMesh\");\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"BonesBlock\";\n }\n /**\n * Gets the matrix indices input component\n */\n get matricesIndices() {\n return this._inputs[0];\n }\n /**\n * Gets the matrix weights input component\n */\n get matricesWeights() {\n return this._inputs[1];\n }\n /**\n * Gets the extra matrix indices input component\n */\n get matricesIndicesExtra() {\n return this._inputs[2];\n }\n /**\n * Gets the extra matrix weights input component\n */\n get matricesWeightsExtra() {\n return this._inputs[3];\n }\n /**\n * Gets the world input component\n */\n get world() {\n return this._inputs[4];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n autoConfigure(material) {\n if (!this.matricesIndices.isConnected) {\n let matricesIndicesInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"matricesIndices\");\n if (!matricesIndicesInput) {\n matricesIndicesInput = new InputBlock(\"matricesIndices\");\n matricesIndicesInput.setAsAttribute(\"matricesIndices\");\n }\n matricesIndicesInput.output.connectTo(this.matricesIndices);\n }\n if (!this.matricesWeights.isConnected) {\n let matricesWeightsInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"matricesWeights\");\n if (!matricesWeightsInput) {\n matricesWeightsInput = new InputBlock(\"matricesWeights\");\n matricesWeightsInput.setAsAttribute(\"matricesWeights\");\n }\n matricesWeightsInput.output.connectTo(this.matricesWeights);\n }\n if (!this.world.isConnected) {\n let worldInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.World);\n if (!worldInput) {\n worldInput = new InputBlock(\"world\");\n worldInput.setAsSystemValue(NodeMaterialSystemValues.World);\n }\n worldInput.output.connectTo(this.world);\n }\n }\n provideFallbacks(mesh, fallbacks) {\n if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {\n fallbacks.addCPUSkinningFallback(0, mesh);\n }\n }\n bind(effect, nodeMaterial, mesh) {\n MaterialHelper.BindBonesParameters(mesh, effect);\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n if (!defines._areAttributesDirty) {\n return;\n }\n MaterialHelper.PrepareDefinesForBones(mesh, defines);\n }\n _buildBlock(state) {\n super._buildBlock(state);\n // Register for compilation fallbacks\n state.sharedData.blocksWithFallbacks.push(this);\n // Register for binding\n state.sharedData.forcedBindableBlocks.push(this);\n // Register for defines\n state.sharedData.blocksWithDefines.push(this);\n // Register internal uniforms and samplers\n state.uniforms.push(\"boneTextureWidth\");\n state.uniforms.push(\"mBones\");\n state.samplers.push(\"boneSampler\");\n // Emit code\n const comments = `//${this.name}`;\n state._emitFunctionFromInclude(\"bonesDeclaration\", comments, {\n removeAttributes: true,\n removeUniforms: false,\n removeVaryings: true,\n removeIfDef: false,\n });\n const influenceVariablename = state._getFreeVariableName(\"influence\");\n state.compilationString += state._emitCodeFromInclude(\"bonesVertex\", comments, {\n replaceStrings: [\n {\n search: /finalWorld=finalWorld\\*influence;/,\n replace: \"\",\n },\n {\n search: /influence/gm,\n replace: influenceVariablename,\n },\n ],\n });\n const output = this._outputs[0];\n const worldInput = this.world;\n state.compilationString += `#if NUM_BONE_INFLUENCERS>0\\r\\n`;\n state.compilationString += this._declareOutput(output, state) + ` = ${worldInput.associatedVariableName} * ${influenceVariablename};\\r\\n`;\n state.compilationString += `#else\\r\\n`;\n state.compilationString += this._declareOutput(output, state) + ` = ${worldInput.associatedVariableName};\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.BonesBlock\", BonesBlock);\n//# sourceMappingURL=bonesBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialSystemValues } from \"../../Enums/nodeMaterialSystemValues.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\n/**\n * Block used to add support for instances\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/copies/instances\n */\nexport class InstancesBlock extends NodeMaterialBlock {\n /**\n * Creates a new InstancesBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Vertex);\n this.registerInput(\"world0\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerInput(\"world1\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerInput(\"world2\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerInput(\"world3\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerInput(\"world\", NodeMaterialBlockConnectionPointTypes.Matrix, true);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Matrix);\n this.registerOutput(\"instanceID\", NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"InstancesBlock\";\n }\n /**\n * Gets the first world row input component\n */\n get world0() {\n return this._inputs[0];\n }\n /**\n * Gets the second world row input component\n */\n get world1() {\n return this._inputs[1];\n }\n /**\n * Gets the third world row input component\n */\n get world2() {\n return this._inputs[2];\n }\n /**\n * Gets the forth world row input component\n */\n get world3() {\n return this._inputs[3];\n }\n /**\n * Gets the world input component\n */\n get world() {\n return this._inputs[4];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n /**\n * Gets the instanceID component\n */\n get instanceID() {\n return this._outputs[1];\n }\n autoConfigure(material) {\n if (!this.world0.connectedPoint) {\n let world0Input = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"world0\");\n if (!world0Input) {\n world0Input = new InputBlock(\"world0\");\n world0Input.setAsAttribute(\"world0\");\n }\n world0Input.output.connectTo(this.world0);\n }\n if (!this.world1.connectedPoint) {\n let world1Input = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"world1\");\n if (!world1Input) {\n world1Input = new InputBlock(\"world1\");\n world1Input.setAsAttribute(\"world1\");\n }\n world1Input.output.connectTo(this.world1);\n }\n if (!this.world2.connectedPoint) {\n let world2Input = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"world2\");\n if (!world2Input) {\n world2Input = new InputBlock(\"world2\");\n world2Input.setAsAttribute(\"world2\");\n }\n world2Input.output.connectTo(this.world2);\n }\n if (!this.world3.connectedPoint) {\n let world3Input = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"world3\");\n if (!world3Input) {\n world3Input = new InputBlock(\"world3\");\n world3Input.setAsAttribute(\"world3\");\n }\n world3Input.output.connectTo(this.world3);\n }\n if (!this.world.connectedPoint) {\n let worldInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"world\");\n if (!worldInput) {\n worldInput = new InputBlock(\"world\");\n worldInput.setAsSystemValue(NodeMaterialSystemValues.World);\n }\n worldInput.output.connectTo(this.world);\n }\n this.world.define = \"!INSTANCES || THIN_INSTANCES\";\n }\n prepareDefines(mesh, nodeMaterial, defines, useInstances = false, subMesh) {\n let changed = false;\n if (defines[\"INSTANCES\"] !== useInstances) {\n defines.setValue(\"INSTANCES\", useInstances);\n changed = true;\n }\n if (subMesh && defines[\"THIN_INSTANCES\"] !== !!(subMesh === null || subMesh === void 0 ? void 0 : subMesh.getRenderingMesh().hasThinInstances)) {\n defines.setValue(\"THIN_INSTANCES\", !!(subMesh === null || subMesh === void 0 ? void 0 : subMesh.getRenderingMesh().hasThinInstances));\n changed = true;\n }\n if (changed) {\n defines.markAsUnprocessed();\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const engine = state.sharedData.scene.getEngine();\n // Register for defines\n state.sharedData.blocksWithDefines.push(this);\n // Emit code\n const output = this._outputs[0];\n const instanceID = this._outputs[1];\n const world0 = this.world0;\n const world1 = this.world1;\n const world2 = this.world2;\n const world3 = this.world3;\n state.compilationString += `#ifdef INSTANCES\\r\\n`;\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = mat4(${world0.associatedVariableName}, ${world1.associatedVariableName}, ${world2.associatedVariableName}, ${world3.associatedVariableName});\\r\\n`;\n state.compilationString += `#ifdef THIN_INSTANCES\\r\\n`;\n state.compilationString += `${output.associatedVariableName} = ${this.world.associatedVariableName} * ${output.associatedVariableName};\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n if (engine._caps.canUseGLInstanceID) {\n state.compilationString += this._declareOutput(instanceID, state) + ` = float(gl_InstanceID);\\r\\n`;\n }\n else {\n state.compilationString += this._declareOutput(instanceID, state) + ` = 0.0;\\r\\n`;\n }\n state.compilationString += `#else\\r\\n`;\n state.compilationString += this._declareOutput(output, state) + ` = ${this.world.associatedVariableName};\\r\\n`;\n state.compilationString += this._declareOutput(instanceID, state) + ` = 0.0;\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.InstancesBlock\", InstancesBlock);\n//# sourceMappingURL=instancesBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { MaterialHelper } from \"../../../materialHelper.js\";\nimport { VertexBuffer } from \"../../../../Buffers/buffer.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport \"../../../../Shaders/ShadersInclude/morphTargetsVertexDeclaration.js\";\nimport \"../../../../Shaders/ShadersInclude/morphTargetsVertexGlobalDeclaration.js\";\n/**\n * Block used to add morph targets support to vertex shader\n */\nexport class MorphTargetsBlock extends NodeMaterialBlock {\n /**\n * Create a new MorphTargetsBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Vertex);\n this.registerInput(\"position\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerInput(\"normal\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerInput(\"tangent\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.tangent.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color4 | NodeMaterialBlockConnectionPointTypes.Vector4 | NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerInput(\"uv\", NodeMaterialBlockConnectionPointTypes.Vector2);\n this.registerOutput(\"positionOutput\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerOutput(\"normalOutput\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerOutput(\"tangentOutput\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerOutput(\"uvOutput\", NodeMaterialBlockConnectionPointTypes.Vector2);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"MorphTargetsBlock\";\n }\n /**\n * Gets the position input component\n */\n get position() {\n return this._inputs[0];\n }\n /**\n * Gets the normal input component\n */\n get normal() {\n return this._inputs[1];\n }\n /**\n * Gets the tangent input component\n */\n get tangent() {\n return this._inputs[2];\n }\n /**\n * Gets the tangent input component\n */\n get uv() {\n return this._inputs[3];\n }\n /**\n * Gets the position output component\n */\n get positionOutput() {\n return this._outputs[0];\n }\n /**\n * Gets the normal output component\n */\n get normalOutput() {\n return this._outputs[1];\n }\n /**\n * Gets the tangent output component\n */\n get tangentOutput() {\n return this._outputs[2];\n }\n /**\n * Gets the tangent output component\n */\n get uvOutput() {\n return this._outputs[3];\n }\n initialize(state) {\n state._excludeVariableName(\"morphTargetInfluences\");\n }\n autoConfigure(material) {\n if (!this.position.isConnected) {\n let positionInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"position\");\n if (!positionInput) {\n positionInput = new InputBlock(\"position\");\n positionInput.setAsAttribute();\n }\n positionInput.output.connectTo(this.position);\n }\n if (!this.normal.isConnected) {\n let normalInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"normal\");\n if (!normalInput) {\n normalInput = new InputBlock(\"normal\");\n normalInput.setAsAttribute(\"normal\");\n }\n normalInput.output.connectTo(this.normal);\n }\n if (!this.tangent.isConnected) {\n let tangentInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"tangent\");\n if (!tangentInput) {\n tangentInput = new InputBlock(\"tangent\");\n tangentInput.setAsAttribute(\"tangent\");\n }\n tangentInput.output.connectTo(this.tangent);\n }\n if (!this.uv.isConnected) {\n let uvInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"uv\");\n if (!uvInput) {\n uvInput = new InputBlock(\"uv\");\n uvInput.setAsAttribute(\"uv\");\n }\n uvInput.output.connectTo(this.uv);\n }\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n if (mesh.morphTargetManager) {\n const morphTargetManager = mesh.morphTargetManager;\n if ((morphTargetManager === null || morphTargetManager === void 0 ? void 0 : morphTargetManager.isUsingTextureForTargets) && morphTargetManager.numInfluencers !== defines[\"NUM_MORPH_INFLUENCERS\"]) {\n defines.markAsAttributesDirty();\n }\n }\n if (!defines._areAttributesDirty) {\n return;\n }\n MaterialHelper.PrepareDefinesForMorphTargets(mesh, defines);\n }\n bind(effect, nodeMaterial, mesh) {\n if (mesh && mesh.morphTargetManager && mesh.morphTargetManager.numInfluencers > 0) {\n MaterialHelper.BindMorphTargetParameters(mesh, effect);\n if (mesh.morphTargetManager.isUsingTextureForTargets) {\n mesh.morphTargetManager._bind(effect);\n }\n }\n }\n replaceRepeatableContent(vertexShaderState, fragmentShaderState, mesh, defines) {\n const position = this.position;\n const normal = this.normal;\n const tangent = this.tangent;\n const uv = this.uv;\n const positionOutput = this.positionOutput;\n const normalOutput = this.normalOutput;\n const tangentOutput = this.tangentOutput;\n const uvOutput = this.uvOutput;\n const state = vertexShaderState;\n const repeatCount = defines.NUM_MORPH_INFLUENCERS;\n const manager = mesh.morphTargetManager;\n const hasNormals = manager && manager.supportsNormals && defines[\"NORMAL\"];\n const hasTangents = manager && manager.supportsTangents && defines[\"TANGENT\"];\n const hasUVs = manager && manager.supportsUVs && defines[\"UV1\"];\n let injectionCode = \"\";\n if ((manager === null || manager === void 0 ? void 0 : manager.isUsingTextureForTargets) && repeatCount > 0) {\n injectionCode += `float vertexID;\\r\\n`;\n }\n for (let index = 0; index < repeatCount; index++) {\n injectionCode += `#ifdef MORPHTARGETS\\r\\n`;\n if (manager === null || manager === void 0 ? void 0 : manager.isUsingTextureForTargets) {\n injectionCode += `vertexID = float(gl_VertexID) * morphTargetTextureInfo.x;\\r\\n`;\n injectionCode += `${positionOutput.associatedVariableName} += (readVector3FromRawSampler(${index}, vertexID) - ${position.associatedVariableName}) * morphTargetInfluences[${index}];\\r\\n`;\n injectionCode += `vertexID += 1.0;\\r\\n`;\n }\n else {\n injectionCode += `${positionOutput.associatedVariableName} += (position${index} - ${position.associatedVariableName}) * morphTargetInfluences[${index}];\\r\\n`;\n }\n if (hasNormals) {\n injectionCode += `#ifdef MORPHTARGETS_NORMAL\\r\\n`;\n if (manager === null || manager === void 0 ? void 0 : manager.isUsingTextureForTargets) {\n injectionCode += `${normalOutput.associatedVariableName} += (readVector3FromRawSampler(${index}, vertexID) - ${normal.associatedVariableName}) * morphTargetInfluences[${index}];\\r\\n`;\n injectionCode += `vertexID += 1.0;\\r\\n`;\n }\n else {\n injectionCode += `${normalOutput.associatedVariableName} += (normal${index} - ${normal.associatedVariableName}) * morphTargetInfluences[${index}];\\r\\n`;\n }\n injectionCode += `#endif\\r\\n`;\n }\n if (hasUVs) {\n injectionCode += `#ifdef MORPHTARGETS_UV\\r\\n`;\n if (manager === null || manager === void 0 ? void 0 : manager.isUsingTextureForTargets) {\n injectionCode += `${uvOutput.associatedVariableName} += (readVector3FromRawSampler(${index}, vertexID).xy - ${uv.associatedVariableName}) * morphTargetInfluences[${index}];\\r\\n`;\n injectionCode += `vertexID += 1.0;\\r\\n`;\n }\n else {\n injectionCode += `${uvOutput.associatedVariableName}.xy += (uv_${index} - ${uv.associatedVariableName}.xy) * morphTargetInfluences[${index}];\\r\\n`;\n }\n injectionCode += `#endif\\r\\n`;\n }\n if (hasTangents) {\n injectionCode += `#ifdef MORPHTARGETS_TANGENT\\r\\n`;\n if (manager === null || manager === void 0 ? void 0 : manager.isUsingTextureForTargets) {\n injectionCode += `${tangentOutput.associatedVariableName}.xyz += (readVector3FromRawSampler(${index}, vertexID) - ${tangent.associatedVariableName}.xyz) * morphTargetInfluences[${index}];\\r\\n`;\n }\n else {\n injectionCode += `${tangentOutput.associatedVariableName}.xyz += (tangent${index} - ${tangent.associatedVariableName}.xyz) * morphTargetInfluences[${index}];\\r\\n`;\n }\n if (tangent.type === NodeMaterialBlockConnectionPointTypes.Vector4) {\n injectionCode += `${tangentOutput.associatedVariableName}.w = ${tangent.associatedVariableName}.w;\\r\\n`;\n }\n else {\n injectionCode += `${tangentOutput.associatedVariableName}.w = 1.;\\r\\n`;\n }\n injectionCode += `#endif\\r\\n`;\n }\n injectionCode += `#endif\\r\\n`;\n }\n state.compilationString = state.compilationString.replace(this._repeatableContentAnchor, injectionCode);\n if (repeatCount > 0) {\n for (let index = 0; index < repeatCount; index++) {\n state.attributes.push(VertexBuffer.PositionKind + index);\n if (hasNormals) {\n state.attributes.push(VertexBuffer.NormalKind + index);\n }\n if (hasTangents) {\n state.attributes.push(VertexBuffer.TangentKind + index);\n }\n if (hasUVs) {\n state.attributes.push(VertexBuffer.UVKind + \"_\" + index);\n }\n }\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n // Register for defines\n state.sharedData.blocksWithDefines.push(this);\n // Register for binding\n state.sharedData.bindableBlocks.push(this);\n // Register for repeatable content generation\n state.sharedData.repeatableContentBlocks.push(this);\n // Emit code\n const position = this.position;\n const normal = this.normal;\n const tangent = this.tangent;\n const uv = this.uv;\n const positionOutput = this.positionOutput;\n const normalOutput = this.normalOutput;\n const tangentOutput = this.tangentOutput;\n const uvOutput = this.uvOutput;\n const comments = `//${this.name}`;\n state.uniforms.push(\"morphTargetInfluences\");\n state.uniforms.push(\"morphTargetTextureInfo\");\n state.uniforms.push(\"morphTargetTextureIndices\");\n state.samplers.push(\"morphTargets\");\n state._emitFunctionFromInclude(\"morphTargetsVertexGlobalDeclaration\", comments);\n state._emitFunctionFromInclude(\"morphTargetsVertexDeclaration\", comments, {\n repeatKey: \"maxSimultaneousMorphTargets\",\n });\n state.compilationString += `${this._declareOutput(positionOutput, state)} = ${position.associatedVariableName};\\r\\n`;\n state.compilationString += `#ifdef NORMAL\\r\\n`;\n state.compilationString += `${this._declareOutput(normalOutput, state)} = ${normal.associatedVariableName};\\r\\n`;\n state.compilationString += `#else\\r\\n`;\n state.compilationString += `${this._declareOutput(normalOutput, state)} = vec3(0., 0., 0.);\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n state.compilationString += `#ifdef TANGENT\\r\\n`;\n state.compilationString += `${this._declareOutput(tangentOutput, state)} = ${tangent.associatedVariableName};\\r\\n`;\n state.compilationString += `#else\\r\\n`;\n state.compilationString += `${this._declareOutput(tangentOutput, state)} = vec4(0., 0., 0., 0.);\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n state.compilationString += `#ifdef UV1\\r\\n`;\n state.compilationString += `${this._declareOutput(uvOutput, state)} = ${uv.associatedVariableName};\\r\\n`;\n state.compilationString += `#else\\r\\n`;\n state.compilationString += `${this._declareOutput(uvOutput, state)} = vec2(0., 0.);\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n // Repeatable content\n this._repeatableContentAnchor = state._repeatableContentAnchor;\n state.compilationString += this._repeatableContentAnchor;\n return this;\n }\n}\nRegisterClass(\"BABYLON.MorphTargetsBlock\", MorphTargetsBlock);\n//# sourceMappingURL=morphTargetsBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { PointLight } from \"../../../../Lights/pointLight.js\";\n/**\n * Block used to get data information from a light\n */\nexport class LightInformationBlock extends NodeMaterialBlock {\n /**\n * Creates a new LightInformationBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Vertex);\n this.registerInput(\"worldPosition\", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex);\n this.registerOutput(\"direction\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerOutput(\"color\", NodeMaterialBlockConnectionPointTypes.Color3);\n this.registerOutput(\"intensity\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"shadowBias\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"shadowNormalBias\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"shadowDepthScale\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"shadowDepthRange\", NodeMaterialBlockConnectionPointTypes.Vector2);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"LightInformationBlock\";\n }\n /**\n * Gets the world position input component\n */\n get worldPosition() {\n return this._inputs[0];\n }\n /**\n * Gets the direction output component\n */\n get direction() {\n return this._outputs[0];\n }\n /**\n * Gets the direction output component\n */\n get color() {\n return this._outputs[1];\n }\n /**\n * Gets the direction output component\n */\n get intensity() {\n return this._outputs[2];\n }\n /**\n * Gets the shadow bias output component\n */\n get shadowBias() {\n return this._outputs[3];\n }\n /**\n * Gets the shadow normal bias output component\n */\n get shadowNormalBias() {\n return this._outputs[4];\n }\n /**\n * Gets the shadow depth scale component\n */\n get shadowDepthScale() {\n return this._outputs[5];\n }\n /**\n * Gets the shadow depth range component\n */\n get shadowDepthRange() {\n return this._outputs[6];\n }\n bind(effect, nodeMaterial, mesh) {\n if (!mesh) {\n return;\n }\n if (this.light && this.light.isDisposed()) {\n this.light = null;\n }\n let light = this.light;\n const scene = nodeMaterial.getScene();\n if (!light && scene.lights.length) {\n light = this.light = scene.lights[0];\n this._forcePrepareDefines = true;\n }\n if (!light || !light.isEnabled) {\n effect.setFloat3(this._lightDataUniformName, 0, 0, 0);\n effect.setFloat4(this._lightColorUniformName, 0, 0, 0, 0);\n return;\n }\n light.transferToNodeMaterialEffect(effect, this._lightDataUniformName);\n effect.setColor4(this._lightColorUniformName, light.diffuse, light.intensity);\n const generator = light.getShadowGenerator();\n if (this.shadowBias.hasEndpoints || this.shadowNormalBias.hasEndpoints || this.shadowDepthScale.hasEndpoints) {\n if (generator) {\n effect.setFloat3(this._lightShadowUniformName, generator.bias, generator.normalBias, generator.depthScale);\n }\n else {\n effect.setFloat3(this._lightShadowUniformName, 0, 0, 0);\n }\n }\n if (this.shadowDepthRange) {\n if (generator && scene.activeCamera) {\n const shadowLight = light;\n effect.setFloat2(this._lightShadowExtraUniformName, shadowLight.getDepthMinZ(scene.activeCamera), shadowLight.getDepthMinZ(scene.activeCamera) + shadowLight.getDepthMaxZ(scene.activeCamera));\n }\n else {\n effect.setFloat2(this._lightShadowExtraUniformName, 0, 0);\n }\n }\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n if (!defines._areLightsDirty && !this._forcePrepareDefines) {\n return;\n }\n this._forcePrepareDefines = false;\n const light = this.light;\n defines.setValue(this._lightTypeDefineName, light && light instanceof PointLight ? true : false, true);\n }\n _buildBlock(state) {\n super._buildBlock(state);\n state.sharedData.bindableBlocks.push(this);\n state.sharedData.blocksWithDefines.push(this);\n const direction = this.direction;\n const color = this.color;\n const intensity = this.intensity;\n const shadowBias = this.shadowBias;\n const shadowNormalBias = this.shadowNormalBias;\n const shadowDepthScale = this.shadowDepthScale;\n const shadowDepthRange = this.shadowDepthRange;\n this._lightDataUniformName = state._getFreeVariableName(\"lightData\");\n this._lightColorUniformName = state._getFreeVariableName(\"lightColor\");\n this._lightShadowUniformName = state._getFreeVariableName(\"shadowData\");\n this._lightShadowExtraUniformName = state._getFreeVariableName(\"shadowExtraData\");\n this._lightTypeDefineName = state._getFreeDefineName(\"LIGHTPOINTTYPE\");\n state._emitUniformFromString(this._lightDataUniformName, \"vec3\");\n state._emitUniformFromString(this._lightColorUniformName, \"vec4\");\n state.compilationString += `#ifdef ${this._lightTypeDefineName}\\r\\n`;\n state.compilationString += this._declareOutput(direction, state) + ` = normalize(${this.worldPosition.associatedVariableName}.xyz - ${this._lightDataUniformName});\\r\\n`;\n state.compilationString += `#else\\r\\n`;\n state.compilationString += this._declareOutput(direction, state) + ` = ${this._lightDataUniformName};\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n state.compilationString += this._declareOutput(color, state) + ` = ${this._lightColorUniformName}.rgb;\\r\\n`;\n state.compilationString += this._declareOutput(intensity, state) + ` = ${this._lightColorUniformName}.a;\\r\\n`;\n if (shadowBias.hasEndpoints || shadowNormalBias.hasEndpoints || shadowDepthScale.hasEndpoints) {\n state._emitUniformFromString(this._lightShadowUniformName, \"vec3\");\n if (shadowBias.hasEndpoints) {\n state.compilationString += this._declareOutput(shadowBias, state) + ` = ${this._lightShadowUniformName}.x;\\r\\n`;\n }\n if (shadowNormalBias.hasEndpoints) {\n state.compilationString += this._declareOutput(shadowNormalBias, state) + ` = ${this._lightShadowUniformName}.y;\\r\\n`;\n }\n if (shadowDepthScale.hasEndpoints) {\n state.compilationString += this._declareOutput(shadowDepthScale, state) + ` = ${this._lightShadowUniformName}.z;\\r\\n`;\n }\n }\n if (shadowDepthRange.hasEndpoints) {\n state._emitUniformFromString(this._lightShadowExtraUniformName, \"vec2\");\n state.compilationString += this._declareOutput(shadowDepthRange, state) + ` = ${this._lightShadowUniformName};\\r\\n`;\n }\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n if (this.light) {\n serializationObject.lightId = this.light.id;\n }\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n if (serializationObject.lightId) {\n this.light = scene.getLightById(serializationObject.lightId);\n }\n }\n}\nRegisterClass(\"BABYLON.LightInformationBlock\", LightInformationBlock);\n//# sourceMappingURL=lightInformationBlock.js.map","export * from \"./vertexOutputBlock.js\";\nexport * from \"./bonesBlock.js\";\nexport * from \"./instancesBlock.js\";\nexport * from \"./morphTargetsBlock.js\";\nexport * from \"./lightInformationBlock.js\";\n//# sourceMappingURL=index.js.map","import { __decorate } from \"../../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../../nodeMaterialDecorator.js\";\nimport \"../../../../Shaders/ShadersInclude/helperFunctions.js\";\nimport \"../../../../Shaders/ShadersInclude/imageProcessingDeclaration.js\";\nimport \"../../../../Shaders/ShadersInclude/imageProcessingFunctions.js\";\n/**\n * Block used to add image processing support to fragment shader\n */\nexport class ImageProcessingBlock extends NodeMaterialBlock {\n /**\n * Create a new ImageProcessingBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n /**\n * Defines if the input should be converted to linear space (default: true)\n */\n this.convertInputToLinearSpace = true;\n this.registerInput(\"color\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Color4);\n this.registerOutput(\"rgb\", NodeMaterialBlockConnectionPointTypes.Color3);\n this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 |\n NodeMaterialBlockConnectionPointTypes.Color4 |\n NodeMaterialBlockConnectionPointTypes.Vector3 |\n NodeMaterialBlockConnectionPointTypes.Vector4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ImageProcessingBlock\";\n }\n /**\n * Gets the color input component\n */\n get color() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n /**\n * Gets the rgb component\n */\n get rgb() {\n return this._outputs[1];\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"exposureLinear\");\n state._excludeVariableName(\"contrast\");\n state._excludeVariableName(\"vInverseScreenSize\");\n state._excludeVariableName(\"vignetteSettings1\");\n state._excludeVariableName(\"vignetteSettings2\");\n state._excludeVariableName(\"vCameraColorCurveNegative\");\n state._excludeVariableName(\"vCameraColorCurveNeutral\");\n state._excludeVariableName(\"vCameraColorCurvePositive\");\n state._excludeVariableName(\"txColorTransform\");\n state._excludeVariableName(\"colorTransformSettings\");\n state._excludeVariableName(\"ditherIntensity\");\n }\n isReady(mesh, nodeMaterial, defines) {\n if (defines._areImageProcessingDirty && nodeMaterial.imageProcessingConfiguration) {\n if (!nodeMaterial.imageProcessingConfiguration.isReady()) {\n return false;\n }\n }\n return true;\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n if (defines._areImageProcessingDirty && nodeMaterial.imageProcessingConfiguration) {\n nodeMaterial.imageProcessingConfiguration.prepareDefines(defines);\n }\n }\n bind(effect, nodeMaterial, mesh) {\n if (!mesh) {\n return;\n }\n if (!nodeMaterial.imageProcessingConfiguration) {\n return;\n }\n nodeMaterial.imageProcessingConfiguration.bind(effect);\n }\n _buildBlock(state) {\n var _a;\n super._buildBlock(state);\n // Register for defines\n state.sharedData.blocksWithDefines.push(this);\n // Register for blocking\n state.sharedData.blockingBlocks.push(this);\n // Register for binding\n state.sharedData.bindableBlocks.push(this);\n // Uniforms\n state.uniforms.push(\"exposureLinear\");\n state.uniforms.push(\"contrast\");\n state.uniforms.push(\"vInverseScreenSize\");\n state.uniforms.push(\"vignetteSettings1\");\n state.uniforms.push(\"vignetteSettings2\");\n state.uniforms.push(\"vCameraColorCurveNegative\");\n state.uniforms.push(\"vCameraColorCurveNeutral\");\n state.uniforms.push(\"vCameraColorCurvePositive\");\n state.uniforms.push(\"txColorTransform\");\n state.uniforms.push(\"colorTransformSettings\");\n state.uniforms.push(\"ditherIntensity\");\n // Emit code\n const color = this.color;\n const output = this._outputs[0];\n const comments = `//${this.name}`;\n state._emitFunctionFromInclude(\"helperFunctions\", comments);\n state._emitFunctionFromInclude(\"imageProcessingDeclaration\", comments);\n state._emitFunctionFromInclude(\"imageProcessingFunctions\", comments);\n if ((_a = color.connectedPoint) === null || _a === void 0 ? void 0 : _a.isConnected) {\n if (color.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Color4 || color.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Vector4) {\n state.compilationString += `${this._declareOutput(output, state)} = ${color.associatedVariableName};\\r\\n`;\n }\n else {\n state.compilationString += `${this._declareOutput(output, state)} = vec4(${color.associatedVariableName}, 1.0);\\r\\n`;\n }\n state.compilationString += `#ifdef IMAGEPROCESSINGPOSTPROCESS\\r\\n`;\n if (this.convertInputToLinearSpace) {\n state.compilationString += `${output.associatedVariableName}.rgb = toLinearSpace(${color.associatedVariableName}.rgb);\\r\\n`;\n }\n state.compilationString += `#else\\r\\n`;\n state.compilationString += `#ifdef IMAGEPROCESSING\\r\\n`;\n if (this.convertInputToLinearSpace) {\n state.compilationString += `${output.associatedVariableName}.rgb = toLinearSpace(${color.associatedVariableName}.rgb);\\r\\n`;\n }\n state.compilationString += `${output.associatedVariableName} = applyImageProcessing(${output.associatedVariableName});\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n if (this.rgb.hasEndpoints) {\n state.compilationString += this._declareOutput(this.rgb, state) + ` = ${this.output.associatedVariableName}.xyz;\\r\\n`;\n }\n }\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n codeString += `${this._codeVariableName}.convertInputToLinearSpace = ${this.convertInputToLinearSpace};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.convertInputToLinearSpace = this.convertInputToLinearSpace;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n var _a;\n super._deserialize(serializationObject, scene, rootUrl);\n this.convertInputToLinearSpace = (_a = serializationObject.convertInputToLinearSpace) !== null && _a !== void 0 ? _a : true;\n }\n}\n__decorate([\n editableInPropertyPage(\"Convert input to linear space\", PropertyTypeForEdition.Boolean, \"ADVANCED\")\n], ImageProcessingBlock.prototype, \"convertInputToLinearSpace\", void 0);\nRegisterClass(\"BABYLON.ImageProcessingBlock\", ImageProcessingBlock);\n//# sourceMappingURL=imageProcessingBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../../nodeMaterialBlockConnectionPoint.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../../nodeMaterialConnectionPointCustomObject.js\";\nimport { NodeMaterialSystemValues } from \"../../Enums/nodeMaterialSystemValues.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\n/**\n * Block used to implement TBN matrix\n */\nexport class TBNBlock extends NodeMaterialBlock {\n /**\n * Create a new TBNBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment, true);\n this.registerInput(\"normal\", NodeMaterialBlockConnectionPointTypes.AutoDetect, false);\n this.normal.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color4 | NodeMaterialBlockConnectionPointTypes.Vector4 | NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerInput(\"tangent\", NodeMaterialBlockConnectionPointTypes.Vector4, false);\n this.registerInput(\"world\", NodeMaterialBlockConnectionPointTypes.Matrix, false);\n this.registerOutput(\"TBN\", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"TBN\", this, NodeMaterialConnectionPointDirection.Output, TBNBlock, \"TBNBlock\"));\n this.registerOutput(\"row0\", NodeMaterialBlockConnectionPointTypes.Vector3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"row1\", NodeMaterialBlockConnectionPointTypes.Vector3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"row2\", NodeMaterialBlockConnectionPointTypes.Vector3, NodeMaterialBlockTargets.Fragment);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"TBNBlock\";\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"tbnNormal\");\n state._excludeVariableName(\"tbnTangent\");\n state._excludeVariableName(\"tbnBitangent\");\n state._excludeVariableName(\"TBN\");\n }\n /**\n * Gets the normal input component\n */\n get normal() {\n return this._inputs[0];\n }\n /**\n * Gets the tangent input component\n */\n get tangent() {\n return this._inputs[1];\n }\n /**\n * Gets the world matrix input component\n */\n get world() {\n return this._inputs[2];\n }\n /**\n * Gets the TBN output component\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n get TBN() {\n return this._outputs[0];\n }\n /**\n * Gets the row0 of the output matrix\n */\n get row0() {\n return this._outputs[1];\n }\n /**\n * Gets the row1 of the output matrix\n */\n get row1() {\n return this._outputs[2];\n }\n /**\n * Gets the row2 of the output matrix\n */\n get row2() {\n return this._outputs[3];\n }\n get target() {\n return NodeMaterialBlockTargets.Fragment;\n }\n set target(value) { }\n autoConfigure(material) {\n if (!this.world.isConnected) {\n let worldInput = material.getInputBlockByPredicate((b) => b.isSystemValue && b.systemValue === NodeMaterialSystemValues.World);\n if (!worldInput) {\n worldInput = new InputBlock(\"world\");\n worldInput.setAsSystemValue(NodeMaterialSystemValues.World);\n }\n worldInput.output.connectTo(this.world);\n }\n if (!this.normal.isConnected) {\n let normalInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"normal\");\n if (!normalInput) {\n normalInput = new InputBlock(\"normal\");\n normalInput.setAsAttribute(\"normal\");\n }\n normalInput.output.connectTo(this.normal);\n }\n if (!this.tangent.isConnected) {\n let tangentInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"tangent\" && b.type === NodeMaterialBlockConnectionPointTypes.Vector4);\n if (!tangentInput) {\n tangentInput = new InputBlock(\"tangent\");\n tangentInput.setAsAttribute(\"tangent\");\n }\n tangentInput.output.connectTo(this.tangent);\n }\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n var _a, _b, _c, _d;\n const normal = this.normal;\n const tangent = this.tangent;\n let normalAvailable = normal.isConnected;\n if (((_a = normal.connectInputBlock) === null || _a === void 0 ? void 0 : _a.isAttribute) && !mesh.isVerticesDataPresent((_b = normal.connectInputBlock) === null || _b === void 0 ? void 0 : _b.name)) {\n normalAvailable = false;\n }\n let tangentAvailable = tangent.isConnected;\n if (((_c = tangent.connectInputBlock) === null || _c === void 0 ? void 0 : _c.isAttribute) && !mesh.isVerticesDataPresent((_d = tangent.connectInputBlock) === null || _d === void 0 ? void 0 : _d.name)) {\n tangentAvailable = false;\n }\n const useTBNBlock = normalAvailable && tangentAvailable;\n defines.setValue(\"TBNBLOCK\", useTBNBlock, true);\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const normal = this.normal;\n const tangent = this.tangent;\n const world = this.world;\n const TBN = this.TBN;\n const row0 = this.row0;\n const row1 = this.row1;\n const row2 = this.row2;\n // Fragment\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n state.compilationString += `\r\n // ${this.name}\r\n vec3 tbnNormal = normalize(${normal.associatedVariableName}).xyz;\r\n vec3 tbnTangent = normalize(${tangent.associatedVariableName}.xyz);\r\n vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${tangent.associatedVariableName}.w;\r\n mat3 ${TBN.associatedVariableName} = mat3(${world.associatedVariableName}) * mat3(tbnTangent, tbnBitangent, tbnNormal);\r\n `;\n if (row0.hasEndpoints) {\n state.compilationString +=\n this._declareOutput(row0, state) +\n ` = vec3(${TBN.associatedVariableName}[0][0], ${TBN.associatedVariableName}[0][1], ${TBN.associatedVariableName}[0][2]);\\r\\n`;\n }\n if (row1.hasEndpoints) {\n state.compilationString +=\n this._declareOutput(row1, state) + ` = vec3(${TBN.associatedVariableName}[1[0], ${TBN.associatedVariableName}[1][1], ${TBN.associatedVariableName}[1][2]);\\r\\n`;\n }\n if (row2.hasEndpoints) {\n state.compilationString +=\n this._declareOutput(row2, state) +\n ` = vec3(${TBN.associatedVariableName}[2][0], ${TBN.associatedVariableName}[2][1], ${TBN.associatedVariableName}[2][2]);\\r\\n`;\n }\n state.sharedData.blocksWithDefines.push(this);\n }\n return this;\n }\n}\nRegisterClass(\"BABYLON.TBNBlock\", TBNBlock);\n//# sourceMappingURL=TBNBlock.js.map","import { __decorate } from \"../../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../../nodeMaterialBlockConnectionPoint.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../../nodeMaterialDecorator.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../../nodeMaterialConnectionPointCustomObject.js\";\nimport { TBNBlock } from \"./TBNBlock.js\";\nimport \"../../../../Shaders/ShadersInclude/bumpFragmentMainFunctions.js\";\nimport \"../../../../Shaders/ShadersInclude/bumpFragmentFunctions.js\";\nimport \"../../../../Shaders/ShadersInclude/bumpFragment.js\";\n/**\n * Block used to perturb normals based on a normal map\n */\nexport class PerturbNormalBlock extends NodeMaterialBlock {\n /**\n * Create a new PerturbNormalBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this._tangentSpaceParameterName = \"\";\n this._tangentCorrectionFactorName = \"\";\n this._worldMatrixName = \"\";\n /** Gets or sets a boolean indicating that normal should be inverted on X axis */\n this.invertX = false;\n /** Gets or sets a boolean indicating that normal should be inverted on Y axis */\n this.invertY = false;\n /** Gets or sets a boolean indicating that parallax occlusion should be enabled */\n this.useParallaxOcclusion = false;\n /** Gets or sets a boolean indicating that sampling mode is in Object space */\n this.useObjectSpaceNormalMap = false;\n this._isUnique = true;\n // Vertex\n this.registerInput(\"worldPosition\", NodeMaterialBlockConnectionPointTypes.Vector4, false);\n this.registerInput(\"worldNormal\", NodeMaterialBlockConnectionPointTypes.Vector4, false);\n this.registerInput(\"worldTangent\", NodeMaterialBlockConnectionPointTypes.Vector4, true);\n this.registerInput(\"uv\", NodeMaterialBlockConnectionPointTypes.Vector2, false);\n this.registerInput(\"normalMapColor\", NodeMaterialBlockConnectionPointTypes.Color3, false);\n this.registerInput(\"strength\", NodeMaterialBlockConnectionPointTypes.Float, false);\n this.registerInput(\"viewDirection\", NodeMaterialBlockConnectionPointTypes.Vector3, true);\n this.registerInput(\"parallaxScale\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"parallaxHeight\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"TBN\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject(\"TBN\", this, NodeMaterialConnectionPointDirection.Input, TBNBlock, \"TBNBlock\"));\n this.registerInput(\"world\", NodeMaterialBlockConnectionPointTypes.Matrix, true);\n // Fragment\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerOutput(\"uvOffset\", NodeMaterialBlockConnectionPointTypes.Vector2);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"PerturbNormalBlock\";\n }\n /**\n * Gets the world position input component\n */\n get worldPosition() {\n return this._inputs[0];\n }\n /**\n * Gets the world normal input component\n */\n get worldNormal() {\n return this._inputs[1];\n }\n /**\n * Gets the world tangent input component\n */\n get worldTangent() {\n return this._inputs[2];\n }\n /**\n * Gets the uv input component\n */\n get uv() {\n return this._inputs[3];\n }\n /**\n * Gets the normal map color input component\n */\n get normalMapColor() {\n return this._inputs[4];\n }\n /**\n * Gets the strength input component\n */\n get strength() {\n return this._inputs[5];\n }\n /**\n * Gets the view direction input component\n */\n get viewDirection() {\n return this._inputs[6];\n }\n /**\n * Gets the parallax scale input component\n */\n get parallaxScale() {\n return this._inputs[7];\n }\n /**\n * Gets the parallax height input component\n */\n get parallaxHeight() {\n return this._inputs[8];\n }\n /**\n * Gets the TBN input component\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n get TBN() {\n return this._inputs[9];\n }\n /**\n * Gets the World input component\n */\n get world() {\n return this._inputs[10];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n /**\n * Gets the uv offset output component\n */\n get uvOffset() {\n return this._outputs[1];\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n const normalSamplerName = this.normalMapColor.connectedPoint._ownerBlock.samplerName;\n const useParallax = this.viewDirection.isConnected && ((this.useParallaxOcclusion && normalSamplerName) || (!this.useParallaxOcclusion && this.parallaxHeight.isConnected));\n defines.setValue(\"BUMP\", true);\n defines.setValue(\"PARALLAX\", useParallax, true);\n defines.setValue(\"PARALLAXOCCLUSION\", this.useParallaxOcclusion, true);\n defines.setValue(\"OBJECTSPACE_NORMALMAP\", this.useObjectSpaceNormalMap, true);\n }\n bind(effect, nodeMaterial, mesh) {\n if (nodeMaterial.getScene()._mirroredCameraPosition) {\n effect.setFloat2(this._tangentSpaceParameterName, this.invertX ? 1.0 : -1.0, this.invertY ? 1.0 : -1.0);\n }\n else {\n effect.setFloat2(this._tangentSpaceParameterName, this.invertX ? -1.0 : 1.0, this.invertY ? -1.0 : 1.0);\n }\n if (mesh) {\n effect.setFloat(this._tangentCorrectionFactorName, mesh.getWorldMatrix().determinant() < 0 ? -1 : 1);\n if (this.useObjectSpaceNormalMap && !this.world.isConnected) {\n // World default to the mesh world matrix\n effect.setMatrix(this._worldMatrixName, mesh.getWorldMatrix());\n }\n }\n }\n autoConfigure(material) {\n if (!this.uv.isConnected) {\n let uvInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"uv\");\n if (!uvInput) {\n uvInput = new InputBlock(\"uv\");\n uvInput.setAsAttribute();\n }\n uvInput.output.connectTo(this.uv);\n }\n if (!this.strength.isConnected) {\n const strengthInput = new InputBlock(\"strength\");\n strengthInput.value = 1.0;\n strengthInput.output.connectTo(this.strength);\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const comments = `//${this.name}`;\n const uv = this.uv;\n const worldPosition = this.worldPosition;\n const worldNormal = this.worldNormal;\n const worldTangent = this.worldTangent;\n state.sharedData.blocksWithDefines.push(this);\n state.sharedData.bindableBlocks.push(this);\n this._tangentSpaceParameterName = state._getFreeDefineName(\"tangentSpaceParameter\");\n state._emitUniformFromString(this._tangentSpaceParameterName, \"vec2\");\n this._tangentCorrectionFactorName = state._getFreeDefineName(\"tangentCorrectionFactor\");\n state._emitUniformFromString(this._tangentCorrectionFactorName, \"float\");\n this._worldMatrixName = state._getFreeDefineName(\"perturbNormalWorldMatrix\");\n state._emitUniformFromString(this._worldMatrixName, \"mat4\");\n let normalSamplerName = null;\n if (this.normalMapColor.connectedPoint) {\n normalSamplerName = this.normalMapColor.connectedPoint._ownerBlock.samplerName;\n }\n const useParallax = this.viewDirection.isConnected && ((this.useParallaxOcclusion && normalSamplerName) || (!this.useParallaxOcclusion && this.parallaxHeight.isConnected));\n const replaceForParallaxInfos = !this.parallaxScale.isConnectedToInputBlock\n ? \"0.05\"\n : this.parallaxScale.connectInputBlock.isConstant\n ? state._emitFloat(this.parallaxScale.connectInputBlock.value)\n : this.parallaxScale.associatedVariableName;\n const replaceForBumpInfos = this.strength.isConnectedToInputBlock && this.strength.connectInputBlock.isConstant\n ? `\\r\\n#if !defined(NORMALXYSCALE)\\r\\n1.0/\\r\\n#endif\\r\\n${state._emitFloat(this.strength.connectInputBlock.value)}`\n : `\\r\\n#if !defined(NORMALXYSCALE)\\r\\n1.0/\\r\\n#endif\\r\\n${this.strength.associatedVariableName}`;\n state._emitExtension(\"derivatives\", \"#extension GL_OES_standard_derivatives : enable\");\n const tangentReplaceString = { search: /defined\\(TANGENT\\)/g, replace: worldTangent.isConnected ? \"defined(TANGENT)\" : \"defined(IGNORE)\" };\n const tbnVarying = { search: /varying mat3 vTBN/g, replace: \"\" };\n const normalMatrixReplaceString = { search: /uniform mat4 normalMatrix;/g, replace: \"\" };\n const TBN = this.TBN;\n if (TBN.isConnected) {\n state.compilationString += `\r\n #ifdef TBNBLOCK\r\n mat3 vTBN = ${TBN.associatedVariableName};\r\n #endif\r\n `;\n }\n else if (worldTangent.isConnected) {\n state.compilationString += `vec3 tbnNormal = normalize(${worldNormal.associatedVariableName}.xyz);\\r\\n`;\n state.compilationString += `vec3 tbnTangent = normalize(${worldTangent.associatedVariableName}.xyz);\\r\\n`;\n state.compilationString += `vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};\\r\\n`;\n state.compilationString += `mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\\r\\n`;\n }\n state._emitFunctionFromInclude(\"bumpFragmentMainFunctions\", comments, {\n replaceStrings: [tangentReplaceString, tbnVarying, normalMatrixReplaceString],\n });\n state._emitFunctionFromInclude(\"bumpFragmentFunctions\", comments, {\n replaceStrings: [\n { search: /#include\\(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump\\)/g, replace: \"\" },\n { search: /uniform sampler2D bumpSampler;/g, replace: \"\" },\n {\n search: /vec2 parallaxOcclusion\\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\\)/g,\n replace: \"#define inline\\r\\nvec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale, sampler2D bumpSampler)\",\n },\n { search: /vec2 parallaxOffset\\(vec3 viewDir,float heightScale\\)/g, replace: \"vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)\" },\n { search: /texture2D\\(bumpSampler,vBumpUV\\)\\.w/g, replace: \"height_\" },\n ],\n });\n const uvForPerturbNormal = !useParallax || !normalSamplerName ? this.normalMapColor.associatedVariableName : `texture2D(${normalSamplerName}, ${uv.associatedVariableName} + uvOffset).xyz`;\n state.compilationString += this._declareOutput(this.output, state) + \" = vec4(0.);\\r\\n\";\n state.compilationString += state._emitCodeFromInclude(\"bumpFragment\", comments, {\n replaceStrings: [\n { search: /texture2D\\(bumpSampler,vBumpUV\\)/g, replace: `${uvForPerturbNormal}` },\n {\n search: /#define CUSTOM_FRAGMENT_BUMP_FRAGMENT/g,\n replace: `mat4 normalMatrix = toNormalMatrix(${this.world.isConnected ? this.world.associatedVariableName : this._worldMatrixName});`,\n },\n { search: /perturbNormal\\(TBN,texture2D\\(bumpSampler,vBumpUV\\+uvOffset\\).xyz,vBumpInfos.y\\)/g, replace: `perturbNormal(TBN, ${uvForPerturbNormal}, vBumpInfos.y)` },\n {\n search: /parallaxOcclusion\\(invTBN\\*-viewDirectionW,invTBN\\*normalW,vBumpUV,vBumpInfos.z\\)/g,\n replace: `parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ${useParallax && this.useParallaxOcclusion ? normalSamplerName : \"bumpSampler\"})`,\n },\n {\n search: /parallaxOffset\\(invTBN\\*viewDirectionW,vBumpInfos\\.z\\)/g,\n replace: `parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ${useParallax ? this.parallaxHeight.associatedVariableName : \"0.\"})`,\n },\n { search: /vTangentSpaceParams/g, replace: this._tangentSpaceParameterName },\n { search: /vBumpInfos.y/g, replace: replaceForBumpInfos },\n { search: /vBumpInfos.z/g, replace: replaceForParallaxInfos },\n { search: /vBumpUV/g, replace: uv.associatedVariableName },\n { search: /vPositionW/g, replace: worldPosition.associatedVariableName + \".xyz\" },\n { search: /normalW=/g, replace: this.output.associatedVariableName + \".xyz = \" },\n { search: /mat3\\(normalMatrix\\)\\*normalW/g, replace: \"mat3(normalMatrix) * \" + this.output.associatedVariableName + \".xyz\" },\n { search: /normalW/g, replace: worldNormal.associatedVariableName + \".xyz\" },\n { search: /viewDirectionW/g, replace: useParallax ? this.viewDirection.associatedVariableName : \"vec3(0.)\" },\n tangentReplaceString,\n ],\n });\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.invertX = ${this.invertX};\\r\\n`;\n codeString += `${this._codeVariableName}.invertY = ${this.invertY};\\r\\n`;\n codeString += `${this._codeVariableName}.useParallaxOcclusion = ${this.useParallaxOcclusion};\\r\\n`;\n codeString += `${this._codeVariableName}.useObjectSpaceNormalMap = ${this.useObjectSpaceNormalMap};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.invertX = this.invertX;\n serializationObject.invertY = this.invertY;\n serializationObject.useParallaxOcclusion = this.useParallaxOcclusion;\n serializationObject.useObjectSpaceNormalMap = this.useObjectSpaceNormalMap;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.invertX = serializationObject.invertX;\n this.invertY = serializationObject.invertY;\n this.useParallaxOcclusion = !!serializationObject.useParallaxOcclusion;\n this.useObjectSpaceNormalMap = !!serializationObject.useObjectSpaceNormalMap;\n }\n}\n__decorate([\n editableInPropertyPage(\"Invert X axis\", PropertyTypeForEdition.Boolean, \"PROPERTIES\", { notifiers: { update: false } })\n], PerturbNormalBlock.prototype, \"invertX\", void 0);\n__decorate([\n editableInPropertyPage(\"Invert Y axis\", PropertyTypeForEdition.Boolean, \"PROPERTIES\", { notifiers: { update: false } })\n], PerturbNormalBlock.prototype, \"invertY\", void 0);\n__decorate([\n editableInPropertyPage(\"Use parallax occlusion\", PropertyTypeForEdition.Boolean)\n], PerturbNormalBlock.prototype, \"useParallaxOcclusion\", void 0);\n__decorate([\n editableInPropertyPage(\"Object Space Mode\", PropertyTypeForEdition.Boolean, \"PROPERTIES\", { notifiers: { update: false } })\n], PerturbNormalBlock.prototype, \"useObjectSpaceNormalMap\", void 0);\nRegisterClass(\"BABYLON.PerturbNormalBlock\", PerturbNormalBlock);\n//# sourceMappingURL=perturbNormalBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\n/**\n * Block used to discard a pixel if a value is smaller than a cutoff\n */\nexport class DiscardBlock extends NodeMaterialBlock {\n /**\n * Create a new DiscardBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment, true);\n this.registerInput(\"value\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"cutoff\", NodeMaterialBlockConnectionPointTypes.Float, true);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"DiscardBlock\";\n }\n /**\n * Gets the color input component\n */\n get value() {\n return this._inputs[0];\n }\n /**\n * Gets the cutoff input component\n */\n get cutoff() {\n return this._inputs[1];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n state.sharedData.hints.needAlphaTesting = true;\n if (!this.cutoff.isConnected || !this.value.isConnected) {\n return;\n }\n state.compilationString += `if (${this.value.associatedVariableName} < ${this.cutoff.associatedVariableName}) discard;\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.DiscardBlock\", DiscardBlock);\n//# sourceMappingURL=discardBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\n/**\n * Block used to test if the fragment shader is front facing\n */\nexport class FrontFacingBlock extends NodeMaterialBlock {\n /**\n * Creates a new FrontFacingBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"FrontFacingBlock\";\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (state.target === NodeMaterialBlockTargets.Vertex) {\n throw \"FrontFacingBlock must only be used in a fragment shader\";\n }\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = gl_FrontFacing ? 1.0 : 0.0;\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.FrontFacingBlock\", FrontFacingBlock);\n//# sourceMappingURL=frontFacingBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\n/**\n * Block used to get the derivative value on x and y of a given input\n */\nexport class DerivativeBlock extends NodeMaterialBlock {\n /**\n * Create a new DerivativeBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.AutoDetect, false);\n this.registerOutput(\"dx\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this.registerOutput(\"dy\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._outputs[1]._typeConnectionSource = this._inputs[0];\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"DerivativeBlock\";\n }\n /**\n * Gets the input component\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the derivative output on x\n */\n get dx() {\n return this._outputs[0];\n }\n /**\n * Gets the derivative output on y\n */\n get dy() {\n return this._outputs[1];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const dx = this._outputs[0];\n const dy = this._outputs[1];\n state._emitExtension(\"derivatives\", \"#extension GL_OES_standard_derivatives : enable\");\n if (dx.hasEndpoints) {\n state.compilationString += this._declareOutput(dx, state) + ` = dFdx(${this.input.associatedVariableName});\\r\\n`;\n }\n if (dy.hasEndpoints) {\n state.compilationString += this._declareOutput(dy, state) + ` = dFdy(${this.input.associatedVariableName});\\r\\n`;\n }\n return this;\n }\n}\nRegisterClass(\"BABYLON.DerivativeBlock\", DerivativeBlock);\n//# sourceMappingURL=derivativeBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\n/**\n * Block used to make gl_FragCoord available\n */\nexport class FragCoordBlock extends NodeMaterialBlock {\n /**\n * Creates a new FragCoordBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"xy\", NodeMaterialBlockConnectionPointTypes.Vector2, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"xyz\", NodeMaterialBlockConnectionPointTypes.Vector3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"xyzw\", NodeMaterialBlockConnectionPointTypes.Vector4, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"x\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"y\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"z\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"w\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"FragCoordBlock\";\n }\n /**\n * Gets the xy component\n */\n get xy() {\n return this._outputs[0];\n }\n /**\n * Gets the xyz component\n */\n get xyz() {\n return this._outputs[1];\n }\n /**\n * Gets the xyzw component\n */\n get xyzw() {\n return this._outputs[2];\n }\n /**\n * Gets the x component\n */\n get x() {\n return this._outputs[3];\n }\n /**\n * Gets the y component\n */\n get y() {\n return this._outputs[4];\n }\n /**\n * Gets the z component\n */\n get z() {\n return this._outputs[5];\n }\n /**\n * Gets the w component\n */\n get output() {\n return this._outputs[6];\n }\n // eslint-disable-next-line @typescript-eslint/naming-convention\n writeOutputs(state) {\n let code = \"\";\n for (const output of this._outputs) {\n if (output.hasEndpoints) {\n code += `${this._declareOutput(output, state)} = gl_FragCoord.${output.name};\\r\\n`;\n }\n }\n return code;\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (state.target === NodeMaterialBlockTargets.Vertex) {\n throw \"FragCoordBlock must only be used in a fragment shader\";\n }\n state.compilationString += this.writeOutputs(state);\n return this;\n }\n}\nRegisterClass(\"BABYLON.FragCoordBlock\", FragCoordBlock);\n//# sourceMappingURL=fragCoordBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\n/**\n * Block used to get the screen sizes\n */\nexport class ScreenSizeBlock extends NodeMaterialBlock {\n /**\n * Creates a new ScreenSizeBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"xy\", NodeMaterialBlockConnectionPointTypes.Vector2, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"x\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"y\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ScreenSizeBlock\";\n }\n /**\n * Gets the xy component\n */\n get xy() {\n return this._outputs[0];\n }\n /**\n * Gets the x component\n */\n get x() {\n return this._outputs[1];\n }\n /**\n * Gets the y component\n */\n get y() {\n return this._outputs[2];\n }\n bind(effect) {\n const engine = this._scene.getEngine();\n effect.setFloat2(this._varName, engine.getRenderWidth(), engine.getRenderHeight());\n }\n // eslint-disable-next-line @typescript-eslint/naming-convention\n writeOutputs(state, varName) {\n let code = \"\";\n for (const output of this._outputs) {\n if (output.hasEndpoints) {\n code += `${this._declareOutput(output, state)} = ${varName}.${output.name};\\r\\n`;\n }\n }\n return code;\n }\n _buildBlock(state) {\n super._buildBlock(state);\n this._scene = state.sharedData.scene;\n if (state.target === NodeMaterialBlockTargets.Vertex) {\n throw \"ScreenSizeBlock must only be used in a fragment shader\";\n }\n state.sharedData.bindableBlocks.push(this);\n this._varName = state._getFreeVariableName(\"screenSize\");\n state._emitUniformFromString(this._varName, \"vec2\");\n state.compilationString += this.writeOutputs(state, this._varName);\n return this;\n }\n}\nRegisterClass(\"BABYLON.ScreenSizeBlock\", ScreenSizeBlock);\n//# sourceMappingURL=screenSizeBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { NodeMaterialSystemValues } from \"../../Enums/nodeMaterialSystemValues.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\n/**\n * Block used to transform a vector3 or a vector4 into screen space\n */\nexport class ScreenSpaceBlock extends NodeMaterialBlock {\n /**\n * Creates a new ScreenSpaceBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"vector\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"worldViewProjection\", NodeMaterialBlockConnectionPointTypes.Matrix);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Vector2);\n this.registerOutput(\"x\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"y\", NodeMaterialBlockConnectionPointTypes.Float);\n this.inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ScreenSpaceBlock\";\n }\n /**\n * Gets the vector input\n */\n get vector() {\n return this._inputs[0];\n }\n /**\n * Gets the worldViewProjection transform input\n */\n get worldViewProjection() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n /**\n * Gets the x output component\n */\n get x() {\n return this._outputs[1];\n }\n /**\n * Gets the y output component\n */\n get y() {\n return this._outputs[2];\n }\n autoConfigure(material) {\n if (!this.worldViewProjection.isConnected) {\n let worldViewProjectionInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.WorldViewProjection);\n if (!worldViewProjectionInput) {\n worldViewProjectionInput = new InputBlock(\"worldViewProjection\");\n worldViewProjectionInput.setAsSystemValue(NodeMaterialSystemValues.WorldViewProjection);\n }\n worldViewProjectionInput.output.connectTo(this.worldViewProjection);\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const vector = this.vector;\n const worldViewProjection = this.worldViewProjection;\n if (!vector.connectedPoint) {\n return;\n }\n const worldViewProjectionName = worldViewProjection.associatedVariableName;\n const tempVariableName = state._getFreeVariableName(\"screenSpaceTemp\");\n switch (vector.connectedPoint.type) {\n case NodeMaterialBlockConnectionPointTypes.Vector3:\n state.compilationString += `vec4 ${tempVariableName} = ${worldViewProjectionName} * vec4(${vector.associatedVariableName}, 1.0);\\r\\n`;\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector4:\n state.compilationString += `vec4 ${tempVariableName} = ${worldViewProjectionName} * ${vector.associatedVariableName};\\r\\n`;\n break;\n }\n state.compilationString += `${tempVariableName}.xy /= ${tempVariableName}.w;`;\n state.compilationString += `${tempVariableName}.xy = ${tempVariableName}.xy * 0.5 + vec2(0.5, 0.5);`;\n if (this.output.hasEndpoints) {\n state.compilationString += this._declareOutput(this.output, state) + ` = ${tempVariableName}.xy;\\r\\n`;\n }\n if (this.x.hasEndpoints) {\n state.compilationString += this._declareOutput(this.x, state) + ` = ${tempVariableName}.x;\\r\\n`;\n }\n if (this.y.hasEndpoints) {\n state.compilationString += this._declareOutput(this.y, state) + ` = ${tempVariableName}.y;\\r\\n`;\n }\n return this;\n }\n}\nRegisterClass(\"BABYLON.ScreenSpaceBlock\", ScreenSpaceBlock);\n//# sourceMappingURL=screenSpaceBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { Vector2 } from \"../../../../Maths/math.vector.js\";\n/**\n * Block used to generate a twirl\n */\nexport class TwirlBlock extends NodeMaterialBlock {\n /**\n * Creates a new TwirlBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.Vector2);\n this.registerInput(\"strength\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerInput(\"center\", NodeMaterialBlockConnectionPointTypes.Vector2);\n this.registerInput(\"offset\", NodeMaterialBlockConnectionPointTypes.Vector2);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Vector2);\n this.registerOutput(\"x\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"y\", NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"TwirlBlock\";\n }\n /**\n * Gets the input component\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the strength component\n */\n get strength() {\n return this._inputs[1];\n }\n /**\n * Gets the center component\n */\n get center() {\n return this._inputs[2];\n }\n /**\n * Gets the offset component\n */\n get offset() {\n return this._inputs[3];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n /**\n * Gets the x output component\n */\n get x() {\n return this._outputs[1];\n }\n /**\n * Gets the y output component\n */\n get y() {\n return this._outputs[2];\n }\n autoConfigure() {\n if (!this.center.isConnected) {\n const centerInput = new InputBlock(\"center\");\n centerInput.value = new Vector2(0.5, 0.5);\n centerInput.output.connectTo(this.center);\n }\n if (!this.strength.isConnected) {\n const strengthInput = new InputBlock(\"strength\");\n strengthInput.value = 1.0;\n strengthInput.output.connectTo(this.strength);\n }\n if (!this.offset.isConnected) {\n const offsetInput = new InputBlock(\"offset\");\n offsetInput.value = new Vector2(0, 0);\n offsetInput.output.connectTo(this.offset);\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const tempDelta = state._getFreeVariableName(\"delta\");\n const tempAngle = state._getFreeVariableName(\"angle\");\n const tempX = state._getFreeVariableName(\"x\");\n const tempY = state._getFreeVariableName(\"y\");\n const tempResult = state._getFreeVariableName(\"result\");\n state.compilationString += `\r\n vec2 ${tempDelta} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName};\r\n float ${tempAngle} = ${this.strength.associatedVariableName} * length(${tempDelta});\r\n float ${tempX} = cos(${tempAngle}) * ${tempDelta}.x - sin(${tempAngle}) * ${tempDelta}.y;\r\n float ${tempY} = sin(${tempAngle}) * ${tempDelta}.x + cos(${tempAngle}) * ${tempDelta}.y;\r\n vec2 ${tempResult} = vec2(${tempX} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${tempY} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y);\r\n `;\n if (this.output.hasEndpoints) {\n state.compilationString += this._declareOutput(this.output, state) + ` = ${tempResult};\\r\\n`;\n }\n if (this.x.hasEndpoints) {\n state.compilationString += this._declareOutput(this.x, state) + ` = ${tempResult}.x;\\r\\n`;\n }\n if (this.y.hasEndpoints) {\n state.compilationString += this._declareOutput(this.y, state) + ` = ${tempResult}.y;\\r\\n`;\n }\n return this;\n }\n}\nRegisterClass(\"BABYLON.TwirlBlock\", TwirlBlock);\n//# sourceMappingURL=twirlBlock.js.map","import { __decorate } from \"../../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../../nodeMaterialDecorator.js\";\n/**\n * Block used to convert a height vector to a normal\n */\nexport class HeightToNormalBlock extends NodeMaterialBlock {\n /**\n * Creates a new HeightToNormalBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n /**\n * Defines if the output should be generated in world or tangent space.\n * Note that in tangent space the result is also scaled by 0.5 and offsetted by 0.5 so that it can directly be used as a PerturbNormal.normalMapColor input\n */\n this.generateInWorldSpace = false;\n /**\n * Defines that the worldNormal input will be normalized by the HeightToNormal block before being used\n */\n this.automaticNormalizationNormal = true;\n /**\n * Defines that the worldTangent input will be normalized by the HeightToNormal block before being used\n */\n this.automaticNormalizationTangent = true;\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerInput(\"worldPosition\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerInput(\"worldNormal\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerInput(\"worldTangent\", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerOutput(\"xyz\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this._inputs[3].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"HeightToNormalBlock\";\n }\n /**\n * Gets the input component\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the position component\n */\n get worldPosition() {\n return this._inputs[1];\n }\n /**\n * Gets the normal component\n */\n get worldNormal() {\n return this._inputs[2];\n }\n /**\n * Gets the tangent component\n */\n get worldTangent() {\n return this._inputs[3];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n /**\n * Gets the xyz component\n */\n get xyz() {\n return this._outputs[1];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n if (!this.generateInWorldSpace && !this.worldTangent.isConnected) {\n console.error(`You must connect the 'worldTangent' input of the ${this.name} block!`);\n }\n const startCode = this.generateInWorldSpace\n ? \"\"\n : `\r\n vec3 biTangent = cross(normal, tangent);\r\n mat3 TBN = mat3(tangent, biTangent, normal);\r\n `;\n const endCode = this.generateInWorldSpace\n ? \"\"\n : `\r\n result = TBN * result;\r\n result = result * vec3(0.5) + vec3(0.5);\r\n `;\n const heightToNormal = `\r\n vec4 heightToNormal(in float height, in vec3 position, in vec3 tangent, in vec3 normal) {\r\n ${startCode}\r\n ${this.automaticNormalizationTangent ? \"tangent = normalize(tangent);\" : \"\"}\r\n ${this.automaticNormalizationNormal ? \"normal = normalize(normal);\" : \"\"}\r\n vec3 worlddX = dFdx(position);\r\n vec3 worlddY = dFdy(position);\r\n vec3 crossX = cross(normal, worlddX);\r\n vec3 crossY = cross(normal, worlddY);\r\n float d = abs(dot(crossY, worlddX));\r\n vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d));\r\n inToNormal.y *= -1.0;\r\n vec3 result = normalize((d * normal) - inToNormal);\r\n ${endCode}\r\n return vec4(result, 0.);\r\n }`;\n state._emitExtension(\"derivatives\", \"#extension GL_OES_standard_derivatives : enable\");\n state._emitFunction(\"heightToNormal\", heightToNormal, \"// heightToNormal\");\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = heightToNormal(${this.input.associatedVariableName}, ${this.worldPosition.associatedVariableName}, ${this.worldTangent.isConnected ? this.worldTangent.associatedVariableName : \"vec3(0.)\"}.xyz, ${this.worldNormal.associatedVariableName});\\r\\n`;\n if (this.xyz.hasEndpoints) {\n state.compilationString += this._declareOutput(this.xyz, state) + ` = ${this.output.associatedVariableName}.xyz;\\r\\n`;\n }\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n codeString += `${this._codeVariableName}.generateInWorldSpace = ${this.generateInWorldSpace};\\r\\n`;\n codeString += `${this._codeVariableName}.automaticNormalizationNormal = ${this.automaticNormalizationNormal};\\r\\n`;\n codeString += `${this._codeVariableName}.automaticNormalizationTangent = ${this.automaticNormalizationTangent};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.generateInWorldSpace = this.generateInWorldSpace;\n serializationObject.automaticNormalizationNormal = this.automaticNormalizationNormal;\n serializationObject.automaticNormalizationTangent = this.automaticNormalizationTangent;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.generateInWorldSpace = serializationObject.generateInWorldSpace;\n this.automaticNormalizationNormal = serializationObject.automaticNormalizationNormal;\n this.automaticNormalizationTangent = serializationObject.automaticNormalizationTangent;\n }\n}\n__decorate([\n editableInPropertyPage(\"Generate in world space instead of tangent space\", PropertyTypeForEdition.Boolean, \"PROPERTIES\", { notifiers: { update: true } })\n], HeightToNormalBlock.prototype, \"generateInWorldSpace\", void 0);\n__decorate([\n editableInPropertyPage(\"Force normalization for the worldNormal input\", PropertyTypeForEdition.Boolean, \"PROPERTIES\", { notifiers: { update: true } })\n], HeightToNormalBlock.prototype, \"automaticNormalizationNormal\", void 0);\n__decorate([\n editableInPropertyPage(\"Force normalization for the worldTangent input\", PropertyTypeForEdition.Boolean, \"PROPERTIES\", { notifiers: { update: true } })\n], HeightToNormalBlock.prototype, \"automaticNormalizationTangent\", void 0);\nRegisterClass(\"BABYLON.HeightToNormalBlock\", HeightToNormalBlock);\n//# sourceMappingURL=heightToNormalBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\n/**\n * Block used to write the fragment depth\n */\nexport class FragDepthBlock extends NodeMaterialBlock {\n /**\n * Create a new FragDepthBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment, true);\n this.registerInput(\"depth\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"worldPos\", NodeMaterialBlockConnectionPointTypes.Vector4, true);\n this.registerInput(\"viewProjection\", NodeMaterialBlockConnectionPointTypes.Matrix, true);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"FragDepthBlock\";\n }\n /**\n * Gets the depth input component\n */\n get depth() {\n return this._inputs[0];\n }\n /**\n * Gets the worldPos input component\n */\n get worldPos() {\n return this._inputs[1];\n }\n /**\n * Gets the viewProjection input component\n */\n get viewProjection() {\n return this._inputs[2];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (this.depth.isConnected) {\n state.compilationString += `gl_FragDepth = ${this.depth.associatedVariableName};\\r\\n`;\n }\n else if (this.worldPos.isConnected && this.viewProjection.isConnected) {\n state.compilationString += `\r\n vec4 p = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName};\r\n float v = p.z / p.w;\r\n #ifndef IS_NDC_HALF_ZRANGE\r\n v = v * 0.5 + 0.5;\r\n #endif\r\n gl_FragDepth = v;\r\n \r\n `;\n }\n else {\n console.warn(\"FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!\");\n }\n return this;\n }\n}\nRegisterClass(\"BABYLON.FragDepthBlock\", FragDepthBlock);\n//# sourceMappingURL=fragDepthBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\n/**\n * Block used to output the depth to a shadow map\n */\nexport class ShadowMapBlock extends NodeMaterialBlock {\n /**\n * Create a new ShadowMapBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"worldPosition\", NodeMaterialBlockConnectionPointTypes.Vector4, false);\n this.registerInput(\"viewProjection\", NodeMaterialBlockConnectionPointTypes.Matrix, false);\n this.registerInput(\"worldNormal\", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);\n this.registerOutput(\"depth\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.worldNormal.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ShadowMapBlock\";\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"vPositionWSM\");\n state._excludeVariableName(\"lightDataSM\");\n state._excludeVariableName(\"biasAndScaleSM\");\n state._excludeVariableName(\"depthValuesSM\");\n state._excludeVariableName(\"clipPos\");\n state._excludeVariableName(\"worldPos\");\n state._excludeVariableName(\"zSM\");\n }\n /**\n * Gets the world position input component\n */\n get worldPosition() {\n return this._inputs[0];\n }\n /**\n * Gets the view x projection input component\n */\n get viewProjection() {\n return this._inputs[1];\n }\n /**\n * Gets the world normal input component\n */\n get worldNormal() {\n return this._inputs[2];\n }\n /**\n * Gets the depth output component\n */\n get depth() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const comments = `//${this.name}`;\n state._emitUniformFromString(\"biasAndScaleSM\", \"vec3\");\n state._emitUniformFromString(\"lightDataSM\", \"vec3\");\n state._emitUniformFromString(\"depthValuesSM\", \"vec2\");\n state._emitFunctionFromInclude(\"packingFunctions\", comments);\n state.compilationString += `vec4 worldPos = ${this.worldPosition.associatedVariableName};\\r\\n`;\n state.compilationString += `vec3 vPositionWSM;\\r\\n`;\n state.compilationString += `float vDepthMetricSM = 0.0;\\r\\n`;\n state.compilationString += `float zSM;\\r\\n`;\n if (this.worldNormal.isConnected) {\n state.compilationString += `vec3 vNormalW = ${this.worldNormal.associatedVariableName}.xyz;\\r\\n`;\n state.compilationString += state._emitCodeFromInclude(\"shadowMapVertexNormalBias\", comments);\n }\n state.compilationString += `vec4 clipPos = ${this.viewProjection.associatedVariableName} * worldPos;\\r\\n`;\n state.compilationString += state._emitCodeFromInclude(\"shadowMapVertexMetric\", comments, {\n replaceStrings: [\n {\n search: /gl_Position/g,\n replace: \"clipPos\",\n },\n ],\n });\n state.compilationString += state._emitCodeFromInclude(\"shadowMapFragment\", comments, {\n replaceStrings: [\n {\n search: /return;/g,\n replace: \"\",\n },\n ],\n });\n state.compilationString += `\r\n #if SM_DEPTHTEXTURE == 1\r\n #ifdef IS_NDC_HALF_ZRANGE\r\n gl_FragDepth = (clipPos.z / clipPos.w);\r\n #else\r\n gl_FragDepth = (clipPos.z / clipPos.w) * 0.5 + 0.5;\r\n #endif\r\n #endif\r\n `;\n state.compilationString += `${this._declareOutput(this.depth, state)} = vec3(depthSM, 1., 1.);\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.ShadowMapBlock\", ShadowMapBlock);\n//# sourceMappingURL=shadowMapBlock.js.map","export * from \"./fragmentOutputBlock.js\";\nexport * from \"./imageProcessingBlock.js\";\nexport * from \"./perturbNormalBlock.js\";\nexport * from \"./discardBlock.js\";\nexport * from \"./frontFacingBlock.js\";\nexport * from \"./derivativeBlock.js\";\nexport * from \"./fragCoordBlock.js\";\nexport * from \"./screenSizeBlock.js\";\nexport * from \"./screenSpaceBlock.js\";\nexport * from \"./twirlBlock.js\";\nexport * from \"./TBNBlock.js\";\nexport * from \"./heightToNormalBlock.js\";\nexport * from \"./fragDepthBlock.js\";\nexport * from \"./shadowMapBlock.js\";\n//# sourceMappingURL=index.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialSystemValues } from \"../../Enums/nodeMaterialSystemValues.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { MaterialHelper } from \"../../../materialHelper.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport \"../../../../Shaders/ShadersInclude/fogFragmentDeclaration.js\";\n/**\n * Block used to add support for scene fog\n */\nexport class FogBlock extends NodeMaterialBlock {\n /**\n * Create a new FogBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.VertexAndFragment, false);\n // Vertex\n this.registerInput(\"worldPosition\", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex);\n this.registerInput(\"view\", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Vertex);\n // Fragment\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"fogColor\", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.input.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Color4);\n this.fogColor.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Color4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"FogBlock\";\n }\n /**\n * Gets the world position input component\n */\n get worldPosition() {\n return this._inputs[0];\n }\n /**\n * Gets the view input component\n */\n get view() {\n return this._inputs[1];\n }\n /**\n * Gets the color input component\n */\n get input() {\n return this._inputs[2];\n }\n /**\n * Gets the fog color input component\n */\n get fogColor() {\n return this._inputs[3];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n autoConfigure(material) {\n if (!this.view.isConnected) {\n let viewInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.View);\n if (!viewInput) {\n viewInput = new InputBlock(\"view\");\n viewInput.setAsSystemValue(NodeMaterialSystemValues.View);\n }\n viewInput.output.connectTo(this.view);\n }\n if (!this.fogColor.isConnected) {\n let fogColorInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.FogColor);\n if (!fogColorInput) {\n fogColorInput = new InputBlock(\"fogColor\", undefined, NodeMaterialBlockConnectionPointTypes.Color3);\n fogColorInput.setAsSystemValue(NodeMaterialSystemValues.FogColor);\n }\n fogColorInput.output.connectTo(this.fogColor);\n }\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n const scene = mesh.getScene();\n defines.setValue(\"FOG\", nodeMaterial.fogEnabled && MaterialHelper.GetFogState(mesh, scene));\n }\n bind(effect, nodeMaterial, mesh) {\n if (!mesh) {\n return;\n }\n const scene = mesh.getScene();\n effect.setFloat4(this._fogParameters, scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n state.sharedData.blocksWithDefines.push(this);\n state.sharedData.bindableBlocks.push(this);\n state._emitFunctionFromInclude(\"fogFragmentDeclaration\", `//${this.name}`, {\n removeUniforms: true,\n removeVaryings: true,\n removeIfDef: false,\n replaceStrings: [{ search: /float CalcFogFactor\\(\\)/, replace: \"float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)\" }],\n });\n const tempFogVariablename = state._getFreeVariableName(\"fog\");\n const color = this.input;\n const fogColor = this.fogColor;\n this._fogParameters = state._getFreeVariableName(\"fogParameters\");\n const output = this._outputs[0];\n state._emitUniformFromString(this._fogParameters, \"vec4\");\n state.compilationString += `#ifdef FOG\\r\\n`;\n state.compilationString += `float ${tempFogVariablename} = CalcFogFactor(${this._fogDistanceName}, ${this._fogParameters});\\r\\n`;\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = ${tempFogVariablename} * ${color.associatedVariableName}.rgb + (1.0 - ${tempFogVariablename}) * ${fogColor.associatedVariableName}.rgb;\\r\\n`;\n state.compilationString += `#else\\r\\n${this._declareOutput(output, state)} = ${color.associatedVariableName}.rgb;\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n }\n else {\n const worldPos = this.worldPosition;\n const view = this.view;\n this._fogDistanceName = state._getFreeVariableName(\"vFogDistance\");\n state._emitVaryingFromString(this._fogDistanceName, \"vec3\");\n state.compilationString += `${this._fogDistanceName} = (${view.associatedVariableName} * ${worldPos.associatedVariableName}).xyz;\\r\\n`;\n }\n return this;\n }\n}\nRegisterClass(\"BABYLON.FogBlock\", FogBlock);\n//# sourceMappingURL=fogBlock.js.map","import { __decorate } from \"../../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { MaterialHelper } from \"../../../materialHelper.js\";\nimport { NodeMaterialSystemValues } from \"../../Enums/nodeMaterialSystemValues.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../../nodeMaterialDecorator.js\";\nimport \"../../../../Shaders/ShadersInclude/lightFragmentDeclaration.js\";\nimport \"../../../../Shaders/ShadersInclude/lightVxFragmentDeclaration.js\";\nimport \"../../../../Shaders/ShadersInclude/lightUboDeclaration.js\";\nimport \"../../../../Shaders/ShadersInclude/lightVxUboDeclaration.js\";\nimport \"../../../../Shaders/ShadersInclude/lightFragment.js\";\nimport \"../../../../Shaders/ShadersInclude/helperFunctions.js\";\nimport \"../../../../Shaders/ShadersInclude/lightsFragmentFunctions.js\";\nimport \"../../../../Shaders/ShadersInclude/shadowsFragmentFunctions.js\";\nimport \"../../../../Shaders/ShadersInclude/shadowsVertex.js\";\n/**\n * Block used to add light in the fragment shader\n */\nexport class LightBlock extends NodeMaterialBlock {\n static _OnGenerateOnlyFragmentCodeChanged(block, _propertyName) {\n const that = block;\n if (that.worldPosition.isConnected) {\n that.generateOnlyFragmentCode = !that.generateOnlyFragmentCode;\n console.error(\"The worldPosition input must not be connected to be able to switch!\");\n return false;\n }\n that._setTarget();\n return true;\n }\n _setTarget() {\n this._setInitialTarget(this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.VertexAndFragment);\n this.getInputByName(\"worldPosition\").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex;\n }\n /**\n * Create a new LightBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.VertexAndFragment);\n this._lightId = 0;\n /** Indicates that no code should be generated in the vertex shader. Can be useful in some specific circumstances (like when doing ray marching for eg) */\n this.generateOnlyFragmentCode = false;\n this._isUnique = true;\n this.registerInput(\"worldPosition\", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex);\n this.registerInput(\"worldNormal\", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"cameraPosition\", NodeMaterialBlockConnectionPointTypes.Vector3, false, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"glossiness\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"glossPower\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"diffuseColor\", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"specularColor\", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"view\", NodeMaterialBlockConnectionPointTypes.Matrix, true);\n this.registerOutput(\"diffuseOutput\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"specularOutput\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"shadow\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"LightBlock\";\n }\n /**\n * Gets the world position input component\n */\n get worldPosition() {\n return this._inputs[0];\n }\n /**\n * Gets the world normal input component\n */\n get worldNormal() {\n return this._inputs[1];\n }\n /**\n * Gets the camera (or eye) position component\n */\n get cameraPosition() {\n return this._inputs[2];\n }\n /**\n * Gets the glossiness component\n */\n get glossiness() {\n return this._inputs[3];\n }\n /**\n * Gets the glossiness power component\n */\n get glossPower() {\n return this._inputs[4];\n }\n /**\n * Gets the diffuse color component\n */\n get diffuseColor() {\n return this._inputs[5];\n }\n /**\n * Gets the specular color component\n */\n get specularColor() {\n return this._inputs[6];\n }\n /**\n * Gets the view matrix component\n */\n get view() {\n return this._inputs[7];\n }\n /**\n * Gets the diffuse output component\n */\n get diffuseOutput() {\n return this._outputs[0];\n }\n /**\n * Gets the specular output component\n */\n get specularOutput() {\n return this._outputs[1];\n }\n /**\n * Gets the shadow output component\n */\n get shadow() {\n return this._outputs[2];\n }\n autoConfigure(material) {\n if (!this.cameraPosition.isConnected) {\n let cameraPositionInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.CameraPosition);\n if (!cameraPositionInput) {\n cameraPositionInput = new InputBlock(\"cameraPosition\");\n cameraPositionInput.setAsSystemValue(NodeMaterialSystemValues.CameraPosition);\n }\n cameraPositionInput.output.connectTo(this.cameraPosition);\n }\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n if (!defines._areLightsDirty) {\n return;\n }\n const scene = mesh.getScene();\n if (!this.light) {\n MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, nodeMaterial.maxSimultaneousLights);\n }\n else {\n const state = {\n needNormals: false,\n needRebuild: false,\n lightmapMode: false,\n shadowEnabled: false,\n specularEnabled: false,\n };\n MaterialHelper.PrepareDefinesForLight(scene, mesh, this.light, this._lightId, defines, true, state);\n if (state.needRebuild) {\n defines.rebuild();\n }\n }\n }\n updateUniformsAndSamples(state, nodeMaterial, defines, uniformBuffers) {\n for (let lightIndex = 0; lightIndex < nodeMaterial.maxSimultaneousLights; lightIndex++) {\n if (!defines[\"LIGHT\" + lightIndex]) {\n break;\n }\n const onlyUpdateBuffersList = state.uniforms.indexOf(\"vLightData\" + lightIndex) >= 0;\n MaterialHelper.PrepareUniformsAndSamplersForLight(lightIndex, state.uniforms, state.samplers, defines[\"PROJECTEDLIGHTTEXTURE\" + lightIndex], uniformBuffers, onlyUpdateBuffersList);\n }\n }\n bind(effect, nodeMaterial, mesh) {\n if (!mesh) {\n return;\n }\n const scene = mesh.getScene();\n if (!this.light) {\n MaterialHelper.BindLights(scene, mesh, effect, true, nodeMaterial.maxSimultaneousLights);\n }\n else {\n MaterialHelper.BindLight(this.light, this._lightId, scene, effect, true);\n }\n }\n _injectVertexCode(state) {\n const worldPos = this.worldPosition;\n const comments = `//${this.name}`;\n // Declaration\n if (!this.light) {\n // Emit for all lights\n state._emitFunctionFromInclude(state.supportUniformBuffers ? \"lightVxUboDeclaration\" : \"lightVxFragmentDeclaration\", comments, {\n repeatKey: \"maxSimultaneousLights\",\n });\n this._lightId = 0;\n state.sharedData.dynamicUniformBlocks.push(this);\n }\n else {\n this._lightId = (state.counters[\"lightCounter\"] !== undefined ? state.counters[\"lightCounter\"] : -1) + 1;\n state.counters[\"lightCounter\"] = this._lightId;\n state._emitFunctionFromInclude(state.supportUniformBuffers ? \"lightVxUboDeclaration\" : \"lightVxFragmentDeclaration\", comments, {\n replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }],\n }, this._lightId.toString());\n }\n // Inject code in vertex\n const worldPosVaryingName = \"v_\" + worldPos.associatedVariableName;\n if (state._emitVaryingFromString(worldPosVaryingName, \"vec4\")) {\n state.compilationString += `${worldPosVaryingName} = ${worldPos.associatedVariableName};\\r\\n`;\n }\n if (this.light) {\n state.compilationString += state._emitCodeFromInclude(\"shadowsVertex\", comments, {\n replaceStrings: [\n { search: /{X}/g, replace: this._lightId.toString() },\n { search: /worldPos/g, replace: worldPos.associatedVariableName },\n ],\n });\n }\n else {\n state.compilationString += `vec4 worldPos = ${worldPos.associatedVariableName};\\r\\n`;\n if (this.view.isConnected) {\n state.compilationString += `mat4 view = ${this.view.associatedVariableName};\\r\\n`;\n }\n state.compilationString += state._emitCodeFromInclude(\"shadowsVertex\", comments, {\n repeatKey: \"maxSimultaneousLights\",\n });\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (state.target !== NodeMaterialBlockTargets.Fragment) {\n // Vertex\n this._injectVertexCode(state);\n return;\n }\n if (this.generateOnlyFragmentCode) {\n state.sharedData.dynamicUniformBlocks.push(this);\n }\n // Fragment\n state.sharedData.forcedBindableBlocks.push(this);\n state.sharedData.blocksWithDefines.push(this);\n const comments = `//${this.name}`;\n const worldPos = this.worldPosition;\n let worldPosVariableName = worldPos.associatedVariableName;\n if (this.generateOnlyFragmentCode) {\n worldPosVariableName = state._getFreeVariableName(\"globalWorldPos\");\n state._emitFunction(\"light_globalworldpos\", `vec3 ${worldPosVariableName};\\r\\n`, comments);\n state.compilationString += `${worldPosVariableName} = ${worldPos.associatedVariableName}.xyz;\\r\\n`;\n state.compilationString += state._emitCodeFromInclude(\"shadowsVertex\", comments, {\n repeatKey: \"maxSimultaneousLights\",\n substitutionVars: this.generateOnlyFragmentCode ? `worldPos,${worldPos.associatedVariableName}` : undefined,\n });\n }\n else {\n worldPosVariableName = \"v_\" + worldPosVariableName + \".xyz\";\n }\n state._emitFunctionFromInclude(\"helperFunctions\", comments);\n state._emitFunctionFromInclude(\"lightsFragmentFunctions\", comments, {\n replaceStrings: [{ search: /vPositionW/g, replace: worldPosVariableName }],\n });\n state._emitFunctionFromInclude(\"shadowsFragmentFunctions\", comments, {\n replaceStrings: [{ search: /vPositionW/g, replace: worldPosVariableName }],\n });\n if (!this.light) {\n // Emit for all lights\n state._emitFunctionFromInclude(state.supportUniformBuffers ? \"lightUboDeclaration\" : \"lightFragmentDeclaration\", comments, {\n repeatKey: \"maxSimultaneousLights\",\n substitutionVars: this.generateOnlyFragmentCode ? \"varying,\" : undefined,\n });\n }\n else {\n state._emitFunctionFromInclude(state.supportUniformBuffers ? \"lightUboDeclaration\" : \"lightFragmentDeclaration\", comments, {\n replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }],\n }, this._lightId.toString());\n }\n // Code\n if (this._lightId === 0) {\n if (state._registerTempVariable(\"viewDirectionW\")) {\n state.compilationString += `vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${worldPosVariableName});\\r\\n`;\n }\n state.compilationString += `lightingInfo info;\\r\\n`;\n state.compilationString += `float shadow = 1.;\\r\\n`;\n state.compilationString += `float glossiness = ${this.glossiness.isConnected ? this.glossiness.associatedVariableName : \"1.0\"} * ${this.glossPower.isConnected ? this.glossPower.associatedVariableName : \"1024.0\"};\\r\\n`;\n state.compilationString += `vec3 diffuseBase = vec3(0., 0., 0.);\\r\\n`;\n state.compilationString += `vec3 specularBase = vec3(0., 0., 0.);\\r\\n`;\n state.compilationString += `vec3 normalW = ${this.worldNormal.associatedVariableName}.xyz;\\r\\n`;\n }\n if (this.light) {\n state.compilationString += state._emitCodeFromInclude(\"lightFragment\", comments, {\n replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }],\n });\n }\n else {\n state.compilationString += state._emitCodeFromInclude(\"lightFragment\", comments, {\n repeatKey: \"maxSimultaneousLights\",\n });\n }\n const diffuseOutput = this.diffuseOutput;\n const specularOutput = this.specularOutput;\n state.compilationString +=\n this._declareOutput(diffuseOutput, state) + ` = diffuseBase${this.diffuseColor.isConnected ? \" * \" + this.diffuseColor.associatedVariableName : \"\"};\\r\\n`;\n if (specularOutput.hasEndpoints) {\n state.compilationString +=\n this._declareOutput(specularOutput, state) + ` = specularBase${this.specularColor.isConnected ? \" * \" + this.specularColor.associatedVariableName : \"\"};\\r\\n`;\n }\n if (this.shadow.hasEndpoints) {\n state.compilationString += this._declareOutput(this.shadow, state) + ` = shadow;\\r\\n`;\n }\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.generateOnlyFragmentCode = this.generateOnlyFragmentCode;\n if (this.light) {\n serializationObject.lightId = this.light.id;\n }\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n if (serializationObject.lightId) {\n this.light = scene.getLightById(serializationObject.lightId);\n }\n this.generateOnlyFragmentCode = serializationObject.generateOnlyFragmentCode;\n this._setTarget();\n }\n}\n__decorate([\n editableInPropertyPage(\"Generate only fragment code\", PropertyTypeForEdition.Boolean, \"ADVANCED\", {\n notifiers: { rebuild: true, update: true, onValidation: LightBlock._OnGenerateOnlyFragmentCodeChanged },\n })\n], LightBlock.prototype, \"generateOnlyFragmentCode\", void 0);\nRegisterClass(\"BABYLON.LightBlock\", LightBlock);\n//# sourceMappingURL=lightBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../../nodeMaterialBlockConnectionPoint.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { Texture } from \"../../../Textures/texture.js\";\n\nimport { NodeMaterial } from \"../../nodeMaterial.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../../nodeMaterialConnectionPointCustomObject.js\";\nimport { EngineStore } from \"../../../../Engines/engineStore.js\";\n/**\n * Block used to provide an image for a TextureBlock\n */\nexport class ImageSourceBlock extends NodeMaterialBlock {\n /**\n * Gets or sets the texture associated with the node\n */\n get texture() {\n return this._texture;\n }\n set texture(texture) {\n var _a;\n if (this._texture === texture) {\n return;\n }\n const scene = (_a = texture === null || texture === void 0 ? void 0 : texture.getScene()) !== null && _a !== void 0 ? _a : EngineStore.LastCreatedScene;\n if (!texture && scene) {\n scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(this._texture);\n });\n }\n this._texture = texture;\n if (texture && scene) {\n scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(texture);\n });\n }\n }\n /**\n * Gets the sampler name associated with this image source\n */\n get samplerName() {\n return this._samplerName;\n }\n /**\n * Creates a new ImageSourceBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.VertexAndFragment);\n this.registerOutput(\"source\", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject(\"source\", this, NodeMaterialConnectionPointDirection.Output, ImageSourceBlock, \"ImageSourceBlock\"));\n }\n bind(effect) {\n if (!this.texture) {\n return;\n }\n effect.setTexture(this._samplerName, this.texture);\n }\n isReady() {\n if (this.texture && !this.texture.isReadyOrNotBlocking()) {\n return false;\n }\n return true;\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ImageSourceBlock\";\n }\n /**\n * Gets the output component\n */\n get source() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (state.target === NodeMaterialBlockTargets.Vertex) {\n this._samplerName = state._getFreeVariableName(this.name + \"Sampler\");\n // Declarations\n state.sharedData.blockingBlocks.push(this);\n state.sharedData.textureBlocks.push(this);\n state.sharedData.bindableBlocks.push(this);\n }\n state._emit2DSampler(this._samplerName);\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n if (!this.texture) {\n return codeString;\n }\n codeString += `${this._codeVariableName}.texture = new BABYLON.Texture(\"${this.texture.name}\", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\\r\\n`;\n codeString += `${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n if (this.texture && !this.texture.isRenderTarget && this.texture.getClassName() !== \"VideoTexture\") {\n serializationObject.texture = this.texture.serialize();\n }\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n if (serializationObject.texture && !NodeMaterial.IgnoreTexturesAtLoadTime && serializationObject.texture.url !== undefined) {\n rootUrl = serializationObject.texture.url.indexOf(\"data:\") === 0 ? \"\" : rootUrl;\n this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl);\n }\n }\n}\nRegisterClass(\"BABYLON.ImageSourceBlock\", ImageSourceBlock);\n//# sourceMappingURL=imageSourceBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../../nodeMaterialBlockConnectionPoint.js\";\nimport { NodeMaterial } from \"../../nodeMaterial.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { Texture } from \"../../../Textures/texture.js\";\nimport { NodeMaterialModes } from \"../../Enums/nodeMaterialModes.js\";\n\nimport \"../../../../Shaders/ShadersInclude/helperFunctions.js\";\nimport { ImageSourceBlock } from \"./imageSourceBlock.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../../nodeMaterialConnectionPointCustomObject.js\";\nimport { EngineStore } from \"../../../../Engines/engineStore.js\";\n/**\n * Block used to read a texture from a sampler\n */\nexport class TextureBlock extends NodeMaterialBlock {\n /**\n * Gets or sets the texture associated with the node\n */\n get texture() {\n var _a;\n if (this.source.isConnected) {\n return ((_a = this.source.connectedPoint) === null || _a === void 0 ? void 0 : _a.ownerBlock).texture;\n }\n return this._texture;\n }\n set texture(texture) {\n var _a;\n if (this._texture === texture) {\n return;\n }\n const scene = (_a = texture === null || texture === void 0 ? void 0 : texture.getScene()) !== null && _a !== void 0 ? _a : EngineStore.LastCreatedScene;\n if (!texture && scene) {\n scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(this._texture);\n });\n }\n this._texture = texture;\n if (texture && scene) {\n scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(texture);\n });\n }\n }\n /**\n * Gets the sampler name associated with this texture\n */\n get samplerName() {\n if (this._imageSource) {\n return this._imageSource.samplerName;\n }\n return this._samplerName;\n }\n /**\n * Gets a boolean indicating that this block is linked to an ImageSourceBlock\n */\n get hasImageSource() {\n return this.source.isConnected;\n }\n /**\n * Gets or sets a boolean indicating if content needs to be converted to gamma space\n */\n set convertToGammaSpace(value) {\n var _a;\n if (value === this._convertToGammaSpace) {\n return;\n }\n this._convertToGammaSpace = value;\n if (this.texture) {\n const scene = (_a = this.texture.getScene()) !== null && _a !== void 0 ? _a : EngineStore.LastCreatedScene;\n scene === null || scene === void 0 ? void 0 : scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(this.texture);\n });\n }\n }\n get convertToGammaSpace() {\n return this._convertToGammaSpace;\n }\n /**\n * Gets or sets a boolean indicating if content needs to be converted to linear space\n */\n set convertToLinearSpace(value) {\n var _a;\n if (value === this._convertToLinearSpace) {\n return;\n }\n this._convertToLinearSpace = value;\n if (this.texture) {\n const scene = (_a = this.texture.getScene()) !== null && _a !== void 0 ? _a : EngineStore.LastCreatedScene;\n scene === null || scene === void 0 ? void 0 : scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(this.texture);\n });\n }\n }\n get convertToLinearSpace() {\n return this._convertToLinearSpace;\n }\n /**\n * Create a new TextureBlock\n * @param name defines the block name\n * @param fragmentOnly\n */\n constructor(name, fragmentOnly = false) {\n super(name, fragmentOnly ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.VertexAndFragment);\n this._convertToGammaSpace = false;\n this._convertToLinearSpace = false;\n /**\n * Gets or sets a boolean indicating if multiplication of texture with level should be disabled\n */\n this.disableLevelMultiplication = false;\n this._fragmentOnly = fragmentOnly;\n this.registerInput(\"uv\", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.VertexAndFragment);\n this.registerInput(\"source\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject(\"source\", this, NodeMaterialConnectionPointDirection.Input, ImageSourceBlock, \"ImageSourceBlock\"));\n this.registerInput(\"layer\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"lod\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerOutput(\"rgba\", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"rgb\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"r\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"g\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"b\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"a\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"level\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector2 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);\n this._inputs[0]._prioritizeVertex = !fragmentOnly;\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"TextureBlock\";\n }\n /**\n * Gets the uv input component\n */\n get uv() {\n return this._inputs[0];\n }\n /**\n * Gets the source input component\n */\n get source() {\n return this._inputs[1];\n }\n /**\n * Gets the layer input component\n */\n get layer() {\n return this._inputs[2];\n }\n /**\n * Gets the LOD input component\n */\n get lod() {\n return this._inputs[3];\n }\n /**\n * Gets the rgba output component\n */\n get rgba() {\n return this._outputs[0];\n }\n /**\n * Gets the rgb output component\n */\n get rgb() {\n return this._outputs[1];\n }\n /**\n * Gets the r output component\n */\n get r() {\n return this._outputs[2];\n }\n /**\n * Gets the g output component\n */\n get g() {\n return this._outputs[3];\n }\n /**\n * Gets the b output component\n */\n get b() {\n return this._outputs[4];\n }\n /**\n * Gets the a output component\n */\n get a() {\n return this._outputs[5];\n }\n /**\n * Gets the level output component\n */\n get level() {\n return this._outputs[6];\n }\n get target() {\n if (this._fragmentOnly) {\n return NodeMaterialBlockTargets.Fragment;\n }\n // TextureBlock has a special optimizations for uvs that come from the vertex shaders as they can be packed into a single varyings.\n // But we need to detect uvs coming from fragment then\n if (!this.uv.isConnected) {\n return NodeMaterialBlockTargets.VertexAndFragment;\n }\n if (this.uv.sourceBlock.isInput) {\n return NodeMaterialBlockTargets.VertexAndFragment;\n }\n let parent = this.uv.connectedPoint;\n while (parent) {\n if (parent.target === NodeMaterialBlockTargets.Fragment) {\n return NodeMaterialBlockTargets.Fragment;\n }\n if (parent.target === NodeMaterialBlockTargets.Vertex) {\n return NodeMaterialBlockTargets.VertexAndFragment;\n }\n if (parent.target === NodeMaterialBlockTargets.Neutral || parent.target === NodeMaterialBlockTargets.VertexAndFragment) {\n const parentBlock = parent.ownerBlock;\n if (parentBlock.target === NodeMaterialBlockTargets.Fragment) {\n return NodeMaterialBlockTargets.Fragment;\n }\n parent = null;\n for (const input of parentBlock.inputs) {\n if (input.connectedPoint) {\n parent = input.connectedPoint;\n break;\n }\n }\n }\n }\n return NodeMaterialBlockTargets.VertexAndFragment;\n }\n set target(value) { }\n autoConfigure(material) {\n if (!this.uv.isConnected) {\n if (material.mode === NodeMaterialModes.PostProcess) {\n const uvInput = material.getBlockByPredicate((b) => b.name === \"uv\");\n if (uvInput) {\n uvInput.connectTo(this);\n }\n }\n else {\n const attributeName = material.mode === NodeMaterialModes.Particle ? \"particle_uv\" : \"uv\";\n let uvInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === attributeName);\n if (!uvInput) {\n uvInput = new InputBlock(\"uv\");\n uvInput.setAsAttribute(attributeName);\n }\n uvInput.output.connectTo(this.uv);\n }\n }\n }\n initializeDefines(mesh, nodeMaterial, defines) {\n if (!defines._areTexturesDirty) {\n return;\n }\n if (this._mainUVDefineName !== undefined) {\n defines.setValue(this._mainUVDefineName, false, true);\n }\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n if (!defines._areTexturesDirty) {\n return;\n }\n if (!this.texture || !this.texture.getTextureMatrix) {\n if (this._isMixed) {\n defines.setValue(this._defineName, false, true);\n defines.setValue(this._mainUVDefineName, true, true);\n }\n return;\n }\n const toGamma = this.convertToGammaSpace && this.texture && !this.texture.gammaSpace;\n const toLinear = this.convertToLinearSpace && this.texture && this.texture.gammaSpace;\n // Not a bug... Name defines the texture space not the required conversion\n defines.setValue(this._linearDefineName, toGamma, true);\n defines.setValue(this._gammaDefineName, toLinear, true);\n if (this._isMixed) {\n if (!this.texture.getTextureMatrix().isIdentityAs3x2()) {\n defines.setValue(this._defineName, true);\n if (defines[this._mainUVDefineName] == undefined) {\n defines.setValue(this._mainUVDefineName, false, true);\n }\n }\n else {\n defines.setValue(this._defineName, false, true);\n defines.setValue(this._mainUVDefineName, true, true);\n }\n }\n }\n isReady() {\n if (this.texture && !this.texture.isReadyOrNotBlocking()) {\n return false;\n }\n return true;\n }\n bind(effect) {\n if (!this.texture) {\n return;\n }\n if (this._isMixed) {\n effect.setFloat(this._textureInfoName, this.texture.level);\n effect.setMatrix(this._textureTransformName, this.texture.getTextureMatrix());\n }\n if (!this._imageSource) {\n effect.setTexture(this._samplerName, this.texture);\n }\n }\n get _isMixed() {\n return this.target !== NodeMaterialBlockTargets.Fragment;\n }\n _injectVertexCode(state) {\n const uvInput = this.uv;\n // Inject code in vertex\n this._defineName = state._getFreeDefineName(\"UVTRANSFORM\");\n this._mainUVDefineName = \"VMAIN\" + uvInput.associatedVariableName.toUpperCase();\n this._mainUVName = \"vMain\" + uvInput.associatedVariableName;\n this._transformedUVName = state._getFreeVariableName(\"transformedUV\");\n this._textureTransformName = state._getFreeVariableName(\"textureTransform\");\n this._textureInfoName = state._getFreeVariableName(\"textureInfoName\");\n this.level.associatedVariableName = this._textureInfoName;\n state._emitVaryingFromString(this._transformedUVName, \"vec2\", this._defineName);\n state._emitVaryingFromString(this._mainUVName, \"vec2\", this._mainUVDefineName);\n state._emitUniformFromString(this._textureTransformName, \"mat4\", this._defineName);\n state.compilationString += `#ifdef ${this._defineName}\\r\\n`;\n state.compilationString += `${this._transformedUVName} = vec2(${this._textureTransformName} * vec4(${uvInput.associatedVariableName}.xy, 1.0, 0.0));\\r\\n`;\n state.compilationString += `#elif defined(${this._mainUVDefineName})\\r\\n`;\n state.compilationString += `${this._mainUVName} = ${uvInput.associatedVariableName}.xy;\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n if (!this._outputs.some((o) => o.isConnectedInVertexShader)) {\n return;\n }\n this._writeTextureRead(state, true);\n for (const output of this._outputs) {\n if (output.hasEndpoints && output.name !== \"level\") {\n this._writeOutput(state, output, output.name, true);\n }\n }\n }\n _getUVW(uvName) {\n var _a, _b, _c;\n let coords = uvName;\n const is2DArrayTexture = (_c = (_b = (_a = this._texture) === null || _a === void 0 ? void 0 : _a._texture) === null || _b === void 0 ? void 0 : _b.is2DArray) !== null && _c !== void 0 ? _c : false;\n if (is2DArrayTexture) {\n const layerValue = this.layer.isConnected ? this.layer.associatedVariableName : \"0\";\n coords = `vec3(${uvName}, ${layerValue})`;\n }\n return coords;\n }\n get _samplerFunc() {\n return this.lod.isConnected ? \"texture2DLodEXT\" : \"texture2D\";\n }\n get _samplerLodSuffix() {\n return this.lod.isConnected ? `, ${this.lod.associatedVariableName}` : \"\";\n }\n _generateTextureLookup(state) {\n const samplerName = this.samplerName;\n state.compilationString += `#ifdef ${this._defineName}\\r\\n`;\n state.compilationString += `vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${samplerName}, ${this._getUVW(this._transformedUVName)}${this._samplerLodSuffix});\\r\\n`;\n state.compilationString += `#elif defined(${this._mainUVDefineName})\\r\\n`;\n state.compilationString += `vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${samplerName}, ${this._getUVW(this._mainUVName ? this._mainUVName : this.uv.associatedVariableName)}${this._samplerLodSuffix});\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n }\n _writeTextureRead(state, vertexMode = false) {\n const uvInput = this.uv;\n if (vertexMode) {\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n return;\n }\n this._generateTextureLookup(state);\n return;\n }\n if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {\n state.compilationString += `vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${this.samplerName}, ${this._getUVW(uvInput.associatedVariableName)}${this._samplerLodSuffix});\\r\\n`;\n return;\n }\n this._generateTextureLookup(state);\n }\n _generateConversionCode(state, output, swizzle) {\n if (swizzle !== \"a\") {\n // no conversion if the output is \"a\" (alpha)\n if (!this.texture || !this.texture.gammaSpace) {\n state.compilationString += `#ifdef ${this._linearDefineName}\r\n ${output.associatedVariableName} = toGammaSpace(${output.associatedVariableName});\r\n #endif\r\n `;\n }\n state.compilationString += `#ifdef ${this._gammaDefineName}\r\n ${output.associatedVariableName} = toLinearSpace(${output.associatedVariableName});\r\n #endif\r\n `;\n }\n }\n _writeOutput(state, output, swizzle, vertexMode = false) {\n if (vertexMode) {\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n return;\n }\n state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\\r\\n`;\n this._generateConversionCode(state, output, swizzle);\n return;\n }\n if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {\n state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\\r\\n`;\n this._generateConversionCode(state, output, swizzle);\n return;\n }\n let complement = \"\";\n if (!this.disableLevelMultiplication) {\n complement = ` * ${this._textureInfoName}`;\n }\n state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle}${complement};\\r\\n`;\n this._generateConversionCode(state, output, swizzle);\n }\n _buildBlock(state) {\n var _a, _b, _c, _d;\n super._buildBlock(state);\n if (this.source.isConnected) {\n this._imageSource = this.source.connectedPoint.ownerBlock;\n }\n else {\n this._imageSource = null;\n }\n if (state.target === NodeMaterialBlockTargets.Vertex || this._fragmentOnly || state.target === NodeMaterialBlockTargets.Fragment) {\n this._tempTextureRead = state._getFreeVariableName(\"tempTextureRead\");\n this._linearDefineName = state._getFreeDefineName(\"ISLINEAR\");\n this._gammaDefineName = state._getFreeDefineName(\"ISGAMMA\");\n }\n if ((!this._isMixed && state.target === NodeMaterialBlockTargets.Fragment) || (this._isMixed && state.target === NodeMaterialBlockTargets.Vertex)) {\n if (!this._imageSource) {\n this._samplerName = state._getFreeVariableName(this.name + \"Sampler\");\n if ((_b = (_a = this._texture) === null || _a === void 0 ? void 0 : _a._texture) === null || _b === void 0 ? void 0 : _b.is2DArray) {\n state._emit2DArraySampler(this._samplerName);\n }\n else {\n state._emit2DSampler(this._samplerName);\n }\n }\n // Declarations\n state.sharedData.blockingBlocks.push(this);\n state.sharedData.textureBlocks.push(this);\n state.sharedData.blocksWithDefines.push(this);\n state.sharedData.bindableBlocks.push(this);\n }\n if (state.target !== NodeMaterialBlockTargets.Fragment) {\n // Vertex\n this._injectVertexCode(state);\n return;\n }\n // Fragment\n if (!this._outputs.some((o) => o.isConnectedInFragmentShader)) {\n return;\n }\n if (this._isMixed && !this._imageSource) {\n // Reexport the sampler\n if ((_d = (_c = this._texture) === null || _c === void 0 ? void 0 : _c._texture) === null || _d === void 0 ? void 0 : _d.is2DArray) {\n state._emit2DArraySampler(this._samplerName);\n }\n else {\n state._emit2DSampler(this._samplerName);\n }\n }\n const comments = `//${this.name}`;\n state._emitFunctionFromInclude(\"helperFunctions\", comments);\n if (this._isMixed) {\n state._emitUniformFromString(this._textureInfoName, \"float\");\n }\n this._writeTextureRead(state);\n for (const output of this._outputs) {\n if (output.hasEndpoints && output.name !== \"level\") {\n this._writeOutput(state, output, output.name);\n }\n }\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n codeString += `${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\\r\\n`;\n codeString += `${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\\r\\n`;\n codeString += `${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\\r\\n`;\n if (!this.texture) {\n return codeString;\n }\n codeString += `${this._codeVariableName}.texture = new BABYLON.Texture(\"${this.texture.name}\", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\\r\\n`;\n codeString += `${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.convertToGammaSpace = this.convertToGammaSpace;\n serializationObject.convertToLinearSpace = this.convertToLinearSpace;\n serializationObject.fragmentOnly = this._fragmentOnly;\n serializationObject.disableLevelMultiplication = this.disableLevelMultiplication;\n if (!this.hasImageSource && this.texture && !this.texture.isRenderTarget && this.texture.getClassName() !== \"VideoTexture\") {\n serializationObject.texture = this.texture.serialize();\n }\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.convertToGammaSpace = serializationObject.convertToGammaSpace;\n this.convertToLinearSpace = !!serializationObject.convertToLinearSpace;\n this._fragmentOnly = !!serializationObject.fragmentOnly;\n this.disableLevelMultiplication = !!serializationObject.disableLevelMultiplication;\n if (serializationObject.texture && !NodeMaterial.IgnoreTexturesAtLoadTime && serializationObject.texture.url !== undefined) {\n rootUrl = serializationObject.texture.url.indexOf(\"data:\") === 0 ? \"\" : rootUrl;\n this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl);\n }\n }\n}\nRegisterClass(\"BABYLON.TextureBlock\", TextureBlock);\n//# sourceMappingURL=textureBlock.js.map","import { __decorate } from \"../../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { NodeMaterial } from \"../../nodeMaterial.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { NodeMaterialSystemValues } from \"../../Enums/nodeMaterialSystemValues.js\";\n\nimport \"../../../../Shaders/ShadersInclude/reflectionFunction.js\";\nimport { CubeTexture } from \"../../../Textures/cubeTexture.js\";\nimport { Texture } from \"../../../Textures/texture.js\";\nimport { EngineStore } from \"../../../../Engines/engineStore.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../../nodeMaterialDecorator.js\";\n/**\n * Base block used to read a reflection texture from a sampler\n */\nexport class ReflectionTextureBaseBlock extends NodeMaterialBlock {\n /**\n * Gets or sets the texture associated with the node\n */\n get texture() {\n return this._texture;\n }\n set texture(texture) {\n var _a;\n if (this._texture === texture) {\n return;\n }\n const scene = (_a = texture === null || texture === void 0 ? void 0 : texture.getScene()) !== null && _a !== void 0 ? _a : EngineStore.LastCreatedScene;\n if (!texture && scene) {\n scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(this._texture);\n });\n }\n this._texture = texture;\n if (texture && scene) {\n scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(texture);\n });\n }\n }\n static _OnGenerateOnlyFragmentCodeChanged(block, _propertyName) {\n const that = block;\n return that._onGenerateOnlyFragmentCodeChanged();\n }\n _onGenerateOnlyFragmentCodeChanged() {\n this._setTarget();\n return true;\n }\n _setTarget() {\n this._setInitialTarget(this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.VertexAndFragment);\n }\n /**\n * Create a new ReflectionTextureBaseBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.VertexAndFragment);\n /** Indicates that no code should be generated in the vertex shader. Can be useful in some specific circumstances (like when doing ray marching for eg) */\n this.generateOnlyFragmentCode = false;\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ReflectionTextureBaseBlock\";\n }\n _getTexture() {\n return this.texture;\n }\n autoConfigure(material) {\n if (!this.position.isConnected) {\n let positionInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"position\");\n if (!positionInput) {\n positionInput = new InputBlock(\"position\");\n positionInput.setAsAttribute();\n }\n positionInput.output.connectTo(this.position);\n }\n if (!this.world.isConnected) {\n let worldInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.World);\n if (!worldInput) {\n worldInput = new InputBlock(\"world\");\n worldInput.setAsSystemValue(NodeMaterialSystemValues.World);\n }\n worldInput.output.connectTo(this.world);\n }\n if (this.view && !this.view.isConnected) {\n let viewInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.View);\n if (!viewInput) {\n viewInput = new InputBlock(\"view\");\n viewInput.setAsSystemValue(NodeMaterialSystemValues.View);\n }\n viewInput.output.connectTo(this.view);\n }\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n if (!defines._areTexturesDirty) {\n return;\n }\n const texture = this._getTexture();\n if (!texture || !texture.getTextureMatrix) {\n return;\n }\n defines.setValue(this._define3DName, texture.isCube, true);\n defines.setValue(this._defineLocalCubicName, texture.boundingBoxSize ? true : false, true);\n defines.setValue(this._defineExplicitName, texture.coordinatesMode === 0, true);\n defines.setValue(this._defineSkyboxName, texture.coordinatesMode === 5, true);\n defines.setValue(this._defineCubicName, texture.coordinatesMode === 3 || texture.coordinatesMode === 6, true);\n defines.setValue(\"INVERTCUBICMAP\", texture.coordinatesMode === 6, true);\n defines.setValue(this._defineSphericalName, texture.coordinatesMode === 1, true);\n defines.setValue(this._definePlanarName, texture.coordinatesMode === 2, true);\n defines.setValue(this._defineProjectionName, texture.coordinatesMode === 4, true);\n defines.setValue(this._defineEquirectangularName, texture.coordinatesMode === 7, true);\n defines.setValue(this._defineEquirectangularFixedName, texture.coordinatesMode === 8, true);\n defines.setValue(this._defineMirroredEquirectangularFixedName, texture.coordinatesMode === 9, true);\n }\n isReady() {\n const texture = this._getTexture();\n if (texture && !texture.isReadyOrNotBlocking()) {\n return false;\n }\n return true;\n }\n bind(effect, nodeMaterial, mesh) {\n const texture = this._getTexture();\n if (!mesh || !texture) {\n return;\n }\n effect.setMatrix(this._reflectionMatrixName, texture.getReflectionTextureMatrix());\n if (texture.isCube) {\n effect.setTexture(this._cubeSamplerName, texture);\n }\n else {\n effect.setTexture(this._2DSamplerName, texture);\n }\n if (texture.boundingBoxSize) {\n const cubeTexture = texture;\n effect.setVector3(this._reflectionPositionName, cubeTexture.boundingBoxPosition);\n effect.setVector3(this._reflectionSizeName, cubeTexture.boundingBoxSize);\n }\n }\n /**\n * Gets the code to inject in the vertex shader\n * @param state current state of the node material building\n * @returns the shader code\n */\n handleVertexSide(state) {\n if (this.generateOnlyFragmentCode && state.target === NodeMaterialBlockTargets.Vertex) {\n return \"\";\n }\n this._define3DName = state._getFreeDefineName(\"REFLECTIONMAP_3D\");\n this._defineCubicName = state._getFreeDefineName(\"REFLECTIONMAP_CUBIC\");\n this._defineSphericalName = state._getFreeDefineName(\"REFLECTIONMAP_SPHERICAL\");\n this._definePlanarName = state._getFreeDefineName(\"REFLECTIONMAP_PLANAR\");\n this._defineProjectionName = state._getFreeDefineName(\"REFLECTIONMAP_PROJECTION\");\n this._defineExplicitName = state._getFreeDefineName(\"REFLECTIONMAP_EXPLICIT\");\n this._defineEquirectangularName = state._getFreeDefineName(\"REFLECTIONMAP_EQUIRECTANGULAR\");\n this._defineLocalCubicName = state._getFreeDefineName(\"USE_LOCAL_REFLECTIONMAP_CUBIC\");\n this._defineMirroredEquirectangularFixedName = state._getFreeDefineName(\"REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\");\n this._defineEquirectangularFixedName = state._getFreeDefineName(\"REFLECTIONMAP_EQUIRECTANGULAR_FIXED\");\n this._defineSkyboxName = state._getFreeDefineName(\"REFLECTIONMAP_SKYBOX\");\n this._defineOppositeZ = state._getFreeDefineName(\"REFLECTIONMAP_OPPOSITEZ\");\n this._reflectionMatrixName = state._getFreeVariableName(\"reflectionMatrix\");\n state._emitUniformFromString(this._reflectionMatrixName, \"mat4\");\n let code = \"\";\n this._worldPositionNameInFragmentOnlyMode = state._getFreeVariableName(\"worldPosition\");\n const worldPosVaryingName = this.generateOnlyFragmentCode ? this._worldPositionNameInFragmentOnlyMode : \"v_\" + this.worldPosition.associatedVariableName;\n if (this.generateOnlyFragmentCode || state._emitVaryingFromString(worldPosVaryingName, \"vec4\")) {\n code += `${this.generateOnlyFragmentCode ? \"vec4 \" : \"\"}${worldPosVaryingName} = ${this.worldPosition.associatedVariableName};\\r\\n`;\n }\n this._positionUVWName = state._getFreeVariableName(\"positionUVW\");\n this._directionWName = state._getFreeVariableName(\"directionW\");\n if (this.generateOnlyFragmentCode || state._emitVaryingFromString(this._positionUVWName, \"vec3\", this._defineSkyboxName)) {\n code += `#ifdef ${this._defineSkyboxName}\\r\\n`;\n code += `${this.generateOnlyFragmentCode ? \"vec3 \" : \"\"}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz;\\r\\n`;\n code += `#endif\\r\\n`;\n }\n if (this.generateOnlyFragmentCode ||\n state._emitVaryingFromString(this._directionWName, \"vec3\", `defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`)) {\n code += `#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})\\r\\n`;\n code += `${this.generateOnlyFragmentCode ? \"vec3 \" : \"\"}${this._directionWName} = normalize(vec3(${this.world.associatedVariableName} * vec4(${this.position.associatedVariableName}.xyz, 0.0)));\\r\\n`;\n code += `#endif\\r\\n`;\n }\n return code;\n }\n /**\n * Handles the inits for the fragment code path\n * @param state node material build state\n */\n handleFragmentSideInits(state) {\n state.sharedData.blockingBlocks.push(this);\n state.sharedData.textureBlocks.push(this);\n // Samplers\n this._cubeSamplerName = state._getFreeVariableName(this.name + \"CubeSampler\");\n state.samplers.push(this._cubeSamplerName);\n this._2DSamplerName = state._getFreeVariableName(this.name + \"2DSampler\");\n state.samplers.push(this._2DSamplerName);\n state._samplerDeclaration += `#ifdef ${this._define3DName}\\r\\n`;\n state._samplerDeclaration += `uniform samplerCube ${this._cubeSamplerName};\\r\\n`;\n state._samplerDeclaration += `#else\\r\\n`;\n state._samplerDeclaration += `uniform sampler2D ${this._2DSamplerName};\\r\\n`;\n state._samplerDeclaration += `#endif\\r\\n`;\n // Fragment\n state.sharedData.blocksWithDefines.push(this);\n state.sharedData.bindableBlocks.push(this);\n const comments = `//${this.name}`;\n state._emitFunction(\"ReciprocalPI\", \"#define RECIPROCAL_PI2 0.15915494\", \"\");\n state._emitFunctionFromInclude(\"helperFunctions\", comments);\n state._emitFunctionFromInclude(\"reflectionFunction\", comments, {\n replaceStrings: [{ search: /vec3 computeReflectionCoords/g, replace: \"void DUMMYFUNC\" }],\n });\n this._reflectionColorName = state._getFreeVariableName(\"reflectionColor\");\n this._reflectionVectorName = state._getFreeVariableName(\"reflectionUVW\");\n this._reflectionCoordsName = state._getFreeVariableName(\"reflectionCoords\");\n this._reflectionPositionName = state._getFreeVariableName(\"vReflectionPosition\");\n state._emitUniformFromString(this._reflectionPositionName, \"vec3\");\n this._reflectionSizeName = state._getFreeVariableName(\"vReflectionPosition\");\n state._emitUniformFromString(this._reflectionSizeName, \"vec3\");\n }\n /**\n * Generates the reflection coords code for the fragment code path\n * @param worldNormalVarName name of the world normal variable\n * @param worldPos name of the world position variable. If not provided, will use the world position connected to this block\n * @param onlyReflectionVector if true, generates code only for the reflection vector computation, not for the reflection coordinates\n * @param doNotEmitInvertZ if true, does not emit the invertZ code\n * @returns the shader code\n */\n handleFragmentSideCodeReflectionCoords(worldNormalVarName, worldPos, onlyReflectionVector = false, doNotEmitInvertZ = false) {\n if (!worldPos) {\n worldPos = this.generateOnlyFragmentCode ? this._worldPositionNameInFragmentOnlyMode : `v_${this.worldPosition.associatedVariableName}`;\n }\n const reflectionMatrix = this._reflectionMatrixName;\n const direction = `normalize(${this._directionWName})`;\n const positionUVW = `${this._positionUVWName}`;\n const vEyePosition = `${this.cameraPosition.associatedVariableName}`;\n const view = `${this.view.associatedVariableName}`;\n worldNormalVarName += \".xyz\";\n let code = `\r\n #ifdef ${this._defineMirroredEquirectangularFixedName}\r\n vec3 ${this._reflectionVectorName} = computeMirroredFixedEquirectangularCoords(${worldPos}, ${worldNormalVarName}, ${direction});\r\n #endif\r\n\r\n #ifdef ${this._defineEquirectangularFixedName}\r\n vec3 ${this._reflectionVectorName} = computeFixedEquirectangularCoords(${worldPos}, ${worldNormalVarName}, ${direction});\r\n #endif\r\n\r\n #ifdef ${this._defineEquirectangularName}\r\n vec3 ${this._reflectionVectorName} = computeEquirectangularCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix});\r\n #endif\r\n\r\n #ifdef ${this._defineSphericalName}\r\n vec3 ${this._reflectionVectorName} = computeSphericalCoords(${worldPos}, ${worldNormalVarName}, ${view}, ${reflectionMatrix});\r\n #endif\r\n\r\n #ifdef ${this._definePlanarName}\r\n vec3 ${this._reflectionVectorName} = computePlanarCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix});\r\n #endif\r\n\r\n #ifdef ${this._defineCubicName}\r\n #ifdef ${this._defineLocalCubicName}\r\n vec3 ${this._reflectionVectorName} = computeCubicLocalCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix}, ${this._reflectionSizeName}, ${this._reflectionPositionName});\r\n #else\r\n vec3 ${this._reflectionVectorName} = computeCubicCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix});\r\n #endif\r\n #endif\r\n\r\n #ifdef ${this._defineProjectionName}\r\n vec3 ${this._reflectionVectorName} = computeProjectionCoords(${worldPos}, ${view}, ${reflectionMatrix});\r\n #endif\r\n\r\n #ifdef ${this._defineSkyboxName}\r\n vec3 ${this._reflectionVectorName} = computeSkyBoxCoords(${positionUVW}, ${reflectionMatrix});\r\n #endif\r\n\r\n #ifdef ${this._defineExplicitName}\r\n vec3 ${this._reflectionVectorName} = vec3(0, 0, 0);\r\n #endif\\r\\n`;\n if (!doNotEmitInvertZ) {\n code += `#ifdef ${this._defineOppositeZ}\r\n ${this._reflectionVectorName}.z *= -1.0;\r\n #endif\\r\\n`;\n }\n if (!onlyReflectionVector) {\n code += `\r\n #ifdef ${this._define3DName}\r\n vec3 ${this._reflectionCoordsName} = ${this._reflectionVectorName};\r\n #else\r\n vec2 ${this._reflectionCoordsName} = ${this._reflectionVectorName}.xy;\r\n #ifdef ${this._defineProjectionName}\r\n ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z;\r\n #endif\r\n ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y;\r\n #endif\\r\\n`;\n }\n return code;\n }\n /**\n * Generates the reflection color code for the fragment code path\n * @param lodVarName name of the lod variable\n * @param swizzleLookupTexture swizzle to use for the final color variable\n * @returns the shader code\n */\n handleFragmentSideCodeReflectionColor(lodVarName, swizzleLookupTexture = \".rgb\") {\n const colorType = \"vec\" + (swizzleLookupTexture.length === 0 ? \"4\" : swizzleLookupTexture.length - 1);\n let code = `${colorType} ${this._reflectionColorName};\r\n #ifdef ${this._define3DName}\\r\\n`;\n if (lodVarName) {\n code += `${this._reflectionColorName} = textureCubeLodEXT(${this._cubeSamplerName}, ${this._reflectionVectorName}, ${lodVarName})${swizzleLookupTexture};\\r\\n`;\n }\n else {\n code += `${this._reflectionColorName} = textureCube(${this._cubeSamplerName}, ${this._reflectionVectorName})${swizzleLookupTexture};\\r\\n`;\n }\n code += `\r\n #else\\r\\n`;\n if (lodVarName) {\n code += `${this._reflectionColorName} = texture2DLodEXT(${this._2DSamplerName}, ${this._reflectionCoordsName}, ${lodVarName})${swizzleLookupTexture};\\r\\n`;\n }\n else {\n code += `${this._reflectionColorName} = texture2D(${this._2DSamplerName}, ${this._reflectionCoordsName})${swizzleLookupTexture};\\r\\n`;\n }\n code += `#endif\\r\\n`;\n return code;\n }\n /**\n * Generates the code corresponding to the connected output points\n * @param state node material build state\n * @param varName name of the variable to output\n * @returns the shader code\n */\n writeOutputs(state, varName) {\n let code = \"\";\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n for (const output of this._outputs) {\n if (output.hasEndpoints) {\n code += `${this._declareOutput(output, state)} = ${varName}.${output.name};\\r\\n`;\n }\n }\n }\n return code;\n }\n _buildBlock(state) {\n super._buildBlock(state);\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n if (!this.texture) {\n return codeString;\n }\n if (this.texture.isCube) {\n const forcedExtension = this.texture.forcedExtension;\n codeString += `${this._codeVariableName}.texture = new BABYLON.CubeTexture(\"${this.texture.name}\", undefined, undefined, ${this.texture.noMipmap}, null, undefined, undefined, undefined, ${this.texture._prefiltered}, ${forcedExtension ? '\"' + forcedExtension + '\"' : \"null\"});\\r\\n`;\n }\n else {\n codeString += `${this._codeVariableName}.texture = new BABYLON.Texture(\"${this.texture.name}\", null);\\r\\n`;\n }\n codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n if (this.texture && !this.texture.isRenderTarget) {\n serializationObject.texture = this.texture.serialize();\n }\n serializationObject.generateOnlyFragmentCode = this.generateOnlyFragmentCode;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n if (serializationObject.texture && !NodeMaterial.IgnoreTexturesAtLoadTime) {\n rootUrl = serializationObject.texture.url.indexOf(\"data:\") === 0 ? \"\" : rootUrl;\n if (serializationObject.texture.isCube) {\n this.texture = CubeTexture.Parse(serializationObject.texture, scene, rootUrl);\n }\n else {\n this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl);\n }\n }\n this.generateOnlyFragmentCode = serializationObject.generateOnlyFragmentCode;\n this._setTarget();\n }\n}\n__decorate([\n editableInPropertyPage(\"Generate only fragment code\", PropertyTypeForEdition.Boolean, \"ADVANCED\", {\n notifiers: { rebuild: true, update: true, onValidation: ReflectionTextureBaseBlock._OnGenerateOnlyFragmentCodeChanged },\n })\n], ReflectionTextureBaseBlock.prototype, \"generateOnlyFragmentCode\", void 0);\nRegisterClass(\"BABYLON.ReflectionTextureBaseBlock\", ReflectionTextureBaseBlock);\n//# sourceMappingURL=reflectionTextureBaseBlock.js.map","import { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { NodeMaterialSystemValues } from \"../../Enums/nodeMaterialSystemValues.js\";\nimport { ReflectionTextureBaseBlock } from \"./reflectionTextureBaseBlock.js\";\n/**\n * Block used to read a reflection texture from a sampler\n */\nexport class ReflectionTextureBlock extends ReflectionTextureBaseBlock {\n _onGenerateOnlyFragmentCodeChanged() {\n if (this.position.isConnected) {\n this.generateOnlyFragmentCode = !this.generateOnlyFragmentCode;\n console.error(\"The position input must not be connected to be able to switch!\");\n return false;\n }\n if (this.worldPosition.isConnected) {\n this.generateOnlyFragmentCode = !this.generateOnlyFragmentCode;\n console.error(\"The worldPosition input must not be connected to be able to switch!\");\n return false;\n }\n this._setTarget();\n return true;\n }\n _setTarget() {\n super._setTarget();\n this.getInputByName(\"position\").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex;\n this.getInputByName(\"worldPosition\").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex;\n }\n /**\n * Create a new ReflectionTextureBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name);\n this.registerInput(\"position\", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.Vertex);\n this.registerInput(\"worldPosition\", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex);\n this.registerInput(\"worldNormal\", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Fragment); // Flagging as fragment as the normal can be changed by fragment code\n this.registerInput(\"world\", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Vertex);\n this.registerInput(\"cameraPosition\", NodeMaterialBlockConnectionPointTypes.Vector3, false, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"view\", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"rgb\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"rgba\", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"r\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"g\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"b\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"a\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ReflectionTextureBlock\";\n }\n /**\n * Gets the world position input component\n */\n get position() {\n return this._inputs[0];\n }\n /**\n * Gets the world position input component\n */\n get worldPosition() {\n return this._inputs[1];\n }\n /**\n * Gets the world normal input component\n */\n get worldNormal() {\n return this._inputs[2];\n }\n /**\n * Gets the world input component\n */\n get world() {\n return this._inputs[3];\n }\n /**\n * Gets the camera (or eye) position component\n */\n get cameraPosition() {\n return this._inputs[4];\n }\n /**\n * Gets the view input component\n */\n get view() {\n return this._inputs[5];\n }\n /**\n * Gets the rgb output component\n */\n get rgb() {\n return this._outputs[0];\n }\n /**\n * Gets the rgba output component\n */\n get rgba() {\n return this._outputs[1];\n }\n /**\n * Gets the r output component\n */\n get r() {\n return this._outputs[2];\n }\n /**\n * Gets the g output component\n */\n get g() {\n return this._outputs[3];\n }\n /**\n * Gets the b output component\n */\n get b() {\n return this._outputs[4];\n }\n /**\n * Gets the a output component\n */\n get a() {\n return this._outputs[5];\n }\n autoConfigure(material) {\n super.autoConfigure(material);\n if (!this.cameraPosition.isConnected) {\n let cameraPositionInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.CameraPosition);\n if (!cameraPositionInput) {\n cameraPositionInput = new InputBlock(\"cameraPosition\");\n cameraPositionInput.setAsSystemValue(NodeMaterialSystemValues.CameraPosition);\n }\n cameraPositionInput.output.connectTo(this.cameraPosition);\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (!this.texture) {\n state.compilationString += this.writeOutputs(state, \"vec4(0.)\");\n return this;\n }\n if (state.target !== NodeMaterialBlockTargets.Fragment) {\n state.compilationString += this.handleVertexSide(state);\n return this;\n }\n if (this.generateOnlyFragmentCode) {\n state.compilationString += this.handleVertexSide(state);\n }\n this.handleFragmentSideInits(state);\n const normalWUnit = state._getFreeVariableName(\"normalWUnit\");\n state.compilationString += `vec4 ${normalWUnit} = normalize(${this.worldNormal.associatedVariableName});\\r\\n`;\n state.compilationString += this.handleFragmentSideCodeReflectionCoords(normalWUnit);\n state.compilationString += this.handleFragmentSideCodeReflectionColor(undefined, \"\");\n state.compilationString += this.writeOutputs(state, this._reflectionColorName);\n return this;\n }\n}\nRegisterClass(\"BABYLON.ReflectionTextureBlock\", ReflectionTextureBlock);\n//# sourceMappingURL=reflectionTextureBlock.js.map","import { __decorate } from \"../../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../../nodeMaterialDecorator.js\";\n/**\n * Block used to retrieve the depth (zbuffer) of the scene\n * @since 5.0.0\n */\nexport class SceneDepthBlock extends NodeMaterialBlock {\n /**\n * Create a new SceneDepthBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.VertexAndFragment);\n /**\n * Defines if the depth renderer should be setup in non linear mode\n */\n this.useNonLinearDepth = false;\n /**\n * Defines if the depth renderer should be setup in camera space Z mode (if set, useNonLinearDepth has no effect)\n */\n this.storeCameraSpaceZ = false;\n /**\n * Defines if the depth renderer should be setup in full 32 bits float mode\n */\n this.force32itsFloat = false;\n this._isUnique = true;\n this.registerInput(\"uv\", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.VertexAndFragment);\n this.registerOutput(\"depth\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector2 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);\n this._inputs[0]._prioritizeVertex = false;\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"SceneDepthBlock\";\n }\n /**\n * Gets the uv input component\n */\n get uv() {\n return this._inputs[0];\n }\n /**\n * Gets the depth output component\n */\n get depth() {\n return this._outputs[0];\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"textureSampler\");\n }\n get target() {\n if (!this.uv.isConnected) {\n return NodeMaterialBlockTargets.VertexAndFragment;\n }\n if (this.uv.sourceBlock.isInput) {\n return NodeMaterialBlockTargets.VertexAndFragment;\n }\n return NodeMaterialBlockTargets.Fragment;\n }\n _getTexture(scene) {\n const depthRenderer = scene.enableDepthRenderer(undefined, this.useNonLinearDepth, this.force32itsFloat, undefined, this.storeCameraSpaceZ);\n return depthRenderer.getDepthMap();\n }\n bind(effect, nodeMaterial) {\n const texture = this._getTexture(nodeMaterial.getScene());\n effect.setTexture(this._samplerName, texture);\n }\n _injectVertexCode(state) {\n const uvInput = this.uv;\n if (uvInput.connectedPoint.ownerBlock.isInput) {\n const uvInputOwnerBlock = uvInput.connectedPoint.ownerBlock;\n if (!uvInputOwnerBlock.isAttribute) {\n state._emitUniformFromString(uvInput.associatedVariableName, \"vec\" + (uvInput.type === NodeMaterialBlockConnectionPointTypes.Vector3 ? \"3\" : uvInput.type === NodeMaterialBlockConnectionPointTypes.Vector4 ? \"4\" : \"2\"));\n }\n }\n this._mainUVName = \"vMain\" + uvInput.associatedVariableName;\n state._emitVaryingFromString(this._mainUVName, \"vec2\");\n state.compilationString += `${this._mainUVName} = ${uvInput.associatedVariableName}.xy;\\r\\n`;\n if (!this._outputs.some((o) => o.isConnectedInVertexShader)) {\n return;\n }\n this._writeTextureRead(state, true);\n for (const output of this._outputs) {\n if (output.hasEndpoints) {\n this._writeOutput(state, output, \"r\", true);\n }\n }\n }\n _writeTextureRead(state, vertexMode = false) {\n const uvInput = this.uv;\n if (vertexMode) {\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n return;\n }\n state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${uvInput.associatedVariableName}.xy);\\r\\n`;\n return;\n }\n if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {\n state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${uvInput.associatedVariableName}.xy);\\r\\n`;\n return;\n }\n state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\\r\\n`;\n }\n _writeOutput(state, output, swizzle, vertexMode = false) {\n if (vertexMode) {\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n return;\n }\n state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\\r\\n`;\n return;\n }\n if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {\n state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\\r\\n`;\n return;\n }\n state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\\r\\n`;\n }\n _buildBlock(state) {\n super._buildBlock(state);\n this._samplerName = state._getFreeVariableName(this.name + \"Sampler\");\n this._tempTextureRead = state._getFreeVariableName(\"tempTextureRead\");\n if (state.sharedData.bindableBlocks.indexOf(this) < 0) {\n state.sharedData.bindableBlocks.push(this);\n }\n if (state.target !== NodeMaterialBlockTargets.Fragment) {\n // Vertex\n state._emit2DSampler(this._samplerName);\n this._injectVertexCode(state);\n return;\n }\n // Fragment\n if (!this._outputs.some((o) => o.isConnectedInFragmentShader)) {\n return;\n }\n state._emit2DSampler(this._samplerName);\n this._writeTextureRead(state);\n for (const output of this._outputs) {\n if (output.hasEndpoints) {\n this._writeOutput(state, output, \"r\");\n }\n }\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.useNonLinearDepth = this.useNonLinearDepth;\n serializationObject.storeCameraSpaceZ = this.storeCameraSpaceZ;\n serializationObject.force32itsFloat = this.force32itsFloat;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.useNonLinearDepth = serializationObject.useNonLinearDepth;\n this.storeCameraSpaceZ = !!serializationObject.storeCameraSpaceZ;\n this.force32itsFloat = serializationObject.force32itsFloat;\n }\n}\n__decorate([\n editableInPropertyPage(\"Use non linear depth\", PropertyTypeForEdition.Boolean, \"ADVANCED\", {\n notifiers: {\n activatePreviewCommand: true,\n callback: (scene, block) => {\n const sceneDepthBlock = block;\n let retVal = false;\n if (sceneDepthBlock.useNonLinearDepth) {\n sceneDepthBlock.storeCameraSpaceZ = false;\n retVal = true;\n }\n scene.disableDepthRenderer();\n return retVal;\n },\n },\n })\n], SceneDepthBlock.prototype, \"useNonLinearDepth\", void 0);\n__decorate([\n editableInPropertyPage(\"Store Camera space Z\", PropertyTypeForEdition.Boolean, \"ADVANCED\", {\n notifiers: {\n activatePreviewCommand: true,\n callback: (scene, block) => {\n const sceneDepthBlock = block;\n let retVal = false;\n if (sceneDepthBlock.storeCameraSpaceZ) {\n sceneDepthBlock.useNonLinearDepth = false;\n retVal = true;\n }\n scene.disableDepthRenderer();\n return retVal;\n },\n },\n })\n], SceneDepthBlock.prototype, \"storeCameraSpaceZ\", void 0);\n__decorate([\n editableInPropertyPage(\"Force 32 bits float\", PropertyTypeForEdition.Boolean, \"ADVANCED\", {\n notifiers: { activatePreviewCommand: true, callback: (scene) => scene.disableDepthRenderer() },\n })\n], SceneDepthBlock.prototype, \"force32itsFloat\", void 0);\nRegisterClass(\"BABYLON.SceneDepthBlock\", SceneDepthBlock);\n//# sourceMappingURL=sceneDepthBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { bindClipPlane } from \"../../../../Materials/clipPlaneMaterialHelper.js\";\n/**\n * Block used to implement clip planes\n */\nexport class ClipPlanesBlock extends NodeMaterialBlock {\n /**\n * Create a new ClipPlanesBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.VertexAndFragment, true);\n this.registerInput(\"worldPosition\", NodeMaterialBlockConnectionPointTypes.Vector4, false);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ClipPlanesBlock\";\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"vClipPlane\");\n state._excludeVariableName(\"fClipDistance\");\n state._excludeVariableName(\"vClipPlane2\");\n state._excludeVariableName(\"fClipDistance2\");\n state._excludeVariableName(\"vClipPlane3\");\n state._excludeVariableName(\"fClipDistance3\");\n state._excludeVariableName(\"vClipPlane4\");\n state._excludeVariableName(\"fClipDistance4\");\n state._excludeVariableName(\"vClipPlane5\");\n state._excludeVariableName(\"fClipDistance5\");\n state._excludeVariableName(\"vClipPlane6\");\n state._excludeVariableName(\"fClipDistance6\");\n }\n /**\n * Gets the worldPosition input component\n */\n get worldPosition() {\n return this._inputs[0];\n }\n get target() {\n return NodeMaterialBlockTargets.VertexAndFragment;\n }\n set target(value) { }\n prepareDefines(mesh, nodeMaterial, defines) {\n var _a, _b, _c, _d, _e, _f;\n const scene = mesh.getScene();\n const useClipPlane1 = ((_a = nodeMaterial.clipPlane) !== null && _a !== void 0 ? _a : scene.clipPlane) ? true : false;\n const useClipPlane2 = ((_b = nodeMaterial.clipPlane2) !== null && _b !== void 0 ? _b : scene.clipPlane2) ? true : false;\n const useClipPlane3 = ((_c = nodeMaterial.clipPlane3) !== null && _c !== void 0 ? _c : scene.clipPlane3) ? true : false;\n const useClipPlane4 = ((_d = nodeMaterial.clipPlane4) !== null && _d !== void 0 ? _d : scene.clipPlane4) ? true : false;\n const useClipPlane5 = ((_e = nodeMaterial.clipPlane5) !== null && _e !== void 0 ? _e : scene.clipPlane5) ? true : false;\n const useClipPlane6 = ((_f = nodeMaterial.clipPlane6) !== null && _f !== void 0 ? _f : scene.clipPlane6) ? true : false;\n defines.setValue(\"CLIPPLANE\", useClipPlane1, true);\n defines.setValue(\"CLIPPLANE2\", useClipPlane2, true);\n defines.setValue(\"CLIPPLANE3\", useClipPlane3, true);\n defines.setValue(\"CLIPPLANE4\", useClipPlane4, true);\n defines.setValue(\"CLIPPLANE5\", useClipPlane5, true);\n defines.setValue(\"CLIPPLANE6\", useClipPlane6, true);\n }\n bind(effect, nodeMaterial, mesh) {\n if (!mesh) {\n return;\n }\n const scene = mesh.getScene();\n bindClipPlane(effect, nodeMaterial, scene);\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const comments = `//${this.name}`;\n if (state.target !== NodeMaterialBlockTargets.Fragment) {\n // Vertex\n const worldPos = this.worldPosition;\n state._emitFunctionFromInclude(\"clipPlaneVertexDeclaration\", comments, {\n replaceStrings: [{ search: /uniform vec4 vClipPlane\\d*;/g, replace: \"\" }],\n });\n state.compilationString += state._emitCodeFromInclude(\"clipPlaneVertex\", comments, {\n replaceStrings: [{ search: /worldPos/g, replace: worldPos.associatedVariableName }],\n });\n state._emitUniformFromString(\"vClipPlane\", \"vec4\");\n state._emitUniformFromString(\"vClipPlane2\", \"vec4\");\n state._emitUniformFromString(\"vClipPlane3\", \"vec4\");\n state._emitUniformFromString(\"vClipPlane4\", \"vec4\");\n state._emitUniformFromString(\"vClipPlane5\", \"vec4\");\n state._emitUniformFromString(\"vClipPlane6\", \"vec4\");\n return;\n }\n // Fragment\n state.sharedData.bindableBlocks.push(this);\n state.sharedData.blocksWithDefines.push(this);\n state._emitFunctionFromInclude(\"clipPlaneFragmentDeclaration\", comments);\n state.compilationString += state._emitCodeFromInclude(\"clipPlaneFragment\", comments);\n return this;\n }\n}\nRegisterClass(\"BABYLON.ClipPlanesBlock\", ClipPlanesBlock);\n//# sourceMappingURL=clipPlanesBlock.js.map","export * from \"./fogBlock.js\";\nexport * from \"./lightBlock.js\";\nexport * from \"./textureBlock.js\";\nexport * from \"./reflectionTextureBlock.js\";\nexport * from \"./currentScreenBlock.js\";\nexport * from \"./sceneDepthBlock.js\";\nexport * from \"./imageSourceBlock.js\";\nexport * from \"./clipPlanesBlock.js\";\n//# sourceMappingURL=index.js.map","export * from \"./inputBlock.js\";\nexport * from \"./animatedInputBlockTypes.js\";\n//# sourceMappingURL=index.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to add 2 vectors\n */\nexport class AddBlock extends NodeMaterialBlock {\n /**\n * Creates a new AddBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"left\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"right\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._linkConnectionTypes(0, 1);\n this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"AddBlock\";\n }\n /**\n * Gets the left operand input component\n */\n get left() {\n return this._inputs[0];\n }\n /**\n * Gets the right operand input component\n */\n get right() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = ${this.left.associatedVariableName} + ${this.right.associatedVariableName};\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.AddBlock\", AddBlock);\n//# sourceMappingURL=addBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to apply a cross product between 2 vectors\n */\nexport class CrossBlock extends NodeMaterialBlock {\n /**\n * Creates a new CrossBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"left\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"right\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this._linkConnectionTypes(0, 1);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2);\n this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"CrossBlock\";\n }\n /**\n * Gets the left operand input component\n */\n get left() {\n return this._inputs[0];\n }\n /**\n * Gets the right operand input component\n */\n get right() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = cross(${this.left.associatedVariableName}.xyz, ${this.right.associatedVariableName}.xyz);\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.CrossBlock\", CrossBlock);\n//# sourceMappingURL=crossBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../nodeMaterialBlockConnectionPoint.js\";\nimport { ImageSourceBlock } from \"./Dual/imageSourceBlock.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../nodeMaterialConnectionPointCustomObject.js\";\n/**\n * Custom block created from user-defined json\n */\nexport class CustomBlock extends NodeMaterialBlock {\n /**\n * Gets or sets the options for this custom block\n */\n get options() {\n return this._options;\n }\n set options(options) {\n this._deserializeOptions(options);\n }\n /**\n * Creates a new CustomBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"CustomBlock\";\n }\n _buildBlock(state) {\n super._buildBlock(state);\n let code = this._code;\n let functionName = this._options.functionName;\n // Replace the TYPE_XXX placeholders (if any)\n this._inputs.forEach((input) => {\n const rexp = new RegExp(\"\\\\{TYPE_\" + input.name + \"\\\\}\", \"gm\");\n const type = state._getGLType(input.type);\n code = code.replace(rexp, type);\n functionName = functionName.replace(rexp, type);\n });\n this._outputs.forEach((output) => {\n const rexp = new RegExp(\"\\\\{TYPE_\" + output.name + \"\\\\}\", \"gm\");\n const type = state._getGLType(output.type);\n code = code.replace(rexp, type);\n functionName = functionName.replace(rexp, type);\n });\n state._emitFunction(functionName, code, \"\");\n // Declare the output variables\n this._outputs.forEach((output) => {\n state.compilationString += this._declareOutput(output, state) + \";\\r\\n\";\n });\n // Generate the function call\n state.compilationString += functionName + \"(\";\n let hasInput = false;\n this._inputs.forEach((input, index) => {\n var _a, _b, _c;\n if (index > 0) {\n state.compilationString += \", \";\n }\n if (this._inputSamplers && this._inputSamplers.indexOf(input.name) !== -1) {\n state.compilationString += (_c = (_b = (_a = input.connectedPoint) === null || _a === void 0 ? void 0 : _a.ownerBlock) === null || _b === void 0 ? void 0 : _b.samplerName) !== null && _c !== void 0 ? _c : input.associatedVariableName;\n }\n else {\n state.compilationString += input.associatedVariableName;\n }\n hasInput = true;\n });\n this._outputs.forEach((output, index) => {\n if (index > 0 || hasInput) {\n state.compilationString += \", \";\n }\n state.compilationString += output.associatedVariableName;\n });\n state.compilationString += \");\\r\\n\";\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n codeString += `${this._codeVariableName}.options = ${JSON.stringify(this._options)};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.options = this._options;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n this._deserializeOptions(serializationObject.options);\n super._deserialize(serializationObject, scene, rootUrl);\n }\n _deserializeOptions(options) {\n var _a, _b, _c;\n this._options = options;\n this._code = options.code.join(\"\\r\\n\") + \"\\r\\n\";\n this.name = this.name || options.name;\n this.target = NodeMaterialBlockTargets[options.target];\n (_a = options.inParameters) === null || _a === void 0 ? void 0 : _a.forEach((input, index) => {\n const type = NodeMaterialBlockConnectionPointTypes[input.type];\n if (input.type === \"sampler2D\" || input.type === \"samplerCube\") {\n this._inputSamplers = this._inputSamplers || [];\n this._inputSamplers.push(input.name);\n this.registerInput(input.name, NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject(input.name, this, NodeMaterialConnectionPointDirection.Input, ImageSourceBlock, \"ImageSourceBlock\"));\n }\n else {\n this.registerInput(input.name, type);\n }\n Object.defineProperty(this, input.name, {\n get: function () {\n return this._inputs[index];\n },\n enumerable: true,\n configurable: true,\n });\n });\n (_b = options.outParameters) === null || _b === void 0 ? void 0 : _b.forEach((output, index) => {\n this.registerOutput(output.name, NodeMaterialBlockConnectionPointTypes[output.type]);\n Object.defineProperty(this, output.name, {\n get: function () {\n return this._outputs[index];\n },\n enumerable: true,\n configurable: true,\n });\n if (output.type === \"BasedOnInput\") {\n this._outputs[index]._typeConnectionSource = this._findInputByName(output.typeFromInput)[0];\n }\n });\n (_c = options.inLinkedConnectionTypes) === null || _c === void 0 ? void 0 : _c.forEach((connection) => {\n this._linkConnectionTypes(this._findInputByName(connection.input1)[1], this._findInputByName(connection.input2)[1]);\n });\n }\n _findInputByName(name) {\n if (!name) {\n return null;\n }\n for (let i = 0; i < this._inputs.length; i++) {\n if (this._inputs[i].name === name) {\n return [this._inputs[i], i];\n }\n }\n return null;\n }\n}\nRegisterClass(\"BABYLON.CustomBlock\", CustomBlock);\n//# sourceMappingURL=customBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to apply a dot product between 2 vectors\n */\nexport class DotBlock extends NodeMaterialBlock {\n /**\n * Creates a new DotBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"left\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"right\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Float);\n this._linkConnectionTypes(0, 1);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"DotBlock\";\n }\n /**\n * Gets the left operand input component\n */\n get left() {\n return this._inputs[0];\n }\n /**\n * Gets the right operand input component\n */\n get right() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = dot(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.DotBlock\", DotBlock);\n//# sourceMappingURL=dotBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to create a Color3/4 out of individual inputs (one for each component)\n */\nexport class ColorMergerBlock extends NodeMaterialBlock {\n /**\n * Create a new ColorMergerBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n /**\n * Gets or sets the swizzle for r (meaning which component to affect to the output.r)\n */\n this.rSwizzle = \"r\";\n /**\n * Gets or sets the swizzle for g (meaning which component to affect to the output.g)\n */\n this.gSwizzle = \"g\";\n /**\n * Gets or sets the swizzle for b (meaning which component to affect to the output.b)\n */\n this.bSwizzle = \"b\";\n /**\n * Gets or sets the swizzle for a (meaning which component to affect to the output.a)\n */\n this.aSwizzle = \"a\";\n this.registerInput(\"rgb \", NodeMaterialBlockConnectionPointTypes.Color3, true);\n this.registerInput(\"r\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"g\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"b\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"a\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerOutput(\"rgba\", NodeMaterialBlockConnectionPointTypes.Color4);\n this.registerOutput(\"rgb\", NodeMaterialBlockConnectionPointTypes.Color3);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ColorMergerBlock\";\n }\n /**\n * Gets the rgb component (input)\n */\n get rgbIn() {\n return this._inputs[0];\n }\n /**\n * Gets the r component (input)\n */\n get r() {\n return this._inputs[1];\n }\n /**\n * Gets the g component (input)\n */\n get g() {\n return this._inputs[2];\n }\n /**\n * Gets the b component (input)\n */\n get b() {\n return this._inputs[3];\n }\n /**\n * Gets the a component (input)\n */\n get a() {\n return this._inputs[4];\n }\n /**\n * Gets the rgba component (output)\n */\n get rgba() {\n return this._outputs[0];\n }\n /**\n * Gets the rgb component (output)\n */\n get rgbOut() {\n return this._outputs[1];\n }\n /**\n * Gets the rgb component (output)\n * @deprecated Please use rgbOut instead.\n */\n get rgb() {\n return this.rgbOut;\n }\n _inputRename(name) {\n if (name === \"rgb \") {\n return \"rgbIn\";\n }\n return name;\n }\n _buildSwizzle(len) {\n const swizzle = this.rSwizzle + this.gSwizzle + this.bSwizzle + this.aSwizzle;\n return \".\" + swizzle.substr(0, len);\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const rInput = this.r;\n const gInput = this.g;\n const bInput = this.b;\n const aInput = this.a;\n const rgbInput = this.rgbIn;\n const color4Output = this._outputs[0];\n const color3Output = this._outputs[1];\n if (rgbInput.isConnected) {\n if (color4Output.hasEndpoints) {\n state.compilationString +=\n this._declareOutput(color4Output, state) +\n ` = vec4(${rgbInput.associatedVariableName}, ${aInput.isConnected ? this._writeVariable(aInput) : \"0.0\"})${this._buildSwizzle(4)};\\r\\n`;\n }\n if (color3Output.hasEndpoints) {\n state.compilationString += this._declareOutput(color3Output, state) + ` = ${rgbInput.associatedVariableName}${this._buildSwizzle(3)};\\r\\n`;\n }\n }\n else {\n if (color4Output.hasEndpoints) {\n state.compilationString +=\n this._declareOutput(color4Output, state) +\n ` = vec4(${rInput.isConnected ? this._writeVariable(rInput) : \"0.0\"}, ${gInput.isConnected ? this._writeVariable(gInput) : \"0.0\"}, ${bInput.isConnected ? this._writeVariable(bInput) : \"0.0\"}, ${aInput.isConnected ? this._writeVariable(aInput) : \"0.0\"})${this._buildSwizzle(4)};\\r\\n`;\n }\n if (color3Output.hasEndpoints) {\n state.compilationString +=\n this._declareOutput(color3Output, state) +\n ` = vec3(${rInput.isConnected ? this._writeVariable(rInput) : \"0.0\"}, ${gInput.isConnected ? this._writeVariable(gInput) : \"0.0\"}, ${bInput.isConnected ? this._writeVariable(bInput) : \"0.0\"})${this._buildSwizzle(3)};\\r\\n`;\n }\n }\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.rSwizzle = this.rSwizzle;\n serializationObject.gSwizzle = this.gSwizzle;\n serializationObject.bSwizzle = this.bSwizzle;\n serializationObject.aSwizzle = this.aSwizzle;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n var _a, _b, _c, _d;\n super._deserialize(serializationObject, scene, rootUrl);\n this.rSwizzle = (_a = serializationObject.rSwizzle) !== null && _a !== void 0 ? _a : \"r\";\n this.gSwizzle = (_b = serializationObject.gSwizzle) !== null && _b !== void 0 ? _b : \"g\";\n this.bSwizzle = (_c = serializationObject.bSwizzle) !== null && _c !== void 0 ? _c : \"b\";\n this.aSwizzle = (_d = serializationObject.aSwizzle) !== null && _d !== void 0 ? _d : \"a\";\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n codeString += `${this._codeVariableName}.rSwizzle = \"${this.rSwizzle}\";\\r\\n`;\n codeString += `${this._codeVariableName}.gSwizzle = \"${this.gSwizzle}\";\\r\\n`;\n codeString += `${this._codeVariableName}.bSwizzle = \"${this.bSwizzle}\";\\r\\n`;\n codeString += `${this._codeVariableName}.aSwizzle = \"${this.aSwizzle}\";\\r\\n`;\n return codeString;\n }\n}\nRegisterClass(\"BABYLON.ColorMergerBlock\", ColorMergerBlock);\n//# sourceMappingURL=colorMergerBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to expand a Vector3/4 into 4 outputs (one for each component)\n */\nexport class VectorSplitterBlock extends NodeMaterialBlock {\n /**\n * Create a new VectorSplitterBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"xyzw\", NodeMaterialBlockConnectionPointTypes.Vector4, true);\n this.registerInput(\"xyz \", NodeMaterialBlockConnectionPointTypes.Vector3, true);\n this.registerInput(\"xy \", NodeMaterialBlockConnectionPointTypes.Vector2, true);\n this.registerOutput(\"xyz\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerOutput(\"xy\", NodeMaterialBlockConnectionPointTypes.Vector2);\n this.registerOutput(\"zw\", NodeMaterialBlockConnectionPointTypes.Vector2);\n this.registerOutput(\"x\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"y\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"z\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"w\", NodeMaterialBlockConnectionPointTypes.Float);\n this.inputsAreExclusive = true;\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"VectorSplitterBlock\";\n }\n /**\n * Gets the xyzw component (input)\n */\n get xyzw() {\n return this._inputs[0];\n }\n /**\n * Gets the xyz component (input)\n */\n get xyzIn() {\n return this._inputs[1];\n }\n /**\n * Gets the xy component (input)\n */\n get xyIn() {\n return this._inputs[2];\n }\n /**\n * Gets the xyz component (output)\n */\n get xyzOut() {\n return this._outputs[0];\n }\n /**\n * Gets the xy component (output)\n */\n get xyOut() {\n return this._outputs[1];\n }\n /**\n * Gets the zw component (output)\n */\n get zw() {\n return this._outputs[2];\n }\n /**\n * Gets the x component (output)\n */\n get x() {\n return this._outputs[3];\n }\n /**\n * Gets the y component (output)\n */\n get y() {\n return this._outputs[4];\n }\n /**\n * Gets the z component (output)\n */\n get z() {\n return this._outputs[5];\n }\n /**\n * Gets the w component (output)\n */\n get w() {\n return this._outputs[6];\n }\n _inputRename(name) {\n switch (name) {\n case \"xy \":\n return \"xyIn\";\n case \"xyz \":\n return \"xyzIn\";\n default:\n return name;\n }\n }\n _outputRename(name) {\n switch (name) {\n case \"xy\":\n return \"xyOut\";\n case \"xyz\":\n return \"xyzOut\";\n default:\n return name;\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const input = this.xyzw.isConnected ? this.xyzw : this.xyzIn.isConnected ? this.xyzIn : this.xyIn;\n const xyzOutput = this._outputs[0];\n const xyOutput = this._outputs[1];\n const zwOutput = this._outputs[2];\n const xOutput = this._outputs[3];\n const yOutput = this._outputs[4];\n const zOutput = this._outputs[5];\n const wOutput = this._outputs[6];\n if (xyzOutput.hasEndpoints) {\n if (input === this.xyIn) {\n state.compilationString += this._declareOutput(xyzOutput, state) + ` = vec3(${input.associatedVariableName}, 0.0);\\r\\n`;\n }\n else {\n state.compilationString += this._declareOutput(xyzOutput, state) + ` = ${input.associatedVariableName}.xyz;\\r\\n`;\n }\n }\n if (zwOutput.hasEndpoints && this.xyzw.isConnected) {\n state.compilationString += this._declareOutput(zwOutput, state) + ` = ${this.xyzw.associatedVariableName}.zw;\\r\\n`;\n }\n if (xyOutput.hasEndpoints) {\n state.compilationString += this._declareOutput(xyOutput, state) + ` = ${input.associatedVariableName}.xy;\\r\\n`;\n }\n if (xOutput.hasEndpoints) {\n state.compilationString += this._declareOutput(xOutput, state) + ` = ${input.associatedVariableName}.x;\\r\\n`;\n }\n if (yOutput.hasEndpoints) {\n state.compilationString += this._declareOutput(yOutput, state) + ` = ${input.associatedVariableName}.y;\\r\\n`;\n }\n if (zOutput.hasEndpoints) {\n state.compilationString += this._declareOutput(zOutput, state) + ` = ${input.associatedVariableName}.z;\\r\\n`;\n }\n if (wOutput.hasEndpoints) {\n state.compilationString += this._declareOutput(wOutput, state) + ` = ${input.associatedVariableName}.w;\\r\\n`;\n }\n return this;\n }\n}\nRegisterClass(\"BABYLON.VectorSplitterBlock\", VectorSplitterBlock);\n//# sourceMappingURL=vectorSplitterBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to lerp between 2 values\n */\nexport class LerpBlock extends NodeMaterialBlock {\n /**\n * Creates a new LerpBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"left\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"right\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"gradient\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._linkConnectionTypes(0, 1);\n this._linkConnectionTypes(1, 2, true);\n this._inputs[2].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"LerpBlock\";\n }\n /**\n * Gets the left operand input component\n */\n get left() {\n return this._inputs[0];\n }\n /**\n * Gets the right operand input component\n */\n get right() {\n return this._inputs[1];\n }\n /**\n * Gets the gradient operand input component\n */\n get gradient() {\n return this._inputs[2];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString +=\n this._declareOutput(output, state) + ` = mix(${this.left.associatedVariableName} , ${this.right.associatedVariableName}, ${this.gradient.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.LerpBlock\", LerpBlock);\n//# sourceMappingURL=lerpBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to step a value\n */\nexport class StepBlock extends NodeMaterialBlock {\n /**\n * Creates a new StepBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"value\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerInput(\"edge\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"StepBlock\";\n }\n /**\n * Gets the value operand input component\n */\n get value() {\n return this._inputs[0];\n }\n /**\n * Gets the edge operand input component\n */\n get edge() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = step(${this.edge.associatedVariableName}, ${this.value.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.StepBlock\", StepBlock);\n//# sourceMappingURL=stepBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to divide 2 vectors\n */\nexport class DivideBlock extends NodeMaterialBlock {\n /**\n * Creates a new DivideBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"left\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"right\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._linkConnectionTypes(0, 1);\n this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"DivideBlock\";\n }\n /**\n * Gets the left operand input component\n */\n get left() {\n return this._inputs[0];\n }\n /**\n * Gets the right operand input component\n */\n get right() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = ${this.left.associatedVariableName} / ${this.right.associatedVariableName};\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.DivideBlock\", DivideBlock);\n//# sourceMappingURL=divideBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to subtract 2 vectors\n */\nexport class SubtractBlock extends NodeMaterialBlock {\n /**\n * Creates a new SubtractBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"left\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"right\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._linkConnectionTypes(0, 1);\n this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"SubtractBlock\";\n }\n /**\n * Gets the left operand input component\n */\n get left() {\n return this._inputs[0];\n }\n /**\n * Gets the right operand input component\n */\n get right() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = ${this.left.associatedVariableName} - ${this.right.associatedVariableName};\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.SubtractBlock\", SubtractBlock);\n//# sourceMappingURL=subtractBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to get the opposite (1 - x) of a value\n */\nexport class OneMinusBlock extends NodeMaterialBlock {\n /**\n * Creates a new OneMinusBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._outputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"OneMinusBlock\";\n }\n /**\n * Gets the input component\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = 1. - ${this.input.associatedVariableName};\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.OneMinusBlock\", OneMinusBlock);\nRegisterClass(\"BABYLON.OppositeBlock\", OneMinusBlock); // Backward compatibility\n//# sourceMappingURL=oneMinusBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { NodeMaterialSystemValues } from \"../Enums/nodeMaterialSystemValues.js\";\nimport { InputBlock } from \"./Input/inputBlock.js\";\n/**\n * Block used to get the view direction\n */\nexport class ViewDirectionBlock extends NodeMaterialBlock {\n /**\n * Creates a new ViewDirectionBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"worldPosition\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerInput(\"cameraPosition\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Vector3);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ViewDirectionBlock\";\n }\n /**\n * Gets the world position component\n */\n get worldPosition() {\n return this._inputs[0];\n }\n /**\n * Gets the camera position component\n */\n get cameraPosition() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n autoConfigure(material) {\n if (!this.cameraPosition.isConnected) {\n let cameraPositionInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.CameraPosition);\n if (!cameraPositionInput) {\n cameraPositionInput = new InputBlock(\"cameraPosition\");\n cameraPositionInput.setAsSystemValue(NodeMaterialSystemValues.CameraPosition);\n }\n cameraPositionInput.output.connectTo(this.cameraPosition);\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString +=\n this._declareOutput(output, state) + ` = normalize(${this.cameraPosition.associatedVariableName} - ${this.worldPosition.associatedVariableName}.xyz);\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.ViewDirectionBlock\", ViewDirectionBlock);\n//# sourceMappingURL=viewDirectionBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { InputBlock } from \"./Input/inputBlock.js\";\nimport \"../../../Shaders/ShadersInclude/fresnelFunction.js\";\nimport { ViewDirectionBlock } from \"./viewDirectionBlock.js\";\n/**\n * Block used to compute fresnel value\n */\nexport class FresnelBlock extends NodeMaterialBlock {\n /**\n * Create a new FresnelBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"worldNormal\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerInput(\"viewDirection\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerInput(\"bias\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerInput(\"power\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"fresnel\", NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"FresnelBlock\";\n }\n /**\n * Gets the world normal input component\n */\n get worldNormal() {\n return this._inputs[0];\n }\n /**\n * Gets the view direction input component\n */\n get viewDirection() {\n return this._inputs[1];\n }\n /**\n * Gets the bias input component\n */\n get bias() {\n return this._inputs[2];\n }\n /**\n * Gets the camera (or eye) position component\n */\n get power() {\n return this._inputs[3];\n }\n /**\n * Gets the fresnel output component\n */\n get fresnel() {\n return this._outputs[0];\n }\n autoConfigure(material) {\n if (!this.viewDirection.isConnected) {\n const viewDirectionInput = new ViewDirectionBlock(\"View direction\");\n viewDirectionInput.output.connectTo(this.viewDirection);\n viewDirectionInput.autoConfigure(material);\n }\n if (!this.bias.isConnected) {\n const biasInput = new InputBlock(\"bias\");\n biasInput.value = 0;\n biasInput.output.connectTo(this.bias);\n }\n if (!this.power.isConnected) {\n const powerInput = new InputBlock(\"power\");\n powerInput.value = 1;\n powerInput.output.connectTo(this.power);\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const comments = `//${this.name}`;\n state._emitFunctionFromInclude(\"fresnelFunction\", comments, { removeIfDef: true });\n state.compilationString +=\n this._declareOutput(this.fresnel, state) +\n ` = computeFresnelTerm(${this.viewDirection.associatedVariableName}.xyz, ${this.worldNormal.associatedVariableName}.xyz, ${this.bias.associatedVariableName}, ${this.power.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.FresnelBlock\", FresnelBlock);\n//# sourceMappingURL=fresnelBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to get the max of 2 values\n */\nexport class MaxBlock extends NodeMaterialBlock {\n /**\n * Creates a new MaxBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"left\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"right\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._linkConnectionTypes(0, 1);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"MaxBlock\";\n }\n /**\n * Gets the left operand input component\n */\n get left() {\n return this._inputs[0];\n }\n /**\n * Gets the right operand input component\n */\n get right() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = max(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.MaxBlock\", MaxBlock);\n//# sourceMappingURL=maxBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to get negative version of a value (i.e. x * -1)\n */\nexport class NegateBlock extends NodeMaterialBlock {\n /**\n * Creates a new NegateBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"value\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"NegateBlock\";\n }\n /**\n * Gets the value input component\n */\n get value() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = -1.0 * ${this.value.associatedVariableName};\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.NegateBlock\", NegateBlock);\n//# sourceMappingURL=negateBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to get the min of 2 values\n */\nexport class MinBlock extends NodeMaterialBlock {\n /**\n * Creates a new MinBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"left\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"right\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._linkConnectionTypes(0, 1);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"MinBlock\";\n }\n /**\n * Gets the left operand input component\n */\n get left() {\n return this._inputs[0];\n }\n /**\n * Gets the right operand input component\n */\n get right() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = min(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.MinBlock\", MinBlock);\n//# sourceMappingURL=minBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to get the distance between 2 values\n */\nexport class DistanceBlock extends NodeMaterialBlock {\n /**\n * Creates a new DistanceBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"left\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"right\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Float);\n this._linkConnectionTypes(0, 1);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"DistanceBlock\";\n }\n /**\n * Gets the left operand input component\n */\n get left() {\n return this._inputs[0];\n }\n /**\n * Gets the right operand input component\n */\n get right() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = length(${this.left.associatedVariableName} - ${this.right.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.DistanceBlock\", DistanceBlock);\n//# sourceMappingURL=distanceBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to get the length of a vector\n */\nexport class LengthBlock extends NodeMaterialBlock {\n /**\n * Creates a new LengthBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"value\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"LengthBlock\";\n }\n /**\n * Gets the value input component\n */\n get value() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = length(${this.value.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.LengthBlock\", LengthBlock);\n//# sourceMappingURL=lengthBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to get the value of the first parameter raised to the power of the second\n */\nexport class PowBlock extends NodeMaterialBlock {\n /**\n * Creates a new PowBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"value\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"power\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._linkConnectionTypes(0, 1);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"PowBlock\";\n }\n /**\n * Gets the value operand input component\n */\n get value() {\n return this._inputs[0];\n }\n /**\n * Gets the power operand input component\n */\n get power() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = pow(${this.value.associatedVariableName}, ${this.power.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.PowBlock\", PowBlock);\n//# sourceMappingURL=powBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport \"../../../Shaders/ShadersInclude/helperFunctions.js\";\n/**\n * Block used to get a random number\n */\nexport class RandomNumberBlock extends NodeMaterialBlock {\n /**\n * Creates a new RandomNumberBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"seed\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector2 |\n NodeMaterialBlockConnectionPointTypes.Vector3 |\n NodeMaterialBlockConnectionPointTypes.Vector4 |\n NodeMaterialBlockConnectionPointTypes.Color3 |\n NodeMaterialBlockConnectionPointTypes.Color4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"RandomNumberBlock\";\n }\n /**\n * Gets the seed input component\n */\n get seed() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n const comments = `//${this.name}`;\n state._emitFunctionFromInclude(\"helperFunctions\", comments);\n state.compilationString += this._declareOutput(output, state) + ` = getRand(${this.seed.associatedVariableName}.xy);\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.RandomNumberBlock\", RandomNumberBlock);\n//# sourceMappingURL=randomNumberBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to compute arc tangent of 2 values\n */\nexport class ArcTan2Block extends NodeMaterialBlock {\n /**\n * Creates a new ArcTan2Block\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"x\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerInput(\"y\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ArcTan2Block\";\n }\n /**\n * Gets the x operand input component\n */\n get x() {\n return this._inputs[0];\n }\n /**\n * Gets the y operand input component\n */\n get y() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = atan(${this.x.associatedVariableName}, ${this.y.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.ArcTan2Block\", ArcTan2Block);\n//# sourceMappingURL=arcTan2Block.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to smooth step a value\n */\nexport class SmoothStepBlock extends NodeMaterialBlock {\n /**\n * Creates a new SmoothStepBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"value\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"edge0\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerInput(\"edge1\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"SmoothStepBlock\";\n }\n /**\n * Gets the value operand input component\n */\n get value() {\n return this._inputs[0];\n }\n /**\n * Gets the first edge operand input component\n */\n get edge0() {\n return this._inputs[1];\n }\n /**\n * Gets the second edge operand input component\n */\n get edge1() {\n return this._inputs[2];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = smoothstep(${this.edge0.associatedVariableName}, ${this.edge1.associatedVariableName}, ${this.value.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.SmoothStepBlock\", SmoothStepBlock);\n//# sourceMappingURL=smoothStepBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to get the reciprocal (1 / x) of a value\n */\nexport class ReciprocalBlock extends NodeMaterialBlock {\n /**\n * Creates a new ReciprocalBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ReciprocalBlock\";\n }\n /**\n * Gets the input component\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n if (this.input.type === NodeMaterialBlockConnectionPointTypes.Matrix) {\n state.compilationString += this._declareOutput(output, state) + ` = inverse(${this.input.associatedVariableName});\\r\\n`;\n }\n else {\n state.compilationString += this._declareOutput(output, state) + ` = 1. / ${this.input.associatedVariableName};\\r\\n`;\n }\n return this;\n }\n}\nRegisterClass(\"BABYLON.ReciprocalBlock\", ReciprocalBlock);\n//# sourceMappingURL=reciprocalBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to replace a color by another one\n */\nexport class ReplaceColorBlock extends NodeMaterialBlock {\n /**\n * Creates a new ReplaceColorBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"value\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"reference\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"distance\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerInput(\"replacement\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._linkConnectionTypes(0, 1);\n this._linkConnectionTypes(0, 3);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n this._inputs[3].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[3].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ReplaceColorBlock\";\n }\n /**\n * Gets the value input component\n */\n get value() {\n return this._inputs[0];\n }\n /**\n * Gets the reference input component\n */\n get reference() {\n return this._inputs[1];\n }\n /**\n * Gets the distance input component\n */\n get distance() {\n return this._inputs[2];\n }\n /**\n * Gets the replacement input component\n */\n get replacement() {\n return this._inputs[3];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + `;\\r\\n`;\n state.compilationString += `if (length(${this.value.associatedVariableName} - ${this.reference.associatedVariableName}) < ${this.distance.associatedVariableName}) {\\r\\n`;\n state.compilationString += `${output.associatedVariableName} = ${this.replacement.associatedVariableName};\\r\\n`;\n state.compilationString += `} else {\\r\\n`;\n state.compilationString += `${output.associatedVariableName} = ${this.value.associatedVariableName};\\r\\n`;\n state.compilationString += `}\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.ReplaceColorBlock\", ReplaceColorBlock);\n//# sourceMappingURL=replaceColorBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to posterize a value\n * @see https://en.wikipedia.org/wiki/Posterization\n */\nexport class PosterizeBlock extends NodeMaterialBlock {\n /**\n * Creates a new PosterizeBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"value\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"steps\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._linkConnectionTypes(0, 1);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"PosterizeBlock\";\n }\n /**\n * Gets the value input component\n */\n get value() {\n return this._inputs[0];\n }\n /**\n * Gets the steps input component\n */\n get steps() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = floor(${this.value.associatedVariableName} / (1.0 / ${this.steps.associatedVariableName})) * (1.0 / ${this.steps.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.PosterizeBlock\", PosterizeBlock);\n//# sourceMappingURL=posterizeBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Operations supported by the Wave block\n */\nexport var WaveBlockKind;\n(function (WaveBlockKind) {\n /** SawTooth */\n WaveBlockKind[WaveBlockKind[\"SawTooth\"] = 0] = \"SawTooth\";\n /** Square */\n WaveBlockKind[WaveBlockKind[\"Square\"] = 1] = \"Square\";\n /** Triangle */\n WaveBlockKind[WaveBlockKind[\"Triangle\"] = 2] = \"Triangle\";\n})(WaveBlockKind || (WaveBlockKind = {}));\n/**\n * Block used to apply wave operation to floats\n */\nexport class WaveBlock extends NodeMaterialBlock {\n /**\n * Creates a new WaveBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n /**\n * Gets or sets the kibnd of wave to be applied by the block\n */\n this.kind = WaveBlockKind.SawTooth;\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"WaveBlock\";\n }\n /**\n * Gets the input component\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n switch (this.kind) {\n case WaveBlockKind.SawTooth: {\n state.compilationString += this._declareOutput(output, state) + ` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName});\\r\\n`;\n break;\n }\n case WaveBlockKind.Square: {\n state.compilationString += this._declareOutput(output, state) + ` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName}));\\r\\n`;\n break;\n }\n case WaveBlockKind.Triangle: {\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0;\\r\\n`;\n break;\n }\n }\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.kind = this.kind;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.kind = serializationObject.kind;\n }\n}\nRegisterClass(\"BABYLON.WaveBlock\", WaveBlock);\n//# sourceMappingURL=waveBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { Color3 } from \"../../../Maths/math.color.js\";\nimport { Observable } from \"../../../Misc/observable.js\";\n/**\n * Class used to store a color step for the GradientBlock\n */\nexport class GradientBlockColorStep {\n /**\n * Gets value indicating which step this color is associated with (between 0 and 1)\n */\n get step() {\n return this._step;\n }\n /**\n * Sets a value indicating which step this color is associated with (between 0 and 1)\n */\n set step(val) {\n this._step = val;\n }\n /**\n * Gets the color associated with this step\n */\n get color() {\n return this._color;\n }\n /**\n * Sets the color associated with this step\n */\n set color(val) {\n this._color = val;\n }\n /**\n * Creates a new GradientBlockColorStep\n * @param step defines a value indicating which step this color is associated with (between 0 and 1)\n * @param color defines the color associated with this step\n */\n constructor(step, color) {\n this.step = step;\n this.color = color;\n }\n}\n/**\n * Block used to return a color from a gradient based on an input value between 0 and 1\n */\nexport class GradientBlock extends NodeMaterialBlock {\n /** calls observable when the value is changed*/\n colorStepsUpdated() {\n this.onValueChangedObservable.notifyObservers(this);\n }\n /**\n * Creates a new GradientBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n /**\n * Gets or sets the list of color steps\n */\n this.colorSteps = [new GradientBlockColorStep(0, Color3.Black()), new GradientBlockColorStep(1.0, Color3.White())];\n /** Gets an observable raised when the value is changed */\n this.onValueChangedObservable = new Observable();\n this.registerInput(\"gradient\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Color3);\n this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Float |\n NodeMaterialBlockConnectionPointTypes.Vector2 |\n NodeMaterialBlockConnectionPointTypes.Vector3 |\n NodeMaterialBlockConnectionPointTypes.Vector4 |\n NodeMaterialBlockConnectionPointTypes.Color3 |\n NodeMaterialBlockConnectionPointTypes.Color4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"GradientBlock\";\n }\n /**\n * Gets the gradient input component\n */\n get gradient() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _writeColorConstant(index) {\n const step = this.colorSteps[index];\n return `vec3(${step.color.r}, ${step.color.g}, ${step.color.b})`;\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n if (!this.colorSteps.length || !this.gradient.connectedPoint) {\n state.compilationString += this._declareOutput(output, state) + ` = vec3(0., 0., 0.);\\r\\n`;\n return;\n }\n const tempColor = state._getFreeVariableName(\"gradientTempColor\");\n const tempPosition = state._getFreeVariableName(\"gradientTempPosition\");\n state.compilationString += `vec3 ${tempColor} = ${this._writeColorConstant(0)};\\r\\n`;\n state.compilationString += `float ${tempPosition};\\r\\n`;\n let gradientSource = this.gradient.associatedVariableName;\n if (this.gradient.connectedPoint.type !== NodeMaterialBlockConnectionPointTypes.Float) {\n gradientSource += \".x\";\n }\n for (let index = 1; index < this.colorSteps.length; index++) {\n const step = this.colorSteps[index];\n const previousStep = this.colorSteps[index - 1];\n state.compilationString += `${tempPosition} = clamp((${gradientSource} - ${state._emitFloat(previousStep.step)}) / (${state._emitFloat(step.step)} - ${state._emitFloat(previousStep.step)}), 0.0, 1.0) * step(${state._emitFloat(index)}, ${state._emitFloat(this.colorSteps.length - 1)});\\r\\n`;\n state.compilationString += `${tempColor} = mix(${tempColor}, ${this._writeColorConstant(index)}, ${tempPosition});\\r\\n`;\n }\n state.compilationString += this._declareOutput(output, state) + ` = ${tempColor};\\r\\n`;\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.colorSteps = [];\n for (const step of this.colorSteps) {\n serializationObject.colorSteps.push({\n step: step.step,\n color: {\n r: step.color.r,\n g: step.color.g,\n b: step.color.b,\n },\n });\n }\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.colorSteps.length = 0;\n for (const step of serializationObject.colorSteps) {\n this.colorSteps.push(new GradientBlockColorStep(step.step, new Color3(step.color.r, step.color.g, step.color.b)));\n }\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n codeString += `${this._codeVariableName}.colorSteps = [];\\r\\n`;\n for (const colorStep of this.colorSteps) {\n codeString += `${this._codeVariableName}.colorSteps.push(new BABYLON.GradientBlockColorStep(${colorStep.step}, new BABYLON.Color3(${colorStep.color.r}, ${colorStep.color.g}, ${colorStep.color.b})));\\r\\n`;\n }\n return codeString;\n }\n}\nRegisterClass(\"BABYLON.GradientBlock\", GradientBlock);\n//# sourceMappingURL=gradientBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to normalize lerp between 2 values\n */\nexport class NLerpBlock extends NodeMaterialBlock {\n /**\n * Creates a new NLerpBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"left\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"right\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"gradient\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._linkConnectionTypes(0, 1);\n this._linkConnectionTypes(1, 2, true);\n this._inputs[2].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"NLerpBlock\";\n }\n /**\n * Gets the left operand input component\n */\n get left() {\n return this._inputs[0];\n }\n /**\n * Gets the right operand input component\n */\n get right() {\n return this._inputs[1];\n }\n /**\n * Gets the gradient operand input component\n */\n get gradient() {\n return this._inputs[2];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = normalize(mix(${this.left.associatedVariableName} , ${this.right.associatedVariableName}, ${this.gradient.associatedVariableName}));\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.NLerpBlock\", NLerpBlock);\n//# sourceMappingURL=nLerpBlock.js.map","import { __decorate } from \"../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../nodeMaterialDecorator.js\";\n/**\n * block used to Generate a Worley Noise 3D Noise Pattern\n */\n// Source: https://github.com/Erkaman/glsl-worley\n// Converted to BJS by Pryme8\n//\n// Worley Noise 3D\n// Return vec2 value range of -1.0->1.0, F1-F2 respectivly\nexport class WorleyNoise3DBlock extends NodeMaterialBlock {\n /**\n * Creates a new WorleyNoise3DBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n /** Gets or sets a boolean indicating that normal should be inverted on X axis */\n this.manhattanDistance = false;\n this.registerInput(\"seed\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerInput(\"jitter\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Vector2);\n this.registerOutput(\"x\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"y\", NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"WorleyNoise3DBlock\";\n }\n /**\n * Gets the seed input component\n */\n get seed() {\n return this._inputs[0];\n }\n /**\n * Gets the jitter input component\n */\n get jitter() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n /**\n * Gets the x component\n */\n get x() {\n return this._outputs[1];\n }\n /**\n * Gets the y component\n */\n get y() {\n return this._outputs[2];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (!this.seed.isConnected) {\n return;\n }\n if (!this.output.hasEndpoints && !this.x.hasEndpoints && !this.y.hasEndpoints) {\n return;\n }\n let functionString = `vec3 permute(vec3 x){\\r\\n`;\n functionString += ` return mod((34.0 * x + 1.0) * x, 289.0);\\r\\n`;\n functionString += `}\\r\\n\\r\\n`;\n functionString += `vec3 dist(vec3 x, vec3 y, vec3 z, bool manhattanDistance){\\r\\n`;\n functionString += ` return manhattanDistance ? abs(x) + abs(y) + abs(z) : (x * x + y * y + z * z);\\r\\n`;\n functionString += `}\\r\\n\\r\\n`;\n functionString += `vec2 worley(vec3 P, float jitter, bool manhattanDistance){\\r\\n`;\n functionString += ` float K = 0.142857142857; // 1/7\\r\\n`;\n functionString += ` float Ko = 0.428571428571; // 1/2-K/2\\r\\n`;\n functionString += ` float K2 = 0.020408163265306; // 1/(7*7)\\r\\n`;\n functionString += ` float Kz = 0.166666666667; // 1/6\\r\\n`;\n functionString += ` float Kzo = 0.416666666667; // 1/2-1/6*2\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 Pi = mod(floor(P), 289.0);\\r\\n`;\n functionString += ` vec3 Pf = fract(P) - 0.5;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 Pfx = Pf.x + vec3(1.0, 0.0, -1.0);\\r\\n`;\n functionString += ` vec3 Pfy = Pf.y + vec3(1.0, 0.0, -1.0);\\r\\n`;\n functionString += ` vec3 Pfz = Pf.z + vec3(1.0, 0.0, -1.0);\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 p = permute(Pi.x + vec3(-1.0, 0.0, 1.0));\\r\\n`;\n functionString += ` vec3 p1 = permute(p + Pi.y - 1.0);\\r\\n`;\n functionString += ` vec3 p2 = permute(p + Pi.y);\\r\\n`;\n functionString += ` vec3 p3 = permute(p + Pi.y + 1.0);\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 p11 = permute(p1 + Pi.z - 1.0);\\r\\n`;\n functionString += ` vec3 p12 = permute(p1 + Pi.z);\\r\\n`;\n functionString += ` vec3 p13 = permute(p1 + Pi.z + 1.0);\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 p21 = permute(p2 + Pi.z - 1.0);\\r\\n`;\n functionString += ` vec3 p22 = permute(p2 + Pi.z);\\r\\n`;\n functionString += ` vec3 p23 = permute(p2 + Pi.z + 1.0);\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 p31 = permute(p3 + Pi.z - 1.0);\\r\\n`;\n functionString += ` vec3 p32 = permute(p3 + Pi.z);\\r\\n`;\n functionString += ` vec3 p33 = permute(p3 + Pi.z + 1.0);\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 ox11 = fract(p11*K) - Ko;\\r\\n`;\n functionString += ` vec3 oy11 = mod(floor(p11*K), 7.0)*K - Ko;\\r\\n`;\n functionString += ` vec3 oz11 = floor(p11*K2)*Kz - Kzo; // p11 < 289 guaranteed\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 ox12 = fract(p12*K) - Ko;\\r\\n`;\n functionString += ` vec3 oy12 = mod(floor(p12*K), 7.0)*K - Ko;\\r\\n`;\n functionString += ` vec3 oz12 = floor(p12*K2)*Kz - Kzo;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 ox13 = fract(p13*K) - Ko;\\r\\n`;\n functionString += ` vec3 oy13 = mod(floor(p13*K), 7.0)*K - Ko;\\r\\n`;\n functionString += ` vec3 oz13 = floor(p13*K2)*Kz - Kzo;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 ox21 = fract(p21*K) - Ko;\\r\\n`;\n functionString += ` vec3 oy21 = mod(floor(p21*K), 7.0)*K - Ko;\\r\\n`;\n functionString += ` vec3 oz21 = floor(p21*K2)*Kz - Kzo;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 ox22 = fract(p22*K) - Ko;\\r\\n`;\n functionString += ` vec3 oy22 = mod(floor(p22*K), 7.0)*K - Ko;\\r\\n`;\n functionString += ` vec3 oz22 = floor(p22*K2)*Kz - Kzo;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 ox23 = fract(p23*K) - Ko;\\r\\n`;\n functionString += ` vec3 oy23 = mod(floor(p23*K), 7.0)*K - Ko;\\r\\n`;\n functionString += ` vec3 oz23 = floor(p23*K2)*Kz - Kzo;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 ox31 = fract(p31*K) - Ko;\\r\\n`;\n functionString += ` vec3 oy31 = mod(floor(p31*K), 7.0)*K - Ko;\\r\\n`;\n functionString += ` vec3 oz31 = floor(p31*K2)*Kz - Kzo;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 ox32 = fract(p32*K) - Ko;\\r\\n`;\n functionString += ` vec3 oy32 = mod(floor(p32*K), 7.0)*K - Ko;\\r\\n`;\n functionString += ` vec3 oz32 = floor(p32*K2)*Kz - Kzo;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 ox33 = fract(p33*K) - Ko;\\r\\n`;\n functionString += ` vec3 oy33 = mod(floor(p33*K), 7.0)*K - Ko;\\r\\n`;\n functionString += ` vec3 oz33 = floor(p33*K2)*Kz - Kzo;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 dx11 = Pfx + jitter*ox11;\\r\\n`;\n functionString += ` vec3 dy11 = Pfy.x + jitter*oy11;\\r\\n`;\n functionString += ` vec3 dz11 = Pfz.x + jitter*oz11;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 dx12 = Pfx + jitter*ox12;\\r\\n`;\n functionString += ` vec3 dy12 = Pfy.x + jitter*oy12;\\r\\n`;\n functionString += ` vec3 dz12 = Pfz.y + jitter*oz12;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 dx13 = Pfx + jitter*ox13;\\r\\n`;\n functionString += ` vec3 dy13 = Pfy.x + jitter*oy13;\\r\\n`;\n functionString += ` vec3 dz13 = Pfz.z + jitter*oz13;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 dx21 = Pfx + jitter*ox21;\\r\\n`;\n functionString += ` vec3 dy21 = Pfy.y + jitter*oy21;\\r\\n`;\n functionString += ` vec3 dz21 = Pfz.x + jitter*oz21;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 dx22 = Pfx + jitter*ox22;\\r\\n`;\n functionString += ` vec3 dy22 = Pfy.y + jitter*oy22;\\r\\n`;\n functionString += ` vec3 dz22 = Pfz.y + jitter*oz22;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 dx23 = Pfx + jitter*ox23;\\r\\n`;\n functionString += ` vec3 dy23 = Pfy.y + jitter*oy23;\\r\\n`;\n functionString += ` vec3 dz23 = Pfz.z + jitter*oz23;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 dx31 = Pfx + jitter*ox31;\\r\\n`;\n functionString += ` vec3 dy31 = Pfy.z + jitter*oy31;\\r\\n`;\n functionString += ` vec3 dz31 = Pfz.x + jitter*oz31;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 dx32 = Pfx + jitter*ox32;\\r\\n`;\n functionString += ` vec3 dy32 = Pfy.z + jitter*oy32;\\r\\n`;\n functionString += ` vec3 dz32 = Pfz.y + jitter*oz32;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 dx33 = Pfx + jitter*ox33;\\r\\n`;\n functionString += ` vec3 dy33 = Pfy.z + jitter*oy33;\\r\\n`;\n functionString += ` vec3 dz33 = Pfz.z + jitter*oz33;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 d11 = dist(dx11, dy11, dz11, manhattanDistance);\\r\\n`;\n functionString += ` vec3 d12 =dist(dx12, dy12, dz12, manhattanDistance);\\r\\n`;\n functionString += ` vec3 d13 = dist(dx13, dy13, dz13, manhattanDistance);\\r\\n`;\n functionString += ` vec3 d21 = dist(dx21, dy21, dz21, manhattanDistance);\\r\\n`;\n functionString += ` vec3 d22 = dist(dx22, dy22, dz22, manhattanDistance);\\r\\n`;\n functionString += ` vec3 d23 = dist(dx23, dy23, dz23, manhattanDistance);\\r\\n`;\n functionString += ` vec3 d31 = dist(dx31, dy31, dz31, manhattanDistance);\\r\\n`;\n functionString += ` vec3 d32 = dist(dx32, dy32, dz32, manhattanDistance);\\r\\n`;\n functionString += ` vec3 d33 = dist(dx33, dy33, dz33, manhattanDistance);\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 d1a = min(d11, d12);\\r\\n`;\n functionString += ` d12 = max(d11, d12);\\r\\n`;\n functionString += ` d11 = min(d1a, d13); // Smallest now not in d12 or d13\\r\\n`;\n functionString += ` d13 = max(d1a, d13);\\r\\n`;\n functionString += ` d12 = min(d12, d13); // 2nd smallest now not in d13\\r\\n`;\n functionString += ` vec3 d2a = min(d21, d22);\\r\\n`;\n functionString += ` d22 = max(d21, d22);\\r\\n`;\n functionString += ` d21 = min(d2a, d23); // Smallest now not in d22 or d23\\r\\n`;\n functionString += ` d23 = max(d2a, d23);\\r\\n`;\n functionString += ` d22 = min(d22, d23); // 2nd smallest now not in d23\\r\\n`;\n functionString += ` vec3 d3a = min(d31, d32);\\r\\n`;\n functionString += ` d32 = max(d31, d32);\\r\\n`;\n functionString += ` d31 = min(d3a, d33); // Smallest now not in d32 or d33\\r\\n`;\n functionString += ` d33 = max(d3a, d33);\\r\\n`;\n functionString += ` d32 = min(d32, d33); // 2nd smallest now not in d33\\r\\n`;\n functionString += ` vec3 da = min(d11, d21);\\r\\n`;\n functionString += ` d21 = max(d11, d21);\\r\\n`;\n functionString += ` d11 = min(da, d31); // Smallest now in d11\\r\\n`;\n functionString += ` d31 = max(da, d31); // 2nd smallest now not in d31\\r\\n`;\n functionString += ` d11.xy = (d11.x < d11.y) ? d11.xy : d11.yx;\\r\\n`;\n functionString += ` d11.xz = (d11.x < d11.z) ? d11.xz : d11.zx; // d11.x now smallest\\r\\n`;\n functionString += ` d12 = min(d12, d21); // 2nd smallest now not in d21\\r\\n`;\n functionString += ` d12 = min(d12, d22); // nor in d22\\r\\n`;\n functionString += ` d12 = min(d12, d31); // nor in d31\\r\\n`;\n functionString += ` d12 = min(d12, d32); // nor in d32\\r\\n`;\n functionString += ` d11.yz = min(d11.yz,d12.xy); // nor in d12.yz\\r\\n`;\n functionString += ` d11.y = min(d11.y,d12.z); // Only two more to go\\r\\n`;\n functionString += ` d11.y = min(d11.y,d11.z); // Done! (Phew!)\\r\\n`;\n functionString += ` return sqrt(d11.xy); // F1, F2\\r\\n`;\n functionString += `}\\r\\n\\r\\n`;\n state._emitFunction(\"worley3D\", functionString, \"// Worley3D\");\n const tempVariable = state._getFreeVariableName(\"worleyTemp\");\n state.compilationString += `vec2 ${tempVariable} = worley(${this.seed.associatedVariableName}, ${this.jitter.associatedVariableName}, ${this.manhattanDistance});\\r\\n`;\n if (this.output.hasEndpoints) {\n state.compilationString += this._declareOutput(this.output, state) + ` = ${tempVariable};\\r\\n`;\n }\n if (this.x.hasEndpoints) {\n state.compilationString += this._declareOutput(this.x, state) + ` = ${tempVariable}.x;\\r\\n`;\n }\n if (this.y.hasEndpoints) {\n state.compilationString += this._declareOutput(this.y, state) + ` = ${tempVariable}.y;\\r\\n`;\n }\n return this;\n }\n /**\n * Exposes the properties to the UI?\n */\n _dumpPropertiesCode() {\n const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.manhattanDistance = ${this.manhattanDistance};\\r\\n`;\n return codeString;\n }\n /**\n * Exposes the properties to the Serialize?\n */\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.manhattanDistance = this.manhattanDistance;\n return serializationObject;\n }\n /**\n * Exposes the properties to the deserialize?\n * @param serializationObject\n * @param scene\n * @param rootUrl\n */\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.manhattanDistance = serializationObject.manhattanDistance;\n }\n}\n__decorate([\n editableInPropertyPage(\"Use Manhattan Distance\", PropertyTypeForEdition.Boolean, \"PROPERTIES\", { notifiers: { update: false } })\n], WorleyNoise3DBlock.prototype, \"manhattanDistance\", void 0);\nRegisterClass(\"BABYLON.WorleyNoise3DBlock\", WorleyNoise3DBlock);\n//# sourceMappingURL=worleyNoise3DBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * block used to Generate a Simplex Perlin 3d Noise Pattern\n */\n//\n// Wombat\n// An efficient texture-free GLSL procedural noise library\n// Source: https://github.com/BrianSharpe/Wombat\n// Derived from: https://github.com/BrianSharpe/GPU-Noise-Lib\n//\n// I'm not one for copyrights. Use the code however you wish.\n// All I ask is that credit be given back to the blog or myself when appropriate.\n// And also to let me know if you come up with any changes, improvements, thoughts or interesting uses for this stuff. :)\n// Thanks!\n//\n// Brian Sharpe\n// brisharpe CIRCLE_A yahoo DOT com\n// http://briansharpe.wordpress.com\n// https://github.com/BrianSharpe\n//\n//\n// This is a modified version of Stefan Gustavson's and Ian McEwan's work at http://github.com/ashima/webgl-noise\n// Modifications are...\n// - faster random number generation\n// - analytical final normalization\n// - space scaled can have an approx feature size of 1.0\n// - filter kernel changed to fix discontinuities at tetrahedron boundaries\n//\n// Converted to BJS by Pryme8\n//\n// Simplex Perlin Noise 3D\n// Return value range of -1.0->1.0\n//\nexport class SimplexPerlin3DBlock extends NodeMaterialBlock {\n /**\n * Creates a new SimplexPerlin3DBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"seed\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"SimplexPerlin3DBlock\";\n }\n /**\n * Gets the seed operand input component\n */\n get seed() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (!this.seed.isConnected) {\n return;\n }\n if (!this._outputs[0].hasEndpoints) {\n return;\n }\n let functionString = `const float SKEWFACTOR = 1.0/3.0;\\r\\n`;\n functionString += `const float UNSKEWFACTOR = 1.0/6.0;\\r\\n`;\n functionString += `const float SIMPLEX_CORNER_POS = 0.5;\\r\\n`;\n functionString += `const float SIMPLEX_TETRAHADRON_HEIGHT = 0.70710678118654752440084436210485;\\r\\n`;\n functionString += `float SimplexPerlin3D( vec3 P ){\\r\\n`;\n functionString += ` P.x = P == vec3(0., 0., 0.) ? 0.00001 : P.x;\\r\\n`;\n functionString += ` P *= SIMPLEX_TETRAHADRON_HEIGHT;\\r\\n`;\n functionString += ` vec3 Pi = floor( P + dot( P, vec3( SKEWFACTOR) ) );`;\n functionString += ` vec3 x0 = P - Pi + dot(Pi, vec3( UNSKEWFACTOR ) );\\r\\n`;\n functionString += ` vec3 g = step(x0.yzx, x0.xyz);\\r\\n`;\n functionString += ` vec3 l = 1.0 - g;\\r\\n`;\n functionString += ` vec3 Pi_1 = min( g.xyz, l.zxy );\\r\\n`;\n functionString += ` vec3 Pi_2 = max( g.xyz, l.zxy );\\r\\n`;\n functionString += ` vec3 x1 = x0 - Pi_1 + UNSKEWFACTOR;\\r\\n`;\n functionString += ` vec3 x2 = x0 - Pi_2 + SKEWFACTOR;\\r\\n`;\n functionString += ` vec3 x3 = x0 - SIMPLEX_CORNER_POS;\\r\\n`;\n functionString += ` vec4 v1234_x = vec4( x0.x, x1.x, x2.x, x3.x );\\r\\n`;\n functionString += ` vec4 v1234_y = vec4( x0.y, x1.y, x2.y, x3.y );\\r\\n`;\n functionString += ` vec4 v1234_z = vec4( x0.z, x1.z, x2.z, x3.z );\\r\\n`;\n functionString += ` Pi.xyz = Pi.xyz - floor(Pi.xyz * ( 1.0 / 69.0 )) * 69.0;\\r\\n`;\n functionString += ` vec3 Pi_inc1 = step( Pi, vec3( 69.0 - 1.5 ) ) * ( Pi + 1.0 );\\r\\n`;\n functionString += ` vec4 Pt = vec4( Pi.xy, Pi_inc1.xy ) + vec2( 50.0, 161.0 ).xyxy;\\r\\n`;\n functionString += ` Pt *= Pt;\\r\\n`;\n functionString += ` vec4 V1xy_V2xy = mix( Pt.xyxy, Pt.zwzw, vec4( Pi_1.xy, Pi_2.xy ) );\\r\\n`;\n functionString += ` Pt = vec4( Pt.x, V1xy_V2xy.xz, Pt.z ) * vec4( Pt.y, V1xy_V2xy.yw, Pt.w );\\r\\n`;\n functionString += ` const vec3 SOMELARGEFLOATS = vec3( 635.298681, 682.357502, 668.926525 );\\r\\n`;\n functionString += ` const vec3 ZINC = vec3( 48.500388, 65.294118, 63.934599 );\\r\\n`;\n functionString += ` vec3 lowz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi.zzz * ZINC.xyz ) );\\r\\n`;\n functionString += ` vec3 highz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi_inc1.zzz * ZINC.xyz ) );\\r\\n`;\n functionString += ` Pi_1 = ( Pi_1.z < 0.5 ) ? lowz_mods : highz_mods;\\r\\n`;\n functionString += ` Pi_2 = ( Pi_2.z < 0.5 ) ? lowz_mods : highz_mods;\\r\\n`;\n functionString += ` vec4 hash_0 = fract( Pt * vec4( lowz_mods.x, Pi_1.x, Pi_2.x, highz_mods.x ) ) - 0.49999;\\r\\n`;\n functionString += ` vec4 hash_1 = fract( Pt * vec4( lowz_mods.y, Pi_1.y, Pi_2.y, highz_mods.y ) ) - 0.49999;\\r\\n`;\n functionString += ` vec4 hash_2 = fract( Pt * vec4( lowz_mods.z, Pi_1.z, Pi_2.z, highz_mods.z ) ) - 0.49999;\\r\\n`;\n functionString += ` vec4 grad_results = inversesqrt( hash_0 * hash_0 + hash_1 * hash_1 + hash_2 * hash_2 ) * ( hash_0 * v1234_x + hash_1 * v1234_y + hash_2 * v1234_z );\\r\\n`;\n functionString += ` const float FINAL_NORMALIZATION = 37.837227241611314102871574478976;\\r\\n`;\n functionString += ` vec4 kernel_weights = v1234_x * v1234_x + v1234_y * v1234_y + v1234_z * v1234_z;\\r\\n`;\n functionString += ` kernel_weights = max(0.5 - kernel_weights, 0.0);\\r\\n`;\n functionString += ` kernel_weights = kernel_weights*kernel_weights*kernel_weights;\\r\\n`;\n functionString += ` return dot( kernel_weights, grad_results ) * FINAL_NORMALIZATION;\\r\\n`;\n functionString += `}\\r\\n`;\n state._emitFunction(\"SimplexPerlin3D\", functionString, \"// SimplexPerlin3D\");\n state.compilationString += this._declareOutput(this._outputs[0], state) + ` = SimplexPerlin3D(${this.seed.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.SimplexPerlin3DBlock\", SimplexPerlin3DBlock);\n//# sourceMappingURL=simplexPerlin3DBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to blend normals\n */\nexport class NormalBlendBlock extends NodeMaterialBlock {\n /**\n * Creates a new NormalBlendBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"normalMap0\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"normalMap1\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 |\n NodeMaterialBlockConnectionPointTypes.Color4 |\n NodeMaterialBlockConnectionPointTypes.Vector3 |\n NodeMaterialBlockConnectionPointTypes.Vector4);\n this._inputs[1].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 |\n NodeMaterialBlockConnectionPointTypes.Color4 |\n NodeMaterialBlockConnectionPointTypes.Vector3 |\n NodeMaterialBlockConnectionPointTypes.Vector4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"NormalBlendBlock\";\n }\n /**\n * Gets the first input component\n */\n get normalMap0() {\n return this._inputs[0];\n }\n /**\n * Gets the second input component\n */\n get normalMap1() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n const input0 = this._inputs[0];\n const input1 = this._inputs[1];\n const stepR = state._getFreeVariableName(\"stepR\");\n const stepG = state._getFreeVariableName(\"stepG\");\n state.compilationString += `float ${stepR} = step(0.5, ${input0.associatedVariableName}.r);\\r\\n`;\n state.compilationString += `float ${stepG} = step(0.5, ${input0.associatedVariableName}.g);\\r\\n`;\n state.compilationString += this._declareOutput(output, state) + `;\\r\\n`;\n state.compilationString += `${output.associatedVariableName}.r = (1.0 - ${stepR}) * ${input0.associatedVariableName}.r * ${input1.associatedVariableName}.r * 2.0 + ${stepR} * (1.0 - (1.0 - ${input0.associatedVariableName}.r) * (1.0 - ${input1.associatedVariableName}.r) * 2.0);\\r\\n`;\n state.compilationString += `${output.associatedVariableName}.g = (1.0 - ${stepG}) * ${input0.associatedVariableName}.g * ${input1.associatedVariableName}.g * 2.0 + ${stepG} * (1.0 - (1.0 - ${input0.associatedVariableName}.g) * (1.0 - ${input1.associatedVariableName}.g) * 2.0);\\r\\n`;\n state.compilationString += `${output.associatedVariableName}.b = ${input0.associatedVariableName}.b * ${input1.associatedVariableName}.b;\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.NormalBlendBlock\", NormalBlendBlock);\n//# sourceMappingURL=normalBlendBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { InputBlock } from \"./Input/inputBlock.js\";\n/**\n * Block used to rotate a 2d vector by a given angle\n */\nexport class Rotate2dBlock extends NodeMaterialBlock {\n /**\n * Creates a new Rotate2dBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.Vector2);\n this.registerInput(\"angle\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Vector2);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"Rotate2dBlock\";\n }\n /**\n * Gets the input vector\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the input angle\n */\n get angle() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n autoConfigure() {\n if (!this.angle.isConnected) {\n const angleInput = new InputBlock(\"angle\");\n angleInput.value = 0;\n angleInput.output.connectTo(this.angle);\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n const angle = this.angle;\n const input = this.input;\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = vec2(cos(${angle.associatedVariableName}) * ${input.associatedVariableName}.x - sin(${angle.associatedVariableName}) * ${input.associatedVariableName}.y, sin(${angle.associatedVariableName}) * ${input.associatedVariableName}.x + cos(${angle.associatedVariableName}) * ${input.associatedVariableName}.y);\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.Rotate2dBlock\", Rotate2dBlock);\n//# sourceMappingURL=rotate2dBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to get the reflected vector from a direction and a normal\n */\nexport class ReflectBlock extends NodeMaterialBlock {\n /**\n * Creates a new ReflectBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"incident\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"normal\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 |\n NodeMaterialBlockConnectionPointTypes.Vector4 |\n NodeMaterialBlockConnectionPointTypes.Color3 |\n NodeMaterialBlockConnectionPointTypes.Color4);\n this._inputs[1].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 |\n NodeMaterialBlockConnectionPointTypes.Vector4 |\n NodeMaterialBlockConnectionPointTypes.Color3 |\n NodeMaterialBlockConnectionPointTypes.Color4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ReflectBlock\";\n }\n /**\n * Gets the incident component\n */\n get incident() {\n return this._inputs[0];\n }\n /**\n * Gets the normal component\n */\n get normal() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = reflect(${this.incident.associatedVariableName}.xyz, ${this.normal.associatedVariableName}.xyz);\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.ReflectBlock\", ReflectBlock);\n//# sourceMappingURL=reflectBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to get the refracted vector from a direction and a normal\n */\nexport class RefractBlock extends NodeMaterialBlock {\n /**\n * Creates a new RefractBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"incident\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"normal\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"ior\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 |\n NodeMaterialBlockConnectionPointTypes.Vector4 |\n NodeMaterialBlockConnectionPointTypes.Color3 |\n NodeMaterialBlockConnectionPointTypes.Color4);\n this._inputs[1].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 |\n NodeMaterialBlockConnectionPointTypes.Vector4 |\n NodeMaterialBlockConnectionPointTypes.Color3 |\n NodeMaterialBlockConnectionPointTypes.Color4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"RefractBlock\";\n }\n /**\n * Gets the incident component\n */\n get incident() {\n return this._inputs[0];\n }\n /**\n * Gets the normal component\n */\n get normal() {\n return this._inputs[1];\n }\n /**\n * Gets the index of refraction component\n */\n get ior() {\n return this._inputs[2];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = refract(${this.incident.associatedVariableName}.xyz, ${this.normal.associatedVariableName}.xyz, ${this.ior.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.RefractBlock\", RefractBlock);\n//# sourceMappingURL=refractBlock.js.map","import { __decorate } from \"../../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../../nodeMaterialBlockConnectionPoint.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../../nodeMaterialDecorator.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../../nodeMaterialConnectionPointCustomObject.js\";\n/**\n * Block used to implement the sheen module of the PBR material\n */\nexport class SheenBlock extends NodeMaterialBlock {\n /**\n * Create a new SheenBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n /**\n * If true, the sheen effect is layered above the base BRDF with the albedo-scaling technique.\n * It allows the strength of the sheen effect to not depend on the base color of the material,\n * making it easier to setup and tweak the effect\n */\n this.albedoScaling = false;\n /**\n * Defines if the sheen is linked to the sheen color.\n */\n this.linkSheenWithAlbedo = false;\n this._isUnique = true;\n this.registerInput(\"intensity\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"color\", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"roughness\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"sheen\", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"sheen\", this, NodeMaterialConnectionPointDirection.Output, SheenBlock, \"SheenBlock\"));\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"sheenOut\");\n state._excludeVariableName(\"sheenMapData\");\n state._excludeVariableName(\"vSheenColor\");\n state._excludeVariableName(\"vSheenRoughness\");\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"SheenBlock\";\n }\n /**\n * Gets the intensity input component\n */\n get intensity() {\n return this._inputs[0];\n }\n /**\n * Gets the color input component\n */\n get color() {\n return this._inputs[1];\n }\n /**\n * Gets the roughness input component\n */\n get roughness() {\n return this._inputs[2];\n }\n /**\n * Gets the sheen object output component\n */\n get sheen() {\n return this._outputs[0];\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n super.prepareDefines(mesh, nodeMaterial, defines);\n defines.setValue(\"SHEEN\", true);\n defines.setValue(\"SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE\", true, true);\n defines.setValue(\"SHEEN_LINKWITHALBEDO\", this.linkSheenWithAlbedo, true);\n defines.setValue(\"SHEEN_ROUGHNESS\", this.roughness.isConnected, true);\n defines.setValue(\"SHEEN_ALBEDOSCALING\", this.albedoScaling, true);\n }\n /**\n * Gets the main code of the block (fragment side)\n * @param reflectionBlock instance of a ReflectionBlock null if the code must be generated without an active reflection module\n * @returns the shader code\n */\n getCode(reflectionBlock) {\n let code = \"\";\n const color = this.color.isConnected ? this.color.associatedVariableName : \"vec3(1.)\";\n const intensity = this.intensity.isConnected ? this.intensity.associatedVariableName : \"1.\";\n const roughness = this.roughness.isConnected ? this.roughness.associatedVariableName : \"0.\";\n const texture = \"vec4(0.)\";\n code = `#ifdef SHEEN\r\n sheenOutParams sheenOut;\r\n\r\n vec4 vSheenColor = vec4(${color}, ${intensity});\r\n\r\n sheenBlock(\r\n vSheenColor,\r\n #ifdef SHEEN_ROUGHNESS\r\n ${roughness},\r\n #endif\r\n roughness,\r\n #ifdef SHEEN_TEXTURE\r\n ${texture},\r\n 1.0,\r\n #endif\r\n reflectance,\r\n #ifdef SHEEN_LINKWITHALBEDO\r\n baseColor,\r\n surfaceAlbedo,\r\n #endif\r\n #ifdef ENVIRONMENTBRDF\r\n NdotV,\r\n environmentBrdf,\r\n #endif\r\n #if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\r\n AARoughnessFactors,\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._vReflectionMicrosurfaceInfosName},\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._vReflectionInfosName},\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock.reflectionColor},\r\n vLightingIntensity,\r\n #ifdef ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName}\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName},\r\n #else\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._2DSamplerName},\r\n #endif\r\n reflectionOut.reflectionCoords,\r\n NdotVUnclamped,\r\n #ifndef LODBASEDMICROSFURACE\r\n #ifdef ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName}\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName},\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName},\r\n #else\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._2DSamplerName},\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._2DSamplerName},\r\n #endif\r\n #endif\r\n #if !defined(${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName}) && defined(RADIANCEOCCLUSION)\r\n seo,\r\n #endif\r\n #if !defined(${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName}) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName})\r\n eho,\r\n #endif\r\n #endif\r\n sheenOut\r\n );\r\n\r\n #ifdef SHEEN_LINKWITHALBEDO\r\n surfaceAlbedo = sheenOut.surfaceAlbedo;\r\n #endif\r\n #endif\\r\\n`;\n return code;\n }\n _buildBlock(state) {\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n state.sharedData.blocksWithDefines.push(this);\n }\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n codeString += `${this._codeVariableName}.albedoScaling = ${this.albedoScaling};\\r\\n`;\n codeString += `${this._codeVariableName}.linkSheenWithAlbedo = ${this.linkSheenWithAlbedo};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.albedoScaling = this.albedoScaling;\n serializationObject.linkSheenWithAlbedo = this.linkSheenWithAlbedo;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.albedoScaling = serializationObject.albedoScaling;\n this.linkSheenWithAlbedo = serializationObject.linkSheenWithAlbedo;\n }\n}\n__decorate([\n editableInPropertyPage(\"Albedo scaling\", PropertyTypeForEdition.Boolean, \"PROPERTIES\", { notifiers: { update: true } })\n], SheenBlock.prototype, \"albedoScaling\", void 0);\n__decorate([\n editableInPropertyPage(\"Link sheen with albedo\", PropertyTypeForEdition.Boolean, \"PROPERTIES\", { notifiers: { update: true } })\n], SheenBlock.prototype, \"linkSheenWithAlbedo\", void 0);\nRegisterClass(\"BABYLON.SheenBlock\", SheenBlock);\n//# sourceMappingURL=sheenBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to desaturate a color\n */\nexport class DesaturateBlock extends NodeMaterialBlock {\n /**\n * Creates a new DesaturateBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"color\", NodeMaterialBlockConnectionPointTypes.Color3);\n this.registerInput(\"level\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Color3);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"DesaturateBlock\";\n }\n /**\n * Gets the color operand input component\n */\n get color() {\n return this._inputs[0];\n }\n /**\n * Gets the level operand input component\n */\n get level() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n const color = this.color;\n const colorName = color.associatedVariableName;\n const tempMin = state._getFreeVariableName(\"colorMin\");\n const tempMax = state._getFreeVariableName(\"colorMax\");\n const tempMerge = state._getFreeVariableName(\"colorMerge\");\n state.compilationString += `float ${tempMin} = min(min(${colorName}.x, ${colorName}.y), ${colorName}.z);\\r\\n`;\n state.compilationString += `float ${tempMax} = max(max(${colorName}.x, ${colorName}.y), ${colorName}.z);\\r\\n`;\n state.compilationString += `float ${tempMerge} = 0.5 * (${tempMin} + ${tempMax});\\r\\n`;\n state.compilationString +=\n this._declareOutput(output, state) + ` = mix(${colorName}, vec3(${tempMerge}, ${tempMerge}, ${tempMerge}), ${this.level.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.DesaturateBlock\", DesaturateBlock);\n//# sourceMappingURL=desaturateBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../../nodeMaterialBlockConnectionPoint.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../../nodeMaterialConnectionPointCustomObject.js\";\nimport { TBNBlock } from \"../Fragment/TBNBlock.js\";\n/**\n * Block used to implement the anisotropy module of the PBR material\n */\nexport class AnisotropyBlock extends NodeMaterialBlock {\n /**\n * Create a new AnisotropyBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this._tangentCorrectionFactorName = \"\";\n this._isUnique = true;\n this.registerInput(\"intensity\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"direction\", NodeMaterialBlockConnectionPointTypes.Vector2, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"uv\", NodeMaterialBlockConnectionPointTypes.Vector2, true); // need this property and the next one in case there's no PerturbNormal block connected to the main PBR block\n this.registerInput(\"worldTangent\", NodeMaterialBlockConnectionPointTypes.Vector4, true);\n this.registerInput(\"TBN\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject(\"TBN\", this, NodeMaterialConnectionPointDirection.Input, TBNBlock, \"TBNBlock\"));\n this.registerInput(\"roughness\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"anisotropy\", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"anisotropy\", this, NodeMaterialConnectionPointDirection.Output, AnisotropyBlock, \"AnisotropyBlock\"));\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"anisotropicOut\");\n state._excludeVariableName(\"TBN\");\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"AnisotropyBlock\";\n }\n /**\n * Gets the intensity input component\n */\n get intensity() {\n return this._inputs[0];\n }\n /**\n * Gets the direction input component\n */\n get direction() {\n return this._inputs[1];\n }\n /**\n * Gets the uv input component\n */\n get uv() {\n return this._inputs[2];\n }\n /**\n * Gets the worldTangent input component\n */\n get worldTangent() {\n return this._inputs[3];\n }\n /**\n * Gets the TBN input component\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n get TBN() {\n return this._inputs[4];\n }\n /**\n * Gets the roughness input component\n */\n get roughness() {\n return this._inputs[5];\n }\n /**\n * Gets the anisotropy object output component\n */\n get anisotropy() {\n return this._outputs[0];\n }\n _generateTBNSpace(state) {\n let code = \"\";\n const comments = `//${this.name}`;\n const uv = this.uv;\n const worldPosition = this.worldPositionConnectionPoint;\n const worldNormal = this.worldNormalConnectionPoint;\n const worldTangent = this.worldTangent;\n if (!uv.isConnected) {\n // we must set the uv input as optional because we may not end up in this method (in case a PerturbNormal block is linked to the PBR material)\n // in which case uv is not required. But if we do come here, we do need the uv, so we have to raise an error but not with throw, else\n // it will stop the building of the node material and will lead to errors in the editor!\n console.error(\"You must connect the 'uv' input of the Anisotropy block!\");\n }\n state._emitExtension(\"derivatives\", \"#extension GL_OES_standard_derivatives : enable\");\n const tangentReplaceString = { search: /defined\\(TANGENT\\)/g, replace: worldTangent.isConnected ? \"defined(TANGENT)\" : \"defined(IGNORE)\" };\n const TBN = this.TBN;\n if (TBN.isConnected) {\n state.compilationString += `\r\n #ifdef TBNBLOCK\r\n mat3 vTBN = ${TBN.associatedVariableName};\r\n #endif\r\n `;\n }\n else if (worldTangent.isConnected) {\n code += `vec3 tbnNormal = normalize(${worldNormal.associatedVariableName}.xyz);\\r\\n`;\n code += `vec3 tbnTangent = normalize(${worldTangent.associatedVariableName}.xyz);\\r\\n`;\n code += `vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};\\r\\n`;\n code += `mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\\r\\n`;\n }\n code += `\r\n #if defined(${worldTangent.isConnected ? \"TANGENT\" : \"IGNORE\"}) && defined(NORMAL)\r\n mat3 TBN = vTBN;\r\n #else\r\n mat3 TBN = cotangent_frame(${worldNormal.associatedVariableName + \".xyz\"}, ${\"v_\" + worldPosition.associatedVariableName + \".xyz\"}, ${uv.isConnected ? uv.associatedVariableName : \"vec2(0.)\"}, vec2(1., 1.));\r\n #endif\\r\\n`;\n state._emitFunctionFromInclude(\"bumpFragmentMainFunctions\", comments, {\n replaceStrings: [tangentReplaceString],\n });\n return code;\n }\n /**\n * Gets the main code of the block (fragment side)\n * @param state current state of the node material building\n * @param generateTBNSpace if true, the code needed to create the TBN coordinate space is generated\n * @returns the shader code\n */\n getCode(state, generateTBNSpace = false) {\n let code = \"\";\n if (generateTBNSpace) {\n code += this._generateTBNSpace(state);\n }\n const intensity = this.intensity.isConnected ? this.intensity.associatedVariableName : \"1.0\";\n const direction = this.direction.isConnected ? this.direction.associatedVariableName : \"vec2(1., 0.)\";\n const roughness = this.roughness.isConnected ? this.roughness.associatedVariableName : \"0.\";\n code += `anisotropicOutParams anisotropicOut;\r\n anisotropicBlock(\r\n vec3(${direction}, ${intensity}),\r\n ${roughness},\r\n #ifdef ANISOTROPIC_TEXTURE\r\n vec3(0.),\r\n #endif\r\n TBN,\r\n normalW,\r\n viewDirectionW,\r\n anisotropicOut\r\n );\\r\\n`;\n return code;\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n super.prepareDefines(mesh, nodeMaterial, defines);\n defines.setValue(\"ANISOTROPIC\", true);\n defines.setValue(\"ANISOTROPIC_TEXTURE\", false, true);\n defines.setValue(\"ANISOTROPIC_LEGACY\", !this.roughness.isConnected);\n }\n bind(effect, nodeMaterial, mesh) {\n super.bind(effect, nodeMaterial, mesh);\n if (mesh) {\n effect.setFloat(this._tangentCorrectionFactorName, mesh.getWorldMatrix().determinant() < 0 ? -1 : 1);\n }\n }\n _buildBlock(state) {\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n state.sharedData.blocksWithDefines.push(this);\n state.sharedData.bindableBlocks.push(this);\n this._tangentCorrectionFactorName = state._getFreeDefineName(\"tangentCorrectionFactor\");\n state._emitUniformFromString(this._tangentCorrectionFactorName, \"float\");\n }\n return this;\n }\n}\nRegisterClass(\"BABYLON.AnisotropyBlock\", AnisotropyBlock);\n//# sourceMappingURL=anisotropyBlock.js.map","import { __decorate } from \"../../../../tslib.es6.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../../nodeMaterialBlockConnectionPoint.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../../nodeMaterialConnectionPointCustomObject.js\";\nimport { ReflectionTextureBaseBlock } from \"../Dual/reflectionTextureBaseBlock.js\";\nimport { Texture } from \"../../../Textures/texture.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../../nodeMaterialDecorator.js\";\nimport { Scalar } from \"../../../../Maths/math.scalar.js\";\n/**\n * Block used to implement the reflection module of the PBR material\n */\nexport class ReflectionBlock extends ReflectionTextureBaseBlock {\n _onGenerateOnlyFragmentCodeChanged() {\n if (this.position.isConnected) {\n this.generateOnlyFragmentCode = !this.generateOnlyFragmentCode;\n console.error(\"The position input must not be connected to be able to switch!\");\n return false;\n }\n this._setTarget();\n return true;\n }\n _setTarget() {\n super._setTarget();\n this.getInputByName(\"position\").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex;\n if (this.generateOnlyFragmentCode) {\n this.forceIrradianceInFragment = true;\n }\n }\n /**\n * Create a new ReflectionBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name);\n /**\n * Defines if the material uses spherical harmonics vs spherical polynomials for the\n * diffuse part of the IBL.\n */\n this.useSphericalHarmonics = true;\n /**\n * Force the shader to compute irradiance in the fragment shader in order to take bump in account.\n */\n this.forceIrradianceInFragment = false;\n this._isUnique = true;\n this.registerInput(\"position\", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.Vertex);\n this.registerInput(\"world\", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Vertex);\n this.registerInput(\"color\", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"reflection\", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"reflection\", this, NodeMaterialConnectionPointDirection.Output, ReflectionBlock, \"ReflectionBlock\"));\n this.position.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ReflectionBlock\";\n }\n /**\n * Gets the position input component\n */\n get position() {\n return this._inputs[0];\n }\n /**\n * Gets the world position input component\n */\n get worldPosition() {\n return this.worldPositionConnectionPoint;\n }\n /**\n * Gets the world normal input component\n */\n get worldNormal() {\n return this.worldNormalConnectionPoint;\n }\n /**\n * Gets the world input component\n */\n get world() {\n return this._inputs[1];\n }\n /**\n * Gets the camera (or eye) position component\n */\n get cameraPosition() {\n return this.cameraPositionConnectionPoint;\n }\n /**\n * Gets the view input component\n */\n get view() {\n return this.viewConnectionPoint;\n }\n /**\n * Gets the color input component\n */\n get color() {\n return this._inputs[2];\n }\n /**\n * Gets the reflection object output component\n */\n get reflection() {\n return this._outputs[0];\n }\n /**\n * Returns true if the block has a texture (either its own texture or the environment texture from the scene, if set)\n */\n get hasTexture() {\n return !!this._getTexture();\n }\n /**\n * Gets the reflection color (either the name of the variable if the color input is connected, else a default value)\n */\n get reflectionColor() {\n return this.color.isConnected ? this.color.associatedVariableName : \"vec3(1., 1., 1.)\";\n }\n _getTexture() {\n if (this.texture) {\n return this.texture;\n }\n return this._scene.environmentTexture;\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n super.prepareDefines(mesh, nodeMaterial, defines);\n const reflectionTexture = this._getTexture();\n const reflection = reflectionTexture && reflectionTexture.getTextureMatrix;\n defines.setValue(\"REFLECTION\", reflection, true);\n if (!reflection) {\n return;\n }\n defines.setValue(this._defineLODReflectionAlpha, reflectionTexture.lodLevelInAlpha, true);\n defines.setValue(this._defineLinearSpecularReflection, reflectionTexture.linearSpecularLOD, true);\n defines.setValue(this._defineOppositeZ, this._scene.useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ, true);\n defines.setValue(\"SPHERICAL_HARMONICS\", this.useSphericalHarmonics, true);\n defines.setValue(\"GAMMAREFLECTION\", reflectionTexture.gammaSpace, true);\n defines.setValue(\"RGBDREFLECTION\", reflectionTexture.isRGBD, true);\n if (reflectionTexture && reflectionTexture.coordinatesMode !== Texture.SKYBOX_MODE) {\n if (reflectionTexture.isCube) {\n defines.setValue(\"USESPHERICALFROMREFLECTIONMAP\", true);\n defines.setValue(\"USEIRRADIANCEMAP\", false);\n if (this.forceIrradianceInFragment || this._scene.getEngine().getCaps().maxVaryingVectors <= 8) {\n defines.setValue(\"USESPHERICALINVERTEX\", false);\n }\n else {\n defines.setValue(\"USESPHERICALINVERTEX\", true);\n }\n }\n }\n }\n bind(effect, nodeMaterial, mesh, subMesh) {\n super.bind(effect, nodeMaterial, mesh);\n const reflectionTexture = this._getTexture();\n if (!reflectionTexture || !subMesh) {\n return;\n }\n if (reflectionTexture.isCube) {\n effect.setTexture(this._cubeSamplerName, reflectionTexture);\n }\n else {\n effect.setTexture(this._2DSamplerName, reflectionTexture);\n }\n const width = reflectionTexture.getSize().width;\n effect.setFloat3(this._vReflectionMicrosurfaceInfosName, width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);\n effect.setFloat2(this._vReflectionFilteringInfoName, width, Scalar.Log2(width));\n const defines = subMesh.materialDefines;\n const polynomials = reflectionTexture.sphericalPolynomial;\n if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {\n if (defines.SPHERICAL_HARMONICS) {\n const preScaledHarmonics = polynomials.preScaledHarmonics;\n effect.setVector3(\"vSphericalL00\", preScaledHarmonics.l00);\n effect.setVector3(\"vSphericalL1_1\", preScaledHarmonics.l1_1);\n effect.setVector3(\"vSphericalL10\", preScaledHarmonics.l10);\n effect.setVector3(\"vSphericalL11\", preScaledHarmonics.l11);\n effect.setVector3(\"vSphericalL2_2\", preScaledHarmonics.l2_2);\n effect.setVector3(\"vSphericalL2_1\", preScaledHarmonics.l2_1);\n effect.setVector3(\"vSphericalL20\", preScaledHarmonics.l20);\n effect.setVector3(\"vSphericalL21\", preScaledHarmonics.l21);\n effect.setVector3(\"vSphericalL22\", preScaledHarmonics.l22);\n }\n else {\n effect.setFloat3(\"vSphericalX\", polynomials.x.x, polynomials.x.y, polynomials.x.z);\n effect.setFloat3(\"vSphericalY\", polynomials.y.x, polynomials.y.y, polynomials.y.z);\n effect.setFloat3(\"vSphericalZ\", polynomials.z.x, polynomials.z.y, polynomials.z.z);\n effect.setFloat3(\"vSphericalXX_ZZ\", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);\n effect.setFloat3(\"vSphericalYY_ZZ\", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);\n effect.setFloat3(\"vSphericalZZ\", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);\n effect.setFloat3(\"vSphericalXY\", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);\n effect.setFloat3(\"vSphericalYZ\", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);\n effect.setFloat3(\"vSphericalZX\", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);\n }\n }\n }\n /**\n * Gets the code to inject in the vertex shader\n * @param state current state of the node material building\n * @returns the shader code\n */\n handleVertexSide(state) {\n let code = super.handleVertexSide(state);\n state._emitFunctionFromInclude(\"harmonicsFunctions\", `//${this.name}`, {\n replaceStrings: [\n { search: /uniform vec3 vSphericalL00;[\\s\\S]*?uniform vec3 vSphericalL22;/g, replace: \"\" },\n { search: /uniform vec3 vSphericalX;[\\s\\S]*?uniform vec3 vSphericalZX;/g, replace: \"\" },\n ],\n });\n const reflectionVectorName = state._getFreeVariableName(\"reflectionVector\");\n this._vEnvironmentIrradianceName = state._getFreeVariableName(\"vEnvironmentIrradiance\");\n state._emitVaryingFromString(this._vEnvironmentIrradianceName, \"vec3\", \"defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\");\n state._emitUniformFromString(\"vSphericalL00\", \"vec3\", \"SPHERICAL_HARMONICS\");\n state._emitUniformFromString(\"vSphericalL1_1\", \"vec3\", \"SPHERICAL_HARMONICS\");\n state._emitUniformFromString(\"vSphericalL10\", \"vec3\", \"SPHERICAL_HARMONICS\");\n state._emitUniformFromString(\"vSphericalL11\", \"vec3\", \"SPHERICAL_HARMONICS\");\n state._emitUniformFromString(\"vSphericalL2_2\", \"vec3\", \"SPHERICAL_HARMONICS\");\n state._emitUniformFromString(\"vSphericalL2_1\", \"vec3\", \"SPHERICAL_HARMONICS\");\n state._emitUniformFromString(\"vSphericalL20\", \"vec3\", \"SPHERICAL_HARMONICS\");\n state._emitUniformFromString(\"vSphericalL21\", \"vec3\", \"SPHERICAL_HARMONICS\");\n state._emitUniformFromString(\"vSphericalL22\", \"vec3\", \"SPHERICAL_HARMONICS\");\n state._emitUniformFromString(\"vSphericalX\", \"vec3\", \"SPHERICAL_HARMONICS\", true);\n state._emitUniformFromString(\"vSphericalY\", \"vec3\", \"SPHERICAL_HARMONICS\", true);\n state._emitUniformFromString(\"vSphericalZ\", \"vec3\", \"SPHERICAL_HARMONICS\", true);\n state._emitUniformFromString(\"vSphericalXX_ZZ\", \"vec3\", \"SPHERICAL_HARMONICS\", true);\n state._emitUniformFromString(\"vSphericalYY_ZZ\", \"vec3\", \"SPHERICAL_HARMONICS\", true);\n state._emitUniformFromString(\"vSphericalZZ\", \"vec3\", \"SPHERICAL_HARMONICS\", true);\n state._emitUniformFromString(\"vSphericalXY\", \"vec3\", \"SPHERICAL_HARMONICS\", true);\n state._emitUniformFromString(\"vSphericalYZ\", \"vec3\", \"SPHERICAL_HARMONICS\", true);\n state._emitUniformFromString(\"vSphericalZX\", \"vec3\", \"SPHERICAL_HARMONICS\", true);\n code += `#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\r\n vec3 ${reflectionVectorName} = vec3(${this._reflectionMatrixName} * vec4(normalize(${this.worldNormal.associatedVariableName}).xyz, 0)).xyz;\r\n #ifdef ${this._defineOppositeZ}\r\n ${reflectionVectorName}.z *= -1.0;\r\n #endif\r\n ${this._vEnvironmentIrradianceName} = computeEnvironmentIrradiance(${reflectionVectorName});\r\n #endif\\r\\n`;\n return code;\n }\n /**\n * Gets the main code of the block (fragment side)\n * @param state current state of the node material building\n * @param normalVarName name of the existing variable corresponding to the normal\n * @returns the shader code\n */\n getCode(state, normalVarName) {\n let code = \"\";\n this.handleFragmentSideInits(state);\n state._emitFunctionFromInclude(\"harmonicsFunctions\", `//${this.name}`, {\n replaceStrings: [\n { search: /uniform vec3 vSphericalL00;[\\s\\S]*?uniform vec3 vSphericalL22;/g, replace: \"\" },\n { search: /uniform vec3 vSphericalX;[\\s\\S]*?uniform vec3 vSphericalZX;/g, replace: \"\" },\n ],\n });\n state._emitFunction(\"sampleReflection\", `\r\n #ifdef ${this._define3DName}\r\n #define sampleReflection(s, c) textureCube(s, c)\r\n #else\r\n #define sampleReflection(s, c) texture2D(s, c)\r\n #endif\\r\\n`, `//${this.name}`);\n state._emitFunction(\"sampleReflectionLod\", `\r\n #ifdef ${this._define3DName}\r\n #define sampleReflectionLod(s, c, l) textureCubeLodEXT(s, c, l)\r\n #else\r\n #define sampleReflectionLod(s, c, l) texture2DLodEXT(s, c, l)\r\n #endif\\r\\n`, `//${this.name}`);\n const computeReflectionCoordsFunc = `\r\n vec3 computeReflectionCoordsPBR(vec4 worldPos, vec3 worldNormal) {\r\n ${this.handleFragmentSideCodeReflectionCoords(\"worldNormal\", \"worldPos\", true, true)}\r\n return ${this._reflectionVectorName};\r\n }\\r\\n`;\n state._emitFunction(\"computeReflectionCoordsPBR\", computeReflectionCoordsFunc, `//${this.name}`);\n this._vReflectionMicrosurfaceInfosName = state._getFreeVariableName(\"vReflectionMicrosurfaceInfos\");\n state._emitUniformFromString(this._vReflectionMicrosurfaceInfosName, \"vec3\");\n this._vReflectionInfosName = state._getFreeVariableName(\"vReflectionInfos\");\n this._vReflectionFilteringInfoName = state._getFreeVariableName(\"vReflectionFilteringInfo\");\n state._emitUniformFromString(this._vReflectionFilteringInfoName, \"vec2\");\n code += `#ifdef REFLECTION\r\n vec2 ${this._vReflectionInfosName} = vec2(1., 0.);\r\n\r\n reflectionOutParams reflectionOut;\r\n\r\n reflectionBlock(\r\n ${this.generateOnlyFragmentCode ? this._worldPositionNameInFragmentOnlyMode : \"v_\" + this.worldPosition.associatedVariableName}.xyz,\r\n ${normalVarName},\r\n alphaG,\r\n ${this._vReflectionMicrosurfaceInfosName},\r\n ${this._vReflectionInfosName},\r\n ${this.reflectionColor},\r\n #ifdef ANISOTROPIC\r\n anisotropicOut,\r\n #endif\r\n #if defined(${this._defineLODReflectionAlpha}) && !defined(${this._defineSkyboxName})\r\n NdotVUnclamped,\r\n #endif\r\n #ifdef ${this._defineLinearSpecularReflection}\r\n roughness,\r\n #endif\r\n #ifdef ${this._define3DName}\r\n ${this._cubeSamplerName},\r\n #else\r\n ${this._2DSamplerName},\r\n #endif\r\n #if defined(NORMAL) && defined(USESPHERICALINVERTEX)\r\n ${this._vEnvironmentIrradianceName},\r\n #endif\r\n #ifdef USESPHERICALFROMREFLECTIONMAP\r\n #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\r\n ${this._reflectionMatrixName},\r\n #endif\r\n #endif\r\n #ifdef USEIRRADIANCEMAP\r\n irradianceSampler, // ** not handled **\r\n #endif\r\n #ifndef LODBASEDMICROSFURACE\r\n #ifdef ${this._define3DName}\r\n ${this._cubeSamplerName},\r\n ${this._cubeSamplerName},\r\n #else\r\n ${this._2DSamplerName},\r\n ${this._2DSamplerName},\r\n #endif\r\n #endif\r\n #ifdef REALTIME_FILTERING\r\n ${this._vReflectionFilteringInfoName},\r\n #endif\r\n reflectionOut\r\n );\r\n #endif\\r\\n`;\n return code;\n }\n _buildBlock(state) {\n this._scene = state.sharedData.scene;\n if (state.target !== NodeMaterialBlockTargets.Fragment) {\n this._defineLODReflectionAlpha = state._getFreeDefineName(\"LODINREFLECTIONALPHA\");\n this._defineLinearSpecularReflection = state._getFreeDefineName(\"LINEARSPECULARREFLECTION\");\n }\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n if (this.texture) {\n codeString += `${this._codeVariableName}.texture.gammaSpace = ${this.texture.gammaSpace};\\r\\n`;\n }\n codeString += `${this._codeVariableName}.useSphericalHarmonics = ${this.useSphericalHarmonics};\\r\\n`;\n codeString += `${this._codeVariableName}.forceIrradianceInFragment = ${this.forceIrradianceInFragment};\\r\\n`;\n return codeString;\n }\n serialize() {\n var _a, _b;\n const serializationObject = super.serialize();\n serializationObject.useSphericalHarmonics = this.useSphericalHarmonics;\n serializationObject.forceIrradianceInFragment = this.forceIrradianceInFragment;\n serializationObject.gammaSpace = (_b = (_a = this.texture) === null || _a === void 0 ? void 0 : _a.gammaSpace) !== null && _b !== void 0 ? _b : true;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.useSphericalHarmonics = serializationObject.useSphericalHarmonics;\n this.forceIrradianceInFragment = serializationObject.forceIrradianceInFragment;\n if (this.texture) {\n this.texture.gammaSpace = serializationObject.gammaSpace;\n }\n }\n}\n__decorate([\n editableInPropertyPage(\"Spherical Harmonics\", PropertyTypeForEdition.Boolean, \"ADVANCED\", { notifiers: { update: true } })\n], ReflectionBlock.prototype, \"useSphericalHarmonics\", void 0);\n__decorate([\n editableInPropertyPage(\"Force irradiance in fragment\", PropertyTypeForEdition.Boolean, \"ADVANCED\", { notifiers: { update: true } })\n], ReflectionBlock.prototype, \"forceIrradianceInFragment\", void 0);\nRegisterClass(\"BABYLON.ReflectionBlock\", ReflectionBlock);\n//# sourceMappingURL=reflectionBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../../nodeMaterialBlockConnectionPoint.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../../nodeMaterialConnectionPointCustomObject.js\";\nimport { PBRIridescenceConfiguration } from \"../../../../Materials/PBR/pbrIridescenceConfiguration.js\";\n/**\n * Block used to implement the iridescence module of the PBR material\n */\nexport class IridescenceBlock extends NodeMaterialBlock {\n /**\n * Create a new IridescenceBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this._isUnique = true;\n this.registerInput(\"intensity\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"indexOfRefraction\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"thickness\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"iridescence\", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"iridescence\", this, NodeMaterialConnectionPointDirection.Output, IridescenceBlock, \"IridescenceBlock\"));\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"iridescenceOut\");\n state._excludeVariableName(\"vIridescenceParams\");\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"IridescenceBlock\";\n }\n /**\n * Gets the intensity input component\n */\n get intensity() {\n return this._inputs[0];\n }\n /**\n * Gets the indexOfRefraction input component\n */\n get indexOfRefraction() {\n return this._inputs[1];\n }\n /**\n * Gets the thickness input component\n */\n get thickness() {\n return this._inputs[2];\n }\n /**\n * Gets the iridescence object output component\n */\n get iridescence() {\n return this._outputs[0];\n }\n autoConfigure() {\n if (!this.intensity.isConnected) {\n const intensityInput = new InputBlock(\"Iridescence intensity\", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float);\n intensityInput.value = 1;\n intensityInput.output.connectTo(this.intensity);\n const indexOfRefractionInput = new InputBlock(\"Iridescence ior\", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float);\n indexOfRefractionInput.value = 1.3;\n indexOfRefractionInput.output.connectTo(this.indexOfRefraction);\n const thicknessInput = new InputBlock(\"Iridescence thickness\", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float);\n thicknessInput.value = 400;\n thicknessInput.output.connectTo(this.thickness);\n }\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n super.prepareDefines(mesh, nodeMaterial, defines);\n defines.setValue(\"IRIDESCENCE\", true, true);\n defines.setValue(\"IRIDESCENCE_TEXTURE\", false, true);\n defines.setValue(\"IRIDESCENCE_THICKNESS_TEXTURE\", false, true);\n }\n /**\n * Gets the main code of the block (fragment side)\n * @param iridescenceBlock instance of a IridescenceBlock or null if the code must be generated without an active iridescence module\n * @returns the shader code\n */\n static GetCode(iridescenceBlock) {\n let code = \"\";\n const intensityName = (iridescenceBlock === null || iridescenceBlock === void 0 ? void 0 : iridescenceBlock.intensity.isConnected) ? iridescenceBlock.intensity.associatedVariableName : \"1.\";\n const indexOfRefraction = (iridescenceBlock === null || iridescenceBlock === void 0 ? void 0 : iridescenceBlock.indexOfRefraction.isConnected)\n ? iridescenceBlock.indexOfRefraction.associatedVariableName\n : PBRIridescenceConfiguration._DefaultIndexOfRefraction;\n const thickness = (iridescenceBlock === null || iridescenceBlock === void 0 ? void 0 : iridescenceBlock.thickness.isConnected) ? iridescenceBlock.thickness.associatedVariableName : PBRIridescenceConfiguration._DefaultMaximumThickness;\n code += `iridescenceOutParams iridescenceOut;\r\n\r\n #ifdef IRIDESCENCE\r\n iridescenceBlock(\r\n vec4(${intensityName}, ${indexOfRefraction}, 1., ${thickness}),\r\n NdotV,\r\n specularEnvironmentR0,\r\n #ifdef CLEARCOAT\r\n NdotVUnclamped,\r\n #endif\r\n iridescenceOut\r\n );\r\n\r\n float iridescenceIntensity = iridescenceOut.iridescenceIntensity;\r\n specularEnvironmentR0 = iridescenceOut.specularEnvironmentR0;\r\n #endif\\r\\n`;\n return code;\n }\n _buildBlock(state) {\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n state.sharedData.bindableBlocks.push(this);\n state.sharedData.blocksWithDefines.push(this);\n }\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n }\n}\nRegisterClass(\"BABYLON.IridescenceBlock\", IridescenceBlock);\n//# sourceMappingURL=iridescenceBlock.js.map","import { __decorate } from \"../../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../../nodeMaterialBlockConnectionPoint.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../../nodeMaterialConnectionPointCustomObject.js\";\nimport { PBRClearCoatConfiguration } from \"../../../PBR/pbrClearCoatConfiguration.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../../nodeMaterialDecorator.js\";\nimport { TBNBlock } from \"../Fragment/TBNBlock.js\";\n/**\n * Block used to implement the clear coat module of the PBR material\n */\nexport class ClearCoatBlock extends NodeMaterialBlock {\n /**\n * Create a new ClearCoatBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this._tangentCorrectionFactorName = \"\";\n /**\n * Defines if the F0 value should be remapped to account for the interface change in the material.\n */\n this.remapF0OnInterfaceChange = true;\n this._isUnique = true;\n this.registerInput(\"intensity\", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"roughness\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"indexOfRefraction\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"normalMapColor\", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"uv\", NodeMaterialBlockConnectionPointTypes.Vector2, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"tintColor\", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"tintAtDistance\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"tintThickness\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"worldTangent\", NodeMaterialBlockConnectionPointTypes.Vector4, true);\n this.registerInput(\"worldNormal\", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);\n this.worldNormal.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color4 | NodeMaterialBlockConnectionPointTypes.Vector4 | NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerInput(\"TBN\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject(\"TBN\", this, NodeMaterialConnectionPointDirection.Input, TBNBlock, \"TBNBlock\"));\n this.registerOutput(\"clearcoat\", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"clearcoat\", this, NodeMaterialConnectionPointDirection.Output, ClearCoatBlock, \"ClearCoatBlock\"));\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"clearcoatOut\");\n state._excludeVariableName(\"vClearCoatParams\");\n state._excludeVariableName(\"vClearCoatTintParams\");\n state._excludeVariableName(\"vClearCoatRefractionParams\");\n state._excludeVariableName(\"vClearCoatTangentSpaceParams\");\n state._excludeVariableName(\"vGeometricNormaClearCoatW\");\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ClearCoatBlock\";\n }\n /**\n * Gets the intensity input component\n */\n get intensity() {\n return this._inputs[0];\n }\n /**\n * Gets the roughness input component\n */\n get roughness() {\n return this._inputs[1];\n }\n /**\n * Gets the ior input component\n */\n get indexOfRefraction() {\n return this._inputs[2];\n }\n /**\n * Gets the bump texture input component\n */\n get normalMapColor() {\n return this._inputs[3];\n }\n /**\n * Gets the uv input component\n */\n get uv() {\n return this._inputs[4];\n }\n /**\n * Gets the tint color input component\n */\n get tintColor() {\n return this._inputs[5];\n }\n /**\n * Gets the tint \"at distance\" input component\n */\n get tintAtDistance() {\n return this._inputs[6];\n }\n /**\n * Gets the tint thickness input component\n */\n get tintThickness() {\n return this._inputs[7];\n }\n /**\n * Gets the world tangent input component\n */\n get worldTangent() {\n return this._inputs[8];\n }\n /**\n * Gets the world normal input component\n */\n get worldNormal() {\n return this._inputs[9];\n }\n /**\n * Gets the TBN input component\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n get TBN() {\n return this._inputs[10];\n }\n /**\n * Gets the clear coat object output component\n */\n get clearcoat() {\n return this._outputs[0];\n }\n autoConfigure() {\n if (!this.intensity.isConnected) {\n const intensityInput = new InputBlock(\"ClearCoat intensity\", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float);\n intensityInput.value = 1;\n intensityInput.output.connectTo(this.intensity);\n }\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n super.prepareDefines(mesh, nodeMaterial, defines);\n defines.setValue(\"CLEARCOAT\", true);\n defines.setValue(\"CLEARCOAT_TEXTURE\", false, true);\n defines.setValue(\"CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE\", true, true);\n defines.setValue(\"CLEARCOAT_TINT\", this.tintColor.isConnected || this.tintThickness.isConnected || this.tintAtDistance.isConnected, true);\n defines.setValue(\"CLEARCOAT_BUMP\", this.normalMapColor.isConnected, true);\n defines.setValue(\"CLEARCOAT_DEFAULTIOR\", this.indexOfRefraction.isConnected ? this.indexOfRefraction.connectInputBlock.value === PBRClearCoatConfiguration._DefaultIndexOfRefraction : true, true);\n defines.setValue(\"CLEARCOAT_REMAP_F0\", this.remapF0OnInterfaceChange, true);\n }\n bind(effect, nodeMaterial, mesh) {\n var _a, _b;\n super.bind(effect, nodeMaterial, mesh);\n // Clear Coat Refraction params\n const indexOfRefraction = (_b = (_a = this.indexOfRefraction.connectInputBlock) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : PBRClearCoatConfiguration._DefaultIndexOfRefraction;\n const a = 1 - indexOfRefraction;\n const b = 1 + indexOfRefraction;\n const f0 = Math.pow(-a / b, 2); // Schlicks approx: (ior1 - ior2) / (ior1 + ior2) where ior2 for air is close to vacuum = 1.\n const eta = 1 / indexOfRefraction;\n effect.setFloat4(\"vClearCoatRefractionParams\", f0, eta, a, b);\n // Clear Coat tangent space params\n const mainPBRBlock = this.clearcoat.hasEndpoints ? this.clearcoat.endpoints[0].ownerBlock : null;\n const perturbedNormalBlock = (mainPBRBlock === null || mainPBRBlock === void 0 ? void 0 : mainPBRBlock.perturbedNormal.isConnected) ? mainPBRBlock.perturbedNormal.connectedPoint.ownerBlock : null;\n if (this._scene._mirroredCameraPosition) {\n effect.setFloat2(\"vClearCoatTangentSpaceParams\", (perturbedNormalBlock === null || perturbedNormalBlock === void 0 ? void 0 : perturbedNormalBlock.invertX) ? 1.0 : -1.0, (perturbedNormalBlock === null || perturbedNormalBlock === void 0 ? void 0 : perturbedNormalBlock.invertY) ? 1.0 : -1.0);\n }\n else {\n effect.setFloat2(\"vClearCoatTangentSpaceParams\", (perturbedNormalBlock === null || perturbedNormalBlock === void 0 ? void 0 : perturbedNormalBlock.invertX) ? -1.0 : 1.0, (perturbedNormalBlock === null || perturbedNormalBlock === void 0 ? void 0 : perturbedNormalBlock.invertY) ? -1.0 : 1.0);\n }\n if (mesh) {\n effect.setFloat(this._tangentCorrectionFactorName, mesh.getWorldMatrix().determinant() < 0 ? -1 : 1);\n }\n }\n _generateTBNSpace(state, worldPositionVarName, worldNormalVarName) {\n let code = \"\";\n const comments = `//${this.name}`;\n const worldTangent = this.worldTangent;\n state._emitExtension(\"derivatives\", \"#extension GL_OES_standard_derivatives : enable\");\n const tangentReplaceString = { search: /defined\\(TANGENT\\)/g, replace: worldTangent.isConnected ? \"defined(TANGENT)\" : \"defined(IGNORE)\" };\n const TBN = this.TBN;\n if (TBN.isConnected) {\n state.compilationString += `\r\n #ifdef TBNBLOCK\r\n mat3 vTBN = ${TBN.associatedVariableName};\r\n #endif\r\n `;\n }\n else if (worldTangent.isConnected) {\n code += `vec3 tbnNormal = normalize(${worldNormalVarName}.xyz);\\r\\n`;\n code += `vec3 tbnTangent = normalize(${worldTangent.associatedVariableName}.xyz);\\r\\n`;\n code += `vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};\\r\\n`;\n code += `mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\\r\\n`;\n }\n state._emitFunctionFromInclude(\"bumpFragmentMainFunctions\", comments, {\n replaceStrings: [tangentReplaceString],\n });\n return code;\n }\n /**\n * Gets the main code of the block (fragment side)\n * @param state current state of the node material building\n * @param ccBlock instance of a ClearCoatBlock or null if the code must be generated without an active clear coat module\n * @param reflectionBlock instance of a ReflectionBlock null if the code must be generated without an active reflection module\n * @param worldPosVarName name of the variable holding the world position\n * @param generateTBNSpace if true, the code needed to create the TBN coordinate space is generated\n * @param vTBNAvailable indicate that the vTBN variable is already existing because it has already been generated by another block (PerturbNormal or Anisotropy)\n * @param worldNormalVarName name of the variable holding the world normal\n * @returns the shader code\n */\n static GetCode(state, ccBlock, reflectionBlock, worldPosVarName, generateTBNSpace, vTBNAvailable, worldNormalVarName) {\n let code = \"\";\n const intensity = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.intensity.isConnected) ? ccBlock.intensity.associatedVariableName : \"1.\";\n const roughness = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.roughness.isConnected) ? ccBlock.roughness.associatedVariableName : \"0.\";\n const normalMapColor = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.normalMapColor.isConnected) ? ccBlock.normalMapColor.associatedVariableName : \"vec3(0.)\";\n const uv = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.uv.isConnected) ? ccBlock.uv.associatedVariableName : \"vec2(0.)\";\n const tintColor = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.tintColor.isConnected) ? ccBlock.tintColor.associatedVariableName : \"vec3(1.)\";\n const tintThickness = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.tintThickness.isConnected) ? ccBlock.tintThickness.associatedVariableName : \"1.\";\n const tintAtDistance = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.tintAtDistance.isConnected) ? ccBlock.tintAtDistance.associatedVariableName : \"1.\";\n const tintTexture = \"vec4(0.)\";\n if (ccBlock) {\n state._emitUniformFromString(\"vClearCoatRefractionParams\", \"vec4\");\n state._emitUniformFromString(\"vClearCoatTangentSpaceParams\", \"vec2\");\n const normalShading = ccBlock.worldNormal;\n code += `vec3 vGeometricNormaClearCoatW = ${normalShading.isConnected ? \"normalize(\" + normalShading.associatedVariableName + \".xyz)\" : \"geometricNormalW\"};\\r\\n`;\n }\n else {\n code += `vec3 vGeometricNormaClearCoatW = geometricNormalW;\\r\\n`;\n }\n if (generateTBNSpace && ccBlock) {\n code += ccBlock._generateTBNSpace(state, worldPosVarName, worldNormalVarName);\n vTBNAvailable = ccBlock.worldTangent.isConnected;\n }\n code += `clearcoatOutParams clearcoatOut;\r\n\r\n #ifdef CLEARCOAT\r\n vec2 vClearCoatParams = vec2(${intensity}, ${roughness});\r\n vec4 vClearCoatTintParams = vec4(${tintColor}, ${tintThickness});\r\n\r\n clearcoatBlock(\r\n ${worldPosVarName}.xyz,\r\n vGeometricNormaClearCoatW,\r\n viewDirectionW,\r\n vClearCoatParams,\r\n specularEnvironmentR0,\r\n #ifdef CLEARCOAT_TEXTURE\r\n vec2(0.),\r\n #endif\r\n #ifdef CLEARCOAT_TINT\r\n vClearCoatTintParams,\r\n ${tintAtDistance},\r\n vClearCoatRefractionParams,\r\n #ifdef CLEARCOAT_TINT_TEXTURE\r\n ${tintTexture},\r\n #endif\r\n #endif\r\n #ifdef CLEARCOAT_BUMP\r\n vec2(0., 1.),\r\n vec4(${normalMapColor}, 0.),\r\n ${uv},\r\n #if defined(${vTBNAvailable ? \"TANGENT\" : \"IGNORE\"}) && defined(NORMAL)\r\n vTBN,\r\n #else\r\n vClearCoatTangentSpaceParams,\r\n #endif\r\n #ifdef OBJECTSPACE_NORMALMAP\r\n normalMatrix,\r\n #endif\r\n #endif\r\n #if defined(FORCENORMALFORWARD) && defined(NORMAL)\r\n faceNormal,\r\n #endif\r\n #ifdef REFLECTION\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._vReflectionMicrosurfaceInfosName},\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._vReflectionInfosName},\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock.reflectionColor},\r\n vLightingIntensity,\r\n #ifdef ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName}\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName},\r\n #else\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._2DSamplerName},\r\n #endif\r\n #ifndef LODBASEDMICROSFURACE\r\n #ifdef ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName}\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName},\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName},\r\n #else\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._2DSamplerName},\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._2DSamplerName},\r\n #endif\r\n #endif\r\n #endif\r\n #if defined(ENVIRONMENTBRDF) && !defined(${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName})\r\n #ifdef RADIANCEOCCLUSION\r\n ambientMonochrome,\r\n #endif\r\n #endif\r\n #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)\r\n (gl_FrontFacing ? 1. : -1.),\r\n #endif\r\n clearcoatOut\r\n );\r\n #else\r\n clearcoatOut.specularEnvironmentR0 = specularEnvironmentR0;\r\n #endif\\r\\n`;\n return code;\n }\n _buildBlock(state) {\n this._scene = state.sharedData.scene;\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n state.sharedData.bindableBlocks.push(this);\n state.sharedData.blocksWithDefines.push(this);\n this._tangentCorrectionFactorName = state._getFreeDefineName(\"tangentCorrectionFactor\");\n state._emitUniformFromString(this._tangentCorrectionFactorName, \"float\");\n }\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n codeString += `${this._codeVariableName}.remapF0OnInterfaceChange = ${this.remapF0OnInterfaceChange};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.remapF0OnInterfaceChange = this.remapF0OnInterfaceChange;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n var _a;\n super._deserialize(serializationObject, scene, rootUrl);\n this.remapF0OnInterfaceChange = (_a = serializationObject.remapF0OnInterfaceChange) !== null && _a !== void 0 ? _a : true;\n }\n}\n__decorate([\n editableInPropertyPage(\"Remap F0 on interface change\", PropertyTypeForEdition.Boolean, \"ADVANCED\")\n], ClearCoatBlock.prototype, \"remapF0OnInterfaceChange\", void 0);\nRegisterClass(\"BABYLON.ClearCoatBlock\", ClearCoatBlock);\n//# sourceMappingURL=clearCoatBlock.js.map","import { __decorate } from \"../../../../tslib.es6.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../../nodeMaterialBlockConnectionPoint.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../../nodeMaterialConnectionPointCustomObject.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../../nodeMaterialDecorator.js\";\nimport { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { CubeTexture } from \"../../../Textures/cubeTexture.js\";\nimport { Texture } from \"../../../Textures/texture.js\";\nimport { NodeMaterialSystemValues } from \"../../Enums/nodeMaterialSystemValues.js\";\nimport { Scalar } from \"../../../../Maths/math.scalar.js\";\n/**\n * Block used to implement the refraction part of the sub surface module of the PBR material\n */\nexport class RefractionBlock extends NodeMaterialBlock {\n /**\n * Create a new RefractionBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n /**\n * This parameters will make the material used its opacity to control how much it is refracting against not.\n * Materials half opaque for instance using refraction could benefit from this control.\n */\n this.linkRefractionWithTransparency = false;\n /**\n * Controls if refraction needs to be inverted on Y. This could be useful for procedural texture.\n */\n this.invertRefractionY = false;\n /**\n * Controls if refraction needs to be inverted on Y. This could be useful for procedural texture.\n */\n this.useThicknessAsDepth = false;\n this._isUnique = true;\n this.registerInput(\"intensity\", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"tintAtDistance\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"volumeIndexOfRefraction\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"refraction\", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"refraction\", this, NodeMaterialConnectionPointDirection.Output, RefractionBlock, \"RefractionBlock\"));\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"vRefractionPosition\");\n state._excludeVariableName(\"vRefractionSize\");\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"RefractionBlock\";\n }\n /**\n * Gets the intensity input component\n */\n get intensity() {\n return this._inputs[0];\n }\n /**\n * Gets the tint at distance input component\n */\n get tintAtDistance() {\n return this._inputs[1];\n }\n /**\n * Gets the volume index of refraction input component\n */\n get volumeIndexOfRefraction() {\n return this._inputs[2];\n }\n /**\n * Gets the view input component\n */\n get view() {\n return this.viewConnectionPoint;\n }\n /**\n * Gets the refraction object output component\n */\n get refraction() {\n return this._outputs[0];\n }\n /**\n * Returns true if the block has a texture\n */\n get hasTexture() {\n return !!this._getTexture();\n }\n _getTexture() {\n if (this.texture) {\n return this.texture;\n }\n return this._scene.environmentTexture;\n }\n autoConfigure(material) {\n if (!this.intensity.isConnected) {\n const intensityInput = new InputBlock(\"Refraction intensity\", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float);\n intensityInput.value = 1;\n intensityInput.output.connectTo(this.intensity);\n }\n if (this.view && !this.view.isConnected) {\n let viewInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.View);\n if (!viewInput) {\n viewInput = new InputBlock(\"view\");\n viewInput.setAsSystemValue(NodeMaterialSystemValues.View);\n }\n viewInput.output.connectTo(this.view);\n }\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n super.prepareDefines(mesh, nodeMaterial, defines);\n const refractionTexture = this._getTexture();\n const refraction = refractionTexture && refractionTexture.getTextureMatrix;\n defines.setValue(\"SS_REFRACTION\", refraction, true);\n if (!refraction) {\n return;\n }\n defines.setValue(this._define3DName, refractionTexture.isCube, true);\n defines.setValue(this._defineLODRefractionAlpha, refractionTexture.lodLevelInAlpha, true);\n defines.setValue(this._defineLinearSpecularRefraction, refractionTexture.linearSpecularLOD, true);\n defines.setValue(this._defineOppositeZ, this._scene.useRightHandedSystem && refractionTexture.isCube ? !refractionTexture.invertZ : refractionTexture.invertZ, true);\n defines.setValue(\"SS_LINKREFRACTIONTOTRANSPARENCY\", this.linkRefractionWithTransparency, true);\n defines.setValue(\"SS_GAMMAREFRACTION\", refractionTexture.gammaSpace, true);\n defines.setValue(\"SS_RGBDREFRACTION\", refractionTexture.isRGBD, true);\n defines.setValue(\"SS_USE_LOCAL_REFRACTIONMAP_CUBIC\", refractionTexture.boundingBoxSize ? true : false, true);\n defines.setValue(\"SS_USE_THICKNESS_AS_DEPTH\", this.useThicknessAsDepth, true);\n }\n isReady() {\n const texture = this._getTexture();\n if (texture && !texture.isReadyOrNotBlocking()) {\n return false;\n }\n return true;\n }\n bind(effect, nodeMaterial, mesh) {\n var _a, _b, _c, _d;\n super.bind(effect, nodeMaterial, mesh);\n const refractionTexture = this._getTexture();\n if (!refractionTexture) {\n return;\n }\n if (refractionTexture.isCube) {\n effect.setTexture(this._cubeSamplerName, refractionTexture);\n }\n else {\n effect.setTexture(this._2DSamplerName, refractionTexture);\n }\n effect.setMatrix(this._refractionMatrixName, refractionTexture.getRefractionTextureMatrix());\n let depth = 1.0;\n if (!refractionTexture.isCube) {\n if (refractionTexture.depth) {\n depth = refractionTexture.depth;\n }\n }\n const indexOfRefraction = (_d = (_b = (_a = this.volumeIndexOfRefraction.connectInputBlock) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : (_c = this.indexOfRefractionConnectionPoint.connectInputBlock) === null || _c === void 0 ? void 0 : _c.value) !== null && _d !== void 0 ? _d : 1.5;\n effect.setFloat4(this._vRefractionInfosName, refractionTexture.level, 1 / indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);\n effect.setFloat4(this._vRefractionMicrosurfaceInfosName, refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset, 1 / indexOfRefraction);\n const width = refractionTexture.getSize().width;\n effect.setFloat2(this._vRefractionFilteringInfoName, width, Scalar.Log2(width));\n if (refractionTexture.boundingBoxSize) {\n const cubeTexture = refractionTexture;\n effect.setVector3(\"vRefractionPosition\", cubeTexture.boundingBoxPosition);\n effect.setVector3(\"vRefractionSize\", cubeTexture.boundingBoxSize);\n }\n }\n /**\n * Gets the main code of the block (fragment side)\n * @param state current state of the node material building\n * @returns the shader code\n */\n getCode(state) {\n const code = \"\";\n state.sharedData.blockingBlocks.push(this);\n state.sharedData.textureBlocks.push(this);\n // Samplers\n this._cubeSamplerName = state._getFreeVariableName(this.name + \"CubeSampler\");\n state.samplers.push(this._cubeSamplerName);\n this._2DSamplerName = state._getFreeVariableName(this.name + \"2DSampler\");\n state.samplers.push(this._2DSamplerName);\n this._define3DName = state._getFreeDefineName(\"SS_REFRACTIONMAP_3D\");\n state._samplerDeclaration += `#ifdef ${this._define3DName}\\r\\n`;\n state._samplerDeclaration += `uniform samplerCube ${this._cubeSamplerName};\\r\\n`;\n state._samplerDeclaration += `#else\\r\\n`;\n state._samplerDeclaration += `uniform sampler2D ${this._2DSamplerName};\\r\\n`;\n state._samplerDeclaration += `#endif\\r\\n`;\n // Fragment\n state.sharedData.blocksWithDefines.push(this);\n state.sharedData.bindableBlocks.push(this);\n this._defineLODRefractionAlpha = state._getFreeDefineName(\"SS_LODINREFRACTIONALPHA\");\n this._defineLinearSpecularRefraction = state._getFreeDefineName(\"SS_LINEARSPECULARREFRACTION\");\n this._defineOppositeZ = state._getFreeDefineName(\"SS_REFRACTIONMAP_OPPOSITEZ\");\n this._refractionMatrixName = state._getFreeVariableName(\"refractionMatrix\");\n state._emitUniformFromString(this._refractionMatrixName, \"mat4\");\n state._emitFunction(\"sampleRefraction\", `\r\n #ifdef ${this._define3DName}\r\n #define sampleRefraction(s, c) textureCube(s, c)\r\n #else\r\n #define sampleRefraction(s, c) texture2D(s, c)\r\n #endif\\r\\n`, `//${this.name}`);\n state._emitFunction(\"sampleRefractionLod\", `\r\n #ifdef ${this._define3DName}\r\n #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l)\r\n #else\r\n #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l)\r\n #endif\\r\\n`, `//${this.name}`);\n this._vRefractionMicrosurfaceInfosName = state._getFreeVariableName(\"vRefractionMicrosurfaceInfos\");\n state._emitUniformFromString(this._vRefractionMicrosurfaceInfosName, \"vec4\");\n this._vRefractionInfosName = state._getFreeVariableName(\"vRefractionInfos\");\n state._emitUniformFromString(this._vRefractionInfosName, \"vec4\");\n this._vRefractionFilteringInfoName = state._getFreeVariableName(\"vRefractionFilteringInfo\");\n state._emitUniformFromString(this._vRefractionFilteringInfoName, \"vec2\");\n state._emitUniformFromString(\"vRefractionPosition\", \"vec3\");\n state._emitUniformFromString(\"vRefractionSize\", \"vec3\");\n return code;\n }\n _buildBlock(state) {\n this._scene = state.sharedData.scene;\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n if (this.texture) {\n if (this.texture.isCube) {\n codeString = `${this._codeVariableName}.texture = new BABYLON.CubeTexture(\"${this.texture.name}\");\\r\\n`;\n }\n else {\n codeString = `${this._codeVariableName}.texture = new BABYLON.Texture(\"${this.texture.name}\");\\r\\n`;\n }\n codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\\r\\n`;\n }\n codeString += `${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency};\\r\\n`;\n codeString += `${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY};\\r\\n`;\n codeString += `${this._codeVariableName}.useThicknessAsDepth = ${this.useThicknessAsDepth};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n if (this.texture && !this.texture.isRenderTarget) {\n serializationObject.texture = this.texture.serialize();\n }\n serializationObject.linkRefractionWithTransparency = this.linkRefractionWithTransparency;\n serializationObject.invertRefractionY = this.invertRefractionY;\n serializationObject.useThicknessAsDepth = this.useThicknessAsDepth;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n if (serializationObject.texture) {\n rootUrl = serializationObject.texture.url.indexOf(\"data:\") === 0 ? \"\" : rootUrl;\n if (serializationObject.texture.isCube) {\n this.texture = CubeTexture.Parse(serializationObject.texture, scene, rootUrl);\n }\n else {\n this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl);\n }\n }\n this.linkRefractionWithTransparency = serializationObject.linkRefractionWithTransparency;\n this.invertRefractionY = serializationObject.invertRefractionY;\n this.useThicknessAsDepth = !!serializationObject.useThicknessAsDepth;\n }\n}\n__decorate([\n editableInPropertyPage(\"Link refraction to transparency\", PropertyTypeForEdition.Boolean, \"ADVANCED\", { notifiers: { update: true } })\n], RefractionBlock.prototype, \"linkRefractionWithTransparency\", void 0);\n__decorate([\n editableInPropertyPage(\"Invert refraction Y\", PropertyTypeForEdition.Boolean, \"ADVANCED\", { notifiers: { update: true } })\n], RefractionBlock.prototype, \"invertRefractionY\", void 0);\n__decorate([\n editableInPropertyPage(\"Use thickness as depth\", PropertyTypeForEdition.Boolean, \"ADVANCED\", { notifiers: { update: true } })\n], RefractionBlock.prototype, \"useThicknessAsDepth\", void 0);\nRegisterClass(\"BABYLON.RefractionBlock\", RefractionBlock);\n//# sourceMappingURL=refractionBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../../nodeMaterialBlockConnectionPoint.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../../nodeMaterialConnectionPointCustomObject.js\";\nimport { RefractionBlock } from \"./refractionBlock.js\";\n/**\n * Block used to implement the sub surface module of the PBR material\n */\nexport class SubSurfaceBlock extends NodeMaterialBlock {\n /**\n * Create a new SubSurfaceBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this._isUnique = true;\n this.registerInput(\"thickness\", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"tintColor\", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"translucencyIntensity\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"translucencyDiffusionDist\", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"refraction\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"refraction\", this, NodeMaterialConnectionPointDirection.Input, RefractionBlock, \"RefractionBlock\"));\n this.registerOutput(\"subsurface\", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"subsurface\", this, NodeMaterialConnectionPointDirection.Output, SubSurfaceBlock, \"SubSurfaceBlock\"));\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"subSurfaceOut\");\n state._excludeVariableName(\"vThicknessParam\");\n state._excludeVariableName(\"vTintColor\");\n state._excludeVariableName(\"vSubSurfaceIntensity\");\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"SubSurfaceBlock\";\n }\n /**\n * Gets the thickness component\n */\n get thickness() {\n return this._inputs[0];\n }\n /**\n * Gets the tint color input component\n */\n get tintColor() {\n return this._inputs[1];\n }\n /**\n * Gets the translucency intensity input component\n */\n get translucencyIntensity() {\n return this._inputs[2];\n }\n /**\n * Gets the translucency diffusion distance input component\n */\n get translucencyDiffusionDist() {\n return this._inputs[3];\n }\n /**\n * Gets the refraction object parameters\n */\n get refraction() {\n return this._inputs[4];\n }\n /**\n * Gets the sub surface object output component\n */\n get subsurface() {\n return this._outputs[0];\n }\n autoConfigure() {\n if (!this.thickness.isConnected) {\n const thicknessInput = new InputBlock(\"SubSurface thickness\", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float);\n thicknessInput.value = 0;\n thicknessInput.output.connectTo(this.thickness);\n }\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n super.prepareDefines(mesh, nodeMaterial, defines);\n const translucencyEnabled = this.translucencyDiffusionDist.isConnected || this.translucencyIntensity.isConnected;\n defines.setValue(\"SUBSURFACE\", translucencyEnabled || this.refraction.isConnected, true);\n defines.setValue(\"SS_TRANSLUCENCY\", translucencyEnabled, true);\n defines.setValue(\"SS_THICKNESSANDMASK_TEXTURE\", false, true);\n defines.setValue(\"SS_REFRACTIONINTENSITY_TEXTURE\", false, true);\n defines.setValue(\"SS_TRANSLUCENCYINTENSITY_TEXTURE\", false, true);\n defines.setValue(\"SS_MASK_FROM_THICKNESS_TEXTURE\", false, true);\n defines.setValue(\"SS_USE_GLTF_TEXTURES\", false, true);\n }\n /**\n * Gets the main code of the block (fragment side)\n * @param state current state of the node material building\n * @param ssBlock instance of a SubSurfaceBlock or null if the code must be generated without an active sub surface module\n * @param reflectionBlock instance of a ReflectionBlock null if the code must be generated without an active reflection module\n * @param worldPosVarName name of the variable holding the world position\n * @returns the shader code\n */\n static GetCode(state, ssBlock, reflectionBlock, worldPosVarName) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;\n let code = \"\";\n const thickness = (ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.thickness.isConnected) ? ssBlock.thickness.associatedVariableName : \"0.\";\n const tintColor = (ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.tintColor.isConnected) ? ssBlock.tintColor.associatedVariableName : \"vec3(1.)\";\n const translucencyIntensity = (ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.translucencyIntensity.isConnected) ? ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.translucencyIntensity.associatedVariableName : \"1.\";\n const translucencyDiffusionDistance = (ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.translucencyDiffusionDist.isConnected) ? ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.translucencyDiffusionDist.associatedVariableName : \"vec3(1.)\";\n const refractionBlock = ((ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.refraction.isConnected) ? (_a = ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.refraction.connectedPoint) === null || _a === void 0 ? void 0 : _a.ownerBlock : null);\n const refractionTintAtDistance = (refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock.tintAtDistance.isConnected) ? refractionBlock.tintAtDistance.associatedVariableName : \"1.\";\n const refractionIntensity = (refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock.intensity.isConnected) ? refractionBlock.intensity.associatedVariableName : \"1.\";\n const refractionView = (refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock.view.isConnected) ? refractionBlock.view.associatedVariableName : \"\";\n code += (_b = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock.getCode(state)) !== null && _b !== void 0 ? _b : \"\";\n code += `subSurfaceOutParams subSurfaceOut;\r\n\r\n #ifdef SUBSURFACE\r\n vec2 vThicknessParam = vec2(0., ${thickness});\r\n vec4 vTintColor = vec4(${tintColor}, ${refractionTintAtDistance});\r\n vec3 vSubSurfaceIntensity = vec3(${refractionIntensity}, ${translucencyIntensity}, 0.);\r\n\r\n subSurfaceBlock(\r\n vSubSurfaceIntensity,\r\n vThicknessParam,\r\n vTintColor,\r\n normalW,\r\n specularEnvironmentReflectance,\r\n #ifdef SS_THICKNESSANDMASK_TEXTURE\r\n vec4(0.),\r\n #endif\r\n #ifdef REFLECTION\r\n #ifdef SS_TRANSLUCENCY\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._reflectionMatrixName},\r\n #ifdef USESPHERICALFROMREFLECTIONMAP\r\n #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\r\n reflectionOut.irradianceVector,\r\n #endif\r\n #if defined(REALTIME_FILTERING)\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName},\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._vReflectionFilteringInfoName},\r\n #endif\r\n #endif\r\n #ifdef USEIRRADIANCEMAP\r\n irradianceSampler,\r\n #endif\r\n #endif\r\n #endif\r\n #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)\r\n surfaceAlbedo,\r\n #endif\r\n #ifdef SS_REFRACTION\r\n ${worldPosVarName}.xyz,\r\n viewDirectionW,\r\n ${refractionView},\r\n ${(_c = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._vRefractionInfosName) !== null && _c !== void 0 ? _c : \"\"},\r\n ${(_d = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._refractionMatrixName) !== null && _d !== void 0 ? _d : \"\"},\r\n ${(_e = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._vRefractionMicrosurfaceInfosName) !== null && _e !== void 0 ? _e : \"\"},\r\n vLightingIntensity,\r\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\r\n alpha,\r\n #endif\r\n #ifdef ${(_f = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._defineLODRefractionAlpha) !== null && _f !== void 0 ? _f : \"IGNORE\"}\r\n NdotVUnclamped,\r\n #endif\r\n #ifdef ${(_g = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._defineLinearSpecularRefraction) !== null && _g !== void 0 ? _g : \"IGNORE\"}\r\n roughness,\r\n #endif\r\n alphaG,\r\n #ifdef ${(_h = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._define3DName) !== null && _h !== void 0 ? _h : \"IGNORE\"}\r\n ${(_j = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._cubeSamplerName) !== null && _j !== void 0 ? _j : \"\"},\r\n #else\r\n ${(_k = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._2DSamplerName) !== null && _k !== void 0 ? _k : \"\"},\r\n #endif\r\n #ifndef LODBASEDMICROSFURACE\r\n #ifdef ${(_l = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._define3DName) !== null && _l !== void 0 ? _l : \"IGNORE\"}\r\n ${(_m = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._cubeSamplerName) !== null && _m !== void 0 ? _m : \"\"},\r\n ${(_o = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._cubeSamplerName) !== null && _o !== void 0 ? _o : \"\"},\r\n #else\r\n ${(_p = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._2DSamplerName) !== null && _p !== void 0 ? _p : \"\"},\r\n ${(_q = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._2DSamplerName) !== null && _q !== void 0 ? _q : \"\"},\r\n #endif\r\n #endif\r\n #ifdef ANISOTROPIC\r\n anisotropicOut,\r\n #endif\r\n #ifdef REALTIME_FILTERING\r\n ${(_r = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._vRefractionFilteringInfoName) !== null && _r !== void 0 ? _r : \"\"},\r\n #endif\r\n #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\r\n vRefractionPosition,\r\n vRefractionSize,\r\n #endif\r\n #endif\r\n #ifdef SS_TRANSLUCENCY\r\n ${translucencyDiffusionDistance},\r\n #endif\r\n subSurfaceOut\r\n );\r\n\r\n #ifdef SS_REFRACTION\r\n surfaceAlbedo = subSurfaceOut.surfaceAlbedo;\r\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\r\n alpha = subSurfaceOut.alpha;\r\n #endif\r\n #endif\r\n #else\r\n subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance;\r\n #endif\\r\\n`;\n return code;\n }\n _buildBlock(state) {\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n state.sharedData.blocksWithDefines.push(this);\n }\n return this;\n }\n}\nRegisterClass(\"BABYLON.SubSurfaceBlock\", SubSurfaceBlock);\n//# sourceMappingURL=subSurfaceBlock.js.map","import { __decorate } from \"../../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../../nodeMaterialBlockConnectionPoint.js\";\nimport { MaterialHelper } from \"../../../materialHelper.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { NodeMaterialSystemValues } from \"../../Enums/nodeMaterialSystemValues.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { PBRBaseMaterial } from \"../../../PBR/pbrBaseMaterial.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../../nodeMaterialDecorator.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../../nodeMaterialConnectionPointCustomObject.js\";\nimport { SheenBlock } from \"./sheenBlock.js\";\nimport { GetEnvironmentBRDFTexture } from \"../../../../Misc/brdfTextureTools.js\";\nimport { MaterialFlags } from \"../../../materialFlags.js\";\nimport { AnisotropyBlock } from \"./anisotropyBlock.js\";\nimport { ReflectionBlock } from \"./reflectionBlock.js\";\nimport { ClearCoatBlock } from \"./clearCoatBlock.js\";\nimport { IridescenceBlock } from \"./iridescenceBlock.js\";\nimport { SubSurfaceBlock } from \"./subSurfaceBlock.js\";\n\nimport { Color3, TmpColors } from \"../../../../Maths/math.color.js\";\nconst mapOutputToVariable = {\n ambientClr: [\"finalAmbient\", \"\"],\n diffuseDir: [\"finalDiffuse\", \"\"],\n specularDir: [\"finalSpecularScaled\", \"!defined(UNLIT) && defined(SPECULARTERM)\"],\n clearcoatDir: [\"finalClearCoatScaled\", \"!defined(UNLIT) && defined(CLEARCOAT)\"],\n sheenDir: [\"finalSheenScaled\", \"!defined(UNLIT) && defined(SHEEN)\"],\n diffuseInd: [\"finalIrradiance\", \"!defined(UNLIT) && defined(REFLECTION)\"],\n specularInd: [\"finalRadianceScaled\", \"!defined(UNLIT) && defined(REFLECTION)\"],\n clearcoatInd: [\"clearcoatOut.finalClearCoatRadianceScaled\", \"!defined(UNLIT) && defined(REFLECTION) && defined(CLEARCOAT)\"],\n sheenInd: [\"sheenOut.finalSheenRadianceScaled\", \"!defined(UNLIT) && defined(REFLECTION) && defined(SHEEN) && defined(ENVIRONMENTBRDF)\"],\n refraction: [\"subSurfaceOut.finalRefraction\", \"!defined(UNLIT) && defined(SS_REFRACTION)\"],\n lighting: [\"finalColor.rgb\", \"\"],\n shadow: [\"shadow\", \"\"],\n alpha: [\"alpha\", \"\"],\n};\n/**\n * Block used to implement the PBR metallic/roughness model\n */\nexport class PBRMetallicRoughnessBlock extends NodeMaterialBlock {\n static _OnGenerateOnlyFragmentCodeChanged(block, _propertyName) {\n const that = block;\n if (that.worldPosition.isConnected) {\n that.generateOnlyFragmentCode = !that.generateOnlyFragmentCode;\n console.error(\"The worldPosition input must not be connected to be able to switch!\");\n return false;\n }\n that._setTarget();\n return true;\n }\n _setTarget() {\n this._setInitialTarget(this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.VertexAndFragment);\n this.getInputByName(\"worldPosition\").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex;\n }\n /**\n * Create a new ReflectionBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.VertexAndFragment);\n this._environmentBRDFTexture = null;\n this._metallicReflectanceColor = Color3.White();\n this._metallicF0Factor = 1;\n /**\n * Intensity of the direct lights e.g. the four lights available in your scene.\n * This impacts both the direct diffuse and specular highlights.\n */\n this.directIntensity = 1.0;\n /**\n * Intensity of the environment e.g. how much the environment will light the object\n * either through harmonics for rough material or through the reflection for shiny ones.\n */\n this.environmentIntensity = 1.0;\n /**\n * This is a special control allowing the reduction of the specular highlights coming from the\n * four lights of the scene. Those highlights may not be needed in full environment lighting.\n */\n this.specularIntensity = 1.0;\n /**\n * Defines the falloff type used in this material.\n * It by default is Physical.\n */\n this.lightFalloff = 0;\n /**\n * Specifies that alpha test should be used\n */\n this.useAlphaTest = false;\n /**\n * Defines the alpha limits in alpha test mode.\n */\n this.alphaTestCutoff = 0.5;\n /**\n * Specifies that alpha blending should be used\n */\n this.useAlphaBlending = false;\n /**\n * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most luminous ones).\n * A car glass is a good example of that. When the street lights reflects on it you can not see what is behind.\n */\n this.useRadianceOverAlpha = true;\n /**\n * Specifies that the material will keeps the specular highlights over a transparent surface (only the most luminous ones).\n * A car glass is a good example of that. When sun reflects on it you can not see what is behind.\n */\n this.useSpecularOverAlpha = true;\n /**\n * Enables specular anti aliasing in the PBR shader.\n * It will both interacts on the Geometry for analytical and IBL lighting.\n * It also prefilter the roughness map based on the bump values.\n */\n this.enableSpecularAntiAliasing = false;\n /**\n * Enables realtime filtering on the texture.\n */\n this.realTimeFiltering = false;\n /**\n * Quality switch for realtime filtering\n */\n this.realTimeFilteringQuality = 8;\n /**\n * Defines if the material uses energy conservation.\n */\n this.useEnergyConservation = true;\n /**\n * This parameters will enable/disable radiance occlusion by preventing the radiance to lit\n * too much the area relying on ambient texture to define their ambient occlusion.\n */\n this.useRadianceOcclusion = true;\n /**\n * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal\n * makes the reflect vector face the model (under horizon).\n */\n this.useHorizonOcclusion = true;\n /**\n * If set to true, no lighting calculations will be applied.\n */\n this.unlit = false;\n /**\n * Force normal to face away from face.\n */\n this.forceNormalForward = false;\n /** Indicates that no code should be generated in the vertex shader. Can be useful in some specific circumstances (like when doing ray marching for eg) */\n this.generateOnlyFragmentCode = false;\n /**\n * Defines the material debug mode.\n * It helps seeing only some components of the material while troubleshooting.\n */\n this.debugMode = 0;\n /**\n * Specify from where on screen the debug mode should start.\n * The value goes from -1 (full screen) to 1 (not visible)\n * It helps with side by side comparison against the final render\n * This defaults to 0\n */\n this.debugLimit = 0;\n /**\n * As the default viewing range might not be enough (if the ambient is really small for instance)\n * You can use the factor to better multiply the final value.\n */\n this.debugFactor = 1;\n this._isUnique = true;\n this.registerInput(\"worldPosition\", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex);\n this.registerInput(\"worldNormal\", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"view\", NodeMaterialBlockConnectionPointTypes.Matrix, false);\n this.registerInput(\"cameraPosition\", NodeMaterialBlockConnectionPointTypes.Vector3, false, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"perturbedNormal\", NodeMaterialBlockConnectionPointTypes.Vector4, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"baseColor\", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"metallic\", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"roughness\", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"ambientOcc\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"opacity\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"indexOfRefraction\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"ambientColor\", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"reflection\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"reflection\", this, NodeMaterialConnectionPointDirection.Input, ReflectionBlock, \"ReflectionBlock\"));\n this.registerInput(\"clearcoat\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"clearcoat\", this, NodeMaterialConnectionPointDirection.Input, ClearCoatBlock, \"ClearCoatBlock\"));\n this.registerInput(\"sheen\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"sheen\", this, NodeMaterialConnectionPointDirection.Input, SheenBlock, \"SheenBlock\"));\n this.registerInput(\"subsurface\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"subsurface\", this, NodeMaterialConnectionPointDirection.Input, SubSurfaceBlock, \"SubSurfaceBlock\"));\n this.registerInput(\"anisotropy\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"anisotropy\", this, NodeMaterialConnectionPointDirection.Input, AnisotropyBlock, \"AnisotropyBlock\"));\n this.registerInput(\"iridescence\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"iridescence\", this, NodeMaterialConnectionPointDirection.Input, IridescenceBlock, \"IridescenceBlock\"));\n this.registerOutput(\"ambientClr\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"diffuseDir\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"specularDir\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"clearcoatDir\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"sheenDir\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"diffuseInd\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"specularInd\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"clearcoatInd\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"sheenInd\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"refraction\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"lighting\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"shadow\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"alpha\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"vLightingIntensity\");\n state._excludeVariableName(\"geometricNormalW\");\n state._excludeVariableName(\"normalW\");\n state._excludeVariableName(\"faceNormal\");\n state._excludeVariableName(\"albedoOpacityOut\");\n state._excludeVariableName(\"surfaceAlbedo\");\n state._excludeVariableName(\"alpha\");\n state._excludeVariableName(\"aoOut\");\n state._excludeVariableName(\"baseColor\");\n state._excludeVariableName(\"reflectivityOut\");\n state._excludeVariableName(\"microSurface\");\n state._excludeVariableName(\"roughness\");\n state._excludeVariableName(\"NdotVUnclamped\");\n state._excludeVariableName(\"NdotV\");\n state._excludeVariableName(\"alphaG\");\n state._excludeVariableName(\"AARoughnessFactors\");\n state._excludeVariableName(\"environmentBrdf\");\n state._excludeVariableName(\"ambientMonochrome\");\n state._excludeVariableName(\"seo\");\n state._excludeVariableName(\"eho\");\n state._excludeVariableName(\"environmentRadiance\");\n state._excludeVariableName(\"irradianceVector\");\n state._excludeVariableName(\"environmentIrradiance\");\n state._excludeVariableName(\"diffuseBase\");\n state._excludeVariableName(\"specularBase\");\n state._excludeVariableName(\"preInfo\");\n state._excludeVariableName(\"info\");\n state._excludeVariableName(\"shadow\");\n state._excludeVariableName(\"finalDiffuse\");\n state._excludeVariableName(\"finalAmbient\");\n state._excludeVariableName(\"ambientOcclusionForDirectDiffuse\");\n state._excludeVariableName(\"finalColor\");\n state._excludeVariableName(\"vClipSpacePosition\");\n state._excludeVariableName(\"vDebugMode\");\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"PBRMetallicRoughnessBlock\";\n }\n /**\n * Gets the world position input component\n */\n get worldPosition() {\n return this._inputs[0];\n }\n /**\n * Gets the world normal input component\n */\n get worldNormal() {\n return this._inputs[1];\n }\n /**\n * Gets the view matrix parameter\n */\n get view() {\n return this._inputs[2];\n }\n /**\n * Gets the camera position input component\n */\n get cameraPosition() {\n return this._inputs[3];\n }\n /**\n * Gets the perturbed normal input component\n */\n get perturbedNormal() {\n return this._inputs[4];\n }\n /**\n * Gets the base color input component\n */\n get baseColor() {\n return this._inputs[5];\n }\n /**\n * Gets the metallic input component\n */\n get metallic() {\n return this._inputs[6];\n }\n /**\n * Gets the roughness input component\n */\n get roughness() {\n return this._inputs[7];\n }\n /**\n * Gets the ambient occlusion input component\n */\n get ambientOcc() {\n return this._inputs[8];\n }\n /**\n * Gets the opacity input component\n */\n get opacity() {\n return this._inputs[9];\n }\n /**\n * Gets the index of refraction input component\n */\n get indexOfRefraction() {\n return this._inputs[10];\n }\n /**\n * Gets the ambient color input component\n */\n get ambientColor() {\n return this._inputs[11];\n }\n /**\n * Gets the reflection object parameters\n */\n get reflection() {\n return this._inputs[12];\n }\n /**\n * Gets the clear coat object parameters\n */\n get clearcoat() {\n return this._inputs[13];\n }\n /**\n * Gets the sheen object parameters\n */\n get sheen() {\n return this._inputs[14];\n }\n /**\n * Gets the sub surface object parameters\n */\n get subsurface() {\n return this._inputs[15];\n }\n /**\n * Gets the anisotropy object parameters\n */\n get anisotropy() {\n return this._inputs[16];\n }\n /**\n * Gets the iridescence object parameters\n */\n get iridescence() {\n return this._inputs[17];\n }\n /**\n * Gets the ambient output component\n */\n get ambientClr() {\n return this._outputs[0];\n }\n /**\n * Gets the diffuse output component\n */\n get diffuseDir() {\n return this._outputs[1];\n }\n /**\n * Gets the specular output component\n */\n get specularDir() {\n return this._outputs[2];\n }\n /**\n * Gets the clear coat output component\n */\n get clearcoatDir() {\n return this._outputs[3];\n }\n /**\n * Gets the sheen output component\n */\n get sheenDir() {\n return this._outputs[4];\n }\n /**\n * Gets the indirect diffuse output component\n */\n get diffuseInd() {\n return this._outputs[5];\n }\n /**\n * Gets the indirect specular output component\n */\n get specularInd() {\n return this._outputs[6];\n }\n /**\n * Gets the indirect clear coat output component\n */\n get clearcoatInd() {\n return this._outputs[7];\n }\n /**\n * Gets the indirect sheen output component\n */\n get sheenInd() {\n return this._outputs[8];\n }\n /**\n * Gets the refraction output component\n */\n get refraction() {\n return this._outputs[9];\n }\n /**\n * Gets the global lighting output component\n */\n get lighting() {\n return this._outputs[10];\n }\n /**\n * Gets the shadow output component\n */\n get shadow() {\n return this._outputs[11];\n }\n /**\n * Gets the alpha output component\n */\n get alpha() {\n return this._outputs[12];\n }\n autoConfigure(material) {\n if (!this.cameraPosition.isConnected) {\n let cameraPositionInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.CameraPosition);\n if (!cameraPositionInput) {\n cameraPositionInput = new InputBlock(\"cameraPosition\");\n cameraPositionInput.setAsSystemValue(NodeMaterialSystemValues.CameraPosition);\n }\n cameraPositionInput.output.connectTo(this.cameraPosition);\n }\n if (!this.view.isConnected) {\n let viewInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.View);\n if (!viewInput) {\n viewInput = new InputBlock(\"view\");\n viewInput.setAsSystemValue(NodeMaterialSystemValues.View);\n }\n viewInput.output.connectTo(this.view);\n }\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n // General\n defines.setValue(\"PBR\", true);\n defines.setValue(\"METALLICWORKFLOW\", true);\n defines.setValue(\"DEBUGMODE\", this.debugMode, true);\n defines.setValue(\"NORMALXYSCALE\", true);\n defines.setValue(\"BUMP\", this.perturbedNormal.isConnected, true);\n defines.setValue(\"LODBASEDMICROSFURACE\", this._scene.getEngine().getCaps().textureLOD);\n // Albedo & Opacity\n defines.setValue(\"ALBEDO\", false, true);\n defines.setValue(\"OPACITY\", this.opacity.isConnected, true);\n // Ambient occlusion\n defines.setValue(\"AMBIENT\", true, true);\n defines.setValue(\"AMBIENTINGRAYSCALE\", false, true);\n // Reflectivity\n defines.setValue(\"REFLECTIVITY\", false, true);\n defines.setValue(\"AOSTOREINMETALMAPRED\", false, true);\n defines.setValue(\"METALLNESSSTOREINMETALMAPBLUE\", false, true);\n defines.setValue(\"ROUGHNESSSTOREINMETALMAPALPHA\", false, true);\n defines.setValue(\"ROUGHNESSSTOREINMETALMAPGREEN\", false, true);\n // Lighting & colors\n if (this.lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {\n defines.setValue(\"USEPHYSICALLIGHTFALLOFF\", false);\n defines.setValue(\"USEGLTFLIGHTFALLOFF\", false);\n }\n else if (this.lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {\n defines.setValue(\"USEPHYSICALLIGHTFALLOFF\", false);\n defines.setValue(\"USEGLTFLIGHTFALLOFF\", true);\n }\n else {\n defines.setValue(\"USEPHYSICALLIGHTFALLOFF\", true);\n defines.setValue(\"USEGLTFLIGHTFALLOFF\", false);\n }\n // Transparency\n const alphaTestCutOffString = this.alphaTestCutoff.toString();\n defines.setValue(\"ALPHABLEND\", this.useAlphaBlending, true);\n defines.setValue(\"ALPHAFROMALBEDO\", false, true);\n defines.setValue(\"ALPHATEST\", this.useAlphaTest, true);\n defines.setValue(\"ALPHATESTVALUE\", alphaTestCutOffString.indexOf(\".\") < 0 ? alphaTestCutOffString + \".\" : alphaTestCutOffString, true);\n defines.setValue(\"OPACITYRGB\", false, true);\n // Rendering\n defines.setValue(\"RADIANCEOVERALPHA\", this.useRadianceOverAlpha, true);\n defines.setValue(\"SPECULAROVERALPHA\", this.useSpecularOverAlpha, true);\n defines.setValue(\"SPECULARAA\", this._scene.getEngine().getCaps().standardDerivatives && this.enableSpecularAntiAliasing, true);\n defines.setValue(\"REALTIME_FILTERING\", this.realTimeFiltering, true);\n const scene = mesh.getScene();\n const engine = scene.getEngine();\n if (engine._features.needTypeSuffixInShaderConstants) {\n defines.setValue(\"NUM_SAMPLES\", this.realTimeFilteringQuality + \"u\", true);\n }\n else {\n defines.setValue(\"NUM_SAMPLES\", \"\" + this.realTimeFilteringQuality, true);\n }\n // Advanced\n defines.setValue(\"BRDF_V_HEIGHT_CORRELATED\", true);\n defines.setValue(\"MS_BRDF_ENERGY_CONSERVATION\", this.useEnergyConservation, true);\n defines.setValue(\"RADIANCEOCCLUSION\", this.useRadianceOcclusion, true);\n defines.setValue(\"HORIZONOCCLUSION\", this.useHorizonOcclusion, true);\n defines.setValue(\"UNLIT\", this.unlit, true);\n defines.setValue(\"FORCENORMALFORWARD\", this.forceNormalForward, true);\n if (this._environmentBRDFTexture && MaterialFlags.ReflectionTextureEnabled) {\n defines.setValue(\"ENVIRONMENTBRDF\", true);\n defines.setValue(\"ENVIRONMENTBRDF_RGBD\", this._environmentBRDFTexture.isRGBD, true);\n }\n else {\n defines.setValue(\"ENVIRONMENTBRDF\", false);\n defines.setValue(\"ENVIRONMENTBRDF_RGBD\", false);\n }\n if (defines._areImageProcessingDirty && nodeMaterial.imageProcessingConfiguration) {\n nodeMaterial.imageProcessingConfiguration.prepareDefines(defines);\n }\n if (!defines._areLightsDirty) {\n return;\n }\n if (!this.light) {\n // Lights\n MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, nodeMaterial.maxSimultaneousLights);\n defines._needNormals = true;\n // Multiview\n MaterialHelper.PrepareDefinesForMultiview(scene, defines);\n }\n else {\n const state = {\n needNormals: false,\n needRebuild: false,\n lightmapMode: false,\n shadowEnabled: false,\n specularEnabled: false,\n };\n MaterialHelper.PrepareDefinesForLight(scene, mesh, this.light, this._lightId, defines, true, state);\n if (state.needRebuild) {\n defines.rebuild();\n }\n }\n }\n updateUniformsAndSamples(state, nodeMaterial, defines, uniformBuffers) {\n for (let lightIndex = 0; lightIndex < nodeMaterial.maxSimultaneousLights; lightIndex++) {\n if (!defines[\"LIGHT\" + lightIndex]) {\n break;\n }\n const onlyUpdateBuffersList = state.uniforms.indexOf(\"vLightData\" + lightIndex) >= 0;\n MaterialHelper.PrepareUniformsAndSamplersForLight(lightIndex, state.uniforms, state.samplers, defines[\"PROJECTEDLIGHTTEXTURE\" + lightIndex], uniformBuffers, onlyUpdateBuffersList);\n }\n }\n isReady(mesh, nodeMaterial, defines) {\n if (this._environmentBRDFTexture && !this._environmentBRDFTexture.isReady()) {\n return false;\n }\n if (defines._areImageProcessingDirty && nodeMaterial.imageProcessingConfiguration) {\n if (!nodeMaterial.imageProcessingConfiguration.isReady()) {\n return false;\n }\n }\n return true;\n }\n bind(effect, nodeMaterial, mesh) {\n var _a, _b;\n if (!mesh) {\n return;\n }\n const scene = mesh.getScene();\n if (!this.light) {\n MaterialHelper.BindLights(scene, mesh, effect, true, nodeMaterial.maxSimultaneousLights);\n }\n else {\n MaterialHelper.BindLight(this.light, this._lightId, scene, effect, true);\n }\n effect.setTexture(this._environmentBrdfSamplerName, this._environmentBRDFTexture);\n effect.setFloat2(\"vDebugMode\", this.debugLimit, this.debugFactor);\n const ambientScene = this._scene.ambientColor;\n if (ambientScene) {\n effect.setColor3(\"ambientFromScene\", ambientScene);\n }\n const invertNormal = scene.useRightHandedSystem === (scene._mirroredCameraPosition != null);\n effect.setFloat(this._invertNormalName, invertNormal ? -1 : 1);\n effect.setFloat4(\"vLightingIntensity\", this.directIntensity, 1, this.environmentIntensity * this._scene.environmentIntensity, this.specularIntensity);\n // reflectivity bindings\n const outsideIOR = 1; // consider air as clear coat and other layers would remap in the shader.\n const ior = (_b = (_a = this.indexOfRefraction.connectInputBlock) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : 1.5;\n // We are here deriving our default reflectance from a common value for none metallic surface.\n // Based of the schlick fresnel approximation model\n // for dielectrics.\n const f0 = Math.pow((ior - outsideIOR) / (ior + outsideIOR), 2);\n // Tweak the default F0 and F90 based on our given setup\n this._metallicReflectanceColor.scaleToRef(f0 * this._metallicF0Factor, TmpColors.Color3[0]);\n const metallicF90 = this._metallicF0Factor;\n effect.setColor4(this._vMetallicReflectanceFactorsName, TmpColors.Color3[0], metallicF90);\n if (nodeMaterial.imageProcessingConfiguration) {\n nodeMaterial.imageProcessingConfiguration.bind(effect);\n }\n }\n _injectVertexCode(state) {\n var _a, _b;\n const worldPos = this.worldPosition;\n const comments = `//${this.name}`;\n // Declaration\n if (!this.light) {\n // Emit for all lights\n state._emitFunctionFromInclude(state.supportUniformBuffers ? \"lightVxUboDeclaration\" : \"lightVxFragmentDeclaration\", comments, {\n repeatKey: \"maxSimultaneousLights\",\n });\n this._lightId = 0;\n state.sharedData.dynamicUniformBlocks.push(this);\n }\n else {\n this._lightId = (state.counters[\"lightCounter\"] !== undefined ? state.counters[\"lightCounter\"] : -1) + 1;\n state.counters[\"lightCounter\"] = this._lightId;\n state._emitFunctionFromInclude(state.supportUniformBuffers ? \"lightVxUboDeclaration\" : \"lightVxFragmentDeclaration\", comments, {\n replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }],\n }, this._lightId.toString());\n }\n // Inject code in vertex\n const worldPosVaryingName = \"v_\" + worldPos.associatedVariableName;\n if (state._emitVaryingFromString(worldPosVaryingName, \"vec4\")) {\n state.compilationString += `${worldPosVaryingName} = ${worldPos.associatedVariableName};\\r\\n`;\n }\n const reflectionBlock = this.reflection.isConnected ? (_a = this.reflection.connectedPoint) === null || _a === void 0 ? void 0 : _a.ownerBlock : null;\n if (reflectionBlock) {\n reflectionBlock.viewConnectionPoint = this.view;\n }\n state.compilationString += (_b = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock.handleVertexSide(state)) !== null && _b !== void 0 ? _b : \"\";\n if (state._emitVaryingFromString(\"vClipSpacePosition\", \"vec4\", \"defined(IGNORE) || DEBUGMODE > 0\")) {\n state._injectAtEnd += `#if DEBUGMODE > 0\\r\\n`;\n state._injectAtEnd += `vClipSpacePosition = gl_Position;\\r\\n`;\n state._injectAtEnd += `#endif\\r\\n`;\n }\n if (this.light) {\n state.compilationString += state._emitCodeFromInclude(\"shadowsVertex\", comments, {\n replaceStrings: [\n { search: /{X}/g, replace: this._lightId.toString() },\n { search: /worldPos/g, replace: worldPos.associatedVariableName },\n ],\n });\n }\n else {\n state.compilationString += `vec4 worldPos = ${worldPos.associatedVariableName};\\r\\n`;\n if (this.view.isConnected) {\n state.compilationString += `mat4 view = ${this.view.associatedVariableName};\\r\\n`;\n }\n state.compilationString += state._emitCodeFromInclude(\"shadowsVertex\", comments, {\n repeatKey: \"maxSimultaneousLights\",\n });\n }\n }\n _getAlbedoOpacityCode() {\n let code = `albedoOpacityOutParams albedoOpacityOut;\\r\\n`;\n const albedoColor = this.baseColor.isConnected ? this.baseColor.associatedVariableName : \"vec3(1.)\";\n const opacity = this.opacity.isConnected ? this.opacity.associatedVariableName : \"1.\";\n code += `albedoOpacityBlock(\r\n vec4(${albedoColor}, 1.),\r\n #ifdef ALBEDO\r\n vec4(1.),\r\n vec2(1., 1.),\r\n #endif\r\n #ifdef OPACITY\r\n vec4(${opacity}),\r\n vec2(1., 1.),\r\n #endif\r\n albedoOpacityOut\r\n );\r\n\r\n vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo;\r\n float alpha = albedoOpacityOut.alpha;\\r\\n`;\n return code;\n }\n _getAmbientOcclusionCode() {\n let code = `ambientOcclusionOutParams aoOut;\\r\\n`;\n const ao = this.ambientOcc.isConnected ? this.ambientOcc.associatedVariableName : \"1.\";\n code += `ambientOcclusionBlock(\r\n #ifdef AMBIENT\r\n vec3(${ao}),\r\n vec4(0., 1.0, 1.0, 0.),\r\n #endif\r\n aoOut\r\n );\\r\\n`;\n return code;\n }\n _getReflectivityCode(state) {\n let code = `reflectivityOutParams reflectivityOut;\\r\\n`;\n const aoIntensity = \"1.\";\n this._vMetallicReflectanceFactorsName = state._getFreeVariableName(\"vMetallicReflectanceFactors\");\n state._emitUniformFromString(this._vMetallicReflectanceFactorsName, \"vec4\");\n code += `vec3 baseColor = surfaceAlbedo;\r\n\r\n reflectivityBlock(\r\n vec4(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.),\r\n #ifdef METALLICWORKFLOW\r\n surfaceAlbedo,\r\n ${this._vMetallicReflectanceFactorsName},\r\n #endif\r\n #ifdef REFLECTIVITY\r\n vec3(0., 0., ${aoIntensity}),\r\n vec4(1.),\r\n #endif\r\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\r\n aoOut.ambientOcclusionColor,\r\n #endif\r\n #ifdef MICROSURFACEMAP\r\n microSurfaceTexel, <== not handled!\r\n #endif\r\n reflectivityOut\r\n );\r\n\r\n float microSurface = reflectivityOut.microSurface;\r\n float roughness = reflectivityOut.roughness;\r\n\r\n #ifdef METALLICWORKFLOW\r\n surfaceAlbedo = reflectivityOut.surfaceAlbedo;\r\n #endif\r\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\r\n aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor;\r\n #endif\\r\\n`;\n return code;\n }\n _buildBlock(state) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16;\n super._buildBlock(state);\n this._scene = state.sharedData.scene;\n if (!this._environmentBRDFTexture) {\n this._environmentBRDFTexture = GetEnvironmentBRDFTexture(this._scene);\n }\n const reflectionBlock = this.reflection.isConnected ? (_a = this.reflection.connectedPoint) === null || _a === void 0 ? void 0 : _a.ownerBlock : null;\n if (reflectionBlock) {\n // Need those variables to be setup when calling _injectVertexCode\n reflectionBlock.worldPositionConnectionPoint = this.worldPosition;\n reflectionBlock.cameraPositionConnectionPoint = this.cameraPosition;\n reflectionBlock.worldNormalConnectionPoint = this.worldNormal;\n reflectionBlock.viewConnectionPoint = this.view;\n }\n if (state.target !== NodeMaterialBlockTargets.Fragment) {\n // Vertex\n this._injectVertexCode(state);\n return this;\n }\n // Fragment\n state.sharedData.forcedBindableBlocks.push(this);\n state.sharedData.blocksWithDefines.push(this);\n state.sharedData.blockingBlocks.push(this);\n if (this.generateOnlyFragmentCode) {\n state.sharedData.dynamicUniformBlocks.push(this);\n }\n const comments = `//${this.name}`;\n const normalShading = this.perturbedNormal;\n let worldPosVarName = this.worldPosition.associatedVariableName;\n if (this.generateOnlyFragmentCode) {\n worldPosVarName = state._getFreeVariableName(\"globalWorldPos\");\n state._emitFunction(\"pbr_globalworldpos\", `vec3 ${worldPosVarName};\\r\\n`, comments);\n state.compilationString += `${worldPosVarName} = ${this.worldPosition.associatedVariableName}.xyz;\\r\\n`;\n state.compilationString += state._emitCodeFromInclude(\"shadowsVertex\", comments, {\n repeatKey: \"maxSimultaneousLights\",\n substitutionVars: this.generateOnlyFragmentCode ? `worldPos,${this.worldPosition.associatedVariableName}` : undefined,\n });\n state.compilationString += `#if DEBUGMODE > 0\\r\\n`;\n state.compilationString += `vec4 vClipSpacePosition = vec4((vec2(gl_FragCoord.xy) / vec2(1.0)) * 2.0 - 1.0, 0.0, 1.0);\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n }\n else {\n worldPosVarName = \"v_\" + worldPosVarName;\n }\n this._environmentBrdfSamplerName = state._getFreeVariableName(\"environmentBrdfSampler\");\n state._emit2DSampler(this._environmentBrdfSamplerName);\n state.sharedData.hints.needAlphaBlending = state.sharedData.hints.needAlphaBlending || this.useAlphaBlending;\n state.sharedData.hints.needAlphaTesting = state.sharedData.hints.needAlphaTesting || this.useAlphaTest;\n state._emitExtension(\"lod\", \"#extension GL_EXT_shader_texture_lod : enable\", \"defined(LODBASEDMICROSFURACE)\");\n state._emitExtension(\"derivatives\", \"#extension GL_OES_standard_derivatives : enable\");\n state._emitUniformFromString(\"vDebugMode\", \"vec2\", \"defined(IGNORE) || DEBUGMODE > 0\");\n state._emitUniformFromString(\"ambientFromScene\", \"vec3\");\n // Image processing uniforms\n state.uniforms.push(\"exposureLinear\");\n state.uniforms.push(\"contrast\");\n state.uniforms.push(\"vInverseScreenSize\");\n state.uniforms.push(\"vignetteSettings1\");\n state.uniforms.push(\"vignetteSettings2\");\n state.uniforms.push(\"vCameraColorCurveNegative\");\n state.uniforms.push(\"vCameraColorCurveNeutral\");\n state.uniforms.push(\"vCameraColorCurvePositive\");\n state.uniforms.push(\"txColorTransform\");\n state.uniforms.push(\"colorTransformSettings\");\n state.uniforms.push(\"ditherIntensity\");\n //\n // Includes\n //\n if (!this.light) {\n // Emit for all lights\n state._emitFunctionFromInclude(state.supportUniformBuffers ? \"lightUboDeclaration\" : \"lightFragmentDeclaration\", comments, {\n repeatKey: \"maxSimultaneousLights\",\n substitutionVars: this.generateOnlyFragmentCode ? \"varying,\" : undefined,\n });\n }\n else {\n state._emitFunctionFromInclude(state.supportUniformBuffers ? \"lightUboDeclaration\" : \"lightFragmentDeclaration\", comments, {\n replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }],\n }, this._lightId.toString());\n }\n state._emitFunctionFromInclude(\"helperFunctions\", comments);\n state._emitFunctionFromInclude(\"importanceSampling\", comments);\n state._emitFunctionFromInclude(\"pbrHelperFunctions\", comments);\n state._emitFunctionFromInclude(\"imageProcessingDeclaration\", comments);\n state._emitFunctionFromInclude(\"imageProcessingFunctions\", comments);\n state._emitFunctionFromInclude(\"shadowsFragmentFunctions\", comments, {\n replaceStrings: [{ search: /vPositionW/g, replace: worldPosVarName + \".xyz\" }],\n });\n state._emitFunctionFromInclude(\"pbrDirectLightingSetupFunctions\", comments, {\n replaceStrings: [{ search: /vPositionW/g, replace: worldPosVarName + \".xyz\" }],\n });\n state._emitFunctionFromInclude(\"pbrDirectLightingFalloffFunctions\", comments);\n state._emitFunctionFromInclude(\"pbrBRDFFunctions\", comments, {\n replaceStrings: [{ search: /REFLECTIONMAP_SKYBOX/g, replace: (_b = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName) !== null && _b !== void 0 ? _b : \"REFLECTIONMAP_SKYBOX\" }],\n });\n state._emitFunctionFromInclude(\"hdrFilteringFunctions\", comments);\n state._emitFunctionFromInclude(\"pbrDirectLightingFunctions\", comments, {\n replaceStrings: [{ search: /vPositionW/g, replace: worldPosVarName + \".xyz\" }],\n });\n state._emitFunctionFromInclude(\"pbrIBLFunctions\", comments);\n state._emitFunctionFromInclude(\"pbrBlockAlbedoOpacity\", comments);\n state._emitFunctionFromInclude(\"pbrBlockReflectivity\", comments);\n state._emitFunctionFromInclude(\"pbrBlockAmbientOcclusion\", comments);\n state._emitFunctionFromInclude(\"pbrBlockAlphaFresnel\", comments);\n state._emitFunctionFromInclude(\"pbrBlockAnisotropic\", comments);\n //\n // code\n //\n state._emitUniformFromString(\"vLightingIntensity\", \"vec4\");\n if (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock.generateOnlyFragmentCode) {\n state.compilationString += reflectionBlock.handleVertexSide(state);\n }\n // _____________________________ Geometry Information ____________________________\n this._vNormalWName = state._getFreeVariableName(\"vNormalW\");\n state.compilationString += `vec4 ${this._vNormalWName} = normalize(${this.worldNormal.associatedVariableName});\\r\\n`;\n if (state._registerTempVariable(\"viewDirectionW\")) {\n state.compilationString += `vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${worldPosVarName}.xyz);\\r\\n`;\n }\n state.compilationString += `vec3 geometricNormalW = ${this._vNormalWName}.xyz;\\r\\n`;\n state.compilationString += `vec3 normalW = ${normalShading.isConnected ? \"normalize(\" + normalShading.associatedVariableName + \".xyz)\" : \"geometricNormalW\"};\\r\\n`;\n this._invertNormalName = state._getFreeVariableName(\"invertNormal\");\n state._emitUniformFromString(this._invertNormalName, \"float\");\n state.compilationString += state._emitCodeFromInclude(\"pbrBlockNormalFinal\", comments, {\n replaceStrings: [\n { search: /vPositionW/g, replace: worldPosVarName + \".xyz\" },\n { search: /vEyePosition.w/g, replace: this._invertNormalName },\n ],\n });\n // _____________________________ Albedo & Opacity ______________________________\n state.compilationString += this._getAlbedoOpacityCode();\n state.compilationString += state._emitCodeFromInclude(\"depthPrePass\", comments);\n // _____________________________ AO _______________________________\n state.compilationString += this._getAmbientOcclusionCode();\n state.compilationString += state._emitCodeFromInclude(\"pbrBlockLightmapInit\", comments);\n // _____________________________ UNLIT _______________________________\n state.compilationString += `#ifdef UNLIT\r\n vec3 diffuseBase = vec3(1., 1., 1.);\r\n #else\\r\\n`;\n // _____________________________ Reflectivity _______________________________\n state.compilationString += this._getReflectivityCode(state);\n // _____________________________ Geometry info _________________________________\n state.compilationString += state._emitCodeFromInclude(\"pbrBlockGeometryInfo\", comments, {\n replaceStrings: [\n { search: /REFLECTIONMAP_SKYBOX/g, replace: (_c = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName) !== null && _c !== void 0 ? _c : \"REFLECTIONMAP_SKYBOX\" },\n { search: /REFLECTIONMAP_3D/g, replace: (_d = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) !== null && _d !== void 0 ? _d : \"REFLECTIONMAP_3D\" },\n ],\n });\n // _____________________________ Anisotropy _______________________________________\n const anisotropyBlock = this.anisotropy.isConnected ? (_e = this.anisotropy.connectedPoint) === null || _e === void 0 ? void 0 : _e.ownerBlock : null;\n if (anisotropyBlock) {\n anisotropyBlock.worldPositionConnectionPoint = this.worldPosition;\n anisotropyBlock.worldNormalConnectionPoint = this.worldNormal;\n state.compilationString += anisotropyBlock.getCode(state, !this.perturbedNormal.isConnected);\n }\n // _____________________________ Reflection _______________________________________\n if (reflectionBlock && reflectionBlock.hasTexture) {\n state.compilationString += reflectionBlock.getCode(state, anisotropyBlock ? \"anisotropicOut.anisotropicNormal\" : \"normalW\");\n }\n state._emitFunctionFromInclude(\"pbrBlockReflection\", comments, {\n replaceStrings: [\n { search: /computeReflectionCoords/g, replace: \"computeReflectionCoordsPBR\" },\n { search: /REFLECTIONMAP_3D/g, replace: (_f = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) !== null && _f !== void 0 ? _f : \"REFLECTIONMAP_3D\" },\n { search: /REFLECTIONMAP_OPPOSITEZ/g, replace: (_g = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineOppositeZ) !== null && _g !== void 0 ? _g : \"REFLECTIONMAP_OPPOSITEZ\" },\n { search: /REFLECTIONMAP_PROJECTION/g, replace: (_h = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineProjectionName) !== null && _h !== void 0 ? _h : \"REFLECTIONMAP_PROJECTION\" },\n { search: /REFLECTIONMAP_SKYBOX/g, replace: (_j = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName) !== null && _j !== void 0 ? _j : \"REFLECTIONMAP_SKYBOX\" },\n { search: /LODINREFLECTIONALPHA/g, replace: (_k = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineLODReflectionAlpha) !== null && _k !== void 0 ? _k : \"LODINREFLECTIONALPHA\" },\n { search: /LINEARSPECULARREFLECTION/g, replace: (_l = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineLinearSpecularReflection) !== null && _l !== void 0 ? _l : \"LINEARSPECULARREFLECTION\" },\n { search: /vReflectionFilteringInfo/g, replace: (_m = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._vReflectionFilteringInfoName) !== null && _m !== void 0 ? _m : \"vReflectionFilteringInfo\" },\n ],\n });\n // ___________________ Compute Reflectance aka R0 F0 info _________________________\n state.compilationString += state._emitCodeFromInclude(\"pbrBlockReflectance0\", comments, {\n replaceStrings: [{ search: /metallicReflectanceFactors/g, replace: this._vMetallicReflectanceFactorsName }],\n });\n // ________________________________ Sheen ______________________________\n const sheenBlock = this.sheen.isConnected ? (_o = this.sheen.connectedPoint) === null || _o === void 0 ? void 0 : _o.ownerBlock : null;\n if (sheenBlock) {\n state.compilationString += sheenBlock.getCode(reflectionBlock);\n }\n state._emitFunctionFromInclude(\"pbrBlockSheen\", comments, {\n replaceStrings: [\n { search: /REFLECTIONMAP_3D/g, replace: (_p = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) !== null && _p !== void 0 ? _p : \"REFLECTIONMAP_3D\" },\n { search: /REFLECTIONMAP_SKYBOX/g, replace: (_q = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName) !== null && _q !== void 0 ? _q : \"REFLECTIONMAP_SKYBOX\" },\n { search: /LODINREFLECTIONALPHA/g, replace: (_r = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineLODReflectionAlpha) !== null && _r !== void 0 ? _r : \"LODINREFLECTIONALPHA\" },\n { search: /LINEARSPECULARREFLECTION/g, replace: (_s = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineLinearSpecularReflection) !== null && _s !== void 0 ? _s : \"LINEARSPECULARREFLECTION\" },\n ],\n });\n // _____________________________ Iridescence _______________________________\n const iridescenceBlock = this.iridescence.isConnected ? (_t = this.iridescence.connectedPoint) === null || _t === void 0 ? void 0 : _t.ownerBlock : null;\n state.compilationString += IridescenceBlock.GetCode(iridescenceBlock);\n state._emitFunctionFromInclude(\"pbrBlockIridescence\", comments, {\n replaceStrings: [],\n });\n // _____________________________ Clear Coat ____________________________\n const clearcoatBlock = this.clearcoat.isConnected ? (_u = this.clearcoat.connectedPoint) === null || _u === void 0 ? void 0 : _u.ownerBlock : null;\n const generateTBNSpace = !this.perturbedNormal.isConnected && !this.anisotropy.isConnected;\n const isTangentConnectedToPerturbNormal = this.perturbedNormal.isConnected && ((_w = ((_v = this.perturbedNormal.connectedPoint) === null || _v === void 0 ? void 0 : _v.ownerBlock).worldTangent) === null || _w === void 0 ? void 0 : _w.isConnected);\n const isTangentConnectedToAnisotropy = this.anisotropy.isConnected && ((_x = this.anisotropy.connectedPoint) === null || _x === void 0 ? void 0 : _x.ownerBlock).worldTangent.isConnected;\n let vTBNAvailable = isTangentConnectedToPerturbNormal || (!this.perturbedNormal.isConnected && isTangentConnectedToAnisotropy);\n state.compilationString += ClearCoatBlock.GetCode(state, clearcoatBlock, reflectionBlock, worldPosVarName, generateTBNSpace, vTBNAvailable, this.worldNormal.associatedVariableName);\n if (generateTBNSpace) {\n vTBNAvailable = (_y = clearcoatBlock === null || clearcoatBlock === void 0 ? void 0 : clearcoatBlock.worldTangent.isConnected) !== null && _y !== void 0 ? _y : false;\n }\n state._emitFunctionFromInclude(\"pbrBlockClearcoat\", comments, {\n replaceStrings: [\n { search: /computeReflectionCoords/g, replace: \"computeReflectionCoordsPBR\" },\n { search: /REFLECTIONMAP_3D/g, replace: (_z = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) !== null && _z !== void 0 ? _z : \"REFLECTIONMAP_3D\" },\n { search: /REFLECTIONMAP_OPPOSITEZ/g, replace: (_0 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineOppositeZ) !== null && _0 !== void 0 ? _0 : \"REFLECTIONMAP_OPPOSITEZ\" },\n { search: /REFLECTIONMAP_PROJECTION/g, replace: (_1 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineProjectionName) !== null && _1 !== void 0 ? _1 : \"REFLECTIONMAP_PROJECTION\" },\n { search: /REFLECTIONMAP_SKYBOX/g, replace: (_2 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName) !== null && _2 !== void 0 ? _2 : \"REFLECTIONMAP_SKYBOX\" },\n { search: /LODINREFLECTIONALPHA/g, replace: (_3 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineLODReflectionAlpha) !== null && _3 !== void 0 ? _3 : \"LODINREFLECTIONALPHA\" },\n { search: /LINEARSPECULARREFLECTION/g, replace: (_4 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineLinearSpecularReflection) !== null && _4 !== void 0 ? _4 : \"LINEARSPECULARREFLECTION\" },\n { search: /defined\\(TANGENT\\)/g, replace: vTBNAvailable ? \"defined(TANGENT)\" : \"defined(IGNORE)\" },\n ],\n });\n // _________________________ Specular Environment Reflectance __________________________\n state.compilationString += state._emitCodeFromInclude(\"pbrBlockReflectance\", comments, {\n replaceStrings: [\n { search: /REFLECTIONMAP_SKYBOX/g, replace: (_5 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName) !== null && _5 !== void 0 ? _5 : \"REFLECTIONMAP_SKYBOX\" },\n { search: /REFLECTIONMAP_3D/g, replace: (_6 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) !== null && _6 !== void 0 ? _6 : \"REFLECTIONMAP_3D\" },\n ],\n });\n // ___________________________________ SubSurface ______________________________________\n const subsurfaceBlock = this.subsurface.isConnected ? (_7 = this.subsurface.connectedPoint) === null || _7 === void 0 ? void 0 : _7.ownerBlock : null;\n const refractionBlock = this.subsurface.isConnected\n ? (_9 = ((_8 = this.subsurface.connectedPoint) === null || _8 === void 0 ? void 0 : _8.ownerBlock).refraction.connectedPoint) === null || _9 === void 0 ? void 0 : _9.ownerBlock\n : null;\n if (refractionBlock) {\n refractionBlock.viewConnectionPoint = this.view;\n refractionBlock.indexOfRefractionConnectionPoint = this.indexOfRefraction;\n }\n state.compilationString += SubSurfaceBlock.GetCode(state, subsurfaceBlock, reflectionBlock, worldPosVarName);\n state._emitFunctionFromInclude(\"pbrBlockSubSurface\", comments, {\n replaceStrings: [\n { search: /REFLECTIONMAP_3D/g, replace: (_10 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) !== null && _10 !== void 0 ? _10 : \"REFLECTIONMAP_3D\" },\n { search: /REFLECTIONMAP_OPPOSITEZ/g, replace: (_11 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineOppositeZ) !== null && _11 !== void 0 ? _11 : \"REFLECTIONMAP_OPPOSITEZ\" },\n { search: /REFLECTIONMAP_PROJECTION/g, replace: (_12 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineProjectionName) !== null && _12 !== void 0 ? _12 : \"REFLECTIONMAP_PROJECTION\" },\n { search: /SS_REFRACTIONMAP_3D/g, replace: (_13 = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._define3DName) !== null && _13 !== void 0 ? _13 : \"SS_REFRACTIONMAP_3D\" },\n { search: /SS_LODINREFRACTIONALPHA/g, replace: (_14 = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._defineLODRefractionAlpha) !== null && _14 !== void 0 ? _14 : \"SS_LODINREFRACTIONALPHA\" },\n { search: /SS_LINEARSPECULARREFRACTION/g, replace: (_15 = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._defineLinearSpecularRefraction) !== null && _15 !== void 0 ? _15 : \"SS_LINEARSPECULARREFRACTION\" },\n { search: /SS_REFRACTIONMAP_OPPOSITEZ/g, replace: (_16 = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._defineOppositeZ) !== null && _16 !== void 0 ? _16 : \"SS_REFRACTIONMAP_OPPOSITEZ\" },\n ],\n });\n // _____________________________ Direct Lighting Info __________________________________\n state.compilationString += state._emitCodeFromInclude(\"pbrBlockDirectLighting\", comments);\n if (this.light) {\n state.compilationString += state._emitCodeFromInclude(\"lightFragment\", comments, {\n replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }],\n });\n }\n else {\n state.compilationString += state._emitCodeFromInclude(\"lightFragment\", comments, {\n repeatKey: \"maxSimultaneousLights\",\n });\n }\n // _____________________________ Compute Final Lit Components ________________________\n state.compilationString += state._emitCodeFromInclude(\"pbrBlockFinalLitComponents\", comments);\n // _____________________________ UNLIT (2) ________________________\n state.compilationString += `#endif\\r\\n`; // UNLIT\n // _____________________________ Compute Final Unlit Components ________________________\n const aoColor = this.ambientColor.isConnected ? this.ambientColor.associatedVariableName : \"vec3(0., 0., 0.)\";\n let aoDirectLightIntensity = PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();\n if (aoDirectLightIntensity.indexOf(\".\") === -1) {\n aoDirectLightIntensity += \".\";\n }\n state.compilationString += state._emitCodeFromInclude(\"pbrBlockFinalUnlitComponents\", comments, {\n replaceStrings: [\n { search: /vec3 finalEmissive[\\s\\S]*?finalEmissive\\*=vLightingIntensity\\.y;/g, replace: \"\" },\n { search: /vAmbientColor/g, replace: aoColor + \" * ambientFromScene\" },\n { search: /vAmbientInfos\\.w/g, replace: aoDirectLightIntensity },\n ],\n });\n // _____________________________ Output Final Color Composition ________________________\n state.compilationString += state._emitCodeFromInclude(\"pbrBlockFinalColorComposition\", comments, {\n replaceStrings: [{ search: /finalEmissive/g, replace: \"vec3(0.)\" }],\n });\n // _____________________________ Apply image processing ________________________\n state.compilationString += state._emitCodeFromInclude(\"pbrBlockImageProcessing\", comments, {\n replaceStrings: [{ search: /visibility/g, replace: \"1.\" }],\n });\n // _____________________________ Generate debug code ________________________\n state.compilationString += state._emitCodeFromInclude(\"pbrDebug\", comments, {\n replaceStrings: [\n { search: /vNormalW/g, replace: this._vNormalWName },\n { search: /vPositionW/g, replace: worldPosVarName },\n { search: /albedoTexture\\.rgb;/g, replace: \"vec3(1.);\\r\\ngl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb);\\r\\n\" },\n ],\n });\n // _____________________________ Generate end points ________________________\n for (const output of this._outputs) {\n if (output.hasEndpoints) {\n const remap = mapOutputToVariable[output.name];\n if (remap) {\n const [varName, conditions] = remap;\n if (conditions) {\n state.compilationString += `#if ${conditions}\\r\\n`;\n }\n state.compilationString += `${this._declareOutput(output, state)} = ${varName};\\r\\n`;\n if (conditions) {\n state.compilationString += `#else\\r\\n`;\n state.compilationString += `${this._declareOutput(output, state)} = vec3(0.);\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n }\n }\n else {\n console.error(`There's no remapping for the ${output.name} end point! No code generated`);\n }\n }\n }\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n codeString += `${this._codeVariableName}.lightFalloff = ${this.lightFalloff};\\r\\n`;\n codeString += `${this._codeVariableName}.useAlphaTest = ${this.useAlphaTest};\\r\\n`;\n codeString += `${this._codeVariableName}.alphaTestCutoff = ${this.alphaTestCutoff};\\r\\n`;\n codeString += `${this._codeVariableName}.useAlphaBlending = ${this.useAlphaBlending};\\r\\n`;\n codeString += `${this._codeVariableName}.useRadianceOverAlpha = ${this.useRadianceOverAlpha};\\r\\n`;\n codeString += `${this._codeVariableName}.useSpecularOverAlpha = ${this.useSpecularOverAlpha};\\r\\n`;\n codeString += `${this._codeVariableName}.enableSpecularAntiAliasing = ${this.enableSpecularAntiAliasing};\\r\\n`;\n codeString += `${this._codeVariableName}.realTimeFiltering = ${this.realTimeFiltering};\\r\\n`;\n codeString += `${this._codeVariableName}.realTimeFilteringQuality = ${this.realTimeFilteringQuality};\\r\\n`;\n codeString += `${this._codeVariableName}.useEnergyConservation = ${this.useEnergyConservation};\\r\\n`;\n codeString += `${this._codeVariableName}.useRadianceOcclusion = ${this.useRadianceOcclusion};\\r\\n`;\n codeString += `${this._codeVariableName}.useHorizonOcclusion = ${this.useHorizonOcclusion};\\r\\n`;\n codeString += `${this._codeVariableName}.unlit = ${this.unlit};\\r\\n`;\n codeString += `${this._codeVariableName}.forceNormalForward = ${this.forceNormalForward};\\r\\n`;\n codeString += `${this._codeVariableName}.debugMode = ${this.debugMode};\\r\\n`;\n codeString += `${this._codeVariableName}.debugLimit = ${this.debugLimit};\\r\\n`;\n codeString += `${this._codeVariableName}.debugFactor = ${this.debugFactor};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n if (this.light) {\n serializationObject.lightId = this.light.id;\n }\n serializationObject.lightFalloff = this.lightFalloff;\n serializationObject.useAlphaTest = this.useAlphaTest;\n serializationObject.alphaTestCutoff = this.alphaTestCutoff;\n serializationObject.useAlphaBlending = this.useAlphaBlending;\n serializationObject.useRadianceOverAlpha = this.useRadianceOverAlpha;\n serializationObject.useSpecularOverAlpha = this.useSpecularOverAlpha;\n serializationObject.enableSpecularAntiAliasing = this.enableSpecularAntiAliasing;\n serializationObject.realTimeFiltering = this.realTimeFiltering;\n serializationObject.realTimeFilteringQuality = this.realTimeFilteringQuality;\n serializationObject.useEnergyConservation = this.useEnergyConservation;\n serializationObject.useRadianceOcclusion = this.useRadianceOcclusion;\n serializationObject.useHorizonOcclusion = this.useHorizonOcclusion;\n serializationObject.unlit = this.unlit;\n serializationObject.forceNormalForward = this.forceNormalForward;\n serializationObject.debugMode = this.debugMode;\n serializationObject.debugLimit = this.debugLimit;\n serializationObject.debugFactor = this.debugFactor;\n serializationObject.generateOnlyFragmentCode = this.generateOnlyFragmentCode;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n var _a, _b;\n super._deserialize(serializationObject, scene, rootUrl);\n if (serializationObject.lightId) {\n this.light = scene.getLightById(serializationObject.lightId);\n }\n this.lightFalloff = (_a = serializationObject.lightFalloff) !== null && _a !== void 0 ? _a : 0;\n this.useAlphaTest = serializationObject.useAlphaTest;\n this.alphaTestCutoff = serializationObject.alphaTestCutoff;\n this.useAlphaBlending = serializationObject.useAlphaBlending;\n this.useRadianceOverAlpha = serializationObject.useRadianceOverAlpha;\n this.useSpecularOverAlpha = serializationObject.useSpecularOverAlpha;\n this.enableSpecularAntiAliasing = serializationObject.enableSpecularAntiAliasing;\n this.realTimeFiltering = !!serializationObject.realTimeFiltering;\n this.realTimeFilteringQuality = (_b = serializationObject.realTimeFilteringQuality) !== null && _b !== void 0 ? _b : 8;\n this.useEnergyConservation = serializationObject.useEnergyConservation;\n this.useRadianceOcclusion = serializationObject.useRadianceOcclusion;\n this.useHorizonOcclusion = serializationObject.useHorizonOcclusion;\n this.unlit = serializationObject.unlit;\n this.forceNormalForward = !!serializationObject.forceNormalForward;\n this.debugMode = serializationObject.debugMode;\n this.debugLimit = serializationObject.debugLimit;\n this.debugFactor = serializationObject.debugFactor;\n this.generateOnlyFragmentCode = !!serializationObject.generateOnlyFragmentCode;\n this._setTarget();\n }\n}\n__decorate([\n editableInPropertyPage(\"Direct lights\", PropertyTypeForEdition.Float, \"INTENSITY\", { min: 0, max: 1, notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"directIntensity\", void 0);\n__decorate([\n editableInPropertyPage(\"Environment lights\", PropertyTypeForEdition.Float, \"INTENSITY\", { min: 0, max: 1, notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"environmentIntensity\", void 0);\n__decorate([\n editableInPropertyPage(\"Specular highlights\", PropertyTypeForEdition.Float, \"INTENSITY\", { min: 0, max: 1, notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"specularIntensity\", void 0);\n__decorate([\n editableInPropertyPage(\"Light falloff\", PropertyTypeForEdition.List, \"LIGHTING & COLORS\", {\n notifiers: { update: true },\n options: [\n { label: \"Physical\", value: PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL },\n { label: \"GLTF\", value: PBRBaseMaterial.LIGHTFALLOFF_GLTF },\n { label: \"Standard\", value: PBRBaseMaterial.LIGHTFALLOFF_STANDARD },\n ],\n })\n], PBRMetallicRoughnessBlock.prototype, \"lightFalloff\", void 0);\n__decorate([\n editableInPropertyPage(\"Alpha Testing\", PropertyTypeForEdition.Boolean, \"OPACITY\")\n], PBRMetallicRoughnessBlock.prototype, \"useAlphaTest\", void 0);\n__decorate([\n editableInPropertyPage(\"Alpha CutOff\", PropertyTypeForEdition.Float, \"OPACITY\", { min: 0, max: 1, notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"alphaTestCutoff\", void 0);\n__decorate([\n editableInPropertyPage(\"Alpha blending\", PropertyTypeForEdition.Boolean, \"OPACITY\")\n], PBRMetallicRoughnessBlock.prototype, \"useAlphaBlending\", void 0);\n__decorate([\n editableInPropertyPage(\"Radiance over alpha\", PropertyTypeForEdition.Boolean, \"RENDERING\", { notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"useRadianceOverAlpha\", void 0);\n__decorate([\n editableInPropertyPage(\"Specular over alpha\", PropertyTypeForEdition.Boolean, \"RENDERING\", { notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"useSpecularOverAlpha\", void 0);\n__decorate([\n editableInPropertyPage(\"Specular anti-aliasing\", PropertyTypeForEdition.Boolean, \"RENDERING\", { notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"enableSpecularAntiAliasing\", void 0);\n__decorate([\n editableInPropertyPage(\"Realtime filtering\", PropertyTypeForEdition.Boolean, \"RENDERING\", { notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"realTimeFiltering\", void 0);\n__decorate([\n editableInPropertyPage(\"Realtime filtering quality\", PropertyTypeForEdition.List, \"RENDERING\", {\n notifiers: { update: true },\n options: [\n { label: \"Low\", value: 8 },\n { label: \"Medium\", value: 16 },\n { label: \"High\", value: 64 },\n ],\n })\n], PBRMetallicRoughnessBlock.prototype, \"realTimeFilteringQuality\", void 0);\n__decorate([\n editableInPropertyPage(\"Energy Conservation\", PropertyTypeForEdition.Boolean, \"ADVANCED\", { notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"useEnergyConservation\", void 0);\n__decorate([\n editableInPropertyPage(\"Radiance occlusion\", PropertyTypeForEdition.Boolean, \"ADVANCED\", { notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"useRadianceOcclusion\", void 0);\n__decorate([\n editableInPropertyPage(\"Horizon occlusion\", PropertyTypeForEdition.Boolean, \"ADVANCED\", { notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"useHorizonOcclusion\", void 0);\n__decorate([\n editableInPropertyPage(\"Unlit\", PropertyTypeForEdition.Boolean, \"ADVANCED\", { notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"unlit\", void 0);\n__decorate([\n editableInPropertyPage(\"Force normal forward\", PropertyTypeForEdition.Boolean, \"ADVANCED\", { notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"forceNormalForward\", void 0);\n__decorate([\n editableInPropertyPage(\"Generate only fragment code\", PropertyTypeForEdition.Boolean, \"ADVANCED\", {\n notifiers: { rebuild: true, update: true, onValidation: PBRMetallicRoughnessBlock._OnGenerateOnlyFragmentCodeChanged },\n })\n], PBRMetallicRoughnessBlock.prototype, \"generateOnlyFragmentCode\", void 0);\n__decorate([\n editableInPropertyPage(\"Debug mode\", PropertyTypeForEdition.List, \"DEBUG\", {\n notifiers: { update: true },\n options: [\n { label: \"None\", value: 0 },\n // Geometry\n { label: \"Normalized position\", value: 1 },\n { label: \"Normals\", value: 2 },\n { label: \"Tangents\", value: 3 },\n { label: \"Bitangents\", value: 4 },\n { label: \"Bump Normals\", value: 5 },\n //{ label: \"UV1\", value: 6 },\n //{ label: \"UV2\", value: 7 },\n { label: \"ClearCoat Normals\", value: 8 },\n { label: \"ClearCoat Tangents\", value: 9 },\n { label: \"ClearCoat Bitangents\", value: 10 },\n { label: \"Anisotropic Normals\", value: 11 },\n { label: \"Anisotropic Tangents\", value: 12 },\n { label: \"Anisotropic Bitangents\", value: 13 },\n // Maps\n //{ label: \"Emissive Map\", value: 23 },\n //{ label: \"Light Map\", value: 24 },\n // Env\n { label: \"Env Refraction\", value: 40 },\n { label: \"Env Reflection\", value: 41 },\n { label: \"Env Clear Coat\", value: 42 },\n // Lighting\n { label: \"Direct Diffuse\", value: 50 },\n { label: \"Direct Specular\", value: 51 },\n { label: \"Direct Clear Coat\", value: 52 },\n { label: \"Direct Sheen\", value: 53 },\n { label: \"Env Irradiance\", value: 54 },\n // Lighting Params\n { label: \"Surface Albedo\", value: 60 },\n { label: \"Reflectance 0\", value: 61 },\n { label: \"Metallic\", value: 62 },\n { label: \"Metallic F0\", value: 71 },\n { label: \"Roughness\", value: 63 },\n { label: \"AlphaG\", value: 64 },\n { label: \"NdotV\", value: 65 },\n { label: \"ClearCoat Color\", value: 66 },\n { label: \"ClearCoat Roughness\", value: 67 },\n { label: \"ClearCoat NdotV\", value: 68 },\n { label: \"Transmittance\", value: 69 },\n { label: \"Refraction Transmittance\", value: 70 },\n // Misc\n { label: \"SEO\", value: 80 },\n { label: \"EHO\", value: 81 },\n { label: \"Energy Factor\", value: 82 },\n { label: \"Specular Reflectance\", value: 83 },\n { label: \"Clear Coat Reflectance\", value: 84 },\n { label: \"Sheen Reflectance\", value: 85 },\n { label: \"Luminance Over Alpha\", value: 86 },\n { label: \"Alpha\", value: 87 },\n ],\n })\n], PBRMetallicRoughnessBlock.prototype, \"debugMode\", void 0);\n__decorate([\n editableInPropertyPage(\"Split position\", PropertyTypeForEdition.Float, \"DEBUG\", { min: -1, max: 1, notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"debugLimit\", void 0);\n__decorate([\n editableInPropertyPage(\"Output factor\", PropertyTypeForEdition.Float, \"DEBUG\", { min: 0, max: 5, notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"debugFactor\", void 0);\nRegisterClass(\"BABYLON.PBRMetallicRoughnessBlock\", PBRMetallicRoughnessBlock);\n//# sourceMappingURL=pbrMetallicRoughnessBlock.js.map","export * from \"./pbrMetallicRoughnessBlock.js\";\nexport * from \"./sheenBlock.js\";\nexport * from \"./anisotropyBlock.js\";\nexport * from \"./reflectionBlock.js\";\nexport * from \"./clearCoatBlock.js\";\nexport * from \"./refractionBlock.js\";\nexport * from \"./subSurfaceBlock.js\";\n//# sourceMappingURL=index.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to compute value of one parameter modulo another\n */\nexport class ModBlock extends NodeMaterialBlock {\n /**\n * Creates a new ModBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"left\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"right\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._linkConnectionTypes(0, 1);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ModBlock\";\n }\n /**\n * Gets the left operand input component\n */\n get left() {\n return this._inputs[0];\n }\n /**\n * Gets the right operand input component\n */\n get right() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = mod(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.ModBlock\", ModBlock);\n//# sourceMappingURL=modBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { InputBlock } from \"./Input/inputBlock.js\";\nimport { Vector4 } from \"../../../Maths/math.vector.js\";\n/**\n * Block used to build a matrix from 4 Vector4\n */\nexport class MatrixBuilderBlock extends NodeMaterialBlock {\n /**\n * Creates a new MatrixBuilder\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"row0\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerInput(\"row1\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerInput(\"row2\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerInput(\"row3\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Matrix);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"MatrixBuilder\";\n }\n /**\n * Gets the row0 vector\n */\n get row0() {\n return this._inputs[0];\n }\n /**\n * Gets the row1 vector\n */\n get row1() {\n return this._inputs[1];\n }\n /**\n * Gets the row2 vector\n */\n get row2() {\n return this._inputs[2];\n }\n /**\n * Gets the row3 vector\n */\n get row3() {\n return this._inputs[3];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n autoConfigure() {\n if (!this.row0.isConnected) {\n const row0Input = new InputBlock(\"row0\");\n row0Input.value = new Vector4(1, 0, 0, 0);\n row0Input.output.connectTo(this.row0);\n }\n if (!this.row1.isConnected) {\n const row1Input = new InputBlock(\"row1\");\n row1Input.value = new Vector4(0, 1, 0, 0);\n row1Input.output.connectTo(this.row1);\n }\n if (!this.row2.isConnected) {\n const row2Input = new InputBlock(\"row2\");\n row2Input.value = new Vector4(0, 0, 1, 0);\n row2Input.output.connectTo(this.row2);\n }\n if (!this.row3.isConnected) {\n const row3Input = new InputBlock(\"row3\");\n row3Input.value = new Vector4(0, 0, 0, 1);\n row3Input.output.connectTo(this.row3);\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n const row0 = this.row0;\n const row1 = this.row1;\n const row2 = this.row2;\n const row3 = this.row3;\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = mat4(${row0.associatedVariableName}, ${row1.associatedVariableName}, ${row2.associatedVariableName}, ${row3.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.MatrixBuilder\", MatrixBuilderBlock);\n//# sourceMappingURL=matrixBuilderBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Operations supported by the ConditionalBlock block\n */\nexport var ConditionalBlockConditions;\n(function (ConditionalBlockConditions) {\n /** Equal */\n ConditionalBlockConditions[ConditionalBlockConditions[\"Equal\"] = 0] = \"Equal\";\n /** NotEqual */\n ConditionalBlockConditions[ConditionalBlockConditions[\"NotEqual\"] = 1] = \"NotEqual\";\n /** LessThan */\n ConditionalBlockConditions[ConditionalBlockConditions[\"LessThan\"] = 2] = \"LessThan\";\n /** GreaterThan */\n ConditionalBlockConditions[ConditionalBlockConditions[\"GreaterThan\"] = 3] = \"GreaterThan\";\n /** LessOrEqual */\n ConditionalBlockConditions[ConditionalBlockConditions[\"LessOrEqual\"] = 4] = \"LessOrEqual\";\n /** GreaterOrEqual */\n ConditionalBlockConditions[ConditionalBlockConditions[\"GreaterOrEqual\"] = 5] = \"GreaterOrEqual\";\n /** Logical Exclusive OR */\n ConditionalBlockConditions[ConditionalBlockConditions[\"Xor\"] = 6] = \"Xor\";\n /** Logical Or */\n ConditionalBlockConditions[ConditionalBlockConditions[\"Or\"] = 7] = \"Or\";\n /** Logical And */\n ConditionalBlockConditions[ConditionalBlockConditions[\"And\"] = 8] = \"And\";\n})(ConditionalBlockConditions || (ConditionalBlockConditions = {}));\n/**\n * Block used to apply conditional operation between floats\n * @since 5.0.0\n */\nexport class ConditionalBlock extends NodeMaterialBlock {\n /**\n * Creates a new ConditionalBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n /**\n * Gets or sets the condition applied by the block\n */\n this.condition = ConditionalBlockConditions.LessThan;\n this.registerInput(\"a\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerInput(\"b\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerInput(\"true\", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);\n this.registerInput(\"false\", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._linkConnectionTypes(2, 3);\n this._outputs[0]._typeConnectionSource = this._inputs[2];\n this._outputs[0]._defaultConnectionPointType = NodeMaterialBlockConnectionPointTypes.Float;\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ConditionalBlock\";\n }\n /**\n * Gets the first operand component\n */\n get a() {\n return this._inputs[0];\n }\n /**\n * Gets the second operand component\n */\n get b() {\n return this._inputs[1];\n }\n /**\n * Gets the value to return if condition is true\n */\n get true() {\n return this._inputs[2];\n }\n /**\n * Gets the value to return if condition is false\n */\n get false() {\n return this._inputs[3];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n const trueStatement = this.true.isConnected ? this.true.associatedVariableName : \"1.0\";\n const falseStatement = this.false.isConnected ? this.false.associatedVariableName : \"0.0\";\n switch (this.condition) {\n case ConditionalBlockConditions.Equal: {\n state.compilationString +=\n this._declareOutput(output, state) + ` = ${this.a.associatedVariableName} == ${this.b.associatedVariableName} ? ${trueStatement} : ${falseStatement};\\r\\n`;\n break;\n }\n case ConditionalBlockConditions.NotEqual: {\n state.compilationString +=\n this._declareOutput(output, state) + ` = ${this.a.associatedVariableName} != ${this.b.associatedVariableName} ? ${trueStatement} : ${falseStatement};\\r\\n`;\n break;\n }\n case ConditionalBlockConditions.LessThan: {\n state.compilationString +=\n this._declareOutput(output, state) + ` = ${this.a.associatedVariableName} < ${this.b.associatedVariableName} ? ${trueStatement} : ${falseStatement};\\r\\n`;\n break;\n }\n case ConditionalBlockConditions.LessOrEqual: {\n state.compilationString +=\n this._declareOutput(output, state) + ` = ${this.a.associatedVariableName} <= ${this.b.associatedVariableName} ? ${trueStatement} : ${falseStatement};\\r\\n`;\n break;\n }\n case ConditionalBlockConditions.GreaterThan: {\n state.compilationString +=\n this._declareOutput(output, state) + ` = ${this.a.associatedVariableName} > ${this.b.associatedVariableName} ? ${trueStatement} : ${falseStatement};\\r\\n`;\n break;\n }\n case ConditionalBlockConditions.GreaterOrEqual: {\n state.compilationString +=\n this._declareOutput(output, state) + ` = ${this.a.associatedVariableName} >= ${this.b.associatedVariableName} ? ${trueStatement} : ${falseStatement};\\r\\n`;\n break;\n }\n case ConditionalBlockConditions.Xor: {\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = (mod(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 2.0) > 0.0) ? ${trueStatement} : ${falseStatement};\\r\\n`;\n break;\n }\n case ConditionalBlockConditions.Or: {\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = (min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0) ? ${trueStatement} : ${falseStatement};\\r\\n`;\n break;\n }\n case ConditionalBlockConditions.And: {\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = (${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0) ? ${trueStatement} : ${falseStatement};\\r\\n`;\n break;\n }\n }\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.condition = this.condition;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.condition = serializationObject.condition;\n }\n _dumpPropertiesCode() {\n const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.condition = BABYLON.ConditionalBlockConditions.${ConditionalBlockConditions[this.condition]};\\r\\n`;\n return codeString;\n }\n}\nRegisterClass(\"BABYLON.ConditionalBlock\", ConditionalBlock);\n//# sourceMappingURL=conditionalBlock.js.map","import { __decorate } from \"../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../nodeMaterialDecorator.js\";\n/**\n * block used to Generate Fractal Brownian Motion Clouds\n */\nexport class CloudBlock extends NodeMaterialBlock {\n /**\n * Creates a new CloudBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n /** Gets or sets the number of octaves */\n this.octaves = 6.0;\n this.registerInput(\"seed\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"chaos\", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);\n this.registerInput(\"offsetX\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"offsetY\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"offsetZ\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2);\n this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3);\n this._linkConnectionTypes(0, 1);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"CloudBlock\";\n }\n /**\n * Gets the seed input component\n */\n get seed() {\n return this._inputs[0];\n }\n /**\n * Gets the chaos input component\n */\n get chaos() {\n return this._inputs[1];\n }\n /**\n * Gets the offset X input component\n */\n get offsetX() {\n return this._inputs[2];\n }\n /**\n * Gets the offset Y input component\n */\n get offsetY() {\n return this._inputs[3];\n }\n /**\n * Gets the offset Z input component\n */\n get offsetZ() {\n return this._inputs[4];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n var _a, _b;\n super._buildBlock(state);\n if (!this.seed.isConnected) {\n return;\n }\n if (!this._outputs[0].hasEndpoints) {\n return;\n }\n const functionString = `\r\n\r\n float cloudRandom(in float p) { p = fract(p * 0.011); p *= p + 7.5; p *= p + p; return fract(p); }\r\n\r\n // Based on Morgan McGuire @morgan3d\r\n // https://www.shadertoy.com/view/4dS3Wd\r\n float cloudNoise(in vec2 x, in vec2 chaos) {\r\n vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.);\r\n\r\n vec2 i = floor(x);\r\n vec2 f = fract(x);\r\n\r\n float n = dot(i, step);\r\n\r\n vec2 u = f * f * (3.0 - 2.0 * f);\r\n return mix(\r\n mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x),\r\n mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x),\r\n u.y\r\n );\r\n }\r\n\r\n float cloudNoise(in vec3 x, in vec3 chaos) {\r\n vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.);\r\n\r\n vec3 i = floor(x);\r\n vec3 f = fract(x);\r\n\r\n float n = dot(i, step);\r\n\r\n vec3 u = f * f * (3.0 - 2.0 * f);\r\n return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x),\r\n mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y),\r\n mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x),\r\n mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z);\r\n }`;\n const fractalBrownianString = `\r\n float fbm(in vec2 st, in vec2 chaos) {\r\n // Initial values\r\n float value = 0.0;\r\n float amplitude = .5;\r\n float frequency = 0.;\r\n\r\n // Loop of octaves\r\n for (int i = 0; i < OCTAVES; i++) {\r\n value += amplitude * cloudNoise(st, chaos);\r\n st *= 2.0;\r\n amplitude *= 0.5;\r\n }\r\n return value;\r\n }\r\n\r\n float fbm(in vec3 x, in vec3 chaos) {\r\n // Initial values\r\n float value = 0.0;\r\n float amplitude = 0.5;\r\n for (int i = 0; i < OCTAVES; ++i) {\r\n value += amplitude * cloudNoise(x, chaos);\r\n x = x * 2.0;\r\n amplitude *= 0.5;\r\n }\r\n return value;\r\n }`;\n const fbmNewName = `fbm${this.octaves}`;\n state._emitFunction(\"CloudBlockCode\", functionString, \"// CloudBlockCode\");\n state._emitFunction(\"CloudBlockCodeFBM\" + this.octaves, fractalBrownianString.replace(/fbm/gi, fbmNewName).replace(/OCTAVES/gi, (this.octaves | 0).toString()), \"// CloudBlockCode FBM\");\n const localVariable = state._getFreeVariableName(\"st\");\n const seedType = ((_a = this.seed.connectedPoint) === null || _a === void 0 ? void 0 : _a.type) === NodeMaterialBlockConnectionPointTypes.Vector2 ? \"vec2\" : \"vec3\";\n state.compilationString += `${seedType} ${localVariable} = ${this.seed.associatedVariableName};\\r\\n`;\n if (this.offsetX.isConnected) {\n state.compilationString += `${localVariable}.x += 0.1 * ${this.offsetX.associatedVariableName};\\r\\n`;\n }\n if (this.offsetY.isConnected) {\n state.compilationString += `${localVariable}.y += 0.1 * ${this.offsetY.associatedVariableName};\\r\\n`;\n }\n if (this.offsetZ.isConnected && seedType === \"vec3\") {\n state.compilationString += `${localVariable}.z += 0.1 * ${this.offsetZ.associatedVariableName};\\r\\n`;\n }\n let chaosValue = \"\";\n if (this.chaos.isConnected) {\n chaosValue = this.chaos.associatedVariableName;\n }\n else {\n chaosValue = ((_b = this.seed.connectedPoint) === null || _b === void 0 ? void 0 : _b.type) === NodeMaterialBlockConnectionPointTypes.Vector2 ? \"vec2(0., 0.)\" : \"vec3(0., 0., 0.)\";\n }\n state.compilationString += this._declareOutput(this._outputs[0], state) + ` = ${fbmNewName}(${localVariable}, ${chaosValue});\\r\\n`;\n return this;\n }\n _dumpPropertiesCode() {\n const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.octaves = ${this.octaves};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.octaves = this.octaves;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.octaves = serializationObject.octaves;\n }\n}\n__decorate([\n editableInPropertyPage(\"Octaves\", PropertyTypeForEdition.Int)\n], CloudBlock.prototype, \"octaves\", void 0);\nRegisterClass(\"BABYLON.CloudBlock\", CloudBlock);\n//# sourceMappingURL=cloudBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * block used to Generate a Voronoi Noise Pattern\n */\nexport class VoronoiNoiseBlock extends NodeMaterialBlock {\n /**\n * Creates a new VoronoiNoiseBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"seed\", NodeMaterialBlockConnectionPointTypes.Vector2);\n this.registerInput(\"offset\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerInput(\"density\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"cells\", NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"VoronoiNoiseBlock\";\n }\n /**\n * Gets the seed input component\n */\n get seed() {\n return this._inputs[0];\n }\n /**\n * Gets the offset input component\n */\n get offset() {\n return this._inputs[1];\n }\n /**\n * Gets the density input component\n */\n get density() {\n return this._inputs[2];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n /**\n * Gets the output component\n */\n get cells() {\n return this._outputs[1];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (!this.seed.isConnected) {\n return;\n }\n let functionString = `vec2 voronoiRandom(vec2 seed, float offset){\r\n mat2 m = mat2(15.27, 47.63, 99.41, 89.98);\r\n vec2 uv = fract(sin(m * seed) * 46839.32);\r\n return vec2(sin(uv.y * offset) * 0.5 + 0.5, cos(uv.x * offset) * 0.5 + 0.5);\r\n }\r\n `;\n state._emitFunction(\"voronoiRandom\", functionString, \"// Voronoi random generator\");\n functionString = `void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){\r\n vec2 g = floor(seed * density);\r\n vec2 f = fract(seed * density);\r\n float t = 8.0;\r\n vec3 res = vec3(8.0, 0.0, 0.0);\r\n\r\n for(int y=-1; y<=1; y++)\r\n {\r\n for(int x=-1; x<=1; x++)\r\n {\r\n vec2 lattice = vec2(x,y);\r\n vec2 randomOffset = voronoiRandom(lattice + g, offset);\r\n float d = distance(lattice + randomOffset, f);\r\n if(d < res.x)\r\n {\r\n res = vec3(d, randomOffset.x, randomOffset.y);\r\n outValue = res.x;\r\n cells = res.y;\r\n }\r\n }\r\n }\r\n }\r\n `;\n state._emitFunction(\"voronoi\", functionString, \"// Voronoi\");\n const tempOutput = state._getFreeVariableName(\"tempOutput\");\n const tempCells = state._getFreeVariableName(\"tempCells\");\n state.compilationString += `float ${tempOutput} = 0.0;\\r\\n`;\n state.compilationString += `float ${tempCells} = 0.0;\\r\\n`;\n state.compilationString += `voronoi(${this.seed.associatedVariableName}, ${this.offset.associatedVariableName}, ${this.density.associatedVariableName}, ${tempOutput}, ${tempCells});\\r\\n`;\n if (this.output.hasEndpoints) {\n state.compilationString += this._declareOutput(this.output, state) + ` = ${tempOutput};\\r\\n`;\n }\n if (this.cells.hasEndpoints) {\n state.compilationString += this._declareOutput(this.cells, state) + ` = ${tempCells};\\r\\n`;\n }\n return this;\n }\n}\nRegisterClass(\"BABYLON.VoronoiNoiseBlock\", VoronoiNoiseBlock);\n//# sourceMappingURL=voronoiNoiseBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used as a pass through\n */\nexport class ElbowBlock extends NodeMaterialBlock {\n /**\n * Creates a new ElbowBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ElbowBlock\";\n }\n /**\n * Gets the input component\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n /**\n * Gets or sets the target of the block\n */\n get target() {\n const input = this._inputs[0];\n if (input.isConnected) {\n const block = input.connectedPoint.ownerBlock;\n if (block.target !== NodeMaterialBlockTargets.VertexAndFragment) {\n return block.target;\n }\n if (input.connectedPoint.target !== NodeMaterialBlockTargets.VertexAndFragment) {\n return input.connectedPoint.target;\n }\n }\n return this._target;\n }\n set target(value) {\n if ((this._target & value) !== 0) {\n return;\n }\n this._target = value;\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n const input = this._inputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = ${input.associatedVariableName};\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.ElbowBlock\", ElbowBlock);\n//# sourceMappingURL=elbowBlock.js.map","import { __decorate } from \"../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../nodeMaterialBlockConnectionPoint.js\";\nimport { NodeMaterial } from \"../nodeMaterial.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { Texture } from \"../../Textures/texture.js\";\n\nimport \"../../../Shaders/ShadersInclude/helperFunctions.js\";\nimport { ImageSourceBlock } from \"./Dual/imageSourceBlock.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../nodeMaterialConnectionPointCustomObject.js\";\nimport { EngineStore } from \"../../../Engines/engineStore.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../nodeMaterialDecorator.js\";\n/**\n * Block used to read a texture with triplanar mapping (see \"boxmap\" in https://iquilezles.org/articles/biplanar/)\n */\nexport class TriPlanarBlock extends NodeMaterialBlock {\n /**\n * Gets or sets the texture associated with the node\n */\n get texture() {\n var _a;\n if (this.source.isConnected) {\n return ((_a = this.source.connectedPoint) === null || _a === void 0 ? void 0 : _a.ownerBlock).texture;\n }\n return this._texture;\n }\n set texture(texture) {\n var _a;\n if (this._texture === texture) {\n return;\n }\n const scene = (_a = texture === null || texture === void 0 ? void 0 : texture.getScene()) !== null && _a !== void 0 ? _a : EngineStore.LastCreatedScene;\n if (!texture && scene) {\n scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(this._texture);\n });\n }\n this._texture = texture;\n if (texture && scene) {\n scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(texture);\n });\n }\n }\n /**\n * Gets the textureY associated with the node\n */\n get textureY() {\n var _a;\n if (this.sourceY.isConnected) {\n return ((_a = this.sourceY.connectedPoint) === null || _a === void 0 ? void 0 : _a.ownerBlock).texture;\n }\n return null;\n }\n /**\n * Gets the textureZ associated with the node\n */\n get textureZ() {\n var _a, _b;\n if ((_a = this.sourceZ) === null || _a === void 0 ? void 0 : _a.isConnected) {\n return ((_b = this.sourceY.connectedPoint) === null || _b === void 0 ? void 0 : _b.ownerBlock).texture;\n }\n return null;\n }\n _getImageSourceBlock(connectionPoint) {\n return (connectionPoint === null || connectionPoint === void 0 ? void 0 : connectionPoint.isConnected) ? connectionPoint.connectedPoint.ownerBlock : null;\n }\n /**\n * Gets the sampler name associated with this texture\n */\n get samplerName() {\n const imageSourceBlock = this._getImageSourceBlock(this.source);\n if (imageSourceBlock) {\n return imageSourceBlock.samplerName;\n }\n return this._samplerName;\n }\n /**\n * Gets the samplerY name associated with this texture\n */\n get samplerYName() {\n var _a, _b;\n return (_b = (_a = this._getImageSourceBlock(this.sourceY)) === null || _a === void 0 ? void 0 : _a.samplerName) !== null && _b !== void 0 ? _b : null;\n }\n /**\n * Gets the samplerZ name associated with this texture\n */\n get samplerZName() {\n var _a, _b;\n return (_b = (_a = this._getImageSourceBlock(this.sourceZ)) === null || _a === void 0 ? void 0 : _a.samplerName) !== null && _b !== void 0 ? _b : null;\n }\n /**\n * Gets a boolean indicating that this block is linked to an ImageSourceBlock\n */\n get hasImageSource() {\n return this.source.isConnected;\n }\n /**\n * Gets or sets a boolean indicating if content needs to be converted to gamma space\n */\n set convertToGammaSpace(value) {\n var _a;\n if (value === this._convertToGammaSpace) {\n return;\n }\n this._convertToGammaSpace = value;\n if (this.texture) {\n const scene = (_a = this.texture.getScene()) !== null && _a !== void 0 ? _a : EngineStore.LastCreatedScene;\n scene === null || scene === void 0 ? void 0 : scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(this.texture);\n });\n }\n }\n get convertToGammaSpace() {\n return this._convertToGammaSpace;\n }\n /**\n * Gets or sets a boolean indicating if content needs to be converted to linear space\n */\n set convertToLinearSpace(value) {\n var _a;\n if (value === this._convertToLinearSpace) {\n return;\n }\n this._convertToLinearSpace = value;\n if (this.texture) {\n const scene = (_a = this.texture.getScene()) !== null && _a !== void 0 ? _a : EngineStore.LastCreatedScene;\n scene === null || scene === void 0 ? void 0 : scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(this.texture);\n });\n }\n }\n get convertToLinearSpace() {\n return this._convertToLinearSpace;\n }\n /**\n * Create a new TriPlanarBlock\n * @param name defines the block name\n */\n constructor(name, hideSourceZ = false) {\n super(name, NodeMaterialBlockTargets.Neutral);\n /**\n * Project the texture(s) for a better fit to a cube\n */\n this.projectAsCube = false;\n this._convertToGammaSpace = false;\n this._convertToLinearSpace = false;\n /**\n * Gets or sets a boolean indicating if multiplication of texture with level should be disabled\n */\n this.disableLevelMultiplication = false;\n this.registerInput(\"position\", NodeMaterialBlockConnectionPointTypes.AutoDetect, false);\n this.registerInput(\"normal\", NodeMaterialBlockConnectionPointTypes.AutoDetect, false);\n this.registerInput(\"sharpness\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"source\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject(\"source\", this, NodeMaterialConnectionPointDirection.Input, ImageSourceBlock, \"ImageSourceBlock\"));\n this.registerInput(\"sourceY\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject(\"sourceY\", this, NodeMaterialConnectionPointDirection.Input, ImageSourceBlock, \"ImageSourceBlock\"));\n if (!hideSourceZ) {\n this.registerInput(\"sourceZ\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject(\"sourceZ\", this, NodeMaterialConnectionPointDirection.Input, ImageSourceBlock, \"ImageSourceBlock\"));\n }\n this.registerOutput(\"rgba\", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"rgb\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"r\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"g\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"b\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"a\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"level\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);\n this._inputs[1].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"TriPlanarBlock\";\n }\n /**\n * Gets the position input component\n */\n get position() {\n return this._inputs[0];\n }\n /**\n * Gets the normal input component\n */\n get normal() {\n return this._inputs[1];\n }\n /**\n * Gets the sharpness input component\n */\n get sharpness() {\n return this._inputs[2];\n }\n /**\n * Gets the source input component\n */\n get source() {\n return this._inputs[3];\n }\n /**\n * Gets the sourceY input component\n */\n get sourceY() {\n return this._inputs[4];\n }\n /**\n * Gets the sourceZ input component\n */\n get sourceZ() {\n return this._inputs[5];\n }\n /**\n * Gets the rgba output component\n */\n get rgba() {\n return this._outputs[0];\n }\n /**\n * Gets the rgb output component\n */\n get rgb() {\n return this._outputs[1];\n }\n /**\n * Gets the r output component\n */\n get r() {\n return this._outputs[2];\n }\n /**\n * Gets the g output component\n */\n get g() {\n return this._outputs[3];\n }\n /**\n * Gets the b output component\n */\n get b() {\n return this._outputs[4];\n }\n /**\n * Gets the a output component\n */\n get a() {\n return this._outputs[5];\n }\n /**\n * Gets the level output component\n */\n get level() {\n return this._outputs[6];\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n if (!defines._areTexturesDirty) {\n return;\n }\n const toGamma = this.convertToGammaSpace && this.texture && !this.texture.gammaSpace;\n const toLinear = this.convertToLinearSpace && this.texture && this.texture.gammaSpace;\n // Not a bug... Name defines the texture space not the required conversion\n defines.setValue(this._linearDefineName, toGamma, true);\n defines.setValue(this._gammaDefineName, toLinear, true);\n }\n isReady() {\n if (this.texture && !this.texture.isReadyOrNotBlocking()) {\n return false;\n }\n return true;\n }\n bind(effect) {\n if (!this.texture) {\n return;\n }\n effect.setFloat(this._textureInfoName, this.texture.level);\n if (!this._imageSource) {\n effect.setTexture(this._samplerName, this.texture);\n }\n }\n _generateTextureLookup(state) {\n var _a, _b;\n const samplerName = this.samplerName;\n const samplerYName = (_a = this.samplerYName) !== null && _a !== void 0 ? _a : samplerName;\n const samplerZName = (_b = this.samplerZName) !== null && _b !== void 0 ? _b : samplerName;\n const sharpness = this.sharpness.isConnected ? this.sharpness.associatedVariableName : \"1.0\";\n const x = state._getFreeVariableName(\"x\");\n const y = state._getFreeVariableName(\"y\");\n const z = state._getFreeVariableName(\"z\");\n const w = state._getFreeVariableName(\"w\");\n const n = state._getFreeVariableName(\"n\");\n const uvx = state._getFreeVariableName(\"uvx\");\n const uvy = state._getFreeVariableName(\"uvy\");\n const uvz = state._getFreeVariableName(\"uvz\");\n state.compilationString += `\r\n vec3 ${n} = ${this.normal.associatedVariableName}.xyz;\r\n\r\n vec2 ${uvx} = ${this.position.associatedVariableName}.yz;\r\n vec2 ${uvy} = ${this.position.associatedVariableName}.zx;\r\n vec2 ${uvz} = ${this.position.associatedVariableName}.xy;\r\n `;\n if (this.projectAsCube) {\n state.compilationString += `\r\n ${uvx}.xy = ${uvx}.yx;\r\n\r\n if (${n}.x >= 0.0) {\r\n ${uvx}.x = -${uvx}.x;\r\n }\r\n if (${n}.y < 0.0) {\r\n ${uvy}.y = -${uvy}.y;\r\n }\r\n if (${n}.z < 0.0) {\r\n ${uvz}.x = -${uvz}.x;\r\n }\r\n `;\n }\n state.compilationString += `\r\n vec4 ${x} = texture2D(${samplerName}, ${uvx});\r\n vec4 ${y} = texture2D(${samplerYName}, ${uvy});\r\n vec4 ${z} = texture2D(${samplerZName}, ${uvz});\r\n \r\n // blend weights\r\n vec3 ${w} = pow(abs(${n}), vec3(${sharpness}));\r\n\r\n // blend and return\r\n vec4 ${this._tempTextureRead} = (${x}*${w}.x + ${y}*${w}.y + ${z}*${w}.z) / (${w}.x + ${w}.y + ${w}.z); \r\n `;\n }\n _generateConversionCode(state, output, swizzle) {\n if (swizzle !== \"a\") {\n // no conversion if the output is \"a\" (alpha)\n if (!this.texture || !this.texture.gammaSpace) {\n state.compilationString += `#ifdef ${this._linearDefineName}\r\n ${output.associatedVariableName} = toGammaSpace(${output.associatedVariableName});\r\n #endif\r\n `;\n }\n state.compilationString += `#ifdef ${this._gammaDefineName}\r\n ${output.associatedVariableName} = toLinearSpace(${output.associatedVariableName});\r\n #endif\r\n `;\n }\n }\n _writeOutput(state, output, swizzle) {\n let complement = \"\";\n if (!this.disableLevelMultiplication) {\n complement = ` * ${this._textureInfoName}`;\n }\n state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle}${complement};\\r\\n`;\n this._generateConversionCode(state, output, swizzle);\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (this.source.isConnected) {\n this._imageSource = this.source.connectedPoint.ownerBlock;\n }\n else {\n this._imageSource = null;\n }\n this._textureInfoName = state._getFreeVariableName(\"textureInfoName\");\n this.level.associatedVariableName = this._textureInfoName;\n this._tempTextureRead = state._getFreeVariableName(\"tempTextureRead\");\n this._linearDefineName = state._getFreeDefineName(\"ISLINEAR\");\n this._gammaDefineName = state._getFreeDefineName(\"ISGAMMA\");\n if (!this._imageSource) {\n this._samplerName = state._getFreeVariableName(this.name + \"Sampler\");\n state._emit2DSampler(this._samplerName);\n }\n // Declarations\n state.sharedData.blockingBlocks.push(this);\n state.sharedData.textureBlocks.push(this);\n state.sharedData.blocksWithDefines.push(this);\n state.sharedData.bindableBlocks.push(this);\n const comments = `//${this.name}`;\n state._emitFunctionFromInclude(\"helperFunctions\", comments);\n state._emitUniformFromString(this._textureInfoName, \"float\");\n this._generateTextureLookup(state);\n for (const output of this._outputs) {\n if (output.hasEndpoints && output.name !== \"level\") {\n this._writeOutput(state, output, output.name);\n }\n }\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n codeString += `${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\\r\\n`;\n codeString += `${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\\r\\n`;\n codeString += `${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\\r\\n`;\n codeString += `${this._codeVariableName}.projectAsCube = ${this.projectAsCube};\\r\\n`;\n if (!this.texture) {\n return codeString;\n }\n codeString += `${this._codeVariableName}.texture = new BABYLON.Texture(\"${this.texture.name}\", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\\r\\n`;\n codeString += `${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.convertToGammaSpace = this.convertToGammaSpace;\n serializationObject.convertToLinearSpace = this.convertToLinearSpace;\n serializationObject.disableLevelMultiplication = this.disableLevelMultiplication;\n serializationObject.projectAsCube = this.projectAsCube;\n if (!this.hasImageSource && this.texture && !this.texture.isRenderTarget && this.texture.getClassName() !== \"VideoTexture\") {\n serializationObject.texture = this.texture.serialize();\n }\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.convertToGammaSpace = serializationObject.convertToGammaSpace;\n this.convertToLinearSpace = !!serializationObject.convertToLinearSpace;\n this.disableLevelMultiplication = !!serializationObject.disableLevelMultiplication;\n this.projectAsCube = !!serializationObject.projectAsCube;\n if (serializationObject.texture && !NodeMaterial.IgnoreTexturesAtLoadTime && serializationObject.texture.url !== undefined) {\n rootUrl = serializationObject.texture.url.indexOf(\"data:\") === 0 ? \"\" : rootUrl;\n this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl);\n }\n }\n}\n__decorate([\n editableInPropertyPage(\"Project as cube\", PropertyTypeForEdition.Boolean, \"ADVANCED\", { notifiers: { update: true } })\n], TriPlanarBlock.prototype, \"projectAsCube\", void 0);\nRegisterClass(\"BABYLON.TriPlanarBlock\", TriPlanarBlock);\n//# sourceMappingURL=triPlanarBlock.js.map","import { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { TriPlanarBlock } from \"./triPlanarBlock.js\";\n/**\n * Block used to read a texture with triplanar mapping (see https://iquilezles.org/articles/biplanar/)\n */\nexport class BiPlanarBlock extends TriPlanarBlock {\n /**\n * Create a new BiPlanarBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, true);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"BiPlanarBlock\";\n }\n _generateTextureLookup(state) {\n var _a;\n const samplerName = this.samplerName;\n const samplerYName = (_a = this.samplerYName) !== null && _a !== void 0 ? _a : this.samplerName;\n const sharpness = this.sharpness.isConnected ? this.sharpness.associatedVariableName : \"1.0\";\n const dpdx = state._getFreeVariableName(\"dpdx\");\n const dpdy = state._getFreeVariableName(\"dpdy\");\n const n = state._getFreeVariableName(\"n\");\n const ma = state._getFreeVariableName(\"ma\");\n const mi = state._getFreeVariableName(\"mi\");\n const me = state._getFreeVariableName(\"me\");\n const x = state._getFreeVariableName(\"x\");\n const y = state._getFreeVariableName(\"y\");\n const w = state._getFreeVariableName(\"y\");\n state.compilationString += `\r\n // grab coord derivatives for texturing\r\n vec3 ${dpdx} = dFdx(${this.position.associatedVariableName}.xyz);\r\n vec3 ${dpdy} = dFdy(${this.position.associatedVariableName}.xyz);\r\n vec3 ${n} = abs(${this.normal.associatedVariableName}.xyz);\r\n \r\n // determine major axis (in x; yz are following axis)\r\n ivec3 ${ma} = (${n}.x>${n}.y && ${n}.x>${n}.z) ? ivec3(0,1,2) :\r\n (${n}.y>${n}.z) ? ivec3(1,2,0) :\r\n ivec3(2,0,1) ;\r\n // determine minor axis (in x; yz are following axis)\r\n ivec3 ${mi} = (${n}.x<${n}.y && ${n}.x<${n}.z) ? ivec3(0,1,2) :\r\n (${n}.y<${n}.z) ? ivec3(1,2,0) :\r\n ivec3(2,0,1) ;\r\n // determine median axis (in x; yz are following axis)\r\n ivec3 ${me} = ivec3(3) - ${mi} - ${ma};\r\n \r\n // project+fetch\r\n vec4 ${x} = textureGrad( ${samplerName}, vec2( ${this.position.associatedVariableName}[${ma}.y], ${this.position.associatedVariableName}[${ma}.z]), \r\n vec2(${dpdx}[${ma}.y],${dpdx}[${ma}.z]), \r\n vec2(${dpdy}[${ma}.y],${dpdy}[${ma}.z]) );\r\n vec4 ${y} = textureGrad( ${samplerYName}, vec2( ${this.position.associatedVariableName}[${me}.y], ${this.position.associatedVariableName}[${me}.z]), \r\n vec2(${dpdx}[${me}.y],${dpdx}[${me}.z]),\r\n vec2(${dpdy}[${me}.y],${dpdy}[${me}.z]) );\r\n \r\n // blend factors\r\n vec2 ${w} = vec2(${n}[${ma}.x],${n}[${me}.x]);\r\n // make local support\r\n ${w} = clamp( (${w}-0.5773)/(1.0-0.5773), 0.0, 1.0 );\r\n // shape transition\r\n ${w} = pow( ${w}, vec2(${sharpness}/8.0) );\r\n // blend and return\r\n vec4 ${this._tempTextureRead} = (${x}*${w}.x + ${y}*${w}.y) / (${w}.x + ${w}.y);\r\n `;\n }\n}\nRegisterClass(\"BABYLON.BiPlanarBlock\", BiPlanarBlock);\n//# sourceMappingURL=biPlanarBlock.js.map","import { __decorate } from \"../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { InputBlock } from \"./Input/inputBlock.js\";\nimport { MorphTargetsBlock } from \"./Vertex/morphTargetsBlock.js\";\nimport { PropertyTypeForEdition, editableInPropertyPage } from \"../nodeMaterialDecorator.js\";\nexport var MeshAttributeExistsBlockTypes;\n(function (MeshAttributeExistsBlockTypes) {\n MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes[\"None\"] = 0] = \"None\";\n MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes[\"Normal\"] = 1] = \"Normal\";\n MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes[\"Tangent\"] = 2] = \"Tangent\";\n MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes[\"VertexColor\"] = 3] = \"VertexColor\";\n MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes[\"UV1\"] = 4] = \"UV1\";\n MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes[\"UV2\"] = 5] = \"UV2\";\n MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes[\"UV3\"] = 6] = \"UV3\";\n MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes[\"UV4\"] = 7] = \"UV4\";\n MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes[\"UV5\"] = 8] = \"UV5\";\n MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes[\"UV6\"] = 9] = \"UV6\";\n})(MeshAttributeExistsBlockTypes || (MeshAttributeExistsBlockTypes = {}));\n/**\n * Block used to check if Mesh attribute of specified type exists\n * and provide an alternative fallback input for to use in such case\n */\nexport class MeshAttributeExistsBlock extends NodeMaterialBlock {\n /**\n * Creates a new MeshAttributeExistsBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n /**\n * Defines which mesh attribute to use\n */\n this.attributeType = MeshAttributeExistsBlockTypes.None;\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"fallback\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._linkConnectionTypes(0, 1);\n // Try to auto determine attributeType\n this._inputs[0].onConnectionObservable.add((other) => {\n var _a;\n if (this.attributeType) {\n // But only if not already specified\n return;\n }\n const sourceBlock = other.ownerBlock;\n if (sourceBlock instanceof InputBlock && sourceBlock.isAttribute) {\n switch (sourceBlock.name) {\n case \"color\":\n this.attributeType = MeshAttributeExistsBlockTypes.VertexColor;\n break;\n case \"normal\":\n this.attributeType = MeshAttributeExistsBlockTypes.Normal;\n break;\n case \"tangent\":\n this.attributeType = MeshAttributeExistsBlockTypes.Tangent;\n break;\n case \"uv\":\n this.attributeType = MeshAttributeExistsBlockTypes.UV1;\n break;\n case \"uv2\":\n this.attributeType = MeshAttributeExistsBlockTypes.UV2;\n break;\n case \"uv3\":\n this.attributeType = MeshAttributeExistsBlockTypes.UV3;\n break;\n case \"uv4\":\n this.attributeType = MeshAttributeExistsBlockTypes.UV4;\n break;\n case \"uv5\":\n this.attributeType = MeshAttributeExistsBlockTypes.UV5;\n break;\n case \"uv6\":\n this.attributeType = MeshAttributeExistsBlockTypes.UV6;\n break;\n }\n }\n else if (sourceBlock instanceof MorphTargetsBlock) {\n switch ((_a = this.input.connectedPoint) === null || _a === void 0 ? void 0 : _a.name) {\n case \"normalOutput\":\n this.attributeType = MeshAttributeExistsBlockTypes.Normal;\n break;\n case \"tangentOutput\":\n this.attributeType = MeshAttributeExistsBlockTypes.Tangent;\n break;\n case \"uvOutput\":\n this.attributeType = MeshAttributeExistsBlockTypes.UV1;\n break;\n }\n }\n });\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"MeshAttributeExistsBlock\";\n }\n /**\n * Gets the input component\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the fallback component when speciefied attribute doesn't exist\n */\n get fallback() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n let attributeDefine = null;\n switch (this.attributeType) {\n case MeshAttributeExistsBlockTypes.VertexColor:\n attributeDefine = \"VERTEXCOLOR_NME\";\n break;\n case MeshAttributeExistsBlockTypes.Normal:\n attributeDefine = \"NORMAL\";\n break;\n case MeshAttributeExistsBlockTypes.Tangent:\n attributeDefine = \"TANGENT\";\n break;\n case MeshAttributeExistsBlockTypes.UV1:\n attributeDefine = \"UV1\";\n break;\n case MeshAttributeExistsBlockTypes.UV2:\n attributeDefine = \"UV2\";\n break;\n case MeshAttributeExistsBlockTypes.UV3:\n attributeDefine = \"UV3\";\n break;\n case MeshAttributeExistsBlockTypes.UV4:\n attributeDefine = \"UV4\";\n break;\n case MeshAttributeExistsBlockTypes.UV5:\n attributeDefine = \"UV5\";\n break;\n case MeshAttributeExistsBlockTypes.UV6:\n attributeDefine = \"UV6\";\n break;\n }\n const output = this._declareOutput(this.output, state);\n if (attributeDefine) {\n state.compilationString += `#ifdef ${attributeDefine}\\r\\n`;\n }\n state.compilationString += `${output} = ${this.input.associatedVariableName};\\r\\n`;\n if (attributeDefine) {\n state.compilationString += `#else\\r\\n`;\n state.compilationString += `${output} = ${this.fallback.associatedVariableName};\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n }\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.attributeType = this.attributeType;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n var _a;\n super._deserialize(serializationObject, scene, rootUrl);\n this.attributeType = (_a = serializationObject.attributeType) !== null && _a !== void 0 ? _a : MeshAttributeExistsBlockTypes.None;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n codeString += `${this._codeVariableName}.attributeType = ${this.attributeType};\\r\\n`;\n return codeString;\n }\n}\n__decorate([\n editableInPropertyPage(\"Attribute lookup\", PropertyTypeForEdition.List, undefined, {\n notifiers: { update: true },\n options: [\n { label: \"(None)\", value: MeshAttributeExistsBlockTypes.None },\n { label: \"Normal\", value: MeshAttributeExistsBlockTypes.Normal },\n { label: \"Tangent\", value: MeshAttributeExistsBlockTypes.Tangent },\n { label: \"Vertex Color\", value: MeshAttributeExistsBlockTypes.VertexColor },\n { label: \"UV1\", value: MeshAttributeExistsBlockTypes.UV1 },\n { label: \"UV2\", value: MeshAttributeExistsBlockTypes.UV2 },\n { label: \"UV3\", value: MeshAttributeExistsBlockTypes.UV3 },\n { label: \"UV4\", value: MeshAttributeExistsBlockTypes.UV4 },\n { label: \"UV5\", value: MeshAttributeExistsBlockTypes.UV5 },\n { label: \"UV6\", value: MeshAttributeExistsBlockTypes.UV6 },\n ],\n })\n], MeshAttributeExistsBlock.prototype, \"attributeType\", void 0);\nRegisterClass(\"BABYLON.MeshAttributeExistsBlock\", MeshAttributeExistsBlock);\n//# sourceMappingURL=meshAttributeExistsBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to compute the determinant of a matrix\n */\nexport class MatrixDeterminantBlock extends NodeMaterialBlock {\n /**\n * Creates a new MatrixDeterminantBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.Matrix);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"MatrixDeterminantBlock\";\n }\n /**\n * Gets the input matrix\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this.output;\n const input = this.input;\n state.compilationString += this._declareOutput(output, state) + `${output.associatedVariableName} = determinant(${input.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.MatrixDeterminantBlock\", MatrixDeterminantBlock);\n//# sourceMappingURL=matrixDeterminantBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to transpose a matrix\n */\nexport class MatrixTransposeBlock extends NodeMaterialBlock {\n /**\n * Creates a new MatrixTransposeBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.Matrix);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Matrix);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"MatrixTransposeBlock\";\n }\n /**\n * Gets the input matrix\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this.output;\n const input = this.input;\n state.compilationString += this._declareOutput(output, state) + `${output.associatedVariableName} = transpose(${input.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.MatrixTransposeBlock\", MatrixTransposeBlock);\n//# sourceMappingURL=matrixTransposeBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Types of curves supported by the Curve block\n */\nexport var CurveBlockTypes;\n(function (CurveBlockTypes) {\n /** EaseInSine */\n CurveBlockTypes[CurveBlockTypes[\"EaseInSine\"] = 0] = \"EaseInSine\";\n /** EaseOutSine */\n CurveBlockTypes[CurveBlockTypes[\"EaseOutSine\"] = 1] = \"EaseOutSine\";\n /** EaseInOutSine */\n CurveBlockTypes[CurveBlockTypes[\"EaseInOutSine\"] = 2] = \"EaseInOutSine\";\n /** EaseInQuad */\n CurveBlockTypes[CurveBlockTypes[\"EaseInQuad\"] = 3] = \"EaseInQuad\";\n /** EaseOutQuad */\n CurveBlockTypes[CurveBlockTypes[\"EaseOutQuad\"] = 4] = \"EaseOutQuad\";\n /** EaseInOutQuad */\n CurveBlockTypes[CurveBlockTypes[\"EaseInOutQuad\"] = 5] = \"EaseInOutQuad\";\n /** EaseInCubic */\n CurveBlockTypes[CurveBlockTypes[\"EaseInCubic\"] = 6] = \"EaseInCubic\";\n /** EaseOutCubic */\n CurveBlockTypes[CurveBlockTypes[\"EaseOutCubic\"] = 7] = \"EaseOutCubic\";\n /** EaseInOutCubic */\n CurveBlockTypes[CurveBlockTypes[\"EaseInOutCubic\"] = 8] = \"EaseInOutCubic\";\n /** EaseInQuart */\n CurveBlockTypes[CurveBlockTypes[\"EaseInQuart\"] = 9] = \"EaseInQuart\";\n /** EaseOutQuart */\n CurveBlockTypes[CurveBlockTypes[\"EaseOutQuart\"] = 10] = \"EaseOutQuart\";\n /** EaseInOutQuart */\n CurveBlockTypes[CurveBlockTypes[\"EaseInOutQuart\"] = 11] = \"EaseInOutQuart\";\n /** EaseInQuint */\n CurveBlockTypes[CurveBlockTypes[\"EaseInQuint\"] = 12] = \"EaseInQuint\";\n /** EaseOutQuint */\n CurveBlockTypes[CurveBlockTypes[\"EaseOutQuint\"] = 13] = \"EaseOutQuint\";\n /** EaseInOutQuint */\n CurveBlockTypes[CurveBlockTypes[\"EaseInOutQuint\"] = 14] = \"EaseInOutQuint\";\n /** EaseInExpo */\n CurveBlockTypes[CurveBlockTypes[\"EaseInExpo\"] = 15] = \"EaseInExpo\";\n /** EaseOutExpo */\n CurveBlockTypes[CurveBlockTypes[\"EaseOutExpo\"] = 16] = \"EaseOutExpo\";\n /** EaseInOutExpo */\n CurveBlockTypes[CurveBlockTypes[\"EaseInOutExpo\"] = 17] = \"EaseInOutExpo\";\n /** EaseInCirc */\n CurveBlockTypes[CurveBlockTypes[\"EaseInCirc\"] = 18] = \"EaseInCirc\";\n /** EaseOutCirc */\n CurveBlockTypes[CurveBlockTypes[\"EaseOutCirc\"] = 19] = \"EaseOutCirc\";\n /** EaseInOutCirc */\n CurveBlockTypes[CurveBlockTypes[\"EaseInOutCirc\"] = 20] = \"EaseInOutCirc\";\n /** EaseInBack */\n CurveBlockTypes[CurveBlockTypes[\"EaseInBack\"] = 21] = \"EaseInBack\";\n /** EaseOutBack */\n CurveBlockTypes[CurveBlockTypes[\"EaseOutBack\"] = 22] = \"EaseOutBack\";\n /** EaseInOutBack */\n CurveBlockTypes[CurveBlockTypes[\"EaseInOutBack\"] = 23] = \"EaseInOutBack\";\n /** EaseInElastic */\n CurveBlockTypes[CurveBlockTypes[\"EaseInElastic\"] = 24] = \"EaseInElastic\";\n /** EaseOutElastic */\n CurveBlockTypes[CurveBlockTypes[\"EaseOutElastic\"] = 25] = \"EaseOutElastic\";\n /** EaseInOutElastic */\n CurveBlockTypes[CurveBlockTypes[\"EaseInOutElastic\"] = 26] = \"EaseInOutElastic\";\n})(CurveBlockTypes || (CurveBlockTypes = {}));\n/**\n * Block used to apply curve operation\n */\nexport class CurveBlock extends NodeMaterialBlock {\n /**\n * Creates a new CurveBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n /**\n * Gets or sets the type of the curve applied by the block\n */\n this.type = CurveBlockTypes.EaseInOutSine;\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Object);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Int);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"CurveBlock\";\n }\n /**\n * Gets the input component\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _duplicateEntry(entry, component) {\n return `ret.${component} = ${entry.replace(/VAL/g, \"v.\" + component)}`;\n }\n _duplicateEntryDirect(entry) {\n return `return ${entry.replace(/VAL/g, \"v\")}`;\n }\n _duplicateVector(entry, inputType) {\n if (inputType === \"float\") {\n return this._duplicateEntryDirect(entry);\n }\n const size = parseInt(inputType.replace(\"vec\", \"\"));\n let code = `\r\n vec${size} ret = vec${size}(0.0);\r\n `;\n for (let i = 1; i <= size; i++) {\n code += this._duplicateEntry(entry, i === 1 ? \"x\" : i === 2 ? \"y\" : i === 3 ? \"z\" : \"w\") + \";\\r\\n\";\n }\n code += \"return ret;\\r\\n\";\n return code;\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n let registeredFunction = \"\";\n let registeredFunctionName = \"\";\n let inputType = \"\";\n switch (this.input.type) {\n case NodeMaterialBlockConnectionPointTypes.Float:\n inputType = \"float\";\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector2:\n inputType = \"vec2\";\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector3:\n case NodeMaterialBlockConnectionPointTypes.Color3:\n inputType = \"vec3\";\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector4:\n case NodeMaterialBlockConnectionPointTypes.Color4:\n inputType = \"vec4\";\n break;\n }\n registeredFunctionName = CurveBlockTypes[this.type] + \"_\" + inputType;\n switch (this.type) {\n case CurveBlockTypes.EaseInSine:\n registeredFunction = `return 1.0 - cos((v * 3.1415) / 2.0)`;\n break;\n case CurveBlockTypes.EaseOutSine:\n registeredFunction = `return sin((v * 3.1415) / 2.0)`;\n break;\n case CurveBlockTypes.EaseInOutSine:\n registeredFunction = `return -(cos(v * 3.1415) - 1.0) / 2.0`;\n break;\n case CurveBlockTypes.EaseInQuad:\n registeredFunction = `return v * v`;\n break;\n case CurveBlockTypes.EaseOutQuad:\n registeredFunction = `return (1.0 - v) * (1.0 - v)`;\n break;\n case CurveBlockTypes.EaseInOutQuad: {\n const entry = \"VAL < 0.5 ? 2.0 * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInCubic:\n registeredFunction = `return v * v * v`;\n break;\n case CurveBlockTypes.EaseOutCubic: {\n const entry = \"1.0 - pow(1.0 - VAL, 3.0)\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInOutCubic: {\n const entry = \"VAL < 0.5 ? 4.0 * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInQuart:\n registeredFunction = `return v * v * v * v`;\n break;\n case CurveBlockTypes.EaseOutQuart: {\n const entry = \"1.0 - pow(1.0 - VAL, 4.0)\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInOutQuart: {\n const entry = \"VAL < 0.5 ? 8.0 * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInQuint:\n registeredFunction = `return v * v * v * v * v`;\n break;\n case CurveBlockTypes.EaseOutQuint: {\n const entry = \"1.0 - pow(1.0 - VAL, 5.0)\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInOutQuint: {\n const entry = \"VAL < 0.5 ? 16.0 * VAL * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInExpo: {\n const entry = \"VAL == 0.0 ? 0.0 : pow(2.0, 10.0 * VAL - 10.0)\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseOutExpo: {\n const entry = \"VAL == 1.0 ? 1.0 : 1.0 - pow(2.0, -10.0 * VAL)\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInOutExpo: {\n const entry = \"VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : VAL < 0.5 ? pow(2.0, 20.0 * VAL - 10.0) / 2.0 : (2.0 - pow(2.0, -20.0 * VAL + 10.0)) / 2.0\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInCirc: {\n const entry = \"1.0 - sqrt(1.0 - pow(VAL, 2.0))\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseOutCirc: {\n const entry = \"sqrt(1.0 - pow(VAL - 1.0, 2.0))\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInOutCirc: {\n const entry = \"VAL < 0.5 ? (1.0 - sqrt(1.0 - pow(2.0 * VAL, 2.0))) / 2.0 : (sqrt(1.0 - pow(-2.0 * VAL + 2.0, 2.0)) + 1.0) / 2.0\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInBack: {\n registeredFunction = \"return 2.70158 * v * v * v - 1.70158 * v * v\";\n break;\n }\n case CurveBlockTypes.EaseOutBack: {\n const entry = \"2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInOutBack: {\n const entry = \"VAL < 0.5 ? (pow(2.0 * VAL, 2.0) * ((3.5949095) * 2.0 * VAL - 2.5949095)) / 2.0 : (pow(2.0 * VAL - 2.0, 2.0) * (3.5949095 * (VAL * 2.0 - 2.0) + 3.5949095) + 2.0) / 2.0\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInElastic: {\n const entry = \"VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : -pow(2.0, 10.0 * VAL - 10.0) * sin((VAL * 10.0 - 10.75) * ((2.0 * 3.1415) / 3.0))\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseOutElastic: {\n const entry = \"VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : pow(2.0, -10.0 * VAL) * sin((VAL * 10.0 - 0.75) * ((2.0 * 3.1415) / 3.0)) + 1.0\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInOutElastic: {\n const entry = \"VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : VAL < 0.5 ? -(pow(2.0, 20.0 * VAL - 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 : (pow(2.0, -20.0 * VAL + 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 + 1.0\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n }\n state._emitFunction(registeredFunctionName, `${inputType} ${registeredFunctionName}(${inputType} v) {${registeredFunction};}\\r\\n`, \"\");\n state.compilationString += this._declareOutput(output, state) + ` = ${registeredFunctionName}(${this.input.associatedVariableName});\\r\\n`;\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.curveType = this.type;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.type = serializationObject.curveType;\n }\n _dumpPropertiesCode() {\n const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.type = BABYLON.CurveBlockTypes.${CurveBlockTypes[this.type]};\\r\\n`;\n return codeString;\n }\n}\nRegisterClass(\"BABYLON.CurveBlock\", CurveBlock);\n//# sourceMappingURL=curveBlock.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./Vertex/index.js\";\nexport * from \"./Fragment/index.js\";\nexport * from \"./Dual/index.js\";\nexport * from \"./Input/index.js\";\nexport * from \"./multiplyBlock.js\";\nexport * from \"./addBlock.js\";\nexport * from \"./scaleBlock.js\";\nexport * from \"./clampBlock.js\";\nexport * from \"./crossBlock.js\";\nexport * from \"./customBlock.js\";\nexport * from \"./dotBlock.js\";\nexport * from \"./transformBlock.js\";\nexport * from \"./remapBlock.js\";\nexport * from \"./normalizeBlock.js\";\nexport * from \"./trigonometryBlock.js\";\nexport * from \"./colorMergerBlock.js\";\nexport * from \"./vectorMergerBlock.js\";\nexport * from \"./colorSplitterBlock.js\";\nexport * from \"./vectorSplitterBlock.js\";\nexport * from \"./lerpBlock.js\";\nexport * from \"./divideBlock.js\";\nexport * from \"./subtractBlock.js\";\nexport * from \"./stepBlock.js\";\nexport * from \"./oneMinusBlock.js\";\nexport * from \"./viewDirectionBlock.js\";\nexport * from \"./fresnelBlock.js\";\nexport * from \"./maxBlock.js\";\nexport * from \"./minBlock.js\";\nexport * from \"./distanceBlock.js\";\nexport * from \"./lengthBlock.js\";\nexport * from \"./negateBlock.js\";\nexport * from \"./powBlock.js\";\nexport * from \"./randomNumberBlock.js\";\nexport * from \"./arcTan2Block.js\";\nexport * from \"./smoothStepBlock.js\";\nexport * from \"./reciprocalBlock.js\";\nexport * from \"./replaceColorBlock.js\";\nexport * from \"./posterizeBlock.js\";\nexport * from \"./waveBlock.js\";\nexport * from \"./gradientBlock.js\";\nexport * from \"./nLerpBlock.js\";\nexport * from \"./worleyNoise3DBlock.js\";\nexport * from \"./simplexPerlin3DBlock.js\";\nexport * from \"./normalBlendBlock.js\";\nexport * from \"./rotate2dBlock.js\";\nexport * from \"./reflectBlock.js\";\nexport * from \"./refractBlock.js\";\nexport * from \"./desaturateBlock.js\";\nexport * from \"./PBR/index.js\";\nexport * from \"./Particle/index.js\";\nexport * from \"./modBlock.js\";\nexport * from \"./matrixBuilderBlock.js\";\nexport * from \"./conditionalBlock.js\";\nexport * from \"./cloudBlock.js\";\nexport * from \"./voronoiNoiseBlock.js\";\nexport * from \"./elbowBlock.js\";\nexport * from \"./triPlanarBlock.js\";\nexport * from \"./biPlanarBlock.js\";\nexport * from \"./matrixDeterminantBlock.js\";\nexport * from \"./matrixTransposeBlock.js\";\nexport * from \"./meshAttributeExistsBlock.js\";\nexport * from \"./curveBlock.js\";\n//# sourceMappingURL=index.js.map","import { Effect } from \"./effect.js\";\nimport { RandomGUID } from \"../Misc/guid.js\";\nimport { DrawWrapper } from \"./drawWrapper.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nclass MapMap {\n constructor() {\n this.mm = new Map();\n }\n get(a, b) {\n const m = this.mm.get(a);\n if (m !== undefined) {\n return m.get(b);\n }\n return undefined;\n }\n set(a, b, v) {\n let m = this.mm.get(a);\n if (m === undefined) {\n this.mm.set(a, (m = new Map()));\n }\n m.set(b, v);\n }\n}\n/**\n * Class that can be used to wrap a base material to generate accurate shadows when using custom vertex/fragment code in the base material\n */\nexport class ShadowDepthWrapper {\n /** Gets the standalone status of the wrapper */\n get standalone() {\n var _a, _b;\n return (_b = (_a = this._options) === null || _a === void 0 ? void 0 : _a.standalone) !== null && _b !== void 0 ? _b : false;\n }\n /** Gets the base material the wrapper is built upon */\n get baseMaterial() {\n return this._baseMaterial;\n }\n /** Gets the doNotInjectCode status of the wrapper */\n get doNotInjectCode() {\n var _a, _b;\n return (_b = (_a = this._options) === null || _a === void 0 ? void 0 : _a.doNotInjectCode) !== null && _b !== void 0 ? _b : false;\n }\n /**\n * Instantiate a new shadow depth wrapper.\n * It works by injecting some specific code in the vertex/fragment shaders of the base material and is used by a shadow generator to\n * generate the shadow depth map. For more information, please refer to the documentation:\n * https://doc.babylonjs.com/features/featuresDeepDive/lights/shadows\n * @param baseMaterial Material to wrap\n * @param scene Define the scene the material belongs to\n * @param options Options used to create the wrapper\n */\n constructor(baseMaterial, scene, options) {\n this._baseMaterial = baseMaterial;\n this._scene = scene !== null && scene !== void 0 ? scene : EngineStore.LastCreatedScene;\n this._options = options;\n this._subMeshToEffect = new Map();\n this._subMeshToDepthWrapper = new MapMap();\n this._meshes = new Map();\n // Register for onEffectCreated to store the effect of the base material when it is (re)generated. This effect will be used\n // to create the depth effect later on\n this._onEffectCreatedObserver = this._baseMaterial.onEffectCreatedObservable.add((params) => {\n var _a;\n const mesh = (_a = params.subMesh) === null || _a === void 0 ? void 0 : _a.getMesh();\n if (mesh && !this._meshes.has(mesh)) {\n // Register for mesh onDispose to clean up our internal maps when a mesh is disposed\n this._meshes.set(mesh, mesh.onDisposeObservable.add((mesh) => {\n const iterator = this._subMeshToEffect.keys();\n for (let key = iterator.next(); key.done !== true; key = iterator.next()) {\n const subMesh = key.value;\n if ((subMesh === null || subMesh === void 0 ? void 0 : subMesh.getMesh()) === mesh) {\n this._subMeshToEffect.delete(subMesh);\n this._subMeshToDepthWrapper.mm.delete(subMesh);\n }\n }\n }));\n }\n this._subMeshToEffect.set(params.subMesh, [params.effect, this._scene.getEngine().currentRenderPassId]);\n this._subMeshToDepthWrapper.mm.delete(params.subMesh); // trigger a depth effect recreation\n });\n }\n /**\n * Gets the effect to use to generate the depth map\n * @param subMesh subMesh to get the effect for\n * @param shadowGenerator shadow generator to get the effect for\n * @param passIdForDrawWrapper Id of the pass for which the effect from the draw wrapper must be retrieved from\n * @returns the effect to use to generate the depth map for the subMesh + shadow generator specified\n */\n getEffect(subMesh, shadowGenerator, passIdForDrawWrapper) {\n var _a;\n const entry = (_a = this._subMeshToDepthWrapper.mm.get(subMesh)) === null || _a === void 0 ? void 0 : _a.get(shadowGenerator);\n if (!entry) {\n return null;\n }\n let drawWrapper = entry.drawWrapper[passIdForDrawWrapper];\n if (!drawWrapper) {\n drawWrapper = entry.drawWrapper[passIdForDrawWrapper] = new DrawWrapper(this._scene.getEngine());\n drawWrapper.setEffect(entry.mainDrawWrapper.effect, entry.mainDrawWrapper.defines);\n }\n return drawWrapper;\n }\n /**\n * Specifies that the submesh is ready to be used for depth rendering\n * @param subMesh submesh to check\n * @param defines the list of defines to take into account when checking the effect\n * @param shadowGenerator combined with subMesh, it defines the effect to check\n * @param useInstances specifies that instances should be used\n * @param passIdForDrawWrapper Id of the pass for which the draw wrapper should be created\n * @returns a boolean indicating that the submesh is ready or not\n */\n isReadyForSubMesh(subMesh, defines, shadowGenerator, useInstances, passIdForDrawWrapper) {\n var _a, _b;\n if (this.standalone) {\n // will ensure the effect is (re)created for the base material\n if (!this._baseMaterial.isReadyForSubMesh(subMesh.getMesh(), subMesh, useInstances)) {\n return false;\n }\n }\n return (_b = (_a = this._makeEffect(subMesh, defines, shadowGenerator, passIdForDrawWrapper)) === null || _a === void 0 ? void 0 : _a.isReady()) !== null && _b !== void 0 ? _b : false;\n }\n /**\n * Disposes the resources\n */\n dispose() {\n this._baseMaterial.onEffectCreatedObservable.remove(this._onEffectCreatedObserver);\n this._onEffectCreatedObserver = null;\n const iterator = this._meshes.entries();\n for (let entry = iterator.next(); entry.done !== true; entry = iterator.next()) {\n const [mesh, observer] = entry.value;\n mesh.onDisposeObservable.remove(observer);\n }\n }\n _makeEffect(subMesh, defines, shadowGenerator, passIdForDrawWrapper) {\n var _a, _b, _c;\n const engine = this._scene.getEngine();\n const origEffectAndRenderPassId = this._subMeshToEffect.get(subMesh);\n if (!origEffectAndRenderPassId) {\n return null;\n }\n const [origEffect, origRenderPassId] = origEffectAndRenderPassId;\n let params = this._subMeshToDepthWrapper.get(subMesh, shadowGenerator);\n if (!params) {\n const mainDrawWrapper = new DrawWrapper(engine);\n mainDrawWrapper.defines = (_b = (_a = subMesh._getDrawWrapper(origRenderPassId)) === null || _a === void 0 ? void 0 : _a.defines) !== null && _b !== void 0 ? _b : null;\n params = {\n drawWrapper: [],\n mainDrawWrapper,\n depthDefines: \"\",\n token: RandomGUID(),\n };\n params.drawWrapper[passIdForDrawWrapper] = mainDrawWrapper;\n this._subMeshToDepthWrapper.set(subMesh, shadowGenerator, params);\n }\n const join = defines.join(\"\\n\");\n if (params.mainDrawWrapper.effect) {\n if (join === params.depthDefines) {\n // we already created the depth effect and it is still up to date for this submesh + shadow generator\n return params.mainDrawWrapper.effect;\n }\n }\n params.depthDefines = join;\n const uniforms = origEffect.getUniformNames().slice();\n // the depth effect is either out of date or has not been created yet\n let vertexCode = origEffect.vertexSourceCodeBeforeMigration, fragmentCode = origEffect.fragmentSourceCodeBeforeMigration;\n if (!this.doNotInjectCode) {\n // vertex code\n const vertexNormalBiasCode = this._options && this._options.remappedVariables\n ? `#include(${this._options.remappedVariables.join(\",\")})`\n : Effect.IncludesShadersStore[\"shadowMapVertexNormalBias\"], vertexMetricCode = this._options && this._options.remappedVariables\n ? `#include(${this._options.remappedVariables.join(\",\")})`\n : Effect.IncludesShadersStore[\"shadowMapVertexMetric\"], fragmentSoftTransparentShadow = this._options && this._options.remappedVariables\n ? `#include(${this._options.remappedVariables.join(\",\")})`\n : Effect.IncludesShadersStore[\"shadowMapFragmentSoftTransparentShadow\"], fragmentBlockCode = Effect.IncludesShadersStore[\"shadowMapFragment\"];\n vertexCode = vertexCode.replace(/void\\s+?main/g, Effect.IncludesShadersStore[\"shadowMapVertexExtraDeclaration\"] + \"\\r\\nvoid main\");\n vertexCode = vertexCode.replace(/#define SHADOWDEPTH_NORMALBIAS|#define CUSTOM_VERTEX_UPDATE_WORLDPOS/g, vertexNormalBiasCode);\n if (vertexCode.indexOf(\"#define SHADOWDEPTH_METRIC\") !== -1) {\n vertexCode = vertexCode.replace(/#define SHADOWDEPTH_METRIC/g, vertexMetricCode);\n }\n else {\n vertexCode = vertexCode.replace(/}\\s*$/g, vertexMetricCode + \"\\r\\n}\");\n }\n vertexCode = vertexCode.replace(/#define SHADER_NAME.*?\\n|out vec4 glFragColor;\\n/g, \"\");\n // fragment code\n const hasLocationForSoftTransparentShadow = fragmentCode.indexOf(\"#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW\") >= 0 || fragmentCode.indexOf(\"#define CUSTOM_FRAGMENT_BEFORE_FOG\") >= 0;\n const hasLocationForFragment = fragmentCode.indexOf(\"#define SHADOWDEPTH_FRAGMENT\") !== -1;\n let fragmentCodeToInjectAtEnd = \"\";\n if (!hasLocationForSoftTransparentShadow) {\n fragmentCodeToInjectAtEnd = fragmentSoftTransparentShadow + \"\\r\\n\";\n }\n else {\n fragmentCode = fragmentCode.replace(/#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW|#define CUSTOM_FRAGMENT_BEFORE_FOG/g, fragmentSoftTransparentShadow);\n }\n fragmentCode = fragmentCode.replace(/void\\s+?main/g, Effect.IncludesShadersStore[\"shadowMapFragmentExtraDeclaration\"] + \"\\r\\nvoid main\");\n if (hasLocationForFragment) {\n fragmentCode = fragmentCode.replace(/#define SHADOWDEPTH_FRAGMENT/g, fragmentBlockCode);\n }\n else {\n fragmentCodeToInjectAtEnd += fragmentBlockCode + \"\\r\\n\";\n }\n if (fragmentCodeToInjectAtEnd) {\n fragmentCode = fragmentCode.replace(/}\\s*$/g, fragmentCodeToInjectAtEnd + \"}\");\n }\n uniforms.push(\"biasAndScaleSM\", \"depthValuesSM\", \"lightDataSM\", \"softTransparentShadowSM\");\n }\n params.mainDrawWrapper.effect = engine.createEffect({\n vertexSource: vertexCode,\n fragmentSource: fragmentCode,\n vertexToken: params.token,\n fragmentToken: params.token,\n }, {\n attributes: origEffect.getAttributesNames(),\n uniformsNames: uniforms,\n uniformBuffersNames: origEffect.getUniformBuffersNames(),\n samplers: origEffect.getSamplers(),\n defines: join + \"\\n\" + origEffect.defines.replace(\"#define SHADOWS\", \"\").replace(/#define SHADOW\\d/g, \"\"),\n indexParameters: origEffect.getIndexParameters(),\n }, engine);\n for (let id = 0; id < params.drawWrapper.length; ++id) {\n if (id !== passIdForDrawWrapper) {\n (_c = params.drawWrapper[id]) === null || _c === void 0 ? void 0 : _c.setEffect(params.mainDrawWrapper.effect, params.mainDrawWrapper.defines);\n }\n }\n return params.mainDrawWrapper.effect;\n }\n}\n//# sourceMappingURL=shadowDepthWrapper.js.map","/**\n * Root class for all node material optimizers\n */\nexport class NodeMaterialOptimizer {\n /**\n * Function used to optimize a NodeMaterial graph\n * @param _vertexOutputNodes defines the list of output nodes for the vertex shader\n * @param _fragmentOutputNodes defines the list of output nodes for the fragment shader\n */\n optimize(_vertexOutputNodes, _fragmentOutputNodes) {\n // Do nothing by default\n }\n}\n//# sourceMappingURL=nodeMaterialOptimizer.js.map","export * from \"./nodeMaterialOptimizer.js\";\n//# sourceMappingURL=index.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./Enums/index.js\";\nexport * from \"./nodeMaterialConnectionPointCustomObject.js\";\nexport * from \"./nodeMaterialBlockConnectionPoint.js\";\nexport * from \"./nodeMaterialBlock.js\";\nexport * from \"./nodeMaterial.js\";\nexport * from \"./Blocks/index.js\";\nexport * from \"./Optimizers/index.js\";\nexport * from \"./nodeMaterialDecorator.js\";\n//# sourceMappingURL=index.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize, expandToProperty } from \"../Misc/decorators.js\";\nimport { MaterialDefines } from \"./materialDefines.js\";\nimport { MaterialPluginBase } from \"./materialPluginBase.js\";\n\nimport { MaterialFlags } from \"./materialFlags.js\";\nimport { MaterialHelper } from \"./materialHelper.js\";\n/**\n * @internal\n */\nexport class DecalMapDefines extends MaterialDefines {\n constructor() {\n super(...arguments);\n this.DECAL = false;\n this.DECALDIRECTUV = 0;\n this.DECAL_SMOOTHALPHA = false;\n this.GAMMADECAL = false;\n }\n}\n/**\n * Plugin that implements the decal map component of a material\n * @since 5.49.1\n */\nexport class DecalMapConfiguration extends MaterialPluginBase {\n /** @internal */\n _markAllSubMeshesAsTexturesDirty() {\n this._enable(this._isEnabled);\n this._internalMarkAllSubMeshesAsTexturesDirty();\n }\n /**\n * Creates a new DecalMapConfiguration\n * @param material The material to attach the decal map plugin to\n * @param addToPluginList If the plugin should be added to the material plugin list\n */\n constructor(material, addToPluginList = true) {\n super(material, \"DecalMap\", 150, new DecalMapDefines(), addToPluginList);\n this._isEnabled = false;\n /**\n * Enables or disables the decal map on this material\n */\n this.isEnabled = false;\n this._smoothAlpha = false;\n /**\n * Enables or disables the smooth alpha mode on this material. Default: false.\n * When enabled, the alpha value used to blend the decal map will be the squared value and will produce a smoother result.\n */\n this.smoothAlpha = false;\n this.registerForExtraEvents = true; // because we override the hardBindForSubMesh method\n this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];\n }\n isReadyForSubMesh(defines, scene, engine, subMesh) {\n const decalMap = subMesh.getMesh().decalMap;\n if (!this._isEnabled || !(decalMap === null || decalMap === void 0 ? void 0 : decalMap.texture) || !MaterialFlags.DecalMapEnabled || !scene.texturesEnabled) {\n return true;\n }\n return decalMap.isReady();\n }\n prepareDefines(defines, scene, mesh) {\n const decalMap = mesh.decalMap;\n if (!this._isEnabled || !(decalMap === null || decalMap === void 0 ? void 0 : decalMap.texture) || !MaterialFlags.DecalMapEnabled || !scene.texturesEnabled) {\n const isDirty = defines.DECAL;\n if (isDirty) {\n defines.markAsTexturesDirty();\n }\n defines.DECAL = false;\n }\n else {\n const isDirty = !defines.DECAL || defines.GAMMADECAL !== decalMap.texture.gammaSpace;\n if (isDirty) {\n defines.markAsTexturesDirty();\n }\n defines.DECAL = true;\n defines.GAMMADECAL = decalMap.texture.gammaSpace;\n defines.DECAL_SMOOTHALPHA = this._smoothAlpha;\n MaterialHelper.PrepareDefinesForMergedUV(decalMap.texture, defines, \"DECAL\");\n }\n }\n /**\n * Note that we override hardBindForSubMesh and not bindForSubMesh because the material can be shared by multiple meshes,\n * in which case mustRebind could return false even though the decal map is different for each mesh: that's because the decal map\n * is not part of the material but hosted by the decalMap of the mesh instead.\n */\n hardBindForSubMesh(uniformBuffer, scene, _engine, subMesh) {\n const decalMap = subMesh.getMesh().decalMap;\n if (!this._isEnabled || !(decalMap === null || decalMap === void 0 ? void 0 : decalMap.texture) || !MaterialFlags.DecalMapEnabled || !scene.texturesEnabled) {\n return;\n }\n const isFrozen = this._material.isFrozen;\n const texture = decalMap.texture;\n if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {\n uniformBuffer.updateFloat4(\"vDecalInfos\", texture.coordinatesIndex, 0, 0, 0);\n MaterialHelper.BindTextureMatrix(texture, uniformBuffer, \"decal\");\n }\n uniformBuffer.setTexture(\"decalSampler\", texture);\n }\n getClassName() {\n return \"DecalMapConfiguration\";\n }\n getSamplers(samplers) {\n samplers.push(\"decalSampler\");\n }\n getUniforms() {\n return {\n ubo: [\n { name: \"vDecalInfos\", size: 4, type: \"vec4\" },\n { name: \"decalMatrix\", size: 16, type: \"mat4\" },\n ],\n };\n }\n}\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], DecalMapConfiguration.prototype, \"isEnabled\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], DecalMapConfiguration.prototype, \"smoothAlpha\", void 0);\n//# sourceMappingURL=material.decalMapConfiguration.js.map","import { DetailMapConfiguration } from \"./material.detailMapConfiguration.js\";\nimport { PBRAnisotropicConfiguration } from \"./PBR/pbrAnisotropicConfiguration.js\";\nimport { PBRBaseMaterial } from \"./PBR/pbrBaseMaterial.js\";\nimport { PBRBRDFConfiguration } from \"./PBR/pbrBRDFConfiguration.js\";\nimport { PBRClearCoatConfiguration } from \"./PBR/pbrClearCoatConfiguration.js\";\nimport { PBRIridescenceConfiguration } from \"./PBR/pbrIridescenceConfiguration.js\";\nimport { PBRSheenConfiguration } from \"./PBR/pbrSheenConfiguration.js\";\nimport { PBRSubSurfaceConfiguration } from \"./PBR/pbrSubSurfaceConfiguration.js\";\nimport { StandardMaterial } from \"./standardMaterial.js\";\n/**\n * Creates an instance of the anisotropic plugin\n * @param material parent material the plugin will be created for\n * @returns the plugin instance or null if the plugin is incompatible with material\n */\nexport function createPBRAnisotropicPlugin(material) {\n if (material instanceof PBRBaseMaterial) {\n return new PBRAnisotropicConfiguration(material);\n }\n return null;\n}\n/**\n * Creates an instance of the brdf plugin\n * @param material parent material the plugin will be created for\n * @returns the plugin instance or null if the plugin is incompatible with material\n */\nexport function createPBRBRDFPlugin(material) {\n if (material instanceof PBRBaseMaterial) {\n return new PBRBRDFConfiguration(material);\n }\n return null;\n}\n/**\n * Creates an instance of the clear coat plugin\n * @param material parent material the plugin will be created for\n * @returns the plugin instance or null if the plugin is incompatible with material\n */\nexport function createPBRClearCoatPlugin(material) {\n if (material instanceof PBRBaseMaterial) {\n return new PBRClearCoatConfiguration(material);\n }\n return null;\n}\n/**\n * Creates an instance of the iridescence plugin\n * @param material parent material the plugin will be created for\n * @returns the plugin instance or null if the plugin is incompatible with material\n */\nexport function createPBRIridescencePlugin(material) {\n if (material instanceof PBRBaseMaterial) {\n return new PBRIridescenceConfiguration(material);\n }\n return null;\n}\n/**\n * Creates an instance of the sheen plugin\n * @param material parent material the plugin will be created for\n * @returns the plugin instance or null if the plugin is incompatible with material\n */\nexport function createPBRSheenPlugin(material) {\n if (material instanceof PBRBaseMaterial) {\n return new PBRSheenConfiguration(material);\n }\n return null;\n}\n/**\n * Creates an instance of the sub surface plugin\n * @param material parent material the plugin will be created for\n * @returns the plugin instance or null if the plugin is incompatible with material\n */\nexport function createPBRSubSurfacePlugin(material) {\n if (material instanceof PBRBaseMaterial) {\n return new PBRSubSurfaceConfiguration(material);\n }\n return null;\n}\n/**\n * Creates an instance of the detail map plugin\n * @param material parent material the plugin will be created for\n * @returns the plugin instance or null if the plugin is incompatible with material\n */\nexport function createDetailMapPlugin(material) {\n if (material instanceof PBRBaseMaterial || material instanceof StandardMaterial) {\n return new DetailMapConfiguration(material);\n }\n return null;\n}\n//# sourceMappingURL=materialPluginFactoryExport.js.map","import { Engine } from \"../Engines/engine.js\";\nimport { RawTexture } from \"./Textures/rawTexture.js\";\nimport { MaterialPluginBase } from \"./materialPluginBase.js\";\nimport { TmpVectors } from \"../Maths/math.vector.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { MaterialDefines } from \"./materialDefines.js\";\nimport { DeepCopier } from \"../Misc/deepCopier.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\nexport var GreasedLineMeshMaterialType;\n(function (GreasedLineMeshMaterialType) {\n GreasedLineMeshMaterialType[GreasedLineMeshMaterialType[\"MATERIAL_TYPE_STANDARD\"] = 0] = \"MATERIAL_TYPE_STANDARD\";\n GreasedLineMeshMaterialType[GreasedLineMeshMaterialType[\"MATERIAL_TYPE_PBR\"] = 1] = \"MATERIAL_TYPE_PBR\";\n})(GreasedLineMeshMaterialType || (GreasedLineMeshMaterialType = {}));\nexport var GreasedLineMeshColorMode;\n(function (GreasedLineMeshColorMode) {\n GreasedLineMeshColorMode[GreasedLineMeshColorMode[\"COLOR_MODE_SET\"] = 0] = \"COLOR_MODE_SET\";\n GreasedLineMeshColorMode[GreasedLineMeshColorMode[\"COLOR_MODE_ADD\"] = 1] = \"COLOR_MODE_ADD\";\n GreasedLineMeshColorMode[GreasedLineMeshColorMode[\"COLOR_MODE_MULTIPLY\"] = 2] = \"COLOR_MODE_MULTIPLY\";\n})(GreasedLineMeshColorMode || (GreasedLineMeshColorMode = {}));\nexport var GreasedLineMeshColorDistributionType;\n(function (GreasedLineMeshColorDistributionType) {\n GreasedLineMeshColorDistributionType[GreasedLineMeshColorDistributionType[\"COLOR_DISTRIBUTION_TYPE_SEGMENT\"] = 0] = \"COLOR_DISTRIBUTION_TYPE_SEGMENT\";\n GreasedLineMeshColorDistributionType[GreasedLineMeshColorDistributionType[\"COLOR_DISTRIBUTION_TYPE_LINE\"] = 1] = \"COLOR_DISTRIBUTION_TYPE_LINE\";\n})(GreasedLineMeshColorDistributionType || (GreasedLineMeshColorDistributionType = {}));\n/**\n * @internal\n */\nexport class MaterialGreasedLineDefines extends MaterialDefines {\n constructor() {\n super(...arguments);\n /**\n * The material has a color option specified\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n this.GREASED_LINE_HAS_COLOR = false;\n /**\n * The material's size attenuation optiom\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n this.GREASED_LINE_SIZE_ATTENUATION = false;\n /**\n * The type of color distribution is set to line this value equals to true.\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n this.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE = false;\n }\n}\n/**\n * GreasedLinePluginMaterial for GreasedLineMesh\n */\nexport class GreasedLinePluginMaterial extends MaterialPluginBase {\n constructor(material, _scene, options) {\n var _a, _b, _c;\n options = options !== null && options !== void 0 ? options : {};\n const defines = new MaterialGreasedLineDefines();\n defines.GREASED_LINE_HAS_COLOR = !!options.color;\n defines.GREASED_LINE_SIZE_ATTENUATION = (_a = options.sizeAttenuation) !== null && _a !== void 0 ? _a : false;\n defines.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE = options.colorDistributionType === GreasedLineMeshColorDistributionType.COLOR_DISTRIBUTION_TYPE_LINE;\n super(material, GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME, 200, defines);\n this._scene = _scene;\n this._dashArray = 0;\n this._options = options;\n this._scene = (_b = this._scene) !== null && _b !== void 0 ? _b : material.getScene();\n this._engine = this._scene.getEngine();\n if (options.colors) {\n this._createColorsTexture(`${material.name}-colors-texture`, options.colors);\n }\n else {\n GreasedLinePluginMaterial._PrepareEmptyColorsTexture(_scene);\n }\n this.setDashCount((_c = options.dashCount) !== null && _c !== void 0 ? _c : 1); // calculate the _dashArray value\n this._enable(true); // always enabled\n }\n /**\n * Get the shader attributes\n * @param attributes array which will be filled with the attributes\n */\n getAttributes(attributes) {\n attributes.push(\"grl_offsets\");\n attributes.push(\"grl_previousAndSide\");\n attributes.push(\"grl_nextAndCounters\");\n attributes.push(\"grl_widths\");\n attributes.push(\"grl_colorPointers\");\n }\n /**\n * Get the shader samplers\n * @param samplers\n */\n getSamplers(samplers) {\n samplers.push(\"grl_colors\");\n }\n /**\n * Get the shader textures\n * @param activeTextures\n */\n getActiveTextures(activeTextures) {\n if (this._colorsTexture) {\n activeTextures.push(this._colorsTexture);\n }\n }\n /**\n * Get the shader uniforms\n * @returns uniforms\n */\n getUniforms() {\n const ubo = [\n { name: \"grl_projection\", size: 16, type: \"mat4\" },\n { name: \"grl_singleColor\", size: 3, type: \"vec3\" },\n { name: \"grl_resolution_lineWidth\", size: 3, type: \"vec3\" },\n { name: \"grl_dashOptions\", size: 4, type: \"vec4\" },\n { name: \"grl_colorMode_visibility_colorsWidth_useColors\", size: 4, type: \"vec4\" },\n ];\n return {\n ubo,\n vertex: `\r\n uniform vec3 grl_resolution_lineWidth;\r\n uniform mat4 grl_projection;\r\n `,\n fragment: `\r\n uniform vec4 grl_dashOptions;\r\n uniform vec4 grl_colorMode_visibility_colorsWidth_useColors;\r\n uniform vec3 grl_singleColor;\r\n `,\n };\n }\n // only getter, it doesn't make sense to use this plugin on a mesh other than GreasedLineMesh\n // and it doesn't make sense to disable it on the mesh\n get isEnabled() {\n return true;\n }\n /**\n * Bind the uniform buffer\n * @param uniformBuffer\n */\n bindForSubMesh(uniformBuffer) {\n var _a, _b, _c, _d, _e, _f, _g;\n const activeCamera = this._scene.activeCamera;\n if (activeCamera) {\n const projection = activeCamera.getProjectionMatrix();\n uniformBuffer.updateMatrix(\"grl_projection\", projection);\n }\n else {\n throw Error(\"GreasedLinePluginMaterial requires an active camera.\");\n }\n const resolutionLineWidth = TmpVectors.Vector3[0];\n if (this._options.resolution) {\n resolutionLineWidth.x = this._options.resolution.x;\n resolutionLineWidth.y = this._options.resolution.y;\n }\n else {\n resolutionLineWidth.x = this._engine.getRenderWidth();\n resolutionLineWidth.y = this._engine.getRenderHeight();\n }\n resolutionLineWidth.z = this._options.width ? this._options.width : this._options.sizeAttenuation ? 1 : 0.1;\n uniformBuffer.updateVector3(\"grl_resolution_lineWidth\", resolutionLineWidth);\n const dashOptions = TmpVectors.Vector4[0];\n dashOptions.x = GreasedLinePluginMaterial._BooleanToNumber(this._options.useDash);\n dashOptions.y = (_a = this._dashArray) !== null && _a !== void 0 ? _a : 0;\n dashOptions.z = (_b = this._options.dashOffset) !== null && _b !== void 0 ? _b : 0;\n dashOptions.w = (_c = this._options.dashRatio) !== null && _c !== void 0 ? _c : 0.5;\n uniformBuffer.updateVector4(\"grl_dashOptions\", dashOptions);\n const colorModeVisibilityColorsWidthUseColors = TmpVectors.Vector4[1];\n colorModeVisibilityColorsWidthUseColors.x = (_d = this._options.colorMode) !== null && _d !== void 0 ? _d : GreasedLineMeshColorMode.COLOR_MODE_SET;\n colorModeVisibilityColorsWidthUseColors.y = (_e = this._options.visibility) !== null && _e !== void 0 ? _e : 1;\n colorModeVisibilityColorsWidthUseColors.z = this._colorsTexture ? this._colorsTexture.getSize().width : 0;\n colorModeVisibilityColorsWidthUseColors.w = GreasedLinePluginMaterial._BooleanToNumber(this._options.useColors);\n uniformBuffer.updateVector4(\"grl_colorMode_visibility_colorsWidth_useColors\", colorModeVisibilityColorsWidthUseColors);\n if (this._options.color) {\n uniformBuffer.updateColor3(\"grl_singleColor\", (_f = this._options.color) !== null && _f !== void 0 ? _f : Color3.White());\n }\n uniformBuffer.setTexture(\"grl_colors\", (_g = this._colorsTexture) !== null && _g !== void 0 ? _g : GreasedLinePluginMaterial._EmptyColorsTexture);\n }\n /**\n * Prepare the defines\n * @param defines\n * @param _scene\n * @param _mesh\n */\n prepareDefines(defines, _scene, _mesh) {\n var _a;\n const options = this._options;\n defines.GREASED_LINE_HAS_COLOR = !!options.color;\n defines.GREASED_LINE_SIZE_ATTENUATION = (_a = options.sizeAttenuation) !== null && _a !== void 0 ? _a : false;\n defines.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE = options.colorDistributionType === GreasedLineMeshColorDistributionType.COLOR_DISTRIBUTION_TYPE_LINE;\n }\n /**\n * Get the class name\n * @returns class name\n */\n getClassName() {\n return GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME;\n }\n /**\n * Get shader code\n * @param shaderType vertex/fragment\n * @returns shader code\n */\n getCustomCode(shaderType) {\n if (shaderType === \"vertex\") {\n return {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CUSTOM_VERTEX_DEFINITIONS: `\r\n attribute vec4 grl_previousAndSide;\r\n attribute vec4 grl_nextAndCounters;\r\n attribute float grl_widths;\r\n attribute vec3 grl_offsets;\r\n attribute float grl_colorPointers;\r\n\r\n varying float grlCounters;\r\n varying float grlColorPointer;\r\n\r\n vec2 grlFix( vec4 i, float aspect ) {\r\n vec2 res = i.xy / i.w;\r\n res.x *= aspect;\r\n return res;\r\n }\r\n `,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CUSTOM_VERTEX_UPDATE_POSITION: `\r\n vec3 grlPositionOffset = grl_offsets;\r\n positionUpdated += grlPositionOffset;\r\n `,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CUSTOM_VERTEX_MAIN_END: `\r\n vec2 grlResolution = grl_resolution_lineWidth.xy;\r\n float grlBaseWidth = grl_resolution_lineWidth.z;\r\n\r\n grlColorPointer = grl_colorPointers;\r\n\r\n vec3 grlPrevious = grl_previousAndSide.xyz;\r\n float grlSide = grl_previousAndSide.w;\r\n\r\n vec3 grlNext = grl_nextAndCounters.xyz;\r\n grlCounters = grl_nextAndCounters.w;\r\n\r\n float grlAspect = grlResolution.x / grlResolution.y;\r\n\r\n mat4 grlMatrix = viewProjection * world;\r\n vec4 grlFinalPosition = grlMatrix * vec4( positionUpdated , 1.0 );\r\n vec4 grlPrevPos = grlMatrix * vec4( grlPrevious + grlPositionOffset, 1.0 );\r\n vec4 grlNextPos = grlMatrix * vec4( grlNext + grlPositionOffset, 1.0 );\r\n\r\n vec2 grlCurrentP = grlFix( grlFinalPosition, grlAspect );\r\n vec2 grlPrevP = grlFix( grlPrevPos, grlAspect );\r\n vec2 grlNextP = grlFix( grlNextPos, grlAspect );\r\n\r\n float grlWidth = grlBaseWidth * grl_widths;\r\n\r\n vec2 grlDir;\r\n if( grlNextP == grlCurrentP ) grlDir = normalize( grlCurrentP - grlPrevP );\r\n else if( grlPrevP == grlCurrentP ) grlDir = normalize( grlNextP - grlCurrentP );\r\n else {\r\n vec2 grlDir1 = normalize( grlCurrentP - grlPrevP );\r\n vec2 grlDir2 = normalize( grlNextP - grlCurrentP );\r\n grlDir = normalize( grlDir1 + grlDir2 );\r\n }\r\n vec4 grlNormal = vec4( -grlDir.y, grlDir.x, 0., 1. );\r\n grlNormal.xy *= .5 * grlWidth;\r\n grlNormal *= grl_projection;\r\n #ifdef GREASED_LINE_SIZE_ATTENUATION\r\n grlNormal.xy *= grlFinalPosition.w;\r\n grlNormal.xy /= ( vec4( grlResolution, 0., 1. ) * grl_projection ).xy;\r\n #endif\r\n grlFinalPosition.xy += grlNormal.xy * grlSide;\r\n gl_Position = grlFinalPosition;\r\n\r\n vPositionW = vec3(grlFinalPosition);\r\n\r\n `,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n \"!gl_Position\\\\=viewProjection\\\\*worldPos;\": \"//\", // remove\n };\n }\n if (shaderType === \"fragment\") {\n return {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CUSTOM_FRAGMENT_DEFINITIONS: `\r\n varying float grlCounters;\r\n varying float grlColorPointer;\r\n uniform sampler2D grl_colors;\r\n `,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CUSTOM_FRAGMENT_MAIN_END: `\r\n float grlColorMode = grl_colorMode_visibility_colorsWidth_useColors.x;\r\n float grlVisibility = grl_colorMode_visibility_colorsWidth_useColors.y;\r\n float grlColorsWidth = grl_colorMode_visibility_colorsWidth_useColors.z;\r\n float grlUseColors = grl_colorMode_visibility_colorsWidth_useColors.w;\r\n\r\n float grlUseDash = grl_dashOptions.x;\r\n float grlDashArray = grl_dashOptions.y;\r\n float grlDashOffset = grl_dashOptions.z;\r\n float grlDashRatio = grl_dashOptions.w;\r\n\r\n gl_FragColor.a *= step(grlCounters, grlVisibility);\r\n if( gl_FragColor.a == 0. ) discard;\r\n\r\n if(grlUseDash == 1.){\r\n gl_FragColor.a *= ceil(mod(grlCounters + grlDashOffset, grlDashArray) - (grlDashArray * grlDashRatio));\r\n if (gl_FragColor.a == 0.) discard;\r\n }\r\n\r\n #ifdef GREASED_LINE_HAS_COLOR\r\n if (grlColorMode == ${GreasedLineMeshColorMode.COLOR_MODE_SET}.) {\r\n gl_FragColor.rgb = grl_singleColor;\r\n } else if (grlColorMode == ${GreasedLineMeshColorMode.COLOR_MODE_ADD}.) {\r\n gl_FragColor.rgb += grl_singleColor;\r\n } else if (grlColorMode == ${GreasedLineMeshColorMode.COLOR_MODE_MULTIPLY}.) {\r\n gl_FragColor.rgb *= grl_singleColor;\r\n }\r\n #else\r\n if (grlUseColors == 1.) {\r\n #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE\r\n vec4 grlColor = texture2D(grl_colors, vec2(grlCounters, 0.), 0.);\r\n #else\r\n vec4 grlColor = texture2D(grl_colors, vec2(grlColorPointer/grlColorsWidth, 0.), 0.);\r\n #endif\r\n if (grlColorMode == ${GreasedLineMeshColorMode.COLOR_MODE_SET}.) {\r\n gl_FragColor = grlColor;\r\n } else if (grlColorMode == ${GreasedLineMeshColorMode.COLOR_MODE_ADD}.) {\r\n gl_FragColor += grlColor;\r\n } else if (grlColorMode == ${GreasedLineMeshColorMode.COLOR_MODE_MULTIPLY}.) {\r\n gl_FragColor *= grlColor;\r\n }\r\n }\r\n #endif\r\n `,\n };\n }\n return null;\n }\n /**\n * Converts boolean to number.\n * @param bool\n * @returns 1 if true, 0 if false.\n */\n static _BooleanToNumber(bool) {\n return bool ? 1 : 0;\n }\n /**\n * Converts an array of Color3 to Uint8Array\n * @param colors Arrray of Color3\n * @returns Uin8Array of colors [r, g, b, a, r, g, b, a, ...]\n */\n static _Color3toRGBAUint8(colors) {\n const colorTable = new Uint8Array(colors.length * 4);\n for (let i = 0, j = 0; i < colors.length; i++) {\n colorTable[j++] = colors[i].r * 255;\n colorTable[j++] = colors[i].g * 255;\n colorTable[j++] = colors[i].b * 255;\n colorTable[j++] = 255;\n }\n return colorTable;\n }\n /**\n * Creates a RawTexture from an RGBA color array and sets it on the plugin material instance.\n * @param name name of the texture\n * @param colors Uint8Array of colors\n */\n _createColorsTexture(name, colors) {\n var _a;\n const colorsArray = GreasedLinePluginMaterial._Color3toRGBAUint8(colors);\n this._colorsTexture = new RawTexture(colorsArray, colors.length, 1, Engine.TEXTUREFORMAT_RGBA, this._scene, false, true, (_a = this._options.colorsSampling) !== null && _a !== void 0 ? _a : RawTexture.NEAREST_NEAREST);\n this._colorsTexture.name = name;\n }\n /**\n * Disposes the plugin material.\n */\n dispose() {\n var _a;\n (_a = this._colorsTexture) === null || _a === void 0 ? void 0 : _a.dispose();\n super.dispose();\n }\n /**\n * Sets whether to use the colors option to colorize the line.\n * @param value true if use the colors, otherwise false\n */\n setUseColors(value) {\n this._options.useColors = value;\n }\n /**\n * Creates or updates the colors texture\n * @param colors color table RGBA\n * @param lazy if lazy, the colors are not updated\n * @param forceUpdate force creation of a new texture\n * @returns\n */\n setColors(colors, lazy = false, forceUpdate = false) {\n var _a, _b, _c, _d;\n if (colors === null || colors.length === 0) {\n (_a = this._colorsTexture) === null || _a === void 0 ? void 0 : _a.dispose();\n return;\n }\n const origColorsCount = (_c = (_b = this._options.colors) === null || _b === void 0 ? void 0 : _b.length) !== null && _c !== void 0 ? _c : 0;\n this._options.colors = colors;\n if (lazy && !forceUpdate) {\n return;\n }\n if (this._colorsTexture && origColorsCount === colors.length && !forceUpdate) {\n const colorArray = GreasedLinePluginMaterial._Color3toRGBAUint8(colors);\n this._colorsTexture.update(colorArray);\n }\n else {\n (_d = this._colorsTexture) === null || _d === void 0 ? void 0 : _d.dispose();\n this._createColorsTexture(`${this._material.name}-colors-texture`, colors);\n }\n }\n /**\n * Updates the material. Use when material created in lazy mode.\n */\n updateLazy() {\n if (this._options.colors) {\n this.setColors(this._options.colors, false, true);\n }\n }\n /**\n * Gets the plugin material options\n * @returns the plugin material options @see GreasedLineMaterialOptions\n */\n getOptions() {\n return this._options;\n }\n /**\n * Sets the line length visibility.\n * 0 - 0% of the line will be visible\n * 1 - 100% of the line will be visible\n * @param value\n */\n setVisibility(value) {\n this._options.visibility = value;\n }\n /**\n * Turns on/off dashmode\n * @param value\n */\n setUseDash(value) {\n this._options.useDash = value;\n }\n /**\n * Sets the dash array.\n * @param value dash array\n */\n setDashCount(value) {\n this._options.dashCount = value;\n this._dashArray = 1 / value;\n }\n /**\n * Sets the dash ratio\n * @param value dash length ratio 0..1 (0.5 = half empty, half drawn)\n */\n setDashRatio(value) {\n this._options.dashRatio = value;\n }\n /**\n * Sets the dash offset\n * @param value the dashes will be offset by this value\n */\n setDashOffset(value) {\n this._options.dashOffset = value;\n }\n /**\n * Sets line base width. At each point the line width is calculated by widths[pointIndex] * width\n * @param value base width\n */\n setWidth(value) {\n this._options.width = value;\n }\n /**\n * Turn on/off attenuation of the width option and widths array.\n * @param value false means 1 unit in width = 1 unit on scene, true means 1 unit in width is reduced on the screen to make better looking lines\n */\n setSizeAttenuation(value) {\n this._options.sizeAttenuation = value;\n this.markAllDefinesAsDirty();\n }\n /**\n * Sets the color of the line. If set the whole line will be mixed with this color according to the colorMode option.\n * @param value color\n */\n setColor(value, doNotMarkDirty = false) {\n if ((this._options.color === undefined && value !== undefined) || (this._options.color !== undefined && value === undefined)) {\n this._options.color = value;\n !doNotMarkDirty && this.markAllDefinesAsDirty();\n }\n else {\n this._options.color = value;\n }\n }\n /**\n * Sets the mixing mode of the color paramater. Default value is GreasedLineMeshColorMode.SET\n * @see GreasedLineMeshColorMode\n * @param value color mode\n */\n setColorMode(value) {\n this._options.colorMode = value;\n }\n /**\n * Serializes this plugin material\n * @returns serializationObjec\n */\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.materialOptions = {};\n DeepCopier.DeepCopy(this._options, serializationObject.materialOptions);\n return serializationObject;\n }\n /**\n * Parses a serialized objects\n * @param source serialized object\n * @param scene scene\n * @param rootUrl root url for textures\n */\n parse(source, scene, rootUrl) {\n var _a;\n super.parse(source, scene, rootUrl);\n this._options = source.materialOptions;\n (_a = this._colorsTexture) === null || _a === void 0 ? void 0 : _a.dispose();\n if (this._options.colors) {\n this._createColorsTexture(`${this._material.name}-colors-texture`, this._options.colors);\n }\n else {\n GreasedLinePluginMaterial._PrepareEmptyColorsTexture(scene);\n }\n this._options.color && this.setColor(this._options.color, true);\n this._options.colorMode && this.setColorMode(this._options.colorMode);\n this._options.useColors && this.setUseColors(this._options.useColors);\n this._options.visibility && this.setVisibility(this._options.visibility);\n this._options.useDash && this.setUseDash(this._options.useDash);\n this._options.dashCount && this.setDashCount(this._options.dashCount);\n this._options.dashRatio && this.setDashRatio(this._options.dashRatio);\n this._options.dashOffset && this.setDashOffset(this._options.dashOffset);\n this._options.width && this.setWidth(this._options.width);\n this._options.sizeAttenuation && this.setSizeAttenuation(this._options.sizeAttenuation);\n this.markAllDefinesAsDirty();\n }\n /**\n * A minimum size texture for the colors sampler2D when there is no colors texture defined yet.\n * For fast switching using the useColors property without the need to use defines.\n * @param scene Scene\n */\n static _PrepareEmptyColorsTexture(scene) {\n if (!this._EmptyColorsTexture) {\n const colorsArray = new Uint8Array(4);\n this._EmptyColorsTexture = new RawTexture(colorsArray, 1, 1, Engine.TEXTUREFORMAT_RGBA, scene, false, false, RawTexture.NEAREST_NEAREST);\n this._EmptyColorsTexture.name = \"grlEmptyColorsTexture\";\n }\n }\n}\n/**\n * Plugin name\n */\nGreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME = \"GreasedLinePluginMaterial\";\nRegisterClass(`BABYLON.${GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME}`, GreasedLinePluginMaterial);\n//# sourceMappingURL=greasedLinePluginMaterial.js.map","import { DecalMapConfiguration } from \"./material.decalMapConfiguration.js\";\nimport { StandardMaterial } from \"./standardMaterial.js\";\nObject.defineProperty(StandardMaterial.prototype, \"decalMap\", {\n get: function () {\n if (!this._decalMap) {\n if (this._uniformBufferLayoutBuilt) {\n // Material already used to display a mesh, so it's invalid to add the decal map plugin at that point\n // Returns null instead of having new DecalMapConfiguration throws an exception\n return null;\n }\n this._decalMap = new DecalMapConfiguration(this);\n }\n return this._decalMap;\n },\n enumerable: true,\n configurable: true,\n});\n//# sourceMappingURL=standardMaterial.decalMap.js.map","import { DecalMapConfiguration } from \"../material.decalMapConfiguration.js\";\nimport { PBRBaseMaterial } from \"./pbrBaseMaterial.js\";\nObject.defineProperty(PBRBaseMaterial.prototype, \"decalMap\", {\n get: function () {\n if (!this._decalMap) {\n if (this._uniformBufferLayoutBuilt) {\n // Material already used to display a mesh, so it's invalid to add the decal map plugin at that point\n // Returns null instead of having new DecalMapConfiguration throws an exception\n return null;\n }\n this._decalMap = new DecalMapConfiguration(this);\n }\n return this._decalMap;\n },\n enumerable: true,\n configurable: true,\n});\n//# sourceMappingURL=pbrMaterial.decalMap.js.map","import { AbstractMesh } from \"../Meshes/abstractMesh.js\";\nObject.defineProperty(AbstractMesh.prototype, \"decalMap\", {\n get: function () {\n return this._decalMap;\n },\n set: function (decalMap) {\n this._decalMap = decalMap;\n },\n enumerable: true,\n configurable: true,\n});\n//# sourceMappingURL=abstractMesh.decalMap.js.map","import \"./standardMaterial.decalMap.js\";\nimport \"./PBR/pbrMaterial.decalMap.js\";\nimport \"../Meshes/abstractMesh.decalMap.js\";\n//# sourceMappingURL=material.decalMap.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./Background/index.js\";\nexport * from \"./colorCurves.js\";\nexport * from \"./iEffectFallbacks.js\";\nexport * from \"./effectFallbacks.js\";\nexport * from \"./effect.js\";\nexport * from \"./fresnelParameters.js\";\nexport * from \"./imageProcessingConfiguration.js\";\nexport * from \"./material.js\";\nexport * from \"./materialDefines.js\";\nexport * from \"./clipPlaneMaterialHelper.js\";\nexport * from \"./materialHelper.js\";\nexport * from \"./multiMaterial.js\";\nexport * from \"./Occlusion/index.js\";\nexport * from \"./PBR/index.js\";\nexport * from \"./pushMaterial.js\";\nexport * from \"./shaderLanguage.js\";\nexport * from \"./shaderMaterial.js\";\nexport * from \"./standardMaterial.js\";\nexport * from \"./Textures/index.js\";\nexport * from \"./uniformBuffer.js\";\nexport * from \"./materialFlags.js\";\nexport * from \"./Node/index.js\";\nexport * from \"./effectRenderer.js\";\nexport * from \"./shadowDepthWrapper.js\";\nexport * from \"./drawWrapper.js\";\nexport * from \"./materialPluginBase.js\";\nexport * from \"./materialPluginManager.js\";\nexport * from \"./materialPluginEvent.js\";\nexport * from \"./material.detailMapConfiguration.js\";\nexport * from \"./material.decalMapConfiguration.js\";\nexport * from \"./materialPluginFactoryExport.js\";\nexport * from \"./greasedLinePluginMaterial.js\";\nimport \"./material.decalMap.js\";\n//# sourceMappingURL=index.js.map","import { Vector2, Vector3 } from \"./math.vector.js\";\n/**\n * Class used to store (r, theta) vector representation\n */\nexport class Polar {\n /**\n * Creates a new Polar object\n * @param radius the radius of the vector\n * @param theta the angle of the vector\n */\n constructor(radius, theta) {\n this.radius = radius;\n this.theta = theta;\n }\n /**\n * Gets the class name\n * @returns the string \"Polar\"\n */\n getClassName() {\n return \"Polar\";\n }\n /**\n * Converts the current polar to a string\n * @returns the current polar as a string\n */\n toString() {\n return JSON.stringify(this);\n }\n /**\n * Converts the current polar to an array\n * @reutrns the current polar as an array\n */\n asArray() {\n return [this.radius, this.theta];\n }\n /**\n * Adds the current Polar and the given Polar and stores the result\n * @param polar the polar to add\n * @param ref the polar to store the result in\n * @returns the updated ref\n */\n addToRef(polar, ref) {\n ref.radius = this.radius + polar.radius;\n ref.theta = this.theta + polar.theta;\n return ref;\n }\n /**\n * Adds the current Polar and the given Polar\n * @param polar the polar to add\n * @returns the sum polar\n */\n add(polar) {\n const ref = new Polar(0, 0);\n this.addToRef(polar, ref);\n return ref;\n }\n /**\n * Adds the given polar to the current polar\n * @param polar the polar to add\n * @returns the current polar\n */\n addInPlace(polar) {\n this.addToRef(polar, this);\n return this;\n }\n /**\n * Adds the provided values to the current polar\n * @param radius the amount to add to the radius\n * @param theta the amount to add to the theta\n * @returns the current polar\n */\n addInPlaceFromFloats(radius, theta) {\n this.radius += radius;\n this.theta += theta;\n return this;\n }\n /**\n * Subtracts the given Polar from the current Polar and stores the result\n * @param polar the polar to subtract\n * @param ref the polar to store the result in\n * @returns the updated ref\n */\n subtractToRef(polar, ref) {\n ref.radius = this.radius - polar.radius;\n ref.theta = this.theta - polar.theta;\n return ref;\n }\n /**\n * Subtracts the given Polar from the current Polar\n * @param polar the polar to subtract\n * @returns the difference polar\n */\n subtract(polar) {\n const ref = new Polar(0, 0);\n this.subtractToRef(polar, ref);\n return ref;\n }\n /**\n * Subtracts the given Polar from the current Polar\n * @param polar the polar to subtract\n * @returns the current polar\n */\n subtractInPlace(polar) {\n this.subtractToRef(polar, this);\n return this;\n }\n /**\n * Subtracts the given floats from the current polar\n * @param radius the amount to subtract from the radius\n * @param theta the amount to subtract from the theta\n * @param ref the polar to store the result in\n * @returns the updated ref\n */\n subtractFromFloatsToRef(radius, theta, ref) {\n ref.radius = this.radius - radius;\n ref.theta = this.theta - theta;\n return ref;\n }\n /**\n * Subtracts the given floats from the current polar\n * @param radius the amount to subtract from the radius\n * @param theta the amount to subtract from the theta\n * @returns the difference polar\n */\n subtractFromFloats(radius, theta) {\n const ref = new Polar(0, 0);\n this.subtractFromFloatsToRef(radius, theta, ref);\n return ref;\n }\n /**\n * Multiplies the given Polar with the current Polar and stores the result\n * @param polar the polar to multiply\n * @param ref the polar to store the result in\n * @returns the updated ref\n */\n multiplyToRef(polar, ref) {\n ref.radius = this.radius * polar.radius;\n ref.theta = this.theta * polar.theta;\n return ref;\n }\n /**\n * Multiplies the given Polar with the current Polar\n * @param polar the polar to multiply\n * @returns the product polar\n */\n multiply(polar) {\n const ref = new Polar(0, 0);\n this.multiplyToRef(polar, ref);\n return ref;\n }\n /**\n * Multiplies the given Polar with the current Polar\n * @param polar the polar to multiply\n * @returns the current polar\n */\n multiplyInPlace(polar) {\n this.multiplyToRef(polar, this);\n return this;\n }\n /**\n * Divides the current Polar by the given Polar and stores the result\n * @param polar the polar to divide\n * @param ref the polar to store the result in\n * @returns the updated ref\n */\n divideToRef(polar, ref) {\n ref.radius = this.radius / polar.radius;\n ref.theta = this.theta / polar.theta;\n return ref;\n }\n /**\n * Divides the current Polar by the given Polar\n * @param polar the polar to divide\n * @returns the quotient polar\n */\n divide(polar) {\n const ref = new Polar(0, 0);\n this.divideToRef(polar, ref);\n return ref;\n }\n /**\n * Divides the current Polar by the given Polar\n * @param polar the polar to divide\n * @returns the current polar\n */\n divideInPlace(polar) {\n this.divideToRef(polar, this);\n return this;\n }\n /**\n * Clones the current polar\n * @returns a clone of the current polar\n */\n clone() {\n return new Polar(this.radius, this.theta);\n }\n /**\n * Copies the source polar into the current polar\n * @param source the polar to copy from\n * @returns the current polar\n */\n copyFrom(source) {\n this.radius = source.radius;\n this.theta = source.theta;\n return this;\n }\n /**\n * Copies the given values into the current polar\n * @param radius the radius to use\n * @param theta the theta to use\n * @returns the current polar\n */\n copyFromFloats(radius, theta) {\n this.radius = radius;\n this.theta = theta;\n return this;\n }\n /**\n * Scales the current polar and stores the result\n * @param scale defines the multiplication factor\n * @param ref where to store the result\n * @returns the updated ref\n */\n scaleToRef(scale, ref) {\n ref.radius = this.radius * scale;\n ref.theta = this.theta * scale;\n return ref;\n }\n /**\n * Scales the current polar and returns a new polar with the scaled coordinates\n * @param scale defines the multiplication factor\n * @returns the scaled polar\n */\n scale(scale) {\n const ref = new Polar(0, 0);\n this.scaleToRef(scale, ref);\n return ref;\n }\n /**\n * Scales the current polar\n * @param scale defines the multiplication factor\n * @returns the current polar\n */\n scaleInPlace(scale) {\n this.scaleToRef(scale, this);\n return this;\n }\n /**\n * Sets the values of the current polar\n * @param radius the new radius\n * @param theta the new theta\n * @returns the current polar\n */\n set(radius, theta) {\n this.radius = radius;\n this.theta = theta;\n return this;\n }\n /**\n * Sets the values of the current polar\n * @param value the new values\n * @returns the current polar\n */\n setAll(value) {\n this.set(value, value);\n return this;\n }\n /**\n * Gets the rectangular coordinates of the current Polar\n * @param ref the reference to assign the result\n * @returns the updated reference\n */\n toVector2ToRef(ref) {\n const x = this.radius * Math.cos(this.theta);\n const y = this.radius * Math.sin(this.theta);\n ref.set(x, y);\n return ref;\n }\n /**\n * Gets the rectangular coordinates of the current Polar\n * @returns the rectangular coordinates\n */\n toVector2() {\n const ref = new Vector2(0, 0);\n return this.toVector2ToRef(ref);\n }\n /**\n * Converts a given Vector2 to its polar coordinates\n * @param v the Vector2 to convert\n * @param ref the reference to assign the result\n * @returns the updated reference\n */\n static FromVector2ToRef(v, ref) {\n const theta = Math.sign(v.y) * Math.acos(v.x / v.length());\n ref.radius = v.length();\n ref.theta = theta;\n return ref;\n }\n /**\n * Converts a given Vector2 to its polar coordinates\n * @param v the Vector2 to convert\n * @returns a Polar\n */\n static FromVector2(v) {\n const polar = new Polar(0, 0);\n Polar.FromVector2ToRef(v, polar);\n return polar;\n }\n /**\n * Converts an array of floats to a polar\n * @param array the array to convert\n * @returns the converted polar\n */\n static FromArray(array) {\n return new Polar(array[0], array[1]);\n }\n}\n/**\n * Class used for (radius, theta, phi) vector representation.\n */\nexport class Spherical {\n /**\n * @param radius spherical radius\n * @param theta angle from positive y axis to radial line from 0 to PI (vertical)\n * @param phi angle from positive x axis measured anticlockwise from -PI to PI (horizontal)\n */\n constructor(radius, theta, phi) {\n this.radius = radius;\n this.theta = theta;\n this.phi = phi;\n }\n /**\n * Gets the class name\n * @returns the string \"Spherical\"\n */\n getClassName() {\n return \"Spherical\";\n }\n /**\n * Converts the current spherical to a string\n * @returns the current spherical as a string\n */\n toString() {\n return JSON.stringify(this);\n }\n /**\n * Converts the current spherical to an array\n * @reutrns the current spherical as an array\n */\n asArray() {\n return [this.radius, this.theta, this.phi];\n }\n /**\n * Adds the current Spherical and the given Spherical and stores the result\n * @param spherical the spherical to add\n * @param ref the spherical to store the result in\n * @returns the updated ref\n */\n addToRef(spherical, ref) {\n ref.radius = this.radius + spherical.radius;\n ref.theta = this.theta + spherical.theta;\n ref.phi = this.phi + spherical.phi;\n return ref;\n }\n /**\n * Adds the current Spherical and the given Spherical\n * @param spherical the spherical to add\n * @returns the sum spherical\n */\n add(spherical) {\n const ref = new Spherical(0, 0, 0);\n this.addToRef(spherical, ref);\n return ref;\n }\n /**\n * Adds the given spherical to the current spherical\n * @param spherical the spherical to add\n * @returns the current spherical\n */\n addInPlace(spherical) {\n this.addToRef(spherical, this);\n return this;\n }\n /**\n * Adds the provided values to the current spherical\n * @param radius the amount to add to the radius\n * @param theta the amount to add to the theta\n * @param phi the amount to add to the phi\n * @returns the current spherical\n */\n addInPlaceFromFloats(radius, theta, phi) {\n this.radius += radius;\n this.theta += theta;\n this.phi += phi;\n return this;\n }\n /**\n * Subtracts the given Spherical from the current Spherical and stores the result\n * @param spherical the spherical to subtract\n * @param ref the spherical to store the result in\n * @returns the updated ref\n */\n subtractToRef(spherical, ref) {\n ref.radius = this.radius - spherical.radius;\n ref.theta = this.theta - spherical.theta;\n ref.phi = this.phi - spherical.phi;\n return ref;\n }\n /**\n * Subtracts the given Spherical from the current Spherical\n * @param spherical the spherical to subtract\n * @returns the difference spherical\n */\n subtract(spherical) {\n const ref = new Spherical(0, 0, 0);\n this.subtractToRef(spherical, ref);\n return ref;\n }\n /**\n * Subtracts the given Spherical from the current Spherical\n * @param spherical the spherical to subtract\n * @returns the current spherical\n */\n subtractInPlace(spherical) {\n this.subtractToRef(spherical, this);\n return this;\n }\n /**\n * Subtracts the given floats from the current spherical\n * @param radius the amount to subtract from the radius\n * @param theta the amount to subtract from the theta\n * @param phi the amount to subtract from the phi\n * @param ref the spherical to store the result in\n * @returns the updated ref\n */\n subtractFromFloatsToRef(radius, theta, phi, ref) {\n ref.radius = this.radius - radius;\n ref.theta = this.theta - theta;\n ref.phi = this.phi - phi;\n return ref;\n }\n /**\n * Subtracts the given floats from the current spherical\n * @param radius the amount to subtract from the radius\n * @param theta the amount to subtract from the theta\n * @param phi the amount to subtract from the phi\n * @returns the difference spherical\n */\n subtractFromFloats(radius, theta, phi) {\n const ref = new Spherical(0, 0, 0);\n this.subtractFromFloatsToRef(radius, theta, phi, ref);\n return ref;\n }\n /**\n * Multiplies the given Spherical with the current Spherical and stores the result\n * @param spherical the spherical to multiply\n * @param ref the spherical to store the result in\n * @returns the updated ref\n */\n multiplyToRef(spherical, ref) {\n ref.radius = this.radius * spherical.radius;\n ref.theta = this.theta * spherical.theta;\n ref.phi = this.phi * spherical.phi;\n return ref;\n }\n /**\n * Multiplies the given Spherical with the current Spherical\n * @param spherical the spherical to multiply\n * @returns the product spherical\n */\n multiply(spherical) {\n const ref = new Spherical(0, 0, 0);\n this.multiplyToRef(spherical, ref);\n return ref;\n }\n /**\n * Multiplies the given Spherical with the current Spherical\n * @param spherical the spherical to multiply\n * @returns the current spherical\n */\n multiplyInPlace(spherical) {\n this.multiplyToRef(spherical, this);\n return this;\n }\n /**\n * Divides the current Spherical by the given Spherical and stores the result\n * @param spherical the spherical to divide\n * @param ref the spherical to store the result in\n * @returns the updated ref\n */\n divideToRef(spherical, ref) {\n ref.radius = this.radius / spherical.radius;\n ref.theta = this.theta / spherical.theta;\n ref.phi = this.phi / spherical.phi;\n return ref;\n }\n /**\n * Divides the current Spherical by the given Spherical\n * @param spherical the spherical to divide\n * @returns the quotient spherical\n */\n divide(spherical) {\n const ref = new Spherical(0, 0, 0);\n this.divideToRef(spherical, ref);\n return ref;\n }\n /**\n * Divides the current Spherical by the given Spherical\n * @param spherical the spherical to divide\n * @returns the current spherical\n */\n divideInPlace(spherical) {\n this.divideToRef(spherical, this);\n return this;\n }\n /**\n * Clones the current spherical\n * @returns a clone of the current spherical\n */\n clone() {\n return new Spherical(this.radius, this.theta, this.phi);\n }\n /**\n * Copies the source spherical into the current spherical\n * @param source the spherical to copy from\n * @returns the current spherical\n */\n copyFrom(source) {\n this.radius = source.radius;\n this.theta = source.theta;\n this.phi = source.phi;\n return this;\n }\n /**\n * Copies the given values into the current spherical\n * @param radius the radius to use\n * @param theta the theta to use\n * @param phi the phi to use\n * @returns the current spherical\n */\n copyFromFloats(radius, theta, phi) {\n this.radius = radius;\n this.theta = theta;\n this.phi = phi;\n return this;\n }\n /**\n * Scales the current spherical and stores the result\n * @param scale defines the multiplication factor\n * @param ref where to store the result\n * @returns the updated ref\n */\n scaleToRef(scale, ref) {\n ref.radius = this.radius * scale;\n ref.theta = this.theta * scale;\n ref.phi = this.phi * scale;\n return ref;\n }\n /**\n * Scales the current spherical and returns a new spherical with the scaled coordinates\n * @param scale defines the multiplication factor\n * @returns the scaled spherical\n */\n scale(scale) {\n const ref = new Spherical(0, 0, 0);\n this.scaleToRef(scale, ref);\n return ref;\n }\n /**\n * Scales the current spherical\n * @param scale defines the multiplication factor\n * @returns the current spherical\n */\n scaleInPlace(scale) {\n this.scaleToRef(scale, this);\n return this;\n }\n /**\n * Sets the values of the current spherical\n * @param radius the new radius\n * @param theta the new theta\n * @param phi the new phi\n * @returns the current spherical\n */\n set(radius, theta, phi) {\n this.radius = radius;\n this.theta = theta;\n this.phi = phi;\n return this;\n }\n /**\n * Sets the values of the current spherical\n * @param value the new values\n * @returns the current spherical\n */\n setAll(value) {\n this.set(value, value, value);\n return this;\n }\n /**\n * Assigns the rectangular coordinates of the current Spherical to a Vector3\n * @param ref the Vector3 to update\n * @returns the updated Vector3\n */\n toVector3ToRef(ref) {\n const x = this.radius * Math.sin(this.theta) * Math.cos(this.phi);\n const y = this.radius * Math.cos(this.theta);\n const z = this.radius * Math.sin(this.theta) * Math.sin(this.phi);\n ref.set(x, y, z);\n return ref;\n }\n /**\n * Gets a Vector3 from the current spherical coordinates\n * @returns the (x, y,z) form of the current Spherical\n */\n toVector3() {\n const ref = new Vector3(0, 0, 0);\n return this.toVector3ToRef(ref);\n }\n /**\n * Assigns the spherical coordinates from a Vector3\n * @param vector the vector to convert\n * @param ref the Spherical to update\n * @returns the updated ref\n */\n static FromVector3ToRef(vector, ref) {\n ref.radius = vector.length();\n ref.theta = Math.acos(vector.y / ref.radius);\n ref.phi = Math.atan2(vector.z, vector.x);\n return ref;\n }\n /**\n * Gets a Spherical from a Vector3\n * @param vector defines the vector in (x, y, z) coordinate space\n * @returns a new Spherical\n */\n static FromVector3(vector) {\n const spherical = new Spherical(0, 0, 0);\n Spherical.FromVector3ToRef(vector, spherical);\n return spherical;\n }\n /**\n * Converts an array of floats to a spherical\n * @param array the array to convert\n * @returns the converted spherical\n */\n static FromArray(array) {\n return new Spherical(array[0], array[1], array[2]);\n }\n}\n//# sourceMappingURL=math.polar.js.map","export * from \"./math.scalar.js\";\nexport * from \"./math.functions.js\";\nexport * from \"./math.polar.js\";\nexport * from \"./math.js\";\nexport * from \"./sphericalPolynomial.js\";\n//# sourceMappingURL=index.js.map","/* eslint-disable @typescript-eslint/naming-convention */\nimport { Tools } from \"../../Misc/tools.js\";\nimport { AutoReleaseWorkerPool } from \"../../Misc/workerPool.js\";\nimport { VertexData } from \"../../Meshes/mesh.vertexData.js\";\nfunction createDecoderAsync(wasmBinary) {\n return new Promise((resolve) => {\n DracoDecoderModule({ wasmBinary: wasmBinary }).then((module) => {\n resolve({ module: module });\n });\n });\n}\nfunction decodeMesh(decoderModule, dataView, attributes, onIndicesData, onAttributeData, dividers) {\n const buffer = new decoderModule.DecoderBuffer();\n buffer.Init(dataView, dataView.byteLength);\n const decoder = new decoderModule.Decoder();\n let geometry;\n let status;\n try {\n const type = decoder.GetEncodedGeometryType(buffer);\n switch (type) {\n case decoderModule.TRIANGULAR_MESH:\n geometry = new decoderModule.Mesh();\n status = decoder.DecodeBufferToMesh(buffer, geometry);\n break;\n case decoderModule.POINT_CLOUD:\n geometry = new decoderModule.PointCloud();\n status = decoder.DecodeBufferToPointCloud(buffer, geometry);\n break;\n default:\n throw new Error(`Invalid geometry type ${type}`);\n }\n if (!status.ok() || !geometry.ptr) {\n throw new Error(status.error_msg());\n }\n if (type === decoderModule.TRIANGULAR_MESH) {\n const numFaces = geometry.num_faces();\n const numIndices = numFaces * 3;\n const byteLength = numIndices * 4;\n const ptr = decoderModule._malloc(byteLength);\n try {\n decoder.GetTrianglesUInt32Array(geometry, byteLength, ptr);\n const indices = new Uint32Array(numIndices);\n indices.set(new Uint32Array(decoderModule.HEAPF32.buffer, ptr, numIndices));\n onIndicesData(indices);\n }\n finally {\n decoderModule._free(ptr);\n }\n }\n const processAttribute = (kind, attribute, divider = 1) => {\n const numComponents = attribute.num_components();\n const numPoints = geometry.num_points();\n const numValues = numPoints * numComponents;\n const byteLength = numValues * Float32Array.BYTES_PER_ELEMENT;\n const ptr = decoderModule._malloc(byteLength);\n try {\n decoder.GetAttributeDataArrayForAllPoints(geometry, attribute, decoderModule.DT_FLOAT32, byteLength, ptr);\n const values = new Float32Array(decoderModule.HEAPF32.buffer, ptr, numValues);\n if (kind === \"color\" && numComponents === 3) {\n const babylonData = new Float32Array(numPoints * 4);\n for (let i = 0, j = 0; i < babylonData.length; i += 4, j += numComponents) {\n babylonData[i + 0] = values[j + 0];\n babylonData[i + 1] = values[j + 1];\n babylonData[i + 2] = values[j + 2];\n babylonData[i + 3] = 1;\n }\n onAttributeData(kind, babylonData);\n }\n else {\n const babylonData = new Float32Array(numValues);\n babylonData.set(new Float32Array(decoderModule.HEAPF32.buffer, ptr, numValues));\n if (divider !== 1) {\n for (let i = 0; i < babylonData.length; i++) {\n babylonData[i] = babylonData[i] / divider;\n }\n }\n onAttributeData(kind, babylonData);\n }\n }\n finally {\n decoderModule._free(ptr);\n }\n };\n if (attributes) {\n for (const kind in attributes) {\n const id = attributes[kind];\n const attribute = decoder.GetAttributeByUniqueId(geometry, id);\n const divider = (dividers && dividers[kind]) || 1;\n processAttribute(kind, attribute, divider);\n }\n }\n else {\n const nativeAttributeTypes = {\n position: \"POSITION\",\n normal: \"NORMAL\",\n color: \"COLOR\",\n uv: \"TEX_COORD\",\n };\n for (const kind in nativeAttributeTypes) {\n const id = decoder.GetAttributeId(geometry, decoderModule[nativeAttributeTypes[kind]]);\n if (id !== -1) {\n const attribute = decoder.GetAttribute(geometry, id);\n processAttribute(kind, attribute);\n }\n }\n }\n }\n finally {\n if (geometry) {\n decoderModule.destroy(geometry);\n }\n decoderModule.destroy(decoder);\n decoderModule.destroy(buffer);\n }\n}\n/**\n * The worker function that gets converted to a blob url to pass into a worker.\n */\nfunction worker() {\n let decoderPromise;\n onmessage = (event) => {\n const data = event.data;\n switch (data.id) {\n case \"init\": {\n const decoder = data.decoder;\n if (decoder.url) {\n importScripts(decoder.url);\n decoderPromise = DracoDecoderModule({ wasmBinary: decoder.wasmBinary });\n }\n postMessage(\"done\");\n break;\n }\n case \"decodeMesh\": {\n if (!decoderPromise) {\n throw new Error(\"Draco decoder module is not available\");\n }\n decoderPromise.then((decoder) => {\n decodeMesh(decoder, data.dataView, data.attributes, (indices) => {\n postMessage({ id: \"indices\", value: indices }, [indices.buffer]);\n }, (kind, data) => {\n postMessage({ id: kind, value: data }, [data.buffer]);\n });\n postMessage(\"done\");\n });\n break;\n }\n }\n };\n}\n/**\n * Draco compression (https://google.github.io/draco/)\n *\n * This class wraps the Draco module.\n *\n * **Encoder**\n *\n * The encoder is not currently implemented.\n *\n * **Decoder**\n *\n * By default, the configuration points to a copy of the Draco decoder files for glTF from the babylon.js preview cdn https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js.\n *\n * To update the configuration, use the following code:\n * ```javascript\n * DracoCompression.Configuration = {\n * decoder: {\n * wasmUrl: \"\",\n * wasmBinaryUrl: \"\",\n * fallbackUrl: \"\",\n * }\n * };\n * ```\n *\n * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support WebAssembly or only support the JavaScript version.\n * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.\n * Use `DracoCompression.DecoderAvailable` to determine if the decoder configuration is available for the current context.\n *\n * To decode Draco compressed data, get the default DracoCompression object and call decodeMeshAsync:\n * ```javascript\n * var vertexData = await DracoCompression.Default.decodeMeshAsync(data);\n * ```\n *\n * @see https://playground.babylonjs.com/#DMZIBD#0\n */\nexport class DracoCompression {\n /**\n * Returns true if the decoder configuration is available.\n */\n static get DecoderAvailable() {\n const decoder = DracoCompression.Configuration.decoder;\n return !!((decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === \"object\") || decoder.fallbackUrl);\n }\n static GetDefaultNumWorkers() {\n if (typeof navigator !== \"object\" || !navigator.hardwareConcurrency) {\n return 1;\n }\n // Use 50% of the available logical processors but capped at 4.\n return Math.min(Math.floor(navigator.hardwareConcurrency * 0.5), 4);\n }\n /**\n * Default instance for the draco compression object.\n */\n static get Default() {\n if (!DracoCompression._Default) {\n DracoCompression._Default = new DracoCompression();\n }\n return DracoCompression._Default;\n }\n /**\n * Constructor\n * @param numWorkers The number of workers for async operations. Specify `0` to disable web workers and run synchronously in the current context.\n */\n constructor(numWorkers = DracoCompression.DefaultNumWorkers) {\n const decoder = DracoCompression.Configuration.decoder;\n const decoderInfo = decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === \"object\"\n ? {\n url: Tools.GetAbsoluteUrl(decoder.wasmUrl),\n wasmBinaryPromise: Tools.LoadFileAsync(Tools.GetAbsoluteUrl(decoder.wasmBinaryUrl)),\n }\n : {\n url: Tools.GetAbsoluteUrl(decoder.fallbackUrl),\n wasmBinaryPromise: Promise.resolve(undefined),\n };\n if (numWorkers && typeof Worker === \"function\" && typeof URL === \"function\") {\n this._workerPoolPromise = decoderInfo.wasmBinaryPromise.then((decoderWasmBinary) => {\n const workerContent = `${decodeMesh}(${worker})()`;\n const workerBlobUrl = URL.createObjectURL(new Blob([workerContent], { type: \"application/javascript\" }));\n return new AutoReleaseWorkerPool(numWorkers, () => {\n return new Promise((resolve, reject) => {\n const worker = new Worker(workerBlobUrl);\n const onError = (error) => {\n worker.removeEventListener(\"error\", onError);\n worker.removeEventListener(\"message\", onMessage);\n reject(error);\n };\n const onMessage = (message) => {\n if (message.data === \"done\") {\n worker.removeEventListener(\"error\", onError);\n worker.removeEventListener(\"message\", onMessage);\n resolve(worker);\n }\n };\n worker.addEventListener(\"error\", onError);\n worker.addEventListener(\"message\", onMessage);\n worker.postMessage({\n id: \"init\",\n decoder: {\n url: decoderInfo.url,\n wasmBinary: decoderWasmBinary,\n },\n });\n });\n });\n });\n }\n else {\n this._decoderModulePromise = decoderInfo.wasmBinaryPromise.then((decoderWasmBinary) => {\n if (!decoderInfo.url) {\n throw new Error(\"Draco decoder module is not available\");\n }\n return Tools.LoadScriptAsync(decoderInfo.url).then(() => {\n return createDecoderAsync(decoderWasmBinary);\n });\n });\n }\n }\n /**\n * Stop all async operations and release resources.\n */\n dispose() {\n if (this._workerPoolPromise) {\n this._workerPoolPromise.then((workerPool) => {\n workerPool.dispose();\n });\n }\n delete this._workerPoolPromise;\n delete this._decoderModulePromise;\n }\n /**\n * Returns a promise that resolves when ready. Call this manually to ensure draco compression is ready before use.\n * @returns a promise that resolves when ready\n */\n whenReadyAsync() {\n if (this._workerPoolPromise) {\n return this._workerPoolPromise.then(() => { });\n }\n if (this._decoderModulePromise) {\n return this._decoderModulePromise.then(() => { });\n }\n return Promise.resolve();\n }\n /**\n * Decode Draco compressed mesh data to vertex data.\n * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data\n * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids\n * @param dividers a list of optional dividers for normalization\n * @returns A promise that resolves with the decoded vertex data\n */\n decodeMeshAsync(data, attributes, dividers) {\n const dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;\n if (this._workerPoolPromise) {\n return this._workerPoolPromise.then((workerPool) => {\n return new Promise((resolve, reject) => {\n workerPool.push((worker, onComplete) => {\n const vertexData = new VertexData();\n const onError = (error) => {\n worker.removeEventListener(\"error\", onError);\n worker.removeEventListener(\"message\", onMessage);\n reject(error);\n onComplete();\n };\n const onMessage = (message) => {\n if (message.data === \"done\") {\n worker.removeEventListener(\"error\", onError);\n worker.removeEventListener(\"message\", onMessage);\n resolve(vertexData);\n onComplete();\n }\n else if (message.data.id === \"indices\") {\n vertexData.indices = message.data.value;\n }\n else {\n // check normalization\n const divider = dividers && dividers[message.data.id] ? dividers[message.data.id] : 1;\n if (divider !== 1) {\n // normalize\n for (let i = 0; i < message.data.value.length; i++) {\n message.data.value[i] = message.data.value[i] / divider;\n }\n }\n vertexData.set(message.data.value, message.data.id);\n }\n };\n worker.addEventListener(\"error\", onError);\n worker.addEventListener(\"message\", onMessage);\n const dataViewCopy = new Uint8Array(dataView.byteLength);\n dataViewCopy.set(new Uint8Array(dataView.buffer, dataView.byteOffset, dataView.byteLength));\n worker.postMessage({ id: \"decodeMesh\", dataView: dataViewCopy, attributes: attributes }, [dataViewCopy.buffer]);\n });\n });\n });\n }\n if (this._decoderModulePromise) {\n return this._decoderModulePromise.then((decoder) => {\n const vertexData = new VertexData();\n decodeMesh(decoder.module, dataView, attributes, (indices) => {\n vertexData.indices = indices;\n }, (kind, data) => {\n vertexData.set(data, kind);\n }, dividers);\n return vertexData;\n });\n }\n throw new Error(\"Draco decoder module is not available\");\n }\n}\n/**\n * The configuration. Defaults to the following urls:\n * - wasmUrl: \"https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js\"\n * - wasmBinaryUrl: \"https://preview.babylonjs.com/draco_decoder_gltf.wasm\"\n * - fallbackUrl: \"https://preview.babylonjs.com/draco_decoder_gltf.js\"\n */\nDracoCompression.Configuration = {\n decoder: {\n wasmUrl: \"https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js\",\n wasmBinaryUrl: \"https://preview.babylonjs.com/draco_decoder_gltf.wasm\",\n fallbackUrl: \"https://preview.babylonjs.com/draco_decoder_gltf.js\",\n },\n};\n/**\n * Default number of workers to create when creating the draco compression object.\n */\nDracoCompression.DefaultNumWorkers = DracoCompression.GetDefaultNumWorkers();\nDracoCompression._Default = null;\n//# sourceMappingURL=dracoCompression.js.map","import { Tools } from \"../../Misc/tools.js\";\n/**\n * Meshopt compression (https://github.com/zeux/meshoptimizer)\n *\n * This class wraps the meshopt library from https://github.com/zeux/meshoptimizer/tree/master/js.\n *\n * **Encoder**\n *\n * The encoder is not currently implemented.\n *\n * **Decoder**\n *\n * By default, the configuration points to a copy of the meshopt files on the Babylon.js preview CDN (e.g. https://preview.babylonjs.com/meshopt_decoder.js).\n *\n * To update the configuration, use the following code:\n * ```javascript\n * MeshoptCompression.Configuration = {\n * decoder: {\n * url: \"\"\n * }\n * };\n * ```\n */\nexport class MeshoptCompression {\n /**\n * Default instance for the meshoptimizer object.\n */\n static get Default() {\n if (!MeshoptCompression._Default) {\n MeshoptCompression._Default = new MeshoptCompression();\n }\n return MeshoptCompression._Default;\n }\n /**\n * Constructor\n */\n constructor() {\n const decoder = MeshoptCompression.Configuration.decoder;\n this._decoderModulePromise = Tools.LoadScriptAsync(Tools.GetAbsoluteUrl(decoder.url)).then(() => {\n // Wait for WebAssembly compilation before resolving promise\n return MeshoptDecoder.ready;\n });\n }\n /**\n * Stop all async operations and release resources.\n */\n dispose() {\n delete this._decoderModulePromise;\n }\n /**\n * Decode meshopt data.\n * @see https://github.com/zeux/meshoptimizer/tree/master/js#decoder\n * @param source The input data.\n * @param count The number of elements.\n * @param stride The stride in bytes.\n * @param mode The compression mode.\n * @param filter The compression filter.\n * @returns a Promise that resolves to the decoded data\n */\n decodeGltfBufferAsync(source, count, stride, mode, filter) {\n return this._decoderModulePromise.then(() => {\n const result = new Uint8Array(count * stride);\n MeshoptDecoder.decodeGltfBuffer(result, count, stride, source, mode, filter);\n return result;\n });\n }\n}\n/**\n * The configuration. Defaults to the following:\n * ```javascript\n * decoder: {\n * url: \"https://preview.babylonjs.com/meshopt_decoder.js\"\n * }\n * ```\n */\nMeshoptCompression.Configuration = {\n decoder: {\n url: \"https://preview.babylonjs.com/meshopt_decoder.js\",\n },\n};\nMeshoptCompression._Default = null;\n//# sourceMappingURL=meshoptCompression.js.map","export * from \"./dracoCompression.js\";\nexport * from \"./meshoptCompression.js\";\n//# sourceMappingURL=index.js.map","import { Quaternion, Matrix, Vector3, Vector2 } from \"../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { SubMesh } from \"../Meshes/subMesh.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\n\n/**\n * Unique ID when we import meshes from Babylon to CSG\n */\nlet currentCSGMeshId = 0;\n/**\n * Represents a vertex of a polygon. Use your own vertex class instead of this\n * one to provide additional features like texture coordinates and vertex\n * colors. Custom vertex classes need to provide a `pos` property and `clone()`,\n * `flip()`, and `interpolate()` methods that behave analogous to the ones\n * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience\n * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`\n * is not used anywhere else.\n * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes\n */\nclass Vertex {\n /**\n * Initializes the vertex\n * @param pos The position of the vertex\n * @param normal The normal of the vertex\n * @param uv The texture coordinate of the vertex\n * @param vertColor The RGBA color of the vertex\n */\n constructor(\n /**\n * The position of the vertex\n */\n pos, \n /**\n * The normal of the vertex\n */\n normal, \n /**\n * The texture coordinate of the vertex\n */\n uv, \n /**\n * The texture coordinate of the vertex\n */\n vertColor) {\n this.pos = pos;\n this.normal = normal;\n this.uv = uv;\n this.vertColor = vertColor;\n }\n /**\n * Make a clone, or deep copy, of the vertex\n * @returns A new Vertex\n */\n clone() {\n var _a, _b;\n return new Vertex(this.pos.clone(), this.normal.clone(), (_a = this.uv) === null || _a === void 0 ? void 0 : _a.clone(), (_b = this.vertColor) === null || _b === void 0 ? void 0 : _b.clone());\n }\n /**\n * Invert all orientation-specific data (e.g. vertex normal). Called when the\n * orientation of a polygon is flipped.\n */\n flip() {\n this.normal = this.normal.scale(-1);\n }\n /**\n * Create a new vertex between this vertex and `other` by linearly\n * interpolating all properties using a parameter of `t`. Subclasses should\n * override this to interpolate additional properties.\n * @param other the vertex to interpolate against\n * @param t The factor used to linearly interpolate between the vertices\n */\n interpolate(other, t) {\n return new Vertex(Vector3.Lerp(this.pos, other.pos, t), Vector3.Lerp(this.normal, other.normal, t), this.uv && other.uv ? Vector2.Lerp(this.uv, other.uv, t) : undefined, this.vertColor && other.vertColor ? Color4.Lerp(this.vertColor, other.vertColor, t) : undefined);\n }\n}\n/**\n * Represents a plane in 3D space.\n */\nclass Plane {\n /**\n * Initializes the plane\n * @param normal The normal for the plane\n * @param w\n */\n constructor(normal, w) {\n this.normal = normal;\n this.w = w;\n }\n /**\n * Construct a plane from three points\n * @param a Point a\n * @param b Point b\n * @param c Point c\n */\n static FromPoints(a, b, c) {\n const v0 = c.subtract(a);\n const v1 = b.subtract(a);\n if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {\n return null;\n }\n const n = Vector3.Normalize(Vector3.Cross(v0, v1));\n return new Plane(n, Vector3.Dot(n, a));\n }\n /**\n * Clone, or make a deep copy of the plane\n * @returns a new Plane\n */\n clone() {\n return new Plane(this.normal.clone(), this.w);\n }\n /**\n * Flip the face of the plane\n */\n flip() {\n this.normal.scaleInPlace(-1);\n this.w = -this.w;\n }\n /**\n * Split `polygon` by this plane if needed, then put the polygon or polygon\n * fragments in the appropriate lists. Coplanar polygons go into either\n `* coplanarFront` or `coplanarBack` depending on their orientation with\n * respect to this plane. Polygons in front or in back of this plane go into\n * either `front` or `back`\n * @param polygon The polygon to be split\n * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane\n * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane\n * @param front Will contain the polygons in front of the plane\n * @param back Will contain the polygons begind the plane\n */\n splitPolygon(polygon, coplanarFront, coplanarBack, front, back) {\n const COPLANAR = 0;\n const FRONT = 1;\n const BACK = 2;\n const SPANNING = 3;\n // Classify each point as well as the entire polygon into one of the above\n // four classes.\n let polygonType = 0;\n const types = [];\n let i;\n let t;\n for (i = 0; i < polygon.vertices.length; i++) {\n t = Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;\n const type = t < -Plane.EPSILON ? BACK : t > Plane.EPSILON ? FRONT : COPLANAR;\n polygonType |= type;\n types.push(type);\n }\n // Put the polygon in the correct list, splitting it when necessary\n switch (polygonType) {\n case COPLANAR:\n (Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);\n break;\n case FRONT:\n front.push(polygon);\n break;\n case BACK:\n back.push(polygon);\n break;\n case SPANNING: {\n const f = [], b = [];\n for (i = 0; i < polygon.vertices.length; i++) {\n const j = (i + 1) % polygon.vertices.length;\n const ti = types[i], tj = types[j];\n const vi = polygon.vertices[i], vj = polygon.vertices[j];\n if (ti !== BACK) {\n f.push(vi);\n }\n if (ti !== FRONT) {\n b.push(ti !== BACK ? vi.clone() : vi);\n }\n if ((ti | tj) === SPANNING) {\n t = (this.w - Vector3.Dot(this.normal, vi.pos)) / Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));\n const v = vi.interpolate(vj, t);\n f.push(v);\n b.push(v.clone());\n }\n }\n let poly;\n if (f.length >= 3) {\n poly = new Polygon(f, polygon.shared);\n if (poly.plane) {\n front.push(poly);\n }\n }\n if (b.length >= 3) {\n poly = new Polygon(b, polygon.shared);\n if (poly.plane) {\n back.push(poly);\n }\n }\n break;\n }\n }\n }\n}\n/**\n * `CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a\n * point is on the plane\n */\nPlane.EPSILON = 1e-5;\n/**\n * Represents a convex polygon. The vertices used to initialize a polygon must\n * be coplanar and form a convex loop.\n *\n * Each convex polygon has a `shared` property, which is shared between all\n * polygons that are clones of each other or were split from the same polygon.\n * This can be used to define per-polygon properties (such as surface color)\n */\nclass Polygon {\n /**\n * Initializes the polygon\n * @param vertices The vertices of the polygon\n * @param shared The properties shared across all polygons\n */\n constructor(vertices, shared) {\n this.vertices = vertices;\n this.shared = shared;\n this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);\n }\n /**\n * Clones, or makes a deep copy, or the polygon\n */\n clone() {\n const vertices = this.vertices.map((v) => v.clone());\n return new Polygon(vertices, this.shared);\n }\n /**\n * Flips the faces of the polygon\n */\n flip() {\n this.vertices.reverse().map((v) => {\n v.flip();\n });\n this.plane.flip();\n }\n}\n/**\n * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons\n * by picking a polygon to split along. That polygon (and all other coplanar\n * polygons) are added directly to that node and the other polygons are added to\n * the front and/or back subtrees. This is not a leafy BSP tree since there is\n * no distinction between internal and leaf nodes\n */\nclass Node {\n /**\n * Initializes the node\n * @param polygons A collection of polygons held in the node\n */\n constructor(polygons) {\n this._plane = null;\n this._front = null;\n this._back = null;\n this._polygons = new Array();\n if (polygons) {\n this.build(polygons);\n }\n }\n /**\n * Clones, or makes a deep copy, of the node\n * @returns The cloned node\n */\n clone() {\n const node = new Node();\n node._plane = this._plane && this._plane.clone();\n node._front = this._front && this._front.clone();\n node._back = this._back && this._back.clone();\n node._polygons = this._polygons.map((p) => p.clone());\n return node;\n }\n /**\n * Convert solid space to empty space and empty space to solid space\n */\n invert() {\n for (let i = 0; i < this._polygons.length; i++) {\n this._polygons[i].flip();\n }\n if (this._plane) {\n this._plane.flip();\n }\n if (this._front) {\n this._front.invert();\n }\n if (this._back) {\n this._back.invert();\n }\n const temp = this._front;\n this._front = this._back;\n this._back = temp;\n }\n /**\n * Recursively remove all polygons in `polygons` that are inside this BSP\n * tree.\n * @param polygons Polygons to remove from the BSP\n * @returns Polygons clipped from the BSP\n */\n clipPolygons(polygons) {\n if (!this._plane) {\n return polygons.slice();\n }\n let front = new Array(), back = new Array();\n for (let i = 0; i < polygons.length; i++) {\n this._plane.splitPolygon(polygons[i], front, back, front, back);\n }\n if (this._front) {\n front = this._front.clipPolygons(front);\n }\n if (this._back) {\n back = this._back.clipPolygons(back);\n }\n else {\n back = [];\n }\n return front.concat(back);\n }\n /**\n * Remove all polygons in this BSP tree that are inside the other BSP tree\n * `bsp`.\n * @param bsp BSP containing polygons to remove from this BSP\n */\n clipTo(bsp) {\n this._polygons = bsp.clipPolygons(this._polygons);\n if (this._front) {\n this._front.clipTo(bsp);\n }\n if (this._back) {\n this._back.clipTo(bsp);\n }\n }\n /**\n * Return a list of all polygons in this BSP tree\n * @returns List of all polygons in this BSP tree\n */\n allPolygons() {\n let polygons = this._polygons.slice();\n if (this._front) {\n polygons = polygons.concat(this._front.allPolygons());\n }\n if (this._back) {\n polygons = polygons.concat(this._back.allPolygons());\n }\n return polygons;\n }\n /**\n * Build a BSP tree out of `polygons`. When called on an existing tree, the\n * new polygons are filtered down to the bottom of the tree and become new\n * nodes there. Each set of polygons is partitioned using the first polygon\n * (no heuristic is used to pick a good split)\n * @param polygons Polygons used to construct the BSP tree\n */\n build(polygons) {\n if (!polygons.length) {\n return;\n }\n if (!this._plane) {\n this._plane = polygons[0].plane.clone();\n }\n const front = new Array(), back = new Array();\n for (let i = 0; i < polygons.length; i++) {\n this._plane.splitPolygon(polygons[i], this._polygons, this._polygons, front, back);\n }\n if (front.length) {\n if (!this._front) {\n this._front = new Node();\n }\n this._front.build(front);\n }\n if (back.length) {\n if (!this._back) {\n this._back = new Node();\n }\n this._back.build(back);\n }\n }\n}\n/**\n * Class for building Constructive Solid Geometry\n */\nexport class CSG {\n constructor() {\n this._polygons = new Array();\n }\n /**\n * Convert the Mesh to CSG\n * @param mesh The Mesh to convert to CSG\n * @param absolute If true, the final (local) matrix transformation is set to the identity and not to that of `mesh`. It can help when dealing with right-handed meshes (default: false)\n * @returns A new CSG from the Mesh\n */\n static FromMesh(mesh, absolute = false) {\n let vertex, normal, uv = undefined, position, vertColor = undefined, polygon, vertices;\n const polygons = new Array();\n let matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;\n let invertWinding = false;\n if (mesh instanceof Mesh) {\n mesh.computeWorldMatrix(true);\n matrix = mesh.getWorldMatrix();\n meshPosition = mesh.position.clone();\n meshRotation = mesh.rotation.clone();\n if (mesh.rotationQuaternion) {\n meshRotationQuaternion = mesh.rotationQuaternion.clone();\n }\n meshScaling = mesh.scaling.clone();\n if (mesh.material && absolute) {\n invertWinding = mesh.material.sideOrientation === 0;\n }\n }\n else {\n throw \"BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh\";\n }\n const indices = mesh.getIndices(), positions = mesh.getVerticesData(VertexBuffer.PositionKind), normals = mesh.getVerticesData(VertexBuffer.NormalKind), uvs = mesh.getVerticesData(VertexBuffer.UVKind), vertColors = mesh.getVerticesData(VertexBuffer.ColorKind);\n const subMeshes = mesh.subMeshes;\n for (let sm = 0, sml = subMeshes.length; sm < sml; sm++) {\n for (let i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {\n vertices = [];\n for (let j = 0; j < 3; j++) {\n const indexIndices = j === 0 ? i + j : invertWinding ? i + 3 - j : i + j;\n const sourceNormal = new Vector3(normals[indices[indexIndices] * 3], normals[indices[indexIndices] * 3 + 1], normals[indices[indexIndices] * 3 + 2]);\n if (uvs) {\n uv = new Vector2(uvs[indices[indexIndices] * 2], uvs[indices[indexIndices] * 2 + 1]);\n }\n if (vertColors) {\n vertColor = new Color4(vertColors[indices[indexIndices] * 4], vertColors[indices[indexIndices] * 4 + 1], vertColors[indices[indexIndices] * 4 + 2], vertColors[indices[indexIndices] * 4 + 3]);\n }\n const sourcePosition = new Vector3(positions[indices[indexIndices] * 3], positions[indices[indexIndices] * 3 + 1], positions[indices[indexIndices] * 3 + 2]);\n position = Vector3.TransformCoordinates(sourcePosition, matrix);\n normal = Vector3.TransformNormal(sourceNormal, matrix);\n vertex = new Vertex(position, normal, uv, vertColor);\n vertices.push(vertex);\n }\n polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });\n // To handle the case of degenerated triangle\n // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated\n if (polygon.plane) {\n polygons.push(polygon);\n }\n }\n }\n const csg = CSG._FromPolygons(polygons);\n csg.matrix = absolute ? Matrix.Identity() : matrix;\n csg.position = absolute ? Vector3.Zero() : meshPosition;\n csg.rotation = absolute ? Vector3.Zero() : meshRotation;\n csg.scaling = absolute ? Vector3.One() : meshScaling;\n csg.rotationQuaternion = absolute && meshRotationQuaternion ? Quaternion.Identity() : meshRotationQuaternion;\n currentCSGMeshId++;\n return csg;\n }\n /**\n * Construct a CSG solid from a list of `CSG.Polygon` instances.\n * @param polygons Polygons used to construct a CSG solid\n */\n static _FromPolygons(polygons) {\n const csg = new CSG();\n csg._polygons = polygons;\n return csg;\n }\n /**\n * Clones, or makes a deep copy, of the CSG\n * @returns A new CSG\n */\n clone() {\n const csg = new CSG();\n csg._polygons = this._polygons.map((p) => p.clone());\n csg.copyTransformAttributes(this);\n return csg;\n }\n /**\n * Unions this CSG with another CSG\n * @param csg The CSG to union against this CSG\n * @returns The unioned CSG\n */\n union(csg) {\n const a = new Node(this.clone()._polygons);\n const b = new Node(csg.clone()._polygons);\n a.clipTo(b);\n b.clipTo(a);\n b.invert();\n b.clipTo(a);\n b.invert();\n a.build(b.allPolygons());\n return CSG._FromPolygons(a.allPolygons()).copyTransformAttributes(this);\n }\n /**\n * Unions this CSG with another CSG in place\n * @param csg The CSG to union against this CSG\n */\n unionInPlace(csg) {\n const a = new Node(this._polygons);\n const b = new Node(csg._polygons);\n a.clipTo(b);\n b.clipTo(a);\n b.invert();\n b.clipTo(a);\n b.invert();\n a.build(b.allPolygons());\n this._polygons = a.allPolygons();\n }\n /**\n * Subtracts this CSG with another CSG\n * @param csg The CSG to subtract against this CSG\n * @returns A new CSG\n */\n subtract(csg) {\n const a = new Node(this.clone()._polygons);\n const b = new Node(csg.clone()._polygons);\n a.invert();\n a.clipTo(b);\n b.clipTo(a);\n b.invert();\n b.clipTo(a);\n b.invert();\n a.build(b.allPolygons());\n a.invert();\n return CSG._FromPolygons(a.allPolygons()).copyTransformAttributes(this);\n }\n /**\n * Subtracts this CSG with another CSG in place\n * @param csg The CSG to subtract against this CSG\n */\n subtractInPlace(csg) {\n const a = new Node(this._polygons);\n const b = new Node(csg._polygons);\n a.invert();\n a.clipTo(b);\n b.clipTo(a);\n b.invert();\n b.clipTo(a);\n b.invert();\n a.build(b.allPolygons());\n a.invert();\n this._polygons = a.allPolygons();\n }\n /**\n * Intersect this CSG with another CSG\n * @param csg The CSG to intersect against this CSG\n * @returns A new CSG\n */\n intersect(csg) {\n const a = new Node(this.clone()._polygons);\n const b = new Node(csg.clone()._polygons);\n a.invert();\n b.clipTo(a);\n b.invert();\n a.clipTo(b);\n b.clipTo(a);\n a.build(b.allPolygons());\n a.invert();\n return CSG._FromPolygons(a.allPolygons()).copyTransformAttributes(this);\n }\n /**\n * Intersects this CSG with another CSG in place\n * @param csg The CSG to intersect against this CSG\n */\n intersectInPlace(csg) {\n const a = new Node(this._polygons);\n const b = new Node(csg._polygons);\n a.invert();\n b.clipTo(a);\n b.invert();\n a.clipTo(b);\n b.clipTo(a);\n a.build(b.allPolygons());\n a.invert();\n this._polygons = a.allPolygons();\n }\n /**\n * Return a new CSG solid with solid and empty space switched. This solid is\n * not modified.\n * @returns A new CSG solid with solid and empty space switched\n */\n inverse() {\n const csg = this.clone();\n csg.inverseInPlace();\n return csg;\n }\n /**\n * Inverses the CSG in place\n */\n inverseInPlace() {\n this._polygons.map((p) => {\n p.flip();\n });\n }\n /**\n * This is used to keep meshes transformations so they can be restored\n * when we build back a Babylon Mesh\n * NB : All CSG operations are performed in world coordinates\n * @param csg The CSG to copy the transform attributes from\n * @returns This CSG\n */\n copyTransformAttributes(csg) {\n this.matrix = csg.matrix;\n this.position = csg.position;\n this.rotation = csg.rotation;\n this.scaling = csg.scaling;\n this.rotationQuaternion = csg.rotationQuaternion;\n return this;\n }\n /**\n * Build Raw mesh from CSG\n * Coordinates here are in world space\n * @param name The name of the mesh geometry\n * @param scene The Scene\n * @param keepSubMeshes Specifies if the submeshes should be kept\n * @returns A new Mesh\n */\n buildMeshGeometry(name, scene, keepSubMeshes) {\n const matrix = this.matrix.clone();\n matrix.invert();\n const mesh = new Mesh(name, scene);\n const vertices = [];\n const indices = [];\n const normals = [];\n let uvs = null;\n let vertColors = null;\n const vertex = Vector3.Zero();\n const normal = Vector3.Zero();\n const uv = Vector2.Zero();\n const vertColor = new Color4(0, 0, 0, 0);\n const polygons = this._polygons;\n const polygonIndices = [0, 0, 0];\n let polygon;\n const vertice_dict = {};\n let vertex_idx;\n let currentIndex = 0;\n const subMeshDict = {};\n let subMeshObj;\n if (keepSubMeshes) {\n // Sort Polygons, since subMeshes are indices range\n polygons.sort((a, b) => {\n if (a.shared.meshId === b.shared.meshId) {\n return a.shared.subMeshId - b.shared.subMeshId;\n }\n else {\n return a.shared.meshId - b.shared.meshId;\n }\n });\n }\n for (let i = 0, il = polygons.length; i < il; i++) {\n polygon = polygons[i];\n // Building SubMeshes\n if (!subMeshDict[polygon.shared.meshId]) {\n subMeshDict[polygon.shared.meshId] = {};\n }\n if (!subMeshDict[polygon.shared.meshId][polygon.shared.subMeshId]) {\n subMeshDict[polygon.shared.meshId][polygon.shared.subMeshId] = {\n indexStart: +Infinity,\n indexEnd: -Infinity,\n materialIndex: polygon.shared.materialIndex,\n };\n }\n subMeshObj = subMeshDict[polygon.shared.meshId][polygon.shared.subMeshId];\n for (let j = 2, jl = polygon.vertices.length; j < jl; j++) {\n polygonIndices[0] = 0;\n polygonIndices[1] = j - 1;\n polygonIndices[2] = j;\n for (let k = 0; k < 3; k++) {\n vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);\n normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);\n if (polygon.vertices[polygonIndices[k]].uv) {\n if (!uvs) {\n uvs = [];\n }\n uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);\n }\n if (polygon.vertices[polygonIndices[k]].vertColor) {\n if (!vertColors) {\n vertColors = [];\n }\n vertColor.copyFrom(polygon.vertices[polygonIndices[k]].vertColor);\n }\n const localVertex = Vector3.TransformCoordinates(vertex, matrix);\n const localNormal = Vector3.TransformNormal(normal, matrix);\n vertex_idx = vertice_dict[localVertex.x + \",\" + localVertex.y + \",\" + localVertex.z];\n let areUvsDifferent = false;\n if (uvs && !(uvs[vertex_idx * 2] === uv.x || uvs[vertex_idx * 2 + 1] === uv.y)) {\n areUvsDifferent = true;\n }\n let areColorsDifferent = false;\n if (vertColors &&\n !(vertColors[vertex_idx * 4] === vertColor.r ||\n vertColors[vertex_idx * 4 + 1] === vertColor.g ||\n vertColors[vertex_idx * 4 + 2] === vertColor.b ||\n vertColors[vertex_idx * 4 + 3] === vertColor.a)) {\n areColorsDifferent = true;\n }\n // Check if 2 points can be merged\n if (!(typeof vertex_idx !== \"undefined\" &&\n normals[vertex_idx * 3] === localNormal.x &&\n normals[vertex_idx * 3 + 1] === localNormal.y &&\n normals[vertex_idx * 3 + 2] === localNormal.z) ||\n areUvsDifferent ||\n areColorsDifferent) {\n vertices.push(localVertex.x, localVertex.y, localVertex.z);\n if (uvs) {\n uvs.push(uv.x, uv.y);\n }\n normals.push(normal.x, normal.y, normal.z);\n if (vertColors) {\n vertColors.push(vertColor.r, vertColor.g, vertColor.b, vertColor.a);\n }\n vertex_idx = vertice_dict[localVertex.x + \",\" + localVertex.y + \",\" + localVertex.z] = vertices.length / 3 - 1;\n }\n indices.push(vertex_idx);\n subMeshObj.indexStart = Math.min(currentIndex, subMeshObj.indexStart);\n subMeshObj.indexEnd = Math.max(currentIndex, subMeshObj.indexEnd);\n currentIndex++;\n }\n }\n }\n mesh.setVerticesData(VertexBuffer.PositionKind, vertices);\n mesh.setVerticesData(VertexBuffer.NormalKind, normals);\n if (uvs) {\n mesh.setVerticesData(VertexBuffer.UVKind, uvs);\n }\n if (vertColors) {\n mesh.setVerticesData(VertexBuffer.ColorKind, vertColors);\n }\n mesh.setIndices(indices, null);\n if (keepSubMeshes) {\n // We offset the materialIndex by the previous number of materials in the CSG mixed meshes\n let materialIndexOffset = 0, materialMaxIndex;\n mesh.subMeshes = new Array();\n for (const m in subMeshDict) {\n materialMaxIndex = -1;\n for (const sm in subMeshDict[m]) {\n subMeshObj = subMeshDict[m][sm];\n SubMesh.CreateFromIndices(subMeshObj.materialIndex + materialIndexOffset, subMeshObj.indexStart, subMeshObj.indexEnd - subMeshObj.indexStart + 1, mesh);\n materialMaxIndex = Math.max(subMeshObj.materialIndex, materialMaxIndex);\n }\n materialIndexOffset += ++materialMaxIndex;\n }\n }\n return mesh;\n }\n /**\n * Build Mesh from CSG taking material and transforms into account\n * @param name The name of the Mesh\n * @param material The material of the Mesh\n * @param scene The Scene\n * @param keepSubMeshes Specifies if submeshes should be kept\n * @returns The new Mesh\n */\n toMesh(name, material = null, scene, keepSubMeshes) {\n const mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);\n mesh.material = material;\n mesh.position.copyFrom(this.position);\n mesh.rotation.copyFrom(this.rotation);\n if (this.rotationQuaternion) {\n mesh.rotationQuaternion = this.rotationQuaternion.clone();\n }\n mesh.scaling.copyFrom(this.scaling);\n mesh.computeWorldMatrix(true);\n return mesh;\n }\n}\n//# sourceMappingURL=csg.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/bonesDeclaration.js\";\nimport \"./ShadersInclude/bakedVertexAnimationDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexGlobalDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexDeclaration.js\";\nimport \"./ShadersInclude/instancesDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexGlobal.js\";\nimport \"./ShadersInclude/morphTargetsVertex.js\";\nimport \"./ShadersInclude/instancesVertex.js\";\nimport \"./ShadersInclude/bonesVertex.js\";\nimport \"./ShadersInclude/bakedVertexAnimation.js\";\nconst name = \"meshUVSpaceRendererVertexShader\";\nconst shader = `precision highp float;\rattribute vec3 position;\rattribute vec3 normal;\rattribute vec2 uv;\runiform mat4 projMatrix;\rvarying vec2 vDecalTC;\r#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nvoid main(void) {\rvec3 positionUpdated=position;\rvec3 normalUpdated=normal;\r#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\rmat3 normWorldSM=mat3(finalWorld);\rvec3 vNormalW;\r#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));\rvNormalW=normalize(normWorldSM*vNormalW);\r#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\r#endif\nvNormalW=normalize(normWorldSM*normalUpdated);\r#endif\nvec3 normalView=normalize((projMatrix*vec4(vNormalW,0.0)).xyz);\rvec3 decalTC=(projMatrix*worldPos).xyz;\rvDecalTC=decalTC.xy;\rgl_Position=vec4(uv*2.0-1.0,normalView.z>0.0 ? 2. : decalTC.z,1.0);\r}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const meshUVSpaceRendererVertexShader = { name, shader };\n//# sourceMappingURL=meshUVSpaceRenderer.vertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"meshUVSpaceRendererPixelShader\";\nconst shader = `precision highp float;\rvarying vec2 vDecalTC;\runiform sampler2D textureSampler;\rvoid main(void) {\rif (vDecalTC.x<0. || vDecalTC.x>1. || vDecalTC.y<0. || vDecalTC.y>1.) {\rdiscard;\r}\rgl_FragColor=texture2D(textureSampler,vDecalTC);\r}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const meshUVSpaceRendererPixelShader = { name, shader };\n//# sourceMappingURL=meshUVSpaceRenderer.fragment.js.map","import { Matrix } from \"../Maths/math.vector.js\";\n\nimport { ShaderMaterial } from \"../Materials/shaderMaterial.js\";\nimport { RenderTargetTexture } from \"../Materials/Textures/renderTargetTexture.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport \"../Shaders/meshUVSpaceRenderer.vertex.js\";\nimport \"../Shaders/meshUVSpaceRenderer.fragment.js\";\n/**\n * Class used to render in the mesh UV space\n * @since 5.49.1\n */\nexport class MeshUVSpaceRenderer {\n static _GetShader(scene) {\n if (!scene._meshUVSpaceRendererShader) {\n const shader = new ShaderMaterial(\"meshUVSpaceRendererShader\", scene, {\n vertex: \"meshUVSpaceRenderer\",\n fragment: \"meshUVSpaceRenderer\",\n }, {\n attributes: [\"position\", \"normal\", \"uv\"],\n uniforms: [\"world\", \"projMatrix\"],\n samplers: [\"textureSampler\"],\n needAlphaBlending: true,\n });\n shader.backFaceCulling = false;\n shader.alphaMode = 2;\n scene.onDisposeObservable.add(() => {\n var _a;\n (_a = scene._meshUVSpaceRendererShader) === null || _a === void 0 ? void 0 : _a.dispose();\n scene._meshUVSpaceRendererShader = null;\n });\n scene._meshUVSpaceRendererShader = shader;\n }\n return scene._meshUVSpaceRendererShader;\n }\n static _IsRenderTargetTexture(texture) {\n return texture.renderList !== undefined;\n }\n /**\n * Creates a new MeshUVSpaceRenderer\n * @param mesh The mesh used for the source UV space\n * @param scene The scene the mesh belongs to\n * @param options The options to use when creating the texture\n */\n constructor(mesh, scene, options) {\n this._textureCreatedInternally = false;\n /**\n * Clear color of the texture\n */\n this.clearColor = new Color4(0, 0, 0, 0);\n this._mesh = mesh;\n this._scene = scene;\n this._options = Object.assign({ width: 1024, height: 1024, textureType: 0, generateMipMaps: true, optimizeUVAllocation: true }, options);\n }\n /**\n * Checks if the texture is ready to be used\n * @returns true if the texture is ready to be used\n */\n isReady() {\n if (!this.texture) {\n this._createDiffuseRTT();\n }\n return MeshUVSpaceRenderer._IsRenderTargetTexture(this.texture) ? this.texture.isReadyForRendering() : this.texture.isReady();\n }\n /**\n * Projects and renders a texture in the mesh UV space\n * @param texture The texture\n * @param position The position of the center of projection (world space coordinates)\n * @param normal The direction of the projection (world space coordinates)\n * @param size The size of the projection\n * @param angle The rotation angle around the direction of the projection\n */\n renderTexture(texture, position, normal, size, angle = 0) {\n if (!this.texture) {\n this._createDiffuseRTT();\n }\n if (MeshUVSpaceRenderer._IsRenderTargetTexture(this.texture)) {\n const matrix = this._createProjectionMatrix(position, normal, size, angle);\n const shader = MeshUVSpaceRenderer._GetShader(this._scene);\n shader.setTexture(\"textureSampler\", texture);\n shader.setMatrix(\"projMatrix\", matrix);\n this.texture.render();\n }\n }\n /**\n * Clears the texture map\n */\n clear() {\n if (MeshUVSpaceRenderer._IsRenderTargetTexture(this.texture) && this.texture.renderTarget) {\n const engine = this._scene.getEngine();\n engine.bindFramebuffer(this.texture.renderTarget);\n engine.clear(this.clearColor, true, true, true);\n engine.unBindFramebuffer(this.texture.renderTarget);\n }\n }\n /**\n * Disposes of the ressources\n */\n dispose() {\n if (this._textureCreatedInternally) {\n this.texture.dispose();\n this._textureCreatedInternally = false;\n }\n }\n _createDiffuseRTT() {\n this._textureCreatedInternally = true;\n const texture = this._createRenderTargetTexture(this._options.width, this._options.height);\n texture.setMaterialForRendering(this._mesh, MeshUVSpaceRenderer._GetShader(this._scene));\n this.texture = texture;\n }\n _createRenderTargetTexture(width, height) {\n const rtt = new RenderTargetTexture(this._mesh.name + \"_uvspaceTexture\", { width, height }, this._scene, this._options.generateMipMaps, true, this._options.textureType, false, this._options.generateMipMaps ? 3 : 2, false, false, false, 5);\n rtt.optimizeUVAllocation = !!this._options.optimizeUVAllocation;\n rtt.onClearObservable.addOnce(() => {\n this._scene.getEngine().clear(this.clearColor, true, true, true);\n rtt.onClearObservable.add(() => { }); // this disables clearing the texture for the next frames\n });\n rtt.renderList = [this._mesh];\n return rtt;\n }\n _createProjectionMatrix(position, normal, size, angle = 0) {\n const yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;\n const len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);\n const pitch = Math.atan2(normal.y, len);\n const p = position.add(normal.scale(size.z * 0.5));\n const projWorldMatrix = Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(Matrix.Translation(p.x, p.y, p.z));\n const inverseProjWorldMatrix = Matrix.Invert(projWorldMatrix);\n const projMatrix = Matrix.FromArray([2 / size.x, 0, 0, 0, 0, 2 / size.y, 0, 0, 0, 0, 1 / size.z, 0, 0, 0, 0, 1]);\n const screenMatrix = Matrix.FromArray([0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 1, 0, 0.5, 0.5, 0.0, 1]);\n return inverseProjWorldMatrix.multiply(projMatrix).multiply(screenMatrix);\n }\n}\n//# sourceMappingURL=meshUVSpaceRenderer.js.map","import { AbstractMesh } from \"../Meshes/abstractMesh.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { VertexData } from \"../Meshes/mesh.vertexData.js\";\n/**\n * Class used to create a trail following a mesh\n */\nexport class TrailMesh extends Mesh {\n /**\n * Creates a new TrailMesh.\n * @param name The value used by scene.getMeshByName() to do a lookup.\n * @param generator The mesh or transform node to generate a trail.\n * @param scene The scene to add this mesh to.\n * @param diameter Diameter of trailing mesh. Default is 1.\n * @param length Length of trailing mesh. Default is 60.\n * @param autoStart Automatically start trailing mesh. Default true.\n */\n constructor(name, generator, scene, diameter = 1, length = 60, autoStart = true) {\n super(name, scene);\n this._sectionPolygonPointsCount = 4;\n this._running = false;\n this._autoStart = autoStart;\n this._generator = generator;\n this.diameter = diameter;\n this._length = length;\n this._sectionVectors = [];\n this._sectionNormalVectors = [];\n for (let i = 0; i < this._sectionPolygonPointsCount; i++) {\n this._sectionVectors[i] = Vector3.Zero();\n this._sectionNormalVectors[i] = Vector3.Zero();\n }\n this._createMesh();\n }\n /**\n * \"TrailMesh\"\n * @returns \"TrailMesh\"\n */\n getClassName() {\n return \"TrailMesh\";\n }\n _createMesh() {\n const data = new VertexData();\n const positions = [];\n const normals = [];\n const indices = [];\n let meshCenter = Vector3.Zero();\n if (this._generator instanceof AbstractMesh && this._generator.hasBoundingInfo) {\n meshCenter = this._generator.getBoundingInfo().boundingBox.centerWorld;\n }\n else {\n meshCenter = this._generator.position;\n }\n const alpha = (2 * Math.PI) / this._sectionPolygonPointsCount;\n for (let i = 0; i < this._sectionPolygonPointsCount; i++) {\n positions.push(meshCenter.x + Math.cos(i * alpha) * this.diameter, meshCenter.y + Math.sin(i * alpha) * this.diameter, meshCenter.z);\n }\n for (let i = 1; i <= this._length; i++) {\n for (let j = 0; j < this._sectionPolygonPointsCount; j++) {\n positions.push(meshCenter.x + Math.cos(j * alpha) * this.diameter, meshCenter.y + Math.sin(j * alpha) * this.diameter, meshCenter.z);\n }\n const l = positions.length / 3 - 2 * this._sectionPolygonPointsCount;\n for (let j = 0; j < this._sectionPolygonPointsCount - 1; j++) {\n indices.push(l + j, l + j + this._sectionPolygonPointsCount, l + j + this._sectionPolygonPointsCount + 1);\n indices.push(l + j, l + j + this._sectionPolygonPointsCount + 1, l + j + 1);\n }\n indices.push(l + this._sectionPolygonPointsCount - 1, l + this._sectionPolygonPointsCount - 1 + this._sectionPolygonPointsCount, l + this._sectionPolygonPointsCount);\n indices.push(l + this._sectionPolygonPointsCount - 1, l + this._sectionPolygonPointsCount, l);\n }\n VertexData.ComputeNormals(positions, indices, normals);\n data.positions = positions;\n data.normals = normals;\n data.indices = indices;\n data.applyToMesh(this, true);\n if (this._autoStart) {\n this.start();\n }\n }\n /**\n * Start trailing mesh.\n */\n start() {\n if (!this._running) {\n this._running = true;\n this._beforeRenderObserver = this.getScene().onBeforeRenderObservable.add(() => {\n this.update();\n });\n }\n }\n /**\n * Stop trailing mesh.\n */\n stop() {\n if (this._beforeRenderObserver && this._running) {\n this._running = false;\n this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver);\n }\n }\n /**\n * Update trailing mesh geometry.\n */\n update() {\n const positions = this.getVerticesData(VertexBuffer.PositionKind);\n const normals = this.getVerticesData(VertexBuffer.NormalKind);\n const wm = this._generator.getWorldMatrix();\n if (positions && normals) {\n for (let i = 3 * this._sectionPolygonPointsCount; i < positions.length; i++) {\n positions[i - 3 * this._sectionPolygonPointsCount] = positions[i] - (normals[i] / this._length) * this.diameter;\n }\n for (let i = 3 * this._sectionPolygonPointsCount; i < normals.length; i++) {\n normals[i - 3 * this._sectionPolygonPointsCount] = normals[i];\n }\n const l = positions.length - 3 * this._sectionPolygonPointsCount;\n const alpha = (2 * Math.PI) / this._sectionPolygonPointsCount;\n for (let i = 0; i < this._sectionPolygonPointsCount; i++) {\n this._sectionVectors[i].copyFromFloats(Math.cos(i * alpha) * this.diameter, Math.sin(i * alpha) * this.diameter, 0);\n this._sectionNormalVectors[i].copyFromFloats(Math.cos(i * alpha), Math.sin(i * alpha), 0);\n Vector3.TransformCoordinatesToRef(this._sectionVectors[i], wm, this._sectionVectors[i]);\n Vector3.TransformNormalToRef(this._sectionNormalVectors[i], wm, this._sectionNormalVectors[i]);\n }\n for (let i = 0; i < this._sectionPolygonPointsCount; i++) {\n positions[l + 3 * i] = this._sectionVectors[i].x;\n positions[l + 3 * i + 1] = this._sectionVectors[i].y;\n positions[l + 3 * i + 2] = this._sectionVectors[i].z;\n normals[l + 3 * i] = this._sectionNormalVectors[i].x;\n normals[l + 3 * i + 1] = this._sectionNormalVectors[i].y;\n normals[l + 3 * i + 2] = this._sectionNormalVectors[i].z;\n }\n this.updateVerticesData(VertexBuffer.PositionKind, positions, true, false);\n this.updateVerticesData(VertexBuffer.NormalKind, normals, true, false);\n }\n }\n /**\n * Returns a new TrailMesh object.\n * @param name is a string, the name given to the new mesh\n * @param newGenerator use new generator object for cloned trail mesh\n * @returns a new mesh\n */\n clone(name = \"\", newGenerator) {\n return new TrailMesh(name, newGenerator === undefined ? this._generator : newGenerator, this.getScene(), this.diameter, this._length, this._autoStart);\n }\n /**\n * Serializes this trail mesh\n * @param serializationObject object to write serialization to\n */\n serialize(serializationObject) {\n super.serialize(serializationObject);\n }\n /**\n * Parses a serialized trail mesh\n * @param parsedMesh the serialized mesh\n * @param scene the scene to create the trail mesh in\n * @returns the created trail mesh\n */\n static Parse(parsedMesh, scene) {\n var _a;\n return new TrailMesh(parsedMesh.name, parsedMesh._generator, scene, (_a = parsedMesh.diameter) !== null && _a !== void 0 ? _a : parsedMesh._diameter, parsedMesh._length, parsedMesh._autoStart);\n }\n}\n//# sourceMappingURL=trailMesh.js.map","import { Vector3 } from \"../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { SubMesh } from \"../Meshes/subMesh.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { AsyncLoop } from \"../Misc/tools.js\";\nimport { Epsilon } from \"../Maths/math.constants.js\";\n/**\n * Class used to specify simplification options\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/simplifyingMeshes\n */\nexport class SimplificationSettings {\n /**\n * Creates a SimplificationSettings\n * @param quality expected quality\n * @param distance distance when this optimized version should be used\n * @param optimizeMesh already optimized mesh\n */\n constructor(\n /** expected quality */\n quality, \n /** distance when this optimized version should be used */\n distance, \n /** already optimized mesh */\n optimizeMesh) {\n this.quality = quality;\n this.distance = distance;\n this.optimizeMesh = optimizeMesh;\n }\n}\n/**\n * Queue used to order the simplification tasks\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/simplifyingMeshes\n */\nexport class SimplificationQueue {\n /**\n * Creates a new queue\n */\n constructor() {\n this.running = false;\n this._simplificationArray = [];\n }\n /**\n * Adds a new simplification task\n * @param task defines a task to add\n */\n addTask(task) {\n this._simplificationArray.push(task);\n }\n /**\n * Execute next task\n */\n executeNext() {\n const task = this._simplificationArray.pop();\n if (task) {\n this.running = true;\n this.runSimplification(task);\n }\n else {\n this.running = false;\n }\n }\n /**\n * Execute a simplification task\n * @param task defines the task to run\n */\n runSimplification(task) {\n if (task.parallelProcessing) {\n //parallel simplifier\n task.settings.forEach((setting) => {\n const simplifier = this._getSimplifier(task);\n simplifier.simplify(setting, (newMesh) => {\n if (setting.distance !== undefined) {\n task.mesh.addLODLevel(setting.distance, newMesh);\n }\n newMesh.isVisible = true;\n //check if it is the last\n if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {\n //all done, run the success callback.\n task.successCallback();\n }\n this.executeNext();\n });\n });\n }\n else {\n //single simplifier.\n const simplifier = this._getSimplifier(task);\n const runDecimation = (setting, callback) => {\n simplifier.simplify(setting, (newMesh) => {\n if (setting.distance !== undefined) {\n task.mesh.addLODLevel(setting.distance, newMesh);\n }\n newMesh.isVisible = true;\n //run the next quality level\n callback();\n });\n };\n AsyncLoop.Run(task.settings.length, (loop) => {\n runDecimation(task.settings[loop.index], () => {\n loop.executeNext();\n });\n }, () => {\n //execution ended, run the success callback.\n if (task.successCallback) {\n task.successCallback();\n }\n this.executeNext();\n });\n }\n }\n _getSimplifier(task) {\n switch (task.simplificationType) {\n case SimplificationType.QUADRATIC:\n default:\n return new QuadraticErrorSimplification(task.mesh);\n }\n }\n}\n/**\n * The implemented types of simplification\n * At the moment only Quadratic Error Decimation is implemented\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/simplifyingMeshes\n */\nexport var SimplificationType;\n(function (SimplificationType) {\n /** Quadratic error decimation */\n SimplificationType[SimplificationType[\"QUADRATIC\"] = 0] = \"QUADRATIC\";\n})(SimplificationType || (SimplificationType = {}));\nclass DecimationTriangle {\n constructor(_vertices) {\n this._vertices = _vertices;\n this.error = new Array(4);\n this.deleted = false;\n this.isDirty = false;\n this.deletePending = false;\n this.borderFactor = 0;\n }\n}\nclass DecimationVertex {\n constructor(position, id) {\n this.position = position;\n this.id = id;\n this.isBorder = true;\n this.q = new QuadraticMatrix();\n this.triangleCount = 0;\n this.triangleStart = 0;\n this.originalOffsets = [];\n }\n updatePosition(newPosition) {\n this.position.copyFrom(newPosition);\n }\n}\nclass QuadraticMatrix {\n constructor(data) {\n this.data = new Array(10);\n for (let i = 0; i < 10; ++i) {\n if (data && data[i]) {\n this.data[i] = data[i];\n }\n else {\n this.data[i] = 0;\n }\n }\n }\n det(a11, a12, a13, a21, a22, a23, a31, a32, a33) {\n const det = this.data[a11] * this.data[a22] * this.data[a33] +\n this.data[a13] * this.data[a21] * this.data[a32] +\n this.data[a12] * this.data[a23] * this.data[a31] -\n this.data[a13] * this.data[a22] * this.data[a31] -\n this.data[a11] * this.data[a23] * this.data[a32] -\n this.data[a12] * this.data[a21] * this.data[a33];\n return det;\n }\n addInPlace(matrix) {\n for (let i = 0; i < 10; ++i) {\n this.data[i] += matrix.data[i];\n }\n }\n addArrayInPlace(data) {\n for (let i = 0; i < 10; ++i) {\n this.data[i] += data[i];\n }\n }\n add(matrix) {\n const m = new QuadraticMatrix();\n for (let i = 0; i < 10; ++i) {\n m.data[i] = this.data[i] + matrix.data[i];\n }\n return m;\n }\n static FromData(a, b, c, d) {\n return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));\n }\n //returning an array to avoid garbage collection\n static DataFromNumbers(a, b, c, d) {\n return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];\n }\n}\nclass Reference {\n constructor(vertexId, triangleId) {\n this.vertexId = vertexId;\n this.triangleId = triangleId;\n }\n}\n/**\n * An implementation of the Quadratic Error simplification algorithm.\n * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf\n * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS\n * @author RaananW\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/simplifyingMeshes\n */\nexport class QuadraticErrorSimplification {\n /**\n * Creates a new QuadraticErrorSimplification\n * @param _mesh defines the target mesh\n */\n constructor(_mesh) {\n this._mesh = _mesh;\n /** Gets or sets the number pf sync iterations */\n this.syncIterations = 5000;\n this.aggressiveness = 7;\n this.decimationIterations = 100;\n this.boundingBoxEpsilon = Epsilon;\n }\n /**\n * Simplification of a given mesh according to the given settings.\n * Since this requires computation, it is assumed that the function runs async.\n * @param settings The settings of the simplification, including quality and distance\n * @param successCallback A callback that will be called after the mesh was simplified.\n */\n simplify(settings, successCallback) {\n this._initDecimatedMesh();\n //iterating through the submeshes array, one after the other.\n AsyncLoop.Run(this._mesh.subMeshes.length, (loop) => {\n this._initWithMesh(loop.index, () => {\n this._runDecimation(settings, loop.index, () => {\n loop.executeNext();\n });\n }, settings.optimizeMesh);\n }, () => {\n setTimeout(() => {\n successCallback(this._reconstructedMesh);\n }, 0);\n });\n }\n _runDecimation(settings, submeshIndex, successCallback) {\n const targetCount = ~~(this._triangles.length * settings.quality);\n let deletedTriangles = 0;\n const triangleCount = this._triangles.length;\n const iterationFunction = (iteration, callback) => {\n setTimeout(() => {\n if (iteration % 5 === 0) {\n this._updateMesh(iteration === 0);\n }\n for (let i = 0; i < this._triangles.length; ++i) {\n this._triangles[i].isDirty = false;\n }\n const threshold = 0.000000001 * Math.pow(iteration + 3, this.aggressiveness);\n const trianglesIterator = (i) => {\n const tIdx = ~~((this._triangles.length / 2 + i) % this._triangles.length);\n const t = this._triangles[tIdx];\n if (!t) {\n return;\n }\n if (t.error[3] > threshold || t.deleted || t.isDirty) {\n return;\n }\n for (let j = 0; j < 3; ++j) {\n if (t.error[j] < threshold) {\n const deleted0 = [];\n const deleted1 = [];\n const v0 = t._vertices[j];\n const v1 = t._vertices[(j + 1) % 3];\n if (v0.isBorder || v1.isBorder) {\n continue;\n }\n const p = Vector3.Zero();\n // var n = Vector3.Zero();\n // var uv = Vector2.Zero();\n // var color = new Color4(0, 0, 0, 1);\n this._calculateError(v0, v1, p);\n const delTr = new Array();\n if (this._isFlipped(v0, v1, p, deleted0, delTr)) {\n continue;\n }\n if (this._isFlipped(v1, v0, p, deleted1, delTr)) {\n continue;\n }\n if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0) {\n continue;\n }\n const uniqueArray = new Array();\n delTr.forEach((deletedT) => {\n if (uniqueArray.indexOf(deletedT) === -1) {\n deletedT.deletePending = true;\n uniqueArray.push(deletedT);\n }\n });\n if (uniqueArray.length % 2 !== 0) {\n continue;\n }\n v0.q = v1.q.add(v0.q);\n v0.updatePosition(p);\n const tStart = this._references.length;\n deletedTriangles = this._updateTriangles(v0, v0, deleted0, deletedTriangles);\n deletedTriangles = this._updateTriangles(v0, v1, deleted1, deletedTriangles);\n const tCount = this._references.length - tStart;\n if (tCount <= v0.triangleCount) {\n if (tCount) {\n for (let c = 0; c < tCount; c++) {\n this._references[v0.triangleStart + c] = this._references[tStart + c];\n }\n }\n }\n else {\n v0.triangleStart = tStart;\n }\n v0.triangleCount = tCount;\n break;\n }\n }\n };\n AsyncLoop.SyncAsyncForLoop(this._triangles.length, this.syncIterations, trianglesIterator, callback, () => {\n return triangleCount - deletedTriangles <= targetCount;\n });\n }, 0);\n };\n AsyncLoop.Run(this.decimationIterations, (loop) => {\n if (triangleCount - deletedTriangles <= targetCount) {\n loop.breakLoop();\n }\n else {\n iterationFunction(loop.index, () => {\n loop.executeNext();\n });\n }\n }, () => {\n setTimeout(() => {\n //reconstruct this part of the mesh\n this._reconstructMesh(submeshIndex);\n successCallback();\n }, 0);\n });\n }\n _initWithMesh(submeshIndex, callback, optimizeMesh) {\n this._vertices = [];\n this._triangles = [];\n const positionData = this._mesh.getVerticesData(VertexBuffer.PositionKind);\n const indices = this._mesh.getIndices();\n const submesh = this._mesh.subMeshes[submeshIndex];\n const findInVertices = (positionToSearch) => {\n if (optimizeMesh) {\n for (let ii = 0; ii < this._vertices.length; ++ii) {\n if (this._vertices[ii].position.equalsWithEpsilon(positionToSearch, 0.0001)) {\n return this._vertices[ii];\n }\n }\n }\n return null;\n };\n const vertexReferences = [];\n const vertexInit = (i) => {\n if (!positionData) {\n return;\n }\n const offset = i + submesh.verticesStart;\n const position = Vector3.FromArray(positionData, offset * 3);\n const vertex = findInVertices(position) || new DecimationVertex(position, this._vertices.length);\n vertex.originalOffsets.push(offset);\n if (vertex.id === this._vertices.length) {\n this._vertices.push(vertex);\n }\n vertexReferences.push(vertex.id);\n };\n //var totalVertices = mesh.getTotalVertices();\n const totalVertices = submesh.verticesCount;\n AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, () => {\n const indicesInit = (i) => {\n if (!indices) {\n return;\n }\n const offset = submesh.indexStart / 3 + i;\n const pos = offset * 3;\n const i0 = indices[pos + 0];\n const i1 = indices[pos + 1];\n const i2 = indices[pos + 2];\n const v0 = this._vertices[vertexReferences[i0 - submesh.verticesStart]];\n const v1 = this._vertices[vertexReferences[i1 - submesh.verticesStart]];\n const v2 = this._vertices[vertexReferences[i2 - submesh.verticesStart]];\n const triangle = new DecimationTriangle([v0, v1, v2]);\n triangle.originalOffset = pos;\n this._triangles.push(triangle);\n };\n AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, this.syncIterations, indicesInit, () => {\n this._init(callback);\n });\n });\n }\n _init(callback) {\n const triangleInit1 = (i) => {\n const t = this._triangles[i];\n t.normal = Vector3.Cross(t._vertices[1].position.subtract(t._vertices[0].position), t._vertices[2].position.subtract(t._vertices[0].position)).normalize();\n for (let j = 0; j < 3; j++) {\n t._vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -Vector3.Dot(t.normal, t._vertices[0].position)));\n }\n };\n AsyncLoop.SyncAsyncForLoop(this._triangles.length, this.syncIterations, triangleInit1, () => {\n const triangleInit2 = (i) => {\n const t = this._triangles[i];\n for (let j = 0; j < 3; ++j) {\n t.error[j] = this._calculateError(t._vertices[j], t._vertices[(j + 1) % 3]);\n }\n t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);\n };\n AsyncLoop.SyncAsyncForLoop(this._triangles.length, this.syncIterations, triangleInit2, () => {\n callback();\n });\n });\n }\n _reconstructMesh(submeshIndex) {\n const newTriangles = [];\n let i;\n for (i = 0; i < this._vertices.length; ++i) {\n this._vertices[i].triangleCount = 0;\n }\n let t;\n let j;\n for (i = 0; i < this._triangles.length; ++i) {\n if (!this._triangles[i].deleted) {\n t = this._triangles[i];\n for (j = 0; j < 3; ++j) {\n t._vertices[j].triangleCount = 1;\n }\n newTriangles.push(t);\n }\n }\n const newPositionData = (this._reconstructedMesh.getVerticesData(VertexBuffer.PositionKind) || []);\n const newNormalData = (this._reconstructedMesh.getVerticesData(VertexBuffer.NormalKind) || []);\n const newUVsData = (this._reconstructedMesh.getVerticesData(VertexBuffer.UVKind) || []);\n const newColorsData = (this._reconstructedMesh.getVerticesData(VertexBuffer.ColorKind) || []);\n const normalData = this._mesh.getVerticesData(VertexBuffer.NormalKind);\n const uvs = this._mesh.getVerticesData(VertexBuffer.UVKind);\n const colorsData = this._mesh.getVerticesData(VertexBuffer.ColorKind);\n let vertexCount = 0;\n for (i = 0; i < this._vertices.length; ++i) {\n const vertex = this._vertices[i];\n vertex.id = vertexCount;\n if (vertex.triangleCount) {\n vertex.originalOffsets.forEach((originalOffset) => {\n newPositionData.push(vertex.position.x);\n newPositionData.push(vertex.position.y);\n newPositionData.push(vertex.position.z);\n if (normalData && normalData.length) {\n newNormalData.push(normalData[originalOffset * 3]);\n newNormalData.push(normalData[originalOffset * 3 + 1]);\n newNormalData.push(normalData[originalOffset * 3 + 2]);\n }\n if (uvs && uvs.length) {\n newUVsData.push(uvs[originalOffset * 2]);\n newUVsData.push(uvs[originalOffset * 2 + 1]);\n }\n if (colorsData && colorsData.length) {\n newColorsData.push(colorsData[originalOffset * 4]);\n newColorsData.push(colorsData[originalOffset * 4 + 1]);\n newColorsData.push(colorsData[originalOffset * 4 + 2]);\n newColorsData.push(colorsData[originalOffset * 4 + 3]);\n }\n ++vertexCount;\n });\n }\n }\n const startingIndex = this._reconstructedMesh.getTotalIndices();\n const startingVertex = this._reconstructedMesh.getTotalVertices();\n const submeshesArray = this._reconstructedMesh.subMeshes;\n this._reconstructedMesh.subMeshes = [];\n const newIndicesArray = this._reconstructedMesh.getIndices(); //[];\n const originalIndices = this._mesh.getIndices();\n for (i = 0; i < newTriangles.length; ++i) {\n t = newTriangles[i]; //now get the new referencing point for each vertex\n [0, 1, 2].forEach((idx) => {\n const id = originalIndices[t.originalOffset + idx];\n let offset = t._vertices[idx].originalOffsets.indexOf(id);\n if (offset < 0) {\n offset = 0;\n }\n newIndicesArray.push(t._vertices[idx].id + offset + startingVertex);\n });\n }\n //overwriting the old vertex buffers and indices.\n this._reconstructedMesh.setIndices(newIndicesArray);\n this._reconstructedMesh.setVerticesData(VertexBuffer.PositionKind, newPositionData);\n if (newNormalData.length > 0) {\n this._reconstructedMesh.setVerticesData(VertexBuffer.NormalKind, newNormalData);\n }\n if (newUVsData.length > 0) {\n this._reconstructedMesh.setVerticesData(VertexBuffer.UVKind, newUVsData);\n }\n if (newColorsData.length > 0) {\n this._reconstructedMesh.setVerticesData(VertexBuffer.ColorKind, newColorsData);\n }\n //create submesh\n const originalSubmesh = this._mesh.subMeshes[submeshIndex];\n if (submeshIndex > 0) {\n this._reconstructedMesh.subMeshes = [];\n submeshesArray.forEach((submesh) => {\n SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, \n /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());\n });\n SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, \n /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);\n }\n }\n _initDecimatedMesh() {\n this._reconstructedMesh = new Mesh(this._mesh.name + \"Decimated\", this._mesh.getScene());\n this._reconstructedMesh.material = this._mesh.material;\n this._reconstructedMesh.parent = this._mesh.parent;\n this._reconstructedMesh.isVisible = false;\n this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;\n }\n _isFlipped(vertex1, vertex2, point, deletedArray, delTr) {\n for (let i = 0; i < vertex1.triangleCount; ++i) {\n const t = this._triangles[this._references[vertex1.triangleStart + i].triangleId];\n if (t.deleted) {\n continue;\n }\n const s = this._references[vertex1.triangleStart + i].vertexId;\n const v1 = t._vertices[(s + 1) % 3];\n const v2 = t._vertices[(s + 2) % 3];\n if (v1 === vertex2 || v2 === vertex2) {\n deletedArray[i] = true;\n delTr.push(t);\n continue;\n }\n let d1 = v1.position.subtract(point);\n d1 = d1.normalize();\n let d2 = v2.position.subtract(point);\n d2 = d2.normalize();\n if (Math.abs(Vector3.Dot(d1, d2)) > 0.999) {\n return true;\n }\n const normal = Vector3.Cross(d1, d2).normalize();\n deletedArray[i] = false;\n if (Vector3.Dot(normal, t.normal) < 0.2) {\n return true;\n }\n }\n return false;\n }\n _updateTriangles(origVertex, vertex, deletedArray, deletedTriangles) {\n let newDeleted = deletedTriangles;\n for (let i = 0; i < vertex.triangleCount; ++i) {\n const ref = this._references[vertex.triangleStart + i];\n const t = this._triangles[ref.triangleId];\n if (t.deleted) {\n continue;\n }\n if (deletedArray[i] && t.deletePending) {\n t.deleted = true;\n newDeleted++;\n continue;\n }\n t._vertices[ref.vertexId] = origVertex;\n t.isDirty = true;\n t.error[0] = this._calculateError(t._vertices[0], t._vertices[1]) + t.borderFactor / 2;\n t.error[1] = this._calculateError(t._vertices[1], t._vertices[2]) + t.borderFactor / 2;\n t.error[2] = this._calculateError(t._vertices[2], t._vertices[0]) + t.borderFactor / 2;\n t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);\n this._references.push(ref);\n }\n return newDeleted;\n }\n _identifyBorder() {\n for (let i = 0; i < this._vertices.length; ++i) {\n const vCount = [];\n const vId = [];\n const v = this._vertices[i];\n let j;\n for (j = 0; j < v.triangleCount; ++j) {\n const triangle = this._triangles[this._references[v.triangleStart + j].triangleId];\n for (let ii = 0; ii < 3; ii++) {\n let ofs = 0;\n const vv = triangle._vertices[ii];\n while (ofs < vCount.length) {\n if (vId[ofs] === vv.id) {\n break;\n }\n ++ofs;\n }\n if (ofs === vCount.length) {\n vCount.push(1);\n vId.push(vv.id);\n }\n else {\n vCount[ofs]++;\n }\n }\n }\n for (j = 0; j < vCount.length; ++j) {\n if (vCount[j] === 1) {\n this._vertices[vId[j]].isBorder = true;\n }\n else {\n this._vertices[vId[j]].isBorder = false;\n }\n }\n }\n }\n _updateMesh(identifyBorders = false) {\n let i;\n if (!identifyBorders) {\n const newTrianglesVector = [];\n for (i = 0; i < this._triangles.length; ++i) {\n if (!this._triangles[i].deleted) {\n newTrianglesVector.push(this._triangles[i]);\n }\n }\n this._triangles = newTrianglesVector;\n }\n for (i = 0; i < this._vertices.length; ++i) {\n this._vertices[i].triangleCount = 0;\n this._vertices[i].triangleStart = 0;\n }\n let t;\n let j;\n let v;\n for (i = 0; i < this._triangles.length; ++i) {\n t = this._triangles[i];\n for (j = 0; j < 3; ++j) {\n v = t._vertices[j];\n v.triangleCount++;\n }\n }\n let tStart = 0;\n for (i = 0; i < this._vertices.length; ++i) {\n this._vertices[i].triangleStart = tStart;\n tStart += this._vertices[i].triangleCount;\n this._vertices[i].triangleCount = 0;\n }\n const newReferences = new Array(this._triangles.length * 3);\n for (i = 0; i < this._triangles.length; ++i) {\n t = this._triangles[i];\n for (j = 0; j < 3; ++j) {\n v = t._vertices[j];\n newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);\n v.triangleCount++;\n }\n }\n this._references = newReferences;\n if (identifyBorders) {\n this._identifyBorder();\n }\n }\n _vertexError(q, point) {\n const x = point.x;\n const y = point.y;\n const z = point.z;\n return (q.data[0] * x * x +\n 2 * q.data[1] * x * y +\n 2 * q.data[2] * x * z +\n 2 * q.data[3] * x +\n q.data[4] * y * y +\n 2 * q.data[5] * y * z +\n 2 * q.data[6] * y +\n q.data[7] * z * z +\n 2 * q.data[8] * z +\n q.data[9]);\n }\n _calculateError(vertex1, vertex2, pointResult) {\n const q = vertex1.q.add(vertex2.q);\n const border = vertex1.isBorder && vertex2.isBorder;\n let error = 0;\n const qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);\n if (qDet !== 0 && !border) {\n if (!pointResult) {\n pointResult = Vector3.Zero();\n }\n pointResult.x = (-1 / qDet) * q.det(1, 2, 3, 4, 5, 6, 5, 7, 8);\n pointResult.y = (1 / qDet) * q.det(0, 2, 3, 1, 5, 6, 2, 7, 8);\n pointResult.z = (-1 / qDet) * q.det(0, 1, 3, 1, 4, 6, 2, 5, 8);\n error = this._vertexError(q, pointResult);\n }\n else {\n const p3 = vertex1.position.add(vertex2.position).divide(new Vector3(2, 2, 2));\n //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();\n const error1 = this._vertexError(q, vertex1.position);\n const error2 = this._vertexError(q, vertex2.position);\n const error3 = this._vertexError(q, p3);\n error = Math.min(error1, error2, error3);\n if (error === error1) {\n if (pointResult) {\n pointResult.copyFrom(vertex1.position);\n }\n }\n else if (error === error2) {\n if (pointResult) {\n pointResult.copyFrom(vertex2.position);\n }\n }\n else {\n if (pointResult) {\n pointResult.copyFrom(p3);\n }\n }\n }\n return error;\n }\n}\n//# sourceMappingURL=meshSimplification.js.map","import { Vector3 } from \"../Maths/math.vector.js\";\nimport { GreasedLinePluginMaterial } from \"../Materials/greasedLinePluginMaterial.js\";\nimport { Mesh } from \"./mesh.js\";\nimport { Buffer, VertexBuffer } from \"../Buffers/buffer.js\";\nimport { VertexData } from \"./mesh.vertexData.js\";\nimport { PickingInfo } from \"../Collisions/pickingInfo.js\";\nimport { DeepCopier } from \"../Misc/deepCopier.js\";\nimport { GreasedLineTools } from \"../Misc/greasedLineTools.js\";\nMesh._GreasedLineMeshParser = (parsedMesh, scene) => {\n return GreasedLineMesh.Parse(parsedMesh, scene);\n};\n/**\n * GreasedLine\n */\nexport class GreasedLineMesh extends Mesh {\n constructor(name, scene, _options) {\n var _a, _b, _c, _d;\n super(name, scene, null, null, false, false);\n this.name = name;\n this._options = _options;\n this._lazy = false;\n this._updatable = false;\n /**\n * Treshold used to pick the mesh\n */\n this.intersectionThreshold = 0.1;\n this._lazy = (_a = _options.lazy) !== null && _a !== void 0 ? _a : false;\n this._updatable = (_b = _options.updatable) !== null && _b !== void 0 ? _b : false;\n this._vertexPositions = [];\n this._indices = [];\n this._uvs = [];\n this._points = [];\n this._colorPointers = (_c = _options.colorPointers) !== null && _c !== void 0 ? _c : [];\n this._previousAndSide = [];\n this._nextAndCounters = [];\n _options.widths = (_d = _options.widths) !== null && _d !== void 0 ? _d : new Array(_options.points.length).fill(1);\n if (_options.points) {\n this.addPoints(GreasedLineMesh.ConvertPoints(_options.points));\n }\n }\n /**\n * \"GreasedLineMesh\"\n * @returns \"GreasedLineMesh\"\n */\n getClassName() {\n return \"GreasedLineMesh\";\n }\n /**\n * Converts GreasedLinePoints to number[][]\n * @param points GreasedLinePoints\n * @returns number[][] with x, y, z coordinates of the points, like [[x, y, z, x, y, z, ...], [x, y, z, ...]]\n */\n static ConvertPoints(points) {\n if (points.length && Array.isArray(points) && typeof points[0] === \"number\") {\n return [points];\n }\n else if (points.length && Array.isArray(points[0]) && typeof points[0][0] === \"number\") {\n return points;\n }\n else if (points.length && !Array.isArray(points[0]) && points[0] instanceof Vector3) {\n const positions = [];\n for (let j = 0; j < points.length; j++) {\n const p = points[j];\n positions.push(p.x, p.y, p.z);\n }\n return [positions];\n }\n else if (points.length > 0 && Array.isArray(points[0]) && points[0].length > 0 && points[0][0] instanceof Vector3) {\n const positions = [];\n const vectorPoints = points;\n vectorPoints.forEach((p) => {\n positions.push(p.flatMap((p2) => [p2.x, p2.y, p2.z]));\n });\n return positions;\n }\n else if (points instanceof Float32Array) {\n return [Array.from(points)];\n }\n else if (points.length && points[0] instanceof Float32Array) {\n const positions = [];\n points.forEach((p) => {\n positions.push(Array.from(p));\n });\n return positions;\n }\n return [];\n }\n /**\n * Updated a lazy line. Rerenders the line and updates boundinfo as well.\n */\n updateLazy() {\n var _a;\n this.setPoints(this._points);\n if (!this._options.colorPointers) {\n this._updateColorPointers();\n }\n this._createVertexBuffers();\n this.refreshBoundingInfo();\n (_a = this.greasedLineMaterial) === null || _a === void 0 ? void 0 : _a.updateLazy();\n }\n /**\n * Dispose the line and it's resources\n */\n dispose() {\n super.dispose();\n }\n /**\n *\n * @returns true if the mesh was created in lazy mode\n */\n isLazy() {\n return this._lazy;\n }\n /**\n *\n * @returns options of the line\n */\n get options() {\n return this._options;\n }\n /**\n * Sets point offets\n * @param offsets offset table [x,y,z, x,y,z, ....]\n */\n setOffsets(offsets) {\n if (!this._offsetsBuffer) {\n this._createOffsetsBuffer(offsets);\n }\n else {\n this._offsetsBuffer && this._offsetsBuffer.update(offsets);\n }\n }\n /**\n * Sets widths at each line point\n * @param widths width table [widthUpper,widthLower, widthUpper,widthLower, ...]\n */\n setSegmentWidths(widths) {\n this._options.widths = widths;\n if (!this._lazy) {\n this._widthsBuffer && this._widthsBuffer.update(widths);\n }\n }\n /**\n * Sets the color pointer\n * @param colorPointers arra of color pointer in the colors array. One pointer for every vertex is needed.\n */\n setColorPointers(colorPointers) {\n if (!this._lazy) {\n this._colorPointersBuffer && this._colorPointersBuffer.update(colorPointers);\n }\n }\n /**\n * Gets the pluginMaterial associated with line\n */\n get greasedLineMaterial() {\n var _a, _b;\n return (_b = (_a = this.material) === null || _a === void 0 ? void 0 : _a.pluginManager) === null || _b === void 0 ? void 0 : _b.getPlugin(GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME);\n }\n /**\n * Adds new points to the line. It doesn't rerenders the line if in lazy mode.\n * @param points points table\n */\n addPoints(points) {\n const numberPoints = points;\n this._points.push(...numberPoints);\n if (!this._lazy) {\n this.setPoints(this._points);\n }\n }\n _updateColorPointers() {\n let colorPointer = 0;\n this._colorPointers = [];\n this._points.forEach((p) => {\n for (let jj = 0; jj < p.length; jj += 3) {\n this._colorPointers.push(colorPointer);\n this._colorPointers.push(colorPointer++);\n }\n });\n }\n /**\n * Sets line points and rerenders the line.\n * @param points points table\n */\n setPoints(points) {\n this._points = points;\n this._options.points = points;\n this._initGreasedLine();\n let indiceOffset = 0;\n points.forEach((p) => {\n var _a;\n const counters = [];\n const positions = [];\n const indices = [];\n const totalLength = GreasedLineTools.GetLineLength(p);\n for (let j = 0, jj = 0; jj < p.length; j++, jj += 3) {\n const partialLine = p.slice(0, jj + 3);\n const partialLineLength = GreasedLineTools.GetLineLength(partialLine);\n const c = partialLineLength / totalLength;\n positions.push(p[jj], p[jj + 1], p[jj + 2]);\n positions.push(p[jj], p[jj + 1], p[jj + 2]);\n counters.push(c);\n counters.push(c);\n if (jj < p.length - 3) {\n const n = j * 2 + indiceOffset;\n indices.push(n, n + 1, n + 2);\n indices.push(n + 2, n + 1, n + 3);\n }\n }\n indiceOffset += (p.length / 3) * 2;\n const previous = [];\n const next = [];\n const side = [];\n let uvs = [];\n this._preprocess(positions, previous, next, side, uvs);\n this._vertexPositions.push(...positions);\n this._indices.push(...indices);\n for (let i = 0; i < side.length; i++) {\n this._previousAndSide.push(previous[i * 3], previous[i * 3 + 1], previous[i * 3 + 2], side[i]);\n this._nextAndCounters.push(next[i * 3], next[i * 3 + 1], next[i * 3 + 2], counters[i]);\n }\n uvs = (_a = this._options.uvs) !== null && _a !== void 0 ? _a : uvs;\n this._uvs.push(...uvs);\n });\n if (!this._lazy) {\n if (!this._options.colorPointers) {\n this._updateColorPointers();\n }\n this._createVertexBuffers();\n this.refreshBoundingInfo();\n }\n }\n /**\n * Clones the GreasedLineMesh.\n * @param name new line name\n * @param newParent new parent node\n * @returns cloned line\n */\n clone(name = `${this.name}-cloned`, newParent) {\n const lineOptions = {};\n DeepCopier.DeepCopy(this._options, lineOptions, [\"instance\"]);\n const cloned = new GreasedLineMesh(name, this._scene, lineOptions);\n if (newParent) {\n cloned.parent = newParent;\n }\n cloned.material = this.material;\n return cloned;\n }\n /**\n * Serializes this GreasedLineMesh\n * @param serializationObject object to write serialization to\n */\n serialize(serializationObject) {\n super.serialize(serializationObject);\n serializationObject.type = this.getClassName();\n serializationObject.lineOptions = this._options;\n }\n /**\n * Parses a serialized GreasedLineMesh\n * @param parsedMesh the serialized GreasedLineMesh\n * @param scene the scene to create the GreasedLineMesh in\n * @returns the created GreasedLineMesh\n */\n static Parse(parsedMesh, scene) {\n const lineOptions = parsedMesh.lineOptions;\n const name = parsedMesh.name;\n const result = new GreasedLineMesh(name, scene, lineOptions);\n return result;\n }\n /**\n * Checks whether a ray is intersecting this GreasedLineMesh\n * @param ray ray to check the intersection of this mesh with\n * @param fastCheck not supported\n * @param trianglePredicate not supported\n * @param onlyBoundingInfo defines a boolean indicating if picking should only happen using bounding info (false by default)\n * @param worldToUse not supported\n * @param skipBoundingInfo a boolean indicating if we should skip the bounding info check\n * @returns the picking info\n */\n intersects(ray, fastCheck, trianglePredicate, onlyBoundingInfo = false, worldToUse, skipBoundingInfo = false) {\n const pickingInfo = new PickingInfo();\n const intersections = this.findAllIntersections(ray, fastCheck, trianglePredicate, onlyBoundingInfo, worldToUse, skipBoundingInfo, true);\n if ((intersections === null || intersections === void 0 ? void 0 : intersections.length) === 1) {\n const intersection = intersections[0];\n pickingInfo.hit = true;\n pickingInfo.distance = intersection.distance;\n pickingInfo.ray = ray;\n pickingInfo.pickedMesh = this;\n pickingInfo.pickedPoint = intersection.point;\n }\n return pickingInfo;\n }\n /**\n * Gets all intersections of a ray and the line\n * @param ray Ray to check the intersection of this mesh with\n * @param _fastCheck not supported\n * @param _trianglePredicate not supported\n * @param onlyBoundingInfo defines a boolean indicating if picking should only happen using bounding info (false by default)\n * @param _worldToUse not supported\n * @param skipBoundingInfo a boolean indicating if we should skip the bounding info check\n * @param firstOnly If true, the first and only intersection is immediatelly returned if found\n * @returns intersection(s)\n */\n findAllIntersections(ray, _fastCheck, _trianglePredicate, onlyBoundingInfo = false, _worldToUse, skipBoundingInfo = false, firstOnly = false) {\n var _a, _b;\n if (onlyBoundingInfo && !skipBoundingInfo && ray.intersectsSphere(this._boundingSphere, this.intersectionThreshold) === false) {\n return;\n }\n const indices = this.getIndices();\n const positions = this.getVerticesData(VertexBuffer.PositionKind);\n const widths = this._options.widths;\n const lineWidth = (_b = (_a = this.greasedLineMaterial) === null || _a === void 0 ? void 0 : _a.getOptions().width) !== null && _b !== void 0 ? _b : 1;\n const intersects = [];\n if (indices && positions && widths) {\n let i = 0, l = 0;\n for (i = 0, l = indices.length - 1; i < l; i += 3) {\n const a = indices[i];\n const b = indices[i + 1];\n GreasedLineMesh._V_START.fromArray(positions, a * 3);\n GreasedLineMesh._V_END.fromArray(positions, b * 3);\n if (this._offsets) {\n GreasedLineMesh._V_OFFSET_START.fromArray(this._offsets, a * 3);\n GreasedLineMesh._V_OFFSET_END.fromArray(this._offsets, b * 3);\n GreasedLineMesh._V_START.addInPlace(GreasedLineMesh._V_OFFSET_START);\n GreasedLineMesh._V_END.addInPlace(GreasedLineMesh._V_OFFSET_END);\n }\n const iFloored = Math.floor(i / 3);\n const width = widths[iFloored] !== undefined ? widths[iFloored] : 1;\n const precision = (this.intersectionThreshold * (lineWidth * width)) / 2;\n const distance = ray.intersectionSegment(GreasedLineMesh._V_START, GreasedLineMesh._V_END, precision);\n if (distance !== -1) {\n intersects.push({\n distance: distance,\n point: ray.direction.normalize().multiplyByFloats(distance, distance, distance).add(ray.origin),\n });\n if (firstOnly) {\n return intersects;\n }\n }\n }\n i = l;\n }\n return intersects;\n }\n _initGreasedLine() {\n this._vertexPositions = [];\n this._previousAndSide = [];\n this._nextAndCounters = [];\n this._indices = [];\n this._uvs = [];\n }\n get _boundingSphere() {\n return this.getBoundingInfo().boundingSphere;\n }\n static _CompareV3(positionIdx1, positionIdx2, positions) {\n const arrayIdx1 = positionIdx1 * 6;\n const arrayIdx2 = positionIdx2 * 6;\n return positions[arrayIdx1] === positions[arrayIdx2] && positions[arrayIdx1 + 1] === positions[arrayIdx2 + 1] && positions[arrayIdx1 + 2] === positions[arrayIdx2 + 2];\n }\n static _CopyV3(positionIdx, positions) {\n const arrayIdx = positionIdx * 6;\n return [positions[arrayIdx], positions[arrayIdx + 1], positions[arrayIdx + 2]];\n }\n _preprocess(positions, previous, next, side, uvs) {\n const l = positions.length / 6;\n let v = [];\n if (GreasedLineMesh._CompareV3(0, l - 1, positions)) {\n v = GreasedLineMesh._CopyV3(l - 2, positions);\n }\n else {\n v = GreasedLineMesh._CopyV3(0, positions);\n }\n previous.push(v[0], v[1], v[2]);\n previous.push(v[0], v[1], v[2]);\n for (let j = 0; j < l; j++) {\n side.push(1);\n side.push(-1);\n // uvs\n if (!this._options.uvs) {\n uvs.push(j / (l - 1), 0);\n uvs.push(j / (l - 1), 1);\n }\n if (j < l - 1) {\n v = GreasedLineMesh._CopyV3(j, positions);\n previous.push(v[0], v[1], v[2]);\n previous.push(v[0], v[1], v[2]);\n }\n if (j > 0) {\n v = GreasedLineMesh._CopyV3(j, positions);\n next.push(v[0], v[1], v[2]);\n next.push(v[0], v[1], v[2]);\n }\n }\n if (GreasedLineMesh._CompareV3(l - 1, 0, positions)) {\n v = GreasedLineMesh._CopyV3(1, positions);\n }\n else {\n v = GreasedLineMesh._CopyV3(l - 1, positions);\n }\n next.push(v[0], v[1], v[2]);\n next.push(v[0], v[1], v[2]);\n return {\n previous,\n next,\n uvs,\n side,\n };\n }\n _createVertexBuffers() {\n const vertexData = new VertexData();\n vertexData.positions = this._vertexPositions;\n vertexData.indices = this._indices;\n vertexData.uvs = this._uvs;\n vertexData.applyToMesh(this, this._options.updatable);\n const engine = this._scene.getEngine();\n const previousAndSideBuffer = new Buffer(engine, this._previousAndSide, false, 4);\n this.setVerticesBuffer(previousAndSideBuffer.createVertexBuffer(\"grl_previousAndSide\", 0, 4));\n const nextAndCountersBuffer = new Buffer(engine, this._nextAndCounters, false, 4);\n this.setVerticesBuffer(nextAndCountersBuffer.createVertexBuffer(\"grl_nextAndCounters\", 0, 4));\n const widthBuffer = new Buffer(engine, this._options.widths, this._updatable, 1);\n this.setVerticesBuffer(widthBuffer.createVertexBuffer(\"grl_widths\", 0, 1));\n this._widthsBuffer = widthBuffer;\n const colorPointersBuffer = new Buffer(engine, this._colorPointers, this._updatable, 1);\n this.setVerticesBuffer(colorPointersBuffer.createVertexBuffer(\"grl_colorPointers\", 0, 1));\n this._colorPointersBuffer = colorPointersBuffer;\n }\n _createOffsetsBuffer(offsets) {\n const engine = this._scene.getEngine();\n const offsetBuffer = new Buffer(engine, offsets, this._updatable, 3);\n this.setVerticesBuffer(offsetBuffer.createVertexBuffer(\"grl_offsets\", 0, 3));\n this._offsetsBuffer = offsetBuffer;\n }\n}\nGreasedLineMesh._V_START = new Vector3();\nGreasedLineMesh._V_END = new Vector3();\nGreasedLineMesh._V_OFFSET_START = new Vector3();\nGreasedLineMesh._V_OFFSET_END = new Vector3();\n//# sourceMappingURL=greasedLineMesh.js.map","/* eslint-disable import/export */\n/* eslint-disable import/no-internal-modules */\nexport * from \"./abstractMesh.js\";\nimport \"./abstractMesh.decalMap.js\";\nexport * from \"./Compression/index.js\";\nexport * from \"./csg.js\";\nexport * from \"./meshUVSpaceRenderer.js\";\nexport * from \"./geometry.js\";\nexport * from \"./groundMesh.js\";\nexport * from \"./goldbergMesh.js\";\nexport * from \"./trailMesh.js\";\nexport * from \"./instancedMesh.js\";\nexport * from \"./linesMesh.js\";\nexport * from \"./mesh.js\";\nexport * from \"./mesh.vertexData.js\";\nexport * from \"./meshBuilder.js\";\nexport * from \"./meshSimplification.js\";\nexport * from \"./meshSimplificationSceneComponent.js\";\nexport * from \"./polygonMesh.js\";\nexport * from \"./geodesicMesh.js\";\nexport * from \"./subMesh.js\";\nexport * from \"./subMesh.project.js\";\nexport * from \"./meshLODLevel.js\";\nexport * from \"./transformNode.js\";\nexport * from \"./Builders/index.js\";\nexport * from \"./WebGL/webGLDataBuffer.js\";\nexport * from \"./WebGPU/webgpuDataBuffer.js\";\nexport * from \"./greasedLineMesh.js\";\nimport \"./thinInstanceMesh.js\";\n// eslint-disable-next-line no-duplicate-imports\nexport * from \"./thinInstanceMesh.js\";\n//# sourceMappingURL=index.js.map","import { Scene } from \"../scene.js\";\nimport { Mesh } from \"./mesh.js\";\nimport { SimplificationQueue, SimplificationType } from \"./meshSimplification.js\";\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nObject.defineProperty(Scene.prototype, \"simplificationQueue\", {\n get: function () {\n if (!this._simplificationQueue) {\n this._simplificationQueue = new SimplificationQueue();\n let component = this._getComponent(SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);\n if (!component) {\n component = new SimplicationQueueSceneComponent(this);\n this._addComponent(component);\n }\n }\n return this._simplificationQueue;\n },\n set: function (value) {\n this._simplificationQueue = value;\n },\n enumerable: true,\n configurable: true,\n});\nMesh.prototype.simplify = function (settings, parallelProcessing = true, simplificationType = SimplificationType.QUADRATIC, successCallback) {\n this.getScene().simplificationQueue.addTask({\n settings: settings,\n parallelProcessing: parallelProcessing,\n mesh: this,\n simplificationType: simplificationType,\n successCallback: successCallback,\n });\n return this;\n};\n/**\n * Defines the simplification queue scene component responsible to help scheduling the various simplification task\n * created in a scene\n */\nexport class SimplicationQueueSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpfull to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;\n this.scene = scene;\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene._beforeCameraUpdateStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n // Nothing to do for this component\n }\n /**\n * Disposes the component and the associated resources\n */\n dispose() {\n // Nothing to do for this component\n }\n _beforeCameraUpdate() {\n if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {\n this.scene._simplificationQueue.executeNext();\n }\n }\n}\n//# sourceMappingURL=meshSimplificationSceneComponent.js.map","import { Curve3 } from \"../Maths/math.path.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { TmpVectors, Vector3 } from \"../Maths/math.vector.js\";\nimport { CreateTextShapePaths } from \"../Meshes/Builders/textBuilder.js\";\n/**\n * Tool functions for GreasedLine\n */\nexport class GreasedLineTools {\n /**\n * Gets mesh triangles as line positions\n * @param meshes array of meshes\n * @param omitZeroLengthLines do not generate a line when the distance if the vertices in the triangle equals to zero\n * @returns array of arrays of points\n */\n static MeshesToLines(meshes, omitZeroLengthLines = true) {\n const points = [];\n meshes.forEach((m) => {\n const vertices = m.getVerticesData(VertexBuffer.PositionKind);\n const indices = m.getIndices();\n if (vertices && indices) {\n for (let i = 0, ii = 0; i < indices.length; i++) {\n const vi1 = indices[ii++] * 3;\n const vi2 = indices[ii++] * 3;\n const vi3 = indices[ii++] * 3;\n const p1 = new Vector3(vertices[vi1], vertices[vi1 + 1], vertices[vi1 + 2]);\n const p2 = new Vector3(vertices[vi2], vertices[vi2 + 1], vertices[vi2 + 2]);\n const p3 = new Vector3(vertices[vi3], vertices[vi3 + 1], vertices[vi3 + 2]);\n if (omitZeroLengthLines && p1.lengthSquared() + p2.lengthSquared() + p3.lengthSquared() === 0) {\n continue;\n }\n points.push([p1, p2, p3, p1]);\n }\n }\n });\n return points;\n }\n /**\n * Converts number coordinates to Vector3s\n * @param points number array of x, y, z, x, y z, ... coordinates\n * @returns Vector3 array\n */\n static ToVector3Array(points) {\n const array = [];\n for (let i = 0; i < points.length; i += 3) {\n array.push(new Vector3(points[i], points[i + 1], points[i + 2]));\n }\n return array;\n }\n /**\n * Gets a number array from a Vector3 array.\n * You can you for example to convert your Vector3[] offsets to the required number[] for the offsets option.\n * @param points Vector3 array\n * @returns an array of x, y, z coordinates as numbers [x, y, z, x, y, z, x, y, z, ....]\n */\n static ToNumberArray(points) {\n return points.flatMap((v) => [v.x, v.y, v.z]);\n }\n /**\n * Calculates the sum of points of every line and the number of points in each line.\n * This function is useful when you are drawing multiple lines in one mesh and you want\n * to know the counts. For example for creating an offsets table.\n * @param points point array\n * @returns points count info\n */\n static GetPointsCountInfo(points) {\n const counts = new Array(points.length);\n let total = 0;\n for (let n = points.length; n--;) {\n counts[n] = points[n].length / 3;\n total += counts[n];\n }\n return { total, counts };\n }\n /**\n * Gets the length of the line counting all it's segments length\n * @param data array of line points\n * @returns length of the line\n */\n static GetLineLength(data) {\n if (data.length === 0) {\n return 0;\n }\n let points;\n if (typeof data[0] === \"number\") {\n points = GreasedLineTools.ToVector3Array(data);\n }\n else {\n points = data;\n }\n const tmp = TmpVectors.Vector3[0];\n let length = 0;\n for (let index = 0; index < points.length - 1; index++) {\n const point1 = points[index];\n const point2 = points[index + 1];\n length += point2.subtractToRef(point1, tmp).length();\n }\n return length;\n }\n /**\n * Divides a segment into smaller segments.\n * A segment is a part of the line between it's two points.\n * @param point1 first point of the line\n * @param point2 second point of the line\n * @param segmentCount number of segments we want to have in the divided line\n * @returns\n */\n static SegmentizeSegmentByCount(point1, point2, segmentCount) {\n const dividedLinePoints = [];\n const diff = point2.subtract(point1);\n const divisor = TmpVectors.Vector3[0];\n divisor.setAll(segmentCount);\n const segmentVector = TmpVectors.Vector3[1];\n diff.divideToRef(divisor, segmentVector);\n let nextPoint = point1.clone();\n dividedLinePoints.push(nextPoint);\n for (let index = 0; index < segmentCount; index++) {\n nextPoint = nextPoint.clone();\n dividedLinePoints.push(nextPoint.addInPlace(segmentVector));\n }\n return dividedLinePoints;\n }\n /**\n * Divides a line into segments.\n * A segment is a part of the line between it's two points.\n * @param what line points\n * @param segmentLength length of each segment of the resulting line (distance between two line points)\n * @returns line point\n */\n static SegmentizeLineBySegmentLength(what, segmentLength) {\n const subLines = what[0] instanceof Vector3 ? GreasedLineTools.GetLineSegments(what) : what;\n const points = [];\n subLines.forEach((s) => {\n if (s.length > segmentLength) {\n const segments = GreasedLineTools.SegmentizeSegmentByCount(s.point1, s.point2, Math.ceil(s.length / segmentLength));\n segments.forEach((seg) => {\n points.push(seg);\n });\n }\n else {\n points.push(s.point1);\n points.push(s.point2);\n }\n });\n return points;\n }\n /**\n * Divides a line into segments.\n * A segment is a part of the line between it's two points.\n * @param what line points\n * @param segmentCount number of segments\n * @returns line point\n */\n static SegmentizeLineBySegmentCount(what, segmentCount) {\n const segmentLength = GreasedLineTools.GetLineLength(what) / segmentCount;\n return GreasedLineTools.SegmentizeLineBySegmentLength(what, segmentLength);\n }\n /**\n * Gets line segments.\n * A segment is a part of the line between it's two points.\n * @param points line points\n * @returns segments information of the line segment including starting point, ending point and the distance between them\n */\n static GetLineSegments(points) {\n const segments = [];\n for (let index = 0; index < points.length - 1; index++) {\n const point1 = points[index];\n const point2 = points[index + 1];\n const length = point2.subtract(point1).length();\n segments.push({ point1, point2, length });\n }\n return segments;\n }\n /**\n * Gets the minimum and the maximum length of a line segment in the line.\n * A segment is a part of the line between it's two points.\n * @param points line points\n * @returns\n */\n static GetMinMaxSegmentLength(points) {\n const subLines = GreasedLineTools.GetLineSegments(points);\n const sorted = subLines.sort((s) => s.length);\n return {\n min: sorted[0].length,\n max: sorted[sorted.length - 1].length,\n };\n }\n /**\n * Finds the last visible position in world space of the line according to the visibility parameter\n * @param lineSegments segments of the line\n * @param lineLength total length of the line\n * @param visbility normalized value of visibility\n * @returns world space coordinate of the last visible piece of the line\n */\n static GetPositionOnLineByVisibility(lineSegments, lineLength, visbility, localSpace = false) {\n const lengthVisibilityRatio = lineLength * visbility;\n let sumSegmentLengths = 0;\n let segmentIndex = 0;\n const lineSegmentsLength = lineSegments.length;\n for (let i = 0; i < lineSegmentsLength; i++) {\n if (lengthVisibilityRatio <= sumSegmentLengths + lineSegments[i].length) {\n segmentIndex = i;\n break;\n }\n sumSegmentLengths += lineSegments[i].length;\n }\n const s = (lengthVisibilityRatio - sumSegmentLengths) / lineSegments[segmentIndex].length;\n lineSegments[segmentIndex].point2.subtractToRef(lineSegments[segmentIndex].point1, TmpVectors.Vector3[0]);\n TmpVectors.Vector3[1] = TmpVectors.Vector3[0].multiplyByFloats(s, s, s);\n if (!localSpace) {\n TmpVectors.Vector3[1].addInPlace(lineSegments[segmentIndex].point1);\n }\n return TmpVectors.Vector3[1].clone();\n }\n /**\n * Creates lines in a shape of circle/arc.\n * A segment is a part of the line between it's two points.\n * @param radiusX radiusX of the circle\n * @param segments number of segments in the circle\n * @param z z coordinate of the points. Defaults to 0.\n * @param radiusY radiusY of the circle - you can draw an oval if using different values\n * @param segmentAngle angle offset of the segments. Defaults to Math.PI * 2 / segments. Change this value to draw a part of the circle.\n * @returns line points\n */\n static GetCircleLinePoints(radiusX, segments, z = 0, radiusY = radiusX, segmentAngle = (Math.PI * 2) / segments) {\n const points = [];\n for (let i = 0; i <= segments; i++) {\n points.push(new Vector3(Math.cos(i * segmentAngle) * radiusX, Math.sin(i * segmentAngle) * radiusY, z));\n }\n return points;\n }\n /**\n * Gets line points in a shape of a bezier curve\n * @param p0 bezier point0\n * @param p1 bezier point1\n * @param p2 bezier point2\n * @param segments number of segments in the curve\n * @returns\n */\n static GetBezierLinePoints(p0, p1, p2, segments) {\n return Curve3.CreateQuadraticBezier(p0, p1, p2, segments)\n .getPoints()\n .flatMap((v) => [v.x, v.y, v.z]);\n }\n /**\n *\n * @param position position of the arrow cap (mainly you want to create a triangle, set widthUp and widthDown to the same value and omit widthStartUp and widthStartDown)\n * @param direction direction which the arrow points to\n * @param length length (size) of the arrow cap itself\n * @param widthUp the arrow width above the line\n * @param widthDown the arrow width belove the line\n * @param widthStartUp the arrow width at the start of the arrow above the line. In most scenarios this is 0.\n * @param widthStartDown the arrow width at the start of the arrow below the line. In most scenarios this is 0.\n * @returns\n */\n static GetArrowCap(position, direction, length, widthUp, widthDown, widthStartUp = 0, widthStartDown = 0) {\n const points = [position.clone(), position.add(direction.multiplyByFloats(length, length, length))];\n const widths = [widthUp, widthDown, widthStartUp, widthStartDown];\n return {\n points,\n widths,\n };\n }\n /**\n * Gets 3D positions of points from a text and font\n * @param text Text\n * @param size Size of the font\n * @param resolution Resolution of the font\n * @param fontData defines the font data (can be generated with http://gero3.github.io/facetype.js/)\n * @param z z coordinate\n * @param includeInner include the inner parts of the font in the result. Default true. If false, only the outlines will be returned.\n * @returns number[][] of 3D positions\n */\n static GetPointsFromText(text, size, resolution, fontData, z = 0, includeInner = true) {\n const allPoints = [];\n const shapePaths = CreateTextShapePaths(text, size, resolution, fontData);\n for (const sp of shapePaths) {\n for (const p of sp.paths) {\n const points = [];\n const points2d = p.getPoints();\n for (const p2d of points2d) {\n points.push(p2d.x, p2d.y, z);\n }\n allPoints.push(points);\n }\n if (includeInner) {\n for (const h of sp.holes) {\n const holes = [];\n const points2d = h.getPoints();\n for (const p2d of points2d) {\n holes.push(p2d.x, p2d.y, z);\n }\n allPoints.push(holes);\n }\n }\n }\n return allPoints;\n }\n}\n//# sourceMappingURL=greasedLineTools.js.map","import { Color3 } from \"../../Maths/math.color.js\";\nimport { GreasedLineMeshColorMode, GreasedLineMeshMaterialType, GreasedLinePluginMaterial } from \"../../Materials/greasedLinePluginMaterial.js\";\nimport { StandardMaterial } from \"./../../Materials/standardMaterial.js\";\nimport { PBRMaterial } from \"../../Materials/PBR/pbrMaterial.js\";\nimport { GreasedLineMesh } from \"../greasedLineMesh.js\";\nimport { EngineStore } from \"../../Engines/engineStore.js\";\nexport var GreasedLineMeshColorDistribution;\n(function (GreasedLineMeshColorDistribution) {\n GreasedLineMeshColorDistribution[GreasedLineMeshColorDistribution[\"COLOR_DISTRIBUTION_NONE\"] = 0] = \"COLOR_DISTRIBUTION_NONE\";\n GreasedLineMeshColorDistribution[GreasedLineMeshColorDistribution[\"COLOR_DISTRIBUTION_REPEAT\"] = 1] = \"COLOR_DISTRIBUTION_REPEAT\";\n GreasedLineMeshColorDistribution[GreasedLineMeshColorDistribution[\"COLOR_DISTRIBUTION_EVEN\"] = 2] = \"COLOR_DISTRIBUTION_EVEN\";\n GreasedLineMeshColorDistribution[GreasedLineMeshColorDistribution[\"COLOR_DISTRIBUTION_START\"] = 3] = \"COLOR_DISTRIBUTION_START\";\n GreasedLineMeshColorDistribution[GreasedLineMeshColorDistribution[\"COLOR_DISTRIBUTION_END\"] = 4] = \"COLOR_DISTRIBUTION_END\";\n GreasedLineMeshColorDistribution[GreasedLineMeshColorDistribution[\"COLOR_DISTRIBUTION_START_END\"] = 5] = \"COLOR_DISTRIBUTION_START_END\";\n})(GreasedLineMeshColorDistribution || (GreasedLineMeshColorDistribution = {}));\nexport var GreasedLineMeshWidthDistribution;\n(function (GreasedLineMeshWidthDistribution) {\n GreasedLineMeshWidthDistribution[GreasedLineMeshWidthDistribution[\"WIDTH_DISTRIBUTION_NONE\"] = 0] = \"WIDTH_DISTRIBUTION_NONE\";\n GreasedLineMeshWidthDistribution[GreasedLineMeshWidthDistribution[\"WIDTH_DISTRIBUTION_REPEAT\"] = 1] = \"WIDTH_DISTRIBUTION_REPEAT\";\n GreasedLineMeshWidthDistribution[GreasedLineMeshWidthDistribution[\"WIDTH_DISTRIBUTION_EVEN\"] = 2] = \"WIDTH_DISTRIBUTION_EVEN\";\n GreasedLineMeshWidthDistribution[GreasedLineMeshWidthDistribution[\"WIDTH_DISTRIBUTION_START\"] = 3] = \"WIDTH_DISTRIBUTION_START\";\n GreasedLineMeshWidthDistribution[GreasedLineMeshWidthDistribution[\"WIDTH_DISTRIBUTION_END\"] = 4] = \"WIDTH_DISTRIBUTION_END\";\n GreasedLineMeshWidthDistribution[GreasedLineMeshWidthDistribution[\"WIDTH_DISTRIBUTION_START_END\"] = 5] = \"WIDTH_DISTRIBUTION_START_END\";\n})(GreasedLineMeshWidthDistribution || (GreasedLineMeshWidthDistribution = {}));\n/**\n * Builder class for create GreasedLineMeshes\n */\n/**\n * Creates a new @see GreasedLinePluginMaterial\n * @param name name of the material\n * @param options material options @see GreasedLineMaterialOptions\n * @param scene scene or null to use the last scene\n * @returns StandardMaterial or PBRMaterial with the @see GreasedLinePluginMaterial attached to it\n */\nexport function CreateGreasedLineMaterial(name, options, scene) {\n scene = (scene !== null && scene !== void 0 ? scene : EngineStore.LastCreatedScene);\n const material = options.materialType === GreasedLineMeshMaterialType.MATERIAL_TYPE_PBR ? new PBRMaterial(name, scene) : new StandardMaterial(name, scene);\n new GreasedLinePluginMaterial(material, scene, options);\n return material;\n}\n/**\n * Creates a GreasedLine mesh\n * @param name name of the mesh\n * @param options options for the mesh\n * @param materialOptions material options for the mesh\n * @param scene scene where the mesh will be created\n * @returns instance of GreasedLineMesh\n */\nexport function CreateGreasedLine(name, options, materialOptions, scene) {\n var _a, _b, _c, _d, _e, _f;\n scene = (scene !== null && scene !== void 0 ? scene : EngineStore.LastCreatedScene);\n let instance;\n const allPoints = GreasedLineMesh.ConvertPoints(options.points);\n let length = 0;\n if (Array.isArray(allPoints[0])) {\n allPoints.forEach((points) => {\n length += points.length / 3;\n });\n }\n options.widthDistribution = (_a = options.widthDistribution) !== null && _a !== void 0 ? _a : GreasedLineMeshWidthDistribution.WIDTH_DISTRIBUTION_START;\n materialOptions = materialOptions !== null && materialOptions !== void 0 ? materialOptions : {\n color: Color3.White(),\n };\n materialOptions.createAndAssignMaterial = (_b = materialOptions.createAndAssignMaterial) !== null && _b !== void 0 ? _b : true;\n materialOptions.colorDistribution = (_c = materialOptions === null || materialOptions === void 0 ? void 0 : materialOptions.colorDistribution) !== null && _c !== void 0 ? _c : GreasedLineMeshColorDistribution.COLOR_DISTRIBUTION_START;\n const widths = CompleteGreasedLineWidthTable(length, (_d = options.widths) !== null && _d !== void 0 ? _d : [], options.widthDistribution);\n const colors = (materialOptions === null || materialOptions === void 0 ? void 0 : materialOptions.colors)\n ? CompleteGreasedLineColorTable(length, materialOptions.colors, materialOptions.colorDistribution, (_e = materialOptions.color) !== null && _e !== void 0 ? _e : Color3.White())\n : undefined;\n // create new mesh if instance is not defined\n if (!options.instance) {\n const initialGreasedLineOptions = {\n points: allPoints,\n updatable: options.updatable,\n widths,\n lazy: options.lazy,\n };\n instance = new GreasedLineMesh(name, scene, initialGreasedLineOptions);\n if (materialOptions) {\n const initialMaterialOptions = {\n materialType: materialOptions.materialType,\n dashCount: materialOptions.dashCount,\n dashOffset: materialOptions.dashOffset,\n dashRatio: materialOptions.dashRatio,\n resolution: materialOptions.resolution,\n sizeAttenuation: materialOptions.sizeAttenuation,\n useColors: materialOptions.useColors,\n useDash: materialOptions.useDash,\n visibility: materialOptions.visibility,\n width: materialOptions.width,\n color: materialOptions.color,\n colorMode: (_f = materialOptions.colorMode) !== null && _f !== void 0 ? _f : GreasedLineMeshColorMode.COLOR_MODE_SET,\n colorsSampling: materialOptions.colorsSampling,\n colorDistributionType: materialOptions.colorDistributionType,\n };\n if (colors) {\n initialMaterialOptions.colors = colors;\n }\n else if (!materialOptions.color) {\n // if we don't have a color table nor a color assign it a default white color\n initialMaterialOptions.color = Color3.White();\n }\n if (materialOptions.createAndAssignMaterial) {\n const material = materialOptions.materialType === GreasedLineMeshMaterialType.MATERIAL_TYPE_PBR ? new PBRMaterial(name, scene) : new StandardMaterial(name, scene);\n new GreasedLinePluginMaterial(material, scene, initialMaterialOptions);\n instance.material = material;\n }\n }\n }\n else {\n // update the data on the mesh instance\n instance = options.instance;\n const currentWidths = instance.options.widths;\n if (currentWidths) {\n const newWidths = [...currentWidths];\n newWidths.push(...widths);\n instance.setSegmentWidths(newWidths);\n }\n else {\n instance.setSegmentWidths(widths);\n }\n instance.options.instance = instance;\n instance.addPoints(allPoints);\n }\n // add colors\n // it will merge if any colors already on the instance\n if (colors && options.instance) {\n if (options.instance.material instanceof StandardMaterial || instance.material instanceof PBRMaterial) {\n if (options.instance.greasedLineMaterial) {\n const currentColors = options.instance.greasedLineMaterial.getOptions().colors;\n if (currentColors) {\n const newColors = currentColors.concat(colors);\n options.instance.greasedLineMaterial.setColors(newColors, instance.isLazy());\n }\n }\n }\n }\n return instance;\n}\n/**\n * Completes the width table/fills the missing entries. It means it creates a width entry for every point of the line mesh.\n * You can provide more points the widths when creating the mesh. This function will fill the empty entries.\n * The algorithm used to fill the empty entries can be\n * GreasedLineMeshWidthDistribution.REPEAT - the width table will be repeatedly copied to the empty values [wL, wU] = [wL, wU, wL, wU, wL, wU, wL, wU, ...]\n * GreasedLineMeshWidthDistribution.EVEN - the width table will be evenly copied to the empty values [wL, wU] = [wL, wL, wL, wL, wU, wU, wU, wU]\n * GreasedLineMeshWidthDistribution.START - the width table will be copied at the start of the empty values\n * and rest will be filled width the default width upper and default width lower values [wU, wL] = [wL, wU, dwL, dwU, dwL, dwU, dwL, dwU]\n * GreasedLineMeshWidthDistribution.END - the width table will be copied at the end of the empty values\n * and rest will be filled width the default values [wL, wU] = [wL, wU, dwL, dwU, dwL, dwU, wL, wU]\n * @param pointCount number of points of the line mesh\n * @param widths array of widths [widhtLower, widthUpper, widthLower, widthUpper ...]. Two widths (lower/upper) per point.\n * @param widthsDistribution how to distribute widths if the widths array has fewer entries than pointCount\n * @param defaultWidthUpper the default value which will be used to fill empty width entries - upper width\n * @param defaultWidthLower the default value which will be used to fill empty width entries - lower width\n * @returns completed width table.\n */\nexport function CompleteGreasedLineWidthTable(pointCount, widths, widthsDistribution, defaultWidthUpper = 1, defaultWidthLower = 1) {\n const missingCount = pointCount - widths.length / 2;\n const widthsData = [];\n if (missingCount < 0) {\n return widths.slice(0, pointCount * 2);\n }\n // is the width table shorter than the point table?\n if (missingCount > 0) {\n // it is, fill in the missing elements\n if (widthsDistribution === GreasedLineMeshWidthDistribution.WIDTH_DISTRIBUTION_START_END) {\n const halfCount = Math.floor(widths.length / 2);\n // start sector\n for (let i = 0, j = 0; i < halfCount - 1; i++) {\n widthsData.push(widths[j++]);\n widthsData.push(widths[j++]);\n }\n // middle sector\n const widthL = widths[halfCount / 2];\n const widthU = widths[halfCount / 2 + 1];\n for (let i = 0; i < missingCount; i++) {\n widthsData.push(widthU);\n widthsData.push(widthL);\n }\n // end sector\n for (let i = halfCount; i < widths.length; i += 2) {\n widthsData.push(widths[i]);\n widthsData.push(widths[i + 1]);\n }\n }\n else if (widthsDistribution === GreasedLineMeshWidthDistribution.WIDTH_DISTRIBUTION_START) {\n // start sector\n for (let i = 0; i < widths.length; i += 2) {\n widthsData.push(widths[i]);\n widthsData.push(widths[i + 1]);\n }\n // end sector\n for (let i = 0; i < missingCount; i++) {\n widthsData.push(defaultWidthUpper);\n widthsData.push(defaultWidthLower);\n }\n }\n else if (widthsDistribution === GreasedLineMeshWidthDistribution.WIDTH_DISTRIBUTION_END) {\n // start sector\n for (let i = 0; i < missingCount; i++) {\n widthsData.push(defaultWidthUpper);\n widthsData.push(defaultWidthLower);\n }\n // end sector\n for (let i = 0; i < widths.length; i += 2) {\n widthsData.push(widths[i]);\n widthsData.push(widths[i + 1]);\n }\n }\n else if (widthsDistribution === GreasedLineMeshWidthDistribution.WIDTH_DISTRIBUTION_REPEAT) {\n let i = 0;\n for (let x = 0; x < pointCount; x++) {\n widthsData.push(widths[i++]);\n widthsData.push(widths[i++]);\n if (i === widths.length) {\n i = 0;\n }\n }\n }\n else if (widthsDistribution === GreasedLineMeshWidthDistribution.WIDTH_DISTRIBUTION_EVEN) {\n let j = 0;\n const widthsectorLength = widths.length / ((pointCount - 1) * 2);\n for (let x = 0; x < pointCount; x++) {\n const i = Math.floor(j);\n widthsData.push(widths[i]);\n widthsData.push(widths[i + 1]);\n j += widthsectorLength;\n }\n }\n }\n else {\n for (let i = 0; i < widths.length; i++) {\n widthsData.push(widths[i]);\n }\n }\n return widthsData;\n}\n/**\n * Completes the color table/fill the missing color entries. It means it creates a color entry for every point of the line mesh.\n * You can provide more points the colors when creating the mesh. This function will fill the empty entries.\n * The algorithm used to fill the empty entries can be\n * GreasedLineMesColorhDistribution.REPEAT - the color table will be repeatedly copied to the empty values [c1, c2] = [c1, c2, c1, c2, c1, c2, c1, c2]\n * GreasedLineMesColorhDistribution.EVEN - the color table will be evenly copied to the empty values [c1, c2] = [c1, c1, c1, c1, c2, c2, c2, c2]\n * GreasedLineMesColorhDistribution.START - the color table will be copied at the start of the empty values\n * and rest will be filled color the default color value [c1, c2] = [c1, c2, dc, dc, dc, dc, dc, dc]\n * GreasedLineMesColorhDistribution.START_END - the color table will be copied at the start and the end of the empty values\n * and rest will be filled color the default color value [c1, c2] = [c1, c2, dc, dc, dc, dc, c1, c2]\n * @param pointCount number of points of the line mesh\n * @param colors array of Color3 for the color table\n * @param colorDistribution how to distribute colors if the colors array has fewer entries than pointCount\n * @param defaultColor default color to be used to fill empty entries in the color table\n * @returns completed array of Color3s\n */\nexport function CompleteGreasedLineColorTable(pointCount, colors, colorDistribution, defaultColor) {\n const missingCount = pointCount - colors.length;\n if (missingCount < 0) {\n return colors.slice(0, pointCount);\n }\n const colorsData = [];\n // is the color table shorter than the point table?\n if (missingCount > 0) {\n // it is, fill in the missing elements\n if (colorDistribution === GreasedLineMeshColorDistribution.COLOR_DISTRIBUTION_START_END) {\n const halfCount = Math.floor(colors.length / 2);\n // start sector\n for (let i = 0; i < halfCount; i++) {\n colorsData.push(colors[i]);\n }\n // middle sector\n for (let i = 0; i < missingCount - 1; i++) {\n colorsData.push(defaultColor);\n }\n // end sector\n for (let i = halfCount; i < colors.length; i++) {\n colorsData.push(colors[i]);\n }\n }\n else if (colorDistribution === GreasedLineMeshColorDistribution.COLOR_DISTRIBUTION_START) {\n // start sector\n for (let i = 0; i < colors.length; i++) {\n colorsData.push(colors[i]);\n }\n // end sector\n for (let i = 0; i < missingCount; i++) {\n colorsData.push(defaultColor);\n }\n }\n else if (colorDistribution === GreasedLineMeshColorDistribution.COLOR_DISTRIBUTION_END) {\n // start sector\n for (let i = 0; i < missingCount - 1; i++) {\n colorsData.push(defaultColor);\n }\n // end sector\n for (let i = 0; i < colors.length; i++) {\n colorsData.push(colors[i]);\n }\n }\n else if (colorDistribution === GreasedLineMeshColorDistribution.COLOR_DISTRIBUTION_REPEAT) {\n let i = 0;\n for (let x = 0; x < pointCount; x++) {\n colorsData.push(colors[i]);\n i++;\n if (i === colors.length) {\n i = 0;\n }\n }\n }\n else if (colorDistribution === GreasedLineMeshColorDistribution.COLOR_DISTRIBUTION_EVEN) {\n let j = 0;\n const colorSectorLength = colors.length / (pointCount - 1);\n for (let x = 0; x < pointCount - 1; x++) {\n const i = Math.floor(j);\n colorsData.push(colors[i]);\n j += colorSectorLength;\n }\n }\n else if (colorDistribution === GreasedLineMeshColorDistribution.COLOR_DISTRIBUTION_NONE) {\n for (let i = 0; i < colors.length; i++) {\n colorsData.push(colors[i]);\n }\n }\n }\n else {\n for (let i = 0; i < pointCount; i++) {\n colorsData.push(colors[i]);\n }\n }\n return colorsData;\n}\n//# sourceMappingURL=greasedLineBuilder.js.map","import { Mesh } from \"../Meshes/mesh.js\";\nimport { VertexBuffer, Buffer } from \"../Buffers/buffer.js\";\nimport { Matrix, Vector3, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { BoundingInfo } from \"../Culling/boundingInfo.js\";\nMesh.prototype.thinInstanceAdd = function (matrix, refresh = true) {\n if (!this.getScene().getEngine().getCaps().instancedArrays) {\n Logger.Error(\"Thin Instances are not supported on this device as Instanced Array extension not supported\");\n return -1;\n }\n this._thinInstanceUpdateBufferSize(\"matrix\", Array.isArray(matrix) ? matrix.length : 1);\n const index = this._thinInstanceDataStorage.instancesCount;\n if (Array.isArray(matrix)) {\n for (let i = 0; i < matrix.length; ++i) {\n this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++, matrix[i], i === matrix.length - 1 && refresh);\n }\n }\n else {\n this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++, matrix, refresh);\n }\n return index;\n};\nMesh.prototype.thinInstanceAddSelf = function (refresh = true) {\n return this.thinInstanceAdd(Matrix.IdentityReadOnly, refresh);\n};\nMesh.prototype.thinInstanceRegisterAttribute = function (kind, stride) {\n // preserve backward compatibility\n if (kind === VertexBuffer.ColorKind) {\n kind = VertexBuffer.ColorInstanceKind;\n }\n this.removeVerticesData(kind);\n this._thinInstanceInitializeUserStorage();\n this._userThinInstanceBuffersStorage.strides[kind] = stride;\n this._userThinInstanceBuffersStorage.sizes[kind] = stride * Math.max(32, this._thinInstanceDataStorage.instancesCount); // Initial size\n this._userThinInstanceBuffersStorage.data[kind] = new Float32Array(this._userThinInstanceBuffersStorage.sizes[kind]);\n this._userThinInstanceBuffersStorage.vertexBuffers[kind] = new VertexBuffer(this.getEngine(), this._userThinInstanceBuffersStorage.data[kind], kind, true, false, stride, true);\n this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[kind]);\n};\nMesh.prototype.thinInstanceSetMatrixAt = function (index, matrix, refresh = true) {\n if (!this._thinInstanceDataStorage.matrixData || index >= this._thinInstanceDataStorage.instancesCount) {\n return false;\n }\n const matrixData = this._thinInstanceDataStorage.matrixData;\n matrix.copyToArray(matrixData, index * 16);\n if (this._thinInstanceDataStorage.worldMatrices) {\n this._thinInstanceDataStorage.worldMatrices[index] = matrix;\n }\n if (refresh) {\n this.thinInstanceBufferUpdated(\"matrix\");\n if (!this.doNotSyncBoundingInfo) {\n this.thinInstanceRefreshBoundingInfo(false);\n }\n }\n return true;\n};\nMesh.prototype.thinInstanceSetAttributeAt = function (kind, index, value, refresh = true) {\n // preserve backward compatibility\n if (kind === VertexBuffer.ColorKind) {\n kind = VertexBuffer.ColorInstanceKind;\n }\n if (!this._userThinInstanceBuffersStorage || !this._userThinInstanceBuffersStorage.data[kind] || index >= this._thinInstanceDataStorage.instancesCount) {\n return false;\n }\n this._thinInstanceUpdateBufferSize(kind, 0); // make sur the buffer for the kind attribute is big enough\n this._userThinInstanceBuffersStorage.data[kind].set(value, index * this._userThinInstanceBuffersStorage.strides[kind]);\n if (refresh) {\n this.thinInstanceBufferUpdated(kind);\n }\n return true;\n};\nObject.defineProperty(Mesh.prototype, \"thinInstanceCount\", {\n get: function () {\n return this._thinInstanceDataStorage.instancesCount;\n },\n set: function (value) {\n var _a, _b;\n const matrixData = (_a = this._thinInstanceDataStorage.matrixData) !== null && _a !== void 0 ? _a : (_b = this.source) === null || _b === void 0 ? void 0 : _b._thinInstanceDataStorage.matrixData;\n const numMaxInstances = matrixData ? matrixData.length / 16 : 0;\n if (value <= numMaxInstances) {\n this._thinInstanceDataStorage.instancesCount = value;\n }\n },\n enumerable: true,\n configurable: true,\n});\nMesh.prototype._thinInstanceCreateMatrixBuffer = function (kind, buffer, staticBuffer = false) {\n // preserve backward compatibility\n if (kind === VertexBuffer.ColorKind) {\n kind = VertexBuffer.ColorInstanceKind;\n }\n const matrixBuffer = new Buffer(this.getEngine(), buffer, !staticBuffer, 16, false, true);\n for (let i = 0; i < 4; i++) {\n this.setVerticesBuffer(matrixBuffer.createVertexBuffer(kind + i, i * 4, 4));\n }\n return matrixBuffer;\n};\nMesh.prototype.thinInstanceSetBuffer = function (kind, buffer, stride = 0, staticBuffer = false) {\n var _a, _b, _c;\n stride = stride || 16;\n if (kind === \"matrix\") {\n (_a = this._thinInstanceDataStorage.matrixBuffer) === null || _a === void 0 ? void 0 : _a.dispose();\n this._thinInstanceDataStorage.matrixBuffer = null;\n this._thinInstanceDataStorage.matrixBufferSize = buffer ? buffer.length : 32 * stride;\n this._thinInstanceDataStorage.matrixData = buffer;\n this._thinInstanceDataStorage.worldMatrices = null;\n if (buffer !== null) {\n this._thinInstanceDataStorage.instancesCount = buffer.length / stride;\n this._thinInstanceDataStorage.matrixBuffer = this._thinInstanceCreateMatrixBuffer(\"world\", buffer, staticBuffer);\n if (!this.doNotSyncBoundingInfo) {\n this.thinInstanceRefreshBoundingInfo(false);\n }\n }\n else {\n this._thinInstanceDataStorage.instancesCount = 0;\n if (!this.doNotSyncBoundingInfo) {\n // mesh has no more thin instances, so need to recompute the bounding box because it's the regular mesh that will now be displayed\n this.refreshBoundingInfo();\n }\n }\n }\n else if (kind === \"previousMatrix\") {\n (_b = this._thinInstanceDataStorage.previousMatrixBuffer) === null || _b === void 0 ? void 0 : _b.dispose();\n this._thinInstanceDataStorage.previousMatrixBuffer = null;\n this._thinInstanceDataStorage.previousMatrixData = buffer;\n if (buffer !== null) {\n this._thinInstanceDataStorage.previousMatrixBuffer = this._thinInstanceCreateMatrixBuffer(\"previousWorld\", buffer, staticBuffer);\n }\n }\n else {\n // color for instanced mesh is ColorInstanceKind and not ColorKind because of native that needs to do the differenciation\n // hot switching kind here to preserve backward compatibility\n if (kind === VertexBuffer.ColorKind) {\n kind = VertexBuffer.ColorInstanceKind;\n }\n if (buffer === null) {\n if ((_c = this._userThinInstanceBuffersStorage) === null || _c === void 0 ? void 0 : _c.data[kind]) {\n this.removeVerticesData(kind);\n delete this._userThinInstanceBuffersStorage.data[kind];\n delete this._userThinInstanceBuffersStorage.strides[kind];\n delete this._userThinInstanceBuffersStorage.sizes[kind];\n delete this._userThinInstanceBuffersStorage.vertexBuffers[kind];\n }\n }\n else {\n this._thinInstanceInitializeUserStorage();\n this._userThinInstanceBuffersStorage.data[kind] = buffer;\n this._userThinInstanceBuffersStorage.strides[kind] = stride;\n this._userThinInstanceBuffersStorage.sizes[kind] = buffer.length;\n this._userThinInstanceBuffersStorage.vertexBuffers[kind] = new VertexBuffer(this.getEngine(), buffer, kind, !staticBuffer, false, stride, true);\n this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[kind]);\n }\n }\n};\nMesh.prototype.thinInstanceBufferUpdated = function (kind) {\n var _a, _b, _c;\n if (kind === \"matrix\") {\n (_a = this._thinInstanceDataStorage.matrixBuffer) === null || _a === void 0 ? void 0 : _a.updateDirectly(this._thinInstanceDataStorage.matrixData, 0, this._thinInstanceDataStorage.instancesCount);\n }\n else if (kind === \"previousMatrix\") {\n (_b = this._thinInstanceDataStorage.previousMatrixBuffer) === null || _b === void 0 ? void 0 : _b.updateDirectly(this._thinInstanceDataStorage.previousMatrixData, 0, this._thinInstanceDataStorage.instancesCount);\n }\n else {\n // preserve backward compatibility\n if (kind === VertexBuffer.ColorKind) {\n kind = VertexBuffer.ColorInstanceKind;\n }\n if ((_c = this._userThinInstanceBuffersStorage) === null || _c === void 0 ? void 0 : _c.vertexBuffers[kind]) {\n this._userThinInstanceBuffersStorage.vertexBuffers[kind].updateDirectly(this._userThinInstanceBuffersStorage.data[kind], 0);\n }\n }\n};\nMesh.prototype.thinInstancePartialBufferUpdate = function (kind, data, offset) {\n var _a;\n if (kind === \"matrix\") {\n if (this._thinInstanceDataStorage.matrixBuffer) {\n this._thinInstanceDataStorage.matrixBuffer.updateDirectly(data, offset);\n }\n }\n else {\n // preserve backward compatibility\n if (kind === VertexBuffer.ColorKind) {\n kind = VertexBuffer.ColorInstanceKind;\n }\n if ((_a = this._userThinInstanceBuffersStorage) === null || _a === void 0 ? void 0 : _a.vertexBuffers[kind]) {\n this._userThinInstanceBuffersStorage.vertexBuffers[kind].updateDirectly(data, offset);\n }\n }\n};\nMesh.prototype.thinInstanceGetWorldMatrices = function () {\n if (!this._thinInstanceDataStorage.matrixData || !this._thinInstanceDataStorage.matrixBuffer) {\n return [];\n }\n const matrixData = this._thinInstanceDataStorage.matrixData;\n if (!this._thinInstanceDataStorage.worldMatrices) {\n this._thinInstanceDataStorage.worldMatrices = new Array();\n for (let i = 0; i < this._thinInstanceDataStorage.instancesCount; ++i) {\n this._thinInstanceDataStorage.worldMatrices[i] = Matrix.FromArray(matrixData, i * 16);\n }\n }\n return this._thinInstanceDataStorage.worldMatrices;\n};\nMesh.prototype.thinInstanceRefreshBoundingInfo = function (forceRefreshParentInfo = false, applySkeleton = false, applyMorph = false) {\n if (!this._thinInstanceDataStorage.matrixData || !this._thinInstanceDataStorage.matrixBuffer) {\n return;\n }\n const vectors = this._thinInstanceDataStorage.boundingVectors;\n if (forceRefreshParentInfo || !this.rawBoundingInfo) {\n vectors.length = 0;\n this.refreshBoundingInfo(applySkeleton, applyMorph);\n const boundingInfo = this.getBoundingInfo();\n this.rawBoundingInfo = new BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);\n }\n const boundingInfo = this.getBoundingInfo();\n const matrixData = this._thinInstanceDataStorage.matrixData;\n if (vectors.length === 0) {\n for (let v = 0; v < boundingInfo.boundingBox.vectors.length; ++v) {\n vectors.push(boundingInfo.boundingBox.vectors[v].clone());\n }\n }\n TmpVectors.Vector3[0].setAll(Number.POSITIVE_INFINITY); // min\n TmpVectors.Vector3[1].setAll(Number.NEGATIVE_INFINITY); // max\n for (let i = 0; i < this._thinInstanceDataStorage.instancesCount; ++i) {\n Matrix.FromArrayToRef(matrixData, i * 16, TmpVectors.Matrix[0]);\n for (let v = 0; v < vectors.length; ++v) {\n Vector3.TransformCoordinatesToRef(vectors[v], TmpVectors.Matrix[0], TmpVectors.Vector3[2]);\n TmpVectors.Vector3[0].minimizeInPlace(TmpVectors.Vector3[2]);\n TmpVectors.Vector3[1].maximizeInPlace(TmpVectors.Vector3[2]);\n }\n }\n boundingInfo.reConstruct(TmpVectors.Vector3[0], TmpVectors.Vector3[1]);\n this._updateBoundingInfo();\n};\nMesh.prototype._thinInstanceUpdateBufferSize = function (kind, numInstances = 1) {\n var _a, _b, _c;\n // preserve backward compatibility\n if (kind === VertexBuffer.ColorKind) {\n kind = VertexBuffer.ColorInstanceKind;\n }\n const kindIsMatrix = kind === \"matrix\";\n if (!kindIsMatrix && (!this._userThinInstanceBuffersStorage || !this._userThinInstanceBuffersStorage.strides[kind])) {\n return;\n }\n const stride = kindIsMatrix ? 16 : this._userThinInstanceBuffersStorage.strides[kind];\n const currentSize = kindIsMatrix ? this._thinInstanceDataStorage.matrixBufferSize : this._userThinInstanceBuffersStorage.sizes[kind];\n let data = kindIsMatrix ? this._thinInstanceDataStorage.matrixData : this._userThinInstanceBuffersStorage.data[kind];\n const bufferSize = (this._thinInstanceDataStorage.instancesCount + numInstances) * stride;\n let newSize = currentSize;\n while (newSize < bufferSize) {\n newSize *= 2;\n }\n if (!data || currentSize != newSize) {\n if (!data) {\n data = new Float32Array(newSize);\n }\n else {\n const newData = new Float32Array(newSize);\n newData.set(data, 0);\n data = newData;\n }\n if (kindIsMatrix) {\n (_a = this._thinInstanceDataStorage.matrixBuffer) === null || _a === void 0 ? void 0 : _a.dispose();\n this._thinInstanceDataStorage.matrixBuffer = this._thinInstanceCreateMatrixBuffer(\"world\", data, false);\n this._thinInstanceDataStorage.matrixData = data;\n this._thinInstanceDataStorage.matrixBufferSize = newSize;\n if (this._scene.needsPreviousWorldMatrices && !this._thinInstanceDataStorage.previousMatrixData) {\n (_b = this._thinInstanceDataStorage.previousMatrixBuffer) === null || _b === void 0 ? void 0 : _b.dispose();\n this._thinInstanceDataStorage.previousMatrixBuffer = this._thinInstanceCreateMatrixBuffer(\"previousWorld\", data, false);\n }\n }\n else {\n (_c = this._userThinInstanceBuffersStorage.vertexBuffers[kind]) === null || _c === void 0 ? void 0 : _c.dispose();\n this._userThinInstanceBuffersStorage.data[kind] = data;\n this._userThinInstanceBuffersStorage.sizes[kind] = newSize;\n this._userThinInstanceBuffersStorage.vertexBuffers[kind] = new VertexBuffer(this.getEngine(), data, kind, true, false, stride, true);\n this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[kind]);\n }\n }\n};\nMesh.prototype._thinInstanceInitializeUserStorage = function () {\n if (!this._userThinInstanceBuffersStorage) {\n this._userThinInstanceBuffersStorage = {\n data: {},\n sizes: {},\n vertexBuffers: {},\n strides: {},\n };\n }\n};\nMesh.prototype._disposeThinInstanceSpecificData = function () {\n var _a;\n if ((_a = this._thinInstanceDataStorage) === null || _a === void 0 ? void 0 : _a.matrixBuffer) {\n this._thinInstanceDataStorage.matrixBuffer.dispose();\n this._thinInstanceDataStorage.matrixBuffer = null;\n }\n};\n//# sourceMappingURL=thinInstanceMesh.js.map","export {};\n//# sourceMappingURL=INavigationEngine.js.map","import { Logger } from \"../../Misc/logger.js\";\nimport { VertexData } from \"../../Meshes/mesh.vertexData.js\";\nimport { Mesh } from \"../../Meshes/mesh.js\";\nimport { Epsilon, Vector3, Matrix } from \"../../Maths/math.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { VertexBuffer } from \"../../Buffers/buffer.js\";\n/**\n * RecastJS navigation plugin\n */\nexport class RecastJSPlugin {\n /**\n * Initializes the recastJS plugin\n * @param recastInjection can be used to inject your own recast reference\n */\n constructor(recastInjection = Recast) {\n /**\n * Reference to the Recast library\n */\n this.bjsRECAST = {};\n /**\n * plugin name\n */\n this.name = \"RecastJSPlugin\";\n this._maximumSubStepCount = 10;\n this._timeStep = 1 / 60;\n this._timeFactor = 1;\n this._worker = null;\n if (typeof recastInjection === \"function\") {\n Logger.Error(\"RecastJS is not ready. Please make sure you await Recast() before using the plugin.\");\n }\n else {\n this.bjsRECAST = recastInjection;\n }\n if (!this.isSupported()) {\n Logger.Error(\"RecastJS is not available. Please make sure you included the js file.\");\n return;\n }\n this.setTimeStep();\n this._tempVec1 = new this.bjsRECAST.Vec3();\n this._tempVec2 = new this.bjsRECAST.Vec3();\n }\n /**\n * Set worker URL to be used when generating a new navmesh\n * @param workerURL url string\n * @returns boolean indicating if worker is created\n */\n setWorkerURL(workerURL) {\n if (window && window.Worker) {\n this._worker = new Worker(workerURL);\n return true;\n }\n return false;\n }\n /**\n * Set the time step of the navigation tick update.\n * Default is 1/60.\n * A value of 0 will disable fixed time update\n * @param newTimeStep the new timestep to apply to this world.\n */\n setTimeStep(newTimeStep = 1 / 60) {\n this._timeStep = newTimeStep;\n }\n /**\n * Get the time step of the navigation tick update.\n * @returns the current time step\n */\n getTimeStep() {\n return this._timeStep;\n }\n /**\n * If delta time in navigation tick update is greater than the time step\n * a number of sub iterations are done. If more iterations are need to reach deltatime\n * they will be discarded.\n * A value of 0 will set to no maximum and update will use as many substeps as needed\n * @param newStepCount the maximum number of iterations\n */\n setMaximumSubStepCount(newStepCount = 10) {\n this._maximumSubStepCount = newStepCount;\n }\n /**\n * Get the maximum number of iterations per navigation tick update\n * @returns the maximum number of iterations\n */\n getMaximumSubStepCount() {\n return this._maximumSubStepCount;\n }\n /**\n * Time factor applied when updating crowd agents (default 1). A value of 0 will pause crowd updates.\n * @param value the time factor applied at update\n */\n set timeFactor(value) {\n this._timeFactor = Math.max(value, 0);\n }\n /**\n * Get the time factor used for crowd agent update\n * @returns the time factor\n */\n get timeFactor() {\n return this._timeFactor;\n }\n /**\n * Creates a navigation mesh\n * @param meshes array of all the geometry used to compute the navigation mesh\n * @param parameters bunch of parameters used to filter geometry\n * @param completion callback when data is available from the worker. Not used without a worker\n */\n createNavMesh(meshes, parameters, completion) {\n if (this._worker && !completion) {\n console.warn(\"A worker is avaible but no completion callback. Defaulting to blocking navmesh creation\");\n }\n else if (!this._worker && completion) {\n console.warn(\"A completion callback is avaible but no worker. Defaulting to blocking navmesh creation\");\n }\n this.navMesh = new this.bjsRECAST.NavMesh();\n let index;\n let tri;\n let pt;\n const indices = [];\n const positions = [];\n let offset = 0;\n for (index = 0; index < meshes.length; index++) {\n if (meshes[index]) {\n const mesh = meshes[index];\n const meshIndices = mesh.getIndices();\n if (!meshIndices) {\n continue;\n }\n const meshPositions = mesh.getVerticesData(VertexBuffer.PositionKind, false, false);\n if (!meshPositions) {\n continue;\n }\n const worldMatrices = [];\n const worldMatrix = mesh.computeWorldMatrix(true);\n if (mesh.hasThinInstances) {\n const thinMatrices = mesh.thinInstanceGetWorldMatrices();\n for (let instanceIndex = 0; instanceIndex < thinMatrices.length; instanceIndex++) {\n const tmpMatrix = new Matrix();\n const thinMatrix = thinMatrices[instanceIndex];\n thinMatrix.multiplyToRef(worldMatrix, tmpMatrix);\n worldMatrices.push(tmpMatrix);\n }\n }\n else {\n worldMatrices.push(worldMatrix);\n }\n for (let matrixIndex = 0; matrixIndex < worldMatrices.length; matrixIndex++) {\n const wm = worldMatrices[matrixIndex];\n for (tri = 0; tri < meshIndices.length; tri++) {\n indices.push(meshIndices[tri] + offset);\n }\n const transformed = Vector3.Zero();\n const position = Vector3.Zero();\n for (pt = 0; pt < meshPositions.length; pt += 3) {\n Vector3.FromArrayToRef(meshPositions, pt, position);\n Vector3.TransformCoordinatesToRef(position, wm, transformed);\n positions.push(transformed.x, transformed.y, transformed.z);\n }\n offset += meshPositions.length / 3;\n }\n }\n }\n if (this._worker && completion) {\n // spawn worker and send message\n this._worker.postMessage([positions, offset, indices, indices.length, parameters]);\n this._worker.onmessage = function (e) {\n completion(e.data);\n };\n }\n else {\n // blocking calls\n const rc = new this.bjsRECAST.rcConfig();\n rc.cs = parameters.cs;\n rc.ch = parameters.ch;\n rc.borderSize = parameters.borderSize ? parameters.borderSize : 0;\n rc.tileSize = parameters.tileSize ? parameters.tileSize : 0;\n rc.walkableSlopeAngle = parameters.walkableSlopeAngle;\n rc.walkableHeight = parameters.walkableHeight;\n rc.walkableClimb = parameters.walkableClimb;\n rc.walkableRadius = parameters.walkableRadius;\n rc.maxEdgeLen = parameters.maxEdgeLen;\n rc.maxSimplificationError = parameters.maxSimplificationError;\n rc.minRegionArea = parameters.minRegionArea;\n rc.mergeRegionArea = parameters.mergeRegionArea;\n rc.maxVertsPerPoly = parameters.maxVertsPerPoly;\n rc.detailSampleDist = parameters.detailSampleDist;\n rc.detailSampleMaxError = parameters.detailSampleMaxError;\n this.navMesh.build(positions, offset, indices, indices.length, rc);\n }\n }\n /**\n * Create a navigation mesh debug mesh\n * @param scene is where the mesh will be added\n * @returns debug display mesh\n */\n createDebugNavMesh(scene) {\n let tri;\n let pt;\n const debugNavMesh = this.navMesh.getDebugNavMesh();\n const triangleCount = debugNavMesh.getTriangleCount();\n const indices = [];\n const positions = [];\n for (tri = 0; tri < triangleCount * 3; tri++) {\n indices.push(tri);\n }\n for (tri = 0; tri < triangleCount; tri++) {\n for (pt = 0; pt < 3; pt++) {\n const point = debugNavMesh.getTriangle(tri).getPoint(pt);\n positions.push(point.x, point.y, point.z);\n }\n }\n const mesh = new Mesh(\"NavMeshDebug\", scene);\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.applyToMesh(mesh, false);\n return mesh;\n }\n /**\n * Get a navigation mesh constrained position, closest to the parameter position\n * @param position world position\n * @returns the closest point to position constrained by the navigation mesh\n */\n getClosestPoint(position) {\n this._tempVec1.x = position.x;\n this._tempVec1.y = position.y;\n this._tempVec1.z = position.z;\n const ret = this.navMesh.getClosestPoint(this._tempVec1);\n const pr = new Vector3(ret.x, ret.y, ret.z);\n return pr;\n }\n /**\n * Get a navigation mesh constrained position, closest to the parameter position\n * @param position world position\n * @param result output the closest point to position constrained by the navigation mesh\n */\n getClosestPointToRef(position, result) {\n this._tempVec1.x = position.x;\n this._tempVec1.y = position.y;\n this._tempVec1.z = position.z;\n const ret = this.navMesh.getClosestPoint(this._tempVec1);\n result.set(ret.x, ret.y, ret.z);\n }\n /**\n * Get a navigation mesh constrained position, within a particular radius\n * @param position world position\n * @param maxRadius the maximum distance to the constrained world position\n * @returns the closest point to position constrained by the navigation mesh\n */\n getRandomPointAround(position, maxRadius) {\n this._tempVec1.x = position.x;\n this._tempVec1.y = position.y;\n this._tempVec1.z = position.z;\n const ret = this.navMesh.getRandomPointAround(this._tempVec1, maxRadius);\n const pr = new Vector3(ret.x, ret.y, ret.z);\n return pr;\n }\n /**\n * Get a navigation mesh constrained position, within a particular radius\n * @param position world position\n * @param maxRadius the maximum distance to the constrained world position\n * @param result output the closest point to position constrained by the navigation mesh\n */\n getRandomPointAroundToRef(position, maxRadius, result) {\n this._tempVec1.x = position.x;\n this._tempVec1.y = position.y;\n this._tempVec1.z = position.z;\n const ret = this.navMesh.getRandomPointAround(this._tempVec1, maxRadius);\n result.set(ret.x, ret.y, ret.z);\n }\n /**\n * Compute the final position from a segment made of destination-position\n * @param position world position\n * @param destination world position\n * @returns the resulting point along the navmesh\n */\n moveAlong(position, destination) {\n this._tempVec1.x = position.x;\n this._tempVec1.y = position.y;\n this._tempVec1.z = position.z;\n this._tempVec2.x = destination.x;\n this._tempVec2.y = destination.y;\n this._tempVec2.z = destination.z;\n const ret = this.navMesh.moveAlong(this._tempVec1, this._tempVec2);\n const pr = new Vector3(ret.x, ret.y, ret.z);\n return pr;\n }\n /**\n * Compute the final position from a segment made of destination-position\n * @param position world position\n * @param destination world position\n * @param result output the resulting point along the navmesh\n */\n moveAlongToRef(position, destination, result) {\n this._tempVec1.x = position.x;\n this._tempVec1.y = position.y;\n this._tempVec1.z = position.z;\n this._tempVec2.x = destination.x;\n this._tempVec2.y = destination.y;\n this._tempVec2.z = destination.z;\n const ret = this.navMesh.moveAlong(this._tempVec1, this._tempVec2);\n result.set(ret.x, ret.y, ret.z);\n }\n /**\n * Compute a navigation path from start to end. Returns an empty array if no path can be computed\n * @param start world position\n * @param end world position\n * @returns array containing world position composing the path\n */\n computePath(start, end) {\n let pt;\n this._tempVec1.x = start.x;\n this._tempVec1.y = start.y;\n this._tempVec1.z = start.z;\n this._tempVec2.x = end.x;\n this._tempVec2.y = end.y;\n this._tempVec2.z = end.z;\n const navPath = this.navMesh.computePath(this._tempVec1, this._tempVec2);\n const pointCount = navPath.getPointCount();\n const positions = [];\n for (pt = 0; pt < pointCount; pt++) {\n const p = navPath.getPoint(pt);\n positions.push(new Vector3(p.x, p.y, p.z));\n }\n return positions;\n }\n /**\n * Create a new Crowd so you can add agents\n * @param maxAgents the maximum agent count in the crowd\n * @param maxAgentRadius the maximum radius an agent can have\n * @param scene to attach the crowd to\n * @returns the crowd you can add agents to\n */\n createCrowd(maxAgents, maxAgentRadius, scene) {\n const crowd = new RecastJSCrowd(this, maxAgents, maxAgentRadius, scene);\n return crowd;\n }\n /**\n * Set the Bounding box extent for doing spatial queries (getClosestPoint, getRandomPointAround, ...)\n * The queries will try to find a solution within those bounds\n * default is (1,1,1)\n * @param extent x,y,z value that define the extent around the queries point of reference\n */\n setDefaultQueryExtent(extent) {\n this._tempVec1.x = extent.x;\n this._tempVec1.y = extent.y;\n this._tempVec1.z = extent.z;\n this.navMesh.setDefaultQueryExtent(this._tempVec1);\n }\n /**\n * Get the Bounding box extent specified by setDefaultQueryExtent\n * @returns the box extent values\n */\n getDefaultQueryExtent() {\n const p = this.navMesh.getDefaultQueryExtent();\n return new Vector3(p.x, p.y, p.z);\n }\n /**\n * build the navmesh from a previously saved state using getNavmeshData\n * @param data the Uint8Array returned by getNavmeshData\n */\n buildFromNavmeshData(data) {\n const nDataBytes = data.length * data.BYTES_PER_ELEMENT;\n const dataPtr = this.bjsRECAST._malloc(nDataBytes);\n const dataHeap = new Uint8Array(this.bjsRECAST.HEAPU8.buffer, dataPtr, nDataBytes);\n dataHeap.set(data);\n const buf = new this.bjsRECAST.NavmeshData();\n buf.dataPointer = dataHeap.byteOffset;\n buf.size = data.length;\n this.navMesh = new this.bjsRECAST.NavMesh();\n this.navMesh.buildFromNavmeshData(buf);\n // Free memory\n this.bjsRECAST._free(dataHeap.byteOffset);\n }\n /**\n * returns the navmesh data that can be used later. The navmesh must be built before retrieving the data\n * @returns data the Uint8Array that can be saved and reused\n */\n getNavmeshData() {\n const navmeshData = this.navMesh.getNavmeshData();\n const arrView = new Uint8Array(this.bjsRECAST.HEAPU8.buffer, navmeshData.dataPointer, navmeshData.size);\n const ret = new Uint8Array(navmeshData.size);\n ret.set(arrView);\n this.navMesh.freeNavmeshData(navmeshData);\n return ret;\n }\n /**\n * Get the Bounding box extent result specified by setDefaultQueryExtent\n * @param result output the box extent values\n */\n getDefaultQueryExtentToRef(result) {\n const p = this.navMesh.getDefaultQueryExtent();\n result.set(p.x, p.y, p.z);\n }\n /**\n * Disposes\n */\n dispose() { }\n /**\n * Creates a cylinder obstacle and add it to the navigation\n * @param position world position\n * @param radius cylinder radius\n * @param height cylinder height\n * @returns the obstacle freshly created\n */\n addCylinderObstacle(position, radius, height) {\n this._tempVec1.x = position.x;\n this._tempVec1.y = position.y;\n this._tempVec1.z = position.z;\n return this.navMesh.addCylinderObstacle(this._tempVec1, radius, height);\n }\n /**\n * Creates an oriented box obstacle and add it to the navigation\n * @param position world position\n * @param extent box size\n * @param angle angle in radians of the box orientation on Y axis\n * @returns the obstacle freshly created\n */\n addBoxObstacle(position, extent, angle) {\n this._tempVec1.x = position.x;\n this._tempVec1.y = position.y;\n this._tempVec1.z = position.z;\n this._tempVec2.x = extent.x;\n this._tempVec2.y = extent.y;\n this._tempVec2.z = extent.z;\n return this.navMesh.addBoxObstacle(this._tempVec1, this._tempVec2, angle);\n }\n /**\n * Removes an obstacle created by addCylinderObstacle or addBoxObstacle\n * @param obstacle obstacle to remove from the navigation\n */\n removeObstacle(obstacle) {\n this.navMesh.removeObstacle(obstacle);\n }\n /**\n * If this plugin is supported\n * @returns true if plugin is supported\n */\n isSupported() {\n return this.bjsRECAST !== undefined;\n }\n}\n/**\n * Recast detour crowd implementation\n */\nexport class RecastJSCrowd {\n /**\n * Constructor\n * @param plugin recastJS plugin\n * @param maxAgents the maximum agent count in the crowd\n * @param maxAgentRadius the maximum radius an agent can have\n * @param scene to attach the crowd to\n * @returns the crowd you can add agents to\n */\n constructor(plugin, maxAgents, maxAgentRadius, scene) {\n /**\n * Link to the detour crowd\n */\n this.recastCrowd = {};\n /**\n * One transform per agent\n */\n this.transforms = new Array();\n /**\n * All agents created\n */\n this.agents = new Array();\n /**\n * agents reach radius\n */\n this.reachRadii = new Array();\n /**\n * true when a destination is active for an agent and notifier hasn't been notified of reach\n */\n this._agentDestinationArmed = new Array();\n /**\n * agent current target\n */\n this._agentDestination = new Array();\n /**\n * Observer for crowd updates\n */\n this._onBeforeAnimationsObserver = null;\n /**\n * Fires each time an agent is in reach radius of its destination\n */\n this.onReachTargetObservable = new Observable();\n this.bjsRECASTPlugin = plugin;\n this.recastCrowd = new this.bjsRECASTPlugin.bjsRECAST.Crowd(maxAgents, maxAgentRadius, this.bjsRECASTPlugin.navMesh.getNavMesh());\n this._scene = scene;\n this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(() => {\n this.update(scene.getEngine().getDeltaTime() * 0.001 * plugin.timeFactor);\n });\n }\n /**\n * Add a new agent to the crowd with the specified parameter a corresponding transformNode.\n * You can attach anything to that node. The node position is updated in the scene update tick.\n * @param pos world position that will be constrained by the navigation mesh\n * @param parameters agent parameters\n * @param transform hooked to the agent that will be update by the scene\n * @returns agent index\n */\n addAgent(pos, parameters, transform) {\n const agentParams = new this.bjsRECASTPlugin.bjsRECAST.dtCrowdAgentParams();\n agentParams.radius = parameters.radius;\n agentParams.height = parameters.height;\n agentParams.maxAcceleration = parameters.maxAcceleration;\n agentParams.maxSpeed = parameters.maxSpeed;\n agentParams.collisionQueryRange = parameters.collisionQueryRange;\n agentParams.pathOptimizationRange = parameters.pathOptimizationRange;\n agentParams.separationWeight = parameters.separationWeight;\n agentParams.updateFlags = 7;\n agentParams.obstacleAvoidanceType = 0;\n agentParams.queryFilterType = 0;\n agentParams.userData = 0;\n const agentIndex = this.recastCrowd.addAgent(new this.bjsRECASTPlugin.bjsRECAST.Vec3(pos.x, pos.y, pos.z), agentParams);\n this.transforms.push(transform);\n this.agents.push(agentIndex);\n this.reachRadii.push(parameters.reachRadius ? parameters.reachRadius : parameters.radius);\n this._agentDestinationArmed.push(false);\n this._agentDestination.push(new Vector3(0, 0, 0));\n return agentIndex;\n }\n /**\n * Returns the agent position in world space\n * @param index agent index returned by addAgent\n * @returns world space position\n */\n getAgentPosition(index) {\n const agentPos = this.recastCrowd.getAgentPosition(index);\n return new Vector3(agentPos.x, agentPos.y, agentPos.z);\n }\n /**\n * Returns the agent position result in world space\n * @param index agent index returned by addAgent\n * @param result output world space position\n */\n getAgentPositionToRef(index, result) {\n const agentPos = this.recastCrowd.getAgentPosition(index);\n result.set(agentPos.x, agentPos.y, agentPos.z);\n }\n /**\n * Returns the agent velocity in world space\n * @param index agent index returned by addAgent\n * @returns world space velocity\n */\n getAgentVelocity(index) {\n const agentVel = this.recastCrowd.getAgentVelocity(index);\n return new Vector3(agentVel.x, agentVel.y, agentVel.z);\n }\n /**\n * Returns the agent velocity result in world space\n * @param index agent index returned by addAgent\n * @param result output world space velocity\n */\n getAgentVelocityToRef(index, result) {\n const agentVel = this.recastCrowd.getAgentVelocity(index);\n result.set(agentVel.x, agentVel.y, agentVel.z);\n }\n /**\n * Returns the agent next target point on the path\n * @param index agent index returned by addAgent\n * @returns world space position\n */\n getAgentNextTargetPath(index) {\n const pathTargetPos = this.recastCrowd.getAgentNextTargetPath(index);\n return new Vector3(pathTargetPos.x, pathTargetPos.y, pathTargetPos.z);\n }\n /**\n * Returns the agent next target point on the path\n * @param index agent index returned by addAgent\n * @param result output world space position\n */\n getAgentNextTargetPathToRef(index, result) {\n const pathTargetPos = this.recastCrowd.getAgentNextTargetPath(index);\n result.set(pathTargetPos.x, pathTargetPos.y, pathTargetPos.z);\n }\n /**\n * Gets the agent state\n * @param index agent index returned by addAgent\n * @returns agent state\n */\n getAgentState(index) {\n return this.recastCrowd.getAgentState(index);\n }\n /**\n * returns true if the agent in over an off mesh link connection\n * @param index agent index returned by addAgent\n * @returns true if over an off mesh link connection\n */\n overOffmeshConnection(index) {\n return this.recastCrowd.overOffmeshConnection(index);\n }\n /**\n * Asks a particular agent to go to a destination. That destination is constrained by the navigation mesh\n * @param index agent index returned by addAgent\n * @param destination targeted world position\n */\n agentGoto(index, destination) {\n this.recastCrowd.agentGoto(index, new this.bjsRECASTPlugin.bjsRECAST.Vec3(destination.x, destination.y, destination.z));\n // arm observer\n const item = this.agents.indexOf(index);\n if (item > -1) {\n this._agentDestinationArmed[item] = true;\n this._agentDestination[item].set(destination.x, destination.y, destination.z);\n }\n }\n /**\n * Teleport the agent to a new position\n * @param index agent index returned by addAgent\n * @param destination targeted world position\n */\n agentTeleport(index, destination) {\n this.recastCrowd.agentTeleport(index, new this.bjsRECASTPlugin.bjsRECAST.Vec3(destination.x, destination.y, destination.z));\n }\n /**\n * Update agent parameters\n * @param index agent index returned by addAgent\n * @param parameters agent parameters\n */\n updateAgentParameters(index, parameters) {\n const agentParams = this.recastCrowd.getAgentParameters(index);\n if (parameters.radius !== undefined) {\n agentParams.radius = parameters.radius;\n }\n if (parameters.height !== undefined) {\n agentParams.height = parameters.height;\n }\n if (parameters.maxAcceleration !== undefined) {\n agentParams.maxAcceleration = parameters.maxAcceleration;\n }\n if (parameters.maxSpeed !== undefined) {\n agentParams.maxSpeed = parameters.maxSpeed;\n }\n if (parameters.collisionQueryRange !== undefined) {\n agentParams.collisionQueryRange = parameters.collisionQueryRange;\n }\n if (parameters.pathOptimizationRange !== undefined) {\n agentParams.pathOptimizationRange = parameters.pathOptimizationRange;\n }\n if (parameters.separationWeight !== undefined) {\n agentParams.separationWeight = parameters.separationWeight;\n }\n this.recastCrowd.setAgentParameters(index, agentParams);\n }\n /**\n * remove a particular agent previously created\n * @param index agent index returned by addAgent\n */\n removeAgent(index) {\n this.recastCrowd.removeAgent(index);\n const item = this.agents.indexOf(index);\n if (item > -1) {\n this.agents.splice(item, 1);\n this.transforms.splice(item, 1);\n this.reachRadii.splice(item, 1);\n this._agentDestinationArmed.splice(item, 1);\n this._agentDestination.splice(item, 1);\n }\n }\n /**\n * get the list of all agents attached to this crowd\n * @returns list of agent indices\n */\n getAgents() {\n return this.agents;\n }\n /**\n * Tick update done by the Scene. Agent position/velocity/acceleration is updated by this function\n * @param deltaTime in seconds\n */\n update(deltaTime) {\n // update obstacles\n this.bjsRECASTPlugin.navMesh.update();\n if (deltaTime <= Epsilon) {\n return;\n }\n // update crowd\n const timeStep = this.bjsRECASTPlugin.getTimeStep();\n const maxStepCount = this.bjsRECASTPlugin.getMaximumSubStepCount();\n if (timeStep <= Epsilon) {\n this.recastCrowd.update(deltaTime);\n }\n else {\n let iterationCount = Math.floor(deltaTime / timeStep);\n if (maxStepCount && iterationCount > maxStepCount) {\n iterationCount = maxStepCount;\n }\n if (iterationCount < 1) {\n iterationCount = 1;\n }\n const step = deltaTime / iterationCount;\n for (let i = 0; i < iterationCount; i++) {\n this.recastCrowd.update(step);\n }\n }\n // update transforms\n for (let index = 0; index < this.agents.length; index++) {\n // update transform position\n const agentIndex = this.agents[index];\n const agentPosition = this.getAgentPosition(agentIndex);\n this.transforms[index].position = agentPosition;\n // check agent reach destination\n if (this._agentDestinationArmed[index]) {\n const dx = agentPosition.x - this._agentDestination[index].x;\n const dz = agentPosition.z - this._agentDestination[index].z;\n const radius = this.reachRadii[index];\n const groundY = this._agentDestination[index].y - this.reachRadii[index];\n const ceilingY = this._agentDestination[index].y + this.reachRadii[index];\n const distanceXZSquared = dx * dx + dz * dz;\n if (agentPosition.y > groundY && agentPosition.y < ceilingY && distanceXZSquared < radius * radius) {\n this.onReachTargetObservable.notifyObservers({ agentIndex: agentIndex, destination: this._agentDestination[index] });\n this._agentDestinationArmed[index] = false;\n }\n }\n }\n }\n /**\n * Set the Bounding box extent for doing spatial queries (getClosestPoint, getRandomPointAround, ...)\n * The queries will try to find a solution within those bounds\n * default is (1,1,1)\n * @param extent x,y,z value that define the extent around the queries point of reference\n */\n setDefaultQueryExtent(extent) {\n const ext = new this.bjsRECASTPlugin.bjsRECAST.Vec3(extent.x, extent.y, extent.z);\n this.recastCrowd.setDefaultQueryExtent(ext);\n }\n /**\n * Get the Bounding box extent specified by setDefaultQueryExtent\n * @returns the box extent values\n */\n getDefaultQueryExtent() {\n const p = this.recastCrowd.getDefaultQueryExtent();\n return new Vector3(p.x, p.y, p.z);\n }\n /**\n * Get the Bounding box extent result specified by setDefaultQueryExtent\n * @param result output the box extent values\n */\n getDefaultQueryExtentToRef(result) {\n const p = this.recastCrowd.getDefaultQueryExtent();\n result.set(p.x, p.y, p.z);\n }\n /**\n * Get the next corner points composing the path (max 4 points)\n * @param index agent index returned by addAgent\n * @returns array containing world position composing the path\n */\n getCorners(index) {\n let pt;\n const navPath = this.recastCrowd.getCorners(index);\n const pointCount = navPath.getPointCount();\n const positions = [];\n for (pt = 0; pt < pointCount; pt++) {\n const p = navPath.getPoint(pt);\n positions.push(new Vector3(p.x, p.y, p.z));\n }\n return positions;\n }\n /**\n * Release all resources\n */\n dispose() {\n this.recastCrowd.destroy();\n this._scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);\n this._onBeforeAnimationsObserver = null;\n this.onReachTargetObservable.clear();\n }\n}\n//# sourceMappingURL=recastJSPlugin.js.map","import { Tools } from \"../Misc/tools.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { GetTGAHeader } from \"../Misc/tga.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { WebRequest } from \"../Misc/webRequest.js\";\n// Sets the default offline provider to Babylon.js\nEngine.OfflineProviderFactory = (urlToScene, callbackManifestChecked, disableManifestCheck = false) => {\n return new Database(urlToScene, callbackManifestChecked, disableManifestCheck);\n};\n/**\n * Class used to enable access to IndexedDB\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimizeCached\n */\nexport class Database {\n /**\n * Gets a boolean indicating if scene must be saved in the database\n */\n get enableSceneOffline() {\n return this._enableSceneOffline;\n }\n /**\n * Gets a boolean indicating if textures must be saved in the database\n */\n get enableTexturesOffline() {\n return this._enableTexturesOffline;\n }\n /**\n * Creates a new Database\n * @param urlToScene defines the url to load the scene\n * @param callbackManifestChecked defines the callback to use when manifest is checked\n * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)\n */\n constructor(urlToScene, callbackManifestChecked, disableManifestCheck = false) {\n // Handling various flavors of prefixed version of IndexedDB\n this._idbFactory = (typeof indexedDB !== \"undefined\" ? indexedDB : undefined);\n this._currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);\n this._db = null;\n this._enableSceneOffline = false;\n this._enableTexturesOffline = false;\n this._manifestVersionFound = 0;\n this._mustUpdateRessources = false;\n this._hasReachedQuota = false;\n if (!Database.IDBStorageEnabled) {\n callbackManifestChecked(true);\n }\n else {\n if (disableManifestCheck) {\n this._enableSceneOffline = true;\n this._enableTexturesOffline = true;\n this._manifestVersionFound = 1;\n Tools.SetImmediate(() => {\n callbackManifestChecked(true);\n });\n }\n else {\n this._checkManifestFile(callbackManifestChecked);\n }\n }\n }\n _checkManifestFile(callbackManifestChecked) {\n const noManifestFile = () => {\n this._enableSceneOffline = false;\n this._enableTexturesOffline = false;\n callbackManifestChecked(false);\n };\n const createManifestURL = () => {\n try {\n // make sure we have a valid URL.\n if (typeof URL === \"function\" && this._currentSceneUrl.indexOf(\"http\") === 0) {\n // we don't have the base url, so the URL string must have a protocol\n const url = new URL(this._currentSceneUrl);\n url.pathname += \".manifest\";\n return url.toString();\n }\n }\n catch (e) {\n // defensive - if this fails for any reason, fall back to the older method\n }\n return `${this._currentSceneUrl}.manifest`;\n };\n let timeStampUsed = false;\n let manifestURL = createManifestURL();\n const xhr = new WebRequest();\n if (navigator.onLine) {\n // Adding a timestamp to by-pass browsers' cache\n timeStampUsed = true;\n manifestURL = manifestURL + (manifestURL.match(/\\?/) == null ? \"?\" : \"&\") + Date.now();\n }\n xhr.open(\"GET\", manifestURL);\n xhr.addEventListener(\"load\", () => {\n if (xhr.status === 200 || Database._ValidateXHRData(xhr, 1)) {\n try {\n const manifestFile = JSON.parse(xhr.response);\n this._enableSceneOffline = manifestFile.enableSceneOffline;\n this._enableTexturesOffline = manifestFile.enableTexturesOffline && Database._IsUASupportingBlobStorage;\n if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {\n this._manifestVersionFound = manifestFile.version;\n }\n callbackManifestChecked(true);\n }\n catch (ex) {\n noManifestFile();\n }\n }\n else {\n noManifestFile();\n }\n }, false);\n xhr.addEventListener(\"error\", () => {\n if (timeStampUsed) {\n timeStampUsed = false;\n // Let's retry without the timeStamp\n // It could fail when coupled with HTML5 Offline API\n const retryManifestURL = createManifestURL();\n xhr.open(\"GET\", retryManifestURL);\n xhr.send();\n }\n else {\n noManifestFile();\n }\n }, false);\n try {\n xhr.send();\n }\n catch (ex) {\n Logger.Error(\"Error on XHR send request.\");\n callbackManifestChecked(false);\n }\n }\n /**\n * Open the database and make it available\n * @param successCallback defines the callback to call on success\n * @param errorCallback defines the callback to call on error\n */\n open(successCallback, errorCallback) {\n const handleError = () => {\n this._isSupported = false;\n if (errorCallback) {\n errorCallback();\n }\n };\n if (!this._idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {\n // Your browser doesn't support IndexedDB\n this._isSupported = false;\n if (errorCallback) {\n errorCallback();\n }\n }\n else {\n // If the DB hasn't been opened or created yet\n if (!this._db) {\n this._hasReachedQuota = false;\n this._isSupported = true;\n const request = this._idbFactory.open(\"babylonjs\", 1);\n // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB\n request.onerror = () => {\n handleError();\n };\n // executes when a version change transaction cannot complete due to other active transactions\n request.onblocked = () => {\n Logger.Error(\"IDB request blocked. Please reload the page.\");\n handleError();\n };\n // DB has been opened successfully\n request.onsuccess = () => {\n this._db = request.result;\n successCallback();\n };\n // Initialization of the DB. Creating Scenes & Textures stores\n request.onupgradeneeded = (event) => {\n this._db = event.target.result;\n if (this._db) {\n try {\n this._db.createObjectStore(\"scenes\", { keyPath: \"sceneUrl\" });\n this._db.createObjectStore(\"versions\", { keyPath: \"sceneUrl\" });\n this._db.createObjectStore(\"textures\", { keyPath: \"textureUrl\" });\n }\n catch (ex) {\n Logger.Error(\"Error while creating object stores. Exception: \" + ex.message);\n handleError();\n }\n }\n };\n }\n // DB has already been created and opened\n else {\n if (successCallback) {\n successCallback();\n }\n }\n }\n }\n /**\n * Loads an image from the database\n * @param url defines the url to load from\n * @param image defines the target DOM image\n */\n loadImage(url, image) {\n const completeURL = Database._ReturnFullUrlLocation(url);\n const saveAndLoadImage = () => {\n if (!this._hasReachedQuota && this._db !== null) {\n // the texture is not yet in the DB, let's try to save it\n this._saveImageIntoDBAsync(completeURL, image);\n }\n // If the texture is not in the DB and we've reached the DB quota limit\n // let's load it directly from the web\n else {\n image.src = url;\n }\n };\n if (!this._mustUpdateRessources) {\n this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);\n }\n // First time we're download the images or update requested in the manifest file by a version change\n else {\n saveAndLoadImage();\n }\n }\n _loadImageFromDBAsync(url, image, notInDBCallback) {\n if (this._isSupported && this._db !== null) {\n let texture;\n const transaction = this._db.transaction([\"textures\"]);\n transaction.onabort = () => {\n image.src = url;\n };\n transaction.oncomplete = () => {\n let blobTextureURL;\n if (texture && typeof URL === \"function\") {\n blobTextureURL = URL.createObjectURL(texture.data);\n image.onerror = () => {\n Logger.Error(\"Error loading image from blob URL: \" + blobTextureURL + \" switching back to web url: \" + url);\n image.src = url;\n };\n image.src = blobTextureURL;\n }\n else {\n notInDBCallback();\n }\n };\n const getRequest = transaction.objectStore(\"textures\").get(url);\n getRequest.onsuccess = (event) => {\n texture = event.target.result;\n };\n getRequest.onerror = () => {\n Logger.Error(\"Error loading texture \" + url + \" from DB.\");\n image.src = url;\n };\n }\n else {\n Logger.Error(\"Error: IndexedDB not supported by your browser or BabylonJS Database is not open.\");\n image.src = url;\n }\n }\n _saveImageIntoDBAsync(url, image) {\n let blob;\n if (this._isSupported) {\n // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on\n const generateBlobUrl = () => {\n let blobTextureURL;\n if (blob && typeof URL === \"function\") {\n try {\n blobTextureURL = URL.createObjectURL(blob);\n }\n catch (ex) {\n // Chrome is raising a type error if we're setting the oneTimeOnly parameter\n blobTextureURL = URL.createObjectURL(blob);\n }\n }\n if (blobTextureURL) {\n image.src = blobTextureURL;\n }\n };\n if (Database._IsUASupportingBlobStorage) {\n // Create XHR\n const xhr = new WebRequest();\n xhr.open(\"GET\", url);\n xhr.responseType = \"blob\";\n xhr.addEventListener(\"load\", () => {\n if (xhr.status === 200 && this._db) {\n // Blob as response\n blob = xhr.response;\n const transaction = this._db.transaction([\"textures\"], \"readwrite\");\n // the transaction could abort because of a QuotaExceededError error\n transaction.onabort = (event) => {\n try {\n //backwards compatibility with ts 1.0, srcElement doesn't have an \"error\" according to ts 1.3\n const srcElement = event.target;\n const error = srcElement.error;\n if (error && error.name === \"QuotaExceededError\") {\n this._hasReachedQuota = true;\n }\n }\n catch (ex) { }\n generateBlobUrl();\n };\n transaction.oncomplete = () => {\n generateBlobUrl();\n };\n const newTexture = { textureUrl: url, data: blob };\n try {\n // Put the blob into the dabase\n const addRequest = transaction.objectStore(\"textures\").put(newTexture);\n addRequest.onsuccess = () => { };\n addRequest.onerror = () => {\n generateBlobUrl();\n };\n }\n catch (ex) {\n // \"DataCloneError\" generated by Chrome when you try to inject blob into IndexedDB\n if (ex.code === 25) {\n Database._IsUASupportingBlobStorage = false;\n this._enableTexturesOffline = false;\n }\n image.src = url;\n }\n }\n else {\n image.src = url;\n }\n }, false);\n xhr.addEventListener(\"error\", () => {\n Logger.Error(\"Error in XHR request in BABYLON.Database.\");\n image.src = url;\n }, false);\n xhr.send();\n }\n else {\n image.src = url;\n }\n }\n else {\n Logger.Error(\"Error: IndexedDB not supported by your browser or Babylon.js database is not open.\");\n image.src = url;\n }\n }\n _checkVersionFromDB(url, versionLoaded) {\n const updateVersion = () => {\n // the version is not yet in the DB or we need to update it\n this._saveVersionIntoDBAsync(url, versionLoaded);\n };\n this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);\n }\n _loadVersionFromDBAsync(url, callback, updateInDBCallback) {\n if (this._isSupported && this._db) {\n let version;\n try {\n const transaction = this._db.transaction([\"versions\"]);\n transaction.oncomplete = () => {\n if (version) {\n // If the version in the JSON file is different from the version in DB\n if (this._manifestVersionFound !== version.data) {\n this._mustUpdateRessources = true;\n updateInDBCallback();\n }\n else {\n callback(version.data);\n }\n }\n // version was not found in DB\n else {\n this._mustUpdateRessources = true;\n updateInDBCallback();\n }\n };\n transaction.onabort = () => {\n callback(-1);\n };\n const getRequest = transaction.objectStore(\"versions\").get(url);\n getRequest.onsuccess = (event) => {\n version = event.target.result;\n };\n getRequest.onerror = () => {\n Logger.Error(\"Error loading version for scene \" + url + \" from DB.\");\n callback(-1);\n };\n }\n catch (ex) {\n Logger.Error(\"Error while accessing 'versions' object store (READ OP). Exception: \" + ex.message);\n callback(-1);\n }\n }\n else {\n Logger.Error(\"Error: IndexedDB not supported by your browser or Babylon.js database is not open.\");\n callback(-1);\n }\n }\n _saveVersionIntoDBAsync(url, callback) {\n if (this._isSupported && !this._hasReachedQuota && this._db) {\n try {\n // Open a transaction to the database\n const transaction = this._db.transaction([\"versions\"], \"readwrite\");\n // the transaction could abort because of a QuotaExceededError error\n transaction.onabort = (event) => {\n try {\n //backwards compatibility with ts 1.0, srcElement doesn't have an \"error\" according to ts 1.3\n const error = event.target[\"error\"];\n if (error && error.name === \"QuotaExceededError\") {\n this._hasReachedQuota = true;\n }\n }\n catch (ex) { }\n callback(-1);\n };\n transaction.oncomplete = () => {\n callback(this._manifestVersionFound);\n };\n const newVersion = { sceneUrl: url, data: this._manifestVersionFound };\n // Put the scene into the database\n const addRequest = transaction.objectStore(\"versions\").put(newVersion);\n addRequest.onsuccess = () => { };\n addRequest.onerror = () => {\n Logger.Error(\"Error in DB add version request in BABYLON.Database.\");\n };\n }\n catch (ex) {\n Logger.Error(\"Error while accessing 'versions' object store (WRITE OP). Exception: \" + ex.message);\n callback(-1);\n }\n }\n else {\n callback(-1);\n }\n }\n /**\n * Loads a file from database\n * @param url defines the URL to load from\n * @param sceneLoaded defines a callback to call on success\n * @param progressCallBack defines a callback to call when progress changed\n * @param errorCallback defines a callback to call on error\n * @param useArrayBuffer defines a boolean to use array buffer instead of text string\n */\n loadFile(url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {\n const completeUrl = Database._ReturnFullUrlLocation(url);\n const saveAndLoadFile = () => {\n // the scene is not yet in the DB, let's try to save it\n this._saveFileAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);\n };\n this._checkVersionFromDB(completeUrl, (version) => {\n if (version !== -1) {\n if (!this._mustUpdateRessources) {\n this._loadFileAsync(completeUrl, sceneLoaded, saveAndLoadFile);\n }\n else {\n this._saveFileAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);\n }\n }\n else {\n if (errorCallback) {\n errorCallback();\n }\n }\n });\n }\n _loadFileAsync(url, callback, notInDBCallback) {\n if (this._isSupported && this._db) {\n let targetStore;\n if (url.indexOf(\".babylon\") !== -1) {\n targetStore = \"scenes\";\n }\n else {\n targetStore = \"textures\";\n }\n let file;\n const transaction = this._db.transaction([targetStore]);\n transaction.oncomplete = () => {\n if (file) {\n callback(file.data);\n }\n // file was not found in DB\n else {\n notInDBCallback();\n }\n };\n transaction.onabort = () => {\n notInDBCallback();\n };\n const getRequest = transaction.objectStore(targetStore).get(url);\n getRequest.onsuccess = (event) => {\n file = event.target.result;\n };\n getRequest.onerror = () => {\n Logger.Error(\"Error loading file \" + url + \" from DB.\");\n notInDBCallback();\n };\n }\n else {\n Logger.Error(\"Error: IndexedDB not supported by your browser or BabylonJS Database is not open.\");\n callback();\n }\n }\n _saveFileAsync(url, callback, progressCallback, useArrayBuffer, errorCallback) {\n if (this._isSupported) {\n let targetStore;\n if (url.indexOf(\".babylon\") !== -1) {\n targetStore = \"scenes\";\n }\n else {\n targetStore = \"textures\";\n }\n // Create XHR\n const xhr = new WebRequest();\n let fileData;\n xhr.open(\"GET\", url + (url.match(/\\?/) == null ? \"?\" : \"&\") + Date.now());\n if (useArrayBuffer) {\n xhr.responseType = \"arraybuffer\";\n }\n if (progressCallback) {\n xhr.onprogress = progressCallback;\n }\n xhr.addEventListener(\"load\", () => {\n if (xhr.status === 200 || (xhr.status < 400 && Database._ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {\n // Blob as response\n fileData = !useArrayBuffer ? xhr.responseText : xhr.response;\n if (!this._hasReachedQuota && this._db) {\n // Open a transaction to the database\n const transaction = this._db.transaction([targetStore], \"readwrite\");\n // the transaction could abort because of a QuotaExceededError error\n transaction.onabort = (event) => {\n try {\n //backwards compatibility with ts 1.0, srcElement doesn't have an \"error\" according to ts 1.3\n const error = event.target[\"error\"];\n if (error && error.name === \"QuotaExceededError\") {\n this._hasReachedQuota = true;\n }\n }\n catch (ex) { }\n callback(fileData);\n };\n transaction.oncomplete = () => {\n callback(fileData);\n };\n let newFile;\n if (targetStore === \"scenes\") {\n newFile = { sceneUrl: url, data: fileData, version: this._manifestVersionFound };\n }\n else {\n newFile = { textureUrl: url, data: fileData };\n }\n try {\n // Put the scene into the database\n const addRequest = transaction.objectStore(targetStore).put(newFile);\n addRequest.onsuccess = () => { };\n addRequest.onerror = () => {\n Logger.Error(\"Error in DB add file request in BABYLON.Database.\");\n };\n }\n catch (ex) {\n callback(fileData);\n }\n }\n else {\n callback(fileData);\n }\n }\n else {\n if (xhr.status >= 400 && errorCallback) {\n errorCallback(xhr);\n }\n else {\n callback();\n }\n }\n }, false);\n xhr.addEventListener(\"error\", () => {\n Logger.Error(\"error on XHR request.\");\n errorCallback && errorCallback();\n }, false);\n xhr.send();\n }\n else {\n Logger.Error(\"Error: IndexedDB not supported by your browser or Babylon.js database is not open.\");\n errorCallback && errorCallback();\n }\n }\n /**\n * Validates if xhr data is correct\n * @param xhr defines the request to validate\n * @param dataType defines the expected data type\n * @returns true if data is correct\n */\n static _ValidateXHRData(xhr, dataType = 7) {\n // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all\n try {\n if (dataType & 1) {\n if (xhr.responseText && xhr.responseText.length > 0) {\n return true;\n }\n else if (dataType === 1) {\n return false;\n }\n }\n if (dataType & 2) {\n // Check header width and height since there is no \"TGA\" magic number\n const tgaHeader = GetTGAHeader(xhr.response);\n if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {\n return true;\n }\n else if (dataType === 2) {\n return false;\n }\n }\n if (dataType & 4) {\n // Check for the \"DDS\" magic number\n const ddsHeader = new Uint8Array(xhr.response, 0, 3);\n if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {\n return true;\n }\n else {\n return false;\n }\n }\n }\n catch (e) {\n // Global protection\n }\n return false;\n }\n}\n/** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */\nDatabase._IsUASupportingBlobStorage = true;\n/**\n * Gets a boolean indicating if Database storage is enabled (off by default)\n */\nDatabase.IDBStorageEnabled = false;\nDatabase._ParseURL = (url) => {\n const a = document.createElement(\"a\");\n a.href = url;\n const urlWithoutHash = url.substring(0, url.lastIndexOf(\"#\"));\n const fileName = url.substring(urlWithoutHash.lastIndexOf(\"/\") + 1, url.length);\n const absLocation = url.substring(0, url.indexOf(fileName, 0));\n return absLocation;\n};\nDatabase._ReturnFullUrlLocation = (url) => {\n if (url.indexOf(\"http:/\") === -1 && url.indexOf(\"https:/\") === -1 && typeof window !== \"undefined\") {\n return Database._ParseURL(window.location.href) + url;\n }\n else {\n return url;\n }\n};\n//# sourceMappingURL=database.js.map","/** @internal */\nexport class UniformBufferEffectCommonAccessor {\n _isUbo(uboOrEffect) {\n return uboOrEffect.addUniform !== undefined;\n }\n constructor(uboOrEffect) {\n if (this._isUbo(uboOrEffect)) {\n this.setMatrix3x3 = uboOrEffect.updateMatrix3x3.bind(uboOrEffect);\n this.setMatrix2x2 = uboOrEffect.updateMatrix2x2.bind(uboOrEffect);\n this.setFloat = uboOrEffect.updateFloat.bind(uboOrEffect);\n this.setFloat2 = uboOrEffect.updateFloat2.bind(uboOrEffect);\n this.setFloat3 = uboOrEffect.updateFloat3.bind(uboOrEffect);\n this.setFloat4 = uboOrEffect.updateFloat4.bind(uboOrEffect);\n this.setFloatArray = uboOrEffect.updateFloatArray.bind(uboOrEffect);\n this.setArray = uboOrEffect.updateArray.bind(uboOrEffect);\n this.setIntArray = uboOrEffect.updateIntArray.bind(uboOrEffect);\n this.setMatrix = uboOrEffect.updateMatrix.bind(uboOrEffect);\n this.setMatrices = uboOrEffect.updateMatrices.bind(uboOrEffect);\n this.setVector3 = uboOrEffect.updateVector3.bind(uboOrEffect);\n this.setVector4 = uboOrEffect.updateVector4.bind(uboOrEffect);\n this.setColor3 = uboOrEffect.updateColor3.bind(uboOrEffect);\n this.setColor4 = uboOrEffect.updateColor4.bind(uboOrEffect);\n this.setDirectColor4 = uboOrEffect.updateDirectColor4.bind(uboOrEffect);\n this.setInt = uboOrEffect.updateInt.bind(uboOrEffect);\n this.setInt2 = uboOrEffect.updateInt2.bind(uboOrEffect);\n this.setInt3 = uboOrEffect.updateInt3.bind(uboOrEffect);\n this.setInt4 = uboOrEffect.updateInt4.bind(uboOrEffect);\n }\n else {\n this.setMatrix3x3 = uboOrEffect.setMatrix3x3.bind(uboOrEffect);\n this.setMatrix2x2 = uboOrEffect.setMatrix2x2.bind(uboOrEffect);\n this.setFloat = uboOrEffect.setFloat.bind(uboOrEffect);\n this.setFloat2 = uboOrEffect.setFloat2.bind(uboOrEffect);\n this.setFloat3 = uboOrEffect.setFloat3.bind(uboOrEffect);\n this.setFloat4 = uboOrEffect.setFloat4.bind(uboOrEffect);\n this.setFloatArray = uboOrEffect.setFloatArray.bind(uboOrEffect);\n this.setArray = uboOrEffect.setArray.bind(uboOrEffect);\n this.setIntArray = uboOrEffect.setIntArray.bind(uboOrEffect);\n this.setMatrix = uboOrEffect.setMatrix.bind(uboOrEffect);\n this.setMatrices = uboOrEffect.setMatrices.bind(uboOrEffect);\n this.setVector3 = uboOrEffect.setVector3.bind(uboOrEffect);\n this.setVector4 = uboOrEffect.setVector4.bind(uboOrEffect);\n this.setColor3 = uboOrEffect.setColor3.bind(uboOrEffect);\n this.setColor4 = uboOrEffect.setColor4.bind(uboOrEffect);\n this.setDirectColor4 = uboOrEffect.setDirectColor4.bind(uboOrEffect);\n this.setInt = uboOrEffect.setInt.bind(uboOrEffect);\n this.setInt2 = uboOrEffect.setInt2.bind(uboOrEffect);\n this.setInt3 = uboOrEffect.setInt3.bind(uboOrEffect);\n this.setInt4 = uboOrEffect.setInt4.bind(uboOrEffect);\n }\n }\n}\n//# sourceMappingURL=uniformBufferEffectCommonAccessor.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"gpuUpdateParticlesPixelShader\";\nconst shader = `#version 300 es\nvoid main() {\rdiscard;\r}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const gpuUpdateParticlesPixelShader = { name, shader };\n//# sourceMappingURL=gpuUpdateParticles.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"gpuUpdateParticlesVertexShader\";\nconst shader = `#version 300 es\n#define PI 3.14159\nuniform float currentCount;\runiform float timeDelta;\runiform float stopFactor;\r#ifndef LOCAL\nuniform mat4 emitterWM;\r#endif\nuniform vec2 lifeTime;\runiform vec2 emitPower;\runiform vec2 sizeRange;\runiform vec4 scaleRange;\r#ifndef COLORGRADIENTS\nuniform vec4 color1;\runiform vec4 color2;\r#endif\nuniform vec3 gravity;\runiform sampler2D randomSampler;\runiform sampler2D randomSampler2;\runiform vec4 angleRange;\r#ifdef BOXEMITTER\nuniform vec3 direction1;\runiform vec3 direction2;\runiform vec3 minEmitBox;\runiform vec3 maxEmitBox;\r#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\runiform vec3 direction2;\r#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\runiform float radiusRange;\runiform float directionRandomizer;\r#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\runiform float radiusRange;\r#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\runiform vec3 direction2;\r#else\nuniform float directionRandomizer;\r#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\runiform float height;\runiform float radiusRange;\r#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\runiform vec3 direction2;\r#else\nuniform float directionRandomizer;\r#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\runiform float coneAngle;\runiform vec2 height;\runiform float directionRandomizer;\r#endif\nin vec3 position;\r#ifdef CUSTOMEMITTER\nin vec3 initialPosition;\r#endif\nin float age;\rin float life;\rin vec4 seed;\rin vec3 size;\r#ifndef COLORGRADIENTS\nin vec4 color;\r#endif\nin vec3 direction;\r#ifndef BILLBOARD\nin vec3 initialDirection;\r#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\r#else\nin vec2 angle;\r#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\r#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\r#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;\rin vec3 noiseCoordinates2;\r#endif\nout vec3 outPosition;\r#ifdef CUSTOMEMITTER\nout vec3 outInitialPosition;\r#endif\nout float outAge;\rout float outLife;\rout vec4 outSeed;\rout vec3 outSize;\r#ifndef COLORGRADIENTS\nout vec4 outColor;\r#endif\nout vec3 outDirection;\r#ifndef BILLBOARD\nout vec3 outInitialDirection;\r#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\r#else\nout vec2 outAngle;\r#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\r#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\r#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;\rout vec3 outNoiseCoordinates2;\r#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\r#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\r#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\r#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\runiform float limitVelocityDamping;\r#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\r#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\runiform sampler2D noiseSampler;\r#endif\n#ifdef ANIMATESHEET\nuniform vec4 cellInfos;\r#endif\nvec3 getRandomVec3(float offset) {\rreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\r}\rvec4 getRandomVec4(float offset) {\rreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\r}\rvoid main() {\rfloat newAge=age+timeDelta; \rif (newAge>=life && stopFactor != 0.) {\rvec3 newPosition;\rvec3 newDirection;\rvec4 randoms=getRandomVec4(seed.x);\routLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\routAge=newAge-life;\routSeed=seed;\r#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\r#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\r#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\routSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \r#ifndef COLORGRADIENTS\noutColor=color1+(color2-color1)*randoms.b;\r#endif\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\routAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\r#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\r#endif \n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\rvec3 randoms3=getRandomVec3(seed.z);\rnewPosition=vec3(0,0,0);\rnewDirection=direction1+(direction2-direction1)*randoms3;\r#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\rvec3 randoms3=getRandomVec3(seed.z);\rnewPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\rnewDirection=direction1+(direction2-direction1)*randoms3; \r#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\rvec3 randoms3=getRandomVec3(seed.z);\rfloat phi=2.0*PI*randoms2.x;\rfloat theta=acos(2.0*randoms2.y-1.0);\rfloat randX=cos(phi)*sin(theta);\rfloat randY=cos(theta);\rfloat randZ=sin(phi)*sin(theta);\rnewPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\rnewDirection=newPosition+directionRandomizer*randoms3; \r#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\rvec3 randoms3=getRandomVec3(seed.z);\rfloat phi=2.0*PI*randoms2.x;\rfloat theta=acos(2.0*randoms2.y-1.0);\rfloat randX=cos(phi)*sin(theta);\rfloat randY=cos(theta);\rfloat randZ=sin(phi)*sin(theta);\rnewPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\r#ifdef DIRECTEDSPHEREEMITTER\nnewDirection=normalize(direction1+(direction2-direction1)*randoms3);\r#else\nnewDirection=normalize(newPosition+directionRandomizer*randoms3);\r#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\rvec3 randoms3=getRandomVec3(seed.z);\rfloat yPos=(randoms2.x-0.5)*height;\rfloat angle=randoms2.y*PI*2.;\rfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\rfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\rfloat xPos=positionRadius*cos(angle);\rfloat zPos=positionRadius*sin(angle);\rnewPosition=vec3(xPos,yPos,zPos);\r#ifdef DIRECTEDCYLINDEREMITTER\nnewDirection=direction1+(direction2-direction1)*randoms3;\r#else\nangle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;\rnewDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));\rnewDirection=normalize(newDirection);\r#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\rfloat s=2.0*PI*randoms2.x;\r#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.0001;\r#else\nfloat h=randoms2.y*height.y;\rh=1.-h*h; \r#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\rlRadius=lRadius*h;\rfloat randX=lRadius*sin(s);\rfloat randZ=lRadius*cos(s);\rfloat randY=h *height.x;\rnewPosition=vec3(randX,randY,randZ); \rif (abs(cos(coneAngle))==1.0) {\rnewDirection=vec3(0.,1.0,0.);\r} else {\rvec3 randoms3=getRandomVec3(seed.z);\rnewDirection=normalize(newPosition+directionRandomizer*randoms3); \r}\r#elif defined(CUSTOMEMITTER)\nnewPosition=initialPosition;\routInitialPosition=initialPosition;\r#else \nnewPosition=vec3(0.,0.,0.);\rnewDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\r#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\r#ifdef LOCAL\noutPosition=newPosition;\r#else\noutPosition=(emitterWM*vec4(newPosition,1.)).xyz;\r#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\r#ifndef BILLBOARD \noutInitialDirection=direction;\r#endif\n#else\n#ifdef LOCAL\nvec3 initial=newDirection;\r#else \nvec3 initial=(emitterWM*vec4(newDirection,0.)).xyz;\r#endif\noutDirection=initial*power;\r#ifndef BILLBOARD \noutInitialDirection=initial;\r#endif\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\r#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\r#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\routNoiseCoordinates2=noiseCoordinates2;\r#endif\n} else {\rfloat directionScale=timeDelta;\routAge=newAge;\rfloat ageGradient=newAge/life;\r#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\r#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\r#endif\n#if defined(CUSTOMEMITTER)\noutPosition=position+(direction-position)*ageGradient; \routInitialPosition=initialPosition;\r#else\noutPosition=position+direction*directionScale;\r#endif\noutLife=life;\routSeed=seed;\r#ifndef COLORGRADIENTS \noutColor=color;\r#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\routSize.yz=size.yz;\r#else\noutSize=size;\r#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\r#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\r#else\nvec3 updatedDirection=direction+gravity*timeDelta;\r#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\rfloat currentVelocity=length(updatedDirection);\rif (currentVelocity>limitVelocity) {\rupdatedDirection=updatedDirection*limitVelocityDamping;\r}\r#endif\noutDirection=updatedDirection;\r#ifdef NOISE\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\rfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\rfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\rvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\routDirection=outDirection+force*timeDelta;\routNoiseCoordinates1=noiseCoordinates1;\routNoiseCoordinates2=noiseCoordinates2;\r#endif \n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\routAngle=angle+angularSpeed*timeDelta;\r#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\r#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\rfloat dist=cellInfos.y-cellInfos.x;\r#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\roffsetAge+=cellStartOffset;\r#else\nfloat cellStartOffset=0.;\r#endif \nfloat ratio=0.;\rif (cellInfos.w==1.0) {\rratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);\r}\relse {\rratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);\r}\routCellIndex=float(int(cellInfos.x+ratio*dist));\r#endif\n}\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const gpuUpdateParticlesVertexShader = { name, shader };\n//# sourceMappingURL=gpuUpdateParticles.vertex.js.map","import { Effect } from \"../Materials/effect.js\";\nimport { CustomParticleEmitter } from \"./EmitterTypes/customParticleEmitter.js\";\nimport { UniformBufferEffectCommonAccessor } from \"../Materials/uniformBufferEffectCommonAccessor.js\";\n\nimport { RegisterClass } from \"../Misc/typeStore.js\";\nimport \"../Shaders/gpuUpdateParticles.fragment.js\";\nimport \"../Shaders/gpuUpdateParticles.vertex.js\";\n/** @internal */\nexport class WebGL2ParticleSystem {\n constructor(parent, engine) {\n this._renderVAO = [];\n this._updateVAO = [];\n this.alignDataInBuffer = false;\n this._parent = parent;\n this._engine = engine;\n this._updateEffectOptions = {\n attributes: [\n \"position\",\n \"initialPosition\",\n \"age\",\n \"life\",\n \"seed\",\n \"size\",\n \"color\",\n \"direction\",\n \"initialDirection\",\n \"angle\",\n \"cellIndex\",\n \"cellStartOffset\",\n \"noiseCoordinates1\",\n \"noiseCoordinates2\",\n ],\n uniformsNames: [\n \"currentCount\",\n \"timeDelta\",\n \"emitterWM\",\n \"lifeTime\",\n \"color1\",\n \"color2\",\n \"sizeRange\",\n \"scaleRange\",\n \"gravity\",\n \"emitPower\",\n \"direction1\",\n \"direction2\",\n \"minEmitBox\",\n \"maxEmitBox\",\n \"radius\",\n \"directionRandomizer\",\n \"height\",\n \"coneAngle\",\n \"stopFactor\",\n \"angleRange\",\n \"radiusRange\",\n \"cellInfos\",\n \"noiseStrength\",\n \"limitVelocityDamping\",\n ],\n uniformBuffersNames: [],\n samplers: [\n \"randomSampler\",\n \"randomSampler2\",\n \"sizeGradientSampler\",\n \"angularSpeedGradientSampler\",\n \"velocityGradientSampler\",\n \"limitVelocityGradientSampler\",\n \"noiseSampler\",\n \"dragGradientSampler\",\n ],\n defines: \"\",\n fallbacks: null,\n onCompiled: null,\n onError: null,\n indexParameters: null,\n maxSimultaneousLights: 0,\n transformFeedbackVaryings: [],\n };\n }\n isUpdateBufferCreated() {\n return !!this._updateEffect;\n }\n isUpdateBufferReady() {\n var _a, _b;\n return (_b = (_a = this._updateEffect) === null || _a === void 0 ? void 0 : _a.isReady()) !== null && _b !== void 0 ? _b : false;\n }\n createUpdateBuffer(defines) {\n this._updateEffectOptions.transformFeedbackVaryings = [\"outPosition\"];\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outAge\");\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outSize\");\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outLife\");\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outSeed\");\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outDirection\");\n if (this._parent.particleEmitterType instanceof CustomParticleEmitter) {\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outInitialPosition\");\n }\n if (!this._parent._colorGradientsTexture) {\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outColor\");\n }\n if (!this._parent._isBillboardBased) {\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outInitialDirection\");\n }\n if (this._parent.noiseTexture) {\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outNoiseCoordinates1\");\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outNoiseCoordinates2\");\n }\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outAngle\");\n if (this._parent.isAnimationSheetEnabled) {\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outCellIndex\");\n if (this._parent.spriteRandomStartCell) {\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outCellStartOffset\");\n }\n }\n this._updateEffectOptions.defines = defines;\n this._updateEffect = new Effect(\"gpuUpdateParticles\", this._updateEffectOptions, this._engine);\n return new UniformBufferEffectCommonAccessor(this._updateEffect);\n }\n createVertexBuffers(updateBuffer, renderVertexBuffers) {\n this._updateVAO.push(this._createUpdateVAO(updateBuffer));\n this._renderVAO.push(this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._parent._getWrapper(this._parent.blendMode).effect));\n this._engine.bindArrayBuffer(null);\n }\n createParticleBuffer(data) {\n return data;\n }\n bindDrawBuffers(index) {\n this._engine.bindVertexArrayObject(this._renderVAO[index], null);\n }\n preUpdateParticleBuffer() {\n const engine = this._engine;\n this._engine.enableEffect(this._updateEffect);\n if (!engine.setState) {\n throw new Error(\"GPU particles cannot work without a full Engine. ThinEngine is not supported\");\n }\n }\n updateParticleBuffer(index, targetBuffer, currentActiveCount) {\n this._updateEffect.setTexture(\"randomSampler\", this._parent._randomTexture);\n this._updateEffect.setTexture(\"randomSampler2\", this._parent._randomTexture2);\n if (this._parent._sizeGradientsTexture) {\n this._updateEffect.setTexture(\"sizeGradientSampler\", this._parent._sizeGradientsTexture);\n }\n if (this._parent._angularSpeedGradientsTexture) {\n this._updateEffect.setTexture(\"angularSpeedGradientSampler\", this._parent._angularSpeedGradientsTexture);\n }\n if (this._parent._velocityGradientsTexture) {\n this._updateEffect.setTexture(\"velocityGradientSampler\", this._parent._velocityGradientsTexture);\n }\n if (this._parent._limitVelocityGradientsTexture) {\n this._updateEffect.setTexture(\"limitVelocityGradientSampler\", this._parent._limitVelocityGradientsTexture);\n }\n if (this._parent._dragGradientsTexture) {\n this._updateEffect.setTexture(\"dragGradientSampler\", this._parent._dragGradientsTexture);\n }\n if (this._parent.noiseTexture) {\n this._updateEffect.setTexture(\"noiseSampler\", this._parent.noiseTexture);\n }\n // Bind source VAO\n this._engine.bindVertexArrayObject(this._updateVAO[index], null);\n // Update\n const engine = this._engine;\n engine.bindTransformFeedbackBuffer(targetBuffer.getBuffer());\n engine.setRasterizerState(false);\n engine.beginTransformFeedback(true);\n engine.drawArraysType(3, 0, currentActiveCount);\n engine.endTransformFeedback();\n engine.setRasterizerState(true);\n engine.bindTransformFeedbackBuffer(null);\n }\n releaseBuffers() { }\n releaseVertexBuffers() {\n for (let index = 0; index < this._updateVAO.length; index++) {\n this._engine.releaseVertexArrayObject(this._updateVAO[index]);\n }\n this._updateVAO.length = 0;\n for (let index = 0; index < this._renderVAO.length; index++) {\n this._engine.releaseVertexArrayObject(this._renderVAO[index]);\n }\n this._renderVAO.length = 0;\n }\n _createUpdateVAO(source) {\n const updateVertexBuffers = {};\n updateVertexBuffers[\"position\"] = source.createVertexBuffer(\"position\", 0, 3);\n let offset = 3;\n updateVertexBuffers[\"age\"] = source.createVertexBuffer(\"age\", offset, 1);\n offset += 1;\n updateVertexBuffers[\"size\"] = source.createVertexBuffer(\"size\", offset, 3);\n offset += 3;\n updateVertexBuffers[\"life\"] = source.createVertexBuffer(\"life\", offset, 1);\n offset += 1;\n updateVertexBuffers[\"seed\"] = source.createVertexBuffer(\"seed\", offset, 4);\n offset += 4;\n updateVertexBuffers[\"direction\"] = source.createVertexBuffer(\"direction\", offset, 3);\n offset += 3;\n if (this._parent.particleEmitterType instanceof CustomParticleEmitter) {\n updateVertexBuffers[\"initialPosition\"] = source.createVertexBuffer(\"initialPosition\", offset, 3);\n offset += 3;\n }\n if (!this._parent._colorGradientsTexture) {\n updateVertexBuffers[\"color\"] = source.createVertexBuffer(\"color\", offset, 4);\n offset += 4;\n }\n if (!this._parent._isBillboardBased) {\n updateVertexBuffers[\"initialDirection\"] = source.createVertexBuffer(\"initialDirection\", offset, 3);\n offset += 3;\n }\n if (this._parent.noiseTexture) {\n updateVertexBuffers[\"noiseCoordinates1\"] = source.createVertexBuffer(\"noiseCoordinates1\", offset, 3);\n offset += 3;\n updateVertexBuffers[\"noiseCoordinates2\"] = source.createVertexBuffer(\"noiseCoordinates2\", offset, 3);\n offset += 3;\n }\n if (this._parent._angularSpeedGradientsTexture) {\n updateVertexBuffers[\"angle\"] = source.createVertexBuffer(\"angle\", offset, 1);\n offset += 1;\n }\n else {\n updateVertexBuffers[\"angle\"] = source.createVertexBuffer(\"angle\", offset, 2);\n offset += 2;\n }\n if (this._parent._isAnimationSheetEnabled) {\n updateVertexBuffers[\"cellIndex\"] = source.createVertexBuffer(\"cellIndex\", offset, 1);\n offset += 1;\n if (this._parent.spriteRandomStartCell) {\n updateVertexBuffers[\"cellStartOffset\"] = source.createVertexBuffer(\"cellStartOffset\", offset, 1);\n offset += 1;\n }\n }\n const vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);\n this._engine.bindArrayBuffer(null);\n return vao;\n }\n}\nRegisterClass(\"BABYLON.WebGL2ParticleSystem\", WebGL2ParticleSystem);\n//# sourceMappingURL=webgl2ParticleSystem.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"gpuUpdateParticlesComputeShader\";\nconst shader = `struct Particle {\rposition : vec3,\rage : f32,\rsize : vec3,\rlife : f32,\rseed : vec4,\rdirection : vec3,\rdummy0: f32,\r#ifdef CUSTOMEMITTER\ninitialPosition : vec3,\rdummy1: f32,\r#endif\n#ifndef COLORGRADIENTS\ncolor : vec4,\r#endif\n#ifndef BILLBOARD\ninitialDirection : vec3,\rdummy2: f32,\r#endif\n#ifdef NOISE\nnoiseCoordinates1 : vec3,\rdummy3: f32,\rnoiseCoordinates2 : vec3,\rdummy4: f32,\r#endif\n#ifdef ANGULARSPEEDGRADIENTS\nangle : f32,\r#else\nangle : vec2,\r#endif\n#ifdef ANIMATESHEET\ncellIndex : f32,\r#ifdef ANIMATESHEETRANDOMSTART\ncellStartOffset : f32,\r#endif\n#endif\n};\rstruct Particles {\rparticles : array,\r};\rstruct SimParams {\rcurrentCount : f32,\rtimeDelta : f32,\rstopFactor : f32,\rrandomTextureSize: i32,\rlifeTime : vec2,\remitPower : vec2,\r#ifndef COLORGRADIENTS\ncolor1 : vec4,\rcolor2 : vec4,\r#endif\nsizeRange : vec2,\rscaleRange : vec4,\rangleRange : vec4,\rgravity : vec3,\r#ifdef LIMITVELOCITYGRADIENTS\nlimitVelocityDamping : f32,\r#endif\n#ifdef ANIMATESHEET\ncellInfos : vec4,\r#endif\n#ifdef NOISE\nnoiseStrength : vec3,\r#endif\n#ifndef LOCAL\nemitterWM : mat4x4,\r#endif\n#ifdef BOXEMITTER\ndirection1 : vec3,\rdirection2 : vec3,\rminEmitBox : vec3,\rmaxEmitBox : vec3,\r#endif\n#ifdef CONEEMITTER\nradius : vec2,\rconeAngle : f32,\rheight : vec2,\rdirectionRandomizer : f32,\r#endif\n#ifdef CYLINDEREMITTER\nradius : f32,\rheight : f32,\rradiusRange : f32,\r#ifdef DIRECTEDCYLINDEREMITTER\ndirection1 : vec3,\rdirection2 : vec3,\r#else\ndirectionRandomizer : f32,\r#endif\n#endif\n#ifdef HEMISPHERICEMITTER\nradius : f32,\rradiusRange : f32,\rdirectionRandomizer : f32,\r#endif\n#ifdef POINTEMITTER\ndirection1 : vec3,\rdirection2 : vec3,\r#endif\n#ifdef SPHEREEMITTER\nradius : f32,\rradiusRange : f32,\r#ifdef DIRECTEDSPHEREEMITTER\ndirection1 : vec3,\rdirection2 : vec3,\r#else\ndirectionRandomizer : f32,\r#endif\n#endif\n};\r@binding(0) @group(0) var params : SimParams;\r@binding(1) @group(0) var particlesIn : Particles;\r@binding(2) @group(0) var particlesOut : Particles;\r@binding(3) @group(0) var randomTexture : texture_2d;\r@binding(4) @group(0) var randomTexture2 : texture_2d;\r#ifdef SIZEGRADIENTS\n@binding(0) @group(1) var sizeGradientSampler : sampler;\r@binding(1) @group(1) var sizeGradientTexture : texture_2d;\r#endif \n#ifdef ANGULARSPEEDGRADIENTS\n@binding(2) @group(1) var angularSpeedGradientSampler : sampler;\r@binding(3) @group(1) var angularSpeedGradientTexture : texture_2d;\r#endif \n#ifdef VELOCITYGRADIENTS\n@binding(4) @group(1) var velocityGradientSampler : sampler;\r@binding(5) @group(1) var velocityGradientTexture : texture_2d;\r#endif\n#ifdef LIMITVELOCITYGRADIENTS\n@binding(6) @group(1) var limitVelocityGradientSampler : sampler;\r@binding(7) @group(1) var limitVelocityGradientTexture : texture_2d;\r#endif\n#ifdef DRAGGRADIENTS\n@binding(8) @group(1) var dragGradientSampler : sampler;\r@binding(9) @group(1) var dragGradientTexture : texture_2d;\r#endif\n#ifdef NOISE\n@binding(10) @group(1) var noiseSampler : sampler;\r@binding(11) @group(1) var noiseTexture : texture_2d;\r#endif\nfn getRandomVec3(offset : f32,vertexID : f32)->vec3 {\rreturn textureLoad(randomTexture2,vec2(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0).rgb;\r}\rfn getRandomVec4(offset : f32,vertexID : f32)->vec4 {\rreturn textureLoad(randomTexture,vec2(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0);\r}\r@compute @workgroup_size(64)\rfn main(@builtin(global_invocation_id) GlobalInvocationID : vec3) {\rlet index : u32=GlobalInvocationID.x;\rlet vertexID : f32=f32(index);\rif (index>=u32(params.currentCount)) {\rreturn;\r}\rlet PI : f32=3.14159;\rlet timeDelta : f32=params.timeDelta;\rlet newAge : f32=particlesIn.particles[index].age+timeDelta;\rlet life : f32=particlesIn.particles[index].life;\rlet seed : vec4=particlesIn.particles[index].seed;\rlet direction : vec3=particlesIn.particles[index].direction;\rif (newAge>=life && params.stopFactor != 0.) {\rvar newPosition : vec3;\rvar newDirection : vec3;\rlet randoms : vec4=getRandomVec4(seed.x,vertexID);\rlet outLife : f32=params.lifeTime.x+(params.lifeTime.y-params.lifeTime.x)*randoms.r;\rparticlesOut.particles[index].life=outLife;\rparticlesOut.particles[index].age=newAge-life;\rparticlesOut.particles[index].seed=seed;\rvar sizex : f32;\r#ifdef SIZEGRADIENTS \nsizex=textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2(0.,0.),0.).r;\r#else\nsizex=params.sizeRange.x+(params.sizeRange.y-params.sizeRange.x)*randoms.g;\r#endif\nparticlesOut.particles[index].size=vec3(\rsizex,\rparams.scaleRange.x+(params.scaleRange.y-params.scaleRange.x)*randoms.b,\rparams.scaleRange.z+(params.scaleRange.w-params.scaleRange.z)*randoms.a);\r#ifndef COLORGRADIENTS\nparticlesOut.particles[index].color=params.color1+(params.color2-params.color1)*randoms.b;\r#endif\n#ifndef ANGULARSPEEDGRADIENTS \nparticlesOut.particles[index].angle=vec2(\rparams.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r,\rparams.angleRange.x+(params.angleRange.y-params.angleRange.x)*randoms.a);\r#else\nparticlesOut.particles[index].angle=params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r;\r#endif \n#if defined(POINTEMITTER)\nlet randoms2 : vec3=getRandomVec3(seed.y,vertexID);\rlet randoms3 : vec3=getRandomVec3(seed.z,vertexID);\rnewPosition=vec3(0.,0.,0.);\rnewDirection=params.direction1+(params.direction2-params.direction1)*randoms3;\r#elif defined(BOXEMITTER)\nlet randoms2 : vec3=getRandomVec3(seed.y,vertexID);\rlet randoms3 : vec3=getRandomVec3(seed.z,vertexID);\rnewPosition=params.minEmitBox+(params.maxEmitBox-params.minEmitBox)*randoms2;\rnewDirection=params.direction1+(params.direction2-params.direction1)*randoms3; \r#elif defined(HEMISPHERICEMITTER)\nlet randoms2 : vec3=getRandomVec3(seed.y,vertexID);\rlet randoms3 : vec3=getRandomVec3(seed.z,vertexID);\rlet phi : f32=2.0*PI*randoms2.x;\rlet theta : f32=acos(-1.0+2.0*randoms2.y);\rlet randX : f32=cos(phi)*sin(theta);\rlet randY : f32=cos(theta);\rlet randZ : f32=sin(phi)*sin(theta);\rnewPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\rnewDirection=normalize(newPosition+params.directionRandomizer*randoms3);\r#elif defined(SPHEREEMITTER)\nlet randoms2 : vec3=getRandomVec3(seed.y,vertexID);\rlet randoms3 : vec3=getRandomVec3(seed.z,vertexID);\rlet phi : f32=2.0*PI*randoms2.x;\rlet theta : f32=acos(-1.0+2.0*randoms2.y);\rlet randX : f32=cos(phi)*sin(theta);\rlet randY : f32=cos(theta);\rlet randZ : f32=sin(phi)*sin(theta);\rnewPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3(randX,randY,randZ);\r#ifdef DIRECTEDSPHEREEMITTER\nnewDirection=normalize(params.direction1+(params.direction2-params.direction1)*randoms3);\r#else\nnewDirection=normalize(newPosition+params.directionRandomizer*randoms3);\r#endif\n#elif defined(CYLINDEREMITTER)\nlet randoms2 : vec3=getRandomVec3(seed.y,vertexID);\rlet randoms3 : vec3=getRandomVec3(seed.z,vertexID);\rlet yPos : f32=(-0.5+randoms2.x)*params.height;\rvar angle : f32=randoms2.y*PI*2.;\rlet inverseRadiusRangeSquared : f32=(1.-params.radiusRange)*(1.-params.radiusRange);\rlet positionRadius : f32=params.radius*sqrt(inverseRadiusRangeSquared+randoms2.z*(1.-inverseRadiusRangeSquared));\rlet xPos : f32=positionRadius*cos(angle);\rlet zPos : f32=positionRadius*sin(angle);\rnewPosition=vec3(xPos,yPos,zPos);\r#ifdef DIRECTEDCYLINDEREMITTER\nnewDirection=params.direction1+(params.direction2-params.direction1)*randoms3;\r#else\nangle=angle+(-0.5+randoms3.x)*PI*params.directionRandomizer;\rnewDirection=vec3(cos(angle),(-0.5+randoms3.y)*params.directionRandomizer,sin(angle));\rnewDirection=normalize(newDirection);\r#endif\n#elif defined(CONEEMITTER)\nlet randoms2 : vec3=getRandomVec3(seed.y,vertexID);\rlet s : f32=2.0*PI*randoms2.x;\r#ifdef CONEEMITTERSPAWNPOINT\nlet h : f32=0.0001;\r#else\nvar h : f32=randoms2.y*params.height.y;\rh=1.-h*h; \r#endif\nvar lRadius : f32=params.radius.x-params.radius.x*randoms2.z*params.radius.y;\rlRadius=lRadius*h;\rlet randX : f32=lRadius*sin(s);\rlet randZ : f32=lRadius*cos(s);\rlet randY : f32=h *params.height.x;\rnewPosition=vec3(randX,randY,randZ); \rif (abs(cos(params.coneAngle))==1.0) {\rnewDirection=vec3(0.,1.0,0.);\r} else {\rlet randoms3 : vec3=getRandomVec3(seed.z,vertexID);\rnewDirection=normalize(newPosition+params.directionRandomizer*randoms3); \r}\r#elif defined(CUSTOMEMITTER)\nnewPosition=particlesIn.particles[index].initialPosition;\rparticlesOut.particles[index].initialPosition=newPosition;\r#else \nnewPosition=vec3(0.,0.,0.);\rnewDirection=2.0*(getRandomVec3(seed.w,vertexID)-vec3(0.5,0.5,0.5));\r#endif\nlet power : f32=params.emitPower.x+(params.emitPower.y-params.emitPower.x)*randoms.a;\r#ifdef LOCAL\nparticlesOut.particles[index].position=newPosition;\r#else\nparticlesOut.particles[index].position=(params.emitterWM*vec4(newPosition,1.)).xyz;\r#endif\n#ifdef CUSTOMEMITTER\nparticlesOut.particles[index].direction=direction;\r#ifndef BILLBOARD \nparticlesOut.particles[index].initialDirection=direction;\r#endif\n#else\n#ifdef LOCAL\nlet initial : vec3=newDirection;\r#else \nlet initial : vec3=(params.emitterWM*vec4(newDirection,0.)).xyz;\r#endif\nparticlesOut.particles[index].direction=initial*power;\r#ifndef BILLBOARD \nparticlesOut.particles[index].initialDirection=initial;\r#endif\n#endif\n#ifdef ANIMATESHEET \nparticlesOut.particles[index].cellIndex=params.cellInfos.x;\r#ifdef ANIMATESHEETRANDOMSTART\nparticlesOut.particles[index].cellStartOffset=randoms.a*outLife;\r#endif \n#endif\n#ifdef NOISE\nparticlesOut.particles[index].noiseCoordinates1=particlesIn.particles[index].noiseCoordinates1;\rparticlesOut.particles[index].noiseCoordinates2=particlesIn.particles[index].noiseCoordinates2;\r#endif\n} else {\rvar directionScale : f32=timeDelta;\rparticlesOut.particles[index].age=newAge;\rlet ageGradient : f32=newAge/life;\r#ifdef VELOCITYGRADIENTS\ndirectionScale=directionScale*textureSampleLevel(velocityGradientTexture,velocityGradientSampler,vec2(ageGradient,0.),0.).r;\r#endif\n#ifdef DRAGGRADIENTS\ndirectionScale=directionScale*(1.0-textureSampleLevel(dragGradientTexture,dragGradientSampler,vec2(ageGradient,0.),0.).r);\r#endif\nlet position : vec3=particlesIn.particles[index].position;\r#if defined(CUSTOMEMITTER)\nparticlesOut.particles[index].position=position+(direction-position)*ageGradient; \rparticlesOut.particles[index].initialPosition=particlesIn.particles[index].initialPosition;\r#else\nparticlesOut.particles[index].position=position+direction*directionScale;\r#endif\nparticlesOut.particles[index].life=life;\rparticlesOut.particles[index].seed=seed;\r#ifndef COLORGRADIENTS \nparticlesOut.particles[index].color=particlesIn.particles[index].color;\r#endif\n#ifdef SIZEGRADIENTS\nparticlesOut.particles[index].size=vec3(\rtextureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2(ageGradient,0.),0.).r,\rparticlesIn.particles[index].size.yz);\r#else\nparticlesOut.particles[index].size=particlesIn.particles[index].size;\r#endif \n#ifndef BILLBOARD \nparticlesOut.particles[index].initialDirection=particlesIn.particles[index].initialDirection;\r#endif\n#ifdef CUSTOMEMITTER\nparticlesOut.particles[index].direction=direction;\r#else\nvar updatedDirection : vec3=direction+params.gravity*timeDelta;\r#ifdef LIMITVELOCITYGRADIENTS\nlet limitVelocity : f32=textureSampleLevel(limitVelocityGradientTexture,limitVelocityGradientSampler,vec2(ageGradient,0.),0.).r;\rlet currentVelocity : f32=length(updatedDirection);\rif (currentVelocity>limitVelocity) {\rupdatedDirection=updatedDirection*params.limitVelocityDamping;\r}\r#endif\nparticlesOut.particles[index].direction=updatedDirection;\r#ifdef NOISE\nlet noiseCoordinates1 : vec3=particlesIn.particles[index].noiseCoordinates1;\rlet noiseCoordinates2 : vec3=particlesIn.particles[index].noiseCoordinates2;\rlet fetchedR : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;\rlet fetchedG : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;\rlet fetchedB : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;\rlet force : vec3=vec3(-1.+2.*fetchedR,-1.+2.*fetchedG,-1.+2.*fetchedB)*params.noiseStrength;\rparticlesOut.particles[index].direction=particlesOut.particles[index].direction+force*timeDelta;\rparticlesOut.particles[index].noiseCoordinates1=noiseCoordinates1;\rparticlesOut.particles[index].noiseCoordinates2=noiseCoordinates2;\r#endif \n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nlet angularSpeed : f32=textureSampleLevel(angularSpeedGradientTexture,angularSpeedGradientSampler,vec2(ageGradient,0.),0.).r;\rparticlesOut.particles[index].angle=particlesIn.particles[index].angle+angularSpeed*timeDelta;\r#else\nlet angle : vec2=particlesIn.particles[index].angle;\rparticlesOut.particles[index].angle=vec2(angle.x+angle.y*timeDelta,angle.y);\r#endif\n#ifdef ANIMATESHEET \nvar offsetAge : f32=particlesOut.particles[index].age;\rlet dist : f32=params.cellInfos.y-params.cellInfos.x;\r#ifdef ANIMATESHEETRANDOMSTART\nlet cellStartOffset : f32=particlesIn.particles[index].cellStartOffset;\rparticlesOut.particles[index].cellStartOffset=cellStartOffset;\roffsetAge=offsetAge+cellStartOffset;\r#else\nlet cellStartOffset : f32=0.;\r#endif \nvar ratio : f32;\rif (params.cellInfos.w==1.0) {\rratio=clamp(((cellStartOffset+params.cellInfos.z*offsetAge) % life)/life,0.,1.0);\r}\relse {\rratio=clamp((cellStartOffset+params.cellInfos.z*offsetAge)/life,0.,1.0);\r}\rparticlesOut.particles[index].cellIndex=f32(i32(params.cellInfos.x+ratio*dist));\r#endif\n}\r}\r`;\n// Sideeffect\nShaderStore.ShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const gpuUpdateParticlesComputeShader = { name, shader };\n//# sourceMappingURL=gpuUpdateParticles.compute.js.map","import { Vector2, Vector3, TmpVectors, Vector4 } from \"../Maths/math.vector.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { Scalar } from \"../Maths/math.scalar.js\";\n/**\n * A particle represents one of the element emitted by a particle system.\n * This is mainly define by its coordinates, direction, velocity and age.\n */\nexport class Particle {\n /**\n * Creates a new instance Particle\n * @param particleSystem the particle system the particle belongs to\n */\n constructor(\n /**\n * The particle system the particle belongs to.\n */\n particleSystem) {\n this.particleSystem = particleSystem;\n /**\n * The world position of the particle in the scene.\n */\n this.position = Vector3.Zero();\n /**\n * The world direction of the particle in the scene.\n */\n this.direction = Vector3.Zero();\n /**\n * The color of the particle.\n */\n this.color = new Color4(0, 0, 0, 0);\n /**\n * The color change of the particle per step.\n */\n this.colorStep = new Color4(0, 0, 0, 0);\n /**\n * Defines how long will the life of the particle be.\n */\n this.lifeTime = 1.0;\n /**\n * The current age of the particle.\n */\n this.age = 0;\n /**\n * The current size of the particle.\n */\n this.size = 0;\n /**\n * The current scale of the particle.\n */\n this.scale = new Vector2(1, 1);\n /**\n * The current angle of the particle.\n */\n this.angle = 0;\n /**\n * Defines how fast is the angle changing.\n */\n this.angularSpeed = 0;\n /**\n * Defines the cell index used by the particle to be rendered from a sprite.\n */\n this.cellIndex = 0;\n /** @internal */\n this._attachedSubEmitters = null;\n /** @internal */\n this._currentColor1 = new Color4(0, 0, 0, 0);\n /** @internal */\n this._currentColor2 = new Color4(0, 0, 0, 0);\n /** @internal */\n this._currentSize1 = 0;\n /** @internal */\n this._currentSize2 = 0;\n /** @internal */\n this._currentAngularSpeed1 = 0;\n /** @internal */\n this._currentAngularSpeed2 = 0;\n /** @internal */\n this._currentVelocity1 = 0;\n /** @internal */\n this._currentVelocity2 = 0;\n /** @internal */\n this._currentLimitVelocity1 = 0;\n /** @internal */\n this._currentLimitVelocity2 = 0;\n /** @internal */\n this._currentDrag1 = 0;\n /** @internal */\n this._currentDrag2 = 0;\n this.id = Particle._Count++;\n if (!this.particleSystem.isAnimationSheetEnabled) {\n return;\n }\n this._updateCellInfoFromSystem();\n }\n _updateCellInfoFromSystem() {\n this.cellIndex = this.particleSystem.startSpriteCellID;\n }\n /**\n * Defines how the sprite cell index is updated for the particle\n */\n updateCellIndex() {\n let offsetAge = this.age;\n let changeSpeed = this.particleSystem.spriteCellChangeSpeed;\n if (this.particleSystem.spriteRandomStartCell) {\n if (this._randomCellOffset === undefined) {\n this._randomCellOffset = Math.random() * this.lifeTime;\n }\n if (changeSpeed === 0) {\n // Special case when speed = 0 meaning we want to stay on initial cell\n changeSpeed = 1;\n offsetAge = this._randomCellOffset;\n }\n else {\n offsetAge += this._randomCellOffset;\n }\n }\n const dist = this._initialEndSpriteCellID - this._initialStartSpriteCellID;\n let ratio;\n if (this._initialSpriteCellLoop) {\n ratio = Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);\n }\n else {\n ratio = Scalar.Clamp((offsetAge * changeSpeed) / this.lifeTime);\n }\n this.cellIndex = (this._initialStartSpriteCellID + ratio * dist) | 0;\n }\n /**\n * @internal\n */\n _inheritParticleInfoToSubEmitter(subEmitter) {\n if (subEmitter.particleSystem.emitter.position) {\n const emitterMesh = subEmitter.particleSystem.emitter;\n emitterMesh.position.copyFrom(this.position);\n if (subEmitter.inheritDirection) {\n const temp = TmpVectors.Vector3[0];\n this.direction.normalizeToRef(temp);\n emitterMesh.setDirection(temp, 0, Math.PI / 2);\n }\n }\n else {\n const emitterPosition = subEmitter.particleSystem.emitter;\n emitterPosition.copyFrom(this.position);\n }\n // Set inheritedVelocityOffset to be used when new particles are created\n this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, TmpVectors.Vector3[0]);\n subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(TmpVectors.Vector3[0]);\n }\n /** @internal */\n _inheritParticleInfoToSubEmitters() {\n if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {\n this._attachedSubEmitters.forEach((subEmitter) => {\n this._inheritParticleInfoToSubEmitter(subEmitter);\n });\n }\n }\n /** @internal */\n _reset() {\n this.age = 0;\n this.id = Particle._Count++;\n this._currentColorGradient = null;\n this._currentSizeGradient = null;\n this._currentAngularSpeedGradient = null;\n this._currentVelocityGradient = null;\n this._currentLimitVelocityGradient = null;\n this._currentDragGradient = null;\n this.cellIndex = this.particleSystem.startSpriteCellID;\n this._randomCellOffset = undefined;\n }\n /**\n * Copy the properties of particle to another one.\n * @param other the particle to copy the information to.\n */\n copyTo(other) {\n other.position.copyFrom(this.position);\n if (this._initialDirection) {\n if (other._initialDirection) {\n other._initialDirection.copyFrom(this._initialDirection);\n }\n else {\n other._initialDirection = this._initialDirection.clone();\n }\n }\n else {\n other._initialDirection = null;\n }\n other.direction.copyFrom(this.direction);\n if (this._localPosition) {\n if (other._localPosition) {\n other._localPosition.copyFrom(this._localPosition);\n }\n else {\n other._localPosition = this._localPosition.clone();\n }\n }\n other.color.copyFrom(this.color);\n other.colorStep.copyFrom(this.colorStep);\n other.lifeTime = this.lifeTime;\n other.age = this.age;\n other._randomCellOffset = this._randomCellOffset;\n other.size = this.size;\n other.scale.copyFrom(this.scale);\n other.angle = this.angle;\n other.angularSpeed = this.angularSpeed;\n other.particleSystem = this.particleSystem;\n other.cellIndex = this.cellIndex;\n other.id = this.id;\n other._attachedSubEmitters = this._attachedSubEmitters;\n if (this._currentColorGradient) {\n other._currentColorGradient = this._currentColorGradient;\n other._currentColor1.copyFrom(this._currentColor1);\n other._currentColor2.copyFrom(this._currentColor2);\n }\n if (this._currentSizeGradient) {\n other._currentSizeGradient = this._currentSizeGradient;\n other._currentSize1 = this._currentSize1;\n other._currentSize2 = this._currentSize2;\n }\n if (this._currentAngularSpeedGradient) {\n other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;\n other._currentAngularSpeed1 = this._currentAngularSpeed1;\n other._currentAngularSpeed2 = this._currentAngularSpeed2;\n }\n if (this._currentVelocityGradient) {\n other._currentVelocityGradient = this._currentVelocityGradient;\n other._currentVelocity1 = this._currentVelocity1;\n other._currentVelocity2 = this._currentVelocity2;\n }\n if (this._currentLimitVelocityGradient) {\n other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;\n other._currentLimitVelocity1 = this._currentLimitVelocity1;\n other._currentLimitVelocity2 = this._currentLimitVelocity2;\n }\n if (this._currentDragGradient) {\n other._currentDragGradient = this._currentDragGradient;\n other._currentDrag1 = this._currentDrag1;\n other._currentDrag2 = this._currentDrag2;\n }\n if (this.particleSystem.isAnimationSheetEnabled) {\n other._initialStartSpriteCellID = this._initialStartSpriteCellID;\n other._initialEndSpriteCellID = this._initialEndSpriteCellID;\n other._initialSpriteCellLoop = this._initialSpriteCellLoop;\n }\n if (this.particleSystem.useRampGradients) {\n if (other.remapData && this.remapData) {\n other.remapData.copyFrom(this.remapData);\n }\n else {\n other.remapData = new Vector4(0, 0, 0, 0);\n }\n }\n if (this._randomNoiseCoordinates1) {\n if (other._randomNoiseCoordinates1) {\n other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);\n other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);\n }\n else {\n other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();\n other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();\n }\n }\n }\n}\nParticle._Count = 0;\n//# sourceMappingURL=particle.js.map","import { FactorGradient, ColorGradient, Color3Gradient, GradientHelper } from \"../Misc/gradients.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Vector3, Matrix, TmpVectors, Vector4 } from \"../Maths/math.vector.js\";\nimport { Scalar } from \"../Maths/math.scalar.js\";\nimport { VertexBuffer, Buffer } from \"../Buffers/buffer.js\";\nimport { ImageProcessingConfiguration } from \"../Materials/imageProcessingConfiguration.js\";\nimport { RawTexture } from \"../Materials/Textures/rawTexture.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { BoxParticleEmitter, HemisphericParticleEmitter, SphereParticleEmitter, SphereDirectedParticleEmitter, CylinderParticleEmitter, ConeParticleEmitter, PointParticleEmitter, MeshParticleEmitter, CylinderDirectedParticleEmitter, } from \"../Particles/EmitterTypes/index.js\";\nimport { BaseParticleSystem } from \"./baseParticleSystem.js\";\nimport { Particle } from \"./particle.js\";\nimport { SubEmitter, SubEmitterType } from \"./subEmitter.js\";\n\nimport { SerializationHelper } from \"../Misc/decorators.js\";\nimport { GetClass } from \"../Misc/typeStore.js\";\nimport { DrawWrapper } from \"../Materials/drawWrapper.js\";\nimport \"../Shaders/particles.fragment.js\";\nimport \"../Shaders/particles.vertex.js\";\nimport { Color4, Color3, TmpColors } from \"../Maths/math.color.js\";\nimport { ThinEngine } from \"../Engines/thinEngine.js\";\nimport { MaterialHelper } from \"../Materials/materialHelper.js\";\nimport \"../Engines/Extensions/engine.alpha.js\";\nimport { addClipPlaneUniforms, prepareStringDefinesForClipPlanes, bindClipPlane } from \"../Materials/clipPlaneMaterialHelper.js\";\n/**\n * This represents a particle system in Babylon.\n * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.\n * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.\n * @example https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro\n */\nexport class ParticleSystem extends BaseParticleSystem {\n /**\n * Sets a callback that will be triggered when the system is disposed\n */\n set onDispose(callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n }\n /** Gets or sets a boolean indicating that ramp gradients must be used\n * @see https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro#ramp-gradients\n */\n get useRampGradients() {\n return this._useRampGradients;\n }\n set useRampGradients(value) {\n if (this._useRampGradients === value) {\n return;\n }\n this._useRampGradients = value;\n this._resetEffect();\n }\n //end of Sub-emitter\n /**\n * Gets the current list of active particles\n */\n get particles() {\n return this._particles;\n }\n /**\n * Gets the number of particles active at the same time.\n * @returns The number of active particles.\n */\n getActiveCount() {\n return this._particles.length;\n }\n /**\n * Returns the string \"ParticleSystem\"\n * @returns a string containing the class name\n */\n getClassName() {\n return \"ParticleSystem\";\n }\n /**\n * Gets a boolean indicating that the system is stopping\n * @returns true if the system is currently stopping\n */\n isStopping() {\n return this._stopped && this.isAlive();\n }\n /**\n * Gets the custom effect used to render the particles\n * @param blendMode Blend mode for which the effect should be retrieved\n * @returns The effect\n */\n getCustomEffect(blendMode = 0) {\n var _a, _b;\n return (_b = (_a = this._customWrappers[blendMode]) === null || _a === void 0 ? void 0 : _a.effect) !== null && _b !== void 0 ? _b : this._customWrappers[0].effect;\n }\n _getCustomDrawWrapper(blendMode = 0) {\n var _a;\n return (_a = this._customWrappers[blendMode]) !== null && _a !== void 0 ? _a : this._customWrappers[0];\n }\n /**\n * Sets the custom effect used to render the particles\n * @param effect The effect to set\n * @param blendMode Blend mode for which the effect should be set\n */\n setCustomEffect(effect, blendMode = 0) {\n this._customWrappers[blendMode] = new DrawWrapper(this._engine);\n this._customWrappers[blendMode].effect = effect;\n if (this._customWrappers[blendMode].drawContext) {\n this._customWrappers[blendMode].drawContext.useInstancing = this._useInstancing;\n }\n }\n /**\n * Observable that will be called just before the particles are drawn\n */\n get onBeforeDrawParticlesObservable() {\n if (!this._onBeforeDrawParticlesObservable) {\n this._onBeforeDrawParticlesObservable = new Observable();\n }\n return this._onBeforeDrawParticlesObservable;\n }\n /**\n * Gets the name of the particle vertex shader\n */\n get vertexShaderName() {\n return \"particles\";\n }\n /**\n * Gets the vertex buffers used by the particle system\n */\n get vertexBuffers() {\n return this._vertexBuffers;\n }\n /**\n * Gets the index buffer used by the particle system (or null if no index buffer is used (if _useInstancing=true))\n */\n get indexBuffer() {\n return this._indexBuffer;\n }\n /**\n * Instantiates a particle system.\n * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.\n * @param name The name of the particle system\n * @param capacity The max number of particles alive at the same time\n * @param sceneOrEngine The scene the particle system belongs to or the engine to use if no scene\n * @param customEffect a custom effect used to change the way particles are rendered by default\n * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture\n * @param epsilon Offset used to render the particles\n */\n constructor(name, capacity, sceneOrEngine, customEffect = null, isAnimationSheetEnabled = false, epsilon = 0.01) {\n super(name);\n this._emitterInverseWorldMatrix = Matrix.Identity();\n /**\n * @internal\n */\n this._inheritedVelocityOffset = new Vector3();\n /**\n * An event triggered when the system is disposed\n */\n this.onDisposeObservable = new Observable();\n /**\n * An event triggered when the system is stopped\n */\n this.onStoppedObservable = new Observable();\n this._particles = new Array();\n this._stockParticles = new Array();\n this._newPartsExcess = 0;\n this._vertexBuffers = {};\n this._scaledColorStep = new Color4(0, 0, 0, 0);\n this._colorDiff = new Color4(0, 0, 0, 0);\n this._scaledDirection = Vector3.Zero();\n this._scaledGravity = Vector3.Zero();\n this._currentRenderId = -1;\n this._useInstancing = false;\n this._started = false;\n this._stopped = false;\n this._actualFrame = 0;\n /** @internal */\n this._currentEmitRate1 = 0;\n /** @internal */\n this._currentEmitRate2 = 0;\n /** @internal */\n this._currentStartSize1 = 0;\n /** @internal */\n this._currentStartSize2 = 0;\n /** Indicates that the update of particles is done in the animate function */\n this.updateInAnimate = true;\n this._rawTextureWidth = 256;\n this._useRampGradients = false;\n /**\n * @internal\n * If the particle systems emitter should be disposed when the particle system is disposed\n */\n this._disposeEmitterOnDispose = false;\n /**\n * Specifies if the particles are updated in emitter local space or world space\n */\n this.isLocal = false;\n /** Indicates that the particle system is CPU based */\n this.isGPU = false;\n /** @internal */\n this._onBeforeDrawParticlesObservable = null;\n // start of sub system methods\n /**\n * \"Recycles\" one of the particle by copying it back to the \"stock\" of particles and removing it from the active list.\n * Its lifetime will start back at 0.\n * @param particle\n */\n this.recycleParticle = (particle) => {\n // move particle from activeParticle list to stock particles\n const lastParticle = this._particles.pop();\n if (lastParticle !== particle) {\n lastParticle.copyTo(particle);\n }\n this._stockParticles.push(lastParticle);\n };\n this._createParticle = () => {\n let particle;\n if (this._stockParticles.length !== 0) {\n particle = this._stockParticles.pop();\n particle._reset();\n }\n else {\n particle = new Particle(this);\n }\n // Attach emitters\n if (this._subEmitters && this._subEmitters.length > 0) {\n const subEmitters = this._subEmitters[Math.floor(Math.random() * this._subEmitters.length)];\n particle._attachedSubEmitters = [];\n subEmitters.forEach((subEmitter) => {\n if (subEmitter.type === SubEmitterType.ATTACHED) {\n const newEmitter = subEmitter.clone();\n particle._attachedSubEmitters.push(newEmitter);\n newEmitter.particleSystem.start();\n }\n });\n }\n return particle;\n };\n this._emitFromParticle = (particle) => {\n if (!this._subEmitters || this._subEmitters.length === 0) {\n return;\n }\n const templateIndex = Math.floor(Math.random() * this._subEmitters.length);\n this._subEmitters[templateIndex].forEach((subEmitter) => {\n if (subEmitter.type === SubEmitterType.END) {\n const subSystem = subEmitter.clone();\n particle._inheritParticleInfoToSubEmitter(subSystem);\n subSystem.particleSystem._rootParticleSystem = this;\n this.activeSubSystems.push(subSystem.particleSystem);\n subSystem.particleSystem.start();\n }\n });\n };\n this._capacity = capacity;\n this._epsilon = epsilon;\n this._isAnimationSheetEnabled = isAnimationSheetEnabled;\n if (!sceneOrEngine || sceneOrEngine.getClassName() === \"Scene\") {\n this._scene = sceneOrEngine || EngineStore.LastCreatedScene;\n this._engine = this._scene.getEngine();\n this.uniqueId = this._scene.getUniqueId();\n this._scene.particleSystems.push(this);\n }\n else {\n this._engine = sceneOrEngine;\n this.defaultProjectionMatrix = Matrix.PerspectiveFovLH(0.8, 1, 0.1, 100, this._engine.isNDCHalfZRange);\n }\n if (this._engine.getCaps().vertexArrayObject) {\n this._vertexArrayObject = null;\n }\n // Setup the default processing configuration to the scene.\n this._attachImageProcessingConfiguration(null);\n // eslint-disable-next-line @typescript-eslint/naming-convention\n this._customWrappers = { 0: new DrawWrapper(this._engine) };\n this._customWrappers[0].effect = customEffect;\n this._drawWrappers = [];\n this._useInstancing = this._engine.getCaps().instancedArrays;\n this._createIndexBuffer();\n this._createVertexBuffers();\n // Default emitter type\n this.particleEmitterType = new BoxParticleEmitter();\n let noiseTextureData = null;\n // Update\n this.updateFunction = (particles) => {\n var _a;\n let noiseTextureSize = null;\n if (this.noiseTexture) {\n // We need to get texture data back to CPU\n noiseTextureSize = this.noiseTexture.getSize();\n (_a = this.noiseTexture.getContent()) === null || _a === void 0 ? void 0 : _a.then((data) => {\n noiseTextureData = data;\n });\n }\n for (let index = 0; index < particles.length; index++) {\n const particle = particles[index];\n let scaledUpdateSpeed = this._scaledUpdateSpeed;\n const previousAge = particle.age;\n particle.age += scaledUpdateSpeed;\n // Evaluate step to death\n if (particle.age > particle.lifeTime) {\n const diff = particle.age - previousAge;\n const oldDiff = particle.lifeTime - previousAge;\n scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;\n particle.age = particle.lifeTime;\n }\n const ratio = particle.age / particle.lifeTime;\n // Color\n if (this._colorGradients && this._colorGradients.length > 0) {\n GradientHelper.GetCurrentGradient(ratio, this._colorGradients, (currentGradient, nextGradient, scale) => {\n if (currentGradient !== particle._currentColorGradient) {\n particle._currentColor1.copyFrom(particle._currentColor2);\n nextGradient.getColorToRef(particle._currentColor2);\n particle._currentColorGradient = currentGradient;\n }\n Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);\n });\n }\n else {\n particle.colorStep.scaleToRef(scaledUpdateSpeed, this._scaledColorStep);\n particle.color.addInPlace(this._scaledColorStep);\n if (particle.color.a < 0) {\n particle.color.a = 0;\n }\n }\n // Angular speed\n if (this._angularSpeedGradients && this._angularSpeedGradients.length > 0) {\n GradientHelper.GetCurrentGradient(ratio, this._angularSpeedGradients, (currentGradient, nextGradient, scale) => {\n if (currentGradient !== particle._currentAngularSpeedGradient) {\n particle._currentAngularSpeed1 = particle._currentAngularSpeed2;\n particle._currentAngularSpeed2 = nextGradient.getFactor();\n particle._currentAngularSpeedGradient = currentGradient;\n }\n particle.angularSpeed = Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);\n });\n }\n particle.angle += particle.angularSpeed * scaledUpdateSpeed;\n // Direction\n let directionScale = scaledUpdateSpeed;\n /// Velocity\n if (this._velocityGradients && this._velocityGradients.length > 0) {\n GradientHelper.GetCurrentGradient(ratio, this._velocityGradients, (currentGradient, nextGradient, scale) => {\n if (currentGradient !== particle._currentVelocityGradient) {\n particle._currentVelocity1 = particle._currentVelocity2;\n particle._currentVelocity2 = nextGradient.getFactor();\n particle._currentVelocityGradient = currentGradient;\n }\n directionScale *= Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);\n });\n }\n particle.direction.scaleToRef(directionScale, this._scaledDirection);\n /// Limit velocity\n if (this._limitVelocityGradients && this._limitVelocityGradients.length > 0) {\n GradientHelper.GetCurrentGradient(ratio, this._limitVelocityGradients, (currentGradient, nextGradient, scale) => {\n if (currentGradient !== particle._currentLimitVelocityGradient) {\n particle._currentLimitVelocity1 = particle._currentLimitVelocity2;\n particle._currentLimitVelocity2 = nextGradient.getFactor();\n particle._currentLimitVelocityGradient = currentGradient;\n }\n const limitVelocity = Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);\n const currentVelocity = particle.direction.length();\n if (currentVelocity > limitVelocity) {\n particle.direction.scaleInPlace(this.limitVelocityDamping);\n }\n });\n }\n /// Drag\n if (this._dragGradients && this._dragGradients.length > 0) {\n GradientHelper.GetCurrentGradient(ratio, this._dragGradients, (currentGradient, nextGradient, scale) => {\n if (currentGradient !== particle._currentDragGradient) {\n particle._currentDrag1 = particle._currentDrag2;\n particle._currentDrag2 = nextGradient.getFactor();\n particle._currentDragGradient = currentGradient;\n }\n const drag = Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);\n this._scaledDirection.scaleInPlace(1.0 - drag);\n });\n }\n if (this.isLocal && particle._localPosition) {\n particle._localPosition.addInPlace(this._scaledDirection);\n Vector3.TransformCoordinatesToRef(particle._localPosition, this._emitterWorldMatrix, particle.position);\n }\n else {\n particle.position.addInPlace(this._scaledDirection);\n }\n // Noise\n if (noiseTextureData && noiseTextureSize && particle._randomNoiseCoordinates1) {\n const fetchedColorR = this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);\n const fetchedColorG = this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);\n const fetchedColorB = this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);\n const force = TmpVectors.Vector3[0];\n const scaledForce = TmpVectors.Vector3[1];\n force.copyFromFloats((2 * fetchedColorR - 1) * this.noiseStrength.x, (2 * fetchedColorG - 1) * this.noiseStrength.y, (2 * fetchedColorB - 1) * this.noiseStrength.z);\n force.scaleToRef(scaledUpdateSpeed, scaledForce);\n particle.direction.addInPlace(scaledForce);\n }\n // Gravity\n this.gravity.scaleToRef(scaledUpdateSpeed, this._scaledGravity);\n particle.direction.addInPlace(this._scaledGravity);\n // Size\n if (this._sizeGradients && this._sizeGradients.length > 0) {\n GradientHelper.GetCurrentGradient(ratio, this._sizeGradients, (currentGradient, nextGradient, scale) => {\n if (currentGradient !== particle._currentSizeGradient) {\n particle._currentSize1 = particle._currentSize2;\n particle._currentSize2 = nextGradient.getFactor();\n particle._currentSizeGradient = currentGradient;\n }\n particle.size = Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);\n });\n }\n // Remap data\n if (this._useRampGradients) {\n if (this._colorRemapGradients && this._colorRemapGradients.length > 0) {\n GradientHelper.GetCurrentGradient(ratio, this._colorRemapGradients, (currentGradient, nextGradient, scale) => {\n const min = Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);\n const max = Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);\n particle.remapData.x = min;\n particle.remapData.y = max - min;\n });\n }\n if (this._alphaRemapGradients && this._alphaRemapGradients.length > 0) {\n GradientHelper.GetCurrentGradient(ratio, this._alphaRemapGradients, (currentGradient, nextGradient, scale) => {\n const min = Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);\n const max = Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);\n particle.remapData.z = min;\n particle.remapData.w = max - min;\n });\n }\n }\n if (this._isAnimationSheetEnabled) {\n particle.updateCellIndex();\n }\n // Update the position of the attached sub-emitters to match their attached particle\n particle._inheritParticleInfoToSubEmitters();\n if (particle.age >= particle.lifeTime) {\n // Recycle by swapping with last particle\n this._emitFromParticle(particle);\n if (particle._attachedSubEmitters) {\n particle._attachedSubEmitters.forEach((subEmitter) => {\n subEmitter.particleSystem.disposeOnStop = true;\n subEmitter.particleSystem.stop();\n });\n particle._attachedSubEmitters = null;\n }\n this.recycleParticle(particle);\n index--;\n continue;\n }\n }\n };\n }\n _addFactorGradient(factorGradients, gradient, factor, factor2) {\n const newGradient = new FactorGradient(gradient, factor, factor2);\n factorGradients.push(newGradient);\n factorGradients.sort((a, b) => {\n if (a.gradient < b.gradient) {\n return -1;\n }\n else if (a.gradient > b.gradient) {\n return 1;\n }\n return 0;\n });\n }\n _removeFactorGradient(factorGradients, gradient) {\n if (!factorGradients) {\n return;\n }\n let index = 0;\n for (const factorGradient of factorGradients) {\n if (factorGradient.gradient === gradient) {\n factorGradients.splice(index, 1);\n break;\n }\n index++;\n }\n }\n /**\n * Adds a new life time gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the life time factor to affect to the specified gradient\n * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from\n * @returns the current particle system\n */\n addLifeTimeGradient(gradient, factor, factor2) {\n if (!this._lifeTimeGradients) {\n this._lifeTimeGradients = [];\n }\n this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);\n return this;\n }\n /**\n * Remove a specific life time gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeLifeTimeGradient(gradient) {\n this._removeFactorGradient(this._lifeTimeGradients, gradient);\n return this;\n }\n /**\n * Adds a new size gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the size factor to affect to the specified gradient\n * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from\n * @returns the current particle system\n */\n addSizeGradient(gradient, factor, factor2) {\n if (!this._sizeGradients) {\n this._sizeGradients = [];\n }\n this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);\n return this;\n }\n /**\n * Remove a specific size gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeSizeGradient(gradient) {\n this._removeFactorGradient(this._sizeGradients, gradient);\n return this;\n }\n /**\n * Adds a new color remap gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param min defines the color remap minimal range\n * @param max defines the color remap maximal range\n * @returns the current particle system\n */\n addColorRemapGradient(gradient, min, max) {\n if (!this._colorRemapGradients) {\n this._colorRemapGradients = [];\n }\n this._addFactorGradient(this._colorRemapGradients, gradient, min, max);\n return this;\n }\n /**\n * Remove a specific color remap gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeColorRemapGradient(gradient) {\n this._removeFactorGradient(this._colorRemapGradients, gradient);\n return this;\n }\n /**\n * Adds a new alpha remap gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param min defines the alpha remap minimal range\n * @param max defines the alpha remap maximal range\n * @returns the current particle system\n */\n addAlphaRemapGradient(gradient, min, max) {\n if (!this._alphaRemapGradients) {\n this._alphaRemapGradients = [];\n }\n this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);\n return this;\n }\n /**\n * Remove a specific alpha remap gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeAlphaRemapGradient(gradient) {\n this._removeFactorGradient(this._alphaRemapGradients, gradient);\n return this;\n }\n /**\n * Adds a new angular speed gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the angular speed to affect to the specified gradient\n * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from\n * @returns the current particle system\n */\n addAngularSpeedGradient(gradient, factor, factor2) {\n if (!this._angularSpeedGradients) {\n this._angularSpeedGradients = [];\n }\n this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);\n return this;\n }\n /**\n * Remove a specific angular speed gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeAngularSpeedGradient(gradient) {\n this._removeFactorGradient(this._angularSpeedGradients, gradient);\n return this;\n }\n /**\n * Adds a new velocity gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the velocity to affect to the specified gradient\n * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from\n * @returns the current particle system\n */\n addVelocityGradient(gradient, factor, factor2) {\n if (!this._velocityGradients) {\n this._velocityGradients = [];\n }\n this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);\n return this;\n }\n /**\n * Remove a specific velocity gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeVelocityGradient(gradient) {\n this._removeFactorGradient(this._velocityGradients, gradient);\n return this;\n }\n /**\n * Adds a new limit velocity gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the limit velocity value to affect to the specified gradient\n * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from\n * @returns the current particle system\n */\n addLimitVelocityGradient(gradient, factor, factor2) {\n if (!this._limitVelocityGradients) {\n this._limitVelocityGradients = [];\n }\n this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);\n return this;\n }\n /**\n * Remove a specific limit velocity gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeLimitVelocityGradient(gradient) {\n this._removeFactorGradient(this._limitVelocityGradients, gradient);\n return this;\n }\n /**\n * Adds a new drag gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the drag value to affect to the specified gradient\n * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from\n * @returns the current particle system\n */\n addDragGradient(gradient, factor, factor2) {\n if (!this._dragGradients) {\n this._dragGradients = [];\n }\n this._addFactorGradient(this._dragGradients, gradient, factor, factor2);\n return this;\n }\n /**\n * Remove a specific drag gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeDragGradient(gradient) {\n this._removeFactorGradient(this._dragGradients, gradient);\n return this;\n }\n /**\n * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the emit rate value to affect to the specified gradient\n * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from\n * @returns the current particle system\n */\n addEmitRateGradient(gradient, factor, factor2) {\n if (!this._emitRateGradients) {\n this._emitRateGradients = [];\n }\n this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);\n return this;\n }\n /**\n * Remove a specific emit rate gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeEmitRateGradient(gradient) {\n this._removeFactorGradient(this._emitRateGradients, gradient);\n return this;\n }\n /**\n * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the start size value to affect to the specified gradient\n * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from\n * @returns the current particle system\n */\n addStartSizeGradient(gradient, factor, factor2) {\n if (!this._startSizeGradients) {\n this._startSizeGradients = [];\n }\n this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);\n return this;\n }\n /**\n * Remove a specific start size gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeStartSizeGradient(gradient) {\n this._removeFactorGradient(this._startSizeGradients, gradient);\n return this;\n }\n _createRampGradientTexture() {\n if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture || !this._scene) {\n return;\n }\n const data = new Uint8Array(this._rawTextureWidth * 4);\n const tmpColor = TmpColors.Color3[0];\n for (let x = 0; x < this._rawTextureWidth; x++) {\n const ratio = x / this._rawTextureWidth;\n GradientHelper.GetCurrentGradient(ratio, this._rampGradients, (currentGradient, nextGradient, scale) => {\n Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);\n data[x * 4] = tmpColor.r * 255;\n data[x * 4 + 1] = tmpColor.g * 255;\n data[x * 4 + 2] = tmpColor.b * 255;\n data[x * 4 + 3] = 255;\n });\n }\n this._rampGradientsTexture = RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, 1);\n }\n /**\n * Gets the current list of ramp gradients.\n * You must use addRampGradient and removeRampGradient to update this list\n * @returns the list of ramp gradients\n */\n getRampGradients() {\n return this._rampGradients;\n }\n /** Force the system to rebuild all gradients that need to be resync */\n forceRefreshGradients() {\n this._syncRampGradientTexture();\n }\n _syncRampGradientTexture() {\n if (!this._rampGradients) {\n return;\n }\n this._rampGradients.sort((a, b) => {\n if (a.gradient < b.gradient) {\n return -1;\n }\n else if (a.gradient > b.gradient) {\n return 1;\n }\n return 0;\n });\n if (this._rampGradientsTexture) {\n this._rampGradientsTexture.dispose();\n this._rampGradientsTexture = null;\n }\n this._createRampGradientTexture();\n }\n /**\n * Adds a new ramp gradient used to remap particle colors\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param color defines the color to affect to the specified gradient\n * @returns the current particle system\n */\n addRampGradient(gradient, color) {\n if (!this._rampGradients) {\n this._rampGradients = [];\n }\n const rampGradient = new Color3Gradient(gradient, color);\n this._rampGradients.push(rampGradient);\n this._syncRampGradientTexture();\n return this;\n }\n /**\n * Remove a specific ramp gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeRampGradient(gradient) {\n this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);\n this._rampGradientsTexture = null;\n if (this._rampGradients && this._rampGradients.length > 0) {\n this._createRampGradientTexture();\n }\n return this;\n }\n /**\n * Adds a new color gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param color1 defines the color to affect to the specified gradient\n * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from\n * @returns this particle system\n */\n addColorGradient(gradient, color1, color2) {\n if (!this._colorGradients) {\n this._colorGradients = [];\n }\n const colorGradient = new ColorGradient(gradient, color1, color2);\n this._colorGradients.push(colorGradient);\n this._colorGradients.sort((a, b) => {\n if (a.gradient < b.gradient) {\n return -1;\n }\n else if (a.gradient > b.gradient) {\n return 1;\n }\n return 0;\n });\n return this;\n }\n /**\n * Remove a specific color gradient\n * @param gradient defines the gradient to remove\n * @returns this particle system\n */\n removeColorGradient(gradient) {\n if (!this._colorGradients) {\n return this;\n }\n let index = 0;\n for (const colorGradient of this._colorGradients) {\n if (colorGradient.gradient === gradient) {\n this._colorGradients.splice(index, 1);\n break;\n }\n index++;\n }\n return this;\n }\n /**\n * Resets the draw wrappers cache\n */\n resetDrawCache() {\n for (const drawWrappers of this._drawWrappers) {\n if (drawWrappers) {\n for (const drawWrapper of drawWrappers) {\n drawWrapper === null || drawWrapper === void 0 ? void 0 : drawWrapper.dispose();\n }\n }\n }\n this._drawWrappers = [];\n }\n _fetchR(u, v, width, height, pixels) {\n u = Math.abs(u) * 0.5 + 0.5;\n v = Math.abs(v) * 0.5 + 0.5;\n const wrappedU = (u * width) % width | 0;\n const wrappedV = (v * height) % height | 0;\n const position = (wrappedU + wrappedV * width) * 4;\n return pixels[position] / 255;\n }\n _reset() {\n this._resetEffect();\n }\n _resetEffect() {\n if (this._vertexBuffer) {\n this._vertexBuffer.dispose();\n this._vertexBuffer = null;\n }\n if (this._spriteBuffer) {\n this._spriteBuffer.dispose();\n this._spriteBuffer = null;\n }\n if (this._vertexArrayObject) {\n this._engine.releaseVertexArrayObject(this._vertexArrayObject);\n this._vertexArrayObject = null;\n }\n this._createVertexBuffers();\n }\n _createVertexBuffers() {\n this._vertexBufferSize = this._useInstancing ? 10 : 12;\n if (this._isAnimationSheetEnabled) {\n this._vertexBufferSize += 1;\n }\n if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL) {\n this._vertexBufferSize += 3;\n }\n if (this._useRampGradients) {\n this._vertexBufferSize += 4;\n }\n const engine = this._engine;\n const vertexSize = this._vertexBufferSize * (this._useInstancing ? 1 : 4);\n this._vertexData = new Float32Array(this._capacity * vertexSize);\n this._vertexBuffer = new Buffer(engine, this._vertexData, true, vertexSize);\n let dataOffset = 0;\n const positions = this._vertexBuffer.createVertexBuffer(VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[VertexBuffer.PositionKind] = positions;\n dataOffset += 3;\n const colors = this._vertexBuffer.createVertexBuffer(VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[VertexBuffer.ColorKind] = colors;\n dataOffset += 4;\n const options = this._vertexBuffer.createVertexBuffer(\"angle\", dataOffset, 1, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[\"angle\"] = options;\n dataOffset += 1;\n const size = this._vertexBuffer.createVertexBuffer(\"size\", dataOffset, 2, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[\"size\"] = size;\n dataOffset += 2;\n if (this._isAnimationSheetEnabled) {\n const cellIndexBuffer = this._vertexBuffer.createVertexBuffer(\"cellIndex\", dataOffset, 1, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[\"cellIndex\"] = cellIndexBuffer;\n dataOffset += 1;\n }\n if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL) {\n const directionBuffer = this._vertexBuffer.createVertexBuffer(\"direction\", dataOffset, 3, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[\"direction\"] = directionBuffer;\n dataOffset += 3;\n }\n if (this._useRampGradients) {\n const rampDataBuffer = this._vertexBuffer.createVertexBuffer(\"remapData\", dataOffset, 4, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[\"remapData\"] = rampDataBuffer;\n dataOffset += 4;\n }\n let offsets;\n if (this._useInstancing) {\n const spriteData = new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]);\n this._spriteBuffer = new Buffer(engine, spriteData, false, 2);\n offsets = this._spriteBuffer.createVertexBuffer(\"offset\", 0, 2);\n }\n else {\n offsets = this._vertexBuffer.createVertexBuffer(\"offset\", dataOffset, 2, this._vertexBufferSize, this._useInstancing);\n dataOffset += 2;\n }\n this._vertexBuffers[\"offset\"] = offsets;\n this.resetDrawCache();\n }\n _createIndexBuffer() {\n if (this._useInstancing) {\n return;\n }\n const indices = [];\n let index = 0;\n for (let count = 0; count < this._capacity; count++) {\n indices.push(index);\n indices.push(index + 1);\n indices.push(index + 2);\n indices.push(index);\n indices.push(index + 2);\n indices.push(index + 3);\n index += 4;\n }\n this._indexBuffer = this._engine.createIndexBuffer(indices);\n }\n /**\n * Gets the maximum number of particles active at the same time.\n * @returns The max number of active particles.\n */\n getCapacity() {\n return this._capacity;\n }\n /**\n * Gets whether there are still active particles in the system.\n * @returns True if it is alive, otherwise false.\n */\n isAlive() {\n return this._alive;\n }\n /**\n * Gets if the system has been started. (Note: this will still be true after stop is called)\n * @returns True if it has been started, otherwise false.\n */\n isStarted() {\n return this._started;\n }\n _prepareSubEmitterInternalArray() {\n this._subEmitters = new Array();\n if (this.subEmitters) {\n this.subEmitters.forEach((subEmitter) => {\n if (subEmitter instanceof ParticleSystem) {\n this._subEmitters.push([new SubEmitter(subEmitter)]);\n }\n else if (subEmitter instanceof SubEmitter) {\n this._subEmitters.push([subEmitter]);\n }\n else if (subEmitter instanceof Array) {\n this._subEmitters.push(subEmitter);\n }\n });\n }\n }\n /**\n * Starts the particle system and begins to emit\n * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)\n */\n start(delay = this.startDelay) {\n var _a;\n if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {\n throw \"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set\";\n }\n if (delay) {\n setTimeout(() => {\n this.start(0);\n }, delay);\n return;\n }\n // Convert the subEmitters field to the constant type field _subEmitters\n this._prepareSubEmitterInternalArray();\n this._started = true;\n this._stopped = false;\n this._actualFrame = 0;\n if (this._subEmitters && this._subEmitters.length != 0) {\n this.activeSubSystems = new Array();\n }\n // Reset emit gradient so it acts the same on every start\n if (this._emitRateGradients) {\n if (this._emitRateGradients.length > 0) {\n this._currentEmitRateGradient = this._emitRateGradients[0];\n this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();\n this._currentEmitRate2 = this._currentEmitRate1;\n }\n if (this._emitRateGradients.length > 1) {\n this._currentEmitRate2 = this._emitRateGradients[1].getFactor();\n }\n }\n // Reset start size gradient so it acts the same on every start\n if (this._startSizeGradients) {\n if (this._startSizeGradients.length > 0) {\n this._currentStartSizeGradient = this._startSizeGradients[0];\n this._currentStartSize1 = this._currentStartSizeGradient.getFactor();\n this._currentStartSize2 = this._currentStartSize1;\n }\n if (this._startSizeGradients.length > 1) {\n this._currentStartSize2 = this._startSizeGradients[1].getFactor();\n }\n }\n if (this.preWarmCycles) {\n if (((_a = this.emitter) === null || _a === void 0 ? void 0 : _a.getClassName().indexOf(\"Mesh\")) !== -1) {\n this.emitter.computeWorldMatrix(true);\n }\n const noiseTextureAsProcedural = this.noiseTexture;\n if (noiseTextureAsProcedural && noiseTextureAsProcedural.onGeneratedObservable) {\n noiseTextureAsProcedural.onGeneratedObservable.addOnce(() => {\n setTimeout(() => {\n for (let index = 0; index < this.preWarmCycles; index++) {\n this.animate(true);\n noiseTextureAsProcedural.render();\n }\n });\n });\n }\n else {\n for (let index = 0; index < this.preWarmCycles; index++) {\n this.animate(true);\n }\n }\n }\n // Animations\n if (this.beginAnimationOnStart && this.animations && this.animations.length > 0 && this._scene) {\n this._scene.beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);\n }\n }\n /**\n * Stops the particle system.\n * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.\n */\n stop(stopSubEmitters = true) {\n if (this._stopped) {\n return;\n }\n this.onStoppedObservable.notifyObservers(this);\n this._stopped = true;\n if (stopSubEmitters) {\n this._stopSubEmitters();\n }\n }\n // animation sheet\n /**\n * Remove all active particles\n */\n reset() {\n this._stockParticles.length = 0;\n this._particles.length = 0;\n }\n /**\n * @internal (for internal use only)\n */\n _appendParticleVertex(index, particle, offsetX, offsetY) {\n let offset = index * this._vertexBufferSize;\n this._vertexData[offset++] = particle.position.x + this.worldOffset.x;\n this._vertexData[offset++] = particle.position.y + this.worldOffset.y;\n this._vertexData[offset++] = particle.position.z + this.worldOffset.z;\n this._vertexData[offset++] = particle.color.r;\n this._vertexData[offset++] = particle.color.g;\n this._vertexData[offset++] = particle.color.b;\n this._vertexData[offset++] = particle.color.a;\n this._vertexData[offset++] = particle.angle;\n this._vertexData[offset++] = particle.scale.x * particle.size;\n this._vertexData[offset++] = particle.scale.y * particle.size;\n if (this._isAnimationSheetEnabled) {\n this._vertexData[offset++] = particle.cellIndex;\n }\n if (!this._isBillboardBased) {\n if (particle._initialDirection) {\n let initialDirection = particle._initialDirection;\n if (this.isLocal) {\n Vector3.TransformNormalToRef(initialDirection, this._emitterWorldMatrix, TmpVectors.Vector3[0]);\n initialDirection = TmpVectors.Vector3[0];\n }\n if (initialDirection.x === 0 && initialDirection.z === 0) {\n initialDirection.x = 0.001;\n }\n this._vertexData[offset++] = initialDirection.x;\n this._vertexData[offset++] = initialDirection.y;\n this._vertexData[offset++] = initialDirection.z;\n }\n else {\n let direction = particle.direction;\n if (this.isLocal) {\n Vector3.TransformNormalToRef(direction, this._emitterWorldMatrix, TmpVectors.Vector3[0]);\n direction = TmpVectors.Vector3[0];\n }\n if (direction.x === 0 && direction.z === 0) {\n direction.x = 0.001;\n }\n this._vertexData[offset++] = direction.x;\n this._vertexData[offset++] = direction.y;\n this._vertexData[offset++] = direction.z;\n }\n }\n else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL) {\n this._vertexData[offset++] = particle.direction.x;\n this._vertexData[offset++] = particle.direction.y;\n this._vertexData[offset++] = particle.direction.z;\n }\n if (this._useRampGradients && particle.remapData) {\n this._vertexData[offset++] = particle.remapData.x;\n this._vertexData[offset++] = particle.remapData.y;\n this._vertexData[offset++] = particle.remapData.z;\n this._vertexData[offset++] = particle.remapData.w;\n }\n if (!this._useInstancing) {\n if (this._isAnimationSheetEnabled) {\n if (offsetX === 0) {\n offsetX = this._epsilon;\n }\n else if (offsetX === 1) {\n offsetX = 1 - this._epsilon;\n }\n if (offsetY === 0) {\n offsetY = this._epsilon;\n }\n else if (offsetY === 1) {\n offsetY = 1 - this._epsilon;\n }\n }\n this._vertexData[offset++] = offsetX;\n this._vertexData[offset++] = offsetY;\n }\n }\n _stopSubEmitters() {\n if (!this.activeSubSystems) {\n return;\n }\n this.activeSubSystems.forEach((subSystem) => {\n subSystem.stop(true);\n });\n this.activeSubSystems = new Array();\n }\n _removeFromRoot() {\n if (!this._rootParticleSystem) {\n return;\n }\n const index = this._rootParticleSystem.activeSubSystems.indexOf(this);\n if (index !== -1) {\n this._rootParticleSystem.activeSubSystems.splice(index, 1);\n }\n this._rootParticleSystem = null;\n }\n // End of sub system methods\n _update(newParticles) {\n // Update current\n this._alive = this._particles.length > 0;\n if (this.emitter.position) {\n const emitterMesh = this.emitter;\n this._emitterWorldMatrix = emitterMesh.getWorldMatrix();\n }\n else {\n const emitterPosition = this.emitter;\n this._emitterWorldMatrix = Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);\n }\n this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix);\n this.updateFunction(this._particles);\n // Add new ones\n let particle;\n for (let index = 0; index < newParticles; index++) {\n if (this._particles.length === this._capacity) {\n break;\n }\n particle = this._createParticle();\n this._particles.push(particle);\n // Life time\n if (this.targetStopDuration && this._lifeTimeGradients && this._lifeTimeGradients.length > 0) {\n const ratio = Scalar.Clamp(this._actualFrame / this.targetStopDuration);\n GradientHelper.GetCurrentGradient(ratio, this._lifeTimeGradients, (currentGradient, nextGradient) => {\n const factorGradient1 = currentGradient;\n const factorGradient2 = nextGradient;\n const lifeTime1 = factorGradient1.getFactor();\n const lifeTime2 = factorGradient2.getFactor();\n const gradient = (ratio - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);\n particle.lifeTime = Scalar.Lerp(lifeTime1, lifeTime2, gradient);\n });\n }\n else {\n particle.lifeTime = Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);\n }\n // Emitter\n const emitPower = Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);\n if (this.startPositionFunction) {\n this.startPositionFunction(this._emitterWorldMatrix, particle.position, particle, this.isLocal);\n }\n else {\n this.particleEmitterType.startPositionFunction(this._emitterWorldMatrix, particle.position, particle, this.isLocal);\n }\n if (this.isLocal) {\n if (!particle._localPosition) {\n particle._localPosition = particle.position.clone();\n }\n else {\n particle._localPosition.copyFrom(particle.position);\n }\n Vector3.TransformCoordinatesToRef(particle._localPosition, this._emitterWorldMatrix, particle.position);\n }\n if (this.startDirectionFunction) {\n this.startDirectionFunction(this._emitterWorldMatrix, particle.direction, particle, this.isLocal);\n }\n else {\n this.particleEmitterType.startDirectionFunction(this._emitterWorldMatrix, particle.direction, particle, this.isLocal, this._emitterInverseWorldMatrix);\n }\n if (emitPower === 0) {\n if (!particle._initialDirection) {\n particle._initialDirection = particle.direction.clone();\n }\n else {\n particle._initialDirection.copyFrom(particle.direction);\n }\n }\n else {\n particle._initialDirection = null;\n }\n particle.direction.scaleInPlace(emitPower);\n // Size\n if (!this._sizeGradients || this._sizeGradients.length === 0) {\n particle.size = Scalar.RandomRange(this.minSize, this.maxSize);\n }\n else {\n particle._currentSizeGradient = this._sizeGradients[0];\n particle._currentSize1 = particle._currentSizeGradient.getFactor();\n particle.size = particle._currentSize1;\n if (this._sizeGradients.length > 1) {\n particle._currentSize2 = this._sizeGradients[1].getFactor();\n }\n else {\n particle._currentSize2 = particle._currentSize1;\n }\n }\n // Size and scale\n particle.scale.copyFromFloats(Scalar.RandomRange(this.minScaleX, this.maxScaleX), Scalar.RandomRange(this.minScaleY, this.maxScaleY));\n // Adjust scale by start size\n if (this._startSizeGradients && this._startSizeGradients[0] && this.targetStopDuration) {\n const ratio = this._actualFrame / this.targetStopDuration;\n GradientHelper.GetCurrentGradient(ratio, this._startSizeGradients, (currentGradient, nextGradient, scale) => {\n if (currentGradient !== this._currentStartSizeGradient) {\n this._currentStartSize1 = this._currentStartSize2;\n this._currentStartSize2 = nextGradient.getFactor();\n this._currentStartSizeGradient = currentGradient;\n }\n const value = Scalar.Lerp(this._currentStartSize1, this._currentStartSize2, scale);\n particle.scale.scaleInPlace(value);\n });\n }\n // Angle\n if (!this._angularSpeedGradients || this._angularSpeedGradients.length === 0) {\n particle.angularSpeed = Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);\n }\n else {\n particle._currentAngularSpeedGradient = this._angularSpeedGradients[0];\n particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();\n particle._currentAngularSpeed1 = particle.angularSpeed;\n if (this._angularSpeedGradients.length > 1) {\n particle._currentAngularSpeed2 = this._angularSpeedGradients[1].getFactor();\n }\n else {\n particle._currentAngularSpeed2 = particle._currentAngularSpeed1;\n }\n }\n particle.angle = Scalar.RandomRange(this.minInitialRotation, this.maxInitialRotation);\n // Velocity\n if (this._velocityGradients && this._velocityGradients.length > 0) {\n particle._currentVelocityGradient = this._velocityGradients[0];\n particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();\n if (this._velocityGradients.length > 1) {\n particle._currentVelocity2 = this._velocityGradients[1].getFactor();\n }\n else {\n particle._currentVelocity2 = particle._currentVelocity1;\n }\n }\n // Limit velocity\n if (this._limitVelocityGradients && this._limitVelocityGradients.length > 0) {\n particle._currentLimitVelocityGradient = this._limitVelocityGradients[0];\n particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();\n if (this._limitVelocityGradients.length > 1) {\n particle._currentLimitVelocity2 = this._limitVelocityGradients[1].getFactor();\n }\n else {\n particle._currentLimitVelocity2 = particle._currentLimitVelocity1;\n }\n }\n // Drag\n if (this._dragGradients && this._dragGradients.length > 0) {\n particle._currentDragGradient = this._dragGradients[0];\n particle._currentDrag1 = particle._currentDragGradient.getFactor();\n if (this._dragGradients.length > 1) {\n particle._currentDrag2 = this._dragGradients[1].getFactor();\n }\n else {\n particle._currentDrag2 = particle._currentDrag1;\n }\n }\n // Color\n if (!this._colorGradients || this._colorGradients.length === 0) {\n const step = Scalar.RandomRange(0, 1.0);\n Color4.LerpToRef(this.color1, this.color2, step, particle.color);\n this.colorDead.subtractToRef(particle.color, this._colorDiff);\n this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);\n }\n else {\n particle._currentColorGradient = this._colorGradients[0];\n particle._currentColorGradient.getColorToRef(particle.color);\n particle._currentColor1.copyFrom(particle.color);\n if (this._colorGradients.length > 1) {\n this._colorGradients[1].getColorToRef(particle._currentColor2);\n }\n else {\n particle._currentColor2.copyFrom(particle.color);\n }\n }\n // Sheet\n if (this._isAnimationSheetEnabled) {\n particle._initialStartSpriteCellID = this.startSpriteCellID;\n particle._initialEndSpriteCellID = this.endSpriteCellID;\n particle._initialSpriteCellLoop = this.spriteCellLoop;\n }\n // Inherited Velocity\n particle.direction.addInPlace(this._inheritedVelocityOffset);\n // Ramp\n if (this._useRampGradients) {\n particle.remapData = new Vector4(0, 1, 0, 1);\n }\n // Noise texture coordinates\n if (this.noiseTexture) {\n if (particle._randomNoiseCoordinates1) {\n particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());\n particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());\n }\n else {\n particle._randomNoiseCoordinates1 = new Vector3(Math.random(), Math.random(), Math.random());\n particle._randomNoiseCoordinates2 = new Vector3(Math.random(), Math.random(), Math.random());\n }\n }\n // Update the position of the attached sub-emitters to match their attached particle\n particle._inheritParticleInfoToSubEmitters();\n }\n }\n /**\n * @internal\n */\n static _GetAttributeNamesOrOptions(isAnimationSheetEnabled = false, isBillboardBased = false, useRampGradients = false) {\n const attributeNamesOrOptions = [VertexBuffer.PositionKind, VertexBuffer.ColorKind, \"angle\", \"offset\", \"size\"];\n if (isAnimationSheetEnabled) {\n attributeNamesOrOptions.push(\"cellIndex\");\n }\n if (!isBillboardBased) {\n attributeNamesOrOptions.push(\"direction\");\n }\n if (useRampGradients) {\n attributeNamesOrOptions.push(\"remapData\");\n }\n return attributeNamesOrOptions;\n }\n /**\n * @internal\n */\n static _GetEffectCreationOptions(isAnimationSheetEnabled = false, useLogarithmicDepth = false) {\n const effectCreationOption = [\"invView\", \"view\", \"projection\", \"textureMask\", \"translationPivot\", \"eyePosition\"];\n addClipPlaneUniforms(effectCreationOption);\n if (isAnimationSheetEnabled) {\n effectCreationOption.push(\"particlesInfos\");\n }\n if (useLogarithmicDepth) {\n effectCreationOption.push(\"logarithmicDepthConstant\");\n }\n return effectCreationOption;\n }\n /**\n * Fill the defines array according to the current settings of the particle system\n * @param defines Array to be updated\n * @param blendMode blend mode to take into account when updating the array\n */\n fillDefines(defines, blendMode) {\n if (this._scene) {\n prepareStringDefinesForClipPlanes(this, this._scene, defines);\n }\n if (this._isAnimationSheetEnabled) {\n defines.push(\"#define ANIMATESHEET\");\n }\n if (this.useLogarithmicDepth) {\n defines.push(\"#define LOGARITHMICDEPTH\");\n }\n if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {\n defines.push(\"#define BLENDMULTIPLYMODE\");\n }\n if (this._useRampGradients) {\n defines.push(\"#define RAMPGRADIENT\");\n }\n if (this._isBillboardBased) {\n defines.push(\"#define BILLBOARD\");\n switch (this.billboardMode) {\n case ParticleSystem.BILLBOARDMODE_Y:\n defines.push(\"#define BILLBOARDY\");\n break;\n case ParticleSystem.BILLBOARDMODE_STRETCHED:\n case ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL:\n defines.push(\"#define BILLBOARDSTRETCHED\");\n if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL) {\n defines.push(\"#define BILLBOARDSTRETCHED_LOCAL\");\n }\n break;\n case ParticleSystem.BILLBOARDMODE_ALL:\n defines.push(\"#define BILLBOARDMODE_ALL\");\n break;\n default:\n break;\n }\n }\n if (this._imageProcessingConfiguration) {\n this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);\n defines.push(this._imageProcessingConfigurationDefines.toString());\n }\n }\n /**\n * Fill the uniforms, attributes and samplers arrays according to the current settings of the particle system\n * @param uniforms Uniforms array to fill\n * @param attributes Attributes array to fill\n * @param samplers Samplers array to fill\n */\n fillUniformsAttributesAndSamplerNames(uniforms, attributes, samplers) {\n attributes.push(...ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL, this._useRampGradients));\n uniforms.push(...ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled, this.useLogarithmicDepth));\n samplers.push(\"diffuseSampler\", \"rampSampler\");\n if (this._imageProcessingConfiguration) {\n ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);\n ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);\n }\n }\n /**\n * @internal\n */\n _getWrapper(blendMode) {\n const customWrapper = this._getCustomDrawWrapper(blendMode);\n if (customWrapper === null || customWrapper === void 0 ? void 0 : customWrapper.effect) {\n return customWrapper;\n }\n const defines = [];\n this.fillDefines(defines, blendMode);\n // Effect\n const currentRenderPassId = this._engine._features.supportRenderPasses ? this._engine.currentRenderPassId : 0;\n let drawWrappers = this._drawWrappers[currentRenderPassId];\n if (!drawWrappers) {\n drawWrappers = this._drawWrappers[currentRenderPassId] = [];\n }\n let drawWrapper = drawWrappers[blendMode];\n if (!drawWrapper) {\n drawWrapper = new DrawWrapper(this._engine);\n if (drawWrapper.drawContext) {\n drawWrapper.drawContext.useInstancing = this._useInstancing;\n }\n drawWrappers[blendMode] = drawWrapper;\n }\n const join = defines.join(\"\\n\");\n if (drawWrapper.defines !== join) {\n const attributesNamesOrOptions = [];\n const effectCreationOption = [];\n const samplers = [];\n this.fillUniformsAttributesAndSamplerNames(effectCreationOption, attributesNamesOrOptions, samplers);\n drawWrapper.setEffect(this._engine.createEffect(\"particles\", attributesNamesOrOptions, effectCreationOption, samplers, join), join);\n }\n return drawWrapper;\n }\n /**\n * Animates the particle system for the current frame by emitting new particles and or animating the living ones.\n * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)\n */\n animate(preWarmOnly = false) {\n var _a;\n if (!this._started) {\n return;\n }\n if (!preWarmOnly && this._scene) {\n // Check\n if (!this.isReady()) {\n return;\n }\n if (this._currentRenderId === this._scene.getFrameId()) {\n return;\n }\n this._currentRenderId = this._scene.getFrameId();\n }\n this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : ((_a = this._scene) === null || _a === void 0 ? void 0 : _a.getAnimationRatio()) || 1);\n // Determine the number of particles we need to create\n let newParticles;\n if (this.manualEmitCount > -1) {\n newParticles = this.manualEmitCount;\n this._newPartsExcess = 0;\n this.manualEmitCount = 0;\n }\n else {\n let rate = this.emitRate;\n if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {\n const ratio = this._actualFrame / this.targetStopDuration;\n GradientHelper.GetCurrentGradient(ratio, this._emitRateGradients, (currentGradient, nextGradient, scale) => {\n if (currentGradient !== this._currentEmitRateGradient) {\n this._currentEmitRate1 = this._currentEmitRate2;\n this._currentEmitRate2 = nextGradient.getFactor();\n this._currentEmitRateGradient = currentGradient;\n }\n rate = Scalar.Lerp(this._currentEmitRate1, this._currentEmitRate2, scale);\n });\n }\n newParticles = (rate * this._scaledUpdateSpeed) >> 0;\n this._newPartsExcess += rate * this._scaledUpdateSpeed - newParticles;\n }\n if (this._newPartsExcess > 1.0) {\n newParticles += this._newPartsExcess >> 0;\n this._newPartsExcess -= this._newPartsExcess >> 0;\n }\n this._alive = false;\n if (!this._stopped) {\n this._actualFrame += this._scaledUpdateSpeed;\n if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {\n this.stop();\n }\n }\n else {\n newParticles = 0;\n }\n this._update(newParticles);\n // Stopped?\n if (this._stopped) {\n if (!this._alive) {\n this._started = false;\n if (this.onAnimationEnd) {\n this.onAnimationEnd();\n }\n if (this.disposeOnStop && this._scene) {\n this._scene._toBeDisposed.push(this);\n }\n }\n }\n if (!preWarmOnly) {\n // Update VBO\n let offset = 0;\n for (let index = 0; index < this._particles.length; index++) {\n const particle = this._particles[index];\n this._appendParticleVertices(offset, particle);\n offset += this._useInstancing ? 1 : 4;\n }\n if (this._vertexBuffer) {\n this._vertexBuffer.updateDirectly(this._vertexData, 0, this._particles.length);\n }\n }\n if (this.manualEmitCount === 0 && this.disposeOnStop) {\n this.stop();\n }\n }\n _appendParticleVertices(offset, particle) {\n this._appendParticleVertex(offset++, particle, 0, 0);\n if (!this._useInstancing) {\n this._appendParticleVertex(offset++, particle, 1, 0);\n this._appendParticleVertex(offset++, particle, 1, 1);\n this._appendParticleVertex(offset++, particle, 0, 1);\n }\n }\n /**\n * Rebuilds the particle system.\n */\n rebuild() {\n var _a, _b;\n if (this._engine.getCaps().vertexArrayObject) {\n this._vertexArrayObject = null;\n }\n this._createIndexBuffer();\n (_a = this._spriteBuffer) === null || _a === void 0 ? void 0 : _a._rebuild();\n (_b = this._vertexBuffer) === null || _b === void 0 ? void 0 : _b._rebuild();\n for (const key in this._vertexBuffers) {\n this._vertexBuffers[key]._rebuild();\n }\n this.resetDrawCache();\n }\n /**\n * Is this system ready to be used/rendered\n * @returns true if the system is ready\n */\n isReady() {\n if (!this.emitter || (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.isReady()) || !this.particleTexture || !this.particleTexture.isReady()) {\n return false;\n }\n if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {\n if (!this._getWrapper(this.blendMode).effect.isReady()) {\n return false;\n }\n }\n else {\n if (!this._getWrapper(ParticleSystem.BLENDMODE_MULTIPLY).effect.isReady()) {\n return false;\n }\n if (!this._getWrapper(ParticleSystem.BLENDMODE_ADD).effect.isReady()) {\n return false;\n }\n }\n return true;\n }\n _render(blendMode) {\n var _a, _b;\n const drawWrapper = this._getWrapper(blendMode);\n const effect = drawWrapper.effect;\n const engine = this._engine;\n // Render\n engine.enableEffect(drawWrapper);\n const viewMatrix = (_a = this.defaultViewMatrix) !== null && _a !== void 0 ? _a : this._scene.getViewMatrix();\n effect.setTexture(\"diffuseSampler\", this.particleTexture);\n effect.setMatrix(\"view\", viewMatrix);\n effect.setMatrix(\"projection\", (_b = this.defaultProjectionMatrix) !== null && _b !== void 0 ? _b : this._scene.getProjectionMatrix());\n if (this._isAnimationSheetEnabled && this.particleTexture) {\n const baseSize = this.particleTexture.getBaseSize();\n effect.setFloat3(\"particlesInfos\", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, this.spriteCellWidth / baseSize.width);\n }\n effect.setVector2(\"translationPivot\", this.translationPivot);\n effect.setFloat4(\"textureMask\", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);\n if (this._isBillboardBased && this._scene) {\n const camera = this._scene.activeCamera;\n effect.setVector3(\"eyePosition\", camera.globalPosition);\n }\n if (this._rampGradientsTexture) {\n if (!this._rampGradients || !this._rampGradients.length) {\n this._rampGradientsTexture.dispose();\n this._rampGradientsTexture = null;\n }\n effect.setTexture(\"rampSampler\", this._rampGradientsTexture);\n }\n const defines = effect.defines;\n if (this._scene) {\n bindClipPlane(effect, this, this._scene);\n }\n if (defines.indexOf(\"#define BILLBOARDMODE_ALL\") >= 0) {\n viewMatrix.invertToRef(TmpVectors.Matrix[0]);\n effect.setMatrix(\"invView\", TmpVectors.Matrix[0]);\n }\n if (this._vertexArrayObject !== undefined) {\n if (!this._vertexArrayObject) {\n this._vertexArrayObject = this._engine.recordVertexArrayObject(this._vertexBuffers, this._indexBuffer, effect);\n }\n this._engine.bindVertexArrayObject(this._vertexArrayObject, this._indexBuffer);\n }\n else {\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);\n }\n // Log. depth\n if (this.useLogarithmicDepth && this._scene) {\n MaterialHelper.BindLogDepth(defines, effect, this._scene);\n }\n // image processing\n if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {\n this._imageProcessingConfiguration.bind(effect);\n }\n // Draw order\n switch (blendMode) {\n case ParticleSystem.BLENDMODE_ADD:\n engine.setAlphaMode(1);\n break;\n case ParticleSystem.BLENDMODE_ONEONE:\n engine.setAlphaMode(6);\n break;\n case ParticleSystem.BLENDMODE_STANDARD:\n engine.setAlphaMode(2);\n break;\n case ParticleSystem.BLENDMODE_MULTIPLY:\n engine.setAlphaMode(4);\n break;\n }\n if (this._onBeforeDrawParticlesObservable) {\n this._onBeforeDrawParticlesObservable.notifyObservers(effect);\n }\n if (this._useInstancing) {\n engine.drawArraysType(7, 0, 4, this._particles.length);\n }\n else {\n engine.drawElementsType(0, 0, this._particles.length * 6);\n }\n return this._particles.length;\n }\n /**\n * Renders the particle system in its current state.\n * @returns the current number of particles\n */\n render() {\n // Check\n if (!this.isReady() || !this._particles.length) {\n return 0;\n }\n const engine = this._engine;\n if (engine.setState) {\n engine.setState(false);\n if (this.forceDepthWrite) {\n engine.setDepthWrite(true);\n }\n }\n let outparticles = 0;\n if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {\n outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);\n }\n else {\n outparticles = this._render(this.blendMode);\n }\n this._engine.unbindInstanceAttributes();\n this._engine.setAlphaMode(0);\n return outparticles;\n }\n /**\n * Disposes the particle system and free the associated resources\n * @param disposeTexture defines if the particle texture must be disposed as well (true by default)\n */\n dispose(disposeTexture = true) {\n this.resetDrawCache();\n if (this._vertexBuffer) {\n this._vertexBuffer.dispose();\n this._vertexBuffer = null;\n }\n if (this._spriteBuffer) {\n this._spriteBuffer.dispose();\n this._spriteBuffer = null;\n }\n if (this._indexBuffer) {\n this._engine._releaseBuffer(this._indexBuffer);\n this._indexBuffer = null;\n }\n if (this._vertexArrayObject) {\n this._engine.releaseVertexArrayObject(this._vertexArrayObject);\n this._vertexArrayObject = null;\n }\n if (disposeTexture && this.particleTexture) {\n this.particleTexture.dispose();\n this.particleTexture = null;\n }\n if (disposeTexture && this.noiseTexture) {\n this.noiseTexture.dispose();\n this.noiseTexture = null;\n }\n if (this._rampGradientsTexture) {\n this._rampGradientsTexture.dispose();\n this._rampGradientsTexture = null;\n }\n this._removeFromRoot();\n if (this.subEmitters && !this._subEmitters) {\n this._prepareSubEmitterInternalArray();\n }\n if (this._subEmitters && this._subEmitters.length) {\n for (let index = 0; index < this._subEmitters.length; index++) {\n for (const subEmitter of this._subEmitters[index]) {\n subEmitter.dispose();\n }\n }\n this._subEmitters = [];\n this.subEmitters = [];\n }\n if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {\n this.emitter.dispose(true);\n }\n if (this._onBeforeDrawParticlesObservable) {\n this._onBeforeDrawParticlesObservable.clear();\n }\n // Remove from scene\n if (this._scene) {\n const index = this._scene.particleSystems.indexOf(this);\n if (index > -1) {\n this._scene.particleSystems.splice(index, 1);\n }\n this._scene._activeParticleSystems.dispose();\n }\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n this.onStoppedObservable.clear();\n this.reset();\n }\n // Clone\n /**\n * Clones the particle system.\n * @param name The name of the cloned object\n * @param newEmitter The new emitter to use\n * @param cloneTexture Also clone the textures if true\n * @returns the cloned particle system\n */\n clone(name, newEmitter, cloneTexture = false) {\n const custom = Object.assign({}, this._customWrappers);\n let program = null;\n const engine = this._engine;\n if (engine.createEffectForParticles) {\n if (this.customShader != null) {\n program = this.customShader;\n const defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join(\"\\n\") : \"\";\n const effect = engine.createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);\n if (!custom[0]) {\n this.setCustomEffect(effect, 0);\n }\n else {\n custom[0].effect = effect;\n }\n }\n }\n const serialization = this.serialize(cloneTexture);\n const result = ParticleSystem.Parse(serialization, this._scene || this._engine, this._rootUrl);\n result.name = name;\n result.customShader = program;\n result._customWrappers = custom;\n if (newEmitter === undefined) {\n newEmitter = this.emitter;\n }\n if (this.noiseTexture) {\n result.noiseTexture = this.noiseTexture.clone();\n }\n result.emitter = newEmitter;\n if (!this.preventAutoStart) {\n result.start();\n }\n return result;\n }\n /**\n * Serializes the particle system to a JSON object\n * @param serializeTexture defines if the texture must be serialized as well\n * @returns the JSON object\n */\n serialize(serializeTexture = false) {\n const serializationObject = {};\n ParticleSystem._Serialize(serializationObject, this, serializeTexture);\n serializationObject.textureMask = this.textureMask.asArray();\n serializationObject.customShader = this.customShader;\n serializationObject.preventAutoStart = this.preventAutoStart;\n // SubEmitters\n if (this.subEmitters) {\n serializationObject.subEmitters = [];\n if (!this._subEmitters) {\n this._prepareSubEmitterInternalArray();\n }\n for (const subs of this._subEmitters) {\n const cell = [];\n for (const sub of subs) {\n cell.push(sub.serialize(serializeTexture));\n }\n serializationObject.subEmitters.push(cell);\n }\n }\n return serializationObject;\n }\n /**\n * @internal\n */\n static _Serialize(serializationObject, particleSystem, serializeTexture) {\n serializationObject.name = particleSystem.name;\n serializationObject.id = particleSystem.id;\n serializationObject.capacity = particleSystem.getCapacity();\n serializationObject.disposeOnStop = particleSystem.disposeOnStop;\n serializationObject.manualEmitCount = particleSystem.manualEmitCount;\n // Emitter\n if (particleSystem.emitter.position) {\n const emitterMesh = particleSystem.emitter;\n serializationObject.emitterId = emitterMesh.id;\n }\n else {\n const emitterPosition = particleSystem.emitter;\n serializationObject.emitter = emitterPosition.asArray();\n }\n // Emitter\n if (particleSystem.particleEmitterType) {\n serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();\n }\n if (particleSystem.particleTexture) {\n if (serializeTexture) {\n serializationObject.texture = particleSystem.particleTexture.serialize();\n }\n else {\n serializationObject.textureName = particleSystem.particleTexture.name;\n serializationObject.invertY = !!particleSystem.particleTexture._invertY;\n }\n }\n serializationObject.isLocal = particleSystem.isLocal;\n // Animations\n SerializationHelper.AppendSerializedAnimations(particleSystem, serializationObject);\n serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;\n serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;\n serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;\n serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;\n // Particle system\n serializationObject.startDelay = particleSystem.startDelay;\n serializationObject.renderingGroupId = particleSystem.renderingGroupId;\n serializationObject.isBillboardBased = particleSystem.isBillboardBased;\n serializationObject.billboardMode = particleSystem.billboardMode;\n serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;\n serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;\n serializationObject.minSize = particleSystem.minSize;\n serializationObject.maxSize = particleSystem.maxSize;\n serializationObject.minScaleX = particleSystem.minScaleX;\n serializationObject.maxScaleX = particleSystem.maxScaleX;\n serializationObject.minScaleY = particleSystem.minScaleY;\n serializationObject.maxScaleY = particleSystem.maxScaleY;\n serializationObject.minEmitPower = particleSystem.minEmitPower;\n serializationObject.maxEmitPower = particleSystem.maxEmitPower;\n serializationObject.minLifeTime = particleSystem.minLifeTime;\n serializationObject.maxLifeTime = particleSystem.maxLifeTime;\n serializationObject.emitRate = particleSystem.emitRate;\n serializationObject.gravity = particleSystem.gravity.asArray();\n serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();\n serializationObject.color1 = particleSystem.color1.asArray();\n serializationObject.color2 = particleSystem.color2.asArray();\n serializationObject.colorDead = particleSystem.colorDead.asArray();\n serializationObject.updateSpeed = particleSystem.updateSpeed;\n serializationObject.targetStopDuration = particleSystem.targetStopDuration;\n serializationObject.blendMode = particleSystem.blendMode;\n serializationObject.preWarmCycles = particleSystem.preWarmCycles;\n serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;\n serializationObject.minInitialRotation = particleSystem.minInitialRotation;\n serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;\n serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;\n serializationObject.spriteCellLoop = particleSystem.spriteCellLoop;\n serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;\n serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;\n serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;\n serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;\n serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;\n serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;\n serializationObject.useLogarithmicDepth = particleSystem.useLogarithmicDepth;\n const colorGradients = particleSystem.getColorGradients();\n if (colorGradients) {\n serializationObject.colorGradients = [];\n for (const colorGradient of colorGradients) {\n const serializedGradient = {\n gradient: colorGradient.gradient,\n color1: colorGradient.color1.asArray(),\n };\n if (colorGradient.color2) {\n serializedGradient.color2 = colorGradient.color2.asArray();\n }\n else {\n serializedGradient.color2 = colorGradient.color1.asArray();\n }\n serializationObject.colorGradients.push(serializedGradient);\n }\n }\n const rampGradients = particleSystem.getRampGradients();\n if (rampGradients) {\n serializationObject.rampGradients = [];\n for (const rampGradient of rampGradients) {\n const serializedGradient = {\n gradient: rampGradient.gradient,\n color: rampGradient.color.asArray(),\n };\n serializationObject.rampGradients.push(serializedGradient);\n }\n serializationObject.useRampGradients = particleSystem.useRampGradients;\n }\n const colorRemapGradients = particleSystem.getColorRemapGradients();\n if (colorRemapGradients) {\n serializationObject.colorRemapGradients = [];\n for (const colorRemapGradient of colorRemapGradients) {\n const serializedGradient = {\n gradient: colorRemapGradient.gradient,\n factor1: colorRemapGradient.factor1,\n };\n if (colorRemapGradient.factor2 !== undefined) {\n serializedGradient.factor2 = colorRemapGradient.factor2;\n }\n else {\n serializedGradient.factor2 = colorRemapGradient.factor1;\n }\n serializationObject.colorRemapGradients.push(serializedGradient);\n }\n }\n const alphaRemapGradients = particleSystem.getAlphaRemapGradients();\n if (alphaRemapGradients) {\n serializationObject.alphaRemapGradients = [];\n for (const alphaRemapGradient of alphaRemapGradients) {\n const serializedGradient = {\n gradient: alphaRemapGradient.gradient,\n factor1: alphaRemapGradient.factor1,\n };\n if (alphaRemapGradient.factor2 !== undefined) {\n serializedGradient.factor2 = alphaRemapGradient.factor2;\n }\n else {\n serializedGradient.factor2 = alphaRemapGradient.factor1;\n }\n serializationObject.alphaRemapGradients.push(serializedGradient);\n }\n }\n const sizeGradients = particleSystem.getSizeGradients();\n if (sizeGradients) {\n serializationObject.sizeGradients = [];\n for (const sizeGradient of sizeGradients) {\n const serializedGradient = {\n gradient: sizeGradient.gradient,\n factor1: sizeGradient.factor1,\n };\n if (sizeGradient.factor2 !== undefined) {\n serializedGradient.factor2 = sizeGradient.factor2;\n }\n else {\n serializedGradient.factor2 = sizeGradient.factor1;\n }\n serializationObject.sizeGradients.push(serializedGradient);\n }\n }\n const angularSpeedGradients = particleSystem.getAngularSpeedGradients();\n if (angularSpeedGradients) {\n serializationObject.angularSpeedGradients = [];\n for (const angularSpeedGradient of angularSpeedGradients) {\n const serializedGradient = {\n gradient: angularSpeedGradient.gradient,\n factor1: angularSpeedGradient.factor1,\n };\n if (angularSpeedGradient.factor2 !== undefined) {\n serializedGradient.factor2 = angularSpeedGradient.factor2;\n }\n else {\n serializedGradient.factor2 = angularSpeedGradient.factor1;\n }\n serializationObject.angularSpeedGradients.push(serializedGradient);\n }\n }\n const velocityGradients = particleSystem.getVelocityGradients();\n if (velocityGradients) {\n serializationObject.velocityGradients = [];\n for (const velocityGradient of velocityGradients) {\n const serializedGradient = {\n gradient: velocityGradient.gradient,\n factor1: velocityGradient.factor1,\n };\n if (velocityGradient.factor2 !== undefined) {\n serializedGradient.factor2 = velocityGradient.factor2;\n }\n else {\n serializedGradient.factor2 = velocityGradient.factor1;\n }\n serializationObject.velocityGradients.push(serializedGradient);\n }\n }\n const dragGradients = particleSystem.getDragGradients();\n if (dragGradients) {\n serializationObject.dragGradients = [];\n for (const dragGradient of dragGradients) {\n const serializedGradient = {\n gradient: dragGradient.gradient,\n factor1: dragGradient.factor1,\n };\n if (dragGradient.factor2 !== undefined) {\n serializedGradient.factor2 = dragGradient.factor2;\n }\n else {\n serializedGradient.factor2 = dragGradient.factor1;\n }\n serializationObject.dragGradients.push(serializedGradient);\n }\n }\n const emitRateGradients = particleSystem.getEmitRateGradients();\n if (emitRateGradients) {\n serializationObject.emitRateGradients = [];\n for (const emitRateGradient of emitRateGradients) {\n const serializedGradient = {\n gradient: emitRateGradient.gradient,\n factor1: emitRateGradient.factor1,\n };\n if (emitRateGradient.factor2 !== undefined) {\n serializedGradient.factor2 = emitRateGradient.factor2;\n }\n else {\n serializedGradient.factor2 = emitRateGradient.factor1;\n }\n serializationObject.emitRateGradients.push(serializedGradient);\n }\n }\n const startSizeGradients = particleSystem.getStartSizeGradients();\n if (startSizeGradients) {\n serializationObject.startSizeGradients = [];\n for (const startSizeGradient of startSizeGradients) {\n const serializedGradient = {\n gradient: startSizeGradient.gradient,\n factor1: startSizeGradient.factor1,\n };\n if (startSizeGradient.factor2 !== undefined) {\n serializedGradient.factor2 = startSizeGradient.factor2;\n }\n else {\n serializedGradient.factor2 = startSizeGradient.factor1;\n }\n serializationObject.startSizeGradients.push(serializedGradient);\n }\n }\n const lifeTimeGradients = particleSystem.getLifeTimeGradients();\n if (lifeTimeGradients) {\n serializationObject.lifeTimeGradients = [];\n for (const lifeTimeGradient of lifeTimeGradients) {\n const serializedGradient = {\n gradient: lifeTimeGradient.gradient,\n factor1: lifeTimeGradient.factor1,\n };\n if (lifeTimeGradient.factor2 !== undefined) {\n serializedGradient.factor2 = lifeTimeGradient.factor2;\n }\n else {\n serializedGradient.factor2 = lifeTimeGradient.factor1;\n }\n serializationObject.lifeTimeGradients.push(serializedGradient);\n }\n }\n const limitVelocityGradients = particleSystem.getLimitVelocityGradients();\n if (limitVelocityGradients) {\n serializationObject.limitVelocityGradients = [];\n for (const limitVelocityGradient of limitVelocityGradients) {\n const serializedGradient = {\n gradient: limitVelocityGradient.gradient,\n factor1: limitVelocityGradient.factor1,\n };\n if (limitVelocityGradient.factor2 !== undefined) {\n serializedGradient.factor2 = limitVelocityGradient.factor2;\n }\n else {\n serializedGradient.factor2 = limitVelocityGradient.factor1;\n }\n serializationObject.limitVelocityGradients.push(serializedGradient);\n }\n serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;\n }\n if (particleSystem.noiseTexture) {\n serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();\n }\n }\n /**\n * @internal\n */\n static _Parse(parsedParticleSystem, particleSystem, sceneOrEngine, rootUrl) {\n var _a, _b, _c;\n let scene;\n if (sceneOrEngine instanceof ThinEngine) {\n scene = null;\n }\n else {\n scene = sceneOrEngine;\n }\n const internalClass = GetClass(\"BABYLON.Texture\");\n if (internalClass && scene) {\n // Texture\n if (parsedParticleSystem.texture) {\n particleSystem.particleTexture = internalClass.Parse(parsedParticleSystem.texture, scene, rootUrl);\n }\n else if (parsedParticleSystem.textureName) {\n particleSystem.particleTexture = new internalClass(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);\n particleSystem.particleTexture.name = parsedParticleSystem.textureName;\n }\n }\n // Emitter\n if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {\n particleSystem.emitter = Vector3.Zero();\n }\n else if (parsedParticleSystem.emitterId && scene) {\n particleSystem.emitter = scene.getLastMeshById(parsedParticleSystem.emitterId);\n }\n else {\n particleSystem.emitter = Vector3.FromArray(parsedParticleSystem.emitter);\n }\n particleSystem.isLocal = !!parsedParticleSystem.isLocal;\n // Misc.\n if (parsedParticleSystem.renderingGroupId !== undefined) {\n particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;\n }\n if (parsedParticleSystem.isBillboardBased !== undefined) {\n particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;\n }\n if (parsedParticleSystem.billboardMode !== undefined) {\n particleSystem.billboardMode = parsedParticleSystem.billboardMode;\n }\n if (parsedParticleSystem.useLogarithmicDepth !== undefined) {\n particleSystem.useLogarithmicDepth = parsedParticleSystem.useLogarithmicDepth;\n }\n // Animations\n if (parsedParticleSystem.animations) {\n for (let animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {\n const parsedAnimation = parsedParticleSystem.animations[animationIndex];\n const internalClass = GetClass(\"BABYLON.Animation\");\n if (internalClass) {\n particleSystem.animations.push(internalClass.Parse(parsedAnimation));\n }\n }\n particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;\n particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;\n particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;\n particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;\n }\n if (parsedParticleSystem.autoAnimate && scene) {\n scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);\n }\n // Particle system\n particleSystem.startDelay = parsedParticleSystem.startDelay | 0;\n particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;\n particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;\n particleSystem.minSize = parsedParticleSystem.minSize;\n particleSystem.maxSize = parsedParticleSystem.maxSize;\n if (parsedParticleSystem.minScaleX) {\n particleSystem.minScaleX = parsedParticleSystem.minScaleX;\n particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;\n particleSystem.minScaleY = parsedParticleSystem.minScaleY;\n particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;\n }\n if (parsedParticleSystem.preWarmCycles !== undefined) {\n particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;\n particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;\n }\n if (parsedParticleSystem.minInitialRotation !== undefined) {\n particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;\n particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;\n }\n particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;\n particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;\n particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;\n particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;\n particleSystem.emitRate = parsedParticleSystem.emitRate;\n particleSystem.gravity = Vector3.FromArray(parsedParticleSystem.gravity);\n if (parsedParticleSystem.noiseStrength) {\n particleSystem.noiseStrength = Vector3.FromArray(parsedParticleSystem.noiseStrength);\n }\n particleSystem.color1 = Color4.FromArray(parsedParticleSystem.color1);\n particleSystem.color2 = Color4.FromArray(parsedParticleSystem.color2);\n particleSystem.colorDead = Color4.FromArray(parsedParticleSystem.colorDead);\n particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;\n particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;\n particleSystem.blendMode = parsedParticleSystem.blendMode;\n if (parsedParticleSystem.colorGradients) {\n for (const colorGradient of parsedParticleSystem.colorGradients) {\n particleSystem.addColorGradient(colorGradient.gradient, Color4.FromArray(colorGradient.color1), colorGradient.color2 ? Color4.FromArray(colorGradient.color2) : undefined);\n }\n }\n if (parsedParticleSystem.rampGradients) {\n for (const rampGradient of parsedParticleSystem.rampGradients) {\n particleSystem.addRampGradient(rampGradient.gradient, Color3.FromArray(rampGradient.color));\n }\n particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;\n }\n if (parsedParticleSystem.colorRemapGradients) {\n for (const colorRemapGradient of parsedParticleSystem.colorRemapGradients) {\n particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);\n }\n }\n if (parsedParticleSystem.alphaRemapGradients) {\n for (const alphaRemapGradient of parsedParticleSystem.alphaRemapGradients) {\n particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);\n }\n }\n if (parsedParticleSystem.sizeGradients) {\n for (const sizeGradient of parsedParticleSystem.sizeGradients) {\n particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);\n }\n }\n if (parsedParticleSystem.angularSpeedGradients) {\n for (const angularSpeedGradient of parsedParticleSystem.angularSpeedGradients) {\n particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);\n }\n }\n if (parsedParticleSystem.velocityGradients) {\n for (const velocityGradient of parsedParticleSystem.velocityGradients) {\n particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);\n }\n }\n if (parsedParticleSystem.dragGradients) {\n for (const dragGradient of parsedParticleSystem.dragGradients) {\n particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);\n }\n }\n if (parsedParticleSystem.emitRateGradients) {\n for (const emitRateGradient of parsedParticleSystem.emitRateGradients) {\n particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);\n }\n }\n if (parsedParticleSystem.startSizeGradients) {\n for (const startSizeGradient of parsedParticleSystem.startSizeGradients) {\n particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);\n }\n }\n if (parsedParticleSystem.lifeTimeGradients) {\n for (const lifeTimeGradient of parsedParticleSystem.lifeTimeGradients) {\n particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);\n }\n }\n if (parsedParticleSystem.limitVelocityGradients) {\n for (const limitVelocityGradient of parsedParticleSystem.limitVelocityGradients) {\n particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);\n }\n particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;\n }\n if (parsedParticleSystem.noiseTexture && scene) {\n const internalClass = GetClass(\"BABYLON.ProceduralTexture\");\n particleSystem.noiseTexture = internalClass.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);\n }\n // Emitter\n let emitterType;\n if (parsedParticleSystem.particleEmitterType) {\n switch (parsedParticleSystem.particleEmitterType.type) {\n case \"SphereParticleEmitter\":\n emitterType = new SphereParticleEmitter();\n break;\n case \"SphereDirectedParticleEmitter\":\n emitterType = new SphereDirectedParticleEmitter();\n break;\n case \"ConeEmitter\":\n case \"ConeParticleEmitter\":\n emitterType = new ConeParticleEmitter();\n break;\n case \"CylinderParticleEmitter\":\n emitterType = new CylinderParticleEmitter();\n break;\n case \"CylinderDirectedParticleEmitter\":\n emitterType = new CylinderDirectedParticleEmitter();\n break;\n case \"HemisphericParticleEmitter\":\n emitterType = new HemisphericParticleEmitter();\n break;\n case \"PointParticleEmitter\":\n emitterType = new PointParticleEmitter();\n break;\n case \"MeshParticleEmitter\":\n emitterType = new MeshParticleEmitter();\n break;\n case \"BoxEmitter\":\n case \"BoxParticleEmitter\":\n default:\n emitterType = new BoxParticleEmitter();\n break;\n }\n emitterType.parse(parsedParticleSystem.particleEmitterType, scene);\n }\n else {\n emitterType = new BoxParticleEmitter();\n emitterType.parse(parsedParticleSystem, scene);\n }\n particleSystem.particleEmitterType = emitterType;\n // Animation sheet\n particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;\n particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;\n particleSystem.spriteCellLoop = (_a = parsedParticleSystem.spriteCellLoop) !== null && _a !== void 0 ? _a : true;\n particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;\n particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;\n particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;\n particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;\n particleSystem.disposeOnStop = (_b = parsedParticleSystem.disposeOnStop) !== null && _b !== void 0 ? _b : false;\n particleSystem.manualEmitCount = (_c = parsedParticleSystem.manualEmitCount) !== null && _c !== void 0 ? _c : -1;\n }\n /**\n * Parses a JSON object to create a particle system.\n * @param parsedParticleSystem The JSON object to parse\n * @param sceneOrEngine The scene or the engine to create the particle system in\n * @param rootUrl The root url to use to load external dependencies like texture\n * @param doNotStart Ignore the preventAutoStart attribute and does not start\n * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used)\n * @returns the Parsed particle system\n */\n static Parse(parsedParticleSystem, sceneOrEngine, rootUrl, doNotStart = false, capacity) {\n const name = parsedParticleSystem.name;\n let custom = null;\n let program = null;\n let engine;\n let scene;\n if (sceneOrEngine instanceof ThinEngine) {\n engine = sceneOrEngine;\n }\n else {\n scene = sceneOrEngine;\n engine = scene.getEngine();\n }\n if (parsedParticleSystem.customShader && engine.createEffectForParticles) {\n program = parsedParticleSystem.customShader;\n const defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join(\"\\n\") : \"\";\n custom = engine.createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);\n }\n const particleSystem = new ParticleSystem(name, capacity || parsedParticleSystem.capacity, sceneOrEngine, custom, parsedParticleSystem.isAnimationSheetEnabled);\n particleSystem.customShader = program;\n particleSystem._rootUrl = rootUrl;\n if (parsedParticleSystem.id) {\n particleSystem.id = parsedParticleSystem.id;\n }\n // SubEmitters\n if (parsedParticleSystem.subEmitters) {\n particleSystem.subEmitters = [];\n for (const cell of parsedParticleSystem.subEmitters) {\n const cellArray = [];\n for (const sub of cell) {\n cellArray.push(SubEmitter.Parse(sub, sceneOrEngine, rootUrl));\n }\n particleSystem.subEmitters.push(cellArray);\n }\n }\n ParticleSystem._Parse(parsedParticleSystem, particleSystem, sceneOrEngine, rootUrl);\n if (parsedParticleSystem.textureMask) {\n particleSystem.textureMask = Color4.FromArray(parsedParticleSystem.textureMask);\n }\n // Auto start\n if (parsedParticleSystem.preventAutoStart) {\n particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;\n }\n if (!doNotStart && !particleSystem.preventAutoStart) {\n particleSystem.start();\n }\n return particleSystem;\n }\n}\n/**\n * Billboard mode will only apply to Y axis\n */\nParticleSystem.BILLBOARDMODE_Y = 2;\n/**\n * Billboard mode will apply to all axes\n */\nParticleSystem.BILLBOARDMODE_ALL = 7;\n/**\n * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction\n */\nParticleSystem.BILLBOARDMODE_STRETCHED = 8;\n/**\n * Special billboard mode where the particle will be billboard to the camera but only around the axis of the direction of particle emission\n */\nParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL = 9;\nSubEmitter._ParseParticleSystem = ParticleSystem.Parse;\n//# sourceMappingURL=particleSystem.js.map","import { FactorGradient, ColorGradient, GradientHelper } from \"../Misc/gradients.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Matrix, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Color4, TmpColors } from \"../Maths/math.color.js\";\nimport { Scalar } from \"../Maths/math.scalar.js\";\nimport { VertexBuffer, Buffer } from \"../Buffers/buffer.js\";\nimport { BaseParticleSystem } from \"./baseParticleSystem.js\";\nimport { ParticleSystem } from \"./particleSystem.js\";\nimport { BoxParticleEmitter } from \"../Particles/EmitterTypes/boxParticleEmitter.js\";\nimport { MaterialHelper } from \"../Materials/materialHelper.js\";\nimport { ImageProcessingConfiguration } from \"../Materials/imageProcessingConfiguration.js\";\nimport { RawTexture } from \"../Materials/Textures/rawTexture.js\";\n\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { CustomParticleEmitter } from \"./EmitterTypes/customParticleEmitter.js\";\nimport { ThinEngine } from \"../Engines/thinEngine.js\";\nimport { DrawWrapper } from \"../Materials/drawWrapper.js\";\nimport { GetClass } from \"../Misc/typeStore.js\";\nimport { addClipPlaneUniforms, bindClipPlane, prepareStringDefinesForClipPlanes } from \"../Materials/clipPlaneMaterialHelper.js\";\nimport \"../Engines/Extensions/engine.transformFeedback.js\";\nimport \"../Shaders/gpuRenderParticles.fragment.js\";\nimport \"../Shaders/gpuRenderParticles.vertex.js\";\n/**\n * This represents a GPU particle system in Babylon\n * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data\n * @see https://www.babylonjs-playground.com/#PU4WYI#4\n */\nexport class GPUParticleSystem extends BaseParticleSystem {\n /**\n * Gets a boolean indicating if the GPU particles can be rendered on current browser\n */\n static get IsSupported() {\n if (!EngineStore.LastCreatedEngine) {\n return false;\n }\n const caps = EngineStore.LastCreatedEngine.getCaps();\n return caps.supportTransformFeedbacks || caps.supportComputeShaders;\n }\n /**\n * Gets the maximum number of particles active at the same time.\n * @returns The max number of active particles.\n */\n getCapacity() {\n return this._capacity;\n }\n /**\n * Gets or set the number of active particles\n */\n get activeParticleCount() {\n return this._activeCount;\n }\n set activeParticleCount(value) {\n this._activeCount = Math.min(value, this._capacity);\n }\n /**\n * Is this system ready to be used/rendered\n * @returns true if the system is ready\n */\n isReady() {\n if (!this.emitter || (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.isReady()) || !this.particleTexture || !this.particleTexture.isReady()) {\n return false;\n }\n if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {\n if (!this._getWrapper(this.blendMode).effect.isReady()) {\n return false;\n }\n }\n else {\n if (!this._getWrapper(ParticleSystem.BLENDMODE_MULTIPLY).effect.isReady()) {\n return false;\n }\n if (!this._getWrapper(ParticleSystem.BLENDMODE_ADD).effect.isReady()) {\n return false;\n }\n }\n if (!this._platform.isUpdateBufferCreated()) {\n this._recreateUpdateEffect();\n return false;\n }\n return this._platform.isUpdateBufferReady();\n }\n /**\n * Gets if the system has been started. (Note: this will still be true after stop is called)\n * @returns True if it has been started, otherwise false.\n */\n isStarted() {\n return this._started;\n }\n /**\n * Gets if the system has been stopped. (Note: rendering is still happening but the system is frozen)\n * @returns True if it has been stopped, otherwise false.\n */\n isStopped() {\n return this._stopped;\n }\n /**\n * Gets a boolean indicating that the system is stopping\n * @returns true if the system is currently stopping\n */\n isStopping() {\n return false; // Stop is immediate on GPU\n }\n /**\n * Gets the number of particles active at the same time.\n * @returns The number of active particles.\n */\n getActiveCount() {\n return this._currentActiveCount;\n }\n /**\n * Starts the particle system and begins to emit\n * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)\n */\n start(delay = this.startDelay) {\n if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {\n throw \"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set\";\n }\n if (delay) {\n setTimeout(() => {\n this.start(0);\n }, delay);\n return;\n }\n this._started = true;\n this._stopped = false;\n this._preWarmDone = false;\n // Animations\n if (this.beginAnimationOnStart && this.animations && this.animations.length > 0 && this._scene) {\n this._scene.beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);\n }\n }\n /**\n * Stops the particle system.\n */\n stop() {\n if (this._stopped) {\n return;\n }\n this._stopped = true;\n }\n /**\n * Remove all active particles\n */\n reset() {\n this._releaseBuffers();\n this._platform.releaseVertexBuffers();\n this._currentActiveCount = 0;\n this._targetIndex = 0;\n }\n /**\n * Returns the string \"GPUParticleSystem\"\n * @returns a string containing the class name\n */\n getClassName() {\n return \"GPUParticleSystem\";\n }\n /**\n * Gets the custom effect used to render the particles\n * @param blendMode Blend mode for which the effect should be retrieved\n * @returns The effect\n */\n getCustomEffect(blendMode = 0) {\n var _a, _b;\n return (_b = (_a = this._customWrappers[blendMode]) === null || _a === void 0 ? void 0 : _a.effect) !== null && _b !== void 0 ? _b : this._customWrappers[0].effect;\n }\n _getCustomDrawWrapper(blendMode = 0) {\n var _a;\n return (_a = this._customWrappers[blendMode]) !== null && _a !== void 0 ? _a : this._customWrappers[0];\n }\n /**\n * Sets the custom effect used to render the particles\n * @param effect The effect to set\n * @param blendMode Blend mode for which the effect should be set\n */\n setCustomEffect(effect, blendMode = 0) {\n this._customWrappers[blendMode] = new DrawWrapper(this._engine);\n this._customWrappers[blendMode].effect = effect;\n }\n /**\n * Observable that will be called just before the particles are drawn\n */\n get onBeforeDrawParticlesObservable() {\n if (!this._onBeforeDrawParticlesObservable) {\n this._onBeforeDrawParticlesObservable = new Observable();\n }\n return this._onBeforeDrawParticlesObservable;\n }\n /**\n * Gets the name of the particle vertex shader\n */\n get vertexShaderName() {\n return \"gpuRenderParticles\";\n }\n /**\n * Gets the vertex buffers used by the particle system\n * Should be called after render() has been called for the current frame so that the buffers returned are the ones that have been updated\n * in the current frame (there's a ping-pong between two sets of buffers - for a given frame, one set is used as the source and the other as the destination)\n */\n get vertexBuffers() {\n // We return the other buffers than those corresponding to this._targetIndex because it is assumed vertexBuffers will be called in the current frame\n // after render() has been called, meaning that the buffers have already been swapped and this._targetIndex points to the buffers that will be updated\n // in the next frame (and which are the sources in this frame) and (this._targetIndex ^ 1) points to the buffers that have been updated this frame\n // (and that will be the source buffers in the next frame)\n return this._renderVertexBuffers[this._targetIndex ^ 1];\n }\n /**\n * Gets the index buffer used by the particle system (null for GPU particle systems)\n */\n get indexBuffer() {\n return null;\n }\n _removeGradientAndTexture(gradient, gradients, texture) {\n super._removeGradientAndTexture(gradient, gradients, texture);\n this._releaseBuffers();\n return this;\n }\n /**\n * Adds a new color gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param color1 defines the color to affect to the specified gradient\n * @returns the current particle system\n */\n addColorGradient(gradient, color1) {\n if (!this._colorGradients) {\n this._colorGradients = [];\n }\n const colorGradient = new ColorGradient(gradient, color1);\n this._colorGradients.push(colorGradient);\n this._refreshColorGradient(true);\n this._releaseBuffers();\n return this;\n }\n _refreshColorGradient(reorder = false) {\n if (this._colorGradients) {\n if (reorder) {\n this._colorGradients.sort((a, b) => {\n if (a.gradient < b.gradient) {\n return -1;\n }\n else if (a.gradient > b.gradient) {\n return 1;\n }\n return 0;\n });\n }\n if (this._colorGradientsTexture) {\n this._colorGradientsTexture.dispose();\n this._colorGradientsTexture = null;\n }\n }\n }\n /** Force the system to rebuild all gradients that need to be resync */\n forceRefreshGradients() {\n this._refreshColorGradient();\n this._refreshFactorGradient(this._sizeGradients, \"_sizeGradientsTexture\");\n this._refreshFactorGradient(this._angularSpeedGradients, \"_angularSpeedGradientsTexture\");\n this._refreshFactorGradient(this._velocityGradients, \"_velocityGradientsTexture\");\n this._refreshFactorGradient(this._limitVelocityGradients, \"_limitVelocityGradientsTexture\");\n this._refreshFactorGradient(this._dragGradients, \"_dragGradientsTexture\");\n this.reset();\n }\n /**\n * Remove a specific color gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeColorGradient(gradient) {\n this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);\n this._colorGradientsTexture = null;\n return this;\n }\n /**\n * Resets the draw wrappers cache\n */\n resetDrawCache() {\n var _a;\n for (const blendMode in this._drawWrappers) {\n const drawWrapper = this._drawWrappers[blendMode];\n (_a = drawWrapper.drawContext) === null || _a === void 0 ? void 0 : _a.reset();\n }\n }\n _addFactorGradient(factorGradients, gradient, factor) {\n const valueGradient = new FactorGradient(gradient, factor);\n factorGradients.push(valueGradient);\n this._releaseBuffers();\n }\n /**\n * Adds a new size gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the size factor to affect to the specified gradient\n * @returns the current particle system\n */\n addSizeGradient(gradient, factor) {\n if (!this._sizeGradients) {\n this._sizeGradients = [];\n }\n this._addFactorGradient(this._sizeGradients, gradient, factor);\n this._refreshFactorGradient(this._sizeGradients, \"_sizeGradientsTexture\", true);\n this._releaseBuffers();\n return this;\n }\n /**\n * Remove a specific size gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeSizeGradient(gradient) {\n this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);\n this._sizeGradientsTexture = null;\n return this;\n }\n _refreshFactorGradient(factorGradients, textureName, reorder = false) {\n if (!factorGradients) {\n return;\n }\n if (reorder) {\n factorGradients.sort((a, b) => {\n if (a.gradient < b.gradient) {\n return -1;\n }\n else if (a.gradient > b.gradient) {\n return 1;\n }\n return 0;\n });\n }\n const that = this;\n if (that[textureName]) {\n that[textureName].dispose();\n that[textureName] = null;\n }\n }\n /**\n * Adds a new angular speed gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the angular speed to affect to the specified gradient\n * @returns the current particle system\n */\n addAngularSpeedGradient(gradient, factor) {\n if (!this._angularSpeedGradients) {\n this._angularSpeedGradients = [];\n }\n this._addFactorGradient(this._angularSpeedGradients, gradient, factor);\n this._refreshFactorGradient(this._angularSpeedGradients, \"_angularSpeedGradientsTexture\", true);\n this._releaseBuffers();\n return this;\n }\n /**\n * Remove a specific angular speed gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeAngularSpeedGradient(gradient) {\n this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);\n this._angularSpeedGradientsTexture = null;\n return this;\n }\n /**\n * Adds a new velocity gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the velocity to affect to the specified gradient\n * @returns the current particle system\n */\n addVelocityGradient(gradient, factor) {\n if (!this._velocityGradients) {\n this._velocityGradients = [];\n }\n this._addFactorGradient(this._velocityGradients, gradient, factor);\n this._refreshFactorGradient(this._velocityGradients, \"_velocityGradientsTexture\", true);\n this._releaseBuffers();\n return this;\n }\n /**\n * Remove a specific velocity gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeVelocityGradient(gradient) {\n this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);\n this._velocityGradientsTexture = null;\n return this;\n }\n /**\n * Adds a new limit velocity gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the limit velocity value to affect to the specified gradient\n * @returns the current particle system\n */\n addLimitVelocityGradient(gradient, factor) {\n if (!this._limitVelocityGradients) {\n this._limitVelocityGradients = [];\n }\n this._addFactorGradient(this._limitVelocityGradients, gradient, factor);\n this._refreshFactorGradient(this._limitVelocityGradients, \"_limitVelocityGradientsTexture\", true);\n this._releaseBuffers();\n return this;\n }\n /**\n * Remove a specific limit velocity gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeLimitVelocityGradient(gradient) {\n this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);\n this._limitVelocityGradientsTexture = null;\n return this;\n }\n /**\n * Adds a new drag gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the drag value to affect to the specified gradient\n * @returns the current particle system\n */\n addDragGradient(gradient, factor) {\n if (!this._dragGradients) {\n this._dragGradients = [];\n }\n this._addFactorGradient(this._dragGradients, gradient, factor);\n this._refreshFactorGradient(this._dragGradients, \"_dragGradientsTexture\", true);\n this._releaseBuffers();\n return this;\n }\n /**\n * Remove a specific drag gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeDragGradient(gradient) {\n this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);\n this._dragGradientsTexture = null;\n return this;\n }\n /**\n * Not supported by GPUParticleSystem\n * @returns the current particle system\n */\n addEmitRateGradient() {\n // Do nothing as emit rate is not supported by GPUParticleSystem\n return this;\n }\n /**\n * Not supported by GPUParticleSystem\n * @returns the current particle system\n */\n removeEmitRateGradient() {\n // Do nothing as emit rate is not supported by GPUParticleSystem\n return this;\n }\n /**\n * Not supported by GPUParticleSystem\n * @returns the current particle system\n */\n addStartSizeGradient() {\n // Do nothing as start size is not supported by GPUParticleSystem\n return this;\n }\n /**\n * Not supported by GPUParticleSystem\n * @returns the current particle system\n */\n removeStartSizeGradient() {\n // Do nothing as start size is not supported by GPUParticleSystem\n return this;\n }\n /**\n * Not supported by GPUParticleSystem\n * @returns the current particle system\n */\n addColorRemapGradient() {\n // Do nothing as start size is not supported by GPUParticleSystem\n return this;\n }\n /**\n * Not supported by GPUParticleSystem\n * @returns the current particle system\n */\n removeColorRemapGradient() {\n // Do nothing as start size is not supported by GPUParticleSystem\n return this;\n }\n /**\n * Not supported by GPUParticleSystem\n * @returns the current particle system\n */\n addAlphaRemapGradient() {\n // Do nothing as start size is not supported by GPUParticleSystem\n return this;\n }\n /**\n * Not supported by GPUParticleSystem\n * @returns the current particle system\n */\n removeAlphaRemapGradient() {\n // Do nothing as start size is not supported by GPUParticleSystem\n return this;\n }\n /**\n * Not supported by GPUParticleSystem\n * @returns the current particle system\n */\n addRampGradient() {\n //Not supported by GPUParticleSystem\n return this;\n }\n /**\n * Not supported by GPUParticleSystem\n * @returns the current particle system\n */\n removeRampGradient() {\n //Not supported by GPUParticleSystem\n return this;\n }\n /**\n * Not supported by GPUParticleSystem\n * @returns the list of ramp gradients\n */\n getRampGradients() {\n return null;\n }\n /**\n * Not supported by GPUParticleSystem\n * Gets or sets a boolean indicating that ramp gradients must be used\n * @see https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro#ramp-gradients\n */\n get useRampGradients() {\n //Not supported by GPUParticleSystem\n return false;\n }\n set useRampGradients(value) {\n //Not supported by GPUParticleSystem\n }\n /**\n * Not supported by GPUParticleSystem\n * @returns the current particle system\n */\n addLifeTimeGradient() {\n //Not supported by GPUParticleSystem\n return this;\n }\n /**\n * Not supported by GPUParticleSystem\n * @returns the current particle system\n */\n removeLifeTimeGradient() {\n //Not supported by GPUParticleSystem\n return this;\n }\n /**\n * Instantiates a GPU particle system.\n * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.\n * @param name The name of the particle system\n * @param options The options used to create the system\n * @param sceneOrEngine The scene the particle system belongs to or the engine to use if no scene\n * @param customEffect a custom effect used to change the way particles are rendered by default\n * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture\n */\n constructor(name, options, sceneOrEngine, customEffect = null, isAnimationSheetEnabled = false) {\n super(name);\n /**\n * The layer mask we are rendering the particles through.\n */\n this.layerMask = 0x0fffffff;\n this._accumulatedCount = 0;\n this._renderVertexBuffers = [];\n this._targetIndex = 0;\n this._currentRenderId = -1;\n this._currentRenderingCameraUniqueId = -1;\n this._started = false;\n this._stopped = false;\n this._timeDelta = 0;\n /** Indicates that the update of particles is done in the animate function (and not in render). Default: false */\n this.updateInAnimate = false;\n this._actualFrame = 0;\n this._rawTextureWidth = 256;\n /**\n * An event triggered when the system is disposed.\n */\n this.onDisposeObservable = new Observable();\n /**\n * An event triggered when the system is stopped\n */\n this.onStoppedObservable = new Observable();\n /**\n * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls\n * to override the particles.\n */\n this.forceDepthWrite = false;\n this._preWarmDone = false;\n /**\n * Specifies if the particles are updated in emitter local space or world space.\n */\n this.isLocal = false;\n /** Indicates that the particle system is GPU based */\n this.isGPU = true;\n /** @internal */\n this._onBeforeDrawParticlesObservable = null;\n if (!sceneOrEngine || sceneOrEngine.getClassName() === \"Scene\") {\n this._scene = sceneOrEngine || EngineStore.LastCreatedScene;\n this._engine = this._scene.getEngine();\n this.uniqueId = this._scene.getUniqueId();\n this._scene.particleSystems.push(this);\n }\n else {\n this._engine = sceneOrEngine;\n this.defaultProjectionMatrix = Matrix.PerspectiveFovLH(0.8, 1, 0.1, 100, this._engine.isNDCHalfZRange);\n }\n if (this._engine.getCaps().supportComputeShaders) {\n if (!GetClass(\"BABYLON.ComputeShaderParticleSystem\")) {\n throw new Error(\"The ComputeShaderParticleSystem class is not available! Make sure you have imported it.\");\n }\n this._platform = new (GetClass(\"BABYLON.ComputeShaderParticleSystem\"))(this, this._engine);\n }\n else {\n if (!GetClass(\"BABYLON.WebGL2ParticleSystem\")) {\n throw new Error(\"The WebGL2ParticleSystem class is not available! Make sure you have imported it.\");\n }\n this._platform = new (GetClass(\"BABYLON.WebGL2ParticleSystem\"))(this, this._engine);\n }\n this._customWrappers = { 0: new DrawWrapper(this._engine) };\n this._customWrappers[0].effect = customEffect;\n this._drawWrappers = { 0: new DrawWrapper(this._engine) };\n if (this._drawWrappers[0].drawContext) {\n this._drawWrappers[0].drawContext.useInstancing = true;\n }\n // Setup the default processing configuration to the scene.\n this._attachImageProcessingConfiguration(null);\n options = options !== null && options !== void 0 ? options : {};\n if (!options.randomTextureSize) {\n delete options.randomTextureSize;\n }\n const fullOptions = Object.assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);\n const optionsAsNumber = options;\n if (isFinite(optionsAsNumber)) {\n fullOptions.capacity = optionsAsNumber;\n }\n this._capacity = fullOptions.capacity;\n this._activeCount = fullOptions.capacity;\n this._currentActiveCount = 0;\n this._isAnimationSheetEnabled = isAnimationSheetEnabled;\n this.particleEmitterType = new BoxParticleEmitter();\n // Random data\n const maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);\n let d = [];\n for (let i = 0; i < maxTextureSize; ++i) {\n d.push(Math.random());\n d.push(Math.random());\n d.push(Math.random());\n d.push(Math.random());\n }\n this._randomTexture = new RawTexture(new Float32Array(d), maxTextureSize, 1, 5, sceneOrEngine, false, false, 1, 1);\n this._randomTexture.name = \"GPUParticleSystem_random1\";\n this._randomTexture.wrapU = 1;\n this._randomTexture.wrapV = 1;\n d = [];\n for (let i = 0; i < maxTextureSize; ++i) {\n d.push(Math.random());\n d.push(Math.random());\n d.push(Math.random());\n d.push(Math.random());\n }\n this._randomTexture2 = new RawTexture(new Float32Array(d), maxTextureSize, 1, 5, sceneOrEngine, false, false, 1, 1);\n this._randomTexture2.name = \"GPUParticleSystem_random2\";\n this._randomTexture2.wrapU = 1;\n this._randomTexture2.wrapV = 1;\n this._randomTextureSize = maxTextureSize;\n }\n _reset() {\n this._releaseBuffers();\n }\n _createVertexBuffers(updateBuffer, renderBuffer, spriteSource) {\n const renderVertexBuffers = {};\n renderVertexBuffers[\"position\"] = renderBuffer.createVertexBuffer(\"position\", 0, 3, this._attributesStrideSize, true);\n let offset = 3;\n renderVertexBuffers[\"age\"] = renderBuffer.createVertexBuffer(\"age\", offset, 1, this._attributesStrideSize, true);\n offset += 1;\n renderVertexBuffers[\"size\"] = renderBuffer.createVertexBuffer(\"size\", offset, 3, this._attributesStrideSize, true);\n offset += 3;\n renderVertexBuffers[\"life\"] = renderBuffer.createVertexBuffer(\"life\", offset, 1, this._attributesStrideSize, true);\n offset += 1;\n offset += 4; // seed\n if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {\n renderVertexBuffers[\"direction\"] = renderBuffer.createVertexBuffer(\"direction\", offset, 3, this._attributesStrideSize, true);\n }\n offset += 3; // direction\n if (this._platform.alignDataInBuffer) {\n offset += 1;\n }\n if (this.particleEmitterType instanceof CustomParticleEmitter) {\n offset += 3;\n if (this._platform.alignDataInBuffer) {\n offset += 1;\n }\n }\n if (!this._colorGradientsTexture) {\n renderVertexBuffers[\"color\"] = renderBuffer.createVertexBuffer(\"color\", offset, 4, this._attributesStrideSize, true);\n offset += 4;\n }\n if (!this._isBillboardBased) {\n renderVertexBuffers[\"initialDirection\"] = renderBuffer.createVertexBuffer(\"initialDirection\", offset, 3, this._attributesStrideSize, true);\n offset += 3;\n if (this._platform.alignDataInBuffer) {\n offset += 1;\n }\n }\n if (this.noiseTexture) {\n renderVertexBuffers[\"noiseCoordinates1\"] = renderBuffer.createVertexBuffer(\"noiseCoordinates1\", offset, 3, this._attributesStrideSize, true);\n offset += 3;\n if (this._platform.alignDataInBuffer) {\n offset += 1;\n }\n renderVertexBuffers[\"noiseCoordinates2\"] = renderBuffer.createVertexBuffer(\"noiseCoordinates2\", offset, 3, this._attributesStrideSize, true);\n offset += 3;\n if (this._platform.alignDataInBuffer) {\n offset += 1;\n }\n }\n renderVertexBuffers[\"angle\"] = renderBuffer.createVertexBuffer(\"angle\", offset, 1, this._attributesStrideSize, true);\n if (this._angularSpeedGradientsTexture) {\n offset++;\n }\n else {\n offset += 2;\n }\n if (this._isAnimationSheetEnabled) {\n renderVertexBuffers[\"cellIndex\"] = renderBuffer.createVertexBuffer(\"cellIndex\", offset, 1, this._attributesStrideSize, true);\n offset += 1;\n if (this.spriteRandomStartCell) {\n renderVertexBuffers[\"cellStartOffset\"] = renderBuffer.createVertexBuffer(\"cellStartOffset\", offset, 1, this._attributesStrideSize, true);\n offset += 1;\n }\n }\n renderVertexBuffers[\"offset\"] = spriteSource.createVertexBuffer(\"offset\", 0, 2);\n renderVertexBuffers[\"uv\"] = spriteSource.createVertexBuffer(\"uv\", 2, 2);\n this._renderVertexBuffers.push(renderVertexBuffers);\n this._platform.createVertexBuffers(updateBuffer, renderVertexBuffers);\n this.resetDrawCache();\n }\n _initialize(force = false) {\n if (this._buffer0 && !force) {\n return;\n }\n const engine = this._engine;\n const data = new Array();\n this._attributesStrideSize = 21;\n this._targetIndex = 0;\n if (this._platform.alignDataInBuffer) {\n this._attributesStrideSize += 1;\n }\n if (this.particleEmitterType instanceof CustomParticleEmitter) {\n this._attributesStrideSize += 3;\n if (this._platform.alignDataInBuffer) {\n this._attributesStrideSize += 1;\n }\n }\n if (!this.isBillboardBased) {\n this._attributesStrideSize += 3;\n if (this._platform.alignDataInBuffer) {\n this._attributesStrideSize += 1;\n }\n }\n if (this._colorGradientsTexture) {\n this._attributesStrideSize -= 4;\n }\n if (this._angularSpeedGradientsTexture) {\n this._attributesStrideSize -= 1;\n }\n if (this._isAnimationSheetEnabled) {\n this._attributesStrideSize += 1;\n if (this.spriteRandomStartCell) {\n this._attributesStrideSize += 1;\n }\n }\n if (this.noiseTexture) {\n this._attributesStrideSize += 6;\n if (this._platform.alignDataInBuffer) {\n this._attributesStrideSize += 2;\n }\n }\n if (this._platform.alignDataInBuffer) {\n this._attributesStrideSize += 3 - ((this._attributesStrideSize + 3) & 3); // round to multiple of 4\n }\n const usingCustomEmitter = this.particleEmitterType instanceof CustomParticleEmitter;\n const tmpVector = TmpVectors.Vector3[0];\n let offset = 0;\n for (let particleIndex = 0; particleIndex < this._capacity; particleIndex++) {\n // position\n data.push(0.0);\n data.push(0.0);\n data.push(0.0);\n // Age\n data.push(0.0); // create the particle as a dead one to create a new one at start\n // Size\n data.push(0.0);\n data.push(0.0);\n data.push(0.0);\n // life\n data.push(0.0);\n // Seed\n data.push(Math.random());\n data.push(Math.random());\n data.push(Math.random());\n data.push(Math.random());\n // direction\n if (usingCustomEmitter) {\n this.particleEmitterType.particleDestinationGenerator(particleIndex, null, tmpVector);\n data.push(tmpVector.x);\n data.push(tmpVector.y);\n data.push(tmpVector.z);\n }\n else {\n data.push(0.0);\n data.push(0.0);\n data.push(0.0);\n }\n if (this._platform.alignDataInBuffer) {\n data.push(0.0); // dummy0\n }\n offset += 16; // position, age, size, life, seed, direction, dummy0\n if (usingCustomEmitter) {\n this.particleEmitterType.particlePositionGenerator(particleIndex, null, tmpVector);\n data.push(tmpVector.x);\n data.push(tmpVector.y);\n data.push(tmpVector.z);\n if (this._platform.alignDataInBuffer) {\n data.push(0.0); // dummy1\n }\n offset += 4;\n }\n if (!this._colorGradientsTexture) {\n // color\n data.push(0.0);\n data.push(0.0);\n data.push(0.0);\n data.push(0.0);\n offset += 4;\n }\n if (!this.isBillboardBased) {\n // initialDirection\n data.push(0.0);\n data.push(0.0);\n data.push(0.0);\n if (this._platform.alignDataInBuffer) {\n data.push(0.0); // dummy2\n }\n offset += 4;\n }\n if (this.noiseTexture) {\n // Random coordinates for reading into noise texture\n data.push(Math.random());\n data.push(Math.random());\n data.push(Math.random());\n if (this._platform.alignDataInBuffer) {\n data.push(0.0); // dummy3\n }\n data.push(Math.random());\n data.push(Math.random());\n data.push(Math.random());\n if (this._platform.alignDataInBuffer) {\n data.push(0.0); // dummy4\n }\n offset += 8;\n }\n // angle\n data.push(0.0);\n offset += 1;\n if (!this._angularSpeedGradientsTexture) {\n data.push(0.0);\n offset += 1;\n }\n if (this._isAnimationSheetEnabled) {\n data.push(0.0);\n offset += 1;\n if (this.spriteRandomStartCell) {\n data.push(0.0);\n offset += 1;\n }\n }\n if (this._platform.alignDataInBuffer) {\n let numDummies = 3 - ((offset + 3) & 3);\n offset += numDummies;\n while (numDummies-- > 0) {\n data.push(0.0);\n }\n }\n }\n // Sprite data\n const spriteData = new Float32Array([0.5, 0.5, 1, 1, -0.5, 0.5, 0, 1, 0.5, -0.5, 1, 0, -0.5, -0.5, 0, 0]);\n const bufferData1 = this._platform.createParticleBuffer(data);\n const bufferData2 = this._platform.createParticleBuffer(data);\n // Buffers\n this._buffer0 = new Buffer(engine, bufferData1, false, this._attributesStrideSize);\n this._buffer1 = new Buffer(engine, bufferData2, false, this._attributesStrideSize);\n this._spriteBuffer = new Buffer(engine, spriteData, false, 4);\n // Update & Render vertex buffers\n this._renderVertexBuffers = [];\n this._createVertexBuffers(this._buffer0, this._buffer1, this._spriteBuffer);\n this._createVertexBuffers(this._buffer1, this._buffer0, this._spriteBuffer);\n // Links\n this._sourceBuffer = this._buffer0;\n this._targetBuffer = this._buffer1;\n }\n /** @internal */\n _recreateUpdateEffect() {\n this._createColorGradientTexture();\n this._createSizeGradientTexture();\n this._createAngularSpeedGradientTexture();\n this._createVelocityGradientTexture();\n this._createLimitVelocityGradientTexture();\n this._createDragGradientTexture();\n let defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : \"\";\n if (this._isBillboardBased) {\n defines += \"\\n#define BILLBOARD\";\n }\n if (this._colorGradientsTexture) {\n defines += \"\\n#define COLORGRADIENTS\";\n }\n if (this._sizeGradientsTexture) {\n defines += \"\\n#define SIZEGRADIENTS\";\n }\n if (this._angularSpeedGradientsTexture) {\n defines += \"\\n#define ANGULARSPEEDGRADIENTS\";\n }\n if (this._velocityGradientsTexture) {\n defines += \"\\n#define VELOCITYGRADIENTS\";\n }\n if (this._limitVelocityGradientsTexture) {\n defines += \"\\n#define LIMITVELOCITYGRADIENTS\";\n }\n if (this._dragGradientsTexture) {\n defines += \"\\n#define DRAGGRADIENTS\";\n }\n if (this.isAnimationSheetEnabled) {\n defines += \"\\n#define ANIMATESHEET\";\n if (this.spriteRandomStartCell) {\n defines += \"\\n#define ANIMATESHEETRANDOMSTART\";\n }\n }\n if (this.noiseTexture) {\n defines += \"\\n#define NOISE\";\n }\n if (this.isLocal) {\n defines += \"\\n#define LOCAL\";\n }\n if (this._platform.isUpdateBufferCreated() && this._cachedUpdateDefines === defines) {\n return true;\n }\n this._cachedUpdateDefines = defines;\n this._updateBuffer = this._platform.createUpdateBuffer(defines);\n return this._platform.isUpdateBufferReady();\n }\n /**\n * @internal\n */\n _getWrapper(blendMode) {\n const customWrapper = this._getCustomDrawWrapper(blendMode);\n if (customWrapper === null || customWrapper === void 0 ? void 0 : customWrapper.effect) {\n return customWrapper;\n }\n const defines = [];\n this.fillDefines(defines, blendMode);\n // Effect\n let drawWrapper = this._drawWrappers[blendMode];\n if (!drawWrapper) {\n drawWrapper = new DrawWrapper(this._engine);\n if (drawWrapper.drawContext) {\n drawWrapper.drawContext.useInstancing = true;\n }\n this._drawWrappers[blendMode] = drawWrapper;\n }\n const join = defines.join(\"\\n\");\n if (drawWrapper.defines !== join) {\n const attributes = [];\n const uniforms = [];\n const samplers = [];\n this.fillUniformsAttributesAndSamplerNames(uniforms, attributes, samplers);\n drawWrapper.setEffect(this._engine.createEffect(\"gpuRenderParticles\", attributes, uniforms, samplers, join), join);\n }\n return drawWrapper;\n }\n /**\n * @internal\n */\n static _GetAttributeNamesOrOptions(hasColorGradients = false, isAnimationSheetEnabled = false, isBillboardBased = false, isBillboardStretched = false) {\n const attributeNamesOrOptions = [VertexBuffer.PositionKind, \"age\", \"life\", \"size\", \"angle\"];\n if (!hasColorGradients) {\n attributeNamesOrOptions.push(VertexBuffer.ColorKind);\n }\n if (isAnimationSheetEnabled) {\n attributeNamesOrOptions.push(\"cellIndex\");\n }\n if (!isBillboardBased) {\n attributeNamesOrOptions.push(\"initialDirection\");\n }\n if (!isBillboardStretched) {\n attributeNamesOrOptions.push(\"direction\");\n }\n attributeNamesOrOptions.push(\"offset\", VertexBuffer.UVKind);\n return attributeNamesOrOptions;\n }\n /**\n * @internal\n */\n static _GetEffectCreationOptions(isAnimationSheetEnabled = false, useLogarithmicDepth = false) {\n const effectCreationOption = [\"emitterWM\", \"worldOffset\", \"view\", \"projection\", \"colorDead\", \"invView\", \"translationPivot\", \"eyePosition\"];\n addClipPlaneUniforms(effectCreationOption);\n if (isAnimationSheetEnabled) {\n effectCreationOption.push(\"sheetInfos\");\n }\n if (useLogarithmicDepth) {\n effectCreationOption.push(\"logarithmicDepthConstant\");\n }\n return effectCreationOption;\n }\n /**\n * Fill the defines array according to the current settings of the particle system\n * @param defines Array to be updated\n * @param blendMode blend mode to take into account when updating the array\n */\n fillDefines(defines, blendMode = 0) {\n if (this._scene) {\n prepareStringDefinesForClipPlanes(this, this._scene, defines);\n }\n if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {\n defines.push(\"#define BLENDMULTIPLYMODE\");\n }\n if (this.isLocal) {\n defines.push(\"#define LOCAL\");\n }\n if (this.useLogarithmicDepth) {\n defines.push(\"#define LOGARITHMICDEPTH\");\n }\n if (this._isBillboardBased) {\n defines.push(\"#define BILLBOARD\");\n switch (this.billboardMode) {\n case ParticleSystem.BILLBOARDMODE_Y:\n defines.push(\"#define BILLBOARDY\");\n break;\n case ParticleSystem.BILLBOARDMODE_STRETCHED:\n defines.push(\"#define BILLBOARDSTRETCHED\");\n break;\n case ParticleSystem.BILLBOARDMODE_ALL:\n defines.push(\"#define BILLBOARDMODE_ALL\");\n break;\n default:\n break;\n }\n }\n if (this._colorGradientsTexture) {\n defines.push(\"#define COLORGRADIENTS\");\n }\n if (this.isAnimationSheetEnabled) {\n defines.push(\"#define ANIMATESHEET\");\n }\n if (this._imageProcessingConfiguration) {\n this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);\n defines.push(\"\" + this._imageProcessingConfigurationDefines.toString());\n }\n }\n /**\n * Fill the uniforms, attributes and samplers arrays according to the current settings of the particle system\n * @param uniforms Uniforms array to fill\n * @param attributes Attributes array to fill\n * @param samplers Samplers array to fill\n */\n fillUniformsAttributesAndSamplerNames(uniforms, attributes, samplers) {\n attributes.push(...GPUParticleSystem._GetAttributeNamesOrOptions(!!this._colorGradientsTexture, this._isAnimationSheetEnabled, this._isBillboardBased, this._isBillboardBased && this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED));\n uniforms.push(...GPUParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled, this.useLogarithmicDepth));\n samplers.push(\"diffuseSampler\", \"colorGradientSampler\");\n if (this._imageProcessingConfiguration) {\n ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);\n ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);\n }\n }\n /**\n * Animates the particle system for the current frame by emitting new particles and or animating the living ones.\n * @param preWarm defines if we are in the pre-warmimg phase\n */\n animate(preWarm = false) {\n var _a;\n this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : ((_a = this._scene) === null || _a === void 0 ? void 0 : _a.getAnimationRatio()) || 1);\n this._actualFrame += this._timeDelta;\n if (!this._stopped) {\n if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {\n this.stop();\n }\n }\n if (this.updateInAnimate) {\n this._update();\n }\n }\n _createFactorGradientTexture(factorGradients, textureName) {\n const texture = this[textureName];\n if (!factorGradients || !factorGradients.length || texture) {\n return;\n }\n const data = new Float32Array(this._rawTextureWidth);\n for (let x = 0; x < this._rawTextureWidth; x++) {\n const ratio = x / this._rawTextureWidth;\n GradientHelper.GetCurrentGradient(ratio, factorGradients, (currentGradient, nextGradient, scale) => {\n data[x] = Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);\n });\n }\n this[textureName] = RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene || this._engine, false, false, 1);\n this[textureName].name = textureName.substring(1);\n }\n _createSizeGradientTexture() {\n this._createFactorGradientTexture(this._sizeGradients, \"_sizeGradientsTexture\");\n }\n _createAngularSpeedGradientTexture() {\n this._createFactorGradientTexture(this._angularSpeedGradients, \"_angularSpeedGradientsTexture\");\n }\n _createVelocityGradientTexture() {\n this._createFactorGradientTexture(this._velocityGradients, \"_velocityGradientsTexture\");\n }\n _createLimitVelocityGradientTexture() {\n this._createFactorGradientTexture(this._limitVelocityGradients, \"_limitVelocityGradientsTexture\");\n }\n _createDragGradientTexture() {\n this._createFactorGradientTexture(this._dragGradients, \"_dragGradientsTexture\");\n }\n _createColorGradientTexture() {\n if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {\n return;\n }\n const data = new Uint8Array(this._rawTextureWidth * 4);\n const tmpColor = TmpColors.Color4[0];\n for (let x = 0; x < this._rawTextureWidth; x++) {\n const ratio = x / this._rawTextureWidth;\n GradientHelper.GetCurrentGradient(ratio, this._colorGradients, (currentGradient, nextGradient, scale) => {\n Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);\n data[x * 4] = tmpColor.r * 255;\n data[x * 4 + 1] = tmpColor.g * 255;\n data[x * 4 + 2] = tmpColor.b * 255;\n data[x * 4 + 3] = tmpColor.a * 255;\n });\n }\n this._colorGradientsTexture = RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, 1);\n this._colorGradientsTexture.name = \"colorGradients\";\n }\n _render(blendMode, emitterWM) {\n var _a, _b;\n // Enable render effect\n const drawWrapper = this._getWrapper(blendMode);\n const effect = drawWrapper.effect;\n this._engine.enableEffect(drawWrapper);\n const viewMatrix = ((_a = this._scene) === null || _a === void 0 ? void 0 : _a.getViewMatrix()) || Matrix.IdentityReadOnly;\n effect.setMatrix(\"view\", viewMatrix);\n effect.setMatrix(\"projection\", (_b = this.defaultProjectionMatrix) !== null && _b !== void 0 ? _b : this._scene.getProjectionMatrix());\n effect.setTexture(\"diffuseSampler\", this.particleTexture);\n effect.setVector2(\"translationPivot\", this.translationPivot);\n effect.setVector3(\"worldOffset\", this.worldOffset);\n if (this.isLocal) {\n effect.setMatrix(\"emitterWM\", emitterWM);\n }\n if (this._colorGradientsTexture) {\n effect.setTexture(\"colorGradientSampler\", this._colorGradientsTexture);\n }\n else {\n effect.setDirectColor4(\"colorDead\", this.colorDead);\n }\n if (this._isAnimationSheetEnabled && this.particleTexture) {\n const baseSize = this.particleTexture.getBaseSize();\n effect.setFloat3(\"sheetInfos\", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);\n }\n if (this._isBillboardBased && this._scene) {\n const camera = this._scene.activeCamera;\n effect.setVector3(\"eyePosition\", camera.globalPosition);\n }\n const defines = effect.defines;\n if (this._scene) {\n bindClipPlane(effect, this, this._scene);\n }\n if (defines.indexOf(\"#define BILLBOARDMODE_ALL\") >= 0) {\n const invView = viewMatrix.clone();\n invView.invert();\n effect.setMatrix(\"invView\", invView);\n }\n // Log. depth\n if (this.useLogarithmicDepth && this._scene) {\n MaterialHelper.BindLogDepth(defines, effect, this._scene);\n }\n // image processing\n if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {\n this._imageProcessingConfiguration.bind(effect);\n }\n // Draw order\n switch (blendMode) {\n case ParticleSystem.BLENDMODE_ADD:\n this._engine.setAlphaMode(1);\n break;\n case ParticleSystem.BLENDMODE_ONEONE:\n this._engine.setAlphaMode(6);\n break;\n case ParticleSystem.BLENDMODE_STANDARD:\n this._engine.setAlphaMode(2);\n break;\n case ParticleSystem.BLENDMODE_MULTIPLY:\n this._engine.setAlphaMode(4);\n break;\n }\n // Bind source VAO\n this._platform.bindDrawBuffers(this._targetIndex, effect);\n if (this._onBeforeDrawParticlesObservable) {\n this._onBeforeDrawParticlesObservable.notifyObservers(effect);\n }\n // Render\n this._engine.drawArraysType(7, 0, 4, this._currentActiveCount);\n this._engine.setAlphaMode(0);\n return this._currentActiveCount;\n }\n /** @internal */\n _update(emitterWM) {\n if (!this.emitter || !this._targetBuffer) {\n return;\n }\n if (!this._recreateUpdateEffect()) {\n return;\n }\n if (!emitterWM) {\n if (this.emitter.position) {\n const emitterMesh = this.emitter;\n emitterWM = emitterMesh.getWorldMatrix();\n }\n else {\n const emitterPosition = this.emitter;\n emitterWM = TmpVectors.Matrix[0];\n Matrix.TranslationToRef(emitterPosition.x, emitterPosition.y, emitterPosition.z, emitterWM);\n }\n }\n this._platform.preUpdateParticleBuffer();\n this._updateBuffer.setFloat(\"currentCount\", this._currentActiveCount);\n this._updateBuffer.setFloat(\"timeDelta\", this._timeDelta);\n this._updateBuffer.setFloat(\"stopFactor\", this._stopped ? 0 : 1);\n this._updateBuffer.setInt(\"randomTextureSize\", this._randomTextureSize);\n this._updateBuffer.setFloat2(\"lifeTime\", this.minLifeTime, this.maxLifeTime);\n this._updateBuffer.setFloat2(\"emitPower\", this.minEmitPower, this.maxEmitPower);\n if (!this._colorGradientsTexture) {\n this._updateBuffer.setDirectColor4(\"color1\", this.color1);\n this._updateBuffer.setDirectColor4(\"color2\", this.color2);\n }\n this._updateBuffer.setFloat2(\"sizeRange\", this.minSize, this.maxSize);\n this._updateBuffer.setFloat4(\"scaleRange\", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);\n this._updateBuffer.setFloat4(\"angleRange\", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);\n this._updateBuffer.setVector3(\"gravity\", this.gravity);\n if (this._limitVelocityGradientsTexture) {\n this._updateBuffer.setFloat(\"limitVelocityDamping\", this.limitVelocityDamping);\n }\n if (this.particleEmitterType) {\n this.particleEmitterType.applyToShader(this._updateBuffer);\n }\n if (this._isAnimationSheetEnabled) {\n this._updateBuffer.setFloat4(\"cellInfos\", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed, this.spriteCellLoop ? 1 : 0);\n }\n if (this.noiseTexture) {\n this._updateBuffer.setVector3(\"noiseStrength\", this.noiseStrength);\n }\n if (!this.isLocal) {\n this._updateBuffer.setMatrix(\"emitterWM\", emitterWM);\n }\n this._platform.updateParticleBuffer(this._targetIndex, this._targetBuffer, this._currentActiveCount);\n // Switch VAOs\n this._targetIndex++;\n if (this._targetIndex === 2) {\n this._targetIndex = 0;\n }\n // Switch buffers\n const tmpBuffer = this._sourceBuffer;\n this._sourceBuffer = this._targetBuffer;\n this._targetBuffer = tmpBuffer;\n }\n /**\n * Renders the particle system in its current state\n * @param preWarm defines if the system should only update the particles but not render them\n * @param forceUpdateOnly if true, force to only update the particles and never display them (meaning, even if preWarm=false, when forceUpdateOnly=true the particles won't be displayed)\n * @returns the current number of particles\n */\n render(preWarm = false, forceUpdateOnly = false) {\n if (!this._started) {\n return 0;\n }\n if (!this.isReady()) {\n return 0;\n }\n if (!preWarm && this._scene) {\n if (!this._preWarmDone && this.preWarmCycles) {\n for (let index = 0; index < this.preWarmCycles; index++) {\n this.animate(true);\n this.render(true, true);\n }\n this._preWarmDone = true;\n }\n if (this._currentRenderId === this._scene.getRenderId() &&\n (!this._scene.activeCamera || (this._scene.activeCamera && this._currentRenderingCameraUniqueId === this._scene.activeCamera.uniqueId))) {\n return 0;\n }\n this._currentRenderId = this._scene.getRenderId();\n if (this._scene.activeCamera) {\n this._currentRenderingCameraUniqueId = this._scene.activeCamera.uniqueId;\n }\n }\n // Get everything ready to render\n this._initialize();\n this._accumulatedCount += this.emitRate * this._timeDelta;\n if (this._accumulatedCount > 1) {\n const intPart = this._accumulatedCount | 0;\n this._accumulatedCount -= intPart;\n this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);\n }\n if (!this._currentActiveCount) {\n return 0;\n }\n // Enable update effect\n let emitterWM;\n if (this.emitter.position) {\n const emitterMesh = this.emitter;\n emitterWM = emitterMesh.getWorldMatrix();\n }\n else {\n const emitterPosition = this.emitter;\n emitterWM = TmpVectors.Matrix[0];\n Matrix.TranslationToRef(emitterPosition.x, emitterPosition.y, emitterPosition.z, emitterWM);\n }\n const engine = this._engine;\n if (!this.updateInAnimate) {\n this._update(emitterWM);\n }\n let outparticles = 0;\n if (!preWarm && !forceUpdateOnly) {\n engine.setState(false);\n if (this.forceDepthWrite) {\n engine.setDepthWrite(true);\n }\n if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {\n outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY, emitterWM) + this._render(ParticleSystem.BLENDMODE_ADD, emitterWM);\n }\n else {\n outparticles = this._render(this.blendMode, emitterWM);\n }\n this._engine.setAlphaMode(0);\n }\n return outparticles;\n }\n /**\n * Rebuilds the particle system\n */\n rebuild() {\n this._initialize(true);\n }\n _releaseBuffers() {\n if (this._buffer0) {\n this._buffer0.dispose();\n this._buffer0 = null;\n }\n if (this._buffer1) {\n this._buffer1.dispose();\n this._buffer1 = null;\n }\n if (this._spriteBuffer) {\n this._spriteBuffer.dispose();\n this._spriteBuffer = null;\n }\n this._platform.releaseBuffers();\n }\n /**\n * Disposes the particle system and free the associated resources\n * @param disposeTexture defines if the particule texture must be disposed as well (true by default)\n */\n dispose(disposeTexture = true) {\n for (const blendMode in this._drawWrappers) {\n const drawWrapper = this._drawWrappers[blendMode];\n drawWrapper.dispose();\n }\n this._drawWrappers = {};\n if (this._scene) {\n const index = this._scene.particleSystems.indexOf(this);\n if (index > -1) {\n this._scene.particleSystems.splice(index, 1);\n }\n }\n this._releaseBuffers();\n this._platform.releaseVertexBuffers();\n for (let i = 0; i < this._renderVertexBuffers.length; ++i) {\n const rvb = this._renderVertexBuffers[i];\n for (const key in rvb) {\n rvb[key].dispose();\n }\n }\n this._renderVertexBuffers = [];\n if (this._colorGradientsTexture) {\n this._colorGradientsTexture.dispose();\n this._colorGradientsTexture = null;\n }\n if (this._sizeGradientsTexture) {\n this._sizeGradientsTexture.dispose();\n this._sizeGradientsTexture = null;\n }\n if (this._angularSpeedGradientsTexture) {\n this._angularSpeedGradientsTexture.dispose();\n this._angularSpeedGradientsTexture = null;\n }\n if (this._velocityGradientsTexture) {\n this._velocityGradientsTexture.dispose();\n this._velocityGradientsTexture = null;\n }\n if (this._limitVelocityGradientsTexture) {\n this._limitVelocityGradientsTexture.dispose();\n this._limitVelocityGradientsTexture = null;\n }\n if (this._dragGradientsTexture) {\n this._dragGradientsTexture.dispose();\n this._dragGradientsTexture = null;\n }\n if (this._randomTexture) {\n this._randomTexture.dispose();\n this._randomTexture = null;\n }\n if (this._randomTexture2) {\n this._randomTexture2.dispose();\n this._randomTexture2 = null;\n }\n if (disposeTexture && this.particleTexture) {\n this.particleTexture.dispose();\n this.particleTexture = null;\n }\n if (disposeTexture && this.noiseTexture) {\n this.noiseTexture.dispose();\n this.noiseTexture = null;\n }\n // Callback\n this.onStoppedObservable.clear();\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n }\n /**\n * Clones the particle system.\n * @param name The name of the cloned object\n * @param newEmitter The new emitter to use\n * @param cloneTexture Also clone the textures if true\n * @returns the cloned particle system\n */\n clone(name, newEmitter, cloneTexture = false) {\n const custom = Object.assign({}, this._customWrappers);\n let program = null;\n const engine = this._engine;\n if (engine.createEffectForParticles) {\n if (this.customShader != null) {\n program = this.customShader;\n const defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join(\"\\n\") : \"\";\n custom[0] = engine.createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines, undefined, undefined, undefined, this);\n }\n }\n const serialization = this.serialize(cloneTexture);\n const result = GPUParticleSystem.Parse(serialization, this._scene || this._engine, this._rootUrl);\n result.name = name;\n result.customShader = program;\n result._customWrappers = custom;\n if (newEmitter === undefined) {\n newEmitter = this.emitter;\n }\n if (this.noiseTexture) {\n result.noiseTexture = this.noiseTexture.clone();\n }\n result.emitter = newEmitter;\n return result;\n }\n /**\n * Serializes the particle system to a JSON object\n * @param serializeTexture defines if the texture must be serialized as well\n * @returns the JSON object\n */\n serialize(serializeTexture = false) {\n const serializationObject = {};\n ParticleSystem._Serialize(serializationObject, this, serializeTexture);\n serializationObject.activeParticleCount = this.activeParticleCount;\n serializationObject.randomTextureSize = this._randomTextureSize;\n serializationObject.customShader = this.customShader;\n return serializationObject;\n }\n /**\n * Parses a JSON object to create a GPU particle system.\n * @param parsedParticleSystem The JSON object to parse\n * @param sceneOrEngine The scene or the engine to create the particle system in\n * @param rootUrl The root url to use to load external dependencies like texture\n * @param doNotStart Ignore the preventAutoStart attribute and does not start\n * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used)\n * @returns the parsed GPU particle system\n */\n static Parse(parsedParticleSystem, sceneOrEngine, rootUrl, doNotStart = false, capacity) {\n const name = parsedParticleSystem.name;\n let engine;\n let scene;\n if (sceneOrEngine instanceof ThinEngine) {\n engine = sceneOrEngine;\n }\n else {\n scene = sceneOrEngine;\n engine = scene.getEngine();\n }\n const particleSystem = new GPUParticleSystem(name, { capacity: capacity || parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, sceneOrEngine, null, parsedParticleSystem.isAnimationSheetEnabled);\n particleSystem._rootUrl = rootUrl;\n if (parsedParticleSystem.customShader && engine.createEffectForParticles) {\n const program = parsedParticleSystem.customShader;\n const defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join(\"\\n\") : \"\";\n const custom = engine.createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines, undefined, undefined, undefined, particleSystem);\n particleSystem.setCustomEffect(custom, 0);\n particleSystem.customShader = program;\n }\n if (parsedParticleSystem.id) {\n particleSystem.id = parsedParticleSystem.id;\n }\n if (parsedParticleSystem.activeParticleCount) {\n particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;\n }\n ParticleSystem._Parse(parsedParticleSystem, particleSystem, sceneOrEngine, rootUrl);\n // Auto start\n if (parsedParticleSystem.preventAutoStart) {\n particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;\n }\n if (!doNotStart && !particleSystem.preventAutoStart) {\n particleSystem.start();\n }\n return particleSystem;\n }\n}\n//# sourceMappingURL=gpuParticleSystem.js.map","import { Color3 } from \"../Maths/math.color.js\";\nimport { CreateSphere } from \"../Meshes/Builders/sphereBuilder.js\";\nimport { GPUParticleSystem } from \"./gpuParticleSystem.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { ParticleSystem } from \"../Particles/particleSystem.js\";\nimport { StandardMaterial } from \"../Materials/standardMaterial.js\";\n/** Internal class used to store shapes for emitters */\nclass ParticleSystemSetEmitterCreationOptions {\n}\n/**\n * Represents a set of particle systems working together to create a specific effect\n */\nexport class ParticleSystemSet {\n constructor() {\n this._emitterNodeIsOwned = true;\n /**\n * Gets the particle system list\n */\n this.systems = new Array();\n }\n /**\n * Gets or sets the emitter node used with this set\n */\n get emitterNode() {\n return this._emitterNode;\n }\n set emitterNode(value) {\n if (this._emitterNodeIsOwned && this._emitterNode) {\n if (this._emitterNode.dispose) {\n this._emitterNode.dispose();\n }\n this._emitterNodeIsOwned = false;\n }\n for (const system of this.systems) {\n system.emitter = value;\n }\n this._emitterNode = value;\n }\n /**\n * Creates a new emitter mesh as a sphere\n * @param options defines the options used to create the sphere\n * @param options.diameter\n * @param options.segments\n * @param options.color\n * @param renderingGroupId defines the renderingGroupId to use for the sphere\n * @param scene defines the hosting scene\n */\n setEmitterAsSphere(options, renderingGroupId, scene) {\n if (this._emitterNodeIsOwned && this._emitterNode) {\n if (this._emitterNode.dispose) {\n this._emitterNode.dispose();\n }\n }\n this._emitterNodeIsOwned = true;\n this._emitterCreationOptions = {\n kind: \"Sphere\",\n options: options,\n renderingGroupId: renderingGroupId,\n };\n const emitterMesh = CreateSphere(\"emitterSphere\", { diameter: options.diameter, segments: options.segments }, scene);\n emitterMesh.renderingGroupId = renderingGroupId;\n const material = new StandardMaterial(\"emitterSphereMaterial\", scene);\n material.emissiveColor = options.color;\n emitterMesh.material = material;\n for (const system of this.systems) {\n system.emitter = emitterMesh;\n }\n this._emitterNode = emitterMesh;\n }\n /**\n * Starts all particle systems of the set\n * @param emitter defines an optional mesh to use as emitter for the particle systems\n */\n start(emitter) {\n for (const system of this.systems) {\n if (emitter) {\n system.emitter = emitter;\n }\n system.start();\n }\n }\n /**\n * Release all associated resources\n */\n dispose() {\n for (const system of this.systems) {\n system.dispose();\n }\n this.systems.length = 0;\n if (this._emitterNode) {\n if (this._emitterNode.dispose) {\n this._emitterNode.dispose();\n }\n this._emitterNode = null;\n }\n }\n /**\n * Serialize the set into a JSON compatible object\n * @param serializeTexture defines if the texture must be serialized as well\n * @returns a JSON compatible representation of the set\n */\n serialize(serializeTexture = false) {\n const result = {};\n result.systems = [];\n for (const system of this.systems) {\n result.systems.push(system.serialize(serializeTexture));\n }\n if (this._emitterNode) {\n result.emitter = this._emitterCreationOptions;\n }\n return result;\n }\n /**\n * Parse a new ParticleSystemSet from a serialized source\n * @param data defines a JSON compatible representation of the set\n * @param scene defines the hosting scene\n * @param gpu defines if we want GPU particles or CPU particles\n * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used)\n * @returns a new ParticleSystemSet\n */\n static Parse(data, scene, gpu = false, capacity) {\n const result = new ParticleSystemSet();\n const rootUrl = this.BaseAssetsUrl + \"/textures/\";\n scene = scene || EngineStore.LastCreatedScene;\n for (const system of data.systems) {\n result.systems.push(gpu ? GPUParticleSystem.Parse(system, scene, rootUrl, true, capacity) : ParticleSystem.Parse(system, scene, rootUrl, true, capacity));\n }\n if (data.emitter) {\n const options = data.emitter.options;\n switch (data.emitter.kind) {\n case \"Sphere\":\n result.setEmitterAsSphere({\n diameter: options.diameter,\n segments: options.segments,\n color: Color3.FromArray(options.color),\n }, data.emitter.renderingGroupId, scene);\n break;\n }\n }\n return result;\n }\n}\n/**\n * Gets or sets base Assets URL\n */\nParticleSystemSet.BaseAssetsUrl = \"https://assets.babylonjs.com/particles\";\n//# sourceMappingURL=particleSystemSet.js.map","import { Tools } from \"../Misc/tools.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { GPUParticleSystem } from \"./gpuParticleSystem.js\";\nimport { ParticleSystemSet } from \"./particleSystemSet.js\";\nimport { ParticleSystem } from \"./particleSystem.js\";\nimport { WebRequest } from \"../Misc/webRequest.js\";\n\n/**\n * This class is made for on one-liner static method to help creating particle system set.\n */\nexport class ParticleHelper {\n /**\n * Create a default particle system that you can tweak\n * @param emitter defines the emitter to use\n * @param capacity defines the system capacity (default is 500 particles)\n * @param scene defines the hosting scene\n * @param useGPU defines if a GPUParticleSystem must be created (default is false)\n * @returns the new Particle system\n */\n static CreateDefault(emitter, capacity = 500, scene, useGPU = false) {\n let system;\n if (useGPU) {\n system = new GPUParticleSystem(\"default system\", { capacity: capacity }, scene);\n }\n else {\n system = new ParticleSystem(\"default system\", capacity, scene);\n }\n system.emitter = emitter;\n system.particleTexture = new Texture(\"https://assets.babylonjs.com/textures/flare.png\", system.getScene());\n system.createConeEmitter(0.1, Math.PI / 4);\n // Particle color\n system.color1 = new Color4(1.0, 1.0, 1.0, 1.0);\n system.color2 = new Color4(1.0, 1.0, 1.0, 1.0);\n system.colorDead = new Color4(1.0, 1.0, 1.0, 0.0);\n // Particle Size\n system.minSize = 0.1;\n system.maxSize = 0.1;\n // Emission speed\n system.minEmitPower = 2;\n system.maxEmitPower = 2;\n // Update speed\n system.updateSpeed = 1 / 60;\n system.emitRate = 30;\n return system;\n }\n /**\n * This is the main static method (one-liner) of this helper to create different particle systems\n * @param type This string represents the type to the particle system to create\n * @param scene The scene where the particle system should live\n * @param gpu If the system will use gpu\n * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used)\n * @returns the ParticleSystemSet created\n */\n static CreateAsync(type, scene, gpu = false, capacity) {\n if (!scene) {\n scene = EngineStore.LastCreatedScene;\n }\n const token = {};\n scene.addPendingData(token);\n return new Promise((resolve, reject) => {\n if (gpu && !GPUParticleSystem.IsSupported) {\n scene.removePendingData(token);\n return reject(\"Particle system with GPU is not supported.\");\n }\n Tools.LoadFile(`${ParticleHelper.BaseAssetsUrl}/systems/${type}.json`, (data) => {\n scene.removePendingData(token);\n const newData = JSON.parse(data.toString());\n return resolve(ParticleSystemSet.Parse(newData, scene, gpu, capacity));\n }, undefined, undefined, undefined, () => {\n scene.removePendingData(token);\n return reject(`An error occurred with the creation of your particle system. Check if your type '${type}' exists.`);\n });\n });\n }\n /**\n * Static function used to export a particle system to a ParticleSystemSet variable.\n * Please note that the emitter shape is not exported\n * @param systems defines the particle systems to export\n * @returns the created particle system set\n */\n static ExportSet(systems) {\n const set = new ParticleSystemSet();\n for (const system of systems) {\n set.systems.push(system);\n }\n return set;\n }\n /**\n * Creates a particle system from a snippet saved in a remote file\n * @param name defines the name of the particle system to create (can be null or empty to use the one from the json data)\n * @param url defines the url to load from\n * @param scene defines the hosting scene\n * @param gpu If the system will use gpu\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used)\n * @returns a promise that will resolve to the new particle system\n */\n static ParseFromFileAsync(name, url, scene, gpu = false, rootUrl = \"\", capacity) {\n return new Promise((resolve, reject) => {\n const request = new WebRequest();\n request.addEventListener(\"readystatechange\", () => {\n if (request.readyState == 4) {\n if (request.status == 200) {\n const serializationObject = JSON.parse(request.responseText);\n let output;\n if (gpu) {\n output = GPUParticleSystem.Parse(serializationObject, scene, rootUrl, false, capacity);\n }\n else {\n output = ParticleSystem.Parse(serializationObject, scene, rootUrl, false, capacity);\n }\n if (name) {\n output.name = name;\n }\n resolve(output);\n }\n else {\n reject(\"Unable to load the particle system\");\n }\n }\n });\n request.open(\"GET\", url);\n request.send();\n });\n }\n /**\n * Creates a particle system from a snippet saved by the particle system editor\n * @param snippetId defines the snippet to load (can be set to _BLANK to create a default one)\n * @param scene defines the hosting scene\n * @param gpu If the system will use gpu\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used)\n * @returns a promise that will resolve to the new particle system\n */\n static ParseFromSnippetAsync(snippetId, scene, gpu = false, rootUrl = \"\", capacity) {\n if (snippetId === \"_BLANK\") {\n const system = this.CreateDefault(null);\n system.start();\n return Promise.resolve(system);\n }\n return new Promise((resolve, reject) => {\n const request = new WebRequest();\n request.addEventListener(\"readystatechange\", () => {\n if (request.readyState == 4) {\n if (request.status == 200) {\n const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload);\n const serializationObject = JSON.parse(snippet.particleSystem);\n let output;\n if (gpu) {\n output = GPUParticleSystem.Parse(serializationObject, scene, rootUrl, false, capacity);\n }\n else {\n output = ParticleSystem.Parse(serializationObject, scene, rootUrl, false, capacity);\n }\n output.snippetId = snippetId;\n resolve(output);\n }\n else {\n reject(\"Unable to load the snippet \" + snippetId);\n }\n }\n });\n request.open(\"GET\", this.SnippetUrl + \"/\" + snippetId.replace(/#/g, \"/\"));\n request.send();\n });\n }\n}\n/**\n * Gets or sets base Assets URL\n */\nParticleHelper.BaseAssetsUrl = ParticleSystemSet.BaseAssetsUrl;\n/** Define the Url to load snippets */\nParticleHelper.SnippetUrl = `https://snippet.babylonjs.com`;\n/**\n * Creates a particle system from a snippet saved by the particle system editor\n * @deprecated Please use ParseFromSnippetAsync instead\n * @param snippetId defines the snippet to load (can be set to _BLANK to create a default one)\n * @param scene defines the hosting scene\n * @param gpu If the system will use gpu\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used)\n * @returns a promise that will resolve to the new particle system\n */\nParticleHelper.CreateFromSnippetAsync = ParticleHelper.ParseFromSnippetAsync;\n//# sourceMappingURL=particleHelper.js.map","import { Vector3, TmpVectors, Quaternion, Vector4, Vector2 } from \"../Maths/math.vector.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { BoundingInfo } from \"../Culling/boundingInfo.js\";\nimport { BoundingSphere } from \"../Culling/boundingSphere.js\";\nimport { AbstractMesh } from \"../Meshes/abstractMesh.js\";\n/**\n * Represents one particle of a solid particle system.\n */\nexport class SolidParticle {\n /**\n * Particle BoundingInfo object\n * @returns a BoundingInfo\n */\n getBoundingInfo() {\n return this._boundingInfo;\n }\n /**\n * Returns true if there is already a bounding info\n */\n get hasBoundingInfo() {\n return this._boundingInfo !== null;\n }\n /**\n * Creates a Solid Particle object.\n * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()\n * @param particleIndex (integer) is the particle index in the Solid Particle System pool.\n * @param particleId (integer) is the particle identifier. Unless some particles are removed from the SPS, it's the same value than the particle idx.\n * @param positionIndex (integer) is the starting index of the particle vertices in the SPS \"positions\" array.\n * @param indiceIndex (integer) is the starting index of the particle indices in the SPS \"indices\" array.\n * @param model (ModelShape) is a reference to the model shape on what the particle is designed.\n * @param shapeId (integer) is the model shape identifier in the SPS.\n * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))\n * @param sps defines the sps it is associated to\n * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.\n * @param materialIndex is the particle material identifier (integer) when the MultiMaterials are enabled in the SPS.\n */\n constructor(particleIndex, particleId, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo = null, materialIndex = null) {\n /**\n * particle global index\n */\n this.idx = 0;\n /**\n * particle identifier\n */\n this.id = 0;\n /**\n * The color of the particle\n */\n this.color = new Color4(1.0, 1.0, 1.0, 1.0);\n /**\n * The world space position of the particle.\n */\n this.position = Vector3.Zero();\n /**\n * The world space rotation of the particle. (Not use if rotationQuaternion is set)\n */\n this.rotation = Vector3.Zero();\n /**\n * The scaling of the particle.\n */\n this.scaling = Vector3.One();\n /**\n * The uvs of the particle.\n */\n this.uvs = new Vector4(0.0, 0.0, 1.0, 1.0);\n /**\n * The current speed of the particle.\n */\n this.velocity = Vector3.Zero();\n /**\n * The pivot point in the particle local space.\n */\n this.pivot = Vector3.Zero();\n /**\n * Must the particle be translated from its pivot point in its local space ?\n * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.\n * Default : false\n */\n this.translateFromPivot = false;\n /**\n * Is the particle active or not ?\n */\n this.alive = true;\n /**\n * Is the particle visible or not ?\n */\n this.isVisible = true;\n /**\n * Index of this particle in the global \"positions\" array (Internal use)\n * @internal\n */\n this._pos = 0;\n /**\n * @internal Index of this particle in the global \"indices\" array (Internal use)\n */\n this._ind = 0;\n /**\n * ModelShape id of this particle\n */\n this.shapeId = 0;\n /**\n * Index of the particle in its shape id\n */\n this.idxInShape = 0;\n /**\n * @internal Still set as invisible in order to skip useless computations (Internal use)\n */\n this._stillInvisible = false;\n /**\n * @internal Last computed particle rotation matrix\n */\n this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];\n /**\n * Parent particle Id, if any.\n * Default null.\n */\n this.parentId = null;\n /**\n * The particle material identifier (integer) when MultiMaterials are enabled in the SPS.\n */\n this.materialIndex = null;\n /**\n * Custom object or properties.\n */\n this.props = null;\n /**\n * The culling strategy to use to check whether the solid particle must be culled or not when using isInFrustum().\n * The possible values are :\n * - AbstractMesh.CULLINGSTRATEGY_STANDARD\n * - AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY\n * - AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION\n * - AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY\n * The default value for solid particles is AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY\n * Please read each static variable documentation in the class AbstractMesh to get details about the culling process.\n * */\n this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY;\n /**\n * @internal Internal global position in the SPS.\n */\n this._globalPosition = Vector3.Zero();\n this.idx = particleIndex;\n this.id = particleId;\n this._pos = positionIndex;\n this._ind = indiceIndex;\n this._model = model;\n this.shapeId = shapeId;\n this.idxInShape = idxInShape;\n this._sps = sps;\n if (modelBoundingInfo) {\n this._modelBoundingInfo = modelBoundingInfo;\n this._boundingInfo = new BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);\n }\n if (materialIndex !== null) {\n this.materialIndex = materialIndex;\n }\n }\n /**\n * Copies the particle property values into the existing target : position, rotation, scaling, uvs, colors, pivot, parent, visibility, alive\n * @param target the particle target\n * @returns the current particle\n */\n copyToRef(target) {\n target.position.copyFrom(this.position);\n target.rotation.copyFrom(this.rotation);\n if (this.rotationQuaternion) {\n if (target.rotationQuaternion) {\n target.rotationQuaternion.copyFrom(this.rotationQuaternion);\n }\n else {\n target.rotationQuaternion = this.rotationQuaternion.clone();\n }\n }\n target.scaling.copyFrom(this.scaling);\n if (this.color) {\n if (target.color) {\n target.color.copyFrom(this.color);\n }\n else {\n target.color = this.color.clone();\n }\n }\n target.uvs.copyFrom(this.uvs);\n target.velocity.copyFrom(this.velocity);\n target.pivot.copyFrom(this.pivot);\n target.translateFromPivot = this.translateFromPivot;\n target.alive = this.alive;\n target.isVisible = this.isVisible;\n target.parentId = this.parentId;\n target.cullingStrategy = this.cullingStrategy;\n if (this.materialIndex !== null) {\n target.materialIndex = this.materialIndex;\n }\n return this;\n }\n /**\n * Legacy support, changed scale to scaling\n */\n get scale() {\n return this.scaling;\n }\n /**\n * Legacy support, changed scale to scaling\n */\n set scale(scale) {\n this.scaling = scale;\n }\n /**\n * Legacy support, changed quaternion to rotationQuaternion\n */\n get quaternion() {\n return this.rotationQuaternion;\n }\n /**\n * Legacy support, changed quaternion to rotationQuaternion\n */\n set quaternion(q) {\n this.rotationQuaternion = q;\n }\n /**\n * Returns a boolean. True if the particle intersects another particle or another mesh, else false.\n * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)\n * @param target is the object (solid particle or mesh) what the intersection is computed against.\n * @returns true if it intersects\n */\n intersectsMesh(target) {\n if (!this._boundingInfo || !target.hasBoundingInfo) {\n return false;\n }\n if (this._sps._bSphereOnly) {\n return BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target.getBoundingInfo().boundingSphere);\n }\n return this._boundingInfo.intersects(target.getBoundingInfo(), false);\n }\n /**\n * Returns `true` if the solid particle is within the frustum defined by the passed array of planes.\n * A particle is in the frustum if its bounding box intersects the frustum\n * @param frustumPlanes defines the frustum to test\n * @returns true if the particle is in the frustum planes\n */\n isInFrustum(frustumPlanes) {\n return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);\n }\n /**\n * get the rotation matrix of the particle\n * @internal\n */\n getRotationMatrix(m) {\n let quaternion;\n if (this.rotationQuaternion) {\n quaternion = this.rotationQuaternion;\n }\n else {\n quaternion = TmpVectors.Quaternion[0];\n const rotation = this.rotation;\n Quaternion.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, quaternion);\n }\n quaternion.toRotationMatrix(m);\n }\n}\n/**\n * Represents the shape of the model used by one particle of a solid particle system.\n * SPS internal tool, don't use it manually.\n */\nexport class ModelShape {\n /**\n * Get or set the shapeId\n * @deprecated Please use shapeId instead\n */\n get shapeID() {\n return this.shapeId;\n }\n set shapeID(shapeID) {\n this.shapeId = shapeID;\n }\n /**\n * Creates a ModelShape object. This is an internal simplified reference to a mesh used as for a model to replicate particles from by the SPS.\n * SPS internal tool, don't use it manually.\n * @internal\n */\n constructor(id, shape, indices, normals, colors, shapeUV, posFunction, vtxFunction, material) {\n /**\n * length of the shape in the model indices array (internal use)\n * @internal\n */\n this._indicesLength = 0;\n this.shapeId = id;\n this._shape = shape;\n this._indices = indices;\n this._indicesLength = indices.length;\n this._shapeUV = shapeUV;\n this._shapeColors = colors;\n this._normals = normals;\n this._positionFunction = posFunction;\n this._vertexFunction = vtxFunction;\n this._material = material;\n }\n}\n/**\n * Represents a Depth Sorted Particle in the solid particle system.\n * @internal\n */\nexport class DepthSortedParticle {\n /**\n * Creates a new sorted particle\n * @param idx\n * @param ind\n * @param indLength\n * @param materialIndex\n */\n constructor(idx, ind, indLength, materialIndex) {\n /**\n * Particle index\n */\n this.idx = 0;\n /**\n * Index of the particle in the \"indices\" array\n */\n this.ind = 0;\n /**\n * Length of the particle shape in the \"indices\" array\n */\n this.indicesLength = 0;\n /**\n * Squared distance from the particle to the camera\n */\n this.sqDistance = 0.0;\n /**\n * Material index when used with MultiMaterials\n */\n this.materialIndex = 0;\n this.idx = idx;\n this.ind = ind;\n this.indicesLength = indLength;\n this.materialIndex = materialIndex;\n }\n}\n/**\n * Represents a solid particle vertex\n */\nexport class SolidParticleVertex {\n /**\n * Creates a new solid particle vertex\n */\n constructor() {\n this.position = Vector3.Zero();\n this.color = new Color4(1.0, 1.0, 1.0, 1.0);\n this.uv = Vector2.Zero();\n }\n // Getters and Setters for back-compatibility\n /** Vertex x coordinate */\n get x() {\n return this.position.x;\n }\n set x(val) {\n this.position.x = val;\n }\n /** Vertex y coordinate */\n get y() {\n return this.position.y;\n }\n set y(val) {\n this.position.y = val;\n }\n /** Vertex z coordinate */\n get z() {\n return this.position.z;\n }\n set z(val) {\n this.position.z = val;\n }\n}\n//# sourceMappingURL=solidParticle.js.map","import { Vector3, Matrix, TmpVectors, Quaternion } from \"../Maths/math.vector.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { VertexData } from \"../Meshes/mesh.vertexData.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { CreateDisc } from \"../Meshes/Builders/discBuilder.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { DepthSortedParticle, SolidParticle, ModelShape, SolidParticleVertex } from \"./solidParticle.js\";\nimport { BoundingInfo } from \"../Culling/boundingInfo.js\";\nimport { Axis } from \"../Maths/math.axis.js\";\nimport { SubMesh } from \"../Meshes/subMesh.js\";\nimport { StandardMaterial } from \"../Materials/standardMaterial.js\";\nimport { MultiMaterial } from \"../Materials/multiMaterial.js\";\n/**\n * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces of this big mesh.\n *As it is just a mesh, the SPS has all the same properties than any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc.\n\n * The SPS is also a particle system. It provides some methods to manage the particles.\n * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.\n *\n * Full documentation here : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/sps_intro\n */\nexport class SolidParticleSystem {\n /**\n * Creates a SPS (Solid Particle System) object.\n * @param name (String) is the SPS name, this will be the underlying mesh name.\n * @param scene (Scene) is the scene in which the SPS is added.\n * @param options defines the options of the sps e.g.\n * * updatable (optional boolean, default true) : if the SPS must be updatable or immutable.\n * * isPickable (optional boolean, default false) : if the solid particles must be pickable.\n * * enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.\n * * useModelMaterial (optional boolean, default false) : if the model materials must be used to create the SPS multimaterial. This enables the multimaterial supports of the SPS.\n * * enableMultiMaterial (optional boolean, default false) : if the solid particles can be given different materials.\n * * expandable (optional boolean, default false) : if particles can still be added after the initial SPS mesh creation.\n * * particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.\n * * boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).\n * * bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the bounding sphere radius by in order to reduce it for instance.\n * * computeBoundingBox (optional boolean, default false): if the bounding box of the entire SPS will be computed (for occlusion detection, for example). If it is false, the bounding box will be the bounding box of the first particle.\n * * autoFixFaceOrientation (optional boolean, default false): if the particle face orientations will be flipped for transformations that change orientation (scale (-1, 1, 1), for example)\n * @param options.updatable\n * @param options.isPickable\n * @param options.enableDepthSort\n * @param options.particleIntersection\n * @param options.boundingSphereOnly\n * @param options.bSphereRadiusFactor\n * @param options.expandable\n * @param options.useModelMaterial\n * @param options.enableMultiMaterial\n * @param options.computeBoundingBox\n * @param options.autoFixFaceOrientation\n * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.\n */\n constructor(name, scene, options) {\n /**\n * The SPS array of Solid Particle objects. Just access each particle as with any classic array.\n * Example : var p = SPS.particles[i];\n */\n this.particles = new Array();\n /**\n * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.\n */\n this.nbParticles = 0;\n /**\n * If the particles must ever face the camera (default false). Useful for planar particles.\n */\n this.billboard = false;\n /**\n * Recompute normals when adding a shape\n */\n this.recomputeNormals = false;\n /**\n * This a counter ofr your own usage. It's not set by any SPS functions.\n */\n this.counter = 0;\n /**\n * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.\n * Please read : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/optimize_sps#limit-garbage-collection\n */\n this.vars = {};\n /**\n * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)\n * @internal\n */\n this._bSphereOnly = false;\n /**\n * A number to multiply the bounding sphere radius by in order to reduce it for instance. (Internal use only)\n * @internal\n */\n this._bSphereRadiusFactor = 1.0;\n this._positions = new Array();\n this._indices = new Array();\n this._normals = new Array();\n this._colors = new Array();\n this._uvs = new Array();\n this._index = 0; // indices index\n this._updatable = true;\n this._pickable = false;\n this._isVisibilityBoxLocked = false;\n this._alwaysVisible = false;\n this._depthSort = false;\n this._expandable = false;\n this._shapeCounter = 0;\n this._copy = new SolidParticle(0, 0, 0, 0, null, 0, 0, this);\n this._color = new Color4(0, 0, 0, 0);\n this._computeParticleColor = true;\n this._computeParticleTexture = true;\n this._computeParticleRotation = true;\n this._computeParticleVertex = false;\n this._computeBoundingBox = false;\n this._autoFixFaceOrientation = false;\n this._depthSortParticles = true;\n this._mustUnrotateFixedNormals = false;\n this._particlesIntersect = false;\n this._needs32Bits = false;\n this._isNotBuilt = true;\n this._lastParticleId = 0;\n this._idxOfId = []; // array : key = particle.id / value = particle.idx\n this._multimaterialEnabled = false;\n this._useModelMaterial = false;\n this._depthSortFunction = (p1, p2) => p2.sqDistance - p1.sqDistance;\n this._materialSortFunction = (p1, p2) => p1.materialIndex - p2.materialIndex;\n this._autoUpdateSubMeshes = false;\n this._recomputeInvisibles = false;\n this.name = name;\n this._scene = scene || EngineStore.LastCreatedScene;\n this._camera = scene.activeCamera;\n this._pickable = options ? options.isPickable : false;\n this._depthSort = options ? options.enableDepthSort : false;\n this._multimaterialEnabled = options ? options.enableMultiMaterial : false;\n this._useModelMaterial = options ? options.useModelMaterial : false;\n this._multimaterialEnabled = this._useModelMaterial ? true : this._multimaterialEnabled;\n this._expandable = options ? options.expandable : false;\n this._particlesIntersect = options ? options.particleIntersection : false;\n this._bSphereOnly = options ? options.boundingSphereOnly : false;\n this._bSphereRadiusFactor = options && options.bSphereRadiusFactor ? options.bSphereRadiusFactor : 1.0;\n this._computeBoundingBox = (options === null || options === void 0 ? void 0 : options.computeBoundingBox) ? options.computeBoundingBox : false;\n this._autoFixFaceOrientation = (options === null || options === void 0 ? void 0 : options.autoFixFaceOrientation) ? options.autoFixFaceOrientation : false;\n if (options && options.updatable !== undefined) {\n this._updatable = options.updatable;\n }\n else {\n this._updatable = true;\n }\n if (this._pickable) {\n this.pickedBySubMesh = [[]];\n this.pickedParticles = this.pickedBySubMesh[0];\n }\n if (this._depthSort || this._multimaterialEnabled) {\n this.depthSortedParticles = [];\n }\n if (this._multimaterialEnabled) {\n this._multimaterial = new MultiMaterial(this.name + \"MultiMaterial\", this._scene);\n this._materials = [];\n this._materialIndexesById = {};\n }\n this._tmpVertex = new SolidParticleVertex();\n }\n /**\n * Builds the SPS underlying mesh. Returns a standard Mesh.\n * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.\n * @returns the created mesh\n */\n buildMesh() {\n if (!this._isNotBuilt && this.mesh) {\n return this.mesh;\n }\n if (this.nbParticles === 0 && !this.mesh) {\n const triangle = CreateDisc(\"\", { radius: 1, tessellation: 3 }, this._scene);\n this.addShape(triangle, 1);\n triangle.dispose();\n }\n this._indices32 = this._needs32Bits ? new Uint32Array(this._indices) : new Uint16Array(this._indices);\n this._positions32 = new Float32Array(this._positions);\n this._uvs32 = new Float32Array(this._uvs);\n this._colors32 = new Float32Array(this._colors);\n if (!this.mesh) {\n // in case it's already expanded\n const mesh = new Mesh(this.name, this._scene);\n this.mesh = mesh;\n }\n if (!this._updatable && this._multimaterialEnabled) {\n this._sortParticlesByMaterial(); // this may reorder the indices32\n }\n if (this.recomputeNormals) {\n VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);\n }\n this._normals32 = new Float32Array(this._normals);\n this._fixedNormal32 = new Float32Array(this._normals);\n if (this._mustUnrotateFixedNormals) {\n // the particles could be created already rotated in the mesh with a positionFunction\n this._unrotateFixedNormals();\n }\n const vertexData = new VertexData();\n vertexData.indices = this._depthSort ? this._indices : this._indices32;\n vertexData.set(this._positions32, VertexBuffer.PositionKind);\n vertexData.set(this._normals32, VertexBuffer.NormalKind);\n if (this._uvs32.length > 0) {\n vertexData.set(this._uvs32, VertexBuffer.UVKind);\n }\n if (this._colors32.length > 0) {\n vertexData.set(this._colors32, VertexBuffer.ColorKind);\n }\n vertexData.applyToMesh(this.mesh, this._updatable);\n this.mesh.isPickable = this._pickable;\n if (this._pickable) {\n let faceId = 0;\n for (let p = 0; p < this.nbParticles; p++) {\n const part = this.particles[p];\n const lind = part._model._indicesLength;\n for (let i = 0; i < lind; i++) {\n const f = i % 3;\n if (f == 0) {\n const pickedData = { idx: part.idx, faceId: faceId };\n this.pickedParticles[faceId] = pickedData;\n faceId++;\n }\n }\n }\n }\n if (this._multimaterialEnabled) {\n this.setMultiMaterial(this._materials);\n }\n if (!this._expandable) {\n // free memory\n if (!this._depthSort && !this._multimaterialEnabled && !this._autoFixFaceOrientation) {\n this._indices = null;\n }\n this._positions = null;\n this._normals = null;\n this._uvs = null;\n this._colors = null;\n if (!this._updatable) {\n this.particles.length = 0;\n }\n }\n this._isNotBuilt = false;\n this.recomputeNormals = false;\n this._recomputeInvisibles = true;\n return this.mesh;\n }\n /**\n * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.\n * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.\n * Thus the particles generated from `digest()` have their property `position` set yet.\n * @param mesh ( Mesh ) is the mesh to be digested\n * @param options {facetNb} (optional integer, default 1) is the number of mesh facets per particle, this parameter is overridden by the parameter `number` if any\n * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets\n * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets\n * {storage} (optional existing array) is an array where the particles will be stored for a further use instead of being inserted in the SPS.\n * @param options.facetNb\n * @param options.number\n * @param options.delta\n * @param options.storage\n * @returns the current SPS\n */\n digest(mesh, options) {\n let size = (options && options.facetNb) || 1;\n let number = (options && options.number) || 0;\n let delta = (options && options.delta) || 0;\n const meshPos = mesh.getVerticesData(VertexBuffer.PositionKind);\n const meshInd = mesh.getIndices();\n const meshUV = mesh.getVerticesData(VertexBuffer.UVKind);\n const meshCol = mesh.getVerticesData(VertexBuffer.ColorKind);\n const meshNor = mesh.getVerticesData(VertexBuffer.NormalKind);\n const storage = options && options.storage ? options.storage : null;\n let f = 0; // facet counter\n const totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices\n // compute size from number\n if (number) {\n number = number > totalFacets ? totalFacets : number;\n size = Math.round(totalFacets / number);\n delta = 0;\n }\n else {\n size = size > totalFacets ? totalFacets : size;\n }\n const facetPos = []; // submesh positions\n const facetNor = [];\n const facetInd = []; // submesh indices\n const facetUV = []; // submesh UV\n const facetCol = []; // submesh colors\n const barycenter = Vector3.Zero();\n const sizeO = size;\n while (f < totalFacets) {\n size = sizeO + Math.floor((1 + delta) * Math.random());\n if (f > totalFacets - size) {\n size = totalFacets - f;\n }\n // reset temp arrays\n facetPos.length = 0;\n facetNor.length = 0;\n facetInd.length = 0;\n facetUV.length = 0;\n facetCol.length = 0;\n // iterate over \"size\" facets\n let fi = 0;\n for (let j = f * 3; j < (f + size) * 3; j++) {\n facetInd.push(fi);\n const i = meshInd[j];\n const i3 = i * 3;\n facetPos.push(meshPos[i3], meshPos[i3 + 1], meshPos[i3 + 2]);\n facetNor.push(meshNor[i3], meshNor[i3 + 1], meshNor[i3 + 2]);\n if (meshUV) {\n const i2 = i * 2;\n facetUV.push(meshUV[i2], meshUV[i2 + 1]);\n }\n if (meshCol) {\n const i4 = i * 4;\n facetCol.push(meshCol[i4], meshCol[i4 + 1], meshCol[i4 + 2], meshCol[i4 + 3]);\n }\n fi++;\n }\n // create a model shape for each single particle\n let idx = this.nbParticles;\n const shape = this._posToShape(facetPos);\n const shapeUV = this._uvsToShapeUV(facetUV);\n const shapeInd = facetInd.slice();\n const shapeCol = facetCol.slice();\n const shapeNor = facetNor.slice();\n // compute the barycenter of the shape\n barycenter.copyFromFloats(0, 0, 0);\n let v;\n for (v = 0; v < shape.length; v++) {\n barycenter.addInPlace(shape[v]);\n }\n barycenter.scaleInPlace(1 / shape.length);\n // shift the shape from its barycenter to the origin\n // and compute the BBox required for intersection.\n const minimum = new Vector3(Infinity, Infinity, Infinity);\n const maximum = new Vector3(-Infinity, -Infinity, -Infinity);\n for (v = 0; v < shape.length; v++) {\n shape[v].subtractInPlace(barycenter);\n minimum.minimizeInPlaceFromFloats(shape[v].x, shape[v].y, shape[v].z);\n maximum.maximizeInPlaceFromFloats(shape[v].x, shape[v].y, shape[v].z);\n }\n let bInfo;\n if (this._particlesIntersect) {\n bInfo = new BoundingInfo(minimum, maximum);\n }\n let material = null;\n if (this._useModelMaterial) {\n material = mesh.material ? mesh.material : this._setDefaultMaterial();\n }\n const modelShape = new ModelShape(this._shapeCounter, shape, shapeInd, shapeNor, shapeCol, shapeUV, null, null, material);\n // add the particle in the SPS\n const currentPos = this._positions.length;\n const currentInd = this._indices.length;\n this._meshBuilder(this._index, currentInd, shape, this._positions, shapeInd, this._indices, facetUV, this._uvs, shapeCol, this._colors, shapeNor, this._normals, idx, 0, null, modelShape);\n this._addParticle(idx, this._lastParticleId, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo, storage);\n // initialize the particle position\n this.particles[this.nbParticles].position.addInPlace(barycenter);\n if (!storage) {\n this._index += shape.length;\n idx++;\n this.nbParticles++;\n this._lastParticleId++;\n }\n this._shapeCounter++;\n f += size;\n }\n this._isNotBuilt = true; // buildMesh() is now expected for setParticles() to work\n return this;\n }\n /**\n * Unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()\n * @internal\n */\n _unrotateFixedNormals() {\n let index = 0;\n let idx = 0;\n const tmpNormal = TmpVectors.Vector3[0];\n const quaternion = TmpVectors.Quaternion[0];\n const invertedRotMatrix = TmpVectors.Matrix[0];\n for (let p = 0; p < this.particles.length; p++) {\n const particle = this.particles[p];\n const shape = particle._model._shape;\n // computing the inverse of the rotation matrix from the quaternion\n // is equivalent to computing the matrix of the inverse quaternion, i.e of the conjugate quaternion\n if (particle.rotationQuaternion) {\n particle.rotationQuaternion.conjugateToRef(quaternion);\n }\n else {\n const rotation = particle.rotation;\n Quaternion.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, quaternion);\n quaternion.conjugateInPlace();\n }\n quaternion.toRotationMatrix(invertedRotMatrix);\n for (let pt = 0; pt < shape.length; pt++) {\n idx = index + pt * 3;\n Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], invertedRotMatrix, tmpNormal);\n tmpNormal.toArray(this._fixedNormal32, idx);\n }\n index = idx + 3;\n }\n }\n /**\n * Resets the temporary working copy particle\n * @internal\n */\n _resetCopy() {\n const copy = this._copy;\n copy.position.setAll(0);\n copy.rotation.setAll(0);\n copy.rotationQuaternion = null;\n copy.scaling.setAll(1);\n copy.uvs.copyFromFloats(0.0, 0.0, 1.0, 1.0);\n copy.color = null;\n copy.translateFromPivot = false;\n copy.shapeId = 0;\n copy.materialIndex = null;\n }\n /**\n * Inserts the shape model geometry in the global SPS mesh by updating the positions, indices, normals, colors, uvs arrays\n * @param p the current index in the positions array to be updated\n * @param ind the current index in the indices array\n * @param shape a Vector3 array, the shape geometry\n * @param positions the positions array to be updated\n * @param meshInd the shape indices array\n * @param indices the indices array to be updated\n * @param meshUV the shape uv array\n * @param uvs the uv array to be updated\n * @param meshCol the shape color array\n * @param colors the color array to be updated\n * @param meshNor the shape normals array\n * @param normals the normals array to be updated\n * @param idx the particle index\n * @param idxInShape the particle index in its shape\n * @param options the addShape() method passed options\n * @param model\n * @model the particle model\n * @internal\n */\n _meshBuilder(p, ind, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options, model) {\n let i;\n let u = 0;\n let c = 0;\n let n = 0;\n this._resetCopy();\n const copy = this._copy;\n const storeApart = options && options.storage ? true : false;\n copy.idx = idx;\n copy.idxInShape = idxInShape;\n copy.shapeId = model.shapeId;\n if (this._useModelMaterial) {\n const materialId = model._material.uniqueId;\n const materialIndexesById = this._materialIndexesById;\n if (!Object.prototype.hasOwnProperty.call(materialIndexesById, materialId)) {\n materialIndexesById[materialId] = this._materials.length;\n this._materials.push(model._material);\n }\n const matIdx = materialIndexesById[materialId];\n copy.materialIndex = matIdx;\n }\n if (options && options.positionFunction) {\n // call to custom positionFunction\n options.positionFunction(copy, idx, idxInShape);\n this._mustUnrotateFixedNormals = true;\n }\n // in case the particle geometry must NOT be inserted in the SPS mesh geometry\n if (storeApart) {\n return copy;\n }\n const rotMatrix = TmpVectors.Matrix[0];\n const tmpVertex = this._tmpVertex;\n const tmpVector = tmpVertex.position;\n const tmpColor = tmpVertex.color;\n const tmpUV = tmpVertex.uv;\n const tmpRotated = TmpVectors.Vector3[1];\n const pivotBackTranslation = TmpVectors.Vector3[2];\n const scaledPivot = TmpVectors.Vector3[3];\n Matrix.IdentityToRef(rotMatrix);\n copy.getRotationMatrix(rotMatrix);\n copy.pivot.multiplyToRef(copy.scaling, scaledPivot);\n if (copy.translateFromPivot) {\n pivotBackTranslation.setAll(0.0);\n }\n else {\n pivotBackTranslation.copyFrom(scaledPivot);\n }\n const someVertexFunction = options && options.vertexFunction;\n for (i = 0; i < shape.length; i++) {\n tmpVector.copyFrom(shape[i]);\n if (copy.color) {\n tmpColor.copyFrom(copy.color);\n }\n if (meshUV) {\n tmpUV.copyFromFloats(meshUV[u], meshUV[u + 1]);\n }\n if (someVertexFunction) {\n options.vertexFunction(copy, tmpVertex, i);\n }\n tmpVector.multiplyInPlace(copy.scaling).subtractInPlace(scaledPivot);\n Vector3.TransformCoordinatesToRef(tmpVector, rotMatrix, tmpRotated);\n tmpRotated.addInPlace(pivotBackTranslation).addInPlace(copy.position);\n positions.push(tmpRotated.x, tmpRotated.y, tmpRotated.z);\n if (meshUV) {\n const copyUvs = copy.uvs;\n uvs.push((copyUvs.z - copyUvs.x) * tmpUV.x + copyUvs.x, (copyUvs.w - copyUvs.y) * tmpUV.y + copyUvs.y);\n u += 2;\n }\n if (copy.color) {\n this._color.copyFrom(tmpColor);\n }\n else {\n const color = this._color;\n if (meshCol && meshCol[c] !== undefined) {\n color.r = meshCol[c];\n color.g = meshCol[c + 1];\n color.b = meshCol[c + 2];\n color.a = meshCol[c + 3];\n }\n else {\n color.r = 1.0;\n color.g = 1.0;\n color.b = 1.0;\n color.a = 1.0;\n }\n }\n colors.push(this._color.r, this._color.g, this._color.b, this._color.a);\n c += 4;\n if (!this.recomputeNormals && meshNor) {\n Vector3.TransformNormalFromFloatsToRef(meshNor[n], meshNor[n + 1], meshNor[n + 2], rotMatrix, tmpVector);\n normals.push(tmpVector.x, tmpVector.y, tmpVector.z);\n n += 3;\n }\n }\n for (i = 0; i < meshInd.length; i++) {\n const current_ind = p + meshInd[i];\n indices.push(current_ind);\n if (current_ind > 65535) {\n this._needs32Bits = true;\n }\n }\n if (this._depthSort || this._multimaterialEnabled) {\n const matIndex = copy.materialIndex !== null ? copy.materialIndex : 0;\n this.depthSortedParticles.push(new DepthSortedParticle(idx, ind, meshInd.length, matIndex));\n }\n return copy;\n }\n /**\n * Returns a shape Vector3 array from positions float array\n * @param positions float array\n * @returns a vector3 array\n * @internal\n */\n _posToShape(positions) {\n const shape = [];\n for (let i = 0; i < positions.length; i += 3) {\n shape.push(Vector3.FromArray(positions, i));\n }\n return shape;\n }\n /**\n * Returns a shapeUV array from a float uvs (array deep copy)\n * @param uvs as a float array\n * @returns a shapeUV array\n * @internal\n */\n _uvsToShapeUV(uvs) {\n const shapeUV = [];\n if (uvs) {\n for (let i = 0; i < uvs.length; i++) {\n shapeUV.push(uvs[i]);\n }\n }\n return shapeUV;\n }\n /**\n * Adds a new particle object in the particles array\n * @param idx particle index in particles array\n * @param id particle id\n * @param idxpos positionIndex : the starting index of the particle vertices in the SPS \"positions\" array\n * @param idxind indiceIndex : he starting index of the particle indices in the SPS \"indices\" array\n * @param model particle ModelShape object\n * @param shapeId model shape identifier\n * @param idxInShape index of the particle in the current model\n * @param bInfo model bounding info object\n * @param storage target storage array, if any\n * @internal\n */\n _addParticle(idx, id, idxpos, idxind, model, shapeId, idxInShape, bInfo = null, storage = null) {\n const sp = new SolidParticle(idx, id, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);\n const target = storage ? storage : this.particles;\n target.push(sp);\n return sp;\n }\n /**\n * Adds some particles to the SPS from the model shape. Returns the shape id.\n * Please read the doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/immutable_sps\n * @param mesh is any Mesh object that will be used as a model for the solid particles.\n * @param nb (positive integer) the number of particles to be created from this model\n * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.\n * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation\n * {storage} (optional existing array) is an array where the particles will be stored for a further use instead of being inserted in the SPS.\n * @param options.positionFunction\n * @param options.vertexFunction\n * @param options.storage\n * @returns the number of shapes in the system\n */\n addShape(mesh, nb, options) {\n const meshPos = mesh.getVerticesData(VertexBuffer.PositionKind);\n const meshInd = mesh.getIndices();\n const meshUV = mesh.getVerticesData(VertexBuffer.UVKind);\n const meshCol = mesh.getVerticesData(VertexBuffer.ColorKind);\n const meshNor = mesh.getVerticesData(VertexBuffer.NormalKind);\n this.recomputeNormals = meshNor ? false : true;\n const indices = Array.from(meshInd);\n const shapeNormals = Array.from(meshNor);\n const shapeColors = meshCol ? Array.from(meshCol) : [];\n const storage = options && options.storage ? options.storage : null;\n let bbInfo = null;\n if (this._particlesIntersect) {\n bbInfo = mesh.getBoundingInfo();\n }\n const shape = this._posToShape(meshPos);\n const shapeUV = this._uvsToShapeUV(meshUV);\n const posfunc = options ? options.positionFunction : null;\n const vtxfunc = options ? options.vertexFunction : null;\n let material = null;\n if (this._useModelMaterial) {\n material = mesh.material ? mesh.material : this._setDefaultMaterial();\n }\n const modelShape = new ModelShape(this._shapeCounter, shape, indices, shapeNormals, shapeColors, shapeUV, posfunc, vtxfunc, material);\n // particles\n for (let i = 0; i < nb; i++) {\n this._insertNewParticle(this.nbParticles, i, modelShape, shape, meshInd, meshUV, meshCol, meshNor, bbInfo, storage, options);\n }\n this._shapeCounter++;\n this._isNotBuilt = true; // buildMesh() call is now expected for setParticles() to work\n return this._shapeCounter - 1;\n }\n /**\n * Rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices\n * @internal\n */\n _rebuildParticle(particle, reset = false) {\n this._resetCopy();\n const copy = this._copy;\n if (particle._model._positionFunction) {\n // recall to stored custom positionFunction\n particle._model._positionFunction(copy, particle.idx, particle.idxInShape);\n }\n const rotMatrix = TmpVectors.Matrix[0];\n const tmpVertex = TmpVectors.Vector3[0];\n const tmpRotated = TmpVectors.Vector3[1];\n const pivotBackTranslation = TmpVectors.Vector3[2];\n const scaledPivot = TmpVectors.Vector3[3];\n copy.getRotationMatrix(rotMatrix);\n particle.pivot.multiplyToRef(particle.scaling, scaledPivot);\n if (copy.translateFromPivot) {\n pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);\n }\n else {\n pivotBackTranslation.copyFrom(scaledPivot);\n }\n const shape = particle._model._shape;\n for (let pt = 0; pt < shape.length; pt++) {\n tmpVertex.copyFrom(shape[pt]);\n if (particle._model._vertexFunction) {\n particle._model._vertexFunction(copy, tmpVertex, pt); // recall to stored vertexFunction\n }\n tmpVertex.multiplyInPlace(copy.scaling).subtractInPlace(scaledPivot);\n Vector3.TransformCoordinatesToRef(tmpVertex, rotMatrix, tmpRotated);\n tmpRotated\n .addInPlace(pivotBackTranslation)\n .addInPlace(copy.position)\n .toArray(this._positions32, particle._pos + pt * 3);\n }\n if (reset) {\n particle.position.setAll(0.0);\n particle.rotation.setAll(0.0);\n particle.rotationQuaternion = null;\n particle.scaling.setAll(1.0);\n particle.uvs.setAll(0.0);\n particle.pivot.setAll(0.0);\n particle.translateFromPivot = false;\n particle.parentId = null;\n }\n }\n /**\n * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.\n * @param reset boolean, default false : if the particles must be reset at position and rotation zero, scaling 1, color white, initial UVs and not parented.\n * @returns the SPS.\n */\n rebuildMesh(reset = false) {\n for (let p = 0; p < this.particles.length; p++) {\n this._rebuildParticle(this.particles[p], reset);\n }\n this.mesh.updateVerticesData(VertexBuffer.PositionKind, this._positions32, false, false);\n return this;\n }\n /** Removes the particles from the start-th to the end-th included from an expandable SPS (required).\n * Returns an array with the removed particles.\n * If the number of particles to remove is lower than zero or greater than the global remaining particle number, then an empty array is returned.\n * The SPS can't be empty so at least one particle needs to remain in place.\n * Under the hood, the VertexData array, so the VBO buffer, is recreated each call.\n * @param start index of the first particle to remove\n * @param end index of the last particle to remove (included)\n * @returns an array populated with the removed particles\n */\n removeParticles(start, end) {\n const nb = end - start + 1;\n if (!this._expandable || nb <= 0 || nb >= this.nbParticles || !this._updatable) {\n return [];\n }\n const particles = this.particles;\n const currentNb = this.nbParticles;\n if (end < currentNb - 1) {\n // update the particle indexes in the positions array in case they're remaining particles after the last removed\n const firstRemaining = end + 1;\n const shiftPos = particles[firstRemaining]._pos - particles[start]._pos;\n const shifInd = particles[firstRemaining]._ind - particles[start]._ind;\n for (let i = firstRemaining; i < currentNb; i++) {\n const part = particles[i];\n part._pos -= shiftPos;\n part._ind -= shifInd;\n }\n }\n const removed = particles.splice(start, nb);\n this._positions.length = 0;\n this._indices.length = 0;\n this._colors.length = 0;\n this._uvs.length = 0;\n this._normals.length = 0;\n this._index = 0;\n this._idxOfId.length = 0;\n if (this._depthSort || this._multimaterialEnabled) {\n this.depthSortedParticles = [];\n }\n let ind = 0;\n const particlesLength = particles.length;\n for (let p = 0; p < particlesLength; p++) {\n const particle = particles[p];\n const model = particle._model;\n const shape = model._shape;\n const modelIndices = model._indices;\n const modelNormals = model._normals;\n const modelColors = model._shapeColors;\n const modelUVs = model._shapeUV;\n particle.idx = p;\n this._idxOfId[particle.id] = p;\n this._meshBuilder(this._index, ind, shape, this._positions, modelIndices, this._indices, modelUVs, this._uvs, modelColors, this._colors, modelNormals, this._normals, particle.idx, particle.idxInShape, null, model);\n this._index += shape.length;\n ind += modelIndices.length;\n }\n this.nbParticles -= nb;\n this._isNotBuilt = true; // buildMesh() call is now expected for setParticles() to work\n return removed;\n }\n /**\n * Inserts some pre-created particles in the solid particle system so that they can be managed by setParticles().\n * @param solidParticleArray an array populated with Solid Particles objects\n * @returns the SPS\n */\n insertParticlesFromArray(solidParticleArray) {\n if (!this._expandable) {\n return this;\n }\n let idxInShape = 0;\n let currentShapeId = solidParticleArray[0].shapeId;\n const nb = solidParticleArray.length;\n for (let i = 0; i < nb; i++) {\n const sp = solidParticleArray[i];\n const model = sp._model;\n const shape = model._shape;\n const meshInd = model._indices;\n const meshUV = model._shapeUV;\n const meshCol = model._shapeColors;\n const meshNor = model._normals;\n const noNor = meshNor ? false : true;\n this.recomputeNormals = noNor || this.recomputeNormals;\n const bbInfo = sp.getBoundingInfo();\n const newPart = this._insertNewParticle(this.nbParticles, idxInShape, model, shape, meshInd, meshUV, meshCol, meshNor, bbInfo, null, null);\n sp.copyToRef(newPart);\n idxInShape++;\n if (currentShapeId != sp.shapeId) {\n currentShapeId = sp.shapeId;\n idxInShape = 0;\n }\n }\n this._isNotBuilt = true; // buildMesh() call is now expected for setParticles() to work\n return this;\n }\n /**\n * Creates a new particle and modifies the SPS mesh geometry :\n * - calls _meshBuilder() to increase the SPS mesh geometry step by step\n * - calls _addParticle() to populate the particle array\n * factorized code from addShape() and insertParticlesFromArray()\n * @param idx particle index in the particles array\n * @param i particle index in its shape\n * @param modelShape particle ModelShape object\n * @param shape shape vertex array\n * @param meshInd shape indices array\n * @param meshUV shape uv array\n * @param meshCol shape color array\n * @param meshNor shape normals array\n * @param bbInfo shape bounding info\n * @param storage target particle storage\n * @param options\n * @options addShape() passed options\n * @internal\n */\n _insertNewParticle(idx, i, modelShape, shape, meshInd, meshUV, meshCol, meshNor, bbInfo, storage, options) {\n const currentPos = this._positions.length;\n const currentInd = this._indices.length;\n const currentCopy = this._meshBuilder(this._index, currentInd, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options, modelShape);\n let sp = null;\n if (this._updatable) {\n sp = this._addParticle(this.nbParticles, this._lastParticleId, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo, storage);\n sp.position.copyFrom(currentCopy.position);\n sp.rotation.copyFrom(currentCopy.rotation);\n if (currentCopy.rotationQuaternion) {\n if (sp.rotationQuaternion) {\n sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);\n }\n else {\n sp.rotationQuaternion = currentCopy.rotationQuaternion.clone();\n }\n }\n if (currentCopy.color) {\n if (sp.color) {\n sp.color.copyFrom(currentCopy.color);\n }\n else {\n sp.color = currentCopy.color.clone();\n }\n }\n sp.scaling.copyFrom(currentCopy.scaling);\n sp.uvs.copyFrom(currentCopy.uvs);\n if (currentCopy.materialIndex !== null) {\n sp.materialIndex = currentCopy.materialIndex;\n }\n if (this.expandable) {\n this._idxOfId[sp.id] = sp.idx;\n }\n }\n if (!storage) {\n this._index += shape.length;\n this.nbParticles++;\n this._lastParticleId++;\n }\n return sp;\n }\n /**\n * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.\n * This method calls `updateParticle()` for each particle of the SPS.\n * For an animated SPS, it is usually called within the render loop.\n * This methods does nothing if called on a non updatable or not yet built SPS. Example : buildMesh() not called after having added or removed particles from an expandable SPS.\n * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_\n * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_\n * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_\n * @returns the SPS.\n */\n setParticles(start = 0, end = this.nbParticles - 1, update = true) {\n if (!this._updatable || this._isNotBuilt) {\n return this;\n }\n // custom beforeUpdate\n this.beforeUpdateParticles(start, end, update);\n const rotMatrix = TmpVectors.Matrix[0];\n const invertedMatrix = TmpVectors.Matrix[1];\n const mesh = this.mesh;\n const colors32 = this._colors32;\n const positions32 = this._positions32;\n const normals32 = this._normals32;\n const uvs32 = this._uvs32;\n const indices32 = this._indices32;\n const indices = this._indices;\n const fixedNormal32 = this._fixedNormal32;\n const depthSortParticles = this._depthSort && this._depthSortParticles;\n const tempVectors = TmpVectors.Vector3;\n const camAxisX = tempVectors[5].copyFromFloats(1.0, 0.0, 0.0);\n const camAxisY = tempVectors[6].copyFromFloats(0.0, 1.0, 0.0);\n const camAxisZ = tempVectors[7].copyFromFloats(0.0, 0.0, 1.0);\n const minimum = tempVectors[8].setAll(Number.MAX_VALUE);\n const maximum = tempVectors[9].setAll(-Number.MAX_VALUE);\n const camInvertedPosition = tempVectors[10].setAll(0);\n const tmpVertex = this._tmpVertex;\n const tmpVector = tmpVertex.position;\n const tmpColor = tmpVertex.color;\n const tmpUV = tmpVertex.uv;\n // cases when the World Matrix is to be computed first\n if (this.billboard || this._depthSort) {\n this.mesh.computeWorldMatrix(true);\n this.mesh._worldMatrix.invertToRef(invertedMatrix);\n }\n // if the particles will always face the camera\n if (this.billboard) {\n // compute the camera position and un-rotate it by the current mesh rotation\n const tmpVector0 = tempVectors[0];\n this._camera.getDirectionToRef(Axis.Z, tmpVector0);\n Vector3.TransformNormalToRef(tmpVector0, invertedMatrix, camAxisZ);\n camAxisZ.normalize();\n // same for camera up vector extracted from the cam view matrix\n const view = this._camera.getViewMatrix(true);\n Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], invertedMatrix, camAxisY);\n Vector3.CrossToRef(camAxisY, camAxisZ, camAxisX);\n camAxisY.normalize();\n camAxisX.normalize();\n }\n // if depthSort, compute the camera global position in the mesh local system\n if (this._depthSort) {\n Vector3.TransformCoordinatesToRef(this._camera.globalPosition, invertedMatrix, camInvertedPosition); // then un-rotate the camera\n }\n Matrix.IdentityToRef(rotMatrix);\n let idx = 0; // current position index in the global array positions32\n let index = 0; // position start index in the global array positions32 of the current particle\n let colidx = 0; // current color index in the global array colors32\n let colorIndex = 0; // color start index in the global array colors32 of the current particle\n let uvidx = 0; // current uv index in the global array uvs32\n let uvIndex = 0; // uv start index in the global array uvs32 of the current particle\n let pt = 0; // current index in the particle model shape\n if (this.mesh.isFacetDataEnabled) {\n this._computeBoundingBox = true;\n }\n end = end >= this.nbParticles ? this.nbParticles - 1 : end;\n if (this._computeBoundingBox) {\n if (start != 0 || end != this.nbParticles - 1) {\n // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.\n const boundingInfo = this.mesh.getBoundingInfo();\n if (boundingInfo) {\n minimum.copyFrom(boundingInfo.minimum);\n maximum.copyFrom(boundingInfo.maximum);\n }\n }\n }\n // particle loop\n index = this.particles[start]._pos;\n const vpos = (index / 3) | 0;\n colorIndex = vpos * 4;\n uvIndex = vpos * 2;\n for (let p = start; p <= end; p++) {\n const particle = this.particles[p];\n // call to custom user function to update the particle properties\n this.updateParticle(particle);\n const shape = particle._model._shape;\n const shapeUV = particle._model._shapeUV;\n const particleRotationMatrix = particle._rotationMatrix;\n const particlePosition = particle.position;\n const particleRotation = particle.rotation;\n const particleScaling = particle.scaling;\n const particleGlobalPosition = particle._globalPosition;\n // camera-particle distance for depth sorting\n if (depthSortParticles) {\n const dsp = this.depthSortedParticles[p];\n dsp.idx = particle.idx;\n dsp.ind = particle._ind;\n dsp.indicesLength = particle._model._indicesLength;\n dsp.sqDistance = Vector3.DistanceSquared(particle.position, camInvertedPosition);\n }\n // skip the computations for inactive or already invisible particles\n if (!particle.alive || (particle._stillInvisible && !particle.isVisible && !this._recomputeInvisibles)) {\n // increment indexes for the next particle\n pt = shape.length;\n index += pt * 3;\n colorIndex += pt * 4;\n uvIndex += pt * 2;\n continue;\n }\n if (particle.isVisible) {\n particle._stillInvisible = false; // un-mark permanent invisibility\n const scaledPivot = tempVectors[12];\n particle.pivot.multiplyToRef(particleScaling, scaledPivot);\n // particle rotation matrix\n if (this.billboard) {\n particleRotation.x = 0.0;\n particleRotation.y = 0.0;\n }\n if (this._computeParticleRotation || this.billboard) {\n particle.getRotationMatrix(rotMatrix);\n }\n const particleHasParent = particle.parentId !== null;\n if (particleHasParent) {\n const parent = this.getParticleById(particle.parentId);\n if (parent) {\n const parentRotationMatrix = parent._rotationMatrix;\n const parentGlobalPosition = parent._globalPosition;\n const rotatedY = particlePosition.x * parentRotationMatrix[1] + particlePosition.y * parentRotationMatrix[4] + particlePosition.z * parentRotationMatrix[7];\n const rotatedX = particlePosition.x * parentRotationMatrix[0] + particlePosition.y * parentRotationMatrix[3] + particlePosition.z * parentRotationMatrix[6];\n const rotatedZ = particlePosition.x * parentRotationMatrix[2] + particlePosition.y * parentRotationMatrix[5] + particlePosition.z * parentRotationMatrix[8];\n particleGlobalPosition.x = parentGlobalPosition.x + rotatedX;\n particleGlobalPosition.y = parentGlobalPosition.y + rotatedY;\n particleGlobalPosition.z = parentGlobalPosition.z + rotatedZ;\n if (this._computeParticleRotation || this.billboard) {\n const rotMatrixValues = rotMatrix.m;\n particleRotationMatrix[0] =\n rotMatrixValues[0] * parentRotationMatrix[0] + rotMatrixValues[1] * parentRotationMatrix[3] + rotMatrixValues[2] * parentRotationMatrix[6];\n particleRotationMatrix[1] =\n rotMatrixValues[0] * parentRotationMatrix[1] + rotMatrixValues[1] * parentRotationMatrix[4] + rotMatrixValues[2] * parentRotationMatrix[7];\n particleRotationMatrix[2] =\n rotMatrixValues[0] * parentRotationMatrix[2] + rotMatrixValues[1] * parentRotationMatrix[5] + rotMatrixValues[2] * parentRotationMatrix[8];\n particleRotationMatrix[3] =\n rotMatrixValues[4] * parentRotationMatrix[0] + rotMatrixValues[5] * parentRotationMatrix[3] + rotMatrixValues[6] * parentRotationMatrix[6];\n particleRotationMatrix[4] =\n rotMatrixValues[4] * parentRotationMatrix[1] + rotMatrixValues[5] * parentRotationMatrix[4] + rotMatrixValues[6] * parentRotationMatrix[7];\n particleRotationMatrix[5] =\n rotMatrixValues[4] * parentRotationMatrix[2] + rotMatrixValues[5] * parentRotationMatrix[5] + rotMatrixValues[6] * parentRotationMatrix[8];\n particleRotationMatrix[6] =\n rotMatrixValues[8] * parentRotationMatrix[0] + rotMatrixValues[9] * parentRotationMatrix[3] + rotMatrixValues[10] * parentRotationMatrix[6];\n particleRotationMatrix[7] =\n rotMatrixValues[8] * parentRotationMatrix[1] + rotMatrixValues[9] * parentRotationMatrix[4] + rotMatrixValues[10] * parentRotationMatrix[7];\n particleRotationMatrix[8] =\n rotMatrixValues[8] * parentRotationMatrix[2] + rotMatrixValues[9] * parentRotationMatrix[5] + rotMatrixValues[10] * parentRotationMatrix[8];\n }\n }\n else {\n // in case the parent were removed at some moment\n particle.parentId = null;\n }\n }\n else {\n particleGlobalPosition.x = particlePosition.x;\n particleGlobalPosition.y = particlePosition.y;\n particleGlobalPosition.z = particlePosition.z;\n if (this._computeParticleRotation || this.billboard) {\n const rotMatrixValues = rotMatrix.m;\n particleRotationMatrix[0] = rotMatrixValues[0];\n particleRotationMatrix[1] = rotMatrixValues[1];\n particleRotationMatrix[2] = rotMatrixValues[2];\n particleRotationMatrix[3] = rotMatrixValues[4];\n particleRotationMatrix[4] = rotMatrixValues[5];\n particleRotationMatrix[5] = rotMatrixValues[6];\n particleRotationMatrix[6] = rotMatrixValues[8];\n particleRotationMatrix[7] = rotMatrixValues[9];\n particleRotationMatrix[8] = rotMatrixValues[10];\n }\n }\n const pivotBackTranslation = tempVectors[11];\n if (particle.translateFromPivot) {\n pivotBackTranslation.setAll(0.0);\n }\n else {\n pivotBackTranslation.copyFrom(scaledPivot);\n }\n // particle vertex loop\n for (pt = 0; pt < shape.length; pt++) {\n idx = index + pt * 3;\n colidx = colorIndex + pt * 4;\n uvidx = uvIndex + pt * 2;\n const iu = 2 * pt;\n const iv = iu + 1;\n tmpVector.copyFrom(shape[pt]);\n if (this._computeParticleColor && particle.color) {\n tmpColor.copyFrom(particle.color);\n }\n if (this._computeParticleTexture) {\n tmpUV.copyFromFloats(shapeUV[iu], shapeUV[iv]);\n }\n if (this._computeParticleVertex) {\n this.updateParticleVertex(particle, tmpVertex, pt);\n }\n // positions\n const vertexX = tmpVector.x * particleScaling.x - scaledPivot.x;\n const vertexY = tmpVector.y * particleScaling.y - scaledPivot.y;\n const vertexZ = tmpVector.z * particleScaling.z - scaledPivot.z;\n let rotatedX = vertexX * particleRotationMatrix[0] + vertexY * particleRotationMatrix[3] + vertexZ * particleRotationMatrix[6];\n let rotatedY = vertexX * particleRotationMatrix[1] + vertexY * particleRotationMatrix[4] + vertexZ * particleRotationMatrix[7];\n let rotatedZ = vertexX * particleRotationMatrix[2] + vertexY * particleRotationMatrix[5] + vertexZ * particleRotationMatrix[8];\n rotatedX += pivotBackTranslation.x;\n rotatedY += pivotBackTranslation.y;\n rotatedZ += pivotBackTranslation.z;\n const px = (positions32[idx] = particleGlobalPosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ);\n const py = (positions32[idx + 1] = particleGlobalPosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ);\n const pz = (positions32[idx + 2] = particleGlobalPosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ);\n if (this._computeBoundingBox) {\n minimum.minimizeInPlaceFromFloats(px, py, pz);\n maximum.maximizeInPlaceFromFloats(px, py, pz);\n }\n // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()\n if (!this._computeParticleVertex) {\n const normalx = fixedNormal32[idx];\n const normaly = fixedNormal32[idx + 1];\n const normalz = fixedNormal32[idx + 2];\n const rotatedx = normalx * particleRotationMatrix[0] + normaly * particleRotationMatrix[3] + normalz * particleRotationMatrix[6];\n const rotatedy = normalx * particleRotationMatrix[1] + normaly * particleRotationMatrix[4] + normalz * particleRotationMatrix[7];\n const rotatedz = normalx * particleRotationMatrix[2] + normaly * particleRotationMatrix[5] + normalz * particleRotationMatrix[8];\n normals32[idx] = camAxisX.x * rotatedx + camAxisY.x * rotatedy + camAxisZ.x * rotatedz;\n normals32[idx + 1] = camAxisX.y * rotatedx + camAxisY.y * rotatedy + camAxisZ.y * rotatedz;\n normals32[idx + 2] = camAxisX.z * rotatedx + camAxisY.z * rotatedy + camAxisZ.z * rotatedz;\n }\n if (this._computeParticleColor && particle.color) {\n const colors32 = this._colors32;\n colors32[colidx] = tmpColor.r;\n colors32[colidx + 1] = tmpColor.g;\n colors32[colidx + 2] = tmpColor.b;\n colors32[colidx + 3] = tmpColor.a;\n }\n if (this._computeParticleTexture) {\n const uvs = particle.uvs;\n uvs32[uvidx] = tmpUV.x * (uvs.z - uvs.x) + uvs.x;\n uvs32[uvidx + 1] = tmpUV.y * (uvs.w - uvs.y) + uvs.y;\n }\n }\n }\n // particle just set invisible : scaled to zero and positioned at the origin\n else {\n particle._stillInvisible = true; // mark the particle as invisible\n for (pt = 0; pt < shape.length; pt++) {\n idx = index + pt * 3;\n colidx = colorIndex + pt * 4;\n uvidx = uvIndex + pt * 2;\n positions32[idx] = positions32[idx + 1] = positions32[idx + 2] = 0;\n normals32[idx] = normals32[idx + 1] = normals32[idx + 2] = 0;\n if (this._computeParticleColor && particle.color) {\n const color = particle.color;\n colors32[colidx] = color.r;\n colors32[colidx + 1] = color.g;\n colors32[colidx + 2] = color.b;\n colors32[colidx + 3] = color.a;\n }\n if (this._computeParticleTexture) {\n const uvs = particle.uvs;\n uvs32[uvidx] = shapeUV[pt * 2] * (uvs.z - uvs.x) + uvs.x;\n uvs32[uvidx + 1] = shapeUV[pt * 2 + 1] * (uvs.w - uvs.y) + uvs.y;\n }\n }\n }\n // if the particle intersections must be computed : update the bbInfo\n if (this._particlesIntersect) {\n const bInfo = particle.getBoundingInfo();\n const bBox = bInfo.boundingBox;\n const bSphere = bInfo.boundingSphere;\n const modelBoundingInfo = particle._modelBoundingInfo;\n if (!this._bSphereOnly) {\n // place, scale and rotate the particle bbox within the SPS local system, then update it\n const modelBoundingInfoVectors = modelBoundingInfo.boundingBox.vectors;\n const tempMin = tempVectors[1];\n const tempMax = tempVectors[2];\n tempMin.setAll(Number.MAX_VALUE);\n tempMax.setAll(-Number.MAX_VALUE);\n for (let b = 0; b < 8; b++) {\n const scaledX = modelBoundingInfoVectors[b].x * particleScaling.x;\n const scaledY = modelBoundingInfoVectors[b].y * particleScaling.y;\n const scaledZ = modelBoundingInfoVectors[b].z * particleScaling.z;\n const rotatedX = scaledX * particleRotationMatrix[0] + scaledY * particleRotationMatrix[3] + scaledZ * particleRotationMatrix[6];\n const rotatedY = scaledX * particleRotationMatrix[1] + scaledY * particleRotationMatrix[4] + scaledZ * particleRotationMatrix[7];\n const rotatedZ = scaledX * particleRotationMatrix[2] + scaledY * particleRotationMatrix[5] + scaledZ * particleRotationMatrix[8];\n const x = particlePosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ;\n const y = particlePosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ;\n const z = particlePosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ;\n tempMin.minimizeInPlaceFromFloats(x, y, z);\n tempMax.maximizeInPlaceFromFloats(x, y, z);\n }\n bBox.reConstruct(tempMin, tempMax, mesh._worldMatrix);\n }\n // place and scale the particle bouding sphere in the SPS local system, then update it\n const minBbox = modelBoundingInfo.minimum.multiplyToRef(particleScaling, tempVectors[1]);\n const maxBbox = modelBoundingInfo.maximum.multiplyToRef(particleScaling, tempVectors[2]);\n const bSphereCenter = maxBbox.addToRef(minBbox, tempVectors[3]).scaleInPlace(0.5).addInPlace(particleGlobalPosition);\n const halfDiag = maxBbox.subtractToRef(minBbox, tempVectors[4]).scaleInPlace(0.5 * this._bSphereRadiusFactor);\n const bSphereMinBbox = bSphereCenter.subtractToRef(halfDiag, tempVectors[1]);\n const bSphereMaxBbox = bSphereCenter.addToRef(halfDiag, tempVectors[2]);\n bSphere.reConstruct(bSphereMinBbox, bSphereMaxBbox, mesh._worldMatrix);\n }\n // increment indexes for the next particle\n index = idx + 3;\n colorIndex = colidx + 4;\n uvIndex = uvidx + 2;\n }\n // if the VBO must be updated\n if (update) {\n if (this._computeParticleColor) {\n const vb = mesh.getVertexBuffer(VertexBuffer.ColorKind);\n if (vb && !mesh.isPickable) {\n vb.updateDirectly(colors32, 0);\n }\n else {\n mesh.updateVerticesData(VertexBuffer.ColorKind, colors32, false, false);\n }\n }\n if (this._computeParticleTexture) {\n const vb = mesh.getVertexBuffer(VertexBuffer.UVKind);\n if (vb && !mesh.isPickable) {\n vb.updateDirectly(uvs32, 0);\n }\n else {\n mesh.updateVerticesData(VertexBuffer.UVKind, uvs32, false, false);\n }\n }\n const vbp = mesh.getVertexBuffer(VertexBuffer.PositionKind);\n if (vbp && !mesh.isPickable) {\n vbp.updateDirectly(positions32, 0);\n }\n else {\n mesh.updateVerticesData(VertexBuffer.PositionKind, positions32, false, false);\n }\n if (!mesh.areNormalsFrozen || mesh.isFacetDataEnabled) {\n if (this._computeParticleVertex || mesh.isFacetDataEnabled) {\n // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]\n const params = mesh.isFacetDataEnabled ? mesh.getFacetDataParameters() : null;\n VertexData.ComputeNormals(positions32, indices32, normals32, params);\n for (let i = 0; i < normals32.length; i++) {\n fixedNormal32[i] = normals32[i];\n }\n }\n if (!mesh.areNormalsFrozen) {\n const vb = mesh.getVertexBuffer(VertexBuffer.NormalKind);\n if (vb && !mesh.isPickable) {\n vb.updateDirectly(normals32, 0);\n }\n else {\n mesh.updateVerticesData(VertexBuffer.NormalKind, normals32, false, false);\n }\n }\n }\n if (depthSortParticles) {\n const depthSortedParticles = this.depthSortedParticles;\n depthSortedParticles.sort(this._depthSortFunction);\n const dspl = depthSortedParticles.length;\n let sid = 0;\n let faceId = 0;\n for (let sorted = 0; sorted < dspl; sorted++) {\n const sortedParticle = depthSortedParticles[sorted];\n const lind = sortedParticle.indicesLength;\n const sind = sortedParticle.ind;\n for (let i = 0; i < lind; i++) {\n indices32[sid] = indices[sind + i];\n sid++;\n if (this._pickable) {\n const f = i % 3;\n if (f == 0) {\n const pickedData = this.pickedParticles[faceId];\n pickedData.idx = sortedParticle.idx;\n pickedData.faceId = faceId;\n faceId++;\n }\n }\n }\n }\n }\n if (this._autoFixFaceOrientation) {\n let particleInd = 0;\n for (let particleIdx = 0; particleIdx < this.particles.length; particleIdx++) {\n const particle = depthSortParticles ? this.particles[this.depthSortedParticles[particleIdx].idx] : this.particles[particleIdx];\n const flipFaces = particle.scale.x * particle.scale.y * particle.scale.z < 0;\n if (flipFaces) {\n for (let faceInd = 0; faceInd < particle._model._indicesLength; faceInd += 3) {\n const tmp = indices[particle._ind + faceInd];\n indices32[particleInd + faceInd] = indices[particle._ind + faceInd + 1];\n indices32[particleInd + faceInd + 1] = tmp;\n }\n }\n particleInd += particle._model._indicesLength;\n }\n }\n if (depthSortParticles || this._autoFixFaceOrientation) {\n mesh.updateIndices(indices32);\n }\n }\n if (this._computeBoundingBox) {\n if (mesh.hasBoundingInfo) {\n mesh.getBoundingInfo().reConstruct(minimum, maximum, mesh._worldMatrix);\n }\n else {\n mesh.buildBoundingInfo(minimum, maximum, mesh._worldMatrix);\n }\n }\n if (this._autoUpdateSubMeshes) {\n this.computeSubMeshes();\n }\n this._recomputeInvisibles = false;\n this.afterUpdateParticles(start, end, update);\n return this;\n }\n /**\n * Disposes the SPS.\n */\n dispose() {\n this.mesh.dispose();\n this.vars = null;\n // drop references to internal big arrays for the GC\n this._positions = null;\n this._indices = null;\n this._normals = null;\n this._uvs = null;\n this._colors = null;\n this._indices32 = null;\n this._positions32 = null;\n this._normals32 = null;\n this._fixedNormal32 = null;\n this._uvs32 = null;\n this._colors32 = null;\n this.pickedParticles = null;\n this.pickedBySubMesh = null;\n this._materials = null;\n this._materialIndexes = null;\n this._indicesByMaterial = null;\n this._idxOfId = null;\n }\n /** Returns an object {idx: number faceId: number} for the picked particle from the passed pickingInfo object.\n * idx is the particle index in the SPS\n * faceId is the picked face index counted within this particle.\n * Returns null if the pickInfo can't identify a picked particle.\n * @param pickingInfo (PickingInfo object)\n * @returns {idx: number, faceId: number} or null\n */\n pickedParticle(pickingInfo) {\n if (pickingInfo.hit) {\n const subMesh = pickingInfo.subMeshId;\n const faceId = pickingInfo.faceId - this.mesh.subMeshes[subMesh].indexStart / 3;\n const picked = this.pickedBySubMesh;\n if (picked[subMesh] && picked[subMesh][faceId]) {\n return picked[subMesh][faceId];\n }\n }\n return null;\n }\n /**\n * Returns a SolidParticle object from its identifier : particle.id\n * @param id (integer) the particle Id\n * @returns the searched particle or null if not found in the SPS.\n */\n getParticleById(id) {\n const p = this.particles[id];\n if (p && p.id == id) {\n return p;\n }\n const particles = this.particles;\n const idx = this._idxOfId[id];\n if (idx !== undefined) {\n return particles[idx];\n }\n let i = 0;\n const nb = this.nbParticles;\n while (i < nb) {\n const particle = particles[i];\n if (particle.id == id) {\n return particle;\n }\n i++;\n }\n return null;\n }\n /**\n * Returns a new array populated with the particles having the passed shapeId.\n * @param shapeId (integer) the shape identifier\n * @returns a new solid particle array\n */\n getParticlesByShapeId(shapeId) {\n const ref = [];\n this.getParticlesByShapeIdToRef(shapeId, ref);\n return ref;\n }\n /**\n * Populates the passed array \"ref\" with the particles having the passed shapeId.\n * @param shapeId the shape identifier\n * @returns the SPS\n * @param ref\n */\n getParticlesByShapeIdToRef(shapeId, ref) {\n ref.length = 0;\n for (let i = 0; i < this.nbParticles; i++) {\n const p = this.particles[i];\n if (p.shapeId == shapeId) {\n ref.push(p);\n }\n }\n return this;\n }\n /**\n * Computes the required SubMeshes according the materials assigned to the particles.\n * @returns the solid particle system.\n * Does nothing if called before the SPS mesh is built.\n */\n computeSubMeshes() {\n if (!this.mesh || !this._multimaterialEnabled) {\n return this;\n }\n const depthSortedParticles = this.depthSortedParticles;\n if (this.particles.length > 0) {\n for (let p = 0; p < this.particles.length; p++) {\n const part = this.particles[p];\n if (!part.materialIndex) {\n part.materialIndex = 0;\n }\n const sortedPart = depthSortedParticles[p];\n sortedPart.materialIndex = part.materialIndex;\n sortedPart.ind = part._ind;\n sortedPart.indicesLength = part._model._indicesLength;\n sortedPart.idx = part.idx;\n }\n }\n this._sortParticlesByMaterial();\n const indicesByMaterial = this._indicesByMaterial;\n const materialIndexes = this._materialIndexes;\n const mesh = this.mesh;\n mesh.subMeshes = [];\n const vcount = mesh.getTotalVertices();\n for (let m = 0; m < materialIndexes.length; m++) {\n const start = indicesByMaterial[m];\n const count = indicesByMaterial[m + 1] - start;\n const matIndex = materialIndexes[m];\n new SubMesh(matIndex, 0, vcount, start, count, mesh);\n }\n return this;\n }\n /**\n * Sorts the solid particles by material when MultiMaterial is enabled.\n * Updates the indices32 array.\n * Updates the indicesByMaterial array.\n * Updates the mesh indices array.\n * @returns the SPS\n * @internal\n */\n _sortParticlesByMaterial() {\n const indicesByMaterial = [0];\n this._indicesByMaterial = indicesByMaterial;\n const materialIndexes = [];\n this._materialIndexes = materialIndexes;\n const depthSortedParticles = this.depthSortedParticles;\n depthSortedParticles.sort(this._materialSortFunction);\n const length = depthSortedParticles.length;\n const indices32 = this._indices32;\n const indices = this._indices;\n let subMeshIndex = 0;\n let subMeshFaceId = 0;\n let sid = 0;\n let lastMatIndex = depthSortedParticles[0].materialIndex;\n materialIndexes.push(lastMatIndex);\n if (this._pickable) {\n this.pickedBySubMesh = [[]];\n this.pickedParticles = this.pickedBySubMesh[0];\n }\n for (let sorted = 0; sorted < length; sorted++) {\n const sortedPart = depthSortedParticles[sorted];\n const lind = sortedPart.indicesLength;\n const sind = sortedPart.ind;\n if (sortedPart.materialIndex !== lastMatIndex) {\n lastMatIndex = sortedPart.materialIndex;\n indicesByMaterial.push(sid);\n materialIndexes.push(lastMatIndex);\n if (this._pickable) {\n subMeshIndex++;\n this.pickedBySubMesh[subMeshIndex] = [];\n subMeshFaceId = 0;\n }\n }\n let faceId = 0;\n for (let i = 0; i < lind; i++) {\n indices32[sid] = indices[sind + i];\n if (this._pickable) {\n const f = i % 3;\n if (f == 0) {\n const pickedData = this.pickedBySubMesh[subMeshIndex][subMeshFaceId];\n if (pickedData) {\n pickedData.idx = sortedPart.idx;\n pickedData.faceId = faceId;\n }\n else {\n this.pickedBySubMesh[subMeshIndex][subMeshFaceId] = { idx: sortedPart.idx, faceId: faceId };\n }\n subMeshFaceId++;\n faceId++;\n }\n }\n sid++;\n }\n }\n indicesByMaterial.push(indices32.length); // add the last number to ease the indices start/count values for subMeshes creation\n if (this._updatable) {\n this.mesh.updateIndices(indices32);\n }\n return this;\n }\n /**\n * Sets the material indexes by id materialIndexesById[id] = materialIndex\n * @internal\n */\n _setMaterialIndexesById() {\n this._materialIndexesById = {};\n for (let i = 0; i < this._materials.length; i++) {\n const id = this._materials[i].uniqueId;\n this._materialIndexesById[id] = i;\n }\n }\n /**\n * Returns an array with unique values of Materials from the passed array\n * @param array the material array to be checked and filtered\n * @internal\n */\n _filterUniqueMaterialId(array) {\n const filtered = array.filter(function (value, index, self) {\n return self.indexOf(value) === index;\n });\n return filtered;\n }\n /**\n * Sets a new Standard Material as _defaultMaterial if not already set.\n * @internal\n */\n _setDefaultMaterial() {\n if (!this._defaultMaterial) {\n this._defaultMaterial = new StandardMaterial(this.name + \"DefaultMaterial\", this._scene);\n }\n return this._defaultMaterial;\n }\n /**\n * Visibility helper : Recomputes the visible size according to the mesh bounding box\n * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/sps_visibility\n * @returns the SPS.\n */\n refreshVisibleSize() {\n if (!this._isVisibilityBoxLocked) {\n this.mesh.refreshBoundingInfo();\n }\n return this;\n }\n /**\n * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.\n * @param size the size (float) of the visibility box\n * note : this doesn't lock the SPS mesh bounding box.\n * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/sps_visibility\n */\n setVisibilityBox(size) {\n const vis = size / 2;\n this.mesh.buildBoundingInfo(new Vector3(-vis, -vis, -vis), new Vector3(vis, vis, vis));\n }\n /**\n * Gets whether the SPS as always visible or not\n * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/sps_visibility\n */\n get isAlwaysVisible() {\n return this._alwaysVisible;\n }\n /**\n * Sets the SPS as always visible or not\n * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/sps_visibility\n */\n set isAlwaysVisible(val) {\n this._alwaysVisible = val;\n this.mesh.alwaysSelectAsActiveMesh = val;\n }\n /**\n * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.\n * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/sps_visibility\n */\n set isVisibilityBoxLocked(val) {\n this._isVisibilityBoxLocked = val;\n const boundingInfo = this.mesh.getBoundingInfo();\n boundingInfo.isLocked = val;\n }\n /**\n * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.\n * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/sps_visibility\n */\n get isVisibilityBoxLocked() {\n return this._isVisibilityBoxLocked;\n }\n /**\n * Tells to `setParticles()` to compute the particle rotations or not.\n * Default value : true. The SPS is faster when it's set to false.\n * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.\n */\n set computeParticleRotation(val) {\n this._computeParticleRotation = val;\n }\n /**\n * Tells to `setParticles()` to compute the particle colors or not.\n * Default value : true. The SPS is faster when it's set to false.\n * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.\n */\n set computeParticleColor(val) {\n this._computeParticleColor = val;\n }\n set computeParticleTexture(val) {\n this._computeParticleTexture = val;\n }\n /**\n * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.\n * Default value : false. The SPS is faster when it's set to false.\n * Note : the particle custom vertex positions aren't stored values.\n */\n set computeParticleVertex(val) {\n this._computeParticleVertex = val;\n }\n /**\n * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.\n */\n set computeBoundingBox(val) {\n this._computeBoundingBox = val;\n }\n /**\n * Tells to `setParticles()` to sort or not the distance between each particle and the camera.\n * Skipped when `enableDepthSort` is set to `false` (default) at construction time.\n * Default : `true`\n */\n set depthSortParticles(val) {\n this._depthSortParticles = val;\n }\n /**\n * Gets if `setParticles()` computes the particle rotations or not.\n * Default value : true. The SPS is faster when it's set to false.\n * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.\n */\n get computeParticleRotation() {\n return this._computeParticleRotation;\n }\n /**\n * Gets if `setParticles()` computes the particle colors or not.\n * Default value : true. The SPS is faster when it's set to false.\n * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.\n */\n get computeParticleColor() {\n return this._computeParticleColor;\n }\n /**\n * Gets if `setParticles()` computes the particle textures or not.\n * Default value : true. The SPS is faster when it's set to false.\n * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.\n */\n get computeParticleTexture() {\n return this._computeParticleTexture;\n }\n /**\n * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.\n * Default value : false. The SPS is faster when it's set to false.\n * Note : the particle custom vertex positions aren't stored values.\n */\n get computeParticleVertex() {\n return this._computeParticleVertex;\n }\n /**\n * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.\n */\n get computeBoundingBox() {\n return this._computeBoundingBox;\n }\n /**\n * Gets if `setParticles()` sorts or not the distance between each particle and the camera.\n * Skipped when `enableDepthSort` is set to `false` (default) at construction time.\n * Default : `true`\n */\n get depthSortParticles() {\n return this._depthSortParticles;\n }\n /**\n * Gets if the SPS is created as expandable at construction time.\n * Default : `false`\n */\n get expandable() {\n return this._expandable;\n }\n /**\n * Gets if the SPS supports the Multi Materials\n */\n get multimaterialEnabled() {\n return this._multimaterialEnabled;\n }\n /**\n * Gets if the SPS uses the model materials for its own multimaterial.\n */\n get useModelMaterial() {\n return this._useModelMaterial;\n }\n /**\n * The SPS used material array.\n */\n get materials() {\n return this._materials;\n }\n /**\n * Sets the SPS MultiMaterial from the passed materials.\n * Note : the passed array is internally copied and not used then by reference.\n * @param materials an array of material objects. This array indexes are the materialIndex values of the particles.\n */\n setMultiMaterial(materials) {\n this._materials = this._filterUniqueMaterialId(materials);\n this._setMaterialIndexesById();\n if (this._multimaterial) {\n this._multimaterial.dispose();\n }\n this._multimaterial = new MultiMaterial(this.name + \"MultiMaterial\", this._scene);\n for (let m = 0; m < this._materials.length; m++) {\n this._multimaterial.subMaterials.push(this._materials[m]);\n }\n this.computeSubMeshes();\n this.mesh.material = this._multimaterial;\n }\n /**\n * The SPS computed multimaterial object\n */\n get multimaterial() {\n return this._multimaterial;\n }\n set multimaterial(mm) {\n this._multimaterial = mm;\n }\n /**\n * If the subMeshes must be updated on the next call to setParticles()\n */\n get autoUpdateSubMeshes() {\n return this._autoUpdateSubMeshes;\n }\n set autoUpdateSubMeshes(val) {\n this._autoUpdateSubMeshes = val;\n }\n // =======================================================================\n // Particle behavior logic\n // these following methods may be overwritten by the user to fit his needs\n /**\n * This function does nothing. It may be overwritten to set all the particle first values.\n * The SPS doesn't call this function, you may have to call it by your own.\n * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/manage_sps_particles\n */\n initParticles() { }\n /**\n * This function does nothing. It may be overwritten to recycle a particle.\n * The SPS doesn't call this function, you may have to call it by your own.\n * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/manage_sps_particles\n * @param particle The particle to recycle\n * @returns the recycled particle\n */\n recycleParticle(particle) {\n return particle;\n }\n /**\n * Updates a particle : this function should be overwritten by the user.\n * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.\n * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/manage_sps_particles\n * @example : just set a particle position or velocity and recycle conditions\n * @param particle The particle to update\n * @returns the updated particle\n */\n updateParticle(particle) {\n return particle;\n }\n /**\n * Updates a vertex of a particle : it can be overwritten by the user.\n * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.\n * @param particle the current particle\n * @param vertex the current vertex of the current particle : a SolidParticleVertex object\n * @param pt the index of the current vertex in the particle shape\n * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/sps_vertices\n * @example : just set a vertex particle position or color\n * @returns the sps\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n updateParticleVertex(particle, vertex, pt) {\n return this;\n }\n /**\n * This will be called before any other treatment by `setParticles()` and will be passed three parameters.\n * This does nothing and may be overwritten by the user.\n * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()\n * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()\n * @param update the boolean update value actually passed to setParticles()\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n beforeUpdateParticles(start, stop, update) { }\n /**\n * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.\n * This will be passed three parameters.\n * This does nothing and may be overwritten by the user.\n * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()\n * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()\n * @param update the boolean update value actually passed to setParticles()\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n afterUpdateParticles(start, stop, update) { }\n}\n//# sourceMappingURL=solidParticleSystem.js.map","import { Color4, Vector2, Vector3, TmpVectors, Quaternion } from \"../Maths/math.js\";\n/**\n * Represents one particle of a points cloud system.\n */\nexport class CloudPoint {\n /**\n * Creates a Point Cloud object.\n * Don't create particles manually, use instead the PCS internal tools like _addParticle()\n * @param particleIndex (integer) is the particle index in the PCS pool. It's also the particle identifier.\n * @param group (PointsGroup) is the group the particle belongs to\n * @param groupId (integer) is the group identifier in the PCS.\n * @param idxInGroup (integer) is the index of the particle in the current point group (ex: the 10th point of addPoints(30))\n * @param pcs defines the PCS it is associated to\n */\n constructor(particleIndex, group, groupId, idxInGroup, pcs) {\n /**\n * particle global index\n */\n this.idx = 0;\n /**\n * The color of the particle\n */\n this.color = new Color4(1.0, 1.0, 1.0, 1.0);\n /**\n * The world space position of the particle.\n */\n this.position = Vector3.Zero();\n /**\n * The world space rotation of the particle. (Not use if rotationQuaternion is set)\n */\n this.rotation = Vector3.Zero();\n /**\n * The uv of the particle.\n */\n this.uv = new Vector2(0.0, 0.0);\n /**\n * The current speed of the particle.\n */\n this.velocity = Vector3.Zero();\n /**\n * The pivot point in the particle local space.\n */\n this.pivot = Vector3.Zero();\n /**\n * Must the particle be translated from its pivot point in its local space ?\n * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.\n * Default : false\n */\n this.translateFromPivot = false;\n /**\n * Index of this particle in the global \"positions\" array (Internal use)\n * @internal\n */\n this._pos = 0;\n /**\n * @internal Index of this particle in the global \"indices\" array (Internal use)\n */\n this._ind = 0;\n /**\n * Group id of this particle\n */\n this.groupId = 0;\n /**\n * Index of the particle in its group id (Internal use)\n */\n this.idxInGroup = 0;\n /**\n * @internal Still set as invisible in order to skip useless computations (Internal use)\n */\n this._stillInvisible = false;\n /**\n * @internal Last computed particle rotation matrix\n */\n this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];\n /**\n * Parent particle Id, if any.\n * Default null.\n */\n this.parentId = null;\n /**\n * @internal Internal global position in the PCS.\n */\n this._globalPosition = Vector3.Zero();\n this.idx = particleIndex;\n this._group = group;\n this.groupId = groupId;\n this.idxInGroup = idxInGroup;\n this._pcs = pcs;\n }\n /**\n * get point size\n */\n get size() {\n return this.size;\n }\n /**\n * Set point size\n */\n set size(scale) {\n this.size = scale;\n }\n /**\n * Legacy support, changed quaternion to rotationQuaternion\n */\n get quaternion() {\n return this.rotationQuaternion;\n }\n /**\n * Legacy support, changed quaternion to rotationQuaternion\n */\n set quaternion(q) {\n this.rotationQuaternion = q;\n }\n /**\n * Returns a boolean. True if the particle intersects a mesh, else false\n * The intersection is computed on the particle position and Axis Aligned Bounding Box (AABB) or Sphere\n * @param target is the object (point or mesh) what the intersection is computed against\n * @param isSphere is boolean flag when false (default) bounding box of mesh is used, when true the bounding sphere is used\n * @returns true if it intersects\n */\n intersectsMesh(target, isSphere) {\n if (!target.hasBoundingInfo) {\n return false;\n }\n if (!this._pcs.mesh) {\n throw new Error(\"Point Cloud System doesnt contain the Mesh\");\n }\n if (isSphere) {\n return target.getBoundingInfo().boundingSphere.intersectsPoint(this.position.add(this._pcs.mesh.position));\n }\n const bbox = target.getBoundingInfo().boundingBox;\n const maxX = bbox.maximumWorld.x;\n const minX = bbox.minimumWorld.x;\n const maxY = bbox.maximumWorld.y;\n const minY = bbox.minimumWorld.y;\n const maxZ = bbox.maximumWorld.z;\n const minZ = bbox.minimumWorld.z;\n const x = this.position.x + this._pcs.mesh.position.x;\n const y = this.position.y + this._pcs.mesh.position.y;\n const z = this.position.z + this._pcs.mesh.position.z;\n return minX <= x && x <= maxX && minY <= y && y <= maxY && minZ <= z && z <= maxZ;\n }\n /**\n * get the rotation matrix of the particle\n * @internal\n */\n getRotationMatrix(m) {\n let quaternion;\n if (this.rotationQuaternion) {\n quaternion = this.rotationQuaternion;\n }\n else {\n quaternion = TmpVectors.Quaternion[0];\n const rotation = this.rotation;\n Quaternion.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, quaternion);\n }\n quaternion.toRotationMatrix(m);\n }\n}\n/**\n * Represents a group of points in a points cloud system\n * * PCS internal tool, don't use it manually.\n */\nexport class PointsGroup {\n /**\n * Get or set the groupId\n * @deprecated Please use groupId instead\n */\n get groupID() {\n return this.groupId;\n }\n set groupID(groupID) {\n this.groupId = groupID;\n }\n /**\n * Creates a points group object. This is an internal reference to produce particles for the PCS.\n * PCS internal tool, don't use it manually.\n * @internal\n */\n constructor(id, posFunction) {\n this.groupId = id;\n this._positionFunction = posFunction;\n }\n}\n//# sourceMappingURL=cloudPoint.js.map","import { Color4, Color3 } from \"../Maths/math.js\";\nimport { Vector2, Vector3, Vector4, TmpVectors, Matrix } from \"../Maths/math.vector.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { VertexData } from \"../Meshes/mesh.vertexData.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { CloudPoint, PointsGroup } from \"./cloudPoint.js\";\nimport { Ray } from \"../Culling/ray.js\";\nimport { StandardMaterial } from \"../Materials/standardMaterial.js\";\nimport { BaseTexture } from \"./../Materials/Textures/baseTexture.js\";\nimport { Scalar } from \"../Maths/math.scalar.js\";\n/** Defines the 4 color options */\nexport var PointColor;\n(function (PointColor) {\n /** color value */\n PointColor[PointColor[\"Color\"] = 2] = \"Color\";\n /** uv value */\n PointColor[PointColor[\"UV\"] = 1] = \"UV\";\n /** random value */\n PointColor[PointColor[\"Random\"] = 0] = \"Random\";\n /** stated value */\n PointColor[PointColor[\"Stated\"] = 3] = \"Stated\";\n})(PointColor || (PointColor = {}));\n/**\n * The PointCloudSystem (PCS) is a single updatable mesh. The points corresponding to the vertices of this big mesh.\n * As it is just a mesh, the PointCloudSystem has all the same properties as any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc.\n\n * The PointCloudSystem is also a particle system, with each point being a particle. It provides some methods to manage the particles.\n * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.\n *\n * Full documentation here : TO BE ENTERED\n */\nexport class PointsCloudSystem {\n /**\n * Gets the particle positions computed by the Point Cloud System\n */\n get positions() {\n return this._positions32;\n }\n /**\n * Gets the particle colors computed by the Point Cloud System\n */\n get colors() {\n return this._colors32;\n }\n /**\n * Gets the particle uvs computed by the Point Cloud System\n */\n get uvs() {\n return this._uvs32;\n }\n /**\n * Creates a PCS (Points Cloud System) object\n * @param name (String) is the PCS name, this will be the underlying mesh name\n * @param pointSize (number) is the size for each point. Has no effect on a WebGPU engine.\n * @param scene (Scene) is the scene in which the PCS is added\n * @param options defines the options of the PCS e.g.\n * * updatable (optional boolean, default true) : if the PCS must be updatable or immutable\n * @param options.updatable\n */\n constructor(name, pointSize, scene, options) {\n /**\n * The PCS array of cloud point objects. Just access each particle as with any classic array.\n * Example : var p = SPS.particles[i];\n */\n this.particles = new Array();\n /**\n * The PCS total number of particles. Read only. Use PCS.counter instead if you need to set your own value.\n */\n this.nbParticles = 0;\n /**\n * This a counter for your own usage. It's not set by any SPS functions.\n */\n this.counter = 0;\n /**\n * This empty object is intended to store some PCS specific or temporary values in order to lower the Garbage Collector activity.\n * Please read :\n */\n this.vars = {};\n this._promises = [];\n this._positions = new Array();\n this._indices = new Array();\n this._normals = new Array();\n this._colors = new Array();\n this._uvs = new Array();\n this._updatable = true;\n this._isVisibilityBoxLocked = false;\n this._alwaysVisible = false;\n this._groups = new Array(); //start indices for each group of particles\n this._groupCounter = 0;\n this._computeParticleColor = true;\n this._computeParticleTexture = true;\n this._computeParticleRotation = true;\n this._computeBoundingBox = false;\n this._isReady = false;\n this.name = name;\n this._size = pointSize;\n this._scene = scene || EngineStore.LastCreatedScene;\n if (options && options.updatable !== undefined) {\n this._updatable = options.updatable;\n }\n else {\n this._updatable = true;\n }\n }\n /**\n * Builds the PCS underlying mesh. Returns a standard Mesh.\n * If no points were added to the PCS, the returned mesh is just a single point.\n * @param material The material to use to render the mesh. If not provided, will create a default one\n * @returns a promise for the created mesh\n */\n buildMeshAsync(material) {\n return Promise.all(this._promises).then(() => {\n this._isReady = true;\n return this._buildMesh(material);\n });\n }\n /**\n * @internal\n */\n _buildMesh(material) {\n if (this.nbParticles === 0) {\n this.addPoints(1);\n }\n this._positions32 = new Float32Array(this._positions);\n this._uvs32 = new Float32Array(this._uvs);\n this._colors32 = new Float32Array(this._colors);\n const vertexData = new VertexData();\n vertexData.set(this._positions32, VertexBuffer.PositionKind);\n if (this._uvs32.length > 0) {\n vertexData.set(this._uvs32, VertexBuffer.UVKind);\n }\n let ec = 0; //emissive color value 0 for UVs, 1 for color\n if (this._colors32.length > 0) {\n ec = 1;\n vertexData.set(this._colors32, VertexBuffer.ColorKind);\n }\n const mesh = new Mesh(this.name, this._scene);\n vertexData.applyToMesh(mesh, this._updatable);\n this.mesh = mesh;\n // free memory\n this._positions = null;\n this._uvs = null;\n this._colors = null;\n if (!this._updatable) {\n this.particles.length = 0;\n }\n let mat = material;\n if (!mat) {\n mat = new StandardMaterial(\"point cloud material\", this._scene);\n mat.emissiveColor = new Color3(ec, ec, ec);\n mat.disableLighting = true;\n mat.pointsCloud = true;\n mat.pointSize = this._size;\n }\n mesh.material = mat;\n return new Promise((resolve) => resolve(mesh));\n }\n // adds a new particle object in the particles array\n _addParticle(idx, group, groupId, idxInGroup) {\n const cp = new CloudPoint(idx, group, groupId, idxInGroup, this);\n this.particles.push(cp);\n return cp;\n }\n _randomUnitVector(particle) {\n particle.position = new Vector3(Math.random(), Math.random(), Math.random());\n particle.color = new Color4(1, 1, 1, 1);\n }\n _getColorIndicesForCoord(pointsGroup, x, y, width) {\n const imageData = pointsGroup._groupImageData;\n const color = y * (width * 4) + x * 4;\n const colorIndices = [color, color + 1, color + 2, color + 3];\n const redIndex = colorIndices[0];\n const greenIndex = colorIndices[1];\n const blueIndex = colorIndices[2];\n const alphaIndex = colorIndices[3];\n const redForCoord = imageData[redIndex];\n const greenForCoord = imageData[greenIndex];\n const blueForCoord = imageData[blueIndex];\n const alphaForCoord = imageData[alphaIndex];\n return new Color4(redForCoord / 255, greenForCoord / 255, blueForCoord / 255, alphaForCoord);\n }\n _setPointsColorOrUV(mesh, pointsGroup, isVolume, colorFromTexture, hasTexture, color, range) {\n if (isVolume) {\n mesh.updateFacetData();\n }\n const boundInfo = mesh.getBoundingInfo();\n const diameter = 2 * boundInfo.boundingSphere.radius;\n let meshPos = mesh.getVerticesData(VertexBuffer.PositionKind);\n const meshInd = mesh.getIndices();\n const meshUV = mesh.getVerticesData(VertexBuffer.UVKind);\n const meshCol = mesh.getVerticesData(VertexBuffer.ColorKind);\n const place = Vector3.Zero();\n mesh.computeWorldMatrix();\n const meshMatrix = mesh.getWorldMatrix();\n if (!meshMatrix.isIdentity()) {\n meshPos = meshPos.slice(0);\n for (let p = 0; p < meshPos.length / 3; p++) {\n Vector3.TransformCoordinatesFromFloatsToRef(meshPos[3 * p], meshPos[3 * p + 1], meshPos[3 * p + 2], meshMatrix, place);\n meshPos[3 * p] = place.x;\n meshPos[3 * p + 1] = place.y;\n meshPos[3 * p + 2] = place.z;\n }\n }\n let idxPoints = 0;\n let id0 = 0;\n let id1 = 0;\n let id2 = 0;\n let v0X = 0;\n let v0Y = 0;\n let v0Z = 0;\n let v1X = 0;\n let v1Y = 0;\n let v1Z = 0;\n let v2X = 0;\n let v2Y = 0;\n let v2Z = 0;\n const vertex0 = Vector3.Zero();\n const vertex1 = Vector3.Zero();\n const vertex2 = Vector3.Zero();\n const vec0 = Vector3.Zero();\n const vec1 = Vector3.Zero();\n let uv0X = 0;\n let uv0Y = 0;\n let uv1X = 0;\n let uv1Y = 0;\n let uv2X = 0;\n let uv2Y = 0;\n const uv0 = Vector2.Zero();\n const uv1 = Vector2.Zero();\n const uv2 = Vector2.Zero();\n const uvec0 = Vector2.Zero();\n const uvec1 = Vector2.Zero();\n let col0X = 0;\n let col0Y = 0;\n let col0Z = 0;\n let col0A = 0;\n let col1X = 0;\n let col1Y = 0;\n let col1Z = 0;\n let col1A = 0;\n let col2X = 0;\n let col2Y = 0;\n let col2Z = 0;\n let col2A = 0;\n const col0 = Vector4.Zero();\n const col1 = Vector4.Zero();\n const col2 = Vector4.Zero();\n const colvec0 = Vector4.Zero();\n const colvec1 = Vector4.Zero();\n let lamda = 0;\n let mu = 0;\n range = range ? range : 0;\n let facetPoint;\n let uvPoint;\n let colPoint = new Vector4(0, 0, 0, 0);\n let norm = Vector3.Zero();\n let tang = Vector3.Zero();\n let biNorm = Vector3.Zero();\n let angle = 0;\n let facetPlaneVec = Vector3.Zero();\n let gap = 0;\n let distance = 0;\n const ray = new Ray(Vector3.Zero(), new Vector3(1, 0, 0));\n let pickInfo;\n let direction = Vector3.Zero();\n for (let index = 0; index < meshInd.length / 3; index++) {\n id0 = meshInd[3 * index];\n id1 = meshInd[3 * index + 1];\n id2 = meshInd[3 * index + 2];\n v0X = meshPos[3 * id0];\n v0Y = meshPos[3 * id0 + 1];\n v0Z = meshPos[3 * id0 + 2];\n v1X = meshPos[3 * id1];\n v1Y = meshPos[3 * id1 + 1];\n v1Z = meshPos[3 * id1 + 2];\n v2X = meshPos[3 * id2];\n v2Y = meshPos[3 * id2 + 1];\n v2Z = meshPos[3 * id2 + 2];\n vertex0.set(v0X, v0Y, v0Z);\n vertex1.set(v1X, v1Y, v1Z);\n vertex2.set(v2X, v2Y, v2Z);\n vertex1.subtractToRef(vertex0, vec0);\n vertex2.subtractToRef(vertex1, vec1);\n if (meshUV) {\n uv0X = meshUV[2 * id0];\n uv0Y = meshUV[2 * id0 + 1];\n uv1X = meshUV[2 * id1];\n uv1Y = meshUV[2 * id1 + 1];\n uv2X = meshUV[2 * id2];\n uv2Y = meshUV[2 * id2 + 1];\n uv0.set(uv0X, uv0Y);\n uv1.set(uv1X, uv1Y);\n uv2.set(uv2X, uv2Y);\n uv1.subtractToRef(uv0, uvec0);\n uv2.subtractToRef(uv1, uvec1);\n }\n if (meshCol && colorFromTexture) {\n col0X = meshCol[4 * id0];\n col0Y = meshCol[4 * id0 + 1];\n col0Z = meshCol[4 * id0 + 2];\n col0A = meshCol[4 * id0 + 3];\n col1X = meshCol[4 * id1];\n col1Y = meshCol[4 * id1 + 1];\n col1Z = meshCol[4 * id1 + 2];\n col1A = meshCol[4 * id1 + 3];\n col2X = meshCol[4 * id2];\n col2Y = meshCol[4 * id2 + 1];\n col2Z = meshCol[4 * id2 + 2];\n col2A = meshCol[4 * id2 + 3];\n col0.set(col0X, col0Y, col0Z, col0A);\n col1.set(col1X, col1Y, col1Z, col1A);\n col2.set(col2X, col2Y, col2Z, col2A);\n col1.subtractToRef(col0, colvec0);\n col2.subtractToRef(col1, colvec1);\n }\n let width;\n let height;\n let deltaS;\n let deltaV;\n let h;\n let s;\n let v;\n let hsvCol;\n const statedColor = new Color3(0, 0, 0);\n const colPoint3 = new Color3(0, 0, 0);\n let pointColors;\n let particle;\n for (let i = 0; i < pointsGroup._groupDensity[index]; i++) {\n idxPoints = this.particles.length;\n this._addParticle(idxPoints, pointsGroup, this._groupCounter, index + i);\n particle = this.particles[idxPoints];\n //form a point inside the facet v0, v1, v2;\n lamda = Scalar.RandomRange(0, 1);\n mu = Scalar.RandomRange(0, 1);\n facetPoint = vertex0.add(vec0.scale(lamda)).add(vec1.scale(lamda * mu));\n if (isVolume) {\n norm = mesh.getFacetNormal(index).normalize().scale(-1);\n tang = vec0.clone().normalize();\n biNorm = Vector3.Cross(norm, tang);\n angle = Scalar.RandomRange(0, 2 * Math.PI);\n facetPlaneVec = tang.scale(Math.cos(angle)).add(biNorm.scale(Math.sin(angle)));\n angle = Scalar.RandomRange(0.1, Math.PI / 2);\n direction = facetPlaneVec.scale(Math.cos(angle)).add(norm.scale(Math.sin(angle)));\n ray.origin = facetPoint.add(direction.scale(0.00001));\n ray.direction = direction;\n ray.length = diameter;\n pickInfo = ray.intersectsMesh(mesh);\n if (pickInfo.hit) {\n distance = pickInfo.pickedPoint.subtract(facetPoint).length();\n gap = Scalar.RandomRange(0, 1) * distance;\n facetPoint.addInPlace(direction.scale(gap));\n }\n }\n particle.position = facetPoint.clone();\n this._positions.push(particle.position.x, particle.position.y, particle.position.z);\n if (colorFromTexture !== undefined) {\n if (meshUV) {\n uvPoint = uv0.add(uvec0.scale(lamda)).add(uvec1.scale(lamda * mu));\n if (colorFromTexture) {\n //Set particle color to texture color\n if (hasTexture && pointsGroup._groupImageData !== null) {\n width = pointsGroup._groupImgWidth;\n height = pointsGroup._groupImgHeight;\n pointColors = this._getColorIndicesForCoord(pointsGroup, Math.round(uvPoint.x * width), Math.round(uvPoint.y * height), width);\n particle.color = pointColors;\n this._colors.push(pointColors.r, pointColors.g, pointColors.b, pointColors.a);\n }\n else {\n if (meshCol) {\n //failure in texture and colors available\n colPoint = col0.add(colvec0.scale(lamda)).add(colvec1.scale(lamda * mu));\n particle.color = new Color4(colPoint.x, colPoint.y, colPoint.z, colPoint.w);\n this._colors.push(colPoint.x, colPoint.y, colPoint.z, colPoint.w);\n }\n else {\n colPoint = col0.set(Math.random(), Math.random(), Math.random(), 1);\n particle.color = new Color4(colPoint.x, colPoint.y, colPoint.z, colPoint.w);\n this._colors.push(colPoint.x, colPoint.y, colPoint.z, colPoint.w);\n }\n }\n }\n else {\n //Set particle uv based on a mesh uv\n particle.uv = uvPoint.clone();\n this._uvs.push(particle.uv.x, particle.uv.y);\n }\n }\n }\n else {\n if (color) {\n statedColor.set(color.r, color.g, color.b);\n deltaS = Scalar.RandomRange(-range, range);\n deltaV = Scalar.RandomRange(-range, range);\n hsvCol = statedColor.toHSV();\n h = hsvCol.r;\n s = hsvCol.g + deltaS;\n v = hsvCol.b + deltaV;\n if (s < 0) {\n s = 0;\n }\n if (s > 1) {\n s = 1;\n }\n if (v < 0) {\n v = 0;\n }\n if (v > 1) {\n v = 1;\n }\n Color3.HSVtoRGBToRef(h, s, v, colPoint3);\n colPoint.set(colPoint3.r, colPoint3.g, colPoint3.b, 1);\n }\n else {\n colPoint = col0.set(Math.random(), Math.random(), Math.random(), 1);\n }\n particle.color = new Color4(colPoint.x, colPoint.y, colPoint.z, colPoint.w);\n this._colors.push(colPoint.x, colPoint.y, colPoint.z, colPoint.w);\n }\n }\n }\n }\n // stores mesh texture in dynamic texture for color pixel retrieval\n // when pointColor type is color for surface points\n _colorFromTexture(mesh, pointsGroup, isVolume) {\n if (mesh.material === null) {\n Logger.Warn(mesh.name + \"has no material.\");\n pointsGroup._groupImageData = null;\n this._setPointsColorOrUV(mesh, pointsGroup, isVolume, true, false);\n return;\n }\n const mat = mesh.material;\n const textureList = mat.getActiveTextures();\n if (textureList.length === 0) {\n Logger.Warn(mesh.name + \"has no usable texture.\");\n pointsGroup._groupImageData = null;\n this._setPointsColorOrUV(mesh, pointsGroup, isVolume, true, false);\n return;\n }\n const clone = mesh.clone();\n clone.setEnabled(false);\n this._promises.push(new Promise((resolve) => {\n BaseTexture.WhenAllReady(textureList, () => {\n let n = pointsGroup._textureNb;\n if (n < 0) {\n n = 0;\n }\n if (n > textureList.length - 1) {\n n = textureList.length - 1;\n }\n const finalize = () => {\n pointsGroup._groupImgWidth = textureList[n].getSize().width;\n pointsGroup._groupImgHeight = textureList[n].getSize().height;\n this._setPointsColorOrUV(clone, pointsGroup, isVolume, true, true);\n clone.dispose();\n resolve();\n };\n pointsGroup._groupImageData = null;\n const dataPromise = textureList[n].readPixels();\n if (!dataPromise) {\n finalize();\n }\n else {\n dataPromise.then((data) => {\n pointsGroup._groupImageData = data;\n finalize();\n });\n }\n });\n }));\n }\n // calculates the point density per facet of a mesh for surface points\n _calculateDensity(nbPoints, positions, indices) {\n let density = new Array();\n let id0;\n let id1;\n let id2;\n let v0X;\n let v0Y;\n let v0Z;\n let v1X;\n let v1Y;\n let v1Z;\n let v2X;\n let v2Y;\n let v2Z;\n const vertex0 = Vector3.Zero();\n const vertex1 = Vector3.Zero();\n const vertex2 = Vector3.Zero();\n const vec0 = Vector3.Zero();\n const vec1 = Vector3.Zero();\n const vec2 = Vector3.Zero();\n let a; //length of side of triangle\n let b; //length of side of triangle\n let c; //length of side of triangle\n let p; //perimeter of triangle\n let area;\n const areas = new Array();\n let surfaceArea = 0;\n const nbFacets = indices.length / 3;\n //surface area\n for (let index = 0; index < nbFacets; index++) {\n id0 = indices[3 * index];\n id1 = indices[3 * index + 1];\n id2 = indices[3 * index + 2];\n v0X = positions[3 * id0];\n v0Y = positions[3 * id0 + 1];\n v0Z = positions[3 * id0 + 2];\n v1X = positions[3 * id1];\n v1Y = positions[3 * id1 + 1];\n v1Z = positions[3 * id1 + 2];\n v2X = positions[3 * id2];\n v2Y = positions[3 * id2 + 1];\n v2Z = positions[3 * id2 + 2];\n vertex0.set(v0X, v0Y, v0Z);\n vertex1.set(v1X, v1Y, v1Z);\n vertex2.set(v2X, v2Y, v2Z);\n vertex1.subtractToRef(vertex0, vec0);\n vertex2.subtractToRef(vertex1, vec1);\n vertex2.subtractToRef(vertex0, vec2);\n a = vec0.length();\n b = vec1.length();\n c = vec2.length();\n p = (a + b + c) / 2;\n area = Math.sqrt(p * (p - a) * (p - b) * (p - c));\n surfaceArea += area;\n areas[index] = area;\n }\n let pointCount = 0;\n for (let index = 0; index < nbFacets; index++) {\n density[index] = Math.floor((nbPoints * areas[index]) / surfaceArea);\n pointCount += density[index];\n }\n const diff = nbPoints - pointCount;\n const pointsPerFacet = Math.floor(diff / nbFacets);\n const extraPoints = diff % nbFacets;\n if (pointsPerFacet > 0) {\n density = density.map((x) => x + pointsPerFacet);\n }\n for (let index = 0; index < extraPoints; index++) {\n density[index] += 1;\n }\n return density;\n }\n /**\n * Adds points to the PCS in random positions within a unit sphere\n * @param nb (positive integer) the number of particles to be created from this model\n * @param pointFunction is an optional javascript function to be called for each particle on PCS creation\n * @returns the number of groups in the system\n */\n addPoints(nb, pointFunction = this._randomUnitVector) {\n const pointsGroup = new PointsGroup(this._groupCounter, pointFunction);\n let cp;\n // particles\n let idx = this.nbParticles;\n for (let i = 0; i < nb; i++) {\n cp = this._addParticle(idx, pointsGroup, this._groupCounter, i);\n if (pointsGroup && pointsGroup._positionFunction) {\n pointsGroup._positionFunction(cp, idx, i);\n }\n this._positions.push(cp.position.x, cp.position.y, cp.position.z);\n if (cp.color) {\n this._colors.push(cp.color.r, cp.color.g, cp.color.b, cp.color.a);\n }\n if (cp.uv) {\n this._uvs.push(cp.uv.x, cp.uv.y);\n }\n idx++;\n }\n this.nbParticles += nb;\n this._groupCounter++;\n return this._groupCounter;\n }\n /**\n * Adds points to the PCS from the surface of the model shape\n * @param mesh is any Mesh object that will be used as a surface model for the points\n * @param nb (positive integer) the number of particles to be created from this model\n * @param colorWith determines whether a point is colored using color (default), uv, random, stated or none (invisible)\n * @param color (color4) to be used when colorWith is stated or color (number) when used to specify texture position\n * @param range (number from 0 to 1) to determine the variation in shape and tone for a stated color\n * @returns the number of groups in the system\n */\n addSurfacePoints(mesh, nb, colorWith, color, range) {\n let colored = colorWith ? colorWith : PointColor.Random;\n if (isNaN(colored) || colored < 0 || colored > 3) {\n colored = PointColor.Random;\n }\n const meshPos = mesh.getVerticesData(VertexBuffer.PositionKind);\n const meshInd = mesh.getIndices();\n this._groups.push(this._groupCounter);\n const pointsGroup = new PointsGroup(this._groupCounter, null);\n pointsGroup._groupDensity = this._calculateDensity(nb, meshPos, meshInd);\n if (colored === PointColor.Color) {\n pointsGroup._textureNb = color ? color : 0;\n }\n else {\n color = color ? color : new Color4(1, 1, 1, 1);\n }\n switch (colored) {\n case PointColor.Color:\n this._colorFromTexture(mesh, pointsGroup, false);\n break;\n case PointColor.UV:\n this._setPointsColorOrUV(mesh, pointsGroup, false, false, false);\n break;\n case PointColor.Random:\n this._setPointsColorOrUV(mesh, pointsGroup, false);\n break;\n case PointColor.Stated:\n this._setPointsColorOrUV(mesh, pointsGroup, false, undefined, undefined, color, range);\n break;\n }\n this.nbParticles += nb;\n this._groupCounter++;\n return this._groupCounter - 1;\n }\n /**\n * Adds points to the PCS inside the model shape\n * @param mesh is any Mesh object that will be used as a surface model for the points\n * @param nb (positive integer) the number of particles to be created from this model\n * @param colorWith determines whether a point is colored using color (default), uv, random, stated or none (invisible)\n * @param color (color4) to be used when colorWith is stated or color (number) when used to specify texture position\n * @param range (number from 0 to 1) to determine the variation in shape and tone for a stated color\n * @returns the number of groups in the system\n */\n addVolumePoints(mesh, nb, colorWith, color, range) {\n let colored = colorWith ? colorWith : PointColor.Random;\n if (isNaN(colored) || colored < 0 || colored > 3) {\n colored = PointColor.Random;\n }\n const meshPos = mesh.getVerticesData(VertexBuffer.PositionKind);\n const meshInd = mesh.getIndices();\n this._groups.push(this._groupCounter);\n const pointsGroup = new PointsGroup(this._groupCounter, null);\n pointsGroup._groupDensity = this._calculateDensity(nb, meshPos, meshInd);\n if (colored === PointColor.Color) {\n pointsGroup._textureNb = color ? color : 0;\n }\n else {\n color = color ? color : new Color4(1, 1, 1, 1);\n }\n switch (colored) {\n case PointColor.Color:\n this._colorFromTexture(mesh, pointsGroup, true);\n break;\n case PointColor.UV:\n this._setPointsColorOrUV(mesh, pointsGroup, true, false, false);\n break;\n case PointColor.Random:\n this._setPointsColorOrUV(mesh, pointsGroup, true);\n break;\n case PointColor.Stated:\n this._setPointsColorOrUV(mesh, pointsGroup, true, undefined, undefined, color, range);\n break;\n }\n this.nbParticles += nb;\n this._groupCounter++;\n return this._groupCounter - 1;\n }\n /**\n * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.\n * This method calls `updateParticle()` for each particle of the SPS.\n * For an animated SPS, it is usually called within the render loop.\n * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_\n * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_\n * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_\n * @returns the PCS.\n */\n setParticles(start = 0, end = this.nbParticles - 1, update = true) {\n var _a, _b;\n if (!this._updatable || !this._isReady) {\n return this;\n }\n // custom beforeUpdate\n this.beforeUpdateParticles(start, end, update);\n const rotMatrix = TmpVectors.Matrix[0];\n const mesh = this.mesh;\n const colors32 = this._colors32;\n const positions32 = this._positions32;\n const uvs32 = this._uvs32;\n const tempVectors = TmpVectors.Vector3;\n const camAxisX = tempVectors[5].copyFromFloats(1.0, 0.0, 0.0);\n const camAxisY = tempVectors[6].copyFromFloats(0.0, 1.0, 0.0);\n const camAxisZ = tempVectors[7].copyFromFloats(0.0, 0.0, 1.0);\n const minimum = tempVectors[8].setAll(Number.MAX_VALUE);\n const maximum = tempVectors[9].setAll(-Number.MAX_VALUE);\n Matrix.IdentityToRef(rotMatrix);\n let idx = 0; // current index of the particle\n if ((_a = this.mesh) === null || _a === void 0 ? void 0 : _a.isFacetDataEnabled) {\n this._computeBoundingBox = true;\n }\n end = end >= this.nbParticles ? this.nbParticles - 1 : end;\n if (this._computeBoundingBox) {\n if (start != 0 || end != this.nbParticles - 1) {\n // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.\n const boundingInfo = (_b = this.mesh) === null || _b === void 0 ? void 0 : _b.getBoundingInfo();\n if (boundingInfo) {\n minimum.copyFrom(boundingInfo.minimum);\n maximum.copyFrom(boundingInfo.maximum);\n }\n }\n }\n idx = 0; // particle index\n let pindex = 0; //index in positions array\n let cindex = 0; //index in color array\n let uindex = 0; //index in uv array\n // particle loop\n for (let p = start; p <= end; p++) {\n const particle = this.particles[p];\n idx = particle.idx;\n pindex = 3 * idx;\n cindex = 4 * idx;\n uindex = 2 * idx;\n // call to custom user function to update the particle properties\n this.updateParticle(particle);\n const particleRotationMatrix = particle._rotationMatrix;\n const particlePosition = particle.position;\n const particleGlobalPosition = particle._globalPosition;\n if (this._computeParticleRotation) {\n particle.getRotationMatrix(rotMatrix);\n }\n const particleHasParent = particle.parentId !== null;\n if (particleHasParent) {\n const parent = this.particles[particle.parentId];\n const parentRotationMatrix = parent._rotationMatrix;\n const parentGlobalPosition = parent._globalPosition;\n const rotatedY = particlePosition.x * parentRotationMatrix[1] + particlePosition.y * parentRotationMatrix[4] + particlePosition.z * parentRotationMatrix[7];\n const rotatedX = particlePosition.x * parentRotationMatrix[0] + particlePosition.y * parentRotationMatrix[3] + particlePosition.z * parentRotationMatrix[6];\n const rotatedZ = particlePosition.x * parentRotationMatrix[2] + particlePosition.y * parentRotationMatrix[5] + particlePosition.z * parentRotationMatrix[8];\n particleGlobalPosition.x = parentGlobalPosition.x + rotatedX;\n particleGlobalPosition.y = parentGlobalPosition.y + rotatedY;\n particleGlobalPosition.z = parentGlobalPosition.z + rotatedZ;\n if (this._computeParticleRotation) {\n const rotMatrixValues = rotMatrix.m;\n particleRotationMatrix[0] =\n rotMatrixValues[0] * parentRotationMatrix[0] + rotMatrixValues[1] * parentRotationMatrix[3] + rotMatrixValues[2] * parentRotationMatrix[6];\n particleRotationMatrix[1] =\n rotMatrixValues[0] * parentRotationMatrix[1] + rotMatrixValues[1] * parentRotationMatrix[4] + rotMatrixValues[2] * parentRotationMatrix[7];\n particleRotationMatrix[2] =\n rotMatrixValues[0] * parentRotationMatrix[2] + rotMatrixValues[1] * parentRotationMatrix[5] + rotMatrixValues[2] * parentRotationMatrix[8];\n particleRotationMatrix[3] =\n rotMatrixValues[4] * parentRotationMatrix[0] + rotMatrixValues[5] * parentRotationMatrix[3] + rotMatrixValues[6] * parentRotationMatrix[6];\n particleRotationMatrix[4] =\n rotMatrixValues[4] * parentRotationMatrix[1] + rotMatrixValues[5] * parentRotationMatrix[4] + rotMatrixValues[6] * parentRotationMatrix[7];\n particleRotationMatrix[5] =\n rotMatrixValues[4] * parentRotationMatrix[2] + rotMatrixValues[5] * parentRotationMatrix[5] + rotMatrixValues[6] * parentRotationMatrix[8];\n particleRotationMatrix[6] =\n rotMatrixValues[8] * parentRotationMatrix[0] + rotMatrixValues[9] * parentRotationMatrix[3] + rotMatrixValues[10] * parentRotationMatrix[6];\n particleRotationMatrix[7] =\n rotMatrixValues[8] * parentRotationMatrix[1] + rotMatrixValues[9] * parentRotationMatrix[4] + rotMatrixValues[10] * parentRotationMatrix[7];\n particleRotationMatrix[8] =\n rotMatrixValues[8] * parentRotationMatrix[2] + rotMatrixValues[9] * parentRotationMatrix[5] + rotMatrixValues[10] * parentRotationMatrix[8];\n }\n }\n else {\n particleGlobalPosition.x = 0;\n particleGlobalPosition.y = 0;\n particleGlobalPosition.z = 0;\n if (this._computeParticleRotation) {\n const rotMatrixValues = rotMatrix.m;\n particleRotationMatrix[0] = rotMatrixValues[0];\n particleRotationMatrix[1] = rotMatrixValues[1];\n particleRotationMatrix[2] = rotMatrixValues[2];\n particleRotationMatrix[3] = rotMatrixValues[4];\n particleRotationMatrix[4] = rotMatrixValues[5];\n particleRotationMatrix[5] = rotMatrixValues[6];\n particleRotationMatrix[6] = rotMatrixValues[8];\n particleRotationMatrix[7] = rotMatrixValues[9];\n particleRotationMatrix[8] = rotMatrixValues[10];\n }\n }\n const pivotBackTranslation = tempVectors[11];\n if (particle.translateFromPivot) {\n pivotBackTranslation.setAll(0.0);\n }\n else {\n pivotBackTranslation.copyFrom(particle.pivot);\n }\n // positions\n const tmpVertex = tempVectors[0];\n tmpVertex.copyFrom(particle.position);\n const vertexX = tmpVertex.x - particle.pivot.x;\n const vertexY = tmpVertex.y - particle.pivot.y;\n const vertexZ = tmpVertex.z - particle.pivot.z;\n let rotatedX = vertexX * particleRotationMatrix[0] + vertexY * particleRotationMatrix[3] + vertexZ * particleRotationMatrix[6];\n let rotatedY = vertexX * particleRotationMatrix[1] + vertexY * particleRotationMatrix[4] + vertexZ * particleRotationMatrix[7];\n let rotatedZ = vertexX * particleRotationMatrix[2] + vertexY * particleRotationMatrix[5] + vertexZ * particleRotationMatrix[8];\n rotatedX += pivotBackTranslation.x;\n rotatedY += pivotBackTranslation.y;\n rotatedZ += pivotBackTranslation.z;\n const px = (positions32[pindex] = particleGlobalPosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ);\n const py = (positions32[pindex + 1] = particleGlobalPosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ);\n const pz = (positions32[pindex + 2] = particleGlobalPosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ);\n if (this._computeBoundingBox) {\n minimum.minimizeInPlaceFromFloats(px, py, pz);\n maximum.maximizeInPlaceFromFloats(px, py, pz);\n }\n if (this._computeParticleColor && particle.color) {\n const color = particle.color;\n const colors32 = this._colors32;\n colors32[cindex] = color.r;\n colors32[cindex + 1] = color.g;\n colors32[cindex + 2] = color.b;\n colors32[cindex + 3] = color.a;\n }\n if (this._computeParticleTexture && particle.uv) {\n const uv = particle.uv;\n const uvs32 = this._uvs32;\n uvs32[uindex] = uv.x;\n uvs32[uindex + 1] = uv.y;\n }\n }\n // if the VBO must be updated\n if (mesh) {\n if (update) {\n if (this._computeParticleColor) {\n mesh.updateVerticesData(VertexBuffer.ColorKind, colors32, false, false);\n }\n if (this._computeParticleTexture) {\n mesh.updateVerticesData(VertexBuffer.UVKind, uvs32, false, false);\n }\n mesh.updateVerticesData(VertexBuffer.PositionKind, positions32, false, false);\n }\n if (this._computeBoundingBox) {\n if (mesh.hasBoundingInfo) {\n mesh.getBoundingInfo().reConstruct(minimum, maximum, mesh._worldMatrix);\n }\n else {\n mesh.buildBoundingInfo(minimum, maximum, mesh._worldMatrix);\n }\n }\n }\n this.afterUpdateParticles(start, end, update);\n return this;\n }\n /**\n * Disposes the PCS.\n */\n dispose() {\n var _a;\n (_a = this.mesh) === null || _a === void 0 ? void 0 : _a.dispose();\n this.vars = null;\n // drop references to internal big arrays for the GC\n this._positions = null;\n this._indices = null;\n this._normals = null;\n this._uvs = null;\n this._colors = null;\n this._indices32 = null;\n this._positions32 = null;\n this._uvs32 = null;\n this._colors32 = null;\n }\n /**\n * Visibility helper : Recomputes the visible size according to the mesh bounding box\n * doc :\n * @returns the PCS.\n */\n refreshVisibleSize() {\n var _a;\n if (!this._isVisibilityBoxLocked) {\n (_a = this.mesh) === null || _a === void 0 ? void 0 : _a.refreshBoundingInfo();\n }\n return this;\n }\n /**\n * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.\n * @param size the size (float) of the visibility box\n * note : this doesn't lock the PCS mesh bounding box.\n * doc :\n */\n setVisibilityBox(size) {\n if (!this.mesh) {\n return;\n }\n const vis = size / 2;\n this.mesh.buildBoundingInfo(new Vector3(-vis, -vis, -vis), new Vector3(vis, vis, vis));\n }\n /**\n * Gets whether the PCS is always visible or not\n * doc :\n */\n get isAlwaysVisible() {\n return this._alwaysVisible;\n }\n /**\n * Sets the PCS as always visible or not\n * doc :\n */\n set isAlwaysVisible(val) {\n if (!this.mesh) {\n return;\n }\n this._alwaysVisible = val;\n this.mesh.alwaysSelectAsActiveMesh = val;\n }\n /**\n * Tells to `setParticles()` to compute the particle rotations or not\n * Default value : false. The PCS is faster when it's set to false\n * Note : particle rotations are only applied to parent particles\n * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate\n */\n set computeParticleRotation(val) {\n this._computeParticleRotation = val;\n }\n /**\n * Tells to `setParticles()` to compute the particle colors or not.\n * Default value : true. The PCS is faster when it's set to false.\n * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.\n */\n set computeParticleColor(val) {\n this._computeParticleColor = val;\n }\n set computeParticleTexture(val) {\n this._computeParticleTexture = val;\n }\n /**\n * Gets if `setParticles()` computes the particle colors or not.\n * Default value : false. The PCS is faster when it's set to false.\n * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.\n */\n get computeParticleColor() {\n return this._computeParticleColor;\n }\n /**\n * Gets if `setParticles()` computes the particle textures or not.\n * Default value : false. The PCS is faster when it's set to false.\n * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.\n */\n get computeParticleTexture() {\n return this._computeParticleTexture;\n }\n /**\n * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.\n */\n set computeBoundingBox(val) {\n this._computeBoundingBox = val;\n }\n /**\n * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.\n */\n get computeBoundingBox() {\n return this._computeBoundingBox;\n }\n // =======================================================================\n // Particle behavior logic\n // these following methods may be overwritten by users to fit their needs\n /**\n * This function does nothing. It may be overwritten to set all the particle first values.\n * The PCS doesn't call this function, you may have to call it by your own.\n * doc :\n */\n initParticles() { }\n /**\n * This function does nothing. It may be overwritten to recycle a particle\n * The PCS doesn't call this function, you can to call it\n * doc :\n * @param particle The particle to recycle\n * @returns the recycled particle\n */\n recycleParticle(particle) {\n return particle;\n }\n /**\n * Updates a particle : this function should be overwritten by the user.\n * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.\n * doc :\n * @example : just set a particle position or velocity and recycle conditions\n * @param particle The particle to update\n * @returns the updated particle\n */\n updateParticle(particle) {\n return particle;\n }\n /**\n * This will be called before any other treatment by `setParticles()` and will be passed three parameters.\n * This does nothing and may be overwritten by the user.\n * @param start the particle index in the particle array where to start to iterate, same than the value passed to setParticle()\n * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()\n * @param update the boolean update value actually passed to setParticles()\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n beforeUpdateParticles(start, stop, update) { }\n /**\n * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.\n * This will be passed three parameters.\n * This does nothing and may be overwritten by the user.\n * @param start the particle index in the particle array where to start to iterate, same than the value passed to setParticle()\n * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()\n * @param update the boolean update value actually passed to setParticles()\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n afterUpdateParticles(start, stop, update) { }\n}\n//# sourceMappingURL=pointsCloudSystem.js.map","/* eslint-disable import/export */\n/* eslint-disable import/no-internal-modules */\nexport * from \"./baseParticleSystem.js\";\nexport * from \"./EmitterTypes/index.js\";\nexport * from \"./webgl2ParticleSystem.js\";\nexport * from \"./computeShaderParticleSystem.js\";\nexport * from \"./gpuParticleSystem.js\";\nexport * from \"./IParticleSystem.js\";\nexport * from \"./particle.js\";\nexport * from \"./particleHelper.js\";\nexport * from \"./particleSystem.js\";\nimport \"./particleSystemComponent.js\";\n// eslint-disable-next-line no-duplicate-imports\nexport * from \"./particleSystemComponent.js\";\nexport * from \"./particleSystemSet.js\";\nexport * from \"./solidParticle.js\";\nexport * from \"./solidParticleSystem.js\";\nexport * from \"./cloudPoint.js\";\nexport * from \"./pointsCloudSystem.js\";\nexport * from \"./subEmitter.js\";\n//# sourceMappingURL=index.js.map","import { AbstractMesh } from \"../../Meshes/abstractMesh.js\";\nimport { PhysicsJoint } from \"./physicsJoint.js\";\nObject.defineProperty(AbstractMesh.prototype, \"physicsImpostor\", {\n get: function () {\n return this._physicsImpostor;\n },\n set: function (value) {\n if (this._physicsImpostor === value) {\n return;\n }\n if (this._disposePhysicsObserver) {\n this.onDisposeObservable.remove(this._disposePhysicsObserver);\n }\n this._physicsImpostor = value;\n if (value) {\n this._disposePhysicsObserver = this.onDisposeObservable.add(() => {\n // Physics\n if (this.physicsImpostor) {\n this.physicsImpostor.dispose( /*!doNotRecurse*/);\n this.physicsImpostor = null;\n }\n });\n }\n },\n enumerable: true,\n configurable: true,\n});\n/**\n * Gets the current physics impostor\n * @see https://doc.babylonjs.com/features/featuresDeepDive/physics\n * @returns a physics impostor or null\n */\nAbstractMesh.prototype.getPhysicsImpostor = function () {\n return this.physicsImpostor;\n};\n/**\n * Apply a physic impulse to the mesh\n * @param force defines the force to apply\n * @param contactPoint defines where to apply the force\n * @returns the current mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine\n */\nAbstractMesh.prototype.applyImpulse = function (force, contactPoint) {\n if (!this.physicsImpostor) {\n return this;\n }\n this.physicsImpostor.applyImpulse(force, contactPoint);\n return this;\n};\n/**\n * Creates a physic joint between two meshes\n * @param otherMesh defines the other mesh to use\n * @param pivot1 defines the pivot to use on this mesh\n * @param pivot2 defines the pivot to use on the other mesh\n * @param options defines additional options (can be plugin dependent)\n * @returns the current mesh\n * @see https://www.babylonjs-playground.com/#0BS5U0#0\n */\nAbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {\n if (!this.physicsImpostor || !otherMesh.physicsImpostor) {\n return this;\n }\n this.physicsImpostor.createJoint(otherMesh.physicsImpostor, PhysicsJoint.HingeJoint, {\n mainPivot: pivot1,\n connectedPivot: pivot2,\n nativeParams: options,\n });\n return this;\n};\n//# sourceMappingURL=physicsEngineComponent.js.map","export {};\n//# sourceMappingURL=IPhysicsEnginePlugin.js.map","export * from \"./cannonJSPlugin.js\";\nexport * from \"./ammoJSPlugin.js\";\nexport * from \"./oimoJSPlugin.js\";\n//# sourceMappingURL=index.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./IPhysicsEnginePlugin.js\";\nexport * from \"./physicsEngine.js\";\nexport * from \"./physicsEngineComponent.js\";\nexport * from \"./physicsImpostor.js\";\nexport * from \"./physicsJoint.js\";\nexport * from \"./Plugins/index.js\";\n//# sourceMappingURL=index.js.map","import { Vector3 } from \"../../Maths/math.vector.js\";\nimport { PhysicsRaycastResult } from \"../physicsRaycastResult.js\";\nimport { _WarnImport } from \"../../Misc/devTools.js\";\n/**\n * Class used to control physics engine\n * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine\n */\nexport class PhysicsEngine {\n /**\n *\n * @returns physics plugin version\n */\n getPluginVersion() {\n return this._physicsPlugin.getPluginVersion();\n }\n /**\n * Factory used to create the default physics plugin.\n * @returns The default physics plugin\n */\n static DefaultPluginFactory() {\n throw _WarnImport(\"\");\n }\n /**\n * Creates a new Physics Engine\n * @param gravity defines the gravity vector used by the simulation\n * @param _physicsPlugin defines the plugin to use (CannonJS by default)\n */\n constructor(gravity, _physicsPlugin = PhysicsEngine.DefaultPluginFactory()) {\n this._physicsPlugin = _physicsPlugin;\n /** @internal */\n this._physicsBodies = [];\n this._subTimeStep = 0;\n gravity = gravity || new Vector3(0, -9.807, 0);\n this.setGravity(gravity);\n this.setTimeStep();\n }\n /**\n * Sets the gravity vector used by the simulation\n * @param gravity defines the gravity vector to use\n */\n setGravity(gravity) {\n this.gravity = gravity;\n this._physicsPlugin.setGravity(this.gravity);\n }\n /**\n * Set the time step of the physics engine.\n * Default is 1/60.\n * To slow it down, enter 1/600 for example.\n * To speed it up, 1/30\n * @param newTimeStep defines the new timestep to apply to this world.\n */\n setTimeStep(newTimeStep = 1 / 60) {\n this._physicsPlugin.setTimeStep(newTimeStep);\n }\n /**\n * Get the time step of the physics engine.\n * @returns the current time step\n */\n getTimeStep() {\n return this._physicsPlugin.getTimeStep();\n }\n /**\n * Set the sub time step of the physics engine.\n * Default is 0 meaning there is no sub steps\n * To increase physics resolution precision, set a small value (like 1 ms)\n * @param subTimeStep defines the new sub timestep used for physics resolution.\n */\n setSubTimeStep(subTimeStep = 0) {\n this._subTimeStep = subTimeStep;\n }\n /**\n * Get the sub time step of the physics engine.\n * @returns the current sub time step\n */\n getSubTimeStep() {\n return this._subTimeStep;\n }\n /**\n * Release all resources\n */\n dispose() {\n this._physicsPlugin.dispose();\n }\n /**\n * Gets the name of the current physics plugin\n * @returns the name of the plugin\n */\n getPhysicsPluginName() {\n return this._physicsPlugin.name;\n }\n /**\n * Adding a new impostor for the impostor tracking.\n * This will be done by the impostor itself.\n * @param impostor the impostor to add\n */\n /**\n * Called by the scene. No need to call it.\n * @param delta defines the timespan between frames\n */\n _step(delta) {\n if (delta > 0.1) {\n delta = 0.1;\n }\n else if (delta <= 0) {\n delta = 1.0 / 60.0;\n }\n this._physicsPlugin.executeStep(delta, this._physicsBodies);\n }\n /**\n * Add a body as an active component of this engine\n * @param body\n */\n addBody(physicsBody) {\n this._physicsBodies.push(physicsBody);\n }\n /**\n * Removes a particular body from this engine\n */\n removeBody(physicsBody) {\n const index = this._physicsBodies.indexOf(physicsBody);\n if (index > -1) {\n /*const removed =*/ this._physicsBodies.splice(index, 1);\n }\n }\n /**\n * Returns an array of bodies added to this engine\n\n */\n getBodies() {\n return this._physicsBodies;\n }\n /**\n * Gets the current plugin used to run the simulation\n * @returns current plugin\n */\n getPhysicsPlugin() {\n return this._physicsPlugin;\n }\n /**\n * Does a raycast in the physics world\n * @param from when should the ray start?\n * @param to when should the ray end?\n * @param result resulting PhysicsRaycastResult\n */\n raycastToRef(from, to, result, query) {\n this._physicsPlugin.raycast(from, to, result, query);\n }\n /**\n * Does a raycast in the physics world\n * @param from when should the ray start?\n * @param to when should the ray end?\n * @returns PhysicsRaycastResult\n */\n raycast(from, to, query) {\n const result = new PhysicsRaycastResult();\n this._physicsPlugin.raycast(from, to, result, query);\n return result;\n }\n}\n//# sourceMappingURL=physicsEngine.js.map","import { Vector3, Quaternion, TmpVectors } from \"../../Maths/math.vector.js\";\nimport { Space } from \"../../Maths/math.axis.js\";\n/**\n * PhysicsBody is useful for creating a physics body that can be used in a physics engine. It allows\n * the user to set the mass and velocity of the body, which can then be used to calculate the\n * motion of the body in the physics engine.\n */\nexport class PhysicsBody {\n /**\n * Constructs a new physics body for the given node.\n * @param transformNode - The Transform Node to construct the physics body for. For better performance, it is advised that this node does not have a parent.\n * @param motionType - The motion type of the physics body. The options are:\n * - PhysicsMotionType.STATIC - Static bodies are not moving and unaffected by forces or collisions. They are good for level boundaries or terrain.\n * - PhysicsMotionType.DYNAMIC - Dynamic bodies are fully simulated. They can move and collide with other objects.\n * - PhysicsMotionType.ANIMATED - They behave like dynamic bodies, but they won't be affected by other bodies, but still push other bodies out of the way.\n * @param startsAsleep - Whether the physics body should start in a sleeping state (not a guarantee). Defaults to false.\n * @param scene - The scene containing the physics engine.\n *\n * This code is useful for creating a physics body for a given Transform Node in a scene.\n * It checks the version of the physics engine and the physics plugin, and initializes the body accordingly.\n * It also sets the node's rotation quaternion if it is not already set. Finally, it adds the body to the physics engine.\n */\n constructor(transformNode, motionType, startsAsleep, scene) {\n /**\n * V2 Physics plugin private data for single Transform\n */\n this._pluginData = undefined;\n /**\n * V2 Physics plugin private data for instances\n */\n this._pluginDataInstances = [];\n /**\n * If the collision callback is enabled\n */\n this._collisionCBEnabled = false;\n /**\n * Disable pre-step that consists in updating Physics Body from Transform Node Translation/Orientation.\n * True by default for maximum performance.\n */\n this.disablePreStep = true;\n if (!scene) {\n return;\n }\n const physicsEngine = scene.getPhysicsEngine();\n if (!physicsEngine) {\n throw new Error(\"No Physics Engine available.\");\n }\n this._physicsEngine = physicsEngine;\n if (physicsEngine.getPluginVersion() != 2) {\n throw new Error(\"Plugin version is incorrect. Expected version 2.\");\n }\n const physicsPlugin = physicsEngine.getPhysicsPlugin();\n if (!physicsPlugin) {\n throw new Error(\"No Physics Plugin available.\");\n }\n this._physicsPlugin = physicsPlugin;\n if (!transformNode.rotationQuaternion) {\n transformNode.rotationQuaternion = Quaternion.FromEulerAngles(transformNode.rotation.x, transformNode.rotation.y, transformNode.rotation.z);\n }\n this.startAsleep = startsAsleep;\n // instances?\n const m = transformNode;\n if (m.hasThinInstances) {\n this._physicsPlugin.initBodyInstances(this, motionType, m);\n }\n else {\n // single instance\n if (transformNode.parent) {\n // Force computation of world matrix so that the parent transforms are correctly reflected in absolutePosition/absoluteRotationQuaternion.\n transformNode.computeWorldMatrix(true);\n }\n this._physicsPlugin.initBody(this, motionType, transformNode.absolutePosition, transformNode.absoluteRotationQuaternion);\n }\n this.transformNode = transformNode;\n transformNode.physicsBody = this;\n physicsEngine.addBody(this);\n this._nodeDisposeObserver = transformNode.onDisposeObservable.add(() => {\n this.dispose();\n });\n }\n /**\n * Returns the string \"PhysicsBody\".\n * @returns \"PhysicsBody\"\n */\n getClassName() {\n return \"PhysicsBody\";\n }\n /**\n * Clone the PhysicsBody to a new body and assign it to the transformNode parameter\n * @param transformNode transformNode that will be used for the cloned PhysicsBody\n * @returns the newly cloned PhysicsBody\n */\n clone(transformNode) {\n const clonedBody = new PhysicsBody(transformNode, this.getMotionType(), this.startAsleep, this.transformNode.getScene());\n clonedBody.shape = this.shape;\n return clonedBody;\n }\n /**\n * If a physics body is connected to an instanced node, update the number physic instances to match the number of node instances.\n */\n updateBodyInstances() {\n const m = this.transformNode;\n if (m.hasThinInstances) {\n this._physicsPlugin.updateBodyInstances(this, m);\n }\n }\n /**\n * This returns the number of internal instances of the physics body\n */\n get numInstances() {\n return this._pluginDataInstances.length;\n }\n /**\n * Sets the shape of the physics body.\n * @param shape - The shape of the physics body.\n *\n * This method is useful for setting the shape of the physics body, which is necessary for the physics engine to accurately simulate the body's behavior.\n * The shape is used to calculate the body's mass, inertia, and other properties.\n */\n set shape(shape) {\n this._physicsPlugin.setShape(this, shape);\n }\n /**\n * Retrieves the physics shape associated with this object.\n *\n * @returns The physics shape associated with this object, or `undefined` if no\n * shape is associated.\n *\n * This method is useful for retrieving the physics shape associated with this object,\n * which can be used to apply physical forces to the object or to detect collisions.\n */\n get shape() {\n return this._physicsPlugin.getShape(this);\n }\n /**\n * Sets the event mask for the physics engine.\n *\n * @param eventMask - A bitmask that determines which events will be sent to the physics engine.\n *\n * This method is useful for setting the event mask for the physics engine, which determines which events\n * will be sent to the physics engine. This allows the user to control which events the physics engine will respond to.\n */\n setEventMask(eventMask, instanceIndex) {\n this._physicsPlugin.setEventMask(this, eventMask, instanceIndex);\n }\n /**\n * Gets the event mask of the physics engine.\n *\n * @returns The event mask of the physics engine.\n *\n * This method is useful for getting the event mask of the physics engine,\n * which is used to determine which events the engine will respond to.\n * This is important for ensuring that the engine is responding to the correct events and not\n * wasting resources on unnecessary events.\n */\n getEventMask(instanceIndex) {\n return this._physicsPlugin.getEventMask(this, instanceIndex);\n }\n /**\n * Sets the motion type of the physics body. Can be STATIC, DYNAMIC, or ANIMATED.\n */\n setMotionType(motionType, instanceIndex) {\n this._physicsPlugin.setMotionType(this, motionType, instanceIndex);\n }\n /**\n * Gets the motion type of the physics body. Can be STATIC, DYNAMIC, or ANIMATED.\n */\n getMotionType(instanceIndex) {\n return this._physicsPlugin.getMotionType(this, instanceIndex);\n }\n /**\n * Computes the mass properties of the physics object, based on the set of physics shapes this body uses.\n * This method is useful for computing the initial mass properties of a physics object, such as its mass,\n * inertia, and center of mass; these values are important for accurately simulating the physics of the\n * object in the physics engine, and computing values based on the shape will provide you with reasonable\n * intial values, which you can then customize.\n */\n computeMassProperties(instanceIndex) {\n return this._physicsPlugin.computeMassProperties(this, instanceIndex);\n }\n /**\n * Sets the mass properties of the physics object.\n *\n * @param massProps - The mass properties to set.\n * @param instanceIndex - The index of the instance to set the mass properties for. If not defined, the mass properties will be set for all instances.\n *\n * This method is useful for setting the mass properties of a physics object, such as its mass,\n * inertia, and center of mass. This is important for accurately simulating the physics of the object in the physics engine.\n */\n setMassProperties(massProps, instanceIndex) {\n this._physicsPlugin.setMassProperties(this, massProps, instanceIndex);\n }\n /**\n * Retrieves the mass properties of the object.\n *\n * @returns The mass properties of the object.\n *\n * This method is useful for physics simulations, as it allows the user to\n * retrieve the mass properties of the object, such as its mass, center of mass,\n * and moment of inertia. This information is necessary for accurate physics\n * simulations.\n */\n getMassProperties(instanceIndex) {\n return this._physicsPlugin.getMassProperties(this, instanceIndex);\n }\n /**\n * Sets the linear damping of the physics body.\n *\n * @param damping - The linear damping value.\n *\n * This method is useful for controlling the linear damping of the physics body,\n * which is the rate at which the body's velocity decreases over time. This is useful for simulating\n * the effects of air resistance or other forms of friction.\n */\n setLinearDamping(damping, instanceIndex) {\n this._physicsPlugin.setLinearDamping(this, damping, instanceIndex);\n }\n /**\n * Gets the linear damping of the physics body.\n * @returns The linear damping of the physics body.\n *\n * This method is useful for retrieving the linear damping of the physics body, which is the amount of\n * resistance the body has to linear motion. This is useful for simulating realistic physics behavior\n * in a game.\n */\n getLinearDamping(instanceIndex) {\n return this._physicsPlugin.getLinearDamping(this, instanceIndex);\n }\n /**\n * Sets the angular damping of the physics body.\n * @param damping The angular damping of the body.\n *\n * This method is useful for controlling the angular velocity of a physics body.\n * By setting the damping, the body's angular velocity will be reduced over time, simulating the effect of friction.\n * This can be used to create realistic physical behavior in a physics engine.\n */\n setAngularDamping(damping, instanceIndex) {\n this._physicsPlugin.setAngularDamping(this, damping, instanceIndex);\n }\n /**\n * Gets the angular damping of the physics body.\n *\n * @returns The angular damping of the physics body.\n *\n * This method is useful for getting the angular damping of the physics body,\n * which is the rate of reduction of the angular velocity over time.\n * This is important for simulating realistic physics behavior in a game.\n */\n getAngularDamping(instanceIndex) {\n return this._physicsPlugin.getAngularDamping(this, instanceIndex);\n }\n /**\n * Sets the linear velocity of the physics object.\n * @param linVel - The linear velocity to set.\n *\n * This method is useful for setting the linear velocity of a physics object,\n * which is necessary for simulating realistic physics in a game engine.\n * By setting the linear velocity, the physics object will move in the direction and speed specified by the vector.\n * This allows for realistic physics simulations, such as simulating the motion of a ball rolling down a hill.\n */\n setLinearVelocity(linVel, instanceIndex) {\n this._physicsPlugin.setLinearVelocity(this, linVel, instanceIndex);\n }\n /**\n * Gets the linear velocity of the physics body and stores it in the given vector3.\n * @param linVel - The vector3 to store the linear velocity in.\n *\n * This method is useful for getting the linear velocity of a physics body in a physics engine.\n * This can be used to determine the speed and direction of the body, which can be used to calculate the motion of the body.*/\n getLinearVelocityToRef(linVel, instanceIndex) {\n return this._physicsPlugin.getLinearVelocityToRef(this, linVel, instanceIndex);\n }\n /**\n * Sets the angular velocity of the physics object.\n * @param angVel - The angular velocity to set.\n *\n * This method is useful for setting the angular velocity of a physics object, which is necessary for\n * simulating realistic physics behavior. The angular velocity is used to determine the rate of rotation of the object,\n * which is important for simulating realistic motion.\n */\n setAngularVelocity(angVel, instanceIndex) {\n this._physicsPlugin.setAngularVelocity(this, angVel, instanceIndex);\n }\n /**\n * Gets the angular velocity of the physics body and stores it in the given vector3.\n * @param angVel - The vector3 to store the angular velocity in.\n *\n * This method is useful for getting the angular velocity of a physics body, which can be used to determine the body's\n * rotational speed. This information can be used to create realistic physics simulations.\n */\n getAngularVelocityToRef(angVel, instanceIndex) {\n return this._physicsPlugin.getAngularVelocityToRef(this, angVel, instanceIndex);\n }\n /**\n * Applies an impulse to the physics object.\n *\n * @param impulse The impulse vector.\n * @param location The location of the impulse.\n * @param instanceIndex For a instanced body, the instance to where the impulse should be applied. If not specified, the impulse is applied to all instances.\n *\n * This method is useful for applying an impulse to a physics object, which can be used to simulate physical forces such as gravity,\n * collisions, and explosions. This can be used to create realistic physics simulations in a game or other application.\n */\n applyImpulse(impulse, location, instanceIndex) {\n this._physicsPlugin.applyImpulse(this, impulse, location, instanceIndex);\n }\n /**\n * Applies a force to the physics object.\n *\n * @param force The force vector.\n * @param location The location of the force.\n * @param instanceIndex For a instanced body, the instance to where the force should be applied. If not specified, the force is applied to all instances.\n *\n * This method is useful for applying a force to a physics object, which can be used to simulate physical forces such as gravity,\n * collisions, and explosions. This can be used to create realistic physics simulations in a game or other application.\n */\n applyForce(force, location, instanceIndex) {\n this._physicsPlugin.applyForce(this, force, location, instanceIndex);\n }\n /**\n * Retrieves the geometry of the body from the physics plugin.\n *\n * @returns The geometry of the body.\n *\n * This method is useful for retrieving the geometry of the body from the physics plugin, which can be used for various physics calculations.\n */\n getGeometry() {\n return this._physicsPlugin.getBodyGeometry(this);\n }\n /**\n * Returns an observable that will be notified for all collisions happening for event-enabled bodies\n * @returns Observable\n */\n getCollisionObservable() {\n return this._physicsPlugin.getCollisionObservable(this);\n }\n /**\n * Enable or disable collision callback for this PhysicsBody.\n * @param enabled true if PhysicsBody's collision will rise a collision event and notifies the observable\n */\n setCollisionCallbackEnabled(enabled) {\n this._collisionCBEnabled = enabled;\n this._physicsPlugin.setCollisionCallbackEnabled(this, enabled);\n }\n /*\n * Get the center of the object in world space.\n * @param instanceIndex - If this body is instanced, the index of the instance to get the center for.\n * @returns geometric center of the associated mesh\n */\n getObjectCenterWorld(instanceIndex) {\n const ref = new Vector3();\n return this.getObjectCenterWorldToRef(ref, instanceIndex);\n }\n /*\n * Get the center of the object in world space.\n * @param ref - The vector3 to store the result in.\n * @param instanceIndex - If this body is instanced, the index of the instance to get the center for.\n * @returns geometric center of the associated mesh\n */\n getObjectCenterWorldToRef(ref, instanceIndex) {\n var _a;\n if (((_a = this._pluginDataInstances) === null || _a === void 0 ? void 0 : _a.length) > 0) {\n const index = instanceIndex || 0;\n const matrixData = this.transformNode._thinInstanceDataStorage.matrixData;\n if (matrixData) {\n ref.set(matrixData[index * 16 + 12], matrixData[index * 16 + 13], matrixData[index * 16 + 14]);\n }\n }\n else {\n ref.copyFrom(this.transformNode.position);\n }\n return ref;\n }\n /**\n * Adds a constraint to the physics engine.\n *\n * @param childBody - The body to which the constraint will be applied.\n * @param constraint - The constraint to be applied.\n * @param instanceIndex - If this body is instanced, the index of the instance to which the constraint will be applied. If not specified, no constraint will be applied.\n * @param childInstanceIndex - If the child body is instanced, the index of the instance to which the constraint will be applied. If not specified, no constraint will be applied.\n *\n */\n addConstraint(childBody, constraint, instanceIndex, childInstanceIndex) {\n this._physicsPlugin.addConstraint(this, childBody, constraint, instanceIndex, childInstanceIndex);\n }\n /**\n * Sync with a bone\n * @param bone The bone that the impostor will be synced to.\n * @param boneMesh The mesh that the bone is influencing.\n * @param jointPivot The pivot of the joint / bone in local space.\n * @param distToJoint Optional distance from the impostor to the joint.\n * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.\n * @param boneAxis Optional vector3 axis the bone is aligned with\n */\n syncWithBone(bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {\n const mesh = this.transformNode;\n if (mesh.rotationQuaternion) {\n if (adjustRotation) {\n const tempQuat = TmpVectors.Quaternion[0];\n bone.getRotationQuaternionToRef(Space.WORLD, boneMesh, tempQuat);\n tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);\n }\n else {\n bone.getRotationQuaternionToRef(Space.WORLD, boneMesh, mesh.rotationQuaternion);\n }\n }\n const pos = TmpVectors.Vector3[0];\n const boneDir = TmpVectors.Vector3[1];\n if (!boneAxis) {\n boneAxis = TmpVectors.Vector3[2];\n boneAxis.x = 0;\n boneAxis.y = 1;\n boneAxis.z = 0;\n }\n bone.getDirectionToRef(boneAxis, boneMesh, boneDir);\n bone.getAbsolutePositionToRef(boneMesh, pos);\n if ((distToJoint === undefined || distToJoint === null) && jointPivot) {\n distToJoint = jointPivot.length();\n }\n if (distToJoint !== undefined && distToJoint !== null) {\n pos.x += boneDir.x * distToJoint;\n pos.y += boneDir.y * distToJoint;\n pos.z += boneDir.z * distToJoint;\n }\n mesh.setAbsolutePosition(pos);\n }\n /**\n * Executes a callback on the body or all of the instances of a body\n * @param callback the callback to execute\n */\n iterateOverAllInstances(callback) {\n var _a;\n if (((_a = this._pluginDataInstances) === null || _a === void 0 ? void 0 : _a.length) > 0) {\n for (let i = 0; i < this._pluginDataInstances.length; i++) {\n callback(this, i);\n }\n }\n else {\n callback(this, undefined);\n }\n }\n /**\n * Sets the gravity factor of the physics body\n * @param factor the gravity factor to set\n * @param instanceIndex the instance of the body to set, if undefined all instances will be set\n */\n setGravityFactor(factor, instanceIndex) {\n this._physicsPlugin.setGravityFactor(this, factor, instanceIndex);\n }\n /**\n * Gets the gravity factor of the physics body\n * @param instanceIndex the instance of the body to get, if undefined the value of first instance will be returned\n * @returns the gravity factor\n */\n getGravityFactor(instanceIndex) {\n return this._physicsPlugin.getGravityFactor(this, instanceIndex);\n }\n /**\n * Disposes the body from the physics engine.\n *\n * This method is useful for cleaning up the physics engine when a body is no longer needed. Disposing the body will free up resources and prevent memory leaks.\n */\n dispose() {\n // Disable collisions CB so it doesn't fire when the body is disposed\n if (this._collisionCBEnabled) {\n this.setCollisionCallbackEnabled(false);\n }\n if (this._nodeDisposeObserver) {\n this.transformNode.onDisposeObservable.remove(this._nodeDisposeObserver);\n this._nodeDisposeObserver = null;\n }\n this._physicsEngine.removeBody(this);\n this._physicsPlugin.removeBody(this);\n this._physicsPlugin.disposeBody(this);\n this._pluginData = null;\n this._pluginDataInstances.length = 0;\n }\n}\n//# sourceMappingURL=physicsBody.js.map","/** How a specific axis can be constrained */\nexport var PhysicsConstraintAxisLimitMode;\n(function (PhysicsConstraintAxisLimitMode) {\n /*\n * The axis is not restricted at all\n */\n PhysicsConstraintAxisLimitMode[PhysicsConstraintAxisLimitMode[\"FREE\"] = 0] = \"FREE\";\n /*\n * The axis has a minimum/maximum limit\n */\n PhysicsConstraintAxisLimitMode[PhysicsConstraintAxisLimitMode[\"LIMITED\"] = 1] = \"LIMITED\";\n /*\n * The axis allows no relative movement of the pivots\n */\n PhysicsConstraintAxisLimitMode[PhysicsConstraintAxisLimitMode[\"LOCKED\"] = 2] = \"LOCKED\";\n})(PhysicsConstraintAxisLimitMode || (PhysicsConstraintAxisLimitMode = {}));\n/** The constraint specific axis to use when setting Friction, `ConstraintAxisLimitMode`, max force, ... */\nexport var PhysicsConstraintAxis;\n(function (PhysicsConstraintAxis) {\n /*\n * Translation along the primary axis of the constraint (i.e. the\n * direction specified by PhysicsConstraintParameters.axisA/axisB)\n */\n PhysicsConstraintAxis[PhysicsConstraintAxis[\"LINEAR_X\"] = 0] = \"LINEAR_X\";\n /*\n * Translation along the second axis of the constraint (i.e. the\n * direction specified by PhysicsConstraintParameters.perpAxisA/perpAxisB)\n */\n PhysicsConstraintAxis[PhysicsConstraintAxis[\"LINEAR_Y\"] = 1] = \"LINEAR_Y\";\n /*\n * Translation along the third axis of the constraint. This axis is\n * computed from the cross product of axisA/axisB and perpAxisA/perpAxisB)\n */\n PhysicsConstraintAxis[PhysicsConstraintAxis[\"LINEAR_Z\"] = 2] = \"LINEAR_Z\";\n /*\n * Rotation around the primary axis of the constraint (i.e. the\n * axis specified by PhysicsConstraintParameters.axisA/axisB)\n */\n PhysicsConstraintAxis[PhysicsConstraintAxis[\"ANGULAR_X\"] = 3] = \"ANGULAR_X\";\n /*\n * Rotation around the second axis of the constraint (i.e. the\n * axis specified by PhysicsConstraintParameters.perpAxisA/perpAxisB)\n */\n PhysicsConstraintAxis[PhysicsConstraintAxis[\"ANGULAR_Y\"] = 4] = \"ANGULAR_Y\";\n /*\n * Rotation around the third axis of the constraint. This axis is\n * computed from the cross product of axisA/axisB and perpAxisA/perpAxisB)\n */\n PhysicsConstraintAxis[PhysicsConstraintAxis[\"ANGULAR_Z\"] = 5] = \"ANGULAR_Z\";\n /*\n * A 3D distance limit; similar to specifying the LINEAR_X/Y/Z axes\n * individually, but the distance calculation uses all three axes\n * simultaneously, instead of individually.\n */\n PhysicsConstraintAxis[PhysicsConstraintAxis[\"LINEAR_DISTANCE\"] = 6] = \"LINEAR_DISTANCE\";\n})(PhysicsConstraintAxis || (PhysicsConstraintAxis = {}));\n/** Type of Constraint */\nexport var PhysicsConstraintType;\n(function (PhysicsConstraintType) {\n /**\n * A ball and socket constraint will attempt to line up the pivot\n * positions in each body, and have no restrictions on rotation\n */\n PhysicsConstraintType[PhysicsConstraintType[\"BALL_AND_SOCKET\"] = 1] = \"BALL_AND_SOCKET\";\n /**\n * A distance constraint will attempt to keep the pivot locations\n * within a specified distance.\n */\n PhysicsConstraintType[PhysicsConstraintType[\"DISTANCE\"] = 2] = \"DISTANCE\";\n /**\n * A hinge constraint will keep the pivot positions aligned as well\n * as two angular axes. The remaining angular axis will be free to rotate.\n */\n PhysicsConstraintType[PhysicsConstraintType[\"HINGE\"] = 3] = \"HINGE\";\n /**\n * A slider constraint allows bodies to translate along one axis and\n * rotate about the same axis. The remaining two axes are locked in\n * place\n */\n PhysicsConstraintType[PhysicsConstraintType[\"SLIDER\"] = 4] = \"SLIDER\";\n /**\n * A lock constraint will attempt to keep the pivots completely lined\n * up between both bodies, allowing no relative movement.\n */\n PhysicsConstraintType[PhysicsConstraintType[\"LOCK\"] = 5] = \"LOCK\";\n /*\n * A prismatic will lock the rotations of the bodies, and allow translation\n * only along one axis\n */\n PhysicsConstraintType[PhysicsConstraintType[\"PRISMATIC\"] = 6] = \"PRISMATIC\";\n /*\n * A generic constraint; this starts with no limits on how the bodies can\n * move relative to each other, but limits can be added via the PhysicsConstraint\n * interfaces. This can be used to specify a large variety of constraints\n */\n PhysicsConstraintType[PhysicsConstraintType[\"SIX_DOF\"] = 7] = \"SIX_DOF\";\n})(PhysicsConstraintType || (PhysicsConstraintType = {}));\n/** Type of Shape */\nexport var PhysicsShapeType;\n(function (PhysicsShapeType) {\n PhysicsShapeType[PhysicsShapeType[\"SPHERE\"] = 0] = \"SPHERE\";\n PhysicsShapeType[PhysicsShapeType[\"CAPSULE\"] = 1] = \"CAPSULE\";\n PhysicsShapeType[PhysicsShapeType[\"CYLINDER\"] = 2] = \"CYLINDER\";\n PhysicsShapeType[PhysicsShapeType[\"BOX\"] = 3] = \"BOX\";\n PhysicsShapeType[PhysicsShapeType[\"CONVEX_HULL\"] = 4] = \"CONVEX_HULL\";\n PhysicsShapeType[PhysicsShapeType[\"CONTAINER\"] = 5] = \"CONTAINER\";\n PhysicsShapeType[PhysicsShapeType[\"MESH\"] = 6] = \"MESH\";\n PhysicsShapeType[PhysicsShapeType[\"HEIGHTFIELD\"] = 7] = \"HEIGHTFIELD\";\n})(PhysicsShapeType || (PhysicsShapeType = {}));\n/** Optional motor which attempts to move a body at a specific velocity, or at a specific position */\nexport var PhysicsConstraintMotorType;\n(function (PhysicsConstraintMotorType) {\n PhysicsConstraintMotorType[PhysicsConstraintMotorType[\"NONE\"] = 0] = \"NONE\";\n PhysicsConstraintMotorType[PhysicsConstraintMotorType[\"VELOCITY\"] = 1] = \"VELOCITY\";\n PhysicsConstraintMotorType[PhysicsConstraintMotorType[\"POSITION\"] = 2] = \"POSITION\";\n})(PhysicsConstraintMotorType || (PhysicsConstraintMotorType = {}));\n/**\n * Indicates how the body will behave.\n */\nexport var PhysicsMotionType;\n(function (PhysicsMotionType) {\n PhysicsMotionType[PhysicsMotionType[\"STATIC\"] = 0] = \"STATIC\";\n PhysicsMotionType[PhysicsMotionType[\"ANIMATED\"] = 1] = \"ANIMATED\";\n PhysicsMotionType[PhysicsMotionType[\"DYNAMIC\"] = 2] = \"DYNAMIC\";\n})(PhysicsMotionType || (PhysicsMotionType = {}));\n//# sourceMappingURL=IPhysicsEnginePlugin.js.map","import { PhysicsShapeType } from \"./IPhysicsEnginePlugin.js\";\nimport { Matrix, Vector3, Quaternion, TmpVectors } from \"../../Maths/math.vector.js\";\n/**\n * PhysicsShape class.\n * This class is useful for creating a physics shape that can be used in a physics engine.\n * A Physic Shape determine how collision are computed. It must be attached to a body.\n */\nexport class PhysicsShape {\n /**\n * Constructs a new physics shape.\n * @param options The options for the physics shape. These are:\n * * type: The type of the shape. This can be one of the following: SPHERE, BOX, CAPSULE, CYLINDER, CONVEX_HULL, MESH, HEIGHTFIELD, CONTAINER\n * * parameters: The parameters of the shape.\n * * pluginData: The plugin data of the shape. This is used if you already have a reference to the object on the plugin side.\n * You need to specify either type or pluginData.\n * @param scene The scene the shape belongs to.\n *\n * This code is useful for creating a new physics shape with the given type, options, and scene.\n * It also checks that the physics engine and plugin version are correct.\n * If not, it throws an error. This ensures that the shape is created with the correct parameters and is compatible with the physics engine.\n */\n constructor(options, scene) {\n var _a;\n /**\n * V2 Physics plugin private data for single shape\n */\n this._pluginData = undefined;\n if (!scene) {\n return;\n }\n const physicsEngine = scene.getPhysicsEngine();\n if (!physicsEngine) {\n throw new Error(\"No Physics Engine available.\");\n }\n if (physicsEngine.getPluginVersion() != 2) {\n throw new Error(\"Plugin version is incorrect. Expected version 2.\");\n }\n const physicsPlugin = physicsEngine.getPhysicsPlugin();\n if (!physicsPlugin) {\n throw new Error(\"No Physics Plugin available.\");\n }\n this._physicsPlugin = physicsPlugin;\n if (options.pluginData !== undefined && options.pluginData !== null) {\n this._pluginData = options.pluginData;\n this._type = this._physicsPlugin.getShapeType(this);\n }\n else if (options.type !== undefined && options.type !== null) {\n this._type = options.type;\n const parameters = (_a = options.parameters) !== null && _a !== void 0 ? _a : {};\n this._physicsPlugin.initShape(this, options.type, parameters);\n }\n }\n /**\n * Returns the string \"PhysicsShape\".\n * @returns \"PhysicsShape\"\n */\n getClassName() {\n return \"PhysicsShape\";\n }\n /**\n *\n */\n get type() {\n return this._type;\n }\n /**\n * Set the membership mask of a shape. This is a bitfield of arbitrary\n * \"categories\" to which the shape is a member. This is used in combination\n * with the collide mask to determine if this shape should collide with\n * another.\n *\n * @param membershipMask Bitfield of categories of this shape.\n */\n set filterMembershipMask(membershipMask) {\n this._physicsPlugin.setShapeFilterMembershipMask(this, membershipMask);\n }\n /**\n * Get the membership mask of a shape.\n * @returns Bitmask of categories which this shape is a member of.\n */\n get filterMembershipMask() {\n return this._physicsPlugin.getShapeFilterMembershipMask(this);\n }\n /**\n * Sets the collide mask of a shape. This is a bitfield of arbitrary\n * \"categories\" to which this shape collides with. Given two shapes,\n * the engine will check if the collide mask and membership overlap:\n * shapeA.filterMembershipMask & shapeB.filterCollideMask\n *\n * If this value is zero (i.e. shapeB only collides with categories\n * which shapeA is _not_ a member of) then the shapes will not collide.\n *\n * Note, the engine will also perform the same test with shapeA and\n * shapeB swapped; the shapes will not collide if either shape has\n * a collideMask which prevents collision with the other shape.\n *\n * @param collideMask Bitmask of categories this shape should collide with\n */\n set filterCollideMask(collideMask) {\n this._physicsPlugin.setShapeFilterCollideMask(this, collideMask);\n }\n /**\n *\n * @returns Bitmask of categories that this shape should collide with\n */\n get filterCollideMask() {\n return this._physicsPlugin.getShapeFilterCollideMask(this);\n }\n /**\n *\n * @param material\n */\n set material(material) {\n this._physicsPlugin.setMaterial(this, material);\n this._material = material;\n }\n /**\n *\n * @returns\n */\n get material() {\n return this._material;\n }\n /**\n *\n * @param density\n */\n set density(density) {\n this._physicsPlugin.setDensity(this, density);\n }\n /**\n *\n */\n get density() {\n return this._physicsPlugin.getDensity(this);\n }\n /**\n * Utility to add a child shape to this container,\n * automatically computing the relative transform between\n * the container shape and the child instance.\n *\n * @param parentTransform The transform node associated with this shape\n * @param newChild The new PhysicsShape to add\n * @param childTransform The transform node associated with the child shape\n */\n addChildFromParent(parentTransform, newChild, childTransform) {\n const childToWorld = childTransform.computeWorldMatrix(true);\n const parentToWorld = parentTransform.computeWorldMatrix(true);\n const childToParent = TmpVectors.Matrix[0];\n childToWorld.multiplyToRef(Matrix.Invert(parentToWorld), childToParent);\n const translation = TmpVectors.Vector3[0];\n const rotation = TmpVectors.Quaternion[0];\n const scale = TmpVectors.Vector3[1];\n childToParent.decompose(scale, rotation, translation);\n this._physicsPlugin.addChild(this, newChild, translation, rotation, scale);\n }\n /**\n * Adds a child shape to a container with an optional transform\n * @param newChild The new PhysicsShape to add\n * @param translation Optional position of the child shape relative to this shape\n * @param rotation Optional rotation of the child shape relative to this shape\n * @param scale Optional scale of the child shape relative to this shape\n */\n addChild(newChild, translation, rotation, scale) {\n this._physicsPlugin.addChild(this, newChild, translation, rotation, scale);\n }\n /**\n *\n * @param childIndex\n */\n removeChild(childIndex) {\n this._physicsPlugin.removeChild(this, childIndex);\n }\n /**\n *\n * @returns\n */\n getNumChildren() {\n return this._physicsPlugin.getNumChildren(this);\n }\n /**\n *\n */\n getBoundingBox() {\n return this._physicsPlugin.getBoundingBox(this);\n }\n /**\n *\n */\n dispose() {\n this._physicsPlugin.disposeShape(this);\n }\n}\n/**\n * Helper object to create a sphere shape\n */\nexport class PhysicsShapeSphere extends PhysicsShape {\n /**\n * Constructor for the Sphere Shape\n * @param center local center of the sphere\n * @param radius radius\n * @param scene scene to attach to\n */\n constructor(center, radius, scene) {\n super({ type: PhysicsShapeType.SPHERE, parameters: { center: center, radius: radius } }, scene);\n }\n /**\n *\n * @param mesh\n * @returns PhysicsShapeSphere\n */\n static FromMesh(mesh) {\n const bounds = mesh.getBoundingInfo();\n const centerLocal = bounds.boundingSphere.center;\n const he = bounds.boundingBox.extendSize;\n const radius = Math.max(he.x, he.y, he.z);\n return new PhysicsShapeSphere(centerLocal, radius, mesh.getScene());\n }\n}\n/**\n * Helper object to create a capsule shape\n */\nexport class PhysicsShapeCapsule extends PhysicsShape {\n /**\n *\n * @param pointA Starting point that defines the capsule segment\n * @param pointB ending point of that same segment\n * @param radius radius\n * @param scene scene to attach to\n */\n constructor(pointA, pointB, radius, scene) {\n super({ type: PhysicsShapeType.CAPSULE, parameters: { pointA: pointA, pointB: pointB, radius: radius } }, scene);\n }\n /**\n * Derive an approximate capsule from the transform node. Note, this is\n * not the optimal bounding capsule.\n * @param TransformNode node Node from which to derive a cylinder shape\n */\n static FromMesh(mesh) {\n const boundsLocal = mesh.getBoundingInfo();\n const radius = boundsLocal.boundingBox.extendSize.x;\n const pointFromCenter = new Vector3(0, boundsLocal.boundingBox.extendSize.y - radius, 0);\n const pointA = boundsLocal.boundingBox.center.add(pointFromCenter);\n const pointB = boundsLocal.boundingBox.center.subtract(pointFromCenter);\n return new PhysicsShapeCapsule(pointA, pointB, radius, mesh.getScene());\n }\n}\n/**\n * Helper object to create a cylinder shape\n */\nexport class PhysicsShapeCylinder extends PhysicsShape {\n /**\n *\n * @param pointA Starting point that defines the cylinder segment\n * @param pointB ending point of that same segment\n * @param radius radius\n * @param scene scene to attach to\n */\n constructor(pointA, pointB, radius, scene) {\n super({ type: PhysicsShapeType.CYLINDER, parameters: { pointA: pointA, pointB: pointB, radius: radius } }, scene);\n }\n /**\n * Derive an approximate cylinder from the transform node. Note, this is\n * not the optimal bounding cylinder.\n * @param TransformNode node Node from which to derive a cylinder shape\n */\n static FromMesh(mesh) {\n const boundsLocal = mesh.getBoundingInfo();\n const radius = boundsLocal.boundingBox.extendSize.x;\n const pointFromCenter = new Vector3(0, boundsLocal.boundingBox.extendSize.y, 0);\n const pointA = boundsLocal.boundingBox.center.add(pointFromCenter);\n const pointB = boundsLocal.boundingBox.center.subtract(pointFromCenter);\n return new PhysicsShapeCylinder(pointA, pointB, radius, mesh.getScene());\n }\n}\n/**\n * Helper object to create a box shape\n */\nexport class PhysicsShapeBox extends PhysicsShape {\n /**\n *\n * @param center local center of the sphere\n * @param rotation local orientation\n * @param extents size of the box in each direction\n * @param scene scene to attach to\n */\n constructor(center, rotation, extents, scene) {\n super({ type: PhysicsShapeType.BOX, parameters: { center: center, rotation: rotation, extents: extents } }, scene);\n }\n /**\n *\n * @param mesh\n * @returns PhysicsShapeBox\n */\n static FromMesh(mesh) {\n const bounds = mesh.getBoundingInfo();\n const centerLocal = bounds.boundingBox.center;\n const extents = bounds.boundingBox.extendSize.scale(2.0); // {\n this.dispose();\n });\n }\n _getObjectBoundingBox() {\n if (this.transformNode.getRawBoundingInfo) {\n return this.transformNode.getRawBoundingInfo().boundingBox;\n }\n else {\n return new BoundingBox(new Vector3(-0.5, -0.5, -0.5), new Vector3(0.5, 0.5, 0.5));\n }\n }\n _hasVertices(node) {\n return (node === null || node === void 0 ? void 0 : node.getTotalVertices()) > 0;\n }\n _addSizeOptions() {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n this.transformNode.computeWorldMatrix(true);\n const bb = this._getObjectBoundingBox();\n const extents = TmpVectors.Vector3[0];\n extents.copyFrom(bb.extendSize);\n extents.scaleInPlace(2);\n extents.multiplyInPlace(this.transformNode.scaling);\n const min = TmpVectors.Vector3[1];\n min.copyFrom(bb.minimum);\n min.multiplyInPlace(this.transformNode.scaling);\n if (!this._options.center) {\n const center = new Vector3();\n center.copyFrom(bb.center);\n center.multiplyInPlace(this.transformNode.scaling);\n this._options.center = center;\n }\n switch (this.type) {\n case PhysicsShapeType.SPHERE:\n if (!this._options.radius && Scalar.WithinEpsilon(extents.x, extents.y, 0.0001) && Scalar.WithinEpsilon(extents.x, extents.z, 0.0001)) {\n this._options.radius = extents.x / 2;\n }\n else if (!this._options.radius) {\n Logger.Warn(\"Non uniform scaling is unsupported for sphere shapes. Setting the radius to the biggest bounding box extent.\");\n this._options.radius = Math.max(extents.x, extents.y, extents.z) / 2;\n }\n break;\n case PhysicsShapeType.CAPSULE:\n {\n const capRadius = extents.x / 2;\n this._options.radius = (_a = this._options.radius) !== null && _a !== void 0 ? _a : capRadius;\n this._options.pointA = (_b = this._options.pointA) !== null && _b !== void 0 ? _b : new Vector3(0, min.y + capRadius, 0);\n this._options.pointB = (_c = this._options.pointB) !== null && _c !== void 0 ? _c : new Vector3(0, min.y + extents.y - capRadius, 0);\n }\n break;\n case PhysicsShapeType.CYLINDER:\n {\n const capRadius = extents.x / 2;\n this._options.radius = (_d = this._options.radius) !== null && _d !== void 0 ? _d : capRadius;\n this._options.pointA = (_e = this._options.pointA) !== null && _e !== void 0 ? _e : new Vector3(0, min.y, 0);\n this._options.pointB = (_f = this._options.pointB) !== null && _f !== void 0 ? _f : new Vector3(0, min.y + extents.y, 0);\n }\n break;\n case PhysicsShapeType.MESH:\n case PhysicsShapeType.CONVEX_HULL:\n if (!this._options.mesh && this._hasVertices(this.transformNode)) {\n this._options.mesh = this.transformNode;\n }\n else if (!this._options.mesh || !this._hasVertices(this._options.mesh)) {\n throw new Error(\"No valid mesh was provided for mesh or convex hull shape parameter. Please provide a mesh with valid geometry (number of vertices greater than 0).\");\n }\n break;\n case PhysicsShapeType.BOX:\n this._options.extents = (_g = this._options.extents) !== null && _g !== void 0 ? _g : new Vector3(extents.x, extents.y, extents.z);\n this._options.rotation = (_h = this._options.rotation) !== null && _h !== void 0 ? _h : Quaternion.Identity();\n break;\n }\n }\n /**\n * Releases the body, shape and material\n */\n dispose() {\n if (this._nodeDisposeObserver) {\n this.body.transformNode.onDisposeObservable.remove(this._nodeDisposeObserver);\n this._nodeDisposeObserver = null;\n }\n this.body.dispose();\n if (this._disposeShapeWhenDisposed) {\n this.shape.dispose();\n }\n }\n}\n//# sourceMappingURL=physicsAggregate.js.map","import { Matrix, Quaternion, TmpVectors, Vector3 } from \"../../../Maths/math.vector.js\";\nimport { PhysicsShapeType, PhysicsConstraintType, PhysicsMotionType, PhysicsConstraintMotorType, PhysicsConstraintAxis, PhysicsConstraintAxisLimitMode, } from \"../IPhysicsEnginePlugin.js\";\nimport { Logger } from \"../../../Misc/logger.js\";\nimport { PhysicsMaterialCombineMode } from \"../physicsMaterial.js\";\nimport { PhysicsShape } from \"../physicsShape.js\";\nimport { Mesh } from \"../../../Meshes/mesh.js\";\nimport { VertexBuffer } from \"../../../Buffers/buffer.js\";\nimport { ArrayTools } from \"../../../Misc/arrayTools.js\";\nimport { Observable } from \"../../../Misc/observable.js\";\nclass MeshAccumulator {\n /**\n * Constructor of the mesh accumulator\n * @param mesh - The mesh used to compute the world matrix.\n * @param collectIndices - use mesh indices\n * @param scene - The scene used to determine the right handed system.\n *\n * Merge mesh and its children so whole hierarchy can be used as a mesh shape or convex hull\n */\n constructor(mesh, collectIndices, scene) {\n this._vertices = []; /// Vertices in body space\n this._indices = [];\n this._isRightHanded = scene.useRightHandedSystem;\n this._collectIndices = collectIndices;\n }\n /**\n * Adds a mesh to the physics engine.\n * @param mesh The mesh to add.\n * @param includeChildren Whether to include the children of the mesh.\n *\n * This method adds a mesh to the physics engine by computing the world matrix,\n * multiplying it with the body from world matrix, and then transforming the\n * coordinates of the mesh's vertices. It also adds the indices of the mesh\n * to the physics engine. If includeChildren is true, it will also add the\n * children of the mesh to the physics engine, ignoring any children which\n * have a physics impostor. This is useful for creating a physics engine\n * that accurately reflects the mesh and its children.\n */\n addMesh(mesh, includeChildren) {\n const indexOffset = this._vertices.length;\n // Force absoluteScaling to be computed\n mesh.computeWorldMatrix(true);\n const shapeFromBody = TmpVectors.Matrix[0];\n Matrix.ScalingToRef(mesh.absoluteScaling.x, mesh.absoluteScaling.y, mesh.absoluteScaling.z, shapeFromBody);\n const vertexData = mesh.getVerticesData(VertexBuffer.PositionKind) || [];\n const numVerts = vertexData.length / 3;\n for (let v = 0; v < numVerts; v++) {\n const pos = new Vector3(vertexData[v * 3 + 0], vertexData[v * 3 + 1], vertexData[v * 3 + 2]);\n this._vertices.push(Vector3.TransformCoordinates(pos, shapeFromBody));\n }\n if (this._collectIndices) {\n const meshIndices = mesh.getIndices();\n if (meshIndices) {\n for (let i = 0; i < meshIndices.length; i += 3) {\n // Havok wants the correct triangle winding to enable the interior triangle optimization\n if (this._isRightHanded) {\n this._indices.push(meshIndices[i + 0] + indexOffset);\n this._indices.push(meshIndices[i + 1] + indexOffset);\n this._indices.push(meshIndices[i + 2] + indexOffset);\n }\n else {\n this._indices.push(meshIndices[i + 2] + indexOffset);\n this._indices.push(meshIndices[i + 1] + indexOffset);\n this._indices.push(meshIndices[i + 0] + indexOffset);\n }\n }\n }\n }\n if (includeChildren) {\n const children = mesh.getChildMeshes(false);\n // Ignore any children which have a physics body.\n // Other plugin implementations do not have this check, which appears to be\n // a bug, as otherwise, the mesh will have a duplicate collider\n children.filter((m) => !m.physicsBody).forEach((m) => this.addMesh(m, includeChildren));\n }\n }\n /**\n * Allocate and populate the vertex positions inside the physics plugin.\n *\n * @returns An array of floats, whose backing memory is inside the plugin. The array contains the\n * positions of the mesh vertices, where a position is defined by three floats. You must call\n * freeBuffer() on the returned array once you have finished with it, in order to free the\n * memory inside the plugin..\n */\n getVertices(plugin) {\n const nFloats = this._vertices.length * 3;\n const bytesPerFloat = 4;\n const nBytes = nFloats * bytesPerFloat;\n const bufferBegin = plugin._malloc(nBytes);\n const ret = new Float32Array(plugin.HEAPU8.buffer, bufferBegin, nFloats);\n for (let i = 0; i < this._vertices.length; i++) {\n ret[i * 3 + 0] = this._vertices[i].x;\n ret[i * 3 + 1] = this._vertices[i].y;\n ret[i * 3 + 2] = this._vertices[i].z;\n }\n return ret;\n }\n freeBuffer(plugin, arr) {\n plugin._free(arr.byteOffset);\n }\n /**\n * Allocate and populate the triangle indices inside the physics plugin\n *\n * @returns A new Int32Array, whose backing memory is inside the plugin. The array contains the indices\n * of the triangle positions, where a single triangle is defined by three indices. You must call\n * freeBuffer() on this array once you have finished with it, to free the memory inside the plugin..\n */\n getTriangles(plugin) {\n const bytesPerInt = 4;\n const nBytes = this._indices.length * bytesPerInt;\n const bufferBegin = plugin._malloc(nBytes);\n const ret = new Int32Array(plugin.HEAPU8.buffer, bufferBegin, this._indices.length);\n for (let i = 0; i < this._indices.length; i++) {\n ret[i] = this._indices[i];\n }\n return ret;\n }\n}\nclass BodyPluginData {\n constructor(bodyId) {\n this.hpBodyId = bodyId;\n this.userMassProps = { centerOfMass: undefined, mass: undefined, inertia: undefined, inertiaOrientation: undefined };\n }\n}\n/*\nclass ShapePath\n{\n public colliderId: number;\n public pathData: number;\n}\n*/\nclass ContactPoint {\n constructor() {\n this.bodyId = BigInt(0); //0,2\n //public colliderId: number = 0; //2,4\n //public shapePath: ShapePath = new ShapePath(); //4,8\n this.position = new Vector3(); //8,11\n this.normal = new Vector3(); //11,14\n //public triIdx: number = 0; //14,15\n }\n}\nclass CollisionEvent {\n constructor() {\n //public eventType: number = 0; //0,1\n this.contactOnA = new ContactPoint(); //1\n this.contactOnB = new ContactPoint();\n this.impulseApplied = 0;\n }\n static readToRef(buffer, offset, eventOut) {\n const intBuf = new Int32Array(buffer, offset);\n const floatBuf = new Float32Array(buffer, offset);\n const offA = 2;\n eventOut.contactOnA.bodyId = BigInt(intBuf[offA]); // 0) {\n for (const instance of body._pluginDataInstances) {\n this._bodyCollisionObservable.delete(instance.hpBodyId[0]);\n this._hknp.HP_World_RemoveBody(this.world, instance.hpBodyId);\n }\n }\n if (body._pluginData) {\n this._bodyCollisionObservable.delete(body._pluginData.hpBodyId[0]);\n this._hknp.HP_World_RemoveBody(this.world, body._pluginData.hpBodyId);\n }\n }\n /**\n * Initializes the body instances for a given physics body and mesh.\n *\n * @param body - The physics body to initialize.\n * @param motionType - How the body will be handled by the engine\n * @param mesh - The mesh to initialize.\n *\n * This code is useful for creating a physics body from a mesh. It creates a\n * body instance for each instance of the mesh and adds it to the world. It also\n * sets the position of the body instance to the position of the mesh instance.\n * This allows for the physics engine to accurately simulate the mesh in the\n * world.\n */\n initBodyInstances(body, motionType, mesh) {\n var _a, _b;\n const instancesCount = (_b = (_a = mesh._thinInstanceDataStorage) === null || _a === void 0 ? void 0 : _a.instancesCount) !== null && _b !== void 0 ? _b : 0;\n const matrixData = mesh._thinInstanceDataStorage.matrixData;\n if (!matrixData) {\n return; // TODO: error handling\n }\n this._createOrUpdateBodyInstances(body, motionType, matrixData, 0, instancesCount, false);\n body._pluginDataInstances.forEach((bodyId, index) => {\n this._bodies.set(bodyId.hpBodyId[0], { body: body, index: index });\n });\n }\n _createOrUpdateBodyInstances(body, motionType, matrixData, startIndex, endIndex, update) {\n const rotation = TmpVectors.Quaternion[0];\n const rotationMatrix = Matrix.Identity();\n for (let i = startIndex; i < endIndex; i++) {\n const position = [matrixData[i * 16 + 12], matrixData[i * 16 + 13], matrixData[i * 16 + 14]];\n let hkbody;\n if (!update) {\n hkbody = this._hknp.HP_Body_Create()[1];\n }\n else {\n hkbody = body._pluginDataInstances[i].hpBodyId;\n }\n rotationMatrix.setRowFromFloats(0, matrixData[i * 16 + 0], matrixData[i * 16 + 1], matrixData[i * 16 + 2], 0);\n rotationMatrix.setRowFromFloats(1, matrixData[i * 16 + 4], matrixData[i * 16 + 5], matrixData[i * 16 + 6], 0);\n rotationMatrix.setRowFromFloats(2, matrixData[i * 16 + 8], matrixData[i * 16 + 9], matrixData[i * 16 + 10], 0);\n Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);\n const transform = [position, [rotation.x, rotation.y, rotation.z, rotation.w]];\n this._hknp.HP_Body_SetQTransform(hkbody, transform);\n if (!update) {\n const pluginData = new BodyPluginData(hkbody);\n if (body._pluginDataInstances.length) {\n // If an instance already exists, copy any user-provided mass properties\n pluginData.userMassProps = body._pluginDataInstances[0].userMassProps;\n }\n this._internalSetMotionType(pluginData, motionType);\n this._internalUpdateMassProperties(pluginData);\n body._pluginDataInstances.push(pluginData);\n this._hknp.HP_World_AddBody(this.world, hkbody, body.startAsleep);\n pluginData.worldTransformOffset = this._hknp.HP_Body_GetWorldTransformOffset(hkbody)[1];\n }\n }\n }\n /**\n * Update the internal body instances for a given physics body to match the instances in a mesh.\n * @param body the body that will be updated\n * @param mesh the mesh with reference instances\n */\n updateBodyInstances(body, mesh) {\n var _a, _b;\n const instancesCount = (_b = (_a = mesh._thinInstanceDataStorage) === null || _a === void 0 ? void 0 : _a.instancesCount) !== null && _b !== void 0 ? _b : 0;\n const matrixData = mesh._thinInstanceDataStorage.matrixData;\n if (!matrixData) {\n return; // TODO: error handling\n }\n const pluginInstancesCount = body._pluginDataInstances.length;\n const motionType = this.getMotionType(body);\n if (instancesCount > pluginInstancesCount) {\n this._createOrUpdateBodyInstances(body, motionType, matrixData, pluginInstancesCount, instancesCount, false);\n const firstBodyShape = this._hknp.HP_Body_GetShape(body._pluginDataInstances[0].hpBodyId)[1];\n for (let i = pluginInstancesCount; i < instancesCount; i++) {\n this._hknp.HP_Body_SetShape(body._pluginDataInstances[i].hpBodyId, firstBodyShape);\n this._internalUpdateMassProperties(body._pluginDataInstances[i]);\n this._bodies.set(body._pluginDataInstances[i].hpBodyId[0], { body: body, index: i });\n }\n }\n else if (instancesCount < pluginInstancesCount) {\n const instancesToRemove = pluginInstancesCount - instancesCount;\n for (let i = 0; i < instancesToRemove; i++) {\n const hkbody = body._pluginDataInstances.pop();\n this._bodies.delete(hkbody.hpBodyId[0]);\n this._hknp.HP_World_RemoveBody(this.world, hkbody.hpBodyId);\n this._hknp.HP_Body_Release(hkbody.hpBodyId);\n }\n this._createOrUpdateBodyInstances(body, motionType, matrixData, 0, instancesCount, true);\n }\n }\n /**\n * Synchronizes the transform of a physics body with its transform node.\n * @param body - The physics body to synchronize.\n *\n * This function is useful for keeping the physics body's transform in sync with its transform node.\n * This is important for ensuring that the physics body is accurately represented in the physics engine.\n */\n sync(body) {\n this.syncTransform(body, body.transformNode);\n }\n /**\n * Synchronizes the transform of a physics body with the transform of its\n * corresponding transform node.\n *\n * @param body - The physics body to synchronize.\n * @param transformNode - The destination Transform Node.\n *\n * This code is useful for synchronizing the position and orientation of a\n * physics body with the position and orientation of its corresponding\n * transform node. This is important for ensuring that the physics body and\n * the transform node are in the same position and orientation in the scene.\n * This is necessary for the physics engine to accurately simulate the\n * physical behavior of the body.\n */\n syncTransform(body, transformNode) {\n var _a;\n if (body._pluginDataInstances.length) {\n // instances\n const m = transformNode;\n const matrixData = m._thinInstanceDataStorage.matrixData;\n if (!matrixData) {\n return; // TODO: error handling\n }\n const instancesCount = body._pluginDataInstances.length;\n for (let i = 0; i < instancesCount; i++) {\n const bufOffset = body._pluginDataInstances[i].worldTransformOffset;\n const transformBuffer = new Float32Array(this._hknp.HEAPU8.buffer, this._bodyBuffer + bufOffset, 16);\n const index = i * 16;\n for (let mi = 0; mi < 15; mi++) {\n if ((mi & 3) != 3) {\n matrixData[index + mi] = transformBuffer[mi];\n }\n }\n matrixData[index + 15] = 1;\n }\n m.thinInstanceBufferUpdated(\"matrix\");\n }\n else {\n try {\n // regular\n const bodyTransform = this._hknp.HP_Body_GetQTransform(body._pluginData.hpBodyId)[1];\n const bodyTranslation = bodyTransform[0];\n const bodyOrientation = bodyTransform[1];\n const quat = TmpVectors.Quaternion[0];\n quat.set(bodyOrientation[0], bodyOrientation[1], bodyOrientation[2], bodyOrientation[3]);\n const parent = transformNode.parent;\n // transform position/orientation in parent space\n if (parent && !parent.getWorldMatrix().isIdentity()) {\n parent.computeWorldMatrix(true);\n quat.normalize();\n const finalTransform = TmpVectors.Matrix[0];\n const finalTranslation = TmpVectors.Vector3[0];\n finalTranslation.copyFromFloats(bodyTranslation[0], bodyTranslation[1], bodyTranslation[2]);\n Matrix.ComposeToRef(transformNode.absoluteScaling, quat, finalTranslation, finalTransform);\n const parentInverseTransform = TmpVectors.Matrix[1];\n parent.getWorldMatrix().invertToRef(parentInverseTransform);\n const localTransform = TmpVectors.Matrix[2];\n finalTransform.multiplyToRef(parentInverseTransform, localTransform);\n localTransform.decomposeToTransformNode(transformNode);\n (_a = transformNode.rotationQuaternion) === null || _a === void 0 ? void 0 : _a.normalize();\n }\n else {\n transformNode.position.set(bodyTranslation[0], bodyTranslation[1], bodyTranslation[2]);\n if (transformNode.rotationQuaternion) {\n transformNode.rotationQuaternion.copyFrom(quat);\n }\n else {\n quat.toEulerAnglesToRef(transformNode.rotation);\n }\n }\n }\n catch (e) {\n console.log(`Syncing transform failed for node ${transformNode.name}: ${e.message}...`);\n }\n }\n }\n /**\n * Sets the shape of a physics body.\n * @param body - The physics body to set the shape for.\n * @param shape - The physics shape to set.\n *\n * This function is used to set the shape of a physics body. It is useful for\n * creating a physics body with a specific shape, such as a box or a sphere,\n * which can then be used to simulate physical interactions in a physics engine.\n * This function is especially useful for meshes with multiple instances, as it\n * will set the shape for each instance of the mesh.\n */\n setShape(body, shape) {\n var _a, _b, _c;\n const shapeHandle = shape && shape._pluginData ? shape._pluginData : BigInt(0);\n if (!(body.transformNode instanceof Mesh) || !((_a = body.transformNode._thinInstanceDataStorage) === null || _a === void 0 ? void 0 : _a.matrixData)) {\n this._hknp.HP_Body_SetShape(body._pluginData.hpBodyId, shapeHandle);\n this._internalUpdateMassProperties(body._pluginData);\n return;\n }\n const m = body.transformNode;\n const instancesCount = (_c = (_b = m._thinInstanceDataStorage) === null || _b === void 0 ? void 0 : _b.instancesCount) !== null && _c !== void 0 ? _c : 0;\n for (let i = 0; i < instancesCount; i++) {\n this._hknp.HP_Body_SetShape(body._pluginDataInstances[i].hpBodyId, shapeHandle);\n this._internalUpdateMassProperties(body._pluginDataInstances[i]);\n }\n }\n /**\n * Returns a reference to the first instance of the plugin data for a physics body.\n * @param body\n * @param instanceIndex\n * @returns a reference to the first instance\n */\n _getPluginReference(body, instanceIndex) {\n var _a;\n return ((_a = body._pluginDataInstances) === null || _a === void 0 ? void 0 : _a.length) ? body._pluginDataInstances[instanceIndex !== null && instanceIndex !== void 0 ? instanceIndex : 0] : body._pluginData;\n }\n /**\n * Gets the shape of a physics body. This will create a new shape object\n *\n * @param body - The physics body.\n * @returns The shape of the physics body.\n *\n */\n getShape(body) {\n const pluginRef = this._getPluginReference(body);\n const shapePluginData = this._hknp.HP_Body_GetShape(pluginRef.hpBodyId)[1];\n if (shapePluginData != 0) {\n const scene = body.transformNode.getScene();\n return new PhysicsShape({ pluginData: shapePluginData }, scene);\n }\n return null;\n }\n /**\n * Gets the type of a physics shape.\n * @param shape - The physics shape to get the type for.\n * @returns The type of the physics shape.\n *\n */\n getShapeType(shape) {\n if (shape.type) {\n return shape.type;\n }\n else {\n // {\n this._hknp.HP_Body_SetEventMask(bodyPluginData.hpBodyId, eventMask);\n }, instanceIndex);\n }\n /**\n * Retrieves the event mask of a physics body.\n *\n * @param body - The physics body to retrieve the event mask from.\n * @returns The event mask of the physics body.\n *\n */\n getEventMask(body, instanceIndex) {\n const pluginRef = this._getPluginReference(body, instanceIndex);\n return this._hknp.HP_Body_GetEventMask(pluginRef.hpBodyId)[1];\n }\n _fromMassPropertiesTuple(massPropsTuple) {\n return {\n centerOfMass: Vector3.FromArray(massPropsTuple[0]),\n mass: massPropsTuple[1],\n inertia: Vector3.FromArray(massPropsTuple[2]),\n inertiaOrientation: Quaternion.FromArray(massPropsTuple[3]),\n };\n }\n _internalUpdateMassProperties(pluginData) {\n // Recompute the mass based on the shape\n const newProps = this._internalComputeMassProperties(pluginData);\n const massProps = pluginData.userMassProps;\n // Override the computed values with any the user has set\n if (massProps.centerOfMass) {\n newProps[0] = massProps.centerOfMass.asArray();\n }\n if (massProps.mass != undefined) {\n newProps[1] = massProps.mass;\n }\n if (massProps.inertia) {\n newProps[2] = massProps.inertia.asArray();\n }\n if (massProps.inertiaOrientation) {\n newProps[3] = massProps.inertiaOrientation.asArray();\n }\n this._hknp.HP_Body_SetMassProperties(pluginData.hpBodyId, newProps);\n }\n _internalSetMotionType(pluginData, motionType) {\n switch (motionType) {\n case PhysicsMotionType.STATIC:\n this._hknp.HP_Body_SetMotionType(pluginData.hpBodyId, this._hknp.MotionType.STATIC);\n break;\n case PhysicsMotionType.ANIMATED:\n this._hknp.HP_Body_SetMotionType(pluginData.hpBodyId, this._hknp.MotionType.KINEMATIC);\n break;\n case PhysicsMotionType.DYNAMIC:\n this._hknp.HP_Body_SetMotionType(pluginData.hpBodyId, this._hknp.MotionType.DYNAMIC);\n break;\n }\n }\n setMotionType(body, motionType, instanceIndex) {\n this._applyToBodyOrInstances(body, (pluginData) => {\n this._internalSetMotionType(pluginData, motionType);\n }, instanceIndex);\n }\n getMotionType(body, instanceIndex) {\n const pluginRef = this._getPluginReference(body, instanceIndex);\n const type = this._hknp.HP_Body_GetMotionType(pluginRef.hpBodyId)[1];\n switch (type) {\n case this._hknp.MotionType.STATIC:\n return PhysicsMotionType.STATIC;\n case this._hknp.MotionType.KINEMATIC:\n return PhysicsMotionType.ANIMATED;\n case this._hknp.MotionType.DYNAMIC:\n return PhysicsMotionType.DYNAMIC;\n }\n throw new Error(\"Unknown motion type: \" + type);\n }\n _internalComputeMassProperties(pluginData) {\n const shapeRes = this._hknp.HP_Body_GetShape(pluginData.hpBodyId);\n if (shapeRes[0] == this._hknp.Result.RESULT_OK) {\n const shapeMass = this._hknp.HP_Shape_BuildMassProperties(shapeRes[1]);\n if (shapeMass[0] == this._hknp.Result.RESULT_OK) {\n return shapeMass[1];\n }\n }\n // Failed; return a unit inertia\n return [[0, 0, 0], 1, [1, 1, 1], [0, 0, 0, 1]];\n }\n /**\n * Computes the mass properties of a physics body, from it's shape\n *\n * @param body - The physics body to copmute the mass properties of\n */\n computeMassProperties(body, instanceIndex) {\n const pluginRef = this._getPluginReference(body, instanceIndex);\n const computed = this._internalComputeMassProperties(pluginRef);\n return this._fromMassPropertiesTuple(computed);\n }\n /**\n * Sets the mass properties of a physics body.\n *\n * @param body - The physics body to set the mass properties of.\n * @param massProps - The mass properties to set.\n * @param instanceIndex - The index of the instance to set the mass properties of. If undefined, the mass properties of all the bodies will be set.\n * This function is useful for setting the mass properties of a physics body,\n * such as its mass, inertia, and center of mass. This is important for\n * accurately simulating the physics of the body in the physics engine.\n *\n */\n setMassProperties(body, massProps, instanceIndex) {\n this._applyToBodyOrInstances(body, (pluginData) => {\n pluginData.userMassProps = massProps;\n this._internalUpdateMassProperties(pluginData);\n }, instanceIndex);\n }\n /**\n *\n */\n getMassProperties(body, instanceIndex) {\n const pluginRef = this._getPluginReference(body, instanceIndex);\n const massPropsTuple = this._hknp.HP_Body_GetMassProperties(pluginRef.hpBodyId)[1];\n return this._fromMassPropertiesTuple(massPropsTuple);\n }\n /**\n * Sets the linear damping of the given body.\n * @param body - The body to set the linear damping for.\n * @param damping - The linear damping to set.\n *\n * This method is useful for controlling the linear damping of a body in a physics engine.\n * Linear damping is a force that opposes the motion of the body, and is proportional to the velocity of the body.\n * This method allows the user to set the linear damping of a body, which can be used to control the motion of the body.\n */\n setLinearDamping(body, damping, instanceIndex) {\n this._applyToBodyOrInstances(body, (pluginData) => {\n this._hknp.HP_Body_SetLinearDamping(pluginData.hpBodyId, damping);\n }, instanceIndex);\n }\n /**\n * Gets the linear damping of the given body.\n * @param body - The body to get the linear damping from.\n * @returns The linear damping of the given body.\n *\n * This method is useful for getting the linear damping of a body in a physics engine.\n * Linear damping is a force that opposes the motion of the body and is proportional to the velocity of the body.\n * It is used to simulate the effects of air resistance and other forms of friction.\n */\n getLinearDamping(body, instanceIndex) {\n const pluginRef = this._getPluginReference(body, instanceIndex);\n return this._hknp.HP_Body_GetLinearDamping(pluginRef.hpBodyId)[1];\n }\n /**\n * Sets the angular damping of a physics body.\n * @param body - The physics body to set the angular damping for.\n * @param damping - The angular damping value to set.\n *\n * This function is useful for controlling the angular velocity of a physics body.\n * By setting the angular damping, the body's angular velocity will be reduced over time, allowing for more realistic physics simulations.\n */\n setAngularDamping(body, damping, instanceIndex) {\n this._applyToBodyOrInstances(body, (pluginData) => {\n this._hknp.HP_Body_SetAngularDamping(pluginData.hpBodyId, damping);\n }, instanceIndex);\n }\n /**\n * Gets the angular damping of a physics body.\n * @param body - The physics body to get the angular damping from.\n * @returns The angular damping of the body.\n *\n * This function is useful for retrieving the angular damping of a physics body,\n * which is used to control the rotational motion of the body. The angular damping is a value between 0 and 1, where 0 is no damping and 1 is full damping.\n */\n getAngularDamping(body, instanceIndex) {\n const pluginRef = this._getPluginReference(body, instanceIndex);\n return this._hknp.HP_Body_GetAngularDamping(pluginRef.hpBodyId)[1];\n }\n /**\n * Sets the linear velocity of a physics body.\n * @param body - The physics body to set the linear velocity of.\n * @param linVel - The linear velocity to set.\n *\n * This function is useful for setting the linear velocity of a physics body, which is necessary for simulating\n * motion in a physics engine. The linear velocity is the speed and direction of the body's movement.\n */\n setLinearVelocity(body, linVel, instanceIndex) {\n this._applyToBodyOrInstances(body, (pluginData) => {\n this._hknp.HP_Body_SetLinearVelocity(pluginData.hpBodyId, this._bVecToV3(linVel));\n }, instanceIndex);\n }\n /**\n * Gets the linear velocity of a physics body and stores it in a given vector.\n * @param body - The physics body to get the linear velocity from.\n * @param linVel - The vector to store the linear velocity in.\n *\n * This function is useful for retrieving the linear velocity of a physics body,\n * which can be used to determine the speed and direction of the body. This\n * information can be used to simulate realistic physics behavior in a game.\n */\n getLinearVelocityToRef(body, linVel, instanceIndex) {\n const pluginRef = this._getPluginReference(body, instanceIndex);\n const lv = this._hknp.HP_Body_GetLinearVelocity(pluginRef.hpBodyId)[1];\n this._v3ToBvecRef(lv, linVel);\n }\n /*\n * Apply an operation either to all instances of a body, if instanceIndex is not specified, or to a specific instance.\n */\n _applyToBodyOrInstances(body, fnToApply, instanceIndex) {\n var _a;\n if (((_a = body._pluginDataInstances) === null || _a === void 0 ? void 0 : _a.length) > 0 && instanceIndex === undefined) {\n for (let i = 0; i < body._pluginDataInstances.length; i++) {\n fnToApply(body._pluginDataInstances[i]);\n }\n }\n else {\n fnToApply(this._getPluginReference(body, instanceIndex));\n }\n }\n /**\n * Applies an impulse to a physics body at a given location.\n * @param body - The physics body to apply the impulse to.\n * @param impulse - The impulse vector to apply.\n * @param location - The location in world space to apply the impulse.\n * @param instanceIndex - The index of the instance to apply the impulse to. If not specified, the impulse will be applied to all instances.\n *\n * This method is useful for applying an impulse to a physics body at a given location.\n * This can be used to simulate physical forces such as explosions, collisions, and gravity.\n */\n applyImpulse(body, impulse, location, instanceIndex) {\n this._applyToBodyOrInstances(body, (pluginRef) => {\n this._hknp.HP_Body_ApplyImpulse(pluginRef.hpBodyId, this._bVecToV3(location), this._bVecToV3(impulse));\n }, instanceIndex);\n }\n /**\n * Applies a force to a physics body at a given location.\n * @param body - The physics body to apply the impulse to.\n * @param force - The force vector to apply.\n * @param location - The location in world space to apply the impulse.\n * @param instanceIndex - The index of the instance to apply the force to. If not specified, the force will be applied to all instances.\n *\n * This method is useful for applying a force to a physics body at a given location.\n * This can be used to simulate physical forces such as explosions, collisions, and gravity.\n */\n applyForce(body, force, location, instanceIndex) {\n force.scaleToRef(this.getTimeStep(), this._tmpVec3[0]);\n this.applyImpulse(body, this._tmpVec3[0], location, instanceIndex);\n }\n /**\n * Sets the angular velocity of a physics body.\n *\n * @param body - The physics body to set the angular velocity of.\n * @param angVel - The angular velocity to set.\n *\n * This function is useful for setting the angular velocity of a physics body in a physics engine.\n * This allows for more realistic simulations of physical objects, as they can be given a rotational velocity.\n */\n setAngularVelocity(body, angVel, instanceIndex) {\n this._applyToBodyOrInstances(body, (pluginRef) => {\n this._hknp.HP_Body_SetAngularVelocity(pluginRef.hpBodyId, this._bVecToV3(angVel));\n }, instanceIndex);\n }\n /**\n * Gets the angular velocity of a body.\n * @param body - The body to get the angular velocity from.\n * @param angVel - The vector3 to store the angular velocity.\n *\n * This method is useful for getting the angular velocity of a body in a physics engine. It\n * takes the body and a vector3 as parameters and stores the angular velocity of the body\n * in the vector3. This is useful for getting the angular velocity of a body in order to\n * calculate the motion of the body in the physics engine.\n */\n getAngularVelocityToRef(body, angVel, instanceIndex) {\n const pluginRef = this._getPluginReference(body, instanceIndex);\n const av = this._hknp.HP_Body_GetAngularVelocity(pluginRef.hpBodyId)[1];\n this._v3ToBvecRef(av, angVel);\n }\n /**\n * Sets the transformation of the given physics body to the given transform node.\n * @param body The physics body to set the transformation for.\n * @param node The transform node to set the transformation from.\n * Sets the transformation of the given physics body to the given transform node.\n *\n * This function is useful for setting the transformation of a physics body to a\n * transform node, which is necessary for the physics engine to accurately simulate\n * the motion of the body. It also takes into account instances of the transform\n * node, which is necessary for accurate simulation of multiple bodies with the\n * same transformation.\n */\n setPhysicsBodyTransformation(body, node) {\n const transformNode = body.transformNode;\n if (body.numInstances > 0) {\n // instances\n const m = transformNode;\n const matrixData = m._thinInstanceDataStorage.matrixData;\n if (!matrixData) {\n return; // TODO: error handling\n }\n const instancesCount = body.numInstances;\n this._createOrUpdateBodyInstances(body, body.getMotionType(), matrixData, 0, instancesCount, true);\n }\n else {\n // regular\n this._hknp.HP_Body_SetQTransform(body._pluginData.hpBodyId, this._getTransformInfos(node));\n }\n }\n /**\n * Sets the gravity factor of a body\n * @param body the physics body to set the gravity factor for\n * @param factor the gravity factor\n * @param instanceIndex the index of the instance in an instanced body\n */\n setGravityFactor(body, factor, instanceIndex) {\n this._applyToBodyOrInstances(body, (pluginRef) => {\n this._hknp.HP_Body_SetGravityFactor(pluginRef.hpBodyId, factor);\n }, instanceIndex);\n }\n /**\n * Get the gravity factor of a body\n * @param body the physics body to get the gravity factor from\n * @param instanceIndex the index of the instance in an instanced body. If not specified, the gravity factor of the first instance will be returned.\n * @returns the gravity factor\n */\n getGravityFactor(body, instanceIndex) {\n const pluginRef = this._getPluginReference(body, instanceIndex);\n return this._hknp.HP_Body_GetGravityFactor(pluginRef.hpBodyId)[1];\n }\n /**\n * Disposes a physics body.\n *\n * @param body - The physics body to dispose.\n *\n * This method is useful for releasing the resources associated with a physics body when it is no longer needed.\n * This is important for avoiding memory leaks in the physics engine.\n */\n disposeBody(body) {\n if (body._pluginDataInstances && body._pluginDataInstances.length > 0) {\n for (const instance of body._pluginDataInstances) {\n this._hknp.HP_Body_Release(instance.hpBodyId);\n instance.hpBodyId = undefined;\n }\n }\n if (body._pluginData) {\n this._hknp.HP_Body_Release(body._pluginData.hpBodyId);\n body._pluginData.hpBodyId = undefined;\n }\n }\n /**\n * Initializes a physics shape with the given type and parameters.\n * @param shape - The physics shape to initialize.\n * @param type - The type of shape to initialize.\n * @param options - The parameters for the shape.\n *\n * This code is useful for initializing a physics shape with the given type and parameters.\n * It allows for the creation of a sphere, box, capsule, container, cylinder, mesh, and heightfield.\n * Depending on the type of shape, different parameters are required.\n * For example, a sphere requires a radius, while a box requires extents and a rotation.\n */\n initShape(shape, type, options) {\n switch (type) {\n case PhysicsShapeType.SPHERE:\n {\n const radius = options.radius || 1;\n const center = options.center ? this._bVecToV3(options.center) : [0, 0, 0];\n shape._pluginData = this._hknp.HP_Shape_CreateSphere(center, radius)[1];\n }\n break;\n case PhysicsShapeType.BOX:\n {\n const rotation = options.rotation ? this._bQuatToV4(options.rotation) : [0, 0, 0, 1];\n const extent = options.extents ? this._bVecToV3(options.extents) : [1, 1, 1];\n const center = options.center ? this._bVecToV3(options.center) : [0, 0, 0];\n shape._pluginData = this._hknp.HP_Shape_CreateBox(center, rotation, extent)[1];\n }\n break;\n case PhysicsShapeType.CAPSULE:\n {\n const pointA = options.pointA ? this._bVecToV3(options.pointA) : [0, 0, 0];\n const pointB = options.pointB ? this._bVecToV3(options.pointB) : [0, 1, 0];\n const radius = options.radius || 0;\n shape._pluginData = this._hknp.HP_Shape_CreateCapsule(pointA, pointB, radius)[1];\n }\n break;\n case PhysicsShapeType.CONTAINER:\n {\n shape._pluginData = this._hknp.HP_Shape_CreateContainer()[1];\n }\n break;\n case PhysicsShapeType.CYLINDER:\n {\n const pointA = options.pointA ? this._bVecToV3(options.pointA) : [0, 0, 0];\n const pointB = options.pointB ? this._bVecToV3(options.pointB) : [0, 1, 0];\n const radius = options.radius || 0;\n shape._pluginData = this._hknp.HP_Shape_CreateCylinder(pointA, pointB, radius)[1];\n }\n break;\n case PhysicsShapeType.CONVEX_HULL:\n case PhysicsShapeType.MESH:\n {\n const mesh = options.mesh;\n if (mesh) {\n const includeChildMeshes = !!options.includeChildMeshes;\n const needIndices = type != PhysicsShapeType.CONVEX_HULL;\n const accum = new MeshAccumulator(mesh, needIndices, mesh === null || mesh === void 0 ? void 0 : mesh.getScene());\n accum.addMesh(mesh, includeChildMeshes);\n const positions = accum.getVertices(this._hknp);\n const numVec3s = positions.length / 3;\n if (type == PhysicsShapeType.CONVEX_HULL) {\n shape._pluginData = this._hknp.HP_Shape_CreateConvexHull(positions.byteOffset, numVec3s)[1];\n }\n else {\n const triangles = accum.getTriangles(this._hknp);\n const numTriangles = triangles.length / 3;\n shape._pluginData = this._hknp.HP_Shape_CreateMesh(positions.byteOffset, numVec3s, triangles.byteOffset, numTriangles)[1];\n accum.freeBuffer(this._hknp, triangles);\n }\n accum.freeBuffer(this._hknp, positions);\n }\n else {\n throw new Error(\"No mesh provided to create physics shape.\");\n }\n }\n break;\n default:\n throw new Error(\"Unsupported Shape Type.\");\n break;\n }\n }\n setShapeFilterMembershipMask(shape, membershipMask) {\n const collideWith = this._hknp.HP_Shape_GetFilterInfo(shape._pluginData)[1][1];\n this._hknp.HP_Shape_SetFilterInfo(shape._pluginData, [membershipMask, collideWith]);\n }\n getShapeFilterMembershipMask(shape) {\n return this._hknp.HP_Shape_GetFilterInfo(shape._pluginData)[1][0];\n }\n setShapeFilterCollideMask(shape, collideMask) {\n const membership = this._hknp.HP_Shape_GetFilterInfo(shape._pluginData)[1][0];\n this._hknp.HP_Shape_SetFilterInfo(shape._pluginData, [membership, collideMask]);\n }\n getShapeFilterCollideMask(shape) {\n return this._hknp.HP_Shape_GetFilterInfo(shape._pluginData)[1][1];\n }\n /**\n * Sets the material of a physics shape.\n * @param shape - The physics shape to set the material of.\n * @param material - The material to set.\n *\n */\n setMaterial(shape, material) {\n var _a, _b, _c, _d, _e;\n const dynamicFriction = (_a = material.friction) !== null && _a !== void 0 ? _a : 0.5;\n const staticFriction = (_b = material.staticFriction) !== null && _b !== void 0 ? _b : dynamicFriction;\n const restitution = (_c = material.restitution) !== null && _c !== void 0 ? _c : 0.0;\n const frictionCombine = (_d = material.frictionCombine) !== null && _d !== void 0 ? _d : PhysicsMaterialCombineMode.MINIMUM;\n const restitutionCombine = (_e = material.restitutionCombine) !== null && _e !== void 0 ? _e : PhysicsMaterialCombineMode.MAXIMUM;\n const hpMaterial = [staticFriction, dynamicFriction, restitution, this._materialCombineToNative(frictionCombine), this._materialCombineToNative(restitutionCombine)];\n this._hknp.HP_Shape_SetMaterial(shape._pluginData, hpMaterial);\n }\n /**\n * Sets the density of a physics shape.\n * @param shape - The physics shape to set the density of.\n * @param density - The density to set.\n *\n */\n setDensity(shape, density) {\n this._hknp.HP_Shape_SetDensity(shape._pluginData, density);\n }\n /**\n * Calculates the density of a given physics shape.\n *\n * @param shape - The physics shape to calculate the density of.\n * @returns The density of the given physics shape.\n *\n */\n getDensity(shape) {\n return this._hknp.HP_Shape_GetDensity(shape._pluginData)[1];\n }\n /**\n * Gets the transform infos of a given transform node.\n * @param node - The transform node.\n * @returns An array containing the position and orientation of the node.\n * This code is useful for getting the position and orientation of a given transform node.\n * It first checks if the node has a rotation quaternion, and if not, it creates one from the node's rotation.\n * It then creates an array containing the position and orientation of the node and returns it.\n */\n _getTransformInfos(node) {\n if (node.parent) {\n node.computeWorldMatrix(true);\n return [this._bVecToV3(node.absolutePosition), this._bQuatToV4(node.absoluteRotationQuaternion)];\n }\n let orientation = TmpVectors.Quaternion[0];\n if (node.rotationQuaternion) {\n orientation = node.rotationQuaternion;\n }\n else {\n const r = node.rotation;\n Quaternion.FromEulerAnglesToRef(r.x, r.y, r.z, orientation);\n }\n const transform = [this._bVecToV3(node.position), this._bQuatToV4(orientation)];\n return transform;\n }\n /**\n * Adds a child shape to the given shape.\n * @param shape - The parent shape.\n * @param newChild - The child shape to add.\n * @param childTransform - The transform of the child shape relative to the parent shape.\n *\n */\n addChild(shape, newChild, translation, rotation, scale) {\n const transformNative = [\n translation ? this._bVecToV3(translation) : [0, 0, 0],\n rotation ? this._bQuatToV4(rotation) : [0, 0, 0, 1],\n scale ? this._bVecToV3(scale) : [1, 1, 1],\n ];\n this._hknp.HP_Shape_AddChild(shape._pluginData, newChild._pluginData, transformNative);\n }\n /**\n * Removes a child shape from a parent shape.\n * @param shape - The parent shape.\n * @param childIndex - The index of the child shape to remove.\n *\n */\n removeChild(shape, childIndex) {\n this._hknp.HP_Shape_RemoveChild(shape._pluginData, childIndex);\n }\n /**\n * Returns the number of children of the given shape.\n *\n * @param shape - The shape to get the number of children from.\n * @returns The number of children of the given shape.\n *\n */\n getNumChildren(shape) {\n return this._hknp.HP_Shape_GetNumChildren(shape._pluginData)[1];\n }\n /**\n * Calculates the bounding box of a given physics shape.\n *\n * @param shape - The physics shape to calculate the bounding box for.\n * @returns The calculated bounding box.\n *\n * This method is useful for physics engines as it allows to calculate the\n * boundaries of a given shape. Knowing the boundaries of a shape is important\n * for collision detection and other physics calculations.\n */\n getBoundingBox(shape) {\n return {};\n }\n /**\n * Gets the geometry of a physics body.\n *\n * @param body - The physics body.\n * @returns An object containing the positions and indices of the body's geometry.\n *\n */\n getBodyGeometry(body) {\n var _a;\n const dataInfo = ((_a = body._pluginDataInstances) === null || _a === void 0 ? void 0 : _a.length) > 0 ? body._pluginDataInstances[0] : body._pluginData;\n const shape = this._hknp.HP_Body_GetShape(dataInfo.hpBodyId)[1];\n const geometryRes = this._hknp.HP_Shape_CreateDebugDisplayGeometry(shape);\n if (geometryRes[0] != this._hknp.Result.RESULT_OK) {\n return { positions: [], indices: [] };\n }\n const geometryInfo = this._hknp.HP_DebugGeometry_GetInfo(geometryRes[1])[1];\n const positionsInPlugin = new Float32Array(this._hknp.HEAPU8.buffer, geometryInfo[0], geometryInfo[1] * 3); // 3 floats per position\n const indicesInPlugin = new Uint32Array(this._hknp.HEAPU8.buffer, geometryInfo[2], geometryInfo[3] * 3); // 3 indices per triangle\n // HP_DebugGeometry_Release will free the buffer in the plugin. To avoid a\n // use-after-free, we need to make a copy of the data here.\n const positions = positionsInPlugin.slice(0);\n const indices = indicesInPlugin.slice(0);\n this._hknp.HP_DebugGeometry_Release(geometryRes[1]);\n return { positions: positions, indices: indices };\n }\n /**\n * Releases a physics shape from the physics engine.\n *\n * @param shape - The physics shape to be released.\n * @returns void\n *\n * This method is useful for releasing a physics shape from the physics engine, freeing up resources and preventing memory leaks.\n */\n disposeShape(shape) {\n this._hknp.HP_Shape_Release(shape._pluginData);\n shape._pluginData = undefined;\n }\n // constraint\n /**\n * Initializes a physics constraint with the given parameters.\n *\n * @param constraint - The physics constraint to be initialized.\n * @param body - The main body\n * @param childBody - The child body.\n * @param instanceIndex - If this body is instanced, the index of the instance to which the constraint will be applied. If not specified, no constraint will be applied.\n * @param childInstanceIndex - If the child body is instanced, the index of the instance to which the constraint will be applied. If not specified, no constraint will be applied.\n *\n * This function is useful for setting up a physics constraint in a physics engine.\n */\n initConstraint(constraint, body, childBody, instanceIndex, childInstanceIndex) {\n var _a, _b, _c, _d;\n const type = constraint.type;\n const options = constraint.options;\n if (!type || !options) {\n Logger.Warn(\"No constraint type or options. Constraint is invalid.\");\n return;\n }\n if ((body._pluginDataInstances.length > 0 && instanceIndex === undefined) || (childBody._pluginDataInstances.length > 0 && childInstanceIndex === undefined)) {\n Logger.Warn(\"Body is instanced but no instance index was specified. Constraint will not be applied.\");\n return;\n }\n const jointId = this._hknp.HP_Constraint_Create()[1];\n constraint._pluginData = jointId;\n // body parenting\n const bodyA = this._getPluginReference(body, instanceIndex).hpBodyId;\n const bodyB = this._getPluginReference(childBody, childInstanceIndex).hpBodyId;\n this._hknp.HP_Constraint_SetParentBody(jointId, bodyA);\n this._hknp.HP_Constraint_SetChildBody(jointId, bodyB);\n // anchors\n const pivotA = options.pivotA ? this._bVecToV3(options.pivotA) : this._bVecToV3(Vector3.Zero());\n const axisA = (_a = options.axisA) !== null && _a !== void 0 ? _a : new Vector3(1, 0, 0);\n const perpAxisA = this._tmpVec3[0];\n if (options.perpAxisA) {\n perpAxisA.copyFrom(options.perpAxisA);\n }\n else {\n axisA.getNormalToRef(perpAxisA);\n }\n this._hknp.HP_Constraint_SetAnchorInParent(jointId, pivotA, this._bVecToV3(axisA), this._bVecToV3(perpAxisA));\n const pivotB = options.pivotB ? this._bVecToV3(options.pivotB) : this._bVecToV3(Vector3.Zero());\n const axisB = (_b = options.axisB) !== null && _b !== void 0 ? _b : new Vector3(1, 0, 0);\n const perpAxisB = this._tmpVec3[0];\n if (options.perpAxisB) {\n perpAxisB.copyFrom(options.perpAxisB);\n }\n else {\n axisB.getNormalToRef(perpAxisB);\n }\n this._hknp.HP_Constraint_SetAnchorInChild(jointId, pivotB, this._bVecToV3(axisB), this._bVecToV3(perpAxisB));\n if (type == PhysicsConstraintType.LOCK) {\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_X, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_X, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED);\n }\n else if (type == PhysicsConstraintType.DISTANCE) {\n const distance = options.maxDistance || 0;\n const dist3d = this._hknp.ConstraintAxis.LINEAR_DISTANCE;\n this._hknp.HP_Constraint_SetAxisMode(jointId, dist3d, this._hknp.ConstraintAxisLimitMode.LIMITED);\n this._hknp.HP_Constraint_SetAxisMinLimit(jointId, dist3d, distance);\n this._hknp.HP_Constraint_SetAxisMaxLimit(jointId, dist3d, distance);\n }\n else if (type == PhysicsConstraintType.HINGE) {\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_X, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED);\n }\n else if (type == PhysicsConstraintType.PRISMATIC) {\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_X, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED);\n }\n else if (type == PhysicsConstraintType.SLIDER) {\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED);\n }\n else if (type == PhysicsConstraintType.BALL_AND_SOCKET) {\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_X, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED);\n }\n else if (type == PhysicsConstraintType.SIX_DOF) {\n const sixdofData = constraint;\n for (const l of sixdofData.limits) {\n const axId = this._constraintAxisToNative(l.axis);\n if (((_c = l.minLimit) !== null && _c !== void 0 ? _c : -1) == 0 && ((_d = l.maxLimit) !== null && _d !== void 0 ? _d : -1) == 0) {\n this._hknp.HP_Constraint_SetAxisMode(jointId, axId, this._hknp.ConstraintAxisLimitMode.LOCKED);\n }\n else {\n if (l.minLimit != undefined) {\n this._hknp.HP_Constraint_SetAxisMode(jointId, axId, this._hknp.ConstraintAxisLimitMode.LIMITED);\n this._hknp.HP_Constraint_SetAxisMinLimit(jointId, axId, l.minLimit);\n }\n if (l.maxLimit != undefined) {\n this._hknp.HP_Constraint_SetAxisMode(jointId, axId, this._hknp.ConstraintAxisLimitMode.LIMITED);\n this._hknp.HP_Constraint_SetAxisMaxLimit(jointId, axId, l.maxLimit);\n }\n }\n }\n }\n else {\n throw new Error(\"Unsupported Constraint Type.\");\n }\n const collisionEnabled = !!options.collision;\n this._hknp.HP_Constraint_SetCollisionsEnabled(jointId, collisionEnabled);\n this._hknp.HP_Constraint_SetEnabled(jointId, true);\n }\n /**\n * Adds a constraint to the physics engine.\n *\n * @param body - The main body to which the constraint is applied.\n * @param childBody - The body to which the constraint is applied.\n * @param constraint - The constraint to be applied.\n * @param instanceIndex - If this body is instanced, the index of the instance to which the constraint will be applied. If not specified, no constraint will be applied.\n * @param childInstanceIndex - If the child body is instanced, the index of the instance to which the constraint will be applied. If not specified, no constraint will be applied.\n */\n addConstraint(body, childBody, constraint, instanceIndex, childInstanceIndex) {\n // 0) {\n const hitData = this._hknp.HP_QueryCollector_GetCastRayResult(this._queryCollector, 0)[1];\n const hitPos = hitData[1][3];\n const hitNormal = hitData[1][4];\n const hitTriangle = hitData[1][5];\n result.setHitData({ x: hitNormal[0], y: hitNormal[1], z: hitNormal[2] }, { x: hitPos[0], y: hitPos[1], z: hitPos[2] }, hitTriangle);\n result.calculateHitDistance();\n const hitBody = this._bodies.get(hitData[1][0][0]);\n result.body = hitBody === null || hitBody === void 0 ? void 0 : hitBody.body;\n result.bodyIndex = hitBody === null || hitBody === void 0 ? void 0 : hitBody.index;\n }\n }\n /**\n * Return the collision observable for a particular physics body.\n * @param body the physics body\n */\n getCollisionObservable(body) {\n const bodyId = body._pluginData.hpBodyId[0];\n let observable = this._bodyCollisionObservable.get(bodyId);\n if (!observable) {\n observable = new Observable();\n this._bodyCollisionObservable.set(bodyId, observable);\n }\n return observable;\n }\n /**\n * Enable collision to be reported for a body when a callback is settup on the world\n * @param body the physics body\n * @param enabled\n */\n setCollisionCallbackEnabled(body, enabled) {\n // Register for collide events by default\n const collideEvents = this._hknp.EventType.COLLISION_STARTED.value | this._hknp.EventType.COLLISION_CONTINUED.value | this._hknp.EventType.COLLISION_FINISHED.value;\n if (body._pluginDataInstances && body._pluginDataInstances.length) {\n body._pluginDataInstances.forEach((bodyId) => {\n this._hknp.HP_Body_SetEventMask(bodyId.hpBodyId, enabled ? collideEvents : 0);\n });\n }\n else if (body._pluginData) {\n this._hknp.HP_Body_SetEventMask(body._pluginData.hpBodyId, enabled ? collideEvents : 0);\n }\n }\n /**\n * Runs thru all detected collisions and filter by body\n */\n _notifyCollisions() {\n let eventAddress = this._hknp.HP_World_GetCollisionEvents(this.world)[1];\n const event = new CollisionEvent();\n const worldAddr = Number(this.world);\n while (eventAddress) {\n CollisionEvent.readToRef(this._hknp.HEAPU8.buffer, eventAddress, event);\n event.contactOnB.position.subtractToRef(event.contactOnA.position, this._tmpVec3[0]);\n const distance = Vector3.Dot(this._tmpVec3[0], event.contactOnA.normal);\n const bodyInfoA = this._bodies.get(event.contactOnA.bodyId);\n const bodyInfoB = this._bodies.get(event.contactOnB.bodyId);\n const collisionInfo = {\n collider: bodyInfoA.body,\n colliderIndex: bodyInfoA.index,\n collidedAgainst: bodyInfoB.body,\n collidedAgainstIndex: bodyInfoB.index,\n point: event.contactOnA.position,\n distance: distance,\n impulse: event.impulseApplied,\n normal: event.contactOnA.normal,\n };\n this.onCollisionObservable.notifyObservers(collisionInfo);\n if (this._bodyCollisionObservable.size) {\n const observableA = this._bodyCollisionObservable.get(event.contactOnA.bodyId);\n const observableB = this._bodyCollisionObservable.get(event.contactOnB.bodyId);\n if (observableA) {\n observableA.notifyObservers(collisionInfo);\n }\n else if (observableB) {\n // {\n const index = camera.attachPostProcess(postProcess);\n this._indicesForCamera[cameraName].push(index);\n });\n if (!this._cameras[cameraName]) {\n this._cameras[cameraName] = camera;\n }\n }\n }\n /**\n * Detaches the effect on cameras\n * @param cameras The camera to detach from.\n * @internal\n */\n _detachCameras(cameras) {\n const cams = Tools.MakeArray(cameras || this._cameras);\n if (!cams) {\n return;\n }\n for (let i = 0; i < cams.length; i++) {\n const camera = cams[i];\n const cameraName = camera.name;\n const postProcesses = this._postProcesses[this._singleInstance ? 0 : cameraName];\n if (postProcesses) {\n postProcesses.forEach((postProcess) => {\n camera.detachPostProcess(postProcess);\n });\n }\n if (this._cameras[cameraName]) {\n this._cameras[cameraName] = null;\n }\n }\n }\n /**\n * Enables the effect on given cameras\n * @param cameras The camera to enable.\n * @internal\n */\n _enable(cameras) {\n const cams = Tools.MakeArray(cameras || this._cameras);\n if (!cams) {\n return;\n }\n for (let i = 0; i < cams.length; i++) {\n const camera = cams[i];\n const cameraName = camera.name;\n for (let j = 0; j < this._indicesForCamera[cameraName].length; j++) {\n if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {\n this._postProcesses[this._singleInstance ? 0 : cameraName].forEach((postProcess) => {\n cams[i].attachPostProcess(postProcess, this._indicesForCamera[cameraName][j]);\n });\n }\n }\n }\n }\n /**\n * Disables the effect on the given cameras\n * @param cameras The camera to disable.\n * @internal\n */\n _disable(cameras) {\n const cams = Tools.MakeArray(cameras || this._cameras);\n if (!cams) {\n return;\n }\n for (let i = 0; i < cams.length; i++) {\n const camera = cams[i];\n const cameraName = camera.name;\n this._postProcesses[this._singleInstance ? 0 : cameraName].forEach((postProcess) => {\n camera.detachPostProcess(postProcess);\n });\n }\n }\n /**\n * Gets a list of the post processes contained in the effect.\n * @param camera The camera to get the post processes on.\n * @returns The list of the post processes in the effect.\n */\n getPostProcesses(camera) {\n if (this._singleInstance) {\n return this._postProcesses[0];\n }\n else {\n if (!camera) {\n return null;\n }\n return this._postProcesses[camera.name];\n }\n }\n}\n//# sourceMappingURL=postProcessRenderEffect.js.map","import { Matrix } from \"../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\n\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { MultiRenderTarget } from \"../Materials/Textures/multiRenderTarget.js\";\nimport { MaterialHelper } from \"../Materials/materialHelper.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { _WarnImport } from \"../Misc/devTools.js\";\nimport { Material } from \"../Materials/material.js\";\nimport \"../Shaders/geometry.fragment.js\";\nimport \"../Shaders/geometry.vertex.js\";\nimport { MaterialFlags } from \"../Materials/materialFlags.js\";\nimport { addClipPlaneUniforms, bindClipPlane, prepareStringDefinesForClipPlanes } from \"../Materials/clipPlaneMaterialHelper.js\";\n/** list the uniforms used by the geometry renderer */\nconst uniforms = [\n \"world\",\n \"mBones\",\n \"viewProjection\",\n \"diffuseMatrix\",\n \"view\",\n \"previousWorld\",\n \"previousViewProjection\",\n \"mPreviousBones\",\n \"bumpMatrix\",\n \"reflectivityMatrix\",\n \"albedoMatrix\",\n \"reflectivityColor\",\n \"albedoColor\",\n \"metallic\",\n \"glossiness\",\n \"vTangentSpaceParams\",\n \"vBumpInfos\",\n \"morphTargetInfluences\",\n \"morphTargetTextureInfo\",\n \"morphTargetTextureIndices\",\n];\naddClipPlaneUniforms(uniforms);\n/**\n * This renderer is helpful to fill one of the render target with a geometry buffer.\n */\nexport class GeometryBufferRenderer {\n /**\n * @internal\n * Sets up internal structures to share outputs with PrePassRenderer\n * This method should only be called by the PrePassRenderer itself\n */\n _linkPrePassRenderer(prePassRenderer) {\n this._linkedWithPrePass = true;\n this._prePassRenderer = prePassRenderer;\n if (this._multiRenderTarget) {\n // prevents clearing of the RT since it's done by prepass\n this._multiRenderTarget.onClearObservable.clear();\n this._multiRenderTarget.onClearObservable.add(() => {\n // pass\n });\n }\n }\n /**\n * @internal\n * Separates internal structures from PrePassRenderer so the geometry buffer can now operate by itself.\n * This method should only be called by the PrePassRenderer itself\n */\n _unlinkPrePassRenderer() {\n this._linkedWithPrePass = false;\n this._createRenderTargets();\n }\n /**\n * @internal\n * Resets the geometry buffer layout\n */\n _resetLayout() {\n this._enablePosition = false;\n this._enableReflectivity = false;\n this._enableVelocity = false;\n this._attachmentsFromPrePass = [];\n }\n /**\n * @internal\n * Replaces a texture in the geometry buffer renderer\n * Useful when linking textures of the prepass renderer\n */\n _forceTextureType(geometryBufferType, index) {\n if (geometryBufferType === GeometryBufferRenderer.POSITION_TEXTURE_TYPE) {\n this._positionIndex = index;\n this._enablePosition = true;\n }\n else if (geometryBufferType === GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE) {\n this._velocityIndex = index;\n this._enableVelocity = true;\n }\n else if (geometryBufferType === GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE) {\n this._reflectivityIndex = index;\n this._enableReflectivity = true;\n }\n else if (geometryBufferType === GeometryBufferRenderer.DEPTH_TEXTURE_TYPE) {\n this._depthIndex = index;\n }\n else if (geometryBufferType === GeometryBufferRenderer.NORMAL_TEXTURE_TYPE) {\n this._normalIndex = index;\n }\n }\n /**\n * @internal\n * Sets texture attachments\n * Useful when linking textures of the prepass renderer\n */\n _setAttachments(attachments) {\n this._attachmentsFromPrePass = attachments;\n }\n /**\n * @internal\n * Replaces the first texture which is hard coded as a depth texture in the geometry buffer\n * Useful when linking textures of the prepass renderer\n */\n _linkInternalTexture(internalTexture) {\n this._multiRenderTarget.setInternalTexture(internalTexture, 0, false);\n }\n /**\n * Gets the render list (meshes to be rendered) used in the G buffer.\n */\n get renderList() {\n return this._multiRenderTarget.renderList;\n }\n /**\n * Set the render list (meshes to be rendered) used in the G buffer.\n */\n set renderList(meshes) {\n this._multiRenderTarget.renderList = meshes;\n }\n /**\n * Gets whether or not G buffer are supported by the running hardware.\n * This requires draw buffer supports\n */\n get isSupported() {\n return this._multiRenderTarget.isSupported;\n }\n /**\n * Returns the index of the given texture type in the G-Buffer textures array\n * @param textureType The texture type constant. For example GeometryBufferRenderer.POSITION_TEXTURE_INDEX\n * @returns the index of the given texture type in the G-Buffer textures array\n */\n getTextureIndex(textureType) {\n switch (textureType) {\n case GeometryBufferRenderer.POSITION_TEXTURE_TYPE:\n return this._positionIndex;\n case GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE:\n return this._velocityIndex;\n case GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE:\n return this._reflectivityIndex;\n default:\n return -1;\n }\n }\n /**\n * Gets a boolean indicating if objects positions are enabled for the G buffer.\n */\n get enablePosition() {\n return this._enablePosition;\n }\n /**\n * Sets whether or not objects positions are enabled for the G buffer.\n */\n set enablePosition(enable) {\n this._enablePosition = enable;\n // PrePass handles index and texture links\n if (!this._linkedWithPrePass) {\n this.dispose();\n this._createRenderTargets();\n }\n }\n /**\n * Gets a boolean indicating if objects velocities are enabled for the G buffer.\n */\n get enableVelocity() {\n return this._enableVelocity;\n }\n /**\n * Sets whether or not objects velocities are enabled for the G buffer.\n */\n set enableVelocity(enable) {\n this._enableVelocity = enable;\n if (!enable) {\n this._previousTransformationMatrices = {};\n }\n if (!this._linkedWithPrePass) {\n this.dispose();\n this._createRenderTargets();\n }\n this._scene.needsPreviousWorldMatrices = enable;\n }\n /**\n * Gets a boolean indicating if objects reflectivity are enabled in the G buffer.\n */\n get enableReflectivity() {\n return this._enableReflectivity;\n }\n /**\n * Sets whether or not objects reflectivity are enabled for the G buffer.\n * For Metallic-Roughness workflow with ORM texture, we assume that ORM texture is defined according to the default layout:\n * pbr.useRoughnessFromMetallicTextureAlpha = false;\n * pbr.useRoughnessFromMetallicTextureGreen = true;\n * pbr.useMetallnessFromMetallicTextureBlue = true;\n */\n set enableReflectivity(enable) {\n this._enableReflectivity = enable;\n if (!this._linkedWithPrePass) {\n this.dispose();\n this._createRenderTargets();\n }\n }\n /**\n * Gets the scene associated with the buffer.\n */\n get scene() {\n return this._scene;\n }\n /**\n * Gets the ratio used by the buffer during its creation.\n * How big is the buffer related to the main canvas.\n */\n get ratio() {\n return this._ratio;\n }\n /**\n * Creates a new G Buffer for the scene\n * @param scene The scene the buffer belongs to\n * @param ratio How big is the buffer related to the main canvas (default: 1)\n * @param depthFormat Format of the depth texture (default: 15)\n */\n constructor(scene, ratio = 1, depthFormat = 15) {\n /**\n * Dictionary used to store the previous transformation matrices of each rendered mesh\n * in order to compute objects velocities when enableVelocity is set to \"true\"\n * @internal\n */\n this._previousTransformationMatrices = {};\n /**\n * Dictionary used to store the previous bones transformation matrices of each rendered mesh\n * in order to compute objects velocities when enableVelocity is set to \"true\"\n * @internal\n */\n this._previousBonesTransformationMatrices = {};\n /**\n * Array used to store the ignored skinned meshes while computing velocity map (typically used by the motion blur post-process).\n * Avoids computing bones velocities and computes only mesh's velocity itself (position, rotation, scaling).\n */\n this.excludedSkinnedMeshesFromVelocity = [];\n /** Gets or sets a boolean indicating if transparent meshes should be rendered */\n this.renderTransparentMeshes = true;\n this._resizeObserver = null;\n this._enablePosition = false;\n this._enableVelocity = false;\n this._enableReflectivity = false;\n this._clearColor = new Color4(0, 0, 0, 0);\n this._clearDepthColor = new Color4(1e8, 0, 0, 1); // \"infinity\" value - depth in the depth texture is view.z, not a 0..1 value!\n this._positionIndex = -1;\n this._velocityIndex = -1;\n this._reflectivityIndex = -1;\n this._depthIndex = -1;\n this._normalIndex = -1;\n this._linkedWithPrePass = false;\n /**\n * If set to true (default: false), the depth texture will be cleared with the depth value corresponding to the far plane (1 in normal mode, 0 in reverse depth buffer mode)\n * If set to false, the depth texture is always cleared with 0.\n */\n this.useSpecificClearForDepthTexture = false;\n this._scene = scene;\n this._ratio = ratio;\n this._useUbo = scene.getEngine().supportsUniformBuffers;\n this._depthFormat = depthFormat;\n GeometryBufferRenderer._SceneComponentInitialization(this._scene);\n // Render target\n this._createRenderTargets();\n }\n /**\n * Checks whether everything is ready to render a submesh to the G buffer.\n * @param subMesh the submesh to check readiness for\n * @param useInstances is the mesh drawn using instance or not\n * @returns true if ready otherwise false\n */\n isReady(subMesh, useInstances) {\n const material = subMesh.getMaterial();\n if (material && material.disableDepthWrite) {\n return false;\n }\n const defines = [];\n const attribs = [VertexBuffer.PositionKind, VertexBuffer.NormalKind];\n const mesh = subMesh.getMesh();\n // Alpha test\n if (material) {\n let needUv = false;\n if (material.needAlphaTesting() && material.getAlphaTestTexture()) {\n defines.push(\"#define ALPHATEST\");\n defines.push(`#define ALPHATEST_UV${material.getAlphaTestTexture().coordinatesIndex + 1}`);\n needUv = true;\n }\n if (material.bumpTexture && MaterialFlags.BumpTextureEnabled) {\n defines.push(\"#define BUMP\");\n defines.push(`#define BUMP_UV${material.bumpTexture.coordinatesIndex + 1}`);\n needUv = true;\n }\n if (this._enableReflectivity) {\n let metallicWorkflow = false;\n // for PBR materials: cf. https://doc.babylonjs.com/features/featuresDeepDive/materials/using/masterPBR\n if (material.getClassName() === \"PBRMetallicRoughnessMaterial\") {\n // if it is a PBR material in MetallicRoughness Mode:\n if (material.metallicRoughnessTexture !== null) {\n defines.push(\"#define ORMTEXTURE\");\n defines.push(`#define REFLECTIVITY_UV${material.metallicRoughnessTexture.coordinatesIndex + 1}`);\n defines.push(\"#define METALLICWORKFLOW\");\n needUv = true;\n metallicWorkflow = true;\n }\n if (material.metallic !== null) {\n defines.push(\"#define METALLIC\");\n defines.push(\"#define METALLICWORKFLOW\");\n metallicWorkflow = true;\n }\n if (material.roughness !== null) {\n defines.push(\"#define ROUGHNESS\");\n defines.push(\"#define METALLICWORKFLOW\");\n metallicWorkflow = true;\n }\n if (metallicWorkflow) {\n if (material.baseTexture !== null) {\n defines.push(\"#define ALBEDOTEXTURE\");\n defines.push(`#define ALBEDO_UV${material.baseTexture.coordinatesIndex + 1}`);\n if (material.baseTexture.gammaSpace) {\n defines.push(\"#define GAMMAALBEDO\");\n }\n needUv = true;\n }\n if (material.baseColor !== null) {\n defines.push(\"#define ALBEDOCOLOR\");\n }\n }\n }\n else if (material.getClassName() === \"PBRSpecularGlossinessMaterial\") {\n // if it is a PBR material in Specular/Glossiness Mode:\n if (material.specularGlossinessTexture !== null) {\n defines.push(\"#define SPECULARGLOSSINESSTEXTURE\");\n defines.push(`#define REFLECTIVITY_UV${material.specularGlossinessTexture.coordinatesIndex + 1}`);\n needUv = true;\n if (material.specularGlossinessTexture.gammaSpace) {\n defines.push(\"#define GAMMAREFLECTIVITYTEXTURE\");\n }\n }\n else {\n if (material.specularColor !== null) {\n defines.push(\"#define REFLECTIVITYCOLOR\");\n }\n }\n if (material.glossiness !== null) {\n defines.push(\"#define GLOSSINESS\");\n }\n }\n else if (material.getClassName() === \"PBRMaterial\") {\n // if it is the bigger PBRMaterial\n if (material.metallicTexture !== null) {\n defines.push(\"#define ORMTEXTURE\");\n defines.push(`#define REFLECTIVITY_UV${material.metallicTexture.coordinatesIndex + 1}`);\n defines.push(\"#define METALLICWORKFLOW\");\n needUv = true;\n metallicWorkflow = true;\n }\n if (material.metallic !== null) {\n defines.push(\"#define METALLIC\");\n defines.push(\"#define METALLICWORKFLOW\");\n metallicWorkflow = true;\n }\n if (material.roughness !== null) {\n defines.push(\"#define ROUGHNESS\");\n defines.push(\"#define METALLICWORKFLOW\");\n metallicWorkflow = true;\n }\n if (metallicWorkflow) {\n if (material.albedoTexture !== null) {\n defines.push(\"#define ALBEDOTEXTURE\");\n defines.push(`#define ALBEDO_UV${material.albedoTexture.coordinatesIndex + 1}`);\n if (material.albedoTexture.gammaSpace) {\n defines.push(\"#define GAMMAALBEDO\");\n }\n needUv = true;\n }\n if (material.albedoColor !== null) {\n defines.push(\"#define ALBEDOCOLOR\");\n }\n }\n else {\n // SpecularGlossiness Model\n if (material.reflectivityTexture !== null) {\n defines.push(\"#define SPECULARGLOSSINESSTEXTURE\");\n defines.push(`#define REFLECTIVITY_UV${material.reflectivityTexture.coordinatesIndex + 1}`);\n if (material.reflectivityTexture.gammaSpace) {\n defines.push(\"#define GAMMAREFLECTIVITYTEXTURE\");\n }\n needUv = true;\n }\n else if (material.reflectivityColor !== null) {\n defines.push(\"#define REFLECTIVITYCOLOR\");\n }\n if (material.microSurface !== null) {\n defines.push(\"#define GLOSSINESS\");\n }\n }\n }\n else if (material.getClassName() === \"StandardMaterial\") {\n // if StandardMaterial:\n if (material.specularTexture !== null) {\n defines.push(\"#define REFLECTIVITYTEXTURE\");\n defines.push(`#define REFLECTIVITY_UV${material.specularTexture.coordinatesIndex + 1}`);\n if (material.specularTexture.gammaSpace) {\n defines.push(\"#define GAMMAREFLECTIVITYTEXTURE\");\n }\n needUv = true;\n }\n if (material.specularColor !== null) {\n defines.push(\"#define REFLECTIVITYCOLOR\");\n }\n }\n }\n if (needUv) {\n defines.push(\"#define NEED_UV\");\n if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {\n attribs.push(VertexBuffer.UVKind);\n defines.push(\"#define UV1\");\n }\n if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {\n attribs.push(VertexBuffer.UV2Kind);\n defines.push(\"#define UV2\");\n }\n }\n }\n // PrePass\n if (this._linkedWithPrePass) {\n defines.push(\"#define PREPASS\");\n if (this._depthIndex !== -1) {\n defines.push(\"#define DEPTH_INDEX \" + this._depthIndex);\n defines.push(\"#define PREPASS_DEPTH\");\n }\n if (this._normalIndex !== -1) {\n defines.push(\"#define NORMAL_INDEX \" + this._normalIndex);\n defines.push(\"#define PREPASS_NORMAL\");\n }\n }\n // Buffers\n if (this._enablePosition) {\n defines.push(\"#define POSITION\");\n defines.push(\"#define POSITION_INDEX \" + this._positionIndex);\n }\n if (this._enableVelocity) {\n defines.push(\"#define VELOCITY\");\n defines.push(\"#define VELOCITY_INDEX \" + this._velocityIndex);\n if (this.excludedSkinnedMeshesFromVelocity.indexOf(mesh) === -1) {\n defines.push(\"#define BONES_VELOCITY_ENABLED\");\n }\n }\n if (this._enableReflectivity) {\n defines.push(\"#define REFLECTIVITY\");\n defines.push(\"#define REFLECTIVITY_INDEX \" + this._reflectivityIndex);\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders) {\n attribs.push(VertexBuffer.MatricesIndicesKind);\n attribs.push(VertexBuffer.MatricesWeightsKind);\n if (mesh.numBoneInfluencers > 4) {\n attribs.push(VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(VertexBuffer.MatricesWeightsExtraKind);\n }\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n defines.push(\"#define BonesPerMesh \" + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Morph targets\n const morphTargetManager = mesh.morphTargetManager;\n let numMorphInfluencers = 0;\n if (morphTargetManager) {\n if (morphTargetManager.numInfluencers > 0) {\n numMorphInfluencers = morphTargetManager.numInfluencers;\n defines.push(\"#define MORPHTARGETS\");\n defines.push(\"#define NUM_MORPH_INFLUENCERS \" + numMorphInfluencers);\n if (morphTargetManager.isUsingTextureForTargets) {\n defines.push(\"#define MORPHTARGETS_TEXTURE\");\n }\n MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, numMorphInfluencers);\n }\n }\n // Instances\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n MaterialHelper.PushAttributesForInstances(attribs, this._enableVelocity);\n if (subMesh.getRenderingMesh().hasThinInstances) {\n defines.push(\"#define THIN_INSTANCES\");\n }\n }\n // Setup textures count\n if (this._linkedWithPrePass) {\n defines.push(\"#define RENDER_TARGET_COUNT \" + this._attachmentsFromPrePass.length);\n }\n else {\n defines.push(\"#define RENDER_TARGET_COUNT \" + this._multiRenderTarget.textures.length);\n }\n prepareStringDefinesForClipPlanes(material, this._scene, defines);\n // Get correct effect\n const engine = this._scene.getEngine();\n const drawWrapper = subMesh._getDrawWrapper(undefined, true);\n const cachedDefines = drawWrapper.defines;\n const join = defines.join(\"\\n\");\n if (cachedDefines !== join) {\n drawWrapper.setEffect(engine.createEffect(\"geometry\", {\n attributes: attribs,\n uniformsNames: uniforms,\n samplers: [\"diffuseSampler\", \"bumpSampler\", \"reflectivitySampler\", \"albedoSampler\", \"morphTargets\"],\n defines: join,\n onCompiled: null,\n fallbacks: null,\n onError: null,\n uniformBuffersNames: [\"Scene\"],\n indexParameters: { buffersCount: this._multiRenderTarget.textures.length - 1, maxSimultaneousMorphTargets: numMorphInfluencers },\n }, engine), join);\n }\n return drawWrapper.effect.isReady();\n }\n /**\n * Gets the current underlying G Buffer.\n * @returns the buffer\n */\n getGBuffer() {\n return this._multiRenderTarget;\n }\n /**\n * Gets the number of samples used to render the buffer (anti aliasing).\n */\n get samples() {\n return this._multiRenderTarget.samples;\n }\n /**\n * Sets the number of samples used to render the buffer (anti aliasing).\n */\n set samples(value) {\n this._multiRenderTarget.samples = value;\n }\n /**\n * Disposes the renderer and frees up associated resources.\n */\n dispose() {\n if (this._resizeObserver) {\n const engine = this._scene.getEngine();\n engine.onResizeObservable.remove(this._resizeObserver);\n this._resizeObserver = null;\n }\n this.getGBuffer().dispose();\n }\n _assignRenderTargetIndices() {\n const textureNames = [];\n let count = 2;\n textureNames.push(\"gBuffer_Depth\", \"gBuffer_Normal\");\n if (this._enablePosition) {\n this._positionIndex = count;\n count++;\n textureNames.push(\"gBuffer_Position\");\n }\n if (this._enableVelocity) {\n this._velocityIndex = count;\n count++;\n textureNames.push(\"gBuffer_Velocity\");\n }\n if (this._enableReflectivity) {\n this._reflectivityIndex = count;\n count++;\n textureNames.push(\"gBuffer_Reflectivity\");\n }\n return [count, textureNames];\n }\n _createRenderTargets() {\n const engine = this._scene.getEngine();\n const [count, textureNames] = this._assignRenderTargetIndices();\n let type = 0;\n if (engine._caps.textureFloat && engine._caps.textureFloatLinearFiltering) {\n type = 1;\n }\n else if (engine._caps.textureHalfFloat && engine._caps.textureHalfFloatLinearFiltering) {\n type = 2;\n }\n this._multiRenderTarget = new MultiRenderTarget(\"gBuffer\", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true, defaultType: type, depthTextureFormat: this._depthFormat }, textureNames.concat(\"gBuffer_DepthBuffer\"));\n if (!this.isSupported) {\n return;\n }\n this._multiRenderTarget.wrapU = Texture.CLAMP_ADDRESSMODE;\n this._multiRenderTarget.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._multiRenderTarget.refreshRate = 1;\n this._multiRenderTarget.renderParticles = false;\n this._multiRenderTarget.renderList = null;\n // Depth is always the first texture in the geometry buffer renderer!\n const layoutAttachmentsAll = [true];\n const layoutAttachmentsAllButDepth = [false];\n const layoutAttachmentsDepthOnly = [true];\n for (let i = 1; i < count; ++i) {\n layoutAttachmentsAll.push(true);\n layoutAttachmentsDepthOnly.push(false);\n layoutAttachmentsAllButDepth.push(true);\n }\n const attachmentsAll = engine.buildTextureLayout(layoutAttachmentsAll);\n const attachmentsAllButDepth = engine.buildTextureLayout(layoutAttachmentsAllButDepth);\n const attachmentsDepthOnly = engine.buildTextureLayout(layoutAttachmentsDepthOnly);\n this._multiRenderTarget.onClearObservable.add((engine) => {\n engine.bindAttachments(this.useSpecificClearForDepthTexture ? attachmentsAllButDepth : attachmentsAll);\n engine.clear(this._clearColor, true, true, true);\n if (this.useSpecificClearForDepthTexture) {\n engine.bindAttachments(attachmentsDepthOnly);\n engine.clear(this._clearDepthColor, true, true, true);\n }\n engine.bindAttachments(attachmentsAll);\n });\n this._resizeObserver = engine.onResizeObservable.add(() => {\n if (this._multiRenderTarget) {\n this._multiRenderTarget.resize({ width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio });\n }\n });\n // Custom render function\n const renderSubMesh = (subMesh) => {\n const renderingMesh = subMesh.getRenderingMesh();\n const effectiveMesh = subMesh.getEffectiveMesh();\n const scene = this._scene;\n const engine = scene.getEngine();\n const material = subMesh.getMaterial();\n if (!material) {\n return;\n }\n effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;\n // Velocity\n if (this._enableVelocity && !this._previousTransformationMatrices[effectiveMesh.uniqueId]) {\n this._previousTransformationMatrices[effectiveMesh.uniqueId] = {\n world: Matrix.Identity(),\n viewProjection: scene.getTransformMatrix(),\n };\n if (renderingMesh.skeleton) {\n const bonesTransformations = renderingMesh.skeleton.getTransformMatrices(renderingMesh);\n this._previousBonesTransformationMatrices[renderingMesh.uniqueId] = this._copyBonesTransformationMatrices(bonesTransformations, new Float32Array(bonesTransformations.length));\n }\n }\n // Managing instances\n const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());\n if (batch.mustReturn) {\n return;\n }\n const hardwareInstancedRendering = engine.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null || renderingMesh.hasThinInstances);\n const world = effectiveMesh.getWorldMatrix();\n if (this.isReady(subMesh, hardwareInstancedRendering)) {\n const drawWrapper = subMesh._getDrawWrapper();\n if (!drawWrapper) {\n return;\n }\n const effect = drawWrapper.effect;\n engine.enableEffect(drawWrapper);\n if (!hardwareInstancedRendering) {\n renderingMesh._bind(subMesh, effect, material.fillMode);\n }\n if (!this._useUbo) {\n effect.setMatrix(\"viewProjection\", scene.getTransformMatrix());\n effect.setMatrix(\"view\", scene.getViewMatrix());\n }\n else {\n MaterialHelper.BindSceneUniformBuffer(effect, this._scene.getSceneUniformBuffer());\n this._scene.finalizeSceneUbo();\n }\n let sideOrientation;\n const instanceDataStorage = renderingMesh._instanceDataStorage;\n if (!instanceDataStorage.isFrozen && (material.backFaceCulling || renderingMesh.overrideMaterialSideOrientation !== null)) {\n const mainDeterminant = effectiveMesh._getWorldMatrixDeterminant();\n sideOrientation = renderingMesh.overrideMaterialSideOrientation;\n if (sideOrientation === null) {\n sideOrientation = material.sideOrientation;\n }\n if (mainDeterminant < 0) {\n sideOrientation = sideOrientation === Material.ClockWiseSideOrientation ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation;\n }\n }\n else {\n sideOrientation = instanceDataStorage.sideOrientation;\n }\n material._preBind(drawWrapper, sideOrientation);\n // Alpha test\n if (material.needAlphaTesting()) {\n const alphaTexture = material.getAlphaTestTexture();\n if (alphaTexture) {\n effect.setTexture(\"diffuseSampler\", alphaTexture);\n effect.setMatrix(\"diffuseMatrix\", alphaTexture.getTextureMatrix());\n }\n }\n // Bump\n if (material.bumpTexture && scene.getEngine().getCaps().standardDerivatives && MaterialFlags.BumpTextureEnabled) {\n effect.setFloat3(\"vBumpInfos\", material.bumpTexture.coordinatesIndex, 1.0 / material.bumpTexture.level, material.parallaxScaleBias);\n effect.setMatrix(\"bumpMatrix\", material.bumpTexture.getTextureMatrix());\n effect.setTexture(\"bumpSampler\", material.bumpTexture);\n effect.setFloat2(\"vTangentSpaceParams\", material.invertNormalMapX ? -1.0 : 1.0, material.invertNormalMapY ? -1.0 : 1.0);\n }\n // Reflectivity\n if (this._enableReflectivity) {\n // for PBR materials: cf. https://doc.babylonjs.com/features/featuresDeepDive/materials/using/masterPBR\n if (material.getClassName() === \"PBRMetallicRoughnessMaterial\") {\n // if it is a PBR material in MetallicRoughness Mode:\n if (material.metallicRoughnessTexture !== null) {\n effect.setTexture(\"reflectivitySampler\", material.metallicRoughnessTexture);\n effect.setMatrix(\"reflectivityMatrix\", material.metallicRoughnessTexture.getTextureMatrix());\n }\n if (material.metallic !== null) {\n effect.setFloat(\"metallic\", material.metallic);\n }\n if (material.roughness !== null) {\n effect.setFloat(\"glossiness\", 1.0 - material.roughness);\n }\n if (material.baseTexture !== null) {\n effect.setTexture(\"albedoSampler\", material.baseTexture);\n effect.setMatrix(\"albedoMatrix\", material.baseTexture.getTextureMatrix());\n }\n if (material.baseColor !== null) {\n effect.setColor3(\"albedoColor\", material.baseColor);\n }\n }\n else if (material.getClassName() === \"PBRSpecularGlossinessMaterial\") {\n // if it is a PBR material in Specular/Glossiness Mode:\n if (material.specularGlossinessTexture !== null) {\n effect.setTexture(\"reflectivitySampler\", material.specularGlossinessTexture);\n effect.setMatrix(\"reflectivityMatrix\", material.specularGlossinessTexture.getTextureMatrix());\n }\n else {\n if (material.specularColor !== null) {\n effect.setColor3(\"reflectivityColor\", material.specularColor);\n }\n }\n if (material.glossiness !== null) {\n effect.setFloat(\"glossiness\", material.glossiness);\n }\n }\n else if (material.getClassName() === \"PBRMaterial\") {\n // if it is the bigger PBRMaterial\n if (material.metallicTexture !== null) {\n effect.setTexture(\"reflectivitySampler\", material.metallicTexture);\n effect.setMatrix(\"reflectivityMatrix\", material.metallicTexture.getTextureMatrix());\n }\n if (material.metallic !== null) {\n effect.setFloat(\"metallic\", material.metallic);\n }\n if (material.roughness !== null) {\n effect.setFloat(\"glossiness\", 1.0 - material.roughness);\n }\n if (material.roughness !== null || material.metallic !== null || material.metallicTexture !== null) {\n // MetallicRoughness Model\n if (material.albedoTexture !== null) {\n effect.setTexture(\"albedoSampler\", material.albedoTexture);\n effect.setMatrix(\"albedoMatrix\", material.albedoTexture.getTextureMatrix());\n }\n if (material.albedoColor !== null) {\n effect.setColor3(\"albedoColor\", material.albedoColor);\n }\n }\n else {\n // SpecularGlossiness Model\n if (material.reflectivityTexture !== null) {\n effect.setTexture(\"reflectivitySampler\", material.reflectivityTexture);\n effect.setMatrix(\"reflectivityMatrix\", material.reflectivityTexture.getTextureMatrix());\n }\n else if (material.reflectivityColor !== null) {\n effect.setColor3(\"reflectivityColor\", material.reflectivityColor);\n }\n if (material.microSurface !== null) {\n effect.setFloat(\"glossiness\", material.microSurface);\n }\n }\n }\n else if (material.getClassName() === \"StandardMaterial\") {\n // if StandardMaterial:\n if (material.specularTexture !== null) {\n effect.setTexture(\"reflectivitySampler\", material.specularTexture);\n effect.setMatrix(\"reflectivityMatrix\", material.specularTexture.getTextureMatrix());\n }\n if (material.specularColor !== null) {\n effect.setColor3(\"reflectivityColor\", material.specularColor);\n }\n }\n }\n // Clip plane\n bindClipPlane(effect, material, this._scene);\n // Bones\n if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) {\n effect.setMatrices(\"mBones\", renderingMesh.skeleton.getTransformMatrices(renderingMesh));\n if (this._enableVelocity) {\n effect.setMatrices(\"mPreviousBones\", this._previousBonesTransformationMatrices[renderingMesh.uniqueId]);\n }\n }\n // Morph targets\n MaterialHelper.BindMorphTargetParameters(renderingMesh, effect);\n if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) {\n renderingMesh.morphTargetManager._bind(effect);\n }\n // Velocity\n if (this._enableVelocity) {\n effect.setMatrix(\"previousWorld\", this._previousTransformationMatrices[effectiveMesh.uniqueId].world);\n effect.setMatrix(\"previousViewProjection\", this._previousTransformationMatrices[effectiveMesh.uniqueId].viewProjection);\n }\n if (hardwareInstancedRendering && renderingMesh.hasThinInstances) {\n effect.setMatrix(\"world\", world);\n }\n // Draw\n renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, w) => {\n if (!isInstance) {\n effect.setMatrix(\"world\", w);\n }\n });\n }\n // Velocity\n if (this._enableVelocity) {\n this._previousTransformationMatrices[effectiveMesh.uniqueId].world = world.clone();\n this._previousTransformationMatrices[effectiveMesh.uniqueId].viewProjection = this._scene.getTransformMatrix().clone();\n if (renderingMesh.skeleton) {\n this._copyBonesTransformationMatrices(renderingMesh.skeleton.getTransformMatrices(renderingMesh), this._previousBonesTransformationMatrices[effectiveMesh.uniqueId]);\n }\n }\n };\n this._multiRenderTarget.customIsReadyFunction = (mesh, refreshRate, preWarm) => {\n if ((preWarm || refreshRate === 0) && mesh.subMeshes) {\n for (let i = 0; i < mesh.subMeshes.length; ++i) {\n const subMesh = mesh.subMeshes[i];\n const material = subMesh.getMaterial();\n const renderingMesh = subMesh.getRenderingMesh();\n if (!material) {\n continue;\n }\n const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());\n const hardwareInstancedRendering = engine.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null || renderingMesh.hasThinInstances);\n if (!this.isReady(subMesh, hardwareInstancedRendering)) {\n return false;\n }\n }\n }\n return true;\n };\n this._multiRenderTarget.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => {\n let index;\n if (this._linkedWithPrePass) {\n if (!this._prePassRenderer.enabled) {\n return;\n }\n this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass);\n }\n if (depthOnlySubMeshes.length) {\n engine.setColorWrite(false);\n for (index = 0; index < depthOnlySubMeshes.length; index++) {\n renderSubMesh(depthOnlySubMeshes.data[index]);\n }\n engine.setColorWrite(true);\n }\n for (index = 0; index < opaqueSubMeshes.length; index++) {\n renderSubMesh(opaqueSubMeshes.data[index]);\n }\n engine.setDepthWrite(false);\n for (index = 0; index < alphaTestSubMeshes.length; index++) {\n renderSubMesh(alphaTestSubMeshes.data[index]);\n }\n if (this.renderTransparentMeshes) {\n for (index = 0; index < transparentSubMeshes.length; index++) {\n renderSubMesh(transparentSubMeshes.data[index]);\n }\n }\n engine.setDepthWrite(true);\n };\n }\n // Copies the bones transformation matrices into the target array and returns the target's reference\n _copyBonesTransformationMatrices(source, target) {\n for (let i = 0; i < source.length; i++) {\n target[i] = source[i];\n }\n return target;\n }\n}\n/**\n * Constant used to retrieve the depth texture index in the G-Buffer textures array\n * using getIndex(GeometryBufferRenderer.DEPTH_TEXTURE_INDEX)\n */\nGeometryBufferRenderer.DEPTH_TEXTURE_TYPE = 0;\n/**\n * Constant used to retrieve the normal texture index in the G-Buffer textures array\n * using getIndex(GeometryBufferRenderer.NORMAL_TEXTURE_INDEX)\n */\nGeometryBufferRenderer.NORMAL_TEXTURE_TYPE = 1;\n/**\n * Constant used to retrieve the position texture index in the G-Buffer textures array\n * using getIndex(GeometryBufferRenderer.POSITION_TEXTURE_INDEX)\n */\nGeometryBufferRenderer.POSITION_TEXTURE_TYPE = 2;\n/**\n * Constant used to retrieve the velocity texture index in the G-Buffer textures array\n * using getIndex(GeometryBufferRenderer.VELOCITY_TEXTURE_INDEX)\n */\nGeometryBufferRenderer.VELOCITY_TEXTURE_TYPE = 3;\n/**\n * Constant used to retrieve the reflectivity texture index in the G-Buffer textures array\n * using the getIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE)\n */\nGeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE = 4;\n/**\n * @internal\n */\nGeometryBufferRenderer._SceneComponentInitialization = (_) => {\n throw _WarnImport(\"GeometryBufferRendererSceneComponent\");\n};\n//# sourceMappingURL=geometryBufferRenderer.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { Matrix, TmpVectors, Vector2 } from \"../Maths/math.vector.js\";\nimport { PostProcess } from \"./postProcess.js\";\n\nimport { GeometryBufferRenderer } from \"../Rendering/geometryBufferRenderer.js\";\nimport { MotionBlurConfiguration } from \"../Rendering/motionBlurConfiguration.js\";\nimport \"../Animations/animatable.js\";\nimport \"../Rendering/geometryBufferRendererSceneComponent.js\";\nimport \"../Shaders/motionBlur.fragment.js\";\nimport { serialize, SerializationHelper } from \"../Misc/decorators.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\n/**\n * The Motion Blur Post Process which blurs an image based on the objects velocity in scene.\n * Velocity can be affected by each object's rotation, position and scale depending on the transformation speed.\n * As an example, all you have to do is to create the post-process:\n * var mb = new BABYLON.MotionBlurPostProcess(\n * 'mb', // The name of the effect.\n * scene, // The scene containing the objects to blur according to their velocity.\n * 1.0, // The required width/height ratio to downsize to before computing the render pass.\n * camera // The camera to apply the render pass to.\n * );\n * Then, all objects moving, rotating and/or scaling will be blurred depending on the transformation speed.\n */\nexport class MotionBlurPostProcess extends PostProcess {\n /**\n * Gets the number of iterations are used for motion blur quality. Default value is equal to 32\n */\n get motionBlurSamples() {\n return this._motionBlurSamples;\n }\n /**\n * Sets the number of iterations to be used for motion blur quality\n */\n set motionBlurSamples(samples) {\n this._motionBlurSamples = samples;\n this._updateEffect();\n }\n /**\n * Gets whether or not the motion blur post-process is in object based mode.\n */\n get isObjectBased() {\n return this._isObjectBased;\n }\n /**\n * Sets whether or not the motion blur post-process is in object based mode.\n */\n set isObjectBased(value) {\n if (this._isObjectBased === value) {\n return;\n }\n this._isObjectBased = value;\n this._applyMode();\n }\n get _geometryBufferRenderer() {\n if (!this._forceGeometryBuffer) {\n return null;\n }\n return this._scene.geometryBufferRenderer;\n }\n get _prePassRenderer() {\n if (this._forceGeometryBuffer) {\n return null;\n }\n return this._scene.prePassRenderer;\n }\n /**\n * Gets a string identifying the name of the class\n * @returns \"MotionBlurPostProcess\" string\n */\n getClassName() {\n return \"MotionBlurPostProcess\";\n }\n /**\n * Creates a new instance MotionBlurPostProcess\n * @param name The name of the effect.\n * @param scene The scene containing the objects to blur according to their velocity.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: true)\n * @param forceGeometryBuffer If this post process should use geometry buffer instead of prepass (default: false)\n */\n constructor(name, scene, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false, forceGeometryBuffer = false) {\n super(name, \"motionBlur\", [\"motionStrength\", \"motionScale\", \"screenSize\", \"inverseViewProjection\", \"prevViewProjection\", \"projection\"], [\"velocitySampler\", \"depthSampler\"], options, camera, samplingMode, engine, reusable, \"#define GEOMETRY_SUPPORTED\\n#define SAMPLES 64.0\\n#define OBJECT_BASED\", textureType, undefined, null, blockCompilation);\n /**\n * Defines how much the image is blurred by the movement. Default value is equal to 1\n */\n this.motionStrength = 1;\n this._motionBlurSamples = 32;\n this._isObjectBased = true;\n this._forceGeometryBuffer = false;\n this._invViewProjection = null;\n this._previousViewProjection = null;\n this._forceGeometryBuffer = forceGeometryBuffer;\n // Set up assets\n if (this._forceGeometryBuffer) {\n scene.enableGeometryBufferRenderer();\n if (this._geometryBufferRenderer) {\n this._geometryBufferRenderer.enableVelocity = true;\n }\n }\n else {\n scene.enablePrePassRenderer();\n if (this._prePassRenderer) {\n this._prePassRenderer.markAsDirty();\n this._prePassEffectConfiguration = new MotionBlurConfiguration();\n }\n }\n this._applyMode();\n }\n /**\n * Excludes the given skinned mesh from computing bones velocities.\n * Computing bones velocities can have a cost and that cost. The cost can be saved by calling this function and by passing the skinned mesh reference to ignore.\n * @param skinnedMesh The mesh containing the skeleton to ignore when computing the velocity map.\n */\n excludeSkinnedMesh(skinnedMesh) {\n if (skinnedMesh.skeleton) {\n let list;\n if (this._geometryBufferRenderer) {\n list = this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;\n }\n else if (this._prePassRenderer) {\n list = this._prePassRenderer.excludedSkinnedMesh;\n }\n else {\n return;\n }\n list.push(skinnedMesh);\n }\n }\n /**\n * Removes the given skinned mesh from the excluded meshes to integrate bones velocities while rendering the velocity map.\n * @param skinnedMesh The mesh containing the skeleton that has been ignored previously.\n * @see excludeSkinnedMesh to exclude a skinned mesh from bones velocity computation.\n */\n removeExcludedSkinnedMesh(skinnedMesh) {\n if (skinnedMesh.skeleton) {\n let list;\n if (this._geometryBufferRenderer) {\n list = this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;\n }\n else if (this._prePassRenderer) {\n list = this._prePassRenderer.excludedSkinnedMesh;\n }\n else {\n return;\n }\n const index = list.indexOf(skinnedMesh);\n if (index !== -1) {\n list.splice(index, 1);\n }\n }\n }\n /**\n * Disposes the post process.\n * @param camera The camera to dispose the post process on.\n */\n dispose(camera) {\n if (this._geometryBufferRenderer) {\n // Clear previous transformation matrices dictionary used to compute objects velocities\n this._geometryBufferRenderer._previousTransformationMatrices = {};\n this._geometryBufferRenderer._previousBonesTransformationMatrices = {};\n this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity = [];\n }\n super.dispose(camera);\n }\n /**\n * Called on the mode changed (object based or screen based).\n */\n _applyMode() {\n if (!this._geometryBufferRenderer && !this._prePassRenderer) {\n // We can't get a velocity or depth texture. So, work as a passthrough.\n Logger.Warn(\"Multiple Render Target support needed to compute object based motion blur\");\n return this.updateEffect();\n }\n this._updateEffect();\n this._invViewProjection = null;\n this._previousViewProjection = null;\n if (this.isObjectBased) {\n if (this._prePassRenderer && this._prePassEffectConfiguration) {\n this._prePassEffectConfiguration.texturesRequired[0] = 2;\n }\n this.onApply = (effect) => this._onApplyObjectBased(effect);\n }\n else {\n this._invViewProjection = Matrix.Identity();\n this._previousViewProjection = this._scene.getTransformMatrix().clone();\n if (this._prePassRenderer && this._prePassEffectConfiguration) {\n this._prePassEffectConfiguration.texturesRequired[0] = 5;\n }\n this.onApply = (effect) => this._onApplyScreenBased(effect);\n }\n }\n /**\n * Called on the effect is applied when the motion blur post-process is in object based mode.\n * @param effect\n */\n _onApplyObjectBased(effect) {\n effect.setVector2(\"screenSize\", new Vector2(this.width, this.height));\n effect.setFloat(\"motionScale\", this._scene.getAnimationRatio());\n effect.setFloat(\"motionStrength\", this.motionStrength);\n if (this._geometryBufferRenderer) {\n const velocityIndex = this._geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE);\n effect.setTexture(\"velocitySampler\", this._geometryBufferRenderer.getGBuffer().textures[velocityIndex]);\n }\n else if (this._prePassRenderer) {\n const velocityIndex = this._prePassRenderer.getIndex(2);\n effect.setTexture(\"velocitySampler\", this._prePassRenderer.getRenderTarget().textures[velocityIndex]);\n }\n }\n /**\n * Called on the effect is applied when the motion blur post-process is in screen based mode.\n * @param effect\n */\n _onApplyScreenBased(effect) {\n const viewProjection = TmpVectors.Matrix[0];\n viewProjection.copyFrom(this._scene.getTransformMatrix());\n viewProjection.invertToRef(this._invViewProjection);\n effect.setMatrix(\"inverseViewProjection\", this._invViewProjection);\n effect.setMatrix(\"prevViewProjection\", this._previousViewProjection);\n this._previousViewProjection.copyFrom(viewProjection);\n effect.setMatrix(\"projection\", this._scene.getProjectionMatrix());\n effect.setVector2(\"screenSize\", new Vector2(this.width, this.height));\n effect.setFloat(\"motionScale\", this._scene.getAnimationRatio());\n effect.setFloat(\"motionStrength\", this.motionStrength);\n if (this._geometryBufferRenderer) {\n const depthIndex = this._geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.DEPTH_TEXTURE_TYPE);\n effect.setTexture(\"depthSampler\", this._geometryBufferRenderer.getGBuffer().textures[depthIndex]);\n }\n else if (this._prePassRenderer) {\n const depthIndex = this._prePassRenderer.getIndex(5);\n effect.setTexture(\"depthSampler\", this._prePassRenderer.getRenderTarget().textures[depthIndex]);\n }\n }\n /**\n * Called on the effect must be updated (changed mode, samples count, etc.).\n */\n _updateEffect() {\n if (this._geometryBufferRenderer || this._prePassRenderer) {\n const defines = [\n \"#define GEOMETRY_SUPPORTED\",\n \"#define SAMPLES \" + this._motionBlurSamples.toFixed(1),\n this._isObjectBased ? \"#define OBJECT_BASED\" : \"#define SCREEN_BASED\",\n ];\n this.updateEffect(defines.join(\"\\n\"));\n }\n }\n /**\n * @internal\n */\n static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) {\n return SerializationHelper.Parse(() => {\n return new MotionBlurPostProcess(parsedPostProcess.name, scene, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable, parsedPostProcess.textureType, false);\n }, parsedPostProcess, scene, rootUrl);\n }\n}\n__decorate([\n serialize()\n], MotionBlurPostProcess.prototype, \"motionStrength\", void 0);\n__decorate([\n serialize()\n], MotionBlurPostProcess.prototype, \"motionBlurSamples\", null);\n__decorate([\n serialize()\n], MotionBlurPostProcess.prototype, \"isObjectBased\", null);\nRegisterClass(\"BABYLON.MotionBlurPostProcess\", MotionBlurPostProcess);\n//# sourceMappingURL=motionBlurPostProcess.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { PostProcess } from \"./postProcess.js\";\n\nimport { GeometryBufferRenderer } from \"../Rendering/geometryBufferRenderer.js\";\nimport { serialize, SerializationHelper } from \"../Misc/decorators.js\";\nimport { ScreenSpaceReflectionsConfiguration } from \"../Rendering/screenSpaceReflectionsConfiguration.js\";\nimport \"../Shaders/screenSpaceReflection.fragment.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\n/**\n * The ScreenSpaceReflectionPostProcess performs realtime reflections using only and only the available informations on the screen (positions and normals).\n * Basically, the screen space reflection post-process will compute reflections according the material's reflectivity.\n * @deprecated Use the new SSRRenderingPipeline instead.\n */\nexport class ScreenSpaceReflectionPostProcess extends PostProcess {\n get _geometryBufferRenderer() {\n if (!this._forceGeometryBuffer) {\n return null;\n }\n return this._scene.geometryBufferRenderer;\n }\n get _prePassRenderer() {\n if (this._forceGeometryBuffer) {\n return null;\n }\n return this._scene.prePassRenderer;\n }\n /**\n * Gets a string identifying the name of the class\n * @returns \"ScreenSpaceReflectionPostProcess\" string\n */\n getClassName() {\n return \"ScreenSpaceReflectionPostProcess\";\n }\n /**\n * Creates a new instance of ScreenSpaceReflectionPostProcess.\n * @param name The name of the effect.\n * @param scene The scene containing the objects to calculate reflections.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: true)\n * @param forceGeometryBuffer If this post process should use geometry buffer instead of prepass (default: false)\n */\n constructor(name, scene, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false, forceGeometryBuffer = false) {\n super(name, \"screenSpaceReflection\", [\"projection\", \"view\", \"threshold\", \"reflectionSpecularFalloffExponent\", \"strength\", \"stepSize\", \"roughnessFactor\"], [\"textureSampler\", \"normalSampler\", \"positionSampler\", \"reflectivitySampler\"], options, camera, samplingMode, engine, reusable, \"#define SSR_SUPPORTED\\n#define REFLECTION_SAMPLES 64\\n#define SMOOTH_STEPS 5\\n\", textureType, undefined, null, blockCompilation);\n /**\n * Gets or sets a reflection threshold mainly used to adjust the reflection's height.\n */\n this.threshold = 1.2;\n /**\n * Gets or sets the current reflection strength. 1.0 is an ideal value but can be increased/decreased for particular results.\n */\n this.strength = 1;\n /**\n * Gets or sets the falloff exponent used while computing fresnel. More the exponent is high, more the reflections will be discrete.\n */\n this.reflectionSpecularFalloffExponent = 3;\n /**\n * Gets or sets the step size used to iterate until the effect finds the color of the reflection's pixel. Typically in interval [0.1, 1.0]\n */\n this.step = 1.0;\n /**\n * Gets or sets the factor applied when computing roughness. Default value is 0.2.\n */\n this.roughnessFactor = 0.2;\n this._forceGeometryBuffer = false;\n this._enableSmoothReflections = false;\n this._reflectionSamples = 64;\n this._smoothSteps = 5;\n this._forceGeometryBuffer = forceGeometryBuffer;\n if (this._forceGeometryBuffer) {\n // Get geometry buffer renderer and update effect\n const geometryBufferRenderer = scene.enableGeometryBufferRenderer();\n if (geometryBufferRenderer) {\n if (geometryBufferRenderer.isSupported) {\n geometryBufferRenderer.enablePosition = true;\n geometryBufferRenderer.enableReflectivity = true;\n }\n }\n }\n else {\n const prePassRenderer = scene.enablePrePassRenderer();\n prePassRenderer === null || prePassRenderer === void 0 ? void 0 : prePassRenderer.markAsDirty();\n this._prePassEffectConfiguration = new ScreenSpaceReflectionsConfiguration();\n }\n this._updateEffectDefines();\n // On apply, send uniforms\n this.onApply = (effect) => {\n const geometryBufferRenderer = this._geometryBufferRenderer;\n const prePassRenderer = this._prePassRenderer;\n if (!prePassRenderer && !geometryBufferRenderer) {\n return;\n }\n if (geometryBufferRenderer) {\n // Samplers\n const positionIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.POSITION_TEXTURE_TYPE);\n const roughnessIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE);\n effect.setTexture(\"normalSampler\", geometryBufferRenderer.getGBuffer().textures[1]);\n effect.setTexture(\"positionSampler\", geometryBufferRenderer.getGBuffer().textures[positionIndex]);\n effect.setTexture(\"reflectivitySampler\", geometryBufferRenderer.getGBuffer().textures[roughnessIndex]);\n }\n else if (prePassRenderer) {\n // Samplers\n const positionIndex = prePassRenderer.getIndex(1);\n const roughnessIndex = prePassRenderer.getIndex(3);\n const normalIndex = prePassRenderer.getIndex(6);\n effect.setTexture(\"normalSampler\", prePassRenderer.getRenderTarget().textures[normalIndex]);\n effect.setTexture(\"positionSampler\", prePassRenderer.getRenderTarget().textures[positionIndex]);\n effect.setTexture(\"reflectivitySampler\", prePassRenderer.getRenderTarget().textures[roughnessIndex]);\n }\n // Uniforms\n const camera = scene.activeCamera;\n if (!camera) {\n return;\n }\n const viewMatrix = camera.getViewMatrix(true);\n const projectionMatrix = camera.getProjectionMatrix(true);\n effect.setMatrix(\"projection\", projectionMatrix);\n effect.setMatrix(\"view\", viewMatrix);\n effect.setFloat(\"threshold\", this.threshold);\n effect.setFloat(\"reflectionSpecularFalloffExponent\", this.reflectionSpecularFalloffExponent);\n effect.setFloat(\"strength\", this.strength);\n effect.setFloat(\"stepSize\", this.step);\n effect.setFloat(\"roughnessFactor\", this.roughnessFactor);\n };\n this._isSceneRightHanded = scene.useRightHandedSystem;\n }\n /**\n * Gets whether or not smoothing reflections is enabled.\n * Enabling smoothing will require more GPU power and can generate a drop in FPS.\n */\n get enableSmoothReflections() {\n return this._enableSmoothReflections;\n }\n /**\n * Sets whether or not smoothing reflections is enabled.\n * Enabling smoothing will require more GPU power and can generate a drop in FPS.\n */\n set enableSmoothReflections(enabled) {\n if (enabled === this._enableSmoothReflections) {\n return;\n }\n this._enableSmoothReflections = enabled;\n this._updateEffectDefines();\n }\n /**\n * Gets the number of samples taken while computing reflections. More samples count is high,\n * more the post-process wil require GPU power and can generate a drop in FPS. Basically in interval [25, 100].\n */\n get reflectionSamples() {\n return this._reflectionSamples;\n }\n /**\n * Sets the number of samples taken while computing reflections. More samples count is high,\n * more the post-process wil require GPU power and can generate a drop in FPS. Basically in interval [25, 100].\n */\n set reflectionSamples(samples) {\n if (samples === this._reflectionSamples) {\n return;\n }\n this._reflectionSamples = samples;\n this._updateEffectDefines();\n }\n /**\n * Gets the number of samples taken while smoothing reflections. More samples count is high,\n * more the post-process will require GPU power and can generate a drop in FPS.\n * Default value (5.0) work pretty well in all cases but can be adjusted.\n */\n get smoothSteps() {\n return this._smoothSteps;\n }\n /*\n * Sets the number of samples taken while smoothing reflections. More samples count is high,\n * more the post-process will require GPU power and can generate a drop in FPS.\n * Default value (5.0) work pretty well in all cases but can be adjusted.\n */\n set smoothSteps(steps) {\n if (steps === this._smoothSteps) {\n return;\n }\n this._smoothSteps = steps;\n this._updateEffectDefines();\n }\n _updateEffectDefines() {\n const defines = [];\n if (this._geometryBufferRenderer || this._prePassRenderer) {\n defines.push(\"#define SSR_SUPPORTED\");\n }\n if (this._enableSmoothReflections) {\n defines.push(\"#define ENABLE_SMOOTH_REFLECTIONS\");\n }\n if (this._isSceneRightHanded) {\n defines.push(\"#define RIGHT_HANDED_SCENE\");\n }\n defines.push(\"#define REFLECTION_SAMPLES \" + (this._reflectionSamples >> 0));\n defines.push(\"#define SMOOTH_STEPS \" + (this._smoothSteps >> 0));\n this.updateEffect(defines.join(\"\\n\"));\n }\n /**\n * @internal\n */\n static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) {\n return SerializationHelper.Parse(() => {\n return new ScreenSpaceReflectionPostProcess(parsedPostProcess.name, scene, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.textureType, parsedPostProcess.reusable);\n }, parsedPostProcess, scene, rootUrl);\n }\n}\n__decorate([\n serialize()\n], ScreenSpaceReflectionPostProcess.prototype, \"threshold\", void 0);\n__decorate([\n serialize()\n], ScreenSpaceReflectionPostProcess.prototype, \"strength\", void 0);\n__decorate([\n serialize()\n], ScreenSpaceReflectionPostProcess.prototype, \"reflectionSpecularFalloffExponent\", void 0);\n__decorate([\n serialize()\n], ScreenSpaceReflectionPostProcess.prototype, \"step\", void 0);\n__decorate([\n serialize()\n], ScreenSpaceReflectionPostProcess.prototype, \"roughnessFactor\", void 0);\n__decorate([\n serialize()\n], ScreenSpaceReflectionPostProcess.prototype, \"enableSmoothReflections\", null);\n__decorate([\n serialize()\n], ScreenSpaceReflectionPostProcess.prototype, \"reflectionSamples\", null);\n__decorate([\n serialize()\n], ScreenSpaceReflectionPostProcess.prototype, \"smoothSteps\", null);\nRegisterClass(\"BABYLON.ScreenSpaceReflectionPostProcess\", ScreenSpaceReflectionPostProcess);\n//# sourceMappingURL=screenSpaceReflectionPostProcess.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"filterPixelShader\";\nconst shader = `varying vec2 vUV;\runiform sampler2D textureSampler;\runiform mat4 kernelMatrix;\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\r{\rvec3 baseColor=texture2D(textureSampler,vUV).rgb;\rvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\rgl_FragColor=vec4(updatedColor,1.0);\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const filterPixelShader = { name, shader };\n//# sourceMappingURL=filter.fragment.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { PostProcess } from \"./postProcess.js\";\nimport \"../Shaders/filter.fragment.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\nimport { serializeAsMatrix, SerializationHelper } from \"../Misc/decorators.js\";\n/**\n * Applies a kernel filter to the image\n */\nexport class FilterPostProcess extends PostProcess {\n /**\n * Gets a string identifying the name of the class\n * @returns \"FilterPostProcess\" string\n */\n getClassName() {\n return \"FilterPostProcess\";\n }\n /**\n *\n * @param name The name of the effect.\n * @param kernelMatrix The matrix to be applied to the image\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n */\n constructor(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {\n super(name, \"filter\", [\"kernelMatrix\"], null, options, camera, samplingMode, engine, reusable);\n this.kernelMatrix = kernelMatrix;\n this.onApply = (effect) => {\n effect.setMatrix(\"kernelMatrix\", this.kernelMatrix);\n };\n }\n /**\n * @internal\n */\n static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) {\n return SerializationHelper.Parse(() => {\n return new FilterPostProcess(parsedPostProcess.name, parsedPostProcess.kernelMatrix, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable);\n }, parsedPostProcess, scene, rootUrl);\n }\n}\n__decorate([\n serializeAsMatrix()\n], FilterPostProcess.prototype, \"kernelMatrix\", void 0);\nRegisterClass(\"BABYLON.FilterPostProcess\", FilterPostProcess);\n//# sourceMappingURL=filterPostProcess.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"fxaaPixelShader\";\nconst shader = `#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nuniform sampler2D textureSampler;\runiform vec2 texelSize;\rvarying vec2 vUV;\rvarying vec2 sampleCoordS;\rvarying vec2 sampleCoordE;\rvarying vec2 sampleCoordN;\rvarying vec2 sampleCoordW;\rvarying vec2 sampleCoordNW;\rvarying vec2 sampleCoordSE;\rvarying vec2 sampleCoordNE;\rvarying vec2 sampleCoordSW;\rconst float fxaaQualitySubpix=1.0;\rconst float fxaaQualityEdgeThreshold=0.166;\rconst float fxaaQualityEdgeThresholdMin=0.0833;\rconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\r#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\rvec2 posM;\rposM.x=vUV.x;\rposM.y=vUV.y;\rvec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);\rfloat lumaM=FxaaLuma(rgbyM);\rfloat lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));\rfloat lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));\rfloat lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));\rfloat lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));\rfloat maxSM=max(lumaS,lumaM);\rfloat minSM=min(lumaS,lumaM);\rfloat maxESM=max(lumaE,maxSM);\rfloat minESM=min(lumaE,minSM);\rfloat maxWN=max(lumaN,lumaW);\rfloat minWN=min(lumaN,lumaW);\rfloat rangeMax=max(maxWN,maxESM);\rfloat rangeMin=min(minWN,minESM);\rfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\rfloat range=rangeMax-rangeMin;\rfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\r#ifndef MALI\nif(range=edgeVert;\rfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\rif (!horzSpan)\r{\rlumaN=lumaW;\r}\rif (!horzSpan) \r{\rlumaS=lumaE;\r}\rif (horzSpan) \r{\rlengthSign=texelSize.y;\r}\rfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\rfloat gradientN=lumaN-lumaM;\rfloat gradientS=lumaS-lumaM;\rfloat lumaNN=lumaN+lumaM;\rfloat lumaSS=lumaS+lumaM;\rbool pairN=abs(gradientN)>=abs(gradientS);\rfloat gradient=max(abs(gradientN),abs(gradientS));\rif (pairN)\r{\rlengthSign=-lengthSign;\r}\rfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\rvec2 posB;\rposB.x=posM.x;\rposB.y=posM.y;\rvec2 offNP;\roffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\roffNP.y=(horzSpan) ? 0.0 : texelSize.y;\rif (!horzSpan) \r{\rposB.x+=lengthSign*0.5;\r}\rif (horzSpan)\r{\rposB.y+=lengthSign*0.5;\r}\rvec2 posN;\rposN.x=posB.x-offNP.x*1.5;\rposN.y=posB.y-offNP.y*1.5;\rvec2 posP;\rposP.x=posB.x+offNP.x*1.5;\rposP.y=posB.y+offNP.y*1.5;\rfloat subpixD=((-2.0)*subpixC)+3.0;\rfloat lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));\rfloat subpixE=subpixC*subpixC;\rfloat lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));\rif (!pairN) \r{\rlumaNN=lumaSS;\r}\rfloat gradientScaled=gradient*1.0/4.0;\rfloat lumaMM=lumaM-lumaNN*0.5;\rfloat subpixF=subpixD*subpixE;\rbool lumaMLTZero=lumaMM<0.0;\rlumaEndN-=lumaNN*0.5;\rlumaEndP-=lumaNN*0.5;\rbool doneN=abs(lumaEndN)>=gradientScaled;\rbool doneP=abs(lumaEndP)>=gradientScaled;\rif (!doneN) \r{\rposN.x-=offNP.x*3.0;\r}\rif (!doneN) \r{\rposN.y-=offNP.y*3.0;\r}\rbool doneNP=(!doneN) || (!doneP);\rif (!doneP) \r{\rposP.x+=offNP.x*3.0;\r}\rif (!doneP)\r{\rposP.y+=offNP.y*3.0;\r}\rif (doneNP)\r{\rif (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));\rif (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));\rif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\rif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\rdoneN=abs(lumaEndN)>=gradientScaled;\rdoneP=abs(lumaEndP)>=gradientScaled;\rif (!doneN) posN.x-=offNP.x*12.0;\rif (!doneN) posN.y-=offNP.y*12.0;\rdoneNP=(!doneN) || (!doneP);\rif (!doneP) posP.x+=offNP.x*12.0;\rif (!doneP) posP.y+=offNP.y*12.0;\r}\rfloat dstN=posM.x-posN.x;\rfloat dstP=posP.x-posM.x;\rif (!horzSpan)\r{\rdstN=posM.y-posN.y;\r}\rif (!horzSpan) \r{\rdstP=posP.y-posM.y;\r}\rbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\rfloat spanLength=(dstP+dstN);\rbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\rfloat spanLengthRcp=1.0/spanLength;\rbool directionN=dstN {\n const texelSize = this.texelSize;\n effect.setFloat2(\"texelSize\", texelSize.x, texelSize.y);\n });\n }\n _getDefines() {\n const engine = this.getEngine();\n if (!engine) {\n return null;\n }\n const glInfo = engine.getGlInfo();\n if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf(\"mali\") > -1) {\n return \"#define MALI 1\\n\";\n }\n return null;\n }\n /**\n * @internal\n */\n static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) {\n return SerializationHelper.Parse(() => {\n return new FxaaPostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable);\n }, parsedPostProcess, scene, rootUrl);\n }\n}\nRegisterClass(\"BABYLON.FxaaPostProcess\", FxaaPostProcess);\n//# sourceMappingURL=fxaaPostProcess.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/helperFunctions.js\";\nconst name = \"grainPixelShader\";\nconst shader = `#include\nuniform sampler2D textureSampler; \runiform float intensity;\runiform float animatedSeed;\rvarying vec2 vUV;\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\r{\rgl_FragColor=texture2D(textureSampler,vUV);\rvec2 seed=vUV*(animatedSeed);\rfloat grain=dither(seed,intensity);\rfloat lum=getLuminance(gl_FragColor.rgb);\rfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\rgl_FragColor.rgb+=grain*grainAmount;\rgl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const grainPixelShader = { name, shader };\n//# sourceMappingURL=grain.fragment.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { PostProcess } from \"./postProcess.js\";\n\nimport \"../Shaders/grain.fragment.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\nimport { serialize, SerializationHelper } from \"../Misc/decorators.js\";\n/**\n * The GrainPostProcess adds noise to the image at mid luminance levels\n */\nexport class GrainPostProcess extends PostProcess {\n /**\n * Gets a string identifying the name of the class\n * @returns \"GrainPostProcess\" string\n */\n getClassName() {\n return \"GrainPostProcess\";\n }\n /**\n * Creates a new instance of @see GrainPostProcess\n * @param name The name of the effect.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n constructor(name, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) {\n super(name, \"grain\", [\"intensity\", \"animatedSeed\"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation);\n /**\n * The intensity of the grain added (default: 30)\n */\n this.intensity = 30;\n /**\n * If the grain should be randomized on every frame\n */\n this.animated = false;\n this.onApplyObservable.add((effect) => {\n effect.setFloat(\"intensity\", this.intensity);\n effect.setFloat(\"animatedSeed\", this.animated ? Math.random() + 1 : 1);\n });\n }\n /**\n * @internal\n */\n static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) {\n return SerializationHelper.Parse(() => {\n return new GrainPostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable);\n }, parsedPostProcess, scene, rootUrl);\n }\n}\n__decorate([\n serialize()\n], GrainPostProcess.prototype, \"intensity\", void 0);\n__decorate([\n serialize()\n], GrainPostProcess.prototype, \"animated\", void 0);\nRegisterClass(\"BABYLON.GrainPostProcess\", GrainPostProcess);\n//# sourceMappingURL=grainPostProcess.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"highlightsPixelShader\";\nconst shader = `varying vec2 vUV;\runiform sampler2D textureSampler;\rconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \r{\rvec4 tex=texture2D(textureSampler,vUV);\rvec3 c=tex.rgb;\rfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\rgl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const highlightsPixelShader = { name, shader };\n//# sourceMappingURL=highlights.fragment.js.map","import { PostProcess } from \"./postProcess.js\";\n\nimport \"../Shaders/highlights.fragment.js\";\n/**\n * Extracts highlights from the image\n * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses\n */\nexport class HighlightsPostProcess extends PostProcess {\n /**\n * Gets a string identifying the name of the class\n * @returns \"HighlightsPostProcess\" string\n */\n getClassName() {\n return \"HighlightsPostProcess\";\n }\n /**\n * Extracts highlights from the image\n * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses\n * @param name The name of the effect.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of texture for the post process (default: Engine.TEXTURETYPE_UNSIGNED_INT)\n */\n constructor(name, options, camera, samplingMode, engine, reusable, textureType = 0) {\n super(name, \"highlights\", null, null, options, camera, samplingMode, engine, reusable, null, textureType);\n }\n}\n//# sourceMappingURL=highlightsPostProcess.js.map","import { Texture } from \"../../../Materials/Textures/texture.js\";\nimport { DynamicTexture } from \"../../../Materials/Textures/dynamicTexture.js\";\nimport { PostProcess } from \"../../../PostProcesses/postProcess.js\";\nimport { PostProcessRenderPipeline } from \"../../../PostProcesses/RenderPipeline/postProcessRenderPipeline.js\";\nimport { PostProcessRenderEffect } from \"../../../PostProcesses/RenderPipeline/postProcessRenderEffect.js\";\nimport \"../../../PostProcesses/RenderPipeline/postProcessRenderPipelineManagerSceneComponent.js\";\nimport \"../../../Shaders/chromaticAberration.fragment.js\";\nimport \"../../../Shaders/lensHighlights.fragment.js\";\nimport \"../../../Shaders/depthOfField.fragment.js\";\n/**\n * BABYLON.JS Chromatic Aberration GLSL Shader\n * Author: Olivier Guyot\n * Separates very slightly R, G and B colors on the edges of the screen\n * Inspired by Francois Tarlier & Martins Upitis\n */\nexport class LensRenderingPipeline extends PostProcessRenderPipeline {\n /**\n * @constructor\n *\n * Effect parameters are as follow:\n * {\n * chromatic_aberration: number; // from 0 to x (1 for realism)\n * edge_blur: number; // from 0 to x (1 for realism)\n * distortion: number; // from 0 to x (1 for realism), note that this will effect the pointer position precision\n * grain_amount: number; // from 0 to 1\n * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise\n * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)\n * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)\n * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)\n * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like \"bokeh\" effect\n * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)\n * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)\n * blur_noise: boolean; // add a little bit of noise to the blur (default: true)\n * }\n * Note: if an effect parameter is unset, effect is disabled\n *\n * @param name The rendering pipeline name\n * @param parameters - An object containing all parameters (see above)\n * @param scene The scene linked to this pipeline\n * @param ratio The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)\n * @param cameras The array of cameras that the rendering pipeline will be attached to\n */\n constructor(name, parameters, scene, ratio = 1.0, cameras) {\n super(scene.getEngine(), name);\n // Lens effects can be of the following:\n // - chromatic aberration (slight shift of RGB colors)\n // - blur on the edge of the lens\n // - lens distortion\n // - depth-of-field blur & highlights enhancing\n // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)\n // - grain effect (noise or custom texture)\n // Two additional texture samplers are needed:\n // - depth map (for depth-of-field)\n // - grain texture\n /**\n * @ignore\n * The chromatic aberration PostProcess id in the pipeline\n */\n this.LensChromaticAberrationEffect = \"LensChromaticAberrationEffect\";\n /**\n * @ignore\n * The highlights enhancing PostProcess id in the pipeline\n */\n this.HighlightsEnhancingEffect = \"HighlightsEnhancingEffect\";\n /**\n * @ignore\n * The depth-of-field PostProcess id in the pipeline\n */\n this.LensDepthOfFieldEffect = \"LensDepthOfFieldEffect\";\n this._pentagonBokehIsEnabled = false;\n this._scene = scene;\n // Fetch texture samplers\n this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer \"on\"\n if (parameters.grain_texture) {\n this._grainTexture = parameters.grain_texture;\n }\n else {\n this._createGrainTexture();\n }\n // save parameters\n this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;\n this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;\n this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;\n this._distortion = parameters.distortion ? parameters.distortion : 0;\n this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;\n this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;\n this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;\n this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;\n this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;\n this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;\n this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;\n // Create effects\n this._createChromaticAberrationPostProcess(ratio);\n this._createHighlightsPostProcess(ratio);\n this._createDepthOfFieldPostProcess(ratio / 4);\n // Set up pipeline\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, () => {\n return this._chromaticAberrationPostProcess;\n }, true));\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, () => {\n return this._highlightsPostProcess;\n }, true));\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, () => {\n return this._depthOfFieldPostProcess;\n }, true));\n if (this._highlightsGain === -1) {\n this._disableEffect(this.HighlightsEnhancingEffect, null);\n }\n // Finish\n scene.postProcessRenderPipelineManager.addPipeline(this);\n if (cameras) {\n scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);\n }\n }\n /**\n * Get the class name\n * @returns \"LensRenderingPipeline\"\n */\n getClassName() {\n return \"LensRenderingPipeline\";\n }\n // Properties\n /**\n * Gets associated scene\n */\n get scene() {\n return this._scene;\n }\n /**\n * Gets or sets the edge blur\n */\n get edgeBlur() {\n return this._edgeBlur;\n }\n set edgeBlur(value) {\n this.setEdgeBlur(value);\n }\n /**\n * Gets or sets the grain amount\n */\n get grainAmount() {\n return this._grainAmount;\n }\n set grainAmount(value) {\n this.setGrainAmount(value);\n }\n /**\n * Gets or sets the chromatic aberration amount\n */\n get chromaticAberration() {\n return this._chromaticAberration;\n }\n set chromaticAberration(value) {\n this.setChromaticAberration(value);\n }\n /**\n * Gets or sets the depth of field aperture\n */\n get dofAperture() {\n return this._dofAperture;\n }\n set dofAperture(value) {\n this.setAperture(value);\n }\n /**\n * Gets or sets the edge distortion\n */\n get edgeDistortion() {\n return this._distortion;\n }\n set edgeDistortion(value) {\n this.setEdgeDistortion(value);\n }\n /**\n * Gets or sets the depth of field distortion\n */\n get dofDistortion() {\n return this._dofDistance;\n }\n set dofDistortion(value) {\n this.setFocusDistance(value);\n }\n /**\n * Gets or sets the darken out of focus amount\n */\n get darkenOutOfFocus() {\n return this._dofDarken;\n }\n set darkenOutOfFocus(value) {\n this.setDarkenOutOfFocus(value);\n }\n /**\n * Gets or sets a boolean indicating if blur noise is enabled\n */\n get blurNoise() {\n return this._blurNoise;\n }\n set blurNoise(value) {\n this._blurNoise = value;\n }\n /**\n * Gets or sets a boolean indicating if pentagon bokeh is enabled\n */\n get pentagonBokeh() {\n return this._pentagonBokehIsEnabled;\n }\n set pentagonBokeh(value) {\n if (value) {\n this.enablePentagonBokeh();\n }\n else {\n this.disablePentagonBokeh();\n }\n }\n /**\n * Gets or sets the highlight grain amount\n */\n get highlightsGain() {\n return this._highlightsGain;\n }\n set highlightsGain(value) {\n this.setHighlightsGain(value);\n }\n /**\n * Gets or sets the highlight threshold\n */\n get highlightsThreshold() {\n return this._highlightsThreshold;\n }\n set highlightsThreshold(value) {\n this.setHighlightsThreshold(value);\n }\n // public methods (self explanatory)\n /**\n * Sets the amount of blur at the edges\n * @param amount blur amount\n */\n setEdgeBlur(amount) {\n this._edgeBlur = amount;\n }\n /**\n * Sets edge blur to 0\n */\n disableEdgeBlur() {\n this._edgeBlur = 0;\n }\n /**\n * Sets the amount of grain\n * @param amount Amount of grain\n */\n setGrainAmount(amount) {\n this._grainAmount = amount;\n }\n /**\n * Set grain amount to 0\n */\n disableGrain() {\n this._grainAmount = 0;\n }\n /**\n * Sets the chromatic aberration amount\n * @param amount amount of chromatic aberration\n */\n setChromaticAberration(amount) {\n this._chromaticAberration = amount;\n }\n /**\n * Sets chromatic aberration amount to 0\n */\n disableChromaticAberration() {\n this._chromaticAberration = 0;\n }\n /**\n * Sets the EdgeDistortion amount\n * @param amount amount of EdgeDistortion\n */\n setEdgeDistortion(amount) {\n this._distortion = amount;\n }\n /**\n * Sets edge distortion to 0\n */\n disableEdgeDistortion() {\n this._distortion = 0;\n }\n /**\n * Sets the FocusDistance amount\n * @param amount amount of FocusDistance\n */\n setFocusDistance(amount) {\n this._dofDistance = amount;\n }\n /**\n * Disables depth of field\n */\n disableDepthOfField() {\n this._dofDistance = -1;\n }\n /**\n * Sets the Aperture amount\n * @param amount amount of Aperture\n */\n setAperture(amount) {\n this._dofAperture = amount;\n }\n /**\n * Sets the DarkenOutOfFocus amount\n * @param amount amount of DarkenOutOfFocus\n */\n setDarkenOutOfFocus(amount) {\n this._dofDarken = amount;\n }\n /**\n * Creates a pentagon bokeh effect\n */\n enablePentagonBokeh() {\n this._highlightsPostProcess.updateEffect(\"#define PENTAGON\\n\");\n this._pentagonBokehIsEnabled = true;\n }\n /**\n * Disables the pentagon bokeh effect\n */\n disablePentagonBokeh() {\n this._pentagonBokehIsEnabled = false;\n this._highlightsPostProcess.updateEffect();\n }\n /**\n * Enables noise blur\n */\n enableNoiseBlur() {\n this._blurNoise = true;\n }\n /**\n * Disables noise blur\n */\n disableNoiseBlur() {\n this._blurNoise = false;\n }\n /**\n * Sets the HighlightsGain amount\n * @param amount amount of HighlightsGain\n */\n setHighlightsGain(amount) {\n this._highlightsGain = amount;\n }\n /**\n * Sets the HighlightsThreshold amount\n * @param amount amount of HighlightsThreshold\n */\n setHighlightsThreshold(amount) {\n if (this._highlightsGain === -1) {\n this._highlightsGain = 1.0;\n }\n this._highlightsThreshold = amount;\n }\n /**\n * Disables highlights\n */\n disableHighlights() {\n this._highlightsGain = -1;\n }\n /**\n * Removes the internal pipeline assets and detaches the pipeline from the scene cameras\n * @param disableDepthRender If the scene's depth rendering should be disabled (default: false)\n */\n dispose(disableDepthRender = false) {\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);\n this._chromaticAberrationPostProcess = null;\n this._highlightsPostProcess = null;\n this._depthOfFieldPostProcess = null;\n this._grainTexture.dispose();\n if (disableDepthRender) {\n this._scene.disableDepthRenderer();\n }\n }\n // colors shifting and distortion\n _createChromaticAberrationPostProcess(ratio) {\n this._chromaticAberrationPostProcess = new PostProcess(\"LensChromaticAberration\", \"chromaticAberration\", [\"chromatic_aberration\", \"screen_width\", \"screen_height\", \"direction\", \"radialIntensity\", \"centerPosition\"], // uniforms\n [], // samplers\n ratio, null, Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);\n this._chromaticAberrationPostProcess.onApply = (effect) => {\n effect.setFloat(\"chromatic_aberration\", this._chromaticAberration);\n effect.setFloat(\"screen_width\", this._scene.getEngine().getRenderWidth());\n effect.setFloat(\"screen_height\", this._scene.getEngine().getRenderHeight());\n effect.setFloat(\"radialIntensity\", 1);\n effect.setFloat2(\"direction\", 17, 17);\n effect.setFloat2(\"centerPosition\", 0.5, 0.5);\n };\n }\n // highlights enhancing\n _createHighlightsPostProcess(ratio) {\n this._highlightsPostProcess = new PostProcess(\"LensHighlights\", \"lensHighlights\", [\"gain\", \"threshold\", \"screen_width\", \"screen_height\"], // uniforms\n [], // samplers\n ratio, null, Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? \"#define PENTAGON\\n\" : \"\");\n this._highlightsPostProcess.externalTextureSamplerBinding = true;\n this._highlightsPostProcess.onApply = (effect) => {\n effect.setFloat(\"gain\", this._highlightsGain);\n effect.setFloat(\"threshold\", this._highlightsThreshold);\n effect.setTextureFromPostProcess(\"textureSampler\", this._chromaticAberrationPostProcess);\n effect.setFloat(\"screen_width\", this._scene.getEngine().getRenderWidth());\n effect.setFloat(\"screen_height\", this._scene.getEngine().getRenderHeight());\n };\n }\n // colors shifting and distortion\n _createDepthOfFieldPostProcess(ratio) {\n this._depthOfFieldPostProcess = new PostProcess(\"LensDepthOfField\", \"depthOfField\", [\n \"grain_amount\",\n \"blur_noise\",\n \"screen_width\",\n \"screen_height\",\n \"distortion\",\n \"dof_enabled\",\n \"screen_distance\",\n \"aperture\",\n \"darken\",\n \"edge_blur\",\n \"highlights\",\n \"near\",\n \"far\",\n ], [\"depthSampler\", \"grainSampler\", \"highlightsSampler\"], ratio, null, Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);\n this._depthOfFieldPostProcess.externalTextureSamplerBinding = true;\n this._depthOfFieldPostProcess.onApply = (effect) => {\n effect.setTexture(\"depthSampler\", this._depthTexture);\n effect.setTexture(\"grainSampler\", this._grainTexture);\n effect.setTextureFromPostProcess(\"textureSampler\", this._highlightsPostProcess);\n effect.setTextureFromPostProcess(\"highlightsSampler\", this._depthOfFieldPostProcess);\n effect.setFloat(\"grain_amount\", this._grainAmount);\n effect.setBool(\"blur_noise\", this._blurNoise);\n effect.setFloat(\"screen_width\", this._scene.getEngine().getRenderWidth());\n effect.setFloat(\"screen_height\", this._scene.getEngine().getRenderHeight());\n effect.setFloat(\"distortion\", this._distortion);\n effect.setBool(\"dof_enabled\", this._dofDistance !== -1);\n effect.setFloat(\"screen_distance\", 1.0 / (0.1 - 1.0 / this._dofDistance));\n effect.setFloat(\"aperture\", this._dofAperture);\n effect.setFloat(\"darken\", this._dofDarken);\n effect.setFloat(\"edge_blur\", this._edgeBlur);\n effect.setBool(\"highlights\", this._highlightsGain !== -1);\n if (this._scene.activeCamera) {\n effect.setFloat(\"near\", this._scene.activeCamera.minZ);\n effect.setFloat(\"far\", this._scene.activeCamera.maxZ);\n }\n };\n }\n // creates a black and white random noise texture, 512x512\n _createGrainTexture() {\n const size = 512;\n this._grainTexture = new DynamicTexture(\"LensNoiseTexture\", size, this._scene, false, Texture.BILINEAR_SAMPLINGMODE);\n this._grainTexture.wrapU = Texture.WRAP_ADDRESSMODE;\n this._grainTexture.wrapV = Texture.WRAP_ADDRESSMODE;\n const context = this._grainTexture.getContext();\n const rand = (min, max) => {\n return Math.random() * (max - min) + min;\n };\n let value;\n for (let x = 0; x < size; x++) {\n for (let y = 0; y < size; y++) {\n value = Math.floor(rand(0.42, 0.58) * 255);\n context.fillStyle = \"rgb(\" + value + \", \" + value + \", \" + value + \")\";\n context.fillRect(x, y, 1, 1);\n }\n }\n this._grainTexture.update(false);\n }\n}\n//# sourceMappingURL=lensRenderingPipeline.js.map","\n/**\n * Contains all parameters needed for the prepass to perform\n * screen space subsurface scattering\n */\nexport class SSAO2Configuration {\n constructor() {\n /**\n * Is subsurface enabled\n */\n this.enabled = false;\n /**\n * Name of the configuration\n */\n this.name = \"ssao2\";\n /**\n * Textures that should be present in the MRT for this effect to work\n */\n this.texturesRequired = [6, 5];\n }\n}\n//# sourceMappingURL=ssao2Configuration.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"ssao2PixelShader\";\nconst shader = `precision highp float;\runiform sampler2D textureSampler;\rvarying vec2 vUV;\r#ifdef SSAO\nfloat scales[16]=float[16](\r0.1,\r0.11406250000000001,\r0.131640625,\r0.15625,\r0.187890625,\r0.2265625,\r0.272265625,\r0.325,\r0.384765625,\r0.4515625,\r0.525390625,\r0.60625,\r0.694140625,\r0.7890625,\r0.891015625,\r1.0\r);\runiform float near;\runiform float radius;\runiform sampler2D depthSampler;\runiform sampler2D randomSampler;\runiform sampler2D normalSampler;\runiform float randTextureTiles;\runiform float samplesFactor;\runiform vec3 sampleSphere[SAMPLES];\runiform float totalStrength;\runiform float base;\runiform float xViewport;\runiform float yViewport;\runiform mat3 depthProjection;\runiform float maxZ;\runiform float minZAspect;\runiform vec2 texelSize;\runiform mat4 projection;\rvoid main()\r{\rvec3 random=textureLod(randomSampler,vUV*randTextureTiles,0.0).rgb;\rfloat depth=textureLod(depthSampler,vUV,0.0).r;\rfloat depthSign=depth/abs(depth);\rdepth=depth*depthSign;\rvec3 normal=textureLod(normalSampler,vUV,0.0).rgb;\rfloat occlusion=0.0;\rfloat correctedRadius=min(radius,minZAspect*depth/near);\rvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\rvec3 vDepthFactor=depthProjection*vec3(1.0,1.0,depth);\rvec3 origin=vViewRay*vDepthFactor;\rvec3 rvec=random*2.0-1.0;\rrvec.z=0.0;\rfloat dotProduct=dot(rvec,normal);\rrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\rvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\rvec3 bitangent=cross(normal,tangent);\rmat3 tbn=mat3(tangent,bitangent,normal);\rfloat difference;\rfor (int i=0; i1.0 || offset.y>1.0) {\rcontinue;\r}\rfloat sampleDepth=abs(textureLod(depthSampler,offset.xy,0.0).r);\rdifference=depthSign*samplePosition.z-sampleDepth;\rfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\rocclusion+=step(EPSILON,difference)*rangeCheck;\r}\rocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\rfloat ao=1.0-totalStrength*occlusion*samplesFactor;\rfloat result=clamp(ao+base,0.0,1.0);\rgl_FragColor=vec4(vec3(result),1.0);\r}\r#endif\n#ifdef BLUR\nuniform float outSize;\runiform float soften;\runiform float tolerance;\runiform int samples;\r#ifndef BLUR_BYPASS\nuniform sampler2D depthSampler;\r#ifdef BLUR_LEGACY\n#define inline\nfloat blur13Bilateral(sampler2D image,vec2 uv,vec2 step) {\rfloat result=0.0;\rvec2 off1=vec2(1.411764705882353)*step;\rvec2 off2=vec2(3.2941176470588234)*step;\rvec2 off3=vec2(5.176470588235294)*step;\rfloat compareDepth=abs(textureLod(depthSampler,uv,0.0).r);\rfloat sampleDepth;\rfloat weight;\rfloat weightSum=30.0;\rresult+=textureLod(image,uv,0.0).r*30.0;\rsampleDepth=abs(textureLod(depthSampler,uv+off1,0.0).r);\rweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\rweightSum+= weight;\rresult+=textureLod(image,uv+off1,0.0).r*weight;\rsampleDepth=abs(textureLod(depthSampler,uv-off1,0.0).r);\rweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\rweightSum+= weight;\rresult+=textureLod(image,uv-off1,0.0).r*weight;\rsampleDepth=abs(textureLod(depthSampler,uv+off2,0.0).r);\rweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\rweightSum+=weight;\rresult+=textureLod(image,uv+off2,0.0).r*weight;\rsampleDepth=abs(textureLod(depthSampler,uv-off2,0.0).r);\rweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\rweightSum+=weight;\rresult+=textureLod(image,uv-off2,0.0).r*weight;\rsampleDepth=abs(textureLod(depthSampler,uv+off3,0.0).r);\rweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\rweightSum+=weight;\rresult+=textureLod(image,uv+off3,0.0).r*weight;\rsampleDepth=abs(textureLod(depthSampler,uv-off3,0.0).r);\rweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\rweightSum+=weight;\rresult+=textureLod(image,uv-off3,0.0).r*weight;\rreturn result/weightSum;\r}\r#endif\n#endif\nvoid main()\r{\rfloat result=0.0;\r#ifdef BLUR_BYPASS\nresult=textureLod(textureSampler,vUV,0.0).r;\r#else\n#ifdef BLUR_H\nvec2 step=vec2(1.0/outSize,0.0);\r#else\nvec2 step=vec2(0.0,1.0/outSize);\r#endif\n#ifdef BLUR_LEGACY\nresult=blur13Bilateral(textureSampler,vUV,step);\r#else\nfloat compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);\rfloat weightSum=0.0;\rfor (int i=-samples; i {\n return this._originalColorPostProcess;\n }, true));\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, () => {\n return this._ssaoPostProcess;\n }, true));\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, () => {\n return this._blurHPostProcess;\n }, true));\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, () => {\n return this._blurVPostProcess;\n }, true));\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, () => {\n return this._ssaoCombinePostProcess;\n }, true));\n // Finish\n scene.postProcessRenderPipelineManager.addPipeline(this);\n if (cameras) {\n scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);\n }\n }\n // Public Methods\n /**\n * Get the class name\n * @returns \"SSAO2RenderingPipeline\"\n */\n getClassName() {\n return \"SSAO2RenderingPipeline\";\n }\n /**\n * Removes the internal pipeline assets and detaches the pipeline from the scene cameras\n * @param disableGeometryBufferRenderer\n */\n dispose(disableGeometryBufferRenderer = false) {\n for (let i = 0; i < this._scene.cameras.length; i++) {\n const camera = this._scene.cameras[i];\n this._originalColorPostProcess.dispose(camera);\n this._ssaoPostProcess.dispose(camera);\n this._blurHPostProcess.dispose(camera);\n this._blurVPostProcess.dispose(camera);\n this._ssaoCombinePostProcess.dispose(camera);\n }\n this._randomTexture.dispose();\n if (disableGeometryBufferRenderer) {\n this._scene.disableGeometryBufferRenderer();\n }\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);\n super.dispose();\n }\n // Private Methods\n /** @internal */\n _rebuild() {\n super._rebuild();\n }\n _getSamplersForBlur(disabled) {\n return disabled ? [\"textureSampler\"] : [\"textureSampler\", \"depthSampler\"];\n }\n _getDefinesForBlur(bilateral, disabled) {\n let define = \"#define BLUR\\n\";\n if (disabled) {\n define += \"#define BLUR_BYPASS\\n\";\n }\n if (!bilateral) {\n define += \"#define BLUR_LEGACY\\n\";\n }\n return { h: define + \"#define BLUR_H\\n\", v: define };\n }\n _createBlurPostProcess(ssaoRatio, blurRatio, textureType) {\n const defines = this._getDefinesForBlur(this.expensiveBlur, this.bypassBlur);\n const samplers = this._getSamplersForBlur(this.bypassBlur);\n this._blurHPostProcess = this._createBlurFilter(\"BlurH\", samplers, ssaoRatio, defines.h, textureType, true);\n this._blurVPostProcess = this._createBlurFilter(\"BlurV\", samplers, blurRatio, defines.v, textureType, false);\n }\n _createBlurFilter(name, samplers, ratio, defines, textureType, horizontal) {\n const blurFilter = new PostProcess(name, \"ssao2\", [\"outSize\", \"samples\", \"soften\", \"tolerance\"], samplers, ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, defines, textureType);\n blurFilter.onApply = (effect) => {\n if (!this._scene.activeCamera) {\n return;\n }\n const ssaoCombineSize = horizontal ? this._ssaoCombinePostProcess.width : this._ssaoCombinePostProcess.height;\n const originalColorSize = horizontal ? this._originalColorPostProcess.width : this._originalColorPostProcess.height;\n effect.setFloat(\"outSize\", ssaoCombineSize > 0 ? ssaoCombineSize : originalColorSize);\n effect.setInt(\"samples\", this.bilateralSamples);\n effect.setFloat(\"soften\", this.bilateralSoften);\n effect.setFloat(\"tolerance\", this.bilateralTolerance);\n if (this._geometryBufferRenderer) {\n effect.setTexture(\"depthSampler\", this._geometryBufferRenderer.getGBuffer().textures[0]);\n }\n else if (this._prePassRenderer) {\n effect.setTexture(\"depthSampler\", this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]);\n }\n };\n blurFilter.samples = this.textureSamples;\n return blurFilter;\n }\n //Van der Corput radical inverse\n _radicalInverse_VdC(i) {\n this._bits[0] = i;\n this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;\n this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | (((this._bits[0] & 0xaaaaaaaa) >>> 1) >>> 0);\n this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | (((this._bits[0] & 0xcccccccc) >>> 2) >>> 0);\n this._bits[0] = ((this._bits[0] & 0x0f0f0f0f) << 4) | (((this._bits[0] & 0xf0f0f0f0) >>> 4) >>> 0);\n this._bits[0] = ((this._bits[0] & 0x00ff00ff) << 8) | (((this._bits[0] & 0xff00ff00) >>> 8) >>> 0);\n return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296\n }\n _hammersley(i, n) {\n return [i / n, this._radicalInverse_VdC(i)];\n }\n _hemisphereSample_uniform(u, v) {\n const phi = v * 2.0 * Math.PI;\n // rejecting samples that are close to tangent plane to avoid z-fighting artifacts\n const cosTheta = 1.0 - u * 0.85;\n const sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);\n return new Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);\n }\n _generateHemisphere() {\n const numSamples = this.samples;\n const result = [];\n let vector;\n let i = 0;\n while (i < numSamples) {\n if (numSamples < 16) {\n vector = this._hemisphereSample_uniform(Math.random(), Math.random());\n }\n else {\n const rand = this._hammersley(i, numSamples);\n vector = this._hemisphereSample_uniform(rand[0], rand[1]);\n }\n result.push(vector.x, vector.y, vector.z);\n i++;\n }\n return result;\n }\n _getDefinesForSSAO() {\n const defines = `#define SSAO\\n#define SAMPLES ${this.samples}\\n#define EPSILON ${this.epsilon.toFixed(4)}`;\n return defines;\n }\n _createSSAOPostProcess(ratio, textureType) {\n this._sampleSphere = this._generateHemisphere();\n const defines = this._getDefinesForSSAO();\n const samplers = [\"randomSampler\", \"depthSampler\", \"normalSampler\"];\n this._ssaoPostProcess = new PostProcess(\"ssao2\", \"ssao2\", [\n \"sampleSphere\",\n \"samplesFactor\",\n \"randTextureTiles\",\n \"totalStrength\",\n \"radius\",\n \"base\",\n \"range\",\n \"projection\",\n \"near\",\n \"texelSize\",\n \"xViewport\",\n \"yViewport\",\n \"maxZ\",\n \"minZAspect\",\n \"depthProjection\",\n ], samplers, ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, defines, textureType);\n this._ssaoPostProcess.onApply = (effect) => {\n var _a, _b, _c, _d;\n if (!this._scene.activeCamera) {\n return;\n }\n effect.setArray3(\"sampleSphere\", this._sampleSphere);\n effect.setFloat(\"randTextureTiles\", 32.0);\n effect.setFloat(\"samplesFactor\", 1 / this.samples);\n effect.setFloat(\"totalStrength\", this.totalStrength);\n effect.setFloat2(\"texelSize\", 1 / this._ssaoPostProcess.width, 1 / this._ssaoPostProcess.height);\n effect.setFloat(\"radius\", this.radius);\n effect.setFloat(\"maxZ\", this.maxZ);\n effect.setFloat(\"minZAspect\", this.minZAspect);\n effect.setFloat(\"base\", this.base);\n effect.setFloat(\"near\", this._scene.activeCamera.minZ);\n if (this._scene.activeCamera.mode === Camera.PERSPECTIVE_CAMERA) {\n effect.setMatrix3x3(\"depthProjection\", SSAO2RenderingPipeline.PERSPECTIVE_DEPTH_PROJECTION);\n effect.setFloat(\"xViewport\", Math.tan(this._scene.activeCamera.fov / 2) * this._scene.getEngine().getAspectRatio(this._scene.activeCamera, true));\n effect.setFloat(\"yViewport\", Math.tan(this._scene.activeCamera.fov / 2));\n }\n else {\n const halfWidth = this._scene.getEngine().getRenderWidth() / 2.0;\n const halfHeight = this._scene.getEngine().getRenderHeight() / 2.0;\n const orthoLeft = (_a = this._scene.activeCamera.orthoLeft) !== null && _a !== void 0 ? _a : -halfWidth;\n const orthoRight = (_b = this._scene.activeCamera.orthoRight) !== null && _b !== void 0 ? _b : halfWidth;\n const orthoBottom = (_c = this._scene.activeCamera.orthoBottom) !== null && _c !== void 0 ? _c : -halfHeight;\n const orthoTop = (_d = this._scene.activeCamera.orthoTop) !== null && _d !== void 0 ? _d : halfHeight;\n effect.setMatrix3x3(\"depthProjection\", SSAO2RenderingPipeline.ORTHO_DEPTH_PROJECTION);\n effect.setFloat(\"xViewport\", (orthoRight - orthoLeft) * 0.5);\n effect.setFloat(\"yViewport\", (orthoTop - orthoBottom) * 0.5);\n }\n effect.setMatrix(\"projection\", this._scene.getProjectionMatrix());\n if (this._geometryBufferRenderer) {\n effect.setTexture(\"depthSampler\", this._geometryBufferRenderer.getGBuffer().textures[0]);\n effect.setTexture(\"normalSampler\", this._geometryBufferRenderer.getGBuffer().textures[1]);\n }\n else if (this._prePassRenderer) {\n effect.setTexture(\"depthSampler\", this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]);\n effect.setTexture(\"normalSampler\", this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)]);\n }\n effect.setTexture(\"randomSampler\", this._randomTexture);\n };\n this._ssaoPostProcess.samples = this.textureSamples;\n if (!this._forceGeometryBuffer) {\n this._ssaoPostProcess._prePassEffectConfiguration = new SSAO2Configuration();\n }\n }\n _createSSAOCombinePostProcess(ratio, textureType) {\n this._ssaoCombinePostProcess = new PostProcess(\"ssaoCombine\", \"ssaoCombine\", [], [\"originalColor\", \"viewport\"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, undefined, textureType);\n this._ssaoCombinePostProcess.onApply = (effect) => {\n const viewport = this._scene.activeCamera.viewport;\n effect.setVector4(\"viewport\", TmpVectors.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));\n effect.setTextureFromPostProcessOutput(\"originalColor\", this._originalColorPostProcess);\n };\n this._ssaoCombinePostProcess.samples = this.textureSamples;\n }\n _createRandomTexture() {\n const size = 128;\n this._randomTexture = new DynamicTexture(\"SSAORandomTexture\", size, this._scene, false, Texture.BILINEAR_SAMPLINGMODE);\n this._randomTexture.wrapU = Texture.WRAP_ADDRESSMODE;\n this._randomTexture.wrapV = Texture.WRAP_ADDRESSMODE;\n const context = this._randomTexture.getContext();\n const rand = (min, max) => {\n return Math.random() * (max - min) + min;\n };\n const randVector = Vector3.Zero();\n for (let x = 0; x < size; x++) {\n for (let y = 0; y < size; y++) {\n randVector.x = rand(0.0, 1.0);\n randVector.y = rand(0.0, 1.0);\n randVector.z = 0.0;\n randVector.normalize();\n randVector.scaleInPlace(255);\n randVector.x = Math.floor(randVector.x);\n randVector.y = Math.floor(randVector.y);\n context.fillStyle = \"rgb(\" + randVector.x + \", \" + randVector.y + \", \" + randVector.z + \")\";\n context.fillRect(x, y, 1, 1);\n }\n }\n this._randomTexture.update(false);\n }\n /**\n * Serialize the rendering pipeline (Used when exporting)\n * @returns the serialized object\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this);\n serializationObject.customType = \"SSAO2RenderingPipeline\";\n return serializationObject;\n }\n /**\n * Parse the serialized pipeline\n * @param source Source pipeline.\n * @param scene The scene to load the pipeline to.\n * @param rootUrl The URL of the serialized pipeline.\n * @returns An instantiated pipeline from the serialized object.\n */\n static Parse(source, scene, rootUrl) {\n return SerializationHelper.Parse(() => new SSAO2RenderingPipeline(source._name, scene, source._ratio, undefined, source._forceGeometryBuffer, source._textureType), source, scene, rootUrl);\n }\n}\nSSAO2RenderingPipeline.ORTHO_DEPTH_PROJECTION = [1, 0, 0, 0, 1, 0, 0, 0, 1];\nSSAO2RenderingPipeline.PERSPECTIVE_DEPTH_PROJECTION = [0, 0, 0, 0, 0, 0, 1, 1, 1];\n__decorate([\n serialize()\n], SSAO2RenderingPipeline.prototype, \"totalStrength\", void 0);\n__decorate([\n serialize()\n], SSAO2RenderingPipeline.prototype, \"maxZ\", void 0);\n__decorate([\n serialize()\n], SSAO2RenderingPipeline.prototype, \"minZAspect\", void 0);\n__decorate([\n serialize(\"epsilon\")\n], SSAO2RenderingPipeline.prototype, \"_epsilon\", void 0);\n__decorate([\n serialize(\"samples\")\n], SSAO2RenderingPipeline.prototype, \"_samples\", void 0);\n__decorate([\n serialize(\"textureSamples\")\n], SSAO2RenderingPipeline.prototype, \"_textureSamples\", void 0);\n__decorate([\n serialize()\n], SSAO2RenderingPipeline.prototype, \"_forceGeometryBuffer\", void 0);\n__decorate([\n serialize()\n], SSAO2RenderingPipeline.prototype, \"_ratio\", void 0);\n__decorate([\n serialize()\n], SSAO2RenderingPipeline.prototype, \"_textureType\", void 0);\n__decorate([\n serialize()\n], SSAO2RenderingPipeline.prototype, \"radius\", void 0);\n__decorate([\n serialize()\n], SSAO2RenderingPipeline.prototype, \"base\", void 0);\n__decorate([\n serialize(\"bypassBlur\")\n], SSAO2RenderingPipeline.prototype, \"_bypassBlur\", void 0);\n__decorate([\n serialize(\"expensiveBlur\")\n], SSAO2RenderingPipeline.prototype, \"_expensiveBlur\", void 0);\n__decorate([\n serialize()\n], SSAO2RenderingPipeline.prototype, \"bilateralSamples\", void 0);\n__decorate([\n serialize()\n], SSAO2RenderingPipeline.prototype, \"bilateralSoften\", void 0);\n__decorate([\n serialize()\n], SSAO2RenderingPipeline.prototype, \"bilateralTolerance\", void 0);\nRegisterClass(\"BABYLON.SSAO2RenderingPipeline\", SSAO2RenderingPipeline);\n//# sourceMappingURL=ssao2RenderingPipeline.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"ssaoPixelShader\";\nconst shader = `uniform sampler2D textureSampler;\rvarying vec2 vUV;\r#ifdef SSAO\nuniform sampler2D randomSampler;\runiform float randTextureTiles;\runiform float samplesFactor;\runiform vec3 sampleSphere[SAMPLES];\runiform float totalStrength;\runiform float radius;\runiform float area;\runiform float fallOff;\runiform float base;\rvec3 normalFromDepth(float depth,vec2 coords)\r{\rvec2 offset1=vec2(0.0,radius);\rvec2 offset2=vec2(radius,0.0);\rfloat depth1=texture2D(textureSampler,coords+offset1).r;\rfloat depth2=texture2D(textureSampler,coords+offset2).r;\rvec3 p1=vec3(offset1,depth1-depth);\rvec3 p2=vec3(offset2,depth2-depth);\rvec3 normal=cross(p1,p2);\rnormal.z=-normal.z;\rreturn normalize(normal);\r}\rvoid main()\r{\rvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\rfloat depth=texture2D(textureSampler,vUV).r;\rvec3 position=vec3(vUV,depth);\rvec3 normal=normalFromDepth(depth,vUV);\rfloat radiusDepth=radius/depth;\rfloat occlusion=0.0;\rvec3 ray;\rvec3 hemiRay;\rfloat occlusionDepth;\rfloat difference;\rfor (int i=0; i {\n return this._originalColorPostProcess;\n }, true));\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, () => {\n return this._ssaoPostProcess;\n }, true));\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, () => {\n return this._blurHPostProcess;\n }, true));\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, () => {\n return this._blurVPostProcess;\n }, true));\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, () => {\n return this._ssaoCombinePostProcess;\n }, true));\n // Finish\n scene.postProcessRenderPipelineManager.addPipeline(this);\n if (cameras) {\n scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);\n }\n }\n /**\n * @internal\n */\n _attachCameras(cameras, unique) {\n super._attachCameras(cameras, unique);\n for (const camera of this._cameras) {\n this._scene.enableDepthRenderer(camera).getDepthMap(); // Force depth renderer \"on\"\n }\n }\n // Public Methods\n /**\n * Get the class name\n * @returns \"SSAORenderingPipeline\"\n */\n getClassName() {\n return \"SSAORenderingPipeline\";\n }\n /**\n * Removes the internal pipeline assets and detaches the pipeline from the scene cameras\n * @param disableDepthRender\n */\n dispose(disableDepthRender = false) {\n for (let i = 0; i < this._scene.cameras.length; i++) {\n const camera = this._scene.cameras[i];\n this._originalColorPostProcess.dispose(camera);\n this._ssaoPostProcess.dispose(camera);\n this._blurHPostProcess.dispose(camera);\n this._blurVPostProcess.dispose(camera);\n this._ssaoCombinePostProcess.dispose(camera);\n }\n this._randomTexture.dispose();\n if (disableDepthRender) {\n this._scene.disableDepthRenderer();\n }\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);\n super.dispose();\n }\n // Private Methods\n _createBlurPostProcess(ratio) {\n const size = 16;\n this._blurHPostProcess = new BlurPostProcess(\"BlurH\", new Vector2(1, 0), size, ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, 0);\n this._blurVPostProcess = new BlurPostProcess(\"BlurV\", new Vector2(0, 1), size, ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, 0);\n this._blurHPostProcess.onActivateObservable.add(() => {\n const dw = this._blurHPostProcess.width / this._scene.getEngine().getRenderWidth();\n this._blurHPostProcess.kernel = size * dw;\n });\n this._blurVPostProcess.onActivateObservable.add(() => {\n const dw = this._blurVPostProcess.height / this._scene.getEngine().getRenderHeight();\n this._blurVPostProcess.kernel = size * dw;\n });\n }\n /** @internal */\n _rebuild() {\n this._firstUpdate = true;\n super._rebuild();\n }\n _createSSAOPostProcess(ratio) {\n const numSamples = 16;\n const sampleSphere = [\n 0.5381, 0.1856, -0.4319, 0.1379, 0.2486, 0.443, 0.3371, 0.5679, -0.0057, -0.6999, -0.0451, -0.0019, 0.0689, -0.1598, -0.8547, 0.056, 0.0069, -0.1843, -0.0146, 0.1402,\n 0.0762, 0.01, -0.1924, -0.0344, -0.3577, -0.5301, -0.4358, -0.3169, 0.1063, 0.0158, 0.0103, -0.5869, 0.0046, -0.0897, -0.494, 0.3287, 0.7119, -0.0154, -0.0918, -0.0533,\n 0.0596, -0.5411, 0.0352, -0.0631, 0.546, -0.4776, 0.2847, -0.0271,\n ];\n const samplesFactor = 1.0 / numSamples;\n this._ssaoPostProcess = new PostProcess(\"ssao\", \"ssao\", [\"sampleSphere\", \"samplesFactor\", \"randTextureTiles\", \"totalStrength\", \"radius\", \"area\", \"fallOff\", \"base\", \"range\", \"viewport\"], [\"randomSampler\"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, \"#define SAMPLES \" + numSamples + \"\\n#define SSAO\");\n this._ssaoPostProcess.externalTextureSamplerBinding = true;\n this._ssaoPostProcess.onApply = (effect) => {\n if (this._firstUpdate) {\n effect.setArray3(\"sampleSphere\", sampleSphere);\n effect.setFloat(\"samplesFactor\", samplesFactor);\n effect.setFloat(\"randTextureTiles\", 4.0);\n }\n effect.setFloat(\"totalStrength\", this.totalStrength);\n effect.setFloat(\"radius\", this.radius);\n effect.setFloat(\"area\", this.area);\n effect.setFloat(\"fallOff\", this.fallOff);\n effect.setFloat(\"base\", this.base);\n effect.setTexture(\"textureSampler\", this._scene.enableDepthRenderer(this._scene.activeCamera).getDepthMap());\n effect.setTexture(\"randomSampler\", this._randomTexture);\n };\n }\n _createSSAOCombinePostProcess(ratio) {\n this._ssaoCombinePostProcess = new PostProcess(\"ssaoCombine\", \"ssaoCombine\", [], [\"originalColor\", \"viewport\"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);\n this._ssaoCombinePostProcess.onApply = (effect) => {\n effect.setVector4(\"viewport\", TmpVectors.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));\n effect.setTextureFromPostProcess(\"originalColor\", this._originalColorPostProcess);\n };\n }\n _createRandomTexture() {\n const size = 512;\n this._randomTexture = new DynamicTexture(\"SSAORandomTexture\", size, this._scene, false, Texture.TRILINEAR_SAMPLINGMODE);\n this._randomTexture.wrapU = Texture.WRAP_ADDRESSMODE;\n this._randomTexture.wrapV = Texture.WRAP_ADDRESSMODE;\n const context = this._randomTexture.getContext();\n const rand = (min, max) => {\n return Math.random() * (max - min) + min;\n };\n const randVector = Vector3.Zero();\n for (let x = 0; x < size; x++) {\n for (let y = 0; y < size; y++) {\n randVector.x = Math.floor(Math.max(0.0, rand(-1.0, 1.0)) * 255);\n randVector.y = Math.floor(Math.max(0.0, rand(-1.0, 1.0)) * 255);\n randVector.z = Math.floor(Math.max(0.0, rand(-1.0, 1.0)) * 255);\n context.fillStyle = \"rgb(\" + randVector.x + \", \" + randVector.y + \", \" + randVector.z + \")\";\n context.fillRect(x, y, 1, 1);\n }\n }\n this._randomTexture.update(false);\n }\n}\n__decorate([\n serialize()\n], SSAORenderingPipeline.prototype, \"totalStrength\", void 0);\n__decorate([\n serialize()\n], SSAORenderingPipeline.prototype, \"radius\", void 0);\n__decorate([\n serialize()\n], SSAORenderingPipeline.prototype, \"area\", void 0);\n__decorate([\n serialize()\n], SSAORenderingPipeline.prototype, \"fallOff\", void 0);\n__decorate([\n serialize()\n], SSAORenderingPipeline.prototype, \"base\", void 0);\n//# sourceMappingURL=ssaoRenderingPipeline.js.map","\n/**\n * Contains all parameters needed for the prepass to perform\n * screen space reflections\n */\nexport class ScreenSpaceReflectionsConfiguration {\n constructor() {\n /**\n * Is ssr enabled\n */\n this.enabled = false;\n /**\n * Name of the configuration\n */\n this.name = \"screenSpaceReflections\";\n /**\n * Textures that should be present in the MRT for this effect to work\n */\n this.texturesRequired = [6, 3, 1];\n }\n}\n//# sourceMappingURL=screenSpaceReflectionsConfiguration.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"screenSpaceReflectionPixelShader\";\nconst shader = `uniform sampler2D textureSampler;\r#ifdef SSR_SUPPORTED\nuniform sampler2D reflectivitySampler;\runiform sampler2D normalSampler;\runiform sampler2D positionSampler;\r#endif\nuniform mat4 view;\runiform mat4 projection;\runiform float stepSize;\runiform float strength;\runiform float threshold;\runiform float roughnessFactor;\runiform float reflectionSpecularFalloffExponent;\rvarying vec2 vUV;\r#ifdef SSR_SUPPORTED\nstruct ReflectionInfo {\rvec3 color;\rvec4 coords;\r};\r/**\r* According to specular,see https:\r*/\rvec3 fresnelSchlick(float cosTheta,vec3 F0)\r{\rreturn F0+(1.0-F0)*pow(1.0-cosTheta,5.0);\r}\r/**\r* Once the pixel's coordinates has been found,let's adjust (smooth) a little bit\r* by sampling multiple reflection pixels.\r*/\rReflectionInfo smoothReflectionInfo(vec3 dir,vec3 hitCoord)\r{\rReflectionInfo info;\rinfo.color=vec3(0.0);\rvec4 projectedCoord;\rfloat sampledDepth;\rfor(int i=0; i0.0)\rhitCoord-=dir;\relse\rhitCoord+=dir;\rinfo.color+=texture2D(textureSampler,projectedCoord.xy).rgb;\r}\rprojectedCoord=projection*vec4(hitCoord,1.0);\rprojectedCoord.xy/=projectedCoord.w;\rprojectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);\rinfo.coords=vec4(projectedCoord.xy,sampledDepth,1.0);\rinfo.color+=texture2D(textureSampler,projectedCoord.xy).rgb;\rinfo.color/=float(SMOOTH_STEPS+1);\rreturn info;\r}\r/**\r* Tests the given world position (hitCoord) according to the given reflection vector (dir)\r* until it finds a collision (means that depth is enough close to say \"it's the pixel to sample!\").\r*/\rReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord)\r{\rReflectionInfo info;\rvec4 projectedCoord;\rfloat sampledDepth;\rdir*=stepSize;\rfor(int i=0; ishadowPixelDepth)\raccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\rcurrentPosition+=stepL;\r}\raccumFog/=NB_STEPS;\rvec3 color=accumFog*scatteringPower;\rgl_FragColor=vec4(color*exp(color) ,1.0);\r}\r#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\rvoid main(void)\r{\rgl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\r}\r#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\rvoid main()\r{\rfloat average=0.0;\rvec4 color=vec4(0.0);\rfloat maximum=-1e20;\rvec3 weight=vec3(0.299,0.587,0.114);\rfor (int i=0; i<4; i++)\r{\rcolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\rfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\r#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\r#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\r#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\r#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\r#endif\nmaximum=max(maximum,GreyValue);\raverage+=(0.25*log(1e-5+GreyValue));\r}\raverage=exp(average);\rgl_FragColor=vec4(average,maximum,0.0,1.0);\r}\r#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\runiform float halfDestPixelSize;\r#ifdef FINAL_DOWN_SAMPLER\n#include\n#endif\nvoid main()\r{\rvec4 color=vec4(0.0);\rfloat average=0.0;\rfor (int i=0; i<9; i++)\r{\rcolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\raverage+=color.r;\r}\raverage/=9.0;\r#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\r#else\ngl_FragColor=vec4(average,average,0.0,1.0);\r#endif\n}\r#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\runiform float averageLuminance;\rvoid main()\r{\rvec4 color=texture2D(textureAdderSampler,vUV);\r#ifndef AUTO_EXPOSURE\nvec4 adjustedColor=color/averageLuminance;\rcolor=adjustedColor;\rcolor.a=1.0;\r#endif\ngl_FragColor=color;\r}\r#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\runiform float strength;\runiform float ghostDispersal;\runiform float haloWidth;\runiform vec2 resolution;\runiform float distortionStrength;\rfloat hash(vec2 p)\r{\rfloat h=dot(p,vec2(127.1,311.7));\rreturn -1.0+2.0*fract(sin(h)*43758.5453123);\r}\rfloat noise(in vec2 p)\r{\rvec2 i=floor(p);\rvec2 f=fract(p);\rvec2 u=f*f*(3.0-2.0*f);\rreturn mix(mix(hash(i+vec2(0.0,0.0)),\rhash(i+vec2(1.0,0.0)),u.x),\rmix(hash(i+vec2(0.0,1.0)),\rhash(i+vec2(1.0,1.0)),u.x),u.y);\r}\rfloat fbm(vec2 p)\r{\rfloat f=0.0;\rf+=0.5000*noise(p); p*=2.02;\rf+=0.2500*noise(p); p*=2.03;\rf+=0.1250*noise(p); p*=2.01;\rf+=0.0625*noise(p); p*=2.04;\rf/=0.9375;\rreturn f;\r}\rvec3 pattern(vec2 uv)\r{\rvec2 p=-1.0+2.0*uv;\rfloat p2=dot(p,p);\rfloat f=fbm(vec2(15.0*p2))/2.0;\rfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\rfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\rfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\rreturn (1.0-f)*vec3(r,g,b);\r}\rfloat luminance(vec3 color)\r{\rreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\r}\rvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\r{\rreturn vec4(\rtexture2D(tex,texcoord+direction*distortion.r).r,\rtexture2D(tex,texcoord+direction*distortion.g).g,\rtexture2D(tex,texcoord+direction*distortion.b).b,\r1.0\r);\r}\rvoid main(void)\r{\rvec2 uv=-vUV+vec2(1.0);\rvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\rvec2 texelSize=1.0/resolution;\rvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\rvec4 result=vec4(0.0);\rfloat ghostIndice=1.0;\rfor (int i=0; i=nSamples)\rbreak;\rvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\rresult+=texture2D(textureSampler,offset1);\r}\rgl_FragColor=result/float(nSamples);\r}\r#endif\n`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const standardPixelShader = { name, shader };\n//# sourceMappingURL=standard.fragment.js.map","import { __decorate } from \"../../../tslib.es6.js\";\nimport { serialize, serializeAsTexture, SerializationHelper } from \"../../../Misc/decorators.js\";\nimport { Logger } from \"../../../Misc/logger.js\";\nimport { Vector2, Vector3, Matrix, Vector4 } from \"../../../Maths/math.vector.js\";\nimport { Scalar } from \"../../../Maths/math.scalar.js\";\nimport { Texture } from \"../../../Materials/Textures/texture.js\";\nimport { PostProcess } from \"../../../PostProcesses/postProcess.js\";\nimport { PostProcessRenderPipeline } from \"../../../PostProcesses/RenderPipeline/postProcessRenderPipeline.js\";\nimport { PostProcessRenderEffect } from \"../../../PostProcesses/RenderPipeline/postProcessRenderEffect.js\";\nimport { BlurPostProcess } from \"../../../PostProcesses/blurPostProcess.js\";\nimport { FxaaPostProcess } from \"../../../PostProcesses/fxaaPostProcess.js\";\n\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { MotionBlurPostProcess } from \"../../motionBlurPostProcess.js\";\nimport { ScreenSpaceReflectionPostProcess } from \"../../screenSpaceReflectionPostProcess.js\";\nimport \"../../../PostProcesses/RenderPipeline/postProcessRenderPipelineManagerSceneComponent.js\";\nimport \"../../../Shaders/standard.fragment.js\";\n/**\n * Standard rendering pipeline\n * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/standardRenderingPipeline\n */\nexport class StandardRenderingPipeline extends PostProcessRenderPipeline {\n /**\n * Gets the overall exposure used by the pipeline\n */\n get exposure() {\n return this._fixedExposure;\n }\n /**\n * Sets the overall exposure used by the pipeline\n */\n set exposure(value) {\n this._fixedExposure = value;\n this._currentExposure = value;\n }\n /**\n * Gets whether or not the exposure of the overall pipeline should be automatically adjusted by the HDR post-process\n */\n get hdrAutoExposure() {\n return this._hdrAutoExposure;\n }\n /**\n * Sets whether or not the exposure of the overall pipeline should be automatically adjusted by the HDR post-process\n */\n set hdrAutoExposure(value) {\n this._hdrAutoExposure = value;\n if (this.hdrPostProcess) {\n const defines = [\"#define HDR\"];\n if (value) {\n defines.push(\"#define AUTO_EXPOSURE\");\n }\n this.hdrPostProcess.updateEffect(defines.join(\"\\n\"));\n }\n }\n /**\n * Gets how much the image is blurred by the movement while using the motion blur post-process\n */\n get motionStrength() {\n return this._motionStrength;\n }\n /**\n * Sets how much the image is blurred by the movement while using the motion blur post-process\n */\n set motionStrength(strength) {\n this._motionStrength = strength;\n if (this._isObjectBasedMotionBlur && this.motionBlurPostProcess) {\n this.motionBlurPostProcess.motionStrength = strength;\n }\n }\n /**\n * Gets whether or not the motion blur post-process is object based or screen based.\n */\n get objectBasedMotionBlur() {\n return this._isObjectBasedMotionBlur;\n }\n /**\n * Sets whether or not the motion blur post-process should be object based or screen based\n */\n set objectBasedMotionBlur(value) {\n const shouldRebuild = this._isObjectBasedMotionBlur !== value;\n this._isObjectBasedMotionBlur = value;\n if (shouldRebuild) {\n this._buildPipeline();\n }\n }\n /**\n * @ignore\n * Specifies if the bloom pipeline is enabled\n */\n get BloomEnabled() {\n return this._bloomEnabled;\n }\n set BloomEnabled(enabled) {\n if (this._bloomEnabled === enabled) {\n return;\n }\n this._bloomEnabled = enabled;\n this._buildPipeline();\n }\n /**\n * @ignore\n * Specifies if the depth of field pipeline is enabled\n */\n get DepthOfFieldEnabled() {\n return this._depthOfFieldEnabled;\n }\n set DepthOfFieldEnabled(enabled) {\n if (this._depthOfFieldEnabled === enabled) {\n return;\n }\n this._depthOfFieldEnabled = enabled;\n this._buildPipeline();\n }\n /**\n * @ignore\n * Specifies if the lens flare pipeline is enabled\n */\n get LensFlareEnabled() {\n return this._lensFlareEnabled;\n }\n set LensFlareEnabled(enabled) {\n if (this._lensFlareEnabled === enabled) {\n return;\n }\n this._lensFlareEnabled = enabled;\n this._buildPipeline();\n }\n /**\n * @ignore\n * Specifies if the HDR pipeline is enabled\n */\n get HDREnabled() {\n return this._hdrEnabled;\n }\n set HDREnabled(enabled) {\n if (this._hdrEnabled === enabled) {\n return;\n }\n this._hdrEnabled = enabled;\n this._buildPipeline();\n }\n /**\n * @ignore\n * Specifies if the volumetric lights scattering effect is enabled\n */\n get VLSEnabled() {\n return this._vlsEnabled;\n }\n // eslint-disable-next-line @typescript-eslint/naming-convention\n set VLSEnabled(enabled) {\n if (this._vlsEnabled === enabled) {\n return;\n }\n if (enabled) {\n const geometry = this._scene.enableGeometryBufferRenderer();\n if (!geometry) {\n Logger.Warn(\"Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline\");\n return;\n }\n }\n this._vlsEnabled = enabled;\n this._buildPipeline();\n }\n /**\n * @ignore\n * Specifies if the motion blur effect is enabled\n */\n get MotionBlurEnabled() {\n return this._motionBlurEnabled;\n }\n set MotionBlurEnabled(enabled) {\n if (this._motionBlurEnabled === enabled) {\n return;\n }\n this._motionBlurEnabled = enabled;\n this._buildPipeline();\n }\n /**\n * Specifies if anti-aliasing is enabled\n */\n get fxaaEnabled() {\n return this._fxaaEnabled;\n }\n set fxaaEnabled(enabled) {\n if (this._fxaaEnabled === enabled) {\n return;\n }\n this._fxaaEnabled = enabled;\n this._buildPipeline();\n }\n /**\n * Specifies if screen space reflections are enabled.\n */\n get screenSpaceReflectionsEnabled() {\n return this._screenSpaceReflectionsEnabled;\n }\n set screenSpaceReflectionsEnabled(enabled) {\n if (this._screenSpaceReflectionsEnabled === enabled) {\n return;\n }\n this._screenSpaceReflectionsEnabled = enabled;\n this._buildPipeline();\n }\n /**\n * Specifies the number of steps used to calculate the volumetric lights\n * Typically in interval [50, 200]\n */\n get volumetricLightStepsCount() {\n return this._volumetricLightStepsCount;\n }\n set volumetricLightStepsCount(count) {\n if (this.volumetricLightPostProcess) {\n this.volumetricLightPostProcess.updateEffect(\"#define VLS\\n#define NB_STEPS \" + count.toFixed(1));\n }\n this._volumetricLightStepsCount = count;\n }\n /**\n * Specifies the number of samples used for the motion blur effect\n * Typically in interval [16, 64]\n */\n get motionBlurSamples() {\n return this._motionBlurSamples;\n }\n set motionBlurSamples(samples) {\n if (this.motionBlurPostProcess) {\n if (this._isObjectBasedMotionBlur) {\n this.motionBlurPostProcess.motionBlurSamples = samples;\n }\n else {\n this.motionBlurPostProcess.updateEffect(\"#define MOTION_BLUR\\n#define MAX_MOTION_SAMPLES \" + samples.toFixed(1));\n }\n }\n this._motionBlurSamples = samples;\n }\n /**\n * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)\n */\n get samples() {\n return this._samples;\n }\n set samples(sampleCount) {\n if (this._samples === sampleCount) {\n return;\n }\n this._samples = sampleCount;\n this._buildPipeline();\n }\n /**\n * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.\n * @constructor\n * @param name The rendering pipeline name\n * @param scene The scene linked to this pipeline\n * @param ratio The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)\n * @param originalPostProcess the custom original color post-process. Must be \"reusable\". Can be null.\n * @param cameras The array of cameras that the rendering pipeline will be attached to\n */\n constructor(name, scene, ratio, originalPostProcess = null, cameras) {\n super(scene.getEngine(), name);\n /**\n * Post-process used to down scale an image x4\n */\n this.downSampleX4PostProcess = null;\n /**\n * Post-process used to calculate the illuminated surfaces controlled by a threshold\n */\n this.brightPassPostProcess = null;\n /**\n * Post-process array storing all the horizontal blur post-processes used by the pipeline\n */\n this.blurHPostProcesses = [];\n /**\n * Post-process array storing all the vertical blur post-processes used by the pipeline\n */\n this.blurVPostProcesses = [];\n /**\n * Post-process used to add colors of 2 textures (typically brightness + real scene color)\n */\n this.textureAdderPostProcess = null;\n /**\n * Post-process used to create volumetric lighting effect\n */\n this.volumetricLightPostProcess = null;\n /**\n * Post-process used to smooth the previous volumetric light post-process on the X axis\n */\n this.volumetricLightSmoothXPostProcess = null;\n /**\n * Post-process used to smooth the previous volumetric light post-process on the Y axis\n */\n this.volumetricLightSmoothYPostProcess = null;\n /**\n * Post-process used to merge the volumetric light effect and the real scene color\n */\n this.volumetricLightMergePostProces = null;\n /**\n * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)\n */\n this.volumetricLightFinalPostProcess = null;\n /**\n * Base post-process used to calculate the average luminance of the final image for HDR\n */\n this.luminancePostProcess = null;\n /**\n * Post-processes used to create down sample post-processes in order to get\n * the average luminance of the final image for HDR\n * Array of length \"StandardRenderingPipeline.LuminanceSteps\"\n */\n this.luminanceDownSamplePostProcesses = [];\n /**\n * Post-process used to create a HDR effect (light adaptation)\n */\n this.hdrPostProcess = null;\n /**\n * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)\n */\n this.textureAdderFinalPostProcess = null;\n /**\n * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)\n */\n this.lensFlareFinalPostProcess = null;\n /**\n * Post-process used to merge the final HDR post-process and the real scene color\n */\n this.hdrFinalPostProcess = null;\n /**\n * Post-process used to create a lens flare effect\n */\n this.lensFlarePostProcess = null;\n /**\n * Post-process that merges the result of the lens flare post-process and the real scene color\n */\n this.lensFlareComposePostProcess = null;\n /**\n * Post-process used to create a motion blur effect\n */\n this.motionBlurPostProcess = null;\n /**\n * Post-process used to create a depth of field effect\n */\n this.depthOfFieldPostProcess = null;\n /**\n * The Fast Approximate Anti-Aliasing post process which attempts to remove aliasing from an image.\n */\n this.fxaaPostProcess = null;\n /**\n * Post-process used to simulate realtime reflections using the screen space and geometry renderer.\n */\n this.screenSpaceReflectionPostProcess = null;\n // Values\n /**\n * Represents the brightness threshold in order to configure the illuminated surfaces\n */\n this.brightThreshold = 1.0;\n /**\n * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)\n */\n this.blurWidth = 512.0;\n /**\n * Sets if the blur for highlighted surfaces must be only horizontal\n */\n this.horizontalBlur = false;\n /**\n * Texture used typically to simulate \"dirty\" on camera lens\n */\n this.lensTexture = null;\n /**\n * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]\n */\n this.volumetricLightCoefficient = 0.2;\n /**\n * The overall power of volumetric lights, typically in interval [0, 10] maximum\n */\n this.volumetricLightPower = 4.0;\n /**\n * Used the set the blur intensity to smooth the volumetric lights\n */\n this.volumetricLightBlurScale = 64.0;\n /**\n * Light (spot or directional) used to generate the volumetric lights rays\n * The source light must have a shadow generate so the pipeline can get its\n * depth map\n */\n this.sourceLight = null;\n /**\n * For eye adaptation, represents the minimum luminance the eye can see\n */\n this.hdrMinimumLuminance = 1.0;\n /**\n * For eye adaptation, represents the decrease luminance speed\n */\n this.hdrDecreaseRate = 0.5;\n /**\n * For eye adaptation, represents the increase luminance speed\n */\n this.hdrIncreaseRate = 0.5;\n /**\n * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled\n */\n this.lensColorTexture = null;\n /**\n * The overall strength for the lens flare effect\n */\n this.lensFlareStrength = 20.0;\n /**\n * Dispersion coefficient for lens flare ghosts\n */\n this.lensFlareGhostDispersal = 1.4;\n /**\n * Main lens flare halo width\n */\n this.lensFlareHaloWidth = 0.7;\n /**\n * Based on the lens distortion effect, defines how much the lens flare result\n * is distorted\n */\n this.lensFlareDistortionStrength = 16.0;\n /**\n * Configures the blur intensity used for for lens flare (halo)\n */\n this.lensFlareBlurWidth = 512.0;\n /**\n * Lens star texture must be used to simulate rays on the flares and is available\n * in the documentation\n */\n this.lensStarTexture = null;\n /**\n * As the \"lensTexture\" (can be the same texture or different), it is used to apply the lens\n * flare effect by taking account of the dirt texture\n */\n this.lensFlareDirtTexture = null;\n /**\n * Represents the focal length for the depth of field effect\n */\n this.depthOfFieldDistance = 10.0;\n /**\n * Represents the blur intensity for the blurred part of the depth of field effect\n */\n this.depthOfFieldBlurWidth = 64.0;\n /**\n * List of animations for the pipeline (IAnimatable implementation)\n */\n this.animations = [];\n this._currentDepthOfFieldSource = null;\n this._fixedExposure = 1.0;\n this._currentExposure = 1.0;\n this._hdrAutoExposure = false;\n this._hdrCurrentLuminance = 1.0;\n this._motionStrength = 1.0;\n this._isObjectBasedMotionBlur = false;\n this._camerasToBeAttached = [];\n // Getters and setters\n this._bloomEnabled = false;\n this._depthOfFieldEnabled = false;\n this._vlsEnabled = false;\n this._lensFlareEnabled = false;\n this._hdrEnabled = false;\n this._motionBlurEnabled = false;\n this._fxaaEnabled = false;\n this._screenSpaceReflectionsEnabled = false;\n this._motionBlurSamples = 64.0;\n this._volumetricLightStepsCount = 50.0;\n this._samples = 1;\n this._cameras = cameras || scene.cameras;\n this._cameras = this._cameras.slice();\n this._camerasToBeAttached = this._cameras.slice();\n // Initialize\n this._scene = scene;\n this._basePostProcess = originalPostProcess;\n this._ratio = ratio;\n // Misc\n this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? 1 : 2;\n // Finish\n scene.postProcessRenderPipelineManager.addPipeline(this);\n this._buildPipeline();\n }\n _buildPipeline() {\n const ratio = this._ratio;\n const scene = this._scene;\n this._disposePostProcesses();\n if (this._cameras !== null) {\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);\n // get back cameras to be used to reattach pipeline\n this._cameras = this._camerasToBeAttached.slice();\n }\n this._reset();\n // Create pass post-process\n if (this._screenSpaceReflectionsEnabled) {\n this.screenSpaceReflectionPostProcess = new ScreenSpaceReflectionPostProcess(\"HDRPass\", scene, ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, this._floatTextureType);\n this.screenSpaceReflectionPostProcess.onApplyObservable.add(() => {\n this._currentDepthOfFieldSource = this.screenSpaceReflectionPostProcess;\n });\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRScreenSpaceReflections\", () => this.screenSpaceReflectionPostProcess, true));\n }\n if (!this._basePostProcess) {\n this.originalPostProcess = new PostProcess(\"HDRPass\", \"standard\", [], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define PASS_POST_PROCESS\", this._floatTextureType);\n }\n else {\n this.originalPostProcess = this._basePostProcess;\n }\n this.originalPostProcess.autoClear = !this.screenSpaceReflectionPostProcess;\n this.originalPostProcess.onApplyObservable.add(() => {\n this._currentDepthOfFieldSource = this.originalPostProcess;\n });\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRPassPostProcess\", () => this.originalPostProcess, true));\n if (this._bloomEnabled) {\n // Create down sample X4 post-process\n this._createDownSampleX4PostProcess(scene, ratio / 4);\n // Create bright pass post-process\n this._createBrightPassPostProcess(scene, ratio / 4);\n // Create gaussian blur post-processes (down sampling blurs)\n this._createBlurPostProcesses(scene, ratio / 4, 1);\n // Create texture adder post-process\n this._createTextureAdderPostProcess(scene, ratio);\n // Create depth-of-field source post-process\n this.textureAdderFinalPostProcess = new PostProcess(\"HDRDepthOfFieldSource\", \"standard\", [], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define PASS_POST_PROCESS\", 0);\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRBaseDepthOfFieldSource\", () => {\n return this.textureAdderFinalPostProcess;\n }, true));\n }\n if (this._vlsEnabled) {\n // Create volumetric light\n this._createVolumetricLightPostProcess(scene, ratio);\n // Create volumetric light final post-process\n this.volumetricLightFinalPostProcess = new PostProcess(\"HDRVLSFinal\", \"standard\", [], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define PASS_POST_PROCESS\", 0);\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRVLSFinal\", () => {\n return this.volumetricLightFinalPostProcess;\n }, true));\n }\n if (this._lensFlareEnabled) {\n // Create lens flare post-process\n this._createLensFlarePostProcess(scene, ratio);\n // Create depth-of-field source post-process post lens-flare and disable it now\n this.lensFlareFinalPostProcess = new PostProcess(\"HDRPostLensFlareDepthOfFieldSource\", \"standard\", [], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define PASS_POST_PROCESS\", 0);\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRPostLensFlareDepthOfFieldSource\", () => {\n return this.lensFlareFinalPostProcess;\n }, true));\n }\n if (this._hdrEnabled) {\n // Create luminance\n this._createLuminancePostProcesses(scene, this._floatTextureType);\n // Create HDR\n this._createHdrPostProcess(scene, ratio);\n // Create depth-of-field source post-process post hdr and disable it now\n this.hdrFinalPostProcess = new PostProcess(\"HDRPostHDReDepthOfFieldSource\", \"standard\", [], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define PASS_POST_PROCESS\", 0);\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRPostHDReDepthOfFieldSource\", () => {\n return this.hdrFinalPostProcess;\n }, true));\n }\n if (this._depthOfFieldEnabled) {\n // Create gaussian blur used by depth-of-field\n this._createBlurPostProcesses(scene, ratio / 2, 3, \"depthOfFieldBlurWidth\");\n // Create depth-of-field post-process\n this._createDepthOfFieldPostProcess(scene, ratio);\n }\n if (this._motionBlurEnabled) {\n // Create motion blur post-process\n this._createMotionBlurPostProcess(scene, ratio);\n }\n if (this._fxaaEnabled) {\n // Create fxaa post-process\n this.fxaaPostProcess = new FxaaPostProcess(\"fxaa\", 1.0, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, 0);\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRFxaa\", () => {\n return this.fxaaPostProcess;\n }, true));\n }\n if (this._cameras !== null) {\n this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);\n }\n if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {\n Logger.Warn(\"MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0\");\n }\n }\n // Down Sample X4 Post-Process\n _createDownSampleX4PostProcess(scene, ratio) {\n const downSampleX4Offsets = new Array(32);\n this.downSampleX4PostProcess = new PostProcess(\"HDRDownSampleX4\", \"standard\", [\"dsOffsets\"], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define DOWN_SAMPLE_X4\", this._floatTextureType);\n this.downSampleX4PostProcess.onApply = (effect) => {\n let id = 0;\n const width = this.downSampleX4PostProcess.width;\n const height = this.downSampleX4PostProcess.height;\n for (let i = -2; i < 2; i++) {\n for (let j = -2; j < 2; j++) {\n downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);\n downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);\n id += 2;\n }\n }\n effect.setArray2(\"dsOffsets\", downSampleX4Offsets);\n };\n // Add to pipeline\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRDownSampleX4\", () => {\n return this.downSampleX4PostProcess;\n }, true));\n }\n // Brightpass Post-Process\n _createBrightPassPostProcess(scene, ratio) {\n const brightOffsets = new Array(8);\n this.brightPassPostProcess = new PostProcess(\"HDRBrightPass\", \"standard\", [\"dsOffsets\", \"brightThreshold\"], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define BRIGHT_PASS\", this._floatTextureType);\n this.brightPassPostProcess.onApply = (effect) => {\n const sU = 1.0 / this.brightPassPostProcess.width;\n const sV = 1.0 / this.brightPassPostProcess.height;\n brightOffsets[0] = -0.5 * sU;\n brightOffsets[1] = 0.5 * sV;\n brightOffsets[2] = 0.5 * sU;\n brightOffsets[3] = 0.5 * sV;\n brightOffsets[4] = -0.5 * sU;\n brightOffsets[5] = -0.5 * sV;\n brightOffsets[6] = 0.5 * sU;\n brightOffsets[7] = -0.5 * sV;\n effect.setArray2(\"dsOffsets\", brightOffsets);\n effect.setFloat(\"brightThreshold\", this.brightThreshold);\n };\n // Add to pipeline\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRBrightPass\", () => {\n return this.brightPassPostProcess;\n }, true));\n }\n // Create blur H&V post-processes\n _createBlurPostProcesses(scene, ratio, indice, blurWidthKey = \"blurWidth\") {\n const engine = scene.getEngine();\n const blurX = new BlurPostProcess(\"HDRBlurH\" + \"_\" + indice, new Vector2(1, 0), this[blurWidthKey], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, this._floatTextureType);\n const blurY = new BlurPostProcess(\"HDRBlurV\" + \"_\" + indice, new Vector2(0, 1), this[blurWidthKey], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, this._floatTextureType);\n blurX.onActivateObservable.add(() => {\n const dw = blurX.width / engine.getRenderWidth();\n blurX.kernel = this[blurWidthKey] * dw;\n });\n blurY.onActivateObservable.add(() => {\n const dw = blurY.height / engine.getRenderHeight();\n blurY.kernel = this.horizontalBlur ? 64 * dw : this[blurWidthKey] * dw;\n });\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRBlurH\" + indice, () => {\n return blurX;\n }, true));\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRBlurV\" + indice, () => {\n return blurY;\n }, true));\n this.blurHPostProcesses.push(blurX);\n this.blurVPostProcesses.push(blurY);\n }\n // Create texture adder post-process\n _createTextureAdderPostProcess(scene, ratio) {\n this.textureAdderPostProcess = new PostProcess(\"HDRTextureAdder\", \"standard\", [\"exposure\"], [\"otherSampler\", \"lensSampler\"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define TEXTURE_ADDER\", this._floatTextureType);\n this.textureAdderPostProcess.onApply = (effect) => {\n effect.setTextureFromPostProcess(\"otherSampler\", this._vlsEnabled ? this._currentDepthOfFieldSource : this.originalPostProcess);\n effect.setTexture(\"lensSampler\", this.lensTexture);\n effect.setFloat(\"exposure\", this._currentExposure);\n this._currentDepthOfFieldSource = this.textureAdderFinalPostProcess;\n };\n // Add to pipeline\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRTextureAdder\", () => {\n return this.textureAdderPostProcess;\n }, true));\n }\n _createVolumetricLightPostProcess(scene, ratio) {\n const geometryRenderer = scene.enableGeometryBufferRenderer();\n geometryRenderer.enablePosition = true;\n const geometry = geometryRenderer.getGBuffer();\n // Base post-process\n this.volumetricLightPostProcess = new PostProcess(\"HDRVLS\", \"standard\", [\"shadowViewProjection\", \"cameraPosition\", \"sunDirection\", \"sunColor\", \"scatteringCoefficient\", \"scatteringPower\", \"depthValues\"], [\"shadowMapSampler\", \"positionSampler\"], ratio / 8, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define VLS\\n#define NB_STEPS \" + this._volumetricLightStepsCount.toFixed(1));\n const depthValues = Vector2.Zero();\n this.volumetricLightPostProcess.onApply = (effect) => {\n if (this.sourceLight && this.sourceLight.getShadowGenerator() && this._scene.activeCamera) {\n const generator = this.sourceLight.getShadowGenerator();\n effect.setTexture(\"shadowMapSampler\", generator.getShadowMap());\n effect.setTexture(\"positionSampler\", geometry.textures[2]);\n effect.setColor3(\"sunColor\", this.sourceLight.diffuse);\n effect.setVector3(\"sunDirection\", this.sourceLight.getShadowDirection());\n effect.setVector3(\"cameraPosition\", this._scene.activeCamera.globalPosition);\n effect.setMatrix(\"shadowViewProjection\", generator.getTransformMatrix());\n effect.setFloat(\"scatteringCoefficient\", this.volumetricLightCoefficient);\n effect.setFloat(\"scatteringPower\", this.volumetricLightPower);\n depthValues.x = this.sourceLight.getDepthMinZ(this._scene.activeCamera);\n depthValues.y = this.sourceLight.getDepthMaxZ(this._scene.activeCamera);\n effect.setVector2(\"depthValues\", depthValues);\n }\n };\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRVLS\", () => {\n return this.volumetricLightPostProcess;\n }, true));\n // Smooth\n this._createBlurPostProcesses(scene, ratio / 4, 0, \"volumetricLightBlurScale\");\n // Merge\n this.volumetricLightMergePostProces = new PostProcess(\"HDRVLSMerge\", \"standard\", [], [\"originalSampler\"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define VLSMERGE\");\n this.volumetricLightMergePostProces.onApply = (effect) => {\n effect.setTextureFromPostProcess(\"originalSampler\", this._bloomEnabled ? this.textureAdderFinalPostProcess : this.originalPostProcess);\n this._currentDepthOfFieldSource = this.volumetricLightFinalPostProcess;\n };\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRVLSMerge\", () => {\n return this.volumetricLightMergePostProces;\n }, true));\n }\n // Create luminance\n _createLuminancePostProcesses(scene, textureType) {\n // Create luminance\n let size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);\n this.luminancePostProcess = new PostProcess(\"HDRLuminance\", \"standard\", [\"lumOffsets\"], [], { width: size, height: size }, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define LUMINANCE\", textureType);\n const offsets = [];\n this.luminancePostProcess.onApply = (effect) => {\n const sU = 1.0 / this.luminancePostProcess.width;\n const sV = 1.0 / this.luminancePostProcess.height;\n offsets[0] = -0.5 * sU;\n offsets[1] = 0.5 * sV;\n offsets[2] = 0.5 * sU;\n offsets[3] = 0.5 * sV;\n offsets[4] = -0.5 * sU;\n offsets[5] = -0.5 * sV;\n offsets[6] = 0.5 * sU;\n offsets[7] = -0.5 * sV;\n effect.setArray2(\"lumOffsets\", offsets);\n };\n // Add to pipeline\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRLuminance\", () => {\n return this.luminancePostProcess;\n }, true));\n // Create down sample luminance\n for (let i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {\n size = Math.pow(3, i);\n let defines = \"#define LUMINANCE_DOWN_SAMPLE\\n\";\n if (i === 0) {\n defines += \"#define FINAL_DOWN_SAMPLER\";\n }\n const postProcess = new PostProcess(\"HDRLuminanceDownSample\" + i, \"standard\", [\"dsOffsets\", \"halfDestPixelSize\"], [], { width: size, height: size }, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);\n this.luminanceDownSamplePostProcesses.push(postProcess);\n }\n // Create callbacks and add effects\n let lastLuminance = this.luminancePostProcess;\n this.luminanceDownSamplePostProcesses.forEach((pp, index) => {\n const downSampleOffsets = new Array(18);\n pp.onApply = (effect) => {\n if (!lastLuminance) {\n return;\n }\n let id = 0;\n for (let x = -1; x < 2; x++) {\n for (let y = -1; y < 2; y++) {\n downSampleOffsets[id] = x / lastLuminance.width;\n downSampleOffsets[id + 1] = y / lastLuminance.height;\n id += 2;\n }\n }\n effect.setArray2(\"dsOffsets\", downSampleOffsets);\n effect.setFloat(\"halfDestPixelSize\", 0.5 / lastLuminance.width);\n if (index === this.luminanceDownSamplePostProcesses.length - 1) {\n lastLuminance = this.luminancePostProcess;\n }\n else {\n lastLuminance = pp;\n }\n };\n if (index === this.luminanceDownSamplePostProcesses.length - 1) {\n pp.onAfterRender = () => {\n const pixel = scene.getEngine().readPixels(0, 0, 1, 1);\n const bit_shift = new Vector4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\n pixel.then((pixel) => {\n const data = new Uint8Array(pixel.buffer);\n this._hdrCurrentLuminance = (data[0] * bit_shift.x + data[1] * bit_shift.y + data[2] * bit_shift.z + data[3] * bit_shift.w) / 100.0;\n });\n };\n }\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRLuminanceDownSample\" + index, () => {\n return pp;\n }, true));\n });\n }\n // Create HDR post-process\n _createHdrPostProcess(scene, ratio) {\n const defines = [\"#define HDR\"];\n if (this._hdrAutoExposure) {\n defines.push(\"#define AUTO_EXPOSURE\");\n }\n this.hdrPostProcess = new PostProcess(\"HDR\", \"standard\", [\"averageLuminance\"], [\"textureAdderSampler\"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines.join(\"\\n\"), 0);\n let outputLiminance = 1;\n let time = 0;\n let lastTime = 0;\n this.hdrPostProcess.onApply = (effect) => {\n effect.setTextureFromPostProcess(\"textureAdderSampler\", this._currentDepthOfFieldSource);\n time += scene.getEngine().getDeltaTime();\n if (outputLiminance < 0) {\n outputLiminance = this._hdrCurrentLuminance;\n }\n else {\n const dt = (lastTime - time) / 1000.0;\n if (this._hdrCurrentLuminance < outputLiminance + this.hdrDecreaseRate * dt) {\n outputLiminance += this.hdrDecreaseRate * dt;\n }\n else if (this._hdrCurrentLuminance > outputLiminance - this.hdrIncreaseRate * dt) {\n outputLiminance -= this.hdrIncreaseRate * dt;\n }\n else {\n outputLiminance = this._hdrCurrentLuminance;\n }\n }\n if (this.hdrAutoExposure) {\n this._currentExposure = this._fixedExposure / outputLiminance;\n }\n else {\n outputLiminance = Scalar.Clamp(outputLiminance, this.hdrMinimumLuminance, 1e20);\n effect.setFloat(\"averageLuminance\", outputLiminance);\n }\n lastTime = time;\n this._currentDepthOfFieldSource = this.hdrFinalPostProcess;\n };\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDR\", () => {\n return this.hdrPostProcess;\n }, true));\n }\n // Create lens flare post-process\n _createLensFlarePostProcess(scene, ratio) {\n this.lensFlarePostProcess = new PostProcess(\"HDRLensFlare\", \"standard\", [\"strength\", \"ghostDispersal\", \"haloWidth\", \"resolution\", \"distortionStrength\"], [\"lensColorSampler\"], ratio / 2, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define LENS_FLARE\", 0);\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRLensFlare\", () => {\n return this.lensFlarePostProcess;\n }, true));\n this._createBlurPostProcesses(scene, ratio / 4, 2, \"lensFlareBlurWidth\");\n this.lensFlareComposePostProcess = new PostProcess(\"HDRLensFlareCompose\", \"standard\", [\"lensStarMatrix\"], [\"otherSampler\", \"lensDirtSampler\", \"lensStarSampler\"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define LENS_FLARE_COMPOSE\", 0);\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRLensFlareCompose\", () => {\n return this.lensFlareComposePostProcess;\n }, true));\n const resolution = new Vector2(0, 0);\n // Lens flare\n this.lensFlarePostProcess.externalTextureSamplerBinding = true;\n this.lensFlarePostProcess.onApply = (effect) => {\n effect.setTextureFromPostProcess(\"textureSampler\", this._bloomEnabled ? this.blurHPostProcesses[0] : this.originalPostProcess);\n effect.setTexture(\"lensColorSampler\", this.lensColorTexture);\n effect.setFloat(\"strength\", this.lensFlareStrength);\n effect.setFloat(\"ghostDispersal\", this.lensFlareGhostDispersal);\n effect.setFloat(\"haloWidth\", this.lensFlareHaloWidth);\n // Shift\n resolution.x = this.lensFlarePostProcess.width;\n resolution.y = this.lensFlarePostProcess.height;\n effect.setVector2(\"resolution\", resolution);\n effect.setFloat(\"distortionStrength\", this.lensFlareDistortionStrength);\n };\n // Compose\n const scaleBias1 = Matrix.FromValues(2.0, 0.0, -1.0, 0.0, 0.0, 2.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);\n const scaleBias2 = Matrix.FromValues(0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);\n this.lensFlareComposePostProcess.onApply = (effect) => {\n if (!this._scene.activeCamera) {\n return;\n }\n effect.setTextureFromPostProcess(\"otherSampler\", this.lensFlarePostProcess);\n effect.setTexture(\"lensDirtSampler\", this.lensFlareDirtTexture);\n effect.setTexture(\"lensStarSampler\", this.lensStarTexture);\n // Lens start rotation matrix\n const camerax = this._scene.activeCamera.getViewMatrix().getRow(0);\n const cameraz = this._scene.activeCamera.getViewMatrix().getRow(2);\n let camRot = Vector3.Dot(camerax.toVector3(), new Vector3(1.0, 0.0, 0.0)) + Vector3.Dot(cameraz.toVector3(), new Vector3(0.0, 0.0, 1.0));\n camRot *= 4.0;\n const starRotation = Matrix.FromValues(Math.cos(camRot) * 0.5, -Math.sin(camRot), 0.0, 0.0, Math.sin(camRot), Math.cos(camRot) * 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);\n const lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);\n effect.setMatrix(\"lensStarMatrix\", lensStarMatrix);\n this._currentDepthOfFieldSource = this.lensFlareFinalPostProcess;\n };\n }\n // Create depth-of-field post-process\n _createDepthOfFieldPostProcess(scene, ratio) {\n this.depthOfFieldPostProcess = new PostProcess(\"HDRDepthOfField\", \"standard\", [\"distance\"], [\"otherSampler\", \"depthSampler\"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define DEPTH_OF_FIELD\", 0);\n this.depthOfFieldPostProcess.onApply = (effect) => {\n effect.setTextureFromPostProcess(\"otherSampler\", this._currentDepthOfFieldSource);\n effect.setTexture(\"depthSampler\", this._getDepthTexture());\n effect.setFloat(\"distance\", this.depthOfFieldDistance);\n };\n // Add to pipeline\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRDepthOfField\", () => {\n return this.depthOfFieldPostProcess;\n }, true));\n }\n // Create motion blur post-process\n _createMotionBlurPostProcess(scene, ratio) {\n if (this._isObjectBasedMotionBlur) {\n const mb = new MotionBlurPostProcess(\"HDRMotionBlur\", scene, ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, 0);\n mb.motionStrength = this.motionStrength;\n mb.motionBlurSamples = this.motionBlurSamples;\n this.motionBlurPostProcess = mb;\n }\n else {\n this.motionBlurPostProcess = new PostProcess(\"HDRMotionBlur\", \"standard\", [\"inverseViewProjection\", \"prevViewProjection\", \"screenSize\", \"motionScale\", \"motionStrength\"], [\"depthSampler\"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define MOTION_BLUR\\n#define MAX_MOTION_SAMPLES \" + this.motionBlurSamples.toFixed(1), 0);\n let motionScale = 0;\n let prevViewProjection = Matrix.Identity();\n const invViewProjection = Matrix.Identity();\n let viewProjection = Matrix.Identity();\n const screenSize = Vector2.Zero();\n this.motionBlurPostProcess.onApply = (effect) => {\n viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());\n viewProjection.invertToRef(invViewProjection);\n effect.setMatrix(\"inverseViewProjection\", invViewProjection);\n effect.setMatrix(\"prevViewProjection\", prevViewProjection);\n prevViewProjection = viewProjection;\n screenSize.x = this.motionBlurPostProcess.width;\n screenSize.y = this.motionBlurPostProcess.height;\n effect.setVector2(\"screenSize\", screenSize);\n motionScale = scene.getEngine().getFps() / 60.0;\n effect.setFloat(\"motionScale\", motionScale);\n effect.setFloat(\"motionStrength\", this.motionStrength);\n effect.setTexture(\"depthSampler\", this._getDepthTexture());\n };\n }\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRMotionBlur\", () => {\n return this.motionBlurPostProcess;\n }, true));\n }\n _getDepthTexture() {\n if (this._scene.getEngine().getCaps().drawBuffersExtension) {\n const renderer = this._scene.enableGeometryBufferRenderer();\n return renderer.getGBuffer().textures[0];\n }\n return this._scene.enableDepthRenderer().getDepthMap();\n }\n _disposePostProcesses() {\n for (let i = 0; i < this._cameras.length; i++) {\n const camera = this._cameras[i];\n if (this.originalPostProcess) {\n this.originalPostProcess.dispose(camera);\n }\n if (this.screenSpaceReflectionPostProcess) {\n this.screenSpaceReflectionPostProcess.dispose(camera);\n }\n if (this.downSampleX4PostProcess) {\n this.downSampleX4PostProcess.dispose(camera);\n }\n if (this.brightPassPostProcess) {\n this.brightPassPostProcess.dispose(camera);\n }\n if (this.textureAdderPostProcess) {\n this.textureAdderPostProcess.dispose(camera);\n }\n if (this.volumetricLightPostProcess) {\n this.volumetricLightPostProcess.dispose(camera);\n }\n if (this.volumetricLightSmoothXPostProcess) {\n this.volumetricLightSmoothXPostProcess.dispose(camera);\n }\n if (this.volumetricLightSmoothYPostProcess) {\n this.volumetricLightSmoothYPostProcess.dispose(camera);\n }\n if (this.volumetricLightMergePostProces) {\n this.volumetricLightMergePostProces.dispose(camera);\n }\n if (this.volumetricLightFinalPostProcess) {\n this.volumetricLightFinalPostProcess.dispose(camera);\n }\n if (this.lensFlarePostProcess) {\n this.lensFlarePostProcess.dispose(camera);\n }\n if (this.lensFlareComposePostProcess) {\n this.lensFlareComposePostProcess.dispose(camera);\n }\n for (let j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {\n this.luminanceDownSamplePostProcesses[j].dispose(camera);\n }\n if (this.luminancePostProcess) {\n this.luminancePostProcess.dispose(camera);\n }\n if (this.hdrPostProcess) {\n this.hdrPostProcess.dispose(camera);\n }\n if (this.hdrFinalPostProcess) {\n this.hdrFinalPostProcess.dispose(camera);\n }\n if (this.depthOfFieldPostProcess) {\n this.depthOfFieldPostProcess.dispose(camera);\n }\n if (this.motionBlurPostProcess) {\n this.motionBlurPostProcess.dispose(camera);\n }\n if (this.fxaaPostProcess) {\n this.fxaaPostProcess.dispose(camera);\n }\n for (let j = 0; j < this.blurHPostProcesses.length; j++) {\n this.blurHPostProcesses[j].dispose(camera);\n }\n for (let j = 0; j < this.blurVPostProcesses.length; j++) {\n this.blurVPostProcesses[j].dispose(camera);\n }\n }\n this.originalPostProcess = null;\n this.downSampleX4PostProcess = null;\n this.brightPassPostProcess = null;\n this.textureAdderPostProcess = null;\n this.textureAdderFinalPostProcess = null;\n this.volumetricLightPostProcess = null;\n this.volumetricLightSmoothXPostProcess = null;\n this.volumetricLightSmoothYPostProcess = null;\n this.volumetricLightMergePostProces = null;\n this.volumetricLightFinalPostProcess = null;\n this.lensFlarePostProcess = null;\n this.lensFlareComposePostProcess = null;\n this.luminancePostProcess = null;\n this.hdrPostProcess = null;\n this.hdrFinalPostProcess = null;\n this.depthOfFieldPostProcess = null;\n this.motionBlurPostProcess = null;\n this.fxaaPostProcess = null;\n this.screenSpaceReflectionPostProcess = null;\n this.luminanceDownSamplePostProcesses.length = 0;\n this.blurHPostProcesses.length = 0;\n this.blurVPostProcesses.length = 0;\n }\n /**\n * Dispose of the pipeline and stop all post processes\n */\n dispose() {\n this._disposePostProcesses();\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);\n super.dispose();\n }\n /**\n * Serialize the rendering pipeline (Used when exporting)\n * @returns the serialized object\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this);\n if (this.sourceLight) {\n serializationObject.sourceLightId = this.sourceLight.id;\n }\n if (this.screenSpaceReflectionPostProcess) {\n serializationObject.screenSpaceReflectionPostProcess = SerializationHelper.Serialize(this.screenSpaceReflectionPostProcess);\n }\n serializationObject.customType = \"StandardRenderingPipeline\";\n return serializationObject;\n }\n /**\n * Parse the serialized pipeline\n * @param source Source pipeline.\n * @param scene The scene to load the pipeline to.\n * @param rootUrl The URL of the serialized pipeline.\n * @returns An instantiated pipeline from the serialized object.\n */\n static Parse(source, scene, rootUrl) {\n const p = SerializationHelper.Parse(() => new StandardRenderingPipeline(source._name, scene, source._ratio), source, scene, rootUrl);\n if (source.sourceLightId) {\n p.sourceLight = scene.getLightById(source.sourceLightId);\n }\n if (source.screenSpaceReflectionPostProcess) {\n SerializationHelper.Parse(() => p.screenSpaceReflectionPostProcess, source.screenSpaceReflectionPostProcess, scene, rootUrl);\n }\n return p;\n }\n}\n/**\n * Luminance steps\n */\nStandardRenderingPipeline.LuminanceSteps = 6;\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"brightThreshold\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"blurWidth\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"horizontalBlur\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"exposure\", null);\n__decorate([\n serializeAsTexture(\"lensTexture\")\n], StandardRenderingPipeline.prototype, \"lensTexture\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"volumetricLightCoefficient\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"volumetricLightPower\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"volumetricLightBlurScale\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"hdrMinimumLuminance\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"hdrDecreaseRate\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"hdrIncreaseRate\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"hdrAutoExposure\", null);\n__decorate([\n serializeAsTexture(\"lensColorTexture\")\n], StandardRenderingPipeline.prototype, \"lensColorTexture\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"lensFlareStrength\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"lensFlareGhostDispersal\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"lensFlareHaloWidth\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"lensFlareDistortionStrength\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"lensFlareBlurWidth\", void 0);\n__decorate([\n serializeAsTexture(\"lensStarTexture\")\n], StandardRenderingPipeline.prototype, \"lensStarTexture\", void 0);\n__decorate([\n serializeAsTexture(\"lensFlareDirtTexture\")\n], StandardRenderingPipeline.prototype, \"lensFlareDirtTexture\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"depthOfFieldDistance\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"depthOfFieldBlurWidth\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"motionStrength\", null);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"objectBasedMotionBlur\", null);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"_ratio\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"BloomEnabled\", null);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"DepthOfFieldEnabled\", null);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"LensFlareEnabled\", null);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"HDREnabled\", null);\n__decorate([\n serialize()\n // eslint-disable-next-line @typescript-eslint/naming-convention\n], StandardRenderingPipeline.prototype, \"VLSEnabled\", null);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"MotionBlurEnabled\", null);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"fxaaEnabled\", null);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"screenSpaceReflectionsEnabled\", null);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"volumetricLightStepsCount\", null);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"motionBlurSamples\", null);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"samples\", null);\nRegisterClass(\"BABYLON.StandardRenderingPipeline\", StandardRenderingPipeline);\n//# sourceMappingURL=standardRenderingPipeline.js.map","\n/**\n * Contains all parameters needed for the prepass to perform\n * screen space reflections\n */\nexport class ScreenSpaceReflections2Configuration {\n constructor() {\n /**\n * Is ssr enabled\n */\n this.enabled = false;\n /**\n * Name of the configuration\n */\n this.name = \"screenSpaceReflections2\";\n /**\n * Textures that should be present in the MRT for this effect to work\n */\n this.texturesRequired = [6, 3, 5];\n }\n}\n//# sourceMappingURL=screenSpaceReflections2Configuration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"screenSpaceRayTrace\";\nconst shader = `float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); }\r/**\r\\param csOrigin Camera-space ray origin,which must be \rwithin the view volume and must have z>0.01 and project within the valid screen rectangle\r\\param csDirection Unit length camera-space ray direction\r\\param projectToPixelMatrix A projection matrix that maps to **pixel** coordinates \r(**not** [-1,+1] normalized device coordinates).\r\\param csZBuffer The camera-space Z buffer\r\\param csZBufferSize Dimensions of csZBuffer\r\\param csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer\r\\param nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value\rfor clipping rays headed towards the camera\r\\param stride Step in horizontal or vertical pixels between samples. This is a float\rbecause integer math is slow on GPUs,but should be set to an integer>=1\r\\param jitterFraction Number between 0 and 1 for how far to bump the ray in stride units\rto conceal banding artifacts,plus the stride ray offset.\r\\param maxSteps Maximum number of iterations. Higher gives better images but may be slow\r\\param maxRayTraceDistance Maximum camera-space distance to trace before returning a miss\r\\param selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions.\r1 is a reasonable value,depending on the scene you may need to set this value to 2\r\\param hitPixel Pixel coordinates of the first intersection with the scene\r\\param numIterations number of iterations performed\r\\param csHitPoint Camera space location of the ray hit\r*/\r#define inline\nbool traceScreenSpaceRay1(\rvec3 csOrigin,\rvec3 csDirection,\rmat4 projectToPixelMatrix,\rsampler2D csZBuffer,\rvec2 csZBufferSize,\r#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nsampler2D csZBackBuffer,\rfloat csZBackSizeFactor,\r#endif\nfloat csZThickness,\rfloat nearPlaneZ,\rfloat stride,\rfloat jitterFraction,\rfloat maxSteps,\rfloat maxRayTraceDistance,\rfloat selfCollisionNumSkip,\rout vec2 startPixel,\rout vec2 hitPixel,\rout vec3 csHitPoint,\rout float numIterations\r#ifdef SSRAYTRACE_DEBUG\n,out vec3 debugColor\r#endif\n)\r{\r#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance;\r#else\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)yMax) || (P1.yyMax) ? yMax : yMin))/(P1.y-P0.y);\r}\rif ((P1.x>xMax) || (P1.xxMax) ? xMax : xMin))/(P1.x-P0.x));\r}\rP1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha);\r#endif\nP1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);\rvec2 delta=P1-P0;\rbool permute=false;\rif (abs(delta.x)rayZMax) { \rfloat t=rayZMin; rayZMin=rayZMax; rayZMax=t;\r}\rsceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r;\r#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;\rhit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax);\r#else\nhit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax);\r#endif\n#else\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;\rhit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0);\r#else\nhit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax);\r#endif\n#endif\n}\rpqk-=dPQK;\rstepCount-=1.0;\rif (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {\rhit=false;\r}\r#ifdef SSRAYTRACE_ENABLE_REFINEMENT\nif (stride>1.0 && hit) {\rpqk-=dPQK;\rstepCount-=1.0;\rfloat invStride=1.0/stride;\rdPQK*=invStride;\rfloat refinementStepCount=0.0;\rprevZMaxEstimate=pqk.z/pqk.w;\rrayZMax=prevZMaxEstimate;\rsceneZMax=rayZMax+1e7;\rfor (;\rrefinementStepCount<=1.0 ||\r(refinementStepCount<=stride*1.4) &&\r(rayZMaxend) {\rdebugColor=vec3(0,0,1);\r} else if ((stepCount+1.0)>=maxSteps) {\rdebugColor=vec3(1,0,0);\r} else if (sceneZMax==0.0) {\rdebugColor=vec3(1,1,0);\r} else {\rdebugColor=vec3(0,stepCount/maxSteps,0);\r}\r#endif\nreturn hit;\r}\r/**\rtexCoord: in the [0,1] range\rdepth: depth in view space (range [znear,zfar]])\r*/\rvec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {\rvec4 ndc;\rndc.xy=texCoord*2.0-1.0;\r#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nndc.z=-projection[2].z-projection[3].z/depth;\r#else\nndc.z=projection[2].z+projection[3].z/depth;\r#endif\nndc.w=1.0;\rvec4 eyePos=invProjectionMatrix*ndc;\reyePos.xyz/=eyePos.w;\rreturn eyePos.xyz;\r}\r`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const screenSpaceRayTrace = { name, shader };\n//# sourceMappingURL=screenSpaceRayTrace.js.map","import { __decorate } from \"../../../tslib.es6.js\";\n/* eslint-disable @typescript-eslint/naming-convention */\nimport { serialize, SerializationHelper } from \"../../../Misc/decorators.js\";\nimport { Vector3, Matrix, Quaternion, TmpVectors } from \"../../../Maths/math.vector.js\";\nimport { PostProcess } from \"../../postProcess.js\";\nimport { PostProcessRenderPipeline } from \"../postProcessRenderPipeline.js\";\nimport { PostProcessRenderEffect } from \"../postProcessRenderEffect.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { ScreenSpaceReflections2Configuration } from \"../../../Rendering/screenSpaceReflections2Configuration.js\";\nimport { GeometryBufferRenderer } from \"../../../Rendering/geometryBufferRenderer.js\";\n\nimport { DepthRenderer } from \"../../../Rendering/depthRenderer.js\";\nimport \"../postProcessRenderPipelineManagerSceneComponent.js\";\nimport \"../../../Shaders/screenSpaceReflection2.fragment.js\";\nimport \"../../../Shaders/screenSpaceReflection2Blur.fragment.js\";\nimport \"../../../Shaders/screenSpaceReflection2BlurCombiner.fragment.js\";\nconst trs = Matrix.Compose(new Vector3(0.5, 0.5, 0.5), Quaternion.Identity(), new Vector3(0.5, 0.5, 0.5));\nconst trsWebGPU = Matrix.Compose(new Vector3(0.5, 0.5, 1), Quaternion.Identity(), new Vector3(0.5, 0.5, 0));\n/**\n * Render pipeline to produce Screen Space Reflections (SSR) effect\n *\n * References:\n * Screen Space Ray Tracing:\n * - http://casual-effects.blogspot.com/2014/08/screen-space-ray-tracing.html\n * - https://sourceforge.net/p/g3d/code/HEAD/tree/G3D10/data-files/shader/screenSpaceRayTrace.glsl\n * - https://github.com/kode80/kode80SSR\n * SSR:\n * - general tips: https://sakibsaikia.github.io/graphics/2016/12/26/Screen-Space-Reflection-in-Killing-Floor-2.html\n * - computation of blur radius from roughness and distance: https://github.com/godotengine/godot/blob/master/servers/rendering/renderer_rd/shaders/effects/screen_space_reflection.glsl\n * - blur and usage of back depth buffer: https://github.com/kode80/kode80SSR\n */\nexport class SSRRenderingPipeline extends PostProcessRenderPipeline {\n /**\n * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)\n */\n set samples(sampleCount) {\n if (this._samples === sampleCount) {\n return;\n }\n this._samples = sampleCount;\n this._buildPipeline();\n }\n get samples() {\n return this._samples;\n }\n /**\n * Gets or sets the minimum value for one of the reflectivity component of the material to consider it for SSR (default: 0.04).\n * If all r/g/b components of the reflectivity is below or equal this value, the pixel will not be considered reflective and SSR won't be applied.\n */\n get reflectivityThreshold() {\n return this._reflectivityThreshold;\n }\n set reflectivityThreshold(threshold) {\n if (threshold === this._reflectivityThreshold) {\n return;\n }\n if ((threshold === 0 && this._reflectivityThreshold !== 0) || (threshold !== 0 && this._reflectivityThreshold === 0)) {\n this._reflectivityThreshold = threshold;\n this._buildPipeline();\n }\n else {\n this._reflectivityThreshold = threshold;\n }\n }\n /**\n * Gets or sets the downsample factor used to reduce the size of the texture used to compute the SSR contribution (default: 0).\n * Use 0 to render the SSR contribution at full resolution, 1 to render at half resolution, 2 to render at 1/3 resolution, etc.\n * Note that it is used only when blurring is enabled (blurDispersionStrength \\> 0), because in that mode the SSR contribution is generated in a separate texture.\n */\n get ssrDownsample() {\n return this._ssrDownsample;\n }\n set ssrDownsample(downsample) {\n if (downsample === this._ssrDownsample) {\n return;\n }\n this._ssrDownsample = downsample;\n this._buildPipeline();\n }\n /**\n * Gets or sets the blur dispersion strength. Set this value to 0 to disable blurring (default: 0.05)\n * The reflections are blurred based on the roughness of the surface and the distance between the pixel shaded and the reflected pixel: the higher the distance the more blurry the reflection is.\n * blurDispersionStrength allows to increase or decrease this effect.\n */\n get blurDispersionStrength() {\n return this._blurDispersionStrength;\n }\n set blurDispersionStrength(strength) {\n if (strength === this._blurDispersionStrength) {\n return;\n }\n const rebuild = (strength === 0 && this._blurDispersionStrength !== 0) || (strength !== 0 && this._blurDispersionStrength === 0);\n this._blurDispersionStrength = strength;\n if (rebuild) {\n this._buildPipeline();\n }\n }\n _useBlur() {\n return this._blurDispersionStrength > 0;\n }\n /**\n * Gets or sets the downsample factor used to reduce the size of the textures used to blur the reflection effect (default: 0).\n * Use 0 to blur at full resolution, 1 to render at half resolution, 2 to render at 1/3 resolution, etc.\n */\n get blurDownsample() {\n return this._blurDownsample;\n }\n set blurDownsample(downsample) {\n if (downsample === this._blurDownsample) {\n return;\n }\n this._blurDownsample = downsample;\n this._buildPipeline();\n }\n /**\n * Gets or sets whether or not smoothing reflections is enabled (default: false)\n * Enabling smoothing will require more GPU power.\n * Note that this setting has no effect if step = 1: it's only used if step \\> 1.\n */\n get enableSmoothReflections() {\n return this._enableSmoothReflections;\n }\n set enableSmoothReflections(enabled) {\n if (enabled === this._enableSmoothReflections) {\n return;\n }\n this._enableSmoothReflections = enabled;\n this._updateEffectDefines();\n }\n /**\n * Gets or sets the environment cube texture used to define the reflection when the reflected rays of SSR leave the view space or when the maxDistance/maxSteps is reached.\n */\n get environmentTexture() {\n return this._environmentTexture;\n }\n set environmentTexture(texture) {\n this._environmentTexture = texture;\n this._updateEffectDefines();\n }\n /**\n * Gets or sets the boolean defining if the environment texture is a standard cubemap (false) or a probe (true). Default value is false.\n * Note: a probe cube texture is treated differently than an ordinary cube texture because the Y axis is reversed.\n */\n get environmentTextureIsProbe() {\n return this._environmentTextureIsProbe;\n }\n set environmentTextureIsProbe(isProbe) {\n this._environmentTextureIsProbe = isProbe;\n this._updateEffectDefines();\n }\n /**\n * Gets or sets a boolean indicating if the reflections should be attenuated at the screen borders (default: true).\n */\n get attenuateScreenBorders() {\n return this._attenuateScreenBorders;\n }\n set attenuateScreenBorders(attenuate) {\n if (this._attenuateScreenBorders === attenuate) {\n return;\n }\n this._attenuateScreenBorders = attenuate;\n this._updateEffectDefines();\n }\n /**\n * Gets or sets a boolean indicating if the reflections should be attenuated according to the distance of the intersection (default: true).\n */\n get attenuateIntersectionDistance() {\n return this._attenuateIntersectionDistance;\n }\n set attenuateIntersectionDistance(attenuate) {\n if (this._attenuateIntersectionDistance === attenuate) {\n return;\n }\n this._attenuateIntersectionDistance = attenuate;\n this._updateEffectDefines();\n }\n /**\n * Gets or sets a boolean indicating if the reflections should be attenuated according to the number of iterations performed to find the intersection (default: true).\n */\n get attenuateIntersectionIterations() {\n return this._attenuateIntersectionIterations;\n }\n set attenuateIntersectionIterations(attenuate) {\n if (this._attenuateIntersectionIterations === attenuate) {\n return;\n }\n this._attenuateIntersectionIterations = attenuate;\n this._updateEffectDefines();\n }\n /**\n * Gets or sets a boolean indicating if the reflections should be attenuated when the reflection ray is facing the camera (the view direction) (default: false).\n */\n get attenuateFacingCamera() {\n return this._attenuateFacingCamera;\n }\n set attenuateFacingCamera(attenuate) {\n if (this._attenuateFacingCamera === attenuate) {\n return;\n }\n this._attenuateFacingCamera = attenuate;\n this._updateEffectDefines();\n }\n /**\n * Gets or sets a boolean indicating if the backface reflections should be attenuated (default: false).\n */\n get attenuateBackfaceReflection() {\n return this._attenuateBackfaceReflection;\n }\n set attenuateBackfaceReflection(attenuate) {\n if (this._attenuateBackfaceReflection === attenuate) {\n return;\n }\n this._attenuateBackfaceReflection = attenuate;\n this._updateEffectDefines();\n }\n /**\n * Gets or sets a boolean indicating if the ray should be clipped to the frustum (default: true).\n * You can try to set this parameter to false to save some performances: it may produce some artefacts in some cases, but generally they won't really be visible\n */\n get clipToFrustum() {\n return this._clipToFrustum;\n }\n set clipToFrustum(clip) {\n if (this._clipToFrustum === clip) {\n return;\n }\n this._clipToFrustum = clip;\n this._updateEffectDefines();\n }\n /**\n * Gets or sets a boolean indicating whether the blending between the current color pixel and the reflection color should be done with a Fresnel coefficient (default: false).\n * It is more physically accurate to use the Fresnel coefficient (otherwise it uses the reflectivity of the material for blending), but it is also more expensive when you use blur (when blurDispersionStrength \\> 0).\n */\n get useFresnel() {\n return this._useFresnel;\n }\n set useFresnel(fresnel) {\n if (this._useFresnel === fresnel) {\n return;\n }\n this._useFresnel = fresnel;\n this._buildPipeline();\n }\n /**\n * Gets or sets a boolean defining if geometry thickness should be computed automatically (default: false).\n * When enabled, a depth renderer is created which will render the back faces of the scene to a depth texture (meaning additional work for the GPU).\n * In that mode, the \"thickness\" property is still used as an offset to compute the ray intersection, but you can typically use a much lower\n * value than when enableAutomaticThicknessComputation is false (it's even possible to use a value of 0 when using low values for \"step\")\n * Note that for performance reasons, this option will only apply to the first camera to which the the rendering pipeline is attached!\n */\n get enableAutomaticThicknessComputation() {\n return this._enableAutomaticThicknessComputation;\n }\n set enableAutomaticThicknessComputation(automatic) {\n if (this._enableAutomaticThicknessComputation === automatic) {\n return;\n }\n this._enableAutomaticThicknessComputation = automatic;\n this._buildPipeline();\n }\n /**\n * Gets the depth renderer used to render the back faces of the scene to a depth texture.\n */\n get backfaceDepthRenderer() {\n return this._depthRenderer;\n }\n /**\n * Gets or sets the downsample factor (default: 0) used to create the backface depth texture - used only if enableAutomaticThicknessComputation = true.\n * Use 0 to render the depth at full resolution, 1 to render at half resolution, 2 to render at 1/4 resolution, etc.\n * Note that you will get rendering artefacts when using a value different from 0: it's a tradeoff between image quality and performances.\n */\n get backfaceDepthTextureDownsample() {\n return this._backfaceDepthTextureDownsample;\n }\n set backfaceDepthTextureDownsample(factor) {\n if (this._backfaceDepthTextureDownsample === factor) {\n return;\n }\n this._backfaceDepthTextureDownsample = factor;\n this._resizeDepthRenderer();\n }\n /**\n * Gets or sets a boolean (default: true) indicating if the depth of transparent meshes should be written to the backface depth texture (when automatic thickness computation is enabled).\n */\n get backfaceForceDepthWriteTransparentMeshes() {\n return this._backfaceForceDepthWriteTransparentMeshes;\n }\n set backfaceForceDepthWriteTransparentMeshes(force) {\n if (this._backfaceForceDepthWriteTransparentMeshes === force) {\n return;\n }\n this._backfaceForceDepthWriteTransparentMeshes = force;\n if (this._depthRenderer) {\n this._depthRenderer.forceDepthWriteTransparentMeshes = force;\n }\n }\n /**\n * Gets or sets a boolean indicating if the effect is enabled (default: true).\n */\n get isEnabled() {\n return this._isEnabled;\n }\n set isEnabled(value) {\n if (this._isEnabled === value) {\n return;\n }\n this._isEnabled = value;\n if (!value) {\n if (this._cameras !== null) {\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);\n this._cameras = this._camerasToBeAttached.slice();\n }\n }\n else if (value) {\n if (!this._isDirty) {\n if (this._cameras !== null) {\n this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);\n }\n }\n else {\n this._buildPipeline();\n }\n }\n }\n /**\n * Gets or sets a boolean defining if the input color texture is in gamma space (default: true)\n * The SSR effect works in linear space, so if the input texture is in gamma space, we must convert the texture to linear space before applying the effect\n */\n get inputTextureColorIsInGammaSpace() {\n return this._inputTextureColorIsInGammaSpace;\n }\n set inputTextureColorIsInGammaSpace(gammaSpace) {\n if (this._inputTextureColorIsInGammaSpace === gammaSpace) {\n return;\n }\n this._inputTextureColorIsInGammaSpace = gammaSpace;\n this._buildPipeline();\n }\n /**\n * Gets or sets a boolean defining if the output color texture generated by the SSR pipeline should be in gamma space (default: true)\n * If you have a post-process that comes after the SSR and that post-process needs the input to be in a linear space, you must disable generateOutputInGammaSpace\n */\n get generateOutputInGammaSpace() {\n return this._generateOutputInGammaSpace;\n }\n set generateOutputInGammaSpace(gammaSpace) {\n if (this._generateOutputInGammaSpace === gammaSpace) {\n return;\n }\n this._generateOutputInGammaSpace = gammaSpace;\n this._buildPipeline();\n }\n /**\n * Gets or sets a boolean indicating if the effect should be rendered in debug mode (default: false).\n * In this mode, colors have this meaning:\n * - blue: the ray hit the max distance (we reached maxDistance)\n * - red: the ray ran out of steps (we reached maxSteps)\n * - yellow: the ray went off screen\n * - green: the ray hit a surface. The brightness of the green color is proportional to the distance between the ray origin and the intersection point: A brighter green means more computation than a darker green.\n * In the first 3 cases, the final color is calculated by mixing the skybox color with the pixel color (if environmentTexture is defined), otherwise the pixel color is not modified\n * You should try to get as few blue/red/yellow pixels as possible, as this means that the ray has gone further than if it had hit a surface.\n */\n get debug() {\n return this._debug;\n }\n set debug(value) {\n if (this._debug === value) {\n return;\n }\n this._debug = value;\n this._buildPipeline();\n }\n /**\n * Gets the scene the effect belongs to.\n * @returns the scene the effect belongs to.\n */\n getScene() {\n return this._scene;\n }\n get _geometryBufferRenderer() {\n if (!this._forceGeometryBuffer) {\n return null;\n }\n return this._scene.geometryBufferRenderer;\n }\n get _prePassRenderer() {\n if (this._forceGeometryBuffer) {\n return null;\n }\n return this._scene.prePassRenderer;\n }\n /**\n * Gets active scene\n */\n get scene() {\n return this._scene;\n }\n /**\n * Returns true if SSR is supported by the running hardware\n */\n get isSupported() {\n const caps = this._scene.getEngine().getCaps();\n return caps.drawBuffersExtension && caps.texelFetch;\n }\n /**\n * Constructor of the SSR rendering pipeline\n * @param name The rendering pipeline name\n * @param scene The scene linked to this pipeline\n * @param cameras The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)\n * @param forceGeometryBuffer Set to true if you want to use the legacy geometry buffer renderer (default: false)\n * @param textureType The texture type used by the different post processes created by SSR (default: 0)\n */\n constructor(name, scene, cameras, forceGeometryBuffer = false, textureType = 0) {\n super(scene.getEngine(), name);\n /**\n * The SSR PostProcess effect id in the pipeline\n */\n this.SSRRenderEffect = \"SSRRenderEffect\";\n /**\n * The blur PostProcess effect id in the pipeline\n */\n this.SSRBlurRenderEffect = \"SSRBlurRenderEffect\";\n /**\n * The PostProcess effect id in the pipeline that combines the SSR-Blur output with the original scene color\n */\n this.SSRCombineRenderEffect = \"SSRCombineRenderEffect\";\n this._samples = 1;\n /**\n * Gets or sets the maxDistance used to define how far we look for reflection during the ray-marching on the reflected ray (default: 1000).\n * Note that this value is a view (camera) space distance (not pixels!).\n */\n this.maxDistance = 1000.0;\n /**\n * Gets or sets the step size used to iterate until the effect finds the color of the reflection's pixel. Should be an integer \\>= 1 as it is the number of pixels we advance at each step (default: 1).\n * Use higher values to improve performances (but at the expense of quality).\n */\n this.step = 1.0;\n /**\n * Gets or sets the thickness value used as tolerance when computing the intersection between the reflected ray and the scene (default: 0.5).\n * If setting \"enableAutomaticThicknessComputation\" to true, you can use lower values for \"thickness\" (even 0), as the geometry thickness\n * is automatically computed thank to the regular depth buffer + the backface depth buffer\n */\n this.thickness = 0.5;\n /**\n * Gets or sets the current reflection strength. 1.0 is an ideal value but can be increased/decreased for particular results (default: 1).\n */\n this.strength = 1;\n /**\n * Gets or sets the falloff exponent used to compute the reflection strength. Higher values lead to fainter reflections (default: 1).\n */\n this.reflectionSpecularFalloffExponent = 1;\n /**\n * Maximum number of steps during the ray marching process after which we consider an intersection could not be found (default: 1000).\n * Should be an integer value.\n */\n this.maxSteps = 1000.0;\n /**\n * Gets or sets the factor applied when computing roughness. Default value is 0.2.\n * When blurring based on roughness is enabled (meaning blurDispersionStrength \\> 0), roughnessFactor is used as a global roughness factor applied on all objects.\n * If you want to disable this global roughness set it to 0.\n */\n this.roughnessFactor = 0.2;\n /**\n * Number of steps to skip at start when marching the ray to avoid self collisions (default: 1)\n * 1 should normally be a good value, depending on the scene you may need to use a higher value (2 or 3)\n */\n this.selfCollisionNumSkip = 1;\n this._reflectivityThreshold = 0.04;\n this._ssrDownsample = 0;\n this._blurDispersionStrength = 0.03;\n this._blurDownsample = 0;\n this._enableSmoothReflections = false;\n this._environmentTextureIsProbe = false;\n this._attenuateScreenBorders = true;\n this._attenuateIntersectionDistance = true;\n this._attenuateIntersectionIterations = true;\n this._attenuateFacingCamera = false;\n this._attenuateBackfaceReflection = false;\n this._clipToFrustum = true;\n this._useFresnel = false;\n this._enableAutomaticThicknessComputation = false;\n this._backfaceDepthTextureDownsample = 0;\n this._backfaceForceDepthWriteTransparentMeshes = true;\n this._isEnabled = true;\n this._inputTextureColorIsInGammaSpace = true;\n this._generateOutputInGammaSpace = true;\n this._debug = false;\n this._forceGeometryBuffer = false;\n this._isDirty = false;\n this._camerasToBeAttached = [];\n this._cameras = cameras || scene.cameras;\n this._cameras = this._cameras.slice();\n this._camerasToBeAttached = this._cameras.slice();\n this._scene = scene;\n this._textureType = textureType;\n this._forceGeometryBuffer = forceGeometryBuffer;\n if (this.isSupported) {\n scene.postProcessRenderPipelineManager.addPipeline(this);\n if (this._forceGeometryBuffer) {\n const geometryBufferRenderer = scene.enableGeometryBufferRenderer();\n if (geometryBufferRenderer) {\n geometryBufferRenderer.enableReflectivity = true;\n geometryBufferRenderer.useSpecificClearForDepthTexture = true;\n }\n }\n else {\n const prePassRenderer = scene.enablePrePassRenderer();\n if (prePassRenderer) {\n prePassRenderer.useSpecificClearForDepthTexture = true;\n prePassRenderer.markAsDirty();\n }\n }\n this._buildPipeline();\n }\n }\n /**\n * Get the class name\n * @returns \"SSRRenderingPipeline\"\n */\n getClassName() {\n return \"SSRRenderingPipeline\";\n }\n /**\n * Adds a camera to the pipeline\n * @param camera the camera to be added\n */\n addCamera(camera) {\n this._camerasToBeAttached.push(camera);\n this._buildPipeline();\n }\n /**\n * Removes a camera from the pipeline\n * @param camera the camera to remove\n */\n removeCamera(camera) {\n const index = this._camerasToBeAttached.indexOf(camera);\n this._camerasToBeAttached.splice(index, 1);\n this._buildPipeline();\n }\n /**\n * Removes the internal pipeline assets and detaches the pipeline from the scene cameras\n * @param disableGeometryBufferRenderer\n */\n dispose(disableGeometryBufferRenderer = false) {\n this._disposeDepthRenderer();\n this._disposePostProcesses();\n if (disableGeometryBufferRenderer) {\n this._scene.disableGeometryBufferRenderer();\n }\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);\n super.dispose();\n }\n _getTextureSize() {\n var _a, _b;\n const engine = this._scene.getEngine();\n const prePassRenderer = this._prePassRenderer;\n let textureSize = { width: engine.getRenderWidth(), height: engine.getRenderHeight() };\n if (prePassRenderer && ((_a = this._scene.activeCamera) === null || _a === void 0 ? void 0 : _a._getFirstPostProcess()) === this._ssrPostProcess) {\n const renderTarget = prePassRenderer.getRenderTarget();\n if (renderTarget && renderTarget.textures) {\n textureSize = renderTarget.textures[prePassRenderer.getIndex(4)].getSize();\n }\n }\n else if ((_b = this._ssrPostProcess) === null || _b === void 0 ? void 0 : _b.inputTexture) {\n textureSize.width = this._ssrPostProcess.inputTexture.width;\n textureSize.height = this._ssrPostProcess.inputTexture.height;\n }\n return textureSize;\n }\n _updateEffectDefines() {\n var _a;\n const defines = [];\n if (this._geometryBufferRenderer || this._prePassRenderer) {\n defines.push(\"#define SSR_SUPPORTED\");\n }\n if (this._enableSmoothReflections) {\n defines.push(\"#define SSRAYTRACE_ENABLE_REFINEMENT\");\n }\n if (this._scene.useRightHandedSystem) {\n defines.push(\"#define SSRAYTRACE_RIGHT_HANDED_SCENE\");\n }\n if (this._environmentTexture) {\n defines.push(\"#define SSR_USE_ENVIRONMENT_CUBE\");\n if (this._environmentTexture.boundingBoxSize) {\n defines.push(\"#define SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\");\n }\n if (this._environmentTexture.gammaSpace) {\n defines.push(\"#define SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE\");\n }\n }\n if (this._environmentTextureIsProbe) {\n defines.push(\"#define SSR_INVERTCUBICMAP\");\n }\n if (this._enableAutomaticThicknessComputation) {\n defines.push(\"#define SSRAYTRACE_USE_BACK_DEPTHBUFFER\");\n }\n if (this._attenuateScreenBorders) {\n defines.push(\"#define SSR_ATTENUATE_SCREEN_BORDERS\");\n }\n if (this._attenuateIntersectionDistance) {\n defines.push(\"#define SSR_ATTENUATE_INTERSECTION_DISTANCE\");\n }\n if (this._attenuateIntersectionIterations) {\n defines.push(\"#define SSR_ATTENUATE_INTERSECTION_NUMITERATIONS\");\n }\n if (this._attenuateFacingCamera) {\n defines.push(\"#define SSR_ATTENUATE_FACING_CAMERA\");\n }\n if (this._attenuateBackfaceReflection) {\n defines.push(\"#define SSR_ATTENUATE_BACKFACE_REFLECTION\");\n }\n if (this._clipToFrustum) {\n defines.push(\"#define SSRAYTRACE_CLIP_TO_FRUSTUM\");\n }\n if (this._useBlur()) {\n defines.push(\"#define SSR_USE_BLUR\");\n }\n if (this._debug) {\n defines.push(\"#define SSRAYTRACE_DEBUG\");\n }\n if (this._inputTextureColorIsInGammaSpace) {\n defines.push(\"#define SSR_INPUT_IS_GAMMA_SPACE\");\n }\n if (this._generateOutputInGammaSpace) {\n defines.push(\"#define SSR_OUTPUT_IS_GAMMA_SPACE\");\n }\n if (this._useFresnel) {\n defines.push(\"#define SSR_BLEND_WITH_FRESNEL\");\n }\n if (this._reflectivityThreshold === 0) {\n defines.push(\"#define SSR_DISABLE_REFLECTIVITY_TEST\");\n }\n (_a = this._ssrPostProcess) === null || _a === void 0 ? void 0 : _a.updateEffect(defines.join(\"\\n\"));\n }\n _buildPipeline() {\n var _a;\n if (!this.isSupported) {\n return;\n }\n if (!this._isEnabled) {\n this._isDirty = true;\n return;\n }\n this._isDirty = false;\n const engine = this._scene.getEngine();\n this._disposeDepthRenderer();\n this._disposePostProcesses();\n if (this._cameras !== null) {\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);\n // get back cameras to be used to reattach pipeline\n this._cameras = this._camerasToBeAttached.slice();\n }\n this._reset();\n if (this._enableAutomaticThicknessComputation) {\n const camera = (_a = this._cameras) === null || _a === void 0 ? void 0 : _a[0];\n if (camera) {\n this._depthRendererCamera = camera;\n this._depthRenderer = new DepthRenderer(this._scene, undefined, undefined, undefined, 1, true, \"SSRBackDepth\");\n this._depthRenderer.clearColor.r = 1e8; // \"infinity\": put a big value because we use the storeCameraSpaceZ mode\n this._depthRenderer.reverseCulling = true; // we generate depth for the back faces\n this._depthRenderer.forceDepthWriteTransparentMeshes = this._backfaceForceDepthWriteTransparentMeshes;\n this._resizeDepthRenderer();\n camera.customRenderTargets.push(this._depthRenderer.getDepthMap());\n }\n }\n this._createSSRPostProcess();\n this.addEffect(new PostProcessRenderEffect(engine, this.SSRRenderEffect, () => {\n return this._ssrPostProcess;\n }, true));\n if (this._useBlur()) {\n this._createBlurAndCombinerPostProcesses();\n this.addEffect(new PostProcessRenderEffect(engine, this.SSRBlurRenderEffect, () => {\n return [this._blurPostProcessX, this._blurPostProcessY];\n }, true));\n this.addEffect(new PostProcessRenderEffect(engine, this.SSRCombineRenderEffect, () => {\n return this._blurCombinerPostProcess;\n }, true));\n }\n if (this._cameras !== null) {\n this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);\n }\n }\n _resizeDepthRenderer() {\n if (!this._depthRenderer) {\n return;\n }\n const textureSize = this._getTextureSize();\n const depthRendererSize = this._depthRenderer.getDepthMap().getSize();\n const width = Math.floor(textureSize.width / (this._backfaceDepthTextureDownsample + 1));\n const height = Math.floor(textureSize.height / (this._backfaceDepthTextureDownsample + 1));\n if (depthRendererSize.width !== width || depthRendererSize.height !== height) {\n this._depthRenderer.getDepthMap().resize({ width, height });\n }\n }\n _disposeDepthRenderer() {\n var _a;\n if (this._depthRenderer) {\n if (this._depthRendererCamera) {\n const idx = (_a = this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap())) !== null && _a !== void 0 ? _a : -1;\n if (idx !== -1) {\n this._depthRendererCamera.customRenderTargets.splice(idx, 1);\n }\n }\n this._depthRendererCamera = null;\n this._depthRenderer.getDepthMap().dispose();\n }\n this._depthRenderer = null;\n }\n _disposePostProcesses() {\n var _a, _b, _c, _d;\n for (let i = 0; i < this._cameras.length; i++) {\n const camera = this._cameras[i];\n (_a = this._ssrPostProcess) === null || _a === void 0 ? void 0 : _a.dispose(camera);\n (_b = this._blurPostProcessX) === null || _b === void 0 ? void 0 : _b.dispose(camera);\n (_c = this._blurPostProcessY) === null || _c === void 0 ? void 0 : _c.dispose(camera);\n (_d = this._blurCombinerPostProcess) === null || _d === void 0 ? void 0 : _d.dispose(camera);\n }\n this._ssrPostProcess = null;\n this._blurPostProcessX = null;\n this._blurPostProcessY = null;\n this._blurCombinerPostProcess = null;\n }\n _createSSRPostProcess() {\n this._ssrPostProcess = new PostProcess(\"ssr\", \"screenSpaceReflection2\", [\n \"projection\",\n \"invProjectionMatrix\",\n \"view\",\n \"invView\",\n \"thickness\",\n \"reflectionSpecularFalloffExponent\",\n \"strength\",\n \"stepSize\",\n \"maxSteps\",\n \"roughnessFactor\",\n \"projectionPixel\",\n \"nearPlaneZ\",\n \"maxDistance\",\n \"selfCollisionNumSkip\",\n \"vReflectionPosition\",\n \"vReflectionSize\",\n \"backSizeFactor\",\n \"reflectivityThreshold\",\n ], [\"textureSampler\", \"normalSampler\", \"reflectivitySampler\", \"depthSampler\", \"envCubeSampler\", \"backDepthSampler\"], 1.0, null, this._textureType, this._scene.getEngine(), false, \"\", this._textureType);\n this._updateEffectDefines();\n this._ssrPostProcess.onApply = (effect) => {\n this._resizeDepthRenderer();\n const geometryBufferRenderer = this._geometryBufferRenderer;\n const prePassRenderer = this._prePassRenderer;\n if (!prePassRenderer && !geometryBufferRenderer) {\n return;\n }\n if (geometryBufferRenderer) {\n const roughnessIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE);\n effect.setTexture(\"normalSampler\", geometryBufferRenderer.getGBuffer().textures[1]);\n effect.setTexture(\"reflectivitySampler\", geometryBufferRenderer.getGBuffer().textures[roughnessIndex]);\n effect.setTexture(\"depthSampler\", geometryBufferRenderer.getGBuffer().textures[0]);\n }\n else if (prePassRenderer) {\n const depthIndex = prePassRenderer.getIndex(5);\n const roughnessIndex = prePassRenderer.getIndex(3);\n const normalIndex = prePassRenderer.getIndex(6);\n effect.setTexture(\"normalSampler\", prePassRenderer.getRenderTarget().textures[normalIndex]);\n effect.setTexture(\"depthSampler\", prePassRenderer.getRenderTarget().textures[depthIndex]);\n effect.setTexture(\"reflectivitySampler\", prePassRenderer.getRenderTarget().textures[roughnessIndex]);\n }\n if (this._enableAutomaticThicknessComputation && this._depthRenderer) {\n effect.setTexture(\"backDepthSampler\", this._depthRenderer.getDepthMap());\n effect.setFloat(\"backSizeFactor\", this._backfaceDepthTextureDownsample + 1);\n }\n const camera = this._scene.activeCamera;\n if (!camera) {\n return;\n }\n const viewMatrix = camera.getViewMatrix(true);\n const projectionMatrix = camera.getProjectionMatrix(true);\n projectionMatrix.invertToRef(TmpVectors.Matrix[0]);\n viewMatrix.invertToRef(TmpVectors.Matrix[1]);\n effect.setMatrix(\"projection\", projectionMatrix);\n effect.setMatrix(\"view\", viewMatrix);\n effect.setMatrix(\"invView\", TmpVectors.Matrix[1]);\n effect.setMatrix(\"invProjectionMatrix\", TmpVectors.Matrix[0]);\n effect.setFloat(\"thickness\", this.thickness);\n effect.setFloat(\"reflectionSpecularFalloffExponent\", this.reflectionSpecularFalloffExponent);\n effect.setFloat(\"strength\", this.strength);\n effect.setFloat(\"stepSize\", this.step);\n effect.setFloat(\"maxSteps\", this.maxSteps);\n effect.setFloat(\"roughnessFactor\", this.roughnessFactor);\n effect.setFloat(\"nearPlaneZ\", camera.minZ);\n effect.setFloat(\"maxDistance\", this.maxDistance);\n effect.setFloat(\"selfCollisionNumSkip\", this.selfCollisionNumSkip);\n effect.setFloat(\"reflectivityThreshold\", this._reflectivityThreshold);\n const textureSize = this._getTextureSize();\n Matrix.ScalingToRef(textureSize.width, textureSize.height, 1, TmpVectors.Matrix[2]);\n projectionMatrix.multiplyToRef(this._scene.getEngine().isWebGPU ? trsWebGPU : trs, TmpVectors.Matrix[3]);\n TmpVectors.Matrix[3].multiplyToRef(TmpVectors.Matrix[2], TmpVectors.Matrix[4]);\n effect.setMatrix(\"projectionPixel\", TmpVectors.Matrix[4]);\n if (this._environmentTexture) {\n effect.setTexture(\"envCubeSampler\", this._environmentTexture);\n if (this._environmentTexture.boundingBoxSize) {\n effect.setVector3(\"vReflectionPosition\", this._environmentTexture.boundingBoxPosition);\n effect.setVector3(\"vReflectionSize\", this._environmentTexture.boundingBoxSize);\n }\n }\n };\n this._ssrPostProcess.samples = this.samples;\n if (!this._forceGeometryBuffer) {\n this._ssrPostProcess._prePassEffectConfiguration = new ScreenSpaceReflections2Configuration();\n }\n }\n _createBlurAndCombinerPostProcesses() {\n const engine = this._scene.getEngine();\n this._blurPostProcessX = new PostProcess(\"SSRblurX\", \"screenSpaceReflection2Blur\", [\"texelOffsetScale\"], [\"textureSampler\"], this._useBlur() ? 1 / (this._ssrDownsample + 1) : 1, null, 2, engine, false, \"\", this._textureType);\n this._blurPostProcessX.autoClear = false;\n this._blurPostProcessX.onApplyObservable.add((effect) => {\n var _a, _b;\n const width = (_b = (_a = this._blurPostProcessX) === null || _a === void 0 ? void 0 : _a.inputTexture.width) !== null && _b !== void 0 ? _b : this._scene.getEngine().getRenderWidth();\n effect.setFloat2(\"texelOffsetScale\", this._blurDispersionStrength / width, 0);\n });\n this._blurPostProcessY = new PostProcess(\"SSRblurY\", \"screenSpaceReflection2Blur\", [\"texelOffsetScale\"], [\"textureSampler\"], this._useBlur() ? 1 / (this._blurDownsample + 1) : 1, null, 2, engine, false, \"\", this._textureType);\n this._blurPostProcessY.autoClear = false;\n this._blurPostProcessY.onApplyObservable.add((effect) => {\n var _a, _b;\n const height = (_b = (_a = this._blurPostProcessY) === null || _a === void 0 ? void 0 : _a.inputTexture.height) !== null && _b !== void 0 ? _b : this._scene.getEngine().getRenderHeight();\n effect.setFloat2(\"texelOffsetScale\", 0, this._blurDispersionStrength / height);\n });\n const uniformNames = [\"strength\", \"reflectionSpecularFalloffExponent\", \"reflectivityThreshold\"];\n const samplerNames = [\"textureSampler\", \"mainSampler\", \"reflectivitySampler\"];\n let defines = \"\";\n if (this._debug) {\n defines += \"#define SSRAYTRACE_DEBUG\\n\";\n }\n if (this._inputTextureColorIsInGammaSpace) {\n defines += \"#define SSR_INPUT_IS_GAMMA_SPACE\\n\";\n }\n if (this._generateOutputInGammaSpace) {\n defines += \"#define SSR_OUTPUT_IS_GAMMA_SPACE\\n\";\n }\n if (this.useFresnel) {\n defines += \"#define SSR_BLEND_WITH_FRESNEL\\n\";\n uniformNames.push(\"projection\", \"invProjectionMatrix\");\n samplerNames.push(\"depthSampler\", \"normalSampler\");\n }\n if (this._reflectivityThreshold === 0) {\n defines += \"#define SSR_DISABLE_REFLECTIVITY_TEST\";\n }\n this._blurCombinerPostProcess = new PostProcess(\"SSRblurCombiner\", \"screenSpaceReflection2BlurCombiner\", uniformNames, samplerNames, this._useBlur() ? 1 / (this._blurDownsample + 1) : 1, null, 1, engine, false, defines, this._textureType);\n this._blurCombinerPostProcess.autoClear = false;\n this._blurCombinerPostProcess.onApplyObservable.add((effect) => {\n var _a;\n const geometryBufferRenderer = this._geometryBufferRenderer;\n const prePassRenderer = this._prePassRenderer;\n if (!prePassRenderer && !geometryBufferRenderer) {\n return;\n }\n if (prePassRenderer && ((_a = this._scene.activeCamera) === null || _a === void 0 ? void 0 : _a._getFirstPostProcess()) === this._ssrPostProcess) {\n const renderTarget = prePassRenderer.getRenderTarget();\n if (renderTarget && renderTarget.textures) {\n effect.setTexture(\"mainSampler\", renderTarget.textures[prePassRenderer.getIndex(4)]);\n }\n }\n else {\n effect.setTextureFromPostProcess(\"mainSampler\", this._ssrPostProcess);\n }\n if (geometryBufferRenderer) {\n const roughnessIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE);\n effect.setTexture(\"reflectivitySampler\", geometryBufferRenderer.getGBuffer().textures[roughnessIndex]);\n if (this.useFresnel) {\n effect.setTexture(\"normalSampler\", geometryBufferRenderer.getGBuffer().textures[1]);\n effect.setTexture(\"depthSampler\", geometryBufferRenderer.getGBuffer().textures[0]);\n }\n }\n else if (prePassRenderer) {\n const roughnessIndex = prePassRenderer.getIndex(3);\n effect.setTexture(\"reflectivitySampler\", prePassRenderer.getRenderTarget().textures[roughnessIndex]);\n if (this.useFresnel) {\n const depthIndex = prePassRenderer.getIndex(5);\n const normalIndex = prePassRenderer.getIndex(6);\n effect.setTexture(\"normalSampler\", prePassRenderer.getRenderTarget().textures[normalIndex]);\n effect.setTexture(\"depthSampler\", prePassRenderer.getRenderTarget().textures[depthIndex]);\n }\n }\n effect.setFloat(\"strength\", this.strength);\n effect.setFloat(\"reflectionSpecularFalloffExponent\", this.reflectionSpecularFalloffExponent);\n effect.setFloat(\"reflectivityThreshold\", this._reflectivityThreshold);\n if (this.useFresnel) {\n const camera = this._scene.activeCamera;\n if (camera) {\n const projectionMatrix = camera.getProjectionMatrix();\n projectionMatrix.invertToRef(TmpVectors.Matrix[0]);\n effect.setMatrix(\"projection\", projectionMatrix);\n effect.setMatrix(\"invProjectionMatrix\", TmpVectors.Matrix[0]);\n }\n }\n });\n }\n /**\n * Serializes the rendering pipeline (Used when exporting)\n * @returns the serialized object\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this);\n serializationObject.customType = \"SSRRenderingPipeline\";\n return serializationObject;\n }\n /**\n * Parse the serialized pipeline\n * @param source Source pipeline.\n * @param scene The scene to load the pipeline to.\n * @param rootUrl The URL of the serialized pipeline.\n * @returns An instantiated pipeline from the serialized object.\n */\n static Parse(source, scene, rootUrl) {\n return SerializationHelper.Parse(() => new SSRRenderingPipeline(source._name, scene, source._ratio), source, scene, rootUrl);\n }\n}\n__decorate([\n serialize()\n], SSRRenderingPipeline.prototype, \"samples\", null);\n__decorate([\n serialize()\n], SSRRenderingPipeline.prototype, \"maxDistance\", void 0);\n__decorate([\n serialize()\n], SSRRenderingPipeline.prototype, \"step\", void 0);\n__decorate([\n serialize()\n], SSRRenderingPipeline.prototype, \"thickness\", void 0);\n__decorate([\n serialize()\n], SSRRenderingPipeline.prototype, \"strength\", void 0);\n__decorate([\n serialize()\n], SSRRenderingPipeline.prototype, \"reflectionSpecularFalloffExponent\", void 0);\n__decorate([\n serialize()\n], SSRRenderingPipeline.prototype, \"maxSteps\", void 0);\n__decorate([\n serialize()\n], SSRRenderingPipeline.prototype, \"roughnessFactor\", void 0);\n__decorate([\n serialize()\n], SSRRenderingPipeline.prototype, \"selfCollisionNumSkip\", void 0);\n__decorate([\n serialize()\n], SSRRenderingPipeline.prototype, \"_reflectivityThreshold\", void 0);\n__decorate([\n serialize(\"_ssrDownsample\")\n], SSRRenderingPipeline.prototype, \"_ssrDownsample\", void 0);\n__decorate([\n serialize()\n], SSRRenderingPipeline.prototype, \"ssrDownsample\", null);\n__decorate([\n serialize(\"blurDispersionStrength\")\n], SSRRenderingPipeline.prototype, \"_blurDispersionStrength\", void 0);\n__decorate([\n serialize(\"blurDownsample\")\n], SSRRenderingPipeline.prototype, \"_blurDownsample\", void 0);\n__decorate([\n serialize(\"enableSmoothReflections\")\n], SSRRenderingPipeline.prototype, \"_enableSmoothReflections\", void 0);\n__decorate([\n serialize(\"environmentTexture\")\n], SSRRenderingPipeline.prototype, \"_environmentTexture\", void 0);\n__decorate([\n serialize(\"environmentTextureIsProbe\")\n], SSRRenderingPipeline.prototype, \"_environmentTextureIsProbe\", void 0);\n__decorate([\n serialize(\"attenuateScreenBorders\")\n], SSRRenderingPipeline.prototype, \"_attenuateScreenBorders\", void 0);\n__decorate([\n serialize(\"attenuateIntersectionDistance\")\n], SSRRenderingPipeline.prototype, \"_attenuateIntersectionDistance\", void 0);\n__decorate([\n serialize(\"attenuateIntersectionIterations\")\n], SSRRenderingPipeline.prototype, \"_attenuateIntersectionIterations\", void 0);\n__decorate([\n serialize(\"attenuateFacingCamera\")\n], SSRRenderingPipeline.prototype, \"_attenuateFacingCamera\", void 0);\n__decorate([\n serialize(\"attenuateBackfaceReflection\")\n], SSRRenderingPipeline.prototype, \"_attenuateBackfaceReflection\", void 0);\n__decorate([\n serialize(\"clipToFrustum\")\n], SSRRenderingPipeline.prototype, \"_clipToFrustum\", void 0);\n__decorate([\n serialize(\"useFresnel\")\n], SSRRenderingPipeline.prototype, \"_useFresnel\", void 0);\n__decorate([\n serialize(\"enableAutomaticThicknessComputation\")\n], SSRRenderingPipeline.prototype, \"_enableAutomaticThicknessComputation\", void 0);\n__decorate([\n serialize(\"backfaceDepthTextureDownsample\")\n], SSRRenderingPipeline.prototype, \"_backfaceDepthTextureDownsample\", void 0);\n__decorate([\n serialize(\"backfaceForceDepthWriteTransparentMeshes\")\n], SSRRenderingPipeline.prototype, \"_backfaceForceDepthWriteTransparentMeshes\", void 0);\n__decorate([\n serialize(\"isEnabled\")\n], SSRRenderingPipeline.prototype, \"_isEnabled\", void 0);\n__decorate([\n serialize(\"inputTextureColorIsInGammaSpace\")\n], SSRRenderingPipeline.prototype, \"_inputTextureColorIsInGammaSpace\", void 0);\n__decorate([\n serialize(\"generateOutputInGammaSpace\")\n], SSRRenderingPipeline.prototype, \"_generateOutputInGammaSpace\", void 0);\n__decorate([\n serialize(\"debug\")\n], SSRRenderingPipeline.prototype, \"_debug\", void 0);\nRegisterClass(\"BABYLON.SSRRenderingPipeline\", SSRRenderingPipeline);\n//# sourceMappingURL=ssrRenderingPipeline.js.map","export * from \"./defaultRenderingPipeline.js\";\nexport * from \"./lensRenderingPipeline.js\";\nexport * from \"./ssao2RenderingPipeline.js\";\nexport * from \"./ssaoRenderingPipeline.js\";\nexport * from \"./standardRenderingPipeline.js\";\nexport * from \"./ssrRenderingPipeline.js\";\n//# sourceMappingURL=index.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./Pipelines/index.js\";\nexport * from \"./postProcessRenderEffect.js\";\nexport * from \"./postProcessRenderPipeline.js\";\nexport * from \"./postProcessRenderPipelineManager.js\";\nexport * from \"./postProcessRenderPipelineManagerSceneComponent.js\";\n//# sourceMappingURL=index.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"tonemapPixelShader\";\nconst shader = `varying vec2 vUV;\runiform sampler2D textureSampler;\runiform float _ExposureAdjustment;\r#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\rconst float B=0.50;\rconst float C=0.10;\rconst float D=0.20;\rconst float E=0.02;\rconst float F=0.30;\rconst float W=11.2;\r#endif\nfloat Luminance(vec3 c)\r{\rreturn dot(c,vec3(0.22,0.707,0.071));\r}\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \r{\rvec3 colour=texture2D(textureSampler,vUV).rgb;\r#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \rfloat lumTm=lum*_ExposureAdjustment;\rfloat scale=lumTm/(1.0+lumTm); \rcolour*=scale/lum;\r#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\rconst float ExposureBias=2.0;\rvec3 x=ExposureBias*colour;\rvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\rx=vec3(W,W,W);\rvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\rcolour=curr*whiteScale;\r#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\rvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\rvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\rcolour=retColor*retColor;\r#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\r#endif\ngl_FragColor=vec4(colour.rgb,1.0);\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const tonemapPixelShader = { name, shader };\n//# sourceMappingURL=tonemap.fragment.js.map","import { PostProcess } from \"./postProcess.js\";\n\nimport \"../Shaders/tonemap.fragment.js\";\n/** Defines operator used for tonemapping */\nexport var TonemappingOperator;\n(function (TonemappingOperator) {\n /** Hable */\n TonemappingOperator[TonemappingOperator[\"Hable\"] = 0] = \"Hable\";\n /** Reinhard */\n TonemappingOperator[TonemappingOperator[\"Reinhard\"] = 1] = \"Reinhard\";\n /** HejiDawson */\n TonemappingOperator[TonemappingOperator[\"HejiDawson\"] = 2] = \"HejiDawson\";\n /** Photographic */\n TonemappingOperator[TonemappingOperator[\"Photographic\"] = 3] = \"Photographic\";\n})(TonemappingOperator || (TonemappingOperator = {}));\n/**\n * Defines a post process to apply tone mapping\n */\nexport class TonemapPostProcess extends PostProcess {\n /**\n * Gets a string identifying the name of the class\n * @returns \"TonemapPostProcess\" string\n */\n getClassName() {\n return \"TonemapPostProcess\";\n }\n /**\n * Creates a new TonemapPostProcess\n * @param name defines the name of the postprocess\n * @param _operator defines the operator to use\n * @param exposureAdjustment defines the required exposure adjustment\n * @param camera defines the camera to use (can be null)\n * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)\n * @param engine defines the hosting engine (can be ignore if camera is set)\n * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n */\n constructor(name, _operator, \n /** Defines the required exposure adjustment */\n exposureAdjustment, camera, samplingMode = 2, engine, textureFormat = 0, reusable) {\n super(name, \"tonemap\", [\"_ExposureAdjustment\"], null, 1.0, camera, samplingMode, engine, reusable, null, textureFormat);\n this._operator = _operator;\n this.exposureAdjustment = exposureAdjustment;\n let defines = \"#define \";\n if (this._operator === TonemappingOperator.Hable) {\n defines += \"HABLE_TONEMAPPING\";\n }\n else if (this._operator === TonemappingOperator.Reinhard) {\n defines += \"REINHARD_TONEMAPPING\";\n }\n else if (this._operator === TonemappingOperator.HejiDawson) {\n defines += \"OPTIMIZED_HEJIDAWSON_TONEMAPPING\";\n }\n else if (this._operator === TonemappingOperator.Photographic) {\n defines += \"PHOTOGRAPHIC_TONEMAPPING\";\n }\n //sadly a second call to create the effect.\n this.updateEffect(defines);\n this.onApply = (effect) => {\n effect.setFloat(\"_ExposureAdjustment\", this.exposureAdjustment);\n };\n }\n}\n//# sourceMappingURL=tonemapPostProcess.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"volumetricLightScatteringPixelShader\";\nconst shader = `uniform sampler2D textureSampler;\runiform sampler2D lightScatteringSampler;\runiform float decay;\runiform float exposure;\runiform float weight;\runiform float density;\runiform vec2 meshPositionOnScreen;\rvarying vec2 vUV;\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec2 tc=vUV;\rvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\rdeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\rfloat illuminationDecay=1.0;\rvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\rfor(int i=0; i\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nuniform mat4 viewProjection;\runiform vec2 depthValues;\r#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\runiform mat4 diffuseMatrix;\r#ifdef UV1\nattribute vec2 uv;\r#endif\n#ifdef UV2\nattribute vec2 uv2;\r#endif\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\r{\rvec3 positionUpdated=position;\r#if (defined(ALPHATEST) || defined(NEED_UV)) && defined(UV1)\nvec2 uvUpdated=uv;\r#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\r#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\r#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\r#endif\n#endif\n}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const volumetricLightScatteringPassVertexShader = { name, shader };\n//# sourceMappingURL=volumetricLightScatteringPass.vertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"volumetricLightScatteringPassPixelShader\";\nconst shader = `#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\r#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\r#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\r{\r#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\rif (diffuseColor.a<0.4)\rdiscard;\r#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\r}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const volumetricLightScatteringPassPixelShader = { name, shader };\n//# sourceMappingURL=volumetricLightScatteringPass.fragment.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serializeAsVector3, serialize, serializeAsMeshReference } from \"../Misc/decorators.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { Vector2, Vector3, Matrix } from \"../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { AbstractMesh } from \"../Meshes/abstractMesh.js\";\nimport { Material } from \"../Materials/material.js\";\nimport { MaterialHelper } from \"../Materials/materialHelper.js\";\nimport { StandardMaterial } from \"../Materials/standardMaterial.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { RenderTargetTexture } from \"../Materials/Textures/renderTargetTexture.js\";\nimport { PostProcess } from \"./postProcess.js\";\n\nimport { CreatePlane } from \"../Meshes/Builders/planeBuilder.js\";\nimport \"../Shaders/depth.vertex.js\";\nimport \"../Shaders/volumetricLightScattering.fragment.js\";\nimport \"../Shaders/volumetricLightScatteringPass.vertex.js\";\nimport \"../Shaders/volumetricLightScatteringPass.fragment.js\";\nimport { Color4, Color3 } from \"../Maths/math.color.js\";\nimport { Viewport } from \"../Maths/math.viewport.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\n/**\n * Inspired by https://developer.nvidia.com/gpugems/gpugems3/part-ii-light-and-shadows/chapter-13-volumetric-light-scattering-post-process\n */\nexport class VolumetricLightScatteringPostProcess extends PostProcess {\n /**\n * @internal\n * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead\n */\n get useDiffuseColor() {\n Logger.Warn(\"VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead\");\n return false;\n }\n set useDiffuseColor(useDiffuseColor) {\n Logger.Warn(\"VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead\");\n }\n /**\n * @constructor\n * @param name The post-process name\n * @param ratio The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)\n * @param camera The camera that the post-process will be attached to\n * @param mesh The mesh used to create the light scattering\n * @param samples The post-process quality, default 100\n * @param samplingMode The post-process filtering mode\n * @param engine The babylon engine\n * @param reusable If the post-process is reusable\n * @param scene The constructor needs a scene reference to initialize internal components. If \"camera\" is null a \"scene\" must be provided\n */\n constructor(name, ratio, camera, mesh, samples = 100, samplingMode = Texture.BILINEAR_SAMPLINGMODE, engine, reusable, scene) {\n var _a, _b;\n super(name, \"volumetricLightScattering\", [\"decay\", \"exposure\", \"weight\", \"meshPositionOnScreen\", \"density\"], [\"lightScatteringSampler\"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, \"#define NUM_SAMPLES \" + samples);\n this._screenCoordinates = Vector2.Zero();\n /**\n * Custom position of the mesh. Used if \"useCustomMeshPosition\" is set to \"true\"\n */\n this.customMeshPosition = Vector3.Zero();\n /**\n * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)\n */\n this.useCustomMeshPosition = false;\n /**\n * If the post-process should inverse the light scattering direction\n */\n this.invert = true;\n /**\n * Array containing the excluded meshes not rendered in the internal pass\n */\n this.excludedMeshes = new Array();\n /**\n * Array containing the only meshes rendered in the internal pass.\n * If this array is not empty, only the meshes from this array are rendered in the internal pass\n */\n this.includedMeshes = new Array();\n /**\n * Controls the overall intensity of the post-process\n */\n this.exposure = 0.3;\n /**\n * Dissipates each sample's contribution in range [0, 1]\n */\n this.decay = 0.96815;\n /**\n * Controls the overall intensity of each sample\n */\n this.weight = 0.58767;\n /**\n * Controls the density of each sample\n */\n this.density = 0.926;\n scene = (_b = (_a = camera === null || camera === void 0 ? void 0 : camera.getScene()) !== null && _a !== void 0 ? _a : scene) !== null && _b !== void 0 ? _b : this._scene; // parameter \"scene\" can be null.\n engine = scene.getEngine();\n this._viewPort = new Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());\n // Configure mesh\n this.mesh = mesh !== null && mesh !== void 0 ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh(\"VolumetricLightScatteringMesh\", scene);\n // Configure\n this._createPass(scene, ratio.passRatio || ratio);\n this.onActivate = (camera) => {\n if (!this.isSupported) {\n this.dispose(camera);\n }\n this.onActivate = null;\n };\n this.onApplyObservable.add((effect) => {\n this._updateMeshScreenCoordinates(scene);\n effect.setTexture(\"lightScatteringSampler\", this._volumetricLightScatteringRTT);\n effect.setFloat(\"exposure\", this.exposure);\n effect.setFloat(\"decay\", this.decay);\n effect.setFloat(\"weight\", this.weight);\n effect.setFloat(\"density\", this.density);\n effect.setVector2(\"meshPositionOnScreen\", this._screenCoordinates);\n });\n }\n /**\n * Returns the string \"VolumetricLightScatteringPostProcess\"\n * @returns \"VolumetricLightScatteringPostProcess\"\n */\n getClassName() {\n return \"VolumetricLightScatteringPostProcess\";\n }\n _isReady(subMesh, useInstances) {\n var _a;\n const mesh = subMesh.getMesh();\n // Render this.mesh as default\n if (mesh === this.mesh && mesh.material) {\n return mesh.material.isReady(mesh);\n }\n const renderingMaterial = (_a = mesh._internalAbstractMeshDataInfo._materialForRenderPass) === null || _a === void 0 ? void 0 : _a[this._scene.getEngine().currentRenderPassId];\n if (renderingMaterial) {\n return renderingMaterial.isReadyForSubMesh(mesh, subMesh, useInstances);\n }\n const defines = [];\n const attribs = [VertexBuffer.PositionKind];\n const material = subMesh.getMaterial();\n // Alpha test\n if (material) {\n if (material.needAlphaTesting()) {\n defines.push(\"#define ALPHATEST\");\n }\n if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {\n attribs.push(VertexBuffer.UVKind);\n defines.push(\"#define UV1\");\n }\n if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {\n attribs.push(VertexBuffer.UV2Kind);\n defines.push(\"#define UV2\");\n }\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders) {\n attribs.push(VertexBuffer.MatricesIndicesKind);\n attribs.push(VertexBuffer.MatricesWeightsKind);\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n defines.push(\"#define BonesPerMesh \" + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Instances\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n MaterialHelper.PushAttributesForInstances(attribs);\n if (subMesh.getRenderingMesh().hasThinInstances) {\n defines.push(\"#define THIN_INSTANCES\");\n }\n }\n // Get correct effect\n const drawWrapper = subMesh._getDrawWrapper(undefined, true);\n const cachedDefines = drawWrapper.defines;\n const join = defines.join(\"\\n\");\n if (cachedDefines !== join) {\n drawWrapper.setEffect(mesh\n .getScene()\n .getEngine()\n .createEffect(\"volumetricLightScatteringPass\", attribs, [\"world\", \"mBones\", \"viewProjection\", \"diffuseMatrix\"], [\"diffuseSampler\"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: mesh.numBoneInfluencers }), join);\n }\n return drawWrapper.effect.isReady();\n }\n /**\n * Sets the new light position for light scattering effect\n * @param position The new custom light position\n */\n setCustomMeshPosition(position) {\n this.customMeshPosition = position;\n }\n /**\n * Returns the light position for light scattering effect\n * @returns Vector3 The custom light position\n */\n getCustomMeshPosition() {\n return this.customMeshPosition;\n }\n /**\n * Disposes the internal assets and detaches the post-process from the camera\n * @param camera\n */\n dispose(camera) {\n const rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);\n if (rttIndex !== -1) {\n camera.getScene().customRenderTargets.splice(rttIndex, 1);\n }\n this._volumetricLightScatteringRTT.dispose();\n super.dispose(camera);\n }\n /**\n * Returns the render target texture used by the post-process\n * @returns the render target texture used by the post-process\n */\n getPass() {\n return this._volumetricLightScatteringRTT;\n }\n // Private methods\n _meshExcluded(mesh) {\n if ((this.includedMeshes.length > 0 && this.includedMeshes.indexOf(mesh) === -1) || (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1)) {\n return true;\n }\n return false;\n }\n _createPass(scene, ratio) {\n const engine = scene.getEngine();\n this._volumetricLightScatteringRTT = new RenderTargetTexture(\"volumetricLightScatteringMap\", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, 0);\n this._volumetricLightScatteringRTT.wrapU = Texture.CLAMP_ADDRESSMODE;\n this._volumetricLightScatteringRTT.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._volumetricLightScatteringRTT.renderList = null;\n this._volumetricLightScatteringRTT.renderParticles = false;\n this._volumetricLightScatteringRTT.ignoreCameraViewport = true;\n const camera = this.getCamera();\n if (camera) {\n camera.customRenderTargets.push(this._volumetricLightScatteringRTT);\n }\n else {\n scene.customRenderTargets.push(this._volumetricLightScatteringRTT);\n }\n // Custom render function for submeshes\n const renderSubMesh = (subMesh) => {\n var _a;\n const renderingMesh = subMesh.getRenderingMesh();\n const effectiveMesh = subMesh.getEffectiveMesh();\n if (this._meshExcluded(renderingMesh)) {\n return;\n }\n effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;\n const material = subMesh.getMaterial();\n if (!material) {\n return;\n }\n const scene = renderingMesh.getScene();\n const engine = scene.getEngine();\n // Culling\n engine.setState(material.backFaceCulling, undefined, undefined, undefined, material.cullBackFaces);\n // Managing instances\n const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());\n if (batch.mustReturn) {\n return;\n }\n const hardwareInstancedRendering = engine.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null || renderingMesh.hasThinInstances);\n if (this._isReady(subMesh, hardwareInstancedRendering)) {\n const renderingMaterial = (_a = effectiveMesh._internalAbstractMeshDataInfo._materialForRenderPass) === null || _a === void 0 ? void 0 : _a[engine.currentRenderPassId];\n let drawWrapper = subMesh._getDrawWrapper();\n if (renderingMesh === this.mesh && !drawWrapper) {\n drawWrapper = material._getDrawWrapper();\n }\n if (!drawWrapper) {\n return;\n }\n const effect = drawWrapper.effect;\n engine.enableEffect(drawWrapper);\n if (!hardwareInstancedRendering) {\n renderingMesh._bind(subMesh, effect, material.fillMode);\n }\n if (renderingMesh === this.mesh) {\n material.bind(effectiveMesh.getWorldMatrix(), renderingMesh);\n }\n else if (renderingMaterial) {\n renderingMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), effectiveMesh, subMesh);\n }\n else {\n effect.setMatrix(\"viewProjection\", scene.getTransformMatrix());\n // Alpha test\n if (material && material.needAlphaTesting()) {\n const alphaTexture = material.getAlphaTestTexture();\n effect.setTexture(\"diffuseSampler\", alphaTexture);\n if (alphaTexture) {\n effect.setMatrix(\"diffuseMatrix\", alphaTexture.getTextureMatrix());\n }\n }\n // Bones\n if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) {\n effect.setMatrices(\"mBones\", renderingMesh.skeleton.getTransformMatrices(renderingMesh));\n }\n }\n if (hardwareInstancedRendering && renderingMesh.hasThinInstances) {\n effect.setMatrix(\"world\", effectiveMesh.getWorldMatrix());\n }\n // Draw\n renderingMesh._processRendering(effectiveMesh, subMesh, effect, Material.TriangleFillMode, batch, hardwareInstancedRendering, (isInstance, world) => {\n if (!isInstance) {\n effect.setMatrix(\"world\", world);\n }\n });\n }\n };\n // Render target texture callbacks\n let savedSceneClearColor;\n const sceneClearColor = new Color4(0.0, 0.0, 0.0, 1.0);\n this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(() => {\n savedSceneClearColor = scene.clearColor;\n scene.clearColor = sceneClearColor;\n });\n this._volumetricLightScatteringRTT.onAfterRenderObservable.add(() => {\n scene.clearColor = savedSceneClearColor;\n });\n this._volumetricLightScatteringRTT.customIsReadyFunction = (mesh, refreshRate, preWarm) => {\n if ((preWarm || refreshRate === 0) && mesh.subMeshes) {\n for (let i = 0; i < mesh.subMeshes.length; ++i) {\n const subMesh = mesh.subMeshes[i];\n const material = subMesh.getMaterial();\n const renderingMesh = subMesh.getRenderingMesh();\n if (!material) {\n continue;\n }\n const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());\n const hardwareInstancedRendering = engine.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null || renderingMesh.hasThinInstances);\n if (!this._isReady(subMesh, hardwareInstancedRendering)) {\n return false;\n }\n }\n }\n return true;\n };\n this._volumetricLightScatteringRTT.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => {\n const engine = scene.getEngine();\n let index;\n if (depthOnlySubMeshes.length) {\n engine.setColorWrite(false);\n for (index = 0; index < depthOnlySubMeshes.length; index++) {\n renderSubMesh(depthOnlySubMeshes.data[index]);\n }\n engine.setColorWrite(true);\n }\n for (index = 0; index < opaqueSubMeshes.length; index++) {\n renderSubMesh(opaqueSubMeshes.data[index]);\n }\n for (index = 0; index < alphaTestSubMeshes.length; index++) {\n renderSubMesh(alphaTestSubMeshes.data[index]);\n }\n if (transparentSubMeshes.length) {\n // Sort sub meshes\n for (index = 0; index < transparentSubMeshes.length; index++) {\n const submesh = transparentSubMeshes.data[index];\n const boundingInfo = submesh.getBoundingInfo();\n if (boundingInfo && scene.activeCamera) {\n submesh._alphaIndex = submesh.getMesh().alphaIndex;\n submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();\n }\n }\n const sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);\n sortedArray.sort((a, b) => {\n // Alpha index first\n if (a._alphaIndex > b._alphaIndex) {\n return 1;\n }\n if (a._alphaIndex < b._alphaIndex) {\n return -1;\n }\n // Then distance to camera\n if (a._distanceToCamera < b._distanceToCamera) {\n return 1;\n }\n if (a._distanceToCamera > b._distanceToCamera) {\n return -1;\n }\n return 0;\n });\n // Render sub meshes\n engine.setAlphaMode(2);\n for (index = 0; index < sortedArray.length; index++) {\n renderSubMesh(sortedArray[index]);\n }\n engine.setAlphaMode(0);\n }\n };\n }\n _updateMeshScreenCoordinates(scene) {\n const transform = scene.getTransformMatrix();\n let meshPosition;\n if (this.useCustomMeshPosition) {\n meshPosition = this.customMeshPosition;\n }\n else if (this.attachedNode) {\n meshPosition = this.attachedNode.position;\n }\n else {\n meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;\n }\n const pos = Vector3.Project(meshPosition, Matrix.Identity(), transform, this._viewPort);\n this._screenCoordinates.x = pos.x / this._viewPort.width;\n this._screenCoordinates.y = pos.y / this._viewPort.height;\n if (this.invert) {\n this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;\n }\n }\n // Static methods\n /**\n * Creates a default mesh for the Volumeric Light Scattering post-process\n * @param name The mesh name\n * @param scene The scene where to create the mesh\n * @returns the default mesh\n */\n static CreateDefaultMesh(name, scene) {\n const mesh = CreatePlane(name, { size: 1 }, scene);\n mesh.billboardMode = AbstractMesh.BILLBOARDMODE_ALL;\n const material = new StandardMaterial(name + \"Material\", scene);\n material.emissiveColor = new Color3(1, 1, 1);\n mesh.material = material;\n return mesh;\n }\n}\n__decorate([\n serializeAsVector3()\n], VolumetricLightScatteringPostProcess.prototype, \"customMeshPosition\", void 0);\n__decorate([\n serialize()\n], VolumetricLightScatteringPostProcess.prototype, \"useCustomMeshPosition\", void 0);\n__decorate([\n serialize()\n], VolumetricLightScatteringPostProcess.prototype, \"invert\", void 0);\n__decorate([\n serializeAsMeshReference()\n], VolumetricLightScatteringPostProcess.prototype, \"mesh\", void 0);\n__decorate([\n serialize()\n], VolumetricLightScatteringPostProcess.prototype, \"excludedMeshes\", void 0);\n__decorate([\n serialize()\n], VolumetricLightScatteringPostProcess.prototype, \"includedMeshes\", void 0);\n__decorate([\n serialize()\n], VolumetricLightScatteringPostProcess.prototype, \"exposure\", void 0);\n__decorate([\n serialize()\n], VolumetricLightScatteringPostProcess.prototype, \"decay\", void 0);\n__decorate([\n serialize()\n], VolumetricLightScatteringPostProcess.prototype, \"weight\", void 0);\n__decorate([\n serialize()\n], VolumetricLightScatteringPostProcess.prototype, \"density\", void 0);\nRegisterClass(\"BABYLON.VolumetricLightScatteringPostProcess\", VolumetricLightScatteringPostProcess);\n//# sourceMappingURL=volumetricLightScatteringPostProcess.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"screenSpaceCurvaturePixelShader\";\nconst shader = `precision highp float;\rvarying vec2 vUV;\runiform sampler2D textureSampler;\runiform sampler2D normalSampler;\runiform float curvature_ridge;\runiform float curvature_valley;\r#ifndef CURVATURE_OFFSET\n#define CURVATURE_OFFSET 1\n#endif\nfloat curvature_soft_clamp(float curvature,float control)\r{\rif (curvature<0.5/control)\rreturn curvature*(1.0-curvature*control);\rreturn 0.25/control;\r}\rfloat calculate_curvature(ivec2 texel,float ridge,float valley)\r{\rvec2 normal_up =texelFetch(normalSampler,texel+ivec2(0, CURVATURE_OFFSET),0).rb;\rvec2 normal_down =texelFetch(normalSampler,texel+ivec2(0,-CURVATURE_OFFSET),0).rb;\rvec2 normal_left =texelFetch(normalSampler,texel+ivec2(-CURVATURE_OFFSET,0),0).rb;\rvec2 normal_right=texelFetch(normalSampler,texel+ivec2( CURVATURE_OFFSET,0),0).rb;\rfloat normal_diff=((normal_up.g-normal_down.g)+(normal_right.r-normal_left.r));\rif (normal_diff<0.0)\rreturn -2.0*curvature_soft_clamp(-normal_diff,valley);\rreturn 2.0*curvature_soft_clamp(normal_diff,ridge);\r}\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \r{\rivec2 texel=ivec2(gl_FragCoord.xy);\rvec4 baseColor=texture2D(textureSampler,vUV);\rfloat curvature=calculate_curvature(texel,curvature_ridge,curvature_valley);\rbaseColor.rgb*=curvature+1.0;\rgl_FragColor=baseColor;\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const screenSpaceCurvaturePixelShader = { name, shader };\n//# sourceMappingURL=screenSpaceCurvature.fragment.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { PostProcess } from \"./postProcess.js\";\n\nimport \"../Rendering/geometryBufferRendererSceneComponent.js\";\nimport \"../Shaders/screenSpaceCurvature.fragment.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\nimport { serialize, SerializationHelper } from \"../Misc/decorators.js\";\n/**\n * The Screen Space curvature effect can help highlighting ridge and valley of a model.\n */\nexport class ScreenSpaceCurvaturePostProcess extends PostProcess {\n /**\n * Gets a string identifying the name of the class\n * @returns \"ScreenSpaceCurvaturePostProcess\" string\n */\n getClassName() {\n return \"ScreenSpaceCurvaturePostProcess\";\n }\n /**\n * Creates a new instance ScreenSpaceCurvaturePostProcess\n * @param name The name of the effect.\n * @param scene The scene containing the objects to blur according to their velocity.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n constructor(name, scene, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) {\n super(name, \"screenSpaceCurvature\", [\"curvature_ridge\", \"curvature_valley\"], [\"textureSampler\", \"normalSampler\"], options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation);\n /**\n * Defines how much ridge the curvature effect displays.\n */\n this.ridge = 1;\n /**\n * Defines how much valley the curvature effect displays.\n */\n this.valley = 1;\n this._geometryBufferRenderer = scene.enableGeometryBufferRenderer();\n if (!this._geometryBufferRenderer) {\n // Geometry buffer renderer is not supported. So, work as a passthrough.\n Logger.Error(\"Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.\");\n }\n else {\n // Geometry buffer renderer is supported.\n this.onApply = (effect) => {\n effect.setFloat(\"curvature_ridge\", 0.5 / Math.max(this.ridge * this.ridge, 1e-4));\n effect.setFloat(\"curvature_valley\", 0.7 / Math.max(this.valley * this.valley, 1e-4));\n const normalTexture = this._geometryBufferRenderer.getGBuffer().textures[1];\n effect.setTexture(\"normalSampler\", normalTexture);\n };\n }\n }\n /**\n * Support test.\n */\n static get IsSupported() {\n const engine = EngineStore.LastCreatedEngine;\n if (!engine) {\n return false;\n }\n return engine.getCaps().drawBuffersExtension;\n }\n /**\n * @internal\n */\n static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) {\n return SerializationHelper.Parse(() => {\n return new ScreenSpaceCurvaturePostProcess(parsedPostProcess.name, scene, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.textureType, parsedPostProcess.reusable);\n }, parsedPostProcess, scene, rootUrl);\n }\n}\n__decorate([\n serialize()\n], ScreenSpaceCurvaturePostProcess.prototype, \"ridge\", void 0);\n__decorate([\n serialize()\n], ScreenSpaceCurvaturePostProcess.prototype, \"valley\", void 0);\nRegisterClass(\"BABYLON.ScreenSpaceCurvaturePostProcess\", ScreenSpaceCurvaturePostProcess);\n//# sourceMappingURL=screenSpaceCurvaturePostProcess.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./anaglyphPostProcess.js\";\nexport * from \"./blackAndWhitePostProcess.js\";\nexport * from \"./bloomEffect.js\";\nexport * from \"./bloomMergePostProcess.js\";\nexport * from \"./blurPostProcess.js\";\nexport * from \"./chromaticAberrationPostProcess.js\";\nexport * from \"./circleOfConfusionPostProcess.js\";\nexport * from \"./colorCorrectionPostProcess.js\";\nexport * from \"./convolutionPostProcess.js\";\nexport * from \"./depthOfFieldBlurPostProcess.js\";\nexport * from \"./depthOfFieldEffect.js\";\nexport * from \"./depthOfFieldMergePostProcess.js\";\nexport * from \"./displayPassPostProcess.js\";\nexport * from \"./extractHighlightsPostProcess.js\";\nexport * from \"./filterPostProcess.js\";\nexport * from \"./fxaaPostProcess.js\";\nexport * from \"./grainPostProcess.js\";\nexport * from \"./highlightsPostProcess.js\";\nexport * from \"./imageProcessingPostProcess.js\";\nexport * from \"./motionBlurPostProcess.js\";\nexport * from \"./passPostProcess.js\";\nexport * from \"./postProcess.js\";\nexport * from \"./postProcessManager.js\";\nexport * from \"./refractionPostProcess.js\";\nexport * from \"./RenderPipeline/index.js\";\nexport * from \"./sharpenPostProcess.js\";\nexport * from \"./stereoscopicInterlacePostProcess.js\";\nexport * from \"./tonemapPostProcess.js\";\nexport * from \"./volumetricLightScatteringPostProcess.js\";\nexport * from \"./vrDistortionCorrectionPostProcess.js\";\nexport * from \"./vrMultiviewToSingleviewPostProcess.js\";\nexport * from \"./screenSpaceReflectionPostProcess.js\";\nexport * from \"./screenSpaceCurvaturePostProcess.js\";\n//# sourceMappingURL=index.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"boundingBoxRendererUboDeclaration\";\nconst shader = `#ifdef WEBGL2\nuniform vec4 color;\runiform mat4 world;\runiform mat4 viewProjection;\r#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\r#endif\n#else\nlayout(std140,column_major) uniform;\runiform BoundingBoxRenderer {\rvec4 color;\rmat4 world;\rmat4 viewProjection;\rmat4 viewProjectionR;\r};\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const boundingBoxRendererUboDeclaration = { name, shader };\n//# sourceMappingURL=boundingBoxRendererUboDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/boundingBoxRendererFragmentDeclaration.js\";\nimport \"./ShadersInclude/boundingBoxRendererUboDeclaration.js\";\nconst name = \"boundingBoxRendererPixelShader\";\nconst shader = `#include<__decl__boundingBoxRendererFragment>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_FRAGMENT_MAIN_BEGIN\ngl_FragColor=color;\r#define CUSTOM_FRAGMENT_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const boundingBoxRendererPixelShader = { name, shader };\n//# sourceMappingURL=boundingBoxRenderer.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"boundingBoxRendererVertexDeclaration\";\nconst shader = `uniform mat4 world;\runiform mat4 viewProjection;\r#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const boundingBoxRendererVertexDeclaration = { name, shader };\n//# sourceMappingURL=boundingBoxRendererVertexDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/boundingBoxRendererVertexDeclaration.js\";\nimport \"./ShadersInclude/boundingBoxRendererUboDeclaration.js\";\nconst name = \"boundingBoxRendererVertexShader\";\nconst shader = `attribute vec3 position;\r#include<__decl__boundingBoxRendererVertex>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_VERTEX_MAIN_BEGIN\nvec4 worldPos=world*vec4(position,1.0);\r#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {\rgl_Position=viewProjection*worldPos;\r} else {\rgl_Position=viewProjectionR*worldPos;\r}\r#else\ngl_Position=viewProjection*worldPos;\r#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const boundingBoxRendererVertexShader = { name, shader };\n//# sourceMappingURL=boundingBoxRenderer.vertex.js.map","import { Scene } from \"../scene.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { AbstractMesh } from \"../Meshes/abstractMesh.js\";\nimport { Matrix } from \"../Maths/math.vector.js\";\nimport { SmartArray } from \"../Misc/smartArray.js\";\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { Material } from \"../Materials/material.js\";\nimport { ShaderMaterial } from \"../Materials/shaderMaterial.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { DrawWrapper } from \"../Materials/drawWrapper.js\";\nimport { UniformBuffer } from \"../Materials/uniformBuffer.js\";\nimport { CreateBoxVertexData } from \"../Meshes/Builders/boxBuilder.js\";\nimport \"../Shaders/boundingBoxRenderer.fragment.js\";\nimport \"../Shaders/boundingBoxRenderer.vertex.js\";\nObject.defineProperty(Scene.prototype, \"forceShowBoundingBoxes\", {\n get: function () {\n return this._forceShowBoundingBoxes || false;\n },\n set: function (value) {\n this._forceShowBoundingBoxes = value;\n // Lazyly creates a BB renderer if needed.\n if (value) {\n this.getBoundingBoxRenderer();\n }\n },\n enumerable: true,\n configurable: true,\n});\nScene.prototype.getBoundingBoxRenderer = function () {\n if (!this._boundingBoxRenderer) {\n this._boundingBoxRenderer = new BoundingBoxRenderer(this);\n }\n return this._boundingBoxRenderer;\n};\nObject.defineProperty(AbstractMesh.prototype, \"showBoundingBox\", {\n get: function () {\n return this._showBoundingBox || false;\n },\n set: function (value) {\n this._showBoundingBox = value;\n // Lazyly creates a BB renderer if needed.\n if (value) {\n this.getScene().getBoundingBoxRenderer();\n }\n },\n enumerable: true,\n configurable: true,\n});\n/**\n * Component responsible of rendering the bounding box of the meshes in a scene.\n * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties\n */\nexport class BoundingBoxRenderer {\n /**\n * Instantiates a new bounding box renderer in a scene.\n * @param scene the scene the renderer renders in\n */\n constructor(scene) {\n /**\n * The component name helpful to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;\n /**\n * Color of the bounding box lines placed in front of an object\n */\n this.frontColor = new Color3(1, 1, 1);\n /**\n * Color of the bounding box lines placed behind an object\n */\n this.backColor = new Color3(0.1, 0.1, 0.1);\n /**\n * Defines if the renderer should show the back lines or not\n */\n this.showBackLines = true;\n /**\n * Observable raised before rendering a bounding box\n */\n this.onBeforeBoxRenderingObservable = new Observable();\n /**\n * Observable raised after rendering a bounding box\n */\n this.onAfterBoxRenderingObservable = new Observable();\n /**\n * Observable raised after resources are created\n */\n this.onResourcesReadyObservable = new Observable();\n /**\n * When false, no bounding boxes will be rendered\n */\n this.enabled = true;\n /**\n * @internal\n */\n this.renderList = new SmartArray(32);\n this._vertexBuffers = {};\n this._fillIndexBuffer = null;\n this._fillIndexData = null;\n this.scene = scene;\n scene._addComponent(this);\n this._uniformBufferFront = new UniformBuffer(this.scene.getEngine(), undefined, undefined, \"BoundingBoxRendererFront\", !this.scene.getEngine().isWebGPU);\n this._buildUniformLayout(this._uniformBufferFront);\n this._uniformBufferBack = new UniformBuffer(this.scene.getEngine(), undefined, undefined, \"BoundingBoxRendererBack\", !this.scene.getEngine().isWebGPU);\n this._buildUniformLayout(this._uniformBufferBack);\n }\n _buildUniformLayout(ubo) {\n ubo.addUniform(\"color\", 4);\n ubo.addUniform(\"world\", 16);\n ubo.addUniform(\"viewProjection\", 16);\n ubo.addUniform(\"viewProjectionR\", 16);\n ubo.create();\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene._beforeEvaluateActiveMeshStage.registerStep(SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);\n this.scene._preActiveMeshStage.registerStep(SceneComponentConstants.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER, this, this._preActiveMesh);\n this.scene._evaluateSubMeshStage.registerStep(SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);\n this.scene._afterRenderingGroupDrawStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);\n }\n _evaluateSubMesh(mesh, subMesh) {\n if (mesh.showSubMeshesBoundingBox) {\n const boundingInfo = subMesh.getBoundingInfo();\n if (boundingInfo !== null && boundingInfo !== undefined) {\n boundingInfo.boundingBox._tag = mesh.renderingGroupId;\n this.renderList.push(boundingInfo.boundingBox);\n }\n }\n }\n _preActiveMesh(mesh) {\n if (mesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {\n const boundingInfo = mesh.getBoundingInfo();\n boundingInfo.boundingBox._tag = mesh.renderingGroupId;\n this.renderList.push(boundingInfo.boundingBox);\n }\n }\n _prepareResources() {\n if (this._colorShader) {\n return;\n }\n this._colorShader = new ShaderMaterial(\"colorShader\", this.scene, \"boundingBoxRenderer\", {\n attributes: [VertexBuffer.PositionKind],\n uniforms: [\"world\", \"viewProjection\", \"viewProjectionR\", \"color\"],\n uniformBuffers: [\"BoundingBoxRenderer\"],\n }, false);\n this._colorShader.doNotSerialize = true;\n this._colorShader.reservedDataStore = {\n hidden: true,\n };\n this._colorShaderForOcclusionQuery = new ShaderMaterial(\"colorShaderOccQuery\", this.scene, \"boundingBoxRenderer\", {\n attributes: [VertexBuffer.PositionKind],\n uniforms: [\"world\", \"viewProjection\", \"viewProjectionR\", \"color\"],\n uniformBuffers: [\"BoundingBoxRenderer\"],\n }, true);\n this._colorShaderForOcclusionQuery.doNotSerialize = true;\n this._colorShaderForOcclusionQuery.reservedDataStore = {\n hidden: true,\n };\n const engine = this.scene.getEngine();\n const boxdata = CreateBoxVertexData({ size: 1.0 });\n this._vertexBuffers[VertexBuffer.PositionKind] = new VertexBuffer(engine, boxdata.positions, VertexBuffer.PositionKind, false);\n this._createIndexBuffer();\n this._fillIndexData = boxdata.indices;\n this.onResourcesReadyObservable.notifyObservers(this);\n }\n _createIndexBuffer() {\n const engine = this.scene.getEngine();\n this._indexBuffer = engine.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n const vb = this._vertexBuffers[VertexBuffer.PositionKind];\n if (vb) {\n vb._rebuild();\n }\n this._createIndexBuffer();\n }\n /**\n * @internal\n */\n reset() {\n this.renderList.reset();\n }\n /**\n * Render the bounding boxes of a specific rendering group\n * @param renderingGroupId defines the rendering group to render\n */\n render(renderingGroupId) {\n var _a, _b;\n if (this.renderList.length === 0 || !this.enabled) {\n return;\n }\n this._prepareResources();\n if (!this._colorShader.isReady()) {\n return;\n }\n const engine = this.scene.getEngine();\n engine.setDepthWrite(false);\n const transformMatrix = this.scene.getTransformMatrix();\n for (let boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {\n const boundingBox = this.renderList.data[boundingBoxIndex];\n if (boundingBox._tag !== renderingGroupId) {\n continue;\n }\n this._createWrappersForBoundingBox(boundingBox);\n this.onBeforeBoxRenderingObservable.notifyObservers(boundingBox);\n const min = boundingBox.minimum;\n const max = boundingBox.maximum;\n const diff = max.subtract(min);\n const median = min.add(diff.scale(0.5));\n const worldMatrix = Matrix.Scaling(diff.x, diff.y, diff.z).multiply(Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());\n const useReverseDepthBuffer = engine.useReverseDepthBuffer;\n if (this.showBackLines) {\n const drawWrapperBack = (_a = boundingBox._drawWrapperBack) !== null && _a !== void 0 ? _a : this._colorShader._getDrawWrapper();\n this._colorShader._preBind(drawWrapperBack);\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());\n // Back\n if (useReverseDepthBuffer) {\n engine.setDepthFunctionToLessOrEqual();\n }\n else {\n engine.setDepthFunctionToGreaterOrEqual();\n }\n this._uniformBufferBack.bindToEffect(drawWrapperBack.effect, \"BoundingBoxRenderer\");\n this._uniformBufferBack.updateColor4(\"color\", this.backColor, 1);\n this._uniformBufferBack.updateMatrix(\"world\", worldMatrix);\n this._uniformBufferBack.updateMatrix(\"viewProjection\", transformMatrix);\n this._uniformBufferBack.update();\n // Draw order\n engine.drawElementsType(Material.LineListDrawMode, 0, 24);\n }\n const drawWrapperFront = (_b = boundingBox._drawWrapperFront) !== null && _b !== void 0 ? _b : this._colorShader._getDrawWrapper();\n this._colorShader._preBind(drawWrapperFront);\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());\n // Front\n if (useReverseDepthBuffer) {\n engine.setDepthFunctionToGreater();\n }\n else {\n engine.setDepthFunctionToLess();\n }\n this._uniformBufferFront.bindToEffect(drawWrapperFront.effect, \"BoundingBoxRenderer\");\n this._uniformBufferFront.updateColor4(\"color\", this.frontColor, 1);\n this._uniformBufferFront.updateMatrix(\"world\", worldMatrix);\n this._uniformBufferFront.updateMatrix(\"viewProjection\", transformMatrix);\n this._uniformBufferFront.update();\n // Draw order\n engine.drawElementsType(Material.LineListDrawMode, 0, 24);\n this.onAfterBoxRenderingObservable.notifyObservers(boundingBox);\n }\n this._colorShader.unbind();\n engine.setDepthFunctionToLessOrEqual();\n engine.setDepthWrite(true);\n }\n _createWrappersForBoundingBox(boundingBox) {\n if (!boundingBox._drawWrapperFront) {\n const engine = this.scene.getEngine();\n boundingBox._drawWrapperFront = new DrawWrapper(engine);\n boundingBox._drawWrapperBack = new DrawWrapper(engine);\n boundingBox._drawWrapperFront.setEffect(this._colorShader.getEffect());\n boundingBox._drawWrapperBack.setEffect(this._colorShader.getEffect());\n }\n }\n /**\n * In case of occlusion queries, we can render the occlusion bounding box through this method\n * @param mesh Define the mesh to render the occlusion bounding box for\n */\n renderOcclusionBoundingBox(mesh) {\n const engine = this.scene.getEngine();\n if (this._renderPassIdForOcclusionQuery === undefined) {\n this._renderPassIdForOcclusionQuery = engine.createRenderPassId(`Render pass for occlusion query`);\n }\n const currentRenderPassId = engine.currentRenderPassId;\n engine.currentRenderPassId = this._renderPassIdForOcclusionQuery;\n this._prepareResources();\n const subMesh = mesh.subMeshes[0];\n if (!this._colorShaderForOcclusionQuery.isReady(mesh, undefined, subMesh) || !mesh.hasBoundingInfo) {\n engine.currentRenderPassId = currentRenderPassId;\n return;\n }\n if (!this._fillIndexBuffer) {\n this._fillIndexBuffer = engine.createIndexBuffer(this._fillIndexData);\n }\n const useReverseDepthBuffer = engine.useReverseDepthBuffer;\n engine.setDepthWrite(false);\n engine.setColorWrite(false);\n const boundingBox = mesh.getBoundingInfo().boundingBox;\n const min = boundingBox.minimum;\n const max = boundingBox.maximum;\n const diff = max.subtract(min);\n const median = min.add(diff.scale(0.5));\n const worldMatrix = Matrix.Scaling(diff.x, diff.y, diff.z).multiply(Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());\n const drawWrapper = subMesh._drawWrapper;\n this._colorShaderForOcclusionQuery._preBind(drawWrapper);\n engine.bindBuffers(this._vertexBuffers, this._fillIndexBuffer, drawWrapper.effect);\n if (useReverseDepthBuffer) {\n engine.setDepthFunctionToGreater();\n }\n else {\n engine.setDepthFunctionToLess();\n }\n this.scene.resetCachedMaterial();\n this._uniformBufferFront.bindToEffect(drawWrapper.effect, \"BoundingBoxRenderer\");\n this._uniformBufferFront.updateMatrix(\"world\", worldMatrix);\n this._uniformBufferFront.updateMatrix(\"viewProjection\", this.scene.getTransformMatrix());\n this._uniformBufferFront.update();\n engine.drawElementsType(Material.TriangleFillMode, 0, 36);\n this._colorShaderForOcclusionQuery.unbind();\n engine.setDepthFunctionToLessOrEqual();\n engine.setDepthWrite(true);\n engine.setColorWrite(true);\n engine.currentRenderPassId = currentRenderPassId;\n }\n /**\n * Dispose and release the resources attached to this renderer.\n */\n dispose() {\n if (this._renderPassIdForOcclusionQuery !== undefined) {\n this.scene.getEngine().releaseRenderPassId(this._renderPassIdForOcclusionQuery);\n this._renderPassIdForOcclusionQuery = undefined;\n }\n if (!this._colorShader) {\n return;\n }\n this.onBeforeBoxRenderingObservable.clear();\n this.onAfterBoxRenderingObservable.clear();\n this.onResourcesReadyObservable.clear();\n this.renderList.dispose();\n this._colorShader.dispose();\n this._colorShaderForOcclusionQuery.dispose();\n this._uniformBufferFront.dispose();\n this._uniformBufferBack.dispose();\n const buffer = this._vertexBuffers[VertexBuffer.PositionKind];\n if (buffer) {\n buffer.dispose();\n this._vertexBuffers[VertexBuffer.PositionKind] = null;\n }\n this.scene.getEngine()._releaseBuffer(this._indexBuffer);\n if (this._fillIndexBuffer) {\n this.scene.getEngine()._releaseBuffer(this._fillIndexBuffer);\n this._fillIndexBuffer = null;\n }\n }\n}\n//# sourceMappingURL=boundingBoxRenderer.js.map","import { Scene } from \"../scene.js\";\nimport { DepthRenderer } from \"./depthRenderer.js\";\n\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nScene.prototype.enableDepthRenderer = function (camera, storeNonLinearDepth = false, force32bitsFloat = false, samplingMode = 3, storeCameraSpaceZ = false) {\n camera = camera || this.activeCamera;\n if (!camera) {\n throw \"No camera available to enable depth renderer\";\n }\n if (!this._depthRenderer) {\n this._depthRenderer = {};\n }\n if (!this._depthRenderer[camera.id]) {\n const supportFullfloat = !!this.getEngine().getCaps().textureFloatRender;\n let textureType = 0;\n if (this.getEngine().getCaps().textureHalfFloatRender && (!force32bitsFloat || !supportFullfloat)) {\n textureType = 2;\n }\n else if (supportFullfloat) {\n textureType = 1;\n }\n else {\n textureType = 0;\n }\n this._depthRenderer[camera.id] = new DepthRenderer(this, textureType, camera, storeNonLinearDepth, samplingMode, storeCameraSpaceZ);\n }\n return this._depthRenderer[camera.id];\n};\nScene.prototype.disableDepthRenderer = function (camera) {\n camera = camera || this.activeCamera;\n if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {\n return;\n }\n this._depthRenderer[camera.id].dispose();\n};\n/**\n * Defines the Depth Renderer scene component responsible to manage a depth buffer useful\n * in several rendering techniques.\n */\nexport class DepthRendererSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpful to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_DEPTHRENDERER;\n this.scene = scene;\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene._gatherRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);\n this.scene._gatherActiveCameraRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n // Nothing to do for this component\n }\n /**\n * Disposes the component and the associated resources\n */\n dispose() {\n for (const key in this.scene._depthRenderer) {\n this.scene._depthRenderer[key].dispose();\n }\n }\n _gatherRenderTargets(renderTargets) {\n if (this.scene._depthRenderer) {\n for (const key in this.scene._depthRenderer) {\n const depthRenderer = this.scene._depthRenderer[key];\n if (depthRenderer.enabled && !depthRenderer.useOnlyInActiveCamera) {\n renderTargets.push(depthRenderer.getDepthMap());\n }\n }\n }\n }\n _gatherActiveCameraRenderTargets(renderTargets) {\n if (this.scene._depthRenderer) {\n for (const key in this.scene._depthRenderer) {\n const depthRenderer = this.scene._depthRenderer[key];\n if (depthRenderer.enabled && depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {\n renderTargets.push(depthRenderer.getDepthMap());\n }\n }\n }\n }\n}\nDepthRenderer._SceneComponentInitialization = (scene) => {\n // Register the G Buffer component to the scene.\n let component = scene._getComponent(SceneComponentConstants.NAME_DEPTHRENDERER);\n if (!component) {\n component = new DepthRendererSceneComponent(scene);\n scene._addComponent(component);\n }\n};\n//# sourceMappingURL=depthRendererSceneComponent.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"oitFinalPixelShader\";\nconst shader = `precision highp float;\runiform sampler2D uFrontColor;\runiform sampler2D uBackColor;\rvoid main() {\rivec2 fragCoord=ivec2(gl_FragCoord.xy);\rvec4 frontColor=texelFetch(uFrontColor,fragCoord,0);\rvec4 backColor=texelFetch(uBackColor,fragCoord,0);\rfloat alphaMultiplier=1.0-frontColor.a;\rglFragColor=vec4(\rfrontColor.rgb+alphaMultiplier*backColor.rgb,\rfrontColor.a+backColor.a\r);\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const oitFinalPixelShader = { name, shader };\n//# sourceMappingURL=oitFinal.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"oitBackBlendPixelShader\";\nconst shader = `precision highp float;\runiform sampler2D uBackColor;\rvoid main() {\rglFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);\rif (glFragColor.a==0.0) { \rdiscard;\r}\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const oitBackBlendPixelShader = { name, shader };\n//# sourceMappingURL=oitBackBlend.fragment.js.map","/**\n * Implementation based on https://medium.com/@shrekshao_71662/dual-depth-peeling-implementation-in-webgl-11baa061ba4b\n */\n\nimport { MultiRenderTarget } from \"../Materials/Textures/multiRenderTarget.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { SmartArray } from \"../Misc/smartArray.js\";\nimport { ThinTexture } from \"../Materials/Textures/thinTexture.js\";\nimport { EffectRenderer, EffectWrapper } from \"../Materials/effectRenderer.js\";\nimport { RenderTargetTexture } from \"../Materials/Textures/renderTargetTexture.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { Material } from \"../Materials/material.js\";\nimport \"../Shaders/postprocess.vertex.js\";\nimport \"../Shaders/oitFinal.fragment.js\";\nimport \"../Shaders/oitBackBlend.fragment.js\";\nclass DepthPeelingEffectConfiguration {\n constructor() {\n /**\n * Is this effect enabled\n */\n this.enabled = true;\n /**\n * Name of the configuration\n */\n this.name = \"depthPeeling\";\n /**\n * Textures that should be present in the MRT for this effect to work\n */\n this.texturesRequired = [4];\n }\n}\n/**\n * The depth peeling renderer that performs\n * Order independant transparency (OIT).\n * This should not be instanciated directly, as it is part of a scene component\n */\nexport class DepthPeelingRenderer {\n /**\n * Number of depth peeling passes. As we are using dual depth peeling, each pass two levels of transparency are processed.\n */\n get passCount() {\n return this._passCount;\n }\n set passCount(count) {\n if (this._passCount === count) {\n return;\n }\n this._passCount = count;\n this._createRenderPassIds();\n }\n /**\n * Instructs the renderer to use render passes. It is an optimization that makes the rendering faster for some engines (like WebGPU) but that consumes more memory, so it is disabled by default.\n */\n get useRenderPasses() {\n return this._useRenderPasses;\n }\n set useRenderPasses(usePasses) {\n if (this._useRenderPasses === usePasses) {\n return;\n }\n this._useRenderPasses = usePasses;\n this._createRenderPassIds();\n }\n /**\n * Add a mesh in the exclusion list to prevent it to be handled by the depth peeling renderer\n * @param mesh The mesh to exclude from the depth peeling renderer\n */\n addExcludedMesh(mesh) {\n if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {\n this._excludedMeshes.push(mesh.uniqueId);\n }\n }\n /**\n * Remove a mesh from the exclusion list of the depth peeling renderer\n * @param mesh The mesh to remove\n */\n removeExcludedMesh(mesh) {\n const index = this._excludedMeshes.indexOf(mesh.uniqueId);\n if (index !== -1) {\n this._excludedMeshes.splice(index, 1);\n }\n }\n /**\n * Instanciates the depth peeling renderer\n * @param scene Scene to attach to\n * @param passCount Number of depth layers to peel\n * @returns The depth peeling renderer\n */\n constructor(scene, passCount = 5) {\n this._thinTextures = [];\n this._currentPingPongState = 0;\n this._layoutCacheFormat = [[true], [true, true], [true, true, true]];\n this._layoutCache = [];\n this._candidateSubMeshes = new SmartArray(10);\n this._excludedSubMeshes = new SmartArray(10);\n this._excludedMeshes = [];\n this._colorCache = [\n new Color4(DepthPeelingRenderer._DEPTH_CLEAR_VALUE, DepthPeelingRenderer._DEPTH_CLEAR_VALUE, 0, 0),\n new Color4(-DepthPeelingRenderer._MIN_DEPTH, DepthPeelingRenderer._MAX_DEPTH, 0, 0),\n new Color4(0, 0, 0, 0),\n ];\n this._scene = scene;\n this._engine = scene.getEngine();\n this._passCount = passCount;\n // We need a depth texture for opaque\n if (!scene.enablePrePassRenderer()) {\n Logger.Warn(\"Depth peeling for order independant transparency could not enable PrePass, aborting.\");\n return;\n }\n for (let i = 0; i < this._layoutCacheFormat.length; ++i) {\n this._layoutCache[i] = this._engine.buildTextureLayout(this._layoutCacheFormat[i]);\n }\n this._renderPassIds = [];\n this.useRenderPasses = false;\n this._prePassEffectConfiguration = new DepthPeelingEffectConfiguration();\n this._createTextures();\n this._createEffects();\n }\n _createRenderPassIds() {\n this._releaseRenderPassIds();\n if (this._useRenderPasses) {\n for (let i = 0; i < this._passCount + 1; ++i) {\n if (!this._renderPassIds[i]) {\n this._renderPassIds[i] = this._engine.createRenderPassId(`DepthPeelingRenderer - pass #${i}`);\n }\n }\n }\n }\n _releaseRenderPassIds() {\n for (let i = 0; i < this._renderPassIds.length; ++i) {\n this._engine.releaseRenderPassId(this._renderPassIds[i]);\n }\n this._renderPassIds = [];\n }\n _createTextures() {\n const size = {\n width: this._engine.getRenderWidth(),\n height: this._engine.getRenderHeight(),\n };\n // 2 for ping pong\n this._depthMrts = [new MultiRenderTarget(\"depthPeelingDepth0\", size, 3, this._scene), new MultiRenderTarget(\"depthPeelingDepth1\", size, 3, this._scene)];\n this._colorMrts = [\n new MultiRenderTarget(\"depthPeelingColor0\", size, 2, this._scene, { generateDepthBuffer: false }),\n new MultiRenderTarget(\"depthPeelingColor1\", size, 2, this._scene, { generateDepthBuffer: false }),\n ];\n this._blendBackMrt = new MultiRenderTarget(\"depthPeelingBack\", size, 1, this._scene, { generateDepthBuffer: false });\n this._outputRT = new RenderTargetTexture(\"depthPeelingOutput\", size, this._scene, false);\n // 0 is a depth texture\n // 1 is a color texture\n const optionsArray = [\n {\n format: 7,\n samplingMode: 1,\n type: this._engine.getCaps().textureFloatLinearFiltering ? 1 : 2,\n label: \"DepthPeelingRenderer-DepthTexture\",\n },\n {\n format: 5,\n samplingMode: 1,\n type: 2,\n label: \"DepthPeelingRenderer-ColorTexture\",\n },\n ];\n for (let i = 0; i < 2; i++) {\n const depthTexture = this._engine._createInternalTexture(size, optionsArray[0], false);\n const frontColorTexture = this._engine._createInternalTexture(size, optionsArray[1], false);\n const backColorTexture = this._engine._createInternalTexture(size, optionsArray[1], false);\n this._depthMrts[i].setInternalTexture(depthTexture, 0);\n this._depthMrts[i].setInternalTexture(frontColorTexture, 1);\n this._depthMrts[i].setInternalTexture(backColorTexture, 2);\n this._colorMrts[i].setInternalTexture(frontColorTexture, 0);\n this._colorMrts[i].setInternalTexture(backColorTexture, 1);\n this._thinTextures.push(new ThinTexture(depthTexture), new ThinTexture(frontColorTexture), new ThinTexture(backColorTexture));\n }\n }\n // TODO : explore again MSAA with depth peeling when\n // we are able to fetch individual samples in a multisampled renderbuffer\n // public set samples(value: number) {\n // for (let i = 0; i < 2; i++) {\n // this._depthMrts[i].samples = value;\n // this._colorMrts[i].samples = value;\n // }\n // this._scene.prePassRenderer!.samples = value;\n // }\n _disposeTextures() {\n for (let i = 0; i < this._thinTextures.length; i++) {\n if (i === 6) {\n // Do not dispose the shared texture with the prepass\n continue;\n }\n this._thinTextures[i].dispose();\n }\n for (let i = 0; i < 2; i++) {\n this._depthMrts[i].dispose(true);\n this._colorMrts[i].dispose(true);\n this._blendBackMrt.dispose(true);\n }\n this._outputRT.dispose();\n this._thinTextures = [];\n this._colorMrts = [];\n this._depthMrts = [];\n }\n _updateTextures() {\n if (this._depthMrts[0].getSize().width !== this._engine.getRenderWidth() || this._depthMrts[0].getSize().height !== this._engine.getRenderHeight()) {\n this._disposeTextures();\n this._createTextures();\n }\n return this._updateTextureReferences();\n }\n _updateTextureReferences() {\n var _a;\n const prePassRenderer = this._scene.prePassRenderer;\n if (!prePassRenderer) {\n return false;\n }\n // Retrieve opaque color texture\n const textureIndex = prePassRenderer.getIndex(4);\n const prePassTexture = ((_a = prePassRenderer.defaultRT.textures) === null || _a === void 0 ? void 0 : _a.length) ? prePassRenderer.defaultRT.textures[textureIndex].getInternalTexture() : null;\n if (!prePassTexture) {\n return false;\n }\n if (this._blendBackTexture !== prePassTexture) {\n this._blendBackTexture = prePassTexture;\n this._blendBackMrt.setInternalTexture(this._blendBackTexture, 0);\n if (this._thinTextures[6]) {\n this._thinTextures[6].dispose();\n }\n this._thinTextures[6] = new ThinTexture(this._blendBackTexture);\n prePassRenderer.defaultRT.renderTarget._shareDepth(this._depthMrts[0].renderTarget);\n }\n return true;\n }\n _createEffects() {\n this._blendBackEffectWrapper = new EffectWrapper({\n fragmentShader: \"oitBackBlend\",\n useShaderStore: true,\n engine: this._engine,\n samplerNames: [\"uBackColor\"],\n uniformNames: [],\n });\n this._blendBackEffectWrapperPingPong = new EffectWrapper({\n fragmentShader: \"oitBackBlend\",\n useShaderStore: true,\n engine: this._engine,\n samplerNames: [\"uBackColor\"],\n uniformNames: [],\n });\n this._finalEffectWrapper = new EffectWrapper({\n fragmentShader: \"oitFinal\",\n useShaderStore: true,\n engine: this._engine,\n samplerNames: [\"uFrontColor\", \"uBackColor\"],\n uniformNames: [],\n });\n this._effectRenderer = new EffectRenderer(this._engine);\n }\n /**\n * Links to the prepass renderer\n * @param prePassRenderer The scene PrePassRenderer\n */\n setPrePassRenderer(prePassRenderer) {\n prePassRenderer.addEffectConfiguration(this._prePassEffectConfiguration);\n }\n /**\n * Binds depth peeling textures on an effect\n * @param effect The effect to bind textures on\n */\n bind(effect) {\n effect.setTexture(\"oitDepthSampler\", this._thinTextures[this._currentPingPongState * 3]);\n effect.setTexture(\"oitFrontColorSampler\", this._thinTextures[this._currentPingPongState * 3 + 1]);\n }\n _renderSubMeshes(transparentSubMeshes) {\n let mapMaterialContext;\n if (this._useRenderPasses) {\n mapMaterialContext = {};\n }\n for (let j = 0; j < transparentSubMeshes.length; j++) {\n const material = transparentSubMeshes.data[j].getMaterial();\n let previousShaderHotSwapping = true;\n let previousBFC = false;\n const subMesh = transparentSubMeshes.data[j];\n let drawWrapper;\n let firstDraw = false;\n if (this._useRenderPasses) {\n drawWrapper = subMesh._getDrawWrapper();\n firstDraw = !drawWrapper;\n }\n if (material) {\n previousShaderHotSwapping = material.allowShaderHotSwapping;\n previousBFC = material.backFaceCulling;\n material.allowShaderHotSwapping = false;\n material.backFaceCulling = false;\n }\n subMesh.render(false);\n if (firstDraw) {\n // first time we draw this submesh: we replace the material context\n drawWrapper = subMesh._getDrawWrapper(); // we are sure it is now non empty as we just rendered the submesh\n if (drawWrapper.materialContext) {\n let newMaterialContext = mapMaterialContext[drawWrapper.materialContext.uniqueId];\n if (!newMaterialContext) {\n newMaterialContext = mapMaterialContext[drawWrapper.materialContext.uniqueId] = this._engine.createMaterialContext();\n }\n subMesh._getDrawWrapper().materialContext = newMaterialContext;\n }\n }\n if (material) {\n material.allowShaderHotSwapping = previousShaderHotSwapping;\n material.backFaceCulling = previousBFC;\n }\n }\n }\n _finalCompose(writeId) {\n var _a;\n const output = (_a = this._scene.prePassRenderer) === null || _a === void 0 ? void 0 : _a.setCustomOutput(this._outputRT);\n if (output) {\n this._engine.bindFramebuffer(this._outputRT.renderTarget);\n }\n else {\n this._engine.restoreDefaultFramebuffer();\n }\n this._engine.setAlphaMode(0);\n this._engine.applyStates();\n this._engine.enableEffect(this._finalEffectWrapper._drawWrapper);\n this._finalEffectWrapper.effect.setTexture(\"uFrontColor\", this._thinTextures[writeId * 3 + 1]);\n this._finalEffectWrapper.effect.setTexture(\"uBackColor\", this._thinTextures[6]);\n this._effectRenderer.render(this._finalEffectWrapper);\n }\n /**\n * Renders transparent submeshes with depth peeling\n * @param transparentSubMeshes List of transparent meshes to render\n * @returns The array of submeshes that could not be handled by this renderer\n */\n render(transparentSubMeshes) {\n this._candidateSubMeshes.length = 0;\n this._excludedSubMeshes.length = 0;\n if (!this._blendBackEffectWrapper.effect.isReady() ||\n !this._blendBackEffectWrapperPingPong.effect.isReady() ||\n !this._finalEffectWrapper.effect.isReady() ||\n !this._updateTextures()) {\n return this._excludedSubMeshes;\n }\n for (let i = 0; i < transparentSubMeshes.length; i++) {\n const subMesh = transparentSubMeshes.data[i];\n const material = subMesh.getMaterial();\n const fillMode = material && subMesh.getRenderingMesh()._getRenderingFillMode(material.fillMode);\n if (material &&\n (fillMode === Material.TriangleFanDrawMode || fillMode === Material.TriangleFillMode || fillMode === Material.TriangleStripDrawMode) &&\n this._excludedMeshes.indexOf(subMesh.getMesh().uniqueId) === -1) {\n this._candidateSubMeshes.push(subMesh);\n }\n else {\n this._excludedSubMeshes.push(subMesh);\n }\n }\n if (!this._candidateSubMeshes.length) {\n this._engine.bindFramebuffer(this._colorMrts[1].renderTarget);\n this._engine.bindAttachments(this._layoutCache[1]);\n this._engine.clear(this._colorCache[2], true, false, false);\n this._engine.unBindFramebuffer(this._colorMrts[1].renderTarget);\n this._finalCompose(1);\n return this._excludedSubMeshes;\n }\n const currentRenderPassId = this._engine.currentRenderPassId;\n this._scene.prePassRenderer._enabled = false;\n if (this._useRenderPasses) {\n this._engine.currentRenderPassId = this._renderPassIds[0];\n }\n // Clears\n this._engine.bindFramebuffer(this._depthMrts[0].renderTarget);\n this._engine.bindAttachments(this._layoutCache[0]);\n this._engine.clear(this._colorCache[0], true, false, false);\n this._engine.unBindFramebuffer(this._depthMrts[0].renderTarget);\n this._engine.bindFramebuffer(this._depthMrts[1].renderTarget);\n this._engine.bindAttachments(this._layoutCache[0]);\n this._engine.clear(this._colorCache[1], true, false, false);\n this._engine.unBindFramebuffer(this._depthMrts[1].renderTarget);\n this._engine.bindFramebuffer(this._colorMrts[0].renderTarget);\n this._engine.bindAttachments(this._layoutCache[1]);\n this._engine.clear(this._colorCache[2], true, false, false);\n this._engine.unBindFramebuffer(this._colorMrts[0].renderTarget);\n this._engine.bindFramebuffer(this._colorMrts[1].renderTarget);\n this._engine.bindAttachments(this._layoutCache[1]);\n this._engine.clear(this._colorCache[2], true, false, false);\n this._engine.unBindFramebuffer(this._colorMrts[1].renderTarget);\n // Draw depth for first pass\n this._engine.bindFramebuffer(this._depthMrts[0].renderTarget);\n this._engine.bindAttachments(this._layoutCache[0]);\n this._engine.setAlphaMode(11); // in WebGPU, when using MIN or MAX equation, the src / dst color factors should not use SRC_ALPHA and the src / dst alpha factors must be 1 else WebGPU will throw a validation error\n this._engine.setAlphaEquation(3);\n this._engine.depthCullingState.depthMask = false;\n this._engine.depthCullingState.depthTest = true;\n this._engine.applyStates();\n this._currentPingPongState = 1;\n // Render\n this._renderSubMeshes(this._candidateSubMeshes);\n this._engine.unBindFramebuffer(this._depthMrts[0].renderTarget);\n this._scene.resetCachedMaterial();\n // depth peeling ping-pong\n let readId = 0;\n let writeId = 0;\n for (let i = 0; i < this._passCount; i++) {\n readId = i % 2;\n writeId = 1 - readId;\n this._currentPingPongState = readId;\n if (this._useRenderPasses) {\n this._engine.currentRenderPassId = this._renderPassIds[i + 1];\n }\n // Clears\n this._engine.bindFramebuffer(this._depthMrts[writeId].renderTarget);\n this._engine.bindAttachments(this._layoutCache[0]);\n this._engine.clear(this._colorCache[0], true, false, false);\n this._engine.unBindFramebuffer(this._depthMrts[writeId].renderTarget);\n this._engine.bindFramebuffer(this._colorMrts[writeId].renderTarget);\n this._engine.bindAttachments(this._layoutCache[1]);\n this._engine.clear(this._colorCache[2], true, false, false);\n this._engine.unBindFramebuffer(this._colorMrts[writeId].renderTarget);\n this._engine.bindFramebuffer(this._depthMrts[writeId].renderTarget);\n this._engine.bindAttachments(this._layoutCache[2]);\n this._engine.setAlphaMode(11); // the value does not matter (as MAX operation does not use them) but the src and dst color factors should not use SRC_ALPHA else WebGPU will throw a validation error\n this._engine.setAlphaEquation(3);\n this._engine.depthCullingState.depthTest = false;\n this._engine.applyStates();\n // Render\n this._renderSubMeshes(this._candidateSubMeshes);\n this._engine.unBindFramebuffer(this._depthMrts[writeId].renderTarget);\n this._scene.resetCachedMaterial();\n // Back color\n this._engine.bindFramebuffer(this._blendBackMrt.renderTarget);\n this._engine.bindAttachments(this._layoutCache[0]);\n this._engine.setAlphaEquation(0);\n this._engine.setAlphaMode(17);\n this._engine.applyStates();\n const blendBackEffectWrapper = writeId === 0 || !this._useRenderPasses ? this._blendBackEffectWrapper : this._blendBackEffectWrapperPingPong;\n this._engine.enableEffect(blendBackEffectWrapper._drawWrapper);\n blendBackEffectWrapper.effect.setTexture(\"uBackColor\", this._thinTextures[writeId * 3 + 2]);\n this._effectRenderer.render(blendBackEffectWrapper);\n this._engine.unBindFramebuffer(this._blendBackMrt.renderTarget);\n }\n this._engine.currentRenderPassId = currentRenderPassId;\n // Final composition on default FB\n this._finalCompose(writeId);\n this._scene.prePassRenderer._enabled = true;\n this._engine.depthCullingState.depthMask = true;\n this._engine.depthCullingState.depthTest = true;\n return this._excludedSubMeshes;\n }\n /**\n * Disposes the depth peeling renderer and associated ressources\n */\n dispose() {\n this._disposeTextures();\n this._blendBackEffectWrapper.dispose();\n this._finalEffectWrapper.dispose();\n this._effectRenderer.dispose();\n this._releaseRenderPassIds();\n }\n}\nDepthPeelingRenderer._DEPTH_CLEAR_VALUE = -99999.0;\nDepthPeelingRenderer._MIN_DEPTH = 0;\nDepthPeelingRenderer._MAX_DEPTH = 1;\n//# sourceMappingURL=depthPeelingRenderer.js.map","\nimport { Scene } from \"../scene.js\";\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { DepthPeelingRenderer } from \"./depthPeelingRenderer.js\";\nObject.defineProperty(Scene.prototype, \"depthPeelingRenderer\", {\n get: function () {\n if (!this._depthPeelingRenderer) {\n let component = this._getComponent(SceneComponentConstants.NAME_DEPTHPEELINGRENDERER);\n if (!component) {\n component = new DepthPeelingSceneComponent(this);\n this._addComponent(component);\n }\n }\n return this._depthPeelingRenderer;\n },\n set: function (value) {\n this._depthPeelingRenderer = value;\n },\n enumerable: true,\n configurable: true,\n});\nObject.defineProperty(Scene.prototype, \"useOrderIndependentTransparency\", {\n get: function () {\n return this._useOrderIndependentTransparency;\n },\n set: function (value) {\n var _a;\n if (this._useOrderIndependentTransparency === value) {\n return;\n }\n this._useOrderIndependentTransparency = value;\n this.markAllMaterialsAsDirty(63);\n (_a = this.prePassRenderer) === null || _a === void 0 ? void 0 : _a.markAsDirty();\n },\n enumerable: true,\n configurable: true,\n});\n/**\n * Scene component to render order independent transparency with depth peeling\n */\nexport class DepthPeelingSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpful to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_DEPTHPEELINGRENDERER;\n this.scene = scene;\n scene.depthPeelingRenderer = new DepthPeelingRenderer(scene);\n }\n /**\n * Registers the component in a given scene\n */\n register() { }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() { }\n /**\n * Disposes the component and the associated resources.\n */\n dispose() {\n var _a;\n (_a = this.scene.depthPeelingRenderer) === null || _a === void 0 ? void 0 : _a.dispose();\n this.scene.depthPeelingRenderer = null;\n }\n}\n//# sourceMappingURL=depthPeelingSceneComponent.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/clipPlaneFragmentDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneFragment.js\";\nconst name = \"linePixelShader\";\nconst shader = `#include\nuniform vec4 color;\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\ngl_FragColor=color;\r#define CUSTOM_FRAGMENT_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const linePixelShader = { name, shader };\n//# sourceMappingURL=line.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/instancesDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneVertexDeclaration.js\";\nimport \"./ShadersInclude/instancesVertex.js\";\nimport \"./ShadersInclude/clipPlaneVertex.js\";\nconst name = \"lineVertexShader\";\nconst shader = `#include\n#include\nattribute vec3 position;\rattribute vec4 normal;\runiform mat4 viewProjection;\runiform float width;\runiform float aspectRatio;\r#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\nmat4 worldViewProjection=viewProjection*finalWorld;\rvec4 viewPosition=worldViewProjection*vec4(position,1.0);\rvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\rvec2 currentScreen=viewPosition.xy/viewPosition.w;\rvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\rcurrentScreen.x*=aspectRatio;\rnextScreen.x*=aspectRatio;\rvec2 dir=normalize(nextScreen-currentScreen);\rvec2 normalDir=vec2(-dir.y,dir.x);\rnormalDir*=width/2.0;\rnormalDir.x/=aspectRatio;\rvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\rgl_Position=viewPosition+offset;\r#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nvec4 worldPos=finalWorld*vec4(position,1.0);\r#include\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const lineVertexShader = { name, shader };\n//# sourceMappingURL=line.vertex.js.map","import { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { AbstractMesh } from \"../Meshes/abstractMesh.js\";\nimport { LinesMesh, InstancedLinesMesh } from \"../Meshes/linesMesh.js\";\nimport { Vector3, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Material } from \"../Materials/material.js\";\nimport { ShaderMaterial } from \"../Materials/shaderMaterial.js\";\nimport { Camera } from \"../Cameras/camera.js\";\n\nimport \"../Shaders/line.fragment.js\";\nimport \"../Shaders/line.vertex.js\";\nimport { SmartArray } from \"../Misc/smartArray.js\";\nimport { DrawWrapper } from \"../Materials/drawWrapper.js\";\nAbstractMesh.prototype.disableEdgesRendering = function () {\n if (this._edgesRenderer) {\n this._edgesRenderer.dispose();\n this._edgesRenderer = null;\n }\n return this;\n};\nAbstractMesh.prototype.enableEdgesRendering = function (epsilon = 0.95, checkVerticesInsteadOfIndices = false, options) {\n this.disableEdgesRendering();\n this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices, true, options);\n return this;\n};\nObject.defineProperty(AbstractMesh.prototype, \"edgesRenderer\", {\n get: function () {\n return this._edgesRenderer;\n },\n enumerable: true,\n configurable: true,\n});\nLinesMesh.prototype.enableEdgesRendering = function (epsilon = 0.95, checkVerticesInsteadOfIndices = false) {\n this.disableEdgesRendering();\n this._edgesRenderer = new LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);\n return this;\n};\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nInstancedLinesMesh.prototype.enableEdgesRendering = function (epsilon = 0.95, checkVerticesInsteadOfIndices = false) {\n LinesMesh.prototype.enableEdgesRendering.apply(this, arguments);\n return this;\n};\n/**\n * FaceAdjacencies Helper class to generate edges\n */\nclass FaceAdjacencies {\n constructor() {\n this.edges = new Array();\n this.edgesConnectedCount = 0;\n }\n}\n/**\n * This class is used to generate edges of the mesh that could then easily be rendered in a scene.\n */\nexport class EdgesRenderer {\n /** Gets the vertices generated by the edge renderer */\n get linesPositions() {\n return this._linesPositions;\n }\n /** Gets the normals generated by the edge renderer */\n get linesNormals() {\n return this._linesNormals;\n }\n /** Gets the indices generated by the edge renderer */\n get linesIndices() {\n return this._linesIndices;\n }\n /**\n * Gets or sets the shader used to draw the lines\n */\n get lineShader() {\n return this._lineShader;\n }\n set lineShader(shader) {\n this._lineShader = shader;\n }\n static _GetShader(scene) {\n if (!scene._edgeRenderLineShader) {\n const shader = new ShaderMaterial(\"lineShader\", scene, \"line\", {\n attributes: [\"position\", \"normal\"],\n uniforms: [\"world\", \"viewProjection\", \"color\", \"width\", \"aspectRatio\"],\n }, false);\n shader.disableDepthWrite = true;\n shader.backFaceCulling = false;\n shader.checkReadyOnEveryCall = scene.getEngine().isWebGPU;\n scene._edgeRenderLineShader = shader;\n }\n return scene._edgeRenderLineShader;\n }\n /**\n * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.\n * Beware when you use this class with complex objects as the adjacencies computation can be really long\n * @param source Mesh used to create edges\n * @param epsilon sum of angles in adjacency to check for edge\n * @param checkVerticesInsteadOfIndices bases the edges detection on vertices vs indices. Note that this parameter is not used if options.useAlternateEdgeFinder = true\n * @param generateEdgesLines - should generate Lines or only prepare resources.\n * @param options The options to apply when generating the edges\n */\n constructor(source, epsilon = 0.95, checkVerticesInsteadOfIndices = false, generateEdgesLines = true, options) {\n var _a;\n /**\n * Define the size of the edges with an orthographic camera\n */\n this.edgesWidthScalerForOrthographic = 1000.0;\n /**\n * Define the size of the edges with a perspective camera\n */\n this.edgesWidthScalerForPerspective = 50.0;\n this._linesPositions = new Array();\n this._linesNormals = new Array();\n this._linesIndices = new Array();\n this._buffers = {};\n this._buffersForInstances = {};\n this._checkVerticesInsteadOfIndices = false;\n /** Gets or sets a boolean indicating if the edgesRenderer is active */\n this.isEnabled = true;\n /**\n * List of instances to render in case the source mesh has instances\n */\n this.customInstances = new SmartArray(32);\n this._source = source;\n this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;\n this._options = options !== null && options !== void 0 ? options : null;\n this._epsilon = epsilon;\n if (this._source.getScene().getEngine().isWebGPU) {\n this._drawWrapper = new DrawWrapper(source.getEngine());\n }\n this._prepareRessources();\n if (generateEdgesLines) {\n if ((_a = options === null || options === void 0 ? void 0 : options.useAlternateEdgeFinder) !== null && _a !== void 0 ? _a : true) {\n this._generateEdgesLinesAlternate();\n }\n else {\n this._generateEdgesLines();\n }\n }\n this._meshRebuildObserver = this._source.onRebuildObservable.add(() => {\n this._rebuild();\n });\n this._meshDisposeObserver = this._source.onDisposeObservable.add(() => {\n this.dispose();\n });\n }\n _prepareRessources() {\n if (this._lineShader) {\n return;\n }\n this._lineShader = EdgesRenderer._GetShader(this._source.getScene());\n }\n /** @internal */\n _rebuild() {\n let buffer = this._buffers[VertexBuffer.PositionKind];\n if (buffer) {\n buffer._rebuild();\n }\n buffer = this._buffers[VertexBuffer.NormalKind];\n if (buffer) {\n buffer._rebuild();\n }\n const scene = this._source.getScene();\n const engine = scene.getEngine();\n this._ib = engine.createIndexBuffer(this._linesIndices);\n }\n /**\n * Releases the required resources for the edges renderer\n */\n dispose() {\n var _a;\n this._source.onRebuildObservable.remove(this._meshRebuildObserver);\n this._source.onDisposeObservable.remove(this._meshDisposeObserver);\n let buffer = this._buffers[VertexBuffer.PositionKind];\n if (buffer) {\n buffer.dispose();\n this._buffers[VertexBuffer.PositionKind] = null;\n }\n buffer = this._buffers[VertexBuffer.NormalKind];\n if (buffer) {\n buffer.dispose();\n this._buffers[VertexBuffer.NormalKind] = null;\n }\n if (this._ib) {\n this._source.getScene().getEngine()._releaseBuffer(this._ib);\n }\n this._lineShader.dispose();\n (_a = this._drawWrapper) === null || _a === void 0 ? void 0 : _a.dispose();\n }\n _processEdgeForAdjacencies(pa, pb, p0, p1, p2) {\n if ((pa === p0 && pb === p1) || (pa === p1 && pb === p0)) {\n return 0;\n }\n if ((pa === p1 && pb === p2) || (pa === p2 && pb === p1)) {\n return 1;\n }\n if ((pa === p2 && pb === p0) || (pa === p0 && pb === p2)) {\n return 2;\n }\n return -1;\n }\n _processEdgeForAdjacenciesWithVertices(pa, pb, p0, p1, p2) {\n const eps = 1e-10;\n if ((pa.equalsWithEpsilon(p0, eps) && pb.equalsWithEpsilon(p1, eps)) || (pa.equalsWithEpsilon(p1, eps) && pb.equalsWithEpsilon(p0, eps))) {\n return 0;\n }\n if ((pa.equalsWithEpsilon(p1, eps) && pb.equalsWithEpsilon(p2, eps)) || (pa.equalsWithEpsilon(p2, eps) && pb.equalsWithEpsilon(p1, eps))) {\n return 1;\n }\n if ((pa.equalsWithEpsilon(p2, eps) && pb.equalsWithEpsilon(p0, eps)) || (pa.equalsWithEpsilon(p0, eps) && pb.equalsWithEpsilon(p2, eps))) {\n return 2;\n }\n return -1;\n }\n /**\n * Checks if the pair of p0 and p1 is en edge\n * @param faceIndex\n * @param edge\n * @param faceNormals\n * @param p0\n * @param p1\n * @private\n */\n _checkEdge(faceIndex, edge, faceNormals, p0, p1) {\n let needToCreateLine;\n if (edge === undefined) {\n needToCreateLine = true;\n }\n else {\n const dotProduct = Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);\n needToCreateLine = dotProduct < this._epsilon;\n }\n if (needToCreateLine) {\n this.createLine(p0, p1, this._linesPositions.length / 3);\n }\n }\n /**\n * push line into the position, normal and index buffer\n * @param p0\n * @param p1\n * @param offset\n * @protected\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n createLine(p0, p1, offset) {\n // Positions\n this._linesPositions.push(p0.x, p0.y, p0.z, p0.x, p0.y, p0.z, p1.x, p1.y, p1.z, p1.x, p1.y, p1.z);\n // Normals\n this._linesNormals.push(p1.x, p1.y, p1.z, -1, p1.x, p1.y, p1.z, 1, p0.x, p0.y, p0.z, -1, p0.x, p0.y, p0.z, 1);\n // Indices\n this._linesIndices.push(offset, offset + 1, offset + 2, offset, offset + 2, offset + 3);\n }\n /**\n * See https://playground.babylonjs.com/#R3JR6V#1 for a visual display of the algorithm\n * @param edgePoints\n * @param indexTriangle\n * @param indices\n * @param remapVertexIndices\n */\n _tessellateTriangle(edgePoints, indexTriangle, indices, remapVertexIndices) {\n const makePointList = (edgePoints, pointIndices, firstIndex) => {\n if (firstIndex >= 0) {\n pointIndices.push(firstIndex);\n }\n for (let i = 0; i < edgePoints.length; ++i) {\n pointIndices.push(edgePoints[i][0]);\n }\n };\n let startEdge = 0;\n if (edgePoints[1].length >= edgePoints[0].length && edgePoints[1].length >= edgePoints[2].length) {\n startEdge = 1;\n }\n else if (edgePoints[2].length >= edgePoints[0].length && edgePoints[2].length >= edgePoints[1].length) {\n startEdge = 2;\n }\n for (let e = 0; e < 3; ++e) {\n if (e === startEdge) {\n edgePoints[e].sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0));\n }\n else {\n edgePoints[e].sort((a, b) => (a[1] > b[1] ? -1 : a[1] < b[1] ? 1 : 0));\n }\n }\n const mainPointIndices = [], otherPointIndices = [];\n makePointList(edgePoints[startEdge], mainPointIndices, -1);\n const numMainPoints = mainPointIndices.length;\n for (let i = startEdge + 2; i >= startEdge + 1; --i) {\n makePointList(edgePoints[i % 3], otherPointIndices, i !== startEdge + 2 ? remapVertexIndices[indices[indexTriangle + ((i + 1) % 3)]] : -1);\n }\n const numOtherPoints = otherPointIndices.length;\n const idxMain = 0;\n const idxOther = 0;\n indices.push(remapVertexIndices[indices[indexTriangle + startEdge]], mainPointIndices[0], otherPointIndices[0]);\n indices.push(remapVertexIndices[indices[indexTriangle + ((startEdge + 1) % 3)]], otherPointIndices[numOtherPoints - 1], mainPointIndices[numMainPoints - 1]);\n const bucketIsMain = numMainPoints <= numOtherPoints;\n const bucketStep = bucketIsMain ? numMainPoints : numOtherPoints;\n const bucketLimit = bucketIsMain ? numOtherPoints : numMainPoints;\n const bucketIdxLimit = bucketIsMain ? numMainPoints - 1 : numOtherPoints - 1;\n const winding = bucketIsMain ? 0 : 1;\n let numTris = numMainPoints + numOtherPoints - 2;\n let bucketIdx = bucketIsMain ? idxMain : idxOther;\n let nbucketIdx = bucketIsMain ? idxOther : idxMain;\n const bucketPoints = bucketIsMain ? mainPointIndices : otherPointIndices;\n const nbucketPoints = bucketIsMain ? otherPointIndices : mainPointIndices;\n let bucket = 0;\n while (numTris-- > 0) {\n if (winding) {\n indices.push(bucketPoints[bucketIdx], nbucketPoints[nbucketIdx]);\n }\n else {\n indices.push(nbucketPoints[nbucketIdx], bucketPoints[bucketIdx]);\n }\n bucket += bucketStep;\n let lastIdx;\n if (bucket >= bucketLimit && bucketIdx < bucketIdxLimit) {\n lastIdx = bucketPoints[++bucketIdx];\n bucket -= bucketLimit;\n }\n else {\n lastIdx = nbucketPoints[++nbucketIdx];\n }\n indices.push(lastIdx);\n }\n indices[indexTriangle + 0] = indices[indices.length - 3];\n indices[indexTriangle + 1] = indices[indices.length - 2];\n indices[indexTriangle + 2] = indices[indices.length - 1];\n indices.length = indices.length - 3;\n }\n _generateEdgesLinesAlternate() {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;\n const positions = this._source.getVerticesData(VertexBuffer.PositionKind);\n let indices = this._source.getIndices();\n if (!indices || !positions) {\n return;\n }\n if (!Array.isArray(indices)) {\n indices = Array.from(indices);\n }\n /**\n * Find all vertices that are at the same location (with an epsilon) and remapp them on the same vertex\n */\n const useFastVertexMerger = (_b = (_a = this._options) === null || _a === void 0 ? void 0 : _a.useFastVertexMerger) !== null && _b !== void 0 ? _b : true;\n const epsVertexMerge = useFastVertexMerger ? Math.round(-Math.log((_d = (_c = this._options) === null || _c === void 0 ? void 0 : _c.epsilonVertexMerge) !== null && _d !== void 0 ? _d : 1e-6) / Math.log(10)) : (_f = (_e = this._options) === null || _e === void 0 ? void 0 : _e.epsilonVertexMerge) !== null && _f !== void 0 ? _f : 1e-6;\n const remapVertexIndices = [];\n const uniquePositions = []; // list of unique index of vertices - needed for tessellation\n if (useFastVertexMerger) {\n const mapVertices = {};\n for (let v1 = 0; v1 < positions.length; v1 += 3) {\n const x1 = positions[v1 + 0], y1 = positions[v1 + 1], z1 = positions[v1 + 2];\n const key = x1.toFixed(epsVertexMerge) + \"|\" + y1.toFixed(epsVertexMerge) + \"|\" + z1.toFixed(epsVertexMerge);\n if (mapVertices[key] !== undefined) {\n remapVertexIndices.push(mapVertices[key]);\n }\n else {\n const idx = v1 / 3;\n mapVertices[key] = idx;\n remapVertexIndices.push(idx);\n uniquePositions.push(idx);\n }\n }\n }\n else {\n for (let v1 = 0; v1 < positions.length; v1 += 3) {\n const x1 = positions[v1 + 0], y1 = positions[v1 + 1], z1 = positions[v1 + 2];\n let found = false;\n for (let v2 = 0; v2 < v1 && !found; v2 += 3) {\n const x2 = positions[v2 + 0], y2 = positions[v2 + 1], z2 = positions[v2 + 2];\n if (Math.abs(x1 - x2) < epsVertexMerge && Math.abs(y1 - y2) < epsVertexMerge && Math.abs(z1 - z2) < epsVertexMerge) {\n remapVertexIndices.push(v2 / 3);\n found = true;\n break;\n }\n }\n if (!found) {\n remapVertexIndices.push(v1 / 3);\n uniquePositions.push(v1 / 3);\n }\n }\n }\n if ((_g = this._options) === null || _g === void 0 ? void 0 : _g.applyTessellation) {\n /**\n * Tessellate triangles if necessary:\n *\n * A\n * +\n * |\\\n * | \\\n * | \\\n * E + \\\n * /| \\\n * / | \\\n * / | \\\n * +---+-------+ B\n * D C\n *\n * For the edges to be rendered correctly, the ABC triangle has to be split into ABE and BCE, else AC is considered to be an edge, whereas only AE should be.\n *\n * The tessellation process looks for the vertices like E that are in-between two other vertices making of an edge and create new triangles as necessary\n */\n // First step: collect the triangles to tessellate\n const epsVertexAligned = (_j = (_h = this._options) === null || _h === void 0 ? void 0 : _h.epsilonVertexAligned) !== null && _j !== void 0 ? _j : 1e-6;\n const mustTesselate = []; // liste of triangles that must be tessellated\n for (let index = 0; index < indices.length; index += 3) {\n // loop over all triangles\n let triangleToTessellate;\n for (let i = 0; i < 3; ++i) {\n // loop over the 3 edges of the triangle\n const p0Index = remapVertexIndices[indices[index + i]];\n const p1Index = remapVertexIndices[indices[index + ((i + 1) % 3)]];\n const p2Index = remapVertexIndices[indices[index + ((i + 2) % 3)]];\n if (p0Index === p1Index) {\n continue;\n } // degenerated triangle - don't process\n const p0x = positions[p0Index * 3 + 0], p0y = positions[p0Index * 3 + 1], p0z = positions[p0Index * 3 + 2];\n const p1x = positions[p1Index * 3 + 0], p1y = positions[p1Index * 3 + 1], p1z = positions[p1Index * 3 + 2];\n const p0p1 = Math.sqrt((p1x - p0x) * (p1x - p0x) + (p1y - p0y) * (p1y - p0y) + (p1z - p0z) * (p1z - p0z));\n for (let v = 0; v < uniquePositions.length - 1; v++) {\n // loop over all (unique) vertices and look for the ones that would be in-between p0 and p1\n const vIndex = uniquePositions[v];\n if (vIndex === p0Index || vIndex === p1Index || vIndex === p2Index) {\n continue;\n } // don't handle the vertex if it is a vertex of the current triangle\n const x = positions[vIndex * 3 + 0], y = positions[vIndex * 3 + 1], z = positions[vIndex * 3 + 2];\n const p0p = Math.sqrt((x - p0x) * (x - p0x) + (y - p0y) * (y - p0y) + (z - p0z) * (z - p0z));\n const pp1 = Math.sqrt((x - p1x) * (x - p1x) + (y - p1y) * (y - p1y) + (z - p1z) * (z - p1z));\n if (Math.abs(p0p + pp1 - p0p1) < epsVertexAligned) {\n // vertices are aligned and p in-between p0 and p1 if distance(p0, p) + distance (p, p1) ~ distance(p0, p1)\n if (!triangleToTessellate) {\n triangleToTessellate = {\n index: index,\n edgesPoints: [[], [], []],\n };\n mustTesselate.push(triangleToTessellate);\n }\n triangleToTessellate.edgesPoints[i].push([vIndex, p0p]);\n }\n }\n }\n }\n // Second step: tesselate the triangles\n for (let t = 0; t < mustTesselate.length; ++t) {\n const triangle = mustTesselate[t];\n this._tessellateTriangle(triangle.edgesPoints, triangle.index, indices, remapVertexIndices);\n }\n mustTesselate.length = 0;\n }\n /**\n * Collect the edges to render\n */\n const edges = {};\n for (let index = 0; index < indices.length; index += 3) {\n let faceNormal;\n for (let i = 0; i < 3; ++i) {\n let p0Index = remapVertexIndices[indices[index + i]];\n let p1Index = remapVertexIndices[indices[index + ((i + 1) % 3)]];\n const p2Index = remapVertexIndices[indices[index + ((i + 2) % 3)]];\n if (p0Index === p1Index || ((p0Index === p2Index || p1Index === p2Index) && ((_k = this._options) === null || _k === void 0 ? void 0 : _k.removeDegeneratedTriangles))) {\n continue;\n }\n TmpVectors.Vector3[0].copyFromFloats(positions[p0Index * 3 + 0], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);\n TmpVectors.Vector3[1].copyFromFloats(positions[p1Index * 3 + 0], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);\n TmpVectors.Vector3[2].copyFromFloats(positions[p2Index * 3 + 0], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);\n if (!faceNormal) {\n TmpVectors.Vector3[1].subtractToRef(TmpVectors.Vector3[0], TmpVectors.Vector3[3]);\n TmpVectors.Vector3[2].subtractToRef(TmpVectors.Vector3[1], TmpVectors.Vector3[4]);\n faceNormal = Vector3.Cross(TmpVectors.Vector3[3], TmpVectors.Vector3[4]);\n faceNormal.normalize();\n }\n if (p0Index > p1Index) {\n const tmp = p0Index;\n p0Index = p1Index;\n p1Index = tmp;\n }\n const key = p0Index + \"_\" + p1Index;\n const ei = edges[key];\n if (ei) {\n if (!ei.done) {\n const dotProduct = Vector3.Dot(faceNormal, ei.normal);\n if (dotProduct < this._epsilon) {\n this.createLine(TmpVectors.Vector3[0], TmpVectors.Vector3[1], this._linesPositions.length / 3);\n }\n ei.done = true;\n }\n }\n else {\n edges[key] = { normal: faceNormal, done: false, index: index, i: i };\n }\n }\n }\n for (const key in edges) {\n const ei = edges[key];\n if (!ei.done) {\n // Orphaned edge - we must display it\n const p0Index = remapVertexIndices[indices[ei.index + ei.i]];\n const p1Index = remapVertexIndices[indices[ei.index + ((ei.i + 1) % 3)]];\n TmpVectors.Vector3[0].copyFromFloats(positions[p0Index * 3 + 0], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);\n TmpVectors.Vector3[1].copyFromFloats(positions[p1Index * 3 + 0], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);\n this.createLine(TmpVectors.Vector3[0], TmpVectors.Vector3[1], this._linesPositions.length / 3);\n }\n }\n /**\n * Merge into a single mesh\n */\n const engine = this._source.getScene().getEngine();\n this._buffers[VertexBuffer.PositionKind] = new VertexBuffer(engine, this._linesPositions, VertexBuffer.PositionKind, false);\n this._buffers[VertexBuffer.NormalKind] = new VertexBuffer(engine, this._linesNormals, VertexBuffer.NormalKind, false, false, 4);\n this._buffersForInstances[VertexBuffer.PositionKind] = this._buffers[VertexBuffer.PositionKind];\n this._buffersForInstances[VertexBuffer.NormalKind] = this._buffers[VertexBuffer.NormalKind];\n this._ib = engine.createIndexBuffer(this._linesIndices);\n this._indicesCount = this._linesIndices.length;\n }\n /**\n * Generates lines edges from adjacencjes\n * @private\n */\n _generateEdgesLines() {\n const positions = this._source.getVerticesData(VertexBuffer.PositionKind);\n const indices = this._source.getIndices();\n if (!indices || !positions) {\n return;\n }\n // First let's find adjacencies\n const adjacencies = new Array();\n const faceNormals = new Array();\n let index;\n let faceAdjacencies;\n // Prepare faces\n for (index = 0; index < indices.length; index += 3) {\n faceAdjacencies = new FaceAdjacencies();\n const p0Index = indices[index];\n const p1Index = indices[index + 1];\n const p2Index = indices[index + 2];\n faceAdjacencies.p0 = new Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);\n faceAdjacencies.p1 = new Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);\n faceAdjacencies.p2 = new Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);\n const faceNormal = Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));\n faceNormal.normalize();\n faceNormals.push(faceNormal);\n adjacencies.push(faceAdjacencies);\n }\n // Scan\n for (index = 0; index < adjacencies.length; index++) {\n faceAdjacencies = adjacencies[index];\n for (let otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {\n const otherFaceAdjacencies = adjacencies[otherIndex];\n if (faceAdjacencies.edgesConnectedCount === 3) {\n // Full\n break;\n }\n if (otherFaceAdjacencies.edgesConnectedCount === 3) {\n // Full\n continue;\n }\n const otherP0 = indices[otherIndex * 3];\n const otherP1 = indices[otherIndex * 3 + 1];\n const otherP2 = indices[otherIndex * 3 + 2];\n for (let edgeIndex = 0; edgeIndex < 3; edgeIndex++) {\n let otherEdgeIndex = 0;\n if (faceAdjacencies.edges[edgeIndex] !== undefined) {\n continue;\n }\n switch (edgeIndex) {\n case 0:\n if (this._checkVerticesInsteadOfIndices) {\n otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);\n }\n else {\n otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);\n }\n break;\n case 1:\n if (this._checkVerticesInsteadOfIndices) {\n otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);\n }\n else {\n otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);\n }\n break;\n case 2:\n if (this._checkVerticesInsteadOfIndices) {\n otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);\n }\n else {\n otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);\n }\n break;\n }\n if (otherEdgeIndex === -1) {\n continue;\n }\n faceAdjacencies.edges[edgeIndex] = otherIndex;\n otherFaceAdjacencies.edges[otherEdgeIndex] = index;\n faceAdjacencies.edgesConnectedCount++;\n otherFaceAdjacencies.edgesConnectedCount++;\n if (faceAdjacencies.edgesConnectedCount === 3) {\n break;\n }\n }\n }\n }\n // Create lines\n for (index = 0; index < adjacencies.length; index++) {\n // We need a line when a face has no adjacency on a specific edge or if all the adjacencies has an angle greater than epsilon\n const current = adjacencies[index];\n this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);\n this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);\n this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);\n }\n // Merge into a single mesh\n const engine = this._source.getScene().getEngine();\n this._buffers[VertexBuffer.PositionKind] = new VertexBuffer(engine, this._linesPositions, VertexBuffer.PositionKind, false);\n this._buffers[VertexBuffer.NormalKind] = new VertexBuffer(engine, this._linesNormals, VertexBuffer.NormalKind, false, false, 4);\n this._buffersForInstances[VertexBuffer.PositionKind] = this._buffers[VertexBuffer.PositionKind];\n this._buffersForInstances[VertexBuffer.NormalKind] = this._buffers[VertexBuffer.NormalKind];\n this._ib = engine.createIndexBuffer(this._linesIndices);\n this._indicesCount = this._linesIndices.length;\n }\n /**\n * Checks whether or not the edges renderer is ready to render.\n * @returns true if ready, otherwise false.\n */\n isReady() {\n return this._lineShader.isReady(this._source, (this._source.hasInstances && this.customInstances.length > 0) || this._source.hasThinInstances);\n }\n /**\n * Renders the edges of the attached mesh,\n */\n render() {\n const scene = this._source.getScene();\n const currentDrawWrapper = this._lineShader._getDrawWrapper();\n if (this._drawWrapper) {\n this._lineShader._setDrawWrapper(this._drawWrapper);\n }\n if (!this.isReady() || !scene.activeCamera) {\n this._lineShader._setDrawWrapper(currentDrawWrapper);\n return;\n }\n const hasInstances = this._source.hasInstances && this.customInstances.length > 0;\n const useBuffersWithInstances = hasInstances || this._source.hasThinInstances;\n let instanceCount = 0;\n if (useBuffersWithInstances) {\n this._buffersForInstances[\"world0\"] = this._source.getVertexBuffer(\"world0\");\n this._buffersForInstances[\"world1\"] = this._source.getVertexBuffer(\"world1\");\n this._buffersForInstances[\"world2\"] = this._source.getVertexBuffer(\"world2\");\n this._buffersForInstances[\"world3\"] = this._source.getVertexBuffer(\"world3\");\n if (hasInstances) {\n const instanceStorage = this._source._instanceDataStorage;\n instanceCount = this.customInstances.length;\n if (!instanceStorage.instancesData) {\n if (!this._source.getScene()._activeMeshesFrozen) {\n this.customInstances.reset();\n }\n return;\n }\n if (!instanceStorage.isFrozen) {\n let offset = 0;\n for (let i = 0; i < instanceCount; ++i) {\n this.customInstances.data[i].copyToArray(instanceStorage.instancesData, offset);\n offset += 16;\n }\n instanceStorage.instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instanceCount);\n }\n }\n else {\n instanceCount = this._source.thinInstanceCount;\n }\n }\n const engine = scene.getEngine();\n this._lineShader._preBind();\n if (this._source.edgesColor.a !== 1) {\n engine.setAlphaMode(2);\n }\n else {\n engine.setAlphaMode(0);\n }\n // VBOs\n engine.bindBuffers(useBuffersWithInstances ? this._buffersForInstances : this._buffers, this._ib, this._lineShader.getEffect());\n scene.resetCachedMaterial();\n this._lineShader.setColor4(\"color\", this._source.edgesColor);\n if (scene.activeCamera.mode === Camera.ORTHOGRAPHIC_CAMERA) {\n this._lineShader.setFloat(\"width\", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);\n }\n else {\n this._lineShader.setFloat(\"width\", this._source.edgesWidth / this.edgesWidthScalerForPerspective);\n }\n this._lineShader.setFloat(\"aspectRatio\", engine.getAspectRatio(scene.activeCamera));\n this._lineShader.bind(this._source.getWorldMatrix());\n // Draw order\n engine.drawElementsType(Material.TriangleFillMode, 0, this._indicesCount, instanceCount);\n this._lineShader.unbind();\n if (useBuffersWithInstances) {\n engine.unbindInstanceAttributes();\n }\n if (!this._source.getScene()._activeMeshesFrozen) {\n this.customInstances.reset();\n }\n this._lineShader._setDrawWrapper(currentDrawWrapper);\n }\n}\n/**\n * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation\n */\nexport class LineEdgesRenderer extends EdgesRenderer {\n /**\n * This constructor turns off auto generating edges line in Edges Renderer to make it here.\n * @param source LineMesh used to generate edges\n * @param epsilon not important (specified angle for edge detection)\n * @param checkVerticesInsteadOfIndices not important for LineMesh\n */\n constructor(source, epsilon = 0.95, checkVerticesInsteadOfIndices = false) {\n super(source, epsilon, checkVerticesInsteadOfIndices, false);\n this._generateEdgesLines();\n }\n /**\n * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.\n */\n _generateEdgesLines() {\n const positions = this._source.getVerticesData(VertexBuffer.PositionKind);\n const indices = this._source.getIndices();\n if (!indices || !positions) {\n return;\n }\n const p0 = TmpVectors.Vector3[0];\n const p1 = TmpVectors.Vector3[1];\n const len = indices.length - 1;\n for (let i = 0, offset = 0; i < len; i += 2, offset += 4) {\n Vector3.FromArrayToRef(positions, 3 * indices[i], p0);\n Vector3.FromArrayToRef(positions, 3 * indices[i + 1], p1);\n this.createLine(p0, p1, offset);\n }\n // Merge into a single mesh\n const engine = this._source.getScene().getEngine();\n this._buffers[VertexBuffer.PositionKind] = new VertexBuffer(engine, this._linesPositions, VertexBuffer.PositionKind, false);\n this._buffers[VertexBuffer.NormalKind] = new VertexBuffer(engine, this._linesNormals, VertexBuffer.NormalKind, false, false, 4);\n this._ib = engine.createIndexBuffer(this._linesIndices);\n this._indicesCount = this._linesIndices.length;\n }\n}\n//# sourceMappingURL=edgesRenderer.js.map","import { PrePassRenderTarget } from \"../Materials/Textures/prePassRenderTarget.js\";\n\nimport { _WarnImport } from \"../Misc/devTools.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { Material } from \"../Materials/material.js\";\nimport { GeometryBufferRenderer } from \"../Rendering/geometryBufferRenderer.js\";\n/**\n * Renders a pre pass of the scene\n * This means every mesh in the scene will be rendered to a render target texture\n * And then this texture will be composited to the rendering canvas with post processes\n * It is necessary for effects like subsurface scattering or deferred shading\n */\nexport class PrePassRenderer {\n /**\n * Returns the index of a texture in the multi render target texture array.\n * @param type Texture type\n * @returns The index\n */\n getIndex(type) {\n return this._textureIndices[type];\n }\n /**\n * How many samples are used for MSAA of the scene render target\n */\n get samples() {\n return this.defaultRT.samples;\n }\n set samples(n) {\n this.defaultRT.samples = n;\n }\n /**\n * If set to true (default: false), the depth texture will be cleared with the depth value corresponding to the far plane (1 in normal mode, 0 in reverse depth buffer mode)\n * If set to false, the depth texture is always cleared with 0.\n */\n get useSpecificClearForDepthTexture() {\n return this._useSpecificClearForDepthTexture;\n }\n set useSpecificClearForDepthTexture(value) {\n if (this._useSpecificClearForDepthTexture === value) {\n return;\n }\n this._useSpecificClearForDepthTexture = value;\n this._isDirty = true;\n }\n /**\n * @returns the prepass render target for the rendering pass.\n * If we are currently rendering a render target, it returns the PrePassRenderTarget\n * associated with that render target. Otherwise, it returns the scene default PrePassRenderTarget\n */\n getRenderTarget() {\n return this._currentTarget;\n }\n /**\n * @internal\n * Managed by the scene component\n * @param prePassRenderTarget\n */\n _setRenderTarget(prePassRenderTarget) {\n var _a, _b;\n if (prePassRenderTarget) {\n this._currentTarget = prePassRenderTarget;\n }\n else {\n this._currentTarget = this.defaultRT;\n this._engine.currentRenderPassId = (_b = (_a = this._scene.activeCamera) === null || _a === void 0 ? void 0 : _a.renderPassId) !== null && _b !== void 0 ? _b : this._currentTarget.renderPassId;\n }\n }\n /**\n * Returns true if the currently rendered prePassRenderTarget is the one\n * associated with the scene.\n */\n get currentRTisSceneRT() {\n return this._currentTarget === this.defaultRT;\n }\n _refreshGeometryBufferRendererLink() {\n if (!this.doNotUseGeometryRendererFallback) {\n this._geometryBuffer = this._scene.enableGeometryBufferRenderer();\n if (!this._geometryBuffer) {\n // Not supported\n this.doNotUseGeometryRendererFallback = true;\n return;\n }\n this._geometryBuffer._linkPrePassRenderer(this);\n }\n else {\n if (this._geometryBuffer) {\n this._geometryBuffer._unlinkPrePassRenderer();\n }\n this._geometryBuffer = null;\n this._scene.disableGeometryBufferRenderer();\n }\n }\n /**\n * Indicates if the prepass is enabled\n */\n get enabled() {\n return this._enabled;\n }\n /**\n * Instantiates a prepass renderer\n * @param scene The scene\n */\n constructor(scene) {\n /**\n * To save performance, we can excluded skinned meshes from the prepass\n */\n this.excludedSkinnedMesh = [];\n /**\n * Force material to be excluded from the prepass\n * Can be useful when `useGeometryBufferFallback` is set to `true`\n * and you don't want a material to show in the effect.\n */\n this.excludedMaterials = [];\n /**\n * Number of textures in the multi render target texture where the scene is directly rendered\n */\n this.mrtCount = 0;\n this._mrtTypes = [];\n this._mrtFormats = [];\n this._mrtLayout = [];\n this._mrtNames = [];\n this._textureIndices = [];\n this._useSpecificClearForDepthTexture = false;\n this._isDirty = true;\n /**\n * Configuration for prepass effects\n */\n this._effectConfigurations = [];\n /**\n * Prevents the PrePassRenderer from using the GeometryBufferRenderer as a fallback\n */\n this.doNotUseGeometryRendererFallback = true;\n /**\n * All the render targets generated by prepass\n */\n this.renderTargets = [];\n this._clearColor = new Color4(0, 0, 0, 0);\n this._clearDepthColor = new Color4(1e8, 0, 0, 1); // \"infinity\" value - depth in the depth texture is view.z, not a 0..1 value!\n this._enabled = false;\n this._needsCompositionForThisPass = false;\n /**\n * Set to true to disable gamma transform in PrePass.\n * Can be useful in case you already proceed to gamma transform on a material level\n * and your post processes don't need to be in linear color space.\n */\n this.disableGammaTransform = false;\n this._scene = scene;\n this._engine = scene.getEngine();\n let type = 0;\n if (this._engine._caps.textureFloat && this._engine._caps.textureFloatLinearFiltering) {\n type = 1;\n }\n else if (this._engine._caps.textureHalfFloat && this._engine._caps.textureHalfFloatLinearFiltering) {\n type = 2;\n }\n if (type !== 1) {\n for (let i = 0; i < PrePassRenderer.TextureFormats.length; ++i) {\n if (PrePassRenderer.TextureFormats[i].type === 1) {\n PrePassRenderer.TextureFormats[5].type = type;\n }\n }\n }\n PrePassRenderer._SceneComponentInitialization(this._scene);\n this.defaultRT = this._createRenderTarget(\"sceneprePassRT\", null);\n this._currentTarget = this.defaultRT;\n }\n /**\n * Creates a new PrePassRenderTarget\n * This should be the only way to instantiate a `PrePassRenderTarget`\n * @param name Name of the `PrePassRenderTarget`\n * @param renderTargetTexture RenderTarget the `PrePassRenderTarget` will be attached to.\n * Can be `null` if the created `PrePassRenderTarget` is attached to the scene (default framebuffer).\n * @internal\n */\n _createRenderTarget(name, renderTargetTexture) {\n const rt = new PrePassRenderTarget(name, renderTargetTexture, { width: this._engine.getRenderWidth(), height: this._engine.getRenderHeight() }, 0, this._scene, {\n generateMipMaps: false,\n generateStencilBuffer: this._engine.isStencilEnable,\n defaultType: 0,\n types: [],\n drawOnlyOnFirstAttachmentByDefault: true,\n });\n this.renderTargets.push(rt);\n if (this._enabled) {\n // The pre-pass renderer is already enabled, so make sure we create the render target with the correct number of textures\n this._update();\n }\n return rt;\n }\n /**\n * Indicates if rendering a prepass is supported\n */\n get isSupported() {\n return this._scene.getEngine().getCaps().drawBuffersExtension;\n }\n /**\n * Sets the proper output textures to draw in the engine.\n * @param effect The effect that is drawn. It can be or not be compatible with drawing to several output textures.\n * @param subMesh Submesh on which the effect is applied\n */\n bindAttachmentsForEffect(effect, subMesh) {\n const material = subMesh.getMaterial();\n const isPrePassCapable = material && material.isPrePassCapable;\n const excluded = material && this.excludedMaterials.indexOf(material) !== -1;\n if (this.enabled && this._currentTarget.enabled) {\n if (effect._multiTarget && isPrePassCapable && !excluded) {\n this._engine.bindAttachments(this._multiRenderAttachments);\n }\n else {\n if (this._engine._currentRenderTarget) {\n this._engine.bindAttachments(this._defaultAttachments);\n }\n else {\n this._engine.restoreSingleAttachment();\n }\n if (this._geometryBuffer && this.currentRTisSceneRT && !excluded) {\n this._geometryBuffer.renderList.push(subMesh.getRenderingMesh());\n }\n }\n }\n }\n _reinitializeAttachments() {\n const multiRenderLayout = [];\n const clearLayout = [false];\n const clearDepthLayout = [false];\n const defaultLayout = [true];\n for (let i = 0; i < this.mrtCount; i++) {\n multiRenderLayout.push(true);\n if (i > 0) {\n if (this._useSpecificClearForDepthTexture && this._mrtLayout[i] === 5) {\n clearLayout.push(false);\n clearDepthLayout.push(true);\n }\n else {\n clearLayout.push(true);\n clearDepthLayout.push(false);\n }\n defaultLayout.push(false);\n }\n }\n this._multiRenderAttachments = this._engine.buildTextureLayout(multiRenderLayout);\n this._clearAttachments = this._engine.buildTextureLayout(clearLayout);\n this._clearDepthAttachments = this._engine.buildTextureLayout(clearDepthLayout);\n this._defaultAttachments = this._engine.buildTextureLayout(defaultLayout);\n }\n _resetLayout() {\n for (let i = 0; i < PrePassRenderer.TextureFormats.length; i++) {\n this._textureIndices[PrePassRenderer.TextureFormats[i].purpose] = -1;\n }\n this._textureIndices[4] = 0;\n this._mrtLayout = [4];\n this._mrtTypes = [PrePassRenderer.TextureFormats[4].type];\n this._mrtFormats = [PrePassRenderer.TextureFormats[4].format];\n this._mrtNames = [PrePassRenderer.TextureFormats[4].name];\n this.mrtCount = 1;\n }\n _updateGeometryBufferLayout() {\n this._refreshGeometryBufferRendererLink();\n if (this._geometryBuffer) {\n this._geometryBuffer._resetLayout();\n const texturesActivated = [];\n for (let i = 0; i < this._mrtLayout.length; i++) {\n texturesActivated.push(false);\n }\n this._geometryBuffer._linkInternalTexture(this.defaultRT.getInternalTexture());\n const matches = [\n {\n prePassConstant: 5,\n geometryBufferConstant: GeometryBufferRenderer.DEPTH_TEXTURE_TYPE,\n },\n {\n prePassConstant: 6,\n geometryBufferConstant: GeometryBufferRenderer.NORMAL_TEXTURE_TYPE,\n },\n {\n prePassConstant: 1,\n geometryBufferConstant: GeometryBufferRenderer.POSITION_TEXTURE_TYPE,\n },\n {\n prePassConstant: 3,\n geometryBufferConstant: GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE,\n },\n {\n prePassConstant: 2,\n geometryBufferConstant: GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE,\n },\n ];\n // replace textures in the geometryBuffer RT\n for (let i = 0; i < matches.length; i++) {\n const index = this._mrtLayout.indexOf(matches[i].prePassConstant);\n if (index !== -1) {\n this._geometryBuffer._forceTextureType(matches[i].geometryBufferConstant, index);\n texturesActivated[index] = true;\n }\n }\n this._geometryBuffer._setAttachments(this._engine.buildTextureLayout(texturesActivated));\n }\n }\n /**\n * Restores attachments for single texture draw.\n */\n restoreAttachments() {\n if (this.enabled && this._currentTarget.enabled && this._defaultAttachments) {\n if (this._engine._currentRenderTarget) {\n this._engine.bindAttachments(this._defaultAttachments);\n }\n else {\n this._engine.restoreSingleAttachment();\n }\n }\n }\n /**\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _beforeDraw(camera, faceIndex, layer) {\n // const previousEnabled = this._enabled && this._currentTarget.enabled;\n if (this._isDirty) {\n this._update();\n }\n if (!this._enabled || !this._currentTarget.enabled) {\n return;\n }\n if (this._geometryBuffer) {\n this._geometryBuffer.renderList = [];\n }\n this._setupOutputForThisPass(this._currentTarget, camera);\n }\n _prepareFrame(prePassRenderTarget, faceIndex, layer) {\n if (prePassRenderTarget.renderTargetTexture) {\n prePassRenderTarget.renderTargetTexture._prepareFrame(this._scene, faceIndex, layer, prePassRenderTarget.renderTargetTexture.useCameraPostProcesses);\n }\n else if (this._postProcessesSourceForThisPass.length) {\n this._scene.postProcessManager._prepareFrame();\n }\n else {\n this._engine.restoreDefaultFramebuffer();\n }\n }\n /**\n * Sets an intermediary texture between prepass and postprocesses. This texture\n * will be used as input for post processes\n * @param rt\n * @returns true if there are postprocesses that will use this texture,\n * false if there is no postprocesses - and the function has no effect\n */\n setCustomOutput(rt) {\n const firstPP = this._postProcessesSourceForThisPass[0];\n if (!firstPP) {\n return false;\n }\n firstPP.inputTexture = rt.renderTarget;\n return true;\n }\n _renderPostProcesses(prePassRenderTarget, faceIndex) {\n var _a;\n const firstPP = this._postProcessesSourceForThisPass[0];\n const outputTexture = firstPP ? firstPP.inputTexture : prePassRenderTarget.renderTargetTexture ? prePassRenderTarget.renderTargetTexture.renderTarget : null;\n // Build post process chain for this prepass post draw\n let postProcessChain = this._currentTarget._beforeCompositionPostProcesses;\n if (this._needsCompositionForThisPass) {\n postProcessChain = postProcessChain.concat([this._currentTarget.imageProcessingPostProcess]);\n }\n // Activates and renders the chain\n if (postProcessChain.length) {\n this._scene.postProcessManager._prepareFrame((_a = this._currentTarget.renderTarget) === null || _a === void 0 ? void 0 : _a.texture, postProcessChain);\n this._scene.postProcessManager.directRender(postProcessChain, outputTexture, false, faceIndex);\n }\n }\n /**\n * @internal\n */\n _afterDraw(faceIndex, layer) {\n if (this._enabled && this._currentTarget.enabled) {\n this._prepareFrame(this._currentTarget, faceIndex, layer);\n this._renderPostProcesses(this._currentTarget, faceIndex);\n }\n }\n /**\n * Clears the current prepass render target (in the sense of settings pixels to the scene clear color value)\n * @internal\n */\n _clear() {\n if (this._enabled && this._currentTarget.enabled) {\n this._bindFrameBuffer(this._currentTarget);\n // Clearing other attachment with 0 on all other attachments\n this._engine.bindAttachments(this._clearAttachments);\n this._engine.clear(this._clearColor, true, false, false);\n if (this._useSpecificClearForDepthTexture) {\n this._engine.bindAttachments(this._clearDepthAttachments);\n this._engine.clear(this._clearDepthColor, true, false, false);\n }\n // Regular clear color with the scene clear color of the 1st attachment\n this._engine.bindAttachments(this._defaultAttachments);\n }\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _bindFrameBuffer(prePassRenderTarget) {\n if (this._enabled && this._currentTarget.enabled) {\n this._currentTarget._checkSize();\n const internalTexture = this._currentTarget.renderTarget;\n if (internalTexture) {\n this._engine.bindFramebuffer(internalTexture);\n }\n }\n }\n _setEnabled(enabled) {\n this._enabled = enabled;\n }\n _setRenderTargetEnabled(prePassRenderTarget, enabled) {\n prePassRenderTarget.enabled = enabled;\n if (!enabled) {\n this._unlinkInternalTexture(prePassRenderTarget);\n }\n }\n /**\n * Adds an effect configuration to the prepass render target.\n * If an effect has already been added, it won't add it twice and will return the configuration\n * already present.\n * @param cfg the effect configuration\n * @returns the effect configuration now used by the prepass\n */\n addEffectConfiguration(cfg) {\n // Do not add twice\n for (let i = 0; i < this._effectConfigurations.length; i++) {\n if (this._effectConfigurations[i].name === cfg.name) {\n return this._effectConfigurations[i];\n }\n }\n this._effectConfigurations.push(cfg);\n return cfg;\n }\n _enable() {\n const previousMrtCount = this.mrtCount;\n for (let i = 0; i < this._effectConfigurations.length; i++) {\n if (this._effectConfigurations[i].enabled) {\n this._enableTextures(this._effectConfigurations[i].texturesRequired);\n }\n }\n for (let i = 0; i < this.renderTargets.length; i++) {\n if (this.mrtCount !== previousMrtCount || this.renderTargets[i].count !== this.mrtCount) {\n this.renderTargets[i].updateCount(this.mrtCount, { types: this._mrtTypes, formats: this._mrtFormats }, this._mrtNames.concat(\"prePass_DepthBuffer\"));\n }\n this.renderTargets[i]._resetPostProcessChain();\n for (let j = 0; j < this._effectConfigurations.length; j++) {\n if (this._effectConfigurations[j].enabled) {\n // TODO : subsurface scattering has 1 scene-wide effect configuration\n // solution : do not stock postProcess on effectConfiguration, but in the prepassRenderTarget (hashmap configuration => postProcess)\n // And call createPostProcess whenever the post process does not exist in the RT\n if (!this._effectConfigurations[j].postProcess && this._effectConfigurations[j].createPostProcess) {\n this._effectConfigurations[j].createPostProcess();\n }\n if (this._effectConfigurations[j].postProcess) {\n this.renderTargets[i]._beforeCompositionPostProcesses.push(this._effectConfigurations[j].postProcess);\n }\n }\n }\n }\n this._reinitializeAttachments();\n this._setEnabled(true);\n this._updateGeometryBufferLayout();\n }\n _disable() {\n this._setEnabled(false);\n for (let i = 0; i < this.renderTargets.length; i++) {\n this._setRenderTargetEnabled(this.renderTargets[i], false);\n }\n this._resetLayout();\n for (let i = 0; i < this._effectConfigurations.length; i++) {\n this._effectConfigurations[i].enabled = false;\n }\n }\n _getPostProcessesSource(prePassRenderTarget, camera) {\n if (camera) {\n return camera._postProcesses;\n }\n else if (prePassRenderTarget.renderTargetTexture) {\n if (prePassRenderTarget.renderTargetTexture.useCameraPostProcesses) {\n const camera = prePassRenderTarget.renderTargetTexture.activeCamera ? prePassRenderTarget.renderTargetTexture.activeCamera : this._scene.activeCamera;\n return camera ? camera._postProcesses : [];\n }\n else if (prePassRenderTarget.renderTargetTexture.postProcesses) {\n return prePassRenderTarget.renderTargetTexture.postProcesses;\n }\n else {\n return [];\n }\n }\n else {\n return this._scene.activeCamera ? this._scene.activeCamera._postProcesses : [];\n }\n }\n _setupOutputForThisPass(prePassRenderTarget, camera) {\n // Order is : draw ===> prePassRenderTarget._postProcesses ==> ipp ==> camera._postProcesses\n const secondaryCamera = camera && this._scene.activeCameras && !!this._scene.activeCameras.length && this._scene.activeCameras.indexOf(camera) !== 0;\n this._postProcessesSourceForThisPass = this._getPostProcessesSource(prePassRenderTarget, camera);\n this._postProcessesSourceForThisPass = this._postProcessesSourceForThisPass.filter((pp) => {\n return pp != null;\n });\n this._scene.autoClear = true;\n const cameraHasImageProcessing = this._hasImageProcessing(this._postProcessesSourceForThisPass);\n this._needsCompositionForThisPass = !cameraHasImageProcessing && !this.disableGammaTransform && this._needsImageProcessing() && !secondaryCamera;\n const firstCameraPP = this._getFirstPostProcess(this._postProcessesSourceForThisPass);\n const firstPrePassPP = prePassRenderTarget._beforeCompositionPostProcesses && prePassRenderTarget._beforeCompositionPostProcesses[0];\n let firstPP = null;\n // Setting the scene-wide post process configuration\n this._scene.imageProcessingConfiguration.applyByPostProcess = this._needsCompositionForThisPass || cameraHasImageProcessing;\n // Create composition effect if needed\n if (this._needsCompositionForThisPass && !prePassRenderTarget.imageProcessingPostProcess) {\n prePassRenderTarget._createCompositionEffect();\n }\n // Setting the prePassRenderTarget as input texture of the first PP\n if (firstPrePassPP) {\n firstPP = firstPrePassPP;\n }\n else if (this._needsCompositionForThisPass) {\n firstPP = prePassRenderTarget.imageProcessingPostProcess;\n }\n else if (firstCameraPP) {\n firstPP = firstCameraPP;\n }\n this._bindFrameBuffer(prePassRenderTarget);\n this._linkInternalTexture(prePassRenderTarget, firstPP);\n }\n _linkInternalTexture(prePassRenderTarget, postProcess) {\n if (postProcess) {\n postProcess.autoClear = false;\n postProcess.inputTexture = prePassRenderTarget.renderTarget;\n }\n if (prePassRenderTarget._outputPostProcess !== postProcess) {\n if (prePassRenderTarget._outputPostProcess) {\n this._unlinkInternalTexture(prePassRenderTarget);\n }\n prePassRenderTarget._outputPostProcess = postProcess;\n }\n if (prePassRenderTarget._internalTextureDirty) {\n this._updateGeometryBufferLayout();\n prePassRenderTarget._internalTextureDirty = false;\n }\n }\n /**\n * @internal\n */\n _unlinkInternalTexture(prePassRenderTarget) {\n if (prePassRenderTarget._outputPostProcess) {\n prePassRenderTarget._outputPostProcess.autoClear = true;\n prePassRenderTarget._outputPostProcess.restoreDefaultInputTexture();\n prePassRenderTarget._outputPostProcess = null;\n }\n }\n _needsImageProcessing() {\n for (let i = 0; i < this._effectConfigurations.length; i++) {\n if (this._effectConfigurations[i].enabled && this._effectConfigurations[i].needsImageProcessing) {\n return true;\n }\n }\n return false;\n }\n _hasImageProcessing(postProcesses) {\n var _a;\n let isIPPAlreadyPresent = false;\n if (postProcesses) {\n for (let i = 0; i < postProcesses.length; i++) {\n if (((_a = postProcesses[i]) === null || _a === void 0 ? void 0 : _a.getClassName()) === \"ImageProcessingPostProcess\") {\n isIPPAlreadyPresent = true;\n break;\n }\n }\n }\n return isIPPAlreadyPresent;\n }\n /**\n * Internal, gets the first post proces.\n * @param postProcesses\n * @returns the first post process to be run on this camera.\n */\n _getFirstPostProcess(postProcesses) {\n for (let ppIndex = 0; ppIndex < postProcesses.length; ppIndex++) {\n if (postProcesses[ppIndex] !== null) {\n return postProcesses[ppIndex];\n }\n }\n return null;\n }\n /**\n * Marks the prepass renderer as dirty, triggering a check if the prepass is necessary for the next rendering.\n */\n markAsDirty() {\n this._isDirty = true;\n }\n /**\n * Enables a texture on the MultiRenderTarget for prepass\n * @param types\n */\n _enableTextures(types) {\n // For velocity : enable storage of previous matrices for instances\n this._scene.needsPreviousWorldMatrices = false;\n for (let i = 0; i < types.length; i++) {\n const type = types[i];\n if (this._textureIndices[type] === -1) {\n this._textureIndices[type] = this._mrtLayout.length;\n this._mrtLayout.push(type);\n this._mrtTypes.push(PrePassRenderer.TextureFormats[type].type);\n this._mrtFormats.push(PrePassRenderer.TextureFormats[type].format);\n this._mrtNames.push(PrePassRenderer.TextureFormats[type].name);\n this.mrtCount++;\n }\n if (type === 2) {\n this._scene.needsPreviousWorldMatrices = true;\n }\n }\n }\n /**\n * Makes sure that the prepass renderer is up to date if it has been dirtified.\n */\n update() {\n if (this._isDirty) {\n this._update();\n }\n }\n _update() {\n this._disable();\n let enablePrePass = false;\n this._scene.imageProcessingConfiguration.applyByPostProcess = false;\n if (this._scene._depthPeelingRenderer && this._scene.useOrderIndependentTransparency) {\n this._scene._depthPeelingRenderer.setPrePassRenderer(this);\n enablePrePass = true;\n }\n for (let i = 0; i < this._scene.materials.length; i++) {\n if (this._scene.materials[i].setPrePassRenderer(this)) {\n enablePrePass = true;\n }\n }\n if (enablePrePass) {\n this._setRenderTargetEnabled(this.defaultRT, true);\n }\n let postProcesses;\n for (let i = 0; i < this.renderTargets.length; i++) {\n if (this.renderTargets[i].renderTargetTexture) {\n postProcesses = this._getPostProcessesSource(this.renderTargets[i]);\n }\n else {\n const camera = this._scene.activeCamera;\n if (!camera) {\n continue;\n }\n postProcesses = camera._postProcesses;\n }\n if (!postProcesses) {\n continue;\n }\n postProcesses = postProcesses.filter((pp) => {\n return pp != null;\n });\n if (postProcesses) {\n for (let j = 0; j < postProcesses.length; j++) {\n if (postProcesses[j].setPrePassRenderer(this)) {\n this._setRenderTargetEnabled(this.renderTargets[i], true);\n enablePrePass = true;\n }\n }\n if (this._hasImageProcessing(postProcesses)) {\n this._scene.imageProcessingConfiguration.applyByPostProcess = true;\n }\n }\n }\n this._markAllMaterialsAsPrePassDirty();\n this._isDirty = false;\n if (enablePrePass) {\n this._enable();\n }\n }\n _markAllMaterialsAsPrePassDirty() {\n const materials = this._scene.materials;\n for (let i = 0; i < materials.length; i++) {\n materials[i].markAsDirty(Material.PrePassDirtyFlag);\n }\n }\n /**\n * Disposes the prepass renderer.\n */\n dispose() {\n for (let i = this.renderTargets.length - 1; i >= 0; i--) {\n this.renderTargets[i].dispose();\n }\n for (let i = 0; i < this._effectConfigurations.length; i++) {\n if (this._effectConfigurations[i].dispose) {\n this._effectConfigurations[i].dispose();\n }\n }\n }\n}\n/**\n * @internal\n */\nPrePassRenderer._SceneComponentInitialization = (_) => {\n throw _WarnImport(\"PrePassRendererSceneComponent\");\n};\n/**\n * Describes the types and formats of the textures used by the pre-pass renderer\n */\nPrePassRenderer.TextureFormats = [\n {\n purpose: 0,\n type: 2,\n format: 5,\n name: \"prePass_Irradiance\",\n },\n {\n purpose: 1,\n type: 2,\n format: 5,\n name: \"prePass_Position\",\n },\n {\n purpose: 2,\n type: 0,\n format: 5,\n name: \"prePass_Velocity\",\n },\n {\n purpose: 3,\n type: 0,\n format: 5,\n name: \"prePass_Reflectivity\",\n },\n {\n purpose: 4,\n type: 2,\n format: 5,\n name: \"prePass_Color\",\n },\n {\n purpose: 5,\n type: 1,\n format: 6,\n name: \"prePass_Depth\",\n },\n {\n purpose: 6,\n type: 2,\n format: 5,\n name: \"prePass_Normal\",\n },\n {\n purpose: 7,\n type: 0,\n format: 5,\n name: \"prePass_Albedo\",\n },\n];\n//# sourceMappingURL=prePassRenderer.js.map","import { Scene } from \"../scene.js\";\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { PrePassRenderer } from \"./prePassRenderer.js\";\nimport { Logger } from \"../Misc/logger.js\";\nObject.defineProperty(Scene.prototype, \"prePassRenderer\", {\n get: function () {\n return this._prePassRenderer;\n },\n set: function (value) {\n if (value && value.isSupported) {\n this._prePassRenderer = value;\n }\n },\n enumerable: true,\n configurable: true,\n});\nScene.prototype.enablePrePassRenderer = function () {\n if (this._prePassRenderer) {\n return this._prePassRenderer;\n }\n this._prePassRenderer = new PrePassRenderer(this);\n if (!this._prePassRenderer.isSupported) {\n this._prePassRenderer = null;\n Logger.Error(\"PrePassRenderer needs WebGL 2 support.\\n\" + \"Maybe you tried to use the following features that need the PrePassRenderer :\\n\" + \" + Subsurface Scattering\");\n }\n return this._prePassRenderer;\n};\nScene.prototype.disablePrePassRenderer = function () {\n if (!this._prePassRenderer) {\n return;\n }\n this._prePassRenderer.dispose();\n this._prePassRenderer = null;\n};\n/**\n * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful\n * in several rendering techniques.\n */\nexport class PrePassRendererSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpful to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_PREPASSRENDERER;\n this.scene = scene;\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene._beforeCameraDrawStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERADRAW_PREPASS, this, this._beforeCameraDraw);\n this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_PREPASS, this, this._afterCameraDraw);\n this.scene._beforeRenderTargetDrawStage.registerStep(SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_PREPASS, this, this._beforeRenderTargetDraw);\n this.scene._afterRenderTargetDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_PREPASS, this, this._afterRenderTargetDraw);\n this.scene._beforeClearStage.registerStep(SceneComponentConstants.STEP_BEFORECLEAR_PREPASS, this, this._beforeClearStage);\n this.scene._beforeRenderTargetClearStage.registerStep(SceneComponentConstants.STEP_BEFORERENDERTARGETCLEAR_PREPASS, this, this._beforeRenderTargetClearStage);\n this.scene._beforeRenderingMeshStage.registerStep(SceneComponentConstants.STEP_BEFORERENDERINGMESH_PREPASS, this, this._beforeRenderingMeshStage);\n this.scene._afterRenderingMeshStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERINGMESH_PREPASS, this, this._afterRenderingMeshStage);\n }\n _beforeRenderTargetDraw(renderTarget, faceIndex, layer) {\n if (this.scene.prePassRenderer && !renderTarget.noPrePassRenderer) {\n this.scene.prePassRenderer._setRenderTarget(renderTarget._prePassRenderTarget);\n this.scene.prePassRenderer._beforeDraw(undefined, faceIndex, layer);\n }\n }\n _afterRenderTargetDraw(renderTarget, faceIndex, layer) {\n if (this.scene.prePassRenderer && !renderTarget.noPrePassRenderer) {\n this.scene.prePassRenderer._afterDraw(faceIndex, layer);\n }\n }\n _beforeRenderTargetClearStage(renderTarget) {\n if (this.scene.prePassRenderer && !renderTarget.noPrePassRenderer) {\n if (!renderTarget._prePassRenderTarget) {\n renderTarget._prePassRenderTarget = this.scene.prePassRenderer._createRenderTarget(renderTarget.name + \"_prePassRTT\", renderTarget);\n }\n this.scene.prePassRenderer._setRenderTarget(renderTarget._prePassRenderTarget);\n this.scene.prePassRenderer._clear();\n }\n }\n _beforeCameraDraw(camera) {\n if (this.scene.prePassRenderer) {\n this.scene.prePassRenderer._setRenderTarget(null);\n this.scene.prePassRenderer._beforeDraw(camera);\n }\n }\n _afterCameraDraw() {\n if (this.scene.prePassRenderer) {\n this.scene.prePassRenderer._afterDraw();\n }\n }\n _beforeClearStage() {\n if (this.scene.prePassRenderer) {\n this.scene.prePassRenderer._setRenderTarget(null);\n this.scene.prePassRenderer._clear();\n }\n }\n _beforeRenderingMeshStage(mesh, subMesh, batch, effect) {\n if (!effect) {\n return;\n }\n // Render to MRT\n const scene = mesh.getScene();\n if (scene.prePassRenderer) {\n scene.prePassRenderer.bindAttachmentsForEffect(effect, subMesh);\n }\n }\n _afterRenderingMeshStage(mesh) {\n const scene = mesh.getScene();\n if (scene.prePassRenderer) {\n scene.prePassRenderer.restoreAttachments();\n }\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n // Release textures first\n this.scene.disablePrePassRenderer();\n // Re-enable\n this.scene.enablePrePassRenderer();\n }\n /**\n * Disposes the component and the associated resources\n */\n dispose() {\n this.scene.disablePrePassRenderer();\n }\n}\nPrePassRenderer._SceneComponentInitialization = (scene) => {\n // Register the G Buffer component to the scene.\n let component = scene._getComponent(SceneComponentConstants.NAME_PREPASSRENDERER);\n if (!component) {\n component = new PrePassRendererSceneComponent(scene);\n scene._addComponent(component);\n }\n};\n//# sourceMappingURL=prePassRendererSceneComponent.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"fibonacci\";\nconst shader = `#define rcp(x) 1./x\n#define GOLDEN_RATIO 1.618033988749895\n#define TWO_PI 6.2831855\nvec2 Golden2dSeq(int i,float n)\r{\rreturn vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));\r}\rvec2 SampleDiskGolden(int i,int sampleCount)\r{\rvec2 f=Golden2dSeq(i,float(sampleCount));\rreturn vec2(sqrt(f.x),TWO_PI*f.y);\r}`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const fibonacci = { name, shader };\n//# sourceMappingURL=fibonacci.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"diffusionProfile\";\nconst shader = `uniform vec3 diffusionS[5];\runiform float diffusionD[5];\runiform float filterRadii[5];`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const diffusionProfile = { name, shader };\n//# sourceMappingURL=diffusionProfile.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/fibonacci.js\";\nimport \"./ShadersInclude/helperFunctions.js\";\nimport \"./ShadersInclude/subSurfaceScatteringFunctions.js\";\nimport \"./ShadersInclude/diffusionProfile.js\";\nconst name = \"subSurfaceScatteringPixelShader\";\nconst shader = `#include\n#include\n#include\n#include\nvarying vec2 vUV;\runiform vec2 texelSize;\runiform sampler2D textureSampler;\runiform sampler2D irradianceSampler;\runiform sampler2D depthSampler;\runiform sampler2D albedoSampler;\runiform vec2 viewportSize;\runiform float metersPerUnit;\rconst float LOG2_E=1.4426950408889634;\rconst float SSS_PIXELS_PER_SAMPLE=4.;\rconst int _SssSampleBudget=40;\r#define rcp(x) 1./x\n#define Sq(x) x*x\n#define SSS_BILATERAL_FILTER true\nvec3 EvalBurleyDiffusionProfile(float r,vec3 S)\r{\rvec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); \rvec3 expSum=exp_13*(1.+exp_13*exp_13); \rreturn (S*rcp(8.*PI))*expSum; \r}\rvec2 SampleBurleyDiffusionProfile(float u,float rcpS)\r{\ru=1.-u; \rfloat g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));\rfloat n=exp2(log2(g)*(-1.0/3.0)); \rfloat p=(g*n)*n; \rfloat c=1.+p+n; \rfloat d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); \rfloat x=(3./LOG2_E)*log2(c)-d; \rfloat rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));\rfloat r=x*rcpS;\rfloat rcpPdf=(8.*PI*rcpS)*rcpExp; \rreturn vec2(r,rcpPdf);\r}\rvec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf)\r{\r#ifndef SSS_BILATERAL_FILTER\nz=0.;\r#endif\nfloat r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));\rfloat area=rcpPdf;\r#if SSS_CLAMP_ARTIFACT\nreturn clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0);\r#else\nreturn EvalBurleyDiffusionProfile(r,S)*area;\r#endif\n}\rvoid EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm,\rfloat phase,inout vec3 totalIrradiance,inout vec3 totalWeight)\r{\rfloat scale =rcp(float(n));\rfloat offset=rcp(float(n))*0.5;\rfloat sinPhase,cosPhase;\rsinPhase=sin(phase);\rcosPhase=cos(phase);\rvec2 bdp=SampleBurleyDiffusionProfile(float(i)*scale+offset,d);\rfloat r=bdp.x;\rfloat rcpPdf=bdp.y;\rfloat phi=SampleDiskGolden(i,n).y;\rfloat sinPhi,cosPhi;\rsinPhi=sin(phi);\rcosPhi=cos(phi);\rfloat sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; \rfloat cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; \rvec2 vec=r*vec2(cosPsi,sinPsi);\rvec2 position; \rfloat xy2;\rposition=vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*texelSize;\rxy2 =r*r;\rvec4 textureSample=texture2D(irradianceSampler,position);\rfloat viewZ=texture2D(depthSampler,position).r;\rvec3 irradiance =textureSample.rgb;\rif (testLightingForSSS(textureSample.a))\r{\rfloat relZ=viewZ-centerPosVS.z;\rvec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);\rtotalIrradiance+=weight*irradiance;\rtotalWeight +=weight;\r}\relse\r{\r}\r}\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \r{\rvec4 irradianceAndDiffusionProfile =texture2D(irradianceSampler,vUV);\rvec3 centerIrradiance=irradianceAndDiffusionProfile.rgb;\rint diffusionProfileIndex=int(round(irradianceAndDiffusionProfile.a*255.));\rfloat centerDepth =0.;\rvec4 inputColor=texture2D(textureSampler,vUV);\rbool passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);\rif (passedStencilTest)\r{\rcenterDepth=texture2D(depthSampler,vUV).r;\r}\rif (!passedStencilTest) { \rgl_FragColor=inputColor;\rreturn;\r}\rfloat distScale =1.;\rvec3 S =diffusionS[diffusionProfileIndex];\rfloat d =diffusionD[diffusionProfileIndex];\rfloat filterRadius=filterRadii[diffusionProfileIndex];\rvec2 centerPosNDC=vUV;\rvec2 cornerPosNDC=vUV+0.5*texelSize;\rvec3 centerPosVS =vec3(centerPosNDC*viewportSize,1.0)*centerDepth; \rvec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; \rfloat mmPerUnit =1000.*(metersPerUnit*rcp(distScale));\rfloat unitsPerMm=rcp(mmPerUnit);\rfloat unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);\rfloat pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;\rfloat filterArea =PI*Sq(filterRadius*pixelsPerMm);\rint sampleCount =int(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));\rint sampleBudget=_SssSampleBudget;\rint texturingMode=0;\rvec3 albedo =texture2D(albedoSampler,vUV).rgb;\rif (distScale==0. || sampleCount<1)\r{\r#ifdef DEBUG_SSS_SAMPLES\nvec3 green=vec3(0.,1.,0.);\rgl_FragColor=vec4(green,1.0);\rreturn;\r#endif\ngl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);\rreturn;\r}\r#ifdef DEBUG_SSS_SAMPLES\nvec3 red =vec3(1.,0.,0.);\rvec3 blue=vec3(0.,0.,1.);\rgl_FragColor=vec4(mix(blue,red,clamp(float(sampleCount)/float(sampleBudget),0.0,1.0)),1.0);\rreturn;\r#endif\nfloat phase=0.;\rint n=min(sampleCount,sampleBudget);\rvec3 centerWeight =vec3(0.); \rvec3 totalIrradiance=vec3(0.);\rvec3 totalWeight =vec3(0.);\rfor (int i=0; i {\n if (!scene.prePassRenderer || !scene.subSurfaceConfiguration) {\n Logger.Error(\"PrePass and subsurface configuration needs to be enabled for subsurface scattering.\");\n return;\n }\n const texelSize = this.texelSize;\n effect.setFloat(\"metersPerUnit\", scene.subSurfaceConfiguration.metersPerUnit);\n effect.setFloat2(\"texelSize\", texelSize.x, texelSize.y);\n effect.setTexture(\"irradianceSampler\", scene.prePassRenderer.getRenderTarget().textures[scene.prePassRenderer.getIndex(0)]);\n effect.setTexture(\"depthSampler\", scene.prePassRenderer.getRenderTarget().textures[scene.prePassRenderer.getIndex(5)]);\n effect.setTexture(\"albedoSampler\", scene.prePassRenderer.getRenderTarget().textures[scene.prePassRenderer.getIndex(7)]);\n effect.setFloat2(\"viewportSize\", Math.tan(scene.activeCamera.fov / 2) * scene.getEngine().getAspectRatio(scene.activeCamera, true), Math.tan(scene.activeCamera.fov / 2));\n effect.setArray3(\"diffusionS\", scene.subSurfaceConfiguration.ssDiffusionS);\n effect.setArray(\"diffusionD\", scene.subSurfaceConfiguration.ssDiffusionD);\n effect.setArray(\"filterRadii\", scene.subSurfaceConfiguration.ssFilterRadii);\n });\n }\n}\n//# sourceMappingURL=subSurfaceScatteringPostProcess.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { SubSurfaceScatteringPostProcess } from \"../PostProcesses/subSurfaceScatteringPostProcess.js\";\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { _WarnImport } from \"../Misc/devTools.js\";\n\n/**\n * Contains all parameters needed for the prepass to perform\n * screen space subsurface scattering\n */\nexport class SubSurfaceConfiguration {\n /**\n * Diffusion profile color for subsurface scattering\n */\n get ssDiffusionS() {\n return this._ssDiffusionS;\n }\n /**\n * Diffusion profile max color channel value for subsurface scattering\n */\n get ssDiffusionD() {\n return this._ssDiffusionD;\n }\n /**\n * Diffusion profile filter radius for subsurface scattering\n */\n get ssFilterRadii() {\n return this._ssFilterRadii;\n }\n /**\n * Builds a subsurface configuration object\n * @param scene The scene\n */\n constructor(scene) {\n this._ssDiffusionS = [];\n this._ssFilterRadii = [];\n this._ssDiffusionD = [];\n /**\n * Is subsurface enabled\n */\n this.enabled = false;\n /**\n * Does the output of this prepass need to go through imageprocessing\n */\n this.needsImageProcessing = true;\n /**\n * Name of the configuration\n */\n this.name = SceneComponentConstants.NAME_SUBSURFACE;\n /**\n * Diffusion profile colors for subsurface scattering\n * You can add one diffusion color using `addDiffusionProfile` on `scene.prePassRenderer`\n * See ...\n * Note that you can only store up to 5 of them\n */\n this.ssDiffusionProfileColors = [];\n /**\n * Defines the ratio real world => scene units.\n * Used for subsurface scattering\n */\n this.metersPerUnit = 1;\n /**\n * Textures that should be present in the MRT for this effect to work\n */\n this.texturesRequired = [\n 5,\n 7,\n 4,\n 0,\n ];\n // Adding default diffusion profile\n this.addDiffusionProfile(new Color3(1, 1, 1));\n this._scene = scene;\n SubSurfaceConfiguration._SceneComponentInitialization(this._scene);\n }\n /**\n * Adds a new diffusion profile.\n * Useful for more realistic subsurface scattering on diverse materials.\n * @param color The color of the diffusion profile. Should be the average color of the material.\n * @returns The index of the diffusion profile for the material subsurface configuration\n */\n addDiffusionProfile(color) {\n if (this.ssDiffusionD.length >= 5) {\n // We only suppport 5 diffusion profiles\n Logger.Error(\"You already reached the maximum number of diffusion profiles.\");\n return 0; // default profile\n }\n // Do not add doubles\n for (let i = 0; i < this._ssDiffusionS.length / 3; i++) {\n if (this._ssDiffusionS[i * 3] === color.r && this._ssDiffusionS[i * 3 + 1] === color.g && this._ssDiffusionS[i * 3 + 2] === color.b) {\n return i;\n }\n }\n this._ssDiffusionS.push(color.r, color.b, color.g);\n this._ssDiffusionD.push(Math.max(Math.max(color.r, color.b), color.g));\n this._ssFilterRadii.push(this.getDiffusionProfileParameters(color));\n this.ssDiffusionProfileColors.push(color);\n return this._ssDiffusionD.length - 1;\n }\n /**\n * Creates the sss post process\n * @returns The created post process\n */\n createPostProcess() {\n this.postProcess = new SubSurfaceScatteringPostProcess(\"subSurfaceScattering\", this._scene, 1, null, undefined, this._scene.getEngine());\n this.postProcess.autoClear = false;\n return this.postProcess;\n }\n /**\n * Deletes all diffusion profiles.\n * Note that in order to render subsurface scattering, you should have at least 1 diffusion profile.\n */\n clearAllDiffusionProfiles() {\n this._ssDiffusionD = [];\n this._ssDiffusionS = [];\n this._ssFilterRadii = [];\n this.ssDiffusionProfileColors = [];\n }\n /**\n * Disposes this object\n */\n dispose() {\n this.clearAllDiffusionProfiles();\n if (this.postProcess) {\n this.postProcess.dispose();\n }\n }\n /**\n * @internal\n * https://zero-radiance.github.io/post/sampling-diffusion/\n *\n * Importance sample the normalized diffuse reflectance profile for the computed value of 's'.\n * ------------------------------------------------------------------------------------\n * R[r, phi, s] = s * (Exp[-r * s] + Exp[-r * s / 3]) / (8 * Pi * r)\n * PDF[r, phi, s] = r * R[r, phi, s]\n * CDF[r, s] = 1 - 1/4 * Exp[-r * s] - 3/4 * Exp[-r * s / 3]\n * ------------------------------------------------------------------------------------\n * We importance sample the color channel with the widest scattering distance.\n */\n getDiffusionProfileParameters(color) {\n const cdf = 0.997;\n const maxScatteringDistance = Math.max(color.r, color.g, color.b);\n return this._sampleBurleyDiffusionProfile(cdf, maxScatteringDistance);\n }\n /**\n * Performs sampling of a Normalized Burley diffusion profile in polar coordinates.\n * 'u' is the random number (the value of the CDF): [0, 1).\n * rcp(s) = 1 / ShapeParam = ScatteringDistance.\n * Returns the sampled radial distance, s.t. (u = 0 -> r = 0) and (u = 1 -> r = Inf).\n * @param u\n * @param rcpS\n */\n _sampleBurleyDiffusionProfile(u, rcpS) {\n u = 1 - u; // Convert CDF to CCDF\n const g = 1 + 4 * u * (2 * u + Math.sqrt(1 + 4 * u * u));\n const n = Math.pow(g, -1.0 / 3.0); // g^(-1/3)\n const p = g * n * n; // g^(+1/3)\n const c = 1 + p + n; // 1 + g^(+1/3) + g^(-1/3)\n const x = 3 * Math.log(c / (4 * u));\n return x * rcpS;\n }\n}\n/**\n * @internal\n */\nSubSurfaceConfiguration._SceneComponentInitialization = (_) => {\n throw _WarnImport(\"SubSurfaceSceneComponent\");\n};\n//# sourceMappingURL=subSurfaceConfiguration.js.map","import { Scene } from \"../scene.js\";\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { SubSurfaceConfiguration } from \"./subSurfaceConfiguration.js\";\nimport { AbstractScene } from \"../abstractScene.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\n// Adds the parser to the scene parsers.\nAbstractScene.AddParser(SceneComponentConstants.NAME_SUBSURFACE, (parsedData, scene) => {\n // Diffusion profiles\n if (parsedData.ssDiffusionProfileColors !== undefined && parsedData.ssDiffusionProfileColors !== null) {\n scene.enableSubSurfaceForPrePass();\n if (scene.subSurfaceConfiguration) {\n for (let index = 0, cache = parsedData.ssDiffusionProfileColors.length; index < cache; index++) {\n const color = parsedData.ssDiffusionProfileColors[index];\n scene.subSurfaceConfiguration.addDiffusionProfile(new Color3(color.r, color.g, color.b));\n }\n }\n }\n});\nObject.defineProperty(Scene.prototype, \"subSurfaceConfiguration\", {\n get: function () {\n return this._subSurfaceConfiguration;\n },\n set: function (value) {\n if (value) {\n if (this.enablePrePassRenderer()) {\n this._subSurfaceConfiguration = value;\n }\n }\n },\n enumerable: true,\n configurable: true,\n});\nScene.prototype.enableSubSurfaceForPrePass = function () {\n if (this._subSurfaceConfiguration) {\n return this._subSurfaceConfiguration;\n }\n const prePassRenderer = this.enablePrePassRenderer();\n if (prePassRenderer) {\n this._subSurfaceConfiguration = new SubSurfaceConfiguration(this);\n prePassRenderer.addEffectConfiguration(this._subSurfaceConfiguration);\n return this._subSurfaceConfiguration;\n }\n return null;\n};\nScene.prototype.disableSubSurfaceForPrePass = function () {\n if (!this._subSurfaceConfiguration) {\n return;\n }\n this._subSurfaceConfiguration.dispose();\n this._subSurfaceConfiguration = null;\n};\n/**\n * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful\n * in several rendering techniques.\n */\nexport class SubSurfaceSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpful to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_PREPASSRENDERER;\n this.scene = scene;\n }\n /**\n * Registers the component in a given scene\n */\n register() { }\n /**\n * Serializes the component data to the specified json object\n * @param serializationObject The object to serialize to\n */\n serialize(serializationObject) {\n if (!this.scene.subSurfaceConfiguration) {\n return;\n }\n const ssDiffusionProfileColors = this.scene.subSurfaceConfiguration.ssDiffusionProfileColors;\n serializationObject.ssDiffusionProfileColors = [];\n for (let i = 0; i < ssDiffusionProfileColors.length; i++) {\n serializationObject.ssDiffusionProfileColors.push({\n r: ssDiffusionProfileColors[i].r,\n g: ssDiffusionProfileColors[i].g,\n b: ssDiffusionProfileColors[i].b,\n });\n }\n }\n /**\n * Adds all the elements from the container to the scene\n */\n addFromContainer() {\n // Nothing to do\n }\n /**\n * Removes all the elements in the container from the scene\n */\n removeFromContainer() {\n // Make sure nothing will be serialized\n if (!this.scene.prePassRenderer) {\n return;\n }\n if (this.scene.subSurfaceConfiguration) {\n this.scene.subSurfaceConfiguration.clearAllDiffusionProfiles();\n }\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n // Nothing to do for this component\n }\n /**\n * Disposes the component and the associated resources\n */\n dispose() {\n // Nothing to do for this component\n }\n}\nSubSurfaceConfiguration._SceneComponentInitialization = (scene) => {\n // Register the G Buffer component to the scene.\n let component = scene._getComponent(SceneComponentConstants.NAME_SUBSURFACE);\n if (!component) {\n component = new SubSurfaceSceneComponent(scene);\n scene._addComponent(component);\n }\n};\n//# sourceMappingURL=subSurfaceSceneComponent.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/clipPlaneFragmentDeclaration.js\";\nimport \"./ShadersInclude/logDepthDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneFragment.js\";\nimport \"./ShadersInclude/logDepthFragment.js\";\nconst name = \"outlinePixelShader\";\nconst shader = `#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\r#ifdef ALPHATEST\nvarying vec2 vUV;\runiform sampler2D diffuseSampler;\r#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\rdiscard;\r#endif\n#include\ngl_FragColor=color;\r#define CUSTOM_FRAGMENT_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const outlinePixelShader = { name, shader };\n//# sourceMappingURL=outline.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/bonesDeclaration.js\";\nimport \"./ShadersInclude/bakedVertexAnimationDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexGlobalDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneVertexDeclaration.js\";\nimport \"./ShadersInclude/instancesDeclaration.js\";\nimport \"./ShadersInclude/logDepthDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexGlobal.js\";\nimport \"./ShadersInclude/morphTargetsVertex.js\";\nimport \"./ShadersInclude/instancesVertex.js\";\nimport \"./ShadersInclude/bonesVertex.js\";\nimport \"./ShadersInclude/bakedVertexAnimation.js\";\nimport \"./ShadersInclude/clipPlaneVertex.js\";\nimport \"./ShadersInclude/logDepthVertex.js\";\nconst name = \"outlineVertexShader\";\nconst shader = `attribute vec3 position;\rattribute vec3 normal;\r#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nuniform float offset;\r#include\nuniform mat4 viewProjection;\r#ifdef ALPHATEST\nvarying vec2 vUV;\runiform mat4 diffuseMatrix;\r#ifdef UV1\nattribute vec2 uv;\r#endif\n#ifdef UV2\nattribute vec2 uv2;\r#endif\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\r{\rvec3 positionUpdated=position;\rvec3 normalUpdated=normal;\r#ifdef UV1\nvec2 uvUpdated=uv;\r#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\nvec3 offsetPosition=positionUpdated+(normalUpdated*offset);\r#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(offsetPosition,1.0);\rgl_Position=viewProjection*worldPos;\r#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\r#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\r#endif\n#endif\n#include\n#include\n}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const outlineVertexShader = { name, shader };\n//# sourceMappingURL=outline.vertex.js.map","import { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { Scene } from \"../scene.js\";\n\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { DrawWrapper } from \"../Materials/drawWrapper.js\";\nimport { MaterialHelper } from \"../Materials/materialHelper.js\";\nimport \"../Shaders/outline.fragment.js\";\nimport \"../Shaders/outline.vertex.js\";\nimport { addClipPlaneUniforms, bindClipPlane, prepareStringDefinesForClipPlanes } from \"../Materials/clipPlaneMaterialHelper.js\";\n/**\n * Gets the outline renderer associated with the scene\n * @returns a OutlineRenderer\n */\nScene.prototype.getOutlineRenderer = function () {\n if (!this._outlineRenderer) {\n this._outlineRenderer = new OutlineRenderer(this);\n }\n return this._outlineRenderer;\n};\nObject.defineProperty(Mesh.prototype, \"renderOutline\", {\n get: function () {\n return this._renderOutline;\n },\n set: function (value) {\n if (value) {\n // Lazy Load the component.\n this.getScene().getOutlineRenderer();\n }\n this._renderOutline = value;\n },\n enumerable: true,\n configurable: true,\n});\nObject.defineProperty(Mesh.prototype, \"renderOverlay\", {\n get: function () {\n return this._renderOverlay;\n },\n set: function (value) {\n if (value) {\n // Lazy Load the component.\n this.getScene().getOutlineRenderer();\n }\n this._renderOverlay = value;\n },\n enumerable: true,\n configurable: true,\n});\n/**\n * This class is responsible to draw the outline/overlay of meshes.\n * It should not be used directly but through the available method on mesh.\n */\nexport class OutlineRenderer {\n /**\n * Instantiates a new outline renderer. (There could be only one per scene).\n * @param scene Defines the scene it belongs to\n */\n constructor(scene) {\n /**\n * The name of the component. Each component must have a unique name.\n */\n this.name = SceneComponentConstants.NAME_OUTLINERENDERER;\n /**\n * Defines a zOffset default Factor to prevent zFighting between the overlay and the mesh.\n */\n this.zOffset = 1;\n /**\n * Defines a zOffset default Unit to prevent zFighting between the overlay and the mesh.\n */\n this.zOffsetUnits = 4; // 4 to account for projection a bit by default\n this.scene = scene;\n this._engine = scene.getEngine();\n this.scene._addComponent(this);\n this._passIdForDrawWrapper = [];\n for (let i = 0; i < 4; ++i) {\n this._passIdForDrawWrapper[i] = this._engine.createRenderPassId(`Outline Renderer (${i})`);\n }\n }\n /**\n * Register the component to one instance of a scene.\n */\n register() {\n this.scene._beforeRenderingMeshStage.registerStep(SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);\n this.scene._afterRenderingMeshStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n // Nothing to do here.\n }\n /**\n * Disposes the component and the associated resources.\n */\n dispose() {\n for (let i = 0; i < this._passIdForDrawWrapper.length; ++i) {\n this._engine.releaseRenderPassId(this._passIdForDrawWrapper[i]);\n }\n }\n /**\n * Renders the outline in the canvas.\n * @param subMesh Defines the sumesh to render\n * @param batch Defines the batch of meshes in case of instances\n * @param useOverlay Defines if the rendering is for the overlay or the outline\n * @param renderPassId Render pass id to use to render the mesh\n */\n render(subMesh, batch, useOverlay = false, renderPassId) {\n renderPassId = renderPassId !== null && renderPassId !== void 0 ? renderPassId : this._passIdForDrawWrapper[0];\n const scene = this.scene;\n const engine = scene.getEngine();\n const hardwareInstancedRendering = engine.getCaps().instancedArrays &&\n ((batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined) || subMesh.getRenderingMesh().hasThinInstances);\n if (!this.isReady(subMesh, hardwareInstancedRendering, renderPassId)) {\n return;\n }\n const ownerMesh = subMesh.getMesh();\n const replacementMesh = ownerMesh._internalAbstractMeshDataInfo._actAsRegularMesh ? ownerMesh : null;\n const renderingMesh = subMesh.getRenderingMesh();\n const effectiveMesh = replacementMesh ? replacementMesh : renderingMesh;\n const material = subMesh.getMaterial();\n if (!material || !scene.activeCamera) {\n return;\n }\n const drawWrapper = subMesh._getDrawWrapper(renderPassId);\n const effect = DrawWrapper.GetEffect(drawWrapper);\n engine.enableEffect(drawWrapper);\n // Logarithmic depth\n if (material.useLogarithmicDepth) {\n effect.setFloat(\"logarithmicDepthConstant\", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));\n }\n effect.setFloat(\"offset\", useOverlay ? 0 : renderingMesh.outlineWidth);\n effect.setColor4(\"color\", useOverlay ? renderingMesh.overlayColor : renderingMesh.outlineColor, useOverlay ? renderingMesh.overlayAlpha : material.alpha);\n effect.setMatrix(\"viewProjection\", scene.getTransformMatrix());\n effect.setMatrix(\"world\", effectiveMesh.getWorldMatrix());\n // Bones\n if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) {\n effect.setMatrices(\"mBones\", renderingMesh.skeleton.getTransformMatrices(renderingMesh));\n }\n if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) {\n renderingMesh.morphTargetManager._bind(effect);\n }\n // Morph targets\n MaterialHelper.BindMorphTargetParameters(renderingMesh, effect);\n if (!hardwareInstancedRendering) {\n renderingMesh._bind(subMesh, effect, material.fillMode);\n }\n // Alpha test\n if (material && material.needAlphaTesting()) {\n const alphaTexture = material.getAlphaTestTexture();\n if (alphaTexture) {\n effect.setTexture(\"diffuseSampler\", alphaTexture);\n effect.setMatrix(\"diffuseMatrix\", alphaTexture.getTextureMatrix());\n }\n }\n // Clip plane\n bindClipPlane(effect, material, scene);\n engine.setZOffset(-this.zOffset);\n engine.setZOffsetUnits(-this.zOffsetUnits);\n renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, world) => {\n effect.setMatrix(\"world\", world);\n });\n engine.setZOffset(0);\n engine.setZOffsetUnits(0);\n }\n /**\n * Returns whether or not the outline renderer is ready for a given submesh.\n * All the dependencies e.g. submeshes, texture, effect... mus be ready\n * @param subMesh Defines the submesh to check readiness for\n * @param useInstances Defines whether wee are trying to render instances or not\n * @param renderPassId Render pass id to use to render the mesh\n * @returns true if ready otherwise false\n */\n isReady(subMesh, useInstances, renderPassId) {\n renderPassId = renderPassId !== null && renderPassId !== void 0 ? renderPassId : this._passIdForDrawWrapper[0];\n const defines = [];\n const attribs = [VertexBuffer.PositionKind, VertexBuffer.NormalKind];\n const mesh = subMesh.getMesh();\n const material = subMesh.getMaterial();\n if (!material) {\n return false;\n }\n const scene = mesh.getScene();\n // Alpha test\n if (material.needAlphaTesting()) {\n defines.push(\"#define ALPHATEST\");\n if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {\n attribs.push(VertexBuffer.UVKind);\n defines.push(\"#define UV1\");\n }\n if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {\n attribs.push(VertexBuffer.UV2Kind);\n defines.push(\"#define UV2\");\n }\n }\n //Logarithmic depth\n if (material.useLogarithmicDepth) {\n defines.push(\"#define LOGARITHMICDEPTH\");\n }\n // Clip planes\n prepareStringDefinesForClipPlanes(material, scene, defines);\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders) {\n attribs.push(VertexBuffer.MatricesIndicesKind);\n attribs.push(VertexBuffer.MatricesWeightsKind);\n if (mesh.numBoneInfluencers > 4) {\n attribs.push(VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(VertexBuffer.MatricesWeightsExtraKind);\n }\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n defines.push(\"#define BonesPerMesh \" + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Morph targets\n const morphTargetManager = mesh.morphTargetManager;\n let numMorphInfluencers = 0;\n if (morphTargetManager) {\n if (morphTargetManager.numInfluencers > 0) {\n numMorphInfluencers = morphTargetManager.numInfluencers;\n defines.push(\"#define MORPHTARGETS\");\n defines.push(\"#define NUM_MORPH_INFLUENCERS \" + numMorphInfluencers);\n if (morphTargetManager.isUsingTextureForTargets) {\n defines.push(\"#define MORPHTARGETS_TEXTURE\");\n }\n MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, numMorphInfluencers);\n }\n }\n // Instances\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n MaterialHelper.PushAttributesForInstances(attribs);\n if (subMesh.getRenderingMesh().hasThinInstances) {\n defines.push(\"#define THIN_INSTANCES\");\n }\n }\n // Get correct effect\n const drawWrapper = subMesh._getDrawWrapper(renderPassId, true);\n const cachedDefines = drawWrapper.defines;\n const join = defines.join(\"\\n\");\n if (cachedDefines !== join) {\n const uniforms = [\n \"world\",\n \"mBones\",\n \"viewProjection\",\n \"diffuseMatrix\",\n \"offset\",\n \"color\",\n \"logarithmicDepthConstant\",\n \"morphTargetInfluences\",\n \"morphTargetTextureInfo\",\n \"morphTargetTextureIndices\",\n ];\n addClipPlaneUniforms(uniforms);\n drawWrapper.setEffect(this.scene.getEngine().createEffect(\"outline\", attribs, uniforms, [\"diffuseSampler\", \"morphTargets\"], join, undefined, undefined, undefined, {\n maxSimultaneousMorphTargets: numMorphInfluencers,\n }), join);\n }\n return drawWrapper.effect.isReady();\n }\n _beforeRenderingMesh(mesh, subMesh, batch) {\n // Outline - step 1\n this._savedDepthWrite = this._engine.getDepthWrite();\n if (mesh.renderOutline) {\n const material = subMesh.getMaterial();\n if (material && material.needAlphaBlendingForMesh(mesh)) {\n this._engine.cacheStencilState();\n // Draw only to stencil buffer for the original mesh\n // The resulting stencil buffer will be used so the outline is not visible inside the mesh when the mesh is transparent\n this._engine.setDepthWrite(false);\n this._engine.setColorWrite(false);\n this._engine.setStencilBuffer(true);\n this._engine.setStencilOperationPass(7681);\n this._engine.setStencilFunction(519);\n this._engine.setStencilMask(OutlineRenderer._StencilReference);\n this._engine.setStencilFunctionReference(OutlineRenderer._StencilReference);\n this._engine.stencilStateComposer.useStencilGlobalOnly = true;\n this.render(subMesh, batch, /* This sets offset to 0 */ true, this._passIdForDrawWrapper[1]);\n this._engine.setColorWrite(true);\n this._engine.setStencilFunction(517);\n }\n // Draw the outline using the above stencil if needed to avoid drawing within the mesh\n this._engine.setDepthWrite(false);\n this.render(subMesh, batch, false, this._passIdForDrawWrapper[0]);\n this._engine.setDepthWrite(this._savedDepthWrite);\n if (material && material.needAlphaBlendingForMesh(mesh)) {\n this._engine.stencilStateComposer.useStencilGlobalOnly = false;\n this._engine.restoreStencilState();\n }\n }\n }\n _afterRenderingMesh(mesh, subMesh, batch) {\n // Overlay\n if (mesh.renderOverlay) {\n const currentMode = this._engine.getAlphaMode();\n const alphaBlendState = this._engine.alphaState.alphaBlend;\n this._engine.setAlphaMode(2);\n this.render(subMesh, batch, true, this._passIdForDrawWrapper[3]);\n this._engine.setAlphaMode(currentMode);\n this._engine.setDepthWrite(this._savedDepthWrite);\n this._engine.alphaState.alphaBlend = alphaBlendState;\n }\n // Outline - step 2\n if (mesh.renderOutline && this._savedDepthWrite) {\n this._engine.setDepthWrite(true);\n this._engine.setColorWrite(false);\n this.render(subMesh, batch, false, this._passIdForDrawWrapper[2]);\n this._engine.setColorWrite(true);\n }\n }\n}\n/**\n * Stencil value used to avoid outline being seen within the mesh when the mesh is transparent\n */\nOutlineRenderer._StencilReference = 0x04;\n//# sourceMappingURL=outlineRenderer.js.map","\nimport { EffectWrapper } from \"../../Materials/effectRenderer.js\";\nimport { Observable } from \"../../Misc/observable.js\";\n/**\n * Defines the base object used for fluid rendering.\n * It is based on a list of vertices (particles)\n */\nexport class FluidRenderingObject {\n /** Gets or sets the size of the particle */\n get particleSize() {\n return this._particleSize;\n }\n set particleSize(size) {\n if (size === this._particleSize) {\n return;\n }\n this._particleSize = size;\n this.onParticleSizeChanged.notifyObservers(this);\n }\n /** Indicates if the object uses instancing or not */\n get useInstancing() {\n return !this.indexBuffer;\n }\n /** Indicates if velocity of particles should be used when rendering the object. The vertex buffer set must contain a \"velocity\" buffer for this to work! */\n get useVelocity() {\n return this._useVelocity;\n }\n set useVelocity(use) {\n if (this._useVelocity === use || !this._hasVelocity()) {\n return;\n }\n this._useVelocity = use;\n this._effectsAreDirty = true;\n }\n _hasVelocity() {\n var _a;\n return !!((_a = this.vertexBuffers) === null || _a === void 0 ? void 0 : _a.velocity);\n }\n /**\n * Gets the index buffer (or null if the object is using instancing)\n */\n get indexBuffer() {\n return null;\n }\n /**\n * Gets the name of the class\n */\n getClassName() {\n return \"FluidRenderingObject\";\n }\n /**\n * Instantiates a fluid rendering object\n * @param scene The scene the object is part of\n */\n constructor(scene) {\n /** Defines the priority of the object. Objects will be rendered in ascending order of priority */\n this.priority = 0;\n this._particleSize = 0.1;\n /** Observable triggered when the size of the particle is changed */\n this.onParticleSizeChanged = new Observable();\n /** Defines the alpha value of a particle */\n this.particleThicknessAlpha = 0.05;\n this._useVelocity = false;\n this._scene = scene;\n this._engine = scene.getEngine();\n this._effectsAreDirty = true;\n this._depthEffectWrapper = null;\n this._thicknessEffectWrapper = null;\n }\n _createEffects() {\n const uniformNames = [\"view\", \"projection\", \"particleRadius\", \"size\"];\n const attributeNames = [\"position\", \"offset\"];\n const defines = [];\n this._effectsAreDirty = false;\n if (this.useVelocity) {\n attributeNames.push(\"velocity\");\n defines.push(\"#define FLUIDRENDERING_VELOCITY\");\n }\n if (this._scene.useRightHandedSystem) {\n defines.push(\"#define FLUIDRENDERING_RHS\");\n }\n this._depthEffectWrapper = new EffectWrapper({\n engine: this._engine,\n useShaderStore: true,\n vertexShader: \"fluidRenderingParticleDepth\",\n fragmentShader: \"fluidRenderingParticleDepth\",\n attributeNames,\n uniformNames,\n samplerNames: [],\n defines,\n });\n uniformNames.push(\"particleAlpha\");\n this._thicknessEffectWrapper = new EffectWrapper({\n engine: this._engine,\n useShaderStore: true,\n vertexShader: \"fluidRenderingParticleThickness\",\n fragmentShader: \"fluidRenderingParticleThickness\",\n attributeNames: [\"position\", \"offset\"],\n uniformNames,\n samplerNames: [],\n });\n }\n /**\n * Indicates if the object is ready to be rendered\n * @returns True if everything is ready for the object to be rendered, otherwise false\n */\n isReady() {\n if (this._effectsAreDirty) {\n this._createEffects();\n }\n if (!this._depthEffectWrapper || !this._thicknessEffectWrapper) {\n return false;\n }\n const depthEffect = this._depthEffectWrapper._drawWrapper.effect;\n const thicknessEffect = this._thicknessEffectWrapper._drawWrapper.effect;\n return depthEffect.isReady() && thicknessEffect.isReady();\n }\n /**\n * Render the depth texture for this object\n */\n renderDepthTexture() {\n const numParticles = this.numParticles;\n if (!this._depthEffectWrapper || numParticles === 0) {\n return;\n }\n const depthDrawWrapper = this._depthEffectWrapper._drawWrapper;\n const depthEffect = depthDrawWrapper.effect;\n this._engine.enableEffect(depthDrawWrapper);\n this._engine.bindBuffers(this.vertexBuffers, this.indexBuffer, depthEffect);\n depthEffect.setMatrix(\"view\", this._scene.getViewMatrix());\n depthEffect.setMatrix(\"projection\", this._scene.getProjectionMatrix());\n depthEffect.setFloat2(\"size\", this._particleSize, this._particleSize);\n depthEffect.setFloat(\"particleRadius\", this._particleSize / 2);\n if (this.useInstancing) {\n this._engine.drawArraysType(7, 0, 4, numParticles);\n }\n else {\n this._engine.drawElementsType(0, 0, numParticles);\n }\n }\n /**\n * Render the thickness texture for this object\n */\n renderThicknessTexture() {\n const numParticles = this.numParticles;\n if (!this._thicknessEffectWrapper || numParticles === 0) {\n return;\n }\n const thicknessDrawWrapper = this._thicknessEffectWrapper._drawWrapper;\n const thicknessEffect = thicknessDrawWrapper.effect;\n this._engine.setAlphaMode(6);\n this._engine.setDepthWrite(false);\n this._engine.enableEffect(thicknessDrawWrapper);\n this._engine.bindBuffers(this.vertexBuffers, this.indexBuffer, thicknessEffect);\n thicknessEffect.setMatrix(\"view\", this._scene.getViewMatrix());\n thicknessEffect.setMatrix(\"projection\", this._scene.getProjectionMatrix());\n thicknessEffect.setFloat(\"particleAlpha\", this.particleThicknessAlpha);\n thicknessEffect.setFloat2(\"size\", this._particleSize, this._particleSize);\n if (this.useInstancing) {\n this._engine.drawArraysType(7, 0, 4, numParticles);\n }\n else {\n this._engine.drawElementsType(0, 0, numParticles);\n }\n this._engine.setDepthWrite(true);\n this._engine.setAlphaMode(0);\n }\n /**\n * Render the diffuse texture for this object\n */\n renderDiffuseTexture() {\n // do nothing by default\n }\n /**\n * Releases the ressources used by the class\n */\n dispose() {\n var _a, _b;\n (_a = this._depthEffectWrapper) === null || _a === void 0 ? void 0 : _a.dispose();\n (_b = this._thicknessEffectWrapper) === null || _b === void 0 ? void 0 : _b.dispose();\n }\n}\n//# sourceMappingURL=fluidRenderingObject.js.map","\nimport { Texture } from \"../../Materials/Textures/texture.js\";\nimport { Vector2 } from \"../../Maths/math.vector.js\";\nimport { PostProcess } from \"../../PostProcesses/postProcess.js\";\nimport { Observable } from \"../../Misc/observable.js\";\n/** @internal */\nexport class FluidRenderingTextures {\n get blurNumIterations() {\n return this._blurNumIterations;\n }\n set blurNumIterations(numIterations) {\n if (this._blurNumIterations === numIterations) {\n return;\n }\n this._blurNumIterations = numIterations;\n if (this._blurPostProcesses !== null) {\n const blurX = this._blurPostProcesses[0];\n const blurY = this._blurPostProcesses[1];\n this._blurPostProcesses = [];\n for (let i = 0; i < this._blurNumIterations * 2; ++i) {\n this._blurPostProcesses[i] = i & 1 ? blurY : blurX;\n }\n }\n }\n get renderTarget() {\n return this._rt;\n }\n get renderTargetBlur() {\n return this._rtBlur;\n }\n get texture() {\n return this._texture;\n }\n get textureBlur() {\n return this._textureBlurred;\n }\n constructor(name, scene, width, height, blurTextureSizeX, blurTextureSizeY, textureType = 1, textureFormat = 6, blurTextureType = 1, blurTextureFormat = 6, useStandardBlur = false, camera = null, generateDepthBuffer = true, samples = 1) {\n this.enableBlur = true;\n this.blurSizeDivisor = 1;\n this.blurFilterSize = 7;\n this._blurNumIterations = 3;\n this.blurMaxFilterSize = 100;\n this.blurDepthScale = 10;\n this.particleSize = 0.02;\n this.onDisposeObservable = new Observable();\n this._name = name;\n this._scene = scene;\n this._camera = camera;\n this._engine = scene.getEngine();\n this._width = width;\n this._height = height;\n this._blurTextureSizeX = blurTextureSizeX;\n this._blurTextureSizeY = blurTextureSizeY;\n this._textureType = textureType;\n this._textureFormat = textureFormat;\n this._blurTextureType = blurTextureType;\n this._blurTextureFormat = blurTextureFormat;\n this._useStandardBlur = useStandardBlur;\n this._generateDepthBuffer = generateDepthBuffer;\n this._samples = samples;\n this._postProcessRunningIndex = 0;\n this.enableBlur = blurTextureSizeX !== 0 && blurTextureSizeY !== 0;\n this._rt = null;\n this._texture = null;\n this._rtBlur = null;\n this._textureBlurred = null;\n this._blurPostProcesses = null;\n }\n initialize() {\n this.dispose();\n this._createRenderTarget();\n if (this.enableBlur && this._texture) {\n const [rtBlur, textureBlurred, blurPostProcesses] = this._createBlurPostProcesses(this._texture, this._blurTextureType, this._blurTextureFormat, this.blurSizeDivisor, this._name, this._useStandardBlur);\n this._rtBlur = rtBlur;\n this._textureBlurred = textureBlurred;\n this._blurPostProcesses = blurPostProcesses;\n }\n }\n applyBlurPostProcesses() {\n if (this.enableBlur && this._blurPostProcesses) {\n this._postProcessRunningIndex = 0;\n this._scene.postProcessManager.directRender(this._blurPostProcesses, this._rtBlur, true);\n this._engine.unBindFramebuffer(this._rtBlur);\n }\n }\n _createRenderTarget() {\n this._rt = this._engine.createRenderTargetTexture({ width: this._width, height: this._height }, {\n generateMipMaps: false,\n type: this._textureType,\n format: this._textureFormat,\n samplingMode: 1,\n generateDepthBuffer: this._generateDepthBuffer,\n generateStencilBuffer: false,\n samples: this._samples,\n label: `FluidRenderingRTT-${this._name}`,\n });\n const renderTexture = this._rt.texture;\n renderTexture.incrementReferences();\n this._texture = new Texture(null, this._scene);\n this._texture.name = \"rtt\" + this._name;\n this._texture._texture = renderTexture;\n this._texture.wrapU = Texture.CLAMP_ADDRESSMODE;\n this._texture.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._texture.anisotropicFilteringLevel = 1;\n }\n _createBlurPostProcesses(textureBlurSource, textureType, textureFormat, blurSizeDivisor, debugName, useStandardBlur = false) {\n const engine = this._scene.getEngine();\n const targetSize = new Vector2(Math.floor(this._blurTextureSizeX / blurSizeDivisor), Math.floor(this._blurTextureSizeY / blurSizeDivisor));\n const useBilinearFiltering = (textureType === 1 && engine.getCaps().textureFloatLinearFiltering) ||\n (textureType === 2 && engine.getCaps().textureHalfFloatLinearFiltering);\n const rtBlur = this._engine.createRenderTargetTexture({ width: targetSize.x, height: targetSize.y }, {\n generateMipMaps: false,\n type: textureType,\n format: textureFormat,\n samplingMode: useBilinearFiltering ? 2 : 1,\n generateDepthBuffer: false,\n generateStencilBuffer: false,\n samples: this._samples,\n label: `FluidRenderingRTTBlur-${debugName}`,\n });\n const renderTexture = rtBlur.texture;\n renderTexture.incrementReferences();\n const texture = new Texture(null, this._scene);\n texture.name = \"rttBlurred\" + debugName;\n texture._texture = renderTexture;\n texture.wrapU = Texture.CLAMP_ADDRESSMODE;\n texture.wrapV = Texture.CLAMP_ADDRESSMODE;\n texture.anisotropicFilteringLevel = 1;\n if (useStandardBlur) {\n const kernelBlurXPostprocess = new PostProcess(\"BilateralBlurX\", \"fluidRenderingStandardBlur\", [\"filterSize\", \"blurDir\"], null, 1, null, 1, engine, true, null, textureType, undefined, undefined, undefined, textureFormat);\n kernelBlurXPostprocess.samples = this._samples;\n kernelBlurXPostprocess.externalTextureSamplerBinding = true;\n kernelBlurXPostprocess.onApplyObservable.add((effect) => {\n if (this._postProcessRunningIndex === 0) {\n effect.setTexture(\"textureSampler\", textureBlurSource);\n }\n else {\n effect._bindTexture(\"textureSampler\", kernelBlurXPostprocess.inputTexture.texture);\n }\n effect.setInt(\"filterSize\", this.blurFilterSize);\n effect.setFloat2(\"blurDir\", 1 / this._blurTextureSizeX, 0);\n this._postProcessRunningIndex++;\n });\n kernelBlurXPostprocess.onSizeChangedObservable.add(() => {\n kernelBlurXPostprocess._textures.forEach((rt) => {\n rt.texture.wrapU = Texture.CLAMP_ADDRESSMODE;\n rt.texture.wrapV = Texture.CLAMP_ADDRESSMODE;\n });\n });\n this._fixReusablePostProcess(kernelBlurXPostprocess);\n const kernelBlurYPostprocess = new PostProcess(\"BilateralBlurY\", \"fluidRenderingStandardBlur\", [\"filterSize\", \"blurDir\"], null, 1, null, 1, engine, true, null, textureType, undefined, undefined, undefined, textureFormat);\n kernelBlurYPostprocess.samples = this._samples;\n kernelBlurYPostprocess.onApplyObservable.add((effect) => {\n effect.setInt(\"filterSize\", this.blurFilterSize);\n effect.setFloat2(\"blurDir\", 0, 1 / this._blurTextureSizeY);\n this._postProcessRunningIndex++;\n });\n kernelBlurYPostprocess.onSizeChangedObservable.add(() => {\n kernelBlurYPostprocess._textures.forEach((rt) => {\n rt.texture.wrapU = Texture.CLAMP_ADDRESSMODE;\n rt.texture.wrapV = Texture.CLAMP_ADDRESSMODE;\n });\n });\n this._fixReusablePostProcess(kernelBlurYPostprocess);\n kernelBlurXPostprocess.autoClear = false;\n kernelBlurYPostprocess.autoClear = false;\n const blurList = [];\n for (let i = 0; i < this._blurNumIterations * 2; ++i) {\n blurList[i] = i & 1 ? kernelBlurYPostprocess : kernelBlurXPostprocess;\n }\n return [rtBlur, texture, blurList];\n }\n else {\n const uniforms = [\"maxFilterSize\", \"blurDir\", \"projectedParticleConstant\", \"depthThreshold\"];\n const kernelBlurXPostprocess = new PostProcess(\"BilateralBlurX\", \"fluidRenderingBilateralBlur\", uniforms, null, 1, null, 1, engine, true, null, textureType, undefined, undefined, undefined, textureFormat);\n kernelBlurXPostprocess.samples = this._samples;\n kernelBlurXPostprocess.externalTextureSamplerBinding = true;\n kernelBlurXPostprocess.onApplyObservable.add((effect) => {\n if (this._postProcessRunningIndex === 0) {\n effect.setTexture(\"textureSampler\", textureBlurSource);\n }\n else {\n effect._bindTexture(\"textureSampler\", kernelBlurXPostprocess.inputTexture.texture);\n }\n effect.setInt(\"maxFilterSize\", this.blurMaxFilterSize);\n effect.setFloat2(\"blurDir\", 1 / this._blurTextureSizeX, 0);\n effect.setFloat(\"projectedParticleConstant\", this._getProjectedParticleConstant());\n effect.setFloat(\"depthThreshold\", this._getDepthThreshold());\n this._postProcessRunningIndex++;\n });\n kernelBlurXPostprocess.onSizeChangedObservable.add(() => {\n kernelBlurXPostprocess._textures.forEach((rt) => {\n rt.texture.wrapU = Texture.CLAMP_ADDRESSMODE;\n rt.texture.wrapV = Texture.CLAMP_ADDRESSMODE;\n });\n });\n this._fixReusablePostProcess(kernelBlurXPostprocess);\n const kernelBlurYPostprocess = new PostProcess(\"BilateralBlurY\", \"fluidRenderingBilateralBlur\", uniforms, null, 1, null, 1, engine, true, null, textureType, undefined, undefined, undefined, textureFormat);\n kernelBlurYPostprocess.samples = this._samples;\n kernelBlurYPostprocess.onApplyObservable.add((effect) => {\n effect.setInt(\"maxFilterSize\", this.blurMaxFilterSize);\n effect.setFloat2(\"blurDir\", 0, 1 / this._blurTextureSizeY);\n effect.setFloat(\"projectedParticleConstant\", this._getProjectedParticleConstant());\n effect.setFloat(\"depthThreshold\", this._getDepthThreshold());\n this._postProcessRunningIndex++;\n });\n kernelBlurYPostprocess.onSizeChangedObservable.add(() => {\n kernelBlurYPostprocess._textures.forEach((rt) => {\n rt.texture.wrapU = Texture.CLAMP_ADDRESSMODE;\n rt.texture.wrapV = Texture.CLAMP_ADDRESSMODE;\n });\n });\n this._fixReusablePostProcess(kernelBlurYPostprocess);\n kernelBlurXPostprocess.autoClear = false;\n kernelBlurYPostprocess.autoClear = false;\n const blurList = [];\n for (let i = 0; i < this._blurNumIterations * 2; ++i) {\n blurList[i] = i & 1 ? kernelBlurYPostprocess : kernelBlurXPostprocess;\n }\n return [rtBlur, texture, blurList];\n }\n }\n _fixReusablePostProcess(pp) {\n if (!pp.isReusable()) {\n return;\n }\n pp.onActivateObservable.add(() => {\n // undo what calling activate() does which will make sure we will retrieve the right texture when getting the input for the post process\n pp._currentRenderTextureInd = (pp._currentRenderTextureInd + 1) % 2;\n });\n pp.onApplyObservable.add(() => {\n // now we can advance to the next texture\n pp._currentRenderTextureInd = (pp._currentRenderTextureInd + 1) % 2;\n });\n }\n _getProjectedParticleConstant() {\n var _a, _b;\n return (this.blurFilterSize * this.particleSize * 0.05 * (this._height / 2)) / Math.tan(((_b = (_a = this._camera) === null || _a === void 0 ? void 0 : _a.fov) !== null && _b !== void 0 ? _b : (45 * Math.PI) / 180) / 2);\n }\n _getDepthThreshold() {\n return (this.particleSize / 2) * this.blurDepthScale;\n }\n dispose() {\n var _a, _b, _c, _d;\n if (this.onDisposeObservable.hasObservers()) {\n this.onDisposeObservable.notifyObservers(this);\n }\n (_a = this._rt) === null || _a === void 0 ? void 0 : _a.dispose();\n this._rt = null;\n (_b = this._texture) === null || _b === void 0 ? void 0 : _b.dispose();\n this._texture = null;\n (_c = this._rtBlur) === null || _c === void 0 ? void 0 : _c.dispose();\n this._rtBlur = null;\n (_d = this._textureBlurred) === null || _d === void 0 ? void 0 : _d.dispose();\n this._textureBlurred = null;\n if (this._blurPostProcesses) {\n this._blurPostProcesses[0].dispose();\n this._blurPostProcesses[1].dispose();\n }\n this._blurPostProcesses = null;\n }\n}\n//# sourceMappingURL=fluidRenderingTextures.js.map","\nimport { Color3, Color4 } from \"../../Maths/math.color.js\";\nimport { Matrix, Vector2, Vector3 } from \"../../Maths/math.vector.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { PostProcess } from \"../../PostProcesses/postProcess.js\";\nimport { FluidRenderingTextures } from \"./fluidRenderingTextures.js\";\n/**\n * Textures that can be displayed as a debugging tool\n */\nexport var FluidRenderingDebug;\n(function (FluidRenderingDebug) {\n FluidRenderingDebug[FluidRenderingDebug[\"DepthTexture\"] = 0] = \"DepthTexture\";\n FluidRenderingDebug[FluidRenderingDebug[\"DepthBlurredTexture\"] = 1] = \"DepthBlurredTexture\";\n FluidRenderingDebug[FluidRenderingDebug[\"ThicknessTexture\"] = 2] = \"ThicknessTexture\";\n FluidRenderingDebug[FluidRenderingDebug[\"ThicknessBlurredTexture\"] = 3] = \"ThicknessBlurredTexture\";\n FluidRenderingDebug[FluidRenderingDebug[\"DiffuseTexture\"] = 4] = \"DiffuseTexture\";\n FluidRenderingDebug[FluidRenderingDebug[\"Normals\"] = 5] = \"Normals\";\n FluidRenderingDebug[FluidRenderingDebug[\"DiffuseRendering\"] = 6] = \"DiffuseRendering\";\n})(FluidRenderingDebug || (FluidRenderingDebug = {}));\n/**\n * Class used to render an object as a fluid thanks to different render target textures (depth, thickness, diffuse)\n */\nexport class FluidRenderingTargetRenderer {\n /**\n * Returns true if the class needs to be reinitialized (because of changes in parameterization)\n */\n get needInitialization() {\n return this._needInitialization;\n }\n /**\n * Gets or sets a boolean indicating that the diffuse texture should be generated and used for the rendering\n */\n get generateDiffuseTexture() {\n return this._generateDiffuseTexture;\n }\n set generateDiffuseTexture(generate) {\n if (this._generateDiffuseTexture === generate) {\n return;\n }\n this._generateDiffuseTexture = generate;\n this._needInitialization = true;\n }\n /**\n * Gets or sets the feature (texture) to be debugged. Not used if debug is false\n */\n get debugFeature() {\n return this._debugFeature;\n }\n set debugFeature(feature) {\n if (this._debugFeature === feature) {\n return;\n }\n this._needInitialization = true;\n this._debugFeature = feature;\n }\n /**\n * Gets or sets a boolean indicating if we should display a specific texture (given by debugFeature) for debugging purpose\n */\n get debug() {\n return this._debug;\n }\n set debug(debug) {\n if (this._debug === debug) {\n return;\n }\n this._debug = debug;\n this._needInitialization = true;\n }\n /**\n * Gets or sets the environment map used for the reflection part of the shading\n * If null, no map will be used. If undefined, the scene.environmentMap will be used (if defined)\n */\n get environmentMap() {\n return this._environmentMap;\n }\n set environmentMap(map) {\n if (this._environmentMap === map) {\n return;\n }\n this._needInitialization = true;\n this._environmentMap = map;\n }\n /**\n * Gets or sets a boolean indicating that the depth texture should be blurred\n */\n get enableBlurDepth() {\n return this._enableBlurDepth;\n }\n set enableBlurDepth(enable) {\n if (this._enableBlurDepth === enable) {\n return;\n }\n this._enableBlurDepth = enable;\n this._needInitialization = true;\n }\n /**\n * Gets or sets the depth size divisor (positive number, generally between 1 and 4), which is used as a divisor when creating the texture used for blurring the depth\n * For eg. if blurDepthSizeDivisor=2, the texture used to blur the depth will be half the size of the depth texture\n */\n get blurDepthSizeDivisor() {\n return this._blurDepthSizeDivisor;\n }\n set blurDepthSizeDivisor(scale) {\n if (this._blurDepthSizeDivisor === scale) {\n return;\n }\n this._blurDepthSizeDivisor = scale;\n this._needInitialization = true;\n }\n /**\n * Size of the kernel used to filter the depth blur texture (positive number, generally between 1 and 20 - higher values will require more processing power from the GPU)\n */\n get blurDepthFilterSize() {\n return this._blurDepthFilterSize;\n }\n set blurDepthFilterSize(filterSize) {\n if (this._blurDepthFilterSize === filterSize) {\n return;\n }\n this._blurDepthFilterSize = filterSize;\n this._setBlurParameters();\n }\n /**\n * Number of blurring iterations used to generate the depth blur texture (positive number, generally between 1 and 10 - higher values will require more processing power from the GPU)\n */\n get blurDepthNumIterations() {\n return this._blurDepthNumIterations;\n }\n set blurDepthNumIterations(numIterations) {\n if (this._blurDepthNumIterations === numIterations) {\n return;\n }\n this._blurDepthNumIterations = numIterations;\n this._setBlurParameters();\n }\n /**\n * Maximum size of the kernel used to blur the depth texture (positive number, generally between 1 and 200 - higher values will require more processing power from the GPU when the particles are larger on screen)\n */\n get blurDepthMaxFilterSize() {\n return this._blurDepthMaxFilterSize;\n }\n set blurDepthMaxFilterSize(maxFilterSize) {\n if (this._blurDepthMaxFilterSize === maxFilterSize) {\n return;\n }\n this._blurDepthMaxFilterSize = maxFilterSize;\n this._setBlurParameters();\n }\n /**\n * Depth weight in the calculation when applying the bilateral blur to generate the depth blur texture (positive number, generally between 0 and 100)\n */\n get blurDepthDepthScale() {\n return this._blurDepthDepthScale;\n }\n set blurDepthDepthScale(scale) {\n if (this._blurDepthDepthScale === scale) {\n return;\n }\n this._blurDepthDepthScale = scale;\n this._setBlurParameters();\n }\n /**\n * Gets or sets a boolean indicating that the thickness texture should be blurred\n */\n get enableBlurThickness() {\n return this._enableBlurThickness;\n }\n set enableBlurThickness(enable) {\n if (this._enableBlurThickness === enable) {\n return;\n }\n this._enableBlurThickness = enable;\n this._needInitialization = true;\n }\n /**\n * Gets or sets the thickness size divisor (positive number, generally between 1 and 4), which is used as a divisor when creating the texture used for blurring the thickness\n * For eg. if blurThicknessSizeDivisor=2, the texture used to blur the thickness will be half the size of the thickness texture\n */\n get blurThicknessSizeDivisor() {\n return this._blurThicknessSizeDivisor;\n }\n set blurThicknessSizeDivisor(scale) {\n if (this._blurThicknessSizeDivisor === scale) {\n return;\n }\n this._blurThicknessSizeDivisor = scale;\n this._needInitialization = true;\n }\n /**\n * Size of the kernel used to filter the thickness blur texture (positive number, generally between 1 and 20 - higher values will require more processing power from the GPU)\n */\n get blurThicknessFilterSize() {\n return this._blurThicknessFilterSize;\n }\n set blurThicknessFilterSize(filterSize) {\n if (this._blurThicknessFilterSize === filterSize) {\n return;\n }\n this._blurThicknessFilterSize = filterSize;\n this._setBlurParameters();\n }\n /**\n * Number of blurring iterations used to generate the thickness blur texture (positive number, generally between 1 and 10 - higher values will require more processing power from the GPU)\n */\n get blurThicknessNumIterations() {\n return this._blurThicknessNumIterations;\n }\n set blurThicknessNumIterations(numIterations) {\n if (this._blurThicknessNumIterations === numIterations) {\n return;\n }\n this._blurThicknessNumIterations = numIterations;\n this._setBlurParameters();\n }\n /**\n * Gets or sets a boolean indicating that a fixed thickness should be used instead of generating a thickness texture\n */\n get useFixedThickness() {\n return this._useFixedThickness;\n }\n set useFixedThickness(use) {\n if (this._useFixedThickness === use) {\n return;\n }\n this._useFixedThickness = use;\n this._needInitialization = true;\n }\n /**\n * Gets or sets a boolean indicating that the velocity should be used when rendering the particles as a fluid.\n * Note: the vertex buffers must contain a \"velocity\" buffer for this to work!\n */\n get useVelocity() {\n return this._useVelocity;\n }\n set useVelocity(use) {\n if (this._useVelocity === use) {\n return;\n }\n this._useVelocity = use;\n this._needInitialization = true;\n this._onUseVelocityChanged.notifyObservers(this);\n }\n /**\n * Defines the size of the depth texture.\n * If null, the texture will have the size of the screen\n */\n get depthMapSize() {\n return this._depthMapSize;\n }\n set depthMapSize(size) {\n if (this._depthMapSize === size) {\n return;\n }\n this._depthMapSize = size;\n this._needInitialization = true;\n }\n /**\n * Defines the size of the thickness texture.\n * If null, the texture will have the size of the screen\n */\n get thicknessMapSize() {\n return this._thicknessMapSize;\n }\n set thicknessMapSize(size) {\n if (this._thicknessMapSize === size) {\n return;\n }\n this._thicknessMapSize = size;\n this._needInitialization = true;\n }\n /**\n * Defines the size of the diffuse texture.\n * If null, the texture will have the size of the screen\n */\n get diffuseMapSize() {\n return this._diffuseMapSize;\n }\n set diffuseMapSize(size) {\n if (this._diffuseMapSize === size) {\n return;\n }\n this._diffuseMapSize = size;\n this._needInitialization = true;\n }\n /**\n * Gets or sets the number of samples used by MSAA\n * Note: changing this value in WebGL does not work because depth/stencil textures can't be created with MSAA (see https://github.com/BabylonJS/Babylon.js/issues/12444)\n */\n get samples() {\n return this._samples;\n }\n set samples(samples) {\n if (this._samples === samples) {\n return;\n }\n this._samples = samples;\n this._needInitialization = true;\n }\n /**\n * Gets the camera used for the rendering\n */\n get camera() {\n return this._camera;\n }\n /**\n * Creates an instance of the class\n * @param scene Scene used to render the fluid object into\n * @param camera Camera used to render the fluid object. If not provided, use the active camera of the scene instead\n */\n constructor(scene, camera) {\n this._generateDiffuseTexture = false;\n /**\n * Fluid color. Not used if generateDiffuseTexture is true\n */\n this.fluidColor = new Color3(0.085, 0.6375, 0.765);\n /**\n * Density of the fluid (positive number). The higher the value, the more opaque the fluid.\n */\n this.density = 2;\n /**\n * Strength of the refraction (positive number, but generally between 0 and 0.3).\n */\n this.refractionStrength = 0.1;\n /**\n * Strength of the fresnel effect (value between 0 and 1). Lower the value if you want to soften the specular effect\n */\n this.fresnelClamp = 1.0;\n /**\n * Strength of the specular power (positive number). Increase the value to make the specular effect more concentrated\n */\n this.specularPower = 250;\n /**\n * Minimum thickness of the particles (positive number). If useFixedThickness is true, minimumThickness is the thickness used\n */\n this.minimumThickness = 0;\n /**\n * Direction of the light. The fluid is assumed to be lit by a directional light\n */\n this.dirLight = new Vector3(-2, -1, 1).normalize();\n this._debugFeature = FluidRenderingDebug.DepthBlurredTexture;\n this._debug = false;\n this._enableBlurDepth = true;\n this._blurDepthSizeDivisor = 1;\n this._blurDepthFilterSize = 7;\n this._blurDepthNumIterations = 3;\n this._blurDepthMaxFilterSize = 100;\n this._blurDepthDepthScale = 10;\n this._enableBlurThickness = true;\n this._blurThicknessSizeDivisor = 1;\n this._blurThicknessFilterSize = 5;\n this._blurThicknessNumIterations = 1;\n this._useFixedThickness = false;\n /** @internal */\n this._onUseVelocityChanged = new Observable();\n this._useVelocity = false;\n this._depthMapSize = null;\n this._thicknessMapSize = null;\n this._diffuseMapSize = null;\n this._samples = 1;\n this._scene = scene;\n this._engine = scene.getEngine();\n this._camera = camera !== null && camera !== void 0 ? camera : scene.activeCamera;\n this._needInitialization = true;\n this._bgDepthTexture = null;\n this._invProjectionMatrix = new Matrix();\n this._depthClearColor = new Color4(1e6, 1e6, 1e6, 1);\n this._thicknessClearColor = new Color4(0, 0, 0, 1);\n this._depthRenderTarget = null;\n this._diffuseRenderTarget = null;\n this._thicknessRenderTarget = null;\n this._renderPostProcess = null;\n }\n /** @internal */\n _initialize() {\n var _a, _b, _c;\n this.dispose();\n this._needInitialization = false;\n const depthWidth = (_a = this._depthMapSize) !== null && _a !== void 0 ? _a : this._engine.getRenderWidth();\n const depthHeight = this._depthMapSize !== null ? Math.round((this._depthMapSize * this._engine.getRenderHeight()) / this._engine.getRenderWidth()) : this._engine.getRenderHeight();\n this._depthRenderTarget = new FluidRenderingTextures(\"Depth\", this._scene, depthWidth, depthHeight, depthWidth, depthHeight, 1, 7, 1, 7, false, this._camera, true, this._samples);\n this._initializeRenderTarget(this._depthRenderTarget);\n if (this.generateDiffuseTexture) {\n const diffuseWidth = (_b = this._diffuseMapSize) !== null && _b !== void 0 ? _b : this._engine.getRenderWidth();\n const diffuseHeight = this._diffuseMapSize !== null\n ? Math.round((this._diffuseMapSize * this._engine.getRenderHeight()) / this._engine.getRenderWidth())\n : this._engine.getRenderHeight();\n this._diffuseRenderTarget = new FluidRenderingTextures(\"Diffuse\", this._scene, diffuseWidth, diffuseHeight, 0, 0, 0, 5, 0, 5, true, this._camera, true, this._samples);\n this._initializeRenderTarget(this._diffuseRenderTarget);\n }\n const thicknessWidth = (_c = this._thicknessMapSize) !== null && _c !== void 0 ? _c : this._engine.getRenderWidth();\n const thicknessHeight = this._thicknessMapSize !== null\n ? Math.round((this._thicknessMapSize * this._engine.getRenderHeight()) / this._engine.getRenderWidth())\n : this._engine.getRenderHeight();\n if (!this._useFixedThickness) {\n this._thicknessRenderTarget = new FluidRenderingTextures(\"Thickness\", this._scene, thicknessWidth, thicknessHeight, thicknessWidth, thicknessHeight, 2, 6, 2, 6, true, this._camera, false, this._samples);\n this._initializeRenderTarget(this._thicknessRenderTarget);\n }\n this._createLiquidRenderingPostProcess();\n }\n _setBlurParameters(renderTarget = null) {\n if (renderTarget === null || renderTarget === this._depthRenderTarget) {\n this._setBlurDepthParameters();\n }\n if (renderTarget === null || renderTarget === this._thicknessRenderTarget) {\n this._setBlurThicknessParameters();\n }\n }\n _setBlurDepthParameters() {\n if (!this._depthRenderTarget) {\n return;\n }\n this._depthRenderTarget.blurFilterSize = this.blurDepthFilterSize;\n this._depthRenderTarget.blurMaxFilterSize = this.blurDepthMaxFilterSize;\n this._depthRenderTarget.blurNumIterations = this.blurDepthNumIterations;\n this._depthRenderTarget.blurDepthScale = this.blurDepthDepthScale;\n }\n _setBlurThicknessParameters() {\n if (!this._thicknessRenderTarget) {\n return;\n }\n this._thicknessRenderTarget.blurFilterSize = this.blurThicknessFilterSize;\n this._thicknessRenderTarget.blurNumIterations = this.blurThicknessNumIterations;\n }\n _initializeRenderTarget(renderTarget) {\n if (renderTarget !== this._diffuseRenderTarget) {\n renderTarget.enableBlur = renderTarget === this._depthRenderTarget ? this.enableBlurDepth : this.enableBlurThickness;\n renderTarget.blurSizeDivisor = renderTarget === this._depthRenderTarget ? this.blurDepthSizeDivisor : this.blurThicknessSizeDivisor;\n }\n this._setBlurParameters(renderTarget);\n renderTarget.initialize();\n }\n _createLiquidRenderingPostProcess() {\n var _a;\n const engine = this._scene.getEngine();\n const uniformNames = [\n \"viewMatrix\",\n \"projectionMatrix\",\n \"invProjectionMatrix\",\n \"texelSize\",\n \"dirLight\",\n \"cameraFar\",\n \"density\",\n \"refractionStrength\",\n \"fresnelClamp\",\n \"specularPower\",\n ];\n const samplerNames = [\"depthSampler\"];\n const defines = [];\n this.dispose(true);\n if (!this._camera) {\n return;\n }\n const texture = this._depthRenderTarget.enableBlur ? this._depthRenderTarget.textureBlur : this._depthRenderTarget.texture;\n const texelSize = new Vector2(1 / texture.getSize().width, 1 / texture.getSize().height);\n if (this._scene.useRightHandedSystem) {\n defines.push(\"#define FLUIDRENDERING_RHS\");\n }\n if (this._environmentMap !== null) {\n const envMap = (_a = this._environmentMap) !== null && _a !== void 0 ? _a : this._scene.environmentTexture;\n if (envMap) {\n samplerNames.push(\"reflectionSampler\");\n defines.push(\"#define FLUIDRENDERING_ENVIRONMENT\");\n }\n }\n if (this._diffuseRenderTarget) {\n samplerNames.push(\"diffuseSampler\");\n defines.push(\"#define FLUIDRENDERING_DIFFUSETEXTURE\");\n }\n else {\n uniformNames.push(\"diffuseColor\");\n }\n if (this._useVelocity) {\n samplerNames.push(\"velocitySampler\");\n defines.push(\"#define FLUIDRENDERING_VELOCITY\");\n }\n if (this._useFixedThickness) {\n uniformNames.push(\"thickness\");\n samplerNames.push(\"bgDepthSampler\");\n defines.push(\"#define FLUIDRENDERING_FIXED_THICKNESS\");\n }\n else {\n uniformNames.push(\"minimumThickness\");\n samplerNames.push(\"thicknessSampler\");\n }\n if (this._debug) {\n defines.push(\"#define FLUIDRENDERING_DEBUG\");\n if (this._debugFeature === FluidRenderingDebug.Normals) {\n defines.push(\"#define FLUIDRENDERING_DEBUG_SHOWNORMAL\");\n }\n else if (this._debugFeature === FluidRenderingDebug.DiffuseRendering) {\n defines.push(\"#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING\");\n }\n else {\n defines.push(\"#define FLUIDRENDERING_DEBUG_TEXTURE\");\n samplerNames.push(\"debugSampler\");\n if (this._debugFeature === FluidRenderingDebug.DepthTexture || this._debugFeature === FluidRenderingDebug.DepthBlurredTexture) {\n defines.push(\"#define FLUIDRENDERING_DEBUG_DEPTH\");\n }\n }\n }\n this._renderPostProcess = new PostProcess(\"FluidRendering\", \"fluidRenderingRender\", uniformNames, samplerNames, 1, null, 2, engine, false, null, 0, undefined, undefined, true, undefined);\n this._renderPostProcess.updateEffect(defines.join(\"\\n\"));\n this._renderPostProcess.samples = this._samples;\n this._renderPostProcess.onApplyObservable.add((effect) => {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y;\n this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix());\n this._invProjectionMatrix.invert();\n if (engine.isWebGPU) {\n effect.setTextureSampler(\"textureSamplerSampler\", this._renderPostProcess.inputTexture.texture);\n }\n if (!this._depthRenderTarget.enableBlur) {\n effect.setTexture(\"depthSampler\", this._depthRenderTarget.texture);\n if (engine.isWebGPU) {\n effect.setTextureSampler(\"depthSamplerSampler\", (_b = (_a = this._depthRenderTarget.texture) === null || _a === void 0 ? void 0 : _a.getInternalTexture()) !== null && _b !== void 0 ? _b : null);\n }\n }\n else {\n effect.setTexture(\"depthSampler\", this._depthRenderTarget.textureBlur);\n if (engine.isWebGPU) {\n effect.setTextureSampler(\"depthSamplerSampler\", (_d = (_c = this._depthRenderTarget.textureBlur) === null || _c === void 0 ? void 0 : _c.getInternalTexture()) !== null && _d !== void 0 ? _d : null);\n }\n }\n if (this._diffuseRenderTarget) {\n if (!this._diffuseRenderTarget.enableBlur) {\n effect.setTexture(\"diffuseSampler\", this._diffuseRenderTarget.texture);\n if (engine.isWebGPU) {\n effect.setTextureSampler(\"diffuseSamplerSampler\", (_f = (_e = this._diffuseRenderTarget.texture) === null || _e === void 0 ? void 0 : _e.getInternalTexture()) !== null && _f !== void 0 ? _f : null);\n }\n }\n else {\n effect.setTexture(\"diffuseSampler\", this._diffuseRenderTarget.textureBlur);\n if (engine.isWebGPU) {\n effect.setTextureSampler(\"diffuseSamplerSampler\", (_h = (_g = this._diffuseRenderTarget.textureBlur) === null || _g === void 0 ? void 0 : _g.getInternalTexture()) !== null && _h !== void 0 ? _h : null);\n }\n }\n }\n else {\n effect.setColor3(\"diffuseColor\", this.fluidColor);\n }\n if (this._useFixedThickness) {\n effect.setFloat(\"thickness\", this.minimumThickness);\n effect._bindTexture(\"bgDepthSampler\", this._bgDepthTexture);\n if (engine.isWebGPU) {\n effect.setTextureSampler(\"bgDepthSamplerSampler\", (_j = this._bgDepthTexture) !== null && _j !== void 0 ? _j : null);\n }\n }\n else {\n if (!this._thicknessRenderTarget.enableBlur) {\n effect.setTexture(\"thicknessSampler\", this._thicknessRenderTarget.texture);\n if (engine.isWebGPU) {\n effect.setTextureSampler(\"thicknessSamplerSampler\", (_l = (_k = this._thicknessRenderTarget.texture) === null || _k === void 0 ? void 0 : _k.getInternalTexture()) !== null && _l !== void 0 ? _l : null);\n }\n }\n else {\n effect.setTexture(\"thicknessSampler\", this._thicknessRenderTarget.textureBlur);\n if (engine.isWebGPU) {\n effect.setTextureSampler(\"thicknessSamplerSampler\", (_o = (_m = this._thicknessRenderTarget.textureBlur) === null || _m === void 0 ? void 0 : _m.getInternalTexture()) !== null && _o !== void 0 ? _o : null);\n }\n }\n effect.setFloat(\"minimumThickness\", this.minimumThickness);\n }\n if (this._environmentMap !== null) {\n const envMap = (_p = this._environmentMap) !== null && _p !== void 0 ? _p : this._scene.environmentTexture;\n if (envMap) {\n effect.setTexture(\"reflectionSampler\", envMap);\n if (engine.isWebGPU) {\n effect.setTextureSampler(\"reflectionSamplerSampler\", (_q = envMap === null || envMap === void 0 ? void 0 : envMap.getInternalTexture()) !== null && _q !== void 0 ? _q : null);\n }\n }\n }\n effect.setMatrix(\"viewMatrix\", this._scene.getViewMatrix());\n effect.setMatrix(\"invProjectionMatrix\", this._invProjectionMatrix);\n effect.setMatrix(\"projectionMatrix\", this._scene.getProjectionMatrix());\n effect.setVector2(\"texelSize\", texelSize);\n effect.setFloat(\"density\", this.density);\n effect.setFloat(\"refractionStrength\", this.refractionStrength);\n effect.setFloat(\"fresnelClamp\", this.fresnelClamp);\n effect.setFloat(\"specularPower\", this.specularPower);\n effect.setVector3(\"dirLight\", this.dirLight);\n effect.setFloat(\"cameraFar\", this._camera.maxZ);\n if (this._debug) {\n let texture = null;\n switch (this._debugFeature) {\n case FluidRenderingDebug.DepthTexture:\n texture = this._depthRenderTarget.texture;\n break;\n case FluidRenderingDebug.DepthBlurredTexture:\n texture = this._depthRenderTarget.enableBlur ? this._depthRenderTarget.textureBlur : this._depthRenderTarget.texture;\n break;\n case FluidRenderingDebug.ThicknessTexture:\n texture = (_s = (_r = this._thicknessRenderTarget) === null || _r === void 0 ? void 0 : _r.texture) !== null && _s !== void 0 ? _s : null;\n break;\n case FluidRenderingDebug.ThicknessBlurredTexture:\n texture = ((_t = this._thicknessRenderTarget) === null || _t === void 0 ? void 0 : _t.enableBlur) ? (_v = (_u = this._thicknessRenderTarget) === null || _u === void 0 ? void 0 : _u.textureBlur) !== null && _v !== void 0 ? _v : null : (_x = (_w = this._thicknessRenderTarget) === null || _w === void 0 ? void 0 : _w.texture) !== null && _x !== void 0 ? _x : null;\n break;\n case FluidRenderingDebug.DiffuseTexture:\n if (this._diffuseRenderTarget) {\n texture = this._diffuseRenderTarget.texture;\n }\n break;\n }\n if (this._debugFeature !== FluidRenderingDebug.Normals) {\n effect.setTexture(\"debugSampler\", texture);\n if (engine.isWebGPU) {\n effect.setTextureSampler(\"debugSamplerSampler\", (_y = texture === null || texture === void 0 ? void 0 : texture.getInternalTexture()) !== null && _y !== void 0 ? _y : null);\n }\n }\n }\n });\n }\n /** @internal */\n _clearTargets() {\n var _a, _b, _c;\n if ((_a = this._depthRenderTarget) === null || _a === void 0 ? void 0 : _a.renderTarget) {\n this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget);\n this._engine.clear(this._depthClearColor, true, true, false);\n this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget);\n }\n if ((_b = this._diffuseRenderTarget) === null || _b === void 0 ? void 0 : _b.renderTarget) {\n this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget);\n this._engine.clear(this._thicknessClearColor, true, true, false);\n this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget);\n }\n if ((_c = this._thicknessRenderTarget) === null || _c === void 0 ? void 0 : _c.renderTarget) {\n this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget);\n // we don't clear the depth buffer because it is the depth buffer that is coming from the scene and that we reuse in the thickness rendering pass\n this._engine.clear(this._thicknessClearColor, true, false, false);\n this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget);\n }\n }\n /** @internal */\n _render(fluidObject) {\n var _a, _b, _c, _d, _e, _f;\n if (this._needInitialization || !fluidObject.isReady()) {\n return;\n }\n const currentRenderTarget = this._engine._currentRenderTarget;\n this._engine.setState(false, undefined, undefined, undefined, true);\n this._engine.setDepthBuffer(true);\n this._engine.setDepthWrite(true);\n this._engine.setAlphaMode(0);\n // Render the particles in the depth texture\n if ((_a = this._depthRenderTarget) === null || _a === void 0 ? void 0 : _a.renderTarget) {\n this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget);\n fluidObject.renderDepthTexture();\n this._engine.unbindInstanceAttributes();\n this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget);\n }\n // Render the particles in the diffuse texture\n if ((_b = this._diffuseRenderTarget) === null || _b === void 0 ? void 0 : _b.renderTarget) {\n this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget);\n fluidObject.renderDiffuseTexture();\n this._engine.unbindInstanceAttributes();\n this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget);\n }\n // Render the particles in the thickness texture\n if ((_c = this._thicknessRenderTarget) === null || _c === void 0 ? void 0 : _c.renderTarget) {\n this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget);\n fluidObject.renderThicknessTexture();\n this._engine.unbindInstanceAttributes();\n this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget);\n }\n // Run the blur post processes\n (_d = this._depthRenderTarget) === null || _d === void 0 ? void 0 : _d.applyBlurPostProcesses();\n (_e = this._diffuseRenderTarget) === null || _e === void 0 ? void 0 : _e.applyBlurPostProcesses();\n (_f = this._thicknessRenderTarget) === null || _f === void 0 ? void 0 : _f.applyBlurPostProcesses();\n if (currentRenderTarget) {\n this._engine.bindFramebuffer(currentRenderTarget);\n }\n }\n /**\n * Releases all the ressources used by the class\n * @param onlyPostProcesses If true, releases only the ressources used by the render post processes\n */\n dispose(onlyPostProcesses = false) {\n var _a, _b, _c, _d;\n if (!onlyPostProcesses) {\n (_a = this._depthRenderTarget) === null || _a === void 0 ? void 0 : _a.dispose();\n this._depthRenderTarget = null;\n (_b = this._diffuseRenderTarget) === null || _b === void 0 ? void 0 : _b.dispose();\n this._diffuseRenderTarget = null;\n (_c = this._thicknessRenderTarget) === null || _c === void 0 ? void 0 : _c.dispose();\n this._thicknessRenderTarget = null;\n }\n if (this._renderPostProcess && this._camera) {\n this._camera.detachPostProcess(this._renderPostProcess);\n }\n (_d = this._renderPostProcess) === null || _d === void 0 ? void 0 : _d.dispose();\n this._renderPostProcess = null;\n this._needInitialization = false;\n }\n}\n//# sourceMappingURL=fluidRenderingTargetRenderer.js.map","import { VertexBuffer } from \"../../Buffers/buffer.js\";\n\nimport { EffectWrapper } from \"../../Materials/effectRenderer.js\";\nimport { FluidRenderingObject } from \"./fluidRenderingObject.js\";\n/**\n * Defines a rendering object based on a list of custom buffers\n * The list must contain at least a \"position\" buffer!\n */\nexport class FluidRenderingObjectCustomParticles extends FluidRenderingObject {\n /**\n * Gets the name of the class\n */\n getClassName() {\n return \"FluidRenderingObjectCustomParticles\";\n }\n /**\n * Gets the vertex buffers\n */\n get vertexBuffers() {\n return this._vertexBuffers;\n }\n /**\n * Creates a new instance of the class\n * @param scene The scene the particles should be rendered into\n * @param buffers The list of buffers (must contain at least one \"position\" buffer!). Note that you don't have to pass all (or any!) buffers at once in the constructor, you can use the addBuffers method to add more later.\n * @param numParticles Number of vertices to take into account from the buffers\n */\n constructor(scene, buffers, numParticles) {\n super(scene);\n this._numParticles = numParticles;\n this._diffuseEffectWrapper = null;\n this._vertexBuffers = {};\n this.addBuffers(buffers);\n }\n /**\n * Add some new buffers\n * @param buffers List of buffers\n */\n addBuffers(buffers) {\n for (const name in buffers) {\n let stride;\n let instanced = true;\n switch (name) {\n case \"velocity\":\n stride = 3;\n break;\n case \"offset\":\n instanced = false;\n break;\n }\n this._vertexBuffers[name] = new VertexBuffer(this._engine, buffers[name], name, true, false, stride, instanced);\n }\n }\n _createEffects() {\n super._createEffects();\n const uniformNames = [\"view\", \"projection\", \"size\"];\n const attributeNames = [\"position\", \"offset\", \"color\"];\n this._diffuseEffectWrapper = new EffectWrapper({\n engine: this._engine,\n useShaderStore: true,\n vertexShader: \"fluidRenderingParticleDiffuse\",\n fragmentShader: \"fluidRenderingParticleDiffuse\",\n attributeNames,\n uniformNames,\n samplerNames: [],\n });\n }\n /**\n * Indicates if the object is ready to be rendered\n * @returns True if everything is ready for the object to be rendered, otherwise false\n */\n isReady() {\n var _a, _b;\n if (!this._vertexBuffers[\"offset\"]) {\n this._vertexBuffers[\"offset\"] = new VertexBuffer(this._engine, [0, 0, 1, 0, 0, 1, 1, 1], \"offset\", false, false, 2);\n }\n return super.isReady() && ((_b = (_a = this._diffuseEffectWrapper) === null || _a === void 0 ? void 0 : _a.effect.isReady()) !== null && _b !== void 0 ? _b : false);\n }\n /**\n * Gets the number of particles in this object\n * @returns The number of particles\n */\n get numParticles() {\n return this._numParticles;\n }\n /**\n * Sets the number of particles in this object\n * @param num The number of particles to take into account\n */\n setNumParticles(num) {\n this._numParticles = num;\n }\n /**\n * Render the diffuse texture for this object\n */\n renderDiffuseTexture() {\n const numParticles = this.numParticles;\n if (!this._diffuseEffectWrapper || numParticles === 0) {\n return;\n }\n const diffuseDrawWrapper = this._diffuseEffectWrapper._drawWrapper;\n const diffuseEffect = diffuseDrawWrapper.effect;\n this._engine.enableEffect(diffuseDrawWrapper);\n this._engine.bindBuffers(this.vertexBuffers, this.indexBuffer, diffuseEffect);\n diffuseEffect.setMatrix(\"view\", this._scene.getViewMatrix());\n diffuseEffect.setMatrix(\"projection\", this._scene.getProjectionMatrix());\n if (this._particleSize !== null) {\n diffuseEffect.setFloat2(\"size\", this._particleSize, this._particleSize);\n }\n if (this.useInstancing) {\n this._engine.drawArraysType(7, 0, 4, numParticles);\n }\n else {\n this._engine.drawElementsType(0, 0, numParticles);\n }\n }\n /**\n * Releases the ressources used by the class\n */\n dispose() {\n var _a;\n super.dispose();\n (_a = this._diffuseEffectWrapper) === null || _a === void 0 ? void 0 : _a.dispose();\n for (const name in this._vertexBuffers) {\n this._vertexBuffers[name].dispose();\n }\n this._vertexBuffers = {};\n }\n}\n//# sourceMappingURL=fluidRenderingObjectCustomParticles.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/helperFunctions.js\";\nconst name = \"copyTextureToTexturePixelShader\";\nconst shader = `uniform float conversion;\runiform sampler2D textureSampler;\rvarying vec2 vUV;\r#include\nvoid main(void) \r{\rvec4 color=texture2D(textureSampler,vUV);\r#ifdef DEPTH_TEXTURE\ngl_FragDepth=color.r;\r#else\nif (conversion==1.) {\rcolor=toLinearSpace(color);\r} else if (conversion==2.) {\rcolor=toGammaSpace(color);\r}\rgl_FragColor=color;\r#endif\n}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const copyTextureToTexturePixelShader = { name, shader };\n//# sourceMappingURL=copyTextureToTexture.fragment.js.map","import { EffectRenderer, EffectWrapper } from \"../Materials/effectRenderer.js\";\n\nimport \"../Shaders/copyTextureToTexture.fragment.js\";\n/**\n * Conversion modes available when copying a texture into another one\n */\nexport var ConversionMode;\n(function (ConversionMode) {\n ConversionMode[ConversionMode[\"None\"] = 0] = \"None\";\n ConversionMode[ConversionMode[\"ToLinearSpace\"] = 1] = \"ToLinearSpace\";\n ConversionMode[ConversionMode[\"ToGammaSpace\"] = 2] = \"ToGammaSpace\";\n})(ConversionMode || (ConversionMode = {}));\n/**\n * Class used for fast copy from one texture to another\n */\nexport class CopyTextureToTexture {\n _textureIsInternal(texture) {\n return texture.getInternalTexture === undefined;\n }\n /**\n * Constructs a new instance of the class\n * @param engine The engine to use for the copy\n * @param isDepthTexture True means that we should write (using gl_FragDepth) into the depth texture attached to the destination (default: false)\n */\n constructor(engine, isDepthTexture = false) {\n this._engine = engine;\n this._isDepthTexture = isDepthTexture;\n this._renderer = new EffectRenderer(engine);\n this._effectWrapper = new EffectWrapper({\n engine: engine,\n name: \"CopyTextureToTexture\",\n fragmentShader: \"copyTextureToTexture\",\n useShaderStore: true,\n uniformNames: [\"conversion\"],\n samplerNames: [\"textureSampler\"],\n defines: isDepthTexture ? [\"#define DEPTH_TEXTURE\"] : [],\n });\n this._effectWrapper.onApplyObservable.add(() => {\n if (isDepthTexture) {\n engine.setState(false);\n engine.setDepthBuffer(true);\n engine.depthCullingState.depthMask = true;\n engine.depthCullingState.depthFunc = 519;\n }\n if (this._textureIsInternal(this._source)) {\n this._effectWrapper.effect._bindTexture(\"textureSampler\", this._source);\n }\n else {\n this._effectWrapper.effect.setTexture(\"textureSampler\", this._source);\n }\n this._effectWrapper.effect.setFloat(\"conversion\", this._conversion);\n });\n }\n /**\n * Indicates if the effect is ready to be used for the copy\n * @returns true if \"copy\" can be called without delay, else false\n */\n isReady() {\n return this._effectWrapper.effect.isReady();\n }\n /**\n * Copy one texture into another\n * @param source The source texture\n * @param destination The destination texture\n * @param conversion The conversion mode that should be applied when copying\n * @returns\n */\n copy(source, destination, conversion = ConversionMode.None) {\n if (!this.isReady()) {\n return false;\n }\n this._source = source;\n this._conversion = conversion;\n const engineDepthFunc = this._engine.depthCullingState.depthFunc;\n this._renderer.render(this._effectWrapper, destination);\n if (this._isDepthTexture && engineDepthFunc) {\n this._engine.depthCullingState.depthFunc = engineDepthFunc;\n }\n return true;\n }\n /**\n * Releases all the resources used by the class\n */\n dispose() {\n this._effectWrapper.dispose();\n this._renderer.dispose();\n }\n}\n//# sourceMappingURL=copyTextureToTexture.js.map","\nimport { CopyTextureToTexture } from \"../../Misc/copyTextureToTexture.js\";\n/** @internal */\nexport class FluidRenderingDepthTextureCopy {\n get depthRTWrapper() {\n return this._depthRTWrapper;\n }\n constructor(engine, width, height, samples = 1) {\n this._engine = engine;\n this._copyTextureToTexture = new CopyTextureToTexture(engine, true);\n this._depthRTWrapper = this._engine.createRenderTargetTexture({ width, height }, {\n generateMipMaps: false,\n type: 0,\n format: 6,\n samplingMode: 1,\n generateDepthBuffer: true,\n generateStencilBuffer: false,\n samples,\n noColorAttachment: true,\n label: \"FluidRenderingDepthTextureCopyRTT\",\n });\n this._depthRTWrapper.createDepthStencilTexture(0, false, false, 1, undefined, \"FluidRenderingDepthTextureCopyRTTDepthStencil\");\n }\n copy(source) {\n return this._copyTextureToTexture.copy(source, this._depthRTWrapper);\n }\n dispose() {\n this._depthRTWrapper.dispose();\n this._copyTextureToTexture.dispose();\n }\n}\n//# sourceMappingURL=fluidRenderingDepthTextureCopy.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"fluidRenderingParticleDepthVertexShader\";\nconst shader = `attribute vec3 position;\rattribute vec2 offset;\runiform mat4 view;\runiform mat4 projection;\runiform vec2 size;\rvarying vec2 uv;\rvarying vec3 viewPos;\rvarying float sphereRadius;\r#ifdef FLUIDRENDERING_VELOCITY\nattribute vec3 velocity;\rvarying float velocityNorm;\r#endif\nvoid main(void) {\rvec3 cornerPos;\rcornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;\rcornerPos.z=0.0;\rviewPos=(view*vec4(position,1.0)).xyz;\rgl_Position=projection*vec4(viewPos+cornerPos,1.0);\ruv=offset;\rsphereRadius=size.x/2.0;\r#ifdef FLUIDRENDERING_VELOCITY\nvelocityNorm=length(velocity);\r#endif\n}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const fluidRenderingParticleDepthVertexShader = { name, shader };\n//# sourceMappingURL=fluidRenderingParticleDepth.vertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"fluidRenderingParticleDepthPixelShader\";\nconst shader = `uniform mat4 projection;\rvarying vec2 uv;\rvarying vec3 viewPos;\rvarying float sphereRadius;\r#ifdef FLUIDRENDERING_VELOCITY\nvarying float velocityNorm;\r#endif\nvoid main(void) {\rvec3 normal;\rnormal.xy=uv*2.0-1.0;\rfloat r2=dot(normal.xy,normal.xy);\rif (r2>1.0) discard;\rnormal.z=sqrt(1.0-r2);\r#ifndef FLUIDRENDERING_RHS\nnormal.z=-normal.z;\r#endif\nvec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);\rvec4 clipSpacePos=projection*realViewPos;\r#ifdef WEBGPU\ngl_FragDepth=clipSpacePos.z/clipSpacePos.w;\r#else\ngl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5;\r#endif\n#ifdef FLUIDRENDERING_RHS\nrealViewPos.z=-realViewPos.z;\r#endif\n#ifdef FLUIDRENDERING_VELOCITY\nglFragColor=vec4(realViewPos.z,velocityNorm,0.,1.);\r#else\nglFragColor=vec4(realViewPos.z,0.,0.,1.);\r#endif\n}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const fluidRenderingParticleDepthPixelShader = { name, shader };\n//# sourceMappingURL=fluidRenderingParticleDepth.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"fluidRenderingParticleThicknessVertexShader\";\nconst shader = `attribute vec3 position;\rattribute vec2 offset;\runiform mat4 view;\runiform mat4 projection;\runiform vec2 size;\rvarying vec2 uv;\rvoid main(void) {\rvec3 cornerPos;\rcornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;\rcornerPos.z=0.0;\rvec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;\rgl_Position=projection*vec4(viewPos,1.0);\ruv=offset;\r}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const fluidRenderingParticleThicknessVertexShader = { name, shader };\n//# sourceMappingURL=fluidRenderingParticleThickness.vertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"fluidRenderingParticleThicknessPixelShader\";\nconst shader = `uniform float particleAlpha;\rvarying vec2 uv;\rvoid main(void) {\rvec3 normal;\rnormal.xy=uv*2.0-1.0;\rfloat r2=dot(normal.xy,normal.xy);\rif (r2>1.0) discard;\rfloat thickness=sqrt(1.0-r2);\rglFragColor=vec4(vec3(particleAlpha*thickness),1.0);\r}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const fluidRenderingParticleThicknessPixelShader = { name, shader };\n//# sourceMappingURL=fluidRenderingParticleThickness.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"fluidRenderingParticleDiffuseVertexShader\";\nconst shader = `attribute vec3 position;\rattribute vec2 offset;\rattribute vec4 color;\runiform mat4 view;\runiform mat4 projection;\runiform vec2 size;\rvarying vec2 uv;\rvarying vec3 diffuseColor;\rvoid main(void) {\rvec3 cornerPos;\rcornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;\rcornerPos.z=0.0;\rvec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;\rgl_Position=projection*vec4(viewPos,1.0);\ruv=offset;\rdiffuseColor=color.rgb;\r}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const fluidRenderingParticleDiffuseVertexShader = { name, shader };\n//# sourceMappingURL=fluidRenderingParticleDiffuse.vertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"fluidRenderingParticleDiffusePixelShader\";\nconst shader = `uniform float particleAlpha;\rvarying vec2 uv;\rvarying vec3 diffuseColor;\rvoid main(void) {\rvec3 normal;\rnormal.xy=uv*2.0-1.0;\rfloat r2=dot(normal.xy,normal.xy);\rif (r2>1.0) discard;\rglFragColor=vec4(diffuseColor,1.0);\r}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const fluidRenderingParticleDiffusePixelShader = { name, shader };\n//# sourceMappingURL=fluidRenderingParticleDiffuse.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"fluidRenderingBilateralBlurPixelShader\";\nconst shader = `uniform sampler2D textureSampler;\runiform int maxFilterSize;\runiform vec2 blurDir;\runiform float projectedParticleConstant;\runiform float depthThreshold;\rvarying vec2 vUV;\rvoid main(void) {\rfloat depth=textureLod(textureSampler,vUV,0.).x;\rif (depth>=1e6 || depth<=0.) {\rglFragColor=vec4(vec3(depth),1.);\rreturn;\r}\rint filterSize=min(maxFilterSize,int(ceil(projectedParticleConstant/depth)));\rfloat sigma=float(filterSize)/3.0;\rfloat two_sigma2=2.0*sigma*sigma;\rfloat sigmaDepth=depthThreshold/3.0;\rfloat two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;\rfloat sum=0.;\rfloat wsum=0.;\rfloat sumVel=0.;\rfor (int x=-filterSize; x<=filterSize; ++x) {\rvec2 coords=vec2(x);\rvec2 sampleDepthVel=textureLod(textureSampler,vUV+coords*blurDir,0.).rg;\rfloat r=dot(coords,coords);\rfloat w=exp(-r/two_sigma2);\rfloat rDepth=sampleDepthVel.r-depth;\rfloat wd=exp(-rDepth*rDepth/two_sigmaDepth2);\rsum+=sampleDepthVel.r*w*wd;\rsumVel+=sampleDepthVel.g*w*wd;\rwsum+=w*wd;\r}\rglFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);\r}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const fluidRenderingBilateralBlurPixelShader = { name, shader };\n//# sourceMappingURL=fluidRenderingBilateralBlur.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"fluidRenderingStandardBlurPixelShader\";\nconst shader = `uniform sampler2D textureSampler;\runiform int filterSize;\runiform vec2 blurDir;\rvarying vec2 vUV;\rvoid main(void) {\rvec4 s=textureLod(textureSampler,vUV,0.);\rif (s.r==0.) {\rglFragColor=vec4(0.,0.,0.,1.);\rreturn;\r}\rfloat sigma=float(filterSize)/3.0;\rfloat twoSigma2=2.0*sigma*sigma;\rvec4 sum=vec4(0.);\rfloat wsum=0.;\rfor (int x=-filterSize; x<=filterSize; ++x) {\rvec2 coords=vec2(x);\rvec4 sampl=textureLod(textureSampler,vUV+coords*blurDir,0.);\rfloat w=exp(-coords.x*coords.x/twoSigma2);\rsum+=sampl*w;\rwsum+=w;\r}\rsum/=wsum;\rglFragColor=vec4(sum.rgb,1.);\r}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const fluidRenderingStandardBlurPixelShader = { name, shader };\n//# sourceMappingURL=fluidRenderingStandardBlur.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"fluidRenderingRenderPixelShader\";\nconst shader = `/* disable_uniformity_analysis */\r#define IOR 1.333\n#define ETA 1.0/IOR\n#define F0 0.02\nuniform sampler2D textureSampler;\runiform sampler2D depthSampler;\r#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nuniform sampler2D diffuseSampler;\r#else\nuniform vec3 diffuseColor;\r#endif\n#ifdef FLUIDRENDERING_FIXED_THICKNESS\nuniform float thickness;\runiform sampler2D bgDepthSampler;\r#else\nuniform float minimumThickness;\runiform sampler2D thicknessSampler;\r#endif\n#ifdef FLUIDRENDERING_ENVIRONMENT\nuniform samplerCube reflectionSampler;\r#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nuniform sampler2D debugSampler;\r#endif\nuniform mat4 viewMatrix;\runiform mat4 projectionMatrix;\runiform mat4 invProjectionMatrix;\runiform vec2 texelSize;\runiform vec3 dirLight;\runiform float cameraFar;\runiform float density;\runiform float refractionStrength;\runiform float fresnelClamp;\runiform float specularPower;\rvarying vec2 vUV;\rvec3 computeViewPosFromUVDepth(vec2 texCoord,float depth) {\rvec4 ndc;\rndc.xy=texCoord*2.0-1.0;\r#ifdef FLUIDRENDERING_RHS\nndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth;\r#else\nndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth;\r#endif\nndc.w=1.0;\rvec4 eyePos=invProjectionMatrix*ndc;\reyePos.xyz/=eyePos.w;\rreturn eyePos.xyz;\r}\rvec3 getViewPosFromTexCoord(vec2 texCoord) {\rfloat depth=textureLod(depthSampler,texCoord,0.).x;\rreturn computeViewPosFromUVDepth(texCoord,depth);\r}\rvoid main(void) {\rvec2 texCoord=vUV;\r#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nvec4 color=texture2D(debugSampler,texCoord);\r#ifdef FLUIDRENDERING_DEBUG_DEPTH\nglFragColor=vec4(color.rgb/vec3(2.0),1.);\rif (color.r>0.999 && color.g>0.999) {\rglFragColor=texture2D(textureSampler,texCoord);\r}\r#else\nglFragColor=vec4(color.rgb,1.);\rif (color.r<0.001 && color.g<0.001 && color.b<0.001) {\rglFragColor=texture2D(textureSampler,texCoord);\r}\r#endif\nreturn;\r#endif\nvec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;\rfloat depth=depthVel.r;\r#ifndef FLUIDRENDERING_FIXED_THICKNESS\nfloat thickness=texture2D(thicknessSampler,texCoord).x;\r#else\nfloat bgDepth=texture2D(bgDepthSampler,texCoord).x;\rfloat depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;\rdepthNonLinear=depthNonLinear*0.5+0.5;\r#endif\nvec4 backColor=texture2D(textureSampler,texCoord);\r#ifndef FLUIDRENDERING_FIXED_THICKNESS\nif (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) {\r#else\nif (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) {\r#endif\nglFragColor=backColor;\rreturn;\r}\rvec3 viewPos=computeViewPosFromUVDepth(texCoord,depth);\rvec3 ddx=getViewPosFromTexCoord(texCoord+vec2(texelSize.x,0.))-viewPos;\rvec3 ddy=getViewPosFromTexCoord(texCoord+vec2(0.,texelSize.y))-viewPos;\rvec3 ddx2=viewPos-getViewPosFromTexCoord(texCoord+vec2(-texelSize.x,0.));\rif (abs(ddx.z)>abs(ddx2.z)) {\rddx=ddx2;\r}\rvec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));\rif (abs(ddy.z)>abs(ddy2.z)) {\rddy=ddy2;\r}\rvec3 normal=normalize(cross(ddy,ddx));\r#ifdef FLUIDRENDERING_RHS\nnormal=-normal;\r#endif\n#ifndef WEBGPU\nif(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {\rnormal=vec3(0.,0.,-1.);\r}\r#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL)\nglFragColor=vec4(normal*0.5+0.5,1.0);\rreturn;\r#endif\nvec3 rayDir=normalize(viewPos); \r#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nvec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb;\r#endif\nvec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));\rvec3 H =normalize(lightDir-rayDir);\rfloat specular=pow(max(0.0,dot(H,normal)),specularPower);\r#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING\nfloat diffuse =max(0.0,dot(lightDir,normal))*1.0;\rglFragColor=vec4(vec3(0.1) /*ambient*/+vec3(0.42,0.50,1.00)*diffuse+vec3(0,0,0.2)+specular,1.);\rreturn;\r#endif\nvec3 refractionDir=refract(rayDir,normal,ETA);\rvec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0);\rvec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); \rvec3 refractionColor=transmitted.rgb*transmittance;\r#ifdef FLUIDRENDERING_ENVIRONMENT\nvec3 reflectionDir=reflect(rayDir,normal);\rvec3 reflectionColor=(textureCube(reflectionSampler,reflectionDir).rgb);\rfloat fresnel=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,fresnelClamp);\rvec3 finalColor=mix(refractionColor,reflectionColor,fresnel)+specular;\r#else\nvec3 finalColor=refractionColor+specular;\r#endif\n#ifdef FLUIDRENDERING_VELOCITY\nfloat velocity=depthVel.g;\rfinalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0));\r#endif\nglFragColor=vec4(finalColor,transmitted.a);\r}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const fluidRenderingRenderPixelShader = { name, shader };\n//# sourceMappingURL=fluidRenderingRender.fragment.js.map","import { Scene } from \"../../scene.js\";\nimport { SceneComponentConstants } from \"../../sceneComponent.js\";\n\nimport { FluidRenderingObjectParticleSystem } from \"./fluidRenderingObjectParticleSystem.js\";\nimport { FluidRenderingTargetRenderer } from \"./fluidRenderingTargetRenderer.js\";\nimport { FluidRenderingObjectCustomParticles } from \"./fluidRenderingObjectCustomParticles.js\";\nimport { FluidRenderingDepthTextureCopy } from \"./fluidRenderingDepthTextureCopy.js\";\nimport \"../../Shaders/fluidRenderingParticleDepth.vertex.js\";\nimport \"../../Shaders/fluidRenderingParticleDepth.fragment.js\";\nimport \"../../Shaders/fluidRenderingParticleThickness.vertex.js\";\nimport \"../../Shaders/fluidRenderingParticleThickness.fragment.js\";\nimport \"../../Shaders/fluidRenderingParticleDiffuse.vertex.js\";\nimport \"../../Shaders/fluidRenderingParticleDiffuse.fragment.js\";\nimport \"../../Shaders/fluidRenderingBilateralBlur.fragment.js\";\nimport \"../../Shaders/fluidRenderingStandardBlur.fragment.js\";\nimport \"../../Shaders/fluidRenderingRender.fragment.js\";\nObject.defineProperty(Scene.prototype, \"fluidRenderer\", {\n get: function () {\n return this._fluidRenderer;\n },\n set: function (value) {\n this._fluidRenderer = value;\n },\n enumerable: true,\n configurable: true,\n});\nScene.prototype.enableFluidRenderer = function () {\n if (this._fluidRenderer) {\n return this._fluidRenderer;\n }\n this._fluidRenderer = new FluidRenderer(this);\n return this._fluidRenderer;\n};\nScene.prototype.disableFluidRenderer = function () {\n var _a;\n (_a = this._fluidRenderer) === null || _a === void 0 ? void 0 : _a.dispose();\n this._fluidRenderer = null;\n};\nfunction IsParticleSystemObject(obj) {\n return !!obj.particleSystem;\n}\n/**\n * Defines the fluid renderer scene component responsible to render objects as fluids\n */\nexport class FluidRendererSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpful to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_FLUIDRENDERER;\n this.scene = scene;\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene._gatherActiveCameraRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER, this, this._gatherActiveCameraRenderTargets);\n this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_FLUIDRENDERER, this, this._afterCameraDraw);\n }\n _gatherActiveCameraRenderTargets(_renderTargets) {\n var _a;\n (_a = this.scene.fluidRenderer) === null || _a === void 0 ? void 0 : _a._prepareRendering();\n }\n _afterCameraDraw(camera) {\n var _a;\n (_a = this.scene.fluidRenderer) === null || _a === void 0 ? void 0 : _a._render(camera);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n if (this.scene._fluidRenderer) {\n // Release resources first\n this.scene.disableFluidRenderer();\n // Re-enable\n this.scene.enableFluidRenderer();\n }\n }\n /**\n * Disposes the component and the associated resources\n */\n dispose() {\n this.scene.disableFluidRenderer();\n }\n}\n/**\n * Class responsible for fluid rendering.\n * It is implementing the method described in https://developer.download.nvidia.com/presentations/2010/gdc/Direct3D_Effects.pdf\n */\nexport class FluidRenderer {\n /** @internal */\n static _SceneComponentInitialization(scene) {\n let component = scene._getComponent(SceneComponentConstants.NAME_FLUIDRENDERER);\n if (!component) {\n component = new FluidRendererSceneComponent(scene);\n scene._addComponent(component);\n }\n }\n /**\n * Initializes the class\n * @param scene Scene in which the objects are part of\n */\n constructor(scene) {\n this._scene = scene;\n this._engine = scene.getEngine();\n this._onEngineResizeObserver = null;\n this.renderObjects = [];\n this.targetRenderers = [];\n this._cameras = new Map();\n FluidRenderer._SceneComponentInitialization(this._scene);\n this._onEngineResizeObserver = this._engine.onResizeObservable.add(() => {\n this._initialize();\n });\n }\n /**\n * Reinitializes the class\n * Can be used if you change the object priority (FluidRenderingObject.priority), to make sure the objects are rendered in the right order\n */\n recreate() {\n this._sortRenderingObjects();\n this._initialize();\n }\n /**\n * Gets the render object corresponding to a particle system (null if the particle system is not rendered as a fluid)\n * @param ps The particle system\n * @returns the render object corresponding to this particle system if any, otherwise null\n */\n getRenderObjectFromParticleSystem(ps) {\n const index = this._getParticleSystemIndex(ps);\n return index !== -1 ? this.renderObjects[index] : null;\n }\n /**\n * Adds a particle system to the fluid renderer.\n * Note that you should not normally call this method directly, as you can simply use the renderAsFluid property of the ParticleSystem/GPUParticleSystem class\n * @param ps particle system\n * @param generateDiffuseTexture True if you want to generate a diffuse texture from the particle system and use it as part of the fluid rendering (default: false)\n * @param targetRenderer The target renderer used to display the particle system as a fluid. If not provided, the method will create a new one\n * @param camera The camera used by the target renderer (if the target renderer is created by the method)\n * @returns the render object corresponding to the particle system\n */\n addParticleSystem(ps, generateDiffuseTexture, targetRenderer, camera) {\n const object = new FluidRenderingObjectParticleSystem(this._scene, ps);\n object.onParticleSizeChanged.add(this._setParticleSizeForRenderTargets.bind(this));\n if (!targetRenderer) {\n targetRenderer = new FluidRenderingTargetRenderer(this._scene, camera);\n this.targetRenderers.push(targetRenderer);\n }\n if (!targetRenderer._onUseVelocityChanged.hasObservers()) {\n targetRenderer._onUseVelocityChanged.add(this._setUseVelocityForRenderObject.bind(this));\n }\n if (generateDiffuseTexture !== undefined) {\n targetRenderer.generateDiffuseTexture = generateDiffuseTexture;\n }\n const renderObject = { object, targetRenderer };\n this.renderObjects.push(renderObject);\n this._sortRenderingObjects();\n this._setParticleSizeForRenderTargets();\n return renderObject;\n }\n /**\n * Adds a custom particle set to the fluid renderer.\n * @param buffers The list of buffers (should contain at least a \"position\" buffer!)\n * @param numParticles Number of particles in each buffer\n * @param generateDiffuseTexture True if you want to generate a diffuse texture from buffers and use it as part of the fluid rendering (default: false). For the texture to be generated correctly, you need a \"color\" buffer in the set!\n * @param targetRenderer The target renderer used to display the particle system as a fluid. If not provided, the method will create a new one\n * @param camera The camera used by the target renderer (if the target renderer is created by the method)\n * @returns the render object corresponding to the custom particle set\n */\n addCustomParticles(buffers, numParticles, generateDiffuseTexture, targetRenderer, camera) {\n const object = new FluidRenderingObjectCustomParticles(this._scene, buffers, numParticles);\n object.onParticleSizeChanged.add(this._setParticleSizeForRenderTargets.bind(this));\n if (!targetRenderer) {\n targetRenderer = new FluidRenderingTargetRenderer(this._scene, camera);\n this.targetRenderers.push(targetRenderer);\n }\n if (!targetRenderer._onUseVelocityChanged.hasObservers()) {\n targetRenderer._onUseVelocityChanged.add(this._setUseVelocityForRenderObject.bind(this));\n }\n if (generateDiffuseTexture !== undefined) {\n targetRenderer.generateDiffuseTexture = generateDiffuseTexture;\n }\n const renderObject = { object, targetRenderer };\n this.renderObjects.push(renderObject);\n this._sortRenderingObjects();\n this._setParticleSizeForRenderTargets();\n return renderObject;\n }\n /**\n * Removes a render object from the fluid renderer\n * @param renderObject the render object to remove\n * @param removeUnusedTargetRenderer True to remove/dispose of the target renderer if it's not used anymore (default: true)\n * @returns True if the render object has been found and released, else false\n */\n removeRenderObject(renderObject, removeUnusedTargetRenderer = true) {\n const index = this.renderObjects.indexOf(renderObject);\n if (index === -1) {\n return false;\n }\n renderObject.object.dispose();\n this.renderObjects.splice(index, 1);\n if (removeUnusedTargetRenderer && this._removeUnusedTargetRenderers()) {\n this._initialize();\n }\n else {\n this._setParticleSizeForRenderTargets();\n }\n return true;\n }\n _sortRenderingObjects() {\n this.renderObjects.sort((a, b) => {\n return a.object.priority < b.object.priority ? -1 : a.object.priority > b.object.priority ? 1 : 0;\n });\n }\n _removeUnusedTargetRenderers() {\n const indexes = {};\n for (let i = 0; i < this.renderObjects.length; ++i) {\n const targetRenderer = this.renderObjects[i].targetRenderer;\n indexes[this.targetRenderers.indexOf(targetRenderer)] = true;\n }\n let removed = false;\n const newList = [];\n for (let i = 0; i < this.targetRenderers.length; ++i) {\n if (!indexes[i]) {\n this.targetRenderers[i].dispose();\n removed = true;\n }\n else {\n newList.push(this.targetRenderers[i]);\n }\n }\n if (removed) {\n this.targetRenderers.length = 0;\n this.targetRenderers.push(...newList);\n }\n return removed;\n }\n _getParticleSystemIndex(ps) {\n for (let i = 0; i < this.renderObjects.length; ++i) {\n const obj = this.renderObjects[i].object;\n if (IsParticleSystemObject(obj) && obj.particleSystem === ps) {\n return i;\n }\n }\n return -1;\n }\n _initialize() {\n for (let i = 0; i < this.targetRenderers.length; ++i) {\n this.targetRenderers[i].dispose();\n }\n const cameras = new Map();\n for (let i = 0; i < this.targetRenderers.length; ++i) {\n const targetRenderer = this.targetRenderers[i];\n targetRenderer._initialize();\n if (targetRenderer.camera && targetRenderer._renderPostProcess) {\n let list = cameras.get(targetRenderer.camera);\n if (!list) {\n list = [[], {}];\n cameras.set(targetRenderer.camera, list);\n }\n list[0].push(targetRenderer);\n targetRenderer.camera.attachPostProcess(targetRenderer._renderPostProcess, i);\n }\n }\n let iterator = cameras.keys();\n for (let key = iterator.next(); key.done !== true; key = iterator.next()) {\n const camera = key.value;\n const list = cameras.get(camera);\n const firstPostProcess = camera._getFirstPostProcess();\n if (!firstPostProcess) {\n continue;\n }\n const [targetRenderers, copyDepthTextures] = list;\n firstPostProcess.onSizeChangedObservable.add(() => {\n var _a;\n if (!firstPostProcess.inputTexture.depthStencilTexture) {\n firstPostProcess.inputTexture.createDepthStencilTexture(0, true, this._engine.isStencilEnable, targetRenderers[0].samples, this._engine.isStencilEnable ? 13 : 14, `PostProcessRTTDepthStencil-${firstPostProcess.name}`);\n }\n for (const targetRenderer of targetRenderers) {\n const thicknessRT = (_a = targetRenderer._thicknessRenderTarget) === null || _a === void 0 ? void 0 : _a.renderTarget;\n const thicknessTexture = thicknessRT === null || thicknessRT === void 0 ? void 0 : thicknessRT.texture;\n if (thicknessRT && thicknessTexture) {\n const key = thicknessTexture.width + \"_\" + thicknessTexture.height;\n let copyDepthTexture = copyDepthTextures[key];\n if (!copyDepthTexture) {\n copyDepthTexture = copyDepthTextures[key] = new FluidRenderingDepthTextureCopy(this._engine, thicknessTexture.width, thicknessTexture.height);\n }\n copyDepthTexture.depthRTWrapper._shareDepth(thicknessRT);\n }\n }\n });\n }\n // Dispose the CopyDepthTexture instances that we don't need anymore\n iterator = this._cameras.keys();\n for (let key = iterator.next(); key.done !== true; key = iterator.next()) {\n const camera = key.value;\n const list = this._cameras.get(camera);\n const copyDepthTextures = list[1];\n const list2 = cameras.get(camera);\n if (!list2) {\n for (const key in copyDepthTextures) {\n copyDepthTextures[key].dispose();\n }\n }\n else {\n for (const key in copyDepthTextures) {\n if (!list2[1][key]) {\n copyDepthTextures[key].dispose();\n }\n }\n }\n }\n this._cameras.clear();\n this._cameras = cameras;\n this._setParticleSizeForRenderTargets();\n }\n _setParticleSizeForRenderTargets() {\n const particleSizes = new Map();\n for (let i = 0; i < this.renderObjects.length; ++i) {\n const renderingObject = this.renderObjects[i];\n let curSize = particleSizes.get(renderingObject.targetRenderer);\n if (curSize === undefined) {\n curSize = 0;\n }\n particleSizes.set(renderingObject.targetRenderer, Math.max(curSize, renderingObject.object.particleSize));\n }\n particleSizes.forEach((particleSize, targetRenderer) => {\n if (targetRenderer._depthRenderTarget) {\n targetRenderer._depthRenderTarget.particleSize = particleSize;\n }\n });\n }\n _setUseVelocityForRenderObject() {\n for (const renderingObject of this.renderObjects) {\n renderingObject.object.useVelocity = renderingObject.targetRenderer.useVelocity;\n }\n }\n /** @internal */\n _prepareRendering() {\n for (const renderer of this.targetRenderers) {\n if (renderer.needInitialization) {\n this._initialize();\n return;\n }\n }\n }\n /** @internal */\n _render(forCamera) {\n var _a;\n for (let i = 0; i < this.targetRenderers.length; ++i) {\n if (!forCamera || this.targetRenderers[i].camera === forCamera) {\n this.targetRenderers[i]._clearTargets();\n }\n }\n const iterator = this._cameras.keys();\n for (let key = iterator.next(); key.done !== true; key = iterator.next()) {\n const camera = key.value;\n const list = this._cameras.get(camera);\n if (forCamera && camera !== forCamera) {\n continue;\n }\n const firstPostProcess = camera._getFirstPostProcess();\n if (!firstPostProcess) {\n continue;\n }\n const sourceCopyDepth = (_a = firstPostProcess.inputTexture) === null || _a === void 0 ? void 0 : _a.depthStencilTexture;\n if (sourceCopyDepth) {\n const [targetRenderers, copyDepthTextures] = list;\n for (const targetRenderer of targetRenderers) {\n targetRenderer._bgDepthTexture = sourceCopyDepth;\n }\n for (const key in copyDepthTextures) {\n copyDepthTextures[key].copy(sourceCopyDepth);\n }\n }\n }\n for (let i = 0; i < this.renderObjects.length; ++i) {\n const renderingObject = this.renderObjects[i];\n if (!forCamera || renderingObject.targetRenderer.camera === forCamera) {\n renderingObject.targetRenderer._render(renderingObject.object);\n }\n }\n }\n /**\n * Disposes of all the ressources used by the class\n */\n dispose() {\n this._engine.onResizeObservable.remove(this._onEngineResizeObserver);\n this._onEngineResizeObserver = null;\n for (let i = 0; i < this.renderObjects.length; ++i) {\n this.renderObjects[i].object.dispose();\n }\n for (let i = 0; i < this.targetRenderers.length; ++i) {\n this.targetRenderers[i].dispose();\n }\n this._cameras.forEach((list) => {\n const copyDepthTextures = list[1];\n for (const key in copyDepthTextures) {\n copyDepthTextures[key].dispose();\n }\n });\n this.renderObjects = [];\n this.targetRenderers = [];\n this._cameras.clear();\n }\n}\n//# sourceMappingURL=fluidRenderer.js.map","export * from \"./fluidRenderer.js\";\nexport * from \"./fluidRenderingObject.js\";\nexport * from \"./fluidRenderingObjectParticleSystem.js\";\nexport * from \"./fluidRenderingObjectCustomParticles.js\";\nexport * from \"./fluidRenderingTargetRenderer.js\";\n//# sourceMappingURL=index.js.map","/**\n * ThinSprite Class used to represent a thin sprite\n * This is the base class for sprites but can also directly be used with ThinEngine\n * @see https://doc.babylonjs.com/features/featuresDeepDive/sprites\n */\nexport class ThinSprite {\n /**\n * Returns a boolean indicating if the animation is started\n */\n get animationStarted() {\n return this._animationStarted;\n }\n /** Gets the initial key for the animation (setting it will restart the animation) */\n get fromIndex() {\n return this._fromIndex;\n }\n /** Gets or sets the end key for the animation (setting it will restart the animation) */\n get toIndex() {\n return this._toIndex;\n }\n /** Gets or sets a boolean indicating if the animation is looping (setting it will restart the animation) */\n get loopAnimation() {\n return this._loopAnimation;\n }\n /** Gets or sets the delay between cell changes (setting it will restart the animation) */\n get delay() {\n return Math.max(this._delay, 1);\n }\n /**\n * Creates a new Thin Sprite\n */\n constructor() {\n /** Gets or sets the width */\n this.width = 1.0;\n /** Gets or sets the height */\n this.height = 1.0;\n /** Gets or sets rotation angle */\n this.angle = 0;\n /** Gets or sets a boolean indicating if UV coordinates should be inverted in U axis */\n this.invertU = false;\n /** Gets or sets a boolean indicating if UV coordinates should be inverted in B axis */\n this.invertV = false;\n /** Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true */\n this.isVisible = true;\n this._animationStarted = false;\n this._loopAnimation = false;\n this._fromIndex = 0;\n this._toIndex = 0;\n this._delay = 0;\n this._direction = 1;\n this._time = 0;\n this._onBaseAnimationEnd = null;\n this.position = { x: 1.0, y: 1.0, z: 1.0 };\n this.color = { r: 1.0, g: 1.0, b: 1.0, a: 1.0 };\n }\n /**\n * Starts an animation\n * @param from defines the initial key\n * @param to defines the end key\n * @param loop defines if the animation must loop\n * @param delay defines the start delay (in ms)\n * @param onAnimationEnd defines a callback for when the animation ends\n */\n playAnimation(from, to, loop, delay, onAnimationEnd) {\n this._fromIndex = from;\n this._toIndex = to;\n this._loopAnimation = loop;\n this._delay = delay || 1;\n this._animationStarted = true;\n this._onBaseAnimationEnd = onAnimationEnd;\n if (from < to) {\n this._direction = 1;\n }\n else {\n this._direction = -1;\n this._toIndex = from;\n this._fromIndex = to;\n }\n this.cellIndex = from;\n this._time = 0;\n }\n /** Stops current animation (if any) */\n stopAnimation() {\n this._animationStarted = false;\n }\n /**\n * @internal\n */\n _animate(deltaTime) {\n if (!this._animationStarted) {\n return;\n }\n this._time += deltaTime;\n if (this._time > this._delay) {\n this._time = this._time % this._delay;\n this.cellIndex += this._direction;\n if ((this._direction > 0 && this.cellIndex > this._toIndex) || (this._direction < 0 && this.cellIndex < this._fromIndex)) {\n if (this._loopAnimation) {\n this.cellIndex = this._direction > 0 ? this._fromIndex : this._toIndex;\n }\n else {\n this.cellIndex = this._toIndex;\n this._animationStarted = false;\n if (this._onBaseAnimationEnd) {\n this._onBaseAnimationEnd();\n }\n }\n }\n }\n }\n}\n//# sourceMappingURL=thinSprite.js.map","import { Vector3 } from \"../Maths/math.vector.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { ThinSprite } from \"./thinSprite.js\";\n/**\n * Class used to represent a sprite\n * @see https://doc.babylonjs.com/features/featuresDeepDive/sprites\n */\nexport class Sprite extends ThinSprite {\n /**\n * Gets or sets the sprite size\n */\n get size() {\n return this.width;\n }\n set size(value) {\n this.width = value;\n this.height = value;\n }\n /**\n * Gets the manager of this sprite\n */\n get manager() {\n return this._manager;\n }\n /**\n * Creates a new Sprite\n * @param name defines the name\n * @param manager defines the manager\n */\n constructor(\n /** defines the name */\n name, manager) {\n super();\n this.name = name;\n /** Gets the list of attached animations */\n this.animations = new Array();\n /** Gets or sets a boolean indicating if the sprite can be picked */\n this.isPickable = false;\n /** Gets or sets a boolean indicating that sprite texture alpha will be used for precise picking (false by default) */\n this.useAlphaForPicking = false;\n /**\n * An event triggered when the control has been disposed\n */\n this.onDisposeObservable = new Observable();\n this._onAnimationEnd = null;\n this._endAnimation = () => {\n if (this._onAnimationEnd) {\n this._onAnimationEnd();\n }\n if (this.disposeWhenFinishedAnimating) {\n this.dispose();\n }\n };\n this.color = new Color4(1.0, 1.0, 1.0, 1.0);\n this.position = Vector3.Zero();\n this._manager = manager;\n this._manager.sprites.push(this);\n this.uniqueId = this._manager.scene.getUniqueId();\n }\n /**\n * Returns the string \"Sprite\"\n * @returns \"Sprite\"\n */\n getClassName() {\n return \"Sprite\";\n }\n /** Gets or sets the initial key for the animation (setting it will restart the animation) */\n get fromIndex() {\n return this._fromIndex;\n }\n set fromIndex(value) {\n this.playAnimation(value, this._toIndex, this._loopAnimation, this._delay, this._onAnimationEnd);\n }\n /** Gets or sets the end key for the animation (setting it will restart the animation) */\n get toIndex() {\n return this._toIndex;\n }\n set toIndex(value) {\n this.playAnimation(this._fromIndex, value, this._loopAnimation, this._delay, this._onAnimationEnd);\n }\n /** Gets or sets a boolean indicating if the animation is looping (setting it will restart the animation) */\n get loopAnimation() {\n return this._loopAnimation;\n }\n set loopAnimation(value) {\n this.playAnimation(this._fromIndex, this._toIndex, value, this._delay, this._onAnimationEnd);\n }\n /** Gets or sets the delay between cell changes (setting it will restart the animation) */\n get delay() {\n return Math.max(this._delay, 1);\n }\n set delay(value) {\n this.playAnimation(this._fromIndex, this._toIndex, this._loopAnimation, value, this._onAnimationEnd);\n }\n /**\n * Starts an animation\n * @param from defines the initial key\n * @param to defines the end key\n * @param loop defines if the animation must loop\n * @param delay defines the start delay (in ms)\n * @param onAnimationEnd defines a callback to call when animation ends\n */\n playAnimation(from, to, loop, delay, onAnimationEnd = null) {\n this._onAnimationEnd = onAnimationEnd;\n super.playAnimation(from, to, loop, delay, this._endAnimation);\n }\n /** Release associated resources */\n dispose() {\n for (let i = 0; i < this._manager.sprites.length; i++) {\n if (this._manager.sprites[i] == this) {\n this._manager.sprites.splice(i, 1);\n }\n }\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n }\n /**\n * Serializes the sprite to a JSON object\n * @returns the JSON object\n */\n serialize() {\n const serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.position = this.position.asArray();\n serializationObject.color = this.color.asArray();\n serializationObject.width = this.width;\n serializationObject.height = this.height;\n serializationObject.angle = this.angle;\n serializationObject.cellIndex = this.cellIndex;\n serializationObject.cellRef = this.cellRef;\n serializationObject.invertU = this.invertU;\n serializationObject.invertV = this.invertV;\n serializationObject.disposeWhenFinishedAnimating = this.disposeWhenFinishedAnimating;\n serializationObject.isPickable = this.isPickable;\n serializationObject.isVisible = this.isVisible;\n serializationObject.useAlphaForPicking = this.useAlphaForPicking;\n serializationObject.animationStarted = this.animationStarted;\n serializationObject.fromIndex = this.fromIndex;\n serializationObject.toIndex = this.toIndex;\n serializationObject.loopAnimation = this.loopAnimation;\n serializationObject.delay = this.delay;\n return serializationObject;\n }\n /**\n * Parses a JSON object to create a new sprite\n * @param parsedSprite The JSON object to parse\n * @param manager defines the hosting manager\n * @returns the new sprite\n */\n static Parse(parsedSprite, manager) {\n const sprite = new Sprite(parsedSprite.name, manager);\n sprite.position = Vector3.FromArray(parsedSprite.position);\n sprite.color = Color4.FromArray(parsedSprite.color);\n sprite.width = parsedSprite.width;\n sprite.height = parsedSprite.height;\n sprite.angle = parsedSprite.angle;\n sprite.cellIndex = parsedSprite.cellIndex;\n sprite.cellRef = parsedSprite.cellRef;\n sprite.invertU = parsedSprite.invertU;\n sprite.invertV = parsedSprite.invertV;\n sprite.disposeWhenFinishedAnimating = parsedSprite.disposeWhenFinishedAnimating;\n sprite.isPickable = parsedSprite.isPickable;\n sprite.isVisible = parsedSprite.isVisible;\n sprite.useAlphaForPicking = parsedSprite.useAlphaForPicking;\n sprite.fromIndex = parsedSprite.fromIndex;\n sprite.toIndex = parsedSprite.toIndex;\n sprite.loopAnimation = parsedSprite.loopAnimation;\n sprite.delay = parsedSprite.delay;\n if (parsedSprite.animationStarted) {\n sprite.playAnimation(sprite.fromIndex, sprite.toIndex, sprite.loopAnimation, sprite.delay);\n }\n return sprite;\n }\n}\n//# sourceMappingURL=sprite.js.map","export {};\n//# sourceMappingURL=ISprites.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { Scene } from \"../scene.js\";\nimport { Ray } from \"../Culling/ray.js\";\nimport { PickingInfo } from \"../Collisions/pickingInfo.js\";\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { ActionEvent } from \"../Actions/actionEvent.js\";\n\nScene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {\n if (!PickingInfo) {\n return null;\n }\n let pickingInfo = null;\n if (!camera) {\n if (!this.activeCamera) {\n return null;\n }\n camera = this.activeCamera;\n }\n if (this.spriteManagers && this.spriteManagers.length > 0) {\n for (let spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {\n const spriteManager = this.spriteManagers[spriteIndex];\n if (!spriteManager.isPickable) {\n continue;\n }\n const result = spriteManager.intersects(ray, camera, predicate, fastCheck);\n if (!result || !result.hit) {\n continue;\n }\n if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {\n continue;\n }\n pickingInfo = result;\n if (fastCheck) {\n break;\n }\n }\n }\n return pickingInfo || new PickingInfo();\n};\nScene.prototype._internalMultiPickSprites = function (ray, predicate, camera) {\n if (!PickingInfo) {\n return null;\n }\n let pickingInfos = new Array();\n if (!camera) {\n if (!this.activeCamera) {\n return null;\n }\n camera = this.activeCamera;\n }\n if (this.spriteManagers && this.spriteManagers.length > 0) {\n for (let spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {\n const spriteManager = this.spriteManagers[spriteIndex];\n if (!spriteManager.isPickable) {\n continue;\n }\n const results = spriteManager.multiIntersects(ray, camera, predicate);\n if (results !== null) {\n pickingInfos = pickingInfos.concat(results);\n }\n }\n }\n return pickingInfos;\n};\nScene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {\n if (!this._tempSpritePickingRay) {\n return null;\n }\n this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);\n const result = this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);\n if (result) {\n result.ray = this.createPickingRayInCameraSpace(x, y, camera);\n }\n return result;\n};\nScene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {\n if (!this._tempSpritePickingRay) {\n return null;\n }\n if (!camera) {\n if (!this.activeCamera) {\n return null;\n }\n camera = this.activeCamera;\n }\n Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);\n const result = this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);\n if (result) {\n result.ray = ray;\n }\n return result;\n};\nScene.prototype.multiPickSprite = function (x, y, predicate, camera) {\n this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);\n return this._internalMultiPickSprites(this._tempSpritePickingRay, predicate, camera);\n};\nScene.prototype.multiPickSpriteWithRay = function (ray, predicate, camera) {\n if (!this._tempSpritePickingRay) {\n return null;\n }\n if (!camera) {\n if (!this.activeCamera) {\n return null;\n }\n camera = this.activeCamera;\n }\n Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);\n return this._internalMultiPickSprites(this._tempSpritePickingRay, predicate, camera);\n};\nScene.prototype.setPointerOverSprite = function (sprite) {\n if (this._pointerOverSprite === sprite) {\n return;\n }\n if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {\n this._pointerOverSprite.actionManager.processTrigger(10, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));\n }\n this._pointerOverSprite = sprite;\n if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {\n this._pointerOverSprite.actionManager.processTrigger(9, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));\n }\n};\nScene.prototype.getPointerOverSprite = function () {\n return this._pointerOverSprite;\n};\n/**\n * Defines the sprite scene component responsible to manage sprites\n * in a given scene.\n */\nexport class SpriteSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpfull to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_SPRITE;\n this.scene = scene;\n this.scene.spriteManagers = new Array();\n this.scene._tempSpritePickingRay = Ray ? Ray.Zero() : null;\n this.scene.onBeforeSpritesRenderingObservable = new Observable();\n this.scene.onAfterSpritesRenderingObservable = new Observable();\n this._spritePredicate = (sprite) => {\n if (!sprite.actionManager) {\n return false;\n }\n return sprite.isPickable && sprite.actionManager.hasPointerTriggers;\n };\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene._pointerMoveStage.registerStep(SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);\n this.scene._pointerDownStage.registerStep(SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);\n this.scene._pointerUpStage.registerStep(SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n /** Nothing to do for sprites */\n }\n /**\n * Disposes the component and the associated resources.\n */\n dispose() {\n this.scene.onBeforeSpritesRenderingObservable.clear();\n this.scene.onAfterSpritesRenderingObservable.clear();\n const spriteManagers = this.scene.spriteManagers;\n if (!spriteManagers) {\n return;\n }\n while (spriteManagers.length) {\n spriteManagers[0].dispose();\n }\n }\n _pickSpriteButKeepRay(originalPointerInfo, x, y, fastCheck, camera) {\n const result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);\n if (result) {\n result.ray = originalPointerInfo ? originalPointerInfo.ray : null;\n }\n return result;\n }\n _pointerMove(unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, element) {\n const scene = this.scene;\n if (isMeshPicked) {\n scene.setPointerOverSprite(null);\n }\n else {\n pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);\n if (pickResult && pickResult.hit && pickResult.pickedSprite) {\n scene.setPointerOverSprite(pickResult.pickedSprite);\n if (!scene.doNotHandleCursors && element) {\n if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {\n element.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;\n }\n else {\n element.style.cursor = scene.hoverCursor;\n }\n }\n }\n else {\n scene.setPointerOverSprite(null);\n }\n }\n return pickResult;\n }\n _pointerDown(unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {\n const scene = this.scene;\n scene._pickedDownSprite = null;\n if (scene.spriteManagers && scene.spriteManagers.length > 0) {\n pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);\n if (pickResult && pickResult.hit && pickResult.pickedSprite) {\n if (pickResult.pickedSprite.actionManager) {\n scene._pickedDownSprite = pickResult.pickedSprite;\n switch (evt.button) {\n case 0:\n pickResult.pickedSprite.actionManager.processTrigger(2, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));\n break;\n case 1:\n pickResult.pickedSprite.actionManager.processTrigger(4, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));\n break;\n case 2:\n pickResult.pickedSprite.actionManager.processTrigger(3, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));\n break;\n }\n if (pickResult.pickedSprite.actionManager) {\n pickResult.pickedSprite.actionManager.processTrigger(5, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));\n }\n }\n }\n }\n return pickResult;\n }\n _pointerUp(unTranslatedPointerX, unTranslatedPointerY, pickResult, evt, doubleClick) {\n const scene = this.scene;\n if (scene.spriteManagers && scene.spriteManagers.length > 0) {\n const spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);\n if (spritePickResult) {\n if (spritePickResult.hit && spritePickResult.pickedSprite) {\n if (spritePickResult.pickedSprite.actionManager) {\n spritePickResult.pickedSprite.actionManager.processTrigger(7, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));\n if (spritePickResult.pickedSprite.actionManager) {\n if (!this.scene._inputManager._isPointerSwiping()) {\n spritePickResult.pickedSprite.actionManager.processTrigger(1, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));\n }\n if (doubleClick) {\n spritePickResult.pickedSprite.actionManager.processTrigger(6, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));\n }\n }\n }\n }\n if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {\n scene._pickedDownSprite.actionManager.processTrigger(16, ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));\n }\n }\n }\n return pickResult;\n }\n}\n//# sourceMappingURL=spriteSceneComponent.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/fogVertexDeclaration.js\";\nconst name = \"spritesVertexShader\";\nconst shader = `attribute vec4 position;\rattribute vec2 options;\rattribute vec2 offsets;\rattribute vec2 inverts;\rattribute vec4 cellInfo;\rattribute vec4 color;\runiform mat4 view;\runiform mat4 projection;\rvarying vec2 vUV;\rvarying vec4 vColor;\r#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \rvec2 cornerPos;\rfloat angle=position.w;\rvec2 size=vec2(options.x,options.y);\rvec2 offset=offsets.xy;\rcornerPos=vec2(offset.x-0.5,offset.y -0.5)*size;\rvec3 rotatedCorner;\rrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\rrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\rrotatedCorner.z=0.;\rviewPos+=rotatedCorner;\rgl_Position=projection*vec4(viewPos,1.0); \rvColor=color;\rvec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));\rvec2 uvPlace=cellInfo.xy;\rvec2 uvSize=cellInfo.zw;\rvUV.x=uvPlace.x+uvSize.x*uvOffset.x;\rvUV.y=uvPlace.y+uvSize.y*uvOffset.y;\r#ifdef FOG\nvFogDistance=viewPos;\r#endif\n#define CUSTOM_VERTEX_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const spritesVertexShader = { name, shader };\n//# sourceMappingURL=sprites.vertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"imageProcessingCompatibility\";\nconst shader = `#ifdef IMAGEPROCESSINGPOSTPROCESS\ngl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2));\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const imageProcessingCompatibility = { name, shader };\n//# sourceMappingURL=imageProcessingCompatibility.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/fogFragmentDeclaration.js\";\nimport \"./ShadersInclude/fogFragment.js\";\nimport \"./ShadersInclude/imageProcessingCompatibility.js\";\nconst name = \"spritesPixelShader\";\nconst shader = `uniform bool alphaTest;\rvarying vec4 vColor;\rvarying vec2 vUV;\runiform sampler2D diffuseSampler;\r#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#ifdef PIXEL_PERFECT\nvec2 uvPixelPerfect(vec2 uv) {\rvec2 res=vec2(textureSize(diffuseSampler,0));\ruv=uv*res;\rvec2 seam=floor(uv+0.5);\ruv=seam+clamp((uv-seam)/fwidth(uv),-0.5,0.5);\rreturn uv/res;\r}\r#endif\nvoid main(void) {\r#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#ifdef PIXEL_PERFECT\nvec2 uv=uvPixelPerfect(vUV);\r#else\nvec2 uv=vUV;\r#endif\nvec4 color=texture2D(diffuseSampler,uv);\rfloat fAlphaTest=float(alphaTest);\rif (fAlphaTest != 0.)\r{\rif (color.a<0.95)\rdiscard;\r}\rcolor*=vColor;\r#include\ngl_FragColor=color;\r#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const spritesPixelShader = { name, shader };\n//# sourceMappingURL=sprites.fragment.js.map","\nimport { Buffer, VertexBuffer } from \"../Buffers/buffer.js\";\nimport { DrawWrapper } from \"../Materials/drawWrapper.js\";\nimport \"../Engines/Extensions/engine.alpha.js\";\nimport \"../Engines/Extensions/engine.dynamicBuffer.js\";\nimport \"../Shaders/sprites.fragment.js\";\nimport \"../Shaders/sprites.vertex.js\";\n/**\n * Class used to render sprites.\n *\n * It can be used either to render Sprites or ThinSprites with ThinEngine only.\n */\nexport class SpriteRenderer {\n /**\n * Gets the capacity of the manager\n */\n get capacity() {\n return this._capacity;\n }\n /**\n * Gets or sets a boolean indicating if the renderer must render sprites with pixel perfect rendering\n * Note that pixel perfect mode is not supported in WebGL 1\n */\n get pixelPerfect() {\n return this._pixelPerfect;\n }\n set pixelPerfect(value) {\n if (this._pixelPerfect === value) {\n return;\n }\n this._pixelPerfect = value;\n this._createEffects();\n }\n /**\n * Creates a new sprite Renderer\n * @param engine defines the engine the renderer works with\n * @param capacity defines the maximum allowed number of sprites\n * @param epsilon defines the epsilon value to align texture (0.01 by default)\n * @param scene defines the hosting scene\n */\n constructor(engine, capacity, epsilon = 0.01, scene = null) {\n /**\n * Blend mode use to render the particle, it can be any of\n * the static undefined properties provided in this class.\n * Default value is 2\n */\n this.blendMode = 2;\n /**\n * Gets or sets a boolean indicating if alpha mode is automatically\n * reset.\n */\n this.autoResetAlpha = true;\n /**\n * Disables writing to the depth buffer when rendering the sprites.\n * It can be handy to disable depth writing when using textures without alpha channel\n * and setting some specific blend modes.\n */\n this.disableDepthWrite = false;\n /**\n * Gets or sets a boolean indicating if the manager must consider scene fog when rendering\n */\n this.fogEnabled = true;\n this._pixelPerfect = false;\n this._useVAO = false;\n this._useInstancing = false;\n this._vertexBuffers = {};\n this._capacity = capacity;\n this._epsilon = epsilon;\n this._engine = engine;\n this._useInstancing = engine.getCaps().instancedArrays && engine._features.supportSpriteInstancing;\n this._useVAO = engine.getCaps().vertexArrayObject && !engine.disableVertexArrayObjects;\n this._scene = scene;\n if (!this._useInstancing) {\n this._buildIndexBuffer();\n }\n // VBO\n // 18 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellLeft, cellTop, cellWidth, cellHeight, color r, color g, color b, color a)\n // 16 when using instances\n this._vertexBufferSize = this._useInstancing ? 16 : 18;\n this._vertexData = new Float32Array(capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));\n this._buffer = new Buffer(engine, this._vertexData, true, this._vertexBufferSize);\n const positions = this._buffer.createVertexBuffer(VertexBuffer.PositionKind, 0, 4, this._vertexBufferSize, this._useInstancing);\n const options = this._buffer.createVertexBuffer(\"options\", 4, 2, this._vertexBufferSize, this._useInstancing);\n let offset = 6;\n let offsets;\n if (this._useInstancing) {\n const spriteData = new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]);\n this._spriteBuffer = new Buffer(engine, spriteData, false, 2);\n offsets = this._spriteBuffer.createVertexBuffer(\"offsets\", 0, 2);\n }\n else {\n offsets = this._buffer.createVertexBuffer(\"offsets\", offset, 2, this._vertexBufferSize, this._useInstancing);\n offset += 2;\n }\n const inverts = this._buffer.createVertexBuffer(\"inverts\", offset, 2, this._vertexBufferSize, this._useInstancing);\n const cellInfo = this._buffer.createVertexBuffer(\"cellInfo\", offset + 2, 4, this._vertexBufferSize, this._useInstancing);\n const colors = this._buffer.createVertexBuffer(VertexBuffer.ColorKind, offset + 6, 4, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[VertexBuffer.PositionKind] = positions;\n this._vertexBuffers[\"options\"] = options;\n this._vertexBuffers[\"offsets\"] = offsets;\n this._vertexBuffers[\"inverts\"] = inverts;\n this._vertexBuffers[\"cellInfo\"] = cellInfo;\n this._vertexBuffers[VertexBuffer.ColorKind] = colors;\n this._createEffects();\n }\n _createEffects() {\n var _a, _b, _c, _d;\n (_a = this._drawWrapperBase) === null || _a === void 0 ? void 0 : _a.dispose();\n (_b = this._drawWrapperFog) === null || _b === void 0 ? void 0 : _b.dispose();\n (_c = this._drawWrapperDepth) === null || _c === void 0 ? void 0 : _c.dispose();\n (_d = this._drawWrapperFogDepth) === null || _d === void 0 ? void 0 : _d.dispose();\n this._drawWrapperBase = new DrawWrapper(this._engine);\n this._drawWrapperFog = new DrawWrapper(this._engine);\n this._drawWrapperDepth = new DrawWrapper(this._engine, false);\n this._drawWrapperFogDepth = new DrawWrapper(this._engine, false);\n if (this._drawWrapperBase.drawContext) {\n this._drawWrapperBase.drawContext.useInstancing = this._useInstancing;\n }\n if (this._drawWrapperFog.drawContext) {\n this._drawWrapperFog.drawContext.useInstancing = this._useInstancing;\n }\n if (this._drawWrapperDepth.drawContext) {\n this._drawWrapperDepth.drawContext.useInstancing = this._useInstancing;\n }\n if (this._drawWrapperFogDepth.drawContext) {\n this._drawWrapperFogDepth.drawContext.useInstancing = this._useInstancing;\n }\n const defines = this._pixelPerfect ? \"#define PIXEL_PERFECT\\n\" : \"\";\n this._drawWrapperBase.effect = this._engine.createEffect(\"sprites\", [VertexBuffer.PositionKind, \"options\", \"offsets\", \"inverts\", \"cellInfo\", VertexBuffer.ColorKind], [\"view\", \"projection\", \"textureInfos\", \"alphaTest\"], [\"diffuseSampler\"], defines);\n this._drawWrapperDepth.effect = this._drawWrapperBase.effect;\n this._drawWrapperDepth.materialContext = this._drawWrapperBase.materialContext;\n if (this._scene) {\n this._drawWrapperFog.effect = this._scene\n .getEngine()\n .createEffect(\"sprites\", [VertexBuffer.PositionKind, \"options\", \"offsets\", \"inverts\", \"cellInfo\", VertexBuffer.ColorKind], [\"view\", \"projection\", \"textureInfos\", \"alphaTest\", \"vFogInfos\", \"vFogColor\"], [\"diffuseSampler\"], defines + \"#define FOG\");\n this._drawWrapperFogDepth.effect = this._drawWrapperFog.effect;\n this._drawWrapperFogDepth.materialContext = this._drawWrapperFog.materialContext;\n }\n }\n /**\n * Render all child sprites\n * @param sprites defines the list of sprites to render\n * @param deltaTime defines the time since last frame\n * @param viewMatrix defines the viewMatrix to use to render the sprites\n * @param projectionMatrix defines the projectionMatrix to use to render the sprites\n * @param customSpriteUpdate defines a custom function to update the sprites data before they render\n */\n render(sprites, deltaTime, viewMatrix, projectionMatrix, customSpriteUpdate = null) {\n if (!this.texture || !this.texture.isReady() || !sprites.length) {\n return;\n }\n let drawWrapper = this._drawWrapperBase;\n let drawWrapperDepth = this._drawWrapperDepth;\n let shouldRenderFog = false;\n if (this.fogEnabled && this._scene && this._scene.fogEnabled && this._scene.fogMode !== 0) {\n drawWrapper = this._drawWrapperFog;\n drawWrapperDepth = this._drawWrapperFogDepth;\n shouldRenderFog = true;\n }\n const effect = drawWrapper.effect;\n // Check\n if (!effect.isReady()) {\n return;\n }\n const engine = this._engine;\n const useRightHandedSystem = !!(this._scene && this._scene.useRightHandedSystem);\n const baseSize = this.texture.getBaseSize();\n // Sprites\n const max = Math.min(this._capacity, sprites.length);\n let offset = 0;\n let noSprite = true;\n for (let index = 0; index < max; index++) {\n const sprite = sprites[index];\n if (!sprite || !sprite.isVisible) {\n continue;\n }\n noSprite = false;\n sprite._animate(deltaTime);\n this._appendSpriteVertex(offset++, sprite, 0, 0, baseSize, useRightHandedSystem, customSpriteUpdate);\n if (!this._useInstancing) {\n this._appendSpriteVertex(offset++, sprite, 1, 0, baseSize, useRightHandedSystem, customSpriteUpdate);\n this._appendSpriteVertex(offset++, sprite, 1, 1, baseSize, useRightHandedSystem, customSpriteUpdate);\n this._appendSpriteVertex(offset++, sprite, 0, 1, baseSize, useRightHandedSystem, customSpriteUpdate);\n }\n }\n if (noSprite) {\n return;\n }\n this._buffer.update(this._vertexData);\n const culling = !!engine.depthCullingState.cull;\n const zOffset = engine.depthCullingState.zOffset;\n const zOffsetUnits = engine.depthCullingState.zOffsetUnits;\n engine.setState(culling, zOffset, false, false, undefined, undefined, zOffsetUnits);\n // Render\n engine.enableEffect(drawWrapper);\n effect.setTexture(\"diffuseSampler\", this.texture);\n effect.setMatrix(\"view\", viewMatrix);\n effect.setMatrix(\"projection\", projectionMatrix);\n // Scene Info\n if (shouldRenderFog) {\n const scene = this._scene;\n // Fog\n effect.setFloat4(\"vFogInfos\", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);\n effect.setColor3(\"vFogColor\", scene.fogColor);\n }\n if (this._useVAO) {\n if (!this._vertexArrayObject) {\n this._vertexArrayObject = engine.recordVertexArrayObject(this._vertexBuffers, this._indexBuffer, effect);\n }\n engine.bindVertexArrayObject(this._vertexArrayObject, this._indexBuffer);\n }\n else {\n // VBOs\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);\n }\n // Draw order\n engine.depthCullingState.depthFunc = engine.useReverseDepthBuffer ? 518 : 515;\n if (!this.disableDepthWrite) {\n effect.setBool(\"alphaTest\", true);\n engine.setColorWrite(false);\n engine.enableEffect(drawWrapperDepth);\n if (this._useInstancing) {\n engine.drawArraysType(7, 0, 4, offset);\n }\n else {\n engine.drawElementsType(0, 0, (offset / 4) * 6);\n }\n engine.enableEffect(drawWrapper);\n engine.setColorWrite(true);\n effect.setBool(\"alphaTest\", false);\n }\n engine.setAlphaMode(this.blendMode);\n if (this._useInstancing) {\n engine.drawArraysType(7, 0, 4, offset);\n }\n else {\n engine.drawElementsType(0, 0, (offset / 4) * 6);\n }\n if (this.autoResetAlpha) {\n engine.setAlphaMode(0);\n }\n // Restore Right Handed\n if (useRightHandedSystem) {\n this._scene.getEngine().setState(culling, zOffset, false, true, undefined, undefined, zOffsetUnits);\n }\n engine.unbindInstanceAttributes();\n }\n _appendSpriteVertex(index, sprite, offsetX, offsetY, baseSize, useRightHandedSystem, customSpriteUpdate) {\n let arrayOffset = index * this._vertexBufferSize;\n if (offsetX === 0) {\n offsetX = this._epsilon;\n }\n else if (offsetX === 1) {\n offsetX = 1 - this._epsilon;\n }\n if (offsetY === 0) {\n offsetY = this._epsilon;\n }\n else if (offsetY === 1) {\n offsetY = 1 - this._epsilon;\n }\n if (customSpriteUpdate) {\n customSpriteUpdate(sprite, baseSize);\n }\n else {\n if (!sprite.cellIndex) {\n sprite.cellIndex = 0;\n }\n const rowSize = baseSize.width / this.cellWidth;\n const offset = (sprite.cellIndex / rowSize) >> 0;\n sprite._xOffset = ((sprite.cellIndex - offset * rowSize) * this.cellWidth) / baseSize.width;\n sprite._yOffset = (offset * this.cellHeight) / baseSize.height;\n sprite._xSize = this.cellWidth;\n sprite._ySize = this.cellHeight;\n }\n // Positions\n this._vertexData[arrayOffset] = sprite.position.x;\n this._vertexData[arrayOffset + 1] = sprite.position.y;\n this._vertexData[arrayOffset + 2] = sprite.position.z;\n this._vertexData[arrayOffset + 3] = sprite.angle;\n // Options\n this._vertexData[arrayOffset + 4] = sprite.width;\n this._vertexData[arrayOffset + 5] = sprite.height;\n if (!this._useInstancing) {\n this._vertexData[arrayOffset + 6] = offsetX;\n this._vertexData[arrayOffset + 7] = offsetY;\n }\n else {\n arrayOffset -= 2;\n }\n // Inverts according to Right Handed\n if (useRightHandedSystem) {\n this._vertexData[arrayOffset + 8] = sprite.invertU ? 0 : 1;\n }\n else {\n this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;\n }\n this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;\n this._vertexData[arrayOffset + 10] = sprite._xOffset;\n this._vertexData[arrayOffset + 11] = sprite._yOffset;\n this._vertexData[arrayOffset + 12] = sprite._xSize / baseSize.width;\n this._vertexData[arrayOffset + 13] = sprite._ySize / baseSize.height;\n // Color\n this._vertexData[arrayOffset + 14] = sprite.color.r;\n this._vertexData[arrayOffset + 15] = sprite.color.g;\n this._vertexData[arrayOffset + 16] = sprite.color.b;\n this._vertexData[arrayOffset + 17] = sprite.color.a;\n }\n _buildIndexBuffer() {\n const indices = [];\n let index = 0;\n for (let count = 0; count < this._capacity; count++) {\n indices.push(index);\n indices.push(index + 1);\n indices.push(index + 2);\n indices.push(index);\n indices.push(index + 2);\n indices.push(index + 3);\n index += 4;\n }\n this._indexBuffer = this._engine.createIndexBuffer(indices);\n }\n /**\n * Rebuilds the renderer (after a context lost, for eg)\n */\n rebuild() {\n var _a;\n if (this._indexBuffer) {\n this._buildIndexBuffer();\n }\n if (this._useVAO) {\n this._vertexArrayObject = undefined;\n }\n this._buffer._rebuild();\n for (const key in this._vertexBuffers) {\n const vertexBuffer = this._vertexBuffers[key];\n vertexBuffer._rebuild();\n }\n (_a = this._spriteBuffer) === null || _a === void 0 ? void 0 : _a._rebuild();\n }\n /**\n * Release associated resources\n */\n dispose() {\n if (this._buffer) {\n this._buffer.dispose();\n this._buffer = null;\n }\n if (this._spriteBuffer) {\n this._spriteBuffer.dispose();\n this._spriteBuffer = null;\n }\n if (this._indexBuffer) {\n this._engine._releaseBuffer(this._indexBuffer);\n this._indexBuffer = null;\n }\n if (this._vertexArrayObject) {\n this._engine.releaseVertexArrayObject(this._vertexArrayObject);\n this._vertexArrayObject = null;\n }\n if (this.texture) {\n this.texture.dispose();\n this.texture = null;\n }\n this._drawWrapperBase.dispose();\n this._drawWrapperFog.dispose();\n this._drawWrapperDepth.dispose();\n this._drawWrapperFogDepth.dispose();\n }\n}\n//# sourceMappingURL=spriteRenderer.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { Vector3, TmpVectors, Matrix } from \"../Maths/math.vector.js\";\nimport { Sprite } from \"./sprite.js\";\nimport { SpriteSceneComponent } from \"./spriteSceneComponent.js\";\nimport { PickingInfo } from \"../Collisions/pickingInfo.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { Tools } from \"../Misc/tools.js\";\nimport { WebRequest } from \"../Misc/webRequest.js\";\nimport { SpriteRenderer } from \"./spriteRenderer.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n\n/**\n * Class used to manage multiple sprites on the same spritesheet\n * @see https://doc.babylonjs.com/features/featuresDeepDive/sprites\n */\nexport class SpriteManager {\n /**\n * Callback called when the manager is disposed\n */\n set onDispose(callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n }\n /**\n * Gets the array of sprites\n */\n get children() {\n return this.sprites;\n }\n /**\n * Gets the hosting scene\n */\n get scene() {\n return this._scene;\n }\n /**\n * Gets the capacity of the manager\n */\n get capacity() {\n return this._spriteRenderer.capacity;\n }\n /**\n * Gets or sets the spritesheet texture\n */\n get texture() {\n return this._spriteRenderer.texture;\n }\n set texture(value) {\n value.wrapU = Texture.CLAMP_ADDRESSMODE;\n value.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._spriteRenderer.texture = value;\n this._textureContent = null;\n }\n /** Defines the default width of a cell in the spritesheet */\n get cellWidth() {\n return this._spriteRenderer.cellWidth;\n }\n set cellWidth(value) {\n this._spriteRenderer.cellWidth = value;\n }\n /** Defines the default height of a cell in the spritesheet */\n get cellHeight() {\n return this._spriteRenderer.cellHeight;\n }\n set cellHeight(value) {\n this._spriteRenderer.cellHeight = value;\n }\n /** Gets or sets a boolean indicating if the manager must consider scene fog when rendering */\n get fogEnabled() {\n return this._spriteRenderer.fogEnabled;\n }\n set fogEnabled(value) {\n this._spriteRenderer.fogEnabled = value;\n }\n /**\n * Blend mode use to render the particle, it can be any of\n * the static undefined properties provided in this class.\n * Default value is 2\n */\n get blendMode() {\n return this._spriteRenderer.blendMode;\n }\n set blendMode(blendMode) {\n this._spriteRenderer.blendMode = blendMode;\n }\n /** Disables writing to the depth buffer when rendering the sprites.\n * It can be handy to disable depth writing when using textures without alpha channel\n * and setting some specific blend modes.\n */\n get disableDepthWrite() {\n return this._disableDepthWrite;\n }\n set disableDepthWrite(value) {\n this._disableDepthWrite = value;\n this._spriteRenderer.disableDepthWrite = value;\n }\n /**\n * Gets or sets a boolean indicating if the renderer must render sprites with pixel perfect rendering\n * In this mode, sprites are rendered as \"pixel art\", which means that they appear as pixelated but remain stable when moving or when rotated or scaled.\n * Note that for this mode to work as expected, the sprite texture must use the BILINEAR sampling mode, not NEAREST!\n */\n get pixelPerfect() {\n return this._spriteRenderer.pixelPerfect;\n }\n set pixelPerfect(value) {\n this._spriteRenderer.pixelPerfect = value;\n if (value && this.texture.samplingMode !== 3) {\n this.texture.updateSamplingMode(3);\n }\n }\n /**\n * Creates a new sprite manager\n * @param name defines the manager's name\n * @param imgUrl defines the sprite sheet url\n * @param capacity defines the maximum allowed number of sprites\n * @param cellSize defines the size of a sprite cell\n * @param scene defines the hosting scene\n * @param epsilon defines the epsilon value to align texture (0.01 by default)\n * @param samplingMode defines the sampling mode to use with spritesheet\n * @param fromPacked set to false; do not alter\n * @param spriteJSON null otherwise a JSON object defining sprite sheet data; do not alter\n */\n constructor(\n /** defines the manager's name */\n name, imgUrl, capacity, cellSize, scene, epsilon = 0.01, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, fromPacked = false, spriteJSON = null) {\n this.name = name;\n /** Gets the list of sprites */\n this.sprites = new Array();\n /** Gets or sets the rendering group id (0 by default) */\n this.renderingGroupId = 0;\n /** Gets or sets camera layer mask */\n this.layerMask = 0x0fffffff;\n /** Gets or sets a boolean indicating if the sprites are pickable */\n this.isPickable = false;\n /**\n * Gets or sets an object used to store user defined information for the sprite manager\n */\n this.metadata = null;\n /** @internal */\n this._wasDispatched = false;\n /**\n * An event triggered when the manager is disposed.\n */\n this.onDisposeObservable = new Observable();\n this._disableDepthWrite = false;\n /** True when packed cell data from JSON file is ready*/\n this._packedAndReady = false;\n this._customUpdate = (sprite, baseSize) => {\n if (!sprite.cellRef) {\n sprite.cellIndex = 0;\n }\n const num = sprite.cellIndex;\n if (typeof num === \"number\" && isFinite(num) && Math.floor(num) === num) {\n sprite.cellRef = this._spriteMap[sprite.cellIndex];\n }\n sprite._xOffset = this._cellData[sprite.cellRef].frame.x / baseSize.width;\n sprite._yOffset = this._cellData[sprite.cellRef].frame.y / baseSize.height;\n sprite._xSize = this._cellData[sprite.cellRef].frame.w;\n sprite._ySize = this._cellData[sprite.cellRef].frame.h;\n };\n if (!scene) {\n scene = EngineStore.LastCreatedScene;\n }\n if (!scene._getComponent(SceneComponentConstants.NAME_SPRITE)) {\n scene._addComponent(new SpriteSceneComponent(scene));\n }\n this._fromPacked = fromPacked;\n this._scene = scene;\n const engine = this._scene.getEngine();\n this._spriteRenderer = new SpriteRenderer(engine, capacity, epsilon, scene);\n if (cellSize.width && cellSize.height) {\n this.cellWidth = cellSize.width;\n this.cellHeight = cellSize.height;\n }\n else if (cellSize !== undefined) {\n this.cellWidth = cellSize;\n this.cellHeight = cellSize;\n }\n else {\n this._spriteRenderer = null;\n return;\n }\n this._scene.spriteManagers && this._scene.spriteManagers.push(this);\n this.uniqueId = this.scene.getUniqueId();\n if (imgUrl) {\n this.texture = new Texture(imgUrl, scene, true, false, samplingMode);\n }\n if (this._fromPacked) {\n this._makePacked(imgUrl, spriteJSON);\n }\n }\n /**\n * Returns the string \"SpriteManager\"\n * @returns \"SpriteManager\"\n */\n getClassName() {\n return \"SpriteManager\";\n }\n _makePacked(imgUrl, spriteJSON) {\n if (spriteJSON !== null) {\n try {\n //Get the JSON and Check its structure. If its an array parse it if its a JSON string etc...\n let celldata;\n if (typeof spriteJSON === \"string\") {\n celldata = JSON.parse(spriteJSON);\n }\n else {\n celldata = spriteJSON;\n }\n if (celldata.frames.length) {\n const frametemp = {};\n for (let i = 0; i < celldata.frames.length; i++) {\n const _f = celldata.frames[i];\n if (typeof Object.keys(_f)[0] !== \"string\") {\n throw new Error(\"Invalid JSON Format. Check the frame values and make sure the name is the first parameter.\");\n }\n const name = _f[Object.keys(_f)[0]];\n frametemp[name] = _f;\n }\n celldata.frames = frametemp;\n }\n const spritemap = Reflect.ownKeys(celldata.frames);\n this._spriteMap = spritemap;\n this._packedAndReady = true;\n this._cellData = celldata.frames;\n }\n catch (e) {\n this._fromPacked = false;\n this._packedAndReady = false;\n throw new Error(\"Invalid JSON from string. Spritesheet managed with constant cell size.\");\n }\n }\n else {\n const re = /\\./g;\n let li;\n do {\n li = re.lastIndex;\n re.test(imgUrl);\n } while (re.lastIndex > 0);\n const jsonUrl = imgUrl.substring(0, li - 1) + \".json\";\n const onerror = () => {\n Logger.Error(\"JSON ERROR: Unable to load JSON file.\");\n this._fromPacked = false;\n this._packedAndReady = false;\n };\n const onload = (data) => {\n try {\n const celldata = JSON.parse(data);\n const spritemap = Reflect.ownKeys(celldata.frames);\n this._spriteMap = spritemap;\n this._packedAndReady = true;\n this._cellData = celldata.frames;\n }\n catch (e) {\n this._fromPacked = false;\n this._packedAndReady = false;\n throw new Error(\"Invalid JSON format. Please check documentation for format specifications.\");\n }\n };\n Tools.LoadFile(jsonUrl, onload, undefined, undefined, false, onerror);\n }\n }\n _checkTextureAlpha(sprite, ray, distance, min, max) {\n if (!sprite.useAlphaForPicking || !this.texture) {\n return true;\n }\n const textureSize = this.texture.getSize();\n if (!this._textureContent) {\n this._textureContent = new Uint8Array(textureSize.width * textureSize.height * 4);\n this.texture.readPixels(0, 0, this._textureContent);\n }\n const contactPoint = TmpVectors.Vector3[0];\n contactPoint.copyFrom(ray.direction);\n contactPoint.normalize();\n contactPoint.scaleInPlace(distance);\n contactPoint.addInPlace(ray.origin);\n const contactPointU = (contactPoint.x - min.x) / (max.x - min.x);\n const contactPointV = 1.0 - (contactPoint.y - min.y) / (max.y - min.y);\n const u = (sprite._xOffset * textureSize.width + contactPointU * sprite._xSize) | 0;\n const v = (sprite._yOffset * textureSize.height + contactPointV * sprite._ySize) | 0;\n const alpha = this._textureContent[(u + v * textureSize.width) * 4 + 3];\n return alpha > 0.5;\n }\n /**\n * Intersects the sprites with a ray\n * @param ray defines the ray to intersect with\n * @param camera defines the current active camera\n * @param predicate defines a predicate used to select candidate sprites\n * @param fastCheck defines if a fast check only must be done (the first potential sprite is will be used and not the closer)\n * @returns null if no hit or a PickingInfo\n */\n intersects(ray, camera, predicate, fastCheck) {\n const count = Math.min(this.capacity, this.sprites.length);\n const min = Vector3.Zero();\n const max = Vector3.Zero();\n let distance = Number.MAX_VALUE;\n let currentSprite = null;\n const pickedPoint = TmpVectors.Vector3[0];\n const cameraSpacePosition = TmpVectors.Vector3[1];\n const cameraView = camera.getViewMatrix();\n let activeRay = ray;\n let pickedRay = ray;\n for (let index = 0; index < count; index++) {\n const sprite = this.sprites[index];\n if (!sprite) {\n continue;\n }\n if (predicate) {\n if (!predicate(sprite)) {\n continue;\n }\n }\n else if (!sprite.isPickable) {\n continue;\n }\n Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);\n if (sprite.angle) {\n // Create a rotation matrix to rotate the ray to the sprite's rotation\n Matrix.TranslationToRef(-cameraSpacePosition.x, -cameraSpacePosition.y, 0, TmpVectors.Matrix[1]);\n Matrix.TranslationToRef(cameraSpacePosition.x, cameraSpacePosition.y, 0, TmpVectors.Matrix[2]);\n Matrix.RotationZToRef(-sprite.angle, TmpVectors.Matrix[3]);\n // inv translation x rotation x translation\n TmpVectors.Matrix[1].multiplyToRef(TmpVectors.Matrix[3], TmpVectors.Matrix[4]);\n TmpVectors.Matrix[4].multiplyToRef(TmpVectors.Matrix[2], TmpVectors.Matrix[0]);\n activeRay = ray.clone();\n Vector3.TransformCoordinatesToRef(ray.origin, TmpVectors.Matrix[0], activeRay.origin);\n Vector3.TransformNormalToRef(ray.direction, TmpVectors.Matrix[0], activeRay.direction);\n }\n else {\n activeRay = ray;\n }\n min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);\n max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);\n if (activeRay.intersectsBoxMinMax(min, max)) {\n const currentDistance = Vector3.Distance(cameraSpacePosition, activeRay.origin);\n if (distance > currentDistance) {\n if (!this._checkTextureAlpha(sprite, activeRay, currentDistance, min, max)) {\n continue;\n }\n pickedRay = activeRay;\n distance = currentDistance;\n currentSprite = sprite;\n if (fastCheck) {\n break;\n }\n }\n }\n }\n if (currentSprite) {\n const result = new PickingInfo();\n cameraView.invertToRef(TmpVectors.Matrix[0]);\n result.hit = true;\n result.pickedSprite = currentSprite;\n result.distance = distance;\n // Get picked point\n const direction = TmpVectors.Vector3[2];\n direction.copyFrom(pickedRay.direction);\n direction.normalize();\n direction.scaleInPlace(distance);\n pickedRay.origin.addToRef(direction, pickedPoint);\n result.pickedPoint = Vector3.TransformCoordinates(pickedPoint, TmpVectors.Matrix[0]);\n return result;\n }\n return null;\n }\n /**\n * Intersects the sprites with a ray\n * @param ray defines the ray to intersect with\n * @param camera defines the current active camera\n * @param predicate defines a predicate used to select candidate sprites\n * @returns null if no hit or a PickingInfo array\n */\n multiIntersects(ray, camera, predicate) {\n const count = Math.min(this.capacity, this.sprites.length);\n const min = Vector3.Zero();\n const max = Vector3.Zero();\n let distance;\n const results = [];\n const pickedPoint = TmpVectors.Vector3[0].copyFromFloats(0, 0, 0);\n const cameraSpacePosition = TmpVectors.Vector3[1].copyFromFloats(0, 0, 0);\n const cameraView = camera.getViewMatrix();\n for (let index = 0; index < count; index++) {\n const sprite = this.sprites[index];\n if (!sprite) {\n continue;\n }\n if (predicate) {\n if (!predicate(sprite)) {\n continue;\n }\n }\n else if (!sprite.isPickable) {\n continue;\n }\n Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);\n min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);\n max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);\n if (ray.intersectsBoxMinMax(min, max)) {\n distance = Vector3.Distance(cameraSpacePosition, ray.origin);\n if (!this._checkTextureAlpha(sprite, ray, distance, min, max)) {\n continue;\n }\n const result = new PickingInfo();\n results.push(result);\n cameraView.invertToRef(TmpVectors.Matrix[0]);\n result.hit = true;\n result.pickedSprite = sprite;\n result.distance = distance;\n // Get picked point\n const direction = TmpVectors.Vector3[2];\n direction.copyFrom(ray.direction);\n direction.normalize();\n direction.scaleInPlace(distance);\n ray.origin.addToRef(direction, pickedPoint);\n result.pickedPoint = Vector3.TransformCoordinates(pickedPoint, TmpVectors.Matrix[0]);\n }\n }\n return results;\n }\n /**\n * Render all child sprites\n */\n render() {\n // Check\n if (this._fromPacked && (!this._packedAndReady || !this._spriteMap || !this._cellData)) {\n return;\n }\n const engine = this._scene.getEngine();\n const deltaTime = engine.getDeltaTime();\n if (this._packedAndReady) {\n this._spriteRenderer.render(this.sprites, deltaTime, this._scene.getViewMatrix(), this._scene.getProjectionMatrix(), this._customUpdate);\n }\n else {\n this._spriteRenderer.render(this.sprites, deltaTime, this._scene.getViewMatrix(), this._scene.getProjectionMatrix());\n }\n }\n /**\n * Rebuilds the manager (after a context lost, for eg)\n */\n rebuild() {\n var _a;\n (_a = this._spriteRenderer) === null || _a === void 0 ? void 0 : _a.rebuild();\n }\n /**\n * Release associated resources\n */\n dispose() {\n if (this._spriteRenderer) {\n this._spriteRenderer.dispose();\n this._spriteRenderer = null;\n }\n this._textureContent = null;\n // Remove from scene\n if (this._scene.spriteManagers) {\n const index = this._scene.spriteManagers.indexOf(this);\n this._scene.spriteManagers.splice(index, 1);\n }\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n this.metadata = null;\n }\n /**\n * Serializes the sprite manager to a JSON object\n * @param serializeTexture defines if the texture must be serialized as well\n * @returns the JSON object\n */\n serialize(serializeTexture = false) {\n const serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.capacity = this.capacity;\n serializationObject.cellWidth = this.cellWidth;\n serializationObject.cellHeight = this.cellHeight;\n serializationObject.fogEnabled = this.fogEnabled;\n serializationObject.blendMode = this.blendMode;\n serializationObject.disableDepthWrite = this.disableDepthWrite;\n serializationObject.pixelPerfect = this.pixelPerfect;\n if (this.texture) {\n if (serializeTexture) {\n serializationObject.texture = this.texture.serialize();\n }\n else {\n serializationObject.textureUrl = this.texture.name;\n serializationObject.invertY = this.texture._invertY;\n }\n }\n serializationObject.sprites = [];\n for (const sprite of this.sprites) {\n serializationObject.sprites.push(sprite.serialize());\n }\n serializationObject.metadata = this.metadata;\n return serializationObject;\n }\n /**\n * Parses a JSON object to create a new sprite manager.\n * @param parsedManager The JSON object to parse\n * @param scene The scene to create the sprite manager\n * @param rootUrl The root url to use to load external dependencies like texture\n * @returns the new sprite manager\n */\n static Parse(parsedManager, scene, rootUrl) {\n const manager = new SpriteManager(parsedManager.name, \"\", parsedManager.capacity, {\n width: parsedManager.cellWidth,\n height: parsedManager.cellHeight,\n }, scene);\n if (parsedManager.fogEnabled !== undefined) {\n manager.fogEnabled = parsedManager.fogEnabled;\n }\n if (parsedManager.blendMode !== undefined) {\n manager.blendMode = parsedManager.blendMode;\n }\n if (parsedManager.disableDepthWrite !== undefined) {\n manager.disableDepthWrite = parsedManager.disableDepthWrite;\n }\n if (parsedManager.pixelPerfect !== undefined) {\n manager.pixelPerfect = parsedManager.pixelPerfect;\n }\n if (parsedManager.metadata !== undefined) {\n manager.metadata = parsedManager.metadata;\n }\n if (parsedManager.texture) {\n manager.texture = Texture.Parse(parsedManager.texture, scene, rootUrl);\n }\n else if (parsedManager.textureName) {\n manager.texture = new Texture(rootUrl + parsedManager.textureUrl, scene, false, parsedManager.invertY !== undefined ? parsedManager.invertY : true);\n }\n for (const parsedSprite of parsedManager.sprites) {\n Sprite.Parse(parsedSprite, manager);\n }\n return manager;\n }\n /**\n * Creates a sprite manager from a snippet saved in a remote file\n * @param name defines the name of the sprite manager to create (can be null or empty to use the one from the json data)\n * @param url defines the url to load from\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @returns a promise that will resolve to the new sprite manager\n */\n static ParseFromFileAsync(name, url, scene, rootUrl = \"\") {\n return new Promise((resolve, reject) => {\n const request = new WebRequest();\n request.addEventListener(\"readystatechange\", () => {\n if (request.readyState == 4) {\n if (request.status == 200) {\n const serializationObject = JSON.parse(request.responseText);\n const output = SpriteManager.Parse(serializationObject, scene || EngineStore.LastCreatedScene, rootUrl);\n if (name) {\n output.name = name;\n }\n resolve(output);\n }\n else {\n reject(\"Unable to load the sprite manager\");\n }\n }\n });\n request.open(\"GET\", url);\n request.send();\n });\n }\n /**\n * Creates a sprite manager from a snippet saved by the sprite editor\n * @param snippetId defines the snippet to load (can be set to _BLANK to create a default one)\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @returns a promise that will resolve to the new sprite manager\n */\n static ParseFromSnippetAsync(snippetId, scene, rootUrl = \"\") {\n if (snippetId === \"_BLANK\") {\n return Promise.resolve(new SpriteManager(\"Default sprite manager\", \"//playground.babylonjs.com/textures/player.png\", 500, 64, scene));\n }\n return new Promise((resolve, reject) => {\n const request = new WebRequest();\n request.addEventListener(\"readystatechange\", () => {\n if (request.readyState == 4) {\n if (request.status == 200) {\n const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload);\n const serializationObject = JSON.parse(snippet.spriteManager);\n const output = SpriteManager.Parse(serializationObject, scene || EngineStore.LastCreatedScene, rootUrl);\n output.snippetId = snippetId;\n resolve(output);\n }\n else {\n reject(\"Unable to load the snippet \" + snippetId);\n }\n }\n });\n request.open(\"GET\", this.SnippetUrl + \"/\" + snippetId.replace(/#/g, \"/\"));\n request.send();\n });\n }\n}\n/** Define the Url to load snippets */\nSpriteManager.SnippetUrl = `https://snippet.babylonjs.com`;\n/**\n * Creates a sprite manager from a snippet saved by the sprite editor\n * @deprecated Please use ParseFromSnippetAsync instead\n * @param snippetId defines the snippet to load (can be set to _BLANK to create a default one)\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @returns a promise that will resolve to the new sprite manager\n */\nSpriteManager.CreateFromSnippetAsync = SpriteManager.ParseFromSnippetAsync;\n//# sourceMappingURL=spriteManager.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"spriteMapPixelShader\";\nconst shader = `#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nprecision highp float;\rvarying vec3 vPosition;\rvarying vec2 vUV;\rvarying vec2 tUV;\runiform float time;\runiform float spriteCount;\runiform sampler2D spriteSheet;\runiform vec2 spriteMapSize;\runiform vec2 outputSize;\runiform vec2 stageSize;\runiform sampler2D frameMap;\runiform sampler2D tileMaps[LAYERS];\runiform sampler2D animationMap;\runiform vec3 colorMul;\rfloat mt;\rconst float fdStep=1./4.;\rconst float aFrameSteps=1./MAX_ANIMATION_FRAMES;\rmat4 getFrameData(float frameID){\rfloat fX=frameID/spriteCount;\rreturn mat4(\rtexture2D(frameMap,vec2(fX,0.),0.),\rtexture2D(frameMap,vec2(fX,fdStep*1.),0.),\rtexture2D(frameMap,vec2(fX,fdStep*2.),0.),\rvec4(0.)\r);\r}\rvoid main(){\rvec4 color=vec4(0.);\rvec2 tileUV=fract(tUV);\r#ifdef FLIPU\ntileUV.y=1.0-tileUV.y;\r#endif\nvec2 tileID=floor(tUV);\rvec2 sheetUnits=1./spriteMapSize;\rfloat spriteUnits=1./spriteCount;\rvec2 stageUnits=1./stageSize;\rfor(int i=0; i0.) {\rmt=mod(time*animationData.z,1.0);\rfor(float f=0.; fmt){\rframeID=animationData.x;\rbreak;\r}\ranimationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.);\r}\r}\rmat4 frameData=getFrameData(frameID+0.5);\rvec2 frameSize=(frameData[0].zw)/spriteMapSize;\rvec2 offset=frameData[0].xy*sheetUnits;\rvec2 ratio=frameData[2].xy/frameData[0].zw;\rif (frameData[2].z==1.){\rtileUV.xy=tileUV.yx;\r}\rvec4 nc=texture2D(spriteSheet,tileUV*frameSize+offset);\rif (i==0){\rcolor=nc;\r} else {\rfloat alpha=min(color.a+nc.a,1.0);\rvec3 mixed=mix(color.xyz,nc.xyz,nc.a);\rcolor=vec4(mixed,alpha);\r}\r}\rcolor.xyz*=colorMul;\rgl_FragColor=color;\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const spriteMapPixelShader = { name, shader };\n//# sourceMappingURL=spriteMap.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"spriteMapVertexShader\";\nconst shader = `precision highp float;\rattribute vec3 position;\rattribute vec3 normal;\rattribute vec2 uv;\rvarying vec3 vPosition;\rvarying vec2 vUV;\rvarying vec2 tUV;\rvarying vec2 stageUnits;\rvarying vec2 levelUnits;\rvarying vec2 tileID;\runiform float time;\runiform mat4 worldViewProjection;\runiform vec2 outputSize;\runiform vec2 stageSize;\runiform vec2 spriteMapSize;\runiform float stageScale;\rvoid main() {\rvec4 p=vec4( position,1. );\rvPosition=p.xyz;\rvUV=uv;\rtUV=uv*stageSize; \rgl_Position=worldViewProjection*p;\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const spriteMapVertexShader = { name, shader };\n//# sourceMappingURL=spriteMap.vertex.js.map","import { Engine } from \"../Engines/engine.js\";\nimport { Vector2, Vector3 } from \"../Maths/math.vector.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { RawTexture } from \"../Materials/Textures/rawTexture.js\";\nimport { ShaderMaterial } from \"../Materials/shaderMaterial.js\";\nimport { Effect } from \"../Materials/effect.js\";\nimport { CreatePlane } from \"../Meshes/Builders/planeBuilder.js\";\nimport \"../Shaders/spriteMap.fragment.js\";\nimport \"../Shaders/spriteMap.vertex.js\";\n/**\n * Class used to manage a grid restricted sprite deployment on an Output plane.\n */\nexport class SpriteMap {\n /** Returns the Number of Sprites in the System */\n get spriteCount() {\n return this.sprites.length;\n }\n /** Returns the Position of Output Plane*/\n get position() {\n return this._output.position;\n }\n /** Returns the Position of Output Plane*/\n set position(v) {\n this._output.position = v;\n }\n /** Returns the Rotation of Output Plane*/\n get rotation() {\n return this._output.rotation;\n }\n /** Returns the Rotation of Output Plane*/\n set rotation(v) {\n this._output.rotation = v;\n }\n /** Sets the AnimationMap*/\n get animationMap() {\n return this._animationMap;\n }\n /** Sets the AnimationMap*/\n set animationMap(v) {\n const buffer = v._texture._bufferView;\n const am = this._createTileAnimationBuffer(buffer);\n this._animationMap.dispose();\n this._animationMap = am;\n this._material.setTexture(\"animationMap\", this._animationMap);\n }\n /**\n * Creates a new SpriteMap\n * @param name defines the SpriteMaps Name\n * @param atlasJSON is the JSON file that controls the Sprites Frames and Meta\n * @param spriteSheet is the Texture that the Sprites are on.\n * @param options a basic deployment configuration\n * @param scene The Scene that the map is deployed on\n */\n constructor(name, atlasJSON, spriteSheet, options, scene) {\n this.name = name;\n this.sprites = [];\n this.atlasJSON = atlasJSON;\n this.sprites = this.atlasJSON[\"frames\"];\n this.spriteSheet = spriteSheet;\n /**\n * Run through the options and set what ever defaults are needed that where not declared.\n */\n this.options = options;\n options.stageSize = options.stageSize || new Vector2(1, 1);\n options.outputSize = options.outputSize || options.stageSize;\n options.outputPosition = options.outputPosition || Vector3.Zero();\n options.outputRotation = options.outputRotation || Vector3.Zero();\n options.layerCount = options.layerCount || 1;\n options.maxAnimationFrames = options.maxAnimationFrames || 0;\n options.baseTile = options.baseTile || 0;\n options.flipU = options.flipU || false;\n options.colorMultiply = options.colorMultiply || new Vector3(1, 1, 1);\n this._scene = scene;\n this._frameMap = this._createFrameBuffer();\n this._tileMaps = new Array();\n for (let i = 0; i < options.layerCount; i++) {\n this._tileMaps.push(this._createTileBuffer(null, i));\n }\n this._animationMap = this._createTileAnimationBuffer(null);\n const defines = [];\n defines.push(\"#define LAYERS \" + options.layerCount);\n if (options.flipU) {\n defines.push(\"#define FLIPU\");\n }\n defines.push(`#define MAX_ANIMATION_FRAMES ${options.maxAnimationFrames}.0`);\n const shaderString = Effect.ShadersStore[\"spriteMapPixelShader\"];\n let layerSampleString;\n if (!scene.getEngine()._features.supportSwitchCaseInShader) {\n layerSampleString = \"\";\n for (let i = 0; i < options.layerCount; i++) {\n layerSampleString += `if (${i} == i) { frameID = texture2D(tileMaps[${i}], (tileID + 0.5) / stageSize, 0.).x; }`;\n }\n }\n else {\n layerSampleString = \"switch(i) {\";\n for (let i = 0; i < options.layerCount; i++) {\n layerSampleString += \"case \" + i + \" : frameID = texture(tileMaps[\" + i + \"], (tileID + 0.5) / stageSize, 0.).x;\";\n layerSampleString += \"break;\";\n }\n layerSampleString += \"}\";\n }\n Effect.ShadersStore[\"spriteMap\" + this.name + \"PixelShader\"] = shaderString.replace(\"#define LAYER_ID_SWITCH\", layerSampleString);\n this._material = new ShaderMaterial(\"spriteMap:\" + this.name, this._scene, {\n vertex: \"spriteMap\",\n fragment: \"spriteMap\" + this.name,\n }, {\n defines,\n attributes: [\"position\", \"normal\", \"uv\"],\n uniforms: [\"worldViewProjection\", \"time\", \"stageSize\", \"outputSize\", \"spriteMapSize\", \"spriteCount\", \"time\", \"colorMul\", \"mousePosition\", \"curTile\", \"flipU\"],\n samplers: [\"spriteSheet\", \"frameMap\", \"tileMaps\", \"animationMap\"],\n needAlphaBlending: true,\n });\n this._time = 0;\n this._material.setFloat(\"spriteCount\", this.spriteCount);\n this._material.setVector2(\"stageSize\", options.stageSize);\n this._material.setVector2(\"outputSize\", options.outputSize);\n this._material.setTexture(\"spriteSheet\", this.spriteSheet);\n this._material.setVector2(\"spriteMapSize\", new Vector2(1, 1));\n this._material.setVector3(\"colorMul\", options.colorMultiply);\n let tickSave = 0;\n const bindSpriteTexture = () => {\n if (this.spriteSheet && this.spriteSheet.isReady()) {\n if (this.spriteSheet._texture) {\n this._material.setVector2(\"spriteMapSize\", new Vector2(this.spriteSheet._texture.baseWidth || 1, this.spriteSheet._texture.baseHeight || 1));\n return;\n }\n }\n if (tickSave < 100) {\n setTimeout(() => {\n tickSave++;\n bindSpriteTexture();\n }, 100);\n }\n };\n bindSpriteTexture();\n this._material.setVector3(\"colorMul\", options.colorMultiply);\n this._material.setTexture(\"frameMap\", this._frameMap);\n this._material.setTextureArray(\"tileMaps\", this._tileMaps);\n this._material.setTexture(\"animationMap\", this._animationMap);\n this._material.setFloat(\"time\", this._time);\n this._output = CreatePlane(name + \":output\", { size: 1, updatable: true }, scene);\n this._output.scaling.x = options.outputSize.x;\n this._output.scaling.y = options.outputSize.y;\n this.position = options.outputPosition;\n this.rotation = options.outputRotation;\n const obfunction = () => {\n this._time += this._scene.getEngine().getDeltaTime();\n this._material.setFloat(\"time\", this._time);\n };\n this._scene.onBeforeRenderObservable.add(obfunction);\n this._output.material = this._material;\n }\n /**\n * Returns tileID location\n * @returns Vector2 the cell position ID\n */\n getTileID() {\n const p = this.getMousePosition();\n p.multiplyInPlace(this.options.stageSize || Vector2.Zero());\n p.x = Math.floor(p.x);\n p.y = Math.floor(p.y);\n return p;\n }\n /**\n * Gets the UV location of the mouse over the SpriteMap.\n * @returns Vector2 the UV position of the mouse interaction\n */\n getMousePosition() {\n const out = this._output;\n const pickinfo = this._scene.pick(this._scene.pointerX, this._scene.pointerY, (mesh) => {\n if (mesh !== out) {\n return false;\n }\n return true;\n });\n if (!pickinfo || !pickinfo.hit || !pickinfo.getTextureCoordinates) {\n return new Vector2(-1, -1);\n }\n const coords = pickinfo.getTextureCoordinates();\n if (coords) {\n return coords;\n }\n return new Vector2(-1, -1);\n }\n /**\n * Creates the \"frame\" texture Buffer\n * -------------------------------------\n * Structure of frames\n * \"filename\": \"Falling-Water-2.png\",\n * \"frame\": {\"x\":69,\"y\":103,\"w\":24,\"h\":32},\n * \"rotated\": true,\n * \"trimmed\": true,\n * \"spriteSourceSize\": {\"x\":4,\"y\":0,\"w\":24,\"h\":32},\n * \"sourceSize\": {\"w\":32,\"h\":32}\n * @returns RawTexture of the frameMap\n */\n _createFrameBuffer() {\n const data = new Array();\n //Do two Passes\n for (let i = 0; i < this.spriteCount; i++) {\n data.push(0, 0, 0, 0); //frame\n data.push(0, 0, 0, 0); //spriteSourceSize\n data.push(0, 0, 0, 0); //sourceSize, rotated, trimmed\n data.push(0, 0, 0, 0); //Keep it pow2 cause I\"m cool like that... it helps with sampling accuracy as well. Plus then we have 4 other parameters for future stuff.\n }\n //Second Pass\n for (let i = 0; i < this.spriteCount; i++) {\n const f = this.sprites[i][\"frame\"];\n const sss = this.sprites[i][\"spriteSourceSize\"];\n const ss = this.sprites[i][\"sourceSize\"];\n const r = this.sprites[i][\"rotated\"] ? 1 : 0;\n const t = this.sprites[i][\"trimmed\"] ? 1 : 0;\n //frame\n data[i * 4] = f.x;\n data[i * 4 + 1] = f.y;\n data[i * 4 + 2] = f.w;\n data[i * 4 + 3] = f.h;\n //spriteSourceSize\n data[i * 4 + this.spriteCount * 4] = sss.x;\n data[i * 4 + 1 + this.spriteCount * 4] = sss.y;\n data[i * 4 + 3 + this.spriteCount * 4] = sss.h;\n //sourceSize, rotated, trimmed\n data[i * 4 + this.spriteCount * 8] = ss.w;\n data[i * 4 + 1 + this.spriteCount * 8] = ss.h;\n data[i * 4 + 2 + this.spriteCount * 8] = r;\n data[i * 4 + 3 + this.spriteCount * 8] = t;\n }\n const floatArray = new Float32Array(data);\n const t = RawTexture.CreateRGBATexture(floatArray, this.spriteCount, 4, this._scene, false, false, Texture.NEAREST_NEAREST, Engine.TEXTURETYPE_FLOAT);\n return t;\n }\n /**\n * Creates the tileMap texture Buffer\n * @param buffer normally and array of numbers, or a false to generate from scratch\n * @param _layer indicates what layer for a logic trigger dealing with the baseTile. The system uses this\n * @returns RawTexture of the tileMap\n */\n _createTileBuffer(buffer, _layer = 0) {\n let data = new Array();\n const _ty = this.options.stageSize.y || 0;\n const _tx = this.options.stageSize.x || 0;\n if (!buffer) {\n let bt = this.options.baseTile;\n if (_layer != 0) {\n bt = 0;\n }\n for (let y = 0; y < _ty; y++) {\n for (let x = 0; x < _tx * 4; x += 4) {\n data.push(bt, 0, 0, 0);\n }\n }\n }\n else {\n data = buffer;\n }\n const floatArray = new Float32Array(data);\n const t = RawTexture.CreateRGBATexture(floatArray, _tx, _ty, this._scene, false, false, Texture.NEAREST_NEAREST, Engine.TEXTURETYPE_FLOAT);\n return t;\n }\n /**\n * Modifies the data of the tileMaps\n * @param _layer is the ID of the layer you want to edit on the SpriteMap\n * @param pos is the iVector2 Coordinates of the Tile\n * @param tile The SpriteIndex of the new Tile\n */\n changeTiles(_layer = 0, pos, tile = 0) {\n const buffer = this._tileMaps[_layer]._texture._bufferView;\n if (buffer === null) {\n return;\n }\n let p = new Array();\n if (pos instanceof Vector2) {\n p.push(pos);\n }\n else {\n p = pos;\n }\n const _tx = this.options.stageSize.x || 0;\n for (let i = 0; i < p.length; i++) {\n const _p = p[i];\n _p.x = Math.floor(_p.x);\n _p.y = Math.floor(_p.y);\n const id = _p.x * 4 + _p.y * (_tx * 4);\n buffer[id] = tile;\n }\n const t = this._createTileBuffer(buffer);\n this._tileMaps[_layer].dispose();\n this._tileMaps[_layer] = t;\n this._material.setTextureArray(\"tileMap\", this._tileMaps);\n }\n /**\n * Creates the animationMap texture Buffer\n * @param buffer normally and array of numbers, or a false to generate from scratch\n * @returns RawTexture of the animationMap\n */\n _createTileAnimationBuffer(buffer) {\n const data = new Array();\n let floatArray;\n if (!buffer) {\n for (let i = 0; i < this.spriteCount; i++) {\n data.push(0, 0, 0, 0);\n let count = 1;\n while (count < (this.options.maxAnimationFrames || 4)) {\n data.push(0, 0, 0, 0);\n count++;\n }\n }\n floatArray = new Float32Array(data);\n }\n else {\n floatArray = buffer;\n }\n const t = RawTexture.CreateRGBATexture(floatArray, this.spriteCount, this.options.maxAnimationFrames || 4, this._scene, false, false, Texture.NEAREST_NEAREST, Engine.TEXTURETYPE_FLOAT);\n return t;\n }\n /**\n * Modifies the data of the animationMap\n * @param cellID is the Index of the Sprite\n * @param _frame is the target Animation frame\n * @param toCell is the Target Index of the next frame of the animation\n * @param time is a value between 0-1 that is the trigger for when the frame should change tiles\n * @param speed is a global scalar of the time variable on the map.\n */\n addAnimationToTile(cellID = 0, _frame = 0, toCell = 0, time = 0, speed = 1) {\n const buffer = this._animationMap._texture._bufferView;\n const id = cellID * 4 + this.spriteCount * 4 * _frame;\n if (!buffer) {\n return;\n }\n buffer[id] = toCell;\n buffer[id + 1] = time;\n buffer[id + 2] = speed;\n const t = this._createTileAnimationBuffer(buffer);\n this._animationMap.dispose();\n this._animationMap = t;\n this._material.setTexture(\"animationMap\", this._animationMap);\n }\n /**\n * Exports the .tilemaps file\n */\n saveTileMaps() {\n let maps = \"\";\n for (let i = 0; i < this._tileMaps.length; i++) {\n if (i > 0) {\n maps += \"\\n\\r\";\n }\n maps += this._tileMaps[i]._texture._bufferView.toString();\n }\n const hiddenElement = document.createElement(\"a\");\n hiddenElement.href = \"data:octet/stream;charset=utf-8,\" + encodeURI(maps);\n hiddenElement.target = \"_blank\";\n hiddenElement.download = this.name + \".tilemaps\";\n hiddenElement.click();\n hiddenElement.remove();\n }\n /**\n * Imports the .tilemaps file\n * @param url of the .tilemaps file\n */\n loadTileMaps(url) {\n const xhr = new XMLHttpRequest();\n xhr.open(\"GET\", url);\n const _lc = this.options.layerCount || 0;\n xhr.onload = () => {\n const data = xhr.response.split(\"\\n\\r\");\n for (let i = 0; i < _lc; i++) {\n const d = data[i].split(\",\").map(Number);\n const t = this._createTileBuffer(d);\n this._tileMaps[i].dispose();\n this._tileMaps[i] = t;\n }\n this._material.setTextureArray(\"tileMap\", this._tileMaps);\n };\n xhr.send();\n }\n /**\n * Release associated resources\n */\n dispose() {\n this._output.dispose();\n this._material.dispose();\n this._animationMap.dispose();\n this._tileMaps.forEach((tm) => {\n tm.dispose();\n });\n this._frameMap.dispose();\n }\n}\n//# sourceMappingURL=spriteMap.js.map","import { SpriteManager } from \"./spriteManager.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\n/**\n * Class used to manage multiple sprites of different sizes on the same spritesheet\n * @see https://doc.babylonjs.com/features/featuresDeepDive/sprites\n */\nexport class SpritePackedManager extends SpriteManager {\n /**\n * Creates a new sprite manager from a packed sprite sheet\n * @param name defines the manager's name\n * @param imgUrl defines the sprite sheet url\n * @param capacity defines the maximum allowed number of sprites\n * @param scene defines the hosting scene\n * @param spriteJSON null otherwise a JSON object defining sprite sheet data\n * @param epsilon defines the epsilon value to align texture (0.01 by default)\n * @param samplingMode defines the sampling mode to use with spritesheet\n * @param fromPacked set to true; do not alter\n */\n constructor(\n /** defines the packed manager's name */\n name, imgUrl, capacity, scene, spriteJSON = null, epsilon = 0.01, samplingMode = Texture.TRILINEAR_SAMPLINGMODE) {\n //the cellSize parameter is not used when built from JSON which provides individual cell data, defaults to 64 if JSON load fails\n super(name, imgUrl, capacity, 64, scene, epsilon, samplingMode, true, spriteJSON);\n this.name = name;\n }\n}\n//# sourceMappingURL=spritePackedManager.js.map","export * from \"./sprite.js\";\nexport * from \"./ISprites.js\";\nexport * from \"./spriteManager.js\";\nexport * from \"./spriteMap.js\";\nexport * from \"./spritePackedManager.js\";\nexport * from \"./spriteSceneComponent.js\";\n//# sourceMappingURL=index.js.map","export * from \"./alphaCullingState.js\";\nexport * from \"./depthCullingState.js\";\nexport * from \"./stencilState.js\";\nexport * from \"./stencilStateComposer.js\";\n//# sourceMappingURL=index.js.map","import { SceneLoader, SceneLoaderAnimationGroupLoadingMode } from \"../Loading/sceneLoader.js\";\nimport { Tools } from \"./tools.js\";\nimport { Observable } from \"./observable.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { CubeTexture } from \"../Materials/Textures/cubeTexture.js\";\nimport { HDRCubeTexture } from \"../Materials/Textures/hdrCubeTexture.js\";\nimport { EquiRectangularCubeTexture } from \"../Materials/Textures/equiRectangularCubeTexture.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n/**\n * Defines the list of states available for a task inside a AssetsManager\n */\nexport var AssetTaskState;\n(function (AssetTaskState) {\n /**\n * Initialization\n */\n AssetTaskState[AssetTaskState[\"INIT\"] = 0] = \"INIT\";\n /**\n * Running\n */\n AssetTaskState[AssetTaskState[\"RUNNING\"] = 1] = \"RUNNING\";\n /**\n * Done\n */\n AssetTaskState[AssetTaskState[\"DONE\"] = 2] = \"DONE\";\n /**\n * Error\n */\n AssetTaskState[AssetTaskState[\"ERROR\"] = 3] = \"ERROR\";\n})(AssetTaskState || (AssetTaskState = {}));\n/**\n * Define an abstract asset task used with a AssetsManager class to load assets into a scene\n */\nexport class AbstractAssetTask {\n /**\n * Creates a new AssetsManager\n * @param name defines the name of the task\n */\n constructor(\n /**\n * Task name\n */ name) {\n this.name = name;\n this._isCompleted = false;\n this._taskState = AssetTaskState.INIT;\n }\n /**\n * Get if the task is completed\n */\n get isCompleted() {\n return this._isCompleted;\n }\n /**\n * Gets the current state of the task\n */\n get taskState() {\n return this._taskState;\n }\n /**\n * Gets the current error object (if task is in error)\n */\n get errorObject() {\n return this._errorObject;\n }\n /**\n * Internal only\n * @internal\n */\n _setErrorObject(message, exception) {\n if (this._errorObject) {\n return;\n }\n this._errorObject = {\n message: message,\n exception: exception,\n };\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n run(scene, onSuccess, onError) {\n this._taskState = AssetTaskState.RUNNING;\n this.runTask(scene, () => {\n this._onDoneCallback(onSuccess, onError);\n }, (msg, exception) => {\n this._onErrorCallback(onError, msg, exception);\n });\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n runTask(scene, onSuccess, onError) {\n throw new Error(\"runTask is not implemented\");\n }\n /**\n * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.\n * This can be used with failed tasks that have the reason for failure fixed.\n */\n reset() {\n this._taskState = AssetTaskState.INIT;\n }\n _onErrorCallback(onError, message, exception) {\n this._taskState = AssetTaskState.ERROR;\n this._errorObject = {\n message: message,\n exception: exception,\n };\n if (this.onError) {\n this.onError(this, message, exception);\n }\n onError();\n }\n _onDoneCallback(onSuccess, onError) {\n try {\n this._taskState = AssetTaskState.DONE;\n this._isCompleted = true;\n if (this.onSuccess) {\n this.onSuccess(this);\n }\n onSuccess();\n }\n catch (e) {\n this._onErrorCallback(onError, \"Task is done, error executing success callback(s)\", e);\n }\n }\n}\n/**\n * Class used to share progress information about assets loading\n */\nexport class AssetsProgressEvent {\n /**\n * Creates a AssetsProgressEvent\n * @param remainingCount defines the number of remaining tasks to process\n * @param totalCount defines the total number of tasks\n * @param task defines the task that was just processed\n */\n constructor(remainingCount, totalCount, task) {\n this.remainingCount = remainingCount;\n this.totalCount = totalCount;\n this.task = task;\n }\n}\n/**\n * Define a task used by AssetsManager to load assets into a container\n */\nexport class ContainerAssetTask extends AbstractAssetTask {\n /**\n * Creates a new ContainerAssetTask\n * @param name defines the name of the task\n * @param meshesNames defines the list of mesh's names you want to load\n * @param rootUrl defines the root url to use as a base to load your meshes and associated resources\n * @param sceneFilename defines the filename or File of the scene to load from\n */\n constructor(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the list of mesh's names you want to load\n */\n meshesNames, \n /**\n * Defines the root url to use as a base to load your meshes and associated resources\n */\n rootUrl, \n /**\n * Defines the filename or File of the scene to load from\n */\n sceneFilename, \n /**\n * Defines the extension to use to load the scene (if not defined, \".babylon\" will be used)\n */\n extension) {\n super(name);\n this.name = name;\n this.meshesNames = meshesNames;\n this.rootUrl = rootUrl;\n this.sceneFilename = sceneFilename;\n this.extension = extension;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n runTask(scene, onSuccess, onError) {\n SceneLoader.LoadAssetContainer(this.rootUrl, this.sceneFilename, scene, (container) => {\n this.loadedContainer = container;\n this.loadedMeshes = container.meshes;\n this.loadedTransformNodes = container.transformNodes;\n this.loadedParticleSystems = container.particleSystems;\n this.loadedSkeletons = container.skeletons;\n this.loadedAnimationGroups = container.animationGroups;\n onSuccess();\n }, null, (scene, message, exception) => {\n onError(message, exception);\n }, this.extension);\n }\n}\n/**\n * Define a task used by AssetsManager to load meshes\n */\nexport class MeshAssetTask extends AbstractAssetTask {\n /**\n * Creates a new MeshAssetTask\n * @param name defines the name of the task\n * @param meshesNames defines the list of mesh's names you want to load\n * @param rootUrl defines the root url to use as a base to load your meshes and associated resources\n * @param sceneFilename defines the filename or File of the scene to load from\n */\n constructor(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the list of mesh's names you want to load\n */\n meshesNames, \n /**\n * Defines the root url to use as a base to load your meshes and associated resources\n */\n rootUrl, \n /**\n * Defines the filename or File of the scene to load from\n */\n sceneFilename, \n /**\n * Defines the extension to use to load the scene (if not defined, \".babylon\" will be used)\n */\n extension) {\n super(name);\n this.name = name;\n this.meshesNames = meshesNames;\n this.rootUrl = rootUrl;\n this.sceneFilename = sceneFilename;\n this.extension = extension;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n runTask(scene, onSuccess, onError) {\n SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, (meshes, particleSystems, skeletons, animationGroups, transformNodes) => {\n this.loadedMeshes = meshes;\n this.loadedTransformNodes = transformNodes;\n this.loadedParticleSystems = particleSystems;\n this.loadedSkeletons = skeletons;\n this.loadedAnimationGroups = animationGroups;\n onSuccess();\n }, null, (scene, message, exception) => {\n onError(message, exception);\n }, this.extension);\n }\n}\n/**\n * Define a task used by AssetsManager to load animations\n */\nexport class AnimationAssetTask extends AbstractAssetTask {\n /**\n * Creates a new AnimationAssetTask\n * @param name defines the name of the task\n * @param rootUrl defines the root url to use as a base to load your meshes and associated resources\n * @param filename defines the filename or File of the scene to load from\n * @param targetConverter defines a function used to convert animation targets from loaded scene to current scene (default: search node by name)\n */\n constructor(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the root url to use as a base to load your meshes and associated resources\n */\n rootUrl, \n /**\n * Defines the filename to load from\n */\n filename, \n /**\n * Defines a function used to convert animation targets from loaded scene to current scene (default: search node by name)\n */\n targetConverter, \n /**\n * Defines the extension to use to load the scene (if not defined, \".babylon\" will be used)\n */\n extension) {\n super(name);\n this.name = name;\n this.rootUrl = rootUrl;\n this.filename = filename;\n this.targetConverter = targetConverter;\n this.extension = extension;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n runTask(scene, onSuccess, onError) {\n const startingIndexForNewAnimatables = scene.animatables.length;\n const startingIndexForNewAnimationGroups = scene.animationGroups.length;\n this.loadedAnimatables = [];\n this.loadedAnimationGroups = [];\n SceneLoader.ImportAnimations(this.rootUrl, this.filename, scene, false, SceneLoaderAnimationGroupLoadingMode.NoSync, this.targetConverter, () => {\n this.loadedAnimatables = scene.animatables.slice(startingIndexForNewAnimatables);\n this.loadedAnimationGroups = scene.animationGroups.slice(startingIndexForNewAnimationGroups);\n onSuccess();\n }, null, (scene, message, exception) => {\n onError(message, exception);\n }, this.extension);\n }\n}\n/**\n * Define a task used by AssetsManager to load text content\n */\nexport class TextFileAssetTask extends AbstractAssetTask {\n /**\n * Creates a new TextFileAssetTask object\n * @param name defines the name of the task\n * @param url defines the location of the file to load\n */\n constructor(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the location of the file to load\n */\n url) {\n super(name);\n this.name = name;\n this.url = url;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n runTask(scene, onSuccess, onError) {\n scene._loadFile(this.url, (data) => {\n this.text = data;\n onSuccess();\n }, undefined, false, false, (request, exception) => {\n if (request) {\n onError(request.status + \" \" + request.statusText, exception);\n }\n });\n }\n}\n/**\n * Define a task used by AssetsManager to load binary data\n */\nexport class BinaryFileAssetTask extends AbstractAssetTask {\n /**\n * Creates a new BinaryFileAssetTask object\n * @param name defines the name of the new task\n * @param url defines the location of the file to load\n */\n constructor(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the location of the file to load\n */\n url) {\n super(name);\n this.name = name;\n this.url = url;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n runTask(scene, onSuccess, onError) {\n scene._loadFile(this.url, (data) => {\n this.data = data;\n onSuccess();\n }, undefined, true, true, (request, exception) => {\n if (request) {\n onError(request.status + \" \" + request.statusText, exception);\n }\n });\n }\n}\n/**\n * Define a task used by AssetsManager to load images\n */\nexport class ImageAssetTask extends AbstractAssetTask {\n /**\n * Creates a new ImageAssetTask\n * @param name defines the name of the task\n * @param url defines the location of the image to load\n */\n constructor(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the location of the image to load\n */\n url) {\n super(name);\n this.name = name;\n this.url = url;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n runTask(scene, onSuccess, onError) {\n const img = new Image();\n Tools.SetCorsBehavior(this.url, img);\n img.onload = () => {\n this.image = img;\n onSuccess();\n };\n img.onerror = (err) => {\n onError(\"Error loading image\", err);\n };\n img.src = this.url;\n }\n}\n/**\n * Define a task used by AssetsManager to load 2D textures\n */\nexport class TextureAssetTask extends AbstractAssetTask {\n /**\n * Creates a new TextureAssetTask object\n * @param name defines the name of the task\n * @param url defines the location of the file to load\n * @param noMipmap defines if mipmap should not be generated (default is false)\n * @param invertY defines if texture must be inverted on Y axis (default is true)\n * @param samplingMode defines the sampling mode to use (default is Texture.TRILINEAR_SAMPLINGMODE)\n */\n constructor(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the location of the file to load\n */\n url, \n /**\n * Defines if mipmap should not be generated (default is false)\n */\n noMipmap, \n /**\n * Defines if texture must be inverted on Y axis (default is true)\n */\n invertY = true, \n /**\n * Defines the sampling mode to use (default is Texture.TRILINEAR_SAMPLINGMODE)\n */\n samplingMode = Texture.TRILINEAR_SAMPLINGMODE) {\n super(name);\n this.name = name;\n this.url = url;\n this.noMipmap = noMipmap;\n this.invertY = invertY;\n this.samplingMode = samplingMode;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n runTask(scene, onSuccess, onError) {\n const onload = () => {\n onSuccess();\n };\n const onerror = (message, exception) => {\n onError(message, exception);\n };\n this.texture = new Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);\n }\n}\n/**\n * Define a task used by AssetsManager to load cube textures\n */\nexport class CubeTextureAssetTask extends AbstractAssetTask {\n /**\n * Creates a new CubeTextureAssetTask\n * @param name defines the name of the task\n * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)\n * @param extensions defines the extensions to use to load files ([\"_px\", \"_py\", \"_pz\", \"_nx\", \"_ny\", \"_nz\"] by default)\n * @param noMipmap defines if mipmaps should not be generated (default is false)\n * @param files defines the explicit list of files (undefined by default)\n * @param prefiltered\n */\n constructor(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)\n */\n url, \n /**\n * Defines the extensions to use to load files ([\"_px\", \"_py\", \"_pz\", \"_nx\", \"_ny\", \"_nz\"] by default)\n */\n extensions, \n /**\n * Defines if mipmaps should not be generated (default is false)\n */\n noMipmap, \n /**\n * Defines the explicit list of files (undefined by default)\n */\n files, \n /**\n * Defines the prefiltered texture option (default is false)\n */\n prefiltered) {\n super(name);\n this.name = name;\n this.url = url;\n this.extensions = extensions;\n this.noMipmap = noMipmap;\n this.files = files;\n this.prefiltered = prefiltered;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n runTask(scene, onSuccess, onError) {\n const onload = () => {\n onSuccess();\n };\n const onerror = (message, exception) => {\n onError(message, exception);\n };\n this.texture = new CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror, undefined, this.prefiltered);\n }\n}\n/**\n * Define a task used by AssetsManager to load HDR cube textures\n */\nexport class HDRCubeTextureAssetTask extends AbstractAssetTask {\n /**\n * Creates a new HDRCubeTextureAssetTask object\n * @param name defines the name of the task\n * @param url defines the location of the file to load\n * @param size defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.\n * @param noMipmap defines if mipmaps should not be generated (default is false)\n * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)\n * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)\n * @param reserved Internal use only\n */\n constructor(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the location of the file to load\n */\n url, \n /**\n * Defines the desired size (the more it increases the longer the generation will be)\n */\n size, \n /**\n * Defines if mipmaps should not be generated (default is false)\n */\n noMipmap = false, \n /**\n * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)\n */\n generateHarmonics = true, \n /**\n * Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)\n */\n gammaSpace = false, \n /**\n * Internal Use Only\n */\n reserved = false) {\n super(name);\n this.name = name;\n this.url = url;\n this.size = size;\n this.noMipmap = noMipmap;\n this.generateHarmonics = generateHarmonics;\n this.gammaSpace = gammaSpace;\n this.reserved = reserved;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n runTask(scene, onSuccess, onError) {\n const onload = () => {\n onSuccess();\n };\n const onerror = (message, exception) => {\n onError(message, exception);\n };\n this.texture = new HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);\n }\n}\n/**\n * Define a task used by AssetsManager to load Equirectangular cube textures\n */\nexport class EquiRectangularCubeTextureAssetTask extends AbstractAssetTask {\n /**\n * Creates a new EquiRectangularCubeTextureAssetTask object\n * @param name defines the name of the task\n * @param url defines the location of the file to load\n * @param size defines the desired size (the more it increases the longer the generation will be)\n * If the size is omitted this implies you are using a preprocessed cubemap.\n * @param noMipmap defines if mipmaps should not be generated (default is false)\n * @param gammaSpace specifies if the texture will be used in gamma or linear space\n * (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)\n * (default is true)\n */\n constructor(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the location of the file to load\n */\n url, \n /**\n * Defines the desired size (the more it increases the longer the generation will be)\n */\n size, \n /**\n * Defines if mipmaps should not be generated (default is false)\n */\n noMipmap = false, \n /**\n * Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space,\n * but the standard material would require them in Gamma space) (default is true)\n */\n gammaSpace = true) {\n super(name);\n this.name = name;\n this.url = url;\n this.size = size;\n this.noMipmap = noMipmap;\n this.gammaSpace = gammaSpace;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n runTask(scene, onSuccess, onError) {\n const onload = () => {\n onSuccess();\n };\n const onerror = (message, exception) => {\n onError(message, exception);\n };\n this.texture = new EquiRectangularCubeTexture(this.url, scene, this.size, this.noMipmap, this.gammaSpace, onload, onerror);\n }\n}\n/**\n * This class can be used to easily import assets into a scene\n * @see https://doc.babylonjs.com/features/featuresDeepDive/importers/assetManager\n */\nexport class AssetsManager {\n /**\n * Creates a new AssetsManager\n * @param scene defines the scene to work on\n */\n constructor(scene) {\n this._isLoading = false;\n this._tasks = new Array();\n this._waitingTasksCount = 0;\n this._totalTasksCount = 0;\n /**\n * Observable called when all tasks are processed\n */\n this.onTaskSuccessObservable = new Observable();\n /**\n * Observable called when a task had an error\n */\n this.onTaskErrorObservable = new Observable();\n /**\n * Observable called when all tasks were executed\n */\n this.onTasksDoneObservable = new Observable();\n /**\n * Observable called when a task is done (whatever the result is)\n */\n this.onProgressObservable = new Observable();\n /**\n * Gets or sets a boolean defining if the AssetsManager should use the default loading screen\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen\n */\n this.useDefaultLoadingScreen = true;\n /**\n * Gets or sets a boolean defining if the AssetsManager should automatically hide the loading screen\n * when all assets have been downloaded.\n * If set to false, you need to manually call in hideLoadingUI() once your scene is ready.\n */\n this.autoHideLoadingUI = true;\n this._scene = scene || EngineStore.LastCreatedScene;\n }\n /**\n * Add a ContainerAssetTask to the list of active tasks\n * @param taskName defines the name of the new task\n * @param meshesNames defines the name of meshes to load\n * @param rootUrl defines the root url to use to locate files\n * @param sceneFilename defines the filename of the scene file or the File itself\n * @param extension defines the extension to use to load the file\n * @returns a new ContainerAssetTask object\n */\n addContainerTask(taskName, meshesNames, rootUrl, sceneFilename, extension) {\n const task = new ContainerAssetTask(taskName, meshesNames, rootUrl, sceneFilename, extension);\n this._tasks.push(task);\n return task;\n }\n /**\n * Add a MeshAssetTask to the list of active tasks\n * @param taskName defines the name of the new task\n * @param meshesNames defines the name of meshes to load\n * @param rootUrl defines the root url to use to locate files\n * @param sceneFilename defines the filename of the scene file or the File itself\n * @param extension defines the extension to use to load the file\n * @returns a new MeshAssetTask object\n */\n addMeshTask(taskName, meshesNames, rootUrl, sceneFilename, extension) {\n const task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename, extension);\n this._tasks.push(task);\n return task;\n }\n /**\n * Add a TextFileAssetTask to the list of active tasks\n * @param taskName defines the name of the new task\n * @param url defines the url of the file to load\n * @returns a new TextFileAssetTask object\n */\n addTextFileTask(taskName, url) {\n const task = new TextFileAssetTask(taskName, url);\n this._tasks.push(task);\n return task;\n }\n /**\n * Add a BinaryFileAssetTask to the list of active tasks\n * @param taskName defines the name of the new task\n * @param url defines the url of the file to load\n * @returns a new BinaryFileAssetTask object\n */\n addBinaryFileTask(taskName, url) {\n const task = new BinaryFileAssetTask(taskName, url);\n this._tasks.push(task);\n return task;\n }\n /**\n * Add a ImageAssetTask to the list of active tasks\n * @param taskName defines the name of the new task\n * @param url defines the url of the file to load\n * @returns a new ImageAssetTask object\n */\n addImageTask(taskName, url) {\n const task = new ImageAssetTask(taskName, url);\n this._tasks.push(task);\n return task;\n }\n /**\n * Add a TextureAssetTask to the list of active tasks\n * @param taskName defines the name of the new task\n * @param url defines the url of the file to load\n * @param noMipmap defines if the texture must not receive mipmaps (false by default)\n * @param invertY defines if you want to invert Y axis of the loaded texture (true by default)\n * @param samplingMode defines the sampling mode to use (Texture.TRILINEAR_SAMPLINGMODE by default)\n * @returns a new TextureAssetTask object\n */\n addTextureTask(taskName, url, noMipmap, invertY, samplingMode = Texture.TRILINEAR_SAMPLINGMODE) {\n const task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);\n this._tasks.push(task);\n return task;\n }\n /**\n * Add a CubeTextureAssetTask to the list of active tasks\n * @param taskName defines the name of the new task\n * @param url defines the url of the file to load\n * @param extensions defines the extension to use to load the cube map (can be null)\n * @param noMipmap defines if the texture must not receive mipmaps (false by default)\n * @param files defines the list of files to load (can be null)\n * @param prefiltered defines the prefiltered texture option (default is false)\n * @returns a new CubeTextureAssetTask object\n */\n addCubeTextureTask(taskName, url, extensions, noMipmap, files, prefiltered) {\n const task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files, prefiltered);\n this._tasks.push(task);\n return task;\n }\n /**\n *\n * Add a HDRCubeTextureAssetTask to the list of active tasks\n * @param taskName defines the name of the new task\n * @param url defines the url of the file to load\n * @param size defines the size you want for the cubemap (can be null)\n * @param noMipmap defines if the texture must not receive mipmaps (false by default)\n * @param generateHarmonics defines if you want to automatically generate (true by default)\n * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)\n * @param reserved Internal use only\n * @returns a new HDRCubeTextureAssetTask object\n */\n addHDRCubeTextureTask(taskName, url, size, noMipmap = false, generateHarmonics = true, gammaSpace = false, reserved = false) {\n const task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);\n this._tasks.push(task);\n return task;\n }\n /**\n *\n * Add a EquiRectangularCubeTextureAssetTask to the list of active tasks\n * @param taskName defines the name of the new task\n * @param url defines the url of the file to load\n * @param size defines the size you want for the cubemap (can be null)\n * @param noMipmap defines if the texture must not receive mipmaps (false by default)\n * @param gammaSpace Specifies if the texture will be used in gamma or linear space\n * (the PBR material requires those textures in linear space, but the standard material would require them in Gamma space)\n * @returns a new EquiRectangularCubeTextureAssetTask object\n */\n addEquiRectangularCubeTextureAssetTask(taskName, url, size, noMipmap = false, gammaSpace = true) {\n const task = new EquiRectangularCubeTextureAssetTask(taskName, url, size, noMipmap, gammaSpace);\n this._tasks.push(task);\n return task;\n }\n /**\n * Remove a task from the assets manager.\n * @param task the task to remove\n */\n removeTask(task) {\n const index = this._tasks.indexOf(task);\n if (index > -1) {\n this._tasks.splice(index, 1);\n }\n }\n _decreaseWaitingTasksCount(task) {\n this._waitingTasksCount--;\n try {\n if (this.onProgress) {\n this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);\n }\n this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));\n }\n catch (e) {\n Logger.Error(\"Error running progress callbacks.\");\n console.log(e);\n }\n if (this._waitingTasksCount === 0) {\n try {\n const currentTasks = this._tasks.slice();\n if (this.onFinish) {\n // Calling onFinish with immutable array of tasks\n this.onFinish(currentTasks);\n }\n // Let's remove successful tasks\n for (const task of currentTasks) {\n if (task.taskState === AssetTaskState.DONE) {\n const index = this._tasks.indexOf(task);\n if (index > -1) {\n this._tasks.splice(index, 1);\n }\n }\n }\n this.onTasksDoneObservable.notifyObservers(this._tasks);\n }\n catch (e) {\n Logger.Error(\"Error running tasks-done callbacks.\");\n console.log(e);\n }\n this._isLoading = false;\n if (this.autoHideLoadingUI) {\n this._scene.getEngine().hideLoadingUI();\n }\n }\n }\n _runTask(task) {\n const done = () => {\n try {\n if (this.onTaskSuccess) {\n this.onTaskSuccess(task);\n }\n this.onTaskSuccessObservable.notifyObservers(task);\n this._decreaseWaitingTasksCount(task);\n }\n catch (e) {\n error(\"Error executing task success callbacks\", e);\n }\n };\n const error = (message, exception) => {\n task._setErrorObject(message, exception);\n if (this.onTaskError) {\n this.onTaskError(task);\n }\n else if (!task.onError) {\n Logger.Error(this._formatTaskErrorMessage(task));\n }\n this.onTaskErrorObservable.notifyObservers(task);\n this._decreaseWaitingTasksCount(task);\n };\n task.run(this._scene, done, error);\n }\n _formatTaskErrorMessage(task) {\n let errorMessage = \"Unable to complete task \" + task.name;\n if (task.errorObject.message) {\n errorMessage += `: ${task.errorObject.message}`;\n }\n if (task.errorObject.exception) {\n errorMessage += `: ${task.errorObject.exception}`;\n }\n return errorMessage;\n }\n /**\n * Reset the AssetsManager and remove all tasks\n * @returns the current instance of the AssetsManager\n */\n reset() {\n this._isLoading = false;\n this._tasks = new Array();\n return this;\n }\n /**\n * Start the loading process\n * @returns the current instance of the AssetsManager\n */\n load() {\n if (this._isLoading) {\n return this;\n }\n this._isLoading = true;\n this._waitingTasksCount = this._tasks.length;\n this._totalTasksCount = this._tasks.length;\n if (this._waitingTasksCount === 0) {\n this._isLoading = false;\n if (this.onFinish) {\n this.onFinish(this._tasks);\n }\n this.onTasksDoneObservable.notifyObservers(this._tasks);\n return this;\n }\n if (this.useDefaultLoadingScreen) {\n this._scene.getEngine().displayLoadingUI();\n }\n for (let index = 0; index < this._tasks.length; index++) {\n const task = this._tasks[index];\n if (task.taskState === AssetTaskState.INIT) {\n this._runTask(task);\n }\n }\n return this;\n }\n /**\n * Start the loading process as an async operation\n * @returns a promise returning the list of failed tasks\n */\n loadAsync() {\n return new Promise((resolve, reject) => {\n if (this._isLoading) {\n resolve();\n return;\n }\n this.onTasksDoneObservable.addOnce((remainingTasks) => {\n if (remainingTasks && remainingTasks.length) {\n reject(remainingTasks);\n }\n else {\n resolve();\n }\n });\n this.load();\n });\n }\n}\n//# sourceMappingURL=assetsManager.js.map","/**\n * Wrapper class for promise with external resolve and reject.\n */\nexport class Deferred {\n /**\n * The resolve method of the promise associated with this deferred object.\n */\n get resolve() {\n return this._resolve;\n }\n /**\n * The reject method of the promise associated with this deferred object.\n */\n get reject() {\n return this._reject;\n }\n /**\n * Constructor for this deferred object.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n}\n//# sourceMappingURL=deferred.js.map","import { Vector3 } from \"../Maths/math.vector.js\";\n/**\n * Class used to explode meshes (ie. to have a center and move them away from that center to better see the overall organization)\n */\nexport class MeshExploder {\n /**\n * Explodes meshes from a center mesh.\n * @param meshes The meshes to explode.\n * @param centerMesh The mesh to be center of explosion.\n */\n constructor(meshes, centerMesh) {\n this._meshesOrigins = [];\n this._toCenterVectors = [];\n this._scaledDirection = new Vector3(1, 1, 1);\n this._newPosition = Vector3.Zero();\n this._centerPosition = Vector3.Zero();\n this._meshes = meshes.slice();\n if (centerMesh) {\n this._centerMesh = centerMesh;\n }\n else {\n this._setCenterMesh();\n }\n this._centerMesh.computeWorldMatrix(true);\n const centerMeshIndex = this._meshes.indexOf(this._centerMesh);\n if (centerMeshIndex >= 0) {\n this._meshes.splice(centerMeshIndex, 1);\n }\n this._centerPosition = this._centerMesh.getAbsolutePosition().clone();\n for (let index = 0; index < this._meshes.length; index++) {\n if (this._meshes[index]) {\n const mesh = this._meshes[index];\n this._meshesOrigins[index] = mesh.getAbsolutePosition().clone();\n this._toCenterVectors[index] = Vector3.Zero();\n if (mesh.hasBoundingInfo && this._centerMesh.hasBoundingInfo) {\n mesh.computeWorldMatrix(true);\n mesh.getBoundingInfo().boundingBox.centerWorld.subtractToRef(this._centerMesh.getBoundingInfo().boundingBox.centerWorld, this._toCenterVectors[index]);\n }\n }\n }\n }\n _setCenterMesh() {\n let averageCenter = Vector3.Zero();\n const totalCenters = Vector3.Zero();\n let shortestToCenter = Number.MAX_VALUE;\n for (let index = 0; index < this._meshes.length; index++) {\n if (this._meshes[index]) {\n const mesh = this._meshes[index];\n const boundingInfo = mesh.getBoundingInfo();\n if (boundingInfo) {\n totalCenters.addInPlace(boundingInfo.boundingBox.centerWorld);\n }\n }\n }\n averageCenter = totalCenters.scale(1 / this._meshes.length);\n for (let index = 0; index < this._meshes.length; index++) {\n if (this._meshes[index]) {\n const mesh = this._meshes[index];\n const boundingInfo = mesh.getBoundingInfo();\n if (boundingInfo) {\n const distanceToCenter = boundingInfo.boundingBox.centerWorld.subtract(averageCenter).lengthSquared();\n if (distanceToCenter < shortestToCenter) {\n this._centerMesh = mesh;\n shortestToCenter = distanceToCenter;\n }\n }\n }\n }\n }\n /**\n * Get class name\n * @returns \"MeshExploder\"\n */\n getClassName() {\n return \"MeshExploder\";\n }\n /**\n * \"Exploded meshes\"\n * @returns Array of meshes with the centerMesh at index 0.\n */\n getMeshes() {\n const meshArray = this._meshes.slice();\n meshArray.unshift(this._centerMesh);\n return meshArray;\n }\n /**\n * Explodes meshes giving a specific direction\n * @param direction Number to multiply distance of each mesh's origin from center. Use a negative number to implode, or zero to reset.\n */\n explode(direction = 1.0) {\n for (let index = 0; index < this._meshes.length; index++) {\n if (this._meshes[index] && this._meshesOrigins[index] && this._toCenterVectors[index]) {\n this._toCenterVectors[index].scaleToRef(direction, this._scaledDirection);\n this._meshesOrigins[index].addToRef(this._scaledDirection, this._newPosition);\n this._meshes[index].setAbsolutePosition(this._newPosition);\n }\n }\n this._centerMesh.setAbsolutePosition(this._centerPosition);\n }\n}\n//# sourceMappingURL=meshExploder.js.map","import { SceneLoader } from \"../Loading/sceneLoader.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { FilesInputStore } from \"./filesInputStore.js\";\n/**\n * Class used to help managing file picking and drag-n-drop\n */\nexport class FilesInput {\n /**\n * List of files ready to be loaded\n */\n static get FilesToLoad() {\n return FilesInputStore.FilesToLoad;\n }\n /**\n * Creates a new FilesInput\n * @param engine defines the rendering engine\n * @param scene defines the hosting scene\n * @param sceneLoadedCallback callback called when scene (files provided) is loaded\n * @param progressCallback callback called to track progress\n * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop\n * @param textureLoadingCallback callback called when a texture is loading\n * @param startingProcessingFilesCallback callback called when the system is about to process all files\n * @param onReloadCallback callback called when a reload is requested\n * @param errorCallback callback call if an error occurs\n * @param useAppend defines if the file loaded must be appended (true) or have the scene replaced (false, default behavior)\n */\n constructor(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback, useAppend = false) {\n this.useAppend = useAppend;\n /**\n * Callback called when a file is processed\n */\n this.onProcessFileCallback = () => {\n return true;\n };\n this.displayLoadingUI = true;\n /**\n * Function used when loading the scene file\n * @param sceneFile\n * @param onProgress\n */\n this.loadAsync = (sceneFile, onProgress) => this.useAppend ? SceneLoader.AppendAsync(\"file:\", sceneFile, this._currentScene, onProgress) : SceneLoader.LoadAsync(\"file:\", sceneFile, this._engine, onProgress);\n this._engine = engine;\n this._currentScene = scene;\n this._sceneLoadedCallback = sceneLoadedCallback;\n this._progressCallback = progressCallback;\n this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;\n this._textureLoadingCallback = textureLoadingCallback;\n this._startingProcessingFilesCallback = startingProcessingFilesCallback;\n this._onReloadCallback = onReloadCallback;\n this._errorCallback = errorCallback;\n }\n /**\n * Calls this function to listen to drag'n'drop events on a specific DOM element\n * @param elementToMonitor defines the DOM element to track\n */\n monitorElementForDragNDrop(elementToMonitor) {\n if (elementToMonitor) {\n this._elementToMonitor = elementToMonitor;\n this._dragEnterHandler = (e) => {\n this._drag(e);\n };\n this._dragOverHandler = (e) => {\n this._drag(e);\n };\n this._dropHandler = (e) => {\n this._drop(e);\n };\n this._elementToMonitor.addEventListener(\"dragenter\", this._dragEnterHandler, false);\n this._elementToMonitor.addEventListener(\"dragover\", this._dragOverHandler, false);\n this._elementToMonitor.addEventListener(\"drop\", this._dropHandler, false);\n }\n }\n /** Gets the current list of files to load */\n get filesToLoad() {\n return this._filesToLoad;\n }\n /**\n * Release all associated resources\n */\n dispose() {\n if (!this._elementToMonitor) {\n return;\n }\n this._elementToMonitor.removeEventListener(\"dragenter\", this._dragEnterHandler);\n this._elementToMonitor.removeEventListener(\"dragover\", this._dragOverHandler);\n this._elementToMonitor.removeEventListener(\"drop\", this._dropHandler);\n }\n _renderFunction() {\n if (this._additionalRenderLoopLogicCallback) {\n this._additionalRenderLoopLogicCallback();\n }\n if (this._currentScene) {\n if (this._textureLoadingCallback) {\n const remaining = this._currentScene.getWaitingItemsCount();\n if (remaining > 0) {\n this._textureLoadingCallback(remaining);\n }\n }\n this._currentScene.render();\n }\n }\n _drag(e) {\n e.stopPropagation();\n e.preventDefault();\n }\n _drop(eventDrop) {\n eventDrop.stopPropagation();\n eventDrop.preventDefault();\n this.loadFiles(eventDrop);\n }\n _traverseFolder(folder, files, remaining, callback) {\n const reader = folder.createReader();\n const relativePath = folder.fullPath.replace(/^\\//, \"\").replace(/(.+?)\\/?$/, \"$1/\");\n reader.readEntries((entries) => {\n remaining.count += entries.length;\n for (const entry of entries) {\n if (entry.isFile) {\n entry.file((file) => {\n file.correctName = relativePath + file.name;\n files.push(file);\n if (--remaining.count === 0) {\n callback();\n }\n });\n }\n else if (entry.isDirectory) {\n this._traverseFolder(entry, files, remaining, callback);\n }\n }\n if (--remaining.count === 0) {\n callback();\n }\n });\n }\n _processFiles(files) {\n for (let i = 0; i < files.length; i++) {\n const name = files[i].correctName.toLowerCase();\n const extension = name.split(\".\").pop();\n if (!this.onProcessFileCallback(files[i], name, extension, (sceneFile) => (this._sceneFileToLoad = sceneFile))) {\n continue;\n }\n if (SceneLoader.IsPluginForExtensionAvailable(\".\" + extension)) {\n this._sceneFileToLoad = files[i];\n }\n FilesInput.FilesToLoad[name] = files[i];\n }\n }\n /**\n * Load files from a drop event\n * @param event defines the drop event to use as source\n */\n loadFiles(event) {\n // Handling data transfer via drag'n'drop\n if (event && event.dataTransfer && event.dataTransfer.files) {\n this._filesToLoad = event.dataTransfer.files;\n }\n // Handling files from input files\n if (event && event.target && event.target.files) {\n this._filesToLoad = event.target.files;\n }\n if (!this._filesToLoad || this._filesToLoad.length === 0) {\n return;\n }\n if (this._startingProcessingFilesCallback) {\n this._startingProcessingFilesCallback(this._filesToLoad);\n }\n if (this._filesToLoad && this._filesToLoad.length > 0) {\n const files = new Array();\n const folders = [];\n const items = event.dataTransfer ? event.dataTransfer.items : null;\n for (let i = 0; i < this._filesToLoad.length; i++) {\n const fileToLoad = this._filesToLoad[i];\n const name = fileToLoad.name.toLowerCase();\n let entry;\n fileToLoad.correctName = name;\n if (items) {\n const item = items[i];\n if (item.getAsEntry) {\n entry = item.getAsEntry();\n }\n else if (item.webkitGetAsEntry) {\n entry = item.webkitGetAsEntry();\n }\n }\n if (!entry) {\n files.push(fileToLoad);\n }\n else {\n if (entry.isDirectory) {\n folders.push(entry);\n }\n else {\n files.push(fileToLoad);\n }\n }\n }\n if (folders.length === 0) {\n this._processFiles(files);\n this._processReload();\n }\n else {\n const remaining = { count: folders.length };\n for (const folder of folders) {\n this._traverseFolder(folder, files, remaining, () => {\n this._processFiles(files);\n if (remaining.count === 0) {\n this._processReload();\n }\n });\n }\n }\n }\n }\n _processReload() {\n if (this._onReloadCallback) {\n this._onReloadCallback(this._sceneFileToLoad);\n }\n else {\n this.reload();\n }\n }\n /**\n * Reload the current scene from the loaded files\n */\n reload() {\n // If a scene file has been provided\n if (this._sceneFileToLoad) {\n if (!this.useAppend) {\n if (this._currentScene) {\n if (Logger.errorsCount > 0) {\n Logger.ClearLogCache();\n }\n this._engine.stopRenderLoop();\n }\n }\n SceneLoader.ShowLoadingScreen = false;\n if (this.displayLoadingUI) {\n this._engine.displayLoadingUI();\n }\n this.loadAsync(this._sceneFileToLoad, this._progressCallback)\n .then((scene) => {\n // if appending do nothing\n if (!this.useAppend) {\n if (this._currentScene) {\n this._currentScene.dispose();\n }\n this._currentScene = scene;\n // Wait for textures and shaders to be ready\n this._currentScene.executeWhenReady(() => {\n if (this.displayLoadingUI) {\n this._engine.hideLoadingUI();\n }\n this._engine.runRenderLoop(() => {\n this._renderFunction();\n });\n });\n }\n else {\n if (this.displayLoadingUI) {\n this._engine.hideLoadingUI();\n }\n }\n if (this._sceneLoadedCallback && this._currentScene) {\n this._sceneLoadedCallback(this._sceneFileToLoad, this._currentScene);\n }\n })\n .catch((error) => {\n if (this.displayLoadingUI) {\n this._engine.hideLoadingUI();\n }\n if (this._errorCallback) {\n this._errorCallback(this._sceneFileToLoad, this._currentScene, error.message);\n }\n });\n }\n else {\n Logger.Error(\"Please provide a valid .babylon file.\");\n }\n }\n}\n//# sourceMappingURL=filesInput.js.map","export * from \"./cubemapToSphericalPolynomial.js\";\nexport * from \"./hdr.js\";\nexport * from \"./panoramaToCubemap.js\";\n//# sourceMappingURL=index.js.map","import { Observable } from \"./observable.js\";\n/**\n * Represent a list of observers registered to multiple Observables object.\n */\nexport class MultiObserver {\n /**\n * Release associated resources\n */\n dispose() {\n if (this._observers && this._observables) {\n for (let index = 0; index < this._observers.length; index++) {\n this._observables[index].remove(this._observers[index]);\n }\n }\n this._observers = null;\n this._observables = null;\n }\n /**\n * Raise a callback when one of the observable will notify\n * @param observables defines a list of observables to watch\n * @param callback defines the callback to call on notification\n * @param mask defines the mask used to filter notifications\n * @param scope defines the current scope used to restore the JS context\n * @returns the new MultiObserver\n */\n static Watch(observables, callback, mask = -1, scope = null) {\n const result = new MultiObserver();\n result._observers = new Array();\n result._observables = observables;\n for (const observable of observables) {\n const observer = observable.add(callback, mask, false, scope);\n if (observer) {\n result._observers.push(observer);\n }\n }\n return result;\n }\n}\nObservable.prototype.notifyObserversWithPromise = async function (eventData, mask = -1, target, currentTarget, userInfo) {\n // create an empty promise\n let p = Promise.resolve(eventData);\n // no observers? return this promise.\n if (!this.observers.length) {\n return p;\n }\n const state = this._eventState;\n state.mask = mask;\n state.target = target;\n state.currentTarget = currentTarget;\n state.skipNextObservers = false;\n state.userInfo = userInfo;\n // execute one callback after another (not using Promise.all, the order is important)\n this.observers.forEach((obs) => {\n if (state.skipNextObservers) {\n return;\n }\n if (obs._willBeUnregistered) {\n return;\n }\n if (obs.mask & mask) {\n if (obs.scope) {\n p = p.then((lastReturnedValue) => {\n state.lastReturnValue = lastReturnedValue;\n return obs.callback.apply(obs.scope, [eventData, state]);\n });\n }\n else {\n p = p.then((lastReturnedValue) => {\n state.lastReturnValue = lastReturnedValue;\n return obs.callback(eventData, state);\n });\n }\n if (obs.unregisterOnNextCall) {\n this._deferUnregister(obs);\n }\n }\n });\n // return the eventData\n await p;\n return eventData;\n};\n//# sourceMappingURL=observable.extensions.js.map","import { EngineStore } from \"../Engines/engineStore.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { Observable } from \"./observable.js\";\n/**\n * Defines the root class used to create scene optimization to use with SceneOptimizer\n * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer\n */\nexport class SceneOptimization {\n /**\n * Gets a string describing the action executed by the current optimization\n * @returns description string\n */\n getDescription() {\n return \"\";\n }\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n apply(scene, optimizer) {\n return true;\n }\n /**\n * Creates the SceneOptimization object\n * @param priority defines the priority of this optimization (0 by default which means first in the list)\n */\n constructor(\n /**\n * Defines the priority of this optimization (0 by default which means first in the list)\n */\n priority = 0) {\n this.priority = priority;\n }\n}\n/**\n * Defines an optimization used to reduce the size of render target textures\n * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer\n */\nexport class TextureOptimization extends SceneOptimization {\n /**\n * Gets a string describing the action executed by the current optimization\n * @returns description string\n */\n getDescription() {\n return \"Reducing render target texture size to \" + this.maximumSize;\n }\n /**\n * Creates the TextureOptimization object\n * @param priority defines the priority of this optimization (0 by default which means first in the list)\n * @param maximumSize defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter\n * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.\n */\n constructor(\n /**\n * Defines the priority of this optimization (0 by default which means first in the list)\n */\n priority = 0, \n /**\n * Defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter\n */\n maximumSize = 1024, \n /**\n * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.\n */\n step = 0.5) {\n super(priority);\n this.priority = priority;\n this.maximumSize = maximumSize;\n this.step = step;\n }\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n apply(scene, optimizer) {\n let allDone = true;\n for (let index = 0; index < scene.textures.length; index++) {\n const texture = scene.textures[index];\n if (!texture.canRescale || texture.getContext) {\n continue;\n }\n const currentSize = texture.getSize();\n const maxDimension = Math.max(currentSize.width, currentSize.height);\n if (maxDimension > this.maximumSize) {\n texture.scale(this.step);\n allDone = false;\n }\n }\n return allDone;\n }\n}\n/**\n * Defines an optimization used to increase or decrease the rendering resolution\n * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer\n */\nexport class HardwareScalingOptimization extends SceneOptimization {\n /**\n * Gets a string describing the action executed by the current optimization\n * @returns description string\n */\n getDescription() {\n return \"Setting hardware scaling level to \" + this._currentScale;\n }\n /**\n * Creates the HardwareScalingOptimization object\n * @param priority defines the priority of this optimization (0 by default which means first in the list)\n * @param maximumScale defines the maximum scale to use (2 by default)\n * @param step defines the step to use between two passes (0.5 by default)\n */\n constructor(\n /**\n * Defines the priority of this optimization (0 by default which means first in the list)\n */\n priority = 0, \n /**\n * Defines the maximum scale to use (2 by default)\n */\n maximumScale = 2, \n /**\n * Defines the step to use between two passes (0.5 by default)\n */\n step = 0.25) {\n super(priority);\n this.priority = priority;\n this.maximumScale = maximumScale;\n this.step = step;\n this._currentScale = -1;\n this._directionOffset = 1;\n }\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n apply(scene, optimizer) {\n if (this._currentScale === -1) {\n this._currentScale = scene.getEngine().getHardwareScalingLevel();\n if (this._currentScale > this.maximumScale) {\n this._directionOffset = -1;\n }\n }\n this._currentScale += this._directionOffset * this.step;\n scene.getEngine().setHardwareScalingLevel(this._currentScale);\n return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;\n }\n}\n/**\n * Defines an optimization used to remove shadows\n * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer\n */\nexport class ShadowsOptimization extends SceneOptimization {\n /**\n * Gets a string describing the action executed by the current optimization\n * @returns description string\n */\n getDescription() {\n return \"Turning shadows on/off\";\n }\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n apply(scene, optimizer) {\n scene.shadowsEnabled = optimizer.isInImprovementMode;\n return true;\n }\n}\n/**\n * Defines an optimization used to turn post-processes off\n * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer\n */\nexport class PostProcessesOptimization extends SceneOptimization {\n /**\n * Gets a string describing the action executed by the current optimization\n * @returns description string\n */\n getDescription() {\n return \"Turning post-processes on/off\";\n }\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n apply(scene, optimizer) {\n scene.postProcessesEnabled = optimizer.isInImprovementMode;\n return true;\n }\n}\n/**\n * Defines an optimization used to turn lens flares off\n * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer\n */\nexport class LensFlaresOptimization extends SceneOptimization {\n /**\n * Gets a string describing the action executed by the current optimization\n * @returns description string\n */\n getDescription() {\n return \"Turning lens flares on/off\";\n }\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n apply(scene, optimizer) {\n scene.lensFlaresEnabled = optimizer.isInImprovementMode;\n return true;\n }\n}\n/**\n * Defines an optimization based on user defined callback.\n * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer\n */\nexport class CustomOptimization extends SceneOptimization {\n /**\n * Gets a string describing the action executed by the current optimization\n * @returns description string\n */\n getDescription() {\n if (this.onGetDescription) {\n return this.onGetDescription();\n }\n return \"Running user defined callback\";\n }\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n apply(scene, optimizer) {\n if (this.onApply) {\n return this.onApply(scene, optimizer);\n }\n return true;\n }\n}\n/**\n * Defines an optimization used to turn particles off\n * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer\n */\nexport class ParticlesOptimization extends SceneOptimization {\n /**\n * Gets a string describing the action executed by the current optimization\n * @returns description string\n */\n getDescription() {\n return \"Turning particles on/off\";\n }\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n apply(scene, optimizer) {\n scene.particlesEnabled = optimizer.isInImprovementMode;\n return true;\n }\n}\n/**\n * Defines an optimization used to turn render targets off\n * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer\n */\nexport class RenderTargetsOptimization extends SceneOptimization {\n /**\n * Gets a string describing the action executed by the current optimization\n * @returns description string\n */\n getDescription() {\n return \"Turning render targets off\";\n }\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n apply(scene, optimizer) {\n scene.renderTargetsEnabled = optimizer.isInImprovementMode;\n return true;\n }\n}\n/**\n * Defines an optimization used to merge meshes with compatible materials\n * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer\n */\nexport class MergeMeshesOptimization extends SceneOptimization {\n constructor() {\n super(...arguments);\n this._canBeMerged = (abstractMesh) => {\n if (!(abstractMesh instanceof Mesh)) {\n return false;\n }\n const mesh = abstractMesh;\n if (mesh.isDisposed()) {\n return false;\n }\n if (!mesh.isVisible || !mesh.isEnabled()) {\n return false;\n }\n if (mesh.instances.length > 0) {\n return false;\n }\n if (mesh.skeleton || mesh.hasLODLevels) {\n return false;\n }\n if (mesh.getTotalVertices() === 0) {\n return false;\n }\n return true;\n };\n }\n /**\n * Gets or sets a boolean which defines if optimization octree has to be updated\n */\n static get UpdateSelectionTree() {\n return MergeMeshesOptimization._UpdateSelectionTree;\n }\n /**\n * Gets or sets a boolean which defines if optimization octree has to be updated\n */\n static set UpdateSelectionTree(value) {\n MergeMeshesOptimization._UpdateSelectionTree = value;\n }\n /**\n * Gets a string describing the action executed by the current optimization\n * @returns description string\n */\n getDescription() {\n return \"Merging similar meshes together\";\n }\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @param updateSelectionTree defines that the selection octree has to be updated (false by default)\n * @returns true if everything that can be done was applied\n */\n apply(scene, optimizer, updateSelectionTree) {\n const globalPool = scene.meshes.slice(0);\n let globalLength = globalPool.length;\n for (let index = 0; index < globalLength; index++) {\n const currentPool = new Array();\n const current = globalPool[index];\n // Checks\n if (!this._canBeMerged(current)) {\n continue;\n }\n currentPool.push(current);\n // Find compatible meshes\n for (let subIndex = index + 1; subIndex < globalLength; subIndex++) {\n const otherMesh = globalPool[subIndex];\n if (!this._canBeMerged(otherMesh)) {\n continue;\n }\n if (otherMesh.material !== current.material) {\n continue;\n }\n if (otherMesh.checkCollisions !== current.checkCollisions) {\n continue;\n }\n currentPool.push(otherMesh);\n globalLength--;\n globalPool.splice(subIndex, 1);\n subIndex--;\n }\n if (currentPool.length < 2) {\n continue;\n }\n // Merge meshes\n Mesh.MergeMeshes(currentPool, undefined, true);\n }\n // Call the octree system optimization if it is defined.\n const sceneAsAny = scene;\n if (sceneAsAny.createOrUpdateSelectionOctree) {\n if (updateSelectionTree != undefined) {\n if (updateSelectionTree) {\n sceneAsAny.createOrUpdateSelectionOctree();\n }\n }\n else if (MergeMeshesOptimization.UpdateSelectionTree) {\n sceneAsAny.createOrUpdateSelectionOctree();\n }\n }\n return true;\n }\n}\nMergeMeshesOptimization._UpdateSelectionTree = false;\n/**\n * Defines a list of options used by SceneOptimizer\n * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer\n */\nexport class SceneOptimizerOptions {\n /**\n * Creates a new list of options used by SceneOptimizer\n * @param targetFrameRate defines the target frame rate to reach (60 by default)\n * @param trackerDuration defines the interval between two checks (2000ms by default)\n */\n constructor(\n /**\n * Defines the target frame rate to reach (60 by default)\n */\n targetFrameRate = 60, \n /**\n * Defines the interval between two checks (2000ms by default)\n */\n trackerDuration = 2000) {\n this.targetFrameRate = targetFrameRate;\n this.trackerDuration = trackerDuration;\n /**\n * Gets the list of optimizations to apply\n */\n this.optimizations = new Array();\n }\n /**\n * Add a new optimization\n * @param optimization defines the SceneOptimization to add to the list of active optimizations\n * @returns the current SceneOptimizerOptions\n */\n addOptimization(optimization) {\n this.optimizations.push(optimization);\n return this;\n }\n /**\n * Add a new custom optimization\n * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)\n * @param onGetDescription defines the callback called to get the description attached with the optimization.\n * @param priority defines the priority of this optimization (0 by default which means first in the list)\n * @returns the current SceneOptimizerOptions\n */\n addCustomOptimization(onApply, onGetDescription, priority = 0) {\n const optimization = new CustomOptimization(priority);\n optimization.onApply = onApply;\n optimization.onGetDescription = onGetDescription;\n this.optimizations.push(optimization);\n return this;\n }\n /**\n * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene\n * @param targetFrameRate defines the target frame rate (60 by default)\n * @returns a SceneOptimizerOptions object\n */\n static LowDegradationAllowed(targetFrameRate) {\n const result = new SceneOptimizerOptions(targetFrameRate);\n let priority = 0;\n result.addOptimization(new MergeMeshesOptimization(priority));\n result.addOptimization(new ShadowsOptimization(priority));\n result.addOptimization(new LensFlaresOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new PostProcessesOptimization(priority));\n result.addOptimization(new ParticlesOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new TextureOptimization(priority, 1024));\n return result;\n }\n /**\n * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual\n * @param targetFrameRate defines the target frame rate (60 by default)\n * @returns a SceneOptimizerOptions object\n */\n static ModerateDegradationAllowed(targetFrameRate) {\n const result = new SceneOptimizerOptions(targetFrameRate);\n let priority = 0;\n result.addOptimization(new MergeMeshesOptimization(priority));\n result.addOptimization(new ShadowsOptimization(priority));\n result.addOptimization(new LensFlaresOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new PostProcessesOptimization(priority));\n result.addOptimization(new ParticlesOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new TextureOptimization(priority, 512));\n // Next priority\n priority++;\n result.addOptimization(new RenderTargetsOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new HardwareScalingOptimization(priority, 2));\n return result;\n }\n /**\n * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual\n * @param targetFrameRate defines the target frame rate (60 by default)\n * @returns a SceneOptimizerOptions object\n */\n static HighDegradationAllowed(targetFrameRate) {\n const result = new SceneOptimizerOptions(targetFrameRate);\n let priority = 0;\n result.addOptimization(new MergeMeshesOptimization(priority));\n result.addOptimization(new ShadowsOptimization(priority));\n result.addOptimization(new LensFlaresOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new PostProcessesOptimization(priority));\n result.addOptimization(new ParticlesOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new TextureOptimization(priority, 256));\n // Next priority\n priority++;\n result.addOptimization(new RenderTargetsOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new HardwareScalingOptimization(priority, 4));\n return result;\n }\n}\n/**\n * Class used to run optimizations in order to reach a target frame rate\n * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer\n */\nexport class SceneOptimizer {\n /**\n * Gets or sets a boolean indicating if the optimizer is in improvement mode\n */\n get isInImprovementMode() {\n return this._improvementMode;\n }\n set isInImprovementMode(value) {\n this._improvementMode = value;\n }\n /**\n * Gets the current priority level (0 at start)\n */\n get currentPriorityLevel() {\n return this._currentPriorityLevel;\n }\n /**\n * Gets the current frame rate checked by the SceneOptimizer\n */\n get currentFrameRate() {\n return this._currentFrameRate;\n }\n /**\n * Gets or sets the current target frame rate (60 by default)\n */\n get targetFrameRate() {\n return this._targetFrameRate;\n }\n /**\n * Gets or sets the current target frame rate (60 by default)\n */\n set targetFrameRate(value) {\n this._targetFrameRate = value;\n }\n /**\n * Gets or sets the current interval between two checks (every 2000ms by default)\n */\n get trackerDuration() {\n return this._trackerDuration;\n }\n /**\n * Gets or sets the current interval between two checks (every 2000ms by default)\n */\n set trackerDuration(value) {\n this._trackerDuration = value;\n }\n /**\n * Gets the list of active optimizations\n */\n get optimizations() {\n return this._options.optimizations;\n }\n /**\n * Creates a new SceneOptimizer\n * @param scene defines the scene to work on\n * @param options defines the options to use with the SceneOptimizer\n * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)\n * @param improvementMode defines if the scene optimizer must run the maximum optimization while staying over a target frame instead of trying to reach the target framerate (false by default)\n */\n constructor(scene, options, autoGeneratePriorities = true, improvementMode = false) {\n this._isRunning = false;\n this._currentPriorityLevel = 0;\n this._targetFrameRate = 60;\n this._trackerDuration = 2000;\n this._currentFrameRate = 0;\n this._improvementMode = false;\n /**\n * Defines an observable called when the optimizer reaches the target frame rate\n */\n this.onSuccessObservable = new Observable();\n /**\n * Defines an observable called when the optimizer enables an optimization\n */\n this.onNewOptimizationAppliedObservable = new Observable();\n /**\n * Defines an observable called when the optimizer is not able to reach the target frame rate\n */\n this.onFailureObservable = new Observable();\n if (!options) {\n this._options = new SceneOptimizerOptions();\n }\n else {\n this._options = options;\n }\n if (this._options.targetFrameRate) {\n this._targetFrameRate = this._options.targetFrameRate;\n }\n if (this._options.trackerDuration) {\n this._trackerDuration = this._options.trackerDuration;\n }\n if (autoGeneratePriorities) {\n let priority = 0;\n for (const optim of this._options.optimizations) {\n optim.priority = priority++;\n }\n }\n this._improvementMode = improvementMode;\n this._scene = scene || EngineStore.LastCreatedScene;\n this._sceneDisposeObserver = this._scene.onDisposeObservable.add(() => {\n this._sceneDisposeObserver = null;\n this.dispose();\n });\n }\n /**\n * Stops the current optimizer\n */\n stop() {\n this._isRunning = false;\n }\n /**\n * Reset the optimizer to initial step (current priority level = 0)\n */\n reset() {\n this._currentPriorityLevel = 0;\n }\n /**\n * Start the optimizer. By default it will try to reach a specific framerate\n * but if the optimizer is set with improvementMode === true then it will run all optimization while frame rate is above the target frame rate\n */\n start() {\n if (this._isRunning) {\n return;\n }\n this._isRunning = true;\n // Let's wait for the scene to be ready before running our check\n this._scene.executeWhenReady(() => {\n setTimeout(() => {\n this._checkCurrentState();\n }, this._trackerDuration);\n });\n }\n _checkCurrentState() {\n if (!this._isRunning) {\n return;\n }\n const scene = this._scene;\n const options = this._options;\n this._currentFrameRate = Math.round(scene.getEngine().getFps());\n if ((this._improvementMode && this._currentFrameRate <= this._targetFrameRate) || (!this._improvementMode && this._currentFrameRate >= this._targetFrameRate)) {\n this._isRunning = false;\n this.onSuccessObservable.notifyObservers(this);\n return;\n }\n // Apply current level of optimizations\n let allDone = true;\n let noOptimizationApplied = true;\n for (let index = 0; index < options.optimizations.length; index++) {\n const optimization = options.optimizations[index];\n if (optimization.priority === this._currentPriorityLevel) {\n noOptimizationApplied = false;\n allDone = allDone && optimization.apply(scene, this);\n this.onNewOptimizationAppliedObservable.notifyObservers(optimization);\n }\n }\n // If no optimization was applied, this is a failure :(\n if (noOptimizationApplied) {\n this._isRunning = false;\n this.onFailureObservable.notifyObservers(this);\n return;\n }\n // If all optimizations were done, move to next level\n if (allDone) {\n this._currentPriorityLevel++;\n }\n // Let's the system running for a specific amount of time before checking FPS\n scene.executeWhenReady(() => {\n setTimeout(() => {\n this._checkCurrentState();\n }, this._trackerDuration);\n });\n }\n /**\n * Release all resources\n */\n dispose() {\n this.stop();\n this.onSuccessObservable.clear();\n this.onFailureObservable.clear();\n this.onNewOptimizationAppliedObservable.clear();\n if (this._sceneDisposeObserver) {\n this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);\n }\n }\n /**\n * Helper function to create a SceneOptimizer with one single line of code\n * @param scene defines the scene to work on\n * @param options defines the options to use with the SceneOptimizer\n * @param onSuccess defines a callback to call on success\n * @param onFailure defines a callback to call on failure\n * @returns the new SceneOptimizer object\n */\n static OptimizeAsync(scene, options, onSuccess, onFailure) {\n const optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);\n if (onSuccess) {\n optimizer.onSuccessObservable.add(() => {\n onSuccess();\n });\n }\n if (onFailure) {\n optimizer.onFailureObservable.add(() => {\n onFailure();\n });\n }\n optimizer.start();\n return optimizer;\n }\n}\n//# sourceMappingURL=sceneOptimizer.js.map","import { Mesh } from \"../Meshes/mesh.js\";\n\nimport { MultiMaterial } from \"../Materials/multiMaterial.js\";\nimport { SerializationHelper } from \"./decorators.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nlet serializedGeometries = [];\nconst SerializeGeometry = (geometry, serializationGeometries) => {\n if (geometry.doNotSerialize) {\n return;\n }\n serializationGeometries.vertexData.push(geometry.serializeVerticeData());\n serializedGeometries[geometry.id] = true;\n};\nconst SerializeMesh = (mesh, serializationScene) => {\n const serializationObject = {};\n // Geometry\n const geometry = mesh._geometry;\n if (geometry) {\n if (!mesh.getScene().getGeometryById(geometry.id)) {\n // Geometry was in the memory but not added to the scene, nevertheless it's better to serialize to be able to reload the mesh with its geometry\n SerializeGeometry(geometry, serializationScene.geometries);\n }\n }\n // Custom\n if (mesh.serialize) {\n mesh.serialize(serializationObject);\n }\n return serializationObject;\n};\nconst FinalizeSingleMesh = (mesh, serializationObject) => {\n //only works if the mesh is already loaded\n if (mesh.delayLoadState === 1 || mesh.delayLoadState === 0) {\n const serializeMaterial = (material) => {\n serializationObject.materials = serializationObject.materials || [];\n if (mesh.material && !serializationObject.materials.some((mat) => mat.id === mesh.material.id)) {\n serializationObject.materials.push(material.serialize());\n }\n };\n //serialize material\n if (mesh.material && !mesh.material.doNotSerialize) {\n if (mesh.material instanceof MultiMaterial) {\n serializationObject.multiMaterials = serializationObject.multiMaterials || [];\n if (!serializationObject.multiMaterials.some((mat) => mat.id === mesh.material.id)) {\n serializationObject.multiMaterials.push(mesh.material.serialize());\n for (const submaterial of mesh.material.subMaterials) {\n if (submaterial) {\n serializeMaterial(submaterial);\n }\n }\n }\n }\n else {\n serializeMaterial(mesh.material);\n }\n }\n else if (!mesh.material) {\n serializeMaterial(mesh.getScene().defaultMaterial);\n }\n //serialize geometry\n const geometry = mesh._geometry;\n if (geometry) {\n if (!serializationObject.geometries) {\n serializationObject.geometries = {};\n serializationObject.geometries.boxes = [];\n serializationObject.geometries.spheres = [];\n serializationObject.geometries.cylinders = [];\n serializationObject.geometries.toruses = [];\n serializationObject.geometries.grounds = [];\n serializationObject.geometries.planes = [];\n serializationObject.geometries.torusKnots = [];\n serializationObject.geometries.vertexData = [];\n }\n SerializeGeometry(geometry, serializationObject.geometries);\n }\n // Skeletons\n if (mesh.skeleton && !mesh.skeleton.doNotSerialize) {\n serializationObject.skeletons = serializationObject.skeletons || [];\n serializationObject.skeletons.push(mesh.skeleton.serialize());\n }\n //serialize the actual mesh\n serializationObject.meshes = serializationObject.meshes || [];\n serializationObject.meshes.push(SerializeMesh(mesh, serializationObject));\n }\n};\n/**\n * Class used to serialize a scene into a string\n */\nexport class SceneSerializer {\n /**\n * Clear cache used by a previous serialization\n */\n static ClearCache() {\n serializedGeometries = [];\n }\n /**\n * Serialize a scene into a JSON compatible object\n * Note that if the current engine does not support synchronous texture reading (like WebGPU), you should use SerializeAsync instead\n * as else you may not retrieve the proper base64 encoded texture data (when using the Texture.ForceSerializeBuffers flag)\n * @param scene defines the scene to serialize\n * @returns a JSON compatible object\n */\n static Serialize(scene) {\n return SceneSerializer._Serialize(scene);\n }\n static _Serialize(scene, checkSyncReadSupported = true) {\n const serializationObject = {};\n if (checkSyncReadSupported && !scene.getEngine()._features.supportSyncTextureRead && Texture.ForceSerializeBuffers) {\n console.warn(\"The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead.\");\n }\n SceneSerializer.ClearCache();\n // Scene\n serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;\n serializationObject.autoClear = scene.autoClear;\n serializationObject.clearColor = scene.clearColor.asArray();\n serializationObject.ambientColor = scene.ambientColor.asArray();\n serializationObject.gravity = scene.gravity.asArray();\n serializationObject.collisionsEnabled = scene.collisionsEnabled;\n serializationObject.useRightHandedSystem = scene.useRightHandedSystem;\n // Fog\n if (scene.fogMode && scene.fogMode !== 0) {\n serializationObject.fogMode = scene.fogMode;\n serializationObject.fogColor = scene.fogColor.asArray();\n serializationObject.fogStart = scene.fogStart;\n serializationObject.fogEnd = scene.fogEnd;\n serializationObject.fogDensity = scene.fogDensity;\n }\n //Physics\n if (scene.isPhysicsEnabled()) {\n const physicEngine = scene.getPhysicsEngine();\n if (physicEngine) {\n serializationObject.physicsEnabled = true;\n serializationObject.physicsGravity = physicEngine.gravity.asArray();\n serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();\n }\n }\n // Metadata\n if (scene.metadata) {\n serializationObject.metadata = scene.metadata;\n }\n // Morph targets\n serializationObject.morphTargetManagers = [];\n for (const abstractMesh of scene.meshes) {\n const manager = abstractMesh.morphTargetManager;\n if (manager) {\n serializationObject.morphTargetManagers.push(manager.serialize());\n }\n }\n // Lights\n serializationObject.lights = [];\n let index;\n let light;\n for (index = 0; index < scene.lights.length; index++) {\n light = scene.lights[index];\n if (!light.doNotSerialize) {\n serializationObject.lights.push(light.serialize());\n }\n }\n // Cameras\n serializationObject.cameras = [];\n for (index = 0; index < scene.cameras.length; index++) {\n const camera = scene.cameras[index];\n if (!camera.doNotSerialize) {\n serializationObject.cameras.push(camera.serialize());\n }\n }\n if (scene.activeCamera) {\n serializationObject.activeCameraID = scene.activeCamera.id;\n }\n // Animations\n SerializationHelper.AppendSerializedAnimations(scene, serializationObject);\n // Animation Groups\n if (scene.animationGroups && scene.animationGroups.length > 0) {\n serializationObject.animationGroups = [];\n for (let animationGroupIndex = 0; animationGroupIndex < scene.animationGroups.length; animationGroupIndex++) {\n const animationGroup = scene.animationGroups[animationGroupIndex];\n serializationObject.animationGroups.push(animationGroup.serialize());\n }\n }\n // Reflection probes\n if (scene.reflectionProbes && scene.reflectionProbes.length > 0) {\n serializationObject.reflectionProbes = [];\n for (index = 0; index < scene.reflectionProbes.length; index++) {\n const reflectionProbe = scene.reflectionProbes[index];\n serializationObject.reflectionProbes.push(reflectionProbe.serialize());\n }\n }\n // Materials\n serializationObject.materials = [];\n serializationObject.multiMaterials = [];\n let material;\n for (index = 0; index < scene.materials.length; index++) {\n material = scene.materials[index];\n if (!material.doNotSerialize) {\n serializationObject.materials.push(material.serialize());\n }\n }\n // MultiMaterials\n serializationObject.multiMaterials = [];\n for (index = 0; index < scene.multiMaterials.length; index++) {\n const multiMaterial = scene.multiMaterials[index];\n serializationObject.multiMaterials.push(multiMaterial.serialize());\n }\n // Environment texture\n if (scene.environmentTexture) {\n if (scene.environmentTexture._files) {\n serializationObject.environmentTexture = scene.environmentTexture.serialize();\n }\n else {\n serializationObject.environmentTexture = scene.environmentTexture.name;\n serializationObject.environmentTextureRotationY = scene.environmentTexture.rotationY;\n }\n }\n // Environment Intensity\n serializationObject.environmentIntensity = scene.environmentIntensity;\n // Skeletons\n serializationObject.skeletons = [];\n for (index = 0; index < scene.skeletons.length; index++) {\n const skeleton = scene.skeletons[index];\n if (!skeleton.doNotSerialize) {\n serializationObject.skeletons.push(skeleton.serialize());\n }\n }\n // Transform nodes\n serializationObject.transformNodes = [];\n for (index = 0; index < scene.transformNodes.length; index++) {\n if (!scene.transformNodes[index].doNotSerialize) {\n serializationObject.transformNodes.push(scene.transformNodes[index].serialize());\n }\n }\n // Geometries\n serializationObject.geometries = {};\n serializationObject.geometries.boxes = [];\n serializationObject.geometries.spheres = [];\n serializationObject.geometries.cylinders = [];\n serializationObject.geometries.toruses = [];\n serializationObject.geometries.grounds = [];\n serializationObject.geometries.planes = [];\n serializationObject.geometries.torusKnots = [];\n serializationObject.geometries.vertexData = [];\n serializedGeometries = [];\n const geometries = scene.getGeometries();\n for (index = 0; index < geometries.length; index++) {\n const geometry = geometries[index];\n if (geometry.isReady()) {\n SerializeGeometry(geometry, serializationObject.geometries);\n }\n }\n // Meshes\n serializationObject.meshes = [];\n for (index = 0; index < scene.meshes.length; index++) {\n const abstractMesh = scene.meshes[index];\n if (abstractMesh instanceof Mesh) {\n const mesh = abstractMesh;\n if (!mesh.doNotSerialize) {\n if (mesh.delayLoadState === 1 || mesh.delayLoadState === 0) {\n serializationObject.meshes.push(SerializeMesh(mesh, serializationObject));\n }\n }\n }\n }\n // Particles Systems\n serializationObject.particleSystems = [];\n for (index = 0; index < scene.particleSystems.length; index++) {\n serializationObject.particleSystems.push(scene.particleSystems[index].serialize(false));\n }\n // Post processes\n serializationObject.postProcesses = [];\n for (index = 0; index < scene.postProcesses.length; index++) {\n serializationObject.postProcesses.push(scene.postProcesses[index].serialize());\n }\n // Action Manager\n if (scene.actionManager) {\n serializationObject.actions = scene.actionManager.serialize(\"scene\");\n }\n // Components\n for (const component of scene._serializableComponents) {\n component.serialize(serializationObject);\n }\n return serializationObject;\n }\n /**\n * Serialize a scene into a JSON compatible object\n * @param scene defines the scene to serialize\n * @returns a JSON promise compatible object\n */\n static SerializeAsync(scene) {\n const serializationObject = SceneSerializer._Serialize(scene, false);\n const promises = [];\n this._CollectPromises(serializationObject, promises);\n return Promise.all(promises).then(() => serializationObject);\n }\n static _CollectPromises(obj, promises) {\n if (Array.isArray(obj)) {\n for (let i = 0; i < obj.length; ++i) {\n const o = obj[i];\n if (o instanceof Promise) {\n promises.push(o.then((res) => (obj[i] = res)));\n }\n else if (o instanceof Object || Array.isArray(o)) {\n this._CollectPromises(o, promises);\n }\n }\n }\n else if (obj instanceof Object) {\n for (const name in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, name)) {\n const o = obj[name];\n if (o instanceof Promise) {\n promises.push(o.then((res) => (obj[name] = res)));\n }\n else if (o instanceof Object || Array.isArray(o)) {\n this._CollectPromises(o, promises);\n }\n }\n }\n }\n }\n /**\n * Serialize a mesh into a JSON compatible object\n * @param toSerialize defines the mesh to serialize\n * @param withParents defines if parents must be serialized as well\n * @param withChildren defines if children must be serialized as well\n * @returns a JSON compatible object\n */\n static SerializeMesh(toSerialize /* Mesh || Mesh[] */, withParents = false, withChildren = false) {\n const serializationObject = {};\n SceneSerializer.ClearCache();\n toSerialize = toSerialize instanceof Array ? toSerialize : [toSerialize];\n if (withParents || withChildren) {\n //deliberate for loop! not for each, appended should be processed as well.\n for (let i = 0; i < toSerialize.length; ++i) {\n if (withChildren) {\n toSerialize[i].getDescendants().forEach((node) => {\n if (node instanceof Mesh && toSerialize.indexOf(node) < 0 && !node.doNotSerialize) {\n toSerialize.push(node);\n }\n });\n }\n //make sure the array doesn't contain the object already\n if (withParents && toSerialize[i].parent && toSerialize.indexOf(toSerialize[i].parent) < 0 && !toSerialize[i].parent.doNotSerialize) {\n toSerialize.push(toSerialize[i].parent);\n }\n }\n }\n toSerialize.forEach((mesh) => {\n FinalizeSingleMesh(mesh, serializationObject);\n });\n return serializationObject;\n }\n}\n//# sourceMappingURL=sceneSerializer.js.map","import { Tools } from \"./tools.js\";\n/**\n * This can help with recording videos from BabylonJS.\n * This is based on the available WebRTC functionalities of the browser.\n *\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToVideo\n */\nexport class VideoRecorder {\n /**\n * Returns whether or not the VideoRecorder is available in your browser.\n * @param engine Defines the Babylon Engine.\n * @returns true if supported otherwise false.\n */\n static IsSupported(engine) {\n const canvas = engine.getRenderingCanvas();\n return !!canvas && typeof canvas.captureStream === \"function\";\n }\n /**\n * True when a recording is already in progress.\n */\n get isRecording() {\n return !!this._canvas && this._canvas.isRecording;\n }\n /**\n * Create a new VideoCapture object which can help converting what you see in Babylon to a video file.\n * @param engine Defines the BabylonJS Engine you wish to record.\n * @param options Defines options that can be used to customize the capture.\n */\n constructor(engine, options = {}) {\n if (!VideoRecorder.IsSupported(engine)) {\n throw \"Your browser does not support recording so far.\";\n }\n const canvas = engine.getRenderingCanvas();\n if (!canvas) {\n throw \"The babylon engine must have a canvas to be recorded\";\n }\n this._canvas = canvas;\n this._canvas.isRecording = false;\n this._options = Object.assign(Object.assign({}, VideoRecorder._DefaultOptions), options);\n const stream = this._canvas.captureStream(this._options.fps);\n if (this._options.audioTracks) {\n for (const track of this._options.audioTracks) {\n stream.addTrack(track);\n }\n }\n this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });\n this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);\n this._mediaRecorder.onerror = this._handleError.bind(this);\n this._mediaRecorder.onstop = this._handleStop.bind(this);\n }\n /**\n * Stops the current recording before the default capture timeout passed in the startRecording function.\n */\n stopRecording() {\n if (!this._canvas || !this._mediaRecorder) {\n return;\n }\n if (!this.isRecording) {\n return;\n }\n this._canvas.isRecording = false;\n this._mediaRecorder.stop();\n }\n /**\n * Starts recording the canvas for a max duration specified in parameters.\n * @param fileName Defines the name of the file to be downloaded when the recording stop.\n * If null no automatic download will start and you can rely on the promise to get the data back.\n * @param maxDuration Defines the maximum recording time in seconds.\n * It defaults to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.\n * @returns A promise callback at the end of the recording with the video data in Blob.\n */\n startRecording(fileName = \"babylonjs.webm\", maxDuration = 7) {\n if (!this._canvas || !this._mediaRecorder) {\n throw \"Recorder has already been disposed\";\n }\n if (this.isRecording) {\n throw \"Recording already in progress\";\n }\n if (maxDuration > 0) {\n setTimeout(() => {\n this.stopRecording();\n }, maxDuration * 1000);\n }\n this._fileName = fileName;\n this._recordedChunks = [];\n this._resolve = null;\n this._reject = null;\n this._canvas.isRecording = true;\n this._mediaRecorder.start(this._options.recordChunckSize);\n return new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n /**\n * Releases internal resources used during the recording.\n */\n dispose() {\n this._canvas = null;\n this._mediaRecorder = null;\n this._recordedChunks = [];\n this._fileName = null;\n this._resolve = null;\n this._reject = null;\n }\n _handleDataAvailable(event) {\n if (event.data.size > 0) {\n this._recordedChunks.push(event.data);\n }\n }\n _handleError(event) {\n this.stopRecording();\n if (this._reject) {\n this._reject(event.error);\n }\n else {\n throw new event.error();\n }\n }\n _handleStop() {\n this.stopRecording();\n const superBuffer = new Blob(this._recordedChunks);\n if (this._resolve) {\n this._resolve(superBuffer);\n }\n window.URL.createObjectURL(superBuffer);\n if (this._fileName) {\n Tools.Download(superBuffer, this._fileName);\n }\n }\n}\nVideoRecorder._DefaultOptions = {\n mimeType: \"video/webm\",\n fps: 25,\n recordChunckSize: 3000,\n};\n//# sourceMappingURL=videoRecorder.js.map","import { Texture } from \"../Materials/Textures/texture.js\";\nimport { RenderTargetTexture } from \"../Materials/Textures/renderTargetTexture.js\";\nimport { FxaaPostProcess } from \"../PostProcesses/fxaaPostProcess.js\";\n\nimport { Logger } from \"./logger.js\";\nimport { Tools } from \"./tools.js\";\nimport { DumpTools } from \"./dumpTools.js\";\nimport { ApplyPostProcess } from \"./textureTools.js\";\nlet screenshotCanvas = null;\n/**\n * Captures a screenshot of the current rendering\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine defines the rendering engine\n * @param camera defines the source camera\n * @param size This parameter can be set to a single number or to an object with the\n * following (optional) properties: precision, width, height. If a single number is passed,\n * it will be used for both width and height. If an object is passed, the screenshot size\n * will be derived from the parameters. The precision property is a multiplier allowing\n * rendering at a higher or lower resolution\n * @param successCallback defines the callback receives a single parameter which contains the\n * screenshot as a string of base64-encoded characters. This string can be assigned to the\n * src parameter of an to display it\n * @param mimeType defines the MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param forceDownload force the system to download the image even if a successCallback is provided\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n */\nexport function CreateScreenshot(engine, camera, size, successCallback, mimeType = \"image/png\", forceDownload = false, quality) {\n const { height, width } = _GetScreenshotSize(engine, camera, size);\n if (!(height && width)) {\n Logger.Error(\"Invalid 'size' parameter !\");\n return;\n }\n if (!screenshotCanvas) {\n screenshotCanvas = document.createElement(\"canvas\");\n }\n screenshotCanvas.width = width;\n screenshotCanvas.height = height;\n const renderContext = screenshotCanvas.getContext(\"2d\");\n const ratio = engine.getRenderWidth() / engine.getRenderHeight();\n let newWidth = width;\n let newHeight = newWidth / ratio;\n if (newHeight > height) {\n newHeight = height;\n newWidth = newHeight * ratio;\n }\n const offsetX = Math.max(0, width - newWidth) / 2;\n const offsetY = Math.max(0, height - newHeight) / 2;\n const scene = camera.getScene();\n if (scene.activeCamera !== camera) {\n CreateScreenshotUsingRenderTarget(engine, camera, size, (data) => {\n if (forceDownload) {\n const blob = new Blob([data]);\n Tools.DownloadBlob(blob);\n if (successCallback) {\n successCallback(\"\");\n }\n }\n else if (successCallback) {\n successCallback(data);\n }\n }, mimeType, 1.0, engine.getCreationOptions().antialias, undefined, undefined, undefined, undefined, quality);\n }\n else {\n engine.onEndFrameObservable.addOnce(() => {\n const renderingCanvas = engine.getRenderingCanvas();\n if (renderContext && renderingCanvas) {\n renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);\n }\n if (screenshotCanvas) {\n if (forceDownload) {\n Tools.EncodeScreenshotCanvasData(screenshotCanvas, undefined, mimeType, undefined, quality);\n if (successCallback) {\n successCallback(\"\");\n }\n }\n else {\n Tools.EncodeScreenshotCanvasData(screenshotCanvas, successCallback, mimeType, undefined, quality);\n }\n }\n });\n }\n}\n/**\n * Captures a screenshot of the current rendering\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine defines the rendering engine\n * @param camera defines the source camera\n * @param size This parameter can be set to a single number or to an object with the\n * following (optional) properties: precision, width, height. If a single number is passed,\n * it will be used for both width and height. If an object is passed, the screenshot size\n * will be derived from the parameters. The precision property is a multiplier allowing\n * rendering at a higher or lower resolution\n * @param mimeType defines the MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n * @returns screenshot as a string of base64-encoded characters. This string can be assigned\n * to the src parameter of an to display it\n */\nexport function CreateScreenshotAsync(engine, camera, size, mimeType = \"image/png\", quality) {\n return new Promise((resolve, reject) => {\n CreateScreenshot(engine, camera, size, (data) => {\n if (typeof data !== \"undefined\") {\n resolve(data);\n }\n else {\n reject(new Error(\"Data is undefined\"));\n }\n }, mimeType, undefined, quality);\n });\n}\n/**\n * Captures a screenshot of the current rendering for a specific size. This will render the entire canvas but will generate a blink (due to canvas resize)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine defines the rendering engine\n * @param camera defines the source camera\n * @param width defines the expected width\n * @param height defines the expected height\n * @param mimeType defines the MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n * @returns screenshot as a string of base64-encoded characters. This string can be assigned\n * to the src parameter of an to display it\n */\nexport function CreateScreenshotWithResizeAsync(engine, camera, width, height, mimeType = \"image/png\", quality) {\n return new Promise((resolve) => {\n CreateScreenshot(engine, camera, { width: width, height: height }, () => {\n resolve();\n }, mimeType, true, quality);\n });\n}\n/**\n * Generates an image screenshot from the specified camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine The engine to use for rendering\n * @param camera The camera to use for rendering\n * @param size This parameter can be set to a single number or to an object with the\n * following (optional) properties: precision, width, height, finalWidth, finalHeight. If a single number is passed,\n * it will be used for both width and height, as well as finalWidth, finalHeight. If an object is passed, the screenshot size\n * will be derived from the parameters. The precision property is a multiplier allowing\n * rendering at a higher or lower resolution\n * @param successCallback The callback receives a single parameter which contains the\n * screenshot as a string of base64-encoded characters. This string can be assigned to the\n * src parameter of an to display it\n * @param mimeType The MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param samples Texture samples (default: 1)\n * @param antialiasing Whether antialiasing should be turned on or not (default: false)\n * @param fileName A name for for the downloaded file.\n * @param renderSprites Whether the sprites should be rendered or not (default: false)\n * @param enableStencilBuffer Whether the stencil buffer should be enabled or not (default: false)\n * @param useLayerMask if the camera's layer mask should be used to filter what should be rendered (default: true)\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n */\nexport function CreateScreenshotUsingRenderTarget(engine, camera, size, successCallback, mimeType = \"image/png\", samples = 1, antialiasing = false, fileName, renderSprites = false, enableStencilBuffer = false, useLayerMask = true, quality) {\n const { height, width, finalWidth, finalHeight } = _GetScreenshotSize(engine, camera, size);\n const targetTextureSize = { width, height };\n if (!(height && width)) {\n Logger.Error(\"Invalid 'size' parameter !\");\n return;\n }\n const originalSize = { width: engine.getRenderWidth(), height: engine.getRenderHeight() };\n engine.setSize(width, height); // we need this call to trigger onResizeObservable with the screenshot width/height on all the subsystems that are observing this event and that needs to (re)create some resources with the right dimensions\n const scene = camera.getScene();\n // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)\n const texture = new RenderTargetTexture(\"screenShot\", targetTextureSize, scene, false, false, 0, false, Texture.BILINEAR_SAMPLINGMODE, undefined, enableStencilBuffer, undefined, undefined, undefined, samples);\n texture.renderList = scene.meshes.slice();\n texture.samples = samples;\n texture.renderSprites = renderSprites;\n texture.activeCamera = camera;\n texture.forceLayerMaskCheck = useLayerMask;\n const renderToTexture = () => {\n engine.onEndFrameObservable.addOnce(() => {\n if (finalWidth === width && finalHeight === height) {\n texture.readPixels(undefined, undefined, undefined, false).then((data) => {\n DumpTools.DumpData(width, height, data, successCallback, mimeType, fileName, true, undefined, quality);\n texture.dispose();\n });\n }\n else {\n ApplyPostProcess(\"pass\", texture.getInternalTexture(), scene, undefined, undefined, undefined, finalWidth, finalHeight).then((texture) => {\n engine._readTexturePixels(texture, finalWidth, finalHeight, -1, 0, null, true, false, 0, 0).then((data) => {\n DumpTools.DumpData(finalWidth, finalHeight, data, successCallback, mimeType, fileName, true, undefined, quality);\n texture.dispose();\n });\n });\n }\n });\n // render the RTT\n scene.incrementRenderId();\n scene.resetCachedMaterial();\n texture.render(true);\n // re-render the scene after the camera has been reset to the original camera to avoid a flicker that could occur\n // if the camera used for the RTT rendering stays in effect for the next frame (and if that camera was different from the original camera)\n scene.incrementRenderId();\n scene.resetCachedMaterial();\n engine.setSize(originalSize.width, originalSize.height);\n camera.getProjectionMatrix(true); // Force cache refresh;\n scene.render();\n };\n if (antialiasing) {\n const fxaaPostProcess = new FxaaPostProcess(\"antialiasing\", 1.0, scene.activeCamera);\n texture.addPostProcess(fxaaPostProcess);\n // Async Shader Compilation can lead to none ready effects in synchronous code\n if (!fxaaPostProcess.getEffect().isReady()) {\n fxaaPostProcess.getEffect().onCompiled = () => {\n renderToTexture();\n };\n }\n // The effect is ready we can render\n else {\n renderToTexture();\n }\n }\n else {\n // No need to wait for extra resources to be ready\n renderToTexture();\n }\n}\n/**\n * Generates an image screenshot from the specified camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine The engine to use for rendering\n * @param camera The camera to use for rendering\n * @param size This parameter can be set to a single number or to an object with the\n * following (optional) properties: precision, width, height. If a single number is passed,\n * it will be used for both width and height. If an object is passed, the screenshot size\n * will be derived from the parameters. The precision property is a multiplier allowing\n * rendering at a higher or lower resolution\n * @param mimeType The MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param samples Texture samples (default: 1)\n * @param antialiasing Whether antialiasing should be turned on or not (default: false)\n * @param fileName A name for for the downloaded file.\n * @param renderSprites Whether the sprites should be rendered or not (default: false)\n * @param enableStencilBuffer Whether the stencil buffer should be enabled or not (default: false)\n * @param useLayerMask if the camera's layer mask should be used to filter what should be rendered (default: true)\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n * @returns screenshot as a string of base64-encoded characters. This string can be assigned\n * to the src parameter of an to display it\n */\nexport function CreateScreenshotUsingRenderTargetAsync(engine, camera, size, mimeType = \"image/png\", samples = 1, antialiasing = false, fileName, renderSprites = false, enableStencilBuffer = false, useLayerMask = true, quality) {\n return new Promise((resolve, reject) => {\n CreateScreenshotUsingRenderTarget(engine, camera, size, (data) => {\n if (typeof data !== \"undefined\") {\n resolve(data);\n }\n else {\n reject(new Error(\"Data is undefined\"));\n }\n }, mimeType, samples, antialiasing, fileName, renderSprites, enableStencilBuffer, useLayerMask, quality);\n });\n}\n/**\n * Gets height and width for screenshot size\n * @param engine\n * @param camera\n * @param size\n * @private\n */\nfunction _GetScreenshotSize(engine, camera, size) {\n let height = 0;\n let width = 0;\n let finalWidth = 0;\n let finalHeight = 0;\n //If a size value defined as object\n if (typeof size === \"object\") {\n const precision = size.precision\n ? Math.abs(size.precision) // prevent GL_INVALID_VALUE : glViewport: negative width/height\n : 1;\n //If a width and height values is specified\n if (size.width && size.height) {\n height = size.height * precision;\n width = size.width * precision;\n }\n //If passing only width, computing height to keep display canvas ratio.\n else if (size.width && !size.height) {\n width = size.width * precision;\n height = Math.round(width / engine.getAspectRatio(camera));\n }\n //If passing only height, computing width to keep display canvas ratio.\n else if (size.height && !size.width) {\n height = size.height * precision;\n width = Math.round(height * engine.getAspectRatio(camera));\n }\n else {\n width = Math.round(engine.getRenderWidth() * precision);\n height = Math.round(width / engine.getAspectRatio(camera));\n }\n //If a finalWidth and finalHeight values is specified\n if (size.finalWidth && size.finalHeight) {\n finalHeight = size.finalHeight;\n finalWidth = size.finalWidth;\n }\n //If passing only finalWidth, computing finalHeight to keep display canvas ratio.\n else if (size.finalWidth && !size.finalHeight) {\n finalWidth = size.finalWidth;\n finalHeight = Math.round(finalWidth / engine.getAspectRatio(camera));\n }\n //If passing only finalHeight, computing finalWidth to keep display canvas ratio.\n else if (size.finalHeight && !size.finalWidth) {\n finalHeight = size.finalHeight;\n finalWidth = Math.round(finalHeight * engine.getAspectRatio(camera));\n }\n else {\n finalWidth = width;\n finalHeight = height;\n }\n }\n //Assuming here that \"size\" parameter is a number\n else if (!isNaN(size)) {\n height = size;\n width = size;\n finalWidth = size;\n finalHeight = size;\n }\n // When creating the image data from the CanvasRenderingContext2D, the width and height is clamped to the size of the _gl context\n // On certain GPUs, it seems as if the _gl context truncates to an integer automatically. Therefore, if a user tries to pass the width of their canvas element\n // and it happens to be a float (1000.5 x 600.5 px), the engine.readPixels will return a different size array than context.createImageData\n // to resolve this, we truncate the floats here to ensure the same size\n if (width) {\n width = Math.floor(width);\n }\n if (height) {\n height = Math.floor(height);\n }\n if (finalWidth) {\n finalWidth = Math.floor(finalWidth);\n }\n if (finalHeight) {\n finalHeight = Math.floor(finalHeight);\n }\n return { height: height | 0, width: width | 0, finalWidth: finalWidth | 0, finalHeight: finalHeight | 0 };\n}\n/**\n * Class containing a set of static utilities functions for screenshots\n */\nexport const ScreenshotTools = {\n /**\n * Captures a screenshot of the current rendering\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine defines the rendering engine\n * @param camera defines the source camera\n * @param size This parameter can be set to a single number or to an object with the\n * following (optional) properties: precision, width, height. If a single number is passed,\n * it will be used for both width and height. If an object is passed, the screenshot size\n * will be derived from the parameters. The precision property is a multiplier allowing\n * rendering at a higher or lower resolution\n * @param successCallback defines the callback receives a single parameter which contains the\n * screenshot as a string of base64-encoded characters. This string can be assigned to the\n * src parameter of an to display it\n * @param mimeType defines the MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param forceDownload force the system to download the image even if a successCallback is provided\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n */\n CreateScreenshot,\n /**\n * Captures a screenshot of the current rendering\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine defines the rendering engine\n * @param camera defines the source camera\n * @param size This parameter can be set to a single number or to an object with the\n * following (optional) properties: precision, width, height. If a single number is passed,\n * it will be used for both width and height. If an object is passed, the screenshot size\n * will be derived from the parameters. The precision property is a multiplier allowing\n * rendering at a higher or lower resolution\n * @param mimeType defines the MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n * @returns screenshot as a string of base64-encoded characters. This string can be assigned\n * to the src parameter of an to display it\n */\n CreateScreenshotAsync,\n /**\n * Captures a screenshot of the current rendering for a specific size. This will render the entire canvas but will generate a blink (due to canvas resize)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine defines the rendering engine\n * @param camera defines the source camera\n * @param width defines the expected width\n * @param height defines the expected height\n * @param mimeType defines the MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n * @returns screenshot as a string of base64-encoded characters. This string can be assigned\n * to the src parameter of an to display it\n */\n CreateScreenshotWithResizeAsync,\n /**\n * Generates an image screenshot from the specified camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine The engine to use for rendering\n * @param camera The camera to use for rendering\n * @param size This parameter can be set to a single number or to an object with the\n * following (optional) properties: precision, width, height. If a single number is passed,\n * it will be used for both width and height. If an object is passed, the screenshot size\n * will be derived from the parameters. The precision property is a multiplier allowing\n * rendering at a higher or lower resolution\n * @param successCallback The callback receives a single parameter which contains the\n * screenshot as a string of base64-encoded characters. This string can be assigned to the\n * src parameter of an to display it\n * @param mimeType The MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param samples Texture samples (default: 1)\n * @param antialiasing Whether antialiasing should be turned on or not (default: false)\n * @param fileName A name for for the downloaded file.\n * @param renderSprites Whether the sprites should be rendered or not (default: false)\n * @param enableStencilBuffer Whether the stencil buffer should be enabled or not (default: false)\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n */\n CreateScreenshotUsingRenderTarget,\n /**\n * Generates an image screenshot from the specified camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine The engine to use for rendering\n * @param camera The camera to use for rendering\n * @param size This parameter can be set to a single number or to an object with the\n * following (optional) properties: precision, width, height. If a single number is passed,\n * it will be used for both width and height. If an object is passed, the screenshot size\n * will be derived from the parameters. The precision property is a multiplier allowing\n * rendering at a higher or lower resolution\n * @param mimeType The MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param samples Texture samples (default: 1)\n * @param antialiasing Whether antialiasing should be turned on or not (default: false)\n * @param fileName A name for for the downloaded file.\n * @param renderSprites Whether the sprites should be rendered or not (default: false)\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n * @returns screenshot as a string of base64-encoded characters. This string can be assigned\n * to the src parameter of an to display it\n */\n CreateScreenshotUsingRenderTargetAsync,\n};\n/**\n * This will be executed automatically for UMD and es5.\n * If esm dev wants the side effects to execute they will have to run it manually\n * Once we build native modules those need to be exported.\n * @internal\n */\nconst initSideEffects = () => {\n // References the dependencies.\n Tools.CreateScreenshot = CreateScreenshot;\n Tools.CreateScreenshotAsync = CreateScreenshotAsync;\n Tools.CreateScreenshotUsingRenderTarget = CreateScreenshotUsingRenderTarget;\n Tools.CreateScreenshotUsingRenderTargetAsync = CreateScreenshotUsingRenderTargetAsync;\n};\ninitSideEffects();\n//# sourceMappingURL=screenshotTools.js.map","/**\n * Enum that determines the text-wrapping mode to use.\n */\nexport var InspectableType;\n(function (InspectableType) {\n /**\n * Checkbox for booleans\n */\n InspectableType[InspectableType[\"Checkbox\"] = 0] = \"Checkbox\";\n /**\n * Sliders for numbers\n */\n InspectableType[InspectableType[\"Slider\"] = 1] = \"Slider\";\n /**\n * Vector3\n */\n InspectableType[InspectableType[\"Vector3\"] = 2] = \"Vector3\";\n /**\n * Quaternions\n */\n InspectableType[InspectableType[\"Quaternion\"] = 3] = \"Quaternion\";\n /**\n * Color3\n */\n InspectableType[InspectableType[\"Color3\"] = 4] = \"Color3\";\n /**\n * String\n */\n InspectableType[InspectableType[\"String\"] = 5] = \"String\";\n /**\n * Button\n */\n InspectableType[InspectableType[\"Button\"] = 6] = \"Button\";\n /**\n * Options\n */\n InspectableType[InspectableType[\"Options\"] = 7] = \"Options\";\n /**\n * Tab\n */\n InspectableType[InspectableType[\"Tab\"] = 8] = \"Tab\";\n /**\n * File button\n */\n InspectableType[InspectableType[\"FileButton\"] = 9] = \"FileButton\";\n /**\n * Vector2\n */\n InspectableType[InspectableType[\"Vector2\"] = 10] = \"Vector2\";\n})(InspectableType || (InspectableType = {}));\n//# sourceMappingURL=iInspectable.js.map","export {};\n//# sourceMappingURL=fileRequest.js.map","export {};\n//# sourceMappingURL=customAnimationFrameRequester.js.map","export {};\n//# sourceMappingURL=screenshotSize.js.map","import { Decode } from \"./stringTools.js\";\n/**\n * Utility class for reading from a data buffer\n */\nexport class DataReader {\n /**\n * Constructor\n * @param buffer The buffer to read\n */\n constructor(buffer) {\n /**\n * The current byte offset from the beginning of the data buffer.\n */\n this.byteOffset = 0;\n this.buffer = buffer;\n }\n /**\n * Loads the given byte length.\n * @param byteLength The byte length to load\n * @returns A promise that resolves when the load is complete\n */\n loadAsync(byteLength) {\n return this.buffer.readAsync(this.byteOffset, byteLength).then((data) => {\n this._dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);\n this._dataByteOffset = 0;\n });\n }\n /**\n * Read a unsigned 32-bit integer from the currently loaded data range.\n * @returns The 32-bit integer read\n */\n readUint32() {\n const value = this._dataView.getUint32(this._dataByteOffset, true);\n this._dataByteOffset += 4;\n this.byteOffset += 4;\n return value;\n }\n /**\n * Read a byte array from the currently loaded data range.\n * @param byteLength The byte length to read\n * @returns The byte array read\n */\n readUint8Array(byteLength) {\n const value = new Uint8Array(this._dataView.buffer, this._dataView.byteOffset + this._dataByteOffset, byteLength);\n this._dataByteOffset += byteLength;\n this.byteOffset += byteLength;\n return value;\n }\n /**\n * Read a string from the currently loaded data range.\n * @param byteLength The byte length to read\n * @returns The string read\n */\n readString(byteLength) {\n return Decode(this.readUint8Array(byteLength));\n }\n /**\n * Skips the given byte length the currently loaded data range.\n * @param byteLength The byte length to skip\n */\n skipBytes(byteLength) {\n this._dataByteOffset += byteLength;\n this.byteOffset += byteLength;\n }\n}\n//# sourceMappingURL=dataReader.js.map","/**\n * Class for storing data to local storage if available or in-memory storage otherwise\n */\nexport class DataStorage {\n static _GetStorage() {\n try {\n localStorage.setItem(\"test\", \"\");\n localStorage.removeItem(\"test\");\n return localStorage;\n }\n catch (_a) {\n const inMemoryStorage = {};\n return {\n getItem: (key) => {\n const value = inMemoryStorage[key];\n return value === undefined ? null : value;\n },\n setItem: (key, value) => {\n inMemoryStorage[key] = value;\n },\n };\n }\n }\n /**\n * Reads a string from the data storage\n * @param key The key to read\n * @param defaultValue The value if the key doesn't exist\n * @returns The string value\n */\n static ReadString(key, defaultValue) {\n const value = this._Storage.getItem(key);\n return value !== null ? value : defaultValue;\n }\n /**\n * Writes a string to the data storage\n * @param key The key to write\n * @param value The value to write\n */\n static WriteString(key, value) {\n this._Storage.setItem(key, value);\n }\n /**\n * Reads a boolean from the data storage\n * @param key The key to read\n * @param defaultValue The value if the key doesn't exist\n * @returns The boolean value\n */\n static ReadBoolean(key, defaultValue) {\n const value = this._Storage.getItem(key);\n return value !== null ? value === \"true\" : defaultValue;\n }\n /**\n * Writes a boolean to the data storage\n * @param key The key to write\n * @param value The value to write\n */\n static WriteBoolean(key, value) {\n this._Storage.setItem(key, value ? \"true\" : \"false\");\n }\n /**\n * Reads a number from the data storage\n * @param key The key to read\n * @param defaultValue The value if the key doesn't exist\n * @returns The number value\n */\n static ReadNumber(key, defaultValue) {\n const value = this._Storage.getItem(key);\n return value !== null ? parseFloat(value) : defaultValue;\n }\n /**\n * Writes a number to the data storage\n * @param key The key to write\n * @param value The value to write\n */\n static WriteNumber(key, value) {\n this._Storage.setItem(key, value.toString());\n }\n}\nDataStorage._Storage = DataStorage._GetStorage();\n//# sourceMappingURL=dataStorage.js.map","import { SceneSerializer } from \"./sceneSerializer.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { Light } from \"../Lights/light.js\";\nimport { Camera } from \"../Cameras/camera.js\";\nimport { Skeleton } from \"../Bones/skeleton.js\";\nimport { Material } from \"../Materials/material.js\";\nimport { MultiMaterial } from \"../Materials/multiMaterial.js\";\nimport { TransformNode } from \"../Meshes/transformNode.js\";\nimport { ParticleSystem } from \"../Particles/particleSystem.js\";\nimport { MorphTargetManager } from \"../Morph/morphTargetManager.js\";\nimport { ShadowGenerator } from \"../Lights/Shadows/shadowGenerator.js\";\nimport { PostProcess } from \"../PostProcesses/postProcess.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { SerializationHelper } from \"./decorators.js\";\n/**\n * Class used to record delta files between 2 scene states\n */\nexport class SceneRecorder {\n constructor() {\n this._trackedScene = null;\n }\n /**\n * Track a given scene. This means the current scene state will be considered the original state\n * @param scene defines the scene to track\n */\n track(scene) {\n this._trackedScene = scene;\n SerializationHelper.AllowLoadingUniqueId = true;\n this._savedJSON = SceneSerializer.Serialize(scene);\n SerializationHelper.AllowLoadingUniqueId = false;\n }\n /**\n * Get the delta between current state and original state\n * @returns a any containing the delta\n */\n getDelta() {\n if (!this._trackedScene) {\n return null;\n }\n const currentForceSerializeBuffers = Texture.ForceSerializeBuffers;\n Texture.ForceSerializeBuffers = false;\n SerializationHelper.AllowLoadingUniqueId = true;\n const newJSON = SceneSerializer.Serialize(this._trackedScene);\n SerializationHelper.AllowLoadingUniqueId = false;\n const deltaJSON = {};\n for (const node in newJSON) {\n this._compareCollections(node, this._savedJSON[node], newJSON[node], deltaJSON);\n }\n Texture.ForceSerializeBuffers = currentForceSerializeBuffers;\n return deltaJSON;\n }\n _compareArray(key, original, current, deltaJSON) {\n if (original.length === 0 && current.length === 0) {\n return true;\n }\n // Numbers?\n if ((original.length && !isNaN(original[0])) || (current.length && !isNaN(current[0]))) {\n if (original.length !== current.length) {\n return false;\n }\n if (original.length === 0) {\n return true;\n }\n for (let index = 0; index < original.length; index++) {\n if (original[index] !== current[index]) {\n deltaJSON[key] = current;\n return false;\n }\n }\n return true;\n }\n // let's use uniqueId to find similar objects\n const originalUniqueIds = [];\n for (let index = 0; index < original.length; index++) {\n const originalObject = original[index];\n const originalUniqueId = originalObject.uniqueId;\n originalUniqueIds.push(originalUniqueId);\n // Look for that object in current state\n const currentObjects = current.filter((c) => c.uniqueId === originalUniqueId);\n if (currentObjects.length) {\n // We have a candidate\n const currentObject = currentObjects[0];\n const newObject = {};\n if (!this._compareObjects(originalObject, currentObject, newObject)) {\n if (!deltaJSON[key]) {\n deltaJSON[key] = [];\n }\n newObject.__state = {\n id: currentObject.id || currentObject.name,\n };\n deltaJSON[key].push(newObject);\n }\n }\n else {\n // We need to delete\n const newObject = {\n __state: {\n deleteId: originalObject.id || originalObject.name,\n },\n };\n if (!deltaJSON[key]) {\n deltaJSON[key] = [];\n }\n deltaJSON[key].push(newObject);\n }\n }\n // Checking for new objects\n for (let index = 0; index < current.length; index++) {\n const currentObject = current[index];\n const currentUniqueId = currentObject.uniqueId;\n // Object was added\n if (originalUniqueIds.indexOf(currentUniqueId) === -1) {\n if (!deltaJSON[key]) {\n deltaJSON[key] = [];\n }\n deltaJSON[key].push(currentObject);\n }\n }\n return true;\n }\n _compareObjects(originalObjet, currentObject, deltaJSON) {\n let aDifferenceWasFound = false;\n for (const prop in originalObjet) {\n if (!Object.prototype.hasOwnProperty.call(originalObjet, prop)) {\n continue;\n }\n const originalValue = originalObjet[prop];\n const currentValue = currentObject[prop];\n let diffFound = false;\n if (Array.isArray(originalValue)) {\n diffFound = JSON.stringify(originalValue) !== JSON.stringify(currentValue);\n }\n else if (!isNaN(originalValue) || Object.prototype.toString.call(originalValue) == \"[object String]\") {\n diffFound = originalValue !== currentValue;\n }\n else if (typeof originalValue === \"object\" && typeof currentValue === \"object\") {\n const newObject = {};\n if (!this._compareObjects(originalValue, currentValue, newObject)) {\n deltaJSON[prop] = newObject;\n aDifferenceWasFound = true;\n }\n }\n if (diffFound) {\n aDifferenceWasFound = true;\n deltaJSON[prop] = currentValue;\n }\n }\n return !aDifferenceWasFound;\n }\n _compareCollections(key, original, current, deltaJSON) {\n // Same ?\n if (original === current) {\n return;\n }\n if (original && current) {\n // Array?\n if (Array.isArray(original) && Array.isArray(current)) {\n if (this._compareArray(key, original, current, deltaJSON)) {\n return;\n }\n }\n else if (typeof original === \"object\" && typeof current === \"object\") {\n // Object\n const newObject = {};\n if (!this._compareObjects(original, current, newObject)) {\n deltaJSON[key] = newObject;\n }\n return;\n }\n }\n }\n static GetShadowGeneratorById(scene, id) {\n const allGenerators = scene.lights.map((l) => l.getShadowGenerators());\n for (const generators of allGenerators) {\n if (generators) {\n const iterator = generators.values();\n for (let key = iterator.next(); key.done !== true; key = iterator.next()) {\n const generator = key.value;\n if (generator && generator.id === id) {\n return generator;\n }\n }\n }\n }\n return null;\n }\n /**\n * Apply a given delta to a given scene\n * @param deltaJSON defines the JSON containing the delta\n * @param scene defines the scene to apply the delta to\n */\n static ApplyDelta(deltaJSON, scene) {\n if (typeof deltaJSON === \"string\") {\n deltaJSON = JSON.parse(deltaJSON);\n }\n // Scene\n const anyScene = scene;\n for (const prop in deltaJSON) {\n const source = deltaJSON[prop];\n const property = anyScene[prop];\n if (Array.isArray(property) || prop === \"shadowGenerators\") {\n // Restore array\n switch (prop) {\n case \"cameras\":\n this._ApplyDeltaForEntity(source, scene, scene.getCameraById.bind(scene), (data) => Camera.Parse(data, scene));\n break;\n case \"lights\":\n this._ApplyDeltaForEntity(source, scene, scene.getLightById.bind(scene), (data) => Light.Parse(data, scene));\n break;\n case \"shadowGenerators\":\n this._ApplyDeltaForEntity(source, scene, (id) => this.GetShadowGeneratorById(scene, id), (data) => ShadowGenerator.Parse(data, scene));\n break;\n case \"meshes\":\n this._ApplyDeltaForEntity(source, scene, scene.getMeshById.bind(scene), (data) => Mesh.Parse(data, scene, \"\"));\n break;\n case \"skeletons\":\n this._ApplyDeltaForEntity(source, scene, scene.getSkeletonById.bind(scene), (data) => Skeleton.Parse(data, scene));\n break;\n case \"materials\":\n this._ApplyDeltaForEntity(source, scene, scene.getMaterialById.bind(scene), (data) => Material.Parse(data, scene, \"\"));\n break;\n case \"multiMaterials\":\n this._ApplyDeltaForEntity(source, scene, scene.getMaterialById.bind(scene), (data) => MultiMaterial.Parse(data, scene, \"\"));\n break;\n case \"transformNodes\":\n this._ApplyDeltaForEntity(source, scene, scene.getTransformNodeById.bind(scene), (data) => TransformNode.Parse(data, scene, \"\"));\n break;\n case \"particleSystems\":\n this._ApplyDeltaForEntity(source, scene, scene.getParticleSystemById.bind(scene), (data) => ParticleSystem.Parse(data, scene, \"\"));\n break;\n case \"morphTargetManagers\":\n this._ApplyDeltaForEntity(source, scene, scene.getMorphTargetById.bind(scene), (data) => MorphTargetManager.Parse(data, scene));\n break;\n case \"postProcesses\":\n this._ApplyDeltaForEntity(source, scene, scene.getPostProcessByName.bind(scene), (data) => PostProcess.Parse(data, scene, \"\"));\n break;\n }\n }\n else if (!isNaN(property)) {\n anyScene[prop] = source;\n }\n else if (property.fromArray) {\n property.fromArray(source);\n }\n }\n }\n static _ApplyPropertiesToEntity(deltaJSON, entity) {\n for (const prop in deltaJSON) {\n const source = deltaJSON[prop];\n const property = entity[prop];\n if (property === undefined) {\n continue;\n }\n if (!isNaN(property) || Array.isArray(property)) {\n entity[prop] = source;\n }\n else if (property.fromArray) {\n property.fromArray(source);\n }\n else if (typeof property === \"object\" && property !== null) {\n this._ApplyPropertiesToEntity(source, property);\n }\n }\n }\n static _ApplyDeltaForEntity(sources, scene, finder, addNew) {\n for (const source of sources) {\n // Update\n if (source.__state && source.__state.id !== undefined) {\n const targetEntity = finder(source.__state.id);\n if (targetEntity) {\n // This first pass applies properties that aren't on the serialization list\n this._ApplyPropertiesToEntity(source, targetEntity);\n // The second pass applies the serializable properties\n SerializationHelper.ParseProperties(source, targetEntity, scene, null);\n }\n }\n else if (source.__state && source.__state.deleteId !== undefined) {\n const target = finder(source.__state.deleteId);\n target === null || target === void 0 ? void 0 : target.dispose();\n }\n else {\n // New\n addNew(source);\n }\n }\n }\n}\n//# sourceMappingURL=sceneRecorder.js.map","import { Matrix, Vector3 } from \"../Maths/math.vector.js\";\n// This implementation was based on the original MIT-licensed TRACE repository\n// from https://github.com/septagon/TRACE.\n/**\n * Generic implementation of Levenshtein distance.\n */\nvar Levenshtein;\n(function (Levenshtein) {\n /**\n * Alphabet from which to construct sequences to be compared using Levenshtein\n * distance.\n */\n class Alphabet {\n /**\n * Serialize the Alphabet to JSON string.\n * @returns JSON serialization\n */\n serialize() {\n const jsonObject = {};\n const characters = new Array(this._characterToIdx.size);\n this._characterToIdx.forEach((v, k) => {\n characters[v] = k;\n });\n jsonObject[\"characters\"] = characters;\n jsonObject[\"insertionCosts\"] = this._insertionCosts;\n jsonObject[\"deletionCosts\"] = this._deletionCosts;\n jsonObject[\"substitutionCosts\"] = this._substitutionCosts;\n return JSON.stringify(jsonObject);\n }\n /**\n * Parse an Alphabet from a JSON serialization.\n * @param json JSON string to deserialize\n * @returns deserialized Alphabet\n */\n static Deserialize(json) {\n const jsonObject = JSON.parse(json);\n const alphabet = new Alphabet(jsonObject[\"characters\"]);\n alphabet._insertionCosts = jsonObject[\"insertionCosts\"];\n alphabet._deletionCosts = jsonObject[\"deletionCosts\"];\n alphabet._substitutionCosts = jsonObject[\"substitutionCosts\"];\n return alphabet;\n }\n /**\n * Create a new Alphabet.\n * @param characters characters of the alphabet\n * @param charToInsertionCost function mapping characters to insertion costs\n * @param charToDeletionCost function mapping characters to deletion costs\n * @param charsToSubstitutionCost function mapping character pairs to substitution costs\n */\n constructor(characters, charToInsertionCost = null, charToDeletionCost = null, charsToSubstitutionCost = null) {\n charToInsertionCost = charToInsertionCost !== null && charToInsertionCost !== void 0 ? charToInsertionCost : (() => 1);\n charToDeletionCost = charToDeletionCost !== null && charToDeletionCost !== void 0 ? charToDeletionCost : (() => 1);\n charsToSubstitutionCost = charsToSubstitutionCost !== null && charsToSubstitutionCost !== void 0 ? charsToSubstitutionCost : ((a, b) => (a === b ? 0 : 1));\n this._characterToIdx = new Map();\n this._insertionCosts = new Array(characters.length);\n this._deletionCosts = new Array(characters.length);\n this._substitutionCosts = new Array(characters.length);\n let c;\n for (let outerIdx = 0; outerIdx < characters.length; ++outerIdx) {\n c = characters[outerIdx];\n this._characterToIdx.set(c, outerIdx);\n this._insertionCosts[outerIdx] = charToInsertionCost(c);\n this._deletionCosts[outerIdx] = charToDeletionCost(c);\n this._substitutionCosts[outerIdx] = new Array(characters.length);\n for (let innerIdx = outerIdx; innerIdx < characters.length; ++innerIdx) {\n this._substitutionCosts[outerIdx][innerIdx] = charsToSubstitutionCost(c, characters[innerIdx]);\n }\n }\n }\n /**\n * Get the index (internally-assigned number) for a character.\n * @param char character\n * @returns index\n */\n getCharacterIdx(char) {\n return this._characterToIdx.get(char);\n }\n /**\n * Get the insertion cost of a character from its index.\n * @param idx character index\n * @returns insertion cost\n */\n getInsertionCost(idx) {\n return this._insertionCosts[idx];\n }\n /**\n * Get the deletion cost of a character from its index.\n * @param idx character index\n * @returns deletion cost\n */\n getDeletionCost(idx) {\n return this._deletionCosts[idx];\n }\n /**\n * Gets the cost to substitute two characters. NOTE: this cost is\n * required to be bi-directional, meaning it cannot matter which of\n * the provided characters is being removed and which is being inserted.\n * @param idx1 the first character index\n * @param idx2 the second character index\n * @returns substitution cost\n */\n getSubstitutionCost(idx1, idx2) {\n const min = Math.min(idx1, idx2);\n const max = Math.max(idx1, idx2);\n return this._substitutionCosts[min][max];\n }\n }\n Levenshtein.Alphabet = Alphabet;\n /**\n * Character sequence intended to be compared against other Sequences created\n * with the same Alphabet in order to compute Levenshtein distance.\n */\n class Sequence {\n /**\n * Serialize to JSON string. JSON representation does NOT include the Alphabet\n * from which this Sequence was created; Alphabet must be independently\n * serialized.\n * @returns JSON string\n */\n serialize() {\n return JSON.stringify(this._characters);\n }\n /**\n * Deserialize from JSON string and Alphabet. This should be the same Alphabet\n * from which the Sequence was originally created, which must be serialized and\n * deserialized independently so that it can be passed in here.\n * @param json JSON string representation of Sequence\n * @param alphabet Alphabet from which Sequence was originally created\n * @returns Sequence\n */\n static Deserialize(json, alphabet) {\n const sequence = new Sequence([], alphabet);\n sequence._characters = JSON.parse(json);\n return sequence;\n }\n /**\n * Create a new Sequence.\n * @param characters characters in the new Sequence\n * @param alphabet Alphabet, which must include all used characters\n */\n constructor(characters, alphabet) {\n if (characters.length > Sequence._MAX_SEQUENCE_LENGTH) {\n throw new Error(\"Sequences longer than \" + Sequence._MAX_SEQUENCE_LENGTH + \" not supported.\");\n }\n this._alphabet = alphabet;\n this._characters = characters.map((c) => this._alphabet.getCharacterIdx(c));\n }\n /**\n * Get the distance between this Sequence and another.\n * @param other sequence to compare to\n * @returns Levenshtein distance\n */\n distance(other) {\n return Sequence._Distance(this, other);\n }\n /**\n * Compute the Levenshtein distance between two Sequences.\n * @param a first Sequence\n * @param b second Sequence\n * @returns Levenshtein distance\n */\n static _Distance(a, b) {\n const alphabet = a._alphabet;\n if (alphabet !== b._alphabet) {\n throw new Error(\"Cannot Levenshtein compare Sequences built from different alphabets.\");\n }\n const aChars = a._characters;\n const bChars = b._characters;\n const aLength = aChars.length;\n const bLength = bChars.length;\n const costMatrix = Sequence._CostMatrix;\n costMatrix[0][0] = 0;\n for (let idx = 0; idx < aLength; ++idx) {\n costMatrix[idx + 1][0] = costMatrix[idx][0] + alphabet.getInsertionCost(aChars[idx]);\n }\n for (let idx = 0; idx < bLength; ++idx) {\n costMatrix[0][idx + 1] = costMatrix[0][idx] + alphabet.getInsertionCost(bChars[idx]);\n }\n for (let aIdx = 0; aIdx < aLength; ++aIdx) {\n for (let bIdx = 0; bIdx < bLength; ++bIdx) {\n Sequence._InsertionCost = costMatrix[aIdx + 1][bIdx] + alphabet.getInsertionCost(bChars[bIdx]);\n Sequence._DeletionCost = costMatrix[aIdx][bIdx + 1] + alphabet.getDeletionCost(aChars[aIdx]);\n Sequence._SubstitutionCost = costMatrix[aIdx][bIdx] + alphabet.getSubstitutionCost(aChars[aIdx], bChars[bIdx]);\n costMatrix[aIdx + 1][bIdx + 1] = Math.min(Sequence._InsertionCost, Sequence._DeletionCost, Sequence._SubstitutionCost);\n }\n }\n return costMatrix[aLength][bLength];\n }\n }\n // Scratch values\n Sequence._MAX_SEQUENCE_LENGTH = 256;\n Sequence._CostMatrix = [...Array(Sequence._MAX_SEQUENCE_LENGTH + 1)].map(() => new Array(Sequence._MAX_SEQUENCE_LENGTH + 1));\n Levenshtein.Sequence = Sequence;\n})(Levenshtein || (Levenshtein = {}));\n/**\n * A 3D trajectory consisting of an order list of vectors describing a\n * path of motion through 3D space.\n */\nexport class Trajectory {\n /**\n * Serialize to JSON.\n * @returns serialized JSON string\n */\n serialize() {\n return JSON.stringify(this);\n }\n /**\n * Deserialize from JSON.\n * @param json serialized JSON string\n * @returns deserialized Trajectory\n */\n static Deserialize(json) {\n const jsonObject = JSON.parse(json);\n const trajectory = new Trajectory(jsonObject[\"_segmentLength\"]);\n trajectory._points = jsonObject[\"_points\"].map((pt) => {\n return new Vector3(pt[\"_x\"], pt[\"_y\"], pt[\"_z\"]);\n });\n return trajectory;\n }\n /**\n * Create a new empty Trajectory.\n * @param segmentLength radius of discretization for Trajectory points\n */\n constructor(segmentLength = 0.01) {\n this._points = [];\n this._segmentLength = segmentLength;\n }\n /**\n * Get the length of the Trajectory.\n * @returns length of the Trajectory\n */\n getLength() {\n return this._points.length * this._segmentLength;\n }\n /**\n * Append a new point to the Trajectory.\n * NOTE: This implementation has many allocations.\n * @param point point to append to the Trajectory\n */\n add(point) {\n let numPoints = this._points.length;\n if (numPoints === 0) {\n this._points.push(point.clone());\n }\n else {\n const getT = () => this._segmentLength / Vector3.Distance(this._points[numPoints - 1], point);\n for (let t = getT(); t <= 1.0; t = getT()) {\n const newPoint = this._points[numPoints - 1].scale(1.0 - t);\n point.scaleAndAddToRef(t, newPoint);\n this._points.push(newPoint);\n ++numPoints;\n }\n }\n }\n /**\n * Create a new Trajectory with a segment length chosen to make it\n * probable that the new Trajectory will have a specified number of\n * segments. This operation is imprecise.\n * @param targetResolution number of segments desired\n * @returns new Trajectory with approximately the requested number of segments\n */\n resampleAtTargetResolution(targetResolution) {\n const resampled = new Trajectory(this.getLength() / targetResolution);\n this._points.forEach((pt) => {\n resampled.add(pt);\n });\n return resampled;\n }\n /**\n * Convert Trajectory segments into tokenized representation. This\n * representation is an array of numbers where each nth number is the\n * index of the token which is most similar to the nth segment of the\n * Trajectory.\n * @param tokens list of vectors which serve as discrete tokens\n * @returns list of indices of most similar token per segment\n */\n tokenize(tokens) {\n const tokenization = [];\n const segmentDir = new Vector3();\n for (let idx = 2; idx < this._points.length; ++idx) {\n if (Trajectory._TransformSegmentDirToRef(this._points[idx - 2], this._points[idx - 1], this._points[idx], segmentDir)) {\n tokenization.push(Trajectory._TokenizeSegment(segmentDir, tokens));\n }\n }\n return tokenization;\n }\n /**\n * Transform the rotation (i.e., direction) of a segment to isolate\n * the relative transformation represented by the segment. This operation\n * may or may not succeed due to singularities in the equations that define\n * motion relativity in this context.\n * @param priorVec the origin of the prior segment\n * @param fromVec the origin of the current segment\n * @param toVec the destination of the current segment\n * @param result reference to output variable\n * @returns whether or not transformation was successful\n */\n static _TransformSegmentDirToRef(priorVec, fromVec, toVec, result) {\n const DOT_PRODUCT_SAMPLE_REJECTION_THRESHOLD = 0.98;\n fromVec.subtractToRef(priorVec, Trajectory._ForwardDir);\n Trajectory._ForwardDir.normalize();\n fromVec.scaleToRef(-1, Trajectory._InverseFromVec);\n Trajectory._InverseFromVec.normalize();\n if (Math.abs(Vector3.Dot(Trajectory._ForwardDir, Trajectory._InverseFromVec)) > DOT_PRODUCT_SAMPLE_REJECTION_THRESHOLD) {\n return false;\n }\n Vector3.CrossToRef(Trajectory._ForwardDir, Trajectory._InverseFromVec, Trajectory._UpDir);\n Trajectory._UpDir.normalize();\n Matrix.LookAtLHToRef(priorVec, fromVec, Trajectory._UpDir, Trajectory._LookMatrix);\n toVec.subtractToRef(fromVec, Trajectory._FromToVec);\n Trajectory._FromToVec.normalize();\n Vector3.TransformNormalToRef(Trajectory._FromToVec, Trajectory._LookMatrix, result);\n return true;\n }\n /**\n * Determine which token vector is most similar to the\n * segment vector.\n * @param segment segment vector\n * @param tokens token vector list\n * @returns index of the most similar token to the segment\n */\n static _TokenizeSegment(segment, tokens) {\n Trajectory._BestMatch = 0;\n Trajectory._Score = Vector3.Dot(segment, tokens[0]);\n Trajectory._BestScore = Trajectory._Score;\n for (let idx = 1; idx < tokens.length; ++idx) {\n Trajectory._Score = Vector3.Dot(segment, tokens[idx]);\n if (Trajectory._Score > Trajectory._BestScore) {\n Trajectory._BestMatch = idx;\n Trajectory._BestScore = Trajectory._Score;\n }\n }\n return Trajectory._BestMatch;\n }\n}\nTrajectory._ForwardDir = new Vector3();\nTrajectory._InverseFromVec = new Vector3();\nTrajectory._UpDir = new Vector3();\nTrajectory._FromToVec = new Vector3();\nTrajectory._LookMatrix = new Matrix();\n/**\n * Collection of vectors intended to be used as the basis of Trajectory\n * tokenization for Levenshtein distance comparison. Canonically, a\n * Vector3Alphabet will resemble a \"spikeball\" of vectors distributed\n * roughly evenly over the surface of the unit sphere.\n */\nclass Vector3Alphabet {\n /**\n * Helper method to create new \"spikeball\" Vector3Alphabets. Uses a naive\n * optimize-from-random strategy to space points around the unit sphere\n * surface as a simple alternative to really doing the math to tile the\n * sphere.\n * @param alphabetSize size of the desired alphabet\n * @param iterations number of iterations over which to optimize the \"spikeball\"\n * @param startingStepSize distance factor to move points in early optimization iterations\n * @param endingStepSize distance factor to move points in late optimization iterations\n * @param fixedValues alphabet \"characters\" that are required and cannot be moved by optimization\n * @returns a new randomly generated and optimized Vector3Alphabet of the specified size\n */\n static Generate(alphabetSize = 64, iterations = 256, startingStepSize = 0.1, endingStepSize = 0.001, fixedValues = []) {\n const EPSILON = 0.001;\n const EPSILON_SQUARED = EPSILON * EPSILON;\n const alphabet = new Vector3Alphabet(alphabetSize);\n for (let idx = 0; idx < alphabetSize; ++idx) {\n alphabet.chars[idx] = new Vector3(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5);\n alphabet.chars[idx].normalize();\n }\n for (let idx = 0; idx < fixedValues.length; ++idx) {\n alphabet.chars[idx].copyFrom(fixedValues[idx]);\n }\n let stepSize;\n let distSq;\n const force = new Vector3();\n const scratch = new Vector3();\n const lerp = (l, r, t) => (1.0 - t) * l + t * r;\n for (let iteration = 0; iteration < iterations; ++iteration) {\n stepSize = lerp(startingStepSize, endingStepSize, iteration / (iterations - 1));\n for (let idx = fixedValues.length; idx < alphabet.chars.length; ++idx) {\n force.copyFromFloats(0, 0, 0);\n alphabet.chars.forEach((pt) => {\n alphabet.chars[idx].subtractToRef(pt, scratch);\n distSq = scratch.lengthSquared();\n if (distSq > EPSILON_SQUARED) {\n scratch.scaleAndAddToRef(1 / (scratch.lengthSquared() * distSq), force);\n }\n });\n force.scaleInPlace(stepSize);\n alphabet.chars[idx].addInPlace(force);\n alphabet.chars[idx].normalize();\n }\n }\n return alphabet;\n }\n /**\n * Serialize to JSON.\n * @returns JSON serialization\n */\n serialize() {\n return JSON.stringify(this.chars);\n }\n /**\n * Deserialize from JSON.\n * @param json JSON serialization\n * @returns deserialized Vector3Alphabet\n */\n static Deserialize(json) {\n const jsonObject = JSON.parse(json);\n const alphabet = new Vector3Alphabet(jsonObject.length);\n for (let idx = 0; idx < jsonObject.length; ++idx) {\n alphabet.chars[idx] = new Vector3(jsonObject[idx][\"_x\"], jsonObject[idx][\"_y\"], jsonObject[idx][\"_z\"]);\n }\n return alphabet;\n }\n constructor(size) {\n this.chars = new Array(size);\n }\n}\n/**\n * Class which formalizes the manner in which a Vector3Alphabet is used to tokenize and\n * describe a Trajectory. This class houses the functionality which determines what\n * attributes of Trajectories are and are not considered important, such as scale.\n */\nclass TrajectoryDescriptor {\n /**\n * Serialize to JSON.\n * @returns JSON serialization\n */\n serialize() {\n return JSON.stringify(this._sequences.map((sequence) => sequence.serialize()));\n }\n /**\n * Deserialize from JSON string and Alphabet. This should be the same Alphabet\n * from which the descriptor was originally created, which must be serialized and\n * deserialized independently so that it can be passed in here.\n * @param json JSON serialization\n * @param alphabet Alphabet from which descriptor was originally created\n * @returns deserialized TrajectoryDescriptor\n */\n static Deserialize(json, alphabet) {\n const descriptor = new TrajectoryDescriptor();\n descriptor._sequences = JSON.parse(json).map((s) => Levenshtein.Sequence.Deserialize(s, alphabet));\n return descriptor;\n }\n /**\n * Create a new TrajectoryDescriptor to describe a provided Trajectory according\n * to the provided alphabets.\n * @param trajectory Trajectory to be described\n * @param vector3Alphabet Vector3Alphabet to be used to tokenize the Trajectory\n * @param levenshteinAlphabet Levenshtein.Alphabet to be used as basis for comparison with other descriptors\n * @returns TrajectoryDescriptor describing provided Trajectory\n */\n static CreateFromTrajectory(trajectory, vector3Alphabet, levenshteinAlphabet) {\n return TrajectoryDescriptor.CreateFromTokenizationPyramid(TrajectoryDescriptor._GetTokenizationPyramid(trajectory, vector3Alphabet), levenshteinAlphabet);\n }\n /**\n * Create a new TrajectoryDescriptor from a pre-existing pyramid of tokens.\n * NOTE: This function exists to support an outdated serialization mechanism and should\n * be deleted if it is no longer useful.\n * @param pyramid tokenization pyramid\n * @param levenshteinAlphabet Levenshtein.Alphabet to be uses as basis for comparison with other descriptors\n * @returns TrajectoryDescriptor describing the Trajectory from which the pyramid was built\n */\n static CreateFromTokenizationPyramid(pyramid, levenshteinAlphabet) {\n const descriptor = new TrajectoryDescriptor();\n descriptor._sequences = pyramid.map((tokens) => new Levenshtein.Sequence(tokens, levenshteinAlphabet));\n return descriptor;\n }\n constructor() {\n this._sequences = [];\n }\n /**\n * Create the tokenization pyramid for the provided Trajectory according to the given\n * Vector3Alphabet.\n * @param trajectory Trajectory to be tokenized\n * @param alphabet Vector3Alphabet containing tokens\n * @param targetResolution finest resolution of descriptor\n * @returns tokenization pyramid for Trajectory\n */\n static _GetTokenizationPyramid(trajectory, alphabet, targetResolution = TrajectoryDescriptor._FINEST_DESCRIPTOR_RESOLUTION) {\n const pyramid = [];\n for (let res = targetResolution; res > 4; res = Math.floor(res / 2)) {\n pyramid.push(trajectory.resampleAtTargetResolution(res).tokenize(alphabet.chars));\n }\n return pyramid;\n }\n /**\n * Calculate a distance metric between this TrajectoryDescriptor and another. This is\n * essentially a similarity score and does not directly represent Euclidean distance,\n * edit distance, or any other formal distance metric.\n * @param other TrajectoryDescriptor from which to determine distance\n * @returns distance, a nonnegative similarity score where larger values indicate dissimilarity\n */\n distance(other) {\n let totalDistance = 0;\n let weight;\n for (let idx = 0; idx < this._sequences.length; ++idx) {\n weight = Math.pow(2, idx);\n totalDistance += weight * this._sequences[idx].distance(other._sequences[idx]);\n }\n return totalDistance;\n }\n}\nTrajectoryDescriptor._FINEST_DESCRIPTOR_RESOLUTION = 32;\n/**\n * A set of TrajectoryDescriptors defined to be \"the same.\" This is essentially a helper\n * class to facilitate methods of Trajectory clustering.\n */\nclass TrajectoryClass {\n /**\n * Serialize to JSON.\n * @returns JSON serialization\n */\n serialize() {\n const jsonObject = {};\n jsonObject.descriptors = this._descriptors.map((desc) => desc.serialize());\n jsonObject.centroidIdx = this._centroidIdx;\n jsonObject.averageDistance = this._averageDistance;\n return JSON.stringify(jsonObject);\n }\n /**\n * Deserialize from JSON string and Alphabet. This should be the same Alphabet\n * from which the descriptors were originally created, which must be serialized and\n * deserialized independently so that it can be passed in here.\n * @param json JSON string representation\n * @param alphabet Alphabet from which TrajectoryDescriptors were originally created\n * @returns deserialized TrajectoryDescriptor\n */\n static Deserialize(json, alphabet) {\n const jsonObject = JSON.parse(json);\n const described = new TrajectoryClass();\n described._descriptors = jsonObject.descriptors.map((s) => TrajectoryDescriptor.Deserialize(s, alphabet));\n described._centroidIdx = jsonObject.centroidIdx;\n described._averageDistance = jsonObject.averageDistance;\n return described;\n }\n /**\n * Create a new DescribedTrajectory.\n * @param descriptors currently-known TrajectoryDescriptors, if any\n */\n constructor(descriptors = []) {\n this._descriptors = descriptors;\n this._centroidIdx = -1;\n this._averageDistance = 0;\n this._refreshDescription();\n }\n /**\n * Add a new TrajectoryDescriptor to the list of descriptors known to describe\n * this same DescribedTrajectory.\n * @param descriptor descriptor to be added\n */\n add(descriptor) {\n this._descriptors.push(descriptor);\n this._refreshDescription();\n }\n /**\n * Compute the cost, which is inversely related to the likelihood that the provided\n * TrajectoryDescriptor describes a Trajectory that is considered to be the same as\n * the class represented by this DescribedTrajectory.\n * @param descriptor the descriptor to be costed\n * @returns cost of the match, which is a nonnegative similarity metric where larger values indicate dissimilarity\n */\n getMatchCost(descriptor) {\n return descriptor.distance(this._descriptors[this._centroidIdx]) / this._averageDistance;\n }\n /**\n * Compute the minimum distance between the queried TrajectoryDescriptor and a\n * descriptor which is a member of this collection. This is an alternative way of\n * conceptualizing match cost from getMatchCost(), and it serves a different function.\n * @param descriptor the descriptor to find the minimum distance to\n * @returns minimum descriptor distance to a member descriptor of this DescribedTrajectory\n */\n getMatchMinimumDistance(descriptor) {\n return Math.min(...this._descriptors.map((desc) => desc.distance(descriptor)));\n }\n /**\n * Refreshes the internal representation of this DescribedTrajectory.\n */\n _refreshDescription() {\n this._centroidIdx = -1;\n let sum;\n const distances = this._descriptors.map((a) => {\n sum = 0;\n this._descriptors.forEach((b) => {\n sum += a.distance(b);\n });\n return sum;\n });\n for (let idx = 0; idx < distances.length; ++idx) {\n if (this._centroidIdx < 0 || distances[idx] < distances[this._centroidIdx]) {\n this._centroidIdx = idx;\n }\n }\n this._averageDistance = 0;\n this._descriptors.forEach((desc) => {\n this._averageDistance += desc.distance(this._descriptors[this._centroidIdx]);\n });\n if (this._descriptors.length > 0) {\n this._averageDistance = Math.max(this._averageDistance / this._descriptors.length, TrajectoryClass._MIN_AVERAGE_DISTANCE);\n }\n }\n}\nTrajectoryClass._MIN_AVERAGE_DISTANCE = 1;\n/**\n * Class representing a set of known, named trajectories to which Trajectories can be\n * added and using which Trajectories can be recognized.\n */\nexport class TrajectoryClassifier {\n /**\n * Serialize to JSON.\n * @returns JSON serialization\n */\n serialize() {\n const jsonObject = {};\n jsonObject.maximumAllowableMatchCost = this._maximumAllowableMatchCost;\n jsonObject.vector3Alphabet = this._vector3Alphabet.serialize();\n jsonObject.levenshteinAlphabet = this._levenshteinAlphabet.serialize();\n jsonObject.nameToDescribedTrajectory = [];\n this._nameToDescribedTrajectory.forEach((described, name) => {\n jsonObject.nameToDescribedTrajectory.push(name);\n jsonObject.nameToDescribedTrajectory.push(described.serialize());\n });\n return JSON.stringify(jsonObject);\n }\n /**\n * Deserialize from JSON.\n * @param json JSON serialization\n * @returns deserialized TrajectorySet\n */\n static Deserialize(json) {\n const jsonObject = JSON.parse(json);\n const classifier = new TrajectoryClassifier();\n classifier._maximumAllowableMatchCost = jsonObject.maximumAllowableMatchCost;\n classifier._vector3Alphabet = Vector3Alphabet.Deserialize(jsonObject.vector3Alphabet);\n classifier._levenshteinAlphabet = Levenshtein.Alphabet.Deserialize(jsonObject.levenshteinAlphabet);\n for (let idx = 0; idx < jsonObject.nameToDescribedTrajectory.length; idx += 2) {\n classifier._nameToDescribedTrajectory.set(jsonObject.nameToDescribedTrajectory[idx], TrajectoryClass.Deserialize(jsonObject.nameToDescribedTrajectory[idx + 1], classifier._levenshteinAlphabet));\n }\n return classifier;\n }\n /**\n * Initialize a new empty TrajectorySet with auto-generated Alphabets.\n * VERY naive, need to be generating these things from known\n * sets. Better version later, probably eliminating this one.\n * @returns auto-generated TrajectorySet\n */\n static Generate() {\n const vecs = Vector3Alphabet.Generate(64, 256, 0.1, 0.001, [Vector3.Forward()]);\n const charIdxs = new Array(vecs.chars.length);\n for (let idx = 0; idx < charIdxs.length; ++idx) {\n charIdxs[idx] = idx;\n }\n const alphabet = new Levenshtein.Alphabet(charIdxs, (idx) => (idx === 0 ? 0 : 1), (idx) => (idx === 0 ? 0 : 1), (a, b) => Math.min(1 - Vector3.Dot(vecs.chars[a], vecs.chars[b]), 1));\n const trajectorySet = new TrajectoryClassifier();\n trajectorySet._vector3Alphabet = vecs;\n trajectorySet._levenshteinAlphabet = alphabet;\n return trajectorySet;\n }\n constructor() {\n this._maximumAllowableMatchCost = 4;\n this._nameToDescribedTrajectory = new Map();\n }\n /**\n * Add a new Trajectory to the set with a given name.\n * @param trajectory new Trajectory to be added\n * @param classification name to which to add the Trajectory\n */\n addTrajectoryToClassification(trajectory, classification) {\n if (!this._nameToDescribedTrajectory.has(classification)) {\n this._nameToDescribedTrajectory.set(classification, new TrajectoryClass());\n }\n this._nameToDescribedTrajectory.get(classification).add(TrajectoryDescriptor.CreateFromTrajectory(trajectory, this._vector3Alphabet, this._levenshteinAlphabet));\n }\n /**\n * Remove a known named trajectory and all Trajectories associated with it.\n * @param classification name to remove\n * @returns whether anything was removed\n */\n deleteClassification(classification) {\n return this._nameToDescribedTrajectory.delete(classification);\n }\n /**\n * Attempt to recognize a Trajectory from among all the classifications\n * already known to the classifier.\n * @param trajectory Trajectory to be recognized\n * @returns classification of Trajectory if recognized, null otherwise\n */\n classifyTrajectory(trajectory) {\n const descriptor = TrajectoryDescriptor.CreateFromTrajectory(trajectory, this._vector3Alphabet, this._levenshteinAlphabet);\n const allowableMatches = [];\n this._nameToDescribedTrajectory.forEach((trajectoryClass, classification) => {\n if (trajectoryClass.getMatchCost(descriptor) < this._maximumAllowableMatchCost) {\n allowableMatches.push(classification);\n }\n });\n if (allowableMatches.length === 0) {\n return null;\n }\n let bestIdx = 0;\n let bestMatch = this._nameToDescribedTrajectory.get(allowableMatches[bestIdx]).getMatchMinimumDistance(descriptor);\n let match;\n for (let idx = 0; idx < allowableMatches.length; ++idx) {\n match = this._nameToDescribedTrajectory.get(allowableMatches[idx]).getMatchMinimumDistance(descriptor);\n if (match < bestMatch) {\n bestMatch = match;\n bestIdx = idx;\n }\n }\n return allowableMatches[bestIdx];\n }\n}\n//# sourceMappingURL=trajectoryClassifier.js.map","import { Logger } from \"./logger.js\";\nimport { SceneSerializer } from \"./sceneSerializer.js\";\n/**\n * Class used to connect with the reflector zone of the sandbox via the reflector bridge\n * @since 5.0.0\n */\nexport class Reflector {\n /**\n * Constructs a reflector object.\n * @param scene The scene to use\n * @param hostname The hostname of the reflector bridge\n * @param port The port of the reflector bridge\n */\n constructor(scene, hostname, port) {\n this._scene = scene;\n Logger.Log(`[Reflector] Connecting to ws://${hostname}:${port}`);\n this._webSocket = new WebSocket(`ws://${hostname}:${port}`);\n this._webSocket.onmessage = (event) => {\n const message = event.data;\n if (message.startsWith(Reflector._SERVER_PREFIX)) {\n const serverMessage = message.substr(Reflector._SERVER_PREFIX.length);\n Logger.Log(`[Reflector] Received server message: ${serverMessage.substr(0, 64)}`);\n this._handleServerMessage(serverMessage);\n return;\n }\n else {\n Logger.Log(`[Reflector] Received client message: ${message.substr(0, 64)}`);\n this._handleClientMessage();\n }\n };\n this._webSocket.onclose = (event) => {\n Logger.Log(`[Reflector] Disconnected ${event.code} ${event.reason}`);\n };\n }\n /**\n * Closes the reflector connection\n */\n close() {\n this._webSocket.close();\n }\n _handleServerMessage(message) {\n switch (message) {\n case \"connected\": {\n SceneSerializer.SerializeAsync(this._scene).then((serialized) => {\n this._webSocket.send(`load|${JSON.stringify(serialized)}`);\n });\n break;\n }\n }\n }\n _handleClientMessage() {\n // do nothing\n }\n}\nReflector._SERVER_PREFIX = \"$$\";\n//# sourceMappingURL=reflector.js.map","import { Observable } from \"./observable.js\";\n/**\n * A wrapper for the experimental pressure api which allows a callback to be called whenever certain thresholds are met.\n */\nexport class PressureObserverWrapper {\n /**\n * A pressure observer will call this callback, whenever these thresholds are met.\n * @param options An object containing the thresholds used to decide what value to to return for each update property (average of start and end of a threshold boundary).\n */\n constructor(options) {\n this._observer = null;\n this._currentState = [];\n /**\n * An event triggered when the cpu usage/speed meets certain thresholds.\n * Note: pressure is an experimental API.\n */\n this.onPressureChanged = new Observable();\n if (PressureObserverWrapper.IsAvailable) {\n this._observer = new PressureObserver((update) => {\n this._currentState = update;\n this.onPressureChanged.notifyObservers(update);\n }, options);\n }\n }\n /**\n * Returns true if PressureObserver is available for use, false otherwise.\n */\n static get IsAvailable() {\n return typeof PressureObserver !== \"undefined\" && PressureObserver.supportedSources.includes(\"cpu\");\n }\n /**\n * Method that must be called to begin observing changes, and triggering callbacks.\n * @param source defines the source to observe\n */\n observe(source) {\n var _a;\n try {\n (_a = this._observer) === null || _a === void 0 ? void 0 : _a.observe(source);\n this.onPressureChanged.notifyObservers(this._currentState);\n }\n catch (_b) {\n // Ignore error\n }\n }\n /**\n * Method that must be called to stop observing changes and triggering callbacks (cleanup function).\n * @param source defines the source to unobserve\n */\n unobserve(source) {\n var _a;\n try {\n (_a = this._observer) === null || _a === void 0 ? void 0 : _a.unobserve(source);\n }\n catch (_b) {\n // Ignore error\n }\n }\n /**\n * Release the associated resources.\n */\n dispose() {\n var _a;\n (_a = this._observer) === null || _a === void 0 ? void 0 : _a.disconnect();\n this._observer = null;\n this.onPressureChanged.clear();\n }\n}\n//# sourceMappingURL=pressureObserverWrapper.js.map","const growthFactor = 1.5;\n/**\n * A class acting as a dynamic float32array used in the performance viewer\n */\nexport class DynamicFloat32Array {\n /**\n * Creates a new DynamicFloat32Array with the desired item capacity.\n * @param itemCapacity The initial item capacity you would like to set for the array.\n */\n constructor(itemCapacity) {\n this._view = new Float32Array(itemCapacity);\n this._itemLength = 0;\n }\n /**\n * The number of items currently in the array.\n */\n get itemLength() {\n return this._itemLength;\n }\n /**\n * Gets value at index, NaN if no such index exists.\n * @param index the index to get the value at.\n * @returns the value at the index provided.\n */\n at(index) {\n if (index < 0 || index >= this._itemLength) {\n return NaN;\n }\n return this._view[index];\n }\n /**\n * Gets a view of the original array from start to end (exclusive of end).\n * @param start starting index.\n * @param end ending index.\n * @returns a subarray of the original array.\n */\n subarray(start, end) {\n if (start >= end || start < 0) {\n return new Float32Array(0);\n }\n if (end > this._itemLength) {\n end = this._itemLength;\n }\n return this._view.subarray(start, end);\n }\n /**\n * Pushes items to the end of the array.\n * @param item The item to push into the array.\n */\n push(item) {\n this._view[this._itemLength] = item;\n this._itemLength++;\n if (this._itemLength >= this._view.length) {\n this._growArray();\n }\n }\n /**\n * Grows the array by the growth factor when necessary.\n */\n _growArray() {\n const newCapacity = Math.floor(this._view.length * growthFactor);\n const view = new Float32Array(newCapacity);\n view.set(this._view);\n this._view = view;\n }\n}\n//# sourceMappingURL=dynamicFloat32Array.js.map","import { EventState, Observable } from \"../observable.js\";\nimport { PrecisionDate } from \"../precisionDate.js\";\nimport { Tools } from \"../tools.js\";\nimport { DynamicFloat32Array } from \"./dynamicFloat32Array.js\";\n// the initial size of our array, should be a multiple of two!\nconst InitialArraySize = 1800;\n// three octets in a hexcode. #[AA][BB][CC], i.e. 24 bits of data.\nconst NumberOfBitsInHexcode = 24;\n// Allows single numeral hex numbers to be appended by a 0.\nconst HexPadding = \"0\";\n// header for the timestamp column\nconst TimestampColHeader = \"timestamp\";\n// header for the numPoints column\nconst NumPointsColHeader = \"numPoints\";\n// regex to capture all carriage returns in the string.\nconst CarriageReturnRegex = /\\r/g;\n// string to use as separator when exporting extra information along with the dataset id\nconst ExportedDataSeparator = \"@\";\n/**\n * The collector class handles the collection and storage of data into the appropriate array.\n * The collector also handles notifying any observers of any updates.\n */\nexport class PerformanceViewerCollector {\n /**\n * The offset for when actual data values start appearing inside a slice.\n */\n static get SliceDataOffset() {\n return 2;\n }\n /**\n * The offset for the value of the number of points inside a slice.\n */\n static get NumberOfPointsOffset() {\n return 1;\n }\n /**\n * Handles the creation of a performance viewer collector.\n * @param _scene the scene to collect on.\n * @param _enabledStrategyCallbacks the list of data to collect with callbacks for initialization purposes.\n */\n constructor(_scene, _enabledStrategyCallbacks) {\n this._scene = _scene;\n /**\n * Collects data for every dataset by using the appropriate strategy. This is called every frame.\n * This method will then notify all observers with the latest slice.\n */\n this._collectDataAtFrame = () => {\n const timestamp = PrecisionDate.Now - this._startingTimestamp;\n const numPoints = this.datasets.ids.length;\n // add the starting index for the slice\n const numberOfIndices = this.datasets.startingIndices.itemLength;\n let startingIndex = 0;\n if (numberOfIndices > 0) {\n const previousStartingIndex = this.datasets.startingIndices.at(numberOfIndices - 1);\n startingIndex =\n previousStartingIndex + this.datasets.data.at(previousStartingIndex + PerformanceViewerCollector.NumberOfPointsOffset) + PerformanceViewerCollector.SliceDataOffset;\n }\n this.datasets.startingIndices.push(startingIndex);\n // add the first 2 items in our slice.\n this.datasets.data.push(timestamp);\n this.datasets.data.push(numPoints);\n // add the values inside the slice.\n this.datasets.ids.forEach((id) => {\n const strategy = this._strategies.get(id);\n if (!strategy) {\n return;\n }\n this.datasets.data.push(strategy.getData());\n });\n if (this.datasetObservable.hasObservers()) {\n const slice = [timestamp, numPoints];\n for (let i = 0; i < numPoints; i++) {\n slice.push(this.datasets.data.at(startingIndex + PerformanceViewerCollector.SliceDataOffset + i));\n }\n this.datasetObservable.notifyObservers(slice);\n }\n };\n this.datasets = {\n ids: [],\n data: new DynamicFloat32Array(InitialArraySize),\n startingIndices: new DynamicFloat32Array(InitialArraySize),\n };\n this._strategies = new Map();\n this._datasetMeta = new Map();\n this._eventRestoreSet = new Set();\n this._customEventObservable = new Observable();\n this.datasetObservable = new Observable();\n this.metadataObservable = new Observable((observer) => observer.callback(this._datasetMeta, new EventState(0)));\n if (_enabledStrategyCallbacks) {\n this.addCollectionStrategies(..._enabledStrategyCallbacks);\n }\n }\n /**\n * Registers a custom string event which will be callable via sendEvent. This method returns an event object which will contain the id of the event.\n * The user can set a value optionally, which will be used in the sendEvent method. If the value is set, we will record this value at the end of each frame,\n * if not we will increment our counter and record the value of the counter at the end of each frame. The value recorded is 0 if no sendEvent method is called, within a frame.\n * @param name The name of the event to register\n * @param forceUpdate if the code should force add an event, and replace the last one.\n * @param category the category for that event\n * @returns The event registered, used in sendEvent\n */\n registerEvent(name, forceUpdate, category) {\n var _a;\n if (this._strategies.has(name) && !forceUpdate) {\n return;\n }\n if (this._strategies.has(name) && forceUpdate) {\n (_a = this._strategies.get(name)) === null || _a === void 0 ? void 0 : _a.dispose();\n this._strategies.delete(name);\n }\n const strategy = (scene) => {\n let counter = 0;\n let value = 0;\n const afterRenderObserver = scene.onAfterRenderObservable.add(() => {\n value = counter;\n counter = 0;\n });\n const stringObserver = this._customEventObservable.add((eventVal) => {\n if (name !== eventVal.name) {\n return;\n }\n if (eventVal.value !== undefined) {\n counter = eventVal.value;\n }\n else {\n counter++;\n }\n });\n return {\n id: name,\n getData: () => value,\n dispose: () => {\n scene.onAfterRenderObservable.remove(afterRenderObserver);\n this._customEventObservable.remove(stringObserver);\n },\n };\n };\n const event = {\n name,\n };\n this._eventRestoreSet.add(name);\n this.addCollectionStrategies({ strategyCallback: strategy, category });\n return event;\n }\n /**\n * Lets the perf collector handle an event, occurences or event value depending on if the event.value params is set.\n * @param event the event to handle an occurence for\n */\n sendEvent(event) {\n this._customEventObservable.notifyObservers(event);\n }\n /**\n * This event restores all custom string events if necessary.\n */\n _restoreStringEvents() {\n if (this._eventRestoreSet.size !== this._customEventObservable.observers.length) {\n this._eventRestoreSet.forEach((event) => {\n this.registerEvent(event, true);\n });\n }\n }\n /**\n * This method adds additional collection strategies for data collection purposes.\n * @param strategyCallbacks the list of data to collect with callbacks.\n */\n addCollectionStrategies(...strategyCallbacks) {\n // eslint-disable-next-line prefer-const\n for (let { strategyCallback, category, hidden } of strategyCallbacks) {\n const strategy = strategyCallback(this._scene);\n if (this._strategies.has(strategy.id)) {\n strategy.dispose();\n continue;\n }\n this.datasets.ids.push(strategy.id);\n if (category) {\n category = category.replace(new RegExp(ExportedDataSeparator, \"g\"), \"\");\n }\n this._datasetMeta.set(strategy.id, {\n color: this._getHexColorFromId(strategy.id),\n category,\n hidden,\n });\n this._strategies.set(strategy.id, strategy);\n }\n this.metadataObservable.notifyObservers(this._datasetMeta);\n }\n /**\n * Gets a 6 character hexcode representing the colour from a passed in string.\n * @param id the string to get a hex code for.\n * @returns a hexcode hashed from the id.\n */\n _getHexColorFromId(id) {\n // this first bit is just a known way of hashing a string.\n let hash = 0;\n for (let i = 0; i < id.length; i++) {\n // (hash << 5) - hash is the same as hash * 31\n hash = id.charCodeAt(i) + ((hash << 5) - hash);\n }\n // then we build the string octet by octet.\n let hex = \"#\";\n for (let i = 0; i < NumberOfBitsInHexcode; i += 8) {\n const octet = (hash >> i) & 0xff;\n hex += (HexPadding + octet.toString(16)).substr(-2);\n }\n return hex;\n }\n /**\n * Collects and then sends the latest slice to any observers by using the appropriate strategy when the user wants.\n * The slice will be of the form [timestamp, numberOfPoints, value1, value2...]\n * This method does not add onto the collected data accessible via the datasets variable.\n */\n getCurrentSlice() {\n const timestamp = PrecisionDate.Now - this._startingTimestamp;\n const numPoints = this.datasets.ids.length;\n const slice = [timestamp, numPoints];\n // add the values inside the slice.\n this.datasets.ids.forEach((id) => {\n const strategy = this._strategies.get(id);\n if (!strategy) {\n return;\n }\n if (this.datasetObservable.hasObservers()) {\n slice.push(strategy.getData());\n }\n });\n if (this.datasetObservable.hasObservers()) {\n this.datasetObservable.notifyObservers(slice);\n }\n }\n /**\n * Updates a property for a dataset's metadata with the value provided.\n * @param id the id of the dataset which needs its metadata updated.\n * @param prop the property to update.\n * @param value the value to update the property with.\n */\n updateMetadata(id, prop, value) {\n const meta = this._datasetMeta.get(id);\n if (!meta) {\n return;\n }\n meta[prop] = value;\n this.metadataObservable.notifyObservers(this._datasetMeta);\n }\n /**\n * Completely clear, data, ids, and strategies saved to this performance collector.\n * @param preserveStringEventsRestore if it should preserve the string events, by default will clear string events registered when called.\n */\n clear(preserveStringEventsRestore) {\n this.datasets.data = new DynamicFloat32Array(InitialArraySize);\n this.datasets.ids.length = 0;\n this.datasets.startingIndices = new DynamicFloat32Array(InitialArraySize);\n this._datasetMeta.clear();\n this._strategies.forEach((strategy) => strategy.dispose());\n this._strategies.clear();\n if (!preserveStringEventsRestore) {\n this._eventRestoreSet.clear();\n }\n this._hasLoadedData = false;\n }\n /**\n * Accessor which lets the caller know if the performance collector has data loaded from a file or not!\n * Call clear() to reset this value.\n * @returns true if the data is loaded from a file, false otherwise.\n */\n get hasLoadedData() {\n return this._hasLoadedData;\n }\n /**\n * Given a string containing file data, this function parses the file data into the datasets object.\n * It returns a boolean to indicate if this object was successfully loaded with the data.\n * @param data string content representing the file data.\n * @param keepDatasetMeta if it should use reuse the existing dataset metadata\n * @returns true if the data was successfully loaded, false otherwise.\n */\n loadFromFileData(data, keepDatasetMeta) {\n const lines = data\n .replace(CarriageReturnRegex, \"\")\n .split(\"\\n\")\n .map((line) => line.split(\",\").filter((s) => s.length > 0))\n .filter((line) => line.length > 0);\n const timestampIndex = 0;\n const numPointsIndex = PerformanceViewerCollector.NumberOfPointsOffset;\n if (lines.length < 2) {\n return false;\n }\n const parsedDatasets = {\n ids: [],\n data: new DynamicFloat32Array(InitialArraySize),\n startingIndices: new DynamicFloat32Array(InitialArraySize),\n };\n // parse first line separately to populate ids!\n const [firstLine, ...dataLines] = lines;\n // make sure we have the correct beginning headers\n if (firstLine.length < 2 || firstLine[timestampIndex] !== TimestampColHeader || firstLine[numPointsIndex] !== NumPointsColHeader) {\n return false;\n }\n const idCategoryMap = new Map();\n // populate the ids.\n for (let i = PerformanceViewerCollector.SliceDataOffset; i < firstLine.length; i++) {\n const [id, category] = firstLine[i].split(ExportedDataSeparator);\n parsedDatasets.ids.push(id);\n idCategoryMap.set(id, category);\n }\n let startingIndex = 0;\n for (const line of dataLines) {\n if (line.length < 2) {\n return false;\n }\n const timestamp = parseFloat(line[timestampIndex]);\n const numPoints = parseInt(line[numPointsIndex]);\n if (isNaN(numPoints) || isNaN(timestamp)) {\n return false;\n }\n parsedDatasets.data.push(timestamp);\n parsedDatasets.data.push(numPoints);\n if (numPoints + PerformanceViewerCollector.SliceDataOffset !== line.length) {\n return false;\n }\n for (let i = PerformanceViewerCollector.SliceDataOffset; i < line.length; i++) {\n const val = parseFloat(line[i]);\n if (isNaN(val)) {\n return false;\n }\n parsedDatasets.data.push(val);\n }\n parsedDatasets.startingIndices.push(startingIndex);\n startingIndex += line.length;\n }\n this.datasets.ids = parsedDatasets.ids;\n this.datasets.data = parsedDatasets.data;\n this.datasets.startingIndices = parsedDatasets.startingIndices;\n if (!keepDatasetMeta) {\n this._datasetMeta.clear();\n }\n this._strategies.forEach((strategy) => strategy.dispose());\n this._strategies.clear();\n // populate metadata.\n if (!keepDatasetMeta) {\n for (const id of this.datasets.ids) {\n const category = idCategoryMap.get(id);\n this._datasetMeta.set(id, { category, color: this._getHexColorFromId(id) });\n }\n }\n this.metadataObservable.notifyObservers(this._datasetMeta);\n this._hasLoadedData = true;\n return true;\n }\n /**\n * Exports the datasets inside of the collector to a csv.\n */\n exportDataToCsv() {\n let csvContent = \"\";\n // create the header line.\n csvContent += `${TimestampColHeader},${NumPointsColHeader}`;\n for (let i = 0; i < this.datasets.ids.length; i++) {\n csvContent += `,${this.datasets.ids[i]}`;\n if (this._datasetMeta) {\n const meta = this._datasetMeta.get(this.datasets.ids[i]);\n if (meta === null || meta === void 0 ? void 0 : meta.category) {\n csvContent += `${ExportedDataSeparator}${meta.category}`;\n }\n }\n }\n csvContent += \"\\n\";\n // create the data lines\n for (let i = 0; i < this.datasets.startingIndices.itemLength; i++) {\n const startingIndex = this.datasets.startingIndices.at(i);\n const timestamp = this.datasets.data.at(startingIndex);\n const numPoints = this.datasets.data.at(startingIndex + PerformanceViewerCollector.NumberOfPointsOffset);\n csvContent += `${timestamp},${numPoints}`;\n for (let offset = 0; offset < numPoints; offset++) {\n csvContent += `,${this.datasets.data.at(startingIndex + PerformanceViewerCollector.SliceDataOffset + offset)}`;\n }\n // add extra commas.\n for (let diff = 0; diff < this.datasets.ids.length - numPoints; diff++) {\n csvContent += \",\";\n }\n csvContent += \"\\n\";\n }\n const fileName = `${new Date().toISOString()}-perfdata.csv`;\n Tools.Download(new Blob([csvContent], { type: \"text/csv\" }), fileName);\n }\n /**\n * Starts the realtime collection of data.\n * @param shouldPreserve optional boolean param, if set will preserve the dataset between calls of start.\n */\n start(shouldPreserve) {\n if (!shouldPreserve) {\n this.datasets.data = new DynamicFloat32Array(InitialArraySize);\n this.datasets.startingIndices = new DynamicFloat32Array(InitialArraySize);\n this._startingTimestamp = PrecisionDate.Now;\n }\n else if (this._startingTimestamp === undefined) {\n this._startingTimestamp = PrecisionDate.Now;\n }\n this._scene.onAfterRenderObservable.add(this._collectDataAtFrame);\n this._restoreStringEvents();\n this._isStarted = true;\n }\n /**\n * Stops the collection of data.\n */\n stop() {\n this._scene.onAfterRenderObservable.removeCallback(this._collectDataAtFrame);\n this._isStarted = false;\n }\n /**\n * Returns if the perf collector has been started or not.\n */\n get isStarted() {\n return this._isStarted;\n }\n /**\n * Disposes of the object\n */\n dispose() {\n this._scene.onAfterRenderObservable.removeCallback(this._collectDataAtFrame);\n this._datasetMeta.clear();\n this._strategies.forEach((strategy) => {\n strategy.dispose();\n });\n this.datasetObservable.clear();\n this.metadataObservable.clear();\n this._isStarted = false;\n this.datasets = null;\n }\n}\n//# sourceMappingURL=performanceViewerCollector.js.map","import { EngineInstrumentation } from \"../../Instrumentation/engineInstrumentation.js\";\nimport { PrecisionDate } from \"../precisionDate.js\";\nimport { SceneInstrumentation } from \"../../Instrumentation/sceneInstrumentation.js\";\nimport { PressureObserverWrapper } from \"../pressureObserverWrapper.js\";\n// Dispose which does nothing.\nconst defaultDisposeImpl = () => { };\n/**\n * Defines the predefined strategies used in the performance viewer.\n */\nexport class PerfCollectionStrategy {\n /**\n * Gets the initializer for the strategy used for collection of fps metrics\n * @returns the initializer for the fps strategy\n */\n static FpsStrategy() {\n return (scene) => {\n const engine = scene.getEngine();\n return {\n id: \"FPS\",\n getData: () => engine.getFps(),\n dispose: defaultDisposeImpl,\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of thermal utilization metrics.\n * Needs the experimental pressure API.\n * @returns the initializer for the thermal utilization strategy\n */\n static ThermalStrategy() {\n return this._PressureStrategy(\"Thermal utilization\", \"thermal\");\n }\n /**\n * Gets the initializer for the strategy used for collection of power supply utilization metrics.\n * Needs the experimental pressure API.\n * @returns the initializer for the power supply utilization strategy\n */\n static PowerSupplyStrategy() {\n return this._PressureStrategy(\"Power supply utilization\", \"power-supply\");\n }\n /**\n * Gets the initializer for the strategy used for collection of pressure metrics.\n * Needs the experimental pressure API.\n * @returns the initializer for the pressure strategy\n */\n static PressureStrategy() {\n return this._PressureStrategy(\"Pressure\");\n }\n static _PressureStrategy(name, factor = null) {\n return () => {\n let value = 0;\n const wrapper = new PressureObserverWrapper();\n wrapper.observe(\"cpu\");\n wrapper.onPressureChanged.add((update) => {\n for (const record of update) {\n if ((factor && record.factors.includes(factor)) || (!factor && record.factors.length === 0)) {\n // Let s consider each step being 25% of the total pressure.\n switch (record.state) {\n case \"nominal\":\n value = 0;\n break;\n case \"fair\":\n value = 0.25;\n break;\n case \"serious\":\n value = 0.5;\n break;\n case \"critical\":\n value = 1;\n break;\n }\n }\n }\n });\n return {\n id: name,\n getData: () => value,\n dispose: () => wrapper.dispose(),\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of total meshes metrics.\n * @returns the initializer for the total meshes strategy\n */\n static TotalMeshesStrategy() {\n return (scene) => {\n return {\n id: \"Total meshes\",\n getData: () => scene.meshes.length,\n dispose: defaultDisposeImpl,\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of active meshes metrics.\n * @returns the initializer for the active meshes strategy\n */\n static ActiveMeshesStrategy() {\n return (scene) => {\n return {\n id: \"Active meshes\",\n getData: () => scene.getActiveMeshes().length,\n dispose: defaultDisposeImpl,\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of active indices metrics.\n * @returns the initializer for the active indices strategy\n */\n static ActiveIndicesStrategy() {\n return (scene) => {\n return {\n id: \"Active indices\",\n getData: () => scene.getActiveIndices(),\n dispose: defaultDisposeImpl,\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of active faces metrics.\n * @returns the initializer for the active faces strategy\n */\n static ActiveFacesStrategy() {\n return (scene) => {\n return {\n id: \"Active faces\",\n getData: () => scene.getActiveIndices() / 3,\n dispose: defaultDisposeImpl,\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of active bones metrics.\n * @returns the initializer for the active bones strategy\n */\n static ActiveBonesStrategy() {\n return (scene) => {\n return {\n id: \"Active bones\",\n getData: () => scene.getActiveBones(),\n dispose: defaultDisposeImpl,\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of active particles metrics.\n * @returns the initializer for the active particles strategy\n */\n static ActiveParticlesStrategy() {\n return (scene) => {\n return {\n id: \"Active particles\",\n getData: () => scene.getActiveParticles(),\n dispose: defaultDisposeImpl,\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of draw calls metrics.\n * @returns the initializer for the draw calls strategy\n */\n static DrawCallsStrategy() {\n return (scene) => {\n let drawCalls = 0;\n const onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(() => {\n scene.getEngine()._drawCalls.fetchNewFrame();\n });\n const onAfterRenderObserver = scene.onAfterRenderObservable.add(() => {\n drawCalls = scene.getEngine()._drawCalls.current;\n });\n return {\n id: \"Draw calls\",\n getData: () => drawCalls,\n dispose: () => {\n scene.onBeforeAnimationsObservable.remove(onBeforeAnimationsObserver);\n scene.onAfterRenderObservable.remove(onAfterRenderObserver);\n },\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of total lights metrics.\n * @returns the initializer for the total lights strategy\n */\n static TotalLightsStrategy() {\n return (scene) => {\n return {\n id: \"Total lights\",\n getData: () => scene.lights.length,\n dispose: defaultDisposeImpl,\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of total vertices metrics.\n * @returns the initializer for the total vertices strategy\n */\n static TotalVerticesStrategy() {\n return (scene) => {\n return {\n id: \"Total vertices\",\n getData: () => scene.getTotalVertices(),\n dispose: defaultDisposeImpl,\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of total materials metrics.\n * @returns the initializer for the total materials strategy\n */\n static TotalMaterialsStrategy() {\n return (scene) => {\n return {\n id: \"Total materials\",\n getData: () => scene.materials.length,\n dispose: defaultDisposeImpl,\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of total textures metrics.\n * @returns the initializer for the total textures strategy\n */\n static TotalTexturesStrategy() {\n return (scene) => {\n return {\n id: \"Total textures\",\n getData: () => scene.textures.length,\n dispose: defaultDisposeImpl,\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of absolute fps metrics.\n * @returns the initializer for the absolute fps strategy\n */\n static AbsoluteFpsStrategy() {\n return (scene) => {\n const sceneInstrumentation = new SceneInstrumentation(scene);\n sceneInstrumentation.captureFrameTime = true;\n return {\n id: \"Absolute FPS\",\n getData: () => {\n return 1000.0 / sceneInstrumentation.frameTimeCounter.lastSecAverage;\n },\n dispose: defaultDisposeImpl,\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of meshes selection time metrics.\n * @returns the initializer for the meshes selection time strategy\n */\n static MeshesSelectionStrategy() {\n return (scene) => {\n let startTime = PrecisionDate.Now;\n let timeTaken = 0;\n const onBeforeActiveMeshesObserver = scene.onBeforeActiveMeshesEvaluationObservable.add(() => {\n startTime = PrecisionDate.Now;\n });\n const onAfterActiveMeshesObserver = scene.onAfterActiveMeshesEvaluationObservable.add(() => {\n timeTaken = PrecisionDate.Now - startTime;\n });\n return {\n id: \"Meshes Selection\",\n getData: () => timeTaken,\n dispose: () => {\n scene.onBeforeActiveMeshesEvaluationObservable.remove(onBeforeActiveMeshesObserver);\n scene.onAfterActiveMeshesEvaluationObservable.remove(onAfterActiveMeshesObserver);\n },\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of render targets time metrics.\n * @returns the initializer for the render targets time strategy\n */\n static RenderTargetsStrategy() {\n return (scene) => {\n let startTime = PrecisionDate.Now;\n let timeTaken = 0;\n const onBeforeRenderTargetsObserver = scene.onBeforeRenderTargetsRenderObservable.add(() => {\n startTime = PrecisionDate.Now;\n });\n const onAfterRenderTargetsObserver = scene.onAfterRenderTargetsRenderObservable.add(() => {\n timeTaken = PrecisionDate.Now - startTime;\n });\n return {\n id: \"Render Targets\",\n getData: () => timeTaken,\n dispose: () => {\n scene.onBeforeRenderTargetsRenderObservable.remove(onBeforeRenderTargetsObserver);\n scene.onAfterRenderTargetsRenderObservable.remove(onAfterRenderTargetsObserver);\n },\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of particles time metrics.\n * @returns the initializer for the particles time strategy\n */\n static ParticlesStrategy() {\n return (scene) => {\n let startTime = PrecisionDate.Now;\n let timeTaken = 0;\n const onBeforeParticlesObserver = scene.onBeforeParticlesRenderingObservable.add(() => {\n startTime = PrecisionDate.Now;\n });\n const onAfterParticlesObserver = scene.onAfterParticlesRenderingObservable.add(() => {\n timeTaken = PrecisionDate.Now - startTime;\n });\n return {\n id: \"Particles\",\n getData: () => timeTaken,\n dispose: () => {\n scene.onBeforeParticlesRenderingObservable.remove(onBeforeParticlesObserver);\n scene.onAfterParticlesRenderingObservable.remove(onAfterParticlesObserver);\n },\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of sprites time metrics.\n * @returns the initializer for the sprites time strategy\n */\n static SpritesStrategy() {\n return (scene) => {\n var _a, _b;\n let startTime = PrecisionDate.Now;\n let timeTaken = 0;\n const onBeforeSpritesObserver = (_a = scene.onBeforeSpritesRenderingObservable) === null || _a === void 0 ? void 0 : _a.add(() => {\n startTime = PrecisionDate.Now;\n });\n const onAfterSpritesObserver = (_b = scene.onAfterSpritesRenderingObservable) === null || _b === void 0 ? void 0 : _b.add(() => {\n timeTaken = PrecisionDate.Now - startTime;\n });\n return {\n id: \"Sprites\",\n getData: () => timeTaken,\n dispose: () => {\n var _a, _b;\n (_a = scene.onBeforeSpritesRenderingObservable) === null || _a === void 0 ? void 0 : _a.remove(onBeforeSpritesObserver);\n (_b = scene.onAfterSpritesRenderingObservable) === null || _b === void 0 ? void 0 : _b.remove(onAfterSpritesObserver);\n },\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of animations time metrics.\n * @returns the initializer for the animations time strategy\n */\n static AnimationsStrategy() {\n return (scene) => {\n let startTime = PrecisionDate.Now;\n let timeTaken = 0;\n const onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(() => {\n startTime = PrecisionDate.Now;\n });\n const onAfterAnimationsObserver = scene.onAfterAnimationsObservable.add(() => {\n timeTaken = PrecisionDate.Now - startTime;\n });\n return {\n id: \"Animations\",\n getData: () => timeTaken,\n dispose: () => {\n scene.onBeforeAnimationsObservable.remove(onBeforeAnimationsObserver);\n scene.onAfterAnimationsObservable.remove(onAfterAnimationsObserver);\n },\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of physics time metrics.\n * @returns the initializer for the physics time strategy\n */\n static PhysicsStrategy() {\n return (scene) => {\n var _a, _b;\n let startTime = PrecisionDate.Now;\n let timeTaken = 0;\n const onBeforePhysicsObserver = (_a = scene.onBeforePhysicsObservable) === null || _a === void 0 ? void 0 : _a.add(() => {\n startTime = PrecisionDate.Now;\n });\n const onAfterPhysicsObserver = (_b = scene.onAfterPhysicsObservable) === null || _b === void 0 ? void 0 : _b.add(() => {\n timeTaken = PrecisionDate.Now - startTime;\n });\n return {\n id: \"Physics\",\n getData: () => timeTaken,\n dispose: () => {\n var _a, _b;\n (_a = scene.onBeforePhysicsObservable) === null || _a === void 0 ? void 0 : _a.remove(onBeforePhysicsObserver);\n (_b = scene.onAfterPhysicsObservable) === null || _b === void 0 ? void 0 : _b.remove(onAfterPhysicsObserver);\n },\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of render time metrics.\n * @returns the initializer for the render time strategy\n */\n static RenderStrategy() {\n return (scene) => {\n let startTime = PrecisionDate.Now;\n let timeTaken = 0;\n const onBeforeDrawPhaseObserver = scene.onBeforeDrawPhaseObservable.add(() => {\n startTime = PrecisionDate.Now;\n });\n const onAfterDrawPhaseObserver = scene.onAfterDrawPhaseObservable.add(() => {\n timeTaken = PrecisionDate.Now - startTime;\n });\n return {\n id: \"Render\",\n getData: () => timeTaken,\n dispose: () => {\n scene.onBeforeDrawPhaseObservable.remove(onBeforeDrawPhaseObserver);\n scene.onAfterDrawPhaseObservable.remove(onAfterDrawPhaseObserver);\n },\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of total frame time metrics.\n * @returns the initializer for the total frame time strategy\n */\n static FrameTotalStrategy() {\n return (scene) => {\n let startTime = PrecisionDate.Now;\n let timeTaken = 0;\n const onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(() => {\n startTime = PrecisionDate.Now;\n });\n const onAfterRenderObserver = scene.onAfterRenderObservable.add(() => {\n timeTaken = PrecisionDate.Now - startTime;\n });\n return {\n id: \"Frame Total\",\n getData: () => timeTaken,\n dispose: () => {\n scene.onBeforeAnimationsObservable.remove(onBeforeAnimationsObserver);\n scene.onAfterRenderObservable.remove(onAfterRenderObserver);\n },\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of inter-frame time metrics.\n * @returns the initializer for the inter-frame time strategy\n */\n static InterFrameStrategy() {\n return (scene) => {\n let startTime = PrecisionDate.Now;\n let timeTaken = 0;\n const onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(() => {\n timeTaken = PrecisionDate.Now - startTime;\n });\n const onAfterRenderObserver = scene.onAfterRenderObservable.add(() => {\n startTime = PrecisionDate.Now;\n });\n return {\n id: \"Inter-frame\",\n getData: () => timeTaken,\n dispose: () => {\n scene.onBeforeAnimationsObservable.remove(onBeforeAnimationsObserver);\n scene.onAfterRenderObservable.remove(onAfterRenderObserver);\n },\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of gpu frame time metrics.\n * @returns the initializer for the gpu frame time strategy\n */\n static GpuFrameTimeStrategy() {\n return (scene) => {\n const engineInstrumentation = new EngineInstrumentation(scene.getEngine());\n engineInstrumentation.captureGPUFrameTime = true;\n return {\n id: \"GPU frame time\",\n getData: () => Math.max(engineInstrumentation.gpuFrameTimeCounter.current * 0.000001, 0),\n dispose: () => {\n engineInstrumentation.dispose();\n },\n };\n };\n }\n}\n//# sourceMappingURL=performanceViewerCollectionStrategies.js.map","import { Observable } from \"./observable.js\";\nimport { runCoroutineAsync, inlineScheduler } from \"./coroutine.js\";\nfunction CreateObservableScheduler(observable) {\n const coroutines = new Array();\n const onSteps = new Array();\n const onErrors = new Array();\n const observer = observable.add(() => {\n const count = coroutines.length;\n for (let i = 0; i < count; i++) {\n inlineScheduler(coroutines.shift(), onSteps.shift(), onErrors.shift());\n }\n });\n const scheduler = (coroutine, onStep, onError) => {\n coroutines.push(coroutine);\n onSteps.push(onStep);\n onErrors.push(onError);\n };\n return {\n scheduler: scheduler,\n dispose: () => {\n observable.remove(observer);\n },\n };\n}\nObservable.prototype.runCoroutineAsync = function (coroutine) {\n if (!this._coroutineScheduler) {\n const schedulerAndDispose = CreateObservableScheduler(this);\n this._coroutineScheduler = schedulerAndDispose.scheduler;\n this._coroutineSchedulerDispose = schedulerAndDispose.dispose;\n }\n return runCoroutineAsync(coroutine, this._coroutineScheduler);\n};\nObservable.prototype.cancelAllCoroutines = function () {\n if (this._coroutineSchedulerDispose) {\n this._coroutineSchedulerDispose();\n }\n this._coroutineScheduler = undefined;\n this._coroutineSchedulerDispose = undefined;\n};\n//# sourceMappingURL=observableCoroutine.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./andOrNotEvaluator.js\";\nexport * from \"./assetsManager.js\";\nexport * from \"./basis.js\";\nexport * from \"./dds.js\";\nexport * from \"./decorators.js\";\nexport * from \"./deferred.js\";\nexport * from \"./environmentTextureTools.js\";\nexport * from \"./meshExploder.js\";\nexport * from \"./filesInput.js\";\nexport * from \"./HighDynamicRange/index.js\";\nexport * from \"./khronosTextureContainer.js\";\nexport * from \"./observable.js\";\nexport * from \"./observable.extensions.js\";\nexport * from \"./performanceMonitor.js\";\nexport * from \"./sceneOptimizer.js\";\nexport * from \"./sceneSerializer.js\";\nexport * from \"./smartArray.js\";\nexport * from \"./stringDictionary.js\";\nexport * from \"./tags.js\";\nexport * from \"./textureTools.js\";\nexport * from \"./tga.js\";\nexport * from \"./tools.js\";\nexport * from \"./videoRecorder.js\";\nexport * from \"./virtualJoystick.js\";\nexport * from \"./workerPool.js\";\nexport * from \"./logger.js\";\nexport * from \"./typeStore.js\";\nexport * from \"./filesInputStore.js\";\nexport * from \"./deepCopier.js\";\nexport * from \"./pivotTools.js\";\nexport * from \"./precisionDate.js\";\nexport * from \"./screenshotTools.js\";\nexport * from \"./webRequest.js\";\nexport * from \"./iInspectable.js\";\nexport * from \"./brdfTextureTools.js\";\nexport * from \"./rgbdTextureTools.js\";\nexport * from \"./gradients.js\";\nexport * from \"./perfCounter.js\";\nexport * from \"./fileRequest.js\";\nexport * from \"./customAnimationFrameRequester.js\";\nexport * from \"./retryStrategy.js\";\nexport * from \"./interfaces/screenshotSize.js\";\nexport * from \"./interfaces/iPerfViewer.js\";\nexport * from \"./fileTools.js\";\nexport * from \"./stringTools.js\";\nexport * from \"./dataReader.js\";\nexport * from \"./minMaxReducer.js\";\nexport * from \"./depthReducer.js\";\nexport * from \"./dataStorage.js\";\nexport * from \"./sceneRecorder.js\";\nexport * from \"./khronosTextureContainer2.js\";\nexport * from \"./trajectoryClassifier.js\";\nexport * from \"./timer.js\";\nexport * from \"./copyTools.js\";\nexport * from \"./reflector.js\";\nexport * from \"./domManagement.js\";\nexport * from \"./pressureObserverWrapper.js\";\nexport * from \"./PerformanceViewer/index.js\";\nexport * from \"./coroutine.js\";\nexport * from \"./guid.js\";\nexport * from \"./error.js\";\n// eslint-disable-next-line import/export\nexport * from \"./observableCoroutine.js\";\nexport * from \"./copyTextureToTexture.js\";\nexport * from \"./dumpTools.js\";\nexport * from \"./greasedLineTools.js\";\n//# sourceMappingURL=index.js.map","import { WebXRFeaturesManager, WebXRFeatureName } from \"../webXRFeaturesManager.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { Vector3, Matrix } from \"../../Maths/math.vector.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * The currently-working hit-test module.\n * Hit test (or Ray-casting) is used to interact with the real world.\n * For further information read here - https://github.com/immersive-web/hit-test\n */\nexport class WebXRHitTestLegacy extends WebXRAbstractFeature {\n /**\n * Creates a new instance of the (legacy version) hit test feature\n * @param _xrSessionManager an instance of WebXRSessionManager\n * @param options options to use when constructing this feature\n */\n constructor(_xrSessionManager, \n /**\n * options to use when constructing this feature\n */\n options = {}) {\n super(_xrSessionManager);\n this.options = options;\n // in XR space z-forward is negative\n this._direction = new Vector3(0, 0, -1);\n this._mat = new Matrix();\n this._onSelectEnabled = false;\n this._origin = new Vector3(0, 0, 0);\n /**\n * Populated with the last native XR Hit Results\n */\n this.lastNativeXRHitResults = [];\n /**\n * Triggered when new babylon (transformed) hit test results are available\n */\n this.onHitTestResultObservable = new Observable();\n this._onHitTestResults = (xrResults) => {\n const mats = xrResults.map((result) => {\n const mat = Matrix.FromArray(result.hitMatrix);\n if (!this._xrSessionManager.scene.useRightHandedSystem) {\n mat.toggleModelMatrixHandInPlace();\n }\n // if (this.options.coordinatesSpace === Space.WORLD) {\n if (this.options.worldParentNode) {\n mat.multiplyToRef(this.options.worldParentNode.getWorldMatrix(), mat);\n }\n return {\n xrHitResult: result,\n transformationMatrix: mat,\n };\n });\n this.lastNativeXRHitResults = xrResults;\n this.onHitTestResultObservable.notifyObservers(mats);\n };\n // can be done using pointerdown event, and xrSessionManager.currentFrame\n this._onSelect = (event) => {\n if (!this._onSelectEnabled) {\n return;\n }\n WebXRHitTestLegacy.XRHitTestWithSelectEvent(event, this._xrSessionManager.referenceSpace);\n };\n this.xrNativeFeatureName = \"hit-test\";\n Tools.Warn(\"A newer version of this plugin is available\");\n }\n /**\n * execute a hit test with an XR Ray\n *\n * @param xrSession a native xrSession that will execute this hit test\n * @param xrRay the ray (position and direction) to use for ray-casting\n * @param referenceSpace native XR reference space to use for the hit-test\n * @param filter filter function that will filter the results\n * @returns a promise that resolves with an array of native XR hit result in xr coordinates system\n */\n static XRHitTestWithRay(xrSession, xrRay, referenceSpace, filter) {\n return xrSession.requestHitTest(xrRay, referenceSpace).then((results) => {\n const filterFunction = filter || ((result) => !!result.hitMatrix);\n return results.filter(filterFunction);\n });\n }\n /**\n * Execute a hit test on the current running session using a select event returned from a transient input (such as touch)\n * @param event the (select) event to use to select with\n * @param referenceSpace the reference space to use for this hit test\n * @returns a promise that resolves with an array of native XR hit result in xr coordinates system\n */\n static XRHitTestWithSelectEvent(event, referenceSpace) {\n const targetRayPose = event.frame.getPose(event.inputSource.targetRaySpace, referenceSpace);\n if (!targetRayPose) {\n return Promise.resolve([]);\n }\n const targetRay = new XRRay(targetRayPose.transform);\n return this.XRHitTestWithRay(event.frame.session, targetRay, referenceSpace);\n }\n /**\n * attach this feature\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n attach() {\n if (!super.attach()) {\n return false;\n }\n if (this.options.testOnPointerDownOnly) {\n this._xrSessionManager.session.addEventListener(\"select\", this._onSelect, false);\n }\n return true;\n }\n /**\n * detach this feature.\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n detach() {\n if (!super.detach()) {\n return false;\n }\n // disable select\n this._onSelectEnabled = false;\n this._xrSessionManager.session.removeEventListener(\"select\", this._onSelect);\n return true;\n }\n /**\n * Dispose this feature and all of the resources attached\n */\n dispose() {\n super.dispose();\n this.onHitTestResultObservable.clear();\n }\n _onXRFrame(frame) {\n // make sure we do nothing if (async) not attached\n if (!this.attached || this.options.testOnPointerDownOnly) {\n return;\n }\n const pose = frame.getViewerPose(this._xrSessionManager.referenceSpace);\n if (!pose) {\n return;\n }\n Matrix.FromArrayToRef(pose.transform.matrix, 0, this._mat);\n Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, this._mat, this._origin);\n Vector3.TransformCoordinatesFromFloatsToRef(0, 0, -1, this._mat, this._direction);\n this._direction.subtractInPlace(this._origin);\n this._direction.normalize();\n const ray = new XRRay({ x: this._origin.x, y: this._origin.y, z: this._origin.z, w: 0 }, { x: this._direction.x, y: this._direction.y, z: this._direction.z, w: 0 });\n WebXRHitTestLegacy.XRHitTestWithRay(this._xrSessionManager.session, ray, this._xrSessionManager.referenceSpace).then(this._onHitTestResults);\n }\n}\n/**\n * The module's name\n */\nWebXRHitTestLegacy.Name = WebXRFeatureName.HIT_TEST;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRHitTestLegacy.Version = 1;\n//register the plugin versions\nWebXRFeaturesManager.AddWebXRFeature(WebXRHitTestLegacy.Name, (xrSessionManager, options) => {\n return () => new WebXRHitTestLegacy(xrSessionManager, options);\n}, WebXRHitTestLegacy.Version, false);\n//# sourceMappingURL=WebXRHitTestLegacy.js.map","import { WebXRFeatureName, WebXRFeaturesManager } from \"../webXRFeaturesManager.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { Matrix, Vector3, Quaternion } from \"../../Maths/math.vector.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nlet anchorIdProvider = 0;\n/**\n * An implementation of the anchor system for WebXR.\n * For further information see https://github.com/immersive-web/anchors/\n */\nexport class WebXRAnchorSystem extends WebXRAbstractFeature {\n /**\n * Set the reference space to use for anchor creation, when not using a hit test.\n * Will default to the session's reference space if not defined\n */\n set referenceSpaceForFrameAnchors(referenceSpace) {\n this._referenceSpaceForFrameAnchors = referenceSpace;\n }\n /**\n * constructs a new anchor system\n * @param _xrSessionManager an instance of WebXRSessionManager\n * @param _options configuration object for this feature\n */\n constructor(_xrSessionManager, _options = {}) {\n super(_xrSessionManager);\n this._options = _options;\n this._lastFrameDetected = new Set();\n this._trackedAnchors = [];\n this._futureAnchors = [];\n /**\n * Observers registered here will be executed when a new anchor was added to the session\n */\n this.onAnchorAddedObservable = new Observable();\n /**\n * Observers registered here will be executed when an anchor was removed from the session\n */\n this.onAnchorRemovedObservable = new Observable();\n /**\n * Observers registered here will be executed when an existing anchor updates\n * This can execute N times every frame\n */\n this.onAnchorUpdatedObservable = new Observable();\n this._tmpVector = new Vector3();\n this._tmpQuaternion = new Quaternion();\n this.xrNativeFeatureName = \"anchors\";\n }\n _populateTmpTransformation(position, rotationQuaternion) {\n this._tmpVector.copyFrom(position);\n this._tmpQuaternion.copyFrom(rotationQuaternion);\n if (!this._xrSessionManager.scene.useRightHandedSystem) {\n this._tmpVector.z *= -1;\n this._tmpQuaternion.z *= -1;\n this._tmpQuaternion.w *= -1;\n }\n return {\n position: this._tmpVector,\n rotationQuaternion: this._tmpQuaternion,\n };\n }\n /**\n * Create a new anchor point using a hit test result at a specific point in the scene\n * An anchor is tracked only after it is added to the trackerAnchors in xrFrame. The promise returned here does not yet guaranty that.\n * Use onAnchorAddedObservable to get newly added anchors if you require tracking guaranty.\n *\n * @param hitTestResult The hit test result to use for this anchor creation\n * @param position an optional position offset for this anchor\n * @param rotationQuaternion an optional rotation offset for this anchor\n * @returns A promise that fulfills when babylon has created the corresponding WebXRAnchor object and tracking has begun\n */\n async addAnchorPointUsingHitTestResultAsync(hitTestResult, position = new Vector3(), rotationQuaternion = new Quaternion()) {\n // convert to XR space (right handed) if needed\n this._populateTmpTransformation(position, rotationQuaternion);\n // the matrix that we'll use\n const m = new XRRigidTransform({ x: this._tmpVector.x, y: this._tmpVector.y, z: this._tmpVector.z }, { x: this._tmpQuaternion.x, y: this._tmpQuaternion.y, z: this._tmpQuaternion.z, w: this._tmpQuaternion.w });\n if (!hitTestResult.xrHitResult.createAnchor) {\n this.detach();\n throw new Error(\"Anchors not enabled in this environment/browser\");\n }\n else {\n try {\n const nativeAnchor = await hitTestResult.xrHitResult.createAnchor(m);\n return new Promise((resolve, reject) => {\n this._futureAnchors.push({\n nativeAnchor,\n resolved: false,\n submitted: true,\n xrTransformation: m,\n resolve,\n reject,\n });\n });\n }\n catch (error) {\n throw new Error(error);\n }\n }\n }\n /**\n * Add a new anchor at a specific position and rotation\n * This function will add a new anchor per default in the next available frame. Unless forced, the createAnchor function\n * will be called in the next xrFrame loop to make sure that the anchor can be created correctly.\n * An anchor is tracked only after it is added to the trackerAnchors in xrFrame. The promise returned here does not yet guaranty that.\n * Use onAnchorAddedObservable to get newly added anchors if you require tracking guaranty.\n *\n * @param position the position in which to add an anchor\n * @param rotationQuaternion an optional rotation for the anchor transformation\n * @param forceCreateInCurrentFrame force the creation of this anchor in the current frame. Must be called inside xrFrame loop!\n * @returns A promise that fulfills when babylon has created the corresponding WebXRAnchor object and tracking has begun\n */\n async addAnchorAtPositionAndRotationAsync(position, rotationQuaternion = new Quaternion(), forceCreateInCurrentFrame = false) {\n // convert to XR space (right handed) if needed\n this._populateTmpTransformation(position, rotationQuaternion);\n // the matrix that we'll use\n const xrTransformation = new XRRigidTransform({ x: this._tmpVector.x, y: this._tmpVector.y, z: this._tmpVector.z }, { x: this._tmpQuaternion.x, y: this._tmpQuaternion.y, z: this._tmpQuaternion.z, w: this._tmpQuaternion.w });\n const xrAnchor = forceCreateInCurrentFrame && this.attached && this._xrSessionManager.currentFrame\n ? await this._createAnchorAtTransformation(xrTransformation, this._xrSessionManager.currentFrame)\n : undefined;\n // add the transformation to the future anchors list\n return new Promise((resolve, reject) => {\n this._futureAnchors.push({\n nativeAnchor: xrAnchor,\n resolved: false,\n submitted: false,\n xrTransformation,\n resolve,\n reject,\n });\n });\n }\n /**\n * Get the list of anchors currently being tracked by the system\n */\n get anchors() {\n return this._trackedAnchors;\n }\n /**\n * detach this feature.\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n detach() {\n if (!super.detach()) {\n return false;\n }\n if (!this._options.doNotRemoveAnchorsOnSessionEnded) {\n while (this._trackedAnchors.length) {\n const toRemove = this._trackedAnchors.pop();\n if (toRemove) {\n try {\n // try to natively remove it as well\n toRemove.remove();\n }\n catch (e) {\n // no-op\n }\n // as the xr frame loop is removed, we need to notify manually\n this.onAnchorRemovedObservable.notifyObservers(toRemove);\n }\n }\n }\n return true;\n }\n /**\n * Dispose this feature and all of the resources attached\n */\n dispose() {\n this._futureAnchors.length = 0;\n super.dispose();\n this.onAnchorAddedObservable.clear();\n this.onAnchorRemovedObservable.clear();\n this.onAnchorUpdatedObservable.clear();\n }\n _onXRFrame(frame) {\n if (!this.attached || !frame) {\n return;\n }\n const trackedAnchors = frame.trackedAnchors;\n if (trackedAnchors) {\n const toRemove = this._trackedAnchors\n .filter((anchor) => !trackedAnchors.has(anchor.xrAnchor))\n .map((anchor) => {\n const index = this._trackedAnchors.indexOf(anchor);\n return index;\n });\n let idxTracker = 0;\n toRemove.forEach((index) => {\n const anchor = this._trackedAnchors.splice(index - idxTracker, 1)[0];\n this.onAnchorRemovedObservable.notifyObservers(anchor);\n idxTracker++;\n });\n // now check for new ones\n trackedAnchors.forEach((xrAnchor) => {\n if (!this._lastFrameDetected.has(xrAnchor)) {\n const newAnchor = {\n id: anchorIdProvider++,\n xrAnchor: xrAnchor,\n remove: () => xrAnchor.delete(),\n };\n const anchor = this._updateAnchorWithXRFrame(xrAnchor, newAnchor, frame);\n this._trackedAnchors.push(anchor);\n this.onAnchorAddedObservable.notifyObservers(anchor);\n // search for the future anchor promise that matches this\n const results = this._futureAnchors.filter((futureAnchor) => futureAnchor.nativeAnchor === xrAnchor);\n const result = results[0];\n if (result) {\n result.resolve(anchor);\n result.resolved = true;\n }\n }\n else {\n const index = this._findIndexInAnchorArray(xrAnchor);\n const anchor = this._trackedAnchors[index];\n try {\n // anchors update every frame\n this._updateAnchorWithXRFrame(xrAnchor, anchor, frame);\n if (anchor.attachedNode) {\n anchor.attachedNode.rotationQuaternion = anchor.attachedNode.rotationQuaternion || new Quaternion();\n anchor.transformationMatrix.decompose(anchor.attachedNode.scaling, anchor.attachedNode.rotationQuaternion, anchor.attachedNode.position);\n }\n this.onAnchorUpdatedObservable.notifyObservers(anchor);\n }\n catch (e) {\n Tools.Warn(`Anchor could not be updated`);\n }\n }\n });\n this._lastFrameDetected = trackedAnchors;\n }\n // process future anchors\n this._futureAnchors.forEach((futureAnchor) => {\n if (!futureAnchor.resolved && !futureAnchor.submitted) {\n this._createAnchorAtTransformation(futureAnchor.xrTransformation, frame).then((nativeAnchor) => {\n futureAnchor.nativeAnchor = nativeAnchor;\n }, (error) => {\n futureAnchor.resolved = true;\n futureAnchor.reject(error);\n });\n futureAnchor.submitted = true;\n }\n });\n }\n /**\n * avoiding using Array.find for global support.\n * @param xrAnchor the plane to find in the array\n */\n _findIndexInAnchorArray(xrAnchor) {\n for (let i = 0; i < this._trackedAnchors.length; ++i) {\n if (this._trackedAnchors[i].xrAnchor === xrAnchor) {\n return i;\n }\n }\n return -1;\n }\n _updateAnchorWithXRFrame(xrAnchor, anchor, xrFrame) {\n // matrix\n const pose = xrFrame.getPose(xrAnchor.anchorSpace, this._xrSessionManager.referenceSpace);\n if (pose) {\n const mat = anchor.transformationMatrix || new Matrix();\n Matrix.FromArrayToRef(pose.transform.matrix, 0, mat);\n if (!this._xrSessionManager.scene.useRightHandedSystem) {\n mat.toggleModelMatrixHandInPlace();\n }\n anchor.transformationMatrix = mat;\n if (!this._options.worldParentNode) {\n // Logger.Warn(\"Please provide a world parent node to apply world transformation\");\n }\n else {\n mat.multiplyToRef(this._options.worldParentNode.getWorldMatrix(), mat);\n }\n }\n return anchor;\n }\n async _createAnchorAtTransformation(xrTransformation, xrFrame) {\n var _a;\n if (xrFrame.createAnchor) {\n try {\n return xrFrame.createAnchor(xrTransformation, (_a = this._referenceSpaceForFrameAnchors) !== null && _a !== void 0 ? _a : this._xrSessionManager.referenceSpace);\n }\n catch (error) {\n throw new Error(error);\n }\n }\n else {\n this.detach();\n throw new Error(\"Anchors are not enabled in your browser\");\n }\n }\n}\n/**\n * The module's name\n */\nWebXRAnchorSystem.Name = WebXRFeatureName.ANCHOR_SYSTEM;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRAnchorSystem.Version = 1;\n// register the plugin\nWebXRFeaturesManager.AddWebXRFeature(WebXRAnchorSystem.Name, (xrSessionManager, options) => {\n return () => new WebXRAnchorSystem(xrSessionManager, options);\n}, WebXRAnchorSystem.Version);\n//# sourceMappingURL=WebXRAnchorSystem.js.map","import { WebXRFeaturesManager, WebXRFeatureName } from \"../webXRFeaturesManager.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { Vector3, Matrix } from \"../../Maths/math.vector.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nlet planeIdProvider = 0;\n/**\n * The plane detector is used to detect planes in the real world when in AR\n * For more information see https://github.com/immersive-web/real-world-geometry/\n */\nexport class WebXRPlaneDetector extends WebXRAbstractFeature {\n /**\n * construct a new Plane Detector\n * @param _xrSessionManager an instance of xr Session manager\n * @param _options configuration to use when constructing this feature\n */\n constructor(_xrSessionManager, _options = {}) {\n super(_xrSessionManager);\n this._options = _options;\n this._detectedPlanes = [];\n this._enabled = false;\n this._lastFrameDetected = new Set();\n /**\n * Observers registered here will be executed when a new plane was added to the session\n */\n this.onPlaneAddedObservable = new Observable();\n /**\n * Observers registered here will be executed when a plane is no longer detected in the session\n */\n this.onPlaneRemovedObservable = new Observable();\n /**\n * Observers registered here will be executed when an existing plane updates (for example - expanded)\n * This can execute N times every frame\n */\n this.onPlaneUpdatedObservable = new Observable();\n this.xrNativeFeatureName = \"plane-detection\";\n if (this._xrSessionManager.session) {\n this._init();\n }\n else {\n this._xrSessionManager.onXRSessionInit.addOnce(() => {\n this._init();\n });\n }\n }\n /**\n * detach this feature.\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n detach() {\n if (!super.detach()) {\n return false;\n }\n if (!this._options.doNotRemovePlanesOnSessionEnded) {\n while (this._detectedPlanes.length) {\n const toRemove = this._detectedPlanes.pop();\n if (toRemove) {\n this.onPlaneRemovedObservable.notifyObservers(toRemove);\n }\n }\n }\n return true;\n }\n /**\n * Dispose this feature and all of the resources attached\n */\n dispose() {\n super.dispose();\n this.onPlaneAddedObservable.clear();\n this.onPlaneRemovedObservable.clear();\n this.onPlaneUpdatedObservable.clear();\n }\n /**\n * Check if the needed objects are defined.\n * This does not mean that the feature is enabled, but that the objects needed are well defined.\n */\n isCompatible() {\n return typeof XRPlane !== \"undefined\";\n }\n _onXRFrame(frame) {\n var _a;\n if (!this.attached || !this._enabled || !frame) {\n return;\n }\n const detectedPlanes = frame.detectedPlanes || ((_a = frame.worldInformation) === null || _a === void 0 ? void 0 : _a.detectedPlanes);\n if (detectedPlanes) {\n // remove all planes that are not currently detected in the frame\n for (let planeIdx = 0; planeIdx < this._detectedPlanes.length; planeIdx++) {\n const plane = this._detectedPlanes[planeIdx];\n if (!detectedPlanes.has(plane.xrPlane)) {\n this._detectedPlanes.splice(planeIdx--, 1);\n this.onPlaneRemovedObservable.notifyObservers(plane);\n }\n }\n // now check for new ones\n detectedPlanes.forEach((xrPlane) => {\n if (!this._lastFrameDetected.has(xrPlane)) {\n const newPlane = {\n id: planeIdProvider++,\n xrPlane: xrPlane,\n polygonDefinition: [],\n };\n const plane = this._updatePlaneWithXRPlane(xrPlane, newPlane, frame);\n this._detectedPlanes.push(plane);\n this.onPlaneAddedObservable.notifyObservers(plane);\n }\n else {\n // updated?\n if (xrPlane.lastChangedTime === this._xrSessionManager.currentTimestamp) {\n const index = this._findIndexInPlaneArray(xrPlane);\n const plane = this._detectedPlanes[index];\n this._updatePlaneWithXRPlane(xrPlane, plane, frame);\n this.onPlaneUpdatedObservable.notifyObservers(plane);\n }\n }\n });\n this._lastFrameDetected = detectedPlanes;\n }\n }\n _init() {\n const internalInit = () => {\n this._enabled = true;\n if (this._detectedPlanes.length) {\n this._detectedPlanes.length = 0;\n }\n };\n // Only supported by BabylonNative\n if (!!this._xrSessionManager.isNative && !!this._options.preferredDetectorOptions && !!this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions) {\n this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions);\n }\n if (!this._xrSessionManager.session.updateWorldTrackingState) {\n internalInit();\n return;\n }\n this._xrSessionManager.session.updateWorldTrackingState({ planeDetectionState: { enabled: true } });\n internalInit();\n }\n _updatePlaneWithXRPlane(xrPlane, plane, xrFrame) {\n plane.polygonDefinition = xrPlane.polygon.map((xrPoint) => {\n const rightHandedSystem = this._xrSessionManager.scene.useRightHandedSystem ? 1 : -1;\n return new Vector3(xrPoint.x, xrPoint.y, xrPoint.z * rightHandedSystem);\n });\n // matrix\n const pose = xrFrame.getPose(xrPlane.planeSpace, this._xrSessionManager.referenceSpace);\n if (pose) {\n const mat = plane.transformationMatrix || new Matrix();\n Matrix.FromArrayToRef(pose.transform.matrix, 0, mat);\n if (!this._xrSessionManager.scene.useRightHandedSystem) {\n mat.toggleModelMatrixHandInPlace();\n }\n plane.transformationMatrix = mat;\n if (this._options.worldParentNode) {\n mat.multiplyToRef(this._options.worldParentNode.getWorldMatrix(), mat);\n }\n }\n return plane;\n }\n /**\n * avoiding using Array.find for global support.\n * @param xrPlane the plane to find in the array\n */\n _findIndexInPlaneArray(xrPlane) {\n for (let i = 0; i < this._detectedPlanes.length; ++i) {\n if (this._detectedPlanes[i].xrPlane === xrPlane) {\n return i;\n }\n }\n return -1;\n }\n}\n/**\n * The module's name\n */\nWebXRPlaneDetector.Name = WebXRFeatureName.PLANE_DETECTION;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRPlaneDetector.Version = 1;\n//register the plugin\nWebXRFeaturesManager.AddWebXRFeature(WebXRPlaneDetector.Name, (xrSessionManager, options) => {\n return () => new WebXRPlaneDetector(xrSessionManager, options);\n}, WebXRPlaneDetector.Version);\n//# sourceMappingURL=WebXRPlaneDetector.js.map","import { WebXRFeaturesManager, WebXRFeatureName } from \"../webXRFeaturesManager.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\n/**\n * A module that will automatically disable background meshes when entering AR and will enable them when leaving AR.\n */\nexport class WebXRBackgroundRemover extends WebXRAbstractFeature {\n /**\n * constructs a new background remover module\n * @param _xrSessionManager the session manager for this module\n * @param options read-only options to be used in this module\n */\n constructor(_xrSessionManager, \n /**\n * read-only options to be used in this module\n */\n options = {}) {\n super(_xrSessionManager);\n this.options = options;\n /**\n * registered observers will be triggered when the background state changes\n */\n this.onBackgroundStateChangedObservable = new Observable();\n }\n /**\n * attach this feature\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n attach() {\n this._setBackgroundState(false);\n return super.attach();\n }\n /**\n * detach this feature.\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n detach() {\n this._setBackgroundState(true);\n return super.detach();\n }\n /**\n * Dispose this feature and all of the resources attached\n */\n dispose() {\n super.dispose();\n this.onBackgroundStateChangedObservable.clear();\n }\n _onXRFrame(_xrFrame) {\n // no-op\n }\n _setBackgroundState(newState) {\n const scene = this._xrSessionManager.scene;\n if (!this.options.ignoreEnvironmentHelper) {\n if (this.options.environmentHelperRemovalFlags) {\n if (this.options.environmentHelperRemovalFlags.skyBox) {\n const backgroundSkybox = scene.getMeshByName(\"BackgroundSkybox\");\n if (backgroundSkybox) {\n backgroundSkybox.setEnabled(newState);\n }\n }\n if (this.options.environmentHelperRemovalFlags.ground) {\n const backgroundPlane = scene.getMeshByName(\"BackgroundPlane\");\n if (backgroundPlane) {\n backgroundPlane.setEnabled(newState);\n }\n }\n }\n else {\n const backgroundHelper = scene.getMeshByName(\"BackgroundHelper\");\n if (backgroundHelper) {\n backgroundHelper.setEnabled(newState);\n }\n }\n }\n if (this.options.backgroundMeshes) {\n this.options.backgroundMeshes.forEach((mesh) => mesh.setEnabled(newState));\n }\n this.onBackgroundStateChangedObservable.notifyObservers(newState);\n }\n}\n/**\n * The module's name\n */\nWebXRBackgroundRemover.Name = WebXRFeatureName.BACKGROUND_REMOVER;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRBackgroundRemover.Version = 1;\n//register the plugin\nWebXRFeaturesManager.AddWebXRFeature(WebXRBackgroundRemover.Name, (xrSessionManager, options) => {\n return () => new WebXRBackgroundRemover(xrSessionManager, options);\n}, WebXRBackgroundRemover.Version, true);\n//# sourceMappingURL=WebXRBackgroundRemover.js.map","import { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nimport { Vector3, Quaternion } from \"../../Maths/math.vector.js\";\nimport { PhysicsImpostor } from \"../../Physics/v1/physicsImpostor.js\";\nimport { CreateSphere } from \"../../Meshes/Builders/sphereBuilder.js\";\nimport { WebXRFeatureName, WebXRFeaturesManager } from \"../webXRFeaturesManager.js\";\nimport { Logger } from \"../../Misc/logger.js\";\n/**\n * Options for the controller physics feature\n */\nexport class IWebXRControllerPhysicsOptions {\n}\n/**\n * Add physics impostor to your webxr controllers,\n * including naive calculation of their linear and angular velocity\n */\nexport class WebXRControllerPhysics extends WebXRAbstractFeature {\n _createPhysicsImpostor(xrController) {\n const impostorType = this._options.physicsProperties.impostorType || PhysicsImpostor.SphereImpostor;\n const impostorSize = this._options.physicsProperties.impostorSize || 0.1;\n const impostorMesh = CreateSphere(\"impostor-mesh-\" + xrController.uniqueId, {\n diameterX: typeof impostorSize === \"number\" ? impostorSize : impostorSize.width,\n diameterY: typeof impostorSize === \"number\" ? impostorSize : impostorSize.height,\n diameterZ: typeof impostorSize === \"number\" ? impostorSize : impostorSize.depth,\n });\n impostorMesh.isVisible = this._debugMode;\n impostorMesh.isPickable = false;\n impostorMesh.rotationQuaternion = new Quaternion();\n const controllerMesh = xrController.grip || xrController.pointer;\n impostorMesh.position.copyFrom(controllerMesh.position);\n impostorMesh.rotationQuaternion.copyFrom(controllerMesh.rotationQuaternion);\n const impostor = new PhysicsImpostor(impostorMesh, impostorType, Object.assign({ mass: 0 }, this._options.physicsProperties));\n this._controllers[xrController.uniqueId] = {\n xrController,\n impostor,\n impostorMesh,\n };\n }\n /**\n * Construct a new Controller Physics Feature\n * @param _xrSessionManager the corresponding xr session manager\n * @param _options options to create this feature with\n */\n constructor(_xrSessionManager, _options) {\n super(_xrSessionManager);\n this._options = _options;\n this._attachController = (xrController) => {\n if (this._controllers[xrController.uniqueId]) {\n // already attached\n return;\n }\n if (!this._xrSessionManager.scene.isPhysicsEnabled()) {\n Logger.Warn(\"physics engine not enabled, skipped. Please add this controller manually.\");\n }\n // if no motion controller available, create impostors!\n if (this._options.physicsProperties.useControllerMesh && xrController.inputSource.gamepad) {\n xrController.onMotionControllerInitObservable.addOnce((motionController) => {\n if (!motionController._doNotLoadControllerMesh) {\n motionController.onModelLoadedObservable.addOnce(() => {\n const impostor = new PhysicsImpostor(motionController.rootMesh, PhysicsImpostor.MeshImpostor, Object.assign({ mass: 0 }, this._options.physicsProperties));\n const controllerMesh = xrController.grip || xrController.pointer;\n this._controllers[xrController.uniqueId] = {\n xrController,\n impostor,\n oldPos: controllerMesh.position.clone(),\n oldRotation: controllerMesh.rotationQuaternion.clone(),\n };\n });\n }\n else {\n // This controller isn't using a model, create impostors instead\n this._createPhysicsImpostor(xrController);\n }\n });\n }\n else {\n this._createPhysicsImpostor(xrController);\n }\n };\n this._controllers = {};\n this._debugMode = false;\n this._delta = 0;\n this._lastTimestamp = 0;\n this._tmpQuaternion = new Quaternion();\n this._tmpVector = new Vector3();\n if (!this._options.physicsProperties) {\n this._options.physicsProperties = {};\n }\n }\n /**\n * @internal\n * enable debugging - will show console outputs and the impostor mesh\n */\n _enablePhysicsDebug() {\n this._debugMode = true;\n Object.keys(this._controllers).forEach((controllerId) => {\n const controllerData = this._controllers[controllerId];\n if (controllerData.impostorMesh) {\n controllerData.impostorMesh.isVisible = true;\n }\n });\n }\n /**\n * Manually add a controller (if no xrInput was provided or physics engine was not enabled)\n * @param xrController the controller to add\n */\n addController(xrController) {\n this._attachController(xrController);\n }\n /**\n * attach this feature\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n attach() {\n if (!super.attach()) {\n return false;\n }\n if (!this._options.xrInput) {\n return true;\n }\n this._options.xrInput.controllers.forEach(this._attachController);\n this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController);\n this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, (controller) => {\n // REMOVE the controller\n this._detachController(controller.uniqueId);\n });\n if (this._options.enableHeadsetImpostor) {\n const params = this._options.headsetImpostorParams || {\n impostorType: PhysicsImpostor.SphereImpostor,\n restitution: 0.8,\n impostorSize: 0.3,\n };\n const impostorSize = params.impostorSize || 0.3;\n this._headsetMesh = CreateSphere(\"headset-mesh\", {\n diameterX: typeof impostorSize === \"number\" ? impostorSize : impostorSize.width,\n diameterY: typeof impostorSize === \"number\" ? impostorSize : impostorSize.height,\n diameterZ: typeof impostorSize === \"number\" ? impostorSize : impostorSize.depth,\n });\n this._headsetMesh.rotationQuaternion = new Quaternion();\n this._headsetMesh.isVisible = false;\n this._headsetImpostor = new PhysicsImpostor(this._headsetMesh, params.impostorType, Object.assign({ mass: 0 }, params));\n }\n return true;\n }\n /**\n * detach this feature.\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n detach() {\n if (!super.detach()) {\n return false;\n }\n Object.keys(this._controllers).forEach((controllerId) => {\n this._detachController(controllerId);\n });\n if (this._headsetMesh) {\n this._headsetMesh.dispose();\n }\n return true;\n }\n /**\n * Get the headset impostor, if enabled\n * @returns the impostor\n */\n getHeadsetImpostor() {\n return this._headsetImpostor;\n }\n /**\n * Get the physics impostor of a specific controller.\n * The impostor is not attached to a mesh because a mesh for each controller is not obligatory\n * @param controller the controller or the controller id of which to get the impostor\n * @returns the impostor or null\n */\n getImpostorForController(controller) {\n const id = typeof controller === \"string\" ? controller : controller.uniqueId;\n if (this._controllers[id]) {\n return this._controllers[id].impostor;\n }\n else {\n return null;\n }\n }\n /**\n * Update the physics properties provided in the constructor\n * @param newProperties the new properties object\n * @param newProperties.impostorType\n * @param newProperties.impostorSize\n * @param newProperties.friction\n * @param newProperties.restitution\n */\n setPhysicsProperties(newProperties) {\n this._options.physicsProperties = Object.assign(Object.assign({}, this._options.physicsProperties), newProperties);\n }\n _onXRFrame(_xrFrame) {\n var _a, _b;\n this._delta = this._xrSessionManager.currentTimestamp - this._lastTimestamp;\n this._lastTimestamp = this._xrSessionManager.currentTimestamp;\n if (this._headsetMesh && this._headsetImpostor) {\n this._headsetMesh.position.copyFrom(this._options.xrInput.xrCamera.globalPosition);\n this._headsetMesh.rotationQuaternion.copyFrom(this._options.xrInput.xrCamera.absoluteRotation);\n if ((_a = this._options.xrInput.xrCamera._lastXRViewerPose) === null || _a === void 0 ? void 0 : _a.linearVelocity) {\n const lv = this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity;\n this._tmpVector.set(lv.x, lv.y, lv.z);\n this._headsetImpostor.setLinearVelocity(this._tmpVector);\n }\n if ((_b = this._options.xrInput.xrCamera._lastXRViewerPose) === null || _b === void 0 ? void 0 : _b.angularVelocity) {\n const av = this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity;\n this._tmpVector.set(av.x, av.y, av.z);\n this._headsetImpostor.setAngularVelocity(this._tmpVector);\n }\n }\n Object.keys(this._controllers).forEach((controllerId) => {\n var _a, _b;\n const controllerData = this._controllers[controllerId];\n const controllerMesh = controllerData.xrController.grip || controllerData.xrController.pointer;\n const comparedPosition = controllerData.oldPos || controllerData.impostorMesh.position;\n if ((_a = controllerData.xrController._lastXRPose) === null || _a === void 0 ? void 0 : _a.linearVelocity) {\n const lv = controllerData.xrController._lastXRPose.linearVelocity;\n this._tmpVector.set(lv.x, lv.y, lv.z);\n controllerData.impostor.setLinearVelocity(this._tmpVector);\n }\n else {\n controllerMesh.position.subtractToRef(comparedPosition, this._tmpVector);\n this._tmpVector.scaleInPlace(1000 / this._delta);\n controllerData.impostor.setLinearVelocity(this._tmpVector);\n }\n comparedPosition.copyFrom(controllerMesh.position);\n if (this._debugMode) {\n console.log(this._tmpVector, \"linear\");\n }\n const comparedQuaternion = controllerData.oldRotation || controllerData.impostorMesh.rotationQuaternion;\n if ((_b = controllerData.xrController._lastXRPose) === null || _b === void 0 ? void 0 : _b.angularVelocity) {\n const av = controllerData.xrController._lastXRPose.angularVelocity;\n this._tmpVector.set(av.x, av.y, av.z);\n controllerData.impostor.setAngularVelocity(this._tmpVector);\n }\n else {\n if (!comparedQuaternion.equalsWithEpsilon(controllerMesh.rotationQuaternion)) {\n // roughly based on this - https://www.gamedev.net/forums/topic/347752-quaternion-and-angular-velocity/\n comparedQuaternion.conjugateInPlace().multiplyToRef(controllerMesh.rotationQuaternion, this._tmpQuaternion);\n const len = Math.sqrt(this._tmpQuaternion.x * this._tmpQuaternion.x + this._tmpQuaternion.y * this._tmpQuaternion.y + this._tmpQuaternion.z * this._tmpQuaternion.z);\n this._tmpVector.set(this._tmpQuaternion.x, this._tmpQuaternion.y, this._tmpQuaternion.z);\n // define a better epsilon\n if (len < 0.001) {\n this._tmpVector.scaleInPlace(2);\n }\n else {\n const angle = 2 * Math.atan2(len, this._tmpQuaternion.w);\n this._tmpVector.scaleInPlace(angle / (len * (this._delta / 1000)));\n }\n controllerData.impostor.setAngularVelocity(this._tmpVector);\n }\n }\n comparedQuaternion.copyFrom(controllerMesh.rotationQuaternion);\n if (this._debugMode) {\n console.log(this._tmpVector, this._tmpQuaternion, \"angular\");\n }\n });\n }\n _detachController(xrControllerUniqueId) {\n const controllerData = this._controllers[xrControllerUniqueId];\n if (!controllerData) {\n return;\n }\n if (controllerData.impostorMesh) {\n controllerData.impostorMesh.dispose();\n }\n // remove from the map\n delete this._controllers[xrControllerUniqueId];\n }\n}\n/**\n * The module's name\n */\nWebXRControllerPhysics.Name = WebXRFeatureName.PHYSICS_CONTROLLERS;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the webxr specs version\n */\nWebXRControllerPhysics.Version = 1;\n//register the plugin\nWebXRFeaturesManager.AddWebXRFeature(WebXRControllerPhysics.Name, (xrSessionManager, options) => {\n return () => new WebXRControllerPhysics(xrSessionManager, options);\n}, WebXRControllerPhysics.Version, true);\n//# sourceMappingURL=WebXRControllerPhysics.js.map","import { WebXRFeaturesManager, WebXRFeatureName } from \"../webXRFeaturesManager.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { Vector3, Matrix, Quaternion } from \"../../Maths/math.vector.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * The currently-working hit-test module.\n * Hit test (or Ray-casting) is used to interact with the real world.\n * For further information read here - https://github.com/immersive-web/hit-test\n *\n * Tested on chrome (mobile) 80.\n */\nexport class WebXRHitTest extends WebXRAbstractFeature {\n /**\n * Creates a new instance of the hit test feature\n * @param _xrSessionManager an instance of WebXRSessionManager\n * @param options options to use when constructing this feature\n */\n constructor(_xrSessionManager, \n /**\n * options to use when constructing this feature\n */\n options = {}) {\n super(_xrSessionManager);\n this.options = options;\n this._tmpMat = new Matrix();\n this._tmpPos = new Vector3();\n this._tmpQuat = new Quaternion();\n this._initHitTestSource = (referenceSpace) => {\n if (!referenceSpace) {\n return;\n }\n const offsetRay = new XRRay(this.options.offsetRay || {});\n const hitTestOptions = {\n space: this.options.useReferenceSpace ? referenceSpace : this._xrSessionManager.viewerReferenceSpace,\n offsetRay: offsetRay,\n };\n if (this.options.entityTypes) {\n hitTestOptions.entityTypes = this.options.entityTypes;\n }\n if (!hitTestOptions.space) {\n Tools.Warn(\"waiting for viewer reference space to initialize\");\n return;\n }\n this._xrSessionManager.session.requestHitTestSource(hitTestOptions).then((hitTestSource) => {\n if (this._xrHitTestSource) {\n this._xrHitTestSource.cancel();\n }\n this._xrHitTestSource = hitTestSource;\n });\n };\n /**\n * When set to true, each hit test will have its own position/rotation objects\n * When set to false, position and rotation objects will be reused for each hit test. It is expected that\n * the developers will clone them or copy them as they see fit.\n */\n this.autoCloneTransformation = false;\n /**\n * Triggered when new babylon (transformed) hit test results are available\n * Note - this will be called when results come back from the device. It can be an empty array!!\n */\n this.onHitTestResultObservable = new Observable();\n /**\n * Use this to temporarily pause hit test checks.\n */\n this.paused = false;\n this.xrNativeFeatureName = \"hit-test\";\n Tools.Warn(\"Hit test is an experimental and unstable feature.\");\n }\n /**\n * attach this feature\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n attach() {\n if (!super.attach()) {\n return false;\n }\n // Feature enabled, but not available\n if (!this._xrSessionManager.session.requestHitTestSource) {\n return false;\n }\n if (!this.options.disablePermanentHitTest) {\n if (this._xrSessionManager.referenceSpace) {\n this._initHitTestSource(this._xrSessionManager.referenceSpace);\n }\n this._xrSessionManager.onXRReferenceSpaceChanged.add(this._initHitTestSource);\n }\n if (this.options.enableTransientHitTest) {\n const offsetRay = new XRRay(this.options.transientOffsetRay || {});\n this._xrSessionManager.session.requestHitTestSourceForTransientInput({\n profile: this.options.transientHitTestProfile || \"generic-touchscreen\",\n offsetRay,\n entityTypes: this.options.entityTypes,\n }).then((hitSource) => {\n this._transientXrHitTestSource = hitSource;\n });\n }\n return true;\n }\n /**\n * detach this feature.\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n detach() {\n if (!super.detach()) {\n return false;\n }\n if (this._xrHitTestSource) {\n this._xrHitTestSource.cancel();\n this._xrHitTestSource = null;\n }\n this._xrSessionManager.onXRReferenceSpaceChanged.removeCallback(this._initHitTestSource);\n if (this._transientXrHitTestSource) {\n this._transientXrHitTestSource.cancel();\n this._transientXrHitTestSource = null;\n }\n return true;\n }\n /**\n * Dispose this feature and all of the resources attached\n */\n dispose() {\n super.dispose();\n this.onHitTestResultObservable.clear();\n }\n _onXRFrame(frame) {\n // make sure we do nothing if (async) not attached\n if (!this.attached || this.paused) {\n return;\n }\n if (this._xrHitTestSource) {\n const results = frame.getHitTestResults(this._xrHitTestSource);\n this._processWebXRHitTestResult(results);\n }\n if (this._transientXrHitTestSource) {\n const hitTestResultsPerInputSource = frame.getHitTestResultsForTransientInput(this._transientXrHitTestSource);\n hitTestResultsPerInputSource.forEach((resultsPerInputSource) => {\n this._processWebXRHitTestResult(resultsPerInputSource.results, resultsPerInputSource.inputSource);\n });\n }\n }\n _processWebXRHitTestResult(hitTestResults, inputSource) {\n const results = [];\n hitTestResults.forEach((hitTestResult) => {\n const pose = hitTestResult.getPose(this._xrSessionManager.referenceSpace);\n if (!pose) {\n return;\n }\n const pos = pose.transform.position;\n const quat = pose.transform.orientation;\n this._tmpPos.set(pos.x, pos.y, pos.z);\n this._tmpQuat.set(quat.x, quat.y, quat.z, quat.w);\n Matrix.FromFloat32ArrayToRefScaled(pose.transform.matrix, 0, 1, this._tmpMat);\n if (!this._xrSessionManager.scene.useRightHandedSystem) {\n this._tmpPos.z *= -1;\n this._tmpQuat.z *= -1;\n this._tmpQuat.w *= -1;\n this._tmpMat.toggleModelMatrixHandInPlace();\n }\n const result = {\n position: this.autoCloneTransformation ? this._tmpPos.clone() : this._tmpPos,\n rotationQuaternion: this.autoCloneTransformation ? this._tmpQuat.clone() : this._tmpQuat,\n transformationMatrix: this.autoCloneTransformation ? this._tmpMat.clone() : this._tmpMat,\n inputSource: inputSource,\n isTransient: !!inputSource,\n xrHitResult: hitTestResult,\n };\n results.push(result);\n });\n this.onHitTestResultObservable.notifyObservers(results);\n }\n}\n/**\n * The module's name\n */\nWebXRHitTest.Name = WebXRFeatureName.HIT_TEST;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRHitTest.Version = 2;\n//register the plugin versions\nWebXRFeaturesManager.AddWebXRFeature(WebXRHitTest.Name, (xrSessionManager, options) => {\n return () => new WebXRHitTest(xrSessionManager, options);\n}, WebXRHitTest.Version, false);\n//# sourceMappingURL=WebXRHitTest.js.map","import { WebXRFeaturesManager, WebXRFeatureName } from \"../webXRFeaturesManager.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\n/**\n * The feature point system is used to detect feature points from real world geometry.\n * This feature is currently experimental and only supported on BabylonNative, and should not be used in the browser.\n * The newly introduced API can be seen in webxr.nativeextensions.d.ts and described in FeaturePoints.md.\n */\nexport class WebXRFeaturePointSystem extends WebXRAbstractFeature {\n /**\n * The current feature point cloud maintained across frames.\n */\n get featurePointCloud() {\n return this._featurePointCloud;\n }\n /**\n * construct the feature point system\n * @param _xrSessionManager an instance of xr Session manager\n */\n constructor(_xrSessionManager) {\n super(_xrSessionManager);\n this._enabled = false;\n this._featurePointCloud = [];\n /**\n * Observers registered here will be executed whenever new feature points are added (on XRFrame while the session is tracking).\n * Will notify the observers about which feature points have been added.\n */\n this.onFeaturePointsAddedObservable = new Observable();\n /**\n * Observers registered here will be executed whenever a feature point has been updated (on XRFrame while the session is tracking).\n * Will notify the observers about which feature points have been updated.\n */\n this.onFeaturePointsUpdatedObservable = new Observable();\n this.xrNativeFeatureName = \"bjsfeature-points\";\n if (this._xrSessionManager.session) {\n this._init();\n }\n else {\n this._xrSessionManager.onXRSessionInit.addOnce(() => {\n this._init();\n });\n }\n }\n /**\n * Detach this feature.\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n detach() {\n if (!super.detach()) {\n return false;\n }\n this.featurePointCloud.length = 0;\n return true;\n }\n /**\n * Dispose this feature and all of the resources attached\n */\n dispose() {\n super.dispose();\n this._featurePointCloud.length = 0;\n this.onFeaturePointsUpdatedObservable.clear();\n this.onFeaturePointsAddedObservable.clear();\n }\n /**\n * On receiving a new XR frame if this feature is attached notify observers new feature point data is available.\n * @param frame\n */\n _onXRFrame(frame) {\n if (!this.attached || !this._enabled || !frame) {\n return;\n }\n const featurePointRawData = frame.featurePointCloud;\n if (!featurePointRawData || featurePointRawData.length === 0) {\n return;\n }\n else {\n if (featurePointRawData.length % 5 !== 0) {\n throw new Error(\"Received malformed feature point cloud of length: \" + featurePointRawData.length);\n }\n const numberOfFeaturePoints = featurePointRawData.length / 5;\n const updatedFeaturePoints = new Array();\n const addedFeaturePoints = new Array();\n for (let i = 0; i < numberOfFeaturePoints; i++) {\n const rawIndex = i * 5;\n const id = featurePointRawData[rawIndex + 4];\n // IDs should be durable across frames and strictly increasing from 0 up, so use them as indexing into the feature point array.\n if (!this._featurePointCloud[id]) {\n this._featurePointCloud[id] = { position: new Vector3(), confidenceValue: 0 };\n addedFeaturePoints.push(id);\n }\n else {\n updatedFeaturePoints.push(id);\n }\n // Set the feature point values.\n this._featurePointCloud[id].position.x = featurePointRawData[rawIndex];\n this._featurePointCloud[id].position.y = featurePointRawData[rawIndex + 1];\n this._featurePointCloud[id].position.z = featurePointRawData[rawIndex + 2];\n this._featurePointCloud[id].confidenceValue = featurePointRawData[rawIndex + 3];\n }\n // Signal observers that feature points have been added if necessary.\n if (addedFeaturePoints.length > 0) {\n this.onFeaturePointsAddedObservable.notifyObservers(addedFeaturePoints);\n }\n // Signal observers that feature points have been updated if necessary.\n if (updatedFeaturePoints.length > 0) {\n this.onFeaturePointsUpdatedObservable.notifyObservers(updatedFeaturePoints);\n }\n }\n }\n /**\n * Initializes the feature. If the feature point feature is not available for this environment do not mark the feature as enabled.\n */\n _init() {\n if (!this._xrSessionManager.session.trySetFeaturePointCloudEnabled || !this._xrSessionManager.session.trySetFeaturePointCloudEnabled(true)) {\n // fail silently\n return;\n }\n this._enabled = true;\n }\n}\n/**\n * The module's name\n */\nWebXRFeaturePointSystem.Name = WebXRFeatureName.FEATURE_POINTS;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRFeaturePointSystem.Version = 1;\n// register the plugin\nWebXRFeaturesManager.AddWebXRFeature(WebXRFeaturePointSystem.Name, (xrSessionManager) => {\n return () => new WebXRFeaturePointSystem(xrSessionManager);\n}, WebXRFeaturePointSystem.Version);\n//# sourceMappingURL=WebXRFeaturePointSystem.js.map","import { WebXRFeaturesManager, WebXRFeatureName } from \"../webXRFeaturesManager.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nimport { Matrix } from \"../../Maths/math.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nlet meshIdProvider = 0;\n/**\n * The mesh detector is used to detect meshes in the real world when in AR\n */\nexport class WebXRMeshDetector extends WebXRAbstractFeature {\n constructor(_xrSessionManager, _options = {}) {\n super(_xrSessionManager);\n this._options = _options;\n this._detectedMeshes = new Map();\n /**\n * Observers registered here will be executed when a new mesh was added to the session\n */\n this.onMeshAddedObservable = new Observable();\n /**\n * Observers registered here will be executed when a mesh is no longer detected in the session\n */\n this.onMeshRemovedObservable = new Observable();\n /**\n * Observers registered here will be executed when an existing mesh updates\n */\n this.onMeshUpdatedObservable = new Observable();\n this.xrNativeFeatureName = \"mesh-detection\";\n if (this._xrSessionManager.session) {\n this._init();\n }\n else {\n this._xrSessionManager.onXRSessionInit.addOnce(() => {\n this._init();\n });\n }\n }\n detach() {\n if (!super.detach()) {\n return false;\n }\n // Only supported by BabylonNative\n if (!!this._xrSessionManager.isNative && !!this._xrSessionManager.session.trySetMeshDetectorEnabled) {\n this._xrSessionManager.session.trySetMeshDetectorEnabled(false);\n }\n if (!this._options.doNotRemoveMeshesOnSessionEnded) {\n this._detectedMeshes.forEach((mesh) => {\n this.onMeshRemovedObservable.notifyObservers(mesh);\n });\n this._detectedMeshes.clear();\n }\n return true;\n }\n dispose() {\n super.dispose();\n this.onMeshAddedObservable.clear();\n this.onMeshRemovedObservable.clear();\n this.onMeshUpdatedObservable.clear();\n }\n _onXRFrame(frame) {\n var _a;\n // TODO remove try catch\n try {\n if (!this.attached || !frame) {\n return;\n }\n const detectedMeshes = (_a = frame.worldInformation) === null || _a === void 0 ? void 0 : _a.detectedMeshes;\n if (detectedMeshes) {\n const toRemove = new Set();\n this._detectedMeshes.forEach((vertexData, xrMesh) => {\n if (!detectedMeshes.has(xrMesh)) {\n toRemove.add(xrMesh);\n }\n });\n toRemove.forEach((xrMesh) => {\n const vertexData = this._detectedMeshes.get(xrMesh);\n if (vertexData) {\n this.onMeshRemovedObservable.notifyObservers(vertexData);\n this._detectedMeshes.delete(xrMesh);\n }\n });\n // now check for new ones\n detectedMeshes.forEach((xrMesh) => {\n if (!this._detectedMeshes.has(xrMesh)) {\n const partialVertexData = {\n id: meshIdProvider++,\n xrMesh: xrMesh,\n };\n const vertexData = this._updateVertexDataWithXRMesh(xrMesh, partialVertexData, frame);\n this._detectedMeshes.set(xrMesh, vertexData);\n this.onMeshAddedObservable.notifyObservers(vertexData);\n }\n else {\n // updated?\n if (xrMesh.lastChangedTime === this._xrSessionManager.currentTimestamp) {\n const vertexData = this._detectedMeshes.get(xrMesh);\n if (vertexData) {\n this._updateVertexDataWithXRMesh(xrMesh, vertexData, frame);\n this.onMeshUpdatedObservable.notifyObservers(vertexData);\n }\n }\n }\n });\n }\n }\n catch (error) {\n console.log(error.stack);\n }\n }\n _init() {\n // Only supported by BabylonNative\n if (this._xrSessionManager.isNative) {\n if (this._xrSessionManager.session.trySetMeshDetectorEnabled) {\n this._xrSessionManager.session.trySetMeshDetectorEnabled(true);\n }\n if (!!this._options.preferredDetectorOptions && !!this._xrSessionManager.session.trySetPreferredMeshDetectorOptions) {\n this._xrSessionManager.session.trySetPreferredMeshDetectorOptions(this._options.preferredDetectorOptions);\n }\n }\n }\n _updateVertexDataWithXRMesh(xrMesh, mesh, xrFrame) {\n mesh.xrMesh = xrMesh;\n mesh.worldParentNode = this._options.worldParentNode;\n if (this._options.convertCoordinateSystems) {\n if (!this._xrSessionManager.scene.useRightHandedSystem) {\n mesh.positions = new Float32Array(xrMesh.positions.length);\n for (let i = 0; i < xrMesh.positions.length; i += 3) {\n mesh.positions[i] = xrMesh.positions[i];\n mesh.positions[i + 1] = xrMesh.positions[i + 1];\n mesh.positions[i + 2] = -1 * xrMesh.positions[i + 2];\n }\n if (xrMesh.normals) {\n mesh.normals = new Float32Array(xrMesh.normals.length);\n for (let i = 0; i < xrMesh.normals.length; i += 3) {\n mesh.normals[i] = xrMesh.normals[i];\n mesh.normals[i + 1] = xrMesh.normals[i + 1];\n mesh.normals[i + 2] = -1 * xrMesh.normals[i + 2];\n }\n }\n }\n else {\n mesh.positions = xrMesh.positions;\n mesh.normals = xrMesh.normals;\n }\n // WebXR should provide indices in a counterclockwise winding order regardless of coordinate system handedness\n mesh.indices = xrMesh.indices;\n // matrix\n const pose = xrFrame.getPose(xrMesh.meshSpace, this._xrSessionManager.referenceSpace);\n if (pose) {\n const mat = mesh.transformationMatrix || new Matrix();\n Matrix.FromArrayToRef(pose.transform.matrix, 0, mat);\n if (!this._xrSessionManager.scene.useRightHandedSystem) {\n mat.toggleModelMatrixHandInPlace();\n }\n mesh.transformationMatrix = mat;\n if (this._options.worldParentNode) {\n mat.multiplyToRef(this._options.worldParentNode.getWorldMatrix(), mat);\n }\n }\n }\n return mesh;\n }\n}\n/**\n * The module's name\n */\nWebXRMeshDetector.Name = WebXRFeatureName.MESH_DETECTION;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRMeshDetector.Version = 1;\nWebXRFeaturesManager.AddWebXRFeature(WebXRMeshDetector.Name, (xrSessionManager, options) => {\n return () => new WebXRMeshDetector(xrSessionManager, options);\n}, WebXRMeshDetector.Version, false);\n//# sourceMappingURL=WebXRMeshDetector.js.map","import { WebXRFeaturesManager, WebXRFeatureName } from \"../webXRFeaturesManager.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nimport { Matrix } from \"../../Maths/math.vector.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * Enum that describes the state of the image trackability score status for this session.\n */\nvar ImageTrackingScoreStatus;\n(function (ImageTrackingScoreStatus) {\n // AR Session has not yet assessed image trackability scores.\n ImageTrackingScoreStatus[ImageTrackingScoreStatus[\"NotReceived\"] = 0] = \"NotReceived\";\n // A request to retrieve trackability scores has been sent, but no response has been received.\n ImageTrackingScoreStatus[ImageTrackingScoreStatus[\"Waiting\"] = 1] = \"Waiting\";\n // Image trackability scores have been received for this session\n ImageTrackingScoreStatus[ImageTrackingScoreStatus[\"Received\"] = 2] = \"Received\";\n})(ImageTrackingScoreStatus || (ImageTrackingScoreStatus = {}));\n/**\n * Image tracking for immersive AR sessions.\n * Providing a list of images and their estimated widths will enable tracking those images in the real world.\n */\nexport class WebXRImageTracking extends WebXRAbstractFeature {\n /**\n * constructs the image tracking feature\n * @param _xrSessionManager the session manager for this module\n * @param options read-only options to be used in this module\n */\n constructor(_xrSessionManager, \n /**\n * read-only options to be used in this module\n */\n options) {\n super(_xrSessionManager);\n this.options = options;\n /**\n * This will be triggered if the underlying system deems an image untrackable.\n * The index is the index of the image from the array used to initialize the feature.\n */\n this.onUntrackableImageFoundObservable = new Observable();\n /**\n * An image was deemed trackable, and the system will start tracking it.\n */\n this.onTrackableImageFoundObservable = new Observable();\n /**\n * The image was found and its state was updated.\n */\n this.onTrackedImageUpdatedObservable = new Observable();\n this._trackableScoreStatus = ImageTrackingScoreStatus.NotReceived;\n this._trackedImages = [];\n this.xrNativeFeatureName = \"image-tracking\";\n }\n /**\n * attach this feature\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n attach() {\n return super.attach();\n }\n /**\n * detach this feature.\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n detach() {\n return super.detach();\n }\n /**\n * Get a tracked image by its ID.\n *\n * @param id the id of the image to load (position in the init array)\n * @returns a trackable image, if exists in this location\n */\n getTrackedImageById(id) {\n return this._trackedImages[id] || null;\n }\n /**\n * Dispose this feature and all of the resources attached\n */\n dispose() {\n super.dispose();\n this._trackedImages.forEach((trackedImage) => {\n trackedImage.originalBitmap.close();\n });\n this._trackedImages.length = 0;\n this.onTrackableImageFoundObservable.clear();\n this.onUntrackableImageFoundObservable.clear();\n this.onTrackedImageUpdatedObservable.clear();\n }\n /**\n * Extends the session init object if needed\n * @returns augmentation object fo the xr session init object.\n */\n async getXRSessionInitExtension() {\n if (!this.options.images || !this.options.images.length) {\n return {};\n }\n const promises = this.options.images.map((image) => {\n if (typeof image.src === \"string\") {\n return this._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(image.src);\n }\n else {\n return Promise.resolve(image.src); // resolve is probably unneeded\n }\n });\n try {\n const images = await Promise.all(promises);\n this._originalTrackingRequest = images.map((image, idx) => {\n return {\n image,\n widthInMeters: this.options.images[idx].estimatedRealWorldWidth,\n };\n });\n return {\n trackedImages: this._originalTrackingRequest,\n };\n }\n catch (ex) {\n Tools.Error(\"Error loading images for tracking, WebXRImageTracking disabled for this session.\");\n return {};\n }\n }\n _onXRFrame(_xrFrame) {\n if (!_xrFrame.getImageTrackingResults || this._trackableScoreStatus === ImageTrackingScoreStatus.Waiting) {\n return;\n }\n // Image tracking scores may be generated a few frames after the XR Session initializes.\n // If we haven't received scores yet, then kick off the task to check scores and return immediately.\n if (this._trackableScoreStatus === ImageTrackingScoreStatus.NotReceived) {\n this._checkScoresAsync();\n return;\n }\n const imageTrackedResults = _xrFrame.getImageTrackingResults();\n for (const result of imageTrackedResults) {\n let changed = false;\n const imageIndex = result.index;\n const imageObject = this._trackedImages[imageIndex];\n if (!imageObject) {\n // something went wrong!\n continue;\n }\n imageObject.xrTrackingResult = result;\n if (imageObject.realWorldWidth !== result.measuredWidthInMeters) {\n imageObject.realWorldWidth = result.measuredWidthInMeters;\n changed = true;\n }\n // Get the pose of the image relative to a reference space.\n const pose = _xrFrame.getPose(result.imageSpace, this._xrSessionManager.referenceSpace);\n if (pose) {\n const mat = imageObject.transformationMatrix;\n Matrix.FromArrayToRef(pose.transform.matrix, 0, mat);\n if (!this._xrSessionManager.scene.useRightHandedSystem) {\n mat.toggleModelMatrixHandInPlace();\n }\n changed = true;\n }\n const state = result.trackingState;\n const emulated = state === \"emulated\";\n if (imageObject.emulated !== emulated) {\n imageObject.emulated = emulated;\n changed = true;\n }\n if (changed) {\n this.onTrackedImageUpdatedObservable.notifyObservers(imageObject);\n }\n }\n }\n async _checkScoresAsync() {\n if (!this._xrSessionManager.session.getTrackedImageScores || this._trackableScoreStatus !== ImageTrackingScoreStatus.NotReceived) {\n return;\n }\n this._trackableScoreStatus = ImageTrackingScoreStatus.Waiting;\n const imageScores = await this._xrSessionManager.session.getTrackedImageScores();\n if (!imageScores || imageScores.length === 0) {\n this._trackableScoreStatus = ImageTrackingScoreStatus.NotReceived;\n return;\n }\n // check the scores for all\n for (let idx = 0; idx < imageScores.length; ++idx) {\n if (imageScores[idx] == \"untrackable\") {\n this.onUntrackableImageFoundObservable.notifyObservers(idx);\n }\n else {\n const originalBitmap = this._originalTrackingRequest[idx].image;\n const imageObject = {\n id: idx,\n originalBitmap,\n transformationMatrix: new Matrix(),\n ratio: originalBitmap.width / originalBitmap.height,\n };\n this._trackedImages[idx] = imageObject;\n this.onTrackableImageFoundObservable.notifyObservers(imageObject);\n }\n }\n this._trackableScoreStatus = imageScores.length > 0 ? ImageTrackingScoreStatus.Received : ImageTrackingScoreStatus.NotReceived;\n }\n}\n/**\n * The module's name\n */\nWebXRImageTracking.Name = WebXRFeatureName.IMAGE_TRACKING;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRImageTracking.Version = 1;\n//register the plugin\nWebXRFeaturesManager.AddWebXRFeature(WebXRImageTracking.Name, (xrSessionManager, options) => {\n return () => new WebXRImageTracking(xrSessionManager, options);\n}, WebXRImageTracking.Version, false);\n//# sourceMappingURL=WebXRImageTracking.js.map","import { Tools } from \"../../Misc/tools.js\";\nimport { WebXRFeatureName, WebXRFeaturesManager } from \"../webXRFeaturesManager.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\n/**\n * DOM Overlay Feature\n *\n * @since 5.0.0\n */\nexport class WebXRDomOverlay extends WebXRAbstractFeature {\n /**\n * Creates a new instance of the dom-overlay feature\n * @param _xrSessionManager an instance of WebXRSessionManager\n * @param options options to use when constructing this feature\n */\n constructor(_xrSessionManager, \n /**\n * options to use when constructing this feature\n */\n options) {\n super(_xrSessionManager);\n this.options = options;\n /**\n * Type of overlay - non-null when available\n */\n this._domOverlayType = null;\n /**\n * Event Listener to supress \"beforexrselect\" events.\n */\n this._beforeXRSelectListener = null;\n /**\n * Element used for overlay\n */\n this._element = null;\n this.xrNativeFeatureName = \"dom-overlay\";\n // https://immersive-web.github.io/dom-overlays/\n Tools.Warn(\"dom-overlay is an experimental and unstable feature.\");\n }\n /**\n * attach this feature\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n attach() {\n if (!super.attach()) {\n return false;\n }\n // Feature not available\n if (!this._xrSessionManager.session.domOverlayState || this._xrSessionManager.session.domOverlayState.type === null) {\n return false;\n }\n this._domOverlayType = this._xrSessionManager.session.domOverlayState.type;\n if (this._element !== null && this.options.supressXRSelectEvents === true) {\n this._beforeXRSelectListener = (ev) => {\n ev.preventDefault();\n };\n this._element.addEventListener(\"beforexrselect\", this._beforeXRSelectListener);\n }\n return true;\n }\n /**\n * The type of DOM overlay (null when not supported). Provided by UA and remains unchanged for duration of session.\n */\n get domOverlayType() {\n return this._domOverlayType;\n }\n /**\n * Dispose this feature and all of the resources attached\n */\n dispose() {\n super.dispose();\n if (this._element !== null && this._beforeXRSelectListener) {\n this._element.removeEventListener(\"beforexrselect\", this._beforeXRSelectListener);\n }\n }\n _onXRFrame(_xrFrame) {\n /* empty */\n }\n /**\n * Extends the session init object if needed\n * @returns augmentation object for the xr session init object.\n */\n async getXRSessionInitExtension() {\n if (this.options.element === undefined) {\n Tools.Warn('\"element\" option must be provided to attach xr-dom-overlay feature.');\n return {};\n }\n else if (typeof this.options.element === \"string\") {\n const selectedElement = document.querySelector(this.options.element);\n if (selectedElement === null) {\n Tools.Warn(`element not found '${this.options.element}' (not requesting xr-dom-overlay)`);\n return {};\n }\n this._element = selectedElement;\n }\n else {\n this._element = this.options.element;\n }\n return {\n domOverlay: {\n root: this._element,\n },\n };\n }\n}\n/**\n * The module's name\n */\nWebXRDomOverlay.Name = WebXRFeatureName.DOM_OVERLAY;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRDomOverlay.Version = 1;\n//register the plugin\nWebXRFeaturesManager.AddWebXRFeature(WebXRDomOverlay.Name, (xrSessionManager, options) => {\n return () => new WebXRDomOverlay(xrSessionManager, options);\n}, WebXRDomOverlay.Version, false);\n//# sourceMappingURL=WebXRDOMOverlay.js.map","import { WebXRFeaturesManager, WebXRFeatureName } from \"../webXRFeaturesManager.js\";\nimport { WebXRControllerComponent } from \"../motionController/webXRControllerComponent.js\";\nimport { Matrix, Quaternion, Vector3 } from \"../../Maths/math.vector.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * This is a movement feature to be used with WebXR-enabled motion controllers.\n * When enabled and attached, the feature will allow a user to move around and rotate in the scene using\n * the input of the attached controllers.\n */\nexport class WebXRControllerMovement extends WebXRAbstractFeature {\n /**\n * Current movement direction. Will be null before XR Frames have been processed.\n */\n get movementDirection() {\n return this._movementDirection;\n }\n /**\n * Is movement enabled\n */\n get movementEnabled() {\n return this._featureContext.movementEnabled;\n }\n /**\n * Sets whether movement is enabled or not\n * @param enabled is movement enabled\n */\n set movementEnabled(enabled) {\n this._featureContext.movementEnabled = enabled;\n }\n /**\n * If movement follows viewer pose\n */\n get movementOrientationFollowsViewerPose() {\n return this._featureContext.movementOrientationFollowsViewerPose;\n }\n /**\n * Sets whether movement follows viewer pose\n * @param followsPose is movement should follow viewer pose\n */\n set movementOrientationFollowsViewerPose(followsPose) {\n this._featureContext.movementOrientationFollowsViewerPose = followsPose;\n }\n /**\n * Gets movement speed\n */\n get movementSpeed() {\n return this._featureContext.movementSpeed;\n }\n /**\n * Sets movement speed\n * @param movementSpeed movement speed\n */\n set movementSpeed(movementSpeed) {\n this._featureContext.movementSpeed = movementSpeed;\n }\n /**\n * Gets minimum threshold the controller's thumbstick/touchpad must pass before being recognized for movement (avoids jitter/unintentional movement)\n */\n get movementThreshold() {\n return this._featureContext.movementThreshold;\n }\n /**\n * Sets minimum threshold the controller's thumbstick/touchpad must pass before being recognized for movement (avoids jitter/unintentional movement)\n * @param movementThreshold new threshold\n */\n set movementThreshold(movementThreshold) {\n this._featureContext.movementThreshold = movementThreshold;\n }\n /**\n * Is rotation enabled\n */\n get rotationEnabled() {\n return this._featureContext.rotationEnabled;\n }\n /**\n * Sets whether rotation is enabled or not\n * @param enabled is rotation enabled\n */\n set rotationEnabled(enabled) {\n this._featureContext.rotationEnabled = enabled;\n }\n /**\n * Gets rotation speed factor\n */\n get rotationSpeed() {\n return this._featureContext.rotationSpeed;\n }\n /**\n * Sets rotation speed factor (1.0 is default)\n * @param rotationSpeed new rotation speed factor\n */\n set rotationSpeed(rotationSpeed) {\n this._featureContext.rotationSpeed = rotationSpeed;\n }\n /**\n * Gets minimum threshold the controller's thumbstick/touchpad must pass before being recognized for rotation (avoids jitter/unintentional rotation)\n */\n get rotationThreshold() {\n return this._featureContext.rotationThreshold;\n }\n /**\n * Sets minimum threshold the controller's thumbstick/touchpad must pass before being recognized for rotation (avoids jitter/unintentional rotation)\n * @param threshold new threshold\n */\n set rotationThreshold(threshold) {\n this._featureContext.rotationThreshold = threshold;\n }\n /**\n * constructs a new movement controller system\n * @param _xrSessionManager an instance of WebXRSessionManager\n * @param options configuration object for this feature\n */\n constructor(_xrSessionManager, options) {\n var _a, _b, _c, _d, _e, _f;\n super(_xrSessionManager);\n this._controllers = {};\n this._currentRegistrationConfigurations = [];\n // forward direction for movement, which may differ from viewer pose.\n this._movementDirection = null;\n // unused\n this._tmpRotationMatrix = Matrix.Identity();\n this._tmpTranslationDirection = new Vector3();\n this._tmpMovementTranslation = new Vector3();\n this._attachController = (xrController) => {\n if (this._controllers[xrController.uniqueId]) {\n // already attached\n return;\n }\n this._controllers[xrController.uniqueId] = {\n xrController,\n registeredComponents: [],\n };\n const controllerData = this._controllers[xrController.uniqueId];\n // movement controller only available to gamepad-enabled input sources.\n if (controllerData.xrController.inputSource.targetRayMode === \"tracked-pointer\" && controllerData.xrController.inputSource.gamepad) {\n // motion controller support\n const initController = () => {\n if (xrController.motionController) {\n for (const registration of this._currentRegistrationConfigurations) {\n let component = null;\n if (registration.allowedComponentTypes) {\n for (const componentType of registration.allowedComponentTypes) {\n const componentOfType = xrController.motionController.getComponentOfType(componentType);\n if (componentOfType !== null) {\n component = componentOfType;\n break;\n }\n }\n }\n if (registration.mainComponentOnly) {\n const mainComponent = xrController.motionController.getMainComponent();\n if (mainComponent === null) {\n continue;\n }\n component = mainComponent;\n }\n if (typeof registration.componentSelectionPredicate === \"function\") {\n // if does not match we do want to ignore a previously found component\n component = registration.componentSelectionPredicate(xrController);\n }\n if (component && registration.forceHandedness) {\n if (xrController.inputSource.handedness !== registration.forceHandedness) {\n continue; // do not register\n }\n }\n if (component === null) {\n continue; // do not register\n }\n const registeredComponent = {\n registrationConfiguration: registration,\n component,\n };\n controllerData.registeredComponents.push(registeredComponent);\n if (\"axisChangedHandler\" in registration) {\n registeredComponent.onAxisChangedObserver = component.onAxisValueChangedObservable.add((axesData) => {\n registration.axisChangedHandler(axesData, this._movementState, this._featureContext, this._xrInput);\n });\n }\n if (\"buttonChangedhandler\" in registration) {\n registeredComponent.onButtonChangedObserver = component.onButtonStateChangedObservable.add(() => {\n if (component.changes.pressed) {\n registration.buttonChangedhandler(component.changes.pressed, this._movementState, this._featureContext, this._xrInput);\n }\n });\n }\n }\n }\n };\n if (xrController.motionController) {\n initController();\n }\n else {\n xrController.onMotionControllerInitObservable.addOnce(() => {\n initController();\n });\n }\n }\n };\n if (!options || options.xrInput === undefined) {\n Tools.Error('WebXRControllerMovement feature requires \"xrInput\" option.');\n return;\n }\n if (Array.isArray(options.customRegistrationConfigurations)) {\n this._currentRegistrationConfigurations = options.customRegistrationConfigurations;\n }\n else {\n this._currentRegistrationConfigurations = WebXRControllerMovement.REGISTRATIONS.default;\n }\n // synchronized from feature setter properties\n this._featureContext = {\n movementEnabled: options.movementEnabled || true,\n movementOrientationFollowsViewerPose: (_a = options.movementOrientationFollowsViewerPose) !== null && _a !== void 0 ? _a : true,\n movementSpeed: (_b = options.movementSpeed) !== null && _b !== void 0 ? _b : 1,\n movementThreshold: (_c = options.movementThreshold) !== null && _c !== void 0 ? _c : 0.25,\n rotationEnabled: (_d = options.rotationEnabled) !== null && _d !== void 0 ? _d : true,\n rotationSpeed: (_e = options.rotationSpeed) !== null && _e !== void 0 ? _e : 1.0,\n rotationThreshold: (_f = options.rotationThreshold) !== null && _f !== void 0 ? _f : 0.25,\n };\n this._movementState = {\n moveX: 0,\n moveY: 0,\n rotateX: 0,\n rotateY: 0,\n };\n this._xrInput = options.xrInput;\n }\n attach() {\n if (!super.attach()) {\n return false;\n }\n this._xrInput.controllers.forEach(this._attachController);\n this._addNewAttachObserver(this._xrInput.onControllerAddedObservable, this._attachController);\n this._addNewAttachObserver(this._xrInput.onControllerRemovedObservable, (controller) => {\n // REMOVE the controller\n this._detachController(controller.uniqueId);\n });\n return true;\n }\n detach() {\n if (!super.detach()) {\n return false;\n }\n Object.keys(this._controllers).forEach((controllerId) => {\n this._detachController(controllerId);\n });\n this._controllers = {};\n return true;\n }\n /**\n * Occurs on every XR frame.\n * @param _xrFrame\n */\n _onXRFrame(_xrFrame) {\n if (!this.attach) {\n return;\n }\n if (this._movementDirection === null) {\n this._movementDirection = this._xrInput.xrCamera.rotationQuaternion.clone();\n }\n if (this._movementState.rotateX !== 0 && this._featureContext.rotationEnabled) {\n // smooth rotation\n const deltaMillis = this._xrSessionManager.scene.getEngine().getDeltaTime();\n const rotationY = deltaMillis * 0.001 * this._featureContext.rotationSpeed * this._movementState.rotateX * (this._xrSessionManager.scene.useRightHandedSystem ? -1 : 1);\n if (this._featureContext.movementOrientationFollowsViewerPose === true) {\n this._xrInput.xrCamera.cameraRotation.y += rotationY;\n this._movementDirection = this._xrInput.xrCamera.rotationQuaternion.multiply(Quaternion.RotationYawPitchRoll(rotationY, 0, 0));\n }\n else {\n // movement orientation direction does not affect camera. We use rotation speed multiplier\n // otherwise need to implement inertia and constraints for same feel as TargetCamera.\n this._movementDirection.multiplyInPlace(Quaternion.RotationYawPitchRoll(rotationY * 3.0, 0, 0));\n }\n }\n else if (this._featureContext.movementOrientationFollowsViewerPose === true) {\n this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion);\n }\n if ((this._movementState.moveX !== 0 || this._movementState.moveY !== 0) && this._featureContext.movementEnabled) {\n Matrix.FromQuaternionToRef(this._movementDirection, this._tmpRotationMatrix);\n this._tmpTranslationDirection.set(this._movementState.moveX, 0, this._movementState.moveY * (this._xrSessionManager.scene.useRightHandedSystem ? 1.0 : -1.0));\n // move according to forward direction based on camera speed\n Vector3.TransformCoordinatesToRef(this._tmpTranslationDirection, this._tmpRotationMatrix, this._tmpMovementTranslation);\n this._tmpMovementTranslation.scaleInPlace(this._xrInput.xrCamera._computeLocalCameraSpeed() * this._featureContext.movementSpeed);\n this._xrInput.xrCamera.cameraDirection.addInPlace(this._tmpMovementTranslation);\n }\n }\n _detachController(xrControllerUniqueId) {\n const controllerData = this._controllers[xrControllerUniqueId];\n if (!controllerData) {\n return;\n }\n for (const registeredComponent of controllerData.registeredComponents) {\n if (registeredComponent.onAxisChangedObserver) {\n registeredComponent.component.onAxisValueChangedObservable.remove(registeredComponent.onAxisChangedObserver);\n }\n if (registeredComponent.onButtonChangedObserver) {\n registeredComponent.component.onButtonStateChangedObservable.remove(registeredComponent.onButtonChangedObserver);\n }\n }\n // remove from the map\n delete this._controllers[xrControllerUniqueId];\n }\n}\n/**\n * The module's name\n */\nWebXRControllerMovement.Name = WebXRFeatureName.MOVEMENT;\n/**\n * Standard controller configurations.\n */\nWebXRControllerMovement.REGISTRATIONS = {\n default: [\n {\n allowedComponentTypes: [WebXRControllerComponent.THUMBSTICK_TYPE, WebXRControllerComponent.TOUCHPAD_TYPE],\n forceHandedness: \"left\",\n axisChangedHandler: (axes, movementState, featureContext) => {\n movementState.rotateX = Math.abs(axes.x) > featureContext.rotationThreshold ? axes.x : 0;\n movementState.rotateY = Math.abs(axes.y) > featureContext.rotationThreshold ? axes.y : 0;\n },\n },\n {\n allowedComponentTypes: [WebXRControllerComponent.THUMBSTICK_TYPE, WebXRControllerComponent.TOUCHPAD_TYPE],\n forceHandedness: \"right\",\n axisChangedHandler: (axes, movementState, featureContext) => {\n movementState.moveX = Math.abs(axes.x) > featureContext.movementThreshold ? axes.x : 0;\n movementState.moveY = Math.abs(axes.y) > featureContext.movementThreshold ? axes.y : 0;\n },\n },\n ],\n};\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the webxr specs version\n */\nWebXRControllerMovement.Version = 1;\nWebXRFeaturesManager.AddWebXRFeature(WebXRControllerMovement.Name, (xrSessionManager, options) => {\n return () => new WebXRControllerMovement(xrSessionManager, options);\n}, WebXRControllerMovement.Version, true);\n//# sourceMappingURL=WebXRControllerMovement.js.map","import { WebGLHardwareTexture } from \"../../Engines/WebGL/webGLHardwareTexture.js\";\nimport { InternalTexture, InternalTextureSource } from \"../../Materials/Textures/internalTexture.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nimport { WebXRFeatureName, WebXRFeaturesManager } from \"../webXRFeaturesManager.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\n\nimport { Color3 } from \"../../Maths/math.color.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { DirectionalLight } from \"../../Lights/directionalLight.js\";\nimport { BaseTexture } from \"../../Materials/Textures/baseTexture.js\";\nimport { SphericalHarmonics, SphericalPolynomial } from \"../../Maths/sphericalPolynomial.js\";\nimport { LightConstants } from \"../../Lights/lightConstants.js\";\n/**\n * Light Estimation Feature\n *\n * @since 5.0.0\n */\nexport class WebXRLightEstimation extends WebXRAbstractFeature {\n /**\n * Creates a new instance of the light estimation feature\n * @param _xrSessionManager an instance of WebXRSessionManager\n * @param options options to use when constructing this feature\n */\n constructor(_xrSessionManager, \n /**\n * options to use when constructing this feature\n */\n options) {\n super(_xrSessionManager);\n this.options = options;\n this._canvasContext = null;\n this._reflectionCubeMap = null;\n this._xrLightEstimate = null;\n this._xrLightProbe = null;\n this._xrWebGLBinding = null;\n this._lightDirection = Vector3.Up().negateInPlace();\n this._lightColor = Color3.White();\n this._intensity = 1;\n this._sphericalHarmonics = new SphericalHarmonics();\n this._cubeMapPollTime = Date.now();\n this._lightEstimationPollTime = Date.now();\n /**\n * ARCore's reflection cube map size is 16x16.\n * Once other systems support this feature we will need to change this to be dynamic.\n * see https://github.com/immersive-web/lighting-estimation/blob/main/lighting-estimation-explainer.md#cube-map-open-questions\n */\n this._reflectionCubeMapTextureSize = 16;\n /**\n * If createDirectionalLightSource is set to true this light source will be created automatically.\n * Otherwise this can be set with an external directional light source.\n * This light will be updated whenever the light estimation values change.\n */\n this.directionalLight = null;\n /**\n * This observable will notify when the reflection cube map is updated.\n */\n this.onReflectionCubeMapUpdatedObservable = new Observable();\n /**\n * Event Listener for \"reflectionchange\" events.\n */\n this._updateReflectionCubeMap = () => {\n var _a;\n if (!this._xrLightProbe) {\n return;\n }\n // check poll time, do not update if it has not been long enough\n if (this.options.cubeMapPollInterval) {\n const now = Date.now();\n if (now - this._cubeMapPollTime < this.options.cubeMapPollInterval) {\n return;\n }\n this._cubeMapPollTime = now;\n }\n const lp = this._getXRGLBinding().getReflectionCubeMap(this._xrLightProbe);\n if (lp && this._reflectionCubeMap) {\n if (!this._reflectionCubeMap._texture) {\n const internalTexture = new InternalTexture(this._xrSessionManager.scene.getEngine(), InternalTextureSource.Unknown);\n internalTexture.isCube = true;\n internalTexture.invertY = false;\n internalTexture._useSRGBBuffer = this.options.reflectionFormat === \"srgba8\";\n internalTexture.format = 5;\n internalTexture.generateMipMaps = true;\n internalTexture.type = this.options.reflectionFormat !== \"srgba8\" ? 2 : 0;\n internalTexture.samplingMode = 3;\n internalTexture.width = this._reflectionCubeMapTextureSize;\n internalTexture.height = this._reflectionCubeMapTextureSize;\n internalTexture._cachedWrapU = 1;\n internalTexture._cachedWrapV = 1;\n internalTexture._hardwareTexture = new WebGLHardwareTexture(lp, this._getCanvasContext());\n this._reflectionCubeMap._texture = internalTexture;\n }\n else {\n (_a = this._reflectionCubeMap._texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.set(lp);\n this._reflectionCubeMap._texture.getEngine().resetTextureCache();\n }\n this._reflectionCubeMap._texture.isReady = true;\n this._xrSessionManager.scene.markAllMaterialsAsDirty(1);\n this.onReflectionCubeMapUpdatedObservable.notifyObservers(this._reflectionCubeMap);\n }\n };\n this.xrNativeFeatureName = \"light-estimation\";\n if (this.options.createDirectionalLightSource) {\n this.directionalLight = new DirectionalLight(\"light estimation directional\", this._lightDirection, this._xrSessionManager.scene);\n this.directionalLight.position = new Vector3(0, 8, 0);\n // intensity will be set later\n this.directionalLight.intensity = 0;\n this.directionalLight.falloffType = LightConstants.FALLOFF_GLTF;\n }\n // https://immersive-web.github.io/lighting-estimation/\n Tools.Warn(\"light-estimation is an experimental and unstable feature.\");\n }\n /**\n * While the estimated cube map is expected to update over time to better reflect the user's environment as they move around those changes are unlikely to happen with every XRFrame.\n * Since creating and processing the cube map is potentially expensive, especially if mip maps are needed, you can listen to the onReflectionCubeMapUpdatedObservable to determine\n * when it has been updated.\n */\n get reflectionCubeMapTexture() {\n return this._reflectionCubeMap;\n }\n /**\n * The most recent light estimate. Available starting on the first frame where the device provides a light probe.\n */\n get xrLightingEstimate() {\n if (this._xrLightEstimate) {\n return {\n lightColor: this._lightColor,\n lightDirection: this._lightDirection,\n lightIntensity: this._intensity,\n sphericalHarmonics: this._sphericalHarmonics,\n };\n }\n return this._xrLightEstimate;\n }\n _getCanvasContext() {\n if (this._canvasContext === null) {\n this._canvasContext = this._xrSessionManager.scene.getEngine()._gl;\n }\n return this._canvasContext;\n }\n _getXRGLBinding() {\n if (this._xrWebGLBinding === null) {\n const context = this._getCanvasContext();\n this._xrWebGLBinding = new XRWebGLBinding(this._xrSessionManager.session, context);\n }\n return this._xrWebGLBinding;\n }\n /**\n * attach this feature\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n attach() {\n var _a;\n if (!super.attach()) {\n return false;\n }\n const reflectionFormat = (_a = this.options.reflectionFormat) !== null && _a !== void 0 ? _a : (this._xrSessionManager.session.preferredReflectionFormat || \"srgba8\");\n this.options.reflectionFormat = reflectionFormat;\n this._xrSessionManager.session\n .requestLightProbe({\n reflectionFormat,\n })\n .then((xrLightProbe) => {\n this._xrLightProbe = xrLightProbe;\n if (!this.options.disableCubeMapReflection) {\n if (!this._reflectionCubeMap) {\n this._reflectionCubeMap = new BaseTexture(this._xrSessionManager.scene);\n this._reflectionCubeMap._isCube = true;\n this._reflectionCubeMap.coordinatesMode = 3;\n if (this.options.setSceneEnvironmentTexture) {\n this._xrSessionManager.scene.environmentTexture = this._reflectionCubeMap;\n }\n }\n this._xrLightProbe.addEventListener(\"reflectionchange\", this._updateReflectionCubeMap);\n }\n });\n return true;\n }\n /**\n * detach this feature.\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n detach() {\n const detached = super.detach();\n if (this._xrLightProbe !== null && !this.options.disableCubeMapReflection) {\n this._xrLightProbe.removeEventListener(\"reflectionchange\", this._updateReflectionCubeMap);\n this._xrLightProbe = null;\n }\n this._canvasContext = null;\n this._xrLightEstimate = null;\n // When the session ends (on detach) we must clear our XRWebGLBinging instance, which references the ended session.\n this._xrWebGLBinding = null;\n return detached;\n }\n /**\n * Dispose this feature and all of the resources attached\n */\n dispose() {\n super.dispose();\n this.onReflectionCubeMapUpdatedObservable.clear();\n if (this.directionalLight) {\n this.directionalLight.dispose();\n this.directionalLight = null;\n }\n if (this._reflectionCubeMap !== null) {\n if (this._reflectionCubeMap._texture) {\n this._reflectionCubeMap._texture.dispose();\n }\n this._reflectionCubeMap.dispose();\n this._reflectionCubeMap = null;\n }\n }\n _onXRFrame(_xrFrame) {\n var _a;\n if (this._xrLightProbe !== null) {\n if (this.options.lightEstimationPollInterval) {\n const now = Date.now();\n if (now - this._lightEstimationPollTime < this.options.lightEstimationPollInterval) {\n return;\n }\n this._lightEstimationPollTime = now;\n }\n this._xrLightEstimate = _xrFrame.getLightEstimate(this._xrLightProbe);\n if (this._xrLightEstimate) {\n this._intensity = Math.max(1.0, this._xrLightEstimate.primaryLightIntensity.x, this._xrLightEstimate.primaryLightIntensity.y, this._xrLightEstimate.primaryLightIntensity.z);\n const rhsFactor = this._xrSessionManager.scene.useRightHandedSystem ? 1.0 : -1.0;\n // recreate the vector caches, so that the last one provided to the user will persist\n if (this.options.disableVectorReuse) {\n this._lightDirection = new Vector3();\n this._lightColor = new Color3();\n if (this.directionalLight) {\n this.directionalLight.direction = this._lightDirection;\n this.directionalLight.diffuse = this._lightColor;\n }\n }\n this._lightDirection.copyFromFloats(this._xrLightEstimate.primaryLightDirection.x, this._xrLightEstimate.primaryLightDirection.y, this._xrLightEstimate.primaryLightDirection.z * rhsFactor);\n this._lightColor.copyFromFloats(this._xrLightEstimate.primaryLightIntensity.x / this._intensity, this._xrLightEstimate.primaryLightIntensity.y / this._intensity, this._xrLightEstimate.primaryLightIntensity.z / this._intensity);\n this._sphericalHarmonics.updateFromFloatsArray(this._xrLightEstimate.sphericalHarmonicsCoefficients);\n if (this._reflectionCubeMap && !this.options.disableSphericalPolynomial) {\n this._reflectionCubeMap.sphericalPolynomial = this._reflectionCubeMap.sphericalPolynomial || new SphericalPolynomial();\n (_a = this._reflectionCubeMap.sphericalPolynomial) === null || _a === void 0 ? void 0 : _a.updateFromHarmonics(this._sphericalHarmonics);\n }\n // direction from instead of direction to\n this._lightDirection.negateInPlace();\n // set the values after calculating them\n if (this.directionalLight) {\n this.directionalLight.direction.copyFrom(this._lightDirection);\n this.directionalLight.intensity = Math.min(this._intensity, 1.0);\n this.directionalLight.diffuse.copyFrom(this._lightColor);\n }\n }\n }\n }\n}\n/**\n * The module's name\n */\nWebXRLightEstimation.Name = WebXRFeatureName.LIGHT_ESTIMATION;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRLightEstimation.Version = 1;\n// register the plugin\nWebXRFeaturesManager.AddWebXRFeature(WebXRLightEstimation.Name, (xrSessionManager, options) => {\n return () => new WebXRLightEstimation(xrSessionManager, options);\n}, WebXRLightEstimation.Version, false);\n//# sourceMappingURL=WebXRLightEstimation.js.map","import { TmpVectors, Vector2, Vector3 } from \"../../Maths/math.vector.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { WebXRFeatureName, WebXRFeaturesManager } from \"../webXRFeaturesManager.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nclass CircleBuffer {\n constructor(numSamples, initializer) {\n this._samples = [];\n this._idx = 0;\n for (let idx = 0; idx < numSamples; ++idx) {\n this._samples.push(initializer ? initializer() : Vector2.Zero());\n }\n }\n get length() {\n return this._samples.length;\n }\n push(x, y) {\n this._idx = (this._idx + this._samples.length - 1) % this._samples.length;\n this.at(0).copyFromFloats(x, y);\n }\n at(idx) {\n if (idx >= this._samples.length) {\n throw new Error(\"Index out of bounds\");\n }\n return this._samples[(this._idx + idx) % this._samples.length];\n }\n}\nclass FirstStepDetector {\n constructor() {\n this._samples = new CircleBuffer(20);\n this._entropy = 0;\n this.onFirstStepDetected = new Observable();\n }\n update(posX, posY, forwardX, forwardY) {\n this._samples.push(posX, posY);\n const origin = this._samples.at(0);\n this._entropy *= this._entropyDecayFactor;\n this._entropy += Vector2.Distance(origin, this._samples.at(1));\n if (this._entropy > this._entropyThreshold) {\n return;\n }\n let samePointIdx;\n for (samePointIdx = this._samePointCheckStartIdx; samePointIdx < this._samples.length; ++samePointIdx) {\n if (Vector2.DistanceSquared(origin, this._samples.at(samePointIdx)) < this._samePointSquaredDistanceThreshold) {\n break;\n }\n }\n if (samePointIdx === this._samples.length) {\n return;\n }\n let apexDistSquared = -1;\n let apexIdx = 0;\n for (let distSquared, idx = 1; idx < samePointIdx; ++idx) {\n distSquared = Vector2.DistanceSquared(origin, this._samples.at(idx));\n if (distSquared > apexDistSquared) {\n apexIdx = idx;\n apexDistSquared = distSquared;\n }\n }\n if (apexDistSquared < this._apexSquaredDistanceThreshold) {\n return;\n }\n const apex = this._samples.at(apexIdx);\n const axis = apex.subtract(origin);\n axis.normalize();\n const vec = TmpVectors.Vector2[0];\n let dot;\n let sample;\n let sumSquaredProjectionDistances = 0;\n for (let idx = 1; idx < samePointIdx; ++idx) {\n sample = this._samples.at(idx);\n sample.subtractToRef(origin, vec);\n dot = Vector2.Dot(axis, vec);\n sumSquaredProjectionDistances += vec.lengthSquared() - dot * dot;\n }\n if (sumSquaredProjectionDistances > samePointIdx * this._squaredProjectionDistanceThreshold) {\n return;\n }\n const forwardVec = TmpVectors.Vector3[0];\n forwardVec.set(forwardX, forwardY, 0);\n const axisVec = TmpVectors.Vector3[1];\n axisVec.set(axis.x, axis.y, 0);\n const isApexLeft = Vector3.Cross(forwardVec, axisVec).z > 0;\n const leftApex = origin.clone();\n const rightApex = origin.clone();\n apex.subtractToRef(origin, axis);\n if (isApexLeft) {\n axis.scaleAndAddToRef(this._axisToApexShrinkFactor, leftApex);\n axis.scaleAndAddToRef(this._axisToApexExtendFactor, rightApex);\n }\n else {\n axis.scaleAndAddToRef(this._axisToApexExtendFactor, leftApex);\n axis.scaleAndAddToRef(this._axisToApexShrinkFactor, rightApex);\n }\n this.onFirstStepDetected.notifyObservers({\n leftApex: leftApex,\n rightApex: rightApex,\n currentPosition: origin,\n currentStepDirection: isApexLeft ? \"right\" : \"left\",\n });\n }\n reset() {\n for (let idx = 0; idx < this._samples.length; ++idx) {\n this._samples.at(idx).copyFromFloats(0, 0);\n }\n }\n get _samePointCheckStartIdx() {\n return Math.floor(this._samples.length / 3);\n }\n get _samePointSquaredDistanceThreshold() {\n return 0.03 * 0.03;\n }\n get _apexSquaredDistanceThreshold() {\n return 0.09 * 0.09;\n }\n get _squaredProjectionDistanceThreshold() {\n return 0.03 * 0.03;\n }\n get _axisToApexShrinkFactor() {\n return 0.8;\n }\n get _axisToApexExtendFactor() {\n return -1.6;\n }\n get _entropyDecayFactor() {\n return 0.93;\n }\n get _entropyThreshold() {\n return 0.4;\n }\n}\nclass WalkingTracker {\n constructor(leftApex, rightApex, currentPosition, currentStepDirection) {\n this._leftApex = new Vector2();\n this._rightApex = new Vector2();\n this._currentPosition = new Vector2();\n this._axis = new Vector2();\n this._axisLength = -1;\n this._forward = new Vector2();\n this._steppingLeft = false;\n this._t = -1;\n this._maxT = -1;\n this._maxTPosition = new Vector2();\n this._vitality = 0;\n this.onMovement = new Observable();\n this.onFootfall = new Observable();\n this._reset(leftApex, rightApex, currentPosition, currentStepDirection === \"left\");\n }\n _reset(leftApex, rightApex, currentPosition, steppingLeft) {\n this._leftApex.copyFrom(leftApex);\n this._rightApex.copyFrom(rightApex);\n this._steppingLeft = steppingLeft;\n if (this._steppingLeft) {\n this._leftApex.subtractToRef(this._rightApex, this._axis);\n this._forward.copyFromFloats(-this._axis.y, this._axis.x);\n }\n else {\n this._rightApex.subtractToRef(this._leftApex, this._axis);\n this._forward.copyFromFloats(this._axis.y, -this._axis.x);\n }\n this._axisLength = this._axis.length();\n this._forward.scaleInPlace(1 / this._axisLength);\n this._updateTAndVitality(currentPosition.x, currentPosition.y);\n this._maxT = this._t;\n this._maxTPosition.copyFrom(currentPosition);\n this._vitality = 1;\n }\n _updateTAndVitality(x, y) {\n this._currentPosition.copyFromFloats(x, y);\n if (this._steppingLeft) {\n this._currentPosition.subtractInPlace(this._rightApex);\n }\n else {\n this._currentPosition.subtractInPlace(this._leftApex);\n }\n const priorT = this._t;\n const dot = Vector2.Dot(this._currentPosition, this._axis);\n this._t = dot / (this._axisLength * this._axisLength);\n const projDistSquared = this._currentPosition.lengthSquared() - (dot / this._axisLength) * (dot / this._axisLength);\n // TODO: Extricate the magic.\n this._vitality *= 0.92 - 100 * Math.max(projDistSquared - 0.0016, 0) + Math.max(this._t - priorT, 0);\n }\n update(x, y) {\n if (this._vitality < this._vitalityThreshold) {\n return false;\n }\n const priorT = this._t;\n this._updateTAndVitality(x, y);\n if (this._t > this._maxT) {\n this._maxT = this._t;\n this._maxTPosition.copyFromFloats(x, y);\n }\n if (this._vitality < this._vitalityThreshold) {\n return false;\n }\n if (this._t > priorT) {\n this.onMovement.notifyObservers({ deltaT: this._t - priorT });\n if (priorT < 0.5 && this._t >= 0.5) {\n this.onFootfall.notifyObservers({ foot: this._steppingLeft ? \"left\" : \"right\" });\n }\n }\n if (this._t < 0.95 * this._maxT) {\n this._currentPosition.copyFromFloats(x, y);\n if (this._steppingLeft) {\n this._leftApex.copyFrom(this._maxTPosition);\n }\n else {\n this._rightApex.copyFrom(this._maxTPosition);\n }\n this._reset(this._leftApex, this._rightApex, this._currentPosition, !this._steppingLeft);\n }\n if (this._axisLength < 0.03) {\n return false;\n }\n return true;\n }\n get _vitalityThreshold() {\n return 0.1;\n }\n get forward() {\n return this._forward;\n }\n}\nclass Walker {\n static get _MillisecondsPerUpdate() {\n // 15 FPS\n return 1000 / 15;\n }\n constructor(engine) {\n this._detector = new FirstStepDetector();\n this._walker = null;\n this._movement = new Vector2();\n this._millisecondsSinceLastUpdate = Walker._MillisecondsPerUpdate;\n this.movementThisFrame = Vector3.Zero();\n this._engine = engine;\n this._detector.onFirstStepDetected.add((event) => {\n if (!this._walker) {\n this._walker = new WalkingTracker(event.leftApex, event.rightApex, event.currentPosition, event.currentStepDirection);\n this._walker.onFootfall.add(() => {\n console.log(\"Footfall!\");\n });\n this._walker.onMovement.add((event) => {\n this._walker.forward.scaleAndAddToRef(0.024 * event.deltaT, this._movement);\n });\n }\n });\n }\n update(position, forward) {\n forward.y = 0;\n forward.normalize();\n // Enforce reduced framerate\n this._millisecondsSinceLastUpdate += this._engine.getDeltaTime();\n if (this._millisecondsSinceLastUpdate >= Walker._MillisecondsPerUpdate) {\n this._millisecondsSinceLastUpdate -= Walker._MillisecondsPerUpdate;\n this._detector.update(position.x, position.z, forward.x, forward.z);\n if (this._walker) {\n const updated = this._walker.update(position.x, position.z);\n if (!updated) {\n this._walker = null;\n }\n }\n this._movement.scaleInPlace(0.85);\n }\n this.movementThisFrame.set(this._movement.x, 0, this._movement.y);\n }\n}\n/**\n * A module that will enable VR locomotion by detecting when the user walks in place.\n */\nexport class WebXRWalkingLocomotion extends WebXRAbstractFeature {\n /**\n * The module's name.\n */\n static get Name() {\n return WebXRFeatureName.WALKING_LOCOMOTION;\n }\n /**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number has no external basis.\n */\n static get Version() {\n return 1;\n }\n /**\n * The target to be articulated by walking locomotion.\n * When the walking locomotion feature detects walking in place, this element's\n * X and Z coordinates will be modified to reflect locomotion. This target should\n * be either the XR space's origin (i.e., the parent node of the WebXRCamera) or\n * the WebXRCamera itself. Note that the WebXRCamera path will modify the position\n * of the WebXRCamera directly and is thus discouraged.\n */\n get locomotionTarget() {\n return this._locomotionTarget;\n }\n /**\n * The target to be articulated by walking locomotion.\n * When the walking locomotion feature detects walking in place, this element's\n * X and Z coordinates will be modified to reflect locomotion. This target should\n * be either the XR space's origin (i.e., the parent node of the WebXRCamera) or\n * the WebXRCamera itself. Note that the WebXRCamera path will modify the position\n * of the WebXRCamera directly and is thus discouraged.\n */\n set locomotionTarget(locomotionTarget) {\n this._locomotionTarget = locomotionTarget;\n this._isLocomotionTargetWebXRCamera = this._locomotionTarget.getClassName() === \"WebXRCamera\";\n }\n /**\n * Construct a new Walking Locomotion feature.\n * @param sessionManager manager for the current XR session\n * @param options creation options, prominently including the vector target for locomotion\n */\n constructor(sessionManager, options) {\n super(sessionManager);\n this._up = new Vector3();\n this._forward = new Vector3();\n this._position = new Vector3();\n this._movement = new Vector3();\n this._sessionManager = sessionManager;\n this.locomotionTarget = options.locomotionTarget;\n if (this._isLocomotionTargetWebXRCamera) {\n Logger.Warn(\"Using walking locomotion directly on a WebXRCamera may have unintended interactions with other XR techniques. Using an XR space parent is highly recommended\");\n }\n }\n /**\n * Checks whether this feature is compatible with the current WebXR session.\n * Walking locomotion is only compatible with \"immersive-vr\" sessions.\n * @returns true if compatible, false otherwise\n */\n isCompatible() {\n return this._sessionManager.sessionMode === undefined || this._sessionManager.sessionMode === \"immersive-vr\";\n }\n /**\n * Attaches the feature.\n * Typically called automatically by the features manager.\n * @returns true if attach succeeded, false otherwise\n */\n attach() {\n if (!this.isCompatible || !super.attach()) {\n return false;\n }\n this._walker = new Walker(this._sessionManager.scene.getEngine());\n return true;\n }\n /**\n * Detaches the feature.\n * Typically called automatically by the features manager.\n * @returns true if detach succeeded, false otherwise\n */\n detach() {\n if (!super.detach()) {\n return false;\n }\n this._walker = null;\n return true;\n }\n _onXRFrame(frame) {\n const pose = frame.getViewerPose(this._sessionManager.baseReferenceSpace);\n if (!pose) {\n return;\n }\n const handednessScalar = this.locomotionTarget.getScene().useRightHandedSystem ? 1 : -1;\n const m = pose.transform.matrix;\n this._up.copyFromFloats(m[4], m[5], handednessScalar * m[6]);\n this._forward.copyFromFloats(m[8], m[9], handednessScalar * m[10]);\n this._position.copyFromFloats(m[12], m[13], handednessScalar * m[14]);\n // Compute the nape position\n this._forward.scaleAndAddToRef(0.05, this._position);\n this._up.scaleAndAddToRef(-0.05, this._position);\n this._walker.update(this._position, this._forward);\n this._movement.copyFrom(this._walker.movementThisFrame);\n if (!this._isLocomotionTargetWebXRCamera) {\n Vector3.TransformNormalToRef(this._movement, this.locomotionTarget.getWorldMatrix(), this._movement);\n }\n this.locomotionTarget.position.addInPlace(this._movement);\n }\n}\n//register the plugin\nWebXRFeaturesManager.AddWebXRFeature(WebXRWalkingLocomotion.Name, (xrSessionManager, options) => {\n return () => new WebXRWalkingLocomotion(xrSessionManager, options);\n}, WebXRWalkingLocomotion.Version, false);\n//# sourceMappingURL=WebXRWalkingLocomotion.js.map","import { WebXRFeatureName, WebXRFeaturesManager } from \"../webXRFeaturesManager.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nimport { Matrix } from \"../../Maths/math.vector.js\";\nimport { RenderTargetTexture } from \"../../Materials/Textures/renderTargetTexture.js\";\n\nimport { ShaderMaterial } from \"../../Materials/shaderMaterial.js\";\nimport \"../../Shaders/velocity.fragment.js\";\nimport \"../../Shaders/velocity.vertex.js\";\n/**\n * Used for Space Warp render process\n */\nexport class XRSpaceWarpRenderTarget extends RenderTargetTexture {\n /**\n * Creates a Space Warp render target\n * @param motionVectorTexture WebGLTexture provided by WebGLSubImage\n * @param depthStencilTexture WebGLTexture provided by WebGLSubImage\n * @param scene scene used with the render target\n * @param size the size of the render target (used for each view)\n */\n constructor(motionVectorTexture, depthStencilTexture, scene, size = 512) {\n super(\"spacewarp rtt\", size, scene, false, true, 2, false, undefined, false, false, true, undefined, true);\n this._originalPairing = [];\n this._previousWorldMatrices = [];\n this._previousTransforms = [Matrix.Identity(), Matrix.Identity()];\n this._renderTarget = this.getScene()\n .getEngine()\n .createMultiviewRenderTargetTexture(this.getRenderWidth(), this.getRenderHeight(), motionVectorTexture, depthStencilTexture);\n this._renderTarget._disposeOnlyFramebuffers = true;\n this._texture = this._renderTarget.texture;\n this._texture.isMultiview = true;\n this._texture.format = 5;\n if (scene) {\n this._velocityMaterial = new ShaderMaterial(\"velocity shader material\", scene, {\n vertex: \"velocity\",\n fragment: \"velocity\",\n }, {\n uniforms: [\"world\", \"previousWorld\", \"viewProjection\", \"viewProjectionR\", \"previousViewProjection\", \"previousViewProjectionR\"],\n });\n this._velocityMaterial._materialHelperNeedsPreviousMatrices = true;\n this._velocityMaterial.onBindObservable.add((mesh) => {\n // mesh. getWorldMatrix can be incorrect under rare conditions (e.g. when using a effective mesh in the render function).\n // If the case arise that will require changing it we will need to change the bind process in the material class to also provide the world matrix as a parameter\n this._previousWorldMatrices[mesh.uniqueId] = this._previousWorldMatrices[mesh.uniqueId] || mesh.getWorldMatrix();\n this._velocityMaterial.getEffect().setMatrix(\"previousWorld\", this._previousWorldMatrices[mesh.uniqueId]);\n this._previousWorldMatrices[mesh.uniqueId] = mesh.getWorldMatrix();\n // now set the scene's previous matrix\n this._velocityMaterial.getEffect().setMatrix(\"previousViewProjection\", this._previousTransforms[0]);\n // multiview for sure\n this._velocityMaterial.getEffect().setMatrix(\"previousViewProjectionR\", this._previousTransforms[1]);\n // store the previous (current, to be exact) transforms\n this._previousTransforms[0].copyFrom(scene.getTransformMatrix());\n this._previousTransforms[1].copyFrom(scene._transformMatrixR);\n });\n this._velocityMaterial.freeze();\n }\n }\n /**\n * {@inheritDoc}\n */\n render(useCameraPostProcess = false, dumpForDebug = false) {\n // Swap to use velocity material\n this._originalPairing.length = 0;\n const scene = this.getScene();\n // set the velocity material to render the velocity RTT\n if (scene && this._velocityMaterial) {\n scene.getActiveMeshes().forEach((mesh) => {\n this._originalPairing.push([mesh, mesh.material]);\n mesh.material = this._velocityMaterial;\n });\n }\n super.render(useCameraPostProcess, dumpForDebug);\n // Restore original materials\n this._originalPairing.forEach((tuple) => {\n tuple[0].material = tuple[1];\n });\n }\n /**\n * @internal\n */\n _bindFrameBuffer() {\n if (!this._renderTarget) {\n return;\n }\n this.getScene().getEngine().bindSpaceWarpFramebuffer(this._renderTarget);\n }\n /**\n * Gets the number of views the corresponding to the texture (eg. a SpaceWarpRenderTarget will have > 1)\n * @returns the view count\n */\n getViewCount() {\n return 2;\n }\n /**\n * {@inheritdoc}\n */\n dispose() {\n super.dispose();\n this._velocityMaterial.dispose();\n this._previousTransforms.length = 0;\n this._previousWorldMatrices.length = 0;\n this._originalPairing.length = 0;\n }\n}\n/**\n * WebXR Space Warp Render Target Texture Provider\n */\nexport class WebXRSpaceWarpRenderTargetTextureProvider {\n constructor(_scene, _xrSessionManager, _xrWebGLBinding) {\n this._scene = _scene;\n this._xrSessionManager = _xrSessionManager;\n this._xrWebGLBinding = _xrWebGLBinding;\n this._lastSubImages = new Map();\n this._renderTargetTextures = new Map();\n this._engine = _scene.getEngine();\n }\n _getSubImageForView(view) {\n const layerWrapper = this._xrSessionManager._getBaseLayerWrapper();\n if (!layerWrapper) {\n throw new Error(\"For Space Warp, the base layer should be a WebXR Projection Layer.\");\n }\n if (layerWrapper.layerType !== \"XRProjectionLayer\") {\n throw new Error('For Space Warp, the base layer type should \"XRProjectionLayer\".');\n }\n const layer = layerWrapper.layer;\n return this._xrWebGLBinding.getViewSubImage(layer, view);\n }\n _setViewportForSubImage(viewport, subImage) {\n viewport.x = 0;\n viewport.y = 0;\n viewport.width = subImage.motionVectorTextureWidth;\n viewport.height = subImage.motionVectorTextureHeight;\n }\n _createRenderTargetTexture(width, height, framebuffer, motionVectorTexture, depthStencilTexture) {\n if (!this._engine) {\n throw new Error(\"Engine is disposed\");\n }\n const textureSize = { width, height };\n // Create render target texture from the internal texture\n const renderTargetTexture = new XRSpaceWarpRenderTarget(motionVectorTexture, depthStencilTexture, this._scene, textureSize);\n const renderTargetWrapper = renderTargetTexture.renderTarget;\n if (framebuffer) {\n renderTargetWrapper._framebuffer = framebuffer;\n }\n // Create internal texture\n renderTargetWrapper._colorTextureArray = motionVectorTexture;\n renderTargetWrapper._depthStencilTextureArray = depthStencilTexture;\n renderTargetTexture.disableRescaling();\n renderTargetTexture.renderListPredicate = () => true;\n return renderTargetTexture;\n }\n _getRenderTargetForSubImage(subImage, view) {\n const lastSubImage = this._lastSubImages.get(view);\n let renderTargetTexture = this._renderTargetTextures.get(view.eye);\n const width = subImage.motionVectorTextureWidth;\n const height = subImage.motionVectorTextureHeight;\n if (!renderTargetTexture || (lastSubImage === null || lastSubImage === void 0 ? void 0 : lastSubImage.textureWidth) !== width || (lastSubImage === null || lastSubImage === void 0 ? void 0 : lastSubImage.textureHeight) != height) {\n renderTargetTexture = this._createRenderTargetTexture(width, height, null, subImage.motionVectorTexture, subImage.depthStencilTexture);\n this._renderTargetTextures.set(view.eye, renderTargetTexture);\n this._framebufferDimensions = {\n framebufferWidth: width,\n framebufferHeight: height,\n };\n }\n this._lastSubImages.set(view, subImage);\n return renderTargetTexture;\n }\n /**\n * {@inheritDoc}\n */\n trySetViewportForView(viewport, view) {\n const subImage = this._lastSubImages.get(view) || this._getSubImageForView(view);\n if (subImage) {\n this._setViewportForSubImage(viewport, subImage);\n return true;\n }\n return false;\n }\n /**\n * Access the motion vector (which will turn on Space Warp)\n * @param view the view to access the motion vector texture for\n */\n accessMotionVector(view) {\n const subImage = this._getSubImageForView(view);\n if (subImage) {\n // Meta Quest Browser uses accessing these textures as a sign for turning on Space Warp\n subImage.motionVectorTexture;\n subImage.depthStencilTexture;\n }\n }\n /**\n * {@inheritDoc}\n */\n getRenderTargetTextureForEye(_eye) {\n return null;\n }\n /**\n * {@inheritDoc}\n */\n getRenderTargetTextureForView(view) {\n const subImage = this._getSubImageForView(view);\n if (subImage) {\n return this._getRenderTargetForSubImage(subImage, view);\n }\n return null;\n }\n /**\n * {@inheritDoc}\n */\n dispose() {\n this._renderTargetTextures.forEach((rtt) => rtt.dispose());\n this._renderTargetTextures.clear();\n }\n}\n/**\n * the WebXR Space Warp feature.\n */\nexport class WebXRSpaceWarp extends WebXRAbstractFeature {\n /**\n * constructor for the space warp feature\n * @param _xrSessionManager the xr session manager for this feature\n */\n constructor(_xrSessionManager) {\n super(_xrSessionManager);\n /**\n * {@inheritdoc}\n */\n this.dependsOn = [WebXRFeatureName.LAYERS];\n this.xrNativeFeatureName = \"space-warp\";\n this._xrSessionManager.scene.needsPreviousWorldMatrices = true;\n }\n /**\n * Attach this feature.\n * Will usually be called by the features manager.\n *\n * @returns true if successful.\n */\n attach() {\n if (!super.attach()) {\n return false;\n }\n const engine = this._xrSessionManager.scene.getEngine();\n this._glContext = engine._gl;\n this._xrWebGLBinding = new XRWebGLBinding(this._xrSessionManager.session, this._glContext);\n this.spaceWarpRTTProvider = new WebXRSpaceWarpRenderTargetTextureProvider(this._xrSessionManager.scene, this._xrSessionManager, this._xrWebGLBinding);\n this._xrSessionManager.scene.onAfterRenderObservable.add(this._onAfterRender.bind(this));\n return true;\n }\n _onAfterRender() {\n if (this.attached && this._renderTargetTexture) {\n this._renderTargetTexture.render(false, false);\n }\n }\n /**\n * {@inheritdoc}\n */\n isCompatible() {\n return this._xrSessionManager.scene.getEngine().getCaps().colorBufferHalfFloat || false;\n }\n /**\n * {@inheritdoc}\n */\n dispose() {\n super.dispose();\n }\n _onXRFrame(_xrFrame) {\n const pose = _xrFrame.getViewerPose(this._xrSessionManager.referenceSpace);\n if (!pose) {\n return;\n }\n // get the first view to which we will create a texture (or update it)\n const view = pose.views[0];\n this._renderTargetTexture = this._renderTargetTexture || this.spaceWarpRTTProvider.getRenderTargetTextureForView(view);\n this.spaceWarpRTTProvider.accessMotionVector(view);\n }\n}\n/**\n * The module's name\n */\nWebXRSpaceWarp.Name = WebXRFeatureName.SPACE_WARP;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRSpaceWarp.Version = 1;\n//register the plugin\nWebXRFeaturesManager.AddWebXRFeature(WebXRSpaceWarp.Name, (xrSessionManager) => {\n return () => new WebXRSpaceWarp(xrSessionManager);\n}, WebXRSpaceWarp.Version, false);\n//# sourceMappingURL=WebXRSpaceWarp.js.map","export * from \"./WebXRAbstractFeature.js\";\nexport * from \"./WebXRHitTestLegacy.js\";\nexport * from \"./WebXRAnchorSystem.js\";\nexport * from \"./WebXRPlaneDetector.js\";\nexport * from \"./WebXRBackgroundRemover.js\";\nexport * from \"./WebXRControllerTeleportation.js\";\nexport * from \"./WebXRControllerPointerSelection.js\";\nexport * from \"./WebXRControllerPhysics.js\";\nexport * from \"./WebXRHitTest.js\";\nexport * from \"./WebXRFeaturePointSystem.js\";\nexport * from \"./WebXRHandTracking.js\";\nexport * from \"./WebXRMeshDetector.js\";\nexport * from \"./WebXRImageTracking.js\";\nexport * from \"./WebXRNearInteraction.js\";\nexport * from \"./WebXRDOMOverlay.js\";\nexport * from \"./WebXRControllerMovement.js\";\nexport * from \"./WebXRLightEstimation.js\";\nexport * from \"./WebXREyeTracking.js\";\nexport * from \"./WebXRWalkingLocomotion.js\";\nexport * from \"./WebXRLayers.js\";\nexport * from \"./WebXRDepthSensing.js\";\nexport * from \"./WebXRSpaceWarp.js\";\n//# sourceMappingURL=index.js.map","import { WebXRAbstractMotionController } from \"./webXRAbstractMotionController.js\";\nimport { WebXRMotionControllerManager } from \"./webXRMotionControllerManager.js\";\nimport { Mesh } from \"../../Meshes/mesh.js\";\nimport { Quaternion } from \"../../Maths/math.vector.js\";\nimport { SceneLoader } from \"../../Loading/sceneLoader.js\";\nimport { Logger } from \"../../Misc/logger.js\";\n/**\n * The motion controller class for all microsoft mixed reality controllers\n */\nexport class WebXRMicrosoftMixedRealityController extends WebXRAbstractMotionController {\n constructor(scene, gamepadObject, handedness) {\n super(scene, MixedRealityProfile[\"left-right\"], gamepadObject, handedness);\n // use this in the future - https://github.com/immersive-web/webxr-input-profiles/tree/master/packages/assets/profiles/microsoft\n this._mapping = {\n defaultButton: {\n valueNodeName: \"VALUE\",\n unpressedNodeName: \"UNPRESSED\",\n pressedNodeName: \"PRESSED\",\n },\n defaultAxis: {\n valueNodeName: \"VALUE\",\n minNodeName: \"MIN\",\n maxNodeName: \"MAX\",\n },\n buttons: {\n \"xr-standard-trigger\": {\n rootNodeName: \"SELECT\",\n componentProperty: \"button\",\n states: [\"default\", \"touched\", \"pressed\"],\n },\n \"xr-standard-squeeze\": {\n rootNodeName: \"GRASP\",\n componentProperty: \"state\",\n states: [\"pressed\"],\n },\n \"xr-standard-touchpad\": {\n rootNodeName: \"TOUCHPAD_PRESS\",\n labelAnchorNodeName: \"squeeze-label\",\n touchPointNodeName: \"TOUCH\", // TODO - use this for visual feedback\n },\n \"xr-standard-thumbstick\": {\n rootNodeName: \"THUMBSTICK_PRESS\",\n componentProperty: \"state\",\n states: [\"pressed\"],\n },\n },\n axes: {\n \"xr-standard-touchpad\": {\n \"x-axis\": {\n rootNodeName: \"TOUCHPAD_TOUCH_X\",\n },\n \"y-axis\": {\n rootNodeName: \"TOUCHPAD_TOUCH_Y\",\n },\n },\n \"xr-standard-thumbstick\": {\n \"x-axis\": {\n rootNodeName: \"THUMBSTICK_X\",\n },\n \"y-axis\": {\n rootNodeName: \"THUMBSTICK_Y\",\n },\n },\n },\n };\n this.profileId = \"microsoft-mixed-reality\";\n }\n _getFilenameAndPath() {\n let filename = \"\";\n if (this.handedness === \"left\") {\n filename = WebXRMicrosoftMixedRealityController.MODEL_LEFT_FILENAME;\n }\n else {\n // Right is the default if no hand is specified\n filename = WebXRMicrosoftMixedRealityController.MODEL_RIGHT_FILENAME;\n }\n const device = \"default\";\n const path = WebXRMicrosoftMixedRealityController.MODEL_BASE_URL + device + \"/\";\n return {\n filename,\n path,\n };\n }\n _getModelLoadingConstraints() {\n const glbLoaded = SceneLoader.IsPluginForExtensionAvailable(\".glb\");\n if (!glbLoaded) {\n Logger.Warn(\"glTF / glb loaded was not registered, using generic controller instead\");\n }\n return glbLoaded;\n }\n _processLoadedModel(_meshes) {\n if (!this.rootMesh) {\n return;\n }\n // Button Meshes\n this.getComponentIds().forEach((id, i) => {\n if (this.disableAnimation) {\n return;\n }\n if (id && this.rootMesh) {\n const buttonMap = this._mapping.buttons[id];\n const buttonMeshName = buttonMap.rootNodeName;\n if (!buttonMeshName) {\n Logger.Log(\"Skipping unknown button at index: \" + i + \" with mapped name: \" + id);\n return;\n }\n const buttonMesh = this._getChildByName(this.rootMesh, buttonMeshName);\n if (!buttonMesh) {\n Logger.Warn(\"Missing button mesh with name: \" + buttonMeshName);\n return;\n }\n buttonMap.valueMesh = this._getImmediateChildByName(buttonMesh, this._mapping.defaultButton.valueNodeName);\n buttonMap.pressedMesh = this._getImmediateChildByName(buttonMesh, this._mapping.defaultButton.pressedNodeName);\n buttonMap.unpressedMesh = this._getImmediateChildByName(buttonMesh, this._mapping.defaultButton.unpressedNodeName);\n if (buttonMap.valueMesh && buttonMap.pressedMesh && buttonMap.unpressedMesh) {\n const comp = this.getComponent(id);\n if (comp) {\n comp.onButtonStateChangedObservable.add((component) => {\n this._lerpTransform(buttonMap, component.value);\n }, undefined, true);\n }\n }\n else {\n // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.\n Logger.Warn(\"Missing button submesh under mesh with name: \" + buttonMeshName);\n }\n }\n });\n // Axis Meshes\n this.getComponentIds().forEach((id) => {\n const comp = this.getComponent(id);\n if (!comp.isAxes()) {\n return;\n }\n [\"x-axis\", \"y-axis\"].forEach((axis) => {\n if (!this.rootMesh) {\n return;\n }\n const axisMap = this._mapping.axes[id][axis];\n const axisMesh = this._getChildByName(this.rootMesh, axisMap.rootNodeName);\n if (!axisMesh) {\n Logger.Warn(\"Missing axis mesh with name: \" + axisMap.rootNodeName);\n return;\n }\n axisMap.valueMesh = this._getImmediateChildByName(axisMesh, this._mapping.defaultAxis.valueNodeName);\n axisMap.minMesh = this._getImmediateChildByName(axisMesh, this._mapping.defaultAxis.minNodeName);\n axisMap.maxMesh = this._getImmediateChildByName(axisMesh, this._mapping.defaultAxis.maxNodeName);\n if (axisMap.valueMesh && axisMap.minMesh && axisMap.maxMesh) {\n if (comp) {\n comp.onAxisValueChangedObservable.add((axisValues) => {\n const value = axis === \"x-axis\" ? axisValues.x : axisValues.y;\n this._lerpTransform(axisMap, value, true);\n }, undefined, true);\n }\n }\n else {\n // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.\n Logger.Warn(\"Missing axis submesh under mesh with name: \" + axisMap.rootNodeName);\n }\n });\n });\n }\n _setRootMesh(meshes) {\n this.rootMesh = new Mesh(this.profileId + \" \" + this.handedness, this.scene);\n this.rootMesh.isPickable = false;\n let rootMesh;\n // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'\n for (let i = 0; i < meshes.length; i++) {\n const mesh = meshes[i];\n mesh.isPickable = false;\n if (!mesh.parent) {\n // Handle root node, attach to the new parentMesh\n rootMesh = mesh;\n }\n }\n if (rootMesh) {\n rootMesh.setParent(this.rootMesh);\n }\n if (!this.scene.useRightHandedSystem) {\n this.rootMesh.rotationQuaternion = Quaternion.FromEulerAngles(0, Math.PI, 0);\n }\n }\n _updateModel() {\n // no-op. model is updated using observables.\n }\n}\n/**\n * The base url used to load the left and right controller models\n */\nWebXRMicrosoftMixedRealityController.MODEL_BASE_URL = \"https://controllers.babylonjs.com/microsoft/\";\n/**\n * The name of the left controller model file\n */\nWebXRMicrosoftMixedRealityController.MODEL_LEFT_FILENAME = \"left.glb\";\n/**\n * The name of the right controller model file\n */\nWebXRMicrosoftMixedRealityController.MODEL_RIGHT_FILENAME = \"right.glb\";\n// register the profile\nWebXRMotionControllerManager.RegisterController(\"windows-mixed-reality\", (xrInput, scene) => {\n return new WebXRMicrosoftMixedRealityController(scene, xrInput.gamepad, xrInput.handedness);\n});\n// https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/microsoft/microsoft-mixed-reality.json\nconst MixedRealityProfile = {\n left: {\n selectComponentId: \"xr-standard-trigger\",\n components: {\n \"xr-standard-trigger\": {\n type: \"trigger\",\n gamepadIndices: {\n button: 0,\n },\n rootNodeName: \"xr_standard_trigger\",\n visualResponses: {\n xr_standard_trigger_pressed: {\n componentProperty: \"button\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_trigger_pressed_value\",\n minNodeName: \"xr_standard_trigger_pressed_min\",\n maxNodeName: \"xr_standard_trigger_pressed_max\",\n },\n },\n },\n \"xr-standard-squeeze\": {\n type: \"squeeze\",\n gamepadIndices: {\n button: 1,\n },\n rootNodeName: \"xr_standard_squeeze\",\n visualResponses: {\n xr_standard_squeeze_pressed: {\n componentProperty: \"button\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_squeeze_pressed_value\",\n minNodeName: \"xr_standard_squeeze_pressed_min\",\n maxNodeName: \"xr_standard_squeeze_pressed_max\",\n },\n },\n },\n \"xr-standard-touchpad\": {\n type: \"touchpad\",\n gamepadIndices: {\n button: 2,\n xAxis: 0,\n yAxis: 1,\n },\n rootNodeName: \"xr_standard_touchpad\",\n visualResponses: {\n xr_standard_touchpad_pressed: {\n componentProperty: \"button\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_touchpad_pressed_value\",\n minNodeName: \"xr_standard_touchpad_pressed_min\",\n maxNodeName: \"xr_standard_touchpad_pressed_max\",\n },\n xr_standard_touchpad_xaxis_pressed: {\n componentProperty: \"xAxis\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_touchpad_xaxis_pressed_value\",\n minNodeName: \"xr_standard_touchpad_xaxis_pressed_min\",\n maxNodeName: \"xr_standard_touchpad_xaxis_pressed_max\",\n },\n xr_standard_touchpad_yaxis_pressed: {\n componentProperty: \"yAxis\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_touchpad_yaxis_pressed_value\",\n minNodeName: \"xr_standard_touchpad_yaxis_pressed_min\",\n maxNodeName: \"xr_standard_touchpad_yaxis_pressed_max\",\n },\n xr_standard_touchpad_xaxis_touched: {\n componentProperty: \"xAxis\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_touchpad_xaxis_touched_value\",\n minNodeName: \"xr_standard_touchpad_xaxis_touched_min\",\n maxNodeName: \"xr_standard_touchpad_xaxis_touched_max\",\n },\n xr_standard_touchpad_yaxis_touched: {\n componentProperty: \"yAxis\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_touchpad_yaxis_touched_value\",\n minNodeName: \"xr_standard_touchpad_yaxis_touched_min\",\n maxNodeName: \"xr_standard_touchpad_yaxis_touched_max\",\n },\n xr_standard_touchpad_axes_touched: {\n componentProperty: \"state\",\n states: [\"touched\", \"pressed\"],\n valueNodeProperty: \"visibility\",\n valueNodeName: \"xr_standard_touchpad_axes_touched_value\",\n },\n },\n touchPointNodeName: \"xr_standard_touchpad_axes_touched_value\",\n },\n \"xr-standard-thumbstick\": {\n type: \"thumbstick\",\n gamepadIndices: {\n button: 3,\n xAxis: 2,\n yAxis: 3,\n },\n rootNodeName: \"xr_standard_thumbstick\",\n visualResponses: {\n xr_standard_thumbstick_pressed: {\n componentProperty: \"button\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_thumbstick_pressed_value\",\n minNodeName: \"xr_standard_thumbstick_pressed_min\",\n maxNodeName: \"xr_standard_thumbstick_pressed_max\",\n },\n xr_standard_thumbstick_xaxis_pressed: {\n componentProperty: \"xAxis\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_thumbstick_xaxis_pressed_value\",\n minNodeName: \"xr_standard_thumbstick_xaxis_pressed_min\",\n maxNodeName: \"xr_standard_thumbstick_xaxis_pressed_max\",\n },\n xr_standard_thumbstick_yaxis_pressed: {\n componentProperty: \"yAxis\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_thumbstick_yaxis_pressed_value\",\n minNodeName: \"xr_standard_thumbstick_yaxis_pressed_min\",\n maxNodeName: \"xr_standard_thumbstick_yaxis_pressed_max\",\n },\n },\n },\n },\n gamepadMapping: \"xr-standard\",\n rootNodeName: \"microsoft-mixed-reality-left\",\n assetPath: \"left.glb\",\n },\n right: {\n selectComponentId: \"xr-standard-trigger\",\n components: {\n \"xr-standard-trigger\": {\n type: \"trigger\",\n gamepadIndices: {\n button: 0,\n },\n rootNodeName: \"xr_standard_trigger\",\n visualResponses: {\n xr_standard_trigger_pressed: {\n componentProperty: \"button\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_trigger_pressed_value\",\n minNodeName: \"xr_standard_trigger_pressed_min\",\n maxNodeName: \"xr_standard_trigger_pressed_max\",\n },\n },\n },\n \"xr-standard-squeeze\": {\n type: \"squeeze\",\n gamepadIndices: {\n button: 1,\n },\n rootNodeName: \"xr_standard_squeeze\",\n visualResponses: {\n xr_standard_squeeze_pressed: {\n componentProperty: \"button\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_squeeze_pressed_value\",\n minNodeName: \"xr_standard_squeeze_pressed_min\",\n maxNodeName: \"xr_standard_squeeze_pressed_max\",\n },\n },\n },\n \"xr-standard-touchpad\": {\n type: \"touchpad\",\n gamepadIndices: {\n button: 2,\n xAxis: 0,\n yAxis: 1,\n },\n rootNodeName: \"xr_standard_touchpad\",\n visualResponses: {\n xr_standard_touchpad_pressed: {\n componentProperty: \"button\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_touchpad_pressed_value\",\n minNodeName: \"xr_standard_touchpad_pressed_min\",\n maxNodeName: \"xr_standard_touchpad_pressed_max\",\n },\n xr_standard_touchpad_xaxis_pressed: {\n componentProperty: \"xAxis\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_touchpad_xaxis_pressed_value\",\n minNodeName: \"xr_standard_touchpad_xaxis_pressed_min\",\n maxNodeName: \"xr_standard_touchpad_xaxis_pressed_max\",\n },\n xr_standard_touchpad_yaxis_pressed: {\n componentProperty: \"yAxis\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_touchpad_yaxis_pressed_value\",\n minNodeName: \"xr_standard_touchpad_yaxis_pressed_min\",\n maxNodeName: \"xr_standard_touchpad_yaxis_pressed_max\",\n },\n xr_standard_touchpad_xaxis_touched: {\n componentProperty: \"xAxis\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_touchpad_xaxis_touched_value\",\n minNodeName: \"xr_standard_touchpad_xaxis_touched_min\",\n maxNodeName: \"xr_standard_touchpad_xaxis_touched_max\",\n },\n xr_standard_touchpad_yaxis_touched: {\n componentProperty: \"yAxis\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_touchpad_yaxis_touched_value\",\n minNodeName: \"xr_standard_touchpad_yaxis_touched_min\",\n maxNodeName: \"xr_standard_touchpad_yaxis_touched_max\",\n },\n xr_standard_touchpad_axes_touched: {\n componentProperty: \"state\",\n states: [\"touched\", \"pressed\"],\n valueNodeProperty: \"visibility\",\n valueNodeName: \"xr_standard_touchpad_axes_touched_value\",\n },\n },\n touchPointNodeName: \"xr_standard_touchpad_axes_touched_value\",\n },\n \"xr-standard-thumbstick\": {\n type: \"thumbstick\",\n gamepadIndices: {\n button: 3,\n xAxis: 2,\n yAxis: 3,\n },\n rootNodeName: \"xr_standard_thumbstick\",\n visualResponses: {\n xr_standard_thumbstick_pressed: {\n componentProperty: \"button\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_thumbstick_pressed_value\",\n minNodeName: \"xr_standard_thumbstick_pressed_min\",\n maxNodeName: \"xr_standard_thumbstick_pressed_max\",\n },\n xr_standard_thumbstick_xaxis_pressed: {\n componentProperty: \"xAxis\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_thumbstick_xaxis_pressed_value\",\n minNodeName: \"xr_standard_thumbstick_xaxis_pressed_min\",\n maxNodeName: \"xr_standard_thumbstick_xaxis_pressed_max\",\n },\n xr_standard_thumbstick_yaxis_pressed: {\n componentProperty: \"yAxis\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_thumbstick_yaxis_pressed_value\",\n minNodeName: \"xr_standard_thumbstick_yaxis_pressed_min\",\n maxNodeName: \"xr_standard_thumbstick_yaxis_pressed_max\",\n },\n },\n },\n },\n gamepadMapping: \"xr-standard\",\n rootNodeName: \"microsoft-mixed-reality-right\",\n assetPath: \"right.glb\",\n },\n};\n//# sourceMappingURL=webXRMicrosoftMixedRealityController.js.map","import { WebXRAbstractMotionController } from \"./webXRAbstractMotionController.js\";\nimport { WebXRMotionControllerManager } from \"./webXRMotionControllerManager.js\";\nimport { Mesh } from \"../../Meshes/mesh.js\";\nimport { Quaternion } from \"../../Maths/math.vector.js\";\n/**\n * The motion controller class for oculus touch (quest, rift).\n * This class supports legacy mapping as well the standard xr mapping\n */\nexport class WebXROculusTouchMotionController extends WebXRAbstractMotionController {\n constructor(scene, gamepadObject, handedness, _legacyMapping = false, _forceLegacyControllers = false) {\n super(scene, OculusTouchLayouts[handedness], gamepadObject, handedness);\n this._forceLegacyControllers = _forceLegacyControllers;\n this.profileId = \"oculus-touch\";\n }\n _getFilenameAndPath() {\n let filename = \"\";\n if (this.handedness === \"left\") {\n filename = WebXROculusTouchMotionController.MODEL_LEFT_FILENAME;\n }\n else {\n // Right is the default if no hand is specified\n filename = WebXROculusTouchMotionController.MODEL_RIGHT_FILENAME;\n }\n const path = this._isQuest() ? WebXROculusTouchMotionController.QUEST_MODEL_BASE_URL : WebXROculusTouchMotionController.MODEL_BASE_URL;\n return {\n filename,\n path,\n };\n }\n _getModelLoadingConstraints() {\n return true;\n }\n _processLoadedModel(_meshes) {\n const isQuest = this._isQuest();\n const triggerDirection = this.handedness === \"right\" ? -1 : 1;\n this.getComponentIds().forEach((id) => {\n const comp = id && this.getComponent(id);\n if (comp) {\n comp.onButtonStateChangedObservable.add((component) => {\n if (!this.rootMesh || this.disableAnimation) {\n return;\n }\n switch (id) {\n case \"xr-standard-trigger\": // index trigger\n if (!isQuest) {\n this._modelRootNode.getChildren()[3].rotation.x = -component.value * 0.2;\n this._modelRootNode.getChildren()[3].position.y = -component.value * 0.005;\n this._modelRootNode.getChildren()[3].position.z = -component.value * 0.005;\n }\n return;\n case \"xr-standard-squeeze\": // secondary trigger\n if (!isQuest) {\n this._modelRootNode.getChildren()[4].position.x = triggerDirection * component.value * 0.0035;\n }\n return;\n case \"xr-standard-thumbstick\": // thumbstick\n return;\n case \"a-button\":\n case \"x-button\":\n if (!isQuest) {\n if (component.pressed) {\n this._modelRootNode.getChildren()[1].position.y = -0.001;\n }\n else {\n this._modelRootNode.getChildren()[1].position.y = 0;\n }\n }\n return;\n case \"b-button\":\n case \"y-button\":\n if (!isQuest) {\n if (component.pressed) {\n this._modelRootNode.getChildren()[2].position.y = -0.001;\n }\n else {\n this._modelRootNode.getChildren()[2].position.y = 0;\n }\n }\n return;\n }\n }, undefined, true);\n }\n });\n }\n _setRootMesh(meshes) {\n this.rootMesh = new Mesh(this.profileId + \" \" + this.handedness, this.scene);\n if (!this.scene.useRightHandedSystem) {\n this.rootMesh.rotationQuaternion = Quaternion.FromEulerAngles(0, Math.PI, 0);\n }\n meshes.forEach((mesh) => {\n mesh.isPickable = false;\n });\n if (this._isQuest()) {\n this._modelRootNode = meshes[0];\n }\n else {\n this._modelRootNode = meshes[1];\n this.rootMesh.position.y = 0.034;\n this.rootMesh.position.z = 0.052;\n }\n this._modelRootNode.parent = this.rootMesh;\n }\n _updateModel() {\n // no-op. model is updated using observables.\n }\n /**\n * Is this the new type of oculus touch. At the moment both have the same profile and it is impossible to differentiate\n * between the touch and touch 2.\n */\n _isQuest() {\n // this is SADLY the only way to currently check. Until proper profiles will be available.\n return !!navigator.userAgent.match(/Quest/gi) && !this._forceLegacyControllers;\n }\n}\n/**\n * The base url used to load the left and right controller models\n */\nWebXROculusTouchMotionController.MODEL_BASE_URL = \"https://controllers.babylonjs.com/oculus/\";\n/**\n * The name of the left controller model file\n */\nWebXROculusTouchMotionController.MODEL_LEFT_FILENAME = \"left.babylon\";\n/**\n * The name of the right controller model file\n */\nWebXROculusTouchMotionController.MODEL_RIGHT_FILENAME = \"right.babylon\";\n/**\n * Base Url for the Quest controller model.\n */\nWebXROculusTouchMotionController.QUEST_MODEL_BASE_URL = \"https://controllers.babylonjs.com/oculusQuest/\";\n// register the profile\nWebXRMotionControllerManager.RegisterController(\"oculus-touch\", (xrInput, scene) => {\n return new WebXROculusTouchMotionController(scene, xrInput.gamepad, xrInput.handedness);\n});\nWebXRMotionControllerManager.RegisterController(\"oculus-touch-legacy\", (xrInput, scene) => {\n return new WebXROculusTouchMotionController(scene, xrInput.gamepad, xrInput.handedness, true);\n});\nconst OculusTouchLayouts = {\n left: {\n selectComponentId: \"xr-standard-trigger\",\n components: {\n \"xr-standard-trigger\": {\n type: \"trigger\",\n gamepadIndices: {\n button: 0,\n },\n rootNodeName: \"xr_standard_trigger\",\n visualResponses: {},\n },\n \"xr-standard-squeeze\": {\n type: \"squeeze\",\n gamepadIndices: {\n button: 1,\n },\n rootNodeName: \"xr_standard_squeeze\",\n visualResponses: {},\n },\n \"xr-standard-thumbstick\": {\n type: \"thumbstick\",\n gamepadIndices: {\n button: 3,\n xAxis: 2,\n yAxis: 3,\n },\n rootNodeName: \"xr_standard_thumbstick\",\n visualResponses: {},\n },\n \"x-button\": {\n type: \"button\",\n gamepadIndices: {\n button: 4,\n },\n rootNodeName: \"x_button\",\n visualResponses: {},\n },\n \"y-button\": {\n type: \"button\",\n gamepadIndices: {\n button: 5,\n },\n rootNodeName: \"y_button\",\n visualResponses: {},\n },\n thumbrest: {\n type: \"button\",\n gamepadIndices: {\n button: 6,\n },\n rootNodeName: \"thumbrest\",\n visualResponses: {},\n },\n },\n gamepadMapping: \"xr-standard\",\n rootNodeName: \"oculus-touch-v2-left\",\n assetPath: \"left.glb\",\n },\n right: {\n selectComponentId: \"xr-standard-trigger\",\n components: {\n \"xr-standard-trigger\": {\n type: \"trigger\",\n gamepadIndices: {\n button: 0,\n },\n rootNodeName: \"xr_standard_trigger\",\n visualResponses: {},\n },\n \"xr-standard-squeeze\": {\n type: \"squeeze\",\n gamepadIndices: {\n button: 1,\n },\n rootNodeName: \"xr_standard_squeeze\",\n visualResponses: {},\n },\n \"xr-standard-thumbstick\": {\n type: \"thumbstick\",\n gamepadIndices: {\n button: 3,\n xAxis: 2,\n yAxis: 3,\n },\n rootNodeName: \"xr_standard_thumbstick\",\n visualResponses: {},\n },\n \"a-button\": {\n type: \"button\",\n gamepadIndices: {\n button: 4,\n },\n rootNodeName: \"a_button\",\n visualResponses: {},\n },\n \"b-button\": {\n type: \"button\",\n gamepadIndices: {\n button: 5,\n },\n rootNodeName: \"b_button\",\n visualResponses: {},\n },\n thumbrest: {\n type: \"button\",\n gamepadIndices: {\n button: 6,\n },\n rootNodeName: \"thumbrest\",\n visualResponses: {},\n },\n },\n gamepadMapping: \"xr-standard\",\n rootNodeName: \"oculus-touch-v2-right\",\n assetPath: \"right.glb\",\n },\n};\n//# sourceMappingURL=webXROculusTouchMotionController.js.map","import { RegisterNativeTypeAsync } from \"../../Engines/nativeEngine.js\";\n/** @internal */\nexport class NativeXRFrame {\n get session() {\n return this._nativeImpl.session;\n }\n constructor(_nativeImpl) {\n this._nativeImpl = _nativeImpl;\n this._xrTransform = new XRRigidTransform();\n this._xrPose = {\n transform: this._xrTransform,\n emulatedPosition: false,\n };\n // Enough space for position, orientation\n this._xrPoseVectorData = new Float32Array(4 + 4);\n this.fillPoses = this._nativeImpl.fillPoses.bind(this._nativeImpl);\n this.getViewerPose = this._nativeImpl.getViewerPose.bind(this._nativeImpl);\n this.getHitTestResults = this._nativeImpl.getHitTestResults.bind(this._nativeImpl);\n this.getHitTestResultsForTransientInput = () => {\n throw new Error(\"XRFrame.getHitTestResultsForTransientInput not supported on native.\");\n };\n this.createAnchor = this._nativeImpl.createAnchor.bind(this._nativeImpl);\n this.getJointPose = this._nativeImpl.getJointPose.bind(this._nativeImpl);\n this.fillJointRadii = this._nativeImpl.fillJointRadii.bind(this._nativeImpl);\n this.getLightEstimate = () => {\n throw new Error(\"XRFrame.getLightEstimate not supported on native.\");\n };\n this.getImageTrackingResults = () => {\n var _a;\n return (_a = this._nativeImpl._imageTrackingResults) !== null && _a !== void 0 ? _a : [];\n };\n }\n getPose(space, baseSpace) {\n if (!this._nativeImpl.getPoseData(space, baseSpace, this._xrPoseVectorData.buffer, this._xrTransform.matrix.buffer)) {\n return undefined;\n }\n const position = this._xrTransform.position;\n position.x = this._xrPoseVectorData[0];\n position.y = this._xrPoseVectorData[1];\n position.z = this._xrPoseVectorData[2];\n position.w = this._xrPoseVectorData[3];\n const orientation = this._xrTransform.orientation;\n orientation.x = this._xrPoseVectorData[4];\n orientation.y = this._xrPoseVectorData[5];\n orientation.z = this._xrPoseVectorData[6];\n orientation.w = this._xrPoseVectorData[7];\n return this._xrPose;\n }\n get trackedAnchors() {\n return this._nativeImpl.trackedAnchors;\n }\n get worldInformation() {\n return this._nativeImpl.worldInformation;\n }\n get detectedPlanes() {\n return this._nativeImpl.detectedPlanes;\n }\n get featurePointCloud() {\n return this._nativeImpl.featurePointCloud;\n }\n getDepthInformation(view) {\n throw new Error(\"This function is not available in Babylon Native\");\n // return this._nativeImpl.getDepthInformation(view);\n }\n}\nRegisterNativeTypeAsync(\"NativeXRFrame\", NativeXRFrame);\n//# sourceMappingURL=nativeXRFrame.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./abstractScene.js\";\nexport * from \"./Actions/index.js\";\nexport * from \"./Animations/index.js\";\nexport * from \"./assetContainer.js\";\nexport * from \"./Audio/index.js\";\nexport * from \"./BakedVertexAnimation/index.js\";\nexport * from \"./Behaviors/index.js\";\nexport * from \"./Bones/index.js\";\nexport * from \"./Buffers/index.js\";\nexport * from \"./Cameras/index.js\";\nexport * from \"./Collisions/index.js\";\nexport * from \"./Compute/index.js\";\nexport * from \"./Culling/index.js\";\nexport * from \"./Debug/index.js\";\nexport * from \"./DeviceInput/index.js\";\nexport * from \"./Engines/index.js\";\nexport * from \"./Events/index.js\";\nexport * from \"./Gamepads/index.js\";\nexport * from \"./Gizmos/index.js\";\nexport * from \"./Helpers/index.js\";\nexport * from \"./Instrumentation/index.js\";\nexport * from \"./Layers/index.js\";\nexport * from \"./LensFlares/index.js\";\nexport * from \"./Lights/index.js\";\nexport * from \"./Loading/index.js\";\nexport * from \"./Materials/index.js\";\nexport * from \"./Maths/index.js\";\nexport * from \"./Meshes/index.js\";\nexport * from \"./Morph/index.js\";\nexport * from \"./Navigation/index.js\";\nexport * from \"./node.js\";\nexport * from \"./Offline/index.js\";\nexport * from \"./Particles/index.js\";\nexport * from \"./Physics/index.js\";\nexport * from \"./PostProcesses/index.js\";\nexport * from \"./Probes/index.js\";\nexport * from \"./Rendering/index.js\";\nexport * from \"./scene.js\";\nexport * from \"./sceneComponent.js\";\nexport * from \"./Sprites/index.js\";\nexport * from \"./States/index.js\";\nexport * from \"./Misc/index.js\";\nexport * from \"./XR/index.js\";\nexport * from \"./types.js\";\nexport * from \"./Compat/index.js\";\n//# sourceMappingURL=index.js.map","import { Tools } from \"@babylonjs/core/Misc/tools.js\";\nfunction validateAsync(data, rootUrl, fileName, getExternalResource) {\n const options = {\n externalResourceFunction: (uri) => getExternalResource(uri).then((value) => new Uint8Array(value)),\n };\n if (fileName) {\n options.uri = rootUrl === \"file:\" ? fileName : rootUrl + fileName;\n }\n return data instanceof ArrayBuffer ? GLTFValidator.validateBytes(new Uint8Array(data), options) : GLTFValidator.validateString(data, options);\n}\n/**\n * The worker function that gets converted to a blob url to pass into a worker.\n */\nfunction workerFunc() {\n const pendingExternalResources = [];\n onmessage = (message) => {\n const data = message.data;\n switch (data.id) {\n case \"init\": {\n importScripts(data.url);\n break;\n }\n case \"validate\": {\n validateAsync(data.data, data.rootUrl, data.fileName, (uri) => new Promise((resolve, reject) => {\n const index = pendingExternalResources.length;\n pendingExternalResources.push({ resolve, reject });\n postMessage({ id: \"getExternalResource\", index: index, uri: uri });\n })).then((value) => {\n postMessage({ id: \"validate.resolve\", value: value });\n }, (reason) => {\n postMessage({ id: \"validate.reject\", reason: reason });\n });\n break;\n }\n case \"getExternalResource.resolve\": {\n pendingExternalResources[data.index].resolve(data.value);\n break;\n }\n case \"getExternalResource.reject\": {\n pendingExternalResources[data.index].reject(data.reason);\n break;\n }\n }\n };\n}\n/**\n * glTF validation\n */\nexport class GLTFValidation {\n /**\n * Validate a glTF asset using the glTF-Validator.\n * @param data The JSON of a glTF or the array buffer of a binary glTF\n * @param rootUrl The root url for the glTF\n * @param fileName The file name for the glTF\n * @param getExternalResource The callback to get external resources for the glTF validator\n * @returns A promise that resolves with the glTF validation results once complete\n */\n static ValidateAsync(data, rootUrl, fileName, getExternalResource) {\n const dataCopy = ArrayBuffer.isView(data) ? data.slice().buffer : data;\n if (typeof Worker === \"function\") {\n return new Promise((resolve, reject) => {\n const workerContent = `${validateAsync}(${workerFunc})()`;\n const workerBlobUrl = URL.createObjectURL(new Blob([workerContent], { type: \"application/javascript\" }));\n const worker = new Worker(workerBlobUrl);\n const onError = (error) => {\n worker.removeEventListener(\"error\", onError);\n worker.removeEventListener(\"message\", onMessage);\n reject(error);\n };\n const onMessage = (message) => {\n const data = message.data;\n switch (data.id) {\n case \"getExternalResource\": {\n getExternalResource(data.uri).then((value) => {\n worker.postMessage({ id: \"getExternalResource.resolve\", index: data.index, value: value }, [value]);\n }, (reason) => {\n worker.postMessage({ id: \"getExternalResource.reject\", index: data.index, reason: reason });\n });\n break;\n }\n case \"validate.resolve\": {\n worker.removeEventListener(\"error\", onError);\n worker.removeEventListener(\"message\", onMessage);\n resolve(data.value);\n worker.terminate();\n break;\n }\n case \"validate.reject\": {\n worker.removeEventListener(\"error\", onError);\n worker.removeEventListener(\"message\", onMessage);\n reject(data.reason);\n worker.terminate();\n }\n }\n };\n worker.addEventListener(\"error\", onError);\n worker.addEventListener(\"message\", onMessage);\n worker.postMessage({ id: \"init\", url: this.Configuration.url });\n worker.postMessage({ id: \"validate\", data: dataCopy, rootUrl: rootUrl, fileName: fileName });\n });\n }\n else {\n if (!this._LoadScriptPromise) {\n this._LoadScriptPromise = Tools.LoadScriptAsync(this.Configuration.url);\n }\n return this._LoadScriptPromise.then(() => {\n return validateAsync(dataCopy, rootUrl, fileName, getExternalResource);\n });\n }\n }\n}\n/**\n * The configuration. Defaults to `{ url: \"https://preview.babylonjs.com/gltf_validator.js\" }`.\n */\nGLTFValidation.Configuration = {\n url: \"https://preview.babylonjs.com/gltf_validator.js\",\n};\n//# sourceMappingURL=glTFValidation.js.map","import { Observable } from \"@babylonjs/core/Misc/observable.js\";\nimport { Tools } from \"@babylonjs/core/Misc/tools.js\";\nimport { SceneLoader } from \"@babylonjs/core/Loading/sceneLoader.js\";\nimport { AssetContainer } from \"@babylonjs/core/assetContainer.js\";\nimport { Logger } from \"@babylonjs/core/Misc/logger.js\";\nimport { DataReader } from \"@babylonjs/core/Misc/dataReader.js\";\nimport { GLTFValidation } from \"./glTFValidation.js\";\nimport { DecodeBase64UrlToBinary } from \"@babylonjs/core/Misc/fileTools.js\";\nimport { RuntimeError, ErrorCodes } from \"@babylonjs/core/Misc/error.js\";\nfunction readAsync(arrayBuffer, byteOffset, byteLength) {\n try {\n return Promise.resolve(new Uint8Array(arrayBuffer, byteOffset, byteLength));\n }\n catch (e) {\n return Promise.reject(e);\n }\n}\nfunction readViewAsync(arrayBufferView, byteOffset, byteLength) {\n try {\n if (arrayBufferView.byteOffset + byteLength > arrayBufferView.byteLength) {\n throw new Error(\"Array length out of bounds.\");\n }\n return Promise.resolve(new Uint8Array(arrayBufferView.buffer, arrayBufferView.byteOffset + byteOffset, byteLength));\n }\n catch (e) {\n return Promise.reject(e);\n }\n}\n/**\n * Mode that determines the coordinate system to use.\n */\nexport var GLTFLoaderCoordinateSystemMode;\n(function (GLTFLoaderCoordinateSystemMode) {\n /**\n * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.\n */\n GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode[\"AUTO\"] = 0] = \"AUTO\";\n /**\n * Sets the useRightHandedSystem flag on the scene.\n */\n GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode[\"FORCE_RIGHT_HANDED\"] = 1] = \"FORCE_RIGHT_HANDED\";\n})(GLTFLoaderCoordinateSystemMode || (GLTFLoaderCoordinateSystemMode = {}));\n/**\n * Mode that determines what animations will start.\n */\nexport var GLTFLoaderAnimationStartMode;\n(function (GLTFLoaderAnimationStartMode) {\n /**\n * No animation will start.\n */\n GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode[\"NONE\"] = 0] = \"NONE\";\n /**\n * The first animation will start.\n */\n GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode[\"FIRST\"] = 1] = \"FIRST\";\n /**\n * All animations will start.\n */\n GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode[\"ALL\"] = 2] = \"ALL\";\n})(GLTFLoaderAnimationStartMode || (GLTFLoaderAnimationStartMode = {}));\n/**\n * Loader state.\n */\nexport var GLTFLoaderState;\n(function (GLTFLoaderState) {\n /**\n * The asset is loading.\n */\n GLTFLoaderState[GLTFLoaderState[\"LOADING\"] = 0] = \"LOADING\";\n /**\n * The asset is ready for rendering.\n */\n GLTFLoaderState[GLTFLoaderState[\"READY\"] = 1] = \"READY\";\n /**\n * The asset is completely loaded.\n */\n GLTFLoaderState[GLTFLoaderState[\"COMPLETE\"] = 2] = \"COMPLETE\";\n})(GLTFLoaderState || (GLTFLoaderState = {}));\n/**\n * File loader for loading glTF files into a scene.\n */\nexport class GLTFFileLoader {\n constructor() {\n // --------------\n // Common options\n // --------------\n /**\n * Raised when the asset has been parsed\n */\n this.onParsedObservable = new Observable();\n // ----------\n // V2 options\n // ----------\n /**\n * The coordinate system mode. Defaults to AUTO.\n */\n this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;\n /**\n * The animation start mode. Defaults to FIRST.\n */\n this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;\n /**\n * Defines if the loader should compile materials before raising the success callback. Defaults to false.\n */\n this.compileMaterials = false;\n /**\n * Defines if the loader should also compile materials with clip planes. Defaults to false.\n */\n this.useClipPlane = false;\n /**\n * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.\n */\n this.compileShadowGenerators = false;\n /**\n * Defines if the Alpha blended materials are only applied as coverage.\n * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.\n * If true, no extra effects are applied to transparent pixels.\n */\n this.transparencyAsCoverage = false;\n /**\n * Defines if the loader should use range requests when load binary glTF files from HTTP.\n * Enabling will disable offline support and glTF validator.\n * Defaults to false.\n */\n this.useRangeRequests = false;\n /**\n * Defines if the loader should create instances when multiple glTF nodes point to the same glTF mesh. Defaults to true.\n */\n this.createInstances = true;\n /**\n * Defines if the loader should always compute the bounding boxes of meshes and not use the min/max values from the position accessor. Defaults to false.\n */\n this.alwaysComputeBoundingBox = false;\n /**\n * If true, load all materials defined in the file, even if not used by any mesh. Defaults to false.\n */\n this.loadAllMaterials = false;\n /**\n * If true, load only the materials defined in the file. Defaults to false.\n */\n this.loadOnlyMaterials = false;\n /**\n * If true, do not load any materials defined in the file. Defaults to false.\n */\n this.skipMaterials = false;\n /**\n * If true, load the color (gamma encoded) textures into sRGB buffers (if supported by the GPU), which will yield more accurate results when sampling the texture. Defaults to true.\n */\n this.useSRGBBuffers = true;\n /**\n * When loading glTF animations, which are defined in seconds, target them to this FPS. Defaults to 60.\n */\n this.targetFps = 60;\n /**\n * Defines if the loader should always compute the nearest common ancestor of the skeleton joints instead of using `skin.skeleton`. Defaults to false.\n * Set this to true if loading assets with invalid `skin.skeleton` values.\n */\n this.alwaysComputeSkeletonRootNode = false;\n /**\n * Function called before loading a url referenced by the asset.\n * @param url\n */\n this.preprocessUrlAsync = (url) => Promise.resolve(url);\n /**\n * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.\n * Note that the observable is raised as soon as the mesh object is created, meaning some data may not have been setup yet for this mesh (vertex data, morph targets, material, ...)\n */\n this.onMeshLoadedObservable = new Observable();\n /**\n * Callback raised when the loader creates a skin after parsing the glTF properties of the skin node.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/importers/glTF/glTFSkinning#ignoring-the-transform-of-the-skinned-mesh\n * @param node - the transform node that corresponds to the original glTF skin node used for animations\n * @param skinnedNode - the transform node that is the skinned mesh itself or the parent of the skinned meshes\n */\n this.onSkinLoadedObservable = new Observable();\n /**\n * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.\n */\n this.onTextureLoadedObservable = new Observable();\n /**\n * Observable raised when the loader creates a material after parsing the glTF properties of the material.\n */\n this.onMaterialLoadedObservable = new Observable();\n /**\n * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.\n */\n this.onCameraLoadedObservable = new Observable();\n /**\n * Observable raised when the asset is completely loaded, immediately before the loader is disposed.\n * For assets with LODs, raised when all of the LODs are complete.\n * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.\n */\n this.onCompleteObservable = new Observable();\n /**\n * Observable raised when an error occurs.\n */\n this.onErrorObservable = new Observable();\n /**\n * Observable raised after the loader is disposed.\n */\n this.onDisposeObservable = new Observable();\n /**\n * Observable raised after a loader extension is created.\n * Set additional options for a loader extension in this event.\n */\n this.onExtensionLoadedObservable = new Observable();\n /**\n * Defines if the loader should validate the asset.\n */\n this.validate = false;\n /**\n * Observable raised after validation when validate is set to true. The event data is the result of the validation.\n */\n this.onValidatedObservable = new Observable();\n this._loader = null;\n this._state = null;\n this._requests = new Array();\n /**\n * Name of the loader (\"gltf\")\n */\n this.name = \"gltf\";\n /** @internal */\n this.extensions = {\n \".gltf\": { isBinary: false },\n \".glb\": { isBinary: true },\n };\n /**\n * Observable raised when the loader state changes.\n */\n this.onLoaderStateChangedObservable = new Observable();\n this._logIndentLevel = 0;\n this._loggingEnabled = false;\n /** @internal */\n this._log = this._logDisabled;\n this._capturePerformanceCounters = false;\n /** @internal */\n this._startPerformanceCounter = this._startPerformanceCounterDisabled;\n /** @internal */\n this._endPerformanceCounter = this._endPerformanceCounterDisabled;\n }\n /**\n * Raised when the asset has been parsed\n */\n set onParsed(callback) {\n if (this._onParsedObserver) {\n this.onParsedObservable.remove(this._onParsedObserver);\n }\n this._onParsedObserver = this.onParsedObservable.add(callback);\n }\n /**\n * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.\n * Note that the callback is called as soon as the mesh object is created, meaning some data may not have been setup yet for this mesh (vertex data, morph targets, material, ...)\n */\n set onMeshLoaded(callback) {\n if (this._onMeshLoadedObserver) {\n this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);\n }\n this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);\n }\n /**\n * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.\n */\n set onTextureLoaded(callback) {\n if (this._onTextureLoadedObserver) {\n this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);\n }\n this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);\n }\n /**\n * Callback raised when the loader creates a material after parsing the glTF properties of the material.\n */\n set onMaterialLoaded(callback) {\n if (this._onMaterialLoadedObserver) {\n this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);\n }\n this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);\n }\n /**\n * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.\n */\n set onCameraLoaded(callback) {\n if (this._onCameraLoadedObserver) {\n this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);\n }\n this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);\n }\n /**\n * Callback raised when the asset is completely loaded, immediately before the loader is disposed.\n * For assets with LODs, raised when all of the LODs are complete.\n * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.\n */\n set onComplete(callback) {\n if (this._onCompleteObserver) {\n this.onCompleteObservable.remove(this._onCompleteObserver);\n }\n this._onCompleteObserver = this.onCompleteObservable.add(callback);\n }\n /**\n * Callback raised when an error occurs.\n */\n set onError(callback) {\n if (this._onErrorObserver) {\n this.onErrorObservable.remove(this._onErrorObserver);\n }\n this._onErrorObserver = this.onErrorObservable.add(callback);\n }\n /**\n * Callback raised after the loader is disposed.\n */\n set onDispose(callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n }\n /**\n * Callback raised after a loader extension is created.\n */\n set onExtensionLoaded(callback) {\n if (this._onExtensionLoadedObserver) {\n this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);\n }\n this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);\n }\n /**\n * Defines if the loader logging is enabled.\n */\n get loggingEnabled() {\n return this._loggingEnabled;\n }\n set loggingEnabled(value) {\n if (this._loggingEnabled === value) {\n return;\n }\n this._loggingEnabled = value;\n if (this._loggingEnabled) {\n this._log = this._logEnabled;\n }\n else {\n this._log = this._logDisabled;\n }\n }\n /**\n * Defines if the loader should capture performance counters.\n */\n get capturePerformanceCounters() {\n return this._capturePerformanceCounters;\n }\n set capturePerformanceCounters(value) {\n if (this._capturePerformanceCounters === value) {\n return;\n }\n this._capturePerformanceCounters = value;\n if (this._capturePerformanceCounters) {\n this._startPerformanceCounter = this._startPerformanceCounterEnabled;\n this._endPerformanceCounter = this._endPerformanceCounterEnabled;\n }\n else {\n this._startPerformanceCounter = this._startPerformanceCounterDisabled;\n this._endPerformanceCounter = this._endPerformanceCounterDisabled;\n }\n }\n /**\n * Callback raised after a loader extension is created.\n */\n set onValidated(callback) {\n if (this._onValidatedObserver) {\n this.onValidatedObservable.remove(this._onValidatedObserver);\n }\n this._onValidatedObserver = this.onValidatedObservable.add(callback);\n }\n /**\n * Disposes the loader, releases resources during load, and cancels any outstanding requests.\n */\n dispose() {\n if (this._loader) {\n this._loader.dispose();\n this._loader = null;\n }\n for (const request of this._requests) {\n request.abort();\n }\n this._requests.length = 0;\n delete this._progressCallback;\n this.preprocessUrlAsync = (url) => Promise.resolve(url);\n this.onMeshLoadedObservable.clear();\n this.onSkinLoadedObservable.clear();\n this.onTextureLoadedObservable.clear();\n this.onMaterialLoadedObservable.clear();\n this.onCameraLoadedObservable.clear();\n this.onCompleteObservable.clear();\n this.onExtensionLoadedObservable.clear();\n this.onDisposeObservable.notifyObservers(undefined);\n this.onDisposeObservable.clear();\n }\n /**\n * @internal\n */\n loadFile(scene, fileOrUrl, rootUrl, onSuccess, onProgress, useArrayBuffer, onError, name) {\n if (ArrayBuffer.isView(fileOrUrl)) {\n this._loadBinary(scene, fileOrUrl, rootUrl, onSuccess, onError, name);\n return null;\n }\n this._progressCallback = onProgress;\n const fileName = fileOrUrl.name || Tools.GetFilename(fileOrUrl);\n if (useArrayBuffer) {\n if (this.useRangeRequests) {\n if (this.validate) {\n Logger.Warn(\"glTF validation is not supported when range requests are enabled\");\n }\n const fileRequest = {\n abort: () => { },\n onCompleteObservable: new Observable(),\n };\n const dataBuffer = {\n readAsync: (byteOffset, byteLength) => {\n return new Promise((resolve, reject) => {\n this._loadFile(scene, fileOrUrl, (data) => {\n resolve(new Uint8Array(data));\n }, true, (error) => {\n reject(error);\n }, (webRequest) => {\n webRequest.setRequestHeader(\"Range\", `bytes=${byteOffset}-${byteOffset + byteLength - 1}`);\n });\n });\n },\n byteLength: 0,\n };\n this._unpackBinaryAsync(new DataReader(dataBuffer)).then((loaderData) => {\n fileRequest.onCompleteObservable.notifyObservers(fileRequest);\n onSuccess(loaderData);\n }, onError ? (error) => onError(undefined, error) : undefined);\n return fileRequest;\n }\n return this._loadFile(scene, fileOrUrl, (data) => {\n this._validate(scene, new Uint8Array(data), rootUrl, fileName);\n this._unpackBinaryAsync(new DataReader({\n readAsync: (byteOffset, byteLength) => readAsync(data, byteOffset, byteLength),\n byteLength: data.byteLength,\n })).then((loaderData) => {\n onSuccess(loaderData);\n }, onError ? (error) => onError(undefined, error) : undefined);\n }, true, onError);\n }\n return this._loadFile(scene, fileOrUrl, (data) => {\n this._validate(scene, new Uint8Array(data), rootUrl, fileName);\n onSuccess({ json: this._parseJson(data) });\n }, useArrayBuffer, onError);\n }\n /**\n * @internal\n */\n _loadBinary(scene, data, rootUrl, onSuccess, onError, fileName) {\n this._validate(scene, data, rootUrl, fileName);\n this._unpackBinaryAsync(new DataReader({\n readAsync: (byteOffset, byteLength) => readViewAsync(data, byteOffset, byteLength),\n byteLength: data.byteLength,\n })).then((loaderData) => {\n onSuccess(loaderData);\n }, onError ? (error) => onError(undefined, error) : undefined);\n }\n /**\n * @internal\n */\n importMeshAsync(meshesNames, scene, data, rootUrl, onProgress, fileName) {\n return Promise.resolve().then(() => {\n this.onParsedObservable.notifyObservers(data);\n this.onParsedObservable.clear();\n this._log(`Loading ${fileName || \"\"}`);\n this._loader = this._getLoader(data);\n return this._loader.importMeshAsync(meshesNames, scene, null, data, rootUrl, onProgress, fileName);\n });\n }\n /**\n * @internal\n */\n loadAsync(scene, data, rootUrl, onProgress, fileName) {\n return Promise.resolve().then(() => {\n this.onParsedObservable.notifyObservers(data);\n this.onParsedObservable.clear();\n this._log(`Loading ${fileName || \"\"}`);\n this._loader = this._getLoader(data);\n return this._loader.loadAsync(scene, data, rootUrl, onProgress, fileName);\n });\n }\n /**\n * @internal\n */\n loadAssetContainerAsync(scene, data, rootUrl, onProgress, fileName) {\n return Promise.resolve().then(() => {\n this.onParsedObservable.notifyObservers(data);\n this.onParsedObservable.clear();\n this._log(`Loading ${fileName || \"\"}`);\n this._loader = this._getLoader(data);\n // Prepare the asset container.\n const container = new AssetContainer(scene);\n // Get materials/textures when loading to add to container\n const materials = [];\n this.onMaterialLoadedObservable.add((material) => {\n materials.push(material);\n });\n const textures = [];\n this.onTextureLoadedObservable.add((texture) => {\n textures.push(texture);\n });\n const cameras = [];\n this.onCameraLoadedObservable.add((camera) => {\n cameras.push(camera);\n });\n const morphTargetManagers = [];\n this.onMeshLoadedObservable.add((mesh) => {\n if (mesh.morphTargetManager) {\n morphTargetManagers.push(mesh.morphTargetManager);\n }\n });\n return this._loader.importMeshAsync(null, scene, container, data, rootUrl, onProgress, fileName).then((result) => {\n Array.prototype.push.apply(container.geometries, result.geometries);\n Array.prototype.push.apply(container.meshes, result.meshes);\n Array.prototype.push.apply(container.particleSystems, result.particleSystems);\n Array.prototype.push.apply(container.skeletons, result.skeletons);\n Array.prototype.push.apply(container.animationGroups, result.animationGroups);\n Array.prototype.push.apply(container.materials, materials);\n Array.prototype.push.apply(container.textures, textures);\n Array.prototype.push.apply(container.lights, result.lights);\n Array.prototype.push.apply(container.transformNodes, result.transformNodes);\n Array.prototype.push.apply(container.cameras, cameras);\n Array.prototype.push.apply(container.morphTargetManagers, morphTargetManagers);\n return container;\n });\n });\n }\n /**\n * @internal\n */\n canDirectLoad(data) {\n return ((data.indexOf(\"asset\") !== -1 && data.indexOf(\"version\") !== -1) ||\n data.startsWith(\"data:base64,\" + GLTFFileLoader._MagicBase64Encoded) || // this is technically incorrect, but will continue to support for backcompat.\n data.startsWith(\"data:;base64,\" + GLTFFileLoader._MagicBase64Encoded) ||\n data.startsWith(\"data:application/octet-stream;base64,\" + GLTFFileLoader._MagicBase64Encoded) ||\n data.startsWith(\"data:model/gltf-binary;base64,\" + GLTFFileLoader._MagicBase64Encoded));\n }\n /**\n * @internal\n */\n directLoad(scene, data) {\n if (data.startsWith(\"base64,\" + GLTFFileLoader._MagicBase64Encoded) || // this is technically incorrect, but will continue to support for backcompat.\n data.startsWith(\";base64,\" + GLTFFileLoader._MagicBase64Encoded) ||\n data.startsWith(\"application/octet-stream;base64,\" + GLTFFileLoader._MagicBase64Encoded) ||\n data.startsWith(\"model/gltf-binary;base64,\" + GLTFFileLoader._MagicBase64Encoded)) {\n const arrayBuffer = DecodeBase64UrlToBinary(data);\n this._validate(scene, new Uint8Array(arrayBuffer));\n return this._unpackBinaryAsync(new DataReader({\n readAsync: (byteOffset, byteLength) => readAsync(arrayBuffer, byteOffset, byteLength),\n byteLength: arrayBuffer.byteLength,\n }));\n }\n this._validate(scene, data);\n return Promise.resolve({ json: this._parseJson(data) });\n }\n /** @internal */\n createPlugin() {\n return new GLTFFileLoader();\n }\n /**\n * The loader state or null if the loader is not active.\n */\n get loaderState() {\n return this._state;\n }\n /**\n * Returns a promise that resolves when the asset is completely loaded.\n * @returns a promise that resolves when the asset is completely loaded.\n */\n whenCompleteAsync() {\n return new Promise((resolve, reject) => {\n this.onCompleteObservable.addOnce(() => {\n resolve();\n });\n this.onErrorObservable.addOnce((reason) => {\n reject(reason);\n });\n });\n }\n /**\n * @internal\n */\n _setState(state) {\n if (this._state === state) {\n return;\n }\n this._state = state;\n this.onLoaderStateChangedObservable.notifyObservers(this._state);\n this._log(GLTFLoaderState[this._state]);\n }\n /**\n * @internal\n */\n _loadFile(scene, fileOrUrl, onSuccess, useArrayBuffer, onError, onOpened) {\n const request = scene._loadFile(fileOrUrl, onSuccess, (event) => {\n this._onProgress(event, request);\n }, true, useArrayBuffer, onError, onOpened);\n request.onCompleteObservable.add((request) => {\n this._requests.splice(this._requests.indexOf(request), 1);\n });\n this._requests.push(request);\n return request;\n }\n _onProgress(event, request) {\n if (!this._progressCallback) {\n return;\n }\n request._lengthComputable = event.lengthComputable;\n request._loaded = event.loaded;\n request._total = event.total;\n let lengthComputable = true;\n let loaded = 0;\n let total = 0;\n for (const request of this._requests) {\n if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {\n return;\n }\n lengthComputable = lengthComputable && request._lengthComputable;\n loaded += request._loaded;\n total += request._total;\n }\n this._progressCallback({\n lengthComputable: lengthComputable,\n loaded: loaded,\n total: lengthComputable ? total : 0,\n });\n }\n _validate(scene, data, rootUrl = \"\", fileName = \"\") {\n if (!this.validate) {\n return;\n }\n this._startPerformanceCounter(\"Validate JSON\");\n GLTFValidation.ValidateAsync(data, rootUrl, fileName, (uri) => {\n return this.preprocessUrlAsync(rootUrl + uri).then((url) => scene._loadFileAsync(url, undefined, true, true));\n }).then((result) => {\n this._endPerformanceCounter(\"Validate JSON\");\n this.onValidatedObservable.notifyObservers(result);\n this.onValidatedObservable.clear();\n }, (reason) => {\n this._endPerformanceCounter(\"Validate JSON\");\n Tools.Warn(`Failed to validate: ${reason.message}`);\n this.onValidatedObservable.clear();\n });\n }\n _getLoader(loaderData) {\n const asset = loaderData.json.asset || {};\n this._log(`Asset version: ${asset.version}`);\n asset.minVersion && this._log(`Asset minimum version: ${asset.minVersion}`);\n asset.generator && this._log(`Asset generator: ${asset.generator}`);\n const version = GLTFFileLoader._parseVersion(asset.version);\n if (!version) {\n throw new Error(\"Invalid version: \" + asset.version);\n }\n if (asset.minVersion !== undefined) {\n const minVersion = GLTFFileLoader._parseVersion(asset.minVersion);\n if (!minVersion) {\n throw new Error(\"Invalid minimum version: \" + asset.minVersion);\n }\n if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {\n throw new Error(\"Incompatible minimum version: \" + asset.minVersion);\n }\n }\n const createLoaders = {\n 1: GLTFFileLoader._CreateGLTF1Loader,\n 2: GLTFFileLoader._CreateGLTF2Loader,\n };\n const createLoader = createLoaders[version.major];\n if (!createLoader) {\n throw new Error(\"Unsupported version: \" + asset.version);\n }\n return createLoader(this);\n }\n _parseJson(json) {\n this._startPerformanceCounter(\"Parse JSON\");\n this._log(`JSON length: ${json.length}`);\n const parsed = JSON.parse(json);\n this._endPerformanceCounter(\"Parse JSON\");\n return parsed;\n }\n _unpackBinaryAsync(dataReader) {\n this._startPerformanceCounter(\"Unpack Binary\");\n // Read magic + version + length + json length + json format\n return dataReader.loadAsync(20).then(() => {\n const Binary = {\n Magic: 0x46546c67,\n };\n const magic = dataReader.readUint32();\n if (magic !== Binary.Magic) {\n throw new RuntimeError(\"Unexpected magic: \" + magic, ErrorCodes.GLTFLoaderUnexpectedMagicError);\n }\n const version = dataReader.readUint32();\n if (this.loggingEnabled) {\n this._log(`Binary version: ${version}`);\n }\n const length = dataReader.readUint32();\n if (!this.useRangeRequests && length !== dataReader.buffer.byteLength) {\n Logger.Warn(`Length in header does not match actual data length: ${length} != ${dataReader.buffer.byteLength}`);\n }\n let unpacked;\n switch (version) {\n case 1: {\n unpacked = this._unpackBinaryV1Async(dataReader, length);\n break;\n }\n case 2: {\n unpacked = this._unpackBinaryV2Async(dataReader, length);\n break;\n }\n default: {\n throw new Error(\"Unsupported version: \" + version);\n }\n }\n this._endPerformanceCounter(\"Unpack Binary\");\n return unpacked;\n });\n }\n _unpackBinaryV1Async(dataReader, length) {\n const ContentFormat = {\n JSON: 0,\n };\n const contentLength = dataReader.readUint32();\n const contentFormat = dataReader.readUint32();\n if (contentFormat !== ContentFormat.JSON) {\n throw new Error(`Unexpected content format: ${contentFormat}`);\n }\n const bodyLength = length - dataReader.byteOffset;\n const data = { json: this._parseJson(dataReader.readString(contentLength)), bin: null };\n if (bodyLength !== 0) {\n const startByteOffset = dataReader.byteOffset;\n data.bin = {\n readAsync: (byteOffset, byteLength) => dataReader.buffer.readAsync(startByteOffset + byteOffset, byteLength),\n byteLength: bodyLength,\n };\n }\n return Promise.resolve(data);\n }\n _unpackBinaryV2Async(dataReader, length) {\n const ChunkFormat = {\n JSON: 0x4e4f534a,\n BIN: 0x004e4942,\n };\n // Read the JSON chunk header.\n const chunkLength = dataReader.readUint32();\n const chunkFormat = dataReader.readUint32();\n if (chunkFormat !== ChunkFormat.JSON) {\n throw new Error(\"First chunk format is not JSON\");\n }\n // Bail if there are no other chunks.\n if (dataReader.byteOffset + chunkLength === length) {\n return dataReader.loadAsync(chunkLength).then(() => {\n return { json: this._parseJson(dataReader.readString(chunkLength)), bin: null };\n });\n }\n // Read the JSON chunk and the length and type of the next chunk.\n return dataReader.loadAsync(chunkLength + 8).then(() => {\n const data = { json: this._parseJson(dataReader.readString(chunkLength)), bin: null };\n const readAsync = () => {\n const chunkLength = dataReader.readUint32();\n const chunkFormat = dataReader.readUint32();\n switch (chunkFormat) {\n case ChunkFormat.JSON: {\n throw new Error(\"Unexpected JSON chunk\");\n }\n case ChunkFormat.BIN: {\n const startByteOffset = dataReader.byteOffset;\n data.bin = {\n readAsync: (byteOffset, byteLength) => dataReader.buffer.readAsync(startByteOffset + byteOffset, byteLength),\n byteLength: chunkLength,\n };\n dataReader.skipBytes(chunkLength);\n break;\n }\n default: {\n // ignore unrecognized chunkFormat\n dataReader.skipBytes(chunkLength);\n break;\n }\n }\n if (dataReader.byteOffset !== length) {\n return dataReader.loadAsync(8).then(readAsync);\n }\n return Promise.resolve(data);\n };\n return readAsync();\n });\n }\n static _parseVersion(version) {\n if (version === \"1.0\" || version === \"1.0.1\") {\n return {\n major: 1,\n minor: 0,\n };\n }\n const match = (version + \"\").match(/^(\\d+)\\.(\\d+)/);\n if (!match) {\n return null;\n }\n return {\n major: parseInt(match[1]),\n minor: parseInt(match[2]),\n };\n }\n static _compareVersion(a, b) {\n if (a.major > b.major) {\n return 1;\n }\n if (a.major < b.major) {\n return -1;\n }\n if (a.minor > b.minor) {\n return 1;\n }\n if (a.minor < b.minor) {\n return -1;\n }\n return 0;\n }\n /**\n * @internal\n */\n _logOpen(message) {\n this._log(message);\n this._logIndentLevel++;\n }\n /** @internal */\n _logClose() {\n --this._logIndentLevel;\n }\n _logEnabled(message) {\n const spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);\n Logger.Log(`${spaces}${message}`);\n }\n _logDisabled(message) { }\n _startPerformanceCounterEnabled(counterName) {\n Tools.StartPerformanceCounter(counterName);\n }\n _startPerformanceCounterDisabled(counterName) { }\n _endPerformanceCounterEnabled(counterName) {\n Tools.EndPerformanceCounter(counterName);\n }\n _endPerformanceCounterDisabled(counterName) { }\n}\n// ----------\n// V1 options\n// ----------\n/**\n * Set this property to false to disable incremental loading which delays the loader from calling the success callback until after loading the meshes and shaders.\n * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.\n * Defaults to true.\n * @internal\n */\nGLTFFileLoader.IncrementalLoading = true;\n/**\n * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.\n * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.\n * @internal\n */\nGLTFFileLoader.HomogeneousCoordinates = false;\nGLTFFileLoader._MagicBase64Encoded = \"Z2xURg\"; // \"glTF\" base64 encoded (without the quotes!)\nGLTFFileLoader._logSpaces = \" \";\nif (SceneLoader) {\n SceneLoader.RegisterPlugin(new GLTFFileLoader());\n}\n//# sourceMappingURL=glTFFileLoader.js.map","export * from \"./nativeXRRenderTarget.js\";\nexport * from \"./nativeXRFrame.js\";\n//# sourceMappingURL=index.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./webXRCamera.js\";\nexport * from \"./webXREnterExitUI.js\";\nexport * from \"./webXRExperienceHelper.js\";\nexport * from \"./webXRInput.js\";\nexport * from \"./webXRInputSource.js\";\nexport * from \"./webXRManagedOutputCanvas.js\";\nexport * from \"./webXRTypes.js\";\nexport * from \"./webXRSessionManager.js\";\nexport * from \"./webXRDefaultExperience.js\";\nexport * from \"./webXRFeaturesManager.js\";\nexport * from \"./features/index.js\";\nexport * from \"./motionController/index.js\";\nexport * from \"./native/index.js\";\n//# sourceMappingURL=index.js.map","export {};\n/** @internal */\n/* interface DeepImmutableMap extends ReadonlyMap, DeepImmutable> {} // es2015+ only */\n//# sourceMappingURL=types.js.map","export * from \"./compatibilityOptions.js\";\n//# sourceMappingURL=index.js.map","import { EParameterType, ETextureWrapMode, ETextureFilterType, EComponentType } from \"./glTFLoaderInterfaces.js\";\nimport { Vector2, Vector3, Vector4, Matrix } from \"@babylonjs/core/Maths/math.vector.js\";\nimport { Color4 } from \"@babylonjs/core/Maths/math.color.js\";\nimport { Effect } from \"@babylonjs/core/Materials/effect.js\";\nimport { ShaderMaterial } from \"@babylonjs/core/Materials/shaderMaterial.js\";\nimport { Texture } from \"@babylonjs/core/Materials/Textures/texture.js\";\n/**\n * Utils functions for GLTF\n * @internal\n * @deprecated\n */\nexport class GLTFUtils {\n /**\n * Sets the given \"parameter\" matrix\n * @param scene the Scene object\n * @param source the source node where to pick the matrix\n * @param parameter the GLTF technique parameter\n * @param uniformName the name of the shader's uniform\n * @param shaderMaterial the shader material\n */\n static SetMatrix(scene, source, parameter, uniformName, shaderMaterial) {\n let mat = null;\n if (parameter.semantic === \"MODEL\") {\n mat = source.getWorldMatrix();\n }\n else if (parameter.semantic === \"PROJECTION\") {\n mat = scene.getProjectionMatrix();\n }\n else if (parameter.semantic === \"VIEW\") {\n mat = scene.getViewMatrix();\n }\n else if (parameter.semantic === \"MODELVIEWINVERSETRANSPOSE\") {\n mat = Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());\n }\n else if (parameter.semantic === \"MODELVIEW\") {\n mat = source.getWorldMatrix().multiply(scene.getViewMatrix());\n }\n else if (parameter.semantic === \"MODELVIEWPROJECTION\") {\n mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());\n }\n else if (parameter.semantic === \"MODELINVERSE\") {\n mat = source.getWorldMatrix().invert();\n }\n else if (parameter.semantic === \"VIEWINVERSE\") {\n mat = scene.getViewMatrix().invert();\n }\n else if (parameter.semantic === \"PROJECTIONINVERSE\") {\n mat = scene.getProjectionMatrix().invert();\n }\n else if (parameter.semantic === \"MODELVIEWINVERSE\") {\n mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();\n }\n else if (parameter.semantic === \"MODELVIEWPROJECTIONINVERSE\") {\n mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();\n }\n else if (parameter.semantic === \"MODELINVERSETRANSPOSE\") {\n mat = Matrix.Transpose(source.getWorldMatrix().invert());\n }\n if (mat) {\n switch (parameter.type) {\n case EParameterType.FLOAT_MAT2:\n shaderMaterial.setMatrix2x2(uniformName, Matrix.GetAsMatrix2x2(mat));\n break;\n case EParameterType.FLOAT_MAT3:\n shaderMaterial.setMatrix3x3(uniformName, Matrix.GetAsMatrix3x3(mat));\n break;\n case EParameterType.FLOAT_MAT4:\n shaderMaterial.setMatrix(uniformName, mat);\n break;\n default:\n break;\n }\n }\n }\n /**\n * Sets the given \"parameter\" matrix\n * @param shaderMaterial the shader material\n * @param uniform the name of the shader's uniform\n * @param value the value of the uniform\n * @param type the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)\n */\n static SetUniform(shaderMaterial, uniform, value, type) {\n switch (type) {\n case EParameterType.FLOAT:\n shaderMaterial.setFloat(uniform, value);\n return true;\n case EParameterType.FLOAT_VEC2:\n shaderMaterial.setVector2(uniform, Vector2.FromArray(value));\n return true;\n case EParameterType.FLOAT_VEC3:\n shaderMaterial.setVector3(uniform, Vector3.FromArray(value));\n return true;\n case EParameterType.FLOAT_VEC4:\n shaderMaterial.setVector4(uniform, Vector4.FromArray(value));\n return true;\n default:\n return false;\n }\n }\n /**\n * Returns the wrap mode of the texture\n * @param mode the mode value\n */\n static GetWrapMode(mode) {\n switch (mode) {\n case ETextureWrapMode.CLAMP_TO_EDGE:\n return Texture.CLAMP_ADDRESSMODE;\n case ETextureWrapMode.MIRRORED_REPEAT:\n return Texture.MIRROR_ADDRESSMODE;\n case ETextureWrapMode.REPEAT:\n return Texture.WRAP_ADDRESSMODE;\n default:\n return Texture.WRAP_ADDRESSMODE;\n }\n }\n /**\n * Returns the byte stride giving an accessor\n * @param accessor the GLTF accessor objet\n */\n static GetByteStrideFromType(accessor) {\n // Needs this function since \"byteStride\" isn't requiered in glTF format\n const type = accessor.type;\n switch (type) {\n case \"VEC2\":\n return 2;\n case \"VEC3\":\n return 3;\n case \"VEC4\":\n return 4;\n case \"MAT2\":\n return 4;\n case \"MAT3\":\n return 9;\n case \"MAT4\":\n return 16;\n default:\n return 1;\n }\n }\n /**\n * Returns the texture filter mode giving a mode value\n * @param mode the filter mode value\n * @returns the filter mode (TODO - needs to be a type?)\n */\n static GetTextureFilterMode(mode) {\n switch (mode) {\n case ETextureFilterType.LINEAR:\n case ETextureFilterType.LINEAR_MIPMAP_NEAREST:\n case ETextureFilterType.LINEAR_MIPMAP_LINEAR:\n return Texture.TRILINEAR_SAMPLINGMODE;\n case ETextureFilterType.NEAREST:\n case ETextureFilterType.NEAREST_MIPMAP_NEAREST:\n return Texture.NEAREST_SAMPLINGMODE;\n default:\n return Texture.BILINEAR_SAMPLINGMODE;\n }\n }\n static GetBufferFromBufferView(gltfRuntime, bufferView, byteOffset, byteLength, componentType) {\n byteOffset = bufferView.byteOffset + byteOffset;\n const loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];\n if (byteOffset + byteLength > loadedBufferView.byteLength) {\n throw new Error(\"Buffer access is out of range\");\n }\n const buffer = loadedBufferView.buffer;\n byteOffset += loadedBufferView.byteOffset;\n switch (componentType) {\n case EComponentType.BYTE:\n return new Int8Array(buffer, byteOffset, byteLength);\n case EComponentType.UNSIGNED_BYTE:\n return new Uint8Array(buffer, byteOffset, byteLength);\n case EComponentType.SHORT:\n return new Int16Array(buffer, byteOffset, byteLength);\n case EComponentType.UNSIGNED_SHORT:\n return new Uint16Array(buffer, byteOffset, byteLength);\n default:\n return new Float32Array(buffer, byteOffset, byteLength);\n }\n }\n /**\n * Returns a buffer from its accessor\n * @param gltfRuntime the GLTF runtime\n * @param accessor the GLTF accessor\n */\n static GetBufferFromAccessor(gltfRuntime, accessor) {\n const bufferView = gltfRuntime.bufferViews[accessor.bufferView];\n const byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);\n return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);\n }\n /**\n * Decodes a buffer view into a string\n * @param view the buffer view\n */\n static DecodeBufferToText(view) {\n let result = \"\";\n const length = view.byteLength;\n for (let i = 0; i < length; ++i) {\n result += String.fromCharCode(view[i]);\n }\n return result;\n }\n /**\n * Returns the default material of gltf. Related to\n * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material\n * @param scene the Babylon.js scene\n */\n static GetDefaultMaterial(scene) {\n if (!GLTFUtils._DefaultMaterial) {\n Effect.ShadersStore[\"GLTFDefaultMaterialVertexShader\"] = [\n \"precision highp float;\",\n \"\",\n \"uniform mat4 worldView;\",\n \"uniform mat4 projection;\",\n \"\",\n \"attribute vec3 position;\",\n \"\",\n \"void main(void)\",\n \"{\",\n \" gl_Position = projection * worldView * vec4(position, 1.0);\",\n \"}\",\n ].join(\"\\n\");\n Effect.ShadersStore[\"GLTFDefaultMaterialPixelShader\"] = [\n \"precision highp float;\",\n \"\",\n \"uniform vec4 u_emission;\",\n \"\",\n \"void main(void)\",\n \"{\",\n \" gl_FragColor = u_emission;\",\n \"}\",\n ].join(\"\\n\");\n const shaderPath = {\n vertex: \"GLTFDefaultMaterial\",\n fragment: \"GLTFDefaultMaterial\",\n };\n const options = {\n attributes: [\"position\"],\n uniforms: [\"worldView\", \"projection\", \"u_emission\"],\n samplers: new Array(),\n needAlphaBlending: false,\n };\n GLTFUtils._DefaultMaterial = new ShaderMaterial(\"GLTFDefaultMaterial\", scene, shaderPath, options);\n GLTFUtils._DefaultMaterial.setColor4(\"u_emission\", new Color4(0.5, 0.5, 0.5, 1.0));\n }\n return GLTFUtils._DefaultMaterial;\n }\n}\n// The GLTF default material\nGLTFUtils._DefaultMaterial = null;\n//# sourceMappingURL=glTFLoaderUtils.js.map","/**\n * Enums\n * @internal\n */\nexport var EComponentType;\n(function (EComponentType) {\n EComponentType[EComponentType[\"BYTE\"] = 5120] = \"BYTE\";\n EComponentType[EComponentType[\"UNSIGNED_BYTE\"] = 5121] = \"UNSIGNED_BYTE\";\n EComponentType[EComponentType[\"SHORT\"] = 5122] = \"SHORT\";\n EComponentType[EComponentType[\"UNSIGNED_SHORT\"] = 5123] = \"UNSIGNED_SHORT\";\n EComponentType[EComponentType[\"FLOAT\"] = 5126] = \"FLOAT\";\n})(EComponentType || (EComponentType = {}));\n/** @internal */\nexport var EShaderType;\n(function (EShaderType) {\n EShaderType[EShaderType[\"FRAGMENT\"] = 35632] = \"FRAGMENT\";\n EShaderType[EShaderType[\"VERTEX\"] = 35633] = \"VERTEX\";\n})(EShaderType || (EShaderType = {}));\n/** @internal */\nexport var EParameterType;\n(function (EParameterType) {\n EParameterType[EParameterType[\"BYTE\"] = 5120] = \"BYTE\";\n EParameterType[EParameterType[\"UNSIGNED_BYTE\"] = 5121] = \"UNSIGNED_BYTE\";\n EParameterType[EParameterType[\"SHORT\"] = 5122] = \"SHORT\";\n EParameterType[EParameterType[\"UNSIGNED_SHORT\"] = 5123] = \"UNSIGNED_SHORT\";\n EParameterType[EParameterType[\"INT\"] = 5124] = \"INT\";\n EParameterType[EParameterType[\"UNSIGNED_INT\"] = 5125] = \"UNSIGNED_INT\";\n EParameterType[EParameterType[\"FLOAT\"] = 5126] = \"FLOAT\";\n EParameterType[EParameterType[\"FLOAT_VEC2\"] = 35664] = \"FLOAT_VEC2\";\n EParameterType[EParameterType[\"FLOAT_VEC3\"] = 35665] = \"FLOAT_VEC3\";\n EParameterType[EParameterType[\"FLOAT_VEC4\"] = 35666] = \"FLOAT_VEC4\";\n EParameterType[EParameterType[\"INT_VEC2\"] = 35667] = \"INT_VEC2\";\n EParameterType[EParameterType[\"INT_VEC3\"] = 35668] = \"INT_VEC3\";\n EParameterType[EParameterType[\"INT_VEC4\"] = 35669] = \"INT_VEC4\";\n EParameterType[EParameterType[\"BOOL\"] = 35670] = \"BOOL\";\n EParameterType[EParameterType[\"BOOL_VEC2\"] = 35671] = \"BOOL_VEC2\";\n EParameterType[EParameterType[\"BOOL_VEC3\"] = 35672] = \"BOOL_VEC3\";\n EParameterType[EParameterType[\"BOOL_VEC4\"] = 35673] = \"BOOL_VEC4\";\n EParameterType[EParameterType[\"FLOAT_MAT2\"] = 35674] = \"FLOAT_MAT2\";\n EParameterType[EParameterType[\"FLOAT_MAT3\"] = 35675] = \"FLOAT_MAT3\";\n EParameterType[EParameterType[\"FLOAT_MAT4\"] = 35676] = \"FLOAT_MAT4\";\n EParameterType[EParameterType[\"SAMPLER_2D\"] = 35678] = \"SAMPLER_2D\";\n})(EParameterType || (EParameterType = {}));\n/** @internal */\nexport var ETextureWrapMode;\n(function (ETextureWrapMode) {\n ETextureWrapMode[ETextureWrapMode[\"CLAMP_TO_EDGE\"] = 33071] = \"CLAMP_TO_EDGE\";\n ETextureWrapMode[ETextureWrapMode[\"MIRRORED_REPEAT\"] = 33648] = \"MIRRORED_REPEAT\";\n ETextureWrapMode[ETextureWrapMode[\"REPEAT\"] = 10497] = \"REPEAT\";\n})(ETextureWrapMode || (ETextureWrapMode = {}));\n/** @internal */\nexport var ETextureFilterType;\n(function (ETextureFilterType) {\n ETextureFilterType[ETextureFilterType[\"NEAREST\"] = 9728] = \"NEAREST\";\n ETextureFilterType[ETextureFilterType[\"LINEAR\"] = 9728] = \"LINEAR\";\n ETextureFilterType[ETextureFilterType[\"NEAREST_MIPMAP_NEAREST\"] = 9984] = \"NEAREST_MIPMAP_NEAREST\";\n ETextureFilterType[ETextureFilterType[\"LINEAR_MIPMAP_NEAREST\"] = 9985] = \"LINEAR_MIPMAP_NEAREST\";\n ETextureFilterType[ETextureFilterType[\"NEAREST_MIPMAP_LINEAR\"] = 9986] = \"NEAREST_MIPMAP_LINEAR\";\n ETextureFilterType[ETextureFilterType[\"LINEAR_MIPMAP_LINEAR\"] = 9987] = \"LINEAR_MIPMAP_LINEAR\";\n})(ETextureFilterType || (ETextureFilterType = {}));\n/** @internal */\nexport var ETextureFormat;\n(function (ETextureFormat) {\n ETextureFormat[ETextureFormat[\"ALPHA\"] = 6406] = \"ALPHA\";\n ETextureFormat[ETextureFormat[\"RGB\"] = 6407] = \"RGB\";\n ETextureFormat[ETextureFormat[\"RGBA\"] = 6408] = \"RGBA\";\n ETextureFormat[ETextureFormat[\"LUMINANCE\"] = 6409] = \"LUMINANCE\";\n ETextureFormat[ETextureFormat[\"LUMINANCE_ALPHA\"] = 6410] = \"LUMINANCE_ALPHA\";\n})(ETextureFormat || (ETextureFormat = {}));\n/** @internal */\nexport var ECullingType;\n(function (ECullingType) {\n ECullingType[ECullingType[\"FRONT\"] = 1028] = \"FRONT\";\n ECullingType[ECullingType[\"BACK\"] = 1029] = \"BACK\";\n ECullingType[ECullingType[\"FRONT_AND_BACK\"] = 1032] = \"FRONT_AND_BACK\";\n})(ECullingType || (ECullingType = {}));\n/** @internal */\nexport var EBlendingFunction;\n(function (EBlendingFunction) {\n EBlendingFunction[EBlendingFunction[\"ZERO\"] = 0] = \"ZERO\";\n EBlendingFunction[EBlendingFunction[\"ONE\"] = 1] = \"ONE\";\n EBlendingFunction[EBlendingFunction[\"SRC_COLOR\"] = 768] = \"SRC_COLOR\";\n EBlendingFunction[EBlendingFunction[\"ONE_MINUS_SRC_COLOR\"] = 769] = \"ONE_MINUS_SRC_COLOR\";\n EBlendingFunction[EBlendingFunction[\"DST_COLOR\"] = 774] = \"DST_COLOR\";\n EBlendingFunction[EBlendingFunction[\"ONE_MINUS_DST_COLOR\"] = 775] = \"ONE_MINUS_DST_COLOR\";\n EBlendingFunction[EBlendingFunction[\"SRC_ALPHA\"] = 770] = \"SRC_ALPHA\";\n EBlendingFunction[EBlendingFunction[\"ONE_MINUS_SRC_ALPHA\"] = 771] = \"ONE_MINUS_SRC_ALPHA\";\n EBlendingFunction[EBlendingFunction[\"DST_ALPHA\"] = 772] = \"DST_ALPHA\";\n EBlendingFunction[EBlendingFunction[\"ONE_MINUS_DST_ALPHA\"] = 773] = \"ONE_MINUS_DST_ALPHA\";\n EBlendingFunction[EBlendingFunction[\"CONSTANT_COLOR\"] = 32769] = \"CONSTANT_COLOR\";\n EBlendingFunction[EBlendingFunction[\"ONE_MINUS_CONSTANT_COLOR\"] = 32770] = \"ONE_MINUS_CONSTANT_COLOR\";\n EBlendingFunction[EBlendingFunction[\"CONSTANT_ALPHA\"] = 32771] = \"CONSTANT_ALPHA\";\n EBlendingFunction[EBlendingFunction[\"ONE_MINUS_CONSTANT_ALPHA\"] = 32772] = \"ONE_MINUS_CONSTANT_ALPHA\";\n EBlendingFunction[EBlendingFunction[\"SRC_ALPHA_SATURATE\"] = 776] = \"SRC_ALPHA_SATURATE\";\n})(EBlendingFunction || (EBlendingFunction = {}));\n//# sourceMappingURL=glTFLoaderInterfaces.js.map","import { EParameterType, ETextureFilterType, ECullingType, EBlendingFunction, EShaderType } from \"./glTFLoaderInterfaces.js\";\nimport { Quaternion, Vector3, Matrix } from \"@babylonjs/core/Maths/math.vector.js\";\nimport { Color3 } from \"@babylonjs/core/Maths/math.color.js\";\nimport { Tools } from \"@babylonjs/core/Misc/tools.js\";\nimport { Camera } from \"@babylonjs/core/Cameras/camera.js\";\nimport { FreeCamera } from \"@babylonjs/core/Cameras/freeCamera.js\";\nimport { Animation } from \"@babylonjs/core/Animations/animation.js\";\nimport { Bone } from \"@babylonjs/core/Bones/bone.js\";\nimport { Skeleton } from \"@babylonjs/core/Bones/skeleton.js\";\nimport { Effect } from \"@babylonjs/core/Materials/effect.js\";\nimport { Material } from \"@babylonjs/core/Materials/material.js\";\nimport { MultiMaterial } from \"@babylonjs/core/Materials/multiMaterial.js\";\nimport { StandardMaterial } from \"@babylonjs/core/Materials/standardMaterial.js\";\nimport { ShaderMaterial } from \"@babylonjs/core/Materials/shaderMaterial.js\";\nimport { Texture } from \"@babylonjs/core/Materials/Textures/texture.js\";\nimport { VertexData } from \"@babylonjs/core/Meshes/mesh.vertexData.js\";\nimport { VertexBuffer } from \"@babylonjs/core/Buffers/buffer.js\";\nimport { Geometry } from \"@babylonjs/core/Meshes/geometry.js\";\nimport { SubMesh } from \"@babylonjs/core/Meshes/subMesh.js\";\nimport { AbstractMesh } from \"@babylonjs/core/Meshes/abstractMesh.js\";\nimport { Mesh } from \"@babylonjs/core/Meshes/mesh.js\";\nimport { HemisphericLight } from \"@babylonjs/core/Lights/hemisphericLight.js\";\nimport { DirectionalLight } from \"@babylonjs/core/Lights/directionalLight.js\";\nimport { PointLight } from \"@babylonjs/core/Lights/pointLight.js\";\nimport { SpotLight } from \"@babylonjs/core/Lights/spotLight.js\";\nimport { GLTFUtils } from \"./glTFLoaderUtils.js\";\nimport { GLTFFileLoader } from \"../glTFFileLoader.js\";\nimport { Constants } from \"@babylonjs/core/Engines/constants.js\";\n/**\n * Tokenizer. Used for shaders compatibility\n * Automatically map world, view, projection, worldViewProjection, attributes and so on\n */\nvar ETokenType;\n(function (ETokenType) {\n ETokenType[ETokenType[\"IDENTIFIER\"] = 1] = \"IDENTIFIER\";\n ETokenType[ETokenType[\"UNKNOWN\"] = 2] = \"UNKNOWN\";\n ETokenType[ETokenType[\"END_OF_INPUT\"] = 3] = \"END_OF_INPUT\";\n})(ETokenType || (ETokenType = {}));\nclass Tokenizer {\n constructor(toParse) {\n this._pos = 0;\n this.currentToken = ETokenType.UNKNOWN;\n this.currentIdentifier = \"\";\n this.currentString = \"\";\n this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;\n this._toParse = toParse;\n this._maxPos = toParse.length;\n }\n getNextToken() {\n if (this.isEnd()) {\n return ETokenType.END_OF_INPUT;\n }\n this.currentString = this.read();\n this.currentToken = ETokenType.UNKNOWN;\n if (this.currentString === \"_\" || this.isLetterOrDigitPattern.test(this.currentString)) {\n this.currentToken = ETokenType.IDENTIFIER;\n this.currentIdentifier = this.currentString;\n while (!this.isEnd() && (this.isLetterOrDigitPattern.test((this.currentString = this.peek())) || this.currentString === \"_\")) {\n this.currentIdentifier += this.currentString;\n this.forward();\n }\n }\n return this.currentToken;\n }\n peek() {\n return this._toParse[this._pos];\n }\n read() {\n return this._toParse[this._pos++];\n }\n forward() {\n this._pos++;\n }\n isEnd() {\n return this._pos >= this._maxPos;\n }\n}\n/**\n * Values\n */\nconst glTFTransforms = [\"MODEL\", \"VIEW\", \"PROJECTION\", \"MODELVIEW\", \"MODELVIEWPROJECTION\", \"JOINTMATRIX\"];\nconst babylonTransforms = [\"world\", \"view\", \"projection\", \"worldView\", \"worldViewProjection\", \"mBones\"];\nconst glTFAnimationPaths = [\"translation\", \"rotation\", \"scale\"];\nconst babylonAnimationPaths = [\"position\", \"rotationQuaternion\", \"scaling\"];\n/**\n * Parse\n * @param parsedBuffers\n * @param gltfRuntime\n */\nconst parseBuffers = (parsedBuffers, gltfRuntime) => {\n for (const buf in parsedBuffers) {\n const parsedBuffer = parsedBuffers[buf];\n gltfRuntime.buffers[buf] = parsedBuffer;\n gltfRuntime.buffersCount++;\n }\n};\nconst parseShaders = (parsedShaders, gltfRuntime) => {\n for (const sha in parsedShaders) {\n const parsedShader = parsedShaders[sha];\n gltfRuntime.shaders[sha] = parsedShader;\n gltfRuntime.shaderscount++;\n }\n};\nconst parseObject = (parsedObjects, runtimeProperty, gltfRuntime) => {\n for (const object in parsedObjects) {\n const parsedObject = parsedObjects[object];\n gltfRuntime[runtimeProperty][object] = parsedObject;\n }\n};\n/**\n * Utils\n * @param buffer\n */\nconst normalizeUVs = (buffer) => {\n if (!buffer) {\n return;\n }\n for (let i = 0; i < buffer.length / 2; i++) {\n buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];\n }\n};\nconst getAttribute = (attributeParameter) => {\n if (attributeParameter.semantic === \"NORMAL\") {\n return \"normal\";\n }\n else if (attributeParameter.semantic === \"POSITION\") {\n return \"position\";\n }\n else if (attributeParameter.semantic === \"JOINT\") {\n return \"matricesIndices\";\n }\n else if (attributeParameter.semantic === \"WEIGHT\") {\n return \"matricesWeights\";\n }\n else if (attributeParameter.semantic === \"COLOR\") {\n return \"color\";\n }\n else if (attributeParameter.semantic && attributeParameter.semantic.indexOf(\"TEXCOORD_\") !== -1) {\n const channel = Number(attributeParameter.semantic.split(\"_\")[1]);\n return \"uv\" + (channel === 0 ? \"\" : channel + 1);\n }\n return null;\n};\n/**\n * Loads and creates animations\n * @param gltfRuntime\n */\nconst loadAnimations = (gltfRuntime) => {\n for (const anim in gltfRuntime.animations) {\n const animation = gltfRuntime.animations[anim];\n if (!animation.channels || !animation.samplers) {\n continue;\n }\n let lastAnimation = null;\n for (let i = 0; i < animation.channels.length; i++) {\n // Get parameters and load buffers\n const channel = animation.channels[i];\n const sampler = animation.samplers[channel.sampler];\n if (!sampler) {\n continue;\n }\n let inputData = null;\n let outputData = null;\n if (animation.parameters) {\n inputData = animation.parameters[sampler.input];\n outputData = animation.parameters[sampler.output];\n }\n else {\n inputData = sampler.input;\n outputData = sampler.output;\n }\n const bufferInput = GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);\n const bufferOutput = GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);\n const targetId = channel.target.id;\n let targetNode = gltfRuntime.scene.getNodeById(targetId);\n if (targetNode === null) {\n targetNode = gltfRuntime.scene.getNodeByName(targetId);\n }\n if (targetNode === null) {\n Tools.Warn(\"Creating animation named \" + anim + \". But cannot find node named \" + targetId + \" to attach to\");\n continue;\n }\n const isBone = targetNode instanceof Bone;\n // Get target path (position, rotation or scaling)\n let targetPath = channel.target.path;\n const targetPathIndex = glTFAnimationPaths.indexOf(targetPath);\n if (targetPathIndex !== -1) {\n targetPath = babylonAnimationPaths[targetPathIndex];\n }\n // Determine animation type\n let animationType = Animation.ANIMATIONTYPE_MATRIX;\n if (!isBone) {\n if (targetPath === \"rotationQuaternion\") {\n animationType = Animation.ANIMATIONTYPE_QUATERNION;\n targetNode.rotationQuaternion = new Quaternion();\n }\n else {\n animationType = Animation.ANIMATIONTYPE_VECTOR3;\n }\n }\n // Create animation and key frames\n let babylonAnimation = null;\n const keys = [];\n let arrayOffset = 0;\n let modifyKey = false;\n if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {\n babylonAnimation = lastAnimation;\n modifyKey = true;\n }\n if (!modifyKey) {\n gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;\n babylonAnimation = new Animation(anim, isBone ? \"_matrix\" : targetPath, 1, animationType, Animation.ANIMATIONLOOPMODE_CYCLE);\n gltfRuntime.scene._blockEntityCollection = false;\n }\n // For each frame\n for (let j = 0; j < bufferInput.length; j++) {\n let value = null;\n if (targetPath === \"rotationQuaternion\") {\n // VEC4\n value = Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);\n arrayOffset += 4;\n }\n else {\n // Position and scaling are VEC3\n value = Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);\n arrayOffset += 3;\n }\n if (isBone) {\n const bone = targetNode;\n let translation = Vector3.Zero();\n let rotationQuaternion = new Quaternion();\n let scaling = Vector3.Zero();\n // Warning on decompose\n let mat = bone.getBaseMatrix();\n if (modifyKey && lastAnimation) {\n mat = lastAnimation.getKeys()[j].value;\n }\n mat.decompose(scaling, rotationQuaternion, translation);\n if (targetPath === \"position\") {\n translation = value;\n }\n else if (targetPath === \"rotationQuaternion\") {\n rotationQuaternion = value;\n }\n else {\n scaling = value;\n }\n value = Matrix.Compose(scaling, rotationQuaternion, translation);\n }\n if (!modifyKey) {\n keys.push({\n frame: bufferInput[j],\n value: value,\n });\n }\n else if (lastAnimation) {\n lastAnimation.getKeys()[j].value = value;\n }\n }\n // Finish\n if (!modifyKey && babylonAnimation) {\n babylonAnimation.setKeys(keys);\n targetNode.animations.push(babylonAnimation);\n }\n lastAnimation = babylonAnimation;\n gltfRuntime.scene.stopAnimation(targetNode);\n gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);\n }\n }\n};\n/**\n * Returns the bones transformation matrix\n * @param node\n */\nconst configureBoneTransformation = (node) => {\n let mat = null;\n if (node.translation || node.rotation || node.scale) {\n const scale = Vector3.FromArray(node.scale || [1, 1, 1]);\n const rotation = Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);\n const position = Vector3.FromArray(node.translation || [0, 0, 0]);\n mat = Matrix.Compose(scale, rotation, position);\n }\n else {\n mat = Matrix.FromArray(node.matrix);\n }\n return mat;\n};\n/**\n * Returns the parent bone\n * @param gltfRuntime\n * @param skins\n * @param jointName\n * @param newSkeleton\n */\nconst getParentBone = (gltfRuntime, skins, jointName, newSkeleton) => {\n // Try to find\n for (let i = 0; i < newSkeleton.bones.length; i++) {\n if (newSkeleton.bones[i].name === jointName) {\n return newSkeleton.bones[i];\n }\n }\n // Not found, search in gltf nodes\n const nodes = gltfRuntime.nodes;\n for (const nde in nodes) {\n const node = nodes[nde];\n if (!node.jointName) {\n continue;\n }\n const children = node.children;\n for (let i = 0; i < children.length; i++) {\n const child = gltfRuntime.nodes[children[i]];\n if (!child.jointName) {\n continue;\n }\n if (child.jointName === jointName) {\n const mat = configureBoneTransformation(node);\n const bone = new Bone(node.name || \"\", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);\n bone.id = nde;\n return bone;\n }\n }\n }\n return null;\n};\n/**\n * Returns the appropriate root node\n * @param nodesToRoot\n * @param id\n */\nconst getNodeToRoot = (nodesToRoot, id) => {\n for (let i = 0; i < nodesToRoot.length; i++) {\n const nodeToRoot = nodesToRoot[i];\n for (let j = 0; j < nodeToRoot.node.children.length; j++) {\n const child = nodeToRoot.node.children[j];\n if (child === id) {\n return nodeToRoot.bone;\n }\n }\n }\n return null;\n};\n/**\n * Returns the node with the joint name\n * @param gltfRuntime\n * @param jointName\n */\nconst getJointNode = (gltfRuntime, jointName) => {\n const nodes = gltfRuntime.nodes;\n let node = nodes[jointName];\n if (node) {\n return {\n node: node,\n id: jointName,\n };\n }\n for (const nde in nodes) {\n node = nodes[nde];\n if (node.jointName === jointName) {\n return {\n node: node,\n id: nde,\n };\n }\n }\n return null;\n};\n/**\n * Checks if a nodes is in joints\n * @param skins\n * @param id\n */\nconst nodeIsInJoints = (skins, id) => {\n for (let i = 0; i < skins.jointNames.length; i++) {\n if (skins.jointNames[i] === id) {\n return true;\n }\n }\n return false;\n};\n/**\n * Fills the nodes to root for bones and builds hierarchy\n * @param gltfRuntime\n * @param newSkeleton\n * @param skins\n * @param nodesToRoot\n */\nconst getNodesToRoot = (gltfRuntime, newSkeleton, skins, nodesToRoot) => {\n // Creates nodes for root\n for (const nde in gltfRuntime.nodes) {\n const node = gltfRuntime.nodes[nde];\n const id = nde;\n if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {\n continue;\n }\n // Create node to root bone\n const mat = configureBoneTransformation(node);\n const bone = new Bone(node.name || \"\", newSkeleton, null, mat);\n bone.id = id;\n nodesToRoot.push({ bone: bone, node: node, id: id });\n }\n // Parenting\n for (let i = 0; i < nodesToRoot.length; i++) {\n const nodeToRoot = nodesToRoot[i];\n const children = nodeToRoot.node.children;\n for (let j = 0; j < children.length; j++) {\n let child = null;\n for (let k = 0; k < nodesToRoot.length; k++) {\n if (nodesToRoot[k].id === children[j]) {\n child = nodesToRoot[k];\n break;\n }\n }\n if (child) {\n child.bone._parent = nodeToRoot.bone;\n nodeToRoot.bone.children.push(child.bone);\n }\n }\n }\n};\n/**\n * Imports a skeleton\n * @param gltfRuntime\n * @param skins\n * @param mesh\n * @param newSkeleton\n */\nconst importSkeleton = (gltfRuntime, skins, mesh, newSkeleton) => {\n if (!newSkeleton) {\n newSkeleton = new Skeleton(skins.name || \"\", \"\", gltfRuntime.scene);\n }\n if (!skins.babylonSkeleton) {\n return newSkeleton;\n }\n // Find the root bones\n const nodesToRoot = [];\n const nodesToRootToAdd = [];\n getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);\n newSkeleton.bones = [];\n // Joints\n for (let i = 0; i < skins.jointNames.length; i++) {\n const jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);\n if (!jointNode) {\n continue;\n }\n const node = jointNode.node;\n if (!node) {\n Tools.Warn(\"Joint named \" + skins.jointNames[i] + \" does not exist\");\n continue;\n }\n const id = jointNode.id;\n // Optimize, if the bone already exists...\n const existingBone = gltfRuntime.scene.getBoneById(id);\n if (existingBone) {\n newSkeleton.bones.push(existingBone);\n continue;\n }\n // Search for parent bone\n let foundBone = false;\n let parentBone = null;\n for (let j = 0; j < i; j++) {\n const jointNode = getJointNode(gltfRuntime, skins.jointNames[j]);\n if (!jointNode) {\n continue;\n }\n const joint = jointNode.node;\n if (!joint) {\n Tools.Warn(\"Joint named \" + skins.jointNames[j] + \" does not exist when looking for parent\");\n continue;\n }\n const children = joint.children;\n if (!children) {\n continue;\n }\n foundBone = false;\n for (let k = 0; k < children.length; k++) {\n if (children[k] === id) {\n parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);\n foundBone = true;\n break;\n }\n }\n if (foundBone) {\n break;\n }\n }\n // Create bone\n const mat = configureBoneTransformation(node);\n if (!parentBone && nodesToRoot.length > 0) {\n parentBone = getNodeToRoot(nodesToRoot, id);\n if (parentBone) {\n if (nodesToRootToAdd.indexOf(parentBone) === -1) {\n nodesToRootToAdd.push(parentBone);\n }\n }\n }\n const bone = new Bone(node.jointName || \"\", newSkeleton, parentBone, mat);\n bone.id = id;\n }\n // Polish\n const bones = newSkeleton.bones;\n newSkeleton.bones = [];\n for (let i = 0; i < skins.jointNames.length; i++) {\n const jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);\n if (!jointNode) {\n continue;\n }\n for (let j = 0; j < bones.length; j++) {\n if (bones[j].id === jointNode.id) {\n newSkeleton.bones.push(bones[j]);\n break;\n }\n }\n }\n newSkeleton.prepare();\n // Finish\n for (let i = 0; i < nodesToRootToAdd.length; i++) {\n newSkeleton.bones.push(nodesToRootToAdd[i]);\n }\n return newSkeleton;\n};\n/**\n * Imports a mesh and its geometries\n * @param gltfRuntime\n * @param node\n * @param meshes\n * @param id\n * @param newMesh\n */\nconst importMesh = (gltfRuntime, node, meshes, id, newMesh) => {\n if (!newMesh) {\n gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;\n newMesh = new Mesh(node.name || \"\", gltfRuntime.scene);\n newMesh._parentContainer = gltfRuntime.assetContainer;\n gltfRuntime.scene._blockEntityCollection = false;\n newMesh.id = id;\n }\n if (!node.babylonNode) {\n return newMesh;\n }\n const subMaterials = [];\n let vertexData = null;\n const verticesStarts = new Array();\n const verticesCounts = new Array();\n const indexStarts = new Array();\n const indexCounts = new Array();\n for (let meshIndex = 0; meshIndex < meshes.length; meshIndex++) {\n const meshId = meshes[meshIndex];\n const mesh = gltfRuntime.meshes[meshId];\n if (!mesh) {\n continue;\n }\n // Positions, normals and UVs\n for (let i = 0; i < mesh.primitives.length; i++) {\n // Temporary vertex data\n const tempVertexData = new VertexData();\n const primitive = mesh.primitives[i];\n if (primitive.mode !== 4) {\n // continue;\n }\n const attributes = primitive.attributes;\n let accessor = null;\n let buffer = null;\n // Set positions, normal and uvs\n for (const semantic in attributes) {\n // Link accessor and buffer view\n accessor = gltfRuntime.accessors[attributes[semantic]];\n buffer = GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);\n if (semantic === \"NORMAL\") {\n tempVertexData.normals = new Float32Array(buffer.length);\n tempVertexData.normals.set(buffer);\n }\n else if (semantic === \"POSITION\") {\n if (GLTFFileLoader.HomogeneousCoordinates) {\n tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);\n for (let j = 0; j < buffer.length; j += 4) {\n tempVertexData.positions[j] = buffer[j];\n tempVertexData.positions[j + 1] = buffer[j + 1];\n tempVertexData.positions[j + 2] = buffer[j + 2];\n }\n }\n else {\n tempVertexData.positions = new Float32Array(buffer.length);\n tempVertexData.positions.set(buffer);\n }\n verticesCounts.push(tempVertexData.positions.length);\n }\n else if (semantic.indexOf(\"TEXCOORD_\") !== -1) {\n const channel = Number(semantic.split(\"_\")[1]);\n const uvKind = VertexBuffer.UVKind + (channel === 0 ? \"\" : channel + 1);\n const uvs = new Float32Array(buffer.length);\n uvs.set(buffer);\n normalizeUVs(uvs);\n tempVertexData.set(uvs, uvKind);\n }\n else if (semantic === \"JOINT\") {\n tempVertexData.matricesIndices = new Float32Array(buffer.length);\n tempVertexData.matricesIndices.set(buffer);\n }\n else if (semantic === \"WEIGHT\") {\n tempVertexData.matricesWeights = new Float32Array(buffer.length);\n tempVertexData.matricesWeights.set(buffer);\n }\n else if (semantic === \"COLOR\") {\n tempVertexData.colors = new Float32Array(buffer.length);\n tempVertexData.colors.set(buffer);\n }\n }\n // Indices\n accessor = gltfRuntime.accessors[primitive.indices];\n if (accessor) {\n buffer = GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);\n tempVertexData.indices = new Int32Array(buffer.length);\n tempVertexData.indices.set(buffer);\n indexCounts.push(tempVertexData.indices.length);\n }\n else {\n // Set indices on the fly\n const indices = [];\n for (let j = 0; j < tempVertexData.positions.length / 3; j++) {\n indices.push(j);\n }\n tempVertexData.indices = new Int32Array(indices);\n indexCounts.push(tempVertexData.indices.length);\n }\n if (!vertexData) {\n vertexData = tempVertexData;\n }\n else {\n vertexData.merge(tempVertexData);\n }\n // Sub material\n const material = gltfRuntime.scene.getMaterialById(primitive.material);\n subMaterials.push(material === null ? GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);\n // Update vertices start and index start\n verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);\n indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);\n }\n }\n let material;\n gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;\n if (subMaterials.length > 1) {\n material = new MultiMaterial(\"multimat\" + id, gltfRuntime.scene);\n material.subMaterials = subMaterials;\n }\n else {\n material = new StandardMaterial(\"multimat\" + id, gltfRuntime.scene);\n }\n if (subMaterials.length === 1) {\n material = subMaterials[0];\n }\n material._parentContainer = gltfRuntime.assetContainer;\n if (!newMesh.material) {\n newMesh.material = material;\n }\n // Apply geometry\n new Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);\n newMesh.computeWorldMatrix(true);\n gltfRuntime.scene._blockEntityCollection = false;\n // Apply submeshes\n newMesh.subMeshes = [];\n let index = 0;\n for (let meshIndex = 0; meshIndex < meshes.length; meshIndex++) {\n const meshId = meshes[meshIndex];\n const mesh = gltfRuntime.meshes[meshId];\n if (!mesh) {\n continue;\n }\n for (let i = 0; i < mesh.primitives.length; i++) {\n if (mesh.primitives[i].mode !== 4) {\n //continue;\n }\n SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);\n index++;\n }\n }\n // Finish\n return newMesh;\n};\n/**\n * Configure node transformation from position, rotation and scaling\n * @param newNode\n * @param position\n * @param rotation\n * @param scaling\n */\nconst configureNode = (newNode, position, rotation, scaling) => {\n if (newNode.position) {\n newNode.position = position;\n }\n if (newNode.rotationQuaternion || newNode.rotation) {\n newNode.rotationQuaternion = rotation;\n }\n if (newNode.scaling) {\n newNode.scaling = scaling;\n }\n};\n/**\n * Configures node from transformation matrix\n * @param newNode\n * @param node\n */\nconst configureNodeFromMatrix = (newNode, node) => {\n if (node.matrix) {\n const position = new Vector3(0, 0, 0);\n const rotation = new Quaternion();\n const scaling = new Vector3(0, 0, 0);\n const mat = Matrix.FromArray(node.matrix);\n mat.decompose(scaling, rotation, position);\n configureNode(newNode, position, rotation, scaling);\n }\n else if (node.translation && node.rotation && node.scale) {\n configureNode(newNode, Vector3.FromArray(node.translation), Quaternion.FromArray(node.rotation), Vector3.FromArray(node.scale));\n }\n newNode.computeWorldMatrix(true);\n};\n/**\n * Imports a node\n * @param gltfRuntime\n * @param node\n * @param id\n */\nconst importNode = (gltfRuntime, node, id) => {\n let lastNode = null;\n if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {\n if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || \"\") === -1) {\n return null;\n }\n }\n // Meshes\n if (node.skin) {\n if (node.meshes) {\n const skin = gltfRuntime.skins[node.skin];\n const newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);\n newMesh.skeleton = gltfRuntime.scene.getLastSkeletonById(node.skin);\n if (newMesh.skeleton === null) {\n newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton);\n if (!skin.babylonSkeleton) {\n skin.babylonSkeleton = newMesh.skeleton;\n }\n }\n lastNode = newMesh;\n }\n }\n else if (node.meshes) {\n /**\n * Improve meshes property\n */\n const newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);\n lastNode = newMesh;\n }\n // Lights\n else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {\n const light = gltfRuntime.lights[node.light];\n if (light) {\n if (light.type === \"ambient\") {\n const ambienLight = light[light.type];\n const hemiLight = new HemisphericLight(node.light, Vector3.Zero(), gltfRuntime.scene);\n hemiLight.name = node.name || \"\";\n if (ambienLight.color) {\n hemiLight.diffuse = Color3.FromArray(ambienLight.color);\n }\n lastNode = hemiLight;\n }\n else if (light.type === \"directional\") {\n const directionalLight = light[light.type];\n const dirLight = new DirectionalLight(node.light, Vector3.Zero(), gltfRuntime.scene);\n dirLight.name = node.name || \"\";\n if (directionalLight.color) {\n dirLight.diffuse = Color3.FromArray(directionalLight.color);\n }\n lastNode = dirLight;\n }\n else if (light.type === \"point\") {\n const pointLight = light[light.type];\n const ptLight = new PointLight(node.light, Vector3.Zero(), gltfRuntime.scene);\n ptLight.name = node.name || \"\";\n if (pointLight.color) {\n ptLight.diffuse = Color3.FromArray(pointLight.color);\n }\n lastNode = ptLight;\n }\n else if (light.type === \"spot\") {\n const spotLight = light[light.type];\n const spLight = new SpotLight(node.light, Vector3.Zero(), Vector3.Zero(), 0, 0, gltfRuntime.scene);\n spLight.name = node.name || \"\";\n if (spotLight.color) {\n spLight.diffuse = Color3.FromArray(spotLight.color);\n }\n if (spotLight.fallOfAngle) {\n spLight.angle = spotLight.fallOfAngle;\n }\n if (spotLight.fallOffExponent) {\n spLight.exponent = spotLight.fallOffExponent;\n }\n lastNode = spLight;\n }\n }\n }\n // Cameras\n else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {\n const camera = gltfRuntime.cameras[node.camera];\n if (camera) {\n gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;\n if (camera.type === \"orthographic\") {\n const orthoCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene, false);\n orthoCamera.name = node.name || \"\";\n orthoCamera.mode = Camera.ORTHOGRAPHIC_CAMERA;\n orthoCamera.attachControl();\n lastNode = orthoCamera;\n orthoCamera._parentContainer = gltfRuntime.assetContainer;\n }\n else if (camera.type === \"perspective\") {\n const perspectiveCamera = camera[camera.type];\n const persCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene, false);\n persCamera.name = node.name || \"\";\n persCamera.attachControl();\n if (!perspectiveCamera.aspectRatio) {\n perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();\n }\n if (perspectiveCamera.znear && perspectiveCamera.zfar) {\n persCamera.maxZ = perspectiveCamera.zfar;\n persCamera.minZ = perspectiveCamera.znear;\n }\n lastNode = persCamera;\n persCamera._parentContainer = gltfRuntime.assetContainer;\n }\n gltfRuntime.scene._blockEntityCollection = false;\n }\n }\n // Empty node\n if (!node.jointName) {\n if (node.babylonNode) {\n return node.babylonNode;\n }\n else if (lastNode === null) {\n gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;\n const dummy = new Mesh(node.name || \"\", gltfRuntime.scene);\n dummy._parentContainer = gltfRuntime.assetContainer;\n gltfRuntime.scene._blockEntityCollection = false;\n node.babylonNode = dummy;\n lastNode = dummy;\n }\n }\n if (lastNode !== null) {\n if (node.matrix && lastNode instanceof Mesh) {\n configureNodeFromMatrix(lastNode, node);\n }\n else {\n const translation = node.translation || [0, 0, 0];\n const rotation = node.rotation || [0, 0, 0, 1];\n const scale = node.scale || [1, 1, 1];\n configureNode(lastNode, Vector3.FromArray(translation), Quaternion.FromArray(rotation), Vector3.FromArray(scale));\n }\n lastNode.updateCache(true);\n node.babylonNode = lastNode;\n }\n return lastNode;\n};\n/**\n * Traverses nodes and creates them\n * @param gltfRuntime\n * @param id\n * @param parent\n * @param meshIncluded\n */\nconst traverseNodes = (gltfRuntime, id, parent, meshIncluded = false) => {\n const node = gltfRuntime.nodes[id];\n let newNode = null;\n if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {\n if (gltfRuntime.importMeshesNames.indexOf(node.name || \"\") !== -1 || gltfRuntime.importMeshesNames.length === 0) {\n meshIncluded = true;\n }\n else {\n meshIncluded = false;\n }\n }\n else {\n meshIncluded = true;\n }\n if (!node.jointName && meshIncluded) {\n newNode = importNode(gltfRuntime, node, id);\n if (newNode !== null) {\n newNode.id = id;\n newNode.parent = parent;\n }\n }\n if (node.children) {\n for (let i = 0; i < node.children.length; i++) {\n traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);\n }\n }\n};\n/**\n * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)\n * @param gltfRuntime\n */\nconst postLoad = (gltfRuntime) => {\n // Nodes\n let currentScene = gltfRuntime.currentScene;\n if (currentScene) {\n for (let i = 0; i < currentScene.nodes.length; i++) {\n traverseNodes(gltfRuntime, currentScene.nodes[i], null);\n }\n }\n else {\n for (const thing in gltfRuntime.scenes) {\n currentScene = gltfRuntime.scenes[thing];\n for (let i = 0; i < currentScene.nodes.length; i++) {\n traverseNodes(gltfRuntime, currentScene.nodes[i], null);\n }\n }\n }\n // Set animations\n loadAnimations(gltfRuntime);\n for (let i = 0; i < gltfRuntime.scene.skeletons.length; i++) {\n const skeleton = gltfRuntime.scene.skeletons[i];\n gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);\n }\n};\n/**\n * onBind shaderrs callback to set uniforms and matrices\n * @param mesh\n * @param gltfRuntime\n * @param unTreatedUniforms\n * @param shaderMaterial\n * @param technique\n * @param material\n * @param onSuccess\n */\nconst onBindShaderMaterial = (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) => {\n const materialValues = material.values || technique.parameters;\n for (const unif in unTreatedUniforms) {\n const uniform = unTreatedUniforms[unif];\n const type = uniform.type;\n if (type === EParameterType.FLOAT_MAT2 || type === EParameterType.FLOAT_MAT3 || type === EParameterType.FLOAT_MAT4) {\n if (uniform.semantic && !uniform.source && !uniform.node) {\n GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());\n }\n else if (uniform.semantic && (uniform.source || uniform.node)) {\n let source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || \"\");\n if (source === null) {\n source = gltfRuntime.scene.getNodeById(uniform.source || uniform.node || \"\");\n }\n if (source === null) {\n continue;\n }\n GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());\n }\n }\n else {\n const value = materialValues[technique.uniforms[unif]];\n if (!value) {\n continue;\n }\n if (type === EParameterType.SAMPLER_2D) {\n const texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;\n if (texture === null || texture === undefined) {\n continue;\n }\n shaderMaterial.getEffect().setTexture(unif, texture);\n }\n else {\n GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);\n }\n }\n }\n onSuccess(shaderMaterial);\n};\n/**\n * Prepare uniforms to send the only one time\n * Loads the appropriate textures\n * @param gltfRuntime\n * @param shaderMaterial\n * @param technique\n * @param material\n */\nconst prepareShaderMaterialUniforms = (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) => {\n const materialValues = material.values || technique.parameters;\n const techniqueUniforms = technique.uniforms;\n /**\n * Prepare values here (not matrices)\n */\n for (const unif in unTreatedUniforms) {\n const uniform = unTreatedUniforms[unif];\n const type = uniform.type;\n let value = materialValues[techniqueUniforms[unif]];\n if (value === undefined) {\n // In case the value is the same for all materials\n value = uniform.value;\n }\n if (!value) {\n continue;\n }\n const onLoadTexture = (uniformName) => {\n return (texture) => {\n if (uniform.value && uniformName) {\n // Static uniform\n shaderMaterial.setTexture(uniformName, texture);\n delete unTreatedUniforms[uniformName];\n }\n };\n };\n // Texture (sampler2D)\n if (type === EParameterType.SAMPLER_2D) {\n GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), () => onLoadTexture(null));\n }\n // Others\n else {\n if (uniform.value && GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {\n // Static uniform\n delete unTreatedUniforms[unif];\n }\n }\n }\n};\n/**\n * Shader compilation failed\n * @param program\n * @param shaderMaterial\n * @param onError\n */\nconst onShaderCompileError = (program, shaderMaterial, onError) => {\n return (effect, error) => {\n shaderMaterial.dispose(true);\n onError(\"Cannot compile program named \" + program.name + \". Error: \" + error + \". Default material will be applied\");\n };\n};\n/**\n * Shader compilation success\n * @param gltfRuntime\n * @param shaderMaterial\n * @param technique\n * @param material\n * @param unTreatedUniforms\n * @param onSuccess\n */\nconst onShaderCompileSuccess = (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) => {\n return (_) => {\n prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);\n shaderMaterial.onBind = (mesh) => {\n onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);\n };\n };\n};\n/**\n * Returns the appropriate uniform if already handled by babylon\n * @param tokenizer\n * @param technique\n */\nconst parseShaderUniforms = (tokenizer, technique, unTreatedUniforms) => {\n for (const unif in technique.uniforms) {\n const uniform = technique.uniforms[unif];\n const uniformParameter = technique.parameters[uniform];\n if (tokenizer.currentIdentifier === unif) {\n if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {\n const transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);\n if (transformIndex !== -1) {\n delete unTreatedUniforms[unif];\n return babylonTransforms[transformIndex];\n }\n }\n }\n }\n return tokenizer.currentIdentifier;\n};\n/**\n * All shaders loaded. Create materials one by one\n * @param gltfRuntime\n */\nconst importMaterials = (gltfRuntime) => {\n // Create materials\n for (const mat in gltfRuntime.materials) {\n GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, () => { }, () => { });\n }\n};\n/**\n * Implementation of the base glTF spec\n * @internal\n */\nexport class GLTFLoaderBase {\n static CreateRuntime(parsedData, scene, rootUrl) {\n const gltfRuntime = {\n extensions: {},\n accessors: {},\n buffers: {},\n bufferViews: {},\n meshes: {},\n lights: {},\n cameras: {},\n nodes: {},\n images: {},\n textures: {},\n shaders: {},\n programs: {},\n samplers: {},\n techniques: {},\n materials: {},\n animations: {},\n skins: {},\n extensionsUsed: [],\n scenes: {},\n buffersCount: 0,\n shaderscount: 0,\n scene: scene,\n rootUrl: rootUrl,\n loadedBufferCount: 0,\n loadedBufferViews: {},\n loadedShaderCount: 0,\n importOnlyMeshes: false,\n dummyNodes: [],\n assetContainer: null,\n };\n // Parse\n if (parsedData.extensions) {\n parseObject(parsedData.extensions, \"extensions\", gltfRuntime);\n }\n if (parsedData.extensionsUsed) {\n parseObject(parsedData.extensionsUsed, \"extensionsUsed\", gltfRuntime);\n }\n if (parsedData.buffers) {\n parseBuffers(parsedData.buffers, gltfRuntime);\n }\n if (parsedData.bufferViews) {\n parseObject(parsedData.bufferViews, \"bufferViews\", gltfRuntime);\n }\n if (parsedData.accessors) {\n parseObject(parsedData.accessors, \"accessors\", gltfRuntime);\n }\n if (parsedData.meshes) {\n parseObject(parsedData.meshes, \"meshes\", gltfRuntime);\n }\n if (parsedData.lights) {\n parseObject(parsedData.lights, \"lights\", gltfRuntime);\n }\n if (parsedData.cameras) {\n parseObject(parsedData.cameras, \"cameras\", gltfRuntime);\n }\n if (parsedData.nodes) {\n parseObject(parsedData.nodes, \"nodes\", gltfRuntime);\n }\n if (parsedData.images) {\n parseObject(parsedData.images, \"images\", gltfRuntime);\n }\n if (parsedData.textures) {\n parseObject(parsedData.textures, \"textures\", gltfRuntime);\n }\n if (parsedData.shaders) {\n parseShaders(parsedData.shaders, gltfRuntime);\n }\n if (parsedData.programs) {\n parseObject(parsedData.programs, \"programs\", gltfRuntime);\n }\n if (parsedData.samplers) {\n parseObject(parsedData.samplers, \"samplers\", gltfRuntime);\n }\n if (parsedData.techniques) {\n parseObject(parsedData.techniques, \"techniques\", gltfRuntime);\n }\n if (parsedData.materials) {\n parseObject(parsedData.materials, \"materials\", gltfRuntime);\n }\n if (parsedData.animations) {\n parseObject(parsedData.animations, \"animations\", gltfRuntime);\n }\n if (parsedData.skins) {\n parseObject(parsedData.skins, \"skins\", gltfRuntime);\n }\n if (parsedData.scenes) {\n gltfRuntime.scenes = parsedData.scenes;\n }\n if (parsedData.scene && parsedData.scenes) {\n gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];\n }\n return gltfRuntime;\n }\n static LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress) {\n const buffer = gltfRuntime.buffers[id];\n if (Tools.IsBase64(buffer.uri)) {\n setTimeout(() => onSuccess(new Uint8Array(Tools.DecodeBase64(buffer.uri))));\n }\n else {\n Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, (data) => onSuccess(new Uint8Array(data)), onProgress, undefined, true, (request) => {\n if (request) {\n onError(request.status + \" \" + request.statusText);\n }\n });\n }\n }\n static LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError) {\n const texture = gltfRuntime.textures[id];\n if (!texture || !texture.source) {\n onError(\"\");\n return;\n }\n if (texture.babylonTexture) {\n onSuccess(null);\n return;\n }\n const source = gltfRuntime.images[texture.source];\n if (Tools.IsBase64(source.uri)) {\n setTimeout(() => onSuccess(new Uint8Array(Tools.DecodeBase64(source.uri))));\n }\n else {\n Tools.LoadFile(gltfRuntime.rootUrl + source.uri, (data) => onSuccess(new Uint8Array(data)), undefined, undefined, true, (request) => {\n if (request) {\n onError(request.status + \" \" + request.statusText);\n }\n });\n }\n }\n static CreateTextureAsync(gltfRuntime, id, buffer, onSuccess) {\n const texture = gltfRuntime.textures[id];\n if (texture.babylonTexture) {\n onSuccess(texture.babylonTexture);\n return;\n }\n const sampler = gltfRuntime.samplers[texture.sampler];\n const createMipMaps = sampler.minFilter === ETextureFilterType.NEAREST_MIPMAP_NEAREST ||\n sampler.minFilter === ETextureFilterType.NEAREST_MIPMAP_LINEAR ||\n sampler.minFilter === ETextureFilterType.LINEAR_MIPMAP_NEAREST ||\n sampler.minFilter === ETextureFilterType.LINEAR_MIPMAP_LINEAR;\n const samplingMode = Texture.BILINEAR_SAMPLINGMODE;\n const blob = buffer == null ? new Blob() : new Blob([buffer]);\n const blobURL = URL.createObjectURL(blob);\n const revokeBlobURL = () => URL.revokeObjectURL(blobURL);\n const newTexture = new Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);\n if (sampler.wrapS !== undefined) {\n newTexture.wrapU = GLTFUtils.GetWrapMode(sampler.wrapS);\n }\n if (sampler.wrapT !== undefined) {\n newTexture.wrapV = GLTFUtils.GetWrapMode(sampler.wrapT);\n }\n newTexture.name = id;\n texture.babylonTexture = newTexture;\n onSuccess(newTexture);\n }\n static LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError) {\n const shader = gltfRuntime.shaders[id];\n if (Tools.IsBase64(shader.uri)) {\n const shaderString = atob(shader.uri.split(\",\")[1]);\n if (onSuccess) {\n onSuccess(shaderString);\n }\n }\n else {\n Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, (request) => {\n if (request && onError) {\n onError(request.status + \" \" + request.statusText);\n }\n });\n }\n }\n static LoadMaterialAsync(gltfRuntime, id, onSuccess, onError) {\n const material = gltfRuntime.materials[id];\n if (!material.technique) {\n if (onError) {\n onError(\"No technique found.\");\n }\n return;\n }\n const technique = gltfRuntime.techniques[material.technique];\n if (!technique) {\n gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;\n const defaultMaterial = new StandardMaterial(id, gltfRuntime.scene);\n defaultMaterial._parentContainer = gltfRuntime.assetContainer;\n gltfRuntime.scene._blockEntityCollection = false;\n defaultMaterial.diffuseColor = new Color3(0.5, 0.5, 0.5);\n defaultMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;\n onSuccess(defaultMaterial);\n return;\n }\n const program = gltfRuntime.programs[technique.program];\n const states = technique.states;\n const vertexShader = Effect.ShadersStore[program.vertexShader + \"VertexShader\"];\n const pixelShader = Effect.ShadersStore[program.fragmentShader + \"PixelShader\"];\n let newVertexShader = \"\";\n let newPixelShader = \"\";\n const vertexTokenizer = new Tokenizer(vertexShader);\n const pixelTokenizer = new Tokenizer(pixelShader);\n const unTreatedUniforms = {};\n const uniforms = [];\n const attributes = [];\n const samplers = [];\n // Fill uniform, sampler2D and attributes\n for (const unif in technique.uniforms) {\n const uniform = technique.uniforms[unif];\n const uniformParameter = technique.parameters[uniform];\n unTreatedUniforms[unif] = uniformParameter;\n if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {\n const transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);\n if (transformIndex !== -1) {\n uniforms.push(babylonTransforms[transformIndex]);\n delete unTreatedUniforms[unif];\n }\n else {\n uniforms.push(unif);\n }\n }\n else if (uniformParameter.type === EParameterType.SAMPLER_2D) {\n samplers.push(unif);\n }\n else {\n uniforms.push(unif);\n }\n }\n for (const attr in technique.attributes) {\n const attribute = technique.attributes[attr];\n const attributeParameter = technique.parameters[attribute];\n if (attributeParameter.semantic) {\n const name = getAttribute(attributeParameter);\n if (name) {\n attributes.push(name);\n }\n }\n }\n // Configure vertex shader\n while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {\n const tokenType = vertexTokenizer.currentToken;\n if (tokenType !== ETokenType.IDENTIFIER) {\n newVertexShader += vertexTokenizer.currentString;\n continue;\n }\n let foundAttribute = false;\n for (const attr in technique.attributes) {\n const attribute = technique.attributes[attr];\n const attributeParameter = technique.parameters[attribute];\n if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {\n newVertexShader += getAttribute(attributeParameter);\n foundAttribute = true;\n break;\n }\n }\n if (foundAttribute) {\n continue;\n }\n newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);\n }\n // Configure pixel shader\n while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {\n const tokenType = pixelTokenizer.currentToken;\n if (tokenType !== ETokenType.IDENTIFIER) {\n newPixelShader += pixelTokenizer.currentString;\n continue;\n }\n newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);\n }\n // Create shader material\n const shaderPath = {\n vertex: program.vertexShader + id,\n fragment: program.fragmentShader + id,\n };\n const options = {\n attributes: attributes,\n uniforms: uniforms,\n samplers: samplers,\n needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1,\n };\n Effect.ShadersStore[program.vertexShader + id + \"VertexShader\"] = newVertexShader;\n Effect.ShadersStore[program.fragmentShader + id + \"PixelShader\"] = newPixelShader;\n const shaderMaterial = new ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);\n shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);\n shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);\n shaderMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;\n if (states && states.functions) {\n const functions = states.functions;\n if (functions.cullFace && functions.cullFace[0] !== ECullingType.BACK) {\n shaderMaterial.backFaceCulling = false;\n }\n const blendFunc = functions.blendFuncSeparate;\n if (blendFunc) {\n if (blendFunc[0] === EBlendingFunction.SRC_ALPHA &&\n blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_ALPHA &&\n blendFunc[2] === EBlendingFunction.ONE &&\n blendFunc[3] === EBlendingFunction.ONE) {\n shaderMaterial.alphaMode = Constants.ALPHA_COMBINE;\n }\n else if (blendFunc[0] === EBlendingFunction.ONE &&\n blendFunc[1] === EBlendingFunction.ONE &&\n blendFunc[2] === EBlendingFunction.ZERO &&\n blendFunc[3] === EBlendingFunction.ONE) {\n shaderMaterial.alphaMode = Constants.ALPHA_ONEONE;\n }\n else if (blendFunc[0] === EBlendingFunction.SRC_ALPHA &&\n blendFunc[1] === EBlendingFunction.ONE &&\n blendFunc[2] === EBlendingFunction.ZERO &&\n blendFunc[3] === EBlendingFunction.ONE) {\n shaderMaterial.alphaMode = Constants.ALPHA_ADD;\n }\n else if (blendFunc[0] === EBlendingFunction.ZERO &&\n blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR &&\n blendFunc[2] === EBlendingFunction.ONE &&\n blendFunc[3] === EBlendingFunction.ONE) {\n shaderMaterial.alphaMode = Constants.ALPHA_SUBTRACT;\n }\n else if (blendFunc[0] === EBlendingFunction.DST_COLOR &&\n blendFunc[1] === EBlendingFunction.ZERO &&\n blendFunc[2] === EBlendingFunction.ONE &&\n blendFunc[3] === EBlendingFunction.ONE) {\n shaderMaterial.alphaMode = Constants.ALPHA_MULTIPLY;\n }\n else if (blendFunc[0] === EBlendingFunction.SRC_ALPHA &&\n blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR &&\n blendFunc[2] === EBlendingFunction.ONE &&\n blendFunc[3] === EBlendingFunction.ONE) {\n shaderMaterial.alphaMode = Constants.ALPHA_MAXIMIZED;\n }\n }\n }\n }\n}\n/**\n * glTF V1 Loader\n * @internal\n * @deprecated\n */\nexport class GLTFLoader {\n static RegisterExtension(extension) {\n if (GLTFLoader.Extensions[extension.name]) {\n Tools.Error('Tool with the same name \"' + extension.name + '\" already exists');\n return;\n }\n GLTFLoader.Extensions[extension.name] = extension;\n }\n dispose() {\n // do nothing\n }\n _importMeshAsync(meshesNames, scene, data, rootUrl, assetContainer, onSuccess, onProgress, onError) {\n scene.useRightHandedSystem = true;\n GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, (gltfRuntime) => {\n gltfRuntime.assetContainer = assetContainer;\n gltfRuntime.importOnlyMeshes = true;\n if (meshesNames === \"\") {\n gltfRuntime.importMeshesNames = [];\n }\n else if (typeof meshesNames === \"string\") {\n gltfRuntime.importMeshesNames = [meshesNames];\n }\n else if (meshesNames && !(meshesNames instanceof Array)) {\n gltfRuntime.importMeshesNames = [meshesNames];\n }\n else {\n gltfRuntime.importMeshesNames = [];\n Tools.Warn(\"Argument meshesNames must be of type string or string[]\");\n }\n // Create nodes\n this._createNodes(gltfRuntime);\n const meshes = new Array();\n const skeletons = new Array();\n // Fill arrays of meshes and skeletons\n for (const nde in gltfRuntime.nodes) {\n const node = gltfRuntime.nodes[nde];\n if (node.babylonNode instanceof AbstractMesh) {\n meshes.push(node.babylonNode);\n }\n }\n for (const skl in gltfRuntime.skins) {\n const skin = gltfRuntime.skins[skl];\n if (skin.babylonSkeleton instanceof Skeleton) {\n skeletons.push(skin.babylonSkeleton);\n }\n }\n // Load buffers, shaders, materials, etc.\n this._loadBuffersAsync(gltfRuntime, () => {\n this._loadShadersAsync(gltfRuntime, () => {\n importMaterials(gltfRuntime);\n postLoad(gltfRuntime);\n if (!GLTFFileLoader.IncrementalLoading && onSuccess) {\n onSuccess(meshes, skeletons);\n }\n });\n });\n if (GLTFFileLoader.IncrementalLoading && onSuccess) {\n onSuccess(meshes, skeletons);\n }\n }, onError);\n return true;\n }\n /**\n * Imports one or more meshes from a loaded gltf file and adds them to the scene\n * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file\n * @param scene the scene the meshes should be added to\n * @param assetContainer defines the asset container to use (can be null)\n * @param data gltf data containing information of the meshes in a loaded file\n * @param rootUrl root url to load from\n * @param onProgress event that fires when loading progress has occured\n * @returns a promise containg the loaded meshes, particles, skeletons and animations\n */\n importMeshAsync(meshesNames, scene, assetContainer, data, rootUrl, onProgress) {\n return new Promise((resolve, reject) => {\n this._importMeshAsync(meshesNames, scene, data, rootUrl, assetContainer, (meshes, skeletons) => {\n resolve({\n meshes: meshes,\n particleSystems: [],\n skeletons: skeletons,\n animationGroups: [],\n lights: [],\n transformNodes: [],\n geometries: [],\n });\n }, onProgress, (message) => {\n reject(new Error(message));\n });\n });\n }\n _loadAsync(scene, data, rootUrl, onSuccess, onProgress, onError) {\n scene.useRightHandedSystem = true;\n GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, (gltfRuntime) => {\n // Load runtime extensios\n GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, () => {\n // Create nodes\n this._createNodes(gltfRuntime);\n // Load buffers, shaders, materials, etc.\n this._loadBuffersAsync(gltfRuntime, () => {\n this._loadShadersAsync(gltfRuntime, () => {\n importMaterials(gltfRuntime);\n postLoad(gltfRuntime);\n if (!GLTFFileLoader.IncrementalLoading) {\n onSuccess();\n }\n });\n });\n if (GLTFFileLoader.IncrementalLoading) {\n onSuccess();\n }\n }, onError);\n }, onError);\n }\n /**\n * Imports all objects from a loaded gltf file and adds them to the scene\n * @param scene the scene the objects should be added to\n * @param data gltf data containing information of the meshes in a loaded file\n * @param rootUrl root url to load from\n * @param onProgress event that fires when loading progress has occured\n * @returns a promise which completes when objects have been loaded to the scene\n */\n loadAsync(scene, data, rootUrl, onProgress) {\n return new Promise((resolve, reject) => {\n this._loadAsync(scene, data, rootUrl, () => {\n resolve();\n }, onProgress, (message) => {\n reject(new Error(message));\n });\n });\n }\n _loadShadersAsync(gltfRuntime, onload) {\n let hasShaders = false;\n const processShader = (sha, shader) => {\n GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, (shaderString) => {\n if (shaderString instanceof ArrayBuffer) {\n return;\n }\n gltfRuntime.loadedShaderCount++;\n if (shaderString) {\n Effect.ShadersStore[sha + (shader.type === EShaderType.VERTEX ? \"VertexShader\" : \"PixelShader\")] = shaderString;\n }\n if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {\n onload();\n }\n }, () => {\n Tools.Error(\"Error when loading shader program named \" + sha + \" located at \" + shader.uri);\n });\n };\n for (const sha in gltfRuntime.shaders) {\n hasShaders = true;\n const shader = gltfRuntime.shaders[sha];\n if (shader) {\n processShader.bind(this, sha, shader)();\n }\n else {\n Tools.Error(\"No shader named: \" + sha);\n }\n }\n if (!hasShaders) {\n onload();\n }\n }\n _loadBuffersAsync(gltfRuntime, onLoad) {\n let hasBuffers = false;\n const processBuffer = (buf, buffer) => {\n GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, (bufferView) => {\n gltfRuntime.loadedBufferCount++;\n if (bufferView) {\n if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {\n Tools.Error(\"Buffer named \" + buf + \" is length \" + bufferView.byteLength + \". Expected: \" + buffer.byteLength); // Improve error message\n }\n gltfRuntime.loadedBufferViews[buf] = bufferView;\n }\n if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {\n onLoad();\n }\n }, () => {\n Tools.Error(\"Error when loading buffer named \" + buf + \" located at \" + buffer.uri);\n });\n };\n for (const buf in gltfRuntime.buffers) {\n hasBuffers = true;\n const buffer = gltfRuntime.buffers[buf];\n if (buffer) {\n processBuffer.bind(this, buf, buffer)();\n }\n else {\n Tools.Error(\"No buffer named: \" + buf);\n }\n }\n if (!hasBuffers) {\n onLoad();\n }\n }\n _createNodes(gltfRuntime) {\n let currentScene = gltfRuntime.currentScene;\n if (currentScene) {\n // Only one scene even if multiple scenes are defined\n for (let i = 0; i < currentScene.nodes.length; i++) {\n traverseNodes(gltfRuntime, currentScene.nodes[i], null);\n }\n }\n else {\n // Load all scenes\n for (const thing in gltfRuntime.scenes) {\n currentScene = gltfRuntime.scenes[thing];\n for (let i = 0; i < currentScene.nodes.length; i++) {\n traverseNodes(gltfRuntime, currentScene.nodes[i], null);\n }\n }\n }\n }\n}\nGLTFLoader.Extensions = {};\n/** @internal */\nexport class GLTFLoaderExtension {\n constructor(name) {\n this._name = name;\n }\n get name() {\n return this._name;\n }\n /**\n * Defines an override for loading the runtime\n * Return true to stop further extensions from loading the runtime\n * @param scene\n * @param data\n * @param rootUrl\n * @param onSuccess\n * @param onError\n */\n loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError) {\n return false;\n }\n /**\n * Defines an onverride for creating gltf runtime\n * Return true to stop further extensions from creating the runtime\n * @param gltfRuntime\n * @param onSuccess\n * @param onError\n */\n loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError) {\n return false;\n }\n /**\n * Defines an override for loading buffers\n * Return true to stop further extensions from loading this buffer\n * @param gltfRuntime\n * @param id\n * @param onSuccess\n * @param onError\n * @param onProgress\n */\n loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress) {\n return false;\n }\n /**\n * Defines an override for loading texture buffers\n * Return true to stop further extensions from loading this texture data\n * @param gltfRuntime\n * @param id\n * @param onSuccess\n * @param onError\n */\n loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError) {\n return false;\n }\n /**\n * Defines an override for creating textures\n * Return true to stop further extensions from loading this texture\n * @param gltfRuntime\n * @param id\n * @param buffer\n * @param onSuccess\n * @param onError\n */\n createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError) {\n return false;\n }\n /**\n * Defines an override for loading shader strings\n * Return true to stop further extensions from loading this shader data\n * @param gltfRuntime\n * @param id\n * @param onSuccess\n * @param onError\n */\n loadShaderStringAsync(gltfRuntime, id, onSuccess, onError) {\n return false;\n }\n /**\n * Defines an override for loading materials\n * Return true to stop further extensions from loading this material\n * @param gltfRuntime\n * @param id\n * @param onSuccess\n * @param onError\n */\n loadMaterialAsync(gltfRuntime, id, onSuccess, onError) {\n return false;\n }\n // ---------\n // Utilities\n // ---------\n static LoadRuntimeAsync(scene, data, rootUrl, onSuccess, onError) {\n GLTFLoaderExtension._ApplyExtensions((loaderExtension) => {\n return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);\n }, () => {\n setTimeout(() => {\n if (!onSuccess) {\n return;\n }\n onSuccess(GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));\n });\n });\n }\n static LoadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError) {\n GLTFLoaderExtension._ApplyExtensions((loaderExtension) => {\n return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);\n }, () => {\n setTimeout(() => {\n onSuccess();\n });\n });\n }\n static LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress) {\n GLTFLoaderExtension._ApplyExtensions((loaderExtension) => {\n return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);\n }, () => {\n GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);\n });\n }\n static LoadTextureAsync(gltfRuntime, id, onSuccess, onError) {\n GLTFLoaderExtension._LoadTextureBufferAsync(gltfRuntime, id, (buffer) => {\n if (buffer) {\n GLTFLoaderExtension._CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);\n }\n }, onError);\n }\n static LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError) {\n GLTFLoaderExtension._ApplyExtensions((loaderExtension) => {\n return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);\n }, () => {\n GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);\n });\n }\n static LoadMaterialAsync(gltfRuntime, id, onSuccess, onError) {\n GLTFLoaderExtension._ApplyExtensions((loaderExtension) => {\n return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);\n }, () => {\n GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);\n });\n }\n static _LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError) {\n GLTFLoaderExtension._ApplyExtensions((loaderExtension) => {\n return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);\n }, () => {\n GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);\n });\n }\n static _CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError) {\n GLTFLoaderExtension._ApplyExtensions((loaderExtension) => {\n return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);\n }, () => {\n GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess);\n });\n }\n static _ApplyExtensions(func, defaultFunc) {\n for (const extensionName in GLTFLoader.Extensions) {\n const loaderExtension = GLTFLoader.Extensions[extensionName];\n if (func(loaderExtension)) {\n return;\n }\n }\n defaultFunc();\n }\n}\nGLTFFileLoader._CreateGLTF1Loader = () => new GLTFLoader();\n//# sourceMappingURL=glTFLoader.js.map","import { GLTFLoaderExtension, GLTFLoader, GLTFLoaderBase } from \"./glTFLoader.js\";\nimport { GLTFUtils } from \"./glTFLoaderUtils.js\";\nimport { EComponentType } from \"./glTFLoaderInterfaces.js\";\nconst BinaryExtensionBufferName = \"binary_glTF\";\n/**\n * @internal\n * @deprecated\n */\nexport class GLTFBinaryExtension extends GLTFLoaderExtension {\n constructor() {\n super(\"KHR_binary_glTF\");\n }\n loadRuntimeAsync(scene, data, rootUrl, onSuccess) {\n const extensionsUsed = data.json.extensionsUsed;\n if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {\n return false;\n }\n this._bin = data.bin;\n onSuccess(GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));\n return true;\n }\n loadBufferAsync(gltfRuntime, id, onSuccess, onError) {\n if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {\n return false;\n }\n if (id !== BinaryExtensionBufferName) {\n return false;\n }\n this._bin.readAsync(0, this._bin.byteLength).then(onSuccess, (error) => onError(error.message));\n return true;\n }\n loadTextureBufferAsync(gltfRuntime, id, onSuccess) {\n const texture = gltfRuntime.textures[id];\n const source = gltfRuntime.images[texture.source];\n if (!source.extensions || !(this.name in source.extensions)) {\n return false;\n }\n const sourceExt = source.extensions[this.name];\n const bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];\n const buffer = GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, EComponentType.UNSIGNED_BYTE);\n onSuccess(buffer);\n return true;\n }\n loadShaderStringAsync(gltfRuntime, id, onSuccess) {\n const shader = gltfRuntime.shaders[id];\n if (!shader.extensions || !(this.name in shader.extensions)) {\n return false;\n }\n const binaryExtensionShader = shader.extensions[this.name];\n const bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];\n const shaderBytes = GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, EComponentType.UNSIGNED_BYTE);\n setTimeout(() => {\n const shaderString = GLTFUtils.DecodeBufferToText(shaderBytes);\n onSuccess(shaderString);\n });\n return true;\n }\n}\nGLTFLoader.RegisterExtension(new GLTFBinaryExtension());\n//# sourceMappingURL=glTFBinaryExtension.js.map","import { GLTFLoaderExtension, GLTFLoaderBase, GLTFLoader } from \"./glTFLoader.js\";\nimport { Vector3 } from \"@babylonjs/core/Maths/math.vector.js\";\nimport { Color3 } from \"@babylonjs/core/Maths/math.color.js\";\nimport { Tools } from \"@babylonjs/core/Misc/tools.js\";\nimport { Material } from \"@babylonjs/core/Materials/material.js\";\nimport { StandardMaterial } from \"@babylonjs/core/Materials/standardMaterial.js\";\nimport { HemisphericLight } from \"@babylonjs/core/Lights/hemisphericLight.js\";\nimport { DirectionalLight } from \"@babylonjs/core/Lights/directionalLight.js\";\nimport { PointLight } from \"@babylonjs/core/Lights/pointLight.js\";\nimport { SpotLight } from \"@babylonjs/core/Lights/spotLight.js\";\n/**\n * @internal\n * @deprecated\n */\nexport class GLTFMaterialsCommonExtension extends GLTFLoaderExtension {\n constructor() {\n super(\"KHR_materials_common\");\n }\n loadRuntimeExtensionsAsync(gltfRuntime) {\n if (!gltfRuntime.extensions) {\n return false;\n }\n const extension = gltfRuntime.extensions[this.name];\n if (!extension) {\n return false;\n }\n // Create lights\n const lights = extension.lights;\n if (lights) {\n for (const thing in lights) {\n const light = lights[thing];\n switch (light.type) {\n case \"ambient\": {\n const ambientLight = new HemisphericLight(light.name, new Vector3(0, 1, 0), gltfRuntime.scene);\n const ambient = light.ambient;\n if (ambient) {\n ambientLight.diffuse = Color3.FromArray(ambient.color || [1, 1, 1]);\n }\n break;\n }\n case \"point\": {\n const pointLight = new PointLight(light.name, new Vector3(10, 10, 10), gltfRuntime.scene);\n const point = light.point;\n if (point) {\n pointLight.diffuse = Color3.FromArray(point.color || [1, 1, 1]);\n }\n break;\n }\n case \"directional\": {\n const dirLight = new DirectionalLight(light.name, new Vector3(0, -1, 0), gltfRuntime.scene);\n const directional = light.directional;\n if (directional) {\n dirLight.diffuse = Color3.FromArray(directional.color || [1, 1, 1]);\n }\n break;\n }\n case \"spot\": {\n const spot = light.spot;\n if (spot) {\n const spotLight = new SpotLight(light.name, new Vector3(0, 10, 0), new Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);\n spotLight.diffuse = Color3.FromArray(spot.color || [1, 1, 1]);\n }\n break;\n }\n default:\n Tools.Warn('GLTF Material Common extension: light type \"' + light.type + \"” not supported\");\n break;\n }\n }\n }\n return false;\n }\n loadMaterialAsync(gltfRuntime, id, onSuccess, onError) {\n const material = gltfRuntime.materials[id];\n if (!material || !material.extensions) {\n return false;\n }\n const extension = material.extensions[this.name];\n if (!extension) {\n return false;\n }\n const standardMaterial = new StandardMaterial(id, gltfRuntime.scene);\n standardMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;\n if (extension.technique === \"CONSTANT\") {\n standardMaterial.disableLighting = true;\n }\n standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;\n standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;\n standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;\n // Ambient\n if (typeof extension.values.ambient === \"string\") {\n this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, \"ambientTexture\", onError);\n }\n else {\n standardMaterial.ambientColor = Color3.FromArray(extension.values.ambient || [0, 0, 0]);\n }\n // Diffuse\n if (typeof extension.values.diffuse === \"string\") {\n this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, \"diffuseTexture\", onError);\n }\n else {\n standardMaterial.diffuseColor = Color3.FromArray(extension.values.diffuse || [0, 0, 0]);\n }\n // Emission\n if (typeof extension.values.emission === \"string\") {\n this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, \"emissiveTexture\", onError);\n }\n else {\n standardMaterial.emissiveColor = Color3.FromArray(extension.values.emission || [0, 0, 0]);\n }\n // Specular\n if (typeof extension.values.specular === \"string\") {\n this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, \"specularTexture\", onError);\n }\n else {\n standardMaterial.specularColor = Color3.FromArray(extension.values.specular || [0, 0, 0]);\n }\n return true;\n }\n _loadTexture(gltfRuntime, id, material, propertyPath, onError) {\n // Create buffer from texture url\n GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, (buffer) => {\n // Create texture from buffer\n GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, (texture) => (material[propertyPath] = texture));\n }, onError);\n }\n}\nGLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());\n//# sourceMappingURL=glTFMaterialsCommonExtension.js.map","export * from \"./glTFBinaryExtension.js\";\nexport * from \"./glTFLoader.js\";\nexport * from \"./glTFLoaderInterfaces.js\";\nexport * from \"./glTFLoaderUtils.js\";\nexport * from \"./glTFMaterialsCommonExtension.js\";\n//# sourceMappingURL=index.js.map","import { Animation } from \"@babylonjs/core/Animations/animation.js\";\nimport { Quaternion, Vector3 } from \"@babylonjs/core/Maths/math.vector.js\";\n/** @internal */\nexport function getVector3(_target, source, offset, scale) {\n return Vector3.FromArray(source, offset).scaleInPlace(scale);\n}\n/** @internal */\nexport function getQuaternion(_target, source, offset, scale) {\n return Quaternion.FromArray(source, offset).scaleInPlace(scale);\n}\n/** @internal */\nexport function getWeights(target, source, offset, scale) {\n const value = new Array(target._numMorphTargets);\n for (let i = 0; i < value.length; i++) {\n value[i] = source[offset++] * scale;\n }\n return value;\n}\n/** @internal */\nexport class AnimationPropertyInfo {\n /** @internal */\n constructor(type, name, getValue, getStride) {\n this.type = type;\n this.name = name;\n this.getValue = getValue;\n this.getStride = getStride;\n }\n _buildAnimation(name, fps, keys) {\n const babylonAnimation = new Animation(name, this.name, fps, this.type);\n babylonAnimation.setKeys(keys);\n return babylonAnimation;\n }\n}\n/** @internal */\nexport class TransformNodeAnimationPropertyInfo extends AnimationPropertyInfo {\n /** @internal */\n buildAnimations(target, name, fps, keys, callback) {\n callback(target._babylonTransformNode, this._buildAnimation(name, fps, keys));\n }\n}\n/** @internal */\nexport class WeightAnimationPropertyInfo extends AnimationPropertyInfo {\n buildAnimations(target, name, fps, keys, callback) {\n if (target._numMorphTargets) {\n for (let targetIndex = 0; targetIndex < target._numMorphTargets; targetIndex++) {\n const babylonAnimation = new Animation(`${name}_${targetIndex}`, this.name, fps, this.type);\n babylonAnimation.setKeys(keys.map((key) => ({\n frame: key.frame,\n inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,\n value: key.value[targetIndex],\n outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined,\n interpolation: key.interpolation,\n })));\n if (target._primitiveBabylonMeshes) {\n for (const babylonMesh of target._primitiveBabylonMeshes) {\n if (babylonMesh.morphTargetManager) {\n const morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);\n const babylonAnimationClone = babylonAnimation.clone();\n morphTarget.animations.push(babylonAnimationClone);\n callback(morphTarget, babylonAnimationClone);\n }\n }\n }\n }\n }\n }\n}\n/** @internal */\nexport const nodeAnimationData = {\n translation: [new TransformNodeAnimationPropertyInfo(Animation.ANIMATIONTYPE_VECTOR3, \"position\", getVector3, () => 3)],\n rotation: [new TransformNodeAnimationPropertyInfo(Animation.ANIMATIONTYPE_QUATERNION, \"rotationQuaternion\", getQuaternion, () => 4)],\n scale: [new TransformNodeAnimationPropertyInfo(Animation.ANIMATIONTYPE_VECTOR3, \"scaling\", getVector3, () => 3)],\n weights: [new WeightAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"influence\", getWeights, (target) => target._numMorphTargets)],\n};\n//# sourceMappingURL=glTFLoaderAnimation.js.map","import { Deferred } from \"@babylonjs/core/Misc/deferred.js\";\nimport { Quaternion, Vector3, Matrix, TmpVectors } from \"@babylonjs/core/Maths/math.vector.js\";\nimport { Color3 } from \"@babylonjs/core/Maths/math.color.js\";\nimport { Tools } from \"@babylonjs/core/Misc/tools.js\";\nimport { Camera } from \"@babylonjs/core/Cameras/camera.js\";\nimport { FreeCamera } from \"@babylonjs/core/Cameras/freeCamera.js\";\nimport { AnimationKeyInterpolation } from \"@babylonjs/core/Animations/animationKey.js\";\nimport { AnimationGroup } from \"@babylonjs/core/Animations/animationGroup.js\";\nimport { Bone } from \"@babylonjs/core/Bones/bone.js\";\nimport { Skeleton } from \"@babylonjs/core/Bones/skeleton.js\";\nimport { Material } from \"@babylonjs/core/Materials/material.js\";\nimport { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { Texture } from \"@babylonjs/core/Materials/Textures/texture.js\";\nimport { TransformNode } from \"@babylonjs/core/Meshes/transformNode.js\";\nimport { Buffer, VertexBuffer } from \"@babylonjs/core/Buffers/buffer.js\";\nimport { Geometry } from \"@babylonjs/core/Meshes/geometry.js\";\nimport { Mesh } from \"@babylonjs/core/Meshes/mesh.js\";\nimport { MorphTarget } from \"@babylonjs/core/Morph/morphTarget.js\";\nimport { MorphTargetManager } from \"@babylonjs/core/Morph/morphTargetManager.js\";\nimport { GLTFFileLoader, GLTFLoaderState, GLTFLoaderCoordinateSystemMode, GLTFLoaderAnimationStartMode } from \"../glTFFileLoader.js\";\nimport { DecodeBase64UrlToBinary, IsBase64DataUrl, LoadFileError } from \"@babylonjs/core/Misc/fileTools.js\";\nimport { Logger } from \"@babylonjs/core/Misc/logger.js\";\nimport { BoundingInfo } from \"@babylonjs/core/Culling/boundingInfo.js\";\nimport { nodeAnimationData } from \"./glTFLoaderAnimation.js\";\n// https://stackoverflow.com/a/48218209\nfunction mergeDeep(...objects) {\n const isObject = (obj) => obj && typeof obj === \"object\";\n return objects.reduce((prev, obj) => {\n Object.keys(obj).forEach((key) => {\n const pVal = prev[key];\n const oVal = obj[key];\n if (Array.isArray(pVal) && Array.isArray(oVal)) {\n prev[key] = pVal.concat(...oVal);\n }\n else if (isObject(pVal) && isObject(oVal)) {\n prev[key] = mergeDeep(pVal, oVal);\n }\n else {\n prev[key] = oVal;\n }\n });\n return prev;\n }, {});\n}\n/**\n * Helper class for working with arrays when loading the glTF asset\n */\nexport class ArrayItem {\n /**\n * Gets an item from the given array.\n * @param context The context when loading the asset\n * @param array The array to get the item from\n * @param index The index to the array\n * @returns The array item\n */\n static Get(context, array, index) {\n if (!array || index == undefined || !array[index]) {\n throw new Error(`${context}: Failed to find index (${index})`);\n }\n return array[index];\n }\n /**\n * Assign an `index` field to each item of the given array.\n * @param array The array of items\n */\n static Assign(array) {\n if (array) {\n for (let index = 0; index < array.length; index++) {\n array[index].index = index;\n }\n }\n }\n}\n/**\n * The glTF 2.0 loader\n */\nexport class GLTFLoader {\n /**\n * Registers a loader extension.\n * @param name The name of the loader extension.\n * @param factory The factory function that creates the loader extension.\n */\n static RegisterExtension(name, factory) {\n if (GLTFLoader.UnregisterExtension(name)) {\n Logger.Warn(`Extension with the name '${name}' already exists`);\n }\n GLTFLoader._RegisteredExtensions[name] = {\n factory: factory,\n };\n }\n /**\n * Unregisters a loader extension.\n * @param name The name of the loader extension.\n * @returns A boolean indicating whether the extension has been unregistered\n */\n static UnregisterExtension(name) {\n if (!GLTFLoader._RegisteredExtensions[name]) {\n return false;\n }\n delete GLTFLoader._RegisteredExtensions[name];\n return true;\n }\n /**\n * The object that represents the glTF JSON.\n */\n get gltf() {\n if (!this._gltf) {\n throw new Error(\"glTF JSON is not available\");\n }\n return this._gltf;\n }\n /**\n * The BIN chunk of a binary glTF.\n */\n get bin() {\n return this._bin;\n }\n /**\n * The parent file loader.\n */\n get parent() {\n return this._parent;\n }\n /**\n * The Babylon scene when loading the asset.\n */\n get babylonScene() {\n if (!this._babylonScene) {\n throw new Error(\"Scene is not available\");\n }\n return this._babylonScene;\n }\n /**\n * The root Babylon mesh when loading the asset.\n */\n get rootBabylonMesh() {\n return this._rootBabylonMesh;\n }\n /**\n * @internal\n */\n constructor(parent) {\n /** @internal */\n this._completePromises = new Array();\n /** @internal */\n this._assetContainer = null;\n /** Storage */\n this._babylonLights = [];\n /** @internal */\n this._disableInstancedMesh = 0;\n this._extensions = new Array();\n this._disposed = false;\n this._rootUrl = null;\n this._fileName = null;\n this._uniqueRootUrl = null;\n this._bin = null;\n this._rootBabylonMesh = null;\n this._defaultBabylonMaterialData = {};\n this._postSceneLoadActions = new Array();\n this._parent = parent;\n }\n /** @internal */\n dispose() {\n if (this._disposed) {\n return;\n }\n this._disposed = true;\n this._completePromises.length = 0;\n this._extensions.forEach((extension) => extension.dispose && extension.dispose());\n this._extensions.length = 0;\n this._gltf = null; // TODO\n this._bin = null;\n this._babylonScene = null; // TODO\n this._rootBabylonMesh = null;\n this._defaultBabylonMaterialData = {};\n this._postSceneLoadActions.length = 0;\n this._parent.dispose();\n }\n /**\n * @internal\n */\n importMeshAsync(meshesNames, scene, container, data, rootUrl, onProgress, fileName = \"\") {\n return Promise.resolve().then(() => {\n this._babylonScene = scene;\n this._assetContainer = container;\n this._loadData(data);\n let nodes = null;\n if (meshesNames) {\n const nodeMap = {};\n if (this._gltf.nodes) {\n for (const node of this._gltf.nodes) {\n if (node.name) {\n nodeMap[node.name] = node.index;\n }\n }\n }\n const names = meshesNames instanceof Array ? meshesNames : [meshesNames];\n nodes = names.map((name) => {\n const node = nodeMap[name];\n if (node === undefined) {\n throw new Error(`Failed to find node '${name}'`);\n }\n return node;\n });\n }\n return this._loadAsync(rootUrl, fileName, nodes, () => {\n return {\n meshes: this._getMeshes(),\n particleSystems: [],\n skeletons: this._getSkeletons(),\n animationGroups: this._getAnimationGroups(),\n lights: this._babylonLights,\n transformNodes: this._getTransformNodes(),\n geometries: this._getGeometries(),\n };\n });\n });\n }\n /**\n * @internal\n */\n loadAsync(scene, data, rootUrl, onProgress, fileName = \"\") {\n return Promise.resolve().then(() => {\n this._babylonScene = scene;\n this._loadData(data);\n return this._loadAsync(rootUrl, fileName, null, () => undefined);\n });\n }\n _loadAsync(rootUrl, fileName, nodes, resultFunc) {\n return Promise.resolve()\n .then(() => {\n this._rootUrl = rootUrl;\n this._uniqueRootUrl = !rootUrl.startsWith(\"file:\") && fileName ? rootUrl : `${rootUrl}${Date.now()}/`;\n this._fileName = fileName;\n this._loadExtensions();\n this._checkExtensions();\n const loadingToReadyCounterName = `${GLTFLoaderState[GLTFLoaderState.LOADING]} => ${GLTFLoaderState[GLTFLoaderState.READY]}`;\n const loadingToCompleteCounterName = `${GLTFLoaderState[GLTFLoaderState.LOADING]} => ${GLTFLoaderState[GLTFLoaderState.COMPLETE]}`;\n this._parent._startPerformanceCounter(loadingToReadyCounterName);\n this._parent._startPerformanceCounter(loadingToCompleteCounterName);\n this._parent._setState(GLTFLoaderState.LOADING);\n this._extensionsOnLoading();\n const promises = new Array();\n // Block the marking of materials dirty until the scene is loaded.\n const oldBlockMaterialDirtyMechanism = this._babylonScene.blockMaterialDirtyMechanism;\n this._babylonScene.blockMaterialDirtyMechanism = true;\n if (!this.parent.loadOnlyMaterials) {\n if (nodes) {\n promises.push(this.loadSceneAsync(\"/nodes\", { nodes: nodes, index: -1 }));\n }\n else if (this._gltf.scene != undefined || (this._gltf.scenes && this._gltf.scenes[0])) {\n const scene = ArrayItem.Get(`/scene`, this._gltf.scenes, this._gltf.scene || 0);\n promises.push(this.loadSceneAsync(`/scenes/${scene.index}`, scene));\n }\n }\n if (!this.parent.skipMaterials && this.parent.loadAllMaterials && this._gltf.materials) {\n for (let m = 0; m < this._gltf.materials.length; ++m) {\n const material = this._gltf.materials[m];\n const context = \"/materials/\" + m;\n const babylonDrawMode = Material.TriangleFillMode;\n promises.push(this._loadMaterialAsync(context, material, null, babylonDrawMode, () => { }));\n }\n }\n // Restore the blocking of material dirty.\n this._babylonScene.blockMaterialDirtyMechanism = oldBlockMaterialDirtyMechanism;\n if (this._parent.compileMaterials) {\n promises.push(this._compileMaterialsAsync());\n }\n if (this._parent.compileShadowGenerators) {\n promises.push(this._compileShadowGeneratorsAsync());\n }\n const resultPromise = Promise.all(promises).then(() => {\n if (this._rootBabylonMesh) {\n this._rootBabylonMesh.setEnabled(true);\n }\n this._extensionsOnReady();\n this._parent._setState(GLTFLoaderState.READY);\n this._startAnimations();\n return resultFunc();\n });\n return resultPromise.then((result) => {\n this._parent._endPerformanceCounter(loadingToReadyCounterName);\n Tools.SetImmediate(() => {\n if (!this._disposed) {\n Promise.all(this._completePromises).then(() => {\n this._parent._endPerformanceCounter(loadingToCompleteCounterName);\n this._parent._setState(GLTFLoaderState.COMPLETE);\n this._parent.onCompleteObservable.notifyObservers(undefined);\n this._parent.onCompleteObservable.clear();\n this.dispose();\n }, (error) => {\n this._parent.onErrorObservable.notifyObservers(error);\n this._parent.onErrorObservable.clear();\n this.dispose();\n });\n }\n });\n return result;\n });\n })\n .catch((error) => {\n if (!this._disposed) {\n this._parent.onErrorObservable.notifyObservers(error);\n this._parent.onErrorObservable.clear();\n this.dispose();\n }\n throw error;\n });\n }\n _loadData(data) {\n this._gltf = data.json;\n this._setupData();\n if (data.bin) {\n const buffers = this._gltf.buffers;\n if (buffers && buffers[0] && !buffers[0].uri) {\n const binaryBuffer = buffers[0];\n if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {\n Logger.Warn(`Binary buffer length (${binaryBuffer.byteLength}) from JSON does not match chunk length (${data.bin.byteLength})`);\n }\n this._bin = data.bin;\n }\n else {\n Logger.Warn(\"Unexpected BIN chunk\");\n }\n }\n }\n _setupData() {\n ArrayItem.Assign(this._gltf.accessors);\n ArrayItem.Assign(this._gltf.animations);\n ArrayItem.Assign(this._gltf.buffers);\n ArrayItem.Assign(this._gltf.bufferViews);\n ArrayItem.Assign(this._gltf.cameras);\n ArrayItem.Assign(this._gltf.images);\n ArrayItem.Assign(this._gltf.materials);\n ArrayItem.Assign(this._gltf.meshes);\n ArrayItem.Assign(this._gltf.nodes);\n ArrayItem.Assign(this._gltf.samplers);\n ArrayItem.Assign(this._gltf.scenes);\n ArrayItem.Assign(this._gltf.skins);\n ArrayItem.Assign(this._gltf.textures);\n if (this._gltf.nodes) {\n const nodeParents = {};\n for (const node of this._gltf.nodes) {\n if (node.children) {\n for (const index of node.children) {\n nodeParents[index] = node.index;\n }\n }\n }\n const rootNode = this._createRootNode();\n for (const node of this._gltf.nodes) {\n const parentIndex = nodeParents[node.index];\n node.parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];\n }\n }\n }\n _loadExtensions() {\n for (const name in GLTFLoader._RegisteredExtensions) {\n const extension = GLTFLoader._RegisteredExtensions[name].factory(this);\n if (extension.name !== name) {\n Logger.Warn(`The name of the glTF loader extension instance does not match the registered name: ${extension.name} !== ${name}`);\n }\n this._extensions.push(extension);\n this._parent.onExtensionLoadedObservable.notifyObservers(extension);\n }\n this._extensions.sort((a, b) => (a.order || Number.MAX_VALUE) - (b.order || Number.MAX_VALUE));\n this._parent.onExtensionLoadedObservable.clear();\n }\n _checkExtensions() {\n if (this._gltf.extensionsRequired) {\n for (const name of this._gltf.extensionsRequired) {\n const available = this._extensions.some((extension) => extension.name === name && extension.enabled);\n if (!available) {\n throw new Error(`Require extension ${name} is not available`);\n }\n }\n }\n }\n _createRootNode() {\n this._babylonScene._blockEntityCollection = !!this._assetContainer;\n this._rootBabylonMesh = new Mesh(\"__root__\", this._babylonScene);\n this._rootBabylonMesh._parentContainer = this._assetContainer;\n this._babylonScene._blockEntityCollection = false;\n this._rootBabylonMesh.setEnabled(false);\n const rootNode = {\n _babylonTransformNode: this._rootBabylonMesh,\n index: -1,\n };\n switch (this._parent.coordinateSystemMode) {\n case GLTFLoaderCoordinateSystemMode.AUTO: {\n if (!this._babylonScene.useRightHandedSystem) {\n rootNode.rotation = [0, 1, 0, 0];\n rootNode.scale = [1, 1, -1];\n GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);\n }\n break;\n }\n case GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {\n this._babylonScene.useRightHandedSystem = true;\n break;\n }\n default: {\n throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`);\n }\n }\n this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);\n return rootNode;\n }\n /**\n * Loads a glTF scene.\n * @param context The context when loading the asset\n * @param scene The glTF scene property\n * @returns A promise that resolves when the load is complete\n */\n loadSceneAsync(context, scene) {\n const extensionPromise = this._extensionsLoadSceneAsync(context, scene);\n if (extensionPromise) {\n return extensionPromise;\n }\n const promises = new Array();\n this.logOpen(`${context} ${scene.name || \"\"}`);\n if (scene.nodes) {\n for (const index of scene.nodes) {\n const node = ArrayItem.Get(`${context}/nodes/${index}`, this._gltf.nodes, index);\n promises.push(this.loadNodeAsync(`/nodes/${node.index}`, node, (babylonMesh) => {\n babylonMesh.parent = this._rootBabylonMesh;\n }));\n }\n }\n for (const action of this._postSceneLoadActions) {\n action();\n }\n promises.push(this._loadAnimationsAsync());\n this.logClose();\n return Promise.all(promises).then(() => { });\n }\n _forEachPrimitive(node, callback) {\n if (node._primitiveBabylonMeshes) {\n for (const babylonMesh of node._primitiveBabylonMeshes) {\n callback(babylonMesh);\n }\n }\n }\n _getGeometries() {\n const geometries = new Array();\n const nodes = this._gltf.nodes;\n if (nodes) {\n for (const node of nodes) {\n this._forEachPrimitive(node, (babylonMesh) => {\n const geometry = babylonMesh.geometry;\n if (geometry && geometries.indexOf(geometry) === -1) {\n geometries.push(geometry);\n }\n });\n }\n }\n return geometries;\n }\n _getMeshes() {\n const meshes = new Array();\n // Root mesh is always first, if available.\n if (this._rootBabylonMesh) {\n meshes.push(this._rootBabylonMesh);\n }\n const nodes = this._gltf.nodes;\n if (nodes) {\n for (const node of nodes) {\n this._forEachPrimitive(node, (babylonMesh) => {\n meshes.push(babylonMesh);\n });\n }\n }\n return meshes;\n }\n _getTransformNodes() {\n const transformNodes = new Array();\n const nodes = this._gltf.nodes;\n if (nodes) {\n for (const node of nodes) {\n if (node._babylonTransformNode && node._babylonTransformNode.getClassName() === \"TransformNode\") {\n transformNodes.push(node._babylonTransformNode);\n }\n if (node._babylonTransformNodeForSkin) {\n transformNodes.push(node._babylonTransformNodeForSkin);\n }\n }\n }\n return transformNodes;\n }\n _getSkeletons() {\n const skeletons = new Array();\n const skins = this._gltf.skins;\n if (skins) {\n for (const skin of skins) {\n if (skin._data) {\n skeletons.push(skin._data.babylonSkeleton);\n }\n }\n }\n return skeletons;\n }\n _getAnimationGroups() {\n const animationGroups = new Array();\n const animations = this._gltf.animations;\n if (animations) {\n for (const animation of animations) {\n if (animation._babylonAnimationGroup) {\n animationGroups.push(animation._babylonAnimationGroup);\n }\n }\n }\n return animationGroups;\n }\n _startAnimations() {\n switch (this._parent.animationStartMode) {\n case GLTFLoaderAnimationStartMode.NONE: {\n // do nothing\n break;\n }\n case GLTFLoaderAnimationStartMode.FIRST: {\n const babylonAnimationGroups = this._getAnimationGroups();\n if (babylonAnimationGroups.length !== 0) {\n babylonAnimationGroups[0].start(true);\n }\n break;\n }\n case GLTFLoaderAnimationStartMode.ALL: {\n const babylonAnimationGroups = this._getAnimationGroups();\n for (const babylonAnimationGroup of babylonAnimationGroups) {\n babylonAnimationGroup.start(true);\n }\n break;\n }\n default: {\n Logger.Error(`Invalid animation start mode (${this._parent.animationStartMode})`);\n return;\n }\n }\n }\n /**\n * Loads a glTF node.\n * @param context The context when loading the asset\n * @param node The glTF node property\n * @param assign A function called synchronously after parsing the glTF properties\n * @returns A promise that resolves with the loaded Babylon mesh when the load is complete\n */\n loadNodeAsync(context, node, assign = () => { }) {\n const extensionPromise = this._extensionsLoadNodeAsync(context, node, assign);\n if (extensionPromise) {\n return extensionPromise;\n }\n if (node._babylonTransformNode) {\n throw new Error(`${context}: Invalid recursive node hierarchy`);\n }\n const promises = new Array();\n this.logOpen(`${context} ${node.name || \"\"}`);\n const loadNode = (babylonTransformNode) => {\n GLTFLoader.AddPointerMetadata(babylonTransformNode, context);\n GLTFLoader._LoadTransform(node, babylonTransformNode);\n if (node.camera != undefined) {\n const camera = ArrayItem.Get(`${context}/camera`, this._gltf.cameras, node.camera);\n promises.push(this.loadCameraAsync(`/cameras/${camera.index}`, camera, (babylonCamera) => {\n babylonCamera.parent = babylonTransformNode;\n }));\n }\n if (node.children) {\n for (const index of node.children) {\n const childNode = ArrayItem.Get(`${context}/children/${index}`, this._gltf.nodes, index);\n promises.push(this.loadNodeAsync(`/nodes/${childNode.index}`, childNode, (childBabylonMesh) => {\n childBabylonMesh.parent = babylonTransformNode;\n }));\n }\n }\n assign(babylonTransformNode);\n };\n if (node.mesh == undefined || node.skin != undefined) {\n const nodeName = node.name || `node${node.index}`;\n this._babylonScene._blockEntityCollection = !!this._assetContainer;\n const transformNode = new TransformNode(nodeName, this._babylonScene);\n transformNode._parentContainer = this._assetContainer;\n this._babylonScene._blockEntityCollection = false;\n if (node.mesh == undefined) {\n node._babylonTransformNode = transformNode;\n }\n else {\n node._babylonTransformNodeForSkin = transformNode;\n }\n loadNode(transformNode);\n }\n if (node.mesh != undefined) {\n if (node.skin == undefined) {\n const mesh = ArrayItem.Get(`${context}/mesh`, this._gltf.meshes, node.mesh);\n promises.push(this._loadMeshAsync(`/meshes/${mesh.index}`, node, mesh, loadNode));\n }\n else {\n // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)\n // This code path will place the skinned mesh as a sibling of the skeleton root node without loading the\n // transform, which effectively ignores the transform of the skinned mesh, as per spec.\n const mesh = ArrayItem.Get(`${context}/mesh`, this._gltf.meshes, node.mesh);\n promises.push(this._loadMeshAsync(`/meshes/${mesh.index}`, node, mesh, (babylonTransformNode) => {\n const babylonTransformNodeForSkin = node._babylonTransformNodeForSkin;\n // Merge the metadata from the skin node to the skinned mesh in case a loader extension added metadata.\n babylonTransformNode.metadata = mergeDeep(babylonTransformNodeForSkin.metadata, babylonTransformNode.metadata || {});\n const skin = ArrayItem.Get(`${context}/skin`, this._gltf.skins, node.skin);\n promises.push(this._loadSkinAsync(`/skins/${skin.index}`, node, skin, (babylonSkeleton) => {\n this._forEachPrimitive(node, (babylonMesh) => {\n babylonMesh.skeleton = babylonSkeleton;\n });\n // Wait until all the nodes are parented before parenting the skinned mesh.\n this._postSceneLoadActions.push(() => {\n if (skin.skeleton != undefined) {\n // Place the skinned mesh node as a sibling of the skeleton root node.\n // Handle special case when the parent of the skeleton root is the skinned mesh.\n const parentNode = ArrayItem.Get(`/skins/${skin.index}/skeleton`, this._gltf.nodes, skin.skeleton).parent;\n if (node.index === parentNode.index) {\n babylonTransformNode.parent = babylonTransformNodeForSkin.parent;\n }\n else {\n babylonTransformNode.parent = parentNode._babylonTransformNode;\n }\n }\n else {\n babylonTransformNode.parent = this._rootBabylonMesh;\n }\n this._parent.onSkinLoadedObservable.notifyObservers({ node: babylonTransformNodeForSkin, skinnedNode: babylonTransformNode });\n });\n }));\n }));\n }\n }\n this.logClose();\n return Promise.all(promises).then(() => {\n this._forEachPrimitive(node, (babylonMesh) => {\n if (babylonMesh.geometry && babylonMesh.geometry.useBoundingInfoFromGeometry) {\n // simply apply the world matrices to the bounding info - the extends are already ok\n babylonMesh._updateBoundingInfo();\n }\n else {\n babylonMesh.refreshBoundingInfo(true);\n }\n });\n return node._babylonTransformNode;\n });\n }\n _loadMeshAsync(context, node, mesh, assign) {\n const primitives = mesh.primitives;\n if (!primitives || !primitives.length) {\n throw new Error(`${context}: Primitives are missing`);\n }\n if (primitives[0].index == undefined) {\n ArrayItem.Assign(primitives);\n }\n const promises = new Array();\n this.logOpen(`${context} ${mesh.name || \"\"}`);\n const name = node.name || `node${node.index}`;\n if (primitives.length === 1) {\n const primitive = mesh.primitives[0];\n promises.push(this._loadMeshPrimitiveAsync(`${context}/primitives/${primitive.index}`, name, node, mesh, primitive, (babylonMesh) => {\n node._babylonTransformNode = babylonMesh;\n node._primitiveBabylonMeshes = [babylonMesh];\n }));\n }\n else {\n this._babylonScene._blockEntityCollection = !!this._assetContainer;\n node._babylonTransformNode = new TransformNode(name, this._babylonScene);\n node._babylonTransformNode._parentContainer = this._assetContainer;\n this._babylonScene._blockEntityCollection = false;\n node._primitiveBabylonMeshes = [];\n for (const primitive of primitives) {\n promises.push(this._loadMeshPrimitiveAsync(`${context}/primitives/${primitive.index}`, `${name}_primitive${primitive.index}`, node, mesh, primitive, (babylonMesh) => {\n babylonMesh.parent = node._babylonTransformNode;\n node._primitiveBabylonMeshes.push(babylonMesh);\n }));\n }\n }\n assign(node._babylonTransformNode);\n this.logClose();\n return Promise.all(promises).then(() => {\n return node._babylonTransformNode;\n });\n }\n /**\n * @internal Define this method to modify the default behavior when loading data for mesh primitives.\n * @param context The context when loading the asset\n * @param name The mesh name when loading the asset\n * @param node The glTF node when loading the asset\n * @param mesh The glTF mesh when loading the asset\n * @param primitive The glTF mesh primitive property\n * @param assign A function called synchronously after parsing the glTF properties\n * @returns A promise that resolves with the loaded mesh when the load is complete or null if not handled\n */\n _loadMeshPrimitiveAsync(context, name, node, mesh, primitive, assign) {\n const extensionPromise = this._extensionsLoadMeshPrimitiveAsync(context, name, node, mesh, primitive, assign);\n if (extensionPromise) {\n return extensionPromise;\n }\n this.logOpen(`${context}`);\n const shouldInstance = this._disableInstancedMesh === 0 && this._parent.createInstances && node.skin == undefined && !mesh.primitives[0].targets;\n let babylonAbstractMesh;\n let promise;\n if (shouldInstance && primitive._instanceData) {\n this._babylonScene._blockEntityCollection = !!this._assetContainer;\n babylonAbstractMesh = primitive._instanceData.babylonSourceMesh.createInstance(name);\n babylonAbstractMesh._parentContainer = this._assetContainer;\n this._babylonScene._blockEntityCollection = false;\n promise = primitive._instanceData.promise;\n }\n else {\n const promises = new Array();\n this._babylonScene._blockEntityCollection = !!this._assetContainer;\n const babylonMesh = new Mesh(name, this._babylonScene);\n babylonMesh._parentContainer = this._assetContainer;\n this._babylonScene._blockEntityCollection = false;\n babylonMesh.overrideMaterialSideOrientation = this._babylonScene.useRightHandedSystem ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation;\n this._createMorphTargets(context, node, mesh, primitive, babylonMesh);\n promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then((babylonGeometry) => {\n return this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(() => {\n if (this._disposed) {\n return;\n }\n this._babylonScene._blockEntityCollection = !!this._assetContainer;\n babylonGeometry.applyToMesh(babylonMesh);\n babylonGeometry._parentContainer = this._assetContainer;\n this._babylonScene._blockEntityCollection = false;\n });\n }));\n const babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);\n if (primitive.material == undefined) {\n let babylonMaterial = this._defaultBabylonMaterialData[babylonDrawMode];\n if (!babylonMaterial) {\n babylonMaterial = this._createDefaultMaterial(\"__GLTFLoader._default\", babylonDrawMode);\n this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);\n this._defaultBabylonMaterialData[babylonDrawMode] = babylonMaterial;\n }\n babylonMesh.material = babylonMaterial;\n }\n else if (!this.parent.skipMaterials) {\n const material = ArrayItem.Get(`${context}/material`, this._gltf.materials, primitive.material);\n promises.push(this._loadMaterialAsync(`/materials/${material.index}`, material, babylonMesh, babylonDrawMode, (babylonMaterial) => {\n babylonMesh.material = babylonMaterial;\n }));\n }\n promise = Promise.all(promises);\n if (shouldInstance) {\n primitive._instanceData = {\n babylonSourceMesh: babylonMesh,\n promise: promise,\n };\n }\n babylonAbstractMesh = babylonMesh;\n }\n GLTFLoader.AddPointerMetadata(babylonAbstractMesh, context);\n this._parent.onMeshLoadedObservable.notifyObservers(babylonAbstractMesh);\n assign(babylonAbstractMesh);\n this.logClose();\n return promise.then(() => {\n return babylonAbstractMesh;\n });\n }\n _loadVertexDataAsync(context, primitive, babylonMesh) {\n const extensionPromise = this._extensionsLoadVertexDataAsync(context, primitive, babylonMesh);\n if (extensionPromise) {\n return extensionPromise;\n }\n const attributes = primitive.attributes;\n if (!attributes) {\n throw new Error(`${context}: Attributes are missing`);\n }\n const promises = new Array();\n const babylonGeometry = new Geometry(babylonMesh.name, this._babylonScene);\n if (primitive.indices == undefined) {\n babylonMesh.isUnIndexed = true;\n }\n else {\n const accessor = ArrayItem.Get(`${context}/indices`, this._gltf.accessors, primitive.indices);\n promises.push(this._loadIndicesAccessorAsync(`/accessors/${accessor.index}`, accessor).then((data) => {\n babylonGeometry.setIndices(data);\n }));\n }\n const loadAttribute = (attribute, kind, callback) => {\n if (attributes[attribute] == undefined) {\n return;\n }\n babylonMesh._delayInfo = babylonMesh._delayInfo || [];\n if (babylonMesh._delayInfo.indexOf(kind) === -1) {\n babylonMesh._delayInfo.push(kind);\n }\n const accessor = ArrayItem.Get(`${context}/attributes/${attribute}`, this._gltf.accessors, attributes[attribute]);\n promises.push(this._loadVertexAccessorAsync(`/accessors/${accessor.index}`, accessor, kind).then((babylonVertexBuffer) => {\n if (babylonVertexBuffer.getKind() === VertexBuffer.PositionKind && !this.parent.alwaysComputeBoundingBox && !babylonMesh.skeleton) {\n if (accessor.min && accessor.max) {\n const min = TmpVectors.Vector3[0].copyFromFloats(...accessor.min);\n const max = TmpVectors.Vector3[1].copyFromFloats(...accessor.max);\n if (accessor.normalized && accessor.componentType !== 5126 /* AccessorComponentType.FLOAT */) {\n let divider = 1;\n switch (accessor.componentType) {\n case 5120 /* AccessorComponentType.BYTE */:\n divider = 127.0;\n break;\n case 5121 /* AccessorComponentType.UNSIGNED_BYTE */:\n divider = 255.0;\n break;\n case 5122 /* AccessorComponentType.SHORT */:\n divider = 32767.0;\n break;\n case 5123 /* AccessorComponentType.UNSIGNED_SHORT */:\n divider = 65535.0;\n break;\n }\n const oneOverDivider = 1 / divider;\n min.scaleInPlace(oneOverDivider);\n max.scaleInPlace(oneOverDivider);\n }\n babylonGeometry._boundingInfo = new BoundingInfo(min, max);\n babylonGeometry.useBoundingInfoFromGeometry = true;\n }\n }\n babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);\n }));\n if (kind == VertexBuffer.MatricesIndicesExtraKind) {\n babylonMesh.numBoneInfluencers = 8;\n }\n if (callback) {\n callback(accessor);\n }\n };\n loadAttribute(\"POSITION\", VertexBuffer.PositionKind);\n loadAttribute(\"NORMAL\", VertexBuffer.NormalKind);\n loadAttribute(\"TANGENT\", VertexBuffer.TangentKind);\n loadAttribute(\"TEXCOORD_0\", VertexBuffer.UVKind);\n loadAttribute(\"TEXCOORD_1\", VertexBuffer.UV2Kind);\n loadAttribute(\"TEXCOORD_2\", VertexBuffer.UV3Kind);\n loadAttribute(\"TEXCOORD_3\", VertexBuffer.UV4Kind);\n loadAttribute(\"TEXCOORD_4\", VertexBuffer.UV5Kind);\n loadAttribute(\"TEXCOORD_5\", VertexBuffer.UV6Kind);\n loadAttribute(\"JOINTS_0\", VertexBuffer.MatricesIndicesKind);\n loadAttribute(\"WEIGHTS_0\", VertexBuffer.MatricesWeightsKind);\n loadAttribute(\"JOINTS_1\", VertexBuffer.MatricesIndicesExtraKind);\n loadAttribute(\"WEIGHTS_1\", VertexBuffer.MatricesWeightsExtraKind);\n loadAttribute(\"COLOR_0\", VertexBuffer.ColorKind, (accessor) => {\n if (accessor.type === \"VEC4\" /* AccessorType.VEC4 */) {\n babylonMesh.hasVertexAlpha = true;\n }\n });\n return Promise.all(promises).then(() => {\n return babylonGeometry;\n });\n }\n _createMorphTargets(context, node, mesh, primitive, babylonMesh) {\n if (!primitive.targets) {\n return;\n }\n if (node._numMorphTargets == undefined) {\n node._numMorphTargets = primitive.targets.length;\n }\n else if (primitive.targets.length !== node._numMorphTargets) {\n throw new Error(`${context}: Primitives do not have the same number of targets`);\n }\n const targetNames = mesh.extras ? mesh.extras.targetNames : null;\n this._babylonScene._blockEntityCollection = !!this._assetContainer;\n babylonMesh.morphTargetManager = new MorphTargetManager(this._babylonScene);\n babylonMesh.morphTargetManager._parentContainer = this._assetContainer;\n this._babylonScene._blockEntityCollection = false;\n babylonMesh.morphTargetManager.areUpdatesFrozen = true;\n for (let index = 0; index < primitive.targets.length; index++) {\n const weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;\n const name = targetNames ? targetNames[index] : `morphTarget${index}`;\n babylonMesh.morphTargetManager.addTarget(new MorphTarget(name, weight, babylonMesh.getScene()));\n // TODO: tell the target whether it has positions, normals, tangents\n }\n }\n _loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry) {\n if (!primitive.targets) {\n return Promise.resolve();\n }\n const promises = new Array();\n const morphTargetManager = babylonMesh.morphTargetManager;\n for (let index = 0; index < morphTargetManager.numTargets; index++) {\n const babylonMorphTarget = morphTargetManager.getTarget(index);\n promises.push(this._loadMorphTargetVertexDataAsync(`${context}/targets/${index}`, babylonGeometry, primitive.targets[index], babylonMorphTarget));\n }\n return Promise.all(promises).then(() => {\n morphTargetManager.areUpdatesFrozen = false;\n });\n }\n _loadMorphTargetVertexDataAsync(context, babylonGeometry, attributes, babylonMorphTarget) {\n const promises = new Array();\n const loadAttribute = (attribute, kind, setData) => {\n if (attributes[attribute] == undefined) {\n return;\n }\n const babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);\n if (!babylonVertexBuffer) {\n return;\n }\n const accessor = ArrayItem.Get(`${context}/${attribute}`, this._gltf.accessors, attributes[attribute]);\n promises.push(this._loadFloatAccessorAsync(`/accessors/${accessor.index}`, accessor).then((data) => {\n setData(babylonVertexBuffer, data);\n }));\n };\n loadAttribute(\"POSITION\", VertexBuffer.PositionKind, (babylonVertexBuffer, data) => {\n const positions = new Float32Array(data.length);\n babylonVertexBuffer.forEach(data.length, (value, index) => {\n positions[index] = data[index] + value;\n });\n babylonMorphTarget.setPositions(positions);\n });\n loadAttribute(\"NORMAL\", VertexBuffer.NormalKind, (babylonVertexBuffer, data) => {\n const normals = new Float32Array(data.length);\n babylonVertexBuffer.forEach(normals.length, (value, index) => {\n normals[index] = data[index] + value;\n });\n babylonMorphTarget.setNormals(normals);\n });\n loadAttribute(\"TANGENT\", VertexBuffer.TangentKind, (babylonVertexBuffer, data) => {\n const tangents = new Float32Array((data.length / 3) * 4);\n let dataIndex = 0;\n babylonVertexBuffer.forEach((data.length / 3) * 4, (value, index) => {\n // Tangent data for morph targets is stored as xyz delta.\n // The vertexData.tangent is stored as xyzw.\n // So we need to skip every fourth vertexData.tangent.\n if ((index + 1) % 4 !== 0) {\n tangents[dataIndex] = data[dataIndex] + value;\n dataIndex++;\n }\n });\n babylonMorphTarget.setTangents(tangents);\n });\n return Promise.all(promises).then(() => { });\n }\n static _LoadTransform(node, babylonNode) {\n // Ignore the TRS of skinned nodes.\n // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)\n if (node.skin != undefined) {\n return;\n }\n let position = Vector3.Zero();\n let rotation = Quaternion.Identity();\n let scaling = Vector3.One();\n if (node.matrix) {\n const matrix = Matrix.FromArray(node.matrix);\n matrix.decompose(scaling, rotation, position);\n }\n else {\n if (node.translation) {\n position = Vector3.FromArray(node.translation);\n }\n if (node.rotation) {\n rotation = Quaternion.FromArray(node.rotation);\n }\n if (node.scale) {\n scaling = Vector3.FromArray(node.scale);\n }\n }\n babylonNode.position = position;\n babylonNode.rotationQuaternion = rotation;\n babylonNode.scaling = scaling;\n }\n _loadSkinAsync(context, node, skin, assign) {\n const extensionPromise = this._extensionsLoadSkinAsync(context, node, skin);\n if (extensionPromise) {\n return extensionPromise;\n }\n if (skin._data) {\n assign(skin._data.babylonSkeleton);\n return skin._data.promise;\n }\n const skeletonId = `skeleton${skin.index}`;\n this._babylonScene._blockEntityCollection = !!this._assetContainer;\n const babylonSkeleton = new Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);\n babylonSkeleton._parentContainer = this._assetContainer;\n this._babylonScene._blockEntityCollection = false;\n this._loadBones(context, skin, babylonSkeleton);\n const promise = this._loadSkinInverseBindMatricesDataAsync(context, skin).then((inverseBindMatricesData) => {\n this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);\n });\n skin._data = {\n babylonSkeleton: babylonSkeleton,\n promise: promise,\n };\n assign(babylonSkeleton);\n return promise;\n }\n _loadBones(context, skin, babylonSkeleton) {\n if (skin.skeleton == undefined || this._parent.alwaysComputeSkeletonRootNode) {\n const rootNode = this._findSkeletonRootNode(`${context}/joints`, skin.joints);\n if (rootNode) {\n if (skin.skeleton === undefined) {\n skin.skeleton = rootNode.index;\n }\n else {\n const isParent = (a, b) => {\n for (; b.parent; b = b.parent) {\n if (b.parent === a) {\n return true;\n }\n }\n return false;\n };\n const skeletonNode = ArrayItem.Get(`${context}/skeleton`, this._gltf.nodes, skin.skeleton);\n if (skeletonNode !== rootNode && !isParent(skeletonNode, rootNode)) {\n Logger.Warn(`${context}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`);\n skin.skeleton = rootNode.index;\n }\n }\n }\n else {\n Logger.Warn(`${context}: Failed to find common root`);\n }\n }\n const babylonBones = {};\n for (const index of skin.joints) {\n const node = ArrayItem.Get(`${context}/joints/${index}`, this._gltf.nodes, index);\n this._loadBone(node, skin, babylonSkeleton, babylonBones);\n }\n }\n _findSkeletonRootNode(context, joints) {\n if (joints.length === 0) {\n return null;\n }\n const paths = {};\n for (const index of joints) {\n const path = new Array();\n let node = ArrayItem.Get(`${context}/${index}`, this._gltf.nodes, index);\n while (node.index !== -1) {\n path.unshift(node);\n node = node.parent;\n }\n paths[index] = path;\n }\n let rootNode = null;\n for (let i = 0;; ++i) {\n let path = paths[joints[0]];\n if (i >= path.length) {\n return rootNode;\n }\n const node = path[i];\n for (let j = 1; j < joints.length; ++j) {\n path = paths[joints[j]];\n if (i >= path.length || node !== path[i]) {\n return rootNode;\n }\n }\n rootNode = node;\n }\n }\n _loadBone(node, skin, babylonSkeleton, babylonBones) {\n let babylonBone = babylonBones[node.index];\n if (babylonBone) {\n return babylonBone;\n }\n let parentBabylonBone = null;\n if (node.index !== skin.skeleton) {\n if (node.parent && node.parent.index !== -1) {\n parentBabylonBone = this._loadBone(node.parent, skin, babylonSkeleton, babylonBones);\n }\n else if (skin.skeleton !== undefined) {\n Logger.Warn(`/skins/${skin.index}/skeleton: Skeleton node is not a common root`);\n }\n }\n const boneIndex = skin.joints.indexOf(node.index);\n babylonBone = new Bone(node.name || `joint${node.index}`, babylonSkeleton, parentBabylonBone, this._getNodeMatrix(node), null, null, boneIndex);\n babylonBones[node.index] = babylonBone;\n // Wait until the scene is loaded to ensure the transform nodes are loaded.\n this._postSceneLoadActions.push(() => {\n // Link the Babylon bone with the corresponding Babylon transform node.\n // A glTF joint is a pointer to a glTF node in the glTF node hierarchy similar to Unity3D.\n babylonBone.linkTransformNode(node._babylonTransformNode);\n });\n return babylonBone;\n }\n _loadSkinInverseBindMatricesDataAsync(context, skin) {\n if (skin.inverseBindMatrices == undefined) {\n return Promise.resolve(null);\n }\n const accessor = ArrayItem.Get(`${context}/inverseBindMatrices`, this._gltf.accessors, skin.inverseBindMatrices);\n return this._loadFloatAccessorAsync(`/accessors/${accessor.index}`, accessor);\n }\n _updateBoneMatrices(babylonSkeleton, inverseBindMatricesData) {\n for (const babylonBone of babylonSkeleton.bones) {\n const baseMatrix = Matrix.Identity();\n const boneIndex = babylonBone._index;\n if (inverseBindMatricesData && boneIndex !== -1) {\n Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);\n baseMatrix.invertToRef(baseMatrix);\n }\n const babylonParentBone = babylonBone.getParent();\n if (babylonParentBone) {\n baseMatrix.multiplyToRef(babylonParentBone.getAbsoluteInverseBindMatrix(), baseMatrix);\n }\n babylonBone.updateMatrix(baseMatrix, false, false);\n babylonBone._updateAbsoluteBindMatrices(undefined, false);\n }\n }\n _getNodeMatrix(node) {\n return node.matrix\n ? Matrix.FromArray(node.matrix)\n : Matrix.Compose(node.scale ? Vector3.FromArray(node.scale) : Vector3.One(), node.rotation ? Quaternion.FromArray(node.rotation) : Quaternion.Identity(), node.translation ? Vector3.FromArray(node.translation) : Vector3.Zero());\n }\n /**\n * Loads a glTF camera.\n * @param context The context when loading the asset\n * @param camera The glTF camera property\n * @param assign A function called synchronously after parsing the glTF properties\n * @returns A promise that resolves with the loaded Babylon camera when the load is complete\n */\n loadCameraAsync(context, camera, assign = () => { }) {\n const extensionPromise = this._extensionsLoadCameraAsync(context, camera, assign);\n if (extensionPromise) {\n return extensionPromise;\n }\n const promises = new Array();\n this.logOpen(`${context} ${camera.name || \"\"}`);\n this._babylonScene._blockEntityCollection = !!this._assetContainer;\n const babylonCamera = new FreeCamera(camera.name || `camera${camera.index}`, Vector3.Zero(), this._babylonScene, false);\n babylonCamera._parentContainer = this._assetContainer;\n this._babylonScene._blockEntityCollection = false;\n babylonCamera.ignoreParentScaling = true;\n camera._babylonCamera = babylonCamera;\n babylonCamera.rotation = new Vector3(0, Math.PI, 0);\n switch (camera.type) {\n case \"perspective\" /* CameraType.PERSPECTIVE */: {\n const perspective = camera.perspective;\n if (!perspective) {\n throw new Error(`${context}: Camera perspective properties are missing`);\n }\n babylonCamera.fov = perspective.yfov;\n babylonCamera.minZ = perspective.znear;\n babylonCamera.maxZ = perspective.zfar || 0;\n break;\n }\n case \"orthographic\" /* CameraType.ORTHOGRAPHIC */: {\n if (!camera.orthographic) {\n throw new Error(`${context}: Camera orthographic properties are missing`);\n }\n babylonCamera.mode = Camera.ORTHOGRAPHIC_CAMERA;\n babylonCamera.orthoLeft = -camera.orthographic.xmag;\n babylonCamera.orthoRight = camera.orthographic.xmag;\n babylonCamera.orthoBottom = -camera.orthographic.ymag;\n babylonCamera.orthoTop = camera.orthographic.ymag;\n babylonCamera.minZ = camera.orthographic.znear;\n babylonCamera.maxZ = camera.orthographic.zfar;\n break;\n }\n default: {\n throw new Error(`${context}: Invalid camera type (${camera.type})`);\n }\n }\n GLTFLoader.AddPointerMetadata(babylonCamera, context);\n this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);\n assign(babylonCamera);\n this.logClose();\n return Promise.all(promises).then(() => {\n return babylonCamera;\n });\n }\n _loadAnimationsAsync() {\n const animations = this._gltf.animations;\n if (!animations) {\n return Promise.resolve();\n }\n const promises = new Array();\n for (let index = 0; index < animations.length; index++) {\n const animation = animations[index];\n promises.push(this.loadAnimationAsync(`/animations/${animation.index}`, animation).then((animationGroup) => {\n // Delete the animation group if it ended up not having any animations in it.\n if (animationGroup.targetedAnimations.length === 0) {\n animationGroup.dispose();\n }\n }));\n }\n return Promise.all(promises).then(() => { });\n }\n /**\n * Loads a glTF animation.\n * @param context The context when loading the asset\n * @param animation The glTF animation property\n * @returns A promise that resolves with the loaded Babylon animation group when the load is complete\n */\n loadAnimationAsync(context, animation) {\n const promise = this._extensionsLoadAnimationAsync(context, animation);\n if (promise) {\n return promise;\n }\n this._babylonScene._blockEntityCollection = !!this._assetContainer;\n const babylonAnimationGroup = new AnimationGroup(animation.name || `animation${animation.index}`, this._babylonScene);\n babylonAnimationGroup._parentContainer = this._assetContainer;\n this._babylonScene._blockEntityCollection = false;\n animation._babylonAnimationGroup = babylonAnimationGroup;\n const promises = new Array();\n ArrayItem.Assign(animation.channels);\n ArrayItem.Assign(animation.samplers);\n for (const channel of animation.channels) {\n promises.push(this._loadAnimationChannelAsync(`${context}/channels/${channel.index}`, context, animation, channel, (babylonTarget, babylonAnimation) => {\n babylonTarget.animations = babylonTarget.animations || [];\n babylonTarget.animations.push(babylonAnimation);\n babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonTarget);\n }));\n }\n return Promise.all(promises).then(() => {\n babylonAnimationGroup.normalize(0);\n return babylonAnimationGroup;\n });\n }\n /**\n * @hidden\n * Loads a glTF animation channel.\n * @param context The context when loading the asset\n * @param animationContext The context of the animation when loading the asset\n * @param animation The glTF animation property\n * @param channel The glTF animation channel property\n * @param onLoad Called for each animation loaded\n * @returns A void promise that resolves when the load is complete\n */\n _loadAnimationChannelAsync(context, animationContext, animation, channel, onLoad) {\n const promise = this._extensionsLoadAnimationChannelAsync(context, animationContext, animation, channel, onLoad);\n if (promise) {\n return promise;\n }\n if (channel.target.node == undefined) {\n return Promise.resolve();\n }\n const targetNode = ArrayItem.Get(`${context}/target/node`, this._gltf.nodes, channel.target.node);\n // Ignore animations that have no animation targets.\n if ((channel.target.path === \"weights\" /* AnimationChannelTargetPath.WEIGHTS */ && !targetNode._numMorphTargets) ||\n (channel.target.path !== \"weights\" /* AnimationChannelTargetPath.WEIGHTS */ && !targetNode._babylonTransformNode)) {\n return Promise.resolve();\n }\n let properties;\n switch (channel.target.path) {\n case \"translation\" /* AnimationChannelTargetPath.TRANSLATION */: {\n properties = nodeAnimationData.translation;\n break;\n }\n case \"rotation\" /* AnimationChannelTargetPath.ROTATION */: {\n properties = nodeAnimationData.rotation;\n break;\n }\n case \"scale\" /* AnimationChannelTargetPath.SCALE */: {\n properties = nodeAnimationData.scale;\n break;\n }\n case \"weights\" /* AnimationChannelTargetPath.WEIGHTS */: {\n properties = nodeAnimationData.weights;\n break;\n }\n default: {\n throw new Error(`${context}/target/path: Invalid value (${channel.target.path})`);\n }\n }\n const targetInfo = {\n target: targetNode,\n properties: properties,\n };\n return this._loadAnimationChannelFromTargetInfoAsync(context, animationContext, animation, channel, targetInfo, onLoad);\n }\n /**\n * @hidden\n * Loads a glTF animation channel.\n * @param context The context when loading the asset\n * @param animationContext The context of the animation when loading the asset\n * @param animation The glTF animation property\n * @param channel The glTF animation channel property\n * @param targetInfo The glTF target and properties\n * @param onLoad Called for each animation loaded\n * @returns A void promise that resolves when the load is complete\n */\n _loadAnimationChannelFromTargetInfoAsync(context, animationContext, animation, channel, targetInfo, onLoad) {\n const fps = this.parent.targetFps;\n const invfps = 1 / fps;\n const sampler = ArrayItem.Get(`${context}/sampler`, animation.samplers, channel.sampler);\n return this._loadAnimationSamplerAsync(`${animationContext}/samplers/${channel.sampler}`, sampler).then((data) => {\n let numAnimations = 0;\n // Extract the corresponding values from the read value.\n // GLTF values may be dispatched to several Babylon properties.\n // For example, baseColorFactor [`r`, `g`, `b`, `a`] is dispatched to\n // - albedoColor as Color3(`r`, `g`, `b`)\n // - alpha as `a`\n for (const property of targetInfo.properties) {\n const stride = property.getStride(targetInfo.target);\n const input = data.input;\n const output = data.output;\n const keys = new Array(input.length);\n let outputOffset = 0;\n switch (data.interpolation) {\n case \"STEP\" /* AnimationSamplerInterpolation.STEP */: {\n for (let index = 0; index < input.length; index++) {\n const value = property.getValue(targetInfo.target, output, outputOffset, 1);\n outputOffset += stride;\n keys[index] = {\n frame: input[index] * fps,\n value: value,\n interpolation: AnimationKeyInterpolation.STEP,\n };\n }\n break;\n }\n case \"CUBICSPLINE\" /* AnimationSamplerInterpolation.CUBICSPLINE */: {\n for (let index = 0; index < input.length; index++) {\n const inTangent = property.getValue(targetInfo.target, output, outputOffset, invfps);\n outputOffset += stride;\n const value = property.getValue(targetInfo.target, output, outputOffset, 1);\n outputOffset += stride;\n const outTangent = property.getValue(targetInfo.target, output, outputOffset, invfps);\n outputOffset += stride;\n keys[index] = {\n frame: input[index] * fps,\n inTangent: inTangent,\n value: value,\n outTangent: outTangent,\n };\n }\n break;\n }\n case \"LINEAR\" /* AnimationSamplerInterpolation.LINEAR */: {\n for (let index = 0; index < input.length; index++) {\n const value = property.getValue(targetInfo.target, output, outputOffset, 1);\n outputOffset += stride;\n keys[index] = {\n frame: input[index] * fps,\n value: value,\n };\n }\n break;\n }\n }\n if (outputOffset > 0) {\n const name = `${animation.name || `animation${animation.index}`}_channel${channel.index}_${numAnimations}`;\n property.buildAnimations(targetInfo.target, name, fps, keys, (babylonAnimatable, babylonAnimation) => {\n ++numAnimations;\n onLoad(babylonAnimatable, babylonAnimation);\n });\n }\n }\n });\n }\n _loadAnimationSamplerAsync(context, sampler) {\n if (sampler._data) {\n return sampler._data;\n }\n const interpolation = sampler.interpolation || \"LINEAR\" /* AnimationSamplerInterpolation.LINEAR */;\n switch (interpolation) {\n case \"STEP\" /* AnimationSamplerInterpolation.STEP */:\n case \"LINEAR\" /* AnimationSamplerInterpolation.LINEAR */:\n case \"CUBICSPLINE\" /* AnimationSamplerInterpolation.CUBICSPLINE */: {\n break;\n }\n default: {\n throw new Error(`${context}/interpolation: Invalid value (${sampler.interpolation})`);\n }\n }\n const inputAccessor = ArrayItem.Get(`${context}/input`, this._gltf.accessors, sampler.input);\n const outputAccessor = ArrayItem.Get(`${context}/output`, this._gltf.accessors, sampler.output);\n sampler._data = Promise.all([\n this._loadFloatAccessorAsync(`/accessors/${inputAccessor.index}`, inputAccessor),\n this._loadFloatAccessorAsync(`/accessors/${outputAccessor.index}`, outputAccessor),\n ]).then(([inputData, outputData]) => {\n return {\n input: inputData,\n interpolation: interpolation,\n output: outputData,\n };\n });\n return sampler._data;\n }\n /**\n * Loads a glTF buffer.\n * @param context The context when loading the asset\n * @param buffer The glTF buffer property\n * @param byteOffset The byte offset to use\n * @param byteLength The byte length to use\n * @returns A promise that resolves with the loaded data when the load is complete\n */\n loadBufferAsync(context, buffer, byteOffset, byteLength) {\n const extensionPromise = this._extensionsLoadBufferAsync(context, buffer, byteOffset, byteLength);\n if (extensionPromise) {\n return extensionPromise;\n }\n if (!buffer._data) {\n if (buffer.uri) {\n buffer._data = this.loadUriAsync(`${context}/uri`, buffer, buffer.uri);\n }\n else {\n if (!this._bin) {\n throw new Error(`${context}: Uri is missing or the binary glTF is missing its binary chunk`);\n }\n buffer._data = this._bin.readAsync(0, buffer.byteLength);\n }\n }\n return buffer._data.then((data) => {\n try {\n return new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);\n }\n catch (e) {\n throw new Error(`${context}: ${e.message}`);\n }\n });\n }\n /**\n * Loads a glTF buffer view.\n * @param context The context when loading the asset\n * @param bufferView The glTF buffer view property\n * @returns A promise that resolves with the loaded data when the load is complete\n */\n loadBufferViewAsync(context, bufferView) {\n const extensionPromise = this._extensionsLoadBufferViewAsync(context, bufferView);\n if (extensionPromise) {\n return extensionPromise;\n }\n if (bufferView._data) {\n return bufferView._data;\n }\n const buffer = ArrayItem.Get(`${context}/buffer`, this._gltf.buffers, bufferView.buffer);\n bufferView._data = this.loadBufferAsync(`/buffers/${buffer.index}`, buffer, bufferView.byteOffset || 0, bufferView.byteLength);\n return bufferView._data;\n }\n _loadAccessorAsync(context, accessor, constructor) {\n if (accessor._data) {\n return accessor._data;\n }\n const numComponents = GLTFLoader._GetNumComponents(context, accessor.type);\n const byteStride = numComponents * VertexBuffer.GetTypeByteLength(accessor.componentType);\n const length = numComponents * accessor.count;\n if (accessor.bufferView == undefined) {\n accessor._data = Promise.resolve(new constructor(length));\n }\n else {\n const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, accessor.bufferView);\n accessor._data = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView).then((data) => {\n if (accessor.componentType === 5126 /* AccessorComponentType.FLOAT */ && !accessor.normalized && (!bufferView.byteStride || bufferView.byteStride === byteStride)) {\n return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);\n }\n else {\n const typedArray = new constructor(length);\n VertexBuffer.ForEach(data, accessor.byteOffset || 0, bufferView.byteStride || byteStride, numComponents, accessor.componentType, typedArray.length, accessor.normalized || false, (value, index) => {\n typedArray[index] = value;\n });\n return typedArray;\n }\n });\n }\n if (accessor.sparse) {\n const sparse = accessor.sparse;\n accessor._data = accessor._data.then((data) => {\n const typedArray = data;\n const indicesBufferView = ArrayItem.Get(`${context}/sparse/indices/bufferView`, this._gltf.bufferViews, sparse.indices.bufferView);\n const valuesBufferView = ArrayItem.Get(`${context}/sparse/values/bufferView`, this._gltf.bufferViews, sparse.values.bufferView);\n return Promise.all([\n this.loadBufferViewAsync(`/bufferViews/${indicesBufferView.index}`, indicesBufferView),\n this.loadBufferViewAsync(`/bufferViews/${valuesBufferView.index}`, valuesBufferView),\n ]).then(([indicesData, valuesData]) => {\n const indices = GLTFLoader._GetTypedArray(`${context}/sparse/indices`, sparse.indices.componentType, indicesData, sparse.indices.byteOffset, sparse.count);\n const sparseLength = numComponents * sparse.count;\n let values;\n if (accessor.componentType === 5126 /* AccessorComponentType.FLOAT */ && !accessor.normalized) {\n values = GLTFLoader._GetTypedArray(`${context}/sparse/values`, accessor.componentType, valuesData, sparse.values.byteOffset, sparseLength);\n }\n else {\n const sparseData = GLTFLoader._GetTypedArray(`${context}/sparse/values`, accessor.componentType, valuesData, sparse.values.byteOffset, sparseLength);\n values = new constructor(sparseLength);\n VertexBuffer.ForEach(sparseData, 0, byteStride, numComponents, accessor.componentType, values.length, accessor.normalized || false, (value, index) => {\n values[index] = value;\n });\n }\n let valuesIndex = 0;\n for (let indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {\n let dataIndex = indices[indicesIndex] * numComponents;\n for (let componentIndex = 0; componentIndex < numComponents; componentIndex++) {\n typedArray[dataIndex++] = values[valuesIndex++];\n }\n }\n return typedArray;\n });\n });\n }\n return accessor._data;\n }\n /**\n * @internal\n */\n _loadFloatAccessorAsync(context, accessor) {\n return this._loadAccessorAsync(context, accessor, Float32Array);\n }\n /**\n * @internal\n */\n _loadIndicesAccessorAsync(context, accessor) {\n if (accessor.type !== \"SCALAR\" /* AccessorType.SCALAR */) {\n throw new Error(`${context}/type: Invalid value ${accessor.type}`);\n }\n if (accessor.componentType !== 5121 /* AccessorComponentType.UNSIGNED_BYTE */ &&\n accessor.componentType !== 5123 /* AccessorComponentType.UNSIGNED_SHORT */ &&\n accessor.componentType !== 5125 /* AccessorComponentType.UNSIGNED_INT */) {\n throw new Error(`${context}/componentType: Invalid value ${accessor.componentType}`);\n }\n if (accessor._data) {\n return accessor._data;\n }\n if (accessor.sparse) {\n const constructor = GLTFLoader._GetTypedArrayConstructor(`${context}/componentType`, accessor.componentType);\n accessor._data = this._loadAccessorAsync(context, accessor, constructor);\n }\n else {\n const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, accessor.bufferView);\n accessor._data = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView).then((data) => {\n return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);\n });\n }\n return accessor._data;\n }\n /**\n * @internal\n */\n _loadVertexBufferViewAsync(bufferView) {\n if (bufferView._babylonBuffer) {\n return bufferView._babylonBuffer;\n }\n const engine = this._babylonScene.getEngine();\n bufferView._babylonBuffer = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView).then((data) => {\n return new Buffer(engine, data, false);\n });\n return bufferView._babylonBuffer;\n }\n /**\n * @internal\n */\n _loadVertexAccessorAsync(context, accessor, kind) {\n var _a;\n if ((_a = accessor._babylonVertexBuffer) === null || _a === void 0 ? void 0 : _a[kind]) {\n return accessor._babylonVertexBuffer[kind];\n }\n if (!accessor._babylonVertexBuffer) {\n accessor._babylonVertexBuffer = {};\n }\n const engine = this._babylonScene.getEngine();\n if (accessor.sparse) {\n accessor._babylonVertexBuffer[kind] = this._loadFloatAccessorAsync(context, accessor).then((data) => {\n return new VertexBuffer(engine, data, kind, false);\n });\n }\n // Load joint indices as a float array since the shaders expect float data but glTF uses unsigned byte/short.\n // This prevents certain platforms (e.g. D3D) from having to convert the data to float on the fly.\n else if (kind === VertexBuffer.MatricesIndicesKind || kind === VertexBuffer.MatricesIndicesExtraKind) {\n accessor._babylonVertexBuffer[kind] = this._loadFloatAccessorAsync(context, accessor).then((data) => {\n return new VertexBuffer(engine, data, kind, false);\n });\n }\n else {\n const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, accessor.bufferView);\n accessor._babylonVertexBuffer[kind] = this._loadVertexBufferViewAsync(bufferView).then((babylonBuffer) => {\n const size = GLTFLoader._GetNumComponents(context, accessor.type);\n return new VertexBuffer(engine, babylonBuffer, kind, false, false, bufferView.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true, 1, true);\n });\n }\n return accessor._babylonVertexBuffer[kind];\n }\n _loadMaterialMetallicRoughnessPropertiesAsync(context, properties, babylonMaterial) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n const promises = new Array();\n if (properties) {\n if (properties.baseColorFactor) {\n babylonMaterial.albedoColor = Color3.FromArray(properties.baseColorFactor);\n babylonMaterial.alpha = properties.baseColorFactor[3];\n }\n else {\n babylonMaterial.albedoColor = Color3.White();\n }\n babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;\n babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;\n if (properties.baseColorTexture) {\n promises.push(this.loadTextureInfoAsync(`${context}/baseColorTexture`, properties.baseColorTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Base Color)`;\n babylonMaterial.albedoTexture = texture;\n }));\n }\n if (properties.metallicRoughnessTexture) {\n properties.metallicRoughnessTexture.nonColorData = true;\n promises.push(this.loadTextureInfoAsync(`${context}/metallicRoughnessTexture`, properties.metallicRoughnessTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Metallic Roughness)`;\n babylonMaterial.metallicTexture = texture;\n }));\n babylonMaterial.useMetallnessFromMetallicTextureBlue = true;\n babylonMaterial.useRoughnessFromMetallicTextureGreen = true;\n babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;\n }\n }\n return Promise.all(promises).then(() => { });\n }\n /**\n * @internal\n */\n _loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign = () => { }) {\n const extensionPromise = this._extensionsLoadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign);\n if (extensionPromise) {\n return extensionPromise;\n }\n material._data = material._data || {};\n let babylonData = material._data[babylonDrawMode];\n if (!babylonData) {\n this.logOpen(`${context} ${material.name || \"\"}`);\n const babylonMaterial = this.createMaterial(context, material, babylonDrawMode);\n babylonData = {\n babylonMaterial: babylonMaterial,\n babylonMeshes: [],\n promise: this.loadMaterialPropertiesAsync(context, material, babylonMaterial),\n };\n material._data[babylonDrawMode] = babylonData;\n GLTFLoader.AddPointerMetadata(babylonMaterial, context);\n this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);\n this.logClose();\n }\n if (babylonMesh) {\n babylonData.babylonMeshes.push(babylonMesh);\n babylonMesh.onDisposeObservable.addOnce(() => {\n const index = babylonData.babylonMeshes.indexOf(babylonMesh);\n if (index !== -1) {\n babylonData.babylonMeshes.splice(index, 1);\n }\n });\n }\n assign(babylonData.babylonMaterial);\n return babylonData.promise.then(() => {\n return babylonData.babylonMaterial;\n });\n }\n _createDefaultMaterial(name, babylonDrawMode) {\n this._babylonScene._blockEntityCollection = !!this._assetContainer;\n const babylonMaterial = new PBRMaterial(name, this._babylonScene);\n babylonMaterial._parentContainer = this._assetContainer;\n this._babylonScene._blockEntityCollection = false;\n // Moved to mesh so user can change materials on gltf meshes: babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation;\n babylonMaterial.fillMode = babylonDrawMode;\n babylonMaterial.enableSpecularAntiAliasing = true;\n babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;\n babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;\n babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_OPAQUE;\n babylonMaterial.metallic = 1;\n babylonMaterial.roughness = 1;\n return babylonMaterial;\n }\n /**\n * Creates a Babylon material from a glTF material.\n * @param context The context when loading the asset\n * @param material The glTF material property\n * @param babylonDrawMode The draw mode for the Babylon material\n * @returns The Babylon material\n */\n createMaterial(context, material, babylonDrawMode) {\n const extensionPromise = this._extensionsCreateMaterial(context, material, babylonDrawMode);\n if (extensionPromise) {\n return extensionPromise;\n }\n const name = material.name || `material${material.index}`;\n const babylonMaterial = this._createDefaultMaterial(name, babylonDrawMode);\n return babylonMaterial;\n }\n /**\n * Loads properties from a glTF material into a Babylon material.\n * @param context The context when loading the asset\n * @param material The glTF material property\n * @param babylonMaterial The Babylon material\n * @returns A promise that resolves when the load is complete\n */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n const extensionPromise = this._extensionsLoadMaterialPropertiesAsync(context, material, babylonMaterial);\n if (extensionPromise) {\n return extensionPromise;\n }\n const promises = new Array();\n promises.push(this.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));\n if (material.pbrMetallicRoughness) {\n promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${context}/pbrMetallicRoughness`, material.pbrMetallicRoughness, babylonMaterial));\n }\n this.loadMaterialAlphaProperties(context, material, babylonMaterial);\n return Promise.all(promises).then(() => { });\n }\n /**\n * Loads the normal, occlusion, and emissive properties from a glTF material into a Babylon material.\n * @param context The context when loading the asset\n * @param material The glTF material property\n * @param babylonMaterial The Babylon material\n * @returns A promise that resolves when the load is complete\n */\n loadMaterialBasePropertiesAsync(context, material, babylonMaterial) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n const promises = new Array();\n babylonMaterial.emissiveColor = material.emissiveFactor ? Color3.FromArray(material.emissiveFactor) : new Color3(0, 0, 0);\n if (material.doubleSided) {\n babylonMaterial.backFaceCulling = false;\n babylonMaterial.twoSidedLighting = true;\n }\n if (material.normalTexture) {\n material.normalTexture.nonColorData = true;\n promises.push(this.loadTextureInfoAsync(`${context}/normalTexture`, material.normalTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Normal)`;\n babylonMaterial.bumpTexture = texture;\n }));\n babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;\n babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;\n if (material.normalTexture.scale != undefined && babylonMaterial.bumpTexture) {\n babylonMaterial.bumpTexture.level = material.normalTexture.scale;\n }\n babylonMaterial.forceIrradianceInFragment = true;\n }\n if (material.occlusionTexture) {\n material.occlusionTexture.nonColorData = true;\n promises.push(this.loadTextureInfoAsync(`${context}/occlusionTexture`, material.occlusionTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Occlusion)`;\n babylonMaterial.ambientTexture = texture;\n }));\n babylonMaterial.useAmbientInGrayScale = true;\n if (material.occlusionTexture.strength != undefined) {\n babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;\n }\n }\n if (material.emissiveTexture) {\n promises.push(this.loadTextureInfoAsync(`${context}/emissiveTexture`, material.emissiveTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Emissive)`;\n babylonMaterial.emissiveTexture = texture;\n }));\n }\n return Promise.all(promises).then(() => { });\n }\n /**\n * Loads the alpha properties from a glTF material into a Babylon material.\n * Must be called after the setting the albedo texture of the Babylon material when the material has an albedo texture.\n * @param context The context when loading the asset\n * @param material The glTF material property\n * @param babylonMaterial The Babylon material\n */\n loadMaterialAlphaProperties(context, material, babylonMaterial) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n const alphaMode = material.alphaMode || \"OPAQUE\" /* MaterialAlphaMode.OPAQUE */;\n switch (alphaMode) {\n case \"OPAQUE\" /* MaterialAlphaMode.OPAQUE */: {\n babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_OPAQUE;\n break;\n }\n case \"MASK\" /* MaterialAlphaMode.MASK */: {\n babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHATEST;\n babylonMaterial.alphaCutOff = material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff;\n if (babylonMaterial.albedoTexture) {\n babylonMaterial.albedoTexture.hasAlpha = true;\n }\n break;\n }\n case \"BLEND\" /* MaterialAlphaMode.BLEND */: {\n babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHABLEND;\n if (babylonMaterial.albedoTexture) {\n babylonMaterial.albedoTexture.hasAlpha = true;\n babylonMaterial.useAlphaFromAlbedoTexture = true;\n }\n break;\n }\n default: {\n throw new Error(`${context}/alphaMode: Invalid value (${material.alphaMode})`);\n }\n }\n }\n /**\n * Loads a glTF texture info.\n * @param context The context when loading the asset\n * @param textureInfo The glTF texture info property\n * @param assign A function called synchronously after parsing the glTF properties\n * @returns A promise that resolves with the loaded Babylon texture when the load is complete\n */\n loadTextureInfoAsync(context, textureInfo, assign = () => { }) {\n const extensionPromise = this._extensionsLoadTextureInfoAsync(context, textureInfo, assign);\n if (extensionPromise) {\n return extensionPromise;\n }\n this.logOpen(`${context}`);\n if (textureInfo.texCoord >= 6) {\n throw new Error(`${context}/texCoord: Invalid value (${textureInfo.texCoord})`);\n }\n const texture = ArrayItem.Get(`${context}/index`, this._gltf.textures, textureInfo.index);\n texture._textureInfo = textureInfo;\n const promise = this._loadTextureAsync(`/textures/${textureInfo.index}`, texture, (babylonTexture) => {\n babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;\n GLTFLoader.AddPointerMetadata(babylonTexture, context);\n this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);\n assign(babylonTexture);\n });\n this.logClose();\n return promise;\n }\n /**\n * @internal\n */\n _loadTextureAsync(context, texture, assign = () => { }) {\n const extensionPromise = this._extensionsLoadTextureAsync(context, texture, assign);\n if (extensionPromise) {\n return extensionPromise;\n }\n this.logOpen(`${context} ${texture.name || \"\"}`);\n const sampler = texture.sampler == undefined ? GLTFLoader.DefaultSampler : ArrayItem.Get(`${context}/sampler`, this._gltf.samplers, texture.sampler);\n const image = ArrayItem.Get(`${context}/source`, this._gltf.images, texture.source);\n const promise = this._createTextureAsync(context, sampler, image, assign, undefined, !texture._textureInfo.nonColorData);\n this.logClose();\n return promise;\n }\n /**\n * @internal\n */\n _createTextureAsync(context, sampler, image, assign = () => { }, textureLoaderOptions, useSRGBBuffer) {\n const samplerData = this._loadSampler(`/samplers/${sampler.index}`, sampler);\n const promises = new Array();\n const deferred = new Deferred();\n this._babylonScene._blockEntityCollection = !!this._assetContainer;\n const textureCreationOptions = {\n noMipmap: samplerData.noMipMaps,\n invertY: false,\n samplingMode: samplerData.samplingMode,\n onLoad: () => {\n if (!this._disposed) {\n deferred.resolve();\n }\n },\n onError: (message, exception) => {\n if (!this._disposed) {\n deferred.reject(new Error(`${context}: ${exception && exception.message ? exception.message : message || \"Failed to load texture\"}`));\n }\n },\n mimeType: image.mimeType,\n loaderOptions: textureLoaderOptions,\n useSRGBBuffer: !!useSRGBBuffer && this._parent.useSRGBBuffers,\n };\n const babylonTexture = new Texture(null, this._babylonScene, textureCreationOptions);\n babylonTexture._parentContainer = this._assetContainer;\n this._babylonScene._blockEntityCollection = false;\n promises.push(deferred.promise);\n promises.push(this.loadImageAsync(`/images/${image.index}`, image).then((data) => {\n const name = image.uri || `${this._fileName}#image${image.index}`;\n const dataUrl = `data:${this._uniqueRootUrl}${name}`;\n babylonTexture.updateURL(dataUrl, data);\n }));\n babylonTexture.wrapU = samplerData.wrapU;\n babylonTexture.wrapV = samplerData.wrapV;\n assign(babylonTexture);\n return Promise.all(promises).then(() => {\n return babylonTexture;\n });\n }\n _loadSampler(context, sampler) {\n if (!sampler._data) {\n sampler._data = {\n noMipMaps: sampler.minFilter === 9728 /* TextureMinFilter.NEAREST */ || sampler.minFilter === 9729 /* TextureMinFilter.LINEAR */,\n samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler),\n wrapU: GLTFLoader._GetTextureWrapMode(`${context}/wrapS`, sampler.wrapS),\n wrapV: GLTFLoader._GetTextureWrapMode(`${context}/wrapT`, sampler.wrapT),\n };\n }\n return sampler._data;\n }\n /**\n * Loads a glTF image.\n * @param context The context when loading the asset\n * @param image The glTF image property\n * @returns A promise that resolves with the loaded data when the load is complete\n */\n loadImageAsync(context, image) {\n if (!image._data) {\n this.logOpen(`${context} ${image.name || \"\"}`);\n if (image.uri) {\n image._data = this.loadUriAsync(`${context}/uri`, image, image.uri);\n }\n else {\n const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, image.bufferView);\n image._data = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView);\n }\n this.logClose();\n }\n return image._data;\n }\n /**\n * Loads a glTF uri.\n * @param context The context when loading the asset\n * @param property The glTF property associated with the uri\n * @param uri The base64 or relative uri\n * @returns A promise that resolves with the loaded data when the load is complete\n */\n loadUriAsync(context, property, uri) {\n const extensionPromise = this._extensionsLoadUriAsync(context, property, uri);\n if (extensionPromise) {\n return extensionPromise;\n }\n if (!GLTFLoader._ValidateUri(uri)) {\n throw new Error(`${context}: '${uri}' is invalid`);\n }\n if (IsBase64DataUrl(uri)) {\n const data = new Uint8Array(DecodeBase64UrlToBinary(uri));\n this.log(`${context}: Decoded ${uri.substr(0, 64)}... (${data.length} bytes)`);\n return Promise.resolve(data);\n }\n this.log(`${context}: Loading ${uri}`);\n return this._parent.preprocessUrlAsync(this._rootUrl + uri).then((url) => {\n return new Promise((resolve, reject) => {\n this._parent._loadFile(this._babylonScene, url, (data) => {\n if (!this._disposed) {\n this.log(`${context}: Loaded ${uri} (${data.byteLength} bytes)`);\n resolve(new Uint8Array(data));\n }\n }, true, (request) => {\n reject(new LoadFileError(`${context}: Failed to load '${uri}'${request ? \": \" + request.status + \" \" + request.statusText : \"\"}`, request));\n });\n });\n });\n }\n /**\n * Adds a JSON pointer to the _internalMetadata of the Babylon object at `._internalMetadata.gltf.pointers`.\n * @param babylonObject the Babylon object with _internalMetadata\n * @param pointer the JSON pointer\n */\n static AddPointerMetadata(babylonObject, pointer) {\n babylonObject.metadata = babylonObject.metadata || {};\n const metadata = (babylonObject._internalMetadata = babylonObject._internalMetadata || {});\n const gltf = (metadata.gltf = metadata.gltf || {});\n const pointers = (gltf.pointers = gltf.pointers || []);\n pointers.push(pointer);\n }\n static _GetTextureWrapMode(context, mode) {\n // Set defaults if undefined\n mode = mode == undefined ? 10497 /* TextureWrapMode.REPEAT */ : mode;\n switch (mode) {\n case 33071 /* TextureWrapMode.CLAMP_TO_EDGE */:\n return Texture.CLAMP_ADDRESSMODE;\n case 33648 /* TextureWrapMode.MIRRORED_REPEAT */:\n return Texture.MIRROR_ADDRESSMODE;\n case 10497 /* TextureWrapMode.REPEAT */:\n return Texture.WRAP_ADDRESSMODE;\n default:\n Logger.Warn(`${context}: Invalid value (${mode})`);\n return Texture.WRAP_ADDRESSMODE;\n }\n }\n static _GetTextureSamplingMode(context, sampler) {\n // Set defaults if undefined\n const magFilter = sampler.magFilter == undefined ? 9729 /* TextureMagFilter.LINEAR */ : sampler.magFilter;\n const minFilter = sampler.minFilter == undefined ? 9987 /* TextureMinFilter.LINEAR_MIPMAP_LINEAR */ : sampler.minFilter;\n if (magFilter === 9729 /* TextureMagFilter.LINEAR */) {\n switch (minFilter) {\n case 9728 /* TextureMinFilter.NEAREST */:\n return Texture.LINEAR_NEAREST;\n case 9729 /* TextureMinFilter.LINEAR */:\n return Texture.LINEAR_LINEAR;\n case 9984 /* TextureMinFilter.NEAREST_MIPMAP_NEAREST */:\n return Texture.LINEAR_NEAREST_MIPNEAREST;\n case 9985 /* TextureMinFilter.LINEAR_MIPMAP_NEAREST */:\n return Texture.LINEAR_LINEAR_MIPNEAREST;\n case 9986 /* TextureMinFilter.NEAREST_MIPMAP_LINEAR */:\n return Texture.LINEAR_NEAREST_MIPLINEAR;\n case 9987 /* TextureMinFilter.LINEAR_MIPMAP_LINEAR */:\n return Texture.LINEAR_LINEAR_MIPLINEAR;\n default:\n Logger.Warn(`${context}/minFilter: Invalid value (${minFilter})`);\n return Texture.LINEAR_LINEAR_MIPLINEAR;\n }\n }\n else {\n if (magFilter !== 9728 /* TextureMagFilter.NEAREST */) {\n Logger.Warn(`${context}/magFilter: Invalid value (${magFilter})`);\n }\n switch (minFilter) {\n case 9728 /* TextureMinFilter.NEAREST */:\n return Texture.NEAREST_NEAREST;\n case 9729 /* TextureMinFilter.LINEAR */:\n return Texture.NEAREST_LINEAR;\n case 9984 /* TextureMinFilter.NEAREST_MIPMAP_NEAREST */:\n return Texture.NEAREST_NEAREST_MIPNEAREST;\n case 9985 /* TextureMinFilter.LINEAR_MIPMAP_NEAREST */:\n return Texture.NEAREST_LINEAR_MIPNEAREST;\n case 9986 /* TextureMinFilter.NEAREST_MIPMAP_LINEAR */:\n return Texture.NEAREST_NEAREST_MIPLINEAR;\n case 9987 /* TextureMinFilter.LINEAR_MIPMAP_LINEAR */:\n return Texture.NEAREST_LINEAR_MIPLINEAR;\n default:\n Logger.Warn(`${context}/minFilter: Invalid value (${minFilter})`);\n return Texture.NEAREST_NEAREST_MIPNEAREST;\n }\n }\n }\n static _GetTypedArrayConstructor(context, componentType) {\n switch (componentType) {\n case 5120 /* AccessorComponentType.BYTE */:\n return Int8Array;\n case 5121 /* AccessorComponentType.UNSIGNED_BYTE */:\n return Uint8Array;\n case 5122 /* AccessorComponentType.SHORT */:\n return Int16Array;\n case 5123 /* AccessorComponentType.UNSIGNED_SHORT */:\n return Uint16Array;\n case 5125 /* AccessorComponentType.UNSIGNED_INT */:\n return Uint32Array;\n case 5126 /* AccessorComponentType.FLOAT */:\n return Float32Array;\n default:\n throw new Error(`${context}: Invalid component type ${componentType}`);\n }\n }\n static _GetTypedArray(context, componentType, bufferView, byteOffset, length) {\n const buffer = bufferView.buffer;\n byteOffset = bufferView.byteOffset + (byteOffset || 0);\n const constructor = GLTFLoader._GetTypedArrayConstructor(`${context}/componentType`, componentType);\n const componentTypeLength = VertexBuffer.GetTypeByteLength(componentType);\n if (byteOffset % componentTypeLength !== 0) {\n // HACK: Copy the buffer if byte offset is not a multiple of component type byte length.\n Logger.Warn(`${context}: Copying buffer as byte offset (${byteOffset}) is not a multiple of component type byte length (${componentTypeLength})`);\n return new constructor(buffer.slice(byteOffset, byteOffset + length * componentTypeLength), 0);\n }\n return new constructor(buffer, byteOffset, length);\n }\n static _GetNumComponents(context, type) {\n switch (type) {\n case \"SCALAR\":\n return 1;\n case \"VEC2\":\n return 2;\n case \"VEC3\":\n return 3;\n case \"VEC4\":\n return 4;\n case \"MAT2\":\n return 4;\n case \"MAT3\":\n return 9;\n case \"MAT4\":\n return 16;\n }\n throw new Error(`${context}: Invalid type (${type})`);\n }\n static _ValidateUri(uri) {\n return Tools.IsBase64(uri) || uri.indexOf(\"..\") === -1;\n }\n /**\n * @internal\n */\n static _GetDrawMode(context, mode) {\n if (mode == undefined) {\n mode = 4 /* MeshPrimitiveMode.TRIANGLES */;\n }\n switch (mode) {\n case 0 /* MeshPrimitiveMode.POINTS */:\n return Material.PointListDrawMode;\n case 1 /* MeshPrimitiveMode.LINES */:\n return Material.LineListDrawMode;\n case 2 /* MeshPrimitiveMode.LINE_LOOP */:\n return Material.LineLoopDrawMode;\n case 3 /* MeshPrimitiveMode.LINE_STRIP */:\n return Material.LineStripDrawMode;\n case 4 /* MeshPrimitiveMode.TRIANGLES */:\n return Material.TriangleFillMode;\n case 5 /* MeshPrimitiveMode.TRIANGLE_STRIP */:\n return Material.TriangleStripDrawMode;\n case 6 /* MeshPrimitiveMode.TRIANGLE_FAN */:\n return Material.TriangleFanDrawMode;\n }\n throw new Error(`${context}: Invalid mesh primitive mode (${mode})`);\n }\n _compileMaterialsAsync() {\n this._parent._startPerformanceCounter(\"Compile materials\");\n const promises = new Array();\n if (this._gltf.materials) {\n for (const material of this._gltf.materials) {\n if (material._data) {\n for (const babylonDrawMode in material._data) {\n const babylonData = material._data[babylonDrawMode];\n for (const babylonMesh of babylonData.babylonMeshes) {\n // Ensure nonUniformScaling is set if necessary.\n babylonMesh.computeWorldMatrix(true);\n const babylonMaterial = babylonData.babylonMaterial;\n promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));\n promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { useInstances: true }));\n if (this._parent.useClipPlane) {\n promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));\n promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true, useInstances: true }));\n }\n }\n }\n }\n }\n }\n return Promise.all(promises).then(() => {\n this._parent._endPerformanceCounter(\"Compile materials\");\n });\n }\n _compileShadowGeneratorsAsync() {\n this._parent._startPerformanceCounter(\"Compile shadow generators\");\n const promises = new Array();\n const lights = this._babylonScene.lights;\n for (const light of lights) {\n const generator = light.getShadowGenerator();\n if (generator) {\n promises.push(generator.forceCompilationAsync());\n }\n }\n return Promise.all(promises).then(() => {\n this._parent._endPerformanceCounter(\"Compile shadow generators\");\n });\n }\n _forEachExtensions(action) {\n for (const extension of this._extensions) {\n if (extension.enabled) {\n action(extension);\n }\n }\n }\n _applyExtensions(property, functionName, actionAsync) {\n for (const extension of this._extensions) {\n if (extension.enabled) {\n const id = `${extension.name}.${functionName}`;\n const loaderProperty = property;\n loaderProperty._activeLoaderExtensionFunctions = loaderProperty._activeLoaderExtensionFunctions || {};\n const activeLoaderExtensionFunctions = loaderProperty._activeLoaderExtensionFunctions;\n if (!activeLoaderExtensionFunctions[id]) {\n activeLoaderExtensionFunctions[id] = true;\n try {\n const result = actionAsync(extension);\n if (result) {\n return result;\n }\n }\n finally {\n delete activeLoaderExtensionFunctions[id];\n }\n }\n }\n }\n return null;\n }\n _extensionsOnLoading() {\n this._forEachExtensions((extension) => extension.onLoading && extension.onLoading());\n }\n _extensionsOnReady() {\n this._forEachExtensions((extension) => extension.onReady && extension.onReady());\n }\n _extensionsLoadSceneAsync(context, scene) {\n return this._applyExtensions(scene, \"loadScene\", (extension) => extension.loadSceneAsync && extension.loadSceneAsync(context, scene));\n }\n _extensionsLoadNodeAsync(context, node, assign) {\n return this._applyExtensions(node, \"loadNode\", (extension) => extension.loadNodeAsync && extension.loadNodeAsync(context, node, assign));\n }\n _extensionsLoadCameraAsync(context, camera, assign) {\n return this._applyExtensions(camera, \"loadCamera\", (extension) => extension.loadCameraAsync && extension.loadCameraAsync(context, camera, assign));\n }\n _extensionsLoadVertexDataAsync(context, primitive, babylonMesh) {\n return this._applyExtensions(primitive, \"loadVertexData\", (extension) => extension._loadVertexDataAsync && extension._loadVertexDataAsync(context, primitive, babylonMesh));\n }\n _extensionsLoadMeshPrimitiveAsync(context, name, node, mesh, primitive, assign) {\n return this._applyExtensions(primitive, \"loadMeshPrimitive\", (extension) => extension._loadMeshPrimitiveAsync && extension._loadMeshPrimitiveAsync(context, name, node, mesh, primitive, assign));\n }\n _extensionsLoadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign) {\n return this._applyExtensions(material, \"loadMaterial\", (extension) => extension._loadMaterialAsync && extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign));\n }\n _extensionsCreateMaterial(context, material, babylonDrawMode) {\n return this._applyExtensions(material, \"createMaterial\", (extension) => extension.createMaterial && extension.createMaterial(context, material, babylonDrawMode));\n }\n _extensionsLoadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return this._applyExtensions(material, \"loadMaterialProperties\", (extension) => extension.loadMaterialPropertiesAsync && extension.loadMaterialPropertiesAsync(context, material, babylonMaterial));\n }\n _extensionsLoadTextureInfoAsync(context, textureInfo, assign) {\n return this._applyExtensions(textureInfo, \"loadTextureInfo\", (extension) => extension.loadTextureInfoAsync && extension.loadTextureInfoAsync(context, textureInfo, assign));\n }\n _extensionsLoadTextureAsync(context, texture, assign) {\n return this._applyExtensions(texture, \"loadTexture\", (extension) => extension._loadTextureAsync && extension._loadTextureAsync(context, texture, assign));\n }\n _extensionsLoadAnimationAsync(context, animation) {\n return this._applyExtensions(animation, \"loadAnimation\", (extension) => extension.loadAnimationAsync && extension.loadAnimationAsync(context, animation));\n }\n _extensionsLoadAnimationChannelAsync(context, animationContext, animation, channel, onLoad) {\n return this._applyExtensions(animation, \"loadAnimationChannel\", (extension) => extension._loadAnimationChannelAsync && extension._loadAnimationChannelAsync(context, animationContext, animation, channel, onLoad));\n }\n _extensionsLoadSkinAsync(context, node, skin) {\n return this._applyExtensions(skin, \"loadSkin\", (extension) => extension._loadSkinAsync && extension._loadSkinAsync(context, node, skin));\n }\n _extensionsLoadUriAsync(context, property, uri) {\n return this._applyExtensions(property, \"loadUri\", (extension) => extension._loadUriAsync && extension._loadUriAsync(context, property, uri));\n }\n _extensionsLoadBufferViewAsync(context, bufferView) {\n return this._applyExtensions(bufferView, \"loadBufferView\", (extension) => extension.loadBufferViewAsync && extension.loadBufferViewAsync(context, bufferView));\n }\n _extensionsLoadBufferAsync(context, buffer, byteOffset, byteLength) {\n return this._applyExtensions(buffer, \"loadBuffer\", (extension) => extension.loadBufferAsync && extension.loadBufferAsync(context, buffer, byteOffset, byteLength));\n }\n /**\n * Helper method called by a loader extension to load an glTF extension.\n * @param context The context when loading the asset\n * @param property The glTF property to load the extension from\n * @param extensionName The name of the extension to load\n * @param actionAsync The action to run\n * @returns The promise returned by actionAsync or null if the extension does not exist\n */\n static LoadExtensionAsync(context, property, extensionName, actionAsync) {\n if (!property.extensions) {\n return null;\n }\n const extensions = property.extensions;\n const extension = extensions[extensionName];\n if (!extension) {\n return null;\n }\n return actionAsync(`${context}/extensions/${extensionName}`, extension);\n }\n /**\n * Helper method called by a loader extension to load a glTF extra.\n * @param context The context when loading the asset\n * @param property The glTF property to load the extra from\n * @param extensionName The name of the extension to load\n * @param actionAsync The action to run\n * @returns The promise returned by actionAsync or null if the extra does not exist\n */\n static LoadExtraAsync(context, property, extensionName, actionAsync) {\n if (!property.extras) {\n return null;\n }\n const extras = property.extras;\n const extra = extras[extensionName];\n if (!extra) {\n return null;\n }\n return actionAsync(`${context}/extras/${extensionName}`, extra);\n }\n /**\n * Checks for presence of an extension.\n * @param name The name of the extension to check\n * @returns A boolean indicating the presence of the given extension name in `extensionsUsed`\n */\n isExtensionUsed(name) {\n return !!this._gltf.extensionsUsed && this._gltf.extensionsUsed.indexOf(name) !== -1;\n }\n /**\n * Increments the indentation level and logs a message.\n * @param message The message to log\n */\n logOpen(message) {\n this._parent._logOpen(message);\n }\n /**\n * Decrements the indentation level.\n */\n logClose() {\n this._parent._logClose();\n }\n /**\n * Logs a message\n * @param message The message to log\n */\n log(message) {\n this._parent._log(message);\n }\n /**\n * Starts a performance counter.\n * @param counterName The name of the performance counter\n */\n startPerformanceCounter(counterName) {\n this._parent._startPerformanceCounter(counterName);\n }\n /**\n * Ends a performance counter.\n * @param counterName The name of the performance counter\n */\n endPerformanceCounter(counterName) {\n this._parent._endPerformanceCounter(counterName);\n }\n}\nGLTFLoader._RegisteredExtensions = {};\n/**\n * The default glTF sampler.\n */\nGLTFLoader.DefaultSampler = { index: -1 };\nGLTFFileLoader._CreateGLTF2Loader = (parent) => new GLTFLoader(parent);\n//# sourceMappingURL=glTFLoader.js.map","export {};\n//# sourceMappingURL=glTFLoaderExtension.js.map","import { Scalar } from \"@babylonjs/core/Maths/math.scalar.js\";\nimport { SphericalHarmonics, SphericalPolynomial } from \"@babylonjs/core/Maths/sphericalPolynomial.js\";\nimport { Quaternion, Matrix } from \"@babylonjs/core/Maths/math.vector.js\";\nimport { RawCubeTexture } from \"@babylonjs/core/Materials/Textures/rawCubeTexture.js\";\nimport { GLTFLoader, ArrayItem } from \"../glTFLoader.js\";\nconst NAME = \"EXT_lights_image_based\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Vendor/EXT_lights_image_based/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class EXT_lights_image_based {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n delete this._lights;\n }\n /** @internal */\n onLoading() {\n const extensions = this._loader.gltf.extensions;\n if (extensions && extensions[this.name]) {\n const extension = extensions[this.name];\n this._lights = extension.lights;\n }\n }\n /**\n * @internal\n */\n loadSceneAsync(context, scene) {\n return GLTFLoader.LoadExtensionAsync(context, scene, this.name, (extensionContext, extension) => {\n const promises = new Array();\n promises.push(this._loader.loadSceneAsync(context, scene));\n this._loader.logOpen(`${extensionContext}`);\n const light = ArrayItem.Get(`${extensionContext}/light`, this._lights, extension.light);\n promises.push(this._loadLightAsync(`/extensions/${this.name}/lights/${extension.light}`, light).then((texture) => {\n this._loader.babylonScene.environmentTexture = texture;\n }));\n this._loader.logClose();\n return Promise.all(promises).then(() => { });\n });\n }\n _loadLightAsync(context, light) {\n if (!light._loaded) {\n const promises = new Array();\n this._loader.logOpen(`${context}`);\n const imageData = new Array(light.specularImages.length);\n for (let mipmap = 0; mipmap < light.specularImages.length; mipmap++) {\n const faces = light.specularImages[mipmap];\n imageData[mipmap] = new Array(faces.length);\n for (let face = 0; face < faces.length; face++) {\n const specularImageContext = `${context}/specularImages/${mipmap}/${face}`;\n this._loader.logOpen(`${specularImageContext}`);\n const index = faces[face];\n const image = ArrayItem.Get(specularImageContext, this._loader.gltf.images, index);\n promises.push(this._loader.loadImageAsync(`/images/${index}`, image).then((data) => {\n imageData[mipmap][face] = data;\n }));\n this._loader.logClose();\n }\n }\n this._loader.logClose();\n light._loaded = Promise.all(promises).then(() => {\n const babylonTexture = new RawCubeTexture(this._loader.babylonScene, null, light.specularImageSize);\n babylonTexture.name = light.name || \"environment\";\n light._babylonTexture = babylonTexture;\n if (light.intensity != undefined) {\n babylonTexture.level = light.intensity;\n }\n if (light.rotation) {\n let rotation = Quaternion.FromArray(light.rotation);\n // Invert the rotation so that positive rotation is counter-clockwise.\n if (!this._loader.babylonScene.useRightHandedSystem) {\n rotation = Quaternion.Inverse(rotation);\n }\n Matrix.FromQuaternionToRef(rotation, babylonTexture.getReflectionTextureMatrix());\n }\n if (!light.irradianceCoefficients) {\n throw new Error(`${context}: Irradiance coefficients are missing`);\n }\n const sphericalHarmonics = SphericalHarmonics.FromArray(light.irradianceCoefficients);\n sphericalHarmonics.scaleInPlace(light.intensity);\n sphericalHarmonics.convertIrradianceToLambertianRadiance();\n const sphericalPolynomial = SphericalPolynomial.FromHarmonics(sphericalHarmonics);\n // Compute the lod generation scale to fit exactly to the number of levels available.\n const lodGenerationScale = (imageData.length - 1) / Scalar.Log2(light.specularImageSize);\n return babylonTexture.updateRGBDAsync(imageData, sphericalPolynomial, lodGenerationScale);\n });\n }\n return light._loaded.then(() => {\n return light._babylonTexture;\n });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new EXT_lights_image_based(loader));\n//# sourceMappingURL=EXT_lights_image_based.js.map","export {};\n//# sourceMappingURL=glTFLoaderInterfaces.js.map","import { Vector3, Quaternion, Matrix, TmpVectors } from \"@babylonjs/core/Maths/math.vector.js\";\nimport { GLTFLoader, ArrayItem } from \"../glTFLoader.js\";\nimport \"@babylonjs/core/Meshes/thinInstanceMesh.js\";\nconst NAME = \"EXT_mesh_gpu_instancing\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Vendor/EXT_mesh_gpu_instancing/README.md)\n * [Playground Sample](https://playground.babylonjs.com/#QFIGLW#9)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class EXT_mesh_gpu_instancing {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadNodeAsync(context, node, assign) {\n return GLTFLoader.LoadExtensionAsync(context, node, this.name, (extensionContext, extension) => {\n this._loader._disableInstancedMesh++;\n const promise = this._loader.loadNodeAsync(`/nodes/${node.index}`, node, assign);\n this._loader._disableInstancedMesh--;\n if (!node._primitiveBabylonMeshes) {\n return promise;\n }\n const promises = new Array();\n let instanceCount = 0;\n const loadAttribute = (attribute) => {\n if (extension.attributes[attribute] == undefined) {\n promises.push(Promise.resolve(null));\n return;\n }\n const accessor = ArrayItem.Get(`${extensionContext}/attributes/${attribute}`, this._loader.gltf.accessors, extension.attributes[attribute]);\n promises.push(this._loader._loadFloatAccessorAsync(`/accessors/${accessor.bufferView}`, accessor));\n if (instanceCount === 0) {\n instanceCount = accessor.count;\n }\n else if (instanceCount !== accessor.count) {\n throw new Error(`${extensionContext}/attributes: Instance buffer accessors do not have the same count.`);\n }\n };\n loadAttribute(\"TRANSLATION\");\n loadAttribute(\"ROTATION\");\n loadAttribute(\"SCALE\");\n return promise.then((babylonTransformNode) => {\n return Promise.all(promises).then(([translationBuffer, rotationBuffer, scaleBuffer]) => {\n const matrices = new Float32Array(instanceCount * 16);\n TmpVectors.Vector3[0].copyFromFloats(0, 0, 0); // translation\n TmpVectors.Quaternion[0].copyFromFloats(0, 0, 0, 1); // rotation\n TmpVectors.Vector3[1].copyFromFloats(1, 1, 1); // scale\n for (let i = 0; i < instanceCount; ++i) {\n translationBuffer && Vector3.FromArrayToRef(translationBuffer, i * 3, TmpVectors.Vector3[0]);\n rotationBuffer && Quaternion.FromArrayToRef(rotationBuffer, i * 4, TmpVectors.Quaternion[0]);\n scaleBuffer && Vector3.FromArrayToRef(scaleBuffer, i * 3, TmpVectors.Vector3[1]);\n Matrix.ComposeToRef(TmpVectors.Vector3[1], TmpVectors.Quaternion[0], TmpVectors.Vector3[0], TmpVectors.Matrix[0]);\n TmpVectors.Matrix[0].copyToArray(matrices, i * 16);\n }\n for (const babylonMesh of node._primitiveBabylonMeshes) {\n babylonMesh.thinInstanceSetBuffer(\"matrix\", matrices, 16, true);\n }\n return babylonTransformNode;\n });\n });\n });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new EXT_mesh_gpu_instancing(loader));\n//# sourceMappingURL=EXT_mesh_gpu_instancing.js.map","import { ArrayItem, GLTFLoader } from \"../glTFLoader.js\";\nimport { MeshoptCompression } from \"@babylonjs/core/Meshes/Compression/meshoptCompression.js\";\nconst NAME = \"EXT_meshopt_compression\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Vendor/EXT_meshopt_compression/README.md)\n *\n * This extension uses a WebAssembly decoder module from https://github.com/zeux/meshoptimizer/tree/master/js\n * @since 5.0.0\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class EXT_meshopt_compression {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n this.enabled = loader.isExtensionUsed(NAME);\n this._loader = loader;\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadBufferViewAsync(context, bufferView) {\n return GLTFLoader.LoadExtensionAsync(context, bufferView, this.name, (extensionContext, extension) => {\n const bufferViewMeshopt = bufferView;\n if (bufferViewMeshopt._meshOptData) {\n return bufferViewMeshopt._meshOptData;\n }\n const buffer = ArrayItem.Get(`${context}/buffer`, this._loader.gltf.buffers, extension.buffer);\n bufferViewMeshopt._meshOptData = this._loader.loadBufferAsync(`/buffers/${buffer.index}`, buffer, extension.byteOffset || 0, extension.byteLength).then((buffer) => {\n return MeshoptCompression.Default.decodeGltfBufferAsync(buffer, extension.count, extension.byteStride, extension.mode, extension.filter);\n });\n return bufferViewMeshopt._meshOptData;\n });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new EXT_meshopt_compression(loader));\n//# sourceMappingURL=EXT_meshopt_compression.js.map","import { GLTFLoader, ArrayItem } from \"../glTFLoader.js\";\nconst NAME = \"EXT_texture_webp\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Vendor/EXT_texture_webp/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class EXT_texture_webp {\n /**\n * @internal\n */\n constructor(loader) {\n /** The name of this extension. */\n this.name = NAME;\n this._loader = loader;\n this.enabled = loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n _loadTextureAsync(context, texture, assign) {\n return GLTFLoader.LoadExtensionAsync(context, texture, this.name, (extensionContext, extension) => {\n const sampler = texture.sampler == undefined ? GLTFLoader.DefaultSampler : ArrayItem.Get(`${context}/sampler`, this._loader.gltf.samplers, texture.sampler);\n const image = ArrayItem.Get(`${extensionContext}/source`, this._loader.gltf.images, extension.source);\n return this._loader._createTextureAsync(context, sampler, image, (babylonTexture) => {\n assign(babylonTexture);\n }, undefined, !texture._textureInfo.nonColorData);\n });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new EXT_texture_webp(loader));\n//# sourceMappingURL=EXT_texture_webp.js.map","import { DracoCompression } from \"@babylonjs/core/Meshes/Compression/dracoCompression.js\";\nimport { VertexBuffer } from \"@babylonjs/core/Buffers/buffer.js\";\nimport { Geometry } from \"@babylonjs/core/Meshes/geometry.js\";\nimport { GLTFLoader, ArrayItem } from \"../glTFLoader.js\";\nconst NAME = \"KHR_draco_mesh_compression\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_draco_mesh_compression/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_draco_mesh_compression {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n this._loader = loader;\n this.enabled = DracoCompression.DecoderAvailable && this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n delete this.dracoCompression;\n this._loader = null;\n }\n /**\n * @internal\n */\n _loadVertexDataAsync(context, primitive, babylonMesh) {\n return GLTFLoader.LoadExtensionAsync(context, primitive, this.name, (extensionContext, extension) => {\n if (primitive.mode != undefined) {\n if (primitive.mode !== 5 /* MeshPrimitiveMode.TRIANGLE_STRIP */ && primitive.mode !== 4 /* MeshPrimitiveMode.TRIANGLES */) {\n throw new Error(`${context}: Unsupported mode ${primitive.mode}`);\n }\n // TODO: handle triangle strips\n if (primitive.mode === 5 /* MeshPrimitiveMode.TRIANGLE_STRIP */) {\n throw new Error(`${context}: Mode ${primitive.mode} is not currently supported`);\n }\n }\n const attributes = {};\n const dividers = {};\n const loadAttribute = (name, kind) => {\n const uniqueId = extension.attributes[name];\n if (uniqueId === undefined || primitive.attributes[name] === undefined) {\n return;\n }\n attributes[kind] = uniqueId;\n const accessor = ArrayItem.Get(`${context}/attributes/${name}`, this._loader.gltf.accessors, primitive.attributes[name]);\n if (accessor.normalized && accessor.componentType !== 5126 /* AccessorComponentType.FLOAT */) {\n let divider = 1;\n switch (accessor.componentType) {\n case 5120 /* AccessorComponentType.BYTE */:\n divider = 127.0;\n break;\n case 5121 /* AccessorComponentType.UNSIGNED_BYTE */:\n divider = 255.0;\n break;\n case 5122 /* AccessorComponentType.SHORT */:\n divider = 32767.0;\n break;\n case 5123 /* AccessorComponentType.UNSIGNED_SHORT */:\n divider = 65535.0;\n break;\n }\n dividers[kind] = divider;\n }\n babylonMesh._delayInfo = babylonMesh._delayInfo || [];\n if (babylonMesh._delayInfo.indexOf(kind) === -1) {\n babylonMesh._delayInfo.push(kind);\n }\n };\n loadAttribute(\"POSITION\", VertexBuffer.PositionKind);\n loadAttribute(\"NORMAL\", VertexBuffer.NormalKind);\n loadAttribute(\"TANGENT\", VertexBuffer.TangentKind);\n loadAttribute(\"TEXCOORD_0\", VertexBuffer.UVKind);\n loadAttribute(\"TEXCOORD_1\", VertexBuffer.UV2Kind);\n loadAttribute(\"TEXCOORD_2\", VertexBuffer.UV3Kind);\n loadAttribute(\"TEXCOORD_3\", VertexBuffer.UV4Kind);\n loadAttribute(\"TEXCOORD_4\", VertexBuffer.UV5Kind);\n loadAttribute(\"TEXCOORD_5\", VertexBuffer.UV6Kind);\n loadAttribute(\"JOINTS_0\", VertexBuffer.MatricesIndicesKind);\n loadAttribute(\"WEIGHTS_0\", VertexBuffer.MatricesWeightsKind);\n loadAttribute(\"COLOR_0\", VertexBuffer.ColorKind);\n const bufferView = ArrayItem.Get(extensionContext, this._loader.gltf.bufferViews, extension.bufferView);\n if (!bufferView._dracoBabylonGeometry) {\n bufferView._dracoBabylonGeometry = this._loader.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView).then((data) => {\n const dracoCompression = this.dracoCompression || DracoCompression.Default;\n return dracoCompression\n .decodeMeshAsync(data, attributes, dividers)\n .then((babylonVertexData) => {\n const babylonGeometry = new Geometry(babylonMesh.name, this._loader.babylonScene);\n babylonVertexData.applyToGeometry(babylonGeometry);\n return babylonGeometry;\n })\n .catch((error) => {\n throw new Error(`${context}: ${error.message}`);\n });\n });\n }\n return bufferView._dracoBabylonGeometry;\n });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_draco_mesh_compression(loader));\n//# sourceMappingURL=KHR_draco_mesh_compression.js.map","import { Vector3 } from \"@babylonjs/core/Maths/math.vector.js\";\nimport { Color3 } from \"@babylonjs/core/Maths/math.color.js\";\nimport { DirectionalLight } from \"@babylonjs/core/Lights/directionalLight.js\";\nimport { PointLight } from \"@babylonjs/core/Lights/pointLight.js\";\nimport { SpotLight } from \"@babylonjs/core/Lights/spotLight.js\";\nimport { Light } from \"@babylonjs/core/Lights/light.js\";\nimport { GLTFLoader, ArrayItem } from \"../glTFLoader.js\";\nconst NAME = \"KHR_lights_punctual\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_lights_punctual/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_lights {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n delete this._lights;\n }\n /** @internal */\n onLoading() {\n const extensions = this._loader.gltf.extensions;\n if (extensions && extensions[this.name]) {\n const extension = extensions[this.name];\n this._lights = extension.lights;\n ArrayItem.Assign(this._lights);\n }\n }\n /**\n * @internal\n */\n loadNodeAsync(context, node, assign) {\n return GLTFLoader.LoadExtensionAsync(context, node, this.name, (extensionContext, extension) => {\n return this._loader.loadNodeAsync(context, node, (babylonMesh) => {\n let babylonLight;\n const light = ArrayItem.Get(extensionContext, this._lights, extension.light);\n const name = light.name || babylonMesh.name;\n this._loader.babylonScene._blockEntityCollection = !!this._loader._assetContainer;\n switch (light.type) {\n case \"directional\" /* KHRLightsPunctual_LightType.DIRECTIONAL */: {\n const babylonDirectionalLight = new DirectionalLight(name, Vector3.Backward(), this._loader.babylonScene);\n babylonDirectionalLight.position.setAll(0);\n babylonLight = babylonDirectionalLight;\n break;\n }\n case \"point\" /* KHRLightsPunctual_LightType.POINT */: {\n babylonLight = new PointLight(name, Vector3.Zero(), this._loader.babylonScene);\n break;\n }\n case \"spot\" /* KHRLightsPunctual_LightType.SPOT */: {\n const babylonSpotLight = new SpotLight(name, Vector3.Zero(), Vector3.Backward(), 0, 1, this._loader.babylonScene);\n babylonSpotLight.angle = ((light.spot && light.spot.outerConeAngle) || Math.PI / 4) * 2;\n babylonSpotLight.innerAngle = ((light.spot && light.spot.innerConeAngle) || 0) * 2;\n babylonLight = babylonSpotLight;\n break;\n }\n default: {\n this._loader.babylonScene._blockEntityCollection = false;\n throw new Error(`${extensionContext}: Invalid light type (${light.type})`);\n }\n }\n babylonLight._parentContainer = this._loader._assetContainer;\n this._loader.babylonScene._blockEntityCollection = false;\n light._babylonLight = babylonLight;\n babylonLight.falloffType = Light.FALLOFF_GLTF;\n babylonLight.diffuse = light.color ? Color3.FromArray(light.color) : Color3.White();\n babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;\n babylonLight.range = light.range == undefined ? Number.MAX_VALUE : light.range;\n babylonLight.parent = babylonMesh;\n this._loader._babylonLights.push(babylonLight);\n GLTFLoader.AddPointerMetadata(babylonLight, extensionContext);\n assign(babylonMesh);\n });\n });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_lights(loader));\n//# sourceMappingURL=KHR_lights_punctual.js.map","import { Color3 } from \"@babylonjs/core/Maths/math.color.js\";\nimport { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"KHR_materials_pbrSpecularGlossiness\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Archived/KHR_materials_pbrSpecularGlossiness/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_materials_pbrSpecularGlossiness {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 200;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => {\n const promises = new Array();\n promises.push(this._loader.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));\n this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial);\n return Promise.all(promises).then(() => { });\n });\n }\n _loadSpecularGlossinessPropertiesAsync(context, material, properties, babylonMaterial) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n const promises = new Array();\n babylonMaterial.metallic = null;\n babylonMaterial.roughness = null;\n if (properties.diffuseFactor) {\n babylonMaterial.albedoColor = Color3.FromArray(properties.diffuseFactor);\n babylonMaterial.alpha = properties.diffuseFactor[3];\n }\n else {\n babylonMaterial.albedoColor = Color3.White();\n }\n babylonMaterial.reflectivityColor = properties.specularFactor ? Color3.FromArray(properties.specularFactor) : Color3.White();\n babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;\n if (properties.diffuseTexture) {\n promises.push(this._loader.loadTextureInfoAsync(`${context}/diffuseTexture`, properties.diffuseTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Diffuse)`;\n babylonMaterial.albedoTexture = texture;\n }));\n }\n if (properties.specularGlossinessTexture) {\n promises.push(this._loader.loadTextureInfoAsync(`${context}/specularGlossinessTexture`, properties.specularGlossinessTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Specular Glossiness)`;\n babylonMaterial.reflectivityTexture = texture;\n babylonMaterial.reflectivityTexture.hasAlpha = true;\n }));\n babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;\n }\n return Promise.all(promises).then(() => { });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_materials_pbrSpecularGlossiness(loader));\n//# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map","import { Color3 } from \"@babylonjs/core/Maths/math.color.js\";\nimport { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"KHR_materials_unlit\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_unlit/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_materials_unlit {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 210;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtensionAsync(context, material, this.name, () => {\n return this._loadUnlitPropertiesAsync(context, material, babylonMaterial);\n });\n }\n _loadUnlitPropertiesAsync(context, material, babylonMaterial) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n const promises = new Array();\n babylonMaterial.unlit = true;\n const properties = material.pbrMetallicRoughness;\n if (properties) {\n if (properties.baseColorFactor) {\n babylonMaterial.albedoColor = Color3.FromArray(properties.baseColorFactor);\n babylonMaterial.alpha = properties.baseColorFactor[3];\n }\n else {\n babylonMaterial.albedoColor = Color3.White();\n }\n if (properties.baseColorTexture) {\n promises.push(this._loader.loadTextureInfoAsync(`${context}/baseColorTexture`, properties.baseColorTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Base Color)`;\n babylonMaterial.albedoTexture = texture;\n }));\n }\n }\n if (material.doubleSided) {\n babylonMaterial.backFaceCulling = false;\n babylonMaterial.twoSidedLighting = true;\n }\n this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial);\n return Promise.all(promises).then(() => { });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_materials_unlit(loader));\n//# sourceMappingURL=KHR_materials_unlit.js.map","import { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"KHR_materials_clearcoat\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_clearcoat/README.md)\n * [Playground Sample](https://www.babylonjs-playground.com/frame.html#7F7PN6#8)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_materials_clearcoat {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 190;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => {\n const promises = new Array();\n promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loadClearCoatPropertiesAsync(extensionContext, extension, babylonMaterial));\n return Promise.all(promises).then(() => { });\n });\n }\n _loadClearCoatPropertiesAsync(context, properties, babylonMaterial) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n const promises = new Array();\n babylonMaterial.clearCoat.isEnabled = true;\n babylonMaterial.clearCoat.useRoughnessFromMainTexture = false;\n babylonMaterial.clearCoat.remapF0OnInterfaceChange = false;\n if (properties.clearcoatFactor != undefined) {\n babylonMaterial.clearCoat.intensity = properties.clearcoatFactor;\n }\n else {\n babylonMaterial.clearCoat.intensity = 0;\n }\n if (properties.clearcoatTexture) {\n promises.push(this._loader.loadTextureInfoAsync(`${context}/clearcoatTexture`, properties.clearcoatTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (ClearCoat Intensity)`;\n babylonMaterial.clearCoat.texture = texture;\n }));\n }\n if (properties.clearcoatRoughnessFactor != undefined) {\n babylonMaterial.clearCoat.roughness = properties.clearcoatRoughnessFactor;\n }\n else {\n babylonMaterial.clearCoat.roughness = 0;\n }\n if (properties.clearcoatRoughnessTexture) {\n properties.clearcoatRoughnessTexture.nonColorData = true;\n promises.push(this._loader.loadTextureInfoAsync(`${context}/clearcoatRoughnessTexture`, properties.clearcoatRoughnessTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (ClearCoat Roughness)`;\n babylonMaterial.clearCoat.textureRoughness = texture;\n }));\n }\n if (properties.clearcoatNormalTexture) {\n properties.clearcoatNormalTexture.nonColorData = true;\n promises.push(this._loader.loadTextureInfoAsync(`${context}/clearcoatNormalTexture`, properties.clearcoatNormalTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (ClearCoat Normal)`;\n babylonMaterial.clearCoat.bumpTexture = texture;\n }));\n babylonMaterial.invertNormalMapX = !babylonMaterial.getScene().useRightHandedSystem;\n babylonMaterial.invertNormalMapY = babylonMaterial.getScene().useRightHandedSystem;\n if (properties.clearcoatNormalTexture.scale != undefined) {\n babylonMaterial.clearCoat.bumpTexture.level = properties.clearcoatNormalTexture.scale;\n }\n }\n return Promise.all(promises).then(() => { });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_materials_clearcoat(loader));\n//# sourceMappingURL=KHR_materials_clearcoat.js.map","import { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"KHR_materials_iridescence\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_iridescence/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_materials_iridescence {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 195;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => {\n const promises = new Array();\n promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loadIridescencePropertiesAsync(extensionContext, extension, babylonMaterial));\n return Promise.all(promises).then(() => { });\n });\n }\n _loadIridescencePropertiesAsync(context, properties, babylonMaterial) {\n var _a, _b, _c, _d, _e;\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n const promises = new Array();\n babylonMaterial.iridescence.isEnabled = true;\n babylonMaterial.iridescence.intensity = (_a = properties.iridescenceFactor) !== null && _a !== void 0 ? _a : 0;\n babylonMaterial.iridescence.indexOfRefraction = (_c = (_b = properties.iridescenceIor) !== null && _b !== void 0 ? _b : properties.iridescenceIOR) !== null && _c !== void 0 ? _c : 1.3;\n babylonMaterial.iridescence.minimumThickness = (_d = properties.iridescenceThicknessMinimum) !== null && _d !== void 0 ? _d : 100;\n babylonMaterial.iridescence.maximumThickness = (_e = properties.iridescenceThicknessMaximum) !== null && _e !== void 0 ? _e : 400;\n if (properties.iridescenceTexture) {\n promises.push(this._loader.loadTextureInfoAsync(`${context}/iridescenceTexture`, properties.iridescenceTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Iridescence Intensity)`;\n babylonMaterial.iridescence.texture = texture;\n }));\n }\n if (properties.iridescenceThicknessTexture) {\n promises.push(this._loader.loadTextureInfoAsync(`${context}/iridescenceThicknessTexture`, properties.iridescenceThicknessTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Iridescence Thickness)`;\n babylonMaterial.iridescence.thicknessTexture = texture;\n }));\n }\n return Promise.all(promises).then(() => { });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_materials_iridescence(loader));\n//# sourceMappingURL=KHR_materials_iridescence.js.map","import { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"KHR_materials_anisotropy\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_anisotropy)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_materials_anisotropy {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 195;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => {\n const promises = new Array();\n promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loadIridescencePropertiesAsync(extensionContext, extension, babylonMaterial));\n return Promise.all(promises).then(() => { });\n });\n }\n _loadIridescencePropertiesAsync(context, properties, babylonMaterial) {\n var _a, _b;\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n const promises = new Array();\n babylonMaterial.anisotropy.isEnabled = true;\n babylonMaterial.anisotropy.intensity = (_a = properties.anisotropyStrength) !== null && _a !== void 0 ? _a : 0;\n babylonMaterial.anisotropy.angle = (_b = properties.anisotropyRotation) !== null && _b !== void 0 ? _b : 0;\n if (properties.anisotropyTexture) {\n promises.push(this._loader.loadTextureInfoAsync(`${context}/anisotropyTexture`, properties.anisotropyTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Anisotropy Intensity)`;\n babylonMaterial.anisotropy.texture = texture;\n }));\n }\n return Promise.all(promises).then(() => { });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_materials_anisotropy(loader));\n//# sourceMappingURL=KHR_materials_anisotropy.js.map","import { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"KHR_materials_emissive_strength\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_emissive_strength/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_materials_emissive_strength {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 170;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => {\n return this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial).then(() => {\n this._loadEmissiveProperties(extensionContext, extension, babylonMaterial);\n });\n });\n }\n _loadEmissiveProperties(context, properties, babylonMaterial) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n if (properties.emissiveStrength !== undefined) {\n babylonMaterial.emissiveColor.scaleToRef(properties.emissiveStrength, babylonMaterial.emissiveColor);\n }\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_materials_emissive_strength(loader));\n//# sourceMappingURL=KHR_materials_emissive_strength.js.map","import { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nimport { Color3 } from \"@babylonjs/core/Maths/math.color.js\";\nconst NAME = \"KHR_materials_sheen\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_sheen/README.md)\n * [Playground Sample](https://www.babylonjs-playground.com/frame.html#BNIZX6#4)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_materials_sheen {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 190;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => {\n const promises = new Array();\n promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loadSheenPropertiesAsync(extensionContext, extension, babylonMaterial));\n return Promise.all(promises).then(() => { });\n });\n }\n _loadSheenPropertiesAsync(context, properties, babylonMaterial) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n const promises = new Array();\n babylonMaterial.sheen.isEnabled = true;\n babylonMaterial.sheen.intensity = 1;\n if (properties.sheenColorFactor != undefined) {\n babylonMaterial.sheen.color = Color3.FromArray(properties.sheenColorFactor);\n }\n else {\n babylonMaterial.sheen.color = Color3.Black();\n }\n if (properties.sheenColorTexture) {\n promises.push(this._loader.loadTextureInfoAsync(`${context}/sheenColorTexture`, properties.sheenColorTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Sheen Color)`;\n babylonMaterial.sheen.texture = texture;\n }));\n }\n if (properties.sheenRoughnessFactor !== undefined) {\n babylonMaterial.sheen.roughness = properties.sheenRoughnessFactor;\n }\n else {\n babylonMaterial.sheen.roughness = 0;\n }\n if (properties.sheenRoughnessTexture) {\n properties.sheenRoughnessTexture.nonColorData = true;\n promises.push(this._loader.loadTextureInfoAsync(`${context}/sheenRoughnessTexture`, properties.sheenRoughnessTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Sheen Roughness)`;\n babylonMaterial.sheen.textureRoughness = texture;\n }));\n }\n babylonMaterial.sheen.albedoScaling = true;\n babylonMaterial.sheen.useRoughnessFromMainTexture = false;\n return Promise.all(promises).then(() => { });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_materials_sheen(loader));\n//# sourceMappingURL=KHR_materials_sheen.js.map","import { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nimport { Color3 } from \"@babylonjs/core/Maths/math.color.js\";\nconst NAME = \"KHR_materials_specular\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_specular/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_materials_specular {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 190;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => {\n const promises = new Array();\n promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loadSpecularPropertiesAsync(extensionContext, extension, babylonMaterial));\n return Promise.all(promises).then(() => { });\n });\n }\n _loadSpecularPropertiesAsync(context, properties, babylonMaterial) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n const promises = new Array();\n if (properties.specularFactor !== undefined) {\n babylonMaterial.metallicF0Factor = properties.specularFactor;\n }\n if (properties.specularColorFactor !== undefined) {\n babylonMaterial.metallicReflectanceColor = Color3.FromArray(properties.specularColorFactor);\n }\n if (properties.specularTexture) {\n properties.specularTexture.nonColorData = true;\n promises.push(this._loader.loadTextureInfoAsync(`${context}/specularTexture`, properties.specularTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Specular F0 Strength)`;\n babylonMaterial.metallicReflectanceTexture = texture;\n babylonMaterial.useOnlyMetallicFromMetallicReflectanceTexture = true;\n }));\n }\n if (properties.specularColorTexture) {\n promises.push(this._loader.loadTextureInfoAsync(`${context}/specularColorTexture`, properties.specularColorTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Specular F0 Color)`;\n babylonMaterial.reflectanceTexture = texture;\n }));\n }\n return Promise.all(promises).then(() => { });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_materials_specular(loader));\n//# sourceMappingURL=KHR_materials_specular.js.map","import { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"KHR_materials_ior\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_ior/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_materials_ior {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 180;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => {\n const promises = new Array();\n promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loadIorPropertiesAsync(extensionContext, extension, babylonMaterial));\n return Promise.all(promises).then(() => { });\n });\n }\n _loadIorPropertiesAsync(context, properties, babylonMaterial) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n if (properties.ior !== undefined) {\n babylonMaterial.indexOfRefraction = properties.ior;\n }\n else {\n babylonMaterial.indexOfRefraction = KHR_materials_ior._DEFAULT_IOR;\n }\n return Promise.resolve();\n }\n}\n/**\n * Default ior Value from the spec.\n */\nKHR_materials_ior._DEFAULT_IOR = 1.5;\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_materials_ior(loader));\n//# sourceMappingURL=KHR_materials_ior.js.map","import { GLTFLoader, ArrayItem } from \"../glTFLoader.js\";\nimport { Mesh } from \"@babylonjs/core/Meshes/mesh.js\";\nconst NAME = \"KHR_materials_variants\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_variants/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_materials_variants {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * Gets the list of available variant names for this asset.\n * @param rootMesh The glTF root mesh\n * @returns the list of all the variant names for this model\n */\n static GetAvailableVariants(rootMesh) {\n const extensionMetadata = this._GetExtensionMetadata(rootMesh);\n if (!extensionMetadata) {\n return [];\n }\n return Object.keys(extensionMetadata.variants);\n }\n /**\n * Gets the list of available variant names for this asset.\n * @param rootMesh The glTF root mesh\n * @returns the list of all the variant names for this model\n */\n getAvailableVariants(rootMesh) {\n return KHR_materials_variants.GetAvailableVariants(rootMesh);\n }\n /**\n * Select a variant given a variant name or a list of variant names.\n * @param rootMesh The glTF root mesh\n * @param variantName The variant name(s) to select.\n */\n static SelectVariant(rootMesh, variantName) {\n const extensionMetadata = this._GetExtensionMetadata(rootMesh);\n if (!extensionMetadata) {\n throw new Error(`Cannot select variant on a glTF mesh that does not have the ${NAME} extension`);\n }\n const select = (variantName) => {\n const entries = extensionMetadata.variants[variantName];\n if (entries) {\n for (const entry of entries) {\n entry.mesh.material = entry.material;\n }\n }\n };\n if (variantName instanceof Array) {\n for (const name of variantName) {\n select(name);\n }\n }\n else {\n select(variantName);\n }\n extensionMetadata.lastSelected = variantName;\n }\n /**\n * Select a variant given a variant name or a list of variant names.\n * @param rootMesh The glTF root mesh\n * @param variantName The variant name(s) to select.\n */\n selectVariant(rootMesh, variantName) {\n return KHR_materials_variants.SelectVariant(rootMesh, variantName);\n }\n /**\n * Reset back to the original before selecting a variant.\n * @param rootMesh The glTF root mesh\n */\n static Reset(rootMesh) {\n const extensionMetadata = this._GetExtensionMetadata(rootMesh);\n if (!extensionMetadata) {\n throw new Error(`Cannot reset on a glTF mesh that does not have the ${NAME} extension`);\n }\n for (const entry of extensionMetadata.original) {\n entry.mesh.material = entry.material;\n }\n extensionMetadata.lastSelected = null;\n }\n /**\n * Reset back to the original before selecting a variant.\n * @param rootMesh The glTF root mesh\n */\n reset(rootMesh) {\n return KHR_materials_variants.Reset(rootMesh);\n }\n /**\n * Gets the last selected variant name(s) or null if original.\n * @param rootMesh The glTF root mesh\n * @returns The selected variant name(s).\n */\n static GetLastSelectedVariant(rootMesh) {\n const extensionMetadata = this._GetExtensionMetadata(rootMesh);\n if (!extensionMetadata) {\n throw new Error(`Cannot get the last selected variant on a glTF mesh that does not have the ${NAME} extension`);\n }\n return extensionMetadata.lastSelected;\n }\n /**\n * Gets the last selected variant name(s) or null if original.\n * @param rootMesh The glTF root mesh\n * @returns The selected variant name(s).\n */\n getLastSelectedVariant(rootMesh) {\n return KHR_materials_variants.GetLastSelectedVariant(rootMesh);\n }\n static _GetExtensionMetadata(rootMesh) {\n var _a, _b;\n return ((_b = (_a = rootMesh === null || rootMesh === void 0 ? void 0 : rootMesh._internalMetadata) === null || _a === void 0 ? void 0 : _a.gltf) === null || _b === void 0 ? void 0 : _b[NAME]) || null;\n }\n /** @internal */\n onLoading() {\n const extensions = this._loader.gltf.extensions;\n if (extensions && extensions[this.name]) {\n const extension = extensions[this.name];\n this._variants = extension.variants;\n }\n }\n /**\n * @internal\n */\n _loadMeshPrimitiveAsync(context, name, node, mesh, primitive, assign) {\n return GLTFLoader.LoadExtensionAsync(context, primitive, this.name, (extensionContext, extension) => {\n const promises = new Array();\n promises.push(this._loader._loadMeshPrimitiveAsync(context, name, node, mesh, primitive, (babylonMesh) => {\n assign(babylonMesh);\n if (babylonMesh instanceof Mesh) {\n const babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);\n const root = this._loader.rootBabylonMesh;\n const metadata = root ? (root._internalMetadata = root._internalMetadata || {}) : {};\n const gltf = (metadata.gltf = metadata.gltf || {});\n const extensionMetadata = (gltf[NAME] = gltf[NAME] || { lastSelected: null, original: [], variants: {} });\n // Store the original material.\n extensionMetadata.original.push({ mesh: babylonMesh, material: babylonMesh.material });\n // For each mapping, look at the variants and make a new entry for them.\n for (let mappingIndex = 0; mappingIndex < extension.mappings.length; ++mappingIndex) {\n const mapping = extension.mappings[mappingIndex];\n const material = ArrayItem.Get(`${extensionContext}/mappings/${mappingIndex}/material`, this._loader.gltf.materials, mapping.material);\n promises.push(this._loader._loadMaterialAsync(`#/materials/${mapping.material}`, material, babylonMesh, babylonDrawMode, (babylonMaterial) => {\n for (let mappingVariantIndex = 0; mappingVariantIndex < mapping.variants.length; ++mappingVariantIndex) {\n const variantIndex = mapping.variants[mappingVariantIndex];\n const variant = ArrayItem.Get(`/extensions/${NAME}/variants/${variantIndex}`, this._variants, variantIndex);\n extensionMetadata.variants[variant.name] = extensionMetadata.variants[variant.name] || [];\n extensionMetadata.variants[variant.name].push({\n mesh: babylonMesh,\n material: babylonMaterial,\n });\n // Replace the target when original mesh is cloned\n babylonMesh.onClonedObservable.add((newOne) => {\n const newMesh = newOne;\n let metadata = null;\n let newRoot = newMesh;\n // Find root to get medata\n do {\n newRoot = newRoot.parent;\n if (!newRoot) {\n return;\n }\n metadata = KHR_materials_variants._GetExtensionMetadata(newRoot);\n } while (metadata === null);\n // Need to clone the metadata on the root (first time only)\n if (root && metadata === KHR_materials_variants._GetExtensionMetadata(root)) {\n // Copy main metadata\n newRoot._internalMetadata = {};\n for (const key in root._internalMetadata) {\n newRoot._internalMetadata[key] = root._internalMetadata[key];\n }\n // Copy the gltf metadata\n newRoot._internalMetadata.gltf = [];\n for (const key in root._internalMetadata.gltf) {\n newRoot._internalMetadata.gltf[key] = root._internalMetadata.gltf[key];\n }\n // Duplicate the extension specific metadata\n newRoot._internalMetadata.gltf[NAME] = { lastSelected: null, original: [], variants: {} };\n for (const original of metadata.original) {\n newRoot._internalMetadata.gltf[NAME].original.push({\n mesh: original.mesh,\n material: original.material,\n });\n }\n for (const key in metadata.variants) {\n if (Object.prototype.hasOwnProperty.call(metadata.variants, key)) {\n newRoot._internalMetadata.gltf[NAME].variants[key] = [];\n for (const variantEntry of metadata.variants[key]) {\n newRoot._internalMetadata.gltf[NAME].variants[key].push({\n mesh: variantEntry.mesh,\n material: variantEntry.material,\n });\n }\n }\n }\n metadata = newRoot._internalMetadata.gltf[NAME];\n }\n // Relocate\n for (const target of metadata.original) {\n if (target.mesh === babylonMesh) {\n target.mesh = newMesh;\n }\n }\n for (const target of metadata.variants[variant.name]) {\n if (target.mesh === babylonMesh) {\n target.mesh = newMesh;\n }\n }\n });\n }\n }));\n }\n }\n }));\n return Promise.all(promises).then(([babylonMesh]) => {\n return babylonMesh;\n });\n });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_materials_variants(loader));\n//# sourceMappingURL=KHR_materials_variants.js.map","import { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nimport { RenderTargetTexture } from \"@babylonjs/core/Materials/Textures/renderTargetTexture.js\";\nimport { Observable } from \"@babylonjs/core/Misc/observable.js\";\nimport { Constants } from \"@babylonjs/core/Engines/constants.js\";\nimport { Tools } from \"@babylonjs/core/Misc/tools.js\";\n/**\n * A class to handle setting up the rendering of opaque objects to be shown through transmissive objects.\n */\nclass TransmissionHelper {\n /**\n * Creates the default options for the helper.\n */\n static _GetDefaultOptions() {\n return {\n renderSize: 1024,\n samples: 4,\n lodGenerationScale: 1,\n lodGenerationOffset: -4,\n renderTargetTextureType: Constants.TEXTURETYPE_HALF_FLOAT,\n generateMipmaps: true,\n };\n }\n /**\n * constructor\n * @param options Defines the options we want to customize the helper\n * @param scene The scene to add the material to\n */\n constructor(options, scene) {\n this._opaqueRenderTarget = null;\n this._opaqueMeshesCache = [];\n this._transparentMeshesCache = [];\n this._materialObservers = {};\n this._options = {\n ...TransmissionHelper._GetDefaultOptions(),\n ...options,\n };\n this._scene = scene;\n this._scene._transmissionHelper = this;\n this.onErrorObservable = new Observable();\n this._scene.onDisposeObservable.addOnce(() => {\n this.dispose();\n });\n this._parseScene();\n this._setupRenderTargets();\n }\n /**\n * Updates the background according to the new options\n * @param options\n */\n updateOptions(options) {\n // First check if any options are actually being changed. If not, exit.\n const newValues = Object.keys(options).filter((key) => this._options[key] !== options[key]);\n if (!newValues.length) {\n return;\n }\n const newOptions = {\n ...this._options,\n ...options,\n };\n const oldOptions = this._options;\n this._options = newOptions;\n // If size changes, recreate everything\n if (newOptions.renderSize !== oldOptions.renderSize ||\n newOptions.renderTargetTextureType !== oldOptions.renderTargetTextureType ||\n newOptions.generateMipmaps !== oldOptions.generateMipmaps ||\n !this._opaqueRenderTarget) {\n this._setupRenderTargets();\n }\n else {\n this._opaqueRenderTarget.samples = newOptions.samples;\n this._opaqueRenderTarget.lodGenerationScale = newOptions.lodGenerationScale;\n this._opaqueRenderTarget.lodGenerationOffset = newOptions.lodGenerationOffset;\n }\n }\n /**\n * Gets the opaque render target texture or null if not available.\n */\n getOpaqueTarget() {\n return this._opaqueRenderTarget;\n }\n _shouldRenderAsTransmission(material) {\n if (!material) {\n return false;\n }\n if (material instanceof PBRMaterial && material.subSurface.isRefractionEnabled) {\n return true;\n }\n return false;\n }\n _addMesh(mesh) {\n this._materialObservers[mesh.uniqueId] = mesh.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this));\n // we need to defer the processing because _addMesh may be called as part as an instance mesh creation, in which case some\n // internal properties are not setup yet, like _sourceMesh (needed when doing mesh.material below)\n Tools.SetImmediate(() => {\n if (this._shouldRenderAsTransmission(mesh.material)) {\n mesh.material.refractionTexture = this._opaqueRenderTarget;\n if (this._transparentMeshesCache.indexOf(mesh) === -1) {\n this._transparentMeshesCache.push(mesh);\n }\n }\n else {\n if (this._opaqueMeshesCache.indexOf(mesh) === -1) {\n this._opaqueMeshesCache.push(mesh);\n }\n }\n });\n }\n _removeMesh(mesh) {\n mesh.onMaterialChangedObservable.remove(this._materialObservers[mesh.uniqueId]);\n delete this._materialObservers[mesh.uniqueId];\n let idx = this._transparentMeshesCache.indexOf(mesh);\n if (idx !== -1) {\n this._transparentMeshesCache.splice(idx, 1);\n }\n idx = this._opaqueMeshesCache.indexOf(mesh);\n if (idx !== -1) {\n this._opaqueMeshesCache.splice(idx, 1);\n }\n }\n _parseScene() {\n this._scene.meshes.forEach(this._addMesh.bind(this));\n // Listen for when a mesh is added to the scene and add it to our cache lists.\n this._scene.onNewMeshAddedObservable.add(this._addMesh.bind(this));\n // Listen for when a mesh is removed from to the scene and remove it from our cache lists.\n this._scene.onMeshRemovedObservable.add(this._removeMesh.bind(this));\n }\n // When one of the meshes in the scene has its material changed, make sure that it's in the correct cache list.\n _onMeshMaterialChanged(mesh) {\n const transparentIdx = this._transparentMeshesCache.indexOf(mesh);\n const opaqueIdx = this._opaqueMeshesCache.indexOf(mesh);\n // If the material is transparent, make sure that it's added to the transparent list and removed from the opaque list\n const useTransmission = this._shouldRenderAsTransmission(mesh.material);\n if (useTransmission) {\n if (mesh.material instanceof PBRMaterial) {\n mesh.material.subSurface.refractionTexture = this._opaqueRenderTarget;\n }\n if (opaqueIdx !== -1) {\n this._opaqueMeshesCache.splice(opaqueIdx, 1);\n this._transparentMeshesCache.push(mesh);\n }\n else if (transparentIdx === -1) {\n this._transparentMeshesCache.push(mesh);\n }\n // If the material is opaque, make sure that it's added to the opaque list and removed from the transparent list\n }\n else {\n if (transparentIdx !== -1) {\n this._transparentMeshesCache.splice(transparentIdx, 1);\n this._opaqueMeshesCache.push(mesh);\n }\n else if (opaqueIdx === -1) {\n this._opaqueMeshesCache.push(mesh);\n }\n }\n }\n /**\n * Setup the render targets according to the specified options.\n */\n _setupRenderTargets() {\n var _a, _b;\n if (this._opaqueRenderTarget) {\n this._opaqueRenderTarget.dispose();\n }\n this._opaqueRenderTarget = new RenderTargetTexture(\"opaqueSceneTexture\", this._options.renderSize, this._scene, this._options.generateMipmaps, undefined, this._options.renderTargetTextureType);\n this._opaqueRenderTarget.ignoreCameraViewport = true;\n this._opaqueRenderTarget.renderList = this._opaqueMeshesCache;\n this._opaqueRenderTarget.clearColor = (_b = (_a = this._options.clearColor) === null || _a === void 0 ? void 0 : _a.clone()) !== null && _b !== void 0 ? _b : this._scene.clearColor.clone();\n this._opaqueRenderTarget.gammaSpace = false;\n this._opaqueRenderTarget.lodGenerationScale = this._options.lodGenerationScale;\n this._opaqueRenderTarget.lodGenerationOffset = this._options.lodGenerationOffset;\n this._opaqueRenderTarget.samples = this._options.samples;\n let sceneImageProcessingapplyByPostProcess;\n let saveSceneEnvIntensity;\n this._opaqueRenderTarget.onBeforeBindObservable.add((opaqueRenderTarget) => {\n saveSceneEnvIntensity = this._scene.environmentIntensity;\n this._scene.environmentIntensity = 1.0;\n sceneImageProcessingapplyByPostProcess = this._scene.imageProcessingConfiguration.applyByPostProcess;\n if (!this._options.clearColor) {\n this._scene.clearColor.toLinearSpaceToRef(opaqueRenderTarget.clearColor, this._scene.getEngine().useExactSrgbConversions);\n }\n else {\n opaqueRenderTarget.clearColor.copyFrom(this._options.clearColor);\n }\n // we do not use the applyByPostProcess setter to avoid flagging all the materials as \"image processing dirty\"!\n this._scene.imageProcessingConfiguration._applyByPostProcess = true;\n });\n this._opaqueRenderTarget.onAfterUnbindObservable.add(() => {\n this._scene.environmentIntensity = saveSceneEnvIntensity;\n this._scene.imageProcessingConfiguration._applyByPostProcess = sceneImageProcessingapplyByPostProcess;\n });\n this._transparentMeshesCache.forEach((mesh) => {\n if (this._shouldRenderAsTransmission(mesh.material)) {\n mesh.material.refractionTexture = this._opaqueRenderTarget;\n }\n });\n }\n /**\n * Dispose all the elements created by the Helper.\n */\n dispose() {\n this._scene._transmissionHelper = undefined;\n if (this._opaqueRenderTarget) {\n this._opaqueRenderTarget.dispose();\n this._opaqueRenderTarget = null;\n }\n this._transparentMeshesCache = [];\n this._opaqueMeshesCache = [];\n }\n}\nconst NAME = \"KHR_materials_transmission\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_transmission/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_materials_transmission {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 175;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n if (this.enabled) {\n loader.parent.transparencyAsCoverage = true;\n }\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => {\n const promises = new Array();\n promises.push(this._loader.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loadTransparentPropertiesAsync(extensionContext, material, babylonMaterial, extension));\n return Promise.all(promises).then(() => { });\n });\n }\n _loadTransparentPropertiesAsync(context, material, babylonMaterial, extension) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n const pbrMaterial = babylonMaterial;\n // Enables \"refraction\" texture which represents transmitted light.\n pbrMaterial.subSurface.isRefractionEnabled = true;\n // Since this extension models thin-surface transmission only, we must make IOR = 1.0\n pbrMaterial.subSurface.volumeIndexOfRefraction = 1.0;\n // Albedo colour will tint transmission.\n pbrMaterial.subSurface.useAlbedoToTintRefraction = true;\n if (extension.transmissionFactor !== undefined) {\n pbrMaterial.subSurface.refractionIntensity = extension.transmissionFactor;\n const scene = pbrMaterial.getScene();\n if (pbrMaterial.subSurface.refractionIntensity && !scene._transmissionHelper) {\n new TransmissionHelper({}, pbrMaterial.getScene());\n }\n }\n else {\n pbrMaterial.subSurface.refractionIntensity = 0.0;\n pbrMaterial.subSurface.isRefractionEnabled = false;\n return Promise.resolve();\n }\n pbrMaterial.subSurface.minimumThickness = 0.0;\n pbrMaterial.subSurface.maximumThickness = 0.0;\n if (extension.transmissionTexture) {\n extension.transmissionTexture.nonColorData = true;\n return this._loader.loadTextureInfoAsync(`${context}/transmissionTexture`, extension.transmissionTexture, undefined).then((texture) => {\n pbrMaterial.subSurface.refractionIntensityTexture = texture;\n pbrMaterial.subSurface.useGltfStyleTextures = true;\n });\n }\n else {\n return Promise.resolve();\n }\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_materials_transmission(loader));\n//# sourceMappingURL=KHR_materials_transmission.js.map","import { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"KHR_materials_translucency\";\n/**\n * [Proposed Specification](https://github.com/KhronosGroup/glTF/pull/1825)\n * !!! Experimental Extension Subject to Changes !!!\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_materials_translucency {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 174;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n if (this.enabled) {\n loader.parent.transparencyAsCoverage = true;\n }\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => {\n const promises = new Array();\n promises.push(this._loader.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loadTranslucentPropertiesAsync(extensionContext, material, babylonMaterial, extension));\n return Promise.all(promises).then(() => { });\n });\n }\n _loadTranslucentPropertiesAsync(context, material, babylonMaterial, extension) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n const pbrMaterial = babylonMaterial;\n // Enables \"translucency\" texture which represents diffusely-transmitted light.\n pbrMaterial.subSurface.isTranslucencyEnabled = true;\n // Since this extension models thin-surface transmission only, we must make the\n // internal IOR == 1.0 and set the thickness to 0.\n pbrMaterial.subSurface.volumeIndexOfRefraction = 1.0;\n pbrMaterial.subSurface.minimumThickness = 0.0;\n pbrMaterial.subSurface.maximumThickness = 0.0;\n // Albedo colour will tint transmission.\n pbrMaterial.subSurface.useAlbedoToTintTranslucency = true;\n if (extension.translucencyFactor !== undefined) {\n pbrMaterial.subSurface.translucencyIntensity = extension.translucencyFactor;\n }\n else {\n pbrMaterial.subSurface.translucencyIntensity = 0.0;\n pbrMaterial.subSurface.isTranslucencyEnabled = false;\n return Promise.resolve();\n }\n if (extension.translucencyTexture) {\n extension.translucencyTexture.nonColorData = true;\n return this._loader.loadTextureInfoAsync(`${context}/translucencyTexture`, extension.translucencyTexture).then((texture) => {\n pbrMaterial.subSurface.translucencyIntensityTexture = texture;\n });\n }\n else {\n return Promise.resolve();\n }\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_materials_translucency(loader));\n//# sourceMappingURL=KHR_materials_translucency.js.map","import { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"KHR_materials_volume\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_volume/README.md)\n * @since 5.0.0\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_materials_volume {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 173;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n if (this.enabled) {\n // We need to disable instance usage because the attenuation factor depends on the node scale of each individual mesh\n this._loader._disableInstancedMesh++;\n }\n }\n /** @internal */\n dispose() {\n if (this.enabled) {\n this._loader._disableInstancedMesh--;\n }\n this._loader = null;\n }\n /**\n * @internal\n */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => {\n const promises = new Array();\n promises.push(this._loader.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loadVolumePropertiesAsync(extensionContext, material, babylonMaterial, extension));\n return Promise.all(promises).then(() => { });\n });\n }\n _loadVolumePropertiesAsync(context, material, babylonMaterial, extension) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n // If transparency isn't enabled already, this extension shouldn't do anything.\n // i.e. it requires either the KHR_materials_transmission or KHR_materials_translucency extensions.\n if ((!babylonMaterial.subSurface.isRefractionEnabled && !babylonMaterial.subSurface.isTranslucencyEnabled) || !extension.thicknessFactor) {\n return Promise.resolve();\n }\n // IOR in this extension only affects interior.\n babylonMaterial.subSurface.volumeIndexOfRefraction = babylonMaterial.indexOfRefraction;\n const attenuationDistance = extension.attenuationDistance !== undefined ? extension.attenuationDistance : Number.MAX_VALUE;\n babylonMaterial.subSurface.tintColorAtDistance = attenuationDistance;\n if (extension.attenuationColor !== undefined && extension.attenuationColor.length == 3) {\n babylonMaterial.subSurface.tintColor.copyFromFloats(extension.attenuationColor[0], extension.attenuationColor[1], extension.attenuationColor[2]);\n }\n babylonMaterial.subSurface.minimumThickness = 0.0;\n babylonMaterial.subSurface.maximumThickness = extension.thicknessFactor;\n babylonMaterial.subSurface.useThicknessAsDepth = true;\n if (extension.thicknessTexture) {\n extension.thicknessTexture.nonColorData = true;\n return this._loader.loadTextureInfoAsync(`${context}/thicknessTexture`, extension.thicknessTexture).then((texture) => {\n babylonMaterial.subSurface.thicknessTexture = texture;\n babylonMaterial.subSurface.useGltfStyleTextures = true;\n });\n }\n else {\n return Promise.resolve();\n }\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_materials_volume(loader));\n//# sourceMappingURL=KHR_materials_volume.js.map","import { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"KHR_mesh_quantization\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_mesh_quantization/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_mesh_quantization {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n this.enabled = loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() { }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_mesh_quantization(loader));\n//# sourceMappingURL=KHR_mesh_quantization.js.map","import { GLTFLoader, ArrayItem } from \"../glTFLoader.js\";\nconst NAME = \"KHR_texture_basisu\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_texture_basisu/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_texture_basisu {\n /**\n * @internal\n */\n constructor(loader) {\n /** The name of this extension. */\n this.name = NAME;\n this._loader = loader;\n this.enabled = loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n _loadTextureAsync(context, texture, assign) {\n return GLTFLoader.LoadExtensionAsync(context, texture, this.name, (extensionContext, extension) => {\n const sampler = texture.sampler == undefined ? GLTFLoader.DefaultSampler : ArrayItem.Get(`${context}/sampler`, this._loader.gltf.samplers, texture.sampler);\n const image = ArrayItem.Get(`${extensionContext}/source`, this._loader.gltf.images, extension.source);\n return this._loader._createTextureAsync(context, sampler, image, (babylonTexture) => {\n assign(babylonTexture);\n }, texture._textureInfo.nonColorData ? { useRGBAIfASTCBC7NotAvailableWhenUASTC: true } : undefined, !texture._textureInfo.nonColorData);\n });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_texture_basisu(loader));\n//# sourceMappingURL=KHR_texture_basisu.js.map","import { Texture } from \"@babylonjs/core/Materials/Textures/texture.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"KHR_texture_transform\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_texture_transform/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_texture_transform {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadTextureInfoAsync(context, textureInfo, assign) {\n return GLTFLoader.LoadExtensionAsync(context, textureInfo, this.name, (extensionContext, extension) => {\n return this._loader.loadTextureInfoAsync(context, textureInfo, (babylonTexture) => {\n if (!(babylonTexture instanceof Texture)) {\n throw new Error(`${extensionContext}: Texture type not supported`);\n }\n if (extension.offset) {\n babylonTexture.uOffset = extension.offset[0];\n babylonTexture.vOffset = extension.offset[1];\n }\n // Always rotate around the origin.\n babylonTexture.uRotationCenter = 0;\n babylonTexture.vRotationCenter = 0;\n if (extension.rotation) {\n babylonTexture.wAng = -extension.rotation;\n }\n if (extension.scale) {\n babylonTexture.uScale = extension.scale[0];\n babylonTexture.vScale = extension.scale[1];\n }\n if (extension.texCoord != undefined) {\n babylonTexture.coordinatesIndex = extension.texCoord;\n }\n assign(babylonTexture);\n });\n });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_texture_transform(loader));\n//# sourceMappingURL=KHR_texture_transform.js.map","import { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"KHR_xmp_json_ld\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_xmp_json_ld/README.md)\n * @since 5.0.0\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_xmp_json_ld {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 100;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * Called after the loader state changes to LOADING.\n */\n onLoading() {\n var _a, _b, _c;\n if (this._loader.rootBabylonMesh === null) {\n return;\n }\n const xmp_gltf = (_a = this._loader.gltf.extensions) === null || _a === void 0 ? void 0 : _a.KHR_xmp_json_ld;\n const xmp_node = (_c = (_b = this._loader.gltf.asset) === null || _b === void 0 ? void 0 : _b.extensions) === null || _c === void 0 ? void 0 : _c.KHR_xmp_json_ld;\n if (xmp_gltf && xmp_node) {\n const packet = +xmp_node.packet;\n if (xmp_gltf.packets && packet < xmp_gltf.packets.length) {\n this._loader.rootBabylonMesh.metadata = this._loader.rootBabylonMesh.metadata || {};\n this._loader.rootBabylonMesh.metadata.xmp = xmp_gltf.packets[packet];\n }\n }\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_xmp_json_ld(loader));\n//# sourceMappingURL=KHR_xmp_json_ld.js.map","/* eslint-disable @typescript-eslint/naming-convention */\nimport { Animation } from \"@babylonjs/core/Animations/animation.js\";\nimport { AnimationPropertyInfo, nodeAnimationData } from \"../glTFLoaderAnimation.js\";\nimport { Color3 } from \"@babylonjs/core/Maths/math.color.js\";\nfunction getColor3(_target, source, offset, scale) {\n return Color3.FromArray(source, offset).scale(scale);\n}\nfunction getAlpha(_target, source, offset, scale) {\n return source[offset + 3] * scale;\n}\nfunction getFloat(_target, source, offset, scale) {\n return source[offset] * scale;\n}\nfunction getMinusFloat(_target, source, offset, scale) {\n return -source[offset] * scale;\n}\nfunction getNextFloat(_target, source, offset, scale) {\n return source[offset + 1] * scale;\n}\nfunction getFloatBy2(_target, source, offset, scale) {\n return source[offset] * scale * 2;\n}\nfunction getTextureTransformTree(textureName) {\n return {\n scale: [\n new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, `${textureName}.uScale`, getFloat, () => 2),\n new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, `${textureName}.vScale`, getNextFloat, () => 2),\n ],\n offset: [\n new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, `${textureName}.uOffset`, getFloat, () => 2),\n new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, `${textureName}.vOffset`, getNextFloat, () => 2),\n ],\n rotation: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, `${textureName}.wAng`, getMinusFloat, () => 1)],\n };\n}\nclass CameraAnimationPropertyInfo extends AnimationPropertyInfo {\n /** @internal */\n buildAnimations(target, name, fps, keys, callback) {\n callback(target._babylonCamera, this._buildAnimation(name, fps, keys));\n }\n}\nclass MaterialAnimationPropertyInfo extends AnimationPropertyInfo {\n /** @internal */\n buildAnimations(target, name, fps, keys, callback) {\n for (const fillMode in target._data) {\n callback(target._data[fillMode].babylonMaterial, this._buildAnimation(name, fps, keys));\n }\n }\n}\nclass LightAnimationPropertyInfo extends AnimationPropertyInfo {\n /** @internal */\n buildAnimations(target, name, fps, keys, callback) {\n callback(target._babylonLight, this._buildAnimation(name, fps, keys));\n }\n}\nconst nodesTree = {\n __array__: {\n __target__: true,\n ...nodeAnimationData,\n },\n};\nconst camerasTree = {\n __array__: {\n __target__: true,\n orthographic: {\n xmag: [\n new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"orthoLeft\", getMinusFloat, () => 1),\n new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"orthoRight\", getNextFloat, () => 1),\n ],\n ymag: [\n new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"orthoBottom\", getMinusFloat, () => 1),\n new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"orthoTop\", getNextFloat, () => 1),\n ],\n zfar: [new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"maxZ\", getFloat, () => 1)],\n znear: [new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"minZ\", getFloat, () => 1)],\n },\n perspective: {\n yfov: [new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"fov\", getFloat, () => 1)],\n zfar: [new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"maxZ\", getFloat, () => 1)],\n znear: [new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"minZ\", getFloat, () => 1)],\n },\n },\n};\nconst materialsTree = {\n __array__: {\n __target__: true,\n pbrMetallicRoughness: {\n baseColorFactor: [\n new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_COLOR3, \"albedoColor\", getColor3, () => 4),\n new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"alpha\", getAlpha, () => 4),\n ],\n metallicFactor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"metallic\", getFloat, () => 1)],\n roughnessFactor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"roughness\", getFloat, () => 1)],\n baseColorTexture: {\n extensions: {\n KHR_texture_transform: getTextureTransformTree(\"albedoTexture\"),\n },\n },\n },\n emissiveFactor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_COLOR3, \"emissiveColor\", getColor3, () => 3)],\n normalTexture: {\n scale: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"bumpTexture.level\", getFloat, () => 1)],\n },\n occlusionTexture: {\n strength: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"ambientTextureStrength\", getFloat, () => 1)],\n extensions: {\n KHR_texture_transform: getTextureTransformTree(\"ambientTexture\"),\n },\n },\n emissiveTexture: {\n extensions: {\n KHR_texture_transform: getTextureTransformTree(\"emissiveTexture\"),\n },\n },\n extensions: {\n KHR_materials_ior: {\n ior: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"indexOfRefraction\", getFloat, () => 1)],\n },\n KHR_materials_clearcoat: {\n clearcoatFactor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"clearCoat.intensity\", getFloat, () => 1)],\n clearcoatRoughnessFactor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"clearCoat.roughness\", getFloat, () => 1)],\n },\n KHR_materials_sheen: {\n sheenColorFactor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_COLOR3, \"sheen.color\", getColor3, () => 3)],\n sheenRoughnessFactor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"sheen.roughness\", getFloat, () => 1)],\n },\n KHR_materials_specular: {\n specularFactor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"metallicF0Factor\", getFloat, () => 1)],\n specularColorFactor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_COLOR3, \"metallicReflectanceColor\", getColor3, () => 3)],\n },\n KHR_materials_emissive_strength: {\n emissiveStrength: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"emissiveIntensity\", getFloat, () => 1)],\n },\n KHR_materials_transmission: {\n transmissionFactor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"subSurface.refractionIntensity\", getFloat, () => 1)],\n },\n KHR_materials_volume: {\n attenuationColor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_COLOR3, \"subSurface.tintColor\", getColor3, () => 3)],\n attenuationDistance: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"subSurface.tintColorAtDistance\", getFloat, () => 1)],\n thicknessFactor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"subSurface.maximumThickness\", getFloat, () => 1)],\n },\n KHR_materials_iridescence: {\n iridescenceFactor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"iridescence.intensity\", getFloat, () => 1)],\n iridescenceIor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"iridescence.indexOfRefraction\", getFloat, () => 1)],\n iridescenceThicknessMinimum: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"iridescence.minimumThickness\", getFloat, () => 1)],\n iridescenceThicknessMaximum: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"iridescence.maximumThickness\", getFloat, () => 1)],\n },\n KHR_materials_anisotropy: {\n anisotropyStrength: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"anisotropy.intensity\", getFloat, () => 1)],\n anisotropyRotation: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"anisotropy.angle\", getFloat, () => 1)],\n },\n },\n },\n};\nconst extensionsTree = {\n KHR_lights_punctual: {\n lights: {\n __array__: {\n __target__: true,\n color: [new LightAnimationPropertyInfo(Animation.ANIMATIONTYPE_COLOR3, \"diffuse\", getColor3, () => 3)],\n intensity: [new LightAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"intensity\", getFloat, () => 1)],\n range: [new LightAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"range\", getFloat, () => 1)],\n spot: {\n innerConeAngle: [new LightAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"innerAngle\", getFloatBy2, () => 1)],\n outerConeAngle: [new LightAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"angle\", getFloatBy2, () => 1)],\n },\n },\n },\n },\n};\n/** @internal */\nexport const animationPointerTree = {\n nodes: nodesTree,\n materials: materialsTree,\n cameras: camerasTree,\n extensions: extensionsTree,\n};\n//# sourceMappingURL=KHR_animation_pointer.data.js.map","import { GLTFLoader } from \"../glTFLoader.js\";\nimport { Logger } from \"@babylonjs/core/Misc/logger.js\";\nimport { animationPointerTree } from \"./KHR_animation_pointer.data.js\";\nconst NAME = \"KHR_animation_pointer\";\n/**\n * [Specification PR](https://github.com/KhronosGroup/glTF/pull/2147)\n * !!! Experimental Extension Subject to Changes !!!\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_animation_pointer {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n this._loader = loader;\n }\n /**\n * Defines whether this extension is enabled.\n */\n get enabled() {\n return this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * Loads a glTF animation channel.\n * @param context The context when loading the asset\n * @param animationContext The context of the animation when loading the asset\n * @param animation The glTF animation property\n * @param channel The glTF animation channel property\n * @param onLoad Called for each animation loaded\n * @returns A void promise that resolves when the load is complete or null if not handled\n */\n _loadAnimationChannelAsync(context, animationContext, animation, channel, onLoad) {\n var _a;\n const extension = (_a = channel.target.extensions) === null || _a === void 0 ? void 0 : _a.KHR_animation_pointer;\n if (!extension) {\n return null;\n }\n if (channel.target.path !== \"pointer\" /* AnimationChannelTargetPath.POINTER */) {\n Logger.Warn(`${context}/target/path: Value (${channel.target.path}) must be (${\"pointer\" /* AnimationChannelTargetPath.POINTER */}) when using the ${this.name} extension`);\n }\n if (channel.target.node != undefined) {\n Logger.Warn(`${context}/target/node: Value (${channel.target.node}) must not be present when using the ${this.name} extension`);\n }\n const extensionContext = `${context}/extensions/${this.name}`;\n const pointer = extension.pointer;\n if (!pointer) {\n throw new Error(`${extensionContext}: Pointer is missing`);\n }\n const targetInfo = this._parseAnimationPointer(`${extensionContext}/pointer`, pointer);\n if (!targetInfo) {\n Logger.Warn(`${extensionContext}/pointer: Invalid pointer (${pointer}) skipped`);\n return null;\n }\n return this._loader._loadAnimationChannelFromTargetInfoAsync(context, animationContext, animation, channel, targetInfo, onLoad);\n }\n /**\n * The pointer string is represented by a [JSON pointer](https://datatracker.ietf.org/doc/html/rfc6901).\n * := ///\n * := \"nodes\" | \"materials\" | \"meshes\" | \"cameras\" | \"extensions\"\n * := | \n * := | \n * := \"extensions\"//\n * := | /\n * := W+\n * := D+\n *\n * Examples:\n * - \"/nodes/0/rotation\"\n * - \"/materials/2/emissiveFactor\"\n * - \"/materials/2/pbrMetallicRoughness/baseColorFactor\"\n * - \"/materials/2/extensions/KHR_materials_emissive_strength/emissiveStrength\"\n */\n _parseAnimationPointer(context, pointer) {\n if (!pointer.startsWith(\"/\")) {\n Logger.Warn(`${context}: Value (${pointer}) must start with a slash`);\n return null;\n }\n const parts = pointer.split(\"/\");\n // Remove the first part since it will be empty string as pointers must start with a slash.\n parts.shift();\n let node = animationPointerTree;\n let gltfCurrentNode = this._loader.gltf;\n let gltfTargetNode = undefined;\n for (const part of parts) {\n if (node.__array__) {\n node = node.__array__;\n }\n else {\n node = node[part];\n if (!node) {\n return null;\n }\n }\n gltfCurrentNode = gltfCurrentNode && gltfCurrentNode[part];\n if (node.__target__) {\n gltfTargetNode = gltfCurrentNode;\n }\n }\n if (!gltfTargetNode || !Array.isArray(node)) {\n return null;\n }\n return {\n target: gltfTargetNode,\n properties: node,\n };\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_animation_pointer(loader));\n//# sourceMappingURL=KHR_animation_pointer.js.map","import { Vector3 } from \"@babylonjs/core/Maths/math.vector.js\";\nimport { Tools } from \"@babylonjs/core/Misc/tools.js\";\nimport { AnimationEvent } from \"@babylonjs/core/Animations/animationEvent.js\";\nimport { Sound } from \"@babylonjs/core/Audio/sound.js\";\nimport { WeightedSound } from \"@babylonjs/core/Audio/weightedsound.js\";\nimport { GLTFLoader, ArrayItem } from \"../glTFLoader.js\";\nconst NAME = \"MSFT_audio_emitter\";\n/**\n * [Specification](https://github.com/najadojo/glTF/blob/MSFT_audio_emitter/extensions/2.0/Vendor/MSFT_audio_emitter/README.md)\n * !!! Experimental Extension Subject to Changes !!!\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class MSFT_audio_emitter {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n this._clips = null;\n this._emitters = null;\n }\n /** @internal */\n onLoading() {\n const extensions = this._loader.gltf.extensions;\n if (extensions && extensions[this.name]) {\n const extension = extensions[this.name];\n this._clips = extension.clips;\n this._emitters = extension.emitters;\n ArrayItem.Assign(this._clips);\n ArrayItem.Assign(this._emitters);\n }\n }\n /**\n * @internal\n */\n loadSceneAsync(context, scene) {\n return GLTFLoader.LoadExtensionAsync(context, scene, this.name, (extensionContext, extension) => {\n const promises = new Array();\n promises.push(this._loader.loadSceneAsync(context, scene));\n for (const emitterIndex of extension.emitters) {\n const emitter = ArrayItem.Get(`${extensionContext}/emitters`, this._emitters, emitterIndex);\n if (emitter.refDistance != undefined ||\n emitter.maxDistance != undefined ||\n emitter.rolloffFactor != undefined ||\n emitter.distanceModel != undefined ||\n emitter.innerAngle != undefined ||\n emitter.outerAngle != undefined) {\n throw new Error(`${extensionContext}: Direction or Distance properties are not allowed on emitters attached to a scene`);\n }\n promises.push(this._loadEmitterAsync(`${extensionContext}/emitters/${emitter.index}`, emitter));\n }\n return Promise.all(promises).then(() => { });\n });\n }\n /**\n * @internal\n */\n loadNodeAsync(context, node, assign) {\n return GLTFLoader.LoadExtensionAsync(context, node, this.name, (extensionContext, extension) => {\n const promises = new Array();\n return this._loader\n .loadNodeAsync(extensionContext, node, (babylonMesh) => {\n for (const emitterIndex of extension.emitters) {\n const emitter = ArrayItem.Get(`${extensionContext}/emitters`, this._emitters, emitterIndex);\n promises.push(this._loadEmitterAsync(`${extensionContext}/emitters/${emitter.index}`, emitter).then(() => {\n for (const sound of emitter._babylonSounds) {\n sound.attachToMesh(babylonMesh);\n if (emitter.innerAngle != undefined || emitter.outerAngle != undefined) {\n sound.setLocalDirectionToMesh(Vector3.Forward());\n sound.setDirectionalCone(2 * Tools.ToDegrees(emitter.innerAngle == undefined ? Math.PI : emitter.innerAngle), 2 * Tools.ToDegrees(emitter.outerAngle == undefined ? Math.PI : emitter.outerAngle), 0);\n }\n }\n }));\n }\n assign(babylonMesh);\n })\n .then((babylonMesh) => {\n return Promise.all(promises).then(() => {\n return babylonMesh;\n });\n });\n });\n }\n /**\n * @internal\n */\n loadAnimationAsync(context, animation) {\n return GLTFLoader.LoadExtensionAsync(context, animation, this.name, (extensionContext, extension) => {\n return this._loader.loadAnimationAsync(context, animation).then((babylonAnimationGroup) => {\n const promises = new Array();\n ArrayItem.Assign(extension.events);\n for (const event of extension.events) {\n promises.push(this._loadAnimationEventAsync(`${extensionContext}/events/${event.index}`, context, animation, event, babylonAnimationGroup));\n }\n return Promise.all(promises).then(() => {\n return babylonAnimationGroup;\n });\n });\n });\n }\n _loadClipAsync(context, clip) {\n if (clip._objectURL) {\n return clip._objectURL;\n }\n let promise;\n if (clip.uri) {\n promise = this._loader.loadUriAsync(context, clip, clip.uri);\n }\n else {\n const bufferView = ArrayItem.Get(`${context}/bufferView`, this._loader.gltf.bufferViews, clip.bufferView);\n promise = this._loader.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView);\n }\n clip._objectURL = promise.then((data) => {\n return URL.createObjectURL(new Blob([data], { type: clip.mimeType }));\n });\n return clip._objectURL;\n }\n _loadEmitterAsync(context, emitter) {\n emitter._babylonSounds = emitter._babylonSounds || [];\n if (!emitter._babylonData) {\n const clipPromises = new Array();\n const name = emitter.name || `emitter${emitter.index}`;\n const options = {\n loop: false,\n autoplay: false,\n volume: emitter.volume == undefined ? 1 : emitter.volume,\n };\n for (let i = 0; i < emitter.clips.length; i++) {\n const clipContext = `/extensions/${this.name}/clips`;\n const clip = ArrayItem.Get(clipContext, this._clips, emitter.clips[i].clip);\n clipPromises.push(this._loadClipAsync(`${clipContext}/${emitter.clips[i].clip}`, clip).then((objectURL) => {\n const sound = (emitter._babylonSounds[i] = new Sound(name, objectURL, this._loader.babylonScene, null, options));\n sound.refDistance = emitter.refDistance || 1;\n sound.maxDistance = emitter.maxDistance || 256;\n sound.rolloffFactor = emitter.rolloffFactor || 1;\n sound.distanceModel = emitter.distanceModel || \"exponential\";\n }));\n }\n const promise = Promise.all(clipPromises).then(() => {\n const weights = emitter.clips.map((clip) => {\n return clip.weight || 1;\n });\n const weightedSound = new WeightedSound(emitter.loop || false, emitter._babylonSounds, weights);\n if (emitter.innerAngle) {\n weightedSound.directionalConeInnerAngle = 2 * Tools.ToDegrees(emitter.innerAngle);\n }\n if (emitter.outerAngle) {\n weightedSound.directionalConeOuterAngle = 2 * Tools.ToDegrees(emitter.outerAngle);\n }\n if (emitter.volume) {\n weightedSound.volume = emitter.volume;\n }\n emitter._babylonData.sound = weightedSound;\n });\n emitter._babylonData = {\n loaded: promise,\n };\n }\n return emitter._babylonData.loaded;\n }\n _getEventAction(context, sound, action, time, startOffset) {\n switch (action) {\n case \"play\" /* IMSFTAudioEmitter_AnimationEventAction.play */: {\n return (currentFrame) => {\n const frameOffset = (startOffset || 0) + (currentFrame - time);\n sound.play(frameOffset);\n };\n }\n case \"stop\" /* IMSFTAudioEmitter_AnimationEventAction.stop */: {\n return () => {\n sound.stop();\n };\n }\n case \"pause\" /* IMSFTAudioEmitter_AnimationEventAction.pause */: {\n return () => {\n sound.pause();\n };\n }\n default: {\n throw new Error(`${context}: Unsupported action ${action}`);\n }\n }\n }\n _loadAnimationEventAsync(context, animationContext, animation, event, babylonAnimationGroup) {\n if (babylonAnimationGroup.targetedAnimations.length == 0) {\n return Promise.resolve();\n }\n const babylonAnimation = babylonAnimationGroup.targetedAnimations[0];\n const emitterIndex = event.emitter;\n const emitter = ArrayItem.Get(`/extensions/${this.name}/emitters`, this._emitters, emitterIndex);\n return this._loadEmitterAsync(context, emitter).then(() => {\n const sound = emitter._babylonData.sound;\n if (sound) {\n const babylonAnimationEvent = new AnimationEvent(event.time, this._getEventAction(context, sound, event.action, event.time, event.startOffset));\n babylonAnimation.animation.addEvent(babylonAnimationEvent);\n // Make sure all started audio stops when this animation is terminated.\n babylonAnimationGroup.onAnimationGroupEndObservable.add(() => {\n sound.stop();\n });\n babylonAnimationGroup.onAnimationGroupPauseObservable.add(() => {\n sound.pause();\n });\n }\n });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new MSFT_audio_emitter(loader));\n//# sourceMappingURL=MSFT_audio_emitter.js.map","import { Observable } from \"@babylonjs/core/Misc/observable.js\";\nimport { Deferred } from \"@babylonjs/core/Misc/deferred.js\";\nimport { GLTFLoader, ArrayItem } from \"../glTFLoader.js\";\nconst NAME = \"MSFT_lod\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Vendor/MSFT_lod/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class MSFT_lod {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 100;\n /**\n * Maximum number of LODs to load, starting from the lowest LOD.\n */\n this.maxLODsToLoad = 10;\n /**\n * Observable raised when all node LODs of one level are loaded.\n * The event data is the index of the loaded LOD starting from zero.\n * Dispose the loader to cancel the loading of the next level of LODs.\n */\n this.onNodeLODsLoadedObservable = new Observable();\n /**\n * Observable raised when all material LODs of one level are loaded.\n * The event data is the index of the loaded LOD starting from zero.\n * Dispose the loader to cancel the loading of the next level of LODs.\n */\n this.onMaterialLODsLoadedObservable = new Observable();\n this._bufferLODs = new Array();\n this._nodeIndexLOD = null;\n this._nodeSignalLODs = new Array();\n this._nodePromiseLODs = new Array();\n this._nodeBufferLODs = new Array();\n this._materialIndexLOD = null;\n this._materialSignalLODs = new Array();\n this._materialPromiseLODs = new Array();\n this._materialBufferLODs = new Array();\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n this._nodeIndexLOD = null;\n this._nodeSignalLODs.length = 0;\n this._nodePromiseLODs.length = 0;\n this._nodeBufferLODs.length = 0;\n this._materialIndexLOD = null;\n this._materialSignalLODs.length = 0;\n this._materialPromiseLODs.length = 0;\n this._materialBufferLODs.length = 0;\n this.onMaterialLODsLoadedObservable.clear();\n this.onNodeLODsLoadedObservable.clear();\n }\n /** @internal */\n onReady() {\n for (let indexLOD = 0; indexLOD < this._nodePromiseLODs.length; indexLOD++) {\n const promise = Promise.all(this._nodePromiseLODs[indexLOD]).then(() => {\n if (indexLOD !== 0) {\n this._loader.endPerformanceCounter(`Node LOD ${indexLOD}`);\n this._loader.log(`Loaded node LOD ${indexLOD}`);\n }\n this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);\n if (indexLOD !== this._nodePromiseLODs.length - 1) {\n this._loader.startPerformanceCounter(`Node LOD ${indexLOD + 1}`);\n this._loadBufferLOD(this._nodeBufferLODs, indexLOD + 1);\n if (this._nodeSignalLODs[indexLOD]) {\n this._nodeSignalLODs[indexLOD].resolve();\n }\n }\n });\n this._loader._completePromises.push(promise);\n }\n for (let indexLOD = 0; indexLOD < this._materialPromiseLODs.length; indexLOD++) {\n const promise = Promise.all(this._materialPromiseLODs[indexLOD]).then(() => {\n if (indexLOD !== 0) {\n this._loader.endPerformanceCounter(`Material LOD ${indexLOD}`);\n this._loader.log(`Loaded material LOD ${indexLOD}`);\n }\n this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);\n if (indexLOD !== this._materialPromiseLODs.length - 1) {\n this._loader.startPerformanceCounter(`Material LOD ${indexLOD + 1}`);\n this._loadBufferLOD(this._materialBufferLODs, indexLOD + 1);\n if (this._materialSignalLODs[indexLOD]) {\n this._materialSignalLODs[indexLOD].resolve();\n }\n }\n });\n this._loader._completePromises.push(promise);\n }\n }\n /**\n * @internal\n */\n loadSceneAsync(context, scene) {\n const promise = this._loader.loadSceneAsync(context, scene);\n this._loadBufferLOD(this._bufferLODs, 0);\n return promise;\n }\n /**\n * @internal\n */\n loadNodeAsync(context, node, assign) {\n return GLTFLoader.LoadExtensionAsync(context, node, this.name, (extensionContext, extension) => {\n let firstPromise;\n const nodeLODs = this._getLODs(extensionContext, node, this._loader.gltf.nodes, extension.ids);\n this._loader.logOpen(`${extensionContext}`);\n for (let indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {\n const nodeLOD = nodeLODs[indexLOD];\n if (indexLOD !== 0) {\n this._nodeIndexLOD = indexLOD;\n this._nodeSignalLODs[indexLOD] = this._nodeSignalLODs[indexLOD] || new Deferred();\n }\n const assignWrap = (babylonTransformNode) => {\n assign(babylonTransformNode);\n babylonTransformNode.setEnabled(false);\n };\n const promise = this._loader.loadNodeAsync(`/nodes/${nodeLOD.index}`, nodeLOD, assignWrap).then((babylonMesh) => {\n if (indexLOD !== 0) {\n // TODO: should not rely on _babylonTransformNode\n const previousNodeLOD = nodeLODs[indexLOD - 1];\n if (previousNodeLOD._babylonTransformNode) {\n this._disposeTransformNode(previousNodeLOD._babylonTransformNode);\n delete previousNodeLOD._babylonTransformNode;\n }\n }\n babylonMesh.setEnabled(true);\n return babylonMesh;\n });\n this._nodePromiseLODs[indexLOD] = this._nodePromiseLODs[indexLOD] || [];\n if (indexLOD === 0) {\n firstPromise = promise;\n }\n else {\n this._nodeIndexLOD = null;\n this._nodePromiseLODs[indexLOD].push(promise);\n }\n }\n this._loader.logClose();\n return firstPromise;\n });\n }\n /**\n * @internal\n */\n _loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign) {\n // Don't load material LODs if already loading a node LOD.\n if (this._nodeIndexLOD) {\n return null;\n }\n return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => {\n let firstPromise;\n const materialLODs = this._getLODs(extensionContext, material, this._loader.gltf.materials, extension.ids);\n this._loader.logOpen(`${extensionContext}`);\n for (let indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {\n const materialLOD = materialLODs[indexLOD];\n if (indexLOD !== 0) {\n this._materialIndexLOD = indexLOD;\n }\n const promise = this._loader\n ._loadMaterialAsync(`/materials/${materialLOD.index}`, materialLOD, babylonMesh, babylonDrawMode, (babylonMaterial) => {\n if (indexLOD === 0) {\n assign(babylonMaterial);\n }\n })\n .then((babylonMaterial) => {\n if (indexLOD !== 0) {\n assign(babylonMaterial);\n // TODO: should not rely on _data\n const previousDataLOD = materialLODs[indexLOD - 1]._data;\n if (previousDataLOD[babylonDrawMode]) {\n this._disposeMaterials([previousDataLOD[babylonDrawMode].babylonMaterial]);\n delete previousDataLOD[babylonDrawMode];\n }\n }\n return babylonMaterial;\n });\n this._materialPromiseLODs[indexLOD] = this._materialPromiseLODs[indexLOD] || [];\n if (indexLOD === 0) {\n firstPromise = promise;\n }\n else {\n this._materialIndexLOD = null;\n this._materialPromiseLODs[indexLOD].push(promise);\n }\n }\n this._loader.logClose();\n return firstPromise;\n });\n }\n /**\n * @internal\n */\n _loadUriAsync(context, property, uri) {\n // Defer the loading of uris if loading a node or material LOD.\n if (this._nodeIndexLOD !== null) {\n this._loader.log(`deferred`);\n const previousIndexLOD = this._nodeIndexLOD - 1;\n this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new Deferred();\n return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(() => {\n return this._loader.loadUriAsync(context, property, uri);\n });\n }\n else if (this._materialIndexLOD !== null) {\n this._loader.log(`deferred`);\n const previousIndexLOD = this._materialIndexLOD - 1;\n this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new Deferred();\n return this._materialSignalLODs[previousIndexLOD].promise.then(() => {\n return this._loader.loadUriAsync(context, property, uri);\n });\n }\n return null;\n }\n /**\n * @internal\n */\n loadBufferAsync(context, buffer, byteOffset, byteLength) {\n if (this._loader.parent.useRangeRequests && !buffer.uri) {\n if (!this._loader.bin) {\n throw new Error(`${context}: Uri is missing or the binary glTF is missing its binary chunk`);\n }\n const loadAsync = (bufferLODs, indexLOD) => {\n const start = byteOffset;\n const end = start + byteLength - 1;\n let bufferLOD = bufferLODs[indexLOD];\n if (bufferLOD) {\n bufferLOD.start = Math.min(bufferLOD.start, start);\n bufferLOD.end = Math.max(bufferLOD.end, end);\n }\n else {\n bufferLOD = { start: start, end: end, loaded: new Deferred() };\n bufferLODs[indexLOD] = bufferLOD;\n }\n return bufferLOD.loaded.promise.then((data) => {\n return new Uint8Array(data.buffer, data.byteOffset + byteOffset - bufferLOD.start, byteLength);\n });\n };\n this._loader.log(`deferred`);\n if (this._nodeIndexLOD !== null) {\n return loadAsync(this._nodeBufferLODs, this._nodeIndexLOD);\n }\n else if (this._materialIndexLOD !== null) {\n return loadAsync(this._materialBufferLODs, this._materialIndexLOD);\n }\n else {\n return loadAsync(this._bufferLODs, 0);\n }\n }\n return null;\n }\n _loadBufferLOD(bufferLODs, indexLOD) {\n const bufferLOD = bufferLODs[indexLOD];\n if (bufferLOD) {\n this._loader.log(`Loading buffer range [${bufferLOD.start}-${bufferLOD.end}]`);\n this._loader.bin.readAsync(bufferLOD.start, bufferLOD.end - bufferLOD.start + 1).then((data) => {\n bufferLOD.loaded.resolve(data);\n }, (error) => {\n bufferLOD.loaded.reject(error);\n });\n }\n }\n /**\n * Gets an array of LOD properties from lowest to highest.\n * @param context\n * @param property\n * @param array\n * @param ids\n */\n _getLODs(context, property, array, ids) {\n if (this.maxLODsToLoad <= 0) {\n throw new Error(\"maxLODsToLoad must be greater than zero\");\n }\n const properties = new Array();\n for (let i = ids.length - 1; i >= 0; i--) {\n properties.push(ArrayItem.Get(`${context}/ids/${ids[i]}`, array, ids[i]));\n if (properties.length === this.maxLODsToLoad) {\n return properties;\n }\n }\n properties.push(property);\n return properties;\n }\n _disposeTransformNode(babylonTransformNode) {\n const babylonMaterials = new Array();\n const babylonMaterial = babylonTransformNode.material;\n if (babylonMaterial) {\n babylonMaterials.push(babylonMaterial);\n }\n for (const babylonMesh of babylonTransformNode.getChildMeshes()) {\n if (babylonMesh.material) {\n babylonMaterials.push(babylonMesh.material);\n }\n }\n babylonTransformNode.dispose();\n const babylonMaterialsToDispose = babylonMaterials.filter((babylonMaterial) => this._loader.babylonScene.meshes.every((mesh) => mesh.material != babylonMaterial));\n this._disposeMaterials(babylonMaterialsToDispose);\n }\n _disposeMaterials(babylonMaterials) {\n const babylonTextures = {};\n for (const babylonMaterial of babylonMaterials) {\n for (const babylonTexture of babylonMaterial.getActiveTextures()) {\n babylonTextures[babylonTexture.uniqueId] = babylonTexture;\n }\n babylonMaterial.dispose();\n }\n for (const uniqueId in babylonTextures) {\n for (const babylonMaterial of this._loader.babylonScene.materials) {\n if (babylonMaterial.hasTexture(babylonTextures[uniqueId])) {\n delete babylonTextures[uniqueId];\n }\n }\n }\n for (const uniqueId in babylonTextures) {\n babylonTextures[uniqueId].dispose();\n }\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new MSFT_lod(loader));\n//# sourceMappingURL=MSFT_lod.js.map","import { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"MSFT_minecraftMesh\";\n/** @internal */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class MSFT_minecraftMesh {\n /** @internal */\n constructor(loader) {\n /** @internal */\n this.name = NAME;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /** @internal */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtraAsync(context, material, this.name, (extraContext, extra) => {\n if (extra) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${extraContext}: Material type not supported`);\n }\n const promise = this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial);\n if (babylonMaterial.needAlphaBlending()) {\n babylonMaterial.forceDepthWrite = true;\n babylonMaterial.separateCullingPass = true;\n }\n babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;\n babylonMaterial.twoSidedLighting = true;\n return promise;\n }\n return null;\n });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new MSFT_minecraftMesh(loader));\n//# sourceMappingURL=MSFT_minecraftMesh.js.map","import { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"MSFT_sRGBFactors\";\n/** @internal */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class MSFT_sRGBFactors {\n /** @internal */\n constructor(loader) {\n /** @internal */\n this.name = NAME;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /** @internal */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtraAsync(context, material, this.name, (extraContext, extra) => {\n if (extra) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${extraContext}: Material type not supported`);\n }\n const promise = this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial);\n const useExactSrgbConversions = babylonMaterial.getScene().getEngine().useExactSrgbConversions;\n if (!babylonMaterial.albedoTexture) {\n babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor, useExactSrgbConversions);\n }\n if (!babylonMaterial.reflectivityTexture) {\n babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor, useExactSrgbConversions);\n }\n return promise;\n }\n return null;\n });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new MSFT_sRGBFactors(loader));\n//# sourceMappingURL=MSFT_sRGBFactors.js.map","import { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"ExtrasAsMetadata\";\n/**\n * Store glTF extras (if present) in BJS objects' metadata\n */\nexport class ExtrasAsMetadata {\n _assignExtras(babylonObject, gltfProp) {\n if (gltfProp.extras && Object.keys(gltfProp.extras).length > 0) {\n const metadata = (babylonObject.metadata = babylonObject.metadata || {});\n const gltf = (metadata.gltf = metadata.gltf || {});\n gltf.extras = gltfProp.extras;\n }\n }\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines whether this extension is enabled.\n */\n this.enabled = true;\n this._loader = loader;\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadNodeAsync(context, node, assign) {\n return this._loader.loadNodeAsync(context, node, (babylonTransformNode) => {\n this._assignExtras(babylonTransformNode, node);\n assign(babylonTransformNode);\n });\n }\n /**\n * @internal\n */\n loadCameraAsync(context, camera, assign) {\n return this._loader.loadCameraAsync(context, camera, (babylonCamera) => {\n this._assignExtras(babylonCamera, camera);\n assign(babylonCamera);\n });\n }\n /**\n * @internal\n */\n createMaterial(context, material, babylonDrawMode) {\n const babylonMaterial = this._loader.createMaterial(context, material, babylonDrawMode);\n this._assignExtras(babylonMaterial, material);\n return babylonMaterial;\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new ExtrasAsMetadata(loader));\n//# sourceMappingURL=ExtrasAsMetadata.js.map","import { DataBuffer } from \"./dataBuffer.js\";\n/**\n * Class used to store data that will be store in GPU memory\n */\nexport class Buffer {\n /**\n * Constructor\n * @param engine the engine\n * @param data the data to use for this buffer\n * @param updatable whether the data is updatable\n * @param stride the stride (optional)\n * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)\n * @param instanced whether the buffer is instanced (optional)\n * @param useBytes set to true if the stride in in bytes (optional)\n * @param divisor sets an optional divisor for instances (1 by default)\n */\n constructor(engine, data, updatable, stride = 0, postponeInternalCreation = false, instanced = false, useBytes = false, divisor) {\n this._isAlreadyOwned = false;\n if (engine.getScene) {\n // old versions of VertexBuffer accepted 'mesh' instead of 'engine'\n this._engine = engine.getScene().getEngine();\n }\n else {\n this._engine = engine;\n }\n this._updatable = updatable;\n this._instanced = instanced;\n this._divisor = divisor || 1;\n if (data instanceof DataBuffer) {\n this._data = null;\n this._buffer = data;\n }\n else {\n this._data = data;\n this._buffer = null;\n }\n this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;\n if (!postponeInternalCreation) {\n // by default\n this.create();\n }\n }\n /**\n * Create a new VertexBuffer based on the current buffer\n * @param kind defines the vertex buffer kind (position, normal, etc.)\n * @param offset defines offset in the buffer (0 by default)\n * @param size defines the size in floats of attributes (position is 3 for instance)\n * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)\n * @param instanced defines if the vertex buffer contains indexed data\n * @param useBytes defines if the offset and stride are in bytes *\n * @param divisor sets an optional divisor for instances (1 by default)\n * @returns the new vertex buffer\n */\n createVertexBuffer(kind, offset, size, stride, instanced, useBytes = false, divisor) {\n const byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;\n const byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;\n // a lot of these parameters are ignored as they are overridden by the buffer\n return new VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true, this._divisor || divisor);\n }\n // Properties\n /**\n * Gets a boolean indicating if the Buffer is updatable?\n * @returns true if the buffer is updatable\n */\n isUpdatable() {\n return this._updatable;\n }\n /**\n * Gets current buffer's data\n * @returns a DataArray or null\n */\n getData() {\n return this._data;\n }\n /**\n * Gets underlying native buffer\n * @returns underlying native buffer\n */\n getBuffer() {\n return this._buffer;\n }\n /**\n * Gets the stride in float32 units (i.e. byte stride / 4).\n * May not be an integer if the byte stride is not divisible by 4.\n * @returns the stride in float32 units\n * @deprecated Please use byteStride instead.\n */\n getStrideSize() {\n return this.byteStride / Float32Array.BYTES_PER_ELEMENT;\n }\n // Methods\n /**\n * Store data into the buffer. Creates the buffer if not used already.\n * If the buffer was already used, it will be updated only if it is updatable, otherwise it will do nothing.\n * @param data defines the data to store\n */\n create(data = null) {\n if (!data && this._buffer) {\n return; // nothing to do\n }\n data = data || this._data;\n if (!data) {\n return;\n }\n if (!this._buffer) {\n // create buffer\n if (this._updatable) {\n this._buffer = this._engine.createDynamicVertexBuffer(data);\n this._data = data;\n }\n else {\n this._buffer = this._engine.createVertexBuffer(data);\n }\n }\n else if (this._updatable) {\n // update buffer\n this._engine.updateDynamicVertexBuffer(this._buffer, data);\n this._data = data;\n }\n }\n /** @internal */\n _rebuild() {\n this._buffer = null;\n this.create(this._data);\n }\n /**\n * Update current buffer data\n * @param data defines the data to store\n */\n update(data) {\n this.create(data);\n }\n /**\n * Updates the data directly.\n * @param data the new data\n * @param offset the new offset\n * @param vertexCount the vertex count (optional)\n * @param useBytes set to true if the offset is in bytes\n */\n updateDirectly(data, offset, vertexCount, useBytes = false) {\n if (!this._buffer) {\n return;\n }\n if (this._updatable) {\n // update buffer\n this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, vertexCount ? vertexCount * this.byteStride : undefined);\n if (offset === 0 && vertexCount === undefined) {\n // Keep the data if we easily can\n this._data = data;\n }\n else {\n this._data = null;\n }\n }\n }\n /** @internal */\n _increaseReferences() {\n if (!this._buffer) {\n return;\n }\n if (!this._isAlreadyOwned) {\n this._isAlreadyOwned = true;\n return;\n }\n this._buffer.references++;\n }\n /**\n * Release all resources\n */\n dispose() {\n if (!this._buffer) {\n return;\n }\n if (this._engine._releaseBuffer(this._buffer)) {\n this._buffer = null;\n this._data = null;\n }\n }\n}\n/**\n * Specialized buffer used to store vertex data\n */\nexport class VertexBuffer {\n /**\n * Gets or sets the instance divisor when in instanced mode\n */\n get instanceDivisor() {\n return this._instanceDivisor;\n }\n set instanceDivisor(value) {\n const isInstanced = value != 0;\n this._instanceDivisor = value;\n if (isInstanced !== this._instanced) {\n this._instanced = isInstanced;\n this._computeHashCode();\n }\n }\n /**\n * Constructor\n * @param engine the engine\n * @param data the data to use for this vertex buffer\n * @param kind the vertex buffer kind\n * @param updatable whether the data is updatable\n * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)\n * @param stride the stride (optional)\n * @param instanced whether the buffer is instanced (optional)\n * @param offset the offset of the data (optional)\n * @param size the number of components (optional)\n * @param type the type of the component (optional)\n * @param normalized whether the data contains normalized data (optional)\n * @param useBytes set to true if stride and offset are in bytes (optional)\n * @param divisor defines the instance divisor to use (1 by default)\n * @param takeBufferOwnership defines if the buffer should be released when the vertex buffer is disposed\n */\n constructor(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized = false, useBytes = false, divisor = 1, takeBufferOwnership = false) {\n if (data instanceof Buffer) {\n this._buffer = data;\n this._ownsBuffer = takeBufferOwnership;\n }\n else {\n this._buffer = new Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);\n this._ownsBuffer = true;\n }\n this.uniqueId = VertexBuffer._Counter++;\n this._kind = kind;\n if (type == undefined) {\n const vertexData = this.getData();\n this.type = VertexBuffer.FLOAT;\n if (vertexData instanceof Int8Array) {\n this.type = VertexBuffer.BYTE;\n }\n else if (vertexData instanceof Uint8Array) {\n this.type = VertexBuffer.UNSIGNED_BYTE;\n }\n else if (vertexData instanceof Int16Array) {\n this.type = VertexBuffer.SHORT;\n }\n else if (vertexData instanceof Uint16Array) {\n this.type = VertexBuffer.UNSIGNED_SHORT;\n }\n else if (vertexData instanceof Int32Array) {\n this.type = VertexBuffer.INT;\n }\n else if (vertexData instanceof Uint32Array) {\n this.type = VertexBuffer.UNSIGNED_INT;\n }\n }\n else {\n this.type = type;\n }\n const typeByteLength = VertexBuffer.GetTypeByteLength(this.type);\n if (useBytes) {\n this._size = size || (stride ? stride / typeByteLength : VertexBuffer.DeduceStride(kind));\n this.byteStride = stride || this._buffer.byteStride || this._size * typeByteLength;\n this.byteOffset = offset || 0;\n }\n else {\n this._size = size || stride || VertexBuffer.DeduceStride(kind);\n this.byteStride = stride ? stride * typeByteLength : this._buffer.byteStride || this._size * typeByteLength;\n this.byteOffset = (offset || 0) * typeByteLength;\n }\n this.normalized = normalized;\n this._instanced = instanced !== undefined ? instanced : false;\n this._instanceDivisor = instanced ? divisor : 0;\n this._computeHashCode();\n }\n _computeHashCode() {\n // note: cast to any because the property is declared readonly\n this.hashCode =\n ((this.type - 5120) << 0) +\n ((this.normalized ? 1 : 0) << 3) +\n (this._size << 4) +\n ((this._instanced ? 1 : 0) << 6) +\n /* keep 5 bits free */\n (this.byteStride << 12);\n }\n /** @internal */\n _rebuild() {\n if (!this._buffer) {\n return;\n }\n this._buffer._rebuild();\n }\n /**\n * Returns the kind of the VertexBuffer (string)\n * @returns a string\n */\n getKind() {\n return this._kind;\n }\n // Properties\n /**\n * Gets a boolean indicating if the VertexBuffer is updatable?\n * @returns true if the buffer is updatable\n */\n isUpdatable() {\n return this._buffer.isUpdatable();\n }\n /**\n * Gets current buffer's data\n * @returns a DataArray or null\n */\n getData() {\n return this._buffer.getData();\n }\n /**\n * Gets current buffer's data as a float array. Float data is constructed if the vertex buffer data cannot be returned directly.\n * @param totalVertices number of vertices in the buffer to take into account\n * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it\n * @returns a float array containing vertex data\n */\n getFloatData(totalVertices, forceCopy) {\n const data = this.getData();\n if (!data) {\n return null;\n }\n const tightlyPackedByteStride = this.getSize() * VertexBuffer.GetTypeByteLength(this.type);\n const count = totalVertices * this.getSize();\n if (this.type !== VertexBuffer.FLOAT || this.byteStride !== tightlyPackedByteStride) {\n const copy = new Float32Array(count);\n this.forEach(count, (value, index) => (copy[index] = value));\n return copy;\n }\n if (!(data instanceof Array || data instanceof Float32Array) || this.byteOffset !== 0 || data.length !== count) {\n if (data instanceof Array) {\n const offset = this.byteOffset / 4;\n return data.slice(offset, offset + count);\n }\n else if (data instanceof ArrayBuffer) {\n return new Float32Array(data, this.byteOffset, count);\n }\n else {\n let offset = data.byteOffset + this.byteOffset;\n if (forceCopy) {\n const result = new Float32Array(count);\n const source = new Float32Array(data.buffer, offset, count);\n result.set(source);\n return result;\n }\n // Protect against bad data\n const remainder = offset % 4;\n if (remainder) {\n offset = Math.max(0, offset - remainder);\n }\n return new Float32Array(data.buffer, offset, count);\n }\n }\n if (forceCopy) {\n return data.slice();\n }\n return data;\n }\n /**\n * Gets underlying native buffer\n * @returns underlying native buffer\n */\n getBuffer() {\n return this._buffer.getBuffer();\n }\n /**\n * Gets the stride in float32 units (i.e. byte stride / 4).\n * May not be an integer if the byte stride is not divisible by 4.\n * @returns the stride in float32 units\n * @deprecated Please use byteStride instead.\n */\n getStrideSize() {\n return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);\n }\n /**\n * Returns the offset as a multiple of the type byte length.\n * @returns the offset in bytes\n * @deprecated Please use byteOffset instead.\n */\n getOffset() {\n return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);\n }\n /**\n * Returns the number of components or the byte size per vertex attribute\n * @param sizeInBytes If true, returns the size in bytes or else the size in number of components of the vertex attribute (default: false)\n * @returns the number of components\n */\n getSize(sizeInBytes = false) {\n return sizeInBytes ? this._size * VertexBuffer.GetTypeByteLength(this.type) : this._size;\n }\n /**\n * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced\n * @returns true if this buffer is instanced\n */\n getIsInstanced() {\n return this._instanced;\n }\n /**\n * Returns the instancing divisor, zero for non-instanced (integer).\n * @returns a number\n */\n getInstanceDivisor() {\n return this._instanceDivisor;\n }\n // Methods\n /**\n * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property\n * @param data defines the data to store\n */\n create(data) {\n this._buffer.create(data);\n }\n /**\n * Updates the underlying buffer according to the passed numeric array or Float32Array.\n * This function will create a new buffer if the current one is not updatable\n * @param data defines the data to store\n */\n update(data) {\n this._buffer.update(data);\n }\n /**\n * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.\n * Returns the directly updated WebGLBuffer.\n * @param data the new data\n * @param offset the new offset\n * @param useBytes set to true if the offset is in bytes\n */\n updateDirectly(data, offset, useBytes = false) {\n this._buffer.updateDirectly(data, offset, undefined, useBytes);\n }\n /**\n * Disposes the VertexBuffer and the underlying WebGLBuffer.\n */\n dispose() {\n if (this._ownsBuffer) {\n this._buffer.dispose();\n }\n }\n /**\n * Enumerates each value of this vertex buffer as numbers.\n * @param count the number of values to enumerate\n * @param callback the callback function called for each value\n */\n forEach(count, callback) {\n VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);\n }\n /**\n * Deduces the stride given a kind.\n * @param kind The kind string to deduce\n * @returns The deduced stride\n */\n static DeduceStride(kind) {\n switch (kind) {\n case VertexBuffer.UVKind:\n case VertexBuffer.UV2Kind:\n case VertexBuffer.UV3Kind:\n case VertexBuffer.UV4Kind:\n case VertexBuffer.UV5Kind:\n case VertexBuffer.UV6Kind:\n return 2;\n case VertexBuffer.NormalKind:\n case VertexBuffer.PositionKind:\n return 3;\n case VertexBuffer.ColorKind:\n case VertexBuffer.MatricesIndicesKind:\n case VertexBuffer.MatricesIndicesExtraKind:\n case VertexBuffer.MatricesWeightsKind:\n case VertexBuffer.MatricesWeightsExtraKind:\n case VertexBuffer.TangentKind:\n return 4;\n default:\n throw new Error(\"Invalid kind '\" + kind + \"'\");\n }\n }\n /**\n * Gets the byte length of the given type.\n * @param type the type\n * @returns the number of bytes\n */\n static GetTypeByteLength(type) {\n switch (type) {\n case VertexBuffer.BYTE:\n case VertexBuffer.UNSIGNED_BYTE:\n return 1;\n case VertexBuffer.SHORT:\n case VertexBuffer.UNSIGNED_SHORT:\n return 2;\n case VertexBuffer.INT:\n case VertexBuffer.UNSIGNED_INT:\n case VertexBuffer.FLOAT:\n return 4;\n default:\n throw new Error(`Invalid type '${type}'`);\n }\n }\n /**\n * Enumerates each value of the given parameters as numbers.\n * @param data the data to enumerate\n * @param byteOffset the byte offset of the data\n * @param byteStride the byte stride of the data\n * @param componentCount the number of components per element\n * @param componentType the type of the component\n * @param count the number of values to enumerate\n * @param normalized whether the data is normalized\n * @param callback the callback function called for each value\n */\n static ForEach(data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {\n if (data instanceof Array) {\n let offset = byteOffset / 4;\n const stride = byteStride / 4;\n for (let index = 0; index < count; index += componentCount) {\n for (let componentIndex = 0; componentIndex < componentCount; componentIndex++) {\n callback(data[offset + componentIndex], index + componentIndex);\n }\n offset += stride;\n }\n }\n else {\n const dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);\n const componentByteLength = VertexBuffer.GetTypeByteLength(componentType);\n for (let index = 0; index < count; index += componentCount) {\n let componentByteOffset = byteOffset;\n for (let componentIndex = 0; componentIndex < componentCount; componentIndex++) {\n const value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);\n callback(value, index + componentIndex);\n componentByteOffset += componentByteLength;\n }\n byteOffset += byteStride;\n }\n }\n }\n static _GetFloatValue(dataView, type, byteOffset, normalized) {\n switch (type) {\n case VertexBuffer.BYTE: {\n let value = dataView.getInt8(byteOffset);\n if (normalized) {\n value = Math.max(value / 127, -1);\n }\n return value;\n }\n case VertexBuffer.UNSIGNED_BYTE: {\n let value = dataView.getUint8(byteOffset);\n if (normalized) {\n value = value / 255;\n }\n return value;\n }\n case VertexBuffer.SHORT: {\n let value = dataView.getInt16(byteOffset, true);\n if (normalized) {\n value = Math.max(value / 32767, -1);\n }\n return value;\n }\n case VertexBuffer.UNSIGNED_SHORT: {\n let value = dataView.getUint16(byteOffset, true);\n if (normalized) {\n value = value / 65535;\n }\n return value;\n }\n case VertexBuffer.INT: {\n return dataView.getInt32(byteOffset, true);\n }\n case VertexBuffer.UNSIGNED_INT: {\n return dataView.getUint32(byteOffset, true);\n }\n case VertexBuffer.FLOAT: {\n return dataView.getFloat32(byteOffset, true);\n }\n default: {\n throw new Error(`Invalid component type ${type}`);\n }\n }\n }\n}\nVertexBuffer._Counter = 0;\n/**\n * The byte type.\n */\nVertexBuffer.BYTE = 5120;\n/**\n * The unsigned byte type.\n */\nVertexBuffer.UNSIGNED_BYTE = 5121;\n/**\n * The short type.\n */\nVertexBuffer.SHORT = 5122;\n/**\n * The unsigned short type.\n */\nVertexBuffer.UNSIGNED_SHORT = 5123;\n/**\n * The integer type.\n */\nVertexBuffer.INT = 5124;\n/**\n * The unsigned integer type.\n */\nVertexBuffer.UNSIGNED_INT = 5125;\n/**\n * The float type.\n */\nVertexBuffer.FLOAT = 5126;\n// Enums\n/**\n * Positions\n */\nVertexBuffer.PositionKind = \"position\";\n/**\n * Normals\n */\nVertexBuffer.NormalKind = \"normal\";\n/**\n * Tangents\n */\nVertexBuffer.TangentKind = \"tangent\";\n/**\n * Texture coordinates\n */\nVertexBuffer.UVKind = \"uv\";\n/**\n * Texture coordinates 2\n */\nVertexBuffer.UV2Kind = \"uv2\";\n/**\n * Texture coordinates 3\n */\nVertexBuffer.UV3Kind = \"uv3\";\n/**\n * Texture coordinates 4\n */\nVertexBuffer.UV4Kind = \"uv4\";\n/**\n * Texture coordinates 5\n */\nVertexBuffer.UV5Kind = \"uv5\";\n/**\n * Texture coordinates 6\n */\nVertexBuffer.UV6Kind = \"uv6\";\n/**\n * Colors\n */\nVertexBuffer.ColorKind = \"color\";\n/**\n * Instance Colors\n */\nVertexBuffer.ColorInstanceKind = \"instanceColor\";\n/**\n * Matrix indices (for bones)\n */\nVertexBuffer.MatricesIndicesKind = \"matricesIndices\";\n/**\n * Matrix weights (for bones)\n */\nVertexBuffer.MatricesWeightsKind = \"matricesWeights\";\n/**\n * Additional matrix indices (for bones)\n */\nVertexBuffer.MatricesIndicesExtraKind = \"matricesIndicesExtra\";\n/**\n * Additional matrix weights (for bones)\n */\nVertexBuffer.MatricesWeightsExtraKind = \"matricesWeightsExtra\";\n//# sourceMappingURL=buffer.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize, SerializationHelper, serializeAsVector3 } from \"../Misc/decorators.js\";\nimport { SmartArray } from \"../Misc/smartArray.js\";\nimport { Tools } from \"../Misc/tools.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Matrix, Vector3, Quaternion } from \"../Maths/math.vector.js\";\nimport { Node } from \"../node.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { GetClass } from \"../Misc/typeStore.js\";\nimport { _WarnImport } from \"../Misc/devTools.js\";\nimport { Viewport } from \"../Maths/math.viewport.js\";\nimport { Frustum } from \"../Maths/math.frustum.js\";\n\n/**\n * This is the base class of all the camera used in the application.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras\n */\nexport class Camera extends Node {\n /**\n * Define the current local position of the camera in the scene\n */\n get position() {\n return this._position;\n }\n set position(newPosition) {\n this._position = newPosition;\n }\n /**\n * The vector the camera should consider as up.\n * (default is Vector3(0, 1, 0) aka Vector3.Up())\n */\n set upVector(vec) {\n this._upVector = vec;\n }\n get upVector() {\n return this._upVector;\n }\n /**\n * The screen area in scene units squared\n */\n get screenArea() {\n var _a, _b, _c, _d;\n let x = 0;\n let y = 0;\n if (this.mode === Camera.PERSPECTIVE_CAMERA) {\n if (this.fovMode === Camera.FOVMODE_VERTICAL_FIXED) {\n y = this.minZ * 2 * Math.tan(this.fov / 2);\n x = this.getEngine().getAspectRatio(this) * y;\n }\n else {\n x = this.minZ * 2 * Math.tan(this.fov / 2);\n y = x / this.getEngine().getAspectRatio(this);\n }\n }\n else {\n const halfWidth = this.getEngine().getRenderWidth() / 2.0;\n const halfHeight = this.getEngine().getRenderHeight() / 2.0;\n x = ((_a = this.orthoRight) !== null && _a !== void 0 ? _a : halfWidth) - ((_b = this.orthoLeft) !== null && _b !== void 0 ? _b : -halfWidth);\n y = ((_c = this.orthoTop) !== null && _c !== void 0 ? _c : halfHeight) - ((_d = this.orthoBottom) !== null && _d !== void 0 ? _d : -halfHeight);\n }\n return x * y;\n }\n set orthoLeft(value) {\n this._orthoLeft = value;\n for (const rigCamera of this._rigCameras) {\n rigCamera.orthoLeft = value;\n }\n }\n get orthoLeft() {\n return this._orthoLeft;\n }\n set orthoRight(value) {\n this._orthoRight = value;\n for (const rigCamera of this._rigCameras) {\n rigCamera.orthoRight = value;\n }\n }\n get orthoRight() {\n return this._orthoRight;\n }\n set orthoBottom(value) {\n this._orthoBottom = value;\n for (const rigCamera of this._rigCameras) {\n rigCamera.orthoBottom = value;\n }\n }\n get orthoBottom() {\n return this._orthoBottom;\n }\n set orthoTop(value) {\n this._orthoTop = value;\n for (const rigCamera of this._rigCameras) {\n rigCamera.orthoTop = value;\n }\n }\n get orthoTop() {\n return this._orthoTop;\n }\n set mode(mode) {\n this._mode = mode;\n // Pass the mode down to the rig cameras\n for (const rigCamera of this._rigCameras) {\n rigCamera.mode = mode;\n }\n }\n get mode() {\n return this._mode;\n }\n /**\n * Instantiates a new camera object.\n * This should not be used directly but through the inherited cameras: ArcRotate, Free...\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras\n * @param name Defines the name of the camera in the scene\n * @param position Defines the position of the camera\n * @param scene Defines the scene the camera belongs too\n * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene\n */\n constructor(name, position, scene, setActiveOnSceneIfNoneActive = true) {\n super(name, scene);\n /** @internal */\n this._position = Vector3.Zero();\n this._upVector = Vector3.Up();\n /**\n * Define the current limit on the left side for an orthographic camera\n * In scene unit\n */\n this._orthoLeft = null;\n /**\n * Define the current limit on the right side for an orthographic camera\n * In scene unit\n */\n this._orthoRight = null;\n /**\n * Define the current limit on the bottom side for an orthographic camera\n * In scene unit\n */\n this._orthoBottom = null;\n /**\n * Define the current limit on the top side for an orthographic camera\n * In scene unit\n */\n this._orthoTop = null;\n /**\n * Field Of View is set in Radians. (default is 0.8)\n */\n this.fov = 0.8;\n /**\n * Projection plane tilt around the X axis (horizontal), set in Radians. (default is 0)\n * Can be used to make vertical lines in world space actually vertical on the screen.\n * See https://forum.babylonjs.com/t/add-vertical-shift-to-3ds-max-exporter-babylon-cameras/17480\n */\n this.projectionPlaneTilt = 0;\n /**\n * Define the minimum distance the camera can see from.\n * This is important to note that the depth buffer are not infinite and the closer it starts\n * the more your scene might encounter depth fighting issue.\n */\n this.minZ = 1;\n /**\n * Define the maximum distance the camera can see to.\n * This is important to note that the depth buffer are not infinite and the further it end\n * the more your scene might encounter depth fighting issue.\n */\n this.maxZ = 10000.0;\n /**\n * Define the default inertia of the camera.\n * This helps giving a smooth feeling to the camera movement.\n */\n this.inertia = 0.9;\n /**\n * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.ORTHOGRAPHIC_CAMERA)\n */\n this._mode = Camera.PERSPECTIVE_CAMERA;\n /**\n * Define whether the camera is intermediate.\n * This is useful to not present the output directly to the screen in case of rig without post process for instance\n */\n this.isIntermediate = false;\n /**\n * Define the viewport of the camera.\n * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.\n */\n this.viewport = new Viewport(0, 0, 1.0, 1.0);\n /**\n * Restricts the camera to viewing objects with the same layerMask.\n * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0\n */\n this.layerMask = 0x0fffffff;\n /**\n * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)\n */\n this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;\n /**\n * Rig mode of the camera.\n * This is useful to create the camera with two \"eyes\" instead of one to create VR or stereoscopic scenes.\n * This is normally controlled byt the camera themselves as internal use.\n */\n this.cameraRigMode = Camera.RIG_MODE_NONE;\n /**\n * Defines the list of custom render target which are rendered to and then used as the input to this camera's render. Eg. display another camera view on a TV in the main scene\n * This is pretty helpful if you wish to make a camera render to a texture you could reuse somewhere\n * else in the scene. (Eg. security camera)\n *\n * To change the final output target of the camera, camera.outputRenderTarget should be used instead (eg. webXR renders to a render target corresponding to an HMD)\n */\n this.customRenderTargets = new Array();\n /**\n * When set, the camera will render to this render target instead of the default canvas\n *\n * If the desire is to use the output of a camera as a texture in the scene consider using camera.customRenderTargets instead\n */\n this.outputRenderTarget = null;\n /**\n * Observable triggered when the camera view matrix has changed.\n */\n this.onViewMatrixChangedObservable = new Observable();\n /**\n * Observable triggered when the camera Projection matrix has changed.\n */\n this.onProjectionMatrixChangedObservable = new Observable();\n /**\n * Observable triggered when the inputs have been processed.\n */\n this.onAfterCheckInputsObservable = new Observable();\n /**\n * Observable triggered when reset has been called and applied to the camera.\n */\n this.onRestoreStateObservable = new Observable();\n /**\n * Is this camera a part of a rig system?\n */\n this.isRigCamera = false;\n /** @internal */\n this._rigCameras = new Array();\n this._webvrViewMatrix = Matrix.Identity();\n /** @internal */\n this._skipRendering = false;\n /** @internal */\n this._projectionMatrix = new Matrix();\n /** @internal */\n this._postProcesses = new Array();\n /** @internal */\n this._activeMeshes = new SmartArray(256);\n this._globalPosition = Vector3.Zero();\n /** @internal */\n this._computedViewMatrix = Matrix.Identity();\n this._doNotComputeProjectionMatrix = false;\n this._transformMatrix = Matrix.Zero();\n this._refreshFrustumPlanes = true;\n this._absoluteRotation = Quaternion.Identity();\n /** @internal */\n this._isCamera = true;\n /** @internal */\n this._isLeftCamera = false;\n /** @internal */\n this._isRightCamera = false;\n this.getScene().addCamera(this);\n if (setActiveOnSceneIfNoneActive && !this.getScene().activeCamera) {\n this.getScene().activeCamera = this;\n }\n this.position = position;\n this.renderPassId = this.getScene().getEngine().createRenderPassId(`Camera ${name}`);\n }\n /**\n * Store current camera state (fov, position, etc..)\n * @returns the camera\n */\n storeState() {\n this._stateStored = true;\n this._storedFov = this.fov;\n return this;\n }\n /**\n * Restores the camera state values if it has been stored. You must call storeState() first\n */\n _restoreStateValues() {\n if (!this._stateStored) {\n return false;\n }\n this.fov = this._storedFov;\n return true;\n }\n /**\n * Restored camera state. You must call storeState() first.\n * @returns true if restored and false otherwise\n */\n restoreState() {\n if (this._restoreStateValues()) {\n this.onRestoreStateObservable.notifyObservers(this);\n return true;\n }\n return false;\n }\n /**\n * Gets the class name of the camera.\n * @returns the class name\n */\n getClassName() {\n return \"Camera\";\n }\n /**\n * Gets a string representation of the camera useful for debug purpose.\n * @param fullDetails Defines that a more verbose level of logging is required\n * @returns the string representation\n */\n toString(fullDetails) {\n let ret = \"Name: \" + this.name;\n ret += \", type: \" + this.getClassName();\n if (this.animations) {\n for (let i = 0; i < this.animations.length; i++) {\n ret += \", animation[0]: \" + this.animations[i].toString(fullDetails);\n }\n }\n return ret;\n }\n /**\n * Automatically tilts the projection plane, using `projectionPlaneTilt`, to correct the perspective effect on vertical lines.\n */\n applyVerticalCorrection() {\n const rot = this.absoluteRotation.toEulerAngles();\n this.projectionPlaneTilt = this._scene.useRightHandedSystem ? -rot.x : rot.x;\n }\n /**\n * Gets the current world space position of the camera.\n */\n get globalPosition() {\n return this._globalPosition;\n }\n /**\n * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)\n * @returns the active meshe list\n */\n getActiveMeshes() {\n return this._activeMeshes;\n }\n /**\n * Check whether a mesh is part of the current active mesh list of the camera\n * @param mesh Defines the mesh to check\n * @returns true if active, false otherwise\n */\n isActiveMesh(mesh) {\n return this._activeMeshes.indexOf(mesh) !== -1;\n }\n /**\n * Is this camera ready to be used/rendered\n * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)\n * @returns true if the camera is ready\n */\n isReady(completeCheck = false) {\n if (completeCheck) {\n for (const pp of this._postProcesses) {\n if (pp && !pp.isReady()) {\n return false;\n }\n }\n }\n return super.isReady(completeCheck);\n }\n /** @internal */\n _initCache() {\n super._initCache();\n this._cache.position = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._cache.upVector = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._cache.mode = undefined;\n this._cache.minZ = undefined;\n this._cache.maxZ = undefined;\n this._cache.fov = undefined;\n this._cache.fovMode = undefined;\n this._cache.aspectRatio = undefined;\n this._cache.orthoLeft = undefined;\n this._cache.orthoRight = undefined;\n this._cache.orthoBottom = undefined;\n this._cache.orthoTop = undefined;\n this._cache.renderWidth = undefined;\n this._cache.renderHeight = undefined;\n }\n /**\n * @internal\n */\n _updateCache(ignoreParentClass) {\n if (!ignoreParentClass) {\n super._updateCache();\n }\n this._cache.position.copyFrom(this.position);\n this._cache.upVector.copyFrom(this.upVector);\n }\n /** @internal */\n _isSynchronized() {\n return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();\n }\n /** @internal */\n _isSynchronizedViewMatrix() {\n if (!super._isSynchronized()) {\n return false;\n }\n return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();\n }\n /** @internal */\n _isSynchronizedProjectionMatrix() {\n let check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;\n if (!check) {\n return false;\n }\n const engine = this.getEngine();\n if (this.mode === Camera.PERSPECTIVE_CAMERA) {\n check =\n this._cache.fov === this.fov &&\n this._cache.fovMode === this.fovMode &&\n this._cache.aspectRatio === engine.getAspectRatio(this) &&\n this._cache.projectionPlaneTilt === this.projectionPlaneTilt;\n }\n else {\n check =\n this._cache.orthoLeft === this.orthoLeft &&\n this._cache.orthoRight === this.orthoRight &&\n this._cache.orthoBottom === this.orthoBottom &&\n this._cache.orthoTop === this.orthoTop &&\n this._cache.renderWidth === engine.getRenderWidth() &&\n this._cache.renderHeight === engine.getRenderHeight();\n }\n return check;\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n * This function is here because typescript removes the typing of the last function.\n * @param _ignored defines an ignored parameter kept for backward compatibility.\n * @param _noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(_ignored, _noPreventDefault) { }\n /**\n * Detach the current controls from the specified dom element.\n * This function is here because typescript removes the typing of the last function.\n * @param _ignored defines an ignored parameter kept for backward compatibility.\n */\n detachControl(_ignored) { }\n /**\n * Update the camera state according to the different inputs gathered during the frame.\n */\n update() {\n this._checkInputs();\n if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {\n this._updateRigCameras();\n }\n // Attempt to update the camera's view and projection matrices.\n // This call is being made because these matrices are no longer being updated\n // as a part of the picking ray process (in addition to scene.render).\n this.getViewMatrix();\n this.getProjectionMatrix();\n }\n /** @internal */\n _checkInputs() {\n this.onAfterCheckInputsObservable.notifyObservers(this);\n }\n /** @internal */\n get rigCameras() {\n return this._rigCameras;\n }\n /**\n * Gets the post process used by the rig cameras\n */\n get rigPostProcess() {\n return this._rigPostProcess;\n }\n /**\n * Internal, gets the first post process.\n * @returns the first post process to be run on this camera.\n */\n _getFirstPostProcess() {\n for (let ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {\n if (this._postProcesses[ppIndex] !== null) {\n return this._postProcesses[ppIndex];\n }\n }\n return null;\n }\n _cascadePostProcessesToRigCams() {\n // invalidate framebuffer\n const firstPostProcess = this._getFirstPostProcess();\n if (firstPostProcess) {\n firstPostProcess.markTextureDirty();\n }\n // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera\n for (let i = 0, len = this._rigCameras.length; i < len; i++) {\n const cam = this._rigCameras[i];\n const rigPostProcess = cam._rigPostProcess;\n // for VR rig, there does not have to be a post process\n if (rigPostProcess) {\n const isPass = rigPostProcess.getEffectName() === \"pass\";\n if (isPass) {\n // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses\n cam.isIntermediate = this._postProcesses.length === 0;\n }\n cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);\n rigPostProcess.markTextureDirty();\n }\n else {\n cam._postProcesses = this._postProcesses.slice(0);\n }\n }\n }\n /**\n * Attach a post process to the camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses#attach-postprocess\n * @param postProcess The post process to attach to the camera\n * @param insertAt The position of the post process in case several of them are in use in the scene\n * @returns the position the post process has been inserted at\n */\n attachPostProcess(postProcess, insertAt = null) {\n if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {\n Logger.Error(\"You're trying to reuse a post process not defined as reusable.\");\n return 0;\n }\n if (insertAt == null || insertAt < 0) {\n this._postProcesses.push(postProcess);\n }\n else if (this._postProcesses[insertAt] === null) {\n this._postProcesses[insertAt] = postProcess;\n }\n else {\n this._postProcesses.splice(insertAt, 0, postProcess);\n }\n this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated\n // Update prePass\n if (this._scene.prePassRenderer) {\n this._scene.prePassRenderer.markAsDirty();\n }\n return this._postProcesses.indexOf(postProcess);\n }\n /**\n * Detach a post process to the camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses#attach-postprocess\n * @param postProcess The post process to detach from the camera\n */\n detachPostProcess(postProcess) {\n const idx = this._postProcesses.indexOf(postProcess);\n if (idx !== -1) {\n this._postProcesses[idx] = null;\n }\n // Update prePass\n if (this._scene.prePassRenderer) {\n this._scene.prePassRenderer.markAsDirty();\n }\n this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated\n }\n /**\n * Gets the current world matrix of the camera\n */\n getWorldMatrix() {\n if (this._isSynchronizedViewMatrix()) {\n return this._worldMatrix;\n }\n // Getting the the view matrix will also compute the world matrix.\n this.getViewMatrix();\n return this._worldMatrix;\n }\n /** @internal */\n _getViewMatrix() {\n return Matrix.Identity();\n }\n /**\n * Gets the current view matrix of the camera.\n * @param force forces the camera to recompute the matrix without looking at the cached state\n * @returns the view matrix\n */\n getViewMatrix(force) {\n if (!force && this._isSynchronizedViewMatrix()) {\n return this._computedViewMatrix;\n }\n this.updateCache();\n this._computedViewMatrix = this._getViewMatrix();\n this._currentRenderId = this.getScene().getRenderId();\n this._childUpdateId++;\n this._refreshFrustumPlanes = true;\n if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {\n this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);\n }\n // Notify parent camera if rig camera is changed\n if (this.parent && this.parent.onViewMatrixChangedObservable) {\n this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent);\n }\n this.onViewMatrixChangedObservable.notifyObservers(this);\n this._computedViewMatrix.invertToRef(this._worldMatrix);\n return this._computedViewMatrix;\n }\n /**\n * Freeze the projection matrix.\n * It will prevent the cache check of the camera projection compute and can speed up perf\n * if no parameter of the camera are meant to change\n * @param projection Defines manually a projection if necessary\n */\n freezeProjectionMatrix(projection) {\n this._doNotComputeProjectionMatrix = true;\n if (projection !== undefined) {\n this._projectionMatrix = projection;\n }\n }\n /**\n * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.\n */\n unfreezeProjectionMatrix() {\n this._doNotComputeProjectionMatrix = false;\n }\n /**\n * Gets the current projection matrix of the camera.\n * @param force forces the camera to recompute the matrix without looking at the cached state\n * @returns the projection matrix\n */\n getProjectionMatrix(force) {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {\n return this._projectionMatrix;\n }\n // Cache\n this._cache.mode = this.mode;\n this._cache.minZ = this.minZ;\n this._cache.maxZ = this.maxZ;\n // Matrix\n this._refreshFrustumPlanes = true;\n const engine = this.getEngine();\n const scene = this.getScene();\n const reverseDepth = engine.useReverseDepthBuffer;\n if (this.mode === Camera.PERSPECTIVE_CAMERA) {\n this._cache.fov = this.fov;\n this._cache.fovMode = this.fovMode;\n this._cache.aspectRatio = engine.getAspectRatio(this);\n this._cache.projectionPlaneTilt = this.projectionPlaneTilt;\n if (this.minZ <= 0) {\n this.minZ = 0.1;\n }\n let getProjectionMatrix;\n if (scene.useRightHandedSystem) {\n getProjectionMatrix = Matrix.PerspectiveFovRHToRef;\n }\n else {\n getProjectionMatrix = Matrix.PerspectiveFovLHToRef;\n }\n getProjectionMatrix(this.fov, engine.getAspectRatio(this), reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED, engine.isNDCHalfZRange, this.projectionPlaneTilt, reverseDepth);\n }\n else {\n const halfWidth = engine.getRenderWidth() / 2.0;\n const halfHeight = engine.getRenderHeight() / 2.0;\n if (scene.useRightHandedSystem) {\n Matrix.OrthoOffCenterRHToRef((_a = this.orthoLeft) !== null && _a !== void 0 ? _a : -halfWidth, (_b = this.orthoRight) !== null && _b !== void 0 ? _b : halfWidth, (_c = this.orthoBottom) !== null && _c !== void 0 ? _c : -halfHeight, (_d = this.orthoTop) !== null && _d !== void 0 ? _d : halfHeight, reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this._projectionMatrix, engine.isNDCHalfZRange);\n }\n else {\n Matrix.OrthoOffCenterLHToRef((_e = this.orthoLeft) !== null && _e !== void 0 ? _e : -halfWidth, (_f = this.orthoRight) !== null && _f !== void 0 ? _f : halfWidth, (_g = this.orthoBottom) !== null && _g !== void 0 ? _g : -halfHeight, (_h = this.orthoTop) !== null && _h !== void 0 ? _h : halfHeight, reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this._projectionMatrix, engine.isNDCHalfZRange);\n }\n this._cache.orthoLeft = this.orthoLeft;\n this._cache.orthoRight = this.orthoRight;\n this._cache.orthoBottom = this.orthoBottom;\n this._cache.orthoTop = this.orthoTop;\n this._cache.renderWidth = engine.getRenderWidth();\n this._cache.renderHeight = engine.getRenderHeight();\n }\n this.onProjectionMatrixChangedObservable.notifyObservers(this);\n return this._projectionMatrix;\n }\n /**\n * Gets the transformation matrix (ie. the multiplication of view by projection matrices)\n * @returns a Matrix\n */\n getTransformationMatrix() {\n this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);\n return this._transformMatrix;\n }\n _updateFrustumPlanes() {\n if (!this._refreshFrustumPlanes) {\n return;\n }\n this.getTransformationMatrix();\n if (!this._frustumPlanes) {\n this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix);\n }\n else {\n Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);\n }\n this._refreshFrustumPlanes = false;\n }\n /**\n * Checks if a cullable object (mesh...) is in the camera frustum\n * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check\n * @param target The object to check\n * @param checkRigCameras If the rig cameras should be checked (eg. with webVR camera both eyes should be checked) (Default: false)\n * @returns true if the object is in frustum otherwise false\n */\n isInFrustum(target, checkRigCameras = false) {\n this._updateFrustumPlanes();\n if (checkRigCameras && this.rigCameras.length > 0) {\n let result = false;\n this.rigCameras.forEach((cam) => {\n cam._updateFrustumPlanes();\n result = result || target.isInFrustum(cam._frustumPlanes);\n });\n return result;\n }\n else {\n return target.isInFrustum(this._frustumPlanes);\n }\n }\n /**\n * Checks if a cullable object (mesh...) is in the camera frustum\n * Unlike isInFrustum this checks the full bounding box\n * @param target The object to check\n * @returns true if the object is in frustum otherwise false\n */\n isCompletelyInFrustum(target) {\n this._updateFrustumPlanes();\n return target.isCompletelyInFrustum(this._frustumPlanes);\n }\n /**\n * Gets a ray in the forward direction from the camera.\n * @param length Defines the length of the ray to create\n * @param transform Defines the transform to apply to the ray, by default the world matrix is used to create a workd space ray\n * @param origin Defines the start point of the ray which defaults to the camera position\n * @returns the forward ray\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getForwardRay(length = 100, transform, origin) {\n throw _WarnImport(\"Ray\");\n }\n /**\n * Gets a ray in the forward direction from the camera.\n * @param refRay the ray to (re)use when setting the values\n * @param length Defines the length of the ray to create\n * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray\n * @param origin Defines the start point of the ray which defaults to the camera position\n * @returns the forward ray\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getForwardRayToRef(refRay, length = 100, transform, origin) {\n throw _WarnImport(\"Ray\");\n }\n /**\n * Releases resources associated with this node.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n dispose(doNotRecurse, disposeMaterialAndTextures = false) {\n // Observables\n this.onViewMatrixChangedObservable.clear();\n this.onProjectionMatrixChangedObservable.clear();\n this.onAfterCheckInputsObservable.clear();\n this.onRestoreStateObservable.clear();\n // Inputs\n if (this.inputs) {\n this.inputs.clear();\n }\n // Animations\n this.getScene().stopAnimation(this);\n // Remove from scene\n this.getScene().removeCamera(this);\n while (this._rigCameras.length > 0) {\n const camera = this._rigCameras.pop();\n if (camera) {\n camera.dispose();\n }\n }\n if (this._parentContainer) {\n const index = this._parentContainer.cameras.indexOf(this);\n if (index > -1) {\n this._parentContainer.cameras.splice(index, 1);\n }\n this._parentContainer = null;\n }\n // Postprocesses\n if (this._rigPostProcess) {\n this._rigPostProcess.dispose(this);\n this._rigPostProcess = null;\n this._postProcesses.length = 0;\n }\n else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {\n this._rigPostProcess = null;\n this._postProcesses.length = 0;\n }\n else {\n let i = this._postProcesses.length;\n while (--i >= 0) {\n const postProcess = this._postProcesses[i];\n if (postProcess) {\n postProcess.dispose(this);\n }\n }\n }\n // Render targets\n let i = this.customRenderTargets.length;\n while (--i >= 0) {\n this.customRenderTargets[i].dispose();\n }\n this.customRenderTargets.length = 0;\n // Active Meshes\n this._activeMeshes.dispose();\n this.getScene().getEngine().releaseRenderPassId(this.renderPassId);\n super.dispose(doNotRecurse, disposeMaterialAndTextures);\n }\n /**\n * Gets the left camera of a rig setup in case of Rigged Camera\n */\n get isLeftCamera() {\n return this._isLeftCamera;\n }\n /**\n * Gets the right camera of a rig setup in case of Rigged Camera\n */\n get isRightCamera() {\n return this._isRightCamera;\n }\n /**\n * Gets the left camera of a rig setup in case of Rigged Camera\n */\n get leftCamera() {\n if (this._rigCameras.length < 1) {\n return null;\n }\n return this._rigCameras[0];\n }\n /**\n * Gets the right camera of a rig setup in case of Rigged Camera\n */\n get rightCamera() {\n if (this._rigCameras.length < 2) {\n return null;\n }\n return this._rigCameras[1];\n }\n /**\n * Gets the left camera target of a rig setup in case of Rigged Camera\n * @returns the target position\n */\n getLeftTarget() {\n if (this._rigCameras.length < 1) {\n return null;\n }\n return this._rigCameras[0].getTarget();\n }\n /**\n * Gets the right camera target of a rig setup in case of Rigged Camera\n * @returns the target position\n */\n getRightTarget() {\n if (this._rigCameras.length < 2) {\n return null;\n }\n return this._rigCameras[1].getTarget();\n }\n /**\n * @internal\n */\n setCameraRigMode(mode, rigParams) {\n if (this.cameraRigMode === mode) {\n return;\n }\n while (this._rigCameras.length > 0) {\n const camera = this._rigCameras.pop();\n if (camera) {\n camera.dispose();\n }\n }\n this.cameraRigMode = mode;\n this._cameraRigParams = {};\n //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,\n //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced\n this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;\n this._cameraRigParams.stereoHalfAngle = Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);\n // create the rig cameras, unless none\n if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {\n const leftCamera = this.createRigCamera(this.name + \"_L\", 0);\n if (leftCamera) {\n leftCamera._isLeftCamera = true;\n }\n const rightCamera = this.createRigCamera(this.name + \"_R\", 1);\n if (rightCamera) {\n rightCamera._isRightCamera = true;\n }\n if (leftCamera && rightCamera) {\n this._rigCameras.push(leftCamera);\n this._rigCameras.push(rightCamera);\n }\n }\n this._setRigMode(rigParams);\n this._cascadePostProcessesToRigCams();\n this.update();\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _setRigMode(rigParams) {\n // no-op\n }\n /** @internal */\n _getVRProjectionMatrix() {\n Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix, true, this.getEngine().isNDCHalfZRange);\n this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);\n return this._projectionMatrix;\n }\n _updateCameraRotationMatrix() {\n //Here for WebVR\n }\n _updateWebVRCameraRotationMatrix() {\n //Here for WebVR\n }\n /**\n * This function MUST be overwritten by the different WebVR cameras available.\n * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.\n * @internal\n */\n _getWebVRProjectionMatrix() {\n return Matrix.Identity();\n }\n /**\n * This function MUST be overwritten by the different WebVR cameras available.\n * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.\n * @internal\n */\n _getWebVRViewMatrix() {\n return Matrix.Identity();\n }\n /**\n * @internal\n */\n setCameraRigParameter(name, value) {\n if (!this._cameraRigParams) {\n this._cameraRigParams = {};\n }\n this._cameraRigParams[name] = value;\n //provisionnally:\n if (name === \"interaxialDistance\") {\n this._cameraRigParams.stereoHalfAngle = Tools.ToRadians(value / 0.0637);\n }\n }\n /**\n * needs to be overridden by children so sub has required properties to be copied\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n createRigCamera(name, cameraIndex) {\n return null;\n }\n /**\n * May need to be overridden by children\n * @internal\n */\n _updateRigCameras() {\n for (let i = 0; i < this._rigCameras.length; i++) {\n this._rigCameras[i].minZ = this.minZ;\n this._rigCameras[i].maxZ = this.maxZ;\n this._rigCameras[i].fov = this.fov;\n this._rigCameras[i].upVector.copyFrom(this.upVector);\n }\n // only update viewport when ANAGLYPH\n if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {\n this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;\n }\n }\n /** @internal */\n _setupInputs() { }\n /**\n * Serialiaze the camera setup to a json representation\n * @returns the JSON representation\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this);\n serializationObject.uniqueId = this.uniqueId;\n // Type\n serializationObject.type = this.getClassName();\n // Parent\n if (this.parent) {\n this.parent._serializeAsParent(serializationObject);\n }\n if (this.inputs) {\n this.inputs.serialize(serializationObject);\n }\n // Animations\n SerializationHelper.AppendSerializedAnimations(this, serializationObject);\n serializationObject.ranges = this.serializeAnimationRanges();\n serializationObject.isEnabled = this.isEnabled();\n return serializationObject;\n }\n /**\n * Clones the current camera.\n * @param name The cloned camera name\n * @param newParent The cloned camera's new parent (none by default)\n * @returns the cloned camera\n */\n clone(name, newParent = null) {\n const camera = SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);\n camera.name = name;\n camera.parent = newParent;\n this.onClonedObservable.notifyObservers(camera);\n return camera;\n }\n /**\n * Gets the direction of the camera relative to a given local axis.\n * @param localAxis Defines the reference axis to provide a relative direction.\n * @returns the direction\n */\n getDirection(localAxis) {\n const result = Vector3.Zero();\n this.getDirectionToRef(localAxis, result);\n return result;\n }\n /**\n * Returns the current camera absolute rotation\n */\n get absoluteRotation() {\n this.getWorldMatrix().decompose(undefined, this._absoluteRotation);\n return this._absoluteRotation;\n }\n /**\n * Gets the direction of the camera relative to a given local axis into a passed vector.\n * @param localAxis Defines the reference axis to provide a relative direction.\n * @param result Defines the vector to store the result in\n */\n getDirectionToRef(localAxis, result) {\n Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);\n }\n /**\n * Gets a camera constructor for a given camera type\n * @param type The type of the camera to construct (should be equal to one of the camera class name)\n * @param name The name of the camera the result will be able to instantiate\n * @param scene The scene the result will construct the camera in\n * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes\n * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side\n * @returns a factory method to construct the camera\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static GetConstructorFromName(type, name, scene, interaxial_distance = 0, isStereoscopicSideBySide = true) {\n const constructorFunc = Node.Construct(type, name, scene, {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n interaxial_distance: interaxial_distance,\n isStereoscopicSideBySide: isStereoscopicSideBySide,\n });\n if (constructorFunc) {\n return constructorFunc;\n }\n // Default to universal camera\n return () => Camera._CreateDefaultParsedCamera(name, scene);\n }\n /**\n * Compute the world matrix of the camera.\n * @returns the camera world matrix\n */\n computeWorldMatrix() {\n return this.getWorldMatrix();\n }\n /**\n * Parse a JSON and creates the camera from the parsed information\n * @param parsedCamera The JSON to parse\n * @param scene The scene to instantiate the camera in\n * @returns the newly constructed camera\n */\n static Parse(parsedCamera, scene) {\n const type = parsedCamera.type;\n const construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);\n const camera = SerializationHelper.Parse(construct, parsedCamera, scene);\n // Parent\n if (parsedCamera.parentId !== undefined) {\n camera._waitingParentId = parsedCamera.parentId;\n }\n // Parent instance index\n if (parsedCamera.parentInstanceIndex !== undefined) {\n camera._waitingParentInstanceIndex = parsedCamera.parentInstanceIndex;\n }\n //If camera has an input manager, let it parse inputs settings\n if (camera.inputs) {\n camera.inputs.parse(parsedCamera);\n camera._setupInputs();\n }\n if (parsedCamera.upVector) {\n camera.upVector = Vector3.FromArray(parsedCamera.upVector); // need to force the upVector\n }\n if (camera.setPosition) {\n // need to force position\n camera.position.copyFromFloats(0, 0, 0);\n camera.setPosition(Vector3.FromArray(parsedCamera.position));\n }\n // Target\n if (parsedCamera.target) {\n if (camera.setTarget) {\n camera.setTarget(Vector3.FromArray(parsedCamera.target));\n }\n }\n // Apply 3d rig, when found\n if (parsedCamera.cameraRigMode) {\n const rigParams = parsedCamera.interaxial_distance ? { interaxialDistance: parsedCamera.interaxial_distance } : {};\n camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);\n }\n // Animations\n if (parsedCamera.animations) {\n for (let animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {\n const parsedAnimation = parsedCamera.animations[animationIndex];\n const internalClass = GetClass(\"BABYLON.Animation\");\n if (internalClass) {\n camera.animations.push(internalClass.Parse(parsedAnimation));\n }\n }\n Node.ParseAnimationRanges(camera, parsedCamera, scene);\n }\n if (parsedCamera.autoAnimate) {\n scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);\n }\n // Check if isEnabled is defined to be back compatible with prior serialized versions.\n if (parsedCamera.isEnabled !== undefined) {\n camera.setEnabled(parsedCamera.isEnabled);\n }\n return camera;\n }\n}\n/**\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nCamera._CreateDefaultParsedCamera = (name, scene) => {\n throw _WarnImport(\"UniversalCamera\");\n};\n/**\n * This is the default projection mode used by the cameras.\n * It helps recreating a feeling of perspective and better appreciate depth.\n * This is the best way to simulate real life cameras.\n */\nCamera.PERSPECTIVE_CAMERA = 0;\n/**\n * This helps creating camera with an orthographic mode.\n * Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object.\n */\nCamera.ORTHOGRAPHIC_CAMERA = 1;\n/**\n * This is the default FOV mode for perspective cameras.\n * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.\n */\nCamera.FOVMODE_VERTICAL_FIXED = 0;\n/**\n * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.\n */\nCamera.FOVMODE_HORIZONTAL_FIXED = 1;\n/**\n * This specifies there is no need for a camera rig.\n * Basically only one eye is rendered corresponding to the camera.\n */\nCamera.RIG_MODE_NONE = 0;\n/**\n * Simulates a camera Rig with one blue eye and one red eye.\n * This can be use with 3d blue and red glasses.\n */\nCamera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;\n/**\n * Defines that both eyes of the camera will be rendered side by side with a parallel target.\n */\nCamera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;\n/**\n * Defines that both eyes of the camera will be rendered side by side with a none parallel target.\n */\nCamera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;\n/**\n * Defines that both eyes of the camera will be rendered over under each other.\n */\nCamera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;\n/**\n * Defines that both eyes of the camera will be rendered on successive lines interlaced for passive 3d monitors.\n */\nCamera.RIG_MODE_STEREOSCOPIC_INTERLACED = 14;\n/**\n * Defines that both eyes of the camera should be renderered in a VR mode (carbox).\n */\nCamera.RIG_MODE_VR = 20;\n/**\n * Defines that both eyes of the camera should be renderered in a VR mode (webVR).\n */\nCamera.RIG_MODE_WEBVR = 21;\n/**\n * Custom rig mode allowing rig cameras to be populated manually with any number of cameras\n */\nCamera.RIG_MODE_CUSTOM = 22;\n/**\n * Defines if by default attaching controls should prevent the default javascript event to continue.\n */\nCamera.ForceAttachControlToAlwaysPreventDefault = false;\n__decorate([\n serializeAsVector3(\"position\")\n], Camera.prototype, \"_position\", void 0);\n__decorate([\n serializeAsVector3(\"upVector\")\n], Camera.prototype, \"_upVector\", void 0);\n__decorate([\n serialize()\n], Camera.prototype, \"orthoLeft\", null);\n__decorate([\n serialize()\n], Camera.prototype, \"orthoRight\", null);\n__decorate([\n serialize()\n], Camera.prototype, \"orthoBottom\", null);\n__decorate([\n serialize()\n], Camera.prototype, \"orthoTop\", null);\n__decorate([\n serialize()\n], Camera.prototype, \"fov\", void 0);\n__decorate([\n serialize()\n], Camera.prototype, \"projectionPlaneTilt\", void 0);\n__decorate([\n serialize()\n], Camera.prototype, \"minZ\", void 0);\n__decorate([\n serialize()\n], Camera.prototype, \"maxZ\", void 0);\n__decorate([\n serialize()\n], Camera.prototype, \"inertia\", void 0);\n__decorate([\n serialize()\n], Camera.prototype, \"mode\", null);\n__decorate([\n serialize()\n], Camera.prototype, \"layerMask\", void 0);\n__decorate([\n serialize()\n], Camera.prototype, \"fovMode\", void 0);\n__decorate([\n serialize()\n], Camera.prototype, \"cameraRigMode\", void 0);\n__decorate([\n serialize()\n], Camera.prototype, \"interaxialDistance\", void 0);\n__decorate([\n serialize()\n], Camera.prototype, \"isStereoscopicSideBySide\", void 0);\n//# sourceMappingURL=camera.js.map","export * from \"./EXT_lights_image_based.js\";\nexport * from \"./EXT_mesh_gpu_instancing.js\";\nexport * from \"./EXT_meshopt_compression.js\";\nexport * from \"./EXT_texture_webp.js\";\nexport * from \"./KHR_draco_mesh_compression.js\";\nexport * from \"./KHR_lights_punctual.js\";\nexport * from \"./KHR_materials_pbrSpecularGlossiness.js\";\nexport * from \"./KHR_materials_unlit.js\";\nexport * from \"./KHR_materials_clearcoat.js\";\nexport * from \"./KHR_materials_iridescence.js\";\nexport * from \"./KHR_materials_anisotropy.js\";\nexport * from \"./KHR_materials_emissive_strength.js\";\nexport * from \"./KHR_materials_sheen.js\";\nexport * from \"./KHR_materials_specular.js\";\nexport * from \"./KHR_materials_ior.js\";\nexport * from \"./KHR_materials_variants.js\";\nexport * from \"./KHR_materials_transmission.js\";\nexport * from \"./KHR_materials_translucency.js\";\nexport * from \"./KHR_materials_volume.js\";\nexport * from \"./KHR_mesh_quantization.js\";\nexport * from \"./KHR_texture_basisu.js\";\nexport * from \"./KHR_texture_transform.js\";\nexport * from \"./KHR_xmp_json_ld.js\";\nexport * from \"./KHR_animation_pointer.js\";\nexport * from \"./MSFT_audio_emitter.js\";\nexport * from \"./MSFT_lod.js\";\nexport * from \"./MSFT_minecraftMesh.js\";\nexport * from \"./MSFT_sRGBFactors.js\";\nexport * from \"./ExtrasAsMetadata.js\";\n//# sourceMappingURL=index.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./glTFLoader.js\";\nexport * from \"./glTFLoaderExtension.js\";\nexport * from \"./glTFLoaderInterfaces.js\";\nexport * from \"./Extensions/index.js\";\n//# sourceMappingURL=index.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./glTFFileLoader.js\";\nexport * from \"./glTFValidation.js\";\nimport * as GLTF1 from \"./1.0/index.js\";\nimport * as GLTF2 from \"./2.0/index.js\";\nexport { GLTF1, GLTF2 };\n//# sourceMappingURL=index.js.map","import {\n Engine,\n Animation,\n AbstractMesh,\n ArcRotateCamera,\n Color4,\n Vector3,\n HemisphericLight,\n Scene,\n Tools,\n SceneLoader,\n} from \"@babylonjs/core\";\nimport \"@babylonjs/loaders/glTF\";\nimport { BabylonjsProps } from \"babylonjs-hook\";\n\nlet scene: Scene;\nlet offscreenCanvas: OffscreenCanvas;\nlet camera: ArcRotateCamera;\nlet drone: AbstractMesh;\n\n// ZOOM animation\nconst getZoomAnimation = (duration: number) => {\n const frameRate = 20;\n const lastFrame = duration * frameRate;\n\n const zoom = new Animation(\n \"zoom\",\n \"position\",\n 20,\n Animation.ANIMATIONTYPE_VECTOR3,\n Animation.ANIMATIONLOOPMODE_CONSTANT\n );\n zoom.setKeys([\n { frame: 0, value: new Vector3(0, 70, 0) },\n { frame: lastFrame, value: new Vector3(3, 7, -15) },\n ]);\n\n return {\n animation: [zoom],\n lastFrame,\n };\n};\n\n// SCENE READY handler\nconst onSceneReady = async (scene: Scene) => {\n // transparent background\n scene.clearColor = Color4.FromHexString(\"#000\");\n\n // camera creation\n camera = new ArcRotateCamera(\n \"camera1\",\n Tools.ToRadians(0),\n Tools.ToRadians(0),\n 15,\n Vector3.Zero(),\n scene\n );\n\n // figure creation\n const { meshes } = await SceneLoader.ImportMeshAsync(\n \"\",\n \"buster_drone/\",\n \"drone.gltf\",\n scene\n );\n drone = meshes[0];\n drone.scaling = new Vector3(3, 3, 3);\n drone.alwaysSelectAsActiveMesh = true;\n drone.enablePointerMoveEvents = true;\n drone.isNearPickable = true;\n\n // get canvas\n const canvas = scene.getEngine().getRenderingCanvas();\n\n // camera settings\n camera.allowUpsideDown;\n camera.wheelDeltaPercentage = 0.01;\n camera.lowerRadiusLimit = 8;\n camera.upperRadiusLimit = 70;\n camera.setTarget(drone);\n camera.attachControl(canvas, false);\n\n // lights\n const light = new HemisphericLight(\"light\", new Vector3(0, 10, 10), scene);\n const light2 = new HemisphericLight(\"light2\", new Vector3(0, -10, 10), scene);\n light.intensity = 2.5;\n light2.intensity = 1.5;\n\n // animation\n const { animation, lastFrame } = getZoomAnimation(4);\n scene.beginDirectAnimation(camera, animation, 0, lastFrame, false);\n};\n\n// BABYLON INITIALIZATION\nconst initBabylonScene = ({\n antialias,\n engineOptions,\n adaptToDeviceRatio,\n sceneOptions,\n onRender,\n onSceneReady,\n canvas,\n}: BabylonjsProps & { canvas: OffscreenCanvas }) => {\n const engine = new Engine(\n canvas,\n antialias,\n engineOptions,\n adaptToDeviceRatio\n );\n const scene = new Scene(engine, sceneOptions);\n if (scene.isReady()) {\n onSceneReady(scene);\n } else {\n scene.onReadyObservable.addOnce((scene) => onSceneReady(scene));\n }\n\n engine.runRenderLoop(() => {\n if (typeof onRender === \"function\") onRender(scene);\n scene.render();\n });\n\n return { scene, canvas };\n};\n\n// WORKER EVENT HANDLER\nself.onmessage = async ({\n data: { canvas, width, height, dispose, wheel, x, y },\n}: MessageEvent<{\n canvas?: OffscreenCanvas;\n width?: number;\n height?: number;\n dispose?: boolean;\n wheel?: number;\n x?: number;\n y?: number;\n}>) => {\n // initialization\n if (canvas) {\n const elements = initBabylonScene({\n antialias: true,\n onSceneReady,\n canvas: canvas,\n });\n scene = elements.scene;\n offscreenCanvas = elements.canvas;\n self.postMessage(\"ready\");\n }\n\n // resize\n if (scene && offscreenCanvas && !canvas && width && height) {\n offscreenCanvas.width = width;\n offscreenCanvas.height = height;\n scene.getEngine().resize(true);\n }\n\n // dispose\n if (dispose && scene) {\n scene.getEngine().dispose();\n }\n\n // zoom\n if (camera && wheel) {\n camera.radius = camera.radius + wheel * camera.wheelDeltaPercentage;\n }\n\n // camera rotation\n if (scene && x !== undefined && y !== undefined) {\n camera.alpha -= x / 100;\n camera.beta -= y / 100;\n }\n};\n","\n/**\n * Abstract class used to decouple action Manager from scene and meshes.\n * Do not instantiate.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\nexport class AbstractActionManager {\n constructor() {\n /** Gets the cursor to use when hovering items */\n this.hoverCursor = \"\";\n /** Gets the list of actions */\n this.actions = new Array();\n /**\n * Gets or sets a boolean indicating that the manager is recursive meaning that it can trigger action from children\n */\n this.isRecursive = false;\n }\n /**\n * Does exist one action manager with at least one trigger\n **/\n static get HasTriggers() {\n for (const t in AbstractActionManager.Triggers) {\n if (Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers, t)) {\n return true;\n }\n }\n return false;\n }\n /**\n * Does exist one action manager with at least one pick trigger\n **/\n static get HasPickTriggers() {\n for (const t in AbstractActionManager.Triggers) {\n if (Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers, t)) {\n const tAsInt = parseInt(t);\n if (tAsInt >= 1 && tAsInt <= 7) {\n return true;\n }\n }\n }\n return false;\n }\n /**\n * Does exist one action manager that handles actions of a given trigger\n * @param trigger defines the trigger to be tested\n * @returns a boolean indicating whether the trigger is handled by at least one action manager\n **/\n static HasSpecificTrigger(trigger) {\n for (const t in AbstractActionManager.Triggers) {\n if (Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers, t)) {\n const tAsInt = parseInt(t);\n if (tAsInt === trigger) {\n return true;\n }\n }\n }\n return false;\n }\n}\n/** Gets the list of active triggers */\nAbstractActionManager.Triggers = {};\n//# sourceMappingURL=abstractActionManager.js.map","/**\n * ActionEvent is the event being sent when an action is triggered.\n */\nexport class ActionEvent {\n /**\n * Creates a new ActionEvent\n * @param source The mesh or sprite that triggered the action\n * @param pointerX The X mouse cursor position at the time of the event\n * @param pointerY The Y mouse cursor position at the time of the event\n * @param meshUnderPointer The mesh that is currently pointed at (can be null)\n * @param sourceEvent the original (browser) event that triggered the ActionEvent\n * @param additionalData additional data for the event\n */\n constructor(\n /** The mesh or sprite that triggered the action */\n source, \n /** The X mouse cursor position at the time of the event */\n pointerX, \n /** The Y mouse cursor position at the time of the event */\n pointerY, \n /** The mesh that is currently pointed at (can be null) */\n meshUnderPointer, \n /** the original (browser) event that triggered the ActionEvent */\n sourceEvent, \n /** additional data for the event */\n additionalData) {\n this.source = source;\n this.pointerX = pointerX;\n this.pointerY = pointerY;\n this.meshUnderPointer = meshUnderPointer;\n this.sourceEvent = sourceEvent;\n this.additionalData = additionalData;\n }\n /**\n * Helper function to auto-create an ActionEvent from a source mesh.\n * @param source The source mesh that triggered the event\n * @param evt The original (browser) event\n * @param additionalData additional data for the event\n * @returns the new ActionEvent\n */\n static CreateNew(source, evt, additionalData) {\n const scene = source.getScene();\n return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer || source, evt, additionalData);\n }\n /**\n * Helper function to auto-create an ActionEvent from a source sprite\n * @param source The source sprite that triggered the event\n * @param scene Scene associated with the sprite\n * @param evt The original (browser) event\n * @param additionalData additional data for the event\n * @returns the new ActionEvent\n */\n static CreateNewFromSprite(source, scene, evt, additionalData) {\n return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);\n }\n /**\n * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew\n * @param scene the scene where the event occurred\n * @param evt The original (browser) event\n * @returns the new ActionEvent\n */\n static CreateNewFromScene(scene, evt) {\n return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);\n }\n /**\n * Helper function to auto-create an ActionEvent from a primitive\n * @param prim defines the target primitive\n * @param pointerPos defines the pointer position\n * @param evt The original (browser) event\n * @param additionalData additional data for the event\n * @returns the new ActionEvent\n */\n static CreateNewFromPrimitive(prim, pointerPos, evt, additionalData) {\n return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);\n }\n}\n//# sourceMappingURL=actionEvent.js.map","/**\n * Class used to store gfx data (like WebGLBuffer)\n */\nexport class DataBuffer {\n /**\n * Gets the underlying buffer\n */\n get underlyingResource() {\n return null;\n }\n /**\n * Constructs the buffer\n */\n constructor() {\n /**\n * Gets or sets the number of objects referencing this buffer\n */\n this.references = 0;\n /** Gets or sets the size of the underlying buffer */\n this.capacity = 0;\n /**\n * Gets or sets a boolean indicating if the buffer contains 32bits indices\n */\n this.is32Bits = false;\n this.uniqueId = DataBuffer._Counter++;\n }\n}\nDataBuffer._Counter = 0;\n//# sourceMappingURL=dataBuffer.js.map","/**\n * @internal\n */\nexport class IntersectionInfo {\n constructor(bu, bv, distance) {\n this.bu = bu;\n this.bv = bv;\n this.distance = distance;\n this.faceId = 0;\n this.subMeshId = 0;\n }\n}\n//# sourceMappingURL=intersectionInfo.js.map","import { Vector3 } from \"../Maths/math.vector.js\";\n/**\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class _MeshCollisionData {\n constructor() {\n this._checkCollisions = false;\n this._collisionMask = -1;\n this._collisionGroup = -1;\n this._surroundingMeshes = null;\n this._collider = null;\n this._oldPositionForCollisions = new Vector3(0, 0, 0);\n this._diffPositionForCollisions = new Vector3(0, 0, 0);\n this._collisionResponse = true;\n }\n}\n//# sourceMappingURL=meshCollisionData.js.map","import { Vector3, Vector2, TmpVectors } from \"../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\n/**\n * Information about the result of picking within a scene\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/picking_collisions\n */\nexport class PickingInfo {\n constructor() {\n /**\n * If the pick collided with an object\n */\n this.hit = false;\n /**\n * Distance away where the pick collided\n */\n this.distance = 0;\n /**\n * The location of pick collision\n */\n this.pickedPoint = null;\n /**\n * The mesh corresponding the pick collision\n */\n this.pickedMesh = null;\n /** (See getTextureCoordinates) The barycentric U coordinate that is used when calculating the texture coordinates of the collision.*/\n this.bu = 0;\n /** (See getTextureCoordinates) The barycentric V coordinate that is used when calculating the texture coordinates of the collision.*/\n this.bv = 0;\n /** The index of the face on the mesh that was picked, or the index of the Line if the picked Mesh is a LinesMesh */\n this.faceId = -1;\n /** The index of the face on the subMesh that was picked, or the index of the Line if the picked Mesh is a LinesMesh */\n this.subMeshFaceId = -1;\n /** Id of the submesh that was picked */\n this.subMeshId = 0;\n /** If a sprite was picked, this will be the sprite the pick collided with */\n this.pickedSprite = null;\n /** If we are picking a mesh with thin instance, this will give you the picked thin instance */\n this.thinInstanceIndex = -1;\n /**\n * The ray that was used to perform the picking.\n */\n this.ray = null;\n /**\n * If a mesh was used to do the picking (eg. 6dof controller) as a \"near interaction\", this will be populated.\n */\n this.originMesh = null;\n /**\n * The aim-space transform of the input used for picking, if it is an XR input source.\n */\n this.aimTransform = null;\n /**\n * The grip-space transform of the input used for picking, if it is an XR input source.\n * Some XR sources, such as input coming from head mounted displays, do not have this.\n */\n this.gripTransform = null;\n }\n /**\n * Gets the normal corresponding to the face the pick collided with\n * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)\n * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map (default: true)\n * @returns The normal corresponding to the face the pick collided with\n * @remarks Note that the returned normal will always point towards the picking ray.\n */\n getNormal(useWorldCoordinates = false, useVerticesNormals = true) {\n if (!this.pickedMesh || (useVerticesNormals && !this.pickedMesh.isVerticesDataPresent(VertexBuffer.NormalKind))) {\n return null;\n }\n let indices = this.pickedMesh.getIndices();\n if ((indices === null || indices === void 0 ? void 0 : indices.length) === 0) {\n indices = null;\n }\n let result;\n const tmp0 = TmpVectors.Vector3[0];\n const tmp1 = TmpVectors.Vector3[1];\n const tmp2 = TmpVectors.Vector3[2];\n if (useVerticesNormals) {\n const normals = this.pickedMesh.getVerticesData(VertexBuffer.NormalKind);\n let normal0 = indices\n ? Vector3.FromArrayToRef(normals, indices[this.faceId * 3] * 3, tmp0)\n : tmp0.copyFromFloats(normals[this.faceId * 3 * 3], normals[this.faceId * 3 * 3 + 1], normals[this.faceId * 3 * 3 + 2]);\n let normal1 = indices\n ? Vector3.FromArrayToRef(normals, indices[this.faceId * 3 + 1] * 3, tmp1)\n : tmp1.copyFromFloats(normals[(this.faceId * 3 + 1) * 3], normals[(this.faceId * 3 + 1) * 3 + 1], normals[(this.faceId * 3 + 1) * 3 + 2]);\n let normal2 = indices\n ? Vector3.FromArrayToRef(normals, indices[this.faceId * 3 + 2] * 3, tmp2)\n : tmp2.copyFromFloats(normals[(this.faceId * 3 + 2) * 3], normals[(this.faceId * 3 + 2) * 3 + 1], normals[(this.faceId * 3 + 2) * 3 + 2]);\n normal0 = normal0.scale(this.bu);\n normal1 = normal1.scale(this.bv);\n normal2 = normal2.scale(1.0 - this.bu - this.bv);\n result = new Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);\n }\n else {\n const positions = this.pickedMesh.getVerticesData(VertexBuffer.PositionKind);\n const vertex1 = indices\n ? Vector3.FromArrayToRef(positions, indices[this.faceId * 3] * 3, tmp0)\n : tmp0.copyFromFloats(positions[this.faceId * 3 * 3], positions[this.faceId * 3 * 3 + 1], positions[this.faceId * 3 * 3 + 2]);\n const vertex2 = indices\n ? Vector3.FromArrayToRef(positions, indices[this.faceId * 3 + 1] * 3, tmp1)\n : tmp1.copyFromFloats(positions[(this.faceId * 3 + 1) * 3], positions[(this.faceId * 3 + 1) * 3 + 1], positions[(this.faceId * 3 + 1) * 3 + 2]);\n const vertex3 = indices\n ? Vector3.FromArrayToRef(positions, indices[this.faceId * 3 + 2] * 3, tmp2)\n : tmp2.copyFromFloats(positions[(this.faceId * 3 + 2) * 3], positions[(this.faceId * 3 + 2) * 3 + 1], positions[(this.faceId * 3 + 2) * 3 + 2]);\n const p1p2 = vertex1.subtract(vertex2);\n const p3p2 = vertex3.subtract(vertex2);\n result = Vector3.Cross(p1p2, p3p2);\n }\n const transformNormalToWorld = (pickedMesh, n) => {\n let wm = pickedMesh.getWorldMatrix();\n if (pickedMesh.nonUniformScaling) {\n TmpVectors.Matrix[0].copyFrom(wm);\n wm = TmpVectors.Matrix[0];\n wm.setTranslationFromFloats(0, 0, 0);\n wm.invert();\n wm.transposeToRef(TmpVectors.Matrix[1]);\n wm = TmpVectors.Matrix[1];\n }\n Vector3.TransformNormalToRef(n, wm, n);\n };\n if (useWorldCoordinates) {\n transformNormalToWorld(this.pickedMesh, result);\n }\n if (this.ray) {\n const normalForDirectionChecking = TmpVectors.Vector3[0].copyFrom(result);\n if (!useWorldCoordinates) {\n // the normal has not been transformed to world space as part as the normal processing, so we must do it now\n transformNormalToWorld(this.pickedMesh, normalForDirectionChecking);\n }\n // Flip the normal if the picking ray is in the same direction.\n if (Vector3.Dot(normalForDirectionChecking, this.ray.direction) > 0) {\n result.negateInPlace();\n }\n }\n result.normalize();\n return result;\n }\n /**\n * Gets the texture coordinates of where the pick occurred\n * @param uvSet The UV set to use to calculate the texture coordinates (default: VertexBuffer.UVKind)\n * @returns The vector containing the coordinates of the texture\n */\n getTextureCoordinates(uvSet = VertexBuffer.UVKind) {\n if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(uvSet)) {\n return null;\n }\n const indices = this.pickedMesh.getIndices();\n if (!indices) {\n return null;\n }\n const uvs = this.pickedMesh.getVerticesData(uvSet);\n if (!uvs) {\n return null;\n }\n let uv0 = Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);\n let uv1 = Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);\n let uv2 = Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);\n uv0 = uv0.scale(this.bu);\n uv1 = uv1.scale(this.bv);\n uv2 = uv2.scale(1.0 - this.bu - this.bv);\n return new Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);\n }\n}\n//# sourceMappingURL=pickingInfo.js.map","/**\n * Options used to control default behaviors regarding compatibility support\n */\nexport class CompatibilityOptions {\n}\n/**\n * Defines if the system should use OpenGL convention for UVs when creating geometry or loading .babylon files (false by default)\n */\nCompatibilityOptions.UseOpenGLOrientationForUV = false;\n//# sourceMappingURL=compatibilityOptions.js.map","import { ArrayTools } from \"../Misc/arrayTools.js\";\nimport { Matrix, Vector3 } from \"../Maths/math.vector.js\";\nimport { Epsilon } from \"../Maths/math.constants.js\";\n/**\n * Class used to store bounding box information\n */\nexport class BoundingBox {\n /**\n * Creates a new bounding box\n * @param min defines the minimum vector (in local space)\n * @param max defines the maximum vector (in local space)\n * @param worldMatrix defines the new world matrix\n */\n constructor(min, max, worldMatrix) {\n /**\n * Gets the 8 vectors representing the bounding box in local space\n */\n this.vectors = ArrayTools.BuildArray(8, Vector3.Zero);\n /**\n * Gets the center of the bounding box in local space\n */\n this.center = Vector3.Zero();\n /**\n * Gets the center of the bounding box in world space\n */\n this.centerWorld = Vector3.Zero();\n /**\n * Gets the extend size in local space\n */\n this.extendSize = Vector3.Zero();\n /**\n * Gets the extend size in world space\n */\n this.extendSizeWorld = Vector3.Zero();\n /**\n * Gets the OBB (object bounding box) directions\n */\n this.directions = ArrayTools.BuildArray(3, Vector3.Zero);\n /**\n * Gets the 8 vectors representing the bounding box in world space\n */\n this.vectorsWorld = ArrayTools.BuildArray(8, Vector3.Zero);\n /**\n * Gets the minimum vector in world space\n */\n this.minimumWorld = Vector3.Zero();\n /**\n * Gets the maximum vector in world space\n */\n this.maximumWorld = Vector3.Zero();\n /**\n * Gets the minimum vector in local space\n */\n this.minimum = Vector3.Zero();\n /**\n * Gets the maximum vector in local space\n */\n this.maximum = Vector3.Zero();\n /** @internal */\n this._drawWrapperFront = null;\n /** @internal */\n this._drawWrapperBack = null;\n this.reConstruct(min, max, worldMatrix);\n }\n // Methods\n /**\n * Recreates the entire bounding box from scratch as if we call the constructor in place\n * @param min defines the new minimum vector (in local space)\n * @param max defines the new maximum vector (in local space)\n * @param worldMatrix defines the new world matrix\n */\n reConstruct(min, max, worldMatrix) {\n const minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;\n const vectors = this.vectors;\n this.minimum.copyFromFloats(minX, minY, minZ);\n this.maximum.copyFromFloats(maxX, maxY, maxZ);\n vectors[0].copyFromFloats(minX, minY, minZ);\n vectors[1].copyFromFloats(maxX, maxY, maxZ);\n vectors[2].copyFromFloats(maxX, minY, minZ);\n vectors[3].copyFromFloats(minX, maxY, minZ);\n vectors[4].copyFromFloats(minX, minY, maxZ);\n vectors[5].copyFromFloats(maxX, maxY, minZ);\n vectors[6].copyFromFloats(minX, maxY, maxZ);\n vectors[7].copyFromFloats(maxX, minY, maxZ);\n // OBB\n max.addToRef(min, this.center).scaleInPlace(0.5);\n max.subtractToRef(min, this.extendSize).scaleInPlace(0.5);\n this._worldMatrix = worldMatrix || Matrix.IdentityReadOnly;\n this._update(this._worldMatrix);\n }\n /**\n * Scale the current bounding box by applying a scale factor\n * @param factor defines the scale factor to apply\n * @returns the current bounding box\n */\n scale(factor) {\n const tmpVectors = BoundingBox._TmpVector3;\n const diff = this.maximum.subtractToRef(this.minimum, tmpVectors[0]);\n const len = diff.length();\n diff.normalizeFromLength(len);\n const distance = len * factor;\n const newRadius = diff.scaleInPlace(distance * 0.5);\n const min = this.center.subtractToRef(newRadius, tmpVectors[1]);\n const max = this.center.addToRef(newRadius, tmpVectors[2]);\n this.reConstruct(min, max, this._worldMatrix);\n return this;\n }\n /**\n * Gets the world matrix of the bounding box\n * @returns a matrix\n */\n getWorldMatrix() {\n return this._worldMatrix;\n }\n /**\n * @internal\n */\n _update(world) {\n const minWorld = this.minimumWorld;\n const maxWorld = this.maximumWorld;\n const directions = this.directions;\n const vectorsWorld = this.vectorsWorld;\n const vectors = this.vectors;\n if (!world.isIdentity()) {\n minWorld.setAll(Number.MAX_VALUE);\n maxWorld.setAll(-Number.MAX_VALUE);\n for (let index = 0; index < 8; ++index) {\n const v = vectorsWorld[index];\n Vector3.TransformCoordinatesToRef(vectors[index], world, v);\n minWorld.minimizeInPlace(v);\n maxWorld.maximizeInPlace(v);\n }\n // Extend\n maxWorld.subtractToRef(minWorld, this.extendSizeWorld).scaleInPlace(0.5);\n maxWorld.addToRef(minWorld, this.centerWorld).scaleInPlace(0.5);\n }\n else {\n minWorld.copyFrom(this.minimum);\n maxWorld.copyFrom(this.maximum);\n for (let index = 0; index < 8; ++index) {\n vectorsWorld[index].copyFrom(vectors[index]);\n }\n // Extend\n this.extendSizeWorld.copyFrom(this.extendSize);\n this.centerWorld.copyFrom(this.center);\n }\n Vector3.FromArrayToRef(world.m, 0, directions[0]);\n Vector3.FromArrayToRef(world.m, 4, directions[1]);\n Vector3.FromArrayToRef(world.m, 8, directions[2]);\n this._worldMatrix = world;\n }\n /**\n * Tests if the bounding box is intersecting the frustum planes\n * @param frustumPlanes defines the frustum planes to test\n * @returns true if there is an intersection\n */\n isInFrustum(frustumPlanes) {\n return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);\n }\n /**\n * Tests if the bounding box is entirely inside the frustum planes\n * @param frustumPlanes defines the frustum planes to test\n * @returns true if there is an inclusion\n */\n isCompletelyInFrustum(frustumPlanes) {\n return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);\n }\n /**\n * Tests if a point is inside the bounding box\n * @param point defines the point to test\n * @returns true if the point is inside the bounding box\n */\n intersectsPoint(point) {\n const min = this.minimumWorld;\n const max = this.maximumWorld;\n const minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;\n const pointX = point.x, pointY = point.y, pointZ = point.z;\n const delta = -Epsilon;\n if (maxX - pointX < delta || delta > pointX - minX) {\n return false;\n }\n if (maxY - pointY < delta || delta > pointY - minY) {\n return false;\n }\n if (maxZ - pointZ < delta || delta > pointZ - minZ) {\n return false;\n }\n return true;\n }\n /**\n * Tests if the bounding box intersects with a bounding sphere\n * @param sphere defines the sphere to test\n * @returns true if there is an intersection\n */\n intersectsSphere(sphere) {\n return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);\n }\n /**\n * Tests if the bounding box intersects with a box defined by a min and max vectors\n * @param min defines the min vector to use\n * @param max defines the max vector to use\n * @returns true if there is an intersection\n */\n intersectsMinMax(min, max) {\n const myMin = this.minimumWorld;\n const myMax = this.maximumWorld;\n const myMinX = myMin.x, myMinY = myMin.y, myMinZ = myMin.z, myMaxX = myMax.x, myMaxY = myMax.y, myMaxZ = myMax.z;\n const minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;\n if (myMaxX < minX || myMinX > maxX) {\n return false;\n }\n if (myMaxY < minY || myMinY > maxY) {\n return false;\n }\n if (myMaxZ < minZ || myMinZ > maxZ) {\n return false;\n }\n return true;\n }\n /**\n * Disposes the resources of the class\n */\n dispose() {\n var _a, _b;\n (_a = this._drawWrapperFront) === null || _a === void 0 ? void 0 : _a.dispose();\n (_b = this._drawWrapperBack) === null || _b === void 0 ? void 0 : _b.dispose();\n }\n // Statics\n /**\n * Tests if two bounding boxes are intersections\n * @param box0 defines the first box to test\n * @param box1 defines the second box to test\n * @returns true if there is an intersection\n */\n static Intersects(box0, box1) {\n return box0.intersectsMinMax(box1.minimumWorld, box1.maximumWorld);\n }\n /**\n * Tests if a bounding box defines by a min/max vectors intersects a sphere\n * @param minPoint defines the minimum vector of the bounding box\n * @param maxPoint defines the maximum vector of the bounding box\n * @param sphereCenter defines the sphere center\n * @param sphereRadius defines the sphere radius\n * @returns true if there is an intersection\n */\n static IntersectsSphere(minPoint, maxPoint, sphereCenter, sphereRadius) {\n const vector = BoundingBox._TmpVector3[0];\n Vector3.ClampToRef(sphereCenter, minPoint, maxPoint, vector);\n const num = Vector3.DistanceSquared(sphereCenter, vector);\n return num <= sphereRadius * sphereRadius;\n }\n /**\n * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes\n * @param boundingVectors defines an array of 8 vectors representing a bounding box\n * @param frustumPlanes defines the frustum planes to test\n * @returns true if there is an inclusion\n */\n static IsCompletelyInFrustum(boundingVectors, frustumPlanes) {\n for (let p = 0; p < 6; ++p) {\n const frustumPlane = frustumPlanes[p];\n for (let i = 0; i < 8; ++i) {\n if (frustumPlane.dotCoordinate(boundingVectors[i]) < 0) {\n return false;\n }\n }\n }\n return true;\n }\n /**\n * Tests if a bounding box defined with 8 vectors intersects frustum planes\n * @param boundingVectors defines an array of 8 vectors representing a bounding box\n * @param frustumPlanes defines the frustum planes to test\n * @returns true if there is an intersection\n */\n static IsInFrustum(boundingVectors, frustumPlanes) {\n for (let p = 0; p < 6; ++p) {\n let canReturnFalse = true;\n const frustumPlane = frustumPlanes[p];\n for (let i = 0; i < 8; ++i) {\n if (frustumPlane.dotCoordinate(boundingVectors[i]) >= 0) {\n canReturnFalse = false;\n break;\n }\n }\n if (canReturnFalse) {\n return false;\n }\n }\n return true;\n }\n}\nBoundingBox._TmpVector3 = ArrayTools.BuildArray(3, Vector3.Zero);\n//# sourceMappingURL=boundingBox.js.map","import { ArrayTools } from \"../Misc/arrayTools.js\";\nimport { TmpVectors } from \"../Maths/math.vector.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\n\nimport { BoundingBox } from \"./boundingBox.js\";\nimport { BoundingSphere } from \"./boundingSphere.js\";\nconst _result0 = { min: 0, max: 0 };\nconst _result1 = { min: 0, max: 0 };\nconst computeBoxExtents = (axis, box, result) => {\n const p = Vector3.Dot(box.centerWorld, axis);\n const r0 = Math.abs(Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;\n const r1 = Math.abs(Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;\n const r2 = Math.abs(Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;\n const r = r0 + r1 + r2;\n result.min = p - r;\n result.max = p + r;\n};\nconst axisOverlap = (axis, box0, box1) => {\n computeBoxExtents(axis, box0, _result0);\n computeBoxExtents(axis, box1, _result1);\n return !(_result0.min > _result1.max || _result1.min > _result0.max);\n};\n/**\n * Info for a bounding data of a mesh\n */\nexport class BoundingInfo {\n /**\n * Constructs bounding info\n * @param minimum min vector of the bounding box/sphere\n * @param maximum max vector of the bounding box/sphere\n * @param worldMatrix defines the new world matrix\n */\n constructor(minimum, maximum, worldMatrix) {\n this._isLocked = false;\n this.boundingBox = new BoundingBox(minimum, maximum, worldMatrix);\n this.boundingSphere = new BoundingSphere(minimum, maximum, worldMatrix);\n }\n /**\n * Recreates the entire bounding info from scratch as if we call the constructor in place\n * @param min defines the new minimum vector (in local space)\n * @param max defines the new maximum vector (in local space)\n * @param worldMatrix defines the new world matrix\n */\n reConstruct(min, max, worldMatrix) {\n this.boundingBox.reConstruct(min, max, worldMatrix);\n this.boundingSphere.reConstruct(min, max, worldMatrix);\n }\n /**\n * min vector of the bounding box/sphere\n */\n get minimum() {\n return this.boundingBox.minimum;\n }\n /**\n * max vector of the bounding box/sphere\n */\n get maximum() {\n return this.boundingBox.maximum;\n }\n /**\n * If the info is locked and won't be updated to avoid perf overhead\n */\n get isLocked() {\n return this._isLocked;\n }\n set isLocked(value) {\n this._isLocked = value;\n }\n // Methods\n /**\n * Updates the bounding sphere and box\n * @param world world matrix to be used to update\n */\n update(world) {\n if (this._isLocked) {\n return;\n }\n this.boundingBox._update(world);\n this.boundingSphere._update(world);\n }\n /**\n * Recreate the bounding info to be centered around a specific point given a specific extend.\n * @param center New center of the bounding info\n * @param extend New extend of the bounding info\n * @returns the current bounding info\n */\n centerOn(center, extend) {\n const minimum = BoundingInfo._TmpVector3[0].copyFrom(center).subtractInPlace(extend);\n const maximum = BoundingInfo._TmpVector3[1].copyFrom(center).addInPlace(extend);\n this.boundingBox.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix());\n this.boundingSphere.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix());\n return this;\n }\n /**\n * Grows the bounding info to include the given point.\n * @param point The point that will be included in the current bounding info (in local space)\n * @returns the current bounding info\n */\n encapsulate(point) {\n const minimum = Vector3.Minimize(this.minimum, point);\n const maximum = Vector3.Maximize(this.maximum, point);\n this.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix());\n return this;\n }\n /**\n * Grows the bounding info to encapsulate the given bounding info.\n * @param toEncapsulate The bounding info that will be encapsulated in the current bounding info\n * @returns the current bounding info\n */\n encapsulateBoundingInfo(toEncapsulate) {\n const invw = TmpVectors.Matrix[0];\n this.boundingBox.getWorldMatrix().invertToRef(invw);\n const v = TmpVectors.Vector3[0];\n Vector3.TransformCoordinatesToRef(toEncapsulate.boundingBox.minimumWorld, invw, v);\n this.encapsulate(v);\n Vector3.TransformCoordinatesToRef(toEncapsulate.boundingBox.maximumWorld, invw, v);\n this.encapsulate(v);\n return this;\n }\n /**\n * Scale the current bounding info by applying a scale factor\n * @param factor defines the scale factor to apply\n * @returns the current bounding info\n */\n scale(factor) {\n this.boundingBox.scale(factor);\n this.boundingSphere.scale(factor);\n return this;\n }\n /**\n * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.\n * @param frustumPlanes defines the frustum to test\n * @param strategy defines the strategy to use for the culling (default is BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD)\n * The different strategies available are:\n * * BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD most accurate but slower @see https://doc.babylonjs.com/typedoc/classes/BABYLON.AbstractMesh#CULLINGSTRATEGY_STANDARD\n * * BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY faster but less accurate @see https://doc.babylonjs.com/typedoc/classes/BABYLON.AbstractMesh#CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY\n * * BABYLON.AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION can be faster if always visible @see https://doc.babylonjs.com/typedoc/classes/BABYLON.AbstractMesh#CULLINGSTRATEGY_OPTIMISTIC_INCLUSION\n * * BABYLON.AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY can be faster if always visible @see https://doc.babylonjs.com/typedoc/classes/BABYLON.AbstractMesh#CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY\n * @returns true if the bounding info is in the frustum planes\n */\n isInFrustum(frustumPlanes, strategy = 0) {\n const inclusionTest = strategy === 2 || strategy === 3;\n if (inclusionTest) {\n if (this.boundingSphere.isCenterInFrustum(frustumPlanes)) {\n return true;\n }\n }\n if (!this.boundingSphere.isInFrustum(frustumPlanes)) {\n return false;\n }\n const bSphereOnlyTest = strategy === 1 || strategy === 3;\n if (bSphereOnlyTest) {\n return true;\n }\n return this.boundingBox.isInFrustum(frustumPlanes);\n }\n /**\n * Gets the world distance between the min and max points of the bounding box\n */\n get diagonalLength() {\n const boundingBox = this.boundingBox;\n const diag = boundingBox.maximumWorld.subtractToRef(boundingBox.minimumWorld, BoundingInfo._TmpVector3[0]);\n return diag.length();\n }\n /**\n * Checks if a cullable object (mesh...) is in the camera frustum\n * Unlike isInFrustum this checks the full bounding box\n * @param frustumPlanes Camera near/planes\n * @returns true if the object is in frustum otherwise false\n */\n isCompletelyInFrustum(frustumPlanes) {\n return this.boundingBox.isCompletelyInFrustum(frustumPlanes);\n }\n /**\n * @internal\n */\n _checkCollision(collider) {\n return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);\n }\n /**\n * Checks if a point is inside the bounding box and bounding sphere or the mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/mesh_intersect\n * @param point the point to check intersection with\n * @returns if the point intersects\n */\n intersectsPoint(point) {\n if (!this.boundingSphere.centerWorld) {\n return false;\n }\n if (!this.boundingSphere.intersectsPoint(point)) {\n return false;\n }\n if (!this.boundingBox.intersectsPoint(point)) {\n return false;\n }\n return true;\n }\n /**\n * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/mesh_intersect\n * @param boundingInfo the bounding info to check intersection with\n * @param precise if the intersection should be done using OBB\n * @returns if the bounding info intersects\n */\n intersects(boundingInfo, precise) {\n if (!BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {\n return false;\n }\n if (!BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {\n return false;\n }\n if (!precise) {\n return true;\n }\n const box0 = this.boundingBox;\n const box1 = boundingInfo.boundingBox;\n if (!axisOverlap(box0.directions[0], box0, box1)) {\n return false;\n }\n if (!axisOverlap(box0.directions[1], box0, box1)) {\n return false;\n }\n if (!axisOverlap(box0.directions[2], box0, box1)) {\n return false;\n }\n if (!axisOverlap(box1.directions[0], box0, box1)) {\n return false;\n }\n if (!axisOverlap(box1.directions[1], box0, box1)) {\n return false;\n }\n if (!axisOverlap(box1.directions[2], box0, box1)) {\n return false;\n }\n if (!axisOverlap(Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1)) {\n return false;\n }\n if (!axisOverlap(Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1)) {\n return false;\n }\n if (!axisOverlap(Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1)) {\n return false;\n }\n if (!axisOverlap(Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1)) {\n return false;\n }\n if (!axisOverlap(Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1)) {\n return false;\n }\n if (!axisOverlap(Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1)) {\n return false;\n }\n if (!axisOverlap(Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1)) {\n return false;\n }\n if (!axisOverlap(Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1)) {\n return false;\n }\n if (!axisOverlap(Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1)) {\n return false;\n }\n return true;\n }\n}\nBoundingInfo._TmpVector3 = ArrayTools.BuildArray(2, Vector3.Zero);\n//# sourceMappingURL=boundingInfo.js.map","import { ArrayTools } from \"../Misc/arrayTools.js\";\nimport { Matrix, Vector3 } from \"../Maths/math.vector.js\";\n/**\n * Class used to store bounding sphere information\n */\nexport class BoundingSphere {\n /**\n * Creates a new bounding sphere\n * @param min defines the minimum vector (in local space)\n * @param max defines the maximum vector (in local space)\n * @param worldMatrix defines the new world matrix\n */\n constructor(min, max, worldMatrix) {\n /**\n * Gets the center of the bounding sphere in local space\n */\n this.center = Vector3.Zero();\n /**\n * Gets the center of the bounding sphere in world space\n */\n this.centerWorld = Vector3.Zero();\n /**\n * Gets the minimum vector in local space\n */\n this.minimum = Vector3.Zero();\n /**\n * Gets the maximum vector in local space\n */\n this.maximum = Vector3.Zero();\n this.reConstruct(min, max, worldMatrix);\n }\n /**\n * Recreates the entire bounding sphere from scratch as if we call the constructor in place\n * @param min defines the new minimum vector (in local space)\n * @param max defines the new maximum vector (in local space)\n * @param worldMatrix defines the new world matrix\n */\n reConstruct(min, max, worldMatrix) {\n this.minimum.copyFrom(min);\n this.maximum.copyFrom(max);\n const distance = Vector3.Distance(min, max);\n max.addToRef(min, this.center).scaleInPlace(0.5);\n this.radius = distance * 0.5;\n this._update(worldMatrix || Matrix.IdentityReadOnly);\n }\n /**\n * Scale the current bounding sphere by applying a scale factor\n * @param factor defines the scale factor to apply\n * @returns the current bounding box\n */\n scale(factor) {\n const newRadius = this.radius * factor;\n const tmpVectors = BoundingSphere._TmpVector3;\n const tempRadiusVector = tmpVectors[0].setAll(newRadius);\n const min = this.center.subtractToRef(tempRadiusVector, tmpVectors[1]);\n const max = this.center.addToRef(tempRadiusVector, tmpVectors[2]);\n this.reConstruct(min, max, this._worldMatrix);\n return this;\n }\n /**\n * Gets the world matrix of the bounding box\n * @returns a matrix\n */\n getWorldMatrix() {\n return this._worldMatrix;\n }\n // Methods\n /**\n * @internal\n */\n _update(worldMatrix) {\n if (!worldMatrix.isIdentity()) {\n Vector3.TransformCoordinatesToRef(this.center, worldMatrix, this.centerWorld);\n const tempVector = BoundingSphere._TmpVector3[0];\n Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, worldMatrix, tempVector);\n this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius;\n }\n else {\n this.centerWorld.copyFrom(this.center);\n this.radiusWorld = this.radius;\n }\n }\n /**\n * Tests if the bounding sphere is intersecting the frustum planes\n * @param frustumPlanes defines the frustum planes to test\n * @returns true if there is an intersection\n */\n isInFrustum(frustumPlanes) {\n const center = this.centerWorld;\n const radius = this.radiusWorld;\n for (let i = 0; i < 6; i++) {\n if (frustumPlanes[i].dotCoordinate(center) <= -radius) {\n return false;\n }\n }\n return true;\n }\n /**\n * Tests if the bounding sphere center is in between the frustum planes.\n * Used for optimistic fast inclusion.\n * @param frustumPlanes defines the frustum planes to test\n * @returns true if the sphere center is in between the frustum planes\n */\n isCenterInFrustum(frustumPlanes) {\n const center = this.centerWorld;\n for (let i = 0; i < 6; i++) {\n if (frustumPlanes[i].dotCoordinate(center) < 0) {\n return false;\n }\n }\n return true;\n }\n /**\n * Tests if a point is inside the bounding sphere\n * @param point defines the point to test\n * @returns true if the point is inside the bounding sphere\n */\n intersectsPoint(point) {\n const squareDistance = Vector3.DistanceSquared(this.centerWorld, point);\n if (this.radiusWorld * this.radiusWorld < squareDistance) {\n return false;\n }\n return true;\n }\n // Statics\n /**\n * Checks if two sphere intersect\n * @param sphere0 sphere 0\n * @param sphere1 sphere 1\n * @returns true if the spheres intersect\n */\n static Intersects(sphere0, sphere1) {\n const squareDistance = Vector3.DistanceSquared(sphere0.centerWorld, sphere1.centerWorld);\n const radiusSum = sphere0.radiusWorld + sphere1.radiusWorld;\n if (radiusSum * radiusSum < squareDistance) {\n return false;\n }\n return true;\n }\n /**\n * Creates a sphere from a center and a radius\n * @param center The center\n * @param radius radius\n * @param matrix Optional worldMatrix\n * @returns The sphere\n */\n static CreateFromCenterAndRadius(center, radius, matrix) {\n this._TmpVector3[0].copyFrom(center);\n this._TmpVector3[1].copyFromFloats(0, 0, radius);\n this._TmpVector3[2].copyFrom(center);\n this._TmpVector3[0].addInPlace(this._TmpVector3[1]);\n this._TmpVector3[2].subtractInPlace(this._TmpVector3[1]);\n const sphere = new BoundingSphere(this._TmpVector3[0], this._TmpVector3[2]);\n if (matrix) {\n sphere._worldMatrix = matrix;\n }\n else {\n sphere._worldMatrix = Matrix.Identity();\n }\n return sphere;\n }\n}\nBoundingSphere._TmpVector3 = ArrayTools.BuildArray(3, Vector3.Zero);\n//# sourceMappingURL=boundingSphere.js.map","/**\n * Enum for Device Types\n */\nexport var DeviceType;\n(function (DeviceType) {\n /** Generic */\n DeviceType[DeviceType[\"Generic\"] = 0] = \"Generic\";\n /** Keyboard */\n DeviceType[DeviceType[\"Keyboard\"] = 1] = \"Keyboard\";\n /** Mouse */\n DeviceType[DeviceType[\"Mouse\"] = 2] = \"Mouse\";\n /** Touch Pointers */\n DeviceType[DeviceType[\"Touch\"] = 3] = \"Touch\";\n /** PS4 Dual Shock */\n DeviceType[DeviceType[\"DualShock\"] = 4] = \"DualShock\";\n /** Xbox */\n DeviceType[DeviceType[\"Xbox\"] = 5] = \"Xbox\";\n /** Switch Controller */\n DeviceType[DeviceType[\"Switch\"] = 6] = \"Switch\";\n /** PS5 DualSense */\n DeviceType[DeviceType[\"DualSense\"] = 7] = \"DualSense\";\n})(DeviceType || (DeviceType = {}));\n// Device Enums\n/**\n * Enum for All Pointers (Touch/Mouse)\n */\nexport var PointerInput;\n(function (PointerInput) {\n /** Horizontal Axis (Not used in events/observables; only in polling) */\n PointerInput[PointerInput[\"Horizontal\"] = 0] = \"Horizontal\";\n /** Vertical Axis (Not used in events/observables; only in polling) */\n PointerInput[PointerInput[\"Vertical\"] = 1] = \"Vertical\";\n /** Left Click or Touch */\n PointerInput[PointerInput[\"LeftClick\"] = 2] = \"LeftClick\";\n /** Middle Click */\n PointerInput[PointerInput[\"MiddleClick\"] = 3] = \"MiddleClick\";\n /** Right Click */\n PointerInput[PointerInput[\"RightClick\"] = 4] = \"RightClick\";\n /** Browser Back */\n PointerInput[PointerInput[\"BrowserBack\"] = 5] = \"BrowserBack\";\n /** Browser Forward */\n PointerInput[PointerInput[\"BrowserForward\"] = 6] = \"BrowserForward\";\n /** Mouse Wheel X */\n PointerInput[PointerInput[\"MouseWheelX\"] = 7] = \"MouseWheelX\";\n /** Mouse Wheel Y */\n PointerInput[PointerInput[\"MouseWheelY\"] = 8] = \"MouseWheelY\";\n /** Mouse Wheel Z */\n PointerInput[PointerInput[\"MouseWheelZ\"] = 9] = \"MouseWheelZ\";\n /** Used in events/observables to identify if x/y changes occurred */\n PointerInput[PointerInput[\"Move\"] = 12] = \"Move\";\n})(PointerInput || (PointerInput = {}));\n/** @internal */\nexport var NativePointerInput;\n(function (NativePointerInput) {\n /** Horizontal Axis */\n NativePointerInput[NativePointerInput[\"Horizontal\"] = 0] = \"Horizontal\";\n /** Vertical Axis */\n NativePointerInput[NativePointerInput[\"Vertical\"] = 1] = \"Vertical\";\n /** Left Click or Touch */\n NativePointerInput[NativePointerInput[\"LeftClick\"] = 2] = \"LeftClick\";\n /** Middle Click */\n NativePointerInput[NativePointerInput[\"MiddleClick\"] = 3] = \"MiddleClick\";\n /** Right Click */\n NativePointerInput[NativePointerInput[\"RightClick\"] = 4] = \"RightClick\";\n /** Browser Back */\n NativePointerInput[NativePointerInput[\"BrowserBack\"] = 5] = \"BrowserBack\";\n /** Browser Forward */\n NativePointerInput[NativePointerInput[\"BrowserForward\"] = 6] = \"BrowserForward\";\n /** Mouse Wheel X */\n NativePointerInput[NativePointerInput[\"MouseWheelX\"] = 7] = \"MouseWheelX\";\n /** Mouse Wheel Y */\n NativePointerInput[NativePointerInput[\"MouseWheelY\"] = 8] = \"MouseWheelY\";\n /** Mouse Wheel Z */\n NativePointerInput[NativePointerInput[\"MouseWheelZ\"] = 9] = \"MouseWheelZ\";\n /** Delta X */\n NativePointerInput[NativePointerInput[\"DeltaHorizontal\"] = 10] = \"DeltaHorizontal\";\n /** Delta Y */\n NativePointerInput[NativePointerInput[\"DeltaVertical\"] = 11] = \"DeltaVertical\";\n})(NativePointerInput || (NativePointerInput = {}));\n/**\n * Enum for Dual Shock Gamepad\n */\nexport var DualShockInput;\n(function (DualShockInput) {\n /** Cross */\n DualShockInput[DualShockInput[\"Cross\"] = 0] = \"Cross\";\n /** Circle */\n DualShockInput[DualShockInput[\"Circle\"] = 1] = \"Circle\";\n /** Square */\n DualShockInput[DualShockInput[\"Square\"] = 2] = \"Square\";\n /** Triangle */\n DualShockInput[DualShockInput[\"Triangle\"] = 3] = \"Triangle\";\n /** L1 */\n DualShockInput[DualShockInput[\"L1\"] = 4] = \"L1\";\n /** R1 */\n DualShockInput[DualShockInput[\"R1\"] = 5] = \"R1\";\n /** L2 */\n DualShockInput[DualShockInput[\"L2\"] = 6] = \"L2\";\n /** R2 */\n DualShockInput[DualShockInput[\"R2\"] = 7] = \"R2\";\n /** Share */\n DualShockInput[DualShockInput[\"Share\"] = 8] = \"Share\";\n /** Options */\n DualShockInput[DualShockInput[\"Options\"] = 9] = \"Options\";\n /** L3 */\n DualShockInput[DualShockInput[\"L3\"] = 10] = \"L3\";\n /** R3 */\n DualShockInput[DualShockInput[\"R3\"] = 11] = \"R3\";\n /** DPadUp */\n DualShockInput[DualShockInput[\"DPadUp\"] = 12] = \"DPadUp\";\n /** DPadDown */\n DualShockInput[DualShockInput[\"DPadDown\"] = 13] = \"DPadDown\";\n /** DPadLeft */\n DualShockInput[DualShockInput[\"DPadLeft\"] = 14] = \"DPadLeft\";\n /** DRight */\n DualShockInput[DualShockInput[\"DPadRight\"] = 15] = \"DPadRight\";\n /** Home */\n DualShockInput[DualShockInput[\"Home\"] = 16] = \"Home\";\n /** TouchPad */\n DualShockInput[DualShockInput[\"TouchPad\"] = 17] = \"TouchPad\";\n /** LStickXAxis */\n DualShockInput[DualShockInput[\"LStickXAxis\"] = 18] = \"LStickXAxis\";\n /** LStickYAxis */\n DualShockInput[DualShockInput[\"LStickYAxis\"] = 19] = \"LStickYAxis\";\n /** RStickXAxis */\n DualShockInput[DualShockInput[\"RStickXAxis\"] = 20] = \"RStickXAxis\";\n /** RStickYAxis */\n DualShockInput[DualShockInput[\"RStickYAxis\"] = 21] = \"RStickYAxis\";\n})(DualShockInput || (DualShockInput = {}));\n/**\n * Enum for Dual Sense Gamepad\n */\nexport var DualSenseInput;\n(function (DualSenseInput) {\n /** Cross */\n DualSenseInput[DualSenseInput[\"Cross\"] = 0] = \"Cross\";\n /** Circle */\n DualSenseInput[DualSenseInput[\"Circle\"] = 1] = \"Circle\";\n /** Square */\n DualSenseInput[DualSenseInput[\"Square\"] = 2] = \"Square\";\n /** Triangle */\n DualSenseInput[DualSenseInput[\"Triangle\"] = 3] = \"Triangle\";\n /** L1 */\n DualSenseInput[DualSenseInput[\"L1\"] = 4] = \"L1\";\n /** R1 */\n DualSenseInput[DualSenseInput[\"R1\"] = 5] = \"R1\";\n /** L2 */\n DualSenseInput[DualSenseInput[\"L2\"] = 6] = \"L2\";\n /** R2 */\n DualSenseInput[DualSenseInput[\"R2\"] = 7] = \"R2\";\n /** Create */\n DualSenseInput[DualSenseInput[\"Create\"] = 8] = \"Create\";\n /** Options */\n DualSenseInput[DualSenseInput[\"Options\"] = 9] = \"Options\";\n /** L3 */\n DualSenseInput[DualSenseInput[\"L3\"] = 10] = \"L3\";\n /** R3 */\n DualSenseInput[DualSenseInput[\"R3\"] = 11] = \"R3\";\n /** DPadUp */\n DualSenseInput[DualSenseInput[\"DPadUp\"] = 12] = \"DPadUp\";\n /** DPadDown */\n DualSenseInput[DualSenseInput[\"DPadDown\"] = 13] = \"DPadDown\";\n /** DPadLeft */\n DualSenseInput[DualSenseInput[\"DPadLeft\"] = 14] = \"DPadLeft\";\n /** DRight */\n DualSenseInput[DualSenseInput[\"DPadRight\"] = 15] = \"DPadRight\";\n /** Home */\n DualSenseInput[DualSenseInput[\"Home\"] = 16] = \"Home\";\n /** TouchPad */\n DualSenseInput[DualSenseInput[\"TouchPad\"] = 17] = \"TouchPad\";\n /** LStickXAxis */\n DualSenseInput[DualSenseInput[\"LStickXAxis\"] = 18] = \"LStickXAxis\";\n /** LStickYAxis */\n DualSenseInput[DualSenseInput[\"LStickYAxis\"] = 19] = \"LStickYAxis\";\n /** RStickXAxis */\n DualSenseInput[DualSenseInput[\"RStickXAxis\"] = 20] = \"RStickXAxis\";\n /** RStickYAxis */\n DualSenseInput[DualSenseInput[\"RStickYAxis\"] = 21] = \"RStickYAxis\";\n})(DualSenseInput || (DualSenseInput = {}));\n/**\n * Enum for Xbox Gamepad\n */\nexport var XboxInput;\n(function (XboxInput) {\n /** A */\n XboxInput[XboxInput[\"A\"] = 0] = \"A\";\n /** B */\n XboxInput[XboxInput[\"B\"] = 1] = \"B\";\n /** X */\n XboxInput[XboxInput[\"X\"] = 2] = \"X\";\n /** Y */\n XboxInput[XboxInput[\"Y\"] = 3] = \"Y\";\n /** LB */\n XboxInput[XboxInput[\"LB\"] = 4] = \"LB\";\n /** RB */\n XboxInput[XboxInput[\"RB\"] = 5] = \"RB\";\n /** LT */\n XboxInput[XboxInput[\"LT\"] = 6] = \"LT\";\n /** RT */\n XboxInput[XboxInput[\"RT\"] = 7] = \"RT\";\n /** Back */\n XboxInput[XboxInput[\"Back\"] = 8] = \"Back\";\n /** Start */\n XboxInput[XboxInput[\"Start\"] = 9] = \"Start\";\n /** LS */\n XboxInput[XboxInput[\"LS\"] = 10] = \"LS\";\n /** RS */\n XboxInput[XboxInput[\"RS\"] = 11] = \"RS\";\n /** DPadUp */\n XboxInput[XboxInput[\"DPadUp\"] = 12] = \"DPadUp\";\n /** DPadDown */\n XboxInput[XboxInput[\"DPadDown\"] = 13] = \"DPadDown\";\n /** DPadLeft */\n XboxInput[XboxInput[\"DPadLeft\"] = 14] = \"DPadLeft\";\n /** DRight */\n XboxInput[XboxInput[\"DPadRight\"] = 15] = \"DPadRight\";\n /** Home */\n XboxInput[XboxInput[\"Home\"] = 16] = \"Home\";\n /** LStickXAxis */\n XboxInput[XboxInput[\"LStickXAxis\"] = 17] = \"LStickXAxis\";\n /** LStickYAxis */\n XboxInput[XboxInput[\"LStickYAxis\"] = 18] = \"LStickYAxis\";\n /** RStickXAxis */\n XboxInput[XboxInput[\"RStickXAxis\"] = 19] = \"RStickXAxis\";\n /** RStickYAxis */\n XboxInput[XboxInput[\"RStickYAxis\"] = 20] = \"RStickYAxis\";\n})(XboxInput || (XboxInput = {}));\n/**\n * Enum for Switch (Pro/JoyCon L+R) Gamepad\n */\nexport var SwitchInput;\n(function (SwitchInput) {\n /** B */\n SwitchInput[SwitchInput[\"B\"] = 0] = \"B\";\n /** A */\n SwitchInput[SwitchInput[\"A\"] = 1] = \"A\";\n /** Y */\n SwitchInput[SwitchInput[\"Y\"] = 2] = \"Y\";\n /** X */\n SwitchInput[SwitchInput[\"X\"] = 3] = \"X\";\n /** L */\n SwitchInput[SwitchInput[\"L\"] = 4] = \"L\";\n /** R */\n SwitchInput[SwitchInput[\"R\"] = 5] = \"R\";\n /** ZL */\n SwitchInput[SwitchInput[\"ZL\"] = 6] = \"ZL\";\n /** ZR */\n SwitchInput[SwitchInput[\"ZR\"] = 7] = \"ZR\";\n /** Minus */\n SwitchInput[SwitchInput[\"Minus\"] = 8] = \"Minus\";\n /** Plus */\n SwitchInput[SwitchInput[\"Plus\"] = 9] = \"Plus\";\n /** LS */\n SwitchInput[SwitchInput[\"LS\"] = 10] = \"LS\";\n /** RS */\n SwitchInput[SwitchInput[\"RS\"] = 11] = \"RS\";\n /** DPadUp */\n SwitchInput[SwitchInput[\"DPadUp\"] = 12] = \"DPadUp\";\n /** DPadDown */\n SwitchInput[SwitchInput[\"DPadDown\"] = 13] = \"DPadDown\";\n /** DPadLeft */\n SwitchInput[SwitchInput[\"DPadLeft\"] = 14] = \"DPadLeft\";\n /** DRight */\n SwitchInput[SwitchInput[\"DPadRight\"] = 15] = \"DPadRight\";\n /** Home */\n SwitchInput[SwitchInput[\"Home\"] = 16] = \"Home\";\n /** Capture */\n SwitchInput[SwitchInput[\"Capture\"] = 17] = \"Capture\";\n /** LStickXAxis */\n SwitchInput[SwitchInput[\"LStickXAxis\"] = 18] = \"LStickXAxis\";\n /** LStickYAxis */\n SwitchInput[SwitchInput[\"LStickYAxis\"] = 19] = \"LStickYAxis\";\n /** RStickXAxis */\n SwitchInput[SwitchInput[\"RStickXAxis\"] = 20] = \"RStickXAxis\";\n /** RStickYAxis */\n SwitchInput[SwitchInput[\"RStickYAxis\"] = 21] = \"RStickYAxis\";\n})(SwitchInput || (SwitchInput = {}));\n//# sourceMappingURL=deviceEnums.js.map","import { Observable } from \"../../Misc/observable.js\";\n/**\n * Class that handles all input for a specific device\n */\nexport class DeviceSource {\n /**\n * Default Constructor\n * @param deviceInputSystem - Reference to DeviceInputSystem\n * @param deviceType - Type of device\n * @param deviceSlot - \"Slot\" or index that device is referenced in\n */\n constructor(deviceInputSystem, \n /** Type of device */\n deviceType, \n /** \"Slot\" or index that device is referenced in */\n deviceSlot = 0) {\n this.deviceType = deviceType;\n this.deviceSlot = deviceSlot;\n // Public Members\n /**\n * Observable to handle device input changes per device\n */\n this.onInputChangedObservable = new Observable();\n this._deviceInputSystem = deviceInputSystem;\n }\n /**\n * Get input for specific input\n * @param inputIndex - index of specific input on device\n * @returns Input value from DeviceInputSystem\n */\n getInput(inputIndex) {\n return this._deviceInputSystem.pollInput(this.deviceType, this.deviceSlot, inputIndex);\n }\n}\n//# sourceMappingURL=deviceSource.js.map","\nimport { EventConstants } from \"../Events/deviceInputEvents.js\";\nimport { DeviceType, NativePointerInput, PointerInput } from \"./InputDevices/deviceEnums.js\";\n/**\n * Class to wrap DeviceInputSystem data into an event object\n */\nexport class DeviceEventFactory {\n /**\n * Create device input events based on provided type and slot\n *\n * @param deviceType Type of device\n * @param deviceSlot \"Slot\" or index that device is referenced in\n * @param inputIndex Id of input to be checked\n * @param currentState Current value for given input\n * @param deviceInputSystem Reference to DeviceInputSystem\n * @param elementToAttachTo HTMLElement to reference as target for inputs\n * @returns IUIEvent object\n */\n static CreateDeviceEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo, pointerId) {\n switch (deviceType) {\n case DeviceType.Keyboard:\n return this._CreateKeyboardEvent(inputIndex, currentState, deviceInputSystem, elementToAttachTo);\n case DeviceType.Mouse:\n if (inputIndex === PointerInput.MouseWheelX || inputIndex === PointerInput.MouseWheelY || inputIndex === PointerInput.MouseWheelZ) {\n return this._CreateWheelEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo);\n }\n // eslint-disable-next-line no-fallthrough\n case DeviceType.Touch:\n return this._CreatePointerEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo, pointerId);\n default:\n throw `Unable to generate event for device ${DeviceType[deviceType]}`;\n }\n }\n /**\n * Creates pointer event\n *\n * @param deviceType Type of device\n * @param deviceSlot \"Slot\" or index that device is referenced in\n * @param inputIndex Id of input to be checked\n * @param currentState Current value for given input\n * @param deviceInputSystem Reference to DeviceInputSystem\n * @param elementToAttachTo HTMLElement to reference as target for inputs\n * @returns IUIEvent object (Pointer)\n */\n static _CreatePointerEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo, pointerId) {\n const evt = this._CreateMouseEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo);\n if (deviceType === DeviceType.Mouse) {\n evt.deviceType = DeviceType.Mouse;\n evt.pointerId = 1;\n evt.pointerType = \"mouse\";\n }\n else {\n evt.deviceType = DeviceType.Touch;\n evt.pointerId = pointerId !== null && pointerId !== void 0 ? pointerId : deviceSlot;\n evt.pointerType = \"touch\";\n }\n if (inputIndex === PointerInput.Move) {\n evt.type = \"pointermove\";\n }\n else if (inputIndex >= PointerInput.LeftClick && inputIndex <= PointerInput.RightClick) {\n evt.type = currentState === 1 ? \"pointerdown\" : \"pointerup\";\n evt.button = inputIndex - 2;\n }\n return evt;\n }\n /**\n * Create Mouse Wheel Event\n * @param deviceType Type of device\n * @param deviceSlot \"Slot\" or index that device is referenced in\n * @param inputIndex Id of input to be checked\n * @param currentState Current value for given input\n * @param deviceInputSystem Reference to DeviceInputSystem\n * @param elementToAttachTo HTMLElement to reference as target for inputs\n * @returns IUIEvent object (Wheel)\n */\n static _CreateWheelEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo) {\n const evt = this._CreateMouseEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo);\n // While WheelEvents don't generally have a pointerId, we used to add one in the InputManager\n // This line has been added to make the InputManager more platform-agnostic\n // Similar code exists in the WebDeviceInputSystem to handle browser created events\n evt.pointerId = 1;\n evt.type = \"wheel\";\n evt.deltaMode = EventConstants.DOM_DELTA_PIXEL;\n evt.deltaX = 0;\n evt.deltaY = 0;\n evt.deltaZ = 0;\n switch (inputIndex) {\n case PointerInput.MouseWheelX:\n evt.deltaX = currentState;\n break;\n case PointerInput.MouseWheelY:\n evt.deltaY = currentState;\n break;\n case PointerInput.MouseWheelZ:\n evt.deltaZ = currentState;\n break;\n }\n return evt;\n }\n /**\n * Create Mouse Event\n * @param deviceType Type of device\n * @param deviceSlot \"Slot\" or index that device is referenced in\n * @param inputIndex Id of input to be checked\n * @param currentState Current value for given input\n * @param deviceInputSystem Reference to DeviceInputSystem\n * @param elementToAttachTo HTMLElement to reference as target for inputs\n * @returns IUIEvent object (Mouse)\n */\n static _CreateMouseEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo) {\n const evt = this._CreateEvent(elementToAttachTo);\n const pointerX = deviceInputSystem.pollInput(deviceType, deviceSlot, PointerInput.Horizontal);\n const pointerY = deviceInputSystem.pollInput(deviceType, deviceSlot, PointerInput.Vertical);\n // Handle offsets/deltas based on existence of HTMLElement\n if (elementToAttachTo) {\n evt.movementX = 0;\n evt.movementY = 0;\n evt.offsetX = evt.movementX - elementToAttachTo.getBoundingClientRect().x;\n evt.offsetY = evt.movementY - elementToAttachTo.getBoundingClientRect().y;\n }\n else {\n evt.movementX = deviceInputSystem.pollInput(deviceType, deviceSlot, NativePointerInput.DeltaHorizontal); // DeltaHorizontal\n evt.movementY = deviceInputSystem.pollInput(deviceType, deviceSlot, NativePointerInput.DeltaVertical); // DeltaVertical\n evt.offsetX = 0;\n evt.offsetY = 0;\n }\n this._CheckNonCharacterKeys(evt, deviceInputSystem);\n evt.clientX = pointerX;\n evt.clientY = pointerY;\n evt.x = pointerX;\n evt.y = pointerY;\n evt.deviceType = deviceType;\n evt.deviceSlot = deviceSlot;\n evt.inputIndex = inputIndex;\n return evt;\n }\n /**\n * Create Keyboard Event\n * @param inputIndex Id of input to be checked\n * @param currentState Current value for given input\n * @param deviceInputSystem Reference to DeviceInputSystem\n * @param elementToAttachTo HTMLElement to reference as target for inputs\n * @returns IEvent object (Keyboard)\n */\n static _CreateKeyboardEvent(inputIndex, currentState, deviceInputSystem, elementToAttachTo) {\n const evt = this._CreateEvent(elementToAttachTo);\n this._CheckNonCharacterKeys(evt, deviceInputSystem);\n evt.deviceType = DeviceType.Keyboard;\n evt.deviceSlot = 0;\n evt.inputIndex = inputIndex;\n evt.type = currentState === 1 ? \"keydown\" : \"keyup\";\n evt.key = String.fromCharCode(inputIndex);\n evt.keyCode = inputIndex;\n return evt;\n }\n /**\n * Add parameters for non-character keys (Ctrl, Alt, Meta, Shift)\n * @param evt Event object to add parameters to\n * @param deviceInputSystem DeviceInputSystem to pull values from\n */\n static _CheckNonCharacterKeys(evt, deviceInputSystem) {\n const isKeyboardActive = deviceInputSystem.isDeviceAvailable(DeviceType.Keyboard);\n const altKey = isKeyboardActive && deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 18) === 1;\n const ctrlKey = isKeyboardActive && deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 17) === 1;\n const metaKey = isKeyboardActive &&\n (deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 91) === 1 ||\n deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 92) === 1 ||\n deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 93) === 1);\n const shiftKey = isKeyboardActive && deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 16) === 1;\n evt.altKey = altKey;\n evt.ctrlKey = ctrlKey;\n evt.metaKey = metaKey;\n evt.shiftKey = shiftKey;\n }\n /**\n * Create base event object\n * @param elementToAttachTo Value to use as event target\n * @returns\n */\n static _CreateEvent(elementToAttachTo) {\n const evt = {};\n evt.preventDefault = () => { };\n evt.target = elementToAttachTo;\n return evt;\n }\n}\n//# sourceMappingURL=eventFactory.js.map","import { DeviceEventFactory } from \"./eventFactory.js\";\nimport { DeviceType } from \"./InputDevices/deviceEnums.js\";\n/** @internal */\nexport class NativeDeviceInputSystem {\n constructor(onDeviceConnected, onDeviceDisconnected, onInputChanged) {\n this._nativeInput = _native.DeviceInputSystem\n ? new _native.DeviceInputSystem(onDeviceConnected, onDeviceDisconnected, (deviceType, deviceSlot, inputIndex, currentState) => {\n const evt = DeviceEventFactory.CreateDeviceEvent(deviceType, deviceSlot, inputIndex, currentState, this);\n onInputChanged(deviceType, deviceSlot, evt);\n })\n : this._createDummyNativeInput();\n }\n // Public functions\n /**\n * Checks for current device input value, given an id and input index. Throws exception if requested device not initialized.\n * @param deviceType Enum specifying device type\n * @param deviceSlot \"Slot\" or index that device is referenced in\n * @param inputIndex Id of input to be checked\n * @returns Current value of input\n */\n pollInput(deviceType, deviceSlot, inputIndex) {\n return this._nativeInput.pollInput(deviceType, deviceSlot, inputIndex);\n }\n /**\n * Check for a specific device in the DeviceInputSystem\n * @param deviceType Type of device to check for\n * @returns bool with status of device's existence\n */\n isDeviceAvailable(deviceType) {\n //TODO: FIx native side first\n return deviceType === DeviceType.Mouse || deviceType === DeviceType.Touch;\n }\n /**\n * Dispose of all the observables\n */\n dispose() {\n this._nativeInput.dispose();\n }\n /**\n * For versions of BabylonNative that don't have the NativeInput plugin initialized, create a dummy version\n * @returns Object with dummy functions\n */\n _createDummyNativeInput() {\n const nativeInput = {\n pollInput: () => {\n return 0;\n },\n isDeviceAvailable: () => {\n return false;\n },\n dispose: () => { },\n };\n return nativeInput;\n }\n}\n//# sourceMappingURL=nativeDeviceInputSystem.js.map","import { DomManagement, IsNavigatorAvailable } from \"../Misc/domManagement.js\";\nimport { Tools } from \"../Misc/tools.js\";\nimport { DeviceEventFactory } from \"./eventFactory.js\";\nimport { DeviceType, PointerInput } from \"./InputDevices/deviceEnums.js\";\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst MAX_KEYCODES = 255;\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst MAX_POINTER_INPUTS = Object.keys(PointerInput).length / 2;\n/** @internal */\nexport class WebDeviceInputSystem {\n constructor(engine, onDeviceConnected, onDeviceDisconnected, onInputChanged) {\n // Private Members\n this._inputs = [];\n this._keyboardActive = false;\n this._pointerActive = false;\n this._usingSafari = Tools.IsSafari();\n // Found solution for determining if MacOS is being used here:\n // https://stackoverflow.com/questions/10527983/best-way-to-detect-mac-os-x-or-windows-computers-with-javascript-or-jquery\n this._usingMacOS = IsNavigatorAvailable() && /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this._keyboardDownEvent = (evt) => { };\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this._keyboardUpEvent = (evt) => { };\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this._keyboardBlurEvent = (evt) => { };\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this._pointerMoveEvent = (evt) => { };\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this._pointerDownEvent = (evt) => { };\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this._pointerUpEvent = (evt) => { };\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this._pointerCancelEvent = (evt) => { };\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this._pointerWheelEvent = (evt) => { };\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this._pointerBlurEvent = (evt) => { };\n this._eventsAttached = false;\n this._mouseId = -1;\n this._isUsingFirefox = DomManagement.IsNavigatorAvailable() && navigator.userAgent && navigator.userAgent.indexOf(\"Firefox\") !== -1;\n this._maxTouchPoints = 0;\n this._pointerInputClearObserver = null;\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this._gamepadConnectedEvent = (evt) => { };\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this._gamepadDisconnectedEvent = (evt) => { };\n this._eventPrefix = Tools.GetPointerPrefix(engine);\n this._engine = engine;\n this._onDeviceConnected = onDeviceConnected;\n this._onDeviceDisconnected = onDeviceDisconnected;\n this._onInputChanged = onInputChanged;\n // If we need a pointerId, set one for future use\n this._mouseId = this._isUsingFirefox ? 0 : 1;\n this._enableEvents();\n if (this._usingMacOS) {\n this._metaKeys = [];\n }\n // Set callback to enable event handler switching when inputElement changes\n if (!this._engine._onEngineViewChanged) {\n this._engine._onEngineViewChanged = () => {\n this._enableEvents();\n };\n }\n }\n // Public functions\n /**\n * Checks for current device input value, given an id and input index. Throws exception if requested device not initialized.\n * @param deviceType Enum specifying device type\n * @param deviceSlot \"Slot\" or index that device is referenced in\n * @param inputIndex Id of input to be checked\n * @returns Current value of input\n */\n pollInput(deviceType, deviceSlot, inputIndex) {\n const device = this._inputs[deviceType][deviceSlot];\n if (!device) {\n throw `Unable to find device ${DeviceType[deviceType]}`;\n }\n if (deviceType >= DeviceType.DualShock && deviceType <= DeviceType.DualSense) {\n this._updateDevice(deviceType, deviceSlot, inputIndex);\n }\n const currentValue = device[inputIndex];\n if (currentValue === undefined) {\n throw `Unable to find input ${inputIndex} for device ${DeviceType[deviceType]} in slot ${deviceSlot}`;\n }\n if (inputIndex === PointerInput.Move) {\n Tools.Warn(`Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data.`);\n }\n return currentValue;\n }\n /**\n * Check for a specific device in the DeviceInputSystem\n * @param deviceType Type of device to check for\n * @returns bool with status of device's existence\n */\n isDeviceAvailable(deviceType) {\n return this._inputs[deviceType] !== undefined;\n }\n /**\n * Dispose of all the eventlisteners\n */\n dispose() {\n // Callbacks\n this._onDeviceConnected = () => { };\n this._onDeviceDisconnected = () => { };\n this._onInputChanged = () => { };\n delete this._engine._onEngineViewChanged;\n if (this._elementToAttachTo) {\n this._disableEvents();\n }\n }\n /**\n * Enable listening for user input events\n */\n _enableEvents() {\n const inputElement = this === null || this === void 0 ? void 0 : this._engine.getInputElement();\n if (inputElement && (!this._eventsAttached || this._elementToAttachTo !== inputElement)) {\n // Remove events before adding to avoid double events or simultaneous events on multiple canvases\n this._disableEvents();\n // If the inputs array has already been created, zero it out to before setting up events\n if (this._inputs) {\n for (const inputs of this._inputs) {\n if (inputs) {\n for (const deviceSlotKey in inputs) {\n const deviceSlot = +deviceSlotKey;\n const device = inputs[deviceSlot];\n if (device) {\n for (let inputIndex = 0; inputIndex < device.length; inputIndex++) {\n device[inputIndex] = 0;\n }\n }\n }\n }\n }\n }\n this._elementToAttachTo = inputElement;\n // Set tab index for the inputElement to the engine's canvasTabIndex, if and only if the element's tab index is -1\n this._elementToAttachTo.tabIndex = this._elementToAttachTo.tabIndex !== -1 ? this._elementToAttachTo.tabIndex : this._engine.canvasTabIndex;\n this._handleKeyActions();\n this._handlePointerActions();\n this._handleGamepadActions();\n this._eventsAttached = true;\n // Check for devices that are already connected but aren't registered. Currently, only checks for gamepads and mouse\n this._checkForConnectedDevices();\n }\n }\n /**\n * Disable listening for user input events\n */\n _disableEvents() {\n if (this._elementToAttachTo) {\n // Blur Events\n this._elementToAttachTo.removeEventListener(\"blur\", this._keyboardBlurEvent);\n this._elementToAttachTo.removeEventListener(\"blur\", this._pointerBlurEvent);\n // Keyboard Events\n this._elementToAttachTo.removeEventListener(\"keydown\", this._keyboardDownEvent);\n this._elementToAttachTo.removeEventListener(\"keyup\", this._keyboardUpEvent);\n // Pointer Events\n this._elementToAttachTo.removeEventListener(this._eventPrefix + \"move\", this._pointerMoveEvent);\n this._elementToAttachTo.removeEventListener(this._eventPrefix + \"down\", this._pointerDownEvent);\n this._elementToAttachTo.removeEventListener(this._eventPrefix + \"up\", this._pointerUpEvent);\n this._elementToAttachTo.removeEventListener(this._eventPrefix + \"cancel\", this._pointerCancelEvent);\n this._elementToAttachTo.removeEventListener(this._wheelEventName, this._pointerWheelEvent);\n // Gamepad Events\n window.removeEventListener(\"gamepadconnected\", this._gamepadConnectedEvent);\n window.removeEventListener(\"gamepaddisconnected\", this._gamepadDisconnectedEvent);\n }\n if (this._pointerInputClearObserver) {\n this._engine.onEndFrameObservable.remove(this._pointerInputClearObserver);\n }\n this._eventsAttached = false;\n }\n /**\n * Checks for existing connections to devices and register them, if necessary\n * Currently handles gamepads and mouse\n */\n _checkForConnectedDevices() {\n if (navigator.getGamepads) {\n const gamepads = navigator.getGamepads();\n for (const gamepad of gamepads) {\n if (gamepad) {\n this._addGamePad(gamepad);\n }\n }\n }\n // If the device in use has mouse capabilities, pre-register mouse\n if (typeof matchMedia === \"function\" && matchMedia(\"(pointer:fine)\").matches) {\n // This will provide a dummy value for the cursor position and is expected to be overridden when the first mouse event happens.\n // There isn't any good way to get the current position outside of a pointer event so that's why this was done.\n this._addPointerDevice(DeviceType.Mouse, 0, 0, 0);\n }\n }\n // Private functions\n /**\n * Add a gamepad to the DeviceInputSystem\n * @param gamepad A single DOM Gamepad object\n */\n _addGamePad(gamepad) {\n const deviceType = this._getGamepadDeviceType(gamepad.id);\n const deviceSlot = gamepad.index;\n this._gamepads = this._gamepads || new Array(gamepad.index + 1);\n this._registerDevice(deviceType, deviceSlot, gamepad.buttons.length + gamepad.axes.length);\n this._gamepads[deviceSlot] = deviceType;\n }\n /**\n * Add pointer device to DeviceInputSystem\n * @param deviceType Type of Pointer to add\n * @param deviceSlot Pointer ID (0 for mouse, pointerId for Touch)\n * @param currentX Current X at point of adding\n * @param currentY Current Y at point of adding\n */\n _addPointerDevice(deviceType, deviceSlot, currentX, currentY) {\n if (!this._pointerActive) {\n this._pointerActive = true;\n }\n this._registerDevice(deviceType, deviceSlot, MAX_POINTER_INPUTS);\n const pointer = this._inputs[deviceType][deviceSlot]; /* initialize our pointer position immediately after registration */\n pointer[0] = currentX;\n pointer[1] = currentY;\n }\n /**\n * Add device and inputs to device array\n * @param deviceType Enum specifying device type\n * @param deviceSlot \"Slot\" or index that device is referenced in\n * @param numberOfInputs Number of input entries to create for given device\n */\n _registerDevice(deviceType, deviceSlot, numberOfInputs) {\n if (deviceSlot === undefined) {\n throw `Unable to register device ${DeviceType[deviceType]} to undefined slot.`;\n }\n if (!this._inputs[deviceType]) {\n this._inputs[deviceType] = {};\n }\n if (!this._inputs[deviceType][deviceSlot]) {\n const device = new Array(numberOfInputs);\n device.fill(0);\n this._inputs[deviceType][deviceSlot] = device;\n this._onDeviceConnected(deviceType, deviceSlot);\n }\n }\n /**\n * Given a specific device name, remove that device from the device map\n * @param deviceType Enum specifying device type\n * @param deviceSlot \"Slot\" or index that device is referenced in\n */\n _unregisterDevice(deviceType, deviceSlot) {\n if (this._inputs[deviceType][deviceSlot]) {\n delete this._inputs[deviceType][deviceSlot];\n this._onDeviceDisconnected(deviceType, deviceSlot);\n }\n }\n /**\n * Handle all actions that come from keyboard interaction\n */\n _handleKeyActions() {\n this._keyboardDownEvent = (evt) => {\n if (!this._keyboardActive) {\n this._keyboardActive = true;\n this._registerDevice(DeviceType.Keyboard, 0, MAX_KEYCODES);\n }\n const kbKey = this._inputs[DeviceType.Keyboard][0];\n if (kbKey) {\n kbKey[evt.keyCode] = 1;\n const deviceEvent = evt;\n deviceEvent.inputIndex = evt.keyCode;\n if (this._usingMacOS && evt.metaKey && evt.key !== \"Meta\") {\n if (!this._metaKeys.includes(evt.keyCode)) {\n this._metaKeys.push(evt.keyCode);\n }\n }\n this._onInputChanged(DeviceType.Keyboard, 0, deviceEvent);\n }\n };\n this._keyboardUpEvent = (evt) => {\n if (!this._keyboardActive) {\n this._keyboardActive = true;\n this._registerDevice(DeviceType.Keyboard, 0, MAX_KEYCODES);\n }\n const kbKey = this._inputs[DeviceType.Keyboard][0];\n if (kbKey) {\n kbKey[evt.keyCode] = 0;\n const deviceEvent = evt;\n deviceEvent.inputIndex = evt.keyCode;\n if (this._usingMacOS && evt.key === \"Meta\" && this._metaKeys.length > 0) {\n for (const keyCode of this._metaKeys) {\n const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Keyboard, 0, keyCode, 0, this, this._elementToAttachTo);\n kbKey[keyCode] = 0;\n this._onInputChanged(DeviceType.Keyboard, 0, deviceEvent);\n }\n this._metaKeys.splice(0, this._metaKeys.length);\n }\n this._onInputChanged(DeviceType.Keyboard, 0, deviceEvent);\n }\n };\n this._keyboardBlurEvent = () => {\n if (this._keyboardActive) {\n const kbKey = this._inputs[DeviceType.Keyboard][0];\n for (let i = 0; i < kbKey.length; i++) {\n if (kbKey[i] !== 0) {\n kbKey[i] = 0;\n const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Keyboard, 0, i, 0, this, this._elementToAttachTo);\n this._onInputChanged(DeviceType.Keyboard, 0, deviceEvent);\n }\n }\n if (this._usingMacOS) {\n this._metaKeys.splice(0, this._metaKeys.length);\n }\n }\n };\n this._elementToAttachTo.addEventListener(\"keydown\", this._keyboardDownEvent);\n this._elementToAttachTo.addEventListener(\"keyup\", this._keyboardUpEvent);\n this._elementToAttachTo.addEventListener(\"blur\", this._keyboardBlurEvent);\n }\n /**\n * Handle all actions that come from pointer interaction\n */\n _handlePointerActions() {\n // If maxTouchPoints is defined, use that value. Otherwise, allow for a minimum for supported gestures like pinch\n this._maxTouchPoints = (DomManagement.IsNavigatorAvailable() && navigator.maxTouchPoints) || 2;\n if (!this._activeTouchIds) {\n this._activeTouchIds = new Array(this._maxTouchPoints);\n }\n for (let i = 0; i < this._maxTouchPoints; i++) {\n this._activeTouchIds[i] = -1;\n }\n this._pointerMoveEvent = (evt) => {\n const deviceType = this._getPointerType(evt);\n const deviceSlot = deviceType === DeviceType.Mouse ? 0 : this._activeTouchIds.indexOf(evt.pointerId);\n if (!this._inputs[deviceType]) {\n this._inputs[deviceType] = {};\n }\n if (!this._inputs[deviceType][deviceSlot]) {\n this._addPointerDevice(deviceType, deviceSlot, evt.clientX, evt.clientY);\n }\n const pointer = this._inputs[deviceType][deviceSlot];\n if (pointer) {\n const deviceEvent = evt;\n deviceEvent.inputIndex = PointerInput.Move;\n pointer[PointerInput.Horizontal] = evt.clientX;\n pointer[PointerInput.Vertical] = evt.clientY;\n if (evt.pointerId === undefined) {\n evt.pointerId = this._mouseId;\n }\n this._onInputChanged(deviceType, deviceSlot, deviceEvent);\n // Lets Propagate the event for move with same position.\n if (!this._usingSafari && evt.button !== -1) {\n deviceEvent.inputIndex = evt.button + 2;\n pointer[evt.button + 2] = pointer[evt.button + 2] ? 0 : 1; // Reverse state of button if evt.button has value\n this._onInputChanged(deviceType, deviceSlot, deviceEvent);\n }\n }\n };\n this._pointerDownEvent = (evt) => {\n const deviceType = this._getPointerType(evt);\n let deviceSlot = deviceType === DeviceType.Mouse ? 0 : evt.pointerId;\n if (deviceType === DeviceType.Touch) {\n const idx = this._activeTouchIds.indexOf(-1);\n if (idx >= 0) {\n deviceSlot = idx;\n this._activeTouchIds[idx] = evt.pointerId;\n }\n else {\n // We can't find an open slot to store new pointer so just return (can only support max number of touches)\n Tools.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);\n return;\n }\n }\n if (!this._inputs[deviceType]) {\n this._inputs[deviceType] = {};\n }\n if (!this._inputs[deviceType][deviceSlot]) {\n this._addPointerDevice(deviceType, deviceSlot, evt.clientX, evt.clientY);\n }\n else if (deviceType === DeviceType.Touch) {\n this._onDeviceConnected(deviceType, deviceSlot);\n }\n const pointer = this._inputs[deviceType][deviceSlot];\n if (pointer) {\n const previousHorizontal = pointer[PointerInput.Horizontal];\n const previousVertical = pointer[PointerInput.Vertical];\n if (deviceType === DeviceType.Mouse) {\n // Mouse; Set pointerId if undefined\n if (evt.pointerId === undefined) {\n evt.pointerId = this._mouseId;\n }\n if (!document.pointerLockElement) {\n try {\n this._elementToAttachTo.setPointerCapture(this._mouseId);\n }\n catch (e) {\n // DO NOTHING\n }\n }\n }\n else {\n // Touch; Since touches are dynamically assigned, only set capture if we have an id\n if (evt.pointerId && !document.pointerLockElement) {\n try {\n this._elementToAttachTo.setPointerCapture(evt.pointerId);\n }\n catch (e) {\n // DO NOTHING\n }\n }\n }\n pointer[PointerInput.Horizontal] = evt.clientX;\n pointer[PointerInput.Vertical] = evt.clientY;\n pointer[evt.button + 2] = 1;\n const deviceEvent = evt;\n // NOTE: The +2 used here to is because PointerInput has the same value progression for its mouse buttons as PointerEvent.button\n // However, we have our X and Y values front-loaded to group together the touch inputs but not break this progression\n // EG. ([X, Y, Left-click], Middle-click, etc...)\n deviceEvent.inputIndex = evt.button + 2;\n this._onInputChanged(deviceType, deviceSlot, deviceEvent);\n if (previousHorizontal !== evt.clientX || previousVertical !== evt.clientY) {\n deviceEvent.inputIndex = PointerInput.Move;\n this._onInputChanged(deviceType, deviceSlot, deviceEvent);\n }\n }\n };\n this._pointerUpEvent = (evt) => {\n var _a, _b, _c, _d, _e;\n const deviceType = this._getPointerType(evt);\n const deviceSlot = deviceType === DeviceType.Mouse ? 0 : this._activeTouchIds.indexOf(evt.pointerId);\n if (deviceType === DeviceType.Touch) {\n if (deviceSlot === -1) {\n return;\n }\n else {\n this._activeTouchIds[deviceSlot] = -1;\n }\n }\n const pointer = (_a = this._inputs[deviceType]) === null || _a === void 0 ? void 0 : _a[deviceSlot];\n if (pointer && pointer[evt.button + 2] !== 0) {\n const previousHorizontal = pointer[PointerInput.Horizontal];\n const previousVertical = pointer[PointerInput.Vertical];\n pointer[PointerInput.Horizontal] = evt.clientX;\n pointer[PointerInput.Vertical] = evt.clientY;\n pointer[evt.button + 2] = 0;\n const deviceEvent = evt;\n if (evt.pointerId === undefined) {\n evt.pointerId = this._mouseId;\n }\n if (previousHorizontal !== evt.clientX || previousVertical !== evt.clientY) {\n deviceEvent.inputIndex = PointerInput.Move;\n this._onInputChanged(deviceType, deviceSlot, deviceEvent);\n }\n // NOTE: The +2 used here to is because PointerInput has the same value progression for its mouse buttons as PointerEvent.button\n // However, we have our X and Y values front-loaded to group together the touch inputs but not break this progression\n // EG. ([X, Y, Left-click], Middle-click, etc...)\n deviceEvent.inputIndex = evt.button + 2;\n if (deviceType === DeviceType.Mouse && this._mouseId >= 0 && ((_c = (_b = this._elementToAttachTo).hasPointerCapture) === null || _c === void 0 ? void 0 : _c.call(_b, this._mouseId))) {\n this._elementToAttachTo.releasePointerCapture(this._mouseId);\n }\n else if (evt.pointerId && ((_e = (_d = this._elementToAttachTo).hasPointerCapture) === null || _e === void 0 ? void 0 : _e.call(_d, evt.pointerId))) {\n this._elementToAttachTo.releasePointerCapture(evt.pointerId);\n }\n this._onInputChanged(deviceType, deviceSlot, deviceEvent);\n if (deviceType === DeviceType.Touch) {\n this._onDeviceDisconnected(deviceType, deviceSlot);\n }\n }\n };\n this._pointerCancelEvent = (evt) => {\n var _a, _b, _c, _d;\n if (evt.pointerType === \"mouse\") {\n const pointer = this._inputs[DeviceType.Mouse][0];\n if (this._mouseId >= 0 && ((_b = (_a = this._elementToAttachTo).hasPointerCapture) === null || _b === void 0 ? void 0 : _b.call(_a, this._mouseId))) {\n this._elementToAttachTo.releasePointerCapture(this._mouseId);\n }\n for (let inputIndex = PointerInput.LeftClick; inputIndex <= PointerInput.BrowserForward; inputIndex++) {\n if (pointer[inputIndex] === 1) {\n pointer[inputIndex] = 0;\n const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Mouse, 0, inputIndex, 0, this, this._elementToAttachTo);\n this._onInputChanged(DeviceType.Mouse, 0, deviceEvent);\n }\n }\n }\n else {\n const deviceSlot = this._activeTouchIds.indexOf(evt.pointerId);\n if ((_d = (_c = this._elementToAttachTo).hasPointerCapture) === null || _d === void 0 ? void 0 : _d.call(_c, evt.pointerId)) {\n this._elementToAttachTo.releasePointerCapture(evt.pointerId);\n }\n this._inputs[DeviceType.Touch][deviceSlot][PointerInput.LeftClick] = 0;\n const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Touch, deviceSlot, PointerInput.LeftClick, 0, this, this._elementToAttachTo, evt.pointerId);\n this._onInputChanged(DeviceType.Touch, deviceSlot, deviceEvent);\n this._activeTouchIds[deviceSlot] = -1;\n this._onDeviceDisconnected(DeviceType.Touch, deviceSlot);\n }\n };\n // Set Wheel Event Name, code originally from scene.inputManager\n this._wheelEventName =\n \"onwheel\" in document.createElement(\"div\")\n ? \"wheel\" // Modern browsers support \"wheel\"\n : document.onmousewheel !== undefined\n ? \"mousewheel\" // Webkit and IE support at least \"mousewheel\"\n : \"DOMMouseScroll\"; // let's assume that remaining browsers are older Firefox\n // Code originally in scene.inputManager.ts\n // Chrome reports warning in console if wheel listener doesn't set an explicit passive option.\n // IE11 only supports captureEvent:boolean, not options:object, and it defaults to false.\n // Feature detection technique copied from: https://github.com/github/eventlistener-polyfill (MIT license)\n let passiveSupported = false;\n const noop = function () { };\n try {\n const options = Object.defineProperty({}, \"passive\", {\n get: function () {\n passiveSupported = true;\n },\n });\n this._elementToAttachTo.addEventListener(\"test\", noop, options);\n this._elementToAttachTo.removeEventListener(\"test\", noop, options);\n }\n catch (e) {\n /* */\n }\n this._pointerBlurEvent = () => {\n var _a, _b, _c, _d, _e;\n // Handle mouse buttons\n if (this.isDeviceAvailable(DeviceType.Mouse)) {\n const pointer = this._inputs[DeviceType.Mouse][0];\n if (this._mouseId >= 0 && ((_b = (_a = this._elementToAttachTo).hasPointerCapture) === null || _b === void 0 ? void 0 : _b.call(_a, this._mouseId))) {\n this._elementToAttachTo.releasePointerCapture(this._mouseId);\n }\n for (let inputIndex = PointerInput.LeftClick; inputIndex <= PointerInput.BrowserForward; inputIndex++) {\n if (pointer[inputIndex] === 1) {\n pointer[inputIndex] = 0;\n const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Mouse, 0, inputIndex, 0, this, this._elementToAttachTo);\n this._onInputChanged(DeviceType.Mouse, 0, deviceEvent);\n }\n }\n }\n // Handle Active Touches\n if (this.isDeviceAvailable(DeviceType.Touch)) {\n const pointer = this._inputs[DeviceType.Touch];\n for (let deviceSlot = 0; deviceSlot < this._activeTouchIds.length; deviceSlot++) {\n const pointerId = this._activeTouchIds[deviceSlot];\n if ((_d = (_c = this._elementToAttachTo).hasPointerCapture) === null || _d === void 0 ? void 0 : _d.call(_c, pointerId)) {\n this._elementToAttachTo.releasePointerCapture(pointerId);\n }\n if (pointerId !== -1 && ((_e = pointer[deviceSlot]) === null || _e === void 0 ? void 0 : _e[PointerInput.LeftClick]) === 1) {\n pointer[deviceSlot][PointerInput.LeftClick] = 0;\n const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Touch, deviceSlot, PointerInput.LeftClick, 0, this, this._elementToAttachTo, pointerId);\n this._onInputChanged(DeviceType.Touch, deviceSlot, deviceEvent);\n this._activeTouchIds[deviceSlot] = -1;\n this._onDeviceDisconnected(DeviceType.Touch, deviceSlot);\n }\n }\n }\n };\n this._pointerWheelEvent = (evt) => {\n const deviceType = DeviceType.Mouse;\n const deviceSlot = 0;\n if (!this._inputs[deviceType]) {\n this._inputs[deviceType] = [];\n }\n if (!this._inputs[deviceType][deviceSlot]) {\n this._pointerActive = true;\n this._registerDevice(deviceType, deviceSlot, MAX_POINTER_INPUTS);\n }\n const pointer = this._inputs[deviceType][deviceSlot];\n if (pointer) {\n pointer[PointerInput.MouseWheelX] = evt.deltaX || 0;\n pointer[PointerInput.MouseWheelY] = evt.deltaY || evt.wheelDelta || 0;\n pointer[PointerInput.MouseWheelZ] = evt.deltaZ || 0;\n const deviceEvent = evt;\n // By default, there is no pointerId for mouse wheel events so we'll add one here\n // This logic was originally in the InputManager but was added here to make the\n // InputManager more platform-agnostic\n if (evt.pointerId === undefined) {\n evt.pointerId = this._mouseId;\n }\n if (pointer[PointerInput.MouseWheelX] !== 0) {\n deviceEvent.inputIndex = PointerInput.MouseWheelX;\n this._onInputChanged(deviceType, deviceSlot, deviceEvent);\n }\n if (pointer[PointerInput.MouseWheelY] !== 0) {\n deviceEvent.inputIndex = PointerInput.MouseWheelY;\n this._onInputChanged(deviceType, deviceSlot, deviceEvent);\n }\n if (pointer[PointerInput.MouseWheelZ] !== 0) {\n deviceEvent.inputIndex = PointerInput.MouseWheelZ;\n this._onInputChanged(deviceType, deviceSlot, deviceEvent);\n }\n }\n };\n this._elementToAttachTo.addEventListener(this._eventPrefix + \"move\", this._pointerMoveEvent);\n this._elementToAttachTo.addEventListener(this._eventPrefix + \"down\", this._pointerDownEvent);\n this._elementToAttachTo.addEventListener(this._eventPrefix + \"up\", this._pointerUpEvent);\n this._elementToAttachTo.addEventListener(this._eventPrefix + \"cancel\", this._pointerCancelEvent);\n this._elementToAttachTo.addEventListener(\"blur\", this._pointerBlurEvent);\n this._elementToAttachTo.addEventListener(this._wheelEventName, this._pointerWheelEvent, passiveSupported ? { passive: false } : false);\n // Since there's no up or down event for mouse wheel or delta x/y, clear mouse values at end of frame\n this._pointerInputClearObserver = this._engine.onEndFrameObservable.add(() => {\n if (this.isDeviceAvailable(DeviceType.Mouse)) {\n const pointer = this._inputs[DeviceType.Mouse][0];\n pointer[PointerInput.MouseWheelX] = 0;\n pointer[PointerInput.MouseWheelY] = 0;\n pointer[PointerInput.MouseWheelZ] = 0;\n }\n });\n }\n /**\n * Handle all actions that come from gamepad interaction\n */\n _handleGamepadActions() {\n this._gamepadConnectedEvent = (evt) => {\n this._addGamePad(evt.gamepad);\n };\n this._gamepadDisconnectedEvent = (evt) => {\n if (this._gamepads) {\n const deviceType = this._getGamepadDeviceType(evt.gamepad.id);\n const deviceSlot = evt.gamepad.index;\n this._unregisterDevice(deviceType, deviceSlot);\n delete this._gamepads[deviceSlot];\n }\n };\n window.addEventListener(\"gamepadconnected\", this._gamepadConnectedEvent);\n window.addEventListener(\"gamepaddisconnected\", this._gamepadDisconnectedEvent);\n }\n /**\n * Update all non-event based devices with each frame\n * @param deviceType Enum specifying device type\n * @param deviceSlot \"Slot\" or index that device is referenced in\n * @param inputIndex Id of input to be checked\n */\n _updateDevice(deviceType, deviceSlot, inputIndex) {\n // Gamepads\n const gp = navigator.getGamepads()[deviceSlot];\n if (gp && deviceType === this._gamepads[deviceSlot]) {\n const device = this._inputs[deviceType][deviceSlot];\n if (inputIndex >= gp.buttons.length) {\n device[inputIndex] = gp.axes[inputIndex - gp.buttons.length].valueOf();\n }\n else {\n device[inputIndex] = gp.buttons[inputIndex].value;\n }\n }\n }\n /**\n * Gets DeviceType from the device name\n * @param deviceName Name of Device from DeviceInputSystem\n * @returns DeviceType enum value\n */\n _getGamepadDeviceType(deviceName) {\n if (deviceName.indexOf(\"054c\") !== -1) {\n // DualShock 4 Gamepad\n return deviceName.indexOf(\"0ce6\") !== -1 ? DeviceType.DualSense : DeviceType.DualShock;\n }\n else if (deviceName.indexOf(\"Xbox One\") !== -1 || deviceName.search(\"Xbox 360\") !== -1 || deviceName.search(\"xinput\") !== -1) {\n // Xbox Gamepad\n return DeviceType.Xbox;\n }\n else if (deviceName.indexOf(\"057e\") !== -1) {\n // Switch Gamepad\n return DeviceType.Switch;\n }\n return DeviceType.Generic;\n }\n /**\n * Get DeviceType from a given pointer/mouse/touch event.\n * @param evt PointerEvent to evaluate\n * @returns DeviceType interpreted from event\n */\n _getPointerType(evt) {\n let deviceType = DeviceType.Mouse;\n if (evt.pointerType === \"touch\" || evt.pointerType === \"pen\" || evt.touches) {\n deviceType = DeviceType.Touch;\n }\n return deviceType;\n }\n}\n//# sourceMappingURL=webDeviceInputSystem.js.map","import { DeviceType } from \"./InputDevices/deviceEnums.js\";\nimport { NativeDeviceInputSystem } from \"./nativeDeviceInputSystem.js\";\nimport { WebDeviceInputSystem } from \"./webDeviceInputSystem.js\";\nimport { DeviceSource } from \"./InputDevices/deviceSource.js\";\n/** @internal */\nexport class InternalDeviceSourceManager {\n constructor(engine) {\n this._registeredManagers = new Array();\n this._refCount = 0;\n // Public Functions\n this.registerManager = (manager) => {\n for (let deviceType = 0; deviceType < this._devices.length; deviceType++) {\n const device = this._devices[deviceType];\n for (const deviceSlotKey in device) {\n const deviceSlot = +deviceSlotKey;\n manager._addDevice(new DeviceSource(this._deviceInputSystem, deviceType, deviceSlot));\n }\n }\n this._registeredManagers.push(manager);\n };\n this.unregisterManager = (manager) => {\n const idx = this._registeredManagers.indexOf(manager);\n if (idx > -1) {\n this._registeredManagers.splice(idx, 1);\n }\n };\n const numberOfDeviceTypes = Object.keys(DeviceType).length / 2;\n this._devices = new Array(numberOfDeviceTypes);\n const onDeviceConnected = (deviceType, deviceSlot) => {\n if (!this._devices[deviceType]) {\n this._devices[deviceType] = new Array();\n }\n if (!this._devices[deviceType][deviceSlot]) {\n this._devices[deviceType][deviceSlot] = deviceSlot;\n }\n for (const manager of this._registeredManagers) {\n const deviceSource = new DeviceSource(this._deviceInputSystem, deviceType, deviceSlot);\n manager._addDevice(deviceSource);\n }\n };\n const onDeviceDisconnected = (deviceType, deviceSlot) => {\n var _a;\n if ((_a = this._devices[deviceType]) === null || _a === void 0 ? void 0 : _a[deviceSlot]) {\n delete this._devices[deviceType][deviceSlot];\n }\n for (const manager of this._registeredManagers) {\n manager._removeDevice(deviceType, deviceSlot);\n }\n };\n const onInputChanged = (deviceType, deviceSlot, eventData) => {\n if (eventData) {\n for (const manager of this._registeredManagers) {\n manager._onInputChanged(deviceType, deviceSlot, eventData);\n }\n }\n };\n if (typeof _native !== \"undefined\") {\n this._deviceInputSystem = new NativeDeviceInputSystem(onDeviceConnected, onDeviceDisconnected, onInputChanged);\n }\n else {\n this._deviceInputSystem = new WebDeviceInputSystem(engine, onDeviceConnected, onDeviceDisconnected, onInputChanged);\n }\n }\n dispose() {\n this._deviceInputSystem.dispose();\n }\n}\n//# sourceMappingURL=internalDeviceSourceManager.js.map","import { DeviceType } from \"./deviceEnums.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { InternalDeviceSourceManager } from \"../internalDeviceSourceManager.js\";\n/**\n * Class to keep track of devices\n */\nexport class DeviceSourceManager {\n // Public Functions\n /**\n * Gets a DeviceSource, given a type and slot\n * @param deviceType - Type of Device\n * @param deviceSlot - Slot or ID of device\n * @returns DeviceSource\n */\n getDeviceSource(deviceType, deviceSlot) {\n if (deviceSlot === undefined) {\n if (this._firstDevice[deviceType] === undefined) {\n return null;\n }\n deviceSlot = this._firstDevice[deviceType];\n }\n if (!this._devices[deviceType] || this._devices[deviceType][deviceSlot] === undefined) {\n return null;\n }\n return this._devices[deviceType][deviceSlot];\n }\n /**\n * Gets an array of DeviceSource objects for a given device type\n * @param deviceType - Type of Device\n * @returns All available DeviceSources of a given type\n */\n getDeviceSources(deviceType) {\n // If device type hasn't had any devices connected yet, return empty array.\n if (!this._devices[deviceType]) {\n return [];\n }\n return this._devices[deviceType].filter((source) => {\n return !!source;\n });\n }\n /**\n * Default constructor\n * @param engine - Used to get canvas (if applicable)\n */\n constructor(engine) {\n const numberOfDeviceTypes = Object.keys(DeviceType).length / 2;\n this._devices = new Array(numberOfDeviceTypes);\n this._firstDevice = new Array(numberOfDeviceTypes);\n this._engine = engine;\n if (!this._engine._deviceSourceManager) {\n this._engine._deviceSourceManager = new InternalDeviceSourceManager(engine);\n }\n this._engine._deviceSourceManager._refCount++;\n // Observables\n this.onDeviceConnectedObservable = new Observable((observer) => {\n for (const devices of this._devices) {\n if (devices) {\n for (const device of devices) {\n if (device) {\n this.onDeviceConnectedObservable.notifyObserver(observer, device);\n }\n }\n }\n }\n });\n this.onDeviceDisconnectedObservable = new Observable();\n this._engine._deviceSourceManager.registerManager(this);\n this._onDisposeObserver = engine.onDisposeObservable.add(() => {\n this.dispose();\n });\n }\n /**\n * Dispose of DeviceSourceManager\n */\n dispose() {\n // Null out observable refs\n this.onDeviceConnectedObservable.clear();\n this.onDeviceDisconnectedObservable.clear();\n if (this._engine._deviceSourceManager) {\n this._engine._deviceSourceManager.unregisterManager(this);\n if (--this._engine._deviceSourceManager._refCount < 1) {\n this._engine._deviceSourceManager.dispose();\n delete this._engine._deviceSourceManager;\n }\n }\n this._engine.onDisposeObservable.remove(this._onDisposeObserver);\n }\n // Hidden Functions\n /**\n * @param deviceSource - Source to add\n * @internal\n */\n _addDevice(deviceSource) {\n if (!this._devices[deviceSource.deviceType]) {\n this._devices[deviceSource.deviceType] = new Array();\n }\n if (!this._devices[deviceSource.deviceType][deviceSource.deviceSlot]) {\n this._devices[deviceSource.deviceType][deviceSource.deviceSlot] = deviceSource;\n this._updateFirstDevices(deviceSource.deviceType);\n }\n this.onDeviceConnectedObservable.notifyObservers(deviceSource);\n }\n /**\n * @param deviceType - DeviceType\n * @param deviceSlot - DeviceSlot\n * @internal\n */\n _removeDevice(deviceType, deviceSlot) {\n var _a, _b;\n const deviceSource = (_a = this._devices[deviceType]) === null || _a === void 0 ? void 0 : _a[deviceSlot]; // Grab local reference to use before removing from devices\n this.onDeviceDisconnectedObservable.notifyObservers(deviceSource);\n if ((_b = this._devices[deviceType]) === null || _b === void 0 ? void 0 : _b[deviceSlot]) {\n delete this._devices[deviceType][deviceSlot];\n }\n // Even if we don't delete a device, we should still check for the first device as things may have gotten out of sync.\n this._updateFirstDevices(deviceType);\n }\n /**\n * @param deviceType - DeviceType\n * @param deviceSlot - DeviceSlot\n * @param eventData - Event\n * @internal\n */\n _onInputChanged(deviceType, deviceSlot, eventData) {\n var _a, _b;\n (_b = (_a = this._devices[deviceType]) === null || _a === void 0 ? void 0 : _a[deviceSlot]) === null || _b === void 0 ? void 0 : _b.onInputChangedObservable.notifyObservers(eventData);\n }\n // Private Functions\n _updateFirstDevices(type) {\n switch (type) {\n case DeviceType.Keyboard:\n case DeviceType.Mouse:\n this._firstDevice[type] = 0;\n break;\n case DeviceType.Touch:\n case DeviceType.DualSense:\n case DeviceType.DualShock:\n case DeviceType.Xbox:\n case DeviceType.Switch:\n case DeviceType.Generic: {\n delete this._firstDevice[type];\n // eslint-disable-next-line no-case-declarations\n const devices = this._devices[type];\n if (devices) {\n for (let i = 0; i < devices.length; i++) {\n if (devices[i]) {\n this._firstDevice[type] = i;\n break;\n }\n }\n }\n break;\n }\n }\n }\n}\n//# sourceMappingURL=deviceSourceManager.js.map","import { ThinEngine } from \"../../Engines/thinEngine.js\";\n\nThinEngine.prototype.setAlphaConstants = function (r, g, b, a) {\n this._alphaState.setAlphaBlendConstants(r, g, b, a);\n};\nThinEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange = false) {\n if (this._alphaMode === mode) {\n if (!noDepthWriteChange) {\n // Make sure we still have the correct depth mask according to the alpha mode (a transparent material could have forced writting to the depth buffer, for instance)\n const depthMask = mode === 0;\n if (this.depthCullingState.depthMask !== depthMask) {\n this.depthCullingState.depthMask = depthMask;\n }\n }\n return;\n }\n switch (mode) {\n case 0:\n this._alphaState.alphaBlend = false;\n break;\n case 7:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case 8:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);\n this._alphaState.alphaBlend = true;\n break;\n case 2:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case 6:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case 1:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case 3:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case 4:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case 5:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case 9:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);\n this._alphaState.alphaBlend = true;\n break;\n case 10:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);\n this._alphaState.alphaBlend = true;\n break;\n case 11:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ONE, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case 12:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ZERO);\n this._alphaState.alphaBlend = true;\n break;\n case 13:\n 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);\n this._alphaState.alphaBlend = true;\n break;\n case 14:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);\n this._alphaState.alphaBlend = true;\n break;\n case 15:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ONE, this._gl.ZERO);\n this._alphaState.alphaBlend = true;\n break;\n case 16:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ZERO, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case 17:\n // Same as ALPHA_COMBINE but accumulates (1 - alpha) values in the alpha channel for a later readout in order independant transparency\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);\n this._alphaState.alphaBlend = true;\n break;\n }\n if (!noDepthWriteChange) {\n this.depthCullingState.depthMask = mode === 0;\n }\n this._alphaMode = mode;\n};\nThinEngine.prototype.getAlphaMode = function () {\n return this._alphaMode;\n};\nThinEngine.prototype.setAlphaEquation = function (equation) {\n if (this._alphaEquation === equation) {\n return;\n }\n switch (equation) {\n case 0:\n this._alphaState.setAlphaEquationParameters(32774, 32774);\n break;\n case 1:\n this._alphaState.setAlphaEquationParameters(32778, 32778);\n break;\n case 2:\n this._alphaState.setAlphaEquationParameters(32779, 32779);\n break;\n case 3:\n this._alphaState.setAlphaEquationParameters(32776, 32776);\n break;\n case 4:\n this._alphaState.setAlphaEquationParameters(32775, 32775);\n break;\n case 5:\n this._alphaState.setAlphaEquationParameters(32775, 32774);\n break;\n }\n this._alphaEquation = equation;\n};\nThinEngine.prototype.getAlphaEquation = function () {\n return this._alphaEquation;\n};\n//# sourceMappingURL=engine.alpha.js.map","import { ThinEngine } from \"../../Engines/thinEngine.js\";\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nThinEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset = 0) {\n // Force cache update\n this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;\n this.bindIndexBuffer(indexBuffer);\n let view;\n if (indexBuffer.is32Bits) {\n // anything else than Uint32Array needs to be converted to Uint32Array\n view = indices instanceof Uint32Array ? indices : new Uint32Array(indices);\n }\n else {\n // anything else than Uint16Array needs to be converted to Uint16Array\n view = indices instanceof Uint16Array ? indices : new Uint16Array(indices);\n }\n this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, view, this._gl.DYNAMIC_DRAW);\n this._resetIndexBufferBinding();\n};\nThinEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {\n this.bindArrayBuffer(vertexBuffer);\n if (byteOffset === undefined) {\n byteOffset = 0;\n }\n const dataLength = data.byteLength || data.length;\n if (byteLength === undefined || (byteLength >= dataLength && byteOffset === 0)) {\n if (data instanceof Array) {\n this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));\n }\n else {\n this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);\n }\n }\n else {\n if (data instanceof Array) {\n this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));\n }\n else {\n if (data instanceof ArrayBuffer) {\n data = new Uint8Array(data, byteOffset, byteLength);\n }\n else {\n data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);\n }\n this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);\n }\n }\n this._resetVertexBufferBinding();\n};\n//# sourceMappingURL=engine.dynamicBuffer.js.map","import { ThinEngine } from \"../../Engines/thinEngine.js\";\n\n/**\n * Allocate a typed array depending on a texture type. Optionally can copy existing data in the buffer.\n * @param type type of the texture\n * @param sizeOrDstBuffer size of the array OR an existing buffer that will be used as the destination of the copy (if copyBuffer is provided)\n * @param sizeInBytes true if the size of the array is given in bytes, false if it is the number of elements of the array\n * @param copyBuffer if provided, buffer to copy into the destination buffer (either a newly allocated buffer if sizeOrDstBuffer is a number or use sizeOrDstBuffer as the destination buffer otherwise)\n * @returns the allocated buffer or sizeOrDstBuffer if the latter is an ArrayBuffer\n */\nexport function allocateAndCopyTypedBuffer(type, sizeOrDstBuffer, sizeInBytes = false, copyBuffer) {\n switch (type) {\n case 3: {\n const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Int8Array(sizeOrDstBuffer) : new Int8Array(sizeOrDstBuffer);\n if (copyBuffer) {\n buffer.set(new Int8Array(copyBuffer));\n }\n return buffer;\n }\n case 0: {\n const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint8Array(sizeOrDstBuffer) : new Uint8Array(sizeOrDstBuffer);\n if (copyBuffer) {\n buffer.set(new Uint8Array(copyBuffer));\n }\n return buffer;\n }\n case 4: {\n const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Int16Array(sizeOrDstBuffer) : new Int16Array(sizeInBytes ? sizeOrDstBuffer / 2 : sizeOrDstBuffer);\n if (copyBuffer) {\n buffer.set(new Int16Array(copyBuffer));\n }\n return buffer;\n }\n case 5:\n case 8:\n case 9:\n case 10:\n case 2: {\n const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint16Array(sizeOrDstBuffer) : new Uint16Array(sizeInBytes ? sizeOrDstBuffer / 2 : sizeOrDstBuffer);\n if (copyBuffer) {\n buffer.set(new Uint16Array(copyBuffer));\n }\n return buffer;\n }\n case 6: {\n const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Int32Array(sizeOrDstBuffer) : new Int32Array(sizeInBytes ? sizeOrDstBuffer / 4 : sizeOrDstBuffer);\n if (copyBuffer) {\n buffer.set(new Int32Array(copyBuffer));\n }\n return buffer;\n }\n case 7:\n case 11:\n case 12:\n case 13:\n case 14:\n case 15: {\n const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint32Array(sizeOrDstBuffer) : new Uint32Array(sizeInBytes ? sizeOrDstBuffer / 4 : sizeOrDstBuffer);\n if (copyBuffer) {\n buffer.set(new Uint32Array(copyBuffer));\n }\n return buffer;\n }\n case 1: {\n const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Float32Array(sizeOrDstBuffer) : new Float32Array(sizeInBytes ? sizeOrDstBuffer / 4 : sizeOrDstBuffer);\n if (copyBuffer) {\n buffer.set(new Float32Array(copyBuffer));\n }\n return buffer;\n }\n }\n const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint8Array(sizeOrDstBuffer) : new Uint8Array(sizeOrDstBuffer);\n if (copyBuffer) {\n buffer.set(new Uint8Array(copyBuffer));\n }\n return buffer;\n}\nThinEngine.prototype._readTexturePixelsSync = function (texture, width, height, faceIndex = -1, level = 0, buffer = null, flushRenderer = true, noDataConversion = false, x = 0, y = 0) {\n var _a, _b;\n const gl = this._gl;\n if (!gl) {\n throw new Error(\"Engine does not have gl rendering context.\");\n }\n if (!this._dummyFramebuffer) {\n const dummy = gl.createFramebuffer();\n if (!dummy) {\n throw new Error(\"Unable to create dummy framebuffer\");\n }\n this._dummyFramebuffer = dummy;\n }\n gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);\n if (faceIndex > -1) {\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, (_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource, level);\n }\n else {\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, (_b = texture._hardwareTexture) === null || _b === void 0 ? void 0 : _b.underlyingResource, level);\n }\n let readType = texture.type !== undefined ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;\n if (!noDataConversion) {\n switch (readType) {\n case gl.UNSIGNED_BYTE:\n if (!buffer) {\n buffer = new Uint8Array(4 * width * height);\n }\n readType = gl.UNSIGNED_BYTE;\n break;\n default:\n if (!buffer) {\n buffer = new Float32Array(4 * width * height);\n }\n readType = gl.FLOAT;\n break;\n }\n }\n else if (!buffer) {\n buffer = allocateAndCopyTypedBuffer(texture.type, 4 * width * height);\n }\n if (flushRenderer) {\n this.flushFramebuffer();\n }\n gl.readPixels(x, y, width, height, gl.RGBA, readType, buffer);\n gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);\n return buffer;\n};\nThinEngine.prototype._readTexturePixels = function (texture, width, height, faceIndex = -1, level = 0, buffer = null, flushRenderer = true, noDataConversion = false, x = 0, y = 0) {\n return Promise.resolve(this._readTexturePixelsSync(texture, width, height, faceIndex, level, buffer, flushRenderer, noDataConversion, x, y));\n};\n//# sourceMappingURL=engine.readTexture.js.map","import { ThinEngine } from \"../../Engines/thinEngine.js\";\nimport { WebGLDataBuffer } from \"../../Meshes/WebGL/webGLDataBuffer.js\";\nThinEngine.prototype.createUniformBuffer = function (elements) {\n const ubo = this._gl.createBuffer();\n if (!ubo) {\n throw new Error(\"Unable to create uniform buffer\");\n }\n const result = new WebGLDataBuffer(ubo);\n this.bindUniformBuffer(result);\n if (elements instanceof Float32Array) {\n this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);\n }\n else {\n this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);\n }\n this.bindUniformBuffer(null);\n result.references = 1;\n return result;\n};\nThinEngine.prototype.createDynamicUniformBuffer = function (elements) {\n const ubo = this._gl.createBuffer();\n if (!ubo) {\n throw new Error(\"Unable to create dynamic uniform buffer\");\n }\n const result = new WebGLDataBuffer(ubo);\n this.bindUniformBuffer(result);\n if (elements instanceof Float32Array) {\n this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);\n }\n else {\n this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);\n }\n this.bindUniformBuffer(null);\n result.references = 1;\n return result;\n};\nThinEngine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {\n this.bindUniformBuffer(uniformBuffer);\n if (offset === undefined) {\n offset = 0;\n }\n if (count === undefined) {\n if (elements instanceof Float32Array) {\n this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);\n }\n else {\n this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));\n }\n }\n else {\n if (elements instanceof Float32Array) {\n this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));\n }\n else {\n this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));\n }\n }\n this.bindUniformBuffer(null);\n};\nThinEngine.prototype.bindUniformBuffer = function (buffer) {\n this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer ? buffer.underlyingResource : null);\n};\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nThinEngine.prototype.bindUniformBufferBase = function (buffer, location, name) {\n this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer ? buffer.underlyingResource : null);\n};\nThinEngine.prototype.bindUniformBlock = function (pipelineContext, blockName, index) {\n const program = pipelineContext.program;\n const uniformLocation = this._gl.getUniformBlockIndex(program, blockName);\n if (uniformLocation !== 0xffffffff) {\n this._gl.uniformBlockBinding(program, uniformLocation, index);\n }\n};\n//# sourceMappingURL=engine.uniformBuffer.js.map","const defaultAttributeKeywordName = \"attribute\";\nconst defaultVaryingKeywordName = \"varying\";\n/** @internal */\nexport class ShaderCodeNode {\n constructor() {\n this.children = [];\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isValid(preprocessors) {\n return true;\n }\n process(preprocessors, options) {\n var _a, _b, _c, _d, _e, _f, _g;\n let result = \"\";\n if (this.line) {\n let value = this.line;\n const processor = options.processor;\n if (processor) {\n // This must be done before other replacements to avoid mistakenly changing something that was already changed.\n if (processor.lineProcessor) {\n value = processor.lineProcessor(value, options.isFragment, options.processingContext);\n }\n const attributeKeyword = (_b = (_a = options.processor) === null || _a === void 0 ? void 0 : _a.attributeKeywordName) !== null && _b !== void 0 ? _b : defaultAttributeKeywordName;\n const varyingKeyword = options.isFragment && ((_c = options.processor) === null || _c === void 0 ? void 0 : _c.varyingFragmentKeywordName)\n ? (_d = options.processor) === null || _d === void 0 ? void 0 : _d.varyingFragmentKeywordName\n : !options.isFragment && ((_e = options.processor) === null || _e === void 0 ? void 0 : _e.varyingVertexKeywordName)\n ? (_f = options.processor) === null || _f === void 0 ? void 0 : _f.varyingVertexKeywordName\n : defaultVaryingKeywordName;\n if (!options.isFragment && processor.attributeProcessor && this.line.startsWith(attributeKeyword)) {\n value = processor.attributeProcessor(this.line, preprocessors, options.processingContext);\n }\n else if (processor.varyingProcessor &&\n (((_g = processor.varyingCheck) === null || _g === void 0 ? void 0 : _g.call(processor, this.line, options.isFragment)) || (!processor.varyingCheck && this.line.startsWith(varyingKeyword)))) {\n value = processor.varyingProcessor(this.line, options.isFragment, preprocessors, options.processingContext);\n }\n else if (processor.uniformProcessor && processor.uniformRegexp && processor.uniformRegexp.test(this.line)) {\n if (!options.lookForClosingBracketForUniformBuffer) {\n value = processor.uniformProcessor(this.line, options.isFragment, preprocessors, options.processingContext);\n }\n }\n else if (processor.uniformBufferProcessor && processor.uniformBufferRegexp && processor.uniformBufferRegexp.test(this.line)) {\n if (!options.lookForClosingBracketForUniformBuffer) {\n value = processor.uniformBufferProcessor(this.line, options.isFragment, options.processingContext);\n options.lookForClosingBracketForUniformBuffer = true;\n }\n }\n else if (processor.textureProcessor && processor.textureRegexp && processor.textureRegexp.test(this.line)) {\n value = processor.textureProcessor(this.line, options.isFragment, preprocessors, options.processingContext);\n }\n else if ((processor.uniformProcessor || processor.uniformBufferProcessor) && this.line.startsWith(\"uniform\") && !options.lookForClosingBracketForUniformBuffer) {\n const regex = /uniform\\s+(?:(?:highp)?|(?:lowp)?)\\s*(\\S+)\\s+(\\S+)\\s*;/;\n if (regex.test(this.line)) {\n // uniform\n if (processor.uniformProcessor) {\n value = processor.uniformProcessor(this.line, options.isFragment, preprocessors, options.processingContext);\n }\n }\n else {\n // Uniform buffer\n if (processor.uniformBufferProcessor) {\n value = processor.uniformBufferProcessor(this.line, options.isFragment, options.processingContext);\n options.lookForClosingBracketForUniformBuffer = true;\n }\n }\n }\n if (options.lookForClosingBracketForUniformBuffer && this.line.indexOf(\"}\") !== -1) {\n options.lookForClosingBracketForUniformBuffer = false;\n if (processor.endOfUniformBufferProcessor) {\n value = processor.endOfUniformBufferProcessor(this.line, options.isFragment, options.processingContext);\n }\n }\n }\n result += value + \"\\r\\n\";\n }\n this.children.forEach((child) => {\n result += child.process(preprocessors, options);\n });\n if (this.additionalDefineKey) {\n preprocessors[this.additionalDefineKey] = this.additionalDefineValue || \"true\";\n }\n return result;\n }\n}\n//# sourceMappingURL=shaderCodeNode.js.map","/** @internal */\nexport class ShaderCodeCursor {\n constructor() {\n this._lines = [];\n }\n get currentLine() {\n return this._lines[this.lineIndex];\n }\n get canRead() {\n return this.lineIndex < this._lines.length - 1;\n }\n set lines(value) {\n this._lines.length = 0;\n for (const line of value) {\n // Prevent removing line break in macros.\n if (line[0] === \"#\") {\n this._lines.push(line);\n continue;\n }\n // Do not split single line comments\n if (line.trim().startsWith(\"//\")) {\n this._lines.push(line);\n continue;\n }\n const split = line.split(\";\");\n for (let index = 0; index < split.length; index++) {\n let subLine = split[index];\n subLine = subLine.trim();\n if (!subLine) {\n continue;\n }\n this._lines.push(subLine + (index !== split.length - 1 ? \";\" : \"\"));\n }\n }\n }\n}\n//# sourceMappingURL=shaderCodeCursor.js.map","import { ShaderCodeNode } from \"./shaderCodeNode.js\";\n/** @internal */\nexport class ShaderCodeConditionNode extends ShaderCodeNode {\n process(preprocessors, options) {\n for (let index = 0; index < this.children.length; index++) {\n const node = this.children[index];\n if (node.isValid(preprocessors)) {\n return node.process(preprocessors, options);\n }\n }\n return \"\";\n }\n}\n//# sourceMappingURL=shaderCodeConditionNode.js.map","import { ShaderCodeNode } from \"./shaderCodeNode.js\";\n/** @internal */\nexport class ShaderCodeTestNode extends ShaderCodeNode {\n isValid(preprocessors) {\n return this.testExpression.isTrue(preprocessors);\n }\n}\n//# sourceMappingURL=shaderCodeTestNode.js.map","/* eslint-disable @typescript-eslint/naming-convention */\n/** @internal */\nexport class ShaderDefineExpression {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isTrue(preprocessors) {\n return true;\n }\n static postfixToInfix(postfix) {\n const stack = [];\n for (const c of postfix) {\n if (ShaderDefineExpression._OperatorPriority[c] === undefined) {\n stack.push(c);\n }\n else {\n const v1 = stack[stack.length - 1], v2 = stack[stack.length - 2];\n stack.length -= 2;\n stack.push(`(${v2}${c}${v1})`);\n }\n }\n return stack[stack.length - 1];\n }\n /**\n * Converts an infix expression to a postfix expression.\n *\n * This method is used to transform infix expressions, which are more human-readable,\n * into postfix expressions, also known as Reverse Polish Notation (RPN), that can be\n * evaluated more efficiently by a computer. The conversion is based on the operator\n * priority defined in _OperatorPriority.\n *\n * The function employs a stack-based algorithm for the conversion and caches the result\n * to improve performance. The cache keeps track of each converted expression's access time\n * to manage the cache size and optimize memory usage. When the cache size exceeds a specified\n * limit, the least recently accessed items in the cache are deleted.\n *\n * The cache mechanism is particularly helpful for shader compilation, where the same infix\n * expressions might be encountered repeatedly, hence the caching can speed up the process.\n *\n * @param infix - The infix expression to be converted.\n * @returns The postfix expression as an array of strings.\n */\n static infixToPostfix(infix) {\n // Is infix already in cache\n const cacheItem = ShaderDefineExpression._InfixToPostfixCache.get(infix);\n if (cacheItem) {\n cacheItem.accessTime = Date.now();\n return cacheItem.result;\n }\n // Is infix contain any operator\n if (!infix.includes(\"&&\") && !infix.includes(\"||\") && !infix.includes(\")\") && !infix.includes(\"(\")) {\n return [infix];\n }\n const result = [];\n let stackIdx = -1;\n const pushOperand = () => {\n operand = operand.trim();\n if (operand !== \"\") {\n result.push(operand);\n operand = \"\";\n }\n };\n const push = (s) => {\n if (stackIdx < ShaderDefineExpression._Stack.length - 1) {\n ShaderDefineExpression._Stack[++stackIdx] = s;\n }\n };\n const peek = () => ShaderDefineExpression._Stack[stackIdx];\n const pop = () => (stackIdx === -1 ? \"!!INVALID EXPRESSION!!\" : ShaderDefineExpression._Stack[stackIdx--]);\n let idx = 0, operand = \"\";\n while (idx < infix.length) {\n const c = infix.charAt(idx), token = idx < infix.length - 1 ? infix.substr(idx, 2) : \"\";\n if (c === \"(\") {\n operand = \"\";\n push(c);\n }\n else if (c === \")\") {\n pushOperand();\n while (stackIdx !== -1 && peek() !== \"(\") {\n result.push(pop());\n }\n pop();\n }\n else if (ShaderDefineExpression._OperatorPriority[token] > 1) {\n pushOperand();\n while (stackIdx !== -1 && ShaderDefineExpression._OperatorPriority[peek()] >= ShaderDefineExpression._OperatorPriority[token]) {\n result.push(pop());\n }\n push(token);\n idx++;\n }\n else {\n operand += c;\n }\n idx++;\n }\n pushOperand();\n while (stackIdx !== -1) {\n if (peek() === \"(\") {\n pop();\n }\n else {\n result.push(pop());\n }\n }\n // If the cache is at capacity, clear it before adding a new item\n if (ShaderDefineExpression._InfixToPostfixCache.size >= ShaderDefineExpression.InfixToPostfixCacheLimitSize) {\n ShaderDefineExpression.ClearCache();\n }\n // Add the new item to the cache, including the current time as the last access time\n ShaderDefineExpression._InfixToPostfixCache.set(infix, { result, accessTime: Date.now() });\n return result;\n }\n static ClearCache() {\n // Convert the cache to an array and sort by last access time\n const sortedCache = Array.from(ShaderDefineExpression._InfixToPostfixCache.entries()).sort((a, b) => a[1].accessTime - b[1].accessTime);\n // Remove the least recently accessed half of the cache\n for (let i = 0; i < ShaderDefineExpression.InfixToPostfixCacheCleanupSize; i++) {\n ShaderDefineExpression._InfixToPostfixCache.delete(sortedCache[i][0]);\n }\n }\n}\n/**\n * Cache items count limit for the InfixToPostfix cache.\n * It uses to improve the performance of the shader compilation.\n * For details see PR: https://github.com/BabylonJS/Babylon.js/pull/13936\n */\nShaderDefineExpression.InfixToPostfixCacheLimitSize = 50000;\n/**\n * When the cache size is exceeded, a cache cleanup will be triggered\n * and the cache will be reduced by the size specified\n * in the InfixToPostfixCacheCleanupSize variable, removing entries\n * that have not been accessed the longest.\n */\nShaderDefineExpression.InfixToPostfixCacheCleanupSize = 25000;\nShaderDefineExpression._InfixToPostfixCache = new Map();\nShaderDefineExpression._OperatorPriority = {\n \")\": 0,\n \"(\": 1,\n \"||\": 2,\n \"&&\": 3,\n};\nShaderDefineExpression._Stack = [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"];\n//# sourceMappingURL=shaderDefineExpression.js.map","import { ShaderDefineExpression } from \"../shaderDefineExpression.js\";\n/** @internal */\nexport class ShaderDefineIsDefinedOperator extends ShaderDefineExpression {\n constructor(define, not = false) {\n super();\n this.define = define;\n this.not = not;\n }\n isTrue(preprocessors) {\n let condition = preprocessors[this.define] !== undefined;\n if (this.not) {\n condition = !condition;\n }\n return condition;\n }\n}\n//# sourceMappingURL=shaderDefineIsDefinedOperator.js.map","import { ShaderDefineExpression } from \"../shaderDefineExpression.js\";\n/** @internal */\nexport class ShaderDefineAndOperator extends ShaderDefineExpression {\n isTrue(preprocessors) {\n return this.leftOperand.isTrue(preprocessors) && this.rightOperand.isTrue(preprocessors);\n }\n}\n//# sourceMappingURL=shaderDefineAndOperator.js.map","import { ShaderDefineExpression } from \"../shaderDefineExpression.js\";\n/** @internal */\nexport class ShaderDefineArithmeticOperator extends ShaderDefineExpression {\n constructor(define, operand, testValue) {\n super();\n this.define = define;\n this.operand = operand;\n this.testValue = testValue;\n }\n isTrue(preprocessors) {\n let value = preprocessors[this.define];\n if (value === undefined) {\n value = this.define;\n }\n let condition = false;\n const left = parseInt(value);\n const right = parseInt(this.testValue);\n switch (this.operand) {\n case \">\":\n condition = left > right;\n break;\n case \"<\":\n condition = left < right;\n break;\n case \"<=\":\n condition = left <= right;\n break;\n case \">=\":\n condition = left >= right;\n break;\n case \"==\":\n condition = left === right;\n break;\n case \"!=\":\n condition = left !== right;\n break;\n }\n return condition;\n }\n}\n//# sourceMappingURL=shaderDefineArithmeticOperator.js.map","/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { ShaderCodeNode } from \"./shaderCodeNode.js\";\nimport { ShaderCodeCursor } from \"./shaderCodeCursor.js\";\nimport { ShaderCodeConditionNode } from \"./shaderCodeConditionNode.js\";\nimport { ShaderCodeTestNode } from \"./shaderCodeTestNode.js\";\nimport { ShaderDefineIsDefinedOperator } from \"./Expressions/Operators/shaderDefineIsDefinedOperator.js\";\nimport { ShaderDefineOrOperator } from \"./Expressions/Operators/shaderDefineOrOperator.js\";\nimport { ShaderDefineAndOperator } from \"./Expressions/Operators/shaderDefineAndOperator.js\";\nimport { ShaderDefineExpression } from \"./Expressions/shaderDefineExpression.js\";\nimport { ShaderDefineArithmeticOperator } from \"./Expressions/Operators/shaderDefineArithmeticOperator.js\";\nimport { _WarnImport } from \"../../Misc/devTools.js\";\nimport { ShaderLanguage } from \"../../Materials/shaderLanguage.js\";\nconst regexSE = /defined\\s*?\\((.+?)\\)/g;\nconst regexSERevert = /defined\\s*?\\[(.+?)\\]/g;\nconst regexShaderInclude = /#include\\s?<(.+)>(\\((.*)\\))*(\\[(.*)\\])*/g;\nconst regexShaderDecl = /__decl__/;\nconst regexLightX = /light\\{X\\}.(\\w*)/g;\nconst regexX = /\\{X\\}/g;\nconst reusableMatches = [];\n/** @internal */\nexport class ShaderProcessor {\n static Initialize(options) {\n if (options.processor && options.processor.initializeShaders) {\n options.processor.initializeShaders(options.processingContext);\n }\n }\n static Process(sourceCode, options, callback, engine) {\n var _a;\n if ((_a = options.processor) === null || _a === void 0 ? void 0 : _a.preProcessShaderCode) {\n sourceCode = options.processor.preProcessShaderCode(sourceCode, options.isFragment);\n }\n this._ProcessIncludes(sourceCode, options, (codeWithIncludes) => {\n if (options.processCodeAfterIncludes) {\n codeWithIncludes = options.processCodeAfterIncludes(options.isFragment ? \"fragment\" : \"vertex\", codeWithIncludes);\n }\n const migratedCode = this._ProcessShaderConversion(codeWithIncludes, options, engine);\n callback(migratedCode, codeWithIncludes);\n });\n }\n static PreProcess(sourceCode, options, callback, engine) {\n var _a;\n if ((_a = options.processor) === null || _a === void 0 ? void 0 : _a.preProcessShaderCode) {\n sourceCode = options.processor.preProcessShaderCode(sourceCode, options.isFragment);\n }\n this._ProcessIncludes(sourceCode, options, (codeWithIncludes) => {\n if (options.processCodeAfterIncludes) {\n codeWithIncludes = options.processCodeAfterIncludes(options.isFragment ? \"fragment\" : \"vertex\", codeWithIncludes);\n }\n const migratedCode = this._ApplyPreProcessing(codeWithIncludes, options, engine);\n callback(migratedCode, codeWithIncludes);\n });\n }\n static Finalize(vertexCode, fragmentCode, options) {\n if (!options.processor || !options.processor.finalizeShaders) {\n return { vertexCode, fragmentCode };\n }\n return options.processor.finalizeShaders(vertexCode, fragmentCode, options.processingContext);\n }\n static _ProcessPrecision(source, options) {\n var _a;\n if ((_a = options.processor) === null || _a === void 0 ? void 0 : _a.noPrecision) {\n return source;\n }\n const shouldUseHighPrecisionShader = options.shouldUseHighPrecisionShader;\n if (source.indexOf(\"precision highp float\") === -1) {\n if (!shouldUseHighPrecisionShader) {\n source = \"precision mediump float;\\n\" + source;\n }\n else {\n source = \"precision highp float;\\n\" + source;\n }\n }\n else {\n if (!shouldUseHighPrecisionShader) {\n // Moving highp to mediump\n source = source.replace(\"precision highp float\", \"precision mediump float\");\n }\n }\n return source;\n }\n static _ExtractOperation(expression) {\n const regex = /defined\\((.+)\\)/;\n const match = regex.exec(expression);\n if (match && match.length) {\n return new ShaderDefineIsDefinedOperator(match[1].trim(), expression[0] === \"!\");\n }\n const operators = [\"==\", \"!=\", \">=\", \"<=\", \"<\", \">\"];\n let operator = \"\";\n let indexOperator = 0;\n for (operator of operators) {\n indexOperator = expression.indexOf(operator);\n if (indexOperator > -1) {\n break;\n }\n }\n if (indexOperator === -1) {\n return new ShaderDefineIsDefinedOperator(expression);\n }\n const define = expression.substring(0, indexOperator).trim();\n const value = expression.substring(indexOperator + operator.length).trim();\n return new ShaderDefineArithmeticOperator(define, operator, value);\n }\n static _BuildSubExpression(expression) {\n expression = expression.replace(regexSE, \"defined[$1]\");\n const postfix = ShaderDefineExpression.infixToPostfix(expression);\n const stack = [];\n for (const c of postfix) {\n if (c !== \"||\" && c !== \"&&\") {\n stack.push(c);\n }\n else if (stack.length >= 2) {\n let v1 = stack[stack.length - 1], v2 = stack[stack.length - 2];\n stack.length -= 2;\n const operator = c == \"&&\" ? new ShaderDefineAndOperator() : new ShaderDefineOrOperator();\n if (typeof v1 === \"string\") {\n v1 = v1.replace(regexSERevert, \"defined($1)\");\n }\n if (typeof v2 === \"string\") {\n v2 = v2.replace(regexSERevert, \"defined($1)\");\n }\n operator.leftOperand = typeof v2 === \"string\" ? this._ExtractOperation(v2) : v2;\n operator.rightOperand = typeof v1 === \"string\" ? this._ExtractOperation(v1) : v1;\n stack.push(operator);\n }\n }\n let result = stack[stack.length - 1];\n if (typeof result === \"string\") {\n result = result.replace(regexSERevert, \"defined($1)\");\n }\n // note: stack.length !== 1 if there was an error in the parsing\n return typeof result === \"string\" ? this._ExtractOperation(result) : result;\n }\n static _BuildExpression(line, start) {\n const node = new ShaderCodeTestNode();\n const command = line.substring(0, start);\n let expression = line.substring(start);\n expression = expression.substring(0, (expression.indexOf(\"//\") + 1 || expression.length + 1) - 1).trim();\n if (command === \"#ifdef\") {\n node.testExpression = new ShaderDefineIsDefinedOperator(expression);\n }\n else if (command === \"#ifndef\") {\n node.testExpression = new ShaderDefineIsDefinedOperator(expression, true);\n }\n else {\n node.testExpression = this._BuildSubExpression(expression);\n }\n return node;\n }\n static _MoveCursorWithinIf(cursor, rootNode, ifNode) {\n let line = cursor.currentLine;\n while (this._MoveCursor(cursor, ifNode)) {\n line = cursor.currentLine;\n const first5 = line.substring(0, 5).toLowerCase();\n if (first5 === \"#else\") {\n const elseNode = new ShaderCodeNode();\n rootNode.children.push(elseNode);\n this._MoveCursor(cursor, elseNode);\n return;\n }\n else if (first5 === \"#elif\") {\n const elifNode = this._BuildExpression(line, 5);\n rootNode.children.push(elifNode);\n ifNode = elifNode;\n }\n }\n }\n static _MoveCursor(cursor, rootNode) {\n while (cursor.canRead) {\n cursor.lineIndex++;\n const line = cursor.currentLine;\n if (line.indexOf(\"#\") >= 0) {\n const matches = ShaderProcessor._MoveCursorRegex.exec(line);\n if (matches && matches.length) {\n const keyword = matches[0];\n switch (keyword) {\n case \"#ifdef\": {\n const newRootNode = new ShaderCodeConditionNode();\n rootNode.children.push(newRootNode);\n const ifNode = this._BuildExpression(line, 6);\n newRootNode.children.push(ifNode);\n this._MoveCursorWithinIf(cursor, newRootNode, ifNode);\n break;\n }\n case \"#else\":\n case \"#elif\":\n return true;\n case \"#endif\":\n return false;\n case \"#ifndef\": {\n const newRootNode = new ShaderCodeConditionNode();\n rootNode.children.push(newRootNode);\n const ifNode = this._BuildExpression(line, 7);\n newRootNode.children.push(ifNode);\n this._MoveCursorWithinIf(cursor, newRootNode, ifNode);\n break;\n }\n case \"#if\": {\n const newRootNode = new ShaderCodeConditionNode();\n const ifNode = this._BuildExpression(line, 3);\n rootNode.children.push(newRootNode);\n newRootNode.children.push(ifNode);\n this._MoveCursorWithinIf(cursor, newRootNode, ifNode);\n break;\n }\n }\n continue;\n }\n }\n const newNode = new ShaderCodeNode();\n newNode.line = line;\n rootNode.children.push(newNode);\n // Detect additional defines\n if (line[0] === \"#\" && line[1] === \"d\") {\n const split = line.replace(\";\", \"\").split(\" \");\n newNode.additionalDefineKey = split[1];\n if (split.length === 3) {\n newNode.additionalDefineValue = split[2];\n }\n }\n }\n return false;\n }\n static _EvaluatePreProcessors(sourceCode, preprocessors, options) {\n const rootNode = new ShaderCodeNode();\n const cursor = new ShaderCodeCursor();\n cursor.lineIndex = -1;\n cursor.lines = sourceCode.split(\"\\n\");\n // Decompose (We keep it in 2 steps so it is easier to maintain and perf hit is insignificant)\n this._MoveCursor(cursor, rootNode);\n // Recompose\n return rootNode.process(preprocessors, options);\n }\n static _PreparePreProcessors(options, engine) {\n var _a;\n const defines = options.defines;\n const preprocessors = {};\n for (const define of defines) {\n const keyValue = define.replace(\"#define\", \"\").replace(\";\", \"\").trim();\n const split = keyValue.split(\" \");\n preprocessors[split[0]] = split.length > 1 ? split[1] : \"\";\n }\n if (((_a = options.processor) === null || _a === void 0 ? void 0 : _a.shaderLanguage) === ShaderLanguage.GLSL) {\n preprocessors[\"GL_ES\"] = \"true\";\n }\n preprocessors[\"__VERSION__\"] = options.version;\n preprocessors[options.platformName] = \"true\";\n engine._getGlobalDefines(preprocessors);\n return preprocessors;\n }\n static _ProcessShaderConversion(sourceCode, options, engine) {\n let preparedSourceCode = this._ProcessPrecision(sourceCode, options);\n if (!options.processor) {\n return preparedSourceCode;\n }\n // Already converted\n if (options.processor.shaderLanguage === ShaderLanguage.GLSL && preparedSourceCode.indexOf(\"#version 3\") !== -1) {\n preparedSourceCode = preparedSourceCode.replace(\"#version 300 es\", \"\");\n if (!options.processor.parseGLES3) {\n return preparedSourceCode;\n }\n }\n const defines = options.defines;\n const preprocessors = this._PreparePreProcessors(options, engine);\n // General pre processing\n if (options.processor.preProcessor) {\n preparedSourceCode = options.processor.preProcessor(preparedSourceCode, defines, options.isFragment, options.processingContext);\n }\n preparedSourceCode = this._EvaluatePreProcessors(preparedSourceCode, preprocessors, options);\n // Post processing\n if (options.processor.postProcessor) {\n preparedSourceCode = options.processor.postProcessor(preparedSourceCode, defines, options.isFragment, options.processingContext, engine);\n }\n // Inline functions tagged with #define inline\n if (engine._features.needShaderCodeInlining) {\n preparedSourceCode = engine.inlineShaderCode(preparedSourceCode);\n }\n return preparedSourceCode;\n }\n static _ApplyPreProcessing(sourceCode, options, engine) {\n var _a, _b;\n let preparedSourceCode = sourceCode;\n const defines = options.defines;\n const preprocessors = this._PreparePreProcessors(options, engine);\n // General pre processing\n if ((_a = options.processor) === null || _a === void 0 ? void 0 : _a.preProcessor) {\n preparedSourceCode = options.processor.preProcessor(preparedSourceCode, defines, options.isFragment, options.processingContext);\n }\n preparedSourceCode = this._EvaluatePreProcessors(preparedSourceCode, preprocessors, options);\n // Post processing\n if ((_b = options.processor) === null || _b === void 0 ? void 0 : _b.postProcessor) {\n preparedSourceCode = options.processor.postProcessor(preparedSourceCode, defines, options.isFragment, options.processingContext, engine);\n }\n // Inline functions tagged with #define inline\n if (engine._features.needShaderCodeInlining) {\n preparedSourceCode = engine.inlineShaderCode(preparedSourceCode);\n }\n return preparedSourceCode;\n }\n static _ProcessIncludes(sourceCode, options, callback) {\n reusableMatches.length = 0;\n let match;\n // stay back-compat to the old matchAll syntax\n while ((match = regexShaderInclude.exec(sourceCode)) !== null) {\n reusableMatches.push(match);\n }\n let returnValue = String(sourceCode);\n let parts = [sourceCode];\n let keepProcessing = false;\n for (const match of reusableMatches) {\n let includeFile = match[1];\n // Uniform declaration\n if (includeFile.indexOf(\"__decl__\") !== -1) {\n includeFile = includeFile.replace(regexShaderDecl, \"\");\n if (options.supportsUniformBuffers) {\n includeFile = includeFile.replace(\"Vertex\", \"Ubo\").replace(\"Fragment\", \"Ubo\");\n }\n includeFile = includeFile + \"Declaration\";\n }\n if (options.includesShadersStore[includeFile]) {\n // Substitution\n let includeContent = options.includesShadersStore[includeFile];\n if (match[2]) {\n const splits = match[3].split(\",\");\n for (let index = 0; index < splits.length; index += 2) {\n const source = new RegExp(splits[index], \"g\");\n const dest = splits[index + 1];\n includeContent = includeContent.replace(source, dest);\n }\n }\n if (match[4]) {\n const indexString = match[5];\n if (indexString.indexOf(\"..\") !== -1) {\n const indexSplits = indexString.split(\"..\");\n const minIndex = parseInt(indexSplits[0]);\n let maxIndex = parseInt(indexSplits[1]);\n let sourceIncludeContent = includeContent.slice(0);\n includeContent = \"\";\n if (isNaN(maxIndex)) {\n maxIndex = options.indexParameters[indexSplits[1]];\n }\n for (let i = minIndex; i < maxIndex; i++) {\n if (!options.supportsUniformBuffers) {\n // Ubo replacement\n sourceIncludeContent = sourceIncludeContent.replace(regexLightX, (str, p1) => {\n return p1 + \"{X}\";\n });\n }\n includeContent += sourceIncludeContent.replace(regexX, i.toString()) + \"\\n\";\n }\n }\n else {\n if (!options.supportsUniformBuffers) {\n // Ubo replacement\n includeContent = includeContent.replace(regexLightX, (str, p1) => {\n return p1 + \"{X}\";\n });\n }\n includeContent = includeContent.replace(regexX, indexString);\n }\n }\n // Replace\n // Split all parts on match[0] and intersperse the parts with the include content\n const newParts = [];\n for (const part of parts) {\n const splitPart = part.split(match[0]);\n for (let i = 0; i < splitPart.length - 1; i++) {\n newParts.push(splitPart[i]);\n newParts.push(includeContent);\n }\n newParts.push(splitPart[splitPart.length - 1]);\n }\n parts = newParts;\n keepProcessing = keepProcessing || includeContent.indexOf(\"#include<\") >= 0 || includeContent.indexOf(\"#include <\") >= 0;\n }\n else {\n const includeShaderUrl = options.shadersRepository + \"ShadersInclude/\" + includeFile + \".fx\";\n ShaderProcessor._FileToolsLoadFile(includeShaderUrl, (fileContent) => {\n options.includesShadersStore[includeFile] = fileContent;\n this._ProcessIncludes(parts.join(\"\"), options, callback);\n });\n return;\n }\n }\n reusableMatches.length = 0;\n returnValue = parts.join(\"\");\n if (keepProcessing) {\n this._ProcessIncludes(returnValue.toString(), options, callback);\n }\n else {\n callback(returnValue);\n }\n }\n /**\n * Loads a file from a url\n * @param url url to load\n * @param onSuccess callback called when the file successfully loads\n * @param onProgress callback called while file is loading (if the server supports this mode)\n * @param offlineProvider defines the offline provider for caching\n * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer\n * @param onError callback called when the file fails to load\n * @returns a file request object\n * @internal\n */\n static _FileToolsLoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) {\n throw _WarnImport(\"FileTools\");\n }\n}\nShaderProcessor._MoveCursorRegex = /(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;\n//# sourceMappingURL=shaderProcessor.js.map","import { ShaderLanguage } from \"../../Materials/shaderLanguage.js\";\nconst varyingRegex = /(flat\\s)?\\s*varying\\s*.*/;\n/** @internal */\nexport class WebGL2ShaderProcessor {\n constructor() {\n this.shaderLanguage = ShaderLanguage.GLSL;\n }\n attributeProcessor(attribute) {\n return attribute.replace(\"attribute\", \"in\");\n }\n varyingCheck(varying, _isFragment) {\n return varyingRegex.test(varying);\n }\n varyingProcessor(varying, isFragment) {\n return varying.replace(\"varying\", isFragment ? \"in\" : \"out\");\n }\n postProcessor(code, defines, isFragment) {\n const hasDrawBuffersExtension = code.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;\n // Remove extensions\n const regex = /#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;\n code = code.replace(regex, \"\");\n // Replace instructions\n code = code.replace(/texture2D\\s*\\(/g, \"texture(\");\n if (isFragment) {\n code = code.replace(/texture2DLodEXT\\s*\\(/g, \"textureLod(\");\n code = code.replace(/textureCubeLodEXT\\s*\\(/g, \"textureLod(\");\n code = code.replace(/textureCube\\s*\\(/g, \"texture(\");\n code = code.replace(/gl_FragDepthEXT/g, \"gl_FragDepth\");\n code = code.replace(/gl_FragColor/g, \"glFragColor\");\n code = code.replace(/gl_FragData/g, \"glFragData\");\n code = code.replace(/void\\s+?main\\s*\\(/g, (hasDrawBuffersExtension ? \"\" : \"layout(location = 0) out vec4 glFragColor;\\n\") + \"void main(\");\n }\n else {\n const hasMultiviewExtension = defines.indexOf(\"#define MULTIVIEW\") !== -1;\n if (hasMultiviewExtension) {\n return \"#extension GL_OVR_multiview2 : require\\nlayout (num_views = 2) in;\\n\" + code;\n }\n }\n return code;\n }\n}\n//# sourceMappingURL=webGL2ShaderProcessors.js.map","/** @internal */\nexport class WebGLHardwareTexture {\n get underlyingResource() {\n return this._webGLTexture;\n }\n constructor(existingTexture = null, context) {\n // There can be multiple buffers for a single WebGL texture because different layers of a 2DArrayTexture / 3DTexture\n // or different faces of a cube texture can be bound to different render targets at the same time.\n this._MSAARenderBuffers = null;\n this._context = context;\n if (!existingTexture) {\n existingTexture = context.createTexture();\n if (!existingTexture) {\n throw new Error(\"Unable to create webGL texture\");\n }\n }\n this.set(existingTexture);\n }\n setUsage() { }\n set(hardwareTexture) {\n this._webGLTexture = hardwareTexture;\n }\n reset() {\n this._webGLTexture = null;\n this._MSAARenderBuffers = null;\n }\n addMSAARenderBuffer(buffer) {\n if (!this._MSAARenderBuffers) {\n this._MSAARenderBuffers = [];\n }\n this._MSAARenderBuffers.push(buffer);\n }\n releaseMSAARenderBuffers() {\n if (this._MSAARenderBuffers) {\n for (const buffer of this._MSAARenderBuffers) {\n this._context.deleteRenderbuffer(buffer);\n }\n this._MSAARenderBuffers = null;\n }\n }\n release() {\n this.releaseMSAARenderBuffers();\n if (this._webGLTexture) {\n this._context.deleteTexture(this._webGLTexture);\n }\n this.reset();\n }\n}\n//# sourceMappingURL=webGLHardwareTexture.js.map","/** @internal */\nexport class WebGLPipelineContext {\n constructor() {\n this._valueCache = {};\n this.vertexCompilationError = null;\n this.fragmentCompilationError = null;\n this.programLinkError = null;\n this.programValidationError = null;\n }\n get isAsync() {\n return this.isParallelCompiled;\n }\n get isReady() {\n if (this.program) {\n if (this.isParallelCompiled) {\n return this.engine._isRenderingStateCompiled(this);\n }\n return true;\n }\n return false;\n }\n _handlesSpectorRebuildCallback(onCompiled) {\n if (onCompiled && this.program) {\n onCompiled(this.program);\n }\n }\n _fillEffectInformation(effect, uniformBuffersNames, uniformsNames, uniforms, samplerList, samplers, attributesNames, attributes) {\n const engine = this.engine;\n if (engine.supportsUniformBuffers) {\n for (const name in uniformBuffersNames) {\n effect.bindUniformBlock(name, uniformBuffersNames[name]);\n }\n }\n const effectAvailableUniforms = this.engine.getUniforms(this, uniformsNames);\n effectAvailableUniforms.forEach((uniform, index) => {\n uniforms[uniformsNames[index]] = uniform;\n });\n this._uniforms = uniforms;\n let index;\n for (index = 0; index < samplerList.length; index++) {\n const sampler = effect.getUniform(samplerList[index]);\n if (sampler == null) {\n samplerList.splice(index, 1);\n index--;\n }\n }\n samplerList.forEach((name, index) => {\n samplers[name] = index;\n });\n for (const attr of engine.getAttributes(this, attributesNames)) {\n attributes.push(attr);\n }\n }\n /**\n * Release all associated resources.\n **/\n dispose() {\n this._uniforms = {};\n }\n /**\n * @internal\n */\n _cacheMatrix(uniformName, matrix) {\n const cache = this._valueCache[uniformName];\n const flag = matrix.updateFlag;\n if (cache !== undefined && cache === flag) {\n return false;\n }\n this._valueCache[uniformName] = flag;\n return true;\n }\n /**\n * @internal\n */\n _cacheFloat2(uniformName, x, y) {\n let cache = this._valueCache[uniformName];\n if (!cache || cache.length !== 2) {\n cache = [x, y];\n this._valueCache[uniformName] = cache;\n return true;\n }\n let changed = false;\n if (cache[0] !== x) {\n cache[0] = x;\n changed = true;\n }\n if (cache[1] !== y) {\n cache[1] = y;\n changed = true;\n }\n return changed;\n }\n /**\n * @internal\n */\n _cacheFloat3(uniformName, x, y, z) {\n let cache = this._valueCache[uniformName];\n if (!cache || cache.length !== 3) {\n cache = [x, y, z];\n this._valueCache[uniformName] = cache;\n return true;\n }\n let changed = false;\n if (cache[0] !== x) {\n cache[0] = x;\n changed = true;\n }\n if (cache[1] !== y) {\n cache[1] = y;\n changed = true;\n }\n if (cache[2] !== z) {\n cache[2] = z;\n changed = true;\n }\n return changed;\n }\n /**\n * @internal\n */\n _cacheFloat4(uniformName, x, y, z, w) {\n let cache = this._valueCache[uniformName];\n if (!cache || cache.length !== 4) {\n cache = [x, y, z, w];\n this._valueCache[uniformName] = cache;\n return true;\n }\n let changed = false;\n if (cache[0] !== x) {\n cache[0] = x;\n changed = true;\n }\n if (cache[1] !== y) {\n cache[1] = y;\n changed = true;\n }\n if (cache[2] !== z) {\n cache[2] = z;\n changed = true;\n }\n if (cache[3] !== w) {\n cache[3] = w;\n changed = true;\n }\n return changed;\n }\n /**\n * Sets an integer value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value Value to be set.\n */\n setInt(uniformName, value) {\n const cache = this._valueCache[uniformName];\n if (cache !== undefined && cache === value) {\n return;\n }\n if (this.engine.setInt(this._uniforms[uniformName], value)) {\n this._valueCache[uniformName] = value;\n }\n }\n /**\n * Sets a int2 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First int in int2.\n * @param y Second int in int2.\n */\n setInt2(uniformName, x, y) {\n if (this._cacheFloat2(uniformName, x, y)) {\n if (!this.engine.setInt2(this._uniforms[uniformName], x, y)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a int3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First int in int3.\n * @param y Second int in int3.\n * @param z Third int in int3.\n */\n setInt3(uniformName, x, y, z) {\n if (this._cacheFloat3(uniformName, x, y, z)) {\n if (!this.engine.setInt3(this._uniforms[uniformName], x, y, z)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a int4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First int in int4.\n * @param y Second int in int4.\n * @param z Third int in int4.\n * @param w Fourth int in int4.\n */\n setInt4(uniformName, x, y, z, w) {\n if (this._cacheFloat4(uniformName, x, y, z, w)) {\n if (!this.engine.setInt4(this._uniforms[uniformName], x, y, z, w)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets an int array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setIntArray(uniformName, array) {\n this._valueCache[uniformName] = null;\n this.engine.setIntArray(this._uniforms[uniformName], array);\n }\n /**\n * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setIntArray2(uniformName, array) {\n this._valueCache[uniformName] = null;\n this.engine.setIntArray2(this._uniforms[uniformName], array);\n }\n /**\n * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setIntArray3(uniformName, array) {\n this._valueCache[uniformName] = null;\n this.engine.setIntArray3(this._uniforms[uniformName], array);\n }\n /**\n * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setIntArray4(uniformName, array) {\n this._valueCache[uniformName] = null;\n this.engine.setIntArray4(this._uniforms[uniformName], array);\n }\n /**\n * Sets an unsigned integer value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value Value to be set.\n */\n setUInt(uniformName, value) {\n const cache = this._valueCache[uniformName];\n if (cache !== undefined && cache === value) {\n return;\n }\n if (this.engine.setUInt(this._uniforms[uniformName], value)) {\n this._valueCache[uniformName] = value;\n }\n }\n /**\n * Sets an unsigned int2 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First unsigned int in uint2.\n * @param y Second unsigned int in uint2.\n */\n setUInt2(uniformName, x, y) {\n if (this._cacheFloat2(uniformName, x, y)) {\n if (!this.engine.setUInt2(this._uniforms[uniformName], x, y)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets an unsigned int3 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First unsigned int in uint3.\n * @param y Second unsigned int in uint3.\n * @param z Third unsigned int in uint3.\n */\n setUInt3(uniformName, x, y, z) {\n if (this._cacheFloat3(uniformName, x, y, z)) {\n if (!this.engine.setUInt3(this._uniforms[uniformName], x, y, z)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets an unsigned int4 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First unsigned int in uint4.\n * @param y Second unsigned int in uint4.\n * @param z Third unsigned int in uint4.\n * @param w Fourth unsigned int in uint4.\n */\n setUInt4(uniformName, x, y, z, w) {\n if (this._cacheFloat4(uniformName, x, y, z, w)) {\n if (!this.engine.setUInt4(this._uniforms[uniformName], x, y, z, w)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets an unsigned int array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setUIntArray(uniformName, array) {\n this._valueCache[uniformName] = null;\n this.engine.setUIntArray(this._uniforms[uniformName], array);\n }\n /**\n * Sets an unsigned int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setUIntArray2(uniformName, array) {\n this._valueCache[uniformName] = null;\n this.engine.setUIntArray2(this._uniforms[uniformName], array);\n }\n /**\n * Sets an unsigned int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setUIntArray3(uniformName, array) {\n this._valueCache[uniformName] = null;\n this.engine.setUIntArray3(this._uniforms[uniformName], array);\n }\n /**\n * Sets an unsigned int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setUIntArray4(uniformName, array) {\n this._valueCache[uniformName] = null;\n this.engine.setUIntArray4(this._uniforms[uniformName], array);\n }\n /**\n * Sets an array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setArray(uniformName, array) {\n this._valueCache[uniformName] = null;\n this.engine.setArray(this._uniforms[uniformName], array);\n }\n /**\n * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setArray2(uniformName, array) {\n this._valueCache[uniformName] = null;\n this.engine.setArray2(this._uniforms[uniformName], array);\n }\n /**\n * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setArray3(uniformName, array) {\n this._valueCache[uniformName] = null;\n this.engine.setArray3(this._uniforms[uniformName], array);\n }\n /**\n * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setArray4(uniformName, array) {\n this._valueCache[uniformName] = null;\n this.engine.setArray4(this._uniforms[uniformName], array);\n }\n /**\n * Sets matrices on a uniform variable.\n * @param uniformName Name of the variable.\n * @param matrices matrices to be set.\n */\n setMatrices(uniformName, matrices) {\n if (!matrices) {\n return;\n }\n this._valueCache[uniformName] = null;\n this.engine.setMatrices(this._uniforms[uniformName], matrices);\n }\n /**\n * Sets matrix on a uniform variable.\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n */\n setMatrix(uniformName, matrix) {\n if (this._cacheMatrix(uniformName, matrix)) {\n if (!this.engine.setMatrices(this._uniforms[uniformName], matrix.toArray())) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a 3x3 matrix on a uniform variable. (Specified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n */\n setMatrix3x3(uniformName, matrix) {\n this._valueCache[uniformName] = null;\n this.engine.setMatrix3x3(this._uniforms[uniformName], matrix);\n }\n /**\n * Sets a 2x2 matrix on a uniform variable. (Specified as [1,2,3,4] will result in [1,2][3,4] matrix)\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n */\n setMatrix2x2(uniformName, matrix) {\n this._valueCache[uniformName] = null;\n this.engine.setMatrix2x2(this._uniforms[uniformName], matrix);\n }\n /**\n * Sets a float on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value value to be set.\n * @returns this effect.\n */\n setFloat(uniformName, value) {\n const cache = this._valueCache[uniformName];\n if (cache !== undefined && cache === value) {\n return;\n }\n if (this.engine.setFloat(this._uniforms[uniformName], value)) {\n this._valueCache[uniformName] = value;\n }\n }\n /**\n * Sets a Vector2 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector2 vector2 to be set.\n */\n setVector2(uniformName, vector2) {\n if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {\n if (!this.engine.setFloat2(this._uniforms[uniformName], vector2.x, vector2.y)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a float2 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float2.\n * @param y Second float in float2.\n */\n setFloat2(uniformName, x, y) {\n if (this._cacheFloat2(uniformName, x, y)) {\n if (!this.engine.setFloat2(this._uniforms[uniformName], x, y)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a Vector3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector3 Value to be set.\n */\n setVector3(uniformName, vector3) {\n if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {\n if (!this.engine.setFloat3(this._uniforms[uniformName], vector3.x, vector3.y, vector3.z)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a float3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float3.\n * @param y Second float in float3.\n * @param z Third float in float3.\n */\n setFloat3(uniformName, x, y, z) {\n if (this._cacheFloat3(uniformName, x, y, z)) {\n if (!this.engine.setFloat3(this._uniforms[uniformName], x, y, z)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a Vector4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector4 Value to be set.\n */\n setVector4(uniformName, vector4) {\n if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {\n if (!this.engine.setFloat4(this._uniforms[uniformName], vector4.x, vector4.y, vector4.z, vector4.w)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a Quaternion on a uniform variable.\n * @param uniformName Name of the variable.\n * @param quaternion Value to be set.\n */\n setQuaternion(uniformName, quaternion) {\n if (this._cacheFloat4(uniformName, quaternion.x, quaternion.y, quaternion.z, quaternion.w)) {\n if (!this.engine.setFloat4(this._uniforms[uniformName], quaternion.x, quaternion.y, quaternion.z, quaternion.w)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a float4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float4.\n * @param y Second float in float4.\n * @param z Third float in float4.\n * @param w Fourth float in float4.\n * @returns this effect.\n */\n setFloat4(uniformName, x, y, z, w) {\n if (this._cacheFloat4(uniformName, x, y, z, w)) {\n if (!this.engine.setFloat4(this._uniforms[uniformName], x, y, z, w)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a Color3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param color3 Value to be set.\n */\n setColor3(uniformName, color3) {\n if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {\n if (!this.engine.setFloat3(this._uniforms[uniformName], color3.r, color3.g, color3.b)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a Color4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param color3 Value to be set.\n * @param alpha Alpha value to be set.\n */\n setColor4(uniformName, color3, alpha) {\n if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {\n if (!this.engine.setFloat4(this._uniforms[uniformName], color3.r, color3.g, color3.b, alpha)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a Color4 on a uniform variable\n * @param uniformName defines the name of the variable\n * @param color4 defines the value to be set\n */\n setDirectColor4(uniformName, color4) {\n if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {\n if (!this.engine.setFloat4(this._uniforms[uniformName], color4.r, color4.g, color4.b, color4.a)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n _getVertexShaderCode() {\n return this.vertexShader ? this.engine._getShaderSource(this.vertexShader) : null;\n }\n _getFragmentShaderCode() {\n return this.fragmentShader ? this.engine._getShaderSource(this.fragmentShader) : null;\n }\n}\n//# sourceMappingURL=webGLPipelineContext.js.map","import { ShaderLanguage } from \"../../Materials/shaderLanguage.js\";\n/** @internal */\nexport class WebGLShaderProcessor {\n constructor() {\n this.shaderLanguage = ShaderLanguage.GLSL;\n }\n postProcessor(code, defines, isFragment, processingContext, engine) {\n // Remove extensions\n if (!engine.getCaps().drawBuffersExtension) {\n // even if enclosed in #if/#endif, IE11 does parse the #extension declaration, so we need to remove it altogether\n const regex = /#extension.+GL_EXT_draw_buffers.+(enable|require)/g;\n code = code.replace(regex, \"\");\n }\n return code;\n }\n}\n//# sourceMappingURL=webGLShaderProcessors.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { InternalTexture, InternalTextureSource } from \"../Materials/Textures/internalTexture.js\";\nimport { IsDocumentAvailable, IsWindowObjectExist } from \"../Misc/domManagement.js\";\nimport { EngineStore } from \"./engineStore.js\";\nimport { _WarnImport } from \"../Misc/devTools.js\";\nimport { ThinEngine } from \"./thinEngine.js\";\n\nimport { PerformanceMonitor } from \"../Misc/performanceMonitor.js\";\nimport { PerfCounter } from \"../Misc/perfCounter.js\";\nimport { WebGLDataBuffer } from \"../Meshes/WebGL/webGLDataBuffer.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { WebGLHardwareTexture } from \"./WebGL/webGLHardwareTexture.js\";\nimport \"./Extensions/engine.alpha.js\";\nimport \"./Extensions/engine.readTexture.js\";\nimport \"./Extensions/engine.dynamicBuffer.js\";\n/**\n * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio\n */\nexport class Engine extends ThinEngine {\n /**\n * Returns the current npm package of the sdk\n */\n // Not mixed with Version for tooling purpose.\n static get NpmPackage() {\n return ThinEngine.NpmPackage;\n }\n /**\n * Returns the current version of the framework\n */\n static get Version() {\n return ThinEngine.Version;\n }\n /** Gets the list of created engines */\n static get Instances() {\n return EngineStore.Instances;\n }\n /**\n * Gets the latest created engine\n */\n static get LastCreatedEngine() {\n return EngineStore.LastCreatedEngine;\n }\n /**\n * Gets the latest created scene\n */\n static get LastCreatedScene() {\n return EngineStore.LastCreatedScene;\n }\n /** @internal */\n /**\n * Engine abstraction for loading and creating an image bitmap from a given source string.\n * @param imageSource source to load the image from.\n * @param options An object that sets options for the image's extraction.\n * @returns ImageBitmap.\n */\n _createImageBitmapFromSource(imageSource, options) {\n const promise = new Promise((resolve, reject) => {\n const image = new Image();\n image.onload = () => {\n image.decode().then(() => {\n this.createImageBitmap(image, options).then((imageBitmap) => {\n resolve(imageBitmap);\n });\n });\n };\n image.onerror = () => {\n reject(`Error loading image ${image.src}`);\n };\n image.src = imageSource;\n });\n return promise;\n }\n /**\n * Engine abstraction for createImageBitmap\n * @param image source for image\n * @param options An object that sets options for the image's extraction.\n * @returns ImageBitmap\n */\n createImageBitmap(image, options) {\n return createImageBitmap(image, options);\n }\n /**\n * Resize an image and returns the image data as an uint8array\n * @param image image to resize\n * @param bufferWidth destination buffer width\n * @param bufferHeight destination buffer height\n * @returns an uint8array containing RGBA values of bufferWidth * bufferHeight size\n */\n resizeImageBitmap(image, bufferWidth, bufferHeight) {\n const canvas = this.createCanvas(bufferWidth, bufferHeight);\n const context = canvas.getContext(\"2d\");\n if (!context) {\n throw new Error(\"Unable to get 2d context for resizeImageBitmap\");\n }\n context.drawImage(image, 0, 0);\n // Create VertexData from map data\n // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949\n const buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;\n return buffer;\n }\n /**\n * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation\n * @param flag defines which part of the materials must be marked as dirty\n * @param predicate defines a predicate used to filter which materials should be affected\n */\n static MarkAllMaterialsAsDirty(flag, predicate) {\n for (let engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {\n const engine = Engine.Instances[engineIndex];\n for (let sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {\n engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);\n }\n }\n }\n /**\n * Method called to create the default loading screen.\n * This can be overridden in your own app.\n * @param canvas The rendering canvas element\n * @returns The loading screen\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n static DefaultLoadingScreenFactory(canvas) {\n throw _WarnImport(\"LoadingScreen\");\n }\n get _supportsHardwareTextureRescaling() {\n return !!Engine._RescalePostProcessFactory;\n }\n /**\n * Gets the performance monitor attached to this engine\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#engineinstrumentation\n */\n get performanceMonitor() {\n return this._performanceMonitor;\n }\n /**\n * (WebGPU only) True (default) to be in compatibility mode, meaning rendering all existing scenes without artifacts (same rendering than WebGL).\n * Setting the property to false will improve performances but may not work in some scenes if some precautions are not taken.\n * See https://doc.babylonjs.com/setup/support/webGPU/webGPUOptimization/webGPUNonCompatibilityMode for more details\n */\n get compatibilityMode() {\n return this._compatibilityMode;\n }\n set compatibilityMode(mode) {\n // not supported in WebGL\n this._compatibilityMode = true;\n }\n // Events\n /**\n * Gets the HTML element used to attach event listeners\n * @returns a HTML element\n */\n getInputElement() {\n return this._renderingCanvas;\n }\n /**\n * Creates a new engine\n * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which already used the WebGL context\n * @param antialias defines enable antialiasing (default: false)\n * @param options defines further options to be sent to the getContext() function\n * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)\n */\n constructor(canvasOrContext, antialias, options, adaptToDeviceRatio = false) {\n super(canvasOrContext, antialias, options, adaptToDeviceRatio);\n // Members\n /**\n * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest\n **/\n this.enableOfflineSupport = false;\n /**\n * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (js will always consider the database is up to date)\n **/\n this.disableManifestCheck = false;\n /**\n * Gets or sets a boolean to enable/disable the context menu (right-click) from appearing on the main canvas\n */\n this.disableContextMenu = true;\n /**\n * Gets the list of created scenes\n */\n this.scenes = new Array();\n /** @internal */\n this._virtualScenes = new Array();\n /**\n * Event raised when a new scene is created\n */\n this.onNewSceneAddedObservable = new Observable();\n /**\n * Gets the list of created postprocesses\n */\n this.postProcesses = new Array();\n /**\n * Gets a boolean indicating if the pointer is currently locked\n */\n this.isPointerLock = false;\n // Observables\n /**\n * Observable event triggered each time the rendering canvas is resized\n */\n this.onResizeObservable = new Observable();\n /**\n * Observable event triggered each time the canvas loses focus\n */\n this.onCanvasBlurObservable = new Observable();\n /**\n * Observable event triggered each time the canvas gains focus\n */\n this.onCanvasFocusObservable = new Observable();\n /**\n * Observable event triggered each time the canvas receives pointerout event\n */\n this.onCanvasPointerOutObservable = new Observable();\n /**\n * Observable raised when the engine begins a new frame\n */\n this.onBeginFrameObservable = new Observable();\n /**\n * If set, will be used to request the next animation frame for the render loop\n */\n this.customAnimationFrameRequester = null;\n /**\n * Observable raised when the engine ends the current frame\n */\n this.onEndFrameObservable = new Observable();\n /**\n * Observable raised when the engine is about to compile a shader\n */\n this.onBeforeShaderCompilationObservable = new Observable();\n /**\n * Observable raised when the engine has just compiled a shader\n */\n this.onAfterShaderCompilationObservable = new Observable();\n // Deterministic lockstepMaxSteps\n this._deterministicLockstep = false;\n this._lockstepMaxSteps = 4;\n this._timeStep = 1 / 60;\n // FPS\n this._fps = 60;\n this._deltaTime = 0;\n /** @internal */\n this._drawCalls = new PerfCounter();\n /** Gets or sets the tab index to set to the rendering canvas. 1 is the minimum value to set to be able to capture keyboard events */\n this.canvasTabIndex = 1;\n /**\n * Turn this value on if you want to pause FPS computation when in background\n */\n this.disablePerformanceMonitorInBackground = false;\n this._performanceMonitor = new PerformanceMonitor();\n this._compatibilityMode = true;\n /**\n * Gets or sets the current render pass id\n */\n this.currentRenderPassId = 0;\n this._renderPassNames = [\"main\"];\n Engine.Instances.push(this);\n if (!canvasOrContext) {\n return;\n }\n this._features.supportRenderPasses = true;\n options = this._creationOptions;\n if (canvasOrContext.getContext) {\n const canvas = canvasOrContext;\n this._sharedInit(canvas);\n this._connectVREvents();\n }\n // Load WebVR Devices\n this._prepareVRComponent();\n if (options.autoEnableWebVR) {\n this.initWebVR();\n }\n }\n _initGLContext() {\n super._initGLContext();\n this._rescalePostProcess = null;\n }\n /**\n * Shared initialization across engines types.\n * @param canvas The canvas associated with this instance of the engine.\n */\n _sharedInit(canvas) {\n super._sharedInit(canvas);\n this._onCanvasFocus = () => {\n this.onCanvasFocusObservable.notifyObservers(this);\n };\n this._onCanvasBlur = () => {\n this.onCanvasBlurObservable.notifyObservers(this);\n };\n this._onCanvasContextMenu = (evt) => {\n if (this.disableContextMenu) {\n evt.preventDefault();\n }\n };\n canvas.addEventListener(\"focus\", this._onCanvasFocus);\n canvas.addEventListener(\"blur\", this._onCanvasBlur);\n canvas.addEventListener(\"contextmenu\", this._onCanvasContextMenu);\n this._onBlur = () => {\n if (this.disablePerformanceMonitorInBackground) {\n this._performanceMonitor.disable();\n }\n this._windowIsBackground = true;\n };\n this._onFocus = () => {\n if (this.disablePerformanceMonitorInBackground) {\n this._performanceMonitor.enable();\n }\n this._windowIsBackground = false;\n };\n this._onCanvasPointerOut = (ev) => {\n // Check that the element at the point of the pointer out isn't the canvas and if it isn't, notify observers\n // Note: This is a workaround for a bug with Safari\n if (document.elementFromPoint(ev.clientX, ev.clientY) !== canvas) {\n this.onCanvasPointerOutObservable.notifyObservers(ev);\n }\n };\n const hostWindow = this.getHostWindow(); // it calls IsWindowObjectExist()\n if (hostWindow && typeof hostWindow.addEventListener === \"function\") {\n hostWindow.addEventListener(\"blur\", this._onBlur);\n hostWindow.addEventListener(\"focus\", this._onFocus);\n }\n canvas.addEventListener(\"pointerout\", this._onCanvasPointerOut);\n if (!this._creationOptions.doNotHandleTouchAction) {\n this._disableTouchAction();\n }\n // Create Audio Engine if needed.\n if (!Engine.audioEngine && this._creationOptions.audioEngine && Engine.AudioEngineFactory) {\n Engine.audioEngine = Engine.AudioEngineFactory(this.getRenderingCanvas(), this.getAudioContext(), this.getAudioDestination());\n }\n if (IsDocumentAvailable()) {\n // Fullscreen\n this._onFullscreenChange = () => {\n this.isFullscreen = !!document.fullscreenElement;\n // Pointer lock\n if (this.isFullscreen && this._pointerLockRequested && canvas) {\n Engine._RequestPointerlock(canvas);\n }\n };\n document.addEventListener(\"fullscreenchange\", this._onFullscreenChange, false);\n document.addEventListener(\"webkitfullscreenchange\", this._onFullscreenChange, false);\n // Pointer lock\n this._onPointerLockChange = () => {\n this.isPointerLock = document.pointerLockElement === canvas;\n };\n document.addEventListener(\"pointerlockchange\", this._onPointerLockChange, false);\n document.addEventListener(\"webkitpointerlockchange\", this._onPointerLockChange, false);\n }\n this.enableOfflineSupport = Engine.OfflineProviderFactory !== undefined;\n this._deterministicLockstep = !!this._creationOptions.deterministicLockstep;\n this._lockstepMaxSteps = this._creationOptions.lockstepMaxSteps || 0;\n this._timeStep = this._creationOptions.timeStep || 1 / 60;\n }\n /** @internal */\n _verifyPointerLock() {\n var _a;\n (_a = this._onPointerLockChange) === null || _a === void 0 ? void 0 : _a.call(this);\n }\n /**\n * Gets current aspect ratio\n * @param viewportOwner defines the camera to use to get the aspect ratio\n * @param useScreen defines if screen size must be used (or the current render target if any)\n * @returns a number defining the aspect ratio\n */\n getAspectRatio(viewportOwner, useScreen = false) {\n const viewport = viewportOwner.viewport;\n return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);\n }\n /**\n * Gets current screen aspect ratio\n * @returns a number defining the aspect ratio\n */\n getScreenAspectRatio() {\n return this.getRenderWidth(true) / this.getRenderHeight(true);\n }\n /**\n * Gets the client rect of the HTML canvas attached with the current webGL context\n * @returns a client rectangle\n */\n getRenderingCanvasClientRect() {\n if (!this._renderingCanvas) {\n return null;\n }\n return this._renderingCanvas.getBoundingClientRect();\n }\n /**\n * Gets the client rect of the HTML element used for events\n * @returns a client rectangle\n */\n getInputElementClientRect() {\n if (!this._renderingCanvas) {\n return null;\n }\n return this.getInputElement().getBoundingClientRect();\n }\n /**\n * Gets a boolean indicating that the engine is running in deterministic lock step mode\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep\n * @returns true if engine is in deterministic lock step mode\n */\n isDeterministicLockStep() {\n return this._deterministicLockstep;\n }\n /**\n * Gets the max steps when engine is running in deterministic lock step\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep\n * @returns the max steps\n */\n getLockstepMaxSteps() {\n return this._lockstepMaxSteps;\n }\n /**\n * Returns the time in ms between steps when using deterministic lock step.\n * @returns time step in (ms)\n */\n getTimeStep() {\n return this._timeStep * 1000;\n }\n /**\n * Force the mipmap generation for the given render target texture\n * @param texture defines the render target texture to use\n * @param unbind defines whether or not to unbind the texture after generation. Defaults to true.\n */\n generateMipMapsForCubemap(texture, unbind = true) {\n if (texture.generateMipMaps) {\n const gl = this._gl;\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);\n gl.generateMipmap(gl.TEXTURE_CUBE_MAP);\n if (unbind) {\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n }\n }\n }\n /** States */\n /**\n * Gets a boolean indicating if depth writing is enabled\n * @returns the current depth writing state\n */\n getDepthWrite() {\n return this._depthCullingState.depthMask;\n }\n /**\n * Enable or disable depth writing\n * @param enable defines the state to set\n */\n setDepthWrite(enable) {\n this._depthCullingState.depthMask = enable;\n }\n /**\n * Gets a boolean indicating if stencil buffer is enabled\n * @returns the current stencil buffer state\n */\n getStencilBuffer() {\n return this._stencilState.stencilTest;\n }\n /**\n * Enable or disable the stencil buffer\n * @param enable defines if the stencil buffer must be enabled or disabled\n */\n setStencilBuffer(enable) {\n this._stencilState.stencilTest = enable;\n }\n /**\n * Gets the current stencil mask\n * @returns a number defining the new stencil mask to use\n */\n getStencilMask() {\n return this._stencilState.stencilMask;\n }\n /**\n * Sets the current stencil mask\n * @param mask defines the new stencil mask to use\n */\n setStencilMask(mask) {\n this._stencilState.stencilMask = mask;\n }\n /**\n * Gets the current stencil function\n * @returns a number defining the stencil function to use\n */\n getStencilFunction() {\n return this._stencilState.stencilFunc;\n }\n /**\n * Gets the current stencil reference value\n * @returns a number defining the stencil reference value to use\n */\n getStencilFunctionReference() {\n return this._stencilState.stencilFuncRef;\n }\n /**\n * Gets the current stencil mask\n * @returns a number defining the stencil mask to use\n */\n getStencilFunctionMask() {\n return this._stencilState.stencilFuncMask;\n }\n /**\n * Sets the current stencil function\n * @param stencilFunc defines the new stencil function to use\n */\n setStencilFunction(stencilFunc) {\n this._stencilState.stencilFunc = stencilFunc;\n }\n /**\n * Sets the current stencil reference\n * @param reference defines the new stencil reference to use\n */\n setStencilFunctionReference(reference) {\n this._stencilState.stencilFuncRef = reference;\n }\n /**\n * Sets the current stencil mask\n * @param mask defines the new stencil mask to use\n */\n setStencilFunctionMask(mask) {\n this._stencilState.stencilFuncMask = mask;\n }\n /**\n * Gets the current stencil operation when stencil fails\n * @returns a number defining stencil operation to use when stencil fails\n */\n getStencilOperationFail() {\n return this._stencilState.stencilOpStencilFail;\n }\n /**\n * Gets the current stencil operation when depth fails\n * @returns a number defining stencil operation to use when depth fails\n */\n getStencilOperationDepthFail() {\n return this._stencilState.stencilOpDepthFail;\n }\n /**\n * Gets the current stencil operation when stencil passes\n * @returns a number defining stencil operation to use when stencil passes\n */\n getStencilOperationPass() {\n return this._stencilState.stencilOpStencilDepthPass;\n }\n /**\n * Sets the stencil operation to use when stencil fails\n * @param operation defines the stencil operation to use when stencil fails\n */\n setStencilOperationFail(operation) {\n this._stencilState.stencilOpStencilFail = operation;\n }\n /**\n * Sets the stencil operation to use when depth fails\n * @param operation defines the stencil operation to use when depth fails\n */\n setStencilOperationDepthFail(operation) {\n this._stencilState.stencilOpDepthFail = operation;\n }\n /**\n * Sets the stencil operation to use when stencil passes\n * @param operation defines the stencil operation to use when stencil passes\n */\n setStencilOperationPass(operation) {\n this._stencilState.stencilOpStencilDepthPass = operation;\n }\n /**\n * Sets a boolean indicating if the dithering state is enabled or disabled\n * @param value defines the dithering state\n */\n setDitheringState(value) {\n if (value) {\n this._gl.enable(this._gl.DITHER);\n }\n else {\n this._gl.disable(this._gl.DITHER);\n }\n }\n /**\n * Sets a boolean indicating if the rasterizer state is enabled or disabled\n * @param value defines the rasterizer state\n */\n setRasterizerState(value) {\n if (value) {\n this._gl.disable(this._gl.RASTERIZER_DISCARD);\n }\n else {\n this._gl.enable(this._gl.RASTERIZER_DISCARD);\n }\n }\n /**\n * Gets the current depth function\n * @returns a number defining the depth function\n */\n getDepthFunction() {\n return this._depthCullingState.depthFunc;\n }\n /**\n * Sets the current depth function\n * @param depthFunc defines the function to use\n */\n setDepthFunction(depthFunc) {\n this._depthCullingState.depthFunc = depthFunc;\n }\n /**\n * Sets the current depth function to GREATER\n */\n setDepthFunctionToGreater() {\n this.setDepthFunction(516);\n }\n /**\n * Sets the current depth function to GEQUAL\n */\n setDepthFunctionToGreaterOrEqual() {\n this.setDepthFunction(518);\n }\n /**\n * Sets the current depth function to LESS\n */\n setDepthFunctionToLess() {\n this.setDepthFunction(513);\n }\n /**\n * Sets the current depth function to LEQUAL\n */\n setDepthFunctionToLessOrEqual() {\n this.setDepthFunction(515);\n }\n /**\n * Caches the the state of the stencil buffer\n */\n cacheStencilState() {\n this._cachedStencilBuffer = this.getStencilBuffer();\n this._cachedStencilFunction = this.getStencilFunction();\n this._cachedStencilMask = this.getStencilMask();\n this._cachedStencilOperationPass = this.getStencilOperationPass();\n this._cachedStencilOperationFail = this.getStencilOperationFail();\n this._cachedStencilOperationDepthFail = this.getStencilOperationDepthFail();\n this._cachedStencilReference = this.getStencilFunctionReference();\n }\n /**\n * Restores the state of the stencil buffer\n */\n restoreStencilState() {\n this.setStencilFunction(this._cachedStencilFunction);\n this.setStencilMask(this._cachedStencilMask);\n this.setStencilBuffer(this._cachedStencilBuffer);\n this.setStencilOperationPass(this._cachedStencilOperationPass);\n this.setStencilOperationFail(this._cachedStencilOperationFail);\n this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail);\n this.setStencilFunctionReference(this._cachedStencilReference);\n }\n /**\n * Directly set the WebGL Viewport\n * @param x defines the x coordinate of the viewport (in screen space)\n * @param y defines the y coordinate of the viewport (in screen space)\n * @param width defines the width of the viewport (in screen space)\n * @param height defines the height of the viewport (in screen space)\n * @returns the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state\n */\n setDirectViewport(x, y, width, height) {\n const currentViewport = this._cachedViewport;\n this._cachedViewport = null;\n this._viewport(x, y, width, height);\n return currentViewport;\n }\n /**\n * Executes a scissor clear (ie. a clear on a specific portion of the screen)\n * @param x defines the x-coordinate of the bottom left corner of the clear rectangle\n * @param y defines the y-coordinate of the corner of the clear rectangle\n * @param width defines the width of the clear rectangle\n * @param height defines the height of the clear rectangle\n * @param clearColor defines the clear color\n */\n scissorClear(x, y, width, height, clearColor) {\n this.enableScissor(x, y, width, height);\n this.clear(clearColor, true, true, true);\n this.disableScissor();\n }\n /**\n * Enable scissor test on a specific rectangle (ie. render will only be executed on a specific portion of the screen)\n * @param x defines the x-coordinate of the bottom left corner of the clear rectangle\n * @param y defines the y-coordinate of the corner of the clear rectangle\n * @param width defines the width of the clear rectangle\n * @param height defines the height of the clear rectangle\n */\n enableScissor(x, y, width, height) {\n const gl = this._gl;\n // Change state\n gl.enable(gl.SCISSOR_TEST);\n gl.scissor(x, y, width, height);\n }\n /**\n * Disable previously set scissor test rectangle\n */\n disableScissor() {\n const gl = this._gl;\n gl.disable(gl.SCISSOR_TEST);\n }\n /**\n * @internal\n */\n _reportDrawCall(numDrawCalls = 1) {\n this._drawCalls.addCount(numDrawCalls, false);\n }\n /**\n * Initializes a webVR display and starts listening to display change events\n * The onVRDisplayChangedObservable will be notified upon these changes\n * @returns The onVRDisplayChangedObservable\n */\n initWebVR() {\n throw _WarnImport(\"WebVRCamera\");\n }\n /** @internal */\n _prepareVRComponent() {\n // Do nothing as the engine side effect will overload it\n }\n /**\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _connectVREvents(canvas, document) {\n // Do nothing as the engine side effect will overload it\n }\n /** @internal */\n _submitVRFrame() {\n // Do nothing as the engine side effect will overload it\n }\n /**\n * Call this function to leave webVR mode\n * Will do nothing if webVR is not supported or if there is no webVR device\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/webVRCamera\n */\n disableVR() {\n // Do nothing as the engine side effect will overload it\n }\n /**\n * Gets a boolean indicating that the system is in VR mode and is presenting\n * @returns true if VR mode is engaged\n */\n isVRPresenting() {\n return false;\n }\n /** @internal */\n _requestVRFrame() {\n // Do nothing as the engine side effect will overload it\n }\n /**\n * @internal\n */\n _loadFileAsync(url, offlineProvider, useArrayBuffer) {\n return new Promise((resolve, reject) => {\n this._loadFile(url, (data) => {\n resolve(data);\n }, undefined, offlineProvider, useArrayBuffer, (request, exception) => {\n reject(exception);\n });\n });\n }\n /**\n * Gets the source code of the vertex shader associated with a specific webGL program\n * @param program defines the program to use\n * @returns a string containing the source code of the vertex shader associated with the program\n */\n getVertexShaderSource(program) {\n const shaders = this._gl.getAttachedShaders(program);\n if (!shaders) {\n return null;\n }\n return this._gl.getShaderSource(shaders[0]);\n }\n /**\n * Gets the source code of the fragment shader associated with a specific webGL program\n * @param program defines the program to use\n * @returns a string containing the source code of the fragment shader associated with the program\n */\n getFragmentShaderSource(program) {\n const shaders = this._gl.getAttachedShaders(program);\n if (!shaders) {\n return null;\n }\n return this._gl.getShaderSource(shaders[1]);\n }\n /**\n * Sets a depth stencil texture from a render target to the according uniform.\n * @param channel The texture channel\n * @param uniform The uniform to set\n * @param texture The render target texture containing the depth stencil texture to apply\n * @param name The texture name\n */\n setDepthStencilTexture(channel, uniform, texture, name) {\n if (channel === undefined) {\n return;\n }\n if (uniform) {\n this._boundUniforms[channel] = uniform;\n }\n if (!texture || !texture.depthStencilTexture) {\n this._setTexture(channel, null, undefined, undefined, name);\n }\n else {\n this._setTexture(channel, texture, false, true, name);\n }\n }\n /**\n * Sets a texture to the webGL context from a postprocess\n * @param channel defines the channel to use\n * @param postProcess defines the source postprocess\n * @param name name of the channel\n */\n setTextureFromPostProcess(channel, postProcess, name) {\n var _a;\n let postProcessInput = null;\n if (postProcess) {\n if (postProcess._forcedOutputTexture) {\n postProcessInput = postProcess._forcedOutputTexture;\n }\n else if (postProcess._textures.data[postProcess._currentRenderTextureInd]) {\n postProcessInput = postProcess._textures.data[postProcess._currentRenderTextureInd];\n }\n }\n this._bindTexture(channel, (_a = postProcessInput === null || postProcessInput === void 0 ? void 0 : postProcessInput.texture) !== null && _a !== void 0 ? _a : null, name);\n }\n /**\n * Binds the output of the passed in post process to the texture channel specified\n * @param channel The channel the texture should be bound to\n * @param postProcess The post process which's output should be bound\n * @param name name of the channel\n */\n setTextureFromPostProcessOutput(channel, postProcess, name) {\n var _a, _b;\n this._bindTexture(channel, (_b = (_a = postProcess === null || postProcess === void 0 ? void 0 : postProcess._outputTexture) === null || _a === void 0 ? void 0 : _a.texture) !== null && _b !== void 0 ? _b : null, name);\n }\n _rebuildBuffers() {\n // Index / Vertex\n for (const scene of this.scenes) {\n scene.resetCachedMaterial();\n scene._rebuildGeometries();\n scene._rebuildTextures();\n }\n for (const scene of this._virtualScenes) {\n scene.resetCachedMaterial();\n scene._rebuildGeometries();\n scene._rebuildTextures();\n }\n super._rebuildBuffers();\n }\n /** @internal */\n _renderFrame() {\n for (let index = 0; index < this._activeRenderLoops.length; index++) {\n const renderFunction = this._activeRenderLoops[index];\n renderFunction();\n }\n }\n _renderLoop() {\n if (!this._contextWasLost) {\n let shouldRender = true;\n if (this.isDisposed || (!this.renderEvenInBackground && this._windowIsBackground)) {\n shouldRender = false;\n }\n if (shouldRender) {\n // Start new frame\n this.beginFrame();\n // Child canvases\n if (!this._renderViews()) {\n // Main frame\n this._renderFrame();\n }\n // Present\n this.endFrame();\n }\n }\n if (this._activeRenderLoops.length > 0) {\n // Register new frame\n if (this.customAnimationFrameRequester) {\n this.customAnimationFrameRequester.requestID = this._queueNewFrame(this.customAnimationFrameRequester.renderFunction || this._boundRenderFunction, this.customAnimationFrameRequester);\n this._frameHandler = this.customAnimationFrameRequester.requestID;\n }\n else if (this.isVRPresenting()) {\n this._requestVRFrame();\n }\n else {\n this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow());\n }\n }\n else {\n this._renderingQueueLaunched = false;\n }\n }\n /** @internal */\n _renderViews() {\n return false;\n }\n /**\n * Toggle full screen mode\n * @param requestPointerLock defines if a pointer lock should be requested from the user\n */\n switchFullscreen(requestPointerLock) {\n if (this.isFullscreen) {\n this.exitFullscreen();\n }\n else {\n this.enterFullscreen(requestPointerLock);\n }\n }\n /**\n * Enters full screen mode\n * @param requestPointerLock defines if a pointer lock should be requested from the user\n */\n enterFullscreen(requestPointerLock) {\n if (!this.isFullscreen) {\n this._pointerLockRequested = requestPointerLock;\n if (this._renderingCanvas) {\n Engine._RequestFullscreen(this._renderingCanvas);\n }\n }\n }\n /**\n * Exits full screen mode\n */\n exitFullscreen() {\n if (this.isFullscreen) {\n Engine._ExitFullscreen();\n }\n }\n /**\n * Enters Pointerlock mode\n */\n enterPointerlock() {\n if (this._renderingCanvas) {\n Engine._RequestPointerlock(this._renderingCanvas);\n }\n }\n /**\n * Exits Pointerlock mode\n */\n exitPointerlock() {\n Engine._ExitPointerlock();\n }\n /**\n * Begin a new frame\n */\n beginFrame() {\n this._measureFps();\n this.onBeginFrameObservable.notifyObservers(this);\n super.beginFrame();\n }\n /**\n * End the current frame\n */\n endFrame() {\n super.endFrame();\n this._submitVRFrame();\n this.onEndFrameObservable.notifyObservers(this);\n }\n /**\n * Resize the view according to the canvas' size\n * @param forceSetSize true to force setting the sizes of the underlying canvas\n */\n resize(forceSetSize = false) {\n // We're not resizing the size of the canvas while in VR mode & presenting\n if (this.isVRPresenting()) {\n return;\n }\n super.resize(forceSetSize);\n }\n /**\n * Force a specific size of the canvas\n * @param width defines the new canvas' width\n * @param height defines the new canvas' height\n * @param forceSetSize true to force setting the sizes of the underlying canvas\n * @returns true if the size was changed\n */\n setSize(width, height, forceSetSize = false) {\n if (!this._renderingCanvas) {\n return false;\n }\n if (!super.setSize(width, height, forceSetSize)) {\n return false;\n }\n if (this.scenes) {\n for (let index = 0; index < this.scenes.length; index++) {\n const scene = this.scenes[index];\n for (let camIndex = 0; camIndex < scene.cameras.length; camIndex++) {\n const cam = scene.cameras[camIndex];\n cam._currentRenderId = 0;\n }\n }\n if (this.onResizeObservable.hasObservers()) {\n this.onResizeObservable.notifyObservers(this);\n }\n }\n return true;\n }\n _deletePipelineContext(pipelineContext) {\n const webGLPipelineContext = pipelineContext;\n if (webGLPipelineContext && webGLPipelineContext.program) {\n if (webGLPipelineContext.transformFeedback) {\n this.deleteTransformFeedback(webGLPipelineContext.transformFeedback);\n webGLPipelineContext.transformFeedback = null;\n }\n }\n super._deletePipelineContext(pipelineContext);\n }\n createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context, transformFeedbackVaryings = null) {\n context = context || this._gl;\n this.onBeforeShaderCompilationObservable.notifyObservers(this);\n const program = super.createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context, transformFeedbackVaryings);\n this.onAfterShaderCompilationObservable.notifyObservers(this);\n return program;\n }\n _createShaderProgram(pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings = null) {\n const shaderProgram = context.createProgram();\n pipelineContext.program = shaderProgram;\n if (!shaderProgram) {\n throw new Error(\"Unable to create program\");\n }\n context.attachShader(shaderProgram, vertexShader);\n context.attachShader(shaderProgram, fragmentShader);\n if (this.webGLVersion > 1 && transformFeedbackVaryings) {\n const transformFeedback = this.createTransformFeedback();\n this.bindTransformFeedback(transformFeedback);\n this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);\n pipelineContext.transformFeedback = transformFeedback;\n }\n context.linkProgram(shaderProgram);\n if (this.webGLVersion > 1 && transformFeedbackVaryings) {\n this.bindTransformFeedback(null);\n }\n pipelineContext.context = context;\n pipelineContext.vertexShader = vertexShader;\n pipelineContext.fragmentShader = fragmentShader;\n if (!pipelineContext.isParallelCompiled) {\n this._finalizePipelineContext(pipelineContext);\n }\n return shaderProgram;\n }\n /**\n * @internal\n */\n _releaseTexture(texture) {\n super._releaseTexture(texture);\n }\n /**\n * @internal\n */\n _releaseRenderTargetWrapper(rtWrapper) {\n super._releaseRenderTargetWrapper(rtWrapper);\n // Set output texture of post process to null if the framebuffer has been released/disposed\n this.scenes.forEach((scene) => {\n scene.postProcesses.forEach((postProcess) => {\n if (postProcess._outputTexture === rtWrapper) {\n postProcess._outputTexture = null;\n }\n });\n scene.cameras.forEach((camera) => {\n camera._postProcesses.forEach((postProcess) => {\n if (postProcess) {\n if (postProcess._outputTexture === rtWrapper) {\n postProcess._outputTexture = null;\n }\n }\n });\n });\n });\n }\n /**\n * Gets the names of the render passes that are currently created\n * @returns list of the render pass names\n */\n getRenderPassNames() {\n return this._renderPassNames;\n }\n /**\n * Gets the name of the current render pass\n * @returns name of the current render pass\n */\n getCurrentRenderPassName() {\n return this._renderPassNames[this.currentRenderPassId];\n }\n /**\n * Creates a render pass id\n * @param name Name of the render pass (for debug purpose only)\n * @returns the id of the new render pass\n */\n createRenderPassId(name) {\n // Note: render pass id == 0 is always for the main render pass\n const id = ++Engine._RenderPassIdCounter;\n this._renderPassNames[id] = name !== null && name !== void 0 ? name : \"NONAME\";\n return id;\n }\n /**\n * Releases a render pass id\n * @param id id of the render pass to release\n */\n releaseRenderPassId(id) {\n this._renderPassNames[id] = undefined;\n for (let s = 0; s < this.scenes.length; ++s) {\n const scene = this.scenes[s];\n for (let m = 0; m < scene.meshes.length; ++m) {\n const mesh = scene.meshes[m];\n if (mesh.subMeshes) {\n for (let b = 0; b < mesh.subMeshes.length; ++b) {\n const subMesh = mesh.subMeshes[b];\n subMesh._removeDrawWrapper(id);\n }\n }\n }\n }\n }\n /**\n * @internal\n * Rescales a texture\n * @param source input texture\n * @param destination destination texture\n * @param scene scene to use to render the resize\n * @param internalFormat format to use when resizing\n * @param onComplete callback to be called when resize has completed\n */\n _rescaleTexture(source, destination, scene, internalFormat, onComplete) {\n this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, this._gl.LINEAR);\n this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR);\n this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);\n this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);\n const rtt = this.createRenderTargetTexture({\n width: destination.width,\n height: destination.height,\n }, {\n generateMipMaps: false,\n type: 0,\n samplingMode: 2,\n generateDepthBuffer: false,\n generateStencilBuffer: false,\n });\n if (!this._rescalePostProcess && Engine._RescalePostProcessFactory) {\n this._rescalePostProcess = Engine._RescalePostProcessFactory(this);\n }\n if (this._rescalePostProcess) {\n this._rescalePostProcess.externalTextureSamplerBinding = true;\n this._rescalePostProcess.getEffect().executeWhenCompiled(() => {\n this._rescalePostProcess.onApply = function (effect) {\n effect._bindTexture(\"textureSampler\", source);\n };\n let hostingScene = scene;\n if (!hostingScene) {\n hostingScene = this.scenes[this.scenes.length - 1];\n }\n hostingScene.postProcessManager.directRender([this._rescalePostProcess], rtt, true);\n this._bindTextureDirectly(this._gl.TEXTURE_2D, destination, true);\n this._gl.copyTexImage2D(this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);\n this.unBindFramebuffer(rtt);\n rtt.dispose();\n if (onComplete) {\n onComplete();\n }\n });\n }\n }\n // FPS\n /**\n * Gets the current framerate\n * @returns a number representing the framerate\n */\n getFps() {\n return this._fps;\n }\n /**\n * Gets the time spent between current and previous frame\n * @returns a number representing the delta time in ms\n */\n getDeltaTime() {\n return this._deltaTime;\n }\n _measureFps() {\n this._performanceMonitor.sampleFrame();\n this._fps = this._performanceMonitor.averageFPS;\n this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;\n }\n /**\n * Wraps an external web gl texture in a Babylon texture.\n * @param texture defines the external texture\n * @param hasMipMaps defines whether the external texture has mip maps (default: false)\n * @param samplingMode defines the sampling mode for the external texture (default: 3)\n * @returns the babylon internal texture\n */\n wrapWebGLTexture(texture, hasMipMaps = false, samplingMode = 3) {\n const hardwareTexture = new WebGLHardwareTexture(texture, this._gl);\n const internalTexture = new InternalTexture(this, InternalTextureSource.Unknown, true);\n internalTexture._hardwareTexture = hardwareTexture;\n internalTexture.isReady = true;\n internalTexture.useMipMaps = hasMipMaps;\n this.updateTextureSamplingMode(samplingMode, internalTexture);\n return internalTexture;\n }\n /**\n * @internal\n */\n _uploadImageToTexture(texture, image, faceIndex = 0, lod = 0) {\n const gl = this._gl;\n const textureType = this._getWebGLTextureType(texture.type);\n const format = this._getInternalFormat(texture.format);\n const internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);\n const bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;\n this._bindTextureDirectly(bindTarget, texture, true);\n this._unpackFlipY(texture.invertY);\n let target = gl.TEXTURE_2D;\n if (texture.isCube) {\n target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;\n }\n gl.texImage2D(target, lod, internalFormat, format, textureType, image);\n this._bindTextureDirectly(bindTarget, null, true);\n }\n /**\n * Updates a depth texture Comparison Mode and Function.\n * If the comparison Function is equal to 0, the mode will be set to none.\n * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.\n * @param texture The texture to set the comparison function for\n * @param comparisonFunction The comparison function to set, 0 if no comparison required\n */\n updateTextureComparisonFunction(texture, comparisonFunction) {\n if (this.webGLVersion === 1) {\n Logger.Error(\"WebGL 1 does not support texture comparison.\");\n return;\n }\n const gl = this._gl;\n if (texture.isCube) {\n this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);\n if (comparisonFunction === 0) {\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, 515);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);\n }\n else {\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);\n }\n else {\n this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);\n if (comparisonFunction === 0) {\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, 515);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);\n }\n else {\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_2D, null);\n }\n texture._comparisonFunction = comparisonFunction;\n }\n /**\n * Creates a webGL buffer to use with instantiation\n * @param capacity defines the size of the buffer\n * @returns the webGL buffer\n */\n createInstancesBuffer(capacity) {\n const buffer = this._gl.createBuffer();\n if (!buffer) {\n throw new Error(\"Unable to create instance buffer\");\n }\n const result = new WebGLDataBuffer(buffer);\n result.capacity = capacity;\n this.bindArrayBuffer(result);\n this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);\n result.references = 1;\n return result;\n }\n /**\n * Delete a webGL buffer used with instantiation\n * @param buffer defines the webGL buffer to delete\n */\n deleteInstancesBuffer(buffer) {\n this._gl.deleteBuffer(buffer);\n }\n _clientWaitAsync(sync, flags = 0, intervalms = 10) {\n const gl = this._gl;\n return new Promise((resolve, reject) => {\n const check = () => {\n const res = gl.clientWaitSync(sync, flags, 0);\n if (res == gl.WAIT_FAILED) {\n reject();\n return;\n }\n if (res == gl.TIMEOUT_EXPIRED) {\n setTimeout(check, intervalms);\n return;\n }\n resolve();\n };\n check();\n });\n }\n /**\n * @internal\n */\n _readPixelsAsync(x, y, w, h, format, type, outputBuffer) {\n if (this._webGLVersion < 2) {\n throw new Error(\"_readPixelsAsync only work on WebGL2+\");\n }\n const gl = this._gl;\n const buf = gl.createBuffer();\n gl.bindBuffer(gl.PIXEL_PACK_BUFFER, buf);\n gl.bufferData(gl.PIXEL_PACK_BUFFER, outputBuffer.byteLength, gl.STREAM_READ);\n gl.readPixels(x, y, w, h, format, type, 0);\n gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);\n const sync = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0);\n if (!sync) {\n return null;\n }\n gl.flush();\n return this._clientWaitAsync(sync, 0, 10).then(() => {\n gl.deleteSync(sync);\n gl.bindBuffer(gl.PIXEL_PACK_BUFFER, buf);\n gl.getBufferSubData(gl.PIXEL_PACK_BUFFER, 0, outputBuffer);\n gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);\n gl.deleteBuffer(buf);\n return outputBuffer;\n });\n }\n dispose() {\n this.hideLoadingUI();\n this.onNewSceneAddedObservable.clear();\n // Release postProcesses\n while (this.postProcesses.length) {\n this.postProcesses[0].dispose();\n }\n // Rescale PP\n if (this._rescalePostProcess) {\n this._rescalePostProcess.dispose();\n }\n // Release scenes\n while (this.scenes.length) {\n this.scenes[0].dispose();\n }\n while (this._virtualScenes.length) {\n this._virtualScenes[0].dispose();\n }\n // Release audio engine\n if (EngineStore.Instances.length === 1 && Engine.audioEngine) {\n Engine.audioEngine.dispose();\n Engine.audioEngine = null;\n }\n //WebVR\n this.disableVR();\n // Events\n const hostWindow = this.getHostWindow(); // it calls IsWindowObjectExist()\n if (hostWindow && typeof hostWindow.removeEventListener === \"function\") {\n hostWindow.removeEventListener(\"blur\", this._onBlur);\n hostWindow.removeEventListener(\"focus\", this._onFocus);\n }\n if (this._renderingCanvas) {\n this._renderingCanvas.removeEventListener(\"focus\", this._onCanvasFocus);\n this._renderingCanvas.removeEventListener(\"blur\", this._onCanvasBlur);\n this._renderingCanvas.removeEventListener(\"pointerout\", this._onCanvasPointerOut);\n this._renderingCanvas.removeEventListener(\"contextmenu\", this._onCanvasContextMenu);\n }\n if (IsDocumentAvailable()) {\n document.removeEventListener(\"fullscreenchange\", this._onFullscreenChange);\n document.removeEventListener(\"mozfullscreenchange\", this._onFullscreenChange);\n document.removeEventListener(\"webkitfullscreenchange\", this._onFullscreenChange);\n document.removeEventListener(\"msfullscreenchange\", this._onFullscreenChange);\n document.removeEventListener(\"pointerlockchange\", this._onPointerLockChange);\n document.removeEventListener(\"mspointerlockchange\", this._onPointerLockChange);\n document.removeEventListener(\"mozpointerlockchange\", this._onPointerLockChange);\n document.removeEventListener(\"webkitpointerlockchange\", this._onPointerLockChange);\n }\n super.dispose();\n // Remove from Instances\n const index = EngineStore.Instances.indexOf(this);\n if (index >= 0) {\n EngineStore.Instances.splice(index, 1);\n }\n // no more engines left in the engine store? Notify!\n if (!Engine.Instances.length) {\n EngineStore.OnEnginesDisposedObservable.notifyObservers(this);\n }\n // Observables\n this.onResizeObservable.clear();\n this.onCanvasBlurObservable.clear();\n this.onCanvasFocusObservable.clear();\n this.onCanvasPointerOutObservable.clear();\n this.onBeginFrameObservable.clear();\n this.onEndFrameObservable.clear();\n }\n _disableTouchAction() {\n if (!this._renderingCanvas || !this._renderingCanvas.setAttribute) {\n return;\n }\n this._renderingCanvas.setAttribute(\"touch-action\", \"none\");\n this._renderingCanvas.style.touchAction = \"none\";\n this._renderingCanvas.style.webkitTapHighlightColor = \"transparent\";\n }\n // Loading screen\n /**\n * Display the loading screen\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen\n */\n displayLoadingUI() {\n if (!IsWindowObjectExist()) {\n return;\n }\n const loadingScreen = this.loadingScreen;\n if (loadingScreen) {\n loadingScreen.displayLoadingUI();\n }\n }\n /**\n * Hide the loading screen\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen\n */\n hideLoadingUI() {\n if (!IsWindowObjectExist()) {\n return;\n }\n const loadingScreen = this._loadingScreen;\n if (loadingScreen) {\n loadingScreen.hideLoadingUI();\n }\n }\n /**\n * Gets the current loading screen object\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen\n */\n get loadingScreen() {\n if (!this._loadingScreen && this._renderingCanvas) {\n this._loadingScreen = Engine.DefaultLoadingScreenFactory(this._renderingCanvas);\n }\n return this._loadingScreen;\n }\n /**\n * Sets the current loading screen object\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen\n */\n set loadingScreen(loadingScreen) {\n this._loadingScreen = loadingScreen;\n }\n /**\n * Sets the current loading screen text\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen\n */\n set loadingUIText(text) {\n this.loadingScreen.loadingUIText = text;\n }\n /**\n * Sets the current loading screen background color\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen\n */\n set loadingUIBackgroundColor(color) {\n this.loadingScreen.loadingUIBackgroundColor = color;\n }\n /**\n * creates and returns a new video element\n * @param constraints video constraints\n * @returns video element\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n createVideoElement(constraints) {\n return document.createElement(\"video\");\n }\n /** Pointerlock and fullscreen */\n /**\n * Ask the browser to promote the current element to pointerlock mode\n * @param element defines the DOM element to promote\n */\n static _RequestPointerlock(element) {\n if (element.requestPointerLock) {\n // In some browsers, requestPointerLock returns a promise.\n // Handle possible rejections to avoid an unhandled top-level exception.\n const promise = element.requestPointerLock();\n if (promise instanceof Promise)\n promise\n .then(() => {\n element.focus();\n })\n .catch(() => { });\n else\n element.focus();\n }\n }\n /**\n * Asks the browser to exit pointerlock mode\n */\n static _ExitPointerlock() {\n if (document.exitPointerLock) {\n document.exitPointerLock();\n }\n }\n /**\n * Ask the browser to promote the current element to fullscreen rendering mode\n * @param element defines the DOM element to promote\n */\n static _RequestFullscreen(element) {\n const requestFunction = element.requestFullscreen || element.webkitRequestFullscreen;\n if (!requestFunction) {\n return;\n }\n requestFunction.call(element);\n }\n /**\n * Asks the browser to exit fullscreen mode\n */\n static _ExitFullscreen() {\n const anyDoc = document;\n if (document.exitFullscreen) {\n document.exitFullscreen();\n }\n else if (anyDoc.webkitCancelFullScreen) {\n anyDoc.webkitCancelFullScreen();\n }\n }\n /**\n * Get Font size information\n * @param font font name\n * @returns an object containing ascent, height and descent\n */\n getFontOffset(font) {\n const text = document.createElement(\"span\");\n text.innerHTML = \"Hg\";\n text.setAttribute(\"style\", `font: ${font} !important`);\n const block = document.createElement(\"div\");\n block.style.display = \"inline-block\";\n block.style.width = \"1px\";\n block.style.height = \"0px\";\n block.style.verticalAlign = \"bottom\";\n const div = document.createElement(\"div\");\n div.style.whiteSpace = \"nowrap\";\n div.appendChild(text);\n div.appendChild(block);\n document.body.appendChild(div);\n let fontAscent = 0;\n let fontHeight = 0;\n try {\n fontHeight = block.getBoundingClientRect().top - text.getBoundingClientRect().top;\n block.style.verticalAlign = \"baseline\";\n fontAscent = block.getBoundingClientRect().top - text.getBoundingClientRect().top;\n }\n finally {\n document.body.removeChild(div);\n }\n return { ascent: fontAscent, height: fontHeight, descent: fontHeight - fontAscent };\n }\n}\n// Const statics\n/** Defines that alpha blending is disabled */\nEngine.ALPHA_DISABLE = 0;\n/** Defines that alpha blending to SRC ALPHA * SRC + DEST */\nEngine.ALPHA_ADD = 1;\n/** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */\nEngine.ALPHA_COMBINE = 2;\n/** Defines that alpha blending to DEST - SRC * DEST */\nEngine.ALPHA_SUBTRACT = 3;\n/** Defines that alpha blending to SRC * DEST */\nEngine.ALPHA_MULTIPLY = 4;\n/** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */\nEngine.ALPHA_MAXIMIZED = 5;\n/** Defines that alpha blending to SRC + DEST */\nEngine.ALPHA_ONEONE = 6;\n/** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */\nEngine.ALPHA_PREMULTIPLIED = 7;\n/**\n * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST\n * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA\n */\nEngine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;\n/** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */\nEngine.ALPHA_INTERPOLATE = 9;\n/**\n * Defines that alpha blending to SRC + (1 - SRC) * DEST\n * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA\n */\nEngine.ALPHA_SCREENMODE = 10;\n/** Defines that the resource is not delayed*/\nEngine.DELAYLOADSTATE_NONE = 0;\n/** Defines that the resource was successfully delay loaded */\nEngine.DELAYLOADSTATE_LOADED = 1;\n/** Defines that the resource is currently delay loading */\nEngine.DELAYLOADSTATE_LOADING = 2;\n/** Defines that the resource is delayed and has not started loading */\nEngine.DELAYLOADSTATE_NOTLOADED = 4;\n// Depht or Stencil test Constants.\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */\nEngine.NEVER = 512;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */\nEngine.ALWAYS = 519;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */\nEngine.LESS = 513;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */\nEngine.EQUAL = 514;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */\nEngine.LEQUAL = 515;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */\nEngine.GREATER = 516;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */\nEngine.GEQUAL = 518;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */\nEngine.NOTEQUAL = 517;\n// Stencil Actions Constants.\n/** Passed to stencilOperation to specify that stencil value must be kept */\nEngine.KEEP = 7680;\n/** Passed to stencilOperation to specify that stencil value must be replaced */\nEngine.REPLACE = 7681;\n/** Passed to stencilOperation to specify that stencil value must be incremented */\nEngine.INCR = 7682;\n/** Passed to stencilOperation to specify that stencil value must be decremented */\nEngine.DECR = 7683;\n/** Passed to stencilOperation to specify that stencil value must be inverted */\nEngine.INVERT = 5386;\n/** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */\nEngine.INCR_WRAP = 34055;\n/** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */\nEngine.DECR_WRAP = 34056;\n/** Texture is not repeating outside of 0..1 UVs */\nEngine.TEXTURE_CLAMP_ADDRESSMODE = 0;\n/** Texture is repeating outside of 0..1 UVs */\nEngine.TEXTURE_WRAP_ADDRESSMODE = 1;\n/** Texture is repeating and mirrored */\nEngine.TEXTURE_MIRROR_ADDRESSMODE = 2;\n/** ALPHA */\nEngine.TEXTUREFORMAT_ALPHA = 0;\n/** LUMINANCE */\nEngine.TEXTUREFORMAT_LUMINANCE = 1;\n/** LUMINANCE_ALPHA */\nEngine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;\n/** RGB */\nEngine.TEXTUREFORMAT_RGB = 4;\n/** RGBA */\nEngine.TEXTUREFORMAT_RGBA = 5;\n/** RED */\nEngine.TEXTUREFORMAT_RED = 6;\n/** RED (2nd reference) */\nEngine.TEXTUREFORMAT_R = 6;\n/** RG */\nEngine.TEXTUREFORMAT_RG = 7;\n/** RED_INTEGER */\nEngine.TEXTUREFORMAT_RED_INTEGER = 8;\n/** RED_INTEGER (2nd reference) */\nEngine.TEXTUREFORMAT_R_INTEGER = 8;\n/** RG_INTEGER */\nEngine.TEXTUREFORMAT_RG_INTEGER = 9;\n/** RGB_INTEGER */\nEngine.TEXTUREFORMAT_RGB_INTEGER = 10;\n/** RGBA_INTEGER */\nEngine.TEXTUREFORMAT_RGBA_INTEGER = 11;\n/** UNSIGNED_BYTE */\nEngine.TEXTURETYPE_UNSIGNED_BYTE = 0;\n/** UNSIGNED_BYTE (2nd reference) */\nEngine.TEXTURETYPE_UNSIGNED_INT = 0;\n/** FLOAT */\nEngine.TEXTURETYPE_FLOAT = 1;\n/** HALF_FLOAT */\nEngine.TEXTURETYPE_HALF_FLOAT = 2;\n/** BYTE */\nEngine.TEXTURETYPE_BYTE = 3;\n/** SHORT */\nEngine.TEXTURETYPE_SHORT = 4;\n/** UNSIGNED_SHORT */\nEngine.TEXTURETYPE_UNSIGNED_SHORT = 5;\n/** INT */\nEngine.TEXTURETYPE_INT = 6;\n/** UNSIGNED_INT */\nEngine.TEXTURETYPE_UNSIGNED_INTEGER = 7;\n/** UNSIGNED_SHORT_4_4_4_4 */\nEngine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;\n/** UNSIGNED_SHORT_5_5_5_1 */\nEngine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;\n/** UNSIGNED_SHORT_5_6_5 */\nEngine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;\n/** UNSIGNED_INT_2_10_10_10_REV */\nEngine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;\n/** UNSIGNED_INT_24_8 */\nEngine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;\n/** UNSIGNED_INT_10F_11F_11F_REV */\nEngine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;\n/** UNSIGNED_INT_5_9_9_9_REV */\nEngine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;\n/** FLOAT_32_UNSIGNED_INT_24_8_REV */\nEngine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;\n/** nearest is mag = nearest and min = nearest and mip = none */\nEngine.TEXTURE_NEAREST_SAMPLINGMODE = 1;\n/** Bilinear is mag = linear and min = linear and mip = nearest */\nEngine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;\n/** Trilinear is mag = linear and min = linear and mip = linear */\nEngine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;\n/** nearest is mag = nearest and min = nearest and mip = linear */\nEngine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 8;\n/** Bilinear is mag = linear and min = linear and mip = nearest */\nEngine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 11;\n/** Trilinear is mag = linear and min = linear and mip = linear */\nEngine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;\n/** mag = nearest and min = nearest and mip = nearest */\nEngine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;\n/** mag = nearest and min = linear and mip = nearest */\nEngine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;\n/** mag = nearest and min = linear and mip = linear */\nEngine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;\n/** mag = nearest and min = linear and mip = none */\nEngine.TEXTURE_NEAREST_LINEAR = 7;\n/** mag = nearest and min = nearest and mip = none */\nEngine.TEXTURE_NEAREST_NEAREST = 1;\n/** mag = linear and min = nearest and mip = nearest */\nEngine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;\n/** mag = linear and min = nearest and mip = linear */\nEngine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;\n/** mag = linear and min = linear and mip = none */\nEngine.TEXTURE_LINEAR_LINEAR = 2;\n/** mag = linear and min = nearest and mip = none */\nEngine.TEXTURE_LINEAR_NEAREST = 12;\n/** Explicit coordinates mode */\nEngine.TEXTURE_EXPLICIT_MODE = 0;\n/** Spherical coordinates mode */\nEngine.TEXTURE_SPHERICAL_MODE = 1;\n/** Planar coordinates mode */\nEngine.TEXTURE_PLANAR_MODE = 2;\n/** Cubic coordinates mode */\nEngine.TEXTURE_CUBIC_MODE = 3;\n/** Projection coordinates mode */\nEngine.TEXTURE_PROJECTION_MODE = 4;\n/** Skybox coordinates mode */\nEngine.TEXTURE_SKYBOX_MODE = 5;\n/** Inverse Cubic coordinates mode */\nEngine.TEXTURE_INVCUBIC_MODE = 6;\n/** Equirectangular coordinates mode */\nEngine.TEXTURE_EQUIRECTANGULAR_MODE = 7;\n/** Equirectangular Fixed coordinates mode */\nEngine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;\n/** Equirectangular Fixed Mirrored coordinates mode */\nEngine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;\n// Texture rescaling mode\n/** Defines that texture rescaling will use a floor to find the closer power of 2 size */\nEngine.SCALEMODE_FLOOR = 1;\n/** Defines that texture rescaling will look for the nearest power of 2 size */\nEngine.SCALEMODE_NEAREST = 2;\n/** Defines that texture rescaling will use a ceil to find the closer power of 2 size */\nEngine.SCALEMODE_CEILING = 3;\n/**\n * Method called to create the default rescale post process on each engine.\n */\nEngine._RescalePostProcessFactory = null;\n// eslint-disable-next-line @typescript-eslint/naming-convention\nEngine._RenderPassIdCounter = 0;\n//# sourceMappingURL=engine.js.map","import { Observable } from \"../Misc/observable.js\";\n/**\n * The engine store class is responsible to hold all the instances of Engine and Scene created\n * during the life time of the application.\n */\nexport class EngineStore {\n /**\n * Gets the latest created engine\n */\n static get LastCreatedEngine() {\n if (this.Instances.length === 0) {\n return null;\n }\n return this.Instances[this.Instances.length - 1];\n }\n /**\n * Gets the latest created scene\n */\n static get LastCreatedScene() {\n return this._LastCreatedScene;\n }\n}\n/** Gets the list of created engines */\nEngineStore.Instances = new Array();\n/**\n * Notifies when an engine was disposed.\n * Mainly used for static/cache cleanup\n */\nEngineStore.OnEnginesDisposedObservable = new Observable();\n/** @internal */\nEngineStore._LastCreatedScene = null;\n/**\n * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded\n * @ignorenaming\n */\nEngineStore.UseFallbackTexture = true;\n/**\n * Texture content used if a texture cannot loaded\n * @ignorenaming\n */\nEngineStore.FallbackTexture = \"\";\n//# sourceMappingURL=engineStore.js.map","import { ShaderLanguage } from \"../Materials/shaderLanguage.js\";\n/**\n * Defines the shader related stores and directory\n */\nexport class ShaderStore {\n /**\n * Gets the shaders repository path for a given shader language\n * @param shaderLanguage the shader language\n * @returns the path to the shaders repository\n */\n static GetShadersRepository(shaderLanguage = ShaderLanguage.GLSL) {\n return shaderLanguage === ShaderLanguage.GLSL ? ShaderStore.ShadersRepository : ShaderStore.ShadersRepositoryWGSL;\n }\n /**\n * Gets the shaders store of a given shader language\n * @param shaderLanguage the shader language\n * @returns the shaders store\n */\n static GetShadersStore(shaderLanguage = ShaderLanguage.GLSL) {\n return shaderLanguage === ShaderLanguage.GLSL ? ShaderStore.ShadersStore : ShaderStore.ShadersStoreWGSL;\n }\n /**\n * Gets the include shaders store of a given shader language\n * @param shaderLanguage the shader language\n * @returns the include shaders store\n */\n static GetIncludesShadersStore(shaderLanguage = ShaderLanguage.GLSL) {\n return shaderLanguage === ShaderLanguage.GLSL ? ShaderStore.IncludesShadersStore : ShaderStore.IncludesShadersStoreWGSL;\n }\n}\n/**\n * Gets or sets the relative url used to load shaders if using the engine in non-minified mode\n */\nShaderStore.ShadersRepository = \"src/Shaders/\";\n/**\n * Store of each shader (The can be looked up using effect.key)\n */\nShaderStore.ShadersStore = {};\n/**\n * Store of each included file for a shader (The can be looked up using effect.key)\n */\nShaderStore.IncludesShadersStore = {};\n/**\n * Gets or sets the relative url used to load shaders (WGSL) if using the engine in non-minified mode\n */\nShaderStore.ShadersRepositoryWGSL = \"src/ShadersWGSL/\";\n/**\n * Store of each shader (WGSL)\n */\nShaderStore.ShadersStoreWGSL = {};\n/**\n * Store of each included file for a shader (WGSL)\n */\nShaderStore.IncludesShadersStoreWGSL = {};\n//# sourceMappingURL=shaderStore.js.map","/**\n * Event Types\n */\nexport var DeviceInputEventType;\n(function (DeviceInputEventType) {\n // Pointers\n /** PointerMove */\n DeviceInputEventType[DeviceInputEventType[\"PointerMove\"] = 0] = \"PointerMove\";\n /** PointerDown */\n DeviceInputEventType[DeviceInputEventType[\"PointerDown\"] = 1] = \"PointerDown\";\n /** PointerUp */\n DeviceInputEventType[DeviceInputEventType[\"PointerUp\"] = 2] = \"PointerUp\";\n})(DeviceInputEventType || (DeviceInputEventType = {}));\n/**\n * Constants used for Events\n */\nexport class EventConstants {\n}\n/**\n * Pixel delta for Wheel Events (Default)\n */\nEventConstants.DOM_DELTA_PIXEL = 0x00;\n/**\n * Line delta for Wheel Events\n */\nEventConstants.DOM_DELTA_LINE = 0x01;\n/**\n * Page delta for Wheel Events\n */\nEventConstants.DOM_DELTA_PAGE = 0x02;\n//# sourceMappingURL=deviceInputEvents.js.map","/**\n * Gather the list of keyboard event types as constants.\n */\nexport class KeyboardEventTypes {\n}\n/**\n * The keydown event is fired when a key becomes active (pressed).\n */\nKeyboardEventTypes.KEYDOWN = 0x01;\n/**\n * The keyup event is fired when a key has been released.\n */\nKeyboardEventTypes.KEYUP = 0x02;\n/**\n * This class is used to store keyboard related info for the onKeyboardObservable event.\n */\nexport class KeyboardInfo {\n /**\n * Instantiates a new keyboard info.\n * This class is used to store keyboard related info for the onKeyboardObservable event.\n * @param type Defines the type of event (KeyboardEventTypes)\n * @param event Defines the related dom event\n */\n constructor(\n /**\n * Defines the type of event (KeyboardEventTypes)\n */\n type, \n /**\n * Defines the related dom event\n */\n event) {\n this.type = type;\n this.event = event;\n }\n}\n/**\n * This class is used to store keyboard related info for the onPreKeyboardObservable event.\n * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable\n */\nexport class KeyboardInfoPre extends KeyboardInfo {\n /**\n * Defines whether the engine should skip the next onKeyboardObservable associated to this pre.\n * @deprecated use skipOnKeyboardObservable property instead\n */\n get skipOnPointerObservable() {\n return this.skipOnKeyboardObservable;\n }\n set skipOnPointerObservable(value) {\n this.skipOnKeyboardObservable = value;\n }\n /**\n * Instantiates a new keyboard pre info.\n * This class is used to store keyboard related info for the onPreKeyboardObservable event.\n * @param type Defines the type of event (KeyboardEventTypes)\n * @param event Defines the related dom event\n */\n constructor(\n /**\n * Defines the type of event (KeyboardEventTypes)\n */\n type, \n /**\n * Defines the related dom event\n */\n event) {\n super(type, event);\n this.type = type;\n this.event = event;\n this.skipOnKeyboardObservable = false;\n }\n}\n//# sourceMappingURL=keyboardEvents.js.map","import { Vector2 } from \"../Maths/math.vector.js\";\n/**\n * Gather the list of pointer event types as constants.\n */\nexport class PointerEventTypes {\n}\n/**\n * The pointerdown event is fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer.\n */\nPointerEventTypes.POINTERDOWN = 0x01;\n/**\n * The pointerup event is fired when a pointer is no longer active.\n */\nPointerEventTypes.POINTERUP = 0x02;\n/**\n * The pointermove event is fired when a pointer changes coordinates.\n */\nPointerEventTypes.POINTERMOVE = 0x04;\n/**\n * The pointerwheel event is fired when a mouse wheel has been rotated.\n */\nPointerEventTypes.POINTERWHEEL = 0x08;\n/**\n * The pointerpick event is fired when a mesh or sprite has been picked by the pointer.\n */\nPointerEventTypes.POINTERPICK = 0x10;\n/**\n * The pointertap event is fired when a the object has been touched and released without drag.\n */\nPointerEventTypes.POINTERTAP = 0x20;\n/**\n * The pointerdoubletap event is fired when a the object has been touched and released twice without drag.\n */\nPointerEventTypes.POINTERDOUBLETAP = 0x40;\n/**\n * Base class of pointer info types.\n */\nexport class PointerInfoBase {\n /**\n * Instantiates the base class of pointers info.\n * @param type Defines the type of event (PointerEventTypes)\n * @param event Defines the related dom event\n */\n constructor(\n /**\n * Defines the type of event (PointerEventTypes)\n */\n type, \n /**\n * Defines the related dom event\n */\n event) {\n this.type = type;\n this.event = event;\n }\n}\n/**\n * This class is used to store pointer related info for the onPrePointerObservable event.\n * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable\n */\nexport class PointerInfoPre extends PointerInfoBase {\n /**\n * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event.\n * @param type Defines the type of event (PointerEventTypes)\n * @param event Defines the related dom event\n * @param localX Defines the local x coordinates of the pointer when the event occured\n * @param localY Defines the local y coordinates of the pointer when the event occured\n */\n constructor(type, event, localX, localY) {\n super(type, event);\n /**\n * Ray from a pointer if available (eg. 6dof controller)\n */\n this.ray = null;\n /**\n * The original picking info that was used to trigger the pointer event\n */\n this.originalPickingInfo = null;\n this.skipOnPointerObservable = false;\n this.localPosition = new Vector2(localX, localY);\n }\n}\n/**\n * This type contains all the data related to a pointer event in Babylon.js.\n * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.\n */\nexport class PointerInfo extends PointerInfoBase {\n /**\n * Defines the picking info associated with this PointerInfo object (if applicable)\n */\n get pickInfo() {\n if (!this._pickInfo) {\n this._generatePickInfo();\n }\n return this._pickInfo;\n }\n /**\n * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event.\n * @param type Defines the type of event (PointerEventTypes)\n * @param event Defines the related dom event\n * @param pickInfo Defines the picking info associated to the info (if any)\n * @param inputManager Defines the InputManager to use if there is no pickInfo\n */\n constructor(type, event, pickInfo, inputManager = null) {\n super(type, event);\n this._pickInfo = pickInfo;\n this._inputManager = inputManager;\n }\n /**\n * Generates the picking info if needed\n */\n /** @internal */\n _generatePickInfo() {\n if (this._inputManager) {\n this._pickInfo = this._inputManager._pickMove(this.event);\n this._inputManager._setRayOnPointerInfo(this._pickInfo, this.event);\n this._inputManager = null;\n }\n }\n}\n//# sourceMappingURL=pointerEvents.js.map","/**\n * Class used to store configuration data associated with pointer picking\n */\nexport class PointerPickingConfiguration {\n constructor() {\n /**\n * Gets or sets a predicate used to select candidate meshes for a pointer down event\n */\n this.pointerDownFastCheck = false;\n /**\n * Gets or sets a predicate used to select candidate meshes for a pointer up event\n */\n this.pointerUpFastCheck = false;\n /**\n * Gets or sets a predicate used to select candidate meshes for a pointer move event\n */\n this.pointerMoveFastCheck = false;\n /**\n * Gets or sets a boolean indicating if the user want to entirely skip the picking phase when a pointer move event occurs.\n */\n this.skipPointerMovePicking = false;\n /**\n * Gets or sets a boolean indicating if the user want to entirely skip the picking phase when a pointer down event occurs.\n */\n this.skipPointerDownPicking = false;\n /**\n * Gets or sets a boolean indicating if the user want to entirely skip the picking phase when a pointer up event occurs. Off by default.\n */\n this.skipPointerUpPicking = false;\n }\n}\n//# sourceMappingURL=pointerPickingConfiguration.js.map","import { PointerInfoPre, PointerInfo, PointerEventTypes } from \"../Events/pointerEvents.js\";\nimport { AbstractActionManager } from \"../Actions/abstractActionManager.js\";\nimport { PickingInfo } from \"../Collisions/pickingInfo.js\";\nimport { Vector2, Matrix } from \"../Maths/math.vector.js\";\n\nimport { ActionEvent } from \"../Actions/actionEvent.js\";\nimport { KeyboardEventTypes, KeyboardInfoPre, KeyboardInfo } from \"../Events/keyboardEvents.js\";\nimport { DeviceType, PointerInput } from \"../DeviceInput/InputDevices/deviceEnums.js\";\nimport { DeviceSourceManager } from \"../DeviceInput/InputDevices/deviceSourceManager.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n/** @internal */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nclass _ClickInfo {\n constructor() {\n this._singleClick = false;\n this._doubleClick = false;\n this._hasSwiped = false;\n this._ignore = false;\n }\n get singleClick() {\n return this._singleClick;\n }\n get doubleClick() {\n return this._doubleClick;\n }\n get hasSwiped() {\n return this._hasSwiped;\n }\n get ignore() {\n return this._ignore;\n }\n set singleClick(b) {\n this._singleClick = b;\n }\n set doubleClick(b) {\n this._doubleClick = b;\n }\n set hasSwiped(b) {\n this._hasSwiped = b;\n }\n set ignore(b) {\n this._ignore = b;\n }\n}\n/**\n * Class used to manage all inputs for the scene.\n */\nexport class InputManager {\n /**\n * Creates a new InputManager\n * @param scene - defines the hosting scene\n */\n constructor(scene) {\n /** This is a defensive check to not allow control attachment prior to an already active one. If already attached, previous control is unattached before attaching the new one. */\n this._alreadyAttached = false;\n this._meshPickProceed = false;\n this._currentPickResult = null;\n this._previousPickResult = null;\n this._totalPointersPressed = 0;\n this._doubleClickOccured = false;\n this._isSwiping = false;\n this._swipeButtonPressed = -1;\n this._skipPointerTap = false;\n this._isMultiTouchGesture = false;\n this._pointerX = 0;\n this._pointerY = 0;\n this._startingPointerPosition = new Vector2(0, 0);\n this._previousStartingPointerPosition = new Vector2(0, 0);\n this._startingPointerTime = 0;\n this._previousStartingPointerTime = 0;\n this._pointerCaptures = {};\n this._meshUnderPointerId = {};\n this._movePointerInfo = null;\n this._cameraObserverCount = 0;\n this._delayedClicks = [null, null, null, null, null];\n this._deviceSourceManager = null;\n this._scene = scene || EngineStore.LastCreatedScene;\n if (!this._scene) {\n return;\n }\n }\n /**\n * Gets the mesh that is currently under the pointer\n * @returns Mesh that the pointer is pointer is hovering over\n */\n get meshUnderPointer() {\n if (this._movePointerInfo) {\n // Because _pointerOverMesh is populated as part of _pickMove, we need to force a pick to update it.\n // Calling _pickMove calls _setCursorAndPointerOverMesh which calls setPointerOverMesh\n this._movePointerInfo._generatePickInfo();\n // Once we have what we need, we can clear _movePointerInfo because we don't need it anymore\n this._movePointerInfo = null;\n }\n return this._pointerOverMesh;\n }\n /**\n * When using more than one pointer (for example in XR) you can get the mesh under the specific pointer\n * @param pointerId - the pointer id to use\n * @returns The mesh under this pointer id or null if not found\n */\n getMeshUnderPointerByPointerId(pointerId) {\n return this._meshUnderPointerId[pointerId] || null;\n }\n /**\n * Gets the pointer coordinates in 2D without any translation (ie. straight out of the pointer event)\n * @returns Vector with X/Y values directly from pointer event\n */\n get unTranslatedPointer() {\n return new Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);\n }\n /**\n * Gets or sets the current on-screen X position of the pointer\n * @returns Translated X with respect to screen\n */\n get pointerX() {\n return this._pointerX;\n }\n set pointerX(value) {\n this._pointerX = value;\n }\n /**\n * Gets or sets the current on-screen Y position of the pointer\n * @returns Translated Y with respect to screen\n */\n get pointerY() {\n return this._pointerY;\n }\n set pointerY(value) {\n this._pointerY = value;\n }\n _updatePointerPosition(evt) {\n const canvasRect = this._scene.getEngine().getInputElementClientRect();\n if (!canvasRect) {\n return;\n }\n this._pointerX = evt.clientX - canvasRect.left;\n this._pointerY = evt.clientY - canvasRect.top;\n this._unTranslatedPointerX = this._pointerX;\n this._unTranslatedPointerY = this._pointerY;\n }\n _processPointerMove(pickResult, evt) {\n const scene = this._scene;\n const engine = scene.getEngine();\n const canvas = engine.getInputElement();\n if (canvas) {\n canvas.tabIndex = engine.canvasTabIndex;\n // Restore pointer\n if (!scene.doNotHandleCursors) {\n canvas.style.cursor = scene.defaultCursor;\n }\n }\n this._setCursorAndPointerOverMesh(pickResult, evt, scene);\n for (const step of scene._pointerMoveStage) {\n // If _pointerMoveState is defined, we have an active spriteManager and can't use Lazy Picking\n // Therefore, we need to force a pick to update the pickResult\n pickResult = pickResult || this._pickMove(evt);\n const isMeshPicked = (pickResult === null || pickResult === void 0 ? void 0 : pickResult.pickedMesh) ? true : false;\n pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);\n }\n const type = evt.inputIndex >= PointerInput.MouseWheelX && evt.inputIndex <= PointerInput.MouseWheelZ ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;\n if (scene.onPointerMove) {\n // Because of lazy picking, we need to force a pick to update the pickResult\n pickResult = pickResult || this._pickMove(evt);\n scene.onPointerMove(evt, pickResult, type);\n }\n let pointerInfo;\n if (pickResult) {\n pointerInfo = new PointerInfo(type, evt, pickResult);\n this._setRayOnPointerInfo(pickResult, evt);\n }\n else {\n pointerInfo = new PointerInfo(type, evt, null, this);\n this._movePointerInfo = pointerInfo;\n }\n if (scene.onPointerObservable.hasObservers()) {\n scene.onPointerObservable.notifyObservers(pointerInfo, type);\n }\n }\n // Pointers handling\n /** @internal */\n _setRayOnPointerInfo(pickInfo, event) {\n const scene = this._scene;\n if (pickInfo && scene._pickingAvailable) {\n if (!pickInfo.ray) {\n pickInfo.ray = scene.createPickingRay(event.offsetX, event.offsetY, Matrix.Identity(), scene.activeCamera);\n }\n }\n }\n /** @internal */\n _addCameraPointerObserver(observer, mask) {\n this._cameraObserverCount++;\n return this._scene.onPointerObservable.add(observer, mask);\n }\n /** @internal */\n _removeCameraPointerObserver(observer) {\n this._cameraObserverCount--;\n return this._scene.onPointerObservable.remove(observer);\n }\n _checkForPicking() {\n return !!(this._scene.onPointerObservable.observers.length > this._cameraObserverCount || this._scene.onPointerPick);\n }\n _checkPrePointerObservable(pickResult, evt, type) {\n const scene = this._scene;\n const pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);\n if (pickResult) {\n pi.originalPickingInfo = pickResult;\n pi.ray = pickResult.ray;\n if (pickResult.originMesh) {\n pi.nearInteractionPickingInfo = pickResult;\n }\n }\n scene.onPrePointerObservable.notifyObservers(pi, type);\n if (pi.skipOnPointerObservable) {\n return true;\n }\n else {\n return false;\n }\n }\n /** @internal */\n _pickMove(evt) {\n const scene = this._scene;\n const pickResult = scene.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, scene.pointerMovePredicate, scene.pointerMoveFastCheck, scene.cameraToUseForPointers, scene.pointerMoveTrianglePredicate);\n this._setCursorAndPointerOverMesh(pickResult, evt, scene);\n return pickResult;\n }\n _setCursorAndPointerOverMesh(pickResult, evt, scene) {\n const engine = scene.getEngine();\n const canvas = engine.getInputElement();\n if (pickResult === null || pickResult === void 0 ? void 0 : pickResult.pickedMesh) {\n this.setPointerOverMesh(pickResult.pickedMesh, evt.pointerId, pickResult, evt);\n if (!scene.doNotHandleCursors && canvas && this._pointerOverMesh) {\n const actionManager = this._pointerOverMesh._getActionManagerForTrigger();\n if (actionManager && actionManager.hasPointerTriggers) {\n canvas.style.cursor = actionManager.hoverCursor || scene.hoverCursor;\n }\n }\n }\n else {\n this.setPointerOverMesh(null, evt.pointerId, pickResult, evt);\n }\n }\n /**\n * Use this method to simulate a pointer move on a mesh\n * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay\n * @param pickResult - pickingInfo of the object wished to simulate pointer event on\n * @param pointerEventInit - pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)\n */\n simulatePointerMove(pickResult, pointerEventInit) {\n const evt = new PointerEvent(\"pointermove\", pointerEventInit);\n evt.inputIndex = PointerInput.Move;\n if (this._checkPrePointerObservable(pickResult, evt, PointerEventTypes.POINTERMOVE)) {\n return;\n }\n this._processPointerMove(pickResult, evt);\n }\n /**\n * Use this method to simulate a pointer down on a mesh\n * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay\n * @param pickResult - pickingInfo of the object wished to simulate pointer event on\n * @param pointerEventInit - pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)\n */\n simulatePointerDown(pickResult, pointerEventInit) {\n const evt = new PointerEvent(\"pointerdown\", pointerEventInit);\n evt.inputIndex = evt.button + 2;\n if (this._checkPrePointerObservable(pickResult, evt, PointerEventTypes.POINTERDOWN)) {\n return;\n }\n this._processPointerDown(pickResult, evt);\n }\n _processPointerDown(pickResult, evt) {\n const scene = this._scene;\n if (pickResult === null || pickResult === void 0 ? void 0 : pickResult.pickedMesh) {\n this._pickedDownMesh = pickResult.pickedMesh;\n const actionManager = pickResult.pickedMesh._getActionManagerForTrigger();\n if (actionManager) {\n if (actionManager.hasPickTriggers) {\n actionManager.processTrigger(5, ActionEvent.CreateNew(pickResult.pickedMesh, evt));\n switch (evt.button) {\n case 0:\n actionManager.processTrigger(2, ActionEvent.CreateNew(pickResult.pickedMesh, evt));\n break;\n case 1:\n actionManager.processTrigger(4, ActionEvent.CreateNew(pickResult.pickedMesh, evt));\n break;\n case 2:\n actionManager.processTrigger(3, ActionEvent.CreateNew(pickResult.pickedMesh, evt));\n break;\n }\n }\n if (actionManager.hasSpecificTrigger(8)) {\n window.setTimeout(() => {\n const pickResult = scene.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, (mesh) => ((mesh.isPickable &&\n mesh.isVisible &&\n mesh.isReady() &&\n mesh.actionManager &&\n mesh.actionManager.hasSpecificTrigger(8) &&\n mesh === this._pickedDownMesh)), false, scene.cameraToUseForPointers);\n if ((pickResult === null || pickResult === void 0 ? void 0 : pickResult.pickedMesh) && actionManager) {\n if (this._totalPointersPressed !== 0 && Date.now() - this._startingPointerTime > InputManager.LongPressDelay && !this._isPointerSwiping()) {\n this._startingPointerTime = 0;\n actionManager.processTrigger(8, ActionEvent.CreateNew(pickResult.pickedMesh, evt));\n }\n }\n }, InputManager.LongPressDelay);\n }\n }\n }\n else {\n for (const step of scene._pointerDownStage) {\n pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt, false);\n }\n }\n let pointerInfo;\n const type = PointerEventTypes.POINTERDOWN;\n if (pickResult) {\n if (scene.onPointerDown) {\n scene.onPointerDown(evt, pickResult, type);\n }\n pointerInfo = new PointerInfo(type, evt, pickResult);\n this._setRayOnPointerInfo(pickResult, evt);\n }\n else {\n pointerInfo = new PointerInfo(type, evt, null, this);\n }\n if (scene.onPointerObservable.hasObservers()) {\n scene.onPointerObservable.notifyObservers(pointerInfo, type);\n }\n }\n /**\n * @internal\n * @internals Boolean if delta for pointer exceeds drag movement threshold\n */\n _isPointerSwiping() {\n return this._isSwiping;\n }\n /**\n * Use this method to simulate a pointer up on a mesh\n * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay\n * @param pickResult - pickingInfo of the object wished to simulate pointer event on\n * @param pointerEventInit - pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)\n * @param doubleTap - indicates that the pointer up event should be considered as part of a double click (false by default)\n */\n simulatePointerUp(pickResult, pointerEventInit, doubleTap) {\n const evt = new PointerEvent(\"pointerup\", pointerEventInit);\n evt.inputIndex = PointerInput.Move;\n const clickInfo = new _ClickInfo();\n if (doubleTap) {\n clickInfo.doubleClick = true;\n }\n else {\n clickInfo.singleClick = true;\n }\n if (this._checkPrePointerObservable(pickResult, evt, PointerEventTypes.POINTERUP)) {\n return;\n }\n this._processPointerUp(pickResult, evt, clickInfo);\n }\n _processPointerUp(pickResult, evt, clickInfo) {\n const scene = this._scene;\n if (pickResult === null || pickResult === void 0 ? void 0 : pickResult.pickedMesh) {\n this._pickedUpMesh = pickResult.pickedMesh;\n if (this._pickedDownMesh === this._pickedUpMesh) {\n if (scene.onPointerPick) {\n scene.onPointerPick(evt, pickResult);\n }\n if (clickInfo.singleClick && !clickInfo.ignore && scene.onPointerObservable.observers.length > this._cameraObserverCount) {\n const type = PointerEventTypes.POINTERPICK;\n const pi = new PointerInfo(type, evt, pickResult);\n this._setRayOnPointerInfo(pickResult, evt);\n scene.onPointerObservable.notifyObservers(pi, type);\n }\n }\n const actionManager = pickResult.pickedMesh._getActionManagerForTrigger();\n if (actionManager && !clickInfo.ignore) {\n actionManager.processTrigger(7, ActionEvent.CreateNew(pickResult.pickedMesh, evt, pickResult));\n if (!clickInfo.hasSwiped && clickInfo.singleClick) {\n actionManager.processTrigger(1, ActionEvent.CreateNew(pickResult.pickedMesh, evt, pickResult));\n }\n const doubleClickActionManager = pickResult.pickedMesh._getActionManagerForTrigger(6);\n if (clickInfo.doubleClick && doubleClickActionManager) {\n doubleClickActionManager.processTrigger(6, ActionEvent.CreateNew(pickResult.pickedMesh, evt, pickResult));\n }\n }\n }\n else {\n if (!clickInfo.ignore) {\n for (const step of scene._pointerUpStage) {\n pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt, clickInfo.doubleClick);\n }\n }\n }\n if (this._pickedDownMesh && this._pickedDownMesh !== this._pickedUpMesh) {\n const pickedDownActionManager = this._pickedDownMesh._getActionManagerForTrigger(16);\n if (pickedDownActionManager) {\n pickedDownActionManager.processTrigger(16, ActionEvent.CreateNew(this._pickedDownMesh, evt));\n }\n }\n if (!clickInfo.ignore) {\n const pi = new PointerInfo(PointerEventTypes.POINTERUP, evt, pickResult);\n // Set ray on picking info. Note that this info will also be reused for the tap notification.\n this._setRayOnPointerInfo(pickResult, evt);\n scene.onPointerObservable.notifyObservers(pi, PointerEventTypes.POINTERUP);\n if (scene.onPointerUp) {\n scene.onPointerUp(evt, pickResult, PointerEventTypes.POINTERUP);\n }\n if (!clickInfo.hasSwiped && !this._skipPointerTap && !this._isMultiTouchGesture) {\n let type = 0;\n if (clickInfo.singleClick) {\n type = PointerEventTypes.POINTERTAP;\n }\n else if (clickInfo.doubleClick) {\n type = PointerEventTypes.POINTERDOUBLETAP;\n }\n if (type) {\n const pi = new PointerInfo(type, evt, pickResult);\n if (scene.onPointerObservable.hasObservers() && scene.onPointerObservable.hasSpecificMask(type)) {\n scene.onPointerObservable.notifyObservers(pi, type);\n }\n }\n }\n }\n }\n /**\n * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)\n * @param pointerId - defines the pointer id to use in a multi-touch scenario (0 by default)\n * @returns true if the pointer was captured\n */\n isPointerCaptured(pointerId = 0) {\n return this._pointerCaptures[pointerId];\n }\n /**\n * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp\n * @param attachUp - defines if you want to attach events to pointerup\n * @param attachDown - defines if you want to attach events to pointerdown\n * @param attachMove - defines if you want to attach events to pointermove\n * @param elementToAttachTo - defines the target DOM element to attach to (will use the canvas by default)\n */\n attachControl(attachUp = true, attachDown = true, attachMove = true, elementToAttachTo = null) {\n const scene = this._scene;\n const engine = scene.getEngine();\n if (!elementToAttachTo) {\n elementToAttachTo = engine.getInputElement();\n }\n if (this._alreadyAttached) {\n this.detachControl();\n }\n if (elementToAttachTo) {\n this._alreadyAttachedTo = elementToAttachTo;\n }\n this._deviceSourceManager = new DeviceSourceManager(engine);\n // Because this is only called from _initClickEvent, which is called in _onPointerUp, we'll use the pointerUpPredicate for the pick call\n this._initActionManager = (act) => {\n if (!this._meshPickProceed) {\n const pickResult = scene.skipPointerUpPicking || (scene._registeredActions === 0 && !this._checkForPicking() && !scene.onPointerUp)\n ? null\n : scene.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, scene.pointerUpPredicate, scene.pointerUpFastCheck, scene.cameraToUseForPointers);\n this._currentPickResult = pickResult;\n if (pickResult) {\n act = pickResult.hit && pickResult.pickedMesh ? pickResult.pickedMesh._getActionManagerForTrigger() : null;\n }\n this._meshPickProceed = true;\n }\n return act;\n };\n this._delayedSimpleClick = (btn, clickInfo, cb) => {\n // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different\n if ((Date.now() - this._previousStartingPointerTime > InputManager.DoubleClickDelay && !this._doubleClickOccured) || btn !== this._previousButtonPressed) {\n this._doubleClickOccured = false;\n clickInfo.singleClick = true;\n clickInfo.ignore = false;\n // If we have a delayed click, we need to resolve the TAP event\n if (this._delayedClicks[btn]) {\n const evt = this._delayedClicks[btn].evt;\n const type = PointerEventTypes.POINTERTAP;\n const pi = new PointerInfo(type, evt, this._currentPickResult);\n if (scene.onPointerObservable.hasObservers() && scene.onPointerObservable.hasSpecificMask(type)) {\n scene.onPointerObservable.notifyObservers(pi, type);\n }\n // Clear the delayed click\n this._delayedClicks[btn] = null;\n }\n }\n };\n this._initClickEvent = (obs1, obs2, evt, cb) => {\n var _a, _b;\n const clickInfo = new _ClickInfo();\n this._currentPickResult = null;\n let act = null;\n let checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) ||\n obs2.hasSpecificMask(PointerEventTypes.POINTERPICK) ||\n obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) ||\n obs2.hasSpecificMask(PointerEventTypes.POINTERTAP) ||\n obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||\n obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);\n if (!checkPicking && AbstractActionManager) {\n act = this._initActionManager(act, clickInfo);\n if (act) {\n checkPicking = act.hasPickTriggers;\n }\n }\n let needToIgnoreNext = false;\n if (checkPicking) {\n const btn = evt.button;\n clickInfo.hasSwiped = this._isPointerSwiping();\n if (!clickInfo.hasSwiped) {\n let checkSingleClickImmediately = !InputManager.ExclusiveDoubleClickMode;\n if (!checkSingleClickImmediately) {\n checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) && !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);\n if (checkSingleClickImmediately && !AbstractActionManager.HasSpecificTrigger(6)) {\n act = this._initActionManager(act, clickInfo);\n if (act) {\n checkSingleClickImmediately = !act.hasSpecificTrigger(6);\n }\n }\n }\n if (checkSingleClickImmediately) {\n // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required\n if (Date.now() - this._previousStartingPointerTime > InputManager.DoubleClickDelay || btn !== this._previousButtonPressed) {\n clickInfo.singleClick = true;\n cb(clickInfo, this._currentPickResult);\n needToIgnoreNext = true;\n }\n }\n // at least one double click is required to be check and exclusive double click is enabled\n else {\n // Queue up a delayed click, just in case this isn't a double click\n // It should be noted that while this delayed event happens\n // because of user input, it shouldn't be considered as a direct,\n // timing-dependent result of that input. It's meant to just fire the TAP event\n const delayedClick = {\n evt: evt,\n clickInfo: clickInfo,\n timeoutId: window.setTimeout(this._delayedSimpleClick.bind(this, btn, clickInfo, cb), InputManager.DoubleClickDelay),\n };\n this._delayedClicks[btn] = delayedClick;\n }\n let checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);\n if (!checkDoubleClick && AbstractActionManager.HasSpecificTrigger(6)) {\n act = this._initActionManager(act, clickInfo);\n if (act) {\n checkDoubleClick = act.hasSpecificTrigger(6);\n }\n }\n if (checkDoubleClick) {\n // two successive keys pressed are equal, double click delay is not over and double click has not just occurred\n if (btn === this._previousButtonPressed && Date.now() - this._previousStartingPointerTime < InputManager.DoubleClickDelay && !this._doubleClickOccured) {\n // pointer has not moved for 2 clicks, it's a double click\n if (!clickInfo.hasSwiped && !this._isPointerSwiping()) {\n this._previousStartingPointerTime = 0;\n this._doubleClickOccured = true;\n clickInfo.doubleClick = true;\n clickInfo.ignore = false;\n // If we have a pending click, we need to cancel it\n if (InputManager.ExclusiveDoubleClickMode && this._delayedClicks[btn]) {\n clearTimeout((_a = this._delayedClicks[btn]) === null || _a === void 0 ? void 0 : _a.timeoutId);\n this._delayedClicks[btn] = null;\n }\n cb(clickInfo, this._currentPickResult);\n }\n // if the two successive clicks are too far, it's just two simple clicks\n else {\n this._doubleClickOccured = false;\n this._previousStartingPointerTime = this._startingPointerTime;\n this._previousStartingPointerPosition.x = this._startingPointerPosition.x;\n this._previousStartingPointerPosition.y = this._startingPointerPosition.y;\n this._previousButtonPressed = btn;\n if (InputManager.ExclusiveDoubleClickMode) {\n // If we have a delayed click, we need to cancel it\n if (this._delayedClicks[btn]) {\n clearTimeout((_b = this._delayedClicks[btn]) === null || _b === void 0 ? void 0 : _b.timeoutId);\n this._delayedClicks[btn] = null;\n }\n cb(clickInfo, this._previousPickResult);\n }\n else {\n cb(clickInfo, this._currentPickResult);\n }\n }\n needToIgnoreNext = true;\n }\n // just the first click of the double has been raised\n else {\n this._doubleClickOccured = false;\n this._previousStartingPointerTime = this._startingPointerTime;\n this._previousStartingPointerPosition.x = this._startingPointerPosition.x;\n this._previousStartingPointerPosition.y = this._startingPointerPosition.y;\n this._previousButtonPressed = btn;\n }\n }\n }\n }\n // Even if ExclusiveDoubleClickMode is true, we need to always handle\n // up events at time of execution, unless we're explicitly ignoring them.\n if (!needToIgnoreNext) {\n cb(clickInfo, this._currentPickResult);\n }\n };\n this._onPointerMove = (evt) => {\n this._updatePointerPosition(evt);\n // Check if pointer leaves DragMovementThreshold range to determine if swipe is occurring\n if (!this._isSwiping && this._swipeButtonPressed !== -1) {\n this._isSwiping =\n Math.abs(this._startingPointerPosition.x - this._pointerX) > InputManager.DragMovementThreshold ||\n Math.abs(this._startingPointerPosition.y - this._pointerY) > InputManager.DragMovementThreshold;\n }\n // Because there's a race condition between pointermove and pointerlockchange events, we need to\n // verify that the pointer is still locked after each pointermove event.\n if (engine.isPointerLock) {\n engine._verifyPointerLock();\n }\n // PreObservable support\n if (this._checkPrePointerObservable(null, evt, evt.inputIndex >= PointerInput.MouseWheelX && evt.inputIndex <= PointerInput.MouseWheelZ ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE)) {\n return;\n }\n if (!scene.cameraToUseForPointers && !scene.activeCamera) {\n return;\n }\n if (scene.skipPointerMovePicking) {\n this._processPointerMove(new PickingInfo(), evt);\n return;\n }\n if (!scene.pointerMovePredicate) {\n scene.pointerMovePredicate = (mesh) => mesh.isPickable &&\n mesh.isVisible &&\n mesh.isReady() &&\n mesh.isEnabled() &&\n (mesh.enablePointerMoveEvents || scene.constantlyUpdateMeshUnderPointer || mesh._getActionManagerForTrigger() !== null) &&\n (!scene.cameraToUseForPointers || (scene.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0);\n }\n const pickResult = scene._registeredActions > 0 || scene.constantlyUpdateMeshUnderPointer ? this._pickMove(evt) : null;\n this._processPointerMove(pickResult, evt);\n };\n this._onPointerDown = (evt) => {\n var _a;\n this._totalPointersPressed++;\n this._pickedDownMesh = null;\n this._meshPickProceed = false;\n // If ExclusiveDoubleClickMode is true, we need to resolve any pending delayed clicks\n if (InputManager.ExclusiveDoubleClickMode) {\n for (let i = 0; i < this._delayedClicks.length; i++) {\n if (this._delayedClicks[i]) {\n // If the button that was pressed is the same as the one that was released,\n // just clear the timer. This will be resolved in the up event.\n if (evt.button === i) {\n clearTimeout((_a = this._delayedClicks[i]) === null || _a === void 0 ? void 0 : _a.timeoutId);\n }\n else {\n // Otherwise, we need to resolve the click\n const clickInfo = this._delayedClicks[i].clickInfo;\n this._doubleClickOccured = false;\n clickInfo.singleClick = true;\n clickInfo.ignore = false;\n const prevEvt = this._delayedClicks[i].evt;\n const type = PointerEventTypes.POINTERTAP;\n const pi = new PointerInfo(type, prevEvt, this._currentPickResult);\n if (scene.onPointerObservable.hasObservers() && scene.onPointerObservable.hasSpecificMask(type)) {\n scene.onPointerObservable.notifyObservers(pi, type);\n }\n // Clear the delayed click\n this._delayedClicks[i] = null;\n }\n }\n }\n }\n this._updatePointerPosition(evt);\n if (this._swipeButtonPressed === -1) {\n this._swipeButtonPressed = evt.button;\n }\n if (scene.preventDefaultOnPointerDown && elementToAttachTo) {\n evt.preventDefault();\n elementToAttachTo.focus();\n }\n this._startingPointerPosition.x = this._pointerX;\n this._startingPointerPosition.y = this._pointerY;\n this._startingPointerTime = Date.now();\n // PreObservable support\n if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERDOWN)) {\n return;\n }\n if (!scene.cameraToUseForPointers && !scene.activeCamera) {\n return;\n }\n this._pointerCaptures[evt.pointerId] = true;\n if (!scene.pointerDownPredicate) {\n scene.pointerDownPredicate = (mesh) => {\n return (mesh.isPickable &&\n mesh.isVisible &&\n mesh.isReady() &&\n mesh.isEnabled() &&\n (!scene.cameraToUseForPointers || (scene.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0));\n };\n }\n // Meshes\n this._pickedDownMesh = null;\n let pickResult;\n if (scene.skipPointerDownPicking || (scene._registeredActions === 0 && !this._checkForPicking() && !scene.onPointerDown)) {\n pickResult = new PickingInfo();\n }\n else {\n pickResult = scene.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, scene.pointerDownPredicate, scene.pointerDownFastCheck, scene.cameraToUseForPointers);\n }\n this._processPointerDown(pickResult, evt);\n };\n this._onPointerUp = (evt) => {\n if (this._totalPointersPressed === 0) {\n // We are attaching the pointer up to windows because of a bug in FF\n return; // So we need to test it the pointer down was pressed before.\n }\n this._totalPointersPressed--;\n this._pickedUpMesh = null;\n this._meshPickProceed = false;\n this._updatePointerPosition(evt);\n if (scene.preventDefaultOnPointerUp && elementToAttachTo) {\n evt.preventDefault();\n elementToAttachTo.focus();\n }\n this._initClickEvent(scene.onPrePointerObservable, scene.onPointerObservable, evt, (clickInfo, pickResult) => {\n // PreObservable support\n if (scene.onPrePointerObservable.hasObservers()) {\n this._skipPointerTap = false;\n if (!clickInfo.ignore) {\n if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERUP)) {\n // If we're skipping the next observable, we need to reset the swipe state before returning\n if (this._swipeButtonPressed === evt.button) {\n this._isSwiping = false;\n this._swipeButtonPressed = -1;\n }\n return;\n }\n if (!clickInfo.hasSwiped) {\n if (clickInfo.singleClick && scene.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {\n if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERTAP)) {\n this._skipPointerTap = true;\n }\n }\n if (clickInfo.doubleClick && scene.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {\n if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERDOUBLETAP)) {\n this._skipPointerTap = true;\n }\n }\n }\n }\n }\n // There should be a pointer captured at this point so if there isn't we should reset and return\n if (!this._pointerCaptures[evt.pointerId]) {\n if (this._swipeButtonPressed === evt.button) {\n this._isSwiping = false;\n this._swipeButtonPressed = -1;\n }\n return;\n }\n // Only release capture if all buttons are released\n if (evt.buttons === 0) {\n this._pointerCaptures[evt.pointerId] = false;\n }\n if (!scene.cameraToUseForPointers && !scene.activeCamera) {\n return;\n }\n if (!scene.pointerUpPredicate) {\n scene.pointerUpPredicate = (mesh) => {\n return (mesh.isPickable &&\n mesh.isVisible &&\n mesh.isReady() &&\n mesh.isEnabled() &&\n (!scene.cameraToUseForPointers || (scene.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0));\n };\n }\n // Meshes\n if (!this._meshPickProceed && ((AbstractActionManager && AbstractActionManager.HasTriggers) || this._checkForPicking() || scene.onPointerUp)) {\n this._initActionManager(null, clickInfo);\n }\n if (!pickResult) {\n pickResult = this._currentPickResult;\n }\n this._processPointerUp(pickResult, evt, clickInfo);\n this._previousPickResult = this._currentPickResult;\n if (this._swipeButtonPressed === evt.button) {\n this._isSwiping = false;\n this._swipeButtonPressed = -1;\n }\n });\n };\n this._onKeyDown = (evt) => {\n const type = KeyboardEventTypes.KEYDOWN;\n if (scene.onPreKeyboardObservable.hasObservers()) {\n const pi = new KeyboardInfoPre(type, evt);\n scene.onPreKeyboardObservable.notifyObservers(pi, type);\n if (pi.skipOnKeyboardObservable) {\n return;\n }\n }\n if (scene.onKeyboardObservable.hasObservers()) {\n const pi = new KeyboardInfo(type, evt);\n scene.onKeyboardObservable.notifyObservers(pi, type);\n }\n if (scene.actionManager) {\n scene.actionManager.processTrigger(14, ActionEvent.CreateNewFromScene(scene, evt));\n }\n };\n this._onKeyUp = (evt) => {\n const type = KeyboardEventTypes.KEYUP;\n if (scene.onPreKeyboardObservable.hasObservers()) {\n const pi = new KeyboardInfoPre(type, evt);\n scene.onPreKeyboardObservable.notifyObservers(pi, type);\n if (pi.skipOnKeyboardObservable) {\n return;\n }\n }\n if (scene.onKeyboardObservable.hasObservers()) {\n const pi = new KeyboardInfo(type, evt);\n scene.onKeyboardObservable.notifyObservers(pi, type);\n }\n if (scene.actionManager) {\n scene.actionManager.processTrigger(15, ActionEvent.CreateNewFromScene(scene, evt));\n }\n };\n // If a device connects that we can handle, wire up the observable\n this._deviceSourceManager.onDeviceConnectedObservable.add((deviceSource) => {\n if (deviceSource.deviceType === DeviceType.Mouse) {\n deviceSource.onInputChangedObservable.add((eventData) => {\n if (eventData.inputIndex === PointerInput.LeftClick ||\n eventData.inputIndex === PointerInput.MiddleClick ||\n eventData.inputIndex === PointerInput.RightClick ||\n eventData.inputIndex === PointerInput.BrowserBack ||\n eventData.inputIndex === PointerInput.BrowserForward) {\n if (attachDown && deviceSource.getInput(eventData.inputIndex) === 1) {\n this._onPointerDown(eventData);\n }\n else if (attachUp && deviceSource.getInput(eventData.inputIndex) === 0) {\n this._onPointerUp(eventData);\n }\n }\n else if (attachMove) {\n if (eventData.inputIndex === PointerInput.Move) {\n this._onPointerMove(eventData);\n }\n else if (eventData.inputIndex === PointerInput.MouseWheelX ||\n eventData.inputIndex === PointerInput.MouseWheelY ||\n eventData.inputIndex === PointerInput.MouseWheelZ) {\n this._onPointerMove(eventData);\n }\n }\n });\n }\n else if (deviceSource.deviceType === DeviceType.Touch) {\n deviceSource.onInputChangedObservable.add((eventData) => {\n if (eventData.inputIndex === PointerInput.LeftClick) {\n if (attachDown && deviceSource.getInput(eventData.inputIndex) === 1) {\n this._onPointerDown(eventData);\n if (this._totalPointersPressed > 1) {\n this._isMultiTouchGesture = true;\n }\n }\n else if (attachUp && deviceSource.getInput(eventData.inputIndex) === 0) {\n this._onPointerUp(eventData);\n if (this._totalPointersPressed === 0) {\n this._isMultiTouchGesture = false;\n }\n }\n }\n if (attachMove && eventData.inputIndex === PointerInput.Move) {\n this._onPointerMove(eventData);\n }\n });\n }\n else if (deviceSource.deviceType === DeviceType.Keyboard) {\n deviceSource.onInputChangedObservable.add((eventData) => {\n if (eventData.type === \"keydown\") {\n this._onKeyDown(eventData);\n }\n else if (eventData.type === \"keyup\") {\n this._onKeyUp(eventData);\n }\n });\n }\n });\n this._alreadyAttached = true;\n }\n /**\n * Detaches all event handlers\n */\n detachControl() {\n if (this._alreadyAttached) {\n this._deviceSourceManager.dispose();\n this._deviceSourceManager = null;\n // Cursor\n if (this._alreadyAttachedTo && !this._scene.doNotHandleCursors) {\n this._alreadyAttachedTo.style.cursor = this._scene.defaultCursor;\n }\n this._alreadyAttached = false;\n this._alreadyAttachedTo = null;\n }\n }\n /**\n * Force the value of meshUnderPointer\n * @param mesh - defines the mesh to use\n * @param pointerId - optional pointer id when using more than one pointer. Defaults to 0\n * @param pickResult - optional pickingInfo data used to find mesh\n * @param evt - optional pointer event\n */\n setPointerOverMesh(mesh, pointerId = 0, pickResult, evt) {\n if (this._meshUnderPointerId[pointerId] === mesh && (!mesh || !mesh._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting)) {\n return;\n }\n const underPointerMesh = this._meshUnderPointerId[pointerId];\n let actionManager;\n if (underPointerMesh) {\n actionManager = underPointerMesh._getActionManagerForTrigger(10);\n if (actionManager) {\n actionManager.processTrigger(10, ActionEvent.CreateNew(underPointerMesh, evt, { pointerId }));\n }\n }\n if (mesh) {\n this._meshUnderPointerId[pointerId] = mesh;\n this._pointerOverMesh = mesh;\n actionManager = mesh._getActionManagerForTrigger(9);\n if (actionManager) {\n actionManager.processTrigger(9, ActionEvent.CreateNew(mesh, evt, { pointerId, pickResult }));\n }\n }\n else {\n delete this._meshUnderPointerId[pointerId];\n this._pointerOverMesh = null;\n }\n }\n /**\n * Gets the mesh under the pointer\n * @returns a Mesh or null if no mesh is under the pointer\n */\n getPointerOverMesh() {\n return this.meshUnderPointer;\n }\n /**\n * @param mesh - Mesh to invalidate\n * @internal\n */\n _invalidateMesh(mesh) {\n if (this._pointerOverMesh === mesh) {\n this._pointerOverMesh = null;\n }\n if (this._pickedDownMesh === mesh) {\n this._pickedDownMesh = null;\n }\n if (this._pickedUpMesh === mesh) {\n this._pickedUpMesh = null;\n }\n for (const pointerId in this._meshUnderPointerId) {\n if (this._meshUnderPointerId[pointerId] === mesh) {\n delete this._meshUnderPointerId[pointerId];\n }\n }\n }\n}\n/** The distance in pixel that you have to move to prevent some events */\nInputManager.DragMovementThreshold = 10; // in pixels\n/** Time in milliseconds to wait to raise long press events if button is still pressed */\nInputManager.LongPressDelay = 500; // in milliseconds\n/** Time in milliseconds with two consecutive clicks will be considered as a double click */\nInputManager.DoubleClickDelay = 300; // in milliseconds\n/**\n * This flag will modify the behavior so that, when true, a click will happen if and only if\n * another click DOES NOT happen within the DoubleClickDelay time frame. If another click does\n * happen within that time frame, the first click will not fire an event and and a double click will occur.\n */\nInputManager.ExclusiveDoubleClickMode = false;\n//# sourceMappingURL=scene.inputManager.js.map","/** Defines the cross module constantsused by lights to avoid circular dependencies */\nexport class LightConstants {\n /**\n * Sort function to order lights for rendering.\n * @param a First Light object to compare to second.\n * @param b Second Light object to compare first.\n * @returns -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.\n */\n static CompareLightsPriority(a, b) {\n //shadow-casting lights have priority over non-shadow-casting lights\n //the renderPriority is a secondary sort criterion\n if (a.shadowEnabled !== b.shadowEnabled) {\n return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);\n }\n return b.renderPriority - a.renderPriority;\n }\n}\n/**\n * Falloff Default: light is falling off following the material specification:\n * standard material is using standard falloff whereas pbr material can request special falloff per materials.\n */\nLightConstants.FALLOFF_DEFAULT = 0;\n/**\n * Falloff Physical: light is falling off following the inverse squared distance law.\n */\nLightConstants.FALLOFF_PHYSICAL = 1;\n/**\n * Falloff gltf: light is falling off as described in the gltf moving to PBR document\n * to enhance interoperability with other engines.\n */\nLightConstants.FALLOFF_GLTF = 2;\n/**\n * Falloff Standard: light is falling off like in the standard material\n * to enhance interoperability with other materials.\n */\nLightConstants.FALLOFF_STANDARD = 3;\n//lightmapMode Consts\n/**\n * If every light affecting the material is in this lightmapMode,\n * material.lightmapTexture adds or multiplies\n * (depends on material.useLightmapAsShadowmap)\n * after every other light calculations.\n */\nLightConstants.LIGHTMAP_DEFAULT = 0;\n/**\n * material.lightmapTexture as only diffuse lighting from this light\n * adds only specular lighting from this light\n * adds dynamic shadows\n */\nLightConstants.LIGHTMAP_SPECULAR = 1;\n/**\n * material.lightmapTexture as only lighting\n * no light calculation from this light\n * only adds dynamic shadows from this light\n */\nLightConstants.LIGHTMAP_SHADOWSONLY = 2;\n// Intensity Mode Consts\n/**\n * Each light type uses the default quantity according to its type:\n * point/spot lights use luminous intensity\n * directional lights use illuminance\n */\nLightConstants.INTENSITYMODE_AUTOMATIC = 0;\n/**\n * lumen (lm)\n */\nLightConstants.INTENSITYMODE_LUMINOUSPOWER = 1;\n/**\n * candela (lm/sr)\n */\nLightConstants.INTENSITYMODE_LUMINOUSINTENSITY = 2;\n/**\n * lux (lm/m^2)\n */\nLightConstants.INTENSITYMODE_ILLUMINANCE = 3;\n/**\n * nit (cd/m^2)\n */\nLightConstants.INTENSITYMODE_LUMINANCE = 4;\n// Light types ids const.\n/**\n * Light type const id of the point light.\n */\nLightConstants.LIGHTTYPEID_POINTLIGHT = 0;\n/**\n * Light type const id of the directional light.\n */\nLightConstants.LIGHTTYPEID_DIRECTIONALLIGHT = 1;\n/**\n * Light type const id of the spot light.\n */\nLightConstants.LIGHTTYPEID_SPOTLIGHT = 2;\n/**\n * Light type const id of the hemispheric light.\n */\nLightConstants.LIGHTTYPEID_HEMISPHERICLIGHT = 3;\n//# sourceMappingURL=lightConstants.js.map","\n/**\n * Class used to represent data loading progression\n */\nexport class SceneLoaderFlags {\n /**\n * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data\n */\n static get ForceFullSceneLoadingForIncremental() {\n return SceneLoaderFlags._ForceFullSceneLoadingForIncremental;\n }\n static set ForceFullSceneLoadingForIncremental(value) {\n SceneLoaderFlags._ForceFullSceneLoadingForIncremental = value;\n }\n /**\n * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene\n */\n static get ShowLoadingScreen() {\n return SceneLoaderFlags._ShowLoadingScreen;\n }\n static set ShowLoadingScreen(value) {\n SceneLoaderFlags._ShowLoadingScreen = value;\n }\n /**\n * Defines the current logging level (while loading the scene)\n * @ignorenaming\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static get loggingLevel() {\n return SceneLoaderFlags._LoggingLevel;\n }\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static set loggingLevel(value) {\n SceneLoaderFlags._LoggingLevel = value;\n }\n /**\n * Gets or set a boolean indicating if matrix weights must be cleaned upon loading\n */\n static get CleanBoneMatrixWeights() {\n return SceneLoaderFlags._CleanBoneMatrixWeights;\n }\n static set CleanBoneMatrixWeights(value) {\n SceneLoaderFlags._CleanBoneMatrixWeights = value;\n }\n}\n// Flags\nSceneLoaderFlags._ForceFullSceneLoadingForIncremental = false;\nSceneLoaderFlags._ShowLoadingScreen = true;\nSceneLoaderFlags._CleanBoneMatrixWeights = false;\nSceneLoaderFlags._LoggingLevel = 0;\n//# sourceMappingURL=sceneLoaderFlags.js.map","import { Observable } from \"../../Misc/observable.js\";\nimport { TextureSampler } from \"./textureSampler.js\";\n/**\n * Defines the source of the internal texture\n */\nexport var InternalTextureSource;\n(function (InternalTextureSource) {\n /**\n * The source of the texture data is unknown\n */\n InternalTextureSource[InternalTextureSource[\"Unknown\"] = 0] = \"Unknown\";\n /**\n * Texture data comes from an URL\n */\n InternalTextureSource[InternalTextureSource[\"Url\"] = 1] = \"Url\";\n /**\n * Texture data is only used for temporary storage\n */\n InternalTextureSource[InternalTextureSource[\"Temp\"] = 2] = \"Temp\";\n /**\n * Texture data comes from raw data (ArrayBuffer)\n */\n InternalTextureSource[InternalTextureSource[\"Raw\"] = 3] = \"Raw\";\n /**\n * Texture content is dynamic (video or dynamic texture)\n */\n InternalTextureSource[InternalTextureSource[\"Dynamic\"] = 4] = \"Dynamic\";\n /**\n * Texture content is generated by rendering to it\n */\n InternalTextureSource[InternalTextureSource[\"RenderTarget\"] = 5] = \"RenderTarget\";\n /**\n * Texture content is part of a multi render target process\n */\n InternalTextureSource[InternalTextureSource[\"MultiRenderTarget\"] = 6] = \"MultiRenderTarget\";\n /**\n * Texture data comes from a cube data file\n */\n InternalTextureSource[InternalTextureSource[\"Cube\"] = 7] = \"Cube\";\n /**\n * Texture data comes from a raw cube data\n */\n InternalTextureSource[InternalTextureSource[\"CubeRaw\"] = 8] = \"CubeRaw\";\n /**\n * Texture data come from a prefiltered cube data file\n */\n InternalTextureSource[InternalTextureSource[\"CubePrefiltered\"] = 9] = \"CubePrefiltered\";\n /**\n * Texture content is raw 3D data\n */\n InternalTextureSource[InternalTextureSource[\"Raw3D\"] = 10] = \"Raw3D\";\n /**\n * Texture content is raw 2D array data\n */\n InternalTextureSource[InternalTextureSource[\"Raw2DArray\"] = 11] = \"Raw2DArray\";\n /**\n * Texture content is a depth/stencil texture\n */\n InternalTextureSource[InternalTextureSource[\"DepthStencil\"] = 12] = \"DepthStencil\";\n /**\n * Texture data comes from a raw cube data encoded with RGBD\n */\n InternalTextureSource[InternalTextureSource[\"CubeRawRGBD\"] = 13] = \"CubeRawRGBD\";\n /**\n * Texture content is a depth texture\n */\n InternalTextureSource[InternalTextureSource[\"Depth\"] = 14] = \"Depth\";\n})(InternalTextureSource || (InternalTextureSource = {}));\n/**\n * Class used to store data associated with WebGL texture data for the engine\n * This class should not be used directly\n */\nexport class InternalTexture extends TextureSampler {\n /**\n * Gets a boolean indicating if the texture uses mipmaps\n * TODO implements useMipMaps as a separate setting from generateMipMaps\n */\n get useMipMaps() {\n return this.generateMipMaps;\n }\n set useMipMaps(value) {\n this.generateMipMaps = value;\n }\n /** Gets the unique id of the internal texture */\n get uniqueId() {\n return this._uniqueId;\n }\n /** @internal */\n _setUniqueId(id) {\n this._uniqueId = id;\n }\n /**\n * Gets the Engine the texture belongs to.\n * @returns The babylon engine\n */\n getEngine() {\n return this._engine;\n }\n /**\n * Gets the data source type of the texture\n */\n get source() {\n return this._source;\n }\n /**\n * Creates a new InternalTexture\n * @param engine defines the engine to use\n * @param source defines the type of data that will be used\n * @param delayAllocation if the texture allocation should be delayed (default: false)\n */\n constructor(engine, source, delayAllocation = false) {\n super();\n /**\n * Defines if the texture is ready\n */\n this.isReady = false;\n /**\n * Defines if the texture is a cube texture\n */\n this.isCube = false;\n /**\n * Defines if the texture contains 3D data\n */\n this.is3D = false;\n /**\n * Defines if the texture contains 2D array data\n */\n this.is2DArray = false;\n /**\n * Defines if the texture contains multiview data\n */\n this.isMultiview = false;\n /**\n * Gets the URL used to load this texture\n */\n this.url = \"\";\n /**\n * Gets a boolean indicating if the texture needs mipmaps generation\n */\n this.generateMipMaps = false;\n /**\n * Gets the number of samples used by the texture (WebGL2+ only)\n */\n this.samples = 0;\n /**\n * Gets the type of the texture (int, float...)\n */\n this.type = -1;\n /**\n * Gets the format of the texture (RGB, RGBA...)\n */\n this.format = -1;\n /**\n * Observable called when the texture is loaded\n */\n this.onLoadedObservable = new Observable();\n /**\n * Observable called when the texture load is raising an error\n */\n this.onErrorObservable = new Observable();\n /**\n * If this callback is defined it will be called instead of the default _rebuild function\n */\n this.onRebuildCallback = null;\n /**\n * Gets the width of the texture\n */\n this.width = 0;\n /**\n * Gets the height of the texture\n */\n this.height = 0;\n /**\n * Gets the depth of the texture\n */\n this.depth = 0;\n /**\n * Gets the initial width of the texture (It could be rescaled if the current system does not support non power of two textures)\n */\n this.baseWidth = 0;\n /**\n * Gets the initial height of the texture (It could be rescaled if the current system does not support non power of two textures)\n */\n this.baseHeight = 0;\n /**\n * Gets the initial depth of the texture (It could be rescaled if the current system does not support non power of two textures)\n */\n this.baseDepth = 0;\n /**\n * Gets a boolean indicating if the texture is inverted on Y axis\n */\n this.invertY = false;\n // Private\n /** @internal */\n this._invertVScale = false;\n /** @internal */\n this._associatedChannel = -1;\n /** @internal */\n this._source = InternalTextureSource.Unknown;\n /** @internal */\n this._buffer = null;\n /** @internal */\n this._bufferView = null;\n /** @internal */\n this._bufferViewArray = null;\n /** @internal */\n this._bufferViewArrayArray = null;\n /** @internal */\n this._size = 0;\n /** @internal */\n this._extension = \"\";\n /** @internal */\n this._files = null;\n /** @internal */\n this._workingCanvas = null;\n /** @internal */\n this._workingContext = null;\n /** @internal */\n this._cachedCoordinatesMode = null;\n /** @internal */\n this._isDisabled = false;\n /** @internal */\n this._compression = null;\n /** @internal */\n this._sphericalPolynomial = null;\n /** @internal */\n this._sphericalPolynomialPromise = null;\n /** @internal */\n this._sphericalPolynomialComputed = false;\n /** @internal */\n this._lodGenerationScale = 0;\n /** @internal */\n this._lodGenerationOffset = 0;\n /** @internal */\n this._useSRGBBuffer = false;\n // The following three fields helps sharing generated fixed LODs for texture filtering\n // In environment not supporting the textureLOD extension like EDGE. They are for internal use only.\n // They are at the level of the gl texture to benefit from the cache.\n /** @internal */\n this._lodTextureHigh = null;\n /** @internal */\n this._lodTextureMid = null;\n /** @internal */\n this._lodTextureLow = null;\n /** @internal */\n this._isRGBD = false;\n /** @internal */\n this._linearSpecularLOD = false;\n /** @internal */\n this._irradianceTexture = null;\n /** @internal */\n this._hardwareTexture = null;\n /** @internal */\n this._maxLodLevel = null;\n /** @internal */\n this._references = 1;\n /** @internal */\n this._gammaSpace = null;\n this._engine = engine;\n this._source = source;\n this._uniqueId = InternalTexture._Counter++;\n if (!delayAllocation) {\n this._hardwareTexture = engine._createHardwareTexture();\n }\n }\n /**\n * Increments the number of references (ie. the number of Texture that point to it)\n */\n incrementReferences() {\n this._references++;\n }\n /**\n * Change the size of the texture (not the size of the content)\n * @param width defines the new width\n * @param height defines the new height\n * @param depth defines the new depth (1 by default)\n */\n updateSize(width, height, depth = 1) {\n this._engine.updateTextureDimensions(this, width, height, depth);\n this.width = width;\n this.height = height;\n this.depth = depth;\n this.baseWidth = width;\n this.baseHeight = height;\n this.baseDepth = depth;\n this._size = width * height * depth;\n }\n /** @internal */\n _rebuild() {\n var _a;\n this.isReady = false;\n this._cachedCoordinatesMode = null;\n this._cachedWrapU = null;\n this._cachedWrapV = null;\n this._cachedWrapR = null;\n this._cachedAnisotropicFilteringLevel = null;\n if (this.onRebuildCallback) {\n const data = this.onRebuildCallback(this);\n const swapAndSetIsReady = (proxyInternalTexture) => {\n proxyInternalTexture._swapAndDie(this, false);\n this.isReady = data.isReady;\n };\n if (data.isAsync) {\n data.proxy.then(swapAndSetIsReady);\n }\n else {\n swapAndSetIsReady(data.proxy);\n }\n return;\n }\n let proxy;\n switch (this.source) {\n case InternalTextureSource.Temp:\n break;\n case InternalTextureSource.Url:\n proxy = this._engine.createTexture((_a = this._originalUrl) !== null && _a !== void 0 ? _a : this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, \n // Do not use Proxy here as it could be fully synchronous\n // and proxy would be undefined.\n (temp) => {\n temp._swapAndDie(this, false);\n this.isReady = true;\n }, null, this._buffer, undefined, this.format, this._extension, undefined, undefined, undefined, this._useSRGBBuffer);\n return;\n case InternalTextureSource.Raw:\n proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type, undefined, this._useSRGBBuffer);\n proxy._swapAndDie(this, false);\n this.isReady = true;\n break;\n case InternalTextureSource.Raw3D:\n proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type);\n proxy._swapAndDie(this, false);\n this.isReady = true;\n break;\n case InternalTextureSource.Raw2DArray:\n proxy = this._engine.createRawTexture2DArray(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type);\n proxy._swapAndDie(this, false);\n this.isReady = true;\n break;\n case InternalTextureSource.Dynamic:\n proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);\n proxy._swapAndDie(this, false);\n this._engine.updateDynamicTexture(this, this._engine.getRenderingCanvas(), this.invertY, undefined, undefined, true);\n // The engine will make sure to update content so no need to flag it as isReady = true\n break;\n case InternalTextureSource.Cube:\n proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, () => {\n proxy._swapAndDie(this, false);\n this.isReady = true;\n }, null, this.format, this._extension, false, 0, 0, null, undefined, this._useSRGBBuffer);\n return;\n case InternalTextureSource.CubeRaw:\n proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);\n proxy._swapAndDie(this, false);\n this.isReady = true;\n break;\n case InternalTextureSource.CubeRawRGBD:\n // This case is being handeled by the environment texture tools and is not a part of the rebuild process.\n // To use CubeRawRGBD use updateRGBDAsync on the cube texture.\n return;\n case InternalTextureSource.CubePrefiltered:\n proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, (proxy) => {\n if (proxy) {\n proxy._swapAndDie(this, false);\n }\n this.isReady = true;\n }, null, this.format, this._extension);\n proxy._sphericalPolynomial = this._sphericalPolynomial;\n return;\n }\n }\n /**\n * @internal\n */\n _swapAndDie(target, swapAll = true) {\n // TODO what about refcount on target?\n var _a;\n (_a = this._hardwareTexture) === null || _a === void 0 ? void 0 : _a.setUsage(target._source, this.generateMipMaps, this.isCube, this.width, this.height);\n target._hardwareTexture = this._hardwareTexture;\n if (swapAll) {\n target._isRGBD = this._isRGBD;\n }\n if (this._lodTextureHigh) {\n if (target._lodTextureHigh) {\n target._lodTextureHigh.dispose();\n }\n target._lodTextureHigh = this._lodTextureHigh;\n }\n if (this._lodTextureMid) {\n if (target._lodTextureMid) {\n target._lodTextureMid.dispose();\n }\n target._lodTextureMid = this._lodTextureMid;\n }\n if (this._lodTextureLow) {\n if (target._lodTextureLow) {\n target._lodTextureLow.dispose();\n }\n target._lodTextureLow = this._lodTextureLow;\n }\n if (this._irradianceTexture) {\n if (target._irradianceTexture) {\n target._irradianceTexture.dispose();\n }\n target._irradianceTexture = this._irradianceTexture;\n }\n const cache = this._engine.getLoadedTexturesCache();\n let index = cache.indexOf(this);\n if (index !== -1) {\n cache.splice(index, 1);\n }\n index = cache.indexOf(target);\n if (index === -1) {\n cache.push(target);\n }\n }\n /**\n * Dispose the current allocated resources\n */\n dispose() {\n this._references--;\n this.onLoadedObservable.clear();\n this.onErrorObservable.clear();\n if (this._references === 0) {\n this._engine._releaseTexture(this);\n this._hardwareTexture = null;\n }\n }\n}\n/** @internal */\nInternalTexture._Counter = 0;\n//# sourceMappingURL=internalTexture.js.map","\n/**\n * Class used to store a texture sampler data\n */\nexport class TextureSampler {\n /**\n * | Value | Type | Description |\n * | ----- | ------------------ | ----------- |\n * | 0 | CLAMP_ADDRESSMODE | |\n * | 1 | WRAP_ADDRESSMODE | |\n * | 2 | MIRROR_ADDRESSMODE | |\n */\n get wrapU() {\n return this._cachedWrapU;\n }\n set wrapU(value) {\n this._cachedWrapU = value;\n }\n /**\n * | Value | Type | Description |\n * | ----- | ------------------ | ----------- |\n * | 0 | CLAMP_ADDRESSMODE | |\n * | 1 | WRAP_ADDRESSMODE | |\n * | 2 | MIRROR_ADDRESSMODE | |\n */\n get wrapV() {\n return this._cachedWrapV;\n }\n set wrapV(value) {\n this._cachedWrapV = value;\n }\n /**\n * | Value | Type | Description |\n * | ----- | ------------------ | ----------- |\n * | 0 | CLAMP_ADDRESSMODE | |\n * | 1 | WRAP_ADDRESSMODE | |\n * | 2 | MIRROR_ADDRESSMODE | |\n */\n get wrapR() {\n return this._cachedWrapR;\n }\n set wrapR(value) {\n this._cachedWrapR = value;\n }\n /**\n * With compliant hardware and browser (supporting anisotropic filtering)\n * this defines the level of anisotropic filtering in the texture.\n * The higher the better but the slower.\n */\n get anisotropicFilteringLevel() {\n return this._cachedAnisotropicFilteringLevel;\n }\n set anisotropicFilteringLevel(value) {\n this._cachedAnisotropicFilteringLevel = value;\n }\n /**\n * Gets or sets the comparison function (513, 514, etc). Set 0 to not use a comparison function\n */\n get comparisonFunction() {\n return this._comparisonFunction;\n }\n set comparisonFunction(value) {\n this._comparisonFunction = value;\n }\n /**\n * Indicates to use the mip maps (if available on the texture).\n * Thanks to this flag, you can instruct the sampler to not sample the mipmaps even if they exist (and if the sampling mode is set to a value that normally samples the mipmaps!)\n */\n get useMipMaps() {\n return this._useMipMaps;\n }\n set useMipMaps(value) {\n this._useMipMaps = value;\n }\n /**\n * Creates a Sampler instance\n */\n constructor() {\n /**\n * Gets the sampling mode of the texture\n */\n this.samplingMode = -1;\n this._useMipMaps = true;\n /** @internal */\n this._cachedWrapU = null;\n /** @internal */\n this._cachedWrapV = null;\n /** @internal */\n this._cachedWrapR = null;\n /** @internal */\n this._cachedAnisotropicFilteringLevel = null;\n /** @internal */\n this._comparisonFunction = 0;\n }\n /**\n * Sets all the parameters of the sampler\n * @param wrapU u address mode (default: TEXTURE_WRAP_ADDRESSMODE)\n * @param wrapV v address mode (default: TEXTURE_WRAP_ADDRESSMODE)\n * @param wrapR r address mode (default: TEXTURE_WRAP_ADDRESSMODE)\n * @param anisotropicFilteringLevel anisotropic level (default: 1)\n * @param samplingMode sampling mode (default: 2)\n * @param comparisonFunction comparison function (default: 0 - no comparison function)\n * @returns the current sampler instance\n */\n setParameters(wrapU = 1, wrapV = 1, wrapR = 1, anisotropicFilteringLevel = 1, samplingMode = 2, comparisonFunction = 0) {\n this._cachedWrapU = wrapU;\n this._cachedWrapV = wrapV;\n this._cachedWrapR = wrapR;\n this._cachedAnisotropicFilteringLevel = anisotropicFilteringLevel;\n this.samplingMode = samplingMode;\n this._comparisonFunction = comparisonFunction;\n return this;\n }\n /**\n * Compares this sampler with another one\n * @param other sampler to compare with\n * @returns true if the samplers have the same parametres, else false\n */\n compareSampler(other) {\n return (this._cachedWrapU === other._cachedWrapU &&\n this._cachedWrapV === other._cachedWrapV &&\n this._cachedWrapR === other._cachedWrapR &&\n this._cachedAnisotropicFilteringLevel === other._cachedAnisotropicFilteringLevel &&\n this.samplingMode === other.samplingMode &&\n this._comparisonFunction === other._comparisonFunction &&\n this._useMipMaps === other._useMipMaps);\n }\n}\n//# sourceMappingURL=textureSampler.js.map","/** @internal */\nexport function addClipPlaneUniforms(uniforms) {\n if (uniforms.indexOf(\"vClipPlane\") === -1) {\n uniforms.push(\"vClipPlane\");\n }\n if (uniforms.indexOf(\"vClipPlane2\") === -1) {\n uniforms.push(\"vClipPlane2\");\n }\n if (uniforms.indexOf(\"vClipPlane3\") === -1) {\n uniforms.push(\"vClipPlane3\");\n }\n if (uniforms.indexOf(\"vClipPlane4\") === -1) {\n uniforms.push(\"vClipPlane4\");\n }\n if (uniforms.indexOf(\"vClipPlane5\") === -1) {\n uniforms.push(\"vClipPlane5\");\n }\n if (uniforms.indexOf(\"vClipPlane6\") === -1) {\n uniforms.push(\"vClipPlane6\");\n }\n}\n/** @internal */\nexport function prepareStringDefinesForClipPlanes(primaryHolder, secondaryHolder, defines) {\n var _a, _b, _c, _d, _e, _f;\n const clipPlane = !!((_a = primaryHolder.clipPlane) !== null && _a !== void 0 ? _a : secondaryHolder.clipPlane);\n const clipPlane2 = !!((_b = primaryHolder.clipPlane2) !== null && _b !== void 0 ? _b : secondaryHolder.clipPlane2);\n const clipPlane3 = !!((_c = primaryHolder.clipPlane3) !== null && _c !== void 0 ? _c : secondaryHolder.clipPlane3);\n const clipPlane4 = !!((_d = primaryHolder.clipPlane4) !== null && _d !== void 0 ? _d : secondaryHolder.clipPlane4);\n const clipPlane5 = !!((_e = primaryHolder.clipPlane5) !== null && _e !== void 0 ? _e : secondaryHolder.clipPlane5);\n const clipPlane6 = !!((_f = primaryHolder.clipPlane6) !== null && _f !== void 0 ? _f : secondaryHolder.clipPlane6);\n if (clipPlane)\n defines.push(\"#define CLIPPLANE\");\n if (clipPlane2)\n defines.push(\"#define CLIPPLANE2\");\n if (clipPlane3)\n defines.push(\"#define CLIPPLANE3\");\n if (clipPlane4)\n defines.push(\"#define CLIPPLANE4\");\n if (clipPlane5)\n defines.push(\"#define CLIPPLANE5\");\n if (clipPlane6)\n defines.push(\"#define CLIPPLANE6\");\n}\n/** @internal */\nexport function prepareDefinesForClipPlanes(primaryHolder, secondaryHolder, defines) {\n var _a, _b, _c, _d, _e, _f;\n let changed = false;\n const clipPlane = !!((_a = primaryHolder.clipPlane) !== null && _a !== void 0 ? _a : secondaryHolder.clipPlane);\n const clipPlane2 = !!((_b = primaryHolder.clipPlane2) !== null && _b !== void 0 ? _b : secondaryHolder.clipPlane2);\n const clipPlane3 = !!((_c = primaryHolder.clipPlane3) !== null && _c !== void 0 ? _c : secondaryHolder.clipPlane3);\n const clipPlane4 = !!((_d = primaryHolder.clipPlane4) !== null && _d !== void 0 ? _d : secondaryHolder.clipPlane4);\n const clipPlane5 = !!((_e = primaryHolder.clipPlane5) !== null && _e !== void 0 ? _e : secondaryHolder.clipPlane5);\n const clipPlane6 = !!((_f = primaryHolder.clipPlane6) !== null && _f !== void 0 ? _f : secondaryHolder.clipPlane6);\n // Do not factorize this code, it breaks browsers optimizations.\n if (defines[\"CLIPPLANE\"] !== clipPlane) {\n defines[\"CLIPPLANE\"] = clipPlane;\n changed = true;\n }\n if (defines[\"CLIPPLANE2\"] !== clipPlane2) {\n defines[\"CLIPPLANE2\"] = clipPlane2;\n changed = true;\n }\n if (defines[\"CLIPPLANE3\"] !== clipPlane3) {\n defines[\"CLIPPLANE3\"] = clipPlane3;\n changed = true;\n }\n if (defines[\"CLIPPLANE4\"] !== clipPlane4) {\n defines[\"CLIPPLANE4\"] = clipPlane4;\n changed = true;\n }\n if (defines[\"CLIPPLANE5\"] !== clipPlane5) {\n defines[\"CLIPPLANE5\"] = clipPlane5;\n changed = true;\n }\n if (defines[\"CLIPPLANE6\"] !== clipPlane6) {\n defines[\"CLIPPLANE6\"] = clipPlane6;\n changed = true;\n }\n return changed;\n}\n/** @internal */\nexport function bindClipPlane(effect, primaryHolder, secondaryHolder) {\n var _a, _b, _c, _d, _e, _f;\n let clipPlane = (_a = primaryHolder.clipPlane) !== null && _a !== void 0 ? _a : secondaryHolder.clipPlane;\n setClipPlane(effect, \"vClipPlane\", clipPlane);\n clipPlane = (_b = primaryHolder.clipPlane2) !== null && _b !== void 0 ? _b : secondaryHolder.clipPlane2;\n setClipPlane(effect, \"vClipPlane2\", clipPlane);\n clipPlane = (_c = primaryHolder.clipPlane3) !== null && _c !== void 0 ? _c : secondaryHolder.clipPlane3;\n setClipPlane(effect, \"vClipPlane3\", clipPlane);\n clipPlane = (_d = primaryHolder.clipPlane4) !== null && _d !== void 0 ? _d : secondaryHolder.clipPlane4;\n setClipPlane(effect, \"vClipPlane4\", clipPlane);\n clipPlane = (_e = primaryHolder.clipPlane5) !== null && _e !== void 0 ? _e : secondaryHolder.clipPlane5;\n setClipPlane(effect, \"vClipPlane5\", clipPlane);\n clipPlane = (_f = primaryHolder.clipPlane6) !== null && _f !== void 0 ? _f : secondaryHolder.clipPlane6;\n setClipPlane(effect, \"vClipPlane6\", clipPlane);\n}\nfunction setClipPlane(effect, uniformName, clipPlane) {\n if (clipPlane) {\n effect.setFloat4(uniformName, clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);\n }\n}\n//# sourceMappingURL=clipPlaneMaterialHelper.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { SerializationHelper, serialize } from \"../Misc/decorators.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\n/**\n * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\nexport class ColorCurves {\n constructor() {\n this._dirty = true;\n this._tempColor = new Color4(0, 0, 0, 0);\n this._globalCurve = new Color4(0, 0, 0, 0);\n this._highlightsCurve = new Color4(0, 0, 0, 0);\n this._midtonesCurve = new Color4(0, 0, 0, 0);\n this._shadowsCurve = new Color4(0, 0, 0, 0);\n this._positiveCurve = new Color4(0, 0, 0, 0);\n this._negativeCurve = new Color4(0, 0, 0, 0);\n this._globalHue = 30;\n this._globalDensity = 0;\n this._globalSaturation = 0;\n this._globalExposure = 0;\n this._highlightsHue = 30;\n this._highlightsDensity = 0;\n this._highlightsSaturation = 0;\n this._highlightsExposure = 0;\n this._midtonesHue = 30;\n this._midtonesDensity = 0;\n this._midtonesSaturation = 0;\n this._midtonesExposure = 0;\n this._shadowsHue = 30;\n this._shadowsDensity = 0;\n this._shadowsSaturation = 0;\n this._shadowsExposure = 0;\n }\n /**\n * Gets the global Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n get globalHue() {\n return this._globalHue;\n }\n /**\n * Sets the global Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n set globalHue(value) {\n this._globalHue = value;\n this._dirty = true;\n }\n /**\n * Gets the global Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n get globalDensity() {\n return this._globalDensity;\n }\n /**\n * Sets the global Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n set globalDensity(value) {\n this._globalDensity = value;\n this._dirty = true;\n }\n /**\n * Gets the global Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n get globalSaturation() {\n return this._globalSaturation;\n }\n /**\n * Sets the global Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n set globalSaturation(value) {\n this._globalSaturation = value;\n this._dirty = true;\n }\n /**\n * Gets the global Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n get globalExposure() {\n return this._globalExposure;\n }\n /**\n * Sets the global Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n set globalExposure(value) {\n this._globalExposure = value;\n this._dirty = true;\n }\n /**\n * Gets the highlights Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n get highlightsHue() {\n return this._highlightsHue;\n }\n /**\n * Sets the highlights Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n set highlightsHue(value) {\n this._highlightsHue = value;\n this._dirty = true;\n }\n /**\n * Gets the highlights Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n get highlightsDensity() {\n return this._highlightsDensity;\n }\n /**\n * Sets the highlights Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n set highlightsDensity(value) {\n this._highlightsDensity = value;\n this._dirty = true;\n }\n /**\n * Gets the highlights Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n get highlightsSaturation() {\n return this._highlightsSaturation;\n }\n /**\n * Sets the highlights Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n set highlightsSaturation(value) {\n this._highlightsSaturation = value;\n this._dirty = true;\n }\n /**\n * Gets the highlights Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n get highlightsExposure() {\n return this._highlightsExposure;\n }\n /**\n * Sets the highlights Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n set highlightsExposure(value) {\n this._highlightsExposure = value;\n this._dirty = true;\n }\n /**\n * Gets the midtones Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n get midtonesHue() {\n return this._midtonesHue;\n }\n /**\n * Sets the midtones Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n set midtonesHue(value) {\n this._midtonesHue = value;\n this._dirty = true;\n }\n /**\n * Gets the midtones Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n get midtonesDensity() {\n return this._midtonesDensity;\n }\n /**\n * Sets the midtones Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n set midtonesDensity(value) {\n this._midtonesDensity = value;\n this._dirty = true;\n }\n /**\n * Gets the midtones Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n get midtonesSaturation() {\n return this._midtonesSaturation;\n }\n /**\n * Sets the midtones Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n set midtonesSaturation(value) {\n this._midtonesSaturation = value;\n this._dirty = true;\n }\n /**\n * Gets the midtones Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n get midtonesExposure() {\n return this._midtonesExposure;\n }\n /**\n * Sets the midtones Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n set midtonesExposure(value) {\n this._midtonesExposure = value;\n this._dirty = true;\n }\n /**\n * Gets the shadows Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n get shadowsHue() {\n return this._shadowsHue;\n }\n /**\n * Sets the shadows Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n set shadowsHue(value) {\n this._shadowsHue = value;\n this._dirty = true;\n }\n /**\n * Gets the shadows Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n get shadowsDensity() {\n return this._shadowsDensity;\n }\n /**\n * Sets the shadows Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n set shadowsDensity(value) {\n this._shadowsDensity = value;\n this._dirty = true;\n }\n /**\n * Gets the shadows Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n get shadowsSaturation() {\n return this._shadowsSaturation;\n }\n /**\n * Sets the shadows Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n set shadowsSaturation(value) {\n this._shadowsSaturation = value;\n this._dirty = true;\n }\n /**\n * Gets the shadows Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n get shadowsExposure() {\n return this._shadowsExposure;\n }\n /**\n * Sets the shadows Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n set shadowsExposure(value) {\n this._shadowsExposure = value;\n this._dirty = true;\n }\n /**\n * Returns the class name\n * @returns The class name\n */\n getClassName() {\n return \"ColorCurves\";\n }\n /**\n * Binds the color curves to the shader.\n * @param colorCurves The color curve to bind\n * @param effect The effect to bind to\n * @param positiveUniform The positive uniform shader parameter\n * @param neutralUniform The neutral uniform shader parameter\n * @param negativeUniform The negative uniform shader parameter\n */\n static Bind(colorCurves, effect, positiveUniform = \"vCameraColorCurvePositive\", neutralUniform = \"vCameraColorCurveNeutral\", negativeUniform = \"vCameraColorCurveNegative\") {\n if (colorCurves._dirty) {\n colorCurves._dirty = false;\n // Fill in global info.\n colorCurves._getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);\n // Compute highlights info.\n colorCurves._getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);\n colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);\n // Compute midtones info.\n colorCurves._getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);\n colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);\n // Compute shadows info.\n colorCurves._getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);\n colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);\n // Compute deltas (neutral is midtones).\n colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);\n colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);\n }\n if (effect) {\n effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);\n effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);\n effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);\n }\n }\n /**\n * Prepare the list of uniforms associated with the ColorCurves effects.\n * @param uniformsList The list of uniforms used in the effect\n */\n static PrepareUniforms(uniformsList) {\n uniformsList.push(\"vCameraColorCurveNeutral\", \"vCameraColorCurvePositive\", \"vCameraColorCurveNegative\");\n }\n /**\n * Returns color grading data based on a hue, density, saturation and exposure value.\n * @param hue\n * @param density\n * @param saturation The saturation.\n * @param exposure The exposure.\n * @param result The result data container.\n */\n _getColorGradingDataToRef(hue, density, saturation, exposure, result) {\n if (hue == null) {\n return;\n }\n hue = ColorCurves._Clamp(hue, 0, 360);\n density = ColorCurves._Clamp(density, -100, 100);\n saturation = ColorCurves._Clamp(saturation, -100, 100);\n exposure = ColorCurves._Clamp(exposure, -100, 100);\n // Remap the slider/config filter density with non-linear mapping and also scale by half\n // so that the maximum filter density is only 50% control. This provides fine control\n // for small values and reasonable range.\n density = ColorCurves._ApplyColorGradingSliderNonlinear(density);\n density *= 0.5;\n exposure = ColorCurves._ApplyColorGradingSliderNonlinear(exposure);\n if (density < 0) {\n density *= -1;\n hue = (hue + 180) % 360;\n }\n ColorCurves._FromHSBToRef(hue, density, 50 + 0.25 * exposure, result);\n result.scaleToRef(2, result);\n result.a = 1 + 0.01 * saturation;\n }\n /**\n * Takes an input slider value and returns an adjusted value that provides extra control near the centre.\n * @param value The input slider value in range [-100,100].\n * @returns Adjusted value.\n */\n static _ApplyColorGradingSliderNonlinear(value) {\n value /= 100;\n let x = Math.abs(value);\n x = Math.pow(x, 2);\n if (value < 0) {\n x *= -1;\n }\n x *= 100;\n return x;\n }\n /**\n * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).\n * @param hue The hue (H) input.\n * @param saturation The saturation (S) input.\n * @param brightness The brightness (B) input.\n * @param result\n * @result An RGBA color represented as Vector4.\n */\n static _FromHSBToRef(hue, saturation, brightness, result) {\n let h = ColorCurves._Clamp(hue, 0, 360);\n const s = ColorCurves._Clamp(saturation / 100, 0, 1);\n const v = ColorCurves._Clamp(brightness / 100, 0, 1);\n if (s === 0) {\n result.r = v;\n result.g = v;\n result.b = v;\n }\n else {\n // sector 0 to 5\n h /= 60;\n const i = Math.floor(h);\n // fractional part of h\n const f = h - i;\n const p = v * (1 - s);\n const q = v * (1 - s * f);\n const t = v * (1 - s * (1 - f));\n switch (i) {\n case 0:\n result.r = v;\n result.g = t;\n result.b = p;\n break;\n case 1:\n result.r = q;\n result.g = v;\n result.b = p;\n break;\n case 2:\n result.r = p;\n result.g = v;\n result.b = t;\n break;\n case 3:\n result.r = p;\n result.g = q;\n result.b = v;\n break;\n case 4:\n result.r = t;\n result.g = p;\n result.b = v;\n break;\n default:\n // case 5:\n result.r = v;\n result.g = p;\n result.b = q;\n break;\n }\n }\n result.a = 1;\n }\n /**\n * Returns a value clamped between min and max\n * @param value The value to clamp\n * @param min The minimum of value\n * @param max The maximum of value\n * @returns The clamped value.\n */\n static _Clamp(value, min, max) {\n return Math.min(Math.max(value, min), max);\n }\n /**\n * Clones the current color curve instance.\n * @returns The cloned curves\n */\n clone() {\n return SerializationHelper.Clone(() => new ColorCurves(), this);\n }\n /**\n * Serializes the current color curve instance to a json representation.\n * @returns a JSON representation\n */\n serialize() {\n return SerializationHelper.Serialize(this);\n }\n /**\n * Parses the color curve from a json representation.\n * @param source the JSON source to parse\n * @returns The parsed curves\n */\n static Parse(source) {\n return SerializationHelper.Parse(() => new ColorCurves(), source, null, null);\n }\n}\n__decorate([\n serialize()\n], ColorCurves.prototype, \"_globalHue\", void 0);\n__decorate([\n serialize()\n], ColorCurves.prototype, \"_globalDensity\", void 0);\n__decorate([\n serialize()\n], ColorCurves.prototype, \"_globalSaturation\", void 0);\n__decorate([\n serialize()\n], ColorCurves.prototype, \"_globalExposure\", void 0);\n__decorate([\n serialize()\n], ColorCurves.prototype, \"_highlightsHue\", void 0);\n__decorate([\n serialize()\n], ColorCurves.prototype, \"_highlightsDensity\", void 0);\n__decorate([\n serialize()\n], ColorCurves.prototype, \"_highlightsSaturation\", void 0);\n__decorate([\n serialize()\n], ColorCurves.prototype, \"_highlightsExposure\", void 0);\n__decorate([\n serialize()\n], ColorCurves.prototype, \"_midtonesHue\", void 0);\n__decorate([\n serialize()\n], ColorCurves.prototype, \"_midtonesDensity\", void 0);\n__decorate([\n serialize()\n], ColorCurves.prototype, \"_midtonesSaturation\", void 0);\n__decorate([\n serialize()\n], ColorCurves.prototype, \"_midtonesExposure\", void 0);\n// References the dependencies.\nSerializationHelper._ColorCurvesParser = ColorCurves.Parse;\n//# sourceMappingURL=colorCurves.js.map","/** @internal */\nexport class DrawWrapper {\n static IsWrapper(effect) {\n return effect.getPipelineContext === undefined;\n }\n static GetEffect(effect) {\n return effect.getPipelineContext === undefined ? effect.effect : effect;\n }\n constructor(engine, createMaterialContext = true) {\n this.effect = null;\n this.defines = null;\n this.drawContext = engine.createDrawContext();\n if (createMaterialContext) {\n this.materialContext = engine.createMaterialContext();\n }\n }\n setEffect(effect, defines, resetContext = true) {\n var _a;\n this.effect = effect;\n if (defines !== undefined) {\n this.defines = defines;\n }\n if (resetContext) {\n (_a = this.drawContext) === null || _a === void 0 ? void 0 : _a.reset();\n }\n }\n dispose() {\n var _a;\n (_a = this.drawContext) === null || _a === void 0 ? void 0 : _a.dispose();\n }\n}\n//# sourceMappingURL=drawWrapper.js.map","import { Observable } from \"../Misc/observable.js\";\n\nimport { GetDOMTextContent, IsWindowObjectExist } from \"../Misc/domManagement.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { ShaderProcessor } from \"../Engines/Processors/shaderProcessor.js\";\nimport { ShaderStore as EngineShaderStore } from \"../Engines/shaderStore.js\";\nimport { ShaderLanguage } from \"./shaderLanguage.js\";\n/**\n * Effect containing vertex and fragment shader that can be executed on an object.\n */\nexport class Effect {\n /**\n * Gets or sets the relative url used to load shaders if using the engine in non-minified mode\n */\n static get ShadersRepository() {\n return EngineShaderStore.ShadersRepository;\n }\n static set ShadersRepository(repo) {\n EngineShaderStore.ShadersRepository = repo;\n }\n /**\n * Observable that will be called when effect is bound.\n */\n get onBindObservable() {\n if (!this._onBindObservable) {\n this._onBindObservable = new Observable();\n }\n return this._onBindObservable;\n }\n /**\n * Instantiates an effect.\n * An effect can be used to create/manage/execute vertex and fragment shaders.\n * @param baseName Name of the effect.\n * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.\n * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.\n * @param samplers List of sampler variables that will be passed to the shader.\n * @param engine Engine to be used to render the effect\n * @param defines Define statements to be added to the shader.\n * @param fallbacks Possible fallbacks for this effect to improve performance when needed.\n * @param onCompiled Callback that will be called when the shader is compiled.\n * @param onError Callback that will be called if an error occurs during shader compilation.\n * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})\n * @param key Effect Key identifying uniquely compiled shader variants\n * @param shaderLanguage the language the shader is written in (default: GLSL)\n */\n constructor(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers = null, engine, defines = null, fallbacks = null, onCompiled = null, onError = null, indexParameters, key = \"\", shaderLanguage = ShaderLanguage.GLSL) {\n var _a, _b, _c;\n /**\n * Name of the effect.\n */\n this.name = null;\n /**\n * String container all the define statements that should be set on the shader.\n */\n this.defines = \"\";\n /**\n * Callback that will be called when the shader is compiled.\n */\n this.onCompiled = null;\n /**\n * Callback that will be called if an error occurs during shader compilation.\n */\n this.onError = null;\n /**\n * Callback that will be called when effect is bound.\n */\n this.onBind = null;\n /**\n * Unique ID of the effect.\n */\n this.uniqueId = 0;\n /**\n * Observable that will be called when the shader is compiled.\n * It is recommended to use executeWhenCompile() or to make sure that scene.isReady() is called to get this observable raised.\n */\n this.onCompileObservable = new Observable();\n /**\n * Observable that will be called if an error occurs during shader compilation.\n */\n this.onErrorObservable = new Observable();\n /** @internal */\n this._onBindObservable = null;\n /**\n * @internal\n * Specifies if the effect was previously ready\n */\n this._wasPreviouslyReady = false;\n /**\n * @internal\n * Forces the code from bindForSubMesh to be fully run the next time it is called\n * It is used in frozen mode to make sure the effect is properly rebound when a new effect is created\n */\n this._forceRebindOnNextCall = false;\n /**\n * @internal\n * Specifies if the effect was previously using instances\n */\n this._wasPreviouslyUsingInstances = null;\n this._isDisposed = false;\n /** @internal */\n this._bonesComputationForcedToCPU = false;\n /** @internal */\n this._uniformBuffersNames = {};\n /** @internal */\n this._multiTarget = false;\n this._samplers = {};\n this._isReady = false;\n this._compilationError = \"\";\n this._allFallbacksProcessed = false;\n this._uniforms = {};\n /**\n * Key for the effect.\n * @internal\n */\n this._key = \"\";\n this._fallbacks = null;\n this._vertexSourceCodeOverride = \"\";\n this._fragmentSourceCodeOverride = \"\";\n this._transformFeedbackVaryings = null;\n /**\n * Compiled shader to webGL program.\n * @internal\n */\n this._pipelineContext = null;\n /** @internal */\n this._vertexSourceCode = \"\";\n /** @internal */\n this._fragmentSourceCode = \"\";\n /** @internal */\n this._vertexSourceCodeBeforeMigration = \"\";\n /** @internal */\n this._fragmentSourceCodeBeforeMigration = \"\";\n /** @internal */\n this._rawVertexSourceCode = \"\";\n /** @internal */\n this._rawFragmentSourceCode = \"\";\n this.name = baseName;\n this._key = key;\n let processCodeAfterIncludes = undefined;\n let processFinalCode = null;\n if (attributesNamesOrOptions.attributes) {\n const options = attributesNamesOrOptions;\n this._engine = uniformsNamesOrEngine;\n this._attributesNames = options.attributes;\n this._uniformsNames = options.uniformsNames.concat(options.samplers);\n this._samplerList = options.samplers.slice();\n this.defines = options.defines;\n this.onError = options.onError;\n this.onCompiled = options.onCompiled;\n this._fallbacks = options.fallbacks;\n this._indexParameters = options.indexParameters;\n this._transformFeedbackVaryings = options.transformFeedbackVaryings || null;\n this._multiTarget = !!options.multiTarget;\n this._shaderLanguage = (_a = options.shaderLanguage) !== null && _a !== void 0 ? _a : ShaderLanguage.GLSL;\n if (options.uniformBuffersNames) {\n this._uniformBuffersNamesList = options.uniformBuffersNames.slice();\n for (let i = 0; i < options.uniformBuffersNames.length; i++) {\n this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;\n }\n }\n processFinalCode = (_b = options.processFinalCode) !== null && _b !== void 0 ? _b : null;\n processCodeAfterIncludes = (_c = options.processCodeAfterIncludes) !== null && _c !== void 0 ? _c : undefined;\n }\n else {\n this._engine = engine;\n this.defines = defines == null ? \"\" : defines;\n this._uniformsNames = uniformsNamesOrEngine.concat(samplers);\n this._samplerList = samplers ? samplers.slice() : [];\n this._attributesNames = attributesNamesOrOptions;\n this._uniformBuffersNamesList = [];\n this._shaderLanguage = shaderLanguage;\n this.onError = onError;\n this.onCompiled = onCompiled;\n this._indexParameters = indexParameters;\n this._fallbacks = fallbacks;\n }\n this._attributeLocationByName = {};\n this.uniqueId = Effect._UniqueIdSeed++;\n let vertexSource;\n let fragmentSource;\n const hostDocument = IsWindowObjectExist() ? this._engine.getHostDocument() : null;\n if (baseName.vertexSource) {\n vertexSource = \"source:\" + baseName.vertexSource;\n }\n else if (baseName.vertexElement) {\n vertexSource = hostDocument ? hostDocument.getElementById(baseName.vertexElement) : null;\n if (!vertexSource) {\n vertexSource = baseName.vertexElement;\n }\n }\n else {\n vertexSource = baseName.vertex || baseName;\n }\n if (baseName.fragmentSource) {\n fragmentSource = \"source:\" + baseName.fragmentSource;\n }\n else if (baseName.fragmentElement) {\n fragmentSource = hostDocument ? hostDocument.getElementById(baseName.fragmentElement) : null;\n if (!fragmentSource) {\n fragmentSource = baseName.fragmentElement;\n }\n }\n else {\n fragmentSource = baseName.fragment || baseName;\n }\n this._processingContext = this._engine._getShaderProcessingContext(this._shaderLanguage);\n let processorOptions = {\n defines: this.defines.split(\"\\n\"),\n indexParameters: this._indexParameters,\n isFragment: false,\n shouldUseHighPrecisionShader: this._engine._shouldUseHighPrecisionShader,\n processor: this._engine._getShaderProcessor(this._shaderLanguage),\n supportsUniformBuffers: this._engine.supportsUniformBuffers,\n shadersRepository: EngineShaderStore.GetShadersRepository(this._shaderLanguage),\n includesShadersStore: EngineShaderStore.GetIncludesShadersStore(this._shaderLanguage),\n version: (this._engine.version * 100).toString(),\n platformName: this._engine.shaderPlatformName,\n processingContext: this._processingContext,\n isNDCHalfZRange: this._engine.isNDCHalfZRange,\n useReverseDepthBuffer: this._engine.useReverseDepthBuffer,\n processCodeAfterIncludes,\n };\n const shaderCodes = [undefined, undefined];\n const shadersLoaded = () => {\n if (shaderCodes[0] && shaderCodes[1]) {\n processorOptions.isFragment = true;\n const [migratedVertexCode, fragmentCode] = shaderCodes;\n ShaderProcessor.Process(fragmentCode, processorOptions, (migratedFragmentCode, codeBeforeMigration) => {\n this._fragmentSourceCodeBeforeMigration = codeBeforeMigration;\n if (processFinalCode) {\n migratedFragmentCode = processFinalCode(\"fragment\", migratedFragmentCode);\n }\n const finalShaders = ShaderProcessor.Finalize(migratedVertexCode, migratedFragmentCode, processorOptions);\n processorOptions = null;\n this._useFinalCode(finalShaders.vertexCode, finalShaders.fragmentCode, baseName);\n }, this._engine);\n }\n };\n this._loadShader(vertexSource, \"Vertex\", \"\", (vertexCode) => {\n ShaderProcessor.Initialize(processorOptions);\n ShaderProcessor.Process(vertexCode, processorOptions, (migratedVertexCode, codeBeforeMigration) => {\n this._rawVertexSourceCode = vertexCode;\n this._vertexSourceCodeBeforeMigration = codeBeforeMigration;\n if (processFinalCode) {\n migratedVertexCode = processFinalCode(\"vertex\", migratedVertexCode);\n }\n shaderCodes[0] = migratedVertexCode;\n shadersLoaded();\n }, this._engine);\n });\n this._loadShader(fragmentSource, \"Fragment\", \"Pixel\", (fragmentCode) => {\n this._rawFragmentSourceCode = fragmentCode;\n shaderCodes[1] = fragmentCode;\n shadersLoaded();\n });\n }\n _useFinalCode(migratedVertexCode, migratedFragmentCode, baseName) {\n if (baseName) {\n const vertex = baseName.vertexElement || baseName.vertex || baseName.spectorName || baseName;\n const fragment = baseName.fragmentElement || baseName.fragment || baseName.spectorName || baseName;\n this._vertexSourceCode = (this._shaderLanguage === ShaderLanguage.WGSL ? \"//\" : \"\") + \"#define SHADER_NAME vertex:\" + vertex + \"\\n\" + migratedVertexCode;\n this._fragmentSourceCode = (this._shaderLanguage === ShaderLanguage.WGSL ? \"//\" : \"\") + \"#define SHADER_NAME fragment:\" + fragment + \"\\n\" + migratedFragmentCode;\n }\n else {\n this._vertexSourceCode = migratedVertexCode;\n this._fragmentSourceCode = migratedFragmentCode;\n }\n this._prepareEffect();\n }\n /**\n * Unique key for this effect\n */\n get key() {\n return this._key;\n }\n /**\n * If the effect has been compiled and prepared.\n * @returns if the effect is compiled and prepared.\n */\n isReady() {\n try {\n return this._isReadyInternal();\n }\n catch (_a) {\n return false;\n }\n }\n _isReadyInternal() {\n if (this._isReady) {\n return true;\n }\n if (this._pipelineContext) {\n return this._pipelineContext.isReady;\n }\n return false;\n }\n /**\n * The engine the effect was initialized with.\n * @returns the engine.\n */\n getEngine() {\n return this._engine;\n }\n /**\n * The pipeline context for this effect\n * @returns the associated pipeline context\n */\n getPipelineContext() {\n return this._pipelineContext;\n }\n /**\n * The set of names of attribute variables for the shader.\n * @returns An array of attribute names.\n */\n getAttributesNames() {\n return this._attributesNames;\n }\n /**\n * Returns the attribute at the given index.\n * @param index The index of the attribute.\n * @returns The location of the attribute.\n */\n getAttributeLocation(index) {\n return this._attributes[index];\n }\n /**\n * Returns the attribute based on the name of the variable.\n * @param name of the attribute to look up.\n * @returns the attribute location.\n */\n getAttributeLocationByName(name) {\n return this._attributeLocationByName[name];\n }\n /**\n * The number of attributes.\n * @returns the number of attributes.\n */\n getAttributesCount() {\n return this._attributes.length;\n }\n /**\n * Gets the index of a uniform variable.\n * @param uniformName of the uniform to look up.\n * @returns the index.\n */\n getUniformIndex(uniformName) {\n return this._uniformsNames.indexOf(uniformName);\n }\n /**\n * Returns the attribute based on the name of the variable.\n * @param uniformName of the uniform to look up.\n * @returns the location of the uniform.\n */\n getUniform(uniformName) {\n return this._uniforms[uniformName];\n }\n /**\n * Returns an array of sampler variable names\n * @returns The array of sampler variable names.\n */\n getSamplers() {\n return this._samplerList;\n }\n /**\n * Returns an array of uniform variable names\n * @returns The array of uniform variable names.\n */\n getUniformNames() {\n return this._uniformsNames;\n }\n /**\n * Returns an array of uniform buffer variable names\n * @returns The array of uniform buffer variable names.\n */\n getUniformBuffersNames() {\n return this._uniformBuffersNamesList;\n }\n /**\n * Returns the index parameters used to create the effect\n * @returns The index parameters object\n */\n getIndexParameters() {\n return this._indexParameters;\n }\n /**\n * The error from the last compilation.\n * @returns the error string.\n */\n getCompilationError() {\n return this._compilationError;\n }\n /**\n * Gets a boolean indicating that all fallbacks were used during compilation\n * @returns true if all fallbacks were used\n */\n allFallbacksProcessed() {\n return this._allFallbacksProcessed;\n }\n /**\n * Adds a callback to the onCompiled observable and call the callback immediately if already ready.\n * @param func The callback to be used.\n */\n executeWhenCompiled(func) {\n if (this.isReady()) {\n func(this);\n return;\n }\n this.onCompileObservable.add((effect) => {\n func(effect);\n });\n if (!this._pipelineContext || this._pipelineContext.isAsync) {\n setTimeout(() => {\n this._checkIsReady(null);\n }, 16);\n }\n }\n _checkIsReady(previousPipelineContext) {\n try {\n if (this._isReadyInternal()) {\n return;\n }\n }\n catch (e) {\n this._processCompilationErrors(e, previousPipelineContext);\n return;\n }\n if (this._isDisposed) {\n return;\n }\n setTimeout(() => {\n this._checkIsReady(previousPipelineContext);\n }, 16);\n }\n _loadShader(shader, key, optionalKey, callback) {\n if (typeof HTMLElement !== \"undefined\") {\n // DOM element ?\n if (shader instanceof HTMLElement) {\n const shaderCode = GetDOMTextContent(shader);\n callback(shaderCode);\n return;\n }\n }\n // Direct source ?\n if (shader.substr(0, 7) === \"source:\") {\n callback(shader.substr(7));\n return;\n }\n // Base64 encoded ?\n if (shader.substr(0, 7) === \"base64:\") {\n const shaderBinary = window.atob(shader.substr(7));\n callback(shaderBinary);\n return;\n }\n const shaderStore = EngineShaderStore.GetShadersStore(this._shaderLanguage);\n // Is in local store ?\n if (shaderStore[shader + key + \"Shader\"]) {\n callback(shaderStore[shader + key + \"Shader\"]);\n return;\n }\n if (optionalKey && shaderStore[shader + optionalKey + \"Shader\"]) {\n callback(shaderStore[shader + optionalKey + \"Shader\"]);\n return;\n }\n let shaderUrl;\n if (shader[0] === \".\" || shader[0] === \"/\" || shader.indexOf(\"http\") > -1) {\n shaderUrl = shader;\n }\n else {\n shaderUrl = EngineShaderStore.GetShadersRepository(this._shaderLanguage) + shader;\n }\n // Vertex shader\n this._engine._loadFile(shaderUrl + \".\" + key.toLowerCase() + \".fx\", callback);\n }\n /**\n * Gets the vertex shader source code of this effect\n * This is the final source code that will be compiled, after all the processing has been done (pre-processing applied, code injection/replacement, etc)\n */\n get vertexSourceCode() {\n var _a, _b;\n return this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride\n ? this._vertexSourceCodeOverride\n : (_b = (_a = this._pipelineContext) === null || _a === void 0 ? void 0 : _a._getVertexShaderCode()) !== null && _b !== void 0 ? _b : this._vertexSourceCode;\n }\n /**\n * Gets the fragment shader source code of this effect\n * This is the final source code that will be compiled, after all the processing has been done (pre-processing applied, code injection/replacement, etc)\n */\n get fragmentSourceCode() {\n var _a, _b;\n return this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride\n ? this._fragmentSourceCodeOverride\n : (_b = (_a = this._pipelineContext) === null || _a === void 0 ? void 0 : _a._getFragmentShaderCode()) !== null && _b !== void 0 ? _b : this._fragmentSourceCode;\n }\n /**\n * Gets the vertex shader source code before migration.\n * This is the source code after the include directives have been replaced by their contents but before the code is migrated, i.e. before ShaderProcess._ProcessShaderConversion is executed.\n * This method is, among other things, responsible for parsing #if/#define directives as well as converting GLES2 syntax to GLES3 (in the case of WebGL).\n */\n get vertexSourceCodeBeforeMigration() {\n return this._vertexSourceCodeBeforeMigration;\n }\n /**\n * Gets the fragment shader source code before migration.\n * This is the source code after the include directives have been replaced by their contents but before the code is migrated, i.e. before ShaderProcess._ProcessShaderConversion is executed.\n * This method is, among other things, responsible for parsing #if/#define directives as well as converting GLES2 syntax to GLES3 (in the case of WebGL).\n */\n get fragmentSourceCodeBeforeMigration() {\n return this._fragmentSourceCodeBeforeMigration;\n }\n /**\n * Gets the vertex shader source code before it has been modified by any processing\n */\n get rawVertexSourceCode() {\n return this._rawVertexSourceCode;\n }\n /**\n * Gets the fragment shader source code before it has been modified by any processing\n */\n get rawFragmentSourceCode() {\n return this._rawFragmentSourceCode;\n }\n /**\n * Recompiles the webGL program\n * @param vertexSourceCode The source code for the vertex shader.\n * @param fragmentSourceCode The source code for the fragment shader.\n * @param onCompiled Callback called when completed.\n * @param onError Callback called on error.\n * @internal\n */\n _rebuildProgram(vertexSourceCode, fragmentSourceCode, onCompiled, onError) {\n this._isReady = false;\n this._vertexSourceCodeOverride = vertexSourceCode;\n this._fragmentSourceCodeOverride = fragmentSourceCode;\n this.onError = (effect, error) => {\n if (onError) {\n onError(error);\n }\n };\n this.onCompiled = () => {\n const scenes = this.getEngine().scenes;\n if (scenes) {\n for (let i = 0; i < scenes.length; i++) {\n scenes[i].markAllMaterialsAsDirty(63);\n }\n }\n this._pipelineContext._handlesSpectorRebuildCallback(onCompiled);\n };\n this._fallbacks = null;\n this._prepareEffect();\n }\n /**\n * Prepares the effect\n * @internal\n */\n _prepareEffect() {\n const attributesNames = this._attributesNames;\n const defines = this.defines;\n const previousPipelineContext = this._pipelineContext;\n this._isReady = false;\n try {\n const engine = this._engine;\n this._pipelineContext = engine.createPipelineContext(this._processingContext);\n this._pipelineContext._name = this._key;\n const rebuildRebind = this._rebuildProgram.bind(this);\n if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {\n engine._preparePipelineContext(this._pipelineContext, this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, true, this._rawVertexSourceCode, this._rawFragmentSourceCode, rebuildRebind, null, this._transformFeedbackVaryings, this._key);\n }\n else {\n engine._preparePipelineContext(this._pipelineContext, this._vertexSourceCode, this._fragmentSourceCode, false, this._rawVertexSourceCode, this._rawFragmentSourceCode, rebuildRebind, defines, this._transformFeedbackVaryings, this._key);\n }\n engine._executeWhenRenderingStateIsCompiled(this._pipelineContext, () => {\n this._attributes = [];\n this._pipelineContext._fillEffectInformation(this, this._uniformBuffersNames, this._uniformsNames, this._uniforms, this._samplerList, this._samplers, attributesNames, this._attributes);\n // Caches attribute locations.\n if (attributesNames) {\n for (let i = 0; i < attributesNames.length; i++) {\n const name = attributesNames[i];\n this._attributeLocationByName[name] = this._attributes[i];\n }\n }\n engine.bindSamplers(this);\n this._compilationError = \"\";\n this._isReady = true;\n if (this.onCompiled) {\n this.onCompiled(this);\n }\n this.onCompileObservable.notifyObservers(this);\n this.onCompileObservable.clear();\n // Unbind mesh reference in fallbacks\n if (this._fallbacks) {\n this._fallbacks.unBindMesh();\n }\n if (previousPipelineContext) {\n this.getEngine()._deletePipelineContext(previousPipelineContext);\n }\n });\n if (this._pipelineContext.isAsync) {\n this._checkIsReady(previousPipelineContext);\n }\n }\n catch (e) {\n this._processCompilationErrors(e, previousPipelineContext);\n }\n }\n _getShaderCodeAndErrorLine(code, error, isFragment) {\n const regexp = isFragment ? /FRAGMENT SHADER ERROR: 0:(\\d+?):/ : /VERTEX SHADER ERROR: 0:(\\d+?):/;\n let errorLine = null;\n if (error && code) {\n const res = error.match(regexp);\n if (res && res.length === 2) {\n const lineNumber = parseInt(res[1]);\n const lines = code.split(\"\\n\", -1);\n if (lines.length >= lineNumber) {\n errorLine = `Offending line [${lineNumber}] in ${isFragment ? \"fragment\" : \"vertex\"} code: ${lines[lineNumber - 1]}`;\n }\n }\n }\n return [code, errorLine];\n }\n _processCompilationErrors(e, previousPipelineContext = null) {\n var _a, _b, _c;\n this._compilationError = e.message;\n const attributesNames = this._attributesNames;\n const fallbacks = this._fallbacks;\n // Let's go through fallbacks then\n Logger.Error(\"Unable to compile effect:\");\n Logger.Error(\"Uniforms: \" +\n this._uniformsNames.map(function (uniform) {\n return \" \" + uniform;\n }));\n Logger.Error(\"Attributes: \" +\n attributesNames.map(function (attribute) {\n return \" \" + attribute;\n }));\n Logger.Error(\"Defines:\\r\\n\" + this.defines);\n if (Effect.LogShaderCodeOnCompilationError) {\n let lineErrorVertex = null, lineErrorFragment = null, code = null;\n if ((_a = this._pipelineContext) === null || _a === void 0 ? void 0 : _a._getVertexShaderCode()) {\n [code, lineErrorVertex] = this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(), this._compilationError, false);\n if (code) {\n Logger.Error(\"Vertex code:\");\n Logger.Error(code);\n }\n }\n if ((_b = this._pipelineContext) === null || _b === void 0 ? void 0 : _b._getFragmentShaderCode()) {\n [code, lineErrorFragment] = this._getShaderCodeAndErrorLine((_c = this._pipelineContext) === null || _c === void 0 ? void 0 : _c._getFragmentShaderCode(), this._compilationError, true);\n if (code) {\n Logger.Error(\"Fragment code:\");\n Logger.Error(code);\n }\n }\n if (lineErrorVertex) {\n Logger.Error(lineErrorVertex);\n }\n if (lineErrorFragment) {\n Logger.Error(lineErrorFragment);\n }\n }\n Logger.Error(\"Error: \" + this._compilationError);\n const notifyErrors = () => {\n if (this.onError) {\n this.onError(this, this._compilationError);\n }\n this.onErrorObservable.notifyObservers(this);\n };\n // In case a previous compilation was successful, we need to restore the previous pipeline context\n if (previousPipelineContext) {\n this._pipelineContext = previousPipelineContext;\n this._isReady = true;\n notifyErrors();\n }\n // Lets try to compile fallbacks as long as we have some.\n if (fallbacks) {\n this._pipelineContext = null;\n if (fallbacks.hasMoreFallbacks) {\n this._allFallbacksProcessed = false;\n Logger.Error(\"Trying next fallback.\");\n this.defines = fallbacks.reduce(this.defines, this);\n this._prepareEffect();\n }\n else {\n // Sorry we did everything we can\n this._allFallbacksProcessed = true;\n notifyErrors();\n this.onErrorObservable.clear();\n // Unbind mesh reference in fallbacks\n if (this._fallbacks) {\n this._fallbacks.unBindMesh();\n }\n }\n }\n else {\n this._allFallbacksProcessed = true;\n // In case of error, without any prior successful compilation, let s notify observers\n if (!previousPipelineContext) {\n notifyErrors();\n }\n }\n }\n /**\n * Checks if the effect is supported. (Must be called after compilation)\n */\n get isSupported() {\n return this._compilationError === \"\";\n }\n /**\n * Binds a texture to the engine to be used as output of the shader.\n * @param channel Name of the output variable.\n * @param texture Texture to bind.\n * @internal\n */\n _bindTexture(channel, texture) {\n this._engine._bindTexture(this._samplers[channel], texture, channel);\n }\n /**\n * Sets a texture on the engine to be used in the shader.\n * @param channel Name of the sampler variable.\n * @param texture Texture to set.\n */\n setTexture(channel, texture) {\n this._engine.setTexture(this._samplers[channel], this._uniforms[channel], texture, channel);\n }\n /**\n * Sets a depth stencil texture from a render target on the engine to be used in the shader.\n * @param channel Name of the sampler variable.\n * @param texture Texture to set.\n */\n setDepthStencilTexture(channel, texture) {\n this._engine.setDepthStencilTexture(this._samplers[channel], this._uniforms[channel], texture, channel);\n }\n /**\n * Sets an array of textures on the engine to be used in the shader.\n * @param channel Name of the variable.\n * @param textures Textures to set.\n */\n setTextureArray(channel, textures) {\n const exName = channel + \"Ex\";\n if (this._samplerList.indexOf(exName + \"0\") === -1) {\n const initialPos = this._samplerList.indexOf(channel);\n for (let index = 1; index < textures.length; index++) {\n const currentExName = exName + (index - 1).toString();\n this._samplerList.splice(initialPos + index, 0, currentExName);\n }\n // Reset every channels\n let channelIndex = 0;\n for (const key of this._samplerList) {\n this._samplers[key] = channelIndex;\n channelIndex += 1;\n }\n }\n this._engine.setTextureArray(this._samplers[channel], this._uniforms[channel], textures, channel);\n }\n /**\n * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)\n * @param channel Name of the sampler variable.\n * @param postProcess Post process to get the input texture from.\n */\n setTextureFromPostProcess(channel, postProcess) {\n this._engine.setTextureFromPostProcess(this._samplers[channel], postProcess, channel);\n }\n /**\n * (Warning! setTextureFromPostProcessOutput may be desired instead)\n * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)\n * @param channel Name of the sampler variable.\n * @param postProcess Post process to get the output texture from.\n */\n setTextureFromPostProcessOutput(channel, postProcess) {\n this._engine.setTextureFromPostProcessOutput(this._samplers[channel], postProcess, channel);\n }\n /**\n * Binds a buffer to a uniform.\n * @param buffer Buffer to bind.\n * @param name Name of the uniform variable to bind to.\n */\n bindUniformBuffer(buffer, name) {\n const bufferName = this._uniformBuffersNames[name];\n if (bufferName === undefined || (Effect._BaseCache[bufferName] === buffer && this._engine._features.useUBOBindingCache)) {\n return;\n }\n Effect._BaseCache[bufferName] = buffer;\n this._engine.bindUniformBufferBase(buffer, bufferName, name);\n }\n /**\n * Binds block to a uniform.\n * @param blockName Name of the block to bind.\n * @param index Index to bind.\n */\n bindUniformBlock(blockName, index) {\n this._engine.bindUniformBlock(this._pipelineContext, blockName, index);\n }\n /**\n * Sets an integer value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value Value to be set.\n * @returns this effect.\n */\n setInt(uniformName, value) {\n this._pipelineContext.setInt(uniformName, value);\n return this;\n }\n /**\n * Sets an int2 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First int in int2.\n * @param y Second int in int2.\n * @returns this effect.\n */\n setInt2(uniformName, x, y) {\n this._pipelineContext.setInt2(uniformName, x, y);\n return this;\n }\n /**\n * Sets an int3 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First int in int3.\n * @param y Second int in int3.\n * @param z Third int in int3.\n * @returns this effect.\n */\n setInt3(uniformName, x, y, z) {\n this._pipelineContext.setInt3(uniformName, x, y, z);\n return this;\n }\n /**\n * Sets an int4 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First int in int4.\n * @param y Second int in int4.\n * @param z Third int in int4.\n * @param w Fourth int in int4.\n * @returns this effect.\n */\n setInt4(uniformName, x, y, z, w) {\n this._pipelineContext.setInt4(uniformName, x, y, z, w);\n return this;\n }\n /**\n * Sets an int array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setIntArray(uniformName, array) {\n this._pipelineContext.setIntArray(uniformName, array);\n return this;\n }\n /**\n * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setIntArray2(uniformName, array) {\n this._pipelineContext.setIntArray2(uniformName, array);\n return this;\n }\n /**\n * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setIntArray3(uniformName, array) {\n this._pipelineContext.setIntArray3(uniformName, array);\n return this;\n }\n /**\n * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setIntArray4(uniformName, array) {\n this._pipelineContext.setIntArray4(uniformName, array);\n return this;\n }\n /**\n * Sets an unsigned integer value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value Value to be set.\n * @returns this effect.\n */\n setUInt(uniformName, value) {\n this._pipelineContext.setInt(uniformName, value);\n return this;\n }\n /**\n * Sets an unsigned int2 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First unsigned int in uint2.\n * @param y Second unsigned int in uint2.\n * @returns this effect.\n */\n setUInt2(uniformName, x, y) {\n this._pipelineContext.setInt2(uniformName, x, y);\n return this;\n }\n /**\n * Sets an unsigned int3 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First unsigned int in uint3.\n * @param y Second unsigned int in uint3.\n * @param z Third unsigned int in uint3.\n * @returns this effect.\n */\n setUInt3(uniformName, x, y, z) {\n this._pipelineContext.setInt3(uniformName, x, y, z);\n return this;\n }\n /**\n * Sets an unsigned int4 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First unsigned int in uint4.\n * @param y Second unsigned int in uint4.\n * @param z Third unsigned int in uint4.\n * @param w Fourth unsigned int in uint4.\n * @returns this effect.\n */\n setUInt4(uniformName, x, y, z, w) {\n this._pipelineContext.setInt4(uniformName, x, y, z, w);\n return this;\n }\n /**\n * Sets an unsigned int array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setUIntArray(uniformName, array) {\n this._pipelineContext.setUIntArray(uniformName, array);\n return this;\n }\n /**\n * Sets an unsigned int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setUIntArray2(uniformName, array) {\n this._pipelineContext.setUIntArray2(uniformName, array);\n return this;\n }\n /**\n * Sets an unsigned int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setUIntArray3(uniformName, array) {\n this._pipelineContext.setUIntArray3(uniformName, array);\n return this;\n }\n /**\n * Sets an unsigned int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setUIntArray4(uniformName, array) {\n this._pipelineContext.setUIntArray4(uniformName, array);\n return this;\n }\n /**\n * Sets an float array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setFloatArray(uniformName, array) {\n this._pipelineContext.setArray(uniformName, array);\n return this;\n }\n /**\n * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setFloatArray2(uniformName, array) {\n this._pipelineContext.setArray2(uniformName, array);\n return this;\n }\n /**\n * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setFloatArray3(uniformName, array) {\n this._pipelineContext.setArray3(uniformName, array);\n return this;\n }\n /**\n * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setFloatArray4(uniformName, array) {\n this._pipelineContext.setArray4(uniformName, array);\n return this;\n }\n /**\n * Sets an array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setArray(uniformName, array) {\n this._pipelineContext.setArray(uniformName, array);\n return this;\n }\n /**\n * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setArray2(uniformName, array) {\n this._pipelineContext.setArray2(uniformName, array);\n return this;\n }\n /**\n * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setArray3(uniformName, array) {\n this._pipelineContext.setArray3(uniformName, array);\n return this;\n }\n /**\n * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setArray4(uniformName, array) {\n this._pipelineContext.setArray4(uniformName, array);\n return this;\n }\n /**\n * Sets matrices on a uniform variable.\n * @param uniformName Name of the variable.\n * @param matrices matrices to be set.\n * @returns this effect.\n */\n setMatrices(uniformName, matrices) {\n this._pipelineContext.setMatrices(uniformName, matrices);\n return this;\n }\n /**\n * Sets matrix on a uniform variable.\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n * @returns this effect.\n */\n setMatrix(uniformName, matrix) {\n this._pipelineContext.setMatrix(uniformName, matrix);\n return this;\n }\n /**\n * Sets a 3x3 matrix on a uniform variable. (Specified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n * @returns this effect.\n */\n setMatrix3x3(uniformName, matrix) {\n // the cast is ok because it is gl.uniformMatrix3fv() which is called at the end, and this function accepts Float32Array and Array\n this._pipelineContext.setMatrix3x3(uniformName, matrix);\n return this;\n }\n /**\n * Sets a 2x2 matrix on a uniform variable. (Specified as [1,2,3,4] will result in [1,2][3,4] matrix)\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n * @returns this effect.\n */\n setMatrix2x2(uniformName, matrix) {\n // the cast is ok because it is gl.uniformMatrix3fv() which is called at the end, and this function accepts Float32Array and Array\n this._pipelineContext.setMatrix2x2(uniformName, matrix);\n return this;\n }\n /**\n * Sets a float on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value value to be set.\n * @returns this effect.\n */\n setFloat(uniformName, value) {\n this._pipelineContext.setFloat(uniformName, value);\n return this;\n }\n /**\n * Sets a boolean on a uniform variable.\n * @param uniformName Name of the variable.\n * @param bool value to be set.\n * @returns this effect.\n */\n setBool(uniformName, bool) {\n this._pipelineContext.setInt(uniformName, bool ? 1 : 0);\n return this;\n }\n /**\n * Sets a Vector2 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector2 vector2 to be set.\n * @returns this effect.\n */\n setVector2(uniformName, vector2) {\n this._pipelineContext.setVector2(uniformName, vector2);\n return this;\n }\n /**\n * Sets a float2 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float2.\n * @param y Second float in float2.\n * @returns this effect.\n */\n setFloat2(uniformName, x, y) {\n this._pipelineContext.setFloat2(uniformName, x, y);\n return this;\n }\n /**\n * Sets a Vector3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector3 Value to be set.\n * @returns this effect.\n */\n setVector3(uniformName, vector3) {\n this._pipelineContext.setVector3(uniformName, vector3);\n return this;\n }\n /**\n * Sets a float3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float3.\n * @param y Second float in float3.\n * @param z Third float in float3.\n * @returns this effect.\n */\n setFloat3(uniformName, x, y, z) {\n this._pipelineContext.setFloat3(uniformName, x, y, z);\n return this;\n }\n /**\n * Sets a Vector4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector4 Value to be set.\n * @returns this effect.\n */\n setVector4(uniformName, vector4) {\n this._pipelineContext.setVector4(uniformName, vector4);\n return this;\n }\n /**\n * Sets a Quaternion on a uniform variable.\n * @param uniformName Name of the variable.\n * @param quaternion Value to be set.\n * @returns this effect.\n */\n setQuaternion(uniformName, quaternion) {\n this._pipelineContext.setQuaternion(uniformName, quaternion);\n return this;\n }\n /**\n * Sets a float4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float4.\n * @param y Second float in float4.\n * @param z Third float in float4.\n * @param w Fourth float in float4.\n * @returns this effect.\n */\n setFloat4(uniformName, x, y, z, w) {\n this._pipelineContext.setFloat4(uniformName, x, y, z, w);\n return this;\n }\n /**\n * Sets a Color3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param color3 Value to be set.\n * @returns this effect.\n */\n setColor3(uniformName, color3) {\n this._pipelineContext.setColor3(uniformName, color3);\n return this;\n }\n /**\n * Sets a Color4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param color3 Value to be set.\n * @param alpha Alpha value to be set.\n * @returns this effect.\n */\n setColor4(uniformName, color3, alpha) {\n this._pipelineContext.setColor4(uniformName, color3, alpha);\n return this;\n }\n /**\n * Sets a Color4 on a uniform variable\n * @param uniformName defines the name of the variable\n * @param color4 defines the value to be set\n * @returns this effect.\n */\n setDirectColor4(uniformName, color4) {\n this._pipelineContext.setDirectColor4(uniformName, color4);\n return this;\n }\n /**\n * Release all associated resources.\n **/\n dispose() {\n if (this._pipelineContext) {\n this._pipelineContext.dispose();\n }\n this._engine._releaseEffect(this);\n this._isDisposed = true;\n }\n /**\n * This function will add a new shader to the shader store\n * @param name the name of the shader\n * @param pixelShader optional pixel shader content\n * @param vertexShader optional vertex shader content\n * @param shaderLanguage the language the shader is written in (default: GLSL)\n */\n static RegisterShader(name, pixelShader, vertexShader, shaderLanguage = ShaderLanguage.GLSL) {\n if (pixelShader) {\n EngineShaderStore.GetShadersStore(shaderLanguage)[`${name}PixelShader`] = pixelShader;\n }\n if (vertexShader) {\n EngineShaderStore.GetShadersStore(shaderLanguage)[`${name}VertexShader`] = vertexShader;\n }\n }\n /**\n * Resets the cache of effects.\n */\n static ResetCache() {\n Effect._BaseCache = {};\n }\n}\n/**\n * Enable logging of the shader code when a compilation error occurs\n */\nEffect.LogShaderCodeOnCompilationError = true;\nEffect._UniqueIdSeed = 0;\nEffect._BaseCache = {};\n/**\n * Store of each shader (The can be looked up using effect.key)\n */\nEffect.ShadersStore = EngineShaderStore.ShadersStore;\n/**\n * Store of each included file for a shader (The can be looked up using effect.key)\n */\nEffect.IncludesShadersStore = EngineShaderStore.IncludesShadersStore;\n//# sourceMappingURL=effect.js.map","import { __decorate } from \"../tslib.es6.js\";\n/* eslint-disable @typescript-eslint/naming-convention */\nimport { serialize, SerializationHelper, serializeAsTexture, serializeAsColorCurves, serializeAsColor4 } from \"../Misc/decorators.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Tools } from \"../Misc/tools.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { MaterialDefines } from \"../Materials/materialDefines.js\";\nimport { ColorCurves } from \"../Materials/colorCurves.js\";\n/**\n * @internal\n */\nexport class ImageProcessingConfigurationDefines extends MaterialDefines {\n constructor() {\n super();\n this.IMAGEPROCESSING = false;\n this.VIGNETTE = false;\n this.VIGNETTEBLENDMODEMULTIPLY = false;\n this.VIGNETTEBLENDMODEOPAQUE = false;\n this.TONEMAPPING = false;\n this.TONEMAPPING_ACES = false;\n this.CONTRAST = false;\n this.COLORCURVES = false;\n this.COLORGRADING = false;\n this.COLORGRADING3D = false;\n this.SAMPLER3DGREENDEPTH = false;\n this.SAMPLER3DBGRMAP = false;\n this.DITHER = false;\n this.IMAGEPROCESSINGPOSTPROCESS = false;\n this.EXPOSURE = false;\n this.SKIPFINALCOLORCLAMP = false;\n this.rebuild();\n }\n}\n/**\n * This groups together the common properties used for image processing either in direct forward pass\n * or through post processing effect depending on the use of the image processing pipeline in your scene\n * or not.\n */\nexport class ImageProcessingConfiguration {\n constructor() {\n /**\n * Color curves setup used in the effect if colorCurvesEnabled is set to true\n */\n this.colorCurves = new ColorCurves();\n this._colorCurvesEnabled = false;\n this._colorGradingEnabled = false;\n this._colorGradingWithGreenDepth = true;\n this._colorGradingBGR = true;\n /** @internal */\n this._exposure = 1.0;\n this._toneMappingEnabled = false;\n this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;\n this._contrast = 1.0;\n /**\n * Vignette stretch size.\n */\n this.vignetteStretch = 0;\n /**\n * Vignette center X Offset.\n */\n this.vignetteCenterX = 0;\n /**\n * Vignette center Y Offset.\n */\n this.vignetteCenterY = 0;\n /**\n * Vignette weight or intensity of the vignette effect.\n */\n this.vignetteWeight = 1.5;\n /**\n * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)\n * if vignetteEnabled is set to true.\n */\n this.vignetteColor = new Color4(0, 0, 0, 0);\n /**\n * Camera field of view used by the Vignette effect.\n */\n this.vignetteCameraFov = 0.5;\n this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;\n this._vignetteEnabled = false;\n this._ditheringEnabled = false;\n this._ditheringIntensity = 1.0 / 255.0;\n /** @internal */\n this._skipFinalColorClamp = false;\n /** @internal */\n this._applyByPostProcess = false;\n this._isEnabled = true;\n /**\n * An event triggered when the configuration changes and requires Shader to Update some parameters.\n */\n this.onUpdateParameters = new Observable();\n }\n /**\n * Gets whether the color curves effect is enabled.\n */\n get colorCurvesEnabled() {\n return this._colorCurvesEnabled;\n }\n /**\n * Sets whether the color curves effect is enabled.\n */\n set colorCurvesEnabled(value) {\n if (this._colorCurvesEnabled === value) {\n return;\n }\n this._colorCurvesEnabled = value;\n this._updateParameters();\n }\n /**\n * Color grading LUT texture used in the effect if colorGradingEnabled is set to true\n */\n get colorGradingTexture() {\n return this._colorGradingTexture;\n }\n /**\n * Color grading LUT texture used in the effect if colorGradingEnabled is set to true\n */\n set colorGradingTexture(value) {\n if (this._colorGradingTexture === value) {\n return;\n }\n this._colorGradingTexture = value;\n this._updateParameters();\n }\n /**\n * Gets whether the color grading effect is enabled.\n */\n get colorGradingEnabled() {\n return this._colorGradingEnabled;\n }\n /**\n * Sets whether the color grading effect is enabled.\n */\n set colorGradingEnabled(value) {\n if (this._colorGradingEnabled === value) {\n return;\n }\n this._colorGradingEnabled = value;\n this._updateParameters();\n }\n /**\n * Gets whether the color grading effect is using a green depth for the 3d Texture.\n */\n get colorGradingWithGreenDepth() {\n return this._colorGradingWithGreenDepth;\n }\n /**\n * Sets whether the color grading effect is using a green depth for the 3d Texture.\n */\n set colorGradingWithGreenDepth(value) {\n if (this._colorGradingWithGreenDepth === value) {\n return;\n }\n this._colorGradingWithGreenDepth = value;\n this._updateParameters();\n }\n /**\n * Gets whether the color grading texture contains BGR values.\n */\n get colorGradingBGR() {\n return this._colorGradingBGR;\n }\n /**\n * Sets whether the color grading texture contains BGR values.\n */\n set colorGradingBGR(value) {\n if (this._colorGradingBGR === value) {\n return;\n }\n this._colorGradingBGR = value;\n this._updateParameters();\n }\n /**\n * Gets the Exposure used in the effect.\n */\n get exposure() {\n return this._exposure;\n }\n /**\n * Sets the Exposure used in the effect.\n */\n set exposure(value) {\n if (this._exposure === value) {\n return;\n }\n this._exposure = value;\n this._updateParameters();\n }\n /**\n * Gets whether the tone mapping effect is enabled.\n */\n get toneMappingEnabled() {\n return this._toneMappingEnabled;\n }\n /**\n * Sets whether the tone mapping effect is enabled.\n */\n set toneMappingEnabled(value) {\n if (this._toneMappingEnabled === value) {\n return;\n }\n this._toneMappingEnabled = value;\n this._updateParameters();\n }\n /**\n * Gets the type of tone mapping effect.\n */\n get toneMappingType() {\n return this._toneMappingType;\n }\n /**\n * Sets the type of tone mapping effect used in BabylonJS.\n */\n set toneMappingType(value) {\n if (this._toneMappingType === value) {\n return;\n }\n this._toneMappingType = value;\n this._updateParameters();\n }\n /**\n * Gets the contrast used in the effect.\n */\n get contrast() {\n return this._contrast;\n }\n /**\n * Sets the contrast used in the effect.\n */\n set contrast(value) {\n if (this._contrast === value) {\n return;\n }\n this._contrast = value;\n this._updateParameters();\n }\n /**\n * Back Compat: Vignette center Y Offset.\n * @deprecated use vignetteCenterY instead\n */\n get vignetteCentreY() {\n return this.vignetteCenterY;\n }\n set vignetteCentreY(value) {\n this.vignetteCenterY = value;\n }\n /**\n * Back Compat: Vignette center X Offset.\n * @deprecated use vignetteCenterX instead\n */\n get vignetteCentreX() {\n return this.vignetteCenterX;\n }\n set vignetteCentreX(value) {\n this.vignetteCenterX = value;\n }\n /**\n * Gets the vignette blend mode allowing different kind of effect.\n */\n get vignetteBlendMode() {\n return this._vignetteBlendMode;\n }\n /**\n * Sets the vignette blend mode allowing different kind of effect.\n */\n set vignetteBlendMode(value) {\n if (this._vignetteBlendMode === value) {\n return;\n }\n this._vignetteBlendMode = value;\n this._updateParameters();\n }\n /**\n * Gets whether the vignette effect is enabled.\n */\n get vignetteEnabled() {\n return this._vignetteEnabled;\n }\n /**\n * Sets whether the vignette effect is enabled.\n */\n set vignetteEnabled(value) {\n if (this._vignetteEnabled === value) {\n return;\n }\n this._vignetteEnabled = value;\n this._updateParameters();\n }\n /**\n * Gets whether the dithering effect is enabled.\n * The dithering effect can be used to reduce banding.\n */\n get ditheringEnabled() {\n return this._ditheringEnabled;\n }\n /**\n * Sets whether the dithering effect is enabled.\n * The dithering effect can be used to reduce banding.\n */\n set ditheringEnabled(value) {\n if (this._ditheringEnabled === value) {\n return;\n }\n this._ditheringEnabled = value;\n this._updateParameters();\n }\n /**\n * Gets the dithering intensity. 0 is no dithering. Default is 1.0 / 255.0.\n */\n get ditheringIntensity() {\n return this._ditheringIntensity;\n }\n /**\n * Sets the dithering intensity. 0 is no dithering. Default is 1.0 / 255.0.\n */\n set ditheringIntensity(value) {\n if (this._ditheringIntensity === value) {\n return;\n }\n this._ditheringIntensity = value;\n this._updateParameters();\n }\n /**\n * If apply by post process is set to true, setting this to true will skip the the final color clamp step in the fragment shader\n * Applies to PBR materials.\n */\n get skipFinalColorClamp() {\n return this._skipFinalColorClamp;\n }\n /**\n * If apply by post process is set to true, setting this to true will skip the the final color clamp step in the fragment shader\n * Applies to PBR materials.\n */\n set skipFinalColorClamp(value) {\n if (this._skipFinalColorClamp === value) {\n return;\n }\n this._skipFinalColorClamp = value;\n this._updateParameters();\n }\n /**\n * Gets whether the image processing is applied through a post process or not.\n */\n get applyByPostProcess() {\n return this._applyByPostProcess;\n }\n /**\n * Sets whether the image processing is applied through a post process or not.\n */\n set applyByPostProcess(value) {\n if (this._applyByPostProcess === value) {\n return;\n }\n this._applyByPostProcess = value;\n this._updateParameters();\n }\n /**\n * Gets whether the image processing is enabled or not.\n */\n get isEnabled() {\n return this._isEnabled;\n }\n /**\n * Sets whether the image processing is enabled or not.\n */\n set isEnabled(value) {\n if (this._isEnabled === value) {\n return;\n }\n this._isEnabled = value;\n this._updateParameters();\n }\n /**\n * Method called each time the image processing information changes requires to recompile the effect.\n */\n _updateParameters() {\n this.onUpdateParameters.notifyObservers(this);\n }\n /**\n * Gets the current class name.\n * @returns \"ImageProcessingConfiguration\"\n */\n getClassName() {\n return \"ImageProcessingConfiguration\";\n }\n /**\n * Prepare the list of uniforms associated with the Image Processing effects.\n * @param uniforms The list of uniforms used in the effect\n * @param defines the list of defines currently in use\n */\n static PrepareUniforms(uniforms, defines) {\n if (defines.EXPOSURE) {\n uniforms.push(\"exposureLinear\");\n }\n if (defines.CONTRAST) {\n uniforms.push(\"contrast\");\n }\n if (defines.COLORGRADING) {\n uniforms.push(\"colorTransformSettings\");\n }\n if (defines.VIGNETTE || defines.DITHER) {\n uniforms.push(\"vInverseScreenSize\");\n }\n if (defines.VIGNETTE) {\n uniforms.push(\"vignetteSettings1\");\n uniforms.push(\"vignetteSettings2\");\n }\n if (defines.COLORCURVES) {\n ColorCurves.PrepareUniforms(uniforms);\n }\n if (defines.DITHER) {\n uniforms.push(\"ditherIntensity\");\n }\n }\n /**\n * Prepare the list of samplers associated with the Image Processing effects.\n * @param samplersList The list of uniforms used in the effect\n * @param defines the list of defines currently in use\n */\n static PrepareSamplers(samplersList, defines) {\n if (defines.COLORGRADING) {\n samplersList.push(\"txColorTransform\");\n }\n }\n /**\n * Prepare the list of defines associated to the shader.\n * @param defines the list of defines to complete\n * @param forPostProcess Define if we are currently in post process mode or not\n */\n prepareDefines(defines, forPostProcess = false) {\n if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {\n defines.VIGNETTE = false;\n defines.TONEMAPPING = false;\n defines.TONEMAPPING_ACES = false;\n defines.CONTRAST = false;\n defines.EXPOSURE = false;\n defines.COLORCURVES = false;\n defines.COLORGRADING = false;\n defines.COLORGRADING3D = false;\n defines.DITHER = false;\n defines.IMAGEPROCESSING = false;\n defines.SKIPFINALCOLORCLAMP = this.skipFinalColorClamp;\n defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;\n return;\n }\n defines.VIGNETTE = this.vignetteEnabled;\n defines.VIGNETTEBLENDMODEMULTIPLY = this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY;\n defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;\n defines.TONEMAPPING = this.toneMappingEnabled;\n switch (this._toneMappingType) {\n case ImageProcessingConfiguration.TONEMAPPING_ACES:\n defines.TONEMAPPING_ACES = true;\n break;\n default:\n defines.TONEMAPPING_ACES = false;\n break;\n }\n defines.CONTRAST = this.contrast !== 1.0;\n defines.EXPOSURE = this.exposure !== 1.0;\n defines.COLORCURVES = this.colorCurvesEnabled && !!this.colorCurves;\n defines.COLORGRADING = this.colorGradingEnabled && !!this.colorGradingTexture;\n if (defines.COLORGRADING) {\n defines.COLORGRADING3D = this.colorGradingTexture.is3D;\n }\n else {\n defines.COLORGRADING3D = false;\n }\n defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;\n defines.SAMPLER3DBGRMAP = this.colorGradingBGR;\n defines.DITHER = this._ditheringEnabled;\n defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;\n defines.SKIPFINALCOLORCLAMP = this.skipFinalColorClamp;\n defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.DITHER;\n }\n /**\n * Returns true if all the image processing information are ready.\n * @returns True if ready, otherwise, false\n */\n isReady() {\n // Color Grading texture can not be none blocking.\n return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();\n }\n /**\n * Binds the image processing to the shader.\n * @param effect The effect to bind to\n * @param overrideAspectRatio Override the aspect ratio of the effect\n */\n bind(effect, overrideAspectRatio) {\n // Color Curves\n if (this._colorCurvesEnabled && this.colorCurves) {\n ColorCurves.Bind(this.colorCurves, effect);\n }\n // Vignette and dither handled together due to common uniform.\n if (this._vignetteEnabled || this._ditheringEnabled) {\n const inverseWidth = 1 / effect.getEngine().getRenderWidth();\n const inverseHeight = 1 / effect.getEngine().getRenderHeight();\n effect.setFloat2(\"vInverseScreenSize\", inverseWidth, inverseHeight);\n if (this._ditheringEnabled) {\n effect.setFloat(\"ditherIntensity\", 0.5 * this._ditheringIntensity);\n }\n if (this._vignetteEnabled) {\n const aspectRatio = overrideAspectRatio != null ? overrideAspectRatio : inverseHeight / inverseWidth;\n let vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);\n let vignetteScaleX = vignetteScaleY * aspectRatio;\n const vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);\n vignetteScaleX = Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);\n vignetteScaleY = Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);\n effect.setFloat4(\"vignetteSettings1\", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCenterX, -vignetteScaleY * this.vignetteCenterY);\n const vignettePower = -2.0 * this.vignetteWeight;\n effect.setFloat4(\"vignetteSettings2\", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);\n }\n }\n // Exposure\n effect.setFloat(\"exposureLinear\", this.exposure);\n // Contrast\n effect.setFloat(\"contrast\", this.contrast);\n // Color transform settings\n if (this.colorGradingTexture) {\n effect.setTexture(\"txColorTransform\", this.colorGradingTexture);\n const textureSize = this.colorGradingTexture.getSize().height;\n effect.setFloat4(\"colorTransformSettings\", (textureSize - 1) / textureSize, // textureScale\n 0.5 / textureSize, // textureOffset\n textureSize, // textureSize\n this.colorGradingTexture.level // weight\n );\n }\n }\n /**\n * Clones the current image processing instance.\n * @returns The cloned image processing\n */\n clone() {\n return SerializationHelper.Clone(() => new ImageProcessingConfiguration(), this);\n }\n /**\n * Serializes the current image processing instance to a json representation.\n * @returns a JSON representation\n */\n serialize() {\n return SerializationHelper.Serialize(this);\n }\n /**\n * Parses the image processing from a json representation.\n * @param source the JSON source to parse\n * @returns The parsed image processing\n */\n static Parse(source) {\n const parsed = SerializationHelper.Parse(() => new ImageProcessingConfiguration(), source, null, null);\n // Backward compatibility\n if (source.vignetteCentreX !== undefined) {\n parsed.vignetteCenterX = source.vignetteCentreX;\n }\n if (source.vignetteCentreY !== undefined) {\n parsed.vignetteCenterY = source.vignetteCentreY;\n }\n return parsed;\n }\n /**\n * Used to apply the vignette as a mix with the pixel color.\n */\n static get VIGNETTEMODE_MULTIPLY() {\n return this._VIGNETTEMODE_MULTIPLY;\n }\n /**\n * Used to apply the vignette as a replacement of the pixel color.\n */\n static get VIGNETTEMODE_OPAQUE() {\n return this._VIGNETTEMODE_OPAQUE;\n }\n}\n/**\n * Default tone mapping applied in BabylonJS.\n */\nImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;\n/**\n * ACES Tone mapping (used by default in unreal and unity). This can help getting closer\n * to other engines rendering to increase portability.\n */\nImageProcessingConfiguration.TONEMAPPING_ACES = 1;\n// Static constants associated to the image processing.\nImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;\nImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;\n__decorate([\n serializeAsColorCurves()\n], ImageProcessingConfiguration.prototype, \"colorCurves\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_colorCurvesEnabled\", void 0);\n__decorate([\n serializeAsTexture(\"colorGradingTexture\")\n], ImageProcessingConfiguration.prototype, \"_colorGradingTexture\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_colorGradingEnabled\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_colorGradingWithGreenDepth\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_colorGradingBGR\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_exposure\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_toneMappingEnabled\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_toneMappingType\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_contrast\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"vignetteStretch\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"vignetteCenterX\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"vignetteCenterY\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"vignetteWeight\", void 0);\n__decorate([\n serializeAsColor4()\n], ImageProcessingConfiguration.prototype, \"vignetteColor\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"vignetteCameraFov\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_vignetteBlendMode\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_vignetteEnabled\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_ditheringEnabled\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_ditheringIntensity\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_skipFinalColorClamp\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_applyByPostProcess\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_isEnabled\", void 0);\n// References the dependencies.\nSerializationHelper._ImageProcessingConfigurationParser = ImageProcessingConfiguration.Parse;\n//# sourceMappingURL=imageProcessingConfiguration.js.map","import { __decorate } from \"../tslib.es6.js\";\n\nimport { SerializationHelper, serialize } from \"../Misc/decorators.js\";\n/**\n * Class that holds the different stencil states of a material\n * Usage example: https://playground.babylonjs.com/#CW5PRI#10\n */\nexport class MaterialStencilState {\n /**\n * Creates a material stencil state instance\n */\n constructor() {\n this.reset();\n }\n /**\n * Resets all the stencil states to default values\n */\n reset() {\n this.enabled = false;\n this.mask = 0xff;\n this.func = 519;\n this.funcRef = 1;\n this.funcMask = 0xff;\n this.opStencilFail = 7680;\n this.opDepthFail = 7680;\n this.opStencilDepthPass = 7681;\n }\n /**\n * Gets or sets the stencil function\n */\n get func() {\n return this._func;\n }\n set func(value) {\n this._func = value;\n }\n /**\n * Gets or sets the stencil function reference\n */\n get funcRef() {\n return this._funcRef;\n }\n set funcRef(value) {\n this._funcRef = value;\n }\n /**\n * Gets or sets the stencil function mask\n */\n get funcMask() {\n return this._funcMask;\n }\n set funcMask(value) {\n this._funcMask = value;\n }\n /**\n * Gets or sets the operation when the stencil test fails\n */\n get opStencilFail() {\n return this._opStencilFail;\n }\n set opStencilFail(value) {\n this._opStencilFail = value;\n }\n /**\n * Gets or sets the operation when the depth test fails\n */\n get opDepthFail() {\n return this._opDepthFail;\n }\n set opDepthFail(value) {\n this._opDepthFail = value;\n }\n /**\n * Gets or sets the operation when the stencil+depth test succeeds\n */\n get opStencilDepthPass() {\n return this._opStencilDepthPass;\n }\n set opStencilDepthPass(value) {\n this._opStencilDepthPass = value;\n }\n /**\n * Gets or sets the stencil mask\n */\n get mask() {\n return this._mask;\n }\n set mask(value) {\n this._mask = value;\n }\n /**\n * Enables or disables the stencil test\n */\n get enabled() {\n return this._enabled;\n }\n set enabled(value) {\n this._enabled = value;\n }\n /**\n * Get the current class name, useful for serialization or dynamic coding.\n * @returns \"MaterialStencilState\"\n */\n getClassName() {\n return \"MaterialStencilState\";\n }\n /**\n * Makes a duplicate of the current configuration into another one.\n * @param stencilState defines stencil state where to copy the info\n */\n copyTo(stencilState) {\n SerializationHelper.Clone(() => stencilState, this);\n }\n /**\n * Serializes this stencil configuration.\n * @returns - An object with the serialized config.\n */\n serialize() {\n return SerializationHelper.Serialize(this);\n }\n /**\n * Parses a stencil state configuration from a serialized object.\n * @param source - Serialized object.\n * @param scene Defines the scene we are parsing for\n * @param rootUrl Defines the rootUrl to load from\n */\n parse(source, scene, rootUrl) {\n SerializationHelper.Parse(() => this, source, scene, rootUrl);\n }\n}\n__decorate([\n serialize()\n], MaterialStencilState.prototype, \"func\", null);\n__decorate([\n serialize()\n], MaterialStencilState.prototype, \"funcRef\", null);\n__decorate([\n serialize()\n], MaterialStencilState.prototype, \"funcMask\", null);\n__decorate([\n serialize()\n], MaterialStencilState.prototype, \"opStencilFail\", null);\n__decorate([\n serialize()\n], MaterialStencilState.prototype, \"opDepthFail\", null);\n__decorate([\n serialize()\n], MaterialStencilState.prototype, \"opStencilDepthPass\", null);\n__decorate([\n serialize()\n], MaterialStencilState.prototype, \"mask\", null);\n__decorate([\n serialize()\n], MaterialStencilState.prototype, \"enabled\", null);\n//# sourceMappingURL=materialStencilState.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize, SerializationHelper } from \"../Misc/decorators.js\";\nimport { Tools } from \"../Misc/tools.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { SubMesh } from \"../Meshes/subMesh.js\";\nimport { UniformBuffer } from \"./uniformBuffer.js\";\n\nimport { Logger } from \"../Misc/logger.js\";\nimport { Plane } from \"../Maths/math.plane.js\";\nimport { MaterialHelper } from \"./materialHelper.js\";\nimport { DrawWrapper } from \"./drawWrapper.js\";\nimport { MaterialStencilState } from \"./materialStencilState.js\";\nimport { ScenePerformancePriority } from \"../scene.js\";\nimport { MaterialPluginEvent } from \"./materialPluginEvent.js\";\n/**\n * Base class for the main features of a material in Babylon.js\n */\nexport class Material {\n /**\n * If the material can be rendered to several textures with MRT extension\n */\n get canRenderToMRT() {\n // By default, shaders are not compatible with MRTs\n // Base classes should override that if their shader supports MRT\n return false;\n }\n /**\n * Sets the alpha value of the material\n */\n set alpha(value) {\n if (this._alpha === value) {\n return;\n }\n const oldValue = this._alpha;\n this._alpha = value;\n // Only call dirty when there is a state change (no alpha / alpha)\n if (oldValue === 1 || value === 1) {\n this.markAsDirty(Material.MiscDirtyFlag + Material.PrePassDirtyFlag);\n }\n }\n /**\n * Gets the alpha value of the material\n */\n get alpha() {\n return this._alpha;\n }\n /**\n * Sets the culling state (true to enable culling, false to disable)\n */\n set backFaceCulling(value) {\n if (this._backFaceCulling === value) {\n return;\n }\n this._backFaceCulling = value;\n this.markAsDirty(Material.TextureDirtyFlag);\n }\n /**\n * Gets the culling state\n */\n get backFaceCulling() {\n return this._backFaceCulling;\n }\n /**\n * Sets the type of faces that should be culled (true for back faces, false for front faces)\n */\n set cullBackFaces(value) {\n if (this._cullBackFaces === value) {\n return;\n }\n this._cullBackFaces = value;\n this.markAsDirty(Material.TextureDirtyFlag);\n }\n /**\n * Gets the type of faces that should be culled\n */\n get cullBackFaces() {\n return this._cullBackFaces;\n }\n /**\n * Block the dirty-mechanism for this specific material\n * When set to false after being true the material will be marked as dirty.\n */\n get blockDirtyMechanism() {\n return this._blockDirtyMechanism;\n }\n set blockDirtyMechanism(value) {\n if (this._blockDirtyMechanism === value) {\n return;\n }\n this._blockDirtyMechanism = value;\n if (!value) {\n this.markDirty();\n }\n }\n /**\n * This allows you to modify the material without marking it as dirty after every change.\n * This function should be used if you need to make more than one dirty-enabling change to the material - adding a texture, setting a new fill mode and so on.\n * The callback will pass the material as an argument, so you can make your changes to it.\n * @param callback the callback to be executed that will update the material\n */\n atomicMaterialsUpdate(callback) {\n this.blockDirtyMechanism = true;\n try {\n callback(this);\n }\n finally {\n this.blockDirtyMechanism = false;\n }\n }\n /**\n * Gets a boolean indicating that current material needs to register RTT\n */\n get hasRenderTargetTextures() {\n this._eventInfo.hasRenderTargetTextures = false;\n this._callbackPluginEventHasRenderTargetTextures(this._eventInfo);\n return this._eventInfo.hasRenderTargetTextures;\n }\n /**\n * Called during a dispose event\n */\n set onDispose(callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n }\n /**\n * An event triggered when the material is bound\n */\n get onBindObservable() {\n if (!this._onBindObservable) {\n this._onBindObservable = new Observable();\n }\n return this._onBindObservable;\n }\n /**\n * Called during a bind event\n */\n set onBind(callback) {\n if (this._onBindObserver) {\n this.onBindObservable.remove(this._onBindObserver);\n }\n this._onBindObserver = this.onBindObservable.add(callback);\n }\n /**\n * An event triggered when the material is unbound\n */\n get onUnBindObservable() {\n if (!this._onUnBindObservable) {\n this._onUnBindObservable = new Observable();\n }\n return this._onUnBindObservable;\n }\n /**\n * An event triggered when the effect is (re)created\n */\n get onEffectCreatedObservable() {\n if (!this._onEffectCreatedObservable) {\n this._onEffectCreatedObservable = new Observable();\n }\n return this._onEffectCreatedObservable;\n }\n /**\n * Sets the value of the alpha mode.\n *\n * | Value | Type | Description |\n * | --- | --- | --- |\n * | 0 | ALPHA_DISABLE | |\n * | 1 | ALPHA_ADD | |\n * | 2 | ALPHA_COMBINE | |\n * | 3 | ALPHA_SUBTRACT | |\n * | 4 | ALPHA_MULTIPLY | |\n * | 5 | ALPHA_MAXIMIZED | |\n * | 6 | ALPHA_ONEONE | |\n * | 7 | ALPHA_PREMULTIPLIED | |\n * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |\n * | 9 | ALPHA_INTERPOLATE | |\n * | 10 | ALPHA_SCREENMODE | |\n *\n */\n set alphaMode(value) {\n if (this._alphaMode === value) {\n return;\n }\n this._alphaMode = value;\n this.markAsDirty(Material.TextureDirtyFlag);\n }\n /**\n * Gets the value of the alpha mode\n */\n get alphaMode() {\n return this._alphaMode;\n }\n /**\n * Sets the need depth pre-pass value\n */\n set needDepthPrePass(value) {\n if (this._needDepthPrePass === value) {\n return;\n }\n this._needDepthPrePass = value;\n if (this._needDepthPrePass) {\n this.checkReadyOnEveryCall = true;\n }\n }\n /**\n * Gets the depth pre-pass value\n */\n get needDepthPrePass() {\n return this._needDepthPrePass;\n }\n /**\n * Can this material render to prepass\n */\n get isPrePassCapable() {\n return false;\n }\n /**\n * Sets the state for enabling fog\n */\n set fogEnabled(value) {\n if (this._fogEnabled === value) {\n return;\n }\n this._fogEnabled = value;\n this.markAsDirty(Material.MiscDirtyFlag);\n }\n /**\n * Gets the value of the fog enabled state\n */\n get fogEnabled() {\n return this._fogEnabled;\n }\n get wireframe() {\n switch (this._fillMode) {\n case Material.WireFrameFillMode:\n case Material.LineListDrawMode:\n case Material.LineLoopDrawMode:\n case Material.LineStripDrawMode:\n return true;\n }\n return this._scene.forceWireframe;\n }\n /**\n * Sets the state of wireframe mode\n */\n set wireframe(value) {\n this.fillMode = value ? Material.WireFrameFillMode : Material.TriangleFillMode;\n }\n /**\n * Gets the value specifying if point clouds are enabled\n */\n get pointsCloud() {\n switch (this._fillMode) {\n case Material.PointFillMode:\n case Material.PointListDrawMode:\n return true;\n }\n return this._scene.forcePointsCloud;\n }\n /**\n * Sets the state of point cloud mode\n */\n set pointsCloud(value) {\n this.fillMode = value ? Material.PointFillMode : Material.TriangleFillMode;\n }\n /**\n * Gets the material fill mode\n */\n get fillMode() {\n return this._fillMode;\n }\n /**\n * Sets the material fill mode\n */\n set fillMode(value) {\n if (this._fillMode === value) {\n return;\n }\n this._fillMode = value;\n this.markAsDirty(Material.MiscDirtyFlag);\n }\n /** @internal */\n _getDrawWrapper() {\n return this._drawWrapper;\n }\n /**\n * @internal\n */\n _setDrawWrapper(drawWrapper) {\n this._drawWrapper = drawWrapper;\n }\n /**\n * Creates a material instance\n * @param name defines the name of the material\n * @param scene defines the scene to reference\n * @param doNotAdd specifies if the material should be added to the scene\n */\n constructor(name, scene, doNotAdd) {\n /**\n * Custom shadow depth material to use for shadow rendering instead of the in-built one\n */\n this.shadowDepthWrapper = null;\n /**\n * Gets or sets a boolean indicating that the material is allowed (if supported) to do shader hot swapping.\n * This means that the material can keep using a previous shader while a new one is being compiled.\n * This is mostly used when shader parallel compilation is supported (true by default)\n */\n this.allowShaderHotSwapping = true;\n /**\n * Gets or sets user defined metadata\n */\n this.metadata = null;\n /**\n * For internal use only. Please do not use.\n */\n this.reservedDataStore = null;\n /**\n * Specifies if the ready state should be checked on each call\n */\n this.checkReadyOnEveryCall = false;\n /**\n * Specifies if the ready state should be checked once\n */\n this.checkReadyOnlyOnce = false;\n /**\n * The state of the material\n */\n this.state = \"\";\n /**\n * The alpha value of the material\n */\n this._alpha = 1.0;\n /**\n * Specifies if back face culling is enabled\n */\n this._backFaceCulling = true;\n /**\n * Specifies if back or front faces should be culled (when culling is enabled)\n */\n this._cullBackFaces = true;\n this._blockDirtyMechanism = false;\n /**\n * Callback triggered when the material is compiled\n */\n this.onCompiled = null;\n /**\n * Callback triggered when an error occurs\n */\n this.onError = null;\n /**\n * Callback triggered to get the render target textures\n */\n this.getRenderTargetTextures = null;\n /**\n * Specifies if the material should be serialized\n */\n this.doNotSerialize = false;\n /**\n * @internal\n */\n this._storeEffectOnSubMeshes = false;\n /**\n * Stores the animations for the material\n */\n this.animations = null;\n /**\n * An event triggered when the material is disposed\n */\n this.onDisposeObservable = new Observable();\n /**\n * An observer which watches for dispose events\n */\n this._onDisposeObserver = null;\n this._onUnBindObservable = null;\n /**\n * An observer which watches for bind events\n */\n this._onBindObserver = null;\n /**\n * Stores the value of the alpha mode\n */\n this._alphaMode = 2;\n /**\n * Stores the state of the need depth pre-pass value\n */\n this._needDepthPrePass = false;\n /**\n * Specifies if depth writing should be disabled\n */\n this.disableDepthWrite = false;\n /**\n * Specifies if color writing should be disabled\n */\n this.disableColorWrite = false;\n /**\n * Specifies if depth writing should be forced\n */\n this.forceDepthWrite = false;\n /**\n * Specifies the depth function that should be used. 0 means the default engine function\n */\n this.depthFunction = 0;\n /**\n * Specifies if there should be a separate pass for culling\n */\n this.separateCullingPass = false;\n /**\n * Stores the state specifying if fog should be enabled\n */\n this._fogEnabled = true;\n /**\n * Stores the size of points\n */\n this.pointSize = 1.0;\n /**\n * Stores the z offset Factor value\n */\n this.zOffset = 0;\n /**\n * Stores the z offset Units value\n */\n this.zOffsetUnits = 0;\n /**\n * Gives access to the stencil properties of the material\n */\n this.stencil = new MaterialStencilState();\n /**\n * Specifies if uniform buffers should be used\n */\n this._useUBO = false;\n /**\n * Stores the fill mode state\n */\n this._fillMode = Material.TriangleFillMode;\n /**\n * Specifies if the depth write state should be cached\n */\n this._cachedDepthWriteState = false;\n /**\n * Specifies if the color write state should be cached\n */\n this._cachedColorWriteState = false;\n /**\n * Specifies if the depth function state should be cached\n */\n this._cachedDepthFunctionState = 0;\n /** @internal */\n this._indexInSceneMaterialArray = -1;\n /** @internal */\n this.meshMap = null;\n /** @internal */\n this._parentContainer = null;\n /** @internal */\n this._uniformBufferLayoutBuilt = false;\n this._eventInfo = {}; // will be initialized before each event notification\n /** @internal */\n this._callbackPluginEventGeneric = () => void 0;\n /** @internal */\n this._callbackPluginEventIsReadyForSubMesh = () => void 0;\n /** @internal */\n this._callbackPluginEventPrepareDefines = () => void 0;\n /** @internal */\n this._callbackPluginEventPrepareDefinesBeforeAttributes = () => void 0;\n /** @internal */\n this._callbackPluginEventHardBindForSubMesh = () => void 0;\n /** @internal */\n this._callbackPluginEventBindForSubMesh = () => void 0;\n /** @internal */\n this._callbackPluginEventHasRenderTargetTextures = () => void 0;\n /** @internal */\n this._callbackPluginEventFillRenderTargetTextures = () => void 0;\n /**\n * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.\n */\n this._forceAlphaTest = false;\n /**\n * The transparency mode of the material.\n */\n this._transparencyMode = null;\n this.name = name;\n const setScene = scene || EngineStore.LastCreatedScene;\n if (!setScene) {\n return;\n }\n this._scene = setScene;\n this._dirtyCallbacks = {};\n this._dirtyCallbacks[1] = this._markAllSubMeshesAsTexturesDirty.bind(this);\n this._dirtyCallbacks[2] = this._markAllSubMeshesAsLightsDirty.bind(this);\n this._dirtyCallbacks[4] = this._markAllSubMeshesAsFresnelDirty.bind(this);\n this._dirtyCallbacks[8] = this._markAllSubMeshesAsAttributesDirty.bind(this);\n this._dirtyCallbacks[16] = this._markAllSubMeshesAsMiscDirty.bind(this);\n this._dirtyCallbacks[32] = this._markAllSubMeshesAsPrePassDirty.bind(this);\n this._dirtyCallbacks[63] = this._markAllSubMeshesAsAllDirty.bind(this);\n this.id = name || Tools.RandomId();\n this.uniqueId = this._scene.getUniqueId();\n this._materialContext = this._scene.getEngine().createMaterialContext();\n this._drawWrapper = new DrawWrapper(this._scene.getEngine(), false);\n this._drawWrapper.materialContext = this._materialContext;\n if (this._scene.useRightHandedSystem) {\n this.sideOrientation = Material.ClockWiseSideOrientation;\n }\n else {\n this.sideOrientation = Material.CounterClockWiseSideOrientation;\n }\n this._uniformBuffer = new UniformBuffer(this._scene.getEngine(), undefined, undefined, name);\n this._useUBO = this.getScene().getEngine().supportsUniformBuffers;\n if (!doNotAdd) {\n this._scene.addMaterial(this);\n }\n if (this._scene.useMaterialMeshMap) {\n this.meshMap = {};\n }\n Material.OnEventObservable.notifyObservers(this, MaterialPluginEvent.Created);\n }\n /**\n * Returns a string representation of the current material\n * @param fullDetails defines a boolean indicating which levels of logging is desired\n * @returns a string with material information\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n toString(fullDetails) {\n const ret = \"Name: \" + this.name;\n return ret;\n }\n /**\n * Gets the class name of the material\n * @returns a string with the class name of the material\n */\n getClassName() {\n return \"Material\";\n }\n /** @internal */\n get _isMaterial() {\n return true;\n }\n /**\n * Specifies if updates for the material been locked\n */\n get isFrozen() {\n return this.checkReadyOnlyOnce;\n }\n /**\n * Locks updates for the material\n */\n freeze() {\n this.markDirty();\n this.checkReadyOnlyOnce = true;\n }\n /**\n * Unlocks updates for the material\n */\n unfreeze() {\n this.markDirty();\n this.checkReadyOnlyOnce = false;\n }\n /**\n * Specifies if the material is ready to be used\n * @param mesh defines the mesh to check\n * @param useInstances specifies if instances should be used\n * @returns a boolean indicating if the material is ready to be used\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isReady(mesh, useInstances) {\n return true;\n }\n /**\n * Specifies that the submesh is ready to be used\n * @param mesh defines the mesh to check\n * @param subMesh defines which submesh to check\n * @param useInstances specifies that instances should be used\n * @returns a boolean indicating that the submesh is ready or not\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isReadyForSubMesh(mesh, subMesh, useInstances) {\n const defines = subMesh.materialDefines;\n if (!defines) {\n return false;\n }\n this._eventInfo.isReadyForSubMesh = true;\n this._eventInfo.defines = defines;\n this._callbackPluginEventIsReadyForSubMesh(this._eventInfo);\n return this._eventInfo.isReadyForSubMesh;\n }\n /**\n * Returns the material effect\n * @returns the effect associated with the material\n */\n getEffect() {\n return this._drawWrapper.effect;\n }\n /**\n * Returns the current scene\n * @returns a Scene\n */\n getScene() {\n return this._scene;\n }\n /**\n * Gets the current transparency mode.\n */\n get transparencyMode() {\n return this._transparencyMode;\n }\n /**\n * Sets the transparency mode of the material.\n *\n * | Value | Type | Description |\n * | ----- | ----------------------------------- | ----------- |\n * | 0 | OPAQUE | |\n * | 1 | ALPHATEST | |\n * | 2 | ALPHABLEND | |\n * | 3 | ALPHATESTANDBLEND | |\n *\n */\n set transparencyMode(value) {\n if (this._transparencyMode === value) {\n return;\n }\n this._transparencyMode = value;\n this._forceAlphaTest = value === Material.MATERIAL_ALPHATESTANDBLEND;\n this._markAllSubMeshesAsTexturesAndMiscDirty();\n }\n /**\n * Returns true if alpha blending should be disabled.\n */\n get _disableAlphaBlending() {\n return this._transparencyMode === Material.MATERIAL_OPAQUE || this._transparencyMode === Material.MATERIAL_ALPHATEST;\n }\n /**\n * Specifies whether or not this material should be rendered in alpha blend mode.\n * @returns a boolean specifying if alpha blending is needed\n */\n needAlphaBlending() {\n if (this._disableAlphaBlending) {\n return false;\n }\n return this.alpha < 1.0;\n }\n /**\n * Specifies if the mesh will require alpha blending\n * @param mesh defines the mesh to check\n * @returns a boolean specifying if alpha blending is needed for the mesh\n */\n needAlphaBlendingForMesh(mesh) {\n if (mesh.visibility < 1.0) {\n return true;\n }\n if (this._disableAlphaBlending) {\n return false;\n }\n return mesh.hasVertexAlpha || this.needAlphaBlending();\n }\n /**\n * Specifies whether or not this material should be rendered in alpha test mode.\n * @returns a boolean specifying if an alpha test is needed.\n */\n needAlphaTesting() {\n if (this._forceAlphaTest) {\n return true;\n }\n return false;\n }\n /**\n * Specifies if material alpha testing should be turned on for the mesh\n * @param mesh defines the mesh to check\n */\n _shouldTurnAlphaTestOn(mesh) {\n return !this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting();\n }\n /**\n * Gets the texture used for the alpha test\n * @returns the texture to use for alpha testing\n */\n getAlphaTestTexture() {\n return null;\n }\n /**\n * Marks the material to indicate that it needs to be re-calculated\n * @param forceMaterialDirty - Forces the material to be marked as dirty for all components (same as this.markAsDirty(Material.AllDirtyFlag)). You should use this flag if the material is frozen and you want to force a recompilation.\n */\n markDirty(forceMaterialDirty = false) {\n const meshes = this.getScene().meshes;\n for (const mesh of meshes) {\n if (!mesh.subMeshes) {\n continue;\n }\n for (const subMesh of mesh.subMeshes) {\n if (subMesh.getMaterial() !== this) {\n continue;\n }\n if (!subMesh.effect) {\n continue;\n }\n subMesh.effect._wasPreviouslyReady = false;\n subMesh.effect._wasPreviouslyUsingInstances = null;\n subMesh.effect._forceRebindOnNextCall = forceMaterialDirty;\n }\n }\n if (forceMaterialDirty) {\n this.markAsDirty(Material.AllDirtyFlag);\n }\n }\n /**\n * @internal\n */\n _preBind(effect, overrideOrientation = null) {\n const engine = this._scene.getEngine();\n const orientation = overrideOrientation == null ? this.sideOrientation : overrideOrientation;\n const reverse = orientation === Material.ClockWiseSideOrientation;\n engine.enableEffect(effect ? effect : this._getDrawWrapper());\n engine.setState(this.backFaceCulling, this.zOffset, false, reverse, this._scene._mirroredCameraPosition ? !this.cullBackFaces : this.cullBackFaces, this.stencil, this.zOffsetUnits);\n return reverse;\n }\n /**\n * Binds the material to the mesh\n * @param world defines the world transformation matrix\n * @param mesh defines the mesh to bind the material to\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n bind(world, mesh) { }\n /**\n * Initializes the uniform buffer layout for the shader.\n */\n buildUniformLayout() {\n const ubo = this._uniformBuffer;\n this._eventInfo.ubo = ubo;\n this._callbackPluginEventGeneric(MaterialPluginEvent.PrepareUniformBuffer, this._eventInfo);\n ubo.create();\n this._uniformBufferLayoutBuilt = true;\n }\n /**\n * Binds the submesh to the material\n * @param world defines the world transformation matrix\n * @param mesh defines the mesh containing the submesh\n * @param subMesh defines the submesh to bind the material to\n */\n bindForSubMesh(world, mesh, subMesh) {\n const effect = subMesh.effect;\n if (!effect) {\n return;\n }\n this._eventInfo.subMesh = subMesh;\n this._callbackPluginEventBindForSubMesh(this._eventInfo);\n effect._forceRebindOnNextCall = false;\n }\n /**\n * Binds the world matrix to the material\n * @param world defines the world transformation matrix\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n bindOnlyWorldMatrix(world) { }\n /**\n * Binds the view matrix to the effect\n * @param effect defines the effect to bind the view matrix to\n */\n bindView(effect) {\n if (!this._useUBO) {\n effect.setMatrix(\"view\", this.getScene().getViewMatrix());\n }\n else {\n this._needToBindSceneUbo = true;\n }\n }\n /**\n * Binds the view projection and projection matrices to the effect\n * @param effect defines the effect to bind the view projection and projection matrices to\n */\n bindViewProjection(effect) {\n if (!this._useUBO) {\n effect.setMatrix(\"viewProjection\", this.getScene().getTransformMatrix());\n effect.setMatrix(\"projection\", this.getScene().getProjectionMatrix());\n }\n else {\n this._needToBindSceneUbo = true;\n }\n }\n /**\n * Binds the view matrix to the effect\n * @param effect defines the effect to bind the view matrix to\n * @param variableName name of the shader variable that will hold the eye position\n */\n bindEyePosition(effect, variableName) {\n if (!this._useUBO) {\n this._scene.bindEyePosition(effect, variableName);\n }\n else {\n this._needToBindSceneUbo = true;\n }\n }\n /**\n * Processes to execute after binding the material to a mesh\n * @param mesh defines the rendered mesh\n * @param effect\n */\n _afterBind(mesh, effect = null) {\n this._scene._cachedMaterial = this;\n if (this._needToBindSceneUbo) {\n if (effect) {\n this._needToBindSceneUbo = false;\n MaterialHelper.BindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());\n this._scene.finalizeSceneUbo();\n }\n }\n if (mesh) {\n this._scene._cachedVisibility = mesh.visibility;\n }\n else {\n this._scene._cachedVisibility = 1;\n }\n if (this._onBindObservable && mesh) {\n this._onBindObservable.notifyObservers(mesh);\n }\n if (this.disableDepthWrite) {\n const engine = this._scene.getEngine();\n this._cachedDepthWriteState = engine.getDepthWrite();\n engine.setDepthWrite(false);\n }\n if (this.disableColorWrite) {\n const engine = this._scene.getEngine();\n this._cachedColorWriteState = engine.getColorWrite();\n engine.setColorWrite(false);\n }\n if (this.depthFunction !== 0) {\n const engine = this._scene.getEngine();\n this._cachedDepthFunctionState = engine.getDepthFunction() || 0;\n engine.setDepthFunction(this.depthFunction);\n }\n }\n /**\n * Unbinds the material from the mesh\n */\n unbind() {\n if (this._onUnBindObservable) {\n this._onUnBindObservable.notifyObservers(this);\n }\n if (this.depthFunction !== 0) {\n const engine = this._scene.getEngine();\n engine.setDepthFunction(this._cachedDepthFunctionState);\n }\n if (this.disableDepthWrite) {\n const engine = this._scene.getEngine();\n engine.setDepthWrite(this._cachedDepthWriteState);\n }\n if (this.disableColorWrite) {\n const engine = this._scene.getEngine();\n engine.setColorWrite(this._cachedColorWriteState);\n }\n }\n /**\n * Returns the animatable textures.\n * @returns - Array of animatable textures.\n */\n getAnimatables() {\n this._eventInfo.animatables = [];\n this._callbackPluginEventGeneric(MaterialPluginEvent.GetAnimatables, this._eventInfo);\n return this._eventInfo.animatables;\n }\n /**\n * Gets the active textures from the material\n * @returns an array of textures\n */\n getActiveTextures() {\n this._eventInfo.activeTextures = [];\n this._callbackPluginEventGeneric(MaterialPluginEvent.GetActiveTextures, this._eventInfo);\n return this._eventInfo.activeTextures;\n }\n /**\n * Specifies if the material uses a texture\n * @param texture defines the texture to check against the material\n * @returns a boolean specifying if the material uses the texture\n */\n hasTexture(texture) {\n this._eventInfo.hasTexture = false;\n this._eventInfo.texture = texture;\n this._callbackPluginEventGeneric(MaterialPluginEvent.HasTexture, this._eventInfo);\n return this._eventInfo.hasTexture;\n }\n /**\n * Makes a duplicate of the material, and gives it a new name\n * @param name defines the new name for the duplicated material\n * @returns the cloned material\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n clone(name) {\n return null;\n }\n _clonePlugins(targetMaterial, rootUrl) {\n const serializationObject = {};\n // Create plugins in targetMaterial in case they don't exist\n this._serializePlugins(serializationObject);\n Material._parsePlugins(serializationObject, targetMaterial, this._scene, rootUrl);\n // Copy the properties of the current plugins to the cloned material's plugins\n if (this.pluginManager) {\n for (const plugin of this.pluginManager._plugins) {\n const targetPlugin = targetMaterial.pluginManager.getPlugin(plugin.name);\n plugin.copyTo(targetPlugin);\n }\n }\n }\n /**\n * Gets the meshes bound to the material\n * @returns an array of meshes bound to the material\n */\n getBindedMeshes() {\n if (this.meshMap) {\n const result = new Array();\n for (const meshId in this.meshMap) {\n const mesh = this.meshMap[meshId];\n if (mesh) {\n result.push(mesh);\n }\n }\n return result;\n }\n else {\n const meshes = this._scene.meshes;\n return meshes.filter((mesh) => mesh.material === this);\n }\n }\n /**\n * Force shader compilation\n * @param mesh defines the mesh associated with this material\n * @param onCompiled defines a function to execute once the material is compiled\n * @param options defines the options to configure the compilation\n * @param onError defines a function to execute if the material fails compiling\n */\n forceCompilation(mesh, onCompiled, options, onError) {\n const localOptions = Object.assign({ clipPlane: false, useInstances: false }, options);\n const scene = this.getScene();\n const currentHotSwapingState = this.allowShaderHotSwapping;\n this.allowShaderHotSwapping = false; // Turned off to let us evaluate the real compilation state\n const checkReady = () => {\n if (!this._scene || !this._scene.getEngine()) {\n return;\n }\n const clipPlaneState = scene.clipPlane;\n if (localOptions.clipPlane) {\n scene.clipPlane = new Plane(0, 0, 0, 1);\n }\n if (this._storeEffectOnSubMeshes) {\n let allDone = true, lastError = null;\n if (mesh.subMeshes) {\n const tempSubMesh = new SubMesh(0, 0, 0, 0, 0, mesh, undefined, false, false);\n if (tempSubMesh.materialDefines) {\n tempSubMesh.materialDefines._renderId = -1;\n }\n if (!this.isReadyForSubMesh(mesh, tempSubMesh, localOptions.useInstances)) {\n if (tempSubMesh.effect && tempSubMesh.effect.getCompilationError() && tempSubMesh.effect.allFallbacksProcessed()) {\n lastError = tempSubMesh.effect.getCompilationError();\n }\n else {\n allDone = false;\n setTimeout(checkReady, 16);\n }\n }\n }\n if (allDone) {\n this.allowShaderHotSwapping = currentHotSwapingState;\n if (lastError) {\n if (onError) {\n onError(lastError);\n }\n }\n if (onCompiled) {\n onCompiled(this);\n }\n }\n }\n else {\n if (this.isReady()) {\n this.allowShaderHotSwapping = currentHotSwapingState;\n if (onCompiled) {\n onCompiled(this);\n }\n }\n else {\n setTimeout(checkReady, 16);\n }\n }\n if (localOptions.clipPlane) {\n scene.clipPlane = clipPlaneState;\n }\n };\n checkReady();\n }\n /**\n * Force shader compilation\n * @param mesh defines the mesh that will use this material\n * @param options defines additional options for compiling the shaders\n * @returns a promise that resolves when the compilation completes\n */\n forceCompilationAsync(mesh, options) {\n return new Promise((resolve, reject) => {\n this.forceCompilation(mesh, () => {\n resolve();\n }, options, (reason) => {\n reject(reason);\n });\n });\n }\n /**\n * Marks a define in the material to indicate that it needs to be re-computed\n * @param flag defines a flag used to determine which parts of the material have to be marked as dirty\n */\n markAsDirty(flag) {\n if (this.getScene().blockMaterialDirtyMechanism || this._blockDirtyMechanism) {\n return;\n }\n Material._DirtyCallbackArray.length = 0;\n if (flag & Material.TextureDirtyFlag) {\n Material._DirtyCallbackArray.push(Material._TextureDirtyCallBack);\n }\n if (flag & Material.LightDirtyFlag) {\n Material._DirtyCallbackArray.push(Material._LightsDirtyCallBack);\n }\n if (flag & Material.FresnelDirtyFlag) {\n Material._DirtyCallbackArray.push(Material._FresnelDirtyCallBack);\n }\n if (flag & Material.AttributesDirtyFlag) {\n Material._DirtyCallbackArray.push(Material._AttributeDirtyCallBack);\n }\n if (flag & Material.MiscDirtyFlag) {\n Material._DirtyCallbackArray.push(Material._MiscDirtyCallBack);\n }\n if (flag & Material.PrePassDirtyFlag) {\n Material._DirtyCallbackArray.push(Material._PrePassDirtyCallBack);\n }\n if (Material._DirtyCallbackArray.length) {\n this._markAllSubMeshesAsDirty(Material._RunDirtyCallBacks);\n }\n this.getScene().resetCachedMaterial();\n }\n /**\n * Resets the draw wrappers cache for all submeshes that are using this material\n */\n resetDrawCache() {\n const meshes = this.getScene().meshes;\n for (const mesh of meshes) {\n if (!mesh.subMeshes) {\n continue;\n }\n for (const subMesh of mesh.subMeshes) {\n if (subMesh.getMaterial() !== this) {\n continue;\n }\n subMesh.resetDrawCache();\n }\n }\n }\n /**\n * Marks all submeshes of a material to indicate that their material defines need to be re-calculated\n * @param func defines a function which checks material defines against the submeshes\n */\n _markAllSubMeshesAsDirty(func) {\n if (this.getScene().blockMaterialDirtyMechanism || this._blockDirtyMechanism) {\n return;\n }\n const meshes = this.getScene().meshes;\n for (const mesh of meshes) {\n if (!mesh.subMeshes) {\n continue;\n }\n for (const subMesh of mesh.subMeshes) {\n // We want to skip the submeshes which are not using this material or which have not yet rendered at least once\n if (subMesh.getMaterial(false) !== this) {\n continue;\n }\n for (const drawWrapper of subMesh._drawWrappers) {\n if (!drawWrapper || !drawWrapper.defines || !drawWrapper.defines.markAllAsDirty) {\n continue;\n }\n if (this._materialContext === drawWrapper.materialContext) {\n func(drawWrapper.defines);\n }\n }\n }\n }\n }\n /**\n * Indicates that the scene should check if the rendering now needs a prepass\n */\n _markScenePrePassDirty() {\n if (this.getScene().blockMaterialDirtyMechanism || this._blockDirtyMechanism) {\n return;\n }\n const prePassRenderer = this.getScene().enablePrePassRenderer();\n if (prePassRenderer) {\n prePassRenderer.markAsDirty();\n }\n }\n /**\n * Indicates that we need to re-calculated for all submeshes\n */\n _markAllSubMeshesAsAllDirty() {\n this._markAllSubMeshesAsDirty(Material._AllDirtyCallBack);\n }\n /**\n * Indicates that image processing needs to be re-calculated for all submeshes\n */\n _markAllSubMeshesAsImageProcessingDirty() {\n this._markAllSubMeshesAsDirty(Material._ImageProcessingDirtyCallBack);\n }\n /**\n * Indicates that textures need to be re-calculated for all submeshes\n */\n _markAllSubMeshesAsTexturesDirty() {\n this._markAllSubMeshesAsDirty(Material._TextureDirtyCallBack);\n }\n /**\n * Indicates that fresnel needs to be re-calculated for all submeshes\n */\n _markAllSubMeshesAsFresnelDirty() {\n this._markAllSubMeshesAsDirty(Material._FresnelDirtyCallBack);\n }\n /**\n * Indicates that fresnel and misc need to be re-calculated for all submeshes\n */\n _markAllSubMeshesAsFresnelAndMiscDirty() {\n this._markAllSubMeshesAsDirty(Material._FresnelAndMiscDirtyCallBack);\n }\n /**\n * Indicates that lights need to be re-calculated for all submeshes\n */\n _markAllSubMeshesAsLightsDirty() {\n this._markAllSubMeshesAsDirty(Material._LightsDirtyCallBack);\n }\n /**\n * Indicates that attributes need to be re-calculated for all submeshes\n */\n _markAllSubMeshesAsAttributesDirty() {\n this._markAllSubMeshesAsDirty(Material._AttributeDirtyCallBack);\n }\n /**\n * Indicates that misc needs to be re-calculated for all submeshes\n */\n _markAllSubMeshesAsMiscDirty() {\n this._markAllSubMeshesAsDirty(Material._MiscDirtyCallBack);\n }\n /**\n * Indicates that prepass needs to be re-calculated for all submeshes\n */\n _markAllSubMeshesAsPrePassDirty() {\n this._markAllSubMeshesAsDirty(Material._MiscDirtyCallBack);\n }\n /**\n * Indicates that textures and misc need to be re-calculated for all submeshes\n */\n _markAllSubMeshesAsTexturesAndMiscDirty() {\n this._markAllSubMeshesAsDirty(Material._TextureAndMiscDirtyCallBack);\n }\n _checkScenePerformancePriority() {\n if (this._scene.performancePriority !== ScenePerformancePriority.BackwardCompatible) {\n this.checkReadyOnlyOnce = true;\n // re-set the flag when the perf priority changes\n const observer = this._scene.onScenePerformancePriorityChangedObservable.addOnce(() => {\n this.checkReadyOnlyOnce = false;\n });\n // if this material is disposed before the scene is disposed, cleanup the observer\n this.onDisposeObservable.add(() => {\n this._scene.onScenePerformancePriorityChangedObservable.remove(observer);\n });\n }\n }\n /**\n * Sets the required values to the prepass renderer.\n * @param prePassRenderer defines the prepass renderer to setup.\n * @returns true if the pre pass is needed.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n setPrePassRenderer(prePassRenderer) {\n // Do Nothing by default\n return false;\n }\n /**\n * Disposes the material\n * @param forceDisposeEffect specifies if effects should be forcefully disposed\n * @param forceDisposeTextures specifies if textures should be forcefully disposed\n * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh\n */\n dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {\n const scene = this.getScene();\n // Animations\n scene.stopAnimation(this);\n scene.freeProcessedMaterials();\n // Remove from scene\n scene.removeMaterial(this);\n this._eventInfo.forceDisposeTextures = forceDisposeTextures;\n this._callbackPluginEventGeneric(MaterialPluginEvent.Disposed, this._eventInfo);\n if (this._parentContainer) {\n const index = this._parentContainer.materials.indexOf(this);\n if (index > -1) {\n this._parentContainer.materials.splice(index, 1);\n }\n this._parentContainer = null;\n }\n if (notBoundToMesh !== true) {\n // Remove from meshes\n if (this.meshMap) {\n for (const meshId in this.meshMap) {\n const mesh = this.meshMap[meshId];\n if (mesh) {\n mesh.material = null; // will set the entry in the map to undefined\n this.releaseVertexArrayObject(mesh, forceDisposeEffect);\n }\n }\n }\n else {\n const meshes = scene.meshes;\n for (const mesh of meshes) {\n if (mesh.material === this && !mesh.sourceMesh) {\n mesh.material = null;\n this.releaseVertexArrayObject(mesh, forceDisposeEffect);\n }\n }\n }\n }\n this._uniformBuffer.dispose();\n // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect\n if (forceDisposeEffect && this._drawWrapper.effect) {\n if (!this._storeEffectOnSubMeshes) {\n this._drawWrapper.effect.dispose();\n }\n this._drawWrapper.effect = null;\n }\n this.metadata = null;\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n if (this._onBindObservable) {\n this._onBindObservable.clear();\n }\n if (this._onUnBindObservable) {\n this._onUnBindObservable.clear();\n }\n if (this._onEffectCreatedObservable) {\n this._onEffectCreatedObservable.clear();\n }\n if (this._eventInfo) {\n this._eventInfo = {};\n }\n }\n /**\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n releaseVertexArrayObject(mesh, forceDisposeEffect) {\n if (mesh.geometry) {\n const geometry = mesh.geometry;\n if (this._storeEffectOnSubMeshes) {\n for (const subMesh of mesh.subMeshes) {\n geometry._releaseVertexArrayObject(subMesh.effect);\n if (forceDisposeEffect && subMesh.effect) {\n subMesh.effect.dispose();\n }\n }\n }\n else {\n geometry._releaseVertexArrayObject(this._drawWrapper.effect);\n }\n }\n }\n /**\n * Serializes this material\n * @returns the serialized material object\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this);\n serializationObject.stencil = this.stencil.serialize();\n serializationObject.uniqueId = this.uniqueId;\n this._serializePlugins(serializationObject);\n return serializationObject;\n }\n _serializePlugins(serializationObject) {\n serializationObject.plugins = {};\n if (this.pluginManager) {\n for (const plugin of this.pluginManager._plugins) {\n serializationObject.plugins[plugin.getClassName()] = plugin.serialize();\n }\n }\n }\n /**\n * Creates a material from parsed material data\n * @param parsedMaterial defines parsed material data\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures\n * @returns a new material\n */\n static Parse(parsedMaterial, scene, rootUrl) {\n if (!parsedMaterial.customType) {\n parsedMaterial.customType = \"BABYLON.StandardMaterial\";\n }\n else if (parsedMaterial.customType === \"BABYLON.PBRMaterial\" && parsedMaterial.overloadedAlbedo) {\n parsedMaterial.customType = \"BABYLON.LegacyPBRMaterial\";\n if (!BABYLON.LegacyPBRMaterial) {\n Logger.Error(\"Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.\");\n return null;\n }\n }\n const materialType = Tools.Instantiate(parsedMaterial.customType);\n const material = materialType.Parse(parsedMaterial, scene, rootUrl);\n material._loadedUniqueId = parsedMaterial.uniqueId;\n return material;\n }\n static _parsePlugins(serializationObject, material, scene, rootUrl) {\n var _a;\n if (!serializationObject.plugins) {\n return;\n }\n for (const pluginClassName in serializationObject.plugins) {\n const pluginData = serializationObject.plugins[pluginClassName];\n let plugin = (_a = material.pluginManager) === null || _a === void 0 ? void 0 : _a.getPlugin(pluginData.name);\n if (!plugin) {\n const pluginClassType = Tools.Instantiate(\"BABYLON.\" + pluginClassName);\n if (pluginClassType) {\n plugin = new pluginClassType(material);\n }\n }\n plugin === null || plugin === void 0 ? void 0 : plugin.parse(pluginData, scene, rootUrl);\n }\n }\n}\n/**\n * Returns the triangle fill mode\n */\nMaterial.TriangleFillMode = 0;\n/**\n * Returns the wireframe mode\n */\nMaterial.WireFrameFillMode = 1;\n/**\n * Returns the point fill mode\n */\nMaterial.PointFillMode = 2;\n/**\n * Returns the point list draw mode\n */\nMaterial.PointListDrawMode = 3;\n/**\n * Returns the line list draw mode\n */\nMaterial.LineListDrawMode = 4;\n/**\n * Returns the line loop draw mode\n */\nMaterial.LineLoopDrawMode = 5;\n/**\n * Returns the line strip draw mode\n */\nMaterial.LineStripDrawMode = 6;\n/**\n * Returns the triangle strip draw mode\n */\nMaterial.TriangleStripDrawMode = 7;\n/**\n * Returns the triangle fan draw mode\n */\nMaterial.TriangleFanDrawMode = 8;\n/**\n * Stores the clock-wise side orientation\n */\nMaterial.ClockWiseSideOrientation = 0;\n/**\n * Stores the counter clock-wise side orientation\n */\nMaterial.CounterClockWiseSideOrientation = 1;\n/**\n * The dirty texture flag value\n */\nMaterial.TextureDirtyFlag = 1;\n/**\n * The dirty light flag value\n */\nMaterial.LightDirtyFlag = 2;\n/**\n * The dirty fresnel flag value\n */\nMaterial.FresnelDirtyFlag = 4;\n/**\n * The dirty attribute flag value\n */\nMaterial.AttributesDirtyFlag = 8;\n/**\n * The dirty misc flag value\n */\nMaterial.MiscDirtyFlag = 16;\n/**\n * The dirty prepass flag value\n */\nMaterial.PrePassDirtyFlag = 32;\n/**\n * The all dirty flag value\n */\nMaterial.AllDirtyFlag = 63;\n/**\n * MaterialTransparencyMode: No transparency mode, Alpha channel is not use.\n */\nMaterial.MATERIAL_OPAQUE = 0;\n/**\n * MaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.\n */\nMaterial.MATERIAL_ALPHATEST = 1;\n/**\n * MaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.\n */\nMaterial.MATERIAL_ALPHABLEND = 2;\n/**\n * MaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.\n * They are also discarded below the alpha cutoff threshold to improve performances.\n */\nMaterial.MATERIAL_ALPHATESTANDBLEND = 3;\n/**\n * The Whiteout method is used to blend normals.\n * Details of the algorithm can be found here: https://blog.selfshadow.com/publications/blending-in-detail/\n */\nMaterial.MATERIAL_NORMALBLENDMETHOD_WHITEOUT = 0;\n/**\n * The Reoriented Normal Mapping method is used to blend normals.\n * Details of the algorithm can be found here: https://blog.selfshadow.com/publications/blending-in-detail/\n */\nMaterial.MATERIAL_NORMALBLENDMETHOD_RNM = 1;\n/**\n * Event observable which raises global events common to all materials (like MaterialPluginEvent.Created)\n */\nMaterial.OnEventObservable = new Observable();\nMaterial._AllDirtyCallBack = (defines) => defines.markAllAsDirty();\nMaterial._ImageProcessingDirtyCallBack = (defines) => defines.markAsImageProcessingDirty();\nMaterial._TextureDirtyCallBack = (defines) => defines.markAsTexturesDirty();\nMaterial._FresnelDirtyCallBack = (defines) => defines.markAsFresnelDirty();\nMaterial._MiscDirtyCallBack = (defines) => defines.markAsMiscDirty();\nMaterial._PrePassDirtyCallBack = (defines) => defines.markAsPrePassDirty();\nMaterial._LightsDirtyCallBack = (defines) => defines.markAsLightDirty();\nMaterial._AttributeDirtyCallBack = (defines) => defines.markAsAttributesDirty();\nMaterial._FresnelAndMiscDirtyCallBack = (defines) => {\n Material._FresnelDirtyCallBack(defines);\n Material._MiscDirtyCallBack(defines);\n};\nMaterial._TextureAndMiscDirtyCallBack = (defines) => {\n Material._TextureDirtyCallBack(defines);\n Material._MiscDirtyCallBack(defines);\n};\nMaterial._DirtyCallbackArray = [];\nMaterial._RunDirtyCallBacks = (defines) => {\n for (const cb of Material._DirtyCallbackArray) {\n cb(defines);\n }\n};\n__decorate([\n serialize()\n], Material.prototype, \"id\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"uniqueId\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"name\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"metadata\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"checkReadyOnEveryCall\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"checkReadyOnlyOnce\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"state\", void 0);\n__decorate([\n serialize(\"alpha\")\n], Material.prototype, \"_alpha\", void 0);\n__decorate([\n serialize(\"backFaceCulling\")\n], Material.prototype, \"_backFaceCulling\", void 0);\n__decorate([\n serialize(\"cullBackFaces\")\n], Material.prototype, \"_cullBackFaces\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"sideOrientation\", void 0);\n__decorate([\n serialize(\"alphaMode\")\n], Material.prototype, \"_alphaMode\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"_needDepthPrePass\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"disableDepthWrite\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"disableColorWrite\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"forceDepthWrite\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"depthFunction\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"separateCullingPass\", void 0);\n__decorate([\n serialize(\"fogEnabled\")\n], Material.prototype, \"_fogEnabled\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"pointSize\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"zOffset\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"zOffsetUnits\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"pointsCloud\", null);\n__decorate([\n serialize()\n], Material.prototype, \"fillMode\", null);\n__decorate([\n serialize()\n], Material.prototype, \"transparencyMode\", null);\n//# sourceMappingURL=material.js.map","/**\n * Manages the defines for the Material\n */\nexport class MaterialDefines {\n /**\n * Creates a new instance\n * @param externalProperties list of external properties to inject into the object\n */\n constructor(externalProperties) {\n /** @internal */\n this._keys = [];\n this._isDirty = true;\n /** @internal */\n this._areLightsDirty = true;\n /** @internal */\n this._areLightsDisposed = false;\n /** @internal */\n this._areAttributesDirty = true;\n /** @internal */\n this._areTexturesDirty = true;\n /** @internal */\n this._areFresnelDirty = true;\n /** @internal */\n this._areMiscDirty = true;\n /** @internal */\n this._arePrePassDirty = true;\n /** @internal */\n this._areImageProcessingDirty = true;\n /** @internal */\n this._normals = false;\n /** @internal */\n this._uvs = false;\n /** @internal */\n this._needNormals = false;\n /** @internal */\n this._needUVs = false;\n this._externalProperties = externalProperties;\n // Initialize External Properties\n if (externalProperties) {\n for (const prop in externalProperties) {\n if (Object.prototype.hasOwnProperty.call(externalProperties, prop)) {\n this._setDefaultValue(prop);\n }\n }\n }\n }\n /**\n * Specifies if the material needs to be re-calculated\n */\n get isDirty() {\n return this._isDirty;\n }\n /**\n * Marks the material to indicate that it has been re-calculated\n */\n markAsProcessed() {\n this._isDirty = false;\n this._areAttributesDirty = false;\n this._areTexturesDirty = false;\n this._areFresnelDirty = false;\n this._areLightsDirty = false;\n this._areLightsDisposed = false;\n this._areMiscDirty = false;\n this._arePrePassDirty = false;\n this._areImageProcessingDirty = false;\n }\n /**\n * Marks the material to indicate that it needs to be re-calculated\n */\n markAsUnprocessed() {\n this._isDirty = true;\n }\n /**\n * Marks the material to indicate all of its defines need to be re-calculated\n */\n markAllAsDirty() {\n this._areTexturesDirty = true;\n this._areAttributesDirty = true;\n this._areLightsDirty = true;\n this._areFresnelDirty = true;\n this._areMiscDirty = true;\n this._arePrePassDirty = false;\n this._areImageProcessingDirty = true;\n this._isDirty = true;\n }\n /**\n * Marks the material to indicate that image processing needs to be re-calculated\n */\n markAsImageProcessingDirty() {\n this._areImageProcessingDirty = true;\n this._isDirty = true;\n }\n /**\n * Marks the material to indicate the lights need to be re-calculated\n * @param disposed Defines whether the light is dirty due to dispose or not\n */\n markAsLightDirty(disposed = false) {\n this._areLightsDirty = true;\n this._areLightsDisposed = this._areLightsDisposed || disposed;\n this._isDirty = true;\n }\n /**\n * Marks the attribute state as changed\n */\n markAsAttributesDirty() {\n this._areAttributesDirty = true;\n this._isDirty = true;\n }\n /**\n * Marks the texture state as changed\n */\n markAsTexturesDirty() {\n this._areTexturesDirty = true;\n this._isDirty = true;\n }\n /**\n * Marks the fresnel state as changed\n */\n markAsFresnelDirty() {\n this._areFresnelDirty = true;\n this._isDirty = true;\n }\n /**\n * Marks the misc state as changed\n */\n markAsMiscDirty() {\n this._areMiscDirty = true;\n this._isDirty = true;\n }\n /**\n * Marks the prepass state as changed\n */\n markAsPrePassDirty() {\n this._arePrePassDirty = true;\n this._isDirty = true;\n }\n /**\n * Rebuilds the material defines\n */\n rebuild() {\n this._keys.length = 0;\n for (const key of Object.keys(this)) {\n if (key[0] === \"_\") {\n continue;\n }\n this._keys.push(key);\n }\n if (this._externalProperties) {\n for (const name in this._externalProperties) {\n if (this._keys.indexOf(name) === -1) {\n this._keys.push(name);\n }\n }\n }\n }\n /**\n * Specifies if two material defines are equal\n * @param other - A material define instance to compare to\n * @returns - Boolean indicating if the material defines are equal (true) or not (false)\n */\n isEqual(other) {\n if (this._keys.length !== other._keys.length) {\n return false;\n }\n for (let index = 0; index < this._keys.length; index++) {\n const prop = this._keys[index];\n if (this[prop] !== other[prop]) {\n return false;\n }\n }\n return true;\n }\n /**\n * Clones this instance's defines to another instance\n * @param other - material defines to clone values to\n */\n cloneTo(other) {\n if (this._keys.length !== other._keys.length) {\n other._keys = this._keys.slice(0);\n }\n for (let index = 0; index < this._keys.length; index++) {\n const prop = this._keys[index];\n other[prop] = this[prop];\n }\n }\n /**\n * Resets the material define values\n */\n reset() {\n this._keys.forEach((prop) => this._setDefaultValue(prop));\n }\n _setDefaultValue(prop) {\n var _a, _b, _c, _d, _e;\n const type = (_c = (_b = (_a = this._externalProperties) === null || _a === void 0 ? void 0 : _a[prop]) === null || _b === void 0 ? void 0 : _b.type) !== null && _c !== void 0 ? _c : typeof this[prop];\n const defValue = (_e = (_d = this._externalProperties) === null || _d === void 0 ? void 0 : _d[prop]) === null || _e === void 0 ? void 0 : _e.default;\n switch (type) {\n case \"number\":\n this[prop] = defValue !== null && defValue !== void 0 ? defValue : 0;\n break;\n case \"string\":\n this[prop] = defValue !== null && defValue !== void 0 ? defValue : \"\";\n break;\n default:\n this[prop] = defValue !== null && defValue !== void 0 ? defValue : false;\n break;\n }\n }\n /**\n * Converts the material define values to a string\n * @returns - String of material define information\n */\n toString() {\n let result = \"\";\n for (let index = 0; index < this._keys.length; index++) {\n const prop = this._keys[index];\n const value = this[prop];\n const type = typeof value;\n switch (type) {\n case \"number\":\n case \"string\":\n result += \"#define \" + prop + \" \" + value + \"\\n\";\n break;\n default:\n if (value) {\n result += \"#define \" + prop + \"\\n\";\n }\n break;\n }\n }\n return result;\n }\n}\n//# sourceMappingURL=materialDefines.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { Camera } from \"../Cameras/camera.js\";\nimport { Scene } from \"../scene.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { LightConstants } from \"../Lights/lightConstants.js\";\n\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { prepareDefinesForClipPlanes } from \"./clipPlaneMaterialHelper.js\";\n/**\n * \"Static Class\" containing the most commonly used helper while dealing with material for rendering purpose.\n *\n * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.\n *\n * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.\n */\nexport class MaterialHelper {\n /**\n * Binds the scene's uniform buffer to the effect.\n * @param effect defines the effect to bind to the scene uniform buffer\n * @param sceneUbo defines the uniform buffer storing scene data\n */\n static BindSceneUniformBuffer(effect, sceneUbo) {\n sceneUbo.bindToEffect(effect, \"Scene\");\n }\n /**\n * Helps preparing the defines values about the UVs in used in the effect.\n * UVs are shared as much as we can across channels in the shaders.\n * @param texture The texture we are preparing the UVs for\n * @param defines The defines to update\n * @param key The channel key \"diffuse\", \"specular\"... used in the shader\n */\n static PrepareDefinesForMergedUV(texture, defines, key) {\n defines._needUVs = true;\n defines[key] = true;\n if (texture.optimizeUVAllocation && texture.getTextureMatrix().isIdentityAs3x2()) {\n defines[key + \"DIRECTUV\"] = texture.coordinatesIndex + 1;\n defines[\"MAINUV\" + (texture.coordinatesIndex + 1)] = true;\n }\n else {\n defines[key + \"DIRECTUV\"] = 0;\n }\n }\n /**\n * Binds a texture matrix value to its corresponding uniform\n * @param texture The texture to bind the matrix for\n * @param uniformBuffer The uniform buffer receiving the data\n * @param key The channel key \"diffuse\", \"specular\"... used in the shader\n */\n static BindTextureMatrix(texture, uniformBuffer, key) {\n const matrix = texture.getTextureMatrix();\n uniformBuffer.updateMatrix(key + \"Matrix\", matrix);\n }\n /**\n * Gets the current status of the fog (should it be enabled?)\n * @param mesh defines the mesh to evaluate for fog support\n * @param scene defines the hosting scene\n * @returns true if fog must be enabled\n */\n static GetFogState(mesh, scene) {\n return scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE;\n }\n /**\n * Helper used to prepare the list of defines associated with misc. values for shader compilation\n * @param mesh defines the current mesh\n * @param scene defines the current scene\n * @param useLogarithmicDepth defines if logarithmic depth has to be turned on\n * @param pointsCloud defines if point cloud rendering has to be turned on\n * @param fogEnabled defines if fog has to be turned on\n * @param alphaTest defines if alpha testing has to be turned on\n * @param defines defines the current list of defines\n */\n static PrepareDefinesForMisc(mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {\n if (defines._areMiscDirty) {\n defines[\"LOGARITHMICDEPTH\"] = useLogarithmicDepth;\n defines[\"POINTSIZE\"] = pointsCloud;\n defines[\"FOG\"] = fogEnabled && this.GetFogState(mesh, scene);\n defines[\"NONUNIFORMSCALING\"] = mesh.nonUniformScaling;\n defines[\"ALPHATEST\"] = alphaTest;\n }\n }\n /**\n * Helper used to prepare the defines relative to the active camera\n * @param scene defines the current scene\n * @param defines specifies the list of active defines\n * @returns true if the defines have been updated, else false\n */\n static PrepareDefinesForCamera(scene, defines) {\n let changed = false;\n if (scene.activeCamera) {\n const wasOrtho = defines[\"CAMERA_ORTHOGRAPHIC\"] ? 1 : 0;\n const wasPersp = defines[\"CAMERA_PERSPECTIVE\"] ? 1 : 0;\n const isOrtho = scene.activeCamera.mode === Camera.ORTHOGRAPHIC_CAMERA ? 1 : 0;\n const isPersp = scene.activeCamera.mode === Camera.PERSPECTIVE_CAMERA ? 1 : 0;\n if (wasOrtho ^ isOrtho || wasPersp ^ isPersp) {\n defines[\"CAMERA_ORTHOGRAPHIC\"] = isOrtho === 1;\n defines[\"CAMERA_PERSPECTIVE\"] = isPersp === 1;\n changed = true;\n }\n }\n return changed;\n }\n /**\n * Helper used to prepare the list of defines associated with frame values for shader compilation\n * @param scene defines the current scene\n * @param engine defines the current engine\n * @param material defines the material we are compiling the shader for\n * @param defines specifies the list of active defines\n * @param useInstances defines if instances have to be turned on\n * @param useClipPlane defines if clip plane have to be turned on\n * @param useThinInstances defines if thin instances have to be turned on\n */\n static PrepareDefinesForFrameBoundValues(scene, engine, material, defines, useInstances, useClipPlane = null, useThinInstances = false) {\n let changed = MaterialHelper.PrepareDefinesForCamera(scene, defines);\n if (useClipPlane !== false) {\n changed = prepareDefinesForClipPlanes(material, scene, defines);\n }\n if (defines[\"DEPTHPREPASS\"] !== !engine.getColorWrite()) {\n defines[\"DEPTHPREPASS\"] = !defines[\"DEPTHPREPASS\"];\n changed = true;\n }\n if (defines[\"INSTANCES\"] !== useInstances) {\n defines[\"INSTANCES\"] = useInstances;\n changed = true;\n }\n if (defines[\"THIN_INSTANCES\"] !== useThinInstances) {\n defines[\"THIN_INSTANCES\"] = useThinInstances;\n changed = true;\n }\n if (changed) {\n defines.markAsUnprocessed();\n }\n }\n /**\n * Prepares the defines for bones\n * @param mesh The mesh containing the geometry data we will draw\n * @param defines The defines to update\n */\n static PrepareDefinesForBones(mesh, defines) {\n if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {\n defines[\"NUM_BONE_INFLUENCERS\"] = mesh.numBoneInfluencers;\n const materialSupportsBoneTexture = defines[\"BONETEXTURE\"] !== undefined;\n if (mesh.skeleton.isUsingTextureForMatrices && materialSupportsBoneTexture) {\n defines[\"BONETEXTURE\"] = true;\n }\n else {\n defines[\"BonesPerMesh\"] = mesh.skeleton.bones.length + 1;\n defines[\"BONETEXTURE\"] = materialSupportsBoneTexture ? false : undefined;\n const prePassRenderer = mesh.getScene().prePassRenderer;\n if (prePassRenderer && prePassRenderer.enabled) {\n const nonExcluded = prePassRenderer.excludedSkinnedMesh.indexOf(mesh) === -1;\n defines[\"BONES_VELOCITY_ENABLED\"] = nonExcluded;\n }\n }\n }\n else {\n defines[\"NUM_BONE_INFLUENCERS\"] = 0;\n defines[\"BonesPerMesh\"] = 0;\n if (defines[\"BONETEXTURE\"] !== undefined) {\n defines[\"BONETEXTURE\"] = false;\n }\n }\n }\n /**\n * Prepares the defines for morph targets\n * @param mesh The mesh containing the geometry data we will draw\n * @param defines The defines to update\n */\n static PrepareDefinesForMorphTargets(mesh, defines) {\n const manager = mesh.morphTargetManager;\n if (manager) {\n defines[\"MORPHTARGETS_UV\"] = manager.supportsUVs && defines[\"UV1\"];\n defines[\"MORPHTARGETS_TANGENT\"] = manager.supportsTangents && defines[\"TANGENT\"];\n defines[\"MORPHTARGETS_NORMAL\"] = manager.supportsNormals && defines[\"NORMAL\"];\n defines[\"MORPHTARGETS\"] = manager.numInfluencers > 0;\n defines[\"NUM_MORPH_INFLUENCERS\"] = manager.numInfluencers;\n defines[\"MORPHTARGETS_TEXTURE\"] = manager.isUsingTextureForTargets;\n }\n else {\n defines[\"MORPHTARGETS_UV\"] = false;\n defines[\"MORPHTARGETS_TANGENT\"] = false;\n defines[\"MORPHTARGETS_NORMAL\"] = false;\n defines[\"MORPHTARGETS\"] = false;\n defines[\"NUM_MORPH_INFLUENCERS\"] = 0;\n }\n }\n /**\n * Prepares the defines for baked vertex animation\n * @param mesh The mesh containing the geometry data we will draw\n * @param defines The defines to update\n */\n static PrepareDefinesForBakedVertexAnimation(mesh, defines) {\n const manager = mesh.bakedVertexAnimationManager;\n defines[\"BAKED_VERTEX_ANIMATION_TEXTURE\"] = manager && manager.isEnabled ? true : false;\n }\n /**\n * Prepares the defines used in the shader depending on the attributes data available in the mesh\n * @param mesh The mesh containing the geometry data we will draw\n * @param defines The defines to update\n * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)\n * @param useBones Precise whether bones should be used or not (override mesh info)\n * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)\n * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)\n * @param useBakedVertexAnimation Precise whether baked vertex animation should be used or not (override mesh info)\n * @returns false if defines are considered not dirty and have not been checked\n */\n static PrepareDefinesForAttributes(mesh, defines, useVertexColor, useBones, useMorphTargets = false, useVertexAlpha = true, useBakedVertexAnimation = true) {\n if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {\n return false;\n }\n defines._normals = defines._needNormals;\n defines._uvs = defines._needUVs;\n defines[\"NORMAL\"] = defines._needNormals && mesh.isVerticesDataPresent(VertexBuffer.NormalKind);\n if (defines._needNormals && mesh.isVerticesDataPresent(VertexBuffer.TangentKind)) {\n defines[\"TANGENT\"] = true;\n }\n for (let i = 1; i <= 6; ++i) {\n defines[\"UV\" + i] = defines._needUVs ? mesh.isVerticesDataPresent(`uv${i === 1 ? \"\" : i}`) : false;\n }\n if (useVertexColor) {\n const hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(VertexBuffer.ColorKind);\n defines[\"VERTEXCOLOR\"] = hasVertexColors;\n defines[\"VERTEXALPHA\"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;\n }\n if (mesh.isVerticesDataPresent(VertexBuffer.ColorInstanceKind) && (mesh.hasInstances || mesh.hasThinInstances)) {\n defines[\"INSTANCESCOLOR\"] = true;\n }\n if (useBones) {\n this.PrepareDefinesForBones(mesh, defines);\n }\n if (useMorphTargets) {\n this.PrepareDefinesForMorphTargets(mesh, defines);\n }\n if (useBakedVertexAnimation) {\n this.PrepareDefinesForBakedVertexAnimation(mesh, defines);\n }\n return true;\n }\n /**\n * Prepares the defines related to multiview\n * @param scene The scene we are intending to draw\n * @param defines The defines to update\n */\n static PrepareDefinesForMultiview(scene, defines) {\n if (scene.activeCamera) {\n const previousMultiview = defines.MULTIVIEW;\n defines.MULTIVIEW = scene.activeCamera.outputRenderTarget !== null && scene.activeCamera.outputRenderTarget.getViewCount() > 1;\n if (defines.MULTIVIEW != previousMultiview) {\n defines.markAsUnprocessed();\n }\n }\n }\n /**\n * Prepares the defines related to order independant transparency\n * @param scene The scene we are intending to draw\n * @param defines The defines to update\n * @param needAlphaBlending Determines if the material needs alpha blending\n */\n static PrepareDefinesForOIT(scene, defines, needAlphaBlending) {\n const previousDefine = defines.ORDER_INDEPENDENT_TRANSPARENCY;\n const previousDefine16Bits = defines.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;\n defines.ORDER_INDEPENDENT_TRANSPARENCY = scene.useOrderIndependentTransparency && needAlphaBlending;\n defines.ORDER_INDEPENDENT_TRANSPARENCY_16BITS = !scene.getEngine().getCaps().textureFloatLinearFiltering;\n if (previousDefine !== defines.ORDER_INDEPENDENT_TRANSPARENCY || previousDefine16Bits !== defines.ORDER_INDEPENDENT_TRANSPARENCY_16BITS) {\n defines.markAsUnprocessed();\n }\n }\n /**\n * Prepares the defines related to the prepass\n * @param scene The scene we are intending to draw\n * @param defines The defines to update\n * @param canRenderToMRT Indicates if this material renders to several textures in the prepass\n */\n static PrepareDefinesForPrePass(scene, defines, canRenderToMRT) {\n const previousPrePass = defines.PREPASS;\n if (!defines._arePrePassDirty) {\n return;\n }\n const texturesList = [\n {\n type: 1,\n define: \"PREPASS_POSITION\",\n index: \"PREPASS_POSITION_INDEX\",\n },\n {\n type: 2,\n define: \"PREPASS_VELOCITY\",\n index: \"PREPASS_VELOCITY_INDEX\",\n },\n {\n type: 3,\n define: \"PREPASS_REFLECTIVITY\",\n index: \"PREPASS_REFLECTIVITY_INDEX\",\n },\n {\n type: 0,\n define: \"PREPASS_IRRADIANCE\",\n index: \"PREPASS_IRRADIANCE_INDEX\",\n },\n {\n type: 7,\n define: \"PREPASS_ALBEDO_SQRT\",\n index: \"PREPASS_ALBEDO_SQRT_INDEX\",\n },\n {\n type: 5,\n define: \"PREPASS_DEPTH\",\n index: \"PREPASS_DEPTH_INDEX\",\n },\n {\n type: 6,\n define: \"PREPASS_NORMAL\",\n index: \"PREPASS_NORMAL_INDEX\",\n },\n ];\n if (scene.prePassRenderer && scene.prePassRenderer.enabled && canRenderToMRT) {\n defines.PREPASS = true;\n defines.SCENE_MRT_COUNT = scene.prePassRenderer.mrtCount;\n for (let i = 0; i < texturesList.length; i++) {\n const index = scene.prePassRenderer.getIndex(texturesList[i].type);\n if (index !== -1) {\n defines[texturesList[i].define] = true;\n defines[texturesList[i].index] = index;\n }\n else {\n defines[texturesList[i].define] = false;\n }\n }\n }\n else {\n defines.PREPASS = false;\n for (let i = 0; i < texturesList.length; i++) {\n defines[texturesList[i].define] = false;\n }\n }\n if (defines.PREPASS != previousPrePass) {\n defines.markAsUnprocessed();\n defines.markAsImageProcessingDirty();\n }\n }\n /**\n * Prepares the defines related to the light information passed in parameter\n * @param scene The scene we are intending to draw\n * @param mesh The mesh the effect is compiling for\n * @param light The light the effect is compiling for\n * @param lightIndex The index of the light\n * @param defines The defines to update\n * @param specularSupported Specifies whether specular is supported or not (override lights data)\n * @param state Defines the current state regarding what is needed (normals, etc...)\n * @param state.needNormals\n * @param state.needRebuild\n * @param state.shadowEnabled\n * @param state.specularEnabled\n * @param state.lightmapMode\n */\n static PrepareDefinesForLight(scene, mesh, light, lightIndex, defines, specularSupported, state) {\n var _a;\n state.needNormals = true;\n if (defines[\"LIGHT\" + lightIndex] === undefined) {\n state.needRebuild = true;\n }\n defines[\"LIGHT\" + lightIndex] = true;\n defines[\"SPOTLIGHT\" + lightIndex] = false;\n defines[\"HEMILIGHT\" + lightIndex] = false;\n defines[\"POINTLIGHT\" + lightIndex] = false;\n defines[\"DIRLIGHT\" + lightIndex] = false;\n light.prepareLightSpecificDefines(defines, lightIndex);\n // FallOff.\n defines[\"LIGHT_FALLOFF_PHYSICAL\" + lightIndex] = false;\n defines[\"LIGHT_FALLOFF_GLTF\" + lightIndex] = false;\n defines[\"LIGHT_FALLOFF_STANDARD\" + lightIndex] = false;\n switch (light.falloffType) {\n case LightConstants.FALLOFF_GLTF:\n defines[\"LIGHT_FALLOFF_GLTF\" + lightIndex] = true;\n break;\n case LightConstants.FALLOFF_PHYSICAL:\n defines[\"LIGHT_FALLOFF_PHYSICAL\" + lightIndex] = true;\n break;\n case LightConstants.FALLOFF_STANDARD:\n defines[\"LIGHT_FALLOFF_STANDARD\" + lightIndex] = true;\n break;\n }\n // Specular\n if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {\n state.specularEnabled = true;\n }\n // Shadows\n defines[\"SHADOW\" + lightIndex] = false;\n defines[\"SHADOWCSM\" + lightIndex] = false;\n defines[\"SHADOWCSMDEBUG\" + lightIndex] = false;\n defines[\"SHADOWCSMNUM_CASCADES\" + lightIndex] = false;\n defines[\"SHADOWCSMUSESHADOWMAXZ\" + lightIndex] = false;\n defines[\"SHADOWCSMNOBLEND\" + lightIndex] = false;\n defines[\"SHADOWCSM_RIGHTHANDED\" + lightIndex] = false;\n defines[\"SHADOWPCF\" + lightIndex] = false;\n defines[\"SHADOWPCSS\" + lightIndex] = false;\n defines[\"SHADOWPOISSON\" + lightIndex] = false;\n defines[\"SHADOWESM\" + lightIndex] = false;\n defines[\"SHADOWCLOSEESM\" + lightIndex] = false;\n defines[\"SHADOWCUBE\" + lightIndex] = false;\n defines[\"SHADOWLOWQUALITY\" + lightIndex] = false;\n defines[\"SHADOWMEDIUMQUALITY\" + lightIndex] = false;\n if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {\n const shadowGenerator = (_a = light.getShadowGenerator(scene.activeCamera)) !== null && _a !== void 0 ? _a : light.getShadowGenerator();\n if (shadowGenerator) {\n const shadowMap = shadowGenerator.getShadowMap();\n if (shadowMap) {\n if (shadowMap.renderList && shadowMap.renderList.length > 0) {\n state.shadowEnabled = true;\n shadowGenerator.prepareDefines(defines, lightIndex);\n }\n }\n }\n }\n if (light.lightmapMode != LightConstants.LIGHTMAP_DEFAULT) {\n state.lightmapMode = true;\n defines[\"LIGHTMAPEXCLUDED\" + lightIndex] = true;\n defines[\"LIGHTMAPNOSPECULAR\" + lightIndex] = light.lightmapMode == LightConstants.LIGHTMAP_SHADOWSONLY;\n }\n else {\n defines[\"LIGHTMAPEXCLUDED\" + lightIndex] = false;\n defines[\"LIGHTMAPNOSPECULAR\" + lightIndex] = false;\n }\n }\n /**\n * Prepares the defines related to the light information passed in parameter\n * @param scene The scene we are intending to draw\n * @param mesh The mesh the effect is compiling for\n * @param defines The defines to update\n * @param specularSupported Specifies whether specular is supported or not (override lights data)\n * @param maxSimultaneousLights Specifies how manuy lights can be added to the effect at max\n * @param disableLighting Specifies whether the lighting is disabled (override scene and light)\n * @returns true if normals will be required for the rest of the effect\n */\n static PrepareDefinesForLights(scene, mesh, defines, specularSupported, maxSimultaneousLights = 4, disableLighting = false) {\n if (!defines._areLightsDirty) {\n return defines._needNormals;\n }\n let lightIndex = 0;\n const state = {\n needNormals: defines._needNormals,\n needRebuild: false,\n lightmapMode: false,\n shadowEnabled: false,\n specularEnabled: false,\n };\n if (scene.lightsEnabled && !disableLighting) {\n for (const light of mesh.lightSources) {\n this.PrepareDefinesForLight(scene, mesh, light, lightIndex, defines, specularSupported, state);\n lightIndex++;\n if (lightIndex === maxSimultaneousLights) {\n break;\n }\n }\n }\n defines[\"SPECULARTERM\"] = state.specularEnabled;\n defines[\"SHADOWS\"] = state.shadowEnabled;\n // Resetting all other lights if any\n for (let index = lightIndex; index < maxSimultaneousLights; index++) {\n if (defines[\"LIGHT\" + index] !== undefined) {\n defines[\"LIGHT\" + index] = false;\n defines[\"HEMILIGHT\" + index] = false;\n defines[\"POINTLIGHT\" + index] = false;\n defines[\"DIRLIGHT\" + index] = false;\n defines[\"SPOTLIGHT\" + index] = false;\n defines[\"SHADOW\" + index] = false;\n defines[\"SHADOWCSM\" + index] = false;\n defines[\"SHADOWCSMDEBUG\" + index] = false;\n defines[\"SHADOWCSMNUM_CASCADES\" + index] = false;\n defines[\"SHADOWCSMUSESHADOWMAXZ\" + index] = false;\n defines[\"SHADOWCSMNOBLEND\" + index] = false;\n defines[\"SHADOWCSM_RIGHTHANDED\" + index] = false;\n defines[\"SHADOWPCF\" + index] = false;\n defines[\"SHADOWPCSS\" + index] = false;\n defines[\"SHADOWPOISSON\" + index] = false;\n defines[\"SHADOWESM\" + index] = false;\n defines[\"SHADOWCLOSEESM\" + index] = false;\n defines[\"SHADOWCUBE\" + index] = false;\n defines[\"SHADOWLOWQUALITY\" + index] = false;\n defines[\"SHADOWMEDIUMQUALITY\" + index] = false;\n }\n }\n const caps = scene.getEngine().getCaps();\n if (defines[\"SHADOWFLOAT\"] === undefined) {\n state.needRebuild = true;\n }\n defines[\"SHADOWFLOAT\"] =\n state.shadowEnabled && ((caps.textureFloatRender && caps.textureFloatLinearFiltering) || (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));\n defines[\"LIGHTMAPEXCLUDED\"] = state.lightmapMode;\n if (state.needRebuild) {\n defines.rebuild();\n }\n return state.needNormals;\n }\n /**\n * Prepares the uniforms and samplers list to be used in the effect (for a specific light)\n * @param lightIndex defines the light index\n * @param uniformsList The uniform list\n * @param samplersList The sampler list\n * @param projectedLightTexture defines if projected texture must be used\n * @param uniformBuffersList defines an optional list of uniform buffers\n * @param updateOnlyBuffersList True to only update the uniformBuffersList array\n */\n static PrepareUniformsAndSamplersForLight(lightIndex, uniformsList, samplersList, projectedLightTexture, uniformBuffersList = null, updateOnlyBuffersList = false) {\n if (uniformBuffersList) {\n uniformBuffersList.push(\"Light\" + lightIndex);\n }\n if (updateOnlyBuffersList) {\n return;\n }\n uniformsList.push(\"vLightData\" + lightIndex, \"vLightDiffuse\" + lightIndex, \"vLightSpecular\" + lightIndex, \"vLightDirection\" + lightIndex, \"vLightFalloff\" + lightIndex, \"vLightGround\" + lightIndex, \"lightMatrix\" + lightIndex, \"shadowsInfo\" + lightIndex, \"depthValues\" + lightIndex);\n samplersList.push(\"shadowSampler\" + lightIndex);\n samplersList.push(\"depthSampler\" + lightIndex);\n uniformsList.push(\"viewFrustumZ\" + lightIndex, \"cascadeBlendFactor\" + lightIndex, \"lightSizeUVCorrection\" + lightIndex, \"depthCorrection\" + lightIndex, \"penumbraDarkness\" + lightIndex, \"frustumLengths\" + lightIndex);\n if (projectedLightTexture) {\n samplersList.push(\"projectionLightSampler\" + lightIndex);\n uniformsList.push(\"textureProjectionMatrix\" + lightIndex);\n }\n }\n /**\n * Prepares the uniforms and samplers list to be used in the effect\n * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the list and extra information\n * @param samplersList The sampler list\n * @param defines The defines helping in the list generation\n * @param maxSimultaneousLights The maximum number of simultaneous light allowed in the effect\n */\n static PrepareUniformsAndSamplersList(uniformsListOrOptions, samplersList, defines, maxSimultaneousLights = 4) {\n let uniformsList;\n let uniformBuffersList = null;\n if (uniformsListOrOptions.uniformsNames) {\n const options = uniformsListOrOptions;\n uniformsList = options.uniformsNames;\n uniformBuffersList = options.uniformBuffersNames;\n samplersList = options.samplers;\n defines = options.defines;\n maxSimultaneousLights = options.maxSimultaneousLights || 0;\n }\n else {\n uniformsList = uniformsListOrOptions;\n if (!samplersList) {\n samplersList = [];\n }\n }\n for (let lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {\n if (!defines[\"LIGHT\" + lightIndex]) {\n break;\n }\n this.PrepareUniformsAndSamplersForLight(lightIndex, uniformsList, samplersList, defines[\"PROJECTEDLIGHTTEXTURE\" + lightIndex], uniformBuffersList);\n }\n if (defines[\"NUM_MORPH_INFLUENCERS\"]) {\n uniformsList.push(\"morphTargetInfluences\");\n }\n if (defines[\"BAKED_VERTEX_ANIMATION_TEXTURE\"]) {\n uniformsList.push(\"bakedVertexAnimationSettings\");\n uniformsList.push(\"bakedVertexAnimationTextureSizeInverted\");\n uniformsList.push(\"bakedVertexAnimationTime\");\n samplersList.push(\"bakedVertexAnimationTexture\");\n }\n }\n /**\n * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)\n * @param defines The defines to update while falling back\n * @param fallbacks The authorized effect fallbacks\n * @param maxSimultaneousLights The maximum number of lights allowed\n * @param rank the current rank of the Effect\n * @returns The newly affected rank\n */\n static HandleFallbacksForShadows(defines, fallbacks, maxSimultaneousLights = 4, rank = 0) {\n let lightFallbackRank = 0;\n for (let lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {\n if (!defines[\"LIGHT\" + lightIndex]) {\n break;\n }\n if (lightIndex > 0) {\n lightFallbackRank = rank + lightIndex;\n fallbacks.addFallback(lightFallbackRank, \"LIGHT\" + lightIndex);\n }\n if (!defines[\"SHADOWS\"]) {\n if (defines[\"SHADOW\" + lightIndex]) {\n fallbacks.addFallback(rank, \"SHADOW\" + lightIndex);\n }\n if (defines[\"SHADOWPCF\" + lightIndex]) {\n fallbacks.addFallback(rank, \"SHADOWPCF\" + lightIndex);\n }\n if (defines[\"SHADOWPCSS\" + lightIndex]) {\n fallbacks.addFallback(rank, \"SHADOWPCSS\" + lightIndex);\n }\n if (defines[\"SHADOWPOISSON\" + lightIndex]) {\n fallbacks.addFallback(rank, \"SHADOWPOISSON\" + lightIndex);\n }\n if (defines[\"SHADOWESM\" + lightIndex]) {\n fallbacks.addFallback(rank, \"SHADOWESM\" + lightIndex);\n }\n if (defines[\"SHADOWCLOSEESM\" + lightIndex]) {\n fallbacks.addFallback(rank, \"SHADOWCLOSEESM\" + lightIndex);\n }\n }\n }\n return lightFallbackRank++;\n }\n /**\n * Prepares the list of attributes required for morph targets according to the effect defines.\n * @param attribs The current list of supported attribs\n * @param mesh The mesh to prepare the morph targets attributes for\n * @param influencers The number of influencers\n */\n static PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, influencers) {\n this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS = influencers;\n this.PrepareAttributesForMorphTargets(attribs, mesh, this._TmpMorphInfluencers);\n }\n /**\n * Prepares the list of attributes required for morph targets according to the effect defines.\n * @param attribs The current list of supported attribs\n * @param mesh The mesh to prepare the morph targets attributes for\n * @param defines The current Defines of the effect\n */\n static PrepareAttributesForMorphTargets(attribs, mesh, defines) {\n const influencers = defines[\"NUM_MORPH_INFLUENCERS\"];\n if (influencers > 0 && EngineStore.LastCreatedEngine) {\n const maxAttributesCount = EngineStore.LastCreatedEngine.getCaps().maxVertexAttribs;\n const manager = mesh.morphTargetManager;\n if (manager === null || manager === void 0 ? void 0 : manager.isUsingTextureForTargets) {\n return;\n }\n const normal = manager && manager.supportsNormals && defines[\"NORMAL\"];\n const tangent = manager && manager.supportsTangents && defines[\"TANGENT\"];\n const uv = manager && manager.supportsUVs && defines[\"UV1\"];\n for (let index = 0; index < influencers; index++) {\n attribs.push(VertexBuffer.PositionKind + index);\n if (normal) {\n attribs.push(VertexBuffer.NormalKind + index);\n }\n if (tangent) {\n attribs.push(VertexBuffer.TangentKind + index);\n }\n if (uv) {\n attribs.push(VertexBuffer.UVKind + \"_\" + index);\n }\n if (attribs.length > maxAttributesCount) {\n Logger.Error(\"Cannot add more vertex attributes for mesh \" + mesh.name);\n }\n }\n }\n }\n /**\n * Prepares the list of attributes required for baked vertex animations according to the effect defines.\n * @param attribs The current list of supported attribs\n * @param mesh The mesh to prepare the morph targets attributes for\n * @param defines The current Defines of the effect\n */\n static PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines) {\n const enabled = defines[\"BAKED_VERTEX_ANIMATION_TEXTURE\"] && defines[\"INSTANCES\"];\n if (enabled) {\n attribs.push(\"bakedVertexAnimationSettingsInstanced\");\n }\n }\n /**\n * Prepares the list of attributes required for bones according to the effect defines.\n * @param attribs The current list of supported attribs\n * @param mesh The mesh to prepare the bones attributes for\n * @param defines The current Defines of the effect\n * @param fallbacks The current effect fallback strategy\n */\n static PrepareAttributesForBones(attribs, mesh, defines, fallbacks) {\n if (defines[\"NUM_BONE_INFLUENCERS\"] > 0) {\n fallbacks.addCPUSkinningFallback(0, mesh);\n attribs.push(VertexBuffer.MatricesIndicesKind);\n attribs.push(VertexBuffer.MatricesWeightsKind);\n if (defines[\"NUM_BONE_INFLUENCERS\"] > 4) {\n attribs.push(VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(VertexBuffer.MatricesWeightsExtraKind);\n }\n }\n }\n /**\n * Check and prepare the list of attributes required for instances according to the effect defines.\n * @param attribs The current list of supported attribs\n * @param defines The current MaterialDefines of the effect\n */\n static PrepareAttributesForInstances(attribs, defines) {\n if (defines[\"INSTANCES\"] || defines[\"THIN_INSTANCES\"]) {\n this.PushAttributesForInstances(attribs, !!defines[\"PREPASS_VELOCITY\"]);\n }\n if (defines.INSTANCESCOLOR) {\n attribs.push(VertexBuffer.ColorInstanceKind);\n }\n }\n /**\n * Add the list of attributes required for instances to the attribs array.\n * @param attribs The current list of supported attribs\n * @param needsPreviousMatrices If the shader needs previous matrices\n */\n static PushAttributesForInstances(attribs, needsPreviousMatrices = false) {\n attribs.push(\"world0\");\n attribs.push(\"world1\");\n attribs.push(\"world2\");\n attribs.push(\"world3\");\n if (needsPreviousMatrices) {\n attribs.push(\"previousWorld0\");\n attribs.push(\"previousWorld1\");\n attribs.push(\"previousWorld2\");\n attribs.push(\"previousWorld3\");\n }\n }\n /**\n * Binds the light information to the effect.\n * @param light The light containing the generator\n * @param effect The effect we are binding the data to\n * @param lightIndex The light index in the effect used to render\n */\n static BindLightProperties(light, effect, lightIndex) {\n light.transferToEffect(effect, lightIndex + \"\");\n }\n /**\n * Binds the lights information from the scene to the effect for the given mesh.\n * @param light Light to bind\n * @param lightIndex Light index\n * @param scene The scene where the light belongs to\n * @param effect The effect we are binding the data to\n * @param useSpecular Defines if specular is supported\n * @param receiveShadows Defines if the effect (mesh) we bind the light for receives shadows\n */\n static BindLight(light, lightIndex, scene, effect, useSpecular, receiveShadows = true) {\n light._bindLight(lightIndex, scene, effect, useSpecular, receiveShadows);\n }\n /**\n * Binds the lights information from the scene to the effect for the given mesh.\n * @param scene The scene the lights belongs to\n * @param mesh The mesh we are binding the information to render\n * @param effect The effect we are binding the data to\n * @param defines The generated defines for the effect\n * @param maxSimultaneousLights The maximum number of light that can be bound to the effect\n */\n static BindLights(scene, mesh, effect, defines, maxSimultaneousLights = 4) {\n const len = Math.min(mesh.lightSources.length, maxSimultaneousLights);\n for (let i = 0; i < len; i++) {\n const light = mesh.lightSources[i];\n this.BindLight(light, i, scene, effect, typeof defines === \"boolean\" ? defines : defines[\"SPECULARTERM\"], mesh.receiveShadows);\n }\n }\n /**\n * Binds the fog information from the scene to the effect for the given mesh.\n * @param scene The scene the lights belongs to\n * @param mesh The mesh we are binding the information to render\n * @param effect The effect we are binding the data to\n * @param linearSpace Defines if the fog effect is applied in linear space\n */\n static BindFogParameters(scene, mesh, effect, linearSpace = false) {\n if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) {\n effect.setFloat4(\"vFogInfos\", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);\n // Convert fog color to linear space if used in a linear space computed shader.\n if (linearSpace) {\n scene.fogColor.toLinearSpaceToRef(this._TempFogColor, scene.getEngine().useExactSrgbConversions);\n effect.setColor3(\"vFogColor\", this._TempFogColor);\n }\n else {\n effect.setColor3(\"vFogColor\", scene.fogColor);\n }\n }\n }\n /**\n * Binds the bones information from the mesh to the effect.\n * @param mesh The mesh we are binding the information to render\n * @param effect The effect we are binding the data to\n * @param prePassConfiguration Configuration for the prepass, in case prepass is activated\n */\n static BindBonesParameters(mesh, effect, prePassConfiguration) {\n if (!effect || !mesh) {\n return;\n }\n if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {\n mesh.computeBonesUsingShaders = false;\n }\n if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {\n const skeleton = mesh.skeleton;\n if (skeleton.isUsingTextureForMatrices && effect.getUniformIndex(\"boneTextureWidth\") > -1) {\n const boneTexture = skeleton.getTransformMatrixTexture(mesh);\n effect.setTexture(\"boneSampler\", boneTexture);\n effect.setFloat(\"boneTextureWidth\", 4.0 * (skeleton.bones.length + 1));\n }\n else {\n const matrices = skeleton.getTransformMatrices(mesh);\n if (matrices) {\n effect.setMatrices(\"mBones\", matrices);\n if (prePassConfiguration && mesh.getScene().prePassRenderer && mesh.getScene().prePassRenderer.getIndex(2)) {\n if (!prePassConfiguration.previousBones[mesh.uniqueId]) {\n prePassConfiguration.previousBones[mesh.uniqueId] = matrices.slice();\n }\n effect.setMatrices(\"mPreviousBones\", prePassConfiguration.previousBones[mesh.uniqueId]);\n MaterialHelper._CopyBonesTransformationMatrices(matrices, prePassConfiguration.previousBones[mesh.uniqueId]);\n }\n }\n }\n }\n }\n // Copies the bones transformation matrices into the target array and returns the target's reference\n static _CopyBonesTransformationMatrices(source, target) {\n target.set(source);\n return target;\n }\n /**\n * Binds the morph targets information from the mesh to the effect.\n * @param abstractMesh The mesh we are binding the information to render\n * @param effect The effect we are binding the data to\n */\n static BindMorphTargetParameters(abstractMesh, effect) {\n const manager = abstractMesh.morphTargetManager;\n if (!abstractMesh || !manager) {\n return;\n }\n effect.setFloatArray(\"morphTargetInfluences\", manager.influences);\n }\n /**\n * Binds the logarithmic depth information from the scene to the effect for the given defines.\n * @param defines The generated defines used in the effect\n * @param effect The effect we are binding the data to\n * @param scene The scene we are willing to render with logarithmic scale for\n */\n static BindLogDepth(defines, effect, scene) {\n if (!defines || defines[\"LOGARITHMICDEPTH\"] || (defines.indexOf && defines.indexOf(\"LOGARITHMICDEPTH\") >= 0)) {\n const camera = scene.activeCamera;\n if (camera.mode === Camera.ORTHOGRAPHIC_CAMERA) {\n Logger.Error(\"Logarithmic depth is not compatible with orthographic cameras!\", 20);\n }\n effect.setFloat(\"logarithmicDepthConstant\", 2.0 / (Math.log(camera.maxZ + 1.0) / Math.LN2));\n }\n }\n}\n// eslint-disable-next-line @typescript-eslint/naming-convention\nMaterialHelper._TmpMorphInfluencers = { NUM_MORPH_INFLUENCERS: 0 };\nMaterialHelper._TempFogColor = Color3.Black();\n//# sourceMappingURL=materialHelper.js.map","/**\n * @internal\n */\nexport var MaterialPluginEvent;\n(function (MaterialPluginEvent) {\n MaterialPluginEvent[MaterialPluginEvent[\"Created\"] = 1] = \"Created\";\n MaterialPluginEvent[MaterialPluginEvent[\"Disposed\"] = 2] = \"Disposed\";\n MaterialPluginEvent[MaterialPluginEvent[\"GetDefineNames\"] = 4] = \"GetDefineNames\";\n MaterialPluginEvent[MaterialPluginEvent[\"PrepareUniformBuffer\"] = 8] = \"PrepareUniformBuffer\";\n MaterialPluginEvent[MaterialPluginEvent[\"IsReadyForSubMesh\"] = 16] = \"IsReadyForSubMesh\";\n MaterialPluginEvent[MaterialPluginEvent[\"PrepareDefines\"] = 32] = \"PrepareDefines\";\n MaterialPluginEvent[MaterialPluginEvent[\"BindForSubMesh\"] = 64] = \"BindForSubMesh\";\n MaterialPluginEvent[MaterialPluginEvent[\"PrepareEffect\"] = 128] = \"PrepareEffect\";\n MaterialPluginEvent[MaterialPluginEvent[\"GetAnimatables\"] = 256] = \"GetAnimatables\";\n MaterialPluginEvent[MaterialPluginEvent[\"GetActiveTextures\"] = 512] = \"GetActiveTextures\";\n MaterialPluginEvent[MaterialPluginEvent[\"HasTexture\"] = 1024] = \"HasTexture\";\n MaterialPluginEvent[MaterialPluginEvent[\"FillRenderTargetTextures\"] = 2048] = \"FillRenderTargetTextures\";\n MaterialPluginEvent[MaterialPluginEvent[\"HasRenderTargetTextures\"] = 4096] = \"HasRenderTargetTextures\";\n MaterialPluginEvent[MaterialPluginEvent[\"HardBindForSubMesh\"] = 8192] = \"HardBindForSubMesh\";\n})(MaterialPluginEvent || (MaterialPluginEvent = {}));\n//# sourceMappingURL=materialPluginEvent.js.map","import { Material } from \"../Materials/material.js\";\nimport { Tags } from \"../Misc/tags.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\n/**\n * A multi-material is used to apply different materials to different parts of the same object without the need of\n * separate meshes. This can be use to improve performances.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/multiMaterials\n */\nexport class MultiMaterial extends Material {\n /**\n * Gets or Sets the list of Materials used within the multi material.\n * They need to be ordered according to the submeshes order in the associated mesh\n */\n get subMaterials() {\n return this._subMaterials;\n }\n set subMaterials(value) {\n this._subMaterials = value;\n this._hookArray(value);\n }\n /**\n * Function used to align with Node.getChildren()\n * @returns the list of Materials used within the multi material\n */\n getChildren() {\n return this.subMaterials;\n }\n /**\n * Instantiates a new Multi Material\n * A multi-material is used to apply different materials to different parts of the same object without the need of\n * separate meshes. This can be use to improve performances.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/multiMaterials\n * @param name Define the name in the scene\n * @param scene Define the scene the material belongs to\n */\n constructor(name, scene) {\n super(name, scene, true);\n /** @internal */\n this._waitingSubMaterialsUniqueIds = [];\n this.getScene().addMultiMaterial(this);\n this.subMaterials = new Array();\n this._storeEffectOnSubMeshes = true; // multimaterial is considered like a push material\n }\n _hookArray(array) {\n const oldPush = array.push;\n array.push = (...items) => {\n const result = oldPush.apply(array, items);\n this._markAllSubMeshesAsTexturesDirty();\n return result;\n };\n const oldSplice = array.splice;\n array.splice = (index, deleteCount) => {\n const deleted = oldSplice.apply(array, [index, deleteCount]);\n this._markAllSubMeshesAsTexturesDirty();\n return deleted;\n };\n }\n /**\n * Get one of the submaterial by its index in the submaterials array\n * @param index The index to look the sub material at\n * @returns The Material if the index has been defined\n */\n getSubMaterial(index) {\n if (index < 0 || index >= this.subMaterials.length) {\n return this.getScene().defaultMaterial;\n }\n return this.subMaterials[index];\n }\n /**\n * Get the list of active textures for the whole sub materials list.\n * @returns All the textures that will be used during the rendering\n */\n getActiveTextures() {\n return super.getActiveTextures().concat(...this.subMaterials.map((subMaterial) => {\n if (subMaterial) {\n return subMaterial.getActiveTextures();\n }\n else {\n return [];\n }\n }));\n }\n /**\n * Specifies if any sub-materials of this multi-material use a given texture.\n * @param texture Defines the texture to check against this multi-material's sub-materials.\n * @returns A boolean specifying if any sub-material of this multi-material uses the texture.\n */\n hasTexture(texture) {\n var _a;\n if (super.hasTexture(texture)) {\n return true;\n }\n for (let i = 0; i < this.subMaterials.length; i++) {\n if ((_a = this.subMaterials[i]) === null || _a === void 0 ? void 0 : _a.hasTexture(texture)) {\n return true;\n }\n }\n return false;\n }\n /**\n * Gets the current class name of the material e.g. \"MultiMaterial\"\n * Mainly use in serialization.\n * @returns the class name\n */\n getClassName() {\n return \"MultiMaterial\";\n }\n /**\n * Checks if the material is ready to render the requested sub mesh\n * @param mesh Define the mesh the submesh belongs to\n * @param subMesh Define the sub mesh to look readiness for\n * @param useInstances Define whether or not the material is used with instances\n * @returns true if ready, otherwise false\n */\n isReadyForSubMesh(mesh, subMesh, useInstances) {\n for (let index = 0; index < this.subMaterials.length; index++) {\n const subMaterial = this.subMaterials[index];\n if (subMaterial) {\n if (subMaterial._storeEffectOnSubMeshes) {\n if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {\n return false;\n }\n continue;\n }\n if (!subMaterial.isReady(mesh)) {\n return false;\n }\n }\n }\n return true;\n }\n /**\n * Clones the current material and its related sub materials\n * @param name Define the name of the newly cloned material\n * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance\n * @returns the cloned material\n */\n clone(name, cloneChildren) {\n const newMultiMaterial = new MultiMaterial(name, this.getScene());\n for (let index = 0; index < this.subMaterials.length; index++) {\n let subMaterial = null;\n const current = this.subMaterials[index];\n if (cloneChildren && current) {\n subMaterial = current.clone(name + \"-\" + current.name);\n }\n else {\n subMaterial = this.subMaterials[index];\n }\n newMultiMaterial.subMaterials.push(subMaterial);\n }\n return newMultiMaterial;\n }\n /**\n * Serializes the materials into a JSON representation.\n * @returns the JSON representation\n */\n serialize() {\n const serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.id = this.id;\n serializationObject.uniqueId = this.uniqueId;\n if (Tags) {\n serializationObject.tags = Tags.GetTags(this);\n }\n serializationObject.materialsUniqueIds = [];\n serializationObject.materials = [];\n for (let matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {\n const subMat = this.subMaterials[matIndex];\n if (subMat) {\n serializationObject.materialsUniqueIds.push(subMat.uniqueId);\n serializationObject.materials.push(subMat.id);\n }\n else {\n serializationObject.materialsUniqueIds.push(null);\n serializationObject.materials.push(null);\n }\n }\n return serializationObject;\n }\n /**\n * Dispose the material and release its associated resources\n * @param forceDisposeEffect Define if we want to force disposing the associated effect (if false the shader is not released and could be reuse later on)\n * @param forceDisposeTextures Define if we want to force disposing the associated textures (if false, they will not be disposed and can still be use elsewhere in the app)\n * @param forceDisposeChildren Define if we want to force disposing the associated submaterials (if false, they will not be disposed and can still be use elsewhere in the app)\n */\n dispose(forceDisposeEffect, forceDisposeTextures, forceDisposeChildren) {\n const scene = this.getScene();\n if (!scene) {\n return;\n }\n if (forceDisposeChildren) {\n for (let index = 0; index < this.subMaterials.length; index++) {\n const subMaterial = this.subMaterials[index];\n if (subMaterial) {\n subMaterial.dispose(forceDisposeEffect, forceDisposeTextures);\n }\n }\n }\n const index = scene.multiMaterials.indexOf(this);\n if (index >= 0) {\n scene.multiMaterials.splice(index, 1);\n }\n super.dispose(forceDisposeEffect, forceDisposeTextures);\n }\n /**\n * Creates a MultiMaterial from parsed MultiMaterial data.\n * @param parsedMultiMaterial defines parsed MultiMaterial data.\n * @param scene defines the hosting scene\n * @returns a new MultiMaterial\n */\n static ParseMultiMaterial(parsedMultiMaterial, scene) {\n const multiMaterial = new MultiMaterial(parsedMultiMaterial.name, scene);\n multiMaterial.id = parsedMultiMaterial.id;\n multiMaterial._loadedUniqueId = parsedMultiMaterial.uniqueId;\n if (Tags) {\n Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);\n }\n if (parsedMultiMaterial.materialsUniqueIds) {\n multiMaterial._waitingSubMaterialsUniqueIds = parsedMultiMaterial.materialsUniqueIds;\n }\n else {\n parsedMultiMaterial.materials.forEach((subMatId) => multiMaterial.subMaterials.push(scene.getLastMaterialById(subMatId)));\n }\n return multiMaterial;\n }\n}\nRegisterClass(\"BABYLON.MultiMaterial\", MultiMaterial);\n//# sourceMappingURL=multiMaterial.js.map","/**\n * Language of the shader code\n */\nexport var ShaderLanguage;\n(function (ShaderLanguage) {\n /** language is GLSL (used by WebGL) */\n ShaderLanguage[ShaderLanguage[\"GLSL\"] = 0] = \"GLSL\";\n /** language is WGSL (used by WebGPU) */\n ShaderLanguage[ShaderLanguage[\"WGSL\"] = 1] = \"WGSL\";\n})(ShaderLanguage || (ShaderLanguage = {}));\n//# sourceMappingURL=shaderLanguage.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { Tools } from \"../Misc/tools.js\";\nimport \"../Engines/Extensions/engine.uniformBuffer.js\";\n/**\n * Uniform buffer objects.\n *\n * Handles blocks of uniform on the GPU.\n *\n * If WebGL 2 is not available, this class falls back on traditional setUniformXXX calls.\n *\n * For more information, please refer to :\n * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object\n */\nexport class UniformBuffer {\n /**\n * Instantiates a new Uniform buffer objects.\n *\n * Handles blocks of uniform on the GPU.\n *\n * If WebGL 2 is not available, this class falls back on traditional setUniformXXX calls.\n *\n * For more information, please refer to :\n * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object\n * @param engine Define the engine the buffer is associated with\n * @param data Define the data contained in the buffer\n * @param dynamic Define if the buffer is updatable\n * @param name to assign to the buffer (debugging purpose)\n * @param forceNoUniformBuffer define that this object must not rely on UBO objects\n */\n constructor(engine, data, dynamic, name, forceNoUniformBuffer = false) {\n // Matrix cache\n this._valueCache = {};\n this._engine = engine;\n this._noUBO = !engine.supportsUniformBuffers || forceNoUniformBuffer;\n this._dynamic = dynamic;\n this._name = name !== null && name !== void 0 ? name : \"no-name\";\n this._data = data || [];\n this._uniformLocations = {};\n this._uniformSizes = {};\n this._uniformArraySizes = {};\n this._uniformLocationPointer = 0;\n this._needSync = false;\n if (this._engine._features.trackUbosInFrame) {\n this._buffers = [];\n this._bufferIndex = -1;\n this._createBufferOnWrite = false;\n this._currentFrameId = 0;\n }\n if (this._noUBO) {\n this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;\n this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;\n this.updateFloat = this._updateFloatForEffect;\n this.updateFloat2 = this._updateFloat2ForEffect;\n this.updateFloat3 = this._updateFloat3ForEffect;\n this.updateFloat4 = this._updateFloat4ForEffect;\n this.updateFloatArray = this._updateFloatArrayForEffect;\n this.updateArray = this._updateArrayForEffect;\n this.updateIntArray = this._updateIntArrayForEffect;\n this.updateUIntArray = this._updateUIntArrayForEffect;\n this.updateMatrix = this._updateMatrixForEffect;\n this.updateMatrices = this._updateMatricesForEffect;\n this.updateVector3 = this._updateVector3ForEffect;\n this.updateVector4 = this._updateVector4ForEffect;\n this.updateColor3 = this._updateColor3ForEffect;\n this.updateColor4 = this._updateColor4ForEffect;\n this.updateDirectColor4 = this._updateDirectColor4ForEffect;\n this.updateInt = this._updateIntForEffect;\n this.updateInt2 = this._updateInt2ForEffect;\n this.updateInt3 = this._updateInt3ForEffect;\n this.updateInt4 = this._updateInt4ForEffect;\n this.updateUInt = this._updateUIntForEffect;\n this.updateUInt2 = this._updateUInt2ForEffect;\n this.updateUInt3 = this._updateUInt3ForEffect;\n this.updateUInt4 = this._updateUInt4ForEffect;\n }\n else {\n this._engine._uniformBuffers.push(this);\n this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;\n this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;\n this.updateFloat = this._updateFloatForUniform;\n this.updateFloat2 = this._updateFloat2ForUniform;\n this.updateFloat3 = this._updateFloat3ForUniform;\n this.updateFloat4 = this._updateFloat4ForUniform;\n this.updateFloatArray = this._updateFloatArrayForUniform;\n this.updateArray = this._updateArrayForUniform;\n this.updateIntArray = this._updateIntArrayForUniform;\n this.updateUIntArray = this._updateUIntArrayForUniform;\n this.updateMatrix = this._updateMatrixForUniform;\n this.updateMatrices = this._updateMatricesForUniform;\n this.updateVector3 = this._updateVector3ForUniform;\n this.updateVector4 = this._updateVector4ForUniform;\n this.updateColor3 = this._updateColor3ForUniform;\n this.updateColor4 = this._updateColor4ForUniform;\n this.updateDirectColor4 = this._updateDirectColor4ForUniform;\n this.updateInt = this._updateIntForUniform;\n this.updateInt2 = this._updateInt2ForUniform;\n this.updateInt3 = this._updateInt3ForUniform;\n this.updateInt4 = this._updateInt4ForUniform;\n this.updateUInt = this._updateUIntForUniform;\n this.updateUInt2 = this._updateUInt2ForUniform;\n this.updateUInt3 = this._updateUInt3ForUniform;\n this.updateUInt4 = this._updateUInt4ForUniform;\n }\n }\n /**\n * Indicates if the buffer is using the WebGL2 UBO implementation,\n * or just falling back on setUniformXXX calls.\n */\n get useUbo() {\n return !this._noUBO;\n }\n /**\n * Indicates if the WebGL underlying uniform buffer is in sync\n * with the javascript cache data.\n */\n get isSync() {\n return !this._needSync;\n }\n /**\n * Indicates if the WebGL underlying uniform buffer is dynamic.\n * Also, a dynamic UniformBuffer will disable cache verification and always\n * update the underlying WebGL uniform buffer to the GPU.\n * @returns if Dynamic, otherwise false\n */\n isDynamic() {\n return this._dynamic !== undefined;\n }\n /**\n * The data cache on JS side.\n * @returns the underlying data as a float array\n */\n getData() {\n return this._bufferData;\n }\n /**\n * The underlying WebGL Uniform buffer.\n * @returns the webgl buffer\n */\n getBuffer() {\n return this._buffer;\n }\n /**\n * std140 layout specifies how to align data within an UBO structure.\n * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159\n * for specs.\n * @param size\n */\n _fillAlignment(size) {\n // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components\n // and 4x4 matrices\n // TODO : change if other types are used\n let alignment;\n if (size <= 2) {\n alignment = size;\n }\n else {\n alignment = 4;\n }\n if (this._uniformLocationPointer % alignment !== 0) {\n const oldPointer = this._uniformLocationPointer;\n this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);\n const diff = this._uniformLocationPointer - oldPointer;\n for (let i = 0; i < diff; i++) {\n this._data.push(0);\n }\n }\n }\n /**\n * Adds an uniform in the buffer.\n * Warning : the subsequents calls of this function must be in the same order as declared in the shader\n * for the layout to be correct ! The addUniform function only handles types like float, vec2, vec3, vec4, mat4,\n * meaning size=1,2,3,4 or 16. It does not handle struct types.\n * @param name Name of the uniform, as used in the uniform block in the shader.\n * @param size Data size, or data directly.\n * @param arraySize The number of elements in the array, 0 if not an array.\n */\n addUniform(name, size, arraySize = 0) {\n if (this._noUBO) {\n return;\n }\n if (this._uniformLocations[name] !== undefined) {\n // Already existing uniform\n return;\n }\n // This function must be called in the order of the shader layout !\n // size can be the size of the uniform, or data directly\n let data;\n // std140 FTW...\n if (arraySize > 0) {\n if (size instanceof Array) {\n throw \"addUniform should not be use with Array in UBO: \" + name;\n }\n this._fillAlignment(4);\n this._uniformArraySizes[name] = { strideSize: size, arraySize };\n if (size == 16) {\n size = size * arraySize;\n }\n else {\n const perElementPadding = 4 - size;\n const totalPadding = perElementPadding * arraySize;\n size = size * arraySize + totalPadding;\n }\n data = [];\n // Fill with zeros\n for (let i = 0; i < size; i++) {\n data.push(0);\n }\n }\n else {\n if (size instanceof Array) {\n data = size;\n size = data.length;\n }\n else {\n size = size;\n data = [];\n // Fill with zeros\n for (let i = 0; i < size; i++) {\n data.push(0);\n }\n }\n this._fillAlignment(size);\n }\n this._uniformSizes[name] = size;\n this._uniformLocations[name] = this._uniformLocationPointer;\n this._uniformLocationPointer += size;\n for (let i = 0; i < size; i++) {\n this._data.push(data[i]);\n }\n this._needSync = true;\n }\n /**\n * Adds a Matrix 4x4 to the uniform buffer.\n * @param name Name of the uniform, as used in the uniform block in the shader.\n * @param mat A 4x4 matrix.\n */\n addMatrix(name, mat) {\n this.addUniform(name, Array.prototype.slice.call(mat.toArray()));\n }\n /**\n * Adds a vec2 to the uniform buffer.\n * @param name Name of the uniform, as used in the uniform block in the shader.\n * @param x Define the x component value of the vec2\n * @param y Define the y component value of the vec2\n */\n addFloat2(name, x, y) {\n const temp = [x, y];\n this.addUniform(name, temp);\n }\n /**\n * Adds a vec3 to the uniform buffer.\n * @param name Name of the uniform, as used in the uniform block in the shader.\n * @param x Define the x component value of the vec3\n * @param y Define the y component value of the vec3\n * @param z Define the z component value of the vec3\n */\n addFloat3(name, x, y, z) {\n const temp = [x, y, z];\n this.addUniform(name, temp);\n }\n /**\n * Adds a vec3 to the uniform buffer.\n * @param name Name of the uniform, as used in the uniform block in the shader.\n * @param color Define the vec3 from a Color\n */\n addColor3(name, color) {\n const temp = [color.r, color.g, color.b];\n this.addUniform(name, temp);\n }\n /**\n * Adds a vec4 to the uniform buffer.\n * @param name Name of the uniform, as used in the uniform block in the shader.\n * @param color Define the rgb components from a Color\n * @param alpha Define the a component of the vec4\n */\n addColor4(name, color, alpha) {\n const temp = [color.r, color.g, color.b, alpha];\n this.addUniform(name, temp);\n }\n /**\n * Adds a vec3 to the uniform buffer.\n * @param name Name of the uniform, as used in the uniform block in the shader.\n * @param vector Define the vec3 components from a Vector\n */\n addVector3(name, vector) {\n const temp = [vector.x, vector.y, vector.z];\n this.addUniform(name, temp);\n }\n /**\n * Adds a Matrix 3x3 to the uniform buffer.\n * @param name Name of the uniform, as used in the uniform block in the shader.\n */\n addMatrix3x3(name) {\n this.addUniform(name, 12);\n }\n /**\n * Adds a Matrix 2x2 to the uniform buffer.\n * @param name Name of the uniform, as used in the uniform block in the shader.\n */\n addMatrix2x2(name) {\n this.addUniform(name, 8);\n }\n /**\n * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.\n */\n create() {\n if (this._noUBO) {\n return;\n }\n if (this._buffer) {\n return; // nothing to do\n }\n // See spec, alignment must be filled as a vec4\n this._fillAlignment(4);\n this._bufferData = new Float32Array(this._data);\n this._rebuild();\n this._needSync = true;\n }\n /** @internal */\n _rebuild() {\n if (this._noUBO || !this._bufferData) {\n return;\n }\n if (this._dynamic) {\n this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);\n }\n else {\n this._buffer = this._engine.createUniformBuffer(this._bufferData);\n }\n if (this._engine._features.trackUbosInFrame) {\n this._buffers.push([this._buffer, this._engine._features.checkUbosContentBeforeUpload ? this._bufferData.slice() : undefined]);\n this._bufferIndex = this._buffers.length - 1;\n this._createBufferOnWrite = false;\n }\n }\n /** @internal */\n get _numBuffers() {\n return this._buffers.length;\n }\n /** @internal */\n get _indexBuffer() {\n return this._bufferIndex;\n }\n /** Gets the name of this buffer */\n get name() {\n return this._name;\n }\n /** Gets the current effect */\n get currentEffect() {\n return this._currentEffect;\n }\n _buffersEqual(buf1, buf2) {\n for (let i = 0; i < buf1.length; ++i) {\n if (buf1[i] !== buf2[i]) {\n return false;\n }\n }\n return true;\n }\n _copyBuffer(src, dst) {\n for (let i = 0; i < src.length; ++i) {\n dst[i] = src[i];\n }\n }\n /**\n * Updates the WebGL Uniform Buffer on the GPU.\n * If the `dynamic` flag is set to true, no cache comparison is done.\n * Otherwise, the buffer will be updated only if the cache differs.\n */\n update() {\n if (this._noUBO) {\n return;\n }\n this.bindUniformBuffer();\n if (!this._buffer) {\n this.create();\n return;\n }\n if (!this._dynamic && !this._needSync) {\n this._createBufferOnWrite = this._engine._features.trackUbosInFrame;\n return;\n }\n if (this._buffers && this._buffers.length > 1 && this._buffers[this._bufferIndex][1]) {\n if (this._buffersEqual(this._bufferData, this._buffers[this._bufferIndex][1])) {\n this._needSync = false;\n this._createBufferOnWrite = this._engine._features.trackUbosInFrame;\n return;\n }\n else {\n this._copyBuffer(this._bufferData, this._buffers[this._bufferIndex][1]);\n }\n }\n this._engine.updateUniformBuffer(this._buffer, this._bufferData);\n if (this._engine._features._collectUbosUpdatedInFrame) {\n if (!UniformBuffer._UpdatedUbosInFrame[this._name]) {\n UniformBuffer._UpdatedUbosInFrame[this._name] = 0;\n }\n UniformBuffer._UpdatedUbosInFrame[this._name]++;\n }\n this._needSync = false;\n this._createBufferOnWrite = this._engine._features.trackUbosInFrame;\n }\n _createNewBuffer() {\n if (this._bufferIndex + 1 < this._buffers.length) {\n this._bufferIndex++;\n this._buffer = this._buffers[this._bufferIndex][0];\n this._createBufferOnWrite = false;\n this._needSync = true;\n }\n else {\n this._rebuild();\n }\n }\n _checkNewFrame() {\n if (this._engine._features.trackUbosInFrame && this._currentFrameId !== this._engine.frameId) {\n this._currentFrameId = this._engine.frameId;\n this._createBufferOnWrite = false;\n if (this._buffers && this._buffers.length > 0) {\n this._needSync = this._bufferIndex !== 0;\n this._bufferIndex = 0;\n this._buffer = this._buffers[this._bufferIndex][0];\n }\n else {\n this._bufferIndex = -1;\n }\n }\n }\n /**\n * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.\n * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.\n * @param data Define the flattened data\n * @param size Define the size of the data.\n */\n updateUniform(uniformName, data, size) {\n this._checkNewFrame();\n let location = this._uniformLocations[uniformName];\n if (location === undefined) {\n if (this._buffer) {\n // Cannot add an uniform if the buffer is already created\n Logger.Error(\"Cannot add an uniform after UBO has been created.\");\n return;\n }\n this.addUniform(uniformName, size);\n location = this._uniformLocations[uniformName];\n }\n if (!this._buffer) {\n this.create();\n }\n if (!this._dynamic) {\n // Cache for static uniform buffers\n let changed = false;\n for (let i = 0; i < size; i++) {\n // We are checking the matrix cache before calling updateUniform so we do not need to check it here\n // Hence the test for size === 16 to simply commit the matrix values\n if ((size === 16 && !this._engine._features.uniformBufferHardCheckMatrix) || this._bufferData[location + i] !== Tools.FloatRound(data[i])) {\n changed = true;\n if (this._createBufferOnWrite) {\n this._createNewBuffer();\n }\n this._bufferData[location + i] = data[i];\n }\n }\n this._needSync = this._needSync || changed;\n }\n else {\n // No cache for dynamic\n for (let i = 0; i < size; i++) {\n this._bufferData[location + i] = data[i];\n }\n }\n }\n /**\n * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.\n * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.\n * @param data Define the flattened data\n * @param size Define the size of the data.\n */\n updateUniformArray(uniformName, data, size) {\n this._checkNewFrame();\n const location = this._uniformLocations[uniformName];\n if (location === undefined) {\n Logger.Error(\"Cannot add an uniform Array dynamically. Please, add it using addUniform and make sure that uniform buffers are supported by the current engine.\");\n return;\n }\n if (!this._buffer) {\n this.create();\n }\n const arraySizes = this._uniformArraySizes[uniformName];\n if (!this._dynamic) {\n // Cache for static uniform buffers\n let changed = false;\n let countToFour = 0;\n let baseStride = 0;\n for (let i = 0; i < size; i++) {\n if (this._bufferData[location + baseStride * 4 + countToFour] !== Tools.FloatRound(data[i])) {\n changed = true;\n if (this._createBufferOnWrite) {\n this._createNewBuffer();\n }\n this._bufferData[location + baseStride * 4 + countToFour] = data[i];\n }\n countToFour++;\n if (countToFour === arraySizes.strideSize) {\n for (; countToFour < 4; countToFour++) {\n this._bufferData[location + baseStride * 4 + countToFour] = 0;\n }\n countToFour = 0;\n baseStride++;\n }\n }\n this._needSync = this._needSync || changed;\n }\n else {\n // No cache for dynamic\n for (let i = 0; i < size; i++) {\n this._bufferData[location + i] = data[i];\n }\n }\n }\n _cacheMatrix(name, matrix) {\n this._checkNewFrame();\n const cache = this._valueCache[name];\n const flag = matrix.updateFlag;\n if (cache !== undefined && cache === flag) {\n return false;\n }\n this._valueCache[name] = flag;\n return true;\n }\n // Update methods\n _updateMatrix3x3ForUniform(name, matrix) {\n // To match std140, matrix must be realigned\n for (let i = 0; i < 3; i++) {\n UniformBuffer._TempBuffer[i * 4] = matrix[i * 3];\n UniformBuffer._TempBuffer[i * 4 + 1] = matrix[i * 3 + 1];\n UniformBuffer._TempBuffer[i * 4 + 2] = matrix[i * 3 + 2];\n UniformBuffer._TempBuffer[i * 4 + 3] = 0.0;\n }\n this.updateUniform(name, UniformBuffer._TempBuffer, 12);\n }\n _updateMatrix3x3ForEffect(name, matrix) {\n this._currentEffect.setMatrix3x3(name, matrix);\n }\n _updateMatrix2x2ForEffect(name, matrix) {\n this._currentEffect.setMatrix2x2(name, matrix);\n }\n _updateMatrix2x2ForUniform(name, matrix) {\n // To match std140, matrix must be realigned\n for (let i = 0; i < 2; i++) {\n UniformBuffer._TempBuffer[i * 4] = matrix[i * 2];\n UniformBuffer._TempBuffer[i * 4 + 1] = matrix[i * 2 + 1];\n UniformBuffer._TempBuffer[i * 4 + 2] = 0.0;\n UniformBuffer._TempBuffer[i * 4 + 3] = 0.0;\n }\n this.updateUniform(name, UniformBuffer._TempBuffer, 8);\n }\n _updateFloatForEffect(name, x) {\n this._currentEffect.setFloat(name, x);\n }\n _updateFloatForUniform(name, x) {\n UniformBuffer._TempBuffer[0] = x;\n this.updateUniform(name, UniformBuffer._TempBuffer, 1);\n }\n _updateFloat2ForEffect(name, x, y, suffix = \"\") {\n this._currentEffect.setFloat2(name + suffix, x, y);\n }\n _updateFloat2ForUniform(name, x, y) {\n UniformBuffer._TempBuffer[0] = x;\n UniformBuffer._TempBuffer[1] = y;\n this.updateUniform(name, UniformBuffer._TempBuffer, 2);\n }\n _updateFloat3ForEffect(name, x, y, z, suffix = \"\") {\n this._currentEffect.setFloat3(name + suffix, x, y, z);\n }\n _updateFloat3ForUniform(name, x, y, z) {\n UniformBuffer._TempBuffer[0] = x;\n UniformBuffer._TempBuffer[1] = y;\n UniformBuffer._TempBuffer[2] = z;\n this.updateUniform(name, UniformBuffer._TempBuffer, 3);\n }\n _updateFloat4ForEffect(name, x, y, z, w, suffix = \"\") {\n this._currentEffect.setFloat4(name + suffix, x, y, z, w);\n }\n _updateFloat4ForUniform(name, x, y, z, w) {\n UniformBuffer._TempBuffer[0] = x;\n UniformBuffer._TempBuffer[1] = y;\n UniformBuffer._TempBuffer[2] = z;\n UniformBuffer._TempBuffer[3] = w;\n this.updateUniform(name, UniformBuffer._TempBuffer, 4);\n }\n _updateFloatArrayForEffect(name, array) {\n this._currentEffect.setFloatArray(name, array);\n }\n _updateFloatArrayForUniform(name, array) {\n this.updateUniformArray(name, array, array.length);\n }\n _updateArrayForEffect(name, array) {\n this._currentEffect.setArray(name, array);\n }\n _updateArrayForUniform(name, array) {\n this.updateUniformArray(name, array, array.length);\n }\n _updateIntArrayForEffect(name, array) {\n this._currentEffect.setIntArray(name, array);\n }\n _updateIntArrayForUniform(name, array) {\n UniformBuffer._TempBufferInt32View.set(array);\n this.updateUniformArray(name, UniformBuffer._TempBuffer, array.length);\n }\n _updateUIntArrayForEffect(name, array) {\n this._currentEffect.setUIntArray(name, array);\n }\n _updateUIntArrayForUniform(name, array) {\n UniformBuffer._TempBufferUInt32View.set(array);\n this.updateUniformArray(name, UniformBuffer._TempBuffer, array.length);\n }\n _updateMatrixForEffect(name, mat) {\n this._currentEffect.setMatrix(name, mat);\n }\n _updateMatrixForUniform(name, mat) {\n if (this._cacheMatrix(name, mat)) {\n this.updateUniform(name, mat.toArray(), 16);\n }\n }\n _updateMatricesForEffect(name, mat) {\n this._currentEffect.setMatrices(name, mat);\n }\n _updateMatricesForUniform(name, mat) {\n this.updateUniform(name, mat, mat.length);\n }\n _updateVector3ForEffect(name, vector) {\n this._currentEffect.setVector3(name, vector);\n }\n _updateVector3ForUniform(name, vector) {\n UniformBuffer._TempBuffer[0] = vector.x;\n UniformBuffer._TempBuffer[1] = vector.y;\n UniformBuffer._TempBuffer[2] = vector.z;\n this.updateUniform(name, UniformBuffer._TempBuffer, 3);\n }\n _updateVector4ForEffect(name, vector) {\n this._currentEffect.setVector4(name, vector);\n }\n _updateVector4ForUniform(name, vector) {\n UniformBuffer._TempBuffer[0] = vector.x;\n UniformBuffer._TempBuffer[1] = vector.y;\n UniformBuffer._TempBuffer[2] = vector.z;\n UniformBuffer._TempBuffer[3] = vector.w;\n this.updateUniform(name, UniformBuffer._TempBuffer, 4);\n }\n _updateColor3ForEffect(name, color, suffix = \"\") {\n this._currentEffect.setColor3(name + suffix, color);\n }\n _updateColor3ForUniform(name, color) {\n UniformBuffer._TempBuffer[0] = color.r;\n UniformBuffer._TempBuffer[1] = color.g;\n UniformBuffer._TempBuffer[2] = color.b;\n this.updateUniform(name, UniformBuffer._TempBuffer, 3);\n }\n _updateColor4ForEffect(name, color, alpha, suffix = \"\") {\n this._currentEffect.setColor4(name + suffix, color, alpha);\n }\n _updateDirectColor4ForEffect(name, color, suffix = \"\") {\n this._currentEffect.setDirectColor4(name + suffix, color);\n }\n _updateColor4ForUniform(name, color, alpha) {\n UniformBuffer._TempBuffer[0] = color.r;\n UniformBuffer._TempBuffer[1] = color.g;\n UniformBuffer._TempBuffer[2] = color.b;\n UniformBuffer._TempBuffer[3] = alpha;\n this.updateUniform(name, UniformBuffer._TempBuffer, 4);\n }\n _updateDirectColor4ForUniform(name, color) {\n UniformBuffer._TempBuffer[0] = color.r;\n UniformBuffer._TempBuffer[1] = color.g;\n UniformBuffer._TempBuffer[2] = color.b;\n UniformBuffer._TempBuffer[3] = color.a;\n this.updateUniform(name, UniformBuffer._TempBuffer, 4);\n }\n _updateIntForEffect(name, x, suffix = \"\") {\n this._currentEffect.setInt(name + suffix, x);\n }\n _updateIntForUniform(name, x) {\n UniformBuffer._TempBufferInt32View[0] = x;\n this.updateUniform(name, UniformBuffer._TempBuffer, 1);\n }\n _updateInt2ForEffect(name, x, y, suffix = \"\") {\n this._currentEffect.setInt2(name + suffix, x, y);\n }\n _updateInt2ForUniform(name, x, y) {\n UniformBuffer._TempBufferInt32View[0] = x;\n UniformBuffer._TempBufferInt32View[1] = y;\n this.updateUniform(name, UniformBuffer._TempBuffer, 2);\n }\n _updateInt3ForEffect(name, x, y, z, suffix = \"\") {\n this._currentEffect.setInt3(name + suffix, x, y, z);\n }\n _updateInt3ForUniform(name, x, y, z) {\n UniformBuffer._TempBufferInt32View[0] = x;\n UniformBuffer._TempBufferInt32View[1] = y;\n UniformBuffer._TempBufferInt32View[2] = z;\n this.updateUniform(name, UniformBuffer._TempBuffer, 3);\n }\n _updateInt4ForEffect(name, x, y, z, w, suffix = \"\") {\n this._currentEffect.setInt4(name + suffix, x, y, z, w);\n }\n _updateInt4ForUniform(name, x, y, z, w) {\n UniformBuffer._TempBufferInt32View[0] = x;\n UniformBuffer._TempBufferInt32View[1] = y;\n UniformBuffer._TempBufferInt32View[2] = z;\n UniformBuffer._TempBufferInt32View[3] = w;\n this.updateUniform(name, UniformBuffer._TempBuffer, 4);\n }\n _updateUIntForEffect(name, x, suffix = \"\") {\n this._currentEffect.setUInt(name + suffix, x);\n }\n _updateUIntForUniform(name, x) {\n UniformBuffer._TempBufferUInt32View[0] = x;\n this.updateUniform(name, UniformBuffer._TempBuffer, 1);\n }\n _updateUInt2ForEffect(name, x, y, suffix = \"\") {\n this._currentEffect.setUInt2(name + suffix, x, y);\n }\n _updateUInt2ForUniform(name, x, y) {\n UniformBuffer._TempBufferUInt32View[0] = x;\n UniformBuffer._TempBufferUInt32View[1] = y;\n this.updateUniform(name, UniformBuffer._TempBuffer, 2);\n }\n _updateUInt3ForEffect(name, x, y, z, suffix = \"\") {\n this._currentEffect.setUInt3(name + suffix, x, y, z);\n }\n _updateUInt3ForUniform(name, x, y, z) {\n UniformBuffer._TempBufferUInt32View[0] = x;\n UniformBuffer._TempBufferUInt32View[1] = y;\n UniformBuffer._TempBufferUInt32View[2] = z;\n this.updateUniform(name, UniformBuffer._TempBuffer, 3);\n }\n _updateUInt4ForEffect(name, x, y, z, w, suffix = \"\") {\n this._currentEffect.setUInt4(name + suffix, x, y, z, w);\n }\n _updateUInt4ForUniform(name, x, y, z, w) {\n UniformBuffer._TempBufferUInt32View[0] = x;\n UniformBuffer._TempBufferUInt32View[1] = y;\n UniformBuffer._TempBufferUInt32View[2] = z;\n UniformBuffer._TempBufferUInt32View[3] = w;\n this.updateUniform(name, UniformBuffer._TempBuffer, 4);\n }\n /**\n * Sets a sampler uniform on the effect.\n * @param name Define the name of the sampler.\n * @param texture Define the texture to set in the sampler\n */\n setTexture(name, texture) {\n this._currentEffect.setTexture(name, texture);\n }\n /**\n * Directly updates the value of the uniform in the cache AND on the GPU.\n * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.\n * @param data Define the flattened data\n */\n updateUniformDirectly(uniformName, data) {\n this.updateUniform(uniformName, data, data.length);\n this.update();\n }\n /**\n * Associates an effect to this uniform buffer\n * @param effect Define the effect to associate the buffer to\n * @param name Name of the uniform block in the shader.\n */\n bindToEffect(effect, name) {\n this._currentEffect = effect;\n this._currentEffectName = name;\n }\n /**\n * Binds the current (GPU) buffer to the effect\n */\n bindUniformBuffer() {\n if (!this._noUBO && this._buffer && this._currentEffect) {\n this._currentEffect.bindUniformBuffer(this._buffer, this._currentEffectName);\n }\n }\n /**\n * Dissociates the current effect from this uniform buffer\n */\n unbindEffect() {\n this._currentEffect = undefined;\n this._currentEffectName = undefined;\n }\n /**\n * Sets the current state of the class (_bufferIndex, _buffer) to point to the data buffer passed in parameter if this buffer is one of the buffers handled by the class (meaning if it can be found in the _buffers array)\n * This method is meant to be able to update a buffer at any time: just call setDataBuffer to set the class in the right state, call some updateXXX methods and then call udpate() => that will update the GPU buffer on the graphic card\n * @param dataBuffer buffer to look for\n * @returns true if the buffer has been found and the class internal state points to it, else false\n */\n setDataBuffer(dataBuffer) {\n if (!this._buffers) {\n return this._buffer === dataBuffer;\n }\n for (let b = 0; b < this._buffers.length; ++b) {\n const buffer = this._buffers[b];\n if (buffer[0] === dataBuffer) {\n this._bufferIndex = b;\n this._buffer = dataBuffer;\n this._createBufferOnWrite = false;\n this._currentEffect = undefined;\n return true;\n }\n }\n return false;\n }\n /**\n * Disposes the uniform buffer.\n */\n dispose() {\n if (this._noUBO) {\n return;\n }\n const uniformBuffers = this._engine._uniformBuffers;\n const index = uniformBuffers.indexOf(this);\n if (index !== -1) {\n uniformBuffers[index] = uniformBuffers[uniformBuffers.length - 1];\n uniformBuffers.pop();\n }\n if (this._engine._features.trackUbosInFrame && this._buffers) {\n for (let i = 0; i < this._buffers.length; ++i) {\n const buffer = this._buffers[i][0];\n this._engine._releaseBuffer(buffer);\n }\n }\n else if (this._buffer && this._engine._releaseBuffer(this._buffer)) {\n this._buffer = null;\n }\n }\n}\n/** @internal */\nUniformBuffer._UpdatedUbosInFrame = {};\n// Pool for avoiding memory leaks\nUniformBuffer._MAX_UNIFORM_SIZE = 256;\nUniformBuffer._TempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);\nUniformBuffer._TempBufferInt32View = new Int32Array(UniformBuffer._TempBuffer.buffer);\nUniformBuffer._TempBufferUInt32View = new Uint32Array(UniformBuffer._TempBuffer.buffer);\n//# sourceMappingURL=uniformBuffer.js.map","import { Vector3 } from \"./math.vector.js\";\n/** Defines supported spaces */\nexport var Space;\n(function (Space) {\n /** Local (object) space */\n Space[Space[\"LOCAL\"] = 0] = \"LOCAL\";\n /** World space */\n Space[Space[\"WORLD\"] = 1] = \"WORLD\";\n /** Bone space */\n Space[Space[\"BONE\"] = 2] = \"BONE\";\n})(Space || (Space = {}));\n/** Defines the 3 main axes */\nexport class Axis {\n}\n/** X axis */\nAxis.X = new Vector3(1.0, 0.0, 0.0);\n/** Y axis */\nAxis.Y = new Vector3(0.0, 1.0, 0.0);\n/** Z axis */\nAxis.Z = new Vector3(0.0, 0.0, 1.0);\n/**\n * Defines cartesian components.\n */\nexport var Coordinate;\n(function (Coordinate) {\n /** X axis */\n Coordinate[Coordinate[\"X\"] = 0] = \"X\";\n /** Y axis */\n Coordinate[Coordinate[\"Y\"] = 1] = \"Y\";\n /** Z axis */\n Coordinate[Coordinate[\"Z\"] = 2] = \"Z\";\n})(Coordinate || (Coordinate = {}));\n//# sourceMappingURL=math.axis.js.map","import { Scalar } from \"./math.scalar.js\";\nimport { ToLinearSpace, ToGammaSpace } from \"./math.constants.js\";\nimport { ArrayTools } from \"../Misc/arrayTools.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\nfunction colorChannelToLinearSpace(color) {\n return Math.pow(color, ToLinearSpace);\n}\nfunction colorChannelToLinearSpaceExact(color) {\n if (color <= 0.04045) {\n return 0.0773993808 * color;\n }\n return Math.pow(0.947867299 * (color + 0.055), 2.4);\n}\nfunction colorChannelToGammaSpace(color) {\n return Math.pow(color, ToGammaSpace);\n}\nfunction colorChannelToGammaSpaceExact(color) {\n if (color <= 0.0031308) {\n return 12.92 * color;\n }\n return 1.055 * Math.pow(color, 0.41666) - 0.055;\n}\n/**\n * Class used to hold a RGB color\n */\nexport class Color3 {\n /**\n * Creates a new Color3 object from red, green, blue values, all between 0 and 1\n * @param r defines the red component (between 0 and 1, default is 0)\n * @param g defines the green component (between 0 and 1, default is 0)\n * @param b defines the blue component (between 0 and 1, default is 0)\n */\n constructor(\n /**\n * Defines the red component (between 0 and 1, default is 0)\n */\n r = 0, \n /**\n * Defines the green component (between 0 and 1, default is 0)\n */\n g = 0, \n /**\n * Defines the blue component (between 0 and 1, default is 0)\n */\n b = 0) {\n this.r = r;\n this.g = g;\n this.b = b;\n }\n /**\n * Creates a string with the Color3 current values\n * @returns the string representation of the Color3 object\n */\n toString() {\n return \"{R: \" + this.r + \" G:\" + this.g + \" B:\" + this.b + \"}\";\n }\n /**\n * Returns the string \"Color3\"\n * @returns \"Color3\"\n */\n getClassName() {\n return \"Color3\";\n }\n /**\n * Compute the Color3 hash code\n * @returns an unique number that can be used to hash Color3 objects\n */\n getHashCode() {\n let hash = (this.r * 255) | 0;\n hash = (hash * 397) ^ ((this.g * 255) | 0);\n hash = (hash * 397) ^ ((this.b * 255) | 0);\n return hash;\n }\n // Operators\n /**\n * Stores in the given array from the given starting index the red, green, blue values as successive elements\n * @param array defines the array where to store the r,g,b components\n * @param index defines an optional index in the target array to define where to start storing values\n * @returns the current Color3 object\n */\n toArray(array, index = 0) {\n array[index] = this.r;\n array[index + 1] = this.g;\n array[index + 2] = this.b;\n return this;\n }\n /**\n * Update the current color with values stored in an array from the starting index of the given array\n * @param array defines the source array\n * @param offset defines an offset in the source array\n * @returns the current Color3 object\n */\n fromArray(array, offset = 0) {\n Color3.FromArrayToRef(array, offset, this);\n return this;\n }\n /**\n * Returns a new Color4 object from the current Color3 and the given alpha\n * @param alpha defines the alpha component on the new Color4 object (default is 1)\n * @returns a new Color4 object\n */\n toColor4(alpha = 1) {\n return new Color4(this.r, this.g, this.b, alpha);\n }\n /**\n * Returns a new array populated with 3 numeric elements : red, green and blue values\n * @returns the new array\n */\n asArray() {\n return [this.r, this.g, this.b];\n }\n /**\n * Returns the luminance value\n * @returns a float value\n */\n toLuminance() {\n return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;\n }\n /**\n * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object\n * @param otherColor defines the second operand\n * @returns the new Color3 object\n */\n multiply(otherColor) {\n return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);\n }\n /**\n * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object \"result\"\n * @param otherColor defines the second operand\n * @param result defines the Color3 object where to store the result\n * @returns the current Color3\n */\n multiplyToRef(otherColor, result) {\n result.r = this.r * otherColor.r;\n result.g = this.g * otherColor.g;\n result.b = this.b * otherColor.b;\n return this;\n }\n /**\n * Determines equality between Color3 objects\n * @param otherColor defines the second operand\n * @returns true if the rgb values are equal to the given ones\n */\n equals(otherColor) {\n return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;\n }\n /**\n * Determines equality between the current Color3 object and a set of r,b,g values\n * @param r defines the red component to check\n * @param g defines the green component to check\n * @param b defines the blue component to check\n * @returns true if the rgb values are equal to the given ones\n */\n equalsFloats(r, g, b) {\n return this.r === r && this.g === g && this.b === b;\n }\n /**\n * Creates a new Color3 with the current Color3 values multiplied by scale\n * @param scale defines the scaling factor to apply\n * @returns a new Color3 object\n */\n scale(scale) {\n return new Color3(this.r * scale, this.g * scale, this.b * scale);\n }\n /**\n * Multiplies the Color3 values by the float \"scale\"\n * @param scale defines the scaling factor to apply\n * @returns the current updated Color3\n */\n scaleInPlace(scale) {\n this.r *= scale;\n this.g *= scale;\n this.b *= scale;\n return this;\n }\n /**\n * Multiplies the rgb values by scale and stores the result into \"result\"\n * @param scale defines the scaling factor\n * @param result defines the Color3 object where to store the result\n * @returns the unmodified current Color3\n */\n scaleToRef(scale, result) {\n result.r = this.r * scale;\n result.g = this.g * scale;\n result.b = this.b * scale;\n return this;\n }\n /**\n * Scale the current Color3 values by a factor and add the result to a given Color3\n * @param scale defines the scale factor\n * @param result defines color to store the result into\n * @returns the unmodified current Color3\n */\n scaleAndAddToRef(scale, result) {\n result.r += this.r * scale;\n result.g += this.g * scale;\n result.b += this.b * scale;\n return this;\n }\n /**\n * Clamps the rgb values by the min and max values and stores the result into \"result\"\n * @param min defines minimum clamping value (default is 0)\n * @param max defines maximum clamping value (default is 1)\n * @param result defines color to store the result into\n * @returns the original Color3\n */\n clampToRef(min = 0, max = 1, result) {\n result.r = Scalar.Clamp(this.r, min, max);\n result.g = Scalar.Clamp(this.g, min, max);\n result.b = Scalar.Clamp(this.b, min, max);\n return this;\n }\n /**\n * Creates a new Color3 set with the added values of the current Color3 and of the given one\n * @param otherColor defines the second operand\n * @returns the new Color3\n */\n add(otherColor) {\n return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);\n }\n /**\n * Stores the result of the addition of the current Color3 and given one rgb values into \"result\"\n * @param otherColor defines the second operand\n * @param result defines Color3 object to store the result into\n * @returns the unmodified current Color3\n */\n addToRef(otherColor, result) {\n result.r = this.r + otherColor.r;\n result.g = this.g + otherColor.g;\n result.b = this.b + otherColor.b;\n return this;\n }\n /**\n * Returns a new Color3 set with the subtracted values of the given one from the current Color3\n * @param otherColor defines the second operand\n * @returns the new Color3\n */\n subtract(otherColor) {\n return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);\n }\n /**\n * Stores the result of the subtraction of given one from the current Color3 rgb values into \"result\"\n * @param otherColor defines the second operand\n * @param result defines Color3 object to store the result into\n * @returns the unmodified current Color3\n */\n subtractToRef(otherColor, result) {\n result.r = this.r - otherColor.r;\n result.g = this.g - otherColor.g;\n result.b = this.b - otherColor.b;\n return this;\n }\n /**\n * Copy the current object\n * @returns a new Color3 copied the current one\n */\n clone() {\n return new Color3(this.r, this.g, this.b);\n }\n /**\n * Copies the rgb values from the source in the current Color3\n * @param source defines the source Color3 object\n * @returns the updated Color3 object\n */\n copyFrom(source) {\n this.r = source.r;\n this.g = source.g;\n this.b = source.b;\n return this;\n }\n /**\n * Updates the Color3 rgb values from the given floats\n * @param r defines the red component to read from\n * @param g defines the green component to read from\n * @param b defines the blue component to read from\n * @returns the current Color3 object\n */\n copyFromFloats(r, g, b) {\n this.r = r;\n this.g = g;\n this.b = b;\n return this;\n }\n /**\n * Updates the Color3 rgb values from the given floats\n * @param r defines the red component to read from\n * @param g defines the green component to read from\n * @param b defines the blue component to read from\n * @returns the current Color3 object\n */\n set(r, g, b) {\n return this.copyFromFloats(r, g, b);\n }\n /**\n * Compute the Color3 hexadecimal code as a string\n * @returns a string containing the hexadecimal representation of the Color3 object\n */\n toHexString() {\n const intR = Math.round(this.r * 255);\n const intG = Math.round(this.g * 255);\n const intB = Math.round(this.b * 255);\n return \"#\" + Scalar.ToHex(intR) + Scalar.ToHex(intG) + Scalar.ToHex(intB);\n }\n /**\n * Converts current color in rgb space to HSV values\n * @returns a new color3 representing the HSV values\n */\n toHSV() {\n const result = new Color3();\n this.toHSVToRef(result);\n return result;\n }\n /**\n * Converts current color in rgb space to HSV values\n * @param result defines the Color3 where to store the HSV values\n */\n toHSVToRef(result) {\n const r = this.r;\n const g = this.g;\n const b = this.b;\n const max = Math.max(r, g, b);\n const min = Math.min(r, g, b);\n let h = 0;\n let s = 0;\n const v = max;\n const dm = max - min;\n if (max !== 0) {\n s = dm / max;\n }\n if (max != min) {\n if (max == r) {\n h = (g - b) / dm;\n if (g < b) {\n h += 6;\n }\n }\n else if (max == g) {\n h = (b - r) / dm + 2;\n }\n else if (max == b) {\n h = (r - g) / dm + 4;\n }\n h *= 60;\n }\n result.r = h;\n result.g = s;\n result.b = v;\n }\n /**\n * Computes a new Color3 converted from the current one to linear space\n * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false)\n * @returns a new Color3 object\n */\n toLinearSpace(exact = false) {\n const convertedColor = new Color3();\n this.toLinearSpaceToRef(convertedColor, exact);\n return convertedColor;\n }\n /**\n * Converts the Color3 values to linear space and stores the result in \"convertedColor\"\n * @param convertedColor defines the Color3 object where to store the linear space version\n * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false)\n * @returns the unmodified Color3\n */\n toLinearSpaceToRef(convertedColor, exact = false) {\n if (exact) {\n convertedColor.r = colorChannelToLinearSpaceExact(this.r);\n convertedColor.g = colorChannelToLinearSpaceExact(this.g);\n convertedColor.b = colorChannelToLinearSpaceExact(this.b);\n }\n else {\n convertedColor.r = colorChannelToLinearSpace(this.r);\n convertedColor.g = colorChannelToLinearSpace(this.g);\n convertedColor.b = colorChannelToLinearSpace(this.b);\n }\n return this;\n }\n /**\n * Computes a new Color3 converted from the current one to gamma space\n * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false)\n * @returns a new Color3 object\n */\n toGammaSpace(exact = false) {\n const convertedColor = new Color3();\n this.toGammaSpaceToRef(convertedColor, exact);\n return convertedColor;\n }\n /**\n * Converts the Color3 values to gamma space and stores the result in \"convertedColor\"\n * @param convertedColor defines the Color3 object where to store the gamma space version\n * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false)\n * @returns the unmodified Color3\n */\n toGammaSpaceToRef(convertedColor, exact = false) {\n if (exact) {\n convertedColor.r = colorChannelToGammaSpaceExact(this.r);\n convertedColor.g = colorChannelToGammaSpaceExact(this.g);\n convertedColor.b = colorChannelToGammaSpaceExact(this.b);\n }\n else {\n convertedColor.r = colorChannelToGammaSpace(this.r);\n convertedColor.g = colorChannelToGammaSpace(this.g);\n convertedColor.b = colorChannelToGammaSpace(this.b);\n }\n return this;\n }\n /**\n * Converts Hue, saturation and value to a Color3 (RGB)\n * @param hue defines the hue\n * @param saturation defines the saturation\n * @param value defines the value\n * @param result defines the Color3 where to store the RGB values\n */\n static HSVtoRGBToRef(hue, saturation, value, result) {\n const chroma = value * saturation;\n const h = hue / 60;\n const x = chroma * (1 - Math.abs((h % 2) - 1));\n let r = 0;\n let g = 0;\n let b = 0;\n if (h >= 0 && h <= 1) {\n r = chroma;\n g = x;\n }\n else if (h >= 1 && h <= 2) {\n r = x;\n g = chroma;\n }\n else if (h >= 2 && h <= 3) {\n g = chroma;\n b = x;\n }\n else if (h >= 3 && h <= 4) {\n g = x;\n b = chroma;\n }\n else if (h >= 4 && h <= 5) {\n r = x;\n b = chroma;\n }\n else if (h >= 5 && h <= 6) {\n r = chroma;\n b = x;\n }\n const m = value - chroma;\n result.set(r + m, g + m, b + m);\n }\n /**\n * Converts Hue, saturation and value to a new Color3 (RGB)\n * @param hue defines the hue (value between 0 and 360)\n * @param saturation defines the saturation (value between 0 and 1)\n * @param value defines the value (value between 0 and 1)\n * @returns a new Color3 object\n */\n static FromHSV(hue, saturation, value) {\n const result = new Color3(0, 0, 0);\n Color3.HSVtoRGBToRef(hue, saturation, value, result);\n return result;\n }\n /**\n * Creates a new Color3 from the string containing valid hexadecimal values\n * @param hex defines a string containing valid hexadecimal values\n * @returns a new Color3 object\n */\n static FromHexString(hex) {\n if (hex.substring(0, 1) !== \"#\" || hex.length !== 7) {\n return new Color3(0, 0, 0);\n }\n const r = parseInt(hex.substring(1, 3), 16);\n const g = parseInt(hex.substring(3, 5), 16);\n const b = parseInt(hex.substring(5, 7), 16);\n return Color3.FromInts(r, g, b);\n }\n /**\n * Creates a new Color3 from the starting index of the given array\n * @param array defines the source array\n * @param offset defines an offset in the source array\n * @returns a new Color3 object\n */\n static FromArray(array, offset = 0) {\n return new Color3(array[offset], array[offset + 1], array[offset + 2]);\n }\n /**\n * Creates a new Color3 from the starting index element of the given array\n * @param array defines the source array to read from\n * @param offset defines the offset in the source array\n * @param result defines the target Color3 object\n */\n static FromArrayToRef(array, offset = 0, result) {\n result.r = array[offset];\n result.g = array[offset + 1];\n result.b = array[offset + 2];\n }\n /**\n * Creates a new Color3 from integer values (< 256)\n * @param r defines the red component to read from (value between 0 and 255)\n * @param g defines the green component to read from (value between 0 and 255)\n * @param b defines the blue component to read from (value between 0 and 255)\n * @returns a new Color3 object\n */\n static FromInts(r, g, b) {\n return new Color3(r / 255.0, g / 255.0, b / 255.0);\n }\n /**\n * Creates a new Color3 with values linearly interpolated of \"amount\" between the start Color3 and the end Color3\n * @param start defines the start Color3 value\n * @param end defines the end Color3 value\n * @param amount defines the gradient value between start and end\n * @returns a new Color3 object\n */\n static Lerp(start, end, amount) {\n const result = new Color3(0.0, 0.0, 0.0);\n Color3.LerpToRef(start, end, amount, result);\n return result;\n }\n /**\n * Creates a new Color3 with values linearly interpolated of \"amount\" between the start Color3 and the end Color3\n * @param left defines the start value\n * @param right defines the end value\n * @param amount defines the gradient factor\n * @param result defines the Color3 object where to store the result\n */\n static LerpToRef(left, right, amount, result) {\n result.r = left.r + (right.r - left.r) * amount;\n result.g = left.g + (right.g - left.g) * amount;\n result.b = left.b + (right.b - left.b) * amount;\n }\n /**\n * Returns a new Color3 located for \"amount\" (float) on the Hermite interpolation spline defined by the vectors \"value1\", \"tangent1\", \"value2\", \"tangent2\"\n * @param value1 defines the first control point\n * @param tangent1 defines the first tangent Color3\n * @param value2 defines the second control point\n * @param tangent2 defines the second tangent Color3\n * @param amount defines the amount on the interpolation spline (between 0 and 1)\n * @returns the new Color3\n */\n static Hermite(value1, tangent1, value2, tangent2, amount) {\n const squared = amount * amount;\n const cubed = amount * squared;\n const part1 = 2.0 * cubed - 3.0 * squared + 1.0;\n const part2 = -2.0 * cubed + 3.0 * squared;\n const part3 = cubed - 2.0 * squared + amount;\n const part4 = cubed - squared;\n const r = value1.r * part1 + value2.r * part2 + tangent1.r * part3 + tangent2.r * part4;\n const g = value1.g * part1 + value2.g * part2 + tangent1.g * part3 + tangent2.g * part4;\n const b = value1.b * part1 + value2.b * part2 + tangent1.b * part3 + tangent2.b * part4;\n return new Color3(r, g, b);\n }\n /**\n * Returns a new Color3 which is the 1st derivative of the Hermite spline defined by the colors \"value1\", \"value2\", \"tangent1\", \"tangent2\".\n * @param value1 defines the first control point\n * @param tangent1 defines the first tangent\n * @param value2 defines the second control point\n * @param tangent2 defines the second tangent\n * @param time define where the derivative must be done\n * @returns 1st derivative\n */\n static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) {\n const result = Color3.Black();\n this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result);\n return result;\n }\n /**\n * Returns a new Color3 which is the 1st derivative of the Hermite spline defined by the colors \"value1\", \"value2\", \"tangent1\", \"tangent2\".\n * @param value1 defines the first control point\n * @param tangent1 defines the first tangent\n * @param value2 defines the second control point\n * @param tangent2 defines the second tangent\n * @param time define where the derivative must be done\n * @param result define where to store the derivative\n */\n static Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result) {\n const t2 = time * time;\n result.r = (t2 - time) * 6 * value1.r + (3 * t2 - 4 * time + 1) * tangent1.r + (-t2 + time) * 6 * value2.r + (3 * t2 - 2 * time) * tangent2.r;\n result.g = (t2 - time) * 6 * value1.g + (3 * t2 - 4 * time + 1) * tangent1.g + (-t2 + time) * 6 * value2.g + (3 * t2 - 2 * time) * tangent2.g;\n result.b = (t2 - time) * 6 * value1.b + (3 * t2 - 4 * time + 1) * tangent1.b + (-t2 + time) * 6 * value2.b + (3 * t2 - 2 * time) * tangent2.b;\n }\n /**\n * Returns a Color3 value containing a red color\n * @returns a new Color3 object\n */\n static Red() {\n return new Color3(1, 0, 0);\n }\n /**\n * Returns a Color3 value containing a green color\n * @returns a new Color3 object\n */\n static Green() {\n return new Color3(0, 1, 0);\n }\n /**\n * Returns a Color3 value containing a blue color\n * @returns a new Color3 object\n */\n static Blue() {\n return new Color3(0, 0, 1);\n }\n /**\n * Returns a Color3 value containing a black color\n * @returns a new Color3 object\n */\n static Black() {\n return new Color3(0, 0, 0);\n }\n /**\n * Gets a Color3 value containing a black color that must not be updated\n */\n static get BlackReadOnly() {\n return Color3._BlackReadOnly;\n }\n /**\n * Returns a Color3 value containing a white color\n * @returns a new Color3 object\n */\n static White() {\n return new Color3(1, 1, 1);\n }\n /**\n * Returns a Color3 value containing a purple color\n * @returns a new Color3 object\n */\n static Purple() {\n return new Color3(0.5, 0, 0.5);\n }\n /**\n * Returns a Color3 value containing a magenta color\n * @returns a new Color3 object\n */\n static Magenta() {\n return new Color3(1, 0, 1);\n }\n /**\n * Returns a Color3 value containing a yellow color\n * @returns a new Color3 object\n */\n static Yellow() {\n return new Color3(1, 1, 0);\n }\n /**\n * Returns a Color3 value containing a gray color\n * @returns a new Color3 object\n */\n static Gray() {\n return new Color3(0.5, 0.5, 0.5);\n }\n /**\n * Returns a Color3 value containing a teal color\n * @returns a new Color3 object\n */\n static Teal() {\n return new Color3(0, 1.0, 1.0);\n }\n /**\n * Returns a Color3 value containing a random color\n * @returns a new Color3 object\n */\n static Random() {\n return new Color3(Math.random(), Math.random(), Math.random());\n }\n}\n// Statics\nColor3._BlackReadOnly = Color3.Black();\n/**\n * Class used to hold a RBGA color\n */\nexport class Color4 {\n /**\n * Creates a new Color4 object from red, green, blue values, all between 0 and 1\n * @param r defines the red component (between 0 and 1, default is 0)\n * @param g defines the green component (between 0 and 1, default is 0)\n * @param b defines the blue component (between 0 and 1, default is 0)\n * @param a defines the alpha component (between 0 and 1, default is 1)\n */\n constructor(\n /**\n * Defines the red component (between 0 and 1, default is 0)\n */\n r = 0, \n /**\n * Defines the green component (between 0 and 1, default is 0)\n */\n g = 0, \n /**\n * Defines the blue component (between 0 and 1, default is 0)\n */\n b = 0, \n /**\n * Defines the alpha component (between 0 and 1, default is 1)\n */\n a = 1) {\n this.r = r;\n this.g = g;\n this.b = b;\n this.a = a;\n }\n // Operators\n /**\n * Adds in place the given Color4 values to the current Color4 object\n * @param right defines the second operand\n * @returns the current updated Color4 object\n */\n addInPlace(right) {\n this.r += right.r;\n this.g += right.g;\n this.b += right.b;\n this.a += right.a;\n return this;\n }\n /**\n * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values\n * @returns the new array\n */\n asArray() {\n return [this.r, this.g, this.b, this.a];\n }\n /**\n * Stores from the starting index in the given array the Color4 successive values\n * @param array defines the array where to store the r,g,b components\n * @param index defines an optional index in the target array to define where to start storing values\n * @returns the current Color4 object\n */\n toArray(array, index = 0) {\n array[index] = this.r;\n array[index + 1] = this.g;\n array[index + 2] = this.b;\n array[index + 3] = this.a;\n return this;\n }\n /**\n * Update the current color with values stored in an array from the starting index of the given array\n * @param array defines the source array\n * @param offset defines an offset in the source array\n * @returns the current Color4 object\n */\n fromArray(array, offset = 0) {\n Color4.FromArrayToRef(array, offset, this);\n return this;\n }\n /**\n * Determines equality between Color4 objects\n * @param otherColor defines the second operand\n * @returns true if the rgba values are equal to the given ones\n */\n equals(otherColor) {\n return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b && this.a === otherColor.a;\n }\n /**\n * Creates a new Color4 set with the added values of the current Color4 and of the given one\n * @param right defines the second operand\n * @returns a new Color4 object\n */\n add(right) {\n return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);\n }\n /**\n * Creates a new Color4 set with the subtracted values of the given one from the current Color4\n * @param right defines the second operand\n * @returns a new Color4 object\n */\n subtract(right) {\n return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);\n }\n /**\n * Subtracts the given ones from the current Color4 values and stores the results in \"result\"\n * @param right defines the second operand\n * @param result defines the Color4 object where to store the result\n * @returns the current Color4 object\n */\n subtractToRef(right, result) {\n result.r = this.r - right.r;\n result.g = this.g - right.g;\n result.b = this.b - right.b;\n result.a = this.a - right.a;\n return this;\n }\n /**\n * Creates a new Color4 with the current Color4 values multiplied by scale\n * @param scale defines the scaling factor to apply\n * @returns a new Color4 object\n */\n scale(scale) {\n return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);\n }\n /**\n * Multiplies the Color4 values by the float \"scale\"\n * @param scale defines the scaling factor to apply\n * @returns the current updated Color4\n */\n scaleInPlace(scale) {\n this.r *= scale;\n this.g *= scale;\n this.b *= scale;\n this.a *= scale;\n return this;\n }\n /**\n * Multiplies the current Color4 values by scale and stores the result in \"result\"\n * @param scale defines the scaling factor to apply\n * @param result defines the Color4 object where to store the result\n * @returns the current unmodified Color4\n */\n scaleToRef(scale, result) {\n result.r = this.r * scale;\n result.g = this.g * scale;\n result.b = this.b * scale;\n result.a = this.a * scale;\n return this;\n }\n /**\n * Scale the current Color4 values by a factor and add the result to a given Color4\n * @param scale defines the scale factor\n * @param result defines the Color4 object where to store the result\n * @returns the unmodified current Color4\n */\n scaleAndAddToRef(scale, result) {\n result.r += this.r * scale;\n result.g += this.g * scale;\n result.b += this.b * scale;\n result.a += this.a * scale;\n return this;\n }\n /**\n * Clamps the rgb values by the min and max values and stores the result into \"result\"\n * @param min defines minimum clamping value (default is 0)\n * @param max defines maximum clamping value (default is 1)\n * @param result defines color to store the result into.\n * @returns the current Color4\n */\n clampToRef(min = 0, max = 1, result) {\n result.r = Scalar.Clamp(this.r, min, max);\n result.g = Scalar.Clamp(this.g, min, max);\n result.b = Scalar.Clamp(this.b, min, max);\n result.a = Scalar.Clamp(this.a, min, max);\n return this;\n }\n /**\n * Multiply an Color4 value by another and return a new Color4 object\n * @param color defines the Color4 value to multiply by\n * @returns a new Color4 object\n */\n multiply(color) {\n return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);\n }\n /**\n * Multiply a Color4 value by another and push the result in a reference value\n * @param color defines the Color4 value to multiply by\n * @param result defines the Color4 to fill the result in\n * @returns the result Color4\n */\n multiplyToRef(color, result) {\n result.r = this.r * color.r;\n result.g = this.g * color.g;\n result.b = this.b * color.b;\n result.a = this.a * color.a;\n return result;\n }\n /**\n * Creates a string with the Color4 current values\n * @returns the string representation of the Color4 object\n */\n toString() {\n return \"{R: \" + this.r + \" G:\" + this.g + \" B:\" + this.b + \" A:\" + this.a + \"}\";\n }\n /**\n * Returns the string \"Color4\"\n * @returns \"Color4\"\n */\n getClassName() {\n return \"Color4\";\n }\n /**\n * Compute the Color4 hash code\n * @returns an unique number that can be used to hash Color4 objects\n */\n getHashCode() {\n let hash = (this.r * 255) | 0;\n hash = (hash * 397) ^ ((this.g * 255) | 0);\n hash = (hash * 397) ^ ((this.b * 255) | 0);\n hash = (hash * 397) ^ ((this.a * 255) | 0);\n return hash;\n }\n /**\n * Creates a new Color4 copied from the current one\n * @returns a new Color4 object\n */\n clone() {\n return new Color4(this.r, this.g, this.b, this.a);\n }\n /**\n * Copies the given Color4 values into the current one\n * @param source defines the source Color4 object\n * @returns the current updated Color4 object\n */\n copyFrom(source) {\n this.r = source.r;\n this.g = source.g;\n this.b = source.b;\n this.a = source.a;\n return this;\n }\n /**\n * Copies the given float values into the current one\n * @param r defines the red component to read from\n * @param g defines the green component to read from\n * @param b defines the blue component to read from\n * @param a defines the alpha component to read from\n * @returns the current updated Color4 object\n */\n copyFromFloats(r, g, b, a) {\n this.r = r;\n this.g = g;\n this.b = b;\n this.a = a;\n return this;\n }\n /**\n * Copies the given float values into the current one\n * @param r defines the red component to read from\n * @param g defines the green component to read from\n * @param b defines the blue component to read from\n * @param a defines the alpha component to read from\n * @returns the current updated Color4 object\n */\n set(r, g, b, a) {\n return this.copyFromFloats(r, g, b, a);\n }\n /**\n * Compute the Color4 hexadecimal code as a string\n * @param returnAsColor3 defines if the string should only contains RGB values (off by default)\n * @returns a string containing the hexadecimal representation of the Color4 object\n */\n toHexString(returnAsColor3 = false) {\n const intR = Math.round(this.r * 255);\n const intG = Math.round(this.g * 255);\n const intB = Math.round(this.b * 255);\n if (returnAsColor3) {\n return \"#\" + Scalar.ToHex(intR) + Scalar.ToHex(intG) + Scalar.ToHex(intB);\n }\n const intA = Math.round(this.a * 255);\n return \"#\" + Scalar.ToHex(intR) + Scalar.ToHex(intG) + Scalar.ToHex(intB) + Scalar.ToHex(intA);\n }\n /**\n * Computes a new Color4 converted from the current one to linear space\n * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false)\n * @returns a new Color4 object\n */\n toLinearSpace(exact = false) {\n const convertedColor = new Color4();\n this.toLinearSpaceToRef(convertedColor, exact);\n return convertedColor;\n }\n /**\n * Converts the Color4 values to linear space and stores the result in \"convertedColor\"\n * @param convertedColor defines the Color4 object where to store the linear space version\n * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false)\n * @returns the unmodified Color4\n */\n toLinearSpaceToRef(convertedColor, exact = false) {\n if (exact) {\n convertedColor.r = colorChannelToLinearSpaceExact(this.r);\n convertedColor.g = colorChannelToLinearSpaceExact(this.g);\n convertedColor.b = colorChannelToLinearSpaceExact(this.b);\n }\n else {\n convertedColor.r = colorChannelToLinearSpace(this.r);\n convertedColor.g = colorChannelToLinearSpace(this.g);\n convertedColor.b = colorChannelToLinearSpace(this.b);\n }\n convertedColor.a = this.a;\n return this;\n }\n /**\n * Computes a new Color4 converted from the current one to gamma space\n * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false)\n * @returns a new Color4 object\n */\n toGammaSpace(exact = false) {\n const convertedColor = new Color4();\n this.toGammaSpaceToRef(convertedColor, exact);\n return convertedColor;\n }\n /**\n * Converts the Color4 values to gamma space and stores the result in \"convertedColor\"\n * @param convertedColor defines the Color4 object where to store the gamma space version\n * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false)\n * @returns the unmodified Color4\n */\n toGammaSpaceToRef(convertedColor, exact = false) {\n if (exact) {\n convertedColor.r = colorChannelToGammaSpaceExact(this.r);\n convertedColor.g = colorChannelToGammaSpaceExact(this.g);\n convertedColor.b = colorChannelToGammaSpaceExact(this.b);\n }\n else {\n convertedColor.r = colorChannelToGammaSpace(this.r);\n convertedColor.g = colorChannelToGammaSpace(this.g);\n convertedColor.b = colorChannelToGammaSpace(this.b);\n }\n convertedColor.a = this.a;\n return this;\n }\n // Statics\n /**\n * Creates a new Color4 from the string containing valid hexadecimal values.\n *\n * A valid hex string is either in the format #RRGGBB or #RRGGBBAA.\n *\n * When a hex string without alpha is passed, the resulting Color4 has\n * its alpha value set to 1.0.\n *\n * An invalid string results in a Color with all its channels set to 0.0,\n * i.e. \"transparent black\".\n *\n * @param hex defines a string containing valid hexadecimal values\n * @returns a new Color4 object\n */\n static FromHexString(hex) {\n if (hex.substring(0, 1) !== \"#\" || (hex.length !== 9 && hex.length !== 7)) {\n return new Color4(0.0, 0.0, 0.0, 0.0);\n }\n const r = parseInt(hex.substring(1, 3), 16);\n const g = parseInt(hex.substring(3, 5), 16);\n const b = parseInt(hex.substring(5, 7), 16);\n const a = hex.length === 9 ? parseInt(hex.substring(7, 9), 16) : 255;\n return Color4.FromInts(r, g, b, a);\n }\n /**\n * Creates a new Color4 object set with the linearly interpolated values of \"amount\" between the left Color4 object and the right Color4 object\n * @param left defines the start value\n * @param right defines the end value\n * @param amount defines the gradient factor\n * @returns a new Color4 object\n */\n static Lerp(left, right, amount) {\n const result = new Color4(0.0, 0.0, 0.0, 0.0);\n Color4.LerpToRef(left, right, amount, result);\n return result;\n }\n /**\n * Set the given \"result\" with the linearly interpolated values of \"amount\" between the left Color4 object and the right Color4 object\n * @param left defines the start value\n * @param right defines the end value\n * @param amount defines the gradient factor\n * @param result defines the Color4 object where to store data\n */\n static LerpToRef(left, right, amount, result) {\n result.r = left.r + (right.r - left.r) * amount;\n result.g = left.g + (right.g - left.g) * amount;\n result.b = left.b + (right.b - left.b) * amount;\n result.a = left.a + (right.a - left.a) * amount;\n }\n /**\n * Interpolate between two Color4 using Hermite interpolation\n * @param value1 defines first Color4\n * @param tangent1 defines the incoming tangent\n * @param value2 defines second Color4\n * @param tangent2 defines the outgoing tangent\n * @param amount defines the target Color4\n * @returns the new interpolated Color4\n */\n static Hermite(value1, tangent1, value2, tangent2, amount) {\n const squared = amount * amount;\n const cubed = amount * squared;\n const part1 = 2.0 * cubed - 3.0 * squared + 1.0;\n const part2 = -2.0 * cubed + 3.0 * squared;\n const part3 = cubed - 2.0 * squared + amount;\n const part4 = cubed - squared;\n const r = value1.r * part1 + value2.r * part2 + tangent1.r * part3 + tangent2.r * part4;\n const g = value1.g * part1 + value2.g * part2 + tangent1.g * part3 + tangent2.g * part4;\n const b = value1.b * part1 + value2.b * part2 + tangent1.b * part3 + tangent2.b * part4;\n const a = value1.a * part1 + value2.a * part2 + tangent1.a * part3 + tangent2.a * part4;\n return new Color4(r, g, b, a);\n }\n /**\n * Returns a new Color4 which is the 1st derivative of the Hermite spline defined by the colors \"value1\", \"value2\", \"tangent1\", \"tangent2\".\n * @param value1 defines the first control point\n * @param tangent1 defines the first tangent\n * @param value2 defines the second control point\n * @param tangent2 defines the second tangent\n * @param time define where the derivative must be done\n * @returns 1st derivative\n */\n static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) {\n const result = new Color4();\n this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result);\n return result;\n }\n /**\n * Update a Color4 with the 1st derivative of the Hermite spline defined by the colors \"value1\", \"value2\", \"tangent1\", \"tangent2\".\n * @param value1 defines the first control point\n * @param tangent1 defines the first tangent\n * @param value2 defines the second control point\n * @param tangent2 defines the second tangent\n * @param time define where the derivative must be done\n * @param result define where to store the derivative\n */\n static Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result) {\n const t2 = time * time;\n result.r = (t2 - time) * 6 * value1.r + (3 * t2 - 4 * time + 1) * tangent1.r + (-t2 + time) * 6 * value2.r + (3 * t2 - 2 * time) * tangent2.r;\n result.g = (t2 - time) * 6 * value1.g + (3 * t2 - 4 * time + 1) * tangent1.g + (-t2 + time) * 6 * value2.g + (3 * t2 - 2 * time) * tangent2.g;\n result.b = (t2 - time) * 6 * value1.b + (3 * t2 - 4 * time + 1) * tangent1.b + (-t2 + time) * 6 * value2.b + (3 * t2 - 2 * time) * tangent2.b;\n result.a = (t2 - time) * 6 * value1.a + (3 * t2 - 4 * time + 1) * tangent1.a + (-t2 + time) * 6 * value2.a + (3 * t2 - 2 * time) * tangent2.a;\n }\n /**\n * Creates a new Color4 from a Color3 and an alpha value\n * @param color3 defines the source Color3 to read from\n * @param alpha defines the alpha component (1.0 by default)\n * @returns a new Color4 object\n */\n static FromColor3(color3, alpha = 1.0) {\n return new Color4(color3.r, color3.g, color3.b, alpha);\n }\n /**\n * Creates a new Color4 from the starting index element of the given array\n * @param array defines the source array to read from\n * @param offset defines the offset in the source array\n * @returns a new Color4 object\n */\n static FromArray(array, offset = 0) {\n return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);\n }\n /**\n * Creates a new Color4 from the starting index element of the given array\n * @param array defines the source array to read from\n * @param offset defines the offset in the source array\n * @param result defines the target Color4 object\n */\n static FromArrayToRef(array, offset = 0, result) {\n result.r = array[offset];\n result.g = array[offset + 1];\n result.b = array[offset + 2];\n result.a = array[offset + 3];\n }\n /**\n * Creates a new Color3 from integer values (< 256)\n * @param r defines the red component to read from (value between 0 and 255)\n * @param g defines the green component to read from (value between 0 and 255)\n * @param b defines the blue component to read from (value between 0 and 255)\n * @param a defines the alpha component to read from (value between 0 and 255)\n * @returns a new Color3 object\n */\n static FromInts(r, g, b, a) {\n return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);\n }\n /**\n * Check the content of a given array and convert it to an array containing RGBA data\n * If the original array was already containing count * 4 values then it is returned directly\n * @param colors defines the array to check\n * @param count defines the number of RGBA data to expect\n * @returns an array containing count * 4 values (RGBA)\n */\n static CheckColors4(colors, count) {\n // Check if color3 was used\n if (colors.length === count * 3) {\n const colors4 = [];\n for (let index = 0; index < colors.length; index += 3) {\n const newIndex = (index / 3) * 4;\n colors4[newIndex] = colors[index];\n colors4[newIndex + 1] = colors[index + 1];\n colors4[newIndex + 2] = colors[index + 2];\n colors4[newIndex + 3] = 1.0;\n }\n return colors4;\n }\n return colors;\n }\n}\n/**\n * @internal\n */\nexport class TmpColors {\n}\nTmpColors.Color3 = ArrayTools.BuildArray(3, Color3.Black);\nTmpColors.Color4 = ArrayTools.BuildArray(3, () => new Color4(0, 0, 0, 0));\nRegisterClass(\"BABYLON.Color3\", Color3);\nRegisterClass(\"BABYLON.Color4\", Color4);\n//# sourceMappingURL=math.color.js.map","/**\n * Constant used to convert a value to gamma space\n * @ignorenaming\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const ToGammaSpace = 1 / 2.2;\n/**\n * Constant used to convert a value to linear space\n * @ignorenaming\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const ToLinearSpace = 2.2;\n/**\n * Constant Golden Ratio value in Babylon.js\n * @ignorenaming\n */\nexport const PHI = (1 + Math.sqrt(5)) / 2;\n/**\n * Constant used to define the minimal number value in Babylon.js\n * @ignorenaming\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst Epsilon = 0.001;\nexport { Epsilon };\n//# sourceMappingURL=math.constants.js.map","import { Plane } from \"./math.plane.js\";\n/**\n * Represents a camera frustum\n */\nexport class Frustum {\n /**\n * Gets the planes representing the frustum\n * @param transform matrix to be applied to the returned planes\n * @returns a new array of 6 Frustum planes computed by the given transformation matrix.\n */\n static GetPlanes(transform) {\n const frustumPlanes = [];\n for (let index = 0; index < 6; index++) {\n frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));\n }\n Frustum.GetPlanesToRef(transform, frustumPlanes);\n return frustumPlanes;\n }\n /**\n * Gets the near frustum plane transformed by the transform matrix\n * @param transform transformation matrix to be applied to the resulting frustum plane\n * @param frustumPlane the resulting frustum plane\n */\n static GetNearPlaneToRef(transform, frustumPlane) {\n const m = transform.m;\n frustumPlane.normal.x = m[3] + m[2];\n frustumPlane.normal.y = m[7] + m[6];\n frustumPlane.normal.z = m[11] + m[10];\n frustumPlane.d = m[15] + m[14];\n frustumPlane.normalize();\n }\n /**\n * Gets the far frustum plane transformed by the transform matrix\n * @param transform transformation matrix to be applied to the resulting frustum plane\n * @param frustumPlane the resulting frustum plane\n */\n static GetFarPlaneToRef(transform, frustumPlane) {\n const m = transform.m;\n frustumPlane.normal.x = m[3] - m[2];\n frustumPlane.normal.y = m[7] - m[6];\n frustumPlane.normal.z = m[11] - m[10];\n frustumPlane.d = m[15] - m[14];\n frustumPlane.normalize();\n }\n /**\n * Gets the left frustum plane transformed by the transform matrix\n * @param transform transformation matrix to be applied to the resulting frustum plane\n * @param frustumPlane the resulting frustum plane\n */\n static GetLeftPlaneToRef(transform, frustumPlane) {\n const m = transform.m;\n frustumPlane.normal.x = m[3] + m[0];\n frustumPlane.normal.y = m[7] + m[4];\n frustumPlane.normal.z = m[11] + m[8];\n frustumPlane.d = m[15] + m[12];\n frustumPlane.normalize();\n }\n /**\n * Gets the right frustum plane transformed by the transform matrix\n * @param transform transformation matrix to be applied to the resulting frustum plane\n * @param frustumPlane the resulting frustum plane\n */\n static GetRightPlaneToRef(transform, frustumPlane) {\n const m = transform.m;\n frustumPlane.normal.x = m[3] - m[0];\n frustumPlane.normal.y = m[7] - m[4];\n frustumPlane.normal.z = m[11] - m[8];\n frustumPlane.d = m[15] - m[12];\n frustumPlane.normalize();\n }\n /**\n * Gets the top frustum plane transformed by the transform matrix\n * @param transform transformation matrix to be applied to the resulting frustum plane\n * @param frustumPlane the resulting frustum plane\n */\n static GetTopPlaneToRef(transform, frustumPlane) {\n const m = transform.m;\n frustumPlane.normal.x = m[3] - m[1];\n frustumPlane.normal.y = m[7] - m[5];\n frustumPlane.normal.z = m[11] - m[9];\n frustumPlane.d = m[15] - m[13];\n frustumPlane.normalize();\n }\n /**\n * Gets the bottom frustum plane transformed by the transform matrix\n * @param transform transformation matrix to be applied to the resulting frustum plane\n * @param frustumPlane the resulting frustum plane\n */\n static GetBottomPlaneToRef(transform, frustumPlane) {\n const m = transform.m;\n frustumPlane.normal.x = m[3] + m[1];\n frustumPlane.normal.y = m[7] + m[5];\n frustumPlane.normal.z = m[11] + m[9];\n frustumPlane.d = m[15] + m[13];\n frustumPlane.normalize();\n }\n /**\n * Sets the given array \"frustumPlanes\" with the 6 Frustum planes computed by the given transformation matrix.\n * @param transform transformation matrix to be applied to the resulting frustum planes\n * @param frustumPlanes the resulting frustum planes\n */\n static GetPlanesToRef(transform, frustumPlanes) {\n // Near\n Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);\n // Far\n Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);\n // Left\n Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);\n // Right\n Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);\n // Top\n Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);\n // Bottom\n Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);\n }\n /**\n * Tests if a point is located between the frustum planes.\n * @param point defines the point to test\n * @param frustumPlanes defines the frustum planes to test\n * @returns true if the point is located between the frustum planes\n */\n static IsPointInFrustum(point, frustumPlanes) {\n for (let i = 0; i < 6; i++) {\n if (frustumPlanes[i].dotCoordinate(point) < 0) {\n return false;\n }\n }\n return true;\n }\n}\n//# sourceMappingURL=math.frustum.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { Vector3 } from \"./math.vector.js\";\nimport { nativeOverride } from \"../Misc/decorators.js\";\n// This helper class is only here so we can apply the nativeOverride decorator to functions.\nclass MathHelpers {\n static extractMinAndMaxIndexed(positions, indices, indexStart, indexCount, minimum, maximum) {\n for (let index = indexStart; index < indexStart + indexCount; index++) {\n const offset = indices[index] * 3;\n const x = positions[offset];\n const y = positions[offset + 1];\n const z = positions[offset + 2];\n minimum.minimizeInPlaceFromFloats(x, y, z);\n maximum.maximizeInPlaceFromFloats(x, y, z);\n }\n }\n static extractMinAndMax(positions, start, count, stride, minimum, maximum) {\n for (let index = start, offset = start * stride; index < start + count; index++, offset += stride) {\n const x = positions[offset];\n const y = positions[offset + 1];\n const z = positions[offset + 2];\n minimum.minimizeInPlaceFromFloats(x, y, z);\n maximum.maximizeInPlaceFromFloats(x, y, z);\n }\n }\n}\n__decorate([\n nativeOverride.filter((...[positions, indices]) => !Array.isArray(positions) && !Array.isArray(indices))\n // eslint-disable-next-line @typescript-eslint/naming-convention\n], MathHelpers, \"extractMinAndMaxIndexed\", null);\n__decorate([\n nativeOverride.filter((...[positions]) => !Array.isArray(positions))\n // eslint-disable-next-line @typescript-eslint/naming-convention\n], MathHelpers, \"extractMinAndMax\", null);\n/**\n * Extracts minimum and maximum values from a list of indexed positions\n * @param positions defines the positions to use\n * @param indices defines the indices to the positions\n * @param indexStart defines the start index\n * @param indexCount defines the end index\n * @param bias defines bias value to add to the result\n * @returns minimum and maximum values\n */\nexport function extractMinAndMaxIndexed(positions, indices, indexStart, indexCount, bias = null) {\n const minimum = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n const maximum = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);\n MathHelpers.extractMinAndMaxIndexed(positions, indices, indexStart, indexCount, minimum, maximum);\n if (bias) {\n minimum.x -= minimum.x * bias.x + bias.y;\n minimum.y -= minimum.y * bias.x + bias.y;\n minimum.z -= minimum.z * bias.x + bias.y;\n maximum.x += maximum.x * bias.x + bias.y;\n maximum.y += maximum.y * bias.x + bias.y;\n maximum.z += maximum.z * bias.x + bias.y;\n }\n return {\n minimum: minimum,\n maximum: maximum,\n };\n}\n/**\n * Extracts minimum and maximum values from a list of positions\n * @param positions defines the positions to use\n * @param start defines the start index in the positions array\n * @param count defines the number of positions to handle\n * @param bias defines bias value to add to the result\n * @param stride defines the stride size to use (distance between two positions in the positions array)\n * @returns minimum and maximum values\n */\nexport function extractMinAndMax(positions, start, count, bias = null, stride) {\n const minimum = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n const maximum = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);\n if (!stride) {\n stride = 3;\n }\n MathHelpers.extractMinAndMax(positions, start, count, stride, minimum, maximum);\n if (bias) {\n minimum.x -= minimum.x * bias.x + bias.y;\n minimum.y -= minimum.y * bias.x + bias.y;\n minimum.z -= minimum.z * bias.x + bias.y;\n maximum.x += maximum.x * bias.x + bias.y;\n maximum.y += maximum.y * bias.x + bias.y;\n maximum.z += maximum.z * bias.x + bias.y;\n }\n return {\n minimum: minimum,\n maximum: maximum,\n };\n}\n//# sourceMappingURL=math.functions.js.map","import { Vector3, Matrix } from \"./math.vector.js\";\n/**\n * Represents a plane by the equation ax + by + cz + d = 0\n */\nexport class Plane {\n /**\n * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0\n * @param a a component of the plane\n * @param b b component of the plane\n * @param c c component of the plane\n * @param d d component of the plane\n */\n constructor(a, b, c, d) {\n this.normal = new Vector3(a, b, c);\n this.d = d;\n }\n /**\n * @returns the plane coordinates as a new array of 4 elements [a, b, c, d].\n */\n asArray() {\n return [this.normal.x, this.normal.y, this.normal.z, this.d];\n }\n // Methods\n /**\n * @returns a new plane copied from the current Plane.\n */\n clone() {\n return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);\n }\n /**\n * @returns the string \"Plane\".\n */\n getClassName() {\n return \"Plane\";\n }\n /**\n * @returns the Plane hash code.\n */\n getHashCode() {\n let hash = this.normal.getHashCode();\n hash = (hash * 397) ^ (this.d | 0);\n return hash;\n }\n /**\n * Normalize the current Plane in place.\n * @returns the updated Plane.\n */\n normalize() {\n const norm = Math.sqrt(this.normal.x * this.normal.x + this.normal.y * this.normal.y + this.normal.z * this.normal.z);\n let magnitude = 0.0;\n if (norm !== 0) {\n magnitude = 1.0 / norm;\n }\n this.normal.x *= magnitude;\n this.normal.y *= magnitude;\n this.normal.z *= magnitude;\n this.d *= magnitude;\n return this;\n }\n /**\n * Applies a transformation the plane and returns the result\n * @param transformation the transformation matrix to be applied to the plane\n * @returns a new Plane as the result of the transformation of the current Plane by the given matrix.\n */\n transform(transformation) {\n const invertedMatrix = Plane._TmpMatrix;\n transformation.invertToRef(invertedMatrix);\n const m = invertedMatrix.m;\n const x = this.normal.x;\n const y = this.normal.y;\n const z = this.normal.z;\n const d = this.d;\n const normalX = x * m[0] + y * m[1] + z * m[2] + d * m[3];\n const normalY = x * m[4] + y * m[5] + z * m[6] + d * m[7];\n const normalZ = x * m[8] + y * m[9] + z * m[10] + d * m[11];\n const finalD = x * m[12] + y * m[13] + z * m[14] + d * m[15];\n return new Plane(normalX, normalY, normalZ, finalD);\n }\n /**\n * Compute the dot product between the point and the plane normal\n * @param point point to calculate the dot product with\n * @returns the dot product (float) of the point coordinates and the plane normal.\n */\n dotCoordinate(point) {\n return this.normal.x * point.x + this.normal.y * point.y + this.normal.z * point.z + this.d;\n }\n /**\n * Updates the current Plane from the plane defined by the three given points.\n * @param point1 one of the points used to construct the plane\n * @param point2 one of the points used to construct the plane\n * @param point3 one of the points used to construct the plane\n * @returns the updated Plane.\n */\n copyFromPoints(point1, point2, point3) {\n const x1 = point2.x - point1.x;\n const y1 = point2.y - point1.y;\n const z1 = point2.z - point1.z;\n const x2 = point3.x - point1.x;\n const y2 = point3.y - point1.y;\n const z2 = point3.z - point1.z;\n const yz = y1 * z2 - z1 * y2;\n const xz = z1 * x2 - x1 * z2;\n const xy = x1 * y2 - y1 * x2;\n const pyth = Math.sqrt(yz * yz + xz * xz + xy * xy);\n let invPyth;\n if (pyth !== 0) {\n invPyth = 1.0 / pyth;\n }\n else {\n invPyth = 0.0;\n }\n this.normal.x = yz * invPyth;\n this.normal.y = xz * invPyth;\n this.normal.z = xy * invPyth;\n this.d = -(this.normal.x * point1.x + this.normal.y * point1.y + this.normal.z * point1.z);\n return this;\n }\n /**\n * Checks if the plane is facing a given direction (meaning if the plane's normal is pointing in the opposite direction of the given vector).\n * Note that for this function to work as expected you should make sure that:\n * - direction and the plane normal are normalized\n * - epsilon is a number just bigger than -1, something like -0.99 for eg\n * @param direction the direction to check if the plane is facing\n * @param epsilon value the dot product is compared against (returns true if dot <= epsilon)\n * @returns True if the plane is facing the given direction\n */\n isFrontFacingTo(direction, epsilon) {\n const dot = Vector3.Dot(this.normal, direction);\n return dot <= epsilon;\n }\n /**\n * Calculates the distance to a point\n * @param point point to calculate distance to\n * @returns the signed distance (float) from the given point to the Plane.\n */\n signedDistanceTo(point) {\n return Vector3.Dot(point, this.normal) + this.d;\n }\n // Statics\n /**\n * Creates a plane from an array\n * @param array the array to create a plane from\n * @returns a new Plane from the given array.\n */\n static FromArray(array) {\n return new Plane(array[0], array[1], array[2], array[3]);\n }\n /**\n * Creates a plane from three points\n * @param point1 point used to create the plane\n * @param point2 point used to create the plane\n * @param point3 point used to create the plane\n * @returns a new Plane defined by the three given points.\n */\n static FromPoints(point1, point2, point3) {\n const result = new Plane(0.0, 0.0, 0.0, 0.0);\n result.copyFromPoints(point1, point2, point3);\n return result;\n }\n /**\n * Creates a plane from an origin point and a normal\n * @param origin origin of the plane to be constructed\n * @param normal normal of the plane to be constructed\n * @returns a new Plane the normal vector to this plane at the given origin point.\n * Note : the vector \"normal\" is updated because normalized.\n */\n static FromPositionAndNormal(origin, normal) {\n const result = new Plane(0.0, 0.0, 0.0, 0.0);\n normal.normalize();\n result.normal = normal;\n result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);\n return result;\n }\n /**\n * Calculates the distance from a plane and a point\n * @param origin origin of the plane to be constructed\n * @param normal normal of the plane to be constructed\n * @param point point to calculate distance to\n * @returns the signed distance between the plane defined by the normal vector at the \"origin\"\" point and the given other point.\n */\n static SignedDistanceToPlaneFromPositionAndNormal(origin, normal, point) {\n const d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);\n return Vector3.Dot(point, normal) + d;\n }\n}\nPlane._TmpMatrix = Matrix.Identity();\n//# sourceMappingURL=math.plane.js.map","/**\n * Scalar computation library\n */\nexport class Scalar {\n /**\n * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)\n * @param a number\n * @param b number\n * @param epsilon (default = 1.401298E-45)\n * @returns true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)\n */\n static WithinEpsilon(a, b, epsilon = 1.401298e-45) {\n return Math.abs(a - b) <= epsilon;\n }\n /**\n * Returns a string : the upper case translation of the number i to hexadecimal.\n * @param i number\n * @returns the upper case translation of the number i to hexadecimal.\n */\n static ToHex(i) {\n const str = i.toString(16);\n if (i <= 15) {\n return (\"0\" + str).toUpperCase();\n }\n return str.toUpperCase();\n }\n /**\n * Returns -1 if value is negative and +1 is value is positive.\n * @param value the value\n * @returns the value itself if it's equal to zero.\n */\n static Sign(value) {\n value = +value; // convert to a number\n if (value === 0 || isNaN(value)) {\n return value;\n }\n return value > 0 ? 1 : -1;\n }\n /**\n * Returns the value itself if it's between min and max.\n * Returns min if the value is lower than min.\n * Returns max if the value is greater than max.\n * @param value the value to clmap\n * @param min the min value to clamp to (default: 0)\n * @param max the max value to clamp to (default: 1)\n * @returns the clamped value\n */\n static Clamp(value, min = 0, max = 1) {\n return Math.min(max, Math.max(min, value));\n }\n /**\n * the log2 of value.\n * @param value the value to compute log2 of\n * @returns the log2 of value.\n */\n static Log2(value) {\n return Math.log(value) * Math.LOG2E;\n }\n /**\n * the floor part of a log2 value.\n * @param value the value to compute log2 of\n * @returns the log2 of value.\n */\n static ILog2(value) {\n if (Math.log2) {\n return Math.floor(Math.log2(value));\n }\n if (value < 0) {\n return NaN;\n }\n else if (value === 0) {\n return -Infinity;\n }\n let n = 0;\n if (value < 1) {\n while (value < 1) {\n n++;\n value = value * 2;\n }\n n = -n;\n }\n else if (value > 1) {\n while (value > 1) {\n n++;\n value = Math.floor(value / 2);\n }\n }\n return n;\n }\n /**\n * Loops the value, so that it is never larger than length and never smaller than 0.\n *\n * This is similar to the modulo operator but it works with floating point numbers.\n * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.\n * With t = 5 and length = 2.5, the result would be 0.0.\n * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator\n * @param value the value\n * @param length the length\n * @returns the looped value\n */\n static Repeat(value, length) {\n return value - Math.floor(value / length) * length;\n }\n /**\n * Normalize the value between 0.0 and 1.0 using min and max values\n * @param value value to normalize\n * @param min max to normalize between\n * @param max min to normalize between\n * @returns the normalized value\n */\n static Normalize(value, min, max) {\n return (value - min) / (max - min);\n }\n /**\n * Denormalize the value from 0.0 and 1.0 using min and max values\n * @param normalized value to denormalize\n * @param min max to denormalize between\n * @param max min to denormalize between\n * @returns the denormalized value\n */\n static Denormalize(normalized, min, max) {\n return normalized * (max - min) + min;\n }\n /**\n * Calculates the shortest difference between two given angles given in degrees.\n * @param current current angle in degrees\n * @param target target angle in degrees\n * @returns the delta\n */\n static DeltaAngle(current, target) {\n let num = Scalar.Repeat(target - current, 360.0);\n if (num > 180.0) {\n num -= 360.0;\n }\n return num;\n }\n /**\n * PingPongs the value t, so that it is never larger than length and never smaller than 0.\n * @param tx value\n * @param length length\n * @returns The returned value will move back and forth between 0 and length\n */\n static PingPong(tx, length) {\n const t = Scalar.Repeat(tx, length * 2.0);\n return length - Math.abs(t - length);\n }\n /**\n * Interpolates between min and max with smoothing at the limits.\n *\n * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up\n * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.\n * @param from from\n * @param to to\n * @param tx value\n * @returns the smooth stepped value\n */\n static SmoothStep(from, to, tx) {\n let t = Scalar.Clamp(tx);\n t = -2.0 * t * t * t + 3.0 * t * t;\n return to * t + from * (1.0 - t);\n }\n /**\n * Moves a value current towards target.\n *\n * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.\n * Negative values of maxDelta pushes the value away from target.\n * @param current current value\n * @param target target value\n * @param maxDelta max distance to move\n * @returns resulting value\n */\n static MoveTowards(current, target, maxDelta) {\n let result = 0;\n if (Math.abs(target - current) <= maxDelta) {\n result = target;\n }\n else {\n result = current + Scalar.Sign(target - current) * maxDelta;\n }\n return result;\n }\n /**\n * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.\n *\n * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta\n * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.\n * @param current current value\n * @param target target value\n * @param maxDelta max distance to move\n * @returns resulting angle\n */\n static MoveTowardsAngle(current, target, maxDelta) {\n const num = Scalar.DeltaAngle(current, target);\n let result = 0;\n if (-maxDelta < num && num < maxDelta) {\n result = target;\n }\n else {\n target = current + num;\n result = Scalar.MoveTowards(current, target, maxDelta);\n }\n return result;\n }\n /**\n * Creates a new scalar with values linearly interpolated of \"amount\" between the start scalar and the end scalar.\n * @param start start value\n * @param end target value\n * @param amount amount to lerp between\n * @returns the lerped value\n */\n static Lerp(start, end, amount) {\n return start + (end - start) * amount;\n }\n /**\n * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.\n * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.\n * @param start start value\n * @param end target value\n * @param amount amount to lerp between\n * @returns the lerped value\n */\n static LerpAngle(start, end, amount) {\n let num = Scalar.Repeat(end - start, 360.0);\n if (num > 180.0) {\n num -= 360.0;\n }\n return start + num * Scalar.Clamp(amount);\n }\n /**\n * Calculates the linear parameter t that produces the interpolant value within the range [a, b].\n * @param a start value\n * @param b target value\n * @param value value between a and b\n * @returns the inverseLerp value\n */\n static InverseLerp(a, b, value) {\n let result = 0;\n if (a != b) {\n result = Scalar.Clamp((value - a) / (b - a));\n }\n else {\n result = 0.0;\n }\n return result;\n }\n /**\n * Returns a new scalar located for \"amount\" (float) on the Hermite spline defined by the scalars \"value1\", \"value3\", \"tangent1\", \"tangent2\".\n * @see http://mathworld.wolfram.com/HermitePolynomial.html\n * @param value1 defines the first control point\n * @param tangent1 defines the first tangent\n * @param value2 defines the second control point\n * @param tangent2 defines the second tangent\n * @param amount defines the amount on the interpolation spline (between 0 and 1)\n * @returns hermite result\n */\n static Hermite(value1, tangent1, value2, tangent2, amount) {\n const squared = amount * amount;\n const cubed = amount * squared;\n const part1 = 2.0 * cubed - 3.0 * squared + 1.0;\n const part2 = -2.0 * cubed + 3.0 * squared;\n const part3 = cubed - 2.0 * squared + amount;\n const part4 = cubed - squared;\n return value1 * part1 + value2 * part2 + tangent1 * part3 + tangent2 * part4;\n }\n /**\n * Returns a new scalar which is the 1st derivative of the Hermite spline defined by the scalars \"value1\", \"value2\", \"tangent1\", \"tangent2\".\n * @param value1 defines the first control point\n * @param tangent1 defines the first tangent\n * @param value2 defines the second control point\n * @param tangent2 defines the second tangent\n * @param time define where the derivative must be done\n * @returns 1st derivative\n */\n static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) {\n const t2 = time * time;\n return (t2 - time) * 6 * value1 + (3 * t2 - 4 * time + 1) * tangent1 + (-t2 + time) * 6 * value2 + (3 * t2 - 2 * time) * tangent2;\n }\n /**\n * Returns a random float number between and min and max values\n * @param min min value of random\n * @param max max value of random\n * @returns random value\n */\n static RandomRange(min, max) {\n if (min === max) {\n return min;\n }\n return Math.random() * (max - min) + min;\n }\n /**\n * This function returns percentage of a number in a given range.\n *\n * RangeToPercent(40,20,60) will return 0.5 (50%)\n * RangeToPercent(34,0,100) will return 0.34 (34%)\n * @param number to convert to percentage\n * @param min min range\n * @param max max range\n * @returns the percentage\n */\n static RangeToPercent(number, min, max) {\n return (number - min) / (max - min);\n }\n /**\n * This function returns number that corresponds to the percentage in a given range.\n *\n * PercentToRange(0.34,0,100) will return 34.\n * @param percent to convert to number\n * @param min min range\n * @param max max range\n * @returns the number\n */\n static PercentToRange(percent, min, max) {\n return (max - min) * percent + min;\n }\n /**\n * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.\n * @param angle The angle to normalize in radian.\n * @returns The converted angle.\n */\n static NormalizeRadians(angle) {\n // More precise but slower version kept for reference.\n // angle = angle % Tools.TwoPi;\n // angle = (angle + Tools.TwoPi) % Tools.TwoPi;\n //if (angle > Math.PI) {\n //\tangle -= Tools.TwoPi;\n //}\n angle -= Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi);\n return angle;\n }\n /**\n * Returns the highest common factor of two integers.\n * @param a first parameter\n * @param b second parameter\n * @returns HCF of a and b\n */\n static HCF(a, b) {\n const r = a % b;\n if (r === 0) {\n return b;\n }\n return Scalar.HCF(b, r);\n }\n}\n/**\n * Two pi constants convenient for computation.\n */\nScalar.TwoPi = Math.PI * 2;\n//# sourceMappingURL=math.scalar.js.map","/**\n * Class used to represent a viewport on screen\n */\nexport class Viewport {\n /**\n * Creates a Viewport object located at (x, y) and sized (width, height)\n * @param x defines viewport left coordinate\n * @param y defines viewport top coordinate\n * @param width defines the viewport width\n * @param height defines the viewport height\n */\n constructor(\n /** viewport left coordinate */\n x, \n /** viewport top coordinate */\n y, \n /**viewport width */\n width, \n /** viewport height */\n height) {\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n }\n /**\n * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)\n * @param renderWidth defines the rendering width\n * @param renderHeight defines the rendering height\n * @returns a new Viewport\n */\n toGlobal(renderWidth, renderHeight) {\n return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);\n }\n /**\n * Stores absolute viewport value into a target viewport (from 0-> width, 0-> height instead of 0->1)\n * @param renderWidth defines the rendering width\n * @param renderHeight defines the rendering height\n * @param ref defines the target viewport\n * @returns the current viewport\n */\n toGlobalToRef(renderWidth, renderHeight, ref) {\n ref.x = this.x * renderWidth;\n ref.y = this.y * renderHeight;\n ref.width = this.width * renderWidth;\n ref.height = this.height * renderHeight;\n return this;\n }\n /**\n * Returns a new Viewport copied from the current one\n * @returns a new Viewport\n */\n clone() {\n return new Viewport(this.x, this.y, this.width, this.height);\n }\n}\n//# sourceMappingURL=math.viewport.js.map","import { DataBuffer } from \"../../Buffers/dataBuffer.js\";\n/** @internal */\nexport class WebGLDataBuffer extends DataBuffer {\n constructor(resource) {\n super();\n this._buffer = resource;\n }\n get underlyingResource() {\n return this._buffer;\n }\n}\n//# sourceMappingURL=webGLDataBuffer.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { ScenePerformancePriority } from \"../scene.js\";\nimport { Quaternion, Matrix, Vector3, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { VertexData } from \"../Meshes/mesh.vertexData.js\";\nimport { TransformNode } from \"../Meshes/transformNode.js\";\nimport { PickingInfo } from \"../Collisions/pickingInfo.js\";\nimport { BoundingInfo } from \"../Culling/boundingInfo.js\";\n\nimport { UniformBuffer } from \"../Materials/uniformBuffer.js\";\nimport { _MeshCollisionData } from \"../Collisions/meshCollisionData.js\";\nimport { _WarnImport } from \"../Misc/devTools.js\";\nimport { extractMinAndMax } from \"../Maths/math.functions.js\";\nimport { Color3, Color4 } from \"../Maths/math.color.js\";\nimport { Epsilon } from \"../Maths/math.constants.js\";\nimport { Axis } from \"../Maths/math.axis.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\n/** @internal */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nclass _FacetDataStorage {\n constructor() {\n this.facetNb = 0; // facet number\n this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partitioning space\n this.partitioningBBoxRatio = 1.01; // the partitioning array space is by default 1% bigger than the bounding box\n this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ?\n this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation\n this.bbSize = Vector3.Zero(); // bbox size approximated for facet data\n this.subDiv = {\n // actual number of subdivisions per axis for ComputeNormals()\n max: 1,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n X: 1,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Y: 1,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Z: 1,\n };\n this.facetDepthSort = false; // is the facet depth sort to be computed\n this.facetDepthSortEnabled = false; // is the facet depth sort initialized\n }\n}\n/**\n * @internal\n **/\n// eslint-disable-next-line @typescript-eslint/naming-convention\nclass _InternalAbstractMeshDataInfo {\n constructor() {\n this._hasVertexAlpha = false;\n this._useVertexColors = true;\n this._numBoneInfluencers = 4;\n this._applyFog = true;\n this._receiveShadows = false;\n this._facetData = new _FacetDataStorage();\n this._visibility = 1.0;\n this._skeleton = null;\n this._layerMask = 0x0fffffff;\n this._computeBonesUsingShaders = true;\n this._isActive = false;\n this._onlyForInstances = false;\n this._isActiveIntermediate = false;\n this._onlyForInstancesIntermediate = false;\n this._actAsRegularMesh = false;\n this._currentLOD = null;\n this._currentLODIsUpToDate = false;\n this._collisionRetryCount = 3;\n this._morphTargetManager = null;\n this._renderingGroupId = 0;\n this._bakedVertexAnimationManager = null;\n this._material = null;\n this._positions = null;\n this._pointerOverDisableMeshTesting = false;\n // Collisions\n this._meshCollisionData = new _MeshCollisionData();\n this._enableDistantPicking = false;\n /** @internal\n * Bounding info that is unnafected by the addition of thin instances\n */\n this._rawBoundingInfo = null;\n }\n}\n/**\n * Class used to store all common mesh properties\n */\nexport class AbstractMesh extends TransformNode {\n /**\n * No billboard\n */\n static get BILLBOARDMODE_NONE() {\n return TransformNode.BILLBOARDMODE_NONE;\n }\n /** Billboard on X axis */\n static get BILLBOARDMODE_X() {\n return TransformNode.BILLBOARDMODE_X;\n }\n /** Billboard on Y axis */\n static get BILLBOARDMODE_Y() {\n return TransformNode.BILLBOARDMODE_Y;\n }\n /** Billboard on Z axis */\n static get BILLBOARDMODE_Z() {\n return TransformNode.BILLBOARDMODE_Z;\n }\n /** Billboard on all axes */\n static get BILLBOARDMODE_ALL() {\n return TransformNode.BILLBOARDMODE_ALL;\n }\n /** Billboard on using position instead of orientation */\n static get BILLBOARDMODE_USE_POSITION() {\n return TransformNode.BILLBOARDMODE_USE_POSITION;\n }\n /**\n * Gets the number of facets in the mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#what-is-a-mesh-facet\n */\n get facetNb() {\n return this._internalAbstractMeshDataInfo._facetData.facetNb;\n }\n /**\n * Gets or set the number (integer) of subdivisions per axis in the partitioning space\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#tweaking-the-partitioning\n */\n get partitioningSubdivisions() {\n return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions;\n }\n set partitioningSubdivisions(nb) {\n this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions = nb;\n }\n /**\n * The ratio (float) to apply to the bounding box size to set to the partitioning space.\n * Ex : 1.01 (default) the partitioning space is 1% bigger than the bounding box\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#tweaking-the-partitioning\n */\n get partitioningBBoxRatio() {\n return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio;\n }\n set partitioningBBoxRatio(ratio) {\n this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio = ratio;\n }\n /**\n * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.\n * Works only for updatable meshes.\n * Doesn't work with multi-materials\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#facet-depth-sort\n */\n get mustDepthSortFacets() {\n return this._internalAbstractMeshDataInfo._facetData.facetDepthSort;\n }\n set mustDepthSortFacets(sort) {\n this._internalAbstractMeshDataInfo._facetData.facetDepthSort = sort;\n }\n /**\n * The location (Vector3) where the facet depth sort must be computed from.\n * By default, the active camera position.\n * Used only when facet depth sort is enabled\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#facet-depth-sort\n */\n get facetDepthSortFrom() {\n return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom;\n }\n set facetDepthSortFrom(location) {\n this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom = location;\n }\n /** number of collision detection tries. Change this value if not all collisions are detected and handled properly */\n get collisionRetryCount() {\n return this._internalAbstractMeshDataInfo._collisionRetryCount;\n }\n set collisionRetryCount(retryCount) {\n this._internalAbstractMeshDataInfo._collisionRetryCount = retryCount;\n }\n /**\n * gets a boolean indicating if facetData is enabled\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#what-is-a-mesh-facet\n */\n get isFacetDataEnabled() {\n return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled;\n }\n /**\n * Gets or sets the morph target manager\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/morphTargets\n */\n get morphTargetManager() {\n return this._internalAbstractMeshDataInfo._morphTargetManager;\n }\n set morphTargetManager(value) {\n if (this._internalAbstractMeshDataInfo._morphTargetManager === value) {\n return;\n }\n this._internalAbstractMeshDataInfo._morphTargetManager = value;\n this._syncGeometryWithMorphTargetManager();\n }\n /**\n * Gets or sets the baked vertex animation manager\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/baked_texture_animations\n */\n get bakedVertexAnimationManager() {\n return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager;\n }\n set bakedVertexAnimationManager(value) {\n if (this._internalAbstractMeshDataInfo._bakedVertexAnimationManager === value) {\n return;\n }\n this._internalAbstractMeshDataInfo._bakedVertexAnimationManager = value;\n this._markSubMeshesAsAttributesDirty();\n }\n /** @internal */\n _syncGeometryWithMorphTargetManager() { }\n /**\n * @internal\n */\n _updateNonUniformScalingState(value) {\n if (!super._updateNonUniformScalingState(value)) {\n return false;\n }\n this._markSubMeshesAsMiscDirty();\n return true;\n }\n /** @internal */\n get rawBoundingInfo() {\n return this._internalAbstractMeshDataInfo._rawBoundingInfo;\n }\n set rawBoundingInfo(boundingInfo) {\n this._internalAbstractMeshDataInfo._rawBoundingInfo = boundingInfo;\n }\n /** Set a function to call when this mesh collides with another one */\n set onCollide(callback) {\n if (this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver) {\n this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver);\n }\n this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver = this.onCollideObservable.add(callback);\n }\n /** Set a function to call when the collision's position changes */\n set onCollisionPositionChange(callback) {\n if (this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver) {\n this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver);\n }\n this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);\n }\n /**\n * Gets or sets mesh visibility between 0 and 1 (default is 1)\n */\n get visibility() {\n return this._internalAbstractMeshDataInfo._visibility;\n }\n /**\n * Gets or sets mesh visibility between 0 and 1 (default is 1)\n */\n set visibility(value) {\n if (this._internalAbstractMeshDataInfo._visibility === value) {\n return;\n }\n const oldValue = this._internalAbstractMeshDataInfo._visibility;\n this._internalAbstractMeshDataInfo._visibility = value;\n if ((oldValue === 1 && value !== 1) || (oldValue !== 1 && value === 1)) {\n this._markSubMeshesAsDirty((defines) => {\n defines.markAsMiscDirty();\n defines.markAsPrePassDirty();\n });\n }\n }\n /**\n * Gets or sets the property which disables the test that is checking that the mesh under the pointer is the same than the previous time we tested for it (default: false).\n * Set this property to true if you want thin instances picking to be reported accurately when moving over the mesh.\n * Note that setting this property to true will incur some performance penalties when dealing with pointer events for this mesh so use it sparingly.\n */\n get pointerOverDisableMeshTesting() {\n return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting;\n }\n set pointerOverDisableMeshTesting(disable) {\n this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting = disable;\n }\n /**\n * Specifies the rendering group id for this mesh (0 by default)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/transparent_rendering#rendering-groups\n */\n get renderingGroupId() {\n return this._internalAbstractMeshDataInfo._renderingGroupId;\n }\n set renderingGroupId(value) {\n this._internalAbstractMeshDataInfo._renderingGroupId = value;\n }\n /** Gets or sets current material */\n get material() {\n return this._internalAbstractMeshDataInfo._material;\n }\n set material(value) {\n if (this._internalAbstractMeshDataInfo._material === value) {\n return;\n }\n // remove from material mesh map id needed\n if (this._internalAbstractMeshDataInfo._material && this._internalAbstractMeshDataInfo._material.meshMap) {\n this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId] = undefined;\n }\n this._internalAbstractMeshDataInfo._material = value;\n if (value && value.meshMap) {\n value.meshMap[this.uniqueId] = this;\n }\n if (this.onMaterialChangedObservable.hasObservers()) {\n this.onMaterialChangedObservable.notifyObservers(this);\n }\n if (!this.subMeshes) {\n return;\n }\n this.resetDrawCache();\n this._unBindEffect();\n }\n /**\n * Gets the material used to render the mesh in a specific render pass\n * @param renderPassId render pass id\n * @returns material used for the render pass. If no specific material is used for this render pass, undefined is returned (meaning mesh.material is used for this pass)\n */\n getMaterialForRenderPass(renderPassId) {\n var _a;\n return (_a = this._internalAbstractMeshDataInfo._materialForRenderPass) === null || _a === void 0 ? void 0 : _a[renderPassId];\n }\n /**\n * Sets the material to be used to render the mesh in a specific render pass\n * @param renderPassId render pass id\n * @param material material to use for this render pass. If undefined is passed, no specific material will be used for this render pass but the regular material will be used instead (mesh.material)\n */\n setMaterialForRenderPass(renderPassId, material) {\n this.resetDrawCache(renderPassId);\n if (!this._internalAbstractMeshDataInfo._materialForRenderPass) {\n this._internalAbstractMeshDataInfo._materialForRenderPass = [];\n }\n this._internalAbstractMeshDataInfo._materialForRenderPass[renderPassId] = material;\n }\n /**\n * Gets or sets a boolean indicating that this mesh can receive realtime shadows\n * @see https://doc.babylonjs.com/features/featuresDeepDive/lights/shadows\n */\n get receiveShadows() {\n return this._internalAbstractMeshDataInfo._receiveShadows;\n }\n set receiveShadows(value) {\n if (this._internalAbstractMeshDataInfo._receiveShadows === value) {\n return;\n }\n this._internalAbstractMeshDataInfo._receiveShadows = value;\n this._markSubMeshesAsLightDirty();\n }\n /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */\n get hasVertexAlpha() {\n return this._internalAbstractMeshDataInfo._hasVertexAlpha;\n }\n set hasVertexAlpha(value) {\n if (this._internalAbstractMeshDataInfo._hasVertexAlpha === value) {\n return;\n }\n this._internalAbstractMeshDataInfo._hasVertexAlpha = value;\n this._markSubMeshesAsAttributesDirty();\n this._markSubMeshesAsMiscDirty();\n }\n /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */\n get useVertexColors() {\n return this._internalAbstractMeshDataInfo._useVertexColors;\n }\n set useVertexColors(value) {\n if (this._internalAbstractMeshDataInfo._useVertexColors === value) {\n return;\n }\n this._internalAbstractMeshDataInfo._useVertexColors = value;\n this._markSubMeshesAsAttributesDirty();\n }\n /**\n * Gets or sets a boolean indicating that bone animations must be computed by the GPU (true by default)\n */\n get computeBonesUsingShaders() {\n return this._internalAbstractMeshDataInfo._computeBonesUsingShaders;\n }\n set computeBonesUsingShaders(value) {\n if (this._internalAbstractMeshDataInfo._computeBonesUsingShaders === value) {\n return;\n }\n this._internalAbstractMeshDataInfo._computeBonesUsingShaders = value;\n this._markSubMeshesAsAttributesDirty();\n }\n /** Gets or sets the number of allowed bone influences per vertex (4 by default) */\n get numBoneInfluencers() {\n return this._internalAbstractMeshDataInfo._numBoneInfluencers;\n }\n set numBoneInfluencers(value) {\n if (this._internalAbstractMeshDataInfo._numBoneInfluencers === value) {\n return;\n }\n this._internalAbstractMeshDataInfo._numBoneInfluencers = value;\n this._markSubMeshesAsAttributesDirty();\n }\n /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */\n get applyFog() {\n return this._internalAbstractMeshDataInfo._applyFog;\n }\n set applyFog(value) {\n if (this._internalAbstractMeshDataInfo._applyFog === value) {\n return;\n }\n this._internalAbstractMeshDataInfo._applyFog = value;\n this._markSubMeshesAsMiscDirty();\n }\n /** When enabled, decompose picking matrices for better precision with large values for mesh position and scling */\n get enableDistantPicking() {\n return this._internalAbstractMeshDataInfo._enableDistantPicking;\n }\n set enableDistantPicking(value) {\n this._internalAbstractMeshDataInfo._enableDistantPicking = value;\n }\n /**\n * Gets or sets the current layer mask (default is 0x0FFFFFFF)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/layerMasksAndMultiCam\n */\n get layerMask() {\n return this._internalAbstractMeshDataInfo._layerMask;\n }\n set layerMask(value) {\n if (value === this._internalAbstractMeshDataInfo._layerMask) {\n return;\n }\n this._internalAbstractMeshDataInfo._layerMask = value;\n this._resyncLightSources();\n }\n /**\n * Gets or sets a collision mask used to mask collisions (default is -1).\n * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0\n */\n get collisionMask() {\n return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask;\n }\n set collisionMask(mask) {\n this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask = !isNaN(mask) ? mask : -1;\n }\n /**\n * Gets or sets a collision response flag (default is true).\n * when collisionResponse is false, events are still triggered but colliding entity has no response\n * This helps creating trigger volume when user wants collision feedback events but not position/velocity\n * to respond to the collision.\n */\n get collisionResponse() {\n return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse;\n }\n set collisionResponse(response) {\n this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse = response;\n }\n /**\n * Gets or sets the current collision group mask (-1 by default).\n * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0\n */\n get collisionGroup() {\n return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup;\n }\n set collisionGroup(mask) {\n this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup = !isNaN(mask) ? mask : -1;\n }\n /**\n * Gets or sets current surrounding meshes (null by default).\n *\n * By default collision detection is tested against every mesh in the scene.\n * It is possible to set surroundingMeshes to a defined list of meshes and then only these specified\n * meshes will be tested for the collision.\n *\n * Note: if set to an empty array no collision will happen when this mesh is moved.\n */\n get surroundingMeshes() {\n return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes;\n }\n set surroundingMeshes(meshes) {\n this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes = meshes;\n }\n /** Gets the list of lights affecting that mesh */\n get lightSources() {\n return this._lightSources;\n }\n /** @internal */\n get _positions() {\n return null;\n }\n /**\n * Gets or sets a skeleton to apply skinning transformations\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons\n */\n set skeleton(value) {\n const skeleton = this._internalAbstractMeshDataInfo._skeleton;\n if (skeleton && skeleton.needInitialSkinMatrix) {\n skeleton._unregisterMeshWithPoseMatrix(this);\n }\n if (value && value.needInitialSkinMatrix) {\n value._registerMeshWithPoseMatrix(this);\n }\n this._internalAbstractMeshDataInfo._skeleton = value;\n if (!this._internalAbstractMeshDataInfo._skeleton) {\n this._bonesTransformMatrices = null;\n }\n this._markSubMeshesAsAttributesDirty();\n }\n get skeleton() {\n return this._internalAbstractMeshDataInfo._skeleton;\n }\n // Constructor\n /**\n * Creates a new AbstractMesh\n * @param name defines the name of the mesh\n * @param scene defines the hosting scene\n */\n constructor(name, scene = null) {\n super(name, scene, false);\n // Internal data\n /** @internal */\n this._internalAbstractMeshDataInfo = new _InternalAbstractMeshDataInfo();\n /** @internal */\n this._waitingMaterialId = null;\n /**\n * The culling strategy to use to check whether the mesh must be rendered or not.\n * This value can be changed at any time and will be used on the next render mesh selection.\n * The possible values are :\n * - AbstractMesh.CULLINGSTRATEGY_STANDARD\n * - AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY\n * - AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION\n * - AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY\n * Please read each static variable documentation to get details about the culling process.\n * */\n this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY;\n // Events\n /**\n * An event triggered when this mesh collides with another one\n */\n this.onCollideObservable = new Observable();\n /**\n * An event triggered when the collision's position changes\n */\n this.onCollisionPositionChangeObservable = new Observable();\n /**\n * An event triggered when material is changed\n */\n this.onMaterialChangedObservable = new Observable();\n // Properties\n /**\n * Gets or sets the orientation for POV movement & rotation\n */\n this.definedFacingForward = true;\n /** @internal */\n this._occlusionQuery = null;\n /** @internal */\n this._renderingGroup = null;\n /** Gets or sets the alpha index used to sort transparent meshes\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/transparent_rendering#alpha-index\n */\n this.alphaIndex = Number.MAX_VALUE;\n /**\n * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true\n */\n this.isVisible = true;\n /**\n * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true\n */\n this.isPickable = true;\n /**\n * Gets or sets a boolean indicating if the mesh can be near picked. Default is false\n */\n this.isNearPickable = false;\n /**\n * Gets or sets a boolean indicating if the mesh can be near grabbed. Default is false\n */\n this.isNearGrabbable = false;\n /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */\n this.showSubMeshesBoundingBox = false;\n /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare\n */\n this.isBlocker = false;\n /**\n * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)\n */\n this.enablePointerMoveEvents = false;\n /** Defines color to use when rendering outline */\n this.outlineColor = Color3.Red();\n /** Define width to use when rendering outline */\n this.outlineWidth = 0.02;\n /** Defines color to use when rendering overlay */\n this.overlayColor = Color3.Red();\n /** Defines alpha to use when rendering overlay */\n this.overlayAlpha = 0.5;\n /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */\n this.useOctreeForRenderingSelection = true;\n /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */\n this.useOctreeForPicking = true;\n /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */\n this.useOctreeForCollisions = true;\n /**\n * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)\n */\n this.alwaysSelectAsActiveMesh = false;\n /**\n * Gets or sets a boolean indicating that the bounding info does not need to be kept in sync (for performance reason)\n */\n this.doNotSyncBoundingInfo = false;\n /**\n * Gets or sets the current action manager\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\n this.actionManager = null;\n /**\n * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions\n */\n this.ellipsoid = new Vector3(0.5, 1, 0.5);\n /**\n * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions\n */\n this.ellipsoidOffset = new Vector3(0, 0, 0);\n // Edges\n /**\n * Defines edge width used when edgesRenderer is enabled\n * @see https://www.babylonjs-playground.com/#10OJSG#13\n */\n this.edgesWidth = 1;\n /**\n * Defines edge color used when edgesRenderer is enabled\n * @see https://www.babylonjs-playground.com/#10OJSG#13\n */\n this.edgesColor = new Color4(1, 0, 0, 1);\n /** @internal */\n this._edgesRenderer = null;\n /** @internal */\n this._masterMesh = null;\n this._boundingInfo = null;\n this._boundingInfoIsDirty = true;\n /** @internal */\n this._renderId = 0;\n /** @internal */\n this._intersectionsInProgress = new Array();\n /** @internal */\n this._unIndexed = false;\n /** @internal */\n this._lightSources = new Array();\n // Loading properties\n /** @internal */\n this._waitingData = {\n lods: null,\n actions: null,\n freezeWorldMatrix: null,\n };\n /** @internal */\n this._bonesTransformMatrices = null;\n /** @internal */\n this._transformMatrixTexture = null;\n /**\n * An event triggered when the mesh is rebuilt.\n */\n this.onRebuildObservable = new Observable();\n this._onCollisionPositionChange = (collisionId, newPosition, collidedMesh = null) => {\n newPosition.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions, this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions);\n if (this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length() > Engine.CollisionsEpsilon) {\n this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions);\n }\n if (collidedMesh) {\n this.onCollideObservable.notifyObservers(collidedMesh);\n }\n this.onCollisionPositionChangeObservable.notifyObservers(this.position);\n };\n scene = this.getScene();\n scene.addMesh(this);\n this._resyncLightSources();\n // Mesh Uniform Buffer.\n this._uniformBuffer = new UniformBuffer(this.getScene().getEngine(), undefined, undefined, name, !this.getScene().getEngine().isWebGPU);\n this._buildUniformLayout();\n switch (scene.performancePriority) {\n case ScenePerformancePriority.Aggressive:\n this.doNotSyncBoundingInfo = true;\n // eslint-disable-next-line no-fallthrough\n case ScenePerformancePriority.Intermediate:\n this.alwaysSelectAsActiveMesh = true;\n this.isPickable = false;\n break;\n }\n }\n _buildUniformLayout() {\n this._uniformBuffer.addUniform(\"world\", 16);\n this._uniformBuffer.addUniform(\"visibility\", 1);\n this._uniformBuffer.create();\n }\n /**\n * Transfer the mesh values to its UBO.\n * @param world The world matrix associated with the mesh\n */\n transferToEffect(world) {\n const ubo = this._uniformBuffer;\n ubo.updateMatrix(\"world\", world);\n ubo.updateFloat(\"visibility\", this._internalAbstractMeshDataInfo._visibility);\n ubo.update();\n }\n /**\n * Gets the mesh uniform buffer.\n * @returns the uniform buffer of the mesh.\n */\n getMeshUniformBuffer() {\n return this._uniformBuffer;\n }\n /**\n * Returns the string \"AbstractMesh\"\n * @returns \"AbstractMesh\"\n */\n getClassName() {\n return \"AbstractMesh\";\n }\n /**\n * Gets a string representation of the current mesh\n * @param fullDetails defines a boolean indicating if full details must be included\n * @returns a string representation of the current mesh\n */\n toString(fullDetails) {\n let ret = \"Name: \" + this.name + \", isInstance: \" + (this.getClassName() !== \"InstancedMesh\" ? \"YES\" : \"NO\");\n ret += \", # of submeshes: \" + (this.subMeshes ? this.subMeshes.length : 0);\n const skeleton = this._internalAbstractMeshDataInfo._skeleton;\n if (skeleton) {\n ret += \", skeleton: \" + skeleton.name;\n }\n if (fullDetails) {\n ret += \", billboard mode: \" + [\"NONE\", \"X\", \"Y\", null, \"Z\", null, null, \"ALL\"][this.billboardMode];\n ret += \", freeze wrld mat: \" + (this._isWorldMatrixFrozen || this._waitingData.freezeWorldMatrix ? \"YES\" : \"NO\");\n }\n return ret;\n }\n /**\n * @internal\n */\n _getEffectiveParent() {\n if (this._masterMesh && this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {\n return this._masterMesh;\n }\n return super._getEffectiveParent();\n }\n /**\n * @internal\n */\n _getActionManagerForTrigger(trigger, initialCall = true) {\n if (this.actionManager && (initialCall || this.actionManager.isRecursive)) {\n if (trigger) {\n if (this.actionManager.hasSpecificTrigger(trigger)) {\n return this.actionManager;\n }\n }\n else {\n return this.actionManager;\n }\n }\n if (!this.parent) {\n return null;\n }\n return this.parent._getActionManagerForTrigger(trigger, false);\n }\n /**\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _rebuild(dispose = false) {\n this.onRebuildObservable.notifyObservers(this);\n if (this._occlusionQuery !== null) {\n this._occlusionQuery = null;\n }\n if (!this.subMeshes) {\n return;\n }\n for (const subMesh of this.subMeshes) {\n subMesh._rebuild();\n }\n }\n /** @internal */\n _resyncLightSources() {\n this._lightSources.length = 0;\n for (const light of this.getScene().lights) {\n if (!light.isEnabled()) {\n continue;\n }\n if (light.canAffectMesh(this)) {\n this._lightSources.push(light);\n }\n }\n this._markSubMeshesAsLightDirty();\n }\n /**\n * @internal\n */\n _resyncLightSource(light) {\n const isIn = light.isEnabled() && light.canAffectMesh(this);\n const index = this._lightSources.indexOf(light);\n let removed = false;\n if (index === -1) {\n if (!isIn) {\n return;\n }\n this._lightSources.push(light);\n }\n else {\n if (isIn) {\n return;\n }\n removed = true;\n this._lightSources.splice(index, 1);\n }\n this._markSubMeshesAsLightDirty(removed);\n }\n /** @internal */\n _unBindEffect() {\n for (const subMesh of this.subMeshes) {\n subMesh.setEffect(null);\n }\n }\n /**\n * @internal\n */\n _removeLightSource(light, dispose) {\n const index = this._lightSources.indexOf(light);\n if (index === -1) {\n return;\n }\n this._lightSources.splice(index, 1);\n this._markSubMeshesAsLightDirty(dispose);\n }\n _markSubMeshesAsDirty(func) {\n if (!this.subMeshes) {\n return;\n }\n for (const subMesh of this.subMeshes) {\n for (let i = 0; i < subMesh._drawWrappers.length; ++i) {\n const drawWrapper = subMesh._drawWrappers[i];\n if (!drawWrapper || !drawWrapper.defines || !drawWrapper.defines.markAllAsDirty) {\n continue;\n }\n func(drawWrapper.defines);\n }\n }\n }\n /**\n * @internal\n */\n _markSubMeshesAsLightDirty(dispose = false) {\n this._markSubMeshesAsDirty((defines) => defines.markAsLightDirty(dispose));\n }\n /** @internal */\n _markSubMeshesAsAttributesDirty() {\n this._markSubMeshesAsDirty((defines) => defines.markAsAttributesDirty());\n }\n /** @internal */\n _markSubMeshesAsMiscDirty() {\n this._markSubMeshesAsDirty((defines) => defines.markAsMiscDirty());\n }\n /**\n * Flag the AbstractMesh as dirty (Forcing it to update everything)\n * @param property if set to \"rotation\" the objects rotationQuaternion will be set to null\n * @returns this AbstractMesh\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n markAsDirty(property) {\n this._currentRenderId = Number.MAX_VALUE;\n this._isDirty = true;\n return this;\n }\n /**\n * Resets the draw wrappers cache for all submeshes of this abstract mesh\n * @param passId If provided, releases only the draw wrapper corresponding to this render pass id\n */\n resetDrawCache(passId) {\n if (!this.subMeshes) {\n return;\n }\n for (const subMesh of this.subMeshes) {\n subMesh.resetDrawCache(passId);\n }\n }\n // Methods\n /**\n * Returns true if the mesh is blocked. Implemented by child classes\n */\n get isBlocked() {\n return false;\n }\n /**\n * Returns the mesh itself by default. Implemented by child classes\n * @param camera defines the camera to use to pick the right LOD level\n * @returns the currentAbstractMesh\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getLOD(camera) {\n return this;\n }\n /**\n * Returns 0 by default. Implemented by child classes\n * @returns an integer\n */\n getTotalVertices() {\n return 0;\n }\n /**\n * Returns a positive integer : the total number of indices in this mesh geometry.\n * @returns the number of indices or zero if the mesh has no geometry.\n */\n getTotalIndices() {\n return 0;\n }\n /**\n * Returns null by default. Implemented by child classes\n * @returns null\n */\n getIndices() {\n return null;\n }\n /**\n * Returns the array of the requested vertex data kind. Implemented by child classes\n * @param kind defines the vertex data kind to use\n * @returns null\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getVerticesData(kind) {\n return null;\n }\n /**\n * Sets the vertex data of the mesh geometry for the requested `kind`.\n * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.\n * Note that a new underlying VertexBuffer object is created each call.\n * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.\n * @param kind defines vertex data kind:\n * * VertexBuffer.PositionKind\n * * VertexBuffer.UVKind\n * * VertexBuffer.UV2Kind\n * * VertexBuffer.UV3Kind\n * * VertexBuffer.UV4Kind\n * * VertexBuffer.UV5Kind\n * * VertexBuffer.UV6Kind\n * * VertexBuffer.ColorKind\n * * VertexBuffer.MatricesIndicesKind\n * * VertexBuffer.MatricesIndicesExtraKind\n * * VertexBuffer.MatricesWeightsKind\n * * VertexBuffer.MatricesWeightsExtraKind\n * @param data defines the data source\n * @param updatable defines if the data must be flagged as updatable (or static)\n * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind\n * @returns the current mesh\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n setVerticesData(kind, data, updatable, stride) {\n return this;\n }\n /**\n * Updates the existing vertex data of the mesh geometry for the requested `kind`.\n * If the mesh has no geometry, it is simply returned as it is.\n * @param kind defines vertex data kind:\n * * VertexBuffer.PositionKind\n * * VertexBuffer.UVKind\n * * VertexBuffer.UV2Kind\n * * VertexBuffer.UV3Kind\n * * VertexBuffer.UV4Kind\n * * VertexBuffer.UV5Kind\n * * VertexBuffer.UV6Kind\n * * VertexBuffer.ColorKind\n * * VertexBuffer.MatricesIndicesKind\n * * VertexBuffer.MatricesIndicesExtraKind\n * * VertexBuffer.MatricesWeightsKind\n * * VertexBuffer.MatricesWeightsExtraKind\n * @param data defines the data source\n * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed\n * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh\n * @returns the current mesh\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n updateVerticesData(kind, data, updateExtends, makeItUnique) {\n return this;\n }\n /**\n * Sets the mesh indices,\n * If the mesh has no geometry, a new Geometry object is created and set to the mesh.\n * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)\n * @param totalVertices Defines the total number of vertices\n * @returns the current mesh\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n setIndices(indices, totalVertices) {\n return this;\n }\n /**\n * Gets a boolean indicating if specific vertex data is present\n * @param kind defines the vertex data kind to use\n * @returns true is data kind is present\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isVerticesDataPresent(kind) {\n return false;\n }\n /**\n * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined.\n * Note that it returns a shallow bounding of the mesh (i.e. it does not include children).\n * However, if the mesh contains thin instances, it will be expanded to include them. If you want the \"raw\" bounding data instead, then use `getRawBoundingInfo()`.\n * To get the full bounding of all children, call `getHierarchyBoundingVectors` instead.\n * @returns a BoundingInfo\n */\n getBoundingInfo() {\n if (this._masterMesh) {\n return this._masterMesh.getBoundingInfo();\n }\n if (this._boundingInfoIsDirty) {\n this._boundingInfoIsDirty = false;\n // this._boundingInfo is being created if undefined\n this._updateBoundingInfo();\n }\n // cannot be null.\n return this._boundingInfo;\n }\n /**\n * Returns the bounding info unnafected by instance data.\n * @returns the bounding info of the mesh unaffected by instance data.\n */\n getRawBoundingInfo() {\n var _a;\n return (_a = this.rawBoundingInfo) !== null && _a !== void 0 ? _a : this.getBoundingInfo();\n }\n /**\n * Overwrite the current bounding info\n * @param boundingInfo defines the new bounding info\n * @returns the current mesh\n */\n setBoundingInfo(boundingInfo) {\n this._boundingInfo = boundingInfo;\n return this;\n }\n /**\n * Returns true if there is already a bounding info\n */\n get hasBoundingInfo() {\n return this._boundingInfo !== null;\n }\n /**\n * Creates a new bounding info for the mesh\n * @param minimum min vector of the bounding box/sphere\n * @param maximum max vector of the bounding box/sphere\n * @param worldMatrix defines the new world matrix\n * @returns the new bounding info\n */\n buildBoundingInfo(minimum, maximum, worldMatrix) {\n this._boundingInfo = new BoundingInfo(minimum, maximum, worldMatrix);\n return this._boundingInfo;\n }\n /**\n * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)\n * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box. Default is false\n * @param ignoreRotation ignore rotation when computing the scale (ie. object will be axis aligned). Default is false\n * @param predicate predicate that is passed in to getHierarchyBoundingVectors when selecting which object should be included when scaling\n * @returns the current mesh\n */\n normalizeToUnitCube(includeDescendants = true, ignoreRotation = false, predicate) {\n return super.normalizeToUnitCube(includeDescendants, ignoreRotation, predicate);\n }\n /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */\n get useBones() {\n return ((this.skeleton &&\n this.getScene().skeletonsEnabled &&\n this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind) &&\n this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)));\n }\n /** @internal */\n _preActivate() { }\n /**\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _preActivateForIntermediateRendering(renderId) { }\n /**\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _activate(renderId, intermediateRendering) {\n this._renderId = renderId;\n return true;\n }\n /** @internal */\n _postActivate() {\n // Do nothing\n }\n /** @internal */\n _freeze() {\n // Do nothing\n }\n /** @internal */\n _unFreeze() {\n // Do nothing\n }\n /**\n * Gets the current world matrix\n * @returns a Matrix\n */\n getWorldMatrix() {\n if (this._masterMesh && this.billboardMode === TransformNode.BILLBOARDMODE_NONE) {\n return this._masterMesh.getWorldMatrix();\n }\n return super.getWorldMatrix();\n }\n /** @internal */\n _getWorldMatrixDeterminant() {\n if (this._masterMesh) {\n return this._masterMesh._getWorldMatrixDeterminant();\n }\n return super._getWorldMatrixDeterminant();\n }\n /**\n * Gets a boolean indicating if this mesh is an instance or a regular mesh\n */\n get isAnInstance() {\n return false;\n }\n /**\n * Gets a boolean indicating if this mesh has instances\n */\n get hasInstances() {\n return false;\n }\n /**\n * Gets a boolean indicating if this mesh has thin instances\n */\n get hasThinInstances() {\n return false;\n }\n // ================================== Point of View Movement =================================\n /**\n * Perform relative position change from the point of view of behind the front of the mesh.\n * This is performed taking into account the meshes current rotation, so you do not have to care.\n * Supports definition of mesh facing forward or backward {@link definedFacingForwardSearch | See definedFacingForwardSearch }.\n * @param amountRight defines the distance on the right axis\n * @param amountUp defines the distance on the up axis\n * @param amountForward defines the distance on the forward axis\n * @returns the current mesh\n */\n movePOV(amountRight, amountUp, amountForward) {\n this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));\n return this;\n }\n /**\n * Calculate relative position change from the point of view of behind the front of the mesh.\n * This is performed taking into account the meshes current rotation, so you do not have to care.\n * Supports definition of mesh facing forward or backward {@link definedFacingForwardSearch | See definedFacingForwardSearch }.\n * @param amountRight defines the distance on the right axis\n * @param amountUp defines the distance on the up axis\n * @param amountForward defines the distance on the forward axis\n * @returns the new displacement vector\n */\n calcMovePOV(amountRight, amountUp, amountForward) {\n const rotMatrix = new Matrix();\n const rotQuaternion = this.rotationQuaternion ? this.rotationQuaternion : Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);\n rotQuaternion.toRotationMatrix(rotMatrix);\n const translationDelta = Vector3.Zero();\n const defForwardMult = this.definedFacingForward ? -1 : 1;\n Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);\n return translationDelta;\n }\n // ================================== Point of View Rotation =================================\n /**\n * Perform relative rotation change from the point of view of behind the front of the mesh.\n * Supports definition of mesh facing forward or backward {@link definedFacingForwardSearch | See definedFacingForwardSearch }.\n * @param flipBack defines the flip\n * @param twirlClockwise defines the twirl\n * @param tiltRight defines the tilt\n * @returns the current mesh\n */\n rotatePOV(flipBack, twirlClockwise, tiltRight) {\n this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));\n return this;\n }\n /**\n * Calculate relative rotation change from the point of view of behind the front of the mesh.\n * Supports definition of mesh facing forward or backward {@link definedFacingForwardSearch | See definedFacingForwardSearch }.\n * @param flipBack defines the flip\n * @param twirlClockwise defines the twirl\n * @param tiltRight defines the tilt\n * @returns the new rotation vector\n */\n calcRotatePOV(flipBack, twirlClockwise, tiltRight) {\n const defForwardMult = this.definedFacingForward ? 1 : -1;\n return new Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);\n }\n /**\n * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.\n * This means the mesh underlying bounding box and sphere are recomputed.\n * @param applySkeleton defines whether to apply the skeleton before computing the bounding info\n * @param applyMorph defines whether to apply the morph target before computing the bounding info\n * @returns the current mesh\n */\n refreshBoundingInfo(applySkeleton = false, applyMorph = false) {\n if (this._boundingInfo && this._boundingInfo.isLocked) {\n return this;\n }\n this._refreshBoundingInfo(this._getPositionData(applySkeleton, applyMorph), null);\n return this;\n }\n /**\n * @internal\n */\n _refreshBoundingInfo(data, bias) {\n if (data) {\n const extend = extractMinAndMax(data, 0, this.getTotalVertices(), bias);\n if (this._boundingInfo) {\n this._boundingInfo.reConstruct(extend.minimum, extend.maximum);\n }\n else {\n this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);\n }\n }\n if (this.subMeshes) {\n for (let index = 0; index < this.subMeshes.length; index++) {\n this.subMeshes[index].refreshBoundingInfo(data);\n }\n }\n this._updateBoundingInfo();\n }\n /**\n * Internal function to get buffer data and possibly apply morphs and normals\n * @param applySkeleton\n * @param applyMorph\n * @param data\n * @param kind the kind of data you want. Can be Normal or Position\n */\n _getData(applySkeleton = false, applyMorph = false, data, kind = VertexBuffer.PositionKind) {\n data = data !== null && data !== void 0 ? data : this.getVerticesData(kind).slice();\n if (data && applyMorph && this.morphTargetManager) {\n let faceIndexCount = 0;\n let positionIndex = 0;\n for (let vertexCount = 0; vertexCount < data.length; vertexCount++) {\n for (let targetCount = 0; targetCount < this.morphTargetManager.numTargets; targetCount++) {\n const targetMorph = this.morphTargetManager.getTarget(targetCount);\n const influence = targetMorph.influence;\n if (influence > 0.0) {\n const morphTargetPositions = targetMorph.getPositions();\n if (morphTargetPositions) {\n data[vertexCount] += (morphTargetPositions[vertexCount] - data[vertexCount]) * influence;\n }\n }\n }\n faceIndexCount++;\n if (kind === VertexBuffer.PositionKind) {\n if (this._positions && faceIndexCount === 3) {\n // We want to merge into positions every 3 indices starting (but not 0)\n faceIndexCount = 0;\n const index = positionIndex * 3;\n this._positions[positionIndex++].copyFromFloats(data[index], data[index + 1], data[index + 2]);\n }\n }\n }\n }\n if (data && applySkeleton && this.skeleton) {\n const matricesIndicesData = this.getVerticesData(VertexBuffer.MatricesIndicesKind);\n const matricesWeightsData = this.getVerticesData(VertexBuffer.MatricesWeightsKind);\n if (matricesWeightsData && matricesIndicesData) {\n const needExtras = this.numBoneInfluencers > 4;\n const matricesIndicesExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind) : null;\n const matricesWeightsExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind) : null;\n const skeletonMatrices = this.skeleton.getTransformMatrices(this);\n const tempVector = TmpVectors.Vector3[0];\n const finalMatrix = TmpVectors.Matrix[0];\n const tempMatrix = TmpVectors.Matrix[1];\n let matWeightIdx = 0;\n for (let index = 0; index < data.length; index += 3, matWeightIdx += 4) {\n finalMatrix.reset();\n let inf;\n let weight;\n for (inf = 0; inf < 4; inf++) {\n weight = matricesWeightsData[matWeightIdx + inf];\n if (weight > 0) {\n Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);\n finalMatrix.addToSelf(tempMatrix);\n }\n }\n if (needExtras) {\n for (inf = 0; inf < 4; inf++) {\n weight = matricesWeightsExtraData[matWeightIdx + inf];\n if (weight > 0) {\n Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);\n finalMatrix.addToSelf(tempMatrix);\n }\n }\n }\n if (kind === VertexBuffer.NormalKind) {\n Vector3.TransformNormalFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);\n }\n else {\n Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);\n }\n tempVector.toArray(data, index);\n if (kind === VertexBuffer.PositionKind && this._positions) {\n this._positions[index / 3].copyFrom(tempVector);\n }\n }\n }\n }\n return data;\n }\n /**\n * Get the normals vertex data and optionally apply skeleton and morphing.\n * @param applySkeleton defines whether to apply the skeleton\n * @param applyMorph defines whether to apply the morph target\n * @returns the normals data\n */\n getNormalsData(applySkeleton = false, applyMorph = false) {\n return this._getData(applySkeleton, applyMorph, null, VertexBuffer.NormalKind);\n }\n /**\n * Get the position vertex data and optionally apply skeleton and morphing.\n * @param applySkeleton defines whether to apply the skeleton\n * @param applyMorph defines whether to apply the morph target\n * @param data defines the position data to apply the skeleton and morph to\n * @returns the position data\n */\n getPositionData(applySkeleton = false, applyMorph = false, data) {\n return this._getData(applySkeleton, applyMorph, data, VertexBuffer.PositionKind);\n }\n /**\n * @internal\n */\n _getPositionData(applySkeleton, applyMorph) {\n var _a;\n let data = this.getVerticesData(VertexBuffer.PositionKind);\n if (this._internalAbstractMeshDataInfo._positions) {\n this._internalAbstractMeshDataInfo._positions = null;\n }\n if (data && ((applySkeleton && this.skeleton) || (applyMorph && this.morphTargetManager))) {\n data = data.slice();\n this._generatePointsArray();\n if (this._positions) {\n const pos = this._positions;\n this._internalAbstractMeshDataInfo._positions = new Array(pos.length);\n for (let i = 0; i < pos.length; i++) {\n this._internalAbstractMeshDataInfo._positions[i] = ((_a = pos[i]) === null || _a === void 0 ? void 0 : _a.clone()) || new Vector3();\n }\n }\n return this.getPositionData(applySkeleton, applyMorph, data);\n }\n return data;\n }\n /** @internal */\n _updateBoundingInfo() {\n if (this._boundingInfo) {\n this._boundingInfo.update(this.worldMatrixFromCache);\n }\n else {\n this._boundingInfo = new BoundingInfo(Vector3.Zero(), Vector3.Zero(), this.worldMatrixFromCache);\n }\n this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);\n return this;\n }\n /**\n * @internal\n */\n _updateSubMeshesBoundingInfo(matrix) {\n if (!this.subMeshes) {\n return this;\n }\n const count = this.subMeshes.length;\n for (let subIndex = 0; subIndex < count; subIndex++) {\n const subMesh = this.subMeshes[subIndex];\n if (count > 1 || !subMesh.IsGlobal) {\n subMesh.updateBoundingInfo(matrix);\n }\n }\n return this;\n }\n /** @internal */\n _afterComputeWorldMatrix() {\n if (this.doNotSyncBoundingInfo) {\n return;\n }\n // Bounding info\n this._boundingInfoIsDirty = true;\n }\n /**\n * Returns `true` if the mesh is within the frustum defined by the passed array of planes.\n * A mesh is in the frustum if its bounding box intersects the frustum\n * @param frustumPlanes defines the frustum to test\n * @returns true if the mesh is in the frustum planes\n */\n isInFrustum(frustumPlanes) {\n return this.getBoundingInfo().isInFrustum(frustumPlanes, this.cullingStrategy);\n }\n /**\n * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.\n * A mesh is completely in the frustum if its bounding box it completely inside the frustum.\n * @param frustumPlanes defines the frustum to test\n * @returns true if the mesh is completely in the frustum planes\n */\n isCompletelyInFrustum(frustumPlanes) {\n return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);\n }\n /**\n * True if the mesh intersects another mesh or a SolidParticle object\n * @param mesh defines a target mesh or SolidParticle to test\n * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)\n * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes\n * @returns true if there is an intersection\n */\n intersectsMesh(mesh, precise = false, includeDescendants) {\n const boundingInfo = this.getBoundingInfo();\n const otherBoundingInfo = mesh.getBoundingInfo();\n if (boundingInfo.intersects(otherBoundingInfo, precise)) {\n return true;\n }\n if (includeDescendants) {\n for (const child of this.getChildMeshes()) {\n if (child.intersectsMesh(mesh, precise, true)) {\n return true;\n }\n }\n }\n return false;\n }\n /**\n * Returns true if the passed point (Vector3) is inside the mesh bounding box\n * @param point defines the point to test\n * @returns true if there is an intersection\n */\n intersectsPoint(point) {\n return this.getBoundingInfo().intersectsPoint(point);\n }\n // Collisions\n /**\n * Gets or sets a boolean indicating that this mesh can be used in the collision engine\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions\n */\n get checkCollisions() {\n return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions;\n }\n set checkCollisions(collisionEnabled) {\n this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions = collisionEnabled;\n }\n /**\n * Gets Collider object used to compute collisions (not physics)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions\n */\n get collider() {\n return this._internalAbstractMeshDataInfo._meshCollisionData._collider;\n }\n /**\n * Move the mesh using collision engine\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions\n * @param displacement defines the requested displacement vector\n * @returns the current mesh\n */\n moveWithCollisions(displacement) {\n const globalPosition = this.getAbsolutePosition();\n globalPosition.addToRef(this.ellipsoidOffset, this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);\n const coordinator = this.getScene().collisionCoordinator;\n if (!this._internalAbstractMeshDataInfo._meshCollisionData._collider) {\n this._internalAbstractMeshDataInfo._meshCollisionData._collider = coordinator.createCollider();\n }\n this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius = this.ellipsoid;\n coordinator.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions, displacement, this._internalAbstractMeshDataInfo._meshCollisionData._collider, this.collisionRetryCount, this, this._onCollisionPositionChange, this.uniqueId);\n return this;\n }\n // Collisions\n /**\n * @internal\n */\n _collideForSubMesh(subMesh, transformMatrix, collider) {\n var _a;\n this._generatePointsArray();\n if (!this._positions) {\n return this;\n }\n // Transformation\n if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {\n subMesh._lastColliderTransformMatrix = transformMatrix.clone();\n subMesh._lastColliderWorldVertices = [];\n subMesh._trianglePlanes = [];\n const start = subMesh.verticesStart;\n const end = subMesh.verticesStart + subMesh.verticesCount;\n for (let i = start; i < end; i++) {\n subMesh._lastColliderWorldVertices.push(Vector3.TransformCoordinates(this._positions[i], transformMatrix));\n }\n }\n // Collide\n collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial(), this, this._shouldConvertRHS(), ((_a = subMesh.getMaterial()) === null || _a === void 0 ? void 0 : _a.fillMode) === 7);\n return this;\n }\n /**\n * @internal\n */\n _processCollisionsForSubMeshes(collider, transformMatrix) {\n const subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);\n const len = subMeshes.length;\n for (let index = 0; index < len; index++) {\n const subMesh = subMeshes.data[index];\n // Bounding test\n if (len > 1 && !subMesh._checkCollision(collider)) {\n continue;\n }\n this._collideForSubMesh(subMesh, transformMatrix, collider);\n }\n return this;\n }\n /** @internal */\n _shouldConvertRHS() {\n return false;\n }\n /**\n * @internal\n */\n _checkCollision(collider) {\n // Bounding box test\n if (!this.getBoundingInfo()._checkCollision(collider)) {\n return this;\n }\n // Transformation matrix\n const collisionsScalingMatrix = TmpVectors.Matrix[0];\n const collisionsTransformMatrix = TmpVectors.Matrix[1];\n Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, collisionsScalingMatrix);\n this.worldMatrixFromCache.multiplyToRef(collisionsScalingMatrix, collisionsTransformMatrix);\n this._processCollisionsForSubMeshes(collider, collisionsTransformMatrix);\n return this;\n }\n // Picking\n /** @internal */\n _generatePointsArray() {\n return false;\n }\n /**\n * Checks if the passed Ray intersects with the mesh. A mesh triangle can be picked both from its front and back sides,\n * irrespective of orientation.\n * @param ray defines the ray to use. It should be in the mesh's LOCAL coordinate space.\n * @param fastCheck defines if fast mode (but less precise) must be used (false by default)\n * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected\n * @param onlyBoundingInfo defines a boolean indicating if picking should only happen using bounding info (false by default)\n * @param worldToUse defines the world matrix to use to get the world coordinate of the intersection point\n * @param skipBoundingInfo a boolean indicating if we should skip the bounding info check\n * @returns the picking info\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/mesh_intersect\n */\n intersects(ray, fastCheck, trianglePredicate, onlyBoundingInfo = false, worldToUse, skipBoundingInfo = false) {\n const pickingInfo = new PickingInfo();\n const className = this.getClassName();\n const intersectionThreshold = className === \"InstancedLinesMesh\" || className === \"LinesMesh\" || className === \"GreasedLineMesh\" ? this.intersectionThreshold : 0;\n const boundingInfo = this.getBoundingInfo();\n if (!this.subMeshes) {\n return pickingInfo;\n }\n if (!skipBoundingInfo &&\n (!ray.intersectsSphere(boundingInfo.boundingSphere, intersectionThreshold) || !ray.intersectsBox(boundingInfo.boundingBox, intersectionThreshold))) {\n return pickingInfo;\n }\n if (onlyBoundingInfo) {\n pickingInfo.hit = skipBoundingInfo ? false : true;\n pickingInfo.pickedMesh = skipBoundingInfo ? null : this;\n pickingInfo.distance = skipBoundingInfo ? 0 : Vector3.Distance(ray.origin, boundingInfo.boundingSphere.center);\n pickingInfo.subMeshId = 0;\n return pickingInfo;\n }\n if (!this._generatePointsArray()) {\n return pickingInfo;\n }\n let intersectInfo = null;\n const subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);\n const len = subMeshes.length;\n // Check if all submeshes are using a material that don't allow picking (point/lines rendering)\n // if no submesh can be picked that way, then fallback to BBox picking\n let anySubmeshSupportIntersect = false;\n for (let index = 0; index < len; index++) {\n const subMesh = subMeshes.data[index];\n const material = subMesh.getMaterial();\n if (!material) {\n continue;\n }\n if (material.fillMode == 7 ||\n material.fillMode == 0 ||\n material.fillMode == 1 ||\n material.fillMode == 2 ||\n material.fillMode == 4) {\n anySubmeshSupportIntersect = true;\n break;\n }\n }\n // no sub mesh support intersection, fallback to BBox that has already be done\n if (!anySubmeshSupportIntersect) {\n pickingInfo.hit = true;\n pickingInfo.pickedMesh = this;\n pickingInfo.distance = Vector3.Distance(ray.origin, boundingInfo.boundingSphere.center);\n pickingInfo.subMeshId = -1;\n return pickingInfo;\n }\n // at least 1 submesh supports intersection, keep going\n for (let index = 0; index < len; index++) {\n const subMesh = subMeshes.data[index];\n // Bounding test\n if (len > 1 && !subMesh.canIntersects(ray)) {\n continue;\n }\n const currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck, trianglePredicate);\n if (currentIntersectInfo) {\n if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {\n intersectInfo = currentIntersectInfo;\n intersectInfo.subMeshId = index;\n if (fastCheck) {\n break;\n }\n }\n }\n }\n if (intersectInfo) {\n // Get picked point\n const world = worldToUse !== null && worldToUse !== void 0 ? worldToUse : this.getWorldMatrix();\n const worldOrigin = TmpVectors.Vector3[0];\n const direction = TmpVectors.Vector3[1];\n Vector3.TransformCoordinatesToRef(ray.origin, world, worldOrigin);\n ray.direction.scaleToRef(intersectInfo.distance, direction);\n const worldDirection = Vector3.TransformNormal(direction, world);\n const pickedPoint = worldDirection.addInPlace(worldOrigin);\n // Return result\n pickingInfo.hit = true;\n pickingInfo.distance = Vector3.Distance(worldOrigin, pickedPoint);\n pickingInfo.pickedPoint = pickedPoint;\n pickingInfo.pickedMesh = this;\n pickingInfo.bu = intersectInfo.bu || 0;\n pickingInfo.bv = intersectInfo.bv || 0;\n pickingInfo.subMeshFaceId = intersectInfo.faceId;\n pickingInfo.faceId = intersectInfo.faceId + subMeshes.data[intersectInfo.subMeshId].indexStart / (this.getClassName().indexOf(\"LinesMesh\") !== -1 ? 2 : 3);\n pickingInfo.subMeshId = intersectInfo.subMeshId;\n return pickingInfo;\n }\n return pickingInfo;\n }\n /**\n * Clones the current mesh\n * @param name defines the mesh name\n * @param newParent defines the new mesh parent\n * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)\n * @returns the new mesh\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n clone(name, newParent, doNotCloneChildren) {\n return null;\n }\n /**\n * Disposes all the submeshes of the current meshnp\n * @returns the current mesh\n */\n releaseSubMeshes() {\n if (this.subMeshes) {\n while (this.subMeshes.length) {\n this.subMeshes[0].dispose();\n }\n }\n else {\n this.subMeshes = new Array();\n }\n return this;\n }\n /**\n * Releases resources associated with this abstract mesh.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n dispose(doNotRecurse, disposeMaterialAndTextures = false) {\n let index;\n // mesh map release.\n if (this._scene.useMaterialMeshMap) {\n // remove from material mesh map id needed\n if (this._internalAbstractMeshDataInfo._material && this._internalAbstractMeshDataInfo._material.meshMap) {\n this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId] = undefined;\n }\n }\n // Smart Array Retainers.\n this.getScene().freeActiveMeshes();\n this.getScene().freeRenderingGroups();\n // Action manager\n if (this.actionManager !== undefined && this.actionManager !== null) {\n this.actionManager.dispose();\n this.actionManager = null;\n }\n // Skeleton\n this._internalAbstractMeshDataInfo._skeleton = null;\n if (this._transformMatrixTexture) {\n this._transformMatrixTexture.dispose();\n this._transformMatrixTexture = null;\n }\n // Intersections in progress\n for (index = 0; index < this._intersectionsInProgress.length; index++) {\n const other = this._intersectionsInProgress[index];\n const pos = other._intersectionsInProgress.indexOf(this);\n other._intersectionsInProgress.splice(pos, 1);\n }\n this._intersectionsInProgress.length = 0;\n // Lights\n const lights = this.getScene().lights;\n lights.forEach((light) => {\n let meshIndex = light.includedOnlyMeshes.indexOf(this);\n if (meshIndex !== -1) {\n light.includedOnlyMeshes.splice(meshIndex, 1);\n }\n meshIndex = light.excludedMeshes.indexOf(this);\n if (meshIndex !== -1) {\n light.excludedMeshes.splice(meshIndex, 1);\n }\n // Shadow generators\n const generators = light.getShadowGenerators();\n if (generators) {\n const iterator = generators.values();\n for (let key = iterator.next(); key.done !== true; key = iterator.next()) {\n const generator = key.value;\n const shadowMap = generator.getShadowMap();\n if (shadowMap && shadowMap.renderList) {\n meshIndex = shadowMap.renderList.indexOf(this);\n if (meshIndex !== -1) {\n shadowMap.renderList.splice(meshIndex, 1);\n }\n }\n }\n }\n });\n // SubMeshes\n if (this.getClassName() !== \"InstancedMesh\" || this.getClassName() !== \"InstancedLinesMesh\") {\n this.releaseSubMeshes();\n }\n // Query\n const engine = this.getScene().getEngine();\n if (this._occlusionQuery !== null) {\n this.isOcclusionQueryInProgress = false;\n engine.deleteQuery(this._occlusionQuery);\n this._occlusionQuery = null;\n }\n // Engine\n engine.wipeCaches();\n // Remove from scene\n this.getScene().removeMesh(this);\n if (this._parentContainer) {\n const index = this._parentContainer.meshes.indexOf(this);\n if (index > -1) {\n this._parentContainer.meshes.splice(index, 1);\n }\n this._parentContainer = null;\n }\n if (disposeMaterialAndTextures) {\n if (this.material) {\n if (this.material.getClassName() === \"MultiMaterial\") {\n this.material.dispose(false, true, true);\n }\n else {\n this.material.dispose(false, true);\n }\n }\n }\n if (!doNotRecurse) {\n // Particles\n for (index = 0; index < this.getScene().particleSystems.length; index++) {\n if (this.getScene().particleSystems[index].emitter === this) {\n this.getScene().particleSystems[index].dispose();\n index--;\n }\n }\n }\n // facet data\n if (this._internalAbstractMeshDataInfo._facetData.facetDataEnabled) {\n this.disableFacetData();\n }\n this._uniformBuffer.dispose();\n this.onAfterWorldMatrixUpdateObservable.clear();\n this.onCollideObservable.clear();\n this.onCollisionPositionChangeObservable.clear();\n this.onRebuildObservable.clear();\n super.dispose(doNotRecurse, disposeMaterialAndTextures);\n }\n /**\n * Adds the passed mesh as a child to the current mesh\n * @param mesh defines the child mesh\n * @param preserveScalingSign if true, keep scaling sign of child. Otherwise, scaling sign might change.\n * @returns the current mesh\n */\n addChild(mesh, preserveScalingSign = false) {\n mesh.setParent(this, preserveScalingSign);\n return this;\n }\n /**\n * Removes the passed mesh from the current mesh children list\n * @param mesh defines the child mesh\n * @param preserveScalingSign if true, keep scaling sign of child. Otherwise, scaling sign might change.\n * @returns the current mesh\n */\n removeChild(mesh, preserveScalingSign = false) {\n mesh.setParent(null, preserveScalingSign);\n return this;\n }\n // Facet data\n /** @internal */\n _initFacetData() {\n const data = this._internalAbstractMeshDataInfo._facetData;\n if (!data.facetNormals) {\n data.facetNormals = new Array();\n }\n if (!data.facetPositions) {\n data.facetPositions = new Array();\n }\n if (!data.facetPartitioning) {\n data.facetPartitioning = new Array();\n }\n data.facetNb = (this.getIndices().length / 3) | 0;\n data.partitioningSubdivisions = data.partitioningSubdivisions ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10\n data.partitioningBBoxRatio = data.partitioningBBoxRatio ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box\n for (let f = 0; f < data.facetNb; f++) {\n data.facetNormals[f] = Vector3.Zero();\n data.facetPositions[f] = Vector3.Zero();\n }\n data.facetDataEnabled = true;\n return this;\n }\n /**\n * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.\n * This method can be called within the render loop.\n * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation\n * @returns the current mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData\n */\n updateFacetData() {\n const data = this._internalAbstractMeshDataInfo._facetData;\n if (!data.facetDataEnabled) {\n this._initFacetData();\n }\n const positions = this.getVerticesData(VertexBuffer.PositionKind);\n const indices = this.getIndices();\n const normals = this.getVerticesData(VertexBuffer.NormalKind);\n const bInfo = this.getBoundingInfo();\n if (data.facetDepthSort && !data.facetDepthSortEnabled) {\n // init arrays, matrix and sort function on first call\n data.facetDepthSortEnabled = true;\n if (indices instanceof Uint16Array) {\n data.depthSortedIndices = new Uint16Array(indices);\n }\n else if (indices instanceof Uint32Array) {\n data.depthSortedIndices = new Uint32Array(indices);\n }\n else {\n let needs32bits = false;\n for (let i = 0; i < indices.length; i++) {\n if (indices[i] > 65535) {\n needs32bits = true;\n break;\n }\n }\n if (needs32bits) {\n data.depthSortedIndices = new Uint32Array(indices);\n }\n else {\n data.depthSortedIndices = new Uint16Array(indices);\n }\n }\n data.facetDepthSortFunction = function (f1, f2) {\n return f2.sqDistance - f1.sqDistance;\n };\n if (!data.facetDepthSortFrom) {\n const camera = this.getScene().activeCamera;\n data.facetDepthSortFrom = camera ? camera.position : Vector3.Zero();\n }\n data.depthSortedFacets = [];\n for (let f = 0; f < data.facetNb; f++) {\n const depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };\n data.depthSortedFacets.push(depthSortedFacet);\n }\n data.invertedMatrix = Matrix.Identity();\n data.facetDepthSortOrigin = Vector3.Zero();\n }\n data.bbSize.x = bInfo.maximum.x - bInfo.minimum.x > Epsilon ? bInfo.maximum.x - bInfo.minimum.x : Epsilon;\n data.bbSize.y = bInfo.maximum.y - bInfo.minimum.y > Epsilon ? bInfo.maximum.y - bInfo.minimum.y : Epsilon;\n data.bbSize.z = bInfo.maximum.z - bInfo.minimum.z > Epsilon ? bInfo.maximum.z - bInfo.minimum.z : Epsilon;\n let bbSizeMax = data.bbSize.x > data.bbSize.y ? data.bbSize.x : data.bbSize.y;\n bbSizeMax = bbSizeMax > data.bbSize.z ? bbSizeMax : data.bbSize.z;\n data.subDiv.max = data.partitioningSubdivisions;\n data.subDiv.X = Math.floor((data.subDiv.max * data.bbSize.x) / bbSizeMax); // adjust the number of subdivisions per axis\n data.subDiv.Y = Math.floor((data.subDiv.max * data.bbSize.y) / bbSizeMax); // according to each bbox size per axis\n data.subDiv.Z = Math.floor((data.subDiv.max * data.bbSize.z) / bbSizeMax);\n data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision\n data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;\n data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;\n // set the parameters for ComputeNormals()\n data.facetParameters.facetNormals = this.getFacetLocalNormals();\n data.facetParameters.facetPositions = this.getFacetLocalPositions();\n data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();\n data.facetParameters.bInfo = bInfo;\n data.facetParameters.bbSize = data.bbSize;\n data.facetParameters.subDiv = data.subDiv;\n data.facetParameters.ratio = this.partitioningBBoxRatio;\n data.facetParameters.depthSort = data.facetDepthSort;\n if (data.facetDepthSort && data.facetDepthSortEnabled) {\n this.computeWorldMatrix(true);\n this._worldMatrix.invertToRef(data.invertedMatrix);\n Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);\n data.facetParameters.distanceTo = data.facetDepthSortOrigin;\n }\n data.facetParameters.depthSortedFacets = data.depthSortedFacets;\n if (normals) {\n VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);\n }\n if (data.facetDepthSort && data.facetDepthSortEnabled) {\n data.depthSortedFacets.sort(data.facetDepthSortFunction);\n const l = (data.depthSortedIndices.length / 3) | 0;\n for (let f = 0; f < l; f++) {\n const sind = data.depthSortedFacets[f].ind;\n data.depthSortedIndices[f * 3] = indices[sind];\n data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];\n data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];\n }\n this.updateIndices(data.depthSortedIndices, undefined, true);\n }\n return this;\n }\n /**\n * Returns the facetLocalNormals array.\n * The normals are expressed in the mesh local spac\n * @returns an array of Vector3\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData\n */\n getFacetLocalNormals() {\n const facetData = this._internalAbstractMeshDataInfo._facetData;\n if (!facetData.facetNormals) {\n this.updateFacetData();\n }\n return facetData.facetNormals;\n }\n /**\n * Returns the facetLocalPositions array.\n * The facet positions are expressed in the mesh local space\n * @returns an array of Vector3\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData\n */\n getFacetLocalPositions() {\n const facetData = this._internalAbstractMeshDataInfo._facetData;\n if (!facetData.facetPositions) {\n this.updateFacetData();\n }\n return facetData.facetPositions;\n }\n /**\n * Returns the facetLocalPartitioning array\n * @returns an array of array of numbers\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData\n */\n getFacetLocalPartitioning() {\n const facetData = this._internalAbstractMeshDataInfo._facetData;\n if (!facetData.facetPartitioning) {\n this.updateFacetData();\n }\n return facetData.facetPartitioning;\n }\n /**\n * Returns the i-th facet position in the world system.\n * This method allocates a new Vector3 per call\n * @param i defines the facet index\n * @returns a new Vector3\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData\n */\n getFacetPosition(i) {\n const pos = Vector3.Zero();\n this.getFacetPositionToRef(i, pos);\n return pos;\n }\n /**\n * Sets the reference Vector3 with the i-th facet position in the world system\n * @param i defines the facet index\n * @param ref defines the target vector\n * @returns the current mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData\n */\n getFacetPositionToRef(i, ref) {\n const localPos = this.getFacetLocalPositions()[i];\n const world = this.getWorldMatrix();\n Vector3.TransformCoordinatesToRef(localPos, world, ref);\n return this;\n }\n /**\n * Returns the i-th facet normal in the world system.\n * This method allocates a new Vector3 per call\n * @param i defines the facet index\n * @returns a new Vector3\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData\n */\n getFacetNormal(i) {\n const norm = Vector3.Zero();\n this.getFacetNormalToRef(i, norm);\n return norm;\n }\n /**\n * Sets the reference Vector3 with the i-th facet normal in the world system\n * @param i defines the facet index\n * @param ref defines the target vector\n * @returns the current mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData\n */\n getFacetNormalToRef(i, ref) {\n const localNorm = this.getFacetLocalNormals()[i];\n Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);\n return this;\n }\n /**\n * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system)\n * @param x defines x coordinate\n * @param y defines y coordinate\n * @param z defines z coordinate\n * @returns the array of facet indexes\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData\n */\n getFacetsAtLocalCoordinates(x, y, z) {\n const bInfo = this.getBoundingInfo();\n const data = this._internalAbstractMeshDataInfo._facetData;\n const ox = Math.floor(((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio) / data.bbSize.x);\n const oy = Math.floor(((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio) / data.bbSize.y);\n const oz = Math.floor(((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio) / data.bbSize.z);\n if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {\n return null;\n }\n return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];\n }\n /**\n * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found\n * @param x defines x coordinate\n * @param y defines y coordinate\n * @param z defines z coordinate\n * @param projected sets as the (x,y,z) world projection on the facet\n * @param checkFace if true (default false), only the facet \"facing\" to (x,y,z) or only the ones \"turning their backs\", according to the parameter \"facing\" are returned\n * @param facing if facing and checkFace are true, only the facet \"facing\" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet \"turning their backs\" to (x, y, z) are returned : negative dot (x, y, z) * facet position\n * @returns the face index if found (or null instead)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData\n */\n getClosestFacetAtCoordinates(x, y, z, projected, checkFace = false, facing = true) {\n const world = this.getWorldMatrix();\n const invMat = TmpVectors.Matrix[5];\n world.invertToRef(invMat);\n const invVect = TmpVectors.Vector3[8];\n Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space\n const closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);\n if (projected) {\n // transform the local computed projected vector to world coordinates\n Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);\n }\n return closest;\n }\n /**\n * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found\n * @param x defines x coordinate\n * @param y defines y coordinate\n * @param z defines z coordinate\n * @param projected sets as the (x,y,z) local projection on the facet\n * @param checkFace if true (default false), only the facet \"facing\" to (x,y,z) or only the ones \"turning their backs\", according to the parameter \"facing\" are returned\n * @param facing if facing and checkFace are true, only the facet \"facing\" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet \"turning their backs\" to (x, y, z) are returned : negative dot (x, y, z) * facet position\n * @returns the face index if found (or null instead)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData\n */\n getClosestFacetAtLocalCoordinates(x, y, z, projected, checkFace = false, facing = true) {\n let closest = null;\n let tmpx = 0.0;\n let tmpy = 0.0;\n let tmpz = 0.0;\n let d = 0.0; // tmp dot facet normal * facet position\n let t0 = 0.0;\n let projx = 0.0;\n let projy = 0.0;\n let projz = 0.0;\n // Get all the facets in the same partitioning block than (x, y, z)\n const facetPositions = this.getFacetLocalPositions();\n const facetNormals = this.getFacetLocalNormals();\n const facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);\n if (!facetsInBlock) {\n return null;\n }\n // Get the closest facet to (x, y, z)\n let shortest = Number.MAX_VALUE; // init distance vars\n let tmpDistance = shortest;\n let fib; // current facet in the block\n let norm; // current facet normal\n let p0; // current facet barycenter position\n // loop on all the facets in the current partitioning block\n for (let idx = 0; idx < facetsInBlock.length; idx++) {\n fib = facetsInBlock[idx];\n norm = facetNormals[fib];\n p0 = facetPositions[fib];\n d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;\n if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {\n // compute (x,y,z) projection on the facet = (projx, projy, projz)\n d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;\n t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);\n projx = x + norm.x * t0;\n projy = y + norm.y * t0;\n projz = z + norm.z * t0;\n tmpx = projx - x;\n tmpy = projy - y;\n tmpz = projz - z;\n tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet\n if (tmpDistance < shortest) {\n // just keep the closest facet to (x, y, z)\n shortest = tmpDistance;\n closest = fib;\n if (projected) {\n projected.x = projx;\n projected.y = projy;\n projected.z = projz;\n }\n }\n }\n }\n return closest;\n }\n /**\n * Returns the object \"parameter\" set with all the expected parameters for facetData computation by ComputeNormals()\n * @returns the parameters\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData\n */\n getFacetDataParameters() {\n return this._internalAbstractMeshDataInfo._facetData.facetParameters;\n }\n /**\n * Disables the feature FacetData and frees the related memory\n * @returns the current mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData\n */\n disableFacetData() {\n const facetData = this._internalAbstractMeshDataInfo._facetData;\n if (facetData.facetDataEnabled) {\n facetData.facetDataEnabled = false;\n facetData.facetPositions = new Array();\n facetData.facetNormals = new Array();\n facetData.facetPartitioning = new Array();\n facetData.facetParameters = null;\n facetData.depthSortedIndices = new Uint32Array(0);\n }\n return this;\n }\n /**\n * Updates the AbstractMesh indices array\n * @param indices defines the data source\n * @param offset defines the offset in the index buffer where to store the new data (can be null)\n * @param gpuMemoryOnly defines a boolean indicating that only the GPU memory must be updated leaving the CPU version of the indices unchanged (false by default)\n * @returns the current mesh\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n updateIndices(indices, offset, gpuMemoryOnly = false) {\n return this;\n }\n /**\n * Creates new normals data for the mesh\n * @param updatable defines if the normal vertex buffer must be flagged as updatable\n * @returns the current mesh\n */\n createNormals(updatable) {\n const positions = this.getVerticesData(VertexBuffer.PositionKind);\n const indices = this.getIndices();\n let normals;\n if (this.isVerticesDataPresent(VertexBuffer.NormalKind)) {\n normals = this.getVerticesData(VertexBuffer.NormalKind);\n }\n else {\n normals = [];\n }\n VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });\n this.setVerticesData(VertexBuffer.NormalKind, normals, updatable);\n return this;\n }\n /**\n * Align the mesh with a normal\n * @param normal defines the normal to use\n * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)\n * @returns the current mesh\n */\n alignWithNormal(normal, upDirection) {\n if (!upDirection) {\n upDirection = Axis.Y;\n }\n const axisX = TmpVectors.Vector3[0];\n const axisZ = TmpVectors.Vector3[1];\n Vector3.CrossToRef(upDirection, normal, axisZ);\n Vector3.CrossToRef(normal, axisZ, axisX);\n if (this.rotationQuaternion) {\n Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);\n }\n else {\n Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);\n }\n return this;\n }\n /** @internal */\n _checkOcclusionQuery() {\n // Will be replaced by correct code if Occlusion queries are referenced\n return false;\n }\n /**\n * Disables the mesh edge rendering mode\n * @returns the currentAbstractMesh\n */\n disableEdgesRendering() {\n throw _WarnImport(\"EdgesRenderer\");\n }\n /**\n * Enables the edge rendering mode on the mesh.\n * This mode makes the mesh edges visible\n * @param epsilon defines the maximal distance between two angles to detect a face\n * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces\n * @param options options to the edge renderer\n * @returns the currentAbstractMesh\n * @see https://www.babylonjs-playground.com/#19O9TU#0\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n enableEdgesRendering(epsilon, checkVerticesInsteadOfIndices, options) {\n throw _WarnImport(\"EdgesRenderer\");\n }\n /**\n * This function returns all of the particle systems in the scene that use the mesh as an emitter.\n * @returns an array of particle systems in the scene that use the mesh as an emitter\n */\n getConnectedParticleSystems() {\n return this._scene.particleSystems.filter((particleSystem) => particleSystem.emitter === this);\n }\n}\n/** No occlusion */\nAbstractMesh.OCCLUSION_TYPE_NONE = 0;\n/** Occlusion set to optimistic */\nAbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;\n/** Occlusion set to strict */\nAbstractMesh.OCCLUSION_TYPE_STRICT = 2;\n/** Use an accurate occlusion algorithm */\nAbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;\n/** Use a conservative occlusion algorithm */\nAbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;\n/** Default culling strategy : this is an exclusion test and it's the more accurate.\n * Test order :\n * Is the bounding sphere outside the frustum ?\n * If not, are the bounding box vertices outside the frustum ?\n * It not, then the cullable object is in the frustum.\n */\nAbstractMesh.CULLINGSTRATEGY_STANDARD = 0;\n/** Culling strategy : Bounding Sphere Only.\n * This is an exclusion test. It's faster than the standard strategy because the bounding box is not tested.\n * It's also less accurate than the standard because some not visible objects can still be selected.\n * Test : is the bounding sphere outside the frustum ?\n * If not, then the cullable object is in the frustum.\n */\nAbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;\n/** Culling strategy : Optimistic Inclusion.\n * This in an inclusion test first, then the standard exclusion test.\n * This can be faster when a cullable object is expected to be almost always in the camera frustum.\n * This could also be a little slower than the standard test when the tested object center is not the frustum but one of its bounding box vertex is still inside.\n * Anyway, it's as accurate as the standard strategy.\n * Test :\n * Is the cullable object bounding sphere center in the frustum ?\n * If not, apply the default culling strategy.\n */\nAbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION = 2;\n/** Culling strategy : Optimistic Inclusion then Bounding Sphere Only.\n * This in an inclusion test first, then the bounding sphere only exclusion test.\n * This can be the fastest test when a cullable object is expected to be almost always in the camera frustum.\n * This could also be a little slower than the BoundingSphereOnly strategy when the tested object center is not in the frustum but its bounding sphere still intersects it.\n * It's less accurate than the standard strategy and as accurate as the BoundingSphereOnly strategy.\n * Test :\n * Is the cullable object bounding sphere center in the frustum ?\n * If not, apply the Bounding Sphere Only strategy. No Bounding Box is tested here.\n */\nAbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY = 3;\nRegisterClass(\"BABYLON.AbstractMesh\", AbstractMesh);\n//# sourceMappingURL=abstractMesh.js.map","import { Vector3 } from \"../Maths/math.vector.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { VertexData } from \"../Meshes/mesh.vertexData.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { SubMesh } from \"../Meshes/subMesh.js\";\nimport { SceneLoaderFlags } from \"../Loading/sceneLoaderFlags.js\";\nimport { BoundingInfo } from \"../Culling/boundingInfo.js\";\n\nimport { Tools } from \"../Misc/tools.js\";\nimport { Tags } from \"../Misc/tags.js\";\nimport { extractMinAndMax } from \"../Maths/math.functions.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { CompatibilityOptions } from \"../Compat/compatibilityOptions.js\";\n/**\n * Class used to store geometry data (vertex buffers + index buffer)\n */\nexport class Geometry {\n /**\n * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y\n */\n get boundingBias() {\n return this._boundingBias;\n }\n /**\n * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y\n */\n set boundingBias(value) {\n if (this._boundingBias) {\n this._boundingBias.copyFrom(value);\n }\n else {\n this._boundingBias = value.clone();\n }\n this._updateBoundingInfo(true, null);\n }\n /**\n * Static function used to attach a new empty geometry to a mesh\n * @param mesh defines the mesh to attach the geometry to\n * @returns the new Geometry\n */\n static CreateGeometryForMesh(mesh) {\n const geometry = new Geometry(Geometry.RandomId(), mesh.getScene());\n geometry.applyToMesh(mesh);\n return geometry;\n }\n /** Get the list of meshes using this geometry */\n get meshes() {\n return this._meshes;\n }\n /**\n * Creates a new geometry\n * @param id defines the unique ID\n * @param scene defines the hosting scene\n * @param vertexData defines the VertexData used to get geometry data\n * @param updatable defines if geometry must be updatable (false by default)\n * @param mesh defines the mesh that will be associated with the geometry\n */\n constructor(id, scene, vertexData, updatable = false, mesh = null) {\n /**\n * Gets the delay loading state of the geometry (none by default which means not delayed)\n */\n this.delayLoadState = 0;\n this._totalVertices = 0;\n this._isDisposed = false;\n this._indexBufferIsUpdatable = false;\n this._positionsCache = [];\n /** @internal */\n this._parentContainer = null;\n /**\n * If set to true (false by default), the bounding info applied to the meshes sharing this geometry will be the bounding info defined at the class level\n * and won't be computed based on the vertex positions (which is what we get when useBoundingInfoFromGeometry = false)\n */\n this.useBoundingInfoFromGeometry = false;\n this._scene = scene || EngineStore.LastCreatedScene;\n if (!this._scene) {\n return;\n }\n this.id = id;\n this.uniqueId = this._scene.getUniqueId();\n this._engine = this._scene.getEngine();\n this._meshes = [];\n //Init vertex buffer cache\n this._vertexBuffers = {};\n this._indices = [];\n this._updatable = updatable;\n // vertexData\n if (vertexData) {\n this.setAllVerticesData(vertexData, updatable);\n }\n else {\n this._totalVertices = 0;\n }\n if (this._engine.getCaps().vertexArrayObject) {\n this._vertexArrayObjects = {};\n }\n // applyToMesh\n if (mesh) {\n this.applyToMesh(mesh);\n mesh.computeWorldMatrix(true);\n }\n }\n /**\n * Gets the current extend of the geometry\n */\n get extend() {\n return this._extend;\n }\n /**\n * Gets the hosting scene\n * @returns the hosting Scene\n */\n getScene() {\n return this._scene;\n }\n /**\n * Gets the hosting engine\n * @returns the hosting Engine\n */\n getEngine() {\n return this._engine;\n }\n /**\n * Defines if the geometry is ready to use\n * @returns true if the geometry is ready to be used\n */\n isReady() {\n return this.delayLoadState === 1 || this.delayLoadState === 0;\n }\n /**\n * Gets a value indicating that the geometry should not be serialized\n */\n get doNotSerialize() {\n for (let index = 0; index < this._meshes.length; index++) {\n if (!this._meshes[index].doNotSerialize) {\n return false;\n }\n }\n return true;\n }\n /** @internal */\n _rebuild() {\n if (this._vertexArrayObjects) {\n this._vertexArrayObjects = {};\n }\n // Index buffer\n if (this._meshes.length !== 0 && this._indices) {\n this._indexBuffer = this._engine.createIndexBuffer(this._indices, this._updatable);\n }\n // Vertex buffers\n for (const key in this._vertexBuffers) {\n const vertexBuffer = this._vertexBuffers[key];\n vertexBuffer._rebuild();\n }\n }\n /**\n * Affects all geometry data in one call\n * @param vertexData defines the geometry data\n * @param updatable defines if the geometry must be flagged as updatable (false as default)\n */\n setAllVerticesData(vertexData, updatable) {\n vertexData.applyToGeometry(this, updatable);\n this._notifyUpdate();\n }\n /**\n * Set specific vertex data\n * @param kind defines the data kind (Position, normal, etc...)\n * @param data defines the vertex data to use\n * @param updatable defines if the vertex must be flagged as updatable (false as default)\n * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified\n */\n setVerticesData(kind, data, updatable = false, stride) {\n if (updatable && Array.isArray(data)) {\n // to avoid converting to Float32Array at each draw call in engine.updateDynamicVertexBuffer, we make the conversion a single time here\n data = new Float32Array(data);\n }\n const buffer = new VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);\n this.setVerticesBuffer(buffer);\n }\n /**\n * Removes a specific vertex data\n * @param kind defines the data kind (Position, normal, etc...)\n */\n removeVerticesData(kind) {\n if (this._vertexBuffers[kind]) {\n this._vertexBuffers[kind].dispose();\n delete this._vertexBuffers[kind];\n }\n if (this._vertexArrayObjects) {\n this._disposeVertexArrayObjects();\n }\n }\n /**\n * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data\n * @param buffer defines the vertex buffer to use\n * @param totalVertices defines the total number of vertices for position kind (could be null)\n * @param disposeExistingBuffer disposes the existing buffer, if any (default: true)\n */\n setVerticesBuffer(buffer, totalVertices = null, disposeExistingBuffer = true) {\n const kind = buffer.getKind();\n if (this._vertexBuffers[kind] && disposeExistingBuffer) {\n this._vertexBuffers[kind].dispose();\n }\n if (buffer._buffer) {\n buffer._buffer._increaseReferences();\n }\n this._vertexBuffers[kind] = buffer;\n const meshes = this._meshes;\n const numOfMeshes = meshes.length;\n if (kind === VertexBuffer.PositionKind) {\n const data = buffer.getData();\n if (totalVertices != null) {\n this._totalVertices = totalVertices;\n }\n else {\n if (data != null) {\n this._totalVertices = data.length / (buffer.type === VertexBuffer.BYTE ? buffer.byteStride : buffer.byteStride / 4);\n }\n }\n this._updateExtend(data);\n this._resetPointsArrayCache();\n for (let index = 0; index < numOfMeshes; index++) {\n const mesh = meshes[index];\n mesh.buildBoundingInfo(this._extend.minimum, this._extend.maximum);\n mesh._createGlobalSubMesh(mesh.isUnIndexed);\n mesh.computeWorldMatrix(true);\n mesh.synchronizeInstances();\n }\n }\n this._notifyUpdate(kind);\n }\n /**\n * Update a specific vertex buffer\n * This function will directly update the underlying DataBuffer according to the passed numeric array or Float32Array\n * It will do nothing if the buffer is not updatable\n * @param kind defines the data kind (Position, normal, etc...)\n * @param data defines the data to use\n * @param offset defines the offset in the target buffer where to store the data\n * @param useBytes set to true if the offset is in bytes\n */\n updateVerticesDataDirectly(kind, data, offset, useBytes = false) {\n const vertexBuffer = this.getVertexBuffer(kind);\n if (!vertexBuffer) {\n return;\n }\n vertexBuffer.updateDirectly(data, offset, useBytes);\n this._notifyUpdate(kind);\n }\n /**\n * Update a specific vertex buffer\n * This function will create a new buffer if the current one is not updatable\n * @param kind defines the data kind (Position, normal, etc...)\n * @param data defines the data to use\n * @param updateExtends defines if the geometry extends must be recomputed (false by default)\n */\n updateVerticesData(kind, data, updateExtends = false) {\n const vertexBuffer = this.getVertexBuffer(kind);\n if (!vertexBuffer) {\n return;\n }\n vertexBuffer.update(data);\n if (kind === VertexBuffer.PositionKind) {\n this._updateBoundingInfo(updateExtends, data);\n }\n this._notifyUpdate(kind);\n }\n _updateBoundingInfo(updateExtends, data) {\n if (updateExtends) {\n this._updateExtend(data);\n }\n this._resetPointsArrayCache();\n if (updateExtends) {\n const meshes = this._meshes;\n for (const mesh of meshes) {\n if (mesh.hasBoundingInfo) {\n mesh.getBoundingInfo().reConstruct(this._extend.minimum, this._extend.maximum);\n }\n else {\n mesh.buildBoundingInfo(this._extend.minimum, this._extend.maximum);\n }\n const subMeshes = mesh.subMeshes;\n for (const subMesh of subMeshes) {\n subMesh.refreshBoundingInfo();\n }\n }\n }\n }\n /**\n * @internal\n */\n _bind(effect, indexToBind, overrideVertexBuffers, overrideVertexArrayObjects) {\n if (!effect) {\n return;\n }\n if (indexToBind === undefined) {\n indexToBind = this._indexBuffer;\n }\n const vbs = this.getVertexBuffers();\n if (!vbs) {\n return;\n }\n if (indexToBind != this._indexBuffer || (!this._vertexArrayObjects && !overrideVertexArrayObjects)) {\n this._engine.bindBuffers(vbs, indexToBind, effect, overrideVertexBuffers);\n return;\n }\n const vaos = overrideVertexArrayObjects ? overrideVertexArrayObjects : this._vertexArrayObjects;\n // Using VAO\n if (!vaos[effect.key]) {\n vaos[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect, overrideVertexBuffers);\n }\n this._engine.bindVertexArrayObject(vaos[effect.key], indexToBind);\n }\n /**\n * Gets total number of vertices\n * @returns the total number of vertices\n */\n getTotalVertices() {\n if (!this.isReady()) {\n return 0;\n }\n return this._totalVertices;\n }\n /**\n * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.\n * @param kind defines the data kind (Position, normal, etc...)\n * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes\n * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it\n * @returns a float array containing vertex data\n */\n getVerticesData(kind, copyWhenShared, forceCopy) {\n const vertexBuffer = this.getVertexBuffer(kind);\n if (!vertexBuffer) {\n return null;\n }\n return vertexBuffer.getFloatData(this._totalVertices, forceCopy || (copyWhenShared && this._meshes.length !== 1));\n }\n /**\n * Returns a boolean defining if the vertex data for the requested `kind` is updatable\n * @param kind defines the data kind (Position, normal, etc...)\n * @returns true if the vertex buffer with the specified kind is updatable\n */\n isVertexBufferUpdatable(kind) {\n const vb = this._vertexBuffers[kind];\n if (!vb) {\n return false;\n }\n return vb.isUpdatable();\n }\n /**\n * Gets a specific vertex buffer\n * @param kind defines the data kind (Position, normal, etc...)\n * @returns a VertexBuffer\n */\n getVertexBuffer(kind) {\n if (!this.isReady()) {\n return null;\n }\n return this._vertexBuffers[kind];\n }\n /**\n * Returns all vertex buffers\n * @returns an object holding all vertex buffers indexed by kind\n */\n getVertexBuffers() {\n if (!this.isReady()) {\n return null;\n }\n return this._vertexBuffers;\n }\n /**\n * Gets a boolean indicating if specific vertex buffer is present\n * @param kind defines the data kind (Position, normal, etc...)\n * @returns true if data is present\n */\n isVerticesDataPresent(kind) {\n if (!this._vertexBuffers) {\n if (this._delayInfo) {\n return this._delayInfo.indexOf(kind) !== -1;\n }\n return false;\n }\n return this._vertexBuffers[kind] !== undefined;\n }\n /**\n * Gets a list of all attached data kinds (Position, normal, etc...)\n * @returns a list of string containing all kinds\n */\n getVerticesDataKinds() {\n const result = [];\n let kind;\n if (!this._vertexBuffers && this._delayInfo) {\n for (kind in this._delayInfo) {\n result.push(kind);\n }\n }\n else {\n for (kind in this._vertexBuffers) {\n result.push(kind);\n }\n }\n return result;\n }\n /**\n * Update index buffer\n * @param indices defines the indices to store in the index buffer\n * @param offset defines the offset in the target buffer where to store the data\n * @param gpuMemoryOnly defines a boolean indicating that only the GPU memory must be updated leaving the CPU version of the indices unchanged (false by default)\n */\n updateIndices(indices, offset, gpuMemoryOnly = false) {\n if (!this._indexBuffer) {\n return;\n }\n if (!this._indexBufferIsUpdatable) {\n this.setIndices(indices, null, true);\n }\n else {\n const needToUpdateSubMeshes = indices.length !== this._indices.length;\n if (!gpuMemoryOnly) {\n this._indices = indices.slice();\n }\n this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);\n if (needToUpdateSubMeshes) {\n for (const mesh of this._meshes) {\n mesh._createGlobalSubMesh(true);\n }\n }\n }\n }\n /**\n * Creates a new index buffer\n * @param indices defines the indices to store in the index buffer\n * @param totalVertices defines the total number of vertices (could be null)\n * @param updatable defines if the index buffer must be flagged as updatable (false by default)\n */\n setIndices(indices, totalVertices = null, updatable = false) {\n if (this._indexBuffer) {\n this._engine._releaseBuffer(this._indexBuffer);\n }\n this._indices = indices;\n this._indexBufferIsUpdatable = updatable;\n if (this._meshes.length !== 0 && this._indices) {\n this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);\n }\n if (totalVertices != undefined) {\n // including null and undefined\n this._totalVertices = totalVertices;\n }\n for (const mesh of this._meshes) {\n mesh._createGlobalSubMesh(true);\n mesh.synchronizeInstances();\n }\n this._notifyUpdate();\n }\n /**\n * Return the total number of indices\n * @returns the total number of indices\n */\n getTotalIndices() {\n if (!this.isReady()) {\n return 0;\n }\n return this._indices.length;\n }\n /**\n * Gets the index buffer array\n * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes\n * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it\n * @returns the index buffer array\n */\n getIndices(copyWhenShared, forceCopy) {\n if (!this.isReady()) {\n return null;\n }\n const orig = this._indices;\n if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {\n return orig;\n }\n else {\n return orig.slice();\n }\n }\n /**\n * Gets the index buffer\n * @returns the index buffer\n */\n getIndexBuffer() {\n if (!this.isReady()) {\n return null;\n }\n return this._indexBuffer;\n }\n /**\n * @internal\n */\n _releaseVertexArrayObject(effect = null) {\n if (!effect || !this._vertexArrayObjects) {\n return;\n }\n if (this._vertexArrayObjects[effect.key]) {\n this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);\n delete this._vertexArrayObjects[effect.key];\n }\n }\n /**\n * Release the associated resources for a specific mesh\n * @param mesh defines the source mesh\n * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it\n */\n releaseForMesh(mesh, shouldDispose) {\n const meshes = this._meshes;\n const index = meshes.indexOf(mesh);\n if (index === -1) {\n return;\n }\n meshes.splice(index, 1);\n if (this._vertexArrayObjects) {\n mesh._invalidateInstanceVertexArrayObject();\n }\n mesh._geometry = null;\n if (meshes.length === 0 && shouldDispose) {\n this.dispose();\n }\n }\n /**\n * Apply current geometry to a given mesh\n * @param mesh defines the mesh to apply geometry to\n */\n applyToMesh(mesh) {\n if (mesh._geometry === this) {\n return;\n }\n const previousGeometry = mesh._geometry;\n if (previousGeometry) {\n previousGeometry.releaseForMesh(mesh);\n }\n if (this._vertexArrayObjects) {\n mesh._invalidateInstanceVertexArrayObject();\n }\n const meshes = this._meshes;\n // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()\n mesh._geometry = this;\n mesh._internalAbstractMeshDataInfo._positions = null;\n this._scene.pushGeometry(this);\n meshes.push(mesh);\n if (this.isReady()) {\n this._applyToMesh(mesh);\n }\n else if (this._boundingInfo) {\n mesh.setBoundingInfo(this._boundingInfo);\n }\n }\n _updateExtend(data = null) {\n if (this.useBoundingInfoFromGeometry && this._boundingInfo) {\n this._extend = {\n minimum: this._boundingInfo.minimum.clone(),\n maximum: this._boundingInfo.maximum.clone(),\n };\n }\n else {\n if (!data) {\n data = this.getVerticesData(VertexBuffer.PositionKind);\n // This can happen if the buffer comes from a Hardware Buffer where\n // The data have not been uploaded by Babylon. (ex: Compute Shaders and Storage Buffers)\n if (!data) {\n return;\n }\n }\n this._extend = extractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);\n }\n }\n _applyToMesh(mesh) {\n const numOfMeshes = this._meshes.length;\n // vertexBuffers\n for (const kind in this._vertexBuffers) {\n if (numOfMeshes === 1) {\n this._vertexBuffers[kind].create();\n }\n if (kind === VertexBuffer.PositionKind) {\n if (!this._extend) {\n this._updateExtend();\n }\n mesh.buildBoundingInfo(this._extend.minimum, this._extend.maximum);\n mesh._createGlobalSubMesh(mesh.isUnIndexed);\n //bounding info was just created again, world matrix should be applied again.\n mesh._updateBoundingInfo();\n }\n }\n // indexBuffer\n if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {\n this._indexBuffer = this._engine.createIndexBuffer(this._indices, this._updatable);\n }\n // morphTargets\n mesh._syncGeometryWithMorphTargetManager();\n // instances\n mesh.synchronizeInstances();\n }\n _notifyUpdate(kind) {\n if (this.onGeometryUpdated) {\n this.onGeometryUpdated(this, kind);\n }\n if (this._vertexArrayObjects) {\n this._disposeVertexArrayObjects();\n }\n for (const mesh of this._meshes) {\n mesh._markSubMeshesAsAttributesDirty();\n }\n }\n /**\n * Load the geometry if it was flagged as delay loaded\n * @param scene defines the hosting scene\n * @param onLoaded defines a callback called when the geometry is loaded\n */\n load(scene, onLoaded) {\n if (this.delayLoadState === 2) {\n return;\n }\n if (this.isReady()) {\n if (onLoaded) {\n onLoaded();\n }\n return;\n }\n this.delayLoadState = 2;\n this._queueLoad(scene, onLoaded);\n }\n _queueLoad(scene, onLoaded) {\n if (!this.delayLoadingFile) {\n return;\n }\n scene.addPendingData(this);\n scene._loadFile(this.delayLoadingFile, (data) => {\n if (!this._delayLoadingFunction) {\n return;\n }\n this._delayLoadingFunction(JSON.parse(data), this);\n this.delayLoadState = 1;\n this._delayInfo = [];\n scene.removePendingData(this);\n const meshes = this._meshes;\n const numOfMeshes = meshes.length;\n for (let index = 0; index < numOfMeshes; index++) {\n this._applyToMesh(meshes[index]);\n }\n if (onLoaded) {\n onLoaded();\n }\n }, undefined, true);\n }\n /**\n * Invert the geometry to move from a right handed system to a left handed one.\n */\n toLeftHanded() {\n // Flip faces\n const tIndices = this.getIndices(false);\n if (tIndices != null && tIndices.length > 0) {\n for (let i = 0; i < tIndices.length; i += 3) {\n const tTemp = tIndices[i + 0];\n tIndices[i + 0] = tIndices[i + 2];\n tIndices[i + 2] = tTemp;\n }\n this.setIndices(tIndices);\n }\n // Negate position.z\n const tPositions = this.getVerticesData(VertexBuffer.PositionKind, false);\n if (tPositions != null && tPositions.length > 0) {\n for (let i = 0; i < tPositions.length; i += 3) {\n tPositions[i + 2] = -tPositions[i + 2];\n }\n this.setVerticesData(VertexBuffer.PositionKind, tPositions, false);\n }\n // Negate normal.z\n const tNormals = this.getVerticesData(VertexBuffer.NormalKind, false);\n if (tNormals != null && tNormals.length > 0) {\n for (let i = 0; i < tNormals.length; i += 3) {\n tNormals[i + 2] = -tNormals[i + 2];\n }\n this.setVerticesData(VertexBuffer.NormalKind, tNormals, false);\n }\n }\n // Cache\n /** @internal */\n _resetPointsArrayCache() {\n this._positions = null;\n }\n /** @internal */\n _generatePointsArray() {\n if (this._positions) {\n return true;\n }\n const data = this.getVerticesData(VertexBuffer.PositionKind);\n if (!data || data.length === 0) {\n return false;\n }\n for (let index = this._positionsCache.length * 3, arrayIdx = this._positionsCache.length; index < data.length; index += 3, ++arrayIdx) {\n this._positionsCache[arrayIdx] = Vector3.FromArray(data, index);\n }\n for (let index = 0, arrayIdx = 0; index < data.length; index += 3, ++arrayIdx) {\n this._positionsCache[arrayIdx].set(data[0 + index], data[1 + index], data[2 + index]);\n }\n // just in case the number of positions was reduced, splice the array\n this._positionsCache.length = data.length / 3;\n this._positions = this._positionsCache;\n return true;\n }\n /**\n * Gets a value indicating if the geometry is disposed\n * @returns true if the geometry was disposed\n */\n isDisposed() {\n return this._isDisposed;\n }\n _disposeVertexArrayObjects() {\n if (this._vertexArrayObjects) {\n for (const kind in this._vertexArrayObjects) {\n this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);\n }\n this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported\n const meshes = this._meshes;\n const numOfMeshes = meshes.length;\n for (let index = 0; index < numOfMeshes; index++) {\n meshes[index]._invalidateInstanceVertexArrayObject();\n }\n }\n }\n /**\n * Free all associated resources\n */\n dispose() {\n const meshes = this._meshes;\n const numOfMeshes = meshes.length;\n let index;\n for (index = 0; index < numOfMeshes; index++) {\n this.releaseForMesh(meshes[index]);\n }\n this._meshes.length = 0;\n this._disposeVertexArrayObjects();\n for (const kind in this._vertexBuffers) {\n this._vertexBuffers[kind].dispose();\n }\n this._vertexBuffers = {};\n this._totalVertices = 0;\n if (this._indexBuffer) {\n this._engine._releaseBuffer(this._indexBuffer);\n }\n this._indexBuffer = null;\n this._indices = [];\n this.delayLoadState = 0;\n this.delayLoadingFile = null;\n this._delayLoadingFunction = null;\n this._delayInfo = [];\n this._boundingInfo = null;\n this._scene.removeGeometry(this);\n if (this._parentContainer) {\n const index = this._parentContainer.geometries.indexOf(this);\n if (index > -1) {\n this._parentContainer.geometries.splice(index, 1);\n }\n this._parentContainer = null;\n }\n this._isDisposed = true;\n }\n /**\n * Clone the current geometry into a new geometry\n * @param id defines the unique ID of the new geometry\n * @returns a new geometry object\n */\n copy(id) {\n const vertexData = new VertexData();\n vertexData.indices = [];\n const indices = this.getIndices();\n if (indices) {\n for (let index = 0; index < indices.length; index++) {\n vertexData.indices.push(indices[index]);\n }\n }\n let updatable = false;\n let stopChecking = false;\n let kind;\n for (kind in this._vertexBuffers) {\n // using slice() to make a copy of the array and not just reference it\n const data = this.getVerticesData(kind);\n if (data) {\n if (data instanceof Float32Array) {\n vertexData.set(new Float32Array(data), kind);\n }\n else {\n vertexData.set(data.slice(0), kind);\n }\n if (!stopChecking) {\n const vb = this.getVertexBuffer(kind);\n if (vb) {\n updatable = vb.isUpdatable();\n stopChecking = !updatable;\n }\n }\n }\n }\n const geometry = new Geometry(id, this._scene, vertexData, updatable);\n geometry.delayLoadState = this.delayLoadState;\n geometry.delayLoadingFile = this.delayLoadingFile;\n geometry._delayLoadingFunction = this._delayLoadingFunction;\n for (kind in this._delayInfo) {\n geometry._delayInfo = geometry._delayInfo || [];\n geometry._delayInfo.push(kind);\n }\n // Bounding info\n geometry._boundingInfo = new BoundingInfo(this._extend.minimum, this._extend.maximum);\n return geometry;\n }\n /**\n * Serialize the current geometry info (and not the vertices data) into a JSON object\n * @returns a JSON representation of the current geometry data (without the vertices data)\n */\n serialize() {\n const serializationObject = {};\n serializationObject.id = this.id;\n serializationObject.uniqueId = this.uniqueId;\n serializationObject.updatable = this._updatable;\n if (Tags && Tags.HasTags(this)) {\n serializationObject.tags = Tags.GetTags(this);\n }\n return serializationObject;\n }\n _toNumberArray(origin) {\n if (Array.isArray(origin)) {\n return origin;\n }\n else {\n return Array.prototype.slice.call(origin);\n }\n }\n /**\n * Release any memory retained by the cached data on the Geometry.\n *\n * Call this function to reduce memory footprint of the mesh.\n * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)\n */\n clearCachedData() {\n this._indices = [];\n this._resetPointsArrayCache();\n for (const vbName in this._vertexBuffers) {\n if (!Object.prototype.hasOwnProperty.call(this._vertexBuffers, vbName)) {\n continue;\n }\n this._vertexBuffers[vbName]._buffer._data = null;\n }\n }\n /**\n * Serialize all vertices data into a JSON object\n * @returns a JSON representation of the current geometry data\n */\n serializeVerticeData() {\n const serializationObject = this.serialize();\n if (this.isVerticesDataPresent(VertexBuffer.PositionKind)) {\n serializationObject.positions = this._toNumberArray(this.getVerticesData(VertexBuffer.PositionKind));\n if (this.isVertexBufferUpdatable(VertexBuffer.PositionKind)) {\n serializationObject.positions._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(VertexBuffer.NormalKind)) {\n serializationObject.normals = this._toNumberArray(this.getVerticesData(VertexBuffer.NormalKind));\n if (this.isVertexBufferUpdatable(VertexBuffer.NormalKind)) {\n serializationObject.normals._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(VertexBuffer.TangentKind)) {\n serializationObject.tangents = this._toNumberArray(this.getVerticesData(VertexBuffer.TangentKind));\n if (this.isVertexBufferUpdatable(VertexBuffer.TangentKind)) {\n serializationObject.tangents._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(VertexBuffer.UVKind)) {\n serializationObject.uvs = this._toNumberArray(this.getVerticesData(VertexBuffer.UVKind));\n if (this.isVertexBufferUpdatable(VertexBuffer.UVKind)) {\n serializationObject.uvs._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(VertexBuffer.UV2Kind)) {\n serializationObject.uv2s = this._toNumberArray(this.getVerticesData(VertexBuffer.UV2Kind));\n if (this.isVertexBufferUpdatable(VertexBuffer.UV2Kind)) {\n serializationObject.uv2s._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(VertexBuffer.UV3Kind)) {\n serializationObject.uv3s = this._toNumberArray(this.getVerticesData(VertexBuffer.UV3Kind));\n if (this.isVertexBufferUpdatable(VertexBuffer.UV3Kind)) {\n serializationObject.uv3s._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(VertexBuffer.UV4Kind)) {\n serializationObject.uv4s = this._toNumberArray(this.getVerticesData(VertexBuffer.UV4Kind));\n if (this.isVertexBufferUpdatable(VertexBuffer.UV4Kind)) {\n serializationObject.uv4s._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(VertexBuffer.UV5Kind)) {\n serializationObject.uv5s = this._toNumberArray(this.getVerticesData(VertexBuffer.UV5Kind));\n if (this.isVertexBufferUpdatable(VertexBuffer.UV5Kind)) {\n serializationObject.uv5s._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(VertexBuffer.UV6Kind)) {\n serializationObject.uv6s = this._toNumberArray(this.getVerticesData(VertexBuffer.UV6Kind));\n if (this.isVertexBufferUpdatable(VertexBuffer.UV6Kind)) {\n serializationObject.uv6s._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(VertexBuffer.ColorKind)) {\n serializationObject.colors = this._toNumberArray(this.getVerticesData(VertexBuffer.ColorKind));\n if (this.isVertexBufferUpdatable(VertexBuffer.ColorKind)) {\n serializationObject.colors._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) {\n serializationObject.matricesIndices = this._toNumberArray(this.getVerticesData(VertexBuffer.MatricesIndicesKind));\n serializationObject.matricesIndices._isExpanded = true;\n if (this.isVertexBufferUpdatable(VertexBuffer.MatricesIndicesKind)) {\n serializationObject.matricesIndices._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {\n serializationObject.matricesWeights = this._toNumberArray(this.getVerticesData(VertexBuffer.MatricesWeightsKind));\n if (this.isVertexBufferUpdatable(VertexBuffer.MatricesWeightsKind)) {\n serializationObject.matricesWeights._updatable = true;\n }\n }\n serializationObject.indices = this._toNumberArray(this.getIndices());\n return serializationObject;\n }\n // Statics\n /**\n * Extracts a clone of a mesh geometry\n * @param mesh defines the source mesh\n * @param id defines the unique ID of the new geometry object\n * @returns the new geometry object\n */\n static ExtractFromMesh(mesh, id) {\n const geometry = mesh._geometry;\n if (!geometry) {\n return null;\n }\n return geometry.copy(id);\n }\n /**\n * You should now use Tools.RandomId(), this method is still here for legacy reasons.\n * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523\n * Be aware Math.random() could cause collisions, but:\n * \"All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide\"\n * @returns a string containing a new GUID\n */\n static RandomId() {\n return Tools.RandomId();\n }\n static _GetGeometryByLoadedUniqueId(uniqueId, scene) {\n for (let index = 0; index < scene.geometries.length; index++) {\n if (scene.geometries[index]._loadedUniqueId === uniqueId) {\n return scene.geometries[index];\n }\n }\n return null;\n }\n /**\n * @internal\n */\n static _ImportGeometry(parsedGeometry, mesh) {\n const scene = mesh.getScene();\n // Geometry\n const geometryUniqueId = parsedGeometry.geometryUniqueId;\n const geometryId = parsedGeometry.geometryId;\n if (geometryUniqueId || geometryId) {\n const geometry = geometryUniqueId ? this._GetGeometryByLoadedUniqueId(geometryUniqueId, scene) : scene.getGeometryById(geometryId);\n if (geometry) {\n geometry.applyToMesh(mesh);\n }\n }\n else if (parsedGeometry instanceof ArrayBuffer) {\n const binaryInfo = mesh._binaryInfo;\n if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {\n const positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);\n mesh.setVerticesData(VertexBuffer.PositionKind, positionsData, false);\n }\n if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {\n const normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);\n mesh.setVerticesData(VertexBuffer.NormalKind, normalsData, false);\n }\n if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {\n const tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);\n mesh.setVerticesData(VertexBuffer.TangentKind, tangentsData, false);\n }\n if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {\n const uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);\n if (CompatibilityOptions.UseOpenGLOrientationForUV) {\n for (let index = 1; index < uvsData.length; index += 2) {\n uvsData[index] = 1 - uvsData[index];\n }\n }\n mesh.setVerticesData(VertexBuffer.UVKind, uvsData, false);\n }\n if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {\n const uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);\n if (CompatibilityOptions.UseOpenGLOrientationForUV) {\n for (let index = 1; index < uvs2Data.length; index += 2) {\n uvs2Data[index] = 1 - uvs2Data[index];\n }\n }\n mesh.setVerticesData(VertexBuffer.UV2Kind, uvs2Data, false);\n }\n if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {\n const uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);\n if (CompatibilityOptions.UseOpenGLOrientationForUV) {\n for (let index = 1; index < uvs3Data.length; index += 2) {\n uvs3Data[index] = 1 - uvs3Data[index];\n }\n }\n mesh.setVerticesData(VertexBuffer.UV3Kind, uvs3Data, false);\n }\n if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {\n const uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);\n if (CompatibilityOptions.UseOpenGLOrientationForUV) {\n for (let index = 1; index < uvs4Data.length; index += 2) {\n uvs4Data[index] = 1 - uvs4Data[index];\n }\n }\n mesh.setVerticesData(VertexBuffer.UV4Kind, uvs4Data, false);\n }\n if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {\n const uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);\n if (CompatibilityOptions.UseOpenGLOrientationForUV) {\n for (let index = 1; index < uvs5Data.length; index += 2) {\n uvs5Data[index] = 1 - uvs5Data[index];\n }\n }\n mesh.setVerticesData(VertexBuffer.UV5Kind, uvs5Data, false);\n }\n if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {\n const uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);\n if (CompatibilityOptions.UseOpenGLOrientationForUV) {\n for (let index = 1; index < uvs6Data.length; index += 2) {\n uvs6Data[index] = 1 - uvs6Data[index];\n }\n }\n mesh.setVerticesData(VertexBuffer.UV6Kind, uvs6Data, false);\n }\n if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {\n const colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);\n mesh.setVerticesData(VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);\n }\n if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {\n const matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);\n const floatIndices = [];\n for (let i = 0; i < matricesIndicesData.length; i++) {\n const index = matricesIndicesData[i];\n floatIndices.push(index & 0x000000ff);\n floatIndices.push((index & 0x0000ff00) >> 8);\n floatIndices.push((index & 0x00ff0000) >> 16);\n floatIndices.push((index >> 24) & 0xff); // & 0xFF to convert to v + 256 if v < 0\n }\n mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, floatIndices, false);\n }\n if (binaryInfo.matricesIndicesExtraAttrDesc && binaryInfo.matricesIndicesExtraAttrDesc.count > 0) {\n const matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesExtraAttrDesc.offset, binaryInfo.matricesIndicesExtraAttrDesc.count);\n const floatIndices = [];\n for (let i = 0; i < matricesIndicesData.length; i++) {\n const index = matricesIndicesData[i];\n floatIndices.push(index & 0x000000ff);\n floatIndices.push((index & 0x0000ff00) >> 8);\n floatIndices.push((index & 0x00ff0000) >> 16);\n floatIndices.push((index >> 24) & 0xff); // & 0xFF to convert to v + 256 if v < 0\n }\n mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);\n }\n if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {\n const matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);\n mesh.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);\n }\n if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {\n const indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);\n mesh.setIndices(indicesData, null);\n }\n if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {\n const subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);\n mesh.subMeshes = [];\n for (let i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {\n const materialIndex = subMeshesData[i * 5 + 0];\n const verticesStart = subMeshesData[i * 5 + 1];\n const verticesCount = subMeshesData[i * 5 + 2];\n const indexStart = subMeshesData[i * 5 + 3];\n const indexCount = subMeshesData[i * 5 + 4];\n SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);\n }\n }\n }\n else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {\n mesh.setVerticesData(VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);\n mesh.setVerticesData(VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);\n if (parsedGeometry.tangents) {\n mesh.setVerticesData(VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);\n }\n if (parsedGeometry.uvs) {\n mesh.setVerticesData(VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);\n }\n if (parsedGeometry.uvs2) {\n mesh.setVerticesData(VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);\n }\n if (parsedGeometry.uvs3) {\n mesh.setVerticesData(VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);\n }\n if (parsedGeometry.uvs4) {\n mesh.setVerticesData(VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);\n }\n if (parsedGeometry.uvs5) {\n mesh.setVerticesData(VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);\n }\n if (parsedGeometry.uvs6) {\n mesh.setVerticesData(VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);\n }\n if (parsedGeometry.colors) {\n mesh.setVerticesData(VertexBuffer.ColorKind, Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);\n }\n if (parsedGeometry.matricesIndices) {\n if (!parsedGeometry.matricesIndices._isExpanded) {\n const floatIndices = [];\n for (let i = 0; i < parsedGeometry.matricesIndices.length; i++) {\n const matricesIndex = parsedGeometry.matricesIndices[i];\n floatIndices.push(matricesIndex & 0x000000ff);\n floatIndices.push((matricesIndex & 0x0000ff00) >> 8);\n floatIndices.push((matricesIndex & 0x00ff0000) >> 16);\n floatIndices.push((matricesIndex >> 24) & 0xff); // & 0xFF to convert to v + 256 if v < 0\n }\n mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);\n }\n else {\n delete parsedGeometry.matricesIndices._isExpanded;\n mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);\n }\n }\n if (parsedGeometry.matricesIndicesExtra) {\n if (!parsedGeometry.matricesIndicesExtra._isExpanded) {\n const floatIndices = [];\n for (let i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {\n const matricesIndex = parsedGeometry.matricesIndicesExtra[i];\n floatIndices.push(matricesIndex & 0x000000ff);\n floatIndices.push((matricesIndex & 0x0000ff00) >> 8);\n floatIndices.push((matricesIndex & 0x00ff0000) >> 16);\n floatIndices.push((matricesIndex >> 24) & 0xff); // & 0xFF to convert to v + 256 if v < 0\n }\n mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);\n }\n else {\n delete parsedGeometry.matricesIndices._isExpanded;\n mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);\n }\n }\n if (parsedGeometry.matricesWeights) {\n Geometry._CleanMatricesWeights(parsedGeometry, mesh);\n mesh.setVerticesData(VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);\n }\n if (parsedGeometry.matricesWeightsExtra) {\n mesh.setVerticesData(VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);\n }\n mesh.setIndices(parsedGeometry.indices, null);\n }\n // SubMeshes\n if (parsedGeometry.subMeshes) {\n mesh.subMeshes = [];\n for (let subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {\n const parsedSubMesh = parsedGeometry.subMeshes[subIndex];\n SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);\n }\n }\n // Flat shading\n if (mesh._shouldGenerateFlatShading) {\n mesh.convertToFlatShadedMesh();\n mesh._shouldGenerateFlatShading = false;\n }\n // Update\n mesh.computeWorldMatrix(true);\n scene.onMeshImportedObservable.notifyObservers(mesh);\n }\n static _CleanMatricesWeights(parsedGeometry, mesh) {\n const epsilon = 1e-3;\n if (!SceneLoaderFlags.CleanBoneMatrixWeights) {\n return;\n }\n let noInfluenceBoneIndex = 0.0;\n if (parsedGeometry.skeletonId > -1) {\n const skeleton = mesh.getScene().getLastSkeletonById(parsedGeometry.skeletonId);\n if (!skeleton) {\n return;\n }\n noInfluenceBoneIndex = skeleton.bones.length;\n }\n else {\n return;\n }\n const matricesIndices = mesh.getVerticesData(VertexBuffer.MatricesIndicesKind);\n const matricesIndicesExtra = mesh.getVerticesData(VertexBuffer.MatricesIndicesExtraKind);\n const matricesWeights = parsedGeometry.matricesWeights;\n const matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;\n const influencers = parsedGeometry.numBoneInfluencer;\n const size = matricesWeights.length;\n for (let i = 0; i < size; i += 4) {\n let weight = 0.0;\n let firstZeroWeight = -1;\n for (let j = 0; j < 4; j++) {\n const w = matricesWeights[i + j];\n weight += w;\n if (w < epsilon && firstZeroWeight < 0) {\n firstZeroWeight = j;\n }\n }\n if (matricesWeightsExtra) {\n for (let j = 0; j < 4; j++) {\n const w = matricesWeightsExtra[i + j];\n weight += w;\n if (w < epsilon && firstZeroWeight < 0) {\n firstZeroWeight = j + 4;\n }\n }\n }\n if (firstZeroWeight < 0 || firstZeroWeight > influencers - 1) {\n firstZeroWeight = influencers - 1;\n }\n if (weight > epsilon) {\n const mweight = 1.0 / weight;\n for (let j = 0; j < 4; j++) {\n matricesWeights[i + j] *= mweight;\n }\n if (matricesWeightsExtra) {\n for (let j = 0; j < 4; j++) {\n matricesWeightsExtra[i + j] *= mweight;\n }\n }\n }\n else {\n if (firstZeroWeight >= 4) {\n matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;\n matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;\n }\n else {\n matricesWeights[i + firstZeroWeight] = 1.0 - weight;\n matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;\n }\n }\n }\n mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, matricesIndices);\n if (parsedGeometry.matricesWeightsExtra) {\n mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);\n }\n }\n /**\n * Create a new geometry from persisted data (Using .babylon file format)\n * @param parsedVertexData defines the persisted data\n * @param scene defines the hosting scene\n * @param rootUrl defines the root url to use to load assets (like delayed data)\n * @returns the new geometry object\n */\n static Parse(parsedVertexData, scene, rootUrl) {\n const geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);\n geometry._loadedUniqueId = parsedVertexData.uniqueId;\n if (Tags) {\n Tags.AddTagsTo(geometry, parsedVertexData.tags);\n }\n if (parsedVertexData.delayLoadingFile) {\n geometry.delayLoadState = 4;\n geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;\n geometry._boundingInfo = new BoundingInfo(Vector3.FromArray(parsedVertexData.boundingBoxMinimum), Vector3.FromArray(parsedVertexData.boundingBoxMaximum));\n geometry._delayInfo = [];\n if (parsedVertexData.hasUVs) {\n geometry._delayInfo.push(VertexBuffer.UVKind);\n }\n if (parsedVertexData.hasUVs2) {\n geometry._delayInfo.push(VertexBuffer.UV2Kind);\n }\n if (parsedVertexData.hasUVs3) {\n geometry._delayInfo.push(VertexBuffer.UV3Kind);\n }\n if (parsedVertexData.hasUVs4) {\n geometry._delayInfo.push(VertexBuffer.UV4Kind);\n }\n if (parsedVertexData.hasUVs5) {\n geometry._delayInfo.push(VertexBuffer.UV5Kind);\n }\n if (parsedVertexData.hasUVs6) {\n geometry._delayInfo.push(VertexBuffer.UV6Kind);\n }\n if (parsedVertexData.hasColors) {\n geometry._delayInfo.push(VertexBuffer.ColorKind);\n }\n if (parsedVertexData.hasMatricesIndices) {\n geometry._delayInfo.push(VertexBuffer.MatricesIndicesKind);\n }\n if (parsedVertexData.hasMatricesWeights) {\n geometry._delayInfo.push(VertexBuffer.MatricesWeightsKind);\n }\n geometry._delayLoadingFunction = VertexData.ImportVertexData;\n }\n else {\n VertexData.ImportVertexData(parsedVertexData, geometry);\n }\n scene.pushGeometry(geometry, true);\n return geometry;\n }\n}\n//# sourceMappingURL=geometry.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { Vector3, Vector4, TmpVectors } from \"../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { _WarnImport } from \"../Misc/devTools.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { nativeOverride } from \"../Misc/decorators.js\";\nimport { makeSyncFunction, runCoroutineSync } from \"../Misc/coroutine.js\";\nimport { RuntimeError, ErrorCodes } from \"../Misc/error.js\";\n/**\n * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance\n */\nexport class VertexData {\n constructor() {\n this._applyTo = makeSyncFunction(this._applyToCoroutine.bind(this));\n }\n /**\n * Uses the passed data array to set the set the values for the specified kind of data\n * @param data a linear array of floating numbers\n * @param kind the type of data that is being set, eg positions, colors etc\n */\n set(data, kind) {\n if (!data.length) {\n Logger.Warn(`Setting vertex data kind '${kind}' with an empty array`);\n }\n switch (kind) {\n case VertexBuffer.PositionKind:\n this.positions = data;\n break;\n case VertexBuffer.NormalKind:\n this.normals = data;\n break;\n case VertexBuffer.TangentKind:\n this.tangents = data;\n break;\n case VertexBuffer.UVKind:\n this.uvs = data;\n break;\n case VertexBuffer.UV2Kind:\n this.uvs2 = data;\n break;\n case VertexBuffer.UV3Kind:\n this.uvs3 = data;\n break;\n case VertexBuffer.UV4Kind:\n this.uvs4 = data;\n break;\n case VertexBuffer.UV5Kind:\n this.uvs5 = data;\n break;\n case VertexBuffer.UV6Kind:\n this.uvs6 = data;\n break;\n case VertexBuffer.ColorKind:\n this.colors = data;\n break;\n case VertexBuffer.MatricesIndicesKind:\n this.matricesIndices = data;\n break;\n case VertexBuffer.MatricesWeightsKind:\n this.matricesWeights = data;\n break;\n case VertexBuffer.MatricesIndicesExtraKind:\n this.matricesIndicesExtra = data;\n break;\n case VertexBuffer.MatricesWeightsExtraKind:\n this.matricesWeightsExtra = data;\n break;\n }\n }\n /**\n * Associates the vertexData to the passed Mesh.\n * Sets it as updatable or not (default `false`)\n * @param mesh the mesh the vertexData is applied to\n * @param updatable when used and having the value true allows new data to update the vertexData\n * @returns the VertexData\n */\n applyToMesh(mesh, updatable) {\n this._applyTo(mesh, updatable, false);\n return this;\n }\n /**\n * Associates the vertexData to the passed Geometry.\n * Sets it as updatable or not (default `false`)\n * @param geometry the geometry the vertexData is applied to\n * @param updatable when used and having the value true allows new data to update the vertexData\n * @returns VertexData\n */\n applyToGeometry(geometry, updatable) {\n this._applyTo(geometry, updatable, false);\n return this;\n }\n /**\n * Updates the associated mesh\n * @param mesh the mesh to be updated\n * @returns VertexData\n */\n updateMesh(mesh) {\n this._update(mesh);\n return this;\n }\n /**\n * Updates the associated geometry\n * @param geometry the geometry to be updated\n * @returns VertexData.\n */\n updateGeometry(geometry) {\n this._update(geometry);\n return this;\n }\n /**\n * @internal\n */\n *_applyToCoroutine(meshOrGeometry, updatable = false, isAsync) {\n if (this.positions) {\n meshOrGeometry.setVerticesData(VertexBuffer.PositionKind, this.positions, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.normals) {\n meshOrGeometry.setVerticesData(VertexBuffer.NormalKind, this.normals, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.tangents) {\n meshOrGeometry.setVerticesData(VertexBuffer.TangentKind, this.tangents, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.uvs) {\n meshOrGeometry.setVerticesData(VertexBuffer.UVKind, this.uvs, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.uvs2) {\n meshOrGeometry.setVerticesData(VertexBuffer.UV2Kind, this.uvs2, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.uvs3) {\n meshOrGeometry.setVerticesData(VertexBuffer.UV3Kind, this.uvs3, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.uvs4) {\n meshOrGeometry.setVerticesData(VertexBuffer.UV4Kind, this.uvs4, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.uvs5) {\n meshOrGeometry.setVerticesData(VertexBuffer.UV5Kind, this.uvs5, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.uvs6) {\n meshOrGeometry.setVerticesData(VertexBuffer.UV6Kind, this.uvs6, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.colors) {\n meshOrGeometry.setVerticesData(VertexBuffer.ColorKind, this.colors, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.matricesIndices) {\n meshOrGeometry.setVerticesData(VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.matricesWeights) {\n meshOrGeometry.setVerticesData(VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.matricesIndicesExtra) {\n meshOrGeometry.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.matricesWeightsExtra) {\n meshOrGeometry.setVerticesData(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.indices) {\n meshOrGeometry.setIndices(this.indices, null, updatable);\n if (isAsync) {\n yield;\n }\n }\n else {\n meshOrGeometry.setIndices([], null);\n }\n return this;\n }\n _update(meshOrGeometry, updateExtends, makeItUnique) {\n if (this.positions) {\n meshOrGeometry.updateVerticesData(VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);\n }\n if (this.normals) {\n meshOrGeometry.updateVerticesData(VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);\n }\n if (this.tangents) {\n meshOrGeometry.updateVerticesData(VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);\n }\n if (this.uvs) {\n meshOrGeometry.updateVerticesData(VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);\n }\n if (this.uvs2) {\n meshOrGeometry.updateVerticesData(VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);\n }\n if (this.uvs3) {\n meshOrGeometry.updateVerticesData(VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);\n }\n if (this.uvs4) {\n meshOrGeometry.updateVerticesData(VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);\n }\n if (this.uvs5) {\n meshOrGeometry.updateVerticesData(VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);\n }\n if (this.uvs6) {\n meshOrGeometry.updateVerticesData(VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);\n }\n if (this.colors) {\n meshOrGeometry.updateVerticesData(VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);\n }\n if (this.matricesIndices) {\n meshOrGeometry.updateVerticesData(VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);\n }\n if (this.matricesWeights) {\n meshOrGeometry.updateVerticesData(VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);\n }\n if (this.matricesIndicesExtra) {\n meshOrGeometry.updateVerticesData(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);\n }\n if (this.matricesWeightsExtra) {\n meshOrGeometry.updateVerticesData(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);\n }\n if (this.indices) {\n meshOrGeometry.setIndices(this.indices, null);\n }\n return this;\n }\n static _TransformVector3Coordinates(coordinates, transformation, offset = 0, length = coordinates.length) {\n const coordinate = TmpVectors.Vector3[0];\n const transformedCoordinate = TmpVectors.Vector3[1];\n for (let index = offset; index < offset + length; index += 3) {\n Vector3.FromArrayToRef(coordinates, index, coordinate);\n Vector3.TransformCoordinatesToRef(coordinate, transformation, transformedCoordinate);\n coordinates[index] = transformedCoordinate.x;\n coordinates[index + 1] = transformedCoordinate.y;\n coordinates[index + 2] = transformedCoordinate.z;\n }\n }\n static _TransformVector3Normals(normals, transformation, offset = 0, length = normals.length) {\n const normal = TmpVectors.Vector3[0];\n const transformedNormal = TmpVectors.Vector3[1];\n for (let index = offset; index < offset + length; index += 3) {\n Vector3.FromArrayToRef(normals, index, normal);\n Vector3.TransformNormalToRef(normal, transformation, transformedNormal);\n normals[index] = transformedNormal.x;\n normals[index + 1] = transformedNormal.y;\n normals[index + 2] = transformedNormal.z;\n }\n }\n static _TransformVector4Normals(normals, transformation, offset = 0, length = normals.length) {\n const normal = TmpVectors.Vector4[0];\n const transformedNormal = TmpVectors.Vector4[1];\n for (let index = offset; index < offset + length; index += 4) {\n Vector4.FromArrayToRef(normals, index, normal);\n Vector4.TransformNormalToRef(normal, transformation, transformedNormal);\n normals[index] = transformedNormal.x;\n normals[index + 1] = transformedNormal.y;\n normals[index + 2] = transformedNormal.z;\n normals[index + 3] = transformedNormal.w;\n }\n }\n static _FlipFaces(indices, offset = 0, length = indices.length) {\n for (let index = offset; index < offset + length; index += 3) {\n const tmp = indices[index + 1];\n indices[index + 1] = indices[index + 2];\n indices[index + 2] = tmp;\n }\n }\n /**\n * Transforms each position and each normal of the vertexData according to the passed Matrix\n * @param matrix the transforming matrix\n * @returns the VertexData\n */\n transform(matrix) {\n const flip = matrix.determinant() < 0;\n if (this.positions) {\n VertexData._TransformVector3Coordinates(this.positions, matrix);\n }\n if (this.normals) {\n VertexData._TransformVector3Normals(this.normals, matrix);\n }\n if (this.tangents) {\n VertexData._TransformVector4Normals(this.tangents, matrix);\n }\n if (flip && this.indices) {\n VertexData._FlipFaces(this.indices);\n }\n return this;\n }\n /**\n * Merges the passed VertexData into the current one\n * @param others the VertexData to be merged into the current one\n * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array\n * @param forceCloneIndices defines a boolean indicating if indices are forced to be cloned\n * @returns the modified VertexData\n */\n merge(others, use32BitsIndices = false, forceCloneIndices = false) {\n const vertexDatas = Array.isArray(others)\n ? others.map((other) => {\n return { vertexData: other };\n })\n : [{ vertexData: others }];\n return runCoroutineSync(this._mergeCoroutine(undefined, vertexDatas, use32BitsIndices, false, forceCloneIndices));\n }\n /**\n * @internal\n */\n *_mergeCoroutine(transform, vertexDatas, use32BitsIndices = false, isAsync, forceCloneIndices) {\n var _a, _b, _c, _d;\n this._validate();\n const others = vertexDatas.map((vertexData) => vertexData.vertexData);\n for (const other of others) {\n other._validate();\n if (!this.normals !== !other.normals ||\n !this.tangents !== !other.tangents ||\n !this.uvs !== !other.uvs ||\n !this.uvs2 !== !other.uvs2 ||\n !this.uvs3 !== !other.uvs3 ||\n !this.uvs4 !== !other.uvs4 ||\n !this.uvs5 !== !other.uvs5 ||\n !this.uvs6 !== !other.uvs6 ||\n !this.colors !== !other.colors ||\n !this.matricesIndices !== !other.matricesIndices ||\n !this.matricesWeights !== !other.matricesWeights ||\n !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||\n !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {\n throw new Error(\"Cannot merge vertex data that do not have the same set of attributes\");\n }\n }\n const totalIndices = others.reduce((indexSum, vertexData) => { var _a, _b; return indexSum + ((_b = (_a = vertexData.indices) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0); }, (_b = (_a = this.indices) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0);\n const sliceIndices = forceCloneIndices || others.some((vertexData) => vertexData.indices === this.indices);\n let indices = sliceIndices ? (_c = this.indices) === null || _c === void 0 ? void 0 : _c.slice() : this.indices;\n if (totalIndices > 0) {\n let indicesOffset = (_d = indices === null || indices === void 0 ? void 0 : indices.length) !== null && _d !== void 0 ? _d : 0;\n if (!indices) {\n indices = new Array(totalIndices);\n }\n if (indices.length !== totalIndices) {\n if (Array.isArray(indices)) {\n indices.length = totalIndices;\n }\n else {\n const temp = use32BitsIndices || indices instanceof Uint32Array ? new Uint32Array(totalIndices) : new Uint16Array(totalIndices);\n temp.set(indices);\n indices = temp;\n }\n if (transform && transform.determinant() < 0) {\n VertexData._FlipFaces(indices, 0, indicesOffset);\n }\n }\n let positionsOffset = this.positions ? this.positions.length / 3 : 0;\n for (const { vertexData: other, transform } of vertexDatas) {\n if (other.indices) {\n for (let index = 0; index < other.indices.length; index++) {\n indices[indicesOffset + index] = other.indices[index] + positionsOffset;\n }\n if (transform && transform.determinant() < 0) {\n VertexData._FlipFaces(indices, indicesOffset, other.indices.length);\n }\n // The call to _validate already checked for positions\n positionsOffset += other.positions.length / 3;\n indicesOffset += other.indices.length;\n if (isAsync) {\n yield;\n }\n }\n }\n }\n this.indices = indices;\n this.positions = VertexData._MergeElement(VertexBuffer.PositionKind, this.positions, transform, vertexDatas.map((other) => [other.vertexData.positions, other.transform]));\n if (isAsync) {\n yield;\n }\n this.normals = VertexData._MergeElement(VertexBuffer.NormalKind, this.normals, transform, vertexDatas.map((other) => [other.vertexData.normals, other.transform]));\n if (isAsync) {\n yield;\n }\n this.tangents = VertexData._MergeElement(VertexBuffer.TangentKind, this.tangents, transform, vertexDatas.map((other) => [other.vertexData.tangents, other.transform]));\n if (isAsync) {\n yield;\n }\n this.uvs = VertexData._MergeElement(VertexBuffer.UVKind, this.uvs, transform, vertexDatas.map((other) => [other.vertexData.uvs, other.transform]));\n if (isAsync) {\n yield;\n }\n this.uvs2 = VertexData._MergeElement(VertexBuffer.UV2Kind, this.uvs2, transform, vertexDatas.map((other) => [other.vertexData.uvs2, other.transform]));\n if (isAsync) {\n yield;\n }\n this.uvs3 = VertexData._MergeElement(VertexBuffer.UV3Kind, this.uvs3, transform, vertexDatas.map((other) => [other.vertexData.uvs3, other.transform]));\n if (isAsync) {\n yield;\n }\n this.uvs4 = VertexData._MergeElement(VertexBuffer.UV4Kind, this.uvs4, transform, vertexDatas.map((other) => [other.vertexData.uvs4, other.transform]));\n if (isAsync) {\n yield;\n }\n this.uvs5 = VertexData._MergeElement(VertexBuffer.UV5Kind, this.uvs5, transform, vertexDatas.map((other) => [other.vertexData.uvs5, other.transform]));\n if (isAsync) {\n yield;\n }\n this.uvs6 = VertexData._MergeElement(VertexBuffer.UV6Kind, this.uvs6, transform, vertexDatas.map((other) => [other.vertexData.uvs6, other.transform]));\n if (isAsync) {\n yield;\n }\n this.colors = VertexData._MergeElement(VertexBuffer.ColorKind, this.colors, transform, vertexDatas.map((other) => [other.vertexData.colors, other.transform]));\n if (isAsync) {\n yield;\n }\n this.matricesIndices = VertexData._MergeElement(VertexBuffer.MatricesIndicesKind, this.matricesIndices, transform, vertexDatas.map((other) => [other.vertexData.matricesIndices, other.transform]));\n if (isAsync) {\n yield;\n }\n this.matricesWeights = VertexData._MergeElement(VertexBuffer.MatricesWeightsKind, this.matricesWeights, transform, vertexDatas.map((other) => [other.vertexData.matricesWeights, other.transform]));\n if (isAsync) {\n yield;\n }\n this.matricesIndicesExtra = VertexData._MergeElement(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, transform, vertexDatas.map((other) => [other.vertexData.matricesIndicesExtra, other.transform]));\n if (isAsync) {\n yield;\n }\n this.matricesWeightsExtra = VertexData._MergeElement(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, transform, vertexDatas.map((other) => [other.vertexData.matricesWeightsExtra, other.transform]));\n return this;\n }\n static _MergeElement(kind, source, transform, others) {\n const nonNullOthers = others.filter((other) => other[0] !== null && other[0] !== undefined);\n // If there is no source to copy and no other non-null sources then skip this element.\n if (!source && nonNullOthers.length == 0) {\n return source;\n }\n if (!source) {\n return this._MergeElement(kind, nonNullOthers[0][0], nonNullOthers[0][1], nonNullOthers.slice(1));\n }\n const len = nonNullOthers.reduce((sumLen, elements) => sumLen + elements[0].length, source.length);\n const transformRange = kind === VertexBuffer.PositionKind\n ? VertexData._TransformVector3Coordinates\n : kind === VertexBuffer.NormalKind\n ? VertexData._TransformVector3Normals\n : kind === VertexBuffer.TangentKind\n ? VertexData._TransformVector4Normals\n : () => { };\n if (source instanceof Float32Array) {\n // use non-loop method when the source is Float32Array\n const ret32 = new Float32Array(len);\n ret32.set(source);\n transform && transformRange(ret32, transform, 0, source.length);\n let offset = source.length;\n for (const [vertexData, transform] of nonNullOthers) {\n ret32.set(vertexData, offset);\n transform && transformRange(ret32, transform, offset, vertexData.length);\n offset += vertexData.length;\n }\n return ret32;\n }\n else {\n // don't use concat as it is super slow, just loop for other cases\n const ret = new Array(len);\n for (let i = 0; i < source.length; i++) {\n ret[i] = source[i];\n }\n transform && transformRange(ret, transform, 0, source.length);\n let offset = source.length;\n for (const [vertexData, transform] of nonNullOthers) {\n for (let i = 0; i < vertexData.length; i++) {\n ret[offset + i] = vertexData[i];\n }\n transform && transformRange(ret, transform, offset, vertexData.length);\n offset += vertexData.length;\n }\n return ret;\n }\n }\n _validate() {\n if (!this.positions) {\n throw new RuntimeError(\"Positions are required\", ErrorCodes.MeshInvalidPositionsError);\n }\n const getElementCount = (kind, values) => {\n const stride = VertexBuffer.DeduceStride(kind);\n if (values.length % stride !== 0) {\n throw new Error(\"The \" + kind + \"s array count must be a multiple of \" + stride);\n }\n return values.length / stride;\n };\n const positionsElementCount = getElementCount(VertexBuffer.PositionKind, this.positions);\n const validateElementCount = (kind, values) => {\n const elementCount = getElementCount(kind, values);\n if (elementCount !== positionsElementCount) {\n throw new Error(\"The \" + kind + \"s element count (\" + elementCount + \") does not match the positions count (\" + positionsElementCount + \")\");\n }\n };\n if (this.normals) {\n validateElementCount(VertexBuffer.NormalKind, this.normals);\n }\n if (this.tangents) {\n validateElementCount(VertexBuffer.TangentKind, this.tangents);\n }\n if (this.uvs) {\n validateElementCount(VertexBuffer.UVKind, this.uvs);\n }\n if (this.uvs2) {\n validateElementCount(VertexBuffer.UV2Kind, this.uvs2);\n }\n if (this.uvs3) {\n validateElementCount(VertexBuffer.UV3Kind, this.uvs3);\n }\n if (this.uvs4) {\n validateElementCount(VertexBuffer.UV4Kind, this.uvs4);\n }\n if (this.uvs5) {\n validateElementCount(VertexBuffer.UV5Kind, this.uvs5);\n }\n if (this.uvs6) {\n validateElementCount(VertexBuffer.UV6Kind, this.uvs6);\n }\n if (this.colors) {\n validateElementCount(VertexBuffer.ColorKind, this.colors);\n }\n if (this.matricesIndices) {\n validateElementCount(VertexBuffer.MatricesIndicesKind, this.matricesIndices);\n }\n if (this.matricesWeights) {\n validateElementCount(VertexBuffer.MatricesWeightsKind, this.matricesWeights);\n }\n if (this.matricesIndicesExtra) {\n validateElementCount(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);\n }\n if (this.matricesWeightsExtra) {\n validateElementCount(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);\n }\n }\n /**\n * Serializes the VertexData\n * @returns a serialized object\n */\n serialize() {\n const serializationObject = {};\n if (this.positions) {\n serializationObject.positions = this.positions;\n }\n if (this.normals) {\n serializationObject.normals = this.normals;\n }\n if (this.tangents) {\n serializationObject.tangents = this.tangents;\n }\n if (this.uvs) {\n serializationObject.uvs = this.uvs;\n }\n if (this.uvs2) {\n serializationObject.uvs2 = this.uvs2;\n }\n if (this.uvs3) {\n serializationObject.uvs3 = this.uvs3;\n }\n if (this.uvs4) {\n serializationObject.uvs4 = this.uvs4;\n }\n if (this.uvs5) {\n serializationObject.uvs5 = this.uvs5;\n }\n if (this.uvs6) {\n serializationObject.uvs6 = this.uvs6;\n }\n if (this.colors) {\n serializationObject.colors = this.colors;\n }\n if (this.matricesIndices) {\n serializationObject.matricesIndices = this.matricesIndices;\n serializationObject.matricesIndices._isExpanded = true;\n }\n if (this.matricesWeights) {\n serializationObject.matricesWeights = this.matricesWeights;\n }\n if (this.matricesIndicesExtra) {\n serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;\n serializationObject.matricesIndicesExtra._isExpanded = true;\n }\n if (this.matricesWeightsExtra) {\n serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;\n }\n serializationObject.indices = this.indices;\n return serializationObject;\n }\n // Statics\n /**\n * Extracts the vertexData from a mesh\n * @param mesh the mesh from which to extract the VertexData\n * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false\n * @param forceCopy indicating that the VertexData must be cloned, optional, default false\n * @returns the object VertexData associated to the passed mesh\n */\n static ExtractFromMesh(mesh, copyWhenShared, forceCopy) {\n return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);\n }\n /**\n * Extracts the vertexData from the geometry\n * @param geometry the geometry from which to extract the VertexData\n * @param copyWhenShared defines if the VertexData must be cloned when the geometry is shared between multiple meshes, optional, default false\n * @param forceCopy indicating that the VertexData must be cloned, optional, default false\n * @returns the object VertexData associated to the passed mesh\n */\n static ExtractFromGeometry(geometry, copyWhenShared, forceCopy) {\n return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);\n }\n static _ExtractFrom(meshOrGeometry, copyWhenShared, forceCopy) {\n const result = new VertexData();\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.PositionKind)) {\n result.positions = meshOrGeometry.getVerticesData(VertexBuffer.PositionKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.NormalKind)) {\n result.normals = meshOrGeometry.getVerticesData(VertexBuffer.NormalKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.TangentKind)) {\n result.tangents = meshOrGeometry.getVerticesData(VertexBuffer.TangentKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UVKind)) {\n result.uvs = meshOrGeometry.getVerticesData(VertexBuffer.UVKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV2Kind)) {\n result.uvs2 = meshOrGeometry.getVerticesData(VertexBuffer.UV2Kind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV3Kind)) {\n result.uvs3 = meshOrGeometry.getVerticesData(VertexBuffer.UV3Kind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV4Kind)) {\n result.uvs4 = meshOrGeometry.getVerticesData(VertexBuffer.UV4Kind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV5Kind)) {\n result.uvs5 = meshOrGeometry.getVerticesData(VertexBuffer.UV5Kind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV6Kind)) {\n result.uvs6 = meshOrGeometry.getVerticesData(VertexBuffer.UV6Kind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.ColorKind)) {\n result.colors = meshOrGeometry.getVerticesData(VertexBuffer.ColorKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) {\n result.matricesIndices = meshOrGeometry.getVerticesData(VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {\n result.matricesWeights = meshOrGeometry.getVerticesData(VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.MatricesIndicesExtraKind)) {\n result.matricesIndicesExtra = meshOrGeometry.getVerticesData(VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.MatricesWeightsExtraKind)) {\n result.matricesWeightsExtra = meshOrGeometry.getVerticesData(VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);\n }\n result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);\n return result;\n }\n /**\n * Creates the VertexData for a Ribbon\n * @param options an object used to set the following optional parameters for the ribbon, required but can be empty\n * * pathArray array of paths, each of which an array of successive Vector3\n * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false\n * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false\n * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false\n * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional\n * * colors a linear array, of length 4 * number of vertices, of custom color values, optional\n * @param options.pathArray\n * @param options.closeArray\n * @param options.closePath\n * @param options.offset\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.invertUV\n * @param options.uvs\n * @param options.colors\n * @returns the VertexData of the ribbon\n * @deprecated use CreateRibbonVertexData instead\n */\n static CreateRibbon(options) {\n throw _WarnImport(\"ribbonBuilder\");\n }\n /**\n * Creates the VertexData for a box\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * size sets the width, height and depth of the box to the value of size, optional default 1\n * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size\n * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size\n * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size\n * * faceUV an array of 6 Vector4 elements used to set different images to each box side\n * * faceColors an array of 6 Color3 elements used to set different colors to each box side\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.size\n * @param options.width\n * @param options.height\n * @param options.depth\n * @param options.faceUV\n * @param options.faceColors\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the box\n * @deprecated Please use CreateBoxVertexData from the BoxBuilder file instead\n */\n static CreateBox(options) {\n throw _WarnImport(\"boxBuilder\");\n }\n /**\n * Creates the VertexData for a tiled box\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * faceTiles sets the pattern, tile size and number of tiles for a face\n * * faceUV an array of 6 Vector4 elements used to set different images to each box side\n * * faceColors an array of 6 Color3 elements used to set different colors to each box side\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * @param options.pattern\n * @param options.width\n * @param options.height\n * @param options.depth\n * @param options.tileSize\n * @param options.tileWidth\n * @param options.tileHeight\n * @param options.alignHorizontal\n * @param options.alignVertical\n * @param options.faceUV\n * @param options.faceColors\n * @param options.sideOrientation\n * @returns the VertexData of the box\n * @deprecated Please use CreateTiledBoxVertexData instead\n */\n static CreateTiledBox(options) {\n throw _WarnImport(\"tiledBoxBuilder\");\n }\n /**\n * Creates the VertexData for a tiled plane\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * pattern a limited pattern arrangement depending on the number\n * * tileSize sets the width, height and depth of the tile to the value of size, optional default 1\n * * tileWidth sets the width (x direction) of the tile, overwrites the width set by size, optional, default size\n * * tileHeight sets the height (y direction) of the tile, overwrites the height set by size, optional, default size\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.pattern\n * @param options.tileSize\n * @param options.tileWidth\n * @param options.tileHeight\n * @param options.size\n * @param options.width\n * @param options.height\n * @param options.alignHorizontal\n * @param options.alignVertical\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the tiled plane\n * @deprecated use CreateTiledPlaneVertexData instead\n */\n static CreateTiledPlane(options) {\n throw _WarnImport(\"tiledPlaneBuilder\");\n }\n /**\n * Creates the VertexData for an ellipsoid, defaults to a sphere\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * segments sets the number of horizontal strips optional, default 32\n * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1\n * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter\n * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter\n * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter\n * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1\n * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.segments\n * @param options.diameter\n * @param options.diameterX\n * @param options.diameterY\n * @param options.diameterZ\n * @param options.arc\n * @param options.slice\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the ellipsoid\n * @deprecated use CreateSphereVertexData instead\n */\n static CreateSphere(options) {\n throw _WarnImport(\"sphereBuilder\");\n }\n /**\n * Creates the VertexData for a cylinder, cone or prism\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * height sets the height (y direction) of the cylinder, optional, default 2\n * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter\n * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter\n * * diameter sets the diameter of the top and bottom of the cone, optional default 1\n * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24\n * * subdivisions` the number of rings along the cylinder height, optional, default 1\n * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1\n * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively\n * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively\n * * hasRings when true makes each subdivision independently treated as a face for faceUV and faceColors, optional, default false\n * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.height\n * @param options.diameterTop\n * @param options.diameterBottom\n * @param options.diameter\n * @param options.tessellation\n * @param options.subdivisions\n * @param options.arc\n * @param options.faceColors\n * @param options.faceUV\n * @param options.hasRings\n * @param options.enclose\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the cylinder, cone or prism\n * @deprecated please use CreateCylinderVertexData instead\n */\n static CreateCylinder(options) {\n throw _WarnImport(\"cylinderBuilder\");\n }\n /**\n * Creates the VertexData for a torus\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * diameter the diameter of the torus, optional default 1\n * * thickness the diameter of the tube forming the torus, optional default 0.5\n * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.diameter\n * @param options.thickness\n * @param options.tessellation\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the torus\n * @deprecated use CreateTorusVertexData instead\n */\n static CreateTorus(options) {\n throw _WarnImport(\"torusBuilder\");\n }\n /**\n * Creates the VertexData of the LineSystem\n * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty\n * - lines an array of lines, each line being an array of successive Vector3\n * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point\n * @param options.lines\n * @param options.colors\n * @returns the VertexData of the LineSystem\n * @deprecated use CreateLineSystemVertexData instead\n */\n static CreateLineSystem(options) {\n throw _WarnImport(\"linesBuilder\");\n }\n /**\n * Create the VertexData for a DashedLines\n * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty\n * - points an array successive Vector3\n * - dashSize the size of the dashes relative to the dash number, optional, default 3\n * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1\n * - dashNb the intended total number of dashes, optional, default 200\n * @param options.points\n * @param options.dashSize\n * @param options.gapSize\n * @param options.dashNb\n * @returns the VertexData for the DashedLines\n * @deprecated use CreateDashedLinesVertexData instead\n */\n static CreateDashedLines(options) {\n throw _WarnImport(\"linesBuilder\");\n }\n /**\n * Creates the VertexData for a Ground\n * @param options an object used to set the following optional parameters for the Ground, required but can be empty\n * - width the width (x direction) of the ground, optional, default 1\n * - height the height (z direction) of the ground, optional, default 1\n * - subdivisions the number of subdivisions per side, optional, default 1\n * @param options.width\n * @param options.height\n * @param options.subdivisions\n * @param options.subdivisionsX\n * @param options.subdivisionsY\n * @returns the VertexData of the Ground\n * @deprecated Please use CreateGroundVertexData instead\n */\n static CreateGround(options) {\n throw _WarnImport(\"groundBuilder\");\n }\n /**\n * Creates the VertexData for a TiledGround by subdividing the ground into tiles\n * @param options an object used to set the following optional parameters for the Ground, required but can be empty\n * * xmin the ground minimum X coordinate, optional, default -1\n * * zmin the ground minimum Z coordinate, optional, default -1\n * * xmax the ground maximum X coordinate, optional, default 1\n * * zmax the ground maximum Z coordinate, optional, default 1\n * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}\n * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}\n * @param options.xmin\n * @param options.zmin\n * @param options.xmax\n * @param options.zmax\n * @param options.subdivisions\n * @param options.subdivisions.w\n * @param options.subdivisions.h\n * @param options.precision\n * @param options.precision.w\n * @param options.precision.h\n * @returns the VertexData of the TiledGround\n * @deprecated use CreateTiledGroundVertexData instead\n */\n static CreateTiledGround(options) {\n throw _WarnImport(\"groundBuilder\");\n }\n /**\n * Creates the VertexData of the Ground designed from a heightmap\n * @param options an object used to set the following parameters for the Ground, required and provided by CreateGroundFromHeightMap\n * * width the width (x direction) of the ground\n * * height the height (z direction) of the ground\n * * subdivisions the number of subdivisions per side\n * * minHeight the minimum altitude on the ground, optional, default 0\n * * maxHeight the maximum altitude on the ground, optional default 1\n * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)\n * * buffer the array holding the image color data\n * * bufferWidth the width of image\n * * bufferHeight the height of image\n * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)\n * @param options.width\n * @param options.height\n * @param options.subdivisions\n * @param options.minHeight\n * @param options.maxHeight\n * @param options.colorFilter\n * @param options.buffer\n * @param options.bufferWidth\n * @param options.bufferHeight\n * @param options.alphaFilter\n * @returns the VertexData of the Ground designed from a heightmap\n * @deprecated use CreateGroundFromHeightMapVertexData instead\n */\n static CreateGroundFromHeightMap(options) {\n throw _WarnImport(\"groundBuilder\");\n }\n /**\n * Creates the VertexData for a Plane\n * @param options an object used to set the following optional parameters for the plane, required but can be empty\n * * size sets the width and height of the plane to the value of size, optional default 1\n * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size\n * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.size\n * @param options.width\n * @param options.height\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the box\n * @deprecated use CreatePlaneVertexData instead\n */\n static CreatePlane(options) {\n throw _WarnImport(\"planeBuilder\");\n }\n /**\n * Creates the VertexData of the Disc or regular Polygon\n * @param options an object used to set the following optional parameters for the disc, required but can be empty\n * * radius the radius of the disc, optional default 0.5\n * * tessellation the number of polygon sides, optional, default 64\n * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.radius\n * @param options.tessellation\n * @param options.arc\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the box\n * @deprecated use CreateDiscVertexData instead\n */\n static CreateDisc(options) {\n throw _WarnImport(\"discBuilder\");\n }\n /**\n * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()\n * All parameters are provided by CreatePolygon as needed\n * @param polygon a mesh built from polygonTriangulation.build()\n * @param sideOrientation takes the values Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively\n * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively\n * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param wrap a boolean, default false, when true and fUVs used texture is wrapped around all sides, when false texture is applied side\n * @returns the VertexData of the Polygon\n * @deprecated use CreatePolygonVertexData instead\n */\n static CreatePolygon(polygon, sideOrientation, fUV, fColors, frontUVs, backUVs, wrap) {\n throw _WarnImport(\"polygonBuilder\");\n }\n /**\n * Creates the VertexData of the IcoSphere\n * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty\n * * radius the radius of the IcoSphere, optional default 1\n * * radiusX allows stretching in the x direction, optional, default radius\n * * radiusY allows stretching in the y direction, optional, default radius\n * * radiusZ allows stretching in the z direction, optional, default radius\n * * flat when true creates a flat shaded mesh, optional, default true\n * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.radius\n * @param options.radiusX\n * @param options.radiusY\n * @param options.radiusZ\n * @param options.flat\n * @param options.subdivisions\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the IcoSphere\n * @deprecated use CreateIcoSphereVertexData instead\n */\n static CreateIcoSphere(options) {\n throw _WarnImport(\"icoSphereBuilder\");\n }\n // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html\n /**\n * Creates the VertexData for a Polyhedron\n * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty\n * * type provided types are:\n * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)\n * * 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)\n * * size the size of the IcoSphere, optional default 1\n * * sizeX allows stretching in the x direction, optional, default size\n * * sizeY allows stretching in the y direction, optional, default size\n * * sizeZ allows stretching in the z direction, optional, default size\n * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor\n * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively\n * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively\n * * flat when true creates a flat shaded mesh, optional, default true\n * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.type\n * @param options.size\n * @param options.sizeX\n * @param options.sizeY\n * @param options.sizeZ\n * @param options.custom\n * @param options.faceUV\n * @param options.faceColors\n * @param options.flat\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the Polyhedron\n * @deprecated use CreatePolyhedronVertexData instead\n */\n static CreatePolyhedron(options) {\n throw _WarnImport(\"polyhedronBuilder\");\n }\n /**\n * Creates the VertexData for a Capsule, inspired from https://github.com/maximeq/three-js-capsule-geometry/blob/master/src/CapsuleBufferGeometry.js\n * @param options an object used to set the following optional parameters for the capsule, required but can be empty\n * @returns the VertexData of the Capsule\n * @deprecated Please use CreateCapsuleVertexData from the capsuleBuilder file instead\n */\n static CreateCapsule(options = {\n orientation: Vector3.Up(),\n subdivisions: 2,\n tessellation: 16,\n height: 1,\n radius: 0.25,\n capSubdivisions: 6,\n }) {\n throw _WarnImport(\"capsuleBuilder\");\n }\n // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473\n /**\n * Creates the VertexData for a TorusKnot\n * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty\n * * radius the radius of the torus knot, optional, default 2\n * * tube the thickness of the tube, optional, default 0.5\n * * radialSegments the number of sides on each tube segments, optional, default 32\n * * tubularSegments the number of tubes to decompose the knot into, optional, default 32\n * * p the number of windings around the z axis, optional, default 2\n * * q the number of windings around the x axis, optional, default 3\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.radius\n * @param options.tube\n * @param options.radialSegments\n * @param options.tubularSegments\n * @param options.p\n * @param options.q\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the Torus Knot\n * @deprecated use CreateTorusKnotVertexData instead\n */\n static CreateTorusKnot(options) {\n throw _WarnImport(\"torusKnotBuilder\");\n }\n // Tools\n /**\n * Compute normals for given positions and indices\n * @param positions an array of vertex positions, [...., x, y, z, ......]\n * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]\n * @param normals an array of vertex normals, [...., x, y, z, ......]\n * @param options an object used to set the following optional parameters for the TorusKnot, optional\n * * facetNormals : optional array of facet normals (vector3)\n * * facetPositions : optional array of facet positions (vector3)\n * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation\n * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation\n * * bInfo : optional bounding info, required for facetPartitioning computation\n * * bbSize : optional bounding box size data, required for facetPartitioning computation\n * * subDiv : optional partitioning data about subdivisions on each axis (int), required for facetPartitioning computation\n * * useRightHandedSystem: optional boolean to for right handed system computation\n * * depthSort : optional boolean to enable the facet depth sort computation\n * * distanceTo : optional Vector3 to compute the facet depth from this location\n * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location\n * @param options.facetNormals\n * @param options.facetPositions\n * @param options.facetPartitioning\n * @param options.ratio\n * @param options.bInfo\n * @param options.bbSize\n * @param options.subDiv\n * @param options.useRightHandedSystem\n * @param options.depthSort\n * @param options.distanceTo\n * @param options.depthSortedFacets\n */\n static ComputeNormals(positions, indices, normals, options) {\n // temporary scalar variables\n let index = 0; // facet index\n let p1p2x = 0.0; // p1p2 vector x coordinate\n let p1p2y = 0.0; // p1p2 vector y coordinate\n let p1p2z = 0.0; // p1p2 vector z coordinate\n let p3p2x = 0.0; // p3p2 vector x coordinate\n let p3p2y = 0.0; // p3p2 vector y coordinate\n let p3p2z = 0.0; // p3p2 vector z coordinate\n let faceNormalx = 0.0; // facet normal x coordinate\n let faceNormaly = 0.0; // facet normal y coordinate\n let faceNormalz = 0.0; // facet normal z coordinate\n let length = 0.0; // facet normal length before normalization\n let v1x = 0; // vector1 x index in the positions array\n let v1y = 0; // vector1 y index in the positions array\n let v1z = 0; // vector1 z index in the positions array\n let v2x = 0; // vector2 x index in the positions array\n let v2y = 0; // vector2 y index in the positions array\n let v2z = 0; // vector2 z index in the positions array\n let v3x = 0; // vector3 x index in the positions array\n let v3y = 0; // vector3 y index in the positions array\n let v3z = 0; // vector3 z index in the positions array\n let computeFacetNormals = false;\n let computeFacetPositions = false;\n let computeFacetPartitioning = false;\n let computeDepthSort = false;\n let faceNormalSign = 1;\n let ratio = 0;\n let distanceTo = null;\n if (options) {\n computeFacetNormals = options.facetNormals ? true : false;\n computeFacetPositions = options.facetPositions ? true : false;\n computeFacetPartitioning = options.facetPartitioning ? true : false;\n faceNormalSign = options.useRightHandedSystem === true ? -1 : 1;\n ratio = options.ratio || 0;\n computeDepthSort = options.depthSort ? true : false;\n distanceTo = options.distanceTo;\n if (computeDepthSort) {\n if (distanceTo === undefined) {\n distanceTo = Vector3.Zero();\n }\n }\n }\n // facetPartitioning reinit if needed\n let xSubRatio = 0;\n let ySubRatio = 0;\n let zSubRatio = 0;\n let subSq = 0;\n if (computeFacetPartitioning && options && options.bbSize) {\n //let bbSizeMax = options.bbSize.x > options.bbSize.y ? options.bbSize.x : options.bbSize.y;\n //bbSizeMax = bbSizeMax > options.bbSize.z ? bbSizeMax : options.bbSize.z;\n xSubRatio = (options.subDiv.X * ratio) / options.bbSize.x;\n ySubRatio = (options.subDiv.Y * ratio) / options.bbSize.y;\n zSubRatio = (options.subDiv.Z * ratio) / options.bbSize.z;\n subSq = options.subDiv.max * options.subDiv.max;\n options.facetPartitioning.length = 0;\n }\n // reset the normals\n for (index = 0; index < positions.length; index++) {\n normals[index] = 0.0;\n }\n // Loop : 1 indice triplet = 1 facet\n const nbFaces = (indices.length / 3) | 0;\n for (index = 0; index < nbFaces; index++) {\n // get the indexes of the coordinates of each vertex of the facet\n v1x = indices[index * 3] * 3;\n v1y = v1x + 1;\n v1z = v1x + 2;\n v2x = indices[index * 3 + 1] * 3;\n v2y = v2x + 1;\n v2z = v2x + 2;\n v3x = indices[index * 3 + 2] * 3;\n v3y = v3x + 1;\n v3z = v3x + 2;\n p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2\n p1p2y = positions[v1y] - positions[v2y];\n p1p2z = positions[v1z] - positions[v2z];\n p3p2x = positions[v3x] - positions[v2x];\n p3p2y = positions[v3y] - positions[v2y];\n p3p2z = positions[v3z] - positions[v2z];\n // compute the face normal with the cross product\n faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);\n faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);\n faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);\n // normalize this normal and store it in the array facetData\n length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);\n length = length === 0 ? 1.0 : length;\n faceNormalx /= length;\n faceNormaly /= length;\n faceNormalz /= length;\n if (computeFacetNormals && options) {\n options.facetNormals[index].x = faceNormalx;\n options.facetNormals[index].y = faceNormaly;\n options.facetNormals[index].z = faceNormalz;\n }\n if (computeFacetPositions && options) {\n // compute and the facet barycenter coordinates in the array facetPositions\n options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;\n options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;\n options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;\n }\n if (computeFacetPartitioning && options) {\n // store the facet indexes in arrays in the main facetPartitioning array :\n // compute each facet vertex (+ facet barycenter) index in the partiniong array\n const ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);\n const oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);\n const oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);\n const b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);\n const b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);\n const b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);\n const b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);\n const b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);\n const b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);\n const b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);\n const b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);\n const b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);\n const block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;\n const block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;\n const block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;\n const block_idx_o = ox + options.subDiv.max * oy + subSq * oz;\n options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();\n options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();\n options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();\n options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();\n // push each facet index in each block containing the vertex\n options.facetPartitioning[block_idx_v1].push(index);\n if (block_idx_v2 != block_idx_v1) {\n options.facetPartitioning[block_idx_v2].push(index);\n }\n if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {\n options.facetPartitioning[block_idx_v3].push(index);\n }\n if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {\n options.facetPartitioning[block_idx_o].push(index);\n }\n }\n if (computeDepthSort && options && options.facetPositions) {\n const dsf = options.depthSortedFacets[index];\n dsf.ind = index * 3;\n dsf.sqDistance = Vector3.DistanceSquared(options.facetPositions[index], distanceTo);\n }\n // compute the normals anyway\n normals[v1x] += faceNormalx; // accumulate all the normals per face\n normals[v1y] += faceNormaly;\n normals[v1z] += faceNormalz;\n normals[v2x] += faceNormalx;\n normals[v2y] += faceNormaly;\n normals[v2z] += faceNormalz;\n normals[v3x] += faceNormalx;\n normals[v3y] += faceNormaly;\n normals[v3z] += faceNormalz;\n }\n // last normalization of each normal\n for (index = 0; index < normals.length / 3; index++) {\n faceNormalx = normals[index * 3];\n faceNormaly = normals[index * 3 + 1];\n faceNormalz = normals[index * 3 + 2];\n length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);\n length = length === 0 ? 1.0 : length;\n faceNormalx /= length;\n faceNormaly /= length;\n faceNormalz /= length;\n normals[index * 3] = faceNormalx;\n normals[index * 3 + 1] = faceNormaly;\n normals[index * 3 + 2] = faceNormalz;\n }\n }\n /**\n * @internal\n */\n static _ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {\n const li = indices.length;\n const ln = normals.length;\n let i;\n let n;\n sideOrientation = sideOrientation || VertexData.DEFAULTSIDE;\n switch (sideOrientation) {\n case VertexData.FRONTSIDE:\n // nothing changed\n break;\n case VertexData.BACKSIDE:\n // indices\n for (i = 0; i < li; i += 3) {\n const tmp = indices[i];\n indices[i] = indices[i + 2];\n indices[i + 2] = tmp;\n }\n // normals\n for (n = 0; n < ln; n++) {\n normals[n] = -normals[n];\n }\n break;\n case VertexData.DOUBLESIDE: {\n // positions\n const lp = positions.length;\n const l = lp / 3;\n for (let p = 0; p < lp; p++) {\n positions[lp + p] = positions[p];\n }\n // indices\n for (i = 0; i < li; i += 3) {\n indices[i + li] = indices[i + 2] + l;\n indices[i + 1 + li] = indices[i + 1] + l;\n indices[i + 2 + li] = indices[i] + l;\n }\n // normals\n for (n = 0; n < ln; n++) {\n normals[ln + n] = -normals[n];\n }\n // uvs\n const lu = uvs.length;\n let u = 0;\n for (u = 0; u < lu; u++) {\n uvs[u + lu] = uvs[u];\n }\n frontUVs = frontUVs ? frontUVs : new Vector4(0.0, 0.0, 1.0, 1.0);\n backUVs = backUVs ? backUVs : new Vector4(0.0, 0.0, 1.0, 1.0);\n u = 0;\n for (i = 0; i < lu / 2; i++) {\n uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];\n uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];\n uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];\n uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];\n u += 2;\n }\n break;\n }\n }\n }\n /**\n * Applies VertexData created from the imported parameters to the geometry\n * @param parsedVertexData the parsed data from an imported file\n * @param geometry the geometry to apply the VertexData to\n */\n static ImportVertexData(parsedVertexData, geometry) {\n const vertexData = new VertexData();\n // positions\n const positions = parsedVertexData.positions;\n if (positions) {\n vertexData.set(positions, VertexBuffer.PositionKind);\n }\n // normals\n const normals = parsedVertexData.normals;\n if (normals) {\n vertexData.set(normals, VertexBuffer.NormalKind);\n }\n // tangents\n const tangents = parsedVertexData.tangents;\n if (tangents) {\n vertexData.set(tangents, VertexBuffer.TangentKind);\n }\n // uvs\n const uvs = parsedVertexData.uvs;\n if (uvs) {\n vertexData.set(uvs, VertexBuffer.UVKind);\n }\n // uv2s\n const uv2s = parsedVertexData.uv2s;\n if (uv2s) {\n vertexData.set(uv2s, VertexBuffer.UV2Kind);\n }\n // uv3s\n const uv3s = parsedVertexData.uv3s;\n if (uv3s) {\n vertexData.set(uv3s, VertexBuffer.UV3Kind);\n }\n // uv4s\n const uv4s = parsedVertexData.uv4s;\n if (uv4s) {\n vertexData.set(uv4s, VertexBuffer.UV4Kind);\n }\n // uv5s\n const uv5s = parsedVertexData.uv5s;\n if (uv5s) {\n vertexData.set(uv5s, VertexBuffer.UV5Kind);\n }\n // uv6s\n const uv6s = parsedVertexData.uv6s;\n if (uv6s) {\n vertexData.set(uv6s, VertexBuffer.UV6Kind);\n }\n // colors\n const colors = parsedVertexData.colors;\n if (colors) {\n vertexData.set(Color4.CheckColors4(colors, positions.length / 3), VertexBuffer.ColorKind);\n }\n // matricesIndices\n const matricesIndices = parsedVertexData.matricesIndices;\n if (matricesIndices) {\n vertexData.set(matricesIndices, VertexBuffer.MatricesIndicesKind);\n }\n // matricesWeights\n const matricesWeights = parsedVertexData.matricesWeights;\n if (matricesWeights) {\n vertexData.set(matricesWeights, VertexBuffer.MatricesWeightsKind);\n }\n // indices\n const indices = parsedVertexData.indices;\n if (indices) {\n vertexData.indices = indices;\n }\n geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);\n }\n}\n/**\n * Mesh side orientation : usually the external or front surface\n */\nVertexData.FRONTSIDE = 0;\n/**\n * Mesh side orientation : usually the internal or back surface\n */\nVertexData.BACKSIDE = 1;\n/**\n * Mesh side orientation : both internal and external or front and back surfaces\n */\nVertexData.DOUBLESIDE = 2;\n/**\n * Mesh side orientation : by default, `FRONTSIDE`\n */\nVertexData.DEFAULTSIDE = 0;\n__decorate([\n nativeOverride.filter((...[coordinates]) => !Array.isArray(coordinates))\n], VertexData, \"_TransformVector3Coordinates\", null);\n__decorate([\n nativeOverride.filter((...[normals]) => !Array.isArray(normals))\n], VertexData, \"_TransformVector3Normals\", null);\n__decorate([\n nativeOverride.filter((...[normals]) => !Array.isArray(normals))\n], VertexData, \"_TransformVector4Normals\", null);\n__decorate([\n nativeOverride.filter((...[indices]) => !Array.isArray(indices))\n], VertexData, \"_FlipFaces\", null);\n//# sourceMappingURL=mesh.vertexData.js.map","/**\n * Class used to represent a specific level of detail of a mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/LOD\n */\nexport class MeshLODLevel {\n /**\n * Creates a new LOD level\n * @param distanceOrScreenCoverage defines either the distance or the screen coverage where this level should start being displayed\n * @param mesh defines the mesh to use to render this level\n */\n constructor(\n /** Either distance from the center of the object to show this level or the screen coverage if `useLODScreenCoverage` is set to `true` on the mesh*/\n distanceOrScreenCoverage, \n /** Defines the mesh to use to render this level */\n mesh) {\n this.distanceOrScreenCoverage = distanceOrScreenCoverage;\n this.mesh = mesh;\n }\n}\n//# sourceMappingURL=meshLODLevel.js.map","import { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { IntersectionInfo } from \"../Collisions/intersectionInfo.js\";\nimport { BoundingInfo } from \"../Culling/boundingInfo.js\";\n\nimport { extractMinAndMaxIndexed } from \"../Maths/math.functions.js\";\nimport { DrawWrapper } from \"../Materials/drawWrapper.js\";\n/**\n * Defines a subdivision inside a mesh\n */\nexport class SubMesh {\n /**\n * Gets material defines used by the effect associated to the sub mesh\n */\n get materialDefines() {\n var _a;\n return this._mainDrawWrapperOverride ? this._mainDrawWrapperOverride.defines : (_a = this._getDrawWrapper()) === null || _a === void 0 ? void 0 : _a.defines;\n }\n /**\n * Sets material defines used by the effect associated to the sub mesh\n */\n set materialDefines(defines) {\n var _a;\n const drawWrapper = (_a = this._mainDrawWrapperOverride) !== null && _a !== void 0 ? _a : this._getDrawWrapper(undefined, true);\n drawWrapper.defines = defines;\n }\n /**\n * @internal\n */\n _getDrawWrapper(passId, createIfNotExisting = false) {\n passId = passId !== null && passId !== void 0 ? passId : this._engine.currentRenderPassId;\n let drawWrapper = this._drawWrappers[passId];\n if (!drawWrapper && createIfNotExisting) {\n this._drawWrappers[passId] = drawWrapper = new DrawWrapper(this._mesh.getScene().getEngine());\n }\n return drawWrapper;\n }\n /**\n * @internal\n */\n _removeDrawWrapper(passId, disposeWrapper = true) {\n var _a;\n if (disposeWrapper) {\n (_a = this._drawWrappers[passId]) === null || _a === void 0 ? void 0 : _a.dispose();\n }\n this._drawWrappers[passId] = undefined;\n }\n /**\n * Gets associated (main) effect (possibly the effect override if defined)\n */\n get effect() {\n var _a, _b;\n return this._mainDrawWrapperOverride ? this._mainDrawWrapperOverride.effect : (_b = (_a = this._getDrawWrapper()) === null || _a === void 0 ? void 0 : _a.effect) !== null && _b !== void 0 ? _b : null;\n }\n /** @internal */\n get _drawWrapper() {\n var _a;\n return (_a = this._mainDrawWrapperOverride) !== null && _a !== void 0 ? _a : this._getDrawWrapper(undefined, true);\n }\n /** @internal */\n get _drawWrapperOverride() {\n return this._mainDrawWrapperOverride;\n }\n /**\n * @internal\n */\n _setMainDrawWrapperOverride(wrapper) {\n this._mainDrawWrapperOverride = wrapper;\n }\n /**\n * Sets associated effect (effect used to render this submesh)\n * @param effect defines the effect to associate with\n * @param defines defines the set of defines used to compile this effect\n * @param materialContext material context associated to the effect\n * @param resetContext true to reset the draw context\n */\n setEffect(effect, defines = null, materialContext, resetContext = true) {\n const drawWrapper = this._drawWrapper;\n drawWrapper.setEffect(effect, defines, resetContext);\n if (materialContext !== undefined) {\n drawWrapper.materialContext = materialContext;\n }\n if (!effect) {\n drawWrapper.defines = null;\n drawWrapper.materialContext = undefined;\n }\n }\n /**\n * Resets the draw wrappers cache\n * @param passId If provided, releases only the draw wrapper corresponding to this render pass id\n */\n resetDrawCache(passId) {\n if (this._drawWrappers) {\n if (passId !== undefined) {\n this._removeDrawWrapper(passId);\n return;\n }\n else {\n for (const drawWrapper of this._drawWrappers) {\n drawWrapper === null || drawWrapper === void 0 ? void 0 : drawWrapper.dispose();\n }\n }\n }\n this._drawWrappers = [];\n }\n /**\n * Add a new submesh to a mesh\n * @param materialIndex defines the material index to use\n * @param verticesStart defines vertex index start\n * @param verticesCount defines vertices count\n * @param indexStart defines index start\n * @param indexCount defines indices count\n * @param mesh defines the parent mesh\n * @param renderingMesh defines an optional rendering mesh\n * @param createBoundingBox defines if bounding box should be created for this submesh\n * @returns the new submesh\n */\n static AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox = true) {\n return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);\n }\n /**\n * Creates a new submesh\n * @param materialIndex defines the material index to use\n * @param verticesStart defines vertex index start\n * @param verticesCount defines vertices count\n * @param indexStart defines index start\n * @param indexCount defines indices count\n * @param mesh defines the parent mesh\n * @param renderingMesh defines an optional rendering mesh\n * @param createBoundingBox defines if bounding box should be created for this submesh\n * @param addToMesh defines a boolean indicating that the submesh must be added to the mesh.subMeshes array (true by default)\n */\n constructor(\n /** the material index to use */\n materialIndex, \n /** vertex index start */\n verticesStart, \n /** vertices count */\n verticesCount, \n /** index start */\n indexStart, \n /** indices count */\n indexCount, mesh, renderingMesh, createBoundingBox = true, addToMesh = true) {\n this.materialIndex = materialIndex;\n this.verticesStart = verticesStart;\n this.verticesCount = verticesCount;\n this.indexStart = indexStart;\n this.indexCount = indexCount;\n this._mainDrawWrapperOverride = null;\n /** @internal */\n this._linesIndexCount = 0;\n this._linesIndexBuffer = null;\n /** @internal */\n this._lastColliderWorldVertices = null;\n /** @internal */\n this._lastColliderTransformMatrix = null;\n /** @internal */\n this._wasDispatched = false;\n /** @internal */\n this._renderId = 0;\n /** @internal */\n this._alphaIndex = 0;\n /** @internal */\n this._distanceToCamera = 0;\n this._currentMaterial = null;\n this._mesh = mesh;\n this._renderingMesh = renderingMesh || mesh;\n if (addToMesh) {\n mesh.subMeshes.push(this);\n }\n this._engine = this._mesh.getScene().getEngine();\n this.resetDrawCache();\n this._trianglePlanes = [];\n this._id = mesh.subMeshes.length - 1;\n if (createBoundingBox) {\n this.refreshBoundingInfo();\n mesh.computeWorldMatrix(true);\n }\n }\n /**\n * Returns true if this submesh covers the entire parent mesh\n * @ignorenaming\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n get IsGlobal() {\n return this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices() && this.indexStart === 0 && this.indexCount === this._mesh.getTotalIndices();\n }\n /**\n * Returns the submesh BoundingInfo object\n * @returns current bounding info (or mesh's one if the submesh is global)\n */\n getBoundingInfo() {\n if (this.IsGlobal) {\n return this._mesh.getBoundingInfo();\n }\n return this._boundingInfo;\n }\n /**\n * Sets the submesh BoundingInfo\n * @param boundingInfo defines the new bounding info to use\n * @returns the SubMesh\n */\n setBoundingInfo(boundingInfo) {\n this._boundingInfo = boundingInfo;\n return this;\n }\n /**\n * Returns the mesh of the current submesh\n * @returns the parent mesh\n */\n getMesh() {\n return this._mesh;\n }\n /**\n * Returns the rendering mesh of the submesh\n * @returns the rendering mesh (could be different from parent mesh)\n */\n getRenderingMesh() {\n return this._renderingMesh;\n }\n /**\n * Returns the replacement mesh of the submesh\n * @returns the replacement mesh (could be different from parent mesh)\n */\n getReplacementMesh() {\n return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : null;\n }\n /**\n * Returns the effective mesh of the submesh\n * @returns the effective mesh (could be different from parent mesh)\n */\n getEffectiveMesh() {\n const replacementMesh = this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : null;\n return replacementMesh ? replacementMesh : this._renderingMesh;\n }\n /**\n * Returns the submesh material\n * @param getDefaultMaterial Defines whether or not to get the default material if nothing has been defined.\n * @returns null or the current material\n */\n getMaterial(getDefaultMaterial = true) {\n var _a;\n const rootMaterial = (_a = this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId)) !== null && _a !== void 0 ? _a : this._renderingMesh.material;\n if (!rootMaterial) {\n return getDefaultMaterial ? this._mesh.getScene().defaultMaterial : null;\n }\n else if (this._isMultiMaterial(rootMaterial)) {\n const effectiveMaterial = rootMaterial.getSubMaterial(this.materialIndex);\n if (this._currentMaterial !== effectiveMaterial) {\n this._currentMaterial = effectiveMaterial;\n this.resetDrawCache();\n }\n return effectiveMaterial;\n }\n return rootMaterial;\n }\n _isMultiMaterial(material) {\n return material.getSubMaterial !== undefined;\n }\n // Methods\n /**\n * Sets a new updated BoundingInfo object to the submesh\n * @param data defines an optional position array to use to determine the bounding info\n * @returns the SubMesh\n */\n refreshBoundingInfo(data = null) {\n this._lastColliderWorldVertices = null;\n if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {\n return this;\n }\n if (!data) {\n data = this._renderingMesh.getVerticesData(VertexBuffer.PositionKind);\n }\n if (!data) {\n this._boundingInfo = this._mesh.getBoundingInfo();\n return this;\n }\n const indices = this._renderingMesh.getIndices();\n let extend;\n //is this the only submesh?\n if (this.indexStart === 0 && this.indexCount === indices.length) {\n const boundingInfo = this._renderingMesh.getBoundingInfo();\n //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.\n extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };\n }\n else {\n extend = extractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);\n }\n if (this._boundingInfo) {\n this._boundingInfo.reConstruct(extend.minimum, extend.maximum);\n }\n else {\n this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);\n }\n return this;\n }\n /**\n * @internal\n */\n _checkCollision(collider) {\n const boundingInfo = this.getBoundingInfo();\n return boundingInfo._checkCollision(collider);\n }\n /**\n * Updates the submesh BoundingInfo\n * @param world defines the world matrix to use to update the bounding info\n * @returns the submesh\n */\n updateBoundingInfo(world) {\n let boundingInfo = this.getBoundingInfo();\n if (!boundingInfo) {\n this.refreshBoundingInfo();\n boundingInfo = this.getBoundingInfo();\n }\n if (boundingInfo) {\n boundingInfo.update(world);\n }\n return this;\n }\n /**\n * True is the submesh bounding box intersects the frustum defined by the passed array of planes.\n * @param frustumPlanes defines the frustum planes\n * @returns true if the submesh is intersecting with the frustum\n */\n isInFrustum(frustumPlanes) {\n const boundingInfo = this.getBoundingInfo();\n if (!boundingInfo) {\n return false;\n }\n return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy);\n }\n /**\n * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes\n * @param frustumPlanes defines the frustum planes\n * @returns true if the submesh is inside the frustum\n */\n isCompletelyInFrustum(frustumPlanes) {\n const boundingInfo = this.getBoundingInfo();\n if (!boundingInfo) {\n return false;\n }\n return boundingInfo.isCompletelyInFrustum(frustumPlanes);\n }\n /**\n * Renders the submesh\n * @param enableAlphaMode defines if alpha needs to be used\n * @returns the submesh\n */\n render(enableAlphaMode) {\n this._renderingMesh.render(this, enableAlphaMode, this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : undefined);\n return this;\n }\n /**\n * @internal\n */\n _getLinesIndexBuffer(indices, engine) {\n if (!this._linesIndexBuffer) {\n const linesIndices = [];\n for (let index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {\n linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);\n }\n this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);\n this._linesIndexCount = linesIndices.length;\n }\n return this._linesIndexBuffer;\n }\n /**\n * Checks if the submesh intersects with a ray\n * @param ray defines the ray to test\n * @returns true is the passed ray intersects the submesh bounding box\n */\n canIntersects(ray) {\n const boundingInfo = this.getBoundingInfo();\n if (!boundingInfo) {\n return false;\n }\n return ray.intersectsBox(boundingInfo.boundingBox);\n }\n /**\n * Intersects current submesh with a ray\n * @param ray defines the ray to test\n * @param positions defines mesh's positions array\n * @param indices defines mesh's indices array\n * @param fastCheck defines if the first intersection will be used (and not the closest)\n * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected\n * @returns intersection info or null if no intersection\n */\n intersects(ray, positions, indices, fastCheck, trianglePredicate) {\n const material = this.getMaterial();\n if (!material) {\n return null;\n }\n let step = 3;\n let checkStopper = false;\n switch (material.fillMode) {\n case 3:\n case 5:\n case 6:\n case 8:\n return null;\n case 7:\n step = 1;\n checkStopper = true;\n break;\n default:\n break;\n }\n // LineMesh first as it's also a Mesh...\n if (material.fillMode === 4) {\n // Check if mesh is unindexed\n if (!indices.length) {\n return this._intersectUnIndexedLines(ray, positions, indices, this._mesh.intersectionThreshold, fastCheck);\n }\n return this._intersectLines(ray, positions, indices, this._mesh.intersectionThreshold, fastCheck);\n }\n else {\n // Check if mesh is unindexed\n if (!indices.length && this._mesh._unIndexed) {\n return this._intersectUnIndexedTriangles(ray, positions, indices, fastCheck, trianglePredicate);\n }\n return this._intersectTriangles(ray, positions, indices, step, checkStopper, fastCheck, trianglePredicate);\n }\n }\n /**\n * @internal\n */\n _intersectLines(ray, positions, indices, intersectionThreshold, fastCheck) {\n let intersectInfo = null;\n // Line test\n for (let index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {\n const p0 = positions[indices[index]];\n const p1 = positions[indices[index + 1]];\n const length = ray.intersectionSegment(p0, p1, intersectionThreshold);\n if (length < 0) {\n continue;\n }\n if (fastCheck || !intersectInfo || length < intersectInfo.distance) {\n intersectInfo = new IntersectionInfo(null, null, length);\n intersectInfo.faceId = index / 2;\n if (fastCheck) {\n break;\n }\n }\n }\n return intersectInfo;\n }\n /**\n * @internal\n */\n _intersectUnIndexedLines(ray, positions, indices, intersectionThreshold, fastCheck) {\n let intersectInfo = null;\n // Line test\n for (let index = this.verticesStart; index < this.verticesStart + this.verticesCount; index += 2) {\n const p0 = positions[index];\n const p1 = positions[index + 1];\n const length = ray.intersectionSegment(p0, p1, intersectionThreshold);\n if (length < 0) {\n continue;\n }\n if (fastCheck || !intersectInfo || length < intersectInfo.distance) {\n intersectInfo = new IntersectionInfo(null, null, length);\n intersectInfo.faceId = index / 2;\n if (fastCheck) {\n break;\n }\n }\n }\n return intersectInfo;\n }\n /**\n * @internal\n */\n _intersectTriangles(ray, positions, indices, step, checkStopper, fastCheck, trianglePredicate) {\n let intersectInfo = null;\n // Triangles test\n let faceId = -1;\n for (let index = this.indexStart; index < this.indexStart + this.indexCount - (3 - step); index += step) {\n faceId++;\n const indexA = indices[index];\n const indexB = indices[index + 1];\n const indexC = indices[index + 2];\n if (checkStopper && indexC === 0xffffffff) {\n index += 2;\n continue;\n }\n const p0 = positions[indexA];\n const p1 = positions[indexB];\n const p2 = positions[indexC];\n // stay defensive and don't check against undefined positions.\n if (!p0 || !p1 || !p2) {\n continue;\n }\n if (trianglePredicate && !trianglePredicate(p0, p1, p2, ray, indexA, indexB, indexC)) {\n continue;\n }\n const currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);\n if (currentIntersectInfo) {\n if (currentIntersectInfo.distance < 0) {\n continue;\n }\n if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {\n intersectInfo = currentIntersectInfo;\n intersectInfo.faceId = faceId;\n if (fastCheck) {\n break;\n }\n }\n }\n }\n return intersectInfo;\n }\n /**\n * @internal\n */\n _intersectUnIndexedTriangles(ray, positions, indices, fastCheck, trianglePredicate) {\n let intersectInfo = null;\n // Triangles test\n for (let index = this.verticesStart; index < this.verticesStart + this.verticesCount; index += 3) {\n const p0 = positions[index];\n const p1 = positions[index + 1];\n const p2 = positions[index + 2];\n if (trianglePredicate && !trianglePredicate(p0, p1, p2, ray, -1, -1, -1)) {\n continue;\n }\n const currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);\n if (currentIntersectInfo) {\n if (currentIntersectInfo.distance < 0) {\n continue;\n }\n if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {\n intersectInfo = currentIntersectInfo;\n intersectInfo.faceId = index / 3;\n if (fastCheck) {\n break;\n }\n }\n }\n }\n return intersectInfo;\n }\n /** @internal */\n _rebuild() {\n if (this._linesIndexBuffer) {\n this._linesIndexBuffer = null;\n }\n }\n // Clone\n /**\n * Creates a new submesh from the passed mesh\n * @param newMesh defines the new hosting mesh\n * @param newRenderingMesh defines an optional rendering mesh\n * @returns the new submesh\n */\n clone(newMesh, newRenderingMesh) {\n const result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);\n if (!this.IsGlobal) {\n const boundingInfo = this.getBoundingInfo();\n if (!boundingInfo) {\n return result;\n }\n result._boundingInfo = new BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);\n }\n return result;\n }\n // Dispose\n /**\n * Release associated resources\n */\n dispose() {\n if (this._linesIndexBuffer) {\n this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);\n this._linesIndexBuffer = null;\n }\n // Remove from mesh\n const index = this._mesh.subMeshes.indexOf(this);\n this._mesh.subMeshes.splice(index, 1);\n this.resetDrawCache();\n }\n /**\n * Gets the class name\n * @returns the string \"SubMesh\".\n */\n getClassName() {\n return \"SubMesh\";\n }\n // Statics\n /**\n * Creates a new submesh from indices data\n * @param materialIndex the index of the main mesh material\n * @param startIndex the index where to start the copy in the mesh indices array\n * @param indexCount the number of indices to copy then from the startIndex\n * @param mesh the main mesh to create the submesh from\n * @param renderingMesh the optional rendering mesh\n * @param createBoundingBox defines if bounding box should be created for this submesh\n * @returns a new submesh\n */\n static CreateFromIndices(materialIndex, startIndex, indexCount, mesh, renderingMesh, createBoundingBox = true) {\n let minVertexIndex = Number.MAX_VALUE;\n let maxVertexIndex = -Number.MAX_VALUE;\n const whatWillRender = renderingMesh || mesh;\n const indices = whatWillRender.getIndices();\n for (let index = startIndex; index < startIndex + indexCount; index++) {\n const vertexIndex = indices[index];\n if (vertexIndex < minVertexIndex) {\n minVertexIndex = vertexIndex;\n }\n if (vertexIndex > maxVertexIndex) {\n maxVertexIndex = vertexIndex;\n }\n }\n return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh, createBoundingBox);\n }\n}\n//# sourceMappingURL=subMesh.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize, serializeAsVector3, serializeAsQuaternion, SerializationHelper } from \"../Misc/decorators.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Quaternion, Matrix, Vector3, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Node } from \"../node.js\";\nimport { Space } from \"../Maths/math.axis.js\";\nconst convertRHSToLHS = Matrix.Compose(Vector3.One(), Quaternion.FromEulerAngles(0, Math.PI, 0), Vector3.Zero());\n/**\n * A TransformNode is an object that is not rendered but can be used as a center of transformation. This can decrease memory usage and increase rendering speed compared to using an empty mesh as a parent and is less complicated than using a pivot matrix.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/parent_pivot/transform_node\n */\nexport class TransformNode extends Node {\n /**\n * Gets or sets the billboard mode. Default is 0.\n *\n * | Value | Type | Description |\n * | --- | --- | --- |\n * | 0 | BILLBOARDMODE_NONE | |\n * | 1 | BILLBOARDMODE_X | |\n * | 2 | BILLBOARDMODE_Y | |\n * | 4 | BILLBOARDMODE_Z | |\n * | 7 | BILLBOARDMODE_ALL | |\n *\n */\n get billboardMode() {\n return this._billboardMode;\n }\n set billboardMode(value) {\n if (this._billboardMode === value) {\n return;\n }\n this._billboardMode = value;\n this._cache.useBillboardPosition = (this._billboardMode & TransformNode.BILLBOARDMODE_USE_POSITION) !== 0;\n this._computeUseBillboardPath();\n }\n /**\n * Gets or sets a boolean indicating that parent rotation should be preserved when using billboards.\n * This could be useful for glTF objects where parent rotation helps converting from right handed to left handed\n */\n get preserveParentRotationForBillboard() {\n return this._preserveParentRotationForBillboard;\n }\n set preserveParentRotationForBillboard(value) {\n if (value === this._preserveParentRotationForBillboard) {\n return;\n }\n this._preserveParentRotationForBillboard = value;\n this._computeUseBillboardPath();\n }\n _computeUseBillboardPath() {\n this._cache.useBillboardPath = this._billboardMode !== TransformNode.BILLBOARDMODE_NONE && !this.preserveParentRotationForBillboard;\n }\n /**\n * Gets or sets the distance of the object to max, often used by skybox\n */\n get infiniteDistance() {\n return this._infiniteDistance;\n }\n set infiniteDistance(value) {\n if (this._infiniteDistance === value) {\n return;\n }\n this._infiniteDistance = value;\n }\n constructor(name, scene = null, isPure = true) {\n super(name, scene);\n this._forward = new Vector3(0, 0, 1);\n this._up = new Vector3(0, 1, 0);\n this._right = new Vector3(1, 0, 0);\n // Properties\n this._position = Vector3.Zero();\n this._rotation = Vector3.Zero();\n this._rotationQuaternion = null;\n this._scaling = Vector3.One();\n this._transformToBoneReferal = null;\n this._isAbsoluteSynced = false;\n this._billboardMode = TransformNode.BILLBOARDMODE_NONE;\n this._preserveParentRotationForBillboard = false;\n /**\n * Multiplication factor on scale x/y/z when computing the world matrix. Eg. for a 1x1x1 cube setting this to 2 will make it a 2x2x2 cube\n */\n this.scalingDeterminant = 1;\n this._infiniteDistance = false;\n /**\n * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.\n * By default the system will update normals to compensate\n */\n this.ignoreNonUniformScaling = false;\n /**\n * Gets or sets a boolean indicating that even if rotationQuaternion is defined, you can keep updating rotation property and Babylon.js will just mix both\n */\n this.reIntegrateRotationIntoRotationQuaternion = false;\n // Cache\n /** @internal */\n this._poseMatrix = null;\n /** @internal */\n this._localMatrix = Matrix.Zero();\n this._usePivotMatrix = false;\n this._absolutePosition = Vector3.Zero();\n this._absoluteScaling = Vector3.Zero();\n this._absoluteRotationQuaternion = Quaternion.Identity();\n this._pivotMatrix = Matrix.Identity();\n /** @internal */\n this._postMultiplyPivotMatrix = false;\n this._isWorldMatrixFrozen = false;\n /** @internal */\n this._indexInSceneTransformNodesArray = -1;\n /**\n * An event triggered after the world matrix is updated\n */\n this.onAfterWorldMatrixUpdateObservable = new Observable();\n this._nonUniformScaling = false;\n if (isPure) {\n this.getScene().addTransformNode(this);\n }\n }\n /**\n * Gets a string identifying the name of the class\n * @returns \"TransformNode\" string\n */\n getClassName() {\n return \"TransformNode\";\n }\n /**\n * Gets or set the node position (default is (0.0, 0.0, 0.0))\n */\n get position() {\n return this._position;\n }\n set position(newPosition) {\n this._position = newPosition;\n this._isDirty = true;\n }\n /**\n * return true if a pivot has been set\n * @returns true if a pivot matrix is used\n */\n isUsingPivotMatrix() {\n return this._usePivotMatrix;\n }\n /**\n * Gets or sets the rotation property : a Vector3 defining the rotation value in radians around each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).\n * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion\n */\n get rotation() {\n return this._rotation;\n }\n set rotation(newRotation) {\n this._rotation = newRotation;\n this._rotationQuaternion = null;\n this._isDirty = true;\n }\n /**\n * Gets or sets the scaling property : a Vector3 defining the node scaling along each local axis X, Y, Z (default is (1.0, 1.0, 1.0)).\n */\n get scaling() {\n return this._scaling;\n }\n set scaling(newScaling) {\n this._scaling = newScaling;\n this._isDirty = true;\n }\n /**\n * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (undefined by default, but can be null).\n * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)\n */\n get rotationQuaternion() {\n return this._rotationQuaternion;\n }\n set rotationQuaternion(quaternion) {\n this._rotationQuaternion = quaternion;\n //reset the rotation vector.\n if (quaternion) {\n this._rotation.setAll(0.0);\n }\n this._isDirty = true;\n }\n /**\n * The forward direction of that transform in world space.\n */\n get forward() {\n Vector3.TransformNormalFromFloatsToRef(0, 0, this.getScene().useRightHandedSystem ? -1.0 : 1.0, this.getWorldMatrix(), this._forward);\n return this._forward.normalize();\n }\n /**\n * The up direction of that transform in world space.\n */\n get up() {\n Vector3.TransformNormalFromFloatsToRef(0, 1, 0, this.getWorldMatrix(), this._up);\n return this._up.normalize();\n }\n /**\n * The right direction of that transform in world space.\n */\n get right() {\n Vector3.TransformNormalFromFloatsToRef(this.getScene().useRightHandedSystem ? -1.0 : 1.0, 0, 0, this.getWorldMatrix(), this._right);\n return this._right.normalize();\n }\n /**\n * Copies the parameter passed Matrix into the mesh Pose matrix.\n * @param matrix the matrix to copy the pose from\n * @returns this TransformNode.\n */\n updatePoseMatrix(matrix) {\n if (!this._poseMatrix) {\n this._poseMatrix = matrix.clone();\n return this;\n }\n this._poseMatrix.copyFrom(matrix);\n return this;\n }\n /**\n * Returns the mesh Pose matrix.\n * @returns the pose matrix\n */\n getPoseMatrix() {\n if (!this._poseMatrix) {\n this._poseMatrix = Matrix.Identity();\n }\n return this._poseMatrix;\n }\n /** @internal */\n _isSynchronized() {\n const cache = this._cache;\n if (this._billboardMode !== cache.billboardMode || this._billboardMode !== TransformNode.BILLBOARDMODE_NONE) {\n return false;\n }\n if (cache.pivotMatrixUpdated) {\n return false;\n }\n if (this._infiniteDistance) {\n return false;\n }\n if (this._position._isDirty) {\n return false;\n }\n if (this._scaling._isDirty) {\n return false;\n }\n if ((this._rotationQuaternion && this._rotationQuaternion._isDirty) || this._rotation._isDirty) {\n return false;\n }\n return true;\n }\n /** @internal */\n _initCache() {\n super._initCache();\n const cache = this._cache;\n cache.localMatrixUpdated = false;\n cache.billboardMode = -1;\n cache.infiniteDistance = false;\n cache.useBillboardPosition = false;\n cache.useBillboardPath = false;\n }\n /**\n * Returns the current mesh absolute position.\n * Returns a Vector3.\n */\n get absolutePosition() {\n return this.getAbsolutePosition();\n }\n /**\n * Returns the current mesh absolute scaling.\n * Returns a Vector3.\n */\n get absoluteScaling() {\n this._syncAbsoluteScalingAndRotation();\n return this._absoluteScaling;\n }\n /**\n * Returns the current mesh absolute rotation.\n * Returns a Quaternion.\n */\n get absoluteRotationQuaternion() {\n this._syncAbsoluteScalingAndRotation();\n return this._absoluteRotationQuaternion;\n }\n /**\n * Sets a new matrix to apply before all other transformation\n * @param matrix defines the transform matrix\n * @returns the current TransformNode\n */\n setPreTransformMatrix(matrix) {\n return this.setPivotMatrix(matrix, false);\n }\n /**\n * Sets a new pivot matrix to the current node\n * @param matrix defines the new pivot matrix to use\n * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect\n * @returns the current TransformNode\n */\n setPivotMatrix(matrix, postMultiplyPivotMatrix = true) {\n this._pivotMatrix.copyFrom(matrix);\n this._usePivotMatrix = !this._pivotMatrix.isIdentity();\n this._cache.pivotMatrixUpdated = true;\n this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;\n if (this._postMultiplyPivotMatrix) {\n if (!this._pivotMatrixInverse) {\n this._pivotMatrixInverse = Matrix.Invert(this._pivotMatrix);\n }\n else {\n this._pivotMatrix.invertToRef(this._pivotMatrixInverse);\n }\n }\n return this;\n }\n /**\n * Returns the mesh pivot matrix.\n * Default : Identity.\n * @returns the matrix\n */\n getPivotMatrix() {\n return this._pivotMatrix;\n }\n /**\n * Instantiate (when possible) or clone that node with its hierarchy\n * @param newParent defines the new parent to use for the instance (or clone)\n * @param options defines options to configure how copy is done\n * @param options.doNotInstantiate defines if the model must be instantiated or just cloned\n * @param onNewNodeCreated defines an option callback to call when a clone or an instance is created\n * @returns an instance (or a clone) of the current node with its hierarchy\n */\n instantiateHierarchy(newParent = null, options, onNewNodeCreated) {\n const clone = this.clone(\"Clone of \" + (this.name || this.id), newParent || this.parent, true);\n if (clone) {\n if (onNewNodeCreated) {\n onNewNodeCreated(this, clone);\n }\n }\n for (const child of this.getChildTransformNodes(true)) {\n child.instantiateHierarchy(clone, options, onNewNodeCreated);\n }\n return clone;\n }\n /**\n * Prevents the World matrix to be computed any longer\n * @param newWorldMatrix defines an optional matrix to use as world matrix\n * @param decompose defines whether to decompose the given newWorldMatrix or directly assign\n * @returns the TransformNode.\n */\n freezeWorldMatrix(newWorldMatrix = null, decompose = false) {\n if (newWorldMatrix) {\n if (decompose) {\n this._rotation.setAll(0);\n this._rotationQuaternion = this._rotationQuaternion || Quaternion.Identity();\n newWorldMatrix.decompose(this._scaling, this._rotationQuaternion, this._position);\n this.computeWorldMatrix(true);\n }\n else {\n this._worldMatrix = newWorldMatrix;\n this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);\n this._afterComputeWorldMatrix();\n }\n }\n else {\n this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily\n this.computeWorldMatrix(true);\n }\n this._isDirty = false;\n this._isWorldMatrixFrozen = true;\n return this;\n }\n /**\n * Allows back the World matrix computation.\n * @returns the TransformNode.\n */\n unfreezeWorldMatrix() {\n this._isWorldMatrixFrozen = false;\n this.computeWorldMatrix(true);\n return this;\n }\n /**\n * True if the World matrix has been frozen.\n */\n get isWorldMatrixFrozen() {\n return this._isWorldMatrixFrozen;\n }\n /**\n * Returns the mesh absolute position in the World.\n * @returns a Vector3.\n */\n getAbsolutePosition() {\n this.computeWorldMatrix();\n return this._absolutePosition;\n }\n /**\n * Sets the mesh absolute position in the World from a Vector3 or an Array(3).\n * @param absolutePosition the absolute position to set\n * @returns the TransformNode.\n */\n setAbsolutePosition(absolutePosition) {\n if (!absolutePosition) {\n return this;\n }\n let absolutePositionX;\n let absolutePositionY;\n let absolutePositionZ;\n if (absolutePosition.x === undefined) {\n if (arguments.length < 3) {\n return this;\n }\n absolutePositionX = arguments[0];\n absolutePositionY = arguments[1];\n absolutePositionZ = arguments[2];\n }\n else {\n absolutePositionX = absolutePosition.x;\n absolutePositionY = absolutePosition.y;\n absolutePositionZ = absolutePosition.z;\n }\n if (this.parent) {\n const invertParentWorldMatrix = TmpVectors.Matrix[0];\n this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix);\n Vector3.TransformCoordinatesFromFloatsToRef(absolutePositionX, absolutePositionY, absolutePositionZ, invertParentWorldMatrix, this.position);\n }\n else {\n this.position.x = absolutePositionX;\n this.position.y = absolutePositionY;\n this.position.z = absolutePositionZ;\n }\n this._absolutePosition.copyFrom(absolutePosition);\n return this;\n }\n /**\n * Sets the mesh position in its local space.\n * @param vector3 the position to set in localspace\n * @returns the TransformNode.\n */\n setPositionWithLocalVector(vector3) {\n this.computeWorldMatrix();\n this.position = Vector3.TransformNormal(vector3, this._localMatrix);\n return this;\n }\n /**\n * Returns the mesh position in the local space from the current World matrix values.\n * @returns a new Vector3.\n */\n getPositionExpressedInLocalSpace() {\n this.computeWorldMatrix();\n const invLocalWorldMatrix = TmpVectors.Matrix[0];\n this._localMatrix.invertToRef(invLocalWorldMatrix);\n return Vector3.TransformNormal(this.position, invLocalWorldMatrix);\n }\n /**\n * Translates the mesh along the passed Vector3 in its local space.\n * @param vector3 the distance to translate in localspace\n * @returns the TransformNode.\n */\n locallyTranslate(vector3) {\n this.computeWorldMatrix(true);\n this.position = Vector3.TransformCoordinates(vector3, this._localMatrix);\n return this;\n }\n /**\n * Orients a mesh towards a target point. Mesh must be drawn facing user.\n * @param targetPoint the position (must be in same space as current mesh) to look at\n * @param yawCor optional yaw (y-axis) correction in radians\n * @param pitchCor optional pitch (x-axis) correction in radians\n * @param rollCor optional roll (z-axis) correction in radians\n * @param space the chosen space of the target\n * @returns the TransformNode.\n */\n lookAt(targetPoint, yawCor = 0, pitchCor = 0, rollCor = 0, space = Space.LOCAL) {\n const dv = TransformNode._LookAtVectorCache;\n const pos = space === Space.LOCAL ? this.position : this.getAbsolutePosition();\n targetPoint.subtractToRef(pos, dv);\n this.setDirection(dv, yawCor, pitchCor, rollCor);\n // Correct for parent's rotation offset\n if (space === Space.WORLD && this.parent) {\n if (this.rotationQuaternion) {\n // Get local rotation matrix of the looking object\n const rotationMatrix = TmpVectors.Matrix[0];\n this.rotationQuaternion.toRotationMatrix(rotationMatrix);\n // Offset rotation by parent's inverted rotation matrix to correct in world space\n const parentRotationMatrix = TmpVectors.Matrix[1];\n this.parent.getWorldMatrix().getRotationMatrixToRef(parentRotationMatrix);\n parentRotationMatrix.invert();\n rotationMatrix.multiplyToRef(parentRotationMatrix, rotationMatrix);\n this.rotationQuaternion.fromRotationMatrix(rotationMatrix);\n }\n else {\n // Get local rotation matrix of the looking object\n const quaternionRotation = TmpVectors.Quaternion[0];\n Quaternion.FromEulerVectorToRef(this.rotation, quaternionRotation);\n const rotationMatrix = TmpVectors.Matrix[0];\n quaternionRotation.toRotationMatrix(rotationMatrix);\n // Offset rotation by parent's inverted rotation matrix to correct in world space\n const parentRotationMatrix = TmpVectors.Matrix[1];\n this.parent.getWorldMatrix().getRotationMatrixToRef(parentRotationMatrix);\n parentRotationMatrix.invert();\n rotationMatrix.multiplyToRef(parentRotationMatrix, rotationMatrix);\n quaternionRotation.fromRotationMatrix(rotationMatrix);\n quaternionRotation.toEulerAnglesToRef(this.rotation);\n }\n }\n return this;\n }\n /**\n * Returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.\n * This Vector3 is expressed in the World space.\n * @param localAxis axis to rotate\n * @returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.\n */\n getDirection(localAxis) {\n const result = Vector3.Zero();\n this.getDirectionToRef(localAxis, result);\n return result;\n }\n /**\n * Sets the Vector3 \"result\" as the rotated Vector3 \"localAxis\" in the same rotation than the mesh.\n * localAxis is expressed in the mesh local space.\n * result is computed in the World space from the mesh World matrix.\n * @param localAxis axis to rotate\n * @param result the resulting transformnode\n * @returns this TransformNode.\n */\n getDirectionToRef(localAxis, result) {\n Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);\n return this;\n }\n /**\n * Sets this transform node rotation to the given local axis.\n * @param localAxis the axis in local space\n * @param yawCor optional yaw (y-axis) correction in radians\n * @param pitchCor optional pitch (x-axis) correction in radians\n * @param rollCor optional roll (z-axis) correction in radians\n * @returns this TransformNode\n */\n setDirection(localAxis, yawCor = 0, pitchCor = 0, rollCor = 0) {\n const yaw = -Math.atan2(localAxis.z, localAxis.x) + Math.PI / 2;\n const len = Math.sqrt(localAxis.x * localAxis.x + localAxis.z * localAxis.z);\n const pitch = -Math.atan2(localAxis.y, len);\n if (this.rotationQuaternion) {\n Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);\n }\n else {\n this.rotation.x = pitch + pitchCor;\n this.rotation.y = yaw + yawCor;\n this.rotation.z = rollCor;\n }\n return this;\n }\n /**\n * Sets a new pivot point to the current node\n * @param point defines the new pivot point to use\n * @param space defines if the point is in world or local space (local by default)\n * @returns the current TransformNode\n */\n setPivotPoint(point, space = Space.LOCAL) {\n if (this.getScene().getRenderId() == 0) {\n this.computeWorldMatrix(true);\n }\n const wm = this.getWorldMatrix();\n if (space == Space.WORLD) {\n const tmat = TmpVectors.Matrix[0];\n wm.invertToRef(tmat);\n point = Vector3.TransformCoordinates(point, tmat);\n }\n return this.setPivotMatrix(Matrix.Translation(-point.x, -point.y, -point.z), true);\n }\n /**\n * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.\n * @returns the pivot point\n */\n getPivotPoint() {\n const point = Vector3.Zero();\n this.getPivotPointToRef(point);\n return point;\n }\n /**\n * Sets the passed Vector3 \"result\" with the coordinates of the mesh pivot point in the local space.\n * @param result the vector3 to store the result\n * @returns this TransformNode.\n */\n getPivotPointToRef(result) {\n result.x = -this._pivotMatrix.m[12];\n result.y = -this._pivotMatrix.m[13];\n result.z = -this._pivotMatrix.m[14];\n return this;\n }\n /**\n * Returns a new Vector3 set with the mesh pivot point World coordinates.\n * @returns a new Vector3 set with the mesh pivot point World coordinates.\n */\n getAbsolutePivotPoint() {\n const point = Vector3.Zero();\n this.getAbsolutePivotPointToRef(point);\n return point;\n }\n /**\n * Sets the Vector3 \"result\" coordinates with the mesh pivot point World coordinates.\n * @param result vector3 to store the result\n * @returns this TransformNode.\n */\n getAbsolutePivotPointToRef(result) {\n this.getPivotPointToRef(result);\n Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);\n return this;\n }\n /**\n * Flag the transform node as dirty (Forcing it to update everything)\n * @param property if set to \"rotation\" the objects rotationQuaternion will be set to null\n * @returns this node\n */\n markAsDirty(property) {\n if (this._isDirty) {\n return this;\n }\n // We need to explicitly update the children\n // as the scene.evaluateActiveMeshes will not poll the transform nodes\n if (this._children) {\n for (const child of this._children) {\n child.markAsDirty(property);\n }\n }\n return super.markAsDirty(property);\n }\n /**\n * Defines the passed node as the parent of the current node.\n * The node will remain exactly where it is and its position / rotation will be updated accordingly.\n * Note that if the mesh has a pivot matrix / point defined it will be applied after the parent was updated.\n * In that case the node will not remain in the same space as it is, as the pivot will be applied.\n * To avoid this, you can set updatePivot to true and the pivot will be updated to identity\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/parent_pivot/parent\n * @param node the node ot set as the parent\n * @param preserveScalingSign if true, keep scaling sign of child. Otherwise, scaling sign might change.\n * @param updatePivot if true, update the pivot matrix to keep the node in the same space as before\n * @returns this TransformNode.\n */\n setParent(node, preserveScalingSign = false, updatePivot = false) {\n if (!node && !this.parent) {\n return this;\n }\n const quatRotation = TmpVectors.Quaternion[0];\n const position = TmpVectors.Vector3[0];\n const scale = TmpVectors.Vector3[1];\n const invParentMatrix = TmpVectors.Matrix[1];\n Matrix.IdentityToRef(invParentMatrix);\n const composedMatrix = TmpVectors.Matrix[0];\n this.computeWorldMatrix(true);\n let currentRotation = this.rotationQuaternion;\n if (!currentRotation) {\n currentRotation = TransformNode._TmpRotation;\n Quaternion.RotationYawPitchRollToRef(this._rotation.y, this._rotation.x, this._rotation.z, currentRotation);\n }\n // current global transformation without pivot\n Matrix.ComposeToRef(this.scaling, currentRotation, this.position, composedMatrix);\n if (this.parent) {\n composedMatrix.multiplyToRef(this.parent.computeWorldMatrix(true), composedMatrix);\n }\n // is a node was set, calculate the difference between this and the node\n if (node) {\n node.computeWorldMatrix(true).invertToRef(invParentMatrix);\n composedMatrix.multiplyToRef(invParentMatrix, composedMatrix);\n }\n composedMatrix.decompose(scale, quatRotation, position, preserveScalingSign ? this : undefined);\n if (this.rotationQuaternion) {\n this.rotationQuaternion.copyFrom(quatRotation);\n }\n else {\n quatRotation.toEulerAnglesToRef(this.rotation);\n }\n this.scaling.copyFrom(scale);\n this.position.copyFrom(position);\n this.parent = node;\n if (updatePivot) {\n this.setPivotMatrix(Matrix.Identity());\n }\n return this;\n }\n /**\n * True if the scaling property of this object is non uniform eg. (1,2,1)\n */\n get nonUniformScaling() {\n return this._nonUniformScaling;\n }\n /**\n * @internal\n */\n _updateNonUniformScalingState(value) {\n if (this._nonUniformScaling === value) {\n return false;\n }\n this._nonUniformScaling = value;\n return true;\n }\n /**\n * Attach the current TransformNode to another TransformNode associated with a bone\n * @param bone Bone affecting the TransformNode\n * @param affectedTransformNode TransformNode associated with the bone\n * @returns this object\n */\n attachToBone(bone, affectedTransformNode) {\n this._currentParentWhenAttachingToBone = this.parent;\n this._transformToBoneReferal = affectedTransformNode;\n this.parent = bone;\n bone.getSkeleton().prepare(); // make sure bone.getFinalMatrix() is up to date\n if (bone.getFinalMatrix().determinant() < 0) {\n this.scalingDeterminant *= -1;\n }\n return this;\n }\n /**\n * Detach the transform node if its associated with a bone\n * @param resetToPreviousParent Indicates if the parent that was in effect when attachToBone was called should be set back or if we should set parent to null instead (defaults to the latter)\n * @returns this object\n */\n detachFromBone(resetToPreviousParent = false) {\n if (!this.parent) {\n if (resetToPreviousParent) {\n this.parent = this._currentParentWhenAttachingToBone;\n }\n return this;\n }\n if (this.parent.getWorldMatrix().determinant() < 0) {\n this.scalingDeterminant *= -1;\n }\n this._transformToBoneReferal = null;\n if (resetToPreviousParent) {\n this.parent = this._currentParentWhenAttachingToBone;\n }\n else {\n this.parent = null;\n }\n return this;\n }\n /**\n * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.\n * space (default LOCAL) can be either Space.LOCAL, either Space.WORLD.\n * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.\n * The passed axis is also normalized.\n * @param axis the axis to rotate around\n * @param amount the amount to rotate in radians\n * @param space Space to rotate in (Default: local)\n * @returns the TransformNode.\n */\n rotate(axis, amount, space) {\n axis.normalize();\n if (!this.rotationQuaternion) {\n this.rotationQuaternion = this.rotation.toQuaternion();\n this.rotation.setAll(0);\n }\n let rotationQuaternion;\n if (!space || space === Space.LOCAL) {\n rotationQuaternion = Quaternion.RotationAxisToRef(axis, amount, TransformNode._RotationAxisCache);\n this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);\n }\n else {\n if (this.parent) {\n const invertParentWorldMatrix = TmpVectors.Matrix[0];\n this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix);\n axis = Vector3.TransformNormal(axis, invertParentWorldMatrix);\n }\n rotationQuaternion = Quaternion.RotationAxisToRef(axis, amount, TransformNode._RotationAxisCache);\n rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);\n }\n return this;\n }\n /**\n * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.\n * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.\n * The passed axis is also normalized. .\n * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm\n * @param point the point to rotate around\n * @param axis the axis to rotate around\n * @param amount the amount to rotate in radians\n * @returns the TransformNode\n */\n rotateAround(point, axis, amount) {\n axis.normalize();\n if (!this.rotationQuaternion) {\n this.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);\n this.rotation.setAll(0);\n }\n const tmpVector = TmpVectors.Vector3[0];\n const finalScale = TmpVectors.Vector3[1];\n const finalTranslation = TmpVectors.Vector3[2];\n const finalRotation = TmpVectors.Quaternion[0];\n const translationMatrix = TmpVectors.Matrix[0]; // T\n const translationMatrixInv = TmpVectors.Matrix[1]; // T'\n const rotationMatrix = TmpVectors.Matrix[2]; // R\n const finalMatrix = TmpVectors.Matrix[3]; // T' x R x T\n point.subtractToRef(this.position, tmpVector);\n Matrix.TranslationToRef(tmpVector.x, tmpVector.y, tmpVector.z, translationMatrix); // T\n Matrix.TranslationToRef(-tmpVector.x, -tmpVector.y, -tmpVector.z, translationMatrixInv); // T'\n Matrix.RotationAxisToRef(axis, amount, rotationMatrix); // R\n translationMatrixInv.multiplyToRef(rotationMatrix, finalMatrix); // T' x R\n finalMatrix.multiplyToRef(translationMatrix, finalMatrix); // T' x R x T\n finalMatrix.decompose(finalScale, finalRotation, finalTranslation);\n this.position.addInPlace(finalTranslation);\n finalRotation.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);\n return this;\n }\n /**\n * Translates the mesh along the axis vector for the passed distance in the given space.\n * space (default LOCAL) can be either Space.LOCAL, either Space.WORLD.\n * @param axis the axis to translate in\n * @param distance the distance to translate\n * @param space Space to rotate in (Default: local)\n * @returns the TransformNode.\n */\n translate(axis, distance, space) {\n const displacementVector = axis.scale(distance);\n if (!space || space === Space.LOCAL) {\n const tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);\n this.setPositionWithLocalVector(tempV3);\n }\n else {\n this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));\n }\n return this;\n }\n /**\n * Adds a rotation step to the mesh current rotation.\n * x, y, z are Euler angles expressed in radians.\n * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.\n * This means this rotation is made in the mesh local space only.\n * It's useful to set a custom rotation order different from the BJS standard one YXZ.\n * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.\n * ```javascript\n * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);\n * ```\n * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.\n * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.\n * @param x Rotation to add\n * @param y Rotation to add\n * @param z Rotation to add\n * @returns the TransformNode.\n */\n addRotation(x, y, z) {\n let rotationQuaternion;\n if (this.rotationQuaternion) {\n rotationQuaternion = this.rotationQuaternion;\n }\n else {\n rotationQuaternion = TmpVectors.Quaternion[1];\n Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);\n }\n const accumulation = TmpVectors.Quaternion[0];\n Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);\n rotationQuaternion.multiplyInPlace(accumulation);\n if (!this.rotationQuaternion) {\n rotationQuaternion.toEulerAnglesToRef(this.rotation);\n }\n return this;\n }\n /**\n * @internal\n */\n _getEffectiveParent() {\n return this.parent;\n }\n /**\n * Returns whether the transform node world matrix computation needs the camera information to be computed.\n * This is the case when the node is a billboard or has an infinite distance for instance.\n * @returns true if the world matrix computation needs the camera information to be computed\n */\n isWorldMatrixCameraDependent() {\n return (this._infiniteDistance && !this.parent) || (this._billboardMode !== TransformNode.BILLBOARDMODE_NONE && !this.preserveParentRotationForBillboard);\n }\n /**\n * Computes the world matrix of the node\n * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch\n * @param camera defines the camera used if different from the scene active camera (This is used with modes like Billboard or infinite distance)\n * @returns the world matrix\n */\n computeWorldMatrix(force = false, camera = null) {\n if (this._isWorldMatrixFrozen && !this._isDirty) {\n return this._worldMatrix;\n }\n const currentRenderId = this.getScene().getRenderId();\n if (!this._isDirty && !force && (this._currentRenderId === currentRenderId || this.isSynchronized())) {\n this._currentRenderId = currentRenderId;\n return this._worldMatrix;\n }\n camera = camera || this.getScene().activeCamera;\n this._updateCache();\n const cache = this._cache;\n cache.pivotMatrixUpdated = false;\n cache.billboardMode = this.billboardMode;\n cache.infiniteDistance = this.infiniteDistance;\n cache.parent = this._parentNode;\n this._currentRenderId = currentRenderId;\n this._childUpdateId += 1;\n this._isDirty = false;\n this._position._isDirty = false;\n this._rotation._isDirty = false;\n this._scaling._isDirty = false;\n const parent = this._getEffectiveParent();\n // Scaling\n const scaling = TransformNode._TmpScaling;\n let translation = this._position;\n // Translation\n if (this._infiniteDistance) {\n if (!this.parent && camera) {\n const cameraWorldMatrix = camera.getWorldMatrix();\n const cameraGlobalPosition = new Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);\n translation = TransformNode._TmpTranslation;\n translation.copyFromFloats(this._position.x + cameraGlobalPosition.x, this._position.y + cameraGlobalPosition.y, this._position.z + cameraGlobalPosition.z);\n }\n }\n // Scaling\n scaling.copyFromFloats(this._scaling.x * this.scalingDeterminant, this._scaling.y * this.scalingDeterminant, this._scaling.z * this.scalingDeterminant);\n // Rotation\n let rotation;\n if (this._rotationQuaternion) {\n this._rotationQuaternion._isDirty = false;\n rotation = this._rotationQuaternion;\n if (this.reIntegrateRotationIntoRotationQuaternion) {\n const len = this.rotation.lengthSquared();\n if (len) {\n this._rotationQuaternion.multiplyInPlace(Quaternion.RotationYawPitchRoll(this._rotation.y, this._rotation.x, this._rotation.z));\n this._rotation.copyFromFloats(0, 0, 0);\n }\n }\n }\n else {\n rotation = TransformNode._TmpRotation;\n Quaternion.RotationYawPitchRollToRef(this._rotation.y, this._rotation.x, this._rotation.z, rotation);\n }\n // Compose\n if (this._usePivotMatrix) {\n const scaleMatrix = TmpVectors.Matrix[1];\n Matrix.ScalingToRef(scaling.x, scaling.y, scaling.z, scaleMatrix);\n // Rotation\n const rotationMatrix = TmpVectors.Matrix[0];\n rotation.toRotationMatrix(rotationMatrix);\n // Composing transformations\n this._pivotMatrix.multiplyToRef(scaleMatrix, TmpVectors.Matrix[4]);\n TmpVectors.Matrix[4].multiplyToRef(rotationMatrix, this._localMatrix);\n // Post multiply inverse of pivotMatrix\n if (this._postMultiplyPivotMatrix) {\n this._localMatrix.multiplyToRef(this._pivotMatrixInverse, this._localMatrix);\n }\n this._localMatrix.addTranslationFromFloats(translation.x, translation.y, translation.z);\n }\n else {\n Matrix.ComposeToRef(scaling, rotation, translation, this._localMatrix);\n }\n // Parent\n if (parent && parent.getWorldMatrix) {\n if (force) {\n parent.computeWorldMatrix(force);\n }\n if (cache.useBillboardPath) {\n if (this._transformToBoneReferal) {\n parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), TmpVectors.Matrix[7]);\n }\n else {\n TmpVectors.Matrix[7].copyFrom(parent.getWorldMatrix());\n }\n // Extract scaling and translation from parent\n const translation = TmpVectors.Vector3[5];\n const scale = TmpVectors.Vector3[6];\n const orientation = TmpVectors.Quaternion[0];\n TmpVectors.Matrix[7].decompose(scale, orientation, translation);\n Matrix.ScalingToRef(scale.x, scale.y, scale.z, TmpVectors.Matrix[7]);\n TmpVectors.Matrix[7].setTranslation(translation);\n if (TransformNode.BillboardUseParentOrientation) {\n // set localMatrix translation to be transformed against parent's orientation.\n this._position.applyRotationQuaternionToRef(orientation, translation);\n this._localMatrix.setTranslation(translation);\n }\n this._localMatrix.multiplyToRef(TmpVectors.Matrix[7], this._worldMatrix);\n }\n else {\n if (this._transformToBoneReferal) {\n this._localMatrix.multiplyToRef(parent.getWorldMatrix(), TmpVectors.Matrix[6]);\n TmpVectors.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);\n }\n else {\n this._localMatrix.multiplyToRef(parent.getWorldMatrix(), this._worldMatrix);\n }\n }\n this._markSyncedWithParent();\n }\n else {\n this._worldMatrix.copyFrom(this._localMatrix);\n }\n // Billboarding based on camera orientation (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)\n if (cache.useBillboardPath && camera && this.billboardMode && !cache.useBillboardPosition) {\n const storedTranslation = TmpVectors.Vector3[0];\n this._worldMatrix.getTranslationToRef(storedTranslation); // Save translation\n // Cancel camera rotation\n TmpVectors.Matrix[1].copyFrom(camera.getViewMatrix());\n if (this._scene.useRightHandedSystem) {\n TmpVectors.Matrix[1].multiplyToRef(convertRHSToLHS, TmpVectors.Matrix[1]);\n }\n TmpVectors.Matrix[1].setTranslationFromFloats(0, 0, 0);\n TmpVectors.Matrix[1].invertToRef(TmpVectors.Matrix[0]);\n if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {\n TmpVectors.Matrix[0].decompose(undefined, TmpVectors.Quaternion[0], undefined);\n const eulerAngles = TmpVectors.Vector3[1];\n TmpVectors.Quaternion[0].toEulerAnglesToRef(eulerAngles);\n if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) !== TransformNode.BILLBOARDMODE_X) {\n eulerAngles.x = 0;\n }\n if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) !== TransformNode.BILLBOARDMODE_Y) {\n eulerAngles.y = 0;\n }\n if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) !== TransformNode.BILLBOARDMODE_Z) {\n eulerAngles.z = 0;\n }\n Matrix.RotationYawPitchRollToRef(eulerAngles.y, eulerAngles.x, eulerAngles.z, TmpVectors.Matrix[0]);\n }\n this._worldMatrix.setTranslationFromFloats(0, 0, 0);\n this._worldMatrix.multiplyToRef(TmpVectors.Matrix[0], this._worldMatrix);\n // Restore translation\n this._worldMatrix.setTranslation(TmpVectors.Vector3[0]);\n }\n // Billboarding based on camera position\n else if (cache.useBillboardPath && camera && cache.useBillboardPosition) {\n const storedTranslation = TmpVectors.Vector3[0];\n // Save translation\n this._worldMatrix.getTranslationToRef(storedTranslation);\n // Compute camera position in local space\n const cameraPosition = camera.globalPosition;\n this._worldMatrix.invertToRef(TmpVectors.Matrix[1]);\n const camInObjSpace = TmpVectors.Vector3[1];\n Vector3.TransformCoordinatesToRef(cameraPosition, TmpVectors.Matrix[1], camInObjSpace);\n camInObjSpace.normalize();\n // Find the lookAt info in local space\n const yaw = -Math.atan2(camInObjSpace.z, camInObjSpace.x) + Math.PI / 2;\n const len = Math.sqrt(camInObjSpace.x * camInObjSpace.x + camInObjSpace.z * camInObjSpace.z);\n const pitch = -Math.atan2(camInObjSpace.y, len);\n Quaternion.RotationYawPitchRollToRef(yaw, pitch, 0, TmpVectors.Quaternion[0]);\n if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {\n const eulerAngles = TmpVectors.Vector3[1];\n TmpVectors.Quaternion[0].toEulerAnglesToRef(eulerAngles);\n if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) !== TransformNode.BILLBOARDMODE_X) {\n eulerAngles.x = 0;\n }\n if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) !== TransformNode.BILLBOARDMODE_Y) {\n eulerAngles.y = 0;\n }\n if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) !== TransformNode.BILLBOARDMODE_Z) {\n eulerAngles.z = 0;\n }\n Matrix.RotationYawPitchRollToRef(eulerAngles.y, eulerAngles.x, eulerAngles.z, TmpVectors.Matrix[0]);\n }\n else {\n Matrix.FromQuaternionToRef(TmpVectors.Quaternion[0], TmpVectors.Matrix[0]);\n }\n // Cancel translation\n this._worldMatrix.setTranslationFromFloats(0, 0, 0);\n // Rotate according to lookat (diff from local to lookat)\n this._worldMatrix.multiplyToRef(TmpVectors.Matrix[0], this._worldMatrix);\n // Restore translation\n this._worldMatrix.setTranslation(TmpVectors.Vector3[0]);\n }\n // Normal matrix\n if (!this.ignoreNonUniformScaling) {\n if (this._scaling.isNonUniformWithinEpsilon(0.000001)) {\n this._updateNonUniformScalingState(true);\n }\n else if (parent && parent._nonUniformScaling) {\n this._updateNonUniformScalingState(parent._nonUniformScaling);\n }\n else {\n this._updateNonUniformScalingState(false);\n }\n }\n else {\n this._updateNonUniformScalingState(false);\n }\n this._afterComputeWorldMatrix();\n // Absolute position\n this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);\n this._isAbsoluteSynced = false;\n // Callbacks\n this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);\n if (!this._poseMatrix) {\n this._poseMatrix = Matrix.Invert(this._worldMatrix);\n }\n // Cache the determinant\n this._worldMatrixDeterminantIsDirty = true;\n return this._worldMatrix;\n }\n /**\n * Resets this nodeTransform's local matrix to Matrix.Identity().\n * @param independentOfChildren indicates if all child nodeTransform's world-space transform should be preserved.\n */\n resetLocalMatrix(independentOfChildren = true) {\n this.computeWorldMatrix();\n if (independentOfChildren) {\n const children = this.getChildren();\n for (let i = 0; i < children.length; ++i) {\n const child = children[i];\n if (child) {\n child.computeWorldMatrix();\n const bakedMatrix = TmpVectors.Matrix[0];\n child._localMatrix.multiplyToRef(this._localMatrix, bakedMatrix);\n const tmpRotationQuaternion = TmpVectors.Quaternion[0];\n bakedMatrix.decompose(child.scaling, tmpRotationQuaternion, child.position);\n if (child.rotationQuaternion) {\n child.rotationQuaternion.copyFrom(tmpRotationQuaternion);\n }\n else {\n tmpRotationQuaternion.toEulerAnglesToRef(child.rotation);\n }\n }\n }\n }\n this.scaling.copyFromFloats(1, 1, 1);\n this.position.copyFromFloats(0, 0, 0);\n this.rotation.copyFromFloats(0, 0, 0);\n //only if quaternion is already set\n if (this.rotationQuaternion) {\n this.rotationQuaternion = Quaternion.Identity();\n }\n this._worldMatrix = Matrix.Identity();\n }\n _afterComputeWorldMatrix() { }\n /**\n * If you'd like to be called back after the mesh position, rotation or scaling has been updated.\n * @param func callback function to add\n *\n * @returns the TransformNode.\n */\n registerAfterWorldMatrixUpdate(func) {\n this.onAfterWorldMatrixUpdateObservable.add(func);\n return this;\n }\n /**\n * Removes a registered callback function.\n * @param func callback function to remove\n * @returns the TransformNode.\n */\n unregisterAfterWorldMatrixUpdate(func) {\n this.onAfterWorldMatrixUpdateObservable.removeCallback(func);\n return this;\n }\n /**\n * Gets the position of the current mesh in camera space\n * @param camera defines the camera to use\n * @returns a position\n */\n getPositionInCameraSpace(camera = null) {\n if (!camera) {\n camera = this.getScene().activeCamera;\n }\n return Vector3.TransformCoordinates(this.getAbsolutePosition(), camera.getViewMatrix());\n }\n /**\n * Returns the distance from the mesh to the active camera\n * @param camera defines the camera to use\n * @returns the distance\n */\n getDistanceToCamera(camera = null) {\n if (!camera) {\n camera = this.getScene().activeCamera;\n }\n return this.getAbsolutePosition().subtract(camera.globalPosition).length();\n }\n /**\n * Clone the current transform node\n * @param name Name of the new clone\n * @param newParent New parent for the clone\n * @param doNotCloneChildren Do not clone children hierarchy\n * @returns the new transform node\n */\n clone(name, newParent, doNotCloneChildren) {\n const result = SerializationHelper.Clone(() => new TransformNode(name, this.getScene()), this);\n result.name = name;\n result.id = name;\n if (newParent) {\n result.parent = newParent;\n }\n if (!doNotCloneChildren) {\n // Children\n const directDescendants = this.getDescendants(true);\n for (let index = 0; index < directDescendants.length; index++) {\n const child = directDescendants[index];\n if (child.clone) {\n child.clone(name + \".\" + child.name, result);\n }\n }\n }\n return result;\n }\n /**\n * Serializes the objects information.\n * @param currentSerializationObject defines the object to serialize in\n * @returns the serialized object\n */\n serialize(currentSerializationObject) {\n const serializationObject = SerializationHelper.Serialize(this, currentSerializationObject);\n serializationObject.type = this.getClassName();\n serializationObject.uniqueId = this.uniqueId;\n // Parent\n if (this.parent) {\n this.parent._serializeAsParent(serializationObject);\n }\n serializationObject.localMatrix = this.getPivotMatrix().asArray();\n serializationObject.isEnabled = this.isEnabled();\n return serializationObject;\n }\n // Statics\n /**\n * Returns a new TransformNode object parsed from the source provided.\n * @param parsedTransformNode is the source.\n * @param scene the scene the object belongs to\n * @param rootUrl is a string, it's the root URL to prefix the `delayLoadingFile` property with\n * @returns a new TransformNode object parsed from the source provided.\n */\n static Parse(parsedTransformNode, scene, rootUrl) {\n const transformNode = SerializationHelper.Parse(() => new TransformNode(parsedTransformNode.name, scene), parsedTransformNode, scene, rootUrl);\n if (parsedTransformNode.localMatrix) {\n transformNode.setPreTransformMatrix(Matrix.FromArray(parsedTransformNode.localMatrix));\n }\n else if (parsedTransformNode.pivotMatrix) {\n transformNode.setPivotMatrix(Matrix.FromArray(parsedTransformNode.pivotMatrix));\n }\n transformNode.setEnabled(parsedTransformNode.isEnabled);\n transformNode._waitingParsedUniqueId = parsedTransformNode.uniqueId;\n // Parent\n if (parsedTransformNode.parentId !== undefined) {\n transformNode._waitingParentId = parsedTransformNode.parentId;\n }\n if (parsedTransformNode.parentInstanceIndex !== undefined) {\n transformNode._waitingParentInstanceIndex = parsedTransformNode.parentInstanceIndex;\n }\n return transformNode;\n }\n /**\n * Get all child-transformNodes of this node\n * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered\n * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored\n * @returns an array of TransformNode\n */\n getChildTransformNodes(directDescendantsOnly, predicate) {\n const results = [];\n this._getDescendants(results, directDescendantsOnly, (node) => {\n return (!predicate || predicate(node)) && node instanceof TransformNode;\n });\n return results;\n }\n /**\n * Releases resources associated with this transform node.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n dispose(doNotRecurse, disposeMaterialAndTextures = false) {\n // Animations\n this.getScene().stopAnimation(this);\n // Remove from scene\n this.getScene().removeTransformNode(this);\n if (this._parentContainer) {\n const index = this._parentContainer.transformNodes.indexOf(this);\n if (index > -1) {\n this._parentContainer.transformNodes.splice(index, 1);\n }\n this._parentContainer = null;\n }\n this.onAfterWorldMatrixUpdateObservable.clear();\n if (doNotRecurse) {\n const transformNodes = this.getChildTransformNodes(true);\n for (const transformNode of transformNodes) {\n transformNode.parent = null;\n transformNode.computeWorldMatrix(true);\n }\n }\n super.dispose(doNotRecurse, disposeMaterialAndTextures);\n }\n /**\n * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)\n * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box. Default is false\n * @param ignoreRotation ignore rotation when computing the scale (ie. object will be axis aligned). Default is false\n * @param predicate predicate that is passed in to getHierarchyBoundingVectors when selecting which object should be included when scaling\n * @returns the current mesh\n */\n normalizeToUnitCube(includeDescendants = true, ignoreRotation = false, predicate) {\n let storedRotation = null;\n let storedRotationQuaternion = null;\n if (ignoreRotation) {\n if (this.rotationQuaternion) {\n storedRotationQuaternion = this.rotationQuaternion.clone();\n this.rotationQuaternion.copyFromFloats(0, 0, 0, 1);\n }\n else if (this.rotation) {\n storedRotation = this.rotation.clone();\n this.rotation.copyFromFloats(0, 0, 0);\n }\n }\n const boundingVectors = this.getHierarchyBoundingVectors(includeDescendants, predicate);\n const sizeVec = boundingVectors.max.subtract(boundingVectors.min);\n const maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);\n if (maxDimension === 0) {\n return this;\n }\n const scale = 1 / maxDimension;\n this.scaling.scaleInPlace(scale);\n if (ignoreRotation) {\n if (this.rotationQuaternion && storedRotationQuaternion) {\n this.rotationQuaternion.copyFrom(storedRotationQuaternion);\n }\n else if (this.rotation && storedRotation) {\n this.rotation.copyFrom(storedRotation);\n }\n }\n return this;\n }\n _syncAbsoluteScalingAndRotation() {\n if (!this._isAbsoluteSynced) {\n this._worldMatrix.decompose(this._absoluteScaling, this._absoluteRotationQuaternion);\n this._isAbsoluteSynced = true;\n }\n }\n}\n// Statics\n/**\n * Object will not rotate to face the camera\n */\nTransformNode.BILLBOARDMODE_NONE = 0;\n/**\n * Object will rotate to face the camera but only on the x axis\n */\nTransformNode.BILLBOARDMODE_X = 1;\n/**\n * Object will rotate to face the camera but only on the y axis\n */\nTransformNode.BILLBOARDMODE_Y = 2;\n/**\n * Object will rotate to face the camera but only on the z axis\n */\nTransformNode.BILLBOARDMODE_Z = 4;\n/**\n * Object will rotate to face the camera\n */\nTransformNode.BILLBOARDMODE_ALL = 7;\n/**\n * Object will rotate to face the camera's position instead of orientation\n */\nTransformNode.BILLBOARDMODE_USE_POSITION = 128;\n/**\n * Child transform with Billboard flags should or should not apply parent rotation (default if off)\n */\nTransformNode.BillboardUseParentOrientation = false;\nTransformNode._TmpRotation = Quaternion.Zero();\nTransformNode._TmpScaling = Vector3.Zero();\nTransformNode._TmpTranslation = Vector3.Zero();\nTransformNode._LookAtVectorCache = new Vector3(0, 0, 0);\nTransformNode._RotationAxisCache = new Quaternion();\n__decorate([\n serializeAsVector3(\"position\")\n], TransformNode.prototype, \"_position\", void 0);\n__decorate([\n serializeAsVector3(\"rotation\")\n], TransformNode.prototype, \"_rotation\", void 0);\n__decorate([\n serializeAsQuaternion(\"rotationQuaternion\")\n], TransformNode.prototype, \"_rotationQuaternion\", void 0);\n__decorate([\n serializeAsVector3(\"scaling\")\n], TransformNode.prototype, \"_scaling\", void 0);\n__decorate([\n serialize(\"billboardMode\")\n], TransformNode.prototype, \"_billboardMode\", void 0);\n__decorate([\n serialize()\n], TransformNode.prototype, \"scalingDeterminant\", void 0);\n__decorate([\n serialize(\"infiniteDistance\")\n], TransformNode.prototype, \"_infiniteDistance\", void 0);\n__decorate([\n serialize()\n], TransformNode.prototype, \"ignoreNonUniformScaling\", void 0);\n__decorate([\n serialize()\n], TransformNode.prototype, \"reIntegrateRotationIntoRotationQuaternion\", void 0);\n//# sourceMappingURL=transformNode.js.map","/**\n * Class used to evaluate queries containing `and` and `or` operators\n */\nexport class AndOrNotEvaluator {\n /**\n * Evaluate a query\n * @param query defines the query to evaluate\n * @param evaluateCallback defines the callback used to filter result\n * @returns true if the query matches\n */\n static Eval(query, evaluateCallback) {\n if (!query.match(/\\([^()]*\\)/g)) {\n query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);\n }\n else {\n query = query.replace(/\\([^()]*\\)/g, (r) => {\n // remove parenthesis\n r = r.slice(1, r.length - 1);\n return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);\n });\n }\n if (query === \"true\") {\n return true;\n }\n if (query === \"false\") {\n return false;\n }\n return AndOrNotEvaluator.Eval(query, evaluateCallback);\n }\n static _HandleParenthesisContent(parenthesisContent, evaluateCallback) {\n evaluateCallback =\n evaluateCallback ||\n ((r) => {\n return r === \"true\" ? true : false;\n });\n let result;\n const or = parenthesisContent.split(\"||\");\n for (const i in or) {\n if (Object.prototype.hasOwnProperty.call(or, i)) {\n let ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());\n const and = ori.split(\"&&\");\n if (and.length > 1) {\n for (let j = 0; j < and.length; ++j) {\n const andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());\n if (andj !== \"true\" && andj !== \"false\") {\n if (andj[0] === \"!\") {\n result = !evaluateCallback(andj.substring(1));\n }\n else {\n result = evaluateCallback(andj);\n }\n }\n else {\n result = andj === \"true\" ? true : false;\n }\n if (!result) {\n // no need to continue since 'false && ... && ...' will always return false\n ori = \"false\";\n break;\n }\n }\n }\n if (result || ori === \"true\") {\n // no need to continue since 'true || ... || ...' will always return true\n result = true;\n break;\n }\n // result equals false (or undefined)\n if (ori !== \"true\" && ori !== \"false\") {\n if (ori[0] === \"!\") {\n result = !evaluateCallback(ori.substring(1));\n }\n else {\n result = evaluateCallback(ori);\n }\n }\n else {\n result = ori === \"true\" ? true : false;\n }\n }\n }\n // the whole parenthesis scope is replaced by 'true' or 'false'\n return result ? \"true\" : \"false\";\n }\n static _SimplifyNegation(booleanString) {\n booleanString = booleanString.replace(/^[\\s!]+/, (r) => {\n // remove whitespaces\n r = r.replace(/[\\s]/g, () => \"\");\n return r.length % 2 ? \"!\" : \"\";\n });\n booleanString = booleanString.trim();\n if (booleanString === \"!true\") {\n booleanString = \"false\";\n }\n else if (booleanString === \"!false\") {\n booleanString = \"true\";\n }\n return booleanString;\n }\n}\n//# sourceMappingURL=andOrNotEvaluator.js.map","/* eslint-disable @typescript-eslint/naming-convention */\n/**\n * Class containing a set of static utilities functions for arrays.\n */\nexport class ArrayTools {\n /**\n * Returns an array of the given size filled with elements built from the given constructor and the parameters.\n * @param size the number of element to construct and put in the array.\n * @param itemBuilder a callback responsible for creating new instance of item. Called once per array entry.\n * @returns a new array filled with new objects.\n */\n static BuildArray(size, itemBuilder) {\n const a = [];\n for (let i = 0; i < size; ++i) {\n a.push(itemBuilder());\n }\n return a;\n }\n /**\n * Returns a tuple of the given size filled with elements built from the given constructor and the parameters.\n * @param size he number of element to construct and put in the tuple.\n * @param itemBuilder a callback responsible for creating new instance of item. Called once per tuple entry.\n * @returns a new tuple filled with new objects.\n */\n static BuildTuple(size, itemBuilder) {\n return ArrayTools.BuildArray(size, itemBuilder);\n }\n}\n/**\n * Observes a function and calls the given callback when it is called.\n * @param object Defines the object the function to observe belongs to.\n * @param functionName Defines the name of the function to observe.\n * @param callback Defines the callback to call when the function is called.\n * @returns A function to call to stop observing\n */\nfunction _observeArrayfunction(object, functionName, callback) {\n // Finds the function to observe\n const oldFunction = object[functionName];\n if (typeof oldFunction !== \"function\") {\n return null;\n }\n // Creates a new function that calls the callback and the old function\n const newFunction = function () {\n const previousLength = object.length;\n const returnValue = newFunction.previous.apply(object, arguments);\n callback(functionName, previousLength);\n return returnValue;\n };\n // Doublishly links the new function and the old function\n oldFunction.next = newFunction;\n newFunction.previous = oldFunction;\n // Replaces the old function with the new function\n object[functionName] = newFunction;\n // Returns a function to disable the hook\n return () => {\n // Only unhook if the function is still hooked\n const previous = newFunction.previous;\n if (!previous) {\n return;\n }\n // Finds the ref to the next function in the chain\n const next = newFunction.next;\n // If in the middle of the chain, link the previous and next functions\n if (next) {\n previous.next = next;\n next.previous = previous;\n }\n // If at the end of the chain, remove the reference to the previous function\n // and restore the previous function\n else {\n previous.next = undefined;\n object[functionName] = previous;\n }\n // Lose reference to the previous and next functions\n newFunction.next = undefined;\n newFunction.previous = undefined;\n };\n}\n/**\n * Defines the list of functions to proxy when observing an array.\n * The scope is currently reduced to the common functions used in the render target render list and the scene cameras.\n */\nconst observedArrayFunctions = [\"push\", \"splice\", \"pop\", \"shift\", \"unshift\"];\n/**\n * Observes an array and notifies the given observer when the array is modified.\n * @param array Defines the array to observe\n * @param callback Defines the function to call when the array is modified (in the limit of the observed array functions)\n * @returns A function to call to stop observing the array\n * @internal\n */\nexport function _ObserveArray(array, callback) {\n // Observes all the required array functions and stores the unhook functions\n const unObserveFunctions = observedArrayFunctions.map((name) => {\n return _observeArrayfunction(array, name, callback);\n });\n // Returns a function that unhook all the observed functions\n return () => {\n unObserveFunctions.forEach((unObserveFunction) => {\n unObserveFunction === null || unObserveFunction === void 0 ? void 0 : unObserveFunction();\n });\n };\n}\n//# sourceMappingURL=arrayTools.js.map","/* eslint-disable @typescript-eslint/naming-convention */\n// \"Coroutines are computer program components that generalize subroutines for non-preemptive multitasking, by allowing execution to be suspended and resumed.\"\n// https://en.wikipedia.org/wiki/Coroutine\n// The inline scheduler simply steps the coroutine synchronously. This is useful for running a coroutine synchronously, and also as a helper function for other schedulers.\n/**\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function inlineScheduler(coroutine, onStep, onError) {\n try {\n const step = coroutine.next();\n if (step.done) {\n onStep(step);\n }\n else if (!step.value) {\n // NOTE: The properties of step have been narrowed, but the type of step itself is not narrowed, so the cast below is the most type safe way to deal with this without instantiating a new object to hold the values.\n onStep(step);\n }\n else {\n step.value.then(() => {\n step.value = undefined;\n onStep(step);\n }, onError);\n }\n }\n catch (error) {\n onError(error);\n }\n}\n// The yielding scheduler steps the coroutine synchronously until the specified time interval has elapsed, then yields control so other operations can be performed.\n// A single instance of a yielding scheduler could be shared across multiple coroutines to yield when their collective work exceeds the threshold.\n/**\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function createYieldingScheduler(yieldAfterMS = 25) {\n let startTime;\n return (coroutine, onStep, onError) => {\n const currentTime = performance.now();\n if (startTime === undefined || currentTime - startTime > yieldAfterMS) {\n // If this is the first coroutine step, or if the time interval has elapsed, record a new start time, and schedule the coroutine step to happen later, effectively yielding control of the execution context.\n startTime = currentTime;\n setTimeout(() => {\n inlineScheduler(coroutine, onStep, onError);\n }, 0);\n }\n else {\n // Otherwise it is not time to yield yet, so step the coroutine synchronously.\n inlineScheduler(coroutine, onStep, onError);\n }\n };\n}\n// Runs the specified coroutine with the specified scheduler. The success or error callback will be invoked when the coroutine finishes.\n/**\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function runCoroutine(coroutine, scheduler, onSuccess, onError, abortSignal) {\n const resume = () => {\n let reschedule;\n const onStep = (stepResult) => {\n if (stepResult.done) {\n // If the coroutine is done, report success.\n onSuccess(stepResult.value);\n }\n else {\n // If the coroutine is not done, resume the coroutine (via the scheduler).\n if (reschedule === undefined) {\n // If reschedule is undefined at this point, then the coroutine must have stepped synchronously, so just flag another loop iteration.\n reschedule = true;\n }\n else {\n // If reschedule is defined at this point, then the coroutine must have stepped asynchronously, so call resume to restart the step loop.\n resume();\n }\n }\n };\n do {\n reschedule = undefined;\n if (!abortSignal || !abortSignal.aborted) {\n scheduler(coroutine, onStep, onError);\n }\n else {\n onError(new Error(\"Aborted\"));\n }\n if (reschedule === undefined) {\n // If reschedule is undefined at this point, then the coroutine must have stepped asynchronously, so stop looping and let the coroutine be resumed later.\n reschedule = false;\n }\n } while (reschedule);\n };\n resume();\n}\n// Runs the specified coroutine synchronously.\n/**\n * @internal\n */\nexport function runCoroutineSync(coroutine, abortSignal) {\n // Run the coroutine with the inline scheduler, storing the returned value, or re-throwing the error (since the error callback will be called synchronously by the inline scheduler).\n let result;\n runCoroutine(coroutine, inlineScheduler, (r) => (result = r), (e) => {\n throw e;\n }, abortSignal);\n // Synchronously return the result of the coroutine.\n return result;\n}\n// Runs the specified coroutine asynchronously with the specified scheduler.\n/**\n * @internal\n */\nexport function runCoroutineAsync(coroutine, scheduler, abortSignal) {\n // Run the coroutine with a yielding scheduler, resolving or rejecting the result promise when the coroutine finishes.\n return new Promise((resolve, reject) => {\n runCoroutine(coroutine, scheduler, resolve, reject, abortSignal);\n });\n}\n/**\n * Given a function that returns a Coroutine, produce a function with the same parameters that returns a T.\n * The returned function runs the coroutine synchronously.\n * @param coroutineFactory A function that returns a Coroutine.\n * @param abortSignal\n * @returns A function that runs the coroutine synchronously.\n * @internal\n */\nexport function makeSyncFunction(coroutineFactory, abortSignal) {\n return (...params) => {\n // Run the coroutine synchronously.\n return runCoroutineSync(coroutineFactory(...params), abortSignal);\n };\n}\n/**\n * Given a function that returns a Coroutine, product a function with the same parameters that returns a Promise.\n * The returned function runs the coroutine asynchronously, yield control of the execution context occasionally to enable a more responsive experience.\n * @param coroutineFactory A function that returns a Coroutine.\n * @param scheduler\n * @param abortSignal\n * @returns A function that runs the coroutine asynchronously.\n * @internal\n */\nexport function makeAsyncFunction(coroutineFactory, scheduler, abortSignal) {\n return (...params) => {\n // Run the coroutine asynchronously.\n return runCoroutineAsync(coroutineFactory(...params), scheduler, abortSignal);\n };\n}\n//# sourceMappingURL=coroutine.js.map","/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable @typescript-eslint/naming-convention */\nimport { Tags } from \"../Misc/tags.js\";\nimport { Quaternion, Vector2, Vector3, Matrix } from \"../Maths/math.vector.js\";\nimport { _WarnImport } from \"./devTools.js\";\nimport { Color4, Color3 } from \"../Maths/math.color.js\";\nconst __decoratorInitialStore = {};\nconst __mergedStore = {};\nconst _copySource = function (creationFunction, source, instanciate, options = {}) {\n const destination = creationFunction();\n // Tags\n if (Tags && Tags.HasTags(source)) {\n Tags.AddTagsTo(destination, Tags.GetTags(source, true));\n }\n const classStore = getMergedStore(destination);\n // Map from source texture uniqueId to destination texture\n const textureMap = {};\n // Properties\n for (const property in classStore) {\n const propertyDescriptor = classStore[property];\n const sourceProperty = source[property];\n const propertyType = propertyDescriptor.type;\n if (sourceProperty !== undefined && sourceProperty !== null && (property !== \"uniqueId\" || SerializationHelper.AllowLoadingUniqueId)) {\n switch (propertyType) {\n case 0: // Value\n case 6: // Mesh reference\n case 11: // Camera reference\n destination[property] = sourceProperty;\n break;\n case 1: // Texture\n if (options.cloneTexturesOnlyOnce && textureMap[sourceProperty.uniqueId]) {\n destination[property] = textureMap[sourceProperty.uniqueId];\n }\n else {\n destination[property] = instanciate || sourceProperty.isRenderTarget ? sourceProperty : sourceProperty.clone();\n textureMap[sourceProperty.uniqueId] = destination[property];\n }\n break;\n case 2: // Color3\n case 3: // FresnelParameters\n case 4: // Vector2\n case 5: // Vector3\n case 7: // Color Curves\n case 10: // Quaternion\n case 12: // Matrix\n destination[property] = instanciate ? sourceProperty : sourceProperty.clone();\n break;\n }\n }\n }\n return destination;\n};\nfunction getDirectStore(target) {\n const classKey = target.getClassName();\n if (!__decoratorInitialStore[classKey]) {\n __decoratorInitialStore[classKey] = {};\n }\n return __decoratorInitialStore[classKey];\n}\n/**\n * Return the list of properties flagged as serializable\n * @param target host object\n */\nfunction getMergedStore(target) {\n const classKey = target.getClassName();\n if (__mergedStore[classKey]) {\n return __mergedStore[classKey];\n }\n __mergedStore[classKey] = {};\n const store = __mergedStore[classKey];\n let currentTarget = target;\n let currentKey = classKey;\n while (currentKey) {\n const initialStore = __decoratorInitialStore[currentKey];\n for (const property in initialStore) {\n store[property] = initialStore[property];\n }\n let parent;\n let done = false;\n do {\n parent = Object.getPrototypeOf(currentTarget);\n if (!parent.getClassName) {\n done = true;\n break;\n }\n if (parent.getClassName() !== currentKey) {\n break;\n }\n currentTarget = parent;\n } while (parent);\n if (done) {\n break;\n }\n currentKey = parent.getClassName();\n currentTarget = parent;\n }\n return store;\n}\nfunction generateSerializableMember(type, sourceName) {\n return (target, propertyKey) => {\n const classStore = getDirectStore(target);\n if (!classStore[propertyKey]) {\n classStore[propertyKey] = { type: type, sourceName: sourceName };\n }\n };\n}\nfunction generateExpandMember(setCallback, targetKey = null) {\n return (target, propertyKey) => {\n const key = targetKey || \"_\" + propertyKey;\n Object.defineProperty(target, propertyKey, {\n get: function () {\n return this[key];\n },\n set: function (value) {\n // does this object (i.e. vector3) has an equals function? use it!\n // Note - not using \"with epsilon\" here, it is expected te behave like the internal cache does.\n if (typeof this.equals === \"function\") {\n if (this.equals(value)) {\n return;\n }\n }\n if (this[key] === value) {\n return;\n }\n this[key] = value;\n target[setCallback].apply(this);\n },\n enumerable: true,\n configurable: true,\n });\n };\n}\nexport function expandToProperty(callback, targetKey = null) {\n return generateExpandMember(callback, targetKey);\n}\nexport function serialize(sourceName) {\n return generateSerializableMember(0, sourceName); // value member\n}\nexport function serializeAsTexture(sourceName) {\n return generateSerializableMember(1, sourceName); // texture member\n}\nexport function serializeAsColor3(sourceName) {\n return generateSerializableMember(2, sourceName); // color3 member\n}\nexport function serializeAsFresnelParameters(sourceName) {\n return generateSerializableMember(3, sourceName); // fresnel parameters member\n}\nexport function serializeAsVector2(sourceName) {\n return generateSerializableMember(4, sourceName); // vector2 member\n}\nexport function serializeAsVector3(sourceName) {\n return generateSerializableMember(5, sourceName); // vector3 member\n}\nexport function serializeAsMeshReference(sourceName) {\n return generateSerializableMember(6, sourceName); // mesh reference member\n}\nexport function serializeAsColorCurves(sourceName) {\n return generateSerializableMember(7, sourceName); // color curves\n}\nexport function serializeAsColor4(sourceName) {\n return generateSerializableMember(8, sourceName); // color 4\n}\nexport function serializeAsImageProcessingConfiguration(sourceName) {\n return generateSerializableMember(9, sourceName); // image processing\n}\nexport function serializeAsQuaternion(sourceName) {\n return generateSerializableMember(10, sourceName); // quaternion member\n}\nexport function serializeAsMatrix(sourceName) {\n return generateSerializableMember(12, sourceName); // matrix member\n}\n/**\n * Decorator used to define property that can be serialized as reference to a camera\n * @param sourceName defines the name of the property to decorate\n */\nexport function serializeAsCameraReference(sourceName) {\n return generateSerializableMember(11, sourceName); // camera reference member\n}\n/**\n * Class used to help serialization objects\n */\nexport class SerializationHelper {\n /**\n * Appends the serialized animations from the source animations\n * @param source Source containing the animations\n * @param destination Target to store the animations\n */\n static AppendSerializedAnimations(source, destination) {\n if (source.animations) {\n destination.animations = [];\n for (let animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {\n const animation = source.animations[animationIndex];\n destination.animations.push(animation.serialize());\n }\n }\n }\n /**\n * Static function used to serialized a specific entity\n * @param entity defines the entity to serialize\n * @param serializationObject defines the optional target object where serialization data will be stored\n * @returns a JSON compatible object representing the serialization of the entity\n */\n static Serialize(entity, serializationObject) {\n if (!serializationObject) {\n serializationObject = {};\n }\n // Tags\n if (Tags) {\n serializationObject.tags = Tags.GetTags(entity);\n }\n const serializedProperties = getMergedStore(entity);\n // Properties\n for (const property in serializedProperties) {\n const propertyDescriptor = serializedProperties[property];\n const targetPropertyName = propertyDescriptor.sourceName || property;\n const propertyType = propertyDescriptor.type;\n const sourceProperty = entity[property];\n if (sourceProperty !== undefined && sourceProperty !== null && (property !== \"uniqueId\" || SerializationHelper.AllowLoadingUniqueId)) {\n switch (propertyType) {\n case 0: // Value\n serializationObject[targetPropertyName] = sourceProperty;\n break;\n case 1: // Texture\n serializationObject[targetPropertyName] = sourceProperty.serialize();\n break;\n case 2: // Color3\n serializationObject[targetPropertyName] = sourceProperty.asArray();\n break;\n case 3: // FresnelParameters\n serializationObject[targetPropertyName] = sourceProperty.serialize();\n break;\n case 4: // Vector2\n serializationObject[targetPropertyName] = sourceProperty.asArray();\n break;\n case 5: // Vector3\n serializationObject[targetPropertyName] = sourceProperty.asArray();\n break;\n case 6: // Mesh reference\n serializationObject[targetPropertyName] = sourceProperty.id;\n break;\n case 7: // Color Curves\n serializationObject[targetPropertyName] = sourceProperty.serialize();\n break;\n case 8: // Color 4\n serializationObject[targetPropertyName] = sourceProperty.asArray();\n break;\n case 9: // Image Processing\n serializationObject[targetPropertyName] = sourceProperty.serialize();\n break;\n case 10: // Quaternion\n serializationObject[targetPropertyName] = sourceProperty.asArray();\n break;\n case 11: // Camera reference\n serializationObject[targetPropertyName] = sourceProperty.id;\n break;\n case 12: // Matrix\n serializationObject[targetPropertyName] = sourceProperty.asArray();\n break;\n }\n }\n }\n return serializationObject;\n }\n /**\n * Given a source json and a destination object in a scene, this function will parse the source and will try to apply its content to the destination object\n * @param source the source json data\n * @param destination the destination object\n * @param scene the scene where the object is\n * @param rootUrl root url to use to load assets\n */\n static ParseProperties(source, destination, scene, rootUrl) {\n if (!rootUrl) {\n rootUrl = \"\";\n }\n const classStore = getMergedStore(destination);\n // Properties\n for (const property in classStore) {\n const propertyDescriptor = classStore[property];\n const sourceProperty = source[propertyDescriptor.sourceName || property];\n const propertyType = propertyDescriptor.type;\n if (sourceProperty !== undefined && sourceProperty !== null && (property !== \"uniqueId\" || SerializationHelper.AllowLoadingUniqueId)) {\n const dest = destination;\n switch (propertyType) {\n case 0: // Value\n dest[property] = sourceProperty;\n break;\n case 1: // Texture\n if (scene) {\n dest[property] = SerializationHelper._TextureParser(sourceProperty, scene, rootUrl);\n }\n break;\n case 2: // Color3\n dest[property] = Color3.FromArray(sourceProperty);\n break;\n case 3: // FresnelParameters\n dest[property] = SerializationHelper._FresnelParametersParser(sourceProperty);\n break;\n case 4: // Vector2\n dest[property] = Vector2.FromArray(sourceProperty);\n break;\n case 5: // Vector3\n dest[property] = Vector3.FromArray(sourceProperty);\n break;\n case 6: // Mesh reference\n if (scene) {\n dest[property] = scene.getLastMeshById(sourceProperty);\n }\n break;\n case 7: // Color Curves\n dest[property] = SerializationHelper._ColorCurvesParser(sourceProperty);\n break;\n case 8: // Color 4\n dest[property] = Color4.FromArray(sourceProperty);\n break;\n case 9: // Image Processing\n dest[property] = SerializationHelper._ImageProcessingConfigurationParser(sourceProperty);\n break;\n case 10: // Quaternion\n dest[property] = Quaternion.FromArray(sourceProperty);\n break;\n case 11: // Camera reference\n if (scene) {\n dest[property] = scene.getCameraById(sourceProperty);\n }\n break;\n case 12: // Matrix\n dest[property] = Matrix.FromArray(sourceProperty);\n break;\n }\n }\n }\n }\n /**\n * Creates a new entity from a serialization data object\n * @param creationFunction defines a function used to instanciated the new entity\n * @param source defines the source serialization data\n * @param scene defines the hosting scene\n * @param rootUrl defines the root url for resources\n * @returns a new entity\n */\n static Parse(creationFunction, source, scene, rootUrl = null) {\n const destination = creationFunction();\n // Tags\n if (Tags) {\n Tags.AddTagsTo(destination, source.tags);\n }\n SerializationHelper.ParseProperties(source, destination, scene, rootUrl);\n return destination;\n }\n /**\n * Clones an object\n * @param creationFunction defines the function used to instanciate the new object\n * @param source defines the source object\n * @returns the cloned object\n */\n static Clone(creationFunction, source, options = {}) {\n return _copySource(creationFunction, source, false, options);\n }\n /**\n * Instanciates a new object based on a source one (some data will be shared between both object)\n * @param creationFunction defines the function used to instanciate the new object\n * @param source defines the source object\n * @returns the new object\n */\n static Instanciate(creationFunction, source) {\n return _copySource(creationFunction, source, true);\n }\n}\n/**\n * Gets or sets a boolean to indicate if the UniqueId property should be serialized\n */\nSerializationHelper.AllowLoadingUniqueId = false;\n/**\n * @internal\n */\nSerializationHelper._ImageProcessingConfigurationParser = (sourceProperty) => {\n throw _WarnImport(\"ImageProcessingConfiguration\");\n};\n/**\n * @internal\n */\nSerializationHelper._FresnelParametersParser = (sourceProperty) => {\n throw _WarnImport(\"FresnelParameters\");\n};\n/**\n * @internal\n */\nSerializationHelper._ColorCurvesParser = (sourceProperty) => {\n throw _WarnImport(\"ColorCurves\");\n};\n/**\n * @internal\n */\nSerializationHelper._TextureParser = (sourceProperty, scene, rootUrl) => {\n throw _WarnImport(\"Texture\");\n};\n/**\n * Decorator used to redirect a function to a native implementation if available.\n * @internal\n */\nexport function nativeOverride(target, propertyKey, descriptor, predicate) {\n // Cache the original JS function for later.\n const jsFunc = descriptor.value;\n // Override the JS function to check for a native override on first invocation. Setting descriptor.value overrides the function at the early stage of code being loaded/imported.\n descriptor.value = (...params) => {\n // Assume the resolved function will be the original JS function, then we will check for the Babylon Native context.\n let func = jsFunc;\n // Check if we are executing in a Babylon Native context (e.g. check the presence of the _native global property) and if so also check if a function override is available.\n if (typeof _native !== \"undefined\" && _native[propertyKey]) {\n const nativeFunc = _native[propertyKey];\n // If a predicate was provided, then we'll need to invoke the predicate on each invocation of the underlying function to determine whether to call the native function or the JS function.\n if (predicate) {\n // The resolved function will execute the predicate and then either execute the native function or the JS function.\n func = (...params) => (predicate(...params) ? nativeFunc(...params) : jsFunc(...params));\n }\n else {\n // The resolved function will directly execute the native function.\n func = nativeFunc;\n }\n }\n // Override the JS function again with the final resolved target function.\n target[propertyKey] = func;\n // The JS function has now been overridden based on whether we're executing in the context of Babylon Native, but we still need to invoke that function.\n // Future invocations of the function will just directly invoke the final overridden function, not any of the decorator setup logic above.\n return func(...params);\n };\n}\n/**\n * Decorator factory that applies the nativeOverride decorator, but determines whether to redirect to the native implementation based on a filter function that evaluates the function arguments.\n * @param predicate\n * @example @nativeOverride.filter((...[arg1]: Parameters) => arg1.length > 20)\n * public someMethod(arg1: string, arg2: number): string {\n * @internal\n */\nnativeOverride.filter = function (predicate) {\n return (target, propertyKey, descriptor) => nativeOverride(target, propertyKey, descriptor, predicate);\n};\n//# sourceMappingURL=decorators.js.map","import { Logger } from \"./logger.js\";\nconst CloneValue = (source, destinationObject) => {\n if (!source) {\n return null;\n }\n if (source.getClassName && source.getClassName() === \"Mesh\") {\n return null;\n }\n if (source.getClassName && (source.getClassName() === \"SubMesh\" || source.getClassName() === \"PhysicsBody\")) {\n return source.clone(destinationObject);\n }\n else if (source.clone) {\n return source.clone();\n }\n else if (Array.isArray(source)) {\n return source.slice();\n }\n return null;\n};\nfunction GetAllPropertyNames(obj) {\n const props = [];\n do {\n Object.getOwnPropertyNames(obj).forEach(function (prop) {\n if (props.indexOf(prop) === -1) {\n props.push(prop);\n }\n });\n } while ((obj = Object.getPrototypeOf(obj)));\n return props;\n}\n/**\n * Class containing a set of static utilities functions for deep copy.\n */\nexport class DeepCopier {\n /**\n * Tries to copy an object by duplicating every property\n * @param source defines the source object\n * @param destination defines the target object\n * @param doNotCopyList defines a list of properties to avoid\n * @param mustCopyList defines a list of properties to copy (even if they start with _)\n */\n static DeepCopy(source, destination, doNotCopyList, mustCopyList) {\n const properties = GetAllPropertyNames(source);\n for (const prop of properties) {\n if (prop[0] === \"_\" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {\n continue;\n }\n if (prop.endsWith(\"Observable\")) {\n continue;\n }\n if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {\n continue;\n }\n const sourceValue = source[prop];\n const typeOfSourceValue = typeof sourceValue;\n if (typeOfSourceValue === \"function\") {\n continue;\n }\n try {\n if (typeOfSourceValue === \"object\") {\n if (sourceValue instanceof Uint8Array) {\n destination[prop] = Uint8Array.from(sourceValue);\n }\n else if (sourceValue instanceof Array) {\n destination[prop] = [];\n if (sourceValue.length > 0) {\n if (typeof sourceValue[0] == \"object\") {\n for (let index = 0; index < sourceValue.length; index++) {\n const clonedValue = CloneValue(sourceValue[index], destination);\n if (destination[prop].indexOf(clonedValue) === -1) {\n // Test if auto inject was not done\n destination[prop].push(clonedValue);\n }\n }\n }\n else {\n destination[prop] = sourceValue.slice(0);\n }\n }\n }\n else {\n destination[prop] = CloneValue(sourceValue, destination);\n }\n }\n else {\n destination[prop] = sourceValue;\n }\n }\n catch (e) {\n // Log a warning (it could be because of a read-only property)\n Logger.Warn(e.message);\n }\n }\n }\n}\n//# sourceMappingURL=deepCopier.js.map","/**\n * @internal\n */\nexport function _WarnImport(name) {\n return `${name} needs to be imported before as it contains a side-effect required by your code.`;\n}\n//# sourceMappingURL=devTools.js.map","/* eslint-disable @typescript-eslint/naming-convention */\n/**\n * Checks if the window object exists\n * @returns true if the window object exists\n */\nexport function IsWindowObjectExist() {\n return typeof window !== \"undefined\";\n}\n/**\n * Checks if the navigator object exists\n * @returns true if the navigator object exists\n */\nexport function IsNavigatorAvailable() {\n return typeof navigator !== \"undefined\";\n}\n/**\n * Check if the document object exists\n * @returns true if the document object exists\n */\nexport function IsDocumentAvailable() {\n return typeof document !== \"undefined\";\n}\n/**\n * Extracts text content from a DOM element hierarchy\n * @param element defines the root element\n * @returns a string\n */\nexport function GetDOMTextContent(element) {\n let result = \"\";\n let child = element.firstChild;\n while (child) {\n if (child.nodeType === 3) {\n result += child.textContent;\n }\n child = child.nextSibling;\n }\n return result;\n}\n/**\n * Sets of helpers dealing with the DOM and some of the recurrent functions needed in\n * Babylon.js\n */\nexport const DomManagement = {\n /**\n * Checks if the window object exists\n * @returns true if the window object exists\n */\n IsWindowObjectExist,\n /**\n * Checks if the navigator object exists\n * @returns true if the navigator object exists\n */\n IsNavigatorAvailable,\n /**\n * Check if the document object exists\n * @returns true if the document object exists\n */\n IsDocumentAvailable,\n /**\n * Extracts text content from a DOM element hierarchy\n * @param element defines the root element\n * @returns a string\n */\n GetDOMTextContent,\n};\n//# sourceMappingURL=domManagement.js.map","/* eslint-disable @typescript-eslint/naming-convention */\n/**\n * Base error. Due to limitations of typedoc-check and missing documentation\n * in lib.es5.d.ts, cannot extend Error directly for RuntimeError.\n * @ignore\n */\nexport class BaseError extends Error {\n}\n// See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript\n// and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work\n// Polyfill for Object.setPrototypeOf if necessary.\nBaseError._setPrototypeOf = Object.setPrototypeOf ||\n ((o, proto) => {\n o.__proto__ = proto;\n return o;\n });\n/* IMP! DO NOT CHANGE THE NUMBERING OF EXISTING ERROR CODES */\n/**\n * Error codes for BaseError\n */\nexport const ErrorCodes = {\n // Mesh errors 0-999\n /** Invalid or empty mesh vertex positions. */\n MeshInvalidPositionsError: 0,\n // Texture errors 1000-1999\n /** Unsupported texture found. */\n UnsupportedTextureError: 1000,\n // GLTFLoader errors 2000-2999\n /** Unexpected magic number found in GLTF file header. */\n GLTFLoaderUnexpectedMagicError: 2000,\n // SceneLoader errors 3000-3999\n /** SceneLoader generic error code. Ideally wraps the inner exception. */\n SceneLoaderError: 3000,\n // File related errors 4000-4999\n /** Load file error */\n LoadFileError: 4000,\n /** Request file error */\n RequestFileError: 4001,\n /** Read file error */\n ReadFileError: 4002,\n};\n/**\n * Application runtime error\n */\nexport class RuntimeError extends BaseError {\n /**\n * Creates a new RuntimeError\n * @param message defines the message of the error\n * @param errorCode the error code\n * @param innerError the error that caused the outer error\n */\n constructor(message, errorCode, innerError) {\n super(message);\n this.errorCode = errorCode;\n this.innerError = innerError;\n this.name = \"RuntimeError\";\n BaseError._setPrototypeOf(this, RuntimeError.prototype);\n }\n}\n//# sourceMappingURL=error.js.map","/* eslint-disable @typescript-eslint/naming-convention */\nimport { WebRequest } from \"./webRequest.js\";\nimport { IsWindowObjectExist } from \"./domManagement.js\";\nimport { Observable } from \"./observable.js\";\nimport { FilesInputStore } from \"./filesInputStore.js\";\nimport { RetryStrategy } from \"./retryStrategy.js\";\nimport { BaseError, ErrorCodes, RuntimeError } from \"./error.js\";\nimport { DecodeBase64ToBinary, DecodeBase64ToString, EncodeArrayBufferToBase64 } from \"./stringTools.js\";\nimport { ShaderProcessor } from \"../Engines/Processors/shaderProcessor.js\";\nimport { ThinEngine } from \"../Engines/thinEngine.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { Logger } from \"./logger.js\";\nimport { TimingTools } from \"./timingTools.js\";\nconst Base64DataUrlRegEx = new RegExp(/^data:([^,]+\\/[^,]+)?;base64,/i);\n/** @ignore */\nexport class LoadFileError extends RuntimeError {\n /**\n * Creates a new LoadFileError\n * @param message defines the message of the error\n * @param object defines the optional web request\n */\n constructor(message, object) {\n super(message, ErrorCodes.LoadFileError);\n this.name = \"LoadFileError\";\n BaseError._setPrototypeOf(this, LoadFileError.prototype);\n if (object instanceof WebRequest) {\n this.request = object;\n }\n else {\n this.file = object;\n }\n }\n}\n/** @ignore */\nexport class RequestFileError extends RuntimeError {\n /**\n * Creates a new LoadFileError\n * @param message defines the message of the error\n * @param request defines the optional web request\n */\n constructor(message, request) {\n super(message, ErrorCodes.RequestFileError);\n this.request = request;\n this.name = \"RequestFileError\";\n BaseError._setPrototypeOf(this, RequestFileError.prototype);\n }\n}\n/** @ignore */\nexport class ReadFileError extends RuntimeError {\n /**\n * Creates a new ReadFileError\n * @param message defines the message of the error\n * @param file defines the optional file\n */\n constructor(message, file) {\n super(message, ErrorCodes.ReadFileError);\n this.file = file;\n this.name = \"ReadFileError\";\n BaseError._setPrototypeOf(this, ReadFileError.prototype);\n }\n}\n/**\n * @internal\n */\nexport const FileToolsOptions = {\n /**\n * Gets or sets the retry strategy to apply when an error happens while loading an asset.\n * When defining this function, return the wait time before trying again or return -1 to\n * stop retrying and error out.\n */\n DefaultRetryStrategy: RetryStrategy.ExponentialBackoff(),\n /**\n * Gets or sets the base URL to use to load assets\n */\n BaseUrl: \"\",\n /**\n * Default behaviour for cors in the application.\n * It can be a string if the expected behavior is identical in the entire app.\n * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)\n */\n CorsBehavior: \"anonymous\",\n /**\n * Gets or sets a function used to pre-process url before using them to load assets\n * @param url\n */\n PreprocessUrl: (url) => {\n return url;\n },\n};\n/**\n * Removes unwanted characters from an url\n * @param url defines the url to clean\n * @returns the cleaned url\n */\nconst _CleanUrl = (url) => {\n url = url.replace(/#/gm, \"%23\");\n return url;\n};\n/**\n * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.\n * @param url define the url we are trying\n * @param element define the dom element where to configure the cors policy\n * @internal\n */\nexport const SetCorsBehavior = (url, element) => {\n if (url && url.indexOf(\"data:\") === 0) {\n return;\n }\n if (FileToolsOptions.CorsBehavior) {\n if (typeof FileToolsOptions.CorsBehavior === \"string\" || FileToolsOptions.CorsBehavior instanceof String) {\n element.crossOrigin = FileToolsOptions.CorsBehavior;\n }\n else {\n const result = FileToolsOptions.CorsBehavior(url);\n if (result) {\n element.crossOrigin = result;\n }\n }\n }\n};\n/**\n * Loads an image as an HTMLImageElement.\n * @param input url string, ArrayBuffer, or Blob to load\n * @param onLoad callback called when the image successfully loads\n * @param onError callback called when the image fails to load\n * @param offlineProvider offline provider for caching\n * @param mimeType optional mime type\n * @param imageBitmapOptions\n * @returns the HTMLImageElement of the loaded image\n * @internal\n */\nexport const LoadImage = (input, onLoad, onError, offlineProvider, mimeType = \"\", imageBitmapOptions) => {\n var _a;\n let url;\n let usingObjectURL = false;\n if (input instanceof ArrayBuffer || ArrayBuffer.isView(input)) {\n if (typeof Blob !== \"undefined\" && typeof URL !== \"undefined\") {\n url = URL.createObjectURL(new Blob([input], { type: mimeType }));\n usingObjectURL = true;\n }\n else {\n url = `data:${mimeType};base64,` + EncodeArrayBufferToBase64(input);\n }\n }\n else if (input instanceof Blob) {\n url = URL.createObjectURL(input);\n usingObjectURL = true;\n }\n else {\n url = _CleanUrl(input);\n url = FileToolsOptions.PreprocessUrl(input);\n }\n const engine = EngineStore.LastCreatedEngine;\n const onErrorHandler = (exception) => {\n if (onError) {\n const inputText = url || input.toString();\n onError(`Error while trying to load image: ${inputText.indexOf(\"http\") === 0 || inputText.length <= 128 ? inputText : inputText.slice(0, 128) + \"...\"}`, exception);\n }\n };\n if (typeof Image === \"undefined\" || ((_a = engine === null || engine === void 0 ? void 0 : engine._features.forceBitmapOverHTMLImageElement) !== null && _a !== void 0 ? _a : false)) {\n LoadFile(url, (data) => {\n engine\n .createImageBitmap(new Blob([data], { type: mimeType }), Object.assign({ premultiplyAlpha: \"none\" }, imageBitmapOptions))\n .then((imgBmp) => {\n onLoad(imgBmp);\n if (usingObjectURL) {\n URL.revokeObjectURL(url);\n }\n })\n .catch((reason) => {\n if (onError) {\n onError(\"Error while trying to load image: \" + input, reason);\n }\n });\n }, undefined, offlineProvider || undefined, true, (request, exception) => {\n onErrorHandler(exception);\n });\n return null;\n }\n const img = new Image();\n SetCorsBehavior(url, img);\n const handlersList = [];\n const loadHandlersList = () => {\n handlersList.forEach((handler) => {\n handler.target.addEventListener(handler.name, handler.handler);\n });\n };\n const unloadHandlersList = () => {\n handlersList.forEach((handler) => {\n handler.target.removeEventListener(handler.name, handler.handler);\n });\n handlersList.length = 0;\n };\n const loadHandler = () => {\n unloadHandlersList();\n onLoad(img);\n // Must revoke the URL after calling onLoad to avoid security exceptions in\n // certain scenarios (e.g. when hosted in vscode).\n if (usingObjectURL && img.src) {\n URL.revokeObjectURL(img.src);\n }\n };\n const errorHandler = (err) => {\n unloadHandlersList();\n onErrorHandler(err);\n if (usingObjectURL && img.src) {\n URL.revokeObjectURL(img.src);\n }\n };\n const cspHandler = (err) => {\n if (err.blockedURI !== img.src) {\n return;\n }\n unloadHandlersList();\n const cspException = new Error(`CSP violation of policy ${err.effectiveDirective} ${err.blockedURI}. Current policy is ${err.originalPolicy}`);\n EngineStore.UseFallbackTexture = false;\n onErrorHandler(cspException);\n if (usingObjectURL && img.src) {\n URL.revokeObjectURL(img.src);\n }\n img.src = \"\";\n };\n handlersList.push({ target: img, name: \"load\", handler: loadHandler });\n handlersList.push({ target: img, name: \"error\", handler: errorHandler });\n handlersList.push({ target: document, name: \"securitypolicyviolation\", handler: cspHandler });\n loadHandlersList();\n const fromBlob = url.substring(0, 5) === \"blob:\";\n const fromData = url.substring(0, 5) === \"data:\";\n const noOfflineSupport = () => {\n if (fromBlob || fromData) {\n img.src = url;\n }\n else {\n LoadFile(url, (data, _, contentType) => {\n const type = !mimeType && contentType ? contentType : mimeType;\n const blob = new Blob([data], { type });\n const url = URL.createObjectURL(blob);\n usingObjectURL = true;\n img.src = url;\n }, undefined, offlineProvider || undefined, true, (request, exception) => {\n onErrorHandler(exception);\n });\n }\n };\n const loadFromOfflineSupport = () => {\n if (offlineProvider) {\n offlineProvider.loadImage(url, img);\n }\n };\n if (!fromBlob && !fromData && offlineProvider && offlineProvider.enableTexturesOffline) {\n offlineProvider.open(loadFromOfflineSupport, noOfflineSupport);\n }\n else {\n if (url.indexOf(\"file:\") !== -1) {\n const textureName = decodeURIComponent(url.substring(5).toLowerCase());\n if (FilesInputStore.FilesToLoad[textureName] && typeof URL !== \"undefined\") {\n try {\n let blobURL;\n try {\n blobURL = URL.createObjectURL(FilesInputStore.FilesToLoad[textureName]);\n }\n catch (ex) {\n // Chrome doesn't support oneTimeOnly parameter\n blobURL = URL.createObjectURL(FilesInputStore.FilesToLoad[textureName]);\n }\n img.src = blobURL;\n usingObjectURL = true;\n }\n catch (e) {\n img.src = \"\";\n }\n return img;\n }\n }\n noOfflineSupport();\n }\n return img;\n};\n/**\n * Reads a file from a File object\n * @param file defines the file to load\n * @param onSuccess defines the callback to call when data is loaded\n * @param onProgress defines the callback to call during loading process\n * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer\n * @param onError defines the callback to call when an error occurs\n * @returns a file request object\n * @internal\n */\nexport const ReadFile = (file, onSuccess, onProgress, useArrayBuffer, onError) => {\n const reader = new FileReader();\n const fileRequest = {\n onCompleteObservable: new Observable(),\n abort: () => reader.abort(),\n };\n reader.onloadend = () => fileRequest.onCompleteObservable.notifyObservers(fileRequest);\n if (onError) {\n reader.onerror = () => {\n onError(new ReadFileError(`Unable to read ${file.name}`, file));\n };\n }\n reader.onload = (e) => {\n //target doesn't have result from ts 1.3\n onSuccess(e.target[\"result\"]);\n };\n if (onProgress) {\n reader.onprogress = onProgress;\n }\n if (!useArrayBuffer) {\n // Asynchronous read\n reader.readAsText(file);\n }\n else {\n reader.readAsArrayBuffer(file);\n }\n return fileRequest;\n};\n/**\n * Loads a file from a url, a data url, or a file url\n * @param fileOrUrl file, url, data url, or file url to load\n * @param onSuccess callback called when the file successfully loads\n * @param onProgress callback called while file is loading (if the server supports this mode)\n * @param offlineProvider defines the offline provider for caching\n * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer\n * @param onError callback called when the file fails to load\n * @param onOpened\n * @returns a file request object\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const LoadFile = (fileOrUrl, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError, onOpened) => {\n if (fileOrUrl.name) {\n return ReadFile(fileOrUrl, onSuccess, onProgress, useArrayBuffer, onError\n ? (error) => {\n onError(undefined, error);\n }\n : undefined);\n }\n const url = fileOrUrl;\n // If file and file input are set\n if (url.indexOf(\"file:\") !== -1) {\n let fileName = decodeURIComponent(url.substring(5).toLowerCase());\n if (fileName.indexOf(\"./\") === 0) {\n fileName = fileName.substring(2);\n }\n const file = FilesInputStore.FilesToLoad[fileName];\n if (file) {\n return ReadFile(file, onSuccess, onProgress, useArrayBuffer, onError ? (error) => onError(undefined, new LoadFileError(error.message, error.file)) : undefined);\n }\n }\n // For a Base64 Data URL\n const { match, type } = TestBase64DataUrl(url);\n if (match) {\n const fileRequest = {\n onCompleteObservable: new Observable(),\n abort: () => () => { },\n };\n try {\n const data = useArrayBuffer ? DecodeBase64UrlToBinary(url) : DecodeBase64UrlToString(url);\n onSuccess(data, undefined, type);\n }\n catch (error) {\n if (onError) {\n onError(undefined, error);\n }\n else {\n Logger.Error(error.message || \"Failed to parse the Data URL\");\n }\n }\n TimingTools.SetImmediate(() => {\n fileRequest.onCompleteObservable.notifyObservers(fileRequest);\n });\n return fileRequest;\n }\n return RequestFile(url, (data, request) => {\n onSuccess(data, request === null || request === void 0 ? void 0 : request.responseURL, request === null || request === void 0 ? void 0 : request.getResponseHeader(\"content-type\"));\n }, onProgress, offlineProvider, useArrayBuffer, onError\n ? (error) => {\n onError(error.request, new LoadFileError(error.message, error.request));\n }\n : undefined, onOpened);\n};\n/**\n * Loads a file from a url\n * @param url url to load\n * @param onSuccess callback called when the file successfully loads\n * @param onProgress callback called while file is loading (if the server supports this mode)\n * @param offlineProvider defines the offline provider for caching\n * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer\n * @param onError callback called when the file fails to load\n * @param onOpened callback called when the web request is opened\n * @returns a file request object\n * @internal\n */\nexport const RequestFile = (url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError, onOpened) => {\n url = _CleanUrl(url);\n url = FileToolsOptions.PreprocessUrl(url);\n const loadUrl = FileToolsOptions.BaseUrl + url;\n let aborted = false;\n const fileRequest = {\n onCompleteObservable: new Observable(),\n abort: () => (aborted = true),\n };\n const requestFile = () => {\n let request = new WebRequest();\n let retryHandle = null;\n let onReadyStateChange;\n const unbindEvents = () => {\n if (!request) {\n return;\n }\n if (onProgress) {\n request.removeEventListener(\"progress\", onProgress);\n }\n if (onReadyStateChange) {\n request.removeEventListener(\"readystatechange\", onReadyStateChange);\n }\n request.removeEventListener(\"loadend\", onLoadEnd);\n };\n let onLoadEnd = () => {\n unbindEvents();\n fileRequest.onCompleteObservable.notifyObservers(fileRequest);\n fileRequest.onCompleteObservable.clear();\n onProgress = undefined;\n onReadyStateChange = null;\n onLoadEnd = null;\n onError = undefined;\n onOpened = undefined;\n onSuccess = undefined;\n };\n fileRequest.abort = () => {\n aborted = true;\n if (onLoadEnd) {\n onLoadEnd();\n }\n if (request && request.readyState !== (XMLHttpRequest.DONE || 4)) {\n request.abort();\n }\n if (retryHandle !== null) {\n clearTimeout(retryHandle);\n retryHandle = null;\n }\n request = null;\n };\n const handleError = (error) => {\n const message = error.message || \"Unknown error\";\n if (onError && request) {\n onError(new RequestFileError(message, request));\n }\n else {\n Logger.Error(message);\n }\n };\n const retryLoop = (retryIndex) => {\n if (!request) {\n return;\n }\n request.open(\"GET\", loadUrl);\n if (onOpened) {\n try {\n onOpened(request);\n }\n catch (e) {\n handleError(e);\n return;\n }\n }\n if (useArrayBuffer) {\n request.responseType = \"arraybuffer\";\n }\n if (onProgress) {\n request.addEventListener(\"progress\", onProgress);\n }\n if (onLoadEnd) {\n request.addEventListener(\"loadend\", onLoadEnd);\n }\n onReadyStateChange = () => {\n if (aborted || !request) {\n return;\n }\n // In case of undefined state in some browsers.\n if (request.readyState === (XMLHttpRequest.DONE || 4)) {\n // Some browsers have issues where onreadystatechange can be called multiple times with the same value.\n if (onReadyStateChange) {\n request.removeEventListener(\"readystatechange\", onReadyStateChange);\n }\n if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!IsWindowObjectExist() || IsFileURL()))) {\n try {\n if (onSuccess) {\n onSuccess(useArrayBuffer ? request.response : request.responseText, request);\n }\n }\n catch (e) {\n handleError(e);\n }\n return;\n }\n const retryStrategy = FileToolsOptions.DefaultRetryStrategy;\n if (retryStrategy) {\n const waitTime = retryStrategy(loadUrl, request, retryIndex);\n if (waitTime !== -1) {\n // Prevent the request from completing for retry.\n unbindEvents();\n request = new WebRequest();\n retryHandle = setTimeout(() => retryLoop(retryIndex + 1), waitTime);\n return;\n }\n }\n const error = new RequestFileError(\"Error status: \" + request.status + \" \" + request.statusText + \" - Unable to load \" + loadUrl, request);\n if (onError) {\n onError(error);\n }\n }\n };\n request.addEventListener(\"readystatechange\", onReadyStateChange);\n request.send();\n };\n retryLoop(0);\n };\n // Caching all files\n if (offlineProvider && offlineProvider.enableSceneOffline) {\n const noOfflineSupport = (request) => {\n if (request && request.status > 400) {\n if (onError) {\n onError(request);\n }\n }\n else {\n requestFile();\n }\n };\n const loadFromOfflineSupport = () => {\n // TODO: database needs to support aborting and should return a IFileRequest\n if (offlineProvider) {\n offlineProvider.loadFile(FileToolsOptions.BaseUrl + url, (data) => {\n if (!aborted && onSuccess) {\n onSuccess(data);\n }\n fileRequest.onCompleteObservable.notifyObservers(fileRequest);\n }, onProgress\n ? (event) => {\n if (!aborted && onProgress) {\n onProgress(event);\n }\n }\n : undefined, noOfflineSupport, useArrayBuffer);\n }\n };\n offlineProvider.open(loadFromOfflineSupport, noOfflineSupport);\n }\n else {\n requestFile();\n }\n return fileRequest;\n};\n/**\n * Checks if the loaded document was accessed via `file:`-Protocol.\n * @returns boolean\n * @internal\n */\nexport const IsFileURL = () => {\n return typeof location !== \"undefined\" && location.protocol === \"file:\";\n};\n/**\n * Test if the given uri is a valid base64 data url\n * @param uri The uri to test\n * @returns True if the uri is a base64 data url or false otherwise\n * @internal\n */\nexport const IsBase64DataUrl = (uri) => {\n return Base64DataUrlRegEx.test(uri);\n};\nexport const TestBase64DataUrl = (uri) => {\n const results = Base64DataUrlRegEx.exec(uri);\n if (results === null || results.length === 0) {\n return { match: false, type: \"\" };\n }\n else {\n const type = results[0].replace(\"data:\", \"\").replace(\"base64,\", \"\");\n return { match: true, type };\n }\n};\n/**\n * Decode the given base64 uri.\n * @param uri The uri to decode\n * @returns The decoded base64 data.\n * @internal\n */\nexport function DecodeBase64UrlToBinary(uri) {\n return DecodeBase64ToBinary(uri.split(\",\")[1]);\n}\n/**\n * Decode the given base64 uri into a UTF-8 encoded string.\n * @param uri The uri to decode\n * @returns The decoded base64 data.\n * @internal\n */\nexport const DecodeBase64UrlToString = (uri) => {\n return DecodeBase64ToString(uri.split(\",\")[1]);\n};\n/**\n * This will be executed automatically for UMD and es5.\n * If esm dev wants the side effects to execute they will have to run it manually\n * Once we build native modules those need to be exported.\n * @internal\n */\nconst initSideEffects = () => {\n ThinEngine._FileToolsLoadImage = LoadImage;\n ThinEngine._FileToolsLoadFile = LoadFile;\n ShaderProcessor._FileToolsLoadFile = LoadFile;\n};\ninitSideEffects();\n/**\n* FileTools defined as any.\n* This should not be imported or used in future releases or in any module in the framework\n* @internal\n* @deprecated import the needed function from fileTools.ts\n*/\nexport let FileTools;\n/**\n * @param DecodeBase64UrlToBinary\n * @param DecodeBase64UrlToString\n * @param FileToolsOptions\n * @internal\n */\nexport const _injectLTSFileTools = (DecodeBase64UrlToBinary, DecodeBase64UrlToString, FileToolsOptions, IsBase64DataUrl, IsFileURL, LoadFile, LoadImage, ReadFile, RequestFile, SetCorsBehavior) => {\n /**\n * Backwards compatibility.\n * @internal\n * @deprecated\n */\n FileTools = {\n DecodeBase64UrlToBinary,\n DecodeBase64UrlToString,\n DefaultRetryStrategy: FileToolsOptions.DefaultRetryStrategy,\n BaseUrl: FileToolsOptions.BaseUrl,\n CorsBehavior: FileToolsOptions.CorsBehavior,\n PreprocessUrl: FileToolsOptions.PreprocessUrl,\n IsBase64DataUrl,\n IsFileURL,\n LoadFile,\n LoadImage,\n ReadFile,\n RequestFile,\n SetCorsBehavior,\n };\n Object.defineProperty(FileTools, \"DefaultRetryStrategy\", {\n get: function () {\n return FileToolsOptions.DefaultRetryStrategy;\n },\n set: function (value) {\n FileToolsOptions.DefaultRetryStrategy = value;\n },\n });\n Object.defineProperty(FileTools, \"BaseUrl\", {\n get: function () {\n return FileToolsOptions.BaseUrl;\n },\n set: function (value) {\n FileToolsOptions.BaseUrl = value;\n },\n });\n Object.defineProperty(FileTools, \"PreprocessUrl\", {\n get: function () {\n return FileToolsOptions.PreprocessUrl;\n },\n set: function (value) {\n FileToolsOptions.PreprocessUrl = value;\n },\n });\n Object.defineProperty(FileTools, \"CorsBehavior\", {\n get: function () {\n return FileToolsOptions.CorsBehavior;\n },\n set: function (value) {\n FileToolsOptions.CorsBehavior = value;\n },\n });\n};\n_injectLTSFileTools(DecodeBase64UrlToBinary, DecodeBase64UrlToString, FileToolsOptions, IsBase64DataUrl, IsFileURL, LoadFile, LoadImage, ReadFile, RequestFile, SetCorsBehavior);\n//# sourceMappingURL=fileTools.js.map","import { Logger } from \"./logger.js\";\nimport { GetClass } from \"./typeStore.js\";\n/**\n * Class used to enable instantiation of objects by class name\n */\nexport class InstantiationTools {\n /**\n * Tries to instantiate a new object from a given class name\n * @param className defines the class name to instantiate\n * @returns the new object or null if the system was not able to do the instantiation\n */\n static Instantiate(className) {\n if (this.RegisteredExternalClasses && this.RegisteredExternalClasses[className]) {\n return this.RegisteredExternalClasses[className];\n }\n const internalClass = GetClass(className);\n if (internalClass) {\n return internalClass;\n }\n Logger.Warn(className + \" not found, you may have missed an import.\");\n const arr = className.split(\".\");\n let fn = window || this;\n for (let i = 0, len = arr.length; i < len; i++) {\n fn = fn[arr[i]];\n }\n if (typeof fn !== \"function\") {\n return null;\n }\n return fn;\n }\n}\n/**\n * Use this object to register external classes like custom textures or material\n * to allow the loaders to instantiate them\n */\nInstantiationTools.RegisteredExternalClasses = {};\n//# sourceMappingURL=instantiationTools.js.map","/**\n * Class used to help managing file picking and drag'n'drop\n * File Storage\n */\nexport class FilesInputStore {\n}\n/**\n * List of files ready to be loaded\n */\nFilesInputStore.FilesToLoad = {};\n//# sourceMappingURL=filesInputStore.js.map","/**\n * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523\n * Be aware Math.random() could cause collisions, but:\n * \"All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide\"\n * @returns a pseudo random id\n */\nexport function RandomGUID() {\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0, v = c === \"x\" ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n/**\n * Class used to manipulate GUIDs\n */\nexport const GUID = {\n /**\n * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523\n * Be aware Math.random() could cause collisions, but:\n * \"All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide\"\n * @returns a pseudo random id\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n RandomId: RandomGUID,\n};\n//# sourceMappingURL=guid.js.map","/**\n * Logger used throughout the application to allow configuration of\n * the log level required for the messages.\n */\nexport class Logger {\n static _CheckLimit(message, limit) {\n let entry = Logger._LogLimitOutputs[message];\n if (!entry) {\n entry = { limit, current: 1 };\n Logger._LogLimitOutputs[message] = entry;\n }\n else {\n entry.current++;\n }\n return entry.current <= entry.limit;\n }\n static _GenerateLimitMessage(message, level = 1) {\n var _a;\n const entry = Logger._LogLimitOutputs[message];\n if (!entry || !Logger.MessageLimitReached) {\n return;\n }\n const type = this._Levels[level];\n if (entry.current === entry.limit) {\n Logger[type.name](Logger.MessageLimitReached.replace(/%LIMIT%/g, \"\" + entry.limit).replace(/%TYPE%/g, (_a = type.name) !== null && _a !== void 0 ? _a : \"\"));\n }\n }\n static _AddLogEntry(entry) {\n Logger._LogCache = entry + Logger._LogCache;\n if (Logger.OnNewCacheEntry) {\n Logger.OnNewCacheEntry(entry);\n }\n }\n static _FormatMessage(message) {\n const padStr = (i) => (i < 10 ? \"0\" + i : \"\" + i);\n const date = new Date();\n return \"[\" + padStr(date.getHours()) + \":\" + padStr(date.getMinutes()) + \":\" + padStr(date.getSeconds()) + \"]: \" + message;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n static _LogDisabled(message, limit) {\n // nothing to do\n }\n static _LogEnabled(level = 1, message, limit) {\n if (limit !== undefined && !Logger._CheckLimit(message, limit)) {\n return;\n }\n const formattedMessage = Logger._FormatMessage(message);\n const type = this._Levels[level];\n type.logFunc && type.logFunc(\"BJS - \" + formattedMessage);\n const entry = `
${formattedMessage}

`;\n Logger._AddLogEntry(entry);\n Logger._GenerateLimitMessage(message, level);\n }\n /**\n * Gets current log cache (list of logs)\n */\n static get LogCache() {\n return Logger._LogCache;\n }\n /**\n * Clears the log cache\n */\n static ClearLogCache() {\n Logger._LogCache = \"\";\n Logger._LogLimitOutputs = {};\n Logger.errorsCount = 0;\n }\n /**\n * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)\n */\n static set LogLevels(level) {\n Logger.Log = Logger._LogDisabled;\n Logger.Warn = Logger._LogDisabled;\n Logger.Error = Logger._LogDisabled;\n [Logger.MessageLogLevel, Logger.WarningLogLevel, Logger.ErrorLogLevel].forEach((l) => {\n if ((level & l) === l) {\n const type = this._Levels[l];\n Logger[type.name] = Logger._LogEnabled.bind(Logger, l);\n }\n });\n }\n}\n/**\n * No log\n */\nLogger.NoneLogLevel = 0;\n/**\n * Only message logs\n */\nLogger.MessageLogLevel = 1;\n/**\n * Only warning logs\n */\nLogger.WarningLogLevel = 2;\n/**\n * Only error logs\n */\nLogger.ErrorLogLevel = 4;\n/**\n * All logs\n */\nLogger.AllLogLevel = 7;\n/**\n * Message to display when a message has been logged too many times\n */\nLogger.MessageLimitReached = \"Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.\";\nLogger._LogCache = \"\";\nLogger._LogLimitOutputs = {};\n// levels according to the (binary) numbering.\nLogger._Levels = [\n {},\n { color: \"white\", logFunc: console.log, name: \"Log\" },\n { color: \"orange\", logFunc: console.warn, name: \"Warn\" },\n {},\n { color: \"red\", logFunc: console.error, name: \"Error\" },\n];\n/**\n * Gets a value indicating the number of loading errors\n * @ignorenaming\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nLogger.errorsCount = 0;\n/**\n * Log a message to the console\n */\nLogger.Log = Logger._LogEnabled.bind(Logger, Logger.MessageLogLevel);\n/**\n * Write a warning message to the console\n */\nLogger.Warn = Logger._LogEnabled.bind(Logger, Logger.WarningLogLevel);\n/**\n * Write an error message to the console\n */\nLogger.Error = Logger._LogEnabled.bind(Logger, Logger.ErrorLogLevel);\n//# sourceMappingURL=logger.js.map","/**\n * A class serves as a medium between the observable and its observers\n */\nexport class EventState {\n /**\n * Create a new EventState\n * @param mask defines the mask associated with this state\n * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true\n * @param target defines the original target of the state\n * @param currentTarget defines the current target of the state\n */\n constructor(mask, skipNextObservers = false, target, currentTarget) {\n this.initialize(mask, skipNextObservers, target, currentTarget);\n }\n /**\n * Initialize the current event state\n * @param mask defines the mask associated with this state\n * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true\n * @param target defines the original target of the state\n * @param currentTarget defines the current target of the state\n * @returns the current event state\n */\n initialize(mask, skipNextObservers = false, target, currentTarget) {\n this.mask = mask;\n this.skipNextObservers = skipNextObservers;\n this.target = target;\n this.currentTarget = currentTarget;\n return this;\n }\n}\n/**\n * Represent an Observer registered to a given Observable object.\n */\nexport class Observer {\n /**\n * Creates a new observer\n * @param callback defines the callback to call when the observer is notified\n * @param mask defines the mask of the observer (used to filter notifications)\n * @param scope defines the current scope used to restore the JS context\n */\n constructor(\n /**\n * Defines the callback to call when the observer is notified\n */\n callback, \n /**\n * Defines the mask of the observer (used to filter notifications)\n */\n mask, \n /**\n * Defines the current scope used to restore the JS context\n */\n scope = null) {\n this.callback = callback;\n this.mask = mask;\n this.scope = scope;\n /** @internal */\n this._willBeUnregistered = false;\n /**\n * Gets or sets a property defining that the observer as to be unregistered after the next notification\n */\n this.unregisterOnNextCall = false;\n /**\n * this function can be used to remove the observer from the observable.\n * It will be set by the observable that the observer belongs to.\n * @internal\n */\n this._remove = null;\n }\n /**\n * Remove the observer from its observable\n * This can be used instead of using the observable's remove function.\n */\n remove() {\n if (this._remove) {\n this._remove();\n }\n }\n}\n/**\n * The Observable class is a simple implementation of the Observable pattern.\n *\n * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.\n * This enable a more fine grained execution without having to rely on multiple different Observable objects.\n * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).\n * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.\n */\nexport class Observable {\n /**\n * Create an observable from a Promise.\n * @param promise a promise to observe for fulfillment.\n * @param onErrorObservable an observable to notify if a promise was rejected.\n * @returns the new Observable\n */\n static FromPromise(promise, onErrorObservable) {\n const observable = new Observable();\n promise\n .then((ret) => {\n observable.notifyObservers(ret);\n })\n .catch((err) => {\n if (onErrorObservable) {\n onErrorObservable.notifyObservers(err);\n }\n else {\n throw err;\n }\n });\n return observable;\n }\n /**\n * Gets the list of observers\n * Note that observers that were recently deleted may still be present in the list because they are only really deleted on the next javascript tick!\n */\n get observers() {\n return this._observers;\n }\n /**\n * Creates a new observable\n * @param onObserverAdded defines a callback to call when a new observer is added\n * @param notifyIfTriggered If set to true the observable will notify when an observer was added if the observable was already triggered.\n */\n constructor(onObserverAdded, \n /**\n * If set to true the observable will notify when an observer was added if the observable was already triggered.\n * This is helpful to single-state observables like the scene onReady or the dispose observable.\n */\n notifyIfTriggered = false) {\n this.notifyIfTriggered = notifyIfTriggered;\n this._observers = new Array();\n this._numObserversMarkedAsDeleted = 0;\n this._hasNotified = false;\n this._eventState = new EventState(0);\n if (onObserverAdded) {\n this._onObserverAdded = onObserverAdded;\n }\n }\n /**\n * Create a new Observer with the specified callback\n * @param callback the callback that will be executed for that Observer\n * @param mask the mask used to filter observers\n * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.\n * @param scope optional scope for the callback to be called from\n * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification\n * @returns the new observer created for the callback\n */\n add(callback, mask = -1, insertFirst = false, scope = null, unregisterOnFirstCall = false) {\n if (!callback) {\n return null;\n }\n const observer = new Observer(callback, mask, scope);\n observer.unregisterOnNextCall = unregisterOnFirstCall;\n if (insertFirst) {\n this._observers.unshift(observer);\n }\n else {\n this._observers.push(observer);\n }\n if (this._onObserverAdded) {\n this._onObserverAdded(observer);\n }\n // If the observable was already triggered and the observable is set to notify if triggered, notify the new observer\n if (this._hasNotified && this.notifyIfTriggered) {\n if (this._lastNotifiedValue !== undefined) {\n this.notifyObserver(observer, this._lastNotifiedValue);\n }\n }\n // attach the remove function to the observer\n observer._remove = () => {\n this.remove(observer);\n };\n return observer;\n }\n /**\n * Create a new Observer with the specified callback and unregisters after the next notification\n * @param callback the callback that will be executed for that Observer\n * @returns the new observer created for the callback\n */\n addOnce(callback) {\n return this.add(callback, undefined, undefined, undefined, true);\n }\n /**\n * Remove an Observer from the Observable object\n * @param observer the instance of the Observer to remove\n * @returns false if it doesn't belong to this Observable\n */\n remove(observer) {\n if (!observer) {\n return false;\n }\n observer._remove = null;\n const index = this._observers.indexOf(observer);\n if (index !== -1) {\n this._deferUnregister(observer);\n return true;\n }\n return false;\n }\n /**\n * Remove a callback from the Observable object\n * @param callback the callback to remove\n * @param scope optional scope. If used only the callbacks with this scope will be removed\n * @returns false if it doesn't belong to this Observable\n */\n removeCallback(callback, scope) {\n for (let index = 0; index < this._observers.length; index++) {\n const observer = this._observers[index];\n if (observer._willBeUnregistered) {\n continue;\n }\n if (observer.callback === callback && (!scope || scope === observer.scope)) {\n this._deferUnregister(observer);\n return true;\n }\n }\n return false;\n }\n /**\n * @internal\n */\n _deferUnregister(observer) {\n if (observer._willBeUnregistered) {\n return;\n }\n this._numObserversMarkedAsDeleted++;\n observer.unregisterOnNextCall = false;\n observer._willBeUnregistered = true;\n setTimeout(() => {\n this._remove(observer);\n }, 0);\n }\n // This should only be called when not iterating over _observers to avoid callback skipping.\n // Removes an observer from the _observer Array.\n _remove(observer, updateCounter = true) {\n if (!observer) {\n return false;\n }\n const index = this._observers.indexOf(observer);\n if (index !== -1) {\n if (updateCounter) {\n this._numObserversMarkedAsDeleted--;\n }\n this._observers.splice(index, 1);\n return true;\n }\n return false;\n }\n /**\n * Moves the observable to the top of the observer list making it get called first when notified\n * @param observer the observer to move\n */\n makeObserverTopPriority(observer) {\n this._remove(observer, false);\n this._observers.unshift(observer);\n }\n /**\n * Moves the observable to the bottom of the observer list making it get called last when notified\n * @param observer the observer to move\n */\n makeObserverBottomPriority(observer) {\n this._remove(observer, false);\n this._observers.push(observer);\n }\n /**\n * Notify all Observers by calling their respective callback with the given data\n * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute\n * @param eventData defines the data to send to all observers\n * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)\n * @param target defines the original target of the state\n * @param currentTarget defines the current target of the state\n * @param userInfo defines any user info to send to observers\n * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)\n */\n notifyObservers(eventData, mask = -1, target, currentTarget, userInfo) {\n // this prevents potential memory leaks - if an object is disposed but the observable doesn't get cleared.\n if (this.notifyIfTriggered) {\n this._hasNotified = true;\n this._lastNotifiedValue = eventData;\n }\n if (!this._observers.length) {\n return true;\n }\n const state = this._eventState;\n state.mask = mask;\n state.target = target;\n state.currentTarget = currentTarget;\n state.skipNextObservers = false;\n state.lastReturnValue = eventData;\n state.userInfo = userInfo;\n for (const obs of this._observers) {\n if (obs._willBeUnregistered) {\n continue;\n }\n if (obs.mask & mask) {\n if (obs.unregisterOnNextCall) {\n this._deferUnregister(obs);\n }\n if (obs.scope) {\n state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);\n }\n else {\n state.lastReturnValue = obs.callback(eventData, state);\n }\n }\n if (state.skipNextObservers) {\n return false;\n }\n }\n return true;\n }\n /**\n * Notify a specific observer\n * @param observer defines the observer to notify\n * @param eventData defines the data to be sent to each callback\n * @param mask is used to filter observers defaults to -1\n */\n notifyObserver(observer, eventData, mask = -1) {\n // this prevents potential memory leaks - if an object is disposed but the observable doesn't get cleared.\n if (this.notifyIfTriggered) {\n this._hasNotified = true;\n this._lastNotifiedValue = eventData;\n }\n if (observer._willBeUnregistered) {\n return;\n }\n const state = this._eventState;\n state.mask = mask;\n state.skipNextObservers = false;\n if (observer.unregisterOnNextCall) {\n this._deferUnregister(observer);\n }\n observer.callback(eventData, state);\n }\n /**\n * Gets a boolean indicating if the observable has at least one observer\n * @returns true is the Observable has at least one Observer registered\n */\n hasObservers() {\n return this._observers.length - this._numObserversMarkedAsDeleted > 0;\n }\n /**\n * Clear the list of observers\n */\n clear() {\n while (this._observers.length) {\n const o = this._observers.pop();\n if (o) {\n o._remove = null;\n }\n }\n this._onObserverAdded = null;\n this._numObserversMarkedAsDeleted = 0;\n this.cleanLastNotifiedState();\n }\n /**\n * Clean the last notified state - both the internal last value and the has-notified flag\n */\n cleanLastNotifiedState() {\n this._hasNotified = false;\n this._lastNotifiedValue = undefined;\n }\n /**\n * Clone the current observable\n * @returns a new observable\n */\n clone() {\n const result = new Observable();\n result._observers = this._observers.slice(0);\n return result;\n }\n /**\n * Does this observable handles observer registered with a given mask\n * @param mask defines the mask to be tested\n * @returns whether or not one observer registered with the given mask is handled\n **/\n hasSpecificMask(mask = -1) {\n for (const obs of this._observers) {\n if (obs.mask & mask || obs.mask === mask) {\n return true;\n }\n }\n return false;\n }\n}\n//# sourceMappingURL=observable.js.map","import { PrecisionDate } from \"./precisionDate.js\";\n/**\n * This class is used to track a performance counter which is number based.\n * The user has access to many properties which give statistics of different nature.\n *\n * The implementer can track two kinds of Performance Counter: time and count.\n * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.\n * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.\n */\nexport class PerfCounter {\n /**\n * Returns the smallest value ever\n */\n get min() {\n return this._min;\n }\n /**\n * Returns the biggest value ever\n */\n get max() {\n return this._max;\n }\n /**\n * Returns the average value since the performance counter is running\n */\n get average() {\n return this._average;\n }\n /**\n * Returns the average value of the last second the counter was monitored\n */\n get lastSecAverage() {\n return this._lastSecAverage;\n }\n /**\n * Returns the current value\n */\n get current() {\n return this._current;\n }\n /**\n * Gets the accumulated total\n */\n get total() {\n return this._totalAccumulated;\n }\n /**\n * Gets the total value count\n */\n get count() {\n return this._totalValueCount;\n }\n /**\n * Creates a new counter\n */\n constructor() {\n this._startMonitoringTime = 0;\n this._min = 0;\n this._max = 0;\n this._average = 0;\n this._lastSecAverage = 0;\n this._current = 0;\n this._totalValueCount = 0;\n this._totalAccumulated = 0;\n this._lastSecAccumulated = 0;\n this._lastSecTime = 0;\n this._lastSecValueCount = 0;\n }\n /**\n * Call this method to start monitoring a new frame.\n * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.\n */\n fetchNewFrame() {\n this._totalValueCount++;\n this._current = 0;\n this._lastSecValueCount++;\n }\n /**\n * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)\n * @param newCount the count value to add to the monitored count\n * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.\n */\n addCount(newCount, fetchResult) {\n if (!PerfCounter.Enabled) {\n return;\n }\n this._current += newCount;\n if (fetchResult) {\n this._fetchResult();\n }\n }\n /**\n * Start monitoring this performance counter\n */\n beginMonitoring() {\n if (!PerfCounter.Enabled) {\n return;\n }\n this._startMonitoringTime = PrecisionDate.Now;\n }\n /**\n * Compute the time lapsed since the previous beginMonitoring() call.\n * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter\n */\n endMonitoring(newFrame = true) {\n if (!PerfCounter.Enabled) {\n return;\n }\n if (newFrame) {\n this.fetchNewFrame();\n }\n const currentTime = PrecisionDate.Now;\n this._current = currentTime - this._startMonitoringTime;\n if (newFrame) {\n this._fetchResult();\n }\n }\n /**\n * Call this method to end the monitoring of a frame.\n * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the end of the frame, after beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.\n */\n endFrame() {\n this._fetchResult();\n }\n _fetchResult() {\n this._totalAccumulated += this._current;\n this._lastSecAccumulated += this._current;\n // Min/Max update\n this._min = Math.min(this._min, this._current);\n this._max = Math.max(this._max, this._current);\n this._average = this._totalAccumulated / this._totalValueCount;\n // Reset last sec?\n const now = PrecisionDate.Now;\n if (now - this._lastSecTime > 1000) {\n this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;\n this._lastSecTime = now;\n this._lastSecAccumulated = 0;\n this._lastSecValueCount = 0;\n }\n }\n}\n/**\n * Gets or sets a global boolean to turn on and off all the counters\n */\nPerfCounter.Enabled = true;\n//# sourceMappingURL=perfCounter.js.map","import { PrecisionDate } from \"./precisionDate.js\";\n/**\n * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window\n */\nexport class PerformanceMonitor {\n /**\n * constructor\n * @param frameSampleSize The number of samples required to saturate the sliding window\n */\n constructor(frameSampleSize = 30) {\n this._enabled = true;\n this._rollingFrameTime = new RollingAverage(frameSampleSize);\n }\n /**\n * Samples current frame\n * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames\n */\n sampleFrame(timeMs = PrecisionDate.Now) {\n if (!this._enabled) {\n return;\n }\n if (this._lastFrameTimeMs != null) {\n const dt = timeMs - this._lastFrameTimeMs;\n this._rollingFrameTime.add(dt);\n }\n this._lastFrameTimeMs = timeMs;\n }\n /**\n * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)\n */\n get averageFrameTime() {\n return this._rollingFrameTime.average;\n }\n /**\n * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)\n */\n get averageFrameTimeVariance() {\n return this._rollingFrameTime.variance;\n }\n /**\n * Returns the frame time of the most recent frame\n */\n get instantaneousFrameTime() {\n return this._rollingFrameTime.history(0);\n }\n /**\n * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)\n */\n get averageFPS() {\n return 1000.0 / this._rollingFrameTime.average;\n }\n /**\n * Returns the average framerate in frames per second using the most recent frame time\n */\n get instantaneousFPS() {\n const history = this._rollingFrameTime.history(0);\n if (history === 0) {\n return 0;\n }\n return 1000.0 / history;\n }\n /**\n * Returns true if enough samples have been taken to completely fill the sliding window\n */\n get isSaturated() {\n return this._rollingFrameTime.isSaturated();\n }\n /**\n * Enables contributions to the sliding window sample set\n */\n enable() {\n this._enabled = true;\n }\n /**\n * Disables contributions to the sliding window sample set\n * Samples will not be interpolated over the disabled period\n */\n disable() {\n this._enabled = false;\n //clear last sample to avoid interpolating over the disabled period when next enabled\n this._lastFrameTimeMs = null;\n }\n /**\n * Returns true if sampling is enabled\n */\n get isEnabled() {\n return this._enabled;\n }\n /**\n * Resets performance monitor\n */\n reset() {\n //clear last sample to avoid interpolating over the disabled period when next enabled\n this._lastFrameTimeMs = null;\n //wipe record\n this._rollingFrameTime.reset();\n }\n}\n/**\n * RollingAverage\n *\n * Utility to efficiently compute the rolling average and variance over a sliding window of samples\n */\nexport class RollingAverage {\n /**\n * constructor\n * @param length The number of samples required to saturate the sliding window\n */\n constructor(length) {\n this._samples = new Array(length);\n this.reset();\n }\n /**\n * Adds a sample to the sample set\n * @param v The sample value\n */\n add(v) {\n //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance\n let delta;\n //we need to check if we've already wrapped round\n if (this.isSaturated()) {\n //remove bottom of stack from mean\n const bottomValue = this._samples[this._pos];\n delta = bottomValue - this.average;\n this.average -= delta / (this._sampleCount - 1);\n this._m2 -= delta * (bottomValue - this.average);\n }\n else {\n this._sampleCount++;\n }\n //add new value to mean\n delta = v - this.average;\n this.average += delta / this._sampleCount;\n this._m2 += delta * (v - this.average);\n //set the new variance\n this.variance = this._m2 / (this._sampleCount - 1);\n this._samples[this._pos] = v;\n this._pos++;\n this._pos %= this._samples.length; //positive wrap around\n }\n /**\n * Returns previously added values or null if outside of history or outside the sliding window domain\n * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that\n * @returns Value previously recorded with add() or null if outside of range\n */\n history(i) {\n if (i >= this._sampleCount || i >= this._samples.length) {\n return 0;\n }\n const i0 = this._wrapPosition(this._pos - 1.0);\n return this._samples[this._wrapPosition(i0 - i)];\n }\n /**\n * Returns true if enough samples have been taken to completely fill the sliding window\n * @returns true if sample-set saturated\n */\n isSaturated() {\n return this._sampleCount >= this._samples.length;\n }\n /**\n * Resets the rolling average (equivalent to 0 samples taken so far)\n */\n reset() {\n this.average = 0;\n this.variance = 0;\n this._sampleCount = 0;\n this._pos = 0;\n this._m2 = 0;\n }\n /**\n * Wraps a value around the sample range boundaries\n * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.\n * @returns Wrapped position in sample range\n */\n _wrapPosition(i) {\n const max = this._samples.length;\n return ((i % max) + max) % max;\n }\n}\n//# sourceMappingURL=performanceMonitor.js.map","import { DomManagement } from \"./domManagement.js\";\n/**\n * Class containing a set of static utilities functions for precision date\n */\nexport class PrecisionDate {\n /**\n * Gets either window.performance.now() if supported or Date.now() else\n */\n static get Now() {\n if (DomManagement.IsWindowObjectExist() && window.performance && window.performance.now) {\n return window.performance.now();\n }\n return Date.now();\n }\n}\n//# sourceMappingURL=precisionDate.js.map","/**\n * Class used to define a retry strategy when error happens while loading assets\n */\nexport class RetryStrategy {\n /**\n * Function used to defines an exponential back off strategy\n * @param maxRetries defines the maximum number of retries (3 by default)\n * @param baseInterval defines the interval between retries\n * @returns the strategy function to use\n */\n static ExponentialBackoff(maxRetries = 3, baseInterval = 500) {\n return (url, request, retryIndex) => {\n if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf(\"file:\") !== -1) {\n return -1;\n }\n return Math.pow(2, retryIndex) * baseInterval;\n };\n }\n}\n//# sourceMappingURL=retryStrategy.js.map","/**\n * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.\n */\nexport class SmartArray {\n /**\n * Instantiates a Smart Array.\n * @param capacity defines the default capacity of the array.\n */\n constructor(capacity) {\n /**\n * The active length of the array.\n */\n this.length = 0;\n this.data = new Array(capacity);\n this._id = SmartArray._GlobalId++;\n }\n /**\n * Pushes a value at the end of the active data.\n * @param value defines the object to push in the array.\n */\n push(value) {\n this.data[this.length++] = value;\n if (this.length > this.data.length) {\n this.data.length *= 2;\n }\n }\n /**\n * Iterates over the active data and apply the lambda to them.\n * @param func defines the action to apply on each value.\n */\n forEach(func) {\n for (let index = 0; index < this.length; index++) {\n func(this.data[index]);\n }\n }\n /**\n * Sorts the full sets of data.\n * @param compareFn defines the comparison function to apply.\n */\n sort(compareFn) {\n this.data.sort(compareFn);\n }\n /**\n * Resets the active data to an empty array.\n */\n reset() {\n this.length = 0;\n }\n /**\n * Releases all the data from the array as well as the array.\n */\n dispose() {\n this.reset();\n if (this.data) {\n this.data.length = 0;\n }\n }\n /**\n * Concats the active data with a given array.\n * @param array defines the data to concatenate with.\n */\n concat(array) {\n if (array.length === 0) {\n return;\n }\n if (this.length + array.length > this.data.length) {\n this.data.length = (this.length + array.length) * 2;\n }\n for (let index = 0; index < array.length; index++) {\n this.data[this.length++] = (array.data || array)[index];\n }\n }\n /**\n * Returns the position of a value in the active data.\n * @param value defines the value to find the index for\n * @returns the index if found in the active data otherwise -1\n */\n indexOf(value) {\n const position = this.data.indexOf(value);\n if (position >= this.length) {\n return -1;\n }\n return position;\n }\n /**\n * Returns whether an element is part of the active data.\n * @param value defines the value to look for\n * @returns true if found in the active data otherwise false\n */\n contains(value) {\n return this.indexOf(value) !== -1;\n }\n}\n// Statics\nSmartArray._GlobalId = 0;\n/**\n * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.\n * The data in this array can only be present once\n */\nexport class SmartArrayNoDuplicate extends SmartArray {\n constructor() {\n super(...arguments);\n this._duplicateId = 0;\n }\n /**\n * Pushes a value at the end of the active data.\n * THIS DOES NOT PREVENT DUPPLICATE DATA\n * @param value defines the object to push in the array.\n */\n push(value) {\n super.push(value);\n if (!value.__smartArrayFlags) {\n value.__smartArrayFlags = {};\n }\n value.__smartArrayFlags[this._id] = this._duplicateId;\n }\n /**\n * Pushes a value at the end of the active data.\n * If the data is already present, it won t be added again\n * @param value defines the object to push in the array.\n * @returns true if added false if it was already present\n */\n pushNoDuplicate(value) {\n if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {\n return false;\n }\n this.push(value);\n return true;\n }\n /**\n * Resets the active data to an empty array.\n */\n reset() {\n super.reset();\n this._duplicateId++;\n }\n /**\n * Concats the active data with a given array.\n * This ensures no duplicate will be present in the result.\n * @param array defines the data to concatenate with.\n */\n concatWithNoDuplicate(array) {\n if (array.length === 0) {\n return;\n }\n if (this.length + array.length > this.data.length) {\n this.data.length = (this.length + array.length) * 2;\n }\n for (let index = 0; index < array.length; index++) {\n const item = (array.data || array)[index];\n this.pushNoDuplicate(item);\n }\n }\n}\n//# sourceMappingURL=smartArray.js.map","/**\n * This class implement a typical dictionary using a string as key and the generic type T as value.\n * The underlying implementation relies on an associative array to ensure the best performances.\n * The value can be anything including 'null' but except 'undefined'\n */\nexport class StringDictionary {\n constructor() {\n this._count = 0;\n this._data = {};\n }\n /**\n * This will clear this dictionary and copy the content from the 'source' one.\n * If the T value is a custom object, it won't be copied/cloned, the same object will be used\n * @param source the dictionary to take the content from and copy to this dictionary\n */\n copyFrom(source) {\n this.clear();\n source.forEach((t, v) => this.add(t, v));\n }\n /**\n * Get a value based from its key\n * @param key the given key to get the matching value from\n * @returns the value if found, otherwise undefined is returned\n */\n get(key) {\n const val = this._data[key];\n if (val !== undefined) {\n return val;\n }\n return undefined;\n }\n /**\n * Get a value from its key or add it if it doesn't exist.\n * This method will ensure you that a given key/data will be present in the dictionary.\n * @param key the given key to get the matching value from\n * @param factory the factory that will create the value if the key is not present in the dictionary.\n * The factory will only be invoked if there's no data for the given key.\n * @returns the value corresponding to the key.\n */\n getOrAddWithFactory(key, factory) {\n let val = this.get(key);\n if (val !== undefined) {\n return val;\n }\n val = factory(key);\n if (val) {\n this.add(key, val);\n }\n return val;\n }\n /**\n * Get a value from its key if present in the dictionary otherwise add it\n * @param key the key to get the value from\n * @param val if there's no such key/value pair in the dictionary add it with this value\n * @returns the value corresponding to the key\n */\n getOrAdd(key, val) {\n const curVal = this.get(key);\n if (curVal !== undefined) {\n return curVal;\n }\n this.add(key, val);\n return val;\n }\n /**\n * Check if there's a given key in the dictionary\n * @param key the key to check for\n * @returns true if the key is present, false otherwise\n */\n contains(key) {\n return this._data[key] !== undefined;\n }\n /**\n * Add a new key and its corresponding value\n * @param key the key to add\n * @param value the value corresponding to the key\n * @returns true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary\n */\n add(key, value) {\n if (this._data[key] !== undefined) {\n return false;\n }\n this._data[key] = value;\n ++this._count;\n return true;\n }\n /**\n * Update a specific value associated to a key\n * @param key defines the key to use\n * @param value defines the value to store\n * @returns true if the value was updated (or false if the key was not found)\n */\n set(key, value) {\n if (this._data[key] === undefined) {\n return false;\n }\n this._data[key] = value;\n return true;\n }\n /**\n * Get the element of the given key and remove it from the dictionary\n * @param key defines the key to search\n * @returns the value associated with the key or null if not found\n */\n getAndRemove(key) {\n const val = this.get(key);\n if (val !== undefined) {\n delete this._data[key];\n --this._count;\n return val;\n }\n return null;\n }\n /**\n * Remove a key/value from the dictionary.\n * @param key the key to remove\n * @returns true if the item was successfully deleted, false if no item with such key exist in the dictionary\n */\n remove(key) {\n if (this.contains(key)) {\n delete this._data[key];\n --this._count;\n return true;\n }\n return false;\n }\n /**\n * Clear the whole content of the dictionary\n */\n clear() {\n this._data = {};\n this._count = 0;\n }\n /**\n * Gets the current count\n */\n get count() {\n return this._count;\n }\n /**\n * Execute a callback on each key/val of the dictionary.\n * Note that you can remove any element in this dictionary in the callback implementation\n * @param callback the callback to execute on a given key/value pair\n */\n forEach(callback) {\n for (const cur in this._data) {\n const val = this._data[cur];\n callback(cur, val);\n }\n }\n /**\n * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.\n * If the callback returns null or undefined the method will iterate to the next key/value pair\n * Note that you can remove any element in this dictionary in the callback implementation\n * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned\n * @returns the first item\n */\n first(callback) {\n for (const cur in this._data) {\n const val = this._data[cur];\n const res = callback(cur, val);\n if (res) {\n return res;\n }\n }\n return null;\n }\n}\n//# sourceMappingURL=stringDictionary.js.map","/* eslint-disable @typescript-eslint/naming-convention */\n/**\n * Checks for a matching suffix at the end of a string (for ES5 and lower)\n * @param str Source string\n * @param suffix Suffix to search for in the source string\n * @returns Boolean indicating whether the suffix was found (true) or not (false)\n * @deprecated Please use native string function instead\n */\nexport const EndsWith = (str, suffix) => {\n return str.endsWith(suffix);\n};\n/**\n * Checks for a matching suffix at the beginning of a string (for ES5 and lower)\n * @param str Source string\n * @param suffix Suffix to search for in the source string\n * @returns Boolean indicating whether the suffix was found (true) or not (false)\n * @deprecated Please use native string function instead\n */\nexport const StartsWith = (str, suffix) => {\n if (!str) {\n return false;\n }\n return str.startsWith(suffix);\n};\n/**\n * Decodes a buffer into a string\n * @param buffer The buffer to decode\n * @returns The decoded string\n */\nexport const Decode = (buffer) => {\n if (typeof TextDecoder !== \"undefined\") {\n return new TextDecoder().decode(buffer);\n }\n let result = \"\";\n for (let i = 0; i < buffer.byteLength; i++) {\n result += String.fromCharCode(buffer[i]);\n }\n return result;\n};\n/**\n * Encode a buffer to a base64 string\n * @param buffer defines the buffer to encode\n * @returns the encoded string\n */\nexport const EncodeArrayBufferToBase64 = (buffer) => {\n const keyStr = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\n let output = \"\";\n let chr1, chr2, chr3, enc1, enc2, enc3, enc4;\n let i = 0;\n const bytes = ArrayBuffer.isView(buffer) ? new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength) : new Uint8Array(buffer);\n while (i < bytes.length) {\n chr1 = bytes[i++];\n chr2 = i < bytes.length ? bytes[i++] : Number.NaN;\n chr3 = i < bytes.length ? bytes[i++] : Number.NaN;\n enc1 = chr1 >> 2;\n enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);\n enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);\n enc4 = chr3 & 63;\n if (isNaN(chr2)) {\n enc3 = enc4 = 64;\n }\n else if (isNaN(chr3)) {\n enc4 = 64;\n }\n output += keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);\n }\n return output;\n};\n/**\n * Converts a given base64 string as an ASCII encoded stream of data\n * @param base64Data The base64 encoded string to decode\n * @returns Decoded ASCII string\n */\nexport const DecodeBase64ToString = (base64Data) => {\n return atob(base64Data);\n};\n/**\n * Converts a given base64 string into an ArrayBuffer of raw byte data\n * @param base64Data The base64 encoded string to decode\n * @returns ArrayBuffer of byte data\n */\nexport const DecodeBase64ToBinary = (base64Data) => {\n const decodedString = DecodeBase64ToString(base64Data);\n const bufferLength = decodedString.length;\n const bufferView = new Uint8Array(new ArrayBuffer(bufferLength));\n for (let i = 0; i < bufferLength; i++) {\n bufferView[i] = decodedString.charCodeAt(i);\n }\n return bufferView.buffer;\n};\n/**\n * Converts a number to string and pads with preceding zeroes until it is of specified length.\n * @param num the number to convert and pad\n * @param length the expected length of the string\n * @returns the padded string\n */\nexport const PadNumber = (num, length) => {\n let str = String(num);\n while (str.length < length) {\n str = \"0\" + str;\n }\n return str;\n};\n/**\n * Helper to manipulate strings\n */\nexport const StringTools = {\n EndsWith,\n StartsWith,\n Decode,\n EncodeArrayBufferToBase64,\n DecodeBase64ToString,\n DecodeBase64ToBinary,\n PadNumber,\n};\n//# sourceMappingURL=stringTools.js.map","import { AndOrNotEvaluator } from \"./andOrNotEvaluator.js\";\n/**\n * Class used to store custom tags\n */\nexport class Tags {\n /**\n * Adds support for tags on the given object\n * @param obj defines the object to use\n */\n static EnableFor(obj) {\n obj._tags = obj._tags || {};\n obj.hasTags = () => {\n return Tags.HasTags(obj);\n };\n obj.addTags = (tagsString) => {\n return Tags.AddTagsTo(obj, tagsString);\n };\n obj.removeTags = (tagsString) => {\n return Tags.RemoveTagsFrom(obj, tagsString);\n };\n obj.matchesTagsQuery = (tagsQuery) => {\n return Tags.MatchesQuery(obj, tagsQuery);\n };\n }\n /**\n * Removes tags support\n * @param obj defines the object to use\n */\n static DisableFor(obj) {\n delete obj._tags;\n delete obj.hasTags;\n delete obj.addTags;\n delete obj.removeTags;\n delete obj.matchesTagsQuery;\n }\n /**\n * Gets a boolean indicating if the given object has tags\n * @param obj defines the object to use\n * @returns a boolean\n */\n static HasTags(obj) {\n if (!obj._tags) {\n return false;\n }\n const tags = obj._tags;\n for (const i in tags) {\n if (Object.prototype.hasOwnProperty.call(tags, i)) {\n return true;\n }\n }\n return false;\n }\n /**\n * Gets the tags available on a given object\n * @param obj defines the object to use\n * @param asString defines if the tags must be returned as a string instead of an array of strings\n * @returns the tags\n */\n static GetTags(obj, asString = true) {\n if (!obj._tags) {\n return null;\n }\n if (asString) {\n const tagsArray = [];\n for (const tag in obj._tags) {\n if (Object.prototype.hasOwnProperty.call(obj._tags, tag) && obj._tags[tag] === true) {\n tagsArray.push(tag);\n }\n }\n return tagsArray.join(\" \");\n }\n else {\n return obj._tags;\n }\n }\n /**\n * Adds tags to an object\n * @param obj defines the object to use\n * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags.\n * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces\n */\n static AddTagsTo(obj, tagsString) {\n if (!tagsString) {\n return;\n }\n if (typeof tagsString !== \"string\") {\n return;\n }\n const tags = tagsString.split(\" \");\n tags.forEach(function (tag) {\n Tags._AddTagTo(obj, tag);\n });\n }\n /**\n * @internal\n */\n static _AddTagTo(obj, tag) {\n tag = tag.trim();\n if (tag === \"\" || tag === \"true\" || tag === \"false\") {\n return;\n }\n if (tag.match(/[\\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {\n return;\n }\n Tags.EnableFor(obj);\n obj._tags[tag] = true;\n }\n /**\n * Removes specific tags from a specific object\n * @param obj defines the object to use\n * @param tagsString defines the tags to remove\n */\n static RemoveTagsFrom(obj, tagsString) {\n if (!Tags.HasTags(obj)) {\n return;\n }\n const tags = tagsString.split(\" \");\n for (const t in tags) {\n Tags._RemoveTagFrom(obj, tags[t]);\n }\n }\n /**\n * @internal\n */\n static _RemoveTagFrom(obj, tag) {\n delete obj._tags[tag];\n }\n /**\n * Defines if tags hosted on an object match a given query\n * @param obj defines the object to use\n * @param tagsQuery defines the tag query\n * @returns a boolean\n */\n static MatchesQuery(obj, tagsQuery) {\n if (tagsQuery === undefined) {\n return true;\n }\n if (tagsQuery === \"\") {\n return Tags.HasTags(obj);\n }\n return AndOrNotEvaluator.Eval(tagsQuery, (r) => Tags.HasTags(obj) && obj._tags[r]);\n }\n}\n//# sourceMappingURL=tags.js.map","import { IsWindowObjectExist } from \"./domManagement.js\";\n/**\n * Class used to provide helper for timing\n */\nexport class TimingTools {\n /**\n * Polyfill for setImmediate\n * @param action defines the action to execute after the current execution block\n */\n static SetImmediate(action) {\n if (IsWindowObjectExist() && window.setImmediate) {\n window.setImmediate(action);\n }\n else {\n setTimeout(action, 1);\n }\n }\n}\n//# sourceMappingURL=timingTools.js.map","import { Observable } from \"./observable.js\";\nimport { GetDOMTextContent, IsNavigatorAvailable, IsWindowObjectExist } from \"./domManagement.js\";\nimport { Logger } from \"./logger.js\";\nimport { DeepCopier } from \"./deepCopier.js\";\nimport { PrecisionDate } from \"./precisionDate.js\";\nimport { _WarnImport } from \"./devTools.js\";\nimport { WebRequest } from \"./webRequest.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { FileToolsOptions, DecodeBase64UrlToBinary, IsBase64DataUrl, LoadFile as FileToolsLoadFile, LoadImage as FileToolLoadImage, ReadFile as FileToolsReadFile, SetCorsBehavior, } from \"./fileTools.js\";\nimport { TimingTools } from \"./timingTools.js\";\nimport { InstantiationTools } from \"./instantiationTools.js\";\nimport { RandomGUID } from \"./guid.js\";\n/**\n * Class containing a set of static utilities functions\n */\nexport class Tools {\n /**\n * Gets or sets the base URL to use to load assets\n */\n static get BaseUrl() {\n return FileToolsOptions.BaseUrl;\n }\n static set BaseUrl(value) {\n FileToolsOptions.BaseUrl = value;\n }\n /**\n * Gets or sets the retry strategy to apply when an error happens while loading an asset\n */\n static get DefaultRetryStrategy() {\n return FileToolsOptions.DefaultRetryStrategy;\n }\n static set DefaultRetryStrategy(strategy) {\n FileToolsOptions.DefaultRetryStrategy = strategy;\n }\n /**\n * Default behaviour for cors in the application.\n * It can be a string if the expected behavior is identical in the entire app.\n * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)\n */\n static get CorsBehavior() {\n return FileToolsOptions.CorsBehavior;\n }\n static set CorsBehavior(value) {\n FileToolsOptions.CorsBehavior = value;\n }\n /**\n * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded\n * @ignorenaming\n */\n static get UseFallbackTexture() {\n return EngineStore.UseFallbackTexture;\n }\n static set UseFallbackTexture(value) {\n EngineStore.UseFallbackTexture = value;\n }\n /**\n * Use this object to register external classes like custom textures or material\n * to allow the loaders to instantiate them\n */\n static get RegisteredExternalClasses() {\n return InstantiationTools.RegisteredExternalClasses;\n }\n static set RegisteredExternalClasses(classes) {\n InstantiationTools.RegisteredExternalClasses = classes;\n }\n /**\n * Texture content used if a texture cannot loaded\n * @ignorenaming\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static get fallbackTexture() {\n return EngineStore.FallbackTexture;\n }\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static set fallbackTexture(value) {\n EngineStore.FallbackTexture = value;\n }\n /**\n * Read the content of a byte array at a specified coordinates (taking in account wrapping)\n * @param u defines the coordinate on X axis\n * @param v defines the coordinate on Y axis\n * @param width defines the width of the source data\n * @param height defines the height of the source data\n * @param pixels defines the source byte array\n * @param color defines the output color\n */\n static FetchToRef(u, v, width, height, pixels, color) {\n const wrappedU = (Math.abs(u) * width) % width | 0;\n const wrappedV = (Math.abs(v) * height) % height | 0;\n const position = (wrappedU + wrappedV * width) * 4;\n color.r = pixels[position] / 255;\n color.g = pixels[position + 1] / 255;\n color.b = pixels[position + 2] / 255;\n color.a = pixels[position + 3] / 255;\n }\n /**\n * Interpolates between a and b via alpha\n * @param a The lower value (returned when alpha = 0)\n * @param b The upper value (returned when alpha = 1)\n * @param alpha The interpolation-factor\n * @returns The mixed value\n */\n static Mix(a, b, alpha) {\n return a * (1 - alpha) + b * alpha;\n }\n /**\n * Tries to instantiate a new object from a given class name\n * @param className defines the class name to instantiate\n * @returns the new object or null if the system was not able to do the instantiation\n */\n static Instantiate(className) {\n return InstantiationTools.Instantiate(className);\n }\n /**\n * Polyfill for setImmediate\n * @param action defines the action to execute after the current execution block\n */\n static SetImmediate(action) {\n TimingTools.SetImmediate(action);\n }\n /**\n * Function indicating if a number is an exponent of 2\n * @param value defines the value to test\n * @returns true if the value is an exponent of 2\n */\n static IsExponentOfTwo(value) {\n let count = 1;\n do {\n count *= 2;\n } while (count < value);\n return count === value;\n }\n /**\n * Returns the nearest 32-bit single precision float representation of a Number\n * @param value A Number. If the parameter is of a different type, it will get converted\n * to a number or to NaN if it cannot be converted\n * @returns number\n */\n static FloatRound(value) {\n if (Math.fround) {\n return Math.fround(value);\n }\n return (Tools._TmpFloatArray[0] = value), Tools._TmpFloatArray[0];\n }\n /**\n * Extracts the filename from a path\n * @param path defines the path to use\n * @returns the filename\n */\n static GetFilename(path) {\n const index = path.lastIndexOf(\"/\");\n if (index < 0) {\n return path;\n }\n return path.substring(index + 1);\n }\n /**\n * Extracts the \"folder\" part of a path (everything before the filename).\n * @param uri The URI to extract the info from\n * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present\n * @returns The \"folder\" part of the path\n */\n static GetFolderPath(uri, returnUnchangedIfNoSlash = false) {\n const index = uri.lastIndexOf(\"/\");\n if (index < 0) {\n if (returnUnchangedIfNoSlash) {\n return uri;\n }\n return \"\";\n }\n return uri.substring(0, index + 1);\n }\n /**\n * Convert an angle in radians to degrees\n * @param angle defines the angle to convert\n * @returns the angle in degrees\n */\n static ToDegrees(angle) {\n return (angle * 180) / Math.PI;\n }\n /**\n * Convert an angle in degrees to radians\n * @param angle defines the angle to convert\n * @returns the angle in radians\n */\n static ToRadians(angle) {\n return (angle * Math.PI) / 180;\n }\n /**\n * Smooth angle changes (kind of low-pass filter), in particular for device orientation \"shaking\"\n * Use trigonometric functions to avoid discontinuity (0/360, -180/180)\n * @param previousAngle defines last angle value, in degrees\n * @param newAngle defines new angle value, in degrees\n * @param smoothFactor defines smoothing sensitivity; min 0: no smoothing, max 1: new data ignored\n * @returns the angle in degrees\n */\n static SmoothAngleChange(previousAngle, newAngle, smoothFactor = 0.9) {\n const previousAngleRad = this.ToRadians(previousAngle);\n const newAngleRad = this.ToRadians(newAngle);\n return this.ToDegrees(Math.atan2((1 - smoothFactor) * Math.sin(newAngleRad) + smoothFactor * Math.sin(previousAngleRad), (1 - smoothFactor) * Math.cos(newAngleRad) + smoothFactor * Math.cos(previousAngleRad)));\n }\n /**\n * Returns an array if obj is not an array\n * @param obj defines the object to evaluate as an array\n * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined\n * @returns either obj directly if obj is an array or a new array containing obj\n */\n static MakeArray(obj, allowsNullUndefined) {\n if (allowsNullUndefined !== true && (obj === undefined || obj == null)) {\n return null;\n }\n return Array.isArray(obj) ? obj : [obj];\n }\n /**\n * Gets the pointer prefix to use\n * @param engine defines the engine we are finding the prefix for\n * @returns \"pointer\" if touch is enabled. Else returns \"mouse\"\n */\n static GetPointerPrefix(engine) {\n let eventPrefix = \"pointer\";\n // Check if pointer events are supported\n if (IsWindowObjectExist() && !window.PointerEvent) {\n eventPrefix = \"mouse\";\n }\n // Special Fallback MacOS Safari...\n if (engine._badDesktopOS &&\n !engine._badOS &&\n // And not ipad pros who claim to be macs...\n !(document && \"ontouchend\" in document)) {\n eventPrefix = \"mouse\";\n }\n return eventPrefix;\n }\n /**\n * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.\n * @param url define the url we are trying\n * @param element define the dom element where to configure the cors policy\n * @param element.crossOrigin\n */\n static SetCorsBehavior(url, element) {\n SetCorsBehavior(url, element);\n }\n /**\n * Sets the referrerPolicy behavior on a dom element.\n * @param referrerPolicy define the referrer policy to use\n * @param element define the dom element where to configure the referrer policy\n * @param element.referrerPolicy\n */\n static SetReferrerPolicyBehavior(referrerPolicy, element) {\n element.referrerPolicy = referrerPolicy;\n }\n // External files\n /**\n * Removes unwanted characters from an url\n * @param url defines the url to clean\n * @returns the cleaned url\n */\n static CleanUrl(url) {\n url = url.replace(/#/gm, \"%23\");\n return url;\n }\n /**\n * Gets or sets a function used to pre-process url before using them to load assets\n */\n static get PreprocessUrl() {\n return FileToolsOptions.PreprocessUrl;\n }\n static set PreprocessUrl(processor) {\n FileToolsOptions.PreprocessUrl = processor;\n }\n /**\n * Loads an image as an HTMLImageElement.\n * @param input url string, ArrayBuffer, or Blob to load\n * @param onLoad callback called when the image successfully loads\n * @param onError callback called when the image fails to load\n * @param offlineProvider offline provider for caching\n * @param mimeType optional mime type\n * @param imageBitmapOptions optional the options to use when creating an ImageBitmap\n * @returns the HTMLImageElement of the loaded image\n */\n static LoadImage(input, onLoad, onError, offlineProvider, mimeType, imageBitmapOptions) {\n return FileToolLoadImage(input, onLoad, onError, offlineProvider, mimeType, imageBitmapOptions);\n }\n /**\n * Loads a file from a url\n * @param url url string, ArrayBuffer, or Blob to load\n * @param onSuccess callback called when the file successfully loads\n * @param onProgress callback called while file is loading (if the server supports this mode)\n * @param offlineProvider defines the offline provider for caching\n * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer\n * @param onError callback called when the file fails to load\n * @returns a file request object\n */\n static LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) {\n return FileToolsLoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError);\n }\n /**\n * Loads a file from a url\n * @param url the file url to load\n * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer\n * @returns a promise containing an ArrayBuffer corresponding to the loaded file\n */\n static LoadFileAsync(url, useArrayBuffer = true) {\n return new Promise((resolve, reject) => {\n FileToolsLoadFile(url, (data) => {\n resolve(data);\n }, undefined, undefined, useArrayBuffer, (request, exception) => {\n reject(exception);\n });\n });\n }\n /**\n * Load a script (identified by an url). When the url returns, the\n * content of this file is added into a new script element, attached to the DOM (body element)\n * @param scriptUrl defines the url of the script to laod\n * @param onSuccess defines the callback called when the script is loaded\n * @param onError defines the callback to call if an error occurs\n * @param scriptId defines the id of the script element\n */\n static LoadScript(scriptUrl, onSuccess, onError, scriptId) {\n if (typeof importScripts === \"function\") {\n try {\n importScripts(scriptUrl);\n onSuccess();\n }\n catch (e) {\n onError === null || onError === void 0 ? void 0 : onError(`Unable to load script '${scriptUrl}' in worker`, e);\n }\n return;\n }\n else if (!IsWindowObjectExist()) {\n onError === null || onError === void 0 ? void 0 : onError(`Cannot load script '${scriptUrl}' outside of a window or a worker`);\n return;\n }\n const head = document.getElementsByTagName(\"head\")[0];\n const script = document.createElement(\"script\");\n script.setAttribute(\"type\", \"text/javascript\");\n script.setAttribute(\"src\", scriptUrl);\n if (scriptId) {\n script.id = scriptId;\n }\n script.onload = () => {\n if (onSuccess) {\n onSuccess();\n }\n };\n script.onerror = (e) => {\n if (onError) {\n onError(`Unable to load script '${scriptUrl}'`, e);\n }\n };\n head.appendChild(script);\n }\n /**\n * Load an asynchronous script (identified by an url). When the url returns, the\n * content of this file is added into a new script element, attached to the DOM (body element)\n * @param scriptUrl defines the url of the script to laod\n * @returns a promise request object\n */\n static LoadScriptAsync(scriptUrl) {\n return new Promise((resolve, reject) => {\n this.LoadScript(scriptUrl, () => {\n resolve();\n }, (message, exception) => {\n reject(exception || new Error(message));\n });\n });\n }\n /**\n * Loads a file from a blob\n * @param fileToLoad defines the blob to use\n * @param callback defines the callback to call when data is loaded\n * @param progressCallback defines the callback to call during loading process\n * @returns a file request object\n */\n static ReadFileAsDataURL(fileToLoad, callback, progressCallback) {\n const reader = new FileReader();\n const request = {\n onCompleteObservable: new Observable(),\n abort: () => reader.abort(),\n };\n reader.onloadend = () => {\n request.onCompleteObservable.notifyObservers(request);\n };\n reader.onload = (e) => {\n //target doesn't have result from ts 1.3\n callback(e.target[\"result\"]);\n };\n reader.onprogress = progressCallback;\n reader.readAsDataURL(fileToLoad);\n return request;\n }\n /**\n * Reads a file from a File object\n * @param file defines the file to load\n * @param onSuccess defines the callback to call when data is loaded\n * @param onProgress defines the callback to call during loading process\n * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer\n * @param onError defines the callback to call when an error occurs\n * @returns a file request object\n */\n static ReadFile(file, onSuccess, onProgress, useArrayBuffer, onError) {\n return FileToolsReadFile(file, onSuccess, onProgress, useArrayBuffer, onError);\n }\n /**\n * Creates a data url from a given string content\n * @param content defines the content to convert\n * @returns the new data url link\n */\n static FileAsURL(content) {\n const fileBlob = new Blob([content]);\n const url = window.URL;\n const link = url.createObjectURL(fileBlob);\n return link;\n }\n /**\n * Format the given number to a specific decimal format\n * @param value defines the number to format\n * @param decimals defines the number of decimals to use\n * @returns the formatted string\n */\n static Format(value, decimals = 2) {\n return value.toFixed(decimals);\n }\n /**\n * Tries to copy an object by duplicating every property\n * @param source defines the source object\n * @param destination defines the target object\n * @param doNotCopyList defines a list of properties to avoid\n * @param mustCopyList defines a list of properties to copy (even if they start with _)\n */\n static DeepCopy(source, destination, doNotCopyList, mustCopyList) {\n DeepCopier.DeepCopy(source, destination, doNotCopyList, mustCopyList);\n }\n /**\n * Gets a boolean indicating if the given object has no own property\n * @param obj defines the object to test\n * @returns true if object has no own property\n */\n static IsEmpty(obj) {\n for (const i in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, i)) {\n return false;\n }\n }\n return true;\n }\n /**\n * Function used to register events at window level\n * @param windowElement defines the Window object to use\n * @param events defines the events to register\n */\n static RegisterTopRootEvents(windowElement, events) {\n for (let index = 0; index < events.length; index++) {\n const event = events[index];\n windowElement.addEventListener(event.name, event.handler, false);\n try {\n if (window.parent) {\n window.parent.addEventListener(event.name, event.handler, false);\n }\n }\n catch (e) {\n // Silently fails...\n }\n }\n }\n /**\n * Function used to unregister events from window level\n * @param windowElement defines the Window object to use\n * @param events defines the events to unregister\n */\n static UnregisterTopRootEvents(windowElement, events) {\n for (let index = 0; index < events.length; index++) {\n const event = events[index];\n windowElement.removeEventListener(event.name, event.handler);\n try {\n if (windowElement.parent) {\n windowElement.parent.removeEventListener(event.name, event.handler);\n }\n }\n catch (e) {\n // Silently fails...\n }\n }\n }\n /**\n * Dumps the current bound framebuffer\n * @param width defines the rendering width\n * @param height defines the rendering height\n * @param engine defines the hosting engine\n * @param successCallback defines the callback triggered once the data are available\n * @param mimeType defines the mime type of the result\n * @param fileName defines the filename to download. If present, the result will automatically be downloaded\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n * @returns a void promise\n */\n static async DumpFramebuffer(width, height, engine, successCallback, mimeType = \"image/png\", fileName, quality) {\n throw _WarnImport(\"DumpTools\");\n }\n /**\n * Dumps an array buffer\n * @param width defines the rendering width\n * @param height defines the rendering height\n * @param data the data array\n * @param successCallback defines the callback triggered once the data are available\n * @param mimeType defines the mime type of the result\n * @param fileName defines the filename to download. If present, the result will automatically be downloaded\n * @param invertY true to invert the picture in the Y dimension\n * @param toArrayBuffer true to convert the data to an ArrayBuffer (encoded as `mimeType`) instead of a base64 string\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n */\n static DumpData(width, height, data, successCallback, mimeType = \"image/png\", fileName, invertY = false, toArrayBuffer = false, quality) {\n throw _WarnImport(\"DumpTools\");\n }\n /**\n * Dumps an array buffer\n * @param width defines the rendering width\n * @param height defines the rendering height\n * @param data the data array\n * @param mimeType defines the mime type of the result\n * @param fileName defines the filename to download. If present, the result will automatically be downloaded\n * @param invertY true to invert the picture in the Y dimension\n * @param toArrayBuffer true to convert the data to an ArrayBuffer (encoded as `mimeType`) instead of a base64 string\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n * @returns a promise that resolve to the final data\n */\n static DumpDataAsync(width, height, data, mimeType = \"image/png\", fileName, invertY = false, toArrayBuffer = false, quality) {\n throw _WarnImport(\"DumpTools\");\n }\n static _IsOffScreenCanvas(canvas) {\n return canvas.convertToBlob !== undefined;\n }\n /**\n * Converts the canvas data to blob.\n * This acts as a polyfill for browsers not supporting the to blob function.\n * @param canvas Defines the canvas to extract the data from (can be an offscreen canvas)\n * @param successCallback Defines the callback triggered once the data are available\n * @param mimeType Defines the mime type of the result\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n */\n static ToBlob(canvas, successCallback, mimeType = \"image/png\", quality) {\n // We need HTMLCanvasElement.toBlob for HD screenshots\n if (!Tools._IsOffScreenCanvas(canvas) && !canvas.toBlob) {\n // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)\n canvas.toBlob = function (callback, type, quality) {\n setTimeout(() => {\n const binStr = atob(this.toDataURL(type, quality).split(\",\")[1]), len = binStr.length, arr = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n arr[i] = binStr.charCodeAt(i);\n }\n callback(new Blob([arr]));\n });\n };\n }\n if (Tools._IsOffScreenCanvas(canvas)) {\n canvas\n .convertToBlob({\n type: mimeType,\n quality,\n })\n .then((blob) => successCallback(blob));\n }\n else {\n canvas.toBlob(function (blob) {\n successCallback(blob);\n }, mimeType, quality);\n }\n }\n /**\n * Download a Blob object\n * @param blob the Blob object\n * @param fileName the file name to download\n * @returns\n */\n static DownloadBlob(blob, fileName) {\n //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.\n if (\"download\" in document.createElement(\"a\")) {\n if (!fileName) {\n const date = new Date();\n const stringDate = (date.getFullYear() + \"-\" + (date.getMonth() + 1)).slice(2) + \"-\" + date.getDate() + \"_\" + date.getHours() + \"-\" + (\"0\" + date.getMinutes()).slice(-2);\n fileName = \"screenshot_\" + stringDate + \".png\";\n }\n Tools.Download(blob, fileName);\n }\n else {\n if (blob && typeof URL !== \"undefined\") {\n const url = URL.createObjectURL(blob);\n const newWindow = window.open(\"\");\n if (!newWindow) {\n return;\n }\n const img = newWindow.document.createElement(\"img\");\n img.onload = function () {\n // no longer need to read the blob so it's revoked\n URL.revokeObjectURL(url);\n };\n img.src = url;\n newWindow.document.body.appendChild(img);\n }\n }\n }\n /**\n * Encodes the canvas data to base 64, or automatically downloads the result if `fileName` is defined.\n * @param canvas The canvas to get the data from, which can be an offscreen canvas.\n * @param successCallback The callback which is triggered once the data is available. If `fileName` is defined, the callback will be invoked after the download occurs, and the `data` argument will be an empty string.\n * @param mimeType The mime type of the result.\n * @param fileName The name of the file to download. If defined, the result will automatically be downloaded. If not defined, and `successCallback` is also not defined, the result will automatically be downloaded with an auto-generated file name.\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n */\n static EncodeScreenshotCanvasData(canvas, successCallback, mimeType = \"image/png\", fileName, quality) {\n if (typeof fileName === \"string\" || !successCallback) {\n this.ToBlob(canvas, function (blob) {\n if (blob) {\n Tools.DownloadBlob(blob, fileName);\n }\n if (successCallback) {\n successCallback(\"\");\n }\n }, mimeType, quality);\n }\n else if (successCallback) {\n if (Tools._IsOffScreenCanvas(canvas)) {\n canvas\n .convertToBlob({\n type: mimeType,\n quality,\n })\n .then((blob) => {\n const reader = new FileReader();\n reader.readAsDataURL(blob);\n reader.onloadend = () => {\n const base64data = reader.result;\n successCallback(base64data);\n };\n });\n return;\n }\n const base64Image = canvas.toDataURL(mimeType, quality);\n successCallback(base64Image);\n }\n }\n /**\n * Downloads a blob in the browser\n * @param blob defines the blob to download\n * @param fileName defines the name of the downloaded file\n */\n static Download(blob, fileName) {\n if (typeof URL === \"undefined\") {\n return;\n }\n const url = window.URL.createObjectURL(blob);\n const a = document.createElement(\"a\");\n document.body.appendChild(a);\n a.style.display = \"none\";\n a.href = url;\n a.download = fileName;\n a.addEventListener(\"click\", () => {\n if (a.parentElement) {\n a.parentElement.removeChild(a);\n }\n });\n a.click();\n window.URL.revokeObjectURL(url);\n }\n /**\n * Will return the right value of the noPreventDefault variable\n * Needed to keep backwards compatibility to the old API.\n *\n * @param args arguments passed to the attachControl function\n * @returns the correct value for noPreventDefault\n */\n static BackCompatCameraNoPreventDefault(args) {\n // is it used correctly?\n if (typeof args[0] === \"boolean\") {\n return args[0];\n }\n else if (typeof args[1] === \"boolean\") {\n return args[1];\n }\n return false;\n }\n /**\n * Captures a screenshot of the current rendering\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine defines the rendering engine\n * @param camera defines the source camera\n * @param size This parameter can be set to a single number or to an object with the\n * following (optional) properties: precision, width, height. If a single number is passed,\n * it will be used for both width and height. If an object is passed, the screenshot size\n * will be derived from the parameters. The precision property is a multiplier allowing\n * rendering at a higher or lower resolution\n * @param successCallback defines the callback receives a single parameter which contains the\n * screenshot as a string of base64-encoded characters. This string can be assigned to the\n * src parameter of an to display it\n * @param mimeType defines the MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param forceDownload force the system to download the image even if a successCallback is provided\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n static CreateScreenshot(engine, camera, size, successCallback, mimeType = \"image/png\", forceDownload = false, quality) {\n throw _WarnImport(\"ScreenshotTools\");\n }\n /**\n * Captures a screenshot of the current rendering\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine defines the rendering engine\n * @param camera defines the source camera\n * @param size This parameter can be set to a single number or to an object with the\n * following (optional) properties: precision, width, height. If a single number is passed,\n * it will be used for both width and height. If an object is passed, the screenshot size\n * will be derived from the parameters. The precision property is a multiplier allowing\n * rendering at a higher or lower resolution\n * @param mimeType defines the MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n * @returns screenshot as a string of base64-encoded characters. This string can be assigned\n * to the src parameter of an to display it\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n static CreateScreenshotAsync(engine, camera, size, mimeType = \"image/png\", quality) {\n throw _WarnImport(\"ScreenshotTools\");\n }\n /**\n * Generates an image screenshot from the specified camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine The engine to use for rendering\n * @param camera The camera to use for rendering\n * @param size This parameter can be set to a single number or to an object with the\n * following (optional) properties: precision, width, height. If a single number is passed,\n * it will be used for both width and height. If an object is passed, the screenshot size\n * will be derived from the parameters. The precision property is a multiplier allowing\n * rendering at a higher or lower resolution\n * @param successCallback The callback receives a single parameter which contains the\n * screenshot as a string of base64-encoded characters. This string can be assigned to the\n * src parameter of an to display it\n * @param mimeType The MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param samples Texture samples (default: 1)\n * @param antialiasing Whether antialiasing should be turned on or not (default: false)\n * @param fileName A name for for the downloaded file.\n * @param renderSprites Whether the sprites should be rendered or not (default: false)\n * @param enableStencilBuffer Whether the stencil buffer should be enabled or not (default: false)\n * @param useLayerMask if the camera's layer mask should be used to filter what should be rendered (default: true)\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n static CreateScreenshotUsingRenderTarget(engine, camera, size, successCallback, mimeType = \"image/png\", samples = 1, antialiasing = false, fileName, renderSprites = false, enableStencilBuffer = false, useLayerMask = true, quality) {\n throw _WarnImport(\"ScreenshotTools\");\n }\n /**\n * Generates an image screenshot from the specified camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine The engine to use for rendering\n * @param camera The camera to use for rendering\n * @param size This parameter can be set to a single number or to an object with the\n * following (optional) properties: precision, width, height. If a single number is passed,\n * it will be used for both width and height. If an object is passed, the screenshot size\n * will be derived from the parameters. The precision property is a multiplier allowing\n * rendering at a higher or lower resolution\n * @param mimeType The MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param samples Texture samples (default: 1)\n * @param antialiasing Whether antialiasing should be turned on or not (default: false)\n * @param fileName A name for for the downloaded file.\n * @returns screenshot as a string of base64-encoded characters. This string can be assigned\n * @param renderSprites Whether the sprites should be rendered or not (default: false)\n * @param enableStencilBuffer Whether the stencil buffer should be enabled or not (default: false)\n * @param useLayerMask if the camera's layer mask should be used to filter what should be rendered (default: true)\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n * to the src parameter of an to display it\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n static CreateScreenshotUsingRenderTargetAsync(engine, camera, size, mimeType = \"image/png\", samples = 1, antialiasing = false, fileName, renderSprites = false, enableStencilBuffer = false, useLayerMask = true, quality) {\n throw _WarnImport(\"ScreenshotTools\");\n }\n /**\n * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523\n * Be aware Math.random() could cause collisions, but:\n * \"All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide\"\n * @returns a pseudo random id\n */\n static RandomId() {\n return RandomGUID();\n }\n /**\n * Test if the given uri is a base64 string\n * @deprecated Please use FileTools.IsBase64DataUrl instead.\n * @param uri The uri to test\n * @returns True if the uri is a base64 string or false otherwise\n */\n static IsBase64(uri) {\n return IsBase64DataUrl(uri);\n }\n /**\n * Decode the given base64 uri.\n * @deprecated Please use FileTools.DecodeBase64UrlToBinary instead.\n * @param uri The uri to decode\n * @returns The decoded base64 data.\n */\n static DecodeBase64(uri) {\n return DecodeBase64UrlToBinary(uri);\n }\n /**\n * Gets a value indicating the number of loading errors\n * @ignorenaming\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static get errorsCount() {\n return Logger.errorsCount;\n }\n /**\n * Log a message to the console\n * @param message defines the message to log\n */\n static Log(message) {\n Logger.Log(message);\n }\n /**\n * Write a warning message to the console\n * @param message defines the message to log\n */\n static Warn(message) {\n Logger.Warn(message);\n }\n /**\n * Write an error message to the console\n * @param message defines the message to log\n */\n static Error(message) {\n Logger.Error(message);\n }\n /**\n * Gets current log cache (list of logs)\n */\n static get LogCache() {\n return Logger.LogCache;\n }\n /**\n * Clears the log cache\n */\n static ClearLogCache() {\n Logger.ClearLogCache();\n }\n /**\n * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)\n */\n static set LogLevels(level) {\n Logger.LogLevels = level;\n }\n /**\n * Sets the current performance log level\n */\n static set PerformanceLogLevel(level) {\n if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {\n Tools.StartPerformanceCounter = Tools._StartUserMark;\n Tools.EndPerformanceCounter = Tools._EndUserMark;\n return;\n }\n if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {\n Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;\n Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;\n return;\n }\n Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;\n Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n static _StartPerformanceCounterDisabled(counterName, condition) { }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n static _EndPerformanceCounterDisabled(counterName, condition) { }\n static _StartUserMark(counterName, condition = true) {\n if (!Tools._Performance) {\n if (!IsWindowObjectExist()) {\n return;\n }\n Tools._Performance = window.performance;\n }\n if (!condition || !Tools._Performance.mark) {\n return;\n }\n Tools._Performance.mark(counterName + \"-Begin\");\n }\n static _EndUserMark(counterName, condition = true) {\n if (!condition || !Tools._Performance.mark) {\n return;\n }\n Tools._Performance.mark(counterName + \"-End\");\n Tools._Performance.measure(counterName, counterName + \"-Begin\", counterName + \"-End\");\n }\n static _StartPerformanceConsole(counterName, condition = true) {\n if (!condition) {\n return;\n }\n Tools._StartUserMark(counterName, condition);\n if (console.time) {\n console.time(counterName);\n }\n }\n static _EndPerformanceConsole(counterName, condition = true) {\n if (!condition) {\n return;\n }\n Tools._EndUserMark(counterName, condition);\n console.timeEnd(counterName);\n }\n /**\n * Gets either window.performance.now() if supported or Date.now() else\n */\n static get Now() {\n return PrecisionDate.Now;\n }\n /**\n * This method will return the name of the class used to create the instance of the given object.\n * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.\n * @param object the object to get the class name from\n * @param isType defines if the object is actually a type\n * @returns the name of the class, will be \"object\" for a custom data type not using the @className decorator\n */\n static GetClassName(object, isType = false) {\n let name = null;\n if (!isType && object.getClassName) {\n name = object.getClassName();\n }\n else {\n if (object instanceof Object) {\n const classObj = isType ? object : Object.getPrototypeOf(object);\n name = classObj.constructor[\"__bjsclassName__\"];\n }\n if (!name) {\n name = typeof object;\n }\n }\n return name;\n }\n /**\n * Gets the first element of an array satisfying a given predicate\n * @param array defines the array to browse\n * @param predicate defines the predicate to use\n * @returns null if not found or the element\n */\n static First(array, predicate) {\n for (const el of array) {\n if (predicate(el)) {\n return el;\n }\n }\n return null;\n }\n /**\n * This method will return the name of the full name of the class, including its owning module (if any).\n * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).\n * @param object the object to get the class name from\n * @param isType defines if the object is actually a type\n * @returns a string that can have two forms: \"moduleName.className\" if module was specified when the class' Name was registered or \"className\" if there was not module specified.\n * @ignorenaming\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static getFullClassName(object, isType = false) {\n let className = null;\n let moduleName = null;\n if (!isType && object.getClassName) {\n className = object.getClassName();\n }\n else {\n if (object instanceof Object) {\n const classObj = isType ? object : Object.getPrototypeOf(object);\n className = classObj.constructor[\"__bjsclassName__\"];\n moduleName = classObj.constructor[\"__bjsmoduleName__\"];\n }\n if (!className) {\n className = typeof object;\n }\n }\n if (!className) {\n return null;\n }\n return (moduleName != null ? moduleName + \".\" : \"\") + className;\n }\n /**\n * Returns a promise that resolves after the given amount of time.\n * @param delay Number of milliseconds to delay\n * @returns Promise that resolves after the given amount of time\n */\n static DelayAsync(delay) {\n return new Promise((resolve) => {\n setTimeout(() => {\n resolve();\n }, delay);\n });\n }\n /**\n * Utility function to detect if the current user agent is Safari\n * @returns whether or not the current user agent is safari\n */\n static IsSafari() {\n if (!IsNavigatorAvailable()) {\n return false;\n }\n return /^((?!chrome|android).)*safari/i.test(navigator.userAgent);\n }\n}\n/**\n * Enable/Disable Custom HTTP Request Headers globally.\n * default = false\n * @see CustomRequestHeaders\n */\nTools.UseCustomRequestHeaders = false;\n/**\n * Custom HTTP Request Headers to be sent with XMLHttpRequests\n * i.e. when loading files, where the server/service expects an Authorization header\n */\nTools.CustomRequestHeaders = WebRequest.CustomRequestHeaders;\nTools._TmpFloatArray = new Float32Array(1);\n/**\n * Extracts text content from a DOM element hierarchy\n * Back Compat only, please use GetDOMTextContent instead.\n */\nTools.GetDOMTextContent = GetDOMTextContent;\nTools.GetAbsoluteUrl = typeof document === \"object\"\n ? (url) => {\n const a = document.createElement(\"a\");\n a.href = url;\n return a.href;\n }\n : typeof URL === \"function\" && typeof location === \"object\"\n ? (url) => new URL(url, location.origin).href\n : () => {\n throw new Error(\"Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.\");\n };\n// Logs\n/**\n * No log\n */\nTools.NoneLogLevel = Logger.NoneLogLevel;\n/**\n * Only message logs\n */\nTools.MessageLogLevel = Logger.MessageLogLevel;\n/**\n * Only warning logs\n */\nTools.WarningLogLevel = Logger.WarningLogLevel;\n/**\n * Only error logs\n */\nTools.ErrorLogLevel = Logger.ErrorLogLevel;\n/**\n * All logs\n */\nTools.AllLogLevel = Logger.AllLogLevel;\n/**\n * Checks if the window object exists\n * Back Compat only, please use IsWindowObjectExist instead.\n */\nTools.IsWindowObjectExist = IsWindowObjectExist;\n// Performances\n/**\n * No performance log\n */\nTools.PerformanceNoneLogLevel = 0;\n/**\n * Use user marks to log performance\n */\nTools.PerformanceUserMarkLogLevel = 1;\n/**\n * Log performance to the console\n */\nTools.PerformanceConsoleLogLevel = 2;\n/**\n * Starts a performance counter\n */\nTools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;\n/**\n * Ends a specific performance counter\n */\nTools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;\n/**\n * Use this className as a decorator on a given class definition to add it a name and optionally its module.\n * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.\n * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified\n * @param name The name of the class, case should be preserved\n * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.\n */\nexport function className(name, module) {\n return (target) => {\n target[\"__bjsclassName__\"] = name;\n target[\"__bjsmoduleName__\"] = module != null ? module : null;\n };\n}\n/**\n * An implementation of a loop for asynchronous functions.\n */\nexport class AsyncLoop {\n /**\n * Constructor.\n * @param iterations the number of iterations.\n * @param func the function to run each iteration\n * @param successCallback the callback that will be called upon successful execution\n * @param offset starting offset.\n */\n constructor(\n /**\n * Defines the number of iterations for the loop\n */\n iterations, func, successCallback, offset = 0) {\n this.iterations = iterations;\n this.index = offset - 1;\n this._done = false;\n this._fn = func;\n this._successCallback = successCallback;\n }\n /**\n * Execute the next iteration. Must be called after the last iteration was finished.\n */\n executeNext() {\n if (!this._done) {\n if (this.index + 1 < this.iterations) {\n ++this.index;\n this._fn(this);\n }\n else {\n this.breakLoop();\n }\n }\n }\n /**\n * Break the loop and run the success callback.\n */\n breakLoop() {\n this._done = true;\n this._successCallback();\n }\n /**\n * Create and run an async loop.\n * @param iterations the number of iterations.\n * @param fn the function to run each iteration\n * @param successCallback the callback that will be called upon successful execution\n * @param offset starting offset.\n * @returns the created async loop object\n */\n static Run(iterations, fn, successCallback, offset = 0) {\n const loop = new AsyncLoop(iterations, fn, successCallback, offset);\n loop.executeNext();\n return loop;\n }\n /**\n * A for-loop that will run a given number of iterations synchronous and the rest async.\n * @param iterations total number of iterations\n * @param syncedIterations number of synchronous iterations in each async iteration.\n * @param fn the function to call each iteration.\n * @param callback a success call back that will be called when iterating stops.\n * @param breakFunction a break condition (optional)\n * @param timeout timeout settings for the setTimeout function. default - 0.\n * @returns the created async loop object\n */\n static SyncAsyncForLoop(iterations, syncedIterations, fn, callback, breakFunction, timeout = 0) {\n return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), (loop) => {\n if (breakFunction && breakFunction()) {\n loop.breakLoop();\n }\n else {\n setTimeout(() => {\n for (let i = 0; i < syncedIterations; ++i) {\n const iteration = loop.index * syncedIterations + i;\n if (iteration >= iterations) {\n break;\n }\n fn(iteration);\n if (breakFunction && breakFunction()) {\n loop.breakLoop();\n break;\n }\n }\n loop.executeNext();\n }, timeout);\n }\n }, callback);\n }\n}\n// Will only be define if Tools is imported freeing up some space when only engine is required\nEngineStore.FallbackTexture =\n \"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\";\n//# sourceMappingURL=tools.js.map","/** @internal */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst _RegisteredTypes = {};\n/**\n * @internal\n */\nexport function RegisterClass(className, type) {\n _RegisteredTypes[className] = type;\n}\n/**\n * @internal\n */\nexport function GetClass(fqdn) {\n return _RegisteredTypes[fqdn];\n}\n//# sourceMappingURL=typeStore.js.map","/**\n * Helper class used to generate session unique ID\n */\nexport class UniqueIdGenerator {\n /**\n * Gets an unique (relatively to the current scene) Id\n */\n static get UniqueId() {\n const result = this._UniqueIdCounter;\n this._UniqueIdCounter++;\n return result;\n }\n}\n// Statics\nUniqueIdGenerator._UniqueIdCounter = 1;\n//# sourceMappingURL=uniqueIdGenerator.js.map","/** @internal */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nfunction createXMLHttpRequest() {\n // If running in Babylon Native, then defer to the native XMLHttpRequest, which has the same public contract\n if (typeof _native !== \"undefined\" && _native.XMLHttpRequest) {\n return new _native.XMLHttpRequest();\n }\n else {\n return new XMLHttpRequest();\n }\n}\n/**\n * Extended version of XMLHttpRequest with support for customizations (headers, ...)\n */\nexport class WebRequest {\n constructor() {\n this._xhr = createXMLHttpRequest();\n this._requestURL = \"\";\n }\n _injectCustomRequestHeaders() {\n if (this._shouldSkipRequestModifications(this._requestURL)) {\n return;\n }\n for (const key in WebRequest.CustomRequestHeaders) {\n const val = WebRequest.CustomRequestHeaders[key];\n if (val) {\n this._xhr.setRequestHeader(key, val);\n }\n }\n }\n _shouldSkipRequestModifications(url) {\n return WebRequest.SkipRequestModificationForBabylonCDN && (url.includes(\"preview.babylonjs.com\") || url.includes(\"cdn.babylonjs.com\"));\n }\n /**\n * Gets or sets a function to be called when loading progress changes\n */\n get onprogress() {\n return this._xhr.onprogress;\n }\n set onprogress(value) {\n this._xhr.onprogress = value;\n }\n /**\n * Returns client's state\n */\n get readyState() {\n return this._xhr.readyState;\n }\n /**\n * Returns client's status\n */\n get status() {\n return this._xhr.status;\n }\n /**\n * Returns client's status as a text\n */\n get statusText() {\n return this._xhr.statusText;\n }\n /**\n * Returns client's response\n */\n get response() {\n return this._xhr.response;\n }\n /**\n * Returns client's response url\n */\n get responseURL() {\n return this._xhr.responseURL;\n }\n /**\n * Returns client's response as text\n */\n get responseText() {\n return this._xhr.responseText;\n }\n /**\n * Gets or sets the expected response type\n */\n get responseType() {\n return this._xhr.responseType;\n }\n set responseType(value) {\n this._xhr.responseType = value;\n }\n /**\n * Gets or sets the timeout value in milliseconds\n */\n get timeout() {\n return this._xhr.timeout;\n }\n set timeout(value) {\n this._xhr.timeout = value;\n }\n addEventListener(type, listener, options) {\n this._xhr.addEventListener(type, listener, options);\n }\n removeEventListener(type, listener, options) {\n this._xhr.removeEventListener(type, listener, options);\n }\n /**\n * Cancels any network activity\n */\n abort() {\n this._xhr.abort();\n }\n /**\n * Initiates the request. The optional argument provides the request body. The argument is ignored if request method is GET or HEAD\n * @param body defines an optional request body\n */\n send(body) {\n if (WebRequest.CustomRequestHeaders) {\n this._injectCustomRequestHeaders();\n }\n this._xhr.send(body);\n }\n /**\n * Sets the request method, request URL\n * @param method defines the method to use (GET, POST, etc..)\n * @param url defines the url to connect with\n */\n open(method, url) {\n for (const update of WebRequest.CustomRequestModifiers) {\n if (this._shouldSkipRequestModifications(url)) {\n return;\n }\n update(this._xhr, url);\n }\n // Clean url\n url = url.replace(\"file:http:\", \"http:\");\n url = url.replace(\"file:https:\", \"https:\");\n this._requestURL = url;\n return this._xhr.open(method, url, true);\n }\n /**\n * Sets the value of a request header.\n * @param name The name of the header whose value is to be set\n * @param value The value to set as the body of the header\n */\n setRequestHeader(name, value) {\n this._xhr.setRequestHeader(name, value);\n }\n /**\n * Get the string containing the text of a particular header's value.\n * @param name The name of the header\n * @returns The string containing the text of the given header name\n */\n getResponseHeader(name) {\n return this._xhr.getResponseHeader(name);\n }\n}\n/**\n * Custom HTTP Request Headers to be sent with XMLHttpRequests\n * i.e. when loading files, where the server/service expects an Authorization header\n */\nWebRequest.CustomRequestHeaders = {};\n/**\n * Add callback functions in this array to update all the requests before they get sent to the network\n */\nWebRequest.CustomRequestModifiers = new Array();\nWebRequest.SkipRequestModificationForBabylonCDN = true;\n//# sourceMappingURL=webRequest.js.map","import { VertexBuffer } from \"../Buffers/buffer.js\";\n\n/**\n * PostProcessManager is used to manage one or more post processes or post process pipelines\n * See https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses\n */\nexport class PostProcessManager {\n /**\n * Creates a new instance PostProcess\n * @param scene The scene that the post process is associated with.\n */\n constructor(scene) {\n this._vertexBuffers = {};\n this._scene = scene;\n }\n _prepareBuffers() {\n if (this._vertexBuffers[VertexBuffer.PositionKind]) {\n return;\n }\n // VBO\n const vertices = [];\n vertices.push(1, 1);\n vertices.push(-1, 1);\n vertices.push(-1, -1);\n vertices.push(1, -1);\n this._vertexBuffers[VertexBuffer.PositionKind] = new VertexBuffer(this._scene.getEngine(), vertices, VertexBuffer.PositionKind, false, false, 2);\n this._buildIndexBuffer();\n }\n _buildIndexBuffer() {\n // Indices\n const indices = [];\n indices.push(0);\n indices.push(1);\n indices.push(2);\n indices.push(0);\n indices.push(2);\n indices.push(3);\n this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);\n }\n /**\n * Rebuilds the vertex buffers of the manager.\n * @internal\n */\n _rebuild() {\n const vb = this._vertexBuffers[VertexBuffer.PositionKind];\n if (!vb) {\n return;\n }\n vb._rebuild();\n this._buildIndexBuffer();\n }\n // Methods\n /**\n * Prepares a frame to be run through a post process.\n * @param sourceTexture The input texture to the post processes. (default: null)\n * @param postProcesses An array of post processes to be run. (default: null)\n * @returns True if the post processes were able to be run.\n * @internal\n */\n _prepareFrame(sourceTexture = null, postProcesses = null) {\n const camera = this._scene.activeCamera;\n if (!camera) {\n return false;\n }\n postProcesses = postProcesses || camera._postProcesses.filter((pp) => {\n return pp != null;\n });\n if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {\n return false;\n }\n postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);\n return true;\n }\n /**\n * Manually render a set of post processes to a texture.\n * Please note, the frame buffer won't be unbound after the call in case you have more render to do.\n * @param postProcesses An array of post processes to be run.\n * @param targetTexture The render target wrapper to render to.\n * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight\n * @param faceIndex defines the face to render to if a cubemap is defined as the target\n * @param lodLevel defines which lod of the texture to render to\n * @param doNotBindFrambuffer If set to true, assumes that the framebuffer has been bound previously\n */\n directRender(postProcesses, targetTexture = null, forceFullscreenViewport = false, faceIndex = 0, lodLevel = 0, doNotBindFrambuffer = false) {\n var _a;\n const engine = this._scene.getEngine();\n for (let index = 0; index < postProcesses.length; index++) {\n if (index < postProcesses.length - 1) {\n postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture === null || targetTexture === void 0 ? void 0 : targetTexture.texture);\n }\n else {\n if (targetTexture) {\n engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, lodLevel);\n }\n else if (!doNotBindFrambuffer) {\n engine.restoreDefaultFramebuffer();\n }\n (_a = engine._debugInsertMarker) === null || _a === void 0 ? void 0 : _a.call(engine, `post process ${postProcesses[index].name} output`);\n }\n const pp = postProcesses[index];\n const effect = pp.apply();\n if (effect) {\n pp.onBeforeRenderObservable.notifyObservers(effect);\n // VBOs\n this._prepareBuffers();\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);\n // Draw order\n engine.drawElementsType(0, 0, 6);\n pp.onAfterRenderObservable.notifyObservers(effect);\n }\n }\n // Restore depth buffer\n engine.setDepthBuffer(true);\n engine.setDepthWrite(true);\n }\n /**\n * Finalize the result of the output of the postprocesses.\n * @param doNotPresent If true the result will not be displayed to the screen.\n * @param targetTexture The render target wrapper to render to.\n * @param faceIndex The index of the face to bind the target texture to.\n * @param postProcesses The array of post processes to render.\n * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)\n * @internal\n */\n _finalizeFrame(doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport = false) {\n var _a;\n const camera = this._scene.activeCamera;\n if (!camera) {\n return;\n }\n postProcesses = postProcesses || camera._postProcesses.filter((pp) => {\n return pp != null;\n });\n if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {\n return;\n }\n const engine = this._scene.getEngine();\n for (let index = 0, len = postProcesses.length; index < len; index++) {\n const pp = postProcesses[index];\n if (index < len - 1) {\n pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture === null || targetTexture === void 0 ? void 0 : targetTexture.texture);\n }\n else {\n if (targetTexture) {\n engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);\n pp._outputTexture = targetTexture;\n }\n else {\n engine.restoreDefaultFramebuffer();\n pp._outputTexture = null;\n }\n (_a = engine._debugInsertMarker) === null || _a === void 0 ? void 0 : _a.call(engine, `post process ${postProcesses[index].name} output`);\n }\n if (doNotPresent) {\n break;\n }\n const effect = pp.apply();\n if (effect) {\n pp.onBeforeRenderObservable.notifyObservers(effect);\n // VBOs\n this._prepareBuffers();\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);\n // Draw order\n engine.drawElementsType(0, 0, 6);\n pp.onAfterRenderObservable.notifyObservers(effect);\n }\n }\n // Restore states\n engine.setDepthBuffer(true);\n engine.setDepthWrite(true);\n engine.setAlphaMode(0);\n }\n /**\n * Disposes of the post process manager.\n */\n dispose() {\n const buffer = this._vertexBuffers[VertexBuffer.PositionKind];\n if (buffer) {\n buffer.dispose();\n this._vertexBuffers[VertexBuffer.PositionKind] = null;\n }\n if (this._indexBuffer) {\n this._scene.getEngine()._releaseBuffer(this._indexBuffer);\n this._indexBuffer = null;\n }\n }\n}\n//# sourceMappingURL=postProcessManager.js.map","import { SmartArray, SmartArrayNoDuplicate } from \"../Misc/smartArray.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\n\n/**\n * This represents the object necessary to create a rendering group.\n * This is exclusively used and created by the rendering manager.\n * To modify the behavior, you use the available helpers in your scene or meshes.\n * @internal\n */\nexport class RenderingGroup {\n /**\n * Set the opaque sort comparison function.\n * If null the sub meshes will be render in the order they were created\n */\n set opaqueSortCompareFn(value) {\n if (value) {\n this._opaqueSortCompareFn = value;\n }\n else {\n this._opaqueSortCompareFn = RenderingGroup.PainterSortCompare;\n }\n this._renderOpaque = this._renderOpaqueSorted;\n }\n /**\n * Set the alpha test sort comparison function.\n * If null the sub meshes will be render in the order they were created\n */\n set alphaTestSortCompareFn(value) {\n if (value) {\n this._alphaTestSortCompareFn = value;\n }\n else {\n this._alphaTestSortCompareFn = RenderingGroup.PainterSortCompare;\n }\n this._renderAlphaTest = this._renderAlphaTestSorted;\n }\n /**\n * Set the transparent sort comparison function.\n * If null the sub meshes will be render in the order they were created\n */\n set transparentSortCompareFn(value) {\n if (value) {\n this._transparentSortCompareFn = value;\n }\n else {\n this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;\n }\n this._renderTransparent = this._renderTransparentSorted;\n }\n /**\n * Creates a new rendering group.\n * @param index The rendering group index\n * @param scene\n * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied\n * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied\n * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied\n */\n constructor(index, scene, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) {\n this.index = index;\n this._opaqueSubMeshes = new SmartArray(256);\n this._transparentSubMeshes = new SmartArray(256);\n this._alphaTestSubMeshes = new SmartArray(256);\n this._depthOnlySubMeshes = new SmartArray(256);\n this._particleSystems = new SmartArray(256);\n this._spriteManagers = new SmartArray(256);\n /** @internal */\n this._empty = true;\n /** @internal */\n this._edgesRenderers = new SmartArrayNoDuplicate(16);\n this._scene = scene;\n this.opaqueSortCompareFn = opaqueSortCompareFn;\n this.alphaTestSortCompareFn = alphaTestSortCompareFn;\n this.transparentSortCompareFn = transparentSortCompareFn;\n }\n /**\n * Render all the sub meshes contained in the group.\n * @param customRenderFunction Used to override the default render behaviour of the group.\n * @param renderSprites\n * @param renderParticles\n * @param activeMeshes\n * @returns true if rendered some submeshes.\n */\n render(customRenderFunction, renderSprites, renderParticles, activeMeshes) {\n if (customRenderFunction) {\n customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);\n return;\n }\n const engine = this._scene.getEngine();\n // Depth only\n if (this._depthOnlySubMeshes.length !== 0) {\n engine.setColorWrite(false);\n this._renderAlphaTest(this._depthOnlySubMeshes);\n engine.setColorWrite(true);\n }\n // Opaque\n if (this._opaqueSubMeshes.length !== 0) {\n this._renderOpaque(this._opaqueSubMeshes);\n }\n // Alpha test\n if (this._alphaTestSubMeshes.length !== 0) {\n this._renderAlphaTest(this._alphaTestSubMeshes);\n }\n const stencilState = engine.getStencilBuffer();\n engine.setStencilBuffer(false);\n // Sprites\n if (renderSprites) {\n this._renderSprites();\n }\n // Particles\n if (renderParticles) {\n this._renderParticles(activeMeshes);\n }\n if (this.onBeforeTransparentRendering) {\n this.onBeforeTransparentRendering();\n }\n // Transparent\n if (this._transparentSubMeshes.length !== 0 || this._scene.useOrderIndependentTransparency) {\n engine.setStencilBuffer(stencilState);\n if (this._scene.useOrderIndependentTransparency) {\n const excludedMeshes = this._scene.depthPeelingRenderer.render(this._transparentSubMeshes);\n if (excludedMeshes.length) {\n // Render leftover meshes that could not be processed by depth peeling\n this._renderTransparent(excludedMeshes);\n }\n }\n else {\n this._renderTransparent(this._transparentSubMeshes);\n }\n engine.setAlphaMode(0);\n }\n // Set back stencil to false in case it changes before the edge renderer.\n engine.setStencilBuffer(false);\n // Edges\n if (this._edgesRenderers.length) {\n for (let edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {\n this._edgesRenderers.data[edgesRendererIndex].render();\n }\n engine.setAlphaMode(0);\n }\n // Restore Stencil state.\n engine.setStencilBuffer(stencilState);\n }\n /**\n * Renders the opaque submeshes in the order from the opaqueSortCompareFn.\n * @param subMeshes The submeshes to render\n */\n _renderOpaqueSorted(subMeshes) {\n return RenderingGroup._RenderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);\n }\n /**\n * Renders the opaque submeshes in the order from the alphatestSortCompareFn.\n * @param subMeshes The submeshes to render\n */\n _renderAlphaTestSorted(subMeshes) {\n return RenderingGroup._RenderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);\n }\n /**\n * Renders the opaque submeshes in the order from the transparentSortCompareFn.\n * @param subMeshes The submeshes to render\n */\n _renderTransparentSorted(subMeshes) {\n return RenderingGroup._RenderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);\n }\n /**\n * Renders the submeshes in a specified order.\n * @param subMeshes The submeshes to sort before render\n * @param sortCompareFn The comparison function use to sort\n * @param camera The camera position use to preprocess the submeshes to help sorting\n * @param transparent Specifies to activate blending if true\n */\n static _RenderSorted(subMeshes, sortCompareFn, camera, transparent) {\n let subIndex = 0;\n let subMesh;\n const cameraPosition = camera ? camera.globalPosition : RenderingGroup._ZeroVector;\n if (transparent) {\n for (; subIndex < subMeshes.length; subIndex++) {\n subMesh = subMeshes.data[subIndex];\n subMesh._alphaIndex = subMesh.getMesh().alphaIndex;\n subMesh._distanceToCamera = Vector3.Distance(subMesh.getBoundingInfo().boundingSphere.centerWorld, cameraPosition);\n }\n }\n const sortedArray = subMeshes.length === subMeshes.data.length ? subMeshes.data : subMeshes.data.slice(0, subMeshes.length);\n if (sortCompareFn) {\n sortedArray.sort(sortCompareFn);\n }\n const scene = sortedArray[0].getMesh().getScene();\n for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {\n subMesh = sortedArray[subIndex];\n if (scene._activeMeshesFrozenButKeepClipping && !subMesh.isInFrustum(scene._frustumPlanes)) {\n continue;\n }\n if (transparent) {\n const material = subMesh.getMaterial();\n if (material && material.needDepthPrePass) {\n const engine = material.getScene().getEngine();\n engine.setColorWrite(false);\n engine.setAlphaMode(0);\n subMesh.render(false);\n engine.setColorWrite(true);\n }\n }\n subMesh.render(transparent);\n }\n }\n /**\n * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)\n * are rendered back to front if in the same alpha index.\n *\n * @param a The first submesh\n * @param b The second submesh\n * @returns The result of the comparison\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static defaultTransparentSortCompare(a, b) {\n // Alpha index first\n if (a._alphaIndex > b._alphaIndex) {\n return 1;\n }\n if (a._alphaIndex < b._alphaIndex) {\n return -1;\n }\n // Then distance to camera\n return RenderingGroup.backToFrontSortCompare(a, b);\n }\n /**\n * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)\n * are rendered back to front.\n *\n * @param a The first submesh\n * @param b The second submesh\n * @returns The result of the comparison\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static backToFrontSortCompare(a, b) {\n // Then distance to camera\n if (a._distanceToCamera < b._distanceToCamera) {\n return 1;\n }\n if (a._distanceToCamera > b._distanceToCamera) {\n return -1;\n }\n return 0;\n }\n /**\n * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)\n * are rendered front to back (prevent overdraw).\n *\n * @param a The first submesh\n * @param b The second submesh\n * @returns The result of the comparison\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static frontToBackSortCompare(a, b) {\n // Then distance to camera\n if (a._distanceToCamera < b._distanceToCamera) {\n return -1;\n }\n if (a._distanceToCamera > b._distanceToCamera) {\n return 1;\n }\n return 0;\n }\n /**\n * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)\n * are grouped by material then geometry.\n *\n * @param a The first submesh\n * @param b The second submesh\n * @returns The result of the comparison\n */\n static PainterSortCompare(a, b) {\n const meshA = a.getMesh();\n const meshB = b.getMesh();\n if (meshA.material && meshB.material) {\n return meshA.material.uniqueId - meshB.material.uniqueId;\n }\n return meshA.uniqueId - meshB.uniqueId;\n }\n /**\n * Resets the different lists of submeshes to prepare a new frame.\n */\n prepare() {\n this._opaqueSubMeshes.reset();\n this._transparentSubMeshes.reset();\n this._alphaTestSubMeshes.reset();\n this._depthOnlySubMeshes.reset();\n this._particleSystems.reset();\n this.prepareSprites();\n this._edgesRenderers.reset();\n this._empty = true;\n }\n /**\n * Resets the different lists of sprites to prepare a new frame.\n */\n prepareSprites() {\n this._spriteManagers.reset();\n }\n dispose() {\n this._opaqueSubMeshes.dispose();\n this._transparentSubMeshes.dispose();\n this._alphaTestSubMeshes.dispose();\n this._depthOnlySubMeshes.dispose();\n this._particleSystems.dispose();\n this._spriteManagers.dispose();\n this._edgesRenderers.dispose();\n }\n /**\n * Inserts the submesh in its correct queue depending on its material.\n * @param subMesh The submesh to dispatch\n * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.\n * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.\n */\n dispatch(subMesh, mesh, material) {\n // Get mesh and materials if not provided\n if (mesh === undefined) {\n mesh = subMesh.getMesh();\n }\n if (material === undefined) {\n material = subMesh.getMaterial();\n }\n if (material === null || material === undefined) {\n return;\n }\n if (material.needAlphaBlendingForMesh(mesh)) {\n // Transparent\n this._transparentSubMeshes.push(subMesh);\n }\n else if (material.needAlphaTesting()) {\n // Alpha test\n if (material.needDepthPrePass) {\n this._depthOnlySubMeshes.push(subMesh);\n }\n this._alphaTestSubMeshes.push(subMesh);\n }\n else {\n if (material.needDepthPrePass) {\n this._depthOnlySubMeshes.push(subMesh);\n }\n this._opaqueSubMeshes.push(subMesh); // Opaque\n }\n mesh._renderingGroup = this;\n if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {\n this._edgesRenderers.pushNoDuplicate(mesh._edgesRenderer);\n }\n this._empty = false;\n }\n dispatchSprites(spriteManager) {\n this._spriteManagers.push(spriteManager);\n this._empty = false;\n }\n dispatchParticles(particleSystem) {\n this._particleSystems.push(particleSystem);\n this._empty = false;\n }\n _renderParticles(activeMeshes) {\n if (this._particleSystems.length === 0) {\n return;\n }\n // Particles\n const activeCamera = this._scene.activeCamera;\n this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);\n for (let particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {\n const particleSystem = this._particleSystems.data[particleIndex];\n if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {\n continue;\n }\n const emitter = particleSystem.emitter;\n if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {\n this._scene._activeParticles.addCount(particleSystem.render(), false);\n }\n }\n this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);\n }\n _renderSprites() {\n if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {\n return;\n }\n // Sprites\n const activeCamera = this._scene.activeCamera;\n this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);\n for (let id = 0; id < this._spriteManagers.length; id++) {\n const spriteManager = this._spriteManagers.data[id];\n if ((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0) {\n spriteManager.render();\n }\n }\n this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);\n }\n}\nRenderingGroup._ZeroVector = Vector3.Zero();\n//# sourceMappingURL=renderingGroup.js.map","import { RenderingGroup } from \"./renderingGroup.js\";\n/**\n * This class is used by the onRenderingGroupObservable\n */\nexport class RenderingGroupInfo {\n}\n/**\n * This is the manager responsible of all the rendering for meshes sprites and particles.\n * It is enable to manage the different groups as well as the different necessary sort functions.\n * This should not be used directly aside of the few static configurations\n */\nexport class RenderingManager {\n /**\n * Gets or sets a boolean indicating that the manager will not reset between frames.\n * This means that if a mesh becomes invisible or transparent it will not be visible until this boolean is set to false again.\n * By default, the rendering manager will dispatch all active meshes per frame (moving them to the transparent, opaque or alpha testing lists).\n * By turning this property on, you will accelerate the rendering by keeping all these lists unchanged between frames.\n */\n get maintainStateBetweenFrames() {\n return this._maintainStateBetweenFrames;\n }\n set maintainStateBetweenFrames(value) {\n if (value === this._maintainStateBetweenFrames) {\n return;\n }\n this._maintainStateBetweenFrames = value;\n // Restore wasDispatched flags when switching to maintainStateBetweenFrames to false\n if (!this._maintainStateBetweenFrames) {\n for (const mesh of this._scene.meshes) {\n if (mesh.subMeshes) {\n for (const subMesh of mesh.subMeshes) {\n subMesh._wasDispatched = false;\n }\n }\n }\n if (this._scene.spriteManagers) {\n for (const spriteManager of this._scene.spriteManagers) {\n spriteManager._wasDispatched = false;\n }\n }\n for (const particleSystem of this._scene.particleSystems) {\n particleSystem._wasDispatched = false;\n }\n }\n }\n /**\n * Instantiates a new rendering group for a particular scene\n * @param scene Defines the scene the groups belongs to\n */\n constructor(scene) {\n /**\n * @internal\n */\n this._useSceneAutoClearSetup = false;\n this._renderingGroups = new Array();\n this._autoClearDepthStencil = {};\n this._customOpaqueSortCompareFn = {};\n this._customAlphaTestSortCompareFn = {};\n this._customTransparentSortCompareFn = {};\n this._renderingGroupInfo = new RenderingGroupInfo();\n this._maintainStateBetweenFrames = false;\n this._scene = scene;\n for (let i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {\n this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };\n }\n }\n /**\n * Gets the rendering group with the specified id.\n */\n getRenderingGroup(id) {\n const renderingGroupId = id || 0;\n this._prepareRenderingGroup(renderingGroupId);\n return this._renderingGroups[renderingGroupId];\n }\n _clearDepthStencilBuffer(depth = true, stencil = true) {\n if (this._depthStencilBufferAlreadyCleaned) {\n return;\n }\n this._scene.getEngine().clear(null, false, depth, stencil);\n this._depthStencilBufferAlreadyCleaned = true;\n }\n /**\n * Renders the entire managed groups. This is used by the scene or the different render targets.\n * @internal\n */\n render(customRenderFunction, activeMeshes, renderParticles, renderSprites) {\n // Update the observable context (not null as it only goes away on dispose)\n const info = this._renderingGroupInfo;\n info.scene = this._scene;\n info.camera = this._scene.activeCamera;\n // Dispatch sprites\n if (this._scene.spriteManagers && renderSprites) {\n for (let index = 0; index < this._scene.spriteManagers.length; index++) {\n const manager = this._scene.spriteManagers[index];\n this.dispatchSprites(manager);\n }\n }\n // Render\n for (let index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {\n this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;\n const renderingGroup = this._renderingGroups[index];\n if (!renderingGroup || renderingGroup._empty) {\n continue;\n }\n const renderingGroupMask = Math.pow(2, index);\n info.renderingGroupId = index;\n // Before Observable\n this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);\n // Clear depth/stencil if needed\n if (RenderingManager.AUTOCLEAR) {\n const autoClear = this._useSceneAutoClearSetup ? this._scene.getAutoClearDepthStencilSetup(index) : this._autoClearDepthStencil[index];\n if (autoClear && autoClear.autoClear) {\n this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);\n }\n }\n // Render\n for (const step of this._scene._beforeRenderingGroupDrawStage) {\n step.action(index);\n }\n renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);\n for (const step of this._scene._afterRenderingGroupDrawStage) {\n step.action(index);\n }\n // After Observable\n this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);\n }\n }\n /**\n * Resets the different information of the group to prepare a new frame\n * @internal\n */\n reset() {\n if (this.maintainStateBetweenFrames) {\n return;\n }\n for (let index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {\n const renderingGroup = this._renderingGroups[index];\n if (renderingGroup) {\n renderingGroup.prepare();\n }\n }\n }\n /**\n * Resets the sprites information of the group to prepare a new frame\n * @internal\n */\n resetSprites() {\n if (this.maintainStateBetweenFrames) {\n return;\n }\n for (let index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {\n const renderingGroup = this._renderingGroups[index];\n if (renderingGroup) {\n renderingGroup.prepareSprites();\n }\n }\n }\n /**\n * Dispose and release the group and its associated resources.\n * @internal\n */\n dispose() {\n this.freeRenderingGroups();\n this._renderingGroups.length = 0;\n this._renderingGroupInfo = null;\n }\n /**\n * Clear the info related to rendering groups preventing retention points during dispose.\n */\n freeRenderingGroups() {\n for (let index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {\n const renderingGroup = this._renderingGroups[index];\n if (renderingGroup) {\n renderingGroup.dispose();\n }\n }\n }\n _prepareRenderingGroup(renderingGroupId) {\n if (this._renderingGroups[renderingGroupId] === undefined) {\n this._renderingGroups[renderingGroupId] = new RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);\n }\n }\n /**\n * Add a sprite manager to the rendering manager in order to render it this frame.\n * @param spriteManager Define the sprite manager to render\n */\n dispatchSprites(spriteManager) {\n if (this.maintainStateBetweenFrames && spriteManager._wasDispatched) {\n return;\n }\n spriteManager._wasDispatched = true;\n this.getRenderingGroup(spriteManager.renderingGroupId).dispatchSprites(spriteManager);\n }\n /**\n * Add a particle system to the rendering manager in order to render it this frame.\n * @param particleSystem Define the particle system to render\n */\n dispatchParticles(particleSystem) {\n if (this.maintainStateBetweenFrames && particleSystem._wasDispatched) {\n return;\n }\n particleSystem._wasDispatched = true;\n this.getRenderingGroup(particleSystem.renderingGroupId).dispatchParticles(particleSystem);\n }\n /**\n * Add a submesh to the manager in order to render it this frame\n * @param subMesh The submesh to dispatch\n * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.\n * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.\n */\n dispatch(subMesh, mesh, material) {\n if (mesh === undefined) {\n mesh = subMesh.getMesh();\n }\n if (this.maintainStateBetweenFrames && subMesh._wasDispatched) {\n return;\n }\n subMesh._wasDispatched = true;\n this.getRenderingGroup(mesh.renderingGroupId).dispatch(subMesh, mesh, material);\n }\n /**\n * Overrides the default sort function applied in the rendering group to prepare the meshes.\n * This allowed control for front to back rendering or reversely depending of the special needs.\n *\n * @param renderingGroupId The rendering group id corresponding to its index\n * @param opaqueSortCompareFn The opaque queue comparison function use to sort.\n * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.\n * @param transparentSortCompareFn The transparent queue comparison function use to sort.\n */\n setRenderingOrder(renderingGroupId, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) {\n this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;\n this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;\n this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;\n if (this._renderingGroups[renderingGroupId]) {\n const group = this._renderingGroups[renderingGroupId];\n group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];\n group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];\n group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];\n }\n }\n /**\n * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.\n *\n * @param renderingGroupId The rendering group id corresponding to its index\n * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.\n * @param depth Automatically clears depth between groups if true and autoClear is true.\n * @param stencil Automatically clears stencil between groups if true and autoClear is true.\n */\n setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth = true, stencil = true) {\n this._autoClearDepthStencil[renderingGroupId] = {\n autoClear: autoClearDepthStencil,\n depth: depth,\n stencil: stencil,\n };\n }\n /**\n * Gets the current auto clear configuration for one rendering group of the rendering\n * manager.\n * @param index the rendering group index to get the information for\n * @returns The auto clear setup for the requested rendering group\n */\n getAutoClearDepthStencilSetup(index) {\n return this._autoClearDepthStencil[index];\n }\n}\n/**\n * The max id used for rendering groups (not included)\n */\nRenderingManager.MAX_RENDERINGGROUPS = 4;\n/**\n * The min id used for rendering groups (included)\n */\nRenderingManager.MIN_RENDERINGGROUPS = 0;\n/**\n * Used to globally prevent autoclearing scenes.\n */\nRenderingManager.AUTOCLEAR = true;\n//# sourceMappingURL=renderingManager.js.map","/**\n * @internal\n **/\nexport class AlphaState {\n /**\n * Initializes the state.\n */\n constructor() {\n this._blendFunctionParameters = new Array(4);\n this._blendEquationParameters = new Array(2);\n this._blendConstants = new Array(4);\n this._isBlendConstantsDirty = false;\n this._alphaBlend = false;\n this._isAlphaBlendDirty = false;\n this._isBlendFunctionParametersDirty = false;\n this._isBlendEquationParametersDirty = false;\n this.reset();\n }\n get isDirty() {\n return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty || this._isBlendEquationParametersDirty;\n }\n get alphaBlend() {\n return this._alphaBlend;\n }\n set alphaBlend(value) {\n if (this._alphaBlend === value) {\n return;\n }\n this._alphaBlend = value;\n this._isAlphaBlendDirty = true;\n }\n setAlphaBlendConstants(r, g, b, a) {\n if (this._blendConstants[0] === r && this._blendConstants[1] === g && this._blendConstants[2] === b && this._blendConstants[3] === a) {\n return;\n }\n this._blendConstants[0] = r;\n this._blendConstants[1] = g;\n this._blendConstants[2] = b;\n this._blendConstants[3] = a;\n this._isBlendConstantsDirty = true;\n }\n setAlphaBlendFunctionParameters(value0, value1, value2, value3) {\n if (this._blendFunctionParameters[0] === value0 &&\n this._blendFunctionParameters[1] === value1 &&\n this._blendFunctionParameters[2] === value2 &&\n this._blendFunctionParameters[3] === value3) {\n return;\n }\n this._blendFunctionParameters[0] = value0;\n this._blendFunctionParameters[1] = value1;\n this._blendFunctionParameters[2] = value2;\n this._blendFunctionParameters[3] = value3;\n this._isBlendFunctionParametersDirty = true;\n }\n setAlphaEquationParameters(rgb, alpha) {\n if (this._blendEquationParameters[0] === rgb && this._blendEquationParameters[1] === alpha) {\n return;\n }\n this._blendEquationParameters[0] = rgb;\n this._blendEquationParameters[1] = alpha;\n this._isBlendEquationParametersDirty = true;\n }\n reset() {\n this._alphaBlend = false;\n this._blendFunctionParameters[0] = null;\n this._blendFunctionParameters[1] = null;\n this._blendFunctionParameters[2] = null;\n this._blendFunctionParameters[3] = null;\n this._blendEquationParameters[0] = null;\n this._blendEquationParameters[1] = null;\n this._blendConstants[0] = null;\n this._blendConstants[1] = null;\n this._blendConstants[2] = null;\n this._blendConstants[3] = null;\n this._isAlphaBlendDirty = true;\n this._isBlendFunctionParametersDirty = false;\n this._isBlendEquationParametersDirty = false;\n this._isBlendConstantsDirty = false;\n }\n apply(gl) {\n if (!this.isDirty) {\n return;\n }\n // Alpha blend\n if (this._isAlphaBlendDirty) {\n if (this._alphaBlend) {\n gl.enable(gl.BLEND);\n }\n else {\n gl.disable(gl.BLEND);\n }\n this._isAlphaBlendDirty = false;\n }\n // Alpha function\n if (this._isBlendFunctionParametersDirty) {\n gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);\n this._isBlendFunctionParametersDirty = false;\n }\n // Alpha equation\n if (this._isBlendEquationParametersDirty) {\n gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);\n this._isBlendEquationParametersDirty = false;\n }\n // Constants\n if (this._isBlendConstantsDirty) {\n gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);\n this._isBlendConstantsDirty = false;\n }\n }\n}\n//# sourceMappingURL=alphaCullingState.js.map","/**\n * @internal\n **/\nexport class DepthCullingState {\n /**\n * Initializes the state.\n * @param reset\n */\n constructor(reset = true) {\n this._isDepthTestDirty = false;\n this._isDepthMaskDirty = false;\n this._isDepthFuncDirty = false;\n this._isCullFaceDirty = false;\n this._isCullDirty = false;\n this._isZOffsetDirty = false;\n this._isFrontFaceDirty = false;\n if (reset) {\n this.reset();\n }\n }\n get isDirty() {\n return (this._isDepthFuncDirty ||\n this._isDepthTestDirty ||\n this._isDepthMaskDirty ||\n this._isCullFaceDirty ||\n this._isCullDirty ||\n this._isZOffsetDirty ||\n this._isFrontFaceDirty);\n }\n get zOffset() {\n return this._zOffset;\n }\n set zOffset(value) {\n if (this._zOffset === value) {\n return;\n }\n this._zOffset = value;\n this._isZOffsetDirty = true;\n }\n get zOffsetUnits() {\n return this._zOffsetUnits;\n }\n set zOffsetUnits(value) {\n if (this._zOffsetUnits === value) {\n return;\n }\n this._zOffsetUnits = value;\n this._isZOffsetDirty = true;\n }\n get cullFace() {\n return this._cullFace;\n }\n set cullFace(value) {\n if (this._cullFace === value) {\n return;\n }\n this._cullFace = value;\n this._isCullFaceDirty = true;\n }\n get cull() {\n return this._cull;\n }\n set cull(value) {\n if (this._cull === value) {\n return;\n }\n this._cull = value;\n this._isCullDirty = true;\n }\n get depthFunc() {\n return this._depthFunc;\n }\n set depthFunc(value) {\n if (this._depthFunc === value) {\n return;\n }\n this._depthFunc = value;\n this._isDepthFuncDirty = true;\n }\n get depthMask() {\n return this._depthMask;\n }\n set depthMask(value) {\n if (this._depthMask === value) {\n return;\n }\n this._depthMask = value;\n this._isDepthMaskDirty = true;\n }\n get depthTest() {\n return this._depthTest;\n }\n set depthTest(value) {\n if (this._depthTest === value) {\n return;\n }\n this._depthTest = value;\n this._isDepthTestDirty = true;\n }\n get frontFace() {\n return this._frontFace;\n }\n set frontFace(value) {\n if (this._frontFace === value) {\n return;\n }\n this._frontFace = value;\n this._isFrontFaceDirty = true;\n }\n reset() {\n this._depthMask = true;\n this._depthTest = true;\n this._depthFunc = null;\n this._cullFace = null;\n this._cull = null;\n this._zOffset = 0;\n this._zOffsetUnits = 0;\n this._frontFace = null;\n this._isDepthTestDirty = true;\n this._isDepthMaskDirty = true;\n this._isDepthFuncDirty = false;\n this._isCullFaceDirty = false;\n this._isCullDirty = false;\n this._isZOffsetDirty = true;\n this._isFrontFaceDirty = false;\n }\n apply(gl) {\n if (!this.isDirty) {\n return;\n }\n // Cull\n if (this._isCullDirty) {\n if (this.cull) {\n gl.enable(gl.CULL_FACE);\n }\n else {\n gl.disable(gl.CULL_FACE);\n }\n this._isCullDirty = false;\n }\n // Cull face\n if (this._isCullFaceDirty) {\n gl.cullFace(this.cullFace);\n this._isCullFaceDirty = false;\n }\n // Depth mask\n if (this._isDepthMaskDirty) {\n gl.depthMask(this.depthMask);\n this._isDepthMaskDirty = false;\n }\n // Depth test\n if (this._isDepthTestDirty) {\n if (this.depthTest) {\n gl.enable(gl.DEPTH_TEST);\n }\n else {\n gl.disable(gl.DEPTH_TEST);\n }\n this._isDepthTestDirty = false;\n }\n // Depth func\n if (this._isDepthFuncDirty) {\n gl.depthFunc(this.depthFunc);\n this._isDepthFuncDirty = false;\n }\n // zOffset\n if (this._isZOffsetDirty) {\n if (this.zOffset || this.zOffsetUnits) {\n gl.enable(gl.POLYGON_OFFSET_FILL);\n gl.polygonOffset(this.zOffset, this.zOffsetUnits);\n }\n else {\n gl.disable(gl.POLYGON_OFFSET_FILL);\n }\n this._isZOffsetDirty = false;\n }\n // Front face\n if (this._isFrontFaceDirty) {\n gl.frontFace(this.frontFace);\n this._isFrontFaceDirty = false;\n }\n }\n}\n//# sourceMappingURL=depthCullingState.js.map","\n/**\n * @internal\n **/\nexport class StencilState {\n constructor() {\n this.reset();\n }\n reset() {\n this.enabled = false;\n this.mask = 0xff;\n this.func = StencilState.ALWAYS;\n this.funcRef = 1;\n this.funcMask = 0xff;\n this.opStencilFail = StencilState.KEEP;\n this.opDepthFail = StencilState.KEEP;\n this.opStencilDepthPass = StencilState.REPLACE;\n }\n get stencilFunc() {\n return this.func;\n }\n set stencilFunc(value) {\n this.func = value;\n }\n get stencilFuncRef() {\n return this.funcRef;\n }\n set stencilFuncRef(value) {\n this.funcRef = value;\n }\n get stencilFuncMask() {\n return this.funcMask;\n }\n set stencilFuncMask(value) {\n this.funcMask = value;\n }\n get stencilOpStencilFail() {\n return this.opStencilFail;\n }\n set stencilOpStencilFail(value) {\n this.opStencilFail = value;\n }\n get stencilOpDepthFail() {\n return this.opDepthFail;\n }\n set stencilOpDepthFail(value) {\n this.opDepthFail = value;\n }\n get stencilOpStencilDepthPass() {\n return this.opStencilDepthPass;\n }\n set stencilOpStencilDepthPass(value) {\n this.opStencilDepthPass = value;\n }\n get stencilMask() {\n return this.mask;\n }\n set stencilMask(value) {\n this.mask = value;\n }\n get stencilTest() {\n return this.enabled;\n }\n set stencilTest(value) {\n this.enabled = value;\n }\n}\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */\nStencilState.ALWAYS = 519;\n/** Passed to stencilOperation to specify that stencil value must be kept */\nStencilState.KEEP = 7680;\n/** Passed to stencilOperation to specify that stencil value must be replaced */\nStencilState.REPLACE = 7681;\n//# sourceMappingURL=stencilState.js.map","/**\n * @internal\n **/\nexport class StencilStateComposer {\n get isDirty() {\n return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;\n }\n get func() {\n return this._func;\n }\n set func(value) {\n if (this._func === value) {\n return;\n }\n this._func = value;\n this._isStencilFuncDirty = true;\n }\n get funcRef() {\n return this._funcRef;\n }\n set funcRef(value) {\n if (this._funcRef === value) {\n return;\n }\n this._funcRef = value;\n this._isStencilFuncDirty = true;\n }\n get funcMask() {\n return this._funcMask;\n }\n set funcMask(value) {\n if (this._funcMask === value) {\n return;\n }\n this._funcMask = value;\n this._isStencilFuncDirty = true;\n }\n get opStencilFail() {\n return this._opStencilFail;\n }\n set opStencilFail(value) {\n if (this._opStencilFail === value) {\n return;\n }\n this._opStencilFail = value;\n this._isStencilOpDirty = true;\n }\n get opDepthFail() {\n return this._opDepthFail;\n }\n set opDepthFail(value) {\n if (this._opDepthFail === value) {\n return;\n }\n this._opDepthFail = value;\n this._isStencilOpDirty = true;\n }\n get opStencilDepthPass() {\n return this._opStencilDepthPass;\n }\n set opStencilDepthPass(value) {\n if (this._opStencilDepthPass === value) {\n return;\n }\n this._opStencilDepthPass = value;\n this._isStencilOpDirty = true;\n }\n get mask() {\n return this._mask;\n }\n set mask(value) {\n if (this._mask === value) {\n return;\n }\n this._mask = value;\n this._isStencilMaskDirty = true;\n }\n get enabled() {\n return this._enabled;\n }\n set enabled(value) {\n if (this._enabled === value) {\n return;\n }\n this._enabled = value;\n this._isStencilTestDirty = true;\n }\n constructor(reset = true) {\n this._isStencilTestDirty = false;\n this._isStencilMaskDirty = false;\n this._isStencilFuncDirty = false;\n this._isStencilOpDirty = false;\n this.useStencilGlobalOnly = false;\n if (reset) {\n this.reset();\n }\n }\n reset() {\n var _a;\n this.stencilMaterial = undefined;\n (_a = this.stencilGlobal) === null || _a === void 0 ? void 0 : _a.reset();\n this._isStencilTestDirty = true;\n this._isStencilMaskDirty = true;\n this._isStencilFuncDirty = true;\n this._isStencilOpDirty = true;\n }\n apply(gl) {\n var _a;\n if (!gl) {\n return;\n }\n const stencilMaterialEnabled = !this.useStencilGlobalOnly && !!((_a = this.stencilMaterial) === null || _a === void 0 ? void 0 : _a.enabled);\n this.enabled = stencilMaterialEnabled ? this.stencilMaterial.enabled : this.stencilGlobal.enabled;\n this.func = stencilMaterialEnabled ? this.stencilMaterial.func : this.stencilGlobal.func;\n this.funcRef = stencilMaterialEnabled ? this.stencilMaterial.funcRef : this.stencilGlobal.funcRef;\n this.funcMask = stencilMaterialEnabled ? this.stencilMaterial.funcMask : this.stencilGlobal.funcMask;\n this.opStencilFail = stencilMaterialEnabled ? this.stencilMaterial.opStencilFail : this.stencilGlobal.opStencilFail;\n this.opDepthFail = stencilMaterialEnabled ? this.stencilMaterial.opDepthFail : this.stencilGlobal.opDepthFail;\n this.opStencilDepthPass = stencilMaterialEnabled ? this.stencilMaterial.opStencilDepthPass : this.stencilGlobal.opStencilDepthPass;\n this.mask = stencilMaterialEnabled ? this.stencilMaterial.mask : this.stencilGlobal.mask;\n if (!this.isDirty) {\n return;\n }\n // Stencil test\n if (this._isStencilTestDirty) {\n if (this.enabled) {\n gl.enable(gl.STENCIL_TEST);\n }\n else {\n gl.disable(gl.STENCIL_TEST);\n }\n this._isStencilTestDirty = false;\n }\n // Stencil mask\n if (this._isStencilMaskDirty) {\n gl.stencilMask(this.mask);\n this._isStencilMaskDirty = false;\n }\n // Stencil func\n if (this._isStencilFuncDirty) {\n gl.stencilFunc(this.func, this.funcRef, this.funcMask);\n this._isStencilFuncDirty = false;\n }\n // Stencil op\n if (this._isStencilOpDirty) {\n gl.stencilOp(this.opStencilFail, this.opDepthFail, this.opStencilDepthPass);\n this._isStencilOpDirty = false;\n }\n }\n}\n//# sourceMappingURL=stencilStateComposer.js.map","/**\n * Base class of the scene acting as a container for the different elements composing a scene.\n * This class is dynamically extended by the different components of the scene increasing\n * flexibility and reducing coupling\n */\nexport class AbstractScene {\n constructor() {\n /**\n * Gets the list of root nodes (ie. nodes with no parent)\n */\n this.rootNodes = new Array();\n /** All of the cameras added to this scene\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras\n */\n this.cameras = new Array();\n /**\n * All of the lights added to this scene\n * @see https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction\n */\n this.lights = new Array();\n /**\n * All of the (abstract) meshes added to this scene\n */\n this.meshes = new Array();\n /**\n * The list of skeletons added to the scene\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons\n */\n this.skeletons = new Array();\n /**\n * All of the particle systems added to this scene\n * @see https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro\n */\n this.particleSystems = new Array();\n /**\n * Gets a list of Animations associated with the scene\n */\n this.animations = [];\n /**\n * All of the animation groups added to this scene\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/groupAnimations\n */\n this.animationGroups = new Array();\n /**\n * All of the multi-materials added to this scene\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/multiMaterials\n */\n this.multiMaterials = new Array();\n /**\n * All of the materials added to this scene\n * In the context of a Scene, it is not supposed to be modified manually.\n * Any addition or removal should be done using the addMaterial and removeMaterial Scene methods.\n * Note also that the order of the Material within the array is not significant and might change.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction\n */\n this.materials = new Array();\n /**\n * The list of morph target managers added to the scene\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph\n */\n this.morphTargetManagers = new Array();\n /**\n * The list of geometries used in the scene.\n */\n this.geometries = new Array();\n /**\n * All of the transform nodes added to this scene\n * In the context of a Scene, it is not supposed to be modified manually.\n * Any addition or removal should be done using the addTransformNode and removeTransformNode Scene methods.\n * Note also that the order of the TransformNode within the array is not significant and might change.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/parent_pivot/transform_node\n */\n this.transformNodes = new Array();\n /**\n * ActionManagers available on the scene.\n * @deprecated\n */\n this.actionManagers = new Array();\n /**\n * Textures to keep.\n */\n this.textures = new Array();\n /** @internal */\n this._environmentTexture = null;\n /**\n * The list of postprocesses added to the scene\n */\n this.postProcesses = new Array();\n }\n /**\n * Adds a parser in the list of available ones\n * @param name Defines the name of the parser\n * @param parser Defines the parser to add\n */\n static AddParser(name, parser) {\n this._BabylonFileParsers[name] = parser;\n }\n /**\n * Gets a general parser from the list of available ones\n * @param name Defines the name of the parser\n * @returns the requested parser or null\n */\n static GetParser(name) {\n if (this._BabylonFileParsers[name]) {\n return this._BabylonFileParsers[name];\n }\n return null;\n }\n /**\n * Adds n individual parser in the list of available ones\n * @param name Defines the name of the parser\n * @param parser Defines the parser to add\n */\n static AddIndividualParser(name, parser) {\n this._IndividualBabylonFileParsers[name] = parser;\n }\n /**\n * Gets an individual parser from the list of available ones\n * @param name Defines the name of the parser\n * @returns the requested parser or null\n */\n static GetIndividualParser(name) {\n if (this._IndividualBabylonFileParsers[name]) {\n return this._IndividualBabylonFileParsers[name];\n }\n return null;\n }\n /**\n * Parser json data and populate both a scene and its associated container object\n * @param jsonData Defines the data to parse\n * @param scene Defines the scene to parse the data for\n * @param container Defines the container attached to the parsing sequence\n * @param rootUrl Defines the root url of the data\n */\n static Parse(jsonData, scene, container, rootUrl) {\n for (const parserName in this._BabylonFileParsers) {\n if (Object.prototype.hasOwnProperty.call(this._BabylonFileParsers, parserName)) {\n this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);\n }\n }\n }\n /**\n * Texture used in all pbr material as the reflection texture.\n * As in the majority of the scene they are the same (exception for multi room and so on),\n * this is easier to reference from here than from all the materials.\n */\n get environmentTexture() {\n return this._environmentTexture;\n }\n set environmentTexture(value) {\n this._environmentTexture = value;\n }\n /**\n * @returns all meshes, lights, cameras, transformNodes and bones\n */\n getNodes() {\n let nodes = new Array();\n nodes = nodes.concat(this.meshes);\n nodes = nodes.concat(this.lights);\n nodes = nodes.concat(this.cameras);\n nodes = nodes.concat(this.transformNodes); // dummies\n this.skeletons.forEach((skeleton) => (nodes = nodes.concat(skeleton.bones)));\n return nodes;\n }\n}\n/**\n * Stores the list of available parsers in the application.\n */\nAbstractScene._BabylonFileParsers = {};\n/**\n * Stores the list of available individual parsers in the application.\n */\nAbstractScene._IndividualBabylonFileParsers = {};\n//# sourceMappingURL=abstractScene.js.map","import { __decorate } from \"./tslib.es6.js\";\nimport { Matrix, Vector3 } from \"./Maths/math.vector.js\";\nimport { SerializationHelper, serialize } from \"./Misc/decorators.js\";\nimport { Observable } from \"./Misc/observable.js\";\nimport { EngineStore } from \"./Engines/engineStore.js\";\nimport { _WarnImport } from \"./Misc/devTools.js\";\n/** @internal */\nclass _InternalNodeDataInfo {\n constructor() {\n this._doNotSerialize = false;\n this._isDisposed = false;\n this._sceneRootNodesIndex = -1;\n this._isEnabled = true;\n this._isParentEnabled = true;\n this._isReady = true;\n this._onEnabledStateChangedObservable = new Observable();\n this._onClonedObservable = new Observable();\n }\n}\n/**\n * Node is the basic class for all scene objects (Mesh, Light, Camera.)\n */\nexport class Node {\n /**\n * Add a new node constructor\n * @param type defines the type name of the node to construct\n * @param constructorFunc defines the constructor function\n */\n static AddNodeConstructor(type, constructorFunc) {\n this._NodeConstructors[type] = constructorFunc;\n }\n /**\n * Returns a node constructor based on type name\n * @param type defines the type name\n * @param name defines the new node name\n * @param scene defines the hosting scene\n * @param options defines optional options to transmit to constructors\n * @returns the new constructor or null\n */\n static Construct(type, name, scene, options) {\n const constructorFunc = this._NodeConstructors[type];\n if (!constructorFunc) {\n return null;\n }\n return constructorFunc(name, scene, options);\n }\n /**\n * Gets or sets the accessibility tag to describe the node for accessibility purpose.\n */\n set accessibilityTag(value) {\n this._accessibilityTag = value;\n this.onAccessibilityTagChangedObservable.notifyObservers(value);\n }\n get accessibilityTag() {\n return this._accessibilityTag;\n }\n /**\n * Gets or sets a boolean used to define if the node must be serialized\n */\n get doNotSerialize() {\n if (this._nodeDataStorage._doNotSerialize) {\n return true;\n }\n if (this._parentNode) {\n return this._parentNode.doNotSerialize;\n }\n return false;\n }\n set doNotSerialize(value) {\n this._nodeDataStorage._doNotSerialize = value;\n }\n /**\n * Gets a boolean indicating if the node has been disposed\n * @returns true if the node was disposed\n */\n isDisposed() {\n return this._nodeDataStorage._isDisposed;\n }\n /**\n * Gets or sets the parent of the node (without keeping the current position in the scene)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/parent_pivot/parent\n */\n set parent(parent) {\n if (this._parentNode === parent) {\n return;\n }\n const previousParentNode = this._parentNode;\n // Remove self from list of children of parent\n if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {\n const index = this._parentNode._children.indexOf(this);\n if (index !== -1) {\n this._parentNode._children.splice(index, 1);\n }\n if (!parent && !this._nodeDataStorage._isDisposed) {\n this._addToSceneRootNodes();\n }\n }\n // Store new parent\n this._parentNode = parent;\n // Add as child to new parent\n if (this._parentNode) {\n if (this._parentNode._children === undefined || this._parentNode._children === null) {\n this._parentNode._children = new Array();\n }\n this._parentNode._children.push(this);\n if (!previousParentNode) {\n this._removeFromSceneRootNodes();\n }\n }\n // Enabled state\n this._syncParentEnabledState();\n }\n get parent() {\n return this._parentNode;\n }\n /**\n * @internal\n */\n _serializeAsParent(serializationObject) {\n serializationObject.parentId = this.uniqueId;\n }\n /** @internal */\n _addToSceneRootNodes() {\n if (this._nodeDataStorage._sceneRootNodesIndex === -1) {\n this._nodeDataStorage._sceneRootNodesIndex = this._scene.rootNodes.length;\n this._scene.rootNodes.push(this);\n }\n }\n /** @internal */\n _removeFromSceneRootNodes() {\n if (this._nodeDataStorage._sceneRootNodesIndex !== -1) {\n const rootNodes = this._scene.rootNodes;\n const lastIdx = rootNodes.length - 1;\n rootNodes[this._nodeDataStorage._sceneRootNodesIndex] = rootNodes[lastIdx];\n rootNodes[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex = this._nodeDataStorage._sceneRootNodesIndex;\n this._scene.rootNodes.pop();\n this._nodeDataStorage._sceneRootNodesIndex = -1;\n }\n }\n /**\n * Gets or sets the animation properties override\n */\n get animationPropertiesOverride() {\n if (!this._animationPropertiesOverride) {\n return this._scene.animationPropertiesOverride;\n }\n return this._animationPropertiesOverride;\n }\n set animationPropertiesOverride(value) {\n this._animationPropertiesOverride = value;\n }\n /**\n * Gets a string identifying the name of the class\n * @returns \"Node\" string\n */\n getClassName() {\n return \"Node\";\n }\n /**\n * Sets a callback that will be raised when the node will be disposed\n */\n set onDispose(callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n }\n /**\n * An event triggered when the enabled state of the node changes\n */\n get onEnabledStateChangedObservable() {\n return this._nodeDataStorage._onEnabledStateChangedObservable;\n }\n /**\n * An event triggered when the node is cloned\n */\n get onClonedObservable() {\n return this._nodeDataStorage._onClonedObservable;\n }\n /**\n * Creates a new Node\n * @param name the name and id to be given to this node\n * @param scene the scene this node will be added to\n */\n constructor(name, scene = null) {\n this._isDirty = false;\n this._nodeDataStorage = new _InternalNodeDataInfo();\n /**\n * Gets or sets a string used to store user defined state for the node\n */\n this.state = \"\";\n /**\n * Gets or sets an object used to store user defined information for the node\n */\n this.metadata = null;\n /**\n * For internal use only. Please do not use.\n */\n this.reservedDataStore = null;\n this._accessibilityTag = null;\n this.onAccessibilityTagChangedObservable = new Observable();\n /** @internal */\n this._parentContainer = null;\n /**\n * Gets a list of Animations associated with the node\n */\n this.animations = new Array();\n this._ranges = {};\n /**\n * Callback raised when the node is ready to be used\n */\n this.onReady = null;\n /** @internal */\n this._currentRenderId = -1;\n this._parentUpdateId = -1;\n /** @internal */\n this._childUpdateId = -1;\n /** @internal */\n this._waitingParentId = null;\n /** @internal */\n this._waitingParentInstanceIndex = null;\n /** @internal */\n this._waitingParsedUniqueId = null;\n /** @internal */\n this._cache = {};\n this._parentNode = null;\n /** @internal */\n this._children = null;\n /** @internal */\n this._worldMatrix = Matrix.Identity();\n /** @internal */\n this._worldMatrixDeterminant = 0;\n /** @internal */\n this._worldMatrixDeterminantIsDirty = true;\n this._animationPropertiesOverride = null;\n /** @internal */\n this._isNode = true;\n /**\n * An event triggered when the mesh is disposed\n */\n this.onDisposeObservable = new Observable();\n this._onDisposeObserver = null;\n // Behaviors\n this._behaviors = new Array();\n this.name = name;\n this.id = name;\n this._scene = (scene || EngineStore.LastCreatedScene);\n this.uniqueId = this._scene.getUniqueId();\n this._initCache();\n }\n /**\n * Gets the scene of the node\n * @returns a scene\n */\n getScene() {\n return this._scene;\n }\n /**\n * Gets the engine of the node\n * @returns a Engine\n */\n getEngine() {\n return this._scene.getEngine();\n }\n /**\n * Attach a behavior to the node\n * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors\n * @param behavior defines the behavior to attach\n * @param attachImmediately defines that the behavior must be attached even if the scene is still loading\n * @returns the current Node\n */\n addBehavior(behavior, attachImmediately = false) {\n const index = this._behaviors.indexOf(behavior);\n if (index !== -1) {\n return this;\n }\n behavior.init();\n if (this._scene.isLoading && !attachImmediately) {\n // We defer the attach when the scene will be loaded\n this._scene.onDataLoadedObservable.addOnce(() => {\n behavior.attach(this);\n });\n }\n else {\n behavior.attach(this);\n }\n this._behaviors.push(behavior);\n return this;\n }\n /**\n * Remove an attached behavior\n * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors\n * @param behavior defines the behavior to attach\n * @returns the current Node\n */\n removeBehavior(behavior) {\n const index = this._behaviors.indexOf(behavior);\n if (index === -1) {\n return this;\n }\n this._behaviors[index].detach();\n this._behaviors.splice(index, 1);\n return this;\n }\n /**\n * Gets the list of attached behaviors\n * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors\n */\n get behaviors() {\n return this._behaviors;\n }\n /**\n * Gets an attached behavior by name\n * @param name defines the name of the behavior to look for\n * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors\n * @returns null if behavior was not found else the requested behavior\n */\n getBehaviorByName(name) {\n for (const behavior of this._behaviors) {\n if (behavior.name === name) {\n return behavior;\n }\n }\n return null;\n }\n /**\n * Returns the latest update of the World matrix\n * @returns a Matrix\n */\n getWorldMatrix() {\n if (this._currentRenderId !== this._scene.getRenderId()) {\n this.computeWorldMatrix();\n }\n return this._worldMatrix;\n }\n /** @internal */\n _getWorldMatrixDeterminant() {\n if (this._worldMatrixDeterminantIsDirty) {\n this._worldMatrixDeterminantIsDirty = false;\n this._worldMatrixDeterminant = this._worldMatrix.determinant();\n }\n return this._worldMatrixDeterminant;\n }\n /**\n * Returns directly the latest state of the mesh World matrix.\n * A Matrix is returned.\n */\n get worldMatrixFromCache() {\n return this._worldMatrix;\n }\n // override it in derived class if you add new variables to the cache\n // and call the parent class method\n /** @internal */\n _initCache() {\n this._cache = {};\n this._cache.parent = undefined;\n }\n /**\n * @internal\n */\n updateCache(force) {\n if (!force && this.isSynchronized()) {\n return;\n }\n this._cache.parent = this.parent;\n this._updateCache();\n }\n /**\n * @internal\n */\n _getActionManagerForTrigger(trigger, _initialCall = true) {\n if (!this.parent) {\n return null;\n }\n return this.parent._getActionManagerForTrigger(trigger, false);\n }\n // override it in derived class if you add new variables to the cache\n // and call the parent class method if !ignoreParentClass\n /**\n * @internal\n */\n _updateCache(_ignoreParentClass) { }\n // override it in derived class if you add new variables to the cache\n /** @internal */\n _isSynchronized() {\n return true;\n }\n /** @internal */\n _markSyncedWithParent() {\n if (this._parentNode) {\n this._parentUpdateId = this._parentNode._childUpdateId;\n }\n }\n /** @internal */\n isSynchronizedWithParent() {\n if (!this._parentNode) {\n return true;\n }\n if (this._parentNode._isDirty || this._parentUpdateId !== this._parentNode._childUpdateId) {\n return false;\n }\n return this._parentNode.isSynchronized();\n }\n /** @internal */\n isSynchronized() {\n if (this._cache.parent !== this._parentNode) {\n this._cache.parent = this._parentNode;\n return false;\n }\n if (this._parentNode && !this.isSynchronizedWithParent()) {\n return false;\n }\n return this._isSynchronized();\n }\n /**\n * Is this node ready to be used/rendered\n * @param _completeCheck defines if a complete check (including materials and lights) has to be done (false by default)\n * @returns true if the node is ready\n */\n isReady(_completeCheck = false) {\n return this._nodeDataStorage._isReady;\n }\n /**\n * Flag the node as dirty (Forcing it to update everything)\n * @param _property helps children apply precise \"dirtyfication\"\n * @returns this node\n */\n markAsDirty(_property) {\n this._currentRenderId = Number.MAX_VALUE;\n this._isDirty = true;\n return this;\n }\n /**\n * Is this node enabled?\n * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true\n * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors\n * @returns whether this node (and its parent) is enabled\n */\n isEnabled(checkAncestors = true) {\n if (checkAncestors === false) {\n return this._nodeDataStorage._isEnabled;\n }\n if (!this._nodeDataStorage._isEnabled) {\n return false;\n }\n return this._nodeDataStorage._isParentEnabled;\n }\n /** @internal */\n _syncParentEnabledState() {\n this._nodeDataStorage._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;\n if (this._children) {\n this._children.forEach((c) => {\n c._syncParentEnabledState(); // Force children to update accordingly\n });\n }\n }\n /**\n * Set the enabled state of this node\n * @param value defines the new enabled state\n */\n setEnabled(value) {\n if (this._nodeDataStorage._isEnabled === value) {\n return;\n }\n this._nodeDataStorage._isEnabled = value;\n this._syncParentEnabledState();\n this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(value);\n }\n /**\n * Is this node a descendant of the given node?\n * The function will iterate up the hierarchy until the ancestor was found or no more parents defined\n * @param ancestor defines the parent node to inspect\n * @returns a boolean indicating if this node is a descendant of the given node\n */\n isDescendantOf(ancestor) {\n if (this.parent) {\n if (this.parent === ancestor) {\n return true;\n }\n return this.parent.isDescendantOf(ancestor);\n }\n return false;\n }\n /**\n * @internal\n */\n _getDescendants(results, directDescendantsOnly = false, predicate) {\n if (!this._children) {\n return;\n }\n for (let index = 0; index < this._children.length; index++) {\n const item = this._children[index];\n if (!predicate || predicate(item)) {\n results.push(item);\n }\n if (!directDescendantsOnly) {\n item._getDescendants(results, false, predicate);\n }\n }\n }\n /**\n * Will return all nodes that have this node as ascendant\n * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered\n * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored\n * @returns all children nodes of all types\n */\n getDescendants(directDescendantsOnly, predicate) {\n const results = new Array();\n this._getDescendants(results, directDescendantsOnly, predicate);\n return results;\n }\n /**\n * Get all child-meshes of this node\n * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered (Default: false)\n * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored\n * @returns an array of AbstractMesh\n */\n getChildMeshes(directDescendantsOnly, predicate) {\n const results = [];\n this._getDescendants(results, directDescendantsOnly, (node) => {\n return (!predicate || predicate(node)) && node.cullingStrategy !== undefined;\n });\n return results;\n }\n /**\n * Get all direct children of this node\n * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored\n * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered (Default: true)\n * @returns an array of Node\n */\n getChildren(predicate, directDescendantsOnly = true) {\n return this.getDescendants(directDescendantsOnly, predicate);\n }\n /**\n * @internal\n */\n _setReady(state) {\n if (state === this._nodeDataStorage._isReady) {\n return;\n }\n if (!state) {\n this._nodeDataStorage._isReady = false;\n return;\n }\n if (this.onReady) {\n this.onReady(this);\n }\n this._nodeDataStorage._isReady = true;\n }\n /**\n * Get an animation by name\n * @param name defines the name of the animation to look for\n * @returns null if not found else the requested animation\n */\n getAnimationByName(name) {\n for (let i = 0; i < this.animations.length; i++) {\n const animation = this.animations[i];\n if (animation.name === name) {\n return animation;\n }\n }\n return null;\n }\n /**\n * Creates an animation range for this node\n * @param name defines the name of the range\n * @param from defines the starting key\n * @param to defines the end key\n */\n createAnimationRange(name, from, to) {\n // check name not already in use\n if (!this._ranges[name]) {\n this._ranges[name] = Node._AnimationRangeFactory(name, from, to);\n for (let i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {\n if (this.animations[i]) {\n this.animations[i].createRange(name, from, to);\n }\n }\n }\n }\n /**\n * Delete a specific animation range\n * @param name defines the name of the range to delete\n * @param deleteFrames defines if animation frames from the range must be deleted as well\n */\n deleteAnimationRange(name, deleteFrames = true) {\n for (let i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {\n if (this.animations[i]) {\n this.animations[i].deleteRange(name, deleteFrames);\n }\n }\n this._ranges[name] = null; // said much faster than 'delete this._range[name]'\n }\n /**\n * Get an animation range by name\n * @param name defines the name of the animation range to look for\n * @returns null if not found else the requested animation range\n */\n getAnimationRange(name) {\n return this._ranges[name] || null;\n }\n /**\n * Clone the current node\n * @param name Name of the new clone\n * @param newParent New parent for the clone\n * @param doNotCloneChildren Do not clone children hierarchy\n * @returns the new transform node\n */\n clone(name, newParent, doNotCloneChildren) {\n const result = SerializationHelper.Clone(() => new Node(name, this.getScene()), this);\n if (newParent) {\n result.parent = newParent;\n }\n if (!doNotCloneChildren) {\n // Children\n const directDescendants = this.getDescendants(true);\n for (let index = 0; index < directDescendants.length; index++) {\n const child = directDescendants[index];\n child.clone(name + \".\" + child.name, result);\n }\n }\n return result;\n }\n /**\n * Gets the list of all animation ranges defined on this node\n * @returns an array\n */\n getAnimationRanges() {\n const animationRanges = [];\n let name;\n for (name in this._ranges) {\n animationRanges.push(this._ranges[name]);\n }\n return animationRanges;\n }\n /**\n * Will start the animation sequence\n * @param name defines the range frames for animation sequence\n * @param loop defines if the animation should loop (false by default)\n * @param speedRatio defines the speed factor in which to run the animation (1 by default)\n * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)\n * @returns the object created for this animation. If range does not exist, it will return null\n */\n beginAnimation(name, loop, speedRatio, onAnimationEnd) {\n const range = this.getAnimationRange(name);\n if (!range) {\n return null;\n }\n return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);\n }\n /**\n * Serialize animation ranges into a JSON compatible object\n * @returns serialization object\n */\n serializeAnimationRanges() {\n const serializationRanges = [];\n for (const name in this._ranges) {\n const localRange = this._ranges[name];\n if (!localRange) {\n continue;\n }\n const range = {};\n range.name = name;\n range.from = localRange.from;\n range.to = localRange.to;\n serializationRanges.push(range);\n }\n return serializationRanges;\n }\n /**\n * Computes the world matrix of the node\n * @param _force defines if the cache version should be invalidated forcing the world matrix to be created from scratch\n * @returns the world matrix\n */\n computeWorldMatrix(_force) {\n if (!this._worldMatrix) {\n this._worldMatrix = Matrix.Identity();\n }\n return this._worldMatrix;\n }\n /**\n * Releases resources associated with this node.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n dispose(doNotRecurse, disposeMaterialAndTextures = false) {\n this._nodeDataStorage._isDisposed = true;\n if (!doNotRecurse) {\n const nodes = this.getDescendants(true);\n for (const node of nodes) {\n node.dispose(doNotRecurse, disposeMaterialAndTextures);\n }\n }\n if (!this.parent) {\n this._removeFromSceneRootNodes();\n }\n else {\n this.parent = null;\n }\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n this.onEnabledStateChangedObservable.clear();\n this.onClonedObservable.clear();\n // Behaviors\n for (const behavior of this._behaviors) {\n behavior.detach();\n }\n this._behaviors.length = 0;\n this.metadata = null;\n }\n /**\n * Parse animation range data from a serialization object and store them into a given node\n * @param node defines where to store the animation ranges\n * @param parsedNode defines the serialization object to read data from\n * @param _scene defines the hosting scene\n */\n static ParseAnimationRanges(node, parsedNode, _scene) {\n if (parsedNode.ranges) {\n for (let index = 0; index < parsedNode.ranges.length; index++) {\n const data = parsedNode.ranges[index];\n node.createAnimationRange(data.name, data.from, data.to);\n }\n }\n }\n /**\n * Return the minimum and maximum world vectors of the entire hierarchy under current node\n * @param includeDescendants Include bounding info from descendants as well (true by default)\n * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors\n * @returns the new bounding vectors\n */\n getHierarchyBoundingVectors(includeDescendants = true, predicate = null) {\n // Ensures that all world matrix will be recomputed.\n this.getScene().incrementRenderId();\n this.computeWorldMatrix(true);\n let min;\n let max;\n const thisAbstractMesh = this;\n if (thisAbstractMesh.getBoundingInfo && thisAbstractMesh.subMeshes) {\n // If this is an abstract mesh get its bounding info\n const boundingInfo = thisAbstractMesh.getBoundingInfo();\n min = boundingInfo.boundingBox.minimumWorld.clone();\n max = boundingInfo.boundingBox.maximumWorld.clone();\n }\n else {\n min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);\n }\n if (includeDescendants) {\n const descendants = this.getDescendants(false);\n for (const descendant of descendants) {\n const childMesh = descendant;\n childMesh.computeWorldMatrix(true);\n // Filters meshes based on custom predicate function.\n if (predicate && !predicate(childMesh)) {\n continue;\n }\n //make sure we have the needed params to get mix and max\n if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {\n continue;\n }\n const childBoundingInfo = childMesh.getBoundingInfo();\n const boundingBox = childBoundingInfo.boundingBox;\n const minBox = boundingBox.minimumWorld;\n const maxBox = boundingBox.maximumWorld;\n Vector3.CheckExtends(minBox, min, max);\n Vector3.CheckExtends(maxBox, min, max);\n }\n }\n return {\n min: min,\n max: max,\n };\n }\n}\n/**\n * @internal\n */\nNode._AnimationRangeFactory = (_name, _from, _to) => {\n throw _WarnImport(\"AnimationRange\");\n};\nNode._NodeConstructors = {};\n__decorate([\n serialize()\n], Node.prototype, \"name\", void 0);\n__decorate([\n serialize()\n], Node.prototype, \"id\", void 0);\n__decorate([\n serialize()\n], Node.prototype, \"uniqueId\", void 0);\n__decorate([\n serialize()\n], Node.prototype, \"state\", void 0);\n__decorate([\n serialize()\n], Node.prototype, \"metadata\", void 0);\n//# sourceMappingURL=node.js.map","/**\n * Groups all the scene component constants in one place to ease maintenance.\n * @internal\n */\nexport class SceneComponentConstants {\n}\nSceneComponentConstants.NAME_EFFECTLAYER = \"EffectLayer\";\nSceneComponentConstants.NAME_LAYER = \"Layer\";\nSceneComponentConstants.NAME_LENSFLARESYSTEM = \"LensFlareSystem\";\nSceneComponentConstants.NAME_BOUNDINGBOXRENDERER = \"BoundingBoxRenderer\";\nSceneComponentConstants.NAME_PARTICLESYSTEM = \"ParticleSystem\";\nSceneComponentConstants.NAME_GAMEPAD = \"Gamepad\";\nSceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = \"SimplificationQueue\";\nSceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = \"GeometryBufferRenderer\";\nSceneComponentConstants.NAME_PREPASSRENDERER = \"PrePassRenderer\";\nSceneComponentConstants.NAME_DEPTHRENDERER = \"DepthRenderer\";\nSceneComponentConstants.NAME_DEPTHPEELINGRENDERER = \"DepthPeelingRenderer\";\nSceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = \"PostProcessRenderPipelineManager\";\nSceneComponentConstants.NAME_SPRITE = \"Sprite\";\nSceneComponentConstants.NAME_SUBSURFACE = \"SubSurface\";\nSceneComponentConstants.NAME_OUTLINERENDERER = \"Outline\";\nSceneComponentConstants.NAME_PROCEDURALTEXTURE = \"ProceduralTexture\";\nSceneComponentConstants.NAME_SHADOWGENERATOR = \"ShadowGenerator\";\nSceneComponentConstants.NAME_OCTREE = \"Octree\";\nSceneComponentConstants.NAME_PHYSICSENGINE = \"PhysicsEngine\";\nSceneComponentConstants.NAME_AUDIO = \"Audio\";\nSceneComponentConstants.NAME_FLUIDRENDERER = \"FluidRenderer\";\nSceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;\nSceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;\nSceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;\nSceneComponentConstants.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER = 0;\nSceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;\nSceneComponentConstants.STEP_BEFORECAMERADRAW_PREPASS = 0;\nSceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 1;\nSceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 2;\nSceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_PREPASS = 0;\nSceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_LAYER = 1;\nSceneComponentConstants.STEP_BEFORERENDERINGMESH_PREPASS = 0;\nSceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 1;\nSceneComponentConstants.STEP_AFTERRENDERINGMESH_PREPASS = 0;\nSceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 1;\nSceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;\nSceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;\nSceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;\nSceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;\nSceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;\nSceneComponentConstants.STEP_BEFORECLEAR_PREPASS = 1;\nSceneComponentConstants.STEP_BEFORERENDERTARGETCLEAR_PREPASS = 0;\nSceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_PREPASS = 0;\nSceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_LAYER = 1;\nSceneComponentConstants.STEP_AFTERCAMERADRAW_PREPASS = 0;\nSceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 1;\nSceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 2;\nSceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;\nSceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;\nSceneComponentConstants.STEP_AFTERCAMERADRAW_FLUIDRENDERER = 5;\nSceneComponentConstants.STEP_AFTERCAMERAPOSTPROCESS_LAYER = 0;\nSceneComponentConstants.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER = 0;\nSceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;\nSceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 0;\nSceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;\nSceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 2;\nSceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;\nSceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;\nSceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER = 1;\nSceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;\nSceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;\nSceneComponentConstants.STEP_POINTERUP_SPRITE = 0;\n/**\n * Representation of a stage in the scene (Basically a list of ordered steps)\n * @internal\n */\nexport class Stage extends Array {\n /**\n * Hide ctor from the rest of the world.\n * @param items The items to add.\n */\n constructor(items) {\n super(...items);\n }\n /**\n * Creates a new Stage.\n * @returns A new instance of a Stage\n */\n static Create() {\n return Object.create(Stage.prototype);\n }\n /**\n * Registers a step in an ordered way in the targeted stage.\n * @param index Defines the position to register the step in\n * @param component Defines the component attached to the step\n * @param action Defines the action to launch during the step\n */\n registerStep(index, component, action) {\n let i = 0;\n let maxIndex = Number.MAX_VALUE;\n for (; i < this.length; i++) {\n const step = this[i];\n maxIndex = step.index;\n if (index < maxIndex) {\n break;\n }\n }\n this.splice(i, 0, { index, component, action: action.bind(component) });\n }\n /**\n * Clears all the steps from the stage.\n */\n clear() {\n this.length = 0;\n }\n}\n//# sourceMappingURL=sceneComponent.js.map","\n/******************************************************************************\nCopyright (c) Microsoft Corporation.\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n// the startup function\n__webpack_require__.x = function() {\n\t// Load entry module and return exports\n\t// This entry module depends on other loaded chunks and execution need to be delayed\n\tvar __webpack_exports__ = __webpack_require__.O(undefined, [315,568,770,942], function() { return __webpack_require__(4201); })\n\t__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n\treturn __webpack_exports__;\n};\n\n","var deferred = [];\n__webpack_require__.O = function(result, chunkIds, fn, priority) {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar chunkIds = deferred[i][0];\n\t\tvar fn = deferred[i][1];\n\t\tvar priority = deferred[i][2];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every(function(key) { return __webpack_require__.O[key](chunkIds[j]); })) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","// define getter functions for harmony exports\n__webpack_require__.d = function(exports, definition) {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = function(chunkId) {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce(function(promises, key) {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks and sibling chunks for the entrypoint\n__webpack_require__.u = function(chunkId) {\n\t// return url for filenames based on template\n\treturn \"\" + {\"315\":\"c2b82a6e\",\"568\":\"87a06baf\",\"770\":\"088d5a4e\",\"942\":\"256b551e\"}[chunkId] + \"-\" + {\"315\":\"1e3631aca5d8280099d6\",\"568\":\"5d3ac30d48950f0f9b7a\",\"770\":\"4f2cb64570bdf3425971\",\"942\":\"1832dd584c826cd29ac8\"}[chunkId] + \".js\";\n};","// This function allow to reference all chunks\n__webpack_require__.miniCssF = function(chunkId) {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }","__webpack_require__.p = \"/www.codecave.pro-new/\";","// no baseURI\n\n// object to store loaded chunks\n// \"1\" means \"already loaded\"\nvar installedChunks = {\n\t475: 1\n};\n\n// importScripts chunk loading\nvar installChunk = function(data) {\n\tvar chunkIds = data[0];\n\tvar moreModules = data[1];\n\tvar runtime = data[2];\n\tfor(var moduleId in moreModules) {\n\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t}\n\t}\n\tif(runtime) runtime(__webpack_require__);\n\twhile(chunkIds.length)\n\t\tinstalledChunks[chunkIds.pop()] = 1;\n\tparentChunkLoadingFunction(data);\n};\n__webpack_require__.f.i = function(chunkId, promises) {\n\t// \"1\" is the signal for \"already loaded\"\n\tif(!installedChunks[chunkId]) {\n\t\tif(true) { // all chunks have JS\n\t\t\timportScripts(__webpack_require__.p + __webpack_require__.u(chunkId));\n\t\t}\n\t}\n};\n\nvar chunkLoadingGlobal = self[\"webpackChunkcode_cave\"] = self[\"webpackChunkcode_cave\"] || [];\nvar parentChunkLoadingFunction = chunkLoadingGlobal.push.bind(chunkLoadingGlobal);\nchunkLoadingGlobal.push = installChunk;\n\n// no HMR\n\n// no HMR manifest","var next = __webpack_require__.x;\n__webpack_require__.x = function() {\n\treturn Promise.all([315,568,770,942].map(__webpack_require__.e, __webpack_require__)).then(next);\n};","// run startup\nvar __webpack_exports__ = __webpack_require__.x();\n"],"names":["Action","constructor","triggerOptions","condition","this","onBeforeExecuteObservable","parameter","trigger","_triggerParameter","_nextActiveAction","_condition","_prepare","getTriggerParameter","setTriggerParameter","value","_evaluateConditionForCurrentFrame","currentRenderId","_actionManager","getScene","getRenderId","_evaluationId","_currentResult","isValid","_executeCurrent","evt","notifyObservers","execute","skipToNextActiveAction","_child","then","action","_getProperty","propertyPath","_getEffectiveTarget","target","serialize","parent","_serialize","serializedAction","serializationObject","type","children","name","properties","serializedCondition","push","_SerializeValueAsString","toString","x","y","z","r","g","b","a","_GetTargetProperty","targetType","_isMesh","_isLight","_isCamera","_isMaterial","_isScene","Condition","actionManager","ValueCondition","IsEqual","_IsEqual","IsDifferent","_IsDifferent","IsGreater","_IsGreater","IsLesser","_IsLesser","operator","super","_target","_effectiveTarget","_property","check","equals","GetOperatorName","static","predicate","state","DoNothingAction","SetParentAction","_parent","invertParentWorldMatrix","getWorldMatrix","clone","invert","position","TransformCoordinates","func","stopAnimation","from","to","loop","beginAnimation","String","Warn","markAsDirty","enableChildrenConditions","index","length","combine","i","ActionManager","scene","LastCreatedScene","_scene","actionManagers","dispose","indexOf","actions","Triggers","splice","hasSpecificTriggers","triggers","hasSpecificTriggers2","triggerA","triggerB","hasSpecificTrigger","parameterPredicate","hasPointerTriggers","OnPickTrigger","OnPointerOutTrigger","hasPickTriggers","OnPickUpTrigger","registerAction","OnEveryFrameTrigger","_registeredActions","unregisterAction","processTrigger","OnKeyUpTrigger","OnKeyDownTrigger","sourceEvent","keyCode","toLowerCase","lowerCase","key","unicode","charCode","fromCharCode","split","root","Array","triggerObject","GetTriggerName","Node","DeepCopy","mesh","_meshId","id","parsedActions","object","parseParameter","floatValue","parseFloat","isNaN","effectiveTarget","values","FromArray","traverse","parsedAction","combineArray","detached","parameters","j","NothingTrigger","getMaterialByName","getNodeByName","getSoundByName","param","newAction","params","internalClassType","instantiate","nothing","triggerParams","getMeshByName","getMeshById","OnLeftPickTrigger","OnRightPickTrigger","OnCenterPickTrigger","OnPickDownTrigger","OnDoublePickTrigger","OnPickOutTrigger","OnLongPressTrigger","OnPointerOverTrigger","OnIntersectionEnterTrigger","OnIntersectionExitTrigger","sound","_sound","undefined","play","stop","AnimationKeyInterpolation","AnimationRange","Size","width","height","getClassName","getHashCode","hash","copyFrom","src","copyFromFloats","set","multiplyByFloats","w","h","other","surface","add","otherSize","subtract","start","end","amount","targetProperty","framePerSecond","totalFrame","loopMode","easingFunction","dataType","isFinite","ANIMATIONTYPE_FLOAT","ANIMATIONTYPE_QUATERNION","ANIMATIONTYPE_VECTOR3","ANIMATIONTYPE_VECTOR2","ANIMATIONTYPE_COLOR3","ANIMATIONTYPE_COLOR4","ANIMATIONTYPE_SIZE","animation","keys","frame","setKeys","setEasingFunction","property","animationType","ANIMATIONLOOPMODE_CONSTANT","onAnimationEnd","_PrepareAnimation","beginDirectAnimation","node","directDescendantsOnly","beginDirectHierarchyAnimation","animations","sourceAnimation","referenceFrame","range","cloneOriginal","clonedName","_keys","startIndex","firstKey","endIndex","lastKey","valueStore","referenceValue","referencePosition","Vector3","referenceQuaternion","Quaternion","referenceScaling","keyPosition","keyQuaternion","keyScaling","referenceFound","rangeValue","getRange","fromKeyFound","toKeyFound","_getKeyValue","currentKey","nextKey","animationState","repeatCount","_interpolate","normalize","conjugateInPlace","ANIMATIONTYPE_MATRIX","decompose","subtractInPlace","divideInPlace","multiplyToRef","ComposeToRef","subtractToRef","targetValue","host","frameRate","transition","duration","endFrame","runtimeAnimations","_runtimeAnimations","hasRunningRuntimeAnimations","runtimeAnimation","isStopped","enableBlending","_easingFunction","_events","blendingSpeed","_ranges","targetPropertyPath","ANIMATIONLOOPMODE_CYCLE","uniqueId","_UniqueIdGenerator","fullDetails","ret","Object","first","addEvent","event","sort","removeEvents","getEvents","createRange","deleteRange","deleteFrames","getKeys","getHighestFrame","nKeys","getEasingFunction","floatInterpolateFunction","startValue","endValue","gradient","Lerp","floatInterpolateFunctionWithTangents","outTangent","inTangent","Hermite","quaternionInterpolateFunction","Slerp","quaternionInterpolateFunctionWithTangents","vector3InterpolateFunction","vector3InterpolateFunctionWithTangents","vector2InterpolateFunction","vector2InterpolateFunctionWithTangents","sizeInterpolateFunction","color3InterpolateFunction","color3InterpolateFunctionWithTangents","color4InterpolateFunction","color4InterpolateFunctionWithTangents","evaluate","currentFrame","highLimitValue","keysLength","startKey","endKey","interpolation","STEP","useTangent","frameDelta","ease","ANIMATIONLOOPMODE_YOYO","ANIMATIONLOOPMODE_RELATIVE","offsetValue","quatValue","scale","addInPlace","vec3Value","vec2Value","color3Value","color4Value","AllowMatricesInterpolation","matrixInterpolateFunction","workValue","result","AllowMatrixDecomposeForInterpolation","DecomposeLerpToRef","DecomposeLerp","LerpToRef","join","slice","loopBehavior","animationKey","asArray","ranges","source","left","right","toFixed","parsedAnimation","data","_inTangent","Zero","_outTangent","keyData","destination","AppendSerializedAnimations","url","Promise","resolve","reject","request","addEventListener","readyState","status","JSON","parse","responseText","output","serializedAnimation","Parse","open","send","snippetId","snippet","jsonPayload","outputs","SnippetUrl","replace","CreateFromSnippetAsync","ParseFromSnippetAsync","N","_AnimationRangeFactory","stopOtherAnimations","onInterpolationDone","onInterpolationDoneObservable","_staticOffsetValueQuaternion","freeze","_staticOffsetValueVector3","_staticOffsetValueVector2","_staticOffsetValueSize","_staticOffsetValueColor3","Black","RuntimeAnimation","_currentFrame","weight","_weight","currentValue","_currentValue","targetPath","_targetPath","_currentActiveTarget","isAdditive","_host","_originalValue","_originalBlendValue","_offsetsCache","_highLimitsCache","_stopped","_blendingFactor","_directTarget","_ratioOffset","_previousDelay","_previousRatio","_targetIsArray","_animation","_activeTargets","_animationState","_getCorrectLoopMode","_minFrame","_maxFrame","_minValue","_maxValue","newKey","_preparePath","_getOriginalValues","events","forEach","e","_clone","_enableBlending","animationPropertiesOverride","targetIndex","reset","restoreOriginal","_setValue","isDone","setValue","originalValue","getRestPose","m","_UniversalLerp","_registerTargetForLateAnimationBinding","goToFrame","onlyOnce","_prepareForSpeedRatioChange","newSpeedRatio","newRatio","animate","delay","speedRatio","returnValue","ratio","Math","abs","sin","PI","keyOffset","fromValue","toValue","syncRoot","masterFrame","fromFrame","toFrame","_onLoop","Bone","_matrix","_compose","_localMatrix","_needToCompose","updateFlag","_markAsDirtyAndDecompose","skeleton","parentBone","localMatrix","restMatrix","bindMatrix","_a","_index","_scalingDeterminant","_needToDecompose","_linkedTransformNode","_waitingTransformNodeId","_skeleton","Identity","_restMatrix","_bindMatrix","_absoluteMatrix","_absoluteBindMatrix","_absoluteInverseBindMatrix","_finalMatrix","bones","setParent","_updateAbsoluteBindMatrices","getSkeleton","_parentNode","getParent","getChildren","getIndex","newParent","updateAbsoluteBindMatrices","getLocalMatrix","getBindMatrix","getBaseMatrix","getRestMatrix","setRestMatrix","matrix","setRestPose","getBindPose","setBindMatrix","updateMatrix","setBindPose","getFinalMatrix","returnToRest","localScaling","localRotation","localPosition","rotationQuaternion","scaling","getAbsoluteInverseBindMatrix","getInvertedAbsoluteTransform","getAbsoluteMatrix","getAbsoluteTransform","linkTransformNode","transformNode","_numBonesWithLinkedTransformNode","getTransformNode","_decompose","_localPosition","newPosition","_markAsDirtyAndCompose","rotation","getRotation","newRotation","setRotation","_localRotation","setRotationQuaternion","getScale","newScaling","setScale","_localScaling","updateLocalMatrix","updateChildren","invertToRef","determinant","_currentRenderId","_childUpdateId","_markAsDirty","_updatePosition","vec","space","LOCAL","tNode","translationMode","lm","addAtIndex","setTranslationFromFloats","wm","computeAbsoluteMatrices","tmat","_TmpMats","tvec","_TmpVecs","IdentityToRef","TransformCoordinatesToRef","translate","setPosition","setAbsolutePosition","WORLD","scaleChildren","locMat","scaleMat","ScalingToRef","child","cm","multiplyAtIndex","getScaleToRef","setYawPitchRoll","yaw","pitch","roll","quat","_TmpQuat","RotationYawPitchRollToRef","rotMatInv","_getAbsoluteInverseMatrixUnscaledToRef","rotMat","_rotateWithMatrix","rotate","axis","rmat","RotationAxisToRef","setAxisAngle","angle","FromQuaternionToRef","setRotationMatrix","FromRotationMatrixToRef","rotMat2","lmat","lx","ly","lz","parentScale","parentScaleInv","scaleMatrix","getPosition","pos","getPositionToRef","getAbsolutePosition","getAbsolutePositionToRef","poseMatrix","getPoseMatrix","len","computeAbsoluteTransforms","getDirection","localAxis","getDirectionToRef","mat","TransformNormalToRef","getRotationToRef","getRotationQuaternionToRef","toEulerAnglesToRef","getRotationQuaternion","amat","getRotationMatrix","getRotationMatrixToRef","getAbsolutePositionFromLocal","getAbsolutePositionFromLocalToRef","getLocalPositionFromAbsolute","getLocalPositionFromAbsoluteToRef","setCurrentPoseAsRest","BuildArray","Animatable","_syncRoot","min","max","_speedRatio","_goToFrame","loopAnimation","onAnimationLoop","_localDelayOffset","_pausedDelay","_manualJumpDelay","_paused","_frameToSyncFromJump","disposeOnEnd","animationStarted","onAnimationEndObservable","onAnimationLoopObservable","appendAnimations","_activeAnimatables","syncWith","getAnimations","newRuntimeAnimation","getAnimationByTargetProperty","getRuntimeAnimationByTargetProperty","disableBlending","fps","pause","restart","_raiseOnAnimationEnd","animationName","targetMask","useGlobalSplice","idx","waitAsync","_animate","running","isRunning","clear","prototype","animationsEnabled","now","Now","_animationTimeLast","_pendingData","deltaTime","useConstantAnimationDeltaTime","animationTimeScale","animatables","_animationTime","animationTime","animatable","_processLateAnimationBindings","beginWeightedAnimation","returnedAnimatable","stopCurrent","shouldRunTargetAnimations","getAnimatables","beginHierarchyAnimation","getDescendants","temp","getAnimatableByTarget","getAllAnimatablesByTarget","stopAllAnimations","group","animationGroups","_registeredForLateAnimationBindings","pushNoDuplicate","_lateAnimationHolders","totalWeight","totalAdditiveWeight","additiveAnimations","_processLateAnimationBindingsForMatrices","holder","normalizer","finalPosition","finalScaling","finalQuaternion","originalAnimation","skipOverride","scaleInPlace","animIndex","currentPosition","currentScaling","currentQuaternion","scaleAndAddToRef","Dot","SlerpToRef","Matrix","_processLateAnimationBindingsForQuaternions","refQuaternion","cumulativeQuaternion","quaternions","weights","cumulativeAmount","path","matrixDecomposeMode","finalValue","copyAnimationRange","rangeName","frameOffset","rescaleAsRequired","skelDimensionsRatio","sourceRange","sourceKeys","sourceBoneLength","sourceParent","parentScalingReqd","parentRatio","dimensionsScalingReqd","destKeys","orig","origTranslation","getTranslation","setTranslation","multiplyInPlace","Orientation","Angle","radians","_radians","degrees","delta","theta","atan2","Arc2","startPoint","midPoint","endPoint","pow","startToMid","midToEnd","det","centerPoint","radius","startAngle","BetweenTwoPoints","a1","a2","a3","orientation","CW","CCW","FromDegrees","_points","_length","closed","addLineTo","newPoint","previousPoint","addArcTo","midX","midY","endX","endY","numberOfSegments","arc","increment","currentAngle","cos","addQuadraticCurveTo","controlX","controlY","equation","t","val0","val1","val2","step","addBezierCurveTo","originTangentX","originTangentY","destinationTangentX","destinationTangentY","val3","isPointInside","point","isInside","count","p","q","edgeLow","edgeHigh","edgeDx","edgeDy","Number","EPSILON","perpEdge","close","lastPoint","area","n","getPoints","getPointAtLengthPosition","normalizedLengthPosition","lengthPosition","previousOffset","bToA","nextOffset","dir","localOffset","Path3D","firstNormal","raw","alignTangentsWithPath","_curve","_distances","_tangents","_normals","_binormals","_pointAtData","previousPointArrayIndex","subPosition","interpolateReady","interpolationMatrix","_raw","_alignTangentsWithPath","_compute","getCurve","getTangents","getNormals","getBinormals","getDistances","getPointAt","_updatePointAtData","getTangentAt","interpolated","Forward","getNormalAt","Right","getBinormalAt","UpReadOnly","getDistanceAt","getPreviousPointIndexAt","getSubPositionAt","getClosestPositionTo","smallestDistance","MAX_VALUE","closestPosition","tangent","subLength","Distance","distance","_start","curvePoints","slicePoints","update","l","_getFirstNonNullVector","tg0","pp0","_normalVector","prev","cur","curTang","prevNor","prevBinor","Cross","_getLastNonNullVector","NaN","nNVector","nLVector","vt","va","normal0","tgl","WithinEpsilon","CrossToRef","interpolateTNB","_updateInterpolationMatrix","_setPointAtData","currentPoint","currentLength","targetLength","diff","parentIndex","tangentFrom","normalFrom","binormalFrom","tangentTo","normalTo","binormalTo","quatFrom","RotationQuaternionFromAxis","quatTo","toRotationMatrix","Curve3","v0","v1","v2","nbPoints","bez","v3","p1","t1","p2","t2","nSeg","hermite","points","catmullRom","pointsCount","c","CatmullRom","totalPoints","apply","second","third","steps","fullCircle","vec1","vec2","vec3","zAxis","len4","len1_sq","lengthSquared","len2_sq","len3_sq","len4_sq","center","xAxis","yAxis","dStep","equalsWithEpsilon","_computeLength","continue","curve","continuedPoints","EasingFunction","_easingMode","EASINGMODE_EASEIN","setEasingMode","easingMode","getEasingMode","easeInCore","Error","EASINGMODE_EASEOUT","EASINGMODE_EASEINOUT","CircleEase","sqrt","QuadraticEase","SineEase","AnimationEvent","TargetedAnimation","targetId","AnimationGroup","_from","_to","isStarted","_isStarted","isPlaying","_isPaused","_animatables","_loopAnimation","_isAdditive","targetedAnimations","_targetedAnimations","_parentContainer","onAnimationGroupLoopObservable","onAnimationGroupEndObservable","onAnimationGroupPauseObservable","onAnimationGroupPlayObservable","metadata","_animationLoopFlags","getUniqueId","addAnimationGroup","addTargetedAnimation","targetedAnimation","removeTargetedAnimation","beginFrame","_processLoop","_animationLoopCount","_checkAnimationGroupEnded","list","curIndex","setWeightForAllAnimatables","syncAllAnimationsWith","newName","targetConverter","cloneAnimations","newGroup","targetAnimation","targetedAnimationIndex","HasTags","tags","GetTags","parsedAnimationGroup","animationGroup","morphTarget","getMorphTargetById","targetNode","getNodeById","AddTagsTo","sourceAnimationGroup","MakeAnimationAdditive","_instancedMeshFactory","instance","InstancedMesh","instancedBuffers","_indexInSourceMeshInstanceArray","_distanceToCamera","addInstance","_sourceMesh","_unIndexed","getAnimationRanges","createAnimationRange","infiniteDistance","setPivotMatrix","getPivotMatrix","refreshBoundingInfo","_syncSubMeshes","lightSources","_lightSources","_resyncLightSources","_resyncLightSource","_removeLightSource","receiveShadows","_value","material","visibility","renderingGroupId","getTotalVertices","getTotalIndices","sourceMesh","createInstance","isReady","completeCheck","getVerticesData","kind","copyWhenShared","forceCopy","setVerticesData","updatable","stride","updateVerticesData","updateExtends","makeItUnique","setIndices","indices","totalVertices","isVerticesDataPresent","getIndices","_positions","applySkeleton","applyMorph","hasBoundingInfo","getBoundingInfo","isLocked","bias","geometry","boundingBias","_refreshBoundingInfo","_getPositionData","_preActivate","_currentLOD","_activate","renderId","intermediateRendering","subMeshes","_getWorldMatrixDeterminant","_internalAbstractMeshDataInfo","_actAsRegularMesh","_registerInstanceForRenderId","_isActiveIntermediate","_onlyForInstancesIntermediate","_isActive","_onlyForInstances","_postActivate","edgesShareWithInstances","_edgesRenderer","isEnabled","_renderingGroup","_edgesRenderers","customInstances","billboardMode","BILLBOARDMODE_NONE","_masterMesh","_billboardWorldMatrix","tempMaster","computeWorldMatrix","isAnInstance","getLOD","camera","sourceMeshLODLevels","getLODLevels","boundingInfo","boundingSphere","_preActivateForIntermediateRendering","releaseSubMeshes","_generatePointsArray","_updateBoundingInfo","worldMatrixFromCache","buildBoundingInfo","absolutePosition","_updateSubMeshesBoundingInfo","doNotCloneChildren","newSourceMesh","meshes","onClonedObservable","doNotRecurse","disposeMaterialAndTextures","removeInstance","_serializeAsParent","parentId","parentInstanceIndex","instantiateHierarchy","options","onNewNodeCreated","newSourcedMesh","getChildTransformNodes","registerInstancedBuffer","_b","_userInstancedBuffersStorage","vertexBuffers","instances","strides","sizes","vertexArrayObjects","getEngine","getCaps","vertexArrayObject","Float32Array","_invalidateInstanceVertexArrayObject","_markSubMeshesAsAttributesDirty","_processInstancedBuffers","visibleInstances","renderSelf","instanceCount","size","expectedSize","offset","toArray","copyToArray","instanceIndex","updateDirectly","releaseVertexArrayObject","_disposeInstanceSpecificData","_instanceDataStorage","instancesBuffer","_range","_inverseSquaredRange","intensityMode","_intensityMode","_computePhotometricScale","_radius","shadowEnabled","_shadowEnabled","_markMeshesAsLightDirty","includedOnlyMeshes","_includedOnlyMeshes","_hookArrayForIncludedOnly","excludedMeshes","_excludedMeshes","_hookArrayForExcluded","excludeWithLayerMask","_excludeWithLayerMask","_resyncMeshes","includeOnlyWithLayerMask","_includeOnlyWithLayerMask","lightmapMode","_lightmapMode","diffuse","specular","falloffType","FALLOFF_DEFAULT","intensity","_photometricScale","INTENSITYMODE_AUTOMATIC","renderPriority","_shadowGenerators","_excludedMeshesIds","_includedOnlyMeshesIds","addLight","_uniformBuffer","_buildUniformLayout","transferTexturesToEffect","effect","lightIndex","_bindLight","useSpecular","iAsString","needUpdate","bindToEffect","_renderId","_lastUseSpecular","useUbo","scaledIntensity","getScaledIntensity","transferToEffect","scaleToRef","Color3","updateColor4","shadowsEnabled","shadowGenerator","getShadowGenerator","activeCamera","bindShadowLight","bindUniformBuffer","getTypeID","_syncParentEnabledState","isDisposed","setEnabled","get","getShadowGenerators","canAffectMesh","layerMask","iterator","next","done","lights","removeLight","GetConstructorFromName","clonedLight","Clone","Serialize","excludedMeshesIds","includedOnlyMeshesIds","serializeAnimationRanges","constructorFunc","Construct","parsedLight","light","_waitingParentId","_waitingParentInstanceIndex","animationIndex","internalClass","ParseAnimationRanges","autoAnimate","autoAnimateFrom","autoAnimateTo","autoAnimateLoop","autoAnimateSpeed","array","oldPush","items","item","oldSplice","deleteCount","deleted","_markSubMeshesAsLightDirty","_getPhotometricScale","resetCachedMaterial","photometricScale","lightTypeID","photometricMode","LIGHTTYPEID_DIRECTIONALLIGHT","INTENSITYMODE_ILLUMINANCE","INTENSITYMODE_LUMINOUSINTENSITY","LIGHTTYPEID_POINTLIGHT","LIGHTTYPEID_SPOTLIGHT","INTENSITYMODE_LUMINOUSPOWER","INTENSITYMODE_LUMINANCE","apexAngleRadians","LIGHTTYPEID_HEMISPHERICLIGHT","_reorderLightsInScene","_renderPriority","requireLightSorting","sortLightsByPriority","FALLOFF_PHYSICAL","FALLOFF_GLTF","FALLOFF_STANDARD","LIGHTMAP_DEFAULT","LIGHTMAP_SPECULAR","LIGHTMAP_SHADOWSONLY","KeepAssets","InstantiatedEntries","rootNodes","skeletons","o","AssetContainer","_wasAddedToScene","onDisposeObservable","_onContextRestoredObserver","onContextRestoredObservable","geometries","_rebuild","system","particleSystems","rebuild","texture","textures","_topologicalSort","nodes","nodesUidMap","Map","dependencyGraph","dependsOn","dependedBy","nodeId","Set","masterMesh","has","childId","sortedNodes","leaves","delete","visitList","nodeToVisit","shift","dependedByVisitedNode","dependedByVisitedNodeId","dependsOnDependedByVisitedNode","console","error","_addNodeAndDescendantsToList","addedIds","rootNode","_isNodeInContainer","transformNodes","cameras","_isValidHierarchy","instantiateModelsToScene","nameFunction","cloneMaterials","conversionMap","storeMap","alreadySwappedSkeletons","alreadySwappedMaterials","localOptions","assign","doNotInstantiate","nodesToSort","idsOnSortList","onNewCreated","clonedMesh","morphTargetManager","oldMorphTargetManager","numTargets","oldTarget","getTarget","newTarget","onClone","replicatedParentId","replicatedParent","sourceMaterial","swap","multi","subMaterials","map","multiMaterials","addMultiMaterial","materials","addMaterial","instancedNode","replicatedSourceId","replicatedInstancedNode","canInstance","replicatedNode","s","copy","bone","addAllToScene","addToScene","environmentTexture","component","_serializableComponents","addFromContainer","remove","addCamera","addMesh","addSkeleton","addAnimation","morphTargetManagers","addMorphTargetManager","addGeometry","addTransformNode","addActionManager","addTexture","reflectionProbes","addReflectionProbe","removeAllFromScene","removeFromScene","removeFromContainer","removeCamera","removeMesh","removeSkeleton","removeAnimation","removeAnimationGroup","removeMultiMaterial","removeMaterial","removeMorphTargetManager","removeGeometry","removeTransformNode","removeActionManager","removeTexture","removeReflectionProbe","_moveAssets","sourceAssets","targetAssets","keepAssets","asset","move","keepAsset","moveAllFromScene","hasOwnProperty","call","createRootMesh","rootMesh","addChild","unshift","mergeAnimationsTo","_targetConverter","getTransformNodeByName","getMorphTargetByName","getNodes","nodeInAC","nodeInScene","animationInAC","animationsWithSameProperty","filter","animationInScene","animationWithSameProperty","concat","newAnimationGroups","animationGroupInAC","AudioEngineFactory","hostElement","audioContext","audioDestination","AudioEngine","_audioContextInitialized","unlocked","_muteButton","_displayMuteButton","_initializeAudioContext","_audioContext","_audioDestination","canUseWebAudio","WarnedWebAudioUnsupported","isMP3supported","isOGGsupported","useCustomUnlockedButton","onAudioUnlockedObservable","onAudioLockedObservable","_tryToRun","_onResize","_moveButtonToTopLeft","window","AudioContext","audioElem","document","createElement","_hostElement","canPlayType","lock","_triggerSuspendedState","unlock","_triggerRunningState","_resumeAudioContext","resume","masterGain","createGain","gain","connect","message","_hideMuteButton","catch","className","title","css","SVGSVGElement","style","appendChild","createTextNode","getElementsByTagName","body","top","offsetTop","offsetLeft","removeChild","_connectedAnalyser","stopDebugCanvas","disconnect","removeEventListener","getGlobalVolume","setGlobalVolume","newVolume","connectToAnalyser","analyser","connectAudioNodes","Sound","_loop","updateOptions","currentTime","_htmlAudioElement","audioEngine","isPaused","timeSinceLastStart","_startTime","_currentTime","spatialSound","_spatialSound","newValue","_createSpatialParameters","urlOrArrayBuffer","readyToPlayCallback","_c","_d","_e","autoplay","useCustomAttenuation","refDistance","rolloffFactor","maxDistance","distanceModel","onEndedObservable","_panningModel","_playbackRate","_streaming","_position","_localDirection","_volume","_isReadyToPlay","_isDirectional","_coneInnerAngle","_coneOuterAngle","_coneOuterGain","_isOutputConnected","_urlType","_SceneComponentInitialization","_readyToPlayCallback","_customAttenuationFunction","currentVolume","currentDistance","volume","playbackRate","streaming","_offset","_soundGain","_inputAudioNode","_outputAudioNode","mainSoundTrack","addSound","validParameter","ArrayBuffer","HTMLMediaElement","MediaStream","AudioBuffer","isArray","urls","codecSupportedFound","_streamingSource","createMediaElementSource","createMediaStreamSource","byteLength","_soundLoaded","_audioBufferLoaded","skipCodecCheck","Audio","controls","SetCorsBehavior","preload","load","_loadFile","exception","removeSound","setTimeout","ex","soundTrackId","soundTracks","_soundPanner","_soundSource","_audioBuffer","_connectedTransformNode","_registerFunc","unregisterAfterWorldMatrixUpdate","buffer","audioData","decodeAudioData","err","setAudioBuffer","audioBuffer","_f","_g","_h","_j","_k","_setOffset","setVolume","_updateSpatialParameters","loopStart","loopEnd","headphone","createPanner","panningModel","switchPanningModelToHRTF","_switchPanningModel","switchPanningModelToEqualPower","connectToSoundTrackAudioNode","soundTrackAudioNode","setDirectionalCone","coneInnerAngle","coneOuterAngle","coneOuterGain","directionalConeInnerAngle","directionalConeOuterAngle","positionX","positionY","positionZ","setLocalDirectionToMesh","newLocalDirection","_updateDirection","direction","TransformNormal","orientationX","orientationY","orientationZ","updateDistanceFromListener","audioListenerPositionProvider","getDistanceToCamera","setAttenuationFunction","callback","time","audioEnabled","startTime","setOrientation","onended","_onended","tryToPlay","playPromise","addOnce","oldSource","createBufferSource","actualOffset","stopTime","cancelScheduledValues","setValueAtTime","linearRampToValueAtTime","setPlaybackRate","newPlaybackRate","getPlaybackRate","getVolume","attachToMesh","_onRegisterAfterWorldMatrixUpdate","registerAfterWorldMatrixUpdate","detachFromMesh","centerWorld","setBufferAndRun","clonedSound","getAudioBuffer","currentOptions","getSoundSource","getSoundGain","connectedMeshId","isDirectional","localDirectionToMesh","parsedSound","rootUrl","sourceSound","soundName","soundUrl","newSound","removePendingData","addPendingData","soundPosition","connectedMesh","_","SoundTrack","_isInitialized","soundCollection","_options","mainTrack","_initializeSoundTrackAudioGraph","AddParser","NAME_AUDIO","parsedData","container","loadedSound","loadedSounds","sounds","cache","defineProperty","compo","_getComponent","AudioSceneComponent","_addComponent","_mainSoundTrack","enumerable","configurable","sdIndex","enableAudio","disableAudio","switchAudioModeForHeadphones","switchAudioModeForNormalSpeakers","audioListenerRotationProvider","audioPositioningRefreshRate","_audioEnabled","_headphone","_cachedCameraDirection","_cachedCameraPosition","_lastCheck","_invertMatrixTemp","_cameraDirectionTemp","register","_afterRenderStage","registerStep","STEP_AFTERRENDER_AUDIO","_afterRender","soundtrack","soundId","scIndex","suspend","listeningCamera","activeCameras","listener","globalPosition","rigCameras","getViewMatrix","_CameraDirection","WeightedSound","_sounds","_weights","weightSum","invWeightSum","_currentIndex","startOffset","randomValue","random","total","BakedVertexAnimationManager","_texture","_isEnabled","animationParameters","bakedVertexAnimationManager","bind","useInstances","getSize","setFloat2","setFloat","setVector4","setTexture","copyTo","setAnimationParameters","startFrame","speedFramesPerSecond","forceDisposeTextures","vatMap","wrapU","_wrapU","wrapV","_wrapV","coordinatesMode","isCube","is3D","is2DArray","_shareDepth","internalTexture","wrapR","anisotropicFilteringLevel","delayLoadState","_engine","_cachedSize","_cachedBaseSize","_initialSamplingMode","_IsRenderTargetWrapper","delayLoad","getInternalTexture","_size","getBaseSize","baseWidth","baseHeight","samplingMode","updateSamplingMode","updateTextureSamplingMode","releaseInternalTexture","hasAlpha","_hasAlpha","markAllMaterialsAsDirty","hasTexture","getAlphaFromRGB","_getAlphaFromRGB","coordinatesIndex","_coordinatesIndex","_coordinatesMode","_isCube","gammaSpace","_gammaSpace","_useSRGBBuffer","gamma","_markAllSubMeshesAsTexturesDirty","isRGBD","_isRGBD","noMipmap","lodGenerationOffset","_lodGenerationOffset","lodGenerationScale","_lodGenerationScale","linearSpecularLOD","_linearSpecularLOD","irradianceTexture","_irradianceTexture","uid","_uid","onDispose","_onDisposeObserver","isBlocking","loadingError","_loadingError","errorObject","_errorObject","sceneOrEngine","reservedDataStore","level","optimizeUVAllocation","DEFAULT_ANISOTROPIC_FILTERING_LEVEL","invertZ","lodLevelInAlpha","isRenderTarget","_prefiltered","_forceSerialize","_IsScene","_getEngine","checkTransformsAreIdentical","getTextureMatrix","IdentityReadOnly","getReflectionTextureMatrix","getRefractionTextureMatrix","isReadyOrNotBlocking","canRescale","_getFromCache","sampling","invertY","useSRGBBuffer","engine","correctedUseSRGBBuffer","_getUseSRGBBuffer","texturesCache","getLoadedTexturesCache","texturesCacheEntry","generateMipMaps","incrementReferences","textureType","textureFormat","format","readPixels","faceIndex","flushRenderer","noDataConversion","maxWidth","maxHeight","round","_readTexturePixels","_readPixelsSync","_readTexturePixelsSync","_lodTextureHigh","_lodTextureMid","_lodTextureLow","onTextureRemovedObservable","allowEmptyName","numRemaining","onLoadObservable","GenerateBase64StringFromPixelData","pixels","BYTES_PER_ELEMENT","npixels","Uint8Array","val","canvas","ctx","getContext","imageData","createImageData","putImageData","canvas2","ctx2","drawImage","toDataURL","GenerateBase64StringFromTexture","async","GenerateBase64StringFromTextureAsync","_noMipmap","mimeType","_mimeType","_isBlocking","_invertY","noMipmapOrOptions","TRILINEAR_SAMPLINGMODE","onLoad","onError","deleteBuffer","loaderOptions","creationFlags","forcedExtension","uOffset","vOffset","uScale","vScale","uAng","vAng","wAng","uRotationCenter","vRotationCenter","wRotationCenter","homogeneousRotationInUVTransform","inspectableCustomProperties","_rowGenerationMatrix","_cachedTextureMatrix","_projectionModeMatrix","_t0","_t1","_t2","_cachedUOffset","_cachedVOffset","_cachedUScale","_cachedVScale","_cachedUAng","_cachedVAng","_cachedWAng","_cachedReflectionProjectionMatrixId","_cachedURotationCenter","_cachedVRotationCenter","_cachedWRotationCenter","_cachedHomogeneousRotationInUVTransform","_cachedReflectionTextureMatrix","_cachedReflectionUOffset","_cachedReflectionVOffset","_cachedReflectionUScale","_cachedReflectionVScale","_cachedReflectionCoordinatesMode","_buffer","_deleteBuffer","_format","_delayedOnLoad","_delayedOnError","UseOpenGLOrientationForUV","_loaderOptions","_creationFlags","_forcedExtension","onBeforeTextureInitObservable","_invertVScale","_cachedWrapU","_cachedWrapV","_cachedWrapR","hasObservers","errorHandler","OnTextureLoadErrorObservable","SetImmediate","loadObserver","onLoadedObservable","onErrorObservable","useDelayedTextureLoading","createTexture","updateURL","startsWith","_prepareRowForTextureGeneration","TransformCoordinatesFromFloatsToRef","uBase","TranslationToRef","setRowFromFloats","FromValuesToRef","PROJECTION_MODE","getProjectionMatrix","flagMaterialsAsTextureDirty","PLANAR_MODE","projectionMatrix","getActiveTextures","savedName","SerializeBuffers","_SerializeInternalTextureUniqueId","ForceSerializeBuffers","substr","base64String","_features","supportSyncTextureRead","internalTextureUniqueId","parsedTexture","customType","parsedCustomTexture","Instantiate","_samplingMode","_CubeTextureParser","hasInternalTextureUniqueId","onLoaded","_setUniqueId","mirrorPlane","mirrorTexture","_CreateMirror","renderTargetSize","_waitingRenderList","renderList","renderTargetTexture","probe","cubeTexture","_CreateRenderTargetTexture","CreateFromBase64String","UseSerializedUrlIfAny","jsonTexture","NEAREST_SAMPLINGMODE","NEAREST_NEAREST_MIPLINEAR","BILINEAR_SAMPLINGMODE","LINEAR_LINEAR_MIPNEAREST","LINEAR_LINEAR_MIPLINEAR","NEAREST_NEAREST_MIPNEAREST","NEAREST_LINEAR_MIPNEAREST","NEAREST_LINEAR_MIPLINEAR","NEAREST_LINEAR","NEAREST_NEAREST","LINEAR_NEAREST_MIPNEAREST","LINEAR_NEAREST_MIPLINEAR","LINEAR_LINEAR","LINEAR_NEAREST","EXPLICIT_MODE","SPHERICAL_MODE","CUBIC_MODE","SKYBOX_MODE","INVCUBIC_MODE","EQUIRECTANGULAR_MODE","FIXED_EQUIRECTANGULAR_MODE","FIXED_EQUIRECTANGULAR_MIRRORED_MODE","CLAMP_ADDRESSMODE","WRAP_ADDRESSMODE","MIRROR_ADDRESSMODE","_TextureParser","_convertRGBtoRGBATextureData","rgbData","rgbaData","Uint16Array","Uint32Array","newIndex","_makeCreateRawTextureFunction","depth","compression","_gl","TEXTURE_3D","TEXTURE_2D_ARRAY","Raw3D","Raw2DArray","baseDepth","_doNotHandleContextLost","_bufferView","updateRawTexture3D","updateRawTexture2DArray","_bindTextureDirectly","filters","_getSamplingParameters","texParameteri","TEXTURE_MAG_FILTER","mag","TEXTURE_MIN_FILTER","generateMipmap","_internalTexturesCache","_makeUpdateRawTextureFunction","internalType","_getWebGLTextureType","internalFormat","_getInternalFormat","internalSizedFomat","_getRGBABufferInternalSizedFormat","_unpackFlipY","_compression","pixelStorei","UNPACK_ALIGNMENT","compressedTexImage3D","s3tc","texImage3D","updateRawTexture","TEXTURE_2D","compressedTexImage2D","texImage2D","createRawTexture","Raw","createRawCubeTexture","gl","CubeRaw","_bufferViewArray","RGB","RGBA","FLOAT","_caps","textureFloatLinearFiltering","HALF_FLOAT_OES","textureHalfFloatLinearFiltering","textureFloatRender","HALF_FLOAT","colorBufferFloat","needPOTTextures","IsExponentOfTwo","updateRawCubeTexture","TEXTURE_CUBE_MAP","TEXTURE_CUBE_MAP_POSITIVE_X","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","needConversion","faceData","createRawCubeTextureFromUrl","mipmapGenerator","internalCallback","faceDataArrays","mipData","mipSize","mipFaceData","offlineProvider","statusText","createRawTexture2DArray","createRawTexture3D","AutoRotationBehavior","_zoomStopsAnimation","_idleRotationSpeed","_idleRotationWaitTime","_idleRotationSpinupTime","targetAlpha","_isPointerDown","_lastFrameTime","_lastInteractionTime","Infinity","_cameraRotationSpeed","_lastFrameRadius","zoomStopsAnimation","flag","idleRotationSpeed","speed","idleRotationWaitTime","idleRotationSpinupTime","rotationInProgress","init","attach","_attachedCamera","_onPrePointerObservableObserver","onPrePointerObservable","pointerInfoPre","POINTERDOWN","POINTERUP","_onAfterCheckInputsObserver","onAfterCheckInputsObservable","_reachTargetAlpha","dt","_applyUserInteraction","timeToRotation","alpha","detach","resetLastInteractionTime","customTime","_userIsZooming","inertialRadiusOffset","_shouldAnimationStopForInteraction","zoomHasHitLimit","_userIsMoving","inertialAlphaOffset","inertialBetaOffset","inertialPanningX","inertialPanningY","BouncingBehavior","transitionDuration","lowerRadiusTransitionRange","upperRadiusTransitionRange","_autoTransitionRange","_radiusIsAnimating","_radiusBounceTransition","autoTransitionRange","_onMeshTargetChangedObserver","onMeshTargetChangedObservable","diagonal","diagonalLength","_isRadiusAtLimit","lowerRadiusLimit","_applyBoundRadiusAnimation","upperRadiusLimit","radiusLimit","radiusDelta","EasingMode","CreateAnimation","_cachedWheelPrecision","wheelPrecision","TransitionTo","_clearAnimationLocks","amplitude","num","FramingBehavior","onTargetFramingAnimationEndObservable","_mode","FitFrustumSidesMode","_radiusScale","_positionScale","_defaultElevation","_elevationReturnTime","_elevationReturnWaitTime","_framingTime","autoCorrectCameraLimitsAndSensibility","_betaIsAnimating","mode","radiusScale","positionScale","defaultElevation","elevation","elevationReturnTime","elevationReturnWaitTime","framingTime","zoomOnMesh","_maintainCameraAboveGround","focusOnOriginXZ","boundingBox","zoomOnBoundingInfo","minimumWorld","maximumWorld","zoomOnMeshHierarchy","getHierarchyBoundingVectors","zoomOnMeshesHierarchy","CheckExtends","zoomTarget","bottom","zoomTargetY","radiusWorld","_vectorTransition","_calculateLowerRadiusFromModelBoundingSphere","minZ","IgnoreBoundsSizeMode","extend","panningSensibility","_radiusTransition","useInputToRestoreState","storeState","boxVectorGlobalDiagonal","frustumSlope","_getFrustumSlope","distanceForHorizontalFrustum","distanceForVerticalFrustum","timeSinceInteraction","defaultBeta","limitBeta","beta","_betaTransition","animatabe","aspectRatio","getAspectRatio","frustumSlopeY","tan","fov","frustumSlopeX","isUserIsMoving","exponent","exp","origin","intersectsBoxMinMax","minimum","maximum","intersectionTreshold","newMinimum","_TmpVector3","newMaximum","inv","d","maxValue","intersectsBox","box","intersectsSphere","sphere","pyth","rr","dot","intersectsTriangle","vertex0","vertex1","vertex2","edge1","edge2","pvec","qvec","invdet","bv","bw","intersectsPlane","plane","result1","normal","result2","intersectsAxis","intersectsMesh","fastCheck","trianglePredicate","onlyBoundingInfo","worldToUse","skipBoundingInfo","tm","_tmpRay","TransformToRef","Transform","intersects","intersectsMeshes","results","pickInfo","hit","_comparePickingInfo","pickingInfoA","pickingInfoB","intersectionSegment","sega","segb","threshold","u","rsegb","v","_Rayl","addToRef","D","sN","tN","sD","tD","_Smallnum","sc","tc","qtc","qsc","dP","viewportWidth","viewportHeight","world","view","projection","enableDistantPicking","_RayDistant","unprojectRayToRef","ray","sourceX","sourceY","nearScreenSource","LastCreatedEngine","isNDCHalfZRange","farScreenSource","nearVec3","farVec3","_UnprojectFromInvertedMatrixToRef","createPickingRay","cameraViewSpace","createPickingRayToRef","viewport","toGlobal","getRenderWidth","getRenderHeight","getHardwareScalingLevel","createPickingRayInCameraSpace","createPickingRayInCameraSpaceToRef","identity","_internalPickForMesh","pickingInfo","rayFunction","_internalPick","computeWorldMatrixForCamera","cameraToUseForPointers","currentCamera","meshIndex","isVisible","isPickable","forceCompute","isWorldMatrixCameraDependent","hasThinInstances","thinInstanceEnablePicking","tmpMatrix","thinMatrices","thinInstanceGetWorldMatrices","thinInstanceIndex","_internalMultiPick","pickingInfos","pickWithBoundingInfo","_tempPickingRay","pick","_enableDistantPicking","pickWithRay","_pickWithRayInverseMatrix","_cachedRayForTransform","multiPick","multiPickWithRay","getForwardRay","transform","getForwardRayToRef","refRay","useRightHandedSystem","NormalizeToRef","_PivotCached","getPivotPointToRef","_OldPivotPoint","_PivotPostMultiplyPivotMatrix","_postMultiplyPivotMatrix","equalsToFloats","getPivotPoint","_PivotTranslation","_PivotTmpVector","setPivotPoint","CreatePlaneVertexData","positions","normals","uvs","sideOrientation","DEFAULTSIDE","halfWidth","halfHeight","_ComputeSides","frontUVs","backUVs","vertexData","_GetDefaultSideOrientation","_originalBuilderSideOrientation","applyToMesh","sourcePlane","setDirection","CreatePlane","currentDraggingPointerID","currentDraggingPointerId","enabled","_enabled","onEnabledObservable","_useAlternatePickedPointAboveMaxDragAngleDragSpeed","_activeDragButton","maxDragAngle","dragButtons","_useAlternatePickedPointAboveMaxDragAngle","dragging","dragDeltaRatio","updateDragPlane","_debugMode","_moving","onDragObservable","onDragStartObservable","onDragEndObservable","moveAttached","startAndReleaseDragOnPointerEvents","detachCameraControls","useObjectOrientationForDragging","validateDrag","targetPosition","_tmpVector","_alternatePickedPoint","_worldDragAxis","_targetPosition","_attachedToElement","_startDragRay","_lastPointerRay","_dragDelta","_pointA","_pointC","_localAxis","_lookAt","optionCount","dragAxis","dragPlaneNormal","ownerNode","isNearGrabbable","attachedNode","_PlaneScene","virtual","detachControl","_dragPlane","DOUBLESIDE","lastDragPosition","pickPredicate","isDescendantOf","_pointerObserver","onPointerObservable","pointerInfo","pickedMesh","pickedPoint","button","_activePointerInfo","_startDrag","pointerId","releaseDrag","POINTERMOVE","_AnyMouseId","pointerType","hostInformation","isMobile","MouseEvent","_moveDrag","_beforeRenderObserver","onBeforeRenderObservable","needMatrixUpdate","_RemoveAndStorePivotPoint","_RestorePivotPoint","dragPlanePoint","leftCamera","arcRotateCamera","attachControl","inputs","noPreventDefault","_useCtrlForPanning","_panningMouseButton","startDrag","fromRay","startPickedPoint","lastRay","getTranslationToRef","_updateDragPlanePosition","_pickWithRayOnDragPlane","attachedToElement","dragLength","dragDistance","forward","acos","pickResult","dragPlanePosition","lookAt","ANCHOR_SYSTEM","BACKGROUND_REMOVER","HIT_TEST","MESH_DETECTION","PHYSICS_CONTROLLERS","PLANE_DETECTION","POINTER_SELECTION","TELEPORTATION","FEATURE_POINTS","HAND_TRACKING","IMAGE_TRACKING","NEAR_INTERACTION","DOM_OVERLAY","MOVEMENT","LIGHT_ESTIMATION","EYE_TRACKING","WALKING_LOCOMOTION","LAYERS","DEPTH_SENSING","SPACE_WARP","WebXRFeaturesManager","_xrSessionManager","onXRSessionInit","getEnabledFeatures","featureName","feature","featureImplementation","attached","disableAutoAttach","attachFeature","onXRSessionEnded","detachFeature","constructorFunction","version","stable","_AvailableFeatures","latest","xrSessionManager","disableFeature","Name","enableFeature","moduleOptions","attachIfPossible","required","versionToLoad","GetStableVersionOfFeature","GetLatestVersionOfFeature","conflictingFeature","_ConflictingFeatures","constructFunction","ConstructFeature","constructed","dependentsFound","every","isCompatible","session","getEnabledFeature","xrSessionInit","enabledFeatures","nativeName","xrNativeFeatureName","requiredFeatures","optionalFeatures","getXRSessionInitExtension","extended","WebXRAbstractFeature","_attached","_removeOnDetach","force","_addNewAttachObserver","onXRFrameObservable","_onXRFrame","toRemove","observable","observer","PhysicsJoint","jointData","nativeParams","physicsJoint","_physicsJoint","newJoint","physicsPlugin","_physicsPlugin","executeNativeFunction","DistanceJoint","HingeJoint","BallAndSocketJoint","WheelJoint","SliderJoint","PrismaticJoint","UniversalJoint","Hinge2Joint","PointToPointJoint","SpringJoint","LockJoint","_PhysicsImpostorParser","physicObject","jsonObject","physicsImpostor","mass","physicsMass","friction","physicsFriction","restitution","physicsRestitution","_isDisposed","_physicsEngine","getPhysicsPlugin","getBodyMass","setMass","getBodyFriction","setBodyFriction","getBodyRestitution","setBodyRestitution","pressure","plugin","setBodyPressure","getBodyPressure","stiffness","getBodyStiffness","setBodyStiffness","velocityIterations","getBodyVelocityIterations","setBodyVelocityIterations","positionIterations","getBodyPositionIterations","setBodyPositionIterations","_pluginData","_bodyUpdateRequired","_onBeforePhysicsStepCallbacks","_onAfterPhysicsStepCallbacks","_onPhysicsCollideCallbacks","_deltaPosition","soft","segments","_tmpQuat","_tmpQuat2","beforeStep","_deltaRotationConjugated","getParentsRotation","disableBidirectionalTransformation","setPhysicsBodyTransformation","afterStep","setTransformationFromPhysicsBody","_deltaRotation","applyRotationQuaternionToRef","onCollideEvent","onCollide","otherImpostor","getImpostorWithPhysicsBody","obj","otherImpostors","impulse","getPhysicsEngine","RotationYawPitchRoll","fixedPoints","margin","damping","shape","_joints","ignoreParent","_init","removeImpostor","physicsBody","_getPhysicsParent","addImpostor","isBodyInitRequired","_physicsBody","setScalingUpdated","forceUpdate","removePhysicsBody","resetUpdateFlags","getObjectExtents","IDENTITY_QUATERNION","worldMatrix","extendSize","DEFAULT_OBJECT_SIZE","getObjectCenter","getParam","paramName","setParam","setBodyMass","getLinearVelocity","setLinearVelocity","velocity","getAngularVelocity","setAngularVelocity","registerBeforePhysicsStep","unregisterBeforePhysicsStep","registerAfterPhysicsStep","unregisterAfterPhysicsStep","registerOnPhysicsCollide","collideAgainst","collidedAgainstList","unregisterOnPhysicsCollide","some","cbDef","sameList","impostor","applyForce","contactPoint","applyImpulse","createJoint","jointType","joint","addJoint","addAnchor","influence","noCollisionBetweenLinkedBodies","appendAnchor","addHook","appendHook","sleep","sleepBody","wakeUp","wakeUpBody","newObject","removeJoint","setDeltaPosition","setDeltaRotation","conjugate","getBoxSizeToRef","getRadius","syncBoneWithImpostor","boneMesh","jointPivot","distToJoint","adjustRotation","tempVec","tempQuat","syncImpostorWithBone","boneAxis","boneDir","NoImpostor","SphereImpostor","BoxImpostor","PlaneImpostor","MeshImpostor","CapsuleImpostor","CylinderImpostor","ParticleImpostor","HeightmapImpostor","ConvexHullImpostor","CustomImpostor","RopeImpostor","ClothImpostor","SoftbodyImpostor","SceneLoaderAnimationGroupLoadingMode","ForceFullSceneLoadingForIncremental","ShowLoadingScreen","loggingLevel","CleanBoneMatrixWeights","_RegisteredPlugins","extension","registeredPlugin","GetDefaultPlugin","canDirectLoad","sceneFilename","queryStringPosition","substring","dotPosition","lastIndexOf","_GetPluginForExtension","fileInfo","errorMessage","rawData","onSuccess","onProgress","pluginExtension","directLoad","_GetDirectLoad","_GetPluginForDirectLoad","_GetPluginForFilename","isBinary","createPlugin","OnPluginActivatedObservable","useArrayBuffer","dataCallback","responseURL","pluginDisposed","abort","manifestChecked","errorCallback","loadFile","file","canUseOfflineSupport","enableOfflineSupport","exceptionFound","regex","disableOfflineSupportExceptionRules","test","OfflineProviderFactory","disableManifestCheck","sceneFile","isView","filename","GetFilename","GetFolderPath","extensions","meshNames","_GetFileInfo","loadingToken","disposeHandler","_FormatErrorMessage","SceneLoaderError","progressHandler","successHandler","importedMeshesFiles","_LoadData","rewriteRootURL","importMesh","syncedPlugin","loadingPluginName","importMeshAsync","ImportMesh","Append","Load","_ShowingLoadingScreen","displayLoadingUI","executeWhenReady","hideLoadingUI","loadAsync","assets","loadAssetContainer","assetContainer","loadAssetContainerAsync","LoadAssetContainer","overwriteAnimations","animationGroupLoadingMode","Clean","Stop","Sync","NoSync","startingIndexForNewAnimatables","onAnimationFileImportedObservable","ImportAnimations","NO_LOGGING","MINIMAL_LOGGING","SUMMARY_LOGGING","DETAILED_LOGGING","NodeMaterialBlockConnectionPointTypes","NodeMaterialBlockTargets","PushMaterial","storeEffectOnSubMeshes","_normalMatrix","_storeEffectOnSubMeshes","getEffect","_activeEffect","isReadyForSubMesh","_isReadyForSubMesh","subMesh","defines","materialDefines","checkReadyOnEveryCall","bindOnlyWorldMatrix","setMatrix","bindOnlyNormalMatrix","normalMatrix","bindForSubMesh","_afterBind","_cachedEffect","_forceRebindOnNextCall","_mustRebind","isCachedMaterialInvalid","forceDisposeEffect","notBoundToMesh","NodeMaterialBuildState","supportUniformBuffers","attributes","uniforms","constants","samplers","functions","counters","_attributeDeclaration","_uniformDeclaration","_constantDeclaration","_samplerDeclaration","_varyingTransfer","_injectAtEnd","_repeatableContentAnchorIndex","_builtCompilationString","compilationString","finalize","emitComments","sharedData","isFragmentMode","Fragment","functionCode","functionName","varyingDeclaration","extensionName","_repeatableContentAnchor","_getFreeVariableName","prefix","variableNames","_getFreeDefineName","defineNames","_excludeVariableName","_emit2DSampler","_emit2DArraySampler","_getGLType","Float","Int","Vector2","Color4","Vector4","_emitExtension","define","_emitFunction","code","comments","_emitCodeFromInclude","includeName","repeatKey","substitutionVars","IncludesShadersStore","replaceStrings","replaceString","search","_emitFunctionFromInclude","storeKey","removeAttributes","removeUniforms","removeVaryings","removeIfDef","_registerTempVariable","temps","_emitVaryingFromString","notDefine","varyings","_emitUniformFromString","_emitFloat","NodeMaterialBuildStateSharedData","inputBlocks","textureBlocks","bindableBlocks","forcedBindableBlocks","blocksWithFallbacks","blocksWithDefines","repeatableContentBlocks","dynamicUniformBlocks","blockingBlocks","animatedInputs","hints","needWorldViewMatrix","needWorldViewProjectionMatrix","needAlphaBlending","needAlphaTesting","checks","emitVertex","emitFragment","notConnectedNonOptionalInputs","allowEmptyVertexProgram","emitErrors","notConnectedInput","ownerBlock","NodeMaterialConnectionPointCompatibilityStates","NodeMaterialConnectionPointDirection","NodeMaterialConnectionPoint","type1","type2","_direction","associatedVariableName","_ownerBlock","isInput","_enforceAssociatedVariableName","_associatedVariableName","_connectedPoint","innerType","_linkedConnectionSource","isConnected","_type","AutoDetect","BasedOnInput","_typeConnectionSource","_defaultConnectionPointType","_prioritizeVertex","VertexAndFragment","Vertex","connectedPoint","hasEndpoints","isConnectedToInputBlock","connectInputBlock","sourceBlock","connectedBlocks","_endpoints","endpoints","isDirectlyConnectedToVertexOutput","endpoint","Neutral","isConnectedInVertexShader","isConnectedInFragmentShader","createCustomInputBlock","_acceptedConnectionPointType","needDualDirectionValidation","acceptedConnectionPointTypes","excludedConnectionPointTypes","onConnectionObservable","isExposedOnFrame","exposedPortPosition","canConnectTo","connectionPoint","checkCompatibilityState","Compatible","otherBlock","TargetIncompatible","AreEquivalentTypes","TypeIncompatible","targetBlock","Input","isAnAncestorOf","HierarchyIssue","connectTo","ignoreConstraints","disconnectFrom","addExcludedConnectionPointFromAllowedTypes","mask","bitmask","All","displayName","inputName","targetBlockId","targetConnectionName","PropertyTypeForEdition","NodeMaterialBlock","_name","validateBlockName","isUnique","_isUnique","isFinalMerger","_isFinalMerger","_isInput","buildId","_buildId","_inputs","_outputs","getInputByName","getOutputByName","inputsAreExclusive","_codeVariableName","visibleInInspector","visibleOnFrame","_originalTargetIsNeutral","UniqueId","_setInitialTarget","initialize","nodeMaterial","_declareOutput","_writeVariable","_writeFloat","stringVersion","registerInput","isOptional","registerOutput","Output","getFirstAvailableInput","forOutput","input","getFirstAvailableOutput","forBlock","getSiblingOutput","current","block","notFound","_buildBlock","updateUniformsAndSamples","uniformBuffers","provideFallbacks","fallbacks","initializeDefines","prepareDefines","autoConfigure","replaceRepeatableContent","vertexShaderState","fragmentShaderState","willBeGeneratedIntoVertexShaderFromFragmentShader","_linkConnectionTypes","inputIndex0","inputIndex1","looseCoupling","_processBuild","activeBlocks","build","localBlockIsFragment","_vertexState","otherBlockWasGeneratedInVertexShader","_buildTarget","isAttribute","_noContextSwitch","reservedNames","reservedName","verbose","log","_inputRename","_outputRename","_dumpPropertiesCode","variableName","_dumpCode","uniqueNames","alreadyDumped","codeString","nameAsVariableName","connectedBlock","_dumpCodeForOutputConnections","connectedOutput","blockType","_deserialize","_deserializePortDisplayNamesAndExposedOnFrame","serializedInputs","serializedOutputs","port","TransformBlock","complementW","complementZ","otherAsInput","vector","xyz","transformName","nonUniformScaling","VertexOutputBlock","_isLogarithmicDepthEnabled","nodeList","useLogarithmicDepth","fragmentOutputNodes","editableInPropertyPage","propertyType","Boolean","groupName","propertyKey","propStore","_propStore","propertyName","NodeMaterialBlockConnectionPointMode","NodeMaterialSystemValues","FragmentOutputBlock","convertToGammaSpace","convertToLinearSpace","rgb","rgba","_linearDefineName","_gammaDefineName","BindLogDepth","aValue","notifiers","AnimatedInputBlockTypes","remapAttributeName","position2d","particle_uv","particle_color","particle_texturemask","particle_positionw","attributeInFragmentOnly","attributeAsUniform","InputBlock","isUniform","isSystemValue","_systemValue","World","WorldView","WorldViewProjection","View","ViewProjection","Projection","CameraPosition","FogColor","DeltaTime","MaterialAlpha","CameraParameters","Undefined","_animationType","None","isBoolean","matrixMode","isConstant","groupInInspector","onValueChangedObservable","setDefaultValue","setAsAttribute","attributeName","Attribute","setAsSystemValue","systemValue","_storedValue","Uniform","valueCallback","_valueCallback","isUndefined","isVarying","Varying","Time","getAnimationRatio","RealTime","_emitDefine","White","_emitConstant","toGammaSpaceToRef","useExactSrgbConversions","toLinearSpaceToRef","_emit","_transmitWorld","worldView","worldViewProjection","_transmit","getTransformMatrix","bindEyePosition","setColor3","fogColor","setFloat4","hasOriginBottomLeft","maxZ","setInt","setDirectColor4","setVector2","setVector3","codes","valueString","valueType","wellKnownValue","CurrentScreenBlock","_samplerName","uv","_injectVertexCode","uvInput","_mainUVName","_writeTextureRead","_writeOutput","vertexMode","_tempTextureRead","swizzle","ParticleTextureBlock","getInputBlockByPredicate","ParticleRampGradientBlock","color","rampColor","ParticleBlendMultiplyBlock","alphaTexture","alphaColor","blendColor","EffectFallbacks","_defines","_currentRank","_maxRank","_mesh","unBindMesh","addFallback","rank","addCPUSkinningFallback","hasMoreFallbacks","reduce","currentDefines","computeBonesUsingShaders","numBoneInfluencers","_bonesComputationForcedToCPU","otherMesh","currentFallbacks","shader","targetTypes","layerCounts","rtWrapper","NodeMaterialModes","xy","zwInput","_tempVector","P","particleEmitterType","direction1","direction2","minEmitBox","maxEmitBox","meshToRender","layer","TrigonometryBlockOperations","operation","HandPart","WebXRHandJoint","handMeshes","_bone1","localTarget","xzlen","ang1","ang2","_uniqueId","currentRotation","rotationChange","keysUp","keysDown","keysLeft","keysRight","keysUpward","keysDownward","keysRotateLeft","keysRotateRight","keysRotateUp","keysRotateDown","preventDefault","VirtualJoystick","_VJCanvasContext","stroke","pointers","keyboard","PoseEnabledControllerType","browserGamepad","buttons","_babylonGamepads","ClearCoatTintTextureEnabled","f","uniform","particle","depthOnlySubMeshes","setColorWrite","renderSubMesh","opaqueSubMeshes","transparentSubMeshes","V"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"475-1b51ef15275da40692d5.js","mappings":"wHAQO,MAAMA,EAMTC,YAEAC,EAAgBC,GACZC,KAAKF,eAAiBA,EAItBE,KAAKC,0BAA4B,IAAI,KACjCH,EAAeI,WACfF,KAAKG,QAAUL,EAAeK,QAC9BH,KAAKI,kBAAoBN,EAAeI,WAEnCJ,EAAeK,QACpBH,KAAKG,QAAUL,EAAeK,QAG9BH,KAAKG,QAAUL,EAEnBE,KAAKK,kBAAoBL,KACzBA,KAAKM,WAAaP,CACtB,CAKAQ,WAAa,CAKbC,sBACI,OAAOR,KAAKI,iBAChB,CAKAK,oBAAoBC,GAChBV,KAAKI,kBAAoBM,CAC7B,CAKAC,oCACI,MAAMZ,EAAYC,KAAKM,WACvB,IAAKP,EACD,OAAO,EAEX,MAAMa,EAAkBZ,KAAKa,eAAeC,WAAWC,cAMvD,OAJIhB,EAAUiB,gBAAkBJ,IAC5Bb,EAAUiB,cAAgBJ,EAC1Bb,EAAUkB,eAAiBlB,EAAUmB,WAElCnB,EAAUkB,cACrB,CAKAE,gBAAgBC,GACapB,KAAKW,sCAI9BX,KAAKC,0BAA0BoB,gBAAgBrB,MAC/CA,KAAKK,kBAAkBiB,QAAQF,GAC/BpB,KAAKuB,yBACT,CAMAD,QAAQF,GAAO,CAIfG,yBACQvB,KAAKK,kBAAkBmB,QAClBxB,KAAKK,kBAAkBmB,OAAOX,iBAC/Bb,KAAKK,kBAAkBmB,OAAOX,eAAiBb,KAAKa,gBAExDb,KAAKK,kBAAoBL,KAAKK,kBAAkBmB,QAGhDxB,KAAKK,kBAAoBL,IAEjC,CAOAyB,KAAKC,GAID,OAHA1B,KAAKwB,OAASE,EACdA,EAAOb,eAAiBb,KAAKa,eAC7Ba,EAAOnB,WACAmB,CACX,CAKAC,aAAaC,GACT,OAAO5B,KAAKa,eAAec,aAAaC,EAC5C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AAE,YAC/E,EAAS,EAAQ,QAAU,EAC3B,OAAwB,IAAjB,EAAQ,MAA4B,EAAQ,KACnD,EAAe,EAAQ,cAAgB,EACvC,EAAU,EAAQ,SAAW,EAC7B,EAAU,EAAQ,SAAW,EAC7B,EAAU,EAAQ,SAAW,EAC7B,GAAK,EAAI,KAAK,KAAK,IAAM,EAEzB,EAAc,EACf,EACD,GACC,EACD,EACA0zB,EACA,GACC,GACA,EACD,EACA,GACCA,EACD,EACA,GACC,GACA,EACD,EACA,GACC,EACD,GACC,EACD,EACA,EACA,EACAA,EACA,EACA,EACA,EACA,EACA,GACC,GACA,EACD,EACA,GACC,EACD,GACC,GAGC,EAAc,CAChB,EAAG,GAAI,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,EAAG,GAAI,GAAI,GAAI,GAAI,EAAG,EAAG,GAAI,EAAG,GAAI,EAAG,GAAI,GAAI,GAAI,GAAI,GAAI,EAAG,EAAG,EAAG,EAAG,GAAI,GAAI,EAAG,GAAI,EAAG,EAAG,GAAI,GAAI,EAAG,GAAI,EAAG,GAAI,EAAG,EAAG,EAAG,EAAG,GAAI,EAAG,GAAI,GACxK,GAAI,EAAG,GAAI,GAAI,GAAI,EAAG,GAAI,EAAG,EAAG,GAG9B,EAAsB,CACxB,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,GACA,GAEA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,GACA,IAGE,EAAe,CACjB,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EAEA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,GAgDE,EAAS,CACX,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,E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Ac,KAAK,U,GAEnB,KAAK,oBACA,KAAK,QAAU,EAAQ,CACxB,MAAM,EAAoB,EAAO,iBAC3B,EAAuB,IAAI,EAAkE,EAAE,EAAkB,EAAE,IAAK,EAAkB,EAAE,IAAK,EAAkB,EAAE,KAC3K,EAAc,EAAc,gBAC5B,EAAY,eAAe,KAAK,UAAU,EAAI,EAAqB,EAAG,KAAK,UAAU,EAAI,EAAqB,EAAG,KAAK,UAAU,EAAI,EAAqB,EAC7J,C,KAGI,eAAe,KAAK,SAAS,EAAI,KAAK,mBAAoB,KAAK,SAAS,EAAI,KAAK,mBAAoB,KAAK,SAAS,EAAI,KAAK,oBAGhI,KAAK,qBAGL,GAFA,KAAK,oBAAoB,UAAW,EACpC,EAAW,KAAK,oBACZ,KAAK,0CAA2C,CACpC,KAAK,SAAS,kBAEtB,KAAK,oBAAoB,gBAAgB,EAAqE,GAAG,qBAAqB,KAAK,UAAU,EAAG,KAAK,UAAU,EAAG,KAAK,UAAU,IACzL,KAAK,UAAU,eAAe,EAAG,EAAG,GAE5C,O,iBAIA,EAAqE,GAAG,0BAA0B,KAAK,UAAU,EAAG,KAAK,UAAU,EAAG,KAAK,UAAU,EAAG,G,iFCpCxJ,MAAM,EAAiB,EAAqE,GAAG,OAAO,GACtG,EAAS,iBAAiB,GAE1B,KAAD,6C,6JCFE,KAAK,aAAa,yBAAyB,EAAY,EAAG,EAAY,EAAG,EAAY,E","sources":["webpack://code-cave/./node_modules/@babylonjs/core/Actions/action.js","webpack://code-cave/./node_modules/@babylonjs/core/Actions/condition.js","webpack://code-cave/./node_modules/@babylonjs/core/Actions/directActions.js","webpack://code-cave/./node_modules/@babylonjs/core/Actions/actionManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Actions/directAudioActions.js","webpack://code-cave/./node_modules/@babylonjs/core/Animations/animationKey.js","webpack://code-cave/./node_modules/@babylonjs/core/Animations/animationRange.js","webpack://code-cave/./node_modules/@babylonjs/core/Maths/math.size.js","webpack://code-cave/./node_modules/@babylonjs/core/Animations/animation.js","webpack://code-cave/./node_modules/@babylonjs/core/Actions/interpolateValueAction.js","webpack://code-cave/./node_modules/@babylonjs/core/Animations/runtimeAnimation.js","webpack://code-cave/./node_modules/@babylonjs/core/Bones/bone.js","webpack://code-cave/./node_modules/@babylonjs/core/Animations/animatable.js","webpack://code-cave/./node_modules/@babylonjs/core/Maths/math.path.js","webpack://code-cave/./node_modules/@babylonjs/core/Animations/easing.js","webpack://code-cave/./node_modules/@babylonjs/core/Animations/animationEvent.js","webpack://code-cave/./node_modules/@babylonjs/core/Animations/animationGroup.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/instancedMesh.js","webpack://code-cave/./node_modules/@babylonjs/core/Lights/light.js","webpack://code-cave/./node_modules/@babylonjs/core/assetContainer.js","webpack://code-cave/./node_modules/@babylonjs/core/Audio/audioEngine.js","webpack://code-cave/./node_modules/@babylonjs/core/Audio/sound.js","webpack://code-cave/./node_modules/@babylonjs/core/Audio/soundTrack.js","webpack://code-cave/./node_modules/@babylonjs/core/Audio/audioSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Audio/weightedsound.js","webpack://code-cave/./node_modules/@babylonjs/core/BakedVertexAnimation/bakedVertexAnimationManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/thinTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/baseTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/copyTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/texture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.rawTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/rawTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Behaviors/Cameras/autoRotationBehavior.js","webpack://code-cave/./node_modules/@babylonjs/core/Behaviors/Cameras/bouncingBehavior.js","webpack://code-cave/./node_modules/@babylonjs/core/Behaviors/Cameras/framingBehavior.js","webpack://code-cave/./node_modules/@babylonjs/core/Culling/ray.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/pivotTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/planeBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Behaviors/Meshes/pointerDragBehavior.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/webXRFeaturesManager.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRAbstractFeature.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v1/physicsJoint.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v1/physicsImpostor.js","webpack://code-cave/./node_modules/@babylonjs/core/Loading/sceneLoader.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Enums/nodeMaterialBlockTargets.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/pushMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/nodeMaterialBuildState.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/nodeMaterialBuildStateSharedData.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/nodeMaterialBlockConnectionPoint.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/nodeMaterialDecorator.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/nodeMaterialBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/transformBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Vertex/vertexOutputBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Enums/nodeMaterialBlockConnectionPointMode.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Enums/nodeMaterialSystemValues.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/fragmentOutputBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Input/animatedInputBlockTypes.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Input/inputBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/currentScreenBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Particle/particleTextureBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Particle/particleRampGradientBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Particle/particleBlendMultiplyBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/effectFallbacks.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/postprocess.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/renderTargetWrapper.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGL/webGLRenderTargetWrapper.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.renderTarget.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/postProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Enums/nodeMaterialModes.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/vectorMergerBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/remapBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/multiplyBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/EmitterTypes/boxParticleEmitter.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/EmitterTypes/coneParticleEmitter.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/EmitterTypes/cylinderParticleEmitter.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/EmitterTypes/hemisphericParticleEmitter.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/EmitterTypes/IParticleEmitterType.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/EmitterTypes/pointParticleEmitter.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/EmitterTypes/sphereParticleEmitter.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/EmitterTypes/customParticleEmitter.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/EmitterTypes/meshParticleEmitter.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/EmitterTypes/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/baseParticleSystem.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/colorSplitterBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.renderTargetCube.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/effectRenderer.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/pass.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/dumpTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/renderTargetTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Procedurals/proceduralTextureSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/procedural.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Procedurals/proceduralTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/trigonometryBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/nodeMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/icoSphereBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRHandTracking.js","webpack://code-cave/./node_modules/@babylonjs/core/Behaviors/Meshes/handConstraintBehavior.js","webpack://code-cave/./node_modules/@babylonjs/core/Bones/boneIKController.js","webpack://code-cave/./node_modules/@babylonjs/core/Bones/boneLookController.js","webpack://code-cave/./node_modules/@babylonjs/core/Bones/skeleton.js","webpack://code-cave/./node_modules/@babylonjs/core/Bones/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Buffers/storageBuffer.js","webpack://code-cave/./node_modules/@babylonjs/core/Buffers/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/BaseCameraMouseWheelInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/BaseCameraPointersInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/cameraInputsManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/gamepad.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/arcRotateCameraGamepadInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/arcRotateCameraKeyboardMoveInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/arcRotateCameraMouseWheelInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/arcRotateCameraPointersInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/arcRotateCameraInputsManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/arcRotateCameraVRDeviceOrientationInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/flyCameraKeyboardInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/flyCameraMouseInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/followCameraKeyboardMoveInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/followCameraMouseWheelInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/followCameraPointersInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/freeCameraKeyboardMoveInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/freeCameraMouseInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/freeCameraMouseWheelInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/freeCameraTouchInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/freeCameraInputsManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/freeCameraDeviceOrientationInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/freeCameraGamepadInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/virtualJoystick.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/Controllers/poseEnabledController.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/xboxGamepad.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/dualShockGamepad.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/freeCameraVirtualJoystickInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Inputs/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/targetCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/freeCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/touchCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/arcRotateCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/deviceOrientationCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/flyCameraInputsManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/flyCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/followCameraInputsManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/followCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/gamepadManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/gamepadSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/universalCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/gamepadCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/passCube.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/passPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/anaglyphPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/RigModes/stereoscopicAnaglyphRigMode.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Stereoscopic/anaglyphArcRotateCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Stereoscopic/anaglyphFreeCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Stereoscopic/anaglyphGamepadCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Stereoscopic/anaglyphUniversalCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/stereoscopicInterlace.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/stereoscopicInterlacePostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/RigModes/stereoscopicRigMode.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Stereoscopic/stereoscopicArcRotateCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Stereoscopic/stereoscopicFreeCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Stereoscopic/stereoscopicGamepadCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Stereoscopic/stereoscopicUniversalCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/Stereoscopic/stereoscopicScreenUniversalCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/VR/vrCameraMetrics.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/vrDistortionCorrection.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/vrDistortionCorrectionPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/vrMultiviewToSingleview.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/MultiviewRenderTarget.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.multiview.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/RigModes/vrRigMode.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/vrMultiviewToSingleviewPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/VR/vrDeviceOrientationArcRotateCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/VR/vrDeviceOrientationFreeCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/VR/vrDeviceOrientationGamepadCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Lights/hemisphericLight.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/RigModes/webVRRigMode.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.webVR.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/VR/webVRCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/Controllers/webVRController.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/prePassConfiguration.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/materialFlags.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/decalFragmentDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/defaultFragmentDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/sceneUboDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/meshUboDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/defaultUboDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/prePassDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/lightFragmentDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/lightUboDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowsFragmentFunctions.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/imageProcessingFunctions.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/bumpFragmentMainFunctions.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/fogFragmentDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/decalFragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/depthPrePass.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/lightFragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/lightVxFragmentDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/lightVxUboDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertexGlobalDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertexDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/bakedVertexAnimation.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/prePassVertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/vertexColorMixing.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pointCloudVertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/default.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/materialPluginManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/materialPluginBase.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/material.detailMapConfiguration.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/standardMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.dynamicTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/dynamicTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/imageProcessing.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/imageProcessingPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/webXRLayerWrapper.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/webXRRenderTargetTextureProvider.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/webXRWebGLLayer.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/webXRManagedOutputCanvas.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/native/nativeXRRenderTarget.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/webXRSessionManager.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/webXRTypes.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/cylinderBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/torusBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/groundMesh.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/groundBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/VR/vrExperienceHelper.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/VR/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/RigModes/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Collisions/collider.js","webpack://code-cave/./node_modules/@babylonjs/core/Collisions/collisionCoordinator.js","webpack://code-cave/./node_modules/@babylonjs/core/Collisions/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Compute/computeEffect.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.computeShader.js","webpack://code-cave/./node_modules/@babylonjs/core/Compute/computeShader.js","webpack://code-cave/./node_modules/@babylonjs/core/Compute/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Culling/Octrees/octreeBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Culling/Octrees/octree.js","webpack://code-cave/./node_modules/@babylonjs/core/Culling/Octrees/octreeSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Culling/Octrees/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Culling/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/utilityLayerRenderer.js","webpack://code-cave/./node_modules/@babylonjs/core/Gizmos/gizmo.js","webpack://code-cave/./node_modules/@babylonjs/core/Debug/axesViewer.js","webpack://code-cave/./node_modules/@babylonjs/core/Gizmos/axisDragGizmo.js","webpack://code-cave/./node_modules/@babylonjs/core/Debug/boneAxesViewer.js","webpack://code-cave/./node_modules/@babylonjs/core/Debug/debugLayer.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/boxBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/ribbonBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/torusKnotBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/sphereBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/capsuleBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/discBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/tiledPlaneBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/shaderMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/color.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/color.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/linesMesh.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/linesBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/polygonMesh.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/polygonBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/shapeBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/latheBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/tubeBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/polyhedronBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/decalBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Maths/math.isovector.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/geodesicMesh.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/geodesicBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/goldbergMesh.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/goldbergBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/textBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/meshBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Debug/physicsViewer.js","webpack://code-cave/./node_modules/@babylonjs/core/Debug/rayHelper.js","webpack://code-cave/./node_modules/@babylonjs/core/Debug/skeletonViewer.js","webpack://code-cave/./node_modules/@babylonjs/core/Debug/ISkeletonViewer.js","webpack://code-cave/./node_modules/@babylonjs/core/Debug/directionalLightFrustumViewer.js","webpack://code-cave/./node_modules/@babylonjs/core/Debug/index.js","webpack://code-cave/./node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceTypes.js","webpack://code-cave/./node_modules/@babylonjs/core/DeviceInput/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/constants.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/nullEngine.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.debugging.js","webpack://code-cave/./node_modules/@babylonjs/core/Instrumentation/timeToken.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.query.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.videoTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.multiRender.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.cubeTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.textureSampler.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.views.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/rgbdTextureTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/HighDynamicRange/cubemapToSphericalPolynomial.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/baseTexture.polynomial.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/rgbdEncode.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/environmentTextureTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/codeStringParsingTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Processors/shaderCodeInliner.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Native/nativePipelineContext.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Native/nativeRenderTargetWrapper.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Native/nativeHardwareTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/nativeEngine.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Native/validatedNativeDataStream.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Native/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuConstants.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuShaderProcessor.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuPipelineContext.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuShaderProcessingContext.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuShaderProcessorsGLSL.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bonesDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bonesVertex.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bakedVertexAnimationDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bakedVertexAnimation.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneFragment.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneFragmentDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneVertex.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneVertexDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/instancesDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/instancesVertex.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/meshUboDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertex.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertexDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertexGlobal.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertexGlobalDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/sceneUboDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuShaderProcessorsWGSL.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuHardwareTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuTextureHelper.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/WebGPU/webgpuDataBuffer.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuBufferManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuRenderPassWrapper.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuCacheSampler.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuCacheRenderPipeline.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuCacheRenderPipelineTree.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuStencilStateComposer.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuDepthCullingState.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/externalTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuMaterialContext.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuDrawContext.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuCacheBindGroups.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/clearQuad.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/clearQuad.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuClearQuad.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuBundleList.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuQuerySet.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuTimestampQuery.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuOcclusionQuery.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuTintWASM.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuSnapshotRendering.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/postprocess.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/webgpuEngine.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.alpha.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuComputeContext.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuComputePipelineContext.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.computeShader.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.cubeTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.debugging.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.dynamicBuffer.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.dynamicTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.externalTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuExternalTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.multiRender.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.query.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.rawTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/webgpuRenderTargetWrapper.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.readTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.renderTarget.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.renderTargetCube.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.textureSampler.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.storageBuffer.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.uniformBuffer.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/engine.videoTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGPU/Extensions/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/IPipelineContext.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/ICanvas.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/engineFeatures.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/engineFactory.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/IMaterialContext.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/IDrawContext.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Processors/iShaderProcessor.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Events/clipboardEvents.js","webpack://code-cave/./node_modules/@babylonjs/core/Events/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/Controllers/daydreamController.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/Controllers/gearVRController.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/Controllers/genericController.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/Controllers/oculusTouchController.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/Controllers/viveController.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/Controllers/windowsMotionController.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/Controllers/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Gamepads/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Gizmos/axisScaleGizmo.js","webpack://code-cave/./node_modules/@babylonjs/core/Gizmos/boundingBoxGizmo.js","webpack://code-cave/./node_modules/@babylonjs/core/Gizmos/planeRotationGizmo.js","webpack://code-cave/./node_modules/@babylonjs/core/Gizmos/rotationGizmo.js","webpack://code-cave/./node_modules/@babylonjs/core/Gizmos/planeDragGizmo.js","webpack://code-cave/./node_modules/@babylonjs/core/Gizmos/positionGizmo.js","webpack://code-cave/./node_modules/@babylonjs/core/Gizmos/scaleGizmo.js","webpack://code-cave/./node_modules/@babylonjs/core/Gizmos/gizmoManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Lights/spotLight.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/cubeTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/backgroundFragmentDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/backgroundUboDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/background.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/backgroundVertexDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/background.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Background/backgroundMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Helpers/environmentHelper.js","webpack://code-cave/./node_modules/@babylonjs/core/Helpers/textureDome.js","webpack://code-cave/./node_modules/@babylonjs/core/Helpers/photoDome.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/brdfTextureTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/PBR/pbrBRDFConfiguration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrFragmentDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrFragmentSamplersDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/subSurfaceScatteringFunctions.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrHelperFunctions.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/hdrFilteringFunctions.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrDirectLightingFunctions.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrIBLFunctions.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockAlbedoOpacity.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockReflectivity.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockAmbientOcclusion.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockAlphaFresnel.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockAnisotropic.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockReflection.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockSheen.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockClearcoat.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockIridescence.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockSubSurface.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockNormalGeometric.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockNormalFinal.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockLightmapInit.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockGeometryInfo.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockReflectance0.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockReflectance.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockDirectLighting.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockFinalLitComponents.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockFinalUnlitComponents.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockFinalColorComposition.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBlockImageProcessing.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrDebug.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/pbr.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrVertexDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/pbr.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/PBR/pbrClearCoatConfiguration.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/PBR/pbrIridescenceConfiguration.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/PBR/pbrAnisotropicConfiguration.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/PBR/pbrSheenConfiguration.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/PBR/pbrSubSurfaceConfiguration.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/PBR/pbrBaseMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/PBR/pbrMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/dds.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Loaders/ddsTextureLoader.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Loaders/envTextureLoader.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/khronosTextureContainer.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/workerPool.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/ktx2decoderTypes.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/khronosTextureContainer2.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Loaders/ktxTextureLoader.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/webXRCamera.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/webXRExperienceHelper.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/motionController/webXRControllerComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/motionController/webXRAbstractMotionController.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/motionController/webXRGenericMotionController.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/motionController/webXRProfiledMotionController.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/motionController/webXRMotionControllerManager.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/webXRInputSource.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/webXRInput.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRControllerPointerSelection.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/subMesh.project.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRNearInteraction.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/webXREnterExitUI.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/timer.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRControllerTeleportation.js","webpack://code-cave/./node_modules/@babylonjs/core/Helpers/sceneHelpers.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/webXRDefaultExperience.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/videoTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Helpers/videoDome.js","webpack://code-cave/./node_modules/@babylonjs/core/Helpers/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Instrumentation/engineInstrumentation.js","webpack://code-cave/./node_modules/@babylonjs/core/Instrumentation/sceneInstrumentation.js","webpack://code-cave/./node_modules/@babylonjs/core/Instrumentation/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/glowMapGeneration.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/glowMapGeneration.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Layers/effectLayer.js","webpack://code-cave/./node_modules/@babylonjs/core/Layers/effectLayerSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/glowMapMerge.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/glowMapMerge.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Layers/glowLayer.js","webpack://code-cave/./node_modules/@babylonjs/core/Layers/layerSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/glowBlurPostProcess.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Layers/highlightLayer.js","webpack://code-cave/./node_modules/@babylonjs/core/Layers/layer.js","webpack://code-cave/./node_modules/@babylonjs/core/Layers/index.js","webpack://code-cave/./node_modules/@babylonjs/core/LensFlares/lensFlare.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/lensFlare.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/lensFlare.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/LensFlares/lensFlareSystem.js","webpack://code-cave/./node_modules/@babylonjs/core/LensFlares/lensFlareSystemSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/LensFlares/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/bayerDitherFunctions.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapFragmentExtraDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexNormalBias.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexMetric.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapFragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/shadowMap.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/sceneVertexDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/meshVertexDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapUboDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexExtraDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/shadowMap.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/depthBoxBlur.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Lights/Shadows/shadowGenerator.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapFragmentSoftTransparentShadow.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/depth.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/depth.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/depthRenderer.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/minmaxRedux.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/minMaxReducer.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/depthReducer.js","webpack://code-cave/./node_modules/@babylonjs/core/Lights/Shadows/cascadedShadowGenerator.js","webpack://code-cave/./node_modules/@babylonjs/core/Lights/Shadows/shadowGeneratorSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Lights/Shadows/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Lights/pointLight.js","webpack://code-cave/./node_modules/@babylonjs/core/Lights/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Loading/loadingScreen.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/HighDynamicRange/panoramaToCubemap.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/HighDynamicRange/hdr.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/hdrFiltering.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/hdrFiltering.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Filtering/hdrFiltering.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/hdrCubeTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Morph/morphTarget.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/rawTexture2DArray.js","webpack://code-cave/./node_modules/@babylonjs/core/Morph/morphTargetManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/physicsRaycastResult.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v1/physicsEngine.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v1/Plugins/cannonJSPlugin.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v1/Plugins/oimoJSPlugin.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v1/Plugins/ammoJSPlugin.js","webpack://code-cave/./node_modules/@babylonjs/core/Probes/reflectionProbe.js","webpack://code-cave/./node_modules/@babylonjs/core/Loading/Plugins/babylonFileLoader.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/iEffectFallbacks.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/fresnelParameters.js","webpack://code-cave/./node_modules/@babylonjs/core/Loading/Plugins/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Loading/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Background/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Occlusion/occlusionMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/PBR/pbrBaseSimpleMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/PBR/pbrMetallicRoughnessMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/PBR/pbrSpecularGlossinessMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/PBR/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/colorGradingTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/equiRectangularCubeTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/htmlElementTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/internalTextureLoader.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/tga.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Loaders/tgaTextureLoader.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Loaders/hdrTextureLoader.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/basis.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Loaders/basisTextureLoader.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Loaders/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/multiRenderTarget.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Packer/frame.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Packer/packer.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Packer/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Procedurals/customProceduralTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/noise.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Procedurals/noiseProceduralTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/Procedurals/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/rawCubeTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/rawTexture3D.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/refractionTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/thinRenderTargetTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Enums/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/nodeMaterialConnectionPointCustomObject.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Vertex/bonesBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Vertex/instancesBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Vertex/morphTargetsBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Vertex/lightInformationBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Vertex/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/imageProcessingBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/TBNBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/perturbNormalBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/discardBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/frontFacingBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/derivativeBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/fragCoordBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/screenSizeBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/screenSpaceBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/twirlBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/heightToNormalBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/fragDepthBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/shadowMapBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Fragment/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/fogBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/lightBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/imageSourceBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/textureBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/reflectionTextureBaseBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/reflectionTextureBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/sceneDepthBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/clipPlanesBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Dual/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/Input/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/addBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/crossBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/customBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/dotBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/colorMergerBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/vectorSplitterBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/lerpBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/stepBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/divideBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/subtractBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/oneMinusBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/viewDirectionBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/fresnelBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/maxBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/negateBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/minBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/distanceBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/lengthBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/powBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/randomNumberBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/arcTan2Block.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/smoothStepBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/reciprocalBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/replaceColorBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/posterizeBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/waveBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/gradientBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/nLerpBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/worleyNoise3DBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/simplexPerlin3DBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/normalBlendBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/rotate2dBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/reflectBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/refractBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/sheenBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/desaturateBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/anisotropyBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/reflectionBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/iridescenceBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/clearCoatBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/refractionBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/subSurfaceBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/pbrMetallicRoughnessBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/PBR/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/modBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/matrixBuilderBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/conditionalBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/cloudBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/voronoiNoiseBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/elbowBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/triPlanarBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/biPlanarBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/meshAttributeExistsBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/matrixDeterminantBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/matrixTransposeBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/curveBlock.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Blocks/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/shadowDepthWrapper.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Optimizers/nodeMaterialOptimizer.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/Optimizers/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Node/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/material.decalMapConfiguration.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/materialPluginFactoryExport.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/greasedLinePluginMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/standardMaterial.decalMap.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/PBR/pbrMaterial.decalMap.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/abstractMesh.decalMap.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/material.decalMap.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Maths/math.polar.js","webpack://code-cave/./node_modules/@babylonjs/core/Maths/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Compression/dracoCompression.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Compression/meshoptCompression.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Compression/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/csg.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/meshUVSpaceRenderer.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/meshUVSpaceRenderer.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/meshUVSpaceRenderer.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/trailMesh.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/meshSimplification.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/greasedLineMesh.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/meshSimplificationSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/greasedLineTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/Builders/greasedLineBuilder.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/thinInstanceMesh.js","webpack://code-cave/./node_modules/@babylonjs/core/Navigation/INavigationEngine.js","webpack://code-cave/./node_modules/@babylonjs/core/Navigation/Plugins/recastJSPlugin.js","webpack://code-cave/./node_modules/@babylonjs/core/Offline/database.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/uniformBufferEffectCommonAccessor.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/gpuUpdateParticles.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/gpuUpdateParticles.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/webgl2ParticleSystem.js","webpack://code-cave/./node_modules/@babylonjs/core/ShadersWGSL/gpuUpdateParticles.compute.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/particle.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/particleSystem.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/gpuParticleSystem.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/particleSystemSet.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/particleHelper.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/solidParticle.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/solidParticleSystem.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/cloudPoint.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/pointsCloudSystem.js","webpack://code-cave/./node_modules/@babylonjs/core/Particles/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v1/physicsEngineComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v1/IPhysicsEnginePlugin.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v1/Plugins/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v1/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v2/physicsEngine.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v2/physicsBody.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v2/IPhysicsEnginePlugin.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v2/physicsShape.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v2/physicsConstraint.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v2/physicsMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v2/physicsAggregate.js","webpack://code-cave/./node_modules/@babylonjs/core/Physics/v2/Plugins/havokPlugin.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/postProcessRenderEffect.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/geometryBufferRenderer.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/motionBlurPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/screenSpaceReflectionPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/filter.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/filterPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/fxaa.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/fxaa.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/fxaaPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/grain.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/grainPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/highlights.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/highlightsPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/lensRenderingPipeline.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/ssao2Configuration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ssao2.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ssaoCombine.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/ssao2RenderingPipeline.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ssao.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/ssaoRenderingPipeline.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/screenSpaceReflectionsConfiguration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/screenSpaceReflection.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/standard.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/standardRenderingPipeline.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/screenSpaceReflections2Configuration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/screenSpaceRayTrace.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/ssrRenderingPipeline.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/index.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/RenderPipeline/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/tonemap.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/tonemapPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/volumetricLightScattering.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/volumetricLightScatteringPass.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/volumetricLightScatteringPass.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/volumetricLightScatteringPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/screenSpaceCurvature.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/screenSpaceCurvaturePostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/boundingBoxRendererUboDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/boundingBoxRenderer.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/boundingBoxRendererVertexDeclaration.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/boundingBoxRenderer.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/boundingBoxRenderer.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/depthRendererSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/oitFinal.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/oitBackBlend.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/depthPeelingRenderer.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/depthPeelingSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/line.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/line.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/edgesRenderer.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/prePassRenderer.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/prePassRendererSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/fibonacci.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/diffusionProfile.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/subSurfaceScattering.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/subSurfaceScatteringPostProcess.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/subSurfaceConfiguration.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/subSurfaceSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/outline.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/outline.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/outlineRenderer.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderingObject.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderingTextures.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderingTargetRenderer.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderingObjectCustomParticles.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/copyTextureToTexture.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/copyTextureToTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderingDepthTextureCopy.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/fluidRenderingParticleDepth.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/fluidRenderingParticleDepth.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/fluidRenderingParticleThickness.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/fluidRenderingParticleThickness.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/fluidRenderingParticleDiffuse.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/fluidRenderingParticleDiffuse.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/fluidRenderingBilateralBlur.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/fluidRenderingStandardBlur.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/fluidRenderingRender.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/fluidRenderer/fluidRenderer.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/fluidRenderer/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Sprites/thinSprite.js","webpack://code-cave/./node_modules/@babylonjs/core/Sprites/sprite.js","webpack://code-cave/./node_modules/@babylonjs/core/Sprites/ISprites.js","webpack://code-cave/./node_modules/@babylonjs/core/Sprites/spriteSceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/sprites.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/ShadersInclude/imageProcessingCompatibility.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/sprites.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Sprites/spriteRenderer.js","webpack://code-cave/./node_modules/@babylonjs/core/Sprites/spriteManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/spriteMap.fragment.js","webpack://code-cave/./node_modules/@babylonjs/core/Shaders/spriteMap.vertex.js","webpack://code-cave/./node_modules/@babylonjs/core/Sprites/spriteMap.js","webpack://code-cave/./node_modules/@babylonjs/core/Sprites/spritePackedManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Sprites/index.js","webpack://code-cave/./node_modules/@babylonjs/core/States/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/assetsManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/deferred.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/meshExploder.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/filesInput.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/HighDynamicRange/index.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/observable.extensions.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/sceneOptimizer.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/sceneSerializer.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/videoRecorder.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/screenshotTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/iInspectable.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/fileRequest.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/customAnimationFrameRequester.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/interfaces/screenshotSize.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/dataReader.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/dataStorage.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/sceneRecorder.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/trajectoryClassifier.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/reflector.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/pressureObserverWrapper.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/PerformanceViewer/dynamicFloat32Array.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/PerformanceViewer/performanceViewerCollector.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/PerformanceViewer/performanceViewerCollectionStrategies.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/observableCoroutine.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/index.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRHitTestLegacy.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRAnchorSystem.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRPlaneDetector.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRBackgroundRemover.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRControllerPhysics.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRHitTest.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRFeaturePointSystem.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRMeshDetector.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRImageTracking.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRDOMOverlay.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRControllerMovement.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRLightEstimation.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRWalkingLocomotion.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/WebXRSpaceWarp.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/features/index.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/motionController/webXRMicrosoftMixedRealityController.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/motionController/webXROculusTouchMotionController.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/native/nativeXRFrame.js","webpack://code-cave/./node_modules/@babylonjs/core/index.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/glTFValidation.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/glTFFileLoader.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/native/index.js","webpack://code-cave/./node_modules/@babylonjs/core/XR/index.js","webpack://code-cave/./node_modules/@babylonjs/core/types.js","webpack://code-cave/./node_modules/@babylonjs/core/Compat/index.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/1.0/glTFLoaderUtils.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/1.0/glTFLoaderInterfaces.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/1.0/glTFLoader.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/1.0/glTFBinaryExtension.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/1.0/glTFMaterialsCommonExtension.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/1.0/index.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/glTFLoaderAnimation.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/glTFLoader.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/glTFLoaderExtension.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/EXT_lights_image_based.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/glTFLoaderInterfaces.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/EXT_mesh_gpu_instancing.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/EXT_meshopt_compression.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/EXT_texture_webp.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_draco_mesh_compression.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_lights_punctual.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_unlit.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_clearcoat.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_iridescence.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_anisotropy.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_emissive_strength.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_sheen.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_specular.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_ior.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_variants.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_transmission.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_translucency.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_materials_volume.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_mesh_quantization.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_texture_basisu.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_texture_transform.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_xmp_json_ld.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_animation_pointer.data.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/KHR_animation_pointer.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/MSFT_audio_emitter.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/MSFT_lod.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/MSFT_minecraftMesh.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/MSFT_sRGBFactors.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/ExtrasAsMetadata.js","webpack://code-cave/./node_modules/@babylonjs/core/Buffers/buffer.js","webpack://code-cave/./node_modules/@babylonjs/core/Cameras/camera.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/Extensions/index.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/2.0/index.js","webpack://code-cave/./node_modules/@babylonjs/loaders/glTF/index.js","webpack://code-cave/./src/workers/babylon.worker.ts","webpack://code-cave/./node_modules/@babylonjs/core/Actions/abstractActionManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Actions/actionEvent.js","webpack://code-cave/./node_modules/@babylonjs/core/Buffers/dataBuffer.js","webpack://code-cave/./node_modules/@babylonjs/core/Collisions/intersectionInfo.js","webpack://code-cave/./node_modules/@babylonjs/core/Collisions/meshCollisionData.js","webpack://code-cave/./node_modules/@babylonjs/core/Collisions/pickingInfo.js","webpack://code-cave/./node_modules/@babylonjs/core/Compat/compatibilityOptions.js","webpack://code-cave/./node_modules/@babylonjs/core/Culling/boundingBox.js","webpack://code-cave/./node_modules/@babylonjs/core/Culling/boundingInfo.js","webpack://code-cave/./node_modules/@babylonjs/core/Culling/boundingSphere.js","webpack://code-cave/./node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceEnums.js","webpack://code-cave/./node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceSource.js","webpack://code-cave/./node_modules/@babylonjs/core/DeviceInput/eventFactory.js","webpack://code-cave/./node_modules/@babylonjs/core/DeviceInput/nativeDeviceInputSystem.js","webpack://code-cave/./node_modules/@babylonjs/core/DeviceInput/webDeviceInputSystem.js","webpack://code-cave/./node_modules/@babylonjs/core/DeviceInput/internalDeviceSourceManager.js","webpack://code-cave/./node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceSourceManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.alpha.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.dynamicBuffer.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.readTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Extensions/engine.uniformBuffer.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Processors/shaderCodeNode.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Processors/shaderCodeCursor.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Processors/shaderCodeConditionNode.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Processors/shaderCodeTestNode.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Processors/Expressions/shaderDefineExpression.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineIsDefinedOperator.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineAndOperator.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineArithmeticOperator.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/Processors/shaderProcessor.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGL/webGL2ShaderProcessors.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGL/webGLHardwareTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGL/webGLPipelineContext.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/WebGL/webGLShaderProcessors.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/engine.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/engineStore.js","webpack://code-cave/./node_modules/@babylonjs/core/Engines/shaderStore.js","webpack://code-cave/./node_modules/@babylonjs/core/Events/deviceInputEvents.js","webpack://code-cave/./node_modules/@babylonjs/core/Events/keyboardEvents.js","webpack://code-cave/./node_modules/@babylonjs/core/Events/pointerEvents.js","webpack://code-cave/./node_modules/@babylonjs/core/Inputs/pointerPickingConfiguration.js","webpack://code-cave/./node_modules/@babylonjs/core/Inputs/scene.inputManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Lights/lightConstants.js","webpack://code-cave/./node_modules/@babylonjs/core/Loading/sceneLoaderFlags.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/internalTexture.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/Textures/textureSampler.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/clipPlaneMaterialHelper.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/colorCurves.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/drawWrapper.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/effect.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/imageProcessingConfiguration.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/materialStencilState.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/material.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/materialDefines.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/materialHelper.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/materialPluginEvent.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/multiMaterial.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/shaderLanguage.js","webpack://code-cave/./node_modules/@babylonjs/core/Materials/uniformBuffer.js","webpack://code-cave/./node_modules/@babylonjs/core/Maths/math.axis.js","webpack://code-cave/./node_modules/@babylonjs/core/Maths/math.color.js","webpack://code-cave/./node_modules/@babylonjs/core/Maths/math.constants.js","webpack://code-cave/./node_modules/@babylonjs/core/Maths/math.frustum.js","webpack://code-cave/./node_modules/@babylonjs/core/Maths/math.functions.js","webpack://code-cave/./node_modules/@babylonjs/core/Maths/math.plane.js","webpack://code-cave/./node_modules/@babylonjs/core/Maths/math.scalar.js","webpack://code-cave/./node_modules/@babylonjs/core/Maths/math.viewport.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/WebGL/webGLDataBuffer.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/abstractMesh.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/geometry.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/mesh.vertexData.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/meshLODLevel.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/subMesh.js","webpack://code-cave/./node_modules/@babylonjs/core/Meshes/transformNode.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/andOrNotEvaluator.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/arrayTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/coroutine.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/decorators.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/deepCopier.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/devTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/domManagement.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/error.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/fileTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/instantiationTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/filesInputStore.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/guid.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/logger.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/observable.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/perfCounter.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/performanceMonitor.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/precisionDate.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/retryStrategy.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/smartArray.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/stringDictionary.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/stringTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/tags.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/timingTools.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/tools.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/typeStore.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/uniqueIdGenerator.js","webpack://code-cave/./node_modules/@babylonjs/core/Misc/webRequest.js","webpack://code-cave/./node_modules/@babylonjs/core/PostProcesses/postProcessManager.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/renderingGroup.js","webpack://code-cave/./node_modules/@babylonjs/core/Rendering/renderingManager.js","webpack://code-cave/./node_modules/@babylonjs/core/States/alphaCullingState.js","webpack://code-cave/./node_modules/@babylonjs/core/States/depthCullingState.js","webpack://code-cave/./node_modules/@babylonjs/core/States/stencilState.js","webpack://code-cave/./node_modules/@babylonjs/core/States/stencilStateComposer.js","webpack://code-cave/./node_modules/@babylonjs/core/abstractScene.js","webpack://code-cave/./node_modules/@babylonjs/core/node.js","webpack://code-cave/./node_modules/@babylonjs/core/sceneComponent.js","webpack://code-cave/./node_modules/@babylonjs/core/tslib.es6.js","webpack://code-cave/webpack/bootstrap","webpack://code-cave/webpack/runtime/chunk loaded","webpack://code-cave/webpack/runtime/define property getters","webpack://code-cave/webpack/runtime/ensure chunk","webpack://code-cave/webpack/runtime/get javascript chunk filename","webpack://code-cave/webpack/runtime/get mini-css chunk filename","webpack://code-cave/webpack/runtime/hasOwnProperty shorthand","webpack://code-cave/webpack/runtime/publicPath","webpack://code-cave/webpack/runtime/importScripts chunk loading","webpack://code-cave/webpack/runtime/startup chunk dependencies","webpack://code-cave/webpack/startup"],"sourcesContent":["import { Observable } from \"../Misc/observable.js\";\nimport { Vector2, Vector3 } from \"../Maths/math.vector.js\";\nimport { Color3, Color4 } from \"../Maths/math.color.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\n/**\n * The action to be carried out following a trigger\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#available-actions\n */\nexport class Action {\n /**\n * Creates a new Action\n * @param triggerOptions the trigger, with or without parameters, for the action\n * @param condition an optional determinant of action\n */\n constructor(\n /** the trigger, with or without parameters, for the action */\n triggerOptions, condition) {\n this.triggerOptions = triggerOptions;\n /**\n * An event triggered prior to action being executed.\n */\n this.onBeforeExecuteObservable = new Observable();\n if (triggerOptions.parameter) {\n this.trigger = triggerOptions.trigger;\n this._triggerParameter = triggerOptions.parameter;\n }\n else if (triggerOptions.trigger) {\n this.trigger = triggerOptions.trigger;\n }\n else {\n this.trigger = triggerOptions;\n }\n this._nextActiveAction = this;\n this._condition = condition;\n }\n /**\n * Internal only\n * @internal\n */\n _prepare() { }\n /**\n * Gets the trigger parameter\n * @returns the trigger parameter\n */\n getTriggerParameter() {\n return this._triggerParameter;\n }\n /**\n * Sets the trigger parameter\n * @param value defines the new trigger parameter\n */\n setTriggerParameter(value) {\n this._triggerParameter = value;\n }\n /**\n * Internal only - Returns if the current condition allows to run the action\n * @internal\n */\n _evaluateConditionForCurrentFrame() {\n const condition = this._condition;\n if (!condition) {\n return true;\n }\n const currentRenderId = this._actionManager.getScene().getRenderId();\n // We cache the current evaluation for the current frame\n if (condition._evaluationId !== currentRenderId) {\n condition._evaluationId = currentRenderId;\n condition._currentResult = condition.isValid();\n }\n return condition._currentResult;\n }\n /**\n * Internal only - executes current action event\n * @internal\n */\n _executeCurrent(evt) {\n const isConditionValid = this._evaluateConditionForCurrentFrame();\n if (!isConditionValid) {\n return;\n }\n this.onBeforeExecuteObservable.notifyObservers(this);\n this._nextActiveAction.execute(evt);\n this.skipToNextActiveAction();\n }\n /**\n * Execute placeholder for child classes\n * @param evt optional action event\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n execute(evt) { }\n /**\n * Skips to next active action\n */\n skipToNextActiveAction() {\n if (this._nextActiveAction._child) {\n if (!this._nextActiveAction._child._actionManager) {\n this._nextActiveAction._child._actionManager = this._actionManager;\n }\n this._nextActiveAction = this._nextActiveAction._child;\n }\n else {\n this._nextActiveAction = this;\n }\n }\n /**\n * Adds action to chain of actions, may be a DoNothingAction\n * @param action defines the next action to execute\n * @returns The action passed in\n * @see https://www.babylonjs-playground.com/#1T30HR#0\n */\n then(action) {\n this._child = action;\n action._actionManager = this._actionManager;\n action._prepare();\n return action;\n }\n /**\n * Internal only\n * @internal\n */\n _getProperty(propertyPath) {\n return this._actionManager._getProperty(propertyPath);\n }\n /**\n * @internal\n */\n _getEffectiveTarget(target, propertyPath) {\n return this._actionManager._getEffectiveTarget(target, propertyPath);\n }\n /**\n * Serialize placeholder for child classes\n * @param parent of child\n * @returns the serialized object\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n serialize(parent) { }\n /**\n * Internal only called by serialize\n * @internal\n */\n _serialize(serializedAction, parent) {\n const serializationObject = {\n type: 1,\n children: [],\n name: serializedAction.name,\n properties: serializedAction.properties || [],\n };\n // Serialize child\n if (this._child) {\n this._child.serialize(serializationObject);\n }\n // Check if \"this\" has a condition\n if (this._condition) {\n const serializedCondition = this._condition.serialize();\n serializedCondition.children.push(serializationObject);\n if (parent) {\n parent.children.push(serializedCondition);\n }\n return serializedCondition;\n }\n if (parent) {\n parent.children.push(serializationObject);\n }\n return serializationObject;\n }\n}\n/**\n * Internal only\n * @internal\n */\nAction._SerializeValueAsString = (value) => {\n if (typeof value === \"number\") {\n return value.toString();\n }\n if (typeof value === \"boolean\") {\n return value ? \"true\" : \"false\";\n }\n if (value instanceof Vector2) {\n return value.x + \", \" + value.y;\n }\n if (value instanceof Vector3) {\n return value.x + \", \" + value.y + \", \" + value.z;\n }\n if (value instanceof Color3) {\n return value.r + \", \" + value.g + \", \" + value.b;\n }\n if (value instanceof Color4) {\n return value.r + \", \" + value.g + \", \" + value.b + \", \" + value.a;\n }\n return value; // string\n};\n/**\n * Internal only\n * @internal\n */\nAction._GetTargetProperty = (target) => {\n return {\n name: \"target\",\n targetType: target._isMesh\n ? \"MeshProperties\"\n : target._isLight\n ? \"LightProperties\"\n : target._isCamera\n ? \"CameraProperties\"\n : target._isMaterial\n ? \"MaterialProperties\"\n : \"SceneProperties\",\n value: target._isScene ? \"Scene\" : target.name,\n };\n};\nRegisterClass(\"BABYLON.Action\", Action);\n//# sourceMappingURL=action.js.map","import { Action } from \"./action.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\n/**\n * A Condition applied to an Action\n */\nexport class Condition {\n /**\n * Creates a new Condition\n * @param actionManager the manager of the action the condition is applied to\n */\n constructor(actionManager) {\n this._actionManager = actionManager;\n }\n /**\n * Check if the current condition is valid\n * @returns a boolean\n */\n isValid() {\n return true;\n }\n /**\n * @internal\n */\n _getProperty(propertyPath) {\n return this._actionManager._getProperty(propertyPath);\n }\n /**\n * @internal\n */\n _getEffectiveTarget(target, propertyPath) {\n return this._actionManager._getEffectiveTarget(target, propertyPath);\n }\n /**\n * Serialize placeholder for child classes\n * @returns the serialized object\n */\n serialize() { }\n /**\n * @internal\n */\n _serialize(serializedCondition) {\n return {\n type: 2,\n children: [],\n name: serializedCondition.name,\n properties: serializedCondition.properties,\n };\n }\n}\n/**\n * Defines specific conditional operators as extensions of Condition\n */\nexport class ValueCondition extends Condition {\n /**\n * returns the number for IsEqual\n */\n static get IsEqual() {\n return ValueCondition._IsEqual;\n }\n /**\n * Returns the number for IsDifferent\n */\n static get IsDifferent() {\n return ValueCondition._IsDifferent;\n }\n /**\n * Returns the number for IsGreater\n */\n static get IsGreater() {\n return ValueCondition._IsGreater;\n }\n /**\n * Returns the number for IsLesser\n */\n static get IsLesser() {\n return ValueCondition._IsLesser;\n }\n /**\n * Creates a new ValueCondition\n * @param actionManager manager for the action the condition applies to\n * @param target for the action\n * @param propertyPath path to specify the property of the target the conditional operator uses\n * @param value the value compared by the conditional operator against the current value of the property\n * @param operator the conditional operator, default ValueCondition.IsEqual\n */\n constructor(actionManager, target, \n /** path to specify the property of the target the conditional operator uses */\n propertyPath, \n /** the value compared by the conditional operator against the current value of the property */\n value, \n /** the conditional operator, default ValueCondition.IsEqual */\n operator = ValueCondition.IsEqual) {\n super(actionManager);\n this.propertyPath = propertyPath;\n this.value = value;\n this.operator = operator;\n this._target = target;\n this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);\n this._property = this._getProperty(this.propertyPath);\n }\n /**\n * Compares the given value with the property value for the specified conditional operator\n * @returns the result of the comparison\n */\n isValid() {\n switch (this.operator) {\n case ValueCondition.IsGreater:\n return this._effectiveTarget[this._property] > this.value;\n case ValueCondition.IsLesser:\n return this._effectiveTarget[this._property] < this.value;\n case ValueCondition.IsEqual:\n case ValueCondition.IsDifferent: {\n let check;\n if (this.value.equals) {\n check = this.value.equals(this._effectiveTarget[this._property]);\n }\n else {\n check = this.value === this._effectiveTarget[this._property];\n }\n return this.operator === ValueCondition.IsEqual ? check : !check;\n }\n }\n return false;\n }\n /**\n * Serialize the ValueCondition into a JSON compatible object\n * @returns serialization object\n */\n serialize() {\n return this._serialize({\n name: \"ValueCondition\",\n properties: [\n Action._GetTargetProperty(this._target),\n { name: \"propertyPath\", value: this.propertyPath },\n { name: \"value\", value: Action._SerializeValueAsString(this.value) },\n { name: \"operator\", value: ValueCondition.GetOperatorName(this.operator) },\n ],\n });\n }\n /**\n * Gets the name of the conditional operator for the ValueCondition\n * @param operator the conditional operator\n * @returns the name\n */\n static GetOperatorName(operator) {\n switch (operator) {\n case ValueCondition._IsEqual:\n return \"IsEqual\";\n case ValueCondition._IsDifferent:\n return \"IsDifferent\";\n case ValueCondition._IsGreater:\n return \"IsGreater\";\n case ValueCondition._IsLesser:\n return \"IsLesser\";\n default:\n return \"\";\n }\n }\n}\nValueCondition._IsEqual = 0;\nValueCondition._IsDifferent = 1;\nValueCondition._IsGreater = 2;\nValueCondition._IsLesser = 3;\n/**\n * Defines a predicate condition as an extension of Condition\n */\nexport class PredicateCondition extends Condition {\n /**\n * Creates a new PredicateCondition\n * @param actionManager manager for the action the condition applies to\n * @param predicate defines the predicate function used to validate the condition\n */\n constructor(actionManager, \n /** defines the predicate function used to validate the condition */\n predicate) {\n super(actionManager);\n this.predicate = predicate;\n }\n /**\n * @returns the validity of the predicate condition\n */\n isValid() {\n return this.predicate();\n }\n}\n/**\n * Defines a state condition as an extension of Condition\n */\nexport class StateCondition extends Condition {\n /**\n * Creates a new StateCondition\n * @param actionManager manager for the action the condition applies to\n * @param target of the condition\n * @param value to compare with target state\n */\n constructor(actionManager, target, \n /** Value to compare with target state */\n value) {\n super(actionManager);\n this.value = value;\n this._target = target;\n }\n /**\n * Gets a boolean indicating if the current condition is met\n * @returns the validity of the state\n */\n isValid() {\n return this._target.state === this.value;\n }\n /**\n * Serialize the StateCondition into a JSON compatible object\n * @returns serialization object\n */\n serialize() {\n return this._serialize({\n name: \"StateCondition\",\n properties: [Action._GetTargetProperty(this._target), { name: \"value\", value: this.value }],\n });\n }\n}\nRegisterClass(\"BABYLON.ValueCondition\", ValueCondition);\nRegisterClass(\"BABYLON.PredicateCondition\", PredicateCondition);\nRegisterClass(\"BABYLON.StateCondition\", StateCondition);\n//# sourceMappingURL=condition.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Action } from \"./action.js\";\n\nimport { RegisterClass } from \"../Misc/typeStore.js\";\n/**\n * This defines an action responsible to toggle a boolean once triggered.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\nexport class SwitchBooleanAction extends Action {\n /**\n * Instantiate the action\n * @param triggerOptions defines the trigger options\n * @param target defines the object containing the boolean\n * @param propertyPath defines the path to the boolean property in the target object\n * @param condition defines the trigger related conditions\n */\n constructor(triggerOptions, target, propertyPath, condition) {\n super(triggerOptions, condition);\n this.propertyPath = propertyPath;\n this._target = this._effectiveTarget = target;\n }\n /** @internal */\n _prepare() {\n this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);\n this._property = this._getProperty(this.propertyPath);\n }\n /**\n * Execute the action toggle the boolean value.\n */\n execute() {\n this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];\n }\n /**\n * Serializes the actions and its related information.\n * @param parent defines the object to serialize in\n * @returns the serialized object\n */\n serialize(parent) {\n return super._serialize({\n name: \"SwitchBooleanAction\",\n properties: [Action._GetTargetProperty(this._target), { name: \"propertyPath\", value: this.propertyPath }],\n }, parent);\n }\n}\n/**\n * This defines an action responsible to set a the state field of the target\n * to a desired value once triggered.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\nexport class SetStateAction extends Action {\n /**\n * Instantiate the action\n * @param triggerOptions defines the trigger options\n * @param target defines the object containing the state property\n * @param value defines the value to store in the state field\n * @param condition defines the trigger related conditions\n */\n constructor(triggerOptions, target, value, condition) {\n super(triggerOptions, condition);\n this.value = value;\n this._target = target;\n }\n /**\n * Execute the action and store the value on the target state property.\n */\n execute() {\n this._target.state = this.value;\n }\n /**\n * Serializes the actions and its related information.\n * @param parent defines the object to serialize in\n * @returns the serialized object\n */\n serialize(parent) {\n return super._serialize({\n name: \"SetStateAction\",\n properties: [Action._GetTargetProperty(this._target), { name: \"value\", value: this.value }],\n }, parent);\n }\n}\n/**\n * This defines an action responsible to set a property of the target\n * to a desired value once triggered.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\nexport class SetValueAction extends Action {\n /**\n * Instantiate the action\n * @param triggerOptions defines the trigger options\n * @param target defines the object containing the property\n * @param propertyPath defines the path of the property to set in the target\n * @param value defines the value to set in the property\n * @param condition defines the trigger related conditions\n */\n constructor(triggerOptions, target, propertyPath, value, condition) {\n super(triggerOptions, condition);\n this.propertyPath = propertyPath;\n this.value = value;\n this._target = this._effectiveTarget = target;\n }\n /** @internal */\n _prepare() {\n this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);\n this._property = this._getProperty(this.propertyPath);\n }\n /**\n * Execute the action and set the targeted property to the desired value.\n */\n execute() {\n this._effectiveTarget[this._property] = this.value;\n if (this._target.markAsDirty) {\n this._target.markAsDirty(this._property);\n }\n }\n /**\n * Serializes the actions and its related information.\n * @param parent defines the object to serialize in\n * @returns the serialized object\n */\n serialize(parent) {\n return super._serialize({\n name: \"SetValueAction\",\n properties: [\n Action._GetTargetProperty(this._target),\n { name: \"propertyPath\", value: this.propertyPath },\n { name: \"value\", value: Action._SerializeValueAsString(this.value) },\n ],\n }, parent);\n }\n}\n/**\n * This defines an action responsible to increment the target value\n * to a desired value once triggered.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\nexport class IncrementValueAction extends Action {\n /**\n * Instantiate the action\n * @param triggerOptions defines the trigger options\n * @param target defines the object containing the property\n * @param propertyPath defines the path of the property to increment in the target\n * @param value defines the value value we should increment the property by\n * @param condition defines the trigger related conditions\n */\n constructor(triggerOptions, target, propertyPath, value, condition) {\n super(triggerOptions, condition);\n this.propertyPath = propertyPath;\n this.value = value;\n this._target = this._effectiveTarget = target;\n }\n /** @internal */\n _prepare() {\n this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);\n this._property = this._getProperty(this.propertyPath);\n if (typeof this._effectiveTarget[this._property] !== \"number\") {\n Logger.Warn(\"Warning: IncrementValueAction can only be used with number values\");\n }\n }\n /**\n * Execute the action and increment the target of the value amount.\n */\n execute() {\n this._effectiveTarget[this._property] += this.value;\n if (this._target.markAsDirty) {\n this._target.markAsDirty(this._property);\n }\n }\n /**\n * Serializes the actions and its related information.\n * @param parent defines the object to serialize in\n * @returns the serialized object\n */\n serialize(parent) {\n return super._serialize({\n name: \"IncrementValueAction\",\n properties: [\n Action._GetTargetProperty(this._target),\n { name: \"propertyPath\", value: this.propertyPath },\n { name: \"value\", value: Action._SerializeValueAsString(this.value) },\n ],\n }, parent);\n }\n}\n/**\n * This defines an action responsible to start an animation once triggered.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\nexport class PlayAnimationAction extends Action {\n /**\n * Instantiate the action\n * @param triggerOptions defines the trigger options\n * @param target defines the target animation or animation name\n * @param from defines from where the animation should start (animation frame)\n * @param to defines where the animation should stop (animation frame)\n * @param loop defines if the animation should loop or stop after the first play\n * @param condition defines the trigger related conditions\n */\n constructor(triggerOptions, target, from, to, loop, condition) {\n super(triggerOptions, condition);\n this.from = from;\n this.to = to;\n this.loop = loop;\n this._target = target;\n }\n /** @internal */\n _prepare() { }\n /**\n * Execute the action and play the animation.\n */\n execute() {\n const scene = this._actionManager.getScene();\n scene.beginAnimation(this._target, this.from, this.to, this.loop);\n }\n /**\n * Serializes the actions and its related information.\n * @param parent defines the object to serialize in\n * @returns the serialized object\n */\n serialize(parent) {\n return super._serialize({\n name: \"PlayAnimationAction\",\n properties: [\n Action._GetTargetProperty(this._target),\n { name: \"from\", value: String(this.from) },\n { name: \"to\", value: String(this.to) },\n { name: \"loop\", value: Action._SerializeValueAsString(this.loop) || false },\n ],\n }, parent);\n }\n}\n/**\n * This defines an action responsible to stop an animation once triggered.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\nexport class StopAnimationAction extends Action {\n /**\n * Instantiate the action\n * @param triggerOptions defines the trigger options\n * @param target defines the target animation or animation name\n * @param condition defines the trigger related conditions\n */\n constructor(triggerOptions, target, condition) {\n super(triggerOptions, condition);\n this._target = target;\n }\n /** @internal */\n _prepare() { }\n /**\n * Execute the action and stop the animation.\n */\n execute() {\n const scene = this._actionManager.getScene();\n scene.stopAnimation(this._target);\n }\n /**\n * Serializes the actions and its related information.\n * @param parent defines the object to serialize in\n * @returns the serialized object\n */\n serialize(parent) {\n return super._serialize({\n name: \"StopAnimationAction\",\n properties: [Action._GetTargetProperty(this._target)],\n }, parent);\n }\n}\n/**\n * This defines an action responsible that does nothing once triggered.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\nexport class DoNothingAction extends Action {\n /**\n * Instantiate the action\n * @param triggerOptions defines the trigger options\n * @param condition defines the trigger related conditions\n */\n constructor(triggerOptions = 0, condition) {\n super(triggerOptions, condition);\n }\n /**\n * Execute the action and do nothing.\n */\n execute() { }\n /**\n * Serializes the actions and its related information.\n * @param parent defines the object to serialize in\n * @returns the serialized object\n */\n serialize(parent) {\n return super._serialize({\n name: \"DoNothingAction\",\n properties: [],\n }, parent);\n }\n}\n/**\n * This defines an action responsible to trigger several actions once triggered.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\nexport class CombineAction extends Action {\n /**\n * Instantiate the action\n * @param triggerOptions defines the trigger options\n * @param children defines the list of aggregated animations to run\n * @param condition defines the trigger related conditions\n * @param enableChildrenConditions defines if the children actions conditions should be check before execution\n */\n constructor(triggerOptions, children, condition, enableChildrenConditions = true) {\n super(triggerOptions, condition);\n this.children = children;\n this.enableChildrenConditions = enableChildrenConditions;\n }\n /** @internal */\n _prepare() {\n for (let index = 0; index < this.children.length; index++) {\n this.children[index]._actionManager = this._actionManager;\n this.children[index]._prepare();\n }\n }\n /**\n * Execute the action and executes all the aggregated actions.\n * @param evt\n */\n execute(evt) {\n for (const action of this.children) {\n if (!this.enableChildrenConditions || action._evaluateConditionForCurrentFrame()) {\n action.execute(evt);\n }\n }\n }\n /**\n * Serializes the actions and its related information.\n * @param parent defines the object to serialize in\n * @returns the serialized object\n */\n serialize(parent) {\n const serializationObject = super._serialize({\n name: \"CombineAction\",\n properties: [],\n combine: [],\n }, parent);\n for (let i = 0; i < this.children.length; i++) {\n serializationObject.combine.push(this.children[i].serialize(null));\n }\n return serializationObject;\n }\n}\n/**\n * This defines an action responsible to run code (external event) once triggered.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\nexport class ExecuteCodeAction extends Action {\n /**\n * Instantiate the action\n * @param triggerOptions defines the trigger options\n * @param func defines the callback function to run\n * @param condition defines the trigger related conditions\n */\n constructor(triggerOptions, func, condition) {\n super(triggerOptions, condition);\n this.func = func;\n }\n /**\n * Execute the action and run the attached code.\n * @param evt\n */\n execute(evt) {\n this.func(evt);\n }\n}\n/**\n * This defines an action responsible to set the parent property of the target once triggered.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\nexport class SetParentAction extends Action {\n /**\n * Instantiate the action\n * @param triggerOptions defines the trigger options\n * @param target defines the target containing the parent property\n * @param parent defines from where the animation should start (animation frame)\n * @param condition defines the trigger related conditions\n */\n constructor(triggerOptions, target, parent, condition) {\n super(triggerOptions, condition);\n this._target = target;\n this._parent = parent;\n }\n /** @internal */\n _prepare() { }\n /**\n * Execute the action and set the parent property.\n */\n execute() {\n if (this._target.parent === this._parent) {\n return;\n }\n const invertParentWorldMatrix = this._parent.getWorldMatrix().clone();\n invertParentWorldMatrix.invert();\n this._target.position = Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);\n this._target.parent = this._parent;\n }\n /**\n * Serializes the actions and its related information.\n * @param parent defines the object to serialize in\n * @returns the serialized object\n */\n serialize(parent) {\n return super._serialize({\n name: \"SetParentAction\",\n properties: [Action._GetTargetProperty(this._target), Action._GetTargetProperty(this._parent)],\n }, parent);\n }\n}\nRegisterClass(\"BABYLON.SetParentAction\", SetParentAction);\nRegisterClass(\"BABYLON.ExecuteCodeAction\", ExecuteCodeAction);\nRegisterClass(\"BABYLON.DoNothingAction\", DoNothingAction);\nRegisterClass(\"BABYLON.StopAnimationAction\", StopAnimationAction);\nRegisterClass(\"BABYLON.PlayAnimationAction\", PlayAnimationAction);\nRegisterClass(\"BABYLON.IncrementValueAction\", IncrementValueAction);\nRegisterClass(\"BABYLON.SetValueAction\", SetValueAction);\nRegisterClass(\"BABYLON.SetStateAction\", SetStateAction);\nRegisterClass(\"BABYLON.SetParentAction\", SetParentAction);\nRegisterClass(\"BABYLON.SwitchBooleanAction\", SwitchBooleanAction);\nRegisterClass(\"BABYLON.CombineAction\", CombineAction);\n//# sourceMappingURL=directActions.js.map","import { Vector3, Vector4 } from \"../Maths/math.vector.js\";\nimport { Color3, Color4 } from \"../Maths/math.color.js\";\nimport { Condition, ValueCondition } from \"./condition.js\";\nimport { Action } from \"./action.js\";\nimport { DoNothingAction } from \"./directActions.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { DeepCopier } from \"../Misc/deepCopier.js\";\nimport { GetClass } from \"../Misc/typeStore.js\";\nimport { AbstractActionManager } from \"./abstractActionManager.js\";\n\n/**\n * Action Manager manages all events to be triggered on a given mesh or the global scene.\n * A single scene can have many Action Managers to handle predefined actions on specific meshes.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\nexport class ActionManager extends AbstractActionManager {\n /**\n * Creates a new action manager\n * @param scene defines the hosting scene\n */\n constructor(scene) {\n super();\n scene = scene || EngineStore.LastCreatedScene;\n if (!scene) {\n return;\n }\n this._scene = scene;\n scene.actionManagers.push(this);\n }\n // Methods\n /**\n * Releases all associated resources\n */\n dispose() {\n const index = this._scene.actionManagers.indexOf(this);\n for (let i = 0; i < this.actions.length; i++) {\n const action = this.actions[i];\n ActionManager.Triggers[action.trigger]--;\n if (ActionManager.Triggers[action.trigger] === 0) {\n delete ActionManager.Triggers[action.trigger];\n }\n }\n if (index > -1) {\n this._scene.actionManagers.splice(index, 1);\n }\n }\n /**\n * Gets hosting scene\n * @returns the hosting scene\n */\n getScene() {\n return this._scene;\n }\n /**\n * Does this action manager handles actions of any of the given triggers\n * @param triggers defines the triggers to be tested\n * @returns a boolean indicating whether one (or more) of the triggers is handled\n */\n hasSpecificTriggers(triggers) {\n for (let index = 0; index < this.actions.length; index++) {\n const action = this.actions[index];\n if (triggers.indexOf(action.trigger) > -1) {\n return true;\n }\n }\n return false;\n }\n /**\n * Does this action manager handles actions of any of the given triggers. This function takes two arguments for\n * speed.\n * @param triggerA defines the trigger to be tested\n * @param triggerB defines the trigger to be tested\n * @returns a boolean indicating whether one (or more) of the triggers is handled\n */\n hasSpecificTriggers2(triggerA, triggerB) {\n for (let index = 0; index < this.actions.length; index++) {\n const action = this.actions[index];\n if (triggerA == action.trigger || triggerB == action.trigger) {\n return true;\n }\n }\n return false;\n }\n /**\n * Does this action manager handles actions of a given trigger\n * @param trigger defines the trigger to be tested\n * @param parameterPredicate defines an optional predicate to filter triggers by parameter\n * @returns whether the trigger is handled\n */\n hasSpecificTrigger(trigger, parameterPredicate) {\n for (let index = 0; index < this.actions.length; index++) {\n const action = this.actions[index];\n if (action.trigger === trigger) {\n if (parameterPredicate) {\n if (parameterPredicate(action.getTriggerParameter())) {\n return true;\n }\n }\n else {\n return true;\n }\n }\n }\n return false;\n }\n /**\n * Does this action manager has pointer triggers\n */\n get hasPointerTriggers() {\n for (let index = 0; index < this.actions.length; index++) {\n const action = this.actions[index];\n if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {\n return true;\n }\n }\n return false;\n }\n /**\n * Does this action manager has pick triggers\n */\n get hasPickTriggers() {\n for (let index = 0; index < this.actions.length; index++) {\n const action = this.actions[index];\n if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {\n return true;\n }\n }\n return false;\n }\n /**\n * Registers an action to this action manager\n * @param action defines the action to be registered\n * @returns the action amended (prepared) after registration\n */\n registerAction(action) {\n if (action.trigger === ActionManager.OnEveryFrameTrigger) {\n if (this.getScene().actionManager !== this) {\n Logger.Warn(\"OnEveryFrameTrigger can only be used with scene.actionManager\");\n return null;\n }\n }\n this.actions.push(action);\n this.getScene()._registeredActions++;\n if (ActionManager.Triggers[action.trigger]) {\n ActionManager.Triggers[action.trigger]++;\n }\n else {\n ActionManager.Triggers[action.trigger] = 1;\n }\n action._actionManager = this;\n action._prepare();\n return action;\n }\n /**\n * Unregisters an action to this action manager\n * @param action defines the action to be unregistered\n * @returns a boolean indicating whether the action has been unregistered\n */\n unregisterAction(action) {\n const index = this.actions.indexOf(action);\n if (index !== -1) {\n this.actions.splice(index, 1);\n ActionManager.Triggers[action.trigger] -= 1;\n if (ActionManager.Triggers[action.trigger] === 0) {\n delete ActionManager.Triggers[action.trigger];\n }\n action._actionManager = null;\n this.getScene()._registeredActions--;\n return true;\n }\n return false;\n }\n /**\n * Process a specific trigger\n * @param trigger defines the trigger to process\n * @param evt defines the event details to be processed\n */\n processTrigger(trigger, evt) {\n for (let index = 0; index < this.actions.length; index++) {\n const action = this.actions[index];\n if (action.trigger === trigger) {\n if (evt) {\n if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {\n const parameter = action.getTriggerParameter();\n if (typeof parameter === \"function\") {\n if (!parameter(evt)) {\n continue;\n }\n }\n else if (parameter && parameter !== evt.sourceEvent.keyCode) {\n if (!parameter.toLowerCase) {\n continue;\n }\n const lowerCase = parameter.toLowerCase();\n if (lowerCase !== evt.sourceEvent.key) {\n const unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;\n const actualkey = String.fromCharCode(unicode).toLowerCase();\n if (actualkey !== lowerCase) {\n continue;\n }\n }\n }\n }\n }\n action._executeCurrent(evt);\n }\n }\n }\n /**\n * @internal\n */\n _getEffectiveTarget(target, propertyPath) {\n const properties = propertyPath.split(\".\");\n for (let index = 0; index < properties.length - 1; index++) {\n target = target[properties[index]];\n }\n return target;\n }\n /**\n * @internal\n */\n _getProperty(propertyPath) {\n const properties = propertyPath.split(\".\");\n return properties[properties.length - 1];\n }\n /**\n * Serialize this manager to a JSON object\n * @param name defines the property name to store this manager\n * @returns a JSON representation of this manager\n */\n serialize(name) {\n const root = {\n children: new Array(),\n name: name,\n type: 3,\n properties: new Array(), // Empty for root but required\n };\n for (let i = 0; i < this.actions.length; i++) {\n const triggerObject = {\n type: 0,\n children: new Array(),\n name: ActionManager.GetTriggerName(this.actions[i].trigger),\n properties: new Array(),\n };\n const triggerOptions = this.actions[i].triggerOptions;\n if (triggerOptions && typeof triggerOptions !== \"number\") {\n if (triggerOptions.parameter instanceof Node) {\n triggerObject.properties.push(Action._GetTargetProperty(triggerOptions.parameter));\n }\n else if (typeof triggerOptions.parameter === \"object\") {\n const parameter = {};\n DeepCopier.DeepCopy(triggerOptions.parameter, parameter, [\"mesh\"]);\n if (triggerOptions.parameter && triggerOptions.parameter.mesh) {\n parameter._meshId = triggerOptions.parameter.mesh.id;\n }\n triggerObject.properties.push({ name: \"parameter\", targetType: null, value: parameter });\n }\n else {\n triggerObject.properties.push({ name: \"parameter\", targetType: null, value: triggerOptions.parameter });\n }\n }\n // Serialize child action, recursively\n this.actions[i].serialize(triggerObject);\n // Add serialized trigger\n root.children.push(triggerObject);\n }\n return root;\n }\n /**\n * Creates a new ActionManager from a JSON data\n * @param parsedActions defines the JSON data to read from\n * @param object defines the hosting mesh\n * @param scene defines the hosting scene\n */\n static Parse(parsedActions, object, scene) {\n const actionManager = new ActionManager(scene);\n if (object === null) {\n scene.actionManager = actionManager;\n }\n else {\n object.actionManager = actionManager;\n }\n // instantiate a new object\n const instantiate = (name, params) => {\n const internalClassType = GetClass(\"BABYLON.\" + name);\n return internalClassType && new internalClassType(...params);\n };\n const parseParameter = (name, value, target, propertyPath) => {\n if (propertyPath === null) {\n // String, boolean or float\n const floatValue = parseFloat(value);\n if (value === \"true\" || value === \"false\") {\n return value === \"true\";\n }\n else {\n return isNaN(floatValue) ? value : floatValue;\n }\n }\n const effectiveTarget = propertyPath.split(\".\");\n const values = value.split(\",\");\n // Get effective Target\n for (let i = 0; i < effectiveTarget.length; i++) {\n target = target[effectiveTarget[i]];\n }\n // Return appropriate value with its type\n if (typeof target === \"boolean\") {\n return values[0] === \"true\";\n }\n if (typeof target === \"string\") {\n return values[0];\n }\n // Parameters with multiple values such as Vector3 etc.\n const split = new Array();\n for (let i = 0; i < values.length; i++) {\n split.push(parseFloat(values[i]));\n }\n if (target instanceof Vector3) {\n return Vector3.FromArray(split);\n }\n if (target instanceof Vector4) {\n return Vector4.FromArray(split);\n }\n if (target instanceof Color3) {\n return Color3.FromArray(split);\n }\n if (target instanceof Color4) {\n return Color4.FromArray(split);\n }\n return parseFloat(values[0]);\n };\n // traverse graph per trigger\n const traverse = (parsedAction, trigger, condition, action, combineArray = null) => {\n if (parsedAction.detached) {\n return;\n }\n const parameters = new Array();\n let target = null;\n let propertyPath = null;\n const combine = parsedAction.combine && parsedAction.combine.length > 0;\n // Parameters\n if (parsedAction.type === 2) {\n parameters.push(actionManager);\n }\n else {\n parameters.push(trigger);\n }\n if (combine) {\n const actions = new Array();\n for (let j = 0; j < parsedAction.combine.length; j++) {\n traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);\n }\n parameters.push(actions);\n }\n else {\n for (let i = 0; i < parsedAction.properties.length; i++) {\n let value = parsedAction.properties[i].value;\n const name = parsedAction.properties[i].name;\n const targetType = parsedAction.properties[i].targetType;\n if (name === \"target\") {\n if (targetType === \"SceneProperties\") {\n value = target = scene;\n }\n else if (targetType === \"MaterialProperties\") {\n value = target = scene.getMaterialByName(value);\n }\n else {\n value = target = scene.getNodeByName(value);\n }\n }\n else if (name === \"parent\") {\n value = scene.getNodeByName(value);\n }\n else if (name === \"sound\") {\n // Can not externalize to component, so only checks for the presence off the API.\n if (scene.getSoundByName) {\n value = scene.getSoundByName(value);\n }\n }\n else if (name !== \"propertyPath\") {\n if (parsedAction.type === 2 && name === \"operator\") {\n value = ValueCondition[value];\n }\n else {\n value = parseParameter(name, value, target, name === \"value\" ? propertyPath : null);\n }\n }\n else {\n propertyPath = value;\n }\n parameters.push(value);\n }\n }\n if (combineArray === null) {\n parameters.push(condition);\n }\n else {\n parameters.push(null);\n }\n // If interpolate value action\n if (parsedAction.name === \"InterpolateValueAction\") {\n const param = parameters[parameters.length - 2];\n parameters[parameters.length - 1] = param;\n parameters[parameters.length - 2] = condition;\n }\n // Action or condition(s) and not CombineAction\n let newAction = instantiate(parsedAction.name, parameters);\n if (newAction instanceof Condition && condition !== null) {\n const nothing = new DoNothingAction(trigger, condition);\n if (action) {\n action.then(nothing);\n }\n else {\n actionManager.registerAction(nothing);\n }\n action = nothing;\n }\n if (combineArray === null) {\n if (newAction instanceof Condition) {\n condition = newAction;\n newAction = action;\n }\n else {\n condition = null;\n if (action) {\n action.then(newAction);\n }\n else {\n actionManager.registerAction(newAction);\n }\n }\n }\n else {\n combineArray.push(newAction);\n }\n for (let i = 0; i < parsedAction.children.length; i++) {\n traverse(parsedAction.children[i], trigger, condition, newAction, null);\n }\n };\n // triggers\n for (let i = 0; i < parsedActions.children.length; i++) {\n let triggerParams;\n const trigger = parsedActions.children[i];\n if (trigger.properties.length > 0) {\n const param = trigger.properties[0].value;\n const value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);\n if (value._meshId) {\n value.mesh = scene.getMeshById(value._meshId);\n }\n triggerParams = { trigger: ActionManager[trigger.name], parameter: value };\n }\n else {\n triggerParams = ActionManager[trigger.name];\n }\n for (let j = 0; j < trigger.children.length; j++) {\n if (!trigger.detached) {\n traverse(trigger.children[j], triggerParams, null, null);\n }\n }\n }\n }\n /**\n * Get a trigger name by index\n * @param trigger defines the trigger index\n * @returns a trigger name\n */\n static GetTriggerName(trigger) {\n switch (trigger) {\n case 0:\n return \"NothingTrigger\";\n case 1:\n return \"OnPickTrigger\";\n case 2:\n return \"OnLeftPickTrigger\";\n case 3:\n return \"OnRightPickTrigger\";\n case 4:\n return \"OnCenterPickTrigger\";\n case 5:\n return \"OnPickDownTrigger\";\n case 6:\n return \"OnDoublePickTrigger\"; // start;\n case 7:\n return \"OnPickUpTrigger\";\n case 8:\n return \"OnLongPressTrigger\";\n case 9:\n return \"OnPointerOverTrigger\";\n case 10:\n return \"OnPointerOutTrigger\";\n case 11:\n return \"OnEveryFrameTrigger\";\n case 12:\n return \"OnIntersectionEnterTrigger\";\n case 13:\n return \"OnIntersectionExitTrigger\";\n case 14:\n return \"OnKeyDownTrigger\";\n case 15:\n return \"OnKeyUpTrigger\";\n case 16:\n return \"OnPickOutTrigger\";\n default:\n return \"\";\n }\n }\n}\n/**\n * Nothing\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.NothingTrigger = 0;\n/**\n * On pick\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnPickTrigger = 1;\n/**\n * On left pick\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnLeftPickTrigger = 2;\n/**\n * On right pick\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnRightPickTrigger = 3;\n/**\n * On center pick\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnCenterPickTrigger = 4;\n/**\n * On pick down\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnPickDownTrigger = 5;\n/**\n * On double pick\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnDoublePickTrigger = 6;\n/**\n * On pick up\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnPickUpTrigger = 7;\n/**\n * On pick out.\n * This trigger will only be raised if you also declared a OnPickDown\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnPickOutTrigger = 16;\n/**\n * On long press\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnLongPressTrigger = 8;\n/**\n * On pointer over\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnPointerOverTrigger = 9;\n/**\n * On pointer out\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnPointerOutTrigger = 10;\n/**\n * On every frame\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnEveryFrameTrigger = 11;\n/**\n * On intersection enter\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnIntersectionEnterTrigger = 12;\n/**\n * On intersection exit\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnIntersectionExitTrigger = 13;\n/**\n * On key down\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnKeyDownTrigger = 14;\n/**\n * On key up\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nActionManager.OnKeyUpTrigger = 15;\n//# sourceMappingURL=actionManager.js.map","import { Action } from \"./action.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\n/**\n * This defines an action helpful to play a defined sound on a triggered action.\n */\nexport class PlaySoundAction extends Action {\n /**\n * Instantiate the action\n * @param triggerOptions defines the trigger options\n * @param sound defines the sound to play\n * @param condition defines the trigger related conditions\n */\n constructor(triggerOptions, sound, condition) {\n super(triggerOptions, condition);\n this._sound = sound;\n }\n /** @internal */\n _prepare() { }\n /**\n * Execute the action and play the sound.\n */\n execute() {\n if (this._sound !== undefined) {\n this._sound.play();\n }\n }\n /**\n * Serializes the actions and its related information.\n * @param parent defines the object to serialize in\n * @returns the serialized object\n */\n serialize(parent) {\n return super._serialize({\n name: \"PlaySoundAction\",\n properties: [{ name: \"sound\", value: this._sound.name }],\n }, parent);\n }\n}\n/**\n * This defines an action helpful to stop a defined sound on a triggered action.\n */\nexport class StopSoundAction extends Action {\n /**\n * Instantiate the action\n * @param triggerOptions defines the trigger options\n * @param sound defines the sound to stop\n * @param condition defines the trigger related conditions\n */\n constructor(triggerOptions, sound, condition) {\n super(triggerOptions, condition);\n this._sound = sound;\n }\n /** @internal */\n _prepare() { }\n /**\n * Execute the action and stop the sound.\n */\n execute() {\n if (this._sound !== undefined) {\n this._sound.stop();\n }\n }\n /**\n * Serializes the actions and its related information.\n * @param parent defines the object to serialize in\n * @returns the serialized object\n */\n serialize(parent) {\n return super._serialize({\n name: \"StopSoundAction\",\n properties: [{ name: \"sound\", value: this._sound.name }],\n }, parent);\n }\n}\nRegisterClass(\"BABYLON.PlaySoundAction\", PlaySoundAction);\nRegisterClass(\"BABYLON.StopSoundAction\", StopSoundAction);\n//# sourceMappingURL=directAudioActions.js.map","/**\n * Enum for the animation key frame interpolation type\n */\nexport var AnimationKeyInterpolation;\n(function (AnimationKeyInterpolation) {\n /**\n * Use tangents to interpolate between start and end values.\n */\n AnimationKeyInterpolation[AnimationKeyInterpolation[\"NONE\"] = 0] = \"NONE\";\n /**\n * Do not interpolate between keys and use the start key value only. Tangents are ignored\n */\n AnimationKeyInterpolation[AnimationKeyInterpolation[\"STEP\"] = 1] = \"STEP\";\n})(AnimationKeyInterpolation || (AnimationKeyInterpolation = {}));\n//# sourceMappingURL=animationKey.js.map","/**\n * Represents the range of an animation\n */\nexport class AnimationRange {\n /**\n * Initializes the range of an animation\n * @param name The name of the animation range\n * @param from The starting frame of the animation\n * @param to The ending frame of the animation\n */\n constructor(\n /**The name of the animation range**/\n name, \n /**The starting frame of the animation */\n from, \n /**The ending frame of the animation*/\n to) {\n this.name = name;\n this.from = from;\n this.to = to;\n }\n /**\n * Makes a copy of the animation range\n * @returns A copy of the animation range\n */\n clone() {\n return new AnimationRange(this.name, this.from, this.to);\n }\n}\n//# sourceMappingURL=animationRange.js.map","/**\n * Size containing width and height\n */\nexport class Size {\n /**\n * Creates a Size object from the given width and height (floats).\n * @param width width of the new size\n * @param height height of the new size\n */\n constructor(width, height) {\n this.width = width;\n this.height = height;\n }\n /**\n * Returns a string with the Size width and height\n * @returns a string with the Size width and height\n */\n toString() {\n return `{W: ${this.width}, H: ${this.height}}`;\n }\n /**\n * \"Size\"\n * @returns the string \"Size\"\n */\n getClassName() {\n return \"Size\";\n }\n /**\n * Returns the Size hash code.\n * @returns a hash code for a unique width and height\n */\n getHashCode() {\n let hash = this.width | 0;\n hash = (hash * 397) ^ (this.height | 0);\n return hash;\n }\n /**\n * Updates the current size from the given one.\n * @param src the given size\n */\n copyFrom(src) {\n this.width = src.width;\n this.height = src.height;\n }\n /**\n * Updates in place the current Size from the given floats.\n * @param width width of the new size\n * @param height height of the new size\n * @returns the updated Size.\n */\n copyFromFloats(width, height) {\n this.width = width;\n this.height = height;\n return this;\n }\n /**\n * Updates in place the current Size from the given floats.\n * @param width width to set\n * @param height height to set\n * @returns the updated Size.\n */\n set(width, height) {\n return this.copyFromFloats(width, height);\n }\n /**\n * Multiplies the width and height by numbers\n * @param w factor to multiple the width by\n * @param h factor to multiple the height by\n * @returns a new Size set with the multiplication result of the current Size and the given floats.\n */\n multiplyByFloats(w, h) {\n return new Size(this.width * w, this.height * h);\n }\n /**\n * Clones the size\n * @returns a new Size copied from the given one.\n */\n clone() {\n return new Size(this.width, this.height);\n }\n /**\n * True if the current Size and the given one width and height are strictly equal.\n * @param other the other size to compare against\n * @returns True if the current Size and the given one width and height are strictly equal.\n */\n equals(other) {\n if (!other) {\n return false;\n }\n return this.width === other.width && this.height === other.height;\n }\n /**\n * The surface of the Size : width * height (float).\n */\n get surface() {\n return this.width * this.height;\n }\n /**\n * Create a new size of zero\n * @returns a new Size set to (0.0, 0.0)\n */\n static Zero() {\n return new Size(0.0, 0.0);\n }\n /**\n * Sums the width and height of two sizes\n * @param otherSize size to add to this size\n * @returns a new Size set as the addition result of the current Size and the given one.\n */\n add(otherSize) {\n const r = new Size(this.width + otherSize.width, this.height + otherSize.height);\n return r;\n }\n /**\n * Subtracts the width and height of two\n * @param otherSize size to subtract to this size\n * @returns a new Size set as the subtraction result of the given one from the current Size.\n */\n subtract(otherSize) {\n const r = new Size(this.width - otherSize.width, this.height - otherSize.height);\n return r;\n }\n /**\n * Creates a new Size set at the linear interpolation \"amount\" between \"start\" and \"end\"\n * @param start starting size to lerp between\n * @param end end size to lerp between\n * @param amount amount to lerp between the start and end values\n * @returns a new Size set at the linear interpolation \"amount\" between \"start\" and \"end\"\n */\n static Lerp(start, end, amount) {\n const w = start.width + (end.width - start.width) * amount;\n const h = start.height + (end.height - start.height) * amount;\n return new Size(w, h);\n }\n}\n//# sourceMappingURL=math.size.js.map","import { Vector3, Quaternion, Vector2, Matrix, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Color3, Color4 } from \"../Maths/math.color.js\";\nimport { Scalar } from \"../Maths/math.scalar.js\";\nimport { SerializationHelper } from \"../Misc/decorators.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\nimport { AnimationKeyInterpolation } from \"./animationKey.js\";\nimport { AnimationRange } from \"./animationRange.js\";\nimport { Node } from \"../node.js\";\nimport { Size } from \"../Maths/math.size.js\";\nimport { WebRequest } from \"../Misc/webRequest.js\";\n\n/**\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class _IAnimationState {\n}\n/**\n * Class used to store any kind of animation\n */\nexport class Animation {\n /**\n * @internal Internal use\n */\n static _PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {\n let dataType = undefined;\n if (!isNaN(parseFloat(from)) && isFinite(from)) {\n dataType = Animation.ANIMATIONTYPE_FLOAT;\n }\n else if (from instanceof Quaternion) {\n dataType = Animation.ANIMATIONTYPE_QUATERNION;\n }\n else if (from instanceof Vector3) {\n dataType = Animation.ANIMATIONTYPE_VECTOR3;\n }\n else if (from instanceof Vector2) {\n dataType = Animation.ANIMATIONTYPE_VECTOR2;\n }\n else if (from instanceof Color3) {\n dataType = Animation.ANIMATIONTYPE_COLOR3;\n }\n else if (from instanceof Color4) {\n dataType = Animation.ANIMATIONTYPE_COLOR4;\n }\n else if (from instanceof Size) {\n dataType = Animation.ANIMATIONTYPE_SIZE;\n }\n if (dataType == undefined) {\n return null;\n }\n const animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);\n const keys = [\n { frame: 0, value: from },\n { frame: totalFrame, value: to },\n ];\n animation.setKeys(keys);\n if (easingFunction !== undefined) {\n animation.setEasingFunction(easingFunction);\n }\n return animation;\n }\n /**\n * Sets up an animation\n * @param property The property to animate\n * @param animationType The animation type to apply\n * @param framePerSecond The frames per second of the animation\n * @param easingFunction The easing function used in the animation\n * @returns The created animation\n */\n static CreateAnimation(property, animationType, framePerSecond, easingFunction) {\n const animation = new Animation(property + \"Animation\", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);\n animation.setEasingFunction(easingFunction);\n return animation;\n }\n /**\n * Create and start an animation on a node\n * @param name defines the name of the global animation that will be run on all nodes\n * @param target defines the target where the animation will take place\n * @param targetProperty defines property to animate\n * @param framePerSecond defines the number of frame per second yo use\n * @param totalFrame defines the number of frames in total\n * @param from defines the initial value\n * @param to defines the final value\n * @param loopMode defines which loop mode you want to use (off by default)\n * @param easingFunction defines the easing function to use (linear by default)\n * @param onAnimationEnd defines the callback to call when animation end\n * @param scene defines the hosting scene\n * @returns the animatable created for this animation\n */\n static CreateAndStartAnimation(name, target, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd, scene) {\n const animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);\n if (!animation) {\n return null;\n }\n if (target.getScene) {\n scene = target.getScene();\n }\n if (!scene) {\n return null;\n }\n return scene.beginDirectAnimation(target, [animation], 0, totalFrame, animation.loopMode === 1, 1.0, onAnimationEnd);\n }\n /**\n * Create and start an animation on a node and its descendants\n * @param name defines the name of the global animation that will be run on all nodes\n * @param node defines the root node where the animation will take place\n * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used\n * @param targetProperty defines property to animate\n * @param framePerSecond defines the number of frame per second to use\n * @param totalFrame defines the number of frames in total\n * @param from defines the initial value\n * @param to defines the final value\n * @param loopMode defines which loop mode you want to use (off by default)\n * @param easingFunction defines the easing function to use (linear by default)\n * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)\n * @returns the list of animatables created for all nodes\n * @example https://www.babylonjs-playground.com/#MH0VLI\n */\n static CreateAndStartHierarchyAnimation(name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {\n const animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);\n if (!animation) {\n return null;\n }\n const scene = node.getScene();\n return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, animation.loopMode === 1, 1.0, onAnimationEnd);\n }\n /**\n * Creates a new animation, merges it with the existing animations and starts it\n * @param name Name of the animation\n * @param node Node which contains the scene that begins the animations\n * @param targetProperty Specifies which property to animate\n * @param framePerSecond The frames per second of the animation\n * @param totalFrame The total number of frames\n * @param from The frame at the beginning of the animation\n * @param to The frame at the end of the animation\n * @param loopMode Specifies the loop mode of the animation\n * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations\n * @param onAnimationEnd Callback to run once the animation is complete\n * @returns Nullable animation\n */\n static CreateMergeAndStartAnimation(name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {\n const animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);\n if (!animation) {\n return null;\n }\n node.animations.push(animation);\n return node.getScene().beginAnimation(node, 0, totalFrame, animation.loopMode === 1, 1.0, onAnimationEnd);\n }\n /**\n * Convert the keyframes for all animations belonging to the group to be relative to a given reference frame.\n * @param sourceAnimation defines the Animation containing keyframes to convert\n * @param referenceFrame defines the frame that keyframes in the range will be relative to\n * @param range defines the name of the AnimationRange belonging to the Animation to convert\n * @param cloneOriginal defines whether or not to clone the animation and convert the clone or convert the original animation (default is false)\n * @param clonedName defines the name of the resulting cloned Animation if cloneOriginal is true\n * @returns a new Animation if cloneOriginal is true or the original Animation if cloneOriginal is false\n */\n static MakeAnimationAdditive(sourceAnimation, referenceFrame = 0, range, cloneOriginal = false, clonedName) {\n let animation = sourceAnimation;\n if (cloneOriginal) {\n animation = sourceAnimation.clone();\n animation.name = clonedName || animation.name;\n }\n if (!animation._keys.length) {\n return animation;\n }\n referenceFrame = referenceFrame >= 0 ? referenceFrame : 0;\n let startIndex = 0;\n const firstKey = animation._keys[0];\n let endIndex = animation._keys.length - 1;\n const lastKey = animation._keys[endIndex];\n const valueStore = {\n referenceValue: firstKey.value,\n referencePosition: TmpVectors.Vector3[0],\n referenceQuaternion: TmpVectors.Quaternion[0],\n referenceScaling: TmpVectors.Vector3[1],\n keyPosition: TmpVectors.Vector3[2],\n keyQuaternion: TmpVectors.Quaternion[1],\n keyScaling: TmpVectors.Vector3[3],\n };\n let referenceFound = false;\n let from = firstKey.frame;\n let to = lastKey.frame;\n if (range) {\n const rangeValue = animation.getRange(range);\n if (rangeValue) {\n from = rangeValue.from;\n to = rangeValue.to;\n }\n }\n let fromKeyFound = firstKey.frame === from;\n let toKeyFound = lastKey.frame === to;\n // There's only one key, so use it\n if (animation._keys.length === 1) {\n const value = animation._getKeyValue(animation._keys[0]);\n valueStore.referenceValue = value.clone ? value.clone() : value;\n referenceFound = true;\n }\n // Reference frame is before the first frame, so just use the first frame\n else if (referenceFrame <= firstKey.frame) {\n const value = animation._getKeyValue(firstKey.value);\n valueStore.referenceValue = value.clone ? value.clone() : value;\n referenceFound = true;\n }\n // Reference frame is after the last frame, so just use the last frame\n else if (referenceFrame >= lastKey.frame) {\n const value = animation._getKeyValue(lastKey.value);\n valueStore.referenceValue = value.clone ? value.clone() : value;\n referenceFound = true;\n }\n // Find key bookends, create them if they don't exist\n let index = 0;\n while (!referenceFound || !fromKeyFound || (!toKeyFound && index < animation._keys.length - 1)) {\n const currentKey = animation._keys[index];\n const nextKey = animation._keys[index + 1];\n // If reference frame wasn't found yet, check if we can interpolate to it\n if (!referenceFound && referenceFrame >= currentKey.frame && referenceFrame <= nextKey.frame) {\n let value;\n if (referenceFrame === currentKey.frame) {\n value = animation._getKeyValue(currentKey.value);\n }\n else if (referenceFrame === nextKey.frame) {\n value = animation._getKeyValue(nextKey.value);\n }\n else {\n const animationState = {\n key: index,\n repeatCount: 0,\n loopMode: this.ANIMATIONLOOPMODE_CONSTANT,\n };\n value = animation._interpolate(referenceFrame, animationState);\n }\n valueStore.referenceValue = value.clone ? value.clone() : value;\n referenceFound = true;\n }\n // If from key wasn't found yet, check if we can interpolate to it\n if (!fromKeyFound && from >= currentKey.frame && from <= nextKey.frame) {\n if (from === currentKey.frame) {\n startIndex = index;\n }\n else if (from === nextKey.frame) {\n startIndex = index + 1;\n }\n else {\n const animationState = {\n key: index,\n repeatCount: 0,\n loopMode: this.ANIMATIONLOOPMODE_CONSTANT,\n };\n const value = animation._interpolate(from, animationState);\n const key = {\n frame: from,\n value: value.clone ? value.clone() : value,\n };\n animation._keys.splice(index + 1, 0, key);\n startIndex = index + 1;\n }\n fromKeyFound = true;\n }\n // If to key wasn't found yet, check if we can interpolate to it\n if (!toKeyFound && to >= currentKey.frame && to <= nextKey.frame) {\n if (to === currentKey.frame) {\n endIndex = index;\n }\n else if (to === nextKey.frame) {\n endIndex = index + 1;\n }\n else {\n const animationState = {\n key: index,\n repeatCount: 0,\n loopMode: this.ANIMATIONLOOPMODE_CONSTANT,\n };\n const value = animation._interpolate(to, animationState);\n const key = {\n frame: to,\n value: value.clone ? value.clone() : value,\n };\n animation._keys.splice(index + 1, 0, key);\n endIndex = index + 1;\n }\n toKeyFound = true;\n }\n index++;\n }\n // Conjugate the quaternion\n if (animation.dataType === Animation.ANIMATIONTYPE_QUATERNION) {\n valueStore.referenceValue.normalize().conjugateInPlace();\n }\n // Decompose matrix and conjugate the quaternion\n else if (animation.dataType === Animation.ANIMATIONTYPE_MATRIX) {\n valueStore.referenceValue.decompose(valueStore.referenceScaling, valueStore.referenceQuaternion, valueStore.referencePosition);\n valueStore.referenceQuaternion.normalize().conjugateInPlace();\n }\n // Subtract the reference value from all of the key values\n for (index = startIndex; index <= endIndex; index++) {\n const key = animation._keys[index];\n // If this key was duplicated to create a frame 0 key, skip it because its value has already been updated\n if (index && animation.dataType !== Animation.ANIMATIONTYPE_FLOAT && key.value === firstKey.value) {\n continue;\n }\n switch (animation.dataType) {\n case Animation.ANIMATIONTYPE_MATRIX:\n key.value.decompose(valueStore.keyScaling, valueStore.keyQuaternion, valueStore.keyPosition);\n valueStore.keyPosition.subtractInPlace(valueStore.referencePosition);\n valueStore.keyScaling.divideInPlace(valueStore.referenceScaling);\n valueStore.referenceQuaternion.multiplyToRef(valueStore.keyQuaternion, valueStore.keyQuaternion);\n Matrix.ComposeToRef(valueStore.keyScaling, valueStore.keyQuaternion, valueStore.keyPosition, key.value);\n break;\n case Animation.ANIMATIONTYPE_QUATERNION:\n valueStore.referenceValue.multiplyToRef(key.value, key.value);\n break;\n case Animation.ANIMATIONTYPE_VECTOR2:\n case Animation.ANIMATIONTYPE_VECTOR3:\n case Animation.ANIMATIONTYPE_COLOR3:\n case Animation.ANIMATIONTYPE_COLOR4:\n key.value.subtractToRef(valueStore.referenceValue, key.value);\n break;\n case Animation.ANIMATIONTYPE_SIZE:\n key.value.width -= valueStore.referenceValue.width;\n key.value.height -= valueStore.referenceValue.height;\n break;\n default:\n key.value -= valueStore.referenceValue;\n }\n }\n return animation;\n }\n /**\n * Transition property of an host to the target Value\n * @param property The property to transition\n * @param targetValue The target Value of the property\n * @param host The object where the property to animate belongs\n * @param scene Scene used to run the animation\n * @param frameRate Framerate (in frame/s) to use\n * @param transition The transition type we want to use\n * @param duration The duration of the animation, in milliseconds\n * @param onAnimationEnd Callback trigger at the end of the animation\n * @returns Nullable animation\n */\n static TransitionTo(property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd = null) {\n if (duration <= 0) {\n host[property] = targetValue;\n if (onAnimationEnd) {\n onAnimationEnd();\n }\n return null;\n }\n const endFrame = frameRate * (duration / 1000);\n transition.setKeys([\n {\n frame: 0,\n value: host[property].clone ? host[property].clone() : host[property],\n },\n {\n frame: endFrame,\n value: targetValue,\n },\n ]);\n if (!host.animations) {\n host.animations = [];\n }\n host.animations.push(transition);\n const animation = scene.beginAnimation(host, 0, endFrame, false);\n animation.onAnimationEnd = onAnimationEnd;\n return animation;\n }\n /**\n * Return the array of runtime animations currently using this animation\n */\n get runtimeAnimations() {\n return this._runtimeAnimations;\n }\n /**\n * Specifies if any of the runtime animations are currently running\n */\n get hasRunningRuntimeAnimations() {\n for (const runtimeAnimation of this._runtimeAnimations) {\n if (!runtimeAnimation.isStopped()) {\n return true;\n }\n }\n return false;\n }\n /**\n * Initializes the animation\n * @param name Name of the animation\n * @param targetProperty Property to animate\n * @param framePerSecond The frames per second of the animation\n * @param dataType The data type of the animation\n * @param loopMode The loop mode of the animation\n * @param enableBlending Specifies if blending should be enabled\n */\n constructor(\n /**Name of the animation */\n name, \n /**Property to animate */\n targetProperty, \n /**The frames per second of the animation */\n framePerSecond, \n /**The data type of the animation */\n dataType, \n /**The loop mode of the animation */\n loopMode, \n /**Specifies if blending should be enabled */\n enableBlending) {\n this.name = name;\n this.targetProperty = targetProperty;\n this.framePerSecond = framePerSecond;\n this.dataType = dataType;\n this.loopMode = loopMode;\n this.enableBlending = enableBlending;\n /**\n * Stores the easing function of the animation\n */\n this._easingFunction = null;\n /**\n * @internal Internal use only\n */\n this._runtimeAnimations = new Array();\n /**\n * The set of event that will be linked to this animation\n */\n this._events = new Array();\n /**\n * Stores the blending speed of the animation\n */\n this.blendingSpeed = 0.01;\n /**\n * Stores the animation ranges for the animation\n */\n this._ranges = {};\n this.targetPropertyPath = targetProperty.split(\".\");\n this.dataType = dataType;\n this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;\n this.uniqueId = Animation._UniqueIdGenerator++;\n }\n // Methods\n /**\n * Converts the animation to a string\n * @param fullDetails support for multiple levels of logging within scene loading\n * @returns String form of the animation\n */\n toString(fullDetails) {\n let ret = \"Name: \" + this.name + \", property: \" + this.targetProperty;\n ret += \", datatype: \" + [\"Float\", \"Vector3\", \"Quaternion\", \"Matrix\", \"Color3\", \"Vector2\"][this.dataType];\n ret += \", nKeys: \" + (this._keys ? this._keys.length : \"none\");\n ret += \", nRanges: \" + (this._ranges ? Object.keys(this._ranges).length : \"none\");\n if (fullDetails) {\n ret += \", Ranges: {\";\n let first = true;\n for (const name in this._ranges) {\n if (first) {\n ret += \", \";\n first = false;\n }\n ret += name;\n }\n ret += \"}\";\n }\n return ret;\n }\n /**\n * Add an event to this animation\n * @param event Event to add\n */\n addEvent(event) {\n this._events.push(event);\n this._events.sort((a, b) => a.frame - b.frame);\n }\n /**\n * Remove all events found at the given frame\n * @param frame The frame to remove events from\n */\n removeEvents(frame) {\n for (let index = 0; index < this._events.length; index++) {\n if (this._events[index].frame === frame) {\n this._events.splice(index, 1);\n index--;\n }\n }\n }\n /**\n * Retrieves all the events from the animation\n * @returns Events from the animation\n */\n getEvents() {\n return this._events;\n }\n /**\n * Creates an animation range\n * @param name Name of the animation range\n * @param from Starting frame of the animation range\n * @param to Ending frame of the animation\n */\n createRange(name, from, to) {\n // check name not already in use; could happen for bones after serialized\n if (!this._ranges[name]) {\n this._ranges[name] = new AnimationRange(name, from, to);\n }\n }\n /**\n * Deletes an animation range by name\n * @param name Name of the animation range to delete\n * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)\n */\n deleteRange(name, deleteFrames = true) {\n const range = this._ranges[name];\n if (!range) {\n return;\n }\n if (deleteFrames) {\n const from = range.from;\n const to = range.to;\n // this loop MUST go high to low for multiple splices to work\n for (let key = this._keys.length - 1; key >= 0; key--) {\n if (this._keys[key].frame >= from && this._keys[key].frame <= to) {\n this._keys.splice(key, 1);\n }\n }\n }\n this._ranges[name] = null; // said much faster than 'delete this._range[name]'\n }\n /**\n * Gets the animation range by name, or null if not defined\n * @param name Name of the animation range\n * @returns Nullable animation range\n */\n getRange(name) {\n return this._ranges[name];\n }\n /**\n * Gets the key frames from the animation\n * @returns The key frames of the animation\n */\n getKeys() {\n return this._keys;\n }\n /**\n * Gets the highest frame rate of the animation\n * @returns Highest frame rate of the animation\n */\n getHighestFrame() {\n let ret = 0;\n for (let key = 0, nKeys = this._keys.length; key < nKeys; key++) {\n if (ret < this._keys[key].frame) {\n ret = this._keys[key].frame;\n }\n }\n return ret;\n }\n /**\n * Gets the easing function of the animation\n * @returns Easing function of the animation\n */\n getEasingFunction() {\n return this._easingFunction;\n }\n /**\n * Sets the easing function of the animation\n * @param easingFunction A custom mathematical formula for animation\n */\n setEasingFunction(easingFunction) {\n this._easingFunction = easingFunction;\n }\n /**\n * Interpolates a scalar linearly\n * @param startValue Start value of the animation curve\n * @param endValue End value of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated scalar value\n */\n floatInterpolateFunction(startValue, endValue, gradient) {\n return Scalar.Lerp(startValue, endValue, gradient);\n }\n /**\n * Interpolates a scalar cubically\n * @param startValue Start value of the animation curve\n * @param outTangent End tangent of the animation\n * @param endValue End value of the animation curve\n * @param inTangent Start tangent of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated scalar value\n */\n floatInterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) {\n return Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);\n }\n /**\n * Interpolates a quaternion using a spherical linear interpolation\n * @param startValue Start value of the animation curve\n * @param endValue End value of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated quaternion value\n */\n quaternionInterpolateFunction(startValue, endValue, gradient) {\n return Quaternion.Slerp(startValue, endValue, gradient);\n }\n /**\n * Interpolates a quaternion cubically\n * @param startValue Start value of the animation curve\n * @param outTangent End tangent of the animation curve\n * @param endValue End value of the animation curve\n * @param inTangent Start tangent of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated quaternion value\n */\n quaternionInterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) {\n return Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();\n }\n /**\n * Interpolates a Vector3 linearly\n * @param startValue Start value of the animation curve\n * @param endValue End value of the animation curve\n * @param gradient Scalar amount to interpolate (value between 0 and 1)\n * @returns Interpolated scalar value\n */\n vector3InterpolateFunction(startValue, endValue, gradient) {\n return Vector3.Lerp(startValue, endValue, gradient);\n }\n /**\n * Interpolates a Vector3 cubically\n * @param startValue Start value of the animation curve\n * @param outTangent End tangent of the animation\n * @param endValue End value of the animation curve\n * @param inTangent Start tangent of the animation curve\n * @param gradient Scalar amount to interpolate (value between 0 and 1)\n * @returns InterpolatedVector3 value\n */\n vector3InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) {\n return Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);\n }\n /**\n * Interpolates a Vector2 linearly\n * @param startValue Start value of the animation curve\n * @param endValue End value of the animation curve\n * @param gradient Scalar amount to interpolate (value between 0 and 1)\n * @returns Interpolated Vector2 value\n */\n vector2InterpolateFunction(startValue, endValue, gradient) {\n return Vector2.Lerp(startValue, endValue, gradient);\n }\n /**\n * Interpolates a Vector2 cubically\n * @param startValue Start value of the animation curve\n * @param outTangent End tangent of the animation\n * @param endValue End value of the animation curve\n * @param inTangent Start tangent of the animation curve\n * @param gradient Scalar amount to interpolate (value between 0 and 1)\n * @returns Interpolated Vector2 value\n */\n vector2InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) {\n return Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);\n }\n /**\n * Interpolates a size linearly\n * @param startValue Start value of the animation curve\n * @param endValue End value of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated Size value\n */\n sizeInterpolateFunction(startValue, endValue, gradient) {\n return Size.Lerp(startValue, endValue, gradient);\n }\n /**\n * Interpolates a Color3 linearly\n * @param startValue Start value of the animation curve\n * @param endValue End value of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated Color3 value\n */\n color3InterpolateFunction(startValue, endValue, gradient) {\n return Color3.Lerp(startValue, endValue, gradient);\n }\n /**\n * Interpolates a Color3 cubically\n * @param startValue Start value of the animation curve\n * @param outTangent End tangent of the animation\n * @param endValue End value of the animation curve\n * @param inTangent Start tangent of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns interpolated value\n */\n color3InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) {\n return Color3.Hermite(startValue, outTangent, endValue, inTangent, gradient);\n }\n /**\n * Interpolates a Color4 linearly\n * @param startValue Start value of the animation curve\n * @param endValue End value of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns Interpolated Color3 value\n */\n color4InterpolateFunction(startValue, endValue, gradient) {\n return Color4.Lerp(startValue, endValue, gradient);\n }\n /**\n * Interpolates a Color4 cubically\n * @param startValue Start value of the animation curve\n * @param outTangent End tangent of the animation\n * @param endValue End value of the animation curve\n * @param inTangent Start tangent of the animation curve\n * @param gradient Scalar amount to interpolate\n * @returns interpolated value\n */\n color4InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) {\n return Color4.Hermite(startValue, outTangent, endValue, inTangent, gradient);\n }\n /**\n * @internal Internal use only\n */\n _getKeyValue(value) {\n if (typeof value === \"function\") {\n return value();\n }\n return value;\n }\n /**\n * Evaluate the animation value at a given frame\n * @param currentFrame defines the frame where we want to evaluate the animation\n * @returns the animation value\n */\n evaluate(currentFrame) {\n return this._interpolate(currentFrame, {\n key: 0,\n repeatCount: 0,\n loopMode: Animation.ANIMATIONLOOPMODE_CONSTANT,\n });\n }\n /**\n * @internal Internal use only\n */\n _interpolate(currentFrame, state) {\n if (state.loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && state.repeatCount > 0) {\n return state.highLimitValue.clone ? state.highLimitValue.clone() : state.highLimitValue;\n }\n const keys = this._keys;\n const keysLength = keys.length;\n let key = state.key;\n while (key >= 0 && currentFrame < keys[key].frame) {\n --key;\n }\n while (key + 1 <= keysLength - 1 && currentFrame >= keys[key + 1].frame) {\n ++key;\n }\n state.key = key;\n if (key < 0) {\n return this._getKeyValue(keys[0].value);\n }\n else if (key + 1 > keysLength - 1) {\n return this._getKeyValue(keys[keysLength - 1].value);\n }\n const startKey = keys[key];\n const endKey = keys[key + 1];\n const startValue = this._getKeyValue(startKey.value);\n const endValue = this._getKeyValue(endKey.value);\n if (startKey.interpolation === AnimationKeyInterpolation.STEP) {\n if (endKey.frame > currentFrame) {\n return startValue;\n }\n else {\n return endValue;\n }\n }\n const useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;\n const frameDelta = endKey.frame - startKey.frame;\n // gradient : percent of currentFrame between the frame inf and the frame sup\n let gradient = (currentFrame - startKey.frame) / frameDelta;\n // check for easingFunction and correction of gradient\n const easingFunction = this.getEasingFunction();\n if (easingFunction !== null) {\n gradient = easingFunction.ease(gradient);\n }\n switch (this.dataType) {\n // Float\n case Animation.ANIMATIONTYPE_FLOAT: {\n const floatValue = useTangent\n ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient)\n : this.floatInterpolateFunction(startValue, endValue, gradient);\n switch (state.loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n case Animation.ANIMATIONLOOPMODE_YOYO:\n return floatValue;\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return state.offsetValue * state.repeatCount + floatValue;\n }\n break;\n }\n // Quaternion\n case Animation.ANIMATIONTYPE_QUATERNION: {\n const quatValue = useTangent\n ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient)\n : this.quaternionInterpolateFunction(startValue, endValue, gradient);\n switch (state.loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n case Animation.ANIMATIONLOOPMODE_YOYO:\n return quatValue;\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return quatValue.addInPlace(state.offsetValue.scale(state.repeatCount));\n }\n return quatValue;\n }\n // Vector3\n case Animation.ANIMATIONTYPE_VECTOR3: {\n const vec3Value = useTangent\n ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient)\n : this.vector3InterpolateFunction(startValue, endValue, gradient);\n switch (state.loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n case Animation.ANIMATIONLOOPMODE_YOYO:\n return vec3Value;\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return vec3Value.add(state.offsetValue.scale(state.repeatCount));\n }\n break;\n }\n // Vector2\n case Animation.ANIMATIONTYPE_VECTOR2: {\n const vec2Value = useTangent\n ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient)\n : this.vector2InterpolateFunction(startValue, endValue, gradient);\n switch (state.loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n case Animation.ANIMATIONLOOPMODE_YOYO:\n return vec2Value;\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return vec2Value.add(state.offsetValue.scale(state.repeatCount));\n }\n break;\n }\n // Size\n case Animation.ANIMATIONTYPE_SIZE: {\n switch (state.loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n case Animation.ANIMATIONLOOPMODE_YOYO:\n return this.sizeInterpolateFunction(startValue, endValue, gradient);\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return this.sizeInterpolateFunction(startValue, endValue, gradient).add(state.offsetValue.scale(state.repeatCount));\n }\n break;\n }\n // Color3\n case Animation.ANIMATIONTYPE_COLOR3: {\n const color3Value = useTangent\n ? this.color3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient)\n : this.color3InterpolateFunction(startValue, endValue, gradient);\n switch (state.loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n case Animation.ANIMATIONLOOPMODE_YOYO:\n return color3Value;\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return color3Value.add(state.offsetValue.scale(state.repeatCount));\n }\n break;\n }\n // Color4\n case Animation.ANIMATIONTYPE_COLOR4: {\n const color4Value = useTangent\n ? this.color4InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient)\n : this.color4InterpolateFunction(startValue, endValue, gradient);\n switch (state.loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n case Animation.ANIMATIONLOOPMODE_YOYO:\n return color4Value;\n case Animation.ANIMATIONLOOPMODE_RELATIVE:\n return color4Value.add(state.offsetValue.scale(state.repeatCount));\n }\n break;\n }\n // Matrix\n case Animation.ANIMATIONTYPE_MATRIX: {\n switch (state.loopMode) {\n case Animation.ANIMATIONLOOPMODE_CYCLE:\n case Animation.ANIMATIONLOOPMODE_CONSTANT:\n case Animation.ANIMATIONLOOPMODE_YOYO: {\n if (Animation.AllowMatricesInterpolation) {\n return this.matrixInterpolateFunction(startValue, endValue, gradient, state.workValue);\n }\n return startValue;\n }\n case Animation.ANIMATIONLOOPMODE_RELATIVE: {\n return startValue;\n }\n }\n break;\n }\n }\n return 0;\n }\n /**\n * Defines the function to use to interpolate matrices\n * @param startValue defines the start matrix\n * @param endValue defines the end matrix\n * @param gradient defines the gradient between both matrices\n * @param result defines an optional target matrix where to store the interpolation\n * @returns the interpolated matrix\n */\n matrixInterpolateFunction(startValue, endValue, gradient, result) {\n if (Animation.AllowMatrixDecomposeForInterpolation) {\n if (result) {\n Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);\n return result;\n }\n return Matrix.DecomposeLerp(startValue, endValue, gradient);\n }\n if (result) {\n Matrix.LerpToRef(startValue, endValue, gradient, result);\n return result;\n }\n return Matrix.Lerp(startValue, endValue, gradient);\n }\n /**\n * Makes a copy of the animation\n * @returns Cloned animation\n */\n clone() {\n const clone = new Animation(this.name, this.targetPropertyPath.join(\".\"), this.framePerSecond, this.dataType, this.loopMode);\n clone.enableBlending = this.enableBlending;\n clone.blendingSpeed = this.blendingSpeed;\n if (this._keys) {\n clone.setKeys(this._keys);\n }\n if (this._ranges) {\n clone._ranges = {};\n for (const name in this._ranges) {\n const range = this._ranges[name];\n if (!range) {\n continue;\n }\n clone._ranges[name] = range.clone();\n }\n }\n return clone;\n }\n /**\n * Sets the key frames of the animation\n * @param values The animation key frames to set\n */\n setKeys(values) {\n this._keys = values.slice(0);\n }\n /**\n * Serializes the animation to an object\n * @returns Serialized object\n */\n serialize() {\n const serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.property = this.targetProperty;\n serializationObject.framePerSecond = this.framePerSecond;\n serializationObject.dataType = this.dataType;\n serializationObject.loopBehavior = this.loopMode;\n serializationObject.enableBlending = this.enableBlending;\n serializationObject.blendingSpeed = this.blendingSpeed;\n const dataType = this.dataType;\n serializationObject.keys = [];\n const keys = this.getKeys();\n for (let index = 0; index < keys.length; index++) {\n const animationKey = keys[index];\n const key = {};\n key.frame = animationKey.frame;\n switch (dataType) {\n case Animation.ANIMATIONTYPE_FLOAT:\n key.values = [animationKey.value];\n if (animationKey.inTangent !== undefined) {\n key.values.push(animationKey.inTangent);\n }\n if (animationKey.outTangent !== undefined) {\n if (animationKey.inTangent === undefined) {\n key.values.push(undefined);\n }\n key.values.push(animationKey.outTangent);\n }\n if (animationKey.interpolation !== undefined) {\n if (animationKey.inTangent === undefined) {\n key.values.push(undefined);\n }\n if (animationKey.outTangent === undefined) {\n key.values.push(undefined);\n }\n key.values.push(animationKey.interpolation);\n }\n break;\n case Animation.ANIMATIONTYPE_QUATERNION:\n case Animation.ANIMATIONTYPE_MATRIX:\n case Animation.ANIMATIONTYPE_VECTOR3:\n case Animation.ANIMATIONTYPE_COLOR3:\n case Animation.ANIMATIONTYPE_COLOR4:\n key.values = animationKey.value.asArray();\n if (animationKey.inTangent != undefined) {\n key.values.push(animationKey.inTangent.asArray());\n }\n if (animationKey.outTangent != undefined) {\n if (animationKey.inTangent === undefined) {\n key.values.push(undefined);\n }\n key.values.push(animationKey.outTangent.asArray());\n }\n if (animationKey.interpolation !== undefined) {\n if (animationKey.inTangent === undefined) {\n key.values.push(undefined);\n }\n if (animationKey.outTangent === undefined) {\n key.values.push(undefined);\n }\n key.values.push(animationKey.interpolation);\n }\n break;\n }\n serializationObject.keys.push(key);\n }\n serializationObject.ranges = [];\n for (const name in this._ranges) {\n const source = this._ranges[name];\n if (!source) {\n continue;\n }\n const range = {};\n range.name = name;\n range.from = source.from;\n range.to = source.to;\n serializationObject.ranges.push(range);\n }\n return serializationObject;\n }\n /**\n * @internal\n */\n static _UniversalLerp(left, right, amount) {\n const constructor = left.constructor;\n if (constructor.Lerp) {\n // Lerp supported\n return constructor.Lerp(left, right, amount);\n }\n else if (constructor.Slerp) {\n // Slerp supported\n return constructor.Slerp(left, right, amount);\n }\n else if (left.toFixed) {\n // Number\n return left * (1.0 - amount) + amount * right;\n }\n else {\n // Blending not supported\n return right;\n }\n }\n /**\n * Parses an animation object and creates an animation\n * @param parsedAnimation Parsed animation object\n * @returns Animation object\n */\n static Parse(parsedAnimation) {\n const animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);\n const dataType = parsedAnimation.dataType;\n const keys = [];\n let data;\n let index;\n if (parsedAnimation.enableBlending) {\n animation.enableBlending = parsedAnimation.enableBlending;\n }\n if (parsedAnimation.blendingSpeed) {\n animation.blendingSpeed = parsedAnimation.blendingSpeed;\n }\n for (index = 0; index < parsedAnimation.keys.length; index++) {\n const key = parsedAnimation.keys[index];\n let inTangent = undefined;\n let outTangent = undefined;\n let interpolation = undefined;\n switch (dataType) {\n case Animation.ANIMATIONTYPE_FLOAT:\n data = key.values[0];\n if (key.values.length >= 2) {\n inTangent = key.values[1];\n }\n if (key.values.length >= 3) {\n outTangent = key.values[2];\n }\n if (key.values.length >= 4) {\n interpolation = key.values[3];\n }\n break;\n case Animation.ANIMATIONTYPE_QUATERNION:\n data = Quaternion.FromArray(key.values);\n if (key.values.length >= 8) {\n const _inTangent = Quaternion.FromArray(key.values.slice(4, 8));\n if (!_inTangent.equals(Quaternion.Zero())) {\n inTangent = _inTangent;\n }\n }\n if (key.values.length >= 12) {\n const _outTangent = Quaternion.FromArray(key.values.slice(8, 12));\n if (!_outTangent.equals(Quaternion.Zero())) {\n outTangent = _outTangent;\n }\n }\n if (key.values.length >= 13) {\n interpolation = key.values[12];\n }\n break;\n case Animation.ANIMATIONTYPE_MATRIX:\n data = Matrix.FromArray(key.values);\n if (key.values.length >= 17) {\n interpolation = key.values[16];\n }\n break;\n case Animation.ANIMATIONTYPE_COLOR3:\n data = Color3.FromArray(key.values);\n if (key.values[3]) {\n inTangent = Color3.FromArray(key.values[3]);\n }\n if (key.values[4]) {\n outTangent = Color3.FromArray(key.values[4]);\n }\n if (key.values[5]) {\n interpolation = key.values[5];\n }\n break;\n case Animation.ANIMATIONTYPE_COLOR4:\n data = Color4.FromArray(key.values);\n if (key.values[4]) {\n inTangent = Color4.FromArray(key.values[4]);\n }\n if (key.values[5]) {\n outTangent = Color4.FromArray(key.values[5]);\n }\n if (key.values[6]) {\n interpolation = Color4.FromArray(key.values[6]);\n }\n break;\n case Animation.ANIMATIONTYPE_VECTOR3:\n default:\n data = Vector3.FromArray(key.values);\n if (key.values[3]) {\n inTangent = Vector3.FromArray(key.values[3]);\n }\n if (key.values[4]) {\n outTangent = Vector3.FromArray(key.values[4]);\n }\n if (key.values[5]) {\n interpolation = key.values[5];\n }\n break;\n }\n const keyData = {};\n keyData.frame = key.frame;\n keyData.value = data;\n if (inTangent != undefined) {\n keyData.inTangent = inTangent;\n }\n if (outTangent != undefined) {\n keyData.outTangent = outTangent;\n }\n if (interpolation != undefined) {\n keyData.interpolation = interpolation;\n }\n keys.push(keyData);\n }\n animation.setKeys(keys);\n if (parsedAnimation.ranges) {\n for (index = 0; index < parsedAnimation.ranges.length; index++) {\n data = parsedAnimation.ranges[index];\n animation.createRange(data.name, data.from, data.to);\n }\n }\n return animation;\n }\n /**\n * Appends the serialized animations from the source animations\n * @param source Source containing the animations\n * @param destination Target to store the animations\n */\n static AppendSerializedAnimations(source, destination) {\n SerializationHelper.AppendSerializedAnimations(source, destination);\n }\n /**\n * Creates a new animation or an array of animations from a snippet saved in a remote file\n * @param name defines the name of the animation to create (can be null or empty to use the one from the json data)\n * @param url defines the url to load from\n * @returns a promise that will resolve to the new animation or an array of animations\n */\n static ParseFromFileAsync(name, url) {\n return new Promise((resolve, reject) => {\n const request = new WebRequest();\n request.addEventListener(\"readystatechange\", () => {\n if (request.readyState == 4) {\n if (request.status == 200) {\n let serializationObject = JSON.parse(request.responseText);\n if (serializationObject.animations) {\n serializationObject = serializationObject.animations;\n }\n if (serializationObject.length) {\n const output = new Array();\n for (const serializedAnimation of serializationObject) {\n output.push(this.Parse(serializedAnimation));\n }\n resolve(output);\n }\n else {\n const output = this.Parse(serializationObject);\n if (name) {\n output.name = name;\n }\n resolve(output);\n }\n }\n else {\n reject(\"Unable to load the animation\");\n }\n }\n });\n request.open(\"GET\", url);\n request.send();\n });\n }\n /**\n * Creates an animation or an array of animations from a snippet saved by the Inspector\n * @param snippetId defines the snippet to load\n * @returns a promise that will resolve to the new animation or a new array of animations\n */\n static ParseFromSnippetAsync(snippetId) {\n return new Promise((resolve, reject) => {\n const request = new WebRequest();\n request.addEventListener(\"readystatechange\", () => {\n if (request.readyState == 4) {\n if (request.status == 200) {\n const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload);\n if (snippet.animations) {\n const serializationObject = JSON.parse(snippet.animations);\n const outputs = new Array();\n for (const serializedAnimation of serializationObject.animations) {\n const output = this.Parse(serializedAnimation);\n output.snippetId = snippetId;\n outputs.push(output);\n }\n resolve(outputs);\n }\n else {\n const serializationObject = JSON.parse(snippet.animation);\n const output = this.Parse(serializationObject);\n output.snippetId = snippetId;\n resolve(output);\n }\n }\n else {\n reject(\"Unable to load the snippet \" + snippetId);\n }\n }\n });\n request.open(\"GET\", this.SnippetUrl + \"/\" + snippetId.replace(/#/g, \"/\"));\n request.send();\n });\n }\n}\nAnimation._UniqueIdGenerator = 0;\n/**\n * Use matrix interpolation instead of using direct key value when animating matrices\n */\nAnimation.AllowMatricesInterpolation = false;\n/**\n * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower\n */\nAnimation.AllowMatrixDecomposeForInterpolation = true;\n/** Define the Url to load snippets */\nAnimation.SnippetUrl = `https://snippet.babylonjs.com`;\n// Statics\n/**\n * Float animation type\n */\nAnimation.ANIMATIONTYPE_FLOAT = 0;\n/**\n * Vector3 animation type\n */\nAnimation.ANIMATIONTYPE_VECTOR3 = 1;\n/**\n * Quaternion animation type\n */\nAnimation.ANIMATIONTYPE_QUATERNION = 2;\n/**\n * Matrix animation type\n */\nAnimation.ANIMATIONTYPE_MATRIX = 3;\n/**\n * Color3 animation type\n */\nAnimation.ANIMATIONTYPE_COLOR3 = 4;\n/**\n * Color3 animation type\n */\nAnimation.ANIMATIONTYPE_COLOR4 = 7;\n/**\n * Vector2 animation type\n */\nAnimation.ANIMATIONTYPE_VECTOR2 = 5;\n/**\n * Size animation type\n */\nAnimation.ANIMATIONTYPE_SIZE = 6;\n/**\n * Relative Loop Mode\n */\nAnimation.ANIMATIONLOOPMODE_RELATIVE = 0;\n/**\n * Cycle Loop Mode\n */\nAnimation.ANIMATIONLOOPMODE_CYCLE = 1;\n/**\n * Constant Loop Mode\n */\nAnimation.ANIMATIONLOOPMODE_CONSTANT = 2;\n/**\n * Yoyo Loop Mode\n */\nAnimation.ANIMATIONLOOPMODE_YOYO = 4;\n/**\n * Creates an animation or an array of animations from a snippet saved by the Inspector\n * @deprecated Please use ParseFromSnippetAsync instead\n * @param snippetId defines the snippet to load\n * @returns a promise that will resolve to the new animation or a new array of animations\n */\nAnimation.CreateFromSnippetAsync = Animation.ParseFromSnippetAsync;\nRegisterClass(\"BABYLON.Animation\", Animation);\nNode._AnimationRangeFactory = (name, from, to) => new AnimationRange(name, from, to);\n//# sourceMappingURL=animation.js.map","import { Action } from \"./action.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { Vector3, Matrix, Quaternion } from \"../Maths/math.vector.js\";\nimport { Animation } from \"../Animations/animation.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\n/**\n * This defines an action responsible to change the value of a property\n * by interpolating between its current value and the newly set one once triggered.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\nexport class InterpolateValueAction extends Action {\n /**\n * Instantiate the action\n * @param triggerOptions defines the trigger options\n * @param target defines the object containing the value to interpolate\n * @param propertyPath defines the path to the property in the target object\n * @param value defines the target value at the end of the interpolation\n * @param duration defines the time it will take for the property to interpolate to the value.\n * @param condition defines the trigger related conditions\n * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered\n * @param onInterpolationDone defines a callback raised once the interpolation animation has been done\n */\n constructor(triggerOptions, target, propertyPath, value, duration = 1000, condition, stopOtherAnimations, onInterpolationDone) {\n super(triggerOptions, condition);\n /**\n * Defines the time it will take for the property to interpolate to the value.\n */\n this.duration = 1000;\n /**\n * Observable triggered once the interpolation animation has been done.\n */\n this.onInterpolationDoneObservable = new Observable();\n this.propertyPath = propertyPath;\n this.value = value;\n this.duration = duration;\n this.stopOtherAnimations = stopOtherAnimations;\n this.onInterpolationDone = onInterpolationDone;\n this._target = this._effectiveTarget = target;\n }\n /** @internal */\n _prepare() {\n this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);\n this._property = this._getProperty(this.propertyPath);\n }\n /**\n * Execute the action starts the value interpolation.\n */\n execute() {\n const scene = this._actionManager.getScene();\n const keys = [\n {\n frame: 0,\n value: this._effectiveTarget[this._property],\n },\n {\n frame: 100,\n value: this.value,\n },\n ];\n let dataType;\n if (typeof this.value === \"number\") {\n dataType = Animation.ANIMATIONTYPE_FLOAT;\n }\n else if (this.value instanceof Color3) {\n dataType = Animation.ANIMATIONTYPE_COLOR3;\n }\n else if (this.value instanceof Vector3) {\n dataType = Animation.ANIMATIONTYPE_VECTOR3;\n }\n else if (this.value instanceof Matrix) {\n dataType = Animation.ANIMATIONTYPE_MATRIX;\n }\n else if (this.value instanceof Quaternion) {\n dataType = Animation.ANIMATIONTYPE_QUATERNION;\n }\n else {\n Logger.Warn(\"InterpolateValueAction: Unsupported type (\" + typeof this.value + \")\");\n return;\n }\n const animation = new Animation(\"InterpolateValueAction\", this._property, 100 * (1000.0 / this.duration), dataType, Animation.ANIMATIONLOOPMODE_CONSTANT);\n animation.setKeys(keys);\n if (this.stopOtherAnimations) {\n scene.stopAnimation(this._effectiveTarget);\n }\n const wrapper = () => {\n this.onInterpolationDoneObservable.notifyObservers(this);\n if (this.onInterpolationDone) {\n this.onInterpolationDone();\n }\n };\n scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);\n }\n /**\n * Serializes the actions and its related information.\n * @param parent defines the object to serialize in\n * @returns the serialized object\n */\n serialize(parent) {\n return super._serialize({\n name: \"InterpolateValueAction\",\n properties: [\n Action._GetTargetProperty(this._target),\n { name: \"propertyPath\", value: this.propertyPath },\n { name: \"value\", value: Action._SerializeValueAsString(this.value) },\n { name: \"duration\", value: Action._SerializeValueAsString(this.duration) },\n { name: \"stopOtherAnimations\", value: Action._SerializeValueAsString(this.stopOtherAnimations) || false },\n ],\n }, parent);\n }\n}\nRegisterClass(\"BABYLON.InterpolateValueAction\", InterpolateValueAction);\n//# sourceMappingURL=interpolateValueAction.js.map","import { Quaternion, Vector3, Vector2, Matrix } from \"../Maths/math.vector.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { Animation } from \"./animation.js\";\nimport { Size } from \"../Maths/math.size.js\";\n// Static values to help the garbage collector\n// Quaternion\nconst _staticOffsetValueQuaternion = Object.freeze(new Quaternion(0, 0, 0, 0));\n// Vector3\nconst _staticOffsetValueVector3 = Object.freeze(Vector3.Zero());\n// Vector2\nconst _staticOffsetValueVector2 = Object.freeze(Vector2.Zero());\n// Size\nconst _staticOffsetValueSize = Object.freeze(Size.Zero());\n// Color3\nconst _staticOffsetValueColor3 = Object.freeze(Color3.Black());\n/**\n * Defines a runtime animation\n */\nexport class RuntimeAnimation {\n /**\n * Gets the current frame of the runtime animation\n */\n get currentFrame() {\n return this._currentFrame;\n }\n /**\n * Gets the weight of the runtime animation\n */\n get weight() {\n return this._weight;\n }\n /**\n * Gets the current value of the runtime animation\n */\n get currentValue() {\n return this._currentValue;\n }\n /**\n * Gets or sets the target path of the runtime animation\n */\n get targetPath() {\n return this._targetPath;\n }\n /**\n * Gets the actual target of the runtime animation\n */\n get target() {\n return this._currentActiveTarget;\n }\n /**\n * Gets the additive state of the runtime animation\n */\n get isAdditive() {\n return this._host && this._host.isAdditive;\n }\n /**\n * Create a new RuntimeAnimation object\n * @param target defines the target of the animation\n * @param animation defines the source animation object\n * @param scene defines the hosting scene\n * @param host defines the initiating Animatable\n */\n constructor(target, animation, scene, host) {\n this._events = new Array();\n /**\n * The current frame of the runtime animation\n */\n this._currentFrame = 0;\n /**\n * The original value of the runtime animation\n */\n this._originalValue = new Array();\n /**\n * The original blend value of the runtime animation\n */\n this._originalBlendValue = null;\n /**\n * The offsets cache of the runtime animation\n */\n this._offsetsCache = {};\n /**\n * The high limits cache of the runtime animation\n */\n this._highLimitsCache = {};\n /**\n * Specifies if the runtime animation has been stopped\n */\n this._stopped = false;\n /**\n * The blending factor of the runtime animation\n */\n this._blendingFactor = 0;\n /**\n * The current value of the runtime animation\n */\n this._currentValue = null;\n this._currentActiveTarget = null;\n this._directTarget = null;\n /**\n * The target path of the runtime animation\n */\n this._targetPath = \"\";\n /**\n * The weight of the runtime animation\n */\n this._weight = 1.0;\n /**\n * The ratio offset of the runtime animation\n */\n this._ratioOffset = 0;\n /**\n * The previous delay of the runtime animation\n */\n this._previousDelay = 0;\n /**\n * The previous ratio of the runtime animation\n */\n this._previousRatio = 0;\n this._targetIsArray = false;\n this._animation = animation;\n this._target = target;\n this._scene = scene;\n this._host = host;\n this._activeTargets = [];\n animation._runtimeAnimations.push(this);\n // State\n this._animationState = {\n key: 0,\n repeatCount: 0,\n loopMode: this._getCorrectLoopMode(),\n };\n if (this._animation.dataType === Animation.ANIMATIONTYPE_MATRIX) {\n this._animationState.workValue = Matrix.Zero();\n }\n // Limits\n this._keys = this._animation.getKeys();\n this._minFrame = this._keys[0].frame;\n this._maxFrame = this._keys[this._keys.length - 1].frame;\n this._minValue = this._keys[0].value;\n this._maxValue = this._keys[this._keys.length - 1].value;\n // Add a start key at frame 0 if missing\n if (this._minFrame !== 0) {\n const newKey = { frame: 0, value: this._minValue };\n this._keys.splice(0, 0, newKey);\n }\n // Check data\n if (this._target instanceof Array) {\n let index = 0;\n for (const target of this._target) {\n this._preparePath(target, index);\n this._getOriginalValues(index);\n index++;\n }\n this._targetIsArray = true;\n }\n else {\n this._preparePath(this._target);\n this._getOriginalValues();\n this._targetIsArray = false;\n this._directTarget = this._activeTargets[0];\n }\n // Cloning events locally\n const events = animation.getEvents();\n if (events && events.length > 0) {\n events.forEach((e) => {\n this._events.push(e._clone());\n });\n }\n this._enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;\n }\n _preparePath(target, targetIndex = 0) {\n const targetPropertyPath = this._animation.targetPropertyPath;\n if (targetPropertyPath.length > 1) {\n let property = target[targetPropertyPath[0]];\n for (let index = 1; index < targetPropertyPath.length - 1; index++) {\n property = property[targetPropertyPath[index]];\n }\n this._targetPath = targetPropertyPath[targetPropertyPath.length - 1];\n this._activeTargets[targetIndex] = property;\n }\n else {\n this._targetPath = targetPropertyPath[0];\n this._activeTargets[targetIndex] = target;\n }\n }\n /**\n * Gets the animation from the runtime animation\n */\n get animation() {\n return this._animation;\n }\n /**\n * Resets the runtime animation to the beginning\n * @param restoreOriginal defines whether to restore the target property to the original value\n */\n reset(restoreOriginal = false) {\n if (restoreOriginal) {\n if (this._target instanceof Array) {\n let index = 0;\n for (const target of this._target) {\n if (this._originalValue[index] !== undefined) {\n this._setValue(target, this._activeTargets[index], this._originalValue[index], -1, index);\n }\n index++;\n }\n }\n else {\n if (this._originalValue[0] !== undefined) {\n this._setValue(this._target, this._directTarget, this._originalValue[0], -1, 0);\n }\n }\n }\n this._offsetsCache = {};\n this._highLimitsCache = {};\n this._currentFrame = 0;\n this._blendingFactor = 0;\n // Events\n for (let index = 0; index < this._events.length; index++) {\n this._events[index].isDone = false;\n }\n }\n /**\n * Specifies if the runtime animation is stopped\n * @returns Boolean specifying if the runtime animation is stopped\n */\n isStopped() {\n return this._stopped;\n }\n /**\n * Disposes of the runtime animation\n */\n dispose() {\n const index = this._animation.runtimeAnimations.indexOf(this);\n if (index > -1) {\n this._animation.runtimeAnimations.splice(index, 1);\n }\n }\n /**\n * Apply the interpolated value to the target\n * @param currentValue defines the value computed by the animation\n * @param weight defines the weight to apply to this value (Defaults to 1.0)\n */\n setValue(currentValue, weight) {\n if (this._targetIsArray) {\n for (let index = 0; index < this._target.length; index++) {\n const target = this._target[index];\n this._setValue(target, this._activeTargets[index], currentValue, weight, index);\n }\n return;\n }\n this._setValue(this._target, this._directTarget, currentValue, weight, 0);\n }\n _getOriginalValues(targetIndex = 0) {\n let originalValue;\n const target = this._activeTargets[targetIndex];\n if (target.getRestPose && this._targetPath === \"_matrix\") {\n // For bones\n originalValue = target.getRestPose();\n }\n else {\n originalValue = target[this._targetPath];\n }\n if (originalValue && originalValue.clone) {\n this._originalValue[targetIndex] = originalValue.clone();\n }\n else {\n this._originalValue[targetIndex] = originalValue;\n }\n }\n _setValue(target, destination, currentValue, weight, targetIndex) {\n // Set value\n this._currentActiveTarget = destination;\n this._weight = weight;\n if (this._enableBlending && this._blendingFactor <= 1.0) {\n if (!this._originalBlendValue) {\n const originalValue = destination[this._targetPath];\n if (originalValue.clone) {\n this._originalBlendValue = originalValue.clone();\n }\n else {\n this._originalBlendValue = originalValue;\n }\n }\n if (this._originalBlendValue.m) {\n // Matrix\n if (Animation.AllowMatrixDecomposeForInterpolation) {\n if (this._currentValue) {\n Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);\n }\n else {\n this._currentValue = Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);\n }\n }\n else {\n if (this._currentValue) {\n Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);\n }\n else {\n this._currentValue = Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);\n }\n }\n }\n else {\n this._currentValue = Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);\n }\n const blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;\n this._blendingFactor += blendingSpeed;\n }\n else {\n if (!this._currentValue) {\n if (currentValue === null || currentValue === void 0 ? void 0 : currentValue.clone) {\n this._currentValue = currentValue.clone();\n }\n else {\n this._currentValue = currentValue;\n }\n }\n else if (this._currentValue.copyFrom) {\n this._currentValue.copyFrom(currentValue);\n }\n else {\n this._currentValue = currentValue;\n }\n }\n if (weight !== -1.0) {\n this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);\n }\n else {\n destination[this._targetPath] = this._currentValue;\n }\n if (target.markAsDirty) {\n target.markAsDirty(this._animation.targetProperty);\n }\n }\n /**\n * Gets the loop pmode of the runtime animation\n * @returns Loop Mode\n */\n _getCorrectLoopMode() {\n if (this._target && this._target.animationPropertiesOverride) {\n return this._target.animationPropertiesOverride.loopMode;\n }\n return this._animation.loopMode;\n }\n /**\n * Move the current animation to a given frame\n * @param frame defines the frame to move to\n */\n goToFrame(frame) {\n const keys = this._animation.getKeys();\n if (frame < keys[0].frame) {\n frame = keys[0].frame;\n }\n else if (frame > keys[keys.length - 1].frame) {\n frame = keys[keys.length - 1].frame;\n }\n // Need to reset animation events\n const events = this._events;\n if (events.length) {\n for (let index = 0; index < events.length; index++) {\n if (!events[index].onlyOnce) {\n // reset events in the future\n events[index].isDone = events[index].frame < frame;\n }\n }\n }\n this._currentFrame = frame;\n const currentValue = this._animation._interpolate(frame, this._animationState);\n this.setValue(currentValue, -1);\n }\n /**\n * @internal Internal use only\n */\n _prepareForSpeedRatioChange(newSpeedRatio) {\n const newRatio = (this._previousDelay * (this._animation.framePerSecond * newSpeedRatio)) / 1000.0;\n this._ratioOffset = this._previousRatio - newRatio;\n }\n /**\n * Execute the current animation\n * @param delay defines the delay to add to the current frame\n * @param from defines the lower bound of the animation range\n * @param to defines the upper bound of the animation range\n * @param loop defines if the current animation must loop\n * @param speedRatio defines the current speed ratio\n * @param weight defines the weight of the animation (default is -1 so no weight)\n * @returns a boolean indicating if the animation is running\n */\n animate(delay, from, to, loop, speedRatio, weight = -1.0) {\n const animation = this._animation;\n const targetPropertyPath = animation.targetPropertyPath;\n if (!targetPropertyPath || targetPropertyPath.length < 1) {\n this._stopped = true;\n return false;\n }\n let returnValue = true;\n // Check limits\n if (from < this._minFrame || from > this._maxFrame) {\n from = this._minFrame;\n }\n if (to < this._minFrame || to > this._maxFrame) {\n to = this._maxFrame;\n }\n const range = to - from;\n let offsetValue;\n // Compute ratio which represents the frame delta between from and to\n let ratio = (delay * (animation.framePerSecond * speedRatio)) / 1000.0 + this._ratioOffset;\n let highLimitValue = 0;\n // Apply the yoyo function if required\n if (loop && this._animationState.loopMode === Animation.ANIMATIONLOOPMODE_YOYO) {\n const position = (ratio - from) / range;\n // Apply the yoyo curve\n const yoyoPosition = Math.abs(Math.sin(position * Math.PI));\n // Map the yoyo position back to the range\n ratio = yoyoPosition * range + from;\n }\n this._previousDelay = delay;\n this._previousRatio = ratio;\n if (!loop && to >= from && ratio >= range) {\n // If we are out of range and not looping get back to caller\n returnValue = false;\n highLimitValue = animation._getKeyValue(this._maxValue);\n }\n else if (!loop && from >= to && ratio <= range) {\n returnValue = false;\n highLimitValue = animation._getKeyValue(this._minValue);\n }\n else if (this._animationState.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {\n const keyOffset = to.toString() + from.toString();\n if (!this._offsetsCache[keyOffset]) {\n this._animationState.repeatCount = 0;\n this._animationState.loopMode = Animation.ANIMATIONLOOPMODE_CYCLE;\n const fromValue = animation._interpolate(from, this._animationState);\n const toValue = animation._interpolate(to, this._animationState);\n this._animationState.loopMode = this._getCorrectLoopMode();\n switch (animation.dataType) {\n // Float\n case Animation.ANIMATIONTYPE_FLOAT:\n this._offsetsCache[keyOffset] = toValue - fromValue;\n break;\n // Quaternion\n case Animation.ANIMATIONTYPE_QUATERNION:\n this._offsetsCache[keyOffset] = toValue.subtract(fromValue);\n break;\n // Vector3\n case Animation.ANIMATIONTYPE_VECTOR3:\n this._offsetsCache[keyOffset] = toValue.subtract(fromValue);\n break;\n // Vector2\n case Animation.ANIMATIONTYPE_VECTOR2:\n this._offsetsCache[keyOffset] = toValue.subtract(fromValue);\n break;\n // Size\n case Animation.ANIMATIONTYPE_SIZE:\n this._offsetsCache[keyOffset] = toValue.subtract(fromValue);\n break;\n // Color3\n case Animation.ANIMATIONTYPE_COLOR3:\n this._offsetsCache[keyOffset] = toValue.subtract(fromValue);\n break;\n default:\n break;\n }\n this._highLimitsCache[keyOffset] = toValue;\n }\n highLimitValue = this._highLimitsCache[keyOffset];\n offsetValue = this._offsetsCache[keyOffset];\n }\n if (offsetValue === undefined) {\n switch (animation.dataType) {\n // Float\n case Animation.ANIMATIONTYPE_FLOAT:\n offsetValue = 0;\n break;\n // Quaternion\n case Animation.ANIMATIONTYPE_QUATERNION:\n offsetValue = _staticOffsetValueQuaternion;\n break;\n // Vector3\n case Animation.ANIMATIONTYPE_VECTOR3:\n offsetValue = _staticOffsetValueVector3;\n break;\n // Vector2\n case Animation.ANIMATIONTYPE_VECTOR2:\n offsetValue = _staticOffsetValueVector2;\n break;\n // Size\n case Animation.ANIMATIONTYPE_SIZE:\n offsetValue = _staticOffsetValueSize;\n break;\n // Color3\n case Animation.ANIMATIONTYPE_COLOR3:\n offsetValue = _staticOffsetValueColor3;\n }\n }\n // Compute value\n let currentFrame;\n if (this._host && this._host.syncRoot) {\n const syncRoot = this._host.syncRoot;\n const hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);\n currentFrame = from + (to - from) * hostNormalizedFrame;\n }\n else {\n if ((ratio > 0 && from > to) || (ratio < 0 && from < to)) {\n currentFrame = returnValue && range !== 0 ? to + (ratio % range) : from;\n }\n else {\n currentFrame = returnValue && range !== 0 ? from + (ratio % range) : to;\n }\n }\n const events = this._events;\n // Reset event/state if looping\n if ((speedRatio > 0 && this.currentFrame > currentFrame) || (speedRatio < 0 && this.currentFrame < currentFrame)) {\n this._onLoop();\n // Need to reset animation events\n for (let index = 0; index < events.length; index++) {\n if (!events[index].onlyOnce) {\n // reset event, the animation is looping\n events[index].isDone = false;\n }\n }\n this._animationState.key = speedRatio > 0 ? 0 : animation.getKeys().length - 1;\n }\n this._currentFrame = currentFrame;\n this._animationState.repeatCount = range === 0 ? 0 : (ratio / range) >> 0;\n this._animationState.highLimitValue = highLimitValue;\n this._animationState.offsetValue = offsetValue;\n const currentValue = animation._interpolate(currentFrame, this._animationState);\n // Set value\n this.setValue(currentValue, weight);\n // Check events\n if (events.length) {\n for (let index = 0; index < events.length; index++) {\n // Make sure current frame has passed event frame and that event frame is within the current range\n // Also, handle both forward and reverse animations\n if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||\n (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {\n const event = events[index];\n if (!event.isDone) {\n // If event should be done only once, remove it.\n if (event.onlyOnce) {\n events.splice(index, 1);\n index--;\n }\n event.isDone = true;\n event.action(currentFrame);\n } // Don't do anything if the event has already be done.\n }\n }\n }\n if (!returnValue) {\n this._stopped = true;\n }\n return returnValue;\n }\n}\n//# sourceMappingURL=runtimeAnimation.js.map","import { Vector3, Quaternion, Matrix, TmpVectors } from \"../Maths/math.vector.js\";\nimport { ArrayTools } from \"../Misc/arrayTools.js\";\nimport { Node } from \"../node.js\";\nimport { Space } from \"../Maths/math.axis.js\";\n/**\n * Class used to store bone information\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons\n */\nexport class Bone extends Node {\n /** @internal */\n get _matrix() {\n this._compose();\n return this._localMatrix;\n }\n /** @internal */\n set _matrix(value) {\n this._needToCompose = false; // in case there was a pending compose\n // skip if the matrices are the same\n if (value.updateFlag === this._localMatrix.updateFlag) {\n return;\n }\n this._localMatrix.copyFrom(value);\n this._markAsDirtyAndDecompose();\n }\n /**\n * Create a new bone\n * @param name defines the bone name\n * @param skeleton defines the parent skeleton\n * @param parentBone defines the parent (can be null if the bone is the root)\n * @param localMatrix defines the local matrix (default: identity)\n * @param restMatrix defines the rest matrix (default: localMatrix)\n * @param bindMatrix defines the bind matrix (default: localMatrix)\n * @param index defines index of the bone in the hierarchy (default: null)\n */\n constructor(\n /**\n * defines the bone name\n */\n name, skeleton, parentBone = null, localMatrix = null, restMatrix = null, bindMatrix = null, index = null) {\n var _a;\n super(name, skeleton.getScene());\n this.name = name;\n /**\n * Gets the list of child bones\n */\n this.children = new Array();\n /** Gets the animations associated with this bone */\n this.animations = new Array();\n /**\n * @internal Internal only\n * Set this value to map this bone to a different index in the transform matrices\n * Set this value to -1 to exclude the bone from the transform matrices\n */\n this._index = null;\n this._scalingDeterminant = 1;\n this._needToDecompose = true;\n this._needToCompose = false;\n /** @internal */\n this._linkedTransformNode = null;\n /** @internal */\n this._waitingTransformNodeId = null;\n this._skeleton = skeleton;\n this._localMatrix = (_a = localMatrix === null || localMatrix === void 0 ? void 0 : localMatrix.clone()) !== null && _a !== void 0 ? _a : Matrix.Identity();\n this._restMatrix = restMatrix !== null && restMatrix !== void 0 ? restMatrix : this._localMatrix.clone();\n this._bindMatrix = bindMatrix !== null && bindMatrix !== void 0 ? bindMatrix : this._localMatrix.clone();\n this._index = index;\n this._absoluteMatrix = new Matrix();\n this._absoluteBindMatrix = new Matrix();\n this._absoluteInverseBindMatrix = new Matrix();\n this._finalMatrix = new Matrix();\n skeleton.bones.push(this);\n this.setParent(parentBone, false);\n this._updateAbsoluteBindMatrices();\n }\n /**\n * Gets the current object class name.\n * @returns the class name\n */\n getClassName() {\n return \"Bone\";\n }\n // Members\n /**\n * Gets the parent skeleton\n * @returns a skeleton\n */\n getSkeleton() {\n return this._skeleton;\n }\n get parent() {\n return this._parentNode;\n }\n /**\n * Gets parent bone\n * @returns a bone or null if the bone is the root of the bone hierarchy\n */\n getParent() {\n return this.parent;\n }\n /**\n * Returns an array containing the children of the bone\n * @returns an array containing the children of the bone (can be empty if the bone has no children)\n */\n getChildren() {\n return this.children;\n }\n /**\n * Gets the node index in matrix array generated for rendering\n * @returns the node index\n */\n getIndex() {\n return this._index === null ? this.getSkeleton().bones.indexOf(this) : this._index;\n }\n set parent(newParent) {\n this.setParent(newParent);\n }\n /**\n * Sets the parent bone\n * @param parent defines the parent (can be null if the bone is the root)\n * @param updateAbsoluteBindMatrices defines if the absolute bind and absolute inverse bind matrices must be updated\n */\n setParent(parent, updateAbsoluteBindMatrices = true) {\n if (this.parent === parent) {\n return;\n }\n if (this.parent) {\n const index = this.parent.children.indexOf(this);\n if (index !== -1) {\n this.parent.children.splice(index, 1);\n }\n }\n this._parentNode = parent;\n if (this.parent) {\n this.parent.children.push(this);\n }\n if (updateAbsoluteBindMatrices) {\n this._updateAbsoluteBindMatrices();\n }\n this.markAsDirty();\n }\n /**\n * Gets the local matrix\n * @returns the local matrix\n */\n getLocalMatrix() {\n this._compose();\n return this._localMatrix;\n }\n /**\n * Gets the bind matrix\n * @returns the bind matrix\n */\n getBindMatrix() {\n return this._bindMatrix;\n }\n /**\n * Gets the bind matrix.\n * @returns the bind matrix\n * @deprecated Please use getBindMatrix instead\n */\n getBaseMatrix() {\n return this.getBindMatrix();\n }\n /**\n * Gets the rest matrix\n * @returns the rest matrix\n */\n getRestMatrix() {\n return this._restMatrix;\n }\n /**\n * Gets the rest matrix\n * @returns the rest matrix\n * @deprecated Please use getRestMatrix instead\n */\n getRestPose() {\n return this.getRestMatrix();\n }\n /**\n * Sets the rest matrix\n * @param matrix the local-space rest matrix to set for this bone\n */\n setRestMatrix(matrix) {\n this._restMatrix.copyFrom(matrix);\n }\n /**\n * Sets the rest matrix\n * @param matrix the local-space rest to set for this bone\n * @deprecated Please use setRestMatrix instead\n */\n setRestPose(matrix) {\n this.setRestMatrix(matrix);\n }\n /**\n * Gets the bind matrix\n * @returns the bind matrix\n * @deprecated Please use getBindMatrix instead\n */\n getBindPose() {\n return this.getBindMatrix();\n }\n /**\n * Sets the bind matrix\n * This will trigger a recomputation of the absolute bind and absolute inverse bind matrices for this bone and its children\n * Note that the local matrix will also be set with the matrix passed in parameter!\n * @param matrix the local-space bind matrix to set for this bone\n */\n setBindMatrix(matrix) {\n this.updateMatrix(matrix);\n }\n /**\n * Sets the bind matrix\n * @param matrix the local-space bind to set for this bone\n * @deprecated Please use setBindMatrix instead\n */\n setBindPose(matrix) {\n this.setBindMatrix(matrix);\n }\n /**\n * Gets the matrix used to store the final world transformation of the bone (ie. the matrix sent to shaders)\n */\n getFinalMatrix() {\n return this._finalMatrix;\n }\n /**\n * Gets the matrix used to store the final world transformation of the bone (ie. the matrix sent to shaders)\n * @deprecated Please use getFinalMatrix instead\n */\n getWorldMatrix() {\n return this.getFinalMatrix();\n }\n /**\n * Sets the local matrix to the rest matrix\n */\n returnToRest() {\n var _a;\n if (this._linkedTransformNode) {\n const localScaling = TmpVectors.Vector3[0];\n const localRotation = TmpVectors.Quaternion[0];\n const localPosition = TmpVectors.Vector3[1];\n this.getRestMatrix().decompose(localScaling, localRotation, localPosition);\n this._linkedTransformNode.position.copyFrom(localPosition);\n this._linkedTransformNode.rotationQuaternion = (_a = this._linkedTransformNode.rotationQuaternion) !== null && _a !== void 0 ? _a : Quaternion.Identity();\n this._linkedTransformNode.rotationQuaternion.copyFrom(localRotation);\n this._linkedTransformNode.scaling.copyFrom(localScaling);\n }\n else {\n this._matrix = this._restMatrix;\n }\n }\n /**\n * Gets the inverse of the bind matrix, in world space (relative to the skeleton root)\n * @returns the inverse bind matrix, in world space\n */\n getAbsoluteInverseBindMatrix() {\n return this._absoluteInverseBindMatrix;\n }\n /**\n * Gets the inverse of the bind matrix, in world space (relative to the skeleton root)\n * @returns the inverse bind matrix, in world space\n * @deprecated Please use getAbsoluteInverseBindMatrix instead\n */\n getInvertedAbsoluteTransform() {\n return this.getAbsoluteInverseBindMatrix();\n }\n /**\n * Gets the bone matrix, in world space (relative to the skeleton root)\n * @returns the bone matrix, in world space\n */\n getAbsoluteMatrix() {\n return this._absoluteMatrix;\n }\n /**\n * Gets the bone matrix, in world space (relative to the skeleton root)\n * @returns the bone matrix, in world space\n * @deprecated Please use getAbsoluteMatrix instead\n */\n getAbsoluteTransform() {\n return this._absoluteMatrix;\n }\n /**\n * Links with the given transform node.\n * The local matrix of this bone is overwritten by the transform of the node every frame.\n * @param transformNode defines the transform node to link to\n */\n linkTransformNode(transformNode) {\n if (this._linkedTransformNode) {\n this._skeleton._numBonesWithLinkedTransformNode--;\n }\n this._linkedTransformNode = transformNode;\n if (this._linkedTransformNode) {\n this._skeleton._numBonesWithLinkedTransformNode++;\n }\n }\n // Properties (matches TransformNode properties)\n /**\n * Gets the node used to drive the bone's transformation\n * @returns a transform node or null\n */\n getTransformNode() {\n return this._linkedTransformNode;\n }\n /** Gets or sets current position (in local space) */\n get position() {\n this._decompose();\n return this._localPosition;\n }\n set position(newPosition) {\n this._decompose();\n this._localPosition.copyFrom(newPosition);\n this._markAsDirtyAndCompose();\n }\n /** Gets or sets current rotation (in local space) */\n get rotation() {\n return this.getRotation();\n }\n set rotation(newRotation) {\n this.setRotation(newRotation);\n }\n /** Gets or sets current rotation quaternion (in local space) */\n get rotationQuaternion() {\n this._decompose();\n return this._localRotation;\n }\n set rotationQuaternion(newRotation) {\n this.setRotationQuaternion(newRotation);\n }\n /** Gets or sets current scaling (in local space) */\n get scaling() {\n return this.getScale();\n }\n set scaling(newScaling) {\n this.setScale(newScaling);\n }\n /**\n * Gets the animation properties override\n */\n get animationPropertiesOverride() {\n return this._skeleton.animationPropertiesOverride;\n }\n // Methods\n _decompose() {\n if (!this._needToDecompose) {\n return;\n }\n this._needToDecompose = false;\n if (!this._localScaling) {\n this._localScaling = Vector3.Zero();\n this._localRotation = Quaternion.Zero();\n this._localPosition = Vector3.Zero();\n }\n this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);\n }\n _compose() {\n if (!this._needToCompose) {\n return;\n }\n if (!this._localScaling) {\n this._needToCompose = false;\n return;\n }\n this._needToCompose = false;\n Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);\n }\n /**\n * Update the bind (and optionally the local) matrix\n * @param bindMatrix defines the new matrix to set to the bind/local matrix, in local space\n * @param updateAbsoluteBindMatrices defines if the absolute bind and absolute inverse bind matrices must be recomputed (default: true)\n * @param updateLocalMatrix defines if the local matrix should also be updated with the matrix passed in parameter (default: true)\n */\n updateMatrix(bindMatrix, updateAbsoluteBindMatrices = true, updateLocalMatrix = true) {\n this._bindMatrix.copyFrom(bindMatrix);\n if (updateAbsoluteBindMatrices) {\n this._updateAbsoluteBindMatrices();\n }\n if (updateLocalMatrix) {\n this._matrix = bindMatrix;\n }\n else {\n this.markAsDirty();\n }\n }\n /**\n * @internal\n */\n _updateAbsoluteBindMatrices(bindMatrix, updateChildren = true) {\n if (!bindMatrix) {\n bindMatrix = this._bindMatrix;\n }\n if (this.parent) {\n bindMatrix.multiplyToRef(this.parent._absoluteBindMatrix, this._absoluteBindMatrix);\n }\n else {\n this._absoluteBindMatrix.copyFrom(bindMatrix);\n }\n this._absoluteBindMatrix.invertToRef(this._absoluteInverseBindMatrix);\n if (updateChildren) {\n for (let index = 0; index < this.children.length; index++) {\n this.children[index]._updateAbsoluteBindMatrices();\n }\n }\n this._scalingDeterminant = this._absoluteBindMatrix.determinant() < 0 ? -1 : 1;\n }\n /**\n * Flag the bone as dirty (Forcing it to update everything)\n * @returns this bone\n */\n markAsDirty() {\n this._currentRenderId++;\n this._childUpdateId++;\n this._skeleton._markAsDirty();\n return this;\n }\n /** @internal */\n _markAsDirtyAndCompose() {\n this.markAsDirty();\n this._needToCompose = true;\n }\n _markAsDirtyAndDecompose() {\n this.markAsDirty();\n this._needToDecompose = true;\n }\n _updatePosition(vec, space = Space.LOCAL, tNode, translationMode = true) {\n const lm = this.getLocalMatrix();\n if (space == Space.LOCAL) {\n if (translationMode) {\n lm.addAtIndex(12, vec.x);\n lm.addAtIndex(13, vec.y);\n lm.addAtIndex(14, vec.z);\n }\n else {\n lm.setTranslationFromFloats(vec.x, vec.y, vec.z);\n }\n }\n else {\n let wm = null;\n //tNode.getWorldMatrix() needs to be called before skeleton.computeAbsoluteMatrices()\n if (tNode) {\n wm = tNode.getWorldMatrix();\n }\n this._skeleton.computeAbsoluteMatrices();\n const tmat = Bone._TmpMats[0];\n const tvec = Bone._TmpVecs[0];\n if (this.parent) {\n if (tNode && wm) {\n tmat.copyFrom(this.parent.getAbsoluteMatrix());\n tmat.multiplyToRef(wm, tmat);\n }\n else {\n tmat.copyFrom(this.parent.getAbsoluteMatrix());\n }\n }\n else {\n Matrix.IdentityToRef(tmat);\n }\n if (translationMode) {\n tmat.setTranslationFromFloats(0, 0, 0);\n }\n tmat.invert();\n Vector3.TransformCoordinatesToRef(vec, tmat, tvec);\n if (translationMode) {\n lm.addAtIndex(12, tvec.x);\n lm.addAtIndex(13, tvec.y);\n lm.addAtIndex(14, tvec.z);\n }\n else {\n lm.setTranslationFromFloats(tvec.x, tvec.y, tvec.z);\n }\n }\n this._markAsDirtyAndDecompose();\n }\n /**\n * Translate the bone in local or world space\n * @param vec The amount to translate the bone\n * @param space The space that the translation is in (default: Space.LOCAL)\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n */\n translate(vec, space = Space.LOCAL, tNode) {\n this._updatePosition(vec, space, tNode, true);\n }\n /**\n * Set the position of the bone in local or world space\n * @param position The position to set the bone\n * @param space The space that the position is in (default: Space.LOCAL)\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n */\n setPosition(position, space = Space.LOCAL, tNode) {\n this._updatePosition(position, space, tNode, false);\n }\n /**\n * Set the absolute position of the bone (world space)\n * @param position The position to set the bone\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n */\n setAbsolutePosition(position, tNode) {\n this.setPosition(position, Space.WORLD, tNode);\n }\n /**\n * Scale the bone on the x, y and z axes (in local space)\n * @param x The amount to scale the bone on the x axis\n * @param y The amount to scale the bone on the y axis\n * @param z The amount to scale the bone on the z axis\n * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)\n */\n scale(x, y, z, scaleChildren = false) {\n const locMat = this.getLocalMatrix();\n // Apply new scaling on top of current local matrix\n const scaleMat = Bone._TmpMats[0];\n Matrix.ScalingToRef(x, y, z, scaleMat);\n scaleMat.multiplyToRef(locMat, locMat);\n // Invert scaling matrix and apply the inverse to all children\n scaleMat.invert();\n for (const child of this.children) {\n const cm = child.getLocalMatrix();\n cm.multiplyToRef(scaleMat, cm);\n cm.multiplyAtIndex(12, x);\n cm.multiplyAtIndex(13, y);\n cm.multiplyAtIndex(14, z);\n child._markAsDirtyAndDecompose();\n }\n this._markAsDirtyAndDecompose();\n if (scaleChildren) {\n for (const child of this.children) {\n child.scale(x, y, z, scaleChildren);\n }\n }\n }\n /**\n * Set the bone scaling in local space\n * @param scale defines the scaling vector\n */\n setScale(scale) {\n this._decompose();\n this._localScaling.copyFrom(scale);\n this._markAsDirtyAndCompose();\n }\n /**\n * Gets the current scaling in local space\n * @returns the current scaling vector\n */\n getScale() {\n this._decompose();\n return this._localScaling;\n }\n /**\n * Gets the current scaling in local space and stores it in a target vector\n * @param result defines the target vector\n */\n getScaleToRef(result) {\n this._decompose();\n result.copyFrom(this._localScaling);\n }\n /**\n * Set the yaw, pitch, and roll of the bone in local or world space\n * @param yaw The rotation of the bone on the y axis\n * @param pitch The rotation of the bone on the x axis\n * @param roll The rotation of the bone on the z axis\n * @param space The space that the axes of rotation are in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n */\n setYawPitchRoll(yaw, pitch, roll, space = Space.LOCAL, tNode) {\n if (space === Space.LOCAL) {\n const quat = Bone._TmpQuat;\n Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);\n this.setRotationQuaternion(quat, space, tNode);\n return;\n }\n const rotMatInv = Bone._TmpMats[0];\n if (!this._getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode)) {\n return;\n }\n const rotMat = Bone._TmpMats[1];\n Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);\n rotMatInv.multiplyToRef(rotMat, rotMat);\n this._rotateWithMatrix(rotMat, space, tNode);\n }\n /**\n * Add a rotation to the bone on an axis in local or world space\n * @param axis The axis to rotate the bone on\n * @param amount The amount to rotate the bone\n * @param space The space that the axis is in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n */\n rotate(axis, amount, space = Space.LOCAL, tNode) {\n const rmat = Bone._TmpMats[0];\n rmat.setTranslationFromFloats(0, 0, 0);\n Matrix.RotationAxisToRef(axis, amount, rmat);\n this._rotateWithMatrix(rmat, space, tNode);\n }\n /**\n * Set the rotation of the bone to a particular axis angle in local or world space\n * @param axis The axis to rotate the bone on\n * @param angle The angle that the bone should be rotated to\n * @param space The space that the axis is in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n */\n setAxisAngle(axis, angle, space = Space.LOCAL, tNode) {\n if (space === Space.LOCAL) {\n const quat = Bone._TmpQuat;\n Quaternion.RotationAxisToRef(axis, angle, quat);\n this.setRotationQuaternion(quat, space, tNode);\n return;\n }\n const rotMatInv = Bone._TmpMats[0];\n if (!this._getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode)) {\n return;\n }\n const rotMat = Bone._TmpMats[1];\n Matrix.RotationAxisToRef(axis, angle, rotMat);\n rotMatInv.multiplyToRef(rotMat, rotMat);\n this._rotateWithMatrix(rotMat, space, tNode);\n }\n /**\n * Set the euler rotation of the bone in local or world space\n * @param rotation The euler rotation that the bone should be set to\n * @param space The space that the rotation is in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n */\n setRotation(rotation, space = Space.LOCAL, tNode) {\n this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, tNode);\n }\n /**\n * Set the quaternion rotation of the bone in local or world space\n * @param quat The quaternion rotation that the bone should be set to\n * @param space The space that the rotation is in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n */\n setRotationQuaternion(quat, space = Space.LOCAL, tNode) {\n if (space === Space.LOCAL) {\n this._decompose();\n this._localRotation.copyFrom(quat);\n this._markAsDirtyAndCompose();\n return;\n }\n const rotMatInv = Bone._TmpMats[0];\n if (!this._getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode)) {\n return;\n }\n const rotMat = Bone._TmpMats[1];\n Matrix.FromQuaternionToRef(quat, rotMat);\n rotMatInv.multiplyToRef(rotMat, rotMat);\n this._rotateWithMatrix(rotMat, space, tNode);\n }\n /**\n * Set the rotation matrix of the bone in local or world space\n * @param rotMat The rotation matrix that the bone should be set to\n * @param space The space that the rotation is in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n */\n setRotationMatrix(rotMat, space = Space.LOCAL, tNode) {\n if (space === Space.LOCAL) {\n const quat = Bone._TmpQuat;\n Quaternion.FromRotationMatrixToRef(rotMat, quat);\n this.setRotationQuaternion(quat, space, tNode);\n return;\n }\n const rotMatInv = Bone._TmpMats[0];\n if (!this._getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode)) {\n return;\n }\n const rotMat2 = Bone._TmpMats[1];\n rotMat2.copyFrom(rotMat);\n rotMatInv.multiplyToRef(rotMat, rotMat2);\n this._rotateWithMatrix(rotMat2, space, tNode);\n }\n _rotateWithMatrix(rmat, space = Space.LOCAL, tNode) {\n const lmat = this.getLocalMatrix();\n const lx = lmat.m[12];\n const ly = lmat.m[13];\n const lz = lmat.m[14];\n const parent = this.getParent();\n const parentScale = Bone._TmpMats[3];\n const parentScaleInv = Bone._TmpMats[4];\n if (parent && space == Space.WORLD) {\n if (tNode) {\n parentScale.copyFrom(tNode.getWorldMatrix());\n parent.getAbsoluteMatrix().multiplyToRef(parentScale, parentScale);\n }\n else {\n parentScale.copyFrom(parent.getAbsoluteMatrix());\n }\n parentScaleInv.copyFrom(parentScale);\n parentScaleInv.invert();\n lmat.multiplyToRef(parentScale, lmat);\n lmat.multiplyToRef(rmat, lmat);\n lmat.multiplyToRef(parentScaleInv, lmat);\n }\n else {\n if (space == Space.WORLD && tNode) {\n parentScale.copyFrom(tNode.getWorldMatrix());\n parentScaleInv.copyFrom(parentScale);\n parentScaleInv.invert();\n lmat.multiplyToRef(parentScale, lmat);\n lmat.multiplyToRef(rmat, lmat);\n lmat.multiplyToRef(parentScaleInv, lmat);\n }\n else {\n lmat.multiplyToRef(rmat, lmat);\n }\n }\n lmat.setTranslationFromFloats(lx, ly, lz);\n this.computeAbsoluteMatrices();\n this._markAsDirtyAndDecompose();\n }\n _getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode) {\n const scaleMatrix = Bone._TmpMats[2];\n rotMatInv.copyFrom(this.getAbsoluteMatrix());\n if (tNode) {\n rotMatInv.multiplyToRef(tNode.getWorldMatrix(), rotMatInv);\n Matrix.ScalingToRef(tNode.scaling.x, tNode.scaling.y, tNode.scaling.z, scaleMatrix);\n }\n else {\n Matrix.IdentityToRef(scaleMatrix);\n }\n rotMatInv.invert();\n if (isNaN(rotMatInv.m[0])) {\n // Matrix failed to invert.\n // This can happen if scale is zero for example.\n return false;\n }\n scaleMatrix.multiplyAtIndex(0, this._scalingDeterminant);\n rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);\n return true;\n }\n /**\n * Get the position of the bone in local or world space\n * @param space The space that the returned position is in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @returns The position of the bone\n */\n getPosition(space = Space.LOCAL, tNode = null) {\n const pos = Vector3.Zero();\n this.getPositionToRef(space, tNode, pos);\n return pos;\n }\n /**\n * Copy the position of the bone to a vector3 in local or world space\n * @param space The space that the returned position is in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @param result The vector3 to copy the position to\n */\n getPositionToRef(space = Space.LOCAL, tNode, result) {\n if (space == Space.LOCAL) {\n const lm = this.getLocalMatrix();\n result.x = lm.m[12];\n result.y = lm.m[13];\n result.z = lm.m[14];\n }\n else {\n let wm = null;\n //tNode.getWorldMatrix() needs to be called before skeleton.computeAbsoluteMatrices()\n if (tNode) {\n wm = tNode.getWorldMatrix();\n }\n this._skeleton.computeAbsoluteMatrices();\n let tmat = Bone._TmpMats[0];\n if (tNode && wm) {\n tmat.copyFrom(this.getAbsoluteMatrix());\n tmat.multiplyToRef(wm, tmat);\n }\n else {\n tmat = this.getAbsoluteMatrix();\n }\n result.x = tmat.m[12];\n result.y = tmat.m[13];\n result.z = tmat.m[14];\n }\n }\n /**\n * Get the absolute position of the bone (world space)\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @returns The absolute position of the bone\n */\n getAbsolutePosition(tNode = null) {\n const pos = Vector3.Zero();\n this.getPositionToRef(Space.WORLD, tNode, pos);\n return pos;\n }\n /**\n * Copy the absolute position of the bone (world space) to the result param\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @param result The vector3 to copy the absolute position to\n */\n getAbsolutePositionToRef(tNode, result) {\n this.getPositionToRef(Space.WORLD, tNode, result);\n }\n /**\n * Compute the absolute matrices of this bone and its children\n */\n computeAbsoluteMatrices() {\n this._compose();\n if (this.parent) {\n this._localMatrix.multiplyToRef(this.parent._absoluteMatrix, this._absoluteMatrix);\n }\n else {\n this._absoluteMatrix.copyFrom(this._localMatrix);\n const poseMatrix = this._skeleton.getPoseMatrix();\n if (poseMatrix) {\n this._absoluteMatrix.multiplyToRef(poseMatrix, this._absoluteMatrix);\n }\n }\n const children = this.children;\n const len = children.length;\n for (let i = 0; i < len; i++) {\n children[i].computeAbsoluteMatrices();\n }\n }\n /**\n * Compute the absolute matrices of this bone and its children\n * @deprecated Please use computeAbsoluteMatrices instead\n */\n computeAbsoluteTransforms() {\n this.computeAbsoluteMatrices();\n }\n /**\n * Get the world direction from an axis that is in the local space of the bone\n * @param localAxis The local direction that is used to compute the world direction\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @returns The world direction\n */\n getDirection(localAxis, tNode = null) {\n const result = Vector3.Zero();\n this.getDirectionToRef(localAxis, tNode, result);\n return result;\n }\n /**\n * Copy the world direction to a vector3 from an axis that is in the local space of the bone\n * @param localAxis The local direction that is used to compute the world direction\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @param result The vector3 that the world direction will be copied to\n */\n getDirectionToRef(localAxis, tNode = null, result) {\n let wm = null;\n //tNode.getWorldMatrix() needs to be called before skeleton.computeAbsoluteMatrices()\n if (tNode) {\n wm = tNode.getWorldMatrix();\n }\n this._skeleton.computeAbsoluteMatrices();\n const mat = Bone._TmpMats[0];\n mat.copyFrom(this.getAbsoluteMatrix());\n if (tNode && wm) {\n mat.multiplyToRef(wm, mat);\n }\n Vector3.TransformNormalToRef(localAxis, mat, result);\n result.normalize();\n }\n /**\n * Get the euler rotation of the bone in local or world space\n * @param space The space that the rotation should be in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @returns The euler rotation\n */\n getRotation(space = Space.LOCAL, tNode = null) {\n const result = Vector3.Zero();\n this.getRotationToRef(space, tNode, result);\n return result;\n }\n /**\n * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space\n * @param space The space that the rotation should be in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @param result The vector3 that the rotation should be copied to\n */\n getRotationToRef(space = Space.LOCAL, tNode = null, result) {\n const quat = Bone._TmpQuat;\n this.getRotationQuaternionToRef(space, tNode, quat);\n quat.toEulerAnglesToRef(result);\n }\n /**\n * Get the quaternion rotation of the bone in either local or world space\n * @param space The space that the rotation should be in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @returns The quaternion rotation\n */\n getRotationQuaternion(space = Space.LOCAL, tNode = null) {\n const result = Quaternion.Identity();\n this.getRotationQuaternionToRef(space, tNode, result);\n return result;\n }\n /**\n * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space\n * @param space The space that the rotation should be in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @param result The quaternion that the rotation should be copied to\n */\n getRotationQuaternionToRef(space = Space.LOCAL, tNode = null, result) {\n if (space == Space.LOCAL) {\n this._decompose();\n result.copyFrom(this._localRotation);\n }\n else {\n const mat = Bone._TmpMats[0];\n const amat = this.getAbsoluteMatrix();\n if (tNode) {\n amat.multiplyToRef(tNode.getWorldMatrix(), mat);\n }\n else {\n mat.copyFrom(amat);\n }\n mat.multiplyAtIndex(0, this._scalingDeterminant);\n mat.multiplyAtIndex(1, this._scalingDeterminant);\n mat.multiplyAtIndex(2, this._scalingDeterminant);\n mat.decompose(undefined, result, undefined);\n }\n }\n /**\n * Get the rotation matrix of the bone in local or world space\n * @param space The space that the rotation should be in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @returns The rotation matrix\n */\n getRotationMatrix(space = Space.LOCAL, tNode) {\n const result = Matrix.Identity();\n this.getRotationMatrixToRef(space, tNode, result);\n return result;\n }\n /**\n * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space\n * @param space The space that the rotation should be in\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @param result The quaternion that the rotation should be copied to\n */\n getRotationMatrixToRef(space = Space.LOCAL, tNode, result) {\n if (space == Space.LOCAL) {\n this.getLocalMatrix().getRotationMatrixToRef(result);\n }\n else {\n const mat = Bone._TmpMats[0];\n const amat = this.getAbsoluteMatrix();\n if (tNode) {\n amat.multiplyToRef(tNode.getWorldMatrix(), mat);\n }\n else {\n mat.copyFrom(amat);\n }\n mat.multiplyAtIndex(0, this._scalingDeterminant);\n mat.multiplyAtIndex(1, this._scalingDeterminant);\n mat.multiplyAtIndex(2, this._scalingDeterminant);\n mat.getRotationMatrixToRef(result);\n }\n }\n /**\n * Get the world position of a point that is in the local space of the bone\n * @param position The local position\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @returns The world position\n */\n getAbsolutePositionFromLocal(position, tNode = null) {\n const result = Vector3.Zero();\n this.getAbsolutePositionFromLocalToRef(position, tNode, result);\n return result;\n }\n /**\n * Get the world position of a point that is in the local space of the bone and copy it to the result param\n * @param position The local position\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @param result The vector3 that the world position should be copied to\n */\n getAbsolutePositionFromLocalToRef(position, tNode = null, result) {\n let wm = null;\n //tNode.getWorldMatrix() needs to be called before skeleton.computeAbsoluteMatrices()\n if (tNode) {\n wm = tNode.getWorldMatrix();\n }\n this._skeleton.computeAbsoluteMatrices();\n const tmat = Bone._TmpMats[0];\n tmat.copyFrom(this.getAbsoluteMatrix());\n if (tNode && wm) {\n tmat.multiplyToRef(wm, tmat);\n }\n Vector3.TransformCoordinatesToRef(position, tmat, result);\n }\n /**\n * Get the local position of a point that is in world space\n * @param position The world position\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @returns The local position\n */\n getLocalPositionFromAbsolute(position, tNode = null) {\n const result = Vector3.Zero();\n this.getLocalPositionFromAbsoluteToRef(position, tNode, result);\n return result;\n }\n /**\n * Get the local position of a point that is in world space and copy it to the result param\n * @param position The world position\n * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD\n * @param result The vector3 that the local position should be copied to\n */\n getLocalPositionFromAbsoluteToRef(position, tNode = null, result) {\n let wm = null;\n //tNode.getWorldMatrix() needs to be called before skeleton.computeAbsoluteMatrices()\n if (tNode) {\n wm = tNode.getWorldMatrix();\n }\n this._skeleton.computeAbsoluteMatrices();\n const tmat = Bone._TmpMats[0];\n tmat.copyFrom(this.getAbsoluteMatrix());\n if (tNode && wm) {\n tmat.multiplyToRef(wm, tmat);\n }\n tmat.invert();\n Vector3.TransformCoordinatesToRef(position, tmat, result);\n }\n /**\n * Set the current local matrix as the restMatrix for this bone.\n */\n setCurrentPoseAsRest() {\n this.setRestMatrix(this.getLocalMatrix());\n }\n}\nBone._TmpVecs = ArrayTools.BuildArray(2, Vector3.Zero);\nBone._TmpQuat = Quaternion.Identity();\nBone._TmpMats = ArrayTools.BuildArray(5, Matrix.Identity);\n//# sourceMappingURL=bone.js.map","import { Animation } from \"./animation.js\";\nimport { RuntimeAnimation } from \"./runtimeAnimation.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Scene } from \"../scene.js\";\nimport { Matrix, Quaternion, Vector3, TmpVectors } from \"../Maths/math.vector.js\";\nimport { PrecisionDate } from \"../Misc/precisionDate.js\";\nimport { Bone } from \"../Bones/bone.js\";\n/**\n * Class used to store an actual running animation\n */\nexport class Animatable {\n /**\n * Gets the root Animatable used to synchronize and normalize animations\n */\n get syncRoot() {\n return this._syncRoot;\n }\n /**\n * Gets the current frame of the first RuntimeAnimation\n * Used to synchronize Animatables\n */\n get masterFrame() {\n if (this._runtimeAnimations.length === 0) {\n return 0;\n }\n return this._runtimeAnimations[0].currentFrame;\n }\n /**\n * Gets or sets the animatable weight (-1.0 by default meaning not weighted)\n */\n get weight() {\n return this._weight;\n }\n set weight(value) {\n if (value === -1) {\n // -1 is ok and means no weight\n this._weight = -1;\n return;\n }\n // Else weight must be in [0, 1] range\n this._weight = Math.min(Math.max(value, 0), 1.0);\n }\n /**\n * Gets or sets the speed ratio to apply to the animatable (1.0 by default)\n */\n get speedRatio() {\n return this._speedRatio;\n }\n set speedRatio(value) {\n for (let index = 0; index < this._runtimeAnimations.length; index++) {\n const animation = this._runtimeAnimations[index];\n animation._prepareForSpeedRatioChange(value);\n }\n this._speedRatio = value;\n // Resync _manualJumpDelay in case goToFrame was called before speedRatio was set.\n if (this._goToFrame !== null) {\n this.goToFrame(this._goToFrame);\n }\n }\n /**\n * Creates a new Animatable\n * @param scene defines the hosting scene\n * @param target defines the target object\n * @param fromFrame defines the starting frame number (default is 0)\n * @param toFrame defines the ending frame number (default is 100)\n * @param loopAnimation defines if the animation must loop (default is false)\n * @param speedRatio defines the factor to apply to animation speed (default is 1)\n * @param onAnimationEnd defines a callback to call when animation ends if it is not looping\n * @param animations defines a group of animation to add to the new Animatable\n * @param onAnimationLoop defines a callback to call when animation loops\n * @param isAdditive defines whether the animation should be evaluated additively\n */\n constructor(scene, \n /** defines the target object */\n target, \n /** defines the starting frame number (default is 0) */\n fromFrame = 0, \n /** defines the ending frame number (default is 100) */\n toFrame = 100, \n /** defines if the animation must loop (default is false) */\n loopAnimation = false, speedRatio = 1.0, \n /** defines a callback to call when animation ends if it is not looping */\n onAnimationEnd, animations, \n /** defines a callback to call when animation loops */\n onAnimationLoop, \n /** defines whether the animation should be evaluated additively */\n isAdditive = false) {\n this.target = target;\n this.fromFrame = fromFrame;\n this.toFrame = toFrame;\n this.loopAnimation = loopAnimation;\n this.onAnimationEnd = onAnimationEnd;\n this.onAnimationLoop = onAnimationLoop;\n this.isAdditive = isAdditive;\n this._localDelayOffset = null;\n this._pausedDelay = null;\n this._manualJumpDelay = null;\n /** @hidden */\n this._runtimeAnimations = new Array();\n this._paused = false;\n this._speedRatio = 1;\n this._weight = -1.0;\n this._syncRoot = null;\n this._frameToSyncFromJump = null;\n this._goToFrame = null;\n /**\n * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.\n * This will only apply for non looping animation (default is true)\n */\n this.disposeOnEnd = true;\n /**\n * Gets a boolean indicating if the animation has started\n */\n this.animationStarted = false;\n /**\n * Observer raised when the animation ends\n */\n this.onAnimationEndObservable = new Observable();\n /**\n * Observer raised when the animation loops\n */\n this.onAnimationLoopObservable = new Observable();\n this._scene = scene;\n if (animations) {\n this.appendAnimations(target, animations);\n }\n this._speedRatio = speedRatio;\n scene._activeAnimatables.push(this);\n }\n // Methods\n /**\n * Synchronize and normalize current Animatable with a source Animatable\n * This is useful when using animation weights and when animations are not of the same length\n * @param root defines the root Animatable to synchronize with (null to stop synchronizing)\n * @returns the current Animatable\n */\n syncWith(root) {\n this._syncRoot = root;\n if (root) {\n // Make sure this animatable will animate after the root\n const index = this._scene._activeAnimatables.indexOf(this);\n if (index > -1) {\n this._scene._activeAnimatables.splice(index, 1);\n this._scene._activeAnimatables.push(this);\n }\n }\n return this;\n }\n /**\n * Gets the list of runtime animations\n * @returns an array of RuntimeAnimation\n */\n getAnimations() {\n return this._runtimeAnimations;\n }\n /**\n * Adds more animations to the current animatable\n * @param target defines the target of the animations\n * @param animations defines the new animations to add\n */\n appendAnimations(target, animations) {\n for (let index = 0; index < animations.length; index++) {\n const animation = animations[index];\n const newRuntimeAnimation = new RuntimeAnimation(target, animation, this._scene, this);\n newRuntimeAnimation._onLoop = () => {\n this.onAnimationLoopObservable.notifyObservers(this);\n if (this.onAnimationLoop) {\n this.onAnimationLoop();\n }\n };\n this._runtimeAnimations.push(newRuntimeAnimation);\n }\n }\n /**\n * Gets the source animation for a specific property\n * @param property defines the property to look for\n * @returns null or the source animation for the given property\n */\n getAnimationByTargetProperty(property) {\n const runtimeAnimations = this._runtimeAnimations;\n for (let index = 0; index < runtimeAnimations.length; index++) {\n if (runtimeAnimations[index].animation.targetProperty === property) {\n return runtimeAnimations[index].animation;\n }\n }\n return null;\n }\n /**\n * Gets the runtime animation for a specific property\n * @param property defines the property to look for\n * @returns null or the runtime animation for the given property\n */\n getRuntimeAnimationByTargetProperty(property) {\n const runtimeAnimations = this._runtimeAnimations;\n for (let index = 0; index < runtimeAnimations.length; index++) {\n if (runtimeAnimations[index].animation.targetProperty === property) {\n return runtimeAnimations[index];\n }\n }\n return null;\n }\n /**\n * Resets the animatable to its original state\n */\n reset() {\n const runtimeAnimations = this._runtimeAnimations;\n for (let index = 0; index < runtimeAnimations.length; index++) {\n runtimeAnimations[index].reset(true);\n }\n this._localDelayOffset = null;\n this._pausedDelay = null;\n }\n /**\n * Allows the animatable to blend with current running animations\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#animation-blending\n * @param blendingSpeed defines the blending speed to use\n */\n enableBlending(blendingSpeed) {\n const runtimeAnimations = this._runtimeAnimations;\n for (let index = 0; index < runtimeAnimations.length; index++) {\n runtimeAnimations[index].animation.enableBlending = true;\n runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;\n }\n }\n /**\n * Disable animation blending\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#animation-blending\n */\n disableBlending() {\n const runtimeAnimations = this._runtimeAnimations;\n for (let index = 0; index < runtimeAnimations.length; index++) {\n runtimeAnimations[index].animation.enableBlending = false;\n }\n }\n /**\n * Jump directly to a given frame\n * @param frame defines the frame to jump to\n */\n goToFrame(frame) {\n var _a;\n const runtimeAnimations = this._runtimeAnimations;\n if (runtimeAnimations[0]) {\n const fps = runtimeAnimations[0].animation.framePerSecond;\n this._frameToSyncFromJump = (_a = this._frameToSyncFromJump) !== null && _a !== void 0 ? _a : runtimeAnimations[0].currentFrame;\n const delay = this.speedRatio === 0 ? 0 : (((frame - this._frameToSyncFromJump) / fps) * 1000) / this.speedRatio;\n this._manualJumpDelay = -delay;\n }\n for (let index = 0; index < runtimeAnimations.length; index++) {\n runtimeAnimations[index].goToFrame(frame);\n }\n this._goToFrame = frame;\n }\n /**\n * Pause the animation\n */\n pause() {\n if (this._paused) {\n return;\n }\n this._paused = true;\n }\n /**\n * Restart the animation\n */\n restart() {\n this._paused = false;\n }\n _raiseOnAnimationEnd() {\n if (this.onAnimationEnd) {\n this.onAnimationEnd();\n }\n this.onAnimationEndObservable.notifyObservers(this);\n }\n /**\n * Stop and delete the current animation\n * @param animationName defines a string used to only stop some of the runtime animations instead of all\n * @param targetMask a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)\n * @param useGlobalSplice if true, the animatables will be removed by the caller of this function (false by default)\n */\n stop(animationName, targetMask, useGlobalSplice = false) {\n if (animationName || targetMask) {\n const idx = this._scene._activeAnimatables.indexOf(this);\n if (idx > -1) {\n const runtimeAnimations = this._runtimeAnimations;\n for (let index = runtimeAnimations.length - 1; index >= 0; index--) {\n const runtimeAnimation = runtimeAnimations[index];\n if (animationName && runtimeAnimation.animation.name != animationName) {\n continue;\n }\n if (targetMask && !targetMask(runtimeAnimation.target)) {\n continue;\n }\n runtimeAnimation.dispose();\n runtimeAnimations.splice(index, 1);\n }\n if (runtimeAnimations.length == 0) {\n if (!useGlobalSplice) {\n this._scene._activeAnimatables.splice(idx, 1);\n }\n this._raiseOnAnimationEnd();\n }\n }\n }\n else {\n const index = this._scene._activeAnimatables.indexOf(this);\n if (index > -1) {\n if (!useGlobalSplice) {\n this._scene._activeAnimatables.splice(index, 1);\n }\n const runtimeAnimations = this._runtimeAnimations;\n for (let index = 0; index < runtimeAnimations.length; index++) {\n runtimeAnimations[index].dispose();\n }\n this._runtimeAnimations.length = 0;\n this._raiseOnAnimationEnd();\n }\n }\n }\n /**\n * Wait asynchronously for the animation to end\n * @returns a promise which will be fulfilled when the animation ends\n */\n waitAsync() {\n return new Promise((resolve) => {\n this.onAnimationEndObservable.add(() => {\n resolve(this);\n }, undefined, undefined, this, true);\n });\n }\n /**\n * @internal\n */\n _animate(delay) {\n if (this._paused) {\n this.animationStarted = false;\n if (this._pausedDelay === null) {\n this._pausedDelay = delay;\n }\n return true;\n }\n if (this._localDelayOffset === null) {\n this._localDelayOffset = delay;\n this._pausedDelay = null;\n }\n else if (this._pausedDelay !== null) {\n this._localDelayOffset += delay - this._pausedDelay;\n this._pausedDelay = null;\n }\n if (this._manualJumpDelay !== null) {\n this._localDelayOffset += this._manualJumpDelay;\n this._manualJumpDelay = null;\n this._frameToSyncFromJump = null;\n }\n this._goToFrame = null;\n if (this._weight === 0) {\n // We consider that an animation with a weight === 0 is \"actively\" paused\n return true;\n }\n // Animating\n let running = false;\n const runtimeAnimations = this._runtimeAnimations;\n let index;\n for (index = 0; index < runtimeAnimations.length; index++) {\n const animation = runtimeAnimations[index];\n const isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);\n running = running || isRunning;\n }\n this.animationStarted = running;\n if (!running) {\n if (this.disposeOnEnd) {\n // Remove from active animatables\n index = this._scene._activeAnimatables.indexOf(this);\n this._scene._activeAnimatables.splice(index, 1);\n // Dispose all runtime animations\n for (index = 0; index < runtimeAnimations.length; index++) {\n runtimeAnimations[index].dispose();\n }\n }\n this._raiseOnAnimationEnd();\n if (this.disposeOnEnd) {\n this.onAnimationEnd = null;\n this.onAnimationLoop = null;\n this.onAnimationLoopObservable.clear();\n this.onAnimationEndObservable.clear();\n }\n }\n return running;\n }\n}\nScene.prototype._animate = function () {\n if (!this.animationsEnabled) {\n return;\n }\n // Getting time\n const now = PrecisionDate.Now;\n if (!this._animationTimeLast) {\n if (this._pendingData.length > 0) {\n return;\n }\n this._animationTimeLast = now;\n }\n this.deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;\n this._animationTimeLast = now;\n const animatables = this._activeAnimatables;\n if (animatables.length === 0) {\n return;\n }\n this._animationTime += this.deltaTime;\n const animationTime = this._animationTime;\n for (let index = 0; index < animatables.length; index++) {\n const animatable = animatables[index];\n if (!animatable._animate(animationTime) && animatable.disposeOnEnd) {\n index--; // Array was updated\n }\n }\n // Late animation bindings\n this._processLateAnimationBindings();\n};\nScene.prototype.beginWeightedAnimation = function (target, from, to, weight = 1.0, loop, speedRatio = 1.0, onAnimationEnd, animatable, targetMask, onAnimationLoop, isAdditive = false) {\n const returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask, onAnimationLoop, isAdditive);\n returnedAnimatable.weight = weight;\n return returnedAnimatable;\n};\nScene.prototype.beginAnimation = function (target, from, to, loop, speedRatio = 1.0, onAnimationEnd, animatable, stopCurrent = true, targetMask, onAnimationLoop, isAdditive = false) {\n if (from > to && speedRatio > 0) {\n speedRatio *= -1;\n }\n if (stopCurrent) {\n this.stopAnimation(target, undefined, targetMask);\n }\n if (!animatable) {\n animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, undefined, onAnimationLoop, isAdditive);\n }\n const shouldRunTargetAnimations = targetMask ? targetMask(target) : true;\n // Local animations\n if (target.animations && shouldRunTargetAnimations) {\n animatable.appendAnimations(target, target.animations);\n }\n // Children animations\n if (target.getAnimatables) {\n const animatables = target.getAnimatables();\n for (let index = 0; index < animatables.length; index++) {\n this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, onAnimationLoop);\n }\n }\n animatable.reset();\n return animatable;\n};\nScene.prototype.beginHierarchyAnimation = function (target, directDescendantsOnly, from, to, loop, speedRatio = 1.0, onAnimationEnd, animatable, stopCurrent = true, targetMask, onAnimationLoop, isAdditive = false) {\n const children = target.getDescendants(directDescendantsOnly);\n const result = [];\n result.push(this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, undefined, isAdditive));\n for (const child of children) {\n result.push(this.beginAnimation(child, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, undefined, isAdditive));\n }\n return result;\n};\nScene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop, isAdditive = false) {\n if (speedRatio === undefined) {\n speedRatio = 1.0;\n }\n if (from > to && speedRatio > 0) {\n speedRatio *= -1;\n }\n else if (to > from && speedRatio < 0) {\n const temp = to;\n to = from;\n from = temp;\n }\n const animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations, onAnimationLoop, isAdditive);\n return animatable;\n};\nScene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop, isAdditive = false) {\n const children = target.getDescendants(directDescendantsOnly);\n const result = [];\n result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop, isAdditive));\n for (const child of children) {\n result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop, isAdditive));\n }\n return result;\n};\nScene.prototype.getAnimatableByTarget = function (target) {\n for (let index = 0; index < this._activeAnimatables.length; index++) {\n if (this._activeAnimatables[index].target === target) {\n return this._activeAnimatables[index];\n }\n }\n return null;\n};\nScene.prototype.getAllAnimatablesByTarget = function (target) {\n const result = [];\n for (let index = 0; index < this._activeAnimatables.length; index++) {\n if (this._activeAnimatables[index].target === target) {\n result.push(this._activeAnimatables[index]);\n }\n }\n return result;\n};\n/**\n * Will stop the animation of the given target\n * @param target - the target\n * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)\n * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)\n */\nScene.prototype.stopAnimation = function (target, animationName, targetMask) {\n const animatables = this.getAllAnimatablesByTarget(target);\n for (const animatable of animatables) {\n animatable.stop(animationName, targetMask);\n }\n};\n/**\n * Stops and removes all animations that have been applied to the scene\n */\nScene.prototype.stopAllAnimations = function () {\n if (this._activeAnimatables) {\n for (let i = 0; i < this._activeAnimatables.length; i++) {\n this._activeAnimatables[i].stop(undefined, undefined, true);\n }\n this._activeAnimatables.length = 0;\n }\n for (const group of this.animationGroups) {\n group.stop();\n }\n};\nScene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {\n const target = runtimeAnimation.target;\n this._registeredForLateAnimationBindings.pushNoDuplicate(target);\n if (!target._lateAnimationHolders) {\n target._lateAnimationHolders = {};\n }\n if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {\n target._lateAnimationHolders[runtimeAnimation.targetPath] = {\n totalWeight: 0,\n totalAdditiveWeight: 0,\n animations: [],\n additiveAnimations: [],\n originalValue: originalValue,\n };\n }\n if (runtimeAnimation.isAdditive) {\n target._lateAnimationHolders[runtimeAnimation.targetPath].additiveAnimations.push(runtimeAnimation);\n target._lateAnimationHolders[runtimeAnimation.targetPath].totalAdditiveWeight += runtimeAnimation.weight;\n }\n else {\n target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);\n target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;\n }\n};\nScene.prototype._processLateAnimationBindingsForMatrices = function (holder) {\n if (holder.totalWeight === 0 && holder.totalAdditiveWeight === 0) {\n return holder.originalValue;\n }\n let normalizer = 1.0;\n const finalPosition = TmpVectors.Vector3[0];\n const finalScaling = TmpVectors.Vector3[1];\n const finalQuaternion = TmpVectors.Quaternion[0];\n let startIndex = 0;\n const originalAnimation = holder.animations[0];\n const originalValue = holder.originalValue;\n let scale = 1;\n let skipOverride = false;\n if (holder.totalWeight < 1.0) {\n // We need to mix the original value in\n scale = 1.0 - holder.totalWeight;\n originalValue.decompose(finalScaling, finalQuaternion, finalPosition);\n }\n else {\n startIndex = 1;\n // We need to normalize the weights\n normalizer = holder.totalWeight;\n scale = originalAnimation.weight / normalizer;\n if (scale == 1) {\n if (holder.totalAdditiveWeight) {\n skipOverride = true;\n }\n else {\n return originalAnimation.currentValue;\n }\n }\n originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);\n }\n // Add up the override animations\n if (!skipOverride) {\n finalScaling.scaleInPlace(scale);\n finalPosition.scaleInPlace(scale);\n finalQuaternion.scaleInPlace(scale);\n for (let animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {\n const runtimeAnimation = holder.animations[animIndex];\n if (runtimeAnimation.weight === 0) {\n continue;\n }\n scale = runtimeAnimation.weight / normalizer;\n const currentPosition = TmpVectors.Vector3[2];\n const currentScaling = TmpVectors.Vector3[3];\n const currentQuaternion = TmpVectors.Quaternion[1];\n runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);\n currentScaling.scaleAndAddToRef(scale, finalScaling);\n currentQuaternion.scaleAndAddToRef(Quaternion.Dot(finalQuaternion, currentQuaternion) > 0 ? scale : -scale, finalQuaternion);\n currentPosition.scaleAndAddToRef(scale, finalPosition);\n }\n finalQuaternion.normalize();\n }\n // Add up the additive animations\n for (let animIndex = 0; animIndex < holder.additiveAnimations.length; animIndex++) {\n const runtimeAnimation = holder.additiveAnimations[animIndex];\n if (runtimeAnimation.weight === 0) {\n continue;\n }\n const currentPosition = TmpVectors.Vector3[2];\n const currentScaling = TmpVectors.Vector3[3];\n const currentQuaternion = TmpVectors.Quaternion[1];\n runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);\n currentScaling.multiplyToRef(finalScaling, currentScaling);\n Vector3.LerpToRef(finalScaling, currentScaling, runtimeAnimation.weight, finalScaling);\n finalQuaternion.multiplyToRef(currentQuaternion, currentQuaternion);\n Quaternion.SlerpToRef(finalQuaternion, currentQuaternion, runtimeAnimation.weight, finalQuaternion);\n currentPosition.scaleAndAddToRef(runtimeAnimation.weight, finalPosition);\n }\n const workValue = originalAnimation ? originalAnimation._animationState.workValue : TmpVectors.Matrix[0].clone();\n Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, workValue);\n return workValue;\n};\nScene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {\n if (holder.totalWeight === 0 && holder.totalAdditiveWeight === 0) {\n return refQuaternion;\n }\n const originalAnimation = holder.animations[0];\n const originalValue = holder.originalValue;\n let cumulativeQuaternion = refQuaternion;\n if (holder.totalWeight === 0 && holder.totalAdditiveWeight > 0) {\n cumulativeQuaternion.copyFrom(originalValue);\n }\n else if (holder.animations.length === 1) {\n Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), cumulativeQuaternion);\n if (holder.totalAdditiveWeight === 0) {\n return cumulativeQuaternion;\n }\n }\n else if (holder.animations.length > 1) {\n // Add up the override animations\n let normalizer = 1.0;\n let quaternions;\n let weights;\n if (holder.totalWeight < 1.0) {\n const scale = 1.0 - holder.totalWeight;\n quaternions = [];\n weights = [];\n quaternions.push(originalValue);\n weights.push(scale);\n }\n else {\n if (holder.animations.length === 2) {\n // Slerp as soon as we can\n Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);\n if (holder.totalAdditiveWeight === 0) {\n return refQuaternion;\n }\n }\n quaternions = [];\n weights = [];\n normalizer = holder.totalWeight;\n }\n for (let animIndex = 0; animIndex < holder.animations.length; animIndex++) {\n const runtimeAnimation = holder.animations[animIndex];\n quaternions.push(runtimeAnimation.currentValue);\n weights.push(runtimeAnimation.weight / normalizer);\n }\n // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions\n let cumulativeAmount = 0;\n for (let index = 0; index < quaternions.length;) {\n if (!index) {\n Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);\n cumulativeQuaternion = refQuaternion;\n cumulativeAmount = weights[index] + weights[index + 1];\n index += 2;\n continue;\n }\n cumulativeAmount += weights[index];\n Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);\n index++;\n }\n }\n // Add up the additive animations\n for (let animIndex = 0; animIndex < holder.additiveAnimations.length; animIndex++) {\n const runtimeAnimation = holder.additiveAnimations[animIndex];\n if (runtimeAnimation.weight === 0) {\n continue;\n }\n cumulativeQuaternion.multiplyToRef(runtimeAnimation.currentValue, TmpVectors.Quaternion[0]);\n Quaternion.SlerpToRef(cumulativeQuaternion, TmpVectors.Quaternion[0], runtimeAnimation.weight, cumulativeQuaternion);\n }\n return cumulativeQuaternion;\n};\nScene.prototype._processLateAnimationBindings = function () {\n if (!this._registeredForLateAnimationBindings.length) {\n return;\n }\n for (let index = 0; index < this._registeredForLateAnimationBindings.length; index++) {\n const target = this._registeredForLateAnimationBindings.data[index];\n for (const path in target._lateAnimationHolders) {\n const holder = target._lateAnimationHolders[path];\n const originalAnimation = holder.animations[0];\n const originalValue = holder.originalValue;\n if (originalValue === undefined || originalValue === null) {\n continue;\n }\n const matrixDecomposeMode = Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix\n let finalValue = target[path];\n if (matrixDecomposeMode) {\n finalValue = this._processLateAnimationBindingsForMatrices(holder);\n }\n else {\n const quaternionMode = originalValue.w !== undefined;\n if (quaternionMode) {\n finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || Quaternion.Identity());\n }\n else {\n let startIndex = 0;\n let normalizer = 1.0;\n if (holder.totalWeight < 1.0) {\n // We need to mix the original value in\n if (originalAnimation && originalValue.scale) {\n finalValue = originalValue.scale(1.0 - holder.totalWeight);\n }\n else if (originalAnimation) {\n finalValue = originalValue * (1.0 - holder.totalWeight);\n }\n else if (originalValue.clone) {\n finalValue = originalValue.clone();\n }\n else {\n finalValue = originalValue;\n }\n }\n else if (originalAnimation) {\n // We need to normalize the weights\n normalizer = holder.totalWeight;\n const scale = originalAnimation.weight / normalizer;\n if (scale !== 1) {\n if (originalAnimation.currentValue.scale) {\n finalValue = originalAnimation.currentValue.scale(scale);\n }\n else {\n finalValue = originalAnimation.currentValue * scale;\n }\n }\n else {\n finalValue = originalAnimation.currentValue;\n }\n startIndex = 1;\n }\n // Add up the override animations\n for (let animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {\n const runtimeAnimation = holder.animations[animIndex];\n const scale = runtimeAnimation.weight / normalizer;\n if (!scale) {\n continue;\n }\n else if (runtimeAnimation.currentValue.scaleAndAddToRef) {\n runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);\n }\n else {\n finalValue += runtimeAnimation.currentValue * scale;\n }\n }\n // Add up the additive animations\n for (let animIndex = 0; animIndex < holder.additiveAnimations.length; animIndex++) {\n const runtimeAnimation = holder.additiveAnimations[animIndex];\n const scale = runtimeAnimation.weight;\n if (!scale) {\n continue;\n }\n else if (runtimeAnimation.currentValue.scaleAndAddToRef) {\n runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);\n }\n else {\n finalValue += runtimeAnimation.currentValue * scale;\n }\n }\n }\n }\n target[path] = finalValue;\n }\n target._lateAnimationHolders = {};\n }\n this._registeredForLateAnimationBindings.reset();\n};\nBone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired = false, skelDimensionsRatio = null) {\n // all animation may be coming from a library skeleton, so may need to create animation\n if (this.animations.length === 0) {\n this.animations.push(new Animation(this.name, \"_matrix\", source.animations[0].framePerSecond, Animation.ANIMATIONTYPE_MATRIX, 0));\n this.animations[0].setKeys([]);\n }\n // get animation info / verify there is such a range from the source bone\n const sourceRange = source.animations[0].getRange(rangeName);\n if (!sourceRange) {\n return false;\n }\n const from = sourceRange.from;\n const to = sourceRange.to;\n const sourceKeys = source.animations[0].getKeys();\n // rescaling prep\n const sourceBoneLength = source.length;\n const sourceParent = source.getParent();\n const parent = this.getParent();\n const parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;\n const parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;\n const dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);\n const destKeys = this.animations[0].getKeys();\n // loop vars declaration\n let orig;\n let origTranslation;\n let mat;\n for (let key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {\n orig = sourceKeys[key];\n if (orig.frame >= from && orig.frame <= to) {\n if (rescaleAsRequired) {\n mat = orig.value.clone();\n // scale based on parent ratio, when bone has parent\n if (parentScalingReqd) {\n origTranslation = mat.getTranslation();\n mat.setTranslation(origTranslation.scaleInPlace(parentRatio));\n // scale based on skeleton dimension ratio when root bone, and value is passed\n }\n else if (dimensionsScalingReqd && skelDimensionsRatio) {\n origTranslation = mat.getTranslation();\n mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));\n // use original when root bone, and no data for skelDimensionsRatio\n }\n else {\n mat = orig.value;\n }\n }\n else {\n mat = orig.value;\n }\n destKeys.push({ frame: orig.frame + frameOffset, value: mat });\n }\n }\n this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);\n return true;\n};\n//# sourceMappingURL=animatable.js.map","import { Scalar } from \"./math.scalar.js\";\nimport { Vector2, Vector3, Quaternion, Matrix } from \"./math.vector.js\";\nimport { Epsilon } from \"./math.constants.js\";\n/**\n * Defines potential orientation for back face culling\n */\nexport var Orientation;\n(function (Orientation) {\n /**\n * Clockwise\n */\n Orientation[Orientation[\"CW\"] = 0] = \"CW\";\n /** Counter clockwise */\n Orientation[Orientation[\"CCW\"] = 1] = \"CCW\";\n})(Orientation || (Orientation = {}));\n/** Class used to represent a Bezier curve */\nexport class BezierCurve {\n /**\n * Returns the cubic Bezier interpolated value (float) at \"t\" (float) from the given x1, y1, x2, y2 floats\n * @param t defines the time\n * @param x1 defines the left coordinate on X axis\n * @param y1 defines the left coordinate on Y axis\n * @param x2 defines the right coordinate on X axis\n * @param y2 defines the right coordinate on Y axis\n * @returns the interpolated value\n */\n static Interpolate(t, x1, y1, x2, y2) {\n // Extract X (which is equal to time here)\n const f0 = 1 - 3 * x2 + 3 * x1;\n const f1 = 3 * x2 - 6 * x1;\n const f2 = 3 * x1;\n let refinedT = t;\n for (let i = 0; i < 5; i++) {\n const refinedT2 = refinedT * refinedT;\n const refinedT3 = refinedT2 * refinedT;\n const x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;\n const slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);\n refinedT -= (x - t) * slope;\n refinedT = Math.min(1, Math.max(0, refinedT));\n }\n // Resolve cubic bezier for the given x\n return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);\n }\n}\n/**\n * Defines angle representation\n */\nexport class Angle {\n /**\n * Creates an Angle object of \"radians\" radians (float).\n * @param radians the angle in radians\n */\n constructor(radians) {\n this._radians = radians;\n if (this._radians < 0.0) {\n this._radians += 2.0 * Math.PI;\n }\n }\n /**\n * Get value in degrees\n * @returns the Angle value in degrees (float)\n */\n degrees() {\n return (this._radians * 180.0) / Math.PI;\n }\n /**\n * Get value in radians\n * @returns the Angle value in radians (float)\n */\n radians() {\n return this._radians;\n }\n /**\n * Gets a new Angle object valued with the gradient angle, in radians, of the line joining two points\n * @param a defines first point as the origin\n * @param b defines point\n * @returns a new Angle\n */\n static BetweenTwoPoints(a, b) {\n const delta = b.subtract(a);\n const theta = Math.atan2(delta.y, delta.x);\n return new Angle(theta);\n }\n /**\n * Gets a new Angle object from the given float in radians\n * @param radians defines the angle value in radians\n * @returns a new Angle\n */\n static FromRadians(radians) {\n return new Angle(radians);\n }\n /**\n * Gets a new Angle object from the given float in degrees\n * @param degrees defines the angle value in degrees\n * @returns a new Angle\n */\n static FromDegrees(degrees) {\n return new Angle((degrees * Math.PI) / 180.0);\n }\n}\n/**\n * This represents an arc in a 2d space.\n */\nexport class Arc2 {\n /**\n * Creates an Arc object from the three given points : start, middle and end.\n * @param startPoint Defines the start point of the arc\n * @param midPoint Defines the middle point of the arc\n * @param endPoint Defines the end point of the arc\n */\n constructor(\n /** Defines the start point of the arc */\n startPoint, \n /** Defines the mid point of the arc */\n midPoint, \n /** Defines the end point of the arc */\n endPoint) {\n this.startPoint = startPoint;\n this.midPoint = midPoint;\n this.endPoint = endPoint;\n const temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);\n const startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2;\n const midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2;\n const det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);\n this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);\n this.radius = this.centerPoint.subtract(this.startPoint).length();\n this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);\n const a1 = this.startAngle.degrees();\n let a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();\n let a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();\n // angles correction\n if (a2 - a1 > +180.0) {\n a2 -= 360.0;\n }\n if (a2 - a1 < -180.0) {\n a2 += 360.0;\n }\n if (a3 - a2 > +180.0) {\n a3 -= 360.0;\n }\n if (a3 - a2 < -180.0) {\n a3 += 360.0;\n }\n this.orientation = a2 - a1 < 0 ? Orientation.CW : Orientation.CCW;\n this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);\n }\n}\n/**\n * Represents a 2D path made up of multiple 2D points\n */\nexport class Path2 {\n /**\n * Creates a Path2 object from the starting 2D coordinates x and y.\n * @param x the starting points x value\n * @param y the starting points y value\n */\n constructor(x, y) {\n this._points = new Array();\n this._length = 0.0;\n /**\n * If the path start and end point are the same\n */\n this.closed = false;\n this._points.push(new Vector2(x, y));\n }\n /**\n * Adds a new segment until the given coordinates (x, y) to the current Path2.\n * @param x the added points x value\n * @param y the added points y value\n * @returns the updated Path2.\n */\n addLineTo(x, y) {\n if (this.closed) {\n return this;\n }\n const newPoint = new Vector2(x, y);\n const previousPoint = this._points[this._points.length - 1];\n this._points.push(newPoint);\n this._length += newPoint.subtract(previousPoint).length();\n return this;\n }\n /**\n * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.\n * @param midX middle point x value\n * @param midY middle point y value\n * @param endX end point x value\n * @param endY end point y value\n * @param numberOfSegments (default: 36)\n * @returns the updated Path2.\n */\n addArcTo(midX, midY, endX, endY, numberOfSegments = 36) {\n if (this.closed) {\n return this;\n }\n const startPoint = this._points[this._points.length - 1];\n const midPoint = new Vector2(midX, midY);\n const endPoint = new Vector2(endX, endY);\n const arc = new Arc2(startPoint, midPoint, endPoint);\n let increment = arc.angle.radians() / numberOfSegments;\n if (arc.orientation === Orientation.CW) {\n increment *= -1;\n }\n let currentAngle = arc.startAngle.radians() + increment;\n for (let i = 0; i < numberOfSegments; i++) {\n const x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;\n const y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;\n this.addLineTo(x, y);\n currentAngle += increment;\n }\n return this;\n }\n /**\n * Adds _numberOfSegments_ segments according to the quadratic curve definition to the current Path2.\n * @param controlX control point x value\n * @param controlY control point y value\n * @param endX end point x value\n * @param endY end point y value\n * @param numberOfSegments (default: 36)\n * @returns the updated Path2.\n */\n addQuadraticCurveTo(controlX, controlY, endX, endY, numberOfSegments = 36) {\n if (this.closed) {\n return this;\n }\n const equation = (t, val0, val1, val2) => {\n const res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;\n return res;\n };\n const startPoint = this._points[this._points.length - 1];\n for (let i = 0; i <= numberOfSegments; i++) {\n const step = i / numberOfSegments;\n const x = equation(step, startPoint.x, controlX, endX);\n const y = equation(step, startPoint.y, controlY, endY);\n this.addLineTo(x, y);\n }\n return this;\n }\n /**\n * Adds _numberOfSegments_ segments according to the bezier curve definition to the current Path2.\n * @param originTangentX tangent vector at the origin point x value\n * @param originTangentY tangent vector at the origin point y value\n * @param destinationTangentX tangent vector at the destination point x value\n * @param destinationTangentY tangent vector at the destination point y value\n * @param endX end point x value\n * @param endY end point y value\n * @param numberOfSegments (default: 36)\n * @returns the updated Path2.\n */\n addBezierCurveTo(originTangentX, originTangentY, destinationTangentX, destinationTangentY, endX, endY, numberOfSegments = 36) {\n if (this.closed) {\n return this;\n }\n const equation = (t, val0, val1, val2, val3) => {\n const res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;\n return res;\n };\n const startPoint = this._points[this._points.length - 1];\n for (let i = 0; i <= numberOfSegments; i++) {\n const step = i / numberOfSegments;\n const x = equation(step, startPoint.x, originTangentX, destinationTangentX, endX);\n const y = equation(step, startPoint.y, originTangentY, destinationTangentY, endY);\n this.addLineTo(x, y);\n }\n return this;\n }\n /**\n * Defines if a given point is inside the polygon defines by the path\n * @param point defines the point to test\n * @returns true if the point is inside\n */\n isPointInside(point) {\n let isInside = false;\n const count = this._points.length;\n for (let p = count - 1, q = 0; q < count; p = q++) {\n let edgeLow = this._points[p];\n let edgeHigh = this._points[q];\n let edgeDx = edgeHigh.x - edgeLow.x;\n let edgeDy = edgeHigh.y - edgeLow.y;\n if (Math.abs(edgeDy) > Number.EPSILON) {\n // Not parallel\n if (edgeDy < 0) {\n edgeLow = this._points[q];\n edgeDx = -edgeDx;\n edgeHigh = this._points[p];\n edgeDy = -edgeDy;\n }\n if (point.y < edgeLow.y || point.y > edgeHigh.y) {\n continue;\n }\n if (point.y === edgeLow.y && point.x === edgeLow.x) {\n return true;\n }\n else {\n const perpEdge = edgeDy * (point.x - edgeLow.x) - edgeDx * (point.y - edgeLow.y);\n if (perpEdge === 0) {\n return true;\n }\n if (perpEdge < 0) {\n continue;\n }\n isInside = !isInside;\n }\n }\n else {\n // parallel or collinear\n if (point.y !== edgeLow.y) {\n continue;\n }\n if ((edgeHigh.x <= point.x && point.x <= edgeLow.x) || (edgeLow.x <= point.x && point.x <= edgeHigh.x)) {\n return true;\n }\n }\n }\n return isInside;\n }\n /**\n * Closes the Path2.\n * @returns the Path2.\n */\n close() {\n this.closed = true;\n return this;\n }\n /**\n * Gets the sum of the distance between each sequential point in the path\n * @returns the Path2 total length (float).\n */\n length() {\n let result = this._length;\n if (this.closed) {\n const lastPoint = this._points[this._points.length - 1];\n const firstPoint = this._points[0];\n result += firstPoint.subtract(lastPoint).length();\n }\n return result;\n }\n /**\n * Gets the area of the polygon defined by the path\n * @returns area value\n */\n area() {\n const n = this._points.length;\n let value = 0.0;\n for (let p = n - 1, q = 0; q < n; p = q++) {\n value += this._points[p].x * this._points[q].y - this._points[q].x * this._points[p].y;\n }\n return value * 0.5;\n }\n /**\n * Gets the points which construct the path\n * @returns the Path2 internal array of points.\n */\n getPoints() {\n return this._points;\n }\n /**\n * Retreives the point at the distance aways from the starting point\n * @param normalizedLengthPosition the length along the path to retrieve the point from\n * @returns a new Vector2 located at a percentage of the Path2 total length on this path.\n */\n getPointAtLengthPosition(normalizedLengthPosition) {\n if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {\n return Vector2.Zero();\n }\n const lengthPosition = normalizedLengthPosition * this.length();\n let previousOffset = 0;\n for (let i = 0; i < this._points.length; i++) {\n const j = (i + 1) % this._points.length;\n const a = this._points[i];\n const b = this._points[j];\n const bToA = b.subtract(a);\n const nextOffset = bToA.length() + previousOffset;\n if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {\n const dir = bToA.normalize();\n const localOffset = lengthPosition - previousOffset;\n return new Vector2(a.x + dir.x * localOffset, a.y + dir.y * localOffset);\n }\n previousOffset = nextOffset;\n }\n return Vector2.Zero();\n }\n /**\n * Creates a new path starting from an x and y position\n * @param x starting x value\n * @param y starting y value\n * @returns a new Path2 starting at the coordinates (x, y).\n */\n static StartingAt(x, y) {\n return new Path2(x, y);\n }\n}\n/**\n * Represents a 3D path made up of multiple 3D points\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/path3D\n */\nexport class Path3D {\n /**\n * new Path3D(path, normal, raw)\n * Creates a Path3D. A Path3D is a logical math object, so not a mesh.\n * please read the description in the tutorial : https://doc.babylonjs.com/features/featuresDeepDive/mesh/path3D\n * @param path an array of Vector3, the curve axis of the Path3D\n * @param firstNormal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.\n * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.\n * @param alignTangentsWithPath (optional, default false) : boolean, if true the tangents will be aligned with the path.\n */\n constructor(\n /**\n * an array of Vector3, the curve axis of the Path3D\n */\n path, firstNormal = null, raw, alignTangentsWithPath = false) {\n this.path = path;\n this._curve = new Array();\n this._distances = new Array();\n this._tangents = new Array();\n this._normals = new Array();\n this._binormals = new Array();\n // holds interpolated point data\n this._pointAtData = {\n id: 0,\n point: Vector3.Zero(),\n previousPointArrayIndex: 0,\n position: 0,\n subPosition: 0,\n interpolateReady: false,\n interpolationMatrix: Matrix.Identity(),\n };\n for (let p = 0; p < path.length; p++) {\n this._curve[p] = path[p].clone(); // hard copy\n }\n this._raw = raw || false;\n this._alignTangentsWithPath = alignTangentsWithPath;\n this._compute(firstNormal, alignTangentsWithPath);\n }\n /**\n * Returns the Path3D array of successive Vector3 designing its curve.\n * @returns the Path3D array of successive Vector3 designing its curve.\n */\n getCurve() {\n return this._curve;\n }\n /**\n * Returns the Path3D array of successive Vector3 designing its curve.\n * @returns the Path3D array of successive Vector3 designing its curve.\n */\n getPoints() {\n return this._curve;\n }\n /**\n * @returns the computed length (float) of the path.\n */\n length() {\n return this._distances[this._distances.length - 1];\n }\n /**\n * Returns an array populated with tangent vectors on each Path3D curve point.\n * @returns an array populated with tangent vectors on each Path3D curve point.\n */\n getTangents() {\n return this._tangents;\n }\n /**\n * Returns an array populated with normal vectors on each Path3D curve point.\n * @returns an array populated with normal vectors on each Path3D curve point.\n */\n getNormals() {\n return this._normals;\n }\n /**\n * Returns an array populated with binormal vectors on each Path3D curve point.\n * @returns an array populated with binormal vectors on each Path3D curve point.\n */\n getBinormals() {\n return this._binormals;\n }\n /**\n * Returns an array populated with distances (float) of the i-th point from the first curve point.\n * @returns an array populated with distances (float) of the i-th point from the first curve point.\n */\n getDistances() {\n return this._distances;\n }\n /**\n * Returns an interpolated point along this path\n * @param position the position of the point along this path, from 0.0 to 1.0\n * @returns a new Vector3 as the point\n */\n getPointAt(position) {\n return this._updatePointAtData(position).point;\n }\n /**\n * Returns the tangent vector of an interpolated Path3D curve point at the specified position along this path.\n * @param position the position of the point along this path, from 0.0 to 1.0\n * @param interpolated (optional, default false) : boolean, if true returns an interpolated tangent instead of the tangent of the previous path point.\n * @returns a tangent vector corresponding to the interpolated Path3D curve point, if not interpolated, the tangent is taken from the precomputed tangents array.\n */\n getTangentAt(position, interpolated = false) {\n this._updatePointAtData(position, interpolated);\n return interpolated ? Vector3.TransformCoordinates(Vector3.Forward(), this._pointAtData.interpolationMatrix) : this._tangents[this._pointAtData.previousPointArrayIndex];\n }\n /**\n * Returns the tangent vector of an interpolated Path3D curve point at the specified position along this path.\n * @param position the position of the point along this path, from 0.0 to 1.0\n * @param interpolated (optional, default false) : boolean, if true returns an interpolated normal instead of the normal of the previous path point.\n * @returns a normal vector corresponding to the interpolated Path3D curve point, if not interpolated, the normal is taken from the precomputed normals array.\n */\n getNormalAt(position, interpolated = false) {\n this._updatePointAtData(position, interpolated);\n return interpolated ? Vector3.TransformCoordinates(Vector3.Right(), this._pointAtData.interpolationMatrix) : this._normals[this._pointAtData.previousPointArrayIndex];\n }\n /**\n * Returns the binormal vector of an interpolated Path3D curve point at the specified position along this path.\n * @param position the position of the point along this path, from 0.0 to 1.0\n * @param interpolated (optional, default false) : boolean, if true returns an interpolated binormal instead of the binormal of the previous path point.\n * @returns a binormal vector corresponding to the interpolated Path3D curve point, if not interpolated, the binormal is taken from the precomputed binormals array.\n */\n getBinormalAt(position, interpolated = false) {\n this._updatePointAtData(position, interpolated);\n return interpolated ? Vector3.TransformCoordinates(Vector3.UpReadOnly, this._pointAtData.interpolationMatrix) : this._binormals[this._pointAtData.previousPointArrayIndex];\n }\n /**\n * Returns the distance (float) of an interpolated Path3D curve point at the specified position along this path.\n * @param position the position of the point along this path, from 0.0 to 1.0\n * @returns the distance of the interpolated Path3D curve point at the specified position along this path.\n */\n getDistanceAt(position) {\n return this.length() * position;\n }\n /**\n * Returns the array index of the previous point of an interpolated point along this path\n * @param position the position of the point to interpolate along this path, from 0.0 to 1.0\n * @returns the array index\n */\n getPreviousPointIndexAt(position) {\n this._updatePointAtData(position);\n return this._pointAtData.previousPointArrayIndex;\n }\n /**\n * Returns the position of an interpolated point relative to the two path points it lies between, from 0.0 (point A) to 1.0 (point B)\n * @param position the position of the point to interpolate along this path, from 0.0 to 1.0\n * @returns the sub position\n */\n getSubPositionAt(position) {\n this._updatePointAtData(position);\n return this._pointAtData.subPosition;\n }\n /**\n * Returns the position of the closest virtual point on this path to an arbitrary Vector3, from 0.0 to 1.0\n * @param target the vector of which to get the closest position to\n * @returns the position of the closest virtual point on this path to the target vector\n */\n getClosestPositionTo(target) {\n let smallestDistance = Number.MAX_VALUE;\n let closestPosition = 0.0;\n for (let i = 0; i < this._curve.length - 1; i++) {\n const point = this._curve[i + 0];\n const tangent = this._curve[i + 1].subtract(point).normalize();\n const subLength = this._distances[i + 1] - this._distances[i + 0];\n const subPosition = Math.min((Math.max(Vector3.Dot(tangent, target.subtract(point).normalize()), 0.0) * Vector3.Distance(point, target)) / subLength, 1.0);\n const distance = Vector3.Distance(point.add(tangent.scale(subPosition * subLength)), target);\n if (distance < smallestDistance) {\n smallestDistance = distance;\n closestPosition = (this._distances[i + 0] + subLength * subPosition) / this.length();\n }\n }\n return closestPosition;\n }\n /**\n * Returns a sub path (slice) of this path\n * @param start the position of the fist path point, from 0.0 to 1.0, or a negative value, which will get wrapped around from the end of the path to 0.0 to 1.0 values\n * @param end the position of the last path point, from 0.0 to 1.0, or a negative value, which will get wrapped around from the end of the path to 0.0 to 1.0 values\n * @returns a sub path (slice) of this path\n */\n slice(start = 0.0, end = 1.0) {\n if (start < 0.0) {\n start = 1 - ((start * -1.0) % 1.0);\n }\n if (end < 0.0) {\n end = 1 - ((end * -1.0) % 1.0);\n }\n if (start > end) {\n const _start = start;\n start = end;\n end = _start;\n }\n const curvePoints = this.getCurve();\n const startPoint = this.getPointAt(start);\n let startIndex = this.getPreviousPointIndexAt(start);\n const endPoint = this.getPointAt(end);\n const endIndex = this.getPreviousPointIndexAt(end) + 1;\n const slicePoints = [];\n if (start !== 0.0) {\n startIndex++;\n slicePoints.push(startPoint);\n }\n slicePoints.push(...curvePoints.slice(startIndex, endIndex));\n if (end !== 1.0 || start === 1.0) {\n slicePoints.push(endPoint);\n }\n return new Path3D(slicePoints, this.getNormalAt(start), this._raw, this._alignTangentsWithPath);\n }\n /**\n * Forces the Path3D tangent, normal, binormal and distance recomputation.\n * @param path path which all values are copied into the curves points\n * @param firstNormal which should be projected onto the curve\n * @param alignTangentsWithPath (optional, default false) : boolean, if true the tangents will be aligned with the path\n * @returns the same object updated.\n */\n update(path, firstNormal = null, alignTangentsWithPath = false) {\n for (let p = 0; p < path.length; p++) {\n this._curve[p].x = path[p].x;\n this._curve[p].y = path[p].y;\n this._curve[p].z = path[p].z;\n }\n this._compute(firstNormal, alignTangentsWithPath);\n return this;\n }\n // private function compute() : computes tangents, normals and binormals\n _compute(firstNormal, alignTangentsWithPath = false) {\n const l = this._curve.length;\n if (l < 2) {\n return;\n }\n // first and last tangents\n this._tangents[0] = this._getFirstNonNullVector(0);\n if (!this._raw) {\n this._tangents[0].normalize();\n }\n this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);\n if (!this._raw) {\n this._tangents[l - 1].normalize();\n }\n // normals and binormals at first point : arbitrary vector with _normalVector()\n const tg0 = this._tangents[0];\n const pp0 = this._normalVector(tg0, firstNormal);\n this._normals[0] = pp0;\n if (!this._raw) {\n this._normals[0].normalize();\n }\n this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);\n if (!this._raw) {\n this._binormals[0].normalize();\n }\n this._distances[0] = 0.0;\n // normals and binormals : next points\n let prev; // previous vector (segment)\n let cur; // current vector (segment)\n let curTang; // current tangent\n // previous normal\n let prevNor; // previous normal\n let prevBinor; // previous binormal\n for (let i = 1; i < l; i++) {\n // tangents\n prev = this._getLastNonNullVector(i);\n if (i < l - 1) {\n cur = this._getFirstNonNullVector(i);\n this._tangents[i] = alignTangentsWithPath ? cur : prev.add(cur);\n this._tangents[i].normalize();\n }\n this._distances[i] = this._distances[i - 1] + this._curve[i].subtract(this._curve[i - 1]).length();\n // normals and binormals\n // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html\n curTang = this._tangents[i];\n prevBinor = this._binormals[i - 1];\n this._normals[i] = Vector3.Cross(prevBinor, curTang);\n if (!this._raw) {\n if (this._normals[i].length() === 0) {\n prevNor = this._normals[i - 1];\n this._normals[i] = prevNor.clone();\n }\n else {\n this._normals[i].normalize();\n }\n }\n this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);\n if (!this._raw) {\n this._binormals[i].normalize();\n }\n }\n this._pointAtData.id = NaN;\n }\n // private function getFirstNonNullVector(index)\n // returns the first non null vector from index : curve[index + N].subtract(curve[index])\n _getFirstNonNullVector(index) {\n let i = 1;\n let nNVector = this._curve[index + i].subtract(this._curve[index]);\n while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {\n i++;\n nNVector = this._curve[index + i].subtract(this._curve[index]);\n }\n return nNVector;\n }\n // private function getLastNonNullVector(index)\n // returns the last non null vector from index : curve[index].subtract(curve[index - N])\n _getLastNonNullVector(index) {\n let i = 1;\n let nLVector = this._curve[index].subtract(this._curve[index - i]);\n while (nLVector.length() === 0 && index > i + 1) {\n i++;\n nLVector = this._curve[index].subtract(this._curve[index - i]);\n }\n return nLVector;\n }\n // private function normalVector(v0, vt, va) :\n // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane\n // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0\n _normalVector(vt, va) {\n let normal0;\n let tgl = vt.length();\n if (tgl === 0.0) {\n tgl = 1.0;\n }\n if (va === undefined || va === null) {\n let point;\n if (!Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, Epsilon)) {\n // search for a point in the plane\n point = new Vector3(0.0, -1.0, 0.0);\n }\n else if (!Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, Epsilon)) {\n point = new Vector3(1.0, 0.0, 0.0);\n }\n else if (!Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, Epsilon)) {\n point = new Vector3(0.0, 0.0, 1.0);\n }\n else {\n point = Vector3.Zero();\n }\n normal0 = Vector3.Cross(vt, point);\n }\n else {\n normal0 = Vector3.Cross(vt, va);\n Vector3.CrossToRef(normal0, vt, normal0);\n }\n normal0.normalize();\n return normal0;\n }\n /**\n * Updates the point at data for an interpolated point along this curve\n * @param position the position of the point along this curve, from 0.0 to 1.0\n * @param interpolateTNB\n * @interpolateTNB whether to compute the interpolated tangent, normal and binormal\n * @returns the (updated) point at data\n */\n _updatePointAtData(position, interpolateTNB = false) {\n // set an id for caching the result\n if (this._pointAtData.id === position) {\n if (!this._pointAtData.interpolateReady) {\n this._updateInterpolationMatrix();\n }\n return this._pointAtData;\n }\n else {\n this._pointAtData.id = position;\n }\n const curvePoints = this.getPoints();\n // clamp position between 0.0 and 1.0\n if (position <= 0.0) {\n return this._setPointAtData(0.0, 0.0, curvePoints[0], 0, interpolateTNB);\n }\n else if (position >= 1.0) {\n return this._setPointAtData(1.0, 1.0, curvePoints[curvePoints.length - 1], curvePoints.length - 1, interpolateTNB);\n }\n let previousPoint = curvePoints[0];\n let currentPoint;\n let currentLength = 0.0;\n const targetLength = position * this.length();\n for (let i = 1; i < curvePoints.length; i++) {\n currentPoint = curvePoints[i];\n const distance = Vector3.Distance(previousPoint, currentPoint);\n currentLength += distance;\n if (currentLength === targetLength) {\n return this._setPointAtData(position, 1.0, currentPoint, i, interpolateTNB);\n }\n else if (currentLength > targetLength) {\n const toLength = currentLength - targetLength;\n const diff = toLength / distance;\n const dir = previousPoint.subtract(currentPoint);\n const point = currentPoint.add(dir.scaleInPlace(diff));\n return this._setPointAtData(position, 1 - diff, point, i - 1, interpolateTNB);\n }\n previousPoint = currentPoint;\n }\n return this._pointAtData;\n }\n /**\n * Updates the point at data from the specified parameters\n * @param position where along the path the interpolated point is, from 0.0 to 1.0\n * @param subPosition\n * @param point the interpolated point\n * @param parentIndex the index of an existing curve point that is on, or else positionally the first behind, the interpolated point\n * @param interpolateTNB\n */\n _setPointAtData(position, subPosition, point, parentIndex, interpolateTNB) {\n this._pointAtData.point = point;\n this._pointAtData.position = position;\n this._pointAtData.subPosition = subPosition;\n this._pointAtData.previousPointArrayIndex = parentIndex;\n this._pointAtData.interpolateReady = interpolateTNB;\n if (interpolateTNB) {\n this._updateInterpolationMatrix();\n }\n return this._pointAtData;\n }\n /**\n * Updates the point at interpolation matrix for the tangents, normals and binormals\n */\n _updateInterpolationMatrix() {\n this._pointAtData.interpolationMatrix = Matrix.Identity();\n const parentIndex = this._pointAtData.previousPointArrayIndex;\n if (parentIndex !== this._tangents.length - 1) {\n const index = parentIndex + 1;\n const tangentFrom = this._tangents[parentIndex].clone();\n const normalFrom = this._normals[parentIndex].clone();\n const binormalFrom = this._binormals[parentIndex].clone();\n const tangentTo = this._tangents[index].clone();\n const normalTo = this._normals[index].clone();\n const binormalTo = this._binormals[index].clone();\n const quatFrom = Quaternion.RotationQuaternionFromAxis(normalFrom, binormalFrom, tangentFrom);\n const quatTo = Quaternion.RotationQuaternionFromAxis(normalTo, binormalTo, tangentTo);\n const quatAt = Quaternion.Slerp(quatFrom, quatTo, this._pointAtData.subPosition);\n quatAt.toRotationMatrix(this._pointAtData.interpolationMatrix);\n }\n }\n}\n/**\n * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.\n * A Curve3 is designed from a series of successive Vector3.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves\n */\nexport class Curve3 {\n /**\n * Returns a Curve3 object along a Quadratic Bezier curve : https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#quadratic-bezier-curve\n * @param v0 (Vector3) the origin point of the Quadratic Bezier\n * @param v1 (Vector3) the control point\n * @param v2 (Vector3) the end point of the Quadratic Bezier\n * @param nbPoints (integer) the wanted number of points in the curve\n * @returns the created Curve3\n */\n static CreateQuadraticBezier(v0, v1, v2, nbPoints) {\n nbPoints = nbPoints > 2 ? nbPoints : 3;\n const bez = new Array();\n const equation = (t, val0, val1, val2) => {\n const res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;\n return res;\n };\n for (let i = 0; i <= nbPoints; i++) {\n bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));\n }\n return new Curve3(bez);\n }\n /**\n * Returns a Curve3 object along a Cubic Bezier curve : https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#cubic-bezier-curve\n * @param v0 (Vector3) the origin point of the Cubic Bezier\n * @param v1 (Vector3) the first control point\n * @param v2 (Vector3) the second control point\n * @param v3 (Vector3) the end point of the Cubic Bezier\n * @param nbPoints (integer) the wanted number of points in the curve\n * @returns the created Curve3\n */\n static CreateCubicBezier(v0, v1, v2, v3, nbPoints) {\n nbPoints = nbPoints > 3 ? nbPoints : 4;\n const bez = new Array();\n const equation = (t, val0, val1, val2, val3) => {\n const res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;\n return res;\n };\n for (let i = 0; i <= nbPoints; i++) {\n bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));\n }\n return new Curve3(bez);\n }\n /**\n * Returns a Curve3 object along a Hermite Spline curve : https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#hermite-spline\n * @param p1 (Vector3) the origin point of the Hermite Spline\n * @param t1 (Vector3) the tangent vector at the origin point\n * @param p2 (Vector3) the end point of the Hermite Spline\n * @param t2 (Vector3) the tangent vector at the end point\n * @param nSeg (integer) the number of curve segments or nSeg + 1 points in the array\n * @returns the created Curve3\n */\n static CreateHermiteSpline(p1, t1, p2, t2, nSeg) {\n const hermite = new Array();\n const step = 1.0 / nSeg;\n for (let i = 0; i <= nSeg; i++) {\n hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));\n }\n return new Curve3(hermite);\n }\n /**\n * Returns a Curve3 object along a CatmullRom Spline curve :\n * @param points (array of Vector3) the points the spline must pass through. At least, four points required\n * @param nbPoints (integer) the wanted number of points between each curve control points\n * @param closed (boolean) optional with default false, when true forms a closed loop from the points\n * @returns the created Curve3\n */\n static CreateCatmullRomSpline(points, nbPoints, closed) {\n const catmullRom = new Array();\n const step = 1.0 / nbPoints;\n let amount = 0.0;\n if (closed) {\n const pointsCount = points.length;\n for (let i = 0; i < pointsCount; i++) {\n amount = 0;\n for (let c = 0; c < nbPoints; c++) {\n catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));\n amount += step;\n }\n }\n catmullRom.push(catmullRom[0]);\n }\n else {\n const totalPoints = new Array();\n totalPoints.push(points[0].clone());\n Array.prototype.push.apply(totalPoints, points);\n totalPoints.push(points[points.length - 1].clone());\n let i = 0;\n for (; i < totalPoints.length - 3; i++) {\n amount = 0;\n for (let c = 0; c < nbPoints; c++) {\n catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));\n amount += step;\n }\n }\n i--;\n catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));\n }\n return new Curve3(catmullRom);\n }\n /**\n * Returns a Curve3 object along an arc through three vector3 points:\n * The three points should not be colinear. When they are the Curve3 is empty.\n * @param first (Vector3) the first point the arc must pass through.\n * @param second (Vector3) the second point the arc must pass through.\n * @param third (Vector3) the third point the arc must pass through.\n * @param steps (number) the larger the number of steps the more detailed the arc.\n * @param closed (boolean) optional with default false, when true forms the chord from the first and third point\n * @param fullCircle Circle (boolean) optional with default false, when true forms the complete circle through the three points\n * @returns the created Curve3\n */\n static ArcThru3Points(first, second, third, steps = 32, closed = false, fullCircle = false) {\n const arc = new Array();\n const vec1 = second.subtract(first);\n const vec2 = third.subtract(second);\n const vec3 = first.subtract(third);\n const zAxis = Vector3.Cross(vec1, vec2);\n const len4 = zAxis.length();\n if (len4 < Math.pow(10, -8)) {\n return new Curve3(arc); // colinear points arc is empty\n }\n const len1_sq = vec1.lengthSquared();\n const len2_sq = vec2.lengthSquared();\n const len3_sq = vec3.lengthSquared();\n const len4_sq = zAxis.lengthSquared();\n const len1 = vec1.length();\n const len2 = vec2.length();\n const len3 = vec3.length();\n const radius = (0.5 * len1 * len2 * len3) / len4;\n const dot1 = Vector3.Dot(vec1, vec3);\n const dot2 = Vector3.Dot(vec1, vec2);\n const dot3 = Vector3.Dot(vec2, vec3);\n const a = (-0.5 * len2_sq * dot1) / len4_sq;\n const b = (-0.5 * len3_sq * dot2) / len4_sq;\n const c = (-0.5 * len1_sq * dot3) / len4_sq;\n const center = first.scale(a).add(second.scale(b)).add(third.scale(c));\n const radiusVec = first.subtract(center);\n const xAxis = radiusVec.normalize();\n const yAxis = Vector3.Cross(zAxis, xAxis).normalize();\n if (fullCircle) {\n const dStep = (2 * Math.PI) / steps;\n for (let theta = 0; theta <= 2 * Math.PI; theta += dStep) {\n arc.push(center.add(xAxis.scale(radius * Math.cos(theta)).add(yAxis.scale(radius * Math.sin(theta)))));\n }\n arc.push(first);\n }\n else {\n const dStep = 1 / steps;\n let theta = 0;\n let point = Vector3.Zero();\n do {\n point = center.add(xAxis.scale(radius * Math.cos(theta)).add(yAxis.scale(radius * Math.sin(theta))));\n arc.push(point);\n theta += dStep;\n } while (!point.equalsWithEpsilon(third, radius * dStep * 1.1));\n arc.push(third);\n if (closed) {\n arc.push(first);\n }\n }\n return new Curve3(arc);\n }\n /**\n * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.\n * A Curve3 is designed from a series of successive Vector3.\n * Tuto : https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#curve3-object\n * @param points points which make up the curve\n */\n constructor(points) {\n this._length = 0.0;\n this._points = points;\n this._length = this._computeLength(points);\n }\n /**\n * @returns the Curve3 stored array of successive Vector3\n */\n getPoints() {\n return this._points;\n }\n /**\n * @returns the computed length (float) of the curve.\n */\n length() {\n return this._length;\n }\n /**\n * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);\n * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.\n * curveA and curveB keep unchanged.\n * @param curve the curve to continue from this curve\n * @returns the newly constructed curve\n */\n continue(curve) {\n const lastPoint = this._points[this._points.length - 1];\n const continuedPoints = this._points.slice();\n const curvePoints = curve.getPoints();\n for (let i = 1; i < curvePoints.length; i++) {\n continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));\n }\n const continuedCurve = new Curve3(continuedPoints);\n return continuedCurve;\n }\n _computeLength(path) {\n let l = 0;\n for (let i = 1; i < path.length; i++) {\n l += path[i].subtract(path[i - 1]).length();\n }\n return l;\n }\n}\n//# sourceMappingURL=math.path.js.map","import { BezierCurve } from \"../Maths/math.path.js\";\n/**\n * Base class used for every default easing function.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions\n */\nexport class EasingFunction {\n constructor() {\n this._easingMode = EasingFunction.EASINGMODE_EASEIN;\n }\n /**\n * Sets the easing mode of the current function.\n * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)\n */\n setEasingMode(easingMode) {\n const n = Math.min(Math.max(easingMode, 0), 2);\n this._easingMode = n;\n }\n /**\n * Gets the current easing mode.\n * @returns the easing mode\n */\n getEasingMode() {\n return this._easingMode;\n }\n /**\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n easeInCore(gradient) {\n throw new Error(\"You must implement this method\");\n }\n /**\n * Given an input gradient between 0 and 1, this returns the corresponding value\n * of the easing function.\n * @param gradient Defines the value between 0 and 1 we want the easing value for\n * @returns the corresponding value on the curve defined by the easing function\n */\n ease(gradient) {\n switch (this._easingMode) {\n case EasingFunction.EASINGMODE_EASEIN:\n return this.easeInCore(gradient);\n case EasingFunction.EASINGMODE_EASEOUT:\n return 1 - this.easeInCore(1 - gradient);\n }\n if (gradient >= 0.5) {\n return (1 - this.easeInCore((1 - gradient) * 2)) * 0.5 + 0.5;\n }\n return this.easeInCore(gradient * 2) * 0.5;\n }\n}\n/**\n * Interpolation follows the mathematical formula associated with the easing function.\n */\nEasingFunction.EASINGMODE_EASEIN = 0;\n/**\n * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.\n */\nEasingFunction.EASINGMODE_EASEOUT = 1;\n/**\n * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.\n */\nEasingFunction.EASINGMODE_EASEINOUT = 2;\n/**\n * Easing function with a circle shape (see link below).\n * @see https://easings.net/#easeInCirc\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions\n */\nexport class CircleEase extends EasingFunction {\n /**\n * @internal\n */\n easeInCore(gradient) {\n gradient = Math.max(0, Math.min(1, gradient));\n return 1.0 - Math.sqrt(1.0 - gradient * gradient);\n }\n}\n/**\n * Easing function with a ease back shape (see link below).\n * @see https://easings.net/#easeInBack\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions\n */\nexport class BackEase extends EasingFunction {\n /**\n * Instantiates a back ease easing\n * @see https://easings.net/#easeInBack\n * @param amplitude Defines the amplitude of the function\n */\n constructor(\n /** Defines the amplitude of the function */\n amplitude = 1) {\n super();\n this.amplitude = amplitude;\n }\n /**\n * @internal\n */\n easeInCore(gradient) {\n const num = Math.max(0, this.amplitude);\n return Math.pow(gradient, 3.0) - gradient * num * Math.sin(3.1415926535897931 * gradient);\n }\n}\n/**\n * Easing function with a bouncing shape (see link below).\n * @see https://easings.net/#easeInBounce\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions\n */\nexport class BounceEase extends EasingFunction {\n /**\n * Instantiates a bounce easing\n * @see https://easings.net/#easeInBounce\n * @param bounces Defines the number of bounces\n * @param bounciness Defines the amplitude of the bounce\n */\n constructor(\n /** Defines the number of bounces */\n bounces = 3, \n /** Defines the amplitude of the bounce */\n bounciness = 2) {\n super();\n this.bounces = bounces;\n this.bounciness = bounciness;\n }\n /**\n * @internal\n */\n easeInCore(gradient) {\n const y = Math.max(0.0, this.bounces);\n let bounciness = this.bounciness;\n if (bounciness <= 1.0) {\n bounciness = 1.001;\n }\n const num9 = Math.pow(bounciness, y);\n const num5 = 1.0 - bounciness;\n const num4 = (1.0 - num9) / num5 + num9 * 0.5;\n const num15 = gradient * num4;\n const num65 = Math.log(-num15 * (1.0 - bounciness) + 1.0) / Math.log(bounciness);\n const num3 = Math.floor(num65);\n const num13 = num3 + 1.0;\n const num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);\n const num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);\n const num7 = (num8 + num12) * 0.5;\n const num6 = gradient - num7;\n const num2 = num7 - num8;\n return (-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2) * (num6 + num2);\n }\n}\n/**\n * Easing function with a power of 3 shape (see link below).\n * @see https://easings.net/#easeInCubic\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions\n */\nexport class CubicEase extends EasingFunction {\n /**\n * @internal\n */\n easeInCore(gradient) {\n return gradient * gradient * gradient;\n }\n}\n/**\n * Easing function with an elastic shape (see link below).\n * @see https://easings.net/#easeInElastic\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions\n */\nexport class ElasticEase extends EasingFunction {\n /**\n * Instantiates an elastic easing function\n * @see https://easings.net/#easeInElastic\n * @param oscillations Defines the number of oscillations\n * @param springiness Defines the amplitude of the oscillations\n */\n constructor(\n /** Defines the number of oscillations*/\n oscillations = 3, \n /** Defines the amplitude of the oscillations*/\n springiness = 3) {\n super();\n this.oscillations = oscillations;\n this.springiness = springiness;\n }\n /**\n * @internal\n */\n easeInCore(gradient) {\n let num2;\n const num3 = Math.max(0.0, this.oscillations);\n const num = Math.max(0.0, this.springiness);\n if (num == 0) {\n num2 = gradient;\n }\n else {\n num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);\n }\n return num2 * Math.sin((6.2831853071795862 * num3 + 1.5707963267948966) * gradient);\n }\n}\n/**\n * Easing function with an exponential shape (see link below).\n * @see https://easings.net/#easeInExpo\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions\n */\nexport class ExponentialEase extends EasingFunction {\n /**\n * Instantiates an exponential easing function\n * @see https://easings.net/#easeInExpo\n * @param exponent Defines the exponent of the function\n */\n constructor(\n /** Defines the exponent of the function */\n exponent = 2) {\n super();\n this.exponent = exponent;\n }\n /**\n * @internal\n */\n easeInCore(gradient) {\n if (this.exponent <= 0) {\n return gradient;\n }\n return (Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0);\n }\n}\n/**\n * Easing function with a power shape (see link below).\n * @see https://easings.net/#easeInQuad\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions\n */\nexport class PowerEase extends EasingFunction {\n /**\n * Instantiates an power base easing function\n * @see https://easings.net/#easeInQuad\n * @param power Defines the power of the function\n */\n constructor(\n /** Defines the power of the function */\n power = 2) {\n super();\n this.power = power;\n }\n /**\n * @internal\n */\n easeInCore(gradient) {\n const y = Math.max(0.0, this.power);\n return Math.pow(gradient, y);\n }\n}\n/**\n * Easing function with a power of 2 shape (see link below).\n * @see https://easings.net/#easeInQuad\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions\n */\nexport class QuadraticEase extends EasingFunction {\n /**\n * @internal\n */\n easeInCore(gradient) {\n return gradient * gradient;\n }\n}\n/**\n * Easing function with a power of 4 shape (see link below).\n * @see https://easings.net/#easeInQuart\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions\n */\nexport class QuarticEase extends EasingFunction {\n /**\n * @internal\n */\n easeInCore(gradient) {\n return gradient * gradient * gradient * gradient;\n }\n}\n/**\n * Easing function with a power of 5 shape (see link below).\n * @see https://easings.net/#easeInQuint\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions\n */\nexport class QuinticEase extends EasingFunction {\n /**\n * @internal\n */\n easeInCore(gradient) {\n return gradient * gradient * gradient * gradient * gradient;\n }\n}\n/**\n * Easing function with a sin shape (see link below).\n * @see https://easings.net/#easeInSine\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions\n */\nexport class SineEase extends EasingFunction {\n /**\n * @internal\n */\n easeInCore(gradient) {\n return 1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient));\n }\n}\n/**\n * Easing function with a bezier shape (see link below).\n * @see http://cubic-bezier.com/#.17,.67,.83,.67\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#easing-functions\n */\nexport class BezierCurveEase extends EasingFunction {\n /**\n * Instantiates a bezier function\n * @see http://cubic-bezier.com/#.17,.67,.83,.67\n * @param x1 Defines the x component of the start tangent in the bezier curve\n * @param y1 Defines the y component of the start tangent in the bezier curve\n * @param x2 Defines the x component of the end tangent in the bezier curve\n * @param y2 Defines the y component of the end tangent in the bezier curve\n */\n constructor(\n /** Defines the x component of the start tangent in the bezier curve */\n x1 = 0, \n /** Defines the y component of the start tangent in the bezier curve */\n y1 = 0, \n /** Defines the x component of the end tangent in the bezier curve */\n x2 = 1, \n /** Defines the y component of the end tangent in the bezier curve */\n y2 = 1) {\n super();\n this.x1 = x1;\n this.y1 = y1;\n this.x2 = x2;\n this.y2 = y2;\n }\n /**\n * @internal\n */\n easeInCore(gradient) {\n return BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);\n }\n}\n//# sourceMappingURL=easing.js.map","/**\n * Composed of a frame, and an action function\n */\nexport class AnimationEvent {\n /**\n * Initializes the animation event\n * @param frame The frame for which the event is triggered\n * @param action The event to perform when triggered\n * @param onlyOnce Specifies if the event should be triggered only once\n */\n constructor(\n /** The frame for which the event is triggered **/\n frame, \n /** The event to perform when triggered **/\n action, \n /** Specifies if the event should be triggered only once**/\n onlyOnce) {\n this.frame = frame;\n this.action = action;\n this.onlyOnce = onlyOnce;\n /**\n * Specifies if the animation event is done\n */\n this.isDone = false;\n }\n /** @internal */\n _clone() {\n return new AnimationEvent(this.frame, this.action, this.onlyOnce);\n }\n}\n//# sourceMappingURL=animationEvent.js.map","import { Animation } from \"./animation.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { Tags } from \"../Misc/tags.js\";\n/**\n * This class defines the direct association between an animation and a target\n */\nexport class TargetedAnimation {\n /**\n * Returns the string \"TargetedAnimation\"\n * @returns \"TargetedAnimation\"\n */\n getClassName() {\n return \"TargetedAnimation\";\n }\n /**\n * Serialize the object\n * @returns the JSON object representing the current entity\n */\n serialize() {\n const serializationObject = {};\n serializationObject.animation = this.animation.serialize();\n serializationObject.targetId = this.target.id;\n return serializationObject;\n }\n}\n/**\n * Use this class to create coordinated animations on multiple targets\n */\nexport class AnimationGroup {\n /**\n * Gets the first frame\n */\n get from() {\n return this._from;\n }\n /**\n * Gets the last frame\n */\n get to() {\n return this._to;\n }\n /**\n * Define if the animations are started\n */\n get isStarted() {\n return this._isStarted;\n }\n /**\n * Gets a value indicating that the current group is playing\n */\n get isPlaying() {\n return this._isStarted && !this._isPaused;\n }\n /**\n * Gets or sets the speed ratio to use for all animations\n */\n get speedRatio() {\n return this._speedRatio;\n }\n /**\n * Gets or sets the speed ratio to use for all animations\n */\n set speedRatio(value) {\n if (this._speedRatio === value) {\n return;\n }\n this._speedRatio = value;\n for (let index = 0; index < this._animatables.length; index++) {\n const animatable = this._animatables[index];\n animatable.speedRatio = this._speedRatio;\n }\n }\n /**\n * Gets or sets if all animations should loop or not\n */\n get loopAnimation() {\n return this._loopAnimation;\n }\n set loopAnimation(value) {\n if (this._loopAnimation === value) {\n return;\n }\n this._loopAnimation = value;\n for (let index = 0; index < this._animatables.length; index++) {\n const animatable = this._animatables[index];\n animatable.loopAnimation = this._loopAnimation;\n }\n }\n /**\n * Gets or sets if all animations should be evaluated additively\n */\n get isAdditive() {\n return this._isAdditive;\n }\n set isAdditive(value) {\n if (this._isAdditive === value) {\n return;\n }\n this._isAdditive = value;\n for (let index = 0; index < this._animatables.length; index++) {\n const animatable = this._animatables[index];\n animatable.isAdditive = this._isAdditive;\n }\n }\n /**\n * Gets the targeted animations for this animation group\n */\n get targetedAnimations() {\n return this._targetedAnimations;\n }\n /**\n * returning the list of animatables controlled by this animation group.\n */\n get animatables() {\n return this._animatables;\n }\n /**\n * Gets the list of target animations\n */\n get children() {\n return this._targetedAnimations;\n }\n /**\n * Instantiates a new Animation Group.\n * This helps managing several animations at once.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/groupAnimations\n * @param name Defines the name of the group\n * @param scene Defines the scene the group belongs to\n */\n constructor(\n /** The name of the animation group */\n name, scene = null) {\n this.name = name;\n this._targetedAnimations = new Array();\n this._animatables = new Array();\n this._from = Number.MAX_VALUE;\n this._to = -Number.MAX_VALUE;\n this._speedRatio = 1;\n this._loopAnimation = false;\n this._isAdditive = false;\n /** @internal */\n this._parentContainer = null;\n /**\n * This observable will notify when one animation have ended\n */\n this.onAnimationEndObservable = new Observable();\n /**\n * Observer raised when one animation loops\n */\n this.onAnimationLoopObservable = new Observable();\n /**\n * Observer raised when all animations have looped\n */\n this.onAnimationGroupLoopObservable = new Observable();\n /**\n * This observable will notify when all animations have ended.\n */\n this.onAnimationGroupEndObservable = new Observable();\n /**\n * This observable will notify when all animations have paused.\n */\n this.onAnimationGroupPauseObservable = new Observable();\n /**\n * This observable will notify when all animations are playing.\n */\n this.onAnimationGroupPlayObservable = new Observable();\n /**\n * Gets or sets an object used to store user defined information for the node\n */\n this.metadata = null;\n this._animationLoopFlags = [];\n this._scene = scene || EngineStore.LastCreatedScene;\n this.uniqueId = this._scene.getUniqueId();\n this._scene.addAnimationGroup(this);\n }\n /**\n * Add an animation (with its target) in the group\n * @param animation defines the animation we want to add\n * @param target defines the target of the animation\n * @returns the TargetedAnimation object\n */\n addTargetedAnimation(animation, target) {\n const targetedAnimation = new TargetedAnimation();\n targetedAnimation.animation = animation;\n targetedAnimation.target = target;\n const keys = animation.getKeys();\n if (this._from > keys[0].frame) {\n this._from = keys[0].frame;\n }\n if (this._to < keys[keys.length - 1].frame) {\n this._to = keys[keys.length - 1].frame;\n }\n this._targetedAnimations.push(targetedAnimation);\n return targetedAnimation;\n }\n /**\n * Remove an animation from the group\n * @param animation defines the animation we want to remove\n */\n removeTargetedAnimation(animation) {\n for (let index = this._targetedAnimations.length - 1; index > -1; index--) {\n const targetedAnimation = this._targetedAnimations[index];\n if (targetedAnimation.animation === animation) {\n this._targetedAnimations.splice(index, 1);\n }\n }\n }\n /**\n * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame\n * It can add constant keys at begin or end\n * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)\n * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)\n * @returns the animation group\n */\n normalize(beginFrame = null, endFrame = null) {\n if (beginFrame == null) {\n beginFrame = this._from;\n }\n if (endFrame == null) {\n endFrame = this._to;\n }\n for (let index = 0; index < this._targetedAnimations.length; index++) {\n const targetedAnimation = this._targetedAnimations[index];\n const keys = targetedAnimation.animation.getKeys();\n const startKey = keys[0];\n const endKey = keys[keys.length - 1];\n if (startKey.frame > beginFrame) {\n const newKey = {\n frame: beginFrame,\n value: startKey.value,\n inTangent: startKey.inTangent,\n outTangent: startKey.outTangent,\n interpolation: startKey.interpolation,\n };\n keys.splice(0, 0, newKey);\n }\n if (endKey.frame < endFrame) {\n const newKey = {\n frame: endFrame,\n value: endKey.value,\n inTangent: endKey.inTangent,\n outTangent: endKey.outTangent,\n interpolation: endKey.interpolation,\n };\n keys.push(newKey);\n }\n }\n this._from = beginFrame;\n this._to = endFrame;\n return this;\n }\n _processLoop(animatable, targetedAnimation, index) {\n animatable.onAnimationLoop = () => {\n this.onAnimationLoopObservable.notifyObservers(targetedAnimation);\n if (this._animationLoopFlags[index]) {\n return;\n }\n this._animationLoopFlags[index] = true;\n this._animationLoopCount++;\n if (this._animationLoopCount === this._targetedAnimations.length) {\n this.onAnimationGroupLoopObservable.notifyObservers(this);\n this._animationLoopCount = 0;\n this._animationLoopFlags.length = 0;\n }\n };\n }\n /**\n * Start all animations on given targets\n * @param loop defines if animations must loop\n * @param speedRatio defines the ratio to apply to animation speed (1 by default)\n * @param from defines the from key (optional)\n * @param to defines the to key (optional)\n * @param isAdditive defines the additive state for the resulting animatables (optional)\n * @returns the current animation group\n */\n start(loop = false, speedRatio = 1, from, to, isAdditive) {\n if (this._isStarted || this._targetedAnimations.length === 0) {\n return this;\n }\n this._loopAnimation = loop;\n this._animationLoopCount = 0;\n this._animationLoopFlags.length = 0;\n for (let index = 0; index < this._targetedAnimations.length; index++) {\n const targetedAnimation = this._targetedAnimations[index];\n const animatable = this._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this._from, to !== undefined ? to : this._to, loop, speedRatio, undefined, undefined, isAdditive !== undefined ? isAdditive : this._isAdditive);\n animatable.onAnimationEnd = () => {\n this.onAnimationEndObservable.notifyObservers(targetedAnimation);\n this._checkAnimationGroupEnded(animatable);\n };\n this._processLoop(animatable, targetedAnimation, index);\n this._animatables.push(animatable);\n }\n this._speedRatio = speedRatio;\n this._isStarted = true;\n this._isPaused = false;\n this.onAnimationGroupPlayObservable.notifyObservers(this);\n return this;\n }\n /**\n * Pause all animations\n * @returns the animation group\n */\n pause() {\n if (!this._isStarted) {\n return this;\n }\n this._isPaused = true;\n for (let index = 0; index < this._animatables.length; index++) {\n const animatable = this._animatables[index];\n animatable.pause();\n }\n this.onAnimationGroupPauseObservable.notifyObservers(this);\n return this;\n }\n /**\n * Play all animations to initial state\n * This function will start() the animations if they were not started or will restart() them if they were paused\n * @param loop defines if animations must loop\n * @returns the animation group\n */\n play(loop) {\n // only if all animatables are ready and exist\n if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {\n if (loop !== undefined) {\n this.loopAnimation = loop;\n }\n this.restart();\n }\n else {\n this.stop();\n this.start(loop, this._speedRatio);\n }\n this._isPaused = false;\n return this;\n }\n /**\n * Reset all animations to initial state\n * @returns the animation group\n */\n reset() {\n if (!this._isStarted) {\n this.play();\n this.goToFrame(0);\n this.stop();\n return this;\n }\n for (let index = 0; index < this._animatables.length; index++) {\n const animatable = this._animatables[index];\n animatable.reset();\n }\n return this;\n }\n /**\n * Restart animations from key 0\n * @returns the animation group\n */\n restart() {\n if (!this._isStarted) {\n return this;\n }\n for (let index = 0; index < this._animatables.length; index++) {\n const animatable = this._animatables[index];\n animatable.restart();\n }\n this.onAnimationGroupPlayObservable.notifyObservers(this);\n return this;\n }\n /**\n * Stop all animations\n * @returns the animation group\n */\n stop() {\n if (!this._isStarted) {\n return this;\n }\n const list = this._animatables.slice();\n for (let index = 0; index < list.length; index++) {\n list[index].stop(undefined, undefined, true);\n }\n // We will take care of removing all stopped animatables\n let curIndex = 0;\n for (let index = 0; index < this._scene._activeAnimatables.length; index++) {\n const animatable = this._scene._activeAnimatables[index];\n if (animatable._runtimeAnimations.length > 0) {\n this._scene._activeAnimatables[curIndex++] = animatable;\n }\n }\n this._scene._activeAnimatables.length = curIndex;\n this._isStarted = false;\n return this;\n }\n /**\n * Set animation weight for all animatables\n * @param weight defines the weight to use\n * @returns the animationGroup\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#animation-weights\n */\n setWeightForAllAnimatables(weight) {\n for (let index = 0; index < this._animatables.length; index++) {\n const animatable = this._animatables[index];\n animatable.weight = weight;\n }\n return this;\n }\n /**\n * Synchronize and normalize all animatables with a source animatable\n * @param root defines the root animatable to synchronize with (null to stop synchronizing)\n * @returns the animationGroup\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#animation-weights\n */\n syncAllAnimationsWith(root) {\n for (let index = 0; index < this._animatables.length; index++) {\n const animatable = this._animatables[index];\n animatable.syncWith(root);\n }\n return this;\n }\n /**\n * Goes to a specific frame in this animation group\n * @param frame the frame number to go to\n * @returns the animationGroup\n */\n goToFrame(frame) {\n if (!this._isStarted) {\n return this;\n }\n for (let index = 0; index < this._animatables.length; index++) {\n const animatable = this._animatables[index];\n animatable.goToFrame(frame);\n }\n return this;\n }\n /**\n * Dispose all associated resources\n */\n dispose() {\n this._targetedAnimations.length = 0;\n this._animatables.length = 0;\n // Remove from scene\n const index = this._scene.animationGroups.indexOf(this);\n if (index > -1) {\n this._scene.animationGroups.splice(index, 1);\n }\n if (this._parentContainer) {\n const index = this._parentContainer.animationGroups.indexOf(this);\n if (index > -1) {\n this._parentContainer.animationGroups.splice(index, 1);\n }\n this._parentContainer = null;\n }\n this.onAnimationEndObservable.clear();\n this.onAnimationGroupEndObservable.clear();\n this.onAnimationGroupPauseObservable.clear();\n this.onAnimationGroupPlayObservable.clear();\n this.onAnimationLoopObservable.clear();\n this.onAnimationGroupLoopObservable.clear();\n }\n _checkAnimationGroupEnded(animatable) {\n // animatable should be taken out of the array\n const idx = this._animatables.indexOf(animatable);\n if (idx > -1) {\n this._animatables.splice(idx, 1);\n }\n // all animatables were removed? animation group ended!\n if (this._animatables.length === 0) {\n this._isStarted = false;\n this.onAnimationGroupEndObservable.notifyObservers(this);\n }\n }\n /**\n * Clone the current animation group and returns a copy\n * @param newName defines the name of the new group\n * @param targetConverter defines an optional function used to convert current animation targets to new ones\n * @param cloneAnimations defines if the animations should be cloned or referenced\n * @returns the new animation group\n */\n clone(newName, targetConverter, cloneAnimations = false) {\n const newGroup = new AnimationGroup(newName || this.name, this._scene);\n for (const targetAnimation of this._targetedAnimations) {\n newGroup.addTargetedAnimation(cloneAnimations ? targetAnimation.animation.clone() : targetAnimation.animation, targetConverter ? targetConverter(targetAnimation.target) : targetAnimation.target);\n }\n return newGroup;\n }\n /**\n * Serializes the animationGroup to an object\n * @returns Serialized object\n */\n serialize() {\n const serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.from = this.from;\n serializationObject.to = this.to;\n serializationObject.targetedAnimations = [];\n for (let targetedAnimationIndex = 0; targetedAnimationIndex < this.targetedAnimations.length; targetedAnimationIndex++) {\n const targetedAnimation = this.targetedAnimations[targetedAnimationIndex];\n serializationObject.targetedAnimations[targetedAnimationIndex] = targetedAnimation.serialize();\n }\n if (Tags && Tags.HasTags(this)) {\n serializationObject.tags = Tags.GetTags(this);\n }\n // Metadata\n if (this.metadata) {\n serializationObject.metadata = this.metadata;\n }\n return serializationObject;\n }\n // Statics\n /**\n * Returns a new AnimationGroup object parsed from the source provided.\n * @param parsedAnimationGroup defines the source\n * @param scene defines the scene that will receive the animationGroup\n * @returns a new AnimationGroup\n */\n static Parse(parsedAnimationGroup, scene) {\n const animationGroup = new AnimationGroup(parsedAnimationGroup.name, scene);\n for (let i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {\n const targetedAnimation = parsedAnimationGroup.targetedAnimations[i];\n const animation = Animation.Parse(targetedAnimation.animation);\n const id = targetedAnimation.targetId;\n if (targetedAnimation.animation.property === \"influence\") {\n // morph target animation\n const morphTarget = scene.getMorphTargetById(id);\n if (morphTarget) {\n animationGroup.addTargetedAnimation(animation, morphTarget);\n }\n }\n else {\n const targetNode = scene.getNodeById(id);\n if (targetNode != null) {\n animationGroup.addTargetedAnimation(animation, targetNode);\n }\n }\n }\n if (parsedAnimationGroup.from !== null && parsedAnimationGroup.to !== null) {\n animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);\n }\n if (Tags) {\n Tags.AddTagsTo(animationGroup, parsedAnimationGroup.tags);\n }\n if (parsedAnimationGroup.metadata !== undefined) {\n animationGroup.metadata = parsedAnimationGroup.metadata;\n }\n return animationGroup;\n }\n /**\n * Convert the keyframes for all animations belonging to the group to be relative to a given reference frame.\n * @param sourceAnimationGroup defines the AnimationGroup containing animations to convert\n * @param referenceFrame defines the frame that keyframes in the range will be relative to\n * @param range defines the name of the AnimationRange belonging to the animations in the group to convert\n * @param cloneOriginal defines whether or not to clone the group and convert the clone or convert the original group (default is false)\n * @param clonedName defines the name of the resulting cloned AnimationGroup if cloneOriginal is true\n * @returns a new AnimationGroup if cloneOriginal is true or the original AnimationGroup if cloneOriginal is false\n */\n static MakeAnimationAdditive(sourceAnimationGroup, referenceFrame = 0, range, cloneOriginal = false, clonedName) {\n let animationGroup = sourceAnimationGroup;\n if (cloneOriginal) {\n animationGroup = sourceAnimationGroup.clone(clonedName || animationGroup.name);\n }\n const targetedAnimations = animationGroup.targetedAnimations;\n for (let index = 0; index < targetedAnimations.length; index++) {\n const targetedAnimation = targetedAnimations[index];\n Animation.MakeAnimationAdditive(targetedAnimation.animation, referenceFrame, range);\n }\n animationGroup.isAdditive = true;\n return animationGroup;\n }\n /**\n * Returns the string \"AnimationGroup\"\n * @returns \"AnimationGroup\"\n */\n getClassName() {\n return \"AnimationGroup\";\n }\n /**\n * Creates a detailed string about the object\n * @param fullDetails defines if the output string will support multiple levels of logging within scene loading\n * @returns a string representing the object\n */\n toString(fullDetails) {\n let ret = \"Name: \" + this.name;\n ret += \", type: \" + this.getClassName();\n if (fullDetails) {\n ret += \", from: \" + this._from;\n ret += \", to: \" + this._to;\n ret += \", isStarted: \" + this._isStarted;\n ret += \", speedRatio: \" + this._speedRatio;\n ret += \", targetedAnimations length: \" + this._targetedAnimations.length;\n ret += \", animatables length: \" + this._animatables;\n }\n return ret;\n }\n}\n//# sourceMappingURL=animationGroup.js.map","import { Matrix, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { AbstractMesh } from \"../Meshes/abstractMesh.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { DeepCopier } from \"../Misc/deepCopier.js\";\nimport { TransformNode } from \"./transformNode.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Tools } from \"../Misc/tools.js\";\nMesh._instancedMeshFactory = (name, mesh) => {\n const instance = new InstancedMesh(name, mesh);\n if (mesh.instancedBuffers) {\n instance.instancedBuffers = {};\n for (const key in mesh.instancedBuffers) {\n instance.instancedBuffers[key] = mesh.instancedBuffers[key];\n }\n }\n return instance;\n};\n/**\n * Creates an instance based on a source mesh.\n */\nexport class InstancedMesh extends AbstractMesh {\n /**\n * Creates a new InstancedMesh object from the mesh source.\n * @param name defines the name of the instance\n * @param source the mesh to create the instance from\n */\n constructor(name, source) {\n super(name, source.getScene());\n /** @internal */\n this._indexInSourceMeshInstanceArray = -1;\n /** @internal */\n this._distanceToCamera = 0;\n source.addInstance(this);\n this._sourceMesh = source;\n this._unIndexed = source._unIndexed;\n this.position.copyFrom(source.position);\n this.rotation.copyFrom(source.rotation);\n this.scaling.copyFrom(source.scaling);\n if (source.rotationQuaternion) {\n this.rotationQuaternion = source.rotationQuaternion.clone();\n }\n this.animations = source.animations.slice();\n for (const range of source.getAnimationRanges()) {\n if (range != null) {\n this.createAnimationRange(range.name, range.from, range.to);\n }\n }\n this.infiniteDistance = source.infiniteDistance;\n this.setPivotMatrix(source.getPivotMatrix());\n this.refreshBoundingInfo(true, true);\n this._syncSubMeshes();\n }\n /**\n * Returns the string \"InstancedMesh\".\n */\n getClassName() {\n return \"InstancedMesh\";\n }\n /** Gets the list of lights affecting that mesh */\n get lightSources() {\n return this._sourceMesh._lightSources;\n }\n _resyncLightSources() {\n // Do nothing as all the work will be done by source mesh\n }\n _resyncLightSource() {\n // Do nothing as all the work will be done by source mesh\n }\n _removeLightSource() {\n // Do nothing as all the work will be done by source mesh\n }\n // Methods\n /**\n * If the source mesh receives shadows\n */\n get receiveShadows() {\n return this._sourceMesh.receiveShadows;\n }\n set receiveShadows(_value) {\n var _a;\n if (((_a = this._sourceMesh) === null || _a === void 0 ? void 0 : _a.receiveShadows) !== _value) {\n Tools.Warn(\"Setting receiveShadows on an instanced mesh has no effect\");\n }\n }\n /**\n * The material of the source mesh\n */\n get material() {\n return this._sourceMesh.material;\n }\n set material(_value) {\n var _a;\n if (((_a = this._sourceMesh) === null || _a === void 0 ? void 0 : _a.material) !== _value) {\n Tools.Warn(\"Setting material on an instanced mesh has no effect\");\n }\n }\n /**\n * Visibility of the source mesh\n */\n get visibility() {\n return this._sourceMesh.visibility;\n }\n set visibility(_value) {\n var _a;\n if (((_a = this._sourceMesh) === null || _a === void 0 ? void 0 : _a.visibility) !== _value) {\n Tools.Warn(\"Setting visibility on an instanced mesh has no effect\");\n }\n }\n /**\n * Skeleton of the source mesh\n */\n get skeleton() {\n return this._sourceMesh.skeleton;\n }\n set skeleton(_value) {\n var _a;\n if (((_a = this._sourceMesh) === null || _a === void 0 ? void 0 : _a.skeleton) !== _value) {\n Tools.Warn(\"Setting skeleton on an instanced mesh has no effect\");\n }\n }\n /**\n * Rendering ground id of the source mesh\n */\n get renderingGroupId() {\n return this._sourceMesh.renderingGroupId;\n }\n set renderingGroupId(value) {\n if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {\n return;\n }\n //no-op with warning\n Logger.Warn(\"Note - setting renderingGroupId of an instanced mesh has no effect on the scene\");\n }\n /**\n * Returns the total number of vertices (integer).\n */\n getTotalVertices() {\n return this._sourceMesh ? this._sourceMesh.getTotalVertices() : 0;\n }\n /**\n * Returns a positive integer : the total number of indices in this mesh geometry.\n * @returns the number of indices or zero if the mesh has no geometry.\n */\n getTotalIndices() {\n return this._sourceMesh.getTotalIndices();\n }\n /**\n * The source mesh of the instance\n */\n get sourceMesh() {\n return this._sourceMesh;\n }\n /**\n * Creates a new InstancedMesh object from the mesh model.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/copies/instances\n * @param name defines the name of the new instance\n * @returns a new InstancedMesh\n */\n createInstance(name) {\n return this._sourceMesh.createInstance(name);\n }\n /**\n * Is this node ready to be used/rendered\n * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)\n * @returns {boolean} is it ready\n */\n isReady(completeCheck = false) {\n return this._sourceMesh.isReady(completeCheck, true);\n }\n /**\n * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.\n * @param kind kind of verticies to retrieve (eg. positions, normals, uvs, etc.)\n * @param copyWhenShared If true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.\n * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is\n * @returns a float array or a Float32Array of the requested kind of data : positions, normals, uvs, etc.\n */\n getVerticesData(kind, copyWhenShared, forceCopy) {\n return this._sourceMesh.getVerticesData(kind, copyWhenShared, forceCopy);\n }\n /**\n * Sets the vertex data of the mesh geometry for the requested `kind`.\n * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.\n * The `data` are either a numeric array either a Float32Array.\n * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initially none) or updater.\n * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).\n * Note that a new underlying VertexBuffer object is created each call.\n * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.\n *\n * Possible `kind` values :\n * - VertexBuffer.PositionKind\n * - VertexBuffer.UVKind\n * - VertexBuffer.UV2Kind\n * - VertexBuffer.UV3Kind\n * - VertexBuffer.UV4Kind\n * - VertexBuffer.UV5Kind\n * - VertexBuffer.UV6Kind\n * - VertexBuffer.ColorKind\n * - VertexBuffer.MatricesIndicesKind\n * - VertexBuffer.MatricesIndicesExtraKind\n * - VertexBuffer.MatricesWeightsKind\n * - VertexBuffer.MatricesWeightsExtraKind\n *\n * Returns the Mesh.\n * @param kind\n * @param data\n * @param updatable\n * @param stride\n */\n setVerticesData(kind, data, updatable, stride) {\n if (this.sourceMesh) {\n this.sourceMesh.setVerticesData(kind, data, updatable, stride);\n }\n return this.sourceMesh;\n }\n /**\n * Updates the existing vertex data of the mesh geometry for the requested `kind`.\n * If the mesh has no geometry, it is simply returned as it is.\n * The `data` are either a numeric array either a Float32Array.\n * No new underlying VertexBuffer object is created.\n * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.\n * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.\n *\n * Possible `kind` values :\n * - VertexBuffer.PositionKind\n * - VertexBuffer.UVKind\n * - VertexBuffer.UV2Kind\n * - VertexBuffer.UV3Kind\n * - VertexBuffer.UV4Kind\n * - VertexBuffer.UV5Kind\n * - VertexBuffer.UV6Kind\n * - VertexBuffer.ColorKind\n * - VertexBuffer.MatricesIndicesKind\n * - VertexBuffer.MatricesIndicesExtraKind\n * - VertexBuffer.MatricesWeightsKind\n * - VertexBuffer.MatricesWeightsExtraKind\n *\n * Returns the Mesh.\n * @param kind\n * @param data\n * @param updateExtends\n * @param makeItUnique\n */\n updateVerticesData(kind, data, updateExtends, makeItUnique) {\n if (this.sourceMesh) {\n this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);\n }\n return this.sourceMesh;\n }\n /**\n * Sets the mesh indices.\n * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).\n * If the mesh has no geometry, a new Geometry object is created and set to the mesh.\n * This method creates a new index buffer each call.\n * Returns the Mesh.\n * @param indices\n * @param totalVertices\n */\n setIndices(indices, totalVertices = null) {\n if (this.sourceMesh) {\n this.sourceMesh.setIndices(indices, totalVertices);\n }\n return this.sourceMesh;\n }\n /**\n * Boolean : True if the mesh owns the requested kind of data.\n * @param kind\n */\n isVerticesDataPresent(kind) {\n return this._sourceMesh.isVerticesDataPresent(kind);\n }\n /**\n * Returns an array of indices (IndicesArray).\n */\n getIndices() {\n return this._sourceMesh.getIndices();\n }\n get _positions() {\n return this._sourceMesh._positions;\n }\n /**\n * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.\n * This means the mesh underlying bounding box and sphere are recomputed.\n * @param applySkeleton defines whether to apply the skeleton before computing the bounding info\n * @param applyMorph defines whether to apply the morph target before computing the bounding info\n * @returns the current mesh\n */\n refreshBoundingInfo(applySkeleton = false, applyMorph = false) {\n if (this.hasBoundingInfo && this.getBoundingInfo().isLocked) {\n return this;\n }\n const bias = this._sourceMesh.geometry ? this._sourceMesh.geometry.boundingBias : null;\n this._refreshBoundingInfo(this._sourceMesh._getPositionData(applySkeleton, applyMorph), bias);\n return this;\n }\n /** @internal */\n _preActivate() {\n if (this._currentLOD) {\n this._currentLOD._preActivate();\n }\n return this;\n }\n /**\n * @internal\n */\n _activate(renderId, intermediateRendering) {\n super._activate(renderId, intermediateRendering);\n if (!this._sourceMesh.subMeshes) {\n Logger.Warn(\"Instances should only be created for meshes with geometry.\");\n }\n if (this._currentLOD) {\n const differentSign = this._currentLOD._getWorldMatrixDeterminant() >= 0 !== this._getWorldMatrixDeterminant() >= 0;\n if (differentSign) {\n this._internalAbstractMeshDataInfo._actAsRegularMesh = true;\n return true;\n }\n this._internalAbstractMeshDataInfo._actAsRegularMesh = false;\n this._currentLOD._registerInstanceForRenderId(this, renderId);\n if (intermediateRendering) {\n if (!this._currentLOD._internalAbstractMeshDataInfo._isActiveIntermediate) {\n this._currentLOD._internalAbstractMeshDataInfo._onlyForInstancesIntermediate = true;\n return true;\n }\n }\n else {\n if (!this._currentLOD._internalAbstractMeshDataInfo._isActive) {\n this._currentLOD._internalAbstractMeshDataInfo._onlyForInstances = true;\n return true;\n }\n }\n }\n return false;\n }\n /** @internal */\n _postActivate() {\n if (this._sourceMesh.edgesShareWithInstances && this._sourceMesh._edgesRenderer && this._sourceMesh._edgesRenderer.isEnabled && this._sourceMesh._renderingGroup) {\n // we are using the edge renderer of the source mesh\n this._sourceMesh._renderingGroup._edgesRenderers.pushNoDuplicate(this._sourceMesh._edgesRenderer);\n this._sourceMesh._edgesRenderer.customInstances.push(this.getWorldMatrix());\n }\n else if (this._edgesRenderer && this._edgesRenderer.isEnabled && this._sourceMesh._renderingGroup) {\n // we are using the edge renderer defined for this instance\n this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer);\n }\n }\n getWorldMatrix() {\n if (this._currentLOD && this._currentLOD.billboardMode !== TransformNode.BILLBOARDMODE_NONE && this._currentLOD._masterMesh !== this) {\n if (!this._billboardWorldMatrix) {\n this._billboardWorldMatrix = new Matrix();\n }\n const tempMaster = this._currentLOD._masterMesh;\n this._currentLOD._masterMesh = this;\n TmpVectors.Vector3[7].copyFrom(this._currentLOD.position);\n this._currentLOD.position.set(0, 0, 0);\n this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(true));\n this._currentLOD.position.copyFrom(TmpVectors.Vector3[7]);\n this._currentLOD._masterMesh = tempMaster;\n return this._billboardWorldMatrix;\n }\n return super.getWorldMatrix();\n }\n get isAnInstance() {\n return true;\n }\n /**\n * Returns the current associated LOD AbstractMesh.\n * @param camera\n */\n getLOD(camera) {\n if (!camera) {\n return this;\n }\n const sourceMeshLODLevels = this.sourceMesh.getLODLevels();\n if (!sourceMeshLODLevels || sourceMeshLODLevels.length === 0) {\n this._currentLOD = this.sourceMesh;\n }\n else {\n const boundingInfo = this.getBoundingInfo();\n this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);\n }\n return this._currentLOD;\n }\n /**\n * @internal\n */\n _preActivateForIntermediateRendering(renderId) {\n return this.sourceMesh._preActivateForIntermediateRendering(renderId);\n }\n /** @internal */\n _syncSubMeshes() {\n this.releaseSubMeshes();\n if (this._sourceMesh.subMeshes) {\n for (let index = 0; index < this._sourceMesh.subMeshes.length; index++) {\n this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);\n }\n }\n return this;\n }\n /** @internal */\n _generatePointsArray() {\n return this._sourceMesh._generatePointsArray();\n }\n /** @internal */\n _updateBoundingInfo() {\n if (this.hasBoundingInfo) {\n this.getBoundingInfo().update(this.worldMatrixFromCache);\n }\n else {\n this.buildBoundingInfo(this.absolutePosition, this.absolutePosition, this.worldMatrixFromCache);\n }\n this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);\n return this;\n }\n /**\n * Creates a new InstancedMesh from the current mesh.\n *\n * Returns the clone.\n * @param name the cloned mesh name\n * @param newParent the optional Node to parent the clone to.\n * @param doNotCloneChildren if `true` the model children aren't cloned.\n * @param newSourceMesh if set this mesh will be used as the source mesh instead of ths instance's one\n * @returns the clone\n */\n clone(name, newParent = null, doNotCloneChildren, newSourceMesh) {\n const result = (newSourceMesh || this._sourceMesh).createInstance(name);\n // Deep copy\n DeepCopier.DeepCopy(this, result, [\n \"name\",\n \"subMeshes\",\n \"uniqueId\",\n \"parent\",\n \"lightSources\",\n \"receiveShadows\",\n \"material\",\n \"visibility\",\n \"skeleton\",\n \"sourceMesh\",\n \"isAnInstance\",\n \"facetNb\",\n \"isFacetDataEnabled\",\n \"isBlocked\",\n \"useBones\",\n \"hasInstances\",\n \"collider\",\n \"edgesRenderer\",\n \"forward\",\n \"up\",\n \"right\",\n \"absolutePosition\",\n \"absoluteScaling\",\n \"absoluteRotationQuaternion\",\n \"isWorldMatrixFrozen\",\n \"nonUniformScaling\",\n \"behaviors\",\n \"worldMatrixFromCache\",\n \"hasThinInstances\",\n \"hasBoundingInfo\",\n ], []);\n // Bounding info\n this.refreshBoundingInfo();\n // Parent\n if (newParent) {\n result.parent = newParent;\n }\n if (!doNotCloneChildren) {\n // Children\n for (let index = 0; index < this.getScene().meshes.length; index++) {\n const mesh = this.getScene().meshes[index];\n if (mesh.parent === this) {\n mesh.clone(mesh.name, result);\n }\n }\n }\n result.computeWorldMatrix(true);\n this.onClonedObservable.notifyObservers(result);\n return result;\n }\n /**\n * Disposes the InstancedMesh.\n * Returns nothing.\n * @param doNotRecurse\n * @param disposeMaterialAndTextures\n */\n dispose(doNotRecurse, disposeMaterialAndTextures = false) {\n // Remove from mesh\n this._sourceMesh.removeInstance(this);\n super.dispose(doNotRecurse, disposeMaterialAndTextures);\n }\n /**\n * @internal\n */\n _serializeAsParent(serializationObject) {\n super._serializeAsParent(serializationObject);\n serializationObject.parentId = this._sourceMesh.uniqueId;\n serializationObject.parentInstanceIndex = this._indexInSourceMeshInstanceArray;\n }\n /**\n * Instantiate (when possible) or clone that node with its hierarchy\n * @param newParent defines the new parent to use for the instance (or clone)\n * @param options defines options to configure how copy is done\n * @param options.doNotInstantiate defines if the model must be instantiated or just cloned\n * @param options.newSourcedMesh newSourcedMesh the new source mesh for the instance (or clone)\n * @param onNewNodeCreated defines an option callback to call when a clone or an instance is created\n * @returns an instance (or a clone) of the current node with its hierarchy\n */\n instantiateHierarchy(newParent = null, options, onNewNodeCreated) {\n const clone = this.clone(\"Clone of \" + (this.name || this.id), newParent || this.parent, true, options && options.newSourcedMesh);\n if (clone) {\n if (onNewNodeCreated) {\n onNewNodeCreated(this, clone);\n }\n }\n for (const child of this.getChildTransformNodes(true)) {\n child.instantiateHierarchy(clone, options, onNewNodeCreated);\n }\n return clone;\n }\n}\nMesh.prototype.registerInstancedBuffer = function (kind, stride) {\n var _a, _b;\n // Remove existing one\n (_b = (_a = this._userInstancedBuffersStorage) === null || _a === void 0 ? void 0 : _a.vertexBuffers[kind]) === null || _b === void 0 ? void 0 : _b.dispose();\n // Creates the instancedBuffer field if not present\n if (!this.instancedBuffers) {\n this.instancedBuffers = {};\n for (const instance of this.instances) {\n instance.instancedBuffers = {};\n }\n if (!this._userInstancedBuffersStorage) {\n this._userInstancedBuffersStorage = {\n data: {},\n vertexBuffers: {},\n strides: {},\n sizes: {},\n vertexArrayObjects: this.getEngine().getCaps().vertexArrayObject ? {} : undefined,\n };\n }\n }\n // Creates an empty property for this kind\n this.instancedBuffers[kind] = null;\n this._userInstancedBuffersStorage.strides[kind] = stride;\n this._userInstancedBuffersStorage.sizes[kind] = stride * 32; // Initial size\n this._userInstancedBuffersStorage.data[kind] = new Float32Array(this._userInstancedBuffersStorage.sizes[kind]);\n this._userInstancedBuffersStorage.vertexBuffers[kind] = new VertexBuffer(this.getEngine(), this._userInstancedBuffersStorage.data[kind], kind, true, false, stride, true);\n for (const instance of this.instances) {\n instance.instancedBuffers[kind] = null;\n }\n this._invalidateInstanceVertexArrayObject();\n this._markSubMeshesAsAttributesDirty();\n};\nMesh.prototype._processInstancedBuffers = function (visibleInstances, renderSelf) {\n const instanceCount = visibleInstances ? visibleInstances.length : 0;\n for (const kind in this.instancedBuffers) {\n let size = this._userInstancedBuffersStorage.sizes[kind];\n const stride = this._userInstancedBuffersStorage.strides[kind];\n // Resize if required\n const expectedSize = (instanceCount + 1) * stride;\n while (size < expectedSize) {\n size *= 2;\n }\n if (this._userInstancedBuffersStorage.data[kind].length != size) {\n this._userInstancedBuffersStorage.data[kind] = new Float32Array(size);\n this._userInstancedBuffersStorage.sizes[kind] = size;\n if (this._userInstancedBuffersStorage.vertexBuffers[kind]) {\n this._userInstancedBuffersStorage.vertexBuffers[kind].dispose();\n this._userInstancedBuffersStorage.vertexBuffers[kind] = null;\n }\n }\n const data = this._userInstancedBuffersStorage.data[kind];\n // Update data buffer\n let offset = 0;\n if (renderSelf) {\n const value = this.instancedBuffers[kind];\n if (value.toArray) {\n value.toArray(data, offset);\n }\n else if (value.copyToArray) {\n value.copyToArray(data, offset);\n }\n else {\n data[offset] = value;\n }\n offset += stride;\n }\n for (let instanceIndex = 0; instanceIndex < instanceCount; instanceIndex++) {\n const instance = visibleInstances[instanceIndex];\n const value = instance.instancedBuffers[kind];\n if (value.toArray) {\n value.toArray(data, offset);\n }\n else if (value.copyToArray) {\n value.copyToArray(data, offset);\n }\n else {\n data[offset] = value;\n }\n offset += stride;\n }\n // Update vertex buffer\n if (!this._userInstancedBuffersStorage.vertexBuffers[kind]) {\n this._userInstancedBuffersStorage.vertexBuffers[kind] = new VertexBuffer(this.getEngine(), this._userInstancedBuffersStorage.data[kind], kind, true, false, stride, true);\n this._invalidateInstanceVertexArrayObject();\n }\n else {\n this._userInstancedBuffersStorage.vertexBuffers[kind].updateDirectly(data, 0);\n }\n }\n};\nMesh.prototype._invalidateInstanceVertexArrayObject = function () {\n if (!this._userInstancedBuffersStorage || this._userInstancedBuffersStorage.vertexArrayObjects === undefined) {\n return;\n }\n for (const kind in this._userInstancedBuffersStorage.vertexArrayObjects) {\n this.getEngine().releaseVertexArrayObject(this._userInstancedBuffersStorage.vertexArrayObjects[kind]);\n }\n this._userInstancedBuffersStorage.vertexArrayObjects = {};\n};\nMesh.prototype._disposeInstanceSpecificData = function () {\n if (this._instanceDataStorage.instancesBuffer) {\n this._instanceDataStorage.instancesBuffer.dispose();\n this._instanceDataStorage.instancesBuffer = null;\n }\n while (this.instances.length) {\n this.instances[0].dispose();\n }\n for (const kind in this.instancedBuffers) {\n if (this._userInstancedBuffersStorage.vertexBuffers[kind]) {\n this._userInstancedBuffersStorage.vertexBuffers[kind].dispose();\n }\n }\n this._invalidateInstanceVertexArrayObject();\n this.instancedBuffers = {};\n};\n//# sourceMappingURL=instancedMesh.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize, SerializationHelper, serializeAsColor3, expandToProperty } from \"../Misc/decorators.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Color3, TmpColors } from \"../Maths/math.color.js\";\nimport { Node } from \"../node.js\";\nimport { UniformBuffer } from \"../Materials/uniformBuffer.js\";\nimport { GetClass } from \"../Misc/typeStore.js\";\nimport { LightConstants } from \"./lightConstants.js\";\n/**\n * Base class of all the lights in Babylon. It groups all the generic information about lights.\n * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.\n * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased.\n */\nexport class Light extends Node {\n /**\n * Defines how far from the source the light is impacting in scene units.\n * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.\n */\n get range() {\n return this._range;\n }\n /**\n * Defines how far from the source the light is impacting in scene units.\n * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.\n */\n set range(value) {\n this._range = value;\n this._inverseSquaredRange = 1.0 / (this.range * this.range);\n }\n /**\n * Gets the photometric scale used to interpret the intensity.\n * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.\n */\n get intensityMode() {\n return this._intensityMode;\n }\n /**\n * Sets the photometric scale used to interpret the intensity.\n * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.\n */\n set intensityMode(value) {\n this._intensityMode = value;\n this._computePhotometricScale();\n }\n /**\n * Gets the light radius used by PBR Materials to simulate soft area lights.\n */\n get radius() {\n return this._radius;\n }\n /**\n * sets the light radius used by PBR Materials to simulate soft area lights.\n */\n set radius(value) {\n this._radius = value;\n this._computePhotometricScale();\n }\n /**\n * Gets whether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching\n * the current shadow generator.\n */\n get shadowEnabled() {\n return this._shadowEnabled;\n }\n /**\n * Sets whether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching\n * the current shadow generator.\n */\n set shadowEnabled(value) {\n if (this._shadowEnabled === value) {\n return;\n }\n this._shadowEnabled = value;\n this._markMeshesAsLightDirty();\n }\n /**\n * Gets the only meshes impacted by this light.\n */\n get includedOnlyMeshes() {\n return this._includedOnlyMeshes;\n }\n /**\n * Sets the only meshes impacted by this light.\n */\n set includedOnlyMeshes(value) {\n this._includedOnlyMeshes = value;\n this._hookArrayForIncludedOnly(value);\n }\n /**\n * Gets the meshes not impacted by this light.\n */\n get excludedMeshes() {\n return this._excludedMeshes;\n }\n /**\n * Sets the meshes not impacted by this light.\n */\n set excludedMeshes(value) {\n this._excludedMeshes = value;\n this._hookArrayForExcluded(value);\n }\n /**\n * Gets the layer id use to find what meshes are not impacted by the light.\n * Inactive if 0\n */\n get excludeWithLayerMask() {\n return this._excludeWithLayerMask;\n }\n /**\n * Sets the layer id use to find what meshes are not impacted by the light.\n * Inactive if 0\n */\n set excludeWithLayerMask(value) {\n this._excludeWithLayerMask = value;\n this._resyncMeshes();\n }\n /**\n * Gets the layer id use to find what meshes are impacted by the light.\n * Inactive if 0\n */\n get includeOnlyWithLayerMask() {\n return this._includeOnlyWithLayerMask;\n }\n /**\n * Sets the layer id use to find what meshes are impacted by the light.\n * Inactive if 0\n */\n set includeOnlyWithLayerMask(value) {\n this._includeOnlyWithLayerMask = value;\n this._resyncMeshes();\n }\n /**\n * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)\n */\n get lightmapMode() {\n return this._lightmapMode;\n }\n /**\n * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)\n */\n set lightmapMode(value) {\n if (this._lightmapMode === value) {\n return;\n }\n this._lightmapMode = value;\n this._markMeshesAsLightDirty();\n }\n /**\n * Creates a Light object in the scene.\n * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction\n * @param name The friendly name of the light\n * @param scene The scene the light belongs too\n */\n constructor(name, scene) {\n super(name, scene);\n /**\n * Diffuse gives the basic color to an object.\n */\n this.diffuse = new Color3(1.0, 1.0, 1.0);\n /**\n * Specular produces a highlight color on an object.\n * Note: This is not affecting PBR materials.\n */\n this.specular = new Color3(1.0, 1.0, 1.0);\n /**\n * Defines the falloff type for this light. This lets overriding how punctual light are\n * falling off base on range or angle.\n * This can be set to any values in Light.FALLOFF_x.\n *\n * Note: This is only useful for PBR Materials at the moment. This could be extended if required to\n * other types of materials.\n */\n this.falloffType = Light.FALLOFF_DEFAULT;\n /**\n * Strength of the light.\n * Note: By default it is define in the framework own unit.\n * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.\n */\n this.intensity = 1.0;\n this._range = Number.MAX_VALUE;\n this._inverseSquaredRange = 0;\n /**\n * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type\n * of light.\n */\n this._photometricScale = 1.0;\n this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;\n this._radius = 0.00001;\n /**\n * Defines the rendering priority of the lights. It can help in case of fallback or number of lights\n * exceeding the number allowed of the materials.\n */\n this.renderPriority = 0;\n this._shadowEnabled = true;\n this._excludeWithLayerMask = 0;\n this._includeOnlyWithLayerMask = 0;\n this._lightmapMode = 0;\n /**\n * Shadow generators associated to the light.\n * @internal Internal use only.\n */\n this._shadowGenerators = null;\n /**\n * @internal Internal use only.\n */\n this._excludedMeshesIds = new Array();\n /**\n * @internal Internal use only.\n */\n this._includedOnlyMeshesIds = new Array();\n /** @internal */\n this._isLight = true;\n this.getScene().addLight(this);\n this._uniformBuffer = new UniformBuffer(this.getScene().getEngine(), undefined, undefined, name);\n this._buildUniformLayout();\n this.includedOnlyMeshes = new Array();\n this.excludedMeshes = new Array();\n this._resyncMeshes();\n }\n /**\n * Sets the passed Effect \"effect\" with the Light textures.\n * @param effect The effect to update\n * @param lightIndex The index of the light in the effect to update\n * @returns The light\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n transferTexturesToEffect(effect, lightIndex) {\n // Do nothing by default.\n return this;\n }\n /**\n * Binds the lights information from the scene to the effect for the given mesh.\n * @param lightIndex Light index\n * @param scene The scene where the light belongs to\n * @param effect The effect we are binding the data to\n * @param useSpecular Defines if specular is supported\n * @param receiveShadows Defines if the effect (mesh) we bind the light for receives shadows\n */\n _bindLight(lightIndex, scene, effect, useSpecular, receiveShadows = true) {\n var _a;\n const iAsString = lightIndex.toString();\n let needUpdate = false;\n this._uniformBuffer.bindToEffect(effect, \"Light\" + iAsString);\n if (this._renderId !== scene.getRenderId() || this._lastUseSpecular !== useSpecular || !this._uniformBuffer.useUbo) {\n this._renderId = scene.getRenderId();\n this._lastUseSpecular = useSpecular;\n const scaledIntensity = this.getScaledIntensity();\n this.transferToEffect(effect, iAsString);\n this.diffuse.scaleToRef(scaledIntensity, TmpColors.Color3[0]);\n this._uniformBuffer.updateColor4(\"vLightDiffuse\", TmpColors.Color3[0], this.range, iAsString);\n if (useSpecular) {\n this.specular.scaleToRef(scaledIntensity, TmpColors.Color3[1]);\n this._uniformBuffer.updateColor4(\"vLightSpecular\", TmpColors.Color3[1], this.radius, iAsString);\n }\n needUpdate = true;\n }\n // Textures might still need to be rebound.\n this.transferTexturesToEffect(effect, iAsString);\n // Shadows\n if (scene.shadowsEnabled && this.shadowEnabled && receiveShadows) {\n const shadowGenerator = (_a = this.getShadowGenerator(scene.activeCamera)) !== null && _a !== void 0 ? _a : this.getShadowGenerator();\n if (shadowGenerator) {\n shadowGenerator.bindShadowLight(iAsString, effect);\n needUpdate = true;\n }\n }\n if (needUpdate) {\n this._uniformBuffer.update();\n }\n else {\n this._uniformBuffer.bindUniformBuffer();\n }\n }\n /**\n * Returns the string \"Light\".\n * @returns the class name\n */\n getClassName() {\n return \"Light\";\n }\n /**\n * Converts the light information to a readable string for debug purpose.\n * @param fullDetails Supports for multiple levels of logging within scene loading\n * @returns the human readable light info\n */\n toString(fullDetails) {\n let ret = \"Name: \" + this.name;\n ret += \", type: \" + [\"Point\", \"Directional\", \"Spot\", \"Hemispheric\"][this.getTypeID()];\n if (this.animations) {\n for (let i = 0; i < this.animations.length; i++) {\n ret += \", animation[0]: \" + this.animations[i].toString(fullDetails);\n }\n }\n return ret;\n }\n /** @internal */\n _syncParentEnabledState() {\n super._syncParentEnabledState();\n if (!this.isDisposed()) {\n this._resyncMeshes();\n }\n }\n /**\n * Set the enabled state of this node.\n * @param value - the new enabled state\n */\n setEnabled(value) {\n super.setEnabled(value);\n this._resyncMeshes();\n }\n /**\n * Returns the Light associated shadow generator if any.\n * @param camera Camera for which the shadow generator should be retrieved (default: null). If null, retrieves the default shadow generator\n * @returns the associated shadow generator.\n */\n getShadowGenerator(camera = null) {\n var _a;\n if (this._shadowGenerators === null) {\n return null;\n }\n return (_a = this._shadowGenerators.get(camera)) !== null && _a !== void 0 ? _a : null;\n }\n /**\n * Returns all the shadow generators associated to this light\n * @returns\n */\n getShadowGenerators() {\n return this._shadowGenerators;\n }\n /**\n * Returns a Vector3, the absolute light position in the World.\n * @returns the world space position of the light\n */\n getAbsolutePosition() {\n return Vector3.Zero();\n }\n /**\n * Specifies if the light will affect the passed mesh.\n * @param mesh The mesh to test against the light\n * @returns true the mesh is affected otherwise, false.\n */\n canAffectMesh(mesh) {\n if (!mesh) {\n return true;\n }\n if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {\n return false;\n }\n if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {\n return false;\n }\n if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {\n return false;\n }\n if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {\n return false;\n }\n return true;\n }\n /**\n * Releases resources associated with this node.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n dispose(doNotRecurse, disposeMaterialAndTextures = false) {\n if (this._shadowGenerators) {\n const iterator = this._shadowGenerators.values();\n for (let key = iterator.next(); key.done !== true; key = iterator.next()) {\n const shadowGenerator = key.value;\n shadowGenerator.dispose();\n }\n this._shadowGenerators = null;\n }\n // Animations\n this.getScene().stopAnimation(this);\n if (this._parentContainer) {\n const index = this._parentContainer.lights.indexOf(this);\n if (index > -1) {\n this._parentContainer.lights.splice(index, 1);\n }\n this._parentContainer = null;\n }\n // Remove from meshes\n for (const mesh of this.getScene().meshes) {\n mesh._removeLightSource(this, true);\n }\n this._uniformBuffer.dispose();\n // Remove from scene\n this.getScene().removeLight(this);\n super.dispose(doNotRecurse, disposeMaterialAndTextures);\n }\n /**\n * Returns the light type ID (integer).\n * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x\n */\n getTypeID() {\n return 0;\n }\n /**\n * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.\n * @returns the scaled intensity in intensity mode unit\n */\n getScaledIntensity() {\n return this._photometricScale * this.intensity;\n }\n /**\n * Returns a new Light object, named \"name\", from the current one.\n * @param name The name of the cloned light\n * @param newParent The parent of this light, if it has one\n * @returns the new created light\n */\n clone(name, newParent = null) {\n const constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());\n if (!constructor) {\n return null;\n }\n const clonedLight = SerializationHelper.Clone(constructor, this);\n if (name) {\n clonedLight.name = name;\n }\n if (newParent) {\n clonedLight.parent = newParent;\n }\n clonedLight.setEnabled(this.isEnabled());\n this.onClonedObservable.notifyObservers(clonedLight);\n return clonedLight;\n }\n /**\n * Serializes the current light into a Serialization object.\n * @returns the serialized object.\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this);\n serializationObject.uniqueId = this.uniqueId;\n // Type\n serializationObject.type = this.getTypeID();\n // Parent\n if (this.parent) {\n this.parent._serializeAsParent(serializationObject);\n }\n // Inclusion / exclusions\n if (this.excludedMeshes.length > 0) {\n serializationObject.excludedMeshesIds = [];\n this.excludedMeshes.forEach((mesh) => {\n serializationObject.excludedMeshesIds.push(mesh.id);\n });\n }\n if (this.includedOnlyMeshes.length > 0) {\n serializationObject.includedOnlyMeshesIds = [];\n this.includedOnlyMeshes.forEach((mesh) => {\n serializationObject.includedOnlyMeshesIds.push(mesh.id);\n });\n }\n // Animations\n SerializationHelper.AppendSerializedAnimations(this, serializationObject);\n serializationObject.ranges = this.serializeAnimationRanges();\n serializationObject.isEnabled = this.isEnabled();\n return serializationObject;\n }\n /**\n * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.\n * This new light is named \"name\" and added to the passed scene.\n * @param type Type according to the types available in Light.LIGHTTYPEID_x\n * @param name The friendly name of the light\n * @param scene The scene the new light will belong to\n * @returns the constructor function\n */\n static GetConstructorFromName(type, name, scene) {\n const constructorFunc = Node.Construct(\"Light_Type_\" + type, name, scene);\n if (constructorFunc) {\n return constructorFunc;\n }\n // Default to no light for none present once.\n return null;\n }\n /**\n * Parses the passed \"parsedLight\" and returns a new instanced Light from this parsing.\n * @param parsedLight The JSON representation of the light\n * @param scene The scene to create the parsed light in\n * @returns the created light after parsing\n */\n static Parse(parsedLight, scene) {\n const constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);\n if (!constructor) {\n return null;\n }\n const light = SerializationHelper.Parse(constructor, parsedLight, scene);\n // Inclusion / exclusions\n if (parsedLight.excludedMeshesIds) {\n light._excludedMeshesIds = parsedLight.excludedMeshesIds;\n }\n if (parsedLight.includedOnlyMeshesIds) {\n light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;\n }\n // Parent\n if (parsedLight.parentId !== undefined) {\n light._waitingParentId = parsedLight.parentId;\n }\n if (parsedLight.parentInstanceIndex !== undefined) {\n light._waitingParentInstanceIndex = parsedLight.parentInstanceIndex;\n }\n // Falloff\n if (parsedLight.falloffType !== undefined) {\n light.falloffType = parsedLight.falloffType;\n }\n // Lightmaps\n if (parsedLight.lightmapMode !== undefined) {\n light.lightmapMode = parsedLight.lightmapMode;\n }\n // Animations\n if (parsedLight.animations) {\n for (let animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {\n const parsedAnimation = parsedLight.animations[animationIndex];\n const internalClass = GetClass(\"BABYLON.Animation\");\n if (internalClass) {\n light.animations.push(internalClass.Parse(parsedAnimation));\n }\n }\n Node.ParseAnimationRanges(light, parsedLight, scene);\n }\n if (parsedLight.autoAnimate) {\n scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);\n }\n // Check if isEnabled is defined to be back compatible with prior serialized versions.\n if (parsedLight.isEnabled !== undefined) {\n light.setEnabled(parsedLight.isEnabled);\n }\n return light;\n }\n _hookArrayForExcluded(array) {\n const oldPush = array.push;\n array.push = (...items) => {\n const result = oldPush.apply(array, items);\n for (const item of items) {\n item._resyncLightSource(this);\n }\n return result;\n };\n const oldSplice = array.splice;\n array.splice = (index, deleteCount) => {\n const deleted = oldSplice.apply(array, [index, deleteCount]);\n for (const item of deleted) {\n item._resyncLightSource(this);\n }\n return deleted;\n };\n for (const item of array) {\n item._resyncLightSource(this);\n }\n }\n _hookArrayForIncludedOnly(array) {\n const oldPush = array.push;\n array.push = (...items) => {\n const result = oldPush.apply(array, items);\n this._resyncMeshes();\n return result;\n };\n const oldSplice = array.splice;\n array.splice = (index, deleteCount) => {\n const deleted = oldSplice.apply(array, [index, deleteCount]);\n this._resyncMeshes();\n return deleted;\n };\n this._resyncMeshes();\n }\n _resyncMeshes() {\n for (const mesh of this.getScene().meshes) {\n mesh._resyncLightSource(this);\n }\n }\n /**\n * Forces the meshes to update their light related information in their rendering used effects\n * @internal Internal Use Only\n */\n _markMeshesAsLightDirty() {\n for (const mesh of this.getScene().meshes) {\n if (mesh.lightSources.indexOf(this) !== -1) {\n mesh._markSubMeshesAsLightDirty();\n }\n }\n }\n /**\n * Recomputes the cached photometric scale if needed.\n */\n _computePhotometricScale() {\n this._photometricScale = this._getPhotometricScale();\n this.getScene().resetCachedMaterial();\n }\n /**\n * Returns the Photometric Scale according to the light type and intensity mode.\n */\n _getPhotometricScale() {\n let photometricScale = 0.0;\n const lightTypeID = this.getTypeID();\n //get photometric mode\n let photometricMode = this.intensityMode;\n if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {\n if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {\n photometricMode = Light.INTENSITYMODE_ILLUMINANCE;\n }\n else {\n photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;\n }\n }\n //compute photometric scale\n switch (lightTypeID) {\n case Light.LIGHTTYPEID_POINTLIGHT:\n case Light.LIGHTTYPEID_SPOTLIGHT:\n switch (photometricMode) {\n case Light.INTENSITYMODE_LUMINOUSPOWER:\n photometricScale = 1.0 / (4.0 * Math.PI);\n break;\n case Light.INTENSITYMODE_LUMINOUSINTENSITY:\n photometricScale = 1.0;\n break;\n case Light.INTENSITYMODE_LUMINANCE:\n photometricScale = this.radius * this.radius;\n break;\n }\n break;\n case Light.LIGHTTYPEID_DIRECTIONALLIGHT:\n switch (photometricMode) {\n case Light.INTENSITYMODE_ILLUMINANCE:\n photometricScale = 1.0;\n break;\n case Light.INTENSITYMODE_LUMINANCE: {\n // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.\n // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).\n let apexAngleRadians = this.radius;\n // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).\n apexAngleRadians = Math.max(apexAngleRadians, 0.001);\n const solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));\n photometricScale = solidAngle;\n break;\n }\n }\n break;\n case Light.LIGHTTYPEID_HEMISPHERICLIGHT:\n // No fall off in hemispheric light.\n photometricScale = 1.0;\n break;\n }\n return photometricScale;\n }\n /**\n * Reorder the light in the scene according to their defined priority.\n * @internal Internal Use Only\n */\n _reorderLightsInScene() {\n const scene = this.getScene();\n if (this._renderPriority != 0) {\n scene.requireLightSorting = true;\n }\n this.getScene().sortLightsByPriority();\n }\n}\n/**\n * Falloff Default: light is falling off following the material specification:\n * standard material is using standard falloff whereas pbr material can request special falloff per materials.\n */\nLight.FALLOFF_DEFAULT = LightConstants.FALLOFF_DEFAULT;\n/**\n * Falloff Physical: light is falling off following the inverse squared distance law.\n */\nLight.FALLOFF_PHYSICAL = LightConstants.FALLOFF_PHYSICAL;\n/**\n * Falloff gltf: light is falling off as described in the gltf moving to PBR document\n * to enhance interoperability with other engines.\n */\nLight.FALLOFF_GLTF = LightConstants.FALLOFF_GLTF;\n/**\n * Falloff Standard: light is falling off like in the standard material\n * to enhance interoperability with other materials.\n */\nLight.FALLOFF_STANDARD = LightConstants.FALLOFF_STANDARD;\n//lightmapMode Consts\n/**\n * If every light affecting the material is in this lightmapMode,\n * material.lightmapTexture adds or multiplies\n * (depends on material.useLightmapAsShadowmap)\n * after every other light calculations.\n */\nLight.LIGHTMAP_DEFAULT = LightConstants.LIGHTMAP_DEFAULT;\n/**\n * material.lightmapTexture as only diffuse lighting from this light\n * adds only specular lighting from this light\n * adds dynamic shadows\n */\nLight.LIGHTMAP_SPECULAR = LightConstants.LIGHTMAP_SPECULAR;\n/**\n * material.lightmapTexture as only lighting\n * no light calculation from this light\n * only adds dynamic shadows from this light\n */\nLight.LIGHTMAP_SHADOWSONLY = LightConstants.LIGHTMAP_SHADOWSONLY;\n// Intensity Mode Consts\n/**\n * Each light type uses the default quantity according to its type:\n * point/spot lights use luminous intensity\n * directional lights use illuminance\n */\nLight.INTENSITYMODE_AUTOMATIC = LightConstants.INTENSITYMODE_AUTOMATIC;\n/**\n * lumen (lm)\n */\nLight.INTENSITYMODE_LUMINOUSPOWER = LightConstants.INTENSITYMODE_LUMINOUSPOWER;\n/**\n * candela (lm/sr)\n */\nLight.INTENSITYMODE_LUMINOUSINTENSITY = LightConstants.INTENSITYMODE_LUMINOUSINTENSITY;\n/**\n * lux (lm/m^2)\n */\nLight.INTENSITYMODE_ILLUMINANCE = LightConstants.INTENSITYMODE_ILLUMINANCE;\n/**\n * nit (cd/m^2)\n */\nLight.INTENSITYMODE_LUMINANCE = LightConstants.INTENSITYMODE_LUMINANCE;\n// Light types ids const.\n/**\n * Light type const id of the point light.\n */\nLight.LIGHTTYPEID_POINTLIGHT = LightConstants.LIGHTTYPEID_POINTLIGHT;\n/**\n * Light type const id of the directional light.\n */\nLight.LIGHTTYPEID_DIRECTIONALLIGHT = LightConstants.LIGHTTYPEID_DIRECTIONALLIGHT;\n/**\n * Light type const id of the spot light.\n */\nLight.LIGHTTYPEID_SPOTLIGHT = LightConstants.LIGHTTYPEID_SPOTLIGHT;\n/**\n * Light type const id of the hemispheric light.\n */\nLight.LIGHTTYPEID_HEMISPHERICLIGHT = LightConstants.LIGHTTYPEID_HEMISPHERICLIGHT;\n__decorate([\n serializeAsColor3()\n], Light.prototype, \"diffuse\", void 0);\n__decorate([\n serializeAsColor3()\n], Light.prototype, \"specular\", void 0);\n__decorate([\n serialize()\n], Light.prototype, \"falloffType\", void 0);\n__decorate([\n serialize()\n], Light.prototype, \"intensity\", void 0);\n__decorate([\n serialize()\n], Light.prototype, \"range\", null);\n__decorate([\n serialize()\n], Light.prototype, \"intensityMode\", null);\n__decorate([\n serialize()\n], Light.prototype, \"radius\", null);\n__decorate([\n serialize()\n], Light.prototype, \"_renderPriority\", void 0);\n__decorate([\n expandToProperty(\"_reorderLightsInScene\")\n], Light.prototype, \"renderPriority\", void 0);\n__decorate([\n serialize(\"shadowEnabled\")\n], Light.prototype, \"_shadowEnabled\", void 0);\n__decorate([\n serialize(\"excludeWithLayerMask\")\n], Light.prototype, \"_excludeWithLayerMask\", void 0);\n__decorate([\n serialize(\"includeOnlyWithLayerMask\")\n], Light.prototype, \"_includeOnlyWithLayerMask\", void 0);\n__decorate([\n serialize(\"lightmapMode\")\n], Light.prototype, \"_lightmapMode\", void 0);\n//# sourceMappingURL=light.js.map","import { AbstractScene } from \"./abstractScene.js\";\nimport { Mesh } from \"./Meshes/mesh.js\";\nimport { TransformNode } from \"./Meshes/transformNode.js\";\nimport { Logger } from \"./Misc/logger.js\";\nimport { EngineStore } from \"./Engines/engineStore.js\";\nimport { InstancedMesh } from \"./Meshes/instancedMesh.js\";\nimport { Light } from \"./Lights/light.js\";\nimport { Camera } from \"./Cameras/camera.js\";\nimport { Tools } from \"./Misc/tools.js\";\n/**\n * Set of assets to keep when moving a scene into an asset container.\n */\nexport class KeepAssets extends AbstractScene {\n}\n/**\n * Class used to store the output of the AssetContainer.instantiateAllMeshesToScene function\n */\nexport class InstantiatedEntries {\n constructor() {\n /**\n * List of new root nodes (eg. nodes with no parent)\n */\n this.rootNodes = [];\n /**\n * List of new skeletons\n */\n this.skeletons = [];\n /**\n * List of new animation groups\n */\n this.animationGroups = [];\n }\n /**\n * Disposes the instantiated entries from the scene\n */\n dispose() {\n this.rootNodes.slice(0).forEach((o) => {\n o.dispose();\n });\n this.rootNodes.length = 0;\n this.skeletons.slice(0).forEach((o) => {\n o.dispose();\n });\n this.skeletons.length = 0;\n this.animationGroups.slice(0).forEach((o) => {\n o.dispose();\n });\n this.animationGroups.length = 0;\n }\n}\n/**\n * Container with a set of assets that can be added or removed from a scene.\n */\nexport class AssetContainer extends AbstractScene {\n /**\n * Instantiates an AssetContainer.\n * @param scene The scene the AssetContainer belongs to.\n */\n constructor(scene) {\n super();\n this._wasAddedToScene = false;\n scene = scene || EngineStore.LastCreatedScene;\n if (!scene) {\n return;\n }\n this.scene = scene;\n this[\"sounds\"] = [];\n this[\"effectLayers\"] = [];\n this[\"layers\"] = [];\n this[\"lensFlareSystems\"] = [];\n this[\"proceduralTextures\"] = [];\n this[\"reflectionProbes\"] = [];\n scene.onDisposeObservable.add(() => {\n if (!this._wasAddedToScene) {\n this.dispose();\n }\n });\n this._onContextRestoredObserver = scene.getEngine().onContextRestoredObservable.add(() => {\n for (const geometry of this.geometries) {\n geometry._rebuild();\n }\n for (const mesh of this.meshes) {\n mesh._rebuild();\n }\n for (const system of this.particleSystems) {\n system.rebuild();\n }\n for (const texture of this.textures) {\n texture._rebuild();\n }\n });\n }\n /**\n * Given a list of nodes, return a topological sorting of them.\n * @param nodes\n */\n _topologicalSort(nodes) {\n const nodesUidMap = new Map();\n for (const node of nodes) {\n nodesUidMap.set(node.uniqueId, node);\n }\n const dependencyGraph = {\n dependsOn: new Map(),\n dependedBy: new Map(), // given a node id, what are the ids of the nodes that depend on it\n };\n // Build the dependency graph given the list of nodes\n // First pass: Initialize the empty dependency graph\n for (const node of nodes) {\n const nodeId = node.uniqueId;\n dependencyGraph.dependsOn.set(nodeId, new Set());\n dependencyGraph.dependedBy.set(nodeId, new Set());\n }\n // Second pass: Populate the dependency graph. We assume that we\n // don't need to check for cycles here, as the scene graph cannot\n // contain cycles. Our graph also already contains all transitive\n // dependencies because getDescendants returns the transitive\n // dependencies by default.\n for (const node of nodes) {\n const nodeId = node.uniqueId;\n const dependsOn = dependencyGraph.dependsOn.get(nodeId);\n if (node instanceof InstancedMesh) {\n const masterMesh = node.sourceMesh;\n if (nodesUidMap.has(masterMesh.uniqueId)) {\n dependsOn.add(masterMesh.uniqueId);\n dependencyGraph.dependedBy.get(masterMesh.uniqueId).add(nodeId);\n }\n }\n const dependedBy = dependencyGraph.dependedBy.get(nodeId);\n for (const child of node.getDescendants()) {\n const childId = child.uniqueId;\n if (nodesUidMap.has(childId)) {\n dependedBy.add(childId);\n const childDependsOn = dependencyGraph.dependsOn.get(childId);\n childDependsOn.add(nodeId);\n }\n }\n }\n // Third pass: Topological sort\n const sortedNodes = [];\n // First: Find all nodes that have no dependencies\n const leaves = [];\n for (const node of nodes) {\n const nodeId = node.uniqueId;\n if (dependencyGraph.dependsOn.get(nodeId).size === 0) {\n leaves.push(node);\n nodesUidMap.delete(nodeId);\n }\n }\n const visitList = leaves;\n while (visitList.length > 0) {\n const nodeToVisit = visitList.shift();\n sortedNodes.push(nodeToVisit);\n // Remove the node from the dependency graph\n // When a node is visited, we know that dependsOn is empty.\n // So we only need to remove the node from dependedBy.\n const dependedByVisitedNode = dependencyGraph.dependedBy.get(nodeToVisit.uniqueId);\n // Array.from(x.values()) is to make the TS compiler happy\n for (const dependedByVisitedNodeId of Array.from(dependedByVisitedNode.values())) {\n const dependsOnDependedByVisitedNode = dependencyGraph.dependsOn.get(dependedByVisitedNodeId);\n dependsOnDependedByVisitedNode.delete(nodeToVisit.uniqueId);\n if (dependsOnDependedByVisitedNode.size === 0 && nodesUidMap.get(dependedByVisitedNodeId)) {\n visitList.push(nodesUidMap.get(dependedByVisitedNodeId));\n nodesUidMap.delete(dependedByVisitedNodeId);\n }\n }\n }\n if (nodesUidMap.size > 0) {\n console.error(\"SceneSerializer._topologicalSort: There were unvisited nodes:\");\n nodesUidMap.forEach((node) => console.error(node.name));\n }\n return sortedNodes;\n }\n _addNodeAndDescendantsToList(list, addedIds, rootNode, predicate) {\n if (!rootNode || (predicate && !predicate(rootNode)) || addedIds.has(rootNode.uniqueId)) {\n return;\n }\n list.push(rootNode);\n addedIds.add(rootNode.uniqueId);\n for (const child of rootNode.getDescendants(true)) {\n this._addNodeAndDescendantsToList(list, addedIds, child, predicate);\n }\n }\n /**\n * Check if a specific node is contained in this asset container.\n * @param node\n */\n _isNodeInContainer(node) {\n if (node instanceof Mesh && this.meshes.indexOf(node) !== -1) {\n return true;\n }\n if (node instanceof TransformNode && this.transformNodes.indexOf(node) !== -1) {\n return true;\n }\n if (node instanceof Light && this.lights.indexOf(node) !== -1) {\n return true;\n }\n if (node instanceof Camera && this.cameras.indexOf(node) !== -1) {\n return true;\n }\n return false;\n }\n /**\n * For every node in the scene, check if its parent node is also in the scene.\n */\n _isValidHierarchy() {\n for (const node of this.meshes) {\n if (node.parent && !this._isNodeInContainer(node.parent)) {\n Logger.Warn(`Node ${node.name} has a parent that is not in the container.`);\n return false;\n }\n }\n for (const node of this.transformNodes) {\n if (node.parent && !this._isNodeInContainer(node.parent)) {\n Logger.Warn(`Node ${node.name} has a parent that is not in the container.`);\n return false;\n }\n }\n for (const node of this.lights) {\n if (node.parent && !this._isNodeInContainer(node.parent)) {\n Logger.Warn(`Node ${node.name} has a parent that is not in the container.`);\n return false;\n }\n }\n for (const node of this.cameras) {\n if (node.parent && !this._isNodeInContainer(node.parent)) {\n Logger.Warn(`Node ${node.name} has a parent that is not in the container.`);\n return false;\n }\n }\n return true;\n }\n /**\n * Instantiate or clone all meshes and add the new ones to the scene.\n * Skeletons and animation groups will all be cloned\n * @param nameFunction defines an optional function used to get new names for clones\n * @param cloneMaterials defines an optional boolean that defines if materials must be cloned as well (false by default)\n * @param options defines an optional list of options to control how to instantiate / clone models\n * @param options.doNotInstantiate defines if the model must be instantiated or just cloned\n * @param options.predicate defines a predicate used to filter whih mesh to instantiate/clone\n * @returns a list of rootNodes, skeletons and animation groups that were duplicated\n */\n instantiateModelsToScene(nameFunction, cloneMaterials = false, options) {\n if (!this._isValidHierarchy()) {\n Tools.Warn(\"SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.\");\n }\n const conversionMap = {};\n const storeMap = {};\n const result = new InstantiatedEntries();\n const alreadySwappedSkeletons = [];\n const alreadySwappedMaterials = [];\n const localOptions = Object.assign({ doNotInstantiate: true }, options);\n const onClone = (source, clone) => {\n conversionMap[source.uniqueId] = clone.uniqueId;\n storeMap[clone.uniqueId] = clone;\n if (nameFunction) {\n clone.name = nameFunction(source.name);\n }\n if (clone instanceof Mesh) {\n const clonedMesh = clone;\n if (clonedMesh.morphTargetManager) {\n const oldMorphTargetManager = source.morphTargetManager;\n clonedMesh.morphTargetManager = oldMorphTargetManager.clone();\n for (let index = 0; index < oldMorphTargetManager.numTargets; index++) {\n const oldTarget = oldMorphTargetManager.getTarget(index);\n const newTarget = clonedMesh.morphTargetManager.getTarget(index);\n conversionMap[oldTarget.uniqueId] = newTarget.uniqueId;\n storeMap[newTarget.uniqueId] = newTarget;\n }\n }\n }\n };\n const nodesToSort = [];\n const idsOnSortList = new Set();\n for (const transformNode of this.transformNodes) {\n if (transformNode.parent === null) {\n this._addNodeAndDescendantsToList(nodesToSort, idsOnSortList, transformNode, localOptions.predicate);\n }\n }\n for (const mesh of this.meshes) {\n if (mesh.parent === null) {\n this._addNodeAndDescendantsToList(nodesToSort, idsOnSortList, mesh, localOptions.predicate);\n }\n }\n // Topologically sort nodes by parenting/instancing relationships so that all resources are in place\n // when a given node is instantiated.\n const sortedNodes = this._topologicalSort(nodesToSort);\n const onNewCreated = (source, clone) => {\n onClone(source, clone);\n if (source.parent) {\n const replicatedParentId = conversionMap[source.parent.uniqueId];\n const replicatedParent = storeMap[replicatedParentId];\n if (replicatedParent) {\n clone.parent = replicatedParent;\n }\n else {\n clone.parent = source.parent;\n }\n }\n if (clone.position && source.position) {\n clone.position.copyFrom(source.position);\n }\n if (clone.rotationQuaternion && source.rotationQuaternion) {\n clone.rotationQuaternion.copyFrom(source.rotationQuaternion);\n }\n if (clone.rotation && source.rotation) {\n clone.rotation.copyFrom(source.rotation);\n }\n if (clone.scaling && source.scaling) {\n clone.scaling.copyFrom(source.scaling);\n }\n if (clone.material) {\n const mesh = clone;\n if (mesh.material) {\n if (cloneMaterials) {\n const sourceMaterial = source.material;\n if (alreadySwappedMaterials.indexOf(sourceMaterial) === -1) {\n let swap = sourceMaterial.clone(nameFunction ? nameFunction(sourceMaterial.name) : \"Clone of \" + sourceMaterial.name);\n alreadySwappedMaterials.push(sourceMaterial);\n conversionMap[sourceMaterial.uniqueId] = swap.uniqueId;\n storeMap[swap.uniqueId] = swap;\n if (sourceMaterial.getClassName() === \"MultiMaterial\") {\n const multi = sourceMaterial;\n for (const material of multi.subMaterials) {\n if (!material) {\n continue;\n }\n swap = material.clone(nameFunction ? nameFunction(material.name) : \"Clone of \" + material.name);\n alreadySwappedMaterials.push(material);\n conversionMap[material.uniqueId] = swap.uniqueId;\n storeMap[swap.uniqueId] = swap;\n }\n multi.subMaterials = multi.subMaterials.map((m) => m && storeMap[conversionMap[m.uniqueId]]);\n }\n }\n if (mesh.getClassName() !== \"InstancedMesh\") {\n mesh.material = storeMap[conversionMap[sourceMaterial.uniqueId]];\n }\n }\n else {\n if (mesh.material.getClassName() === \"MultiMaterial\") {\n if (this.scene.multiMaterials.indexOf(mesh.material) === -1) {\n this.scene.addMultiMaterial(mesh.material);\n }\n }\n else {\n if (this.scene.materials.indexOf(mesh.material) === -1) {\n this.scene.addMaterial(mesh.material);\n }\n }\n }\n }\n }\n if (clone.parent === null) {\n result.rootNodes.push(clone);\n }\n };\n sortedNodes.forEach((node) => {\n if (node.getClassName() === \"InstancedMesh\") {\n const instancedNode = node;\n const sourceMesh = instancedNode.sourceMesh;\n const replicatedSourceId = conversionMap[sourceMesh.uniqueId];\n const replicatedSource = typeof replicatedSourceId === \"number\" ? storeMap[replicatedSourceId] : sourceMesh;\n const replicatedInstancedNode = replicatedSource.createInstance(instancedNode.name);\n onNewCreated(instancedNode, replicatedInstancedNode);\n }\n else {\n // Mesh or TransformNode\n let canInstance = true;\n if (node.getClassName() === \"TransformNode\" ||\n node.getClassName() === \"Node\" ||\n node.skeleton ||\n !node.getTotalVertices ||\n node.getTotalVertices() === 0) {\n // Transform nodes, skinned meshes, and meshes with no vertices can never be instanced!\n canInstance = false;\n }\n else if (localOptions.doNotInstantiate) {\n if (typeof localOptions.doNotInstantiate === \"function\") {\n canInstance = !localOptions.doNotInstantiate(node);\n }\n else {\n canInstance = !localOptions.doNotInstantiate;\n }\n }\n const replicatedNode = canInstance ? node.createInstance(`instance of ${node.name}`) : node.clone(`Clone of ${node.name}`, null, true);\n if (!replicatedNode) {\n throw new Error(`Could not clone or instantiate node on Asset Container ${node.name}`);\n }\n onNewCreated(node, replicatedNode);\n }\n });\n this.skeletons.forEach((s) => {\n if (localOptions.predicate && !localOptions.predicate(s)) {\n return;\n }\n const clone = s.clone(nameFunction ? nameFunction(s.name) : \"Clone of \" + s.name);\n for (const m of this.meshes) {\n if (m.skeleton === s && !m.isAnInstance) {\n const copy = storeMap[conversionMap[m.uniqueId]];\n if (!copy || copy.isAnInstance) {\n continue;\n }\n copy.skeleton = clone;\n if (alreadySwappedSkeletons.indexOf(clone) !== -1) {\n continue;\n }\n alreadySwappedSkeletons.push(clone);\n // Check if bones are mesh linked\n for (const bone of clone.bones) {\n if (bone._linkedTransformNode) {\n bone._linkedTransformNode = storeMap[conversionMap[bone._linkedTransformNode.uniqueId]];\n }\n }\n }\n }\n result.skeletons.push(clone);\n });\n this.animationGroups.forEach((o) => {\n if (localOptions.predicate && !localOptions.predicate(o)) {\n return;\n }\n const clone = o.clone(nameFunction ? nameFunction(o.name) : \"Clone of \" + o.name, (oldTarget) => {\n const newTarget = storeMap[conversionMap[oldTarget.uniqueId]];\n return newTarget || oldTarget;\n });\n result.animationGroups.push(clone);\n });\n return result;\n }\n /**\n * Adds all the assets from the container to the scene.\n */\n addAllToScene() {\n if (this._wasAddedToScene) {\n return;\n }\n if (!this._isValidHierarchy()) {\n Tools.Warn(\"SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid.\");\n }\n this._wasAddedToScene = true;\n this.addToScene(null);\n if (this.environmentTexture) {\n this.scene.environmentTexture = this.environmentTexture;\n }\n for (const component of this.scene._serializableComponents) {\n component.addFromContainer(this);\n }\n this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver);\n this._onContextRestoredObserver = null;\n }\n /**\n * Adds assets from the container to the scene.\n * @param predicate defines a predicate used to select which entity will be added (can be null)\n */\n addToScene(predicate = null) {\n this.cameras.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addCamera(o);\n });\n this.lights.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addLight(o);\n });\n this.meshes.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addMesh(o);\n });\n this.skeletons.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addSkeleton(o);\n });\n this.animations.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addAnimation(o);\n });\n this.animationGroups.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addAnimationGroup(o);\n });\n this.multiMaterials.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addMultiMaterial(o);\n });\n this.materials.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addMaterial(o);\n });\n this.morphTargetManagers.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addMorphTargetManager(o);\n });\n this.geometries.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addGeometry(o);\n });\n this.transformNodes.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addTransformNode(o);\n });\n this.actionManagers.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addActionManager(o);\n });\n this.textures.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addTexture(o);\n });\n this.reflectionProbes.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.addReflectionProbe(o);\n });\n }\n /**\n * Removes all the assets in the container from the scene\n */\n removeAllFromScene() {\n if (!this._isValidHierarchy()) {\n Tools.Warn(\"SceneSerializer.removeAllFromScene: The Asset Container hierarchy is not valid.\");\n }\n this._wasAddedToScene = false;\n this.removeFromScene(null);\n if (this.environmentTexture === this.scene.environmentTexture) {\n this.scene.environmentTexture = null;\n }\n for (const component of this.scene._serializableComponents) {\n component.removeFromContainer(this);\n }\n }\n /**\n * Removes assets in the container from the scene\n * @param predicate defines a predicate used to select which entity will be added (can be null)\n */\n removeFromScene(predicate = null) {\n this.cameras.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeCamera(o);\n });\n this.lights.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeLight(o);\n });\n this.meshes.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeMesh(o);\n });\n this.skeletons.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeSkeleton(o);\n });\n this.animations.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeAnimation(o);\n });\n this.animationGroups.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeAnimationGroup(o);\n });\n this.multiMaterials.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeMultiMaterial(o);\n });\n this.materials.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeMaterial(o);\n });\n this.morphTargetManagers.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeMorphTargetManager(o);\n });\n this.geometries.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeGeometry(o);\n });\n this.transformNodes.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeTransformNode(o);\n });\n this.actionManagers.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeActionManager(o);\n });\n this.textures.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeTexture(o);\n });\n this.reflectionProbes.forEach((o) => {\n if (predicate && !predicate(o)) {\n return;\n }\n this.scene.removeReflectionProbe(o);\n });\n }\n /**\n * Disposes all the assets in the container\n */\n dispose() {\n this.cameras.slice(0).forEach((o) => {\n o.dispose();\n });\n this.cameras.length = 0;\n this.lights.slice(0).forEach((o) => {\n o.dispose();\n });\n this.lights.length = 0;\n this.meshes.slice(0).forEach((o) => {\n o.dispose();\n });\n this.meshes.length = 0;\n this.skeletons.slice(0).forEach((o) => {\n o.dispose();\n });\n this.skeletons.length = 0;\n this.animationGroups.slice(0).forEach((o) => {\n o.dispose();\n });\n this.animationGroups.length = 0;\n this.multiMaterials.slice(0).forEach((o) => {\n o.dispose();\n });\n this.multiMaterials.length = 0;\n this.materials.slice(0).forEach((o) => {\n o.dispose();\n });\n this.materials.length = 0;\n this.geometries.slice(0).forEach((o) => {\n o.dispose();\n });\n this.geometries.length = 0;\n this.transformNodes.slice(0).forEach((o) => {\n o.dispose();\n });\n this.transformNodes.length = 0;\n this.actionManagers.slice(0).forEach((o) => {\n o.dispose();\n });\n this.actionManagers.length = 0;\n this.textures.slice(0).forEach((o) => {\n o.dispose();\n });\n this.textures.length = 0;\n this.reflectionProbes.slice(0).forEach((o) => {\n o.dispose();\n });\n this.reflectionProbes.length = 0;\n this.morphTargetManagers.slice(0).forEach((o) => {\n o.dispose();\n });\n this.morphTargetManagers.length = 0;\n if (this.environmentTexture) {\n this.environmentTexture.dispose();\n this.environmentTexture = null;\n }\n for (const component of this.scene._serializableComponents) {\n component.removeFromContainer(this, true);\n }\n if (this._onContextRestoredObserver) {\n this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver);\n this._onContextRestoredObserver = null;\n }\n }\n _moveAssets(sourceAssets, targetAssets, keepAssets) {\n if (!sourceAssets || !targetAssets) {\n return;\n }\n for (const asset of sourceAssets) {\n let move = true;\n if (keepAssets) {\n for (const keepAsset of keepAssets) {\n if (asset === keepAsset) {\n move = false;\n break;\n }\n }\n }\n if (move) {\n targetAssets.push(asset);\n asset._parentContainer = this;\n }\n }\n }\n /**\n * Removes all the assets contained in the scene and adds them to the container.\n * @param keepAssets Set of assets to keep in the scene. (default: empty)\n */\n moveAllFromScene(keepAssets) {\n this._wasAddedToScene = false;\n if (keepAssets === undefined) {\n keepAssets = new KeepAssets();\n }\n for (const key in this) {\n if (Object.prototype.hasOwnProperty.call(this, key)) {\n this[key] = this[key] || (key === \"_environmentTexture\" ? null : []);\n this._moveAssets(this.scene[key], this[key], keepAssets[key]);\n }\n }\n this.environmentTexture = this.scene.environmentTexture;\n this.removeAllFromScene();\n }\n /**\n * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.\n * @returns the root mesh\n */\n createRootMesh() {\n const rootMesh = new Mesh(\"assetContainerRootMesh\", this.scene);\n this.meshes.forEach((m) => {\n if (!m.parent) {\n rootMesh.addChild(m);\n }\n });\n this.meshes.unshift(rootMesh);\n return rootMesh;\n }\n /**\n * Merge animations (direct and animation groups) from this asset container into a scene\n * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)\n * @param animatables set of animatables to retarget to a node from the scene\n * @param targetConverter defines a function used to convert animation targets from the asset container to the scene (default: search node by name)\n * @returns an array of the new AnimationGroup added to the scene (empty array if none)\n */\n mergeAnimationsTo(scene = EngineStore.LastCreatedScene, animatables, targetConverter = null) {\n if (!scene) {\n Logger.Error(\"No scene available to merge animations to\");\n return [];\n }\n const _targetConverter = targetConverter\n ? targetConverter\n : (target) => {\n let node = null;\n const targetProperty = target.animations.length ? target.animations[0].targetProperty : \"\";\n /*\n BabylonJS adds special naming to targets that are children of nodes.\n This name attempts to remove that special naming to get the parent nodes name in case the target\n can't be found in the node tree\n\n Ex: Torso_primitive0 likely points to a Mesh primitive. We take away primitive0 and are left with \"Torso\" which is the name\n of the primitive's parent.\n */\n const name = target.name.split(\".\").join(\"\").split(\"_primitive\")[0];\n switch (targetProperty) {\n case \"position\":\n case \"rotationQuaternion\":\n node = scene.getTransformNodeByName(target.name) || scene.getTransformNodeByName(name);\n break;\n case \"influence\":\n node = scene.getMorphTargetByName(target.name) || scene.getMorphTargetByName(name);\n break;\n default:\n node = scene.getNodeByName(target.name) || scene.getNodeByName(name);\n }\n return node;\n };\n // Copy new node animations\n const nodesInAC = this.getNodes();\n nodesInAC.forEach((nodeInAC) => {\n const nodeInScene = _targetConverter(nodeInAC);\n if (nodeInScene !== null) {\n // Remove old animations with same target property as a new one\n for (const animationInAC of nodeInAC.animations) {\n // Doing treatment on an array for safety measure\n const animationsWithSameProperty = nodeInScene.animations.filter((animationInScene) => {\n return animationInScene.targetProperty === animationInAC.targetProperty;\n });\n for (const animationWithSameProperty of animationsWithSameProperty) {\n const index = nodeInScene.animations.indexOf(animationWithSameProperty, 0);\n if (index > -1) {\n nodeInScene.animations.splice(index, 1);\n }\n }\n }\n // Append new animations\n nodeInScene.animations = nodeInScene.animations.concat(nodeInAC.animations);\n }\n });\n const newAnimationGroups = new Array();\n // Copy new animation groups\n this.animationGroups.slice().forEach((animationGroupInAC) => {\n // Clone the animation group and all its animatables\n newAnimationGroups.push(animationGroupInAC.clone(animationGroupInAC.name, _targetConverter));\n // Remove animatables related to the asset container\n animationGroupInAC.animatables.forEach((animatable) => {\n animatable.stop();\n });\n });\n // Retarget animatables\n animatables.forEach((animatable) => {\n const target = _targetConverter(animatable.target);\n if (target) {\n // Clone the animatable and retarget it\n scene.beginAnimation(target, animatable.fromFrame, animatable.toFrame, animatable.loopAnimation, animatable.speedRatio, animatable.onAnimationEnd ? animatable.onAnimationEnd : undefined, undefined, true, undefined, animatable.onAnimationLoop ? animatable.onAnimationLoop : undefined);\n // Stop animation for the target in the asset container\n scene.stopAnimation(animatable.target);\n }\n });\n return newAnimationGroups;\n }\n}\n//# sourceMappingURL=assetContainer.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { IsWindowObjectExist } from \"../Misc/domManagement.js\";\n// Sets the default audio engine to Babylon.js\nEngine.AudioEngineFactory = (hostElement, audioContext, audioDestination) => {\n return new AudioEngine(hostElement, audioContext, audioDestination);\n};\n/**\n * This represents the default audio engine used in babylon.\n * It is responsible to play, synchronize and analyse sounds throughout the application.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic\n */\nexport class AudioEngine {\n /**\n * Gets the current AudioContext if available.\n */\n get audioContext() {\n if (!this._audioContextInitialized) {\n this._initializeAudioContext();\n }\n else {\n if (!this.unlocked && !this._muteButton) {\n this._displayMuteButton();\n }\n }\n return this._audioContext;\n }\n /**\n * Instantiates a new audio engine.\n *\n * There should be only one per page as some browsers restrict the number\n * of audio contexts you can create.\n * @param hostElement defines the host element where to display the mute icon if necessary\n * @param audioContext defines the audio context to be used by the audio engine\n * @param audioDestination defines the audio destination node to be used by audio engine\n */\n constructor(hostElement = null, audioContext = null, audioDestination = null) {\n this._audioContext = null;\n this._audioContextInitialized = false;\n this._muteButton = null;\n this._audioDestination = null;\n /**\n * Gets whether the current host supports Web Audio and thus could create AudioContexts.\n */\n this.canUseWebAudio = false;\n /**\n * Defines if Babylon should emit a warning if WebAudio is not supported.\n * @ignoreNaming\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n this.WarnedWebAudioUnsupported = false;\n /**\n * Gets whether or not mp3 are supported by your browser.\n */\n this.isMP3supported = false;\n /**\n * Gets whether or not ogg are supported by your browser.\n */\n this.isOGGsupported = false;\n /**\n * Gets whether audio has been unlocked on the device.\n * Some Browsers have strong restrictions about Audio and won t autoplay unless\n * a user interaction has happened.\n */\n this.unlocked = true;\n /**\n * Defines if the audio engine relies on a custom unlocked button.\n * In this case, the embedded button will not be displayed.\n */\n this.useCustomUnlockedButton = false;\n /**\n * Event raised when audio has been unlocked on the browser.\n */\n this.onAudioUnlockedObservable = new Observable();\n /**\n * Event raised when audio has been locked on the browser.\n */\n this.onAudioLockedObservable = new Observable();\n this._tryToRun = false;\n this._onResize = () => {\n this._moveButtonToTopLeft();\n };\n if (!IsWindowObjectExist()) {\n return;\n }\n if (typeof window.AudioContext !== \"undefined\") {\n this.canUseWebAudio = true;\n }\n const audioElem = document.createElement(\"audio\");\n this._hostElement = hostElement;\n this._audioContext = audioContext;\n this._audioDestination = audioDestination;\n try {\n if (audioElem &&\n !!audioElem.canPlayType &&\n (audioElem.canPlayType('audio/mpeg; codecs=\"mp3\"').replace(/^no$/, \"\") || audioElem.canPlayType(\"audio/mp3\").replace(/^no$/, \"\"))) {\n this.isMP3supported = true;\n }\n }\n catch (e) {\n // protect error during capability check.\n }\n try {\n if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs=\"vorbis\"').replace(/^no$/, \"\")) {\n this.isOGGsupported = true;\n }\n }\n catch (e) {\n // protect error during capability check.\n }\n }\n /**\n * Flags the audio engine in Locked state.\n * This happens due to new browser policies preventing audio to autoplay.\n */\n lock() {\n this._triggerSuspendedState();\n }\n /**\n * Unlocks the audio engine once a user action has been done on the dom.\n * This is helpful to resume play once browser policies have been satisfied.\n */\n unlock() {\n this._triggerRunningState();\n }\n _resumeAudioContext() {\n let result;\n if (this._audioContext.resume !== undefined) {\n result = this._audioContext.resume();\n }\n return result || Promise.resolve();\n }\n _initializeAudioContext() {\n try {\n if (this.canUseWebAudio) {\n if (!this._audioContext) {\n this._audioContext = new AudioContext();\n }\n // create a global volume gain node\n this.masterGain = this._audioContext.createGain();\n this.masterGain.gain.value = 1;\n if (!this._audioDestination) {\n this._audioDestination = this._audioContext.destination;\n }\n this.masterGain.connect(this._audioDestination);\n this._audioContextInitialized = true;\n if (this._audioContext.state === \"running\") {\n // Do not wait for the promise to unlock.\n this._triggerRunningState();\n }\n }\n }\n catch (e) {\n this.canUseWebAudio = false;\n Logger.Error(\"Web Audio: \" + e.message);\n }\n }\n _triggerRunningState() {\n if (this._tryToRun) {\n return;\n }\n this._tryToRun = true;\n this._resumeAudioContext()\n .then(() => {\n this._tryToRun = false;\n if (this._muteButton) {\n this._hideMuteButton();\n }\n // Notify users that the audio stack is unlocked/unmuted\n this.unlocked = true;\n this.onAudioUnlockedObservable.notifyObservers(this);\n })\n .catch(() => {\n this._tryToRun = false;\n this.unlocked = false;\n });\n }\n _triggerSuspendedState() {\n this.unlocked = false;\n this.onAudioLockedObservable.notifyObservers(this);\n this._displayMuteButton();\n }\n _displayMuteButton() {\n if (this.useCustomUnlockedButton || this._muteButton) {\n return;\n }\n this._muteButton = document.createElement(\"BUTTON\");\n this._muteButton.className = \"babylonUnmuteIcon\";\n this._muteButton.id = \"babylonUnmuteIconBtn\";\n this._muteButton.title = \"Unmute\";\n const imageUrl = !window.SVGSVGElement\n ? \"https://cdn.babylonjs.com/Assets/audio.png\"\n : \"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\";\n const css = \".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url(\" +\n imageUrl +\n \"); 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) }\";\n const style = document.createElement(\"style\");\n style.appendChild(document.createTextNode(css));\n document.getElementsByTagName(\"head\")[0].appendChild(style);\n document.body.appendChild(this._muteButton);\n this._moveButtonToTopLeft();\n this._muteButton.addEventListener(\"touchend\", () => {\n this._triggerRunningState();\n }, true);\n this._muteButton.addEventListener(\"click\", () => {\n this._triggerRunningState();\n }, true);\n window.addEventListener(\"resize\", this._onResize);\n }\n _moveButtonToTopLeft() {\n if (this._hostElement && this._muteButton) {\n this._muteButton.style.top = this._hostElement.offsetTop + 20 + \"px\";\n this._muteButton.style.left = this._hostElement.offsetLeft + 20 + \"px\";\n }\n }\n _hideMuteButton() {\n if (this._muteButton) {\n document.body.removeChild(this._muteButton);\n this._muteButton = null;\n }\n }\n /**\n * Destroy and release the resources associated with the audio context.\n */\n dispose() {\n if (this.canUseWebAudio && this._audioContextInitialized) {\n if (this._connectedAnalyser && this._audioContext) {\n this._connectedAnalyser.stopDebugCanvas();\n this._connectedAnalyser.dispose();\n this.masterGain.disconnect();\n this.masterGain.connect(this._audioContext.destination);\n this._connectedAnalyser = null;\n }\n this.masterGain.gain.value = 1;\n }\n this.WarnedWebAudioUnsupported = false;\n this._hideMuteButton();\n window.removeEventListener(\"resize\", this._onResize);\n this.onAudioUnlockedObservable.clear();\n this.onAudioLockedObservable.clear();\n }\n /**\n * Gets the global volume sets on the master gain.\n * @returns the global volume if set or -1 otherwise\n */\n getGlobalVolume() {\n if (this.canUseWebAudio && this._audioContextInitialized) {\n return this.masterGain.gain.value;\n }\n else {\n return -1;\n }\n }\n /**\n * Sets the global volume of your experience (sets on the master gain).\n * @param newVolume Defines the new global volume of the application\n */\n setGlobalVolume(newVolume) {\n if (this.canUseWebAudio && this._audioContextInitialized) {\n this.masterGain.gain.value = newVolume;\n }\n }\n /**\n * Connect the audio engine to an audio analyser allowing some amazing\n * synchronization between the sounds/music and your visualization (VuMeter for instance).\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#using-the-analyser\n * @param analyser The analyser to connect to the engine\n */\n connectToAnalyser(analyser) {\n if (this._connectedAnalyser) {\n this._connectedAnalyser.stopDebugCanvas();\n }\n if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {\n this._connectedAnalyser = analyser;\n this.masterGain.disconnect();\n this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);\n }\n }\n}\n//# sourceMappingURL=audioEngine.js.map","import { Tools } from \"../Misc/tools.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { _WarnImport } from \"../Misc/devTools.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n/**\n * Defines a sound that can be played in the application.\n * The sound can either be an ambient track or a simple sound played in reaction to a user action.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic\n */\nexport class Sound {\n /**\n * Does the sound loop after it finishes playing once.\n */\n get loop() {\n return this._loop;\n }\n set loop(value) {\n if (value === this._loop) {\n return;\n }\n this._loop = value;\n this.updateOptions({ loop: value });\n }\n /**\n * Gets the current time for the sound.\n */\n get currentTime() {\n var _a;\n if (this._htmlAudioElement) {\n return this._htmlAudioElement.currentTime;\n }\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.audioContext) && (this.isPlaying || this.isPaused)) {\n // The `_currentTime` member is only updated when the sound is paused. Add the time since the last start\n // to get the actual current time.\n const timeSinceLastStart = this.isPaused ? 0 : Engine.audioEngine.audioContext.currentTime - this._startTime;\n return this._currentTime + timeSinceLastStart;\n }\n return 0;\n }\n /**\n * Does this sound enables spatial sound.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound\n */\n get spatialSound() {\n return this._spatialSound;\n }\n /**\n * Does this sound enables spatial sound.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound\n */\n set spatialSound(newValue) {\n var _a;\n this._spatialSound = newValue;\n if (this._spatialSound && ((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && Engine.audioEngine.audioContext) {\n this._createSpatialParameters();\n }\n }\n /**\n * Create a sound and attach it to a scene\n * @param name Name of your sound\n * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams and AudioBuffers\n * @param scene defines the scene the sound belongs to\n * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played\n * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming\n */\n constructor(name, urlOrArrayBuffer, scene, readyToPlayCallback = null, options) {\n var _a, _b, _c, _d, _e;\n /**\n * Does the sound autoplay once loaded.\n */\n this.autoplay = false;\n this._loop = false;\n /**\n * Does the sound use a custom attenuation curve to simulate the falloff\n * happening when the source gets further away from the camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-your-own-custom-attenuation-function\n */\n this.useCustomAttenuation = false;\n /**\n * Is this sound currently played.\n */\n this.isPlaying = false;\n /**\n * Is this sound currently paused.\n */\n this.isPaused = false;\n /**\n * Define the reference distance the sound should be heard perfectly.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound\n */\n this.refDistance = 1;\n /**\n * Define the roll off factor of spatial sounds.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound\n */\n this.rolloffFactor = 1;\n /**\n * Define the max distance the sound should be heard (intensity just became 0 at this point).\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound\n */\n this.maxDistance = 100;\n /**\n * Define the distance attenuation model the sound will follow.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound\n */\n this.distanceModel = \"linear\";\n /**\n * Gets or sets an object used to store user defined information for the sound.\n */\n this.metadata = null;\n /**\n * Observable event when the current playing sound finishes.\n */\n this.onEndedObservable = new Observable();\n this._spatialSound = false;\n this._panningModel = \"equalpower\";\n this._playbackRate = 1;\n this._streaming = false;\n this._startTime = 0;\n this._currentTime = 0;\n this._position = Vector3.Zero();\n this._localDirection = new Vector3(1, 0, 0);\n this._volume = 1;\n this._isReadyToPlay = false;\n this._isDirectional = false;\n // Used if you'd like to create a directional sound.\n // If not set, the sound will be omnidirectional\n this._coneInnerAngle = 360;\n this._coneOuterAngle = 360;\n this._coneOuterGain = 0;\n this._isOutputConnected = false;\n this._urlType = \"Unknown\";\n this.name = name;\n scene = scene || EngineStore.LastCreatedScene;\n if (!scene) {\n return;\n }\n this._scene = scene;\n Sound._SceneComponentInitialization(scene);\n this._readyToPlayCallback = readyToPlayCallback;\n // Default custom attenuation function is a linear attenuation\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this._customAttenuationFunction = (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) => {\n if (currentDistance < maxDistance) {\n return currentVolume * (1 - currentDistance / maxDistance);\n }\n else {\n return 0;\n }\n };\n if (options) {\n this.autoplay = options.autoplay || false;\n this._loop = options.loop || false;\n // if volume === 0, we need another way to check this option\n if (options.volume !== undefined) {\n this._volume = options.volume;\n }\n this._spatialSound = (_a = options.spatialSound) !== null && _a !== void 0 ? _a : false;\n this.maxDistance = (_b = options.maxDistance) !== null && _b !== void 0 ? _b : 100;\n this.useCustomAttenuation = (_c = options.useCustomAttenuation) !== null && _c !== void 0 ? _c : false;\n this.rolloffFactor = options.rolloffFactor || 1;\n this.refDistance = options.refDistance || 1;\n this.distanceModel = options.distanceModel || \"linear\";\n this._playbackRate = options.playbackRate || 1;\n this._streaming = (_d = options.streaming) !== null && _d !== void 0 ? _d : false;\n this._length = options.length;\n this._offset = options.offset;\n }\n if (((_e = Engine.audioEngine) === null || _e === void 0 ? void 0 : _e.canUseWebAudio) && Engine.audioEngine.audioContext) {\n this._soundGain = Engine.audioEngine.audioContext.createGain();\n this._soundGain.gain.value = this._volume;\n this._inputAudioNode = this._soundGain;\n this._outputAudioNode = this._soundGain;\n if (this._spatialSound) {\n this._createSpatialParameters();\n }\n this._scene.mainSoundTrack.addSound(this);\n let validParameter = true;\n // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound\n if (urlOrArrayBuffer) {\n try {\n if (typeof urlOrArrayBuffer === \"string\") {\n this._urlType = \"String\";\n }\n else if (urlOrArrayBuffer instanceof ArrayBuffer) {\n this._urlType = \"ArrayBuffer\";\n }\n else if (urlOrArrayBuffer instanceof HTMLMediaElement) {\n this._urlType = \"MediaElement\";\n }\n else if (urlOrArrayBuffer instanceof MediaStream) {\n this._urlType = \"MediaStream\";\n }\n else if (urlOrArrayBuffer instanceof AudioBuffer) {\n this._urlType = \"AudioBuffer\";\n }\n else if (Array.isArray(urlOrArrayBuffer)) {\n this._urlType = \"Array\";\n }\n let urls = [];\n let codecSupportedFound = false;\n switch (this._urlType) {\n case \"MediaElement\":\n this._streaming = true;\n this._isReadyToPlay = true;\n this._streamingSource = Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);\n if (this.autoplay) {\n this.play(0, this._offset, this._length);\n }\n if (this._readyToPlayCallback) {\n this._readyToPlayCallback();\n }\n break;\n case \"MediaStream\":\n this._streaming = true;\n this._isReadyToPlay = true;\n this._streamingSource = Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);\n if (this.autoplay) {\n this.play(0, this._offset, this._length);\n }\n if (this._readyToPlayCallback) {\n this._readyToPlayCallback();\n }\n break;\n case \"ArrayBuffer\":\n if (urlOrArrayBuffer.byteLength > 0) {\n codecSupportedFound = true;\n this._soundLoaded(urlOrArrayBuffer);\n }\n break;\n case \"AudioBuffer\":\n this._audioBufferLoaded(urlOrArrayBuffer);\n break;\n case \"String\":\n urls.push(urlOrArrayBuffer);\n // eslint-disable-next-line no-fallthrough\n case \"Array\":\n if (urls.length === 0) {\n urls = urlOrArrayBuffer;\n }\n // If we found a supported format, we load it immediately and stop the loop\n for (let i = 0; i < urls.length; i++) {\n const url = urls[i];\n codecSupportedFound =\n (options && options.skipCodecCheck) ||\n (url.indexOf(\".mp3\", url.length - 4) !== -1 && Engine.audioEngine.isMP3supported) ||\n (url.indexOf(\".ogg\", url.length - 4) !== -1 && Engine.audioEngine.isOGGsupported) ||\n url.indexOf(\".wav\", url.length - 4) !== -1 ||\n url.indexOf(\".m4a\", url.length - 4) !== -1 ||\n url.indexOf(\".mp4\", url.length - 4) !== -1 ||\n url.indexOf(\"blob:\") !== -1;\n if (codecSupportedFound) {\n // Loading sound\n if (!this._streaming) {\n this._scene._loadFile(url, (data) => {\n this._soundLoaded(data);\n }, undefined, true, true, (exception) => {\n if (exception) {\n Logger.Error(\"XHR \" + exception.status + \" error on: \" + url + \".\");\n }\n Logger.Error(\"Sound creation aborted.\");\n this._scene.mainSoundTrack.removeSound(this);\n });\n }\n // Streaming sound using HTML5 Audio tag\n else {\n this._htmlAudioElement = new Audio(url);\n this._htmlAudioElement.controls = false;\n this._htmlAudioElement.loop = this.loop;\n Tools.SetCorsBehavior(url, this._htmlAudioElement);\n this._htmlAudioElement.preload = \"auto\";\n this._htmlAudioElement.addEventListener(\"canplaythrough\", () => {\n this._isReadyToPlay = true;\n if (this.autoplay) {\n this.play(0, this._offset, this._length);\n }\n if (this._readyToPlayCallback) {\n this._readyToPlayCallback();\n }\n });\n document.body.appendChild(this._htmlAudioElement);\n this._htmlAudioElement.load();\n }\n break;\n }\n }\n break;\n default:\n validParameter = false;\n break;\n }\n if (!validParameter) {\n Logger.Error(\"Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.\");\n }\n else {\n if (!codecSupportedFound) {\n this._isReadyToPlay = true;\n // Simulating a ready to play event to avoid breaking code path\n if (this._readyToPlayCallback) {\n setTimeout(() => {\n if (this._readyToPlayCallback) {\n this._readyToPlayCallback();\n }\n }, 1000);\n }\n }\n }\n }\n catch (ex) {\n Logger.Error(\"Unexpected error. Sound creation aborted.\");\n this._scene.mainSoundTrack.removeSound(this);\n }\n }\n }\n else {\n // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers\n this._scene.mainSoundTrack.addSound(this);\n if (Engine.audioEngine && !Engine.audioEngine.WarnedWebAudioUnsupported) {\n Logger.Error(\"Web Audio is not supported by your browser.\");\n Engine.audioEngine.WarnedWebAudioUnsupported = true;\n }\n // Simulating a ready to play event to avoid breaking code for non web audio browsers\n if (this._readyToPlayCallback) {\n setTimeout(() => {\n if (this._readyToPlayCallback) {\n this._readyToPlayCallback();\n }\n }, 1000);\n }\n }\n }\n /**\n * Release the sound and its associated resources\n */\n dispose() {\n var _a;\n if ((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) {\n if (this.isPlaying) {\n this.stop();\n }\n this._isReadyToPlay = false;\n if (this.soundTrackId === -1) {\n this._scene.mainSoundTrack.removeSound(this);\n }\n else if (this._scene.soundTracks) {\n this._scene.soundTracks[this.soundTrackId].removeSound(this);\n }\n if (this._soundGain) {\n this._soundGain.disconnect();\n this._soundGain = null;\n }\n if (this._soundPanner) {\n this._soundPanner.disconnect();\n this._soundPanner = null;\n }\n if (this._soundSource) {\n this._soundSource.disconnect();\n this._soundSource = null;\n }\n this._audioBuffer = null;\n if (this._htmlAudioElement) {\n this._htmlAudioElement.pause();\n this._htmlAudioElement.src = \"\";\n document.body.removeChild(this._htmlAudioElement);\n }\n if (this._streamingSource) {\n this._streamingSource.disconnect();\n }\n if (this._connectedTransformNode && this._registerFunc) {\n this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc);\n this._connectedTransformNode = null;\n }\n }\n }\n /**\n * Gets if the sounds is ready to be played or not.\n * @returns true if ready, otherwise false\n */\n isReady() {\n return this._isReadyToPlay;\n }\n /**\n * Get the current class name.\n * @returns current class name\n */\n getClassName() {\n return \"Sound\";\n }\n _audioBufferLoaded(buffer) {\n var _a;\n if (!((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.audioContext)) {\n return;\n }\n this._audioBuffer = buffer;\n this._isReadyToPlay = true;\n if (this.autoplay) {\n this.play(0, this._offset, this._length);\n }\n if (this._readyToPlayCallback) {\n this._readyToPlayCallback();\n }\n }\n _soundLoaded(audioData) {\n var _a;\n if (!((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.audioContext)) {\n return;\n }\n Engine.audioEngine.audioContext.decodeAudioData(audioData, (buffer) => {\n this._audioBufferLoaded(buffer);\n }, (err) => {\n Logger.Error(\"Error while decoding audio data for: \" + this.name + \" / Error: \" + err);\n });\n }\n /**\n * Sets the data of the sound from an audiobuffer\n * @param audioBuffer The audioBuffer containing the data\n */\n setAudioBuffer(audioBuffer) {\n var _a;\n if ((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) {\n this._audioBuffer = audioBuffer;\n this._isReadyToPlay = true;\n }\n }\n /**\n * Updates the current sounds options such as maxdistance, loop...\n * @param options A JSON object containing values named as the object properties\n */\n updateOptions(options) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;\n if (options) {\n this.loop = (_a = options.loop) !== null && _a !== void 0 ? _a : this.loop;\n this.maxDistance = (_b = options.maxDistance) !== null && _b !== void 0 ? _b : this.maxDistance;\n this.useCustomAttenuation = (_c = options.useCustomAttenuation) !== null && _c !== void 0 ? _c : this.useCustomAttenuation;\n this.rolloffFactor = (_d = options.rolloffFactor) !== null && _d !== void 0 ? _d : this.rolloffFactor;\n this.refDistance = (_e = options.refDistance) !== null && _e !== void 0 ? _e : this.refDistance;\n this.distanceModel = (_f = options.distanceModel) !== null && _f !== void 0 ? _f : this.distanceModel;\n this._playbackRate = (_g = options.playbackRate) !== null && _g !== void 0 ? _g : this._playbackRate;\n this._length = (_h = options.length) !== null && _h !== void 0 ? _h : undefined;\n this._setOffset((_j = options.offset) !== null && _j !== void 0 ? _j : undefined);\n this.setVolume((_k = options.volume) !== null && _k !== void 0 ? _k : this._volume);\n this._updateSpatialParameters();\n if (this.isPlaying) {\n if (this._streaming && this._htmlAudioElement) {\n this._htmlAudioElement.playbackRate = this._playbackRate;\n if (this._htmlAudioElement.loop !== this.loop) {\n this._htmlAudioElement.loop = this.loop;\n }\n }\n else {\n if (this._soundSource) {\n this._soundSource.playbackRate.value = this._playbackRate;\n if (this._soundSource.loop !== this.loop) {\n this._soundSource.loop = this.loop;\n }\n if (this._offset !== undefined && this._soundSource.loopStart !== this._offset) {\n this._soundSource.loopStart = this._offset;\n }\n if (this._length !== undefined && this._length !== this._soundSource.loopEnd) {\n this._soundSource.loopEnd = (this._offset | 0) + this._length;\n }\n }\n }\n }\n }\n }\n _createSpatialParameters() {\n var _a, _b;\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && Engine.audioEngine.audioContext) {\n if (this._scene.headphone) {\n this._panningModel = \"HRTF\";\n }\n this._soundPanner = (_b = this._soundPanner) !== null && _b !== void 0 ? _b : Engine.audioEngine.audioContext.createPanner();\n if (this._soundPanner && this._outputAudioNode) {\n this._updateSpatialParameters();\n this._soundPanner.connect(this._outputAudioNode);\n this._inputAudioNode = this._soundPanner;\n }\n }\n }\n _updateSpatialParameters() {\n if (this._spatialSound && this._soundPanner) {\n if (this.useCustomAttenuation) {\n // Tricks to disable in a way embedded Web Audio attenuation\n this._soundPanner.distanceModel = \"linear\";\n this._soundPanner.maxDistance = Number.MAX_VALUE;\n this._soundPanner.refDistance = 1;\n this._soundPanner.rolloffFactor = 1;\n this._soundPanner.panningModel = this._panningModel;\n }\n else {\n this._soundPanner.distanceModel = this.distanceModel;\n this._soundPanner.maxDistance = this.maxDistance;\n this._soundPanner.refDistance = this.refDistance;\n this._soundPanner.rolloffFactor = this.rolloffFactor;\n this._soundPanner.panningModel = this._panningModel;\n }\n }\n }\n /**\n * Switch the panning model to HRTF:\n * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound\n */\n switchPanningModelToHRTF() {\n this._panningModel = \"HRTF\";\n this._switchPanningModel();\n }\n /**\n * Switch the panning model to Equal Power:\n * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound\n */\n switchPanningModelToEqualPower() {\n this._panningModel = \"equalpower\";\n this._switchPanningModel();\n }\n _switchPanningModel() {\n var _a;\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._spatialSound && this._soundPanner) {\n this._soundPanner.panningModel = this._panningModel;\n }\n }\n /**\n * Connect this sound to a sound track audio node like gain...\n * @param soundTrackAudioNode the sound track audio node to connect to\n */\n connectToSoundTrackAudioNode(soundTrackAudioNode) {\n var _a;\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._outputAudioNode) {\n if (this._isOutputConnected) {\n this._outputAudioNode.disconnect();\n }\n this._outputAudioNode.connect(soundTrackAudioNode);\n this._isOutputConnected = true;\n }\n }\n /**\n * Transform this sound into a directional source\n * @param coneInnerAngle Size of the inner cone in degree\n * @param coneOuterAngle Size of the outer cone in degree\n * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)\n */\n setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {\n if (coneOuterAngle < coneInnerAngle) {\n Logger.Error(\"setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.\");\n return;\n }\n this._coneInnerAngle = coneInnerAngle;\n this._coneOuterAngle = coneOuterAngle;\n this._coneOuterGain = coneOuterGain;\n this._isDirectional = true;\n if (this.isPlaying && this.loop) {\n this.stop();\n this.play(0, this._offset, this._length);\n }\n }\n /**\n * Gets or sets the inner angle for the directional cone.\n */\n get directionalConeInnerAngle() {\n return this._coneInnerAngle;\n }\n /**\n * Gets or sets the inner angle for the directional cone.\n */\n set directionalConeInnerAngle(value) {\n var _a;\n if (value != this._coneInnerAngle) {\n if (this._coneOuterAngle < value) {\n Logger.Error(\"directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.\");\n return;\n }\n this._coneInnerAngle = value;\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._spatialSound && this._soundPanner) {\n this._soundPanner.coneInnerAngle = this._coneInnerAngle;\n }\n }\n }\n /**\n * Gets or sets the outer angle for the directional cone.\n */\n get directionalConeOuterAngle() {\n return this._coneOuterAngle;\n }\n /**\n * Gets or sets the outer angle for the directional cone.\n */\n set directionalConeOuterAngle(value) {\n var _a;\n if (value != this._coneOuterAngle) {\n if (value < this._coneInnerAngle) {\n Logger.Error(\"directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.\");\n return;\n }\n this._coneOuterAngle = value;\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._spatialSound && this._soundPanner) {\n this._soundPanner.coneOuterAngle = this._coneOuterAngle;\n }\n }\n }\n /**\n * Sets the position of the emitter if spatial sound is enabled\n * @param newPosition Defines the new position\n */\n setPosition(newPosition) {\n var _a;\n if (newPosition.equals(this._position)) {\n return;\n }\n this._position.copyFrom(newPosition);\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {\n this._soundPanner.positionX.value = this._position.x;\n this._soundPanner.positionY.value = this._position.y;\n this._soundPanner.positionZ.value = this._position.z;\n }\n }\n /**\n * Sets the local direction of the emitter if spatial sound is enabled\n * @param newLocalDirection Defines the new local direction\n */\n setLocalDirectionToMesh(newLocalDirection) {\n var _a;\n this._localDirection = newLocalDirection;\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._connectedTransformNode && this.isPlaying) {\n this._updateDirection();\n }\n }\n _updateDirection() {\n if (!this._connectedTransformNode || !this._soundPanner) {\n return;\n }\n const mat = this._connectedTransformNode.getWorldMatrix();\n const direction = Vector3.TransformNormal(this._localDirection, mat);\n direction.normalize();\n this._soundPanner.orientationX.value = direction.x;\n this._soundPanner.orientationY.value = direction.y;\n this._soundPanner.orientationZ.value = direction.z;\n }\n /** @internal */\n updateDistanceFromListener() {\n var _a;\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._connectedTransformNode && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {\n const distance = this._scene.audioListenerPositionProvider\n ? this._connectedTransformNode.position.subtract(this._scene.audioListenerPositionProvider()).length()\n : this._connectedTransformNode.getDistanceToCamera(this._scene.activeCamera);\n this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);\n }\n }\n /**\n * Sets a new custom attenuation function for the sound.\n * @param callback Defines the function used for the attenuation\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-your-own-custom-attenuation-function\n */\n setAttenuationFunction(callback) {\n this._customAttenuationFunction = callback;\n }\n /**\n * Play the sound\n * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.\n * @param offset (optional) Start the sound at a specific time in seconds\n * @param length (optional) Sound duration (in seconds)\n */\n play(time, offset, length) {\n var _a, _b, _c, _d;\n if (this._isReadyToPlay && this._scene.audioEnabled && ((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.audioContext)) {\n try {\n let startTime = time ? ((_b = Engine.audioEngine) === null || _b === void 0 ? void 0 : _b.audioContext.currentTime) + time : (_c = Engine.audioEngine) === null || _c === void 0 ? void 0 : _c.audioContext.currentTime;\n if (!this._soundSource || !this._streamingSource) {\n if (this._spatialSound && this._soundPanner) {\n if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {\n this._soundPanner.positionX.value = this._position.x;\n this._soundPanner.positionY.value = this._position.y;\n this._soundPanner.positionZ.value = this._position.z;\n }\n if (this._isDirectional) {\n this._soundPanner.coneInnerAngle = this._coneInnerAngle;\n this._soundPanner.coneOuterAngle = this._coneOuterAngle;\n this._soundPanner.coneOuterGain = this._coneOuterGain;\n if (this._connectedTransformNode) {\n this._updateDirection();\n }\n else {\n this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);\n }\n }\n }\n }\n if (this._streaming) {\n if (!this._streamingSource) {\n this._streamingSource = Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);\n this._htmlAudioElement.onended = () => {\n this._onended();\n };\n this._htmlAudioElement.playbackRate = this._playbackRate;\n }\n this._streamingSource.disconnect();\n if (this._inputAudioNode) {\n this._streamingSource.connect(this._inputAudioNode);\n }\n if (this._htmlAudioElement) {\n // required to manage properly the new suspended default state of Chrome\n // When the option 'streaming: true' is used, we need first to wait for\n // the audio engine to be unlocked by a user gesture before trying to play\n // an HTML Audio element\n const tryToPlay = () => {\n var _a, _b;\n if ((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.unlocked) {\n const playPromise = this._htmlAudioElement.play();\n // In browsers that don’t yet support this functionality,\n // playPromise won’t be defined.\n if (playPromise !== undefined) {\n playPromise.catch(() => {\n var _a, _b;\n // Automatic playback failed.\n // Waiting for the audio engine to be unlocked by user click on unmute\n (_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.lock();\n if (this.loop || this.autoplay) {\n (_b = Engine.audioEngine) === null || _b === void 0 ? void 0 : _b.onAudioUnlockedObservable.addOnce(() => {\n tryToPlay();\n });\n }\n });\n }\n }\n else {\n if (this.loop || this.autoplay) {\n (_b = Engine.audioEngine) === null || _b === void 0 ? void 0 : _b.onAudioUnlockedObservable.addOnce(() => {\n tryToPlay();\n });\n }\n }\n };\n tryToPlay();\n }\n }\n else {\n const tryToPlay = () => {\n var _a, _b, _c, _d;\n if ((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.audioContext) {\n length = length || this._length;\n if (offset !== undefined) {\n this._setOffset(offset);\n }\n if (this._soundSource) {\n const oldSource = this._soundSource;\n oldSource.onended = () => {\n oldSource.disconnect();\n };\n }\n this._soundSource = (_b = Engine.audioEngine) === null || _b === void 0 ? void 0 : _b.audioContext.createBufferSource();\n if (this._soundSource && this._inputAudioNode) {\n this._soundSource.buffer = this._audioBuffer;\n this._soundSource.connect(this._inputAudioNode);\n this._soundSource.loop = this.loop;\n if (offset !== undefined) {\n this._soundSource.loopStart = offset;\n }\n if (length !== undefined) {\n this._soundSource.loopEnd = (offset | 0) + length;\n }\n this._soundSource.playbackRate.value = this._playbackRate;\n this._soundSource.onended = () => {\n this._onended();\n };\n startTime = time ? ((_c = Engine.audioEngine) === null || _c === void 0 ? void 0 : _c.audioContext.currentTime) + time : Engine.audioEngine.audioContext.currentTime;\n const actualOffset = ((this.isPaused ? this.currentTime : 0) + ((_d = this._offset) !== null && _d !== void 0 ? _d : 0)) % this._soundSource.buffer.duration;\n this._soundSource.start(startTime, actualOffset, this.loop ? undefined : length);\n }\n }\n };\n if (((_d = Engine.audioEngine) === null || _d === void 0 ? void 0 : _d.audioContext.state) === \"suspended\") {\n // Wait a bit for FF as context seems late to be ready.\n setTimeout(() => {\n var _a;\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.audioContext.state) === \"suspended\") {\n // Automatic playback failed.\n // Waiting for the audio engine to be unlocked by user click on unmute\n Engine.audioEngine.lock();\n if (this.loop || this.autoplay) {\n Engine.audioEngine.onAudioUnlockedObservable.addOnce(() => {\n tryToPlay();\n });\n }\n }\n else {\n tryToPlay();\n }\n }, 500);\n }\n else {\n tryToPlay();\n }\n }\n this._startTime = startTime;\n this.isPlaying = true;\n this.isPaused = false;\n }\n catch (ex) {\n Logger.Error(\"Error while trying to play audio: \" + this.name + \", \" + ex.message);\n }\n }\n }\n _onended() {\n this.isPlaying = false;\n this._startTime = 0;\n this._currentTime = 0;\n if (this.onended) {\n this.onended();\n }\n this.onEndedObservable.notifyObservers(this);\n }\n /**\n * Stop the sound\n * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.\n */\n stop(time) {\n var _a;\n if (this.isPlaying) {\n if (this._streaming) {\n if (this._htmlAudioElement) {\n this._htmlAudioElement.pause();\n // Test needed for Firefox or it will generate an Invalid State Error\n if (this._htmlAudioElement.currentTime > 0) {\n this._htmlAudioElement.currentTime = 0;\n }\n }\n else {\n this._streamingSource.disconnect();\n }\n this.isPlaying = false;\n }\n else if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.audioContext) && this._soundSource) {\n const stopTime = time ? Engine.audioEngine.audioContext.currentTime + time : undefined;\n this._soundSource.onended = () => {\n this.isPlaying = false;\n this.isPaused = false;\n this._startTime = 0;\n this._currentTime = 0;\n if (this._soundSource) {\n this._soundSource.onended = () => void 0;\n }\n this._onended();\n };\n this._soundSource.stop(stopTime);\n }\n }\n else if (this.isPaused) {\n this.isPaused = false;\n this._startTime = 0;\n this._currentTime = 0;\n }\n }\n /**\n * Put the sound in pause\n */\n pause() {\n var _a;\n if (this.isPlaying) {\n if (this._streaming) {\n if (this._htmlAudioElement) {\n this._htmlAudioElement.pause();\n }\n else {\n this._streamingSource.disconnect();\n }\n this.isPlaying = false;\n this.isPaused = true;\n }\n else if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.audioContext) && this._soundSource) {\n this._soundSource.onended = () => void 0;\n this._soundSource.stop();\n this.isPlaying = false;\n this.isPaused = true;\n this._currentTime += Engine.audioEngine.audioContext.currentTime - this._startTime;\n }\n }\n }\n /**\n * Sets a dedicated volume for this sounds\n * @param newVolume Define the new volume of the sound\n * @param time Define time for gradual change to new volume\n */\n setVolume(newVolume, time) {\n var _a;\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._soundGain) {\n if (time && Engine.audioEngine.audioContext) {\n this._soundGain.gain.cancelScheduledValues(Engine.audioEngine.audioContext.currentTime);\n this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, Engine.audioEngine.audioContext.currentTime);\n this._soundGain.gain.linearRampToValueAtTime(newVolume, Engine.audioEngine.audioContext.currentTime + time);\n }\n else {\n this._soundGain.gain.value = newVolume;\n }\n }\n this._volume = newVolume;\n }\n /**\n * Set the sound play back rate\n * @param newPlaybackRate Define the playback rate the sound should be played at\n */\n setPlaybackRate(newPlaybackRate) {\n this._playbackRate = newPlaybackRate;\n if (this.isPlaying) {\n if (this._streaming && this._htmlAudioElement) {\n this._htmlAudioElement.playbackRate = this._playbackRate;\n }\n else if (this._soundSource) {\n this._soundSource.playbackRate.value = this._playbackRate;\n }\n }\n }\n /**\n * Gets the sound play back rate.\n * @returns the play back rate of the sound\n */\n getPlaybackRate() {\n return this._playbackRate;\n }\n /**\n * Gets the volume of the sound.\n * @returns the volume of the sound\n */\n getVolume() {\n return this._volume;\n }\n /**\n * Attach the sound to a dedicated mesh\n * @param transformNode The transform node to connect the sound with\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#attaching-a-sound-to-a-mesh\n */\n attachToMesh(transformNode) {\n if (this._connectedTransformNode && this._registerFunc) {\n this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc);\n this._registerFunc = null;\n }\n this._connectedTransformNode = transformNode;\n if (!this._spatialSound) {\n this._spatialSound = true;\n this._createSpatialParameters();\n if (this.isPlaying && this.loop) {\n this.stop();\n this.play(0, this._offset, this._length);\n }\n }\n this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode);\n this._registerFunc = (transformNode) => this._onRegisterAfterWorldMatrixUpdate(transformNode);\n this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc);\n }\n /**\n * Detach the sound from the previously attached mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#attaching-a-sound-to-a-mesh\n */\n detachFromMesh() {\n if (this._connectedTransformNode && this._registerFunc) {\n this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc);\n this._registerFunc = null;\n this._connectedTransformNode = null;\n }\n }\n _onRegisterAfterWorldMatrixUpdate(node) {\n var _a;\n if (!node.getBoundingInfo) {\n this.setPosition(node.absolutePosition);\n }\n else {\n const mesh = node;\n const boundingInfo = mesh.getBoundingInfo();\n this.setPosition(boundingInfo.boundingSphere.centerWorld);\n }\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._isDirectional && this.isPlaying) {\n this._updateDirection();\n }\n }\n /**\n * Clone the current sound in the scene.\n * @returns the new sound clone\n */\n clone() {\n if (!this._streaming) {\n const setBufferAndRun = () => {\n if (this._isReadyToPlay) {\n clonedSound._audioBuffer = this.getAudioBuffer();\n clonedSound._isReadyToPlay = true;\n if (clonedSound.autoplay) {\n clonedSound.play(0, this._offset, this._length);\n }\n }\n else {\n setTimeout(setBufferAndRun, 300);\n }\n };\n const currentOptions = {\n autoplay: this.autoplay,\n loop: this.loop,\n volume: this._volume,\n spatialSound: this._spatialSound,\n maxDistance: this.maxDistance,\n useCustomAttenuation: this.useCustomAttenuation,\n rolloffFactor: this.rolloffFactor,\n refDistance: this.refDistance,\n distanceModel: this.distanceModel,\n };\n const clonedSound = new Sound(this.name + \"_cloned\", new ArrayBuffer(0), this._scene, null, currentOptions);\n if (this.useCustomAttenuation) {\n clonedSound.setAttenuationFunction(this._customAttenuationFunction);\n }\n clonedSound.setPosition(this._position);\n clonedSound.setPlaybackRate(this._playbackRate);\n setBufferAndRun();\n return clonedSound;\n }\n // Can't clone a streaming sound\n else {\n return null;\n }\n }\n /**\n * Gets the current underlying audio buffer containing the data\n * @returns the audio buffer\n */\n getAudioBuffer() {\n return this._audioBuffer;\n }\n /**\n * Gets the WebAudio AudioBufferSourceNode, lets you keep track of and stop instances of this Sound.\n * @returns the source node\n */\n getSoundSource() {\n return this._soundSource;\n }\n /**\n * Gets the WebAudio GainNode, gives you precise control over the gain of instances of this Sound.\n * @returns the gain node\n */\n getSoundGain() {\n return this._soundGain;\n }\n /**\n * Serializes the Sound in a JSON representation\n * @returns the JSON representation of the sound\n */\n serialize() {\n const serializationObject = {\n name: this.name,\n url: this.name,\n autoplay: this.autoplay,\n loop: this.loop,\n volume: this._volume,\n spatialSound: this._spatialSound,\n maxDistance: this.maxDistance,\n rolloffFactor: this.rolloffFactor,\n refDistance: this.refDistance,\n distanceModel: this.distanceModel,\n playbackRate: this._playbackRate,\n panningModel: this._panningModel,\n soundTrackId: this.soundTrackId,\n metadata: this.metadata,\n };\n if (this._spatialSound) {\n if (this._connectedTransformNode) {\n serializationObject.connectedMeshId = this._connectedTransformNode.id;\n }\n serializationObject.position = this._position.asArray();\n serializationObject.refDistance = this.refDistance;\n serializationObject.distanceModel = this.distanceModel;\n serializationObject.isDirectional = this._isDirectional;\n serializationObject.localDirectionToMesh = this._localDirection.asArray();\n serializationObject.coneInnerAngle = this._coneInnerAngle;\n serializationObject.coneOuterAngle = this._coneOuterAngle;\n serializationObject.coneOuterGain = this._coneOuterGain;\n }\n return serializationObject;\n }\n /**\n * Parse a JSON representation of a sound to instantiate in a given scene\n * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)\n * @param scene Define the scene the new parsed sound should be created in\n * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies\n * @param sourceSound Define a sound place holder if do not need to instantiate a new one\n * @returns the newly parsed sound\n */\n static Parse(parsedSound, scene, rootUrl, sourceSound) {\n const soundName = parsedSound.name;\n let soundUrl;\n if (parsedSound.url) {\n soundUrl = rootUrl + parsedSound.url;\n }\n else {\n soundUrl = rootUrl + soundName;\n }\n const options = {\n autoplay: parsedSound.autoplay,\n loop: parsedSound.loop,\n volume: parsedSound.volume,\n spatialSound: parsedSound.spatialSound,\n maxDistance: parsedSound.maxDistance,\n rolloffFactor: parsedSound.rolloffFactor,\n refDistance: parsedSound.refDistance,\n distanceModel: parsedSound.distanceModel,\n playbackRate: parsedSound.playbackRate,\n };\n let newSound;\n if (!sourceSound) {\n newSound = new Sound(soundName, soundUrl, scene, () => {\n scene.removePendingData(newSound);\n }, options);\n scene.addPendingData(newSound);\n }\n else {\n const setBufferAndRun = () => {\n if (sourceSound._isReadyToPlay) {\n newSound._audioBuffer = sourceSound.getAudioBuffer();\n newSound._isReadyToPlay = true;\n if (newSound.autoplay) {\n newSound.play(0, newSound._offset, newSound._length);\n }\n }\n else {\n setTimeout(setBufferAndRun, 300);\n }\n };\n newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);\n setBufferAndRun();\n }\n if (parsedSound.position) {\n const soundPosition = Vector3.FromArray(parsedSound.position);\n newSound.setPosition(soundPosition);\n }\n if (parsedSound.isDirectional) {\n newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);\n if (parsedSound.localDirectionToMesh) {\n const localDirectionToMesh = Vector3.FromArray(parsedSound.localDirectionToMesh);\n newSound.setLocalDirectionToMesh(localDirectionToMesh);\n }\n }\n if (parsedSound.connectedMeshId) {\n const connectedMesh = scene.getMeshById(parsedSound.connectedMeshId);\n if (connectedMesh) {\n newSound.attachToMesh(connectedMesh);\n }\n }\n if (parsedSound.metadata) {\n newSound.metadata = parsedSound.metadata;\n }\n return newSound;\n }\n _setOffset(value) {\n if (this._offset === value) {\n return;\n }\n if (this.isPaused) {\n this.stop();\n this.isPaused = false;\n }\n this._offset = value;\n }\n}\n/**\n * @internal\n */\nSound._SceneComponentInitialization = (_) => {\n throw _WarnImport(\"AudioSceneComponent\");\n};\n//# sourceMappingURL=sound.js.map","import { Engine } from \"../Engines/engine.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n/**\n * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.\n * It will be also used in a future release to apply effects on a specific track.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#using-sound-tracks\n */\nexport class SoundTrack {\n /**\n * Creates a new sound track.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#using-sound-tracks\n * @param scene Define the scene the sound track belongs to\n * @param options\n */\n constructor(scene, options = {}) {\n /**\n * The unique identifier of the sound track in the scene.\n */\n this.id = -1;\n this._isInitialized = false;\n scene = scene || EngineStore.LastCreatedScene;\n if (!scene) {\n return;\n }\n this._scene = scene;\n this.soundCollection = new Array();\n this._options = options;\n if (!this._options.mainTrack && this._scene.soundTracks) {\n this._scene.soundTracks.push(this);\n this.id = this._scene.soundTracks.length - 1;\n }\n }\n _initializeSoundTrackAudioGraph() {\n var _a;\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && Engine.audioEngine.audioContext) {\n this._outputAudioNode = Engine.audioEngine.audioContext.createGain();\n this._outputAudioNode.connect(Engine.audioEngine.masterGain);\n if (this._options) {\n if (this._options.volume) {\n this._outputAudioNode.gain.value = this._options.volume;\n }\n }\n this._isInitialized = true;\n }\n }\n /**\n * Release the sound track and its associated resources\n */\n dispose() {\n if (Engine.audioEngine && Engine.audioEngine.canUseWebAudio) {\n if (this._connectedAnalyser) {\n this._connectedAnalyser.stopDebugCanvas();\n }\n while (this.soundCollection.length) {\n this.soundCollection[0].dispose();\n }\n if (this._outputAudioNode) {\n this._outputAudioNode.disconnect();\n }\n this._outputAudioNode = null;\n }\n }\n /**\n * Adds a sound to this sound track\n * @param sound define the sound to add\n * @ignoreNaming\n */\n addSound(sound) {\n var _a;\n if (!this._isInitialized) {\n this._initializeSoundTrackAudioGraph();\n }\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._outputAudioNode) {\n sound.connectToSoundTrackAudioNode(this._outputAudioNode);\n }\n if (sound.soundTrackId) {\n if (sound.soundTrackId === -1) {\n this._scene.mainSoundTrack.removeSound(sound);\n }\n else if (this._scene.soundTracks) {\n this._scene.soundTracks[sound.soundTrackId].removeSound(sound);\n }\n }\n this.soundCollection.push(sound);\n sound.soundTrackId = this.id;\n }\n /**\n * Removes a sound to this sound track\n * @param sound define the sound to remove\n * @ignoreNaming\n */\n removeSound(sound) {\n const index = this.soundCollection.indexOf(sound);\n if (index !== -1) {\n this.soundCollection.splice(index, 1);\n }\n }\n /**\n * Set a global volume for the full sound track.\n * @param newVolume Define the new volume of the sound track\n */\n setVolume(newVolume) {\n var _a;\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._outputAudioNode) {\n this._outputAudioNode.gain.value = newVolume;\n }\n }\n /**\n * Switch the panning model to HRTF:\n * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound\n */\n switchPanningModelToHRTF() {\n var _a;\n if ((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) {\n for (let i = 0; i < this.soundCollection.length; i++) {\n this.soundCollection[i].switchPanningModelToHRTF();\n }\n }\n }\n /**\n * Switch the panning model to Equal Power:\n * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#creating-a-spatial-3d-sound\n */\n switchPanningModelToEqualPower() {\n var _a;\n if ((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) {\n for (let i = 0; i < this.soundCollection.length; i++) {\n this.soundCollection[i].switchPanningModelToEqualPower();\n }\n }\n }\n /**\n * Connect the sound track to an audio analyser allowing some amazing\n * synchronization between the sounds/music and your visualization (VuMeter for instance).\n * @see https://doc.babylonjs.com/features/featuresDeepDive/audio/playingSoundsMusic#using-the-analyser\n * @param analyser The analyser to connect to the engine\n */\n connectToAnalyser(analyser) {\n var _a;\n if (this._connectedAnalyser) {\n this._connectedAnalyser.stopDebugCanvas();\n }\n this._connectedAnalyser = analyser;\n if (((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) && this._outputAudioNode) {\n this._outputAudioNode.disconnect();\n this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, Engine.audioEngine.masterGain);\n }\n }\n}\n//# sourceMappingURL=soundTrack.js.map","import { Sound } from \"./sound.js\";\nimport { SoundTrack } from \"./soundTrack.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { Matrix, Vector3 } from \"../Maths/math.vector.js\";\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { Scene } from \"../scene.js\";\nimport { AbstractScene } from \"../abstractScene.js\";\nimport \"./audioEngine.js\";\nimport { PrecisionDate } from \"../Misc/precisionDate.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n// Adds the parser to the scene parsers.\nAbstractScene.AddParser(SceneComponentConstants.NAME_AUDIO, (parsedData, scene, container, rootUrl) => {\n var _a;\n // TODO: add sound\n let loadedSounds = [];\n let loadedSound;\n container.sounds = container.sounds || [];\n if (parsedData.sounds !== undefined && parsedData.sounds !== null) {\n for (let index = 0, cache = parsedData.sounds.length; index < cache; index++) {\n const parsedSound = parsedData.sounds[index];\n if ((_a = Engine.audioEngine) === null || _a === void 0 ? void 0 : _a.canUseWebAudio) {\n if (!parsedSound.url) {\n parsedSound.url = parsedSound.name;\n }\n if (!loadedSounds[parsedSound.url]) {\n loadedSound = Sound.Parse(parsedSound, scene, rootUrl);\n loadedSounds[parsedSound.url] = loadedSound;\n container.sounds.push(loadedSound);\n }\n else {\n container.sounds.push(Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));\n }\n }\n else {\n container.sounds.push(new Sound(parsedSound.name, null, scene));\n }\n }\n }\n loadedSounds = [];\n});\nObject.defineProperty(Scene.prototype, \"mainSoundTrack\", {\n get: function () {\n let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);\n if (!compo) {\n compo = new AudioSceneComponent(this);\n this._addComponent(compo);\n }\n if (!this._mainSoundTrack) {\n this._mainSoundTrack = new SoundTrack(this, { mainTrack: true });\n }\n return this._mainSoundTrack;\n },\n enumerable: true,\n configurable: true,\n});\nScene.prototype.getSoundByName = function (name) {\n let index;\n for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {\n if (this.mainSoundTrack.soundCollection[index].name === name) {\n return this.mainSoundTrack.soundCollection[index];\n }\n }\n if (this.soundTracks) {\n for (let sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {\n for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {\n if (this.soundTracks[sdIndex].soundCollection[index].name === name) {\n return this.soundTracks[sdIndex].soundCollection[index];\n }\n }\n }\n }\n return null;\n};\nObject.defineProperty(Scene.prototype, \"audioEnabled\", {\n get: function () {\n let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);\n if (!compo) {\n compo = new AudioSceneComponent(this);\n this._addComponent(compo);\n }\n return compo.audioEnabled;\n },\n set: function (value) {\n let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);\n if (!compo) {\n compo = new AudioSceneComponent(this);\n this._addComponent(compo);\n }\n if (value) {\n compo.enableAudio();\n }\n else {\n compo.disableAudio();\n }\n },\n enumerable: true,\n configurable: true,\n});\nObject.defineProperty(Scene.prototype, \"headphone\", {\n get: function () {\n let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);\n if (!compo) {\n compo = new AudioSceneComponent(this);\n this._addComponent(compo);\n }\n return compo.headphone;\n },\n set: function (value) {\n let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);\n if (!compo) {\n compo = new AudioSceneComponent(this);\n this._addComponent(compo);\n }\n if (value) {\n compo.switchAudioModeForHeadphones();\n }\n else {\n compo.switchAudioModeForNormalSpeakers();\n }\n },\n enumerable: true,\n configurable: true,\n});\nObject.defineProperty(Scene.prototype, \"audioListenerPositionProvider\", {\n get: function () {\n let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);\n if (!compo) {\n compo = new AudioSceneComponent(this);\n this._addComponent(compo);\n }\n return compo.audioListenerPositionProvider;\n },\n set: function (value) {\n let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);\n if (!compo) {\n compo = new AudioSceneComponent(this);\n this._addComponent(compo);\n }\n if (value && typeof value !== \"function\") {\n throw new Error(\"The value passed to [Scene.audioListenerPositionProvider] must be a function that returns a Vector3\");\n }\n else {\n compo.audioListenerPositionProvider = value;\n }\n },\n enumerable: true,\n configurable: true,\n});\nObject.defineProperty(Scene.prototype, \"audioListenerRotationProvider\", {\n get: function () {\n let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);\n if (!compo) {\n compo = new AudioSceneComponent(this);\n this._addComponent(compo);\n }\n return compo.audioListenerRotationProvider;\n },\n set: function (value) {\n let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);\n if (!compo) {\n compo = new AudioSceneComponent(this);\n this._addComponent(compo);\n }\n if (value && typeof value !== \"function\") {\n throw new Error(\"The value passed to [Scene.audioListenerRotationProvider] must be a function that returns a Vector3\");\n }\n else {\n compo.audioListenerRotationProvider = value;\n }\n },\n enumerable: true,\n configurable: true,\n});\nObject.defineProperty(Scene.prototype, \"audioPositioningRefreshRate\", {\n get: function () {\n let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);\n if (!compo) {\n compo = new AudioSceneComponent(this);\n this._addComponent(compo);\n }\n return compo.audioPositioningRefreshRate;\n },\n set: function (value) {\n let compo = this._getComponent(SceneComponentConstants.NAME_AUDIO);\n if (!compo) {\n compo = new AudioSceneComponent(this);\n this._addComponent(compo);\n }\n compo.audioPositioningRefreshRate = value;\n },\n enumerable: true,\n configurable: true,\n});\n/**\n * Defines the sound scene component responsible to manage any sounds\n * in a given scene.\n */\nexport class AudioSceneComponent {\n /**\n * Gets whether audio is enabled or not.\n * Please use related enable/disable method to switch state.\n */\n get audioEnabled() {\n return this._audioEnabled;\n }\n /**\n * Gets whether audio is outputting to headphone or not.\n * Please use the according Switch methods to change output.\n */\n get headphone() {\n return this._headphone;\n }\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpful to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_AUDIO;\n this._audioEnabled = true;\n this._headphone = false;\n /**\n * Gets or sets a refresh rate when using 3D audio positioning\n */\n this.audioPositioningRefreshRate = 500;\n /**\n * Gets or Sets a custom listener position for all sounds in the scene\n * By default, this is the position of the first active camera\n */\n this.audioListenerPositionProvider = null;\n /**\n * Gets or Sets a custom listener rotation for all sounds in the scene\n * By default, this is the rotation of the first active camera\n */\n this.audioListenerRotationProvider = null;\n this._cachedCameraDirection = new Vector3();\n this._cachedCameraPosition = new Vector3();\n this._lastCheck = 0;\n this._invertMatrixTemp = new Matrix();\n this._cameraDirectionTemp = new Vector3();\n scene = scene || EngineStore.LastCreatedScene;\n if (!scene) {\n return;\n }\n this.scene = scene;\n scene.soundTracks = new Array();\n scene.sounds = new Array();\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene._afterRenderStage.registerStep(SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n // Nothing to do here. (Not rendering related)\n }\n /**\n * Serializes the component data to the specified json object\n * @param serializationObject The object to serialize to\n */\n serialize(serializationObject) {\n serializationObject.sounds = [];\n if (this.scene.soundTracks) {\n for (let index = 0; index < this.scene.soundTracks.length; index++) {\n const soundtrack = this.scene.soundTracks[index];\n for (let soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {\n serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());\n }\n }\n }\n }\n /**\n * Adds all the elements from the container to the scene\n * @param container the container holding the elements\n */\n addFromContainer(container) {\n if (!container.sounds) {\n return;\n }\n container.sounds.forEach((sound) => {\n sound.play();\n sound.autoplay = true;\n this.scene.mainSoundTrack.addSound(sound);\n });\n }\n /**\n * Removes all the elements in the container from the scene\n * @param container contains the elements to remove\n * @param dispose if the removed element should be disposed (default: false)\n */\n removeFromContainer(container, dispose = false) {\n if (!container.sounds) {\n return;\n }\n container.sounds.forEach((sound) => {\n sound.stop();\n sound.autoplay = false;\n this.scene.mainSoundTrack.removeSound(sound);\n if (dispose) {\n sound.dispose();\n }\n });\n }\n /**\n * Disposes the component and the associated resources.\n */\n dispose() {\n const scene = this.scene;\n if (scene._mainSoundTrack) {\n scene.mainSoundTrack.dispose();\n }\n if (scene.soundTracks) {\n for (let scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {\n scene.soundTracks[scIndex].dispose();\n }\n }\n }\n /**\n * Disables audio in the associated scene.\n */\n disableAudio() {\n const scene = this.scene;\n this._audioEnabled = false;\n if (Engine.audioEngine && Engine.audioEngine.audioContext) {\n Engine.audioEngine.audioContext.suspend();\n }\n let i;\n for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {\n scene.mainSoundTrack.soundCollection[i].pause();\n }\n if (scene.soundTracks) {\n for (i = 0; i < scene.soundTracks.length; i++) {\n for (let j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {\n scene.soundTracks[i].soundCollection[j].pause();\n }\n }\n }\n }\n /**\n * Enables audio in the associated scene.\n */\n enableAudio() {\n const scene = this.scene;\n this._audioEnabled = true;\n if (Engine.audioEngine && Engine.audioEngine.audioContext) {\n Engine.audioEngine.audioContext.resume();\n }\n let i;\n for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {\n if (scene.mainSoundTrack.soundCollection[i].isPaused) {\n scene.mainSoundTrack.soundCollection[i].play();\n }\n }\n if (scene.soundTracks) {\n for (i = 0; i < scene.soundTracks.length; i++) {\n for (let j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {\n if (scene.soundTracks[i].soundCollection[j].isPaused) {\n scene.soundTracks[i].soundCollection[j].play();\n }\n }\n }\n }\n }\n /**\n * Switch audio to headphone output.\n */\n switchAudioModeForHeadphones() {\n const scene = this.scene;\n this._headphone = true;\n scene.mainSoundTrack.switchPanningModelToHRTF();\n if (scene.soundTracks) {\n for (let i = 0; i < scene.soundTracks.length; i++) {\n scene.soundTracks[i].switchPanningModelToHRTF();\n }\n }\n }\n /**\n * Switch audio to normal speakers.\n */\n switchAudioModeForNormalSpeakers() {\n const scene = this.scene;\n this._headphone = false;\n scene.mainSoundTrack.switchPanningModelToEqualPower();\n if (scene.soundTracks) {\n for (let i = 0; i < scene.soundTracks.length; i++) {\n scene.soundTracks[i].switchPanningModelToEqualPower();\n }\n }\n }\n _afterRender() {\n const now = PrecisionDate.Now;\n if (this._lastCheck && now - this._lastCheck < this.audioPositioningRefreshRate) {\n return;\n }\n this._lastCheck = now;\n const scene = this.scene;\n if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {\n return;\n }\n const audioEngine = Engine.audioEngine;\n if (!audioEngine) {\n return;\n }\n if (audioEngine.audioContext) {\n let listeningCamera = scene.activeCamera;\n if (scene.activeCameras && scene.activeCameras.length > 0) {\n listeningCamera = scene.activeCameras[0];\n }\n // A custom listener position provider was set\n // Use the users provided position instead of camera's\n if (this.audioListenerPositionProvider) {\n const position = this.audioListenerPositionProvider();\n // Set the listener position\n audioEngine.audioContext.listener.setPosition(position.x || 0, position.y || 0, position.z || 0);\n // Check if there is a listening camera\n }\n else if (listeningCamera) {\n // Set the listener position to the listening camera global position\n if (!this._cachedCameraPosition.equals(listeningCamera.globalPosition)) {\n this._cachedCameraPosition.copyFrom(listeningCamera.globalPosition);\n audioEngine.audioContext.listener.setPosition(listeningCamera.globalPosition.x, listeningCamera.globalPosition.y, listeningCamera.globalPosition.z);\n }\n }\n // Otherwise set the listener position to 0, 0 ,0\n else {\n // Set the listener position\n audioEngine.audioContext.listener.setPosition(0, 0, 0);\n }\n // A custom listener rotation provider was set\n // Use the users provided rotation instead of camera's\n if (this.audioListenerRotationProvider) {\n const rotation = this.audioListenerRotationProvider();\n audioEngine.audioContext.listener.setOrientation(rotation.x || 0, rotation.y || 0, rotation.z || 0, 0, 1, 0);\n // Check if there is a listening camera\n }\n else if (listeningCamera) {\n // for VR cameras\n if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {\n listeningCamera = listeningCamera.rigCameras[0];\n }\n listeningCamera.getViewMatrix().invertToRef(this._invertMatrixTemp);\n Vector3.TransformNormalToRef(AudioSceneComponent._CameraDirection, this._invertMatrixTemp, this._cameraDirectionTemp);\n this._cameraDirectionTemp.normalize();\n // To avoid some errors on GearVR\n if (!isNaN(this._cameraDirectionTemp.x) && !isNaN(this._cameraDirectionTemp.y) && !isNaN(this._cameraDirectionTemp.z)) {\n if (!this._cachedCameraDirection.equals(this._cameraDirectionTemp)) {\n this._cachedCameraDirection.copyFrom(this._cameraDirectionTemp);\n audioEngine.audioContext.listener.setOrientation(this._cameraDirectionTemp.x, this._cameraDirectionTemp.y, this._cameraDirectionTemp.z, 0, 1, 0);\n }\n }\n }\n // Otherwise set the listener rotation to 0, 0 ,0\n else {\n // Set the listener position\n audioEngine.audioContext.listener.setOrientation(0, 0, 0, 0, 1, 0);\n }\n let i;\n for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {\n const sound = scene.mainSoundTrack.soundCollection[i];\n if (sound.useCustomAttenuation) {\n sound.updateDistanceFromListener();\n }\n }\n if (scene.soundTracks) {\n for (i = 0; i < scene.soundTracks.length; i++) {\n for (let j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {\n const sound = scene.soundTracks[i].soundCollection[j];\n if (sound.useCustomAttenuation) {\n sound.updateDistanceFromListener();\n }\n }\n }\n }\n }\n }\n}\nAudioSceneComponent._CameraDirection = new Vector3(0, 0, -1);\nSound._SceneComponentInitialization = (scene) => {\n let compo = scene._getComponent(SceneComponentConstants.NAME_AUDIO);\n if (!compo) {\n compo = new AudioSceneComponent(scene);\n scene._addComponent(compo);\n }\n};\n//# sourceMappingURL=audioSceneComponent.js.map","import { Logger } from \"../Misc/logger.js\";\n/**\n * Wraps one or more Sound objects and selects one with random weight for playback.\n */\nexport class WeightedSound {\n /**\n * Creates a new WeightedSound from the list of sounds given.\n * @param loop When true a Sound will be selected and played when the current playing Sound completes.\n * @param sounds Array of Sounds that will be selected from.\n * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1\n */\n constructor(loop, sounds, weights) {\n /** When true a Sound will be selected and played when the current playing Sound completes. */\n this.loop = false;\n this._coneInnerAngle = 360;\n this._coneOuterAngle = 360;\n this._volume = 1;\n /** A Sound is currently playing. */\n this.isPlaying = false;\n /** A Sound is currently paused. */\n this.isPaused = false;\n this._sounds = [];\n this._weights = [];\n if (sounds.length !== weights.length) {\n throw new Error(\"Sounds length does not equal weights length\");\n }\n this.loop = loop;\n this._weights = weights;\n // Normalize the weights\n let weightSum = 0;\n for (const weight of weights) {\n weightSum += weight;\n }\n const invWeightSum = weightSum > 0 ? 1 / weightSum : 0;\n for (let i = 0; i < this._weights.length; i++) {\n this._weights[i] *= invWeightSum;\n }\n this._sounds = sounds;\n for (const sound of this._sounds) {\n sound.onEndedObservable.add(() => {\n this._onended();\n });\n }\n }\n /**\n * The size of cone in degrees for a directional sound in which there will be no attenuation.\n */\n get directionalConeInnerAngle() {\n return this._coneInnerAngle;\n }\n /**\n * The size of cone in degrees for a directional sound in which there will be no attenuation.\n */\n set directionalConeInnerAngle(value) {\n if (value !== this._coneInnerAngle) {\n if (this._coneOuterAngle < value) {\n Logger.Error(\"directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.\");\n return;\n }\n this._coneInnerAngle = value;\n for (const sound of this._sounds) {\n sound.directionalConeInnerAngle = value;\n }\n }\n }\n /**\n * Size of cone in degrees for a directional sound outside of which there will be no sound.\n * Listener angles between innerAngle and outerAngle will falloff linearly.\n */\n get directionalConeOuterAngle() {\n return this._coneOuterAngle;\n }\n /**\n * Size of cone in degrees for a directional sound outside of which there will be no sound.\n * Listener angles between innerAngle and outerAngle will falloff linearly.\n */\n set directionalConeOuterAngle(value) {\n if (value !== this._coneOuterAngle) {\n if (value < this._coneInnerAngle) {\n Logger.Error(\"directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.\");\n return;\n }\n this._coneOuterAngle = value;\n for (const sound of this._sounds) {\n sound.directionalConeOuterAngle = value;\n }\n }\n }\n /**\n * Playback volume.\n */\n get volume() {\n return this._volume;\n }\n /**\n * Playback volume.\n */\n set volume(value) {\n if (value !== this._volume) {\n for (const sound of this._sounds) {\n sound.setVolume(value);\n }\n }\n }\n _onended() {\n if (this._currentIndex !== undefined) {\n this._sounds[this._currentIndex].autoplay = false;\n }\n if (this.loop && this.isPlaying) {\n this.play();\n }\n else {\n this.isPlaying = false;\n }\n }\n /**\n * Suspend playback\n */\n pause() {\n this.isPaused = true;\n if (this._currentIndex !== undefined) {\n this._sounds[this._currentIndex].pause();\n }\n }\n /**\n * Stop playback\n */\n stop() {\n this.isPlaying = false;\n if (this._currentIndex !== undefined) {\n this._sounds[this._currentIndex].stop();\n }\n }\n /**\n * Start playback.\n * @param startOffset Position the clip head at a specific time in seconds.\n */\n play(startOffset) {\n if (!this.isPaused) {\n this.stop();\n const randomValue = Math.random();\n let total = 0;\n for (let i = 0; i < this._weights.length; i++) {\n total += this._weights[i];\n if (randomValue <= total) {\n this._currentIndex = i;\n break;\n }\n }\n }\n const sound = this._sounds[this._currentIndex];\n if (sound.isReady()) {\n sound.play(0, this.isPaused ? undefined : startOffset);\n }\n else {\n sound.autoplay = true;\n }\n this.isPlaying = true;\n this.isPaused = false;\n }\n}\n//# sourceMappingURL=weightedsound.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize, expandToProperty, serializeAsTexture, SerializationHelper } from \"../Misc/decorators.js\";\nimport { Vector4 } from \"../Maths/math.vector.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n/**\n * This class is used to animate meshes using a baked vertex animation texture\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/baked_texture_animations\n * @since 5.0\n */\nexport class BakedVertexAnimationManager {\n /**\n * Creates a new BakedVertexAnimationManager\n * @param scene defines the current scene\n */\n constructor(scene) {\n this._texture = null;\n this._isEnabled = true;\n /**\n * Enable or disable the vertex animation manager\n */\n this.isEnabled = true;\n /**\n * The time counter, to pick the correct animation frame.\n */\n this.time = 0;\n scene = scene || EngineStore.LastCreatedScene;\n if (!scene) {\n return;\n }\n this._scene = scene;\n this.animationParameters = new Vector4(0, 0, 0, 30);\n }\n /** @internal */\n _markSubMeshesAsAttributesDirty() {\n for (const mesh of this._scene.meshes) {\n if (mesh.bakedVertexAnimationManager === this) {\n mesh._markSubMeshesAsAttributesDirty();\n }\n }\n }\n /**\n * Binds to the effect.\n * @param effect The effect to bind to.\n * @param useInstances True when it's an instance.\n */\n bind(effect, useInstances = false) {\n if (!this._texture || !this._isEnabled) {\n return;\n }\n const size = this._texture.getSize();\n effect.setFloat2(\"bakedVertexAnimationTextureSizeInverted\", 1.0 / size.width, 1.0 / size.height);\n effect.setFloat(\"bakedVertexAnimationTime\", this.time);\n if (!useInstances) {\n effect.setVector4(\"bakedVertexAnimationSettings\", this.animationParameters);\n }\n effect.setTexture(\"bakedVertexAnimationTexture\", this._texture);\n }\n /**\n * Clone the current manager\n * @returns a new BakedVertexAnimationManager\n */\n clone() {\n const copy = new BakedVertexAnimationManager(this._scene);\n this.copyTo(copy);\n return copy;\n }\n /**\n * Sets animation parameters.\n * @param startFrame The first frame of the animation.\n * @param endFrame The last frame of the animation.\n * @param offset The offset when starting the animation.\n * @param speedFramesPerSecond The frame rate.\n */\n setAnimationParameters(startFrame, endFrame, offset = 0, speedFramesPerSecond = 30) {\n this.animationParameters = new Vector4(startFrame, endFrame, offset, speedFramesPerSecond);\n }\n /**\n * Disposes the resources of the manager.\n * @param forceDisposeTextures - Forces the disposal of all textures.\n */\n dispose(forceDisposeTextures) {\n var _a;\n if (forceDisposeTextures) {\n (_a = this._texture) === null || _a === void 0 ? void 0 : _a.dispose();\n }\n }\n /**\n * Get the current class name useful for serialization or dynamic coding.\n * @returns \"BakedVertexAnimationManager\"\n */\n getClassName() {\n return \"BakedVertexAnimationManager\";\n }\n /**\n * Makes a duplicate of the current instance into another one.\n * @param vatMap define the instance where to copy the info\n */\n copyTo(vatMap) {\n SerializationHelper.Clone(() => vatMap, this);\n }\n /**\n * Serializes this vertex animation instance\n * @returns - An object with the serialized instance.\n */\n serialize() {\n return SerializationHelper.Serialize(this);\n }\n /**\n * Parses a vertex animation setting from a serialized object.\n * @param source - Serialized object.\n * @param scene Defines the scene we are parsing for\n * @param rootUrl Defines the rootUrl to load from\n */\n parse(source, scene, rootUrl) {\n SerializationHelper.Parse(() => this, source, scene, rootUrl);\n }\n}\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markSubMeshesAsAttributesDirty\")\n], BakedVertexAnimationManager.prototype, \"texture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markSubMeshesAsAttributesDirty\")\n], BakedVertexAnimationManager.prototype, \"isEnabled\", void 0);\n__decorate([\n serialize()\n], BakedVertexAnimationManager.prototype, \"animationParameters\", void 0);\n__decorate([\n serialize()\n], BakedVertexAnimationManager.prototype, \"time\", void 0);\n//# sourceMappingURL=bakedVertexAnimationManager.js.map","\nimport { Size } from \"../../Maths/math.size.js\";\n/**\n * Base class of all the textures in babylon.\n * It groups all the common properties required to work with Thin Engine.\n */\nexport class ThinTexture {\n /**\n * | Value | Type | Description |\n * | ----- | ------------------ | ----------- |\n * | 0 | CLAMP_ADDRESSMODE | |\n * | 1 | WRAP_ADDRESSMODE | |\n * | 2 | MIRROR_ADDRESSMODE | |\n */\n get wrapU() {\n return this._wrapU;\n }\n set wrapU(value) {\n this._wrapU = value;\n }\n /**\n * | Value | Type | Description |\n * | ----- | ------------------ | ----------- |\n * | 0 | CLAMP_ADDRESSMODE | |\n * | 1 | WRAP_ADDRESSMODE | |\n * | 2 | MIRROR_ADDRESSMODE | |\n */\n get wrapV() {\n return this._wrapV;\n }\n set wrapV(value) {\n this._wrapV = value;\n }\n /**\n * How a texture is mapped.\n * Unused in thin texture mode.\n */\n get coordinatesMode() {\n return 0;\n }\n /**\n * Define if the texture is a cube texture or if false a 2d texture.\n */\n get isCube() {\n if (!this._texture) {\n return false;\n }\n return this._texture.isCube;\n }\n set isCube(value) {\n if (!this._texture) {\n return;\n }\n this._texture.isCube = value;\n }\n /**\n * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.\n */\n get is3D() {\n if (!this._texture) {\n return false;\n }\n return this._texture.is3D;\n }\n set is3D(value) {\n if (!this._texture) {\n return;\n }\n this._texture.is3D = value;\n }\n /**\n * Define if the texture is a 2d array texture (webgl 2) or if false a 2d texture.\n */\n get is2DArray() {\n if (!this._texture) {\n return false;\n }\n return this._texture.is2DArray;\n }\n set is2DArray(value) {\n if (!this._texture) {\n return;\n }\n this._texture.is2DArray = value;\n }\n /**\n * Get the class name of the texture.\n * @returns \"ThinTexture\"\n */\n getClassName() {\n return \"ThinTexture\";\n }\n static _IsRenderTargetWrapper(texture) {\n return (texture === null || texture === void 0 ? void 0 : texture._shareDepth) !== undefined;\n }\n /**\n * Instantiates a new ThinTexture.\n * Base class of all the textures in babylon.\n * This can be used as an internal texture wrapper in ThinEngine to benefit from the cache\n * @param internalTexture Define the internalTexture to wrap. You can also pass a RenderTargetWrapper, in which case the texture will be the render target's texture\n */\n constructor(internalTexture) {\n this._wrapU = 1;\n this._wrapV = 1;\n /**\n * | Value | Type | Description |\n * | ----- | ------------------ | ----------- |\n * | 0 | CLAMP_ADDRESSMODE | |\n * | 1 | WRAP_ADDRESSMODE | |\n * | 2 | MIRROR_ADDRESSMODE | |\n */\n this.wrapR = 1;\n /**\n * With compliant hardware and browser (supporting anisotropic filtering)\n * this defines the level of anisotropic filtering in the texture.\n * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.\n */\n this.anisotropicFilteringLevel = 4;\n /**\n * Define the current state of the loading sequence when in delayed load mode.\n */\n this.delayLoadState = 0;\n /** @internal */\n this._texture = null;\n this._engine = null;\n this._cachedSize = Size.Zero();\n this._cachedBaseSize = Size.Zero();\n /** @internal */\n this._initialSamplingMode = 2;\n this._texture = ThinTexture._IsRenderTargetWrapper(internalTexture) ? internalTexture.texture : internalTexture;\n if (this._texture) {\n this._engine = this._texture.getEngine();\n }\n }\n /**\n * Get if the texture is ready to be used (downloaded, converted, mip mapped...).\n * @returns true if fully ready\n */\n isReady() {\n if (this.delayLoadState === 4) {\n this.delayLoad();\n return false;\n }\n if (this._texture) {\n return this._texture.isReady;\n }\n return false;\n }\n /**\n * Triggers the load sequence in delayed load mode.\n */\n delayLoad() { }\n /**\n * Get the underlying lower level texture from Babylon.\n * @returns the internal texture\n */\n getInternalTexture() {\n return this._texture;\n }\n /**\n * Get the size of the texture.\n * @returns the texture size.\n */\n getSize() {\n if (this._texture) {\n if (this._texture.width) {\n this._cachedSize.width = this._texture.width;\n this._cachedSize.height = this._texture.height;\n return this._cachedSize;\n }\n if (this._texture._size) {\n this._cachedSize.width = this._texture._size;\n this._cachedSize.height = this._texture._size;\n return this._cachedSize;\n }\n }\n return this._cachedSize;\n }\n /**\n * Get the base size of the texture.\n * It can be different from the size if the texture has been resized for POT for instance\n * @returns the base size\n */\n getBaseSize() {\n if (!this.isReady() || !this._texture) {\n this._cachedBaseSize.width = 0;\n this._cachedBaseSize.height = 0;\n return this._cachedBaseSize;\n }\n if (this._texture._size) {\n this._cachedBaseSize.width = this._texture._size;\n this._cachedBaseSize.height = this._texture._size;\n return this._cachedBaseSize;\n }\n this._cachedBaseSize.width = this._texture.baseWidth;\n this._cachedBaseSize.height = this._texture.baseHeight;\n return this._cachedBaseSize;\n }\n /**\n * Get the current sampling mode associated with the texture.\n */\n get samplingMode() {\n if (!this._texture) {\n return this._initialSamplingMode;\n }\n return this._texture.samplingMode;\n }\n /**\n * Update the sampling mode of the texture.\n * Default is Trilinear mode.\n *\n * | Value | Type | Description |\n * | ----- | ------------------ | ----------- |\n * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |\n * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |\n * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |\n * | 4 | NEAREST_NEAREST_MIPNEAREST | |\n * | 5 | NEAREST_LINEAR_MIPNEAREST | |\n * | 6 | NEAREST_LINEAR_MIPLINEAR | |\n * | 7 | NEAREST_LINEAR | |\n * | 8 | NEAREST_NEAREST | |\n * | 9 | LINEAR_NEAREST_MIPNEAREST | |\n * | 10 | LINEAR_NEAREST_MIPLINEAR | |\n * | 11 | LINEAR_LINEAR | |\n * | 12 | LINEAR_NEAREST | |\n *\n * > _mag_: magnification filter (close to the viewer)\n * > _min_: minification filter (far from the viewer)\n * > _mip_: filter used between mip map levels\n *@param samplingMode Define the new sampling mode of the texture\n */\n updateSamplingMode(samplingMode) {\n if (this._texture && this._engine) {\n this._engine.updateTextureSamplingMode(samplingMode, this._texture);\n }\n }\n /**\n * Release and destroy the underlying lower level texture aka internalTexture.\n */\n releaseInternalTexture() {\n if (this._texture) {\n this._texture.dispose();\n this._texture = null;\n }\n }\n /**\n * Dispose the texture and release its associated resources.\n */\n dispose() {\n if (this._texture) {\n this.releaseInternalTexture();\n this._engine = null;\n }\n }\n}\n//# sourceMappingURL=thinTexture.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize, SerializationHelper, serializeAsTexture } from \"../../Misc/decorators.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { Matrix } from \"../../Maths/math.vector.js\";\nimport { EngineStore } from \"../../Engines/engineStore.js\";\n\nimport { RandomGUID } from \"../../Misc/guid.js\";\nimport \"../../Misc/fileTools.js\";\nimport { ThinTexture } from \"./thinTexture.js\";\n/**\n * Base class of all the textures in babylon.\n * It groups all the common properties the materials, post process, lights... might need\n * in order to make a correct use of the texture.\n */\nexport class BaseTexture extends ThinTexture {\n /**\n * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance).\n */\n set hasAlpha(value) {\n if (this._hasAlpha === value) {\n return;\n }\n this._hasAlpha = value;\n if (this._scene) {\n this._scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(this);\n });\n }\n }\n get hasAlpha() {\n return this._hasAlpha;\n }\n /**\n * Defines if the alpha value should be determined via the rgb values.\n * If true the luminance of the pixel might be used to find the corresponding alpha value.\n */\n set getAlphaFromRGB(value) {\n if (this._getAlphaFromRGB === value) {\n return;\n }\n this._getAlphaFromRGB = value;\n if (this._scene) {\n this._scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(this);\n });\n }\n }\n get getAlphaFromRGB() {\n return this._getAlphaFromRGB;\n }\n /**\n * Define the UV channel to use starting from 0 and defaulting to 0.\n * This is part of the texture as textures usually maps to one uv set.\n */\n set coordinatesIndex(value) {\n if (this._coordinatesIndex === value) {\n return;\n }\n this._coordinatesIndex = value;\n if (this._scene) {\n this._scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(this);\n });\n }\n }\n get coordinatesIndex() {\n return this._coordinatesIndex;\n }\n /**\n * How a texture is mapped.\n *\n * | Value | Type | Description |\n * | ----- | ----------------------------------- | ----------- |\n * | 0 | EXPLICIT_MODE | |\n * | 1 | SPHERICAL_MODE | |\n * | 2 | PLANAR_MODE | |\n * | 3 | CUBIC_MODE | |\n * | 4 | PROJECTION_MODE | |\n * | 5 | SKYBOX_MODE | |\n * | 6 | INVCUBIC_MODE | |\n * | 7 | EQUIRECTANGULAR_MODE | |\n * | 8 | FIXED_EQUIRECTANGULAR_MODE | |\n * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |\n */\n set coordinatesMode(value) {\n if (this._coordinatesMode === value) {\n return;\n }\n this._coordinatesMode = value;\n if (this._scene) {\n this._scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(this);\n });\n }\n }\n get coordinatesMode() {\n return this._coordinatesMode;\n }\n /**\n * | Value | Type | Description |\n * | ----- | ------------------ | ----------- |\n * | 0 | CLAMP_ADDRESSMODE | |\n * | 1 | WRAP_ADDRESSMODE | |\n * | 2 | MIRROR_ADDRESSMODE | |\n */\n get wrapU() {\n return this._wrapU;\n }\n set wrapU(value) {\n this._wrapU = value;\n }\n /**\n * | Value | Type | Description |\n * | ----- | ------------------ | ----------- |\n * | 0 | CLAMP_ADDRESSMODE | |\n * | 1 | WRAP_ADDRESSMODE | |\n * | 2 | MIRROR_ADDRESSMODE | |\n */\n get wrapV() {\n return this._wrapV;\n }\n set wrapV(value) {\n this._wrapV = value;\n }\n /**\n * Define if the texture is a cube texture or if false a 2d texture.\n */\n get isCube() {\n if (!this._texture) {\n return this._isCube;\n }\n return this._texture.isCube;\n }\n set isCube(value) {\n if (!this._texture) {\n this._isCube = value;\n }\n else {\n this._texture.isCube = value;\n }\n }\n /**\n * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.\n */\n get is3D() {\n if (!this._texture) {\n return false;\n }\n return this._texture.is3D;\n }\n set is3D(value) {\n if (!this._texture) {\n return;\n }\n this._texture.is3D = value;\n }\n /**\n * Define if the texture is a 2d array texture (webgl 2) or if false a 2d texture.\n */\n get is2DArray() {\n if (!this._texture) {\n return false;\n }\n return this._texture.is2DArray;\n }\n set is2DArray(value) {\n if (!this._texture) {\n return;\n }\n this._texture.is2DArray = value;\n }\n /**\n * Define if the texture contains data in gamma space (most of the png/jpg aside bump).\n * HDR texture are usually stored in linear space.\n * This only impacts the PBR and Background materials\n */\n get gammaSpace() {\n if (!this._texture) {\n return this._gammaSpace;\n }\n else {\n if (this._texture._gammaSpace === null) {\n this._texture._gammaSpace = this._gammaSpace;\n }\n }\n return this._texture._gammaSpace && !this._texture._useSRGBBuffer;\n }\n set gammaSpace(gamma) {\n if (!this._texture) {\n if (this._gammaSpace === gamma) {\n return;\n }\n this._gammaSpace = gamma;\n }\n else {\n if (this._texture._gammaSpace === gamma) {\n return;\n }\n this._texture._gammaSpace = gamma;\n }\n this._markAllSubMeshesAsTexturesDirty();\n }\n /**\n * Gets or sets whether or not the texture contains RGBD data.\n */\n get isRGBD() {\n return this._texture != null && this._texture._isRGBD;\n }\n set isRGBD(value) {\n if (this._texture) {\n this._texture._isRGBD = value;\n }\n }\n /**\n * Are mip maps generated for this texture or not.\n */\n get noMipmap() {\n return false;\n }\n /**\n * With prefiltered texture, defined the offset used during the prefiltering steps.\n */\n get lodGenerationOffset() {\n if (this._texture) {\n return this._texture._lodGenerationOffset;\n }\n return 0.0;\n }\n set lodGenerationOffset(value) {\n if (this._texture) {\n this._texture._lodGenerationOffset = value;\n }\n }\n /**\n * With prefiltered texture, defined the scale used during the prefiltering steps.\n */\n get lodGenerationScale() {\n if (this._texture) {\n return this._texture._lodGenerationScale;\n }\n return 0.0;\n }\n set lodGenerationScale(value) {\n if (this._texture) {\n this._texture._lodGenerationScale = value;\n }\n }\n /**\n * With prefiltered texture, defined if the specular generation is based on a linear ramp.\n * By default we are using a log2 of the linear roughness helping to keep a better resolution for\n * average roughness values.\n */\n get linearSpecularLOD() {\n if (this._texture) {\n return this._texture._linearSpecularLOD;\n }\n return false;\n }\n set linearSpecularLOD(value) {\n if (this._texture) {\n this._texture._linearSpecularLOD = value;\n }\n }\n /**\n * In case a better definition than spherical harmonics is required for the diffuse part of the environment.\n * You can set the irradiance texture to rely on a texture instead of the spherical approach.\n * This texture need to have the same characteristics than its parent (Cube vs 2d, coordinates mode, Gamma/Linear, RGBD).\n */\n get irradianceTexture() {\n if (this._texture) {\n return this._texture._irradianceTexture;\n }\n return null;\n }\n set irradianceTexture(value) {\n if (this._texture) {\n this._texture._irradianceTexture = value;\n }\n }\n /**\n * Define the unique id of the texture in the scene.\n */\n get uid() {\n if (!this._uid) {\n this._uid = RandomGUID();\n }\n return this._uid;\n }\n /**\n * Return a string representation of the texture.\n * @returns the texture as a string\n */\n toString() {\n return this.name;\n }\n /**\n * Get the class name of the texture.\n * @returns \"BaseTexture\"\n */\n getClassName() {\n return \"BaseTexture\";\n }\n /**\n * Callback triggered when the texture has been disposed.\n * Kept for back compatibility, you can use the onDisposeObservable instead.\n */\n set onDispose(callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n }\n /**\n * Define if the texture is preventing a material to render or not.\n * If not and the texture is not ready, the engine will use a default black texture instead.\n */\n get isBlocking() {\n return true;\n }\n /**\n * Was there any loading error?\n */\n get loadingError() {\n return this._loadingError;\n }\n /**\n * If a loading error occurred this object will be populated with information about the error.\n */\n get errorObject() {\n return this._errorObject;\n }\n /**\n * Instantiates a new BaseTexture.\n * Base class of all the textures in babylon.\n * It groups all the common properties the materials, post process, lights... might need\n * in order to make a correct use of the texture.\n * @param sceneOrEngine Define the scene or engine the texture belongs to\n * @param internalTexture Define the internal texture associated with the texture\n */\n constructor(sceneOrEngine, internalTexture = null) {\n super(null);\n /**\n * Gets or sets an object used to store user defined information.\n */\n this.metadata = null;\n /**\n * For internal use only. Please do not use.\n */\n this.reservedDataStore = null;\n this._hasAlpha = false;\n this._getAlphaFromRGB = false;\n /**\n * Intensity or strength of the texture.\n * It is commonly used by materials to fine tune the intensity of the texture\n */\n this.level = 1;\n this._coordinatesIndex = 0;\n /**\n * Gets or sets a boolean indicating that the texture should try to reduce shader code if there is no UV manipulation.\n * (ie. when texture.getTextureMatrix().isIdentityAs3x2() returns true)\n */\n this.optimizeUVAllocation = true;\n this._coordinatesMode = 0;\n /**\n * | Value | Type | Description |\n * | ----- | ------------------ | ----------- |\n * | 0 | CLAMP_ADDRESSMODE | |\n * | 1 | WRAP_ADDRESSMODE | |\n * | 2 | MIRROR_ADDRESSMODE | |\n */\n this.wrapR = 1;\n /**\n * With compliant hardware and browser (supporting anisotropic filtering)\n * this defines the level of anisotropic filtering in the texture.\n * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.\n */\n this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;\n /** @internal */\n this._isCube = false;\n this._gammaSpace = true;\n /**\n * Is Z inverted in the texture (useful in a cube texture).\n */\n this.invertZ = false;\n /**\n * @internal\n */\n this.lodLevelInAlpha = false;\n /**\n * Define if the texture is a render target.\n */\n this.isRenderTarget = false;\n /** @internal */\n this._prefiltered = false;\n /** @internal */\n this._forceSerialize = false;\n /**\n * Define the list of animation attached to the texture.\n */\n this.animations = new Array();\n /**\n * An event triggered when the texture is disposed.\n */\n this.onDisposeObservable = new Observable();\n this._onDisposeObserver = null;\n this._scene = null;\n /** @internal */\n this._uid = null;\n /** @internal */\n this._parentContainer = null;\n this._loadingError = false;\n if (sceneOrEngine) {\n if (BaseTexture._IsScene(sceneOrEngine)) {\n this._scene = sceneOrEngine;\n }\n else {\n this._engine = sceneOrEngine;\n }\n }\n else {\n this._scene = EngineStore.LastCreatedScene;\n }\n if (this._scene) {\n this.uniqueId = this._scene.getUniqueId();\n this._scene.addTexture(this);\n this._engine = this._scene.getEngine();\n }\n this._texture = internalTexture;\n this._uid = null;\n }\n /**\n * Get the scene the texture belongs to.\n * @returns the scene or null if undefined\n */\n getScene() {\n return this._scene;\n }\n /** @internal */\n _getEngine() {\n return this._engine;\n }\n /**\n * Checks if the texture has the same transform matrix than another texture\n * @param texture texture to check against\n * @returns true if the transforms are the same, else false\n */\n checkTransformsAreIdentical(texture) {\n return texture !== null;\n }\n /**\n * Get the texture transform matrix used to offset tile the texture for instance.\n * @returns the transformation matrix\n */\n getTextureMatrix() {\n return Matrix.IdentityReadOnly;\n }\n /**\n * Get the texture reflection matrix used to rotate/transform the reflection.\n * @returns the reflection matrix\n */\n getReflectionTextureMatrix() {\n return Matrix.IdentityReadOnly;\n }\n /**\n * Gets a suitable rotate/transform matrix when the texture is used for refraction.\n * There's a separate function from getReflectionTextureMatrix because refraction requires a special configuration of the matrix in right-handed mode.\n * @returns The refraction matrix\n */\n getRefractionTextureMatrix() {\n return this.getReflectionTextureMatrix();\n }\n /**\n * Get if the texture is ready to be consumed (either it is ready or it is not blocking)\n * @returns true if ready, not blocking or if there was an error loading the texture\n */\n isReadyOrNotBlocking() {\n return !this.isBlocking || this.isReady() || this.loadingError;\n }\n /**\n * Scales the texture if is `canRescale()`\n * @param ratio the resize factor we want to use to rescale\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n scale(ratio) { }\n /**\n * Get if the texture can rescale.\n */\n get canRescale() {\n return false;\n }\n /**\n * @internal\n */\n _getFromCache(url, noMipmap, sampling, invertY, useSRGBBuffer, isCube) {\n const engine = this._getEngine();\n if (!engine) {\n return null;\n }\n const correctedUseSRGBBuffer = engine._getUseSRGBBuffer(!!useSRGBBuffer, noMipmap);\n const texturesCache = engine.getLoadedTexturesCache();\n for (let index = 0; index < texturesCache.length; index++) {\n const texturesCacheEntry = texturesCache[index];\n if (useSRGBBuffer === undefined || correctedUseSRGBBuffer === texturesCacheEntry._useSRGBBuffer) {\n if (invertY === undefined || invertY === texturesCacheEntry.invertY) {\n if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {\n if (!sampling || sampling === texturesCacheEntry.samplingMode) {\n if (isCube === undefined || isCube === texturesCacheEntry.isCube) {\n texturesCacheEntry.incrementReferences();\n return texturesCacheEntry;\n }\n }\n }\n }\n }\n }\n return null;\n }\n /** @internal */\n _rebuild() { }\n /**\n * Clones the texture.\n * @returns the cloned texture\n */\n clone() {\n return null;\n }\n /**\n * Get the texture underlying type (INT, FLOAT...)\n */\n get textureType() {\n if (!this._texture) {\n return 0;\n }\n return this._texture.type !== undefined ? this._texture.type : 0;\n }\n /**\n * Get the texture underlying format (RGB, RGBA...)\n */\n get textureFormat() {\n if (!this._texture) {\n return 5;\n }\n return this._texture.format !== undefined ? this._texture.format : 5;\n }\n /**\n * Indicates that textures need to be re-calculated for all materials\n */\n _markAllSubMeshesAsTexturesDirty() {\n const scene = this.getScene();\n if (!scene) {\n return;\n }\n scene.markAllMaterialsAsDirty(1);\n }\n /**\n * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.\n * This will returns an RGBA array buffer containing either in values (0-255) or\n * float values (0-1) depending of the underlying buffer type.\n * @param faceIndex defines the face of the texture to read (in case of cube texture)\n * @param level defines the LOD level of the texture to read (in case of Mip Maps)\n * @param buffer defines a user defined buffer to fill with data (can be null)\n * @param flushRenderer true to flush the renderer from the pending commands before reading the pixels\n * @param noDataConversion false to convert the data to Uint8Array (if texture type is UNSIGNED_BYTE) or to Float32Array (if texture type is anything but UNSIGNED_BYTE). If true, the type of the generated buffer (if buffer==null) will depend on the type of the texture\n * @param x defines the region x coordinates to start reading from (default to 0)\n * @param y defines the region y coordinates to start reading from (default to 0)\n * @param width defines the region width to read from (default to the texture size at level)\n * @param height defines the region width to read from (default to the texture size at level)\n * @returns The Array buffer promise containing the pixels data.\n */\n readPixels(faceIndex = 0, level = 0, buffer = null, flushRenderer = true, noDataConversion = false, x = 0, y = 0, width = Number.MAX_VALUE, height = Number.MAX_VALUE) {\n if (!this._texture) {\n return null;\n }\n const engine = this._getEngine();\n if (!engine) {\n return null;\n }\n const size = this.getSize();\n let maxWidth = size.width;\n let maxHeight = size.height;\n if (level !== 0) {\n maxWidth = maxWidth / Math.pow(2, level);\n maxHeight = maxHeight / Math.pow(2, level);\n maxWidth = Math.round(maxWidth);\n maxHeight = Math.round(maxHeight);\n }\n width = Math.min(maxWidth, width);\n height = Math.min(maxHeight, height);\n try {\n if (this._texture.isCube) {\n return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer, flushRenderer, noDataConversion, x, y);\n }\n return engine._readTexturePixels(this._texture, width, height, -1, level, buffer, flushRenderer, noDataConversion, x, y);\n }\n catch (e) {\n return null;\n }\n }\n /**\n * @internal\n */\n _readPixelsSync(faceIndex = 0, level = 0, buffer = null, flushRenderer = true, noDataConversion = false) {\n if (!this._texture) {\n return null;\n }\n const size = this.getSize();\n let width = size.width;\n let height = size.height;\n const engine = this._getEngine();\n if (!engine) {\n return null;\n }\n if (level != 0) {\n width = width / Math.pow(2, level);\n height = height / Math.pow(2, level);\n width = Math.round(width);\n height = Math.round(height);\n }\n try {\n if (this._texture.isCube) {\n return engine._readTexturePixelsSync(this._texture, width, height, faceIndex, level, buffer, flushRenderer, noDataConversion);\n }\n return engine._readTexturePixelsSync(this._texture, width, height, -1, level, buffer, flushRenderer, noDataConversion);\n }\n catch (e) {\n return null;\n }\n }\n /** @internal */\n get _lodTextureHigh() {\n if (this._texture) {\n return this._texture._lodTextureHigh;\n }\n return null;\n }\n /** @internal */\n get _lodTextureMid() {\n if (this._texture) {\n return this._texture._lodTextureMid;\n }\n return null;\n }\n /** @internal */\n get _lodTextureLow() {\n if (this._texture) {\n return this._texture._lodTextureLow;\n }\n return null;\n }\n /**\n * Dispose the texture and release its associated resources.\n */\n dispose() {\n if (this._scene) {\n // Animations\n if (this._scene.stopAnimation) {\n this._scene.stopAnimation(this);\n }\n // Remove from scene\n this._scene.removePendingData(this);\n const index = this._scene.textures.indexOf(this);\n if (index >= 0) {\n this._scene.textures.splice(index, 1);\n }\n this._scene.onTextureRemovedObservable.notifyObservers(this);\n this._scene = null;\n if (this._parentContainer) {\n const index = this._parentContainer.textures.indexOf(this);\n if (index > -1) {\n this._parentContainer.textures.splice(index, 1);\n }\n this._parentContainer = null;\n }\n }\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n this.metadata = null;\n super.dispose();\n }\n /**\n * Serialize the texture into a JSON representation that can be parsed later on.\n * @param allowEmptyName True to force serialization even if name is empty. Default: false\n * @returns the JSON representation of the texture\n */\n serialize(allowEmptyName = false) {\n if (!this.name && !allowEmptyName) {\n return null;\n }\n const serializationObject = SerializationHelper.Serialize(this);\n // Animations\n SerializationHelper.AppendSerializedAnimations(this, serializationObject);\n return serializationObject;\n }\n /**\n * Helper function to be called back once a list of texture contains only ready textures.\n * @param textures Define the list of textures to wait for\n * @param callback Define the callback triggered once the entire list will be ready\n */\n static WhenAllReady(textures, callback) {\n let numRemaining = textures.length;\n if (numRemaining === 0) {\n callback();\n return;\n }\n for (let i = 0; i < textures.length; i++) {\n const texture = textures[i];\n if (texture.isReady()) {\n if (--numRemaining === 0) {\n callback();\n }\n }\n else {\n const onLoadObservable = texture.onLoadObservable;\n if (onLoadObservable) {\n onLoadObservable.addOnce(() => {\n if (--numRemaining === 0) {\n callback();\n }\n });\n }\n else {\n if (--numRemaining === 0) {\n callback();\n }\n }\n }\n }\n }\n static _IsScene(sceneOrEngine) {\n return sceneOrEngine.getClassName() === \"Scene\";\n }\n}\n/**\n * Default anisotropic filtering level for the application.\n * It is set to 4 as a good tradeoff between perf and quality.\n */\nBaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;\n__decorate([\n serialize()\n], BaseTexture.prototype, \"uniqueId\", void 0);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"name\", void 0);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"metadata\", void 0);\n__decorate([\n serialize(\"hasAlpha\")\n], BaseTexture.prototype, \"_hasAlpha\", void 0);\n__decorate([\n serialize(\"getAlphaFromRGB\")\n], BaseTexture.prototype, \"_getAlphaFromRGB\", void 0);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"level\", void 0);\n__decorate([\n serialize(\"coordinatesIndex\")\n], BaseTexture.prototype, \"_coordinatesIndex\", void 0);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"optimizeUVAllocation\", void 0);\n__decorate([\n serialize(\"coordinatesMode\")\n], BaseTexture.prototype, \"_coordinatesMode\", void 0);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"wrapU\", null);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"wrapV\", null);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"wrapR\", void 0);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"anisotropicFilteringLevel\", void 0);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"isCube\", null);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"is3D\", null);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"is2DArray\", null);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"gammaSpace\", null);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"invertZ\", void 0);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"lodLevelInAlpha\", void 0);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"lodGenerationOffset\", null);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"lodGenerationScale\", null);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"linearSpecularLOD\", null);\n__decorate([\n serializeAsTexture()\n], BaseTexture.prototype, \"irradianceTexture\", null);\n__decorate([\n serialize()\n], BaseTexture.prototype, \"isRenderTarget\", void 0);\n//# sourceMappingURL=baseTexture.js.map","/**\n * Transform some pixel data to a base64 string\n * @param pixels defines the pixel data to transform to base64\n * @param size defines the width and height of the (texture) data\n * @param invertY true if the data must be inverted for the Y coordinate during the conversion\n * @returns The base64 encoded string or null\n */\nexport function GenerateBase64StringFromPixelData(pixels, size, invertY = false) {\n const width = size.width;\n const height = size.height;\n if (pixels instanceof Float32Array) {\n let len = pixels.byteLength / pixels.BYTES_PER_ELEMENT;\n const npixels = new Uint8Array(len);\n while (--len >= 0) {\n let val = pixels[len];\n if (val < 0) {\n val = 0;\n }\n else if (val > 1) {\n val = 1;\n }\n npixels[len] = val * 255;\n }\n pixels = npixels;\n }\n const canvas = document.createElement(\"canvas\");\n canvas.width = width;\n canvas.height = height;\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) {\n return null;\n }\n const imageData = ctx.createImageData(width, height);\n const castData = imageData.data;\n castData.set(pixels);\n ctx.putImageData(imageData, 0, 0);\n if (invertY) {\n const canvas2 = document.createElement(\"canvas\");\n canvas2.width = width;\n canvas2.height = height;\n const ctx2 = canvas2.getContext(\"2d\");\n if (!ctx2) {\n return null;\n }\n ctx2.translate(0, height);\n ctx2.scale(1, -1);\n ctx2.drawImage(canvas, 0, 0);\n return canvas2.toDataURL(\"image/png\");\n }\n return canvas.toDataURL(\"image/png\");\n}\n/**\n * Reads the pixels stored in the webgl texture and returns them as a base64 string\n * @param texture defines the texture to read pixels from\n * @param faceIndex defines the face of the texture to read (in case of cube texture)\n * @param level defines the LOD level of the texture to read (in case of Mip Maps)\n * @returns The base64 encoded string or null\n */\nexport function GenerateBase64StringFromTexture(texture, faceIndex = 0, level = 0) {\n const internalTexture = texture.getInternalTexture();\n if (!internalTexture) {\n return null;\n }\n const pixels = texture._readPixelsSync(faceIndex, level);\n if (!pixels) {\n return null;\n }\n return GenerateBase64StringFromPixelData(pixels, texture.getSize(), internalTexture.invertY);\n}\n/**\n * Reads the pixels stored in the webgl texture and returns them as a base64 string\n * @param texture defines the texture to read pixels from\n * @param faceIndex defines the face of the texture to read (in case of cube texture)\n * @param level defines the LOD level of the texture to read (in case of Mip Maps)\n * @returns The base64 encoded string or null wrapped in a promise\n */\nexport async function GenerateBase64StringFromTextureAsync(texture, faceIndex = 0, level = 0) {\n const internalTexture = texture.getInternalTexture();\n if (!internalTexture) {\n return null;\n }\n const pixels = await texture.readPixels(faceIndex, level);\n if (!pixels) {\n return null;\n }\n return GenerateBase64StringFromPixelData(pixels, texture.getSize(), internalTexture.invertY);\n}\n/**\n * Class used to host copy specific utilities\n * (Back-compat)\n */\nexport const CopyTools = {\n /**\n * Transform some pixel data to a base64 string\n * @param pixels defines the pixel data to transform to base64\n * @param size defines the width and height of the (texture) data\n * @param invertY true if the data must be inverted for the Y coordinate during the conversion\n * @returns The base64 encoded string or null\n */\n GenerateBase64StringFromPixelData,\n /**\n * Reads the pixels stored in the webgl texture and returns them as a base64 string\n * @param texture defines the texture to read pixels from\n * @param faceIndex defines the face of the texture to read (in case of cube texture)\n * @param level defines the LOD level of the texture to read (in case of Mip Maps)\n * @returns The base64 encoded string or null\n */\n GenerateBase64StringFromTexture,\n /**\n * Reads the pixels stored in the webgl texture and returns them as a base64 string\n * @param texture defines the texture to read pixels from\n * @param faceIndex defines the face of the texture to read (in case of cube texture)\n * @param level defines the LOD level of the texture to read (in case of Mip Maps)\n * @returns The base64 encoded string or null wrapped in a promise\n */\n GenerateBase64StringFromTextureAsync,\n};\n//# sourceMappingURL=copyTools.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize, SerializationHelper } from \"../../Misc/decorators.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { Matrix, TmpVectors, Vector3 } from \"../../Maths/math.vector.js\";\nimport { BaseTexture } from \"../../Materials/Textures/baseTexture.js\";\n\nimport { GetClass, RegisterClass } from \"../../Misc/typeStore.js\";\nimport { _WarnImport } from \"../../Misc/devTools.js\";\nimport { TimingTools } from \"../../Misc/timingTools.js\";\nimport { InstantiationTools } from \"../../Misc/instantiationTools.js\";\nimport { Plane } from \"../../Maths/math.plane.js\";\nimport { EncodeArrayBufferToBase64 } from \"../../Misc/stringTools.js\";\nimport { GenerateBase64StringFromTexture, GenerateBase64StringFromTextureAsync } from \"../../Misc/copyTools.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n/**\n * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction#texture\n */\nexport class Texture extends BaseTexture {\n /**\n * Are mip maps generated for this texture or not.\n */\n get noMipmap() {\n return this._noMipmap;\n }\n /** Returns the texture mime type if it was defined by a loader (undefined else) */\n get mimeType() {\n return this._mimeType;\n }\n /**\n * Is the texture preventing material to render while loading.\n * If false, a default texture will be used instead of the loading one during the preparation step.\n */\n set isBlocking(value) {\n this._isBlocking = value;\n }\n get isBlocking() {\n return this._isBlocking;\n }\n /**\n * Gets a boolean indicating if the texture needs to be inverted on the y axis during loading\n */\n get invertY() {\n return this._invertY;\n }\n /**\n * Instantiates a new texture.\n * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction#texture\n * @param url defines the url of the picture to load as a texture\n * @param sceneOrEngine defines the scene or engine the texture will belong to\n * @param noMipmapOrOptions defines if the texture will require mip maps or not or set of all options to create the texture\n * @param invertY defines if the texture needs to be inverted on the y axis during loading\n * @param samplingMode defines the sampling mode we want for the texture while fetching from it (Texture.NEAREST_SAMPLINGMODE...)\n * @param onLoad defines a callback triggered when the texture has been loaded\n * @param onError defines a callback triggered when an error occurred during the loading session\n * @param buffer defines the buffer to load the texture from in case the texture is loaded from a buffer representation\n * @param deleteBuffer defines if the buffer we are loading the texture from should be deleted after load\n * @param format defines the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)\n * @param mimeType defines an optional mime type information\n * @param loaderOptions options to be passed to the loader\n * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)\n * @param forcedExtension defines the extension to use to pick the right loader\n */\n constructor(url, sceneOrEngine, noMipmapOrOptions, invertY, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, onLoad = null, onError = null, buffer = null, deleteBuffer = false, format, mimeType, loaderOptions, creationFlags, forcedExtension) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j;\n super(sceneOrEngine);\n /**\n * Define the url of the texture.\n */\n this.url = null;\n /**\n * Define an offset on the texture to offset the u coordinates of the UVs\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials#offsetting\n */\n this.uOffset = 0;\n /**\n * Define an offset on the texture to offset the v coordinates of the UVs\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials#offsetting\n */\n this.vOffset = 0;\n /**\n * Define an offset on the texture to scale the u coordinates of the UVs\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials#tiling\n */\n this.uScale = 1.0;\n /**\n * Define an offset on the texture to scale the v coordinates of the UVs\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials#tiling\n */\n this.vScale = 1.0;\n /**\n * Define an offset on the texture to rotate around the u coordinates of the UVs\n * The angle is defined in radians.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials\n */\n this.uAng = 0;\n /**\n * Define an offset on the texture to rotate around the v coordinates of the UVs\n * The angle is defined in radians.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials\n */\n this.vAng = 0;\n /**\n * Define an offset on the texture to rotate around the w coordinates of the UVs (in case of 3d texture)\n * The angle is defined in radians.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/moreMaterials\n */\n this.wAng = 0;\n /**\n * Defines the center of rotation (U)\n */\n this.uRotationCenter = 0.5;\n /**\n * Defines the center of rotation (V)\n */\n this.vRotationCenter = 0.5;\n /**\n * Defines the center of rotation (W)\n */\n this.wRotationCenter = 0.5;\n /**\n * Sets this property to true to avoid deformations when rotating the texture with non-uniform scaling\n */\n this.homogeneousRotationInUVTransform = false;\n /**\n * List of inspectable custom properties (used by the Inspector)\n * @see https://doc.babylonjs.com/toolsAndResources/inspector#extensibility\n */\n this.inspectableCustomProperties = null;\n /** @internal */\n this._noMipmap = false;\n /** @internal */\n this._invertY = false;\n this._rowGenerationMatrix = null;\n this._cachedTextureMatrix = null;\n this._projectionModeMatrix = null;\n this._t0 = null;\n this._t1 = null;\n this._t2 = null;\n this._cachedUOffset = -1;\n this._cachedVOffset = -1;\n this._cachedUScale = 0;\n this._cachedVScale = 0;\n this._cachedUAng = -1;\n this._cachedVAng = -1;\n this._cachedWAng = -1;\n this._cachedReflectionProjectionMatrixId = -1;\n this._cachedURotationCenter = -1;\n this._cachedVRotationCenter = -1;\n this._cachedWRotationCenter = -1;\n this._cachedHomogeneousRotationInUVTransform = false;\n this._cachedReflectionTextureMatrix = null;\n this._cachedReflectionUOffset = -1;\n this._cachedReflectionVOffset = -1;\n this._cachedReflectionUScale = 0;\n this._cachedReflectionVScale = 0;\n this._cachedReflectionCoordinatesMode = -1;\n /** @internal */\n this._buffer = null;\n this._deleteBuffer = false;\n this._format = null;\n this._delayedOnLoad = null;\n this._delayedOnError = null;\n /**\n * Observable triggered once the texture has been loaded.\n */\n this.onLoadObservable = new Observable();\n this._isBlocking = true;\n this.name = url || \"\";\n this.url = url;\n let noMipmap;\n let useSRGBBuffer = false;\n let internalTexture = null;\n if (typeof noMipmapOrOptions === \"object\" && noMipmapOrOptions !== null) {\n noMipmap = (_a = noMipmapOrOptions.noMipmap) !== null && _a !== void 0 ? _a : false;\n invertY = (_b = noMipmapOrOptions.invertY) !== null && _b !== void 0 ? _b : (CompatibilityOptions.UseOpenGLOrientationForUV ? false : true);\n samplingMode = (_c = noMipmapOrOptions.samplingMode) !== null && _c !== void 0 ? _c : Texture.TRILINEAR_SAMPLINGMODE;\n onLoad = (_d = noMipmapOrOptions.onLoad) !== null && _d !== void 0 ? _d : null;\n onError = (_e = noMipmapOrOptions.onError) !== null && _e !== void 0 ? _e : null;\n buffer = (_f = noMipmapOrOptions.buffer) !== null && _f !== void 0 ? _f : null;\n deleteBuffer = (_g = noMipmapOrOptions.deleteBuffer) !== null && _g !== void 0 ? _g : false;\n format = noMipmapOrOptions.format;\n mimeType = noMipmapOrOptions.mimeType;\n loaderOptions = noMipmapOrOptions.loaderOptions;\n creationFlags = noMipmapOrOptions.creationFlags;\n useSRGBBuffer = (_h = noMipmapOrOptions.useSRGBBuffer) !== null && _h !== void 0 ? _h : false;\n internalTexture = (_j = noMipmapOrOptions.internalTexture) !== null && _j !== void 0 ? _j : null;\n }\n else {\n noMipmap = !!noMipmapOrOptions;\n }\n this._noMipmap = noMipmap;\n this._invertY = invertY === undefined ? (CompatibilityOptions.UseOpenGLOrientationForUV ? false : true) : invertY;\n this._initialSamplingMode = samplingMode;\n this._buffer = buffer;\n this._deleteBuffer = deleteBuffer;\n this._mimeType = mimeType;\n this._loaderOptions = loaderOptions;\n this._creationFlags = creationFlags;\n this._useSRGBBuffer = useSRGBBuffer;\n this._forcedExtension = forcedExtension;\n if (format) {\n this._format = format;\n }\n const scene = this.getScene();\n const engine = this._getEngine();\n if (!engine) {\n return;\n }\n engine.onBeforeTextureInitObservable.notifyObservers(this);\n const load = () => {\n if (this._texture) {\n if (this._texture._invertVScale) {\n this.vScale *= -1;\n this.vOffset += 1;\n }\n // Update texture to match internal texture's wrapping\n if (this._texture._cachedWrapU !== null) {\n this.wrapU = this._texture._cachedWrapU;\n this._texture._cachedWrapU = null;\n }\n if (this._texture._cachedWrapV !== null) {\n this.wrapV = this._texture._cachedWrapV;\n this._texture._cachedWrapV = null;\n }\n if (this._texture._cachedWrapR !== null) {\n this.wrapR = this._texture._cachedWrapR;\n this._texture._cachedWrapR = null;\n }\n }\n if (this.onLoadObservable.hasObservers()) {\n this.onLoadObservable.notifyObservers(this);\n }\n if (onLoad) {\n onLoad();\n }\n if (!this.isBlocking && scene) {\n scene.resetCachedMaterial();\n }\n };\n const errorHandler = (message, exception) => {\n this._loadingError = true;\n this._errorObject = { message, exception };\n if (onError) {\n onError(message, exception);\n }\n Texture.OnTextureLoadErrorObservable.notifyObservers(this);\n };\n if (!this.url && !internalTexture) {\n this._delayedOnLoad = load;\n this._delayedOnError = errorHandler;\n return;\n }\n this._texture = internalTexture !== null && internalTexture !== void 0 ? internalTexture : this._getFromCache(this.url, noMipmap, samplingMode, this._invertY, useSRGBBuffer);\n if (!this._texture) {\n if (!scene || !scene.useDelayedTextureLoading) {\n try {\n this._texture = engine.createTexture(this.url, noMipmap, this._invertY, scene, samplingMode, load, errorHandler, this._buffer, undefined, this._format, this._forcedExtension, mimeType, loaderOptions, creationFlags, useSRGBBuffer);\n }\n catch (e) {\n errorHandler(\"error loading\", e);\n throw e;\n }\n if (deleteBuffer) {\n this._buffer = null;\n }\n }\n else {\n this.delayLoadState = 4;\n this._delayedOnLoad = load;\n this._delayedOnError = errorHandler;\n }\n }\n else {\n if (this._texture.isReady) {\n TimingTools.SetImmediate(() => load());\n }\n else {\n const loadObserver = this._texture.onLoadedObservable.add(load);\n this._texture.onErrorObservable.add((e) => {\n var _a;\n errorHandler(e.message, e.exception);\n (_a = this._texture) === null || _a === void 0 ? void 0 : _a.onLoadedObservable.remove(loadObserver);\n });\n }\n }\n }\n /**\n * Update the url (and optional buffer) of this texture if url was null during construction.\n * @param url the url of the texture\n * @param buffer the buffer of the texture (defaults to null)\n * @param onLoad callback called when the texture is loaded (defaults to null)\n * @param forcedExtension defines the extension to use to pick the right loader\n */\n updateURL(url, buffer = null, onLoad, forcedExtension) {\n if (this.url) {\n this.releaseInternalTexture();\n this.getScene().markAllMaterialsAsDirty(1);\n }\n if (!this.name || this.name.startsWith(\"data:\")) {\n this.name = url;\n }\n this.url = url;\n this._buffer = buffer;\n this._forcedExtension = forcedExtension;\n this.delayLoadState = 4;\n if (onLoad) {\n this._delayedOnLoad = onLoad;\n }\n this.delayLoad();\n }\n /**\n * Finish the loading sequence of a texture flagged as delayed load.\n * @internal\n */\n delayLoad() {\n if (this.delayLoadState !== 4) {\n return;\n }\n const scene = this.getScene();\n if (!scene) {\n return;\n }\n this.delayLoadState = 1;\n this._texture = this._getFromCache(this.url, this._noMipmap, this.samplingMode, this._invertY, this._useSRGBBuffer);\n if (!this._texture) {\n this._texture = scene\n .getEngine()\n .createTexture(this.url, this._noMipmap, this._invertY, scene, this.samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format, this._forcedExtension, this._mimeType, this._loaderOptions, this._creationFlags, this._useSRGBBuffer);\n if (this._deleteBuffer) {\n this._buffer = null;\n }\n }\n else {\n if (this._delayedOnLoad) {\n if (this._texture.isReady) {\n TimingTools.SetImmediate(this._delayedOnLoad);\n }\n else {\n this._texture.onLoadedObservable.add(this._delayedOnLoad);\n }\n }\n }\n this._delayedOnLoad = null;\n this._delayedOnError = null;\n }\n _prepareRowForTextureGeneration(x, y, z, t) {\n x *= this._cachedUScale;\n y *= this._cachedVScale;\n x -= this.uRotationCenter * this._cachedUScale;\n y -= this.vRotationCenter * this._cachedVScale;\n z -= this.wRotationCenter;\n Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);\n t.x += this.uRotationCenter * this._cachedUScale + this._cachedUOffset;\n t.y += this.vRotationCenter * this._cachedVScale + this._cachedVOffset;\n t.z += this.wRotationCenter;\n }\n /**\n * Checks if the texture has the same transform matrix than another texture\n * @param texture texture to check against\n * @returns true if the transforms are the same, else false\n */\n checkTransformsAreIdentical(texture) {\n return (texture !== null &&\n this.uOffset === texture.uOffset &&\n this.vOffset === texture.vOffset &&\n this.uScale === texture.uScale &&\n this.vScale === texture.vScale &&\n this.uAng === texture.uAng &&\n this.vAng === texture.vAng &&\n this.wAng === texture.wAng);\n }\n /**\n * Get the current texture matrix which includes the requested offsetting, tiling and rotation components.\n * @param uBase\n * @returns the transform matrix of the texture.\n */\n getTextureMatrix(uBase = 1) {\n if (this.uOffset === this._cachedUOffset &&\n this.vOffset === this._cachedVOffset &&\n this.uScale * uBase === this._cachedUScale &&\n this.vScale === this._cachedVScale &&\n this.uAng === this._cachedUAng &&\n this.vAng === this._cachedVAng &&\n this.wAng === this._cachedWAng &&\n this.uRotationCenter === this._cachedURotationCenter &&\n this.vRotationCenter === this._cachedVRotationCenter &&\n this.wRotationCenter === this._cachedWRotationCenter &&\n this.homogeneousRotationInUVTransform === this._cachedHomogeneousRotationInUVTransform) {\n return this._cachedTextureMatrix;\n }\n this._cachedUOffset = this.uOffset;\n this._cachedVOffset = this.vOffset;\n this._cachedUScale = this.uScale * uBase;\n this._cachedVScale = this.vScale;\n this._cachedUAng = this.uAng;\n this._cachedVAng = this.vAng;\n this._cachedWAng = this.wAng;\n this._cachedURotationCenter = this.uRotationCenter;\n this._cachedVRotationCenter = this.vRotationCenter;\n this._cachedWRotationCenter = this.wRotationCenter;\n this._cachedHomogeneousRotationInUVTransform = this.homogeneousRotationInUVTransform;\n if (!this._cachedTextureMatrix || !this._rowGenerationMatrix) {\n this._cachedTextureMatrix = Matrix.Zero();\n this._rowGenerationMatrix = new Matrix();\n this._t0 = Vector3.Zero();\n this._t1 = Vector3.Zero();\n this._t2 = Vector3.Zero();\n }\n Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);\n if (this.homogeneousRotationInUVTransform) {\n Matrix.TranslationToRef(-this._cachedURotationCenter, -this._cachedVRotationCenter, -this._cachedWRotationCenter, TmpVectors.Matrix[0]);\n Matrix.TranslationToRef(this._cachedURotationCenter, this._cachedVRotationCenter, this._cachedWRotationCenter, TmpVectors.Matrix[1]);\n Matrix.ScalingToRef(this._cachedUScale, this._cachedVScale, 0, TmpVectors.Matrix[2]);\n Matrix.TranslationToRef(this._cachedUOffset, this._cachedVOffset, 0, TmpVectors.Matrix[3]);\n TmpVectors.Matrix[0].multiplyToRef(this._rowGenerationMatrix, this._cachedTextureMatrix);\n this._cachedTextureMatrix.multiplyToRef(TmpVectors.Matrix[1], this._cachedTextureMatrix);\n this._cachedTextureMatrix.multiplyToRef(TmpVectors.Matrix[2], this._cachedTextureMatrix);\n this._cachedTextureMatrix.multiplyToRef(TmpVectors.Matrix[3], this._cachedTextureMatrix);\n // copy the translation row to the 3rd row of the matrix so that we don't need to update the shaders (which expects the translation to be on the 3rd row)\n this._cachedTextureMatrix.setRowFromFloats(2, this._cachedTextureMatrix.m[12], this._cachedTextureMatrix.m[13], this._cachedTextureMatrix.m[14], 1);\n }\n else {\n this._prepareRowForTextureGeneration(0, 0, 0, this._t0);\n this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);\n this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);\n this._t1.subtractInPlace(this._t0);\n this._t2.subtractInPlace(this._t0);\n Matrix.FromValuesToRef(this._t1.x, this._t1.y, this._t1.z, 0.0, this._t2.x, this._t2.y, this._t2.z, 0.0, this._t0.x, this._t0.y, this._t0.z, 0.0, 0.0, 0.0, 0.0, 1.0, this._cachedTextureMatrix);\n }\n const scene = this.getScene();\n if (!scene) {\n return this._cachedTextureMatrix;\n }\n if (this.optimizeUVAllocation) {\n // We flag the materials that are using this texture as \"texture dirty\" because depending on the fact that the matrix is the identity or not, some defines\n // will get different values (see MaterialHelper.PrepareDefinesForMergedUV), meaning we should regenerate the effect accordingly\n scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(this);\n });\n }\n return this._cachedTextureMatrix;\n }\n /**\n * Get the current matrix used to apply reflection. This is useful to rotate an environment texture for instance.\n * @returns The reflection texture transform\n */\n getReflectionTextureMatrix() {\n const scene = this.getScene();\n if (!scene) {\n return this._cachedReflectionTextureMatrix;\n }\n if (this.uOffset === this._cachedReflectionUOffset &&\n this.vOffset === this._cachedReflectionVOffset &&\n this.uScale === this._cachedReflectionUScale &&\n this.vScale === this._cachedReflectionVScale &&\n this.coordinatesMode === this._cachedReflectionCoordinatesMode) {\n if (this.coordinatesMode === Texture.PROJECTION_MODE) {\n if (this._cachedReflectionProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {\n return this._cachedReflectionTextureMatrix;\n }\n }\n else {\n return this._cachedReflectionTextureMatrix;\n }\n }\n if (!this._cachedReflectionTextureMatrix) {\n this._cachedReflectionTextureMatrix = Matrix.Zero();\n }\n if (!this._projectionModeMatrix) {\n this._projectionModeMatrix = Matrix.Zero();\n }\n const flagMaterialsAsTextureDirty = this._cachedReflectionCoordinatesMode !== this.coordinatesMode;\n this._cachedReflectionUOffset = this.uOffset;\n this._cachedReflectionVOffset = this.vOffset;\n this._cachedReflectionUScale = this.uScale;\n this._cachedReflectionVScale = this.vScale;\n this._cachedReflectionCoordinatesMode = this.coordinatesMode;\n switch (this.coordinatesMode) {\n case Texture.PLANAR_MODE: {\n Matrix.IdentityToRef(this._cachedReflectionTextureMatrix);\n this._cachedReflectionTextureMatrix[0] = this.uScale;\n this._cachedReflectionTextureMatrix[5] = this.vScale;\n this._cachedReflectionTextureMatrix[12] = this.uOffset;\n this._cachedReflectionTextureMatrix[13] = this.vOffset;\n break;\n }\n case Texture.PROJECTION_MODE: {\n Matrix.FromValuesToRef(0.5, 0.0, 0.0, 0.0, 0.0, -0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5, 1.0, 1.0, this._projectionModeMatrix);\n const projectionMatrix = scene.getProjectionMatrix();\n this._cachedReflectionProjectionMatrixId = projectionMatrix.updateFlag;\n projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedReflectionTextureMatrix);\n break;\n }\n default:\n Matrix.IdentityToRef(this._cachedReflectionTextureMatrix);\n break;\n }\n if (flagMaterialsAsTextureDirty) {\n // We flag the materials that are using this texture as \"texture dirty\" if the coordinatesMode has changed.\n // Indeed, this property is used to set the value of some defines used to generate the effect (in material.isReadyForSubMesh), so we must make sure this code will be re-executed and the effect recreated if necessary\n scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.getActiveTextures().indexOf(this) !== -1;\n });\n }\n return this._cachedReflectionTextureMatrix;\n }\n /**\n * Clones the texture.\n * @returns the cloned texture\n */\n clone() {\n const options = {\n noMipmap: this._noMipmap,\n invertY: this._invertY,\n samplingMode: this.samplingMode,\n onLoad: undefined,\n onError: undefined,\n buffer: this._texture ? this._texture._buffer : undefined,\n deleteBuffer: this._deleteBuffer,\n format: this.textureFormat,\n mimeType: this.mimeType,\n loaderOptions: this._loaderOptions,\n creationFlags: this._creationFlags,\n useSRGBBuffer: this._useSRGBBuffer,\n };\n return SerializationHelper.Clone(() => {\n return new Texture(this._texture ? this._texture.url : null, this.getScene(), options);\n }, this);\n }\n /**\n * Serialize the texture to a JSON representation we can easily use in the respective Parse function.\n * @returns The JSON representation of the texture\n */\n serialize() {\n var _a, _b;\n const savedName = this.name;\n if (!Texture.SerializeBuffers) {\n if (this.name.startsWith(\"data:\")) {\n this.name = \"\";\n }\n }\n if (this.name.startsWith(\"data:\") && this.url === this.name) {\n this.url = \"\";\n }\n const serializationObject = super.serialize(Texture._SerializeInternalTextureUniqueId);\n if (!serializationObject) {\n return null;\n }\n if (Texture.SerializeBuffers || Texture.ForceSerializeBuffers) {\n if (typeof this._buffer === \"string\" && this._buffer.substr(0, 5) === \"data:\") {\n serializationObject.base64String = this._buffer;\n serializationObject.name = serializationObject.name.replace(\"data:\", \"\");\n }\n else if (this.url && this.url.startsWith(\"data:\") && this._buffer instanceof Uint8Array) {\n serializationObject.base64String = \"data:image/png;base64,\" + EncodeArrayBufferToBase64(this._buffer);\n }\n else if (Texture.ForceSerializeBuffers || (this.url && this.url.startsWith(\"blob:\")) || this._forceSerialize) {\n serializationObject.base64String =\n !this._engine || this._engine._features.supportSyncTextureRead ? GenerateBase64StringFromTexture(this) : GenerateBase64StringFromTextureAsync(this);\n }\n }\n serializationObject.invertY = this._invertY;\n serializationObject.samplingMode = this.samplingMode;\n serializationObject._creationFlags = this._creationFlags;\n serializationObject._useSRGBBuffer = this._useSRGBBuffer;\n if (Texture._SerializeInternalTextureUniqueId) {\n serializationObject.internalTextureUniqueId = (_b = (_a = this._texture) === null || _a === void 0 ? void 0 : _a.uniqueId) !== null && _b !== void 0 ? _b : undefined;\n }\n this.name = savedName;\n return serializationObject;\n }\n /**\n * Get the current class name of the texture useful for serialization or dynamic coding.\n * @returns \"Texture\"\n */\n getClassName() {\n return \"Texture\";\n }\n /**\n * Dispose the texture and release its associated resources.\n */\n dispose() {\n super.dispose();\n this.onLoadObservable.clear();\n this._delayedOnLoad = null;\n this._delayedOnError = null;\n this._buffer = null;\n }\n /**\n * Parse the JSON representation of a texture in order to recreate the texture in the given scene.\n * @param parsedTexture Define the JSON representation of the texture\n * @param scene Define the scene the parsed texture should be instantiated in\n * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies\n * @returns The parsed texture if successful\n */\n static Parse(parsedTexture, scene, rootUrl) {\n if (parsedTexture.customType) {\n const customTexture = InstantiationTools.Instantiate(parsedTexture.customType);\n // Update Sampling Mode\n const parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);\n if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {\n if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {\n parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);\n }\n }\n return parsedCustomTexture;\n }\n if (parsedTexture.isCube && !parsedTexture.isRenderTarget) {\n return Texture._CubeTextureParser(parsedTexture, scene, rootUrl);\n }\n const hasInternalTextureUniqueId = parsedTexture.internalTextureUniqueId !== undefined;\n if (!parsedTexture.name && !parsedTexture.isRenderTarget && !hasInternalTextureUniqueId) {\n return null;\n }\n let internalTexture;\n if (hasInternalTextureUniqueId) {\n const cache = scene.getEngine().getLoadedTexturesCache();\n for (const texture of cache) {\n if (texture.uniqueId === parsedTexture.internalTextureUniqueId) {\n internalTexture = texture;\n break;\n }\n }\n }\n const onLoaded = (texture) => {\n var _a;\n // Clear cache\n if (texture && texture._texture) {\n texture._texture._cachedWrapU = null;\n texture._texture._cachedWrapV = null;\n texture._texture._cachedWrapR = null;\n }\n // Update Sampling Mode\n if (parsedTexture.samplingMode) {\n const sampling = parsedTexture.samplingMode;\n if (texture && texture.samplingMode !== sampling) {\n texture.updateSamplingMode(sampling);\n }\n }\n // Animations\n if (texture && parsedTexture.animations) {\n for (let animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {\n const parsedAnimation = parsedTexture.animations[animationIndex];\n const internalClass = GetClass(\"BABYLON.Animation\");\n if (internalClass) {\n texture.animations.push(internalClass.Parse(parsedAnimation));\n }\n }\n }\n if (hasInternalTextureUniqueId && !internalTexture) {\n (_a = texture === null || texture === void 0 ? void 0 : texture._texture) === null || _a === void 0 ? void 0 : _a._setUniqueId(parsedTexture.internalTextureUniqueId);\n }\n };\n const texture = SerializationHelper.Parse(() => {\n var _a, _b, _c;\n let generateMipMaps = true;\n if (parsedTexture.noMipmap) {\n generateMipMaps = false;\n }\n if (parsedTexture.mirrorPlane) {\n const mirrorTexture = Texture._CreateMirror(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);\n mirrorTexture._waitingRenderList = parsedTexture.renderList;\n mirrorTexture.mirrorPlane = Plane.FromArray(parsedTexture.mirrorPlane);\n onLoaded(mirrorTexture);\n return mirrorTexture;\n }\n else if (parsedTexture.isRenderTarget) {\n let renderTargetTexture = null;\n if (parsedTexture.isCube) {\n // Search for an existing reflection probe (which contains a cube render target texture)\n if (scene.reflectionProbes) {\n for (let index = 0; index < scene.reflectionProbes.length; index++) {\n const probe = scene.reflectionProbes[index];\n if (probe.name === parsedTexture.name) {\n return probe.cubeTexture;\n }\n }\n }\n }\n else {\n renderTargetTexture = Texture._CreateRenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps, (_a = parsedTexture._creationFlags) !== null && _a !== void 0 ? _a : 0);\n renderTargetTexture._waitingRenderList = parsedTexture.renderList;\n }\n onLoaded(renderTargetTexture);\n return renderTargetTexture;\n }\n else {\n let texture;\n if (parsedTexture.base64String && !internalTexture) {\n // name and url are the same to ensure caching happens from the actual base64 string\n texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.base64String, scene, !generateMipMaps, parsedTexture.invertY, parsedTexture.samplingMode, () => {\n onLoaded(texture);\n }, (_b = parsedTexture._creationFlags) !== null && _b !== void 0 ? _b : 0, (_c = parsedTexture._useSRGBBuffer) !== null && _c !== void 0 ? _c : false);\n // prettier name to fit with the loaded data\n texture.name = parsedTexture.name;\n }\n else {\n let url;\n if (parsedTexture.name && (parsedTexture.name.indexOf(\"://\") > 0 || parsedTexture.name.startsWith(\"data:\"))) {\n url = parsedTexture.name;\n }\n else {\n url = rootUrl + parsedTexture.name;\n }\n if (parsedTexture.url && (parsedTexture.url.startsWith(\"data:\") || Texture.UseSerializedUrlIfAny)) {\n url = parsedTexture.url;\n }\n const options = {\n noMipmap: !generateMipMaps,\n invertY: parsedTexture.invertY,\n samplingMode: parsedTexture.samplingMode,\n onLoad: () => {\n onLoaded(texture);\n },\n internalTexture,\n };\n texture = new Texture(url, scene, options);\n }\n return texture;\n }\n }, parsedTexture, scene);\n return texture;\n }\n /**\n * Creates a texture from its base 64 representation.\n * @param data Define the base64 payload without the data: prefix\n * @param name Define the name of the texture in the scene useful fo caching purpose for instance\n * @param scene Define the scene the texture should belong to\n * @param noMipmapOrOptions defines if the texture will require mip maps or not or set of all options to create the texture\n * @param invertY define if the texture needs to be inverted on the y axis during loading\n * @param samplingMode define the sampling mode we want for the texture while fetching from it (Texture.NEAREST_SAMPLINGMODE...)\n * @param onLoad define a callback triggered when the texture has been loaded\n * @param onError define a callback triggered when an error occurred during the loading session\n * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)\n * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)\n * @returns the created texture\n */\n static CreateFromBase64String(data, name, scene, noMipmapOrOptions, invertY, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, onLoad = null, onError = null, format = 5, creationFlags) {\n return new Texture(\"data:\" + name, scene, noMipmapOrOptions, invertY, samplingMode, onLoad, onError, data, false, format, undefined, undefined, creationFlags);\n }\n /**\n * Creates a texture from its data: representation. (data: will be added in case only the payload has been passed in)\n * @param name Define the name of the texture in the scene useful fo caching purpose for instance\n * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation\n * @param scene Define the scene the texture should belong to\n * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load\n * @param noMipmapOrOptions defines if the texture will require mip maps or not or set of all options to create the texture\n * @param invertY define if the texture needs to be inverted on the y axis during loading\n * @param samplingMode define the sampling mode we want for the texture while fetching from it (Texture.NEAREST_SAMPLINGMODE...)\n * @param onLoad define a callback triggered when the texture has been loaded\n * @param onError define a callback triggered when an error occurred during the loading session\n * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)\n * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)\n * @returns the created texture\n */\n static LoadFromDataString(name, buffer, scene, deleteBuffer = false, noMipmapOrOptions, invertY = true, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, onLoad = null, onError = null, format = 5, creationFlags) {\n if (name.substr(0, 5) !== \"data:\") {\n name = \"data:\" + name;\n }\n return new Texture(name, scene, noMipmapOrOptions, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format, undefined, undefined, creationFlags);\n }\n}\n/**\n * Gets or sets a general boolean used to indicate that textures containing direct data (buffers) must be saved as part of the serialization process\n */\nTexture.SerializeBuffers = true;\n/**\n * Gets or sets a general boolean used to indicate that texture buffers must be saved as part of the serialization process.\n * If no buffer exists, one will be created as base64 string from the internal webgl data.\n */\nTexture.ForceSerializeBuffers = false;\n/**\n * This observable will notify when any texture had a loading error\n */\nTexture.OnTextureLoadErrorObservable = new Observable();\n/** @internal */\nTexture._SerializeInternalTextureUniqueId = false;\n/**\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nTexture._CubeTextureParser = (jsonTexture, scene, rootUrl) => {\n throw _WarnImport(\"CubeTexture\");\n};\n/**\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nTexture._CreateMirror = (name, renderTargetSize, scene, generateMipMaps) => {\n throw _WarnImport(\"MirrorTexture\");\n};\n/**\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nTexture._CreateRenderTargetTexture = (name, renderTargetSize, scene, generateMipMaps, creationFlags) => {\n throw _WarnImport(\"RenderTargetTexture\");\n};\n/** nearest is mag = nearest and min = nearest and no mip */\nTexture.NEAREST_SAMPLINGMODE = 1;\n/** nearest is mag = nearest and min = nearest and mip = linear */\nTexture.NEAREST_NEAREST_MIPLINEAR = 8; // nearest is mag = nearest and min = nearest and mip = linear\n/** Bilinear is mag = linear and min = linear and no mip */\nTexture.BILINEAR_SAMPLINGMODE = 2;\n/** Bilinear is mag = linear and min = linear and mip = nearest */\nTexture.LINEAR_LINEAR_MIPNEAREST = 11; // Bilinear is mag = linear and min = linear and mip = nearest\n/** Trilinear is mag = linear and min = linear and mip = linear */\nTexture.TRILINEAR_SAMPLINGMODE = 3;\n/** Trilinear is mag = linear and min = linear and mip = linear */\nTexture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear\n/** mag = nearest and min = nearest and mip = nearest */\nTexture.NEAREST_NEAREST_MIPNEAREST = 4;\n/** mag = nearest and min = linear and mip = nearest */\nTexture.NEAREST_LINEAR_MIPNEAREST = 5;\n/** mag = nearest and min = linear and mip = linear */\nTexture.NEAREST_LINEAR_MIPLINEAR = 6;\n/** mag = nearest and min = linear and mip = none */\nTexture.NEAREST_LINEAR = 7;\n/** mag = nearest and min = nearest and mip = none */\nTexture.NEAREST_NEAREST = 1;\n/** mag = linear and min = nearest and mip = nearest */\nTexture.LINEAR_NEAREST_MIPNEAREST = 9;\n/** mag = linear and min = nearest and mip = linear */\nTexture.LINEAR_NEAREST_MIPLINEAR = 10;\n/** mag = linear and min = linear and mip = none */\nTexture.LINEAR_LINEAR = 2;\n/** mag = linear and min = nearest and mip = none */\nTexture.LINEAR_NEAREST = 12;\n/** Explicit coordinates mode */\nTexture.EXPLICIT_MODE = 0;\n/** Spherical coordinates mode */\nTexture.SPHERICAL_MODE = 1;\n/** Planar coordinates mode */\nTexture.PLANAR_MODE = 2;\n/** Cubic coordinates mode */\nTexture.CUBIC_MODE = 3;\n/** Projection coordinates mode */\nTexture.PROJECTION_MODE = 4;\n/** Inverse Cubic coordinates mode */\nTexture.SKYBOX_MODE = 5;\n/** Inverse Cubic coordinates mode */\nTexture.INVCUBIC_MODE = 6;\n/** Equirectangular coordinates mode */\nTexture.EQUIRECTANGULAR_MODE = 7;\n/** Equirectangular Fixed coordinates mode */\nTexture.FIXED_EQUIRECTANGULAR_MODE = 8;\n/** Equirectangular Fixed Mirrored coordinates mode */\nTexture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;\n/** Texture is not repeating outside of 0..1 UVs */\nTexture.CLAMP_ADDRESSMODE = 0;\n/** Texture is repeating outside of 0..1 UVs */\nTexture.WRAP_ADDRESSMODE = 1;\n/** Texture is repeating and mirrored */\nTexture.MIRROR_ADDRESSMODE = 2;\n/**\n * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file\n */\nTexture.UseSerializedUrlIfAny = false;\n__decorate([\n serialize()\n], Texture.prototype, \"url\", void 0);\n__decorate([\n serialize()\n], Texture.prototype, \"uOffset\", void 0);\n__decorate([\n serialize()\n], Texture.prototype, \"vOffset\", void 0);\n__decorate([\n serialize()\n], Texture.prototype, \"uScale\", void 0);\n__decorate([\n serialize()\n], Texture.prototype, \"vScale\", void 0);\n__decorate([\n serialize()\n], Texture.prototype, \"uAng\", void 0);\n__decorate([\n serialize()\n], Texture.prototype, \"vAng\", void 0);\n__decorate([\n serialize()\n], Texture.prototype, \"wAng\", void 0);\n__decorate([\n serialize()\n], Texture.prototype, \"uRotationCenter\", void 0);\n__decorate([\n serialize()\n], Texture.prototype, \"vRotationCenter\", void 0);\n__decorate([\n serialize()\n], Texture.prototype, \"wRotationCenter\", void 0);\n__decorate([\n serialize()\n], Texture.prototype, \"homogeneousRotationInUVTransform\", void 0);\n__decorate([\n serialize()\n], Texture.prototype, \"isBlocking\", null);\n// References the dependencies.\nRegisterClass(\"BABYLON.Texture\", Texture);\nSerializationHelper._TextureParser = Texture.Parse;\n//# sourceMappingURL=texture.js.map","import { InternalTexture, InternalTextureSource } from \"../../Materials/Textures/internalTexture.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n\nimport { ThinEngine } from \"../thinEngine.js\";\nThinEngine.prototype.updateRawTexture = function (texture, data, format, invertY, compression = null, type = 0, useSRGBBuffer = false) {\n if (!texture) {\n return;\n }\n // Babylon's internalSizedFomat but gl's texImage2D internalFormat\n const internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format, useSRGBBuffer);\n // Babylon's internalFormat but gl's texImage2D format\n const internalFormat = this._getInternalFormat(format);\n const textureType = this._getWebGLTextureType(type);\n this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);\n this._unpackFlipY(invertY === undefined ? true : invertY ? true : false);\n if (!this._doNotHandleContextLost) {\n texture._bufferView = data;\n texture.format = format;\n texture.type = type;\n texture.invertY = invertY;\n texture._compression = compression;\n }\n if (texture.width % 4 !== 0) {\n this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);\n }\n if (compression && data) {\n this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);\n }\n else {\n this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);\n }\n if (texture.generateMipMaps) {\n this._gl.generateMipmap(this._gl.TEXTURE_2D);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_2D, null);\n // this.resetTextureCache();\n texture.isReady = true;\n};\nThinEngine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression = null, type = 0, \n// eslint-disable-next-line @typescript-eslint/no-unused-vars\ncreationFlags = 0, useSRGBBuffer = false) {\n const texture = new InternalTexture(this, InternalTextureSource.Raw);\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = width;\n texture.height = height;\n texture.format = format;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.invertY = invertY;\n texture._compression = compression;\n texture.type = type;\n texture._useSRGBBuffer = this._getUseSRGBBuffer(useSRGBBuffer, !generateMipMaps);\n if (!this._doNotHandleContextLost) {\n texture._bufferView = data;\n }\n this.updateRawTexture(texture, data, format, invertY, compression, type, texture._useSRGBBuffer);\n this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);\n // Filters\n const filters = this._getSamplingParameters(samplingMode, generateMipMaps);\n this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);\n this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);\n if (generateMipMaps) {\n this._gl.generateMipmap(this._gl.TEXTURE_2D);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_2D, null);\n this._internalTexturesCache.push(texture);\n return texture;\n};\nThinEngine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression = null) {\n const gl = this._gl;\n const texture = new InternalTexture(this, InternalTextureSource.CubeRaw);\n texture.isCube = true;\n texture.format = format;\n texture.type = type;\n if (!this._doNotHandleContextLost) {\n texture._bufferViewArray = data;\n }\n const textureType = this._getWebGLTextureType(type);\n let internalFormat = this._getInternalFormat(format);\n if (internalFormat === gl.RGB) {\n internalFormat = gl.RGBA;\n }\n // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable\n if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {\n generateMipMaps = false;\n samplingMode = 1;\n Logger.Warn(\"Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.\");\n }\n else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {\n generateMipMaps = false;\n samplingMode = 1;\n Logger.Warn(\"Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.\");\n }\n else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {\n generateMipMaps = false;\n Logger.Warn(\"Render to float textures is not supported. Mipmap generation forced to false.\");\n }\n else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {\n generateMipMaps = false;\n Logger.Warn(\"Render to half float textures is not supported. Mipmap generation forced to false.\");\n }\n const width = size;\n const height = width;\n texture.width = width;\n texture.height = height;\n texture.invertY = invertY;\n texture._compression = compression;\n // Double check on POT to generate Mips.\n const isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));\n if (!isPot) {\n generateMipMaps = false;\n }\n // Upload data if needed. The texture won't be ready until then.\n if (data) {\n this.updateRawCubeTexture(texture, data, format, type, invertY, compression);\n }\n else {\n const internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);\n const level = 0;\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);\n for (let faceIndex = 0; faceIndex < 6; faceIndex++) {\n if (compression) {\n gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, undefined);\n }\n else {\n gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, null);\n }\n }\n this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);\n // Filters\n if (data && generateMipMaps) {\n this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);\n }\n const filters = this._getSamplingParameters(samplingMode, generateMipMaps);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.isReady = true;\n return texture;\n};\nThinEngine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression = null, level = 0) {\n texture._bufferViewArray = data;\n texture.format = format;\n texture.type = type;\n texture.invertY = invertY;\n texture._compression = compression;\n const gl = this._gl;\n const textureType = this._getWebGLTextureType(type);\n let internalFormat = this._getInternalFormat(format);\n const internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);\n let needConversion = false;\n if (internalFormat === gl.RGB) {\n internalFormat = gl.RGBA;\n needConversion = true;\n }\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);\n this._unpackFlipY(invertY === undefined ? true : invertY ? true : false);\n if (texture.width % 4 !== 0) {\n gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);\n }\n // Data are known to be in +X +Y +Z -X -Y -Z\n for (let faceIndex = 0; faceIndex < 6; faceIndex++) {\n let faceData = data[faceIndex];\n if (compression) {\n gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, faceData);\n }\n else {\n if (needConversion) {\n faceData = _convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);\n }\n gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);\n }\n }\n const isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));\n if (isPot && texture.generateMipMaps && level === 0) {\n this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);\n // this.resetTextureCache();\n texture.isReady = true;\n};\nThinEngine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad = null, onError = null, samplingMode = 3, invertY = false) {\n const gl = this._gl;\n const texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode, null);\n scene === null || scene === void 0 ? void 0 : scene.addPendingData(texture);\n texture.url = url;\n texture.isReady = false;\n this._internalTexturesCache.push(texture);\n const onerror = (request, exception) => {\n scene === null || scene === void 0 ? void 0 : scene.removePendingData(texture);\n if (onError && request) {\n onError(request.status + \" \" + request.statusText, exception);\n }\n };\n const internalCallback = (data) => {\n const width = texture.width;\n const faceDataArrays = callback(data);\n if (!faceDataArrays) {\n return;\n }\n if (mipmapGenerator) {\n const textureType = this._getWebGLTextureType(type);\n let internalFormat = this._getInternalFormat(format);\n const internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);\n let needConversion = false;\n if (internalFormat === gl.RGB) {\n internalFormat = gl.RGBA;\n needConversion = true;\n }\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);\n this._unpackFlipY(false);\n const mipData = mipmapGenerator(faceDataArrays);\n for (let level = 0; level < mipData.length; level++) {\n const mipSize = width >> level;\n for (let faceIndex = 0; faceIndex < 6; faceIndex++) {\n let mipFaceData = mipData[level][faceIndex];\n if (needConversion) {\n mipFaceData = _convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);\n }\n gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);\n }\n }\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n }\n else {\n this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);\n }\n texture.isReady = true;\n // this.resetTextureCache();\n scene === null || scene === void 0 ? void 0 : scene.removePendingData(texture);\n texture.onLoadedObservable.notifyObservers(texture);\n texture.onLoadedObservable.clear();\n if (onLoad) {\n onLoad();\n }\n };\n this._loadFile(url, (data) => {\n internalCallback(data);\n }, undefined, scene === null || scene === void 0 ? void 0 : scene.offlineProvider, true, onerror);\n return texture;\n};\n/**\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nfunction _convertRGBtoRGBATextureData(rgbData, width, height, textureType) {\n // Create new RGBA data container.\n let rgbaData;\n let val1 = 1;\n if (textureType === 1) {\n rgbaData = new Float32Array(width * height * 4);\n }\n else if (textureType === 2) {\n rgbaData = new Uint16Array(width * height * 4);\n val1 = 15360; // 15360 is the encoding of 1 in half float\n }\n else if (textureType === 7) {\n rgbaData = new Uint32Array(width * height * 4);\n }\n else {\n rgbaData = new Uint8Array(width * height * 4);\n }\n // Convert each pixel.\n for (let x = 0; x < width; x++) {\n for (let y = 0; y < height; y++) {\n const index = (y * width + x) * 3;\n const newIndex = (y * width + x) * 4;\n // Map Old Value to new value.\n rgbaData[newIndex + 0] = rgbData[index + 0];\n rgbaData[newIndex + 1] = rgbData[index + 1];\n rgbaData[newIndex + 2] = rgbData[index + 2];\n // Add fully opaque alpha channel.\n rgbaData[newIndex + 3] = val1;\n }\n }\n return rgbaData;\n}\n/**\n * Create a function for createRawTexture3D/createRawTexture2DArray\n * @param is3D true for TEXTURE_3D and false for TEXTURE_2D_ARRAY\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nfunction _makeCreateRawTextureFunction(is3D) {\n return function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression = null, textureType = 0) {\n const target = is3D ? this._gl.TEXTURE_3D : this._gl.TEXTURE_2D_ARRAY;\n const source = is3D ? InternalTextureSource.Raw3D : InternalTextureSource.Raw2DArray;\n const texture = new InternalTexture(this, source);\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.baseDepth = depth;\n texture.width = width;\n texture.height = height;\n texture.depth = depth;\n texture.format = format;\n texture.type = textureType;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n if (is3D) {\n texture.is3D = true;\n }\n else {\n texture.is2DArray = true;\n }\n if (!this._doNotHandleContextLost) {\n texture._bufferView = data;\n }\n if (is3D) {\n this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);\n }\n else {\n this.updateRawTexture2DArray(texture, data, format, invertY, compression, textureType);\n }\n this._bindTextureDirectly(target, texture, true);\n // Filters\n const filters = this._getSamplingParameters(samplingMode, generateMipMaps);\n this._gl.texParameteri(target, this._gl.TEXTURE_MAG_FILTER, filters.mag);\n this._gl.texParameteri(target, this._gl.TEXTURE_MIN_FILTER, filters.min);\n if (generateMipMaps) {\n this._gl.generateMipmap(target);\n }\n this._bindTextureDirectly(target, null);\n this._internalTexturesCache.push(texture);\n return texture;\n };\n}\nThinEngine.prototype.createRawTexture2DArray = _makeCreateRawTextureFunction(false);\nThinEngine.prototype.createRawTexture3D = _makeCreateRawTextureFunction(true);\n/**\n * Create a function for updateRawTexture3D/updateRawTexture2DArray\n * @param is3D true for TEXTURE_3D and false for TEXTURE_2D_ARRAY\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nfunction _makeUpdateRawTextureFunction(is3D) {\n return function (texture, data, format, invertY, compression = null, textureType = 0) {\n const target = is3D ? this._gl.TEXTURE_3D : this._gl.TEXTURE_2D_ARRAY;\n const internalType = this._getWebGLTextureType(textureType);\n const internalFormat = this._getInternalFormat(format);\n const internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);\n this._bindTextureDirectly(target, texture, true);\n this._unpackFlipY(invertY === undefined ? true : invertY ? true : false);\n if (!this._doNotHandleContextLost) {\n texture._bufferView = data;\n texture.format = format;\n texture.invertY = invertY;\n texture._compression = compression;\n }\n if (texture.width % 4 !== 0) {\n this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);\n }\n if (compression && data) {\n this._gl.compressedTexImage3D(target, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);\n }\n else {\n this._gl.texImage3D(target, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);\n }\n if (texture.generateMipMaps) {\n this._gl.generateMipmap(target);\n }\n this._bindTextureDirectly(target, null);\n // this.resetTextureCache();\n texture.isReady = true;\n };\n}\nThinEngine.prototype.updateRawTexture2DArray = _makeUpdateRawTextureFunction(false);\nThinEngine.prototype.updateRawTexture3D = _makeUpdateRawTextureFunction(true);\n//# sourceMappingURL=engine.rawTexture.js.map","import { Texture } from \"./texture.js\";\n\nimport \"../../Engines/Extensions/engine.rawTexture.js\";\n/**\n * Raw texture can help creating a texture directly from an array of data.\n * This can be super useful if you either get the data from an uncompressed source or\n * if you wish to create your texture pixel by pixel.\n */\nexport class RawTexture extends Texture {\n /**\n * Instantiates a new RawTexture.\n * Raw texture can help creating a texture directly from an array of data.\n * This can be super useful if you either get the data from an uncompressed source or\n * if you wish to create your texture pixel by pixel.\n * @param data define the array of data to use to create the texture (null to create an empty texture)\n * @param width define the width of the texture\n * @param height define the height of the texture\n * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)\n * @param sceneOrEngine defines the scene or engine the texture will belong to\n * @param generateMipMaps define whether mip maps should be generated or not\n * @param invertY define if the data should be flipped on Y when uploaded to the GPU\n * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)\n * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)\n * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)\n * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU).\n */\n constructor(data, width, height, \n /**\n * Define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)\n */\n format, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, creationFlags, useSRGBBuffer) {\n super(null, sceneOrEngine, !generateMipMaps, invertY, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, creationFlags);\n this.format = format;\n if (!this._engine) {\n return;\n }\n if (!this._engine._caps.textureFloatLinearFiltering && type === 1) {\n samplingMode = 1;\n }\n if (!this._engine._caps.textureHalfFloatLinearFiltering && type === 2) {\n samplingMode = 1;\n }\n this._texture = this._engine.createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type, creationFlags !== null && creationFlags !== void 0 ? creationFlags : 0, useSRGBBuffer !== null && useSRGBBuffer !== void 0 ? useSRGBBuffer : false);\n this.wrapU = Texture.CLAMP_ADDRESSMODE;\n this.wrapV = Texture.CLAMP_ADDRESSMODE;\n }\n /**\n * Updates the texture underlying data.\n * @param data Define the new data of the texture\n */\n update(data) {\n this._getEngine().updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, null, this._texture.type, this._texture._useSRGBBuffer);\n }\n /**\n * Creates a luminance texture from some data.\n * @param data Define the texture data\n * @param width Define the width of the texture\n * @param height Define the height of the texture\n * @param sceneOrEngine defines the scene or engine the texture will belong to\n * @param generateMipMaps Define whether or not to create mip maps for the texture\n * @param invertY define if the data should be flipped on Y when uploaded to the GPU\n * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)\n * @returns the luminance texture\n */\n static CreateLuminanceTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3) {\n return new RawTexture(data, width, height, 1, sceneOrEngine, generateMipMaps, invertY, samplingMode);\n }\n /**\n * Creates a luminance alpha texture from some data.\n * @param data Define the texture data\n * @param width Define the width of the texture\n * @param height Define the height of the texture\n * @param sceneOrEngine defines the scene or engine the texture will belong to\n * @param generateMipMaps Define whether or not to create mip maps for the texture\n * @param invertY define if the data should be flipped on Y when uploaded to the GPU\n * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)\n * @returns the luminance alpha texture\n */\n static CreateLuminanceAlphaTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3) {\n return new RawTexture(data, width, height, 2, sceneOrEngine, generateMipMaps, invertY, samplingMode);\n }\n /**\n * Creates an alpha texture from some data.\n * @param data Define the texture data\n * @param width Define the width of the texture\n * @param height Define the height of the texture\n * @param sceneOrEngine defines the scene or engine the texture will belong to\n * @param generateMipMaps Define whether or not to create mip maps for the texture\n * @param invertY define if the data should be flipped on Y when uploaded to the GPU\n * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)\n * @returns the alpha texture\n */\n static CreateAlphaTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3) {\n return new RawTexture(data, width, height, 0, sceneOrEngine, generateMipMaps, invertY, samplingMode);\n }\n /**\n * Creates a RGB texture from some data.\n * @param data Define the texture data\n * @param width Define the width of the texture\n * @param height Define the height of the texture\n * @param sceneOrEngine defines the scene or engine the texture will belong to\n * @param generateMipMaps Define whether or not to create mip maps for the texture\n * @param invertY define if the data should be flipped on Y when uploaded to the GPU\n * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)\n * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)\n * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)\n * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU).\n * @returns the RGB alpha texture\n */\n static CreateRGBTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, creationFlags = 0, useSRGBBuffer = false) {\n return new RawTexture(data, width, height, 4, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, creationFlags, useSRGBBuffer);\n }\n /**\n * Creates a RGBA texture from some data.\n * @param data Define the texture data\n * @param width Define the width of the texture\n * @param height Define the height of the texture\n * @param sceneOrEngine defines the scene or engine the texture will belong to\n * @param generateMipMaps Define whether or not to create mip maps for the texture\n * @param invertY define if the data should be flipped on Y when uploaded to the GPU\n * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)\n * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)\n * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)\n * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU).\n * @returns the RGBA texture\n */\n static CreateRGBATexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, creationFlags = 0, useSRGBBuffer = false) {\n return new RawTexture(data, width, height, 5, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, creationFlags, useSRGBBuffer);\n }\n /**\n * Creates a RGBA storage texture from some data.\n * @param data Define the texture data\n * @param width Define the width of the texture\n * @param height Define the height of the texture\n * @param sceneOrEngine defines the scene or engine the texture will belong to\n * @param generateMipMaps Define whether or not to create mip maps for the texture\n * @param invertY define if the data should be flipped on Y when uploaded to the GPU\n * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)\n * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)\n * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU).\n * @returns the RGBA texture\n */\n static CreateRGBAStorageTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, useSRGBBuffer = false) {\n return new RawTexture(data, width, height, 5, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, 1, useSRGBBuffer);\n }\n /**\n * Creates a R texture from some data.\n * @param data Define the texture data\n * @param width Define the width of the texture\n * @param height Define the height of the texture\n * @param sceneOrEngine defines the scene or engine the texture will belong to\n * @param generateMipMaps Define whether or not to create mip maps for the texture\n * @param invertY define if the data should be flipped on Y when uploaded to the GPU\n * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)\n * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)\n * @returns the R texture\n */\n static CreateRTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, type = 1) {\n return new RawTexture(data, width, height, 6, sceneOrEngine, generateMipMaps, invertY, samplingMode, type);\n }\n /**\n * Creates a R storage texture from some data.\n * @param data Define the texture data\n * @param width Define the width of the texture\n * @param height Define the height of the texture\n * @param sceneOrEngine defines the scene or engine the texture will belong to\n * @param generateMipMaps Define whether or not to create mip maps for the texture\n * @param invertY define if the data should be flipped on Y when uploaded to the GPU\n * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)\n * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)\n * @returns the R texture\n */\n static CreateRStorageTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, type = 1) {\n return new RawTexture(data, width, height, 6, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, 1);\n }\n}\n//# sourceMappingURL=rawTexture.js.map","import { PointerEventTypes } from \"../../Events/pointerEvents.js\";\nimport { PrecisionDate } from \"../../Misc/precisionDate.js\";\nimport { Epsilon } from \"../../Maths/math.constants.js\";\n/**\n * The autoRotation behavior (AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#autorotation-behavior\n */\nexport class AutoRotationBehavior {\n constructor() {\n this._zoomStopsAnimation = false;\n this._idleRotationSpeed = 0.05;\n this._idleRotationWaitTime = 2000;\n this._idleRotationSpinupTime = 2000;\n this.targetAlpha = null;\n this._isPointerDown = false;\n this._lastFrameTime = null;\n this._lastInteractionTime = -Infinity;\n this._cameraRotationSpeed = 0;\n this._lastFrameRadius = 0;\n }\n /**\n * Gets the name of the behavior.\n */\n get name() {\n return \"AutoRotation\";\n }\n /**\n * Sets the flag that indicates if user zooming should stop animation.\n */\n set zoomStopsAnimation(flag) {\n this._zoomStopsAnimation = flag;\n }\n /**\n * Gets the flag that indicates if user zooming should stop animation.\n */\n get zoomStopsAnimation() {\n return this._zoomStopsAnimation;\n }\n /**\n * Sets the default speed at which the camera rotates around the model.\n */\n set idleRotationSpeed(speed) {\n this._idleRotationSpeed = speed;\n }\n /**\n * Gets the default speed at which the camera rotates around the model.\n */\n get idleRotationSpeed() {\n return this._idleRotationSpeed;\n }\n /**\n * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.\n */\n set idleRotationWaitTime(time) {\n this._idleRotationWaitTime = time;\n }\n /**\n * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.\n */\n get idleRotationWaitTime() {\n return this._idleRotationWaitTime;\n }\n /**\n * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.\n */\n set idleRotationSpinupTime(time) {\n this._idleRotationSpinupTime = time;\n }\n /**\n * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.\n */\n get idleRotationSpinupTime() {\n return this._idleRotationSpinupTime;\n }\n /**\n * Gets a value indicating if the camera is currently rotating because of this behavior\n */\n get rotationInProgress() {\n return Math.abs(this._cameraRotationSpeed) > 0;\n }\n /**\n * Initializes the behavior.\n */\n init() {\n // Do nothing\n }\n /**\n * Attaches the behavior to its arc rotate camera.\n * @param camera Defines the camera to attach the behavior to\n */\n attach(camera) {\n this._attachedCamera = camera;\n const scene = this._attachedCamera.getScene();\n this._onPrePointerObservableObserver = scene.onPrePointerObservable.add((pointerInfoPre) => {\n if (pointerInfoPre.type === PointerEventTypes.POINTERDOWN) {\n this._isPointerDown = true;\n return;\n }\n if (pointerInfoPre.type === PointerEventTypes.POINTERUP) {\n this._isPointerDown = false;\n }\n });\n this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(() => {\n if (this._reachTargetAlpha()) {\n return;\n }\n const now = PrecisionDate.Now;\n let dt = 0;\n if (this._lastFrameTime != null) {\n dt = now - this._lastFrameTime;\n }\n this._lastFrameTime = now;\n // Stop the animation if there is user interaction and the animation should stop for this interaction\n this._applyUserInteraction();\n const timeToRotation = now - this._lastInteractionTime - this._idleRotationWaitTime;\n const scale = Math.max(Math.min(timeToRotation / this._idleRotationSpinupTime, 1), 0);\n this._cameraRotationSpeed = this._idleRotationSpeed * scale;\n // Step camera rotation by rotation speed\n if (this._attachedCamera) {\n this._attachedCamera.alpha -= this._cameraRotationSpeed * (dt / 1000);\n }\n });\n }\n /**\n * Detaches the behavior from its current arc rotate camera.\n */\n detach() {\n if (!this._attachedCamera) {\n return;\n }\n const scene = this._attachedCamera.getScene();\n if (this._onPrePointerObservableObserver) {\n scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);\n }\n this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);\n this._attachedCamera = null;\n }\n /**\n * Force-reset the last interaction time\n * @param customTime an optional time that will be used instead of the current last interaction time. For example `Date.now()`\n */\n resetLastInteractionTime(customTime) {\n this._lastInteractionTime = customTime !== null && customTime !== void 0 ? customTime : PrecisionDate.Now;\n }\n /**\n * Returns true if camera alpha reaches the target alpha\n * @returns true if camera alpha reaches the target alpha\n */\n _reachTargetAlpha() {\n if (this._attachedCamera && this.targetAlpha) {\n return Math.abs(this._attachedCamera.alpha - this.targetAlpha) < Epsilon;\n }\n return false;\n }\n /**\n * Returns true if user is scrolling.\n * @returns true if user is scrolling.\n */\n _userIsZooming() {\n if (!this._attachedCamera) {\n return false;\n }\n return this._attachedCamera.inertialRadiusOffset !== 0;\n }\n _shouldAnimationStopForInteraction() {\n if (!this._attachedCamera) {\n return false;\n }\n let zoomHasHitLimit = false;\n if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {\n zoomHasHitLimit = true;\n }\n // Update the record of previous radius - works as an approx. indicator of hitting radius limits\n this._lastFrameRadius = this._attachedCamera.radius;\n return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();\n }\n /**\n * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.\n */\n _applyUserInteraction() {\n if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {\n this._lastInteractionTime = PrecisionDate.Now;\n }\n }\n // Tools\n _userIsMoving() {\n if (!this._attachedCamera) {\n return false;\n }\n return (this._attachedCamera.inertialAlphaOffset !== 0 ||\n this._attachedCamera.inertialBetaOffset !== 0 ||\n this._attachedCamera.inertialRadiusOffset !== 0 ||\n this._attachedCamera.inertialPanningX !== 0 ||\n this._attachedCamera.inertialPanningY !== 0 ||\n this._isPointerDown);\n }\n}\n//# sourceMappingURL=autoRotationBehavior.js.map","import { BackEase, EasingFunction } from \"../../Animations/easing.js\";\nimport { Animation } from \"../../Animations/animation.js\";\n/**\n * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius\n * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#bouncing-behavior\n */\nexport class BouncingBehavior {\n constructor() {\n /**\n * The duration of the animation, in milliseconds\n */\n this.transitionDuration = 450;\n /**\n * Length of the distance animated by the transition when lower radius is reached\n */\n this.lowerRadiusTransitionRange = 2;\n /**\n * Length of the distance animated by the transition when upper radius is reached\n */\n this.upperRadiusTransitionRange = -2;\n this._autoTransitionRange = false;\n // Animations\n this._radiusIsAnimating = false;\n this._radiusBounceTransition = null;\n this._animatables = new Array();\n }\n /**\n * Gets the name of the behavior.\n */\n get name() {\n return \"Bouncing\";\n }\n /**\n * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically\n */\n get autoTransitionRange() {\n return this._autoTransitionRange;\n }\n /**\n * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically\n * Transition ranges will be set to 5% of the bounding box diagonal in world space\n */\n set autoTransitionRange(value) {\n if (this._autoTransitionRange === value) {\n return;\n }\n this._autoTransitionRange = value;\n const camera = this._attachedCamera;\n if (!camera) {\n return;\n }\n if (value) {\n this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add((mesh) => {\n if (!mesh) {\n return;\n }\n mesh.computeWorldMatrix(true);\n const diagonal = mesh.getBoundingInfo().diagonalLength;\n this.lowerRadiusTransitionRange = diagonal * 0.05;\n this.upperRadiusTransitionRange = diagonal * 0.05;\n });\n }\n else if (this._onMeshTargetChangedObserver) {\n camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);\n }\n }\n /**\n * Initializes the behavior.\n */\n init() {\n // Do nothing\n }\n /**\n * Attaches the behavior to its arc rotate camera.\n * @param camera Defines the camera to attach the behavior to\n */\n attach(camera) {\n this._attachedCamera = camera;\n this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(() => {\n if (!this._attachedCamera) {\n return;\n }\n // Add the bounce animation to the lower radius limit\n if (this._isRadiusAtLimit(this._attachedCamera.lowerRadiusLimit)) {\n this._applyBoundRadiusAnimation(this.lowerRadiusTransitionRange);\n }\n // Add the bounce animation to the upper radius limit\n if (this._isRadiusAtLimit(this._attachedCamera.upperRadiusLimit)) {\n this._applyBoundRadiusAnimation(this.upperRadiusTransitionRange);\n }\n });\n }\n /**\n * Detaches the behavior from its current arc rotate camera.\n */\n detach() {\n if (!this._attachedCamera) {\n return;\n }\n if (this._onAfterCheckInputsObserver) {\n this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);\n }\n if (this._onMeshTargetChangedObserver) {\n this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);\n }\n this._attachedCamera = null;\n }\n /**\n * Checks if the camera radius is at the specified limit. Takes into account animation locks.\n * @param radiusLimit The limit to check against.\n * @returns Bool to indicate if at limit.\n */\n _isRadiusAtLimit(radiusLimit) {\n if (!this._attachedCamera) {\n return false;\n }\n if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {\n return true;\n }\n return false;\n }\n /**\n * Applies an animation to the radius of the camera, extending by the radiusDelta.\n * @param radiusDelta The delta by which to animate to. Can be negative.\n */\n _applyBoundRadiusAnimation(radiusDelta) {\n if (!this._attachedCamera) {\n return;\n }\n if (!this._radiusBounceTransition) {\n BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);\n this._radiusBounceTransition = Animation.CreateAnimation(\"radius\", Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);\n }\n // Prevent zoom until bounce has completed\n this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;\n this._attachedCamera.wheelPrecision = Infinity;\n this._attachedCamera.inertialRadiusOffset = 0;\n // Animate to the radius limit\n this.stopAllAnimations();\n this._radiusIsAnimating = true;\n const animatable = Animation.TransitionTo(\"radius\", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, () => this._clearAnimationLocks());\n if (animatable) {\n this._animatables.push(animatable);\n }\n }\n /**\n * Removes all animation locks. Allows new animations to be added to any of the camera properties.\n */\n _clearAnimationLocks() {\n this._radiusIsAnimating = false;\n if (this._attachedCamera) {\n this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;\n }\n }\n /**\n * Stops and removes all animations that have been applied to the camera\n */\n stopAllAnimations() {\n if (this._attachedCamera) {\n this._attachedCamera.animations = [];\n }\n while (this._animatables.length) {\n this._animatables[0].onAnimationEnd = null;\n this._animatables[0].stop();\n this._animatables.shift();\n }\n }\n}\n/**\n * The easing function used by animations\n */\nBouncingBehavior.EasingFunction = new BackEase(0.3);\n/**\n * The easing mode used by animations\n */\nBouncingBehavior.EasingMode = EasingFunction.EASINGMODE_EASEOUT;\n//# sourceMappingURL=bouncingBehavior.js.map","import { ExponentialEase, EasingFunction } from \"../../Animations/easing.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { PointerEventTypes } from \"../../Events/pointerEvents.js\";\nimport { PrecisionDate } from \"../../Misc/precisionDate.js\";\nimport { Vector3, Vector2 } from \"../../Maths/math.vector.js\";\nimport { Animation } from \"../../Animations/animation.js\";\n/**\n * The framing behavior (FramingBehavior) is designed to automatically position an ArcRotateCamera when its target is set to a mesh. It is also useful if you want to prevent the camera to go under a virtual horizontal plane.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#framing-behavior\n */\nexport class FramingBehavior {\n constructor() {\n /**\n * An event triggered when the animation to zoom on target mesh has ended\n */\n this.onTargetFramingAnimationEndObservable = new Observable();\n this._mode = FramingBehavior.FitFrustumSidesMode;\n this._radiusScale = 1.0;\n this._positionScale = 0.5;\n this._defaultElevation = 0.3;\n this._elevationReturnTime = 1500;\n this._elevationReturnWaitTime = 1000;\n this._zoomStopsAnimation = false;\n this._framingTime = 1500;\n /**\n * Define if the behavior should automatically change the configured\n * camera limits and sensibilities.\n */\n this.autoCorrectCameraLimitsAndSensibility = true;\n this._isPointerDown = false;\n this._lastInteractionTime = -Infinity;\n // Framing control\n this._animatables = new Array();\n this._betaIsAnimating = false;\n }\n /**\n * Gets the name of the behavior.\n */\n get name() {\n return \"Framing\";\n }\n /**\n * Sets the current mode used by the behavior\n */\n set mode(mode) {\n this._mode = mode;\n }\n /**\n * Gets current mode used by the behavior.\n */\n get mode() {\n return this._mode;\n }\n /**\n * Sets the scale applied to the radius (1 by default)\n */\n set radiusScale(radius) {\n this._radiusScale = radius;\n }\n /**\n * Gets the scale applied to the radius\n */\n get radiusScale() {\n return this._radiusScale;\n }\n /**\n * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.\n */\n set positionScale(scale) {\n this._positionScale = scale;\n }\n /**\n * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.\n */\n get positionScale() {\n return this._positionScale;\n }\n /**\n * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle\n * behaviour is triggered, in radians.\n */\n set defaultElevation(elevation) {\n this._defaultElevation = elevation;\n }\n /**\n * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle\n * behaviour is triggered, in radians.\n */\n get defaultElevation() {\n return this._defaultElevation;\n }\n /**\n * Sets the time (in milliseconds) taken to return to the default beta position.\n * Negative value indicates camera should not return to default.\n */\n set elevationReturnTime(speed) {\n this._elevationReturnTime = speed;\n }\n /**\n * Gets the time (in milliseconds) taken to return to the default beta position.\n * Negative value indicates camera should not return to default.\n */\n get elevationReturnTime() {\n return this._elevationReturnTime;\n }\n /**\n * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.\n */\n set elevationReturnWaitTime(time) {\n this._elevationReturnWaitTime = time;\n }\n /**\n * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.\n */\n get elevationReturnWaitTime() {\n return this._elevationReturnWaitTime;\n }\n /**\n * Sets the flag that indicates if user zooming should stop animation.\n */\n set zoomStopsAnimation(flag) {\n this._zoomStopsAnimation = flag;\n }\n /**\n * Gets the flag that indicates if user zooming should stop animation.\n */\n get zoomStopsAnimation() {\n return this._zoomStopsAnimation;\n }\n /**\n * Sets the transition time when framing the mesh, in milliseconds\n */\n set framingTime(time) {\n this._framingTime = time;\n }\n /**\n * Gets the transition time when framing the mesh, in milliseconds\n */\n get framingTime() {\n return this._framingTime;\n }\n /**\n * Initializes the behavior.\n */\n init() {\n // Do nothing\n }\n /**\n * Attaches the behavior to its arc rotate camera.\n * @param camera Defines the camera to attach the behavior to\n */\n attach(camera) {\n this._attachedCamera = camera;\n const scene = this._attachedCamera.getScene();\n FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);\n this._onPrePointerObservableObserver = scene.onPrePointerObservable.add((pointerInfoPre) => {\n if (pointerInfoPre.type === PointerEventTypes.POINTERDOWN) {\n this._isPointerDown = true;\n return;\n }\n if (pointerInfoPre.type === PointerEventTypes.POINTERUP) {\n this._isPointerDown = false;\n }\n });\n this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add((mesh) => {\n if (mesh) {\n this.zoomOnMesh(mesh, undefined, () => {\n this.onTargetFramingAnimationEndObservable.notifyObservers();\n });\n }\n });\n this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(() => {\n // Stop the animation if there is user interaction and the animation should stop for this interaction\n this._applyUserInteraction();\n // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it\n // back to the default position after a given timeout\n this._maintainCameraAboveGround();\n });\n }\n /**\n * Detaches the behavior from its current arc rotate camera.\n */\n detach() {\n if (!this._attachedCamera) {\n return;\n }\n const scene = this._attachedCamera.getScene();\n if (this._onPrePointerObservableObserver) {\n scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);\n }\n if (this._onAfterCheckInputsObserver) {\n this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);\n }\n if (this._onMeshTargetChangedObserver) {\n this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);\n }\n this._attachedCamera = null;\n }\n /**\n * Targets the given mesh and updates zoom level accordingly.\n * @param mesh The mesh to target.\n * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh\n * @param onAnimationEnd Callback triggered at the end of the framing animation\n */\n zoomOnMesh(mesh, focusOnOriginXZ = false, onAnimationEnd = null) {\n mesh.computeWorldMatrix(true);\n const boundingBox = mesh.getBoundingInfo().boundingBox;\n this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);\n }\n /**\n * Targets the given mesh with its children and updates zoom level accordingly.\n * @param mesh The mesh to target.\n * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh\n * @param onAnimationEnd Callback triggered at the end of the framing animation\n */\n zoomOnMeshHierarchy(mesh, focusOnOriginXZ = false, onAnimationEnd = null) {\n mesh.computeWorldMatrix(true);\n const boundingBox = mesh.getHierarchyBoundingVectors(true);\n this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);\n }\n /**\n * Targets the given meshes with their children and updates zoom level accordingly.\n * @param meshes The mesh to target.\n * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh\n * @param onAnimationEnd Callback triggered at the end of the framing animation\n */\n zoomOnMeshesHierarchy(meshes, focusOnOriginXZ = false, onAnimationEnd = null) {\n const min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n const max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);\n for (let i = 0; i < meshes.length; i++) {\n const boundingInfo = meshes[i].getHierarchyBoundingVectors(true);\n Vector3.CheckExtends(boundingInfo.min, min, max);\n Vector3.CheckExtends(boundingInfo.max, min, max);\n }\n this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);\n }\n /**\n * Targets the bounding box info defined by its extends and updates zoom level accordingly.\n * @param minimumWorld Determines the smaller position of the bounding box extend\n * @param maximumWorld Determines the bigger position of the bounding box extend\n * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh\n * @param onAnimationEnd Callback triggered at the end of the framing animation\n */\n zoomOnBoundingInfo(minimumWorld, maximumWorld, focusOnOriginXZ = false, onAnimationEnd = null) {\n let zoomTarget;\n if (!this._attachedCamera) {\n return;\n }\n // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY\n const bottom = minimumWorld.y;\n const top = maximumWorld.y;\n const zoomTargetY = bottom + (top - bottom) * this._positionScale;\n const radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);\n if (focusOnOriginXZ) {\n zoomTarget = new Vector3(0, zoomTargetY, 0);\n }\n else {\n const centerWorld = minimumWorld.add(radiusWorld);\n zoomTarget = new Vector3(centerWorld.x, zoomTargetY, centerWorld.z);\n }\n if (!this._vectorTransition) {\n this._vectorTransition = Animation.CreateAnimation(\"target\", Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);\n }\n this._betaIsAnimating = true;\n let animatable = Animation.TransitionTo(\"target\", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);\n if (animatable) {\n this._animatables.push(animatable);\n }\n // sets the radius and lower radius bounds\n // Small delta ensures camera is not always at lower zoom limit.\n let radius = 0;\n if (this._mode === FramingBehavior.FitFrustumSidesMode) {\n const position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);\n if (this.autoCorrectCameraLimitsAndSensibility) {\n this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;\n }\n radius = position;\n }\n else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {\n radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);\n if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {\n this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;\n }\n }\n // Set sensibilities\n if (this.autoCorrectCameraLimitsAndSensibility) {\n const extend = maximumWorld.subtract(minimumWorld).length();\n this._attachedCamera.panningSensibility = 5000 / extend;\n this._attachedCamera.wheelPrecision = 100 / radius;\n }\n // transition to new radius\n if (!this._radiusTransition) {\n this._radiusTransition = Animation.CreateAnimation(\"radius\", Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);\n }\n animatable = Animation.TransitionTo(\"radius\", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, () => {\n this.stopAllAnimations();\n if (onAnimationEnd) {\n onAnimationEnd();\n }\n if (this._attachedCamera && this._attachedCamera.useInputToRestoreState) {\n this._attachedCamera.storeState();\n }\n });\n if (animatable) {\n this._animatables.push(animatable);\n }\n }\n /**\n * Calculates the lowest radius for the camera based on the bounding box of the mesh.\n * @param minimumWorld\n * @param maximumWorld\n * @returns The minimum distance from the primary mesh's center point at which the camera must be kept in order\n *\t\t to fully enclose the mesh in the viewing frustum.\n */\n _calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld) {\n const size = maximumWorld.subtract(minimumWorld);\n const boxVectorGlobalDiagonal = size.length();\n const frustumSlope = this._getFrustumSlope();\n // Formula for setting distance\n // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)\n const radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;\n // Horizon distance\n const radius = radiusWithoutFraming * this._radiusScale;\n const distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));\n const distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));\n let distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);\n const camera = this._attachedCamera;\n if (!camera) {\n return 0;\n }\n if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {\n // Don't exceed the requested limit\n distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;\n }\n // Don't exceed the upper radius limit\n if (camera.upperRadiusLimit) {\n distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;\n }\n return distance;\n }\n /**\n * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera\n * is automatically returned to its default position (expected to be above ground plane).\n */\n _maintainCameraAboveGround() {\n if (this._elevationReturnTime < 0) {\n return;\n }\n const timeSinceInteraction = PrecisionDate.Now - this._lastInteractionTime;\n const defaultBeta = Math.PI * 0.5 - this._defaultElevation;\n const limitBeta = Math.PI * 0.5;\n // Bring the camera back up if below the ground plane\n if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {\n this._betaIsAnimating = true;\n //Transition to new position\n this.stopAllAnimations();\n if (!this._betaTransition) {\n this._betaTransition = Animation.CreateAnimation(\"beta\", Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);\n }\n const animatabe = Animation.TransitionTo(\"beta\", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, () => {\n this._clearAnimationLocks();\n this.stopAllAnimations();\n });\n if (animatabe) {\n this._animatables.push(animatabe);\n }\n }\n }\n /**\n * Returns the frustum slope based on the canvas ratio and camera FOV\n * @returns The frustum slope represented as a Vector2 with X and Y slopes\n */\n _getFrustumSlope() {\n // Calculate the viewport ratio\n // Aspect Ratio is Height/Width.\n const camera = this._attachedCamera;\n if (!camera) {\n return Vector2.Zero();\n }\n const engine = camera.getScene().getEngine();\n const aspectRatio = engine.getAspectRatio(camera);\n // Camera FOV is the vertical field of view (top-bottom) in radians.\n // Slope of the frustum top/bottom planes in view space, relative to the forward vector.\n const frustumSlopeY = Math.tan(camera.fov / 2);\n // Slope of the frustum left/right planes in view space, relative to the forward vector.\n // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit\n // along the forward vector.\n const frustumSlopeX = frustumSlopeY * aspectRatio;\n return new Vector2(frustumSlopeX, frustumSlopeY);\n }\n /**\n * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.\n */\n _clearAnimationLocks() {\n this._betaIsAnimating = false;\n }\n /**\n * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.\n */\n _applyUserInteraction() {\n if (this.isUserIsMoving) {\n this._lastInteractionTime = PrecisionDate.Now;\n this.stopAllAnimations();\n this._clearAnimationLocks();\n }\n }\n /**\n * Stops and removes all animations that have been applied to the camera\n */\n stopAllAnimations() {\n if (this._attachedCamera) {\n this._attachedCamera.animations = [];\n }\n while (this._animatables.length) {\n if (this._animatables[0]) {\n this._animatables[0].onAnimationEnd = null;\n this._animatables[0].stop();\n }\n this._animatables.shift();\n }\n }\n /**\n * Gets a value indicating if the user is moving the camera\n */\n get isUserIsMoving() {\n if (!this._attachedCamera) {\n return false;\n }\n return (this._attachedCamera.inertialAlphaOffset !== 0 ||\n this._attachedCamera.inertialBetaOffset !== 0 ||\n this._attachedCamera.inertialRadiusOffset !== 0 ||\n this._attachedCamera.inertialPanningX !== 0 ||\n this._attachedCamera.inertialPanningY !== 0 ||\n this._isPointerDown);\n }\n}\n/**\n * The easing function used by animations\n */\nFramingBehavior.EasingFunction = new ExponentialEase();\n/**\n * The easing mode used by animations\n */\nFramingBehavior.EasingMode = EasingFunction.EASINGMODE_EASEINOUT;\n// Statics\n/**\n * The camera can move all the way towards the mesh.\n */\nFramingBehavior.IgnoreBoundsSizeMode = 0;\n/**\n * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides\n */\nFramingBehavior.FitFrustumSidesMode = 1;\n//# sourceMappingURL=framingBehavior.js.map","import { ArrayTools } from \"../Misc/arrayTools.js\";\nimport { Matrix, Vector3, TmpVectors } from \"../Maths/math.vector.js\";\nimport { PickingInfo } from \"../Collisions/pickingInfo.js\";\nimport { IntersectionInfo } from \"../Collisions/intersectionInfo.js\";\nimport { Scene } from \"../scene.js\";\nimport { Camera } from \"../Cameras/camera.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n/**\n * Class representing a ray with position and direction\n */\nexport class Ray {\n /**\n * Creates a new ray\n * @param origin origin point\n * @param direction direction\n * @param length length of the ray\n */\n constructor(\n /** origin point */\n origin, \n /** direction */\n direction, \n /** length of the ray */\n length = Number.MAX_VALUE) {\n this.origin = origin;\n this.direction = direction;\n this.length = length;\n }\n // Methods\n /**\n * Clone the current ray\n * @returns a new ray\n */\n clone() {\n return new Ray(this.origin.clone(), this.direction.clone(), this.length);\n }\n /**\n * Checks if the ray intersects a box\n * This does not account for the ray length by design to improve perfs.\n * @param minimum bound of the box\n * @param maximum bound of the box\n * @param intersectionTreshold extra extend to be added to the box in all direction\n * @returns if the box was hit\n */\n intersectsBoxMinMax(minimum, maximum, intersectionTreshold = 0) {\n const newMinimum = Ray._TmpVector3[0].copyFromFloats(minimum.x - intersectionTreshold, minimum.y - intersectionTreshold, minimum.z - intersectionTreshold);\n const newMaximum = Ray._TmpVector3[1].copyFromFloats(maximum.x + intersectionTreshold, maximum.y + intersectionTreshold, maximum.z + intersectionTreshold);\n let d = 0.0;\n let maxValue = Number.MAX_VALUE;\n let inv;\n let min;\n let max;\n let temp;\n if (Math.abs(this.direction.x) < 0.0000001) {\n if (this.origin.x < newMinimum.x || this.origin.x > newMaximum.x) {\n return false;\n }\n }\n else {\n inv = 1.0 / this.direction.x;\n min = (newMinimum.x - this.origin.x) * inv;\n max = (newMaximum.x - this.origin.x) * inv;\n if (max === -Infinity) {\n max = Infinity;\n }\n if (min > max) {\n temp = min;\n min = max;\n max = temp;\n }\n d = Math.max(min, d);\n maxValue = Math.min(max, maxValue);\n if (d > maxValue) {\n return false;\n }\n }\n if (Math.abs(this.direction.y) < 0.0000001) {\n if (this.origin.y < newMinimum.y || this.origin.y > newMaximum.y) {\n return false;\n }\n }\n else {\n inv = 1.0 / this.direction.y;\n min = (newMinimum.y - this.origin.y) * inv;\n max = (newMaximum.y - this.origin.y) * inv;\n if (max === -Infinity) {\n max = Infinity;\n }\n if (min > max) {\n temp = min;\n min = max;\n max = temp;\n }\n d = Math.max(min, d);\n maxValue = Math.min(max, maxValue);\n if (d > maxValue) {\n return false;\n }\n }\n if (Math.abs(this.direction.z) < 0.0000001) {\n if (this.origin.z < newMinimum.z || this.origin.z > newMaximum.z) {\n return false;\n }\n }\n else {\n inv = 1.0 / this.direction.z;\n min = (newMinimum.z - this.origin.z) * inv;\n max = (newMaximum.z - this.origin.z) * inv;\n if (max === -Infinity) {\n max = Infinity;\n }\n if (min > max) {\n temp = min;\n min = max;\n max = temp;\n }\n d = Math.max(min, d);\n maxValue = Math.min(max, maxValue);\n if (d > maxValue) {\n return false;\n }\n }\n return true;\n }\n /**\n * Checks if the ray intersects a box\n * This does not account for the ray lenght by design to improve perfs.\n * @param box the bounding box to check\n * @param intersectionTreshold extra extend to be added to the BoundingBox in all direction\n * @returns if the box was hit\n */\n intersectsBox(box, intersectionTreshold = 0) {\n return this.intersectsBoxMinMax(box.minimum, box.maximum, intersectionTreshold);\n }\n /**\n * If the ray hits a sphere\n * @param sphere the bounding sphere to check\n * @param intersectionTreshold extra extend to be added to the BoundingSphere in all direction\n * @returns true if it hits the sphere\n */\n intersectsSphere(sphere, intersectionTreshold = 0) {\n const x = sphere.center.x - this.origin.x;\n const y = sphere.center.y - this.origin.y;\n const z = sphere.center.z - this.origin.z;\n const pyth = x * x + y * y + z * z;\n const radius = sphere.radius + intersectionTreshold;\n const rr = radius * radius;\n if (pyth <= rr) {\n return true;\n }\n const dot = x * this.direction.x + y * this.direction.y + z * this.direction.z;\n if (dot < 0.0) {\n return false;\n }\n const temp = pyth - dot * dot;\n return temp <= rr;\n }\n /**\n * If the ray hits a triange\n * @param vertex0 triangle vertex\n * @param vertex1 triangle vertex\n * @param vertex2 triangle vertex\n * @returns intersection information if hit\n */\n intersectsTriangle(vertex0, vertex1, vertex2) {\n const edge1 = Ray._TmpVector3[0];\n const edge2 = Ray._TmpVector3[1];\n const pvec = Ray._TmpVector3[2];\n const tvec = Ray._TmpVector3[3];\n const qvec = Ray._TmpVector3[4];\n vertex1.subtractToRef(vertex0, edge1);\n vertex2.subtractToRef(vertex0, edge2);\n Vector3.CrossToRef(this.direction, edge2, pvec);\n const det = Vector3.Dot(edge1, pvec);\n if (det === 0) {\n return null;\n }\n const invdet = 1 / det;\n this.origin.subtractToRef(vertex0, tvec);\n const bv = Vector3.Dot(tvec, pvec) * invdet;\n if (bv < 0 || bv > 1.0) {\n return null;\n }\n Vector3.CrossToRef(tvec, edge1, qvec);\n const bw = Vector3.Dot(this.direction, qvec) * invdet;\n if (bw < 0 || bv + bw > 1.0) {\n return null;\n }\n //check if the distance is longer than the predefined length.\n const distance = Vector3.Dot(edge2, qvec) * invdet;\n if (distance > this.length) {\n return null;\n }\n return new IntersectionInfo(1 - bv - bw, bv, distance);\n }\n /**\n * Checks if ray intersects a plane\n * @param plane the plane to check\n * @returns the distance away it was hit\n */\n intersectsPlane(plane) {\n let distance;\n const result1 = Vector3.Dot(plane.normal, this.direction);\n if (Math.abs(result1) < 9.99999997475243e-7) {\n return null;\n }\n else {\n const result2 = Vector3.Dot(plane.normal, this.origin);\n distance = (-plane.d - result2) / result1;\n if (distance < 0.0) {\n if (distance < -9.99999997475243e-7) {\n return null;\n }\n else {\n return 0;\n }\n }\n return distance;\n }\n }\n /**\n * Calculate the intercept of a ray on a given axis\n * @param axis to check 'x' | 'y' | 'z'\n * @param offset from axis interception (i.e. an offset of 1y is intercepted above ground)\n * @returns a vector containing the coordinates where 'axis' is equal to zero (else offset), or null if there is no intercept.\n */\n intersectsAxis(axis, offset = 0) {\n switch (axis) {\n case \"y\": {\n const t = (this.origin.y - offset) / this.direction.y;\n if (t > 0) {\n return null;\n }\n return new Vector3(this.origin.x + this.direction.x * -t, offset, this.origin.z + this.direction.z * -t);\n }\n case \"x\": {\n const t = (this.origin.x - offset) / this.direction.x;\n if (t > 0) {\n return null;\n }\n return new Vector3(offset, this.origin.y + this.direction.y * -t, this.origin.z + this.direction.z * -t);\n }\n case \"z\": {\n const t = (this.origin.z - offset) / this.direction.z;\n if (t > 0) {\n return null;\n }\n return new Vector3(this.origin.x + this.direction.x * -t, this.origin.y + this.direction.y * -t, offset);\n }\n default:\n return null;\n }\n }\n /**\n * Checks if ray intersects a mesh. The ray is defined in WORLD space. A mesh triangle can be picked both from its front and back sides,\n * irrespective of orientation.\n * @param mesh the mesh to check\n * @param fastCheck defines if the first intersection will be used (and not the closest)\n * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected\n * @param onlyBoundingInfo defines a boolean indicating if picking should only happen using bounding info (false by default)\n * @param worldToUse defines the world matrix to use to get the world coordinate of the intersection point\n * @param skipBoundingInfo a boolean indicating if we should skip the bounding info check\n * @returns picking info of the intersection\n */\n intersectsMesh(mesh, fastCheck, trianglePredicate, onlyBoundingInfo = false, worldToUse, skipBoundingInfo = false) {\n const tm = TmpVectors.Matrix[0];\n mesh.getWorldMatrix().invertToRef(tm);\n if (this._tmpRay) {\n Ray.TransformToRef(this, tm, this._tmpRay);\n }\n else {\n this._tmpRay = Ray.Transform(this, tm);\n }\n return mesh.intersects(this._tmpRay, fastCheck, trianglePredicate, onlyBoundingInfo, worldToUse, skipBoundingInfo);\n }\n /**\n * Checks if ray intersects a mesh\n * @param meshes the meshes to check\n * @param fastCheck defines if the first intersection will be used (and not the closest)\n * @param results array to store result in\n * @returns Array of picking infos\n */\n intersectsMeshes(meshes, fastCheck, results) {\n if (results) {\n results.length = 0;\n }\n else {\n results = [];\n }\n for (let i = 0; i < meshes.length; i++) {\n const pickInfo = this.intersectsMesh(meshes[i], fastCheck);\n if (pickInfo.hit) {\n results.push(pickInfo);\n }\n }\n results.sort(this._comparePickingInfo);\n return results;\n }\n _comparePickingInfo(pickingInfoA, pickingInfoB) {\n if (pickingInfoA.distance < pickingInfoB.distance) {\n return -1;\n }\n else if (pickingInfoA.distance > pickingInfoB.distance) {\n return 1;\n }\n else {\n return 0;\n }\n }\n /**\n * Intersection test between the ray and a given segment within a given tolerance (threshold)\n * @param sega the first point of the segment to test the intersection against\n * @param segb the second point of the segment to test the intersection against\n * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful\n * @returns the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection\n */\n intersectionSegment(sega, segb, threshold) {\n const o = this.origin;\n const u = TmpVectors.Vector3[0];\n const rsegb = TmpVectors.Vector3[1];\n const v = TmpVectors.Vector3[2];\n const w = TmpVectors.Vector3[3];\n segb.subtractToRef(sega, u);\n this.direction.scaleToRef(Ray._Rayl, v);\n o.addToRef(v, rsegb);\n sega.subtractToRef(o, w);\n const a = Vector3.Dot(u, u); // always >= 0\n const b = Vector3.Dot(u, v);\n const c = Vector3.Dot(v, v); // always >= 0\n const d = Vector3.Dot(u, w);\n const e = Vector3.Dot(v, w);\n const D = a * c - b * b; // always >= 0\n let sN, sD = D; // sc = sN / sD, default sD = D >= 0\n let tN, tD = D; // tc = tN / tD, default tD = D >= 0\n // compute the line parameters of the two closest points\n if (D < Ray._Smallnum) {\n // the lines are almost parallel\n sN = 0.0; // force using point P0 on segment S1\n sD = 1.0; // to prevent possible division by 0.0 later\n tN = e;\n tD = c;\n }\n else {\n // get the closest points on the infinite lines\n sN = b * e - c * d;\n tN = a * e - b * d;\n if (sN < 0.0) {\n // sc < 0 => the s=0 edge is visible\n sN = 0.0;\n tN = e;\n tD = c;\n }\n else if (sN > sD) {\n // sc > 1 => the s=1 edge is visible\n sN = sD;\n tN = e + b;\n tD = c;\n }\n }\n if (tN < 0.0) {\n // tc < 0 => the t=0 edge is visible\n tN = 0.0;\n // recompute sc for this edge\n if (-d < 0.0) {\n sN = 0.0;\n }\n else if (-d > a) {\n sN = sD;\n }\n else {\n sN = -d;\n sD = a;\n }\n }\n else if (tN > tD) {\n // tc > 1 => the t=1 edge is visible\n tN = tD;\n // recompute sc for this edge\n if (-d + b < 0.0) {\n sN = 0;\n }\n else if (-d + b > a) {\n sN = sD;\n }\n else {\n sN = -d + b;\n sD = a;\n }\n }\n // finally do the division to get sc and tc\n const sc = Math.abs(sN) < Ray._Smallnum ? 0.0 : sN / sD;\n const tc = Math.abs(tN) < Ray._Smallnum ? 0.0 : tN / tD;\n // get the difference of the two closest points\n const qtc = TmpVectors.Vector3[4];\n v.scaleToRef(tc, qtc);\n const qsc = TmpVectors.Vector3[5];\n u.scaleToRef(sc, qsc);\n qsc.addInPlace(w);\n const dP = TmpVectors.Vector3[6];\n qsc.subtractToRef(qtc, dP); // = S1(sc) - S2(tc)\n const isIntersected = tc > 0 && tc <= this.length && dP.lengthSquared() < threshold * threshold; // return intersection result\n if (isIntersected) {\n return qsc.length();\n }\n return -1;\n }\n /**\n * Update the ray from viewport position\n * @param x position\n * @param y y position\n * @param viewportWidth viewport width\n * @param viewportHeight viewport height\n * @param world world matrix\n * @param view view matrix\n * @param projection projection matrix\n * @param enableDistantPicking defines if picking should handle large values for mesh position/scaling (false by default)\n * @returns this ray updated\n */\n update(x, y, viewportWidth, viewportHeight, world, view, projection, enableDistantPicking = false) {\n if (enableDistantPicking) {\n // With world matrices having great values (like 8000000000 on 1 or more scaling or position axis),\n // multiplying view/projection/world and doing invert will result in loss of float precision in the matrix.\n // One way to fix it is to compute the ray with world at identity then transform the ray in object space.\n // This is slower (2 matrix inverts instead of 1) but precision is preserved.\n // This is hidden behind `EnableDistantPicking` flag (default is false)\n if (!Ray._RayDistant) {\n Ray._RayDistant = Ray.Zero();\n }\n Ray._RayDistant.unprojectRayToRef(x, y, viewportWidth, viewportHeight, Matrix.IdentityReadOnly, view, projection);\n const tm = TmpVectors.Matrix[0];\n world.invertToRef(tm);\n Ray.TransformToRef(Ray._RayDistant, tm, this);\n }\n else {\n this.unprojectRayToRef(x, y, viewportWidth, viewportHeight, world, view, projection);\n }\n return this;\n }\n // Statics\n /**\n * Creates a ray with origin and direction of 0,0,0\n * @returns the new ray\n */\n static Zero() {\n return new Ray(Vector3.Zero(), Vector3.Zero());\n }\n /**\n * Creates a new ray from screen space and viewport\n * @param x position\n * @param y y position\n * @param viewportWidth viewport width\n * @param viewportHeight viewport height\n * @param world world matrix\n * @param view view matrix\n * @param projection projection matrix\n * @returns new ray\n */\n static CreateNew(x, y, viewportWidth, viewportHeight, world, view, projection) {\n const result = Ray.Zero();\n return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);\n }\n /**\n * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be\n * transformed to the given world matrix.\n * @param origin The origin point\n * @param end The end point\n * @param world a matrix to transform the ray to. Default is the identity matrix.\n * @returns the new ray\n */\n static CreateNewFromTo(origin, end, world = Matrix.IdentityReadOnly) {\n const direction = end.subtract(origin);\n const length = Math.sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z);\n direction.normalize();\n return Ray.Transform(new Ray(origin, direction, length), world);\n }\n /**\n * Transforms a ray by a matrix\n * @param ray ray to transform\n * @param matrix matrix to apply\n * @returns the resulting new ray\n */\n static Transform(ray, matrix) {\n const result = new Ray(new Vector3(0, 0, 0), new Vector3(0, 0, 0));\n Ray.TransformToRef(ray, matrix, result);\n return result;\n }\n /**\n * Transforms a ray by a matrix\n * @param ray ray to transform\n * @param matrix matrix to apply\n * @param result ray to store result in\n */\n static TransformToRef(ray, matrix, result) {\n Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);\n Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);\n result.length = ray.length;\n const dir = result.direction;\n const len = dir.length();\n if (!(len === 0 || len === 1)) {\n const num = 1.0 / len;\n dir.x *= num;\n dir.y *= num;\n dir.z *= num;\n result.length *= len;\n }\n }\n /**\n * Unproject a ray from screen space to object space\n * @param sourceX defines the screen space x coordinate to use\n * @param sourceY defines the screen space y coordinate to use\n * @param viewportWidth defines the current width of the viewport\n * @param viewportHeight defines the current height of the viewport\n * @param world defines the world matrix to use (can be set to Identity to go to world space)\n * @param view defines the view matrix to use\n * @param projection defines the projection matrix to use\n */\n unprojectRayToRef(sourceX, sourceY, viewportWidth, viewportHeight, world, view, projection) {\n var _a;\n const matrix = TmpVectors.Matrix[0];\n world.multiplyToRef(view, matrix);\n matrix.multiplyToRef(projection, matrix);\n matrix.invert();\n const nearScreenSource = TmpVectors.Vector3[0];\n nearScreenSource.x = (sourceX / viewportWidth) * 2 - 1;\n nearScreenSource.y = -((sourceY / viewportHeight) * 2 - 1);\n nearScreenSource.z = ((_a = EngineStore.LastCreatedEngine) === null || _a === void 0 ? void 0 : _a.isNDCHalfZRange) ? 0 : -1;\n // far Z need to be close but < to 1 or camera projection matrix with maxZ = 0 will NaN\n const farScreenSource = TmpVectors.Vector3[1].copyFromFloats(nearScreenSource.x, nearScreenSource.y, 1.0 - 1e-8);\n const nearVec3 = TmpVectors.Vector3[2];\n const farVec3 = TmpVectors.Vector3[3];\n Vector3._UnprojectFromInvertedMatrixToRef(nearScreenSource, matrix, nearVec3);\n Vector3._UnprojectFromInvertedMatrixToRef(farScreenSource, matrix, farVec3);\n this.origin.copyFrom(nearVec3);\n farVec3.subtractToRef(nearVec3, this.direction);\n this.direction.normalize();\n }\n}\nRay._TmpVector3 = ArrayTools.BuildArray(6, Vector3.Zero);\nRay._RayDistant = Ray.Zero();\nRay._Smallnum = 0.00000001;\nRay._Rayl = 10e8;\nScene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace = false) {\n const result = Ray.Zero();\n this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);\n return result;\n};\nScene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace = false, enableDistantPicking = false) {\n const engine = this.getEngine();\n if (!camera) {\n if (!this.activeCamera) {\n return this;\n }\n camera = this.activeCamera;\n }\n const cameraViewport = camera.viewport;\n const viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());\n // Moving coordinates to local viewport world\n x = x / engine.getHardwareScalingLevel() - viewport.x;\n y = y / engine.getHardwareScalingLevel() - (engine.getRenderHeight() - viewport.y - viewport.height);\n result.update(x, y, viewport.width, viewport.height, world ? world : Matrix.IdentityReadOnly, cameraViewSpace ? Matrix.IdentityReadOnly : camera.getViewMatrix(), camera.getProjectionMatrix(), enableDistantPicking);\n return this;\n};\nScene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {\n const result = Ray.Zero();\n this.createPickingRayInCameraSpaceToRef(x, y, result, camera);\n return result;\n};\nScene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {\n if (!PickingInfo) {\n return this;\n }\n const engine = this.getEngine();\n if (!camera) {\n if (!this.activeCamera) {\n throw new Error(\"Active camera not set\");\n }\n camera = this.activeCamera;\n }\n const cameraViewport = camera.viewport;\n const viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());\n const identity = Matrix.Identity();\n // Moving coordinates to local viewport world\n x = x / engine.getHardwareScalingLevel() - viewport.x;\n y = y / engine.getHardwareScalingLevel() - (engine.getRenderHeight() - viewport.y - viewport.height);\n result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());\n return this;\n};\nScene.prototype._internalPickForMesh = function (pickingInfo, rayFunction, mesh, world, fastCheck, onlyBoundingInfo, trianglePredicate, skipBoundingInfo) {\n const ray = rayFunction(world, mesh.enableDistantPicking);\n const result = mesh.intersects(ray, fastCheck, trianglePredicate, onlyBoundingInfo, world, skipBoundingInfo);\n if (!result || !result.hit) {\n return null;\n }\n if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {\n return null;\n }\n return result;\n};\nScene.prototype._internalPick = function (rayFunction, predicate, fastCheck, onlyBoundingInfo, trianglePredicate) {\n let pickingInfo = null;\n const computeWorldMatrixForCamera = !!(this.activeCameras && this.activeCameras.length > 1 && this.cameraToUseForPointers !== this.activeCamera);\n const currentCamera = this.cameraToUseForPointers || this.activeCamera;\n for (let meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {\n const mesh = this.meshes[meshIndex];\n if (predicate) {\n if (!predicate(mesh)) {\n continue;\n }\n }\n else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {\n continue;\n }\n const forceCompute = computeWorldMatrixForCamera && mesh.isWorldMatrixCameraDependent();\n const world = mesh.computeWorldMatrix(forceCompute, currentCamera);\n if (mesh.hasThinInstances && mesh.thinInstanceEnablePicking) {\n // first check if the ray intersects the whole bounding box/sphere of the mesh\n const result = this._internalPickForMesh(pickingInfo, rayFunction, mesh, world, true, true, trianglePredicate);\n if (result) {\n if (onlyBoundingInfo) {\n // the user only asked for a bounding info check so we can return\n return result;\n }\n const tmpMatrix = TmpVectors.Matrix[1];\n const thinMatrices = mesh.thinInstanceGetWorldMatrices();\n for (let index = 0; index < thinMatrices.length; index++) {\n const thinMatrix = thinMatrices[index];\n thinMatrix.multiplyToRef(world, tmpMatrix);\n const result = this._internalPickForMesh(pickingInfo, rayFunction, mesh, tmpMatrix, fastCheck, onlyBoundingInfo, trianglePredicate, true);\n if (result) {\n pickingInfo = result;\n pickingInfo.thinInstanceIndex = index;\n if (fastCheck) {\n return pickingInfo;\n }\n }\n }\n }\n }\n else {\n const result = this._internalPickForMesh(pickingInfo, rayFunction, mesh, world, fastCheck, onlyBoundingInfo, trianglePredicate);\n if (result) {\n pickingInfo = result;\n if (fastCheck) {\n return pickingInfo;\n }\n }\n }\n }\n return pickingInfo || new PickingInfo();\n};\nScene.prototype._internalMultiPick = function (rayFunction, predicate, trianglePredicate) {\n if (!PickingInfo) {\n return null;\n }\n const pickingInfos = new Array();\n const computeWorldMatrixForCamera = !!(this.activeCameras && this.activeCameras.length > 1 && this.cameraToUseForPointers !== this.activeCamera);\n const currentCamera = this.cameraToUseForPointers || this.activeCamera;\n for (let meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {\n const mesh = this.meshes[meshIndex];\n if (predicate) {\n if (!predicate(mesh)) {\n continue;\n }\n }\n else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {\n continue;\n }\n const forceCompute = computeWorldMatrixForCamera && mesh.isWorldMatrixCameraDependent();\n const world = mesh.computeWorldMatrix(forceCompute, currentCamera);\n if (mesh.hasThinInstances && mesh.thinInstanceEnablePicking) {\n const result = this._internalPickForMesh(null, rayFunction, mesh, world, true, true, trianglePredicate);\n if (result) {\n const tmpMatrix = TmpVectors.Matrix[1];\n const thinMatrices = mesh.thinInstanceGetWorldMatrices();\n for (let index = 0; index < thinMatrices.length; index++) {\n const thinMatrix = thinMatrices[index];\n thinMatrix.multiplyToRef(world, tmpMatrix);\n const result = this._internalPickForMesh(null, rayFunction, mesh, tmpMatrix, false, false, trianglePredicate, true);\n if (result) {\n result.thinInstanceIndex = index;\n pickingInfos.push(result);\n }\n }\n }\n }\n else {\n const result = this._internalPickForMesh(null, rayFunction, mesh, world, false, false, trianglePredicate);\n if (result) {\n pickingInfos.push(result);\n }\n }\n }\n return pickingInfos;\n};\nScene.prototype.pickWithBoundingInfo = function (x, y, predicate, fastCheck, camera) {\n if (!PickingInfo) {\n return null;\n }\n const result = this._internalPick((world) => {\n if (!this._tempPickingRay) {\n this._tempPickingRay = Ray.Zero();\n }\n this.createPickingRayToRef(x, y, world, this._tempPickingRay, camera || null);\n return this._tempPickingRay;\n }, predicate, fastCheck, true);\n if (result) {\n result.ray = this.createPickingRay(x, y, Matrix.Identity(), camera || null);\n }\n return result;\n};\nObject.defineProperty(Scene.prototype, \"_pickingAvailable\", {\n get: () => true,\n enumerable: false,\n configurable: false,\n});\nScene.prototype.pick = function (x, y, predicate, fastCheck, camera, trianglePredicate, _enableDistantPicking = false) {\n const result = this._internalPick((world, enableDistantPicking) => {\n if (!this._tempPickingRay) {\n this._tempPickingRay = Ray.Zero();\n }\n this.createPickingRayToRef(x, y, world, this._tempPickingRay, camera || null, false, enableDistantPicking);\n return this._tempPickingRay;\n }, predicate, fastCheck, false, trianglePredicate);\n if (result) {\n result.ray = this.createPickingRay(x, y, Matrix.Identity(), camera || null);\n }\n return result;\n};\nScene.prototype.pickWithRay = function (ray, predicate, fastCheck, trianglePredicate) {\n const result = this._internalPick((world) => {\n if (!this._pickWithRayInverseMatrix) {\n this._pickWithRayInverseMatrix = Matrix.Identity();\n }\n world.invertToRef(this._pickWithRayInverseMatrix);\n if (!this._cachedRayForTransform) {\n this._cachedRayForTransform = Ray.Zero();\n }\n Ray.TransformToRef(ray, this._pickWithRayInverseMatrix, this._cachedRayForTransform);\n return this._cachedRayForTransform;\n }, predicate, fastCheck, false, trianglePredicate);\n if (result) {\n result.ray = ray;\n }\n return result;\n};\nScene.prototype.multiPick = function (x, y, predicate, camera, trianglePredicate) {\n return this._internalMultiPick((world) => this.createPickingRay(x, y, world, camera || null), predicate, trianglePredicate);\n};\nScene.prototype.multiPickWithRay = function (ray, predicate, trianglePredicate) {\n return this._internalMultiPick((world) => {\n if (!this._pickWithRayInverseMatrix) {\n this._pickWithRayInverseMatrix = Matrix.Identity();\n }\n world.invertToRef(this._pickWithRayInverseMatrix);\n if (!this._cachedRayForTransform) {\n this._cachedRayForTransform = Ray.Zero();\n }\n Ray.TransformToRef(ray, this._pickWithRayInverseMatrix, this._cachedRayForTransform);\n return this._cachedRayForTransform;\n }, predicate, trianglePredicate);\n};\nCamera.prototype.getForwardRay = function (length = 100, transform, origin) {\n return this.getForwardRayToRef(new Ray(Vector3.Zero(), Vector3.Zero(), length), length, transform, origin);\n};\nCamera.prototype.getForwardRayToRef = function (refRay, length = 100, transform, origin) {\n if (!transform) {\n transform = this.getWorldMatrix();\n }\n refRay.length = length;\n if (!origin) {\n refRay.origin.copyFrom(this.position);\n }\n else {\n refRay.origin.copyFrom(origin);\n }\n TmpVectors.Vector3[2].set(0, 0, this._scene.useRightHandedSystem ? -1 : 1);\n Vector3.TransformNormalToRef(TmpVectors.Vector3[2], transform, TmpVectors.Vector3[3]);\n Vector3.NormalizeToRef(TmpVectors.Vector3[3], refRay.direction);\n return refRay;\n};\n//# sourceMappingURL=ray.js.map","import { Vector3, Matrix } from \"../Maths/math.vector.js\";\n/**\n * Class containing a set of static utilities functions for managing Pivots\n * @internal\n */\nexport class PivotTools {\n /**\n * @internal\n */\n static _RemoveAndStorePivotPoint(mesh) {\n if (mesh && PivotTools._PivotCached === 0) {\n // Save old pivot and set pivot to 0,0,0\n mesh.getPivotPointToRef(PivotTools._OldPivotPoint);\n PivotTools._PivotPostMultiplyPivotMatrix = mesh._postMultiplyPivotMatrix;\n if (!PivotTools._OldPivotPoint.equalsToFloats(0, 0, 0)) {\n mesh.setPivotMatrix(Matrix.IdentityReadOnly);\n PivotTools._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), PivotTools._PivotTranslation);\n PivotTools._PivotTmpVector.copyFromFloats(1, 1, 1);\n PivotTools._PivotTmpVector.subtractInPlace(mesh.scaling);\n PivotTools._PivotTmpVector.multiplyInPlace(PivotTools._PivotTranslation);\n mesh.position.addInPlace(PivotTools._PivotTmpVector);\n }\n }\n PivotTools._PivotCached++;\n }\n /**\n * @internal\n */\n static _RestorePivotPoint(mesh) {\n if (mesh && !PivotTools._OldPivotPoint.equalsToFloats(0, 0, 0) && PivotTools._PivotCached === 1) {\n mesh.setPivotPoint(PivotTools._OldPivotPoint);\n mesh._postMultiplyPivotMatrix = PivotTools._PivotPostMultiplyPivotMatrix;\n PivotTools._PivotTmpVector.copyFromFloats(1, 1, 1);\n PivotTools._PivotTmpVector.subtractInPlace(mesh.scaling);\n PivotTools._PivotTmpVector.multiplyInPlace(PivotTools._PivotTranslation);\n mesh.position.subtractInPlace(PivotTools._PivotTmpVector);\n }\n this._PivotCached--;\n }\n}\n// Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)\n// store/remove pivot point should only be applied during their outermost calls\nPivotTools._PivotCached = 0;\nPivotTools._OldPivotPoint = new Vector3();\nPivotTools._PivotTranslation = new Vector3();\nPivotTools._PivotTmpVector = new Vector3();\nPivotTools._PivotPostMultiplyPivotMatrix = false;\n//# sourceMappingURL=pivotTools.js.map","import { Mesh } from \"../mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n/**\n * Creates the VertexData for a Plane\n * @param options an object used to set the following optional parameters for the plane, required but can be empty\n * * size sets the width and height of the plane to the value of size, optional default 1\n * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size\n * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.size\n * @param options.width\n * @param options.height\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the box\n */\nexport function CreatePlaneVertexData(options) {\n const indices = [];\n const positions = [];\n const normals = [];\n const uvs = [];\n const width = options.width || options.size || 1;\n const height = options.height || options.size || 1;\n const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;\n // Vertices\n const halfWidth = width / 2.0;\n const halfHeight = height / 2.0;\n positions.push(-halfWidth, -halfHeight, 0);\n normals.push(0, 0, -1.0);\n uvs.push(0.0, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 : 0.0);\n positions.push(halfWidth, -halfHeight, 0);\n normals.push(0, 0, -1.0);\n uvs.push(1.0, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 : 0.0);\n positions.push(halfWidth, halfHeight, 0);\n normals.push(0, 0, -1.0);\n uvs.push(1.0, CompatibilityOptions.UseOpenGLOrientationForUV ? 0.0 : 1.0);\n positions.push(-halfWidth, halfHeight, 0);\n normals.push(0, 0, -1.0);\n uvs.push(0.0, CompatibilityOptions.UseOpenGLOrientationForUV ? 0.0 : 1.0);\n // Indices\n indices.push(0);\n indices.push(1);\n indices.push(2);\n indices.push(0);\n indices.push(2);\n indices.push(3);\n // Sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Result\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n}\n/**\n * Creates a plane mesh\n * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)\n * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)\n * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.size\n * @param options.width\n * @param options.height\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.updatable\n * @param options.sourcePlane\n * @param scene defines the hosting scene\n * @returns the plane mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#plane\n */\nexport function CreatePlane(name, options = {}, scene = null) {\n const plane = new Mesh(name, scene);\n options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n plane._originalBuilderSideOrientation = options.sideOrientation;\n const vertexData = CreatePlaneVertexData(options);\n vertexData.applyToMesh(plane, options.updatable);\n if (options.sourcePlane) {\n plane.translate(options.sourcePlane.normal, -options.sourcePlane.d);\n plane.setDirection(options.sourcePlane.normal.scale(-1));\n }\n return plane;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use the function directly from the module\n */\nexport const PlaneBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreatePlane,\n};\nVertexData.CreatePlane = CreatePlaneVertexData;\nMesh.CreatePlane = (name, size, scene, updatable, sideOrientation) => {\n const options = {\n size,\n width: size,\n height: size,\n sideOrientation,\n updatable,\n };\n return CreatePlane(name, options, scene);\n};\n//# sourceMappingURL=planeBuilder.js.map","import { Mesh } from \"../../Meshes/mesh.js\";\nimport { Scene } from \"../../scene.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { PointerEventTypes } from \"../../Events/pointerEvents.js\";\nimport { Ray } from \"../../Culling/ray.js\";\nimport { PivotTools } from \"../../Misc/pivotTools.js\";\nimport { CreatePlane } from \"../../Meshes/Builders/planeBuilder.js\";\n/**\n * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events\n */\nexport class PointerDragBehavior {\n /**\n * Get or set the currentDraggingPointerId\n * @deprecated Please use currentDraggingPointerId instead\n */\n get currentDraggingPointerID() {\n return this.currentDraggingPointerId;\n }\n set currentDraggingPointerID(currentDraggingPointerID) {\n this.currentDraggingPointerId = currentDraggingPointerID;\n }\n /**\n * If the drag behavior will react to drag events (Default: true)\n */\n set enabled(value) {\n if (value != this._enabled) {\n this.onEnabledObservable.notifyObservers(value);\n }\n this._enabled = value;\n }\n get enabled() {\n return this._enabled;\n }\n /**\n * Gets the options used by the behavior\n */\n get options() {\n return this._options;\n }\n /**\n * Sets the options used by the behavior\n */\n set options(options) {\n this._options = options;\n }\n /**\n * Creates a pointer drag behavior that can be attached to a mesh\n * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)\n * @param options.dragAxis\n * @param options.dragPlaneNormal\n */\n constructor(options) {\n this._useAlternatePickedPointAboveMaxDragAngleDragSpeed = -1.1;\n this._activeDragButton = -1;\n /**\n * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0)\n */\n this.maxDragAngle = 0;\n /**\n * Butttons that can be used to initiate a drag\n */\n this.dragButtons = [0, 1, 2];\n /**\n * @internal\n */\n this._useAlternatePickedPointAboveMaxDragAngle = false;\n /**\n * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)\n */\n this.currentDraggingPointerId = -1;\n /**\n * If the behavior is currently in a dragging state\n */\n this.dragging = false;\n /**\n * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)\n */\n this.dragDeltaRatio = 0.2;\n /**\n * If the drag plane orientation should be updated during the dragging (Default: true)\n */\n this.updateDragPlane = true;\n // Debug mode will display drag planes to help visualize behavior\n this._debugMode = false;\n this._moving = false;\n /**\n * Fires each time the attached mesh is dragged with the pointer\n * * delta between last drag position and current drag position in world space\n * * dragDistance along the drag axis\n * * dragPlaneNormal normal of the current drag plane used during the drag\n * * dragPlanePoint in world space where the drag intersects the drag plane\n *\n * (if validatedDrag is used, the position of the attached mesh might not equal dragPlanePoint)\n */\n this.onDragObservable = new Observable();\n /**\n * Fires each time a drag begins (eg. mouse down on mesh)\n * * dragPlanePoint in world space where the drag intersects the drag plane\n *\n * (if validatedDrag is used, the position of the attached mesh might not equal dragPlanePoint)\n */\n this.onDragStartObservable = new Observable();\n /**\n * Fires each time a drag ends (eg. mouse release after drag)\n * * dragPlanePoint in world space where the drag intersects the drag plane\n *\n * (if validatedDrag is used, the position of the attached mesh might not equal dragPlanePoint)\n */\n this.onDragEndObservable = new Observable();\n /**\n * Fires each time behavior enabled state changes\n */\n this.onEnabledObservable = new Observable();\n /**\n * If the attached mesh should be moved when dragged\n */\n this.moveAttached = true;\n this._enabled = true;\n /**\n * If pointer events should start and release the drag (Default: true)\n */\n this.startAndReleaseDragOnPointerEvents = true;\n /**\n * If camera controls should be detached during the drag\n */\n this.detachCameraControls = true;\n /**\n * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)\n */\n this.useObjectOrientationForDragging = true;\n /**\n * Predicate to determine if it is valid to move the object to a new position when it is moved\n * @param targetPosition\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this.validateDrag = (targetPosition) => {\n return true;\n };\n this._tmpVector = new Vector3(0, 0, 0);\n this._alternatePickedPoint = new Vector3(0, 0, 0);\n this._worldDragAxis = new Vector3(0, 0, 0);\n this._targetPosition = new Vector3(0, 0, 0);\n this._attachedToElement = false;\n this._startDragRay = new Ray(new Vector3(), new Vector3());\n this._lastPointerRay = {};\n this._dragDelta = new Vector3();\n // Variables to avoid instantiation in the below method\n this._pointA = new Vector3(0, 0, 0);\n this._pointC = new Vector3(0, 0, 0);\n this._localAxis = new Vector3(0, 0, 0);\n this._lookAt = new Vector3(0, 0, 0);\n this._options = options ? options : {};\n let optionCount = 0;\n if (this._options.dragAxis) {\n optionCount++;\n }\n if (this._options.dragPlaneNormal) {\n optionCount++;\n }\n if (optionCount > 1) {\n throw \"Multiple drag modes specified in dragBehavior options. Only one expected\";\n }\n }\n /**\n * The name of the behavior\n */\n get name() {\n return \"PointerDrag\";\n }\n /**\n * Initializes the behavior\n */\n init() { }\n /**\n * Attaches the drag behavior the passed in mesh\n * @param ownerNode The mesh that will be dragged around once attached\n * @param predicate Predicate to use for pick filtering\n */\n attach(ownerNode, predicate) {\n this._scene = ownerNode.getScene();\n ownerNode.isNearGrabbable = true;\n this.attachedNode = ownerNode;\n // Initialize drag plane to not interfere with existing scene\n if (!PointerDragBehavior._PlaneScene) {\n if (this._debugMode) {\n PointerDragBehavior._PlaneScene = this._scene;\n }\n else {\n PointerDragBehavior._PlaneScene = new Scene(this._scene.getEngine(), { virtual: true });\n PointerDragBehavior._PlaneScene.detachControl();\n this._scene.onDisposeObservable.addOnce(() => {\n PointerDragBehavior._PlaneScene.dispose();\n PointerDragBehavior._PlaneScene = null;\n });\n }\n }\n this._dragPlane = CreatePlane(\"pointerDragPlane\", { size: this._debugMode ? 1 : 10000, updatable: false, sideOrientation: Mesh.DOUBLESIDE }, PointerDragBehavior._PlaneScene);\n // State of the drag\n this.lastDragPosition = new Vector3(0, 0, 0);\n const pickPredicate = predicate\n ? predicate\n : (m) => {\n return this.attachedNode == m || m.isDescendantOf(this.attachedNode);\n };\n this._pointerObserver = this._scene.onPointerObservable.add((pointerInfo) => {\n if (!this.enabled) {\n // If behavior is disabled before releaseDrag is ever called, call it now.\n if (this._attachedToElement) {\n this.releaseDrag();\n }\n return;\n }\n if (pointerInfo.type == PointerEventTypes.POINTERDOWN) {\n if (this.startAndReleaseDragOnPointerEvents &&\n !this.dragging &&\n pointerInfo.pickInfo &&\n pointerInfo.pickInfo.hit &&\n pointerInfo.pickInfo.pickedMesh &&\n pointerInfo.pickInfo.pickedPoint &&\n pointerInfo.pickInfo.ray &&\n pickPredicate(pointerInfo.pickInfo.pickedMesh)) {\n if (this._activeDragButton === -1 && this.dragButtons.indexOf(pointerInfo.event.button) !== -1) {\n this._activeDragButton = pointerInfo.event.button;\n this._activePointerInfo = pointerInfo;\n this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);\n }\n }\n }\n else if (pointerInfo.type == PointerEventTypes.POINTERUP) {\n if (this.startAndReleaseDragOnPointerEvents &&\n this.currentDraggingPointerId == pointerInfo.event.pointerId &&\n (this._activeDragButton === pointerInfo.event.button || this._activeDragButton === -1)) {\n this.releaseDrag();\n }\n }\n else if (pointerInfo.type == PointerEventTypes.POINTERMOVE) {\n const pointerId = pointerInfo.event.pointerId;\n // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved\n if (this.currentDraggingPointerId === PointerDragBehavior._AnyMouseId && pointerId !== PointerDragBehavior._AnyMouseId) {\n const evt = pointerInfo.event;\n const isMouseEvent = evt.pointerType === \"mouse\" || (!this._scene.getEngine().hostInformation.isMobile && evt instanceof MouseEvent);\n if (isMouseEvent) {\n if (this._lastPointerRay[this.currentDraggingPointerId]) {\n this._lastPointerRay[pointerId] = this._lastPointerRay[this.currentDraggingPointerId];\n delete this._lastPointerRay[this.currentDraggingPointerId];\n }\n this.currentDraggingPointerId = pointerId;\n }\n }\n // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()\n if (!this._lastPointerRay[pointerId]) {\n this._lastPointerRay[pointerId] = new Ray(new Vector3(), new Vector3());\n }\n if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {\n this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);\n this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);\n if (this.currentDraggingPointerId == pointerId && this.dragging) {\n this._moveDrag(pointerInfo.pickInfo.ray);\n }\n }\n }\n });\n this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(() => {\n if (this._moving && this.moveAttached) {\n let needMatrixUpdate = false;\n PivotTools._RemoveAndStorePivotPoint(this.attachedNode);\n // Slowly move mesh to avoid jitter\n this._targetPosition.subtractToRef(this.attachedNode.absolutePosition, this._tmpVector);\n this._tmpVector.scaleInPlace(this.dragDeltaRatio);\n this.attachedNode.getAbsolutePosition().addToRef(this._tmpVector, this._tmpVector);\n if (this.validateDrag(this._tmpVector)) {\n this.attachedNode.setAbsolutePosition(this._tmpVector);\n needMatrixUpdate = true;\n }\n PivotTools._RestorePivotPoint(this.attachedNode);\n if (needMatrixUpdate) {\n this.attachedNode.computeWorldMatrix();\n }\n }\n });\n }\n /**\n * Force release the drag action by code.\n */\n releaseDrag() {\n if (this.dragging) {\n this.dragging = false;\n this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerId, pointerInfo: this._activePointerInfo });\n }\n this.currentDraggingPointerId = -1;\n this._activeDragButton = -1;\n this._activePointerInfo = null;\n this._moving = false;\n // Reattach camera controls\n if (this.detachCameraControls && this._attachedToElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {\n if (this._scene.activeCamera.getClassName() === \"ArcRotateCamera\") {\n const arcRotateCamera = this._scene.activeCamera;\n arcRotateCamera.attachControl(arcRotateCamera.inputs ? arcRotateCamera.inputs.noPreventDefault : true, arcRotateCamera._useCtrlForPanning, arcRotateCamera._panningMouseButton);\n }\n else {\n this._scene.activeCamera.attachControl(this._scene.activeCamera.inputs ? this._scene.activeCamera.inputs.noPreventDefault : true);\n }\n this._attachedToElement = false;\n }\n }\n /**\n * Simulates the start of a pointer drag event on the behavior\n * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)\n * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)\n * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)\n */\n startDrag(pointerId = PointerDragBehavior._AnyMouseId, fromRay, startPickedPoint) {\n this._startDrag(pointerId, fromRay, startPickedPoint);\n let lastRay = this._lastPointerRay[pointerId];\n if (pointerId === PointerDragBehavior._AnyMouseId) {\n lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];\n }\n if (lastRay) {\n // if there was a last pointer ray drag the object there\n this._moveDrag(lastRay);\n }\n }\n _startDrag(pointerId, fromRay, startPickedPoint) {\n if (!this._scene.activeCamera || this.dragging || !this.attachedNode) {\n return;\n }\n PivotTools._RemoveAndStorePivotPoint(this.attachedNode);\n // Create start ray from the camera to the object\n if (fromRay) {\n this._startDragRay.direction.copyFrom(fromRay.direction);\n this._startDragRay.origin.copyFrom(fromRay.origin);\n }\n else {\n this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);\n this.attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);\n this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);\n }\n this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);\n const pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);\n if (pickedPoint) {\n this.dragging = true;\n this.currentDraggingPointerId = pointerId;\n this.lastDragPosition.copyFrom(pickedPoint);\n this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerId, pointerInfo: this._activePointerInfo });\n this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition());\n // Detatch camera controls\n if (this.detachCameraControls && this._scene.activeCamera && this._scene.activeCamera.inputs && !this._scene.activeCamera.leftCamera) {\n if (this._scene.activeCamera.inputs.attachedToElement) {\n this._scene.activeCamera.detachControl();\n this._attachedToElement = true;\n }\n else {\n this._attachedToElement = false;\n }\n }\n }\n else {\n this.releaseDrag();\n }\n PivotTools._RestorePivotPoint(this.attachedNode);\n }\n _moveDrag(ray) {\n this._moving = true;\n const pickedPoint = this._pickWithRayOnDragPlane(ray);\n if (pickedPoint) {\n PivotTools._RemoveAndStorePivotPoint(this.attachedNode);\n if (this.updateDragPlane) {\n this._updateDragPlanePosition(ray, pickedPoint);\n }\n let dragLength = 0;\n // depending on the drag mode option drag accordingly\n if (this._options.dragAxis) {\n // Convert local drag axis to world if useObjectOrientationForDragging\n this.useObjectOrientationForDragging\n ? Vector3.TransformCoordinatesToRef(this._options.dragAxis, this.attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis)\n : this._worldDragAxis.copyFrom(this._options.dragAxis);\n // Project delta drag from the drag plane onto the drag axis\n pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);\n dragLength = Vector3.Dot(this._tmpVector, this._worldDragAxis);\n this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);\n }\n else {\n dragLength = this._dragDelta.length();\n pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);\n }\n this._targetPosition.addInPlace(this._dragDelta);\n this.onDragObservable.notifyObservers({\n dragDistance: dragLength,\n delta: this._dragDelta,\n dragPlanePoint: pickedPoint,\n dragPlaneNormal: this._dragPlane.forward,\n pointerId: this.currentDraggingPointerId,\n pointerInfo: this._activePointerInfo,\n });\n this.lastDragPosition.copyFrom(pickedPoint);\n PivotTools._RestorePivotPoint(this.attachedNode);\n }\n }\n _pickWithRayOnDragPlane(ray) {\n if (!ray) {\n return null;\n }\n // Calculate angle between plane normal and ray\n let angle = Math.acos(Vector3.Dot(this._dragPlane.forward, ray.direction));\n // Correct if ray is casted from oposite side\n if (angle > Math.PI / 2) {\n angle = Math.PI - angle;\n }\n // If the angle is too perpendicular to the plane pick another point on the plane where it is looking\n if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {\n if (this._useAlternatePickedPointAboveMaxDragAngle) {\n // Invert ray direction along the towards object axis\n this._tmpVector.copyFrom(ray.direction);\n this.attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);\n this._alternatePickedPoint.normalize();\n this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed * Vector3.Dot(this._alternatePickedPoint, this._tmpVector));\n this._tmpVector.addInPlace(this._alternatePickedPoint);\n // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point\n const dot = Vector3.Dot(this._dragPlane.forward, this._tmpVector);\n this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);\n this._alternatePickedPoint.addInPlace(this._tmpVector);\n this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition);\n return this._alternatePickedPoint;\n }\n else {\n return null;\n }\n }\n const pickResult = PointerDragBehavior._PlaneScene.pickWithRay(ray, (m) => {\n return m == this._dragPlane;\n });\n if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {\n return pickResult.pickedPoint;\n }\n else {\n return null;\n }\n }\n // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera\n _updateDragPlanePosition(ray, dragPlanePosition) {\n this._pointA.copyFrom(dragPlanePosition);\n if (this._options.dragAxis) {\n this.useObjectOrientationForDragging\n ? Vector3.TransformCoordinatesToRef(this._options.dragAxis, this.attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis)\n : this._localAxis.copyFrom(this._options.dragAxis);\n // Calculate plane normal that is the cross product of local axis and (eye-dragPlanePosition)\n ray.origin.subtractToRef(this._pointA, this._pointC);\n this._pointC.normalize();\n if (Math.abs(Vector3.Dot(this._localAxis, this._pointC)) > 0.999) {\n // the drag axis is colinear with the (eye to position) ray. The cross product will give jittered values.\n // A new axis vector need to be computed\n if (Math.abs(Vector3.Dot(Vector3.UpReadOnly, this._pointC)) > 0.999) {\n this._lookAt.copyFrom(Vector3.Right());\n }\n else {\n this._lookAt.copyFrom(Vector3.UpReadOnly);\n }\n }\n else {\n Vector3.CrossToRef(this._localAxis, this._pointC, this._lookAt);\n // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendicular to camera\n Vector3.CrossToRef(this._localAxis, this._lookAt, this._lookAt);\n this._lookAt.normalize();\n }\n this._dragPlane.position.copyFrom(this._pointA);\n this._pointA.addToRef(this._lookAt, this._lookAt);\n this._dragPlane.lookAt(this._lookAt);\n }\n else if (this._options.dragPlaneNormal) {\n this.useObjectOrientationForDragging\n ? Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this.attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis)\n : this._localAxis.copyFrom(this._options.dragPlaneNormal);\n this._dragPlane.position.copyFrom(this._pointA);\n this._pointA.addToRef(this._localAxis, this._lookAt);\n this._dragPlane.lookAt(this._lookAt);\n }\n else {\n this._dragPlane.position.copyFrom(this._pointA);\n this._dragPlane.lookAt(ray.origin);\n }\n // Update the position of the drag plane so it doesn't get out of sync with the node (eg. when moving back and forth quickly)\n this._dragPlane.position.copyFrom(this.attachedNode.getAbsolutePosition());\n this._dragPlane.computeWorldMatrix(true);\n }\n /**\n * Detaches the behavior from the mesh\n */\n detach() {\n this._lastPointerRay = {};\n if (this.attachedNode) {\n this.attachedNode.isNearGrabbable = false;\n }\n if (this._pointerObserver) {\n this._scene.onPointerObservable.remove(this._pointerObserver);\n }\n if (this._beforeRenderObserver) {\n this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);\n }\n if (this._dragPlane) {\n this._dragPlane.dispose();\n }\n this.releaseDrag();\n }\n}\nPointerDragBehavior._AnyMouseId = -2;\n//# sourceMappingURL=pointerDragBehavior.js.map","import { Tools } from \"../Misc/tools.js\";\n/**\n * A list of the currently available features without referencing them\n */\nexport class WebXRFeatureName {\n}\n/**\n * The name of the anchor system feature\n */\nWebXRFeatureName.ANCHOR_SYSTEM = \"xr-anchor-system\";\n/**\n * The name of the background remover feature\n */\nWebXRFeatureName.BACKGROUND_REMOVER = \"xr-background-remover\";\n/**\n * The name of the hit test feature\n */\nWebXRFeatureName.HIT_TEST = \"xr-hit-test\";\n/**\n * The name of the mesh detection feature\n */\nWebXRFeatureName.MESH_DETECTION = \"xr-mesh-detection\";\n/**\n * physics impostors for xr controllers feature\n */\nWebXRFeatureName.PHYSICS_CONTROLLERS = \"xr-physics-controller\";\n/**\n * The name of the plane detection feature\n */\nWebXRFeatureName.PLANE_DETECTION = \"xr-plane-detection\";\n/**\n * The name of the pointer selection feature\n */\nWebXRFeatureName.POINTER_SELECTION = \"xr-controller-pointer-selection\";\n/**\n * The name of the teleportation feature\n */\nWebXRFeatureName.TELEPORTATION = \"xr-controller-teleportation\";\n/**\n * The name of the feature points feature.\n */\nWebXRFeatureName.FEATURE_POINTS = \"xr-feature-points\";\n/**\n * The name of the hand tracking feature.\n */\nWebXRFeatureName.HAND_TRACKING = \"xr-hand-tracking\";\n/**\n * The name of the image tracking feature\n */\nWebXRFeatureName.IMAGE_TRACKING = \"xr-image-tracking\";\n/**\n * The name of the near interaction feature\n */\nWebXRFeatureName.NEAR_INTERACTION = \"xr-near-interaction\";\n/**\n * The name of the DOM overlay feature\n */\nWebXRFeatureName.DOM_OVERLAY = \"xr-dom-overlay\";\n/**\n * The name of the movement feature\n */\nWebXRFeatureName.MOVEMENT = \"xr-controller-movement\";\n/**\n * The name of the light estimation feature\n */\nWebXRFeatureName.LIGHT_ESTIMATION = \"xr-light-estimation\";\n/**\n * The name of the eye tracking feature\n */\nWebXRFeatureName.EYE_TRACKING = \"xr-eye-tracking\";\n/**\n * The name of the walking locomotion feature\n */\nWebXRFeatureName.WALKING_LOCOMOTION = \"xr-walking-locomotion\";\n/**\n * The name of the composition layers feature\n */\nWebXRFeatureName.LAYERS = \"xr-layers\";\n/**\n * The name of the depth sensing feature\n */\nWebXRFeatureName.DEPTH_SENSING = \"xr-depth-sensing\";\n/**\n * The name of the WebXR Space Warp feature\n */\nWebXRFeatureName.SPACE_WARP = \"xr-space-warp\";\n/**\n * The WebXR features manager is responsible of enabling or disabling features required for the current XR session.\n * It is mainly used in AR sessions.\n *\n * A feature can have a version that is defined by Babylon (and does not correspond with the webxr version).\n */\nexport class WebXRFeaturesManager {\n /**\n * constructs a new features manages.\n *\n * @param _xrSessionManager an instance of WebXRSessionManager\n */\n constructor(_xrSessionManager) {\n this._xrSessionManager = _xrSessionManager;\n this._features = {};\n // when session starts / initialized - attach\n this._xrSessionManager.onXRSessionInit.add(() => {\n this.getEnabledFeatures().forEach((featureName) => {\n const feature = this._features[featureName];\n if (feature.enabled && !feature.featureImplementation.attached && !feature.featureImplementation.disableAutoAttach) {\n this.attachFeature(featureName);\n }\n });\n });\n // when session ends - detach\n this._xrSessionManager.onXRSessionEnded.add(() => {\n this.getEnabledFeatures().forEach((featureName) => {\n const feature = this._features[featureName];\n if (feature.enabled && feature.featureImplementation.attached) {\n // detach, but don't disable!\n this.detachFeature(featureName);\n }\n });\n });\n }\n /**\n * Used to register a module. After calling this function a developer can use this feature in the scene.\n * Mainly used internally.\n *\n * @param featureName the name of the feature to register\n * @param constructorFunction the function used to construct the module\n * @param version the (babylon) version of the module\n * @param stable is that a stable version of this module\n */\n static AddWebXRFeature(featureName, constructorFunction, version = 1, stable = false) {\n this._AvailableFeatures[featureName] = this._AvailableFeatures[featureName] || { latest: version };\n if (version > this._AvailableFeatures[featureName].latest) {\n this._AvailableFeatures[featureName].latest = version;\n }\n if (stable) {\n this._AvailableFeatures[featureName].stable = version;\n }\n this._AvailableFeatures[featureName][version] = constructorFunction;\n }\n /**\n * Returns a constructor of a specific feature.\n *\n * @param featureName the name of the feature to construct\n * @param version the version of the feature to load\n * @param xrSessionManager the xrSessionManager. Used to construct the module\n * @param options optional options provided to the module.\n * @returns a function that, when called, will return a new instance of this feature\n */\n static ConstructFeature(featureName, version = 1, xrSessionManager, options) {\n const constructorFunction = this._AvailableFeatures[featureName][version];\n if (!constructorFunction) {\n // throw an error? return nothing?\n throw new Error(\"feature not found\");\n }\n return constructorFunction(xrSessionManager, options);\n }\n /**\n * Can be used to return the list of features currently registered\n *\n * @returns an Array of available features\n */\n static GetAvailableFeatures() {\n return Object.keys(this._AvailableFeatures);\n }\n /**\n * Gets the versions available for a specific feature\n * @param featureName the name of the feature\n * @returns an array with the available versions\n */\n static GetAvailableVersions(featureName) {\n return Object.keys(this._AvailableFeatures[featureName]);\n }\n /**\n * Return the latest unstable version of this feature\n * @param featureName the name of the feature to search\n * @returns the version number. if not found will return -1\n */\n static GetLatestVersionOfFeature(featureName) {\n return (this._AvailableFeatures[featureName] && this._AvailableFeatures[featureName].latest) || -1;\n }\n /**\n * Return the latest stable version of this feature\n * @param featureName the name of the feature to search\n * @returns the version number. if not found will return -1\n */\n static GetStableVersionOfFeature(featureName) {\n return (this._AvailableFeatures[featureName] && this._AvailableFeatures[featureName].stable) || -1;\n }\n /**\n * Attach a feature to the current session. Mainly used when session started to start the feature effect.\n * Can be used during a session to start a feature\n * @param featureName the name of feature to attach\n */\n attachFeature(featureName) {\n const feature = this._features[featureName];\n if (feature && feature.enabled && !feature.featureImplementation.attached) {\n feature.featureImplementation.attach();\n }\n }\n /**\n * Can be used inside a session or when the session ends to detach a specific feature\n * @param featureName the name of the feature to detach\n */\n detachFeature(featureName) {\n const feature = this._features[featureName];\n if (feature && feature.featureImplementation.attached) {\n feature.featureImplementation.detach();\n }\n }\n /**\n * Used to disable an already-enabled feature\n * The feature will be disposed and will be recreated once enabled.\n * @param featureName the feature to disable\n * @returns true if disable was successful\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n disableFeature(featureName) {\n const name = typeof featureName === \"string\" ? featureName : featureName.Name;\n const feature = this._features[name];\n if (feature && feature.enabled) {\n feature.enabled = false;\n this.detachFeature(name);\n feature.featureImplementation.dispose();\n delete this._features[name];\n return true;\n }\n return false;\n }\n /**\n * dispose this features manager\n */\n dispose() {\n this.getEnabledFeatures().forEach((feature) => {\n this.disableFeature(feature);\n });\n }\n /**\n * Enable a feature using its name and a version. This will enable it in the scene, and will be responsible to attach it when the session starts.\n * If used twice, the old version will be disposed and a new one will be constructed. This way you can re-enable with different configuration.\n *\n * @param featureName the name of the feature to load or the class of the feature\n * @param version optional version to load. if not provided the latest version will be enabled\n * @param moduleOptions options provided to the module. Ses the module documentation / constructor\n * @param attachIfPossible if set to true (default) the feature will be automatically attached, if it is currently possible\n * @param required is this feature required to the app. If set to true the session init will fail if the feature is not available.\n * @returns a new constructed feature or throws an error if feature not found or conflicts with another enabled feature.\n */\n enableFeature(\n // eslint-disable-next-line @typescript-eslint/naming-convention\n featureName, version = \"latest\", moduleOptions = {}, attachIfPossible = true, required = true) {\n const name = typeof featureName === \"string\" ? featureName : featureName.Name;\n let versionToLoad = 0;\n if (typeof version === \"string\") {\n if (!version) {\n throw new Error(`Error in provided version - ${name} (${version})`);\n }\n if (version === \"stable\") {\n versionToLoad = WebXRFeaturesManager.GetStableVersionOfFeature(name);\n }\n else if (version === \"latest\") {\n versionToLoad = WebXRFeaturesManager.GetLatestVersionOfFeature(name);\n }\n else {\n // try loading the number the string represents\n versionToLoad = +version;\n }\n if (versionToLoad === -1 || isNaN(versionToLoad)) {\n throw new Error(`feature not found - ${name} (${version})`);\n }\n }\n else {\n versionToLoad = version;\n }\n // check if there is a feature conflict\n const conflictingFeature = WebXRFeaturesManager._ConflictingFeatures[name];\n if (conflictingFeature !== undefined && this.getEnabledFeatures().indexOf(conflictingFeature) !== -1) {\n throw new Error(`Feature ${name} cannot be enabled while ${conflictingFeature} is enabled.`);\n }\n // check if already initialized\n const feature = this._features[name];\n const constructFunction = WebXRFeaturesManager.ConstructFeature(name, versionToLoad, this._xrSessionManager, moduleOptions);\n if (!constructFunction) {\n // report error?\n throw new Error(`feature not found - ${name}`);\n }\n /* If the feature is already enabled, detach and dispose it, and create a new one */\n if (feature) {\n this.disableFeature(name);\n }\n const constructed = constructFunction();\n if (constructed.dependsOn) {\n const dependentsFound = constructed.dependsOn.every((featureName) => !!this._features[featureName]);\n if (!dependentsFound) {\n throw new Error(`Dependant features missing. Make sure the following features are enabled - ${constructed.dependsOn.join(\", \")}`);\n }\n }\n if (constructed.isCompatible()) {\n this._features[name] = {\n featureImplementation: constructed,\n enabled: true,\n version: versionToLoad,\n required,\n };\n if (attachIfPossible) {\n // if session started already, request and enable\n if (this._xrSessionManager.session && !this._features[name].featureImplementation.attached) {\n // enable feature\n this.attachFeature(name);\n }\n }\n else {\n // disable auto-attach when session starts\n this._features[name].featureImplementation.disableAutoAttach = true;\n }\n return this._features[name].featureImplementation;\n }\n else {\n if (required) {\n throw new Error(\"required feature not compatible\");\n }\n else {\n Tools.Warn(`Feature ${name} not compatible with the current environment/browser and was not enabled.`);\n return constructed;\n }\n }\n }\n /**\n * get the implementation of an enabled feature.\n * @param featureName the name of the feature to load\n * @returns the feature class, if found\n */\n getEnabledFeature(featureName) {\n return this._features[featureName] && this._features[featureName].featureImplementation;\n }\n /**\n * Get the list of enabled features\n * @returns an array of enabled features\n */\n getEnabledFeatures() {\n return Object.keys(this._features);\n }\n /**\n * This function will extend the session creation configuration object with enabled features.\n * If, for example, the anchors feature is enabled, it will be automatically added to the optional or required features list,\n * according to the defined \"required\" variable, provided during enableFeature call\n * @param xrSessionInit the xr Session init object to extend\n *\n * @returns an extended XRSessionInit object\n */\n async _extendXRSessionInitObject(xrSessionInit) {\n const enabledFeatures = this.getEnabledFeatures();\n for (const featureName of enabledFeatures) {\n const feature = this._features[featureName];\n const nativeName = feature.featureImplementation.xrNativeFeatureName;\n if (nativeName) {\n if (feature.required) {\n xrSessionInit.requiredFeatures = xrSessionInit.requiredFeatures || [];\n if (xrSessionInit.requiredFeatures.indexOf(nativeName) === -1) {\n xrSessionInit.requiredFeatures.push(nativeName);\n }\n }\n else {\n xrSessionInit.optionalFeatures = xrSessionInit.optionalFeatures || [];\n if (xrSessionInit.optionalFeatures.indexOf(nativeName) === -1) {\n xrSessionInit.optionalFeatures.push(nativeName);\n }\n }\n }\n if (feature.featureImplementation.getXRSessionInitExtension) {\n const extended = await feature.featureImplementation.getXRSessionInitExtension();\n xrSessionInit = Object.assign(Object.assign({}, xrSessionInit), extended);\n }\n }\n return xrSessionInit;\n }\n}\nWebXRFeaturesManager._AvailableFeatures = {};\n/**\n * The key is the feature to check and the value is the feature that conflicts.\n */\nWebXRFeaturesManager._ConflictingFeatures = {\n [WebXRFeatureName.TELEPORTATION]: WebXRFeatureName.MOVEMENT,\n [WebXRFeatureName.MOVEMENT]: WebXRFeatureName.TELEPORTATION,\n};\n//# sourceMappingURL=webXRFeaturesManager.js.map","/**\n * This is the base class for all WebXR features.\n * Since most features require almost the same resources and callbacks, this class can be used to simplify the development\n * Note that since the features manager is using the `IWebXRFeature` you are in no way obligated to use this class\n */\nexport class WebXRAbstractFeature {\n /**\n * Construct a new (abstract) WebXR feature\n * @param _xrSessionManager the xr session manager for this feature\n */\n constructor(_xrSessionManager) {\n this._xrSessionManager = _xrSessionManager;\n this._attached = false;\n this._removeOnDetach = [];\n /**\n * Is this feature disposed?\n */\n this.isDisposed = false;\n /**\n * Should auto-attach be disabled?\n */\n this.disableAutoAttach = false;\n /**\n * The name of the native xr feature name (like anchor, hit-test, or hand-tracking)\n */\n this.xrNativeFeatureName = \"\";\n }\n /**\n * Is this feature attached\n */\n get attached() {\n return this._attached;\n }\n /**\n * attach this feature\n *\n * @param force should attachment be forced (even when already attached)\n * @returns true if successful, false is failed or already attached\n */\n attach(force) {\n // do not attach a disposed feature\n if (this.isDisposed) {\n return false;\n }\n if (!force) {\n if (this.attached) {\n return false;\n }\n }\n else {\n if (this.attached) {\n // detach first, to be sure\n this.detach();\n }\n }\n this._attached = true;\n this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable, (frame) => this._onXRFrame(frame));\n return true;\n }\n /**\n * detach this feature.\n *\n * @returns true if successful, false if failed or already detached\n */\n detach() {\n if (!this._attached) {\n this.disableAutoAttach = true;\n return false;\n }\n this._attached = false;\n this._removeOnDetach.forEach((toRemove) => {\n toRemove.observable.remove(toRemove.observer);\n });\n return true;\n }\n /**\n * Dispose this feature and all of the resources attached\n */\n dispose() {\n this.detach();\n this.isDisposed = true;\n }\n /**\n * This function will be executed during before enabling the feature and can be used to not-allow enabling it.\n * Note that at this point the session has NOT started, so this is purely checking if the browser supports it\n *\n * @returns whether or not the feature is compatible in this environment\n */\n isCompatible() {\n return true;\n }\n /**\n * This is used to register callbacks that will automatically be removed when detach is called.\n * @param observable the observable to which the observer will be attached\n * @param callback the callback to register\n */\n _addNewAttachObserver(observable, callback) {\n this._removeOnDetach.push({\n observable,\n observer: observable.add(callback),\n });\n }\n}\n//# sourceMappingURL=WebXRAbstractFeature.js.map","/**\n * This is a holder class for the physics joint created by the physics plugin\n * It holds a set of functions to control the underlying joint\n * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine\n */\nexport class PhysicsJoint {\n /**\n * Initializes the physics joint\n * @param type The type of the physics joint\n * @param jointData The data for the physics joint\n */\n constructor(\n /**\n * The type of the physics joint\n */\n type, \n /**\n * The data for the physics joint\n */\n jointData) {\n this.type = type;\n this.jointData = jointData;\n jointData.nativeParams = jointData.nativeParams || {};\n }\n /**\n * Gets the physics joint\n */\n get physicsJoint() {\n return this._physicsJoint;\n }\n /**\n * Sets the physics joint\n */\n set physicsJoint(newJoint) {\n if (this._physicsJoint) {\n //remove from the world\n }\n this._physicsJoint = newJoint;\n }\n /**\n * Sets the physics plugin\n */\n set physicsPlugin(physicsPlugin) {\n this._physicsPlugin = physicsPlugin;\n }\n /**\n * Execute a function that is physics-plugin specific.\n * @param {Function} func the function that will be executed.\n * It accepts two parameters: the physics world and the physics joint\n */\n executeNativeFunction(func) {\n func(this._physicsPlugin.world, this._physicsJoint);\n }\n}\n//TODO check if the native joints are the same\n//Joint Types\n/**\n * Distance-Joint type\n */\nPhysicsJoint.DistanceJoint = 0;\n/**\n * Hinge-Joint type\n */\nPhysicsJoint.HingeJoint = 1;\n/**\n * Ball-and-Socket joint type\n */\nPhysicsJoint.BallAndSocketJoint = 2;\n/**\n * Wheel-Joint type\n */\nPhysicsJoint.WheelJoint = 3;\n/**\n * Slider-Joint type\n */\nPhysicsJoint.SliderJoint = 4;\n//OIMO\n/**\n * Prismatic-Joint type\n */\nPhysicsJoint.PrismaticJoint = 5;\n//\n/**\n * Universal-Joint type\n * ENERGY FTW! (compare with this - @see http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)\n */\nPhysicsJoint.UniversalJoint = 6;\n/**\n * Hinge-Joint 2 type\n */\nPhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;\n//Cannon\n/**\n * Point to Point Joint type. Similar to a Ball-Joint. Different in parameters\n */\nPhysicsJoint.PointToPointJoint = 8;\n//Cannon only at the moment\n/**\n * Spring-Joint type\n */\nPhysicsJoint.SpringJoint = 9;\n/**\n * Lock-Joint type\n */\nPhysicsJoint.LockJoint = 10;\n/**\n * A class representing a physics distance joint\n * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine\n */\nexport class DistanceJoint extends PhysicsJoint {\n /**\n *\n * @param jointData The data for the Distance-Joint\n */\n constructor(jointData) {\n super(PhysicsJoint.DistanceJoint, jointData);\n }\n /**\n * Update the predefined distance.\n * @param maxDistance The maximum preferred distance\n * @param minDistance The minimum preferred distance\n */\n updateDistance(maxDistance, minDistance) {\n this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);\n }\n}\n/**\n * Represents a Motor-Enabled Joint\n * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine\n */\nexport class MotorEnabledJoint extends PhysicsJoint {\n /**\n * Initializes the Motor-Enabled Joint\n * @param type The type of the joint\n * @param jointData The physical joint data for the joint\n */\n constructor(type, jointData) {\n super(type, jointData);\n }\n /**\n * Set the motor values.\n * Attention, this function is plugin specific. Engines won't react 100% the same.\n * @param force the force to apply\n * @param maxForce max force for this motor.\n */\n setMotor(force, maxForce) {\n this._physicsPlugin.setMotor(this, force || 0, maxForce);\n }\n /**\n * Set the motor's limits.\n * Attention, this function is plugin specific. Engines won't react 100% the same.\n * @param upperLimit The upper limit of the motor\n * @param lowerLimit The lower limit of the motor\n */\n setLimit(upperLimit, lowerLimit) {\n this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);\n }\n}\n/**\n * This class represents a single physics Hinge-Joint\n * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine\n */\nexport class HingeJoint extends MotorEnabledJoint {\n /**\n * Initializes the Hinge-Joint\n * @param jointData The joint data for the Hinge-Joint\n */\n constructor(jointData) {\n super(PhysicsJoint.HingeJoint, jointData);\n }\n /**\n * Set the motor values.\n * Attention, this function is plugin specific. Engines won't react 100% the same.\n * @param {number} force the force to apply\n * @param {number} maxForce max force for this motor.\n */\n setMotor(force, maxForce) {\n this._physicsPlugin.setMotor(this, force || 0, maxForce);\n }\n /**\n * Set the motor's limits.\n * Attention, this function is plugin specific. Engines won't react 100% the same.\n * @param upperLimit The upper limit of the motor\n * @param lowerLimit The lower limit of the motor\n */\n setLimit(upperLimit, lowerLimit) {\n this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);\n }\n}\n/**\n * This class represents a dual hinge physics joint (same as wheel joint)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine\n */\nexport class Hinge2Joint extends MotorEnabledJoint {\n /**\n * Initializes the Hinge2-Joint\n * @param jointData The joint data for the Hinge2-Joint\n */\n constructor(jointData) {\n super(PhysicsJoint.Hinge2Joint, jointData);\n }\n /**\n * Set the motor values.\n * Attention, this function is plugin specific. Engines won't react 100% the same.\n * @param targetSpeed the speed the motor is to reach\n * @param maxForce max force for this motor.\n * @param motorIndex motor's index, 0 or 1.\n */\n setMotor(targetSpeed, maxForce, motorIndex = 0) {\n this._physicsPlugin.setMotor(this, targetSpeed || 0, maxForce, motorIndex);\n }\n /**\n * Set the motor limits.\n * Attention, this function is plugin specific. Engines won't react 100% the same.\n * @param upperLimit the upper limit\n * @param lowerLimit lower limit\n * @param motorIndex the motor's index, 0 or 1.\n */\n setLimit(upperLimit, lowerLimit, motorIndex = 0) {\n this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);\n }\n}\n//# sourceMappingURL=physicsJoint.js.map","import { Logger } from \"../../Misc/logger.js\";\nimport { ArrayTools } from \"../../Misc/arrayTools.js\";\nimport { Vector3, Quaternion } from \"../../Maths/math.vector.js\";\nimport { AbstractMesh } from \"../../Meshes/abstractMesh.js\";\nimport { Mesh } from \"../../Meshes/mesh.js\";\nimport { PhysicsJoint } from \"./physicsJoint.js\";\nimport { Space } from \"../../Maths/math.axis.js\";\nMesh._PhysicsImpostorParser = function (scene, physicObject, jsonObject) {\n return new PhysicsImpostor(physicObject, jsonObject.physicsImpostor, {\n mass: jsonObject.physicsMass,\n friction: jsonObject.physicsFriction,\n restitution: jsonObject.physicsRestitution,\n }, scene);\n};\n/**\n * Represents a physics imposter\n * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine\n */\nexport class PhysicsImpostor {\n /**\n * Specifies if the physics imposter is disposed\n */\n get isDisposed() {\n return this._isDisposed;\n }\n /**\n * Gets the mass of the physics imposter\n */\n get mass() {\n return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;\n }\n set mass(value) {\n this.setMass(value);\n }\n /**\n * Gets the coefficient of friction\n */\n get friction() {\n return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;\n }\n /**\n * Sets the coefficient of friction\n */\n set friction(value) {\n if (!this._physicsEngine) {\n return;\n }\n this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);\n }\n /**\n * Gets the coefficient of restitution\n */\n get restitution() {\n return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;\n }\n /**\n * Sets the coefficient of restitution\n */\n set restitution(value) {\n if (!this._physicsEngine) {\n return;\n }\n this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);\n }\n /**\n * Gets the pressure of a soft body; only supported by the AmmoJSPlugin\n */\n get pressure() {\n if (!this._physicsEngine) {\n return 0;\n }\n const plugin = this._physicsEngine.getPhysicsPlugin();\n if (!plugin.setBodyPressure) {\n return 0;\n }\n return plugin.getBodyPressure(this);\n }\n /**\n * Sets the pressure of a soft body; only supported by the AmmoJSPlugin\n */\n set pressure(value) {\n if (!this._physicsEngine) {\n return;\n }\n const plugin = this._physicsEngine.getPhysicsPlugin();\n if (!plugin.setBodyPressure) {\n return;\n }\n plugin.setBodyPressure(this, value);\n }\n /**\n * Gets the stiffness of a soft body; only supported by the AmmoJSPlugin\n */\n get stiffness() {\n if (!this._physicsEngine) {\n return 0;\n }\n const plugin = this._physicsEngine.getPhysicsPlugin();\n if (!plugin.getBodyStiffness) {\n return 0;\n }\n return plugin.getBodyStiffness(this);\n }\n /**\n * Sets the stiffness of a soft body; only supported by the AmmoJSPlugin\n */\n set stiffness(value) {\n if (!this._physicsEngine) {\n return;\n }\n const plugin = this._physicsEngine.getPhysicsPlugin();\n if (!plugin.setBodyStiffness) {\n return;\n }\n plugin.setBodyStiffness(this, value);\n }\n /**\n * Gets the velocityIterations of a soft body; only supported by the AmmoJSPlugin\n */\n get velocityIterations() {\n if (!this._physicsEngine) {\n return 0;\n }\n const plugin = this._physicsEngine.getPhysicsPlugin();\n if (!plugin.getBodyVelocityIterations) {\n return 0;\n }\n return plugin.getBodyVelocityIterations(this);\n }\n /**\n * Sets the velocityIterations of a soft body; only supported by the AmmoJSPlugin\n */\n set velocityIterations(value) {\n if (!this._physicsEngine) {\n return;\n }\n const plugin = this._physicsEngine.getPhysicsPlugin();\n if (!plugin.setBodyVelocityIterations) {\n return;\n }\n plugin.setBodyVelocityIterations(this, value);\n }\n /**\n * Gets the positionIterations of a soft body; only supported by the AmmoJSPlugin\n */\n get positionIterations() {\n if (!this._physicsEngine) {\n return 0;\n }\n const plugin = this._physicsEngine.getPhysicsPlugin();\n if (!plugin.getBodyPositionIterations) {\n return 0;\n }\n return plugin.getBodyPositionIterations(this);\n }\n /**\n * Sets the positionIterations of a soft body; only supported by the AmmoJSPlugin\n */\n set positionIterations(value) {\n if (!this._physicsEngine) {\n return;\n }\n const plugin = this._physicsEngine.getPhysicsPlugin();\n if (!plugin.setBodyPositionIterations) {\n return;\n }\n plugin.setBodyPositionIterations(this, value);\n }\n /**\n * Initializes the physics imposter\n * @param object The physics-enabled object used as the physics imposter\n * @param type The type of the physics imposter. Types are available as static members of this class.\n * @param _options The options for the physics imposter\n * @param _scene The Babylon scene\n */\n constructor(\n /**\n * The physics-enabled object used as the physics imposter\n */\n object, \n /**\n * The type of the physics imposter\n */\n type, _options = { mass: 0 }, _scene) {\n this.object = object;\n this.type = type;\n this._options = _options;\n this._scene = _scene;\n /** @internal */\n this._pluginData = {};\n this._bodyUpdateRequired = false;\n this._onBeforePhysicsStepCallbacks = new Array();\n this._onAfterPhysicsStepCallbacks = new Array();\n /** @internal */\n this._onPhysicsCollideCallbacks = [];\n this._deltaPosition = Vector3.Zero();\n this._isDisposed = false;\n /**\n * @internal\n */\n this.soft = false;\n /**\n * @internal\n */\n this.segments = 0;\n //temp variables for parent rotation calculations\n //private _mats: Array = [new Matrix(), new Matrix()];\n this._tmpQuat = new Quaternion();\n this._tmpQuat2 = new Quaternion();\n /**\n * this function is executed by the physics engine.\n */\n this.beforeStep = () => {\n if (!this._physicsEngine) {\n return;\n }\n this.object.translate(this._deltaPosition, -1);\n this._deltaRotationConjugated &&\n this.object.rotationQuaternion &&\n this.object.rotationQuaternion.multiplyToRef(this._deltaRotationConjugated, this.object.rotationQuaternion);\n this.object.computeWorldMatrix(false);\n if (this.object.parent && this.object.rotationQuaternion) {\n this.getParentsRotation();\n this._tmpQuat.multiplyToRef(this.object.rotationQuaternion, this._tmpQuat);\n }\n else {\n this._tmpQuat.copyFrom(this.object.rotationQuaternion || new Quaternion());\n }\n if (!this._options.disableBidirectionalTransformation) {\n this.object.rotationQuaternion &&\n this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this, /*bInfo.boundingBox.centerWorld*/ this.object.getAbsolutePosition(), this._tmpQuat);\n }\n this._onBeforePhysicsStepCallbacks.forEach((func) => {\n func(this);\n });\n };\n /**\n * this function is executed by the physics engine\n */\n this.afterStep = () => {\n if (!this._physicsEngine) {\n return;\n }\n this._onAfterPhysicsStepCallbacks.forEach((func) => {\n func(this);\n });\n this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(this);\n // object has now its world rotation. needs to be converted to local.\n if (this.object.parent && this.object.rotationQuaternion) {\n this.getParentsRotation();\n this._tmpQuat.conjugateInPlace();\n this._tmpQuat.multiplyToRef(this.object.rotationQuaternion, this.object.rotationQuaternion);\n }\n // take the position set and make it the absolute position of this object.\n this.object.setAbsolutePosition(this.object.position);\n if (this._deltaRotation) {\n this.object.rotationQuaternion && this.object.rotationQuaternion.multiplyToRef(this._deltaRotation, this.object.rotationQuaternion);\n this._deltaPosition.applyRotationQuaternionToRef(this._deltaRotation, PhysicsImpostor._TmpVecs[0]);\n this.object.translate(PhysicsImpostor._TmpVecs[0], 1);\n }\n else {\n this.object.translate(this._deltaPosition, 1);\n }\n this.object.computeWorldMatrix(true);\n };\n /**\n * Legacy collision detection event support\n */\n this.onCollideEvent = null;\n /**\n *\n * @param e\n * @returns\n */\n this.onCollide = (e) => {\n if (!this._onPhysicsCollideCallbacks.length && !this.onCollideEvent) {\n return;\n }\n if (!this._physicsEngine) {\n return;\n }\n const otherImpostor = this._physicsEngine.getImpostorWithPhysicsBody(e.body);\n if (otherImpostor) {\n // Legacy collision detection event support\n if (this.onCollideEvent) {\n this.onCollideEvent(this, otherImpostor);\n }\n this._onPhysicsCollideCallbacks\n .filter((obj) => {\n return obj.otherImpostors.indexOf(otherImpostor) !== -1;\n })\n .forEach((obj) => {\n obj.callback(this, otherImpostor, e.point, e.distance, e.impulse, e.normal);\n });\n }\n };\n //sanity check!\n if (!this.object) {\n Logger.Error(\"No object was provided. A physics object is obligatory\");\n return;\n }\n if (this.object.parent && _options.mass !== 0) {\n Logger.Warn(\"A physics impostor has been created for an object which has a parent. Babylon physics currently works in local space so unexpected issues may occur.\");\n }\n // Legacy support for old syntax.\n if (!this._scene && object.getScene) {\n this._scene = object.getScene();\n }\n if (!this._scene) {\n return;\n }\n if (this.type > 100) {\n this.soft = true;\n }\n this._physicsEngine = this._scene.getPhysicsEngine();\n if (!this._physicsEngine) {\n Logger.Error(\"Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.\");\n }\n else {\n //set the object's quaternion, if not set\n if (!this.object.rotationQuaternion) {\n if (this.object.rotation) {\n this.object.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);\n }\n else {\n this.object.rotationQuaternion = new Quaternion();\n }\n }\n //default options params\n this._options.mass = _options.mass === void 0 ? 0 : _options.mass;\n this._options.friction = _options.friction === void 0 ? 0.2 : _options.friction;\n this._options.restitution = _options.restitution === void 0 ? 0.2 : _options.restitution;\n if (this.soft) {\n //softbody mass must be above 0;\n this._options.mass = this._options.mass > 0 ? this._options.mass : 1;\n this._options.pressure = _options.pressure === void 0 ? 200 : _options.pressure;\n this._options.stiffness = _options.stiffness === void 0 ? 1 : _options.stiffness;\n this._options.velocityIterations = _options.velocityIterations === void 0 ? 20 : _options.velocityIterations;\n this._options.positionIterations = _options.positionIterations === void 0 ? 20 : _options.positionIterations;\n this._options.fixedPoints = _options.fixedPoints === void 0 ? 0 : _options.fixedPoints;\n this._options.margin = _options.margin === void 0 ? 0 : _options.margin;\n this._options.damping = _options.damping === void 0 ? 0 : _options.damping;\n this._options.path = _options.path === void 0 ? null : _options.path;\n this._options.shape = _options.shape === void 0 ? null : _options.shape;\n }\n this._joints = [];\n //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.\n if (!this.object.parent || this._options.ignoreParent) {\n this._init();\n }\n else if (this.object.parent.physicsImpostor) {\n Logger.Warn(\"You must affect impostors to children before affecting impostor to parent.\");\n }\n }\n }\n /**\n * This function will completely initialize this impostor.\n * It will create a new body - but only if this mesh has no parent.\n * If it has, this impostor will not be used other than to define the impostor\n * of the child mesh.\n * @internal\n */\n _init() {\n if (!this._physicsEngine) {\n return;\n }\n this._physicsEngine.removeImpostor(this);\n this.physicsBody = null;\n this._parent = this._parent || this._getPhysicsParent();\n if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {\n this._physicsEngine.addImpostor(this);\n }\n }\n _getPhysicsParent() {\n if (this.object.parent instanceof AbstractMesh) {\n const parentMesh = this.object.parent;\n return parentMesh.physicsImpostor;\n }\n return null;\n }\n /**\n * Should a new body be generated.\n * @returns boolean specifying if body initialization is required\n */\n isBodyInitRequired() {\n return this._bodyUpdateRequired || (!this._physicsBody && (!this._parent || !!this._options.ignoreParent));\n }\n /**\n * Sets the updated scaling\n */\n setScalingUpdated() {\n this.forceUpdate();\n }\n /**\n * Force a regeneration of this or the parent's impostor's body.\n * Use with caution - This will remove all previously-instantiated joints.\n */\n forceUpdate() {\n this._init();\n if (this.parent && !this._options.ignoreParent) {\n this.parent.forceUpdate();\n }\n }\n /*public get mesh(): AbstractMesh {\n return this._mesh;\n }*/\n /**\n * Gets the body that holds this impostor. Either its own, or its parent.\n */\n get physicsBody() {\n return this._parent && !this._options.ignoreParent ? this._parent.physicsBody : this._physicsBody;\n }\n /**\n * Get the parent of the physics imposter\n * @returns Physics imposter or null\n */\n get parent() {\n return !this._options.ignoreParent && this._parent ? this._parent : null;\n }\n /**\n * Sets the parent of the physics imposter\n */\n set parent(value) {\n this._parent = value;\n }\n /**\n * Set the physics body. Used mainly by the physics engine/plugin\n */\n set physicsBody(physicsBody) {\n if (this._physicsBody && this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);\n }\n this._physicsBody = physicsBody;\n this.resetUpdateFlags();\n }\n /**\n * Resets the update flags\n */\n resetUpdateFlags() {\n this._bodyUpdateRequired = false;\n }\n /**\n * Gets the object extents\n * @returns the object extents\n */\n getObjectExtents() {\n if (this.object.getBoundingInfo) {\n const q = this.object.rotationQuaternion;\n const scaling = this.object.scaling.clone();\n //reset rotation\n this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;\n //calculate the world matrix with no rotation\n const worldMatrix = this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);\n if (worldMatrix) {\n worldMatrix.decompose(scaling, undefined, undefined);\n }\n const boundingInfo = this.object.getBoundingInfo();\n // get the global scaling of the object\n const size = boundingInfo.boundingBox.extendSize.scale(2).multiplyInPlace(scaling);\n size.x = Math.abs(size.x);\n size.y = Math.abs(size.y);\n size.z = Math.abs(size.z);\n //bring back the rotation\n this.object.rotationQuaternion = q;\n //calculate the world matrix with the new rotation\n this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);\n return size;\n }\n else {\n return PhysicsImpostor.DEFAULT_OBJECT_SIZE;\n }\n }\n /**\n * Gets the object center\n * @returns The object center\n */\n getObjectCenter() {\n if (this.object.getBoundingInfo) {\n const boundingInfo = this.object.getBoundingInfo();\n return boundingInfo.boundingBox.centerWorld;\n }\n else {\n return this.object.position;\n }\n }\n /**\n * Get a specific parameter from the options parameters\n * @param paramName The object parameter name\n * @returns The object parameter\n */\n getParam(paramName) {\n return this._options[paramName];\n }\n /**\n * Sets a specific parameter in the options given to the physics plugin\n * @param paramName The parameter name\n * @param value The value of the parameter\n */\n setParam(paramName, value) {\n this._options[paramName] = value;\n this._bodyUpdateRequired = true;\n }\n /**\n * Specifically change the body's mass. Won't recreate the physics body object\n * @param mass The mass of the physics imposter\n */\n setMass(mass) {\n if (this.getParam(\"mass\") !== mass) {\n this.setParam(\"mass\", mass);\n }\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);\n }\n }\n /**\n * Gets the linear velocity\n * @returns linear velocity or null\n */\n getLinearVelocity() {\n return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : Vector3.Zero();\n }\n /**\n * Sets the linear velocity\n * @param velocity linear velocity or null\n */\n setLinearVelocity(velocity) {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);\n }\n }\n /**\n * Gets the angular velocity\n * @returns angular velocity or null\n */\n getAngularVelocity() {\n return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : Vector3.Zero();\n }\n /**\n * Sets the angular velocity\n * @param velocity The velocity or null\n */\n setAngularVelocity(velocity) {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);\n }\n }\n /**\n * Execute a function with the physics plugin native code\n * Provide a function the will have two variables - the world object and the physics body object\n * @param func The function to execute with the physics plugin native code\n */\n executeNativeFunction(func) {\n if (this._physicsEngine) {\n func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);\n }\n }\n /**\n * Register a function that will be executed before the physics world is stepping forward\n * @param func The function to execute before the physics world is stepped forward\n */\n registerBeforePhysicsStep(func) {\n this._onBeforePhysicsStepCallbacks.push(func);\n }\n /**\n * Unregister a function that will be executed before the physics world is stepping forward\n * @param func The function to execute before the physics world is stepped forward\n */\n unregisterBeforePhysicsStep(func) {\n const index = this._onBeforePhysicsStepCallbacks.indexOf(func);\n if (index > -1) {\n this._onBeforePhysicsStepCallbacks.splice(index, 1);\n }\n else {\n Logger.Warn(\"Function to remove was not found\");\n }\n }\n /**\n * Register a function that will be executed after the physics step\n * @param func The function to execute after physics step\n */\n registerAfterPhysicsStep(func) {\n this._onAfterPhysicsStepCallbacks.push(func);\n }\n /**\n * Unregisters a function that will be executed after the physics step\n * @param func The function to execute after physics step\n */\n unregisterAfterPhysicsStep(func) {\n const index = this._onAfterPhysicsStepCallbacks.indexOf(func);\n if (index > -1) {\n this._onAfterPhysicsStepCallbacks.splice(index, 1);\n }\n else {\n Logger.Warn(\"Function to remove was not found\");\n }\n }\n /**\n * register a function that will be executed when this impostor collides against a different body\n * @param collideAgainst Physics imposter, or array of physics imposters to collide against\n * @param func Callback that is executed on collision\n */\n registerOnPhysicsCollide(collideAgainst, func) {\n const collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];\n this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });\n }\n /**\n * Unregisters the physics imposter's collision callback\n * @param collideAgainst The physics object to collide against\n * @param func Callback to execute on collision\n */\n unregisterOnPhysicsCollide(collideAgainst, func) {\n const collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];\n let index = -1;\n const found = this._onPhysicsCollideCallbacks.some((cbDef, idx) => {\n if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {\n // chcek the arrays match\n const sameList = cbDef.otherImpostors.every((impostor) => {\n return collidedAgainstList.indexOf(impostor) > -1;\n });\n if (sameList) {\n index = idx;\n }\n return sameList;\n }\n return false;\n });\n if (found) {\n this._onPhysicsCollideCallbacks.splice(index, 1);\n }\n else {\n Logger.Warn(\"Function to remove was not found\");\n }\n }\n /**\n * Get the parent rotation\n * @returns The parent rotation\n */\n getParentsRotation() {\n let parent = this.object.parent;\n this._tmpQuat.copyFromFloats(0, 0, 0, 1);\n while (parent) {\n if (parent.rotationQuaternion) {\n this._tmpQuat2.copyFrom(parent.rotationQuaternion);\n }\n else {\n Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);\n }\n this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);\n parent = parent.parent;\n }\n return this._tmpQuat;\n }\n /**\n * Apply a force\n * @param force The force to apply\n * @param contactPoint The contact point for the force\n * @returns The physics imposter\n */\n applyForce(force, contactPoint) {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);\n }\n return this;\n }\n /**\n * Apply an impulse\n * @param force The impulse force\n * @param contactPoint The contact point for the impulse force\n * @returns The physics imposter\n */\n applyImpulse(force, contactPoint) {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);\n }\n return this;\n }\n /**\n * A help function to create a joint\n * @param otherImpostor A physics imposter used to create a joint\n * @param jointType The type of joint\n * @param jointData The data for the joint\n * @returns The physics imposter\n */\n createJoint(otherImpostor, jointType, jointData) {\n const joint = new PhysicsJoint(jointType, jointData);\n this.addJoint(otherImpostor, joint);\n return this;\n }\n /**\n * Add a joint to this impostor with a different impostor\n * @param otherImpostor A physics imposter used to add a joint\n * @param joint The joint to add\n * @returns The physics imposter\n */\n addJoint(otherImpostor, joint) {\n this._joints.push({\n otherImpostor: otherImpostor,\n joint: joint,\n });\n if (this._physicsEngine) {\n this._physicsEngine.addJoint(this, otherImpostor, joint);\n }\n return this;\n }\n /**\n * Add an anchor to a cloth impostor\n * @param otherImpostor rigid impostor to anchor to\n * @param width ratio across width from 0 to 1\n * @param height ratio up height from 0 to 1\n * @param influence the elasticity between cloth impostor and anchor from 0, very stretchy to 1, little stretch\n * @param noCollisionBetweenLinkedBodies when true collisions between cloth impostor and anchor are ignored; default false\n * @returns impostor the soft imposter\n */\n addAnchor(otherImpostor, width, height, influence, noCollisionBetweenLinkedBodies) {\n if (!this._physicsEngine) {\n return this;\n }\n const plugin = this._physicsEngine.getPhysicsPlugin();\n if (!plugin.appendAnchor) {\n return this;\n }\n if (this._physicsEngine) {\n plugin.appendAnchor(this, otherImpostor, width, height, influence, noCollisionBetweenLinkedBodies);\n }\n return this;\n }\n /**\n * Add a hook to a rope impostor\n * @param otherImpostor rigid impostor to anchor to\n * @param length ratio across rope from 0 to 1\n * @param influence the elasticity between rope impostor and anchor from 0, very stretchy to 1, little stretch\n * @param noCollisionBetweenLinkedBodies when true collisions between soft impostor and anchor are ignored; default false\n * @returns impostor the rope imposter\n */\n addHook(otherImpostor, length, influence, noCollisionBetweenLinkedBodies) {\n if (!this._physicsEngine) {\n return this;\n }\n const plugin = this._physicsEngine.getPhysicsPlugin();\n if (!plugin.appendAnchor) {\n return this;\n }\n if (this._physicsEngine) {\n plugin.appendHook(this, otherImpostor, length, influence, noCollisionBetweenLinkedBodies);\n }\n return this;\n }\n /**\n * Will keep this body still, in a sleep mode.\n * @returns the physics imposter\n */\n sleep() {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().sleepBody(this);\n }\n return this;\n }\n /**\n * Wake the body up.\n * @returns The physics imposter\n */\n wakeUp() {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);\n }\n return this;\n }\n /**\n * Clones the physics imposter\n * @param newObject The physics imposter clones to this physics-enabled object\n * @returns A nullable physics imposter\n */\n clone(newObject) {\n if (!newObject) {\n return null;\n }\n return new PhysicsImpostor(newObject, this.type, this._options, this._scene);\n }\n /**\n * Disposes the physics imposter\n */\n dispose( /*disposeChildren: boolean = true*/) {\n //no dispose if no physics engine is available.\n if (!this._physicsEngine) {\n return;\n }\n this._joints.forEach((j) => {\n if (this._physicsEngine) {\n this._physicsEngine.removeJoint(this, j.otherImpostor, j.joint);\n }\n });\n //dispose the physics body\n this._physicsEngine.removeImpostor(this);\n if (this.parent) {\n this.parent.forceUpdate();\n }\n else {\n /*this._object.getChildMeshes().forEach(function(mesh) {\n if (mesh.physicsImpostor) {\n if (disposeChildren) {\n mesh.physicsImpostor.dispose();\n mesh.physicsImpostor = null;\n }\n }\n })*/\n }\n this._isDisposed = true;\n }\n /**\n * Sets the delta position\n * @param position The delta position amount\n */\n setDeltaPosition(position) {\n this._deltaPosition.copyFrom(position);\n }\n /**\n * Sets the delta rotation\n * @param rotation The delta rotation amount\n */\n setDeltaRotation(rotation) {\n if (!this._deltaRotation) {\n this._deltaRotation = new Quaternion();\n }\n this._deltaRotation.copyFrom(rotation);\n this._deltaRotationConjugated = this._deltaRotation.conjugate();\n }\n /**\n * Gets the box size of the physics imposter and stores the result in the input parameter\n * @param result Stores the box size\n * @returns The physics imposter\n */\n getBoxSizeToRef(result) {\n if (this._physicsEngine) {\n this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);\n }\n return this;\n }\n /**\n * Gets the radius of the physics imposter\n * @returns Radius of the physics imposter\n */\n getRadius() {\n return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;\n }\n /**\n * Sync a bone with this impostor\n * @param bone The bone to sync to the impostor.\n * @param boneMesh The mesh that the bone is influencing.\n * @param jointPivot The pivot of the joint / bone in local space.\n * @param distToJoint Optional distance from the impostor to the joint.\n * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.\n */\n syncBoneWithImpostor(bone, boneMesh, jointPivot, distToJoint, adjustRotation) {\n const tempVec = PhysicsImpostor._TmpVecs[0];\n const mesh = this.object;\n if (mesh.rotationQuaternion) {\n if (adjustRotation) {\n const tempQuat = PhysicsImpostor._TmpQuat;\n mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);\n bone.setRotationQuaternion(tempQuat, Space.WORLD, boneMesh);\n }\n else {\n bone.setRotationQuaternion(mesh.rotationQuaternion, Space.WORLD, boneMesh);\n }\n }\n tempVec.x = 0;\n tempVec.y = 0;\n tempVec.z = 0;\n if (jointPivot) {\n tempVec.x = jointPivot.x;\n tempVec.y = jointPivot.y;\n tempVec.z = jointPivot.z;\n bone.getDirectionToRef(tempVec, boneMesh, tempVec);\n if (distToJoint === undefined || distToJoint === null) {\n distToJoint = jointPivot.length();\n }\n tempVec.x *= distToJoint;\n tempVec.y *= distToJoint;\n tempVec.z *= distToJoint;\n }\n if (bone.getParent()) {\n tempVec.addInPlace(mesh.getAbsolutePosition());\n bone.setAbsolutePosition(tempVec, boneMesh);\n }\n else {\n boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());\n boneMesh.position.x -= tempVec.x;\n boneMesh.position.y -= tempVec.y;\n boneMesh.position.z -= tempVec.z;\n }\n }\n /**\n * Sync impostor to a bone\n * @param bone The bone that the impostor will be synced to.\n * @param boneMesh The mesh that the bone is influencing.\n * @param jointPivot The pivot of the joint / bone in local space.\n * @param distToJoint Optional distance from the impostor to the joint.\n * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.\n * @param boneAxis Optional vector3 axis the bone is aligned with\n */\n syncImpostorWithBone(bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {\n const mesh = this.object;\n if (mesh.rotationQuaternion) {\n if (adjustRotation) {\n const tempQuat = PhysicsImpostor._TmpQuat;\n bone.getRotationQuaternionToRef(Space.WORLD, boneMesh, tempQuat);\n tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);\n }\n else {\n bone.getRotationQuaternionToRef(Space.WORLD, boneMesh, mesh.rotationQuaternion);\n }\n }\n const pos = PhysicsImpostor._TmpVecs[0];\n const boneDir = PhysicsImpostor._TmpVecs[1];\n if (!boneAxis) {\n boneAxis = PhysicsImpostor._TmpVecs[2];\n boneAxis.x = 0;\n boneAxis.y = 1;\n boneAxis.z = 0;\n }\n bone.getDirectionToRef(boneAxis, boneMesh, boneDir);\n bone.getAbsolutePositionToRef(boneMesh, pos);\n if ((distToJoint === undefined || distToJoint === null) && jointPivot) {\n distToJoint = jointPivot.length();\n }\n if (distToJoint !== undefined && distToJoint !== null) {\n pos.x += boneDir.x * distToJoint;\n pos.y += boneDir.y * distToJoint;\n pos.z += boneDir.z * distToJoint;\n }\n mesh.setAbsolutePosition(pos);\n }\n}\n/**\n * The default object size of the imposter\n */\nPhysicsImpostor.DEFAULT_OBJECT_SIZE = new Vector3(1, 1, 1);\n/**\n * The identity quaternion of the imposter\n */\nPhysicsImpostor.IDENTITY_QUATERNION = Quaternion.Identity();\nPhysicsImpostor._TmpVecs = ArrayTools.BuildArray(3, Vector3.Zero);\nPhysicsImpostor._TmpQuat = Quaternion.Identity();\n//Impostor types\n/**\n * No-Imposter type\n */\nPhysicsImpostor.NoImpostor = 0;\n/**\n * Sphere-Imposter type\n */\nPhysicsImpostor.SphereImpostor = 1;\n/**\n * Box-Imposter type\n */\nPhysicsImpostor.BoxImpostor = 2;\n/**\n * Plane-Imposter type\n */\nPhysicsImpostor.PlaneImpostor = 3;\n/**\n * Mesh-imposter type (Only available to objects with vertices data)\n */\nPhysicsImpostor.MeshImpostor = 4;\n/**\n * Capsule-Impostor type (Ammo.js plugin only)\n */\nPhysicsImpostor.CapsuleImpostor = 6;\n/**\n * Cylinder-Imposter type\n */\nPhysicsImpostor.CylinderImpostor = 7;\n/**\n * Particle-Imposter type\n */\nPhysicsImpostor.ParticleImpostor = 8;\n/**\n * Heightmap-Imposter type\n */\nPhysicsImpostor.HeightmapImpostor = 9;\n/**\n * ConvexHull-Impostor type (Ammo.js plugin only)\n */\nPhysicsImpostor.ConvexHullImpostor = 10;\n/**\n * Custom-Imposter type (Ammo.js plugin only)\n */\nPhysicsImpostor.CustomImpostor = 100;\n/**\n * Rope-Imposter type\n */\nPhysicsImpostor.RopeImpostor = 101;\n/**\n * Cloth-Imposter type\n */\nPhysicsImpostor.ClothImpostor = 102;\n/**\n * Softbody-Imposter type\n */\nPhysicsImpostor.SoftbodyImpostor = 103;\n//# sourceMappingURL=physicsImpostor.js.map","import { Tools } from \"../Misc/tools.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Scene } from \"../scene.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { Logger } from \"../Misc/logger.js\";\n\nimport { SceneLoaderFlags } from \"./sceneLoaderFlags.js\";\nimport { IsBase64DataUrl } from \"../Misc/fileTools.js\";\nimport { RuntimeError, ErrorCodes } from \"../Misc/error.js\";\n/**\n * Mode that determines how to handle old animation groups before loading new ones.\n */\nexport var SceneLoaderAnimationGroupLoadingMode;\n(function (SceneLoaderAnimationGroupLoadingMode) {\n /**\n * Reset all old animations to initial state then dispose them.\n */\n SceneLoaderAnimationGroupLoadingMode[SceneLoaderAnimationGroupLoadingMode[\"Clean\"] = 0] = \"Clean\";\n /**\n * Stop all old animations.\n */\n SceneLoaderAnimationGroupLoadingMode[SceneLoaderAnimationGroupLoadingMode[\"Stop\"] = 1] = \"Stop\";\n /**\n * Restart old animations from first frame.\n */\n SceneLoaderAnimationGroupLoadingMode[SceneLoaderAnimationGroupLoadingMode[\"Sync\"] = 2] = \"Sync\";\n /**\n * Old animations remains untouched.\n */\n SceneLoaderAnimationGroupLoadingMode[SceneLoaderAnimationGroupLoadingMode[\"NoSync\"] = 3] = \"NoSync\";\n})(SceneLoaderAnimationGroupLoadingMode || (SceneLoaderAnimationGroupLoadingMode = {}));\n/**\n * Class used to load scene from various file formats using registered plugins\n * @see https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes\n */\nexport class SceneLoader {\n /**\n * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data\n */\n static get ForceFullSceneLoadingForIncremental() {\n return SceneLoaderFlags.ForceFullSceneLoadingForIncremental;\n }\n static set ForceFullSceneLoadingForIncremental(value) {\n SceneLoaderFlags.ForceFullSceneLoadingForIncremental = value;\n }\n /**\n * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene\n */\n static get ShowLoadingScreen() {\n return SceneLoaderFlags.ShowLoadingScreen;\n }\n static set ShowLoadingScreen(value) {\n SceneLoaderFlags.ShowLoadingScreen = value;\n }\n /**\n * Defines the current logging level (while loading the scene)\n * @ignorenaming\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static get loggingLevel() {\n return SceneLoaderFlags.loggingLevel;\n }\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static set loggingLevel(value) {\n SceneLoaderFlags.loggingLevel = value;\n }\n /**\n * Gets or set a boolean indicating if matrix weights must be cleaned upon loading\n */\n static get CleanBoneMatrixWeights() {\n return SceneLoaderFlags.CleanBoneMatrixWeights;\n }\n static set CleanBoneMatrixWeights(value) {\n SceneLoaderFlags.CleanBoneMatrixWeights = value;\n }\n /**\n * Gets the default plugin (used to load Babylon files)\n * @returns the .babylon plugin\n */\n static GetDefaultPlugin() {\n return SceneLoader._RegisteredPlugins[\".babylon\"];\n }\n static _GetPluginForExtension(extension) {\n const registeredPlugin = SceneLoader._RegisteredPlugins[extension];\n if (registeredPlugin) {\n return registeredPlugin;\n }\n Logger.Warn(\"Unable to find a plugin to load \" +\n extension +\n \" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes\");\n return SceneLoader.GetDefaultPlugin();\n }\n static _GetPluginForDirectLoad(data) {\n for (const extension in SceneLoader._RegisteredPlugins) {\n const plugin = SceneLoader._RegisteredPlugins[extension].plugin;\n if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {\n return SceneLoader._RegisteredPlugins[extension];\n }\n }\n return SceneLoader.GetDefaultPlugin();\n }\n static _GetPluginForFilename(sceneFilename) {\n const queryStringPosition = sceneFilename.indexOf(\"?\");\n if (queryStringPosition !== -1) {\n sceneFilename = sceneFilename.substring(0, queryStringPosition);\n }\n const dotPosition = sceneFilename.lastIndexOf(\".\");\n const extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();\n return SceneLoader._GetPluginForExtension(extension);\n }\n static _GetDirectLoad(sceneFilename) {\n if (sceneFilename.substr(0, 5) === \"data:\") {\n return sceneFilename.substr(5);\n }\n return null;\n }\n static _FormatErrorMessage(fileInfo, message, exception) {\n const fromLoad = fileInfo.rawData ? \"binary data\" : fileInfo.url;\n let errorMessage = \"Unable to load from \" + fromLoad;\n if (message) {\n errorMessage += `: ${message}`;\n }\n else if (exception) {\n errorMessage += `: ${exception}`;\n }\n return errorMessage;\n }\n static _LoadData(fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension, name) {\n const directLoad = SceneLoader._GetDirectLoad(fileInfo.url);\n if (fileInfo.rawData && !pluginExtension) {\n throw \"When using ArrayBufferView to load data the file extension must be provided.\";\n }\n const registeredPlugin = pluginExtension\n ? SceneLoader._GetPluginForExtension(pluginExtension)\n : directLoad\n ? SceneLoader._GetPluginForDirectLoad(fileInfo.url)\n : SceneLoader._GetPluginForFilename(fileInfo.url);\n if (fileInfo.rawData && !registeredPlugin.isBinary) {\n throw \"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.\";\n }\n let plugin;\n if (registeredPlugin.plugin.createPlugin !== undefined) {\n plugin = registeredPlugin.plugin.createPlugin();\n }\n else {\n plugin = registeredPlugin.plugin;\n }\n if (!plugin) {\n throw \"The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.\";\n }\n SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);\n // Check if we have a direct load url. If the plugin is registered to handle\n // it or it's not a base64 data url, then pass it through the direct load path.\n if (directLoad && ((plugin.canDirectLoad && plugin.canDirectLoad(fileInfo.url)) || !IsBase64DataUrl(fileInfo.url))) {\n if (plugin.directLoad) {\n const result = plugin.directLoad(scene, directLoad);\n if (result.then) {\n result\n .then((data) => {\n onSuccess(plugin, data);\n })\n .catch((error) => {\n onError(\"Error in directLoad of _loadData: \" + error, error);\n });\n }\n else {\n onSuccess(plugin, result);\n }\n }\n else {\n onSuccess(plugin, directLoad);\n }\n return plugin;\n }\n const useArrayBuffer = registeredPlugin.isBinary;\n const dataCallback = (data, responseURL) => {\n if (scene.isDisposed) {\n onError(\"Scene has been disposed\");\n return;\n }\n onSuccess(plugin, data, responseURL);\n };\n let request = null;\n let pluginDisposed = false;\n const onDisposeObservable = plugin.onDisposeObservable;\n if (onDisposeObservable) {\n onDisposeObservable.add(() => {\n pluginDisposed = true;\n if (request) {\n request.abort();\n request = null;\n }\n onDispose();\n });\n }\n const manifestChecked = () => {\n if (pluginDisposed) {\n return;\n }\n const errorCallback = (request, exception) => {\n onError(request === null || request === void 0 ? void 0 : request.statusText, exception);\n };\n if (!plugin.loadFile && fileInfo.rawData) {\n throw \"Plugin does not support loading ArrayBufferView.\";\n }\n request = plugin.loadFile\n ? plugin.loadFile(scene, fileInfo.rawData || fileInfo.file || fileInfo.url, fileInfo.rootUrl, dataCallback, onProgress, useArrayBuffer, errorCallback, name)\n : scene._loadFile(fileInfo.file || fileInfo.url, dataCallback, onProgress, true, useArrayBuffer, errorCallback);\n };\n const engine = scene.getEngine();\n let canUseOfflineSupport = engine.enableOfflineSupport;\n if (canUseOfflineSupport) {\n // Also check for exceptions\n let exceptionFound = false;\n for (const regex of scene.disableOfflineSupportExceptionRules) {\n if (regex.test(fileInfo.url)) {\n exceptionFound = true;\n break;\n }\n }\n canUseOfflineSupport = !exceptionFound;\n }\n if (canUseOfflineSupport && Engine.OfflineProviderFactory) {\n // Checking if a manifest file has been set for this scene and if offline mode has been requested\n scene.offlineProvider = Engine.OfflineProviderFactory(fileInfo.url, manifestChecked, engine.disableManifestCheck);\n }\n else {\n manifestChecked();\n }\n return plugin;\n }\n static _GetFileInfo(rootUrl, sceneFilename) {\n let url;\n let name;\n let file = null;\n let rawData = null;\n if (!sceneFilename) {\n url = rootUrl;\n name = Tools.GetFilename(rootUrl);\n rootUrl = Tools.GetFolderPath(rootUrl);\n }\n else if (sceneFilename.name) {\n const sceneFile = sceneFilename;\n url = `file:${sceneFile.name}`;\n name = sceneFile.name;\n file = sceneFile;\n }\n else if (ArrayBuffer.isView(sceneFilename)) {\n url = \"\";\n name = \"arrayBuffer\";\n rawData = sceneFilename;\n }\n else if (typeof sceneFilename === \"string\" && sceneFilename.startsWith(\"data:\")) {\n url = sceneFilename;\n name = \"\";\n }\n else {\n const filename = sceneFilename;\n if (filename.substr(0, 1) === \"/\") {\n Tools.Error(\"Wrong sceneFilename parameter\");\n return null;\n }\n url = rootUrl + filename;\n name = filename;\n }\n return {\n url: url,\n rootUrl: rootUrl,\n name: name,\n file: file,\n rawData,\n };\n }\n // Public functions\n /**\n * Gets a plugin that can load the given extension\n * @param extension defines the extension to load\n * @returns a plugin or null if none works\n */\n static GetPluginForExtension(extension) {\n return SceneLoader._GetPluginForExtension(extension).plugin;\n }\n /**\n * Gets a boolean indicating that the given extension can be loaded\n * @param extension defines the extension to load\n * @returns true if the extension is supported\n */\n static IsPluginForExtensionAvailable(extension) {\n return !!SceneLoader._RegisteredPlugins[extension];\n }\n /**\n * Adds a new plugin to the list of registered plugins\n * @param plugin defines the plugin to add\n */\n static RegisterPlugin(plugin) {\n if (typeof plugin.extensions === \"string\") {\n const extension = plugin.extensions;\n SceneLoader._RegisteredPlugins[extension.toLowerCase()] = {\n plugin: plugin,\n isBinary: false,\n };\n }\n else {\n const extensions = plugin.extensions;\n Object.keys(extensions).forEach((extension) => {\n SceneLoader._RegisteredPlugins[extension.toLowerCase()] = {\n plugin: plugin,\n isBinary: extensions[extension].isBinary,\n };\n });\n }\n }\n /**\n * Import meshes into a scene\n * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported\n * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file or starts with \"data:\" following by the stringified version of the scene or a File object (default: empty string)\n * @param scene the instance of BABYLON.Scene to append to\n * @param onSuccess a callback with a list of imported meshes, particleSystems, skeletons, and animationGroups when import succeeds\n * @param onProgress a callback with a progress event for each file being loaded\n * @param onError a callback with the scene, a message, and possibly an exception when import fails\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded plugin\n */\n static ImportMesh(meshNames, rootUrl, sceneFilename = \"\", scene = EngineStore.LastCreatedScene, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name = \"\") {\n if (!scene) {\n Logger.Error(\"No scene available to import mesh to\");\n return null;\n }\n const fileInfo = SceneLoader._GetFileInfo(rootUrl, sceneFilename);\n if (!fileInfo) {\n return null;\n }\n const loadingToken = {};\n scene.addPendingData(loadingToken);\n const disposeHandler = () => {\n scene.removePendingData(loadingToken);\n };\n const errorHandler = (message, exception) => {\n const errorMessage = SceneLoader._FormatErrorMessage(fileInfo, message, exception);\n if (onError) {\n onError(scene, errorMessage, new RuntimeError(errorMessage, ErrorCodes.SceneLoaderError, exception));\n }\n else {\n Logger.Error(errorMessage);\n // should the exception be thrown?\n }\n disposeHandler();\n };\n const progressHandler = onProgress\n ? (event) => {\n try {\n onProgress(event);\n }\n catch (e) {\n errorHandler(\"Error in onProgress callback: \" + e, e);\n }\n }\n : undefined;\n const successHandler = (meshes, particleSystems, skeletons, animationGroups, transformNodes, geometries, lights) => {\n scene.importedMeshesFiles.push(fileInfo.url);\n if (onSuccess) {\n try {\n onSuccess(meshes, particleSystems, skeletons, animationGroups, transformNodes, geometries, lights);\n }\n catch (e) {\n errorHandler(\"Error in onSuccess callback: \" + e, e);\n }\n }\n scene.removePendingData(loadingToken);\n };\n return SceneLoader._LoadData(fileInfo, scene, (plugin, data, responseURL) => {\n if (plugin.rewriteRootURL) {\n fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);\n }\n if (plugin.importMesh) {\n const syncedPlugin = plugin;\n const meshes = new Array();\n const particleSystems = new Array();\n const skeletons = new Array();\n if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {\n return;\n }\n scene.loadingPluginName = plugin.name;\n successHandler(meshes, particleSystems, skeletons, [], [], [], []);\n }\n else {\n const asyncedPlugin = plugin;\n asyncedPlugin\n .importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name)\n .then((result) => {\n scene.loadingPluginName = plugin.name;\n successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups, result.transformNodes, result.geometries, result.lights);\n })\n .catch((error) => {\n errorHandler(error.message, error);\n });\n }\n }, progressHandler, errorHandler, disposeHandler, pluginExtension, name);\n }\n /**\n * Import meshes into a scene\n * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported\n * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file or starts with \"data:\" following by the stringified version of the scene or a File object (default: empty string)\n * @param scene the instance of BABYLON.Scene to append to\n * @param onProgress a callback with a progress event for each file being loaded\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups\n */\n static ImportMeshAsync(meshNames, rootUrl, sceneFilename = \"\", scene = EngineStore.LastCreatedScene, onProgress = null, pluginExtension = null, name = \"\") {\n return new Promise((resolve, reject) => {\n SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, (meshes, particleSystems, skeletons, animationGroups, transformNodes, geometries, lights) => {\n resolve({\n meshes: meshes,\n particleSystems: particleSystems,\n skeletons: skeletons,\n animationGroups: animationGroups,\n transformNodes: transformNodes,\n geometries: geometries,\n lights: lights,\n });\n }, onProgress, (scene, message, exception) => {\n reject(exception || new Error(message));\n }, pluginExtension, name);\n });\n }\n /**\n * Load a scene\n * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file or starts with \"data:\" following by the stringified version of the scene or a File object (default: empty string)\n * @param engine is the instance of BABYLON.Engine to use to create the scene\n * @param onSuccess a callback with the scene when import succeeds\n * @param onProgress a callback with a progress event for each file being loaded\n * @param onError a callback with the scene, a message, and possibly an exception when import fails\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded plugin\n */\n static Load(rootUrl, sceneFilename = \"\", engine = EngineStore.LastCreatedEngine, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name = \"\") {\n if (!engine) {\n Tools.Error(\"No engine available\");\n return null;\n }\n return SceneLoader.Append(rootUrl, sceneFilename, new Scene(engine), onSuccess, onProgress, onError, pluginExtension, name);\n }\n /**\n * Load a scene\n * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file or starts with \"data:\" following by the stringified version of the scene or a File object (default: empty string)\n * @param engine is the instance of BABYLON.Engine to use to create the scene\n * @param onProgress a callback with a progress event for each file being loaded\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded scene\n */\n static LoadAsync(rootUrl, sceneFilename = \"\", engine = EngineStore.LastCreatedEngine, onProgress = null, pluginExtension = null, name = \"\") {\n return new Promise((resolve, reject) => {\n SceneLoader.Load(rootUrl, sceneFilename, engine, (scene) => {\n resolve(scene);\n }, onProgress, (scene, message, exception) => {\n reject(exception || new Error(message));\n }, pluginExtension, name);\n });\n }\n /**\n * Append a scene\n * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file or starts with \"data:\" following by the stringified version of the scene or a File object (default: empty string)\n * @param scene is the instance of BABYLON.Scene to append to\n * @param onSuccess a callback with the scene when import succeeds\n * @param onProgress a callback with a progress event for each file being loaded\n * @param onError a callback with the scene, a message, and possibly an exception when import fails\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded plugin\n */\n static Append(rootUrl, sceneFilename = \"\", scene = EngineStore.LastCreatedScene, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name = \"\") {\n if (!scene) {\n Logger.Error(\"No scene available to append to\");\n return null;\n }\n const fileInfo = SceneLoader._GetFileInfo(rootUrl, sceneFilename);\n if (!fileInfo) {\n return null;\n }\n const loadingToken = {};\n scene.addPendingData(loadingToken);\n const disposeHandler = () => {\n scene.removePendingData(loadingToken);\n };\n if (SceneLoader.ShowLoadingScreen && !this._ShowingLoadingScreen) {\n this._ShowingLoadingScreen = true;\n scene.getEngine().displayLoadingUI();\n scene.executeWhenReady(() => {\n scene.getEngine().hideLoadingUI();\n this._ShowingLoadingScreen = false;\n });\n }\n const errorHandler = (message, exception) => {\n const errorMessage = SceneLoader._FormatErrorMessage(fileInfo, message, exception);\n if (onError) {\n onError(scene, errorMessage, new RuntimeError(errorMessage, ErrorCodes.SceneLoaderError, exception));\n }\n else {\n Logger.Error(errorMessage);\n // should the exception be thrown?\n }\n disposeHandler();\n };\n const progressHandler = onProgress\n ? (event) => {\n try {\n onProgress(event);\n }\n catch (e) {\n errorHandler(\"Error in onProgress callback\", e);\n }\n }\n : undefined;\n const successHandler = () => {\n if (onSuccess) {\n try {\n onSuccess(scene);\n }\n catch (e) {\n errorHandler(\"Error in onSuccess callback\", e);\n }\n }\n scene.removePendingData(loadingToken);\n };\n return SceneLoader._LoadData(fileInfo, scene, (plugin, data) => {\n if (plugin.load) {\n const syncedPlugin = plugin;\n if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {\n return;\n }\n scene.loadingPluginName = plugin.name;\n successHandler();\n }\n else {\n const asyncedPlugin = plugin;\n asyncedPlugin\n .loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name)\n .then(() => {\n scene.loadingPluginName = plugin.name;\n successHandler();\n })\n .catch((error) => {\n errorHandler(error.message, error);\n });\n }\n }, progressHandler, errorHandler, disposeHandler, pluginExtension, name);\n }\n /**\n * Append a scene\n * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file or starts with \"data:\" following by the stringified version of the scene or a File object (default: empty string)\n * @param scene is the instance of BABYLON.Scene to append to\n * @param onProgress a callback with a progress event for each file being loaded\n * @param pluginExtension the extension used to determine the plugin\n * @returns The given scene\n */\n static AppendAsync(rootUrl, sceneFilename = \"\", scene = EngineStore.LastCreatedScene, onProgress = null, pluginExtension = null, name = \"\") {\n return new Promise((resolve, reject) => {\n SceneLoader.Append(rootUrl, sceneFilename, scene, (scene) => {\n resolve(scene);\n }, onProgress, (scene, message, exception) => {\n reject(exception || new Error(message));\n }, pluginExtension, name);\n });\n }\n /**\n * Load a scene into an asset container\n * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file or starts with \"data:\" following by the stringified version of the scene or a File object (default: empty string)\n * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)\n * @param onSuccess a callback with the scene when import succeeds\n * @param onProgress a callback with a progress event for each file being loaded\n * @param onError a callback with the scene, a message, and possibly an exception when import fails\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded plugin\n */\n static LoadAssetContainer(rootUrl, sceneFilename = \"\", scene = EngineStore.LastCreatedScene, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name = \"\") {\n if (!scene) {\n Logger.Error(\"No scene available to load asset container to\");\n return null;\n }\n const fileInfo = SceneLoader._GetFileInfo(rootUrl, sceneFilename);\n if (!fileInfo) {\n return null;\n }\n const loadingToken = {};\n scene.addPendingData(loadingToken);\n const disposeHandler = () => {\n scene.removePendingData(loadingToken);\n };\n const errorHandler = (message, exception) => {\n const errorMessage = SceneLoader._FormatErrorMessage(fileInfo, message, exception);\n if (onError) {\n onError(scene, errorMessage, new RuntimeError(errorMessage, ErrorCodes.SceneLoaderError, exception));\n }\n else {\n Logger.Error(errorMessage);\n // should the exception be thrown?\n }\n disposeHandler();\n };\n const progressHandler = onProgress\n ? (event) => {\n try {\n onProgress(event);\n }\n catch (e) {\n errorHandler(\"Error in onProgress callback\", e);\n }\n }\n : undefined;\n const successHandler = (assets) => {\n if (onSuccess) {\n try {\n onSuccess(assets);\n }\n catch (e) {\n errorHandler(\"Error in onSuccess callback\", e);\n }\n }\n scene.removePendingData(loadingToken);\n };\n return SceneLoader._LoadData(fileInfo, scene, (plugin, data) => {\n if (plugin.loadAssetContainer) {\n const syncedPlugin = plugin;\n const assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);\n if (!assetContainer) {\n return;\n }\n scene.loadingPluginName = plugin.name;\n successHandler(assetContainer);\n }\n else if (plugin.loadAssetContainerAsync) {\n const asyncedPlugin = plugin;\n asyncedPlugin\n .loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name)\n .then((assetContainer) => {\n scene.loadingPluginName = plugin.name;\n successHandler(assetContainer);\n })\n .catch((error) => {\n errorHandler(error.message, error);\n });\n }\n else {\n errorHandler(\"LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.\");\n }\n }, progressHandler, errorHandler, disposeHandler, pluginExtension, name);\n }\n /**\n * Load a scene into an asset container\n * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file or starts with \"data:\" following by the stringified version of the scene (default: empty string)\n * @param scene is the instance of Scene to append to\n * @param onProgress a callback with a progress event for each file being loaded\n * @param pluginExtension the extension used to determine the plugin\n * @returns The loaded asset container\n */\n static LoadAssetContainerAsync(rootUrl, sceneFilename = \"\", scene = EngineStore.LastCreatedScene, onProgress = null, pluginExtension = null) {\n return new Promise((resolve, reject) => {\n SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, (assetContainer) => {\n resolve(assetContainer);\n }, onProgress, (scene, message, exception) => {\n reject(exception || new Error(message));\n }, pluginExtension);\n });\n }\n /**\n * Import animations from a file into a scene\n * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file or starts with \"data:\" following by the stringified version of the scene or a File object (default: empty string)\n * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)\n * @param overwriteAnimations when true, animations are cleaned before importing new ones. Animations are appended otherwise\n * @param animationGroupLoadingMode defines how to handle old animations groups before importing new ones\n * @param targetConverter defines a function used to convert animation targets from loaded scene to current scene (default: search node by name)\n * @param onSuccess a callback with the scene when import succeeds\n * @param onProgress a callback with a progress event for each file being loaded\n * @param onError a callback with the scene, a message, and possibly an exception when import fails\n * @param pluginExtension the extension used to determine the plugin\n */\n static ImportAnimations(rootUrl, sceneFilename = \"\", scene = EngineStore.LastCreatedScene, overwriteAnimations = true, animationGroupLoadingMode = SceneLoaderAnimationGroupLoadingMode.Clean, targetConverter = null, onSuccess = null, onProgress = null, onError = null, pluginExtension = null) {\n if (!scene) {\n Logger.Error(\"No scene available to load animations to\");\n return;\n }\n if (overwriteAnimations) {\n // Reset, stop and dispose all animations before loading new ones\n for (const animatable of scene.animatables) {\n animatable.reset();\n }\n scene.stopAllAnimations();\n scene.animationGroups.slice().forEach((animationGroup) => {\n animationGroup.dispose();\n });\n const nodes = scene.getNodes();\n nodes.forEach((node) => {\n if (node.animations) {\n node.animations = [];\n }\n });\n }\n else {\n switch (animationGroupLoadingMode) {\n case SceneLoaderAnimationGroupLoadingMode.Clean:\n scene.animationGroups.slice().forEach((animationGroup) => {\n animationGroup.dispose();\n });\n break;\n case SceneLoaderAnimationGroupLoadingMode.Stop:\n scene.animationGroups.forEach((animationGroup) => {\n animationGroup.stop();\n });\n break;\n case SceneLoaderAnimationGroupLoadingMode.Sync:\n scene.animationGroups.forEach((animationGroup) => {\n animationGroup.reset();\n animationGroup.restart();\n });\n break;\n case SceneLoaderAnimationGroupLoadingMode.NoSync:\n // nothing to do\n break;\n default:\n Logger.Error(\"Unknown animation group loading mode value '\" + animationGroupLoadingMode + \"'\");\n return;\n }\n }\n const startingIndexForNewAnimatables = scene.animatables.length;\n const onAssetContainerLoaded = (container) => {\n container.mergeAnimationsTo(scene, scene.animatables.slice(startingIndexForNewAnimatables), targetConverter);\n container.dispose();\n scene.onAnimationFileImportedObservable.notifyObservers(scene);\n if (onSuccess) {\n onSuccess(scene);\n }\n };\n this.LoadAssetContainer(rootUrl, sceneFilename, scene, onAssetContainerLoaded, onProgress, onError, pluginExtension);\n }\n /**\n * Import animations from a file into a scene\n * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)\n * @param sceneFilename a string that defines the name of the scene file or starts with \"data:\" following by the stringified version of the scene or a File object (default: empty string)\n * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)\n * @param overwriteAnimations when true, animations are cleaned before importing new ones. Animations are appended otherwise\n * @param animationGroupLoadingMode defines how to handle old animations groups before importing new ones\n * @param targetConverter defines a function used to convert animation targets from loaded scene to current scene (default: search node by name)\n * @param onSuccess a callback with the scene when import succeeds\n * @param onProgress a callback with a progress event for each file being loaded\n * @param onError a callback with the scene, a message, and possibly an exception when import fails\n * @param pluginExtension the extension used to determine the plugin\n * @returns the updated scene with imported animations\n */\n static ImportAnimationsAsync(rootUrl, sceneFilename = \"\", scene = EngineStore.LastCreatedScene, overwriteAnimations = true, animationGroupLoadingMode = SceneLoaderAnimationGroupLoadingMode.Clean, targetConverter = null, \n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onSuccess = null, onProgress = null, \n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onError = null, pluginExtension = null) {\n return new Promise((resolve, reject) => {\n SceneLoader.ImportAnimations(rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, (_scene) => {\n resolve(_scene);\n }, onProgress, (_scene, message, exception) => {\n reject(exception || new Error(message));\n }, pluginExtension);\n });\n }\n}\n/**\n * No logging while loading\n */\nSceneLoader.NO_LOGGING = 0;\n/**\n * Minimal logging while loading\n */\nSceneLoader.MINIMAL_LOGGING = 1;\n/**\n * Summary logging while loading\n */\nSceneLoader.SUMMARY_LOGGING = 2;\n/**\n * Detailed logging while loading\n */\nSceneLoader.DETAILED_LOGGING = 3;\n// Members\n/**\n * Event raised when a plugin is used to load a scene\n */\nSceneLoader.OnPluginActivatedObservable = new Observable();\nSceneLoader._RegisteredPlugins = {};\nSceneLoader._ShowingLoadingScreen = false;\n//# sourceMappingURL=sceneLoader.js.map","/**\n * Defines the kind of connection point for node based material\n */\nexport var NodeMaterialBlockConnectionPointTypes;\n(function (NodeMaterialBlockConnectionPointTypes) {\n /** Float */\n NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes[\"Float\"] = 1] = \"Float\";\n /** Int */\n NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes[\"Int\"] = 2] = \"Int\";\n /** Vector2 */\n NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes[\"Vector2\"] = 4] = \"Vector2\";\n /** Vector3 */\n NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes[\"Vector3\"] = 8] = \"Vector3\";\n /** Vector4 */\n NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes[\"Vector4\"] = 16] = \"Vector4\";\n /** Color3 */\n NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes[\"Color3\"] = 32] = \"Color3\";\n /** Color4 */\n NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes[\"Color4\"] = 64] = \"Color4\";\n /** Matrix */\n NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes[\"Matrix\"] = 128] = \"Matrix\";\n /** Custom object */\n NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes[\"Object\"] = 256] = \"Object\";\n /** Detect type based on connection */\n NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes[\"AutoDetect\"] = 1024] = \"AutoDetect\";\n /** Output type that will be defined by input type */\n NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes[\"BasedOnInput\"] = 2048] = \"BasedOnInput\";\n /** Bitmask of all types */\n NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes[\"All\"] = 4095] = \"All\";\n})(NodeMaterialBlockConnectionPointTypes || (NodeMaterialBlockConnectionPointTypes = {}));\n//# sourceMappingURL=nodeMaterialBlockConnectionPointTypes.js.map","/**\n * Enum used to define the target of a block\n */\nexport var NodeMaterialBlockTargets;\n(function (NodeMaterialBlockTargets) {\n /** Vertex shader */\n NodeMaterialBlockTargets[NodeMaterialBlockTargets[\"Vertex\"] = 1] = \"Vertex\";\n /** Fragment shader */\n NodeMaterialBlockTargets[NodeMaterialBlockTargets[\"Fragment\"] = 2] = \"Fragment\";\n /** Neutral */\n NodeMaterialBlockTargets[NodeMaterialBlockTargets[\"Neutral\"] = 4] = \"Neutral\";\n /** Vertex and Fragment */\n NodeMaterialBlockTargets[NodeMaterialBlockTargets[\"VertexAndFragment\"] = 3] = \"VertexAndFragment\";\n})(NodeMaterialBlockTargets || (NodeMaterialBlockTargets = {}));\n//# sourceMappingURL=nodeMaterialBlockTargets.js.map","import { Matrix } from \"../Maths/math.vector.js\";\nimport { Material } from \"../Materials/material.js\";\n/**\n * Base class of materials working in push mode in babylon JS\n * @internal\n */\nexport class PushMaterial extends Material {\n constructor(name, scene, storeEffectOnSubMeshes = true) {\n super(name, scene);\n this._normalMatrix = new Matrix();\n this._storeEffectOnSubMeshes = storeEffectOnSubMeshes;\n }\n getEffect() {\n return this._storeEffectOnSubMeshes ? this._activeEffect : super.getEffect();\n }\n isReady(mesh, useInstances) {\n if (!mesh) {\n return false;\n }\n if (!this._storeEffectOnSubMeshes) {\n return true;\n }\n if (!mesh.subMeshes || mesh.subMeshes.length === 0) {\n return true;\n }\n return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);\n }\n _isReadyForSubMesh(subMesh) {\n const defines = subMesh.materialDefines;\n if (!this.checkReadyOnEveryCall && subMesh.effect && defines) {\n if (defines._renderId === this.getScene().getRenderId()) {\n return true;\n }\n }\n return false;\n }\n /**\n * Binds the given world matrix to the active effect\n *\n * @param world the matrix to bind\n */\n bindOnlyWorldMatrix(world) {\n this._activeEffect.setMatrix(\"world\", world);\n }\n /**\n * Binds the given normal matrix to the active effect\n *\n * @param normalMatrix the matrix to bind\n */\n bindOnlyNormalMatrix(normalMatrix) {\n this._activeEffect.setMatrix(\"normalMatrix\", normalMatrix);\n }\n bind(world, mesh) {\n if (!mesh) {\n return;\n }\n this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);\n }\n _afterBind(mesh, effect = null) {\n super._afterBind(mesh, effect);\n this.getScene()._cachedEffect = effect;\n if (effect) {\n effect._forceRebindOnNextCall = false;\n }\n }\n _mustRebind(scene, effect, visibility = 1) {\n return scene.isCachedMaterialInvalid(this, effect, visibility);\n }\n dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {\n this._activeEffect = undefined;\n super.dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh);\n }\n}\n//# sourceMappingURL=pushMaterial.js.map","import { NodeMaterialBlockConnectionPointTypes } from \"./Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"./Enums/nodeMaterialBlockTargets.js\";\nimport { Effect } from \"../effect.js\";\n/**\n * Class used to store node based material build state\n */\nexport class NodeMaterialBuildState {\n constructor() {\n /** Gets or sets a boolean indicating if the current state can emit uniform buffers */\n this.supportUniformBuffers = false;\n /**\n * Gets the list of emitted attributes\n */\n this.attributes = new Array();\n /**\n * Gets the list of emitted uniforms\n */\n this.uniforms = new Array();\n /**\n * Gets the list of emitted constants\n */\n this.constants = new Array();\n /**\n * Gets the list of emitted samplers\n */\n this.samplers = new Array();\n /**\n * Gets the list of emitted functions\n */\n this.functions = {};\n /**\n * Gets the list of emitted extensions\n */\n this.extensions = {};\n /**\n * Gets the list of emitted counters\n */\n this.counters = {};\n /** @internal */\n this._attributeDeclaration = \"\";\n /** @internal */\n this._uniformDeclaration = \"\";\n /** @internal */\n this._constantDeclaration = \"\";\n /** @internal */\n this._samplerDeclaration = \"\";\n /** @internal */\n this._varyingTransfer = \"\";\n /** @internal */\n this._injectAtEnd = \"\";\n this._repeatableContentAnchorIndex = 0;\n /** @internal */\n this._builtCompilationString = \"\";\n /**\n * Gets the emitted compilation strings\n */\n this.compilationString = \"\";\n }\n /**\n * Finalize the compilation strings\n * @param state defines the current compilation state\n */\n finalize(state) {\n const emitComments = state.sharedData.emitComments;\n const isFragmentMode = this.target === NodeMaterialBlockTargets.Fragment;\n this.compilationString = `\\r\\n${emitComments ? \"//Entry point\\r\\n\" : \"\"}void main(void) {\\r\\n${this.compilationString}`;\n if (this._constantDeclaration) {\n this.compilationString = `\\r\\n${emitComments ? \"//Constants\\r\\n\" : \"\"}${this._constantDeclaration}\\r\\n${this.compilationString}`;\n }\n let functionCode = \"\";\n for (const functionName in this.functions) {\n functionCode += this.functions[functionName] + `\\r\\n`;\n }\n this.compilationString = `\\r\\n${functionCode}\\r\\n${this.compilationString}`;\n if (!isFragmentMode && this._varyingTransfer) {\n this.compilationString = `${this.compilationString}\\r\\n${this._varyingTransfer}`;\n }\n if (this._injectAtEnd) {\n this.compilationString = `${this.compilationString}\\r\\n${this._injectAtEnd}`;\n }\n this.compilationString = `${this.compilationString}\\r\\n}`;\n if (this.sharedData.varyingDeclaration) {\n this.compilationString = `\\r\\n${emitComments ? \"//Varyings\\r\\n\" : \"\"}${this.sharedData.varyingDeclaration}\\r\\n${this.compilationString}`;\n }\n if (this._samplerDeclaration) {\n this.compilationString = `\\r\\n${emitComments ? \"//Samplers\\r\\n\" : \"\"}${this._samplerDeclaration}\\r\\n${this.compilationString}`;\n }\n if (this._uniformDeclaration) {\n this.compilationString = `\\r\\n${emitComments ? \"//Uniforms\\r\\n\" : \"\"}${this._uniformDeclaration}\\r\\n${this.compilationString}`;\n }\n if (this._attributeDeclaration && !isFragmentMode) {\n this.compilationString = `\\r\\n${emitComments ? \"//Attributes\\r\\n\" : \"\"}${this._attributeDeclaration}\\r\\n${this.compilationString}`;\n }\n this.compilationString = \"precision highp float;\\r\\n\" + this.compilationString;\n this.compilationString = \"#if defined(WEBGL2) || defines(WEBGPU)\\r\\nprecision highp sampler2DArray;\\r\\n#endif\\r\\n\" + this.compilationString;\n for (const extensionName in this.extensions) {\n const extension = this.extensions[extensionName];\n this.compilationString = `\\r\\n${extension}\\r\\n${this.compilationString}`;\n }\n this._builtCompilationString = this.compilationString;\n }\n /** @internal */\n get _repeatableContentAnchor() {\n return `###___ANCHOR${this._repeatableContentAnchorIndex++}___###`;\n }\n /**\n * @internal\n */\n _getFreeVariableName(prefix) {\n prefix = prefix.replace(/[^a-zA-Z_]+/g, \"\");\n if (this.sharedData.variableNames[prefix] === undefined) {\n this.sharedData.variableNames[prefix] = 0;\n // Check reserved words\n if (prefix === \"output\" || prefix === \"texture\") {\n return prefix + this.sharedData.variableNames[prefix];\n }\n return prefix;\n }\n else {\n this.sharedData.variableNames[prefix]++;\n }\n return prefix + this.sharedData.variableNames[prefix];\n }\n /**\n * @internal\n */\n _getFreeDefineName(prefix) {\n if (this.sharedData.defineNames[prefix] === undefined) {\n this.sharedData.defineNames[prefix] = 0;\n }\n else {\n this.sharedData.defineNames[prefix]++;\n }\n return prefix + this.sharedData.defineNames[prefix];\n }\n /**\n * @internal\n */\n _excludeVariableName(name) {\n this.sharedData.variableNames[name] = 0;\n }\n /**\n * @internal\n */\n _emit2DSampler(name) {\n if (this.samplers.indexOf(name) < 0) {\n this._samplerDeclaration += `uniform sampler2D ${name};\\r\\n`;\n this.samplers.push(name);\n }\n }\n /**\n * @internal\n */\n _emit2DArraySampler(name) {\n if (this.samplers.indexOf(name) < 0) {\n this._samplerDeclaration += `uniform sampler2DArray ${name};\\r\\n`;\n this.samplers.push(name);\n }\n }\n /**\n * @internal\n */\n _getGLType(type) {\n switch (type) {\n case NodeMaterialBlockConnectionPointTypes.Float:\n return \"float\";\n case NodeMaterialBlockConnectionPointTypes.Int:\n return \"int\";\n case NodeMaterialBlockConnectionPointTypes.Vector2:\n return \"vec2\";\n case NodeMaterialBlockConnectionPointTypes.Color3:\n case NodeMaterialBlockConnectionPointTypes.Vector3:\n return \"vec3\";\n case NodeMaterialBlockConnectionPointTypes.Color4:\n case NodeMaterialBlockConnectionPointTypes.Vector4:\n return \"vec4\";\n case NodeMaterialBlockConnectionPointTypes.Matrix:\n return \"mat4\";\n }\n return \"\";\n }\n /**\n * @internal\n */\n _emitExtension(name, extension, define = \"\") {\n if (this.extensions[name]) {\n return;\n }\n if (define) {\n extension = `#if ${define}\\r\\n${extension}\\r\\n#endif`;\n }\n this.extensions[name] = extension;\n }\n /**\n * @internal\n */\n _emitFunction(name, code, comments) {\n if (this.functions[name]) {\n return;\n }\n if (this.sharedData.emitComments) {\n code = comments + `\\r\\n` + code;\n }\n this.functions[name] = code;\n }\n /**\n * @internal\n */\n _emitCodeFromInclude(includeName, comments, options) {\n if (options && options.repeatKey) {\n return `#include<${includeName}>${options.substitutionVars ? \"(\" + options.substitutionVars + \")\" : \"\"}[0..${options.repeatKey}]\\r\\n`;\n }\n let code = Effect.IncludesShadersStore[includeName] + \"\\r\\n\";\n if (this.sharedData.emitComments) {\n code = comments + `\\r\\n` + code;\n }\n if (!options) {\n return code;\n }\n if (options.replaceStrings) {\n for (let index = 0; index < options.replaceStrings.length; index++) {\n const replaceString = options.replaceStrings[index];\n code = code.replace(replaceString.search, replaceString.replace);\n }\n }\n return code;\n }\n /**\n * @internal\n */\n _emitFunctionFromInclude(includeName, comments, options, storeKey = \"\") {\n const key = includeName + storeKey;\n if (this.functions[key]) {\n return;\n }\n if (!options || (!options.removeAttributes && !options.removeUniforms && !options.removeVaryings && !options.removeIfDef && !options.replaceStrings)) {\n if (options && options.repeatKey) {\n this.functions[key] = `#include<${includeName}>${options.substitutionVars ? \"(\" + options.substitutionVars + \")\" : \"\"}[0..${options.repeatKey}]\\r\\n`;\n }\n else {\n this.functions[key] = `#include<${includeName}>${(options === null || options === void 0 ? void 0 : options.substitutionVars) ? \"(\" + (options === null || options === void 0 ? void 0 : options.substitutionVars) + \")\" : \"\"}\\r\\n`;\n }\n if (this.sharedData.emitComments) {\n this.functions[key] = comments + `\\r\\n` + this.functions[key];\n }\n return;\n }\n this.functions[key] = Effect.IncludesShadersStore[includeName];\n if (this.sharedData.emitComments) {\n this.functions[key] = comments + `\\r\\n` + this.functions[key];\n }\n if (options.removeIfDef) {\n this.functions[key] = this.functions[key].replace(/^\\s*?#ifdef.+$/gm, \"\");\n this.functions[key] = this.functions[key].replace(/^\\s*?#endif.*$/gm, \"\");\n this.functions[key] = this.functions[key].replace(/^\\s*?#else.*$/gm, \"\");\n this.functions[key] = this.functions[key].replace(/^\\s*?#elif.*$/gm, \"\");\n }\n if (options.removeAttributes) {\n this.functions[key] = this.functions[key].replace(/^\\s*?attribute.+$/gm, \"\");\n }\n if (options.removeUniforms) {\n this.functions[key] = this.functions[key].replace(/^\\s*?uniform.+$/gm, \"\");\n }\n if (options.removeVaryings) {\n this.functions[key] = this.functions[key].replace(/^\\s*?varying.+$/gm, \"\");\n }\n if (options.replaceStrings) {\n for (let index = 0; index < options.replaceStrings.length; index++) {\n const replaceString = options.replaceStrings[index];\n this.functions[key] = this.functions[key].replace(replaceString.search, replaceString.replace);\n }\n }\n }\n /**\n * @internal\n */\n _registerTempVariable(name) {\n if (this.sharedData.temps.indexOf(name) !== -1) {\n return false;\n }\n this.sharedData.temps.push(name);\n return true;\n }\n /**\n * @internal\n */\n _emitVaryingFromString(name, type, define = \"\", notDefine = false) {\n if (this.sharedData.varyings.indexOf(name) !== -1) {\n return false;\n }\n this.sharedData.varyings.push(name);\n if (define) {\n if (define.startsWith(\"defined(\")) {\n this.sharedData.varyingDeclaration += `#if ${define}\\r\\n`;\n }\n else {\n this.sharedData.varyingDeclaration += `${notDefine ? \"#ifndef\" : \"#ifdef\"} ${define}\\r\\n`;\n }\n }\n this.sharedData.varyingDeclaration += `varying ${type} ${name};\\r\\n`;\n if (define) {\n this.sharedData.varyingDeclaration += `#endif\\r\\n`;\n }\n return true;\n }\n /**\n * @internal\n */\n _emitUniformFromString(name, type, define = \"\", notDefine = false) {\n if (this.uniforms.indexOf(name) !== -1) {\n return;\n }\n this.uniforms.push(name);\n if (define) {\n if (define.startsWith(\"defined(\")) {\n this._uniformDeclaration += `#if ${define}\\r\\n`;\n }\n else {\n this._uniformDeclaration += `${notDefine ? \"#ifndef\" : \"#ifdef\"} ${define}\\r\\n`;\n }\n }\n this._uniformDeclaration += `uniform ${type} ${name};\\r\\n`;\n if (define) {\n this._uniformDeclaration += `#endif\\r\\n`;\n }\n }\n /**\n * @internal\n */\n _emitFloat(value) {\n if (value.toString() === value.toFixed(0)) {\n return `${value}.0`;\n }\n return value.toString();\n }\n}\n//# sourceMappingURL=nodeMaterialBuildState.js.map","/**\n * Class used to store shared data between 2 NodeMaterialBuildState\n */\nexport class NodeMaterialBuildStateSharedData {\n /** Creates a new shared data */\n constructor() {\n /**\n * Gets the list of emitted varyings\n */\n this.temps = new Array();\n /**\n * Gets the list of emitted varyings\n */\n this.varyings = new Array();\n /**\n * Gets the varying declaration string\n */\n this.varyingDeclaration = \"\";\n /**\n * Input blocks\n */\n this.inputBlocks = new Array();\n /**\n * Input blocks\n */\n this.textureBlocks = new Array();\n /**\n * Bindable blocks (Blocks that need to set data to the effect)\n */\n this.bindableBlocks = new Array();\n /**\n * Bindable blocks (Blocks that need to set data to the effect) that will always be called (by bindForSubMesh), contrary to bindableBlocks that won't be called if _mustRebind() returns false\n */\n this.forcedBindableBlocks = new Array();\n /**\n * List of blocks that can provide a compilation fallback\n */\n this.blocksWithFallbacks = new Array();\n /**\n * List of blocks that can provide a define update\n */\n this.blocksWithDefines = new Array();\n /**\n * List of blocks that can provide a repeatable content\n */\n this.repeatableContentBlocks = new Array();\n /**\n * List of blocks that can provide a dynamic list of uniforms\n */\n this.dynamicUniformBlocks = new Array();\n /**\n * List of blocks that can block the isReady function for the material\n */\n this.blockingBlocks = new Array();\n /**\n * Gets the list of animated inputs\n */\n this.animatedInputs = new Array();\n /** List of emitted variables */\n this.variableNames = {};\n /** List of emitted defines */\n this.defineNames = {};\n /**\n * Gets the compilation hints emitted at compilation time\n */\n this.hints = {\n needWorldViewMatrix: false,\n needWorldViewProjectionMatrix: false,\n needAlphaBlending: false,\n needAlphaTesting: false,\n };\n /**\n * List of compilation checks\n */\n this.checks = {\n emitVertex: false,\n emitFragment: false,\n notConnectedNonOptionalInputs: new Array(),\n };\n /**\n * Is vertex program allowed to be empty?\n */\n this.allowEmptyVertexProgram = false;\n // Exclude usual attributes from free variable names\n this.variableNames[\"position\"] = 0;\n this.variableNames[\"normal\"] = 0;\n this.variableNames[\"tangent\"] = 0;\n this.variableNames[\"uv\"] = 0;\n this.variableNames[\"uv2\"] = 0;\n this.variableNames[\"uv3\"] = 0;\n this.variableNames[\"uv4\"] = 0;\n this.variableNames[\"uv5\"] = 0;\n this.variableNames[\"uv6\"] = 0;\n this.variableNames[\"color\"] = 0;\n this.variableNames[\"matricesIndices\"] = 0;\n this.variableNames[\"matricesWeights\"] = 0;\n this.variableNames[\"matricesIndicesExtra\"] = 0;\n this.variableNames[\"matricesWeightsExtra\"] = 0;\n this.variableNames[\"diffuseBase\"] = 0;\n this.variableNames[\"specularBase\"] = 0;\n this.variableNames[\"worldPos\"] = 0;\n this.variableNames[\"shadow\"] = 0;\n this.variableNames[\"view\"] = 0;\n // Exclude known varyings\n this.variableNames[\"vTBN\"] = 0;\n // Exclude defines\n this.defineNames[\"MAINUV0\"] = 0;\n this.defineNames[\"MAINUV1\"] = 0;\n this.defineNames[\"MAINUV2\"] = 0;\n this.defineNames[\"MAINUV3\"] = 0;\n this.defineNames[\"MAINUV4\"] = 0;\n this.defineNames[\"MAINUV5\"] = 0;\n this.defineNames[\"MAINUV6\"] = 0;\n this.defineNames[\"MAINUV7\"] = 0;\n }\n /**\n * Emits console errors and exceptions if there is a failing check\n */\n emitErrors() {\n let errorMessage = \"\";\n if (!this.checks.emitVertex && !this.allowEmptyVertexProgram) {\n errorMessage += \"NodeMaterial does not have a vertex output. You need to at least add a block that generates a glPosition value.\\r\\n\";\n }\n if (!this.checks.emitFragment) {\n errorMessage += \"NodeMaterial does not have a fragment output. You need to at least add a block that generates a glFragColor value.\\r\\n\";\n }\n for (const notConnectedInput of this.checks.notConnectedNonOptionalInputs) {\n errorMessage += `input ${notConnectedInput.name} from block ${notConnectedInput.ownerBlock.name}[${notConnectedInput.ownerBlock.getClassName()}] is not connected and is not optional.\\r\\n`;\n }\n if (errorMessage) {\n throw \"Build of NodeMaterial failed:\\r\\n\" + errorMessage;\n }\n }\n}\n//# sourceMappingURL=nodeMaterialBuildStateSharedData.js.map","import { NodeMaterialBlockConnectionPointTypes } from \"./Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"./Enums/nodeMaterialBlockTargets.js\";\nimport { Observable } from \"../../Misc/observable.js\";\n/**\n * Enum used to define the compatibility state between two connection points\n */\nexport var NodeMaterialConnectionPointCompatibilityStates;\n(function (NodeMaterialConnectionPointCompatibilityStates) {\n /** Points are compatibles */\n NodeMaterialConnectionPointCompatibilityStates[NodeMaterialConnectionPointCompatibilityStates[\"Compatible\"] = 0] = \"Compatible\";\n /** Points are incompatible because of their types */\n NodeMaterialConnectionPointCompatibilityStates[NodeMaterialConnectionPointCompatibilityStates[\"TypeIncompatible\"] = 1] = \"TypeIncompatible\";\n /** Points are incompatible because of their targets (vertex vs fragment) */\n NodeMaterialConnectionPointCompatibilityStates[NodeMaterialConnectionPointCompatibilityStates[\"TargetIncompatible\"] = 2] = \"TargetIncompatible\";\n /** Points are incompatible because they are in the same hierarchy **/\n NodeMaterialConnectionPointCompatibilityStates[NodeMaterialConnectionPointCompatibilityStates[\"HierarchyIssue\"] = 3] = \"HierarchyIssue\";\n})(NodeMaterialConnectionPointCompatibilityStates || (NodeMaterialConnectionPointCompatibilityStates = {}));\n/**\n * Defines the direction of a connection point\n */\nexport var NodeMaterialConnectionPointDirection;\n(function (NodeMaterialConnectionPointDirection) {\n /** Input */\n NodeMaterialConnectionPointDirection[NodeMaterialConnectionPointDirection[\"Input\"] = 0] = \"Input\";\n /** Output */\n NodeMaterialConnectionPointDirection[NodeMaterialConnectionPointDirection[\"Output\"] = 1] = \"Output\";\n})(NodeMaterialConnectionPointDirection || (NodeMaterialConnectionPointDirection = {}));\n/**\n * Defines a connection point for a block\n */\nexport class NodeMaterialConnectionPoint {\n /**\n * Checks if two types are equivalent\n * @param type1 type 1 to check\n * @param type2 type 2 to check\n * @returns true if both types are equivalent, else false\n */\n static AreEquivalentTypes(type1, type2) {\n switch (type1) {\n case NodeMaterialBlockConnectionPointTypes.Vector3: {\n if (type2 === NodeMaterialBlockConnectionPointTypes.Color3) {\n return true;\n }\n break;\n }\n case NodeMaterialBlockConnectionPointTypes.Vector4: {\n if (type2 === NodeMaterialBlockConnectionPointTypes.Color4) {\n return true;\n }\n break;\n }\n case NodeMaterialBlockConnectionPointTypes.Color3: {\n if (type2 === NodeMaterialBlockConnectionPointTypes.Vector3) {\n return true;\n }\n break;\n }\n case NodeMaterialBlockConnectionPointTypes.Color4: {\n if (type2 === NodeMaterialBlockConnectionPointTypes.Vector4) {\n return true;\n }\n break;\n }\n }\n return false;\n }\n /** Gets the direction of the point */\n get direction() {\n return this._direction;\n }\n /**\n * Gets or sets the associated variable name in the shader\n */\n get associatedVariableName() {\n if (this._ownerBlock.isInput) {\n return this._ownerBlock.associatedVariableName;\n }\n if ((!this._enforceAssociatedVariableName || !this._associatedVariableName) && this._connectedPoint) {\n return this._connectedPoint.associatedVariableName;\n }\n return this._associatedVariableName;\n }\n set associatedVariableName(value) {\n this._associatedVariableName = value;\n }\n /** Get the inner type (ie AutoDetect for instance instead of the inferred one) */\n get innerType() {\n if (this._linkedConnectionSource && this._linkedConnectionSource.isConnected) {\n return this.type;\n }\n return this._type;\n }\n /**\n * Gets or sets the connection point type (default is float)\n */\n get type() {\n if (this._type === NodeMaterialBlockConnectionPointTypes.AutoDetect) {\n if (this._ownerBlock.isInput) {\n return this._ownerBlock.type;\n }\n if (this._connectedPoint) {\n return this._connectedPoint.type;\n }\n if (this._linkedConnectionSource && this._linkedConnectionSource.isConnected) {\n return this._linkedConnectionSource.type;\n }\n }\n if (this._type === NodeMaterialBlockConnectionPointTypes.BasedOnInput) {\n if (this._typeConnectionSource) {\n if (!this._typeConnectionSource.isConnected && this._defaultConnectionPointType) {\n return this._defaultConnectionPointType;\n }\n return this._typeConnectionSource.type;\n }\n else if (this._defaultConnectionPointType) {\n return this._defaultConnectionPointType;\n }\n }\n return this._type;\n }\n set type(value) {\n this._type = value;\n }\n /** Gets or sets the target of that connection point */\n get target() {\n if (!this._prioritizeVertex || !this._ownerBlock) {\n return this._target;\n }\n if (this._target !== NodeMaterialBlockTargets.VertexAndFragment) {\n return this._target;\n }\n if (this._ownerBlock.target === NodeMaterialBlockTargets.Fragment) {\n return NodeMaterialBlockTargets.Fragment;\n }\n return NodeMaterialBlockTargets.Vertex;\n }\n set target(value) {\n this._target = value;\n }\n /**\n * Gets a boolean indicating that the current point is connected to another NodeMaterialBlock\n */\n get isConnected() {\n return this.connectedPoint !== null || this.hasEndpoints;\n }\n /**\n * Gets a boolean indicating that the current point is connected to an input block\n */\n get isConnectedToInputBlock() {\n return this.connectedPoint !== null && this.connectedPoint.ownerBlock.isInput;\n }\n /**\n * Gets a the connected input block (if any)\n */\n get connectInputBlock() {\n if (!this.isConnectedToInputBlock) {\n return null;\n }\n return this.connectedPoint.ownerBlock;\n }\n /** Get the other side of the connection (if any) */\n get connectedPoint() {\n return this._connectedPoint;\n }\n /** Get the block that owns this connection point */\n get ownerBlock() {\n return this._ownerBlock;\n }\n /** Get the block connected on the other side of this connection (if any) */\n get sourceBlock() {\n if (!this._connectedPoint) {\n return null;\n }\n return this._connectedPoint.ownerBlock;\n }\n /** Get the block connected on the endpoints of this connection (if any) */\n get connectedBlocks() {\n if (this._endpoints.length === 0) {\n return [];\n }\n return this._endpoints.map((e) => e.ownerBlock);\n }\n /** Gets the list of connected endpoints */\n get endpoints() {\n return this._endpoints;\n }\n /** Gets a boolean indicating if that output point is connected to at least one input */\n get hasEndpoints() {\n return this._endpoints && this._endpoints.length > 0;\n }\n /** Gets a boolean indicating that this connection has a path to the vertex output*/\n get isDirectlyConnectedToVertexOutput() {\n if (!this.hasEndpoints) {\n return false;\n }\n for (const endpoint of this._endpoints) {\n if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Vertex) {\n return true;\n }\n if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Neutral || endpoint.ownerBlock.target === NodeMaterialBlockTargets.VertexAndFragment) {\n if (endpoint.ownerBlock.outputs.some((o) => o.isDirectlyConnectedToVertexOutput)) {\n return true;\n }\n }\n }\n return false;\n }\n /** Gets a boolean indicating that this connection will be used in the vertex shader */\n get isConnectedInVertexShader() {\n if (this.target === NodeMaterialBlockTargets.Vertex) {\n return true;\n }\n if (!this.hasEndpoints) {\n return false;\n }\n for (const endpoint of this._endpoints) {\n if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Vertex) {\n return true;\n }\n if (endpoint.target === NodeMaterialBlockTargets.Vertex) {\n return true;\n }\n if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Neutral || endpoint.ownerBlock.target === NodeMaterialBlockTargets.VertexAndFragment) {\n if (endpoint.ownerBlock.outputs.some((o) => o.isConnectedInVertexShader)) {\n return true;\n }\n }\n }\n return false;\n }\n /** Gets a boolean indicating that this connection will be used in the fragment shader */\n get isConnectedInFragmentShader() {\n if (this.target === NodeMaterialBlockTargets.Fragment) {\n return true;\n }\n if (!this.hasEndpoints) {\n return false;\n }\n for (const endpoint of this._endpoints) {\n if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {\n return true;\n }\n if (endpoint.ownerBlock.target === NodeMaterialBlockTargets.Neutral || endpoint.ownerBlock.target === NodeMaterialBlockTargets.VertexAndFragment) {\n if (endpoint.ownerBlock.outputs.some((o) => o.isConnectedInFragmentShader)) {\n return true;\n }\n }\n }\n return false;\n }\n /**\n * Creates a block suitable to be used as an input for this input point.\n * If null is returned, a block based on the point type will be created.\n * @returns The returned string parameter is the name of the output point of NodeMaterialBlock (first parameter of the returned array) that can be connected to the input\n */\n createCustomInputBlock() {\n return null;\n }\n /**\n * Creates a new connection point\n * @param name defines the connection point name\n * @param ownerBlock defines the block hosting this connection point\n * @param direction defines the direction of the connection point\n */\n constructor(name, ownerBlock, direction) {\n /** @internal */\n this._connectedPoint = null;\n this._endpoints = new Array();\n /** @internal */\n this._typeConnectionSource = null;\n /** @internal */\n this._defaultConnectionPointType = null;\n /** @internal */\n this._linkedConnectionSource = null;\n /** @internal */\n this._acceptedConnectionPointType = null;\n this._type = NodeMaterialBlockConnectionPointTypes.Float;\n /** @internal */\n this._enforceAssociatedVariableName = false;\n /** Indicates that this connection point needs dual validation before being connected to another point */\n this.needDualDirectionValidation = false;\n /**\n * Gets or sets the additional types supported by this connection point\n */\n this.acceptedConnectionPointTypes = new Array();\n /**\n * Gets or sets the additional types excluded by this connection point\n */\n this.excludedConnectionPointTypes = new Array();\n /**\n * Observable triggered when this point is connected\n */\n this.onConnectionObservable = new Observable();\n /**\n * Gets or sets a boolean indicating that this connection point is exposed on a frame\n */\n this.isExposedOnFrame = false;\n /**\n * Gets or sets number indicating the position that the port is exposed to on a frame\n */\n this.exposedPortPosition = -1;\n /** @internal */\n this._prioritizeVertex = false;\n this._target = NodeMaterialBlockTargets.VertexAndFragment;\n this._ownerBlock = ownerBlock;\n this.name = name;\n this._direction = direction;\n }\n /**\n * Gets the current class name e.g. \"NodeMaterialConnectionPoint\"\n * @returns the class name\n */\n getClassName() {\n return \"NodeMaterialConnectionPoint\";\n }\n /**\n * Gets a boolean indicating if the current point can be connected to another point\n * @param connectionPoint defines the other connection point\n * @returns a boolean\n */\n canConnectTo(connectionPoint) {\n return this.checkCompatibilityState(connectionPoint) === NodeMaterialConnectionPointCompatibilityStates.Compatible;\n }\n /**\n * Gets a number indicating if the current point can be connected to another point\n * @param connectionPoint defines the other connection point\n * @returns a number defining the compatibility state\n */\n checkCompatibilityState(connectionPoint) {\n const ownerBlock = this._ownerBlock;\n const otherBlock = connectionPoint.ownerBlock;\n if (ownerBlock.target === NodeMaterialBlockTargets.Fragment) {\n // Let's check we are not going reverse\n if (otherBlock.target === NodeMaterialBlockTargets.Vertex) {\n return NodeMaterialConnectionPointCompatibilityStates.TargetIncompatible;\n }\n for (const output of otherBlock.outputs) {\n if (output.ownerBlock.target != NodeMaterialBlockTargets.Neutral && output.isConnectedInVertexShader) {\n return NodeMaterialConnectionPointCompatibilityStates.TargetIncompatible;\n }\n }\n }\n if (this.type !== connectionPoint.type && connectionPoint.innerType !== NodeMaterialBlockConnectionPointTypes.AutoDetect) {\n // Equivalents\n if (NodeMaterialConnectionPoint.AreEquivalentTypes(this.type, connectionPoint.type)) {\n return NodeMaterialConnectionPointCompatibilityStates.Compatible;\n }\n // Accepted types\n if ((connectionPoint.acceptedConnectionPointTypes && connectionPoint.acceptedConnectionPointTypes.indexOf(this.type) !== -1) ||\n (connectionPoint._acceptedConnectionPointType && NodeMaterialConnectionPoint.AreEquivalentTypes(connectionPoint._acceptedConnectionPointType.type, this.type))) {\n return NodeMaterialConnectionPointCompatibilityStates.Compatible;\n }\n else {\n return NodeMaterialConnectionPointCompatibilityStates.TypeIncompatible;\n }\n }\n // Excluded\n if (connectionPoint.excludedConnectionPointTypes && connectionPoint.excludedConnectionPointTypes.indexOf(this.type) !== -1) {\n return NodeMaterialConnectionPointCompatibilityStates.TypeIncompatible;\n }\n // Check hierarchy\n let targetBlock = otherBlock;\n let sourceBlock = ownerBlock;\n if (this.direction === NodeMaterialConnectionPointDirection.Input) {\n targetBlock = ownerBlock;\n sourceBlock = otherBlock;\n }\n if (targetBlock.isAnAncestorOf(sourceBlock)) {\n return NodeMaterialConnectionPointCompatibilityStates.HierarchyIssue;\n }\n return NodeMaterialConnectionPointCompatibilityStates.Compatible;\n }\n /**\n * Connect this point to another connection point\n * @param connectionPoint defines the other connection point\n * @param ignoreConstraints defines if the system will ignore connection type constraints (default is false)\n * @returns the current connection point\n */\n connectTo(connectionPoint, ignoreConstraints = false) {\n if (!ignoreConstraints && !this.canConnectTo(connectionPoint)) {\n throw \"Cannot connect these two connectors.\";\n }\n this._endpoints.push(connectionPoint);\n connectionPoint._connectedPoint = this;\n this._enforceAssociatedVariableName = false;\n this.onConnectionObservable.notifyObservers(connectionPoint);\n connectionPoint.onConnectionObservable.notifyObservers(this);\n return this;\n }\n /**\n * Disconnect this point from one of his endpoint\n * @param endpoint defines the other connection point\n * @returns the current connection point\n */\n disconnectFrom(endpoint) {\n const index = this._endpoints.indexOf(endpoint);\n if (index === -1) {\n return this;\n }\n this._endpoints.splice(index, 1);\n endpoint._connectedPoint = null;\n this._enforceAssociatedVariableName = false;\n endpoint._enforceAssociatedVariableName = false;\n return this;\n }\n /**\n * Fill the list of excluded connection point types with all types other than those passed in the parameter\n * @param mask Types (ORed values of NodeMaterialBlockConnectionPointTypes) that are allowed, and thus will not be pushed to the excluded list\n */\n addExcludedConnectionPointFromAllowedTypes(mask) {\n let bitmask = 1;\n while (bitmask < NodeMaterialBlockConnectionPointTypes.All) {\n if (!(mask & bitmask)) {\n this.excludedConnectionPointTypes.push(bitmask);\n }\n bitmask = bitmask << 1;\n }\n }\n /**\n * Serializes this point in a JSON representation\n * @param isInput defines if the connection point is an input (default is true)\n * @returns the serialized point object\n */\n serialize(isInput = true) {\n const serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.displayName = this.displayName;\n if (isInput && this.connectedPoint) {\n serializationObject.inputName = this.name;\n serializationObject.targetBlockId = this.connectedPoint.ownerBlock.uniqueId;\n serializationObject.targetConnectionName = this.connectedPoint.name;\n serializationObject.isExposedOnFrame = true;\n serializationObject.exposedPortPosition = this.exposedPortPosition;\n }\n if (this.isExposedOnFrame || this.exposedPortPosition >= 0) {\n serializationObject.isExposedOnFrame = true;\n serializationObject.exposedPortPosition = this.exposedPortPosition;\n }\n return serializationObject;\n }\n /**\n * Release resources\n */\n dispose() {\n this.onConnectionObservable.clear();\n }\n}\n//# sourceMappingURL=nodeMaterialBlockConnectionPoint.js.map","/**\n * Enum defining the type of properties that can be edited in the property pages in the NME\n */\nexport var PropertyTypeForEdition;\n(function (PropertyTypeForEdition) {\n /** property is a boolean */\n PropertyTypeForEdition[PropertyTypeForEdition[\"Boolean\"] = 0] = \"Boolean\";\n /** property is a float */\n PropertyTypeForEdition[PropertyTypeForEdition[\"Float\"] = 1] = \"Float\";\n /** property is a int */\n PropertyTypeForEdition[PropertyTypeForEdition[\"Int\"] = 2] = \"Int\";\n /** property is a Vector2 */\n PropertyTypeForEdition[PropertyTypeForEdition[\"Vector2\"] = 3] = \"Vector2\";\n /** property is a list of values */\n PropertyTypeForEdition[PropertyTypeForEdition[\"List\"] = 4] = \"List\";\n})(PropertyTypeForEdition || (PropertyTypeForEdition = {}));\n/**\n * Decorator that flags a property in a node material block as being editable\n * @param displayName\n * @param propertyType\n * @param groupName\n * @param options\n */\nexport function editableInPropertyPage(displayName, propertyType = PropertyTypeForEdition.Boolean, groupName = \"PROPERTIES\", options) {\n return (target, propertyKey) => {\n let propStore = target._propStore;\n if (!propStore) {\n propStore = [];\n target._propStore = propStore;\n }\n propStore.push({\n propertyName: propertyKey,\n displayName: displayName,\n type: propertyType,\n groupName: groupName,\n options: options !== null && options !== void 0 ? options : {},\n });\n };\n}\n//# sourceMappingURL=nodeMaterialDecorator.js.map","import { NodeMaterialBlockConnectionPointTypes } from \"./Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialConnectionPoint, NodeMaterialConnectionPointDirection } from \"./nodeMaterialBlockConnectionPoint.js\";\nimport { NodeMaterialBlockTargets } from \"./Enums/nodeMaterialBlockTargets.js\";\nimport { UniqueIdGenerator } from \"../../Misc/uniqueIdGenerator.js\";\nimport { GetClass } from \"../../Misc/typeStore.js\";\n/**\n * Defines a block that can be used inside a node based material\n */\nexport class NodeMaterialBlock {\n /**\n * Gets the name of the block\n */\n get name() {\n return this._name;\n }\n /**\n * Sets the name of the block. Will check if the name is valid.\n */\n set name(newName) {\n if (!this.validateBlockName(newName)) {\n return;\n }\n this._name = newName;\n }\n /**\n * Gets a boolean indicating that this block can only be used once per NodeMaterial\n */\n get isUnique() {\n return this._isUnique;\n }\n /**\n * Gets a boolean indicating that this block is an end block (e.g. it is generating a system value)\n */\n get isFinalMerger() {\n return this._isFinalMerger;\n }\n /**\n * Gets a boolean indicating that this block is an input (e.g. it sends data to the shader)\n */\n get isInput() {\n return this._isInput;\n }\n /**\n * Gets or sets the build Id\n */\n get buildId() {\n return this._buildId;\n }\n set buildId(value) {\n this._buildId = value;\n }\n /**\n * Gets or sets the target of the block\n */\n get target() {\n return this._target;\n }\n set target(value) {\n if ((this._target & value) !== 0) {\n return;\n }\n this._target = value;\n }\n /**\n * Gets the list of input points\n */\n get inputs() {\n return this._inputs;\n }\n /** Gets the list of output points */\n get outputs() {\n return this._outputs;\n }\n /**\n * Find an input by its name\n * @param name defines the name of the input to look for\n * @returns the input or null if not found\n */\n getInputByName(name) {\n const filter = this._inputs.filter((e) => e.name === name);\n if (filter.length) {\n return filter[0];\n }\n return null;\n }\n /**\n * Find an output by its name\n * @param name defines the name of the output to look for\n * @returns the output or null if not found\n */\n getOutputByName(name) {\n const filter = this._outputs.filter((e) => e.name === name);\n if (filter.length) {\n return filter[0];\n }\n return null;\n }\n /**\n * Creates a new NodeMaterialBlock\n * @param name defines the block name\n * @param target defines the target of that block (Vertex by default)\n * @param isFinalMerger defines a boolean indicating that this block is an end block (e.g. it is generating a system value). Default is false\n * @param isInput defines a boolean indicating that this block is an input (e.g. it sends data to the shader). Default is false\n */\n constructor(name, target = NodeMaterialBlockTargets.Vertex, isFinalMerger = false, isInput = false) {\n this._isFinalMerger = false;\n this._isInput = false;\n this._name = \"\";\n this._isUnique = false;\n /** Gets or sets a boolean indicating that only one input can be connected at a time */\n this.inputsAreExclusive = false;\n /** @internal */\n this._codeVariableName = \"\";\n /** @internal */\n this._inputs = new Array();\n /** @internal */\n this._outputs = new Array();\n /**\n * Gets or sets the comments associated with this block\n */\n this.comments = \"\";\n /** Gets or sets a boolean indicating that this input can be edited in the Inspector (false by default) */\n this.visibleInInspector = false;\n /** Gets or sets a boolean indicating that this input can be edited from a collapsed frame */\n this.visibleOnFrame = false;\n this._target = target;\n this._originalTargetIsNeutral = target === NodeMaterialBlockTargets.Neutral;\n this._isFinalMerger = isFinalMerger;\n this._isInput = isInput;\n this._name = name;\n this.uniqueId = UniqueIdGenerator.UniqueId;\n }\n /** @internal */\n _setInitialTarget(target) {\n this._target = target;\n this._originalTargetIsNeutral = target === NodeMaterialBlockTargets.Neutral;\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n initialize(state) {\n // Do nothing\n }\n /**\n * Bind data to effect. Will only be called for blocks with isBindable === true\n * @param effect defines the effect to bind data to\n * @param nodeMaterial defines the hosting NodeMaterial\n * @param mesh defines the mesh that will be rendered\n * @param subMesh defines the submesh that will be rendered\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n bind(effect, nodeMaterial, mesh, subMesh) {\n // Do nothing\n }\n _declareOutput(output, state) {\n return `${state._getGLType(output.type)} ${output.associatedVariableName}`;\n }\n _writeVariable(currentPoint) {\n const connectionPoint = currentPoint.connectedPoint;\n if (connectionPoint) {\n return `${currentPoint.associatedVariableName}`;\n }\n return `0.`;\n }\n _writeFloat(value) {\n let stringVersion = value.toString();\n if (stringVersion.indexOf(\".\") === -1) {\n stringVersion += \".0\";\n }\n return `${stringVersion}`;\n }\n /**\n * Gets the current class name e.g. \"NodeMaterialBlock\"\n * @returns the class name\n */\n getClassName() {\n return \"NodeMaterialBlock\";\n }\n /**\n * Register a new input. Must be called inside a block constructor\n * @param name defines the connection point name\n * @param type defines the connection point type\n * @param isOptional defines a boolean indicating that this input can be omitted\n * @param target defines the target to use to limit the connection point (will be VertexAndFragment by default)\n * @param point an already created connection point. If not provided, create a new one\n * @returns the current block\n */\n registerInput(name, type, isOptional = false, target, point) {\n point = point !== null && point !== void 0 ? point : new NodeMaterialConnectionPoint(name, this, NodeMaterialConnectionPointDirection.Input);\n point.type = type;\n point.isOptional = isOptional;\n if (target) {\n point.target = target;\n }\n this._inputs.push(point);\n return this;\n }\n /**\n * Register a new output. Must be called inside a block constructor\n * @param name defines the connection point name\n * @param type defines the connection point type\n * @param target defines the target to use to limit the connection point (will be VertexAndFragment by default)\n * @param point an already created connection point. If not provided, create a new one\n * @returns the current block\n */\n registerOutput(name, type, target, point) {\n point = point !== null && point !== void 0 ? point : new NodeMaterialConnectionPoint(name, this, NodeMaterialConnectionPointDirection.Output);\n point.type = type;\n if (target) {\n point.target = target;\n }\n this._outputs.push(point);\n return this;\n }\n /**\n * Will return the first available input e.g. the first one which is not an uniform or an attribute\n * @param forOutput defines an optional connection point to check compatibility with\n * @returns the first available input or null\n */\n getFirstAvailableInput(forOutput = null) {\n for (const input of this._inputs) {\n if (!input.connectedPoint) {\n if (!forOutput || forOutput.type === input.type || input.type === NodeMaterialBlockConnectionPointTypes.AutoDetect) {\n return input;\n }\n }\n }\n return null;\n }\n /**\n * Will return the first available output e.g. the first one which is not yet connected and not a varying\n * @param forBlock defines an optional block to check compatibility with\n * @returns the first available input or null\n */\n getFirstAvailableOutput(forBlock = null) {\n for (const output of this._outputs) {\n if (!forBlock || !forBlock.target || forBlock.target === NodeMaterialBlockTargets.Neutral || (forBlock.target & output.target) !== 0) {\n return output;\n }\n }\n return null;\n }\n /**\n * Gets the sibling of the given output\n * @param current defines the current output\n * @returns the next output in the list or null\n */\n getSiblingOutput(current) {\n const index = this._outputs.indexOf(current);\n if (index === -1 || index >= this._outputs.length) {\n return null;\n }\n return this._outputs[index + 1];\n }\n /**\n * Checks if the current block is an ancestor of a given block\n * @param block defines the potential descendant block to check\n * @returns true if block is a descendant\n */\n isAnAncestorOf(block) {\n for (const output of this._outputs) {\n if (!output.hasEndpoints) {\n continue;\n }\n for (const endpoint of output.endpoints) {\n if (endpoint.ownerBlock === block) {\n return true;\n }\n if (endpoint.ownerBlock.isAnAncestorOf(block)) {\n return true;\n }\n }\n }\n return false;\n }\n /**\n * Connect current block with another block\n * @param other defines the block to connect with\n * @param options define the various options to help pick the right connections\n * @param options.input\n * @param options.output\n * @param options.outputSwizzle\n * @returns the current block\n */\n connectTo(other, options) {\n if (this._outputs.length === 0) {\n return;\n }\n let output = options && options.output ? this.getOutputByName(options.output) : this.getFirstAvailableOutput(other);\n let notFound = true;\n while (notFound) {\n const input = options && options.input ? other.getInputByName(options.input) : other.getFirstAvailableInput(output);\n if (output && input && output.canConnectTo(input)) {\n output.connectTo(input);\n notFound = false;\n }\n else if (!output) {\n throw \"Unable to find a compatible match\";\n }\n else {\n output = this.getSiblingOutput(output);\n }\n }\n return this;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _buildBlock(state) {\n // Empty. Must be defined by child nodes\n }\n /**\n * Add uniforms, samplers and uniform buffers at compilation time\n * @param state defines the state to update\n * @param nodeMaterial defines the node material requesting the update\n * @param defines defines the material defines to update\n * @param uniformBuffers defines the list of uniform buffer names\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n updateUniformsAndSamples(state, nodeMaterial, defines, uniformBuffers) {\n // Do nothing\n }\n /**\n * Add potential fallbacks if shader compilation fails\n * @param mesh defines the mesh to be rendered\n * @param fallbacks defines the current prioritized list of fallbacks\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n provideFallbacks(mesh, fallbacks) {\n // Do nothing\n }\n /**\n * Initialize defines for shader compilation\n * @param mesh defines the mesh to be rendered\n * @param nodeMaterial defines the node material requesting the update\n * @param defines defines the material defines to update\n * @param useInstances specifies that instances should be used\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n initializeDefines(mesh, nodeMaterial, defines, useInstances = false) { }\n /**\n * Update defines for shader compilation\n * @param mesh defines the mesh to be rendered\n * @param nodeMaterial defines the node material requesting the update\n * @param defines defines the material defines to update\n * @param useInstances specifies that instances should be used\n * @param subMesh defines which submesh to render\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n prepareDefines(mesh, nodeMaterial, defines, useInstances = false, subMesh) {\n // Do nothing\n }\n /**\n * Lets the block try to connect some inputs automatically\n * @param material defines the hosting NodeMaterial\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n autoConfigure(material) {\n // Do nothing\n }\n /**\n * Function called when a block is declared as repeatable content generator\n * @param vertexShaderState defines the current compilation state for the vertex shader\n * @param fragmentShaderState defines the current compilation state for the fragment shader\n * @param mesh defines the mesh to be rendered\n * @param defines defines the material defines to update\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n replaceRepeatableContent(vertexShaderState, fragmentShaderState, mesh, defines) {\n // Do nothing\n }\n /** Gets a boolean indicating that the code of this block will be promoted to vertex shader even if connected to fragment output */\n get willBeGeneratedIntoVertexShaderFromFragmentShader() {\n if (this.isInput || this.isFinalMerger) {\n return false;\n }\n if (this._outputs.some((o) => o.isDirectlyConnectedToVertexOutput)) {\n return false;\n }\n if (this.target === NodeMaterialBlockTargets.Vertex) {\n return false;\n }\n if (this.target === NodeMaterialBlockTargets.VertexAndFragment || this.target === NodeMaterialBlockTargets.Neutral) {\n if (this._outputs.some((o) => o.isConnectedInVertexShader)) {\n return true;\n }\n }\n return false;\n }\n /**\n * Checks if the block is ready\n * @param mesh defines the mesh to be rendered\n * @param nodeMaterial defines the node material requesting the update\n * @param defines defines the material defines to update\n * @param useInstances specifies that instances should be used\n * @returns true if the block is ready\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isReady(mesh, nodeMaterial, defines, useInstances = false) {\n return true;\n }\n _linkConnectionTypes(inputIndex0, inputIndex1, looseCoupling = false) {\n if (looseCoupling) {\n this._inputs[inputIndex1]._acceptedConnectionPointType = this._inputs[inputIndex0];\n }\n else {\n this._inputs[inputIndex0]._linkedConnectionSource = this._inputs[inputIndex1];\n }\n this._inputs[inputIndex1]._linkedConnectionSource = this._inputs[inputIndex0];\n }\n _processBuild(block, state, input, activeBlocks) {\n block.build(state, activeBlocks);\n const localBlockIsFragment = state._vertexState != null;\n const otherBlockWasGeneratedInVertexShader = block._buildTarget === NodeMaterialBlockTargets.Vertex && block.target !== NodeMaterialBlockTargets.VertexAndFragment;\n if (localBlockIsFragment &&\n ((block.target & block._buildTarget) === 0 ||\n (block.target & input.target) === 0 ||\n (this.target !== NodeMaterialBlockTargets.VertexAndFragment && otherBlockWasGeneratedInVertexShader))) {\n // context switch! We need a varying\n if ((!block.isInput && state.target !== block._buildTarget) || // block was already emitted by vertex shader\n (block.isInput && block.isAttribute && !block._noContextSwitch) // block is an attribute\n ) {\n const connectedPoint = input.connectedPoint;\n if (state._vertexState._emitVaryingFromString(\"v_\" + connectedPoint.associatedVariableName, state._getGLType(connectedPoint.type))) {\n state._vertexState.compilationString += `${\"v_\" + connectedPoint.associatedVariableName} = ${connectedPoint.associatedVariableName};\\r\\n`;\n }\n input.associatedVariableName = \"v_\" + connectedPoint.associatedVariableName;\n input._enforceAssociatedVariableName = true;\n }\n }\n }\n /**\n * Validates the new name for the block node.\n * @param newName the new name to be given to the node.\n * @returns false if the name is a reserve word, else true.\n */\n validateBlockName(newName) {\n const reservedNames = [\n \"position\",\n \"normal\",\n \"tangent\",\n \"particle_positionw\",\n \"uv\",\n \"uv2\",\n \"uv3\",\n \"uv4\",\n \"uv5\",\n \"uv6\",\n \"position2d\",\n \"particle_uv\",\n \"matricesIndices\",\n \"matricesWeights\",\n \"world0\",\n \"world1\",\n \"world2\",\n \"world3\",\n \"particle_color\",\n \"particle_texturemask\",\n ];\n for (const reservedName of reservedNames) {\n if (newName === reservedName) {\n return false;\n }\n }\n return true;\n }\n /**\n * Compile the current node and generate the shader code\n * @param state defines the current compilation state (uniforms, samplers, current string)\n * @param activeBlocks defines the list of active blocks (i.e. blocks to compile)\n * @returns true if already built\n */\n build(state, activeBlocks) {\n if (this._buildId === state.sharedData.buildId) {\n return true;\n }\n if (!this.isInput) {\n /** Prepare outputs */\n for (const output of this._outputs) {\n if (!output.associatedVariableName) {\n output.associatedVariableName = state._getFreeVariableName(output.name);\n }\n }\n }\n // Check if \"parent\" blocks are compiled\n for (const input of this._inputs) {\n if (!input.connectedPoint) {\n if (!input.isOptional) {\n // Emit a warning\n state.sharedData.checks.notConnectedNonOptionalInputs.push(input);\n }\n continue;\n }\n if (this.target !== NodeMaterialBlockTargets.Neutral) {\n if ((input.target & this.target) === 0) {\n continue;\n }\n if ((input.target & state.target) === 0) {\n continue;\n }\n }\n const block = input.connectedPoint.ownerBlock;\n if (block && block !== this) {\n this._processBuild(block, state, input, activeBlocks);\n }\n }\n if (this._buildId === state.sharedData.buildId) {\n return true; // Need to check again as inputs can be connected multiple time to this endpoint\n }\n // Logs\n if (state.sharedData.verbose) {\n console.log(`${state.target === NodeMaterialBlockTargets.Vertex ? \"Vertex shader\" : \"Fragment shader\"}: Building ${this.name} [${this.getClassName()}]`);\n }\n // Checks final outputs\n if (this.isFinalMerger) {\n switch (state.target) {\n case NodeMaterialBlockTargets.Vertex:\n state.sharedData.checks.emitVertex = true;\n break;\n case NodeMaterialBlockTargets.Fragment:\n state.sharedData.checks.emitFragment = true;\n break;\n }\n }\n if (!this.isInput && state.sharedData.emitComments) {\n state.compilationString += `\\r\\n//${this.name}\\r\\n`;\n }\n this._buildBlock(state);\n this._buildId = state.sharedData.buildId;\n this._buildTarget = state.target;\n // Compile connected blocks\n for (const output of this._outputs) {\n if ((output.target & state.target) === 0) {\n continue;\n }\n for (const endpoint of output.endpoints) {\n const block = endpoint.ownerBlock;\n if (block && (block.target & state.target) !== 0 && activeBlocks.indexOf(block) !== -1) {\n this._processBuild(block, state, endpoint, activeBlocks);\n }\n }\n }\n return false;\n }\n _inputRename(name) {\n return name;\n }\n _outputRename(name) {\n return name;\n }\n _dumpPropertiesCode() {\n const variableName = this._codeVariableName;\n return `${variableName}.visibleInInspector = ${this.visibleInInspector};\\r\\n${variableName}.visibleOnFrame = ${this.visibleOnFrame};\\r\\n${variableName}.target = ${this.target};\\r\\n`;\n }\n /**\n * @internal\n */\n _dumpCode(uniqueNames, alreadyDumped) {\n alreadyDumped.push(this);\n let codeString;\n // Get unique name\n const nameAsVariableName = this.name.replace(/[^A-Za-z_]+/g, \"\");\n this._codeVariableName = nameAsVariableName || `${this.getClassName()}_${this.uniqueId}`;\n if (uniqueNames.indexOf(this._codeVariableName) !== -1) {\n let index = 0;\n do {\n index++;\n this._codeVariableName = nameAsVariableName + index;\n } while (uniqueNames.indexOf(this._codeVariableName) !== -1);\n }\n uniqueNames.push(this._codeVariableName);\n // Declaration\n codeString = `\\r\\n// ${this.getClassName()}\\r\\n`;\n if (this.comments) {\n codeString += `// ${this.comments}\\r\\n`;\n }\n codeString += `var ${this._codeVariableName} = new BABYLON.${this.getClassName()}(\"${this.name}\");\\r\\n`;\n // Properties\n codeString += this._dumpPropertiesCode();\n // Inputs\n for (const input of this.inputs) {\n if (!input.isConnected) {\n continue;\n }\n const connectedOutput = input.connectedPoint;\n const connectedBlock = connectedOutput.ownerBlock;\n if (alreadyDumped.indexOf(connectedBlock) === -1) {\n codeString += connectedBlock._dumpCode(uniqueNames, alreadyDumped);\n }\n }\n // Outputs\n for (const output of this.outputs) {\n if (!output.hasEndpoints) {\n continue;\n }\n for (const endpoint of output.endpoints) {\n const connectedBlock = endpoint.ownerBlock;\n if (connectedBlock && alreadyDumped.indexOf(connectedBlock) === -1) {\n codeString += connectedBlock._dumpCode(uniqueNames, alreadyDumped);\n }\n }\n }\n return codeString;\n }\n /**\n * @internal\n */\n _dumpCodeForOutputConnections(alreadyDumped) {\n let codeString = \"\";\n if (alreadyDumped.indexOf(this) !== -1) {\n return codeString;\n }\n alreadyDumped.push(this);\n for (const input of this.inputs) {\n if (!input.isConnected) {\n continue;\n }\n const connectedOutput = input.connectedPoint;\n const connectedBlock = connectedOutput.ownerBlock;\n codeString += connectedBlock._dumpCodeForOutputConnections(alreadyDumped);\n codeString += `${connectedBlock._codeVariableName}.${connectedBlock._outputRename(connectedOutput.name)}.connectTo(${this._codeVariableName}.${this._inputRename(input.name)});\\r\\n`;\n }\n return codeString;\n }\n /**\n * Clone the current block to a new identical block\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @returns a copy of the current block\n */\n clone(scene, rootUrl = \"\") {\n const serializationObject = this.serialize();\n const blockType = GetClass(serializationObject.customType);\n if (blockType) {\n const block = new blockType();\n block._deserialize(serializationObject, scene, rootUrl);\n return block;\n }\n return null;\n }\n /**\n * Serializes this block in a JSON representation\n * @returns the serialized block object\n */\n serialize() {\n const serializationObject = {};\n serializationObject.customType = \"BABYLON.\" + this.getClassName();\n serializationObject.id = this.uniqueId;\n serializationObject.name = this.name;\n serializationObject.comments = this.comments;\n serializationObject.visibleInInspector = this.visibleInInspector;\n serializationObject.visibleOnFrame = this.visibleOnFrame;\n serializationObject.target = this.target;\n serializationObject.inputs = [];\n serializationObject.outputs = [];\n for (const input of this.inputs) {\n serializationObject.inputs.push(input.serialize());\n }\n for (const output of this.outputs) {\n serializationObject.outputs.push(output.serialize(false));\n }\n return serializationObject;\n }\n /**\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _deserialize(serializationObject, scene, rootUrl) {\n var _a;\n this.name = serializationObject.name;\n this.comments = serializationObject.comments;\n this.visibleInInspector = !!serializationObject.visibleInInspector;\n this.visibleOnFrame = !!serializationObject.visibleOnFrame;\n this._target = (_a = serializationObject.target) !== null && _a !== void 0 ? _a : this.target;\n this._deserializePortDisplayNamesAndExposedOnFrame(serializationObject);\n }\n _deserializePortDisplayNamesAndExposedOnFrame(serializationObject) {\n const serializedInputs = serializationObject.inputs;\n const serializedOutputs = serializationObject.outputs;\n if (serializedInputs) {\n serializedInputs.forEach((port, i) => {\n if (port.displayName) {\n this.inputs[i].displayName = port.displayName;\n }\n if (port.isExposedOnFrame) {\n this.inputs[i].isExposedOnFrame = port.isExposedOnFrame;\n this.inputs[i].exposedPortPosition = port.exposedPortPosition;\n }\n });\n }\n if (serializedOutputs) {\n serializedOutputs.forEach((port, i) => {\n if (port.displayName) {\n this.outputs[i].displayName = port.displayName;\n }\n if (port.isExposedOnFrame) {\n this.outputs[i].isExposedOnFrame = port.isExposedOnFrame;\n this.outputs[i].exposedPortPosition = port.exposedPortPosition;\n }\n });\n }\n }\n /**\n * Release resources\n */\n dispose() {\n for (const input of this.inputs) {\n input.dispose();\n }\n for (const output of this.outputs) {\n output.dispose();\n }\n }\n}\n//# sourceMappingURL=nodeMaterialBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to transform a vector (2, 3 or 4) with a matrix. It will generate a Vector4\n */\nexport class TransformBlock extends NodeMaterialBlock {\n /**\n * Creates a new TransformBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n /**\n * Defines the value to use to complement W value to transform it to a Vector4\n */\n this.complementW = 1;\n /**\n * Defines the value to use to complement z value to transform it to a Vector4\n */\n this.complementZ = 0;\n this.target = NodeMaterialBlockTargets.Vertex;\n this.registerInput(\"vector\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"transform\", NodeMaterialBlockConnectionPointTypes.Matrix);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerOutput(\"xyz\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this._inputs[0].onConnectionObservable.add((other) => {\n if (other.ownerBlock.isInput) {\n const otherAsInput = other.ownerBlock;\n if (otherAsInput.name === \"normal\" || otherAsInput.name === \"tangent\") {\n this.complementW = 0;\n }\n }\n });\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"TransformBlock\";\n }\n /**\n * Gets the vector input\n */\n get vector() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n /**\n * Gets the xyz output component\n */\n get xyz() {\n return this._outputs[1];\n }\n /**\n * Gets the matrix transform input\n */\n get transform() {\n return this._inputs[1];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const vector = this.vector;\n const transform = this.transform;\n if (vector.connectedPoint) {\n // None uniform scaling case.\n if (this.complementW === 0) {\n const comments = `//${this.name}`;\n state._emitFunctionFromInclude(\"helperFunctions\", comments);\n state.sharedData.blocksWithDefines.push(this);\n const transformName = state._getFreeVariableName(`${transform.associatedVariableName}_NUS`);\n state.compilationString += `mat3 ${transformName} = mat3(${transform.associatedVariableName});\\r\\n`;\n state.compilationString += `#ifdef NONUNIFORMSCALING\\r\\n`;\n state.compilationString += `${transformName} = transposeMat3(inverseMat3(${transformName}));\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n switch (vector.connectedPoint.type) {\n case NodeMaterialBlockConnectionPointTypes.Vector2:\n state.compilationString +=\n this._declareOutput(this.output, state) +\n ` = vec4(${transformName} * vec3(${vector.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)});\\r\\n`;\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector3:\n case NodeMaterialBlockConnectionPointTypes.Color3:\n state.compilationString +=\n this._declareOutput(this.output, state) + ` = vec4(${transformName} * ${vector.associatedVariableName}, ${this._writeFloat(this.complementW)});\\r\\n`;\n break;\n default:\n state.compilationString +=\n this._declareOutput(this.output, state) +\n ` = vec4(${transformName} * ${vector.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)});\\r\\n`;\n break;\n }\n }\n else {\n const transformName = transform.associatedVariableName;\n switch (vector.connectedPoint.type) {\n case NodeMaterialBlockConnectionPointTypes.Vector2:\n state.compilationString +=\n this._declareOutput(this.output, state) +\n ` = ${transformName} * vec4(${vector.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)});\\r\\n`;\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector3:\n case NodeMaterialBlockConnectionPointTypes.Color3:\n state.compilationString +=\n this._declareOutput(this.output, state) + ` = ${transformName} * vec4(${vector.associatedVariableName}, ${this._writeFloat(this.complementW)});\\r\\n`;\n break;\n default:\n state.compilationString += this._declareOutput(this.output, state) + ` = ${transformName} * ${vector.associatedVariableName};\\r\\n`;\n break;\n }\n }\n if (this.xyz.hasEndpoints) {\n state.compilationString += this._declareOutput(this.xyz, state) + ` = ${this.output.associatedVariableName}.xyz;\\r\\n`;\n }\n }\n return this;\n }\n /**\n * Update defines for shader compilation\n * @param mesh defines the mesh to be rendered\n * @param nodeMaterial defines the node material requesting the update\n * @param defines defines the material defines to update\n */\n prepareDefines(mesh, nodeMaterial, defines) {\n // Do nothing\n if (mesh.nonUniformScaling) {\n defines.setValue(\"NONUNIFORMSCALING\", true);\n }\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.complementZ = this.complementZ;\n serializationObject.complementW = this.complementW;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.complementZ = serializationObject.complementZ !== undefined ? serializationObject.complementZ : 0.0;\n this.complementW = serializationObject.complementW !== undefined ? serializationObject.complementW : 1.0;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.complementZ = ${this.complementZ};\\r\\n`;\n codeString += `${this._codeVariableName}.complementW = ${this.complementW};\\r\\n`;\n return codeString;\n }\n}\nRegisterClass(\"BABYLON.TransformBlock\", TransformBlock);\n//# sourceMappingURL=transformBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\n/**\n * Block used to output the vertex position\n */\nexport class VertexOutputBlock extends NodeMaterialBlock {\n /**\n * Creates a new VertexOutputBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Vertex, true);\n this.registerInput(\"vector\", NodeMaterialBlockConnectionPointTypes.Vector4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"VertexOutputBlock\";\n }\n /**\n * Gets the vector input component\n */\n get vector() {\n return this._inputs[0];\n }\n _isLogarithmicDepthEnabled(nodeList) {\n for (const node of nodeList) {\n if (node.useLogarithmicDepth) {\n return true;\n }\n }\n return false;\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const input = this.vector;\n state.compilationString += `gl_Position = ${input.associatedVariableName};\\r\\n`;\n if (this._isLogarithmicDepthEnabled(state.sharedData.fragmentOutputNodes)) {\n state._emitUniformFromString(\"logarithmicDepthConstant\", \"float\");\n state._emitVaryingFromString(\"vFragmentDepth\", \"float\");\n state.compilationString += `vFragmentDepth = 1.0 + gl_Position.w;\\r\\n`;\n state.compilationString += `gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant;\\r\\n`;\n }\n return this;\n }\n}\nRegisterClass(\"BABYLON.VertexOutputBlock\", VertexOutputBlock);\n//# sourceMappingURL=vertexOutputBlock.js.map","/**\n * Enum defining the mode of a NodeMaterialBlockConnectionPoint\n */\nexport var NodeMaterialBlockConnectionPointMode;\n(function (NodeMaterialBlockConnectionPointMode) {\n /** Value is an uniform */\n NodeMaterialBlockConnectionPointMode[NodeMaterialBlockConnectionPointMode[\"Uniform\"] = 0] = \"Uniform\";\n /** Value is a mesh attribute */\n NodeMaterialBlockConnectionPointMode[NodeMaterialBlockConnectionPointMode[\"Attribute\"] = 1] = \"Attribute\";\n /** Value is a varying between vertex and fragment shaders */\n NodeMaterialBlockConnectionPointMode[NodeMaterialBlockConnectionPointMode[\"Varying\"] = 2] = \"Varying\";\n /** Mode is undefined */\n NodeMaterialBlockConnectionPointMode[NodeMaterialBlockConnectionPointMode[\"Undefined\"] = 3] = \"Undefined\";\n})(NodeMaterialBlockConnectionPointMode || (NodeMaterialBlockConnectionPointMode = {}));\n//# sourceMappingURL=nodeMaterialBlockConnectionPointMode.js.map","/**\n * Enum used to define system values e.g. values automatically provided by the system\n */\nexport var NodeMaterialSystemValues;\n(function (NodeMaterialSystemValues) {\n /** World */\n NodeMaterialSystemValues[NodeMaterialSystemValues[\"World\"] = 1] = \"World\";\n /** View */\n NodeMaterialSystemValues[NodeMaterialSystemValues[\"View\"] = 2] = \"View\";\n /** Projection */\n NodeMaterialSystemValues[NodeMaterialSystemValues[\"Projection\"] = 3] = \"Projection\";\n /** ViewProjection */\n NodeMaterialSystemValues[NodeMaterialSystemValues[\"ViewProjection\"] = 4] = \"ViewProjection\";\n /** WorldView */\n NodeMaterialSystemValues[NodeMaterialSystemValues[\"WorldView\"] = 5] = \"WorldView\";\n /** WorldViewProjection */\n NodeMaterialSystemValues[NodeMaterialSystemValues[\"WorldViewProjection\"] = 6] = \"WorldViewProjection\";\n /** CameraPosition */\n NodeMaterialSystemValues[NodeMaterialSystemValues[\"CameraPosition\"] = 7] = \"CameraPosition\";\n /** Fog Color */\n NodeMaterialSystemValues[NodeMaterialSystemValues[\"FogColor\"] = 8] = \"FogColor\";\n /** Delta time */\n NodeMaterialSystemValues[NodeMaterialSystemValues[\"DeltaTime\"] = 9] = \"DeltaTime\";\n /** Camera parameters */\n NodeMaterialSystemValues[NodeMaterialSystemValues[\"CameraParameters\"] = 10] = \"CameraParameters\";\n /** Material alpha */\n NodeMaterialSystemValues[NodeMaterialSystemValues[\"MaterialAlpha\"] = 11] = \"MaterialAlpha\";\n})(NodeMaterialSystemValues || (NodeMaterialSystemValues = {}));\n//# sourceMappingURL=nodeMaterialSystemValues.js.map","import { __decorate } from \"../../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../../nodeMaterialDecorator.js\";\nimport { MaterialHelper } from \"../../../materialHelper.js\";\n/**\n * Block used to output the final color\n */\nexport class FragmentOutputBlock extends NodeMaterialBlock {\n /**\n * Create a new FragmentOutputBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment, true);\n /** Gets or sets a boolean indicating if content needs to be converted to gamma space */\n this.convertToGammaSpace = false;\n /** Gets or sets a boolean indicating if content needs to be converted to linear space */\n this.convertToLinearSpace = false;\n /** Gets or sets a boolean indicating if logarithmic depth should be used */\n this.useLogarithmicDepth = false;\n this.registerInput(\"rgba\", NodeMaterialBlockConnectionPointTypes.Color4, true);\n this.registerInput(\"rgb\", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);\n this.registerInput(\"a\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.rgb.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"FragmentOutputBlock\";\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"logarithmicDepthConstant\");\n state._excludeVariableName(\"vFragmentDepth\");\n }\n /**\n * Gets the rgba input component\n */\n get rgba() {\n return this._inputs[0];\n }\n /**\n * Gets the rgb input component\n */\n get rgb() {\n return this._inputs[1];\n }\n /**\n * Gets the a input component\n */\n get a() {\n return this._inputs[2];\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n defines.setValue(this._linearDefineName, this.convertToLinearSpace, true);\n defines.setValue(this._gammaDefineName, this.convertToGammaSpace, true);\n }\n bind(effect, nodeMaterial, mesh) {\n if (this.useLogarithmicDepth && mesh) {\n MaterialHelper.BindLogDepth(undefined, effect, mesh.getScene());\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const rgba = this.rgba;\n const rgb = this.rgb;\n const a = this.a;\n state.sharedData.hints.needAlphaBlending = rgba.isConnected || a.isConnected;\n state.sharedData.blocksWithDefines.push(this);\n if (this.useLogarithmicDepth) {\n state._emitUniformFromString(\"logarithmicDepthConstant\", \"float\");\n state._emitVaryingFromString(\"vFragmentDepth\", \"float\");\n state.sharedData.bindableBlocks.push(this);\n }\n this._linearDefineName = state._getFreeDefineName(\"CONVERTTOLINEAR\");\n this._gammaDefineName = state._getFreeDefineName(\"CONVERTTOGAMMA\");\n const comments = `//${this.name}`;\n state._emitFunctionFromInclude(\"helperFunctions\", comments);\n if (rgba.connectedPoint) {\n if (a.isConnected) {\n state.compilationString += `gl_FragColor = vec4(${rgba.associatedVariableName}.rgb, ${a.associatedVariableName});\\r\\n`;\n }\n else {\n state.compilationString += `gl_FragColor = ${rgba.associatedVariableName};\\r\\n`;\n }\n }\n else if (rgb.connectedPoint) {\n let aValue = \"1.0\";\n if (a.connectedPoint) {\n aValue = a.associatedVariableName;\n }\n if (rgb.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Float) {\n state.compilationString += `gl_FragColor = vec4(${rgb.associatedVariableName}, ${rgb.associatedVariableName}, ${rgb.associatedVariableName}, ${aValue});\\r\\n`;\n }\n else {\n state.compilationString += `gl_FragColor = vec4(${rgb.associatedVariableName}, ${aValue});\\r\\n`;\n }\n }\n else {\n state.sharedData.checks.notConnectedNonOptionalInputs.push(rgba);\n }\n state.compilationString += `#ifdef ${this._linearDefineName}\\r\\n`;\n state.compilationString += `gl_FragColor = toLinearSpace(gl_FragColor);\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n state.compilationString += `#ifdef ${this._gammaDefineName}\\r\\n`;\n state.compilationString += `gl_FragColor = toGammaSpace(gl_FragColor);\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n if (this.useLogarithmicDepth) {\n state.compilationString += `gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5;\\r\\n`;\n }\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n codeString += `${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\\r\\n`;\n codeString += `${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\\r\\n`;\n codeString += `${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.convertToGammaSpace = this.convertToGammaSpace;\n serializationObject.convertToLinearSpace = this.convertToLinearSpace;\n serializationObject.useLogarithmicDepth = this.useLogarithmicDepth;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n var _a;\n super._deserialize(serializationObject, scene, rootUrl);\n this.convertToGammaSpace = serializationObject.convertToGammaSpace;\n this.convertToLinearSpace = serializationObject.convertToLinearSpace;\n this.useLogarithmicDepth = (_a = serializationObject.useLogarithmicDepth) !== null && _a !== void 0 ? _a : false;\n }\n}\n__decorate([\n editableInPropertyPage(\"Convert to gamma space\", PropertyTypeForEdition.Boolean, \"PROPERTIES\", { notifiers: { update: true } })\n], FragmentOutputBlock.prototype, \"convertToGammaSpace\", void 0);\n__decorate([\n editableInPropertyPage(\"Convert to linear space\", PropertyTypeForEdition.Boolean, \"PROPERTIES\", { notifiers: { update: true } })\n], FragmentOutputBlock.prototype, \"convertToLinearSpace\", void 0);\n__decorate([\n editableInPropertyPage(\"Use logarithmic depth\", PropertyTypeForEdition.Boolean, \"PROPERTIES\")\n], FragmentOutputBlock.prototype, \"useLogarithmicDepth\", void 0);\nRegisterClass(\"BABYLON.FragmentOutputBlock\", FragmentOutputBlock);\n//# sourceMappingURL=fragmentOutputBlock.js.map","/**\n * Enum defining the type of animations supported by InputBlock\n */\nexport var AnimatedInputBlockTypes;\n(function (AnimatedInputBlockTypes) {\n /** No animation */\n AnimatedInputBlockTypes[AnimatedInputBlockTypes[\"None\"] = 0] = \"None\";\n /** Time based animation (is incremented by 0.6 each second). Will only work for floats */\n AnimatedInputBlockTypes[AnimatedInputBlockTypes[\"Time\"] = 1] = \"Time\";\n /** Time elapsed (in seconds) since the engine was initialized. Will only work for floats */\n AnimatedInputBlockTypes[AnimatedInputBlockTypes[\"RealTime\"] = 2] = \"RealTime\";\n})(AnimatedInputBlockTypes || (AnimatedInputBlockTypes = {}));\n//# sourceMappingURL=animatedInputBlockTypes.js.map","/* eslint-disable @typescript-eslint/naming-convention */\nimport { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockConnectionPointMode } from \"../../Enums/nodeMaterialBlockConnectionPointMode.js\";\nimport { NodeMaterialSystemValues } from \"../../Enums/nodeMaterialSystemValues.js\";\nimport { Matrix, Vector2, Vector3, Vector4 } from \"../../../../Maths/math.vector.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { GetClass, RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { Color3, Color4, TmpColors } from \"../../../../Maths/math.js\";\nimport { AnimatedInputBlockTypes } from \"./animatedInputBlockTypes.js\";\nimport { Observable } from \"../../../../Misc/observable.js\";\nimport { PrecisionDate } from \"../../../../Misc/precisionDate.js\";\nconst remapAttributeName = {\n position2d: \"position\",\n particle_uv: \"vUV\",\n particle_color: \"vColor\",\n particle_texturemask: \"textureMask\",\n particle_positionw: \"vPositionW\",\n};\nconst attributeInFragmentOnly = {\n particle_uv: true,\n particle_color: true,\n particle_texturemask: true,\n particle_positionw: true,\n};\nconst attributeAsUniform = {\n particle_texturemask: true,\n};\n/**\n * Block used to expose an input value\n */\nexport class InputBlock extends NodeMaterialBlock {\n /**\n * Gets or sets the connection point type (default is float)\n */\n get type() {\n if (this._type === NodeMaterialBlockConnectionPointTypes.AutoDetect) {\n if (this.isUniform && this.value != null) {\n if (!isNaN(this.value)) {\n this._type = NodeMaterialBlockConnectionPointTypes.Float;\n return this._type;\n }\n switch (this.value.getClassName()) {\n case \"Vector2\":\n this._type = NodeMaterialBlockConnectionPointTypes.Vector2;\n return this._type;\n case \"Vector3\":\n this._type = NodeMaterialBlockConnectionPointTypes.Vector3;\n return this._type;\n case \"Vector4\":\n this._type = NodeMaterialBlockConnectionPointTypes.Vector4;\n return this._type;\n case \"Color3\":\n this._type = NodeMaterialBlockConnectionPointTypes.Color3;\n return this._type;\n case \"Color4\":\n this._type = NodeMaterialBlockConnectionPointTypes.Color4;\n return this._type;\n case \"Matrix\":\n this._type = NodeMaterialBlockConnectionPointTypes.Matrix;\n return this._type;\n }\n }\n if (this.isAttribute) {\n switch (this.name) {\n case \"position\":\n case \"normal\":\n case \"particle_positionw\":\n this._type = NodeMaterialBlockConnectionPointTypes.Vector3;\n return this._type;\n case \"uv\":\n case \"uv2\":\n case \"uv3\":\n case \"uv4\":\n case \"uv5\":\n case \"uv6\":\n case \"position2d\":\n case \"particle_uv\":\n this._type = NodeMaterialBlockConnectionPointTypes.Vector2;\n return this._type;\n case \"matricesIndices\":\n case \"matricesWeights\":\n case \"matricesIndicesExtra\":\n case \"matricesWeightsExtra\":\n case \"world0\":\n case \"world1\":\n case \"world2\":\n case \"world3\":\n case \"tangent\":\n this._type = NodeMaterialBlockConnectionPointTypes.Vector4;\n return this._type;\n case \"color\":\n case \"instanceColor\":\n case \"particle_color\":\n case \"particle_texturemask\":\n this._type = NodeMaterialBlockConnectionPointTypes.Color4;\n return this._type;\n }\n }\n if (this.isSystemValue) {\n switch (this._systemValue) {\n case NodeMaterialSystemValues.World:\n case NodeMaterialSystemValues.WorldView:\n case NodeMaterialSystemValues.WorldViewProjection:\n case NodeMaterialSystemValues.View:\n case NodeMaterialSystemValues.ViewProjection:\n case NodeMaterialSystemValues.Projection:\n this._type = NodeMaterialBlockConnectionPointTypes.Matrix;\n return this._type;\n case NodeMaterialSystemValues.CameraPosition:\n this._type = NodeMaterialBlockConnectionPointTypes.Vector3;\n return this._type;\n case NodeMaterialSystemValues.FogColor:\n this._type = NodeMaterialBlockConnectionPointTypes.Color3;\n return this._type;\n case NodeMaterialSystemValues.DeltaTime:\n case NodeMaterialSystemValues.MaterialAlpha:\n this._type = NodeMaterialBlockConnectionPointTypes.Float;\n return this._type;\n case NodeMaterialSystemValues.CameraParameters:\n this._type = NodeMaterialBlockConnectionPointTypes.Vector4;\n return this._type;\n }\n }\n }\n return this._type;\n }\n /**\n * Creates a new InputBlock\n * @param name defines the block name\n * @param target defines the target of that block (Vertex by default)\n * @param type defines the type of the input (can be set to NodeMaterialBlockConnectionPointTypes.AutoDetect)\n */\n constructor(name, target = NodeMaterialBlockTargets.Vertex, type = NodeMaterialBlockConnectionPointTypes.AutoDetect) {\n super(name, target, false, true);\n this._mode = NodeMaterialBlockConnectionPointMode.Undefined;\n this._animationType = AnimatedInputBlockTypes.None;\n /** Gets or set a value used to limit the range of float values */\n this.min = 0;\n /** Gets or set a value used to limit the range of float values */\n this.max = 0;\n /** Gets or set a value indicating that this input can only get 0 and 1 values */\n this.isBoolean = false;\n /** Gets or sets a value used by the Node Material editor to determine how to configure the current value if it is a matrix */\n this.matrixMode = 0;\n /** @internal */\n this._systemValue = null;\n /** Gets or sets a boolean indicating that the value of this input will not change after a build */\n this.isConstant = false;\n /** Gets or sets the group to use to display this block in the Inspector */\n this.groupInInspector = \"\";\n /** Gets an observable raised when the value is changed */\n this.onValueChangedObservable = new Observable();\n /** Gets or sets a boolean indicating if content needs to be converted to gamma space (for color3/4 only) */\n this.convertToGammaSpace = false;\n /** Gets or sets a boolean indicating if content needs to be converted to linear space (for color3/4 only) */\n this.convertToLinearSpace = false;\n this._type = type;\n this.setDefaultValue();\n this.registerOutput(\"output\", type);\n }\n /**\n * Validates if a name is a reserve word.\n * @param newName the new name to be given to the node.\n * @returns false if the name is a reserve word, else true.\n */\n validateBlockName(newName) {\n if (!this.isAttribute) {\n return super.validateBlockName(newName);\n }\n return true;\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n /**\n * Set the source of this connection point to a vertex attribute\n * @param attributeName defines the attribute name (position, uv, normal, etc...). If not specified it will take the connection point name\n * @returns the current connection point\n */\n setAsAttribute(attributeName) {\n this._mode = NodeMaterialBlockConnectionPointMode.Attribute;\n if (attributeName) {\n this.name = attributeName;\n }\n return this;\n }\n /**\n * Set the source of this connection point to a system value\n * @param value define the system value to use (world, view, etc...) or null to switch to manual value\n * @returns the current connection point\n */\n setAsSystemValue(value) {\n this.systemValue = value;\n return this;\n }\n /**\n * Gets or sets the value of that point.\n * Please note that this value will be ignored if valueCallback is defined\n */\n get value() {\n return this._storedValue;\n }\n set value(value) {\n if (this.type === NodeMaterialBlockConnectionPointTypes.Float) {\n if (this.isBoolean) {\n value = value ? 1 : 0;\n }\n else if (this.min !== this.max) {\n value = Math.max(this.min, value);\n value = Math.min(this.max, value);\n }\n }\n this._storedValue = value;\n this._mode = NodeMaterialBlockConnectionPointMode.Uniform;\n this.onValueChangedObservable.notifyObservers(this);\n }\n /**\n * Gets or sets a callback used to get the value of that point.\n * Please note that setting this value will force the connection point to ignore the value property\n */\n get valueCallback() {\n return this._valueCallback;\n }\n set valueCallback(value) {\n this._valueCallback = value;\n this._mode = NodeMaterialBlockConnectionPointMode.Uniform;\n }\n /**\n * Gets or sets the associated variable name in the shader\n */\n get associatedVariableName() {\n return this._associatedVariableName;\n }\n set associatedVariableName(value) {\n this._associatedVariableName = value;\n }\n /** Gets or sets the type of animation applied to the input */\n get animationType() {\n return this._animationType;\n }\n set animationType(value) {\n this._animationType = value;\n }\n /**\n * Gets a boolean indicating that this connection point not defined yet\n */\n get isUndefined() {\n return this._mode === NodeMaterialBlockConnectionPointMode.Undefined;\n }\n /**\n * Gets or sets a boolean indicating that this connection point is coming from an uniform.\n * In this case the connection point name must be the name of the uniform to use.\n * Can only be set on inputs\n */\n get isUniform() {\n return this._mode === NodeMaterialBlockConnectionPointMode.Uniform;\n }\n set isUniform(value) {\n this._mode = value ? NodeMaterialBlockConnectionPointMode.Uniform : NodeMaterialBlockConnectionPointMode.Undefined;\n this.associatedVariableName = \"\";\n }\n /**\n * Gets or sets a boolean indicating that this connection point is coming from an attribute.\n * In this case the connection point name must be the name of the attribute to use\n * Can only be set on inputs\n */\n get isAttribute() {\n return this._mode === NodeMaterialBlockConnectionPointMode.Attribute;\n }\n set isAttribute(value) {\n this._mode = value ? NodeMaterialBlockConnectionPointMode.Attribute : NodeMaterialBlockConnectionPointMode.Undefined;\n this.associatedVariableName = \"\";\n }\n /**\n * Gets or sets a boolean indicating that this connection point is generating a varying variable.\n * Can only be set on exit points\n */\n get isVarying() {\n return this._mode === NodeMaterialBlockConnectionPointMode.Varying;\n }\n set isVarying(value) {\n this._mode = value ? NodeMaterialBlockConnectionPointMode.Varying : NodeMaterialBlockConnectionPointMode.Undefined;\n this.associatedVariableName = \"\";\n }\n /**\n * Gets a boolean indicating that the current connection point is a system value\n */\n get isSystemValue() {\n return this._systemValue != null;\n }\n /**\n * Gets or sets the current well known value or null if not defined as a system value\n */\n get systemValue() {\n return this._systemValue;\n }\n set systemValue(value) {\n this._mode = NodeMaterialBlockConnectionPointMode.Uniform;\n this.associatedVariableName = \"\";\n this._systemValue = value;\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"InputBlock\";\n }\n /**\n * Animate the input if animationType !== None\n * @param scene defines the rendering scene\n */\n animate(scene) {\n switch (this._animationType) {\n case AnimatedInputBlockTypes.Time: {\n if (this.type === NodeMaterialBlockConnectionPointTypes.Float) {\n this.value += scene.getAnimationRatio() * 0.01;\n }\n break;\n }\n case AnimatedInputBlockTypes.RealTime: {\n if (this.type === NodeMaterialBlockConnectionPointTypes.Float) {\n this.value = (PrecisionDate.Now - scene.getEngine().startTime) / 1000;\n }\n break;\n }\n }\n }\n _emitDefine(define) {\n if (define[0] === \"!\") {\n return `#ifndef ${define.substring(1)}\\r\\n`;\n }\n return `#ifdef ${define}\\r\\n`;\n }\n initialize() {\n this.associatedVariableName = \"\";\n }\n /**\n * Set the input block to its default value (based on its type)\n */\n setDefaultValue() {\n switch (this.type) {\n case NodeMaterialBlockConnectionPointTypes.Float:\n this.value = 0;\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector2:\n this.value = Vector2.Zero();\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector3:\n this.value = Vector3.Zero();\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector4:\n this.value = Vector4.Zero();\n break;\n case NodeMaterialBlockConnectionPointTypes.Color3:\n this.value = Color3.White();\n break;\n case NodeMaterialBlockConnectionPointTypes.Color4:\n this.value = new Color4(1, 1, 1, 1);\n break;\n case NodeMaterialBlockConnectionPointTypes.Matrix:\n this.value = Matrix.Identity();\n break;\n }\n }\n _emitConstant(state) {\n switch (this.type) {\n case NodeMaterialBlockConnectionPointTypes.Float:\n return `${state._emitFloat(this.value)}`;\n case NodeMaterialBlockConnectionPointTypes.Vector2:\n return `vec2(${this.value.x}, ${this.value.y})`;\n case NodeMaterialBlockConnectionPointTypes.Vector3:\n return `vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;\n case NodeMaterialBlockConnectionPointTypes.Vector4:\n return `vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;\n case NodeMaterialBlockConnectionPointTypes.Color3:\n TmpColors.Color3[0].set(this.value.r, this.value.g, this.value.b);\n if (this.convertToGammaSpace) {\n TmpColors.Color3[0].toGammaSpaceToRef(TmpColors.Color3[0], state.sharedData.scene.getEngine().useExactSrgbConversions);\n }\n if (this.convertToLinearSpace) {\n TmpColors.Color3[0].toLinearSpaceToRef(TmpColors.Color3[0], state.sharedData.scene.getEngine().useExactSrgbConversions);\n }\n return `vec3(${TmpColors.Color3[0].r}, ${TmpColors.Color3[0].g}, ${TmpColors.Color3[0].b})`;\n case NodeMaterialBlockConnectionPointTypes.Color4:\n TmpColors.Color4[0].set(this.value.r, this.value.g, this.value.b, this.value.a);\n if (this.convertToGammaSpace) {\n TmpColors.Color4[0].toGammaSpaceToRef(TmpColors.Color4[0], state.sharedData.scene.getEngine().useExactSrgbConversions);\n }\n if (this.convertToLinearSpace) {\n TmpColors.Color4[0].toLinearSpaceToRef(TmpColors.Color4[0], state.sharedData.scene.getEngine().useExactSrgbConversions);\n }\n return `vec4(${TmpColors.Color4[0].r}, ${TmpColors.Color4[0].g}, ${TmpColors.Color4[0].b}, ${TmpColors.Color4[0].a})`;\n }\n return \"\";\n }\n /** @internal */\n get _noContextSwitch() {\n return attributeInFragmentOnly[this.name];\n }\n _emit(state, define) {\n var _a;\n // Uniforms\n if (this.isUniform) {\n if (!this.associatedVariableName) {\n this.associatedVariableName = state._getFreeVariableName(\"u_\" + this.name);\n }\n if (this.isConstant) {\n if (state.constants.indexOf(this.associatedVariableName) !== -1) {\n return;\n }\n state.constants.push(this.associatedVariableName);\n state._constantDeclaration += this._declareOutput(this.output, state) + ` = ${this._emitConstant(state)};\\r\\n`;\n return;\n }\n if (state.uniforms.indexOf(this.associatedVariableName) !== -1) {\n return;\n }\n state.uniforms.push(this.associatedVariableName);\n if (define) {\n state._uniformDeclaration += this._emitDefine(define);\n }\n state._uniformDeclaration += `uniform ${state._getGLType(this.type)} ${this.associatedVariableName};\\r\\n`;\n if (define) {\n state._uniformDeclaration += `#endif\\r\\n`;\n }\n // well known\n const hints = state.sharedData.hints;\n if (this._systemValue !== null && this._systemValue !== undefined) {\n switch (this._systemValue) {\n case NodeMaterialSystemValues.WorldView:\n hints.needWorldViewMatrix = true;\n break;\n case NodeMaterialSystemValues.WorldViewProjection:\n hints.needWorldViewProjectionMatrix = true;\n break;\n }\n }\n else {\n if (this._animationType !== AnimatedInputBlockTypes.None) {\n state.sharedData.animatedInputs.push(this);\n }\n }\n return;\n }\n // Attribute\n if (this.isAttribute) {\n this.associatedVariableName = (_a = remapAttributeName[this.name]) !== null && _a !== void 0 ? _a : this.name;\n if (this.target === NodeMaterialBlockTargets.Vertex && state._vertexState) {\n // Attribute for fragment need to be carried over by varyings\n if (attributeInFragmentOnly[this.name]) {\n if (attributeAsUniform[this.name]) {\n state._emitUniformFromString(this.associatedVariableName, state._getGLType(this.type), define);\n }\n else {\n state._emitVaryingFromString(this.associatedVariableName, state._getGLType(this.type), define);\n }\n }\n else {\n this._emit(state._vertexState, define);\n }\n return;\n }\n if (state.attributes.indexOf(this.associatedVariableName) !== -1) {\n return;\n }\n state.attributes.push(this.associatedVariableName);\n if (attributeInFragmentOnly[this.name]) {\n if (attributeAsUniform[this.name]) {\n state._emitUniformFromString(this.associatedVariableName, state._getGLType(this.type), define);\n }\n else {\n state._emitVaryingFromString(this.associatedVariableName, state._getGLType(this.type), define);\n }\n }\n else {\n if (define) {\n state._attributeDeclaration += this._emitDefine(define);\n }\n state._attributeDeclaration += `attribute ${state._getGLType(this.type)} ${this.associatedVariableName};\\r\\n`;\n if (define) {\n state._attributeDeclaration += `#endif\\r\\n`;\n }\n }\n }\n }\n /**\n * @internal\n */\n _transmitWorld(effect, world, worldView, worldViewProjection) {\n if (!this._systemValue) {\n return;\n }\n const variableName = this.associatedVariableName;\n switch (this._systemValue) {\n case NodeMaterialSystemValues.World:\n effect.setMatrix(variableName, world);\n break;\n case NodeMaterialSystemValues.WorldView:\n effect.setMatrix(variableName, worldView);\n break;\n case NodeMaterialSystemValues.WorldViewProjection:\n effect.setMatrix(variableName, worldViewProjection);\n break;\n }\n }\n /**\n * @internal\n */\n _transmit(effect, scene, material) {\n if (this.isAttribute) {\n return;\n }\n const variableName = this.associatedVariableName;\n if (this._systemValue) {\n switch (this._systemValue) {\n case NodeMaterialSystemValues.World:\n case NodeMaterialSystemValues.WorldView:\n case NodeMaterialSystemValues.WorldViewProjection:\n return;\n case NodeMaterialSystemValues.View:\n effect.setMatrix(variableName, scene.getViewMatrix());\n break;\n case NodeMaterialSystemValues.Projection:\n effect.setMatrix(variableName, scene.getProjectionMatrix());\n break;\n case NodeMaterialSystemValues.ViewProjection:\n effect.setMatrix(variableName, scene.getTransformMatrix());\n break;\n case NodeMaterialSystemValues.CameraPosition:\n scene.bindEyePosition(effect, variableName, true);\n break;\n case NodeMaterialSystemValues.FogColor:\n effect.setColor3(variableName, scene.fogColor);\n break;\n case NodeMaterialSystemValues.DeltaTime:\n effect.setFloat(variableName, scene.deltaTime / 1000.0);\n break;\n case NodeMaterialSystemValues.CameraParameters:\n if (scene.activeCamera) {\n effect.setFloat4(variableName, scene.getEngine().hasOriginBottomLeft ? -1 : 1, scene.activeCamera.minZ, scene.activeCamera.maxZ, 1 / scene.activeCamera.maxZ);\n }\n break;\n case NodeMaterialSystemValues.MaterialAlpha:\n effect.setFloat(variableName, material.alpha);\n break;\n }\n return;\n }\n const value = this._valueCallback ? this._valueCallback() : this._storedValue;\n if (value === null) {\n return;\n }\n switch (this.type) {\n case NodeMaterialBlockConnectionPointTypes.Float:\n effect.setFloat(variableName, value);\n break;\n case NodeMaterialBlockConnectionPointTypes.Int:\n effect.setInt(variableName, value);\n break;\n case NodeMaterialBlockConnectionPointTypes.Color3:\n TmpColors.Color3[0].set(this.value.r, this.value.g, this.value.b);\n if (this.convertToGammaSpace) {\n TmpColors.Color3[0].toGammaSpaceToRef(TmpColors.Color3[0], scene.getEngine().useExactSrgbConversions);\n }\n if (this.convertToLinearSpace) {\n TmpColors.Color3[0].toLinearSpaceToRef(TmpColors.Color3[0], scene.getEngine().useExactSrgbConversions);\n }\n effect.setColor3(variableName, TmpColors.Color3[0]);\n break;\n case NodeMaterialBlockConnectionPointTypes.Color4:\n TmpColors.Color4[0].set(this.value.r, this.value.g, this.value.b, this.value.a);\n if (this.convertToGammaSpace) {\n TmpColors.Color4[0].toGammaSpaceToRef(TmpColors.Color4[0], scene.getEngine().useExactSrgbConversions);\n }\n if (this.convertToLinearSpace) {\n TmpColors.Color4[0].toLinearSpaceToRef(TmpColors.Color4[0], scene.getEngine().useExactSrgbConversions);\n }\n effect.setDirectColor4(variableName, TmpColors.Color4[0]);\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector2:\n effect.setVector2(variableName, value);\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector3:\n effect.setVector3(variableName, value);\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector4:\n effect.setVector4(variableName, value);\n break;\n case NodeMaterialBlockConnectionPointTypes.Matrix:\n effect.setMatrix(variableName, value);\n break;\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (this.isUniform || this.isSystemValue) {\n state.sharedData.inputBlocks.push(this);\n }\n this._emit(state);\n }\n _dumpPropertiesCode() {\n const variableName = this._codeVariableName;\n if (this.isAttribute) {\n return super._dumpPropertiesCode() + `${variableName}.setAsAttribute(\"${this.name}\");\\r\\n`;\n }\n if (this.isSystemValue) {\n return super._dumpPropertiesCode() + `${variableName}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${NodeMaterialSystemValues[this._systemValue]});\\r\\n`;\n }\n if (this.isUniform) {\n const codes = [];\n let valueString = \"\";\n switch (this.type) {\n case NodeMaterialBlockConnectionPointTypes.Float:\n valueString = `${this.value}`;\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector2:\n valueString = `new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector3:\n valueString = `new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector4:\n valueString = `new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;\n break;\n case NodeMaterialBlockConnectionPointTypes.Color3:\n valueString = `new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`;\n if (this.convertToGammaSpace) {\n valueString += \".toGammaSpace()\";\n }\n if (this.convertToLinearSpace) {\n valueString += \".toLinearSpace()\";\n }\n break;\n case NodeMaterialBlockConnectionPointTypes.Color4:\n valueString = `new BABYLON.Color4(${this.value.r}, ${this.value.g}, ${this.value.b}, ${this.value.a})`;\n if (this.convertToGammaSpace) {\n valueString += \".toGammaSpace()\";\n }\n if (this.convertToLinearSpace) {\n valueString += \".toLinearSpace()\";\n }\n break;\n case NodeMaterialBlockConnectionPointTypes.Matrix:\n valueString = `BABYLON.Matrix.FromArray([${this.value.m}])`;\n break;\n }\n // Common Property \"Value\"\n codes.push(`${variableName}.value = ${valueString}`);\n // Float-Value-Specific Properties\n if (this.type === NodeMaterialBlockConnectionPointTypes.Float) {\n codes.push(`${variableName}.min = ${this.min}`, `${variableName}.max = ${this.max}`, `${variableName}.isBoolean = ${this.isBoolean}`, `${variableName}.matrixMode = ${this.matrixMode}`, `${variableName}.animationType = BABYLON.AnimatedInputBlockTypes.${AnimatedInputBlockTypes[this.animationType]}`);\n }\n // Common Property \"Type\"\n codes.push(`${variableName}.isConstant = ${this.isConstant}`);\n codes.push(\"\");\n return super._dumpPropertiesCode() + codes.join(\";\\r\\n\");\n }\n return super._dumpPropertiesCode();\n }\n dispose() {\n this.onValueChangedObservable.clear();\n super.dispose();\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.type = this.type;\n serializationObject.mode = this._mode;\n serializationObject.systemValue = this._systemValue;\n serializationObject.animationType = this._animationType;\n serializationObject.min = this.min;\n serializationObject.max = this.max;\n serializationObject.isBoolean = this.isBoolean;\n serializationObject.matrixMode = this.matrixMode;\n serializationObject.isConstant = this.isConstant;\n serializationObject.groupInInspector = this.groupInInspector;\n serializationObject.convertToGammaSpace = this.convertToGammaSpace;\n serializationObject.convertToLinearSpace = this.convertToLinearSpace;\n if (this._storedValue != null && this._mode === NodeMaterialBlockConnectionPointMode.Uniform) {\n if (this._storedValue.asArray) {\n serializationObject.valueType = \"BABYLON.\" + this._storedValue.getClassName();\n serializationObject.value = this._storedValue.asArray();\n }\n else {\n serializationObject.valueType = \"number\";\n serializationObject.value = this._storedValue;\n }\n }\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n this._mode = serializationObject.mode;\n super._deserialize(serializationObject, scene, rootUrl);\n this._type = serializationObject.type;\n this._systemValue = serializationObject.systemValue || serializationObject.wellKnownValue;\n this._animationType = serializationObject.animationType;\n this.min = serializationObject.min || 0;\n this.max = serializationObject.max || 0;\n this.isBoolean = !!serializationObject.isBoolean;\n this.matrixMode = serializationObject.matrixMode || 0;\n this.isConstant = !!serializationObject.isConstant;\n this.groupInInspector = serializationObject.groupInInspector || \"\";\n this.convertToGammaSpace = !!serializationObject.convertToGammaSpace;\n this.convertToLinearSpace = !!serializationObject.convertToLinearSpace;\n // Tangents back compat\n if (serializationObject.name === \"tangent\" &&\n serializationObject.mode === NodeMaterialBlockConnectionPointMode.Attribute &&\n serializationObject.type === NodeMaterialBlockConnectionPointTypes.Vector3) {\n this._type = NodeMaterialBlockConnectionPointTypes.Vector4;\n }\n if (!serializationObject.valueType) {\n return;\n }\n if (serializationObject.valueType === \"number\") {\n this._storedValue = serializationObject.value;\n }\n else {\n const valueType = GetClass(serializationObject.valueType);\n if (valueType) {\n this._storedValue = valueType.FromArray(serializationObject.value);\n }\n }\n }\n}\nRegisterClass(\"BABYLON.InputBlock\", InputBlock);\n//# sourceMappingURL=inputBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { Texture } from \"../../../Textures/texture.js\";\n/**\n * Base block used as input for post process\n */\nexport class CurrentScreenBlock extends NodeMaterialBlock {\n /**\n * Create a new CurrentScreenBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.VertexAndFragment);\n this._samplerName = \"textureSampler\";\n /**\n * Gets or sets a boolean indicating if content needs to be converted to gamma space\n */\n this.convertToGammaSpace = false;\n /**\n * Gets or sets a boolean indicating if content needs to be converted to linear space\n */\n this.convertToLinearSpace = false;\n this._isUnique = false;\n this.registerInput(\"uv\", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.VertexAndFragment);\n this.registerOutput(\"rgba\", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"rgb\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"r\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"g\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"b\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"a\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector2 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);\n this._inputs[0]._prioritizeVertex = false;\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"CurrentScreenBlock\";\n }\n /**\n * Gets the uv input component\n */\n get uv() {\n return this._inputs[0];\n }\n /**\n * Gets the rgba output component\n */\n get rgba() {\n return this._outputs[0];\n }\n /**\n * Gets the rgb output component\n */\n get rgb() {\n return this._outputs[1];\n }\n /**\n * Gets the r output component\n */\n get r() {\n return this._outputs[2];\n }\n /**\n * Gets the g output component\n */\n get g() {\n return this._outputs[3];\n }\n /**\n * Gets the b output component\n */\n get b() {\n return this._outputs[4];\n }\n /**\n * Gets the a output component\n */\n get a() {\n return this._outputs[5];\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"textureSampler\");\n }\n get target() {\n if (!this.uv.isConnected) {\n return NodeMaterialBlockTargets.VertexAndFragment;\n }\n if (this.uv.sourceBlock.isInput) {\n return NodeMaterialBlockTargets.VertexAndFragment;\n }\n return NodeMaterialBlockTargets.Fragment;\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n defines.setValue(this._linearDefineName, this.convertToGammaSpace, true);\n defines.setValue(this._gammaDefineName, this.convertToLinearSpace, true);\n }\n isReady() {\n if (this.texture && !this.texture.isReadyOrNotBlocking()) {\n return false;\n }\n return true;\n }\n _injectVertexCode(state) {\n const uvInput = this.uv;\n if (uvInput.connectedPoint.ownerBlock.isInput) {\n const uvInputOwnerBlock = uvInput.connectedPoint.ownerBlock;\n if (!uvInputOwnerBlock.isAttribute) {\n state._emitUniformFromString(uvInput.associatedVariableName, \"vec2\");\n }\n }\n this._mainUVName = \"vMain\" + uvInput.associatedVariableName;\n state._emitVaryingFromString(this._mainUVName, \"vec2\");\n state.compilationString += `${this._mainUVName} = ${uvInput.associatedVariableName}.xy;\\r\\n`;\n if (!this._outputs.some((o) => o.isConnectedInVertexShader)) {\n return;\n }\n this._writeTextureRead(state, true);\n for (const output of this._outputs) {\n if (output.hasEndpoints) {\n this._writeOutput(state, output, output.name, true);\n }\n }\n }\n _writeTextureRead(state, vertexMode = false) {\n const uvInput = this.uv;\n if (vertexMode) {\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n return;\n }\n state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${uvInput.associatedVariableName});\\r\\n`;\n return;\n }\n if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {\n state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${uvInput.associatedVariableName});\\r\\n`;\n return;\n }\n state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\\r\\n`;\n }\n _writeOutput(state, output, swizzle, vertexMode = false) {\n if (vertexMode) {\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n return;\n }\n state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\\r\\n`;\n return;\n }\n if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {\n state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\\r\\n`;\n return;\n }\n state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\\r\\n`;\n state.compilationString += `#ifdef ${this._linearDefineName}\\r\\n`;\n state.compilationString += `${output.associatedVariableName} = toGammaSpace(${output.associatedVariableName});\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n state.compilationString += `#ifdef ${this._gammaDefineName}\\r\\n`;\n state.compilationString += `${output.associatedVariableName} = toLinearSpace(${output.associatedVariableName});\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n }\n _buildBlock(state) {\n super._buildBlock(state);\n this._tempTextureRead = state._getFreeVariableName(\"tempTextureRead\");\n if (state.sharedData.blockingBlocks.indexOf(this) < 0) {\n state.sharedData.blockingBlocks.push(this);\n }\n if (state.sharedData.textureBlocks.indexOf(this) < 0) {\n state.sharedData.textureBlocks.push(this);\n }\n if (state.sharedData.blocksWithDefines.indexOf(this) < 0) {\n state.sharedData.blocksWithDefines.push(this);\n }\n if (state.target !== NodeMaterialBlockTargets.Fragment) {\n // Vertex\n state._emit2DSampler(this._samplerName);\n this._injectVertexCode(state);\n return;\n }\n // Fragment\n if (!this._outputs.some((o) => o.isConnectedInFragmentShader)) {\n return;\n }\n state._emit2DSampler(this._samplerName);\n this._linearDefineName = state._getFreeDefineName(\"ISLINEAR\");\n this._gammaDefineName = state._getFreeDefineName(\"ISGAMMA\");\n const comments = `//${this.name}`;\n state._emitFunctionFromInclude(\"helperFunctions\", comments);\n this._writeTextureRead(state);\n for (const output of this._outputs) {\n if (output.hasEndpoints) {\n this._writeOutput(state, output, output.name);\n }\n }\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.convertToGammaSpace = this.convertToGammaSpace;\n serializationObject.convertToLinearSpace = this.convertToLinearSpace;\n if (this.texture && !this.texture.isRenderTarget) {\n serializationObject.texture = this.texture.serialize();\n }\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.convertToGammaSpace = serializationObject.convertToGammaSpace;\n this.convertToLinearSpace = !!serializationObject.convertToLinearSpace;\n if (serializationObject.texture) {\n rootUrl = serializationObject.texture.url.indexOf(\"data:\") === 0 ? \"\" : rootUrl;\n this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl);\n }\n }\n}\nRegisterClass(\"BABYLON.CurrentScreenBlock\", CurrentScreenBlock);\n//# sourceMappingURL=currentScreenBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { Texture } from \"../../../Textures/texture.js\";\n/**\n * Base block used for the particle texture\n */\nexport class ParticleTextureBlock extends NodeMaterialBlock {\n /**\n * Create a new ParticleTextureBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this._samplerName = \"diffuseSampler\";\n /**\n * Gets or sets a boolean indicating if content needs to be converted to gamma space\n */\n this.convertToGammaSpace = false;\n /**\n * Gets or sets a boolean indicating if content needs to be converted to linear space\n */\n this.convertToLinearSpace = false;\n this._isUnique = false;\n this.registerInput(\"uv\", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.VertexAndFragment);\n this.registerOutput(\"rgba\", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"rgb\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"r\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"g\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"b\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"a\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector2 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ParticleTextureBlock\";\n }\n /**\n * Gets the uv input component\n */\n get uv() {\n return this._inputs[0];\n }\n /**\n * Gets the rgba output component\n */\n get rgba() {\n return this._outputs[0];\n }\n /**\n * Gets the rgb output component\n */\n get rgb() {\n return this._outputs[1];\n }\n /**\n * Gets the r output component\n */\n get r() {\n return this._outputs[2];\n }\n /**\n * Gets the g output component\n */\n get g() {\n return this._outputs[3];\n }\n /**\n * Gets the b output component\n */\n get b() {\n return this._outputs[4];\n }\n /**\n * Gets the a output component\n */\n get a() {\n return this._outputs[5];\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"diffuseSampler\");\n }\n autoConfigure(material) {\n if (!this.uv.isConnected) {\n let uvInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"particle_uv\");\n if (!uvInput) {\n uvInput = new InputBlock(\"uv\");\n uvInput.setAsAttribute(\"particle_uv\");\n }\n uvInput.output.connectTo(this.uv);\n }\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n defines.setValue(this._linearDefineName, this.convertToGammaSpace, true);\n defines.setValue(this._gammaDefineName, this.convertToLinearSpace, true);\n }\n isReady() {\n if (this.texture && !this.texture.isReadyOrNotBlocking()) {\n return false;\n }\n return true;\n }\n _writeOutput(state, output, swizzle) {\n state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\\r\\n`;\n state.compilationString += `#ifdef ${this._linearDefineName}\\r\\n`;\n state.compilationString += `${output.associatedVariableName} = toGammaSpace(${output.associatedVariableName});\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n state.compilationString += `#ifdef ${this._gammaDefineName}\\r\\n`;\n state.compilationString += `${output.associatedVariableName} = toLinearSpace(${output.associatedVariableName});\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (state.target === NodeMaterialBlockTargets.Vertex) {\n return;\n }\n this._tempTextureRead = state._getFreeVariableName(\"tempTextureRead\");\n state._emit2DSampler(this._samplerName);\n state.sharedData.blockingBlocks.push(this);\n state.sharedData.textureBlocks.push(this);\n state.sharedData.blocksWithDefines.push(this);\n this._linearDefineName = state._getFreeDefineName(\"ISLINEAR\");\n this._gammaDefineName = state._getFreeDefineName(\"ISGAMMA\");\n const comments = `//${this.name}`;\n state._emitFunctionFromInclude(\"helperFunctions\", comments);\n state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this.uv.associatedVariableName});\\r\\n`;\n for (const output of this._outputs) {\n if (output.hasEndpoints) {\n this._writeOutput(state, output, output.name);\n }\n }\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.convertToGammaSpace = this.convertToGammaSpace;\n serializationObject.convertToLinearSpace = this.convertToLinearSpace;\n if (this.texture && !this.texture.isRenderTarget) {\n serializationObject.texture = this.texture.serialize();\n }\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.convertToGammaSpace = serializationObject.convertToGammaSpace;\n this.convertToLinearSpace = !!serializationObject.convertToLinearSpace;\n if (serializationObject.texture) {\n rootUrl = serializationObject.texture.url.indexOf(\"data:\") === 0 ? \"\" : rootUrl;\n this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl);\n }\n }\n}\nRegisterClass(\"BABYLON.ParticleTextureBlock\", ParticleTextureBlock);\n//# sourceMappingURL=particleTextureBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\n/**\n * Block used for the particle ramp gradient section\n */\nexport class ParticleRampGradientBlock extends NodeMaterialBlock {\n /**\n * Create a new ParticleRampGradientBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this._isUnique = true;\n this.registerInput(\"color\", NodeMaterialBlockConnectionPointTypes.Color4, false, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"rampColor\", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Fragment);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ParticleRampGradientBlock\";\n }\n /**\n * Gets the color input component\n */\n get color() {\n return this._inputs[0];\n }\n /**\n * Gets the rampColor output component\n */\n get rampColor() {\n return this._outputs[0];\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"remapRanges\");\n state._excludeVariableName(\"rampSampler\");\n state._excludeVariableName(\"baseColor\");\n state._excludeVariableName(\"alpha\");\n state._excludeVariableName(\"remappedColorIndex\");\n state._excludeVariableName(\"rampColor\");\n state._excludeVariableName(\"finalAlpha\");\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (state.target === NodeMaterialBlockTargets.Vertex) {\n return;\n }\n state._emit2DSampler(\"rampSampler\");\n state._emitVaryingFromString(\"remapRanges\", \"vec4\", \"RAMPGRADIENT\");\n state.compilationString += `\r\n #ifdef RAMPGRADIENT\r\n vec4 baseColor = ${this.color.associatedVariableName};\r\n float alpha = ${this.color.associatedVariableName}.a;\r\n\r\n float remappedColorIndex = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0);\r\n\r\n vec4 rampColor = texture2D(rampSampler, vec2(1.0 - remappedColorIndex, 0.));\r\n baseColor.rgb *= rampColor.rgb;\r\n\r\n // Remapped alpha\r\n float finalAlpha = baseColor.a;\r\n baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0);\r\n\r\n ${this._declareOutput(this.rampColor, state)} = baseColor;\r\n #else\r\n ${this._declareOutput(this.rampColor, state)} = ${this.color.associatedVariableName};\r\n #endif\r\n `;\n return this;\n }\n}\nRegisterClass(\"BABYLON.ParticleRampGradientBlock\", ParticleRampGradientBlock);\n//# sourceMappingURL=particleRampGradientBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\n/**\n * Block used for the particle blend multiply section\n */\nexport class ParticleBlendMultiplyBlock extends NodeMaterialBlock {\n /**\n * Create a new ParticleBlendMultiplyBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this._isUnique = true;\n this.registerInput(\"color\", NodeMaterialBlockConnectionPointTypes.Color4, false, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"alphaTexture\", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"alphaColor\", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"blendColor\", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Fragment);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ParticleBlendMultiplyBlock\";\n }\n /**\n * Gets the color input component\n */\n get color() {\n return this._inputs[0];\n }\n /**\n * Gets the alphaTexture input component\n */\n get alphaTexture() {\n return this._inputs[1];\n }\n /**\n * Gets the alphaColor input component\n */\n get alphaColor() {\n return this._inputs[2];\n }\n /**\n * Gets the blendColor output component\n */\n get blendColor() {\n return this._outputs[0];\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"sourceAlpha\");\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (state.target === NodeMaterialBlockTargets.Vertex) {\n return;\n }\n state.compilationString += `\r\n #ifdef BLENDMULTIPLYMODE\r\n ${this._declareOutput(this.blendColor, state)};\r\n float sourceAlpha = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName};\r\n ${this.blendColor.associatedVariableName}.rgb = ${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha);\r\n ${this.blendColor.associatedVariableName}.a = ${this.color.associatedVariableName}.a;\r\n #else\r\n ${this._declareOutput(this.blendColor, state)} = ${this.color.associatedVariableName};\r\n #endif\r\n `;\n return this;\n }\n}\nRegisterClass(\"BABYLON.ParticleBlendMultiplyBlock\", ParticleBlendMultiplyBlock);\n//# sourceMappingURL=particleBlendMultiplyBlock.js.map","/**\n * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.\n * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)\n */\nexport class EffectFallbacks {\n constructor() {\n this._defines = {};\n this._currentRank = 32;\n this._maxRank = -1;\n this._mesh = null;\n }\n /**\n * Removes the fallback from the bound mesh.\n */\n unBindMesh() {\n this._mesh = null;\n }\n /**\n * Adds a fallback on the specified property.\n * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)\n * @param define The name of the define in the shader\n */\n addFallback(rank, define) {\n if (!this._defines[rank]) {\n if (rank < this._currentRank) {\n this._currentRank = rank;\n }\n if (rank > this._maxRank) {\n this._maxRank = rank;\n }\n this._defines[rank] = new Array();\n }\n this._defines[rank].push(define);\n }\n /**\n * Sets the mesh to use CPU skinning when needing to fallback.\n * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)\n * @param mesh The mesh to use the fallbacks.\n */\n addCPUSkinningFallback(rank, mesh) {\n this._mesh = mesh;\n if (rank < this._currentRank) {\n this._currentRank = rank;\n }\n if (rank > this._maxRank) {\n this._maxRank = rank;\n }\n }\n /**\n * Checks to see if more fallbacks are still available.\n */\n get hasMoreFallbacks() {\n return this._currentRank <= this._maxRank;\n }\n /**\n * Removes the defines that should be removed when falling back.\n * @param currentDefines defines the current define statements for the shader.\n * @param effect defines the current effect we try to compile\n * @returns The resulting defines with defines of the current rank removed.\n */\n reduce(currentDefines, effect) {\n // First we try to switch to CPU skinning\n if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {\n this._mesh.computeBonesUsingShaders = false;\n currentDefines = currentDefines.replace(\"#define NUM_BONE_INFLUENCERS \" + this._mesh.numBoneInfluencers, \"#define NUM_BONE_INFLUENCERS 0\");\n effect._bonesComputationForcedToCPU = true;\n const scene = this._mesh.getScene();\n for (let index = 0; index < scene.meshes.length; index++) {\n const otherMesh = scene.meshes[index];\n if (!otherMesh.material) {\n if (!this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {\n otherMesh.computeBonesUsingShaders = false;\n }\n continue;\n }\n if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {\n continue;\n }\n if (otherMesh.material.getEffect() === effect) {\n otherMesh.computeBonesUsingShaders = false;\n }\n else if (otherMesh.subMeshes) {\n for (const subMesh of otherMesh.subMeshes) {\n const subMeshEffect = subMesh.effect;\n if (subMeshEffect === effect) {\n otherMesh.computeBonesUsingShaders = false;\n break;\n }\n }\n }\n }\n }\n else {\n const currentFallbacks = this._defines[this._currentRank];\n if (currentFallbacks) {\n for (let index = 0; index < currentFallbacks.length; index++) {\n currentDefines = currentDefines.replace(\"#define \" + currentFallbacks[index], \"\");\n }\n }\n this._currentRank++;\n }\n return currentDefines;\n }\n}\n//# sourceMappingURL=effectFallbacks.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"postprocessVertexShader\";\nconst shader = `attribute vec2 position;\runiform vec2 scale;\rvarying vec2 vUV;\rconst vec2 madd=vec2(0.5,0.5);\r#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=(position*madd+madd)*scale;\rgl_Position=vec4(position,0.0,1.0);\r#define CUSTOM_VERTEX_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const postprocessVertexShader = { name, shader };\n//# sourceMappingURL=postprocess.vertex.js.map","import { InternalTextureSource } from \"../Materials/Textures/internalTexture.js\";\n\n/**\n * Wrapper around a render target (either single or multi textures)\n */\nexport class RenderTargetWrapper {\n /**\n * Gets the depth/stencil texture (if created by a createDepthStencilTexture() call)\n */\n get depthStencilTexture() {\n return this._depthStencilTexture;\n }\n /**\n * Indicates if the depth/stencil texture has a stencil aspect\n */\n get depthStencilTextureWithStencil() {\n return this._depthStencilTextureWithStencil;\n }\n /**\n * Defines if the render target wrapper is for a cube texture or if false a 2d texture\n */\n get isCube() {\n return this._isCube;\n }\n /**\n * Defines if the render target wrapper is for a single or multi target render wrapper\n */\n get isMulti() {\n return this._isMulti;\n }\n /**\n * Defines if the render target wrapper is for a single or an array of textures\n */\n get is2DArray() {\n return this.layers > 0;\n }\n /**\n * Gets the size of the render target wrapper (used for cubes, as width=height in this case)\n */\n get size() {\n return this.width;\n }\n /**\n * Gets the width of the render target wrapper\n */\n get width() {\n return this._size.width || this._size;\n }\n /**\n * Gets the height of the render target wrapper\n */\n get height() {\n return this._size.height || this._size;\n }\n /**\n * Gets the number of layers of the render target wrapper (only used if is2DArray is true and wrapper is not a multi render target)\n */\n get layers() {\n return this._size.layers || 0;\n }\n /**\n * Gets the render texture. If this is a multi render target, gets the first texture\n */\n get texture() {\n var _a, _b;\n return (_b = (_a = this._textures) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : null;\n }\n /**\n * Gets the list of render textures. If we are not in a multi render target, the list will be null (use the texture getter instead)\n */\n get textures() {\n return this._textures;\n }\n /**\n * Gets the face indices that correspond to the list of render textures. If we are not in a multi render target, the list will be null\n */\n get faceIndices() {\n return this._faceIndices;\n }\n /**\n * Gets the layer indices that correspond to the list of render textures. If we are not in a multi render target, the list will be null\n */\n get layerIndices() {\n return this._layerIndices;\n }\n /**\n * Gets the sample count of the render target\n */\n get samples() {\n return this._samples;\n }\n /**\n * Sets the sample count of the render target\n * @param value sample count\n * @param initializeBuffers If set to true, the engine will make an initializing call to drawBuffers (only used when isMulti=true).\n * @param force true to force calling the update sample count engine function even if the current sample count is equal to value\n * @returns the sample count that has been set\n */\n setSamples(value, initializeBuffers = true, force = false) {\n if (this.samples === value && !force) {\n return value;\n }\n const result = this._isMulti\n ? this._engine.updateMultipleRenderTargetTextureSampleCount(this, value, initializeBuffers)\n : this._engine.updateRenderTargetTextureSampleCount(this, value);\n this._samples = value;\n return result;\n }\n /**\n * Initializes the render target wrapper\n * @param isMulti true if the wrapper is a multi render target\n * @param isCube true if the wrapper should render to a cube texture\n * @param size size of the render target (width/height/layers)\n * @param engine engine used to create the render target\n */\n constructor(isMulti, isCube, size, engine) {\n this._textures = null;\n this._faceIndices = null;\n this._layerIndices = null;\n /** @internal */\n this._samples = 1;\n /** @internal */\n this._attachments = null;\n /** @internal */\n this._generateStencilBuffer = false;\n /** @internal */\n this._generateDepthBuffer = false;\n /** @internal */\n this._depthStencilTextureWithStencil = false;\n this._isMulti = isMulti;\n this._isCube = isCube;\n this._size = size;\n this._engine = engine;\n this._depthStencilTexture = null;\n }\n /**\n * Sets the render target texture(s)\n * @param textures texture(s) to set\n */\n setTextures(textures) {\n if (Array.isArray(textures)) {\n this._textures = textures;\n }\n else if (textures) {\n this._textures = [textures];\n }\n else {\n this._textures = null;\n }\n }\n /**\n * Set a texture in the textures array\n * @param texture The texture to set\n * @param index The index in the textures array to set\n * @param disposePrevious If this function should dispose the previous texture\n */\n setTexture(texture, index = 0, disposePrevious = true) {\n if (!this._textures) {\n this._textures = [];\n }\n if (this._textures[index] && disposePrevious) {\n this._textures[index].dispose();\n }\n this._textures[index] = texture;\n }\n /**\n * Sets the layer and face indices of every render target texture bound to each color attachment\n * @param layers The layers of each texture to be set\n * @param faces The faces of each texture to be set\n */\n setLayerAndFaceIndices(layers, faces) {\n this._layerIndices = layers;\n this._faceIndices = faces;\n }\n /**\n * Sets the layer and face indices of a texture in the textures array that should be bound to each color attachment\n * @param index The index of the texture in the textures array to modify\n * @param layer The layer of the texture to be set\n * @param face The face of the texture to be set\n */\n setLayerAndFaceIndex(index = 0, layer, face) {\n if (!this._layerIndices) {\n this._layerIndices = [];\n }\n if (!this._faceIndices) {\n this._faceIndices = [];\n }\n if (layer !== undefined && layer >= 0) {\n this._layerIndices[index] = layer;\n }\n if (face !== undefined && face >= 0) {\n this._faceIndices[index] = face;\n }\n }\n /**\n * Creates the depth/stencil texture\n * @param comparisonFunction Comparison function to use for the texture\n * @param bilinearFiltering true if bilinear filtering should be used when sampling the texture\n * @param generateStencil true if the stencil aspect should also be created\n * @param samples sample count to use when creating the texture\n * @param format format of the depth texture\n * @param label defines the label to use for the texture (for debugging purpose only)\n * @returns the depth/stencil created texture\n */\n createDepthStencilTexture(comparisonFunction = 0, bilinearFiltering = true, generateStencil = false, samples = 1, format = 14, label) {\n var _a;\n (_a = this._depthStencilTexture) === null || _a === void 0 ? void 0 : _a.dispose();\n this._depthStencilTextureWithStencil = generateStencil;\n this._depthStencilTexture = this._engine.createDepthStencilTexture(this._size, {\n bilinearFiltering,\n comparisonFunction,\n generateStencil,\n isCube: this._isCube,\n samples,\n depthTextureFormat: format,\n label,\n }, this);\n return this._depthStencilTexture;\n }\n /**\n * Shares the depth buffer of this render target with another render target.\n * @internal\n * @param renderTarget Destination renderTarget\n */\n _shareDepth(renderTarget) {\n if (this._depthStencilTexture) {\n if (renderTarget._depthStencilTexture) {\n renderTarget._depthStencilTexture.dispose();\n }\n renderTarget._depthStencilTexture = this._depthStencilTexture;\n this._depthStencilTexture.incrementReferences();\n }\n }\n /**\n * @internal\n */\n _swapAndDie(target) {\n if (this.texture) {\n this.texture._swapAndDie(target);\n }\n this._textures = null;\n this.dispose(true);\n }\n _cloneRenderTargetWrapper() {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n let rtw = null;\n if (this._isMulti) {\n const textureArray = this.textures;\n if (textureArray && textureArray.length > 0) {\n let generateDepthTexture = false;\n let textureCount = textureArray.length;\n const lastTextureSource = textureArray[textureArray.length - 1]._source;\n if (lastTextureSource === InternalTextureSource.Depth || lastTextureSource === InternalTextureSource.DepthStencil) {\n generateDepthTexture = true;\n textureCount--;\n }\n const samplingModes = [];\n const types = [];\n const formats = [];\n const targetTypes = [];\n const faceIndex = [];\n const layerIndex = [];\n const layerCounts = [];\n const internalTexture2Index = {};\n for (let i = 0; i < textureCount; ++i) {\n const texture = textureArray[i];\n samplingModes.push(texture.samplingMode);\n types.push(texture.type);\n formats.push(texture.format);\n const index = internalTexture2Index[texture.uniqueId];\n if (index !== undefined) {\n targetTypes.push(-1);\n layerCounts.push(0);\n }\n else {\n internalTexture2Index[texture.uniqueId] = i;\n if (texture.is2DArray) {\n targetTypes.push(35866);\n layerCounts.push(texture.depth);\n }\n else if (texture.isCube) {\n targetTypes.push(34067);\n layerCounts.push(0);\n } /*else if (texture.isCubeArray) {\n targetTypes.push(3735928559);\n layerCounts.push(texture.depth);\n }*/\n else if (texture.is3D) {\n targetTypes.push(32879);\n layerCounts.push(texture.depth);\n }\n else {\n targetTypes.push(3553);\n layerCounts.push(0);\n }\n }\n if (this._faceIndices) {\n faceIndex.push((_a = this._faceIndices[i]) !== null && _a !== void 0 ? _a : 0);\n }\n if (this._layerIndices) {\n layerIndex.push((_b = this._layerIndices[i]) !== null && _b !== void 0 ? _b : 0);\n }\n }\n const optionsMRT = {\n samplingModes,\n generateMipMaps: textureArray[0].generateMipMaps,\n generateDepthBuffer: this._generateDepthBuffer,\n generateStencilBuffer: this._generateStencilBuffer,\n generateDepthTexture,\n types,\n formats,\n textureCount,\n targetTypes,\n faceIndex,\n layerIndex,\n layerCounts,\n };\n const size = {\n width: this.width,\n height: this.height,\n };\n rtw = this._engine.createMultipleRenderTarget(size, optionsMRT);\n for (let i = 0; i < textureCount; ++i) {\n if (targetTypes[i] !== -1) {\n continue;\n }\n const index = internalTexture2Index[textureArray[i].uniqueId];\n rtw.setTexture(rtw.textures[index], i);\n }\n }\n }\n else {\n const options = {};\n options.generateDepthBuffer = this._generateDepthBuffer;\n options.generateMipMaps = (_d = (_c = this.texture) === null || _c === void 0 ? void 0 : _c.generateMipMaps) !== null && _d !== void 0 ? _d : false;\n options.generateStencilBuffer = this._generateStencilBuffer;\n options.samplingMode = (_e = this.texture) === null || _e === void 0 ? void 0 : _e.samplingMode;\n options.type = (_f = this.texture) === null || _f === void 0 ? void 0 : _f.type;\n options.format = (_g = this.texture) === null || _g === void 0 ? void 0 : _g.format;\n if (this.isCube) {\n rtw = this._engine.createRenderTargetCubeTexture(this.width, options);\n }\n else {\n const size = {\n width: this.width,\n height: this.height,\n layers: this.is2DArray ? (_h = this.texture) === null || _h === void 0 ? void 0 : _h.depth : undefined,\n };\n rtw = this._engine.createRenderTargetTexture(size, options);\n }\n rtw.texture.isReady = true;\n }\n return rtw;\n }\n _swapRenderTargetWrapper(target) {\n if (this._textures && target._textures) {\n for (let i = 0; i < this._textures.length; ++i) {\n this._textures[i]._swapAndDie(target._textures[i], false);\n target._textures[i].isReady = true;\n }\n }\n if (this._depthStencilTexture && target._depthStencilTexture) {\n this._depthStencilTexture._swapAndDie(target._depthStencilTexture);\n target._depthStencilTexture.isReady = true;\n }\n this._textures = null;\n this._depthStencilTexture = null;\n }\n /** @internal */\n _rebuild() {\n const rtw = this._cloneRenderTargetWrapper();\n if (!rtw) {\n return;\n }\n if (this._depthStencilTexture) {\n const samplingMode = this._depthStencilTexture.samplingMode;\n const bilinear = samplingMode === 2 ||\n samplingMode === 3 ||\n samplingMode === 11;\n rtw.createDepthStencilTexture(this._depthStencilTexture._comparisonFunction, bilinear, this._depthStencilTextureWithStencil, this._depthStencilTexture.samples);\n }\n if (this.samples > 1) {\n rtw.setSamples(this.samples);\n }\n rtw._swapRenderTargetWrapper(this);\n rtw.dispose();\n }\n /**\n * Releases the internal render textures\n */\n releaseTextures() {\n var _a, _b;\n if (this._textures) {\n for (let i = 0; (_b = i < ((_a = this._textures) === null || _a === void 0 ? void 0 : _a.length)) !== null && _b !== void 0 ? _b : 0; ++i) {\n this._textures[i].dispose();\n }\n }\n this._textures = null;\n }\n /**\n * Disposes the whole render target wrapper\n * @param disposeOnlyFramebuffers true if only the frame buffers should be released (used for the WebGL engine). If false, all the textures will also be released\n */\n dispose(disposeOnlyFramebuffers = false) {\n var _a;\n if (!disposeOnlyFramebuffers) {\n (_a = this._depthStencilTexture) === null || _a === void 0 ? void 0 : _a.dispose();\n this._depthStencilTexture = null;\n this.releaseTextures();\n }\n this._engine._releaseRenderTargetWrapper(this);\n }\n}\n//# sourceMappingURL=renderTargetWrapper.js.map","import { RenderTargetWrapper } from \"../renderTargetWrapper.js\";\n/** @internal */\nexport class WebGLRenderTargetWrapper extends RenderTargetWrapper {\n constructor(isMulti, isCube, size, engine, context) {\n super(isMulti, isCube, size, engine);\n /**\n * @internal\n */\n this._framebuffer = null;\n /**\n * @internal\n */\n this._depthStencilBuffer = null;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n /**\n * @internal\n */\n this._MSAAFramebuffer = null;\n // Multiview\n /**\n * @internal\n */\n this._colorTextureArray = null;\n /**\n * @internal\n */\n this._depthStencilTextureArray = null;\n /**\n * @internal\n */\n this._disposeOnlyFramebuffers = false;\n this._context = context;\n }\n _cloneRenderTargetWrapper() {\n let rtw = null;\n if (this._colorTextureArray && this._depthStencilTextureArray) {\n rtw = this._engine.createMultiviewRenderTargetTexture(this.width, this.height);\n rtw.texture.isReady = true;\n }\n else {\n rtw = super._cloneRenderTargetWrapper();\n }\n return rtw;\n }\n _swapRenderTargetWrapper(target) {\n super._swapRenderTargetWrapper(target);\n target._framebuffer = this._framebuffer;\n target._depthStencilBuffer = this._depthStencilBuffer;\n target._MSAAFramebuffer = this._MSAAFramebuffer;\n target._colorTextureArray = this._colorTextureArray;\n target._depthStencilTextureArray = this._depthStencilTextureArray;\n this._framebuffer = this._depthStencilBuffer = this._MSAAFramebuffer = this._colorTextureArray = this._depthStencilTextureArray = null;\n }\n /**\n * Shares the depth buffer of this render target with another render target.\n * @internal\n * @param renderTarget Destination renderTarget\n */\n _shareDepth(renderTarget) {\n super._shareDepth(renderTarget);\n const gl = this._context;\n const depthbuffer = this._depthStencilBuffer;\n const framebuffer = renderTarget._MSAAFramebuffer || renderTarget._framebuffer;\n if (renderTarget._depthStencilBuffer) {\n gl.deleteRenderbuffer(renderTarget._depthStencilBuffer);\n }\n renderTarget._depthStencilBuffer = this._depthStencilBuffer;\n this._engine._bindUnboundFramebuffer(framebuffer);\n gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthbuffer);\n this._engine._bindUnboundFramebuffer(null);\n }\n /**\n * Binds a texture to this render target on a specific attachment\n * @param texture The texture to bind to the framebuffer\n * @param attachmentIndex Index of the attachment\n * @param faceIndexOrLayer The face or layer of the texture to render to in case of cube texture or array texture\n * @param lodLevel defines the lod level to bind to the frame buffer\n */\n _bindTextureRenderTarget(texture, attachmentIndex = 0, faceIndexOrLayer, lodLevel = 0) {\n var _a, _b, _c, _d;\n if (!texture._hardwareTexture) {\n return;\n }\n const framebuffer = this._framebuffer;\n const currentFB = this._engine._currentFramebuffer;\n this._engine._bindUnboundFramebuffer(framebuffer);\n if (this._engine.webGLVersion > 1) {\n const gl = this._context;\n const attachment = gl[\"COLOR_ATTACHMENT\" + attachmentIndex];\n if (texture.is2DArray || texture.is3D) {\n faceIndexOrLayer = (_b = faceIndexOrLayer !== null && faceIndexOrLayer !== void 0 ? faceIndexOrLayer : (_a = this.layerIndices) === null || _a === void 0 ? void 0 : _a[attachmentIndex]) !== null && _b !== void 0 ? _b : 0;\n gl.framebufferTextureLayer(gl.FRAMEBUFFER, attachment, texture._hardwareTexture.underlyingResource, lodLevel, faceIndexOrLayer);\n }\n else if (texture.isCube) {\n // if face index is not specified, try to query it from faceIndices\n // default is face 0\n faceIndexOrLayer = (_d = faceIndexOrLayer !== null && faceIndexOrLayer !== void 0 ? faceIndexOrLayer : (_c = this.faceIndices) === null || _c === void 0 ? void 0 : _c[attachmentIndex]) !== null && _d !== void 0 ? _d : 0;\n gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndexOrLayer, texture._hardwareTexture.underlyingResource, lodLevel);\n }\n else {\n gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._hardwareTexture.underlyingResource, lodLevel);\n }\n }\n else {\n // Default behavior (WebGL)\n const gl = this._context;\n const attachment = gl[\"COLOR_ATTACHMENT\" + attachmentIndex + \"_WEBGL\"];\n const target = faceIndexOrLayer !== undefined ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndexOrLayer : gl.TEXTURE_2D;\n gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, target, texture._hardwareTexture.underlyingResource, lodLevel);\n }\n this._engine._bindUnboundFramebuffer(currentFB);\n }\n /**\n * Set a texture in the textures array\n * @param texture the texture to set\n * @param index the index in the textures array to set\n * @param disposePrevious If this function should dispose the previous texture\n */\n setTexture(texture, index = 0, disposePrevious = true) {\n super.setTexture(texture, index, disposePrevious);\n this._bindTextureRenderTarget(texture, index);\n }\n /**\n * Sets the layer and face indices of every render target texture\n * @param layers The layer of the texture to be set (make negative to not modify)\n * @param faces The face of the texture to be set (make negative to not modify)\n */\n setLayerAndFaceIndices(layers, faces) {\n var _a, _b;\n super.setLayerAndFaceIndices(layers, faces);\n if (!this.textures || !this.layerIndices || !this.faceIndices) {\n return;\n }\n // the length of this._attachments is the right one as it does not count the depth texture, in case we generated it\n const textureCount = (_b = (_a = this._attachments) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : this.textures.length;\n for (let index = 0; index < textureCount; index++) {\n const texture = this.textures[index];\n if (!texture) {\n // The target type was probably -1 at creation time and setTexture has not been called yet for this index\n continue;\n }\n if (texture.is2DArray || texture.is3D) {\n this._bindTextureRenderTarget(texture, index, this.layerIndices[index]);\n }\n else if (texture.isCube) {\n this._bindTextureRenderTarget(texture, index, this.faceIndices[index]);\n }\n else {\n this._bindTextureRenderTarget(texture, index);\n }\n }\n }\n /**\n * Set the face and layer indices of a texture in the textures array\n * @param index The index of the texture in the textures array to modify\n * @param layer The layer of the texture to be set\n * @param face The face of the texture to be set\n */\n setLayerAndFaceIndex(index = 0, layer, face) {\n super.setLayerAndFaceIndex(index, layer, face);\n if (!this.textures || !this.layerIndices || !this.faceIndices) {\n return;\n }\n const texture = this.textures[index];\n if (texture.is2DArray || texture.is3D) {\n this._bindTextureRenderTarget(this.textures[index], index, this.layerIndices[index]);\n }\n else if (texture.isCube) {\n this._bindTextureRenderTarget(this.textures[index], index, this.faceIndices[index]);\n }\n }\n dispose(disposeOnlyFramebuffers = this._disposeOnlyFramebuffers) {\n const gl = this._context;\n if (!disposeOnlyFramebuffers) {\n if (this._colorTextureArray) {\n this._context.deleteTexture(this._colorTextureArray);\n this._colorTextureArray = null;\n }\n if (this._depthStencilTextureArray) {\n this._context.deleteTexture(this._depthStencilTextureArray);\n this._depthStencilTextureArray = null;\n }\n }\n if (this._framebuffer) {\n gl.deleteFramebuffer(this._framebuffer);\n this._framebuffer = null;\n }\n if (this._depthStencilBuffer) {\n gl.deleteRenderbuffer(this._depthStencilBuffer);\n this._depthStencilBuffer = null;\n }\n if (this._MSAAFramebuffer) {\n gl.deleteFramebuffer(this._MSAAFramebuffer);\n this._MSAAFramebuffer = null;\n }\n super.dispose(disposeOnlyFramebuffers);\n }\n}\n//# sourceMappingURL=webGLRenderTargetWrapper.js.map","import { InternalTexture, InternalTextureSource } from \"../../Materials/Textures/internalTexture.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { ThinEngine } from \"../thinEngine.js\";\nimport { WebGLRenderTargetWrapper } from \"../WebGL/webGLRenderTargetWrapper.js\";\n\nThinEngine.prototype._createHardwareRenderTargetWrapper = function (isMulti, isCube, size) {\n const rtWrapper = new WebGLRenderTargetWrapper(isMulti, isCube, size, this, this._gl);\n this._renderTargetWrapperCache.push(rtWrapper);\n return rtWrapper;\n};\nThinEngine.prototype.createRenderTargetTexture = function (size, options) {\n var _a, _b;\n const rtWrapper = this._createHardwareRenderTargetWrapper(false, false, size);\n let generateDepthBuffer = true;\n let generateStencilBuffer = false;\n let noColorAttachment = false;\n let colorAttachment = undefined;\n let samples = 1;\n if (options !== undefined && typeof options === \"object\") {\n generateDepthBuffer = (_a = options.generateDepthBuffer) !== null && _a !== void 0 ? _a : true;\n generateStencilBuffer = !!options.generateStencilBuffer;\n noColorAttachment = !!options.noColorAttachment;\n colorAttachment = options.colorAttachment;\n samples = (_b = options.samples) !== null && _b !== void 0 ? _b : 1;\n }\n const texture = colorAttachment || (noColorAttachment ? null : this._createInternalTexture(size, options, true, InternalTextureSource.RenderTarget));\n const width = size.width || size;\n const height = size.height || size;\n const currentFrameBuffer = this._currentFramebuffer;\n const gl = this._gl;\n // Create the framebuffer\n const framebuffer = gl.createFramebuffer();\n this._bindUnboundFramebuffer(framebuffer);\n rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);\n // No need to rebind on every frame\n if (texture && !texture.is2DArray) {\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._hardwareTexture.underlyingResource, 0);\n }\n this._bindUnboundFramebuffer(currentFrameBuffer);\n rtWrapper._framebuffer = framebuffer;\n rtWrapper._generateDepthBuffer = generateDepthBuffer;\n rtWrapper._generateStencilBuffer = generateStencilBuffer;\n rtWrapper.setTextures(texture);\n this.updateRenderTargetTextureSampleCount(rtWrapper, samples);\n return rtWrapper;\n};\nThinEngine.prototype.createDepthStencilTexture = function (size, options, rtWrapper) {\n if (options.isCube) {\n const width = size.width || size;\n return this._createDepthStencilCubeTexture(width, options, rtWrapper);\n }\n else {\n return this._createDepthStencilTexture(size, options, rtWrapper);\n }\n};\nThinEngine.prototype._createDepthStencilTexture = function (size, options, rtWrapper) {\n const gl = this._gl;\n const layers = size.layers || 0;\n const target = layers !== 0 ? gl.TEXTURE_2D_ARRAY : gl.TEXTURE_2D;\n const internalTexture = new InternalTexture(this, InternalTextureSource.DepthStencil);\n if (!this._caps.depthTextureExtension) {\n Logger.Error(\"Depth texture is not supported by your browser or hardware.\");\n return internalTexture;\n }\n const internalOptions = Object.assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);\n this._bindTextureDirectly(target, internalTexture, true);\n this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.comparisonFunction === 0 ? false : internalOptions.bilinearFiltering, internalOptions.comparisonFunction, internalOptions.samples);\n if (internalOptions.depthTextureFormat !== undefined) {\n if (internalOptions.depthTextureFormat !== 15 &&\n internalOptions.depthTextureFormat !== 16 &&\n internalOptions.depthTextureFormat !== 17 &&\n internalOptions.depthTextureFormat !== 13 &&\n internalOptions.depthTextureFormat !== 14 &&\n internalOptions.depthTextureFormat !== 18) {\n Logger.Error(\"Depth texture format is not supported.\");\n return internalTexture;\n }\n internalTexture.format = internalOptions.depthTextureFormat;\n }\n else {\n internalTexture.format = internalOptions.generateStencil ? 13 : 16;\n }\n const hasStencil = internalTexture.format === 17 ||\n internalTexture.format === 13 ||\n internalTexture.format === 18;\n rtWrapper._depthStencilTexture = internalTexture;\n rtWrapper._depthStencilTextureWithStencil = hasStencil;\n let type = gl.UNSIGNED_INT;\n if (internalTexture.format === 15) {\n type = gl.UNSIGNED_SHORT;\n }\n else if (internalTexture.format === 17 || internalTexture.format === 13) {\n type = gl.UNSIGNED_INT_24_8;\n }\n else if (internalTexture.format === 14) {\n type = gl.FLOAT;\n }\n else if (internalTexture.format === 18) {\n type = gl.FLOAT_32_UNSIGNED_INT_24_8_REV;\n }\n const format = hasStencil ? gl.DEPTH_STENCIL : gl.DEPTH_COMPONENT;\n let internalFormat = format;\n if (this.webGLVersion > 1) {\n if (internalTexture.format === 15) {\n internalFormat = gl.DEPTH_COMPONENT16;\n }\n else if (internalTexture.format === 16) {\n internalFormat = gl.DEPTH_COMPONENT24;\n }\n else if (internalTexture.format === 17 || internalTexture.format === 13) {\n internalFormat = gl.DEPTH24_STENCIL8;\n }\n else if (internalTexture.format === 14) {\n internalFormat = gl.DEPTH_COMPONENT32F;\n }\n else if (internalTexture.format === 18) {\n internalFormat = gl.DEPTH32F_STENCIL8;\n }\n }\n if (internalTexture.is2DArray) {\n gl.texImage3D(target, 0, internalFormat, internalTexture.width, internalTexture.height, layers, 0, format, type, null);\n }\n else {\n gl.texImage2D(target, 0, internalFormat, internalTexture.width, internalTexture.height, 0, format, type, null);\n }\n this._bindTextureDirectly(target, null);\n this._internalTexturesCache.push(internalTexture);\n // Dispose previous depth/stencil render buffers and clear the corresponding attachment.\n // Next time this framebuffer is bound, the new depth/stencil texture will be attached.\n const glRtWrapper = rtWrapper;\n if (glRtWrapper._depthStencilBuffer) {\n const currentFrameBuffer = this._currentFramebuffer;\n this._bindUnboundFramebuffer(glRtWrapper._framebuffer);\n gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, null);\n gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, null);\n gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, null);\n this._bindUnboundFramebuffer(currentFrameBuffer);\n gl.deleteRenderbuffer(glRtWrapper._depthStencilBuffer);\n glRtWrapper._depthStencilBuffer = null;\n }\n return internalTexture;\n};\nThinEngine.prototype.updateRenderTargetTextureSampleCount = function (rtWrapper, samples) {\n if (this.webGLVersion < 2 || !rtWrapper || !rtWrapper.texture) {\n return 1;\n }\n if (rtWrapper.samples === samples) {\n return samples;\n }\n const gl = this._gl;\n samples = Math.min(samples, this.getCaps().maxMSAASamples);\n // Dispose previous render buffers\n if (rtWrapper._depthStencilBuffer) {\n gl.deleteRenderbuffer(rtWrapper._depthStencilBuffer);\n rtWrapper._depthStencilBuffer = null;\n }\n if (rtWrapper._MSAAFramebuffer) {\n gl.deleteFramebuffer(rtWrapper._MSAAFramebuffer);\n rtWrapper._MSAAFramebuffer = null;\n }\n const hardwareTexture = rtWrapper.texture._hardwareTexture;\n hardwareTexture.releaseMSAARenderBuffers();\n if (samples > 1 && typeof gl.renderbufferStorageMultisample === \"function\") {\n const framebuffer = gl.createFramebuffer();\n if (!framebuffer) {\n throw new Error(\"Unable to create multi sampled framebuffer\");\n }\n rtWrapper._MSAAFramebuffer = framebuffer;\n this._bindUnboundFramebuffer(rtWrapper._MSAAFramebuffer);\n const colorRenderbuffer = this._createRenderBuffer(rtWrapper.texture.width, rtWrapper.texture.height, samples, -1 /* not used */, this._getRGBAMultiSampleBufferFormat(rtWrapper.texture.type), gl.COLOR_ATTACHMENT0, false);\n if (!colorRenderbuffer) {\n throw new Error(\"Unable to create multi sampled framebuffer\");\n }\n hardwareTexture.addMSAARenderBuffer(colorRenderbuffer);\n }\n else {\n this._bindUnboundFramebuffer(rtWrapper._framebuffer);\n }\n rtWrapper.texture.samples = samples;\n rtWrapper._samples = samples;\n rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(rtWrapper._generateStencilBuffer, rtWrapper._generateDepthBuffer, rtWrapper.texture.width, rtWrapper.texture.height, samples);\n this._bindUnboundFramebuffer(null);\n return samples;\n};\n//# sourceMappingURL=engine.renderTarget.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { SmartArray } from \"../Misc/smartArray.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Vector2 } from \"../Maths/math.vector.js\";\n\nimport \"../Shaders/postprocess.vertex.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport \"../Engines/Extensions/engine.renderTarget.js\";\nimport { serialize, serializeAsColor4, SerializationHelper } from \"../Misc/decorators.js\";\nimport { GetClass, RegisterClass } from \"../Misc/typeStore.js\";\nimport { DrawWrapper } from \"../Materials/drawWrapper.js\";\nimport { ShaderLanguage } from \"../Materials/shaderLanguage.js\";\n/**\n * PostProcess can be used to apply a shader to a texture after it has been rendered\n * See https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses\n */\nexport class PostProcess {\n /**\n * Registers a shader code processing with a post process name.\n * @param postProcessName name of the post process. Use null for the fallback shader code processing. This is the shader code processing that will be used in case no specific shader code processing has been associated to a post process name\n * @param customShaderCodeProcessing shader code processing to associate to the post process name\n * @returns\n */\n static RegisterShaderCodeProcessing(postProcessName, customShaderCodeProcessing) {\n if (!customShaderCodeProcessing) {\n delete PostProcess._CustomShaderCodeProcessing[postProcessName !== null && postProcessName !== void 0 ? postProcessName : \"\"];\n return;\n }\n PostProcess._CustomShaderCodeProcessing[postProcessName !== null && postProcessName !== void 0 ? postProcessName : \"\"] = customShaderCodeProcessing;\n }\n static _GetShaderCodeProcessing(postProcessName) {\n var _a;\n return (_a = PostProcess._CustomShaderCodeProcessing[postProcessName]) !== null && _a !== void 0 ? _a : PostProcess._CustomShaderCodeProcessing[\"\"];\n }\n /**\n * Number of sample textures (default: 1)\n */\n get samples() {\n return this._samples;\n }\n set samples(n) {\n this._samples = Math.min(n, this._engine.getCaps().maxMSAASamples);\n this._textures.forEach((texture) => {\n texture.setSamples(this._samples);\n });\n }\n /**\n * Returns the fragment url or shader name used in the post process.\n * @returns the fragment url or name in the shader store.\n */\n getEffectName() {\n return this._fragmentUrl;\n }\n /**\n * A function that is added to the onActivateObservable\n */\n set onActivate(callback) {\n if (this._onActivateObserver) {\n this.onActivateObservable.remove(this._onActivateObserver);\n }\n if (callback) {\n this._onActivateObserver = this.onActivateObservable.add(callback);\n }\n }\n /**\n * A function that is added to the onSizeChangedObservable\n */\n set onSizeChanged(callback) {\n if (this._onSizeChangedObserver) {\n this.onSizeChangedObservable.remove(this._onSizeChangedObserver);\n }\n this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);\n }\n /**\n * A function that is added to the onApplyObservable\n */\n set onApply(callback) {\n if (this._onApplyObserver) {\n this.onApplyObservable.remove(this._onApplyObserver);\n }\n this._onApplyObserver = this.onApplyObservable.add(callback);\n }\n /**\n * A function that is added to the onBeforeRenderObservable\n */\n set onBeforeRender(callback) {\n if (this._onBeforeRenderObserver) {\n this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);\n }\n this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);\n }\n /**\n * A function that is added to the onAfterRenderObservable\n */\n set onAfterRender(callback) {\n if (this._onAfterRenderObserver) {\n this.onAfterRenderObservable.remove(this._onAfterRenderObserver);\n }\n this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);\n }\n /**\n * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will\n * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.\n */\n get inputTexture() {\n return this._textures.data[this._currentRenderTextureInd];\n }\n set inputTexture(value) {\n this._forcedOutputTexture = value;\n }\n /**\n * Since inputTexture should always be defined, if we previously manually set `inputTexture`,\n * the only way to unset it is to use this function to restore its internal state\n */\n restoreDefaultInputTexture() {\n if (this._forcedOutputTexture) {\n this._forcedOutputTexture = null;\n this.markTextureDirty();\n }\n }\n /**\n * Gets the camera which post process is applied to.\n * @returns The camera the post process is applied to.\n */\n getCamera() {\n return this._camera;\n }\n /**\n * Gets the texel size of the postprocess.\n * See https://en.wikipedia.org/wiki/Texel_(graphics)\n */\n get texelSize() {\n if (this._shareOutputWithPostProcess) {\n return this._shareOutputWithPostProcess.texelSize;\n }\n if (this._forcedOutputTexture) {\n this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);\n }\n return this._texelSize;\n }\n /**\n * Creates a new instance PostProcess\n * @param name The name of the PostProcess.\n * @param fragmentUrl The url of the fragment shader to be used.\n * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.\n * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.\n * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param defines String of defines that will be set when running the fragment shader. (default: null)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param vertexUrl The url of the vertex shader to be used. (default: \"postprocess\")\n * @param indexParameters The index parameters to be used for babylons include syntax \"#include[0..varyingCount]\". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx\n * @param blockCompilation If the shader should not be compiled immediatly. (default: false)\n * @param textureFormat Format of textures used when performing the post process. (default: TEXTUREFORMAT_RGBA)\n */\n constructor(name, fragmentUrl, parameters, samplers, options, camera, samplingMode = 1, engine, reusable, defines = null, textureType = 0, vertexUrl = \"postprocess\", indexParameters, blockCompilation = false, textureFormat = 5, shaderLanguage = ShaderLanguage.GLSL) {\n /** @internal */\n this._parentContainer = null;\n /**\n * Width of the texture to apply the post process on\n */\n this.width = -1;\n /**\n * Height of the texture to apply the post process on\n */\n this.height = -1;\n /**\n * Gets the node material used to create this postprocess (null if the postprocess was manually created)\n */\n this.nodeMaterialSource = null;\n /**\n * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)\n * @internal\n */\n this._outputTexture = null;\n /**\n * If the buffer needs to be cleared before applying the post process. (default: true)\n * Should be set to false if shader will overwrite all previous pixels.\n */\n this.autoClear = true;\n /**\n * If clearing the buffer should be forced in autoClear mode, even when alpha mode is enabled (default: false).\n * By default, the buffer will only be cleared if alpha mode is disabled (and autoClear is true).\n */\n this.forceAutoClearInAlphaMode = false;\n /**\n * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)\n */\n this.alphaMode = 0;\n /**\n * Animations to be used for the post processing\n */\n this.animations = new Array();\n /**\n * Enable Pixel Perfect mode where texture is not scaled to be power of 2.\n * Can only be used on a single postprocess or on the last one of a chain. (default: false)\n */\n this.enablePixelPerfectMode = false;\n /**\n * Force the postprocess to be applied without taking in account viewport\n */\n this.forceFullscreenViewport = true;\n /**\n * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)\n *\n * | Value | Type | Description |\n * | ----- | ----------------------------------- | ----------- |\n * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](https://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |\n * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](https://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |\n * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](https://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |\n *\n */\n this.scaleMode = 1;\n /**\n * Force textures to be a power of two (default: false)\n */\n this.alwaysForcePOT = false;\n this._samples = 1;\n /**\n * Modify the scale of the post process to be the same as the viewport (default: false)\n */\n this.adaptScaleToCurrentViewport = false;\n this._reusable = false;\n this._renderId = 0;\n /**\n * if externalTextureSamplerBinding is true, the \"apply\" method won't bind the textureSampler texture, it is expected to be done by the \"outside\" (by the onApplyObservable observer most probably).\n * counter-productive in some cases because if the texture bound by \"apply\" is different from the currently texture bound, (the one set by the onApplyObservable observer, for eg) some\n * internal structures (materialContext) will be dirtified, which may impact performances\n */\n this.externalTextureSamplerBinding = false;\n /**\n * Smart array of input and output textures for the post process.\n * @internal\n */\n this._textures = new SmartArray(2);\n /**\n * Smart array of input and output textures for the post process.\n * @internal\n */\n this._textureCache = [];\n /**\n * The index in _textures that corresponds to the output texture.\n * @internal\n */\n this._currentRenderTextureInd = 0;\n this._scaleRatio = new Vector2(1, 1);\n this._texelSize = Vector2.Zero();\n // Events\n /**\n * An event triggered when the postprocess is activated.\n */\n this.onActivateObservable = new Observable();\n /**\n * An event triggered when the postprocess changes its size.\n */\n this.onSizeChangedObservable = new Observable();\n /**\n * An event triggered when the postprocess applies its effect.\n */\n this.onApplyObservable = new Observable();\n /**\n * An event triggered before rendering the postprocess\n */\n this.onBeforeRenderObservable = new Observable();\n /**\n * An event triggered after rendering the postprocess\n */\n this.onAfterRenderObservable = new Observable();\n this.name = name;\n if (camera != null) {\n this._camera = camera;\n this._scene = camera.getScene();\n camera.attachPostProcess(this);\n this._engine = this._scene.getEngine();\n this._scene.postProcesses.push(this);\n this.uniqueId = this._scene.getUniqueId();\n }\n else if (engine) {\n this._engine = engine;\n this._engine.postProcesses.push(this);\n }\n this._options = options;\n this.renderTargetSamplingMode = samplingMode ? samplingMode : 1;\n this._reusable = reusable || false;\n this._textureType = textureType;\n this._textureFormat = textureFormat;\n this._shaderLanguage = shaderLanguage;\n this._samplers = samplers || [];\n this._samplers.push(\"textureSampler\");\n this._fragmentUrl = fragmentUrl;\n this._vertexUrl = vertexUrl;\n this._parameters = parameters || [];\n this._parameters.push(\"scale\");\n this._indexParameters = indexParameters;\n this._drawWrapper = new DrawWrapper(this._engine);\n if (!blockCompilation) {\n this.updateEffect(defines);\n }\n }\n /**\n * Gets a string identifying the name of the class\n * @returns \"PostProcess\" string\n */\n getClassName() {\n return \"PostProcess\";\n }\n /**\n * Gets the engine which this post process belongs to.\n * @returns The engine the post process was enabled with.\n */\n getEngine() {\n return this._engine;\n }\n /**\n * The effect that is created when initializing the post process.\n * @returns The created effect corresponding the the postprocess.\n */\n getEffect() {\n return this._drawWrapper.effect;\n }\n /**\n * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.\n * @param postProcess The post process to share the output with.\n * @returns This post process.\n */\n shareOutputWith(postProcess) {\n this._disposeTextures();\n this._shareOutputWithPostProcess = postProcess;\n return this;\n }\n /**\n * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.\n * This should be called if the post process that shares output with this post process is disabled/disposed.\n */\n useOwnOutput() {\n if (this._textures.length == 0) {\n this._textures = new SmartArray(2);\n }\n this._shareOutputWithPostProcess = null;\n }\n /**\n * Updates the effect with the current post process compile time values and recompiles the shader.\n * @param defines Define statements that should be added at the beginning of the shader. (default: null)\n * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)\n * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)\n * @param indexParameters The index parameters to be used for babylons include syntax \"#include[0..varyingCount]\". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx\n * @param onCompiled Called when the shader has been compiled.\n * @param onError Called if there is an error when compiling a shader.\n * @param vertexUrl The url of the vertex shader to be used (default: the one given at construction time)\n * @param fragmentUrl The url of the fragment shader to be used (default: the one given at construction time)\n */\n updateEffect(defines = null, uniforms = null, samplers = null, indexParameters, onCompiled, onError, vertexUrl, fragmentUrl) {\n var _a, _b;\n const customShaderCodeProcessing = PostProcess._GetShaderCodeProcessing(this.name);\n if (customShaderCodeProcessing === null || customShaderCodeProcessing === void 0 ? void 0 : customShaderCodeProcessing.defineCustomBindings) {\n const newUniforms = (_a = uniforms === null || uniforms === void 0 ? void 0 : uniforms.slice()) !== null && _a !== void 0 ? _a : [];\n newUniforms.push(...this._parameters);\n const newSamplers = (_b = samplers === null || samplers === void 0 ? void 0 : samplers.slice()) !== null && _b !== void 0 ? _b : [];\n newSamplers.push(...this._samplers);\n defines = customShaderCodeProcessing.defineCustomBindings(this.name, defines, newUniforms, newSamplers);\n uniforms = newUniforms;\n samplers = newSamplers;\n }\n this._postProcessDefines = defines;\n this._drawWrapper.effect = this._engine.createEffect({ vertex: vertexUrl !== null && vertexUrl !== void 0 ? vertexUrl : this._vertexUrl, fragment: fragmentUrl !== null && fragmentUrl !== void 0 ? fragmentUrl : this._fragmentUrl }, {\n attributes: [\"position\"],\n uniformsNames: uniforms || this._parameters,\n uniformBuffersNames: [],\n samplers: samplers || this._samplers,\n defines: defines !== null ? defines : \"\",\n fallbacks: null,\n onCompiled: onCompiled !== null && onCompiled !== void 0 ? onCompiled : null,\n onError: onError !== null && onError !== void 0 ? onError : null,\n indexParameters: indexParameters || this._indexParameters,\n processCodeAfterIncludes: (customShaderCodeProcessing === null || customShaderCodeProcessing === void 0 ? void 0 : customShaderCodeProcessing.processCodeAfterIncludes)\n ? (shaderType, code) => customShaderCodeProcessing.processCodeAfterIncludes(this.name, shaderType, code)\n : null,\n processFinalCode: (customShaderCodeProcessing === null || customShaderCodeProcessing === void 0 ? void 0 : customShaderCodeProcessing.processFinalCode)\n ? (shaderType, code) => customShaderCodeProcessing.processFinalCode(this.name, shaderType, code)\n : null,\n shaderLanguage: this._shaderLanguage,\n }, this._engine);\n }\n /**\n * The post process is reusable if it can be used multiple times within one frame.\n * @returns If the post process is reusable\n */\n isReusable() {\n return this._reusable;\n }\n /** invalidate frameBuffer to hint the postprocess to create a depth buffer */\n markTextureDirty() {\n this.width = -1;\n }\n _createRenderTargetTexture(textureSize, textureOptions, channel = 0) {\n for (let i = 0; i < this._textureCache.length; i++) {\n if (this._textureCache[i].texture.width === textureSize.width &&\n this._textureCache[i].texture.height === textureSize.height &&\n this._textureCache[i].postProcessChannel === channel &&\n this._textureCache[i].texture._generateDepthBuffer === textureOptions.generateDepthBuffer &&\n this._textureCache[i].texture.samples === textureOptions.samples) {\n return this._textureCache[i].texture;\n }\n }\n const tex = this._engine.createRenderTargetTexture(textureSize, textureOptions);\n this._textureCache.push({ texture: tex, postProcessChannel: channel, lastUsedRenderId: -1 });\n return tex;\n }\n _flushTextureCache() {\n const currentRenderId = this._renderId;\n for (let i = this._textureCache.length - 1; i >= 0; i--) {\n if (currentRenderId - this._textureCache[i].lastUsedRenderId > 100) {\n let currentlyUsed = false;\n for (let j = 0; j < this._textures.length; j++) {\n if (this._textures.data[j] === this._textureCache[i].texture) {\n currentlyUsed = true;\n break;\n }\n }\n if (!currentlyUsed) {\n this._textureCache[i].texture.dispose();\n this._textureCache.splice(i, 1);\n }\n }\n }\n }\n _resize(width, height, camera, needMipMaps, forceDepthStencil) {\n if (this._textures.length > 0) {\n this._textures.reset();\n }\n this.width = width;\n this.height = height;\n let firstPP = null;\n for (let i = 0; i < camera._postProcesses.length; i++) {\n if (camera._postProcesses[i] !== null) {\n firstPP = camera._postProcesses[i];\n break;\n }\n }\n const textureSize = { width: this.width, height: this.height };\n const textureOptions = {\n generateMipMaps: needMipMaps,\n generateDepthBuffer: forceDepthStencil || firstPP === this,\n generateStencilBuffer: (forceDepthStencil || firstPP === this) && this._engine.isStencilEnable,\n samplingMode: this.renderTargetSamplingMode,\n type: this._textureType,\n format: this._textureFormat,\n samples: this._samples,\n label: \"PostProcessRTT-\" + this.name,\n };\n this._textures.push(this._createRenderTargetTexture(textureSize, textureOptions, 0));\n if (this._reusable) {\n this._textures.push(this._createRenderTargetTexture(textureSize, textureOptions, 1));\n }\n this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);\n this.onSizeChangedObservable.notifyObservers(this);\n }\n /**\n * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.\n * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous.\n * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.\n * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)\n * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)\n * @returns The render target wrapper that was bound to be written to.\n */\n activate(camera, sourceTexture = null, forceDepthStencil) {\n var _a, _b;\n camera = camera || this._camera;\n const scene = camera.getScene();\n const engine = scene.getEngine();\n const maxSize = engine.getCaps().maxTextureSize;\n let requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;\n const requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;\n // If rendering to a webvr camera's left or right eye only half the width should be used to avoid resize when rendered to screen\n const webVRCamera = camera.parent;\n if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {\n requiredWidth /= 2;\n }\n let desiredWidth = this._options.width || requiredWidth;\n let desiredHeight = this._options.height || requiredHeight;\n const needMipMaps = this.renderTargetSamplingMode !== 7 &&\n this.renderTargetSamplingMode !== 1 &&\n this.renderTargetSamplingMode !== 2;\n if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {\n if (this.adaptScaleToCurrentViewport) {\n const currentViewport = engine.currentViewport;\n if (currentViewport) {\n desiredWidth *= currentViewport.width;\n desiredHeight *= currentViewport.height;\n }\n }\n if (needMipMaps || this.alwaysForcePOT) {\n if (!this._options.width) {\n desiredWidth = engine.needPOTTextures ? Engine.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;\n }\n if (!this._options.height) {\n desiredHeight = engine.needPOTTextures ? Engine.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;\n }\n }\n if (this.width !== desiredWidth || this.height !== desiredHeight) {\n this._resize(desiredWidth, desiredHeight, camera, needMipMaps, forceDepthStencil);\n }\n this._textures.forEach((texture) => {\n if (texture.samples !== this.samples) {\n this._engine.updateRenderTargetTextureSampleCount(texture, this.samples);\n }\n });\n this._flushTextureCache();\n this._renderId++;\n }\n let target;\n if (this._shareOutputWithPostProcess) {\n target = this._shareOutputWithPostProcess.inputTexture;\n }\n else if (this._forcedOutputTexture) {\n target = this._forcedOutputTexture;\n this.width = this._forcedOutputTexture.width;\n this.height = this._forcedOutputTexture.height;\n }\n else {\n target = this.inputTexture;\n let cache;\n for (let i = 0; i < this._textureCache.length; i++) {\n if (this._textureCache[i].texture === target) {\n cache = this._textureCache[i];\n break;\n }\n }\n if (cache) {\n cache.lastUsedRenderId = this._renderId;\n }\n }\n // Bind the input of this post process to be used as the output of the previous post process.\n if (this.enablePixelPerfectMode) {\n this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);\n this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);\n }\n else {\n this._scaleRatio.copyFromFloats(1, 1);\n this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);\n }\n (_b = (_a = this._engine)._debugInsertMarker) === null || _b === void 0 ? void 0 : _b.call(_a, `post process ${this.name} input`);\n this.onActivateObservable.notifyObservers(camera);\n // Clear\n if (this.autoClear && (this.alphaMode === 0 || this.forceAutoClearInAlphaMode)) {\n this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);\n }\n if (this._reusable) {\n this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;\n }\n return target;\n }\n /**\n * If the post process is supported.\n */\n get isSupported() {\n return this._drawWrapper.effect.isSupported;\n }\n /**\n * The aspect ratio of the output texture.\n */\n get aspectRatio() {\n if (this._shareOutputWithPostProcess) {\n return this._shareOutputWithPostProcess.aspectRatio;\n }\n if (this._forcedOutputTexture) {\n return this._forcedOutputTexture.width / this._forcedOutputTexture.height;\n }\n return this.width / this.height;\n }\n /**\n * Get a value indicating if the post-process is ready to be used\n * @returns true if the post-process is ready (shader is compiled)\n */\n isReady() {\n var _a, _b;\n return (_b = (_a = this._drawWrapper.effect) === null || _a === void 0 ? void 0 : _a.isReady()) !== null && _b !== void 0 ? _b : false;\n }\n /**\n * Binds all textures and uniforms to the shader, this will be run on every pass.\n * @returns the effect corresponding to this post process. Null if not compiled or not ready.\n */\n apply() {\n var _a, _b, _c;\n // Check\n if (!((_a = this._drawWrapper.effect) === null || _a === void 0 ? void 0 : _a.isReady())) {\n return null;\n }\n // States\n this._engine.enableEffect(this._drawWrapper);\n this._engine.setState(false);\n this._engine.setDepthBuffer(false);\n this._engine.setDepthWrite(false);\n // Alpha\n this._engine.setAlphaMode(this.alphaMode);\n if (this.alphaConstants) {\n this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);\n }\n // Bind the output texture of the preivous post process as the input to this post process.\n let source;\n if (this._shareOutputWithPostProcess) {\n source = this._shareOutputWithPostProcess.inputTexture;\n }\n else if (this._forcedOutputTexture) {\n source = this._forcedOutputTexture;\n }\n else {\n source = this.inputTexture;\n }\n if (!this.externalTextureSamplerBinding) {\n this._drawWrapper.effect._bindTexture(\"textureSampler\", source === null || source === void 0 ? void 0 : source.texture);\n }\n // Parameters\n this._drawWrapper.effect.setVector2(\"scale\", this._scaleRatio);\n this.onApplyObservable.notifyObservers(this._drawWrapper.effect);\n (_c = (_b = PostProcess._GetShaderCodeProcessing(this.name)) === null || _b === void 0 ? void 0 : _b.bindCustomBindings) === null || _c === void 0 ? void 0 : _c.call(_b, this.name, this._drawWrapper.effect);\n return this._drawWrapper.effect;\n }\n _disposeTextures() {\n if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {\n this._disposeTextureCache();\n return;\n }\n this._disposeTextureCache();\n this._textures.dispose();\n }\n _disposeTextureCache() {\n for (let i = this._textureCache.length - 1; i >= 0; i--) {\n this._textureCache[i].texture.dispose();\n }\n this._textureCache.length = 0;\n }\n /**\n * Sets the required values to the prepass renderer.\n * @param prePassRenderer defines the prepass renderer to setup.\n * @returns true if the pre pass is needed.\n */\n setPrePassRenderer(prePassRenderer) {\n if (this._prePassEffectConfiguration) {\n this._prePassEffectConfiguration = prePassRenderer.addEffectConfiguration(this._prePassEffectConfiguration);\n this._prePassEffectConfiguration.enabled = true;\n return true;\n }\n return false;\n }\n /**\n * Disposes the post process.\n * @param camera The camera to dispose the post process on.\n */\n dispose(camera) {\n camera = camera || this._camera;\n this._disposeTextures();\n let index;\n if (this._scene) {\n index = this._scene.postProcesses.indexOf(this);\n if (index !== -1) {\n this._scene.postProcesses.splice(index, 1);\n }\n }\n if (this._parentContainer) {\n const index = this._parentContainer.postProcesses.indexOf(this);\n if (index > -1) {\n this._parentContainer.postProcesses.splice(index, 1);\n }\n this._parentContainer = null;\n }\n index = this._engine.postProcesses.indexOf(this);\n if (index !== -1) {\n this._engine.postProcesses.splice(index, 1);\n }\n if (!camera) {\n return;\n }\n camera.detachPostProcess(this);\n index = camera._postProcesses.indexOf(this);\n if (index === 0 && camera._postProcesses.length > 0) {\n const firstPostProcess = this._camera._getFirstPostProcess();\n if (firstPostProcess) {\n firstPostProcess.markTextureDirty();\n }\n }\n this.onActivateObservable.clear();\n this.onAfterRenderObservable.clear();\n this.onApplyObservable.clear();\n this.onBeforeRenderObservable.clear();\n this.onSizeChangedObservable.clear();\n }\n /**\n * Serializes the post process to a JSON object\n * @returns the JSON object\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this);\n const camera = this.getCamera() || (this._scene && this._scene.activeCamera);\n serializationObject.customType = \"BABYLON.\" + this.getClassName();\n serializationObject.cameraId = camera ? camera.id : null;\n serializationObject.reusable = this._reusable;\n serializationObject.textureType = this._textureType;\n serializationObject.fragmentUrl = this._fragmentUrl;\n serializationObject.parameters = this._parameters;\n serializationObject.samplers = this._samplers;\n serializationObject.options = this._options;\n serializationObject.defines = this._postProcessDefines;\n serializationObject.textureFormat = this._textureFormat;\n serializationObject.vertexUrl = this._vertexUrl;\n serializationObject.indexParameters = this._indexParameters;\n return serializationObject;\n }\n /**\n * Clones this post process\n * @returns a new post process similar to this one\n */\n clone() {\n const serializationObject = this.serialize();\n serializationObject._engine = this._engine;\n serializationObject.cameraId = null;\n const result = PostProcess.Parse(serializationObject, this._scene, \"\");\n if (!result) {\n return null;\n }\n result.onActivateObservable = this.onActivateObservable.clone();\n result.onSizeChangedObservable = this.onSizeChangedObservable.clone();\n result.onApplyObservable = this.onApplyObservable.clone();\n result.onBeforeRenderObservable = this.onBeforeRenderObservable.clone();\n result.onAfterRenderObservable = this.onAfterRenderObservable.clone();\n result._prePassEffectConfiguration = this._prePassEffectConfiguration;\n return result;\n }\n /**\n * Creates a material from parsed material data\n * @param parsedPostProcess defines parsed post process data\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures\n * @returns a new post process\n */\n static Parse(parsedPostProcess, scene, rootUrl) {\n const postProcessType = GetClass(parsedPostProcess.customType);\n if (!postProcessType || !postProcessType._Parse) {\n return null;\n }\n const camera = scene ? scene.getCameraById(parsedPostProcess.cameraId) : null;\n return postProcessType._Parse(parsedPostProcess, camera, scene, rootUrl);\n }\n /**\n * @internal\n */\n static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) {\n return SerializationHelper.Parse(() => {\n return new PostProcess(parsedPostProcess.name, parsedPostProcess.fragmentUrl, parsedPostProcess.parameters, parsedPostProcess.samplers, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, parsedPostProcess._engine, parsedPostProcess.reusable, parsedPostProcess.defines, parsedPostProcess.textureType, parsedPostProcess.vertexUrl, parsedPostProcess.indexParameters, false, parsedPostProcess.textureFormat);\n }, parsedPostProcess, scene, rootUrl);\n }\n}\nPostProcess._CustomShaderCodeProcessing = {};\n__decorate([\n serialize()\n], PostProcess.prototype, \"uniqueId\", void 0);\n__decorate([\n serialize()\n], PostProcess.prototype, \"name\", void 0);\n__decorate([\n serialize()\n], PostProcess.prototype, \"width\", void 0);\n__decorate([\n serialize()\n], PostProcess.prototype, \"height\", void 0);\n__decorate([\n serialize()\n], PostProcess.prototype, \"renderTargetSamplingMode\", void 0);\n__decorate([\n serializeAsColor4()\n], PostProcess.prototype, \"clearColor\", void 0);\n__decorate([\n serialize()\n], PostProcess.prototype, \"autoClear\", void 0);\n__decorate([\n serialize()\n], PostProcess.prototype, \"forceAutoClearInAlphaMode\", void 0);\n__decorate([\n serialize()\n], PostProcess.prototype, \"alphaMode\", void 0);\n__decorate([\n serialize()\n], PostProcess.prototype, \"alphaConstants\", void 0);\n__decorate([\n serialize()\n], PostProcess.prototype, \"enablePixelPerfectMode\", void 0);\n__decorate([\n serialize()\n], PostProcess.prototype, \"forceFullscreenViewport\", void 0);\n__decorate([\n serialize()\n], PostProcess.prototype, \"scaleMode\", void 0);\n__decorate([\n serialize()\n], PostProcess.prototype, \"alwaysForcePOT\", void 0);\n__decorate([\n serialize(\"samples\")\n], PostProcess.prototype, \"_samples\", void 0);\n__decorate([\n serialize()\n], PostProcess.prototype, \"adaptScaleToCurrentViewport\", void 0);\nRegisterClass(\"BABYLON.PostProcess\", PostProcess);\n//# sourceMappingURL=postProcess.js.map","/**\n * Enum used to define the material modes\n */\nexport var NodeMaterialModes;\n(function (NodeMaterialModes) {\n /** Regular material */\n NodeMaterialModes[NodeMaterialModes[\"Material\"] = 0] = \"Material\";\n /** For post process */\n NodeMaterialModes[NodeMaterialModes[\"PostProcess\"] = 1] = \"PostProcess\";\n /** For particle system */\n NodeMaterialModes[NodeMaterialModes[\"Particle\"] = 2] = \"Particle\";\n /** For procedural texture */\n NodeMaterialModes[NodeMaterialModes[\"ProceduralTexture\"] = 3] = \"ProceduralTexture\";\n})(NodeMaterialModes || (NodeMaterialModes = {}));\n//# sourceMappingURL=nodeMaterialModes.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to create a Vector2/3/4 out of individual inputs (one for each component)\n */\nexport class VectorMergerBlock extends NodeMaterialBlock {\n /**\n * Create a new VectorMergerBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n /**\n * Gets or sets the swizzle for x (meaning which component to affect to the output.x)\n */\n this.xSwizzle = \"x\";\n /**\n * Gets or sets the swizzle for y (meaning which component to affect to the output.y)\n */\n this.ySwizzle = \"y\";\n /**\n * Gets or sets the swizzle for z (meaning which component to affect to the output.z)\n */\n this.zSwizzle = \"z\";\n /**\n * Gets or sets the swizzle for w (meaning which component to affect to the output.w)\n */\n this.wSwizzle = \"w\";\n this.registerInput(\"xyzw \", NodeMaterialBlockConnectionPointTypes.Vector4, true);\n this.registerInput(\"xyz \", NodeMaterialBlockConnectionPointTypes.Vector3, true);\n this.registerInput(\"xy \", NodeMaterialBlockConnectionPointTypes.Vector2, true);\n this.registerInput(\"zw \", NodeMaterialBlockConnectionPointTypes.Vector2, true);\n this.registerInput(\"x\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"y\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"z\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"w\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerOutput(\"xyzw\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerOutput(\"xyz\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerOutput(\"xy\", NodeMaterialBlockConnectionPointTypes.Vector2);\n this.registerOutput(\"zw\", NodeMaterialBlockConnectionPointTypes.Vector2);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"VectorMergerBlock\";\n }\n /**\n * Gets the xyzw component (input)\n */\n get xyzwIn() {\n return this._inputs[0];\n }\n /**\n * Gets the xyz component (input)\n */\n get xyzIn() {\n return this._inputs[1];\n }\n /**\n * Gets the xy component (input)\n */\n get xyIn() {\n return this._inputs[2];\n }\n /**\n * Gets the zw component (input)\n */\n get zwIn() {\n return this._inputs[3];\n }\n /**\n * Gets the x component (input)\n */\n get x() {\n return this._inputs[4];\n }\n /**\n * Gets the y component (input)\n */\n get y() {\n return this._inputs[5];\n }\n /**\n * Gets the z component (input)\n */\n get z() {\n return this._inputs[6];\n }\n /**\n * Gets the w component (input)\n */\n get w() {\n return this._inputs[7];\n }\n /**\n * Gets the xyzw component (output)\n */\n get xyzw() {\n return this._outputs[0];\n }\n /**\n * Gets the xyz component (output)\n */\n get xyzOut() {\n return this._outputs[1];\n }\n /**\n * Gets the xy component (output)\n */\n get xyOut() {\n return this._outputs[2];\n }\n /**\n * Gets the zw component (output)\n */\n get zwOut() {\n return this._outputs[3];\n }\n /**\n * Gets the xy component (output)\n * @deprecated Please use xyOut instead.\n */\n get xy() {\n return this.xyOut;\n }\n /**\n * Gets the xyz component (output)\n * @deprecated Please use xyzOut instead.\n */\n get xyz() {\n return this.xyzOut;\n }\n _inputRename(name) {\n if (name === \"xyzw \") {\n return \"xyzwIn\";\n }\n if (name === \"xyz \") {\n return \"xyzIn\";\n }\n if (name === \"xy \") {\n return \"xyIn\";\n }\n if (name === \"zw \") {\n return \"zwIn\";\n }\n return name;\n }\n _buildSwizzle(len) {\n const swizzle = this.xSwizzle + this.ySwizzle + this.zSwizzle + this.wSwizzle;\n return \".\" + swizzle.substr(0, len);\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const xInput = this.x;\n const yInput = this.y;\n const zInput = this.z;\n const wInput = this.w;\n const xyInput = this.xyIn;\n const zwInput = this.zwIn;\n const xyzInput = this.xyzIn;\n const xyzwInput = this.xyzwIn;\n const v4Output = this._outputs[0];\n const v3Output = this._outputs[1];\n const v2Output = this._outputs[2];\n const v2CompOutput = this._outputs[3];\n if (xyzwInput.isConnected) {\n if (v4Output.hasEndpoints) {\n state.compilationString += this._declareOutput(v4Output, state) + ` = ${xyzwInput.associatedVariableName}${this._buildSwizzle(4)};\\r\\n`;\n }\n if (v3Output.hasEndpoints) {\n state.compilationString += this._declareOutput(v3Output, state) + ` = ${xyzwInput.associatedVariableName}${this._buildSwizzle(3)};\\r\\n`;\n }\n if (v2Output.hasEndpoints) {\n state.compilationString += this._declareOutput(v2Output, state) + ` = ${xyzwInput.associatedVariableName}${this._buildSwizzle(2)};\\r\\n`;\n }\n }\n else if (xyzInput.isConnected) {\n if (v4Output.hasEndpoints) {\n state.compilationString +=\n this._declareOutput(v4Output, state) +\n ` = vec4(${xyzInput.associatedVariableName}, ${wInput.isConnected ? this._writeVariable(wInput) : \"0.0\"})${this._buildSwizzle(4)};\\r\\n`;\n }\n if (v3Output.hasEndpoints) {\n state.compilationString += this._declareOutput(v3Output, state) + ` = ${xyzInput.associatedVariableName}${this._buildSwizzle(3)};\\r\\n`;\n }\n if (v2Output.hasEndpoints) {\n state.compilationString += this._declareOutput(v2Output, state) + ` = ${xyzInput.associatedVariableName}${this._buildSwizzle(2)};\\r\\n`;\n }\n }\n else if (xyInput.isConnected) {\n if (v4Output.hasEndpoints) {\n if (zwInput.isConnected) {\n state.compilationString +=\n this._declareOutput(v4Output, state) + ` = vec4(${xyInput.associatedVariableName}, ${zwInput.associatedVariableName})${this._buildSwizzle(4)};\\r\\n`;\n }\n else {\n state.compilationString +=\n this._declareOutput(v4Output, state) +\n ` = vec4(${xyInput.associatedVariableName}, ${zInput.isConnected ? this._writeVariable(zInput) : \"0.0\"}, ${wInput.isConnected ? this._writeVariable(wInput) : \"0.0\"})${this._buildSwizzle(4)};\\r\\n`;\n }\n }\n if (v3Output.hasEndpoints) {\n state.compilationString +=\n this._declareOutput(v3Output, state) +\n ` = vec3(${xyInput.associatedVariableName}, ${zInput.isConnected ? this._writeVariable(zInput) : \"0.0\"})${this._buildSwizzle(3)};\\r\\n`;\n }\n if (v2Output.hasEndpoints) {\n state.compilationString += this._declareOutput(v2Output, state) + ` = ${xyInput.associatedVariableName}${this._buildSwizzle(2)};\\r\\n`;\n }\n if (v2CompOutput.hasEndpoints) {\n if (zwInput.isConnected) {\n state.compilationString += this._declareOutput(v2CompOutput, state) + ` = ${zwInput.associatedVariableName}${this._buildSwizzle(2)};\\r\\n`;\n }\n else {\n state.compilationString +=\n this._declareOutput(v2CompOutput, state) +\n ` = vec2(${zInput.isConnected ? this._writeVariable(zInput) : \"0.0\"}, ${wInput.isConnected ? this._writeVariable(wInput) : \"0.0\"})${this._buildSwizzle(2)};\\r\\n`;\n }\n }\n }\n else {\n if (v4Output.hasEndpoints) {\n if (zwInput.isConnected) {\n state.compilationString +=\n this._declareOutput(v4Output, state) +\n ` = vec4(${xInput.isConnected ? this._writeVariable(xInput) : \"0.0\"}, ${yInput.isConnected ? this._writeVariable(yInput) : \"0.0\"}, ${zwInput.associatedVariableName})${this._buildSwizzle(4)};\\r\\n`;\n }\n else {\n state.compilationString +=\n this._declareOutput(v4Output, state) +\n ` = vec4(${xInput.isConnected ? this._writeVariable(xInput) : \"0.0\"}, ${yInput.isConnected ? this._writeVariable(yInput) : \"0.0\"}, ${zInput.isConnected ? this._writeVariable(zInput) : \"0.0\"}, ${wInput.isConnected ? this._writeVariable(wInput) : \"0.0\"})${this._buildSwizzle(4)};\\r\\n`;\n }\n }\n if (v3Output.hasEndpoints) {\n state.compilationString +=\n this._declareOutput(v3Output, state) +\n ` = vec3(${xInput.isConnected ? this._writeVariable(xInput) : \"0.0\"}, ${yInput.isConnected ? this._writeVariable(yInput) : \"0.0\"}, ${zInput.isConnected ? this._writeVariable(zInput) : \"0.0\"})${this._buildSwizzle(3)};\\r\\n`;\n }\n if (v2Output.hasEndpoints) {\n state.compilationString +=\n this._declareOutput(v2Output, state) +\n ` = vec2(${xInput.isConnected ? this._writeVariable(xInput) : \"0.0\"}, ${yInput.isConnected ? this._writeVariable(yInput) : \"0.0\"})${this._buildSwizzle(2)};\\r\\n`;\n }\n if (v2CompOutput.hasEndpoints) {\n if (zwInput.isConnected) {\n state.compilationString += this._declareOutput(v2CompOutput, state) + ` = ${zwInput.associatedVariableName}${this._buildSwizzle(2)};\\r\\n`;\n }\n else {\n state.compilationString +=\n this._declareOutput(v2CompOutput, state) +\n ` = vec2(${zInput.isConnected ? this._writeVariable(zInput) : \"0.0\"}, ${wInput.isConnected ? this._writeVariable(wInput) : \"0.0\"})${this._buildSwizzle(2)};\\r\\n`;\n }\n }\n }\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.xSwizzle = this.xSwizzle;\n serializationObject.ySwizzle = this.ySwizzle;\n serializationObject.zSwizzle = this.zSwizzle;\n serializationObject.wSwizzle = this.wSwizzle;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n var _a, _b, _c, _d;\n super._deserialize(serializationObject, scene, rootUrl);\n this.xSwizzle = (_a = serializationObject.xSwizzle) !== null && _a !== void 0 ? _a : \"x\";\n this.ySwizzle = (_b = serializationObject.ySwizzle) !== null && _b !== void 0 ? _b : \"y\";\n this.zSwizzle = (_c = serializationObject.zSwizzle) !== null && _c !== void 0 ? _c : \"z\";\n this.wSwizzle = (_d = serializationObject.wSwizzle) !== null && _d !== void 0 ? _d : \"w\";\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n codeString += `${this._codeVariableName}.xSwizzle = \"${this.xSwizzle}\";\\r\\n`;\n codeString += `${this._codeVariableName}.ySwizzle = \"${this.ySwizzle}\";\\r\\n`;\n codeString += `${this._codeVariableName}.zSwizzle = \"${this.zSwizzle}\";\\r\\n`;\n codeString += `${this._codeVariableName}.wSwizzle = \"${this.wSwizzle}\";\\r\\n`;\n return codeString;\n }\n}\nRegisterClass(\"BABYLON.VectorMergerBlock\", VectorMergerBlock);\n//# sourceMappingURL=vectorMergerBlock.js.map","import { __decorate } from \"../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { Vector2 } from \"../../../Maths/math.vector.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../nodeMaterialDecorator.js\";\n/**\n * Block used to remap a float from a range to a new one\n */\nexport class RemapBlock extends NodeMaterialBlock {\n /**\n * Creates a new RemapBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n /**\n * Gets or sets the source range\n */\n this.sourceRange = new Vector2(-1, 1);\n /**\n * Gets or sets the target range\n */\n this.targetRange = new Vector2(0, 1);\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"sourceMin\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"sourceMax\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"targetMin\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"targetMax\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"RemapBlock\";\n }\n /**\n * Gets the input component\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the source min input component\n */\n get sourceMin() {\n return this._inputs[1];\n }\n /**\n * Gets the source max input component\n */\n get sourceMax() {\n return this._inputs[2];\n }\n /**\n * Gets the target min input component\n */\n get targetMin() {\n return this._inputs[3];\n }\n /**\n * Gets the target max input component\n */\n get targetMax() {\n return this._inputs[4];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n const sourceMin = this.sourceMin.isConnected ? this.sourceMin.associatedVariableName : this._writeFloat(this.sourceRange.x);\n const sourceMax = this.sourceMax.isConnected ? this.sourceMax.associatedVariableName : this._writeFloat(this.sourceRange.y);\n const targetMin = this.targetMin.isConnected ? this.targetMin.associatedVariableName : this._writeFloat(this.targetRange.x);\n const targetMax = this.targetMax.isConnected ? this.targetMax.associatedVariableName : this._writeFloat(this.targetRange.y);\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = ${targetMin} + (${this._inputs[0].associatedVariableName} - ${sourceMin}) * (${targetMax} - ${targetMin}) / (${sourceMax} - ${sourceMin});\\r\\n`;\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y});\\r\\n`;\n codeString += `${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y});\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.sourceRange = this.sourceRange.asArray();\n serializationObject.targetRange = this.targetRange.asArray();\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.sourceRange = Vector2.FromArray(serializationObject.sourceRange);\n this.targetRange = Vector2.FromArray(serializationObject.targetRange);\n }\n}\n__decorate([\n editableInPropertyPage(\"From\", PropertyTypeForEdition.Vector2)\n], RemapBlock.prototype, \"sourceRange\", void 0);\n__decorate([\n editableInPropertyPage(\"To\", PropertyTypeForEdition.Vector2)\n], RemapBlock.prototype, \"targetRange\", void 0);\nRegisterClass(\"BABYLON.RemapBlock\", RemapBlock);\n//# sourceMappingURL=remapBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to multiply 2 values\n */\nexport class MultiplyBlock extends NodeMaterialBlock {\n /**\n * Creates a new MultiplyBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"left\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"right\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._linkConnectionTypes(0, 1);\n this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"MultiplyBlock\";\n }\n /**\n * Gets the left operand input component\n */\n get left() {\n return this._inputs[0];\n }\n /**\n * Gets the right operand input component\n */\n get right() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = ${this.left.associatedVariableName} * ${this.right.associatedVariableName};\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.MultiplyBlock\", MultiplyBlock);\n//# sourceMappingURL=multiplyBlock.js.map","import { DeepCopier } from \"../../Misc/deepCopier.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Scalar } from \"../../Maths/math.scalar.js\";\n/**\n * Particle emitter emitting particles from the inside of a box.\n * It emits the particles randomly between 2 given directions.\n */\nexport class BoxParticleEmitter {\n /**\n * Creates a new instance BoxParticleEmitter\n */\n constructor() {\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n */\n this.direction1 = new Vector3(0, 1.0, 0);\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n */\n this.direction2 = new Vector3(0, 1.0, 0);\n /**\n * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.\n */\n this.minEmitBox = new Vector3(-0.5, -0.5, -0.5);\n /**\n * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.\n */\n this.maxEmitBox = new Vector3(0.5, 0.5, 0.5);\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n * @param isLocal defines if the direction should be set in local space\n */\n startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) {\n const randX = Scalar.RandomRange(this.direction1.x, this.direction2.x);\n const randY = Scalar.RandomRange(this.direction1.y, this.direction2.y);\n const randZ = Scalar.RandomRange(this.direction1.z, this.direction2.z);\n if (isLocal) {\n directionToUpdate.x = randX;\n directionToUpdate.y = randY;\n directionToUpdate.z = randZ;\n return;\n }\n Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);\n }\n /**\n * Called by the particle System when the position is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param positionToUpdate is the position vector to update with the result\n * @param particle is the particle we are computed the position for\n * @param isLocal defines if the position should be set in local space\n */\n startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) {\n const randX = Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);\n const randY = Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);\n const randZ = Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);\n if (isLocal) {\n positionToUpdate.x = randX;\n positionToUpdate.y = randY;\n positionToUpdate.z = randZ;\n return;\n }\n Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);\n }\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n clone() {\n const newOne = new BoxParticleEmitter();\n DeepCopier.DeepCopy(this, newOne);\n return newOne;\n }\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param uboOrEffect defines the update shader\n */\n applyToShader(uboOrEffect) {\n uboOrEffect.setVector3(\"direction1\", this.direction1);\n uboOrEffect.setVector3(\"direction2\", this.direction2);\n uboOrEffect.setVector3(\"minEmitBox\", this.minEmitBox);\n uboOrEffect.setVector3(\"maxEmitBox\", this.maxEmitBox);\n }\n /**\n * Creates the structure of the ubo for this particle emitter\n * @param ubo ubo to create the structure for\n */\n buildUniformLayout(ubo) {\n ubo.addUniform(\"direction1\", 3);\n ubo.addUniform(\"direction2\", 3);\n ubo.addUniform(\"minEmitBox\", 3);\n ubo.addUniform(\"maxEmitBox\", 3);\n }\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containing the defines string\n */\n getEffectDefines() {\n return \"#define BOXEMITTER\";\n }\n /**\n * Returns the string \"BoxParticleEmitter\"\n * @returns a string containing the class name\n */\n getClassName() {\n return \"BoxParticleEmitter\";\n }\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n serialize() {\n const serializationObject = {};\n serializationObject.type = this.getClassName();\n serializationObject.direction1 = this.direction1.asArray();\n serializationObject.direction2 = this.direction2.asArray();\n serializationObject.minEmitBox = this.minEmitBox.asArray();\n serializationObject.maxEmitBox = this.maxEmitBox.asArray();\n return serializationObject;\n }\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n parse(serializationObject) {\n Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);\n Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);\n Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);\n Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);\n }\n}\n//# sourceMappingURL=boxParticleEmitter.js.map","import { DeepCopier } from \"../../Misc/deepCopier.js\";\nimport { Vector3, TmpVectors } from \"../../Maths/math.vector.js\";\nimport { Scalar } from \"../../Maths/math.scalar.js\";\n/**\n * Particle emitter emitting particles from the inside of a cone.\n * It emits the particles alongside the cone volume from the base to the particle.\n * The emission direction might be randomized.\n */\nexport class ConeParticleEmitter {\n /**\n * Gets or sets the radius of the emission cone\n */\n get radius() {\n return this._radius;\n }\n set radius(value) {\n this._radius = value;\n this._buildHeight();\n }\n /**\n * Gets or sets the angle of the emission cone\n */\n get angle() {\n return this._angle;\n }\n set angle(value) {\n this._angle = value;\n this._buildHeight();\n }\n _buildHeight() {\n if (this._angle !== 0) {\n this._height = this._radius / Math.tan(this._angle / 2);\n }\n else {\n this._height = 1;\n }\n }\n /**\n * Creates a new instance ConeParticleEmitter\n * @param radius the radius of the emission cone (1 by default)\n * @param angle the cone base angle (PI by default)\n * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)\n */\n constructor(radius = 1, angle = Math.PI, \n /** defines how much to randomize the particle direction [0-1] (default is 0) */\n directionRandomizer = 0) {\n this.directionRandomizer = directionRandomizer;\n /**\n * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)\n */\n this.radiusRange = 1;\n /**\n * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)\n */\n this.heightRange = 1;\n /**\n * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)\n */\n this.emitFromSpawnPointOnly = false;\n this.angle = angle;\n this.radius = radius;\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n * @param isLocal defines if the direction should be set in local space\n */\n startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) {\n if (isLocal) {\n TmpVectors.Vector3[0].copyFrom(particle._localPosition).normalize();\n }\n else {\n particle.position.subtractToRef(worldMatrix.getTranslation(), TmpVectors.Vector3[0]).normalize();\n }\n const randX = Scalar.RandomRange(0, this.directionRandomizer);\n const randY = Scalar.RandomRange(0, this.directionRandomizer);\n const randZ = Scalar.RandomRange(0, this.directionRandomizer);\n directionToUpdate.x = TmpVectors.Vector3[0].x + randX;\n directionToUpdate.y = TmpVectors.Vector3[0].y + randY;\n directionToUpdate.z = TmpVectors.Vector3[0].z + randZ;\n directionToUpdate.normalize();\n }\n /**\n * Called by the particle System when the position is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param positionToUpdate is the position vector to update with the result\n * @param particle is the particle we are computed the position for\n * @param isLocal defines if the position should be set in local space\n */\n startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) {\n const s = Scalar.RandomRange(0, Math.PI * 2);\n let h;\n if (!this.emitFromSpawnPointOnly) {\n h = Scalar.RandomRange(0, this.heightRange);\n // Better distribution in a cone at normal angles.\n h = 1 - h * h;\n }\n else {\n h = 0.0001;\n }\n let radius = this._radius - Scalar.RandomRange(0, this._radius * this.radiusRange);\n radius = radius * h;\n const randX = radius * Math.sin(s);\n const randZ = radius * Math.cos(s);\n const randY = h * this._height;\n if (isLocal) {\n positionToUpdate.x = randX;\n positionToUpdate.y = randY;\n positionToUpdate.z = randZ;\n return;\n }\n Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);\n }\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n clone() {\n const newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);\n DeepCopier.DeepCopy(this, newOne);\n return newOne;\n }\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param uboOrEffect defines the update shader\n */\n applyToShader(uboOrEffect) {\n uboOrEffect.setFloat2(\"radius\", this._radius, this.radiusRange);\n uboOrEffect.setFloat(\"coneAngle\", this._angle);\n uboOrEffect.setFloat2(\"height\", this._height, this.heightRange);\n uboOrEffect.setFloat(\"directionRandomizer\", this.directionRandomizer);\n }\n /**\n * Creates the structure of the ubo for this particle emitter\n * @param ubo ubo to create the structure for\n */\n buildUniformLayout(ubo) {\n ubo.addUniform(\"radius\", 2);\n ubo.addUniform(\"coneAngle\", 1);\n ubo.addUniform(\"height\", 2);\n ubo.addUniform(\"directionRandomizer\", 1);\n }\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containing the defines string\n */\n getEffectDefines() {\n let defines = \"#define CONEEMITTER\";\n if (this.emitFromSpawnPointOnly) {\n defines += \"\\n#define CONEEMITTERSPAWNPOINT\";\n }\n return defines;\n }\n /**\n * Returns the string \"ConeParticleEmitter\"\n * @returns a string containing the class name\n */\n getClassName() {\n return \"ConeParticleEmitter\";\n }\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n serialize() {\n const serializationObject = {};\n serializationObject.type = this.getClassName();\n serializationObject.radius = this._radius;\n serializationObject.angle = this._angle;\n serializationObject.directionRandomizer = this.directionRandomizer;\n serializationObject.radiusRange = this.radiusRange;\n serializationObject.heightRange = this.heightRange;\n serializationObject.emitFromSpawnPointOnly = this.emitFromSpawnPointOnly;\n return serializationObject;\n }\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n parse(serializationObject) {\n this.radius = serializationObject.radius;\n this.angle = serializationObject.angle;\n this.directionRandomizer = serializationObject.directionRandomizer;\n this.radiusRange = serializationObject.radiusRange !== undefined ? serializationObject.radiusRange : 1;\n this.heightRange = serializationObject.radiusRange !== undefined ? serializationObject.heightRange : 1;\n this.emitFromSpawnPointOnly = serializationObject.emitFromSpawnPointOnly !== undefined ? serializationObject.emitFromSpawnPointOnly : false;\n }\n}\n//# sourceMappingURL=coneParticleEmitter.js.map","import { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Scalar } from \"../../Maths/math.scalar.js\";\nimport { DeepCopier } from \"../../Misc/deepCopier.js\";\n/**\n * Particle emitter emitting particles from the inside of a cylinder.\n * It emits the particles alongside the cylinder radius. The emission direction might be randomized.\n */\nexport class CylinderParticleEmitter {\n /**\n * Creates a new instance CylinderParticleEmitter\n * @param radius the radius of the emission cylinder (1 by default)\n * @param height the height of the emission cylinder (1 by default)\n * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)\n * @param directionRandomizer defines how much to randomize the particle direction [0-1]\n */\n constructor(\n /**\n * The radius of the emission cylinder.\n */\n radius = 1, \n /**\n * The height of the emission cylinder.\n */\n height = 1, \n /**\n * The range of emission [0-1] 0 Surface only, 1 Entire Radius.\n */\n radiusRange = 1, \n /**\n * How much to randomize the particle direction [0-1].\n */\n directionRandomizer = 0) {\n this.radius = radius;\n this.height = height;\n this.radiusRange = radiusRange;\n this.directionRandomizer = directionRandomizer;\n this._tempVector = Vector3.Zero();\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n * @param isLocal defines if the direction should be set in local space\n * @param inverseWorldMatrix defines the inverted world matrix to use if isLocal is false\n */\n startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal, inverseWorldMatrix) {\n particle.position.subtractToRef(worldMatrix.getTranslation(), this._tempVector);\n this._tempVector.normalize();\n Vector3.TransformNormalToRef(this._tempVector, inverseWorldMatrix, this._tempVector);\n const randY = Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);\n let angle = Math.atan2(this._tempVector.x, this._tempVector.z);\n angle += Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;\n this._tempVector.y = randY; // set direction y to rand y to mirror normal of cylinder surface\n this._tempVector.x = Math.sin(angle);\n this._tempVector.z = Math.cos(angle);\n this._tempVector.normalize();\n if (isLocal) {\n directionToUpdate.copyFrom(this._tempVector);\n return;\n }\n Vector3.TransformNormalFromFloatsToRef(this._tempVector.x, this._tempVector.y, this._tempVector.z, worldMatrix, directionToUpdate);\n }\n /**\n * Called by the particle System when the position is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param positionToUpdate is the position vector to update with the result\n * @param particle is the particle we are computed the position for\n * @param isLocal defines if the position should be set in local space\n */\n startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) {\n const yPos = Scalar.RandomRange(-this.height / 2, this.height / 2);\n const angle = Scalar.RandomRange(0, 2 * Math.PI);\n // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html\n const radiusDistribution = Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);\n const positionRadius = Math.sqrt(radiusDistribution) * this.radius;\n const xPos = positionRadius * Math.cos(angle);\n const zPos = positionRadius * Math.sin(angle);\n if (isLocal) {\n positionToUpdate.copyFromFloats(xPos, yPos, zPos);\n return;\n }\n Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);\n }\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n clone() {\n const newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);\n DeepCopier.DeepCopy(this, newOne);\n return newOne;\n }\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param uboOrEffect defines the update shader\n */\n applyToShader(uboOrEffect) {\n uboOrEffect.setFloat(\"radius\", this.radius);\n uboOrEffect.setFloat(\"height\", this.height);\n uboOrEffect.setFloat(\"radiusRange\", this.radiusRange);\n uboOrEffect.setFloat(\"directionRandomizer\", this.directionRandomizer);\n }\n /**\n * Creates the structure of the ubo for this particle emitter\n * @param ubo ubo to create the structure for\n */\n buildUniformLayout(ubo) {\n ubo.addUniform(\"radius\", 1);\n ubo.addUniform(\"height\", 1);\n ubo.addUniform(\"radiusRange\", 1);\n ubo.addUniform(\"directionRandomizer\", 1);\n }\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containing the defines string\n */\n getEffectDefines() {\n return \"#define CYLINDEREMITTER\";\n }\n /**\n * Returns the string \"CylinderParticleEmitter\"\n * @returns a string containing the class name\n */\n getClassName() {\n return \"CylinderParticleEmitter\";\n }\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n serialize() {\n const serializationObject = {};\n serializationObject.type = this.getClassName();\n serializationObject.radius = this.radius;\n serializationObject.height = this.height;\n serializationObject.radiusRange = this.radiusRange;\n serializationObject.directionRandomizer = this.directionRandomizer;\n return serializationObject;\n }\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n parse(serializationObject) {\n this.radius = serializationObject.radius;\n this.height = serializationObject.height;\n this.radiusRange = serializationObject.radiusRange;\n this.directionRandomizer = serializationObject.directionRandomizer;\n }\n}\n/**\n * Particle emitter emitting particles from the inside of a cylinder.\n * It emits the particles randomly between two vectors.\n */\nexport class CylinderDirectedParticleEmitter extends CylinderParticleEmitter {\n /**\n * Creates a new instance CylinderDirectedParticleEmitter\n * @param radius the radius of the emission cylinder (1 by default)\n * @param height the height of the emission cylinder (1 by default)\n * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)\n * @param direction1 the min limit of the emission direction (up vector by default)\n * @param direction2 the max limit of the emission direction (up vector by default)\n */\n constructor(radius = 1, height = 1, radiusRange = 1, \n /**\n * The min limit of the emission direction.\n */\n direction1 = new Vector3(0, 1, 0), \n /**\n * The max limit of the emission direction.\n */\n direction2 = new Vector3(0, 1, 0)) {\n super(radius, height, radiusRange);\n this.direction1 = direction1;\n this.direction2 = direction2;\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n */\n startDirectionFunction(worldMatrix, directionToUpdate) {\n const randX = Scalar.RandomRange(this.direction1.x, this.direction2.x);\n const randY = Scalar.RandomRange(this.direction1.y, this.direction2.y);\n const randZ = Scalar.RandomRange(this.direction1.z, this.direction2.z);\n Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);\n }\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n clone() {\n const newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);\n DeepCopier.DeepCopy(this, newOne);\n return newOne;\n }\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param uboOrEffect defines the update shader\n */\n applyToShader(uboOrEffect) {\n uboOrEffect.setFloat(\"radius\", this.radius);\n uboOrEffect.setFloat(\"height\", this.height);\n uboOrEffect.setFloat(\"radiusRange\", this.radiusRange);\n uboOrEffect.setVector3(\"direction1\", this.direction1);\n uboOrEffect.setVector3(\"direction2\", this.direction2);\n }\n /**\n * Creates the structure of the ubo for this particle emitter\n * @param ubo ubo to create the structure for\n */\n buildUniformLayout(ubo) {\n ubo.addUniform(\"radius\", 1);\n ubo.addUniform(\"height\", 1);\n ubo.addUniform(\"radiusRange\", 1);\n ubo.addUniform(\"direction1\", 3);\n ubo.addUniform(\"direction2\", 3);\n }\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containing the defines string\n */\n getEffectDefines() {\n return \"#define CYLINDEREMITTER\\n#define DIRECTEDCYLINDEREMITTER\";\n }\n /**\n * Returns the string \"CylinderDirectedParticleEmitter\"\n * @returns a string containing the class name\n */\n getClassName() {\n return \"CylinderDirectedParticleEmitter\";\n }\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.direction1 = this.direction1.asArray();\n serializationObject.direction2 = this.direction2.asArray();\n return serializationObject;\n }\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n parse(serializationObject) {\n super.parse(serializationObject);\n this.direction1.copyFrom(serializationObject.direction1);\n this.direction2.copyFrom(serializationObject.direction2);\n }\n}\n//# sourceMappingURL=cylinderParticleEmitter.js.map","import { DeepCopier } from \"../../Misc/deepCopier.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Scalar } from \"../../Maths/math.scalar.js\";\n/**\n * Particle emitter emitting particles from the inside of a hemisphere.\n * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.\n */\nexport class HemisphericParticleEmitter {\n /**\n * Creates a new instance HemisphericParticleEmitter\n * @param radius the radius of the emission hemisphere (1 by default)\n * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)\n * @param directionRandomizer defines how much to randomize the particle direction [0-1]\n */\n constructor(\n /**\n * The radius of the emission hemisphere.\n */\n radius = 1, \n /**\n * The range of emission [0-1] 0 Surface only, 1 Entire Radius.\n */\n radiusRange = 1, \n /**\n * How much to randomize the particle direction [0-1].\n */\n directionRandomizer = 0) {\n this.radius = radius;\n this.radiusRange = radiusRange;\n this.directionRandomizer = directionRandomizer;\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n * @param isLocal defines if the direction should be set in local space\n */\n startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) {\n const direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();\n const randX = Scalar.RandomRange(0, this.directionRandomizer);\n const randY = Scalar.RandomRange(0, this.directionRandomizer);\n const randZ = Scalar.RandomRange(0, this.directionRandomizer);\n direction.x += randX;\n direction.y += randY;\n direction.z += randZ;\n direction.normalize();\n if (isLocal) {\n directionToUpdate.copyFrom(direction);\n return;\n }\n Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);\n }\n /**\n * Called by the particle System when the position is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param positionToUpdate is the position vector to update with the result\n * @param particle is the particle we are computed the position for\n * @param isLocal defines if the position should be set in local space\n */\n startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) {\n const randRadius = this.radius - Scalar.RandomRange(0, this.radius * this.radiusRange);\n const v = Scalar.RandomRange(0, 1.0);\n const phi = Scalar.RandomRange(0, 2 * Math.PI);\n const theta = Math.acos(2 * v - 1);\n const randX = randRadius * Math.cos(phi) * Math.sin(theta);\n const randY = randRadius * Math.cos(theta);\n const randZ = randRadius * Math.sin(phi) * Math.sin(theta);\n if (isLocal) {\n positionToUpdate.copyFromFloats(randX, Math.abs(randY), randZ);\n return;\n }\n Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);\n }\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n clone() {\n const newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);\n DeepCopier.DeepCopy(this, newOne);\n return newOne;\n }\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param uboOrEffect defines the update shader\n */\n applyToShader(uboOrEffect) {\n uboOrEffect.setFloat(\"radius\", this.radius);\n uboOrEffect.setFloat(\"radiusRange\", this.radiusRange);\n uboOrEffect.setFloat(\"directionRandomizer\", this.directionRandomizer);\n }\n /**\n * Creates the structure of the ubo for this particle emitter\n * @param ubo ubo to create the structure for\n */\n buildUniformLayout(ubo) {\n ubo.addUniform(\"radius\", 1);\n ubo.addUniform(\"radiusRange\", 1);\n ubo.addUniform(\"directionRandomizer\", 1);\n }\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containing the defines string\n */\n getEffectDefines() {\n return \"#define HEMISPHERICEMITTER\";\n }\n /**\n * Returns the string \"HemisphericParticleEmitter\"\n * @returns a string containing the class name\n */\n getClassName() {\n return \"HemisphericParticleEmitter\";\n }\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n serialize() {\n const serializationObject = {};\n serializationObject.type = this.getClassName();\n serializationObject.radius = this.radius;\n serializationObject.radiusRange = this.radiusRange;\n serializationObject.directionRandomizer = this.directionRandomizer;\n return serializationObject;\n }\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n parse(serializationObject) {\n this.radius = serializationObject.radius;\n this.radiusRange = serializationObject.radiusRange;\n this.directionRandomizer = serializationObject.directionRandomizer;\n }\n}\n//# sourceMappingURL=hemisphericParticleEmitter.js.map","export {};\n//# sourceMappingURL=IParticleEmitterType.js.map","import { DeepCopier } from \"../../Misc/deepCopier.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Scalar } from \"../../Maths/math.scalar.js\";\n/**\n * Particle emitter emitting particles from a point.\n * It emits the particles randomly between 2 given directions.\n */\nexport class PointParticleEmitter {\n /**\n * Creates a new instance PointParticleEmitter\n */\n constructor() {\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n */\n this.direction1 = new Vector3(0, 1.0, 0);\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n */\n this.direction2 = new Vector3(0, 1.0, 0);\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n * @param isLocal defines if the direction should be set in local space\n */\n startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) {\n const randX = Scalar.RandomRange(this.direction1.x, this.direction2.x);\n const randY = Scalar.RandomRange(this.direction1.y, this.direction2.y);\n const randZ = Scalar.RandomRange(this.direction1.z, this.direction2.z);\n if (isLocal) {\n directionToUpdate.copyFromFloats(randX, randY, randZ);\n return;\n }\n Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);\n }\n /**\n * Called by the particle System when the position is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param positionToUpdate is the position vector to update with the result\n * @param particle is the particle we are computed the position for\n * @param isLocal defines if the position should be set in local space\n */\n startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) {\n if (isLocal) {\n positionToUpdate.copyFromFloats(0, 0, 0);\n return;\n }\n Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);\n }\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n clone() {\n const newOne = new PointParticleEmitter();\n DeepCopier.DeepCopy(this, newOne);\n return newOne;\n }\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param uboOrEffect defines the update shader\n */\n applyToShader(uboOrEffect) {\n uboOrEffect.setVector3(\"direction1\", this.direction1);\n uboOrEffect.setVector3(\"direction2\", this.direction2);\n }\n /**\n * Creates the structure of the ubo for this particle emitter\n * @param ubo ubo to create the structure for\n */\n buildUniformLayout(ubo) {\n ubo.addUniform(\"direction1\", 3);\n ubo.addUniform(\"direction2\", 3);\n }\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containing the defines string\n */\n getEffectDefines() {\n return \"#define POINTEMITTER\";\n }\n /**\n * Returns the string \"PointParticleEmitter\"\n * @returns a string containing the class name\n */\n getClassName() {\n return \"PointParticleEmitter\";\n }\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n serialize() {\n const serializationObject = {};\n serializationObject.type = this.getClassName();\n serializationObject.direction1 = this.direction1.asArray();\n serializationObject.direction2 = this.direction2.asArray();\n return serializationObject;\n }\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n parse(serializationObject) {\n Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);\n Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);\n }\n}\n//# sourceMappingURL=pointParticleEmitter.js.map","import { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Scalar } from \"../../Maths/math.scalar.js\";\nimport { DeepCopier } from \"../../Misc/deepCopier.js\";\n/**\n * Particle emitter emitting particles from the inside of a sphere.\n * It emits the particles alongside the sphere radius. The emission direction might be randomized.\n */\nexport class SphereParticleEmitter {\n /**\n * Creates a new instance SphereParticleEmitter\n * @param radius the radius of the emission sphere (1 by default)\n * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)\n * @param directionRandomizer defines how much to randomize the particle direction [0-1]\n */\n constructor(\n /**\n * The radius of the emission sphere.\n */\n radius = 1, \n /**\n * The range of emission [0-1] 0 Surface only, 1 Entire Radius.\n */\n radiusRange = 1, \n /**\n * How much to randomize the particle direction [0-1].\n */\n directionRandomizer = 0) {\n this.radius = radius;\n this.radiusRange = radiusRange;\n this.directionRandomizer = directionRandomizer;\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n * @param isLocal defines if the direction should be set in local space\n */\n startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) {\n const direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();\n const randX = Scalar.RandomRange(0, this.directionRandomizer);\n const randY = Scalar.RandomRange(0, this.directionRandomizer);\n const randZ = Scalar.RandomRange(0, this.directionRandomizer);\n direction.x += randX;\n direction.y += randY;\n direction.z += randZ;\n direction.normalize();\n if (isLocal) {\n directionToUpdate.copyFrom(direction);\n return;\n }\n Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);\n }\n /**\n * Called by the particle System when the position is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param positionToUpdate is the position vector to update with the result\n * @param particle is the particle we are computed the position for\n * @param isLocal defines if the position should be set in local space\n */\n startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) {\n const randRadius = this.radius - Scalar.RandomRange(0, this.radius * this.radiusRange);\n const v = Scalar.RandomRange(0, 1.0);\n const phi = Scalar.RandomRange(0, 2 * Math.PI);\n const theta = Math.acos(2 * v - 1);\n const randX = randRadius * Math.cos(phi) * Math.sin(theta);\n const randY = randRadius * Math.cos(theta);\n const randZ = randRadius * Math.sin(phi) * Math.sin(theta);\n if (isLocal) {\n positionToUpdate.copyFromFloats(randX, randY, randZ);\n return;\n }\n Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);\n }\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n clone() {\n const newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);\n DeepCopier.DeepCopy(this, newOne);\n return newOne;\n }\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param uboOrEffect defines the update shader\n */\n applyToShader(uboOrEffect) {\n uboOrEffect.setFloat(\"radius\", this.radius);\n uboOrEffect.setFloat(\"radiusRange\", this.radiusRange);\n uboOrEffect.setFloat(\"directionRandomizer\", this.directionRandomizer);\n }\n /**\n * Creates the structure of the ubo for this particle emitter\n * @param ubo ubo to create the structure for\n */\n buildUniformLayout(ubo) {\n ubo.addUniform(\"radius\", 1);\n ubo.addUniform(\"radiusRange\", 1);\n ubo.addUniform(\"directionRandomizer\", 1);\n }\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containing the defines string\n */\n getEffectDefines() {\n return \"#define SPHEREEMITTER\";\n }\n /**\n * Returns the string \"SphereParticleEmitter\"\n * @returns a string containing the class name\n */\n getClassName() {\n return \"SphereParticleEmitter\";\n }\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n serialize() {\n const serializationObject = {};\n serializationObject.type = this.getClassName();\n serializationObject.radius = this.radius;\n serializationObject.radiusRange = this.radiusRange;\n serializationObject.directionRandomizer = this.directionRandomizer;\n return serializationObject;\n }\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n parse(serializationObject) {\n this.radius = serializationObject.radius;\n this.radiusRange = serializationObject.radiusRange;\n this.directionRandomizer = serializationObject.directionRandomizer;\n }\n}\n/**\n * Particle emitter emitting particles from the inside of a sphere.\n * It emits the particles randomly between two vectors.\n */\nexport class SphereDirectedParticleEmitter extends SphereParticleEmitter {\n /**\n * Creates a new instance SphereDirectedParticleEmitter\n * @param radius the radius of the emission sphere (1 by default)\n * @param direction1 the min limit of the emission direction (up vector by default)\n * @param direction2 the max limit of the emission direction (up vector by default)\n */\n constructor(radius = 1, \n /**\n * The min limit of the emission direction.\n */\n direction1 = new Vector3(0, 1, 0), \n /**\n * The max limit of the emission direction.\n */\n direction2 = new Vector3(0, 1, 0)) {\n super(radius);\n this.direction1 = direction1;\n this.direction2 = direction2;\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n */\n startDirectionFunction(worldMatrix, directionToUpdate) {\n const randX = Scalar.RandomRange(this.direction1.x, this.direction2.x);\n const randY = Scalar.RandomRange(this.direction1.y, this.direction2.y);\n const randZ = Scalar.RandomRange(this.direction1.z, this.direction2.z);\n Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);\n }\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n clone() {\n const newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);\n DeepCopier.DeepCopy(this, newOne);\n return newOne;\n }\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param uboOrEffect defines the update shader\n */\n applyToShader(uboOrEffect) {\n uboOrEffect.setFloat(\"radius\", this.radius);\n uboOrEffect.setFloat(\"radiusRange\", this.radiusRange);\n uboOrEffect.setVector3(\"direction1\", this.direction1);\n uboOrEffect.setVector3(\"direction2\", this.direction2);\n }\n /**\n * Creates the structure of the ubo for this particle emitter\n * @param ubo ubo to create the structure for\n */\n buildUniformLayout(ubo) {\n ubo.addUniform(\"radius\", 1);\n ubo.addUniform(\"radiusRange\", 1);\n ubo.addUniform(\"direction1\", 3);\n ubo.addUniform(\"direction2\", 3);\n }\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containing the defines string\n */\n getEffectDefines() {\n return \"#define SPHEREEMITTER\\n#define DIRECTEDSPHEREEMITTER\";\n }\n /**\n * Returns the string \"SphereDirectedParticleEmitter\"\n * @returns a string containing the class name\n */\n getClassName() {\n return \"SphereDirectedParticleEmitter\";\n }\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.direction1 = this.direction1.asArray();\n serializationObject.direction2 = this.direction2.asArray();\n return serializationObject;\n }\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n parse(serializationObject) {\n super.parse(serializationObject);\n this.direction1.copyFrom(serializationObject.direction1);\n this.direction2.copyFrom(serializationObject.direction2);\n }\n}\n//# sourceMappingURL=sphereParticleEmitter.js.map","import { DeepCopier } from \"../../Misc/deepCopier.js\";\nimport { Vector3, TmpVectors } from \"../../Maths/math.vector.js\";\n/**\n * Particle emitter emitting particles from a custom list of positions.\n */\nexport class CustomParticleEmitter {\n /**\n * Creates a new instance CustomParticleEmitter\n */\n constructor() {\n /**\n * Gets or sets the position generator that will create the initial position of each particle.\n * Index will be provided when used with GPU particle. Particle will be provided when used with CPU particles\n */\n this.particlePositionGenerator = () => { };\n /**\n * Gets or sets the destination generator that will create the final destination of each particle.\n * * Index will be provided when used with GPU particle. Particle will be provided when used with CPU particles\n */\n this.particleDestinationGenerator = () => { };\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n * @param isLocal defines if the direction should be set in local space\n */\n startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) {\n const tmpVector = TmpVectors.Vector3[0];\n if (this.particleDestinationGenerator) {\n this.particleDestinationGenerator(-1, particle, tmpVector);\n // Get direction\n const diffVector = TmpVectors.Vector3[1];\n tmpVector.subtractToRef(particle.position, diffVector);\n diffVector.scaleToRef(1 / particle.lifeTime, tmpVector);\n }\n else {\n tmpVector.set(0, 0, 0);\n }\n if (isLocal) {\n directionToUpdate.copyFrom(tmpVector);\n return;\n }\n Vector3.TransformNormalToRef(tmpVector, worldMatrix, directionToUpdate);\n }\n /**\n * Called by the particle System when the position is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param positionToUpdate is the position vector to update with the result\n * @param particle is the particle we are computed the position for\n * @param isLocal defines if the position should be set in local space\n */\n startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) {\n const tmpVector = TmpVectors.Vector3[0];\n if (this.particlePositionGenerator) {\n this.particlePositionGenerator(-1, particle, tmpVector);\n }\n else {\n tmpVector.set(0, 0, 0);\n }\n if (isLocal) {\n positionToUpdate.copyFrom(tmpVector);\n return;\n }\n Vector3.TransformCoordinatesToRef(tmpVector, worldMatrix, positionToUpdate);\n }\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n clone() {\n const newOne = new CustomParticleEmitter();\n DeepCopier.DeepCopy(this, newOne);\n return newOne;\n }\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param uboOrEffect defines the update shader\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n applyToShader(uboOrEffect) { }\n /**\n * Creates the structure of the ubo for this particle emitter\n * @param ubo ubo to create the structure for\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n buildUniformLayout(ubo) { }\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containing the defines string\n */\n getEffectDefines() {\n return \"#define CUSTOMEMITTER\";\n }\n /**\n * Returns the string \"PointParticleEmitter\"\n * @returns a string containing the class name\n */\n getClassName() {\n return \"CustomParticleEmitter\";\n }\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n serialize() {\n const serializationObject = {};\n serializationObject.type = this.getClassName();\n return serializationObject;\n }\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n parse(serializationObject) { }\n}\n//# sourceMappingURL=customParticleEmitter.js.map","import { DeepCopier } from \"../../Misc/deepCopier.js\";\nimport { Vector3, TmpVectors } from \"../../Maths/math.vector.js\";\nimport { Scalar } from \"../../Maths/math.scalar.js\";\nimport { VertexBuffer } from \"../../Buffers/buffer.js\";\n/**\n * Particle emitter emitting particles from the inside of a box.\n * It emits the particles randomly between 2 given directions.\n */\nexport class MeshParticleEmitter {\n /** Defines the mesh to use as source */\n get mesh() {\n return this._mesh;\n }\n set mesh(value) {\n if (this._mesh === value) {\n return;\n }\n this._mesh = value;\n if (value) {\n this._indices = value.getIndices();\n this._positions = value.getVerticesData(VertexBuffer.PositionKind);\n this._normals = value.getVerticesData(VertexBuffer.NormalKind);\n }\n else {\n this._indices = null;\n this._positions = null;\n this._normals = null;\n }\n }\n /**\n * Creates a new instance MeshParticleEmitter\n * @param mesh defines the mesh to use as source\n */\n constructor(mesh = null) {\n this._indices = null;\n this._positions = null;\n this._normals = null;\n this._storedNormal = Vector3.Zero();\n this._mesh = null;\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n */\n this.direction1 = new Vector3(0, 1.0, 0);\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n */\n this.direction2 = new Vector3(0, 1.0, 0);\n /**\n * Gets or sets a boolean indicating that particle directions must be built from mesh face normals\n */\n this.useMeshNormalsForDirection = true;\n this.mesh = mesh;\n }\n /**\n * Called by the particle System when the direction is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param directionToUpdate is the direction vector to update with the result\n * @param particle is the particle we are computed the direction for\n * @param isLocal defines if the direction should be set in local space\n */\n startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) {\n if (this.useMeshNormalsForDirection && this._normals) {\n Vector3.TransformNormalToRef(this._storedNormal, worldMatrix, directionToUpdate);\n return;\n }\n const randX = Scalar.RandomRange(this.direction1.x, this.direction2.x);\n const randY = Scalar.RandomRange(this.direction1.y, this.direction2.y);\n const randZ = Scalar.RandomRange(this.direction1.z, this.direction2.z);\n if (isLocal) {\n directionToUpdate.copyFromFloats(randX, randY, randZ);\n return;\n }\n Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);\n }\n /**\n * Called by the particle System when the position is computed for the created particle.\n * @param worldMatrix is the world matrix of the particle system\n * @param positionToUpdate is the position vector to update with the result\n * @param particle is the particle we are computed the position for\n * @param isLocal defines if the position should be set in local space\n */\n startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) {\n if (!this._indices || !this._positions) {\n return;\n }\n const randomFaceIndex = (3 * Math.random() * (this._indices.length / 3)) | 0;\n const bu = Math.random();\n const bv = Math.random() * (1.0 - bu);\n const bw = 1.0 - bu - bv;\n const faceIndexA = this._indices[randomFaceIndex];\n const faceIndexB = this._indices[randomFaceIndex + 1];\n const faceIndexC = this._indices[randomFaceIndex + 2];\n const vertexA = TmpVectors.Vector3[0];\n const vertexB = TmpVectors.Vector3[1];\n const vertexC = TmpVectors.Vector3[2];\n const randomVertex = TmpVectors.Vector3[3];\n Vector3.FromArrayToRef(this._positions, faceIndexA * 3, vertexA);\n Vector3.FromArrayToRef(this._positions, faceIndexB * 3, vertexB);\n Vector3.FromArrayToRef(this._positions, faceIndexC * 3, vertexC);\n randomVertex.x = bu * vertexA.x + bv * vertexB.x + bw * vertexC.x;\n randomVertex.y = bu * vertexA.y + bv * vertexB.y + bw * vertexC.y;\n randomVertex.z = bu * vertexA.z + bv * vertexB.z + bw * vertexC.z;\n if (isLocal) {\n positionToUpdate.copyFromFloats(randomVertex.x, randomVertex.y, randomVertex.z);\n }\n else {\n Vector3.TransformCoordinatesFromFloatsToRef(randomVertex.x, randomVertex.y, randomVertex.z, worldMatrix, positionToUpdate);\n }\n if (this.useMeshNormalsForDirection && this._normals) {\n Vector3.FromArrayToRef(this._normals, faceIndexA * 3, vertexA);\n Vector3.FromArrayToRef(this._normals, faceIndexB * 3, vertexB);\n Vector3.FromArrayToRef(this._normals, faceIndexC * 3, vertexC);\n this._storedNormal.x = bu * vertexA.x + bv * vertexB.x + bw * vertexC.x;\n this._storedNormal.y = bu * vertexA.y + bv * vertexB.y + bw * vertexC.y;\n this._storedNormal.z = bu * vertexA.z + bv * vertexB.z + bw * vertexC.z;\n }\n }\n /**\n * Clones the current emitter and returns a copy of it\n * @returns the new emitter\n */\n clone() {\n const newOne = new MeshParticleEmitter(this.mesh);\n DeepCopier.DeepCopy(this, newOne);\n return newOne;\n }\n /**\n * Called by the GPUParticleSystem to setup the update shader\n * @param uboOrEffect defines the update shader\n */\n applyToShader(uboOrEffect) {\n uboOrEffect.setVector3(\"direction1\", this.direction1);\n uboOrEffect.setVector3(\"direction2\", this.direction2);\n }\n /**\n * Creates the structure of the ubo for this particle emitter\n * @param ubo ubo to create the structure for\n */\n buildUniformLayout(ubo) {\n ubo.addUniform(\"direction1\", 3);\n ubo.addUniform(\"direction2\", 3);\n }\n /**\n * Returns a string to use to update the GPU particles update shader\n * @returns a string containing the defines string\n */\n getEffectDefines() {\n return \"\";\n }\n /**\n * Returns the string \"BoxParticleEmitter\"\n * @returns a string containing the class name\n */\n getClassName() {\n return \"MeshParticleEmitter\";\n }\n /**\n * Serializes the particle system to a JSON object.\n * @returns the JSON object\n */\n serialize() {\n var _a;\n const serializationObject = {};\n serializationObject.type = this.getClassName();\n serializationObject.direction1 = this.direction1.asArray();\n serializationObject.direction2 = this.direction2.asArray();\n serializationObject.meshId = (_a = this.mesh) === null || _a === void 0 ? void 0 : _a.id;\n serializationObject.useMeshNormalsForDirection = this.useMeshNormalsForDirection;\n return serializationObject;\n }\n /**\n * Parse properties from a JSON object\n * @param serializationObject defines the JSON object\n * @param scene defines the hosting scene\n */\n parse(serializationObject, scene) {\n Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);\n Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);\n if (serializationObject.meshId && scene) {\n this.mesh = scene.getLastMeshById(serializationObject.meshId);\n }\n this.useMeshNormalsForDirection = serializationObject.useMeshNormalsForDirection;\n }\n}\n//# sourceMappingURL=meshParticleEmitter.js.map","export * from \"./boxParticleEmitter.js\";\nexport * from \"./coneParticleEmitter.js\";\nexport * from \"./cylinderParticleEmitter.js\";\nexport * from \"./hemisphericParticleEmitter.js\";\nexport * from \"./IParticleEmitterType.js\";\nexport * from \"./pointParticleEmitter.js\";\nexport * from \"./sphereParticleEmitter.js\";\nexport * from \"./customParticleEmitter.js\";\nexport * from \"./meshParticleEmitter.js\";\n//# sourceMappingURL=index.js.map","import { Vector2, Vector3 } from \"../Maths/math.vector.js\";\nimport { ImageProcessingConfigurationDefines } from \"../Materials/imageProcessingConfiguration.js\";\nimport { BoxParticleEmitter, PointParticleEmitter, HemisphericParticleEmitter, SphereParticleEmitter, SphereDirectedParticleEmitter, CylinderParticleEmitter, CylinderDirectedParticleEmitter, ConeParticleEmitter, } from \"../Particles/EmitterTypes/index.js\";\n\nimport { Color4 } from \"../Maths/math.color.js\";\nimport \"../Engines/Extensions/engine.dynamicBuffer.js\";\n/**\n * This represents the base class for particle system in Babylon.\n * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.\n * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.\n * @example https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro\n */\nexport class BaseParticleSystem {\n /**\n * Gets or sets a texture used to add random noise to particle positions\n */\n get noiseTexture() {\n return this._noiseTexture;\n }\n set noiseTexture(value) {\n if (this._noiseTexture === value) {\n return;\n }\n this._noiseTexture = value;\n this._reset();\n }\n /**\n * Gets or sets whether an animation sprite sheet is enabled or not on the particle system\n */\n get isAnimationSheetEnabled() {\n return this._isAnimationSheetEnabled;\n }\n set isAnimationSheetEnabled(value) {\n if (this._isAnimationSheetEnabled == value) {\n return;\n }\n this._isAnimationSheetEnabled = value;\n this._reset();\n }\n /**\n * Gets or sets a boolean enabling the use of logarithmic depth buffers, which is good for wide depth buffers.\n */\n get useLogarithmicDepth() {\n return this._useLogarithmicDepth;\n }\n set useLogarithmicDepth(value) {\n this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;\n }\n /**\n * Get hosting scene\n * @returns the scene\n */\n getScene() {\n return this._scene;\n }\n _hasTargetStopDurationDependantGradient() {\n return ((this._startSizeGradients && this._startSizeGradients.length > 0) ||\n (this._emitRateGradients && this._emitRateGradients.length > 0) ||\n (this._lifeTimeGradients && this._lifeTimeGradients.length > 0));\n }\n /**\n * Gets the current list of drag gradients.\n * You must use addDragGradient and removeDragGradient to update this list\n * @returns the list of drag gradients\n */\n getDragGradients() {\n return this._dragGradients;\n }\n /**\n * Gets the current list of limit velocity gradients.\n * You must use addLimitVelocityGradient and removeLimitVelocityGradient to update this list\n * @returns the list of limit velocity gradients\n */\n getLimitVelocityGradients() {\n return this._limitVelocityGradients;\n }\n /**\n * Gets the current list of color gradients.\n * You must use addColorGradient and removeColorGradient to update this list\n * @returns the list of color gradients\n */\n getColorGradients() {\n return this._colorGradients;\n }\n /**\n * Gets the current list of size gradients.\n * You must use addSizeGradient and removeSizeGradient to update this list\n * @returns the list of size gradients\n */\n getSizeGradients() {\n return this._sizeGradients;\n }\n /**\n * Gets the current list of color remap gradients.\n * You must use addColorRemapGradient and removeColorRemapGradient to update this list\n * @returns the list of color remap gradients\n */\n getColorRemapGradients() {\n return this._colorRemapGradients;\n }\n /**\n * Gets the current list of alpha remap gradients.\n * You must use addAlphaRemapGradient and removeAlphaRemapGradient to update this list\n * @returns the list of alpha remap gradients\n */\n getAlphaRemapGradients() {\n return this._alphaRemapGradients;\n }\n /**\n * Gets the current list of life time gradients.\n * You must use addLifeTimeGradient and removeLifeTimeGradient to update this list\n * @returns the list of life time gradients\n */\n getLifeTimeGradients() {\n return this._lifeTimeGradients;\n }\n /**\n * Gets the current list of angular speed gradients.\n * You must use addAngularSpeedGradient and removeAngularSpeedGradient to update this list\n * @returns the list of angular speed gradients\n */\n getAngularSpeedGradients() {\n return this._angularSpeedGradients;\n }\n /**\n * Gets the current list of velocity gradients.\n * You must use addVelocityGradient and removeVelocityGradient to update this list\n * @returns the list of velocity gradients\n */\n getVelocityGradients() {\n return this._velocityGradients;\n }\n /**\n * Gets the current list of start size gradients.\n * You must use addStartSizeGradient and removeStartSizeGradient to update this list\n * @returns the list of start size gradients\n */\n getStartSizeGradients() {\n return this._startSizeGradients;\n }\n /**\n * Gets the current list of emit rate gradients.\n * You must use addEmitRateGradient and removeEmitRateGradient to update this list\n * @returns the list of emit rate gradients\n */\n getEmitRateGradients() {\n return this._emitRateGradients;\n }\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n * This only works when particleEmitterTyps is a BoxParticleEmitter\n */\n get direction1() {\n if (this.particleEmitterType.direction1) {\n return this.particleEmitterType.direction1;\n }\n return Vector3.Zero();\n }\n set direction1(value) {\n if (this.particleEmitterType.direction1) {\n this.particleEmitterType.direction1 = value;\n }\n }\n /**\n * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.\n * This only works when particleEmitterTyps is a BoxParticleEmitter\n */\n get direction2() {\n if (this.particleEmitterType.direction2) {\n return this.particleEmitterType.direction2;\n }\n return Vector3.Zero();\n }\n set direction2(value) {\n if (this.particleEmitterType.direction2) {\n this.particleEmitterType.direction2 = value;\n }\n }\n /**\n * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.\n * This only works when particleEmitterTyps is a BoxParticleEmitter\n */\n get minEmitBox() {\n if (this.particleEmitterType.minEmitBox) {\n return this.particleEmitterType.minEmitBox;\n }\n return Vector3.Zero();\n }\n set minEmitBox(value) {\n if (this.particleEmitterType.minEmitBox) {\n this.particleEmitterType.minEmitBox = value;\n }\n }\n /**\n * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.\n * This only works when particleEmitterTyps is a BoxParticleEmitter\n */\n get maxEmitBox() {\n if (this.particleEmitterType.maxEmitBox) {\n return this.particleEmitterType.maxEmitBox;\n }\n return Vector3.Zero();\n }\n set maxEmitBox(value) {\n if (this.particleEmitterType.maxEmitBox) {\n this.particleEmitterType.maxEmitBox = value;\n }\n }\n /**\n * Gets or sets the billboard mode to use when isBillboardBased = true.\n * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED\n */\n get billboardMode() {\n return this._billboardMode;\n }\n set billboardMode(value) {\n if (this._billboardMode === value) {\n return;\n }\n this._billboardMode = value;\n this._reset();\n }\n /**\n * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction\n */\n get isBillboardBased() {\n return this._isBillboardBased;\n }\n set isBillboardBased(value) {\n if (this._isBillboardBased === value) {\n return;\n }\n this._isBillboardBased = value;\n this._reset();\n }\n /**\n * Gets the image processing configuration used either in this material.\n */\n get imageProcessingConfiguration() {\n return this._imageProcessingConfiguration;\n }\n /**\n * Sets the Default image processing configuration used either in the this material.\n *\n * If sets to null, the scene one is in use.\n */\n set imageProcessingConfiguration(value) {\n this._attachImageProcessingConfiguration(value);\n }\n /**\n * Attaches a new image processing configuration to the Standard Material.\n * @param configuration\n */\n _attachImageProcessingConfiguration(configuration) {\n if (configuration === this._imageProcessingConfiguration) {\n return;\n }\n // Pick the scene configuration if needed.\n if (!configuration && this._scene) {\n this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;\n }\n else {\n this._imageProcessingConfiguration = configuration;\n }\n }\n /** @internal */\n _reset() { }\n /**\n * @internal\n */\n _removeGradientAndTexture(gradient, gradients, texture) {\n if (!gradients) {\n return this;\n }\n let index = 0;\n for (const valueGradient of gradients) {\n if (valueGradient.gradient === gradient) {\n gradients.splice(index, 1);\n break;\n }\n index++;\n }\n if (texture) {\n texture.dispose();\n }\n return this;\n }\n /**\n * Instantiates a particle system.\n * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.\n * @param name The name of the particle system\n */\n constructor(name) {\n /**\n * List of animations used by the particle system.\n */\n this.animations = [];\n /**\n * The rendering group used by the Particle system to chose when to render.\n */\n this.renderingGroupId = 0;\n /**\n * The emitter represents the Mesh or position we are attaching the particle system to.\n */\n this.emitter = Vector3.Zero();\n /**\n * The maximum number of particles to emit per frame\n */\n this.emitRate = 10;\n /**\n * If you want to launch only a few particles at once, that can be done, as well.\n */\n this.manualEmitCount = -1;\n /**\n * The overall motion speed (0.01 is default update speed, faster updates = faster animation)\n */\n this.updateSpeed = 0.01;\n /**\n * The amount of time the particle system is running (depends of the overall update speed).\n */\n this.targetStopDuration = 0;\n /**\n * Specifies whether the particle system will be disposed once it reaches the end of the animation.\n */\n this.disposeOnStop = false;\n /**\n * Minimum power of emitting particles.\n */\n this.minEmitPower = 1;\n /**\n * Maximum power of emitting particles.\n */\n this.maxEmitPower = 1;\n /**\n * Minimum life time of emitting particles.\n */\n this.minLifeTime = 1;\n /**\n * Maximum life time of emitting particles.\n */\n this.maxLifeTime = 1;\n /**\n * Minimum Size of emitting particles.\n */\n this.minSize = 1;\n /**\n * Maximum Size of emitting particles.\n */\n this.maxSize = 1;\n /**\n * Minimum scale of emitting particles on X axis.\n */\n this.minScaleX = 1;\n /**\n * Maximum scale of emitting particles on X axis.\n */\n this.maxScaleX = 1;\n /**\n * Minimum scale of emitting particles on Y axis.\n */\n this.minScaleY = 1;\n /**\n * Maximum scale of emitting particles on Y axis.\n */\n this.maxScaleY = 1;\n /**\n * Gets or sets the minimal initial rotation in radians.\n */\n this.minInitialRotation = 0;\n /**\n * Gets or sets the maximal initial rotation in radians.\n */\n this.maxInitialRotation = 0;\n /**\n * Minimum angular speed of emitting particles (Z-axis rotation for each particle).\n */\n this.minAngularSpeed = 0;\n /**\n * Maximum angular speed of emitting particles (Z-axis rotation for each particle).\n */\n this.maxAngularSpeed = 0;\n /**\n * The layer mask we are rendering the particles through.\n */\n this.layerMask = 0x0fffffff;\n /**\n * This can help using your own shader to render the particle system.\n * The according effect will be created\n */\n this.customShader = null;\n /**\n * By default particle system starts as soon as they are created. This prevents the\n * automatic start to happen and let you decide when to start emitting particles.\n */\n this.preventAutoStart = false;\n /** @internal */\n this._wasDispatched = false;\n this._rootUrl = \"\";\n /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */\n this.noiseStrength = new Vector3(10, 10, 10);\n /**\n * Callback triggered when the particle animation is ending.\n */\n this.onAnimationEnd = null;\n /**\n * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.\n */\n this.blendMode = BaseParticleSystem.BLENDMODE_ONEONE;\n /**\n * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls\n * to override the particles.\n */\n this.forceDepthWrite = false;\n /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */\n this.preWarmCycles = 0;\n /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */\n this.preWarmStepOffset = 1;\n /**\n * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)\n */\n this.spriteCellChangeSpeed = 1;\n /**\n * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display\n */\n this.startSpriteCellID = 0;\n /**\n * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display\n */\n this.endSpriteCellID = 0;\n /**\n * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use\n */\n this.spriteCellWidth = 0;\n /**\n * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use\n */\n this.spriteCellHeight = 0;\n /**\n * If using a spritesheet (isAnimationSheetEnabled), defines wether the sprite animation is looping\n */\n this.spriteCellLoop = true;\n /**\n * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID\n */\n this.spriteRandomStartCell = false;\n /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */\n this.translationPivot = new Vector2(0, 0);\n /**\n * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called\n */\n this.beginAnimationOnStart = false;\n /**\n * Gets or sets the frame to start the animation from when beginAnimationOnStart is true\n */\n this.beginAnimationFrom = 0;\n /**\n * Gets or sets the frame to end the animation on when beginAnimationOnStart is true\n */\n this.beginAnimationTo = 60;\n /**\n * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true\n */\n this.beginAnimationLoop = false;\n /**\n * Gets or sets a world offset applied to all particles\n */\n this.worldOffset = new Vector3(0, 0, 0);\n this._useLogarithmicDepth = false;\n /**\n * You can use gravity if you want to give an orientation to your particles.\n */\n this.gravity = Vector3.Zero();\n this._colorGradients = null;\n this._sizeGradients = null;\n this._lifeTimeGradients = null;\n this._angularSpeedGradients = null;\n this._velocityGradients = null;\n this._limitVelocityGradients = null;\n this._dragGradients = null;\n this._emitRateGradients = null;\n this._startSizeGradients = null;\n this._rampGradients = null;\n this._colorRemapGradients = null;\n this._alphaRemapGradients = null;\n /**\n * Defines the delay in milliseconds before starting the system (0 by default)\n */\n this.startDelay = 0;\n /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */\n this.limitVelocityDamping = 0.4;\n /**\n * Random color of each particle after it has been emitted, between color1 and color2 vectors\n */\n this.color1 = new Color4(1.0, 1.0, 1.0, 1.0);\n /**\n * Random color of each particle after it has been emitted, between color1 and color2 vectors\n */\n this.color2 = new Color4(1.0, 1.0, 1.0, 1.0);\n /**\n * Color the particle will have at the end of its lifetime\n */\n this.colorDead = new Color4(0, 0, 0, 1.0);\n /**\n * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel\n */\n this.textureMask = new Color4(1.0, 1.0, 1.0, 1.0);\n /** @internal */\n this._isSubEmitter = false;\n /** @internal */\n this._billboardMode = 7;\n /** @internal */\n this._isBillboardBased = true;\n /**\n * Local cache of defines for image processing.\n */\n this._imageProcessingConfigurationDefines = new ImageProcessingConfigurationDefines();\n this.id = name;\n this.name = name;\n }\n /**\n * Creates a Point Emitter for the particle system (emits directly from the emitter position)\n * @param direction1 Particles are emitted between the direction1 and direction2 from within the box\n * @param direction2 Particles are emitted between the direction1 and direction2 from within the box\n * @returns the emitter\n */\n createPointEmitter(direction1, direction2) {\n const particleEmitter = new PointParticleEmitter();\n particleEmitter.direction1 = direction1;\n particleEmitter.direction2 = direction2;\n this.particleEmitterType = particleEmitter;\n return particleEmitter;\n }\n /**\n * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)\n * @param radius The radius of the hemisphere to emit from\n * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius\n * @returns the emitter\n */\n createHemisphericEmitter(radius = 1, radiusRange = 1) {\n const particleEmitter = new HemisphericParticleEmitter(radius, radiusRange);\n this.particleEmitterType = particleEmitter;\n return particleEmitter;\n }\n /**\n * Creates a Sphere Emitter for the particle system (emits along the sphere radius)\n * @param radius The radius of the sphere to emit from\n * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius\n * @returns the emitter\n */\n createSphereEmitter(radius = 1, radiusRange = 1) {\n const particleEmitter = new SphereParticleEmitter(radius, radiusRange);\n this.particleEmitterType = particleEmitter;\n return particleEmitter;\n }\n /**\n * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)\n * @param radius The radius of the sphere to emit from\n * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere\n * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere\n * @returns the emitter\n */\n createDirectedSphereEmitter(radius = 1, direction1 = new Vector3(0, 1.0, 0), direction2 = new Vector3(0, 1.0, 0)) {\n const particleEmitter = new SphereDirectedParticleEmitter(radius, direction1, direction2);\n this.particleEmitterType = particleEmitter;\n return particleEmitter;\n }\n /**\n * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)\n * @param radius The radius of the emission cylinder\n * @param height The height of the emission cylinder\n * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius\n * @param directionRandomizer How much to randomize the particle direction [0-1]\n * @returns the emitter\n */\n createCylinderEmitter(radius = 1, height = 1, radiusRange = 1, directionRandomizer = 0) {\n const particleEmitter = new CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);\n this.particleEmitterType = particleEmitter;\n return particleEmitter;\n }\n /**\n * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)\n * @param radius The radius of the cylinder to emit from\n * @param height The height of the emission cylinder\n * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)\n * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder\n * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder\n * @returns the emitter\n */\n createDirectedCylinderEmitter(radius = 1, height = 1, radiusRange = 1, direction1 = new Vector3(0, 1.0, 0), direction2 = new Vector3(0, 1.0, 0)) {\n const particleEmitter = new CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);\n this.particleEmitterType = particleEmitter;\n return particleEmitter;\n }\n /**\n * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)\n * @param radius The radius of the cone to emit from\n * @param angle The base angle of the cone\n * @returns the emitter\n */\n createConeEmitter(radius = 1, angle = Math.PI / 4) {\n const particleEmitter = new ConeParticleEmitter(radius, angle);\n this.particleEmitterType = particleEmitter;\n return particleEmitter;\n }\n /**\n * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)\n * @param direction1 Particles are emitted between the direction1 and direction2 from within the box\n * @param direction2 Particles are emitted between the direction1 and direction2 from within the box\n * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox\n * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox\n * @returns the emitter\n */\n createBoxEmitter(direction1, direction2, minEmitBox, maxEmitBox) {\n const particleEmitter = new BoxParticleEmitter();\n this.particleEmitterType = particleEmitter;\n this.direction1 = direction1;\n this.direction2 = direction2;\n this.minEmitBox = minEmitBox;\n this.maxEmitBox = maxEmitBox;\n return particleEmitter;\n }\n}\n/**\n * Source color is added to the destination color without alpha affecting the result\n */\nBaseParticleSystem.BLENDMODE_ONEONE = 0;\n/**\n * Blend current color and particle color using particle’s alpha\n */\nBaseParticleSystem.BLENDMODE_STANDARD = 1;\n/**\n * Add current color and particle color multiplied by particle’s alpha\n */\nBaseParticleSystem.BLENDMODE_ADD = 2;\n/**\n * Multiply current color with particle color\n */\nBaseParticleSystem.BLENDMODE_MULTIPLY = 3;\n/**\n * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha\n */\nBaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;\n//# sourceMappingURL=baseParticleSystem.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to expand a Color3/4 into 4 outputs (one for each component)\n */\nexport class ColorSplitterBlock extends NodeMaterialBlock {\n /**\n * Create a new ColorSplitterBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"rgba\", NodeMaterialBlockConnectionPointTypes.Color4, true);\n this.registerInput(\"rgb \", NodeMaterialBlockConnectionPointTypes.Color3, true);\n this.registerOutput(\"rgb\", NodeMaterialBlockConnectionPointTypes.Color3);\n this.registerOutput(\"r\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"g\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"b\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"a\", NodeMaterialBlockConnectionPointTypes.Float);\n this.inputsAreExclusive = true;\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ColorSplitterBlock\";\n }\n /**\n * Gets the rgba component (input)\n */\n get rgba() {\n return this._inputs[0];\n }\n /**\n * Gets the rgb component (input)\n */\n get rgbIn() {\n return this._inputs[1];\n }\n /**\n * Gets the rgb component (output)\n */\n get rgbOut() {\n return this._outputs[0];\n }\n /**\n * Gets the r component (output)\n */\n get r() {\n return this._outputs[1];\n }\n /**\n * Gets the g component (output)\n */\n get g() {\n return this._outputs[2];\n }\n /**\n * Gets the b component (output)\n */\n get b() {\n return this._outputs[3];\n }\n /**\n * Gets the a component (output)\n */\n get a() {\n return this._outputs[4];\n }\n _inputRename(name) {\n if (name === \"rgb \") {\n return \"rgbIn\";\n }\n return name;\n }\n _outputRename(name) {\n if (name === \"rgb\") {\n return \"rgbOut\";\n }\n return name;\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const input = this.rgba.isConnected ? this.rgba : this.rgbIn;\n if (!input.isConnected) {\n return;\n }\n const rgbOutput = this._outputs[0];\n const rOutput = this._outputs[1];\n const gOutput = this._outputs[2];\n const bOutput = this._outputs[3];\n const aOutput = this._outputs[4];\n if (rgbOutput.hasEndpoints) {\n state.compilationString += this._declareOutput(rgbOutput, state) + ` = ${input.associatedVariableName}.rgb;\\r\\n`;\n }\n if (rOutput.hasEndpoints) {\n state.compilationString += this._declareOutput(rOutput, state) + ` = ${input.associatedVariableName}.r;\\r\\n`;\n }\n if (gOutput.hasEndpoints) {\n state.compilationString += this._declareOutput(gOutput, state) + ` = ${input.associatedVariableName}.g;\\r\\n`;\n }\n if (bOutput.hasEndpoints) {\n state.compilationString += this._declareOutput(bOutput, state) + ` = ${input.associatedVariableName}.b;\\r\\n`;\n }\n if (aOutput.hasEndpoints) {\n state.compilationString += this._declareOutput(aOutput, state) + ` = ${input.associatedVariableName}.a;\\r\\n`;\n }\n return this;\n }\n}\nRegisterClass(\"BABYLON.ColorSplitterBlock\", ColorSplitterBlock);\n//# sourceMappingURL=colorSplitterBlock.js.map","import { InternalTexture, InternalTextureSource } from \"../../Materials/Textures/internalTexture.js\";\nimport { Logger } from \"../../Misc/logger.js\";\n\nimport { ThinEngine } from \"../thinEngine.js\";\nThinEngine.prototype.createRenderTargetCubeTexture = function (size, options) {\n const rtWrapper = this._createHardwareRenderTargetWrapper(false, true, size);\n const fullOptions = Object.assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: 0, samplingMode: 3, format: 5 }, options);\n fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;\n if (fullOptions.type === 1 && !this._caps.textureFloatLinearFiltering) {\n // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE\n fullOptions.samplingMode = 1;\n }\n else if (fullOptions.type === 2 && !this._caps.textureHalfFloatLinearFiltering) {\n // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE\n fullOptions.samplingMode = 1;\n }\n const gl = this._gl;\n const texture = new InternalTexture(this, InternalTextureSource.RenderTarget);\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);\n const filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);\n if (fullOptions.type === 1 && !this._caps.textureFloat) {\n fullOptions.type = 0;\n Logger.Warn(\"Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type\");\n }\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n for (let face = 0; face < 6; face++) {\n gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);\n }\n // Create the framebuffer\n const framebuffer = gl.createFramebuffer();\n this._bindUnboundFramebuffer(framebuffer);\n rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);\n // MipMaps\n if (fullOptions.generateMipMaps) {\n gl.generateMipmap(gl.TEXTURE_CUBE_MAP);\n }\n // Unbind\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n this._bindUnboundFramebuffer(null);\n rtWrapper._framebuffer = framebuffer;\n rtWrapper._generateDepthBuffer = fullOptions.generateDepthBuffer;\n rtWrapper._generateStencilBuffer = fullOptions.generateStencilBuffer;\n texture.width = size;\n texture.height = size;\n texture.isReady = true;\n texture.isCube = true;\n texture.samples = 1;\n texture.generateMipMaps = fullOptions.generateMipMaps;\n texture.samplingMode = fullOptions.samplingMode;\n texture.type = fullOptions.type;\n texture.format = fullOptions.format;\n this._internalTexturesCache.push(texture);\n rtWrapper.setTextures(texture);\n return rtWrapper;\n};\n//# sourceMappingURL=engine.renderTargetCube.js.map","import { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Viewport } from \"../Maths/math.viewport.js\";\n\nimport { Observable } from \"../Misc/observable.js\";\nimport { Effect } from \"./effect.js\";\nimport { DrawWrapper } from \"./drawWrapper.js\";\n// Prevents ES6 Crash if not imported.\nimport \"../Shaders/postprocess.vertex.js\";\n// Fullscreen quad buffers by default.\nconst defaultOptions = {\n positions: [1, 1, -1, 1, -1, -1, 1, -1],\n indices: [0, 1, 2, 0, 2, 3],\n};\n/**\n * Helper class to render one or more effects.\n * You can access the previous rendering in your shader by declaring a sampler named textureSampler\n */\nexport class EffectRenderer {\n /**\n * Creates an effect renderer\n * @param engine the engine to use for rendering\n * @param options defines the options of the effect renderer\n */\n constructor(engine, options = defaultOptions) {\n var _a, _b;\n this._fullscreenViewport = new Viewport(0, 0, 1, 1);\n const positions = (_a = options.positions) !== null && _a !== void 0 ? _a : defaultOptions.positions;\n const indices = (_b = options.indices) !== null && _b !== void 0 ? _b : defaultOptions.indices;\n this.engine = engine;\n this._vertexBuffers = {\n [VertexBuffer.PositionKind]: new VertexBuffer(engine, positions, VertexBuffer.PositionKind, false, false, 2),\n };\n this._indexBuffer = engine.createIndexBuffer(indices);\n this._onContextRestoredObserver = engine.onContextRestoredObservable.add(() => {\n this._indexBuffer = engine.createIndexBuffer(indices);\n for (const key in this._vertexBuffers) {\n const vertexBuffer = this._vertexBuffers[key];\n vertexBuffer._rebuild();\n }\n });\n }\n /**\n * Sets the current viewport in normalized coordinates 0-1\n * @param viewport Defines the viewport to set (defaults to 0 0 1 1)\n */\n setViewport(viewport = this._fullscreenViewport) {\n this.engine.setViewport(viewport);\n }\n /**\n * Binds the embedded attributes buffer to the effect.\n * @param effect Defines the effect to bind the attributes for\n */\n bindBuffers(effect) {\n this.engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);\n }\n /**\n * Sets the current effect wrapper to use during draw.\n * The effect needs to be ready before calling this api.\n * This also sets the default full screen position attribute.\n * @param effectWrapper Defines the effect to draw with\n */\n applyEffectWrapper(effectWrapper) {\n this.engine.setState(true);\n this.engine.depthCullingState.depthTest = false;\n this.engine.stencilState.stencilTest = false;\n this.engine.enableEffect(effectWrapper._drawWrapper);\n this.bindBuffers(effectWrapper.effect);\n effectWrapper.onApplyObservable.notifyObservers({});\n }\n /**\n * Restores engine states\n */\n restoreStates() {\n this.engine.depthCullingState.depthTest = true;\n this.engine.stencilState.stencilTest = true;\n }\n /**\n * Draws a full screen quad.\n */\n draw() {\n this.engine.drawElementsType(0, 0, 6);\n }\n _isRenderTargetTexture(texture) {\n return texture.renderTarget !== undefined;\n }\n /**\n * renders one or more effects to a specified texture\n * @param effectWrapper the effect to renderer\n * @param outputTexture texture to draw to, if null it will render to the screen.\n */\n render(effectWrapper, outputTexture = null) {\n // Ensure effect is ready\n if (!effectWrapper.effect.isReady()) {\n return;\n }\n // Reset state\n this.setViewport();\n const out = outputTexture === null ? null : this._isRenderTargetTexture(outputTexture) ? outputTexture.renderTarget : outputTexture;\n if (out) {\n this.engine.bindFramebuffer(out);\n }\n this.applyEffectWrapper(effectWrapper);\n this.draw();\n if (out) {\n this.engine.unBindFramebuffer(out);\n }\n this.restoreStates();\n }\n /**\n * Disposes of the effect renderer\n */\n dispose() {\n const vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];\n if (vertexBuffer) {\n vertexBuffer.dispose();\n delete this._vertexBuffers[VertexBuffer.PositionKind];\n }\n if (this._indexBuffer) {\n this.engine._releaseBuffer(this._indexBuffer);\n }\n if (this._onContextRestoredObserver) {\n this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver);\n this._onContextRestoredObserver = null;\n }\n }\n}\n/**\n * Wraps an effect to be used for rendering\n */\nexport class EffectWrapper {\n /**\n * The underlying effect\n */\n get effect() {\n return this._drawWrapper.effect;\n }\n set effect(effect) {\n this._drawWrapper.effect = effect;\n }\n /**\n * Creates an effect to be renderer\n * @param creationOptions options to create the effect\n */\n constructor(creationOptions) {\n /**\n * Event that is fired right before the effect is drawn (should be used to update uniforms)\n */\n this.onApplyObservable = new Observable();\n let effectCreationOptions;\n const uniformNames = creationOptions.uniformNames || [];\n if (creationOptions.vertexShader) {\n effectCreationOptions = {\n fragmentSource: creationOptions.fragmentShader,\n vertexSource: creationOptions.vertexShader,\n spectorName: creationOptions.name || \"effectWrapper\",\n };\n }\n else {\n // Default scale to use in post process vertex shader.\n uniformNames.push(\"scale\");\n effectCreationOptions = {\n fragmentSource: creationOptions.fragmentShader,\n vertex: \"postprocess\",\n spectorName: creationOptions.name || \"effectWrapper\",\n };\n // Sets the default scale to identity for the post process vertex shader.\n this.onApplyObservable.add(() => {\n this.effect.setFloat2(\"scale\", 1, 1);\n });\n }\n const defines = creationOptions.defines ? creationOptions.defines.join(\"\\n\") : \"\";\n this._drawWrapper = new DrawWrapper(creationOptions.engine);\n if (creationOptions.useShaderStore) {\n effectCreationOptions.fragment = effectCreationOptions.fragmentSource;\n if (!effectCreationOptions.vertex) {\n effectCreationOptions.vertex = effectCreationOptions.vertexSource;\n }\n delete effectCreationOptions.fragmentSource;\n delete effectCreationOptions.vertexSource;\n this.effect = creationOptions.engine.createEffect(effectCreationOptions, creationOptions.attributeNames || [\"position\"], uniformNames, creationOptions.samplerNames, defines, undefined, creationOptions.onCompiled, undefined, undefined, creationOptions.shaderLanguage);\n }\n else {\n this.effect = new Effect(effectCreationOptions, creationOptions.attributeNames || [\"position\"], uniformNames, creationOptions.samplerNames, creationOptions.engine, defines, undefined, creationOptions.onCompiled, undefined, undefined, undefined, creationOptions.shaderLanguage);\n this._onContextRestoredObserver = creationOptions.engine.onContextRestoredObservable.add(() => {\n this.effect._pipelineContext = null; // because _prepareEffect will try to dispose this pipeline before recreating it and that would lead to webgl errors\n this.effect._wasPreviouslyReady = false;\n this.effect._prepareEffect();\n });\n }\n }\n /**\n * Disposes of the effect wrapper\n */\n dispose() {\n if (this._onContextRestoredObserver) {\n this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver);\n this._onContextRestoredObserver = null;\n }\n this.effect.dispose();\n }\n}\n//# sourceMappingURL=effectRenderer.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"passPixelShader\";\nconst shader = `varying vec2 vUV;\runiform sampler2D textureSampler;\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \r{\rgl_FragColor=texture2D(textureSampler,vUV);\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const passPixelShader = { name, shader };\n//# sourceMappingURL=pass.fragment.js.map","import { ThinEngine } from \"../Engines/thinEngine.js\";\n\nimport { EffectRenderer, EffectWrapper } from \"../Materials/effectRenderer.js\";\nimport { Tools } from \"./tools.js\";\nimport { passPixelShader } from \"../Shaders/pass.fragment.js\";\nimport { Scalar } from \"../Maths/math.scalar.js\";\n/**\n * Class containing a set of static utilities functions to dump data from a canvas\n */\nexport class DumpTools {\n static _CreateDumpRenderer() {\n if (!DumpTools._DumpToolsEngine) {\n const canvas = new OffscreenCanvas(100, 100); // will be resized later\n const engine = new ThinEngine(canvas, false, {\n preserveDrawingBuffer: true,\n depth: false,\n stencil: false,\n alpha: true,\n premultipliedAlpha: false,\n antialias: false,\n failIfMajorPerformanceCaveat: false,\n });\n engine.getCaps().parallelShaderCompile = undefined;\n const renderer = new EffectRenderer(engine);\n const wrapper = new EffectWrapper({\n engine,\n name: passPixelShader.name,\n fragmentShader: passPixelShader.shader,\n samplerNames: [\"textureSampler\"],\n });\n DumpTools._DumpToolsEngine = {\n canvas,\n engine,\n renderer,\n wrapper,\n };\n }\n return DumpTools._DumpToolsEngine;\n }\n /**\n * Dumps the current bound framebuffer\n * @param width defines the rendering width\n * @param height defines the rendering height\n * @param engine defines the hosting engine\n * @param successCallback defines the callback triggered once the data are available\n * @param mimeType defines the mime type of the result\n * @param fileName defines the filename to download. If present, the result will automatically be downloaded\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n * @returns a void promise\n */\n static async DumpFramebuffer(width, height, engine, successCallback, mimeType = \"image/png\", fileName, quality) {\n // Read the contents of the framebuffer\n const bufferView = await engine.readPixels(0, 0, width, height);\n const data = new Uint8Array(bufferView.buffer);\n DumpTools.DumpData(width, height, data, successCallback, mimeType, fileName, true, undefined, quality);\n }\n /**\n * Dumps an array buffer\n * @param width defines the rendering width\n * @param height defines the rendering height\n * @param data the data array\n * @param mimeType defines the mime type of the result\n * @param fileName defines the filename to download. If present, the result will automatically be downloaded\n * @param invertY true to invert the picture in the Y dimension\n * @param toArrayBuffer true to convert the data to an ArrayBuffer (encoded as `mimeType`) instead of a base64 string\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n * @returns a promise that resolve to the final data\n */\n static DumpDataAsync(width, height, data, mimeType = \"image/png\", fileName, invertY = false, toArrayBuffer = false, quality) {\n return new Promise((resolve) => {\n DumpTools.DumpData(width, height, data, (result) => resolve(result), mimeType, fileName, invertY, toArrayBuffer, quality);\n });\n }\n /**\n * Dumps an array buffer\n * @param width defines the rendering width\n * @param height defines the rendering height\n * @param data the data array\n * @param successCallback defines the callback triggered once the data are available\n * @param mimeType defines the mime type of the result\n * @param fileName defines the filename to download. If present, the result will automatically be downloaded\n * @param invertY true to invert the picture in the Y dimension\n * @param toArrayBuffer true to convert the data to an ArrayBuffer (encoded as `mimeType`) instead of a base64 string\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n */\n static DumpData(width, height, data, successCallback, mimeType = \"image/png\", fileName, invertY = false, toArrayBuffer = false, quality) {\n const renderer = DumpTools._CreateDumpRenderer();\n renderer.engine.setSize(width, height, true);\n // Convert if data are float32\n if (data instanceof Float32Array) {\n const data2 = new Uint8Array(data.length);\n let n = data.length;\n while (n--) {\n const v = data[n];\n data2[n] = Math.round(Scalar.Clamp(v) * 255);\n }\n data = data2;\n }\n // Create the image\n const texture = renderer.engine.createRawTexture(data, width, height, 5, false, !invertY, 1);\n renderer.renderer.setViewport();\n renderer.renderer.applyEffectWrapper(renderer.wrapper);\n renderer.wrapper.effect._bindTexture(\"textureSampler\", texture);\n renderer.renderer.draw();\n if (toArrayBuffer) {\n Tools.ToBlob(renderer.canvas, (blob) => {\n const fileReader = new FileReader();\n fileReader.onload = (event) => {\n const arrayBuffer = event.target.result;\n if (successCallback) {\n successCallback(arrayBuffer);\n }\n };\n fileReader.readAsArrayBuffer(blob);\n }, mimeType, quality);\n }\n else {\n Tools.EncodeScreenshotCanvasData(renderer.canvas, successCallback, mimeType, fileName, quality);\n }\n texture.dispose();\n }\n /**\n * Dispose the dump tools associated resources\n */\n static Dispose() {\n if (DumpTools._DumpToolsEngine) {\n DumpTools._DumpToolsEngine.wrapper.dispose();\n DumpTools._DumpToolsEngine.renderer.dispose();\n DumpTools._DumpToolsEngine.engine.dispose();\n }\n DumpTools._DumpToolsEngine = null;\n }\n}\n/**\n * This will be executed automatically for UMD and es5.\n * If esm dev wants the side effects to execute they will have to run it manually\n * Once we build native modules those need to be exported.\n * @internal\n */\nconst initSideEffects = () => {\n // References the dependencies.\n Tools.DumpData = DumpTools.DumpData;\n Tools.DumpDataAsync = DumpTools.DumpDataAsync;\n Tools.DumpFramebuffer = DumpTools.DumpFramebuffer;\n};\ninitSideEffects();\n//# sourceMappingURL=dumpTools.js.map","import { Observable } from \"../../Misc/observable.js\";\nimport { Matrix, Vector3 } from \"../../Maths/math.vector.js\";\nimport { Texture } from \"../../Materials/Textures/texture.js\";\nimport { PostProcessManager } from \"../../PostProcesses/postProcessManager.js\";\nimport { RenderingManager } from \"../../Rendering/renderingManager.js\";\n\nimport \"../../Engines/Extensions/engine.renderTarget.js\";\nimport \"../../Engines/Extensions/engine.renderTargetCube.js\";\nimport { Engine } from \"../../Engines/engine.js\";\nimport { _ObserveArray } from \"../../Misc/arrayTools.js\";\nimport { DumpTools } from \"../../Misc/dumpTools.js\";\n/**\n * This Helps creating a texture that will be created from a camera in your scene.\n * It is basically a dynamic texture that could be used to create special effects for instance.\n * Actually, It is the base of lot of effects in the framework like post process, shadows, effect layers and rendering pipelines...\n */\nexport class RenderTargetTexture extends Texture {\n /**\n * Use this list to define the list of mesh you want to render.\n */\n get renderList() {\n return this._renderList;\n }\n set renderList(value) {\n if (this._unObserveRenderList) {\n this._unObserveRenderList();\n this._unObserveRenderList = null;\n }\n if (value) {\n this._unObserveRenderList = _ObserveArray(value, this._renderListHasChanged);\n }\n this._renderList = value;\n }\n /**\n * Post-processes for this render target\n */\n get postProcesses() {\n return this._postProcesses;\n }\n get _prePassEnabled() {\n return !!this._prePassRenderTarget && this._prePassRenderTarget.enabled;\n }\n /**\n * Set a after unbind callback in the texture.\n * This has been kept for backward compatibility and use of onAfterUnbindObservable is recommended.\n */\n set onAfterUnbind(callback) {\n if (this._onAfterUnbindObserver) {\n this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);\n }\n this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);\n }\n /**\n * Set a before render callback in the texture.\n * This has been kept for backward compatibility and use of onBeforeRenderObservable is recommended.\n */\n set onBeforeRender(callback) {\n if (this._onBeforeRenderObserver) {\n this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);\n }\n this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);\n }\n /**\n * Set a after render callback in the texture.\n * This has been kept for backward compatibility and use of onAfterRenderObservable is recommended.\n */\n set onAfterRender(callback) {\n if (this._onAfterRenderObserver) {\n this.onAfterRenderObservable.remove(this._onAfterRenderObserver);\n }\n this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);\n }\n /**\n * Set a clear callback in the texture.\n * This has been kept for backward compatibility and use of onClearObservable is recommended.\n */\n set onClear(callback) {\n if (this._onClearObserver) {\n this.onClearObservable.remove(this._onClearObserver);\n }\n this._onClearObserver = this.onClearObservable.add(callback);\n }\n /**\n * Gets the render pass ids used by the render target texture. For a single render target the array length will be 1, for a cube texture it will be 6 and for\n * a 2D texture array it will return an array of ids the size of the 2D texture array\n */\n get renderPassIds() {\n return this._renderPassIds;\n }\n /**\n * Gets the current value of the refreshId counter\n */\n get currentRefreshId() {\n return this._currentRefreshId;\n }\n /**\n * Sets a specific material to be used to render a mesh/a list of meshes in this render target texture\n * @param mesh mesh or array of meshes\n * @param material material or array of materials to use for this render pass. If undefined is passed, no specific material will be used but the regular material instead (mesh.material). It's possible to provide an array of materials to use a different material for each rendering in the case of a cube texture (6 rendering) and a 2D texture array (as many rendering as the length of the array)\n */\n setMaterialForRendering(mesh, material) {\n let meshes;\n if (!Array.isArray(mesh)) {\n meshes = [mesh];\n }\n else {\n meshes = mesh;\n }\n for (let j = 0; j < meshes.length; ++j) {\n for (let i = 0; i < this._renderPassIds.length; ++i) {\n meshes[j].setMaterialForRenderPass(this._renderPassIds[i], material !== undefined ? (Array.isArray(material) ? material[i] : material) : undefined);\n }\n }\n }\n /**\n * Define if the texture has multiple draw buffers or if false a single draw buffer.\n */\n get isMulti() {\n var _a, _b;\n return (_b = (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.isMulti) !== null && _b !== void 0 ? _b : false;\n }\n /**\n * Gets render target creation options that were used.\n */\n get renderTargetOptions() {\n return this._renderTargetOptions;\n }\n /**\n * Gets the render target wrapper associated with this render target\n */\n get renderTarget() {\n return this._renderTarget;\n }\n _onRatioRescale() {\n if (this._sizeRatio) {\n this.resize(this._initialSizeParameter);\n }\n }\n /**\n * Gets or sets the size of the bounding box associated with the texture (when in cube mode)\n * When defined, the cubemap will switch to local mode\n * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity\n * @example https://www.babylonjs-playground.com/#RNASML\n */\n set boundingBoxSize(value) {\n if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {\n return;\n }\n this._boundingBoxSize = value;\n const scene = this.getScene();\n if (scene) {\n scene.markAllMaterialsAsDirty(1);\n }\n }\n get boundingBoxSize() {\n return this._boundingBoxSize;\n }\n /**\n * In case the RTT has been created with a depth texture, get the associated\n * depth texture.\n * Otherwise, return null.\n */\n get depthStencilTexture() {\n var _a, _b;\n return (_b = (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a._depthStencilTexture) !== null && _b !== void 0 ? _b : null;\n }\n /** @internal */\n constructor(name, size, scene, generateMipMaps = false, doNotChangeAspectRatio = true, type = 0, isCube = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, generateDepthBuffer = true, generateStencilBuffer = false, isMulti = false, format = 5, delayAllocation = false, samples, creationFlags, noColorAttachment = false, useSRGBBuffer = false) {\n var _a, _b, _c, _d, _e, _f;\n let colorAttachment = undefined;\n if (typeof generateMipMaps === \"object\") {\n const options = generateMipMaps;\n generateMipMaps = !!options.generateMipMaps;\n doNotChangeAspectRatio = (_a = options.doNotChangeAspectRatio) !== null && _a !== void 0 ? _a : true;\n type = (_b = options.type) !== null && _b !== void 0 ? _b : 0;\n isCube = !!options.isCube;\n samplingMode = (_c = options.samplingMode) !== null && _c !== void 0 ? _c : Texture.TRILINEAR_SAMPLINGMODE;\n generateDepthBuffer = (_d = options.generateDepthBuffer) !== null && _d !== void 0 ? _d : true;\n generateStencilBuffer = !!options.generateStencilBuffer;\n isMulti = !!options.isMulti;\n format = (_e = options.format) !== null && _e !== void 0 ? _e : 5;\n delayAllocation = !!options.delayAllocation;\n samples = options.samples;\n creationFlags = options.creationFlags;\n noColorAttachment = !!options.noColorAttachment;\n useSRGBBuffer = !!options.useSRGBBuffer;\n colorAttachment = options.colorAttachment;\n }\n super(null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format);\n this._unObserveRenderList = null;\n this._renderListHasChanged = (_functionName, previousLength) => {\n var _a;\n const newLength = this._renderList ? this._renderList.length : 0;\n if ((previousLength === 0 && newLength > 0) || newLength === 0) {\n (_a = this.getScene()) === null || _a === void 0 ? void 0 : _a.meshes.forEach((mesh) => {\n mesh._markSubMeshesAsLightDirty();\n });\n }\n };\n /**\n * Define if particles should be rendered in your texture.\n */\n this.renderParticles = true;\n /**\n * Define if sprites should be rendered in your texture.\n */\n this.renderSprites = false;\n /**\n * Force checking the layerMask property even if a custom list of meshes is provided (ie. if renderList is not undefined)\n */\n this.forceLayerMaskCheck = false;\n /**\n * Define if the camera viewport should be respected while rendering the texture or if the render should be done to the entire texture.\n */\n this.ignoreCameraViewport = false;\n /**\n * An event triggered when the texture is unbind.\n */\n this.onBeforeBindObservable = new Observable();\n /**\n * An event triggered when the texture is unbind.\n */\n this.onAfterUnbindObservable = new Observable();\n /**\n * An event triggered before rendering the texture\n */\n this.onBeforeRenderObservable = new Observable();\n /**\n * An event triggered after rendering the texture\n */\n this.onAfterRenderObservable = new Observable();\n /**\n * An event triggered after the texture clear\n */\n this.onClearObservable = new Observable();\n /**\n * An event triggered when the texture is resized.\n */\n this.onResizeObservable = new Observable();\n /** @internal */\n this._cleared = false;\n /**\n * Skip the initial clear of the rtt at the beginning of the frame render loop\n */\n this.skipInitialClear = false;\n this._currentRefreshId = -1;\n this._refreshRate = 1;\n this._samples = 1;\n this._canRescale = true;\n this._renderTarget = null;\n /**\n * Gets or sets the center of the bounding box associated with the texture (when in cube mode)\n * It must define where the camera used to render the texture is set\n */\n this.boundingBoxPosition = Vector3.Zero();\n scene = this.getScene();\n if (!scene) {\n return;\n }\n const engine = this.getScene().getEngine();\n this._coordinatesMode = Texture.PROJECTION_MODE;\n this.renderList = new Array();\n this.name = name;\n this.isRenderTarget = true;\n this._initialSizeParameter = size;\n this._renderPassIds = [];\n this._isCubeData = isCube;\n this._processSizeParameter(size);\n this.renderPassId = this._renderPassIds[0];\n this._resizeObserver = engine.onResizeObservable.add(() => { });\n this._generateMipMaps = generateMipMaps ? true : false;\n this._doNotChangeAspectRatio = doNotChangeAspectRatio;\n // Rendering groups\n this._renderingManager = new RenderingManager(scene);\n this._renderingManager._useSceneAutoClearSetup = true;\n if (isMulti) {\n return;\n }\n this._renderTargetOptions = {\n generateMipMaps: generateMipMaps,\n type: type,\n format: (_f = this._format) !== null && _f !== void 0 ? _f : undefined,\n samplingMode: this.samplingMode,\n generateDepthBuffer: generateDepthBuffer,\n generateStencilBuffer: generateStencilBuffer,\n samples,\n creationFlags,\n noColorAttachment: noColorAttachment,\n useSRGBBuffer,\n colorAttachment: colorAttachment,\n label: this.name,\n };\n if (this.samplingMode === Texture.NEAREST_SAMPLINGMODE) {\n this.wrapU = Texture.CLAMP_ADDRESSMODE;\n this.wrapV = Texture.CLAMP_ADDRESSMODE;\n }\n if (!delayAllocation) {\n if (isCube) {\n this._renderTarget = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);\n this.coordinatesMode = Texture.INVCUBIC_MODE;\n this._textureMatrix = Matrix.Identity();\n }\n else {\n this._renderTarget = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);\n }\n this._texture = this._renderTarget.texture;\n if (samples !== undefined) {\n this.samples = samples;\n }\n }\n }\n /**\n * Creates a depth stencil texture.\n * This is only available in WebGL 2 or with the depth texture extension available.\n * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode (default: 0)\n * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture (default: true)\n * @param generateStencil Specifies whether or not a stencil should be allocated in the texture (default: false)\n * @param samples sample count of the depth/stencil texture (default: 1)\n * @param format format of the depth texture (default: 14)\n */\n createDepthStencilTexture(comparisonFunction = 0, bilinearFiltering = true, generateStencil = false, samples = 1, format = 14) {\n var _a;\n (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.createDepthStencilTexture(comparisonFunction, bilinearFiltering, generateStencil, samples, format);\n }\n _releaseRenderPassId() {\n if (this._scene) {\n const engine = this._scene.getEngine();\n for (let i = 0; i < this._renderPassIds.length; ++i) {\n engine.releaseRenderPassId(this._renderPassIds[i]);\n }\n }\n this._renderPassIds = [];\n }\n _createRenderPassId() {\n this._releaseRenderPassId();\n const engine = this._scene.getEngine(); // scene can't be null in a RenderTargetTexture, see constructor\n const numPasses = this._isCubeData ? 6 : this.getRenderLayers() || 1;\n for (let i = 0; i < numPasses; ++i) {\n this._renderPassIds[i] = engine.createRenderPassId(`RenderTargetTexture - ${this.name}#${i}`);\n }\n }\n _processSizeParameter(size, createRenderPassIds = true) {\n if (size.ratio) {\n this._sizeRatio = size.ratio;\n const engine = this._getEngine();\n this._size = {\n width: this._bestReflectionRenderTargetDimension(engine.getRenderWidth(), this._sizeRatio),\n height: this._bestReflectionRenderTargetDimension(engine.getRenderHeight(), this._sizeRatio),\n };\n }\n else {\n this._size = size;\n }\n if (createRenderPassIds) {\n this._createRenderPassId();\n }\n }\n /**\n * Define the number of samples to use in case of MSAA.\n * It defaults to one meaning no MSAA has been enabled.\n */\n get samples() {\n var _a, _b;\n return (_b = (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.samples) !== null && _b !== void 0 ? _b : this._samples;\n }\n set samples(value) {\n if (this._renderTarget) {\n this._samples = this._renderTarget.setSamples(value);\n }\n }\n /**\n * Resets the refresh counter of the texture and start bak from scratch.\n * Could be useful to regenerate the texture if it is setup to render only once.\n */\n resetRefreshCounter() {\n this._currentRefreshId = -1;\n }\n /**\n * Define the refresh rate of the texture or the rendering frequency.\n * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...\n */\n get refreshRate() {\n return this._refreshRate;\n }\n set refreshRate(value) {\n this._refreshRate = value;\n this.resetRefreshCounter();\n }\n /**\n * Adds a post process to the render target rendering passes.\n * @param postProcess define the post process to add\n */\n addPostProcess(postProcess) {\n if (!this._postProcessManager) {\n const scene = this.getScene();\n if (!scene) {\n return;\n }\n this._postProcessManager = new PostProcessManager(scene);\n this._postProcesses = new Array();\n }\n this._postProcesses.push(postProcess);\n this._postProcesses[0].autoClear = false;\n }\n /**\n * Clear all the post processes attached to the render target\n * @param dispose define if the cleared post processes should also be disposed (false by default)\n */\n clearPostProcesses(dispose = false) {\n if (!this._postProcesses) {\n return;\n }\n if (dispose) {\n for (const postProcess of this._postProcesses) {\n postProcess.dispose();\n }\n }\n this._postProcesses = [];\n }\n /**\n * Remove one of the post process from the list of attached post processes to the texture\n * @param postProcess define the post process to remove from the list\n */\n removePostProcess(postProcess) {\n if (!this._postProcesses) {\n return;\n }\n const index = this._postProcesses.indexOf(postProcess);\n if (index === -1) {\n return;\n }\n this._postProcesses.splice(index, 1);\n if (this._postProcesses.length > 0) {\n this._postProcesses[0].autoClear = false;\n }\n }\n /** @internal */\n _shouldRender() {\n if (this._currentRefreshId === -1) {\n // At least render once\n this._currentRefreshId = 1;\n return true;\n }\n if (this.refreshRate === this._currentRefreshId) {\n this._currentRefreshId = 1;\n return true;\n }\n this._currentRefreshId++;\n return false;\n }\n /**\n * Gets the actual render size of the texture.\n * @returns the width of the render size\n */\n getRenderSize() {\n return this.getRenderWidth();\n }\n /**\n * Gets the actual render width of the texture.\n * @returns the width of the render size\n */\n getRenderWidth() {\n if (this._size.width) {\n return this._size.width;\n }\n return this._size;\n }\n /**\n * Gets the actual render height of the texture.\n * @returns the height of the render size\n */\n getRenderHeight() {\n if (this._size.width) {\n return this._size.height;\n }\n return this._size;\n }\n /**\n * Gets the actual number of layers of the texture.\n * @returns the number of layers\n */\n getRenderLayers() {\n const layers = this._size.layers;\n if (layers) {\n return layers;\n }\n return 0;\n }\n /**\n * Don't allow this render target texture to rescale. Mainly used to prevent rescaling by the scene optimizer.\n */\n disableRescaling() {\n this._canRescale = false;\n }\n /**\n * Get if the texture can be rescaled or not.\n */\n get canRescale() {\n return this._canRescale;\n }\n /**\n * Resize the texture using a ratio.\n * @param ratio the ratio to apply to the texture size in order to compute the new target size\n */\n scale(ratio) {\n const newSize = Math.max(1, this.getRenderSize() * ratio);\n this.resize(newSize);\n }\n /**\n * Get the texture reflection matrix used to rotate/transform the reflection.\n * @returns the reflection matrix\n */\n getReflectionTextureMatrix() {\n if (this.isCube) {\n return this._textureMatrix;\n }\n return super.getReflectionTextureMatrix();\n }\n /**\n * Resize the texture to a new desired size.\n * Be careful as it will recreate all the data in the new texture.\n * @param size Define the new size. It can be:\n * - a number for squared texture,\n * - an object containing { width: number, height: number }\n * - or an object containing a ratio { ratio: number }\n */\n resize(size) {\n var _a;\n const wasCube = this.isCube;\n (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.dispose();\n this._renderTarget = null;\n const scene = this.getScene();\n if (!scene) {\n return;\n }\n this._processSizeParameter(size, false);\n if (wasCube) {\n this._renderTarget = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);\n }\n else {\n this._renderTarget = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);\n }\n this._texture = this._renderTarget.texture;\n if (this._renderTargetOptions.samples !== undefined) {\n this.samples = this._renderTargetOptions.samples;\n }\n if (this.onResizeObservable.hasObservers()) {\n this.onResizeObservable.notifyObservers(this);\n }\n }\n /**\n * Renders all the objects from the render list into the texture.\n * @param useCameraPostProcess Define if camera post processes should be used during the rendering\n * @param dumpForDebug Define if the rendering result should be dumped (copied) for debugging purpose\n */\n render(useCameraPostProcess = false, dumpForDebug = false) {\n this._render(useCameraPostProcess, dumpForDebug);\n }\n /**\n * This function will check if the render target texture can be rendered (textures are loaded, shaders are compiled)\n * @returns true if all required resources are ready\n */\n isReadyForRendering() {\n return this._render(false, false, true);\n }\n _render(useCameraPostProcess = false, dumpForDebug = false, checkReadiness = false) {\n var _a;\n const scene = this.getScene();\n if (!scene) {\n return checkReadiness;\n }\n const engine = scene.getEngine();\n if (this.useCameraPostProcesses !== undefined) {\n useCameraPostProcess = this.useCameraPostProcesses;\n }\n if (this._waitingRenderList) {\n this.renderList = [];\n for (let index = 0; index < this._waitingRenderList.length; index++) {\n const id = this._waitingRenderList[index];\n const mesh = scene.getMeshById(id);\n if (mesh) {\n this.renderList.push(mesh);\n }\n }\n this._waitingRenderList = undefined;\n }\n // Is predicate defined?\n if (this.renderListPredicate) {\n if (this.renderList) {\n this.renderList.length = 0; // Clear previous renderList\n }\n else {\n this.renderList = [];\n }\n const scene = this.getScene();\n if (!scene) {\n return checkReadiness;\n }\n const sceneMeshes = scene.meshes;\n for (let index = 0; index < sceneMeshes.length; index++) {\n const mesh = sceneMeshes[index];\n if (this.renderListPredicate(mesh)) {\n this.renderList.push(mesh);\n }\n }\n }\n const currentRenderPassId = engine.currentRenderPassId;\n this.onBeforeBindObservable.notifyObservers(this);\n // Set custom projection.\n // Needs to be before binding to prevent changing the aspect ratio.\n const camera = (_a = this.activeCamera) !== null && _a !== void 0 ? _a : scene.activeCamera;\n const sceneCamera = scene.activeCamera;\n if (camera) {\n if (camera !== scene.activeCamera) {\n scene.setTransformMatrix(camera.getViewMatrix(), camera.getProjectionMatrix(true));\n scene.activeCamera = camera;\n }\n engine.setViewport(camera.rigParent ? camera.rigParent.viewport : camera.viewport, this.getRenderWidth(), this.getRenderHeight());\n }\n this._defaultRenderListPrepared = false;\n let returnValue = checkReadiness;\n if (!checkReadiness) {\n if (this.is2DArray && !this.isMulti) {\n for (let layer = 0; layer < this.getRenderLayers(); layer++) {\n this._renderToTarget(0, useCameraPostProcess, dumpForDebug, layer, camera);\n scene.incrementRenderId();\n scene.resetCachedMaterial();\n }\n }\n else if (this.isCube && !this.isMulti) {\n for (let face = 0; face < 6; face++) {\n this._renderToTarget(face, useCameraPostProcess, dumpForDebug, undefined, camera);\n scene.incrementRenderId();\n scene.resetCachedMaterial();\n }\n }\n else {\n this._renderToTarget(0, useCameraPostProcess, dumpForDebug, undefined, camera);\n }\n }\n else {\n if (!scene.getViewMatrix()) {\n // We probably didn't execute scene.render() yet, so make sure we have a view/projection matrix setup for the scene\n scene.updateTransformMatrix();\n }\n const numLayers = this.is2DArray ? this.getRenderLayers() : this.isCube ? 6 : 1;\n for (let layer = 0; layer < numLayers && returnValue; layer++) {\n let currentRenderList = null;\n const defaultRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;\n const defaultRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;\n engine.currentRenderPassId = this._renderPassIds[layer];\n this.onBeforeRenderObservable.notifyObservers(layer);\n if (this.getCustomRenderList) {\n currentRenderList = this.getCustomRenderList(layer, defaultRenderList, defaultRenderListLength);\n }\n if (!currentRenderList) {\n currentRenderList = defaultRenderList;\n }\n if (!this._doNotChangeAspectRatio) {\n scene.updateTransformMatrix(true);\n }\n for (let i = 0; i < currentRenderList.length && returnValue; ++i) {\n const mesh = currentRenderList[i];\n if (!mesh.isEnabled() || mesh.isBlocked || !mesh.isVisible || !mesh.subMeshes) {\n continue;\n }\n if (this.customIsReadyFunction) {\n if (!this.customIsReadyFunction(mesh, this.refreshRate, checkReadiness)) {\n returnValue = false;\n continue;\n }\n }\n else if (!mesh.isReady(true)) {\n returnValue = false;\n continue;\n }\n }\n this.onAfterRenderObservable.notifyObservers(layer);\n if (this.is2DArray || this.isCube) {\n scene.incrementRenderId();\n scene.resetCachedMaterial();\n }\n }\n }\n this.onAfterUnbindObservable.notifyObservers(this);\n engine.currentRenderPassId = currentRenderPassId;\n if (sceneCamera) {\n scene.activeCamera = sceneCamera;\n // Do not avoid setting uniforms when multiple scenes are active as another camera may have overwrite these\n if (scene.getEngine().scenes.length > 1 || (this.activeCamera && this.activeCamera !== scene.activeCamera)) {\n scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));\n }\n engine.setViewport(scene.activeCamera.viewport);\n }\n scene.resetCachedMaterial();\n return returnValue;\n }\n _bestReflectionRenderTargetDimension(renderDimension, scale) {\n const minimum = 128;\n const x = renderDimension * scale;\n const curved = Engine.NearestPOT(x + (minimum * minimum) / (minimum + x));\n // Ensure we don't exceed the render dimension (while staying POT)\n return Math.min(Engine.FloorPOT(renderDimension), curved);\n }\n _prepareRenderingManager(currentRenderList, currentRenderListLength, camera, checkLayerMask) {\n const scene = this.getScene();\n if (!scene) {\n return;\n }\n this._renderingManager.reset();\n const sceneRenderId = scene.getRenderId();\n for (let meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {\n const mesh = currentRenderList[meshIndex];\n if (mesh && !mesh.isBlocked) {\n if (this.customIsReadyFunction) {\n if (!this.customIsReadyFunction(mesh, this.refreshRate, false)) {\n this.resetRefreshCounter();\n continue;\n }\n }\n else if (!mesh.isReady(this.refreshRate === 0)) {\n this.resetRefreshCounter();\n continue;\n }\n if (!mesh._internalAbstractMeshDataInfo._currentLODIsUpToDate && scene.activeCamera) {\n mesh._internalAbstractMeshDataInfo._currentLOD = scene.customLODSelector\n ? scene.customLODSelector(mesh, this.activeCamera || scene.activeCamera)\n : mesh.getLOD(this.activeCamera || scene.activeCamera);\n mesh._internalAbstractMeshDataInfo._currentLODIsUpToDate = true;\n }\n if (!mesh._internalAbstractMeshDataInfo._currentLOD) {\n continue;\n }\n let meshToRender = mesh._internalAbstractMeshDataInfo._currentLOD;\n meshToRender._preActivateForIntermediateRendering(sceneRenderId);\n let isMasked;\n if (checkLayerMask && camera) {\n isMasked = (mesh.layerMask & camera.layerMask) === 0;\n }\n else {\n isMasked = false;\n }\n if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {\n if (meshToRender !== mesh) {\n meshToRender._activate(sceneRenderId, true);\n }\n if (mesh._activate(sceneRenderId, true) && mesh.subMeshes.length) {\n if (!mesh.isAnInstance) {\n meshToRender._internalAbstractMeshDataInfo._onlyForInstancesIntermediate = false;\n }\n else {\n if (mesh._internalAbstractMeshDataInfo._actAsRegularMesh) {\n meshToRender = mesh;\n }\n }\n meshToRender._internalAbstractMeshDataInfo._isActiveIntermediate = true;\n for (let subIndex = 0; subIndex < meshToRender.subMeshes.length; subIndex++) {\n const subMesh = meshToRender.subMeshes[subIndex];\n this._renderingManager.dispatch(subMesh, meshToRender);\n }\n }\n }\n }\n }\n for (let particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {\n const particleSystem = scene.particleSystems[particleIndex];\n const emitter = particleSystem.emitter;\n if (!particleSystem.isStarted() || !emitter || (emitter.position && !emitter.isEnabled())) {\n continue;\n }\n this._renderingManager.dispatchParticles(particleSystem);\n }\n }\n /**\n * @internal\n * @param faceIndex face index to bind to if this is a cubetexture\n * @param layer defines the index of the texture to bind in the array\n */\n _bindFrameBuffer(faceIndex = 0, layer = 0) {\n const scene = this.getScene();\n if (!scene) {\n return;\n }\n const engine = scene.getEngine();\n if (this._renderTarget) {\n engine.bindFramebuffer(this._renderTarget, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, 0, layer);\n }\n }\n _unbindFrameBuffer(engine, faceIndex) {\n if (!this._renderTarget) {\n return;\n }\n engine.unBindFramebuffer(this._renderTarget, this.isCube, () => {\n this.onAfterRenderObservable.notifyObservers(faceIndex);\n });\n }\n /**\n * @internal\n */\n _prepareFrame(scene, faceIndex, layer, useCameraPostProcess) {\n if (this._postProcessManager) {\n if (!this._prePassEnabled) {\n this._postProcessManager._prepareFrame(this._texture, this._postProcesses);\n }\n }\n else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {\n this._bindFrameBuffer(faceIndex, layer);\n }\n }\n _renderToTarget(faceIndex, useCameraPostProcess, dumpForDebug, layer = 0, camera = null) {\n var _a, _b, _c, _d, _e, _f;\n const scene = this.getScene();\n if (!scene) {\n return;\n }\n const engine = scene.getEngine();\n (_a = engine._debugPushGroup) === null || _a === void 0 ? void 0 : _a.call(engine, `render to face #${faceIndex} layer #${layer}`, 1);\n // Bind\n this._prepareFrame(scene, faceIndex, layer, useCameraPostProcess);\n if (this.is2DArray) {\n engine.currentRenderPassId = this._renderPassIds[layer];\n this.onBeforeRenderObservable.notifyObservers(layer);\n }\n else {\n engine.currentRenderPassId = this._renderPassIds[faceIndex];\n this.onBeforeRenderObservable.notifyObservers(faceIndex);\n }\n const fastPath = engine.snapshotRendering && engine.snapshotRenderingMode === 1;\n if (!fastPath) {\n // Get the list of meshes to render\n let currentRenderList = null;\n const defaultRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;\n const defaultRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;\n if (this.getCustomRenderList) {\n currentRenderList = this.getCustomRenderList(this.is2DArray ? layer : faceIndex, defaultRenderList, defaultRenderListLength);\n }\n if (!currentRenderList) {\n // No custom render list provided, we prepare the rendering for the default list, but check\n // first if we did not already performed the preparation before so as to avoid re-doing it several times\n if (!this._defaultRenderListPrepared) {\n this._prepareRenderingManager(defaultRenderList, defaultRenderListLength, camera, !this.renderList || this.forceLayerMaskCheck);\n this._defaultRenderListPrepared = true;\n }\n currentRenderList = defaultRenderList;\n }\n else {\n // Prepare the rendering for the custom render list provided\n this._prepareRenderingManager(currentRenderList, currentRenderList.length, camera, this.forceLayerMaskCheck);\n }\n // Before clear\n for (const step of scene._beforeRenderTargetClearStage) {\n step.action(this, faceIndex, layer);\n }\n // Clear\n if (this.onClearObservable.hasObservers()) {\n this.onClearObservable.notifyObservers(engine);\n }\n else {\n if (!this.skipInitialClear) {\n engine.clear(this.clearColor || scene.clearColor, true, true, true);\n }\n }\n if (!this._doNotChangeAspectRatio) {\n scene.updateTransformMatrix(true);\n }\n // Before Camera Draw\n for (const step of scene._beforeRenderTargetDrawStage) {\n step.action(this, faceIndex, layer);\n }\n // Render\n this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);\n // After Camera Draw\n for (const step of scene._afterRenderTargetDrawStage) {\n step.action(this, faceIndex, layer);\n }\n const saveGenerateMipMaps = (_c = (_b = this._texture) === null || _b === void 0 ? void 0 : _b.generateMipMaps) !== null && _c !== void 0 ? _c : false;\n if (this._texture) {\n this._texture.generateMipMaps = false; // if left true, the mipmaps will be generated (if this._texture.generateMipMaps = true) when the first post process binds its own RTT: by doing so it will unbind the current RTT,\n // which will trigger a mipmap generation. We don't want this because it's a wasted work, we will do an unbind of the current RTT at the end of the process (see unbindFrameBuffer) which will\n // trigger the generation of the final mipmaps\n }\n if (this._postProcessManager) {\n this._postProcessManager._finalizeFrame(false, (_d = this._renderTarget) !== null && _d !== void 0 ? _d : undefined, faceIndex, this._postProcesses, this.ignoreCameraViewport);\n }\n else if (useCameraPostProcess) {\n scene.postProcessManager._finalizeFrame(false, (_e = this._renderTarget) !== null && _e !== void 0 ? _e : undefined, faceIndex);\n }\n for (const step of scene._afterRenderTargetPostProcessStage) {\n step.action(this, faceIndex, layer);\n }\n if (this._texture) {\n this._texture.generateMipMaps = saveGenerateMipMaps;\n }\n if (!this._doNotChangeAspectRatio) {\n scene.updateTransformMatrix(true);\n }\n // Dump ?\n if (dumpForDebug) {\n DumpTools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);\n }\n }\n else {\n // Clear\n if (this.onClearObservable.hasObservers()) {\n this.onClearObservable.notifyObservers(engine);\n }\n else {\n if (!this.skipInitialClear) {\n engine.clear(this.clearColor || scene.clearColor, true, true, true);\n }\n }\n }\n // Unbind\n this._unbindFrameBuffer(engine, faceIndex);\n if (this._texture && this.isCube && faceIndex === 5) {\n engine.generateMipMapsForCubemap(this._texture);\n }\n (_f = engine._debugPopGroup) === null || _f === void 0 ? void 0 : _f.call(engine, 1);\n }\n /**\n * Overrides the default sort function applied in the rendering group to prepare the meshes.\n * This allowed control for front to back rendering or reversely depending of the special needs.\n *\n * @param renderingGroupId The rendering group id corresponding to its index\n * @param opaqueSortCompareFn The opaque queue comparison function use to sort.\n * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.\n * @param transparentSortCompareFn The transparent queue comparison function use to sort.\n */\n setRenderingOrder(renderingGroupId, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) {\n this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);\n }\n /**\n * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.\n *\n * @param renderingGroupId The rendering group id corresponding to its index\n * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.\n */\n setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil) {\n this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);\n this._renderingManager._useSceneAutoClearSetup = false;\n }\n /**\n * Clones the texture.\n * @returns the cloned texture\n */\n clone() {\n const textureSize = this.getSize();\n const newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer, undefined, this._renderTargetOptions.format, undefined, this._renderTargetOptions.samples);\n // Base texture\n newTexture.hasAlpha = this.hasAlpha;\n newTexture.level = this.level;\n // RenderTarget Texture\n newTexture.coordinatesMode = this.coordinatesMode;\n if (this.renderList) {\n newTexture.renderList = this.renderList.slice(0);\n }\n return newTexture;\n }\n /**\n * Serialize the texture to a JSON representation we can easily use in the respective Parse function.\n * @returns The JSON representation of the texture\n */\n serialize() {\n if (!this.name) {\n return null;\n }\n const serializationObject = super.serialize();\n serializationObject.renderTargetSize = this.getRenderSize();\n serializationObject.renderList = [];\n if (this.renderList) {\n for (let index = 0; index < this.renderList.length; index++) {\n serializationObject.renderList.push(this.renderList[index].id);\n }\n }\n return serializationObject;\n }\n /**\n * This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore\n */\n disposeFramebufferObjects() {\n var _a;\n (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.dispose(true);\n }\n /**\n * Release and destroy the underlying lower level texture aka internalTexture.\n */\n releaseInternalTexture() {\n var _a;\n (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.releaseTextures();\n this._texture = null;\n }\n /**\n * Dispose the texture and release its associated resources.\n */\n dispose() {\n var _a;\n this.onResizeObservable.clear();\n this.onClearObservable.clear();\n this.onAfterRenderObservable.clear();\n this.onAfterUnbindObservable.clear();\n this.onBeforeBindObservable.clear();\n this.onBeforeRenderObservable.clear();\n if (this._postProcessManager) {\n this._postProcessManager.dispose();\n this._postProcessManager = null;\n }\n if (this._prePassRenderTarget) {\n this._prePassRenderTarget.dispose();\n }\n this._releaseRenderPassId();\n this.clearPostProcesses(true);\n if (this._resizeObserver) {\n this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);\n this._resizeObserver = null;\n }\n this.renderList = null;\n // Remove from custom render targets\n const scene = this.getScene();\n if (!scene) {\n return;\n }\n let index = scene.customRenderTargets.indexOf(this);\n if (index >= 0) {\n scene.customRenderTargets.splice(index, 1);\n }\n for (const camera of scene.cameras) {\n index = camera.customRenderTargets.indexOf(this);\n if (index >= 0) {\n camera.customRenderTargets.splice(index, 1);\n }\n }\n (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.dispose();\n this._renderTarget = null;\n this._texture = null;\n super.dispose();\n }\n /** @internal */\n _rebuild() {\n if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {\n this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;\n }\n if (this._postProcessManager) {\n this._postProcessManager._rebuild();\n }\n }\n /**\n * Clear the info related to rendering groups preventing retention point in material dispose.\n */\n freeRenderingGroups() {\n if (this._renderingManager) {\n this._renderingManager.freeRenderingGroups();\n }\n }\n /**\n * Gets the number of views the corresponding to the texture (eg. a MultiviewRenderTarget will have > 1)\n * @returns the view count\n */\n getViewCount() {\n return 1;\n }\n}\n/**\n * The texture will only be rendered once which can be useful to improve performance if everything in your render is static for instance.\n */\nRenderTargetTexture.REFRESHRATE_RENDER_ONCE = 0;\n/**\n * The texture will only be rendered rendered every frame and is recommended for dynamic contents.\n */\nRenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME = 1;\n/**\n * The texture will be rendered every 2 frames which could be enough if your dynamic objects are not\n * the central point of your effect and can save a lot of performances.\n */\nRenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nTexture._CreateRenderTargetTexture = (name, renderTargetSize, scene, generateMipMaps, creationFlags) => {\n return new RenderTargetTexture(name, renderTargetSize, scene, generateMipMaps);\n};\n//# sourceMappingURL=renderTargetTexture.js.map","import { Tools } from \"../../../Misc/tools.js\";\nimport { SceneComponentConstants } from \"../../../sceneComponent.js\";\n/**\n * Defines the Procedural Texture scene component responsible to manage any Procedural Texture\n * in a given scene.\n */\nexport class ProceduralTextureSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpful to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_PROCEDURALTEXTURE;\n this.scene = scene;\n this.scene.proceduralTextures = new Array();\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene._beforeClearStage.registerStep(SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n // Nothing to do here.\n }\n /**\n * Disposes the component and the associated resources.\n */\n dispose() {\n // Nothing to do here.\n }\n _beforeClear() {\n if (this.scene.proceduralTexturesEnabled) {\n Tools.StartPerformanceCounter(\"Procedural textures\", this.scene.proceduralTextures.length > 0);\n for (let proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {\n const proceduralTexture = this.scene.proceduralTextures[proceduralIndex];\n if (proceduralTexture._shouldRender()) {\n proceduralTexture.render();\n }\n }\n Tools.EndPerformanceCounter(\"Procedural textures\", this.scene.proceduralTextures.length > 0);\n }\n }\n}\n//# sourceMappingURL=proceduralTextureSceneComponent.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"proceduralVertexShader\";\nconst shader = `attribute vec2 position;\rvarying vec2 vPosition;\rvarying vec2 vUV;\rconst vec2 madd=vec2(0.5,0.5);\r#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_VERTEX_MAIN_BEGIN\nvPosition=position;\rvUV=position*madd+madd;\rgl_Position=vec4(position,0.0,1.0);\r#define CUSTOM_VERTEX_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const proceduralVertexShader = { name, shader };\n//# sourceMappingURL=procedural.vertex.js.map","import { __decorate } from \"../../../tslib.es6.js\";\nimport { serialize } from \"../../../Misc/decorators.js\";\nimport { Observable } from \"../../../Misc/observable.js\";\nimport { VertexBuffer } from \"../../../Buffers/buffer.js\";\nimport { SceneComponentConstants } from \"../../../sceneComponent.js\";\nimport { Material } from \"../../../Materials/material.js\";\nimport { Texture } from \"../../../Materials/Textures/texture.js\";\nimport { RenderTargetTexture } from \"../../../Materials/Textures/renderTargetTexture.js\";\nimport { ProceduralTextureSceneComponent } from \"./proceduralTextureSceneComponent.js\";\nimport \"../../../Engines/Extensions/engine.renderTarget.js\";\nimport \"../../../Engines/Extensions/engine.renderTargetCube.js\";\nimport \"../../../Shaders/procedural.vertex.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { EngineStore } from \"../../../Engines/engineStore.js\";\n\nimport { DrawWrapper } from \"../../drawWrapper.js\";\n/**\n * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes calmpler' images.\n * This is the base class of any Procedural texture and contains most of the shareable code.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/proceduralTextures\n */\nexport class ProceduralTexture extends Texture {\n /**\n * Instantiates a new procedural texture.\n * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.\n * This is the base class of any Procedural texture and contains most of the shareable code.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/proceduralTextures\n * @param name Define the name of the texture\n * @param size Define the size of the texture to create\n * @param fragment Define the fragment shader to use to generate the texture or null if it is defined later\n * @param scene Define the scene the texture belongs to\n * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture\n * @param generateMipMaps Define if the texture should creates mip maps or not\n * @param isCube Define if the texture is a cube texture or not (this will render each faces of the cube)\n * @param textureType The FBO internal texture type\n */\n constructor(name, size, fragment, scene, fallbackTexture = null, generateMipMaps = true, isCube = false, textureType = 0) {\n super(null, scene, !generateMipMaps);\n /**\n * Define if the texture is enabled or not (disabled texture will not render)\n */\n this.isEnabled = true;\n /**\n * Define if the texture must be cleared before rendering (default is true)\n */\n this.autoClear = true;\n /**\n * Event raised when the texture is generated\n */\n this.onGeneratedObservable = new Observable();\n /**\n * Event raised before the texture is generated\n */\n this.onBeforeGenerationObservable = new Observable();\n /**\n * Gets or sets the node material used to create this texture (null if the texture was manually created)\n */\n this.nodeMaterialSource = null;\n /** @internal */\n this._textures = {};\n this._currentRefreshId = -1;\n this._frameId = -1;\n this._refreshRate = 1;\n this._vertexBuffers = {};\n this._uniforms = new Array();\n this._samplers = new Array();\n this._floats = {};\n this._ints = {};\n this._floatsArrays = {};\n this._colors3 = {};\n this._colors4 = {};\n this._vectors2 = {};\n this._vectors3 = {};\n this._matrices = {};\n this._fallbackTextureUsed = false;\n this._cachedDefines = null;\n this._contentUpdateId = -1;\n this._rtWrapper = null;\n scene = this.getScene() || EngineStore.LastCreatedScene;\n let component = scene._getComponent(SceneComponentConstants.NAME_PROCEDURALTEXTURE);\n if (!component) {\n component = new ProceduralTextureSceneComponent(scene);\n scene._addComponent(component);\n }\n scene.proceduralTextures.push(this);\n this._fullEngine = scene.getEngine();\n this.name = name;\n this.isRenderTarget = true;\n this._size = size;\n this._textureType = textureType;\n this._generateMipMaps = generateMipMaps;\n this._drawWrapper = new DrawWrapper(this._fullEngine);\n this.setFragment(fragment);\n this._fallbackTexture = fallbackTexture;\n const rtWrapper = this._createRtWrapper(isCube, size, generateMipMaps, textureType);\n this._texture = rtWrapper.texture;\n // VBO\n const vertices = [];\n vertices.push(1, 1);\n vertices.push(-1, 1);\n vertices.push(-1, -1);\n vertices.push(1, -1);\n this._vertexBuffers[VertexBuffer.PositionKind] = new VertexBuffer(this._fullEngine, vertices, VertexBuffer.PositionKind, false, false, 2);\n this._createIndexBuffer();\n }\n _createRtWrapper(isCube, size, generateMipMaps, textureType) {\n if (isCube) {\n this._rtWrapper = this._fullEngine.createRenderTargetCubeTexture(size, {\n generateMipMaps: generateMipMaps,\n generateDepthBuffer: false,\n generateStencilBuffer: false,\n type: textureType,\n });\n this.setFloat(\"face\", 0);\n }\n else {\n this._rtWrapper = this._fullEngine.createRenderTargetTexture(size, {\n generateMipMaps: generateMipMaps,\n generateDepthBuffer: false,\n generateStencilBuffer: false,\n type: textureType,\n });\n }\n return this._rtWrapper;\n }\n /**\n * The effect that is created when initializing the post process.\n * @returns The created effect corresponding the the postprocess.\n */\n getEffect() {\n return this._drawWrapper.effect;\n }\n /**\n * @internal*\n */\n _setEffect(effect) {\n this._drawWrapper.effect = effect;\n }\n /**\n * Gets texture content (Use this function wisely as reading from a texture can be slow)\n * @returns an ArrayBufferView promise (Uint8Array or Float32Array)\n */\n getContent() {\n if (this._contentData && this._frameId === this._contentUpdateId) {\n return this._contentData;\n }\n if (this._contentData) {\n this._contentData.then((buffer) => {\n this._contentData = this.readPixels(0, 0, buffer);\n this._contentUpdateId = this._frameId;\n });\n }\n else {\n this._contentData = this.readPixels(0, 0);\n this._contentUpdateId = this._frameId;\n }\n return this._contentData;\n }\n _createIndexBuffer() {\n const engine = this._fullEngine;\n // Indices\n const indices = [];\n indices.push(0);\n indices.push(1);\n indices.push(2);\n indices.push(0);\n indices.push(2);\n indices.push(3);\n this._indexBuffer = engine.createIndexBuffer(indices);\n }\n /** @internal */\n _rebuild() {\n const vb = this._vertexBuffers[VertexBuffer.PositionKind];\n if (vb) {\n vb._rebuild();\n }\n this._createIndexBuffer();\n if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {\n this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;\n }\n }\n /**\n * Resets the texture in order to recreate its associated resources.\n * This can be called in case of context loss\n */\n reset() {\n var _a;\n (_a = this._drawWrapper.effect) === null || _a === void 0 ? void 0 : _a.dispose();\n }\n _getDefines() {\n return \"\";\n }\n /**\n * Is the texture ready to be used ? (rendered at least once)\n * @returns true if ready, otherwise, false.\n */\n isReady() {\n const engine = this._fullEngine;\n let shaders;\n if (this.nodeMaterialSource) {\n return this._drawWrapper.effect.isReady();\n }\n if (!this._fragment) {\n return false;\n }\n if (this._fallbackTextureUsed) {\n return true;\n }\n if (!this._texture) {\n return false;\n }\n const defines = this._getDefines();\n if (this._drawWrapper.effect && defines === this._cachedDefines && this._drawWrapper.effect.isReady()) {\n return true;\n }\n if (this._fragment.fragmentElement !== undefined) {\n shaders = { vertex: \"procedural\", fragmentElement: this._fragment.fragmentElement };\n }\n else {\n shaders = { vertex: \"procedural\", fragment: this._fragment };\n }\n if (this._cachedDefines !== defines) {\n this._cachedDefines = defines;\n this._drawWrapper.effect = engine.createEffect(shaders, [VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, () => {\n var _a;\n (_a = this._rtWrapper) === null || _a === void 0 ? void 0 : _a.dispose();\n this._rtWrapper = this._texture = null;\n if (this._fallbackTexture) {\n this._texture = this._fallbackTexture._texture;\n if (this._texture) {\n this._texture.incrementReferences();\n }\n }\n this._fallbackTextureUsed = true;\n });\n }\n return this._drawWrapper.effect.isReady();\n }\n /**\n * Resets the refresh counter of the texture and start bak from scratch.\n * Could be useful to regenerate the texture if it is setup to render only once.\n */\n resetRefreshCounter() {\n this._currentRefreshId = -1;\n }\n /**\n * Set the fragment shader to use in order to render the texture.\n * @param fragment This can be set to a path (into the shader store) or to a json object containing a fragmentElement property.\n */\n setFragment(fragment) {\n this._fragment = fragment;\n }\n /**\n * Define the refresh rate of the texture or the rendering frequency.\n * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...\n */\n get refreshRate() {\n return this._refreshRate;\n }\n set refreshRate(value) {\n this._refreshRate = value;\n this.resetRefreshCounter();\n }\n /** @internal */\n _shouldRender() {\n if (!this.isEnabled || !this.isReady() || !this._texture) {\n if (this._texture) {\n this._texture.isReady = false;\n }\n return false;\n }\n if (this._fallbackTextureUsed) {\n return false;\n }\n if (this._currentRefreshId === -1) {\n // At least render once\n this._currentRefreshId = 1;\n this._frameId++;\n return true;\n }\n if (this.refreshRate === this._currentRefreshId) {\n this._currentRefreshId = 1;\n this._frameId++;\n return true;\n }\n this._currentRefreshId++;\n return false;\n }\n /**\n * Get the size the texture is rendering at.\n * @returns the size (on cube texture it is always squared)\n */\n getRenderSize() {\n return this._size;\n }\n /**\n * Resize the texture to new value.\n * @param size Define the new size the texture should have\n * @param generateMipMaps Define whether the new texture should create mip maps\n */\n resize(size, generateMipMaps) {\n if (this._fallbackTextureUsed || !this._rtWrapper || !this._texture) {\n return;\n }\n const isCube = this._texture.isCube;\n this._rtWrapper.dispose();\n const rtWrapper = this._createRtWrapper(isCube, size, generateMipMaps, this._textureType);\n this._texture = rtWrapper.texture;\n // Update properties\n this._size = size;\n this._generateMipMaps = generateMipMaps;\n }\n _checkUniform(uniformName) {\n if (this._uniforms.indexOf(uniformName) === -1) {\n this._uniforms.push(uniformName);\n }\n }\n /**\n * Set a texture in the shader program used to render.\n * @param name Define the name of the uniform samplers as defined in the shader\n * @param texture Define the texture to bind to this sampler\n * @returns the texture itself allowing \"fluent\" like uniform updates\n */\n setTexture(name, texture) {\n if (this._samplers.indexOf(name) === -1) {\n this._samplers.push(name);\n }\n this._textures[name] = texture;\n return this;\n }\n /**\n * Set a float in the shader.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the texture itself allowing \"fluent\" like uniform updates\n */\n setFloat(name, value) {\n this._checkUniform(name);\n this._floats[name] = value;\n return this;\n }\n /**\n * Set a int in the shader.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the texture itself allowing \"fluent\" like uniform updates\n */\n setInt(name, value) {\n this._checkUniform(name);\n this._ints[name] = value;\n return this;\n }\n /**\n * Set an array of floats in the shader.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the texture itself allowing \"fluent\" like uniform updates\n */\n setFloats(name, value) {\n this._checkUniform(name);\n this._floatsArrays[name] = value;\n return this;\n }\n /**\n * Set a vec3 in the shader from a Color3.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the texture itself allowing \"fluent\" like uniform updates\n */\n setColor3(name, value) {\n this._checkUniform(name);\n this._colors3[name] = value;\n return this;\n }\n /**\n * Set a vec4 in the shader from a Color4.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the texture itself allowing \"fluent\" like uniform updates\n */\n setColor4(name, value) {\n this._checkUniform(name);\n this._colors4[name] = value;\n return this;\n }\n /**\n * Set a vec2 in the shader from a Vector2.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the texture itself allowing \"fluent\" like uniform updates\n */\n setVector2(name, value) {\n this._checkUniform(name);\n this._vectors2[name] = value;\n return this;\n }\n /**\n * Set a vec3 in the shader from a Vector3.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the texture itself allowing \"fluent\" like uniform updates\n */\n setVector3(name, value) {\n this._checkUniform(name);\n this._vectors3[name] = value;\n return this;\n }\n /**\n * Set a mat4 in the shader from a MAtrix.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the texture itself allowing \"fluent\" like uniform updates\n */\n setMatrix(name, value) {\n this._checkUniform(name);\n this._matrices[name] = value;\n return this;\n }\n /**\n * Render the texture to its associated render target.\n * @param useCameraPostProcess Define if camera post process should be applied to the texture\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n render(useCameraPostProcess) {\n var _a, _b;\n const scene = this.getScene();\n if (!scene) {\n return;\n }\n const engine = this._fullEngine;\n // Render\n engine.enableEffect(this._drawWrapper);\n this.onBeforeGenerationObservable.notifyObservers(this);\n engine.setState(false);\n if (!this.nodeMaterialSource) {\n // Texture\n for (const name in this._textures) {\n this._drawWrapper.effect.setTexture(name, this._textures[name]);\n }\n // Float\n for (const name in this._ints) {\n this._drawWrapper.effect.setInt(name, this._ints[name]);\n }\n // Float\n for (const name in this._floats) {\n this._drawWrapper.effect.setFloat(name, this._floats[name]);\n }\n // Floats\n for (const name in this._floatsArrays) {\n this._drawWrapper.effect.setArray(name, this._floatsArrays[name]);\n }\n // Color3\n for (const name in this._colors3) {\n this._drawWrapper.effect.setColor3(name, this._colors3[name]);\n }\n // Color4\n for (const name in this._colors4) {\n const color = this._colors4[name];\n this._drawWrapper.effect.setFloat4(name, color.r, color.g, color.b, color.a);\n }\n // Vector2\n for (const name in this._vectors2) {\n this._drawWrapper.effect.setVector2(name, this._vectors2[name]);\n }\n // Vector3\n for (const name in this._vectors3) {\n this._drawWrapper.effect.setVector3(name, this._vectors3[name]);\n }\n // Matrix\n for (const name in this._matrices) {\n this._drawWrapper.effect.setMatrix(name, this._matrices[name]);\n }\n }\n if (!this._texture || !this._rtWrapper) {\n return;\n }\n (_a = engine._debugPushGroup) === null || _a === void 0 ? void 0 : _a.call(engine, `procedural texture generation for ${this.name}`, 1);\n const viewPort = engine.currentViewport;\n if (this.isCube) {\n for (let face = 0; face < 6; face++) {\n engine.bindFramebuffer(this._rtWrapper, face, undefined, undefined, true);\n // VBOs\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._drawWrapper.effect);\n this._drawWrapper.effect.setFloat(\"face\", face);\n // Clear\n if (this.autoClear) {\n engine.clear(scene.clearColor, true, false, false);\n }\n // Draw order\n engine.drawElementsType(Material.TriangleFillMode, 0, 6);\n }\n }\n else {\n engine.bindFramebuffer(this._rtWrapper, 0, undefined, undefined, true);\n // VBOs\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._drawWrapper.effect);\n // Clear\n if (this.autoClear) {\n engine.clear(scene.clearColor, true, false, false);\n }\n // Draw order\n engine.drawElementsType(Material.TriangleFillMode, 0, 6);\n }\n // Unbind and restore viewport\n engine.unBindFramebuffer(this._rtWrapper, this.isCube);\n if (viewPort) {\n engine.setViewport(viewPort);\n }\n // Mipmaps\n if (this.isCube) {\n engine.generateMipMapsForCubemap(this._texture);\n }\n (_b = engine._debugPopGroup) === null || _b === void 0 ? void 0 : _b.call(engine, 1);\n if (this.onGenerated) {\n this.onGenerated();\n }\n this.onGeneratedObservable.notifyObservers(this);\n }\n /**\n * Clone the texture.\n * @returns the cloned texture\n */\n clone() {\n const textureSize = this.getSize();\n const newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);\n // Base texture\n newTexture.hasAlpha = this.hasAlpha;\n newTexture.level = this.level;\n // RenderTarget Texture\n newTexture.coordinatesMode = this.coordinatesMode;\n return newTexture;\n }\n /**\n * Dispose the texture and release its associated resources.\n */\n dispose() {\n const scene = this.getScene();\n if (!scene) {\n return;\n }\n const index = scene.proceduralTextures.indexOf(this);\n if (index >= 0) {\n scene.proceduralTextures.splice(index, 1);\n }\n const vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];\n if (vertexBuffer) {\n vertexBuffer.dispose();\n this._vertexBuffers[VertexBuffer.PositionKind] = null;\n }\n if (this._indexBuffer && this._fullEngine._releaseBuffer(this._indexBuffer)) {\n this._indexBuffer = null;\n }\n this.onGeneratedObservable.clear();\n this.onBeforeGenerationObservable.clear();\n super.dispose();\n }\n}\n__decorate([\n serialize()\n], ProceduralTexture.prototype, \"isEnabled\", void 0);\n__decorate([\n serialize()\n], ProceduralTexture.prototype, \"autoClear\", void 0);\n__decorate([\n serialize()\n], ProceduralTexture.prototype, \"_generateMipMaps\", void 0);\n__decorate([\n serialize()\n], ProceduralTexture.prototype, \"_size\", void 0);\n__decorate([\n serialize()\n], ProceduralTexture.prototype, \"refreshRate\", null);\nRegisterClass(\"BABYLON.ProceduralTexture\", ProceduralTexture);\n//# sourceMappingURL=proceduralTexture.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Operations supported by the Trigonometry block\n */\nexport var TrigonometryBlockOperations;\n(function (TrigonometryBlockOperations) {\n /** Cos */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Cos\"] = 0] = \"Cos\";\n /** Sin */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Sin\"] = 1] = \"Sin\";\n /** Abs */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Abs\"] = 2] = \"Abs\";\n /** Exp */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Exp\"] = 3] = \"Exp\";\n /** Exp2 */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Exp2\"] = 4] = \"Exp2\";\n /** Round */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Round\"] = 5] = \"Round\";\n /** Floor */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Floor\"] = 6] = \"Floor\";\n /** Ceiling */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Ceiling\"] = 7] = \"Ceiling\";\n /** Square root */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Sqrt\"] = 8] = \"Sqrt\";\n /** Log */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Log\"] = 9] = \"Log\";\n /** Tangent */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Tan\"] = 10] = \"Tan\";\n /** Arc tangent */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"ArcTan\"] = 11] = \"ArcTan\";\n /** Arc cosinus */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"ArcCos\"] = 12] = \"ArcCos\";\n /** Arc sinus */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"ArcSin\"] = 13] = \"ArcSin\";\n /** Fraction */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Fract\"] = 14] = \"Fract\";\n /** Sign */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Sign\"] = 15] = \"Sign\";\n /** To radians (from degrees) */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Radians\"] = 16] = \"Radians\";\n /** To degrees (from radians) */\n TrigonometryBlockOperations[TrigonometryBlockOperations[\"Degrees\"] = 17] = \"Degrees\";\n})(TrigonometryBlockOperations || (TrigonometryBlockOperations = {}));\n/**\n * Block used to apply trigonometry operation to floats\n */\nexport class TrigonometryBlock extends NodeMaterialBlock {\n /**\n * Creates a new TrigonometryBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n /**\n * Gets or sets the operation applied by the block\n */\n this.operation = TrigonometryBlockOperations.Cos;\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"TrigonometryBlock\";\n }\n /**\n * Gets the input component\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n let operation = \"\";\n switch (this.operation) {\n case TrigonometryBlockOperations.Cos: {\n operation = \"cos\";\n break;\n }\n case TrigonometryBlockOperations.Sin: {\n operation = \"sin\";\n break;\n }\n case TrigonometryBlockOperations.Abs: {\n operation = \"abs\";\n break;\n }\n case TrigonometryBlockOperations.Exp: {\n operation = \"exp\";\n break;\n }\n case TrigonometryBlockOperations.Exp2: {\n operation = \"exp2\";\n break;\n }\n case TrigonometryBlockOperations.Round: {\n operation = \"round\";\n break;\n }\n case TrigonometryBlockOperations.Floor: {\n operation = \"floor\";\n break;\n }\n case TrigonometryBlockOperations.Ceiling: {\n operation = \"ceil\";\n break;\n }\n case TrigonometryBlockOperations.Sqrt: {\n operation = \"sqrt\";\n break;\n }\n case TrigonometryBlockOperations.Log: {\n operation = \"log\";\n break;\n }\n case TrigonometryBlockOperations.Tan: {\n operation = \"tan\";\n break;\n }\n case TrigonometryBlockOperations.ArcTan: {\n operation = \"atan\";\n break;\n }\n case TrigonometryBlockOperations.ArcCos: {\n operation = \"acos\";\n break;\n }\n case TrigonometryBlockOperations.ArcSin: {\n operation = \"asin\";\n break;\n }\n case TrigonometryBlockOperations.Fract: {\n operation = \"fract\";\n break;\n }\n case TrigonometryBlockOperations.Sign: {\n operation = \"sign\";\n break;\n }\n case TrigonometryBlockOperations.Radians: {\n operation = \"radians\";\n break;\n }\n case TrigonometryBlockOperations.Degrees: {\n operation = \"degrees\";\n break;\n }\n }\n state.compilationString += this._declareOutput(output, state) + ` = ${operation}(${this.input.associatedVariableName});\\r\\n`;\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.operation = this.operation;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.operation = serializationObject.operation;\n }\n _dumpPropertiesCode() {\n const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.operation = BABYLON.TrigonometryBlockOperations.${TrigonometryBlockOperations[this.operation]};\\r\\n`;\n return codeString;\n }\n}\nRegisterClass(\"BABYLON.TrigonometryBlock\", TrigonometryBlock);\n//# sourceMappingURL=trigonometryBlock.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { PushMaterial } from \"../pushMaterial.js\";\nimport { AbstractMesh } from \"../../Meshes/abstractMesh.js\";\nimport { Matrix, Vector2 } from \"../../Maths/math.vector.js\";\nimport { Color3, Color4 } from \"../../Maths/math.color.js\";\nimport { Engine } from \"../../Engines/engine.js\";\nimport { NodeMaterialBuildState } from \"./nodeMaterialBuildState.js\";\nimport { Effect } from \"../effect.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { NodeMaterialBlockTargets } from \"./Enums/nodeMaterialBlockTargets.js\";\nimport { NodeMaterialBuildStateSharedData } from \"./nodeMaterialBuildStateSharedData.js\";\nimport { MaterialDefines } from \"../../Materials/materialDefines.js\";\nimport { VertexBuffer } from \"../../Buffers/buffer.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nimport { TransformBlock } from \"./Blocks/transformBlock.js\";\nimport { VertexOutputBlock } from \"./Blocks/Vertex/vertexOutputBlock.js\";\nimport { FragmentOutputBlock } from \"./Blocks/Fragment/fragmentOutputBlock.js\";\nimport { InputBlock } from \"./Blocks/Input/inputBlock.js\";\nimport { GetClass, RegisterClass } from \"../../Misc/typeStore.js\";\nimport { serialize, SerializationHelper } from \"../../Misc/decorators.js\";\nimport { CurrentScreenBlock } from \"./Blocks/Dual/currentScreenBlock.js\";\nimport { ParticleTextureBlock } from \"./Blocks/Particle/particleTextureBlock.js\";\nimport { ParticleRampGradientBlock } from \"./Blocks/Particle/particleRampGradientBlock.js\";\nimport { ParticleBlendMultiplyBlock } from \"./Blocks/Particle/particleBlendMultiplyBlock.js\";\nimport { EffectFallbacks } from \"../effectFallbacks.js\";\nimport { WebRequest } from \"../../Misc/webRequest.js\";\nimport { PostProcess } from \"../../PostProcesses/postProcess.js\";\n\nimport { VectorMergerBlock } from \"./Blocks/vectorMergerBlock.js\";\nimport { RemapBlock } from \"./Blocks/remapBlock.js\";\nimport { MultiplyBlock } from \"./Blocks/multiplyBlock.js\";\nimport { NodeMaterialModes } from \"./Enums/nodeMaterialModes.js\";\nimport { Texture } from \"../Textures/texture.js\";\nimport { BaseParticleSystem } from \"../../Particles/baseParticleSystem.js\";\nimport { ColorSplitterBlock } from \"./Blocks/colorSplitterBlock.js\";\nimport { TimingTools } from \"../../Misc/timingTools.js\";\nimport { ProceduralTexture } from \"../Textures/Procedurals/proceduralTexture.js\";\nimport { AnimatedInputBlockTypes } from \"./Blocks/Input/animatedInputBlockTypes.js\";\nimport { TrigonometryBlock, TrigonometryBlockOperations } from \"./Blocks/trigonometryBlock.js\";\nimport { NodeMaterialSystemValues } from \"./Enums/nodeMaterialSystemValues.js\";\nimport { EngineStore } from \"../../Engines/engineStore.js\";\nimport { MaterialHelper } from \"../materialHelper.js\";\nconst onCreatedEffectParameters = { effect: null, subMesh: null };\n/** @internal */\nexport class NodeMaterialDefines extends MaterialDefines {\n constructor() {\n super();\n this.NORMAL = false;\n this.TANGENT = false;\n this.VERTEXCOLOR_NME = false;\n this.UV1 = false;\n this.UV2 = false;\n this.UV3 = false;\n this.UV4 = false;\n this.UV5 = false;\n this.UV6 = false;\n /** BONES */\n this.NUM_BONE_INFLUENCERS = 0;\n this.BonesPerMesh = 0;\n this.BONETEXTURE = false;\n /** MORPH TARGETS */\n this.MORPHTARGETS = false;\n this.MORPHTARGETS_NORMAL = false;\n this.MORPHTARGETS_TANGENT = false;\n this.MORPHTARGETS_UV = false;\n this.NUM_MORPH_INFLUENCERS = 0;\n this.MORPHTARGETS_TEXTURE = false;\n /** IMAGE PROCESSING */\n this.IMAGEPROCESSING = false;\n this.VIGNETTE = false;\n this.VIGNETTEBLENDMODEMULTIPLY = false;\n this.VIGNETTEBLENDMODEOPAQUE = false;\n this.TONEMAPPING = false;\n this.TONEMAPPING_ACES = false;\n this.CONTRAST = false;\n this.EXPOSURE = false;\n this.COLORCURVES = false;\n this.COLORGRADING = false;\n this.COLORGRADING3D = false;\n this.SAMPLER3DGREENDEPTH = false;\n this.SAMPLER3DBGRMAP = false;\n this.DITHER = false;\n this.IMAGEPROCESSINGPOSTPROCESS = false;\n this.SKIPFINALCOLORCLAMP = false;\n /** MISC. */\n this.BUMPDIRECTUV = 0;\n this.CAMERA_ORTHOGRAPHIC = false;\n this.CAMERA_PERSPECTIVE = false;\n this.rebuild();\n }\n setValue(name, value, markAsUnprocessedIfDirty = false) {\n if (this[name] === undefined) {\n this._keys.push(name);\n }\n if (markAsUnprocessedIfDirty && this[name] !== value) {\n this.markAsUnprocessed();\n }\n this[name] = value;\n }\n}\n/**\n * Class used to create a node based material built by assembling shader blocks\n */\nexport class NodeMaterial extends PushMaterial {\n /**\n * Checks if a block is a texture block\n * @param block The block to check\n * @returns True if the block is a texture block\n */\n static _BlockIsTextureBlock(block) {\n return (block.getClassName() === \"TextureBlock\" ||\n block.getClassName() === \"ReflectionTextureBaseBlock\" ||\n block.getClassName() === \"RefractionBlock\" ||\n block.getClassName() === \"CurrentScreenBlock\" ||\n block.getClassName() === \"ParticleTextureBlock\" ||\n block.getClassName() === \"ImageSourceBlock\" ||\n block.getClassName() === \"TriPlanarBlock\" ||\n block.getClassName() === \"BiPlanarBlock\");\n }\n /** Get the inspector from bundle or global */\n _getGlobalNodeMaterialEditor() {\n // UMD Global name detection from Webpack Bundle UMD Name.\n if (typeof NODEEDITOR !== \"undefined\") {\n return NODEEDITOR;\n }\n // In case of module let's check the global emitted from the editor entry point.\n if (typeof BABYLON !== \"undefined\" && typeof BABYLON.NodeEditor !== \"undefined\") {\n return BABYLON;\n }\n return undefined;\n }\n /** Gets or sets options to control the node material overall behavior */\n get options() {\n return this._options;\n }\n set options(options) {\n this._options = options;\n }\n /**\n * Gets the image processing configuration used either in this material.\n */\n get imageProcessingConfiguration() {\n return this._imageProcessingConfiguration;\n }\n /**\n * Sets the Default image processing configuration used either in the this material.\n *\n * If sets to null, the scene one is in use.\n */\n set imageProcessingConfiguration(value) {\n this._attachImageProcessingConfiguration(value);\n // Ensure the effect will be rebuilt.\n this._markAllSubMeshesAsTexturesDirty();\n }\n /**\n * Gets or sets the mode property\n */\n get mode() {\n return this._mode;\n }\n set mode(value) {\n this._mode = value;\n }\n /** Gets or sets the unique identifier used to identified the effect associated with the material */\n get buildId() {\n return this._buildId;\n }\n set buildId(value) {\n this._buildId = value;\n }\n /**\n * Create a new node based material\n * @param name defines the material name\n * @param scene defines the hosting scene\n * @param options defines creation option\n */\n constructor(name, scene, options = {}) {\n super(name, scene || EngineStore.LastCreatedScene);\n this._buildId = NodeMaterial._BuildIdGenerator++;\n this._buildWasSuccessful = false;\n this._cachedWorldViewMatrix = new Matrix();\n this._cachedWorldViewProjectionMatrix = new Matrix();\n this._optimizers = new Array();\n this._animationFrame = -1;\n this.BJSNODEMATERIALEDITOR = this._getGlobalNodeMaterialEditor();\n /**\n * Gets or sets data used by visual editor\n * @see https://nme.babylonjs.com\n */\n this.editorData = null;\n /**\n * Gets or sets a boolean indicating that alpha value must be ignored (This will turn alpha blending off even if an alpha value is produced by the material)\n */\n this.ignoreAlpha = false;\n /**\n * Defines the maximum number of lights that can be used in the material\n */\n this.maxSimultaneousLights = 4;\n /**\n * Observable raised when the material is built\n */\n this.onBuildObservable = new Observable();\n /**\n * Gets or sets the root nodes of the material vertex shader\n */\n this._vertexOutputNodes = new Array();\n /**\n * Gets or sets the root nodes of the material fragment (pixel) shader\n */\n this._fragmentOutputNodes = new Array();\n /**\n * Gets an array of blocks that needs to be serialized even if they are not yet connected\n */\n this.attachedBlocks = new Array();\n /**\n * Specifies the mode of the node material\n * @internal\n */\n this._mode = NodeMaterialModes.Material;\n /**\n * Gets or sets a boolean indicating that alpha blending must be enabled no matter what alpha value or alpha channel of the FragmentBlock are\n */\n this.forceAlphaBlending = false;\n this._options = Object.assign({ emitComments: false }, options);\n // Setup the default processing configuration to the scene.\n this._attachImageProcessingConfiguration(null);\n }\n /**\n * Gets the current class name of the material e.g. \"NodeMaterial\"\n * @returns the class name\n */\n getClassName() {\n return \"NodeMaterial\";\n }\n /**\n * Attaches a new image processing configuration to the Standard Material.\n * @param configuration\n */\n _attachImageProcessingConfiguration(configuration) {\n if (configuration === this._imageProcessingConfiguration) {\n return;\n }\n // Detaches observer.\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n // Pick the scene configuration if needed.\n if (!configuration) {\n this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;\n }\n else {\n this._imageProcessingConfiguration = configuration;\n }\n // Attaches observer.\n if (this._imageProcessingConfiguration) {\n this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => {\n this._markAllSubMeshesAsImageProcessingDirty();\n });\n }\n }\n /**\n * Get a block by its name\n * @param name defines the name of the block to retrieve\n * @returns the required block or null if not found\n */\n getBlockByName(name) {\n let result = null;\n for (const block of this.attachedBlocks) {\n if (block.name === name) {\n if (!result) {\n result = block;\n }\n else {\n Tools.Warn(\"More than one block was found with the name `\" + name + \"`\");\n return result;\n }\n }\n }\n return result;\n }\n /**\n * Get a block by its name\n * @param predicate defines the predicate used to find the good candidate\n * @returns the required block or null if not found\n */\n getBlockByPredicate(predicate) {\n for (const block of this.attachedBlocks) {\n if (predicate(block)) {\n return block;\n }\n }\n return null;\n }\n /**\n * Get an input block by its name\n * @param predicate defines the predicate used to find the good candidate\n * @returns the required input block or null if not found\n */\n getInputBlockByPredicate(predicate) {\n for (const block of this.attachedBlocks) {\n if (block.isInput && predicate(block)) {\n return block;\n }\n }\n return null;\n }\n /**\n * Gets the list of input blocks attached to this material\n * @returns an array of InputBlocks\n */\n getInputBlocks() {\n const blocks = [];\n for (const block of this.attachedBlocks) {\n if (block.isInput) {\n blocks.push(block);\n }\n }\n return blocks;\n }\n /**\n * Adds a new optimizer to the list of optimizers\n * @param optimizer defines the optimizers to add\n * @returns the current material\n */\n registerOptimizer(optimizer) {\n const index = this._optimizers.indexOf(optimizer);\n if (index > -1) {\n return;\n }\n this._optimizers.push(optimizer);\n return this;\n }\n /**\n * Remove an optimizer from the list of optimizers\n * @param optimizer defines the optimizers to remove\n * @returns the current material\n */\n unregisterOptimizer(optimizer) {\n const index = this._optimizers.indexOf(optimizer);\n if (index === -1) {\n return;\n }\n this._optimizers.splice(index, 1);\n return this;\n }\n /**\n * Add a new block to the list of output nodes\n * @param node defines the node to add\n * @returns the current material\n */\n addOutputNode(node) {\n if (node.target === null) {\n throw \"This node is not meant to be an output node. You may want to explicitly set its target value.\";\n }\n if ((node.target & NodeMaterialBlockTargets.Vertex) !== 0) {\n this._addVertexOutputNode(node);\n }\n if ((node.target & NodeMaterialBlockTargets.Fragment) !== 0) {\n this._addFragmentOutputNode(node);\n }\n return this;\n }\n /**\n * Remove a block from the list of root nodes\n * @param node defines the node to remove\n * @returns the current material\n */\n removeOutputNode(node) {\n if (node.target === null) {\n return this;\n }\n if ((node.target & NodeMaterialBlockTargets.Vertex) !== 0) {\n this._removeVertexOutputNode(node);\n }\n if ((node.target & NodeMaterialBlockTargets.Fragment) !== 0) {\n this._removeFragmentOutputNode(node);\n }\n return this;\n }\n _addVertexOutputNode(node) {\n if (this._vertexOutputNodes.indexOf(node) !== -1) {\n return;\n }\n node.target = NodeMaterialBlockTargets.Vertex;\n this._vertexOutputNodes.push(node);\n return this;\n }\n _removeVertexOutputNode(node) {\n const index = this._vertexOutputNodes.indexOf(node);\n if (index === -1) {\n return;\n }\n this._vertexOutputNodes.splice(index, 1);\n return this;\n }\n _addFragmentOutputNode(node) {\n if (this._fragmentOutputNodes.indexOf(node) !== -1) {\n return;\n }\n node.target = NodeMaterialBlockTargets.Fragment;\n this._fragmentOutputNodes.push(node);\n return this;\n }\n _removeFragmentOutputNode(node) {\n const index = this._fragmentOutputNodes.indexOf(node);\n if (index === -1) {\n return;\n }\n this._fragmentOutputNodes.splice(index, 1);\n return this;\n }\n /**\n * Specifies if the material will require alpha blending\n * @returns a boolean specifying if alpha blending is needed\n */\n needAlphaBlending() {\n if (this.ignoreAlpha) {\n return false;\n }\n return this.forceAlphaBlending || this.alpha < 1.0 || (this._sharedData && this._sharedData.hints.needAlphaBlending);\n }\n /**\n * Specifies if this material should be rendered in alpha test mode\n * @returns a boolean specifying if an alpha test is needed.\n */\n needAlphaTesting() {\n return this._sharedData && this._sharedData.hints.needAlphaTesting;\n }\n _initializeBlock(node, state, nodesToProcessForOtherBuildState, autoConfigure = true) {\n node.initialize(state);\n if (autoConfigure) {\n node.autoConfigure(this);\n }\n node._preparationId = this._buildId;\n if (this.attachedBlocks.indexOf(node) === -1) {\n if (node.isUnique) {\n const className = node.getClassName();\n for (const other of this.attachedBlocks) {\n if (other.getClassName() === className) {\n throw `Cannot have multiple blocks of type ${className} in the same NodeMaterial`;\n }\n }\n }\n this.attachedBlocks.push(node);\n }\n for (const input of node.inputs) {\n input.associatedVariableName = \"\";\n const connectedPoint = input.connectedPoint;\n if (connectedPoint) {\n const block = connectedPoint.ownerBlock;\n if (block !== node) {\n if (block.target === NodeMaterialBlockTargets.VertexAndFragment) {\n nodesToProcessForOtherBuildState.push(block);\n }\n else if (state.target === NodeMaterialBlockTargets.Fragment && block.target === NodeMaterialBlockTargets.Vertex && block._preparationId !== this._buildId) {\n nodesToProcessForOtherBuildState.push(block);\n }\n this._initializeBlock(block, state, nodesToProcessForOtherBuildState, autoConfigure);\n }\n }\n }\n for (const output of node.outputs) {\n output.associatedVariableName = \"\";\n }\n }\n _resetDualBlocks(node, id) {\n if (node.target === NodeMaterialBlockTargets.VertexAndFragment) {\n node.buildId = id;\n }\n for (const inputs of node.inputs) {\n const connectedPoint = inputs.connectedPoint;\n if (connectedPoint) {\n const block = connectedPoint.ownerBlock;\n if (block !== node) {\n this._resetDualBlocks(block, id);\n }\n }\n }\n }\n /**\n * Remove a block from the current node material\n * @param block defines the block to remove\n */\n removeBlock(block) {\n const attachedBlockIndex = this.attachedBlocks.indexOf(block);\n if (attachedBlockIndex > -1) {\n this.attachedBlocks.splice(attachedBlockIndex, 1);\n }\n if (block.isFinalMerger) {\n this.removeOutputNode(block);\n }\n }\n /**\n * Build the material and generates the inner effect\n * @param verbose defines if the build should log activity\n * @param updateBuildId defines if the internal build Id should be updated (default is true)\n * @param autoConfigure defines if the autoConfigure method should be called when initializing blocks (default is true)\n */\n build(verbose = false, updateBuildId = true, autoConfigure = true) {\n this._buildWasSuccessful = false;\n const engine = this.getScene().getEngine();\n const allowEmptyVertexProgram = this._mode === NodeMaterialModes.Particle;\n if (this._vertexOutputNodes.length === 0 && !allowEmptyVertexProgram) {\n throw \"You must define at least one vertexOutputNode\";\n }\n if (this._fragmentOutputNodes.length === 0) {\n throw \"You must define at least one fragmentOutputNode\";\n }\n // Compilation state\n this._vertexCompilationState = new NodeMaterialBuildState();\n this._vertexCompilationState.supportUniformBuffers = engine.supportsUniformBuffers;\n this._vertexCompilationState.target = NodeMaterialBlockTargets.Vertex;\n this._fragmentCompilationState = new NodeMaterialBuildState();\n this._fragmentCompilationState.supportUniformBuffers = engine.supportsUniformBuffers;\n this._fragmentCompilationState.target = NodeMaterialBlockTargets.Fragment;\n // Shared data\n this._sharedData = new NodeMaterialBuildStateSharedData();\n this._sharedData.fragmentOutputNodes = this._fragmentOutputNodes;\n this._vertexCompilationState.sharedData = this._sharedData;\n this._fragmentCompilationState.sharedData = this._sharedData;\n this._sharedData.buildId = this._buildId;\n this._sharedData.emitComments = this._options.emitComments;\n this._sharedData.verbose = verbose;\n this._sharedData.scene = this.getScene();\n this._sharedData.allowEmptyVertexProgram = allowEmptyVertexProgram;\n // Initialize blocks\n const vertexNodes = [];\n const fragmentNodes = [];\n for (const vertexOutputNode of this._vertexOutputNodes) {\n vertexNodes.push(vertexOutputNode);\n this._initializeBlock(vertexOutputNode, this._vertexCompilationState, fragmentNodes, autoConfigure);\n }\n for (const fragmentOutputNode of this._fragmentOutputNodes) {\n fragmentNodes.push(fragmentOutputNode);\n this._initializeBlock(fragmentOutputNode, this._fragmentCompilationState, vertexNodes, autoConfigure);\n }\n // Optimize\n this.optimize();\n // Vertex\n for (const vertexOutputNode of vertexNodes) {\n vertexOutputNode.build(this._vertexCompilationState, vertexNodes);\n }\n // Fragment\n this._fragmentCompilationState.uniforms = this._vertexCompilationState.uniforms.slice(0);\n this._fragmentCompilationState._uniformDeclaration = this._vertexCompilationState._uniformDeclaration;\n this._fragmentCompilationState._constantDeclaration = this._vertexCompilationState._constantDeclaration;\n this._fragmentCompilationState._vertexState = this._vertexCompilationState;\n for (const fragmentOutputNode of fragmentNodes) {\n this._resetDualBlocks(fragmentOutputNode, this._buildId - 1);\n }\n for (const fragmentOutputNode of fragmentNodes) {\n fragmentOutputNode.build(this._fragmentCompilationState, fragmentNodes);\n }\n // Finalize\n this._vertexCompilationState.finalize(this._vertexCompilationState);\n this._fragmentCompilationState.finalize(this._fragmentCompilationState);\n if (updateBuildId) {\n this._buildId = NodeMaterial._BuildIdGenerator++;\n }\n // Errors\n this._sharedData.emitErrors();\n if (verbose) {\n console.log(\"Vertex shader:\");\n console.log(this._vertexCompilationState.compilationString);\n console.log(\"Fragment shader:\");\n console.log(this._fragmentCompilationState.compilationString);\n }\n this._buildWasSuccessful = true;\n this.onBuildObservable.notifyObservers(this);\n // Wipe defines\n const meshes = this.getScene().meshes;\n for (const mesh of meshes) {\n if (!mesh.subMeshes) {\n continue;\n }\n for (const subMesh of mesh.subMeshes) {\n if (subMesh.getMaterial() !== this) {\n continue;\n }\n if (!subMesh.materialDefines) {\n continue;\n }\n const defines = subMesh.materialDefines;\n defines.markAllAsDirty();\n defines.reset();\n }\n }\n }\n /**\n * Runs an otpimization phase to try to improve the shader code\n */\n optimize() {\n for (const optimizer of this._optimizers) {\n optimizer.optimize(this._vertexOutputNodes, this._fragmentOutputNodes);\n }\n }\n _prepareDefinesForAttributes(mesh, defines) {\n const oldNormal = defines[\"NORMAL\"];\n const oldTangent = defines[\"TANGENT\"];\n const oldColor = defines[\"VERTEXCOLOR_NME\"];\n defines[\"NORMAL\"] = mesh.isVerticesDataPresent(VertexBuffer.NormalKind);\n defines[\"TANGENT\"] = mesh.isVerticesDataPresent(VertexBuffer.TangentKind);\n const hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(VertexBuffer.ColorKind);\n defines[\"VERTEXCOLOR_NME\"] = hasVertexColors;\n let uvChanged = false;\n for (let i = 1; i <= 6; ++i) {\n const oldUV = defines[\"UV\" + i];\n defines[\"UV\" + i] = mesh.isVerticesDataPresent(`uv${i === 1 ? \"\" : i}`);\n uvChanged = uvChanged || defines[\"UV\" + i] !== oldUV;\n }\n if (oldNormal !== defines[\"NORMAL\"] || oldTangent !== defines[\"TANGENT\"] || oldColor !== defines[\"VERTEXCOLOR_NME\"] || uvChanged) {\n defines.markAsAttributesDirty();\n }\n }\n /**\n * Create a post process from the material\n * @param camera The camera to apply the render pass to.\n * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param textureFormat Format of textures used when performing the post process. (default: TEXTUREFORMAT_RGBA)\n * @returns the post process created\n */\n createPostProcess(camera, options = 1, samplingMode = 1, engine, reusable, textureType = 0, textureFormat = 5) {\n if (this.mode !== NodeMaterialModes.PostProcess) {\n console.log(\"Incompatible material mode\");\n return null;\n }\n return this._createEffectForPostProcess(null, camera, options, samplingMode, engine, reusable, textureType, textureFormat);\n }\n /**\n * Create the post process effect from the material\n * @param postProcess The post process to create the effect for\n */\n createEffectForPostProcess(postProcess) {\n this._createEffectForPostProcess(postProcess);\n }\n _createEffectForPostProcess(postProcess, camera, options = 1, samplingMode = 1, engine, reusable, textureType = 0, textureFormat = 5) {\n let tempName = this.name + this._buildId;\n const defines = new NodeMaterialDefines();\n const dummyMesh = new AbstractMesh(tempName + \"PostProcess\", this.getScene());\n let buildId = this._buildId;\n this._processDefines(dummyMesh, defines);\n Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString, this._vertexCompilationState._builtCompilationString);\n if (!postProcess) {\n postProcess = new PostProcess(this.name + \"PostProcess\", tempName, this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, options, camera, samplingMode, engine, reusable, defines.toString(), textureType, tempName, { maxSimultaneousLights: this.maxSimultaneousLights }, false, textureFormat);\n }\n else {\n postProcess.updateEffect(defines.toString(), this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, { maxSimultaneousLights: this.maxSimultaneousLights }, undefined, undefined, tempName, tempName);\n }\n postProcess.nodeMaterialSource = this;\n postProcess.onApplyObservable.add((effect) => {\n if (buildId !== this._buildId) {\n delete Effect.ShadersStore[tempName + \"VertexShader\"];\n delete Effect.ShadersStore[tempName + \"PixelShader\"];\n tempName = this.name + this._buildId;\n defines.markAllAsDirty();\n buildId = this._buildId;\n }\n const result = this._processDefines(dummyMesh, defines);\n if (result) {\n Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString, this._vertexCompilationState._builtCompilationString);\n TimingTools.SetImmediate(() => postProcess.updateEffect(defines.toString(), this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, { maxSimultaneousLights: this.maxSimultaneousLights }, undefined, undefined, tempName, tempName));\n }\n this._checkInternals(effect);\n });\n return postProcess;\n }\n /**\n * Create a new procedural texture based on this node material\n * @param size defines the size of the texture\n * @param scene defines the hosting scene\n * @returns the new procedural texture attached to this node material\n */\n createProceduralTexture(size, scene) {\n if (this.mode !== NodeMaterialModes.ProceduralTexture) {\n console.log(\"Incompatible material mode\");\n return null;\n }\n let tempName = this.name + this._buildId;\n const proceduralTexture = new ProceduralTexture(tempName, size, null, scene);\n const dummyMesh = new AbstractMesh(tempName + \"Procedural\", this.getScene());\n dummyMesh.reservedDataStore = {\n hidden: true,\n };\n const defines = new NodeMaterialDefines();\n const result = this._processDefines(dummyMesh, defines);\n Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString, this._vertexCompilationState._builtCompilationString);\n let effect = this.getScene().getEngine().createEffect({\n vertexElement: tempName,\n fragmentElement: tempName,\n }, [VertexBuffer.PositionKind], this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, defines.toString(), result === null || result === void 0 ? void 0 : result.fallbacks, undefined);\n proceduralTexture.nodeMaterialSource = this;\n proceduralTexture._setEffect(effect);\n let buildId = this._buildId;\n proceduralTexture.onBeforeGenerationObservable.add(() => {\n if (buildId !== this._buildId) {\n delete Effect.ShadersStore[tempName + \"VertexShader\"];\n delete Effect.ShadersStore[tempName + \"PixelShader\"];\n tempName = this.name + this._buildId;\n defines.markAllAsDirty();\n buildId = this._buildId;\n }\n const result = this._processDefines(dummyMesh, defines);\n if (result) {\n Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString, this._vertexCompilationState._builtCompilationString);\n TimingTools.SetImmediate(() => {\n effect = this.getScene().getEngine().createEffect({\n vertexElement: tempName,\n fragmentElement: tempName,\n }, [VertexBuffer.PositionKind], this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, defines.toString(), result === null || result === void 0 ? void 0 : result.fallbacks, undefined);\n proceduralTexture._setEffect(effect);\n });\n }\n this._checkInternals(effect);\n });\n return proceduralTexture;\n }\n _createEffectForParticles(particleSystem, blendMode, onCompiled, onError, effect, defines, dummyMesh, particleSystemDefinesJoined = \"\") {\n let tempName = this.name + this._buildId + \"_\" + blendMode;\n if (!defines) {\n defines = new NodeMaterialDefines();\n }\n if (!dummyMesh) {\n dummyMesh = this.getScene().getMeshByName(this.name + \"Particle\");\n if (!dummyMesh) {\n dummyMesh = new AbstractMesh(this.name + \"Particle\", this.getScene());\n dummyMesh.reservedDataStore = {\n hidden: true,\n };\n }\n }\n let buildId = this._buildId;\n const particleSystemDefines = [];\n let join = particleSystemDefinesJoined;\n if (!effect) {\n const result = this._processDefines(dummyMesh, defines);\n Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString);\n particleSystem.fillDefines(particleSystemDefines, blendMode);\n join = particleSystemDefines.join(\"\\n\");\n effect = this.getScene()\n .getEngine()\n .createEffectForParticles(tempName, this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, defines.toString() + \"\\n\" + join, result === null || result === void 0 ? void 0 : result.fallbacks, onCompiled, onError, particleSystem);\n particleSystem.setCustomEffect(effect, blendMode);\n }\n effect.onBindObservable.add((effect) => {\n if (buildId !== this._buildId) {\n delete Effect.ShadersStore[tempName + \"PixelShader\"];\n tempName = this.name + this._buildId + \"_\" + blendMode;\n defines.markAllAsDirty();\n buildId = this._buildId;\n }\n particleSystemDefines.length = 0;\n particleSystem.fillDefines(particleSystemDefines, blendMode);\n const particleSystemDefinesJoinedCurrent = particleSystemDefines.join(\"\\n\");\n if (particleSystemDefinesJoinedCurrent !== join) {\n defines.markAllAsDirty();\n join = particleSystemDefinesJoinedCurrent;\n }\n const result = this._processDefines(dummyMesh, defines);\n if (result) {\n Effect.RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString);\n effect = this.getScene()\n .getEngine()\n .createEffectForParticles(tempName, this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, defines.toString() + \"\\n\" + join, result === null || result === void 0 ? void 0 : result.fallbacks, onCompiled, onError, particleSystem);\n particleSystem.setCustomEffect(effect, blendMode);\n this._createEffectForParticles(particleSystem, blendMode, onCompiled, onError, effect, defines, dummyMesh, particleSystemDefinesJoined); // add the effect.onBindObservable observer\n return;\n }\n this._checkInternals(effect);\n });\n }\n _checkInternals(effect) {\n // Animated blocks\n if (this._sharedData.animatedInputs) {\n const scene = this.getScene();\n const frameId = scene.getFrameId();\n if (this._animationFrame !== frameId) {\n for (const input of this._sharedData.animatedInputs) {\n input.animate(scene);\n }\n this._animationFrame = frameId;\n }\n }\n // Bindable blocks\n for (const block of this._sharedData.bindableBlocks) {\n block.bind(effect, this);\n }\n // Connection points\n for (const inputBlock of this._sharedData.inputBlocks) {\n inputBlock._transmit(effect, this.getScene(), this);\n }\n }\n /**\n * Create the effect to be used as the custom effect for a particle system\n * @param particleSystem Particle system to create the effect for\n * @param onCompiled defines a function to call when the effect creation is successful\n * @param onError defines a function to call when the effect creation has failed\n */\n createEffectForParticles(particleSystem, onCompiled, onError) {\n if (this.mode !== NodeMaterialModes.Particle) {\n console.log(\"Incompatible material mode\");\n return;\n }\n this._createEffectForParticles(particleSystem, BaseParticleSystem.BLENDMODE_ONEONE, onCompiled, onError);\n this._createEffectForParticles(particleSystem, BaseParticleSystem.BLENDMODE_MULTIPLY, onCompiled, onError);\n }\n /**\n * Use this material as the shadow depth wrapper of a target material\n * @param targetMaterial defines the target material\n */\n createAsShadowDepthWrapper(targetMaterial) {\n if (this.mode !== NodeMaterialModes.Material) {\n console.log(\"Incompatible material mode\");\n return;\n }\n targetMaterial.shadowDepthWrapper = new BABYLON.ShadowDepthWrapper(this, this.getScene());\n }\n _processDefines(mesh, defines, useInstances = false, subMesh) {\n let result = null;\n // Global defines\n const scene = this.getScene();\n if (MaterialHelper.PrepareDefinesForCamera(scene, defines)) {\n defines.markAsMiscDirty();\n }\n // Shared defines\n this._sharedData.blocksWithDefines.forEach((b) => {\n b.initializeDefines(mesh, this, defines, useInstances);\n });\n this._sharedData.blocksWithDefines.forEach((b) => {\n b.prepareDefines(mesh, this, defines, useInstances, subMesh);\n });\n // Need to recompile?\n if (defines.isDirty) {\n const lightDisposed = defines._areLightsDisposed;\n defines.markAsProcessed();\n // Repeatable content generators\n this._vertexCompilationState.compilationString = this._vertexCompilationState._builtCompilationString;\n this._fragmentCompilationState.compilationString = this._fragmentCompilationState._builtCompilationString;\n this._sharedData.repeatableContentBlocks.forEach((b) => {\n b.replaceRepeatableContent(this._vertexCompilationState, this._fragmentCompilationState, mesh, defines);\n });\n // Uniforms\n const uniformBuffers = [];\n this._sharedData.dynamicUniformBlocks.forEach((b) => {\n b.updateUniformsAndSamples(this._vertexCompilationState, this, defines, uniformBuffers);\n });\n const mergedUniforms = this._vertexCompilationState.uniforms;\n this._fragmentCompilationState.uniforms.forEach((u) => {\n const index = mergedUniforms.indexOf(u);\n if (index === -1) {\n mergedUniforms.push(u);\n }\n });\n // Samplers\n const mergedSamplers = this._vertexCompilationState.samplers;\n this._fragmentCompilationState.samplers.forEach((s) => {\n const index = mergedSamplers.indexOf(s);\n if (index === -1) {\n mergedSamplers.push(s);\n }\n });\n const fallbacks = new EffectFallbacks();\n this._sharedData.blocksWithFallbacks.forEach((b) => {\n b.provideFallbacks(mesh, fallbacks);\n });\n result = {\n lightDisposed,\n uniformBuffers,\n mergedUniforms,\n mergedSamplers,\n fallbacks,\n };\n }\n return result;\n }\n /**\n * Get if the submesh is ready to be used and all its information available.\n * Child classes can use it to update shaders\n * @param mesh defines the mesh to check\n * @param subMesh defines which submesh to check\n * @param useInstances specifies that instances should be used\n * @returns a boolean indicating that the submesh is ready or not\n */\n isReadyForSubMesh(mesh, subMesh, useInstances = false) {\n if (!this._buildWasSuccessful) {\n return false;\n }\n const scene = this.getScene();\n if (this._sharedData.animatedInputs) {\n const frameId = scene.getFrameId();\n if (this._animationFrame !== frameId) {\n for (const input of this._sharedData.animatedInputs) {\n input.animate(scene);\n }\n this._animationFrame = frameId;\n }\n }\n if (subMesh.effect && this.isFrozen) {\n if (subMesh.effect._wasPreviouslyReady && subMesh.effect._wasPreviouslyUsingInstances === useInstances) {\n return true;\n }\n }\n if (!subMesh.materialDefines) {\n subMesh.materialDefines = new NodeMaterialDefines();\n }\n const defines = subMesh.materialDefines;\n if (this._isReadyForSubMesh(subMesh)) {\n return true;\n }\n const engine = scene.getEngine();\n this._prepareDefinesForAttributes(mesh, defines);\n // Check if blocks are ready\n if (this._sharedData.blockingBlocks.some((b) => !b.isReady(mesh, this, defines, useInstances))) {\n return false;\n }\n const result = this._processDefines(mesh, defines, useInstances, subMesh);\n if (result) {\n const previousEffect = subMesh.effect;\n // Compilation\n const join = defines.toString();\n let effect = engine.createEffect({\n vertex: \"nodeMaterial\" + this._buildId,\n fragment: \"nodeMaterial\" + this._buildId,\n vertexSource: this._vertexCompilationState.compilationString,\n fragmentSource: this._fragmentCompilationState.compilationString,\n }, {\n attributes: this._vertexCompilationState.attributes,\n uniformsNames: result.mergedUniforms,\n uniformBuffersNames: result.uniformBuffers,\n samplers: result.mergedSamplers,\n defines: join,\n fallbacks: result.fallbacks,\n onCompiled: this.onCompiled,\n onError: this.onError,\n indexParameters: { maxSimultaneousLights: this.maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS },\n }, engine);\n if (effect) {\n if (this._onEffectCreatedObservable) {\n onCreatedEffectParameters.effect = effect;\n onCreatedEffectParameters.subMesh = subMesh;\n this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters);\n }\n // Use previous effect while new one is compiling\n if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {\n effect = previousEffect;\n defines.markAsUnprocessed();\n if (result.lightDisposed) {\n // re register in case it takes more than one frame.\n defines._areLightsDisposed = true;\n return false;\n }\n }\n else {\n scene.resetCachedMaterial();\n subMesh.setEffect(effect, defines, this._materialContext);\n }\n }\n }\n if (!subMesh.effect || !subMesh.effect.isReady()) {\n return false;\n }\n defines._renderId = scene.getRenderId();\n subMesh.effect._wasPreviouslyReady = true;\n subMesh.effect._wasPreviouslyUsingInstances = useInstances;\n this._checkScenePerformancePriority();\n return true;\n }\n /**\n * Get a string representing the shaders built by the current node graph\n */\n get compiledShaders() {\n return `// Vertex shader\\r\\n${this._vertexCompilationState.compilationString}\\r\\n\\r\\n// Fragment shader\\r\\n${this._fragmentCompilationState.compilationString}`;\n }\n /**\n * Binds the world matrix to the material\n * @param world defines the world transformation matrix\n */\n bindOnlyWorldMatrix(world) {\n const scene = this.getScene();\n if (!this._activeEffect) {\n return;\n }\n const hints = this._sharedData.hints;\n if (hints.needWorldViewMatrix) {\n world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);\n }\n if (hints.needWorldViewProjectionMatrix) {\n world.multiplyToRef(scene.getTransformMatrix(), this._cachedWorldViewProjectionMatrix);\n }\n // Connection points\n for (const inputBlock of this._sharedData.inputBlocks) {\n inputBlock._transmitWorld(this._activeEffect, world, this._cachedWorldViewMatrix, this._cachedWorldViewProjectionMatrix);\n }\n }\n /**\n * Binds the submesh to this material by preparing the effect and shader to draw\n * @param world defines the world transformation matrix\n * @param mesh defines the mesh containing the submesh\n * @param subMesh defines the submesh to bind the material to\n */\n bindForSubMesh(world, mesh, subMesh) {\n const scene = this.getScene();\n const effect = subMesh.effect;\n if (!effect) {\n return;\n }\n this._activeEffect = effect;\n // Matrices\n this.bindOnlyWorldMatrix(world);\n const mustRebind = this._mustRebind(scene, effect, mesh.visibility);\n const sharedData = this._sharedData;\n if (mustRebind) {\n // Bindable blocks\n for (const block of sharedData.bindableBlocks) {\n block.bind(effect, this, mesh, subMesh);\n }\n for (const block of sharedData.forcedBindableBlocks) {\n block.bind(effect, this, mesh, subMesh);\n }\n // Connection points\n for (const inputBlock of sharedData.inputBlocks) {\n inputBlock._transmit(effect, scene, this);\n }\n }\n else if (!this.isFrozen) {\n for (const block of sharedData.forcedBindableBlocks) {\n block.bind(effect, this, mesh, subMesh);\n }\n }\n this._afterBind(mesh, this._activeEffect);\n }\n /**\n * Gets the active textures from the material\n * @returns an array of textures\n */\n getActiveTextures() {\n const activeTextures = super.getActiveTextures();\n if (this._sharedData) {\n activeTextures.push(...this._sharedData.textureBlocks.filter((tb) => tb.texture).map((tb) => tb.texture));\n }\n return activeTextures;\n }\n /**\n * Gets the list of texture blocks\n * Note that this method will only return blocks that are reachable from the final block(s) and only after the material has been built!\n * @returns an array of texture blocks\n */\n getTextureBlocks() {\n if (!this._sharedData) {\n return [];\n }\n return this._sharedData.textureBlocks;\n }\n /**\n * Gets the list of all texture blocks\n * Note that this method will scan all attachedBlocks and return blocks that are texture blocks\n * @returns\n */\n getAllTextureBlocks() {\n const textureBlocks = [];\n for (const block of this.attachedBlocks) {\n if (NodeMaterial._BlockIsTextureBlock(block)) {\n textureBlocks.push(block);\n }\n }\n return textureBlocks;\n }\n /**\n * Specifies if the material uses a texture\n * @param texture defines the texture to check against the material\n * @returns a boolean specifying if the material uses the texture\n */\n hasTexture(texture) {\n if (super.hasTexture(texture)) {\n return true;\n }\n if (!this._sharedData) {\n return false;\n }\n for (const t of this._sharedData.textureBlocks) {\n if (t.texture === texture) {\n return true;\n }\n }\n return false;\n }\n /**\n * Disposes the material\n * @param forceDisposeEffect specifies if effects should be forcefully disposed\n * @param forceDisposeTextures specifies if textures should be forcefully disposed\n * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh\n */\n dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {\n if (forceDisposeTextures) {\n for (const texture of this.getTextureBlocks()\n .filter((tb) => tb.texture)\n .map((tb) => tb.texture)) {\n texture.dispose();\n }\n }\n for (const block of this.attachedBlocks) {\n block.dispose();\n }\n this.attachedBlocks.length = 0;\n this._sharedData = null;\n this._vertexCompilationState = null;\n this._fragmentCompilationState = null;\n this.onBuildObservable.clear();\n if (this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n this._imageProcessingObserver = null;\n }\n super.dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh);\n }\n /** Creates the node editor window. */\n _createNodeEditor(additionalConfig) {\n const nodeEditorConfig = Object.assign({ nodeMaterial: this }, additionalConfig);\n this.BJSNODEMATERIALEDITOR.NodeEditor.Show(nodeEditorConfig);\n }\n /**\n * Launch the node material editor\n * @param config Define the configuration of the editor\n * @returns a promise fulfilled when the node editor is visible\n */\n edit(config) {\n return new Promise((resolve) => {\n this.BJSNODEMATERIALEDITOR = this.BJSNODEMATERIALEDITOR || this._getGlobalNodeMaterialEditor();\n if (typeof this.BJSNODEMATERIALEDITOR == \"undefined\") {\n const editorUrl = config && config.editorURL ? config.editorURL : NodeMaterial.EditorURL;\n // Load editor and add it to the DOM\n Tools.LoadScript(editorUrl, () => {\n this.BJSNODEMATERIALEDITOR = this.BJSNODEMATERIALEDITOR || this._getGlobalNodeMaterialEditor();\n this._createNodeEditor(config === null || config === void 0 ? void 0 : config.nodeEditorConfig);\n resolve();\n });\n }\n else {\n // Otherwise creates the editor\n this._createNodeEditor(config === null || config === void 0 ? void 0 : config.nodeEditorConfig);\n resolve();\n }\n });\n }\n /**\n * Clear the current material\n */\n clear() {\n this._vertexOutputNodes.length = 0;\n this._fragmentOutputNodes.length = 0;\n this.attachedBlocks.length = 0;\n }\n /**\n * Clear the current material and set it to a default state\n */\n setToDefault() {\n this.clear();\n this.editorData = null;\n const positionInput = new InputBlock(\"Position\");\n positionInput.setAsAttribute(\"position\");\n const worldInput = new InputBlock(\"World\");\n worldInput.setAsSystemValue(NodeMaterialSystemValues.World);\n const worldPos = new TransformBlock(\"WorldPos\");\n positionInput.connectTo(worldPos);\n worldInput.connectTo(worldPos);\n const viewProjectionInput = new InputBlock(\"ViewProjection\");\n viewProjectionInput.setAsSystemValue(NodeMaterialSystemValues.ViewProjection);\n const worldPosdMultipliedByViewProjection = new TransformBlock(\"WorldPos * ViewProjectionTransform\");\n worldPos.connectTo(worldPosdMultipliedByViewProjection);\n viewProjectionInput.connectTo(worldPosdMultipliedByViewProjection);\n const vertexOutput = new VertexOutputBlock(\"VertexOutput\");\n worldPosdMultipliedByViewProjection.connectTo(vertexOutput);\n // Pixel\n const pixelColor = new InputBlock(\"color\");\n pixelColor.value = new Color4(0.8, 0.8, 0.8, 1);\n const fragmentOutput = new FragmentOutputBlock(\"FragmentOutput\");\n pixelColor.connectTo(fragmentOutput);\n // Add to nodes\n this.addOutputNode(vertexOutput);\n this.addOutputNode(fragmentOutput);\n this._mode = NodeMaterialModes.Material;\n }\n /**\n * Clear the current material and set it to a default state for post process\n */\n setToDefaultPostProcess() {\n this.clear();\n this.editorData = null;\n const position = new InputBlock(\"Position\");\n position.setAsAttribute(\"position2d\");\n const const1 = new InputBlock(\"Constant1\");\n const1.isConstant = true;\n const1.value = 1;\n const vmerger = new VectorMergerBlock(\"Position3D\");\n position.connectTo(vmerger);\n const1.connectTo(vmerger, { input: \"w\" });\n const vertexOutput = new VertexOutputBlock(\"VertexOutput\");\n vmerger.connectTo(vertexOutput);\n // Pixel\n const scale = new InputBlock(\"Scale\");\n scale.visibleInInspector = true;\n scale.value = new Vector2(1, 1);\n const uv0 = new RemapBlock(\"uv0\");\n position.connectTo(uv0);\n const uv = new MultiplyBlock(\"UV scale\");\n uv0.connectTo(uv);\n scale.connectTo(uv);\n const currentScreen = new CurrentScreenBlock(\"CurrentScreen\");\n uv.connectTo(currentScreen);\n currentScreen.texture = new Texture(\"https://assets.babylonjs.com/nme/currentScreenPostProcess.png\", this.getScene());\n const fragmentOutput = new FragmentOutputBlock(\"FragmentOutput\");\n currentScreen.connectTo(fragmentOutput, { output: \"rgba\" });\n // Add to nodes\n this.addOutputNode(vertexOutput);\n this.addOutputNode(fragmentOutput);\n this._mode = NodeMaterialModes.PostProcess;\n }\n /**\n * Clear the current material and set it to a default state for procedural texture\n */\n setToDefaultProceduralTexture() {\n this.clear();\n this.editorData = null;\n const position = new InputBlock(\"Position\");\n position.setAsAttribute(\"position2d\");\n const const1 = new InputBlock(\"Constant1\");\n const1.isConstant = true;\n const1.value = 1;\n const vmerger = new VectorMergerBlock(\"Position3D\");\n position.connectTo(vmerger);\n const1.connectTo(vmerger, { input: \"w\" });\n const vertexOutput = new VertexOutputBlock(\"VertexOutput\");\n vmerger.connectTo(vertexOutput);\n // Pixel\n const time = new InputBlock(\"Time\");\n time.value = 0;\n time.min = 0;\n time.max = 0;\n time.isBoolean = false;\n time.matrixMode = 0;\n time.animationType = AnimatedInputBlockTypes.Time;\n time.isConstant = false;\n const color = new InputBlock(\"Color3\");\n color.value = new Color3(1, 1, 1);\n color.isConstant = false;\n const fragmentOutput = new FragmentOutputBlock(\"FragmentOutput\");\n const vectorMerger = new VectorMergerBlock(\"VectorMerger\");\n vectorMerger.visibleInInspector = false;\n const cos = new TrigonometryBlock(\"Cos\");\n cos.operation = TrigonometryBlockOperations.Cos;\n position.connectTo(vectorMerger);\n time.output.connectTo(cos.input);\n cos.output.connectTo(vectorMerger.z);\n vectorMerger.xyzOut.connectTo(fragmentOutput.rgb);\n // Add to nodes\n this.addOutputNode(vertexOutput);\n this.addOutputNode(fragmentOutput);\n this._mode = NodeMaterialModes.ProceduralTexture;\n }\n /**\n * Clear the current material and set it to a default state for particle\n */\n setToDefaultParticle() {\n this.clear();\n this.editorData = null;\n // Pixel\n const uv = new InputBlock(\"uv\");\n uv.setAsAttribute(\"particle_uv\");\n const texture = new ParticleTextureBlock(\"ParticleTexture\");\n uv.connectTo(texture);\n const color = new InputBlock(\"Color\");\n color.setAsAttribute(\"particle_color\");\n const multiply = new MultiplyBlock(\"Texture * Color\");\n texture.connectTo(multiply);\n color.connectTo(multiply);\n const rampGradient = new ParticleRampGradientBlock(\"ParticleRampGradient\");\n multiply.connectTo(rampGradient);\n const cSplitter = new ColorSplitterBlock(\"ColorSplitter\");\n color.connectTo(cSplitter);\n const blendMultiply = new ParticleBlendMultiplyBlock(\"ParticleBlendMultiply\");\n rampGradient.connectTo(blendMultiply);\n texture.connectTo(blendMultiply, { output: \"a\" });\n cSplitter.connectTo(blendMultiply, { output: \"a\" });\n const fragmentOutput = new FragmentOutputBlock(\"FragmentOutput\");\n blendMultiply.connectTo(fragmentOutput);\n // Add to nodes\n this.addOutputNode(fragmentOutput);\n this._mode = NodeMaterialModes.Particle;\n }\n /**\n * Loads the current Node Material from a url pointing to a file save by the Node Material Editor\n * @deprecated Please use NodeMaterial.ParseFromFileAsync instead\n * @param url defines the url to load from\n * @param rootUrl defines the root URL for nested url in the node material\n * @returns a promise that will fulfil when the material is fully loaded\n */\n async loadAsync(url, rootUrl = \"\") {\n return NodeMaterial.ParseFromFileAsync(\"\", url, this.getScene(), rootUrl, true, this);\n }\n _gatherBlocks(rootNode, list) {\n if (list.indexOf(rootNode) !== -1) {\n return;\n }\n list.push(rootNode);\n for (const input of rootNode.inputs) {\n const connectedPoint = input.connectedPoint;\n if (connectedPoint) {\n const block = connectedPoint.ownerBlock;\n if (block !== rootNode) {\n this._gatherBlocks(block, list);\n }\n }\n }\n }\n /**\n * Generate a string containing the code declaration required to create an equivalent of this material\n * @returns a string\n */\n generateCode() {\n let alreadyDumped = [];\n const vertexBlocks = [];\n const uniqueNames = [\"const\", \"var\", \"let\"];\n // Gets active blocks\n for (const outputNode of this._vertexOutputNodes) {\n this._gatherBlocks(outputNode, vertexBlocks);\n }\n const fragmentBlocks = [];\n for (const outputNode of this._fragmentOutputNodes) {\n this._gatherBlocks(outputNode, fragmentBlocks);\n }\n // Generate vertex shader\n let codeString = `var nodeMaterial = new BABYLON.NodeMaterial(\"${this.name || \"node material\"}\");\\r\\n`;\n for (const node of vertexBlocks) {\n if (node.isInput && alreadyDumped.indexOf(node) === -1) {\n codeString += node._dumpCode(uniqueNames, alreadyDumped);\n }\n }\n // Generate fragment shader\n for (const node of fragmentBlocks) {\n if (node.isInput && alreadyDumped.indexOf(node) === -1) {\n codeString += node._dumpCode(uniqueNames, alreadyDumped);\n }\n }\n // Connections\n alreadyDumped = [];\n codeString += \"\\r\\n// Connections\\r\\n\";\n for (const node of this._vertexOutputNodes) {\n codeString += node._dumpCodeForOutputConnections(alreadyDumped);\n }\n for (const node of this._fragmentOutputNodes) {\n codeString += node._dumpCodeForOutputConnections(alreadyDumped);\n }\n // Output nodes\n codeString += \"\\r\\n// Output nodes\\r\\n\";\n for (const node of this._vertexOutputNodes) {\n codeString += `nodeMaterial.addOutputNode(${node._codeVariableName});\\r\\n`;\n }\n for (const node of this._fragmentOutputNodes) {\n codeString += `nodeMaterial.addOutputNode(${node._codeVariableName});\\r\\n`;\n }\n codeString += `nodeMaterial.build();\\r\\n`;\n return codeString;\n }\n /**\n * Serializes this material in a JSON representation\n * @param selectedBlocks\n * @returns the serialized material object\n */\n serialize(selectedBlocks) {\n const serializationObject = selectedBlocks ? {} : SerializationHelper.Serialize(this);\n serializationObject.editorData = JSON.parse(JSON.stringify(this.editorData)); // Copy\n let blocks = [];\n if (selectedBlocks) {\n blocks = selectedBlocks;\n }\n else {\n serializationObject.customType = \"BABYLON.NodeMaterial\";\n serializationObject.outputNodes = [];\n // Outputs\n for (const outputNode of this._vertexOutputNodes) {\n this._gatherBlocks(outputNode, blocks);\n serializationObject.outputNodes.push(outputNode.uniqueId);\n }\n for (const outputNode of this._fragmentOutputNodes) {\n this._gatherBlocks(outputNode, blocks);\n if (serializationObject.outputNodes.indexOf(outputNode.uniqueId) === -1) {\n serializationObject.outputNodes.push(outputNode.uniqueId);\n }\n }\n }\n // Blocks\n serializationObject.blocks = [];\n for (const block of blocks) {\n serializationObject.blocks.push(block.serialize());\n }\n if (!selectedBlocks) {\n for (const block of this.attachedBlocks) {\n if (blocks.indexOf(block) !== -1) {\n continue;\n }\n serializationObject.blocks.push(block.serialize());\n }\n }\n return serializationObject;\n }\n _restoreConnections(block, source, map) {\n for (const outputPoint of block.outputs) {\n for (const candidate of source.blocks) {\n const target = map[candidate.id];\n if (!target) {\n continue;\n }\n for (const input of candidate.inputs) {\n if (map[input.targetBlockId] === block && input.targetConnectionName === outputPoint.name) {\n const inputPoint = target.getInputByName(input.inputName);\n if (!inputPoint || inputPoint.isConnected) {\n continue;\n }\n outputPoint.connectTo(inputPoint, true);\n this._restoreConnections(target, source, map);\n continue;\n }\n }\n }\n }\n }\n /**\n * Clear the current graph and load a new one from a serialization object\n * @param source defines the JSON representation of the material\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @param merge defines whether or not the source must be merged or replace the current content\n */\n parseSerializedObject(source, rootUrl = \"\", merge = false) {\n var _a;\n if (!merge) {\n this.clear();\n }\n const map = {};\n // Create blocks\n for (const parsedBlock of source.blocks) {\n const blockType = GetClass(parsedBlock.customType);\n if (blockType) {\n const block = new blockType();\n block._deserialize(parsedBlock, this.getScene(), rootUrl);\n map[parsedBlock.id] = block;\n this.attachedBlocks.push(block);\n }\n }\n // Connections - Starts with input blocks only (except if in \"merge\" mode where we scan all blocks)\n for (let blockIndex = 0; blockIndex < source.blocks.length; blockIndex++) {\n const parsedBlock = source.blocks[blockIndex];\n const block = map[parsedBlock.id];\n if (!block) {\n continue;\n }\n if (block.inputs.length && !merge) {\n continue;\n }\n this._restoreConnections(block, source, map);\n }\n // Outputs\n if (source.outputNodes) {\n for (const outputNodeId of source.outputNodes) {\n this.addOutputNode(map[outputNodeId]);\n }\n }\n // UI related info\n if (source.locations || (source.editorData && source.editorData.locations)) {\n const locations = source.locations || source.editorData.locations;\n for (const location of locations) {\n if (map[location.blockId]) {\n location.blockId = map[location.blockId].uniqueId;\n }\n }\n if (merge && this.editorData && this.editorData.locations) {\n locations.concat(this.editorData.locations);\n }\n if (source.locations) {\n this.editorData = {\n locations: locations,\n };\n }\n else {\n this.editorData = source.editorData;\n this.editorData.locations = locations;\n }\n const blockMap = [];\n for (const key in map) {\n blockMap[key] = map[key].uniqueId;\n }\n this.editorData.map = blockMap;\n }\n this.comment = source.comment;\n if (source.forceAlphaBlending !== undefined) {\n this.forceAlphaBlending = source.forceAlphaBlending;\n }\n if (!merge) {\n this._mode = (_a = source.mode) !== null && _a !== void 0 ? _a : NodeMaterialModes.Material;\n }\n }\n /**\n * Clear the current graph and load a new one from a serialization object\n * @param source defines the JSON representation of the material\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @param merge defines whether or not the source must be merged or replace the current content\n * @deprecated Please use the parseSerializedObject method instead\n */\n loadFromSerialization(source, rootUrl = \"\", merge = false) {\n this.parseSerializedObject(source, rootUrl, merge);\n }\n /**\n * Makes a duplicate of the current material.\n * @param name defines the name to use for the new material\n * @param shareEffect defines if the clone material should share the same effect (default is false)\n */\n clone(name, shareEffect = false) {\n const serializationObject = this.serialize();\n const clone = SerializationHelper.Clone(() => new NodeMaterial(name, this.getScene(), this.options), this);\n clone.id = name;\n clone.name = name;\n clone.parseSerializedObject(serializationObject);\n clone._buildId = this._buildId;\n clone.build(false, !shareEffect);\n return clone;\n }\n /**\n * Creates a node material from parsed material data\n * @param source defines the JSON representation of the material\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @returns a new node material\n */\n static Parse(source, scene, rootUrl = \"\") {\n const nodeMaterial = SerializationHelper.Parse(() => new NodeMaterial(source.name, scene), source, scene, rootUrl);\n nodeMaterial.parseSerializedObject(source, rootUrl);\n nodeMaterial.build();\n return nodeMaterial;\n }\n /**\n * Creates a node material from a snippet saved in a remote file\n * @param name defines the name of the material to create\n * @param url defines the url to load from\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL for nested url in the node material\n * @param skipBuild defines whether to build the node material\n * @param targetMaterial defines a material to use instead of creating a new one\n * @returns a promise that will resolve to the new node material\n */\n static async ParseFromFileAsync(name, url, scene, rootUrl = \"\", skipBuild = false, targetMaterial) {\n const material = targetMaterial !== null && targetMaterial !== void 0 ? targetMaterial : new NodeMaterial(name, scene);\n const data = await scene._loadFileAsync(url);\n const serializationObject = JSON.parse(data);\n material.parseSerializedObject(serializationObject, rootUrl);\n if (!skipBuild) {\n material.build();\n }\n return material;\n }\n /**\n * Creates a node material from a snippet saved by the node material editor\n * @param snippetId defines the snippet to load\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @param nodeMaterial defines a node material to update (instead of creating a new one)\n * @param skipBuild defines whether to build the node material\n * @returns a promise that will resolve to the new node material\n */\n static ParseFromSnippetAsync(snippetId, scene = EngineStore.LastCreatedScene, rootUrl = \"\", nodeMaterial, skipBuild = false) {\n if (snippetId === \"_BLANK\") {\n return Promise.resolve(NodeMaterial.CreateDefault(\"blank\", scene));\n }\n return new Promise((resolve, reject) => {\n const request = new WebRequest();\n request.addEventListener(\"readystatechange\", () => {\n if (request.readyState == 4) {\n if (request.status == 200) {\n const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload);\n const serializationObject = JSON.parse(snippet.nodeMaterial);\n if (!nodeMaterial) {\n nodeMaterial = SerializationHelper.Parse(() => new NodeMaterial(snippetId, scene), serializationObject, scene, rootUrl);\n nodeMaterial.uniqueId = scene.getUniqueId();\n }\n nodeMaterial.parseSerializedObject(serializationObject);\n nodeMaterial.snippetId = snippetId;\n try {\n if (!skipBuild) {\n nodeMaterial.build();\n }\n resolve(nodeMaterial);\n }\n catch (err) {\n reject(err);\n }\n }\n else {\n reject(\"Unable to load the snippet \" + snippetId);\n }\n }\n });\n request.open(\"GET\", this.SnippetUrl + \"/\" + snippetId.replace(/#/g, \"/\"));\n request.send();\n });\n }\n /**\n * Creates a new node material set to default basic configuration\n * @param name defines the name of the material\n * @param scene defines the hosting scene\n * @returns a new NodeMaterial\n */\n static CreateDefault(name, scene) {\n const newMaterial = new NodeMaterial(name, scene);\n newMaterial.setToDefault();\n newMaterial.build();\n return newMaterial;\n }\n}\nNodeMaterial._BuildIdGenerator = 0;\n/** Define the Url to load node editor script */\nNodeMaterial.EditorURL = `https://unpkg.com/babylonjs-node-editor@${Engine.Version}/babylon.nodeEditor.js`;\n/** Define the Url to load snippets */\nNodeMaterial.SnippetUrl = `https://snippet.babylonjs.com`;\n/** Gets or sets a boolean indicating that node materials should not deserialize textures from json / snippet content */\nNodeMaterial.IgnoreTexturesAtLoadTime = false;\n__decorate([\n serialize()\n], NodeMaterial.prototype, \"ignoreAlpha\", void 0);\n__decorate([\n serialize()\n], NodeMaterial.prototype, \"maxSimultaneousLights\", void 0);\n__decorate([\n serialize(\"mode\")\n], NodeMaterial.prototype, \"_mode\", void 0);\n__decorate([\n serialize(\"comment\")\n], NodeMaterial.prototype, \"comment\", void 0);\n__decorate([\n serialize()\n], NodeMaterial.prototype, \"forceAlphaBlending\", void 0);\nRegisterClass(\"BABYLON.NodeMaterial\", NodeMaterial);\n//# sourceMappingURL=nodeMaterial.js.map","import { Vector3, Vector2 } from \"../../Maths/math.vector.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n/**\n * Creates the VertexData of the IcoSphere\n * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty\n * * radius the radius of the IcoSphere, optional default 1\n * * radiusX allows stretching in the x direction, optional, default radius\n * * radiusY allows stretching in the y direction, optional, default radius\n * * radiusZ allows stretching in the z direction, optional, default radius\n * * flat when true creates a flat shaded mesh, optional, default true\n * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.radius\n * @param options.radiusX\n * @param options.radiusY\n * @param options.radiusZ\n * @param options.flat\n * @param options.subdivisions\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the IcoSphere\n */\nexport function CreateIcoSphereVertexData(options) {\n const sideOrientation = options.sideOrientation || VertexData.DEFAULTSIDE;\n const radius = options.radius || 1;\n const flat = options.flat === undefined ? true : options.flat;\n const subdivisions = options.subdivisions || 4;\n const radiusX = options.radiusX || radius;\n const radiusY = options.radiusY || radius;\n const radiusZ = options.radiusZ || radius;\n const t = (1 + Math.sqrt(5)) / 2;\n // 12 vertex x,y,z\n const icoVertices = [\n -1,\n t,\n -0,\n 1,\n t,\n 0,\n -1,\n -t,\n 0,\n 1,\n -t,\n 0,\n 0,\n -1,\n -t,\n 0,\n 1,\n -t,\n 0,\n -1,\n t,\n 0,\n 1,\n t,\n t,\n 0,\n 1,\n t,\n 0,\n -1,\n -t,\n 0,\n 1,\n -t,\n 0,\n -1, // v8-11\n ];\n // index of 3 vertex makes a face of icopshere\n const ico_indices = [\n 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23, 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8, 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9, 4, 21, 5, 13, 17,\n 23, 6, 13, 22, 19, 6, 18, 9, 8, 1,\n ];\n // vertex for uv have aliased position, not for UV\n const vertices_unalias_id = [\n 0,\n 1,\n 2,\n 3,\n 4,\n 5,\n 6,\n 7,\n 8,\n 9,\n 10,\n 11,\n // vertex alias\n 0,\n 2,\n 3,\n 3,\n 3,\n 4,\n 7,\n 8,\n 9,\n 9,\n 10,\n 11, // 23: B + 12\n ];\n // uv as integer step (not pixels !)\n const ico_vertexuv = [\n 5,\n 1,\n 3,\n 1,\n 6,\n 4,\n 0,\n 0,\n 5,\n 3,\n 4,\n 2,\n 2,\n 2,\n 4,\n 0,\n 2,\n 0,\n 1,\n 1,\n 6,\n 0,\n 6,\n 2,\n // vertex alias (for same vertex on different faces)\n 0,\n 4,\n 3,\n 3,\n 4,\n 4,\n 3,\n 1,\n 4,\n 2,\n 4,\n 4,\n 0,\n 2,\n 1,\n 1,\n 2,\n 2,\n 3,\n 3,\n 1,\n 3,\n 2,\n 4, // 23: B + 12\n ];\n // Vertices[0, 1, ...9, A, B] : position on UV plane\n // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)\n // First island of uv mapping\n // v = 4h 3+ 2\n // v = 3h 9+ 4\n // v = 2h 9+ 5 B\n // v = 1h 9 1 0\n // v = 0h 3 8 7 A\n // u = 0 1 2 3 4 5 6 *a\n // Second island of uv mapping\n // v = 4h 0+ B+ 4+\n // v = 3h A+ 2+\n // v = 2h 7+ 6 3+\n // v = 1h 8+ 3+\n // v = 0h\n // u = 0 1 2 3 4 5 6 *a\n // Face layout on texture UV mapping\n // ============\n // \\ 4 /\\ 16 / ======\n // \\ / \\ / /\\ 11 /\n // \\/ 7 \\/ / \\ /\n // ======= / 10 \\/\n // /\\ 17 /\\ =======\n // / \\ / \\ \\ 15 /\\\n // / 8 \\/ 12 \\ \\ / \\\n // ============ \\/ 6 \\\n // \\ 18 /\\ ============\n // \\ / \\ \\ 5 /\\ 0 /\n // \\/ 13 \\ \\ / \\ /\n // ======= \\/ 1 \\/\n // =============\n // /\\ 19 /\\ 2 /\\\n // / \\ / \\ / \\\n // / 14 \\/ 9 \\/ 3 \\\n // ===================\n // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97\n const ustep = 138 / 1024;\n const vstep = 239 / 1024;\n const uoffset = 60 / 1024;\n const voffset = 26 / 1024;\n // Second island should have margin, not to touch the first island\n // avoid any borderline artefact in pixel rounding\n const island_u_offset = -40 / 1024;\n const island_v_offset = +20 / 1024;\n // face is either island 0 or 1 :\n // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]\n const island = [\n 0,\n 0,\n 0,\n 0,\n 1,\n 0,\n 0,\n 1,\n 1,\n 0,\n 0,\n 0,\n 1,\n 1,\n 0,\n 0,\n 1,\n 1,\n 1,\n 0, // 15 - 19\n ];\n const indices = new Array();\n const positions = new Array();\n const normals = new Array();\n const uvs = new Array();\n let current_indice = 0;\n // prepare array of 3 vector (empty) (to be worked in place, shared for each face)\n const face_vertex_pos = new Array(3);\n const face_vertex_uv = new Array(3);\n let v012;\n for (v012 = 0; v012 < 3; v012++) {\n face_vertex_pos[v012] = Vector3.Zero();\n face_vertex_uv[v012] = Vector2.Zero();\n }\n // create all with normals\n for (let face = 0; face < 20; face++) {\n // 3 vertex per face\n for (v012 = 0; v012 < 3; v012++) {\n // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)\n const v_id = ico_indices[3 * face + v012];\n // vertex have 3D position (x,y,z)\n face_vertex_pos[v012].copyFromFloats(icoVertices[3 * vertices_unalias_id[v_id]], icoVertices[3 * vertices_unalias_id[v_id] + 1], icoVertices[3 * vertices_unalias_id[v_id] + 2]);\n // Normalize to get normal\n face_vertex_pos[v012].normalize();\n // uv Coordinates from vertex ID\n face_vertex_uv[v012].copyFromFloats(ico_vertexuv[2 * v_id] * ustep + uoffset + island[face] * island_u_offset, ico_vertexuv[2 * v_id + 1] * vstep + voffset + island[face] * island_v_offset);\n }\n // Subdivide the face (interpolate pos, norm, uv)\n // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)\n // - norm is linear interpolation of vertex corner normal\n // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )\n // - uv is linear interpolation\n //\n // Topology is as below for sub-divide by 2\n // vertex shown as v0,v1,v2\n // interp index is i1 to progress in range [v0,v1[\n // interp index is i2 to progress in range [v0,v2[\n // face index as (i1,i2) for /\\ : (i1,i2),(i1+1,i2),(i1,i2+1)\n // and (i1,i2)' for \\/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)\n //\n //\n // i2 v2\n // ^ ^\n // / / \\\n // / / \\\n // / / \\\n // / / (0,1) \\\n // / #---------\\\n // / / \\ (0,0)'/ \\\n // / / \\ / \\\n // / / \\ / \\\n // / / (0,0) \\ / (1,0) \\\n // / #---------#---------\\\n // v0 v1\n //\n // --------------------> i1\n //\n // interp of (i1,i2):\n // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)\n // along i1 : lerp(x0,x1, i1/(S-i2))\n //\n // centroid of triangle is needed to get help normal computation\n // (c1,c2) are used for centroid location\n const interp_vertex = (i1, i2, c1, c2) => {\n // vertex is interpolated from\n // - face_vertex_pos[0..2]\n // - face_vertex_uv[0..2]\n const pos_x0 = Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);\n const pos_x1 = Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);\n const pos_interp = subdivisions === i2 ? face_vertex_pos[2] : Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));\n pos_interp.normalize();\n let vertex_normal;\n if (flat) {\n // in flat mode, recalculate normal as face centroid normal\n const centroid_x0 = Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);\n const centroid_x1 = Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);\n vertex_normal = Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));\n }\n else {\n // in smooth mode, recalculate normal from each single vertex position\n vertex_normal = new Vector3(pos_interp.x, pos_interp.y, pos_interp.z);\n }\n // Vertex normal need correction due to X,Y,Z radius scaling\n vertex_normal.x /= radiusX;\n vertex_normal.y /= radiusY;\n vertex_normal.z /= radiusZ;\n vertex_normal.normalize();\n const uv_x0 = Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);\n const uv_x1 = Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);\n const uv_interp = subdivisions === i2 ? face_vertex_uv[2] : Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));\n positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);\n normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);\n uvs.push(uv_interp.x, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - uv_interp.y : uv_interp.y);\n // push each vertex has member of a face\n // Same vertex can belong to multiple face, it is pushed multiple time (duplicate vertex are present)\n indices.push(current_indice);\n current_indice++;\n };\n for (let i2 = 0; i2 < subdivisions; i2++) {\n for (let i1 = 0; i1 + i2 < subdivisions; i1++) {\n // face : (i1,i2) for /\\ :\n // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)\n interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);\n interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);\n interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);\n if (i1 + i2 + 1 < subdivisions) {\n // face : (i1,i2)' for \\/ :\n // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)\n interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);\n interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);\n interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);\n }\n }\n }\n }\n // Sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Result\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n}\n/**\n * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided\n * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)\n * * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value of `radius`)\n * * The parameter `subdivisions` sets the number of subdivisions (positive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size\n * * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.radius\n * @param options.radiusX\n * @param options.radiusY\n * @param options.radiusZ\n * @param options.flat\n * @param options.subdivisions\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.updatable\n * @param scene defines the hosting scene\n * @returns the icosahedron mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/polyhedra#icosphere\n */\nexport function CreateIcoSphere(name, options = {}, scene = null) {\n const sphere = new Mesh(name, scene);\n options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n sphere._originalBuilderSideOrientation = options.sideOrientation;\n const vertexData = CreateIcoSphereVertexData(options);\n vertexData.applyToMesh(sphere, options.updatable);\n return sphere;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use the function directly from the module\n */\nexport const IcoSphereBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateIcoSphere,\n};\nVertexData.CreateIcoSphere = CreateIcoSphereVertexData;\nMesh.CreateIcoSphere = (name, options, scene) => {\n return CreateIcoSphere(name, options, scene);\n};\n//# sourceMappingURL=icoSphereBuilder.js.map","import { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nimport { WebXRFeatureName, WebXRFeaturesManager } from \"../webXRFeaturesManager.js\";\nimport { Matrix, Quaternion } from \"../../Maths/math.vector.js\";\nimport { PhysicsImpostor } from \"../../Physics/v1/physicsImpostor.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { SceneLoader } from \"../../Loading/sceneLoader.js\";\nimport { Color3 } from \"../../Maths/math.color.js\";\nimport { NodeMaterial } from \"../../Materials/Node/nodeMaterial.js\";\nimport { Material } from \"../../Materials/material.js\";\nimport { CreateIcoSphere } from \"../../Meshes/Builders/icoSphereBuilder.js\";\nimport { TransformNode } from \"../../Meshes/transformNode.js\";\nimport { Axis } from \"../../Maths/math.axis.js\";\nimport { EngineStore } from \"../../Engines/engineStore.js\";\n\n/**\n * Parts of the hands divided to writs and finger names\n */\nexport var HandPart;\n(function (HandPart) {\n /**\n * HandPart - Wrist\n */\n HandPart[\"WRIST\"] = \"wrist\";\n /**\n * HandPart - The thumb\n */\n HandPart[\"THUMB\"] = \"thumb\";\n /**\n * HandPart - Index finger\n */\n HandPart[\"INDEX\"] = \"index\";\n /**\n * HandPart - Middle finger\n */\n HandPart[\"MIDDLE\"] = \"middle\";\n /**\n * HandPart - Ring finger\n */\n HandPart[\"RING\"] = \"ring\";\n /**\n * HandPart - Little finger\n */\n HandPart[\"LITTLE\"] = \"little\";\n})(HandPart || (HandPart = {}));\n/**\n * Joints of the hand as defined by the WebXR specification.\n * https://immersive-web.github.io/webxr-hand-input/#skeleton-joints-section\n */\nexport var WebXRHandJoint;\n(function (WebXRHandJoint) {\n /** Wrist */\n WebXRHandJoint[\"WRIST\"] = \"wrist\";\n /** Thumb near wrist */\n WebXRHandJoint[\"THUMB_METACARPAL\"] = \"thumb-metacarpal\";\n /** Thumb first knuckle */\n WebXRHandJoint[\"THUMB_PHALANX_PROXIMAL\"] = \"thumb-phalanx-proximal\";\n /** Thumb second knuckle */\n WebXRHandJoint[\"THUMB_PHALANX_DISTAL\"] = \"thumb-phalanx-distal\";\n /** Thumb tip */\n WebXRHandJoint[\"THUMB_TIP\"] = \"thumb-tip\";\n /** Index finger near wrist */\n WebXRHandJoint[\"INDEX_FINGER_METACARPAL\"] = \"index-finger-metacarpal\";\n /** Index finger first knuckle */\n WebXRHandJoint[\"INDEX_FINGER_PHALANX_PROXIMAL\"] = \"index-finger-phalanx-proximal\";\n /** Index finger second knuckle */\n WebXRHandJoint[\"INDEX_FINGER_PHALANX_INTERMEDIATE\"] = \"index-finger-phalanx-intermediate\";\n /** Index finger third knuckle */\n WebXRHandJoint[\"INDEX_FINGER_PHALANX_DISTAL\"] = \"index-finger-phalanx-distal\";\n /** Index finger tip */\n WebXRHandJoint[\"INDEX_FINGER_TIP\"] = \"index-finger-tip\";\n /** Middle finger near wrist */\n WebXRHandJoint[\"MIDDLE_FINGER_METACARPAL\"] = \"middle-finger-metacarpal\";\n /** Middle finger first knuckle */\n WebXRHandJoint[\"MIDDLE_FINGER_PHALANX_PROXIMAL\"] = \"middle-finger-phalanx-proximal\";\n /** Middle finger second knuckle */\n WebXRHandJoint[\"MIDDLE_FINGER_PHALANX_INTERMEDIATE\"] = \"middle-finger-phalanx-intermediate\";\n /** Middle finger third knuckle */\n WebXRHandJoint[\"MIDDLE_FINGER_PHALANX_DISTAL\"] = \"middle-finger-phalanx-distal\";\n /** Middle finger tip */\n WebXRHandJoint[\"MIDDLE_FINGER_TIP\"] = \"middle-finger-tip\";\n /** Ring finger near wrist */\n WebXRHandJoint[\"RING_FINGER_METACARPAL\"] = \"ring-finger-metacarpal\";\n /** Ring finger first knuckle */\n WebXRHandJoint[\"RING_FINGER_PHALANX_PROXIMAL\"] = \"ring-finger-phalanx-proximal\";\n /** Ring finger second knuckle */\n WebXRHandJoint[\"RING_FINGER_PHALANX_INTERMEDIATE\"] = \"ring-finger-phalanx-intermediate\";\n /** Ring finger third knuckle */\n WebXRHandJoint[\"RING_FINGER_PHALANX_DISTAL\"] = \"ring-finger-phalanx-distal\";\n /** Ring finger tip */\n WebXRHandJoint[\"RING_FINGER_TIP\"] = \"ring-finger-tip\";\n /** Pinky finger near wrist */\n WebXRHandJoint[\"PINKY_FINGER_METACARPAL\"] = \"pinky-finger-metacarpal\";\n /** Pinky finger first knuckle */\n WebXRHandJoint[\"PINKY_FINGER_PHALANX_PROXIMAL\"] = \"pinky-finger-phalanx-proximal\";\n /** Pinky finger second knuckle */\n WebXRHandJoint[\"PINKY_FINGER_PHALANX_INTERMEDIATE\"] = \"pinky-finger-phalanx-intermediate\";\n /** Pinky finger third knuckle */\n WebXRHandJoint[\"PINKY_FINGER_PHALANX_DISTAL\"] = \"pinky-finger-phalanx-distal\";\n /** Pinky finger tip */\n WebXRHandJoint[\"PINKY_FINGER_TIP\"] = \"pinky-finger-tip\";\n})(WebXRHandJoint || (WebXRHandJoint = {}));\nconst handJointReferenceArray = [\n WebXRHandJoint.WRIST,\n WebXRHandJoint.THUMB_METACARPAL,\n WebXRHandJoint.THUMB_PHALANX_PROXIMAL,\n WebXRHandJoint.THUMB_PHALANX_DISTAL,\n WebXRHandJoint.THUMB_TIP,\n WebXRHandJoint.INDEX_FINGER_METACARPAL,\n WebXRHandJoint.INDEX_FINGER_PHALANX_PROXIMAL,\n WebXRHandJoint.INDEX_FINGER_PHALANX_INTERMEDIATE,\n WebXRHandJoint.INDEX_FINGER_PHALANX_DISTAL,\n WebXRHandJoint.INDEX_FINGER_TIP,\n WebXRHandJoint.MIDDLE_FINGER_METACARPAL,\n WebXRHandJoint.MIDDLE_FINGER_PHALANX_PROXIMAL,\n WebXRHandJoint.MIDDLE_FINGER_PHALANX_INTERMEDIATE,\n WebXRHandJoint.MIDDLE_FINGER_PHALANX_DISTAL,\n WebXRHandJoint.MIDDLE_FINGER_TIP,\n WebXRHandJoint.RING_FINGER_METACARPAL,\n WebXRHandJoint.RING_FINGER_PHALANX_PROXIMAL,\n WebXRHandJoint.RING_FINGER_PHALANX_INTERMEDIATE,\n WebXRHandJoint.RING_FINGER_PHALANX_DISTAL,\n WebXRHandJoint.RING_FINGER_TIP,\n WebXRHandJoint.PINKY_FINGER_METACARPAL,\n WebXRHandJoint.PINKY_FINGER_PHALANX_PROXIMAL,\n WebXRHandJoint.PINKY_FINGER_PHALANX_INTERMEDIATE,\n WebXRHandJoint.PINKY_FINGER_PHALANX_DISTAL,\n WebXRHandJoint.PINKY_FINGER_TIP,\n];\nconst handPartsDefinition = {\n [HandPart.WRIST]: [WebXRHandJoint.WRIST],\n [HandPart.THUMB]: [WebXRHandJoint.THUMB_METACARPAL, WebXRHandJoint.THUMB_PHALANX_PROXIMAL, WebXRHandJoint.THUMB_PHALANX_DISTAL, WebXRHandJoint.THUMB_TIP],\n [HandPart.INDEX]: [\n WebXRHandJoint.INDEX_FINGER_METACARPAL,\n WebXRHandJoint.INDEX_FINGER_PHALANX_PROXIMAL,\n WebXRHandJoint.INDEX_FINGER_PHALANX_INTERMEDIATE,\n WebXRHandJoint.INDEX_FINGER_PHALANX_DISTAL,\n WebXRHandJoint.INDEX_FINGER_TIP,\n ],\n [HandPart.MIDDLE]: [\n WebXRHandJoint.MIDDLE_FINGER_METACARPAL,\n WebXRHandJoint.MIDDLE_FINGER_PHALANX_PROXIMAL,\n WebXRHandJoint.MIDDLE_FINGER_PHALANX_INTERMEDIATE,\n WebXRHandJoint.MIDDLE_FINGER_PHALANX_DISTAL,\n WebXRHandJoint.MIDDLE_FINGER_TIP,\n ],\n [HandPart.RING]: [\n WebXRHandJoint.RING_FINGER_METACARPAL,\n WebXRHandJoint.RING_FINGER_PHALANX_PROXIMAL,\n WebXRHandJoint.RING_FINGER_PHALANX_INTERMEDIATE,\n WebXRHandJoint.RING_FINGER_PHALANX_DISTAL,\n WebXRHandJoint.RING_FINGER_TIP,\n ],\n [HandPart.LITTLE]: [\n WebXRHandJoint.PINKY_FINGER_METACARPAL,\n WebXRHandJoint.PINKY_FINGER_PHALANX_PROXIMAL,\n WebXRHandJoint.PINKY_FINGER_PHALANX_INTERMEDIATE,\n WebXRHandJoint.PINKY_FINGER_PHALANX_DISTAL,\n WebXRHandJoint.PINKY_FINGER_TIP,\n ],\n};\n/**\n * Representing a single hand (with its corresponding native XRHand object)\n */\nexport class WebXRHand {\n /**\n * Get the hand mesh.\n */\n get handMesh() {\n return this._handMesh;\n }\n /**\n * Get meshes of part of the hand.\n * @param part The part of hand to get.\n * @returns An array of meshes that correlate to the hand part requested.\n */\n getHandPartMeshes(part) {\n return handPartsDefinition[part].map((name) => this._jointMeshes[handJointReferenceArray.indexOf(name)]);\n }\n /**\n * Retrieves a mesh linked to a named joint in the hand.\n * @param jointName The name of the joint.\n * @returns An AbstractMesh whose position corresponds with the joint position.\n */\n getJointMesh(jointName) {\n return this._jointMeshes[handJointReferenceArray.indexOf(jointName)];\n }\n /**\n * Construct a new hand object\n * @param xrController The controller to which the hand correlates.\n * @param _jointMeshes The meshes to be used to track the hand joints.\n * @param _handMesh An optional hand mesh.\n * @param rigMapping An optional rig mapping for the hand mesh.\n * If not provided (but a hand mesh is provided),\n * it will be assumed that the hand mesh's bones are named\n * directly after the WebXR bone names.\n * @param _leftHandedMeshes Are the hand meshes left-handed-system meshes\n * @param _jointsInvisible Are the tracked joint meshes visible\n * @param _jointScaleFactor Scale factor for all joint meshes\n */\n constructor(\n /** The controller to which the hand correlates. */\n xrController, _jointMeshes, _handMesh, \n /** An optional rig mapping for the hand mesh. If not provided (but a hand mesh is provided),\n * it will be assumed that the hand mesh's bones are named directly after the WebXR bone names. */\n rigMapping, _leftHandedMeshes = false, _jointsInvisible = false, _jointScaleFactor = 1) {\n this.xrController = xrController;\n this._jointMeshes = _jointMeshes;\n this._handMesh = _handMesh;\n this.rigMapping = rigMapping;\n this._leftHandedMeshes = _leftHandedMeshes;\n this._jointsInvisible = _jointsInvisible;\n this._jointScaleFactor = _jointScaleFactor;\n /**\n * Transform nodes that will directly receive the transforms from the WebXR matrix data.\n */\n this._jointTransforms = new Array(handJointReferenceArray.length);\n /**\n * The float array that will directly receive the transform matrix data from WebXR.\n */\n this._jointTransformMatrices = new Float32Array(handJointReferenceArray.length * 16);\n this._tempJointMatrix = new Matrix();\n /**\n * The float array that will directly receive the joint radii from WebXR.\n */\n this._jointRadii = new Float32Array(handJointReferenceArray.length);\n this._scene = _jointMeshes[0].getScene();\n // Initialize the joint transform quaternions and link the transforms to the bones.\n for (let jointIdx = 0; jointIdx < this._jointTransforms.length; jointIdx++) {\n const jointTransform = (this._jointTransforms[jointIdx] = new TransformNode(handJointReferenceArray[jointIdx], this._scene));\n jointTransform.rotationQuaternion = new Quaternion();\n // Set the rotation quaternion so we can use it later for tracking.\n _jointMeshes[jointIdx].rotationQuaternion = new Quaternion();\n }\n if (_handMesh) {\n // Note that this logic needs to happen after we initialize the joint tracking transform nodes.\n this.setHandMesh(_handMesh, rigMapping);\n }\n // hide the motion controller, if available/loaded\n if (this.xrController.motionController) {\n if (this.xrController.motionController.rootMesh) {\n this.xrController.motionController.rootMesh.setEnabled(false);\n }\n else {\n this.xrController.motionController.onModelLoadedObservable.add((controller) => {\n if (controller.rootMesh) {\n controller.rootMesh.setEnabled(false);\n }\n });\n }\n }\n this.xrController.onMotionControllerInitObservable.add((motionController) => {\n motionController.onModelLoadedObservable.add((controller) => {\n if (controller.rootMesh) {\n controller.rootMesh.setEnabled(false);\n }\n });\n if (motionController.rootMesh) {\n motionController.rootMesh.setEnabled(false);\n }\n });\n }\n /**\n * Sets the current hand mesh to render for the WebXRHand.\n * @param handMesh The rigged hand mesh that will be tracked to the user's hand.\n * @param rigMapping The mapping from XRHandJoint to bone names to use with the mesh.\n */\n setHandMesh(handMesh, rigMapping) {\n this._handMesh = handMesh;\n // Avoid any strange frustum culling. We will manually control visibility via attach and detach.\n handMesh.alwaysSelectAsActiveMesh = true;\n handMesh.getChildMeshes().forEach((mesh) => (mesh.alwaysSelectAsActiveMesh = true));\n // Link the bones in the hand mesh to the transform nodes that will be bound to the WebXR tracked joints.\n if (this._handMesh.skeleton) {\n const handMeshSkeleton = this._handMesh.skeleton;\n handJointReferenceArray.forEach((jointName, jointIdx) => {\n const jointBoneIdx = handMeshSkeleton.getBoneIndexByName(rigMapping ? rigMapping[jointName] : jointName);\n if (jointBoneIdx !== -1) {\n handMeshSkeleton.bones[jointBoneIdx].linkTransformNode(this._jointTransforms[jointIdx]);\n }\n });\n }\n }\n /**\n * Update this hand from the latest xr frame.\n * @param xrFrame The latest frame received from WebXR.\n * @param referenceSpace The current viewer reference space.\n */\n updateFromXRFrame(xrFrame, referenceSpace) {\n const hand = this.xrController.inputSource.hand;\n if (!hand) {\n return;\n }\n // TODO: Modify webxr.d.ts to better match WebXR IDL so we don't need this any cast.\n const anyHand = hand;\n const jointSpaces = handJointReferenceArray.map((jointName) => anyHand[jointName] || hand.get(jointName));\n let trackingSuccessful = false;\n if (xrFrame.fillPoses && xrFrame.fillJointRadii) {\n trackingSuccessful = xrFrame.fillPoses(jointSpaces, referenceSpace, this._jointTransformMatrices) && xrFrame.fillJointRadii(jointSpaces, this._jointRadii);\n }\n else if (xrFrame.getJointPose) {\n trackingSuccessful = true;\n // Warning: This codepath is slow by comparison, only here for compat.\n for (let jointIdx = 0; jointIdx < jointSpaces.length; jointIdx++) {\n const jointPose = xrFrame.getJointPose(jointSpaces[jointIdx], referenceSpace);\n if (jointPose) {\n this._jointTransformMatrices.set(jointPose.transform.matrix, jointIdx * 16);\n this._jointRadii[jointIdx] = jointPose.radius || 0.008;\n }\n else {\n trackingSuccessful = false;\n break;\n }\n }\n }\n if (!trackingSuccessful) {\n return;\n }\n handJointReferenceArray.forEach((_jointName, jointIdx) => {\n const jointTransform = this._jointTransforms[jointIdx];\n Matrix.FromArrayToRef(this._jointTransformMatrices, jointIdx * 16, this._tempJointMatrix);\n this._tempJointMatrix.decompose(undefined, jointTransform.rotationQuaternion, jointTransform.position);\n // The radius we need to make the joint in order for it to roughly cover the joints of the user's real hand.\n const scaledJointRadius = this._jointRadii[jointIdx] * this._jointScaleFactor;\n const jointMesh = this._jointMeshes[jointIdx];\n jointMesh.isVisible = !this._handMesh && !this._jointsInvisible;\n jointMesh.position.copyFrom(jointTransform.position);\n jointMesh.rotationQuaternion.copyFrom(jointTransform.rotationQuaternion);\n jointMesh.scaling.setAll(scaledJointRadius);\n // The WebXR data comes as right-handed, so we might need to do some conversions.\n if (!this._scene.useRightHandedSystem) {\n jointMesh.position.z *= -1;\n jointMesh.rotationQuaternion.z *= -1;\n jointMesh.rotationQuaternion.w *= -1;\n if (this._leftHandedMeshes && this._handMesh) {\n jointTransform.position.z *= -1;\n jointTransform.rotationQuaternion.z *= -1;\n jointTransform.rotationQuaternion.w *= -1;\n }\n }\n });\n if (this._handMesh) {\n this._handMesh.isVisible = true;\n }\n }\n /**\n * Dispose this Hand object\n */\n dispose() {\n if (this._handMesh) {\n this._handMesh.isVisible = false;\n }\n }\n}\n/**\n * WebXR Hand Joint tracking feature, available for selected browsers and devices\n */\nexport class WebXRHandTracking extends WebXRAbstractFeature {\n static _GenerateTrackedJointMeshes(featureOptions) {\n const meshes = {};\n [\"left\", \"right\"].map((handedness) => {\n var _a, _b, _c, _d, _e;\n const trackedMeshes = [];\n const originalMesh = ((_a = featureOptions.jointMeshes) === null || _a === void 0 ? void 0 : _a.sourceMesh) || CreateIcoSphere(\"jointParent\", WebXRHandTracking._ICOSPHERE_PARAMS);\n originalMesh.isVisible = !!((_b = featureOptions.jointMeshes) === null || _b === void 0 ? void 0 : _b.keepOriginalVisible);\n for (let i = 0; i < handJointReferenceArray.length; ++i) {\n let newInstance = originalMesh.createInstance(`${handedness}-handJoint-${i}`);\n if ((_c = featureOptions.jointMeshes) === null || _c === void 0 ? void 0 : _c.onHandJointMeshGenerated) {\n const returnedMesh = featureOptions.jointMeshes.onHandJointMeshGenerated(newInstance, i, handedness);\n if (returnedMesh) {\n if (returnedMesh !== newInstance) {\n newInstance.dispose();\n newInstance = returnedMesh;\n }\n }\n }\n newInstance.isPickable = false;\n if ((_d = featureOptions.jointMeshes) === null || _d === void 0 ? void 0 : _d.enablePhysics) {\n const props = ((_e = featureOptions.jointMeshes) === null || _e === void 0 ? void 0 : _e.physicsProps) || {};\n // downscale the instances so that physics will be initialized correctly\n newInstance.scaling.setAll(0.02);\n const type = props.impostorType !== undefined ? props.impostorType : PhysicsImpostor.SphereImpostor;\n newInstance.physicsImpostor = new PhysicsImpostor(newInstance, type, Object.assign({ mass: 0 }, props));\n }\n newInstance.rotationQuaternion = new Quaternion();\n newInstance.isVisible = false;\n trackedMeshes.push(newInstance);\n }\n meshes[handedness] = trackedMeshes;\n });\n return { left: meshes.left, right: meshes.right };\n }\n static _GenerateDefaultHandMeshesAsync(scene, options) {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve) => {\n var _a, _b, _c, _d, _e;\n const riggedMeshes = {};\n // check the cache, defensive\n if ((_b = (_a = WebXRHandTracking._RightHandGLB) === null || _a === void 0 ? void 0 : _a.meshes[1]) === null || _b === void 0 ? void 0 : _b.isDisposed()) {\n WebXRHandTracking._RightHandGLB = null;\n }\n if ((_d = (_c = WebXRHandTracking._LeftHandGLB) === null || _c === void 0 ? void 0 : _c.meshes[1]) === null || _d === void 0 ? void 0 : _d.isDisposed()) {\n WebXRHandTracking._LeftHandGLB = null;\n }\n const handsDefined = !!(WebXRHandTracking._RightHandGLB && WebXRHandTracking._LeftHandGLB);\n // load them in parallel\n const handGLBs = await Promise.all([\n WebXRHandTracking._RightHandGLB ||\n SceneLoader.ImportMeshAsync(\"\", WebXRHandTracking.DEFAULT_HAND_MODEL_BASE_URL, WebXRHandTracking.DEFAULT_HAND_MODEL_RIGHT_FILENAME, scene),\n WebXRHandTracking._LeftHandGLB ||\n SceneLoader.ImportMeshAsync(\"\", WebXRHandTracking.DEFAULT_HAND_MODEL_BASE_URL, WebXRHandTracking.DEFAULT_HAND_MODEL_LEFT_FILENAME, scene),\n ]);\n WebXRHandTracking._RightHandGLB = handGLBs[0];\n WebXRHandTracking._LeftHandGLB = handGLBs[1];\n const handShader = new NodeMaterial(\"handShader\", scene, { emitComments: false });\n await handShader.loadAsync(WebXRHandTracking.DEFAULT_HAND_MODEL_SHADER_URL);\n // depth prepass and alpha mode\n handShader.needDepthPrePass = true;\n handShader.transparencyMode = Material.MATERIAL_ALPHABLEND;\n handShader.alphaMode = 2;\n // build node materials\n handShader.build(false);\n // shader\n const handColors = Object.assign({ base: Color3.FromInts(116, 63, 203), fresnel: Color3.FromInts(149, 102, 229), fingerColor: Color3.FromInts(177, 130, 255), tipFresnel: Color3.FromInts(220, 200, 255) }, (_e = options === null || options === void 0 ? void 0 : options.handMeshes) === null || _e === void 0 ? void 0 : _e.customColors);\n const handNodes = {\n base: handShader.getBlockByName(\"baseColor\"),\n fresnel: handShader.getBlockByName(\"fresnelColor\"),\n fingerColor: handShader.getBlockByName(\"fingerColor\"),\n tipFresnel: handShader.getBlockByName(\"tipFresnelColor\"),\n };\n handNodes.base.value = handColors.base;\n handNodes.fresnel.value = handColors.fresnel;\n handNodes.fingerColor.value = handColors.fingerColor;\n handNodes.tipFresnel.value = handColors.tipFresnel;\n [\"left\", \"right\"].forEach((handedness) => {\n const handGLB = handedness == \"left\" ? WebXRHandTracking._LeftHandGLB : WebXRHandTracking._RightHandGLB;\n if (!handGLB) {\n // this should never happen!\n throw new Error(\"Could not load hand model\");\n }\n const handMesh = handGLB.meshes[1];\n handMesh._internalAbstractMeshDataInfo._computeBonesUsingShaders = true;\n handMesh.material = handShader.clone(`${handedness}HandShaderClone`, true);\n handMesh.isVisible = false;\n riggedMeshes[handedness] = handMesh;\n // single change for left handed systems\n if (!handsDefined && !scene.useRightHandedSystem) {\n handGLB.meshes[1].rotate(Axis.Y, Math.PI);\n }\n });\n handShader.dispose();\n resolve({ left: riggedMeshes.left, right: riggedMeshes.right });\n });\n }\n /**\n * Generates a mapping from XRHandJoint to bone name for the default hand mesh.\n * @param handedness The handedness being mapped for.\n */\n static _GenerateDefaultHandMeshRigMapping(handedness) {\n const H = handedness == \"right\" ? \"R\" : \"L\";\n return {\n [WebXRHandJoint.WRIST]: `wrist_${H}`,\n [WebXRHandJoint.THUMB_METACARPAL]: `thumb_metacarpal_${H}`,\n [WebXRHandJoint.THUMB_PHALANX_PROXIMAL]: `thumb_proxPhalanx_${H}`,\n [WebXRHandJoint.THUMB_PHALANX_DISTAL]: `thumb_distPhalanx_${H}`,\n [WebXRHandJoint.THUMB_TIP]: `thumb_tip_${H}`,\n [WebXRHandJoint.INDEX_FINGER_METACARPAL]: `index_metacarpal_${H}`,\n [WebXRHandJoint.INDEX_FINGER_PHALANX_PROXIMAL]: `index_proxPhalanx_${H}`,\n [WebXRHandJoint.INDEX_FINGER_PHALANX_INTERMEDIATE]: `index_intPhalanx_${H}`,\n [WebXRHandJoint.INDEX_FINGER_PHALANX_DISTAL]: `index_distPhalanx_${H}`,\n [WebXRHandJoint.INDEX_FINGER_TIP]: `index_tip_${H}`,\n [WebXRHandJoint.MIDDLE_FINGER_METACARPAL]: `middle_metacarpal_${H}`,\n [WebXRHandJoint.MIDDLE_FINGER_PHALANX_PROXIMAL]: `middle_proxPhalanx_${H}`,\n [WebXRHandJoint.MIDDLE_FINGER_PHALANX_INTERMEDIATE]: `middle_intPhalanx_${H}`,\n [WebXRHandJoint.MIDDLE_FINGER_PHALANX_DISTAL]: `middle_distPhalanx_${H}`,\n [WebXRHandJoint.MIDDLE_FINGER_TIP]: `middle_tip_${H}`,\n [WebXRHandJoint.RING_FINGER_METACARPAL]: `ring_metacarpal_${H}`,\n [WebXRHandJoint.RING_FINGER_PHALANX_PROXIMAL]: `ring_proxPhalanx_${H}`,\n [WebXRHandJoint.RING_FINGER_PHALANX_INTERMEDIATE]: `ring_intPhalanx_${H}`,\n [WebXRHandJoint.RING_FINGER_PHALANX_DISTAL]: `ring_distPhalanx_${H}`,\n [WebXRHandJoint.RING_FINGER_TIP]: `ring_tip_${H}`,\n [WebXRHandJoint.PINKY_FINGER_METACARPAL]: `little_metacarpal_${H}`,\n [WebXRHandJoint.PINKY_FINGER_PHALANX_PROXIMAL]: `little_proxPhalanx_${H}`,\n [WebXRHandJoint.PINKY_FINGER_PHALANX_INTERMEDIATE]: `little_intPhalanx_${H}`,\n [WebXRHandJoint.PINKY_FINGER_PHALANX_DISTAL]: `little_distPhalanx_${H}`,\n [WebXRHandJoint.PINKY_FINGER_TIP]: `little_tip_${H}`,\n };\n }\n /**\n * Check if the needed objects are defined.\n * This does not mean that the feature is enabled, but that the objects needed are well defined.\n */\n isCompatible() {\n return typeof XRHand !== \"undefined\";\n }\n /**\n * Get the hand object according to the controller id\n * @param controllerId the controller id to which we want to get the hand\n * @returns null if not found or the WebXRHand object if found\n */\n getHandByControllerId(controllerId) {\n return this._attachedHands[controllerId];\n }\n /**\n * Get a hand object according to the requested handedness\n * @param handedness the handedness to request\n * @returns null if not found or the WebXRHand object if found\n */\n getHandByHandedness(handedness) {\n if (handedness == \"none\") {\n return null;\n }\n return this._trackingHands[handedness];\n }\n /**\n * Creates a new instance of the XR hand tracking feature.\n * @param _xrSessionManager An instance of WebXRSessionManager.\n * @param options Options to use when constructing this feature.\n */\n constructor(_xrSessionManager, \n /** Options to use when constructing this feature. */\n options) {\n super(_xrSessionManager);\n this.options = options;\n this._attachedHands = {};\n this._trackingHands = { left: null, right: null };\n this._handResources = { jointMeshes: null, handMeshes: null, rigMappings: null };\n /**\n * This observable will notify registered observers when a new hand object was added and initialized\n */\n this.onHandAddedObservable = new Observable();\n /**\n * This observable will notify its observers right before the hand object is disposed\n */\n this.onHandRemovedObservable = new Observable();\n this._attachHand = (xrController) => {\n var _a, _b, _c;\n if (!xrController.inputSource.hand || xrController.inputSource.handedness == \"none\" || !this._handResources.jointMeshes) {\n return;\n }\n const handedness = xrController.inputSource.handedness;\n const webxrHand = new WebXRHand(xrController, this._handResources.jointMeshes[handedness], this._handResources.handMeshes && this._handResources.handMeshes[handedness], this._handResources.rigMappings && this._handResources.rigMappings[handedness], (_a = this.options.handMeshes) === null || _a === void 0 ? void 0 : _a.meshesUseLeftHandedCoordinates, (_b = this.options.jointMeshes) === null || _b === void 0 ? void 0 : _b.invisible, (_c = this.options.jointMeshes) === null || _c === void 0 ? void 0 : _c.scaleFactor);\n this._attachedHands[xrController.uniqueId] = webxrHand;\n this._trackingHands[handedness] = webxrHand;\n this.onHandAddedObservable.notifyObservers(webxrHand);\n };\n this._detachHand = (xrController) => {\n this._detachHandById(xrController.uniqueId);\n };\n this.xrNativeFeatureName = \"hand-tracking\";\n // Support legacy versions of the options object by copying over joint mesh properties\n const anyOptions = options;\n const anyJointMeshOptions = anyOptions.jointMeshes;\n if (anyJointMeshOptions) {\n if (typeof anyJointMeshOptions.disableDefaultHandMesh !== \"undefined\") {\n options.handMeshes = options.handMeshes || {};\n options.handMeshes.disableDefaultMeshes = anyJointMeshOptions.disableDefaultHandMesh;\n }\n if (typeof anyJointMeshOptions.handMeshes !== \"undefined\") {\n options.handMeshes = options.handMeshes || {};\n options.handMeshes.customMeshes = anyJointMeshOptions.handMeshes;\n }\n if (typeof anyJointMeshOptions.leftHandedSystemMeshes !== \"undefined\") {\n options.handMeshes = options.handMeshes || {};\n options.handMeshes.meshesUseLeftHandedCoordinates = anyJointMeshOptions.leftHandedSystemMeshes;\n }\n if (typeof anyJointMeshOptions.rigMapping !== \"undefined\") {\n options.handMeshes = options.handMeshes || {};\n const leftRigMapping = {};\n const rightRigMapping = {};\n [\n [anyJointMeshOptions.rigMapping.left, leftRigMapping],\n [anyJointMeshOptions.rigMapping.right, rightRigMapping],\n ].forEach((rigMappingTuple) => {\n const legacyRigMapping = rigMappingTuple[0];\n const rigMapping = rigMappingTuple[1];\n legacyRigMapping.forEach((modelJointName, index) => {\n rigMapping[handJointReferenceArray[index]] = modelJointName;\n });\n });\n options.handMeshes.customRigMappings = {\n left: leftRigMapping,\n right: rightRigMapping,\n };\n }\n }\n }\n /**\n * Attach this feature.\n * Will usually be called by the features manager.\n *\n * @returns true if successful.\n */\n attach() {\n var _a, _b, _c, _d;\n if (!super.attach()) {\n return false;\n }\n this._handResources = {\n jointMeshes: WebXRHandTracking._GenerateTrackedJointMeshes(this.options),\n handMeshes: ((_a = this.options.handMeshes) === null || _a === void 0 ? void 0 : _a.customMeshes) || null,\n rigMappings: ((_b = this.options.handMeshes) === null || _b === void 0 ? void 0 : _b.customRigMappings) || null,\n };\n // If they didn't supply custom meshes and are not disabling the default meshes...\n if (!((_c = this.options.handMeshes) === null || _c === void 0 ? void 0 : _c.customMeshes) && !((_d = this.options.handMeshes) === null || _d === void 0 ? void 0 : _d.disableDefaultMeshes)) {\n WebXRHandTracking._GenerateDefaultHandMeshesAsync(EngineStore.LastCreatedScene, this.options).then((defaultHandMeshes) => {\n var _a, _b;\n this._handResources.handMeshes = defaultHandMeshes;\n this._handResources.rigMappings = {\n left: WebXRHandTracking._GenerateDefaultHandMeshRigMapping(\"left\"),\n right: WebXRHandTracking._GenerateDefaultHandMeshRigMapping(\"right\"),\n };\n // Apply meshes to existing hands if already tracking.\n (_a = this._trackingHands.left) === null || _a === void 0 ? void 0 : _a.setHandMesh(this._handResources.handMeshes.left, this._handResources.rigMappings.left);\n (_b = this._trackingHands.right) === null || _b === void 0 ? void 0 : _b.setHandMesh(this._handResources.handMeshes.right, this._handResources.rigMappings.right);\n });\n }\n this.options.xrInput.controllers.forEach(this._attachHand);\n this._addNewAttachObserver(this.options.xrInput.onControllerAddedObservable, this._attachHand);\n this._addNewAttachObserver(this.options.xrInput.onControllerRemovedObservable, this._detachHand);\n return true;\n }\n _onXRFrame(_xrFrame) {\n var _a, _b;\n (_a = this._trackingHands.left) === null || _a === void 0 ? void 0 : _a.updateFromXRFrame(_xrFrame, this._xrSessionManager.referenceSpace);\n (_b = this._trackingHands.right) === null || _b === void 0 ? void 0 : _b.updateFromXRFrame(_xrFrame, this._xrSessionManager.referenceSpace);\n }\n _detachHandById(controllerId) {\n var _a;\n const hand = this.getHandByControllerId(controllerId);\n if (hand) {\n const handedness = hand.xrController.inputSource.handedness == \"left\" ? \"left\" : \"right\";\n if (((_a = this._trackingHands[handedness]) === null || _a === void 0 ? void 0 : _a.xrController.uniqueId) === controllerId) {\n this._trackingHands[handedness] = null;\n }\n this.onHandRemovedObservable.notifyObservers(hand);\n hand.dispose();\n delete this._attachedHands[controllerId];\n }\n }\n /**\n * Detach this feature.\n * Will usually be called by the features manager.\n *\n * @returns true if successful.\n */\n detach() {\n if (!super.detach()) {\n return false;\n }\n Object.keys(this._attachedHands).forEach((uniqueId) => this._detachHandById(uniqueId));\n return true;\n }\n /**\n * Dispose this feature and all of the resources attached.\n */\n dispose() {\n var _a;\n super.dispose();\n this.onHandAddedObservable.clear();\n this.onHandRemovedObservable.clear();\n if (this._handResources.handMeshes && !((_a = this.options.handMeshes) === null || _a === void 0 ? void 0 : _a.customMeshes)) {\n // this will dispose the cached meshes\n this._handResources.handMeshes.left.dispose();\n this._handResources.handMeshes.right.dispose();\n // remove the cached meshes\n WebXRHandTracking._RightHandGLB = null;\n WebXRHandTracking._LeftHandGLB = null;\n }\n if (this._handResources.jointMeshes) {\n this._handResources.jointMeshes.left.forEach((trackedMesh) => trackedMesh.dispose());\n this._handResources.jointMeshes.right.forEach((trackedMesh) => trackedMesh.dispose());\n }\n }\n}\n/**\n * The module's name\n */\nWebXRHandTracking.Name = WebXRFeatureName.HAND_TRACKING;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRHandTracking.Version = 1;\n/** The base URL for the default hand model. */\nWebXRHandTracking.DEFAULT_HAND_MODEL_BASE_URL = \"https://assets.babylonjs.com/meshes/HandMeshes/\";\n/** The filename to use for the default right hand model. */\nWebXRHandTracking.DEFAULT_HAND_MODEL_RIGHT_FILENAME = \"r_hand_rhs.glb\";\n/** The filename to use for the default left hand model. */\nWebXRHandTracking.DEFAULT_HAND_MODEL_LEFT_FILENAME = \"l_hand_rhs.glb\";\n/** The URL pointing to the default hand model NodeMaterial shader. */\nWebXRHandTracking.DEFAULT_HAND_MODEL_SHADER_URL = \"https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json\";\n// We want to use lightweight models, diameter will initially be 1 but scaled to the values returned from WebXR.\nWebXRHandTracking._ICOSPHERE_PARAMS = { radius: 0.5, flat: false, subdivisions: 2 };\nWebXRHandTracking._RightHandGLB = null;\nWebXRHandTracking._LeftHandGLB = null;\n//register the plugin\nWebXRFeaturesManager.AddWebXRFeature(WebXRHandTracking.Name, (xrSessionManager, options) => {\n return () => new WebXRHandTracking(xrSessionManager, options);\n}, WebXRHandTracking.Version, false);\n//# sourceMappingURL=WebXRHandTracking.js.map","import { WebXRFeatureName } from \"../../XR/webXRFeaturesManager.js\";\nimport { WebXRHandJoint } from \"../../XR/features/WebXRHandTracking.js\";\nimport { Quaternion, TmpVectors, Vector3 } from \"../../Maths/math.vector.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * Zones around the hand\n */\nexport var HandConstraintZone;\n(function (HandConstraintZone) {\n /**\n * Above finger tips\n */\n HandConstraintZone[HandConstraintZone[\"ABOVE_FINGER_TIPS\"] = 0] = \"ABOVE_FINGER_TIPS\";\n /**\n * Next to the thumb\n */\n HandConstraintZone[HandConstraintZone[\"RADIAL_SIDE\"] = 1] = \"RADIAL_SIDE\";\n /**\n * Next to the pinky finger\n */\n HandConstraintZone[HandConstraintZone[\"ULNAR_SIDE\"] = 2] = \"ULNAR_SIDE\";\n /**\n * Below the wrist\n */\n HandConstraintZone[HandConstraintZone[\"BELOW_WRIST\"] = 3] = \"BELOW_WRIST\";\n})(HandConstraintZone || (HandConstraintZone = {}));\n/**\n * Orientations for the hand zones and for the attached node\n */\nexport var HandConstraintOrientation;\n(function (HandConstraintOrientation) {\n /**\n * Orientation is towards the camera\n */\n HandConstraintOrientation[HandConstraintOrientation[\"LOOK_AT_CAMERA\"] = 0] = \"LOOK_AT_CAMERA\";\n /**\n * Orientation is determined by the rotation of the palm\n */\n HandConstraintOrientation[HandConstraintOrientation[\"HAND_ROTATION\"] = 1] = \"HAND_ROTATION\";\n})(HandConstraintOrientation || (HandConstraintOrientation = {}));\n/**\n * Orientations for the hand zones and for the attached node\n */\nexport var HandConstraintVisibility;\n(function (HandConstraintVisibility) {\n /**\n * Constraint is always visible\n */\n HandConstraintVisibility[HandConstraintVisibility[\"ALWAYS_VISIBLE\"] = 0] = \"ALWAYS_VISIBLE\";\n /**\n * Constraint is only visible when the palm is up\n */\n HandConstraintVisibility[HandConstraintVisibility[\"PALM_UP\"] = 1] = \"PALM_UP\";\n /**\n * Constraint is only visible when the user is looking at the constraint.\n * Uses XR Eye Tracking if enabled/available, otherwise uses camera direction\n */\n HandConstraintVisibility[HandConstraintVisibility[\"GAZE_FOCUS\"] = 2] = \"GAZE_FOCUS\";\n /**\n * Constraint is only visible when the palm is up and the user is looking at it\n */\n HandConstraintVisibility[HandConstraintVisibility[\"PALM_AND_GAZE\"] = 3] = \"PALM_AND_GAZE\";\n})(HandConstraintVisibility || (HandConstraintVisibility = {}));\n/**\n * Hand constraint behavior that makes the attached `TransformNode` follow hands in XR experiences.\n * @since 5.0.0\n */\nexport class HandConstraintBehavior {\n /**\n * Builds a hand constraint behavior\n */\n constructor() {\n this._sceneRenderObserver = null;\n this._zoneAxis = {};\n /**\n * Sets the HandConstraintVisibility level for the hand constraint\n */\n this.handConstraintVisibility = HandConstraintVisibility.PALM_AND_GAZE;\n /**\n * A number from 0.0 to 1.0, marking how restricted the direction the palm faces is for the attached node to be enabled.\n * A 1 means the palm must be directly facing the user before the node is enabled, a 0 means it is always enabled.\n * Used with HandConstraintVisibility.PALM_UP\n */\n this.palmUpStrictness = 0.95;\n /**\n * The radius in meters around the center of the hand that the user must gaze inside for the attached node to be enabled and appear.\n * Used with HandConstraintVisibility.GAZE_FOCUS\n */\n this.gazeProximityRadius = 0.15;\n /**\n * Offset distance from the hand in meters\n */\n this.targetOffset = 0.1;\n /**\n * Where to place the node regarding the center of the hand.\n */\n this.targetZone = HandConstraintZone.ULNAR_SIDE;\n /**\n * Orientation mode of the 4 zones around the hand\n */\n this.zoneOrientationMode = HandConstraintOrientation.HAND_ROTATION;\n /**\n * Orientation mode of the node attached to this behavior\n */\n this.nodeOrientationMode = HandConstraintOrientation.HAND_ROTATION;\n /**\n * Set the hand this behavior should follow. If set to \"none\", it will follow any visible hand (prioritising the left one).\n */\n this.handedness = \"none\";\n /**\n * Rate of interpolation of position and rotation of the attached node.\n * Higher values will give a slower interpolation.\n */\n this.lerpTime = 100;\n // For a right hand\n this._zoneAxis[HandConstraintZone.ABOVE_FINGER_TIPS] = new Vector3(0, 1, 0);\n this._zoneAxis[HandConstraintZone.RADIAL_SIDE] = new Vector3(-1, 0, 0);\n this._zoneAxis[HandConstraintZone.ULNAR_SIDE] = new Vector3(1, 0, 0);\n this._zoneAxis[HandConstraintZone.BELOW_WRIST] = new Vector3(0, -1, 0);\n }\n /** gets or sets behavior's name */\n get name() {\n return \"HandConstraint\";\n }\n /** Enable the behavior */\n enable() {\n this._node.setEnabled(true);\n }\n /** Disable the behavior */\n disable() {\n this._node.setEnabled(false);\n }\n _getHandPose() {\n if (!this._handTracking) {\n return null;\n }\n // Retrieve any available hand, starting by the left\n let hand;\n if (this.handedness === \"none\") {\n hand = this._handTracking.getHandByHandedness(\"left\") || this._handTracking.getHandByHandedness(\"right\");\n }\n else {\n hand = this._handTracking.getHandByHandedness(this.handedness);\n }\n if (hand) {\n const pinkyMetacarpal = hand.getJointMesh(WebXRHandJoint.PINKY_FINGER_METACARPAL);\n const middleMetacarpal = hand.getJointMesh(WebXRHandJoint.MIDDLE_FINGER_METACARPAL);\n const wrist = hand.getJointMesh(WebXRHandJoint.WRIST);\n if (wrist && middleMetacarpal && pinkyMetacarpal) {\n const handPose = { position: middleMetacarpal.absolutePosition, quaternion: new Quaternion(), id: hand.xrController.uniqueId };\n // palm forward\n const up = TmpVectors.Vector3[0];\n const forward = TmpVectors.Vector3[1];\n const left = TmpVectors.Vector3[2];\n up.copyFrom(middleMetacarpal.absolutePosition).subtractInPlace(wrist.absolutePosition).normalize();\n forward.copyFrom(pinkyMetacarpal.absolutePosition).subtractInPlace(middleMetacarpal.absolutePosition).normalize();\n // Create vectors for a rotation quaternion, where forward points out from the palm\n Vector3.CrossToRef(up, forward, forward);\n Vector3.CrossToRef(forward, up, left);\n Quaternion.FromLookDirectionLHToRef(forward, up, handPose.quaternion);\n return handPose;\n }\n }\n return null;\n }\n /**\n * Initializes the hand constraint behavior\n */\n init() { }\n /**\n * Attaches the hand constraint to a `TransformNode`\n * @param node defines the node to attach the behavior to\n */\n attach(node) {\n this._node = node;\n this._scene = node.getScene();\n if (!this._node.rotationQuaternion) {\n this._node.rotationQuaternion = Quaternion.RotationYawPitchRoll(this._node.rotation.y, this._node.rotation.x, this._node.rotation.z);\n }\n let lastTick = Date.now();\n this._sceneRenderObserver = this._scene.onBeforeRenderObservable.add(() => {\n const pose = this._getHandPose();\n this._node.reservedDataStore = this._node.reservedDataStore || {};\n this._node.reservedDataStore.nearInteraction = this._node.reservedDataStore.nearInteraction || {};\n this._node.reservedDataStore.nearInteraction.excludedControllerId = null;\n if (pose) {\n const zoneOffset = TmpVectors.Vector3[0];\n const camera = this._scene.activeCamera;\n zoneOffset.copyFrom(this._zoneAxis[this.targetZone]);\n const cameraLookAtQuaternion = TmpVectors.Quaternion[0];\n if (camera && (this.zoneOrientationMode === HandConstraintOrientation.LOOK_AT_CAMERA || this.nodeOrientationMode === HandConstraintOrientation.LOOK_AT_CAMERA)) {\n const toCamera = TmpVectors.Vector3[1];\n toCamera.copyFrom(camera.position).subtractInPlace(pose.position).normalize();\n if (this._scene.useRightHandedSystem) {\n Quaternion.FromLookDirectionRHToRef(toCamera, Vector3.UpReadOnly, cameraLookAtQuaternion);\n }\n else {\n Quaternion.FromLookDirectionLHToRef(toCamera, Vector3.UpReadOnly, cameraLookAtQuaternion);\n }\n }\n if (this.zoneOrientationMode === HandConstraintOrientation.HAND_ROTATION) {\n pose.quaternion.toRotationMatrix(TmpVectors.Matrix[0]);\n }\n else {\n cameraLookAtQuaternion.toRotationMatrix(TmpVectors.Matrix[0]);\n }\n Vector3.TransformNormalToRef(zoneOffset, TmpVectors.Matrix[0], zoneOffset);\n zoneOffset.scaleInPlace(this.targetOffset);\n const targetPosition = TmpVectors.Vector3[2];\n const targetRotation = TmpVectors.Quaternion[1];\n targetPosition.copyFrom(pose.position).addInPlace(zoneOffset);\n if (this.nodeOrientationMode === HandConstraintOrientation.HAND_ROTATION) {\n targetRotation.copyFrom(pose.quaternion);\n }\n else {\n targetRotation.copyFrom(cameraLookAtQuaternion);\n }\n const elapsed = Date.now() - lastTick;\n Vector3.SmoothToRef(this._node.position, targetPosition, elapsed, this.lerpTime, this._node.position);\n Quaternion.SmoothToRef(this._node.rotationQuaternion, targetRotation, elapsed, this.lerpTime, this._node.rotationQuaternion);\n this._node.reservedDataStore.nearInteraction.excludedControllerId = pose.id;\n }\n this._setVisibility(pose);\n lastTick = Date.now();\n });\n }\n _setVisibility(pose) {\n let palmVisible = true;\n let gazeVisible = true;\n const camera = this._scene.activeCamera;\n if (camera) {\n const cameraForward = camera.getForwardRay();\n if (this.handConstraintVisibility === HandConstraintVisibility.GAZE_FOCUS || this.handConstraintVisibility === HandConstraintVisibility.PALM_AND_GAZE) {\n gazeVisible = false;\n let gaze;\n if (this._eyeTracking) {\n gaze = this._eyeTracking.getEyeGaze();\n }\n gaze = gaze || cameraForward;\n const gazeToBehavior = TmpVectors.Vector3[0];\n if (pose) {\n pose.position.subtractToRef(gaze.origin, gazeToBehavior);\n }\n else {\n this._node.getAbsolutePosition().subtractToRef(gaze.origin, gazeToBehavior);\n }\n const projectedDistance = Vector3.Dot(gazeToBehavior, gaze.direction);\n const projectedSquared = projectedDistance * projectedDistance;\n if (projectedDistance > 0) {\n const radiusSquared = gazeToBehavior.lengthSquared() - projectedSquared;\n if (radiusSquared < this.gazeProximityRadius * this.gazeProximityRadius) {\n gazeVisible = true;\n }\n }\n }\n if (this.handConstraintVisibility === HandConstraintVisibility.PALM_UP || this.handConstraintVisibility === HandConstraintVisibility.PALM_AND_GAZE) {\n palmVisible = false;\n if (pose) {\n const palmDirection = TmpVectors.Vector3[0];\n Vector3.LeftHandedForwardReadOnly.rotateByQuaternionToRef(pose.quaternion, palmDirection);\n if (Vector3.Dot(palmDirection, cameraForward.direction) > this.palmUpStrictness * 2 - 1) {\n palmVisible = true;\n }\n }\n }\n }\n this._node.setEnabled(palmVisible && gazeVisible);\n }\n /**\n * Detaches the behavior from the `TransformNode`\n */\n detach() {\n this._scene.onBeforeRenderObservable.remove(this._sceneRenderObserver);\n }\n /**\n * Links the behavior to the XR experience in which to retrieve hand transform information.\n * @param xr xr experience\n */\n linkToXRExperience(xr) {\n const featuresManager = xr.featuresManager ? xr.featuresManager : xr;\n if (!featuresManager) {\n Tools.Error(\"XR features manager must be available or provided directly for the Hand Menu to work\");\n }\n else {\n try {\n this._eyeTracking = featuresManager.getEnabledFeature(WebXRFeatureName.EYE_TRACKING);\n }\n catch (_a) { }\n try {\n this._handTracking = featuresManager.getEnabledFeature(WebXRFeatureName.HAND_TRACKING);\n }\n catch (_b) {\n Tools.Error(\"Hand tracking must be enabled for the Hand Menu to work\");\n }\n }\n }\n}\n//# sourceMappingURL=handConstraintBehavior.js.map","import { Vector3, Quaternion, Matrix } from \"../Maths/math.vector.js\";\nimport { Space } from \"../Maths/math.axis.js\";\nimport { Logger } from \"../Misc/logger.js\";\n/**\n * Class used to apply inverse kinematics to bones\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons#boneikcontroller\n */\nexport class BoneIKController {\n /**\n * Gets or sets maximum allowed angle\n */\n get maxAngle() {\n return this._maxAngle;\n }\n set maxAngle(value) {\n this._setMaxAngle(value);\n }\n /**\n * Creates a new BoneIKController\n * @param mesh defines the TransformNode to control\n * @param bone defines the bone to control. The bone needs to have a parent bone. It also needs to have a length greater than 0 or a children we can use to infer its length.\n * @param options defines options to set up the controller\n * @param options.targetMesh\n * @param options.poleTargetMesh\n * @param options.poleTargetBone\n * @param options.poleTargetLocalOffset\n * @param options.poleAngle\n * @param options.bendAxis\n * @param options.maxAngle\n * @param options.slerpAmount\n */\n constructor(mesh, bone, options) {\n /**\n * Gets or sets the target position\n */\n this.targetPosition = Vector3.Zero();\n /**\n * Gets or sets the pole target position\n */\n this.poleTargetPosition = Vector3.Zero();\n /**\n * Gets or sets the pole target local offset\n */\n this.poleTargetLocalOffset = Vector3.Zero();\n /**\n * Gets or sets the pole angle\n */\n this.poleAngle = 0;\n /**\n * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp)\n */\n this.slerpAmount = 1;\n this._bone1Quat = Quaternion.Identity();\n this._bone1Mat = Matrix.Identity();\n this._bone2Ang = Math.PI;\n this._maxAngle = Math.PI;\n this._rightHandedSystem = false;\n this._bendAxis = Vector3.Right();\n this._slerping = false;\n this._adjustRoll = 0;\n this._notEnoughInformation = false;\n this._bone2 = bone;\n const bone1 = bone.getParent();\n if (!bone1) {\n this._notEnoughInformation = true;\n Logger.Error(\"BoneIKController: bone must have a parent for IK to work.\");\n return;\n }\n this._bone1 = bone1;\n if (this._bone2.children.length === 0 && !this._bone2.length) {\n this._notEnoughInformation = true;\n Logger.Error(\"BoneIKController: bone must not be a leaf or it should have a length for IK to work.\");\n return;\n }\n this.mesh = mesh;\n const bonePos = bone.getPosition();\n if (bone.getAbsoluteMatrix().determinant() > 0) {\n this._rightHandedSystem = true;\n this._bendAxis.x = 0;\n this._bendAxis.y = 0;\n this._bendAxis.z = -1;\n if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {\n this._adjustRoll = Math.PI * 0.5;\n this._bendAxis.z = 1;\n }\n }\n if (this._bone1.length && this._bone2.length) {\n const boneScale1 = this._bone1.getScale();\n const boneScale2 = this._bone2.getScale();\n this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;\n this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;\n }\n else if (this._bone2.children[0]) {\n mesh.computeWorldMatrix(true);\n const pos1 = this._bone2.children[0].getAbsolutePosition(mesh);\n const pos2 = this._bone2.getAbsolutePosition(mesh);\n const pos3 = this._bone1.getAbsolutePosition(mesh);\n this._bone2Length = Vector3.Distance(pos1, pos2);\n this._bone1Length = Vector3.Distance(pos2, pos3);\n }\n else {\n mesh.computeWorldMatrix(true);\n const boneScale2 = this._bone2.getScale();\n this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;\n const pos2 = this._bone2.getAbsolutePosition(mesh);\n const pos3 = this._bone1.getAbsolutePosition(mesh);\n this._bone1Length = Vector3.Distance(pos2, pos3);\n }\n this._bone1.getRotationMatrixToRef(Space.WORLD, mesh, this._bone1Mat);\n this.maxAngle = Math.PI;\n if (options) {\n if (options.targetMesh) {\n this.targetMesh = options.targetMesh;\n this.targetMesh.computeWorldMatrix(true);\n }\n if (options.poleTargetMesh) {\n this.poleTargetMesh = options.poleTargetMesh;\n this.poleTargetMesh.computeWorldMatrix(true);\n }\n else if (options.poleTargetBone) {\n this.poleTargetBone = options.poleTargetBone;\n }\n else if (this._bone1.getParent()) {\n this.poleTargetBone = this._bone1.getParent();\n }\n if (options.poleTargetLocalOffset) {\n this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);\n }\n if (options.poleAngle) {\n this.poleAngle = options.poleAngle;\n }\n if (options.bendAxis) {\n this._bendAxis.copyFrom(options.bendAxis);\n }\n if (options.maxAngle) {\n this.maxAngle = options.maxAngle;\n }\n if (options.slerpAmount) {\n this.slerpAmount = options.slerpAmount;\n }\n }\n }\n _setMaxAngle(ang) {\n if (ang < 0) {\n ang = 0;\n }\n if (ang > Math.PI || ang == undefined) {\n ang = Math.PI;\n }\n this._maxAngle = ang;\n const a = this._bone1Length;\n const b = this._bone2Length;\n this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));\n }\n /**\n * Force the controller to update the bones\n */\n update() {\n if (this._notEnoughInformation) {\n return;\n }\n const target = this.targetPosition;\n const poleTarget = this.poleTargetPosition;\n const mat1 = BoneIKController._TmpMats[0];\n const mat2 = BoneIKController._TmpMats[1];\n if (this.targetMesh) {\n target.copyFrom(this.targetMesh.getAbsolutePosition());\n }\n if (this.poleTargetBone) {\n this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);\n }\n else if (this.poleTargetMesh) {\n Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);\n }\n const bonePos = BoneIKController._TmpVecs[0];\n const zaxis = BoneIKController._TmpVecs[1];\n const xaxis = BoneIKController._TmpVecs[2];\n const yaxis = BoneIKController._TmpVecs[3];\n const upAxis = BoneIKController._TmpVecs[4];\n const tmpQuat = BoneIKController._TmpQuat;\n this._bone1.getAbsolutePositionToRef(this.mesh, bonePos);\n poleTarget.subtractToRef(bonePos, upAxis);\n if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {\n upAxis.y = 1;\n }\n else {\n upAxis.normalize();\n }\n target.subtractToRef(bonePos, yaxis);\n yaxis.normalize();\n Vector3.CrossToRef(yaxis, upAxis, zaxis);\n zaxis.normalize();\n Vector3.CrossToRef(yaxis, zaxis, xaxis);\n xaxis.normalize();\n Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);\n const a = this._bone1Length;\n const b = this._bone2Length;\n let c = Vector3.Distance(bonePos, target);\n if (this._maxReach > 0) {\n c = Math.min(this._maxReach, c);\n }\n let acosa = (b * b + c * c - a * a) / (2 * b * c);\n let acosb = (c * c + a * a - b * b) / (2 * c * a);\n if (acosa > 1) {\n acosa = 1;\n }\n if (acosb > 1) {\n acosb = 1;\n }\n if (acosa < -1) {\n acosa = -1;\n }\n if (acosb < -1) {\n acosb = -1;\n }\n const angA = Math.acos(acosa);\n const angB = Math.acos(acosb);\n let angC = -angA - angB;\n if (this._rightHandedSystem) {\n Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);\n mat2.multiplyToRef(mat1, mat1);\n Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);\n mat2.multiplyToRef(mat1, mat1);\n }\n else {\n const _tmpVec = BoneIKController._TmpVecs[5];\n _tmpVec.copyFrom(this._bendAxis);\n _tmpVec.x *= -1;\n Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);\n mat2.multiplyToRef(mat1, mat1);\n }\n if (this.poleAngle) {\n Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);\n mat1.multiplyToRef(mat2, mat1);\n }\n if (this._bone1) {\n if (this.slerpAmount < 1) {\n if (!this._slerping) {\n Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);\n }\n Quaternion.FromRotationMatrixToRef(mat1, tmpQuat);\n Quaternion.SlerpToRef(this._bone1Quat, tmpQuat, this.slerpAmount, this._bone1Quat);\n angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;\n this._bone1.setRotationQuaternion(this._bone1Quat, Space.WORLD, this.mesh);\n this._slerping = true;\n }\n else {\n this._bone1.setRotationMatrix(mat1, Space.WORLD, this.mesh);\n this._bone1Mat.copyFrom(mat1);\n this._slerping = false;\n }\n this._updateLinkedTransformRotation(this._bone1);\n }\n this._bone2.setAxisAngle(this._bendAxis, angC, Space.LOCAL);\n this._updateLinkedTransformRotation(this._bone2);\n this._bone2Ang = angC;\n }\n _updateLinkedTransformRotation(bone) {\n if (bone._linkedTransformNode) {\n if (!bone._linkedTransformNode.rotationQuaternion) {\n bone._linkedTransformNode.rotationQuaternion = new Quaternion();\n }\n bone.getRotationQuaternionToRef(Space.LOCAL, null, bone._linkedTransformNode.rotationQuaternion);\n }\n }\n}\nBoneIKController._TmpVecs = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];\nBoneIKController._TmpQuat = Quaternion.Identity();\nBoneIKController._TmpMats = [Matrix.Identity(), Matrix.Identity()];\n//# sourceMappingURL=boneIKController.js.map","import { ArrayTools } from \"../Misc/arrayTools.js\";\nimport { Vector3, Quaternion, Matrix } from \"../Maths/math.vector.js\";\nimport { Space, Axis } from \"../Maths/math.axis.js\";\n/**\n * Class used to make a bone look toward a point in space\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons#bonelookcontroller\n */\nexport class BoneLookController {\n /**\n * Gets or sets the minimum yaw angle that the bone can look to\n */\n get minYaw() {\n return this._minYaw;\n }\n set minYaw(value) {\n this._minYaw = value;\n this._minYawSin = Math.sin(value);\n this._minYawCos = Math.cos(value);\n if (this._maxYaw != null) {\n this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * 0.5 + this._minYaw;\n this._yawRange = this._maxYaw - this._minYaw;\n }\n }\n /**\n * Gets or sets the maximum yaw angle that the bone can look to\n */\n get maxYaw() {\n return this._maxYaw;\n }\n set maxYaw(value) {\n this._maxYaw = value;\n this._maxYawSin = Math.sin(value);\n this._maxYawCos = Math.cos(value);\n if (this._minYaw != null) {\n this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * 0.5 + this._minYaw;\n this._yawRange = this._maxYaw - this._minYaw;\n }\n }\n /**\n * Gets or sets the minimum pitch angle that the bone can look to\n */\n get minPitch() {\n return this._minPitch;\n }\n set minPitch(value) {\n this._minPitch = value;\n this._minPitchTan = Math.tan(value);\n }\n /**\n * Gets or sets the maximum pitch angle that the bone can look to\n */\n get maxPitch() {\n return this._maxPitch;\n }\n set maxPitch(value) {\n this._maxPitch = value;\n this._maxPitchTan = Math.tan(value);\n }\n /**\n * Create a BoneLookController\n * @param mesh the TransformNode that the bone belongs to\n * @param bone the bone that will be looking to the target\n * @param target the target Vector3 to look at\n * @param options optional settings:\n * * maxYaw: the maximum angle the bone will yaw to\n * * minYaw: the minimum angle the bone will yaw to\n * * maxPitch: the maximum angle the bone will pitch to\n * * minPitch: the minimum angle the bone will yaw to\n * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.\n * * upAxis: the up axis of the coordinate system\n * * upAxisSpace: the space that the up axis is in - Space.BONE, Space.LOCAL (default), or Space.WORLD.\n * * yawAxis: set yawAxis if the bone does not yaw on the y axis\n * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis\n * * adjustYaw: used to make an adjustment to the yaw of the bone\n * * adjustPitch: used to make an adjustment to the pitch of the bone\n * * adjustRoll: used to make an adjustment to the roll of the bone\n * @param options.maxYaw\n * @param options.minYaw\n * @param options.maxPitch\n * @param options.minPitch\n * @param options.slerpAmount\n * @param options.upAxis\n * @param options.upAxisSpace\n * @param options.yawAxis\n * @param options.pitchAxis\n * @param options.adjustYaw\n * @param options.adjustPitch\n * @param options.adjustRoll\n **/\n constructor(mesh, bone, target, options) {\n /**\n * The up axis of the coordinate system that is used when the bone is rotated\n */\n this.upAxis = Vector3.Up();\n /**\n * The space that the up axis is in - Space.BONE, Space.LOCAL (default), or Space.WORLD\n */\n this.upAxisSpace = Space.LOCAL;\n /**\n * Used to make an adjustment to the yaw of the bone\n */\n this.adjustYaw = 0;\n /**\n * Used to make an adjustment to the pitch of the bone\n */\n this.adjustPitch = 0;\n /**\n * Used to make an adjustment to the roll of the bone\n */\n this.adjustRoll = 0;\n /**\n * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp)\n */\n this.slerpAmount = 1;\n this._boneQuat = Quaternion.Identity();\n this._slerping = false;\n this._firstFrameSkipped = false;\n this._fowardAxis = Vector3.Forward();\n /**\n * Use the absolute value for yaw when checking the min/max constraints\n */\n this.useAbsoluteValueForYaw = false;\n this.mesh = mesh;\n this.bone = bone;\n this.target = target;\n if (options) {\n if (options.adjustYaw) {\n this.adjustYaw = options.adjustYaw;\n }\n if (options.adjustPitch) {\n this.adjustPitch = options.adjustPitch;\n }\n if (options.adjustRoll) {\n this.adjustRoll = options.adjustRoll;\n }\n if (options.maxYaw != null) {\n this.maxYaw = options.maxYaw;\n }\n else {\n this.maxYaw = Math.PI;\n }\n if (options.minYaw != null) {\n this.minYaw = options.minYaw;\n }\n else {\n this.minYaw = -Math.PI;\n }\n if (options.maxPitch != null) {\n this.maxPitch = options.maxPitch;\n }\n else {\n this.maxPitch = Math.PI;\n }\n if (options.minPitch != null) {\n this.minPitch = options.minPitch;\n }\n else {\n this.minPitch = -Math.PI;\n }\n if (options.slerpAmount != null) {\n this.slerpAmount = options.slerpAmount;\n }\n if (options.upAxis != null) {\n this.upAxis = options.upAxis;\n }\n if (options.upAxisSpace != null) {\n this.upAxisSpace = options.upAxisSpace;\n }\n if (options.yawAxis != null || options.pitchAxis != null) {\n let newYawAxis = Axis.Y;\n let newPitchAxis = Axis.X;\n if (options.yawAxis != null) {\n newYawAxis = options.yawAxis.clone();\n newYawAxis.normalize();\n }\n if (options.pitchAxis != null) {\n newPitchAxis = options.pitchAxis.clone();\n newPitchAxis.normalize();\n }\n const newRollAxis = Vector3.Cross(newPitchAxis, newYawAxis);\n this._transformYawPitch = Matrix.Identity();\n Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);\n this._transformYawPitchInv = this._transformYawPitch.clone();\n this._transformYawPitch.invert();\n }\n if (options.useAbsoluteValueForYaw !== undefined) {\n this.useAbsoluteValueForYaw = options.useAbsoluteValueForYaw;\n }\n }\n if (!bone.getParent() && this.upAxisSpace == Space.BONE) {\n this.upAxisSpace = Space.LOCAL;\n }\n }\n /**\n * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())\n */\n update() {\n //skip the first frame when slerping so that the TransformNode rotation is correct\n if (this.slerpAmount < 1 && !this._firstFrameSkipped) {\n this._firstFrameSkipped = true;\n return;\n }\n const bone = this.bone;\n const bonePos = BoneLookController._TmpVecs[0];\n bone.getAbsolutePositionToRef(this.mesh, bonePos);\n let target = this.target;\n const _tmpMat1 = BoneLookController._TmpMats[0];\n const _tmpMat2 = BoneLookController._TmpMats[1];\n const mesh = this.mesh;\n const parentBone = bone.getParent();\n const upAxis = BoneLookController._TmpVecs[1];\n upAxis.copyFrom(this.upAxis);\n if (this.upAxisSpace == Space.BONE && parentBone) {\n if (this._transformYawPitch) {\n Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);\n }\n parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);\n }\n else if (this.upAxisSpace == Space.LOCAL) {\n mesh.getDirectionToRef(upAxis, upAxis);\n if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {\n upAxis.normalize();\n }\n }\n let checkYaw = false;\n let checkPitch = false;\n if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {\n checkYaw = true;\n }\n if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {\n checkPitch = true;\n }\n if (checkYaw || checkPitch) {\n const spaceMat = BoneLookController._TmpMats[2];\n const spaceMatInv = BoneLookController._TmpMats[3];\n if (this.upAxisSpace == Space.BONE && upAxis.y == 1 && parentBone) {\n parentBone.getRotationMatrixToRef(Space.WORLD, this.mesh, spaceMat);\n }\n else if (this.upAxisSpace == Space.LOCAL && upAxis.y == 1 && !parentBone) {\n spaceMat.copyFrom(mesh.getWorldMatrix());\n }\n else {\n let forwardAxis = BoneLookController._TmpVecs[2];\n forwardAxis.copyFrom(this._fowardAxis);\n if (this._transformYawPitch) {\n Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);\n }\n if (parentBone) {\n parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);\n }\n else {\n mesh.getDirectionToRef(forwardAxis, forwardAxis);\n }\n const rightAxis = Vector3.Cross(upAxis, forwardAxis);\n rightAxis.normalize();\n forwardAxis = Vector3.Cross(rightAxis, upAxis);\n Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);\n }\n spaceMat.invertToRef(spaceMatInv);\n let xzlen = null;\n if (checkPitch) {\n const localTarget = BoneLookController._TmpVecs[3];\n target.subtractToRef(bonePos, localTarget);\n Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);\n xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);\n const pitch = Math.atan2(localTarget.y, xzlen);\n let newPitch = pitch;\n if (pitch > this._maxPitch) {\n localTarget.y = this._maxPitchTan * xzlen;\n newPitch = this._maxPitch;\n }\n else if (pitch < this._minPitch) {\n localTarget.y = this._minPitchTan * xzlen;\n newPitch = this._minPitch;\n }\n if (pitch != newPitch) {\n Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);\n localTarget.addInPlace(bonePos);\n target = localTarget;\n }\n }\n if (checkYaw) {\n const localTarget = BoneLookController._TmpVecs[4];\n target.subtractToRef(bonePos, localTarget);\n Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);\n const yaw = Math.atan2(localTarget.x, localTarget.z);\n const yawCheck = this.useAbsoluteValueForYaw ? Math.abs(yaw) : yaw;\n let newYaw = yaw;\n if (yawCheck > this._maxYaw || yawCheck < this._minYaw) {\n if (xzlen == null) {\n xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);\n }\n if (this._yawRange > Math.PI) {\n if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {\n localTarget.z = this._maxYawCos * xzlen;\n localTarget.x = this._maxYawSin * xzlen;\n newYaw = this._maxYaw;\n }\n else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {\n localTarget.z = this._minYawCos * xzlen;\n localTarget.x = this._minYawSin * xzlen;\n newYaw = this._minYaw;\n }\n }\n else {\n if (yawCheck > this._maxYaw) {\n localTarget.z = this._maxYawCos * xzlen;\n localTarget.x = this._maxYawSin * xzlen;\n if (yaw < 0 && this.useAbsoluteValueForYaw) {\n localTarget.x *= -1;\n }\n newYaw = this._maxYaw;\n }\n else if (yawCheck < this._minYaw) {\n localTarget.z = this._minYawCos * xzlen;\n localTarget.x = this._minYawSin * xzlen;\n if (yaw < 0 && this.useAbsoluteValueForYaw) {\n localTarget.x *= -1;\n }\n newYaw = this._minYaw;\n }\n }\n }\n if (this._slerping && this._yawRange > Math.PI) {\n //are we going to be crossing into the min/max region?\n const boneFwd = BoneLookController._TmpVecs[8];\n boneFwd.copyFrom(Axis.Z);\n if (this._transformYawPitch) {\n Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);\n }\n const boneRotMat = BoneLookController._TmpMats[4];\n this._boneQuat.toRotationMatrix(boneRotMat);\n this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);\n Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);\n Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);\n const boneYaw = Math.atan2(boneFwd.x, boneFwd.z);\n const angBtwTar = this._getAngleBetween(boneYaw, yaw);\n const angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);\n if (angBtwTar > angBtwMidYaw) {\n if (xzlen == null) {\n xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);\n }\n const angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);\n const angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);\n if (angBtwMin < angBtwMax) {\n newYaw = boneYaw + Math.PI * 0.75;\n localTarget.z = Math.cos(newYaw) * xzlen;\n localTarget.x = Math.sin(newYaw) * xzlen;\n }\n else {\n newYaw = boneYaw - Math.PI * 0.75;\n localTarget.z = Math.cos(newYaw) * xzlen;\n localTarget.x = Math.sin(newYaw) * xzlen;\n }\n }\n }\n if (yaw != newYaw) {\n Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);\n localTarget.addInPlace(bonePos);\n target = localTarget;\n }\n }\n }\n const zaxis = BoneLookController._TmpVecs[5];\n const xaxis = BoneLookController._TmpVecs[6];\n const yaxis = BoneLookController._TmpVecs[7];\n const tmpQuat = BoneLookController._TmpQuat;\n target.subtractToRef(bonePos, zaxis);\n zaxis.normalize();\n Vector3.CrossToRef(upAxis, zaxis, xaxis);\n xaxis.normalize();\n Vector3.CrossToRef(zaxis, xaxis, yaxis);\n yaxis.normalize();\n Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);\n if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {\n return;\n }\n if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {\n return;\n }\n if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {\n return;\n }\n if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {\n Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);\n _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);\n }\n if (this.slerpAmount < 1) {\n if (!this._slerping) {\n this.bone.getRotationQuaternionToRef(Space.WORLD, this.mesh, this._boneQuat);\n }\n if (this._transformYawPitch) {\n this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);\n }\n Quaternion.FromRotationMatrixToRef(_tmpMat1, tmpQuat);\n Quaternion.SlerpToRef(this._boneQuat, tmpQuat, this.slerpAmount, this._boneQuat);\n this.bone.setRotationQuaternion(this._boneQuat, Space.WORLD, this.mesh);\n this._slerping = true;\n }\n else {\n if (this._transformYawPitch) {\n this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);\n }\n this.bone.setRotationMatrix(_tmpMat1, Space.WORLD, this.mesh);\n this._slerping = false;\n }\n this._updateLinkedTransformRotation();\n }\n _getAngleDiff(ang1, ang2) {\n let angDiff = ang2 - ang1;\n angDiff %= Math.PI * 2;\n if (angDiff > Math.PI) {\n angDiff -= Math.PI * 2;\n }\n else if (angDiff < -Math.PI) {\n angDiff += Math.PI * 2;\n }\n return angDiff;\n }\n _getAngleBetween(ang1, ang2) {\n ang1 %= 2 * Math.PI;\n ang1 = ang1 < 0 ? ang1 + 2 * Math.PI : ang1;\n ang2 %= 2 * Math.PI;\n ang2 = ang2 < 0 ? ang2 + 2 * Math.PI : ang2;\n let ab = 0;\n if (ang1 < ang2) {\n ab = ang2 - ang1;\n }\n else {\n ab = ang1 - ang2;\n }\n if (ab > Math.PI) {\n ab = Math.PI * 2 - ab;\n }\n return ab;\n }\n _isAngleBetween(ang, ang1, ang2) {\n ang %= 2 * Math.PI;\n ang = ang < 0 ? ang + 2 * Math.PI : ang;\n ang1 %= 2 * Math.PI;\n ang1 = ang1 < 0 ? ang1 + 2 * Math.PI : ang1;\n ang2 %= 2 * Math.PI;\n ang2 = ang2 < 0 ? ang2 + 2 * Math.PI : ang2;\n if (ang1 < ang2) {\n if (ang > ang1 && ang < ang2) {\n return true;\n }\n }\n else {\n if (ang > ang2 && ang < ang1) {\n return true;\n }\n }\n return false;\n }\n _updateLinkedTransformRotation() {\n const bone = this.bone;\n if (bone._linkedTransformNode) {\n if (!bone._linkedTransformNode.rotationQuaternion) {\n bone._linkedTransformNode.rotationQuaternion = new Quaternion();\n }\n bone.getRotationQuaternionToRef(Space.LOCAL, null, bone._linkedTransformNode.rotationQuaternion);\n }\n }\n}\nBoneLookController._TmpVecs = ArrayTools.BuildArray(10, Vector3.Zero);\nBoneLookController._TmpQuat = Quaternion.Identity();\nBoneLookController._TmpMats = ArrayTools.BuildArray(5, Matrix.Identity);\n//# sourceMappingURL=boneLookController.js.map","import { Bone } from \"./bone.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Vector3, Matrix, TmpVectors } from \"../Maths/math.vector.js\";\nimport { RawTexture } from \"../Materials/Textures/rawTexture.js\";\nimport { Animation } from \"../Animations/animation.js\";\nimport { AnimationRange } from \"../Animations/animationRange.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n\nimport { Logger } from \"../Misc/logger.js\";\nimport { DeepCopier } from \"../Misc/deepCopier.js\";\n/**\n * Class used to handle skinning animations\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons\n */\nexport class Skeleton {\n /**\n * Gets or sets a boolean indicating that bone matrices should be stored as a texture instead of using shader uniforms (default is true).\n * Please note that this option is not available if the hardware does not support it\n */\n get useTextureToStoreBoneMatrices() {\n return this._useTextureToStoreBoneMatrices;\n }\n set useTextureToStoreBoneMatrices(value) {\n this._useTextureToStoreBoneMatrices = value;\n this._markAsDirty();\n }\n /**\n * Gets or sets the animation properties override\n */\n get animationPropertiesOverride() {\n if (!this._animationPropertiesOverride) {\n return this._scene.animationPropertiesOverride;\n }\n return this._animationPropertiesOverride;\n }\n set animationPropertiesOverride(value) {\n this._animationPropertiesOverride = value;\n }\n /**\n * Gets a boolean indicating that the skeleton effectively stores matrices into a texture\n */\n get isUsingTextureForMatrices() {\n return this.useTextureToStoreBoneMatrices && this._canUseTextureForBones;\n }\n /**\n * Gets the unique ID of this skeleton\n */\n get uniqueId() {\n return this._uniqueId;\n }\n /**\n * Creates a new skeleton\n * @param name defines the skeleton name\n * @param id defines the skeleton Id\n * @param scene defines the hosting scene\n */\n constructor(\n /** defines the skeleton name */\n name, \n /** defines the skeleton Id */\n id, scene) {\n this.name = name;\n this.id = id;\n /**\n * Defines the list of child bones\n */\n this.bones = new Array();\n /**\n * Defines a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)\n */\n this.needInitialSkinMatrix = false;\n this._isDirty = true;\n this._meshesWithPoseMatrix = new Array();\n this._identity = Matrix.Identity();\n this._ranges = {};\n this._absoluteTransformIsDirty = true;\n this._canUseTextureForBones = false;\n this._uniqueId = 0;\n /** @internal */\n this._numBonesWithLinkedTransformNode = 0;\n /** @internal */\n this._hasWaitingData = null;\n /** @internal */\n this._parentContainer = null;\n /**\n * Specifies if the skeleton should be serialized\n */\n this.doNotSerialize = false;\n this._useTextureToStoreBoneMatrices = true;\n this._animationPropertiesOverride = null;\n // Events\n /**\n * An observable triggered before computing the skeleton's matrices\n */\n this.onBeforeComputeObservable = new Observable();\n this.bones = [];\n this._scene = scene || EngineStore.LastCreatedScene;\n this._uniqueId = this._scene.getUniqueId();\n this._scene.addSkeleton(this);\n //make sure it will recalculate the matrix next time prepare is called.\n this._isDirty = true;\n const engineCaps = this._scene.getEngine().getCaps();\n this._canUseTextureForBones = engineCaps.textureFloat && engineCaps.maxVertexTextureImageUnits > 0;\n }\n /**\n * Gets the current object class name.\n * @returns the class name\n */\n getClassName() {\n return \"Skeleton\";\n }\n /**\n * Returns an array containing the root bones\n * @returns an array containing the root bones\n */\n getChildren() {\n return this.bones.filter((b) => !b.getParent());\n }\n // Members\n /**\n * Gets the list of transform matrices to send to shaders (one matrix per bone)\n * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)\n * @returns a Float32Array containing matrices data\n */\n getTransformMatrices(mesh) {\n if (this.needInitialSkinMatrix) {\n if (!mesh._bonesTransformMatrices) {\n this.prepare();\n }\n return mesh._bonesTransformMatrices;\n }\n if (!this._transformMatrices || this._isDirty) {\n this.prepare();\n }\n return this._transformMatrices;\n }\n /**\n * Gets the list of transform matrices to send to shaders inside a texture (one matrix per bone)\n * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)\n * @returns a raw texture containing the data\n */\n getTransformMatrixTexture(mesh) {\n if (this.needInitialSkinMatrix && mesh._transformMatrixTexture) {\n return mesh._transformMatrixTexture;\n }\n return this._transformMatrixTexture;\n }\n /**\n * Gets the current hosting scene\n * @returns a scene object\n */\n getScene() {\n return this._scene;\n }\n // Methods\n /**\n * Gets a string representing the current skeleton data\n * @param fullDetails defines a boolean indicating if we want a verbose version\n * @returns a string representing the current skeleton data\n */\n toString(fullDetails) {\n let ret = `Name: ${this.name}, nBones: ${this.bones.length}`;\n ret += `, nAnimationRanges: ${this._ranges ? Object.keys(this._ranges).length : \"none\"}`;\n if (fullDetails) {\n ret += \", Ranges: {\";\n let first = true;\n for (const name in this._ranges) {\n if (first) {\n ret += \", \";\n first = false;\n }\n ret += name;\n }\n ret += \"}\";\n }\n return ret;\n }\n /**\n * Get bone's index searching by name\n * @param name defines bone's name to search for\n * @returns the indice of the bone. Returns -1 if not found\n */\n getBoneIndexByName(name) {\n for (let boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {\n if (this.bones[boneIndex].name === name) {\n return boneIndex;\n }\n }\n return -1;\n }\n /**\n * Create a new animation range\n * @param name defines the name of the range\n * @param from defines the start key\n * @param to defines the end key\n */\n createAnimationRange(name, from, to) {\n // check name not already in use\n if (!this._ranges[name]) {\n this._ranges[name] = new AnimationRange(name, from, to);\n for (let i = 0, nBones = this.bones.length; i < nBones; i++) {\n if (this.bones[i].animations[0]) {\n this.bones[i].animations[0].createRange(name, from, to);\n }\n }\n }\n }\n /**\n * Delete a specific animation range\n * @param name defines the name of the range\n * @param deleteFrames defines if frames must be removed as well\n */\n deleteAnimationRange(name, deleteFrames = true) {\n for (let i = 0, nBones = this.bones.length; i < nBones; i++) {\n if (this.bones[i].animations[0]) {\n this.bones[i].animations[0].deleteRange(name, deleteFrames);\n }\n }\n this._ranges[name] = null; // said much faster than 'delete this._range[name]'\n }\n /**\n * Gets a specific animation range\n * @param name defines the name of the range to look for\n * @returns the requested animation range or null if not found\n */\n getAnimationRange(name) {\n return this._ranges[name] || null;\n }\n /**\n * Gets the list of all animation ranges defined on this skeleton\n * @returns an array\n */\n getAnimationRanges() {\n const animationRanges = [];\n let name;\n for (name in this._ranges) {\n animationRanges.push(this._ranges[name]);\n }\n return animationRanges;\n }\n /**\n * Copy animation range from a source skeleton.\n * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences\n * @param source defines the source skeleton\n * @param name defines the name of the range to copy\n * @param rescaleAsRequired defines if rescaling must be applied if required\n * @returns true if operation was successful\n */\n copyAnimationRange(source, name, rescaleAsRequired = false) {\n if (this._ranges[name] || !source.getAnimationRange(name)) {\n return false;\n }\n let ret = true;\n const frameOffset = this._getHighestAnimationFrame() + 1;\n // make a dictionary of source skeleton's bones, so exact same order or doubly nested loop is not required\n const boneDict = {};\n const sourceBones = source.bones;\n let nBones;\n let i;\n for (i = 0, nBones = sourceBones.length; i < nBones; i++) {\n boneDict[sourceBones[i].name] = sourceBones[i];\n }\n if (this.bones.length !== sourceBones.length) {\n Logger.Warn(`copyAnimationRange: this rig has ${this.bones.length} bones, while source as ${sourceBones.length}`);\n ret = false;\n }\n const skelDimensionsRatio = rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;\n for (i = 0, nBones = this.bones.length; i < nBones; i++) {\n const boneName = this.bones[i].name;\n const sourceBone = boneDict[boneName];\n if (sourceBone) {\n ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);\n }\n else {\n Logger.Warn(\"copyAnimationRange: not same rig, missing source bone \" + boneName);\n ret = false;\n }\n }\n // do not call createAnimationRange(), since it also is done to bones, which was already done\n const range = source.getAnimationRange(name);\n if (range) {\n this._ranges[name] = new AnimationRange(name, range.from + frameOffset, range.to + frameOffset);\n }\n return ret;\n }\n /**\n * Forces the skeleton to go to rest pose\n */\n returnToRest() {\n for (const bone of this.bones) {\n if (bone._index !== -1) {\n bone.returnToRest();\n }\n }\n }\n _getHighestAnimationFrame() {\n let ret = 0;\n for (let i = 0, nBones = this.bones.length; i < nBones; i++) {\n if (this.bones[i].animations[0]) {\n const highest = this.bones[i].animations[0].getHighestFrame();\n if (ret < highest) {\n ret = highest;\n }\n }\n }\n return ret;\n }\n /**\n * Begin a specific animation range\n * @param name defines the name of the range to start\n * @param loop defines if looping must be turned on (false by default)\n * @param speedRatio defines the speed ratio to apply (1 by default)\n * @param onAnimationEnd defines a callback which will be called when animation will end\n * @returns a new animatable\n */\n beginAnimation(name, loop, speedRatio, onAnimationEnd) {\n const range = this.getAnimationRange(name);\n if (!range) {\n return null;\n }\n return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);\n }\n /**\n * Convert the keyframes for a range of animation on a skeleton to be relative to a given reference frame.\n * @param skeleton defines the Skeleton containing the animation range to convert\n * @param referenceFrame defines the frame that keyframes in the range will be relative to\n * @param range defines the name of the AnimationRange belonging to the Skeleton to convert\n * @returns the original skeleton\n */\n static MakeAnimationAdditive(skeleton, referenceFrame = 0, range) {\n const rangeValue = skeleton.getAnimationRange(range);\n // We can't make a range additive if it doesn't exist\n if (!rangeValue) {\n return null;\n }\n // Find any current scene-level animatable belonging to the target that matches the range\n const sceneAnimatables = skeleton._scene.getAllAnimatablesByTarget(skeleton);\n let rangeAnimatable = null;\n for (let index = 0; index < sceneAnimatables.length; index++) {\n const sceneAnimatable = sceneAnimatables[index];\n if (sceneAnimatable.fromFrame === (rangeValue === null || rangeValue === void 0 ? void 0 : rangeValue.from) && sceneAnimatable.toFrame === (rangeValue === null || rangeValue === void 0 ? void 0 : rangeValue.to)) {\n rangeAnimatable = sceneAnimatable;\n break;\n }\n }\n // Convert the animations belonging to the skeleton to additive keyframes\n const animatables = skeleton.getAnimatables();\n for (let index = 0; index < animatables.length; index++) {\n const animatable = animatables[index];\n const animations = animatable.animations;\n if (!animations) {\n continue;\n }\n for (let animIndex = 0; animIndex < animations.length; animIndex++) {\n Animation.MakeAnimationAdditive(animations[animIndex], referenceFrame, range);\n }\n }\n // Mark the scene-level animatable as additive\n if (rangeAnimatable) {\n rangeAnimatable.isAdditive = true;\n }\n return skeleton;\n }\n /** @internal */\n _markAsDirty() {\n this._isDirty = true;\n this._absoluteTransformIsDirty = true;\n }\n /**\n * @internal\n */\n _registerMeshWithPoseMatrix(mesh) {\n this._meshesWithPoseMatrix.push(mesh);\n }\n /**\n * @internal\n */\n _unregisterMeshWithPoseMatrix(mesh) {\n const index = this._meshesWithPoseMatrix.indexOf(mesh);\n if (index > -1) {\n this._meshesWithPoseMatrix.splice(index, 1);\n }\n }\n _computeTransformMatrices(targetMatrix, initialSkinMatrix) {\n this.onBeforeComputeObservable.notifyObservers(this);\n for (let index = 0; index < this.bones.length; index++) {\n const bone = this.bones[index];\n bone._childUpdateId++;\n const parentBone = bone.getParent();\n if (parentBone) {\n bone.getLocalMatrix().multiplyToRef(parentBone.getFinalMatrix(), bone.getFinalMatrix());\n }\n else {\n if (initialSkinMatrix) {\n bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getFinalMatrix());\n }\n else {\n bone.getFinalMatrix().copyFrom(bone.getLocalMatrix());\n }\n }\n if (bone._index !== -1) {\n const mappedIndex = bone._index === null ? index : bone._index;\n bone.getAbsoluteInverseBindMatrix().multiplyToArray(bone.getFinalMatrix(), targetMatrix, mappedIndex * 16);\n }\n }\n this._identity.copyToArray(targetMatrix, this.bones.length * 16);\n }\n /**\n * Build all resources required to render a skeleton\n */\n prepare() {\n // Update the local matrix of bones with linked transform nodes.\n if (this._numBonesWithLinkedTransformNode > 0) {\n for (const bone of this.bones) {\n if (bone._linkedTransformNode) {\n const node = bone._linkedTransformNode;\n bone.position = node.position;\n if (node.rotationQuaternion) {\n bone.rotationQuaternion = node.rotationQuaternion;\n }\n else {\n bone.rotation = node.rotation;\n }\n bone.scaling = node.scaling;\n }\n }\n }\n if (this.needInitialSkinMatrix) {\n for (const mesh of this._meshesWithPoseMatrix) {\n const poseMatrix = mesh.getPoseMatrix();\n let needsUpdate = this._isDirty;\n if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {\n mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));\n needsUpdate = true;\n }\n if (!needsUpdate) {\n continue;\n }\n if (this._synchronizedWithMesh !== mesh) {\n this._synchronizedWithMesh = mesh;\n // Prepare bones\n for (const bone of this.bones) {\n if (!bone.getParent()) {\n const matrix = bone.getBindMatrix();\n matrix.multiplyToRef(poseMatrix, TmpVectors.Matrix[1]);\n bone._updateAbsoluteBindMatrices(TmpVectors.Matrix[1]);\n }\n }\n if (this.isUsingTextureForMatrices) {\n const textureWidth = (this.bones.length + 1) * 4;\n if (!mesh._transformMatrixTexture || mesh._transformMatrixTexture.getSize().width !== textureWidth) {\n if (mesh._transformMatrixTexture) {\n mesh._transformMatrixTexture.dispose();\n }\n mesh._transformMatrixTexture = RawTexture.CreateRGBATexture(mesh._bonesTransformMatrices, (this.bones.length + 1) * 4, 1, this._scene, false, false, 1, 1);\n }\n }\n }\n this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);\n if (this.isUsingTextureForMatrices && mesh._transformMatrixTexture) {\n mesh._transformMatrixTexture.update(mesh._bonesTransformMatrices);\n }\n }\n }\n else {\n if (!this._isDirty) {\n return;\n }\n if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {\n this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));\n if (this.isUsingTextureForMatrices) {\n if (this._transformMatrixTexture) {\n this._transformMatrixTexture.dispose();\n }\n this._transformMatrixTexture = RawTexture.CreateRGBATexture(this._transformMatrices, (this.bones.length + 1) * 4, 1, this._scene, false, false, 1, 1);\n }\n }\n this._computeTransformMatrices(this._transformMatrices, null);\n if (this.isUsingTextureForMatrices && this._transformMatrixTexture) {\n this._transformMatrixTexture.update(this._transformMatrices);\n }\n }\n this._isDirty = false;\n }\n /**\n * Gets the list of animatables currently running for this skeleton\n * @returns an array of animatables\n */\n getAnimatables() {\n if (!this._animatables || this._animatables.length !== this.bones.length) {\n this._animatables = [];\n for (let index = 0; index < this.bones.length; index++) {\n this._animatables.push(this.bones[index]);\n }\n }\n return this._animatables;\n }\n /**\n * Clone the current skeleton\n * @param name defines the name of the new skeleton\n * @param id defines the id of the new skeleton\n * @returns the new skeleton\n */\n clone(name, id) {\n const result = new Skeleton(name, id || name, this._scene);\n result.needInitialSkinMatrix = this.needInitialSkinMatrix;\n for (let index = 0; index < this.bones.length; index++) {\n const source = this.bones[index];\n let parentBone = null;\n const parent = source.getParent();\n if (parent) {\n const parentIndex = this.bones.indexOf(parent);\n parentBone = result.bones[parentIndex];\n }\n const bone = new Bone(source.name, result, parentBone, source.getBindMatrix().clone(), source.getRestMatrix().clone());\n bone._index = source._index;\n if (source._linkedTransformNode) {\n bone.linkTransformNode(source._linkedTransformNode);\n }\n DeepCopier.DeepCopy(source.animations, bone.animations);\n }\n if (this._ranges) {\n result._ranges = {};\n for (const rangeName in this._ranges) {\n const range = this._ranges[rangeName];\n if (range) {\n result._ranges[rangeName] = range.clone();\n }\n }\n }\n this._isDirty = true;\n return result;\n }\n /**\n * Enable animation blending for this skeleton\n * @param blendingSpeed defines the blending speed to apply\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#animation-blending\n */\n enableBlending(blendingSpeed = 0.01) {\n this.bones.forEach((bone) => {\n bone.animations.forEach((animation) => {\n animation.enableBlending = true;\n animation.blendingSpeed = blendingSpeed;\n });\n });\n }\n /**\n * Releases all resources associated with the current skeleton\n */\n dispose() {\n this._meshesWithPoseMatrix.length = 0;\n // Animations\n this.getScene().stopAnimation(this);\n // Remove from scene\n this.getScene().removeSkeleton(this);\n if (this._parentContainer) {\n const index = this._parentContainer.skeletons.indexOf(this);\n if (index > -1) {\n this._parentContainer.skeletons.splice(index, 1);\n }\n this._parentContainer = null;\n }\n if (this._transformMatrixTexture) {\n this._transformMatrixTexture.dispose();\n this._transformMatrixTexture = null;\n }\n }\n /**\n * Serialize the skeleton in a JSON object\n * @returns a JSON object\n */\n serialize() {\n var _a;\n const serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.id = this.id;\n if (this.dimensionsAtRest) {\n serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();\n }\n serializationObject.bones = [];\n serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;\n for (let index = 0; index < this.bones.length; index++) {\n const bone = this.bones[index];\n const parent = bone.getParent();\n const serializedBone = {\n parentBoneIndex: parent ? this.bones.indexOf(parent) : -1,\n index: bone.getIndex(),\n name: bone.name,\n id: bone.id,\n matrix: bone.getBindMatrix().toArray(),\n rest: bone.getRestMatrix().toArray(),\n linkedTransformNodeId: (_a = bone.getTransformNode()) === null || _a === void 0 ? void 0 : _a.id,\n };\n serializationObject.bones.push(serializedBone);\n if (bone.length) {\n serializedBone.length = bone.length;\n }\n if (bone.metadata) {\n serializedBone.metadata = bone.metadata;\n }\n if (bone.animations && bone.animations.length > 0) {\n serializedBone.animation = bone.animations[0].serialize();\n }\n serializationObject.ranges = [];\n for (const name in this._ranges) {\n const source = this._ranges[name];\n if (!source) {\n continue;\n }\n const range = {};\n range.name = name;\n range.from = source.from;\n range.to = source.to;\n serializationObject.ranges.push(range);\n }\n }\n return serializationObject;\n }\n /**\n * Creates a new skeleton from serialized data\n * @param parsedSkeleton defines the serialized data\n * @param scene defines the hosting scene\n * @returns a new skeleton\n */\n static Parse(parsedSkeleton, scene) {\n const skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);\n if (parsedSkeleton.dimensionsAtRest) {\n skeleton.dimensionsAtRest = Vector3.FromArray(parsedSkeleton.dimensionsAtRest);\n }\n skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;\n let index;\n for (index = 0; index < parsedSkeleton.bones.length; index++) {\n const parsedBone = parsedSkeleton.bones[index];\n const parsedBoneIndex = parsedSkeleton.bones[index].index;\n let parentBone = null;\n if (parsedBone.parentBoneIndex > -1) {\n parentBone = skeleton.bones[parsedBone.parentBoneIndex];\n }\n const rest = parsedBone.rest ? Matrix.FromArray(parsedBone.rest) : null;\n const bone = new Bone(parsedBone.name, skeleton, parentBone, Matrix.FromArray(parsedBone.matrix), rest, null, parsedBoneIndex);\n if (parsedBone.id !== undefined && parsedBone.id !== null) {\n bone.id = parsedBone.id;\n }\n if (parsedBone.length) {\n bone.length = parsedBone.length;\n }\n if (parsedBone.metadata) {\n bone.metadata = parsedBone.metadata;\n }\n if (parsedBone.animation) {\n bone.animations.push(Animation.Parse(parsedBone.animation));\n }\n if (parsedBone.linkedTransformNodeId !== undefined && parsedBone.linkedTransformNodeId !== null) {\n skeleton._hasWaitingData = true;\n bone._waitingTransformNodeId = parsedBone.linkedTransformNodeId;\n }\n }\n // placed after bones, so createAnimationRange can cascade down\n if (parsedSkeleton.ranges) {\n for (index = 0; index < parsedSkeleton.ranges.length; index++) {\n const data = parsedSkeleton.ranges[index];\n skeleton.createAnimationRange(data.name, data.from, data.to);\n }\n }\n return skeleton;\n }\n /**\n * Compute all node absolute matrices\n * @param forceUpdate defines if computation must be done even if cache is up to date\n */\n computeAbsoluteMatrices(forceUpdate = false) {\n if (this._absoluteTransformIsDirty || forceUpdate) {\n this.bones[0].computeAbsoluteMatrices();\n this._absoluteTransformIsDirty = false;\n }\n }\n /**\n * Compute all node absolute matrices\n * @param forceUpdate defines if computation must be done even if cache is up to date\n * @deprecated Please use computeAbsoluteMatrices instead\n */\n computeAbsoluteTransforms(forceUpdate = false) {\n this.computeAbsoluteMatrices(forceUpdate);\n }\n /**\n * Gets the root pose matrix\n * @returns a matrix\n */\n getPoseMatrix() {\n let poseMatrix = null;\n if (this._meshesWithPoseMatrix.length > 0) {\n poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();\n }\n return poseMatrix;\n }\n /**\n * Sorts bones per internal index\n */\n sortBones() {\n const bones = new Array();\n const visited = new Array(this.bones.length);\n for (let index = 0; index < this.bones.length; index++) {\n this._sortBones(index, bones, visited);\n }\n this.bones = bones;\n }\n _sortBones(index, bones, visited) {\n if (visited[index]) {\n return;\n }\n visited[index] = true;\n const bone = this.bones[index];\n if (!bone)\n return;\n if (bone._index === undefined) {\n bone._index = index;\n }\n const parentBone = bone.getParent();\n if (parentBone) {\n this._sortBones(this.bones.indexOf(parentBone), bones, visited);\n }\n bones.push(bone);\n }\n /**\n * Set the current local matrix as the restPose for all bones in the skeleton.\n */\n setCurrentPoseAsRest() {\n this.bones.forEach((b) => {\n b.setCurrentPoseAsRest();\n });\n }\n}\n//# sourceMappingURL=skeleton.js.map","export * from \"./bone.js\";\nexport * from \"./boneIKController.js\";\nexport * from \"./boneLookController.js\";\nexport * from \"./skeleton.js\";\n//# sourceMappingURL=index.js.map","\n/**\n * This class is a small wrapper around a native buffer that can be read and/or written\n */\nexport class StorageBuffer {\n /**\n * Creates a new storage buffer instance\n * @param engine The engine the buffer will be created inside\n * @param size The size of the buffer in bytes\n * @param creationFlags flags to use when creating the buffer (see undefined). The BUFFER_CREATIONFLAG_STORAGE flag will be automatically added.\n */\n constructor(engine, size, creationFlags = 3) {\n this._engine = engine;\n this._engine._storageBuffers.push(this);\n this._create(size, creationFlags);\n }\n _create(size, creationFlags) {\n this._bufferSize = size;\n this._creationFlags = creationFlags;\n this._buffer = this._engine.createStorageBuffer(size, creationFlags);\n }\n /** @internal */\n _rebuild() {\n this._create(this._bufferSize, this._creationFlags);\n }\n /**\n * Gets underlying native buffer\n * @returns underlying native buffer\n */\n getBuffer() {\n return this._buffer;\n }\n /**\n * Updates the storage buffer\n * @param data the data used to update the storage buffer\n * @param byteOffset the byte offset of the data (optional)\n * @param byteLength the byte length of the data (optional)\n */\n update(data, byteOffset, byteLength) {\n if (!this._buffer) {\n return;\n }\n this._engine.updateStorageBuffer(this._buffer, data, byteOffset, byteLength);\n }\n /**\n * Reads data from the storage buffer\n * @param offset The offset in the storage buffer to start reading from (default: 0)\n * @param size The number of bytes to read from the storage buffer (default: capacity of the buffer)\n * @param buffer The buffer to write the data we have read from the storage buffer to (optional)\n * @returns If not undefined, returns the (promise) buffer (as provided by the 4th parameter) filled with the data, else it returns a (promise) Uint8Array with the data read from the storage buffer\n */\n read(offset, size, buffer) {\n return this._engine.readFromStorageBuffer(this._buffer, offset, size, buffer);\n }\n /**\n * Disposes the storage buffer\n */\n dispose() {\n const storageBuffers = this._engine._storageBuffers;\n const index = storageBuffers.indexOf(this);\n if (index !== -1) {\n storageBuffers[index] = storageBuffers[storageBuffers.length - 1];\n storageBuffers.pop();\n }\n this._engine._releaseBuffer(this._buffer);\n this._buffer = null;\n }\n}\n//# sourceMappingURL=storageBuffer.js.map","export * from \"./buffer.js\";\nexport * from \"./dataBuffer.js\";\nexport * from \"./storageBuffer.js\";\n//# sourceMappingURL=index.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { PointerEventTypes } from \"../../Events/pointerEvents.js\";\nimport { EventConstants } from \"../../Events/deviceInputEvents.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * Base class for mouse wheel input..\n * See FollowCameraMouseWheelInput in src/Cameras/Inputs/freeCameraMouseWheelInput.ts\n * for example usage.\n */\nexport class BaseCameraMouseWheelInput {\n constructor() {\n /**\n * How fast is the camera moves in relation to X axis mouseWheel events.\n * Use negative value to reverse direction.\n */\n this.wheelPrecisionX = 3.0;\n /**\n * How fast is the camera moves in relation to Y axis mouseWheel events.\n * Use negative value to reverse direction.\n */\n this.wheelPrecisionY = 3.0;\n /**\n * How fast is the camera moves in relation to Z axis mouseWheel events.\n * Use negative value to reverse direction.\n */\n this.wheelPrecisionZ = 3.0;\n /**\n * Observable for when a mouse wheel move event occurs.\n */\n this.onChangedObservable = new Observable();\n /**\n * Incremental value of multiple mouse wheel movements of the X axis.\n * Should be zero-ed when read.\n */\n this._wheelDeltaX = 0;\n /**\n * Incremental value of multiple mouse wheel movements of the Y axis.\n * Should be zero-ed when read.\n */\n this._wheelDeltaY = 0;\n /**\n * Incremental value of multiple mouse wheel movements of the Z axis.\n * Should be zero-ed when read.\n */\n this._wheelDeltaZ = 0;\n /**\n * Firefox uses a different scheme to report scroll distances to other\n * browsers. Rather than use complicated methods to calculate the exact\n * multiple we need to apply, let's just cheat and use a constant.\n * https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/deltaMode\n * https://stackoverflow.com/questions/20110224/what-is-the-height-of-a-line-in-a-wheel-event-deltamode-dom-delta-line\n */\n this._ffMultiplier = 12;\n /**\n * Different event attributes for wheel data fall into a few set ranges.\n * Some relevant but dated date here:\n * https://stackoverflow.com/questions/5527601/normalizing-mousewheel-speed-across-browsers\n */\n this._normalize = 120;\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n * @param noPreventDefault Defines whether event caught by the controls\n * should call preventdefault().\n * (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(noPreventDefault) {\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n this._wheel = (pointer) => {\n // sanity check - this should be a PointerWheel event.\n if (pointer.type !== PointerEventTypes.POINTERWHEEL) {\n return;\n }\n const event = pointer.event;\n const platformScale = event.deltaMode === EventConstants.DOM_DELTA_LINE ? this._ffMultiplier : 1; // If this happens to be set to DOM_DELTA_LINE, adjust accordingly\n this._wheelDeltaX += (this.wheelPrecisionX * platformScale * event.deltaX) / this._normalize;\n this._wheelDeltaY -= (this.wheelPrecisionY * platformScale * event.deltaY) / this._normalize;\n this._wheelDeltaZ += (this.wheelPrecisionZ * platformScale * event.deltaZ) / this._normalize;\n if (event.preventDefault) {\n if (!noPreventDefault) {\n event.preventDefault();\n }\n }\n };\n this._observer = this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel, PointerEventTypes.POINTERWHEEL);\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n if (this._observer) {\n this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer);\n this._observer = null;\n this._wheel = null;\n }\n if (this.onChangedObservable) {\n this.onChangedObservable.clear();\n }\n }\n /**\n * Called for each rendered frame.\n */\n checkInputs() {\n this.onChangedObservable.notifyObservers({\n wheelDeltaX: this._wheelDeltaX,\n wheelDeltaY: this._wheelDeltaY,\n wheelDeltaZ: this._wheelDeltaZ,\n });\n // Clear deltas.\n this._wheelDeltaX = 0;\n this._wheelDeltaY = 0;\n this._wheelDeltaZ = 0;\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"BaseCameraMouseWheelInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"mousewheel\";\n }\n}\n__decorate([\n serialize()\n], BaseCameraMouseWheelInput.prototype, \"wheelPrecisionX\", void 0);\n__decorate([\n serialize()\n], BaseCameraMouseWheelInput.prototype, \"wheelPrecisionY\", void 0);\n__decorate([\n serialize()\n], BaseCameraMouseWheelInput.prototype, \"wheelPrecisionZ\", void 0);\n//# sourceMappingURL=BaseCameraMouseWheelInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nimport { PointerEventTypes } from \"../../Events/pointerEvents.js\";\n/**\n * Base class for Camera Pointer Inputs.\n * See FollowCameraPointersInput in src/Cameras/Inputs/followCameraPointersInput.ts\n * for example usage.\n */\nexport class BaseCameraPointersInput {\n constructor() {\n this._currentActiveButton = -1;\n /**\n * Defines the buttons associated with the input to handle camera move.\n */\n this.buttons = [0, 1, 2];\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(noPreventDefault) {\n // eslint-disable-next-line prefer-rest-params\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n const engine = this.camera.getEngine();\n const element = engine.getInputElement();\n let previousPinchSquaredDistance = 0;\n let previousMultiTouchPanPosition = null;\n this._pointA = null;\n this._pointB = null;\n this._altKey = false;\n this._ctrlKey = false;\n this._metaKey = false;\n this._shiftKey = false;\n this._buttonsPressed = 0;\n this._pointerInput = (p) => {\n var _a, _b;\n const evt = p.event;\n const isTouch = evt.pointerType === \"touch\";\n if (engine.isInVRExclusivePointerMode) {\n return;\n }\n if (p.type !== PointerEventTypes.POINTERMOVE && this.buttons.indexOf(evt.button) === -1) {\n return;\n }\n const srcElement = evt.target;\n this._altKey = evt.altKey;\n this._ctrlKey = evt.ctrlKey;\n this._metaKey = evt.metaKey;\n this._shiftKey = evt.shiftKey;\n this._buttonsPressed = evt.buttons;\n if (engine.isPointerLock) {\n const offsetX = evt.movementX;\n const offsetY = evt.movementY;\n this.onTouch(null, offsetX, offsetY);\n this._pointA = null;\n this._pointB = null;\n }\n else if (p.type !== PointerEventTypes.POINTERDOWN && isTouch && ((_a = this._pointA) === null || _a === void 0 ? void 0 : _a.pointerId) !== evt.pointerId && ((_b = this._pointB) === null || _b === void 0 ? void 0 : _b.pointerId) !== evt.pointerId) {\n return; // If we get a non-down event for a touch that we're not tracking, ignore it\n }\n else if (p.type === PointerEventTypes.POINTERDOWN && (this._currentActiveButton === -1 || isTouch)) {\n try {\n srcElement === null || srcElement === void 0 ? void 0 : srcElement.setPointerCapture(evt.pointerId);\n }\n catch (e) {\n //Nothing to do with the error. Execution will continue.\n }\n if (this._pointA === null) {\n this._pointA = {\n x: evt.clientX,\n y: evt.clientY,\n pointerId: evt.pointerId,\n type: evt.pointerType,\n };\n }\n else if (this._pointB === null) {\n this._pointB = {\n x: evt.clientX,\n y: evt.clientY,\n pointerId: evt.pointerId,\n type: evt.pointerType,\n };\n }\n else {\n return; // We are already tracking two pointers so ignore this one\n }\n if (this._currentActiveButton === -1 && !isTouch) {\n this._currentActiveButton = evt.button;\n }\n this.onButtonDown(evt);\n if (!noPreventDefault) {\n evt.preventDefault();\n element && element.focus();\n }\n }\n else if (p.type === PointerEventTypes.POINTERDOUBLETAP) {\n this.onDoubleTap(evt.pointerType);\n }\n else if (p.type === PointerEventTypes.POINTERUP && (this._currentActiveButton === evt.button || isTouch)) {\n try {\n srcElement === null || srcElement === void 0 ? void 0 : srcElement.releasePointerCapture(evt.pointerId);\n }\n catch (e) {\n //Nothing to do with the error.\n }\n if (!isTouch) {\n this._pointB = null; // Mouse and pen are mono pointer\n }\n //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,\n //but emptying completely pointers collection is required to fix a bug on iPhone :\n //when changing orientation while pinching camera,\n //one pointer stay pressed forever if we don't release all pointers\n //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected\n if (engine._badOS) {\n this._pointA = this._pointB = null;\n }\n else {\n //only remove the impacted pointer in case of multitouch allowing on most\n //platforms switching from rotate to zoom and pan seamlessly.\n if (this._pointB && this._pointA && this._pointA.pointerId == evt.pointerId) {\n this._pointA = this._pointB;\n this._pointB = null;\n }\n else if (this._pointA && this._pointB && this._pointB.pointerId == evt.pointerId) {\n this._pointB = null;\n }\n else {\n this._pointA = this._pointB = null;\n }\n }\n if (previousPinchSquaredDistance !== 0 || previousMultiTouchPanPosition) {\n // Previous pinch data is populated but a button has been lifted\n // so pinch has ended.\n this.onMultiTouch(this._pointA, this._pointB, previousPinchSquaredDistance, 0, // pinchSquaredDistance\n previousMultiTouchPanPosition, null // multiTouchPanPosition\n );\n previousPinchSquaredDistance = 0;\n previousMultiTouchPanPosition = null;\n }\n this._currentActiveButton = -1;\n this.onButtonUp(evt);\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n else if (p.type === PointerEventTypes.POINTERMOVE) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n // One button down\n if (this._pointA && this._pointB === null) {\n const offsetX = evt.clientX - this._pointA.x;\n const offsetY = evt.clientY - this._pointA.y;\n this.onTouch(this._pointA, offsetX, offsetY);\n this._pointA.x = evt.clientX;\n this._pointA.y = evt.clientY;\n }\n // Two buttons down: pinch\n else if (this._pointA && this._pointB) {\n const ed = this._pointA.pointerId === evt.pointerId ? this._pointA : this._pointB;\n ed.x = evt.clientX;\n ed.y = evt.clientY;\n const distX = this._pointA.x - this._pointB.x;\n const distY = this._pointA.y - this._pointB.y;\n const pinchSquaredDistance = distX * distX + distY * distY;\n const multiTouchPanPosition = {\n x: (this._pointA.x + this._pointB.x) / 2,\n y: (this._pointA.y + this._pointB.y) / 2,\n pointerId: evt.pointerId,\n type: p.type,\n };\n this.onMultiTouch(this._pointA, this._pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition);\n previousMultiTouchPanPosition = multiTouchPanPosition;\n previousPinchSquaredDistance = pinchSquaredDistance;\n }\n }\n };\n this._observer = this.camera\n .getScene()\n ._inputManager._addCameraPointerObserver(this._pointerInput, PointerEventTypes.POINTERDOWN | PointerEventTypes.POINTERUP | PointerEventTypes.POINTERMOVE | PointerEventTypes.POINTERDOUBLETAP);\n this._onLostFocus = () => {\n this._pointA = this._pointB = null;\n previousPinchSquaredDistance = 0;\n previousMultiTouchPanPosition = null;\n this.onLostFocus();\n };\n this._contextMenuBind = this.onContextMenu.bind(this);\n element && element.addEventListener(\"contextmenu\", this._contextMenuBind, false);\n const hostWindow = this.camera.getScene().getEngine().getHostWindow();\n if (hostWindow) {\n Tools.RegisterTopRootEvents(hostWindow, [{ name: \"blur\", handler: this._onLostFocus }]);\n }\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n if (this._onLostFocus) {\n const hostWindow = this.camera.getScene().getEngine().getHostWindow();\n if (hostWindow) {\n Tools.UnregisterTopRootEvents(hostWindow, [{ name: \"blur\", handler: this._onLostFocus }]);\n }\n }\n if (this._observer) {\n this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer);\n this._observer = null;\n if (this._contextMenuBind) {\n const inputElement = this.camera.getScene().getEngine().getInputElement();\n inputElement && inputElement.removeEventListener(\"contextmenu\", this._contextMenuBind);\n }\n this._onLostFocus = null;\n }\n this._altKey = false;\n this._ctrlKey = false;\n this._metaKey = false;\n this._shiftKey = false;\n this._buttonsPressed = 0;\n this._currentActiveButton = -1;\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"BaseCameraPointersInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"pointers\";\n }\n /**\n * Called on pointer POINTERDOUBLETAP event.\n * Override this method to provide functionality on POINTERDOUBLETAP event.\n * @param type\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onDoubleTap(type) { }\n /**\n * Called on pointer POINTERMOVE event if only a single touch is active.\n * Override this method to provide functionality.\n * @param point\n * @param offsetX\n * @param offsetY\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onTouch(point, offsetX, offsetY) { }\n /**\n * Called on pointer POINTERMOVE event if multiple touches are active.\n * Override this method to provide functionality.\n * @param _pointA\n * @param _pointB\n * @param previousPinchSquaredDistance\n * @param pinchSquaredDistance\n * @param previousMultiTouchPanPosition\n * @param multiTouchPanPosition\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onMultiTouch(_pointA, _pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition) { }\n /**\n * Called on JS contextmenu event.\n * Override this method to provide functionality.\n * @param evt\n */\n onContextMenu(evt) {\n evt.preventDefault();\n }\n /**\n * Called each time a new POINTERDOWN event occurs. Ie, for each button\n * press.\n * Override this method to provide functionality.\n * @param evt\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onButtonDown(evt) { }\n /**\n * Called each time a new POINTERUP event occurs. Ie, for each button\n * release.\n * Override this method to provide functionality.\n * @param evt\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onButtonUp(evt) { }\n /**\n * Called when window becomes inactive.\n * Override this method to provide functionality.\n */\n onLostFocus() { }\n}\n__decorate([\n serialize()\n], BaseCameraPointersInput.prototype, \"buttons\", void 0);\n//# sourceMappingURL=BaseCameraPointersInput.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { SerializationHelper } from \"../Misc/decorators.js\";\nimport { Camera } from \"./camera.js\";\n/**\n * @ignore\n * This is a list of all the different input types that are available in the application.\n * Fo instance: ArcRotateCameraGamepadInput...\n */\n// eslint-disable-next-line no-var, @typescript-eslint/naming-convention\nexport var CameraInputTypes = {};\n/**\n * This represents the input manager used within a camera.\n * It helps dealing with all the different kind of input attached to a camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class CameraInputsManager {\n /**\n * Instantiate a new Camera Input Manager.\n * @param camera Defines the camera the input manager belongs to\n */\n constructor(camera) {\n /**\n * Defines the dom element the camera is collecting inputs from.\n * This is null if the controls have not been attached.\n */\n this.attachedToElement = false;\n this.attached = {};\n this.camera = camera;\n this.checkInputs = () => { };\n }\n /**\n * Add an input method to a camera\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n * @param input Camera input method\n */\n add(input) {\n const type = input.getSimpleName();\n if (this.attached[type]) {\n Logger.Warn(\"camera input of type \" + type + \" already exists on camera\");\n return;\n }\n this.attached[type] = input;\n input.camera = this.camera;\n // for checkInputs, we are dynamically creating a function\n // the goal is to avoid the performance penalty of looping for inputs in the render loop\n if (input.checkInputs) {\n this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));\n }\n if (this.attachedToElement) {\n input.attachControl(this.noPreventDefault);\n }\n }\n /**\n * Remove a specific input method from a camera\n * example: camera.inputs.remove(camera.inputs.attached.mouse);\n * @param inputToRemove camera input method\n */\n remove(inputToRemove) {\n for (const cam in this.attached) {\n const input = this.attached[cam];\n if (input === inputToRemove) {\n input.detachControl();\n input.camera = null;\n delete this.attached[cam];\n this.rebuildInputCheck();\n return;\n }\n }\n }\n /**\n * Remove a specific input type from a camera\n * example: camera.inputs.remove(\"ArcRotateCameraGamepadInput\");\n * @param inputType the type of the input to remove\n */\n removeByType(inputType) {\n for (const cam in this.attached) {\n const input = this.attached[cam];\n if (input.getClassName() === inputType) {\n input.detachControl();\n input.camera = null;\n delete this.attached[cam];\n this.rebuildInputCheck();\n }\n }\n }\n _addCheckInputs(fn) {\n const current = this.checkInputs;\n return () => {\n current();\n fn();\n };\n }\n /**\n * Attach the input controls to the currently attached dom element to listen the events from.\n * @param input Defines the input to attach\n */\n attachInput(input) {\n if (this.attachedToElement) {\n input.attachControl(this.noPreventDefault);\n }\n }\n /**\n * Attach the current manager inputs controls to a specific dom element to listen the events from.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachElement(noPreventDefault = false) {\n if (this.attachedToElement) {\n return;\n }\n noPreventDefault = Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;\n this.attachedToElement = true;\n this.noPreventDefault = noPreventDefault;\n for (const cam in this.attached) {\n this.attached[cam].attachControl(noPreventDefault);\n }\n }\n /**\n * Detach the current manager inputs controls from a specific dom element.\n * @param disconnect Defines whether the input should be removed from the current list of attached inputs\n */\n detachElement(disconnect = false) {\n for (const cam in this.attached) {\n this.attached[cam].detachControl();\n if (disconnect) {\n this.attached[cam].camera = null;\n }\n }\n this.attachedToElement = false;\n }\n /**\n * Rebuild the dynamic inputCheck function from the current list of\n * defined inputs in the manager.\n */\n rebuildInputCheck() {\n this.checkInputs = () => { };\n for (const cam in this.attached) {\n const input = this.attached[cam];\n if (input.checkInputs) {\n this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));\n }\n }\n }\n /**\n * Remove all attached input methods from a camera\n */\n clear() {\n if (this.attachedToElement) {\n this.detachElement(true);\n }\n this.attached = {};\n this.attachedToElement = false;\n this.checkInputs = () => { };\n }\n /**\n * Serialize the current input manager attached to a camera.\n * This ensures than once parsed,\n * the input associated to the camera will be identical to the current ones\n * @param serializedCamera Defines the camera serialization JSON the input serialization should write to\n */\n serialize(serializedCamera) {\n const inputs = {};\n for (const cam in this.attached) {\n const input = this.attached[cam];\n const res = SerializationHelper.Serialize(input);\n inputs[input.getClassName()] = res;\n }\n serializedCamera.inputsmgr = inputs;\n }\n /**\n * Parses an input manager serialized JSON to restore the previous list of inputs\n * and states associated to a camera.\n * @param parsedCamera Defines the JSON to parse\n */\n parse(parsedCamera) {\n const parsedInputs = parsedCamera.inputsmgr;\n if (parsedInputs) {\n this.clear();\n for (const n in parsedInputs) {\n const construct = CameraInputTypes[n];\n if (construct) {\n const parsedinput = parsedInputs[n];\n const input = SerializationHelper.Parse(() => {\n return new construct();\n }, parsedinput, null);\n this.add(input);\n }\n }\n }\n else {\n //2016-03-08 this part is for managing backward compatibility\n for (const n in this.attached) {\n const construct = CameraInputTypes[this.attached[n].getClassName()];\n if (construct) {\n const input = SerializationHelper.Parse(() => {\n return new construct();\n }, parsedCamera, null);\n this.remove(this.attached[n]);\n this.add(input);\n }\n }\n }\n }\n}\n//# sourceMappingURL=cameraInputsManager.js.map","import { Observable } from \"../Misc/observable.js\";\n/**\n * Represents a gamepad control stick position\n */\nexport class StickValues {\n /**\n * Initializes the gamepad x and y control stick values\n * @param x The x component of the gamepad control stick value\n * @param y The y component of the gamepad control stick value\n */\n constructor(\n /**\n * The x component of the control stick\n */\n x, \n /**\n * The y component of the control stick\n */\n y) {\n this.x = x;\n this.y = y;\n }\n}\n/**\n * Represents a gamepad\n */\nexport class Gamepad {\n /**\n * Specifies if the gamepad has been connected\n */\n get isConnected() {\n return this._isConnected;\n }\n /**\n * Initializes the gamepad\n * @param id The id of the gamepad\n * @param index The index of the gamepad\n * @param browserGamepad The browser gamepad\n * @param leftStickX The x component of the left joystick\n * @param leftStickY The y component of the left joystick\n * @param rightStickX The x component of the right joystick\n * @param rightStickY The y component of the right joystick\n */\n constructor(\n /**\n * The id of the gamepad\n */\n id, \n /**\n * The index of the gamepad\n */\n index, \n /**\n * The browser gamepad\n */\n browserGamepad, leftStickX = 0, leftStickY = 1, rightStickX = 2, rightStickY = 3) {\n this.id = id;\n this.index = index;\n this.browserGamepad = browserGamepad;\n this._leftStick = { x: 0, y: 0 };\n this._rightStick = { x: 0, y: 0 };\n /** @internal */\n this._isConnected = true;\n /**\n * Specifies whether the left control stick should be Y-inverted\n */\n this._invertLeftStickY = false;\n this.type = Gamepad.GAMEPAD;\n this._leftStickAxisX = leftStickX;\n this._leftStickAxisY = leftStickY;\n this._rightStickAxisX = rightStickX;\n this._rightStickAxisY = rightStickY;\n if (this.browserGamepad.axes.length >= 2) {\n this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };\n }\n if (this.browserGamepad.axes.length >= 4) {\n this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };\n }\n }\n /**\n * Callback triggered when the left joystick has changed\n * @param callback\n */\n onleftstickchanged(callback) {\n this._onleftstickchanged = callback;\n }\n /**\n * Callback triggered when the right joystick has changed\n * @param callback\n */\n onrightstickchanged(callback) {\n this._onrightstickchanged = callback;\n }\n /**\n * Gets the left joystick\n */\n get leftStick() {\n return this._leftStick;\n }\n /**\n * Sets the left joystick values\n */\n set leftStick(newValues) {\n if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {\n this._onleftstickchanged(newValues);\n }\n this._leftStick = newValues;\n }\n /**\n * Gets the right joystick\n */\n get rightStick() {\n return this._rightStick;\n }\n /**\n * Sets the right joystick value\n */\n set rightStick(newValues) {\n if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {\n this._onrightstickchanged(newValues);\n }\n this._rightStick = newValues;\n }\n /**\n * Updates the gamepad joystick positions\n */\n update() {\n if (this._leftStick) {\n this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };\n if (this._invertLeftStickY) {\n this.leftStick.y *= -1;\n }\n }\n if (this._rightStick) {\n this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };\n }\n }\n /**\n * Disposes the gamepad\n */\n dispose() { }\n}\n/**\n * Represents a gamepad controller\n */\nGamepad.GAMEPAD = 0;\n/**\n * Represents a generic controller\n */\nGamepad.GENERIC = 1;\n/**\n * Represents an XBox controller\n */\nGamepad.XBOX = 2;\n/**\n * Represents a pose-enabled controller\n */\nGamepad.POSE_ENABLED = 3;\n/**\n * Represents an Dual Shock controller\n */\nGamepad.DUALSHOCK = 4;\n/**\n * Represents a generic gamepad\n */\nexport class GenericPad extends Gamepad {\n /**\n * Callback triggered when a button has been pressed\n * @param callback Called when a button has been pressed\n */\n onbuttondown(callback) {\n this._onbuttondown = callback;\n }\n /**\n * Callback triggered when a button has been released\n * @param callback Called when a button has been released\n */\n onbuttonup(callback) {\n this._onbuttonup = callback;\n }\n /**\n * Initializes the generic gamepad\n * @param id The id of the generic gamepad\n * @param index The index of the generic gamepad\n * @param browserGamepad The browser gamepad\n */\n constructor(id, index, browserGamepad) {\n super(id, index, browserGamepad);\n /**\n * Observable triggered when a button has been pressed\n */\n this.onButtonDownObservable = new Observable();\n /**\n * Observable triggered when a button has been released\n */\n this.onButtonUpObservable = new Observable();\n this.type = Gamepad.GENERIC;\n this._buttons = new Array(browserGamepad.buttons.length);\n }\n _setButtonValue(newValue, currentValue, buttonIndex) {\n if (newValue !== currentValue) {\n if (newValue === 1) {\n if (this._onbuttondown) {\n this._onbuttondown(buttonIndex);\n }\n this.onButtonDownObservable.notifyObservers(buttonIndex);\n }\n if (newValue === 0) {\n if (this._onbuttonup) {\n this._onbuttonup(buttonIndex);\n }\n this.onButtonUpObservable.notifyObservers(buttonIndex);\n }\n }\n return newValue;\n }\n /**\n * Updates the generic gamepad\n */\n update() {\n super.update();\n for (let index = 0; index < this._buttons.length; index++) {\n this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);\n }\n }\n /**\n * Disposes the generic gamepad\n */\n dispose() {\n super.dispose();\n this.onButtonDownObservable.clear();\n this.onButtonUpObservable.clear();\n }\n}\n//# sourceMappingURL=gamepad.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { Gamepad } from \"../../Gamepads/gamepad.js\";\n/**\n * Manage the gamepad inputs to control an arc rotate camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class ArcRotateCameraGamepadInput {\n constructor() {\n /**\n * Defines the gamepad rotation sensibility.\n * This is the threshold from when rotation starts to be accounted for to prevent jittering.\n */\n this.gamepadRotationSensibility = 80;\n /**\n * Defines the gamepad move sensibility.\n * This is the threshold from when moving starts to be accounted for for to prevent jittering.\n */\n this.gamepadMoveSensibility = 40;\n this._yAxisScale = 1.0;\n }\n /**\n * Gets or sets a boolean indicating that Yaxis (for right stick) should be inverted\n */\n get invertYAxis() {\n return this._yAxisScale !== 1.0;\n }\n set invertYAxis(value) {\n this._yAxisScale = value ? -1.0 : 1.0;\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n */\n attachControl() {\n const manager = this.camera.getScene().gamepadManager;\n this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add((gamepad) => {\n if (gamepad.type !== Gamepad.POSE_ENABLED) {\n // prioritize XBOX gamepads.\n if (!this.gamepad || gamepad.type === Gamepad.XBOX) {\n this.gamepad = gamepad;\n }\n }\n });\n this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add((gamepad) => {\n if (this.gamepad === gamepad) {\n this.gamepad = null;\n }\n });\n this.gamepad = manager.getGamepadByType(Gamepad.XBOX);\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);\n this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);\n this.gamepad = null;\n }\n /**\n * Update the current camera state depending on the inputs that have been used this frame.\n * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.\n */\n checkInputs() {\n if (this.gamepad) {\n const camera = this.camera;\n const rsValues = this.gamepad.rightStick;\n if (rsValues) {\n if (rsValues.x != 0) {\n const normalizedRX = rsValues.x / this.gamepadRotationSensibility;\n if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {\n camera.inertialAlphaOffset += normalizedRX;\n }\n }\n if (rsValues.y != 0) {\n const normalizedRY = (rsValues.y / this.gamepadRotationSensibility) * this._yAxisScale;\n if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {\n camera.inertialBetaOffset += normalizedRY;\n }\n }\n }\n const lsValues = this.gamepad.leftStick;\n if (lsValues && lsValues.y != 0) {\n const normalizedLY = lsValues.y / this.gamepadMoveSensibility;\n if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {\n this.camera.inertialRadiusOffset -= normalizedLY;\n }\n }\n }\n }\n /**\n * Gets the class name of the current intput.\n * @returns the class name\n */\n getClassName() {\n return \"ArcRotateCameraGamepadInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"gamepad\";\n }\n}\n__decorate([\n serialize()\n], ArcRotateCameraGamepadInput.prototype, \"gamepadRotationSensibility\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraGamepadInput.prototype, \"gamepadMoveSensibility\", void 0);\nCameraInputTypes[\"ArcRotateCameraGamepadInput\"] = ArcRotateCameraGamepadInput;\n//# sourceMappingURL=arcRotateCameraGamepadInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { KeyboardEventTypes } from \"../../Events/keyboardEvents.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * Manage the keyboard inputs to control the movement of an arc rotate camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class ArcRotateCameraKeyboardMoveInput {\n constructor() {\n /**\n * Defines the list of key codes associated with the up action (increase alpha)\n */\n this.keysUp = [38];\n /**\n * Defines the list of key codes associated with the down action (decrease alpha)\n */\n this.keysDown = [40];\n /**\n * Defines the list of key codes associated with the left action (increase beta)\n */\n this.keysLeft = [37];\n /**\n * Defines the list of key codes associated with the right action (decrease beta)\n */\n this.keysRight = [39];\n /**\n * Defines the list of key codes associated with the reset action.\n * Those keys reset the camera to its last stored state (with the method camera.storeState())\n */\n this.keysReset = [220];\n /**\n * Defines the panning sensibility of the inputs.\n * (How fast is the camera panning)\n */\n this.panningSensibility = 50.0;\n /**\n * Defines the zooming sensibility of the inputs.\n * (How fast is the camera zooming)\n */\n this.zoomingSensibility = 25.0;\n /**\n * Defines whether maintaining the alt key down switch the movement mode from\n * orientation to zoom.\n */\n this.useAltToZoom = true;\n /**\n * Rotation speed of the camera\n */\n this.angularSpeed = 0.01;\n this._keys = new Array();\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(noPreventDefault) {\n // was there a second variable defined?\n // eslint-disable-next-line prefer-rest-params\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n if (this._onCanvasBlurObserver) {\n return;\n }\n this._scene = this.camera.getScene();\n this._engine = this._scene.getEngine();\n this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(() => {\n this._keys.length = 0;\n });\n this._onKeyboardObserver = this._scene.onKeyboardObservable.add((info) => {\n const evt = info.event;\n if (!evt.metaKey) {\n if (info.type === KeyboardEventTypes.KEYDOWN) {\n this._ctrlPressed = evt.ctrlKey;\n this._altPressed = evt.altKey;\n if (this.keysUp.indexOf(evt.keyCode) !== -1 ||\n this.keysDown.indexOf(evt.keyCode) !== -1 ||\n this.keysLeft.indexOf(evt.keyCode) !== -1 ||\n this.keysRight.indexOf(evt.keyCode) !== -1 ||\n this.keysReset.indexOf(evt.keyCode) !== -1) {\n const index = this._keys.indexOf(evt.keyCode);\n if (index === -1) {\n this._keys.push(evt.keyCode);\n }\n if (evt.preventDefault) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n }\n }\n else {\n if (this.keysUp.indexOf(evt.keyCode) !== -1 ||\n this.keysDown.indexOf(evt.keyCode) !== -1 ||\n this.keysLeft.indexOf(evt.keyCode) !== -1 ||\n this.keysRight.indexOf(evt.keyCode) !== -1 ||\n this.keysReset.indexOf(evt.keyCode) !== -1) {\n const index = this._keys.indexOf(evt.keyCode);\n if (index >= 0) {\n this._keys.splice(index, 1);\n }\n if (evt.preventDefault) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n }\n }\n }\n });\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n if (this._scene) {\n if (this._onKeyboardObserver) {\n this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);\n }\n if (this._onCanvasBlurObserver) {\n this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);\n }\n this._onKeyboardObserver = null;\n this._onCanvasBlurObserver = null;\n }\n this._keys.length = 0;\n }\n /**\n * Update the current camera state depending on the inputs that have been used this frame.\n * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.\n */\n checkInputs() {\n if (this._onKeyboardObserver) {\n const camera = this.camera;\n for (let index = 0; index < this._keys.length; index++) {\n const keyCode = this._keys[index];\n if (this.keysLeft.indexOf(keyCode) !== -1) {\n if (this._ctrlPressed && this.camera._useCtrlForPanning) {\n camera.inertialPanningX -= 1 / this.panningSensibility;\n }\n else {\n camera.inertialAlphaOffset -= this.angularSpeed;\n }\n }\n else if (this.keysUp.indexOf(keyCode) !== -1) {\n if (this._ctrlPressed && this.camera._useCtrlForPanning) {\n camera.inertialPanningY += 1 / this.panningSensibility;\n }\n else if (this._altPressed && this.useAltToZoom) {\n camera.inertialRadiusOffset += 1 / this.zoomingSensibility;\n }\n else {\n camera.inertialBetaOffset -= this.angularSpeed;\n }\n }\n else if (this.keysRight.indexOf(keyCode) !== -1) {\n if (this._ctrlPressed && this.camera._useCtrlForPanning) {\n camera.inertialPanningX += 1 / this.panningSensibility;\n }\n else {\n camera.inertialAlphaOffset += this.angularSpeed;\n }\n }\n else if (this.keysDown.indexOf(keyCode) !== -1) {\n if (this._ctrlPressed && this.camera._useCtrlForPanning) {\n camera.inertialPanningY -= 1 / this.panningSensibility;\n }\n else if (this._altPressed && this.useAltToZoom) {\n camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;\n }\n else {\n camera.inertialBetaOffset += this.angularSpeed;\n }\n }\n else if (this.keysReset.indexOf(keyCode) !== -1) {\n if (camera.useInputToRestoreState) {\n camera.restoreState();\n }\n }\n }\n }\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"ArcRotateCameraKeyboardMoveInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"keyboard\";\n }\n}\n__decorate([\n serialize()\n], ArcRotateCameraKeyboardMoveInput.prototype, \"keysUp\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraKeyboardMoveInput.prototype, \"keysDown\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraKeyboardMoveInput.prototype, \"keysLeft\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraKeyboardMoveInput.prototype, \"keysRight\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraKeyboardMoveInput.prototype, \"keysReset\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraKeyboardMoveInput.prototype, \"panningSensibility\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraKeyboardMoveInput.prototype, \"zoomingSensibility\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraKeyboardMoveInput.prototype, \"useAltToZoom\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraKeyboardMoveInput.prototype, \"angularSpeed\", void 0);\nCameraInputTypes[\"ArcRotateCameraKeyboardMoveInput\"] = ArcRotateCameraKeyboardMoveInput;\n//# sourceMappingURL=arcRotateCameraKeyboardMoveInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { PointerEventTypes } from \"../../Events/pointerEvents.js\";\nimport { Plane } from \"../../Maths/math.plane.js\";\nimport { Vector3, Matrix, TmpVectors } from \"../../Maths/math.vector.js\";\nimport { Epsilon } from \"../../Maths/math.constants.js\";\nimport { EventConstants } from \"../../Events/deviceInputEvents.js\";\nimport { Scalar } from \"../../Maths/math.scalar.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * Firefox uses a different scheme to report scroll distances to other\n * browsers. Rather than use complicated methods to calculate the exact\n * multiple we need to apply, let's just cheat and use a constant.\n * https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent/deltaMode\n * https://stackoverflow.com/questions/20110224/what-is-the-height-of-a-line-in-a-wheel-event-deltamode-dom-delta-line\n */\nconst ffMultiplier = 40;\n/**\n * Manage the mouse wheel inputs to control an arc rotate camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class ArcRotateCameraMouseWheelInput {\n constructor() {\n /**\n * Gets or Set the mouse wheel precision or how fast is the camera zooming.\n */\n this.wheelPrecision = 3.0;\n /**\n * Gets or Set the boolean value that controls whether or not the mouse wheel\n * zooms to the location of the mouse pointer or not. The default is false.\n */\n this.zoomToMouseLocation = false;\n /**\n * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.\n * It defines the percentage of current camera.radius to use as delta when wheel is used.\n */\n this.wheelDeltaPercentage = 0;\n /**\n * If set, this function will be used to set the radius delta that will be added to the current camera radius\n */\n this.customComputeDeltaFromMouseWheel = null;\n this._inertialPanning = Vector3.Zero();\n }\n _computeDeltaFromMouseWheelLegacyEvent(mouseWheelDelta, radius) {\n let delta = 0;\n const wheelDelta = mouseWheelDelta * 0.01 * this.wheelDeltaPercentage * radius;\n if (mouseWheelDelta > 0) {\n delta = wheelDelta / (1.0 + this.wheelDeltaPercentage);\n }\n else {\n delta = wheelDelta * (1.0 + this.wheelDeltaPercentage);\n }\n return delta;\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(noPreventDefault) {\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n this._wheel = (p) => {\n //sanity check - this should be a PointerWheel event.\n if (p.type !== PointerEventTypes.POINTERWHEEL) {\n return;\n }\n const event = p.event;\n let delta = 0;\n const platformScale = event.deltaMode === EventConstants.DOM_DELTA_LINE ? ffMultiplier : 1; // If this happens to be set to DOM_DELTA_LINE, adjust accordingly\n const wheelDelta = -(event.deltaY * platformScale);\n if (this.customComputeDeltaFromMouseWheel) {\n delta = this.customComputeDeltaFromMouseWheel(wheelDelta, this, event);\n }\n else {\n if (this.wheelDeltaPercentage) {\n delta = this._computeDeltaFromMouseWheelLegacyEvent(wheelDelta, this.camera.radius);\n // If zooming in, estimate the target radius and use that to compute the delta for inertia\n // this will stop multiple scroll events zooming in from adding too much inertia\n if (delta > 0) {\n let estimatedTargetRadius = this.camera.radius;\n let targetInertia = this.camera.inertialRadiusOffset + delta;\n for (let i = 0; i < 20 && Math.abs(targetInertia) > 0.001; i++) {\n estimatedTargetRadius -= targetInertia;\n targetInertia *= this.camera.inertia;\n }\n estimatedTargetRadius = Scalar.Clamp(estimatedTargetRadius, 0, Number.MAX_VALUE);\n delta = this._computeDeltaFromMouseWheelLegacyEvent(wheelDelta, estimatedTargetRadius);\n }\n }\n else {\n delta = wheelDelta / (this.wheelPrecision * 40);\n }\n }\n if (delta) {\n if (this.zoomToMouseLocation) {\n // If we are zooming to the mouse location, then we need to get the hit plane at the start of the zoom gesture if it doesn't exist\n // The hit plane is normally calculated after the first motion and each time there's motion so if we don't do this first,\n // the first zoom will be to the center of the screen\n if (!this._hitPlane) {\n this._updateHitPlane();\n }\n this._zoomToMouse(delta);\n }\n else {\n this.camera.inertialRadiusOffset += delta;\n }\n }\n if (event.preventDefault) {\n if (!noPreventDefault) {\n event.preventDefault();\n }\n }\n };\n this._observer = this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel, PointerEventTypes.POINTERWHEEL);\n if (this.zoomToMouseLocation) {\n this._inertialPanning.setAll(0);\n }\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n if (this._observer) {\n this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer);\n this._observer = null;\n this._wheel = null;\n }\n }\n /**\n * Update the current camera state depending on the inputs that have been used this frame.\n * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.\n */\n checkInputs() {\n if (!this.zoomToMouseLocation) {\n return;\n }\n const camera = this.camera;\n const motion = 0.0 + camera.inertialAlphaOffset + camera.inertialBetaOffset + camera.inertialRadiusOffset;\n if (motion) {\n // if zooming is still happening as a result of inertia, then we also need to update\n // the hit plane.\n this._updateHitPlane();\n // Note we cannot use arcRotateCamera.inertialPlanning here because arcRotateCamera panning\n // uses a different panningInertia which could cause this panning to get out of sync with\n // the zooming, and for this to work they must be exactly in sync.\n camera.target.addInPlace(this._inertialPanning);\n this._inertialPanning.scaleInPlace(camera.inertia);\n this._zeroIfClose(this._inertialPanning);\n }\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"ArcRotateCameraMouseWheelInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"mousewheel\";\n }\n _updateHitPlane() {\n const camera = this.camera;\n const direction = camera.target.subtract(camera.position);\n this._hitPlane = Plane.FromPositionAndNormal(camera.target, direction);\n }\n // Get position on the hit plane\n _getPosition() {\n var _a;\n const camera = this.camera;\n const scene = camera.getScene();\n // since the _hitPlane is always updated to be orthogonal to the camera position vector\n // we don't have to worry about this ray shooting off to infinity. This ray creates\n // a vector defining where we want to zoom to.\n const ray = scene.createPickingRay(scene.pointerX, scene.pointerY, Matrix.Identity(), camera, false);\n // Since the camera is the origin of the picking ray, we need to offset it by the camera's offset manually\n ray.origin.x -= camera.targetScreenOffset.x;\n ray.origin.y -= camera.targetScreenOffset.y;\n let distance = 0;\n if (this._hitPlane) {\n distance = (_a = ray.intersectsPlane(this._hitPlane)) !== null && _a !== void 0 ? _a : 0;\n }\n // not using this ray again, so modifying its vectors here is fine\n return ray.origin.addInPlace(ray.direction.scaleInPlace(distance));\n }\n _zoomToMouse(delta) {\n var _a, _b;\n const camera = this.camera;\n const inertiaComp = 1 - camera.inertia;\n if (camera.lowerRadiusLimit) {\n const lowerLimit = (_a = camera.lowerRadiusLimit) !== null && _a !== void 0 ? _a : 0;\n if (camera.radius - (camera.inertialRadiusOffset + delta) / inertiaComp < lowerLimit) {\n delta = (camera.radius - lowerLimit) * inertiaComp - camera.inertialRadiusOffset;\n }\n }\n if (camera.upperRadiusLimit) {\n const upperLimit = (_b = camera.upperRadiusLimit) !== null && _b !== void 0 ? _b : 0;\n if (camera.radius - (camera.inertialRadiusOffset + delta) / inertiaComp > upperLimit) {\n delta = (camera.radius - upperLimit) * inertiaComp - camera.inertialRadiusOffset;\n }\n }\n const zoomDistance = delta / inertiaComp;\n const ratio = zoomDistance / camera.radius;\n const vec = this._getPosition();\n // Now this vector tells us how much we also need to pan the camera\n // so the targeted mouse location becomes the center of zooming.\n const directionToZoomLocation = TmpVectors.Vector3[6];\n vec.subtractToRef(camera.target, directionToZoomLocation);\n directionToZoomLocation.scaleInPlace(ratio);\n directionToZoomLocation.scaleInPlace(inertiaComp);\n this._inertialPanning.addInPlace(directionToZoomLocation);\n camera.inertialRadiusOffset += delta;\n }\n // Sets x y or z of passed in vector to zero if less than Epsilon.\n _zeroIfClose(vec) {\n if (Math.abs(vec.x) < Epsilon) {\n vec.x = 0;\n }\n if (Math.abs(vec.y) < Epsilon) {\n vec.y = 0;\n }\n if (Math.abs(vec.z) < Epsilon) {\n vec.z = 0;\n }\n }\n}\n__decorate([\n serialize()\n], ArcRotateCameraMouseWheelInput.prototype, \"wheelPrecision\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraMouseWheelInput.prototype, \"zoomToMouseLocation\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraMouseWheelInput.prototype, \"wheelDeltaPercentage\", void 0);\nCameraInputTypes[\"ArcRotateCameraMouseWheelInput\"] = ArcRotateCameraMouseWheelInput;\n//# sourceMappingURL=arcRotateCameraMouseWheelInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { BaseCameraPointersInput } from \"../../Cameras/Inputs/BaseCameraPointersInput.js\";\n/**\n * Manage the pointers inputs to control an arc rotate camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class ArcRotateCameraPointersInput extends BaseCameraPointersInput {\n constructor() {\n super(...arguments);\n /**\n * Defines the buttons associated with the input to handle camera move.\n */\n this.buttons = [0, 1, 2];\n /**\n * Defines the pointer angular sensibility along the X axis or how fast is\n * the camera rotating.\n */\n this.angularSensibilityX = 1000.0;\n /**\n * Defines the pointer angular sensibility along the Y axis or how fast is\n * the camera rotating.\n */\n this.angularSensibilityY = 1000.0;\n /**\n * Defines the pointer pinch precision or how fast is the camera zooming.\n */\n this.pinchPrecision = 12.0;\n /**\n * pinchDeltaPercentage will be used instead of pinchPrecision if different\n * from 0.\n * It defines the percentage of current camera.radius to use as delta when\n * pinch zoom is used.\n */\n this.pinchDeltaPercentage = 0;\n /**\n * When useNaturalPinchZoom is true, multi touch zoom will zoom in such\n * that any object in the plane at the camera's target point will scale\n * perfectly with finger motion.\n * Overrides pinchDeltaPercentage and pinchPrecision.\n */\n this.useNaturalPinchZoom = false;\n /**\n * Defines whether zoom (2 fingers pinch) is enabled through multitouch\n */\n this.pinchZoom = true;\n /**\n * Defines the pointer panning sensibility or how fast is the camera moving.\n */\n this.panningSensibility = 1000.0;\n /**\n * Defines whether panning (2 fingers swipe) is enabled through multitouch.\n */\n this.multiTouchPanning = true;\n /**\n * Defines whether panning is enabled for both pan (2 fingers swipe) and\n * zoom (pinch) through multitouch.\n */\n this.multiTouchPanAndZoom = true;\n /**\n * Revers pinch action direction.\n */\n this.pinchInwards = true;\n this._isPanClick = false;\n this._twoFingerActivityCount = 0;\n this._isPinching = false;\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"ArcRotateCameraPointersInput\";\n }\n /**\n * Move camera from multi touch panning positions.\n * @param previousMultiTouchPanPosition\n * @param multiTouchPanPosition\n */\n _computeMultiTouchPanning(previousMultiTouchPanPosition, multiTouchPanPosition) {\n if (this.panningSensibility !== 0 && previousMultiTouchPanPosition && multiTouchPanPosition) {\n const moveDeltaX = multiTouchPanPosition.x - previousMultiTouchPanPosition.x;\n const moveDeltaY = multiTouchPanPosition.y - previousMultiTouchPanPosition.y;\n this.camera.inertialPanningX += -moveDeltaX / this.panningSensibility;\n this.camera.inertialPanningY += moveDeltaY / this.panningSensibility;\n }\n }\n /**\n * Move camera from pinch zoom distances.\n * @param previousPinchSquaredDistance\n * @param pinchSquaredDistance\n */\n _computePinchZoom(previousPinchSquaredDistance, pinchSquaredDistance) {\n const radius = this.camera.radius || ArcRotateCameraPointersInput.MinimumRadiusForPinch;\n if (this.useNaturalPinchZoom) {\n this.camera.radius = (radius * Math.sqrt(previousPinchSquaredDistance)) / Math.sqrt(pinchSquaredDistance);\n }\n else if (this.pinchDeltaPercentage) {\n this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) * 0.001 * radius * this.pinchDeltaPercentage;\n }\n else {\n this.camera.inertialRadiusOffset +=\n (pinchSquaredDistance - previousPinchSquaredDistance) /\n ((this.pinchPrecision * (this.pinchInwards ? 1 : -1) * (this.angularSensibilityX + this.angularSensibilityY)) / 2);\n }\n }\n /**\n * Called on pointer POINTERMOVE event if only a single touch is active.\n * @param point\n * @param offsetX\n * @param offsetY\n */\n onTouch(point, offsetX, offsetY) {\n if (this.panningSensibility !== 0 && ((this._ctrlKey && this.camera._useCtrlForPanning) || this._isPanClick)) {\n this.camera.inertialPanningX += -offsetX / this.panningSensibility;\n this.camera.inertialPanningY += offsetY / this.panningSensibility;\n }\n else {\n this.camera.inertialAlphaOffset -= offsetX / this.angularSensibilityX;\n this.camera.inertialBetaOffset -= offsetY / this.angularSensibilityY;\n }\n }\n /**\n * Called on pointer POINTERDOUBLETAP event.\n */\n onDoubleTap() {\n if (this.camera.useInputToRestoreState) {\n this.camera.restoreState();\n }\n }\n /**\n * Called on pointer POINTERMOVE event if multiple touches are active.\n * @param pointA\n * @param pointB\n * @param previousPinchSquaredDistance\n * @param pinchSquaredDistance\n * @param previousMultiTouchPanPosition\n * @param multiTouchPanPosition\n */\n onMultiTouch(pointA, pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition) {\n if (previousPinchSquaredDistance === 0 && previousMultiTouchPanPosition === null) {\n // First time this method is called for new pinch.\n // Next time this is called there will be a\n // previousPinchSquaredDistance and pinchSquaredDistance to compare.\n return;\n }\n if (pinchSquaredDistance === 0 && multiTouchPanPosition === null) {\n // Last time this method is called at the end of a pinch.\n return;\n }\n // Zoom and panning enabled together\n if (this.multiTouchPanAndZoom) {\n this._computePinchZoom(previousPinchSquaredDistance, pinchSquaredDistance);\n this._computeMultiTouchPanning(previousMultiTouchPanPosition, multiTouchPanPosition);\n // Zoom and panning enabled but only one at a time\n }\n else if (this.multiTouchPanning && this.pinchZoom) {\n this._twoFingerActivityCount++;\n if (this._isPinching ||\n (this._twoFingerActivityCount < 20 && Math.abs(Math.sqrt(pinchSquaredDistance) - Math.sqrt(previousPinchSquaredDistance)) > this.camera.pinchToPanMaxDistance)) {\n // Since pinch has not been active long, assume we intend to zoom.\n this._computePinchZoom(previousPinchSquaredDistance, pinchSquaredDistance);\n // Since we are pinching, remain pinching on next iteration.\n this._isPinching = true;\n }\n else {\n // Pause between pinch starting and moving implies not a zoom event. Pan instead.\n this._computeMultiTouchPanning(previousMultiTouchPanPosition, multiTouchPanPosition);\n }\n // Panning enabled, zoom disabled\n }\n else if (this.multiTouchPanning) {\n this._computeMultiTouchPanning(previousMultiTouchPanPosition, multiTouchPanPosition);\n // Zoom enabled, panning disabled\n }\n else if (this.pinchZoom) {\n this._computePinchZoom(previousPinchSquaredDistance, pinchSquaredDistance);\n }\n }\n /**\n * Called each time a new POINTERDOWN event occurs. Ie, for each button\n * press.\n * @param evt\n */\n onButtonDown(evt) {\n this._isPanClick = evt.button === this.camera._panningMouseButton;\n }\n /**\n * Called each time a new POINTERUP event occurs. Ie, for each button\n * release.\n */\n onButtonUp() {\n this._twoFingerActivityCount = 0;\n this._isPinching = false;\n }\n /**\n * Called when window becomes inactive.\n */\n onLostFocus() {\n this._isPanClick = false;\n this._twoFingerActivityCount = 0;\n this._isPinching = false;\n }\n}\n/**\n * The minimum radius used for pinch, to avoid radius lock at 0\n */\nArcRotateCameraPointersInput.MinimumRadiusForPinch = 0.001;\n__decorate([\n serialize()\n], ArcRotateCameraPointersInput.prototype, \"buttons\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraPointersInput.prototype, \"angularSensibilityX\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraPointersInput.prototype, \"angularSensibilityY\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraPointersInput.prototype, \"pinchPrecision\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraPointersInput.prototype, \"pinchDeltaPercentage\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraPointersInput.prototype, \"useNaturalPinchZoom\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraPointersInput.prototype, \"pinchZoom\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraPointersInput.prototype, \"panningSensibility\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraPointersInput.prototype, \"multiTouchPanning\", void 0);\n__decorate([\n serialize()\n], ArcRotateCameraPointersInput.prototype, \"multiTouchPanAndZoom\", void 0);\nCameraInputTypes[\"ArcRotateCameraPointersInput\"] = ArcRotateCameraPointersInput;\n//# sourceMappingURL=arcRotateCameraPointersInput.js.map","import { ArcRotateCameraPointersInput } from \"../Cameras/Inputs/arcRotateCameraPointersInput.js\";\nimport { ArcRotateCameraKeyboardMoveInput } from \"../Cameras/Inputs/arcRotateCameraKeyboardMoveInput.js\";\nimport { ArcRotateCameraMouseWheelInput } from \"../Cameras/Inputs/arcRotateCameraMouseWheelInput.js\";\nimport { CameraInputsManager } from \"../Cameras/cameraInputsManager.js\";\n/**\n * Default Inputs manager for the ArcRotateCamera.\n * It groups all the default supported inputs for ease of use.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class ArcRotateCameraInputsManager extends CameraInputsManager {\n /**\n * Instantiates a new ArcRotateCameraInputsManager.\n * @param camera Defines the camera the inputs belong to\n */\n constructor(camera) {\n super(camera);\n }\n /**\n * Add mouse wheel input support to the input manager.\n * @returns the current input manager\n */\n addMouseWheel() {\n this.add(new ArcRotateCameraMouseWheelInput());\n return this;\n }\n /**\n * Add pointers input support to the input manager.\n * @returns the current input manager\n */\n addPointers() {\n this.add(new ArcRotateCameraPointersInput());\n return this;\n }\n /**\n * Add keyboard input support to the input manager.\n * @returns the current input manager\n */\n addKeyboard() {\n this.add(new ArcRotateCameraKeyboardMoveInput());\n return this;\n }\n}\n//# sourceMappingURL=arcRotateCameraInputsManager.js.map","import { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { ArcRotateCameraInputsManager } from \"../../Cameras/arcRotateCameraInputsManager.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * Add orientation input support to the input manager.\n * @returns the current input manager\n */\nArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {\n this.add(new ArcRotateCameraVRDeviceOrientationInput());\n return this;\n};\n/**\n * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class ArcRotateCameraVRDeviceOrientationInput {\n /**\n * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.\n */\n constructor() {\n /**\n * Defines a correction factor applied on the alpha value retrieved from the orientation events.\n */\n this.alphaCorrection = 1;\n /**\n * Defines a correction factor applied on the gamma value retrieved from the orientation events.\n */\n this.gammaCorrection = 1;\n this._alpha = 0;\n this._gamma = 0;\n this._dirty = false;\n this._deviceOrientationHandler = this._onOrientationEvent.bind(this);\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(noPreventDefault) {\n // eslint-disable-next-line prefer-rest-params\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n this.camera.attachControl(noPreventDefault);\n const hostWindow = this.camera.getScene().getEngine().getHostWindow();\n if (hostWindow) {\n // check iOS 13+ support\n if (typeof DeviceOrientationEvent !== \"undefined\" && typeof DeviceOrientationEvent.requestPermission === \"function\") {\n DeviceOrientationEvent\n .requestPermission()\n .then((response) => {\n if (response === \"granted\") {\n hostWindow.addEventListener(\"deviceorientation\", this._deviceOrientationHandler);\n }\n else {\n Tools.Warn(\"Permission not granted.\");\n }\n })\n .catch((error) => {\n Tools.Error(error);\n });\n }\n else {\n hostWindow.addEventListener(\"deviceorientation\", this._deviceOrientationHandler);\n }\n }\n }\n /**\n * @internal\n */\n _onOrientationEvent(evt) {\n if (evt.alpha !== null) {\n this._alpha = (+evt.alpha | 0) * this.alphaCorrection;\n }\n if (evt.gamma !== null) {\n this._gamma = (+evt.gamma | 0) * this.gammaCorrection;\n }\n this._dirty = true;\n }\n /**\n * Update the current camera state depending on the inputs that have been used this frame.\n * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.\n */\n checkInputs() {\n if (this._dirty) {\n this._dirty = false;\n if (this._gamma < 0) {\n this._gamma = 180 + this._gamma;\n }\n this.camera.alpha = (((-this._alpha / 180.0) * Math.PI) % Math.PI) * 2;\n this.camera.beta = (this._gamma / 180.0) * Math.PI;\n }\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n window.removeEventListener(\"deviceorientation\", this._deviceOrientationHandler);\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"ArcRotateCameraVRDeviceOrientationInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"VRDeviceOrientation\";\n }\n}\nCameraInputTypes[\"ArcRotateCameraVRDeviceOrientationInput\"] = ArcRotateCameraVRDeviceOrientationInput;\n//# sourceMappingURL=arcRotateCameraVRDeviceOrientationInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { KeyboardEventTypes } from \"../../Events/keyboardEvents.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * Listen to keyboard events to control the camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FlyCameraKeyboardInput {\n constructor() {\n /**\n * The list of keyboard keys used to control the forward move of the camera.\n */\n this.keysForward = [87];\n /**\n * The list of keyboard keys used to control the backward move of the camera.\n */\n this.keysBackward = [83];\n /**\n * The list of keyboard keys used to control the forward move of the camera.\n */\n this.keysUp = [69];\n /**\n * The list of keyboard keys used to control the backward move of the camera.\n */\n this.keysDown = [81];\n /**\n * The list of keyboard keys used to control the right strafe move of the camera.\n */\n this.keysRight = [68];\n /**\n * The list of keyboard keys used to control the left strafe move of the camera.\n */\n this.keysLeft = [65];\n this._keys = new Array();\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(noPreventDefault) {\n // eslint-disable-next-line prefer-rest-params\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n if (this._onCanvasBlurObserver) {\n return;\n }\n this._scene = this.camera.getScene();\n this._engine = this._scene.getEngine();\n this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(() => {\n this._keys.length = 0;\n });\n this._onKeyboardObserver = this._scene.onKeyboardObservable.add((info) => {\n const evt = info.event;\n if (info.type === KeyboardEventTypes.KEYDOWN) {\n if (this.keysForward.indexOf(evt.keyCode) !== -1 ||\n this.keysBackward.indexOf(evt.keyCode) !== -1 ||\n this.keysUp.indexOf(evt.keyCode) !== -1 ||\n this.keysDown.indexOf(evt.keyCode) !== -1 ||\n this.keysLeft.indexOf(evt.keyCode) !== -1 ||\n this.keysRight.indexOf(evt.keyCode) !== -1) {\n const index = this._keys.indexOf(evt.keyCode);\n if (index === -1) {\n this._keys.push(evt.keyCode);\n }\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n }\n else {\n if (this.keysForward.indexOf(evt.keyCode) !== -1 ||\n this.keysBackward.indexOf(evt.keyCode) !== -1 ||\n this.keysUp.indexOf(evt.keyCode) !== -1 ||\n this.keysDown.indexOf(evt.keyCode) !== -1 ||\n this.keysLeft.indexOf(evt.keyCode) !== -1 ||\n this.keysRight.indexOf(evt.keyCode) !== -1) {\n const index = this._keys.indexOf(evt.keyCode);\n if (index >= 0) {\n this._keys.splice(index, 1);\n }\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n }\n });\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n if (this._scene) {\n if (this._onKeyboardObserver) {\n this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);\n }\n if (this._onCanvasBlurObserver) {\n this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);\n }\n this._onKeyboardObserver = null;\n this._onCanvasBlurObserver = null;\n }\n this._keys.length = 0;\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"FlyCameraKeyboardInput\";\n }\n /**\n * @internal\n */\n _onLostFocus() {\n this._keys.length = 0;\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"keyboard\";\n }\n /**\n * Update the current camera state depending on the inputs that have been used this frame.\n * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.\n */\n checkInputs() {\n if (this._onKeyboardObserver) {\n const camera = this.camera;\n // Keyboard\n for (let index = 0; index < this._keys.length; index++) {\n const keyCode = this._keys[index];\n const speed = camera._computeLocalCameraSpeed();\n if (this.keysForward.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, 0, speed);\n }\n else if (this.keysBackward.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, 0, -speed);\n }\n else if (this.keysUp.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, speed, 0);\n }\n else if (this.keysDown.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, -speed, 0);\n }\n else if (this.keysRight.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(speed, 0, 0);\n }\n else if (this.keysLeft.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(-speed, 0, 0);\n }\n if (camera.getScene().useRightHandedSystem) {\n camera._localDirection.z *= -1;\n }\n camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);\n Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);\n camera.cameraDirection.addInPlace(camera._transformedDirection);\n }\n }\n }\n}\n__decorate([\n serialize()\n], FlyCameraKeyboardInput.prototype, \"keysForward\", void 0);\n__decorate([\n serialize()\n], FlyCameraKeyboardInput.prototype, \"keysBackward\", void 0);\n__decorate([\n serialize()\n], FlyCameraKeyboardInput.prototype, \"keysUp\", void 0);\n__decorate([\n serialize()\n], FlyCameraKeyboardInput.prototype, \"keysDown\", void 0);\n__decorate([\n serialize()\n], FlyCameraKeyboardInput.prototype, \"keysRight\", void 0);\n__decorate([\n serialize()\n], FlyCameraKeyboardInput.prototype, \"keysLeft\", void 0);\nCameraInputTypes[\"FlyCameraKeyboardInput\"] = FlyCameraKeyboardInput;\n//# sourceMappingURL=flyCameraKeyboardInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { PointerEventTypes } from \"../../Events/pointerEvents.js\";\nimport { Quaternion } from \"../../Maths/math.vector.js\";\nimport { Axis } from \"../../Maths/math.axis.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * Listen to mouse events to control the camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FlyCameraMouseInput {\n /**\n * Listen to mouse events to control the camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\n constructor() {\n /**\n * Defines the buttons associated with the input to handle camera rotation.\n */\n this.buttons = [0, 1, 2];\n /**\n * Assign buttons for Yaw control.\n */\n this.buttonsYaw = [-1, 0, 1];\n /**\n * Assign buttons for Pitch control.\n */\n this.buttonsPitch = [-1, 0, 1];\n /**\n * Assign buttons for Roll control.\n */\n this.buttonsRoll = [2];\n /**\n * Detect if any button is being pressed while mouse is moved.\n * -1 = Mouse locked.\n * 0 = Left button.\n * 1 = Middle Button.\n * 2 = Right Button.\n */\n this.activeButton = -1;\n /**\n * Defines the pointer's angular sensibility, to control the camera rotation speed.\n * Higher values reduce its sensitivity.\n */\n this.angularSensibility = 1000.0;\n this._previousPosition = null;\n }\n /**\n * Attach the mouse control to the HTML DOM element.\n * @param noPreventDefault Defines whether events caught by the controls should call preventdefault().\n */\n attachControl(noPreventDefault) {\n // eslint-disable-next-line prefer-rest-params\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n this._noPreventDefault = noPreventDefault;\n this._observer = this.camera.getScene()._inputManager._addCameraPointerObserver((p) => {\n this._pointerInput(p);\n }, PointerEventTypes.POINTERDOWN | PointerEventTypes.POINTERUP | PointerEventTypes.POINTERMOVE);\n // Correct Roll by rate, if enabled.\n this._rollObserver = this.camera.getScene().onBeforeRenderObservable.add(() => {\n if (this.camera.rollCorrect) {\n this.camera.restoreRoll(this.camera.rollCorrect);\n }\n });\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n if (this._observer) {\n this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer);\n this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver);\n this._observer = null;\n this._rollObserver = null;\n this._previousPosition = null;\n this._noPreventDefault = undefined;\n }\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name.\n */\n getClassName() {\n return \"FlyCameraMouseInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input's friendly name.\n */\n getSimpleName() {\n return \"mouse\";\n }\n // Track mouse movement, when the pointer is not locked.\n _pointerInput(p) {\n const e = p.event;\n const camera = this.camera;\n const engine = camera.getEngine();\n if (engine.isInVRExclusivePointerMode) {\n return;\n }\n if (!this.touchEnabled && e.pointerType === \"touch\") {\n return;\n }\n // Mouse is moved but an unknown mouse button is pressed.\n if (p.type !== PointerEventTypes.POINTERMOVE && this.buttons.indexOf(e.button) === -1) {\n return;\n }\n const srcElement = e.target;\n // Mouse down.\n if (p.type === PointerEventTypes.POINTERDOWN) {\n try {\n srcElement === null || srcElement === void 0 ? void 0 : srcElement.setPointerCapture(e.pointerId);\n }\n catch (e) {\n // Nothing to do with the error. Execution continues.\n }\n this._previousPosition = {\n x: e.clientX,\n y: e.clientY,\n };\n this.activeButton = e.button;\n if (!this._noPreventDefault) {\n e.preventDefault();\n this._element.focus();\n }\n // This is required to move while pointer button is down\n if (engine.isPointerLock) {\n this._onMouseMove(p.event);\n }\n }\n // Mouse up.\n else if (p.type === PointerEventTypes.POINTERUP) {\n try {\n srcElement === null || srcElement === void 0 ? void 0 : srcElement.releasePointerCapture(e.pointerId);\n }\n catch (e) {\n // Nothing to do with the error. Execution continues.\n }\n this.activeButton = -1;\n this._previousPosition = null;\n if (!this._noPreventDefault) {\n e.preventDefault();\n }\n }\n // Mouse move.\n else if (p.type === PointerEventTypes.POINTERMOVE) {\n if (!this._previousPosition) {\n if (engine.isPointerLock) {\n this._onMouseMove(p.event);\n }\n return;\n }\n const offsetX = e.clientX - this._previousPosition.x;\n const offsetY = e.clientY - this._previousPosition.y;\n this._rotateCamera(offsetX, offsetY);\n this._previousPosition = {\n x: e.clientX,\n y: e.clientY,\n };\n if (!this._noPreventDefault) {\n e.preventDefault();\n }\n }\n }\n // Track mouse movement, when pointer is locked.\n _onMouseMove(e) {\n const camera = this.camera;\n const engine = camera.getEngine();\n if (!engine.isPointerLock || engine.isInVRExclusivePointerMode) {\n return;\n }\n const offsetX = e.movementX;\n const offsetY = e.movementY;\n this._rotateCamera(offsetX, offsetY);\n this._previousPosition = null;\n if (!this._noPreventDefault) {\n e.preventDefault();\n }\n }\n /**\n * Rotate camera by mouse offset.\n * @param offsetX\n * @param offsetY\n */\n _rotateCamera(offsetX, offsetY) {\n const camera = this.camera;\n const scene = this.camera.getScene();\n if (scene.useRightHandedSystem) {\n offsetX *= -1;\n }\n if (camera.parent && camera.parent._getWorldMatrixDeterminant() < 0) {\n offsetX *= -1;\n }\n const x = offsetX / this.angularSensibility;\n const y = offsetY / this.angularSensibility;\n // Initialize to current rotation.\n const currentRotation = Quaternion.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, camera.rotation.z);\n let rotationChange;\n // Pitch.\n if (this.buttonsPitch.some((v) => {\n return v === this.activeButton;\n })) {\n // Apply change in Radians to vector Angle.\n rotationChange = Quaternion.RotationAxis(Axis.X, y);\n // Apply Pitch to quaternion.\n currentRotation.multiplyInPlace(rotationChange);\n }\n // Yaw.\n if (this.buttonsYaw.some((v) => {\n return v === this.activeButton;\n })) {\n // Apply change in Radians to vector Angle.\n rotationChange = Quaternion.RotationAxis(Axis.Y, x);\n // Apply Yaw to quaternion.\n currentRotation.multiplyInPlace(rotationChange);\n // Add Roll, if banked turning is enabled, within Roll limit.\n const limit = camera.bankedTurnLimit + camera._trackRoll; // Defaults to 90° plus manual roll.\n if (camera.bankedTurn && -limit < camera.rotation.z && camera.rotation.z < limit) {\n const bankingDelta = camera.bankedTurnMultiplier * -x;\n // Apply change in Radians to vector Angle.\n rotationChange = Quaternion.RotationAxis(Axis.Z, bankingDelta);\n // Apply Yaw to quaternion.\n currentRotation.multiplyInPlace(rotationChange);\n }\n }\n // Roll.\n if (this.buttonsRoll.some((v) => {\n return v === this.activeButton;\n })) {\n // Apply change in Radians to vector Angle.\n rotationChange = Quaternion.RotationAxis(Axis.Z, -x);\n // Track Rolling.\n camera._trackRoll -= x;\n // Apply Pitch to quaternion.\n currentRotation.multiplyInPlace(rotationChange);\n }\n // Apply rotationQuaternion to Euler camera.rotation.\n currentRotation.toEulerAnglesToRef(camera.rotation);\n }\n}\n__decorate([\n serialize()\n], FlyCameraMouseInput.prototype, \"buttons\", void 0);\n__decorate([\n serialize()\n], FlyCameraMouseInput.prototype, \"angularSensibility\", void 0);\nCameraInputTypes[\"FlyCameraMouseInput\"] = FlyCameraMouseInput;\n//# sourceMappingURL=flyCameraMouseInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { KeyboardEventTypes } from \"../../Events/keyboardEvents.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * Manage the keyboard inputs to control the movement of a follow camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FollowCameraKeyboardMoveInput {\n constructor() {\n /**\n * Defines the list of key codes associated with the up action (increase heightOffset)\n */\n this.keysHeightOffsetIncr = [38];\n /**\n * Defines the list of key codes associated with the down action (decrease heightOffset)\n */\n this.keysHeightOffsetDecr = [40];\n /**\n * Defines whether the Alt modifier key is required to move up/down (alter heightOffset)\n */\n this.keysHeightOffsetModifierAlt = false;\n /**\n * Defines whether the Ctrl modifier key is required to move up/down (alter heightOffset)\n */\n this.keysHeightOffsetModifierCtrl = false;\n /**\n * Defines whether the Shift modifier key is required to move up/down (alter heightOffset)\n */\n this.keysHeightOffsetModifierShift = false;\n /**\n * Defines the list of key codes associated with the left action (increase rotationOffset)\n */\n this.keysRotationOffsetIncr = [37];\n /**\n * Defines the list of key codes associated with the right action (decrease rotationOffset)\n */\n this.keysRotationOffsetDecr = [39];\n /**\n * Defines whether the Alt modifier key is required to move left/right (alter rotationOffset)\n */\n this.keysRotationOffsetModifierAlt = false;\n /**\n * Defines whether the Ctrl modifier key is required to move left/right (alter rotationOffset)\n */\n this.keysRotationOffsetModifierCtrl = false;\n /**\n * Defines whether the Shift modifier key is required to move left/right (alter rotationOffset)\n */\n this.keysRotationOffsetModifierShift = false;\n /**\n * Defines the list of key codes associated with the zoom-in action (decrease radius)\n */\n this.keysRadiusIncr = [40];\n /**\n * Defines the list of key codes associated with the zoom-out action (increase radius)\n */\n this.keysRadiusDecr = [38];\n /**\n * Defines whether the Alt modifier key is required to zoom in/out (alter radius value)\n */\n this.keysRadiusModifierAlt = true;\n /**\n * Defines whether the Ctrl modifier key is required to zoom in/out (alter radius value)\n */\n this.keysRadiusModifierCtrl = false;\n /**\n * Defines whether the Shift modifier key is required to zoom in/out (alter radius value)\n */\n this.keysRadiusModifierShift = false;\n /**\n * Defines the rate of change of heightOffset.\n */\n this.heightSensibility = 1;\n /**\n * Defines the rate of change of rotationOffset.\n */\n this.rotationSensibility = 1;\n /**\n * Defines the rate of change of radius.\n */\n this.radiusSensibility = 1;\n this._keys = new Array();\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(noPreventDefault) {\n // eslint-disable-next-line prefer-rest-params\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n if (this._onCanvasBlurObserver) {\n return;\n }\n this._scene = this.camera.getScene();\n this._engine = this._scene.getEngine();\n this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(() => {\n this._keys.length = 0;\n });\n this._onKeyboardObserver = this._scene.onKeyboardObservable.add((info) => {\n const evt = info.event;\n if (!evt.metaKey) {\n if (info.type === KeyboardEventTypes.KEYDOWN) {\n this._ctrlPressed = evt.ctrlKey;\n this._altPressed = evt.altKey;\n this._shiftPressed = evt.shiftKey;\n if (this.keysHeightOffsetIncr.indexOf(evt.keyCode) !== -1 ||\n this.keysHeightOffsetDecr.indexOf(evt.keyCode) !== -1 ||\n this.keysRotationOffsetIncr.indexOf(evt.keyCode) !== -1 ||\n this.keysRotationOffsetDecr.indexOf(evt.keyCode) !== -1 ||\n this.keysRadiusIncr.indexOf(evt.keyCode) !== -1 ||\n this.keysRadiusDecr.indexOf(evt.keyCode) !== -1) {\n const index = this._keys.indexOf(evt.keyCode);\n if (index === -1) {\n this._keys.push(evt.keyCode);\n }\n if (evt.preventDefault) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n }\n }\n else {\n if (this.keysHeightOffsetIncr.indexOf(evt.keyCode) !== -1 ||\n this.keysHeightOffsetDecr.indexOf(evt.keyCode) !== -1 ||\n this.keysRotationOffsetIncr.indexOf(evt.keyCode) !== -1 ||\n this.keysRotationOffsetDecr.indexOf(evt.keyCode) !== -1 ||\n this.keysRadiusIncr.indexOf(evt.keyCode) !== -1 ||\n this.keysRadiusDecr.indexOf(evt.keyCode) !== -1) {\n const index = this._keys.indexOf(evt.keyCode);\n if (index >= 0) {\n this._keys.splice(index, 1);\n }\n if (evt.preventDefault) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n }\n }\n }\n });\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n if (this._scene) {\n if (this._onKeyboardObserver) {\n this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);\n }\n if (this._onCanvasBlurObserver) {\n this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);\n }\n this._onKeyboardObserver = null;\n this._onCanvasBlurObserver = null;\n }\n this._keys.length = 0;\n }\n /**\n * Update the current camera state depending on the inputs that have been used this frame.\n * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.\n */\n checkInputs() {\n if (this._onKeyboardObserver) {\n this._keys.forEach((keyCode) => {\n if (this.keysHeightOffsetIncr.indexOf(keyCode) !== -1 && this._modifierHeightOffset()) {\n this.camera.heightOffset += this.heightSensibility;\n }\n else if (this.keysHeightOffsetDecr.indexOf(keyCode) !== -1 && this._modifierHeightOffset()) {\n this.camera.heightOffset -= this.heightSensibility;\n }\n else if (this.keysRotationOffsetIncr.indexOf(keyCode) !== -1 && this._modifierRotationOffset()) {\n this.camera.rotationOffset += this.rotationSensibility;\n this.camera.rotationOffset %= 360;\n }\n else if (this.keysRotationOffsetDecr.indexOf(keyCode) !== -1 && this._modifierRotationOffset()) {\n this.camera.rotationOffset -= this.rotationSensibility;\n this.camera.rotationOffset %= 360;\n }\n else if (this.keysRadiusIncr.indexOf(keyCode) !== -1 && this._modifierRadius()) {\n this.camera.radius += this.radiusSensibility;\n }\n else if (this.keysRadiusDecr.indexOf(keyCode) !== -1 && this._modifierRadius()) {\n this.camera.radius -= this.radiusSensibility;\n }\n });\n }\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"FollowCameraKeyboardMoveInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"keyboard\";\n }\n /**\n * Check if the pressed modifier keys (Alt/Ctrl/Shift) match those configured to\n * allow modification of the heightOffset value.\n */\n _modifierHeightOffset() {\n return (this.keysHeightOffsetModifierAlt === this._altPressed &&\n this.keysHeightOffsetModifierCtrl === this._ctrlPressed &&\n this.keysHeightOffsetModifierShift === this._shiftPressed);\n }\n /**\n * Check if the pressed modifier keys (Alt/Ctrl/Shift) match those configured to\n * allow modification of the rotationOffset value.\n */\n _modifierRotationOffset() {\n return (this.keysRotationOffsetModifierAlt === this._altPressed &&\n this.keysRotationOffsetModifierCtrl === this._ctrlPressed &&\n this.keysRotationOffsetModifierShift === this._shiftPressed);\n }\n /**\n * Check if the pressed modifier keys (Alt/Ctrl/Shift) match those configured to\n * allow modification of the radius value.\n */\n _modifierRadius() {\n return this.keysRadiusModifierAlt === this._altPressed && this.keysRadiusModifierCtrl === this._ctrlPressed && this.keysRadiusModifierShift === this._shiftPressed;\n }\n}\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysHeightOffsetIncr\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysHeightOffsetDecr\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysHeightOffsetModifierAlt\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysHeightOffsetModifierCtrl\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysHeightOffsetModifierShift\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysRotationOffsetIncr\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysRotationOffsetDecr\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysRotationOffsetModifierAlt\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysRotationOffsetModifierCtrl\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysRotationOffsetModifierShift\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysRadiusIncr\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysRadiusDecr\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysRadiusModifierAlt\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysRadiusModifierCtrl\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"keysRadiusModifierShift\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"heightSensibility\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"rotationSensibility\", void 0);\n__decorate([\n serialize()\n], FollowCameraKeyboardMoveInput.prototype, \"radiusSensibility\", void 0);\nCameraInputTypes[\"FollowCameraKeyboardMoveInput\"] = FollowCameraKeyboardMoveInput;\n//# sourceMappingURL=followCameraKeyboardMoveInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { PointerEventTypes } from \"../../Events/pointerEvents.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * Manage the mouse wheel inputs to control a follow camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FollowCameraMouseWheelInput {\n constructor() {\n /**\n * Moue wheel controls zoom. (Mouse wheel modifies camera.radius value.)\n */\n this.axisControlRadius = true;\n /**\n * Moue wheel controls height. (Mouse wheel modifies camera.heightOffset value.)\n */\n this.axisControlHeight = false;\n /**\n * Moue wheel controls angle. (Mouse wheel modifies camera.rotationOffset value.)\n */\n this.axisControlRotation = false;\n /**\n * Gets or Set the mouse wheel precision or how fast is the camera moves in\n * relation to mouseWheel events.\n */\n this.wheelPrecision = 3.0;\n /**\n * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.\n * It defines the percentage of current camera.radius to use as delta when wheel is used.\n */\n this.wheelDeltaPercentage = 0;\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(noPreventDefault) {\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n this._wheel = (p) => {\n // sanity check - this should be a PointerWheel event.\n if (p.type !== PointerEventTypes.POINTERWHEEL) {\n return;\n }\n const event = p.event;\n let delta = 0;\n const wheelDelta = Math.max(-1, Math.min(1, event.deltaY));\n if (this.wheelDeltaPercentage) {\n console.assert(this.axisControlRadius + this.axisControlHeight + this.axisControlRotation <= 1, \"wheelDeltaPercentage only usable when mouse wheel \" +\n \"controls ONE axis. \" +\n \"Currently enabled: \" +\n \"axisControlRadius: \" +\n this.axisControlRadius +\n \", axisControlHeightOffset: \" +\n this.axisControlHeight +\n \", axisControlRotationOffset: \" +\n this.axisControlRotation);\n if (this.axisControlRadius) {\n delta = wheelDelta * 0.01 * this.wheelDeltaPercentage * this.camera.radius;\n }\n else if (this.axisControlHeight) {\n delta = wheelDelta * 0.01 * this.wheelDeltaPercentage * this.camera.heightOffset;\n }\n else if (this.axisControlRotation) {\n delta = wheelDelta * 0.01 * this.wheelDeltaPercentage * this.camera.rotationOffset;\n }\n }\n else {\n delta = wheelDelta * this.wheelPrecision;\n }\n if (delta) {\n if (this.axisControlRadius) {\n this.camera.radius += delta;\n }\n else if (this.axisControlHeight) {\n this.camera.heightOffset -= delta;\n }\n else if (this.axisControlRotation) {\n this.camera.rotationOffset -= delta;\n }\n }\n if (event.preventDefault) {\n if (!noPreventDefault) {\n event.preventDefault();\n }\n }\n };\n this._observer = this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel, PointerEventTypes.POINTERWHEEL);\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n if (this._observer) {\n this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer);\n this._observer = null;\n this._wheel = null;\n }\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"ArcRotateCameraMouseWheelInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"mousewheel\";\n }\n}\n__decorate([\n serialize()\n], FollowCameraMouseWheelInput.prototype, \"axisControlRadius\", void 0);\n__decorate([\n serialize()\n], FollowCameraMouseWheelInput.prototype, \"axisControlHeight\", void 0);\n__decorate([\n serialize()\n], FollowCameraMouseWheelInput.prototype, \"axisControlRotation\", void 0);\n__decorate([\n serialize()\n], FollowCameraMouseWheelInput.prototype, \"wheelPrecision\", void 0);\n__decorate([\n serialize()\n], FollowCameraMouseWheelInput.prototype, \"wheelDeltaPercentage\", void 0);\nCameraInputTypes[\"FollowCameraMouseWheelInput\"] = FollowCameraMouseWheelInput;\n//# sourceMappingURL=followCameraMouseWheelInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { BaseCameraPointersInput } from \"../../Cameras/Inputs/BaseCameraPointersInput.js\";\n/**\n * Manage the pointers inputs to control an follow camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FollowCameraPointersInput extends BaseCameraPointersInput {\n constructor() {\n super(...arguments);\n /**\n * Defines the pointer angular sensibility along the X axis or how fast is\n * the camera rotating.\n * A negative number will reverse the axis direction.\n */\n this.angularSensibilityX = 1;\n /**\n * Defines the pointer angular sensibility along the Y axis or how fast is\n * the camera rotating.\n * A negative number will reverse the axis direction.\n */\n this.angularSensibilityY = 1;\n /**\n * Defines the pointer pinch precision or how fast is the camera zooming.\n * A negative number will reverse the axis direction.\n */\n this.pinchPrecision = 10000.0;\n /**\n * pinchDeltaPercentage will be used instead of pinchPrecision if different\n * from 0.\n * It defines the percentage of current camera.radius to use as delta when\n * pinch zoom is used.\n */\n this.pinchDeltaPercentage = 0;\n /**\n * Pointer X axis controls zoom. (X axis modifies camera.radius value.)\n */\n this.axisXControlRadius = false;\n /**\n * Pointer X axis controls height. (X axis modifies camera.heightOffset value.)\n */\n this.axisXControlHeight = false;\n /**\n * Pointer X axis controls angle. (X axis modifies camera.rotationOffset value.)\n */\n this.axisXControlRotation = true;\n /**\n * Pointer Y axis controls zoom. (Y axis modifies camera.radius value.)\n */\n this.axisYControlRadius = false;\n /**\n * Pointer Y axis controls height. (Y axis modifies camera.heightOffset value.)\n */\n this.axisYControlHeight = true;\n /**\n * Pointer Y axis controls angle. (Y axis modifies camera.rotationOffset value.)\n */\n this.axisYControlRotation = false;\n /**\n * Pinch controls zoom. (Pinch modifies camera.radius value.)\n */\n this.axisPinchControlRadius = true;\n /**\n * Pinch controls height. (Pinch modifies camera.heightOffset value.)\n */\n this.axisPinchControlHeight = false;\n /**\n * Pinch controls angle. (Pinch modifies camera.rotationOffset value.)\n */\n this.axisPinchControlRotation = false;\n /**\n * Log error messages if basic misconfiguration has occurred.\n */\n this.warningEnable = true;\n /* Check for obvious misconfiguration. */\n this._warningCounter = 0;\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"FollowCameraPointersInput\";\n }\n onTouch(pointA, offsetX, offsetY) {\n this._warning();\n if (this.axisXControlRotation) {\n this.camera.rotationOffset += offsetX / this.angularSensibilityX;\n }\n else if (this.axisYControlRotation) {\n this.camera.rotationOffset += offsetY / this.angularSensibilityX;\n }\n if (this.axisXControlHeight) {\n this.camera.heightOffset += offsetX / this.angularSensibilityY;\n }\n else if (this.axisYControlHeight) {\n this.camera.heightOffset += offsetY / this.angularSensibilityY;\n }\n if (this.axisXControlRadius) {\n this.camera.radius -= offsetX / this.angularSensibilityY;\n }\n else if (this.axisYControlRadius) {\n this.camera.radius -= offsetY / this.angularSensibilityY;\n }\n }\n onMultiTouch(pointA, pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition) {\n if (previousPinchSquaredDistance === 0 && previousMultiTouchPanPosition === null) {\n // First time this method is called for new pinch.\n // Next time this is called there will be a\n // previousPinchSquaredDistance and pinchSquaredDistance to compare.\n return;\n }\n if (pinchSquaredDistance === 0 && multiTouchPanPosition === null) {\n // Last time this method is called at the end of a pinch.\n return;\n }\n let pinchDelta = (pinchSquaredDistance - previousPinchSquaredDistance) / ((this.pinchPrecision * (this.angularSensibilityX + this.angularSensibilityY)) / 2);\n if (this.pinchDeltaPercentage) {\n pinchDelta *= 0.01 * this.pinchDeltaPercentage;\n if (this.axisPinchControlRotation) {\n this.camera.rotationOffset += pinchDelta * this.camera.rotationOffset;\n }\n if (this.axisPinchControlHeight) {\n this.camera.heightOffset += pinchDelta * this.camera.heightOffset;\n }\n if (this.axisPinchControlRadius) {\n this.camera.radius -= pinchDelta * this.camera.radius;\n }\n }\n else {\n if (this.axisPinchControlRotation) {\n this.camera.rotationOffset += pinchDelta;\n }\n if (this.axisPinchControlHeight) {\n this.camera.heightOffset += pinchDelta;\n }\n if (this.axisPinchControlRadius) {\n this.camera.radius -= pinchDelta;\n }\n }\n }\n _warning() {\n if (!this.warningEnable || this._warningCounter++ % 100 !== 0) {\n return;\n }\n const warn = \"It probably only makes sense to control ONE camera \" + \"property with each pointer axis. Set 'warningEnable = false' \" + \"if you are sure. Currently enabled: \";\n console.assert(this.axisXControlRotation + this.axisXControlHeight + this.axisXControlRadius <= 1, warn + \"axisXControlRotation: \" + this.axisXControlRotation + \", axisXControlHeight: \" + this.axisXControlHeight + \", axisXControlRadius: \" + this.axisXControlRadius);\n console.assert(this.axisYControlRotation + this.axisYControlHeight + this.axisYControlRadius <= 1, warn + \"axisYControlRotation: \" + this.axisYControlRotation + \", axisYControlHeight: \" + this.axisYControlHeight + \", axisYControlRadius: \" + this.axisYControlRadius);\n console.assert(this.axisPinchControlRotation + this.axisPinchControlHeight + this.axisPinchControlRadius <= 1, warn +\n \"axisPinchControlRotation: \" +\n this.axisPinchControlRotation +\n \", axisPinchControlHeight: \" +\n this.axisPinchControlHeight +\n \", axisPinchControlRadius: \" +\n this.axisPinchControlRadius);\n }\n}\n__decorate([\n serialize()\n], FollowCameraPointersInput.prototype, \"angularSensibilityX\", void 0);\n__decorate([\n serialize()\n], FollowCameraPointersInput.prototype, \"angularSensibilityY\", void 0);\n__decorate([\n serialize()\n], FollowCameraPointersInput.prototype, \"pinchPrecision\", void 0);\n__decorate([\n serialize()\n], FollowCameraPointersInput.prototype, \"pinchDeltaPercentage\", void 0);\n__decorate([\n serialize()\n], FollowCameraPointersInput.prototype, \"axisXControlRadius\", void 0);\n__decorate([\n serialize()\n], FollowCameraPointersInput.prototype, \"axisXControlHeight\", void 0);\n__decorate([\n serialize()\n], FollowCameraPointersInput.prototype, \"axisXControlRotation\", void 0);\n__decorate([\n serialize()\n], FollowCameraPointersInput.prototype, \"axisYControlRadius\", void 0);\n__decorate([\n serialize()\n], FollowCameraPointersInput.prototype, \"axisYControlHeight\", void 0);\n__decorate([\n serialize()\n], FollowCameraPointersInput.prototype, \"axisYControlRotation\", void 0);\n__decorate([\n serialize()\n], FollowCameraPointersInput.prototype, \"axisPinchControlRadius\", void 0);\n__decorate([\n serialize()\n], FollowCameraPointersInput.prototype, \"axisPinchControlHeight\", void 0);\n__decorate([\n serialize()\n], FollowCameraPointersInput.prototype, \"axisPinchControlRotation\", void 0);\nCameraInputTypes[\"FollowCameraPointersInput\"] = FollowCameraPointersInput;\n//# sourceMappingURL=followCameraPointersInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { KeyboardEventTypes } from \"../../Events/keyboardEvents.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * Manage the keyboard inputs to control the movement of a free camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FreeCameraKeyboardMoveInput {\n constructor() {\n /**\n * Gets or Set the list of keyboard keys used to control the forward move of the camera.\n */\n this.keysUp = [38];\n /**\n * Gets or Set the list of keyboard keys used to control the upward move of the camera.\n */\n this.keysUpward = [33];\n /**\n * Gets or Set the list of keyboard keys used to control the backward move of the camera.\n */\n this.keysDown = [40];\n /**\n * Gets or Set the list of keyboard keys used to control the downward move of the camera.\n */\n this.keysDownward = [34];\n /**\n * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.\n */\n this.keysLeft = [37];\n /**\n * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.\n */\n this.keysRight = [39];\n /**\n * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.\n */\n this.rotationSpeed = 0.5;\n /**\n * Gets or Set the list of keyboard keys used to control the left rotation move of the camera.\n */\n this.keysRotateLeft = [];\n /**\n * Gets or Set the list of keyboard keys used to control the right rotation move of the camera.\n */\n this.keysRotateRight = [];\n /**\n * Gets or Set the list of keyboard keys used to control the up rotation move of the camera.\n */\n this.keysRotateUp = [];\n /**\n * Gets or Set the list of keyboard keys used to control the down rotation move of the camera.\n */\n this.keysRotateDown = [];\n this._keys = new Array();\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(noPreventDefault) {\n // eslint-disable-next-line prefer-rest-params\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n if (this._onCanvasBlurObserver) {\n return;\n }\n this._scene = this.camera.getScene();\n this._engine = this._scene.getEngine();\n this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(() => {\n this._keys.length = 0;\n });\n this._onKeyboardObserver = this._scene.onKeyboardObservable.add((info) => {\n const evt = info.event;\n if (!evt.metaKey) {\n if (info.type === KeyboardEventTypes.KEYDOWN) {\n if (this.keysUp.indexOf(evt.keyCode) !== -1 ||\n this.keysDown.indexOf(evt.keyCode) !== -1 ||\n this.keysLeft.indexOf(evt.keyCode) !== -1 ||\n this.keysRight.indexOf(evt.keyCode) !== -1 ||\n this.keysUpward.indexOf(evt.keyCode) !== -1 ||\n this.keysDownward.indexOf(evt.keyCode) !== -1 ||\n this.keysRotateLeft.indexOf(evt.keyCode) !== -1 ||\n this.keysRotateRight.indexOf(evt.keyCode) !== -1 ||\n this.keysRotateUp.indexOf(evt.keyCode) !== -1 ||\n this.keysRotateDown.indexOf(evt.keyCode) !== -1) {\n const index = this._keys.indexOf(evt.keyCode);\n if (index === -1) {\n this._keys.push(evt.keyCode);\n }\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n }\n else {\n if (this.keysUp.indexOf(evt.keyCode) !== -1 ||\n this.keysDown.indexOf(evt.keyCode) !== -1 ||\n this.keysLeft.indexOf(evt.keyCode) !== -1 ||\n this.keysRight.indexOf(evt.keyCode) !== -1 ||\n this.keysUpward.indexOf(evt.keyCode) !== -1 ||\n this.keysDownward.indexOf(evt.keyCode) !== -1 ||\n this.keysRotateLeft.indexOf(evt.keyCode) !== -1 ||\n this.keysRotateRight.indexOf(evt.keyCode) !== -1 ||\n this.keysRotateUp.indexOf(evt.keyCode) !== -1 ||\n this.keysRotateDown.indexOf(evt.keyCode) !== -1) {\n const index = this._keys.indexOf(evt.keyCode);\n if (index >= 0) {\n this._keys.splice(index, 1);\n }\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n }\n }\n });\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n if (this._scene) {\n if (this._onKeyboardObserver) {\n this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);\n }\n if (this._onCanvasBlurObserver) {\n this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);\n }\n this._onKeyboardObserver = null;\n this._onCanvasBlurObserver = null;\n }\n this._keys.length = 0;\n }\n /**\n * Update the current camera state depending on the inputs that have been used this frame.\n * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.\n */\n checkInputs() {\n if (this._onKeyboardObserver) {\n const camera = this.camera;\n // Keyboard\n for (let index = 0; index < this._keys.length; index++) {\n const keyCode = this._keys[index];\n const speed = camera._computeLocalCameraSpeed();\n if (this.keysLeft.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(-speed, 0, 0);\n }\n else if (this.keysUp.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, 0, speed);\n }\n else if (this.keysRight.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(speed, 0, 0);\n }\n else if (this.keysDown.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, 0, -speed);\n }\n else if (this.keysUpward.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, speed, 0);\n }\n else if (this.keysDownward.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, -speed, 0);\n }\n else if (this.keysRotateLeft.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, 0, 0);\n camera.cameraRotation.y -= this._getLocalRotation();\n }\n else if (this.keysRotateRight.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, 0, 0);\n camera.cameraRotation.y += this._getLocalRotation();\n }\n else if (this.keysRotateUp.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, 0, 0);\n camera.cameraRotation.x -= this._getLocalRotation();\n }\n else if (this.keysRotateDown.indexOf(keyCode) !== -1) {\n camera._localDirection.copyFromFloats(0, 0, 0);\n camera.cameraRotation.x += this._getLocalRotation();\n }\n if (camera.getScene().useRightHandedSystem) {\n camera._localDirection.z *= -1;\n }\n camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);\n Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);\n camera.cameraDirection.addInPlace(camera._transformedDirection);\n }\n }\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"FreeCameraKeyboardMoveInput\";\n }\n /** @internal */\n _onLostFocus() {\n this._keys.length = 0;\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"keyboard\";\n }\n _getLocalRotation() {\n let rotation = (this.rotationSpeed * this._engine.getDeltaTime()) / 1000;\n if (this.camera.getScene().useRightHandedSystem) {\n rotation *= -1;\n }\n if (this.camera.parent && this.camera.parent._getWorldMatrixDeterminant() < 0) {\n rotation *= -1;\n }\n return rotation;\n }\n}\n__decorate([\n serialize()\n], FreeCameraKeyboardMoveInput.prototype, \"keysUp\", void 0);\n__decorate([\n serialize()\n], FreeCameraKeyboardMoveInput.prototype, \"keysUpward\", void 0);\n__decorate([\n serialize()\n], FreeCameraKeyboardMoveInput.prototype, \"keysDown\", void 0);\n__decorate([\n serialize()\n], FreeCameraKeyboardMoveInput.prototype, \"keysDownward\", void 0);\n__decorate([\n serialize()\n], FreeCameraKeyboardMoveInput.prototype, \"keysLeft\", void 0);\n__decorate([\n serialize()\n], FreeCameraKeyboardMoveInput.prototype, \"keysRight\", void 0);\n__decorate([\n serialize()\n], FreeCameraKeyboardMoveInput.prototype, \"rotationSpeed\", void 0);\n__decorate([\n serialize()\n], FreeCameraKeyboardMoveInput.prototype, \"keysRotateLeft\", void 0);\n__decorate([\n serialize()\n], FreeCameraKeyboardMoveInput.prototype, \"keysRotateRight\", void 0);\n__decorate([\n serialize()\n], FreeCameraKeyboardMoveInput.prototype, \"keysRotateUp\", void 0);\n__decorate([\n serialize()\n], FreeCameraKeyboardMoveInput.prototype, \"keysRotateDown\", void 0);\nCameraInputTypes[\"FreeCameraKeyboardMoveInput\"] = FreeCameraKeyboardMoveInput;\n//# sourceMappingURL=freeCameraKeyboardMoveInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { PointerEventTypes } from \"../../Events/pointerEvents.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * Manage the mouse inputs to control the movement of a free camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FreeCameraMouseInput {\n /**\n * Manage the mouse inputs to control the movement of a free camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n * @param touchEnabled Defines if touch is enabled or not\n */\n constructor(\n /**\n * Define if touch is enabled in the mouse input\n */\n touchEnabled = true) {\n this.touchEnabled = touchEnabled;\n /**\n * Defines the buttons associated with the input to handle camera move.\n */\n this.buttons = [0, 1, 2];\n /**\n * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.\n */\n this.angularSensibility = 2000.0;\n this._previousPosition = null;\n /**\n * Observable for when a pointer move event occurs containing the move offset\n */\n this.onPointerMovedObservable = new Observable();\n /**\n * @internal\n * If the camera should be rotated automatically based on pointer movement\n */\n this._allowCameraRotation = true;\n this._currentActiveButton = -1;\n this._activePointerId = -1;\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(noPreventDefault) {\n // eslint-disable-next-line prefer-rest-params\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n const engine = this.camera.getEngine();\n const element = engine.getInputElement();\n if (!this._pointerInput) {\n this._pointerInput = (p) => {\n const evt = p.event;\n const isTouch = evt.pointerType === \"touch\";\n if (engine.isInVRExclusivePointerMode) {\n return;\n }\n if (!this.touchEnabled && isTouch) {\n return;\n }\n if (p.type !== PointerEventTypes.POINTERMOVE && this.buttons.indexOf(evt.button) === -1) {\n return;\n }\n const srcElement = evt.target;\n if (p.type === PointerEventTypes.POINTERDOWN) {\n // If the input is touch with more than one touch OR if the input is mouse and there is already an active button, return\n if ((isTouch && this._activePointerId !== -1) || (!isTouch && this._currentActiveButton !== -1)) {\n return;\n }\n this._activePointerId = evt.pointerId;\n try {\n srcElement === null || srcElement === void 0 ? void 0 : srcElement.setPointerCapture(evt.pointerId);\n }\n catch (e) {\n //Nothing to do with the error. Execution will continue.\n }\n if (this._currentActiveButton === -1) {\n this._currentActiveButton = evt.button;\n }\n this._previousPosition = {\n x: evt.clientX,\n y: evt.clientY,\n };\n if (!noPreventDefault) {\n evt.preventDefault();\n element && element.focus();\n }\n // This is required to move while pointer button is down\n if (engine.isPointerLock && this._onMouseMove) {\n this._onMouseMove(p.event);\n }\n }\n else if (p.type === PointerEventTypes.POINTERUP) {\n // If input is touch with a different touch id OR if input is mouse with a different button, return\n if ((isTouch && this._activePointerId !== evt.pointerId) || (!isTouch && this._currentActiveButton !== evt.button)) {\n return;\n }\n try {\n srcElement === null || srcElement === void 0 ? void 0 : srcElement.releasePointerCapture(evt.pointerId);\n }\n catch (e) {\n //Nothing to do with the error.\n }\n this._currentActiveButton = -1;\n this._previousPosition = null;\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n this._activePointerId = -1;\n }\n else if (p.type === PointerEventTypes.POINTERMOVE && (this._activePointerId === evt.pointerId || !isTouch)) {\n if (engine.isPointerLock && this._onMouseMove) {\n this._onMouseMove(p.event);\n }\n else if (this._previousPosition) {\n let offsetX = evt.clientX - this._previousPosition.x;\n const offsetY = evt.clientY - this._previousPosition.y;\n if (this.camera.getScene().useRightHandedSystem) {\n offsetX *= -1;\n }\n if (this.camera.parent && this.camera.parent._getWorldMatrixDeterminant() < 0) {\n offsetX *= -1;\n }\n if (this._allowCameraRotation) {\n this.camera.cameraRotation.y += offsetX / this.angularSensibility;\n this.camera.cameraRotation.x += offsetY / this.angularSensibility;\n }\n this.onPointerMovedObservable.notifyObservers({ offsetX: offsetX, offsetY: offsetY });\n this._previousPosition = {\n x: evt.clientX,\n y: evt.clientY,\n };\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n }\n }\n };\n }\n this._onMouseMove = (evt) => {\n if (!engine.isPointerLock) {\n return;\n }\n if (engine.isInVRExclusivePointerMode) {\n return;\n }\n let offsetX = evt.movementX;\n if (this.camera.getScene().useRightHandedSystem) {\n offsetX *= -1;\n }\n if (this.camera.parent && this.camera.parent._getWorldMatrixDeterminant() < 0) {\n offsetX *= -1;\n }\n this.camera.cameraRotation.y += offsetX / this.angularSensibility;\n const offsetY = evt.movementY;\n this.camera.cameraRotation.x += offsetY / this.angularSensibility;\n this._previousPosition = null;\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n };\n this._observer = this.camera\n .getScene()\n ._inputManager._addCameraPointerObserver(this._pointerInput, PointerEventTypes.POINTERDOWN | PointerEventTypes.POINTERUP | PointerEventTypes.POINTERMOVE);\n if (element) {\n this._contextMenuBind = this.onContextMenu.bind(this);\n element.addEventListener(\"contextmenu\", this._contextMenuBind, false); // TODO: We need to figure out how to handle this for Native\n }\n }\n /**\n * Called on JS contextmenu event.\n * Override this method to provide functionality.\n * @param evt\n */\n onContextMenu(evt) {\n evt.preventDefault();\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n if (this._observer) {\n this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer);\n if (this._contextMenuBind) {\n const engine = this.camera.getEngine();\n const element = engine.getInputElement();\n element && element.removeEventListener(\"contextmenu\", this._contextMenuBind);\n }\n if (this.onPointerMovedObservable) {\n this.onPointerMovedObservable.clear();\n }\n this._observer = null;\n this._onMouseMove = null;\n this._previousPosition = null;\n }\n this._currentActiveButton = -1;\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"FreeCameraMouseInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"mouse\";\n }\n}\n__decorate([\n serialize()\n], FreeCameraMouseInput.prototype, \"buttons\", void 0);\n__decorate([\n serialize()\n], FreeCameraMouseInput.prototype, \"angularSensibility\", void 0);\nCameraInputTypes[\"FreeCameraMouseInput\"] = FreeCameraMouseInput;\n//# sourceMappingURL=freeCameraMouseInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { BaseCameraMouseWheelInput } from \"../../Cameras/Inputs/BaseCameraMouseWheelInput.js\";\nimport { Matrix, Vector3 } from \"../../Maths/math.vector.js\";\nimport { Coordinate } from \"../../Maths/math.axis.js\";\n// eslint-disable-next-line @typescript-eslint/naming-convention\nvar _CameraProperty;\n(function (_CameraProperty) {\n _CameraProperty[_CameraProperty[\"MoveRelative\"] = 0] = \"MoveRelative\";\n _CameraProperty[_CameraProperty[\"RotateRelative\"] = 1] = \"RotateRelative\";\n _CameraProperty[_CameraProperty[\"MoveScene\"] = 2] = \"MoveScene\";\n})(_CameraProperty || (_CameraProperty = {}));\n/**\n * Manage the mouse wheel inputs to control a free camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FreeCameraMouseWheelInput extends BaseCameraMouseWheelInput {\n constructor() {\n super(...arguments);\n this._moveRelative = Vector3.Zero();\n this._rotateRelative = Vector3.Zero();\n this._moveScene = Vector3.Zero();\n /**\n * These are set to the desired default behaviour.\n */\n this._wheelXAction = _CameraProperty.MoveRelative;\n this._wheelXActionCoordinate = Coordinate.X;\n this._wheelYAction = _CameraProperty.MoveRelative;\n this._wheelYActionCoordinate = Coordinate.Z;\n this._wheelZAction = null;\n this._wheelZActionCoordinate = null;\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"FreeCameraMouseWheelInput\";\n }\n /**\n * Set which movement axis (relative to camera's orientation) the mouse\n * wheel's X axis controls.\n * @param axis The axis to be moved. Set null to clear.\n */\n set wheelXMoveRelative(axis) {\n if (axis === null && this._wheelXAction !== _CameraProperty.MoveRelative) {\n // Attempting to clear different _wheelXAction.\n return;\n }\n this._wheelXAction = _CameraProperty.MoveRelative;\n this._wheelXActionCoordinate = axis;\n }\n /**\n * Get the configured movement axis (relative to camera's orientation) the\n * mouse wheel's X axis controls.\n * @returns The configured axis or null if none.\n */\n get wheelXMoveRelative() {\n if (this._wheelXAction !== _CameraProperty.MoveRelative) {\n return null;\n }\n return this._wheelXActionCoordinate;\n }\n /**\n * Set which movement axis (relative to camera's orientation) the mouse\n * wheel's Y axis controls.\n * @param axis The axis to be moved. Set null to clear.\n */\n set wheelYMoveRelative(axis) {\n if (axis === null && this._wheelYAction !== _CameraProperty.MoveRelative) {\n // Attempting to clear different _wheelYAction.\n return;\n }\n this._wheelYAction = _CameraProperty.MoveRelative;\n this._wheelYActionCoordinate = axis;\n }\n /**\n * Get the configured movement axis (relative to camera's orientation) the\n * mouse wheel's Y axis controls.\n * @returns The configured axis or null if none.\n */\n get wheelYMoveRelative() {\n if (this._wheelYAction !== _CameraProperty.MoveRelative) {\n return null;\n }\n return this._wheelYActionCoordinate;\n }\n /**\n * Set which movement axis (relative to camera's orientation) the mouse\n * wheel's Z axis controls.\n * @param axis The axis to be moved. Set null to clear.\n */\n set wheelZMoveRelative(axis) {\n if (axis === null && this._wheelZAction !== _CameraProperty.MoveRelative) {\n // Attempting to clear different _wheelZAction.\n return;\n }\n this._wheelZAction = _CameraProperty.MoveRelative;\n this._wheelZActionCoordinate = axis;\n }\n /**\n * Get the configured movement axis (relative to camera's orientation) the\n * mouse wheel's Z axis controls.\n * @returns The configured axis or null if none.\n */\n get wheelZMoveRelative() {\n if (this._wheelZAction !== _CameraProperty.MoveRelative) {\n return null;\n }\n return this._wheelZActionCoordinate;\n }\n /**\n * Set which rotation axis (relative to camera's orientation) the mouse\n * wheel's X axis controls.\n * @param axis The axis to be moved. Set null to clear.\n */\n set wheelXRotateRelative(axis) {\n if (axis === null && this._wheelXAction !== _CameraProperty.RotateRelative) {\n // Attempting to clear different _wheelXAction.\n return;\n }\n this._wheelXAction = _CameraProperty.RotateRelative;\n this._wheelXActionCoordinate = axis;\n }\n /**\n * Get the configured rotation axis (relative to camera's orientation) the\n * mouse wheel's X axis controls.\n * @returns The configured axis or null if none.\n */\n get wheelXRotateRelative() {\n if (this._wheelXAction !== _CameraProperty.RotateRelative) {\n return null;\n }\n return this._wheelXActionCoordinate;\n }\n /**\n * Set which rotation axis (relative to camera's orientation) the mouse\n * wheel's Y axis controls.\n * @param axis The axis to be moved. Set null to clear.\n */\n set wheelYRotateRelative(axis) {\n if (axis === null && this._wheelYAction !== _CameraProperty.RotateRelative) {\n // Attempting to clear different _wheelYAction.\n return;\n }\n this._wheelYAction = _CameraProperty.RotateRelative;\n this._wheelYActionCoordinate = axis;\n }\n /**\n * Get the configured rotation axis (relative to camera's orientation) the\n * mouse wheel's Y axis controls.\n * @returns The configured axis or null if none.\n */\n get wheelYRotateRelative() {\n if (this._wheelYAction !== _CameraProperty.RotateRelative) {\n return null;\n }\n return this._wheelYActionCoordinate;\n }\n /**\n * Set which rotation axis (relative to camera's orientation) the mouse\n * wheel's Z axis controls.\n * @param axis The axis to be moved. Set null to clear.\n */\n set wheelZRotateRelative(axis) {\n if (axis === null && this._wheelZAction !== _CameraProperty.RotateRelative) {\n // Attempting to clear different _wheelZAction.\n return;\n }\n this._wheelZAction = _CameraProperty.RotateRelative;\n this._wheelZActionCoordinate = axis;\n }\n /**\n * Get the configured rotation axis (relative to camera's orientation) the\n * mouse wheel's Z axis controls.\n * @returns The configured axis or null if none.\n */\n get wheelZRotateRelative() {\n if (this._wheelZAction !== _CameraProperty.RotateRelative) {\n return null;\n }\n return this._wheelZActionCoordinate;\n }\n /**\n * Set which movement axis (relative to the scene) the mouse wheel's X axis\n * controls.\n * @param axis The axis to be moved. Set null to clear.\n */\n set wheelXMoveScene(axis) {\n if (axis === null && this._wheelXAction !== _CameraProperty.MoveScene) {\n // Attempting to clear different _wheelXAction.\n return;\n }\n this._wheelXAction = _CameraProperty.MoveScene;\n this._wheelXActionCoordinate = axis;\n }\n /**\n * Get the configured movement axis (relative to the scene) the mouse wheel's\n * X axis controls.\n * @returns The configured axis or null if none.\n */\n get wheelXMoveScene() {\n if (this._wheelXAction !== _CameraProperty.MoveScene) {\n return null;\n }\n return this._wheelXActionCoordinate;\n }\n /**\n * Set which movement axis (relative to the scene) the mouse wheel's Y axis\n * controls.\n * @param axis The axis to be moved. Set null to clear.\n */\n set wheelYMoveScene(axis) {\n if (axis === null && this._wheelYAction !== _CameraProperty.MoveScene) {\n // Attempting to clear different _wheelYAction.\n return;\n }\n this._wheelYAction = _CameraProperty.MoveScene;\n this._wheelYActionCoordinate = axis;\n }\n /**\n * Get the configured movement axis (relative to the scene) the mouse wheel's\n * Y axis controls.\n * @returns The configured axis or null if none.\n */\n get wheelYMoveScene() {\n if (this._wheelYAction !== _CameraProperty.MoveScene) {\n return null;\n }\n return this._wheelYActionCoordinate;\n }\n /**\n * Set which movement axis (relative to the scene) the mouse wheel's Z axis\n * controls.\n * @param axis The axis to be moved. Set null to clear.\n */\n set wheelZMoveScene(axis) {\n if (axis === null && this._wheelZAction !== _CameraProperty.MoveScene) {\n // Attempting to clear different _wheelZAction.\n return;\n }\n this._wheelZAction = _CameraProperty.MoveScene;\n this._wheelZActionCoordinate = axis;\n }\n /**\n * Get the configured movement axis (relative to the scene) the mouse wheel's\n * Z axis controls.\n * @returns The configured axis or null if none.\n */\n get wheelZMoveScene() {\n if (this._wheelZAction !== _CameraProperty.MoveScene) {\n return null;\n }\n return this._wheelZActionCoordinate;\n }\n /**\n * Called for each rendered frame.\n */\n checkInputs() {\n if (this._wheelDeltaX === 0 && this._wheelDeltaY === 0 && this._wheelDeltaZ == 0) {\n return;\n }\n // Clear the camera properties that we might be updating.\n this._moveRelative.setAll(0);\n this._rotateRelative.setAll(0);\n this._moveScene.setAll(0);\n // Set the camera properties that are to be updated.\n this._updateCamera();\n if (this.camera.getScene().useRightHandedSystem) {\n // TODO: Does this need done for worldUpdate too?\n this._moveRelative.z *= -1;\n }\n // Convert updates relative to camera to world position update.\n const cameraTransformMatrix = Matrix.Zero();\n this.camera.getViewMatrix().invertToRef(cameraTransformMatrix);\n const transformedDirection = Vector3.Zero();\n Vector3.TransformNormalToRef(this._moveRelative, cameraTransformMatrix, transformedDirection);\n // Apply updates to camera position.\n this.camera.cameraRotation.x += this._rotateRelative.x / 200;\n this.camera.cameraRotation.y += this._rotateRelative.y / 200;\n this.camera.cameraDirection.addInPlace(transformedDirection);\n this.camera.cameraDirection.addInPlace(this._moveScene);\n // Call the base class implementation to handle observers and do cleanup.\n super.checkInputs();\n }\n /**\n * Update the camera according to any configured properties for the 3\n * mouse-wheel axis.\n */\n _updateCamera() {\n // Do the camera updates for each of the 3 touch-wheel axis.\n this._updateCameraProperty(this._wheelDeltaX, this._wheelXAction, this._wheelXActionCoordinate);\n this._updateCameraProperty(this._wheelDeltaY, this._wheelYAction, this._wheelYActionCoordinate);\n this._updateCameraProperty(this._wheelDeltaZ, this._wheelZAction, this._wheelZActionCoordinate);\n }\n /**\n * Update one property of the camera.\n * @param value\n * @param cameraProperty\n * @param coordinate\n */\n _updateCameraProperty(\n /* Mouse-wheel delta. */\n value, \n /* Camera property to be changed. */\n cameraProperty, \n /* Axis of Camera property to be changed. */\n coordinate) {\n if (value === 0) {\n // Mouse wheel has not moved.\n return;\n }\n if (cameraProperty === null || coordinate === null) {\n // Mouse wheel axis not configured.\n return;\n }\n let action = null;\n switch (cameraProperty) {\n case _CameraProperty.MoveRelative:\n action = this._moveRelative;\n break;\n case _CameraProperty.RotateRelative:\n action = this._rotateRelative;\n break;\n case _CameraProperty.MoveScene:\n action = this._moveScene;\n break;\n }\n switch (coordinate) {\n case Coordinate.X:\n action.set(value, 0, 0);\n break;\n case Coordinate.Y:\n action.set(0, value, 0);\n break;\n case Coordinate.Z:\n action.set(0, 0, value);\n break;\n }\n }\n}\n__decorate([\n serialize()\n], FreeCameraMouseWheelInput.prototype, \"wheelXMoveRelative\", null);\n__decorate([\n serialize()\n], FreeCameraMouseWheelInput.prototype, \"wheelYMoveRelative\", null);\n__decorate([\n serialize()\n], FreeCameraMouseWheelInput.prototype, \"wheelZMoveRelative\", null);\n__decorate([\n serialize()\n], FreeCameraMouseWheelInput.prototype, \"wheelXRotateRelative\", null);\n__decorate([\n serialize()\n], FreeCameraMouseWheelInput.prototype, \"wheelYRotateRelative\", null);\n__decorate([\n serialize()\n], FreeCameraMouseWheelInput.prototype, \"wheelZRotateRelative\", null);\n__decorate([\n serialize()\n], FreeCameraMouseWheelInput.prototype, \"wheelXMoveScene\", null);\n__decorate([\n serialize()\n], FreeCameraMouseWheelInput.prototype, \"wheelYMoveScene\", null);\n__decorate([\n serialize()\n], FreeCameraMouseWheelInput.prototype, \"wheelZMoveScene\", null);\nCameraInputTypes[\"FreeCameraMouseWheelInput\"] = FreeCameraMouseWheelInput;\n//# sourceMappingURL=freeCameraMouseWheelInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { PointerEventTypes } from \"../../Events/pointerEvents.js\";\nimport { Matrix, Vector3 } from \"../../Maths/math.vector.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * Manage the touch inputs to control the movement of a free camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FreeCameraTouchInput {\n /**\n * Manage the touch inputs to control the movement of a free camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n * @param allowMouse Defines if mouse events can be treated as touch events\n */\n constructor(\n /**\n * Define if mouse events can be treated as touch events\n */\n allowMouse = false) {\n this.allowMouse = allowMouse;\n /**\n * Defines the touch sensibility for rotation.\n * The lower the faster.\n */\n this.touchAngularSensibility = 200000.0;\n /**\n * Defines the touch sensibility for move.\n * The lower the faster.\n */\n this.touchMoveSensibility = 250.0;\n /**\n * Swap touch actions so that one touch is used for rotation and multiple for movement\n */\n this.singleFingerRotate = false;\n this._offsetX = null;\n this._offsetY = null;\n this._pointerPressed = new Array();\n this._isSafari = Tools.IsSafari();\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(noPreventDefault) {\n // eslint-disable-next-line prefer-rest-params\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n let previousPosition = null;\n if (this._pointerInput === undefined) {\n this._onLostFocus = () => {\n this._offsetX = null;\n this._offsetY = null;\n };\n this._pointerInput = (p) => {\n const evt = p.event;\n const isMouseEvent = evt.pointerType === \"mouse\" || (this._isSafari && typeof evt.pointerType === \"undefined\");\n if (!this.allowMouse && isMouseEvent) {\n return;\n }\n if (p.type === PointerEventTypes.POINTERDOWN) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n this._pointerPressed.push(evt.pointerId);\n if (this._pointerPressed.length !== 1) {\n return;\n }\n previousPosition = {\n x: evt.clientX,\n y: evt.clientY,\n };\n }\n else if (p.type === PointerEventTypes.POINTERUP) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n const index = this._pointerPressed.indexOf(evt.pointerId);\n if (index === -1) {\n return;\n }\n this._pointerPressed.splice(index, 1);\n if (index != 0) {\n return;\n }\n previousPosition = null;\n this._offsetX = null;\n this._offsetY = null;\n }\n else if (p.type === PointerEventTypes.POINTERMOVE) {\n if (!noPreventDefault) {\n evt.preventDefault();\n }\n if (!previousPosition) {\n return;\n }\n const index = this._pointerPressed.indexOf(evt.pointerId);\n if (index != 0) {\n return;\n }\n this._offsetX = evt.clientX - previousPosition.x;\n this._offsetY = -(evt.clientY - previousPosition.y);\n }\n };\n }\n this._observer = this.camera\n .getScene()\n ._inputManager._addCameraPointerObserver(this._pointerInput, PointerEventTypes.POINTERDOWN | PointerEventTypes.POINTERUP | PointerEventTypes.POINTERMOVE);\n if (this._onLostFocus) {\n const engine = this.camera.getEngine();\n const element = engine.getInputElement();\n element && element.addEventListener(\"blur\", this._onLostFocus);\n }\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n if (this._pointerInput) {\n if (this._observer) {\n this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer);\n this._observer = null;\n }\n if (this._onLostFocus) {\n const engine = this.camera.getEngine();\n const element = engine.getInputElement();\n element && element.removeEventListener(\"blur\", this._onLostFocus);\n this._onLostFocus = null;\n }\n this._pointerPressed.length = 0;\n this._offsetX = null;\n this._offsetY = null;\n }\n }\n /**\n * Update the current camera state depending on the inputs that have been used this frame.\n * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.\n */\n checkInputs() {\n if (this._offsetX === null || this._offsetY === null) {\n return;\n }\n if (this._offsetX === 0 && this._offsetY === 0) {\n return;\n }\n const camera = this.camera;\n camera.cameraRotation.y = this._offsetX / this.touchAngularSensibility;\n const rotateCamera = (this.singleFingerRotate && this._pointerPressed.length === 1) || (!this.singleFingerRotate && this._pointerPressed.length > 1);\n if (rotateCamera) {\n camera.cameraRotation.x = -this._offsetY / this.touchAngularSensibility;\n }\n else {\n const speed = camera._computeLocalCameraSpeed();\n const direction = new Vector3(0, 0, this.touchMoveSensibility !== 0 ? (speed * this._offsetY) / this.touchMoveSensibility : 0);\n Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);\n camera.cameraDirection.addInPlace(Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));\n }\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"FreeCameraTouchInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"touch\";\n }\n}\n__decorate([\n serialize()\n], FreeCameraTouchInput.prototype, \"touchAngularSensibility\", void 0);\n__decorate([\n serialize()\n], FreeCameraTouchInput.prototype, \"touchMoveSensibility\", void 0);\nCameraInputTypes[\"FreeCameraTouchInput\"] = FreeCameraTouchInput;\n//# sourceMappingURL=freeCameraTouchInput.js.map","import { CameraInputsManager } from \"./cameraInputsManager.js\";\nimport { FreeCameraKeyboardMoveInput } from \"../Cameras/Inputs/freeCameraKeyboardMoveInput.js\";\nimport { FreeCameraMouseInput } from \"../Cameras/Inputs/freeCameraMouseInput.js\";\nimport { FreeCameraMouseWheelInput } from \"../Cameras/Inputs/freeCameraMouseWheelInput.js\";\nimport { FreeCameraTouchInput } from \"../Cameras/Inputs/freeCameraTouchInput.js\";\n/**\n * Default Inputs manager for the FreeCamera.\n * It groups all the default supported inputs for ease of use.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FreeCameraInputsManager extends CameraInputsManager {\n /**\n * Instantiates a new FreeCameraInputsManager.\n * @param camera Defines the camera the inputs belong to\n */\n constructor(camera) {\n super(camera);\n /**\n * @internal\n */\n this._mouseInput = null;\n /**\n * @internal\n */\n this._mouseWheelInput = null;\n }\n /**\n * Add keyboard input support to the input manager.\n * @returns the current input manager\n */\n addKeyboard() {\n this.add(new FreeCameraKeyboardMoveInput());\n return this;\n }\n /**\n * Add mouse input support to the input manager.\n * @param touchEnabled if the FreeCameraMouseInput should support touch (default: true)\n * @returns the current input manager\n */\n addMouse(touchEnabled = true) {\n if (!this._mouseInput) {\n this._mouseInput = new FreeCameraMouseInput(touchEnabled);\n this.add(this._mouseInput);\n }\n return this;\n }\n /**\n * Removes the mouse input support from the manager\n * @returns the current input manager\n */\n removeMouse() {\n if (this._mouseInput) {\n this.remove(this._mouseInput);\n }\n return this;\n }\n /**\n * Add mouse wheel input support to the input manager.\n * @returns the current input manager\n */\n addMouseWheel() {\n if (!this._mouseWheelInput) {\n this._mouseWheelInput = new FreeCameraMouseWheelInput();\n this.add(this._mouseWheelInput);\n }\n return this;\n }\n /**\n * Removes the mouse wheel input support from the manager\n * @returns the current input manager\n */\n removeMouseWheel() {\n if (this._mouseWheelInput) {\n this.remove(this._mouseWheelInput);\n }\n return this;\n }\n /**\n * Add touch input support to the input manager.\n * @returns the current input manager\n */\n addTouch() {\n this.add(new FreeCameraTouchInput());\n return this;\n }\n /**\n * Remove all attached input methods from a camera\n */\n clear() {\n super.clear();\n this._mouseInput = null;\n }\n}\n//# sourceMappingURL=freeCameraInputsManager.js.map","import { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { Quaternion } from \"../../Maths/math.vector.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nimport { FreeCameraInputsManager } from \"../../Cameras/freeCameraInputsManager.js\";\nimport { Observable } from \"../../Misc/observable.js\";\n/**\n * Add orientation input support to the input manager.\n * @param smoothFactor deviceOrientation smoothing. 0: no smoothing, 1: new data ignored, 0.9 recommended for smoothing\n * @returns the current input manager\n */\nFreeCameraInputsManager.prototype.addDeviceOrientation = function (smoothFactor) {\n if (!this._deviceOrientationInput) {\n this._deviceOrientationInput = new FreeCameraDeviceOrientationInput();\n if (smoothFactor) {\n this._deviceOrientationInput.smoothFactor = smoothFactor;\n }\n this.add(this._deviceOrientationInput);\n }\n return this;\n};\n/**\n * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.\n * Screen rotation is taken into account.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FreeCameraDeviceOrientationInput {\n /**\n * Can be used to detect if a device orientation sensor is available on a device\n * @param timeout amount of time in milliseconds to wait for a response from the sensor (default: infinite)\n * @returns a promise that will resolve on orientation change\n */\n static WaitForOrientationChangeAsync(timeout) {\n return new Promise((res, rej) => {\n let gotValue = false;\n const eventHandler = () => {\n window.removeEventListener(\"deviceorientation\", eventHandler);\n gotValue = true;\n res();\n };\n // If timeout is populated reject the promise\n if (timeout) {\n setTimeout(() => {\n if (!gotValue) {\n window.removeEventListener(\"deviceorientation\", eventHandler);\n rej(\"WaitForOrientationChangeAsync timed out\");\n }\n }, timeout);\n }\n if (typeof DeviceOrientationEvent !== \"undefined\" && typeof DeviceOrientationEvent.requestPermission === \"function\") {\n DeviceOrientationEvent\n .requestPermission()\n .then((response) => {\n if (response == \"granted\") {\n window.addEventListener(\"deviceorientation\", eventHandler);\n }\n else {\n Tools.Warn(\"Permission not granted.\");\n }\n })\n .catch((error) => {\n Tools.Error(error);\n });\n }\n else {\n window.addEventListener(\"deviceorientation\", eventHandler);\n }\n });\n }\n /**\n * Instantiates a new input\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\n constructor() {\n this._screenOrientationAngle = 0;\n this._screenQuaternion = new Quaternion();\n this._alpha = 0;\n this._beta = 0;\n this._gamma = 0;\n /** alpha+beta+gamma smoothing. 0: no smoothing, 1: new data ignored, 0.9 recommended for smoothing */\n this.smoothFactor = 0;\n /**\n * @internal\n */\n this._onDeviceOrientationChangedObservable = new Observable();\n this._orientationChanged = () => {\n this._screenOrientationAngle =\n window.orientation !== undefined\n ? +window.orientation\n : window.screen.orientation && window.screen.orientation[\"angle\"]\n ? window.screen.orientation.angle\n : 0;\n this._screenOrientationAngle = -Tools.ToRadians(this._screenOrientationAngle / 2);\n this._screenQuaternion.copyFromFloats(0, Math.sin(this._screenOrientationAngle), 0, Math.cos(this._screenOrientationAngle));\n };\n this._deviceOrientation = (evt) => {\n if (this.smoothFactor) {\n this._alpha = evt.alpha !== null ? Tools.SmoothAngleChange(this._alpha, evt.alpha, this.smoothFactor) : 0;\n this._beta = evt.beta !== null ? Tools.SmoothAngleChange(this._beta, evt.beta, this.smoothFactor) : 0;\n this._gamma = evt.gamma !== null ? Tools.SmoothAngleChange(this._gamma, evt.gamma, this.smoothFactor) : 0;\n }\n else {\n this._alpha = evt.alpha !== null ? evt.alpha : 0;\n this._beta = evt.beta !== null ? evt.beta : 0;\n this._gamma = evt.gamma !== null ? evt.gamma : 0;\n }\n if (evt.alpha !== null) {\n this._onDeviceOrientationChangedObservable.notifyObservers();\n }\n };\n this._constantTranform = new Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));\n this._orientationChanged();\n }\n /**\n * Define the camera controlled by the input.\n */\n get camera() {\n return this._camera;\n }\n set camera(camera) {\n this._camera = camera;\n if (this._camera != null && !this._camera.rotationQuaternion) {\n this._camera.rotationQuaternion = new Quaternion();\n }\n if (this._camera) {\n this._camera.onDisposeObservable.add(() => {\n this._onDeviceOrientationChangedObservable.clear();\n });\n }\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n */\n attachControl() {\n const hostWindow = this.camera.getScene().getEngine().getHostWindow();\n if (hostWindow) {\n const eventHandler = () => {\n hostWindow.addEventListener(\"orientationchange\", this._orientationChanged);\n hostWindow.addEventListener(\"deviceorientation\", this._deviceOrientation);\n //In certain cases, the attach control is called AFTER orientation was changed,\n //So this is needed.\n this._orientationChanged();\n };\n if (typeof DeviceOrientationEvent !== \"undefined\" && typeof DeviceOrientationEvent.requestPermission === \"function\") {\n DeviceOrientationEvent\n .requestPermission()\n .then((response) => {\n if (response === \"granted\") {\n eventHandler();\n }\n else {\n Tools.Warn(\"Permission not granted.\");\n }\n })\n .catch((error) => {\n Tools.Error(error);\n });\n }\n else {\n eventHandler();\n }\n }\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n window.removeEventListener(\"orientationchange\", this._orientationChanged);\n window.removeEventListener(\"deviceorientation\", this._deviceOrientation);\n this._alpha = 0;\n }\n /**\n * Update the current camera state depending on the inputs that have been used this frame.\n * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.\n */\n checkInputs() {\n //if no device orientation provided, don't update the rotation.\n //Only testing against alpha under the assumption thatnorientation will never be so exact when set.\n if (!this._alpha) {\n return;\n }\n Quaternion.RotationYawPitchRollToRef(Tools.ToRadians(this._alpha), Tools.ToRadians(this._beta), -Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);\n this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);\n this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);\n //Mirror on XY Plane\n this._camera.rotationQuaternion.z *= -1;\n this._camera.rotationQuaternion.w *= -1;\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"FreeCameraDeviceOrientationInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"deviceOrientation\";\n }\n}\nCameraInputTypes[\"FreeCameraDeviceOrientationInput\"] = FreeCameraDeviceOrientationInput;\n//# sourceMappingURL=freeCameraDeviceOrientationInput.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize } from \"../../Misc/decorators.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { Matrix, Vector3, Vector2 } from \"../../Maths/math.vector.js\";\nimport { Gamepad } from \"../../Gamepads/gamepad.js\";\n/**\n * Manage the gamepad inputs to control a free camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FreeCameraGamepadInput {\n constructor() {\n /**\n * Defines the gamepad rotation sensibility.\n * This is the threshold from when rotation starts to be accounted for to prevent jittering.\n */\n this.gamepadAngularSensibility = 200;\n /**\n * Defines the gamepad move sensibility.\n * This is the threshold from when moving starts to be accounted for for to prevent jittering.\n */\n this.gamepadMoveSensibility = 40;\n /**\n * Defines the minimum value at which any analog stick input is ignored.\n * Note: This value should only be a value between 0 and 1.\n */\n this.deadzoneDelta = 0.1;\n this._yAxisScale = 1.0;\n this._cameraTransform = Matrix.Identity();\n this._deltaTransform = Vector3.Zero();\n this._vector3 = Vector3.Zero();\n this._vector2 = Vector2.Zero();\n }\n /**\n * Gets or sets a boolean indicating that Yaxis (for right stick) should be inverted\n */\n get invertYAxis() {\n return this._yAxisScale !== 1.0;\n }\n set invertYAxis(value) {\n this._yAxisScale = value ? -1.0 : 1.0;\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n */\n attachControl() {\n const manager = this.camera.getScene().gamepadManager;\n this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add((gamepad) => {\n if (gamepad.type !== Gamepad.POSE_ENABLED) {\n // prioritize XBOX gamepads.\n if (!this.gamepad || gamepad.type === Gamepad.XBOX) {\n this.gamepad = gamepad;\n }\n }\n });\n this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add((gamepad) => {\n if (this.gamepad === gamepad) {\n this.gamepad = null;\n }\n });\n // check if there are already other controllers connected\n this.gamepad = manager.getGamepadByType(Gamepad.XBOX);\n // if no xbox controller was found, but there are gamepad controllers, take the first one\n if (!this.gamepad && manager.gamepads.length) {\n this.gamepad = manager.gamepads[0];\n }\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);\n this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);\n this.gamepad = null;\n }\n /**\n * Update the current camera state depending on the inputs that have been used this frame.\n * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.\n */\n checkInputs() {\n if (this.gamepad && this.gamepad.leftStick) {\n const camera = this.camera;\n const lsValues = this.gamepad.leftStick;\n if (this.gamepadMoveSensibility !== 0) {\n lsValues.x = Math.abs(lsValues.x) > this.deadzoneDelta ? lsValues.x / this.gamepadMoveSensibility : 0;\n lsValues.y = Math.abs(lsValues.y) > this.deadzoneDelta ? lsValues.y / this.gamepadMoveSensibility : 0;\n }\n let rsValues = this.gamepad.rightStick;\n if (rsValues && this.gamepadAngularSensibility !== 0) {\n rsValues.x = Math.abs(rsValues.x) > this.deadzoneDelta ? rsValues.x / this.gamepadAngularSensibility : 0;\n rsValues.y = (Math.abs(rsValues.y) > this.deadzoneDelta ? rsValues.y / this.gamepadAngularSensibility : 0) * this._yAxisScale;\n }\n else {\n rsValues = { x: 0, y: 0 };\n }\n if (!camera.rotationQuaternion) {\n Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);\n }\n else {\n camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);\n }\n const speed = camera._computeLocalCameraSpeed() * 50.0;\n this._vector3.copyFromFloats(lsValues.x * speed, 0, -lsValues.y * speed);\n Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);\n camera.cameraDirection.addInPlace(this._deltaTransform);\n this._vector2.copyFromFloats(rsValues.y, rsValues.x);\n camera.cameraRotation.addInPlace(this._vector2);\n }\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"FreeCameraGamepadInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"gamepad\";\n }\n}\n__decorate([\n serialize()\n], FreeCameraGamepadInput.prototype, \"gamepadAngularSensibility\", void 0);\n__decorate([\n serialize()\n], FreeCameraGamepadInput.prototype, \"gamepadMoveSensibility\", void 0);\nCameraInputTypes[\"FreeCameraGamepadInput\"] = FreeCameraGamepadInput;\n//# sourceMappingURL=freeCameraGamepadInput.js.map","import { Vector3, Vector2 } from \"../Maths/math.vector.js\";\nimport { StringDictionary } from \"./stringDictionary.js\";\n// Mainly based on these 2 articles :\n// Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx\n// & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/\n/**\n * Defines the potential axis of a Joystick\n */\nexport var JoystickAxis;\n(function (JoystickAxis) {\n /** X axis */\n JoystickAxis[JoystickAxis[\"X\"] = 0] = \"X\";\n /** Y axis */\n JoystickAxis[JoystickAxis[\"Y\"] = 1] = \"Y\";\n /** Z axis */\n JoystickAxis[JoystickAxis[\"Z\"] = 2] = \"Z\";\n})(JoystickAxis || (JoystickAxis = {}));\n/**\n * Class used to define virtual joystick (used in touch mode)\n */\nexport class VirtualJoystick {\n static _GetDefaultOptions() {\n return {\n puckSize: 40,\n containerSize: 60,\n color: \"cyan\",\n puckImage: undefined,\n containerImage: undefined,\n position: undefined,\n alwaysVisible: false,\n limitToContainer: false,\n };\n }\n /**\n * Creates a new virtual joystick\n * @param leftJoystick defines that the joystick is for left hand (false by default)\n * @param customizations Defines the options we want to customize the VirtualJoystick\n */\n constructor(leftJoystick, customizations) {\n this._released = false;\n const options = Object.assign(Object.assign({}, VirtualJoystick._GetDefaultOptions()), customizations);\n if (leftJoystick) {\n this._leftJoystick = true;\n }\n else {\n this._leftJoystick = false;\n }\n VirtualJoystick._GlobalJoystickIndex++;\n // By default left & right arrow keys are moving the X\n // and up & down keys are moving the Y\n this._axisTargetedByLeftAndRight = JoystickAxis.X;\n this._axisTargetedByUpAndDown = JoystickAxis.Y;\n this.reverseLeftRight = false;\n this.reverseUpDown = false;\n // collections of pointers\n this._touches = new StringDictionary();\n this.deltaPosition = Vector3.Zero();\n this._joystickSensibility = 25;\n this._inversedSensibility = 1 / (this._joystickSensibility / 1000);\n this._onResize = () => {\n VirtualJoystick._VJCanvasWidth = window.innerWidth;\n VirtualJoystick._VJCanvasHeight = window.innerHeight;\n if (VirtualJoystick.Canvas) {\n VirtualJoystick.Canvas.width = VirtualJoystick._VJCanvasWidth;\n VirtualJoystick.Canvas.height = VirtualJoystick._VJCanvasHeight;\n }\n VirtualJoystick._HalfWidth = VirtualJoystick._VJCanvasWidth / 2;\n };\n // injecting a canvas element on top of the canvas 3D game\n if (!VirtualJoystick.Canvas) {\n window.addEventListener(\"resize\", this._onResize, false);\n VirtualJoystick.Canvas = document.createElement(\"canvas\");\n VirtualJoystick._VJCanvasWidth = window.innerWidth;\n VirtualJoystick._VJCanvasHeight = window.innerHeight;\n VirtualJoystick.Canvas.width = window.innerWidth;\n VirtualJoystick.Canvas.height = window.innerHeight;\n VirtualJoystick.Canvas.style.width = \"100%\";\n VirtualJoystick.Canvas.style.height = \"100%\";\n VirtualJoystick.Canvas.style.position = \"absolute\";\n VirtualJoystick.Canvas.style.backgroundColor = \"transparent\";\n VirtualJoystick.Canvas.style.top = \"0px\";\n VirtualJoystick.Canvas.style.left = \"0px\";\n VirtualJoystick.Canvas.style.zIndex = \"5\";\n VirtualJoystick.Canvas.style.touchAction = \"none\"; // fix https://forum.babylonjs.com/t/virtualjoystick-needs-to-set-style-touch-action-none-explicitly/9562\n // Support for jQuery PEP polyfill\n VirtualJoystick.Canvas.setAttribute(\"touch-action\", \"none\");\n const context = VirtualJoystick.Canvas.getContext(\"2d\");\n if (!context) {\n throw new Error(\"Unable to create canvas for virtual joystick\");\n }\n VirtualJoystick._VJCanvasContext = context;\n VirtualJoystick._VJCanvasContext.strokeStyle = \"#ffffff\";\n VirtualJoystick._VJCanvasContext.lineWidth = 2;\n document.body.appendChild(VirtualJoystick.Canvas);\n }\n VirtualJoystick._HalfWidth = VirtualJoystick.Canvas.width / 2;\n this.pressed = false;\n this.limitToContainer = options.limitToContainer;\n // default joystick color\n this._joystickColor = options.color;\n // default joystick size\n this.containerSize = options.containerSize;\n this.puckSize = options.puckSize;\n if (options.position) {\n this.setPosition(options.position.x, options.position.y);\n }\n if (options.puckImage) {\n this.setPuckImage(options.puckImage);\n }\n if (options.containerImage) {\n this.setContainerImage(options.containerImage);\n }\n if (options.alwaysVisible) {\n VirtualJoystick._AlwaysVisibleSticks++;\n }\n // must come after position potentially set\n this.alwaysVisible = options.alwaysVisible;\n this._joystickPointerId = -1;\n // current joystick position\n this._joystickPointerPos = new Vector2(0, 0);\n this._joystickPreviousPointerPos = new Vector2(0, 0);\n // origin joystick position\n this._joystickPointerStartPos = new Vector2(0, 0);\n this._deltaJoystickVector = new Vector2(0, 0);\n this._onPointerDownHandlerRef = (evt) => {\n this._onPointerDown(evt);\n };\n this._onPointerMoveHandlerRef = (evt) => {\n this._onPointerMove(evt);\n };\n this._onPointerUpHandlerRef = (evt) => {\n this._onPointerUp(evt);\n };\n VirtualJoystick.Canvas.addEventListener(\"pointerdown\", this._onPointerDownHandlerRef, false);\n VirtualJoystick.Canvas.addEventListener(\"pointermove\", this._onPointerMoveHandlerRef, false);\n VirtualJoystick.Canvas.addEventListener(\"pointerup\", this._onPointerUpHandlerRef, false);\n VirtualJoystick.Canvas.addEventListener(\"pointerout\", this._onPointerUpHandlerRef, false);\n VirtualJoystick.Canvas.addEventListener(\"contextmenu\", (evt) => {\n evt.preventDefault(); // Disables system menu\n }, false);\n requestAnimationFrame(() => {\n this._drawVirtualJoystick();\n });\n }\n /**\n * Defines joystick sensibility (ie. the ratio between a physical move and virtual joystick position change)\n * @param newJoystickSensibility defines the new sensibility\n */\n setJoystickSensibility(newJoystickSensibility) {\n this._joystickSensibility = newJoystickSensibility;\n this._inversedSensibility = 1 / (this._joystickSensibility / 1000);\n }\n _onPointerDown(e) {\n let positionOnScreenCondition;\n e.preventDefault();\n if (this._leftJoystick === true) {\n positionOnScreenCondition = e.clientX < VirtualJoystick._HalfWidth;\n }\n else {\n positionOnScreenCondition = e.clientX > VirtualJoystick._HalfWidth;\n }\n if (positionOnScreenCondition && this._joystickPointerId < 0) {\n // First contact will be dedicated to the virtual joystick\n this._joystickPointerId = e.pointerId;\n if (this._joystickPosition) {\n this._joystickPointerStartPos = this._joystickPosition.clone();\n this._joystickPointerPos = this._joystickPosition.clone();\n this._joystickPreviousPointerPos = this._joystickPosition.clone();\n // in case the user only clicks down && doesn't move:\n // this ensures the delta is properly set\n this._onPointerMove(e);\n }\n else {\n this._joystickPointerStartPos.x = e.clientX;\n this._joystickPointerStartPos.y = e.clientY;\n this._joystickPointerPos = this._joystickPointerStartPos.clone();\n this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();\n }\n this._deltaJoystickVector.x = 0;\n this._deltaJoystickVector.y = 0;\n this.pressed = true;\n this._touches.add(e.pointerId.toString(), e);\n }\n else {\n // You can only trigger the action buttons with a joystick declared\n if (VirtualJoystick._GlobalJoystickIndex < 2 && this._action) {\n this._action();\n this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });\n }\n }\n }\n _onPointerMove(e) {\n // If the current pointer is the one associated to the joystick (first touch contact)\n if (this._joystickPointerId == e.pointerId) {\n // limit to container if need be\n if (this.limitToContainer) {\n const vector = new Vector2(e.clientX - this._joystickPointerStartPos.x, e.clientY - this._joystickPointerStartPos.y);\n const distance = vector.length();\n if (distance > this.containerSize) {\n vector.scaleInPlace(this.containerSize / distance);\n }\n this._joystickPointerPos.x = this._joystickPointerStartPos.x + vector.x;\n this._joystickPointerPos.y = this._joystickPointerStartPos.y + vector.y;\n }\n else {\n this._joystickPointerPos.x = e.clientX;\n this._joystickPointerPos.y = e.clientY;\n }\n // create delta vector\n this._deltaJoystickVector = this._joystickPointerPos.clone();\n this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);\n // if a joystick is always visible, there will be clipping issues if\n // you drag the puck from one over the container of the other\n if (0 < VirtualJoystick._AlwaysVisibleSticks) {\n if (this._leftJoystick) {\n this._joystickPointerPos.x = Math.min(VirtualJoystick._HalfWidth, this._joystickPointerPos.x);\n }\n else {\n this._joystickPointerPos.x = Math.max(VirtualJoystick._HalfWidth, this._joystickPointerPos.x);\n }\n }\n const directionLeftRight = this.reverseLeftRight ? -1 : 1;\n const deltaJoystickX = (directionLeftRight * this._deltaJoystickVector.x) / this._inversedSensibility;\n switch (this._axisTargetedByLeftAndRight) {\n case JoystickAxis.X:\n this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));\n break;\n case JoystickAxis.Y:\n this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));\n break;\n case JoystickAxis.Z:\n this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));\n break;\n }\n const directionUpDown = this.reverseUpDown ? 1 : -1;\n const deltaJoystickY = (directionUpDown * this._deltaJoystickVector.y) / this._inversedSensibility;\n switch (this._axisTargetedByUpAndDown) {\n case JoystickAxis.X:\n this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));\n break;\n case JoystickAxis.Y:\n this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));\n break;\n case JoystickAxis.Z:\n this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));\n break;\n }\n }\n else {\n const data = this._touches.get(e.pointerId.toString());\n if (data) {\n data.x = e.clientX;\n data.y = e.clientY;\n }\n }\n }\n _onPointerUp(e) {\n if (this._joystickPointerId == e.pointerId) {\n this._clearPreviousDraw();\n this._joystickPointerId = -1;\n this.pressed = false;\n }\n else {\n const touch = this._touches.get(e.pointerId.toString());\n if (touch) {\n VirtualJoystick._VJCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);\n }\n }\n this._deltaJoystickVector.x = 0;\n this._deltaJoystickVector.y = 0;\n this._touches.remove(e.pointerId.toString());\n }\n /**\n * Change the color of the virtual joystick\n * @param newColor a string that must be a CSS color value (like \"red\") or the hexa value (like \"#FF0000\")\n */\n setJoystickColor(newColor) {\n this._joystickColor = newColor;\n }\n /**\n * Size of the joystick's container\n */\n set containerSize(newSize) {\n this._joystickContainerSize = newSize;\n this._clearContainerSize = ~~(this._joystickContainerSize * 2.1);\n this._clearContainerSizeOffset = ~~(this._clearContainerSize / 2);\n }\n get containerSize() {\n return this._joystickContainerSize;\n }\n /**\n * Size of the joystick's puck\n */\n set puckSize(newSize) {\n this._joystickPuckSize = newSize;\n this._clearPuckSize = ~~(this._joystickPuckSize * 2.1);\n this._clearPuckSizeOffset = ~~(this._clearPuckSize / 2);\n }\n get puckSize() {\n return this._joystickPuckSize;\n }\n /**\n * Clears the set position of the joystick\n */\n clearPosition() {\n this.alwaysVisible = false;\n this._joystickPosition = null;\n }\n /**\n * Defines whether or not the joystick container is always visible\n */\n set alwaysVisible(value) {\n if (this._alwaysVisible === value) {\n return;\n }\n if (value && this._joystickPosition) {\n VirtualJoystick._AlwaysVisibleSticks++;\n this._alwaysVisible = true;\n }\n else {\n VirtualJoystick._AlwaysVisibleSticks--;\n this._alwaysVisible = false;\n }\n }\n get alwaysVisible() {\n return this._alwaysVisible;\n }\n /**\n * Sets the constant position of the Joystick container\n * @param x X axis coordinate\n * @param y Y axis coordinate\n */\n setPosition(x, y) {\n // just in case position is moved while the container is visible\n if (this._joystickPointerStartPos) {\n this._clearPreviousDraw();\n }\n this._joystickPosition = new Vector2(x, y);\n }\n /**\n * Defines a callback to call when the joystick is touched\n * @param action defines the callback\n */\n setActionOnTouch(action) {\n this._action = action;\n }\n /**\n * Defines which axis you'd like to control for left & right\n * @param axis defines the axis to use\n */\n setAxisForLeftRight(axis) {\n switch (axis) {\n case JoystickAxis.X:\n case JoystickAxis.Y:\n case JoystickAxis.Z:\n this._axisTargetedByLeftAndRight = axis;\n break;\n default:\n this._axisTargetedByLeftAndRight = JoystickAxis.X;\n break;\n }\n }\n /**\n * Defines which axis you'd like to control for up & down\n * @param axis defines the axis to use\n */\n setAxisForUpDown(axis) {\n switch (axis) {\n case JoystickAxis.X:\n case JoystickAxis.Y:\n case JoystickAxis.Z:\n this._axisTargetedByUpAndDown = axis;\n break;\n default:\n this._axisTargetedByUpAndDown = JoystickAxis.Y;\n break;\n }\n }\n /**\n * Clears the canvas from the previous puck / container draw\n */\n _clearPreviousDraw() {\n const jp = this._joystickPosition || this._joystickPointerStartPos;\n // clear container pixels\n VirtualJoystick._VJCanvasContext.clearRect(jp.x - this._clearContainerSizeOffset, jp.y - this._clearContainerSizeOffset, this._clearContainerSize, this._clearContainerSize);\n // clear puck pixels + 1 pixel for the change made before it moved\n VirtualJoystick._VJCanvasContext.clearRect(this._joystickPreviousPointerPos.x - this._clearPuckSizeOffset - 1, this._joystickPreviousPointerPos.y - this._clearPuckSizeOffset - 1, this._clearPuckSize + 2, this._clearPuckSize + 2);\n }\n /**\n * Loads `urlPath` to be used for the container's image\n * @param urlPath defines the urlPath of an image to use\n */\n setContainerImage(urlPath) {\n const image = new Image();\n image.src = urlPath;\n image.onload = () => (this._containerImage = image);\n }\n /**\n * Loads `urlPath` to be used for the puck's image\n * @param urlPath defines the urlPath of an image to use\n */\n setPuckImage(urlPath) {\n const image = new Image();\n image.src = urlPath;\n image.onload = () => (this._puckImage = image);\n }\n /**\n * Draws the Virtual Joystick's container\n */\n _drawContainer() {\n const jp = this._joystickPosition || this._joystickPointerStartPos;\n this._clearPreviousDraw();\n if (this._containerImage) {\n VirtualJoystick._VJCanvasContext.drawImage(this._containerImage, jp.x - this.containerSize, jp.y - this.containerSize, this.containerSize * 2, this.containerSize * 2);\n }\n else {\n // outer container\n VirtualJoystick._VJCanvasContext.beginPath();\n VirtualJoystick._VJCanvasContext.strokeStyle = this._joystickColor;\n VirtualJoystick._VJCanvasContext.lineWidth = 2;\n VirtualJoystick._VJCanvasContext.arc(jp.x, jp.y, this.containerSize, 0, Math.PI * 2, true);\n VirtualJoystick._VJCanvasContext.stroke();\n VirtualJoystick._VJCanvasContext.closePath();\n // inner container\n VirtualJoystick._VJCanvasContext.beginPath();\n VirtualJoystick._VJCanvasContext.lineWidth = 6;\n VirtualJoystick._VJCanvasContext.strokeStyle = this._joystickColor;\n VirtualJoystick._VJCanvasContext.arc(jp.x, jp.y, this.puckSize, 0, Math.PI * 2, true);\n VirtualJoystick._VJCanvasContext.stroke();\n VirtualJoystick._VJCanvasContext.closePath();\n }\n }\n /**\n * Draws the Virtual Joystick's puck\n */\n _drawPuck() {\n if (this._puckImage) {\n VirtualJoystick._VJCanvasContext.drawImage(this._puckImage, this._joystickPointerPos.x - this.puckSize, this._joystickPointerPos.y - this.puckSize, this.puckSize * 2, this.puckSize * 2);\n }\n else {\n VirtualJoystick._VJCanvasContext.beginPath();\n VirtualJoystick._VJCanvasContext.strokeStyle = this._joystickColor;\n VirtualJoystick._VJCanvasContext.lineWidth = 2;\n VirtualJoystick._VJCanvasContext.arc(this._joystickPointerPos.x, this._joystickPointerPos.y, this.puckSize, 0, Math.PI * 2, true);\n VirtualJoystick._VJCanvasContext.stroke();\n VirtualJoystick._VJCanvasContext.closePath();\n }\n }\n _drawVirtualJoystick() {\n // canvas released? don't continue iterating\n if (this._released) {\n return;\n }\n if (this.alwaysVisible) {\n this._drawContainer();\n }\n if (this.pressed) {\n this._touches.forEach((key, touch) => {\n if (touch.pointerId === this._joystickPointerId) {\n if (!this.alwaysVisible) {\n this._drawContainer();\n }\n this._drawPuck();\n // store current pointer for next clear\n this._joystickPreviousPointerPos = this._joystickPointerPos.clone();\n }\n else {\n VirtualJoystick._VJCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);\n VirtualJoystick._VJCanvasContext.beginPath();\n VirtualJoystick._VJCanvasContext.fillStyle = \"white\";\n VirtualJoystick._VJCanvasContext.beginPath();\n VirtualJoystick._VJCanvasContext.strokeStyle = \"red\";\n VirtualJoystick._VJCanvasContext.lineWidth = 6;\n VirtualJoystick._VJCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);\n VirtualJoystick._VJCanvasContext.stroke();\n VirtualJoystick._VJCanvasContext.closePath();\n touch.prevX = touch.x;\n touch.prevY = touch.y;\n }\n });\n }\n requestAnimationFrame(() => {\n this._drawVirtualJoystick();\n });\n }\n /**\n * Release internal HTML canvas\n */\n releaseCanvas() {\n if (VirtualJoystick.Canvas) {\n VirtualJoystick.Canvas.removeEventListener(\"pointerdown\", this._onPointerDownHandlerRef);\n VirtualJoystick.Canvas.removeEventListener(\"pointermove\", this._onPointerMoveHandlerRef);\n VirtualJoystick.Canvas.removeEventListener(\"pointerup\", this._onPointerUpHandlerRef);\n VirtualJoystick.Canvas.removeEventListener(\"pointerout\", this._onPointerUpHandlerRef);\n window.removeEventListener(\"resize\", this._onResize);\n document.body.removeChild(VirtualJoystick.Canvas);\n VirtualJoystick.Canvas = null;\n }\n this._released = true;\n }\n}\n// Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas\nVirtualJoystick._GlobalJoystickIndex = 0;\nVirtualJoystick._AlwaysVisibleSticks = 0;\n//# sourceMappingURL=virtualJoystick.js.map","import { Observable } from \"../../Misc/observable.js\";\nimport { Quaternion, Matrix, Vector3, TmpVectors } from \"../../Maths/math.vector.js\";\nimport { Ray } from \"../../Culling/ray.js\";\nimport { EngineStore } from \"../../Engines/engineStore.js\";\nimport { Gamepad } from \"../../Gamepads/gamepad.js\";\n/**\n * Defines the types of pose enabled controllers that are supported\n */\nexport var PoseEnabledControllerType;\n(function (PoseEnabledControllerType) {\n /**\n * HTC Vive\n */\n PoseEnabledControllerType[PoseEnabledControllerType[\"VIVE\"] = 0] = \"VIVE\";\n /**\n * Oculus Rift\n */\n PoseEnabledControllerType[PoseEnabledControllerType[\"OCULUS\"] = 1] = \"OCULUS\";\n /**\n * Windows mixed reality\n */\n PoseEnabledControllerType[PoseEnabledControllerType[\"WINDOWS\"] = 2] = \"WINDOWS\";\n /**\n * Samsung gear VR\n */\n PoseEnabledControllerType[PoseEnabledControllerType[\"GEAR_VR\"] = 3] = \"GEAR_VR\";\n /**\n * Google Daydream\n */\n PoseEnabledControllerType[PoseEnabledControllerType[\"DAYDREAM\"] = 4] = \"DAYDREAM\";\n /**\n * Generic\n */\n PoseEnabledControllerType[PoseEnabledControllerType[\"GENERIC\"] = 5] = \"GENERIC\";\n})(PoseEnabledControllerType || (PoseEnabledControllerType = {}));\n/**\n * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)\n */\nexport class PoseEnabledControllerHelper {\n /**\n * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)\n * @param vrGamepad the gamepad to initialized\n * @returns a vr controller of the type the gamepad identified as\n */\n static InitiateController(vrGamepad) {\n for (const factory of this._ControllerFactories) {\n if (factory.canCreate(vrGamepad)) {\n return factory.create(vrGamepad);\n }\n }\n if (this._DefaultControllerFactory) {\n return this._DefaultControllerFactory(vrGamepad);\n }\n throw \"The type of gamepad you are trying to load needs to be imported first or is not supported.\";\n }\n}\n/** @internal */\nPoseEnabledControllerHelper._ControllerFactories = [];\n/** @internal */\nPoseEnabledControllerHelper._DefaultControllerFactory = null;\n/**\n * Defines the PoseEnabledController object that contains state of a vr capable controller\n */\nexport class PoseEnabledController extends Gamepad {\n /**\n * @internal\n */\n _disableTrackPosition(fixedPosition) {\n if (this._trackPosition) {\n this._calculatedPosition.copyFrom(fixedPosition);\n this._trackPosition = false;\n }\n }\n /**\n * Creates a new PoseEnabledController from a gamepad\n * @param browserGamepad the gamepad that the PoseEnabledController should be created from\n */\n constructor(browserGamepad) {\n super(browserGamepad.id, browserGamepad.index, browserGamepad);\n /**\n * If the controller is used in a webXR session\n */\n this.isXR = false;\n // Represents device position and rotation in room space. Should only be used to help calculate babylon space values\n this._deviceRoomPosition = Vector3.Zero();\n this._deviceRoomRotationQuaternion = new Quaternion();\n /**\n * The device position in babylon space\n */\n this.devicePosition = Vector3.Zero();\n /**\n * The device rotation in babylon space\n */\n this.deviceRotationQuaternion = new Quaternion();\n /**\n * The scale factor of the device in babylon space\n */\n this.deviceScaleFactor = 1;\n // Used to convert 6dof controllers to 3dof\n this._trackPosition = true;\n this._maxRotationDistFromHeadset = Math.PI / 5;\n this._draggedRoomRotation = 0;\n this._leftHandSystemQuaternion = new Quaternion();\n /**\n * Internal, matrix used to convert room space to babylon space\n * @internal\n */\n this._deviceToWorld = Matrix.Identity();\n /**\n * Node to be used when casting a ray from the controller\n * @internal\n */\n this._pointingPoseNode = null;\n this._workingMatrix = Matrix.Identity();\n /**\n * @internal\n */\n this._meshAttachedObservable = new Observable();\n this.type = Gamepad.POSE_ENABLED;\n this.controllerType = PoseEnabledControllerType.GENERIC;\n this.position = Vector3.Zero();\n this.rotationQuaternion = new Quaternion();\n this._calculatedPosition = Vector3.Zero();\n this._calculatedRotation = new Quaternion();\n Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, this._leftHandSystemQuaternion);\n }\n /**\n * Updates the state of the pose enabled controller and mesh based on the current position and rotation of the controller\n */\n update() {\n super.update();\n this._updatePoseAndMesh();\n }\n /**\n * Updates only the pose device and mesh without doing any button event checking\n */\n _updatePoseAndMesh() {\n if (this.isXR) {\n return;\n }\n const pose = this.browserGamepad.pose;\n this.updateFromDevice(pose);\n if (!this._trackPosition &&\n EngineStore.LastCreatedScene &&\n EngineStore.LastCreatedScene.activeCamera &&\n EngineStore.LastCreatedScene.activeCamera.devicePosition) {\n const camera = EngineStore.LastCreatedScene.activeCamera;\n camera._computeDevicePosition();\n this._deviceToWorld.setTranslation(camera.devicePosition);\n if (camera.deviceRotationQuaternion) {\n camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(TmpVectors.Vector3[0]);\n // Find the radian distance away that the headset is from the controllers rotation\n const distanceAway = Math.atan2(Math.sin(TmpVectors.Vector3[0].y - this._draggedRoomRotation), Math.cos(TmpVectors.Vector3[0].y - this._draggedRoomRotation));\n if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {\n // Only rotate enouph to be within the _maxRotationDistFromHeadset\n const rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);\n this._draggedRoomRotation += rotationAmount;\n // Rotate controller around headset\n const sin = Math.sin(-rotationAmount);\n const cos = Math.cos(-rotationAmount);\n this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;\n this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;\n }\n }\n }\n Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);\n this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);\n Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);\n this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);\n if (this._mesh) {\n this._mesh.position.copyFrom(this.devicePosition);\n if (this._mesh.rotationQuaternion) {\n this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);\n }\n }\n }\n /**\n * Updates the state of the pose enbaled controller based on the raw pose data from the device\n * @param poseData raw pose fromthe device\n */\n updateFromDevice(poseData) {\n if (this.isXR) {\n return;\n }\n if (poseData) {\n this.rawPose = poseData;\n if (poseData.position) {\n this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);\n if (this._mesh && this._mesh.getScene().useRightHandedSystem) {\n this._deviceRoomPosition.z *= -1;\n }\n if (this._trackPosition) {\n this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);\n }\n this._calculatedPosition.addInPlace(this.position);\n }\n const pose = this.rawPose;\n if (poseData.orientation && pose.orientation && pose.orientation.length === 4) {\n this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);\n if (this._mesh) {\n if (this._mesh.getScene().useRightHandedSystem) {\n this._deviceRoomRotationQuaternion.z *= -1;\n this._deviceRoomRotationQuaternion.w *= -1;\n }\n else {\n this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);\n }\n }\n // if the camera is set, rotate to the camera's rotation\n this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);\n }\n }\n }\n /**\n * Attaches a mesh to the controller\n * @param mesh the mesh to be attached\n */\n attachToMesh(mesh) {\n if (this._mesh) {\n this._mesh.parent = null;\n }\n this._mesh = mesh;\n if (this._poseControlledCamera) {\n this._mesh.parent = this._poseControlledCamera;\n }\n if (!this._mesh.rotationQuaternion) {\n this._mesh.rotationQuaternion = new Quaternion();\n }\n // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh\n if (!this.isXR) {\n this._updatePoseAndMesh();\n if (this._pointingPoseNode) {\n const parents = [];\n let obj = this._pointingPoseNode;\n while (obj.parent) {\n parents.push(obj.parent);\n obj = obj.parent;\n }\n parents.reverse().forEach((p) => {\n p.computeWorldMatrix(true);\n });\n }\n }\n this._meshAttachedObservable.notifyObservers(mesh);\n }\n /**\n * Attaches the controllers mesh to a camera\n * @param camera the camera the mesh should be attached to\n */\n attachToPoseControlledCamera(camera) {\n this._poseControlledCamera = camera;\n if (this._mesh) {\n this._mesh.parent = this._poseControlledCamera;\n }\n }\n /**\n * Disposes of the controller\n */\n dispose() {\n if (this._mesh) {\n this._mesh.dispose();\n }\n this._mesh = null;\n super.dispose();\n }\n /**\n * The mesh that is attached to the controller\n */\n get mesh() {\n return this._mesh;\n }\n /**\n * Gets the ray of the controller in the direction the controller is pointing\n * @param length the length the resulting ray should be\n * @returns a ray in the direction the controller is pointing\n */\n getForwardRay(length = 100) {\n if (!this.mesh) {\n return new Ray(Vector3.Zero(), new Vector3(0, 0, 1), length);\n }\n const m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();\n const origin = m.getTranslation();\n const forward = new Vector3(0, 0, -1);\n const forwardWorld = Vector3.TransformNormal(forward, m);\n const direction = Vector3.Normalize(forwardWorld);\n return new Ray(origin, direction, length);\n }\n}\n/**\n * Name of the child mesh that can be used to cast a ray from the controller\n */\nPoseEnabledController.POINTING_POSE = \"POINTING_POSE\";\n//# sourceMappingURL=poseEnabledController.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { Gamepad } from \"../Gamepads/gamepad.js\";\n/**\n * Defines supported buttons for XBox360 compatible gamepads\n */\nexport var Xbox360Button;\n(function (Xbox360Button) {\n /** A */\n Xbox360Button[Xbox360Button[\"A\"] = 0] = \"A\";\n /** B */\n Xbox360Button[Xbox360Button[\"B\"] = 1] = \"B\";\n /** X */\n Xbox360Button[Xbox360Button[\"X\"] = 2] = \"X\";\n /** Y */\n Xbox360Button[Xbox360Button[\"Y\"] = 3] = \"Y\";\n /** Left button */\n Xbox360Button[Xbox360Button[\"LB\"] = 4] = \"LB\";\n /** Right button */\n Xbox360Button[Xbox360Button[\"RB\"] = 5] = \"RB\";\n /** Back */\n Xbox360Button[Xbox360Button[\"Back\"] = 8] = \"Back\";\n /** Start */\n Xbox360Button[Xbox360Button[\"Start\"] = 9] = \"Start\";\n /** Left stick */\n Xbox360Button[Xbox360Button[\"LeftStick\"] = 10] = \"LeftStick\";\n /** Right stick */\n Xbox360Button[Xbox360Button[\"RightStick\"] = 11] = \"RightStick\";\n})(Xbox360Button || (Xbox360Button = {}));\n/** Defines values for XBox360 DPad */\nexport var Xbox360Dpad;\n(function (Xbox360Dpad) {\n /** Up */\n Xbox360Dpad[Xbox360Dpad[\"Up\"] = 12] = \"Up\";\n /** Down */\n Xbox360Dpad[Xbox360Dpad[\"Down\"] = 13] = \"Down\";\n /** Left */\n Xbox360Dpad[Xbox360Dpad[\"Left\"] = 14] = \"Left\";\n /** Right */\n Xbox360Dpad[Xbox360Dpad[\"Right\"] = 15] = \"Right\";\n})(Xbox360Dpad || (Xbox360Dpad = {}));\n/**\n * Defines a XBox360 gamepad\n */\nexport class Xbox360Pad extends Gamepad {\n /**\n * Creates a new XBox360 gamepad object\n * @param id defines the id of this gamepad\n * @param index defines its index\n * @param gamepad defines the internal HTML gamepad object\n * @param xboxOne defines if it is a XBox One gamepad\n */\n constructor(id, index, gamepad, xboxOne = false) {\n super(id, index, gamepad, 0, 1, 2, 3);\n this._leftTrigger = 0;\n this._rightTrigger = 0;\n /** Observable raised when a button is pressed */\n this.onButtonDownObservable = new Observable();\n /** Observable raised when a button is released */\n this.onButtonUpObservable = new Observable();\n /** Observable raised when a pad is pressed */\n this.onPadDownObservable = new Observable();\n /** Observable raised when a pad is released */\n this.onPadUpObservable = new Observable();\n this._buttonA = 0;\n this._buttonB = 0;\n this._buttonX = 0;\n this._buttonY = 0;\n this._buttonBack = 0;\n this._buttonStart = 0;\n this._buttonLB = 0;\n this._buttonRB = 0;\n this._buttonLeftStick = 0;\n this._buttonRightStick = 0;\n this._dPadUp = 0;\n this._dPadDown = 0;\n this._dPadLeft = 0;\n this._dPadRight = 0;\n this._isXboxOnePad = false;\n this.type = Gamepad.XBOX;\n this._isXboxOnePad = xboxOne;\n }\n /**\n * Defines the callback to call when left trigger is pressed\n * @param callback defines the callback to use\n */\n onlefttriggerchanged(callback) {\n this._onlefttriggerchanged = callback;\n }\n /**\n * Defines the callback to call when right trigger is pressed\n * @param callback defines the callback to use\n */\n onrighttriggerchanged(callback) {\n this._onrighttriggerchanged = callback;\n }\n /**\n * Gets the left trigger value\n */\n get leftTrigger() {\n return this._leftTrigger;\n }\n /**\n * Sets the left trigger value\n */\n set leftTrigger(newValue) {\n if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {\n this._onlefttriggerchanged(newValue);\n }\n this._leftTrigger = newValue;\n }\n /**\n * Gets the right trigger value\n */\n get rightTrigger() {\n return this._rightTrigger;\n }\n /**\n * Sets the right trigger value\n */\n set rightTrigger(newValue) {\n if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {\n this._onrighttriggerchanged(newValue);\n }\n this._rightTrigger = newValue;\n }\n /**\n * Defines the callback to call when a button is pressed\n * @param callback defines the callback to use\n */\n onbuttondown(callback) {\n this._onbuttondown = callback;\n }\n /**\n * Defines the callback to call when a button is released\n * @param callback defines the callback to use\n */\n onbuttonup(callback) {\n this._onbuttonup = callback;\n }\n /**\n * Defines the callback to call when a pad is pressed\n * @param callback defines the callback to use\n */\n ondpaddown(callback) {\n this._ondpaddown = callback;\n }\n /**\n * Defines the callback to call when a pad is released\n * @param callback defines the callback to use\n */\n ondpadup(callback) {\n this._ondpadup = callback;\n }\n _setButtonValue(newValue, currentValue, buttonType) {\n if (newValue !== currentValue) {\n if (newValue === 1) {\n if (this._onbuttondown) {\n this._onbuttondown(buttonType);\n }\n this.onButtonDownObservable.notifyObservers(buttonType);\n }\n if (newValue === 0) {\n if (this._onbuttonup) {\n this._onbuttonup(buttonType);\n }\n this.onButtonUpObservable.notifyObservers(buttonType);\n }\n }\n return newValue;\n }\n _setDPadValue(newValue, currentValue, buttonType) {\n if (newValue !== currentValue) {\n if (newValue === 1) {\n if (this._ondpaddown) {\n this._ondpaddown(buttonType);\n }\n this.onPadDownObservable.notifyObservers(buttonType);\n }\n if (newValue === 0) {\n if (this._ondpadup) {\n this._ondpadup(buttonType);\n }\n this.onPadUpObservable.notifyObservers(buttonType);\n }\n }\n return newValue;\n }\n /**\n * Gets the value of the `A` button\n */\n get buttonA() {\n return this._buttonA;\n }\n /**\n * Sets the value of the `A` button\n */\n set buttonA(value) {\n this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);\n }\n /**\n * Gets the value of the `B` button\n */\n get buttonB() {\n return this._buttonB;\n }\n /**\n * Sets the value of the `B` button\n */\n set buttonB(value) {\n this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);\n }\n /**\n * Gets the value of the `X` button\n */\n get buttonX() {\n return this._buttonX;\n }\n /**\n * Sets the value of the `X` button\n */\n set buttonX(value) {\n this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);\n }\n /**\n * Gets the value of the `Y` button\n */\n get buttonY() {\n return this._buttonY;\n }\n /**\n * Sets the value of the `Y` button\n */\n set buttonY(value) {\n this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);\n }\n /**\n * Gets the value of the `Start` button\n */\n get buttonStart() {\n return this._buttonStart;\n }\n /**\n * Sets the value of the `Start` button\n */\n set buttonStart(value) {\n this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);\n }\n /**\n * Gets the value of the `Back` button\n */\n get buttonBack() {\n return this._buttonBack;\n }\n /**\n * Sets the value of the `Back` button\n */\n set buttonBack(value) {\n this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);\n }\n /**\n * Gets the value of the `Left` button\n */\n get buttonLB() {\n return this._buttonLB;\n }\n /**\n * Sets the value of the `Left` button\n */\n set buttonLB(value) {\n this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);\n }\n /**\n * Gets the value of the `Right` button\n */\n get buttonRB() {\n return this._buttonRB;\n }\n /**\n * Sets the value of the `Right` button\n */\n set buttonRB(value) {\n this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);\n }\n /**\n * Gets the value of the Left joystick\n */\n get buttonLeftStick() {\n return this._buttonLeftStick;\n }\n /**\n * Sets the value of the Left joystick\n */\n set buttonLeftStick(value) {\n this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);\n }\n /**\n * Gets the value of the Right joystick\n */\n get buttonRightStick() {\n return this._buttonRightStick;\n }\n /**\n * Sets the value of the Right joystick\n */\n set buttonRightStick(value) {\n this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);\n }\n /**\n * Gets the value of D-pad up\n */\n get dPadUp() {\n return this._dPadUp;\n }\n /**\n * Sets the value of D-pad up\n */\n set dPadUp(value) {\n this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);\n }\n /**\n * Gets the value of D-pad down\n */\n get dPadDown() {\n return this._dPadDown;\n }\n /**\n * Sets the value of D-pad down\n */\n set dPadDown(value) {\n this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);\n }\n /**\n * Gets the value of D-pad left\n */\n get dPadLeft() {\n return this._dPadLeft;\n }\n /**\n * Sets the value of D-pad left\n */\n set dPadLeft(value) {\n this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);\n }\n /**\n * Gets the value of D-pad right\n */\n get dPadRight() {\n return this._dPadRight;\n }\n /**\n * Sets the value of D-pad right\n */\n set dPadRight(value) {\n this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);\n }\n /**\n * Force the gamepad to synchronize with device values\n */\n update() {\n super.update();\n if (this._isXboxOnePad) {\n this.buttonA = this.browserGamepad.buttons[0].value;\n this.buttonB = this.browserGamepad.buttons[1].value;\n this.buttonX = this.browserGamepad.buttons[2].value;\n this.buttonY = this.browserGamepad.buttons[3].value;\n this.buttonLB = this.browserGamepad.buttons[4].value;\n this.buttonRB = this.browserGamepad.buttons[5].value;\n this.leftTrigger = this.browserGamepad.buttons[6].value;\n this.rightTrigger = this.browserGamepad.buttons[7].value;\n this.buttonBack = this.browserGamepad.buttons[8].value;\n this.buttonStart = this.browserGamepad.buttons[9].value;\n this.buttonLeftStick = this.browserGamepad.buttons[10].value;\n this.buttonRightStick = this.browserGamepad.buttons[11].value;\n this.dPadUp = this.browserGamepad.buttons[12].value;\n this.dPadDown = this.browserGamepad.buttons[13].value;\n this.dPadLeft = this.browserGamepad.buttons[14].value;\n this.dPadRight = this.browserGamepad.buttons[15].value;\n }\n else {\n this.buttonA = this.browserGamepad.buttons[0].value;\n this.buttonB = this.browserGamepad.buttons[1].value;\n this.buttonX = this.browserGamepad.buttons[2].value;\n this.buttonY = this.browserGamepad.buttons[3].value;\n this.buttonLB = this.browserGamepad.buttons[4].value;\n this.buttonRB = this.browserGamepad.buttons[5].value;\n this.leftTrigger = this.browserGamepad.buttons[6].value;\n this.rightTrigger = this.browserGamepad.buttons[7].value;\n this.buttonBack = this.browserGamepad.buttons[8].value;\n this.buttonStart = this.browserGamepad.buttons[9].value;\n this.buttonLeftStick = this.browserGamepad.buttons[10].value;\n this.buttonRightStick = this.browserGamepad.buttons[11].value;\n this.dPadUp = this.browserGamepad.buttons[12].value;\n this.dPadDown = this.browserGamepad.buttons[13].value;\n this.dPadLeft = this.browserGamepad.buttons[14].value;\n this.dPadRight = this.browserGamepad.buttons[15].value;\n }\n }\n /**\n * Disposes the gamepad\n */\n dispose() {\n super.dispose();\n this.onButtonDownObservable.clear();\n this.onButtonUpObservable.clear();\n this.onPadDownObservable.clear();\n this.onPadUpObservable.clear();\n }\n}\n//# sourceMappingURL=xboxGamepad.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { Gamepad } from \"./gamepad.js\";\n/**\n * Defines supported buttons for DualShock compatible gamepads\n */\nexport var DualShockButton;\n(function (DualShockButton) {\n /** Cross */\n DualShockButton[DualShockButton[\"Cross\"] = 0] = \"Cross\";\n /** Circle */\n DualShockButton[DualShockButton[\"Circle\"] = 1] = \"Circle\";\n /** Square */\n DualShockButton[DualShockButton[\"Square\"] = 2] = \"Square\";\n /** Triangle */\n DualShockButton[DualShockButton[\"Triangle\"] = 3] = \"Triangle\";\n /** L1 */\n DualShockButton[DualShockButton[\"L1\"] = 4] = \"L1\";\n /** R1 */\n DualShockButton[DualShockButton[\"R1\"] = 5] = \"R1\";\n /** Share */\n DualShockButton[DualShockButton[\"Share\"] = 8] = \"Share\";\n /** Options */\n DualShockButton[DualShockButton[\"Options\"] = 9] = \"Options\";\n /** Left stick */\n DualShockButton[DualShockButton[\"LeftStick\"] = 10] = \"LeftStick\";\n /** Right stick */\n DualShockButton[DualShockButton[\"RightStick\"] = 11] = \"RightStick\";\n})(DualShockButton || (DualShockButton = {}));\n/** Defines values for DualShock DPad */\nexport var DualShockDpad;\n(function (DualShockDpad) {\n /** Up */\n DualShockDpad[DualShockDpad[\"Up\"] = 12] = \"Up\";\n /** Down */\n DualShockDpad[DualShockDpad[\"Down\"] = 13] = \"Down\";\n /** Left */\n DualShockDpad[DualShockDpad[\"Left\"] = 14] = \"Left\";\n /** Right */\n DualShockDpad[DualShockDpad[\"Right\"] = 15] = \"Right\";\n})(DualShockDpad || (DualShockDpad = {}));\n/**\n * Defines a DualShock gamepad\n */\nexport class DualShockPad extends Gamepad {\n /**\n * Creates a new DualShock gamepad object\n * @param id defines the id of this gamepad\n * @param index defines its index\n * @param gamepad defines the internal HTML gamepad object\n */\n constructor(id, index, gamepad) {\n super(id.replace(\"STANDARD GAMEPAD\", \"SONY PLAYSTATION DUALSHOCK\"), index, gamepad, 0, 1, 2, 3);\n this._leftTrigger = 0;\n this._rightTrigger = 0;\n /** Observable raised when a button is pressed */\n this.onButtonDownObservable = new Observable();\n /** Observable raised when a button is released */\n this.onButtonUpObservable = new Observable();\n /** Observable raised when a pad is pressed */\n this.onPadDownObservable = new Observable();\n /** Observable raised when a pad is released */\n this.onPadUpObservable = new Observable();\n this._buttonCross = 0;\n this._buttonCircle = 0;\n this._buttonSquare = 0;\n this._buttonTriangle = 0;\n this._buttonShare = 0;\n this._buttonOptions = 0;\n this._buttonL1 = 0;\n this._buttonR1 = 0;\n this._buttonLeftStick = 0;\n this._buttonRightStick = 0;\n this._dPadUp = 0;\n this._dPadDown = 0;\n this._dPadLeft = 0;\n this._dPadRight = 0;\n this.type = Gamepad.DUALSHOCK;\n }\n /**\n * Defines the callback to call when left trigger is pressed\n * @param callback defines the callback to use\n */\n onlefttriggerchanged(callback) {\n this._onlefttriggerchanged = callback;\n }\n /**\n * Defines the callback to call when right trigger is pressed\n * @param callback defines the callback to use\n */\n onrighttriggerchanged(callback) {\n this._onrighttriggerchanged = callback;\n }\n /**\n * Gets the left trigger value\n */\n get leftTrigger() {\n return this._leftTrigger;\n }\n /**\n * Sets the left trigger value\n */\n set leftTrigger(newValue) {\n if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {\n this._onlefttriggerchanged(newValue);\n }\n this._leftTrigger = newValue;\n }\n /**\n * Gets the right trigger value\n */\n get rightTrigger() {\n return this._rightTrigger;\n }\n /**\n * Sets the right trigger value\n */\n set rightTrigger(newValue) {\n if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {\n this._onrighttriggerchanged(newValue);\n }\n this._rightTrigger = newValue;\n }\n /**\n * Defines the callback to call when a button is pressed\n * @param callback defines the callback to use\n */\n onbuttondown(callback) {\n this._onbuttondown = callback;\n }\n /**\n * Defines the callback to call when a button is released\n * @param callback defines the callback to use\n */\n onbuttonup(callback) {\n this._onbuttonup = callback;\n }\n /**\n * Defines the callback to call when a pad is pressed\n * @param callback defines the callback to use\n */\n ondpaddown(callback) {\n this._ondpaddown = callback;\n }\n /**\n * Defines the callback to call when a pad is released\n * @param callback defines the callback to use\n */\n ondpadup(callback) {\n this._ondpadup = callback;\n }\n _setButtonValue(newValue, currentValue, buttonType) {\n if (newValue !== currentValue) {\n if (newValue === 1) {\n if (this._onbuttondown) {\n this._onbuttondown(buttonType);\n }\n this.onButtonDownObservable.notifyObservers(buttonType);\n }\n if (newValue === 0) {\n if (this._onbuttonup) {\n this._onbuttonup(buttonType);\n }\n this.onButtonUpObservable.notifyObservers(buttonType);\n }\n }\n return newValue;\n }\n _setDPadValue(newValue, currentValue, buttonType) {\n if (newValue !== currentValue) {\n if (newValue === 1) {\n if (this._ondpaddown) {\n this._ondpaddown(buttonType);\n }\n this.onPadDownObservable.notifyObservers(buttonType);\n }\n if (newValue === 0) {\n if (this._ondpadup) {\n this._ondpadup(buttonType);\n }\n this.onPadUpObservable.notifyObservers(buttonType);\n }\n }\n return newValue;\n }\n /**\n * Gets the value of the `Cross` button\n */\n get buttonCross() {\n return this._buttonCross;\n }\n /**\n * Sets the value of the `Cross` button\n */\n set buttonCross(value) {\n this._buttonCross = this._setButtonValue(value, this._buttonCross, DualShockButton.Cross);\n }\n /**\n * Gets the value of the `Circle` button\n */\n get buttonCircle() {\n return this._buttonCircle;\n }\n /**\n * Sets the value of the `Circle` button\n */\n set buttonCircle(value) {\n this._buttonCircle = this._setButtonValue(value, this._buttonCircle, DualShockButton.Circle);\n }\n /**\n * Gets the value of the `Square` button\n */\n get buttonSquare() {\n return this._buttonSquare;\n }\n /**\n * Sets the value of the `Square` button\n */\n set buttonSquare(value) {\n this._buttonSquare = this._setButtonValue(value, this._buttonSquare, DualShockButton.Square);\n }\n /**\n * Gets the value of the `Triangle` button\n */\n get buttonTriangle() {\n return this._buttonTriangle;\n }\n /**\n * Sets the value of the `Triangle` button\n */\n set buttonTriangle(value) {\n this._buttonTriangle = this._setButtonValue(value, this._buttonTriangle, DualShockButton.Triangle);\n }\n /**\n * Gets the value of the `Options` button\n */\n get buttonOptions() {\n return this._buttonOptions;\n }\n /**\n * Sets the value of the `Options` button\n */\n set buttonOptions(value) {\n this._buttonOptions = this._setButtonValue(value, this._buttonOptions, DualShockButton.Options);\n }\n /**\n * Gets the value of the `Share` button\n */\n get buttonShare() {\n return this._buttonShare;\n }\n /**\n * Sets the value of the `Share` button\n */\n set buttonShare(value) {\n this._buttonShare = this._setButtonValue(value, this._buttonShare, DualShockButton.Share);\n }\n /**\n * Gets the value of the `L1` button\n */\n get buttonL1() {\n return this._buttonL1;\n }\n /**\n * Sets the value of the `L1` button\n */\n set buttonL1(value) {\n this._buttonL1 = this._setButtonValue(value, this._buttonL1, DualShockButton.L1);\n }\n /**\n * Gets the value of the `R1` button\n */\n get buttonR1() {\n return this._buttonR1;\n }\n /**\n * Sets the value of the `R1` button\n */\n set buttonR1(value) {\n this._buttonR1 = this._setButtonValue(value, this._buttonR1, DualShockButton.R1);\n }\n /**\n * Gets the value of the Left joystick\n */\n get buttonLeftStick() {\n return this._buttonLeftStick;\n }\n /**\n * Sets the value of the Left joystick\n */\n set buttonLeftStick(value) {\n this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, DualShockButton.LeftStick);\n }\n /**\n * Gets the value of the Right joystick\n */\n get buttonRightStick() {\n return this._buttonRightStick;\n }\n /**\n * Sets the value of the Right joystick\n */\n set buttonRightStick(value) {\n this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, DualShockButton.RightStick);\n }\n /**\n * Gets the value of D-pad up\n */\n get dPadUp() {\n return this._dPadUp;\n }\n /**\n * Sets the value of D-pad up\n */\n set dPadUp(value) {\n this._dPadUp = this._setDPadValue(value, this._dPadUp, DualShockDpad.Up);\n }\n /**\n * Gets the value of D-pad down\n */\n get dPadDown() {\n return this._dPadDown;\n }\n /**\n * Sets the value of D-pad down\n */\n set dPadDown(value) {\n this._dPadDown = this._setDPadValue(value, this._dPadDown, DualShockDpad.Down);\n }\n /**\n * Gets the value of D-pad left\n */\n get dPadLeft() {\n return this._dPadLeft;\n }\n /**\n * Sets the value of D-pad left\n */\n set dPadLeft(value) {\n this._dPadLeft = this._setDPadValue(value, this._dPadLeft, DualShockDpad.Left);\n }\n /**\n * Gets the value of D-pad right\n */\n get dPadRight() {\n return this._dPadRight;\n }\n /**\n * Sets the value of D-pad right\n */\n set dPadRight(value) {\n this._dPadRight = this._setDPadValue(value, this._dPadRight, DualShockDpad.Right);\n }\n /**\n * Force the gamepad to synchronize with device values\n */\n update() {\n super.update();\n this.buttonCross = this.browserGamepad.buttons[0].value;\n this.buttonCircle = this.browserGamepad.buttons[1].value;\n this.buttonSquare = this.browserGamepad.buttons[2].value;\n this.buttonTriangle = this.browserGamepad.buttons[3].value;\n this.buttonL1 = this.browserGamepad.buttons[4].value;\n this.buttonR1 = this.browserGamepad.buttons[5].value;\n this.leftTrigger = this.browserGamepad.buttons[6].value;\n this.rightTrigger = this.browserGamepad.buttons[7].value;\n this.buttonShare = this.browserGamepad.buttons[8].value;\n this.buttonOptions = this.browserGamepad.buttons[9].value;\n this.buttonLeftStick = this.browserGamepad.buttons[10].value;\n this.buttonRightStick = this.browserGamepad.buttons[11].value;\n this.dPadUp = this.browserGamepad.buttons[12].value;\n this.dPadDown = this.browserGamepad.buttons[13].value;\n this.dPadLeft = this.browserGamepad.buttons[14].value;\n this.dPadRight = this.browserGamepad.buttons[15].value;\n }\n /**\n * Disposes the gamepad\n */\n dispose() {\n super.dispose();\n this.onButtonDownObservable.clear();\n this.onButtonUpObservable.clear();\n this.onPadDownObservable.clear();\n this.onPadUpObservable.clear();\n }\n}\n//# sourceMappingURL=dualShockGamepad.js.map","import { VirtualJoystick, JoystickAxis } from \"../../Misc/virtualJoystick.js\";\nimport { CameraInputTypes } from \"../../Cameras/cameraInputsManager.js\";\nimport { Matrix, Vector3 } from \"../../Maths/math.vector.js\";\nimport { FreeCameraInputsManager } from \"../../Cameras/freeCameraInputsManager.js\";\n/**\n * Add virtual joystick input support to the input manager.\n * @returns the current input manager\n */\nFreeCameraInputsManager.prototype.addVirtualJoystick = function () {\n this.add(new FreeCameraVirtualJoystickInput());\n return this;\n};\n/**\n * Manage the Virtual Joystick inputs to control the movement of a free camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FreeCameraVirtualJoystickInput {\n /**\n * Gets the left stick of the virtual joystick.\n * @returns The virtual Joystick\n */\n getLeftJoystick() {\n return this._leftjoystick;\n }\n /**\n * Gets the right stick of the virtual joystick.\n * @returns The virtual Joystick\n */\n getRightJoystick() {\n return this._rightjoystick;\n }\n /**\n * Update the current camera state depending on the inputs that have been used this frame.\n * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.\n */\n checkInputs() {\n if (this._leftjoystick) {\n const camera = this.camera;\n const speed = camera._computeLocalCameraSpeed() * 50;\n const cameraTransform = Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);\n const deltaTransform = Vector3.TransformCoordinates(new Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);\n camera.cameraDirection = camera.cameraDirection.add(deltaTransform);\n camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);\n if (!this._leftjoystick.pressed) {\n this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);\n }\n if (!this._rightjoystick.pressed) {\n this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);\n }\n }\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n */\n attachControl() {\n this._leftjoystick = new VirtualJoystick(true);\n this._leftjoystick.setAxisForUpDown(JoystickAxis.Z);\n this._leftjoystick.setAxisForLeftRight(JoystickAxis.X);\n this._leftjoystick.setJoystickSensibility(0.15);\n this._rightjoystick = new VirtualJoystick(false);\n this._rightjoystick.setAxisForUpDown(JoystickAxis.X);\n this._rightjoystick.setAxisForLeftRight(JoystickAxis.Y);\n this._rightjoystick.reverseUpDown = true;\n this._rightjoystick.setJoystickSensibility(0.05);\n this._rightjoystick.setJoystickColor(\"yellow\");\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n this._leftjoystick.releaseCanvas();\n this._rightjoystick.releaseCanvas();\n }\n /**\n * Gets the class name of the current input.\n * @returns the class name\n */\n getClassName() {\n return \"FreeCameraVirtualJoystickInput\";\n }\n /**\n * Get the friendly name associated with the input class.\n * @returns the input friendly name\n */\n getSimpleName() {\n return \"virtualJoystick\";\n }\n}\nCameraInputTypes[\"FreeCameraVirtualJoystickInput\"] = FreeCameraVirtualJoystickInput;\n//# sourceMappingURL=freeCameraVirtualJoystickInput.js.map","export * from \"./BaseCameraMouseWheelInput.js\";\nexport * from \"./BaseCameraPointersInput.js\";\nexport * from \"./arcRotateCameraGamepadInput.js\";\nexport * from \"./arcRotateCameraKeyboardMoveInput.js\";\nexport * from \"./arcRotateCameraMouseWheelInput.js\";\nexport * from \"./arcRotateCameraPointersInput.js\";\nexport * from \"./arcRotateCameraVRDeviceOrientationInput.js\";\nexport * from \"./flyCameraKeyboardInput.js\";\nexport * from \"./flyCameraMouseInput.js\";\nexport * from \"./followCameraKeyboardMoveInput.js\";\nexport * from \"./followCameraMouseWheelInput.js\";\nexport * from \"./followCameraPointersInput.js\";\nexport * from \"./freeCameraDeviceOrientationInput.js\";\nexport * from \"./freeCameraGamepadInput.js\";\nexport * from \"./freeCameraKeyboardMoveInput.js\";\nexport * from \"./freeCameraMouseInput.js\";\nexport * from \"./freeCameraMouseWheelInput.js\";\nexport * from \"./freeCameraTouchInput.js\";\nexport * from \"./freeCameraVirtualJoystickInput.js\";\n//# sourceMappingURL=index.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize, serializeAsVector3, serializeAsMeshReference } from \"../Misc/decorators.js\";\nimport { Camera } from \"./camera.js\";\nimport { Quaternion, Matrix, Vector3, Vector2, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Epsilon } from \"../Maths/math.constants.js\";\nimport { Axis } from \"../Maths/math.axis.js\";\n/**\n * A target camera takes a mesh or position as a target and continues to look at it while it moves.\n * This is the base of the follow, arc rotate cameras and Free camera\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras\n */\nexport class TargetCamera extends Camera {\n /**\n * Instantiates a target camera that takes a mesh or position as a target and continues to look at it while it moves.\n * This is the base of the follow, arc rotate cameras and Free camera\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras\n * @param name Defines the name of the camera in the scene\n * @param position Defines the start position of the camera in the scene\n * @param scene Defines the scene the camera belongs to\n * @param setActiveOnSceneIfNoneActive Defines whether the camera should be marked as active if not other active cameras have been defined\n */\n constructor(name, position, scene, setActiveOnSceneIfNoneActive = true) {\n super(name, position, scene, setActiveOnSceneIfNoneActive);\n this._tmpUpVector = Vector3.Zero();\n this._tmpTargetVector = Vector3.Zero();\n /**\n * Define the current direction the camera is moving to\n */\n this.cameraDirection = new Vector3(0, 0, 0);\n /**\n * Define the current rotation the camera is rotating to\n */\n this.cameraRotation = new Vector2(0, 0);\n /** Gets or sets a boolean indicating that the scaling of the parent hierarchy will not be taken in account by the camera */\n this.ignoreParentScaling = false;\n /**\n * When set, the up vector of the camera will be updated by the rotation of the camera\n */\n this.updateUpVectorFromRotation = false;\n this._tmpQuaternion = new Quaternion();\n /**\n * Define the current rotation of the camera\n */\n this.rotation = new Vector3(0, 0, 0);\n /**\n * Define the current speed of the camera\n */\n this.speed = 2.0;\n /**\n * Add constraint to the camera to prevent it to move freely in all directions and\n * around all axis.\n */\n this.noRotationConstraint = false;\n /**\n * Reverses mouselook direction to 'natural' panning as opposed to traditional direct\n * panning\n */\n this.invertRotation = false;\n /**\n * Speed multiplier for inverse camera panning\n */\n this.inverseRotationSpeed = 0.2;\n /**\n * Define the current target of the camera as an object or a position.\n * Please note that locking a target will disable panning.\n */\n this.lockedTarget = null;\n /** @internal */\n this._currentTarget = Vector3.Zero();\n /** @internal */\n this._initialFocalDistance = 1;\n /** @internal */\n this._viewMatrix = Matrix.Zero();\n /** @internal */\n this._camMatrix = Matrix.Zero();\n /** @internal */\n this._cameraTransformMatrix = Matrix.Zero();\n /** @internal */\n this._cameraRotationMatrix = Matrix.Zero();\n /** @internal */\n this._referencePoint = new Vector3(0, 0, 1);\n /** @internal */\n this._transformedReferencePoint = Vector3.Zero();\n this._defaultUp = Vector3.Up();\n this._cachedRotationZ = 0;\n this._cachedQuaternionRotationZ = 0;\n }\n /**\n * Gets the position in front of the camera at a given distance.\n * @param distance The distance from the camera we want the position to be\n * @returns the position\n */\n getFrontPosition(distance) {\n this.getWorldMatrix();\n const direction = this.getTarget().subtract(this.position);\n direction.normalize();\n direction.scaleInPlace(distance);\n return this.globalPosition.add(direction);\n }\n /** @internal */\n _getLockedTargetPosition() {\n if (!this.lockedTarget) {\n return null;\n }\n if (this.lockedTarget.absolutePosition) {\n const lockedTarget = this.lockedTarget;\n const m = lockedTarget.computeWorldMatrix();\n // in some cases the absolute position resets externally, but doesn't update since the matrix is cached.\n m.getTranslationToRef(lockedTarget.absolutePosition);\n }\n return this.lockedTarget.absolutePosition || this.lockedTarget;\n }\n /**\n * Store current camera state of the camera (fov, position, rotation, etc..)\n * @returns the camera\n */\n storeState() {\n this._storedPosition = this.position.clone();\n this._storedRotation = this.rotation.clone();\n if (this.rotationQuaternion) {\n this._storedRotationQuaternion = this.rotationQuaternion.clone();\n }\n return super.storeState();\n }\n /**\n * Restored camera state. You must call storeState() first\n * @returns whether it was successful or not\n * @internal\n */\n _restoreStateValues() {\n if (!super._restoreStateValues()) {\n return false;\n }\n this.position = this._storedPosition.clone();\n this.rotation = this._storedRotation.clone();\n if (this.rotationQuaternion) {\n this.rotationQuaternion = this._storedRotationQuaternion.clone();\n }\n this.cameraDirection.copyFromFloats(0, 0, 0);\n this.cameraRotation.copyFromFloats(0, 0);\n return true;\n }\n /** @internal */\n _initCache() {\n super._initCache();\n this._cache.lockedTarget = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._cache.rotation = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._cache.rotationQuaternion = new Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n }\n /**\n * @internal\n */\n _updateCache(ignoreParentClass) {\n if (!ignoreParentClass) {\n super._updateCache();\n }\n const lockedTargetPosition = this._getLockedTargetPosition();\n if (!lockedTargetPosition) {\n this._cache.lockedTarget = null;\n }\n else {\n if (!this._cache.lockedTarget) {\n this._cache.lockedTarget = lockedTargetPosition.clone();\n }\n else {\n this._cache.lockedTarget.copyFrom(lockedTargetPosition);\n }\n }\n this._cache.rotation.copyFrom(this.rotation);\n if (this.rotationQuaternion) {\n this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);\n }\n }\n // Synchronized\n /** @internal */\n _isSynchronizedViewMatrix() {\n if (!super._isSynchronizedViewMatrix()) {\n return false;\n }\n const lockedTargetPosition = this._getLockedTargetPosition();\n return ((this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) &&\n (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation)));\n }\n // Methods\n /** @internal */\n _computeLocalCameraSpeed() {\n const engine = this.getEngine();\n return this.speed * Math.sqrt(engine.getDeltaTime() / (engine.getFps() * 100.0));\n }\n // Target\n /**\n * Defines the target the camera should look at.\n * @param target Defines the new target as a Vector\n */\n setTarget(target) {\n this.upVector.normalize();\n this._initialFocalDistance = target.subtract(this.position).length();\n if (this.position.z === target.z) {\n this.position.z += Epsilon;\n }\n this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance);\n Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);\n this._camMatrix.invert();\n this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);\n const vDir = target.subtract(this.position);\n if (vDir.x >= 0.0) {\n this.rotation.y = -Math.atan(vDir.z / vDir.x) + Math.PI / 2.0;\n }\n else {\n this.rotation.y = -Math.atan(vDir.z / vDir.x) - Math.PI / 2.0;\n }\n this.rotation.z = 0;\n if (isNaN(this.rotation.x)) {\n this.rotation.x = 0;\n }\n if (isNaN(this.rotation.y)) {\n this.rotation.y = 0;\n }\n if (isNaN(this.rotation.z)) {\n this.rotation.z = 0;\n }\n if (this.rotationQuaternion) {\n Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);\n }\n }\n /**\n * Defines the target point of the camera.\n * The camera looks towards it form the radius distance.\n */\n get target() {\n return this.getTarget();\n }\n set target(value) {\n this.setTarget(value);\n }\n /**\n * Return the current target position of the camera. This value is expressed in local space.\n * @returns the target position\n */\n getTarget() {\n return this._currentTarget;\n }\n /** @internal */\n _decideIfNeedsToMove() {\n return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;\n }\n /** @internal */\n _updatePosition() {\n if (this.parent) {\n this.parent.getWorldMatrix().invertToRef(TmpVectors.Matrix[0]);\n Vector3.TransformNormalToRef(this.cameraDirection, TmpVectors.Matrix[0], TmpVectors.Vector3[0]);\n this.position.addInPlace(TmpVectors.Vector3[0]);\n return;\n }\n this.position.addInPlace(this.cameraDirection);\n }\n /** @internal */\n _checkInputs() {\n const directionMultiplier = this.invertRotation ? -this.inverseRotationSpeed : 1.0;\n const needToMove = this._decideIfNeedsToMove();\n const needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;\n // Move\n if (needToMove) {\n this._updatePosition();\n }\n // Rotate\n if (needToRotate) {\n //rotate, if quaternion is set and rotation was used\n if (this.rotationQuaternion) {\n this.rotationQuaternion.toEulerAnglesToRef(this.rotation);\n }\n this.rotation.x += this.cameraRotation.x * directionMultiplier;\n this.rotation.y += this.cameraRotation.y * directionMultiplier;\n // Apply constraints\n if (!this.noRotationConstraint) {\n const limit = 1.570796;\n if (this.rotation.x > limit) {\n this.rotation.x = limit;\n }\n if (this.rotation.x < -limit) {\n this.rotation.x = -limit;\n }\n }\n //rotate, if quaternion is set and rotation was used\n if (this.rotationQuaternion) {\n const len = this.rotation.lengthSquared();\n if (len) {\n Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);\n }\n }\n }\n // Inertia\n if (needToMove) {\n if (Math.abs(this.cameraDirection.x) < this.speed * Epsilon) {\n this.cameraDirection.x = 0;\n }\n if (Math.abs(this.cameraDirection.y) < this.speed * Epsilon) {\n this.cameraDirection.y = 0;\n }\n if (Math.abs(this.cameraDirection.z) < this.speed * Epsilon) {\n this.cameraDirection.z = 0;\n }\n this.cameraDirection.scaleInPlace(this.inertia);\n }\n if (needToRotate) {\n if (Math.abs(this.cameraRotation.x) < this.speed * Epsilon) {\n this.cameraRotation.x = 0;\n }\n if (Math.abs(this.cameraRotation.y) < this.speed * Epsilon) {\n this.cameraRotation.y = 0;\n }\n this.cameraRotation.scaleInPlace(this.inertia);\n }\n super._checkInputs();\n }\n _updateCameraRotationMatrix() {\n if (this.rotationQuaternion) {\n this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);\n }\n else {\n Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);\n }\n }\n /**\n * Update the up vector to apply the rotation of the camera (So if you changed the camera rotation.z this will let you update the up vector as well)\n * @returns the current camera\n */\n _rotateUpVectorWithCameraRotationMatrix() {\n Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);\n return this;\n }\n /** @internal */\n _getViewMatrix() {\n if (this.lockedTarget) {\n this.setTarget(this._getLockedTargetPosition());\n }\n // Compute\n this._updateCameraRotationMatrix();\n // Apply the changed rotation to the upVector\n if (this.rotationQuaternion && this._cachedQuaternionRotationZ != this.rotationQuaternion.z) {\n this._rotateUpVectorWithCameraRotationMatrix();\n this._cachedQuaternionRotationZ = this.rotationQuaternion.z;\n }\n else if (this._cachedRotationZ !== this.rotation.z) {\n this._rotateUpVectorWithCameraRotationMatrix();\n this._cachedRotationZ = this.rotation.z;\n }\n Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);\n // Computing target and final matrix\n this.position.addToRef(this._transformedReferencePoint, this._currentTarget);\n if (this.updateUpVectorFromRotation) {\n if (this.rotationQuaternion) {\n Axis.Y.rotateByQuaternionToRef(this.rotationQuaternion, this.upVector);\n }\n else {\n Quaternion.FromEulerVectorToRef(this.rotation, this._tmpQuaternion);\n Axis.Y.rotateByQuaternionToRef(this._tmpQuaternion, this.upVector);\n }\n }\n this._computeViewMatrix(this.position, this._currentTarget, this.upVector);\n return this._viewMatrix;\n }\n _computeViewMatrix(position, target, up) {\n if (this.ignoreParentScaling) {\n if (this.parent) {\n const parentWorldMatrix = this.parent.getWorldMatrix();\n Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);\n Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._tmpTargetVector);\n Vector3.TransformNormalToRef(up, parentWorldMatrix, this._tmpUpVector);\n this._markSyncedWithParent();\n }\n else {\n this._globalPosition.copyFrom(position);\n this._tmpTargetVector.copyFrom(target);\n this._tmpUpVector.copyFrom(up);\n }\n if (this.getScene().useRightHandedSystem) {\n Matrix.LookAtRHToRef(this._globalPosition, this._tmpTargetVector, this._tmpUpVector, this._viewMatrix);\n }\n else {\n Matrix.LookAtLHToRef(this._globalPosition, this._tmpTargetVector, this._tmpUpVector, this._viewMatrix);\n }\n return;\n }\n if (this.getScene().useRightHandedSystem) {\n Matrix.LookAtRHToRef(position, target, up, this._viewMatrix);\n }\n else {\n Matrix.LookAtLHToRef(position, target, up, this._viewMatrix);\n }\n if (this.parent) {\n const parentWorldMatrix = this.parent.getWorldMatrix();\n this._viewMatrix.invert();\n this._viewMatrix.multiplyToRef(parentWorldMatrix, this._viewMatrix);\n this._viewMatrix.getTranslationToRef(this._globalPosition);\n this._viewMatrix.invert();\n this._markSyncedWithParent();\n }\n else {\n this._globalPosition.copyFrom(position);\n }\n }\n /**\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n createRigCamera(name, cameraIndex) {\n if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {\n const rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());\n rigCamera.isRigCamera = true;\n rigCamera.rigParent = this;\n if (this.cameraRigMode === Camera.RIG_MODE_VR || this.cameraRigMode === Camera.RIG_MODE_WEBVR) {\n if (!this.rotationQuaternion) {\n this.rotationQuaternion = new Quaternion();\n }\n rigCamera._cameraRigParams = {};\n rigCamera.rotationQuaternion = new Quaternion();\n }\n rigCamera.mode = this.mode;\n rigCamera.orthoLeft = this.orthoLeft;\n rigCamera.orthoRight = this.orthoRight;\n rigCamera.orthoTop = this.orthoTop;\n rigCamera.orthoBottom = this.orthoBottom;\n return rigCamera;\n }\n return null;\n }\n /**\n * @internal\n */\n _updateRigCameras() {\n const camLeft = this._rigCameras[0];\n const camRight = this._rigCameras[1];\n this.computeWorldMatrix();\n switch (this.cameraRigMode) {\n case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:\n case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:\n case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:\n case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:\n case Camera.RIG_MODE_STEREOSCOPIC_INTERLACED: {\n //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:\n const leftSign = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED ? 1 : -1;\n const rightSign = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED ? -1 : 1;\n this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft);\n this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle * rightSign, camRight);\n break;\n }\n case Camera.RIG_MODE_VR:\n if (camLeft.rotationQuaternion) {\n camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);\n camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);\n }\n else {\n camLeft.rotation.copyFrom(this.rotation);\n camRight.rotation.copyFrom(this.rotation);\n }\n camLeft.position.copyFrom(this.position);\n camRight.position.copyFrom(this.position);\n break;\n }\n super._updateRigCameras();\n }\n _getRigCamPositionAndTarget(halfSpace, rigCamera) {\n const target = this.getTarget();\n target.subtractToRef(this.position, TargetCamera._TargetFocalPoint);\n TargetCamera._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance);\n const newFocalTarget = TargetCamera._TargetFocalPoint.addInPlace(this.position);\n Matrix.TranslationToRef(-newFocalTarget.x, -newFocalTarget.y, -newFocalTarget.z, TargetCamera._TargetTransformMatrix);\n TargetCamera._TargetTransformMatrix.multiplyToRef(Matrix.RotationAxis(rigCamera.upVector, halfSpace), TargetCamera._RigCamTransformMatrix);\n Matrix.TranslationToRef(newFocalTarget.x, newFocalTarget.y, newFocalTarget.z, TargetCamera._TargetTransformMatrix);\n TargetCamera._RigCamTransformMatrix.multiplyToRef(TargetCamera._TargetTransformMatrix, TargetCamera._RigCamTransformMatrix);\n Vector3.TransformCoordinatesToRef(this.position, TargetCamera._RigCamTransformMatrix, rigCamera.position);\n rigCamera.setTarget(newFocalTarget);\n }\n /**\n * Gets the current object class name.\n * @returns the class name\n */\n getClassName() {\n return \"TargetCamera\";\n }\n}\nTargetCamera._RigCamTransformMatrix = new Matrix();\nTargetCamera._TargetTransformMatrix = new Matrix();\nTargetCamera._TargetFocalPoint = new Vector3();\n__decorate([\n serializeAsVector3()\n], TargetCamera.prototype, \"rotation\", void 0);\n__decorate([\n serialize()\n], TargetCamera.prototype, \"speed\", void 0);\n__decorate([\n serializeAsMeshReference(\"lockedTargetId\")\n], TargetCamera.prototype, \"lockedTarget\", void 0);\n//# sourceMappingURL=targetCamera.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serializeAsVector3, serialize } from \"../Misc/decorators.js\";\nimport { Vector3, Vector2 } from \"../Maths/math.vector.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { TargetCamera } from \"./targetCamera.js\";\nimport { FreeCameraInputsManager } from \"./freeCameraInputsManager.js\";\nimport { Tools } from \"../Misc/tools.js\";\n/**\n * This represents a free type of camera. It can be useful in First Person Shooter game for instance.\n * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera\n */\nexport class FreeCamera extends TargetCamera {\n /**\n * Gets the input sensibility for a mouse input. (default is 2000.0)\n * Higher values reduce sensitivity.\n */\n get angularSensibility() {\n const mouse = this.inputs.attached[\"mouse\"];\n if (mouse) {\n return mouse.angularSensibility;\n }\n return 0;\n }\n /**\n * Sets the input sensibility for a mouse input. (default is 2000.0)\n * Higher values reduce sensitivity.\n */\n set angularSensibility(value) {\n const mouse = this.inputs.attached[\"mouse\"];\n if (mouse) {\n mouse.angularSensibility = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control the forward move of the camera.\n */\n get keysUp() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysUp;\n }\n return [];\n }\n set keysUp(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysUp = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control the upward move of the camera.\n */\n get keysUpward() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysUpward;\n }\n return [];\n }\n set keysUpward(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysUpward = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control the backward move of the camera.\n */\n get keysDown() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysDown;\n }\n return [];\n }\n set keysDown(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysDown = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control the downward move of the camera.\n */\n get keysDownward() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysDownward;\n }\n return [];\n }\n set keysDownward(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysDownward = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.\n */\n get keysLeft() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysLeft;\n }\n return [];\n }\n set keysLeft(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysLeft = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.\n */\n get keysRight() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysRight;\n }\n return [];\n }\n set keysRight(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysRight = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control the left rotation move of the camera.\n */\n get keysRotateLeft() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysRotateLeft;\n }\n return [];\n }\n set keysRotateLeft(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysRotateLeft = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control the right rotation move of the camera.\n */\n get keysRotateRight() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysRotateRight;\n }\n return [];\n }\n set keysRotateRight(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysRotateRight = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control the up rotation move of the camera.\n */\n get keysRotateUp() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysRotateUp;\n }\n return [];\n }\n set keysRotateUp(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysRotateUp = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control the down rotation move of the camera.\n */\n get keysRotateDown() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysRotateDown;\n }\n return [];\n }\n set keysRotateDown(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysRotateDown = value;\n }\n }\n /**\n * Instantiates a Free Camera.\n * This represents a free type of camera. It can be useful in First Person Shooter game for instance.\n * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera\n * @param name Define the name of the camera in the scene\n * @param position Define the start position of the camera in the scene\n * @param scene Define the scene the camera belongs to\n * @param setActiveOnSceneIfNoneActive Defines whether the camera should be marked as active if not other active cameras have been defined\n */\n constructor(name, position, scene, setActiveOnSceneIfNoneActive = true) {\n super(name, position, scene, setActiveOnSceneIfNoneActive);\n /**\n * Define the collision ellipsoid of the camera.\n * This is helpful to simulate a camera body like the player body around the camera\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions#arcrotatecamera\n */\n this.ellipsoid = new Vector3(0.5, 1, 0.5);\n /**\n * Define an offset for the position of the ellipsoid around the camera.\n * This can be helpful to determine the center of the body near the gravity center of the body\n * instead of its head.\n */\n this.ellipsoidOffset = new Vector3(0, 0, 0);\n /**\n * Enable or disable collisions of the camera with the rest of the scene objects.\n */\n this.checkCollisions = false;\n /**\n * Enable or disable gravity on the camera.\n */\n this.applyGravity = false;\n this._needMoveForGravity = false;\n this._oldPosition = Vector3.Zero();\n this._diffPosition = Vector3.Zero();\n this._newPosition = Vector3.Zero();\n // Collisions\n this._collisionMask = -1;\n this._onCollisionPositionChange = (collisionId, newPosition, collidedMesh = null) => {\n const updatePosition = (newPos) => {\n this._newPosition.copyFrom(newPos);\n this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);\n if (this._diffPosition.length() > Engine.CollisionsEpsilon) {\n this.position.addInPlace(this._diffPosition);\n if (this.onCollide && collidedMesh) {\n this.onCollide(collidedMesh);\n }\n }\n };\n updatePosition(newPosition);\n };\n this.inputs = new FreeCameraInputsManager(this);\n this.inputs.addKeyboard().addMouse();\n }\n /**\n * Attached controls to the current camera.\n * @param ignored defines an ignored parameter kept for backward compatibility.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(ignored, noPreventDefault) {\n // eslint-disable-next-line prefer-rest-params\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n this.inputs.attachElement(noPreventDefault);\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n this.inputs.detachElement();\n this.cameraDirection = new Vector3(0, 0, 0);\n this.cameraRotation = new Vector2(0, 0);\n }\n /**\n * Define a collision mask to limit the list of object the camera can collide with\n */\n get collisionMask() {\n return this._collisionMask;\n }\n set collisionMask(mask) {\n this._collisionMask = !isNaN(mask) ? mask : -1;\n }\n /**\n * @internal\n */\n _collideWithWorld(displacement) {\n let globalPosition;\n if (this.parent) {\n globalPosition = Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());\n }\n else {\n globalPosition = this.position;\n }\n globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);\n this._oldPosition.addInPlace(this.ellipsoidOffset);\n const coordinator = this.getScene().collisionCoordinator;\n if (!this._collider) {\n this._collider = coordinator.createCollider();\n }\n this._collider._radius = this.ellipsoid;\n this._collider.collisionMask = this._collisionMask;\n //no need for clone, as long as gravity is not on.\n let actualDisplacement = displacement;\n //add gravity to the direction to prevent the dual-collision checking\n if (this.applyGravity) {\n //this prevents mending with cameraDirection, a global variable of the free camera class.\n actualDisplacement = displacement.add(this.getScene().gravity);\n }\n coordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);\n }\n /** @internal */\n _checkInputs() {\n if (!this._localDirection) {\n this._localDirection = Vector3.Zero();\n this._transformedDirection = Vector3.Zero();\n }\n this.inputs.checkInputs();\n super._checkInputs();\n }\n /**\n * Enable movement without a user input. This allows gravity to always be applied.\n */\n set needMoveForGravity(value) {\n this._needMoveForGravity = value;\n }\n /**\n * When true, gravity is applied whether there is user input or not.\n */\n get needMoveForGravity() {\n return this._needMoveForGravity;\n }\n /** @internal */\n _decideIfNeedsToMove() {\n return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;\n }\n /** @internal */\n _updatePosition() {\n if (this.checkCollisions && this.getScene().collisionsEnabled) {\n this._collideWithWorld(this.cameraDirection);\n }\n else {\n super._updatePosition();\n }\n }\n /**\n * Destroy the camera and release the current resources hold by it.\n */\n dispose() {\n this.inputs.clear();\n super.dispose();\n }\n /**\n * Gets the current object class name.\n * @returns the class name\n */\n getClassName() {\n return \"FreeCamera\";\n }\n}\n__decorate([\n serializeAsVector3()\n], FreeCamera.prototype, \"ellipsoid\", void 0);\n__decorate([\n serializeAsVector3()\n], FreeCamera.prototype, \"ellipsoidOffset\", void 0);\n__decorate([\n serialize()\n], FreeCamera.prototype, \"checkCollisions\", void 0);\n__decorate([\n serialize()\n], FreeCamera.prototype, \"applyGravity\", void 0);\n//# sourceMappingURL=freeCamera.js.map","import { FreeCamera } from \"./freeCamera.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Node } from \"../node.js\";\nNode.AddNodeConstructor(\"TouchCamera\", (name, scene) => {\n return () => new TouchCamera(name, Vector3.Zero(), scene);\n});\n/**\n * This represents a FPS type of camera controlled by touch.\n * This is like a universal camera minus the Gamepad controls.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera\n */\nexport class TouchCamera extends FreeCamera {\n /**\n * Defines the touch sensibility for rotation.\n * The higher the faster.\n */\n get touchAngularSensibility() {\n const touch = this.inputs.attached[\"touch\"];\n if (touch) {\n return touch.touchAngularSensibility;\n }\n return 0;\n }\n set touchAngularSensibility(value) {\n const touch = this.inputs.attached[\"touch\"];\n if (touch) {\n touch.touchAngularSensibility = value;\n }\n }\n /**\n * Defines the touch sensibility for move.\n * The higher the faster.\n */\n get touchMoveSensibility() {\n const touch = this.inputs.attached[\"touch\"];\n if (touch) {\n return touch.touchMoveSensibility;\n }\n return 0;\n }\n set touchMoveSensibility(value) {\n const touch = this.inputs.attached[\"touch\"];\n if (touch) {\n touch.touchMoveSensibility = value;\n }\n }\n /**\n * Instantiates a new touch camera.\n * This represents a FPS type of camera controlled by touch.\n * This is like a universal camera minus the Gamepad controls.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera\n * @param name Define the name of the camera in the scene\n * @param position Define the start position of the camera in the scene\n * @param scene Define the scene the camera belongs to\n */\n constructor(name, position, scene) {\n super(name, position, scene);\n this.inputs.addTouch();\n this._setupInputs();\n }\n /**\n * Gets the current object class name.\n * @returns the class name\n */\n getClassName() {\n return \"TouchCamera\";\n }\n /** @internal */\n _setupInputs() {\n const touch = this.inputs.attached[\"touch\"];\n const mouse = this.inputs.attached[\"mouse\"];\n if (mouse) {\n mouse.touchEnabled = false;\n }\n else {\n touch.allowMouse = true;\n }\n }\n}\n//# sourceMappingURL=touchCamera.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize, serializeAsVector3, serializeAsMeshReference, serializeAsVector2 } from \"../Misc/decorators.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Matrix, Vector3, Vector2 } from \"../Maths/math.vector.js\";\nimport { Node } from \"../node.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { AutoRotationBehavior } from \"../Behaviors/Cameras/autoRotationBehavior.js\";\nimport { BouncingBehavior } from \"../Behaviors/Cameras/bouncingBehavior.js\";\nimport { FramingBehavior } from \"../Behaviors/Cameras/framingBehavior.js\";\nimport { Camera } from \"./camera.js\";\nimport { TargetCamera } from \"./targetCamera.js\";\nimport { ArcRotateCameraInputsManager } from \"../Cameras/arcRotateCameraInputsManager.js\";\nimport { Epsilon } from \"../Maths/math.constants.js\";\nimport { Tools } from \"../Misc/tools.js\";\nNode.AddNodeConstructor(\"ArcRotateCamera\", (name, scene) => {\n return () => new ArcRotateCamera(name, 0, 0, 1.0, Vector3.Zero(), scene);\n});\n/**\n * This represents an orbital type of camera.\n *\n * This camera always points towards a given target position and can be rotated around that target with the target as the centre of rotation. It can be controlled with cursors and mouse, or with touch events.\n * Think of this camera as one orbiting its target position, or more imaginatively as a spy satellite orbiting the earth. Its position relative to the target (earth) can be set by three parameters, alpha (radians) the longitudinal rotation, beta (radians) the latitudinal rotation and radius the distance from the target position.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#arc-rotate-camera\n */\nexport class ArcRotateCamera extends TargetCamera {\n /**\n * Defines the target point of the camera.\n * The camera looks towards it from the radius distance.\n */\n get target() {\n return this._target;\n }\n set target(value) {\n this.setTarget(value);\n }\n /**\n * Defines the target mesh of the camera.\n * The camera looks towards it from the radius distance.\n * Please note that setting a target host will disable panning.\n */\n get targetHost() {\n return this._targetHost;\n }\n set targetHost(value) {\n if (value) {\n this.setTarget(value);\n }\n }\n /**\n * Return the current target position of the camera. This value is expressed in local space.\n * @returns the target position\n */\n getTarget() {\n return this.target;\n }\n /**\n * Define the current local position of the camera in the scene\n */\n get position() {\n return this._position;\n }\n set position(newPosition) {\n this.setPosition(newPosition);\n }\n /**\n * The vector the camera should consider as up. (default is Vector3(0, 1, 0) as returned by Vector3.Up())\n * Setting this will copy the given vector to the camera's upVector, and set rotation matrices to and from Y up.\n * DO NOT set the up vector using copyFrom or copyFromFloats, as this bypasses setting the above matrices.\n */\n set upVector(vec) {\n if (!this._upToYMatrix) {\n this._yToUpMatrix = new Matrix();\n this._upToYMatrix = new Matrix();\n this._upVector = Vector3.Zero();\n }\n vec.normalize();\n this._upVector.copyFrom(vec);\n this.setMatUp();\n }\n get upVector() {\n return this._upVector;\n }\n /**\n * Sets the Y-up to camera up-vector rotation matrix, and the up-vector to Y-up rotation matrix.\n */\n setMatUp() {\n // from y-up to custom-up (used in _getViewMatrix)\n Matrix.RotationAlignToRef(Vector3.UpReadOnly, this._upVector, this._yToUpMatrix);\n // from custom-up to y-up (used in rebuildAnglesAndRadius)\n Matrix.RotationAlignToRef(this._upVector, Vector3.UpReadOnly, this._upToYMatrix);\n }\n //-- begin properties for backward compatibility for inputs\n /**\n * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.\n */\n get angularSensibilityX() {\n const pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n return pointers.angularSensibilityX;\n }\n return 0;\n }\n set angularSensibilityX(value) {\n const pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n pointers.angularSensibilityX = value;\n }\n }\n /**\n * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.\n */\n get angularSensibilityY() {\n const pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n return pointers.angularSensibilityY;\n }\n return 0;\n }\n set angularSensibilityY(value) {\n const pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n pointers.angularSensibilityY = value;\n }\n }\n /**\n * Gets or Set the pointer pinch precision or how fast is the camera zooming.\n */\n get pinchPrecision() {\n const pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n return pointers.pinchPrecision;\n }\n return 0;\n }\n set pinchPrecision(value) {\n const pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n pointers.pinchPrecision = value;\n }\n }\n /**\n * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.\n * It will be used instead of pinchDeltaPrecision if different from 0.\n * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.\n */\n get pinchDeltaPercentage() {\n const pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n return pointers.pinchDeltaPercentage;\n }\n return 0;\n }\n set pinchDeltaPercentage(value) {\n const pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n pointers.pinchDeltaPercentage = value;\n }\n }\n /**\n * Gets or Set the pointer use natural pinch zoom to override the pinch precision\n * and pinch delta percentage.\n * When useNaturalPinchZoom is true, multi touch zoom will zoom in such\n * that any object in the plane at the camera's target point will scale\n * perfectly with finger motion.\n */\n get useNaturalPinchZoom() {\n const pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n return pointers.useNaturalPinchZoom;\n }\n return false;\n }\n set useNaturalPinchZoom(value) {\n const pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n pointers.useNaturalPinchZoom = value;\n }\n }\n /**\n * Gets or Set the pointer panning sensibility or how fast is the camera moving.\n */\n get panningSensibility() {\n const pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n return pointers.panningSensibility;\n }\n return 0;\n }\n set panningSensibility(value) {\n const pointers = this.inputs.attached[\"pointers\"];\n if (pointers) {\n pointers.panningSensibility = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.\n */\n get keysUp() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysUp;\n }\n return [];\n }\n set keysUp(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysUp = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.\n */\n get keysDown() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysDown;\n }\n return [];\n }\n set keysDown(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysDown = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.\n */\n get keysLeft() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysLeft;\n }\n return [];\n }\n set keysLeft(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysLeft = value;\n }\n }\n /**\n * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.\n */\n get keysRight() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysRight;\n }\n return [];\n }\n set keysRight(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysRight = value;\n }\n }\n /**\n * Gets or Set the mouse wheel precision or how fast is the camera zooming.\n */\n get wheelPrecision() {\n const mousewheel = this.inputs.attached[\"mousewheel\"];\n if (mousewheel) {\n return mousewheel.wheelPrecision;\n }\n return 0;\n }\n set wheelPrecision(value) {\n const mousewheel = this.inputs.attached[\"mousewheel\"];\n if (mousewheel) {\n mousewheel.wheelPrecision = value;\n }\n }\n /**\n * Gets or Set the boolean value that controls whether or not the mouse wheel\n * zooms to the location of the mouse pointer or not. The default is false.\n */\n get zoomToMouseLocation() {\n const mousewheel = this.inputs.attached[\"mousewheel\"];\n if (mousewheel) {\n return mousewheel.zoomToMouseLocation;\n }\n return false;\n }\n set zoomToMouseLocation(value) {\n const mousewheel = this.inputs.attached[\"mousewheel\"];\n if (mousewheel) {\n mousewheel.zoomToMouseLocation = value;\n }\n }\n /**\n * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.\n * It will be used instead of pinchDeltaPrecision if different from 0.\n * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.\n */\n get wheelDeltaPercentage() {\n const mousewheel = this.inputs.attached[\"mousewheel\"];\n if (mousewheel) {\n return mousewheel.wheelDeltaPercentage;\n }\n return 0;\n }\n set wheelDeltaPercentage(value) {\n const mousewheel = this.inputs.attached[\"mousewheel\"];\n if (mousewheel) {\n mousewheel.wheelDeltaPercentage = value;\n }\n }\n /**\n * Gets the bouncing behavior of the camera if it has been enabled.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#bouncing-behavior\n */\n get bouncingBehavior() {\n return this._bouncingBehavior;\n }\n /**\n * Defines if the bouncing behavior of the camera is enabled on the camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#bouncing-behavior\n */\n get useBouncingBehavior() {\n return this._bouncingBehavior != null;\n }\n set useBouncingBehavior(value) {\n if (value === this.useBouncingBehavior) {\n return;\n }\n if (value) {\n this._bouncingBehavior = new BouncingBehavior();\n this.addBehavior(this._bouncingBehavior);\n }\n else if (this._bouncingBehavior) {\n this.removeBehavior(this._bouncingBehavior);\n this._bouncingBehavior = null;\n }\n }\n /**\n * Gets the framing behavior of the camera if it has been enabled.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#framing-behavior\n */\n get framingBehavior() {\n return this._framingBehavior;\n }\n /**\n * Defines if the framing behavior of the camera is enabled on the camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#framing-behavior\n */\n get useFramingBehavior() {\n return this._framingBehavior != null;\n }\n set useFramingBehavior(value) {\n if (value === this.useFramingBehavior) {\n return;\n }\n if (value) {\n this._framingBehavior = new FramingBehavior();\n this.addBehavior(this._framingBehavior);\n }\n else if (this._framingBehavior) {\n this.removeBehavior(this._framingBehavior);\n this._framingBehavior = null;\n }\n }\n /**\n * Gets the auto rotation behavior of the camera if it has been enabled.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#autorotation-behavior\n */\n get autoRotationBehavior() {\n return this._autoRotationBehavior;\n }\n /**\n * Defines if the auto rotation behavior of the camera is enabled on the camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors/cameraBehaviors#autorotation-behavior\n */\n get useAutoRotationBehavior() {\n return this._autoRotationBehavior != null;\n }\n set useAutoRotationBehavior(value) {\n if (value === this.useAutoRotationBehavior) {\n return;\n }\n if (value) {\n this._autoRotationBehavior = new AutoRotationBehavior();\n this.addBehavior(this._autoRotationBehavior);\n }\n else if (this._autoRotationBehavior) {\n this.removeBehavior(this._autoRotationBehavior);\n this._autoRotationBehavior = null;\n }\n }\n /**\n * Instantiates a new ArcRotateCamera in a given scene\n * @param name Defines the name of the camera\n * @param alpha Defines the camera rotation along the longitudinal axis\n * @param beta Defines the camera rotation along the latitudinal axis\n * @param radius Defines the camera distance from its target\n * @param target Defines the camera target\n * @param scene Defines the scene the camera belongs to\n * @param setActiveOnSceneIfNoneActive Defines whether the camera should be marked as active if not other active cameras have been defined\n */\n constructor(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive = true) {\n super(name, Vector3.Zero(), scene, setActiveOnSceneIfNoneActive);\n /**\n * Current inertia value on the longitudinal axis.\n * The bigger this number the longer it will take for the camera to stop.\n */\n this.inertialAlphaOffset = 0;\n /**\n * Current inertia value on the latitudinal axis.\n * The bigger this number the longer it will take for the camera to stop.\n */\n this.inertialBetaOffset = 0;\n /**\n * Current inertia value on the radius axis.\n * The bigger this number the longer it will take for the camera to stop.\n */\n this.inertialRadiusOffset = 0;\n /**\n * Minimum allowed angle on the longitudinal axis.\n * This can help limiting how the Camera is able to move in the scene.\n */\n this.lowerAlphaLimit = null;\n /**\n * Maximum allowed angle on the longitudinal axis.\n * This can help limiting how the Camera is able to move in the scene.\n */\n this.upperAlphaLimit = null;\n /**\n * Minimum allowed angle on the latitudinal axis.\n * This can help limiting how the Camera is able to move in the scene.\n */\n this.lowerBetaLimit = 0.01;\n /**\n * Maximum allowed angle on the latitudinal axis.\n * This can help limiting how the Camera is able to move in the scene.\n */\n this.upperBetaLimit = Math.PI - 0.01;\n /**\n * Minimum allowed distance of the camera to the target (The camera can not get closer).\n * This can help limiting how the Camera is able to move in the scene.\n */\n this.lowerRadiusLimit = null;\n /**\n * Maximum allowed distance of the camera to the target (The camera can not get further).\n * This can help limiting how the Camera is able to move in the scene.\n */\n this.upperRadiusLimit = null;\n /**\n * Defines the current inertia value used during panning of the camera along the X axis.\n */\n this.inertialPanningX = 0;\n /**\n * Defines the current inertia value used during panning of the camera along the Y axis.\n */\n this.inertialPanningY = 0;\n /**\n * Defines the distance used to consider the camera in pan mode vs pinch/zoom.\n * Basically if your fingers moves away from more than this distance you will be considered\n * in pinch mode.\n */\n this.pinchToPanMaxDistance = 20;\n /**\n * Defines the maximum distance the camera can pan.\n * This could help keeping the camera always in your scene.\n */\n this.panningDistanceLimit = null;\n /**\n * Defines the target of the camera before panning.\n */\n this.panningOriginTarget = Vector3.Zero();\n /**\n * Defines the value of the inertia used during panning.\n * 0 would mean stop inertia and one would mean no deceleration at all.\n */\n this.panningInertia = 0.9;\n //-- end properties for backward compatibility for inputs\n /**\n * Defines how much the radius should be scaled while zooming on a particular mesh (through the zoomOn function)\n */\n this.zoomOnFactor = 1;\n /**\n * Defines a screen offset for the camera position.\n */\n this.targetScreenOffset = Vector2.Zero();\n /**\n * Allows the camera to be completely reversed.\n * If false the camera can not arrive upside down.\n */\n this.allowUpsideDown = true;\n /**\n * Define if double tap/click is used to restore the previously saved state of the camera.\n */\n this.useInputToRestoreState = true;\n /** @internal */\n this._viewMatrix = new Matrix();\n /**\n * Defines the allowed panning axis.\n */\n this.panningAxis = new Vector3(1, 1, 0);\n this._transformedDirection = new Vector3();\n /**\n * Defines if camera will eliminate transform on y axis.\n */\n this.mapPanning = false;\n /**\n * Observable triggered when the mesh target has been changed on the camera.\n */\n this.onMeshTargetChangedObservable = new Observable();\n /**\n * Defines whether the camera should check collision with the objects oh the scene.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions#how-can-i-do-this-\n */\n this.checkCollisions = false;\n /**\n * Defines the collision radius of the camera.\n * This simulates a sphere around the camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions#arcrotatecamera\n */\n this.collisionRadius = new Vector3(0.5, 0.5, 0.5);\n this._previousPosition = Vector3.Zero();\n this._collisionVelocity = Vector3.Zero();\n this._newPosition = Vector3.Zero();\n this._computationVector = Vector3.Zero();\n this._onCollisionPositionChange = (collisionId, newPosition, collidedMesh = null) => {\n if (!collidedMesh) {\n this._previousPosition.copyFrom(this._position);\n }\n else {\n this.setPosition(newPosition);\n if (this.onCollide) {\n this.onCollide(collidedMesh);\n }\n }\n // Recompute because of constraints\n const cosa = Math.cos(this.alpha);\n const sina = Math.sin(this.alpha);\n const cosb = Math.cos(this.beta);\n let sinb = Math.sin(this.beta);\n if (sinb === 0) {\n sinb = 0.0001;\n }\n const target = this._getTargetPosition();\n this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);\n target.addToRef(this._computationVector, this._newPosition);\n this._position.copyFrom(this._newPosition);\n let up = this.upVector;\n if (this.allowUpsideDown && this.beta < 0) {\n up = up.clone();\n up = up.negate();\n }\n this._computeViewMatrix(this._position, target, up);\n this._viewMatrix.addAtIndex(12, this.targetScreenOffset.x);\n this._viewMatrix.addAtIndex(13, this.targetScreenOffset.y);\n this._collisionTriggered = false;\n };\n this._target = Vector3.Zero();\n if (target) {\n this.setTarget(target);\n }\n this.alpha = alpha;\n this.beta = beta;\n this.radius = radius;\n this.getViewMatrix();\n this.inputs = new ArcRotateCameraInputsManager(this);\n this.inputs.addKeyboard().addMouseWheel().addPointers();\n }\n // Cache\n /** @internal */\n _initCache() {\n super._initCache();\n this._cache._target = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._cache.alpha = undefined;\n this._cache.beta = undefined;\n this._cache.radius = undefined;\n this._cache.targetScreenOffset = Vector2.Zero();\n }\n /**\n * @internal\n */\n _updateCache(ignoreParentClass) {\n if (!ignoreParentClass) {\n super._updateCache();\n }\n this._cache._target.copyFrom(this._getTargetPosition());\n this._cache.alpha = this.alpha;\n this._cache.beta = this.beta;\n this._cache.radius = this.radius;\n this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);\n }\n _getTargetPosition() {\n if (this._targetHost && this._targetHost.getAbsolutePosition) {\n const pos = this._targetHost.getAbsolutePosition();\n if (this._targetBoundingCenter) {\n pos.addToRef(this._targetBoundingCenter, this._target);\n }\n else {\n this._target.copyFrom(pos);\n }\n }\n const lockedTargetPosition = this._getLockedTargetPosition();\n if (lockedTargetPosition) {\n return lockedTargetPosition;\n }\n return this._target;\n }\n /**\n * Stores the current state of the camera (alpha, beta, radius and target)\n * @returns the camera itself\n */\n storeState() {\n this._storedAlpha = this.alpha;\n this._storedBeta = this.beta;\n this._storedRadius = this.radius;\n this._storedTarget = this._getTargetPosition().clone();\n this._storedTargetScreenOffset = this.targetScreenOffset.clone();\n return super.storeState();\n }\n /**\n * @internal\n * Restored camera state. You must call storeState() first\n */\n _restoreStateValues() {\n if (!super._restoreStateValues()) {\n return false;\n }\n this.setTarget(this._storedTarget.clone());\n this.alpha = this._storedAlpha;\n this.beta = this._storedBeta;\n this.radius = this._storedRadius;\n this.targetScreenOffset = this._storedTargetScreenOffset.clone();\n this.inertialAlphaOffset = 0;\n this.inertialBetaOffset = 0;\n this.inertialRadiusOffset = 0;\n this.inertialPanningX = 0;\n this.inertialPanningY = 0;\n return true;\n }\n // Synchronized\n /** @internal */\n _isSynchronizedViewMatrix() {\n if (!super._isSynchronizedViewMatrix()) {\n return false;\n }\n return (this._cache._target.equals(this._getTargetPosition()) &&\n this._cache.alpha === this.alpha &&\n this._cache.beta === this.beta &&\n this._cache.radius === this.radius &&\n this._cache.targetScreenOffset.equals(this.targetScreenOffset));\n }\n /**\n * Attached controls to the current camera.\n * @param ignored defines an ignored parameter kept for backward compatibility.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n * @param useCtrlForPanning Defines whether ctrl is used for panning within the controls\n * @param panningMouseButton Defines whether panning is allowed through mouse click button\n */\n attachControl(ignored, noPreventDefault, useCtrlForPanning = true, panningMouseButton = 2) {\n // eslint-disable-next-line prefer-rest-params\n const args = arguments;\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(args);\n this._useCtrlForPanning = useCtrlForPanning;\n this._panningMouseButton = panningMouseButton;\n // backwards compatibility\n if (typeof args[0] === \"boolean\") {\n if (args.length > 1) {\n this._useCtrlForPanning = args[1];\n }\n if (args.length > 2) {\n this._panningMouseButton = args[2];\n }\n }\n this.inputs.attachElement(noPreventDefault);\n this._reset = () => {\n this.inertialAlphaOffset = 0;\n this.inertialBetaOffset = 0;\n this.inertialRadiusOffset = 0;\n this.inertialPanningX = 0;\n this.inertialPanningY = 0;\n };\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n this.inputs.detachElement();\n if (this._reset) {\n this._reset();\n }\n }\n /** @internal */\n _checkInputs() {\n //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.\n if (this._collisionTriggered) {\n return;\n }\n this.inputs.checkInputs();\n // Inertia\n if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {\n const directionModifier = this.invertRotation ? -1 : 1;\n let inertialAlphaOffset = this.inertialAlphaOffset;\n if (this.beta <= 0) {\n inertialAlphaOffset *= -1;\n }\n if (this.getScene().useRightHandedSystem) {\n inertialAlphaOffset *= -1;\n }\n if (this.parent && this.parent._getWorldMatrixDeterminant() < 0) {\n inertialAlphaOffset *= -1;\n }\n this.alpha += inertialAlphaOffset * directionModifier;\n this.beta += this.inertialBetaOffset * directionModifier;\n this.radius -= this.inertialRadiusOffset;\n this.inertialAlphaOffset *= this.inertia;\n this.inertialBetaOffset *= this.inertia;\n this.inertialRadiusOffset *= this.inertia;\n if (Math.abs(this.inertialAlphaOffset) < Epsilon) {\n this.inertialAlphaOffset = 0;\n }\n if (Math.abs(this.inertialBetaOffset) < Epsilon) {\n this.inertialBetaOffset = 0;\n }\n if (Math.abs(this.inertialRadiusOffset) < this.speed * Epsilon) {\n this.inertialRadiusOffset = 0;\n }\n }\n // Panning inertia\n if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {\n const localDirection = new Vector3(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);\n this._viewMatrix.invertToRef(this._cameraTransformMatrix);\n localDirection.multiplyInPlace(this.panningAxis);\n Vector3.TransformNormalToRef(localDirection, this._cameraTransformMatrix, this._transformedDirection);\n // Eliminate y if mapPanning is enabled\n if (this.mapPanning || !this.panningAxis.y) {\n this._transformedDirection.y = 0;\n }\n if (!this._targetHost) {\n if (this.panningDistanceLimit) {\n this._transformedDirection.addInPlace(this._target);\n const distanceSquared = Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);\n if (distanceSquared <= this.panningDistanceLimit * this.panningDistanceLimit) {\n this._target.copyFrom(this._transformedDirection);\n }\n }\n else {\n this._target.addInPlace(this._transformedDirection);\n }\n }\n this.inertialPanningX *= this.panningInertia;\n this.inertialPanningY *= this.panningInertia;\n if (Math.abs(this.inertialPanningX) < this.speed * Epsilon) {\n this.inertialPanningX = 0;\n }\n if (Math.abs(this.inertialPanningY) < this.speed * Epsilon) {\n this.inertialPanningY = 0;\n }\n }\n // Limits\n this._checkLimits();\n super._checkInputs();\n }\n _checkLimits() {\n if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {\n if (this.allowUpsideDown && this.beta > Math.PI) {\n this.beta = this.beta - 2 * Math.PI;\n }\n }\n else {\n if (this.beta < this.lowerBetaLimit) {\n this.beta = this.lowerBetaLimit;\n }\n }\n if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {\n if (this.allowUpsideDown && this.beta < -Math.PI) {\n this.beta = this.beta + 2 * Math.PI;\n }\n }\n else {\n if (this.beta > this.upperBetaLimit) {\n this.beta = this.upperBetaLimit;\n }\n }\n if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {\n this.alpha = this.lowerAlphaLimit;\n }\n if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {\n this.alpha = this.upperAlphaLimit;\n }\n if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {\n this.radius = this.lowerRadiusLimit;\n this.inertialRadiusOffset = 0;\n }\n if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {\n this.radius = this.upperRadiusLimit;\n this.inertialRadiusOffset = 0;\n }\n }\n /**\n * Rebuilds angles (alpha, beta) and radius from the give position and target\n */\n rebuildAnglesAndRadius() {\n this._position.subtractToRef(this._getTargetPosition(), this._computationVector);\n // need to rotate to Y up equivalent if up vector not Axis.Y\n if (this._upVector.x !== 0 || this._upVector.y !== 1.0 || this._upVector.z !== 0) {\n Vector3.TransformCoordinatesToRef(this._computationVector, this._upToYMatrix, this._computationVector);\n }\n this.radius = this._computationVector.length();\n if (this.radius === 0) {\n this.radius = 0.0001; // Just to avoid division by zero\n }\n // Alpha\n const previousAlpha = this.alpha;\n if (this._computationVector.x === 0 && this._computationVector.z === 0) {\n this.alpha = Math.PI / 2; // avoid division by zero when looking along up axis, and set to acos(0)\n }\n else {\n this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));\n }\n if (this._computationVector.z < 0) {\n this.alpha = 2 * Math.PI - this.alpha;\n }\n // Calculate the number of revolutions between the new and old alpha values.\n const alphaCorrectionTurns = Math.round((previousAlpha - this.alpha) / (2.0 * Math.PI));\n // Adjust alpha so that its numerical representation is the closest one to the old value.\n this.alpha += alphaCorrectionTurns * 2.0 * Math.PI;\n // Beta\n this.beta = Math.acos(this._computationVector.y / this.radius);\n this._checkLimits();\n }\n /**\n * Use a position to define the current camera related information like alpha, beta and radius\n * @param position Defines the position to set the camera at\n */\n setPosition(position) {\n if (this._position.equals(position)) {\n return;\n }\n this._position.copyFrom(position);\n this.rebuildAnglesAndRadius();\n }\n /**\n * Defines the target the camera should look at.\n * This will automatically adapt alpha beta and radius to fit within the new target.\n * Please note that setting a target as a mesh will disable panning.\n * @param target Defines the new target as a Vector or a mesh\n * @param toBoundingCenter In case of a mesh target, defines whether to target the mesh position or its bounding information center\n * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)\n * @param cloneAlphaBetaRadius If true, replicate the current setup (alpha, beta, radius) on the new target\n */\n setTarget(target, toBoundingCenter = false, allowSamePosition = false, cloneAlphaBetaRadius = false) {\n var _a;\n cloneAlphaBetaRadius = (_a = this.overrideCloneAlphaBetaRadius) !== null && _a !== void 0 ? _a : cloneAlphaBetaRadius;\n if (target.getBoundingInfo) {\n if (toBoundingCenter) {\n this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();\n }\n else {\n this._targetBoundingCenter = null;\n }\n target.computeWorldMatrix();\n this._targetHost = target;\n this._target = this._getTargetPosition();\n this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);\n }\n else {\n const newTarget = target;\n const currentTarget = this._getTargetPosition();\n if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {\n return;\n }\n this._targetHost = null;\n this._target = newTarget;\n this._targetBoundingCenter = null;\n this.onMeshTargetChangedObservable.notifyObservers(null);\n }\n if (!cloneAlphaBetaRadius) {\n this.rebuildAnglesAndRadius();\n }\n }\n /** @internal */\n _getViewMatrix() {\n // Compute\n const cosa = Math.cos(this.alpha);\n const sina = Math.sin(this.alpha);\n const cosb = Math.cos(this.beta);\n let sinb = Math.sin(this.beta);\n if (sinb === 0) {\n sinb = 0.0001;\n }\n if (this.radius === 0) {\n this.radius = 0.0001; // Just to avoid division by zero\n }\n const target = this._getTargetPosition();\n this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);\n // Rotate according to up vector\n if (this._upVector.x !== 0 || this._upVector.y !== 1.0 || this._upVector.z !== 0) {\n Vector3.TransformCoordinatesToRef(this._computationVector, this._yToUpMatrix, this._computationVector);\n }\n target.addToRef(this._computationVector, this._newPosition);\n if (this.getScene().collisionsEnabled && this.checkCollisions) {\n const coordinator = this.getScene().collisionCoordinator;\n if (!this._collider) {\n this._collider = coordinator.createCollider();\n }\n this._collider._radius = this.collisionRadius;\n this._newPosition.subtractToRef(this._position, this._collisionVelocity);\n this._collisionTriggered = true;\n coordinator.getNewPosition(this._position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);\n }\n else {\n this._position.copyFrom(this._newPosition);\n let up = this.upVector;\n if (this.allowUpsideDown && sinb < 0) {\n up = up.negate();\n }\n this._computeViewMatrix(this._position, target, up);\n this._viewMatrix.addAtIndex(12, this.targetScreenOffset.x);\n this._viewMatrix.addAtIndex(13, this.targetScreenOffset.y);\n }\n this._currentTarget = target;\n return this._viewMatrix;\n }\n /**\n * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.\n * @param meshes Defines the mesh to zoom on\n * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)\n */\n zoomOn(meshes, doNotUpdateMaxZ = false) {\n meshes = meshes || this.getScene().meshes;\n const minMaxVector = Mesh.MinMax(meshes);\n const distance = Vector3.Distance(minMaxVector.min, minMaxVector.max);\n this.radius = distance * this.zoomOnFactor;\n this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);\n }\n /**\n * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.\n * The target will be changed but the radius\n * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on\n * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)\n */\n focusOn(meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ = false) {\n let meshesOrMinMaxVector;\n let distance;\n if (meshesOrMinMaxVectorAndDistance.min === undefined) {\n // meshes\n const meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;\n meshesOrMinMaxVector = Mesh.MinMax(meshes);\n distance = Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);\n }\n else {\n //minMaxVector and distance\n const minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;\n meshesOrMinMaxVector = minMaxVectorAndDistance;\n distance = minMaxVectorAndDistance.distance;\n }\n this._target = Mesh.Center(meshesOrMinMaxVector);\n if (!doNotUpdateMaxZ) {\n this.maxZ = distance * 2;\n }\n }\n /**\n * @override\n * Override Camera.createRigCamera\n */\n createRigCamera(name, cameraIndex) {\n let alphaShift = 0;\n switch (this.cameraRigMode) {\n case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:\n case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:\n case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:\n case Camera.RIG_MODE_STEREOSCOPIC_INTERLACED:\n case Camera.RIG_MODE_VR:\n alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);\n break;\n case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:\n alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);\n break;\n }\n const rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());\n rigCam._cameraRigParams = {};\n rigCam.isRigCamera = true;\n rigCam.rigParent = this;\n rigCam.upVector = this.upVector;\n rigCam.mode = this.mode;\n rigCam.orthoLeft = this.orthoLeft;\n rigCam.orthoRight = this.orthoRight;\n rigCam.orthoBottom = this.orthoBottom;\n rigCam.orthoTop = this.orthoTop;\n return rigCam;\n }\n /**\n * @internal\n * @override\n * Override Camera._updateRigCameras\n */\n _updateRigCameras() {\n const camLeft = this._rigCameras[0];\n const camRight = this._rigCameras[1];\n camLeft.beta = camRight.beta = this.beta;\n switch (this.cameraRigMode) {\n case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:\n case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:\n case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:\n case Camera.RIG_MODE_STEREOSCOPIC_INTERLACED:\n case Camera.RIG_MODE_VR:\n camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;\n camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;\n break;\n case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:\n camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;\n camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;\n break;\n }\n super._updateRigCameras();\n }\n /**\n * Destroy the camera and release the current resources hold by it.\n */\n dispose() {\n this.inputs.clear();\n super.dispose();\n }\n /**\n * Gets the current object class name.\n * @returns the class name\n */\n getClassName() {\n return \"ArcRotateCamera\";\n }\n}\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"alpha\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"beta\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"radius\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"overrideCloneAlphaBetaRadius\", void 0);\n__decorate([\n serializeAsVector3(\"target\")\n], ArcRotateCamera.prototype, \"_target\", void 0);\n__decorate([\n serializeAsMeshReference(\"targetHost\")\n], ArcRotateCamera.prototype, \"_targetHost\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"inertialAlphaOffset\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"inertialBetaOffset\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"inertialRadiusOffset\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"lowerAlphaLimit\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"upperAlphaLimit\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"lowerBetaLimit\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"upperBetaLimit\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"lowerRadiusLimit\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"upperRadiusLimit\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"inertialPanningX\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"inertialPanningY\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"pinchToPanMaxDistance\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"panningDistanceLimit\", void 0);\n__decorate([\n serializeAsVector3()\n], ArcRotateCamera.prototype, \"panningOriginTarget\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"panningInertia\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"zoomToMouseLocation\", null);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"zoomOnFactor\", void 0);\n__decorate([\n serializeAsVector2()\n], ArcRotateCamera.prototype, \"targetScreenOffset\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"allowUpsideDown\", void 0);\n__decorate([\n serialize()\n], ArcRotateCamera.prototype, \"useInputToRestoreState\", void 0);\n//# sourceMappingURL=arcRotateCamera.js.map","import { FreeCamera } from \"./freeCamera.js\";\nimport { Quaternion, Vector3 } from \"../Maths/math.vector.js\";\nimport { Node } from \"../node.js\";\nimport \"./Inputs/freeCameraDeviceOrientationInput.js\";\nimport { Axis } from \"../Maths/math.axis.js\";\nNode.AddNodeConstructor(\"DeviceOrientationCamera\", (name, scene) => {\n return () => new DeviceOrientationCamera(name, Vector3.Zero(), scene);\n});\n// We're mainly based on the logic defined into the FreeCamera code\n/**\n * This is a camera specifically designed to react to device orientation events such as a modern mobile device\n * being tilted forward or back and left or right.\n */\nexport class DeviceOrientationCamera extends FreeCamera {\n /**\n * Creates a new device orientation camera\n * @param name The name of the camera\n * @param position The start position camera\n * @param scene The scene the camera belongs to\n */\n constructor(name, position, scene) {\n super(name, position, scene);\n this._tmpDragQuaternion = new Quaternion();\n this._disablePointerInputWhenUsingDeviceOrientation = true;\n this._dragFactor = 0;\n this._quaternionCache = new Quaternion();\n this.inputs.addDeviceOrientation();\n // When the orientation sensor fires it's first event, disable mouse input\n if (this.inputs._deviceOrientationInput) {\n this.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce(() => {\n if (this._disablePointerInputWhenUsingDeviceOrientation) {\n if (this.inputs._mouseInput) {\n this.inputs._mouseInput._allowCameraRotation = false;\n this.inputs._mouseInput.onPointerMovedObservable.add((e) => {\n if (this._dragFactor != 0) {\n if (!this._initialQuaternion) {\n this._initialQuaternion = new Quaternion();\n }\n // Rotate the initial space around the y axis to allow users to \"turn around\" via touch/mouse\n Quaternion.FromEulerAnglesToRef(0, e.offsetX * this._dragFactor, 0, this._tmpDragQuaternion);\n this._initialQuaternion.multiplyToRef(this._tmpDragQuaternion, this._initialQuaternion);\n }\n });\n }\n }\n });\n }\n }\n /**\n * Gets or sets a boolean indicating that pointer input must be disabled on first orientation sensor update (Default: true)\n */\n get disablePointerInputWhenUsingDeviceOrientation() {\n return this._disablePointerInputWhenUsingDeviceOrientation;\n }\n set disablePointerInputWhenUsingDeviceOrientation(value) {\n this._disablePointerInputWhenUsingDeviceOrientation = value;\n }\n /**\n * Enabled turning on the y axis when the orientation sensor is active\n * @param dragFactor the factor that controls the turn speed (default: 1/300)\n */\n enableHorizontalDragging(dragFactor = 1 / 300) {\n this._dragFactor = dragFactor;\n }\n /**\n * Gets the current instance class name (\"DeviceOrientationCamera\").\n * This helps avoiding instanceof at run time.\n * @returns the class name\n */\n getClassName() {\n return \"DeviceOrientationCamera\";\n }\n /**\n * @internal\n * Checks and applies the current values of the inputs to the camera. (Internal use only)\n */\n _checkInputs() {\n super._checkInputs();\n this._quaternionCache.copyFrom(this.rotationQuaternion);\n if (this._initialQuaternion) {\n this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);\n }\n }\n /**\n * Reset the camera to its default orientation on the specified axis only.\n * @param axis The axis to reset\n */\n resetToCurrentRotation(axis = Axis.Y) {\n //can only work if this camera has a rotation quaternion already.\n if (!this.rotationQuaternion) {\n return;\n }\n if (!this._initialQuaternion) {\n this._initialQuaternion = new Quaternion();\n }\n this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);\n [\"x\", \"y\", \"z\"].forEach((axisName) => {\n if (!axis[axisName]) {\n this._initialQuaternion[axisName] = 0;\n }\n else {\n this._initialQuaternion[axisName] *= -1;\n }\n });\n this._initialQuaternion.normalize();\n //force rotation update\n this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);\n }\n}\n//# sourceMappingURL=deviceOrientationCamera.js.map","import { CameraInputsManager } from \"./cameraInputsManager.js\";\nimport { FlyCameraMouseInput } from \"../Cameras/Inputs/flyCameraMouseInput.js\";\nimport { FlyCameraKeyboardInput } from \"../Cameras/Inputs/flyCameraKeyboardInput.js\";\n/**\n * Default Inputs manager for the FlyCamera.\n * It groups all the default supported inputs for ease of use.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FlyCameraInputsManager extends CameraInputsManager {\n /**\n * Instantiates a new FlyCameraInputsManager.\n * @param camera Defines the camera the inputs belong to.\n */\n constructor(camera) {\n super(camera);\n }\n /**\n * Add keyboard input support to the input manager.\n * @returns the new FlyCameraKeyboardMoveInput().\n */\n addKeyboard() {\n this.add(new FlyCameraKeyboardInput());\n return this;\n }\n /**\n * Add mouse input support to the input manager.\n * @returns the new FlyCameraMouseInput().\n */\n addMouse() {\n this.add(new FlyCameraMouseInput());\n return this;\n }\n}\n//# sourceMappingURL=flyCameraInputsManager.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize, serializeAsVector3 } from \"../Misc/decorators.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { TargetCamera } from \"./targetCamera.js\";\nimport { FlyCameraInputsManager } from \"./flyCameraInputsManager.js\";\nimport { Tools } from \"../Misc/tools.js\";\n/**\n * This is a flying camera, designed for 3D movement and rotation in all directions,\n * such as in a 3D Space Shooter or a Flight Simulator.\n */\nexport class FlyCamera extends TargetCamera {\n /**\n * Gets the input sensibility for mouse input.\n * Higher values reduce sensitivity.\n */\n get angularSensibility() {\n const mouse = this.inputs.attached[\"mouse\"];\n if (mouse) {\n return mouse.angularSensibility;\n }\n return 0;\n }\n /**\n * Sets the input sensibility for a mouse input.\n * Higher values reduce sensitivity.\n */\n set angularSensibility(value) {\n const mouse = this.inputs.attached[\"mouse\"];\n if (mouse) {\n mouse.angularSensibility = value;\n }\n }\n /**\n * Get the keys for camera movement forward.\n */\n get keysForward() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysForward;\n }\n return [];\n }\n /**\n * Set the keys for camera movement forward.\n */\n set keysForward(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysForward = value;\n }\n }\n /**\n * Get the keys for camera movement backward.\n */\n get keysBackward() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysBackward;\n }\n return [];\n }\n set keysBackward(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysBackward = value;\n }\n }\n /**\n * Get the keys for camera movement up.\n */\n get keysUp() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysUp;\n }\n return [];\n }\n /**\n * Set the keys for camera movement up.\n */\n set keysUp(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysUp = value;\n }\n }\n /**\n * Get the keys for camera movement down.\n */\n get keysDown() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysDown;\n }\n return [];\n }\n /**\n * Set the keys for camera movement down.\n */\n set keysDown(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysDown = value;\n }\n }\n /**\n * Get the keys for camera movement left.\n */\n get keysLeft() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysLeft;\n }\n return [];\n }\n /**\n * Set the keys for camera movement left.\n */\n set keysLeft(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysLeft = value;\n }\n }\n /**\n * Set the keys for camera movement right.\n */\n get keysRight() {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n return keyboard.keysRight;\n }\n return [];\n }\n /**\n * Set the keys for camera movement right.\n */\n set keysRight(value) {\n const keyboard = this.inputs.attached[\"keyboard\"];\n if (keyboard) {\n keyboard.keysRight = value;\n }\n }\n /**\n * Instantiates a FlyCamera.\n * This is a flying camera, designed for 3D movement and rotation in all directions,\n * such as in a 3D Space Shooter or a Flight Simulator.\n * @param name Define the name of the camera in the scene.\n * @param position Define the starting position of the camera in the scene.\n * @param scene Define the scene the camera belongs to.\n * @param setActiveOnSceneIfNoneActive Defines whether the camera should be marked as active, if no other camera has been defined as active.\n */\n constructor(name, position, scene, setActiveOnSceneIfNoneActive = true) {\n super(name, position, scene, setActiveOnSceneIfNoneActive);\n /**\n * Define the collision ellipsoid of the camera.\n * This is helpful for simulating a camera body, like a player's body.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions#arcrotatecamera\n */\n this.ellipsoid = new Vector3(1, 1, 1);\n /**\n * Define an offset for the position of the ellipsoid around the camera.\n * This can be helpful if the camera is attached away from the player's body center,\n * such as at its head.\n */\n this.ellipsoidOffset = new Vector3(0, 0, 0);\n /**\n * Enable or disable collisions of the camera with the rest of the scene objects.\n */\n this.checkCollisions = false;\n /**\n * Enable or disable gravity on the camera.\n */\n this.applyGravity = false;\n /**\n * Define the current direction the camera is moving to.\n */\n this.cameraDirection = Vector3.Zero();\n /**\n * Track Roll to maintain the wanted Rolling when looking around.\n */\n this._trackRoll = 0;\n /**\n * Slowly correct the Roll to its original value after a Pitch+Yaw rotation.\n */\n this.rollCorrect = 100;\n /**\n * Mimic a banked turn, Rolling the camera when Yawing.\n * It's recommended to use rollCorrect = 10 for faster banking correction.\n */\n this.bankedTurn = false;\n /**\n * Limit in radians for how much Roll banking will add. (Default: 90°)\n */\n this.bankedTurnLimit = Math.PI / 2;\n /**\n * Value of 0 disables the banked Roll.\n * Value of 1 is equal to the Yaw angle in radians.\n */\n this.bankedTurnMultiplier = 1;\n this._needMoveForGravity = false;\n this._oldPosition = Vector3.Zero();\n this._diffPosition = Vector3.Zero();\n this._newPosition = Vector3.Zero();\n // Collisions.\n this._collisionMask = -1;\n /**\n * @internal\n */\n this._onCollisionPositionChange = (collisionId, newPosition, collidedMesh = null) => {\n const updatePosition = (newPos) => {\n this._newPosition.copyFrom(newPos);\n this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);\n if (this._diffPosition.length() > Engine.CollisionsEpsilon) {\n this.position.addInPlace(this._diffPosition);\n if (this.onCollide && collidedMesh) {\n this.onCollide(collidedMesh);\n }\n }\n };\n updatePosition(newPosition);\n };\n this.inputs = new FlyCameraInputsManager(this);\n this.inputs.addKeyboard().addMouse();\n }\n /**\n * Attached controls to the current camera.\n * @param ignored defines an ignored parameter kept for backward compatibility.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(ignored, noPreventDefault) {\n // eslint-disable-next-line prefer-rest-params\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n this.inputs.attachElement(noPreventDefault);\n }\n /**\n * Detach a control from the HTML DOM element.\n * The camera will stop reacting to that input.\n */\n detachControl() {\n this.inputs.detachElement();\n this.cameraDirection = new Vector3(0, 0, 0);\n }\n /**\n * Get the mask that the camera ignores in collision events.\n */\n get collisionMask() {\n return this._collisionMask;\n }\n /**\n * Set the mask that the camera ignores in collision events.\n */\n set collisionMask(mask) {\n this._collisionMask = !isNaN(mask) ? mask : -1;\n }\n /**\n * @internal\n */\n _collideWithWorld(displacement) {\n let globalPosition;\n if (this.parent) {\n globalPosition = Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());\n }\n else {\n globalPosition = this.position;\n }\n globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);\n this._oldPosition.addInPlace(this.ellipsoidOffset);\n const coordinator = this.getScene().collisionCoordinator;\n if (!this._collider) {\n this._collider = coordinator.createCollider();\n }\n this._collider._radius = this.ellipsoid;\n this._collider.collisionMask = this._collisionMask;\n // No need for clone, as long as gravity is not on.\n let actualDisplacement = displacement;\n // Add gravity to direction to prevent dual-collision checking.\n if (this.applyGravity) {\n // This prevents mending with cameraDirection, a global variable of the fly camera class.\n actualDisplacement = displacement.add(this.getScene().gravity);\n }\n coordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);\n }\n /** @internal */\n _checkInputs() {\n if (!this._localDirection) {\n this._localDirection = Vector3.Zero();\n this._transformedDirection = Vector3.Zero();\n }\n this.inputs.checkInputs();\n super._checkInputs();\n }\n /**\n * Enable movement without a user input. This allows gravity to always be applied.\n */\n set needMoveForGravity(value) {\n this._needMoveForGravity = value;\n }\n /**\n * When true, gravity is applied whether there is user input or not.\n */\n get needMoveForGravity() {\n return this._needMoveForGravity;\n }\n /** @internal */\n _decideIfNeedsToMove() {\n return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;\n }\n /** @internal */\n _updatePosition() {\n if (this.checkCollisions && this.getScene().collisionsEnabled) {\n this._collideWithWorld(this.cameraDirection);\n }\n else {\n super._updatePosition();\n }\n }\n /**\n * Restore the Roll to its target value at the rate specified.\n * @param rate - Higher means slower restoring.\n * @internal\n */\n restoreRoll(rate) {\n const limit = this._trackRoll; // Target Roll.\n const z = this.rotation.z; // Current Roll.\n const delta = limit - z; // Difference in Roll.\n const minRad = 0.001; // Tenth of a radian is a barely noticable difference.\n // If the difference is noticable, restore the Roll.\n if (Math.abs(delta) >= minRad) {\n // Change Z rotation towards the target Roll.\n this.rotation.z += delta / rate;\n // Match when near enough.\n if (Math.abs(limit - this.rotation.z) <= minRad) {\n this.rotation.z = limit;\n }\n }\n }\n /**\n * Destroy the camera and release the current resources held by it.\n */\n dispose() {\n this.inputs.clear();\n super.dispose();\n }\n /**\n * Get the current object class name.\n * @returns the class name.\n */\n getClassName() {\n return \"FlyCamera\";\n }\n}\n__decorate([\n serializeAsVector3()\n], FlyCamera.prototype, \"ellipsoid\", void 0);\n__decorate([\n serializeAsVector3()\n], FlyCamera.prototype, \"ellipsoidOffset\", void 0);\n__decorate([\n serialize()\n], FlyCamera.prototype, \"checkCollisions\", void 0);\n__decorate([\n serialize()\n], FlyCamera.prototype, \"applyGravity\", void 0);\n//# sourceMappingURL=flyCamera.js.map","import { CameraInputsManager } from \"./cameraInputsManager.js\";\nimport { FollowCameraKeyboardMoveInput } from \"./Inputs/followCameraKeyboardMoveInput.js\";\nimport { FollowCameraMouseWheelInput } from \"./Inputs/followCameraMouseWheelInput.js\";\nimport { FollowCameraPointersInput } from \"./Inputs/followCameraPointersInput.js\";\n/**\n * Default Inputs manager for the FollowCamera.\n * It groups all the default supported inputs for ease of use.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/customizingCameraInputs\n */\nexport class FollowCameraInputsManager extends CameraInputsManager {\n /**\n * Instantiates a new FollowCameraInputsManager.\n * @param camera Defines the camera the inputs belong to\n */\n constructor(camera) {\n super(camera);\n }\n /**\n * Add keyboard input support to the input manager.\n * @returns the current input manager\n */\n addKeyboard() {\n this.add(new FollowCameraKeyboardMoveInput());\n return this;\n }\n /**\n * Add mouse wheel input support to the input manager.\n * @returns the current input manager\n */\n addMouseWheel() {\n this.add(new FollowCameraMouseWheelInput());\n return this;\n }\n /**\n * Add pointers input support to the input manager.\n * @returns the current input manager\n */\n addPointers() {\n this.add(new FollowCameraPointersInput());\n return this;\n }\n /**\n * Add orientation input support to the input manager.\n * @returns the current input manager\n */\n addVRDeviceOrientation() {\n console.warn(\"DeviceOrientation support not yet implemented for FollowCamera.\");\n return this;\n }\n}\n//# sourceMappingURL=followCameraInputsManager.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize, serializeAsMeshReference } from \"../Misc/decorators.js\";\nimport { Tools } from \"../Misc/tools.js\";\nimport { TargetCamera } from \"./targetCamera.js\";\nimport { TmpVectors, Vector3 } from \"../Maths/math.vector.js\";\nimport { Node } from \"../node.js\";\nimport { FollowCameraInputsManager } from \"./followCameraInputsManager.js\";\nNode.AddNodeConstructor(\"FollowCamera\", (name, scene) => {\n return () => new FollowCamera(name, Vector3.Zero(), scene);\n});\nNode.AddNodeConstructor(\"ArcFollowCamera\", (name, scene) => {\n return () => new ArcFollowCamera(name, 0, 0, 1.0, null, scene);\n});\n/**\n * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and\n * an arc rotate version arcFollowCamera are available.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#followcamera\n */\nexport class FollowCamera extends TargetCamera {\n /**\n * Instantiates the follow camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#followcamera\n * @param name Define the name of the camera in the scene\n * @param position Define the position of the camera\n * @param scene Define the scene the camera belong to\n * @param lockedTarget Define the target of the camera\n */\n constructor(name, position, scene, lockedTarget = null) {\n super(name, position, scene);\n /**\n * Distance the follow camera should follow an object at\n */\n this.radius = 12;\n /**\n * Minimum allowed distance of the camera to the axis of rotation\n * (The camera can not get closer).\n * This can help limiting how the Camera is able to move in the scene.\n */\n this.lowerRadiusLimit = null;\n /**\n * Maximum allowed distance of the camera to the axis of rotation\n * (The camera can not get further).\n * This can help limiting how the Camera is able to move in the scene.\n */\n this.upperRadiusLimit = null;\n /**\n * Define a rotation offset between the camera and the object it follows\n */\n this.rotationOffset = 0;\n /**\n * Minimum allowed angle to camera position relative to target object.\n * This can help limiting how the Camera is able to move in the scene.\n */\n this.lowerRotationOffsetLimit = null;\n /**\n * Maximum allowed angle to camera position relative to target object.\n * This can help limiting how the Camera is able to move in the scene.\n */\n this.upperRotationOffsetLimit = null;\n /**\n * Define a height offset between the camera and the object it follows.\n * It can help following an object from the top (like a car chasing a plane)\n */\n this.heightOffset = 4;\n /**\n * Minimum allowed height of camera position relative to target object.\n * This can help limiting how the Camera is able to move in the scene.\n */\n this.lowerHeightOffsetLimit = null;\n /**\n * Maximum allowed height of camera position relative to target object.\n * This can help limiting how the Camera is able to move in the scene.\n */\n this.upperHeightOffsetLimit = null;\n /**\n * Define how fast the camera can accelerate to follow it s target.\n */\n this.cameraAcceleration = 0.05;\n /**\n * Define the speed limit of the camera following an object.\n */\n this.maxCameraSpeed = 20;\n this.lockedTarget = lockedTarget;\n this.inputs = new FollowCameraInputsManager(this);\n this.inputs.addKeyboard().addMouseWheel().addPointers();\n // Uncomment the following line when the relevant handlers have been implemented.\n // this.inputs.addKeyboard().addMouseWheel().addPointers().addVRDeviceOrientation();\n }\n _follow(cameraTarget) {\n if (!cameraTarget) {\n return;\n }\n const rotMatrix = TmpVectors.Matrix[0];\n cameraTarget.absoluteRotationQuaternion.toRotationMatrix(rotMatrix);\n const yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);\n const radians = Tools.ToRadians(this.rotationOffset) + yRotation;\n const targetPosition = cameraTarget.getAbsolutePosition();\n const targetX = targetPosition.x + Math.sin(radians) * this.radius;\n const targetZ = targetPosition.z + Math.cos(radians) * this.radius;\n const dx = targetX - this.position.x;\n const dy = targetPosition.y + this.heightOffset - this.position.y;\n const dz = targetZ - this.position.z;\n let vx = dx * this.cameraAcceleration * 2; //this is set to .05\n let vy = dy * this.cameraAcceleration;\n let vz = dz * this.cameraAcceleration * 2;\n if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {\n vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;\n }\n if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {\n vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;\n }\n if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {\n vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;\n }\n this.position = new Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);\n this.setTarget(targetPosition);\n }\n /**\n * Attached controls to the current camera.\n * @param ignored defines an ignored parameter kept for backward compatibility.\n * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(ignored, noPreventDefault) {\n // eslint-disable-next-line prefer-rest-params\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n this.inputs.attachElement(noPreventDefault);\n this._reset = () => { };\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n this.inputs.detachElement();\n if (this._reset) {\n this._reset();\n }\n }\n /** @internal */\n _checkInputs() {\n this.inputs.checkInputs();\n this._checkLimits();\n super._checkInputs();\n if (this.lockedTarget) {\n this._follow(this.lockedTarget);\n }\n }\n _checkLimits() {\n if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {\n this.radius = this.lowerRadiusLimit;\n }\n if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {\n this.radius = this.upperRadiusLimit;\n }\n if (this.lowerHeightOffsetLimit !== null && this.heightOffset < this.lowerHeightOffsetLimit) {\n this.heightOffset = this.lowerHeightOffsetLimit;\n }\n if (this.upperHeightOffsetLimit !== null && this.heightOffset > this.upperHeightOffsetLimit) {\n this.heightOffset = this.upperHeightOffsetLimit;\n }\n if (this.lowerRotationOffsetLimit !== null && this.rotationOffset < this.lowerRotationOffsetLimit) {\n this.rotationOffset = this.lowerRotationOffsetLimit;\n }\n if (this.upperRotationOffsetLimit !== null && this.rotationOffset > this.upperRotationOffsetLimit) {\n this.rotationOffset = this.upperRotationOffsetLimit;\n }\n }\n /**\n * Gets the camera class name.\n * @returns the class name\n */\n getClassName() {\n return \"FollowCamera\";\n }\n}\n__decorate([\n serialize()\n], FollowCamera.prototype, \"radius\", void 0);\n__decorate([\n serialize()\n], FollowCamera.prototype, \"lowerRadiusLimit\", void 0);\n__decorate([\n serialize()\n], FollowCamera.prototype, \"upperRadiusLimit\", void 0);\n__decorate([\n serialize()\n], FollowCamera.prototype, \"rotationOffset\", void 0);\n__decorate([\n serialize()\n], FollowCamera.prototype, \"lowerRotationOffsetLimit\", void 0);\n__decorate([\n serialize()\n], FollowCamera.prototype, \"upperRotationOffsetLimit\", void 0);\n__decorate([\n serialize()\n], FollowCamera.prototype, \"heightOffset\", void 0);\n__decorate([\n serialize()\n], FollowCamera.prototype, \"lowerHeightOffsetLimit\", void 0);\n__decorate([\n serialize()\n], FollowCamera.prototype, \"upperHeightOffsetLimit\", void 0);\n__decorate([\n serialize()\n], FollowCamera.prototype, \"cameraAcceleration\", void 0);\n__decorate([\n serialize()\n], FollowCamera.prototype, \"maxCameraSpeed\", void 0);\n__decorate([\n serializeAsMeshReference(\"lockedTargetId\")\n], FollowCamera.prototype, \"lockedTarget\", void 0);\n/**\n * Arc Rotate version of the follow camera.\n * It still follows a Defined mesh but in an Arc Rotate Camera fashion.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#followcamera\n */\nexport class ArcFollowCamera extends TargetCamera {\n /**\n * Instantiates a new ArcFollowCamera\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#followcamera\n * @param name Define the name of the camera\n * @param alpha Define the rotation angle of the camera around the longitudinal axis\n * @param beta Define the rotation angle of the camera around the elevation axis\n * @param radius Define the radius of the camera from its target point\n * @param target Define the target of the camera\n * @param scene Define the scene the camera belongs to\n */\n constructor(name, \n /** The longitudinal angle of the camera */\n alpha, \n /** The latitudinal angle of the camera */\n beta, \n /** The radius of the camera from its target */\n radius, \n /** Define the camera target (the mesh it should follow) */\n target, scene) {\n super(name, Vector3.Zero(), scene);\n this.alpha = alpha;\n this.beta = beta;\n this.radius = radius;\n this._cartesianCoordinates = Vector3.Zero();\n this.setMeshTarget(target);\n }\n /**\n * Sets the mesh to follow with this camera.\n * @param target the target to follow\n */\n setMeshTarget(target) {\n this._meshTarget = target;\n this._follow();\n }\n _follow() {\n if (!this._meshTarget) {\n return;\n }\n this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);\n this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);\n this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);\n const targetPosition = this._meshTarget.getAbsolutePosition();\n this.position = targetPosition.add(this._cartesianCoordinates);\n this.setTarget(targetPosition);\n }\n /** @internal */\n _checkInputs() {\n super._checkInputs();\n this._follow();\n }\n /**\n * Returns the class name of the object.\n * It is mostly used internally for serialization purposes.\n */\n getClassName() {\n return \"ArcFollowCamera\";\n }\n}\n//# sourceMappingURL=followCamera.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { IsWindowObjectExist } from \"../Misc/domManagement.js\";\nimport { PoseEnabledControllerHelper } from \"../Gamepads/Controllers/poseEnabledController.js\";\nimport { Xbox360Pad } from \"./xboxGamepad.js\";\nimport { Gamepad, GenericPad } from \"./gamepad.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { DualShockPad } from \"./dualShockGamepad.js\";\nimport { Tools } from \"../Misc/tools.js\";\n/**\n * Manager for handling gamepads\n */\nexport class GamepadManager {\n /**\n * Initializes the gamepad manager\n * @param _scene BabylonJS scene\n */\n constructor(_scene) {\n this._scene = _scene;\n this._babylonGamepads = [];\n this._oneGamepadConnected = false;\n /** @internal */\n this._isMonitoring = false;\n /**\n * observable to be triggered when the gamepad controller has been disconnected\n */\n this.onGamepadDisconnectedObservable = new Observable();\n if (!IsWindowObjectExist()) {\n this._gamepadEventSupported = false;\n }\n else {\n this._gamepadEventSupported = \"GamepadEvent\" in window;\n this._gamepadSupport = navigator && navigator.getGamepads;\n }\n this.onGamepadConnectedObservable = new Observable((observer) => {\n // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected\n for (const i in this._babylonGamepads) {\n const gamepad = this._babylonGamepads[i];\n if (gamepad && gamepad._isConnected) {\n this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);\n }\n }\n });\n this._onGamepadConnectedEvent = (evt) => {\n const gamepad = evt.gamepad;\n if (gamepad.index in this._babylonGamepads) {\n if (this._babylonGamepads[gamepad.index].isConnected) {\n return;\n }\n }\n let newGamepad;\n if (this._babylonGamepads[gamepad.index]) {\n newGamepad = this._babylonGamepads[gamepad.index];\n newGamepad.browserGamepad = gamepad;\n newGamepad._isConnected = true;\n }\n else {\n newGamepad = this._addNewGamepad(gamepad);\n }\n this.onGamepadConnectedObservable.notifyObservers(newGamepad);\n this._startMonitoringGamepads();\n };\n this._onGamepadDisconnectedEvent = (evt) => {\n const gamepad = evt.gamepad;\n // Remove the gamepad from the list of gamepads to monitor.\n for (const i in this._babylonGamepads) {\n if (this._babylonGamepads[i].index === gamepad.index) {\n const disconnectedGamepad = this._babylonGamepads[i];\n disconnectedGamepad._isConnected = false;\n this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);\n disconnectedGamepad.dispose && disconnectedGamepad.dispose();\n break;\n }\n }\n };\n if (this._gamepadSupport) {\n //first add already-connected gamepads\n this._updateGamepadObjects();\n if (this._babylonGamepads.length) {\n this._startMonitoringGamepads();\n }\n // Checking if the gamepad connected event is supported (like in Firefox)\n if (this._gamepadEventSupported) {\n const hostWindow = this._scene ? this._scene.getEngine().getHostWindow() : window;\n if (hostWindow) {\n hostWindow.addEventListener(\"gamepadconnected\", this._onGamepadConnectedEvent, false);\n hostWindow.addEventListener(\"gamepaddisconnected\", this._onGamepadDisconnectedEvent, false);\n }\n }\n else {\n this._startMonitoringGamepads();\n }\n }\n }\n /**\n * The gamepads in the game pad manager\n */\n get gamepads() {\n return this._babylonGamepads;\n }\n /**\n * Get the gamepad controllers based on type\n * @param type The type of gamepad controller\n * @returns Nullable gamepad\n */\n getGamepadByType(type = Gamepad.XBOX) {\n for (const gamepad of this._babylonGamepads) {\n if (gamepad && gamepad.type === type) {\n return gamepad;\n }\n }\n return null;\n }\n /**\n * Disposes the gamepad manager\n */\n dispose() {\n if (this._gamepadEventSupported) {\n if (this._onGamepadConnectedEvent) {\n window.removeEventListener(\"gamepadconnected\", this._onGamepadConnectedEvent);\n }\n if (this._onGamepadDisconnectedEvent) {\n window.removeEventListener(\"gamepaddisconnected\", this._onGamepadDisconnectedEvent);\n }\n this._onGamepadConnectedEvent = null;\n this._onGamepadDisconnectedEvent = null;\n }\n this._babylonGamepads.forEach((gamepad) => {\n gamepad.dispose();\n });\n this.onGamepadConnectedObservable.clear();\n this.onGamepadDisconnectedObservable.clear();\n this._oneGamepadConnected = false;\n this._stopMonitoringGamepads();\n this._babylonGamepads = [];\n }\n _addNewGamepad(gamepad) {\n if (!this._oneGamepadConnected) {\n this._oneGamepadConnected = true;\n }\n let newGamepad;\n const dualShock = gamepad.id.search(\"054c\") !== -1 && gamepad.id.search(\"0ce6\") === -1;\n const xboxOne = gamepad.id.search(\"Xbox One\") !== -1;\n if (xboxOne ||\n gamepad.id.search(\"Xbox 360\") !== -1 ||\n gamepad.id.search(\"xinput\") !== -1 ||\n (gamepad.id.search(\"045e\") !== -1 && gamepad.id.search(\"Surface Dock\") === -1)) {\n // make sure the Surface Dock Extender is not detected as an xbox controller\n newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);\n }\n else if (dualShock) {\n newGamepad = new DualShockPad(gamepad.id, gamepad.index, gamepad);\n }\n // if pose is supported, use the (WebVR) pose enabled controller\n else if (gamepad.pose) {\n newGamepad = PoseEnabledControllerHelper.InitiateController(gamepad);\n }\n else {\n newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);\n }\n this._babylonGamepads[newGamepad.index] = newGamepad;\n return newGamepad;\n }\n _startMonitoringGamepads() {\n if (!this._isMonitoring) {\n this._isMonitoring = true;\n //back-comp\n this._checkGamepadsStatus();\n }\n }\n _stopMonitoringGamepads() {\n this._isMonitoring = false;\n }\n /** @internal */\n _checkGamepadsStatus() {\n // Hack to be compatible Chrome\n this._updateGamepadObjects();\n for (const i in this._babylonGamepads) {\n const gamepad = this._babylonGamepads[i];\n if (!gamepad || !gamepad.isConnected) {\n continue;\n }\n try {\n gamepad.update();\n }\n catch (_a) {\n if (this._loggedErrors.indexOf(gamepad.index) === -1) {\n Tools.Warn(`Error updating gamepad ${gamepad.id}`);\n this._loggedErrors.push(gamepad.index);\n }\n }\n }\n if (this._isMonitoring) {\n Engine.QueueNewFrame(() => {\n this._checkGamepadsStatus();\n });\n }\n }\n // This function is called only on Chrome, which does not properly support\n // connection/disconnection events and forces you to recopy again the gamepad object\n _updateGamepadObjects() {\n const gamepads = navigator.getGamepads ? navigator.getGamepads() : [];\n for (let i = 0; i < gamepads.length; i++) {\n const gamepad = gamepads[i];\n if (gamepad) {\n if (!this._babylonGamepads[gamepad.index]) {\n const newGamepad = this._addNewGamepad(gamepad);\n this.onGamepadConnectedObservable.notifyObservers(newGamepad);\n }\n else {\n // Forced to copy again this object for Chrome for unknown reason\n this._babylonGamepads[i].browserGamepad = gamepad;\n if (!this._babylonGamepads[i].isConnected) {\n this._babylonGamepads[i]._isConnected = true;\n this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);\n }\n }\n }\n }\n }\n}\n//# sourceMappingURL=gamepadManager.js.map","import { Scene } from \"../scene.js\";\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { GamepadManager } from \"./gamepadManager.js\";\nimport { FreeCameraInputsManager } from \"../Cameras/freeCameraInputsManager.js\";\nimport { FreeCameraGamepadInput } from \"../Cameras/Inputs/freeCameraGamepadInput.js\";\nimport { ArcRotateCameraInputsManager } from \"../Cameras/arcRotateCameraInputsManager.js\";\nimport { ArcRotateCameraGamepadInput } from \"../Cameras/Inputs/arcRotateCameraGamepadInput.js\";\nObject.defineProperty(Scene.prototype, \"gamepadManager\", {\n get: function () {\n if (!this._gamepadManager) {\n this._gamepadManager = new GamepadManager(this);\n let component = this._getComponent(SceneComponentConstants.NAME_GAMEPAD);\n if (!component) {\n component = new GamepadSystemSceneComponent(this);\n this._addComponent(component);\n }\n }\n return this._gamepadManager;\n },\n enumerable: true,\n configurable: true,\n});\n/**\n * Adds a gamepad to the free camera inputs manager\n */\nFreeCameraInputsManager.prototype.addGamepad = function () {\n this.add(new FreeCameraGamepadInput());\n return this;\n};\n/**\n * Adds a gamepad to the arc rotate camera inputs manager\n */\nArcRotateCameraInputsManager.prototype.addGamepad = function () {\n this.add(new ArcRotateCameraGamepadInput());\n return this;\n};\n/**\n * Defines the gamepad scene component responsible to manage gamepads in a given scene\n */\nexport class GamepadSystemSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpfull to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_GAMEPAD;\n this.scene = scene;\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene._beforeCameraUpdateStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n // Nothing to do for gamepads\n }\n /**\n * Disposes the component and the associated resources\n */\n dispose() {\n const gamepadManager = this.scene._gamepadManager;\n if (gamepadManager) {\n gamepadManager.dispose();\n this.scene._gamepadManager = null;\n }\n }\n _beforeCameraUpdate() {\n const gamepadManager = this.scene._gamepadManager;\n if (gamepadManager && gamepadManager._isMonitoring) {\n gamepadManager._checkGamepadsStatus();\n }\n }\n}\n//# sourceMappingURL=gamepadSceneComponent.js.map","import { TouchCamera } from \"./touchCamera.js\";\nimport { Node } from \"../node.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Camera } from \"./camera.js\";\nimport \"../Gamepads/gamepadSceneComponent.js\";\nNode.AddNodeConstructor(\"FreeCamera\", (name, scene) => {\n // Forcing to use the Universal camera\n return () => new UniversalCamera(name, Vector3.Zero(), scene);\n});\n/**\n * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,\n * which still works and will still be found in many Playgrounds.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera\n */\nexport class UniversalCamera extends TouchCamera {\n /**\n * Defines the gamepad rotation sensibility.\n * This is the threshold from when rotation starts to be accounted for to prevent jittering.\n */\n get gamepadAngularSensibility() {\n const gamepad = this.inputs.attached[\"gamepad\"];\n if (gamepad) {\n return gamepad.gamepadAngularSensibility;\n }\n return 0;\n }\n set gamepadAngularSensibility(value) {\n const gamepad = this.inputs.attached[\"gamepad\"];\n if (gamepad) {\n gamepad.gamepadAngularSensibility = value;\n }\n }\n /**\n * Defines the gamepad move sensibility.\n * This is the threshold from when moving starts to be accounted for to prevent jittering.\n */\n get gamepadMoveSensibility() {\n const gamepad = this.inputs.attached[\"gamepad\"];\n if (gamepad) {\n return gamepad.gamepadMoveSensibility;\n }\n return 0;\n }\n set gamepadMoveSensibility(value) {\n const gamepad = this.inputs.attached[\"gamepad\"];\n if (gamepad) {\n gamepad.gamepadMoveSensibility = value;\n }\n }\n /**\n * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,\n * which still works and will still be found in many Playgrounds.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera\n * @param name Define the name of the camera in the scene\n * @param position Define the start position of the camera in the scene\n * @param scene Define the scene the camera belongs to\n */\n constructor(name, position, scene) {\n super(name, position, scene);\n this.inputs.addGamepad();\n }\n /**\n * Gets the current object class name.\n * @returns the class name\n */\n getClassName() {\n return \"UniversalCamera\";\n }\n}\nCamera._CreateDefaultParsedCamera = (name, scene) => {\n return new UniversalCamera(name, Vector3.Zero(), scene);\n};\n//# sourceMappingURL=universalCamera.js.map","import { UniversalCamera } from \"./universalCamera.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Node } from \"../node.js\";\nNode.AddNodeConstructor(\"GamepadCamera\", (name, scene) => {\n return () => new GamepadCamera(name, Vector3.Zero(), scene);\n});\n/**\n * This represents a FPS type of camera. This is only here for back compat purpose.\n * Please use the UniversalCamera instead as both are identical.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera\n */\nexport class GamepadCamera extends UniversalCamera {\n /**\n * Instantiates a new Gamepad Camera\n * This represents a FPS type of camera. This is only here for back compat purpose.\n * Please use the UniversalCamera instead as both are identical.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#universal-camera\n * @param name Define the name of the camera in the scene\n * @param position Define the start position of the camera in the scene\n * @param scene Define the scene the camera belongs to\n */\n constructor(name, position, scene) {\n super(name, position, scene);\n }\n /**\n * Gets the current object class name.\n * @returns the class name\n */\n getClassName() {\n return \"GamepadCamera\";\n }\n}\n//# sourceMappingURL=gamepadCamera.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"passCubePixelShader\";\nconst shader = `varying vec2 vUV;\runiform samplerCube textureSampler;\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \r{\rvec2 uv=vUV*2.0-1.0;\r#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x));\r#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x));\r#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x));\r#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x));\r#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001));\r#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001));\r#endif\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const passCubePixelShader = { name, shader };\n//# sourceMappingURL=passCube.fragment.js.map","\nimport { PostProcess } from \"./postProcess.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport \"../Shaders/pass.fragment.js\";\nimport \"../Shaders/passCube.fragment.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\nimport { SerializationHelper } from \"../Misc/decorators.js\";\n/**\n * PassPostProcess which produces an output the same as it's input\n */\nexport class PassPostProcess extends PostProcess {\n /**\n * Gets a string identifying the name of the class\n * @returns \"PassPostProcess\" string\n */\n getClassName() {\n return \"PassPostProcess\";\n }\n /**\n * Creates the PassPostProcess\n * @param name The name of the effect.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType The type of texture to be used when performing the post processing.\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n constructor(name, options, camera = null, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) {\n super(name, \"pass\", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation);\n }\n /**\n * @internal\n */\n static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) {\n return SerializationHelper.Parse(() => {\n return new PassPostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, parsedPostProcess._engine, parsedPostProcess.reusable);\n }, parsedPostProcess, scene, rootUrl);\n }\n}\nRegisterClass(\"BABYLON.PassPostProcess\", PassPostProcess);\n/**\n * PassCubePostProcess which produces an output the same as it's input (which must be a cube texture)\n */\nexport class PassCubePostProcess extends PostProcess {\n /**\n * Gets or sets the cube face to display.\n * * 0 is +X\n * * 1 is -X\n * * 2 is +Y\n * * 3 is -Y\n * * 4 is +Z\n * * 5 is -Z\n */\n get face() {\n return this._face;\n }\n set face(value) {\n if (value < 0 || value > 5) {\n return;\n }\n this._face = value;\n switch (this._face) {\n case 0:\n this.updateEffect(\"#define POSITIVEX\");\n break;\n case 1:\n this.updateEffect(\"#define NEGATIVEX\");\n break;\n case 2:\n this.updateEffect(\"#define POSITIVEY\");\n break;\n case 3:\n this.updateEffect(\"#define NEGATIVEY\");\n break;\n case 4:\n this.updateEffect(\"#define POSITIVEZ\");\n break;\n case 5:\n this.updateEffect(\"#define NEGATIVEZ\");\n break;\n }\n }\n /**\n * Gets a string identifying the name of the class\n * @returns \"PassCubePostProcess\" string\n */\n getClassName() {\n return \"PassCubePostProcess\";\n }\n /**\n * Creates the PassCubePostProcess\n * @param name The name of the effect.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType The type of texture to be used when performing the post processing.\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n constructor(name, options, camera = null, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) {\n super(name, \"passCube\", null, null, options, camera, samplingMode, engine, reusable, \"#define POSITIVEX\", textureType, undefined, null, blockCompilation);\n this._face = 0;\n }\n /**\n * @internal\n */\n static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) {\n return SerializationHelper.Parse(() => {\n return new PassCubePostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, parsedPostProcess._engine, parsedPostProcess.reusable);\n }, parsedPostProcess, scene, rootUrl);\n }\n}\nEngine._RescalePostProcessFactory = (engine) => {\n return new PassPostProcess(\"rescale\", 1, null, 2, engine, false, 0);\n};\n//# sourceMappingURL=passPostProcess.js.map","import { PostProcess } from \"./postProcess.js\";\nimport \"../Shaders/anaglyph.fragment.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\n/**\n * Postprocess used to generate anaglyphic rendering\n */\nexport class AnaglyphPostProcess extends PostProcess {\n /**\n * Gets a string identifying the name of the class\n * @returns \"AnaglyphPostProcess\" string\n */\n getClassName() {\n return \"AnaglyphPostProcess\";\n }\n /**\n * Creates a new AnaglyphPostProcess\n * @param name defines postprocess name\n * @param options defines creation options or target ratio scale\n * @param rigCameras defines cameras using this postprocess\n * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)\n * @param engine defines hosting engine\n * @param reusable defines if the postprocess will be reused multiple times per frame\n */\n constructor(name, options, rigCameras, samplingMode, engine, reusable) {\n super(name, \"anaglyph\", null, [\"leftSampler\"], options, rigCameras[1], samplingMode, engine, reusable);\n this._passedProcess = rigCameras[0]._rigPostProcess;\n this.onApplyObservable.add((effect) => {\n effect.setTextureFromPostProcess(\"leftSampler\", this._passedProcess);\n });\n }\n}\nRegisterClass(\"BABYLON.AnaglyphPostProcess\", AnaglyphPostProcess);\n//# sourceMappingURL=anaglyphPostProcess.js.map","import { PassPostProcess } from \"../../PostProcesses/passPostProcess.js\";\nimport { AnaglyphPostProcess } from \"../../PostProcesses/anaglyphPostProcess.js\";\n/**\n * @internal\n */\nexport function setStereoscopicAnaglyphRigMode(camera) {\n camera._rigCameras[0]._rigPostProcess = new PassPostProcess(camera.name + \"_passthru\", 1.0, camera._rigCameras[0]);\n camera._rigCameras[1]._rigPostProcess = new AnaglyphPostProcess(camera.name + \"_anaglyph\", 1.0, camera._rigCameras);\n}\n//# sourceMappingURL=stereoscopicAnaglyphRigMode.js.map","import { Camera } from \"../../Cameras/camera.js\";\nimport { ArcRotateCamera } from \"../../Cameras/arcRotateCamera.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Node } from \"../../node.js\";\nimport { setStereoscopicAnaglyphRigMode } from \"../RigModes/stereoscopicAnaglyphRigMode.js\";\nNode.AddNodeConstructor(\"AnaglyphArcRotateCamera\", (name, scene, options) => {\n return () => new AnaglyphArcRotateCamera(name, 0, 0, 1.0, Vector3.Zero(), options.interaxial_distance, scene);\n});\n/**\n * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#anaglyph-cameras\n */\nexport class AnaglyphArcRotateCamera extends ArcRotateCamera {\n /**\n * Creates a new AnaglyphArcRotateCamera\n * @param name defines camera name\n * @param alpha defines alpha angle (in radians)\n * @param beta defines beta angle (in radians)\n * @param radius defines radius\n * @param target defines camera target\n * @param interaxialDistance defines distance between each color axis\n * @param scene defines the hosting scene\n */\n constructor(name, alpha, beta, radius, target, interaxialDistance, scene) {\n super(name, alpha, beta, radius, target, scene);\n this._setRigMode = setStereoscopicAnaglyphRigMode.bind(null, this);\n this.interaxialDistance = interaxialDistance;\n this.setCameraRigMode(Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });\n }\n /**\n * Gets camera class name\n * @returns AnaglyphArcRotateCamera\n */\n getClassName() {\n return \"AnaglyphArcRotateCamera\";\n }\n}\n//# sourceMappingURL=anaglyphArcRotateCamera.js.map","import { Camera } from \"../../Cameras/camera.js\";\nimport { FreeCamera } from \"../../Cameras/freeCamera.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Node } from \"../../node.js\";\nimport { setStereoscopicAnaglyphRigMode } from \"../RigModes/stereoscopicAnaglyphRigMode.js\";\nNode.AddNodeConstructor(\"AnaglyphFreeCamera\", (name, scene, options) => {\n return () => new AnaglyphFreeCamera(name, Vector3.Zero(), options.interaxial_distance, scene);\n});\n/**\n * Camera used to simulate anaglyphic rendering (based on FreeCamera)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#anaglyph-cameras\n */\nexport class AnaglyphFreeCamera extends FreeCamera {\n /**\n * Creates a new AnaglyphFreeCamera\n * @param name defines camera name\n * @param position defines initial position\n * @param interaxialDistance defines distance between each color axis\n * @param scene defines the hosting scene\n */\n constructor(name, position, interaxialDistance, scene) {\n super(name, position, scene);\n this._setRigMode = setStereoscopicAnaglyphRigMode.bind(null, this);\n this.interaxialDistance = interaxialDistance;\n this.setCameraRigMode(Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });\n }\n /**\n * Gets camera class name\n * @returns AnaglyphFreeCamera\n */\n getClassName() {\n return \"AnaglyphFreeCamera\";\n }\n}\n//# sourceMappingURL=anaglyphFreeCamera.js.map","import { Camera } from \"../../Cameras/camera.js\";\nimport { GamepadCamera } from \"../../Cameras/gamepadCamera.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Node } from \"../../node.js\";\nimport { setStereoscopicAnaglyphRigMode } from \"../RigModes/stereoscopicAnaglyphRigMode.js\";\nNode.AddNodeConstructor(\"AnaglyphGamepadCamera\", (name, scene, options) => {\n return () => new AnaglyphGamepadCamera(name, Vector3.Zero(), options.interaxial_distance, scene);\n});\n/**\n * Camera used to simulate anaglyphic rendering (based on GamepadCamera)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#anaglyph-cameras\n */\nexport class AnaglyphGamepadCamera extends GamepadCamera {\n /**\n * Creates a new AnaglyphGamepadCamera\n * @param name defines camera name\n * @param position defines initial position\n * @param interaxialDistance defines distance between each color axis\n * @param scene defines the hosting scene\n */\n constructor(name, position, interaxialDistance, scene) {\n super(name, position, scene);\n this._setRigMode = setStereoscopicAnaglyphRigMode.bind(null, this);\n this.interaxialDistance = interaxialDistance;\n this.setCameraRigMode(Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });\n }\n /**\n * Gets camera class name\n * @returns AnaglyphGamepadCamera\n */\n getClassName() {\n return \"AnaglyphGamepadCamera\";\n }\n}\n//# sourceMappingURL=anaglyphGamepadCamera.js.map","import { Camera } from \"../../Cameras/camera.js\";\nimport { UniversalCamera } from \"../../Cameras/universalCamera.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Node } from \"../../node.js\";\nimport { setStereoscopicAnaglyphRigMode } from \"../RigModes/stereoscopicAnaglyphRigMode.js\";\nNode.AddNodeConstructor(\"AnaglyphUniversalCamera\", (name, scene, options) => {\n return () => new AnaglyphUniversalCamera(name, Vector3.Zero(), options.interaxial_distance, scene);\n});\n/**\n * Camera used to simulate anaglyphic rendering (based on UniversalCamera)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#anaglyph-cameras\n */\nexport class AnaglyphUniversalCamera extends UniversalCamera {\n /**\n * Creates a new AnaglyphUniversalCamera\n * @param name defines camera name\n * @param position defines initial position\n * @param interaxialDistance defines distance between each color axis\n * @param scene defines the hosting scene\n */\n constructor(name, position, interaxialDistance, scene) {\n super(name, position, scene);\n this._setRigMode = setStereoscopicAnaglyphRigMode.bind(null, this);\n this.interaxialDistance = interaxialDistance;\n this.setCameraRigMode(Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });\n }\n /**\n * Gets camera class name\n * @returns AnaglyphUniversalCamera\n */\n getClassName() {\n return \"AnaglyphUniversalCamera\";\n }\n}\n//# sourceMappingURL=anaglyphUniversalCamera.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"stereoscopicInterlacePixelShader\";\nconst shader = `const vec3 TWO=vec3(2.0,2.0,2.0);\rvarying vec2 vUV;\runiform sampler2D camASampler;\runiform sampler2D textureSampler;\runiform vec2 stepSize;\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\r{\rbool useCamA;\rbool useCamB;\rvec2 texCoord1;\rvec2 texCoord2;\rvec3 frag1;\rvec3 frag2;\r#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ruseCamA=!useCamB;\rtexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\rtexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\r#else\n#ifdef IS_STEREOSCOPIC_INTERLACED\nfloat rowNum=floor(vUV.y/stepSize.y);\ruseCamA=mod(rowNum,2.0)==1.0;\ruseCamB=mod(rowNum,2.0)==0.0;\rtexCoord1=vec2(vUV.x,vUV.y);\rtexCoord2=vec2(vUV.x,vUV.y);\r#else\nuseCamB=vUV.y>0.5;\ruseCamA=!useCamB;\rtexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\rtexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\r#endif\n#endif\nif (useCamB){\rfrag1=texture2D(textureSampler,texCoord1).rgb;\rfrag2=texture2D(textureSampler,texCoord2).rgb;\r}else if (useCamA){\rfrag1=texture2D(camASampler ,texCoord1).rgb;\rfrag2=texture2D(camASampler ,texCoord2).rgb;\r}else {\rdiscard;\r}\rgl_FragColor=vec4((frag1+frag2)/TWO,1.0);\r}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const stereoscopicInterlacePixelShader = { name, shader };\n//# sourceMappingURL=stereoscopicInterlace.fragment.js.map","import { Vector2 } from \"../Maths/math.vector.js\";\nimport { PostProcess } from \"./postProcess.js\";\nimport \"../Shaders/stereoscopicInterlace.fragment.js\";\n/**\n * StereoscopicInterlacePostProcessI used to render stereo views from a rigged camera with support for alternate line interlacing\n */\nexport class StereoscopicInterlacePostProcessI extends PostProcess {\n /**\n * Gets a string identifying the name of the class\n * @returns \"StereoscopicInterlacePostProcessI\" string\n */\n getClassName() {\n return \"StereoscopicInterlacePostProcessI\";\n }\n /**\n * Initializes a StereoscopicInterlacePostProcessI\n * @param name The name of the effect.\n * @param rigCameras The rig cameras to be applied to the post process\n * @param isStereoscopicHoriz If the rendered results are horizontal or vertical\n * @param isStereoscopicInterlaced If the rendered results are alternate line interlaced\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n */\n constructor(name, rigCameras, isStereoscopicHoriz, isStereoscopicInterlaced, samplingMode, engine, reusable) {\n super(name, \"stereoscopicInterlace\", [\"stepSize\"], [\"camASampler\"], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicInterlaced ? \"#define IS_STEREOSCOPIC_INTERLACED 1\" : isStereoscopicHoriz ? \"#define IS_STEREOSCOPIC_HORIZ 1\" : undefined);\n this._passedProcess = rigCameras[0]._rigPostProcess;\n this._stepSize = new Vector2(1 / this.width, 1 / this.height);\n this.onSizeChangedObservable.add(() => {\n this._stepSize = new Vector2(1 / this.width, 1 / this.height);\n });\n this.onApplyObservable.add((effect) => {\n effect.setTextureFromPostProcess(\"camASampler\", this._passedProcess);\n effect.setFloat2(\"stepSize\", this._stepSize.x, this._stepSize.y);\n });\n }\n}\n/**\n * StereoscopicInterlacePostProcess used to render stereo views from a rigged camera\n */\nexport class StereoscopicInterlacePostProcess extends PostProcess {\n /**\n * Gets a string identifying the name of the class\n * @returns \"StereoscopicInterlacePostProcess\" string\n */\n getClassName() {\n return \"StereoscopicInterlacePostProcess\";\n }\n /**\n * Initializes a StereoscopicInterlacePostProcess\n * @param name The name of the effect.\n * @param rigCameras The rig cameras to be applied to the post process\n * @param isStereoscopicHoriz If the rendered results are horizontal or vertical\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n */\n constructor(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {\n super(name, \"stereoscopicInterlace\", [\"stepSize\"], [\"camASampler\"], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? \"#define IS_STEREOSCOPIC_HORIZ 1\" : undefined);\n this._passedProcess = rigCameras[0]._rigPostProcess;\n this._stepSize = new Vector2(1 / this.width, 1 / this.height);\n this.onSizeChangedObservable.add(() => {\n this._stepSize = new Vector2(1 / this.width, 1 / this.height);\n });\n this.onApplyObservable.add((effect) => {\n effect.setTextureFromPostProcess(\"camASampler\", this._passedProcess);\n effect.setFloat2(\"stepSize\", this._stepSize.x, this._stepSize.y);\n });\n }\n}\n//# sourceMappingURL=stereoscopicInterlacePostProcess.js.map","import { Camera } from \"../camera.js\";\nimport { Viewport } from \"../../Maths/math.viewport.js\";\nimport { PassPostProcess } from \"../../PostProcesses/passPostProcess.js\";\nimport { StereoscopicInterlacePostProcessI } from \"../../PostProcesses/stereoscopicInterlacePostProcess.js\";\n/**\n * @internal\n */\nexport function setStereoscopicRigMode(camera) {\n const isStereoscopicHoriz = camera.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || camera.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;\n const isCrossEye = camera.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;\n const isInterlaced = camera.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_INTERLACED;\n // Use post-processors for interlacing\n if (isInterlaced) {\n camera._rigCameras[0]._rigPostProcess = new PassPostProcess(camera.name + \"_passthru\", 1.0, camera._rigCameras[0]);\n camera._rigCameras[1]._rigPostProcess = new StereoscopicInterlacePostProcessI(camera.name + \"_stereoInterlace\", camera._rigCameras, false, true);\n }\n // Otherwise, create appropriate viewports\n else {\n camera._rigCameras[isCrossEye ? 1 : 0].viewport = new Viewport(0, 0, isStereoscopicHoriz ? 0.5 : 1.0, isStereoscopicHoriz ? 1.0 : 0.5);\n camera._rigCameras[isCrossEye ? 0 : 1].viewport = new Viewport(isStereoscopicHoriz ? 0.5 : 0, isStereoscopicHoriz ? 0 : 0.5, isStereoscopicHoriz ? 0.5 : 1.0, isStereoscopicHoriz ? 1.0 : 0.5);\n }\n}\n//# sourceMappingURL=stereoscopicRigMode.js.map","import { Camera } from \"../../Cameras/camera.js\";\nimport { ArcRotateCamera } from \"../../Cameras/arcRotateCamera.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Node } from \"../../node.js\";\nimport { setStereoscopicRigMode } from \"../RigModes/stereoscopicRigMode.js\";\nNode.AddNodeConstructor(\"StereoscopicArcRotateCamera\", (name, scene, options) => {\n return () => new StereoscopicArcRotateCamera(name, 0, 0, 1.0, Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene);\n});\n/**\n * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras\n */\nexport class StereoscopicArcRotateCamera extends ArcRotateCamera {\n /**\n * Creates a new StereoscopicArcRotateCamera\n * @param name defines camera name\n * @param alpha defines alpha angle (in radians)\n * @param beta defines beta angle (in radians)\n * @param radius defines radius\n * @param target defines camera target\n * @param interaxialDistance defines distance between each color axis\n * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under\n * @param scene defines the hosting scene\n */\n constructor(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {\n super(name, alpha, beta, radius, target, scene);\n this._setRigMode = setStereoscopicRigMode.bind(null, this);\n this.interaxialDistance = interaxialDistance;\n this.isStereoscopicSideBySide = isStereoscopicSideBySide;\n this.setCameraRigMode(isStereoscopicSideBySide ? Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, {\n interaxialDistance: interaxialDistance,\n });\n }\n /**\n * Gets camera class name\n * @returns StereoscopicArcRotateCamera\n */\n getClassName() {\n return \"StereoscopicArcRotateCamera\";\n }\n}\n//# sourceMappingURL=stereoscopicArcRotateCamera.js.map","import { Camera } from \"../../Cameras/camera.js\";\nimport { FreeCamera } from \"../../Cameras/freeCamera.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Node } from \"../../node.js\";\nimport { setStereoscopicRigMode } from \"../RigModes/stereoscopicRigMode.js\";\nNode.AddNodeConstructor(\"StereoscopicFreeCamera\", (name, scene, options) => {\n return () => new StereoscopicFreeCamera(name, Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene);\n});\n/**\n * Camera used to simulate stereoscopic rendering (based on FreeCamera)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras\n */\nexport class StereoscopicFreeCamera extends FreeCamera {\n /**\n * Creates a new StereoscopicFreeCamera\n * @param name defines camera name\n * @param position defines initial position\n * @param interaxialDistance defines distance between each color axis\n * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under\n * @param scene defines the hosting scene\n */\n constructor(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {\n super(name, position, scene);\n this._setRigMode = setStereoscopicRigMode.bind(null, this);\n this.interaxialDistance = interaxialDistance;\n this.isStereoscopicSideBySide = isStereoscopicSideBySide;\n this.setCameraRigMode(isStereoscopicSideBySide ? Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, {\n interaxialDistance: interaxialDistance,\n });\n }\n /**\n * Gets camera class name\n * @returns StereoscopicFreeCamera\n */\n getClassName() {\n return \"StereoscopicFreeCamera\";\n }\n}\n//# sourceMappingURL=stereoscopicFreeCamera.js.map","import { Camera } from \"../../Cameras/camera.js\";\nimport { GamepadCamera } from \"../../Cameras/gamepadCamera.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Node } from \"../../node.js\";\nimport { setStereoscopicRigMode } from \"../RigModes/stereoscopicRigMode.js\";\nNode.AddNodeConstructor(\"StereoscopicGamepadCamera\", (name, scene, options) => {\n return () => new StereoscopicGamepadCamera(name, Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene);\n});\n/**\n * Camera used to simulate stereoscopic rendering (based on GamepadCamera)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras\n */\nexport class StereoscopicGamepadCamera extends GamepadCamera {\n /**\n * Creates a new StereoscopicGamepadCamera\n * @param name defines camera name\n * @param position defines initial position\n * @param interaxialDistance defines distance between each color axis\n * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under\n * @param scene defines the hosting scene\n */\n constructor(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {\n super(name, position, scene);\n this._setRigMode = setStereoscopicRigMode.bind(null, this);\n this.interaxialDistance = interaxialDistance;\n this.isStereoscopicSideBySide = isStereoscopicSideBySide;\n this.setCameraRigMode(isStereoscopicSideBySide ? Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, {\n interaxialDistance: interaxialDistance,\n });\n }\n /**\n * Gets camera class name\n * @returns StereoscopicGamepadCamera\n */\n getClassName() {\n return \"StereoscopicGamepadCamera\";\n }\n}\n//# sourceMappingURL=stereoscopicGamepadCamera.js.map","import { Camera } from \"../../Cameras/camera.js\";\nimport { UniversalCamera } from \"../../Cameras/universalCamera.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Node } from \"../../node.js\";\nimport { setStereoscopicRigMode } from \"../RigModes/stereoscopicRigMode.js\";\nNode.AddNodeConstructor(\"StereoscopicFreeCamera\", (name, scene, options) => {\n return () => new StereoscopicUniversalCamera(name, Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene);\n});\n/**\n * Camera used to simulate stereoscopic rendering (based on UniversalCamera)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras\n */\nexport class StereoscopicUniversalCamera extends UniversalCamera {\n /**\n * Creates a new StereoscopicUniversalCamera\n * @param name defines camera name\n * @param position defines initial position\n * @param interaxialDistance defines distance between each color axis\n * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under\n * @param scene defines the hosting scene\n */\n constructor(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {\n super(name, position, scene);\n this._setRigMode = setStereoscopicRigMode.bind(null, this);\n this.interaxialDistance = interaxialDistance;\n this.isStereoscopicSideBySide = isStereoscopicSideBySide;\n this.setCameraRigMode(isStereoscopicSideBySide ? Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, {\n interaxialDistance: interaxialDistance,\n });\n }\n /**\n * Gets camera class name\n * @returns StereoscopicUniversalCamera\n */\n getClassName() {\n return \"StereoscopicUniversalCamera\";\n }\n}\n//# sourceMappingURL=stereoscopicUniversalCamera.js.map","import { Camera } from \"../../Cameras/camera.js\";\nimport { UniversalCamera } from \"../../Cameras/universalCamera.js\";\nimport { Matrix, Vector3 } from \"../../Maths/math.vector.js\";\nimport { TargetCamera } from \"../targetCamera.js\";\nimport { TransformNode } from \"../../Meshes/transformNode.js\";\nimport { Viewport } from \"../../Maths/math.viewport.js\";\n/**\n * Camera used to simulate stereoscopic rendering on real screens (based on UniversalCamera)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras\n */\nexport class StereoscopicScreenUniversalCamera extends UniversalCamera {\n set distanceBetweenEyes(newValue) {\n this._distanceBetweenEyes = newValue;\n }\n /**\n * distance between the eyes\n */\n get distanceBetweenEyes() {\n return this._distanceBetweenEyes;\n }\n set distanceToProjectionPlane(newValue) {\n this._distanceToProjectionPlane = newValue;\n }\n /**\n * Distance to projection plane (should be the same units the like distance between the eyes)\n */\n get distanceToProjectionPlane() {\n return this._distanceToProjectionPlane;\n }\n /**\n * Creates a new StereoscopicScreenUniversalCamera\n * @param name defines camera name\n * @param position defines initial position\n * @param scene defines the hosting scene\n * @param distanceToProjectionPlane defines distance between each color axis. The rig cameras will receive this as their negative z position!\n * @param distanceBetweenEyes defines is stereoscopic is done side by side or over under\n */\n constructor(name, position, scene, distanceToProjectionPlane = 1, distanceBetweenEyes = 0.065) {\n super(name, position, scene);\n this._distanceBetweenEyes = distanceBetweenEyes;\n this._distanceToProjectionPlane = distanceToProjectionPlane;\n this.setCameraRigMode(Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL, {\n stereoHalfAngle: 0,\n });\n this._cameraRigParams.stereoHalfAngle = 0;\n this._cameraRigParams.interaxialDistance = distanceBetweenEyes;\n }\n /**\n * Gets camera class name\n * @returns StereoscopicScreenUniversalCamera\n */\n getClassName() {\n return \"StereoscopicUniversalCamera\";\n }\n /**\n * @internal\n */\n createRigCamera(name) {\n const camera = new TargetCamera(name, Vector3.Zero(), this.getScene());\n const transform = new TransformNode(\"tm_\" + name, this.getScene());\n camera.parent = transform;\n transform.setPivotMatrix(Matrix.Identity(), false);\n camera.isRigCamera = true;\n camera.rigParent = this;\n return camera;\n }\n /**\n * @internal\n */\n _updateRigCameras() {\n for (let cameraIndex = 0; cameraIndex < this._rigCameras.length; cameraIndex++) {\n const cam = this._rigCameras[cameraIndex];\n cam.minZ = this.minZ;\n cam.maxZ = this.maxZ;\n cam.fov = this.fov;\n cam.upVector.copyFrom(this.upVector);\n if (cam.rotationQuaternion) {\n cam.rotationQuaternion.copyFrom(this.rotationQuaternion);\n }\n else {\n cam.rotation.copyFrom(this.rotation);\n }\n this._updateCamera(this._rigCameras[cameraIndex], cameraIndex);\n }\n }\n _updateCamera(camera, cameraIndex) {\n const b = this.distanceBetweenEyes / 2;\n const z = b / this.distanceToProjectionPlane;\n camera.position.copyFrom(this.position);\n camera.position.addInPlaceFromFloats(cameraIndex === 0 ? -b : b, 0, -this._distanceToProjectionPlane);\n const transform = camera.parent;\n const m = transform.getPivotMatrix();\n m.setTranslationFromFloats(cameraIndex === 0 ? b : -b, 0, 0);\n m.setRowFromFloats(2, cameraIndex === 0 ? z : -z, 0, 1, 0);\n transform.setPivotMatrix(m, false);\n }\n _setRigMode() {\n this._rigCameras[0].viewport = new Viewport(0, 0, 0.5, 1);\n this._rigCameras[1].viewport = new Viewport(0.5, 0, 0.5, 1.0);\n for (let cameraIndex = 0; cameraIndex < this._rigCameras.length; cameraIndex++) {\n this._updateCamera(this._rigCameras[cameraIndex], cameraIndex);\n }\n }\n}\n//# sourceMappingURL=stereoscopicScreenUniversalCamera.js.map","import { Matrix } from \"../../Maths/math.vector.js\";\n/**\n * This represents all the required metrics to create a VR camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#device-orientation-camera\n */\nexport class VRCameraMetrics {\n constructor() {\n /**\n * Define if the current vr camera should compensate the distortion of the lens or not.\n */\n this.compensateDistortion = true;\n /**\n * Defines if multiview should be enabled when rendering (Default: false)\n */\n this.multiviewEnabled = false;\n }\n /**\n * Gets the rendering aspect ratio based on the provided resolutions.\n */\n get aspectRatio() {\n return this.hResolution / (2 * this.vResolution);\n }\n /**\n * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.\n */\n get aspectRatioFov() {\n return 2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance));\n }\n /**\n * @internal\n */\n get leftHMatrix() {\n const meters = this.hScreenSize / 4 - this.lensSeparationDistance / 2;\n const h = (4 * meters) / this.hScreenSize;\n return Matrix.Translation(h, 0, 0);\n }\n /**\n * @internal\n */\n get rightHMatrix() {\n const meters = this.hScreenSize / 4 - this.lensSeparationDistance / 2;\n const h = (4 * meters) / this.hScreenSize;\n return Matrix.Translation(-h, 0, 0);\n }\n /**\n * @internal\n */\n get leftPreViewMatrix() {\n return Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);\n }\n /**\n * @internal\n */\n get rightPreViewMatrix() {\n return Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);\n }\n /**\n * Get the default VRMetrics based on the most generic setup.\n * @returns the default vr metrics\n */\n static GetDefault() {\n const result = new VRCameraMetrics();\n result.hResolution = 1280;\n result.vResolution = 800;\n result.hScreenSize = 0.149759993;\n result.vScreenSize = 0.0935999975;\n result.vScreenCenter = 0.0467999987;\n result.eyeToScreenDistance = 0.0410000011;\n result.lensSeparationDistance = 0.063500002;\n result.interpupillaryDistance = 0.064000003;\n result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];\n result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];\n result.postProcessScaleFactor = 1.714605507808412;\n result.lensCenterOffset = 0.151976421;\n return result;\n }\n}\n//# sourceMappingURL=vrCameraMetrics.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"vrDistortionCorrectionPixelShader\";\nconst shader = `varying vec2 vUV;\runiform sampler2D textureSampler;\runiform vec2 LensCenter;\runiform vec2 Scale;\runiform vec2 ScaleIn;\runiform vec4 HmdWarpParam;\rvec2 HmdWarp(vec2 in01) {\rvec2 theta=(in01-LensCenter)*ScaleIn; \rfloat rSq=theta.x*theta.x+theta.y*theta.y;\rvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\rreturn LensCenter+Scale*rvector;\r}\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\r{\rvec2 tc=HmdWarp(vUV);\rif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\rgl_FragColor=vec4(0.0,0.0,0.0,0.0);\relse{\rgl_FragColor=texture2D(textureSampler,tc);\r}\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const vrDistortionCorrectionPixelShader = { name, shader };\n//# sourceMappingURL=vrDistortionCorrection.fragment.js.map","import { Vector2 } from \"../Maths/math.vector.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { PostProcess } from \"./postProcess.js\";\nimport \"../Shaders/vrDistortionCorrection.fragment.js\";\n/**\n * VRDistortionCorrectionPostProcess used for mobile VR\n */\nexport class VRDistortionCorrectionPostProcess extends PostProcess {\n /**\n * Gets a string identifying the name of the class\n * @returns \"VRDistortionCorrectionPostProcess\" string\n */\n getClassName() {\n return \"VRDistortionCorrectionPostProcess\";\n }\n /**\n * Initializes the VRDistortionCorrectionPostProcess\n * @param name The name of the effect.\n * @param camera The camera to apply the render pass to.\n * @param isRightEye If this is for the right eye distortion\n * @param vrMetrics All the required metrics for the VR camera\n */\n constructor(name, camera, isRightEye, vrMetrics) {\n super(name, \"vrDistortionCorrection\", [\"LensCenter\", \"Scale\", \"ScaleIn\", \"HmdWarpParam\"], null, vrMetrics.postProcessScaleFactor, camera, Texture.BILINEAR_SAMPLINGMODE);\n this._isRightEye = isRightEye;\n this._distortionFactors = vrMetrics.distortionK;\n this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;\n this._lensCenterOffset = vrMetrics.lensCenterOffset;\n this.adaptScaleToCurrentViewport = true;\n this.onSizeChangedObservable.add(() => {\n this._scaleIn = new Vector2(2, 2 / this.aspectRatio);\n this._scaleFactor = new Vector2(0.5 * (1 / this._postProcessScaleFactor), 0.5 * (1 / this._postProcessScaleFactor) * this.aspectRatio);\n this._lensCenter = new Vector2(this._isRightEye ? 0.5 - this._lensCenterOffset * 0.5 : 0.5 + this._lensCenterOffset * 0.5, 0.5);\n });\n this.onApplyObservable.add((effect) => {\n effect.setFloat2(\"LensCenter\", this._lensCenter.x, this._lensCenter.y);\n effect.setFloat2(\"Scale\", this._scaleFactor.x, this._scaleFactor.y);\n effect.setFloat2(\"ScaleIn\", this._scaleIn.x, this._scaleIn.y);\n effect.setFloat4(\"HmdWarpParam\", this._distortionFactors[0], this._distortionFactors[1], this._distortionFactors[2], this._distortionFactors[3]);\n });\n }\n}\n//# sourceMappingURL=vrDistortionCorrectionPostProcess.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"vrMultiviewToSingleviewPixelShader\";\nconst shader = `precision mediump sampler2DArray;\rvarying vec2 vUV;\runiform sampler2DArray multiviewSampler;\runiform int imageIndex;\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\r{\rgl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const vrMultiviewToSingleviewPixelShader = { name, shader };\n//# sourceMappingURL=vrMultiviewToSingleview.fragment.js.map","import { RenderTargetTexture } from \"../Textures/renderTargetTexture.js\";\n\n/**\n * Renders to multiple views with a single draw call\n * @see https://www.khronos.org/registry/webgl/extensions/OVR_multiview2/\n */\nexport class MultiviewRenderTarget extends RenderTargetTexture {\n set samples(value) {\n // We override this setter because multisampling is handled by framebufferTextureMultisampleMultiviewOVR\n this._samples = value;\n }\n get samples() {\n return this._samples;\n }\n /**\n * Creates a multiview render target\n * @param scene scene used with the render target\n * @param size the size of the render target (used for each view)\n */\n constructor(scene, size = 512) {\n super(\"multiview rtt\", size, scene, false, true, 0, false, undefined, false, false, true, undefined, true);\n this._renderTarget = this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(), this.getRenderHeight());\n this._texture = this._renderTarget.texture;\n this._texture.isMultiview = true;\n this._texture.format = 5;\n this.samples = this._getEngine().getCaps().maxSamples || this.samples;\n this._texture.samples = this._samples;\n }\n /**\n * @internal\n */\n _bindFrameBuffer() {\n if (!this._renderTarget) {\n return;\n }\n this.getScene().getEngine().bindMultiviewFramebuffer(this._renderTarget);\n }\n /**\n * Gets the number of views the corresponding to the texture (eg. a MultiviewRenderTarget will have > 1)\n * @returns the view count\n */\n getViewCount() {\n return 2;\n }\n}\n//# sourceMappingURL=MultiviewRenderTarget.js.map","import { Camera } from \"../../Cameras/camera.js\";\nimport { Engine } from \"../../Engines/engine.js\";\nimport { Scene } from \"../../scene.js\";\nimport { InternalTexture, InternalTextureSource } from \"../../Materials/Textures/internalTexture.js\";\nimport { Matrix, TmpVectors } from \"../../Maths/math.vector.js\";\nimport { UniformBuffer } from \"../../Materials/uniformBuffer.js\";\nimport { MultiviewRenderTarget } from \"../../Materials/Textures/MultiviewRenderTarget.js\";\nimport { Frustum } from \"../../Maths/math.frustum.js\";\nEngine.prototype.createMultiviewRenderTargetTexture = function (width, height, colorTexture, depthStencilTexture) {\n const gl = this._gl;\n if (!this.getCaps().multiview) {\n throw \"Multiview is not supported\";\n }\n const rtWrapper = this._createHardwareRenderTargetWrapper(false, false, { width, height });\n rtWrapper._framebuffer = gl.createFramebuffer();\n const internalTexture = new InternalTexture(this, InternalTextureSource.Unknown, true);\n internalTexture.width = width;\n internalTexture.height = height;\n internalTexture.isMultiview = true;\n if (!colorTexture) {\n colorTexture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D_ARRAY, colorTexture);\n gl.texStorage3D(gl.TEXTURE_2D_ARRAY, 1, gl.RGBA8, width, height, 2);\n }\n rtWrapper._colorTextureArray = colorTexture;\n if (!depthStencilTexture) {\n depthStencilTexture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D_ARRAY, depthStencilTexture);\n gl.texStorage3D(gl.TEXTURE_2D_ARRAY, 1, gl.DEPTH24_STENCIL8, width, height, 2);\n }\n rtWrapper._depthStencilTextureArray = depthStencilTexture;\n internalTexture.isReady = true;\n rtWrapper.setTextures(internalTexture);\n rtWrapper._depthStencilTexture = internalTexture;\n return rtWrapper;\n};\nEngine.prototype.bindMultiviewFramebuffer = function (_multiviewTexture) {\n const multiviewTexture = _multiviewTexture;\n const gl = this._gl;\n const ext = this.getCaps().oculusMultiview || this.getCaps().multiview;\n this.bindFramebuffer(multiviewTexture, undefined, undefined, undefined, true);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, multiviewTexture._framebuffer);\n if (multiviewTexture._colorTextureArray && multiviewTexture._depthStencilTextureArray) {\n if (this.getCaps().oculusMultiview) {\n ext.framebufferTextureMultisampleMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, multiviewTexture._colorTextureArray, 0, multiviewTexture.samples, 0, 2);\n ext.framebufferTextureMultisampleMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, multiviewTexture._depthStencilTextureArray, 0, multiviewTexture.samples, 0, 2);\n }\n else {\n ext.framebufferTextureMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, multiviewTexture._colorTextureArray, 0, 0, 2);\n ext.framebufferTextureMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, multiviewTexture._depthStencilTextureArray, 0, 0, 2);\n }\n }\n else {\n throw \"Invalid multiview frame buffer\";\n }\n};\nEngine.prototype.bindSpaceWarpFramebuffer = function (_spaceWarpTexture) {\n const spaceWarpTexture = _spaceWarpTexture;\n const gl = this._gl;\n const ext = this.getCaps().oculusMultiview || this.getCaps().multiview;\n this.bindFramebuffer(spaceWarpTexture, undefined, undefined, undefined, true);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, spaceWarpTexture._framebuffer);\n if (spaceWarpTexture._colorTextureArray && spaceWarpTexture._depthStencilTextureArray) {\n ext.framebufferTextureMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, spaceWarpTexture._colorTextureArray, 0, 0, 2);\n ext.framebufferTextureMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.DEPTH_ATTACHMENT, spaceWarpTexture._depthStencilTextureArray, 0, 0, 2);\n }\n else {\n throw new Error(\"Invalid Space Warp framebuffer\");\n }\n};\nCamera.prototype._useMultiviewToSingleView = false;\nCamera.prototype._multiviewTexture = null;\nCamera.prototype._resizeOrCreateMultiviewTexture = function (width, height) {\n if (!this._multiviewTexture) {\n this._multiviewTexture = new MultiviewRenderTarget(this.getScene(), { width: width, height: height });\n }\n else if (this._multiviewTexture.getRenderWidth() != width || this._multiviewTexture.getRenderHeight() != height) {\n this._multiviewTexture.dispose();\n this._multiviewTexture = new MultiviewRenderTarget(this.getScene(), { width: width, height: height });\n }\n};\nfunction createMultiviewUbo(engine, name) {\n const ubo = new UniformBuffer(engine, undefined, true, name);\n ubo.addUniform(\"viewProjection\", 16);\n ubo.addUniform(\"viewProjectionR\", 16);\n ubo.addUniform(\"view\", 16);\n ubo.addUniform(\"projection\", 16);\n ubo.addUniform(\"vEyePosition\", 4);\n return ubo;\n}\nconst currentCreateSceneUniformBuffer = Scene.prototype.createSceneUniformBuffer;\nScene.prototype._transformMatrixR = Matrix.Zero();\nScene.prototype._multiviewSceneUbo = null;\nScene.prototype._createMultiviewUbo = function () {\n this._multiviewSceneUbo = createMultiviewUbo(this.getEngine(), \"scene_multiview\");\n};\nScene.prototype.createSceneUniformBuffer = function (name) {\n if (this._multiviewSceneUbo) {\n return createMultiviewUbo(this.getEngine(), name);\n }\n return currentCreateSceneUniformBuffer.bind(this)(name);\n};\nScene.prototype._updateMultiviewUbo = function (viewR, projectionR) {\n if (viewR && projectionR) {\n viewR.multiplyToRef(projectionR, this._transformMatrixR);\n }\n if (viewR && projectionR) {\n viewR.multiplyToRef(projectionR, TmpVectors.Matrix[0]);\n Frustum.GetRightPlaneToRef(TmpVectors.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane\n }\n if (this._multiviewSceneUbo) {\n this._multiviewSceneUbo.updateMatrix(\"viewProjection\", this.getTransformMatrix());\n this._multiviewSceneUbo.updateMatrix(\"viewProjectionR\", this._transformMatrixR);\n this._multiviewSceneUbo.updateMatrix(\"view\", this._viewMatrix);\n this._multiviewSceneUbo.updateMatrix(\"projection\", this._projectionMatrix);\n }\n};\nScene.prototype._renderMultiviewToSingleView = function (camera) {\n // Multiview is only able to be displayed directly for API's such as webXR\n // This displays a multiview image by rendering to the multiview image and then\n // copying the result into the sub cameras instead of rendering them and proceeding as normal from there\n // Render to a multiview texture\n camera._resizeOrCreateMultiviewTexture(camera._rigPostProcess && camera._rigPostProcess && camera._rigPostProcess.width > 0 ? camera._rigPostProcess.width : this.getEngine().getRenderWidth(true), camera._rigPostProcess && camera._rigPostProcess && camera._rigPostProcess.height > 0 ? camera._rigPostProcess.height : this.getEngine().getRenderHeight(true));\n if (!this._multiviewSceneUbo) {\n this._createMultiviewUbo();\n }\n camera.outputRenderTarget = camera._multiviewTexture;\n this._renderForCamera(camera);\n camera.outputRenderTarget = null;\n // Consume the multiview texture through a shader for each eye\n for (let index = 0; index < camera._rigCameras.length; index++) {\n const engine = this.getEngine();\n this._activeCamera = camera._rigCameras[index];\n engine.setViewport(this._activeCamera.viewport);\n if (this.postProcessManager) {\n this.postProcessManager._prepareFrame();\n this.postProcessManager._finalizeFrame(this._activeCamera.isIntermediate);\n }\n }\n};\n//# sourceMappingURL=engine.multiview.js.map","import { Matrix } from \"../../Maths/math.vector.js\";\nimport { VRDistortionCorrectionPostProcess } from \"../../PostProcesses/vrDistortionCorrectionPostProcess.js\";\nimport { VRMultiviewToSingleviewPostProcess } from \"../../PostProcesses/vrMultiviewToSingleviewPostProcess.js\";\nimport { VRCameraMetrics } from \"../VR/vrCameraMetrics.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { Viewport } from \"../../Maths/math.viewport.js\";\n/**\n * @internal\n */\nexport function setVRRigMode(camera, rigParams) {\n const metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();\n camera._rigCameras[0]._cameraRigParams.vrMetrics = metrics;\n camera._rigCameras[0].viewport = new Viewport(0, 0, 0.5, 1.0);\n camera._rigCameras[0]._cameraRigParams.vrWorkMatrix = new Matrix();\n camera._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;\n camera._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;\n camera._rigCameras[0].getProjectionMatrix = camera._rigCameras[0]._getVRProjectionMatrix;\n camera._rigCameras[1]._cameraRigParams.vrMetrics = metrics;\n camera._rigCameras[1].viewport = new Viewport(0.5, 0, 0.5, 1.0);\n camera._rigCameras[1]._cameraRigParams.vrWorkMatrix = new Matrix();\n camera._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;\n camera._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;\n camera._rigCameras[1].getProjectionMatrix = camera._rigCameras[1]._getVRProjectionMatrix;\n // For multiview on a webVR camera\n // First multiview will be rendered to camera._multiviewTexture\n // Then this postprocess will run on each eye to copy the right texture to each eye\n if (metrics.multiviewEnabled) {\n if (!camera.getScene().getEngine().getCaps().multiview) {\n Logger.Warn(\"Multiview is not supported, falling back to standard rendering\");\n metrics.multiviewEnabled = false;\n }\n else {\n camera._useMultiviewToSingleView = true;\n camera._rigPostProcess = new VRMultiviewToSingleviewPostProcess(\"VRMultiviewToSingleview\", camera, metrics.postProcessScaleFactor);\n }\n }\n if (metrics.compensateDistortion) {\n camera._rigCameras[0]._rigPostProcess = new VRDistortionCorrectionPostProcess(\"VR_Distort_Compensation_Left\", camera._rigCameras[0], false, metrics);\n camera._rigCameras[1]._rigPostProcess = new VRDistortionCorrectionPostProcess(\"VR_Distort_Compensation_Right\", camera._rigCameras[1], true, metrics);\n }\n}\n//# sourceMappingURL=vrRigMode.js.map","import { Texture } from \"../Materials/Textures/texture.js\";\nimport { PostProcess } from \"./postProcess.js\";\nimport \"../Shaders/vrMultiviewToSingleview.fragment.js\";\nimport \"../Engines/Extensions/engine.multiview.js\";\n/**\n * VRMultiviewToSingleview used to convert multiview texture arrays to standard textures for scenarios such as webVR\n * This will not be used for webXR as it supports displaying texture arrays directly\n */\nexport class VRMultiviewToSingleviewPostProcess extends PostProcess {\n /**\n * Gets a string identifying the name of the class\n * @returns \"VRMultiviewToSingleviewPostProcess\" string\n */\n getClassName() {\n return \"VRMultiviewToSingleviewPostProcess\";\n }\n /**\n * Initializes a VRMultiviewToSingleview\n * @param name name of the post process\n * @param camera camera to be applied to\n * @param scaleFactor scaling factor to the size of the output texture\n */\n constructor(name, camera, scaleFactor) {\n super(name, \"vrMultiviewToSingleview\", [\"imageIndex\"], [\"multiviewSampler\"], scaleFactor, camera, Texture.BILINEAR_SAMPLINGMODE);\n const cam = camera !== null && camera !== void 0 ? camera : this.getCamera();\n this.onSizeChangedObservable.add(() => { });\n this.onApplyObservable.add((effect) => {\n if (cam._scene.activeCamera && cam._scene.activeCamera.isLeftCamera) {\n effect.setInt(\"imageIndex\", 0);\n }\n else {\n effect.setInt(\"imageIndex\", 1);\n }\n effect.setTexture(\"multiviewSampler\", cam._multiviewTexture);\n });\n }\n}\n//# sourceMappingURL=vrMultiviewToSingleviewPostProcess.js.map","import { Camera } from \"../../Cameras/camera.js\";\nimport { ArcRotateCamera } from \"../../Cameras/arcRotateCamera.js\";\nimport { VRCameraMetrics } from \"./vrCameraMetrics.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Node } from \"../../node.js\";\nimport { setVRRigMode } from \"../RigModes/vrRigMode.js\";\nimport \"../Inputs/arcRotateCameraVRDeviceOrientationInput.js\";\nNode.AddNodeConstructor(\"VRDeviceOrientationArcRotateCamera\", (name, scene) => {\n return () => new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, Vector3.Zero(), scene);\n});\n/**\n * Camera used to simulate VR rendering (based on ArcRotateCamera)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#vr-device-orientation-cameras\n */\nexport class VRDeviceOrientationArcRotateCamera extends ArcRotateCamera {\n /**\n * Creates a new VRDeviceOrientationArcRotateCamera\n * @param name defines camera name\n * @param alpha defines the camera rotation along the longitudinal axis\n * @param beta defines the camera rotation along the latitudinal axis\n * @param radius defines the camera distance from its target\n * @param target defines the camera target\n * @param scene defines the scene the camera belongs to\n * @param compensateDistortion defines if the camera needs to compensate the lens distortion\n * @param vrCameraMetrics defines the vr metrics associated to the camera\n */\n constructor(name, alpha, beta, radius, target, scene, compensateDistortion = true, vrCameraMetrics = VRCameraMetrics.GetDefault()) {\n super(name, alpha, beta, radius, target, scene);\n this._setRigMode = setVRRigMode.bind(null, this);\n vrCameraMetrics.compensateDistortion = compensateDistortion;\n this.setCameraRigMode(Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });\n this.inputs.addVRDeviceOrientation();\n }\n /**\n * Gets camera class name\n * @returns VRDeviceOrientationArcRotateCamera\n */\n getClassName() {\n return \"VRDeviceOrientationArcRotateCamera\";\n }\n}\n//# sourceMappingURL=vrDeviceOrientationArcRotateCamera.js.map","import { Camera } from \"../../Cameras/camera.js\";\nimport { DeviceOrientationCamera } from \"../../Cameras/deviceOrientationCamera.js\";\nimport { VRCameraMetrics } from \"./vrCameraMetrics.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Node } from \"../../node.js\";\nimport { setVRRigMode } from \"../RigModes/vrRigMode.js\";\nNode.AddNodeConstructor(\"VRDeviceOrientationFreeCamera\", (name, scene) => {\n return () => new VRDeviceOrientationFreeCamera(name, Vector3.Zero(), scene);\n});\n/**\n * Camera used to simulate VR rendering (based on FreeCamera)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#vr-device-orientation-cameras\n */\nexport class VRDeviceOrientationFreeCamera extends DeviceOrientationCamera {\n /**\n * Creates a new VRDeviceOrientationFreeCamera\n * @param name defines camera name\n * @param position defines the start position of the camera\n * @param scene defines the scene the camera belongs to\n * @param compensateDistortion defines if the camera needs to compensate the lens distortion\n * @param vrCameraMetrics defines the vr metrics associated to the camera\n */\n constructor(name, position, scene, compensateDistortion = true, vrCameraMetrics = VRCameraMetrics.GetDefault()) {\n super(name, position, scene);\n this._setRigMode = setVRRigMode.bind(null, this);\n vrCameraMetrics.compensateDistortion = compensateDistortion;\n this.setCameraRigMode(Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });\n }\n /**\n * Gets camera class name\n * @returns VRDeviceOrientationFreeCamera\n */\n getClassName() {\n return \"VRDeviceOrientationFreeCamera\";\n }\n}\n//# sourceMappingURL=vrDeviceOrientationFreeCamera.js.map","import { VRDeviceOrientationFreeCamera } from \"./vrDeviceOrientationFreeCamera.js\";\nimport { VRCameraMetrics } from \"./vrCameraMetrics.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Node } from \"../../node.js\";\nimport { setVRRigMode } from \"../RigModes/vrRigMode.js\";\nimport \"../../Gamepads/gamepadSceneComponent.js\";\nNode.AddNodeConstructor(\"VRDeviceOrientationGamepadCamera\", (name, scene) => {\n return () => new VRDeviceOrientationGamepadCamera(name, Vector3.Zero(), scene);\n});\n/**\n * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_introduction#vr-device-orientation-cameras\n */\nexport class VRDeviceOrientationGamepadCamera extends VRDeviceOrientationFreeCamera {\n /**\n * Creates a new VRDeviceOrientationGamepadCamera\n * @param name defines camera name\n * @param position defines the start position of the camera\n * @param scene defines the scene the camera belongs to\n * @param compensateDistortion defines if the camera needs to compensate the lens distortion\n * @param vrCameraMetrics defines the vr metrics associated to the camera\n */\n constructor(name, position, scene, compensateDistortion = true, vrCameraMetrics = VRCameraMetrics.GetDefault()) {\n super(name, position, scene, compensateDistortion, vrCameraMetrics);\n this._setRigMode = setVRRigMode.bind(null, this);\n this.inputs.addGamepad();\n }\n /**\n * Gets camera class name\n * @returns VRDeviceOrientationGamepadCamera\n */\n getClassName() {\n return \"VRDeviceOrientationGamepadCamera\";\n }\n}\n//# sourceMappingURL=vrDeviceOrientationGamepadCamera.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serializeAsColor3, serializeAsVector3 } from \"../Misc/decorators.js\";\nimport { Matrix, Vector3 } from \"../Maths/math.vector.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { Node } from \"../node.js\";\nimport { Light } from \"./light.js\";\nNode.AddNodeConstructor(\"Light_Type_3\", (name, scene) => {\n return () => new HemisphericLight(name, Vector3.Zero(), scene);\n});\n/**\n * The HemisphericLight simulates the ambient environment light,\n * so the passed direction is the light reflection direction, not the incoming direction.\n */\nexport class HemisphericLight extends Light {\n /**\n * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).\n * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.\n * The HemisphericLight can't cast shadows.\n * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction\n * @param name The friendly name of the light\n * @param direction The direction of the light reflection\n * @param scene The scene the light belongs to\n */\n constructor(name, direction, scene) {\n super(name, scene);\n /**\n * The groundColor is the light in the opposite direction to the one specified during creation.\n * You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction.\n */\n this.groundColor = new Color3(0.0, 0.0, 0.0);\n this.direction = direction || Vector3.Up();\n }\n _buildUniformLayout() {\n this._uniformBuffer.addUniform(\"vLightData\", 4);\n this._uniformBuffer.addUniform(\"vLightDiffuse\", 4);\n this._uniformBuffer.addUniform(\"vLightSpecular\", 4);\n this._uniformBuffer.addUniform(\"vLightGround\", 3);\n this._uniformBuffer.addUniform(\"shadowsInfo\", 3);\n this._uniformBuffer.addUniform(\"depthValues\", 2);\n this._uniformBuffer.create();\n }\n /**\n * Returns the string \"HemisphericLight\".\n * @returns The class name\n */\n getClassName() {\n return \"HemisphericLight\";\n }\n /**\n * Sets the HemisphericLight direction towards the passed target (Vector3).\n * Returns the updated direction.\n * @param target The target the direction should point to\n * @returns The computed direction\n */\n setDirectionToTarget(target) {\n this.direction = Vector3.Normalize(target.subtract(Vector3.Zero()));\n return this.direction;\n }\n /**\n * Returns the shadow generator associated to the light.\n * @returns Always null for hemispheric lights because it does not support shadows.\n */\n getShadowGenerator() {\n return null;\n }\n /**\n * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).\n * @param _effect The effect to update\n * @param lightIndex The index of the light in the effect to update\n * @returns The hemispheric light\n */\n transferToEffect(_effect, lightIndex) {\n const normalizeDirection = Vector3.Normalize(this.direction);\n this._uniformBuffer.updateFloat4(\"vLightData\", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);\n this._uniformBuffer.updateColor3(\"vLightGround\", this.groundColor.scale(this.intensity), lightIndex);\n return this;\n }\n transferToNodeMaterialEffect(effect, lightDataUniformName) {\n const normalizeDirection = Vector3.Normalize(this.direction);\n effect.setFloat3(lightDataUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z);\n return this;\n }\n /**\n * Computes the world matrix of the node\n * @returns the world matrix\n */\n computeWorldMatrix() {\n if (!this._worldMatrix) {\n this._worldMatrix = Matrix.Identity();\n }\n return this._worldMatrix;\n }\n /**\n * Returns the integer 3.\n * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x\n */\n getTypeID() {\n return Light.LIGHTTYPEID_HEMISPHERICLIGHT;\n }\n /**\n * Prepares the list of defines specific to the light type.\n * @param defines the list of defines\n * @param lightIndex defines the index of the light for the effect\n */\n prepareLightSpecificDefines(defines, lightIndex) {\n defines[\"HEMILIGHT\" + lightIndex] = true;\n }\n}\n__decorate([\n serializeAsColor3()\n], HemisphericLight.prototype, \"groundColor\", void 0);\n__decorate([\n serializeAsVector3()\n], HemisphericLight.prototype, \"direction\", void 0);\n//# sourceMappingURL=hemisphericLight.js.map","import { Matrix } from \"../../Maths/math.vector.js\";\nimport { Viewport } from \"../../Maths/math.viewport.js\";\n/**\n * @internal\n */\nexport function setWebVRRigMode(camera, rigParams) {\n if (rigParams.vrDisplay) {\n const leftEye = rigParams.vrDisplay.getEyeParameters(\"left\");\n const rightEye = rigParams.vrDisplay.getEyeParameters(\"right\");\n //Left eye\n camera._rigCameras[0].viewport = new Viewport(0, 0, 0.5, 1.0);\n camera._rigCameras[0].setCameraRigParameter(\"left\", true);\n //leaving this for future reference\n camera._rigCameras[0].setCameraRigParameter(\"specs\", rigParams.specs);\n camera._rigCameras[0].setCameraRigParameter(\"eyeParameters\", leftEye);\n camera._rigCameras[0].setCameraRigParameter(\"frameData\", rigParams.frameData);\n camera._rigCameras[0].setCameraRigParameter(\"parentCamera\", rigParams.parentCamera);\n camera._rigCameras[0]._cameraRigParams.vrWorkMatrix = new Matrix();\n camera._rigCameras[0].getProjectionMatrix = camera._getWebVRProjectionMatrix;\n camera._rigCameras[0].parent = camera;\n camera._rigCameras[0]._getViewMatrix = camera._getWebVRViewMatrix;\n //Right eye\n camera._rigCameras[1].viewport = new Viewport(0.5, 0, 0.5, 1.0);\n camera._rigCameras[1].setCameraRigParameter(\"eyeParameters\", rightEye);\n camera._rigCameras[1].setCameraRigParameter(\"specs\", rigParams.specs);\n camera._rigCameras[1].setCameraRigParameter(\"frameData\", rigParams.frameData);\n camera._rigCameras[1].setCameraRigParameter(\"parentCamera\", rigParams.parentCamera);\n camera._rigCameras[1]._cameraRigParams.vrWorkMatrix = new Matrix();\n camera._rigCameras[1].getProjectionMatrix = camera._getWebVRProjectionMatrix;\n camera._rigCameras[1].parent = camera;\n camera._rigCameras[1]._getViewMatrix = camera._getWebVRViewMatrix;\n }\n}\n//# sourceMappingURL=webVRRigMode.js.map","import { Engine } from \"../../Engines/engine.js\";\nimport { Size } from \"../../Maths/math.size.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nimport { IsWindowObjectExist } from \"../../Misc/domManagement.js\";\nObject.defineProperty(Engine.prototype, \"isInVRExclusivePointerMode\", {\n get: function () {\n return this._vrExclusivePointerMode;\n },\n enumerable: true,\n configurable: true,\n});\nEngine.prototype._prepareVRComponent = function () {\n this._vrSupported = false;\n this._vrExclusivePointerMode = false;\n this.onVRDisplayChangedObservable = new Observable();\n this.onVRRequestPresentComplete = new Observable();\n this.onVRRequestPresentStart = new Observable();\n};\nEngine.prototype.isVRDevicePresent = function () {\n return !!this._vrDisplay;\n};\nEngine.prototype.getVRDevice = function () {\n return this._vrDisplay;\n};\nEngine.prototype.initWebVR = function () {\n this.initWebVRAsync();\n return this.onVRDisplayChangedObservable;\n};\nEngine.prototype.initWebVRAsync = function () {\n const notifyObservers = () => {\n const eventArgs = {\n vrDisplay: this._vrDisplay,\n vrSupported: this._vrSupported,\n };\n this.onVRDisplayChangedObservable.notifyObservers(eventArgs);\n this._webVRInitPromise = new Promise((res) => {\n res(eventArgs);\n });\n };\n if (!this._onVrDisplayConnect) {\n this._onVrDisplayConnect = (event) => {\n this._vrDisplay = event.display;\n notifyObservers();\n };\n this._onVrDisplayDisconnect = () => {\n this._vrDisplay.cancelAnimationFrame(this._frameHandler);\n this._vrDisplay = undefined;\n this._frameHandler = Engine.QueueNewFrame(this._boundRenderFunction);\n notifyObservers();\n };\n this._onVrDisplayPresentChange = () => {\n this._vrExclusivePointerMode = this._vrDisplay && this._vrDisplay.isPresenting;\n };\n const hostWindow = this.getHostWindow();\n if (hostWindow) {\n hostWindow.addEventListener(\"vrdisplayconnect\", this._onVrDisplayConnect);\n hostWindow.addEventListener(\"vrdisplaydisconnect\", this._onVrDisplayDisconnect);\n hostWindow.addEventListener(\"vrdisplaypresentchange\", this._onVrDisplayPresentChange);\n }\n }\n this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();\n this._webVRInitPromise.then(notifyObservers);\n return this._webVRInitPromise;\n};\nEngine.prototype._getVRDisplaysAsync = function () {\n return new Promise((res) => {\n if (navigator.getVRDisplays) {\n navigator.getVRDisplays().then((devices) => {\n this._vrSupported = true;\n // note that devices may actually be an empty array. This is fine;\n // we expect this._vrDisplay to be undefined in this case.\n this._vrDisplay = devices[0];\n res({\n vrDisplay: this._vrDisplay,\n vrSupported: this._vrSupported,\n });\n });\n }\n else {\n this._vrDisplay = undefined;\n this._vrSupported = false;\n res({\n vrDisplay: this._vrDisplay,\n vrSupported: this._vrSupported,\n });\n }\n });\n};\nEngine.prototype.enableVR = function (options) {\n if (this._vrDisplay && !this._vrDisplay.isPresenting) {\n const onResolved = () => {\n this.onVRRequestPresentComplete.notifyObservers(true);\n this._onVRFullScreenTriggered();\n };\n const onRejected = () => {\n this.onVRRequestPresentComplete.notifyObservers(false);\n };\n this.onVRRequestPresentStart.notifyObservers(this);\n const presentationAttributes = {\n highRefreshRate: this.vrPresentationAttributes ? this.vrPresentationAttributes.highRefreshRate : false,\n foveationLevel: this.vrPresentationAttributes ? this.vrPresentationAttributes.foveationLevel : 1,\n multiview: (this.getCaps().multiview || this.getCaps().oculusMultiview) && options.useMultiview,\n };\n this._vrDisplay\n .requestPresent([\n Object.assign({ source: this.getRenderingCanvas(), attributes: presentationAttributes }, presentationAttributes),\n ])\n .then(onResolved)\n .catch(onRejected);\n }\n};\nEngine.prototype._onVRFullScreenTriggered = function () {\n if (this._vrDisplay && this._vrDisplay.isPresenting) {\n //get the old size before we change\n this._oldSize = new Size(this.getRenderWidth(), this.getRenderHeight());\n this._oldHardwareScaleFactor = this.getHardwareScalingLevel();\n //get the width and height, change the render size\n const leftEye = this._vrDisplay.getEyeParameters(\"left\");\n this.setHardwareScalingLevel(1);\n this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);\n }\n else {\n this.setHardwareScalingLevel(this._oldHardwareScaleFactor);\n this.setSize(this._oldSize.width, this._oldSize.height);\n }\n};\nEngine.prototype.disableVR = function () {\n if (this._vrDisplay && this._vrDisplay.isPresenting) {\n this._vrDisplay\n .exitPresent()\n .then(() => this._onVRFullScreenTriggered())\n .catch(() => this._onVRFullScreenTriggered());\n }\n if (IsWindowObjectExist()) {\n window.removeEventListener(\"vrdisplaypointerrestricted\", this._onVRDisplayPointerRestricted);\n window.removeEventListener(\"vrdisplaypointerunrestricted\", this._onVRDisplayPointerUnrestricted);\n if (this._onVrDisplayConnect) {\n window.removeEventListener(\"vrdisplayconnect\", this._onVrDisplayConnect);\n if (this._onVrDisplayDisconnect) {\n window.removeEventListener(\"vrdisplaydisconnect\", this._onVrDisplayDisconnect);\n }\n if (this._onVrDisplayPresentChange) {\n window.removeEventListener(\"vrdisplaypresentchange\", this._onVrDisplayPresentChange);\n }\n this._onVrDisplayConnect = null;\n this._onVrDisplayDisconnect = null;\n }\n }\n};\nEngine.prototype._connectVREvents = function (canvas, document) {\n this._onVRDisplayPointerRestricted = () => {\n if (canvas) {\n canvas.requestPointerLock();\n }\n };\n this._onVRDisplayPointerUnrestricted = () => {\n // Edge fix - for some reason document is not present and this is window\n if (!document) {\n const hostWindow = this.getHostWindow();\n if (hostWindow.document && hostWindow.document.exitPointerLock) {\n hostWindow.document.exitPointerLock();\n }\n return;\n }\n if (!document.exitPointerLock) {\n return;\n }\n document.exitPointerLock();\n };\n if (IsWindowObjectExist()) {\n const hostWindow = this.getHostWindow();\n hostWindow.addEventListener(\"vrdisplaypointerrestricted\", this._onVRDisplayPointerRestricted, false);\n hostWindow.addEventListener(\"vrdisplaypointerunrestricted\", this._onVRDisplayPointerUnrestricted, false);\n }\n};\nEngine.prototype._submitVRFrame = function () {\n // Submit frame to the vr device, if enabled\n if (this._vrDisplay && this._vrDisplay.isPresenting) {\n // TODO: We should only submit the frame if we read frameData successfully.\n try {\n this._vrDisplay.submitFrame();\n }\n catch (e) {\n Tools.Warn(\"webVR submitFrame has had an unexpected failure: \" + e);\n }\n }\n};\nEngine.prototype.isVRPresenting = function () {\n return this._vrDisplay && this._vrDisplay.isPresenting;\n};\nEngine.prototype._requestVRFrame = function () {\n this._frameHandler = Engine.QueueNewFrame(this._boundRenderFunction, this._vrDisplay);\n};\n//# sourceMappingURL=engine.webVR.js.map","import { Observable } from \"../../Misc/observable.js\";\nimport { FreeCamera } from \"../../Cameras/freeCamera.js\";\nimport { Camera } from \"../../Cameras/camera.js\";\nimport { Quaternion, Matrix, Vector3 } from \"../../Maths/math.vector.js\";\nimport { Gamepad } from \"../../Gamepads/gamepad.js\";\nimport { PoseEnabledControllerType } from \"../../Gamepads/Controllers/poseEnabledController.js\";\nimport { Node } from \"../../node.js\";\nimport { HemisphericLight } from \"../../Lights/hemisphericLight.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { VRMultiviewToSingleviewPostProcess } from \"../../PostProcesses/vrMultiviewToSingleviewPostProcess.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nimport { setWebVRRigMode } from \"../RigModes/webVRRigMode.js\";\n// Side effect import to add webvr support to engine\nimport \"../../Engines/Extensions/engine.webVR.js\";\nNode.AddNodeConstructor(\"WebVRFreeCamera\", (name, scene) => {\n return () => new WebVRFreeCamera(name, Vector3.Zero(), scene);\n});\nNode.AddNodeConstructor(\"WebVRGamepadCamera\", (name, scene) => {\n return () => new WebVRFreeCamera(name, Vector3.Zero(), scene);\n});\n/**\n * This represents a WebVR camera.\n * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.\n * @deprecated Use WebXR instead - https://doc.babylonjs.com/features/featuresDeepDive/webXR\n * @example https://doc.babylonjs.com/features/featuresDeepDive/cameras/webVRCamera\n */\nexport class WebVRFreeCamera extends FreeCamera {\n /**\n * Instantiates a WebVRFreeCamera.\n * @param name The name of the WebVRFreeCamera\n * @param position The starting anchor position for the camera\n * @param scene The scene the camera belongs to\n * @param _webVROptions a set of customizable options for the webVRCamera\n */\n constructor(name, position, scene, _webVROptions = {}) {\n super(name, position, scene);\n this._webVROptions = _webVROptions;\n /**\n * @internal\n * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay\n */\n this._vrDevice = null;\n /**\n * The rawPose of the vrDevice.\n */\n this.rawPose = null;\n this._specsVersion = \"1.1\";\n this._attached = false;\n this._descendants = [];\n // Represents device position and rotation in room space. Should only be used to help calculate babylon space values\n this._deviceRoomPosition = Vector3.Zero();\n /** @internal */\n this._deviceRoomRotationQuaternion = Quaternion.Identity();\n this._standingMatrix = null;\n /**\n * Represents device position in babylon space.\n */\n this.devicePosition = Vector3.Zero();\n /**\n * Represents device rotation in babylon space.\n */\n this.deviceRotationQuaternion = Quaternion.Identity();\n /**\n * The scale of the device to be used when translating from device space to babylon space.\n */\n this.deviceScaleFactor = 1;\n this._deviceToWorld = Matrix.Identity();\n this._worldToDevice = Matrix.Identity();\n /**\n * References to the webVR controllers for the vrDevice.\n */\n this.controllers = [];\n /**\n * Emits an event when a controller is attached.\n */\n this.onControllersAttachedObservable = new Observable();\n /**\n * Emits an event when a controller's mesh has been loaded;\n */\n this.onControllerMeshLoadedObservable = new Observable();\n /**\n * Emits an event when the HMD's pose has been updated.\n */\n this.onPoseUpdatedFromDeviceObservable = new Observable();\n this._poseSet = false;\n /**\n * If the rig cameras be used as parent instead of this camera.\n */\n this.rigParenting = true;\n this._defaultHeight = undefined;\n this._setRigMode = setWebVRRigMode.bind(null, this);\n this._detachIfAttached = () => {\n const vrDisplay = this.getEngine().getVRDevice();\n if (vrDisplay && !vrDisplay.isPresenting) {\n this.detachControl();\n }\n };\n this._workingVector = Vector3.Zero();\n this._oneVector = Vector3.One();\n this._workingMatrix = Matrix.Identity();\n this._tmpMatrix = new Matrix();\n this._cache.position = Vector3.Zero();\n if (_webVROptions.defaultHeight) {\n this._defaultHeight = _webVROptions.defaultHeight;\n this.position.y = this._defaultHeight;\n }\n this.minZ = 0.1;\n //legacy support - the compensation boolean was removed.\n if (arguments.length === 5) {\n // eslint-disable-next-line prefer-rest-params\n this._webVROptions = arguments[4];\n }\n // default webVR options\n if (this._webVROptions.trackPosition == undefined) {\n this._webVROptions.trackPosition = true;\n }\n if (this._webVROptions.controllerMeshes == undefined) {\n this._webVROptions.controllerMeshes = true;\n }\n if (this._webVROptions.defaultLightingOnControllers == undefined) {\n this._webVROptions.defaultLightingOnControllers = true;\n }\n this.rotationQuaternion = new Quaternion();\n if (this._webVROptions && this._webVROptions.positionScale) {\n this.deviceScaleFactor = this._webVROptions.positionScale;\n }\n //enable VR\n const engine = this.getEngine();\n this._onVREnabled = (success) => {\n if (success) {\n this.initControllers();\n }\n };\n engine.onVRRequestPresentComplete.add(this._onVREnabled);\n engine.initWebVR().add((event) => {\n if (!event.vrDisplay || this._vrDevice === event.vrDisplay) {\n return;\n }\n this._vrDevice = event.vrDisplay;\n //reset the rig parameters.\n this.setCameraRigMode(Camera.RIG_MODE_WEBVR, { parentCamera: this, vrDisplay: this._vrDevice, frameData: this._frameData, specs: this._specsVersion });\n if (this._attached) {\n this.getEngine().enableVR(this._webVROptions);\n }\n });\n if (typeof VRFrameData !== \"undefined\") {\n this._frameData = new VRFrameData();\n }\n if (_webVROptions.useMultiview) {\n if (!this.getScene().getEngine().getCaps().multiview) {\n Logger.Warn(\"Multiview is not supported, falling back to standard rendering\");\n this._useMultiviewToSingleView = false;\n }\n else {\n this._useMultiviewToSingleView = true;\n this._rigPostProcess = new VRMultiviewToSingleviewPostProcess(\"VRMultiviewToSingleview\", this, 1.0);\n }\n }\n /**\n * The idea behind the following lines:\n * objects that have the camera as parent should actually have the rig cameras as a parent.\n * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,\n * the second will not show it correctly.\n *\n * To solve this - each object that has the camera as parent will be added to a protected array.\n * When the rig camera renders, it will take this array and set all of those to be its children.\n * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.\n * Amazing!\n */\n this.getScene().onBeforeCameraRenderObservable.add((camera) => {\n if (camera.parent === this && this.rigParenting) {\n this._descendants = this.getDescendants(true, (n) => {\n // don't take the cameras or the controllers!\n const isController = this.controllers.some((controller) => {\n return controller._mesh === n;\n });\n const isRigCamera = this._rigCameras.indexOf(n) !== -1;\n return !isController && !isRigCamera;\n });\n this._descendants.forEach((node) => {\n node.parent = camera;\n });\n }\n });\n this.getScene().onAfterCameraRenderObservable.add((camera) => {\n if (camera.parent === this && this.rigParenting) {\n this._descendants.forEach((node) => {\n node.parent = this;\n });\n }\n });\n }\n /**\n * Gets the device distance from the ground in meters.\n * @returns the distance in meters from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.\n */\n deviceDistanceToRoomGround() {\n if (this._standingMatrix) {\n // Add standing matrix offset to get real offset from ground in room\n this._standingMatrix.getTranslationToRef(this._workingVector);\n return this._deviceRoomPosition.y + this._workingVector.y;\n }\n //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.\n return this._defaultHeight || 0;\n }\n /**\n * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.\n * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n useStandingMatrix(callback = (bool) => { }) {\n // Use standing matrix if available\n this.getEngine()\n .initWebVRAsync()\n .then((result) => {\n if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !this._webVROptions.trackPosition) {\n callback(false);\n }\n else {\n this._standingMatrix = new Matrix();\n Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, this._standingMatrix);\n if (!this.getScene().useRightHandedSystem) {\n if (this._standingMatrix) {\n this._standingMatrix.toggleModelMatrixHandInPlace();\n }\n }\n callback(true);\n }\n });\n }\n /**\n * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.\n * @returns A promise with a boolean set to if the standing matrix is supported.\n */\n useStandingMatrixAsync() {\n return new Promise((res) => {\n this.useStandingMatrix((supported) => {\n res(supported);\n });\n });\n }\n /**\n * Disposes the camera\n */\n dispose() {\n this._detachIfAttached();\n this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);\n if (this._updateCacheWhenTrackingDisabledObserver) {\n this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);\n }\n super.dispose();\n }\n /**\n * Gets a vrController by name.\n * @param name The name of the controller to retrieve\n * @returns the controller matching the name specified or null if not found\n */\n getControllerByName(name) {\n for (const gp of this.controllers) {\n if (gp.hand === name) {\n return gp;\n }\n }\n return null;\n }\n /**\n * The controller corresponding to the users left hand.\n */\n get leftController() {\n if (!this._leftController) {\n this._leftController = this.getControllerByName(\"left\");\n }\n return this._leftController;\n }\n /**\n * The controller corresponding to the users right hand.\n */\n get rightController() {\n if (!this._rightController) {\n this._rightController = this.getControllerByName(\"right\");\n }\n return this._rightController;\n }\n /**\n * Casts a ray forward from the vrCamera's gaze.\n * @param length Length of the ray (default: 100)\n * @returns the ray corresponding to the gaze\n */\n getForwardRay(length = 100) {\n if (this.leftCamera) {\n // Use left eye to avoid computation to compute center on every call\n return super.getForwardRay(length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera\n }\n else {\n return super.getForwardRay(length);\n }\n }\n /**\n * @internal\n * Updates the camera based on device's frame data\n */\n _checkInputs() {\n if (this._vrDevice && this._vrDevice.isPresenting) {\n this._vrDevice.getFrameData(this._frameData);\n this.updateFromDevice(this._frameData.pose);\n }\n super._checkInputs();\n }\n /**\n * Updates the poseControlled values based on the input device pose.\n * @param poseData Pose coming from the device\n */\n updateFromDevice(poseData) {\n if (poseData && poseData.orientation && poseData.orientation.length === 4) {\n this.rawPose = poseData;\n this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);\n if (this.getScene().useRightHandedSystem) {\n this._deviceRoomRotationQuaternion.z *= -1;\n this._deviceRoomRotationQuaternion.w *= -1;\n }\n if (this._webVROptions.trackPosition && this.rawPose.position) {\n this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);\n if (this.getScene().useRightHandedSystem) {\n this._deviceRoomPosition.z *= -1;\n }\n }\n this._poseSet = true;\n }\n }\n /**\n * WebVR's attach control will start broadcasting frames to the device.\n * Note that in certain browsers (chrome for example) this function must be called\n * within a user-interaction callback. Example:\n *
 scene.onPointerDown = function() { camera.attachControl(canvas); }
\n *\n * @param noPreventDefault prevent the default html element operation when attaching the vrDevice\n */\n attachControl(noPreventDefault) {\n // eslint-disable-next-line prefer-rest-params\n noPreventDefault = Tools.BackCompatCameraNoPreventDefault(arguments);\n super.attachControl(noPreventDefault);\n this._attached = true;\n noPreventDefault = Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;\n if (this._vrDevice) {\n this.getEngine().enableVR(this._webVROptions);\n }\n const hostWindow = this._scene.getEngine().getHostWindow();\n if (hostWindow) {\n hostWindow.addEventListener(\"vrdisplaypresentchange\", this._detachIfAttached);\n }\n }\n /**\n * Detach the current controls from the specified dom element.\n */\n detachControl() {\n this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);\n this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);\n super.detachControl();\n this._attached = false;\n this.getEngine().disableVR();\n window.removeEventListener(\"vrdisplaypresentchange\", this._detachIfAttached);\n }\n /**\n * @returns the name of this class\n */\n getClassName() {\n return \"WebVRFreeCamera\";\n }\n /**\n * Calls resetPose on the vrDisplay\n * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose\n */\n resetToCurrentRotation() {\n //uses the vrDisplay's \"resetPose()\".\n //pitch and roll won't be affected.\n this._vrDevice.resetPose();\n }\n /**\n * @internal\n * Updates the rig cameras (left and right eye)\n */\n _updateRigCameras() {\n const camLeft = this._rigCameras[0];\n const camRight = this._rigCameras[1];\n camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);\n camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);\n camLeft.position.copyFrom(this._deviceRoomPosition);\n camRight.position.copyFrom(this._deviceRoomPosition);\n }\n // Remove translation from 6dof headset if trackposition is set to false\n _correctPositionIfNotTrackPosition(matrix, isViewMatrix = false) {\n if (this.rawPose && this.rawPose.position && !this._webVROptions.trackPosition) {\n Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);\n if (!isViewMatrix) {\n this._tmpMatrix.invert();\n }\n this._tmpMatrix.multiplyToRef(matrix, matrix);\n }\n }\n /**\n * @internal\n * Updates the cached values of the camera\n * @param ignoreParentClass ignores updating the parent class's cache (default: false)\n */\n _updateCache(ignoreParentClass) {\n if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {\n // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition\n if (!this._updateCacheCalled) {\n // make sure it is only called once per loop. this.update() might cause an infinite loop.\n this._updateCacheCalled = true;\n this.update();\n }\n // Set working vector to the device position in room space rotated by the new rotation\n this.rotationQuaternion.toRotationMatrix(this._workingMatrix);\n Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);\n // Subtract this vector from the current device position in world to get the translation for the device world matrix\n this.devicePosition.subtractToRef(this._workingVector, this._workingVector);\n Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);\n // Add translation from anchor position\n this._deviceToWorld.getTranslationToRef(this._workingVector);\n this._workingVector.addInPlace(this.position);\n this._workingVector.subtractInPlace(this._cache.position);\n this._deviceToWorld.setTranslation(this._workingVector);\n // Set an inverted matrix to be used when updating the camera\n this._deviceToWorld.invertToRef(this._worldToDevice);\n // Update the gamepad to ensure the mesh is updated on the same frame as camera\n this.controllers.forEach((controller) => {\n controller._deviceToWorld.copyFrom(this._deviceToWorld);\n this._correctPositionIfNotTrackPosition(controller._deviceToWorld);\n controller.update();\n });\n }\n if (!ignoreParentClass) {\n super._updateCache();\n }\n this._updateCacheCalled = false;\n }\n /**\n * @internal\n * Get current device position in babylon world\n */\n _computeDevicePosition() {\n Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);\n }\n /**\n * Updates the current device position and rotation in the babylon world\n */\n update() {\n this._computeDevicePosition();\n // Get current device rotation in babylon world\n Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);\n this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);\n Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);\n if (this._poseSet) {\n this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);\n }\n super.update();\n }\n /**\n * @internal\n * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)\n * @returns an identity matrix\n */\n _getViewMatrix() {\n return Matrix.Identity();\n }\n /**\n * This function is called by the two RIG cameras.\n * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)\n * @internal\n */\n _getWebVRViewMatrix() {\n // Update the parent camera prior to using a child camera to avoid desynchronization\n const parentCamera = this._cameraRigParams[\"parentCamera\"];\n parentCamera._updateCache();\n //WebVR 1.1\n const viewArray = this._cameraRigParams[\"left\"] ? this._cameraRigParams[\"frameData\"].leftViewMatrix : this._cameraRigParams[\"frameData\"].rightViewMatrix;\n Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);\n if (!this.getScene().useRightHandedSystem) {\n this._webvrViewMatrix.toggleModelMatrixHandInPlace();\n }\n // update the camera rotation matrix\n this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);\n Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);\n // Computing target and final matrix\n this.position.addToRef(this._transformedReferencePoint, this._currentTarget);\n // should the view matrix be updated with scale and position offset?\n if (parentCamera.deviceScaleFactor !== 1) {\n this._webvrViewMatrix.invert();\n // scale the position, if set\n if (parentCamera.deviceScaleFactor) {\n this._webvrViewMatrix.multiplyAtIndex(12, parentCamera.deviceScaleFactor);\n this._webvrViewMatrix.multiplyAtIndex(13, parentCamera.deviceScaleFactor);\n this._webvrViewMatrix.multiplyAtIndex(14, parentCamera.deviceScaleFactor);\n }\n this._webvrViewMatrix.invert();\n }\n // Remove translation from 6dof headset if trackposition is set to false\n parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);\n parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);\n // Compute global position\n this._workingMatrix = this._workingMatrix || Matrix.Identity();\n this._webvrViewMatrix.invertToRef(this._workingMatrix);\n this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);\n this._workingMatrix.getTranslationToRef(this._globalPosition);\n this._markSyncedWithParent();\n return this._webvrViewMatrix;\n }\n /** @internal */\n _getWebVRProjectionMatrix() {\n const parentCamera = this.parent;\n parentCamera._vrDevice.depthNear = parentCamera.minZ;\n parentCamera._vrDevice.depthFar = parentCamera.maxZ;\n const projectionArray = this._cameraRigParams[\"left\"] ? this._cameraRigParams[\"frameData\"].leftProjectionMatrix : this._cameraRigParams[\"frameData\"].rightProjectionMatrix;\n Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);\n //babylon compatible matrix\n if (!this.getScene().useRightHandedSystem) {\n this._projectionMatrix.toggleProjectionMatrixHandInPlace();\n }\n return this._projectionMatrix;\n }\n /**\n * Initializes the controllers and their meshes\n */\n initControllers() {\n this.controllers.length = 0;\n const manager = this.getScene().gamepadManager;\n this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add((gamepad) => {\n if (gamepad.type === Gamepad.POSE_ENABLED) {\n const webVrController = gamepad;\n if (webVrController.defaultModel) {\n webVrController.defaultModel.setEnabled(false);\n }\n if (webVrController.hand === \"right\") {\n this._rightController = null;\n }\n if (webVrController.hand === \"left\") {\n this._leftController = null;\n }\n const controllerIndex = this.controllers.indexOf(webVrController);\n if (controllerIndex !== -1) {\n this.controllers.splice(controllerIndex, 1);\n }\n }\n });\n this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add((gamepad) => {\n if (gamepad.type === Gamepad.POSE_ENABLED) {\n const webVrController = gamepad;\n if (!this._webVROptions.trackPosition) {\n webVrController._disableTrackPosition(new Vector3(webVrController.hand == \"left\" ? -0.15 : 0.15, -0.5, 0.25));\n // Cache must be updated before rendering controllers to avoid them being one frame behind\n if (!this._updateCacheWhenTrackingDisabledObserver) {\n this._updateCacheWhenTrackingDisabledObserver = this._scene.onBeforeRenderObservable.add(() => {\n this._updateCache();\n });\n }\n }\n webVrController.deviceScaleFactor = this.deviceScaleFactor;\n webVrController._deviceToWorld.copyFrom(this._deviceToWorld);\n this._correctPositionIfNotTrackPosition(webVrController._deviceToWorld);\n if (this._webVROptions.controllerMeshes) {\n if (webVrController.defaultModel) {\n webVrController.defaultModel.setEnabled(true);\n }\n else {\n // Load the meshes\n webVrController.initControllerMesh(this.getScene(), (loadedMesh) => {\n loadedMesh.scaling.scaleInPlace(this.deviceScaleFactor);\n this.onControllerMeshLoadedObservable.notifyObservers(webVrController);\n if (this._webVROptions.defaultLightingOnControllers) {\n if (!this._lightOnControllers) {\n this._lightOnControllers = new HemisphericLight(\"vrControllersLight\", new Vector3(0, 1, 0), this.getScene());\n }\n const activateLightOnSubMeshes = function (mesh, light) {\n const children = mesh.getChildren();\n if (children && children.length !== 0) {\n children.forEach((mesh) => {\n light.includedOnlyMeshes.push(mesh);\n activateLightOnSubMeshes(mesh, light);\n });\n }\n };\n this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);\n activateLightOnSubMeshes(loadedMesh, this._lightOnControllers);\n }\n });\n }\n }\n webVrController.attachToPoseControlledCamera(this);\n // since this is async - sanity check. Is the controller already stored?\n if (this.controllers.indexOf(webVrController) === -1) {\n //add to the controllers array\n this.controllers.push(webVrController);\n // Forced to add some control code for Vive as it doesn't always fill properly the \"hand\" property\n // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...\n // So we're overriding setting left & right manually to be sure\n let firstViveWandDetected = false;\n for (let i = 0; i < this.controllers.length; i++) {\n if (this.controllers[i].controllerType === PoseEnabledControllerType.VIVE) {\n if (!firstViveWandDetected) {\n firstViveWandDetected = true;\n this.controllers[i].hand = \"left\";\n }\n else {\n this.controllers[i].hand = \"right\";\n }\n }\n }\n //did we find enough controllers? Great! let the developer know.\n if (this.controllers.length >= 2) {\n this.onControllersAttachedObservable.notifyObservers(this.controllers);\n }\n }\n }\n });\n }\n}\n//# sourceMappingURL=webVRCamera.js.map","import { Observable } from \"../../Misc/observable.js\";\nimport { PoseEnabledController } from \"./poseEnabledController.js\";\n/**\n * Defines the WebVRController object that represents controllers tracked in 3D space\n * @deprecated Use WebXR instead\n */\nexport class WebVRController extends PoseEnabledController {\n /**\n * Fired when a controller button's state has changed\n * @param callback the callback containing the button that was modified\n */\n onButtonStateChange(callback) {\n this._onButtonStateChange = callback;\n }\n /**\n * The default controller model for the controller\n */\n get defaultModel() {\n return this._defaultModel;\n }\n /**\n * Creates a new WebVRController from a gamepad\n * @param vrGamepad the gamepad that the WebVRController should be created from\n */\n constructor(vrGamepad) {\n super(vrGamepad);\n // Observables\n /**\n * Fired when the trigger state has changed\n */\n this.onTriggerStateChangedObservable = new Observable();\n /**\n * Fired when the main button state has changed\n */\n this.onMainButtonStateChangedObservable = new Observable();\n /**\n * Fired when the secondary button state has changed\n */\n this.onSecondaryButtonStateChangedObservable = new Observable();\n /**\n * Fired when the pad state has changed\n */\n this.onPadStateChangedObservable = new Observable();\n /**\n * Fired when controllers stick values have changed\n */\n this.onPadValuesChangedObservable = new Observable();\n /**\n * X and Y axis corresponding to the controllers joystick\n */\n this.pad = { x: 0, y: 0 };\n // avoid GC, store state in a tmp object\n this._changes = {\n pressChanged: false,\n touchChanged: false,\n valueChanged: false,\n changed: false,\n };\n this._buttons = new Array(vrGamepad.buttons.length);\n this.hand = vrGamepad.hand;\n }\n /**\n * Updates the state of the controller and mesh based on the current position and rotation of the controller\n */\n update() {\n super.update();\n for (let index = 0; index < this._buttons.length; index++) {\n this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);\n }\n if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {\n this.pad.x = this.leftStick.x;\n this.pad.y = this.leftStick.y;\n this.onPadValuesChangedObservable.notifyObservers(this.pad);\n }\n }\n _setButtonValue(newState, currentState, buttonIndex) {\n if (!newState) {\n newState = {\n pressed: false,\n touched: false,\n value: 0,\n };\n }\n if (!currentState) {\n this._buttons[buttonIndex] = {\n pressed: newState.pressed,\n touched: newState.touched,\n value: newState.value,\n };\n return;\n }\n this._checkChanges(newState, currentState);\n if (this._changes.changed) {\n this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);\n this._handleButtonChange(buttonIndex, newState, this._changes);\n }\n this._buttons[buttonIndex].pressed = newState.pressed;\n this._buttons[buttonIndex].touched = newState.touched;\n // oculus triggers are never 0, thou not touched.\n this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;\n }\n _checkChanges(newState, currentState) {\n this._changes.pressChanged = newState.pressed !== currentState.pressed;\n this._changes.touchChanged = newState.touched !== currentState.touched;\n this._changes.valueChanged = newState.value !== currentState.value;\n this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;\n return this._changes;\n }\n /**\n * Disposes of th webVRController\n */\n dispose() {\n super.dispose();\n this._defaultModel = null;\n this.onTriggerStateChangedObservable.clear();\n this.onMainButtonStateChangedObservable.clear();\n this.onSecondaryButtonStateChangedObservable.clear();\n this.onPadStateChangedObservable.clear();\n this.onPadValuesChangedObservable.clear();\n }\n}\n//# sourceMappingURL=webVRController.js.map","\n/**\n * Configuration needed for prepass-capable materials\n */\nexport class PrePassConfiguration {\n constructor() {\n /**\n * Previous world matrices of meshes carrying this material\n * Used for computing velocity\n */\n this.previousWorldMatrices = {};\n /**\n * Previous bones of meshes carrying this material\n * Used for computing velocity\n */\n this.previousBones = {};\n }\n /**\n * Add the required uniforms to the current list.\n * @param uniforms defines the current uniform list.\n */\n static AddUniforms(uniforms) {\n uniforms.push(\"previousWorld\", \"previousViewProjection\", \"mPreviousBones\");\n }\n /**\n * Add the required samplers to the current list.\n * @param samplers defines the current sampler list.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n static AddSamplers(samplers) {\n // pass\n }\n /**\n * Binds the material data.\n * @param effect defines the effect to update\n * @param scene defines the scene the material belongs to.\n * @param mesh The mesh\n * @param world World matrix of this mesh\n * @param isFrozen Is the material frozen\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n bindForSubMesh(effect, scene, mesh, world, isFrozen) {\n if (scene.prePassRenderer && scene.prePassRenderer.enabled && scene.prePassRenderer.currentRTisSceneRT) {\n if (scene.prePassRenderer.getIndex(2) !== -1) {\n if (!this.previousWorldMatrices[mesh.uniqueId]) {\n this.previousWorldMatrices[mesh.uniqueId] = world.clone();\n }\n if (!this.previousViewProjection) {\n this.previousViewProjection = scene.getTransformMatrix().clone();\n this.currentViewProjection = scene.getTransformMatrix().clone();\n }\n const engine = scene.getEngine();\n if (this.currentViewProjection.updateFlag !== scene.getTransformMatrix().updateFlag) {\n // First update of the prepass configuration for this rendering pass\n this._lastUpdateFrameId = engine.frameId;\n this.previousViewProjection.copyFrom(this.currentViewProjection);\n this.currentViewProjection.copyFrom(scene.getTransformMatrix());\n }\n else if (this._lastUpdateFrameId !== engine.frameId) {\n // The scene transformation did not change from the previous frame (so no camera motion), we must update previousViewProjection accordingly\n this._lastUpdateFrameId = engine.frameId;\n this.previousViewProjection.copyFrom(this.currentViewProjection);\n }\n effect.setMatrix(\"previousWorld\", this.previousWorldMatrices[mesh.uniqueId]);\n effect.setMatrix(\"previousViewProjection\", this.previousViewProjection);\n this.previousWorldMatrices[mesh.uniqueId] = world.clone();\n }\n }\n }\n}\n//# sourceMappingURL=prePassConfiguration.js.map","import { Engine } from \"../Engines/engine.js\";\n\n/**\n * This groups all the flags used to control the materials channel.\n */\nexport class MaterialFlags {\n /**\n * Are diffuse textures enabled in the application.\n */\n static get DiffuseTextureEnabled() {\n return this._DiffuseTextureEnabled;\n }\n static set DiffuseTextureEnabled(value) {\n if (this._DiffuseTextureEnabled === value) {\n return;\n }\n this._DiffuseTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are detail textures enabled in the application.\n */\n static get DetailTextureEnabled() {\n return this._DetailTextureEnabled;\n }\n static set DetailTextureEnabled(value) {\n if (this._DetailTextureEnabled === value) {\n return;\n }\n this._DetailTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are decal maps enabled in the application.\n */\n static get DecalMapEnabled() {\n return this._DecalMapEnabled;\n }\n static set DecalMapEnabled(value) {\n if (this._DecalMapEnabled === value) {\n return;\n }\n this._DecalMapEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are ambient textures enabled in the application.\n */\n static get AmbientTextureEnabled() {\n return this._AmbientTextureEnabled;\n }\n static set AmbientTextureEnabled(value) {\n if (this._AmbientTextureEnabled === value) {\n return;\n }\n this._AmbientTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are opacity textures enabled in the application.\n */\n static get OpacityTextureEnabled() {\n return this._OpacityTextureEnabled;\n }\n static set OpacityTextureEnabled(value) {\n if (this._OpacityTextureEnabled === value) {\n return;\n }\n this._OpacityTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are reflection textures enabled in the application.\n */\n static get ReflectionTextureEnabled() {\n return this._ReflectionTextureEnabled;\n }\n static set ReflectionTextureEnabled(value) {\n if (this._ReflectionTextureEnabled === value) {\n return;\n }\n this._ReflectionTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are emissive textures enabled in the application.\n */\n static get EmissiveTextureEnabled() {\n return this._EmissiveTextureEnabled;\n }\n static set EmissiveTextureEnabled(value) {\n if (this._EmissiveTextureEnabled === value) {\n return;\n }\n this._EmissiveTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are specular textures enabled in the application.\n */\n static get SpecularTextureEnabled() {\n return this._SpecularTextureEnabled;\n }\n static set SpecularTextureEnabled(value) {\n if (this._SpecularTextureEnabled === value) {\n return;\n }\n this._SpecularTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are bump textures enabled in the application.\n */\n static get BumpTextureEnabled() {\n return this._BumpTextureEnabled;\n }\n static set BumpTextureEnabled(value) {\n if (this._BumpTextureEnabled === value) {\n return;\n }\n this._BumpTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are lightmap textures enabled in the application.\n */\n static get LightmapTextureEnabled() {\n return this._LightmapTextureEnabled;\n }\n static set LightmapTextureEnabled(value) {\n if (this._LightmapTextureEnabled === value) {\n return;\n }\n this._LightmapTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are refraction textures enabled in the application.\n */\n static get RefractionTextureEnabled() {\n return this._RefractionTextureEnabled;\n }\n static set RefractionTextureEnabled(value) {\n if (this._RefractionTextureEnabled === value) {\n return;\n }\n this._RefractionTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are color grading textures enabled in the application.\n */\n static get ColorGradingTextureEnabled() {\n return this._ColorGradingTextureEnabled;\n }\n static set ColorGradingTextureEnabled(value) {\n if (this._ColorGradingTextureEnabled === value) {\n return;\n }\n this._ColorGradingTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are fresnels enabled in the application.\n */\n static get FresnelEnabled() {\n return this._FresnelEnabled;\n }\n static set FresnelEnabled(value) {\n if (this._FresnelEnabled === value) {\n return;\n }\n this._FresnelEnabled = value;\n Engine.MarkAllMaterialsAsDirty(4);\n }\n /**\n * Are clear coat textures enabled in the application.\n */\n static get ClearCoatTextureEnabled() {\n return this._ClearCoatTextureEnabled;\n }\n static set ClearCoatTextureEnabled(value) {\n if (this._ClearCoatTextureEnabled === value) {\n return;\n }\n this._ClearCoatTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are clear coat bump textures enabled in the application.\n */\n static get ClearCoatBumpTextureEnabled() {\n return this._ClearCoatBumpTextureEnabled;\n }\n static set ClearCoatBumpTextureEnabled(value) {\n if (this._ClearCoatBumpTextureEnabled === value) {\n return;\n }\n this._ClearCoatBumpTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are clear coat tint textures enabled in the application.\n */\n static get ClearCoatTintTextureEnabled() {\n return this._ClearCoatTintTextureEnabled;\n }\n static set ClearCoatTintTextureEnabled(value) {\n if (this._ClearCoatTintTextureEnabled === value) {\n return;\n }\n this._ClearCoatTintTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are sheen textures enabled in the application.\n */\n static get SheenTextureEnabled() {\n return this._SheenTextureEnabled;\n }\n static set SheenTextureEnabled(value) {\n if (this._SheenTextureEnabled === value) {\n return;\n }\n this._SheenTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are anisotropic textures enabled in the application.\n */\n static get AnisotropicTextureEnabled() {\n return this._AnisotropicTextureEnabled;\n }\n static set AnisotropicTextureEnabled(value) {\n if (this._AnisotropicTextureEnabled === value) {\n return;\n }\n this._AnisotropicTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are thickness textures enabled in the application.\n */\n static get ThicknessTextureEnabled() {\n return this._ThicknessTextureEnabled;\n }\n static set ThicknessTextureEnabled(value) {\n if (this._ThicknessTextureEnabled === value) {\n return;\n }\n this._ThicknessTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are refraction intensity textures enabled in the application.\n */\n static get RefractionIntensityTextureEnabled() {\n return this._ThicknessTextureEnabled;\n }\n static set RefractionIntensityTextureEnabled(value) {\n if (this._RefractionIntensityTextureEnabled === value) {\n return;\n }\n this._RefractionIntensityTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are translucency intensity textures enabled in the application.\n */\n static get TranslucencyIntensityTextureEnabled() {\n return this._ThicknessTextureEnabled;\n }\n static set TranslucencyIntensityTextureEnabled(value) {\n if (this._TranslucencyIntensityTextureEnabled === value) {\n return;\n }\n this._TranslucencyIntensityTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n /**\n * Are translucency intensity textures enabled in the application.\n */\n static get IridescenceTextureEnabled() {\n return this._IridescenceTextureEnabled;\n }\n static set IridescenceTextureEnabled(value) {\n if (this._IridescenceTextureEnabled === value) {\n return;\n }\n this._IridescenceTextureEnabled = value;\n Engine.MarkAllMaterialsAsDirty(1);\n }\n}\n// Flags used to enable or disable a type of texture for all Standard Materials\nMaterialFlags._DiffuseTextureEnabled = true;\nMaterialFlags._DetailTextureEnabled = true;\nMaterialFlags._DecalMapEnabled = true;\nMaterialFlags._AmbientTextureEnabled = true;\nMaterialFlags._OpacityTextureEnabled = true;\nMaterialFlags._ReflectionTextureEnabled = true;\nMaterialFlags._EmissiveTextureEnabled = true;\nMaterialFlags._SpecularTextureEnabled = true;\nMaterialFlags._BumpTextureEnabled = true;\nMaterialFlags._LightmapTextureEnabled = true;\nMaterialFlags._RefractionTextureEnabled = true;\nMaterialFlags._ColorGradingTextureEnabled = true;\nMaterialFlags._FresnelEnabled = true;\nMaterialFlags._ClearCoatTextureEnabled = true;\nMaterialFlags._ClearCoatBumpTextureEnabled = true;\nMaterialFlags._ClearCoatTintTextureEnabled = true;\nMaterialFlags._SheenTextureEnabled = true;\nMaterialFlags._AnisotropicTextureEnabled = true;\nMaterialFlags._ThicknessTextureEnabled = true;\nMaterialFlags._RefractionIntensityTextureEnabled = true;\nMaterialFlags._TranslucencyIntensityTextureEnabled = true;\nMaterialFlags._IridescenceTextureEnabled = true;\n//# sourceMappingURL=materialFlags.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"decalFragmentDeclaration\";\nconst shader = `#ifdef DECAL\nuniform vec4 vDecalInfos;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const decalFragmentDeclaration = { name, shader };\n//# sourceMappingURL=decalFragmentDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nimport \"./decalFragmentDeclaration.js\";\nconst name = \"defaultFragmentDeclaration\";\nconst shader = `uniform vec4 vEyePosition;\runiform vec4 vDiffuseColor;\r#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\r#endif\nuniform vec3 vEmissiveColor;\runiform vec3 vAmbientColor;\runiform float visibility;\r#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\r#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\r#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\r#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\r#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\r#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\runiform vec2 vTangentSpaceParams;\r#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\r#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS)\nuniform mat4 view;\r#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\r#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\r#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\runiform vec4 refractionRightColor;\r#endif\n#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D)\nuniform vec3 vRefractionPosition;\runiform vec3 vRefractionSize; \r#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\r#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\runiform vec4 diffuseRightColor;\r#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\r#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\runiform vec4 emissiveRightColor;\r#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\r#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX)\nuniform mat4 reflectionMatrix;\r#endif\n#ifndef REFLECTIONMAP_SKYBOX\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\runiform vec3 vReflectionSize; \r#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\runiform vec4 reflectionRightColor;\r#endif\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\r#endif\n#include\n#define ADDITIONAL_FRAGMENT_DECLARATION\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const defaultFragmentDeclaration = { name, shader };\n//# sourceMappingURL=defaultFragmentDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"sceneUboDeclaration\";\nconst shader = `layout(std140,column_major) uniform;\runiform Scene {\rmat4 viewProjection;\r#ifdef MULTIVIEW\nmat4 viewProjectionR;\r#endif \nmat4 view;\rmat4 projection;\rvec4 vEyePosition;\r};\r`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const sceneUboDeclaration = { name, shader };\n//# sourceMappingURL=sceneUboDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"meshUboDeclaration\";\nconst shader = `#ifdef WEBGL2\nuniform mat4 world;\runiform float visibility;\r#else\nlayout(std140,column_major) uniform;\runiform Mesh\r{\rmat4 world;\rfloat visibility;\r};\r#endif\n#define WORLD_UBO\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const meshUboDeclaration = { name, shader };\n//# sourceMappingURL=meshUboDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nimport \"./sceneUboDeclaration.js\";\nimport \"./meshUboDeclaration.js\";\nconst name = \"defaultUboDeclaration\";\nconst shader = `layout(std140,column_major) uniform;\runiform Material\r{\rvec4 diffuseLeftColor;\rvec4 diffuseRightColor;\rvec4 opacityParts;\rvec4 reflectionLeftColor;\rvec4 reflectionRightColor;\rvec4 refractionLeftColor;\rvec4 refractionRightColor;\rvec4 emissiveLeftColor;\rvec4 emissiveRightColor;\rvec2 vDiffuseInfos;\rvec2 vAmbientInfos;\rvec2 vOpacityInfos;\rvec2 vReflectionInfos;\rvec3 vReflectionPosition;\rvec3 vReflectionSize;\rvec2 vEmissiveInfos;\rvec2 vLightmapInfos;\rvec2 vSpecularInfos;\rvec3 vBumpInfos;\rmat4 diffuseMatrix;\rmat4 ambientMatrix;\rmat4 opacityMatrix;\rmat4 reflectionMatrix;\rmat4 emissiveMatrix;\rmat4 lightmapMatrix;\rmat4 specularMatrix;\rmat4 bumpMatrix;\rvec2 vTangentSpaceParams;\rfloat pointSize;\rfloat alphaCutOff;\rmat4 refractionMatrix;\rvec4 vRefractionInfos;\rvec3 vRefractionPosition;\rvec3 vRefractionSize;\rvec4 vSpecularColor;\rvec3 vEmissiveColor;\rvec4 vDiffuseColor;\rvec3 vAmbientColor;\r#define ADDITIONAL_UBO_DECLARATION\n};\r#include\n#include\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const defaultUboDeclaration = { name, shader };\n//# sourceMappingURL=defaultUboDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"prePassDeclaration\";\nconst shader = `#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`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const prePassDeclaration = { name, shader };\n//# sourceMappingURL=prePassDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"lightFragmentDeclaration\";\nconst shader = `#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\runiform vec4 vLightDiffuse{X};\r#ifdef SPECULARTERM\nuniform vec4 vLightSpecular{X};\r#else\nvec4 vLightSpecular{X}=vec4(0.);\r#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];\runiform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];\runiform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];\runiform float cascadeBlendFactor{X};\rvarying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];\rvarying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];\rvarying vec4 vPositionFromCamera{X};\r#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\runiform highp sampler2DArray depthSampler{X};\runiform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];\runiform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];\runiform float penumbraDarkness{X};\r#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\r#else\nuniform highp sampler2DArray shadowSampler{X};\r#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\r(\rvec3 ( 1.5,0.0,0.0 ),\rvec3 ( 0.0,1.5,0.0 ),\rvec3 ( 0.0,0.0,5.5 ),\rvec3 ( 1.5,0.0,5.5 ),\rvec3 ( 1.5,1.5,0.0 ),\rvec3 ( 1.0,1.0,1.0 ),\rvec3 ( 0.0,1.0,5.5 ),\rvec3 ( 0.5,3.5,0.75 )\r);\rvec3 shadowDebug{X};\r#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\r#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\r#endif\nfloat diff{X}=0.;\r#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\r#else\nvarying vec4 vPositionFromLight{X};\rvarying float vDepthMetric{X};\r#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\runiform highp sampler2D depthSampler{X};\r#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\r#else\nuniform sampler2D shadowSampler{X};\r#endif\nuniform mat4 lightMatrix{X};\r#endif\nuniform vec4 shadowsInfo{X};\runiform vec2 depthValues{X};\r#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\runiform vec4 vLightFalloff{X};\r#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\r#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\r#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\runiform sampler2D projectionLightSampler{X};\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const lightFragmentDeclaration = { name, shader };\n//# sourceMappingURL=lightFragmentDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"lightUboDeclaration\";\nconst shader = `#ifdef LIGHT{X}\nuniform Light{X}\r{\rvec4 vLightData;\rvec4 vLightDiffuse;\rvec4 vLightSpecular;\r#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\rvec4 vLightFalloff;\r#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\r#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\r#endif\nvec4 shadowsInfo;\rvec2 depthValues;\r} light{X};\r#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\runiform sampler2D projectionLightSampler{X};\r#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];\runiform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];\runiform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];\runiform float cascadeBlendFactor{X};\rvarying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];\rvarying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];\rvarying vec4 vPositionFromCamera{X};\r#if defined(SHADOWPCSS{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\runiform highp sampler2DArray depthSampler{X};\runiform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];\runiform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];\runiform float penumbraDarkness{X};\r#elif defined(SHADOWPCF{X})\nuniform highp sampler2DArrayShadow shadowSampler{X};\r#else\nuniform highp sampler2DArray shadowSampler{X};\r#endif\n#ifdef SHADOWCSMDEBUG{X}\nconst vec3 vCascadeColorsMultiplier{X}[8]=vec3[8]\r(\rvec3 ( 1.5,0.0,0.0 ),\rvec3 ( 0.0,1.5,0.0 ),\rvec3 ( 0.0,0.0,5.5 ),\rvec3 ( 1.5,0.0,5.5 ),\rvec3 ( 1.5,1.5,0.0 ),\rvec3 ( 1.0,1.0,1.0 ),\rvec3 ( 0.0,1.0,5.5 ),\rvec3 ( 0.5,3.5,0.75 )\r);\rvec3 shadowDebug{X};\r#endif\n#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nint index{X}=-1;\r#else\nint index{X}=SHADOWCSMNUM_CASCADES{X}-1;\r#endif\nfloat diff{X}=0.;\r#elif defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \r#else\nvarying vec4 vPositionFromLight{X};\rvarying float vDepthMetric{X};\r#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\runiform highp sampler2D depthSampler{X};\r#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\r#else\nuniform sampler2D shadowSampler{X};\r#endif\nuniform mat4 lightMatrix{X};\r#endif\n#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const lightUboDeclaration = { name, shader };\n//# sourceMappingURL=lightUboDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"shadowsFragmentFunctions\";\nconst shader = `#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)\r{\rconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\rreturn dot(color,bit_shift);\r}\r#endif\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\r{\rfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));\rreturn mix(value,1.0,mask);\r}\r#define inline\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\r{\rvec3 directionToLight=vPositionW-lightPosition;\rfloat depth=length(directionToLight);\rdepth=(depth+depthValues.x)/(depthValues.y);\rdepth=clamp(depth,0.,1.0);\rdirectionToLight=normalize(directionToLight);\rdirectionToLight.y=-directionToLight.y;\r#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\r#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\r#endif\nreturn depth>shadow ? darkness : 1.0;\r}\r#define inline\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\r{\rvec3 directionToLight=vPositionW-lightPosition;\rfloat depth=length(directionToLight);\rdepth=(depth+depthValues.x)/(depthValues.y);\rdepth=clamp(depth,0.,1.0);\rdirectionToLight=normalize(directionToLight);\rdirectionToLight.y=-directionToLight.y;\rfloat visibility=1.;\rvec3 poissonDisk[4];\rpoissonDisk[0]=vec3(-1.0,1.0,-1.0);\rpoissonDisk[1]=vec3(1.0,-1.0,-1.0);\rpoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\rpoissonDisk[3]=vec3(1.0,-1.0,1.0);\r#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;\r}\r#endif\n#define inline\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\r{\rvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\rvec2 uv=0.5*clipSpace.xy+vec2(0.5);\rif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\r{\rreturn 1.0;\r}\relse\r{\rfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\r#ifndef SHADOWFLOAT\nfloat shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\r#else\nfloat shadow=TEXTUREFUNC(shadowSampler,uv,0.).x;\r#endif\nreturn shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;\r}\r}\r#define inline\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\r{\rvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\rvec2 uv=0.5*clipSpace.xy+vec2(0.5);\rif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\r{\rreturn 1.0;\r}\relse\r{\rfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\rfloat visibility=1.;\rvec2 poissonDisk[4];\rpoissonDisk[0]=vec2(-0.94201624,-0.39906216);\rpoissonDisk[1]=vec2(0.94558609,-0.76890725);\rpoissonDisk[2]=vec2(-0.094184101,-0.92938870);\rpoissonDisk[3]=vec2(0.34495938,0.29387760);\r#ifndef SHADOWFLOAT\nif (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))1.0 || uv.y<0. || uv.y>1.0)\r{\rreturn 1.0;\r}\relse\r{\rfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\r#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\r#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\r#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\rreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\r}\r}\r#define inline\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\r{\rvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\rvec2 uv=0.5*clipSpace.xy+vec2(0.5);\rif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\r{\rreturn 1.0;\r}\relse\r{\rfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \r#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.));\r#else\nfloat shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x;\r#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\rreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\r}\r}\r#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 inline\nfloat computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff)\r{\rvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\rvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\ruvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);\rvec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);\rfloat shadow=texture2D(shadowSampler,uvDepthLayer);\rshadow=mix(darkness,1.,shadow);\rreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\r}\r#define inline\nfloat computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\r{\rvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\rvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\ruvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);\rvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \ruv+=0.5; \rvec2 st=fract(uv); \rvec2 base_uv=floor(uv)-0.5; \rbase_uv*=shadowMapSizeAndInverse.y; \rvec2 uvw0=3.-2.*st;\rvec2 uvw1=1.+2.*st;\rvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\rvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\rfloat shadow=0.;\rshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));\rshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));\rshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));\rshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));\rshadow=shadow/16.;\rshadow=mix(darkness,1.,shadow);\rreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\r}\r#define inline\nfloat computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\r{\rvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\rvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\ruvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);\rvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \ruv+=0.5; \rvec2 st=fract(uv); \rvec2 base_uv=floor(uv)-0.5; \rbase_uv*=shadowMapSizeAndInverse.y; \rvec2 uvw0=4.-3.*st;\rvec2 uvw1=vec2(7.);\rvec2 uvw2=1.+3.*st;\rvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\rvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\rfloat shadow=0.;\rshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));\rshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));\rshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));\rshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));\rshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));\rshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));\rshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));\rshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));\rshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));\rshadow=shadow/144.;\rshadow=mix(darkness,1.,shadow);\rreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\r}\r#define inline\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\r{\rif (depthMetric>1.0 || depthMetric<0.0) {\rreturn 1.0;\r}\relse\r{\rvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\rvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\ruvDepth.z=ZINCLIP;\rfloat shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);\rshadow=mix(darkness,1.,shadow);\rreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\r}\r}\r#define inline\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\r{\rif (depthMetric>1.0 || depthMetric<0.0) {\rreturn 1.0;\r}\relse\r{\rvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\rvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\ruvDepth.z=ZINCLIP;\rvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \ruv+=0.5; \rvec2 st=fract(uv); \rvec2 base_uv=floor(uv)-0.5; \rbase_uv*=shadowMapSizeAndInverse.y; \rvec2 uvw0=3.-2.*st;\rvec2 uvw1=1.+2.*st;\rvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\rvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\rfloat shadow=0.;\rshadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);\rshadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);\rshadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);\rshadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);\rshadow=shadow/16.;\rshadow=mix(darkness,1.,shadow);\rreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\r}\r}\r#define inline\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\r{\rif (depthMetric>1.0 || depthMetric<0.0) {\rreturn 1.0;\r}\relse\r{\rvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\rvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\ruvDepth.z=ZINCLIP;\rvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \ruv+=0.5; \rvec2 st=fract(uv); \rvec2 base_uv=floor(uv)-0.5; \rbase_uv*=shadowMapSizeAndInverse.y; \rvec2 uvw0=4.-3.*st;\rvec2 uvw1=vec2(7.);\rvec2 uvw2=1.+3.*st;\rvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\rvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\rfloat shadow=0.;\rshadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);\rshadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);\rshadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);\rshadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);\rshadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);\rshadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);\rshadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);\rshadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);\rshadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);\rshadow=shadow/144.;\rshadow=mix(darkness,1.,shadow);\rreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\r}\r}\rconst vec3 PoissonSamplers32[64]=vec3[64](\rvec3(0.06407013,0.05409927,0.),\rvec3(0.7366577,0.5789394,0.),\rvec3(-0.6270542,-0.5320278,0.),\rvec3(-0.4096107,0.8411095,0.),\rvec3(0.6849564,-0.4990818,0.),\rvec3(-0.874181,-0.04579735,0.),\rvec3(0.9989998,0.0009880066,0.),\rvec3(-0.004920578,-0.9151649,0.),\rvec3(0.1805763,0.9747483,0.),\rvec3(-0.2138451,0.2635818,0.),\rvec3(0.109845,0.3884785,0.),\rvec3(0.06876755,-0.3581074,0.),\rvec3(0.374073,-0.7661266,0.),\rvec3(0.3079132,-0.1216763,0.),\rvec3(-0.3794335,-0.8271583,0.),\rvec3(-0.203878,-0.07715034,0.),\rvec3(0.5912697,0.1469799,0.),\rvec3(-0.88069,0.3031784,0.),\rvec3(0.5040108,0.8283722,0.),\rvec3(-0.5844124,0.5494877,0.),\rvec3(0.6017799,-0.1726654,0.),\rvec3(-0.5554981,0.1559997,0.),\rvec3(-0.3016369,-0.3900928,0.),\rvec3(-0.5550632,-0.1723762,0.),\rvec3(0.925029,0.2995041,0.),\rvec3(-0.2473137,0.5538505,0.),\rvec3(0.9183037,-0.2862392,0.),\rvec3(0.2469421,0.6718712,0.),\rvec3(0.3916397,-0.4328209,0.),\rvec3(-0.03576927,-0.6220032,0.),\rvec3(-0.04661255,0.7995201,0.),\rvec3(0.4402924,0.3640312,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.),\rvec3(0.,0.,0.)\r);\rconst vec3 PoissonSamplers64[64]=vec3[64](\rvec3(-0.613392,0.617481,0.),\rvec3(0.170019,-0.040254,0.),\rvec3(-0.299417,0.791925,0.),\rvec3(0.645680,0.493210,0.),\rvec3(-0.651784,0.717887,0.),\rvec3(0.421003,0.027070,0.),\rvec3(-0.817194,-0.271096,0.),\rvec3(-0.705374,-0.668203,0.),\rvec3(0.977050,-0.108615,0.),\rvec3(0.063326,0.142369,0.),\rvec3(0.203528,0.214331,0.),\rvec3(-0.667531,0.326090,0.),\rvec3(-0.098422,-0.295755,0.),\rvec3(-0.885922,0.215369,0.),\rvec3(0.566637,0.605213,0.),\rvec3(0.039766,-0.396100,0.),\rvec3(0.751946,0.453352,0.),\rvec3(0.078707,-0.715323,0.),\rvec3(-0.075838,-0.529344,0.),\rvec3(0.724479,-0.580798,0.),\rvec3(0.222999,-0.215125,0.),\rvec3(-0.467574,-0.405438,0.),\rvec3(-0.248268,-0.814753,0.),\rvec3(0.354411,-0.887570,0.),\rvec3(0.175817,0.382366,0.),\rvec3(0.487472,-0.063082,0.),\rvec3(-0.084078,0.898312,0.),\rvec3(0.488876,-0.783441,0.),\rvec3(0.470016,0.217933,0.),\rvec3(-0.696890,-0.549791,0.),\rvec3(-0.149693,0.605762,0.),\rvec3(0.034211,0.979980,0.),\rvec3(0.503098,-0.308878,0.),\rvec3(-0.016205,-0.872921,0.),\rvec3(0.385784,-0.393902,0.),\rvec3(-0.146886,-0.859249,0.),\rvec3(0.643361,0.164098,0.),\rvec3(0.634388,-0.049471,0.),\rvec3(-0.688894,0.007843,0.),\rvec3(0.464034,-0.188818,0.),\rvec3(-0.440840,0.137486,0.),\rvec3(0.364483,0.511704,0.),\rvec3(0.034028,0.325968,0.),\rvec3(0.099094,-0.308023,0.),\rvec3(0.693960,-0.366253,0.),\rvec3(0.678884,-0.204688,0.),\rvec3(0.001801,0.780328,0.),\rvec3(0.145177,-0.898984,0.),\rvec3(0.062655,-0.611866,0.),\rvec3(0.315226,-0.604297,0.),\rvec3(-0.780145,0.486251,0.),\rvec3(-0.371868,0.882138,0.),\rvec3(0.200476,0.494430,0.),\rvec3(-0.494552,-0.711051,0.),\rvec3(0.612476,0.705252,0.),\rvec3(-0.578845,-0.768792,0.),\rvec3(-0.772454,-0.090976,0.),\rvec3(0.504440,0.372295,0.),\rvec3(0.155736,0.065157,0.),\rvec3(0.391522,0.849605,0.),\rvec3(-0.620106,-0.328104,0.),\rvec3(0.789239,-0.419965,0.),\rvec3(-0.545396,0.538133,0.),\rvec3(-0.178564,-0.596057,0.)\r);\r#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)\r{\rvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\rvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\ruvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);\rvec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);\rfloat blockerDepth=0.0;\rfloat sumBlockerDepth=0.0;\rfloat numBlocker=0.0;\rfor (int i=0; i1.0 || depthMetric<0.0) {\rreturn 1.0;\r}\relse\r{\rvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\rvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\ruvDepth.z=ZINCLIP;\rfloat blockerDepth=0.0;\rfloat sumBlockerDepth=0.0;\rfloat numBlocker=0.0;\rfor (int i=0; i=0.) {\rindex{X}=i;\rbreak;\r}\r}\r#ifdef SHADOWCSMUSESHADOWMAXZ{X}\nif (index{X}>=0)\r#endif\n{\r#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#else\nshadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\r#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\r#else\nshadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\r#endif\n#else\nshadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#endif\n#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=vec3(shadow)*vCascadeColorsMultiplier{X}[index{X}];\r#endif\n#ifndef SHADOWCSMNOBLEND{X}\nfloat frustumLength=frustumLengths{X}[index{X}];\rfloat diffRatio=clamp(diff{X}/frustumLength,0.,1.)*cascadeBlendFactor{X};\rif (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.)\r{\rindex{X}+=1;\rfloat nextShadow=0.;\r#if defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#else\nnextShadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\r#elif defined(SHADOWMEDIUMQUALITY{X})\nnextShadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\r#else\nnextShadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X});\r#endif\n#else\nnextShadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#endif\nshadow=mix(nextShadow,shadow,diffRatio);\r#ifdef SHADOWCSMDEBUG{X}\nshadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio);\r#endif\n}\r#endif\n}\r#elif defined(SHADOWCLOSEESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\r#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\r#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\r#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\r#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\r#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\r#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\r#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\rshadowLightCount+=1.0;\r#endif\n#else\nshadow=1.;\r#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\r#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\r#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor.rgb*shadow;\r#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor.rgb;\r#endif\n#endif\n#ifdef CLEARCOAT\n#ifndef LIGHTMAPNOSPECULAR{X}\nclearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb;\r#endif\n#endif\n#ifdef SHEEN\n#ifndef LIGHTMAPNOSPECULAR{X}\nsheenBase+=info.sheen.rgb*shadow;\r#endif\n#endif\n#else\n#ifdef SHADOWCSMDEBUG{X}\ndiffuseBase+=info.diffuse*shadowDebug{X};\r#else \ndiffuseBase+=info.diffuse*shadow;\r#endif\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\r#endif\n#ifdef CLEARCOAT\nclearCoatBase+=info.clearCoat.rgb*shadow;\r#endif\n#ifdef SHEEN\nsheenBase+=info.sheen.rgb*shadow;\r#endif\n#endif\n#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const lightFragment = { name, shader };\n//# sourceMappingURL=lightFragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"lightVxFragmentDeclaration\";\nconst shader = `#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\runiform vec4 vLightDiffuse{X};\r#ifdef SPECULARTERM\nuniform vec4 vLightSpecular{X};\r#else\nvec4 vLightSpecular{X}=vec4(0.);\r#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];\rvarying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];\rvarying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];\rvarying vec4 vPositionFromCamera{X};\r#elif defined(SHADOWCUBE{X})\n#else\nvarying vec4 vPositionFromLight{X};\rvarying float vDepthMetric{X};\runiform mat4 lightMatrix{X};\r#endif\nuniform vec4 shadowsInfo{X};\runiform vec2 depthValues{X};\r#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\runiform vec4 vLightFalloff{X};\r#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\r#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const lightVxFragmentDeclaration = { name, shader };\n//# sourceMappingURL=lightVxFragmentDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"lightVxUboDeclaration\";\nconst shader = `#ifdef LIGHT{X}\nuniform Light{X}\r{\rvec4 vLightData;\rvec4 vLightDiffuse;\rvec4 vLightSpecular;\r#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\rvec4 vLightFalloff;\r#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\r#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\r#endif\nvec4 shadowsInfo;\rvec2 depthValues;\r} light{X};\r#ifdef SHADOW{X}\n#ifdef SHADOWCSM{X}\nuniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];\rvarying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];\rvarying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];\rvarying vec4 vPositionFromCamera{X};\r#elif defined(SHADOWCUBE{X})\n#else\nvarying vec4 vPositionFromLight{X};\rvarying float vDepthMetric{X};\runiform mat4 lightMatrix{X};\r#endif\n#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const lightVxUboDeclaration = { name, shader };\n//# sourceMappingURL=lightVxUboDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"morphTargetsVertexGlobalDeclaration\";\nconst shader = `#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\r#ifdef MORPHTARGETS_TEXTURE \nprecision mediump sampler2DArray; \runiform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];\runiform vec3 morphTargetTextureInfo;\runiform sampler2DArray morphTargets;\rvec3 readVector3FromRawSampler(int targetIndex,float vertexIndex)\r{ \rfloat y=floor(vertexIndex/morphTargetTextureInfo.y);\rfloat x=vertexIndex-y*morphTargetTextureInfo.y;\rvec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);\rreturn texture(morphTargets,textureUV).xyz;\r}\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const morphTargetsVertexGlobalDeclaration = { name, shader };\n//# sourceMappingURL=morphTargetsVertexGlobalDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"morphTargetsVertexDeclaration\";\nconst shader = `#ifdef MORPHTARGETS\n#ifndef MORPHTARGETS_TEXTURE\nattribute vec3 position{X};\r#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\r#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\r#endif\n#ifdef MORPHTARGETS_UV\nattribute vec2 uv_{X};\r#endif\n#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const morphTargetsVertexDeclaration = { name, shader };\n//# sourceMappingURL=morphTargetsVertexDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"bakedVertexAnimation\";\nconst shader = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\n{\r#ifdef INSTANCES\n#define BVASNAME bakedVertexAnimationSettingsInstanced\n#else\n#define BVASNAME bakedVertexAnimationSettings\n#endif\nfloat VATStartFrame=BVASNAME.x;\rfloat VATEndFrame=BVASNAME.y;\rfloat VATOffsetFrame=BVASNAME.z;\rfloat VATSpeed=BVASNAME.w;\rfloat totalFrames=VATEndFrame-VATStartFrame+1.0;\rfloat time=bakedVertexAnimationTime*VATSpeed/totalFrames;\rfloat frameCorrection=time<1.0 ? 0.0 : 1.0;\rfloat numOfFrames=totalFrames-frameCorrection;\rfloat VATFrameNum=fract(time)*numOfFrames;\rVATFrameNum=mod(VATFrameNum+VATOffsetFrame,numOfFrames);\rVATFrameNum=floor(VATFrameNum);\rVATFrameNum+=VATStartFrame+frameCorrection;\rmat4 VATInfluence;\rVATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[0],VATFrameNum)*matricesWeights[0];\r#if NUM_BONE_INFLUENCERS>1\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1];\r#endif\n#if NUM_BONE_INFLUENCERS>2\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2];\r#endif\n#if NUM_BONE_INFLUENCERS>3\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3];\r#endif\n#if NUM_BONE_INFLUENCERS>4\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0];\r#endif\n#if NUM_BONE_INFLUENCERS>5\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1];\r#endif\n#if NUM_BONE_INFLUENCERS>6\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2];\r#endif\n#if NUM_BONE_INFLUENCERS>7\nVATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3];\r#endif\nfinalWorld=finalWorld*VATInfluence;\r}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const bakedVertexAnimation = { name, shader };\n//# sourceMappingURL=bakedVertexAnimation.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"prePassVertex\";\nconst shader = `#ifdef PREPASS_DEPTH\nvViewPos=(view*worldPos).rgb;\r#endif\n#if defined(PREPASS_VELOCITY) && defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*worldPos;\r#if NUM_BONE_INFLUENCERS>0\nmat4 previousInfluence;\rpreviousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0];\r#if NUM_BONE_INFLUENCERS>1\npreviousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1];\r#endif \n#if NUM_BONE_INFLUENCERS>2\npreviousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2];\r#endif \n#if NUM_BONE_INFLUENCERS>3\npreviousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3];\r#endif\n#if NUM_BONE_INFLUENCERS>4\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\r#endif \n#if NUM_BONE_INFLUENCERS>5\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\r#endif \n#if NUM_BONE_INFLUENCERS>6\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\r#endif \n#if NUM_BONE_INFLUENCERS>7\npreviousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\r#endif\nvPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0);\r#else\nvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const prePassVertex = { name, shader };\n//# sourceMappingURL=prePassVertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"vertexColorMixing\";\nconst shader = `#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvColor=vec4(1.0);\r#ifdef VERTEXCOLOR\n#ifdef VERTEXALPHA\nvColor*=color;\r#else\nvColor.rgb*=color.rgb;\r#endif\n#endif\n#ifdef INSTANCESCOLOR\nvColor*=instanceColor;\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const vertexColorMixing = { name, shader };\n//# sourceMappingURL=vertexColorMixing.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pointCloudVertex\";\nconst shader = `#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pointCloudVertex = { name, shader };\n//# sourceMappingURL=pointCloudVertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/defaultVertexDeclaration.js\";\nimport \"./ShadersInclude/defaultUboDeclaration.js\";\nimport \"./ShadersInclude/uvAttributeDeclaration.js\";\nimport \"./ShadersInclude/helperFunctions.js\";\nimport \"./ShadersInclude/bonesDeclaration.js\";\nimport \"./ShadersInclude/bakedVertexAnimationDeclaration.js\";\nimport \"./ShadersInclude/instancesDeclaration.js\";\nimport \"./ShadersInclude/prePassVertexDeclaration.js\";\nimport \"./ShadersInclude/mainUVVaryingDeclaration.js\";\nimport \"./ShadersInclude/samplerVertexDeclaration.js\";\nimport \"./ShadersInclude/bumpVertexDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneVertexDeclaration.js\";\nimport \"./ShadersInclude/fogVertexDeclaration.js\";\nimport \"./ShadersInclude/lightVxFragmentDeclaration.js\";\nimport \"./ShadersInclude/lightVxUboDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexGlobalDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexDeclaration.js\";\nimport \"./ShadersInclude/logDepthDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexGlobal.js\";\nimport \"./ShadersInclude/morphTargetsVertex.js\";\nimport \"./ShadersInclude/instancesVertex.js\";\nimport \"./ShadersInclude/bonesVertex.js\";\nimport \"./ShadersInclude/bakedVertexAnimation.js\";\nimport \"./ShadersInclude/prePassVertex.js\";\nimport \"./ShadersInclude/uvVariableDeclaration.js\";\nimport \"./ShadersInclude/samplerVertexImplementation.js\";\nimport \"./ShadersInclude/bumpVertex.js\";\nimport \"./ShadersInclude/clipPlaneVertex.js\";\nimport \"./ShadersInclude/fogVertex.js\";\nimport \"./ShadersInclude/shadowsVertex.js\";\nimport \"./ShadersInclude/vertexColorMixing.js\";\nimport \"./ShadersInclude/pointCloudVertex.js\";\nimport \"./ShadersInclude/logDepthVertex.js\";\nconst name = \"defaultVertexShader\";\nconst shader = `#include<__decl__defaultVertex>\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\r#ifdef NORMAL\nattribute vec3 normal;\r#endif\n#ifdef TANGENT\nattribute vec4 tangent;\r#endif\n#ifdef UV1\nattribute vec2 uv;\r#endif\n#include[2..7]\n#ifdef VERTEXCOLOR\nattribute vec4 color;\r#endif\n#include\n#include\n#include\n#include\n#include\n#include[1..7]\n#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)\n#if defined(SPECULARTERM)\n#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular)\n#endif\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)\nvarying vec3 vPositionW;\r#ifdef NORMAL\nvarying vec3 vNormalW;\r#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\r#endif\n#include\n#include\n#include\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\r#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\r#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\r#ifdef NORMAL\nvec3 normalUpdated=normal;\r#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\r#endif\n#ifdef UV1\nvec2 uvUpdated=uv;\r#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\r#endif\n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include\n#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\rvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\r#endif\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\r#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\r#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));\rvNormalW=normalize(normalWorld*vNormalW);\r#else\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\r#endif\nvNormalW=normalize(normalWorld*normalUpdated);\r#endif\n#endif\n#define CUSTOM_VERTEX_UPDATE_WORLDPOS\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {\rgl_Position=viewProjection*worldPos;\r} else {\rgl_Position=viewProjectionR*worldPos;\r}\r#else\ngl_Position=viewProjection*worldPos;\r#endif\nvPositionW=vec3(worldPos);\r#include\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\r#endif\n#ifndef UV1\nvec2 uvUpdated=vec2(0.,0.);\r#endif\n#ifdef MAINUV1\nvMainUV1=uvUpdated;\r#endif\n#include[2..7]\n#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)\n#if defined(SPECULARTERM)\n#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x)\n#endif\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const defaultVertexShader = { name, shader };\n//# sourceMappingURL=default.vertex.js.map","import { Material } from \"./material.js\";\nimport { MaterialPluginEvent } from \"./materialPluginEvent.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nconst rxOption = new RegExp(\"^([gimus]+)!\");\n/**\n * Class that manages the plugins of a material\n * @since 5.0\n */\nexport class MaterialPluginManager {\n /**\n * Creates a new instance of the plugin manager\n * @param material material that this manager will manage the plugins for\n */\n constructor(material) {\n /** @internal */\n this._plugins = [];\n this._activePlugins = [];\n this._activePluginsForExtraEvents = [];\n this._material = material;\n this._scene = material.getScene();\n this._engine = this._scene.getEngine();\n }\n /**\n * @internal\n */\n _addPlugin(plugin) {\n for (let i = 0; i < this._plugins.length; ++i) {\n if (this._plugins[i].name === plugin.name) {\n return false;\n }\n }\n if (this._material._uniformBufferLayoutBuilt) {\n throw `The plugin \"${plugin.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.`;\n }\n const pluginClassName = plugin.getClassName();\n if (!MaterialPluginManager._MaterialPluginClassToMainDefine[pluginClassName]) {\n MaterialPluginManager._MaterialPluginClassToMainDefine[pluginClassName] = \"MATERIALPLUGIN_\" + ++MaterialPluginManager._MaterialPluginCounter;\n }\n this._material._callbackPluginEventGeneric = this._handlePluginEvent.bind(this);\n this._plugins.push(plugin);\n this._plugins.sort((a, b) => a.priority - b.priority);\n this._codeInjectionPoints = {};\n const defineNamesFromPlugins = {};\n defineNamesFromPlugins[MaterialPluginManager._MaterialPluginClassToMainDefine[pluginClassName]] = {\n type: \"boolean\",\n default: true,\n };\n for (const plugin of this._plugins) {\n plugin.collectDefines(defineNamesFromPlugins);\n this._collectPointNames(\"vertex\", plugin.getCustomCode(\"vertex\"));\n this._collectPointNames(\"fragment\", plugin.getCustomCode(\"fragment\"));\n }\n this._defineNamesFromPlugins = defineNamesFromPlugins;\n return true;\n }\n /**\n * @internal\n */\n _activatePlugin(plugin) {\n if (this._activePlugins.indexOf(plugin) === -1) {\n this._activePlugins.push(plugin);\n this._activePlugins.sort((a, b) => a.priority - b.priority);\n this._material._callbackPluginEventIsReadyForSubMesh = this._handlePluginEventIsReadyForSubMesh.bind(this);\n this._material._callbackPluginEventPrepareDefinesBeforeAttributes = this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this);\n this._material._callbackPluginEventPrepareDefines = this._handlePluginEventPrepareDefines.bind(this);\n this._material._callbackPluginEventBindForSubMesh = this._handlePluginEventBindForSubMesh.bind(this);\n if (plugin.registerForExtraEvents) {\n this._activePluginsForExtraEvents.push(plugin);\n this._activePluginsForExtraEvents.sort((a, b) => a.priority - b.priority);\n this._material._callbackPluginEventHasRenderTargetTextures = this._handlePluginEventHasRenderTargetTextures.bind(this);\n this._material._callbackPluginEventFillRenderTargetTextures = this._handlePluginEventFillRenderTargetTextures.bind(this);\n this._material._callbackPluginEventHardBindForSubMesh = this._handlePluginEventHardBindForSubMesh.bind(this);\n }\n }\n }\n /**\n * Gets a plugin from the list of plugins managed by this manager\n * @param name name of the plugin\n * @returns the plugin if found, else null\n */\n getPlugin(name) {\n for (let i = 0; i < this._plugins.length; ++i) {\n if (this._plugins[i].name === name) {\n return this._plugins[i];\n }\n }\n return null;\n }\n _handlePluginEventIsReadyForSubMesh(eventData) {\n let isReady = true;\n for (const plugin of this._activePlugins) {\n isReady = isReady && plugin.isReadyForSubMesh(eventData.defines, this._scene, this._engine, eventData.subMesh);\n }\n eventData.isReadyForSubMesh = isReady;\n }\n _handlePluginEventPrepareDefinesBeforeAttributes(eventData) {\n for (const plugin of this._activePlugins) {\n plugin.prepareDefinesBeforeAttributes(eventData.defines, this._scene, eventData.mesh);\n }\n }\n _handlePluginEventPrepareDefines(eventData) {\n for (const plugin of this._activePlugins) {\n plugin.prepareDefines(eventData.defines, this._scene, eventData.mesh);\n }\n }\n _handlePluginEventHardBindForSubMesh(eventData) {\n for (const plugin of this._activePluginsForExtraEvents) {\n plugin.hardBindForSubMesh(this._material._uniformBuffer, this._scene, this._engine, eventData.subMesh);\n }\n }\n _handlePluginEventBindForSubMesh(eventData) {\n for (const plugin of this._activePlugins) {\n plugin.bindForSubMesh(this._material._uniformBuffer, this._scene, this._engine, eventData.subMesh);\n }\n }\n _handlePluginEventHasRenderTargetTextures(eventData) {\n let hasRenderTargetTextures = false;\n for (const plugin of this._activePluginsForExtraEvents) {\n hasRenderTargetTextures = plugin.hasRenderTargetTextures();\n if (hasRenderTargetTextures) {\n break;\n }\n }\n eventData.hasRenderTargetTextures = hasRenderTargetTextures;\n }\n _handlePluginEventFillRenderTargetTextures(eventData) {\n for (const plugin of this._activePluginsForExtraEvents) {\n plugin.fillRenderTargetTextures(eventData.renderTargets);\n }\n }\n _handlePluginEvent(id, info) {\n var _a;\n switch (id) {\n case MaterialPluginEvent.GetActiveTextures: {\n const eventData = info;\n for (const plugin of this._activePlugins) {\n plugin.getActiveTextures(eventData.activeTextures);\n }\n break;\n }\n case MaterialPluginEvent.GetAnimatables: {\n const eventData = info;\n for (const plugin of this._activePlugins) {\n plugin.getAnimatables(eventData.animatables);\n }\n break;\n }\n case MaterialPluginEvent.HasTexture: {\n const eventData = info;\n let hasTexture = false;\n for (const plugin of this._activePlugins) {\n hasTexture = plugin.hasTexture(eventData.texture);\n if (hasTexture) {\n break;\n }\n }\n eventData.hasTexture = hasTexture;\n break;\n }\n case MaterialPluginEvent.Disposed: {\n const eventData = info;\n for (const plugin of this._plugins) {\n plugin.dispose(eventData.forceDisposeTextures);\n }\n break;\n }\n case MaterialPluginEvent.GetDefineNames: {\n const eventData = info;\n eventData.defineNames = this._defineNamesFromPlugins;\n break;\n }\n case MaterialPluginEvent.PrepareEffect: {\n const eventData = info;\n for (const plugin of this._activePlugins) {\n eventData.fallbackRank = plugin.addFallbacks(eventData.defines, eventData.fallbacks, eventData.fallbackRank);\n plugin.getAttributes(eventData.attributes, this._scene, eventData.mesh);\n }\n if (this._uniformList.length > 0) {\n eventData.uniforms.push(...this._uniformList);\n }\n if (this._samplerList.length > 0) {\n eventData.samplers.push(...this._samplerList);\n }\n if (this._uboList.length > 0) {\n eventData.uniformBuffersNames.push(...this._uboList);\n }\n eventData.customCode = this._injectCustomCode(eventData.customCode);\n break;\n }\n case MaterialPluginEvent.PrepareUniformBuffer: {\n const eventData = info;\n this._uboDeclaration = \"\";\n this._vertexDeclaration = \"\";\n this._fragmentDeclaration = \"\";\n this._uniformList = [];\n this._samplerList = [];\n this._uboList = [];\n for (const plugin of this._plugins) {\n const uniforms = plugin.getUniforms();\n if (uniforms) {\n if (uniforms.ubo) {\n for (const uniform of uniforms.ubo) {\n if (uniform.size && uniform.type) {\n const arraySize = (_a = uniform.arraySize) !== null && _a !== void 0 ? _a : 0;\n eventData.ubo.addUniform(uniform.name, uniform.size, arraySize);\n this._uboDeclaration += `${uniform.type} ${uniform.name}${arraySize > 0 ? `[${arraySize}]` : \"\"};\\r\\n`;\n }\n this._uniformList.push(uniform.name);\n }\n }\n if (uniforms.vertex) {\n this._vertexDeclaration += uniforms.vertex + \"\\r\\n\";\n }\n if (uniforms.fragment) {\n this._fragmentDeclaration += uniforms.fragment + \"\\r\\n\";\n }\n }\n plugin.getSamplers(this._samplerList);\n plugin.getUniformBuffersNames(this._uboList);\n }\n break;\n }\n }\n }\n _collectPointNames(shaderType, customCode) {\n if (!customCode) {\n return;\n }\n for (const pointName in customCode) {\n if (!this._codeInjectionPoints[shaderType]) {\n this._codeInjectionPoints[shaderType] = {};\n }\n this._codeInjectionPoints[shaderType][pointName] = true;\n }\n }\n _injectCustomCode(existingCallback) {\n return (shaderType, code) => {\n var _a;\n if (existingCallback) {\n code = existingCallback(shaderType, code);\n }\n if (this._uboDeclaration) {\n code = code.replace(\"#define ADDITIONAL_UBO_DECLARATION\", this._uboDeclaration);\n }\n if (this._vertexDeclaration) {\n code = code.replace(\"#define ADDITIONAL_VERTEX_DECLARATION\", this._vertexDeclaration);\n }\n if (this._fragmentDeclaration) {\n code = code.replace(\"#define ADDITIONAL_FRAGMENT_DECLARATION\", this._fragmentDeclaration);\n }\n const points = (_a = this._codeInjectionPoints) === null || _a === void 0 ? void 0 : _a[shaderType];\n if (!points) {\n return code;\n }\n for (let pointName in points) {\n let injectedCode = \"\";\n for (const plugin of this._activePlugins) {\n const customCode = plugin.getCustomCode(shaderType);\n if (customCode === null || customCode === void 0 ? void 0 : customCode[pointName]) {\n injectedCode += customCode[pointName] + \"\\r\\n\";\n }\n }\n if (injectedCode.length > 0) {\n if (pointName.charAt(0) === \"!\") {\n // pointName is a regular expression\n pointName = pointName.substring(1);\n let regexFlags = \"g\";\n if (pointName.charAt(0) === \"!\") {\n // no flags\n regexFlags = \"\";\n pointName = pointName.substring(1);\n }\n else {\n // get the flag(s)\n const matchOption = rxOption.exec(pointName);\n if (matchOption && matchOption.length >= 2) {\n regexFlags = matchOption[1];\n pointName = pointName.substring(regexFlags.length + 1);\n }\n }\n if (regexFlags.indexOf(\"g\") < 0) {\n // we force the \"g\" flag so that the regexp object is stateful!\n regexFlags += \"g\";\n }\n const sourceCode = code;\n const rx = new RegExp(pointName, regexFlags);\n let match = rx.exec(sourceCode);\n while (match !== null) {\n let newCode = injectedCode;\n for (let i = 0; i < match.length; ++i) {\n newCode = newCode.replace(\"$\" + i, match[i]);\n }\n code = code.replace(match[0], newCode);\n match = rx.exec(sourceCode);\n }\n }\n else {\n const fullPointName = \"#define \" + pointName;\n code = code.replace(fullPointName, \"\\r\\n\" + injectedCode + \"\\r\\n\" + fullPointName);\n }\n }\n }\n return code;\n };\n }\n}\n/** Map a plugin class name to a #define name (used in the vertex/fragment shaders as a marker of the plugin usage) */\nMaterialPluginManager._MaterialPluginClassToMainDefine = {};\nMaterialPluginManager._MaterialPluginCounter = 0;\n(() => {\n EngineStore.OnEnginesDisposedObservable.add(() => {\n UnregisterAllMaterialPlugins();\n });\n})();\nconst plugins = [];\nlet inited = false;\nlet observer = null;\n/**\n * Registers a new material plugin through a factory, or updates it. This makes the plugin available to all materials instantiated after its registration.\n * @param pluginName The plugin name\n * @param factory The factory function which allows to create the plugin\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function RegisterMaterialPlugin(pluginName, factory) {\n if (!inited) {\n observer = Material.OnEventObservable.add((material) => {\n for (const [, factory] of plugins) {\n factory(material);\n }\n }, MaterialPluginEvent.Created);\n inited = true;\n }\n const existing = plugins.filter(([name, _factory]) => name === pluginName);\n if (existing.length > 0) {\n existing[0][1] = factory;\n }\n else {\n plugins.push([pluginName, factory]);\n }\n}\n/**\n * Removes a material plugin from the list of global plugins.\n * @param pluginName The plugin name\n * @returns true if the plugin has been removed, else false\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function UnregisterMaterialPlugin(pluginName) {\n for (let i = 0; i < plugins.length; ++i) {\n if (plugins[i][0] === pluginName) {\n plugins.splice(i, 1);\n if (plugins.length === 0) {\n UnregisterAllMaterialPlugins();\n }\n return true;\n }\n }\n return false;\n}\n/**\n * Clear the list of global material plugins\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function UnregisterAllMaterialPlugins() {\n plugins.length = 0;\n inited = false;\n Material.OnEventObservable.remove(observer);\n observer = null;\n}\n//# sourceMappingURL=materialPluginManager.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { SerializationHelper, serialize } from \"../Misc/decorators.js\";\nimport { MaterialPluginManager } from \"./materialPluginManager.js\";\n\n/**\n * Base class for material plugins.\n * @since 5.0\n */\nexport class MaterialPluginBase {\n _enable(enable) {\n if (enable) {\n this._pluginManager._activatePlugin(this);\n }\n }\n /**\n * Creates a new material plugin\n * @param material parent material of the plugin\n * @param name name of the plugin\n * @param priority priority of the plugin\n * @param defines list of defines used by the plugin. The value of the property is the default value for this property\n * @param addToPluginList true to add the plugin to the list of plugins managed by the material plugin manager of the material (default: true)\n * @param enable true to enable the plugin (it is handy if the plugin does not handle properties to switch its current activation)\n */\n constructor(material, name, priority, defines, addToPluginList = true, enable = false) {\n /**\n * Defines the priority of the plugin. Lower numbers run first.\n */\n this.priority = 500;\n /**\n * Indicates that this plugin should be notified for the extra events (HasRenderTargetTextures / FillRenderTargetTextures / HardBindForSubMesh)\n */\n this.registerForExtraEvents = false;\n this._material = material;\n this.name = name;\n this.priority = priority;\n if (!material.pluginManager) {\n material.pluginManager = new MaterialPluginManager(material);\n material.onDisposeObservable.add(() => {\n material.pluginManager = undefined;\n });\n }\n this._pluginDefineNames = defines;\n this._pluginManager = material.pluginManager;\n if (addToPluginList) {\n this._pluginManager._addPlugin(this);\n }\n if (enable) {\n this._enable(true);\n }\n this.markAllDefinesAsDirty = material._dirtyCallbacks[63];\n }\n /**\n * Gets the current class name useful for serialization or dynamic coding.\n * @returns The class name.\n */\n getClassName() {\n return \"MaterialPluginBase\";\n }\n /**\n * Specifies that the submesh is ready to be used.\n * @param defines the list of \"defines\" to update.\n * @param scene defines the scene the material belongs to.\n * @param engine the engine this scene belongs to.\n * @param subMesh the submesh to check for readiness\n * @returns - boolean indicating that the submesh is ready or not.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isReadyForSubMesh(defines, scene, engine, subMesh) {\n return true;\n }\n /**\n * Binds the material data (this function is called even if mustRebind() returns false)\n * @param uniformBuffer defines the Uniform buffer to fill in.\n * @param scene defines the scene the material belongs to.\n * @param engine defines the engine the material belongs to.\n * @param subMesh the submesh to bind data for\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n hardBindForSubMesh(uniformBuffer, scene, engine, subMesh) { }\n /**\n * Binds the material data.\n * @param uniformBuffer defines the Uniform buffer to fill in.\n * @param scene defines the scene the material belongs to.\n * @param engine the engine this scene belongs to.\n * @param subMesh the submesh to bind data for\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n bindForSubMesh(uniformBuffer, scene, engine, subMesh) { }\n /**\n * Disposes the resources of the material.\n * @param forceDisposeTextures - Forces the disposal of all textures.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n dispose(forceDisposeTextures) { }\n /**\n * Returns a list of custom shader code fragments to customize the shader.\n * @param shaderType \"vertex\" or \"fragment\"\n * @returns null if no code to be added, or a list of pointName => code.\n * Note that `pointName` can also be a regular expression if it starts with a `!`.\n * In that case, the string found by the regular expression (if any) will be\n * replaced by the code provided.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getCustomCode(shaderType) {\n return null;\n }\n /**\n * Collects all defines.\n * @param defines The object to append to.\n */\n collectDefines(defines) {\n if (!this._pluginDefineNames) {\n return;\n }\n for (const key of Object.keys(this._pluginDefineNames)) {\n if (key[0] === \"_\") {\n continue;\n }\n const type = typeof this._pluginDefineNames[key];\n defines[key] = {\n type: type === \"number\" ? \"number\" : type === \"string\" ? \"string\" : type === \"boolean\" ? \"boolean\" : \"object\",\n default: this._pluginDefineNames[key],\n };\n }\n }\n /**\n * Sets the defines for the next rendering. Called before MaterialHelper.PrepareDefinesForAttributes is called.\n * @param defines the list of \"defines\" to update.\n * @param scene defines the scene to the material belongs to.\n * @param mesh the mesh being rendered\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n prepareDefinesBeforeAttributes(defines, scene, mesh) { }\n /**\n * Sets the defines for the next rendering\n * @param defines the list of \"defines\" to update.\n * @param scene defines the scene to the material belongs to.\n * @param mesh the mesh being rendered\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n prepareDefines(defines, scene, mesh) { }\n /**\n * Checks to see if a texture is used in the material.\n * @param texture - Base texture to use.\n * @returns - Boolean specifying if a texture is used in the material.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n hasTexture(texture) {\n return false;\n }\n /**\n * Gets a boolean indicating that current material needs to register RTT\n * @returns true if this uses a render target otherwise false.\n */\n hasRenderTargetTextures() {\n return false;\n }\n /**\n * Fills the list of render target textures.\n * @param renderTargets the list of render targets to update\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n fillRenderTargetTextures(renderTargets) { }\n /**\n * Returns an array of the actively used textures.\n * @param activeTextures Array of BaseTextures\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getActiveTextures(activeTextures) { }\n /**\n * Returns the animatable textures.\n * @param animatables Array of animatable textures.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getAnimatables(animatables) { }\n /**\n * Add fallbacks to the effect fallbacks list.\n * @param defines defines the Base texture to use.\n * @param fallbacks defines the current fallback list.\n * @param currentRank defines the current fallback rank.\n * @returns the new fallback rank.\n */\n addFallbacks(defines, fallbacks, currentRank) {\n return currentRank;\n }\n /**\n * Gets the samplers used by the plugin.\n * @param samplers list that the sampler names should be added to.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getSamplers(samplers) { }\n /**\n * Gets the attributes used by the plugin.\n * @param attributes list that the attribute names should be added to.\n * @param scene the scene that the material belongs to.\n * @param mesh the mesh being rendered.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getAttributes(attributes, scene, mesh) { }\n /**\n * Gets the uniform buffers names added by the plugin.\n * @param ubos list that the ubo names should be added to.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getUniformBuffersNames(ubos) { }\n /**\n * Gets the description of the uniforms to add to the ubo (if engine supports ubos) or to inject directly in the vertex/fragment shaders (if engine does not support ubos)\n * @returns the description of the uniforms\n */\n getUniforms() {\n return {};\n }\n /**\n * Makes a duplicate of the current configuration into another one.\n * @param plugin define the config where to copy the info\n */\n copyTo(plugin) {\n SerializationHelper.Clone(() => plugin, this);\n }\n /**\n * Serializes this plugin configuration.\n * @returns - An object with the serialized config.\n */\n serialize() {\n return SerializationHelper.Serialize(this);\n }\n /**\n * Parses a plugin configuration from a serialized object.\n * @param source - Serialized object.\n * @param scene Defines the scene we are parsing for\n * @param rootUrl Defines the rootUrl to load from\n */\n parse(source, scene, rootUrl) {\n SerializationHelper.Parse(() => this, source, scene, rootUrl);\n }\n}\n__decorate([\n serialize()\n], MaterialPluginBase.prototype, \"name\", void 0);\n__decorate([\n serialize()\n], MaterialPluginBase.prototype, \"priority\", void 0);\n__decorate([\n serialize()\n], MaterialPluginBase.prototype, \"registerForExtraEvents\", void 0);\n//# sourceMappingURL=materialPluginBase.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { Material } from \"./material.js\";\nimport { serialize, expandToProperty, serializeAsTexture } from \"../Misc/decorators.js\";\nimport { MaterialFlags } from \"./materialFlags.js\";\nimport { MaterialHelper } from \"./materialHelper.js\";\nimport { MaterialDefines } from \"./materialDefines.js\";\nimport { MaterialPluginBase } from \"./materialPluginBase.js\";\n\n/**\n * @internal\n */\nexport class MaterialDetailMapDefines extends MaterialDefines {\n constructor() {\n super(...arguments);\n this.DETAIL = false;\n this.DETAILDIRECTUV = 0;\n this.DETAIL_NORMALBLENDMETHOD = 0;\n }\n}\n/**\n * Plugin that implements the detail map component of a material\n *\n * Inspired from:\n * Unity: https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@9.0/manual/Mask-Map-and-Detail-Map.html and https://docs.unity3d.com/Manual/StandardShaderMaterialParameterDetail.html\n * Unreal: https://docs.unrealengine.com/en-US/Engine/Rendering/Materials/HowTo/DetailTexturing/index.html\n * Cryengine: https://docs.cryengine.com/display/SDKDOC2/Detail+Maps\n */\nexport class DetailMapConfiguration extends MaterialPluginBase {\n /** @internal */\n _markAllSubMeshesAsTexturesDirty() {\n this._enable(this._isEnabled);\n this._internalMarkAllSubMeshesAsTexturesDirty();\n }\n constructor(material, addToPluginList = true) {\n super(material, \"DetailMap\", 140, new MaterialDetailMapDefines(), addToPluginList);\n this._texture = null;\n /**\n * Defines how strongly the detail diffuse/albedo channel is blended with the regular diffuse/albedo texture\n * Bigger values mean stronger blending\n */\n this.diffuseBlendLevel = 1;\n /**\n * Defines how strongly the detail roughness channel is blended with the regular roughness value\n * Bigger values mean stronger blending. Only used with PBR materials\n */\n this.roughnessBlendLevel = 1;\n /**\n * Defines how strong the bump effect from the detail map is\n * Bigger values mean stronger effect\n */\n this.bumpLevel = 1;\n this._normalBlendMethod = Material.MATERIAL_NORMALBLENDMETHOD_WHITEOUT;\n this._isEnabled = false;\n /**\n * Enable or disable the detail map on this material\n */\n this.isEnabled = false;\n this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];\n }\n isReadyForSubMesh(defines, scene, engine) {\n if (!this._isEnabled) {\n return true;\n }\n if (defines._areTexturesDirty && scene.texturesEnabled) {\n if (engine.getCaps().standardDerivatives && this._texture && MaterialFlags.DetailTextureEnabled) {\n // Detail texture cannot be not blocking.\n if (!this._texture.isReady()) {\n return false;\n }\n }\n }\n return true;\n }\n prepareDefines(defines, scene) {\n if (this._isEnabled) {\n defines.DETAIL_NORMALBLENDMETHOD = this._normalBlendMethod;\n const engine = scene.getEngine();\n if (defines._areTexturesDirty) {\n if (engine.getCaps().standardDerivatives && this._texture && MaterialFlags.DetailTextureEnabled && this._isEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._texture, defines, \"DETAIL\");\n defines.DETAIL_NORMALBLENDMETHOD = this._normalBlendMethod;\n }\n else {\n defines.DETAIL = false;\n }\n }\n }\n else {\n defines.DETAIL = false;\n }\n }\n bindForSubMesh(uniformBuffer, scene) {\n if (!this._isEnabled) {\n return;\n }\n const isFrozen = this._material.isFrozen;\n if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {\n if (this._texture && MaterialFlags.DetailTextureEnabled) {\n uniformBuffer.updateFloat4(\"vDetailInfos\", this._texture.coordinatesIndex, this.diffuseBlendLevel, this.bumpLevel, this.roughnessBlendLevel);\n MaterialHelper.BindTextureMatrix(this._texture, uniformBuffer, \"detail\");\n }\n }\n // Textures\n if (scene.texturesEnabled) {\n if (this._texture && MaterialFlags.DetailTextureEnabled) {\n uniformBuffer.setTexture(\"detailSampler\", this._texture);\n }\n }\n }\n hasTexture(texture) {\n if (this._texture === texture) {\n return true;\n }\n return false;\n }\n getActiveTextures(activeTextures) {\n if (this._texture) {\n activeTextures.push(this._texture);\n }\n }\n getAnimatables(animatables) {\n if (this._texture && this._texture.animations && this._texture.animations.length > 0) {\n animatables.push(this._texture);\n }\n }\n dispose(forceDisposeTextures) {\n var _a;\n if (forceDisposeTextures) {\n (_a = this._texture) === null || _a === void 0 ? void 0 : _a.dispose();\n }\n }\n getClassName() {\n return \"DetailMapConfiguration\";\n }\n getSamplers(samplers) {\n samplers.push(\"detailSampler\");\n }\n getUniforms() {\n return {\n ubo: [\n { name: \"vDetailInfos\", size: 4, type: \"vec4\" },\n { name: \"detailMatrix\", size: 16, type: \"mat4\" },\n ],\n };\n }\n}\n__decorate([\n serializeAsTexture(\"detailTexture\"),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], DetailMapConfiguration.prototype, \"texture\", void 0);\n__decorate([\n serialize()\n], DetailMapConfiguration.prototype, \"diffuseBlendLevel\", void 0);\n__decorate([\n serialize()\n], DetailMapConfiguration.prototype, \"roughnessBlendLevel\", void 0);\n__decorate([\n serialize()\n], DetailMapConfiguration.prototype, \"bumpLevel\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], DetailMapConfiguration.prototype, \"normalBlendMethod\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], DetailMapConfiguration.prototype, \"isEnabled\", void 0);\n//# sourceMappingURL=material.detailMapConfiguration.js.map","import { __decorate } from \"../tslib.es6.js\";\n/* eslint-disable @typescript-eslint/naming-convention */\nimport { serialize, SerializationHelper, serializeAsColor3, expandToProperty, serializeAsFresnelParameters, serializeAsTexture } from \"../Misc/decorators.js\";\nimport { SmartArray } from \"../Misc/smartArray.js\";\nimport { Scene } from \"../scene.js\";\nimport { Matrix } from \"../Maths/math.vector.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { PrePassConfiguration } from \"./prePassConfiguration.js\";\nimport { ImageProcessingConfiguration } from \"./imageProcessingConfiguration.js\";\nimport { Material } from \"../Materials/material.js\";\nimport { MaterialPluginEvent } from \"./materialPluginEvent.js\";\nimport { MaterialDefines } from \"../Materials/materialDefines.js\";\nimport { PushMaterial } from \"./pushMaterial.js\";\nimport { MaterialHelper } from \"./materialHelper.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\nimport { MaterialFlags } from \"./materialFlags.js\";\nimport \"../Shaders/default.fragment.js\";\nimport \"../Shaders/default.vertex.js\";\n\nimport { EffectFallbacks } from \"./effectFallbacks.js\";\nimport { DetailMapConfiguration } from \"./material.detailMapConfiguration.js\";\nimport { addClipPlaneUniforms, bindClipPlane } from \"./clipPlaneMaterialHelper.js\";\nconst onCreatedEffectParameters = { effect: null, subMesh: null };\n/** @internal */\nexport class StandardMaterialDefines extends MaterialDefines {\n /**\n * Initializes the Standard Material defines.\n * @param externalProperties The external properties\n */\n constructor(externalProperties) {\n super(externalProperties);\n this.MAINUV1 = false;\n this.MAINUV2 = false;\n this.MAINUV3 = false;\n this.MAINUV4 = false;\n this.MAINUV5 = false;\n this.MAINUV6 = false;\n this.DIFFUSE = false;\n this.DIFFUSEDIRECTUV = 0;\n this.BAKED_VERTEX_ANIMATION_TEXTURE = false;\n this.AMBIENT = false;\n this.AMBIENTDIRECTUV = 0;\n this.OPACITY = false;\n this.OPACITYDIRECTUV = 0;\n this.OPACITYRGB = false;\n this.REFLECTION = false;\n this.EMISSIVE = false;\n this.EMISSIVEDIRECTUV = 0;\n this.SPECULAR = false;\n this.SPECULARDIRECTUV = 0;\n this.BUMP = false;\n this.BUMPDIRECTUV = 0;\n this.PARALLAX = false;\n this.PARALLAXOCCLUSION = false;\n this.SPECULAROVERALPHA = false;\n this.CLIPPLANE = false;\n this.CLIPPLANE2 = false;\n this.CLIPPLANE3 = false;\n this.CLIPPLANE4 = false;\n this.CLIPPLANE5 = false;\n this.CLIPPLANE6 = false;\n this.ALPHATEST = false;\n this.DEPTHPREPASS = false;\n this.ALPHAFROMDIFFUSE = false;\n this.POINTSIZE = false;\n this.FOG = false;\n this.SPECULARTERM = false;\n this.DIFFUSEFRESNEL = false;\n this.OPACITYFRESNEL = false;\n this.REFLECTIONFRESNEL = false;\n this.REFRACTIONFRESNEL = false;\n this.EMISSIVEFRESNEL = false;\n this.FRESNEL = false;\n this.NORMAL = false;\n this.TANGENT = false;\n this.UV1 = false;\n this.UV2 = false;\n this.UV3 = false;\n this.UV4 = false;\n this.UV5 = false;\n this.UV6 = false;\n this.VERTEXCOLOR = false;\n this.VERTEXALPHA = false;\n this.NUM_BONE_INFLUENCERS = 0;\n this.BonesPerMesh = 0;\n this.BONETEXTURE = false;\n this.BONES_VELOCITY_ENABLED = false;\n this.INSTANCES = false;\n this.THIN_INSTANCES = false;\n this.INSTANCESCOLOR = false;\n this.GLOSSINESS = false;\n this.ROUGHNESS = false;\n this.EMISSIVEASILLUMINATION = false;\n this.LINKEMISSIVEWITHDIFFUSE = false;\n this.REFLECTIONFRESNELFROMSPECULAR = false;\n this.LIGHTMAP = false;\n this.LIGHTMAPDIRECTUV = 0;\n this.OBJECTSPACE_NORMALMAP = false;\n this.USELIGHTMAPASSHADOWMAP = false;\n this.REFLECTIONMAP_3D = false;\n this.REFLECTIONMAP_SPHERICAL = false;\n this.REFLECTIONMAP_PLANAR = false;\n this.REFLECTIONMAP_CUBIC = false;\n this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;\n this.USE_LOCAL_REFRACTIONMAP_CUBIC = false;\n this.REFLECTIONMAP_PROJECTION = false;\n this.REFLECTIONMAP_SKYBOX = false;\n this.REFLECTIONMAP_EXPLICIT = false;\n this.REFLECTIONMAP_EQUIRECTANGULAR = false;\n this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;\n this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;\n this.REFLECTIONMAP_OPPOSITEZ = false;\n this.INVERTCUBICMAP = false;\n this.LOGARITHMICDEPTH = false;\n this.REFRACTION = false;\n this.REFRACTIONMAP_3D = false;\n this.REFLECTIONOVERALPHA = false;\n this.TWOSIDEDLIGHTING = false;\n this.SHADOWFLOAT = false;\n this.MORPHTARGETS = false;\n this.MORPHTARGETS_NORMAL = false;\n this.MORPHTARGETS_TANGENT = false;\n this.MORPHTARGETS_UV = false;\n this.NUM_MORPH_INFLUENCERS = 0;\n this.MORPHTARGETS_TEXTURE = false;\n this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH\n this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7\n this.ALPHATEST_AFTERALLALPHACOMPUTATIONS = false;\n this.ALPHABLEND = true;\n this.PREPASS = false;\n this.PREPASS_IRRADIANCE = false;\n this.PREPASS_IRRADIANCE_INDEX = -1;\n this.PREPASS_ALBEDO_SQRT = false;\n this.PREPASS_ALBEDO_SQRT_INDEX = -1;\n this.PREPASS_DEPTH = false;\n this.PREPASS_DEPTH_INDEX = -1;\n this.PREPASS_NORMAL = false;\n this.PREPASS_NORMAL_INDEX = -1;\n this.PREPASS_POSITION = false;\n this.PREPASS_POSITION_INDEX = -1;\n this.PREPASS_VELOCITY = false;\n this.PREPASS_VELOCITY_INDEX = -1;\n this.PREPASS_REFLECTIVITY = false;\n this.PREPASS_REFLECTIVITY_INDEX = -1;\n this.SCENE_MRT_COUNT = 0;\n this.RGBDLIGHTMAP = false;\n this.RGBDREFLECTION = false;\n this.RGBDREFRACTION = false;\n this.IMAGEPROCESSING = false;\n this.VIGNETTE = false;\n this.VIGNETTEBLENDMODEMULTIPLY = false;\n this.VIGNETTEBLENDMODEOPAQUE = false;\n this.TONEMAPPING = false;\n this.TONEMAPPING_ACES = false;\n this.CONTRAST = false;\n this.COLORCURVES = false;\n this.COLORGRADING = false;\n this.COLORGRADING3D = false;\n this.SAMPLER3DGREENDEPTH = false;\n this.SAMPLER3DBGRMAP = false;\n this.DITHER = false;\n this.IMAGEPROCESSINGPOSTPROCESS = false;\n this.SKIPFINALCOLORCLAMP = false;\n this.MULTIVIEW = false;\n this.ORDER_INDEPENDENT_TRANSPARENCY = false;\n this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS = false;\n this.CAMERA_ORTHOGRAPHIC = false;\n this.CAMERA_PERSPECTIVE = false;\n /**\n * If the reflection texture on this material is in linear color space\n * @internal\n */\n this.IS_REFLECTION_LINEAR = false;\n /**\n * If the refraction texture on this material is in linear color space\n * @internal\n */\n this.IS_REFRACTION_LINEAR = false;\n this.EXPOSURE = false;\n this.rebuild();\n }\n setReflectionMode(modeToEnable) {\n const modes = [\n \"REFLECTIONMAP_CUBIC\",\n \"REFLECTIONMAP_EXPLICIT\",\n \"REFLECTIONMAP_PLANAR\",\n \"REFLECTIONMAP_PROJECTION\",\n \"REFLECTIONMAP_PROJECTION\",\n \"REFLECTIONMAP_SKYBOX\",\n \"REFLECTIONMAP_SPHERICAL\",\n \"REFLECTIONMAP_EQUIRECTANGULAR\",\n \"REFLECTIONMAP_EQUIRECTANGULAR_FIXED\",\n \"REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\",\n ];\n for (const mode of modes) {\n this[mode] = mode === modeToEnable;\n }\n }\n}\n/**\n * This is the default material used in Babylon. It is the best trade off between quality\n * and performances.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction\n */\nexport class StandardMaterial extends PushMaterial {\n /**\n * Gets the image processing configuration used either in this material.\n */\n get imageProcessingConfiguration() {\n return this._imageProcessingConfiguration;\n }\n /**\n * Sets the Default image processing configuration used either in the this material.\n *\n * If sets to null, the scene one is in use.\n */\n set imageProcessingConfiguration(value) {\n this._attachImageProcessingConfiguration(value);\n // Ensure the effect will be rebuilt.\n this._markAllSubMeshesAsTexturesDirty();\n }\n /**\n * Attaches a new image processing configuration to the Standard Material.\n * @param configuration\n */\n _attachImageProcessingConfiguration(configuration) {\n if (configuration === this._imageProcessingConfiguration) {\n return;\n }\n // Detaches observer\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n // Pick the scene configuration if needed\n if (!configuration) {\n this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;\n }\n else {\n this._imageProcessingConfiguration = configuration;\n }\n // Attaches observer\n if (this._imageProcessingConfiguration) {\n this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => {\n this._markAllSubMeshesAsImageProcessingDirty();\n });\n }\n }\n /**\n * Can this material render to prepass\n */\n get isPrePassCapable() {\n return !this.disableDepthWrite;\n }\n /**\n * Gets whether the color curves effect is enabled.\n */\n get cameraColorCurvesEnabled() {\n return this.imageProcessingConfiguration.colorCurvesEnabled;\n }\n /**\n * Sets whether the color curves effect is enabled.\n */\n set cameraColorCurvesEnabled(value) {\n this.imageProcessingConfiguration.colorCurvesEnabled = value;\n }\n /**\n * Gets whether the color grading effect is enabled.\n */\n get cameraColorGradingEnabled() {\n return this.imageProcessingConfiguration.colorGradingEnabled;\n }\n /**\n * Gets whether the color grading effect is enabled.\n */\n set cameraColorGradingEnabled(value) {\n this.imageProcessingConfiguration.colorGradingEnabled = value;\n }\n /**\n * Gets whether tonemapping is enabled or not.\n */\n get cameraToneMappingEnabled() {\n return this._imageProcessingConfiguration.toneMappingEnabled;\n }\n /**\n * Sets whether tonemapping is enabled or not\n */\n set cameraToneMappingEnabled(value) {\n this._imageProcessingConfiguration.toneMappingEnabled = value;\n }\n /**\n * The camera exposure used on this material.\n * This property is here and not in the camera to allow controlling exposure without full screen post process.\n * This corresponds to a photographic exposure.\n */\n get cameraExposure() {\n return this._imageProcessingConfiguration.exposure;\n }\n /**\n * The camera exposure used on this material.\n * This property is here and not in the camera to allow controlling exposure without full screen post process.\n * This corresponds to a photographic exposure.\n */\n set cameraExposure(value) {\n this._imageProcessingConfiguration.exposure = value;\n }\n /**\n * Gets The camera contrast used on this material.\n */\n get cameraContrast() {\n return this._imageProcessingConfiguration.contrast;\n }\n /**\n * Sets The camera contrast used on this material.\n */\n set cameraContrast(value) {\n this._imageProcessingConfiguration.contrast = value;\n }\n /**\n * Gets the Color Grading 2D Lookup Texture.\n */\n get cameraColorGradingTexture() {\n return this._imageProcessingConfiguration.colorGradingTexture;\n }\n /**\n * Sets the Color Grading 2D Lookup Texture.\n */\n set cameraColorGradingTexture(value) {\n this._imageProcessingConfiguration.colorGradingTexture = value;\n }\n /**\n * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\n get cameraColorCurves() {\n return this._imageProcessingConfiguration.colorCurves;\n }\n /**\n * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\n set cameraColorCurves(value) {\n this._imageProcessingConfiguration.colorCurves = value;\n }\n /**\n * Can this material render to several textures at once\n */\n get canRenderToMRT() {\n return true;\n }\n /**\n * Instantiates a new standard material.\n * This is the default material used in Babylon. It is the best trade off between quality\n * and performances.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction\n * @param name Define the name of the material in the scene\n * @param scene Define the scene the material belong to\n */\n constructor(name, scene) {\n super(name, scene);\n this._diffuseTexture = null;\n this._ambientTexture = null;\n this._opacityTexture = null;\n this._reflectionTexture = null;\n this._emissiveTexture = null;\n this._specularTexture = null;\n this._bumpTexture = null;\n this._lightmapTexture = null;\n this._refractionTexture = null;\n /**\n * The color of the material lit by the environmental background lighting.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction#ambient-color-example\n */\n this.ambientColor = new Color3(0, 0, 0);\n /**\n * The basic color of the material as viewed under a light.\n */\n this.diffuseColor = new Color3(1, 1, 1);\n /**\n * Define how the color and intensity of the highlight given by the light in the material.\n */\n this.specularColor = new Color3(1, 1, 1);\n /**\n * Define the color of the material as if self lit.\n * This will be mixed in the final result even in the absence of light.\n */\n this.emissiveColor = new Color3(0, 0, 0);\n /**\n * Defines how sharp are the highlights in the material.\n * The bigger the value the sharper giving a more glossy feeling to the result.\n * Reversely, the smaller the value the blurrier giving a more rough feeling to the result.\n */\n this.specularPower = 64;\n this._useAlphaFromDiffuseTexture = false;\n this._useEmissiveAsIllumination = false;\n this._linkEmissiveWithDiffuse = false;\n this._useSpecularOverAlpha = false;\n this._useReflectionOverAlpha = false;\n this._disableLighting = false;\n this._useObjectSpaceNormalMap = false;\n this._useParallax = false;\n this._useParallaxOcclusion = false;\n /**\n * Apply a scaling factor that determine which \"depth\" the height map should reprensent. A value between 0.05 and 0.1 is reasonnable in Parallax, you can reach 0.2 using Parallax Occlusion.\n */\n this.parallaxScaleBias = 0.05;\n this._roughness = 0;\n /**\n * In case of refraction, define the value of the index of refraction.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#how-to-obtain-reflections-and-refractions\n */\n this.indexOfRefraction = 0.98;\n /**\n * Invert the refraction texture alongside the y axis.\n * It can be useful with procedural textures or probe for instance.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#how-to-obtain-reflections-and-refractions\n */\n this.invertRefractionY = true;\n /**\n * Defines the alpha limits in alpha test mode.\n */\n this.alphaCutOff = 0.4;\n this._useLightmapAsShadowmap = false;\n this._useReflectionFresnelFromSpecular = false;\n this._useGlossinessFromSpecularMapAlpha = false;\n this._maxSimultaneousLights = 4;\n this._invertNormalMapX = false;\n this._invertNormalMapY = false;\n this._twoSidedLighting = false;\n this._renderTargets = new SmartArray(16);\n this._worldViewProjectionMatrix = Matrix.Zero();\n this._globalAmbientColor = new Color3(0, 0, 0);\n this._cacheHasRenderTargetTextures = false;\n this.detailMap = new DetailMapConfiguration(this);\n // Setup the default processing configuration to the scene.\n this._attachImageProcessingConfiguration(null);\n this.prePassConfiguration = new PrePassConfiguration();\n this.getRenderTargetTextures = () => {\n this._renderTargets.reset();\n if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {\n this._renderTargets.push(this._reflectionTexture);\n }\n if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {\n this._renderTargets.push(this._refractionTexture);\n }\n this._eventInfo.renderTargets = this._renderTargets;\n this._callbackPluginEventFillRenderTargetTextures(this._eventInfo);\n return this._renderTargets;\n };\n }\n /**\n * Gets a boolean indicating that current material needs to register RTT\n */\n get hasRenderTargetTextures() {\n if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {\n return true;\n }\n if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {\n return true;\n }\n return this._cacheHasRenderTargetTextures;\n }\n /**\n * Gets the current class name of the material e.g. \"StandardMaterial\"\n * Mainly use in serialization.\n * @returns the class name\n */\n getClassName() {\n return \"StandardMaterial\";\n }\n /**\n * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes)\n * You can try switching to logarithmic depth.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/logarithmicDepthBuffer\n */\n get useLogarithmicDepth() {\n return this._useLogarithmicDepth;\n }\n set useLogarithmicDepth(value) {\n this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;\n this._markAllSubMeshesAsMiscDirty();\n }\n /**\n * Specifies if the material will require alpha blending\n * @returns a boolean specifying if alpha blending is needed\n */\n needAlphaBlending() {\n if (this._disableAlphaBlending) {\n return false;\n }\n return (this.alpha < 1.0 ||\n this._opacityTexture != null ||\n this._shouldUseAlphaFromDiffuseTexture() ||\n (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled));\n }\n /**\n * Specifies if this material should be rendered in alpha test mode\n * @returns a boolean specifying if an alpha test is needed.\n */\n needAlphaTesting() {\n if (this._forceAlphaTest) {\n return true;\n }\n return this._hasAlphaChannel() && (this._transparencyMode == null || this._transparencyMode === Material.MATERIAL_ALPHATEST);\n }\n /**\n * Specifies whether or not the alpha value of the diffuse texture should be used for alpha blending.\n */\n _shouldUseAlphaFromDiffuseTexture() {\n return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture && this._transparencyMode !== Material.MATERIAL_OPAQUE;\n }\n /**\n * Specifies whether or not there is a usable alpha channel for transparency.\n */\n _hasAlphaChannel() {\n return (this._diffuseTexture != null && this._diffuseTexture.hasAlpha) || this._opacityTexture != null;\n }\n /**\n * Get the texture used for alpha test purpose.\n * @returns the diffuse texture in case of the standard material.\n */\n getAlphaTestTexture() {\n return this._diffuseTexture;\n }\n /**\n * Get if the submesh is ready to be used and all its information available.\n * Child classes can use it to update shaders\n * @param mesh defines the mesh to check\n * @param subMesh defines which submesh to check\n * @param useInstances specifies that instances should be used\n * @returns a boolean indicating that the submesh is ready or not\n */\n isReadyForSubMesh(mesh, subMesh, useInstances = false) {\n if (!this._uniformBufferLayoutBuilt) {\n this.buildUniformLayout();\n }\n if (subMesh.effect && this.isFrozen) {\n if (subMesh.effect._wasPreviouslyReady && subMesh.effect._wasPreviouslyUsingInstances === useInstances) {\n return true;\n }\n }\n if (!subMesh.materialDefines) {\n this._callbackPluginEventGeneric(MaterialPluginEvent.GetDefineNames, this._eventInfo);\n subMesh.materialDefines = new StandardMaterialDefines(this._eventInfo.defineNames);\n }\n const scene = this.getScene();\n const defines = subMesh.materialDefines;\n if (this._isReadyForSubMesh(subMesh)) {\n return true;\n }\n const engine = scene.getEngine();\n // Lights\n defines._needNormals = MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);\n // Multiview\n MaterialHelper.PrepareDefinesForMultiview(scene, defines);\n // PrePass\n const oit = this.needAlphaBlendingForMesh(mesh) && this.getScene().useOrderIndependentTransparency;\n MaterialHelper.PrepareDefinesForPrePass(scene, defines, this.canRenderToMRT && !oit);\n // Order independant transparency\n MaterialHelper.PrepareDefinesForOIT(scene, defines, oit);\n // Textures\n if (defines._areTexturesDirty) {\n this._eventInfo.hasRenderTargetTextures = false;\n this._callbackPluginEventHasRenderTargetTextures(this._eventInfo);\n this._cacheHasRenderTargetTextures = this._eventInfo.hasRenderTargetTextures;\n defines._needUVs = false;\n for (let i = 1; i <= 6; ++i) {\n defines[\"MAINUV\" + i] = false;\n }\n if (scene.texturesEnabled) {\n defines.DIFFUSEDIRECTUV = 0;\n defines.BUMPDIRECTUV = 0;\n defines.AMBIENTDIRECTUV = 0;\n defines.OPACITYDIRECTUV = 0;\n defines.EMISSIVEDIRECTUV = 0;\n defines.SPECULARDIRECTUV = 0;\n defines.LIGHTMAPDIRECTUV = 0;\n if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {\n if (!this._diffuseTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, \"DIFFUSE\");\n }\n }\n else {\n defines.DIFFUSE = false;\n }\n if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {\n if (!this._ambientTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, \"AMBIENT\");\n }\n }\n else {\n defines.AMBIENT = false;\n }\n if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {\n if (!this._opacityTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, \"OPACITY\");\n defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;\n }\n }\n else {\n defines.OPACITY = false;\n }\n if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {\n if (!this._reflectionTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n defines._needNormals = true;\n defines.REFLECTION = true;\n defines.ROUGHNESS = this._roughness > 0;\n defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;\n defines.INVERTCUBICMAP = this._reflectionTexture.coordinatesMode === Texture.INVCUBIC_MODE;\n defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;\n defines.REFLECTIONMAP_OPPOSITEZ =\n defines.REFLECTIONMAP_3D && this.getScene().useRightHandedSystem ? !this._reflectionTexture.invertZ : this._reflectionTexture.invertZ;\n defines.RGBDREFLECTION = this._reflectionTexture.isRGBD;\n switch (this._reflectionTexture.coordinatesMode) {\n case Texture.EXPLICIT_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_EXPLICIT\");\n break;\n case Texture.PLANAR_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_PLANAR\");\n break;\n case Texture.PROJECTION_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_PROJECTION\");\n break;\n case Texture.SKYBOX_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_SKYBOX\");\n break;\n case Texture.SPHERICAL_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_SPHERICAL\");\n break;\n case Texture.EQUIRECTANGULAR_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_EQUIRECTANGULAR\");\n break;\n case Texture.FIXED_EQUIRECTANGULAR_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_EQUIRECTANGULAR_FIXED\");\n break;\n case Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:\n defines.setReflectionMode(\"REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\");\n break;\n case Texture.CUBIC_MODE:\n case Texture.INVCUBIC_MODE:\n default:\n defines.setReflectionMode(\"REFLECTIONMAP_CUBIC\");\n break;\n }\n defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;\n }\n }\n else {\n defines.REFLECTION = false;\n defines.REFLECTIONMAP_OPPOSITEZ = false;\n }\n if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {\n if (!this._emissiveTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, \"EMISSIVE\");\n }\n }\n else {\n defines.EMISSIVE = false;\n }\n if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {\n if (!this._lightmapTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, \"LIGHTMAP\");\n defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;\n defines.RGBDLIGHTMAP = this._lightmapTexture.isRGBD;\n }\n }\n else {\n defines.LIGHTMAP = false;\n }\n if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {\n if (!this._specularTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, \"SPECULAR\");\n defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;\n }\n }\n else {\n defines.SPECULAR = false;\n }\n if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {\n // Bump texture can not be not blocking.\n if (!this._bumpTexture.isReady()) {\n return false;\n }\n else {\n MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, \"BUMP\");\n defines.PARALLAX = this._useParallax;\n defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;\n }\n defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;\n }\n else {\n defines.BUMP = false;\n defines.PARALLAX = false;\n defines.PARALLAXOCCLUSION = false;\n }\n if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {\n if (!this._refractionTexture.isReadyOrNotBlocking()) {\n return false;\n }\n else {\n defines._needUVs = true;\n defines.REFRACTION = true;\n defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;\n defines.RGBDREFRACTION = this._refractionTexture.isRGBD;\n defines.USE_LOCAL_REFRACTIONMAP_CUBIC = this._refractionTexture.boundingBoxSize ? true : false;\n }\n }\n else {\n defines.REFRACTION = false;\n }\n defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;\n }\n else {\n defines.DIFFUSE = false;\n defines.AMBIENT = false;\n defines.OPACITY = false;\n defines.REFLECTION = false;\n defines.EMISSIVE = false;\n defines.LIGHTMAP = false;\n defines.BUMP = false;\n defines.REFRACTION = false;\n }\n defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();\n defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;\n defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;\n defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;\n defines.PREMULTIPLYALPHA = this.alphaMode === 7 || this.alphaMode === 8;\n defines.ALPHATEST_AFTERALLALPHACOMPUTATIONS = this.transparencyMode !== null;\n defines.ALPHABLEND = this.transparencyMode === null || this.needAlphaBlendingForMesh(mesh); // check on null for backward compatibility\n }\n this._eventInfo.isReadyForSubMesh = true;\n this._eventInfo.defines = defines;\n this._eventInfo.subMesh = subMesh;\n this._callbackPluginEventIsReadyForSubMesh(this._eventInfo);\n if (!this._eventInfo.isReadyForSubMesh) {\n return false;\n }\n if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {\n if (!this._imageProcessingConfiguration.isReady()) {\n return false;\n }\n this._imageProcessingConfiguration.prepareDefines(defines);\n defines.IS_REFLECTION_LINEAR = this.reflectionTexture != null && !this.reflectionTexture.gammaSpace;\n defines.IS_REFRACTION_LINEAR = this.refractionTexture != null && !this.refractionTexture.gammaSpace;\n }\n if (defines._areFresnelDirty) {\n if (StandardMaterial.FresnelEnabled) {\n // Fresnel\n if (this._diffuseFresnelParameters ||\n this._opacityFresnelParameters ||\n this._emissiveFresnelParameters ||\n this._refractionFresnelParameters ||\n this._reflectionFresnelParameters) {\n defines.DIFFUSEFRESNEL = this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled;\n defines.OPACITYFRESNEL = this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;\n defines.REFLECTIONFRESNEL = this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled;\n defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;\n defines.REFRACTIONFRESNEL = this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled;\n defines.EMISSIVEFRESNEL = this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled;\n defines._needNormals = true;\n defines.FRESNEL = true;\n }\n }\n else {\n defines.FRESNEL = false;\n }\n }\n // Misc.\n MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);\n // Values that need to be evaluated on every frame\n MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, this, defines, useInstances, null, subMesh.getRenderingMesh().hasThinInstances);\n // External config\n this._eventInfo.defines = defines;\n this._eventInfo.mesh = mesh;\n this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo);\n // Attribs\n MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);\n // External config\n this._callbackPluginEventPrepareDefines(this._eventInfo);\n // Get correct effect\n let forceWasNotReadyPreviously = false;\n if (defines.isDirty) {\n const lightDisposed = defines._areLightsDisposed;\n defines.markAsProcessed();\n // Fallbacks\n const fallbacks = new EffectFallbacks();\n if (defines.REFLECTION) {\n fallbacks.addFallback(0, \"REFLECTION\");\n }\n if (defines.SPECULAR) {\n fallbacks.addFallback(0, \"SPECULAR\");\n }\n if (defines.BUMP) {\n fallbacks.addFallback(0, \"BUMP\");\n }\n if (defines.PARALLAX) {\n fallbacks.addFallback(1, \"PARALLAX\");\n }\n if (defines.PARALLAXOCCLUSION) {\n fallbacks.addFallback(0, \"PARALLAXOCCLUSION\");\n }\n if (defines.SPECULAROVERALPHA) {\n fallbacks.addFallback(0, \"SPECULAROVERALPHA\");\n }\n if (defines.FOG) {\n fallbacks.addFallback(1, \"FOG\");\n }\n if (defines.POINTSIZE) {\n fallbacks.addFallback(0, \"POINTSIZE\");\n }\n if (defines.LOGARITHMICDEPTH) {\n fallbacks.addFallback(0, \"LOGARITHMICDEPTH\");\n }\n MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);\n if (defines.SPECULARTERM) {\n fallbacks.addFallback(0, \"SPECULARTERM\");\n }\n if (defines.DIFFUSEFRESNEL) {\n fallbacks.addFallback(1, \"DIFFUSEFRESNEL\");\n }\n if (defines.OPACITYFRESNEL) {\n fallbacks.addFallback(2, \"OPACITYFRESNEL\");\n }\n if (defines.REFLECTIONFRESNEL) {\n fallbacks.addFallback(3, \"REFLECTIONFRESNEL\");\n }\n if (defines.EMISSIVEFRESNEL) {\n fallbacks.addFallback(4, \"EMISSIVEFRESNEL\");\n }\n if (defines.FRESNEL) {\n fallbacks.addFallback(4, \"FRESNEL\");\n }\n if (defines.MULTIVIEW) {\n fallbacks.addFallback(0, \"MULTIVIEW\");\n }\n //Attributes\n const attribs = [VertexBuffer.PositionKind];\n if (defines.NORMAL) {\n attribs.push(VertexBuffer.NormalKind);\n }\n if (defines.TANGENT) {\n attribs.push(VertexBuffer.TangentKind);\n }\n for (let i = 1; i <= 6; ++i) {\n if (defines[\"UV\" + i]) {\n attribs.push(`uv${i === 1 ? \"\" : i}`);\n }\n }\n if (defines.VERTEXCOLOR) {\n attribs.push(VertexBuffer.ColorKind);\n }\n MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);\n MaterialHelper.PrepareAttributesForInstances(attribs, defines);\n MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);\n MaterialHelper.PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines);\n let shaderName = \"default\";\n const uniforms = [\n \"world\",\n \"view\",\n \"viewProjection\",\n \"vEyePosition\",\n \"vLightsType\",\n \"vAmbientColor\",\n \"vDiffuseColor\",\n \"vSpecularColor\",\n \"vEmissiveColor\",\n \"visibility\",\n \"vFogInfos\",\n \"vFogColor\",\n \"pointSize\",\n \"vDiffuseInfos\",\n \"vAmbientInfos\",\n \"vOpacityInfos\",\n \"vReflectionInfos\",\n \"vEmissiveInfos\",\n \"vSpecularInfos\",\n \"vBumpInfos\",\n \"vLightmapInfos\",\n \"vRefractionInfos\",\n \"mBones\",\n \"diffuseMatrix\",\n \"ambientMatrix\",\n \"opacityMatrix\",\n \"reflectionMatrix\",\n \"emissiveMatrix\",\n \"specularMatrix\",\n \"bumpMatrix\",\n \"normalMatrix\",\n \"lightmapMatrix\",\n \"refractionMatrix\",\n \"diffuseLeftColor\",\n \"diffuseRightColor\",\n \"opacityParts\",\n \"reflectionLeftColor\",\n \"reflectionRightColor\",\n \"emissiveLeftColor\",\n \"emissiveRightColor\",\n \"refractionLeftColor\",\n \"refractionRightColor\",\n \"vReflectionPosition\",\n \"vReflectionSize\",\n \"vRefractionPosition\",\n \"vRefractionSize\",\n \"logarithmicDepthConstant\",\n \"vTangentSpaceParams\",\n \"alphaCutOff\",\n \"boneTextureWidth\",\n \"morphTargetTextureInfo\",\n \"morphTargetTextureIndices\",\n ];\n const samplers = [\n \"diffuseSampler\",\n \"ambientSampler\",\n \"opacitySampler\",\n \"reflectionCubeSampler\",\n \"reflection2DSampler\",\n \"emissiveSampler\",\n \"specularSampler\",\n \"bumpSampler\",\n \"lightmapSampler\",\n \"refractionCubeSampler\",\n \"refraction2DSampler\",\n \"boneSampler\",\n \"morphTargets\",\n \"oitDepthSampler\",\n \"oitFrontColorSampler\",\n ];\n const uniformBuffers = [\"Material\", \"Scene\", \"Mesh\"];\n this._eventInfo.fallbacks = fallbacks;\n this._eventInfo.fallbackRank = 0;\n this._eventInfo.defines = defines;\n this._eventInfo.uniforms = uniforms;\n this._eventInfo.attributes = attribs;\n this._eventInfo.samplers = samplers;\n this._eventInfo.uniformBuffersNames = uniformBuffers;\n this._eventInfo.customCode = undefined;\n this._eventInfo.mesh = mesh;\n this._callbackPluginEventGeneric(MaterialPluginEvent.PrepareEffect, this._eventInfo);\n PrePassConfiguration.AddUniforms(uniforms);\n PrePassConfiguration.AddSamplers(samplers);\n if (ImageProcessingConfiguration) {\n ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);\n ImageProcessingConfiguration.PrepareSamplers(samplers, defines);\n }\n MaterialHelper.PrepareUniformsAndSamplersList({\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: defines,\n maxSimultaneousLights: this._maxSimultaneousLights,\n });\n addClipPlaneUniforms(uniforms);\n const csnrOptions = {};\n if (this.customShaderNameResolve) {\n shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines, attribs, csnrOptions);\n }\n const join = defines.toString();\n const previousEffect = subMesh.effect;\n let effect = scene.getEngine().createEffect(shaderName, {\n attributes: attribs,\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: join,\n fallbacks: fallbacks,\n onCompiled: this.onCompiled,\n onError: this.onError,\n indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS },\n processFinalCode: csnrOptions.processFinalCode,\n processCodeAfterIncludes: this._eventInfo.customCode,\n multiTarget: defines.PREPASS,\n }, engine);\n this._eventInfo.customCode = undefined;\n if (effect) {\n if (this._onEffectCreatedObservable) {\n onCreatedEffectParameters.effect = effect;\n onCreatedEffectParameters.subMesh = subMesh;\n this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters);\n }\n // Use previous effect while new one is compiling\n if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {\n effect = previousEffect;\n defines.markAsUnprocessed();\n forceWasNotReadyPreviously = this.isFrozen;\n if (lightDisposed) {\n // re register in case it takes more than one frame.\n defines._areLightsDisposed = true;\n return false;\n }\n }\n else {\n scene.resetCachedMaterial();\n subMesh.setEffect(effect, defines, this._materialContext);\n }\n }\n }\n if (!subMesh.effect || !subMesh.effect.isReady()) {\n return false;\n }\n defines._renderId = scene.getRenderId();\n subMesh.effect._wasPreviouslyReady = forceWasNotReadyPreviously ? false : true;\n subMesh.effect._wasPreviouslyUsingInstances = useInstances;\n this._checkScenePerformancePriority();\n return true;\n }\n /**\n * Builds the material UBO layouts.\n * Used internally during the effect preparation.\n */\n buildUniformLayout() {\n // Order is important !\n const ubo = this._uniformBuffer;\n ubo.addUniform(\"diffuseLeftColor\", 4);\n ubo.addUniform(\"diffuseRightColor\", 4);\n ubo.addUniform(\"opacityParts\", 4);\n ubo.addUniform(\"reflectionLeftColor\", 4);\n ubo.addUniform(\"reflectionRightColor\", 4);\n ubo.addUniform(\"refractionLeftColor\", 4);\n ubo.addUniform(\"refractionRightColor\", 4);\n ubo.addUniform(\"emissiveLeftColor\", 4);\n ubo.addUniform(\"emissiveRightColor\", 4);\n ubo.addUniform(\"vDiffuseInfos\", 2);\n ubo.addUniform(\"vAmbientInfos\", 2);\n ubo.addUniform(\"vOpacityInfos\", 2);\n ubo.addUniform(\"vReflectionInfos\", 2);\n ubo.addUniform(\"vReflectionPosition\", 3);\n ubo.addUniform(\"vReflectionSize\", 3);\n ubo.addUniform(\"vEmissiveInfos\", 2);\n ubo.addUniform(\"vLightmapInfos\", 2);\n ubo.addUniform(\"vSpecularInfos\", 2);\n ubo.addUniform(\"vBumpInfos\", 3);\n ubo.addUniform(\"diffuseMatrix\", 16);\n ubo.addUniform(\"ambientMatrix\", 16);\n ubo.addUniform(\"opacityMatrix\", 16);\n ubo.addUniform(\"reflectionMatrix\", 16);\n ubo.addUniform(\"emissiveMatrix\", 16);\n ubo.addUniform(\"lightmapMatrix\", 16);\n ubo.addUniform(\"specularMatrix\", 16);\n ubo.addUniform(\"bumpMatrix\", 16);\n ubo.addUniform(\"vTangentSpaceParams\", 2);\n ubo.addUniform(\"pointSize\", 1);\n ubo.addUniform(\"alphaCutOff\", 1);\n ubo.addUniform(\"refractionMatrix\", 16);\n ubo.addUniform(\"vRefractionInfos\", 4);\n ubo.addUniform(\"vRefractionPosition\", 3);\n ubo.addUniform(\"vRefractionSize\", 3);\n ubo.addUniform(\"vSpecularColor\", 4);\n ubo.addUniform(\"vEmissiveColor\", 3);\n ubo.addUniform(\"vDiffuseColor\", 4);\n ubo.addUniform(\"vAmbientColor\", 3);\n super.buildUniformLayout();\n }\n /**\n * Binds the submesh to this material by preparing the effect and shader to draw\n * @param world defines the world transformation matrix\n * @param mesh defines the mesh containing the submesh\n * @param subMesh defines the submesh to bind the material to\n */\n bindForSubMesh(world, mesh, subMesh) {\n var _a;\n const scene = this.getScene();\n const defines = subMesh.materialDefines;\n if (!defines) {\n return;\n }\n const effect = subMesh.effect;\n if (!effect) {\n return;\n }\n this._activeEffect = effect;\n // Matrices Mesh.\n mesh.getMeshUniformBuffer().bindToEffect(effect, \"Mesh\");\n mesh.transferToEffect(world);\n // Binding unconditionally\n this._uniformBuffer.bindToEffect(effect, \"Material\");\n this.prePassConfiguration.bindForSubMesh(this._activeEffect, scene, mesh, world, this.isFrozen);\n this._eventInfo.subMesh = subMesh;\n this._callbackPluginEventHardBindForSubMesh(this._eventInfo);\n // Normal Matrix\n if (defines.OBJECTSPACE_NORMALMAP) {\n world.toNormalMatrix(this._normalMatrix);\n this.bindOnlyNormalMatrix(this._normalMatrix);\n }\n const mustRebind = effect._forceRebindOnNextCall || this._mustRebind(scene, effect, mesh.visibility);\n // Bones\n MaterialHelper.BindBonesParameters(mesh, effect);\n const ubo = this._uniformBuffer;\n if (mustRebind) {\n this.bindViewProjection(effect);\n if (!ubo.useUbo || !this.isFrozen || !ubo.isSync || effect._forceRebindOnNextCall) {\n if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {\n // Fresnel\n if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {\n ubo.updateColor4(\"diffuseLeftColor\", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);\n ubo.updateColor4(\"diffuseRightColor\", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);\n }\n if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {\n ubo.updateColor4(\"opacityParts\", new Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);\n }\n if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {\n ubo.updateColor4(\"reflectionLeftColor\", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);\n ubo.updateColor4(\"reflectionRightColor\", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);\n }\n if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {\n ubo.updateColor4(\"refractionLeftColor\", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);\n ubo.updateColor4(\"refractionRightColor\", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);\n }\n if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {\n ubo.updateColor4(\"emissiveLeftColor\", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);\n ubo.updateColor4(\"emissiveRightColor\", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);\n }\n }\n // Textures\n if (scene.texturesEnabled) {\n if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {\n ubo.updateFloat2(\"vDiffuseInfos\", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);\n MaterialHelper.BindTextureMatrix(this._diffuseTexture, ubo, \"diffuse\");\n }\n if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {\n ubo.updateFloat2(\"vAmbientInfos\", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);\n MaterialHelper.BindTextureMatrix(this._ambientTexture, ubo, \"ambient\");\n }\n if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {\n ubo.updateFloat2(\"vOpacityInfos\", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);\n MaterialHelper.BindTextureMatrix(this._opacityTexture, ubo, \"opacity\");\n }\n if (this._hasAlphaChannel()) {\n ubo.updateFloat(\"alphaCutOff\", this.alphaCutOff);\n }\n if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {\n ubo.updateFloat2(\"vReflectionInfos\", this._reflectionTexture.level, this.roughness);\n ubo.updateMatrix(\"reflectionMatrix\", this._reflectionTexture.getReflectionTextureMatrix());\n if (this._reflectionTexture.boundingBoxSize) {\n const cubeTexture = this._reflectionTexture;\n ubo.updateVector3(\"vReflectionPosition\", cubeTexture.boundingBoxPosition);\n ubo.updateVector3(\"vReflectionSize\", cubeTexture.boundingBoxSize);\n }\n }\n if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {\n ubo.updateFloat2(\"vEmissiveInfos\", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);\n MaterialHelper.BindTextureMatrix(this._emissiveTexture, ubo, \"emissive\");\n }\n if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {\n ubo.updateFloat2(\"vLightmapInfos\", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);\n MaterialHelper.BindTextureMatrix(this._lightmapTexture, ubo, \"lightmap\");\n }\n if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {\n ubo.updateFloat2(\"vSpecularInfos\", this._specularTexture.coordinatesIndex, this._specularTexture.level);\n MaterialHelper.BindTextureMatrix(this._specularTexture, ubo, \"specular\");\n }\n if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {\n ubo.updateFloat3(\"vBumpInfos\", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);\n MaterialHelper.BindTextureMatrix(this._bumpTexture, ubo, \"bump\");\n if (scene._mirroredCameraPosition) {\n ubo.updateFloat2(\"vTangentSpaceParams\", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);\n }\n else {\n ubo.updateFloat2(\"vTangentSpaceParams\", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);\n }\n }\n if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {\n let depth = 1.0;\n if (!this._refractionTexture.isCube) {\n ubo.updateMatrix(\"refractionMatrix\", this._refractionTexture.getReflectionTextureMatrix());\n if (this._refractionTexture.depth) {\n depth = this._refractionTexture.depth;\n }\n }\n ubo.updateFloat4(\"vRefractionInfos\", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);\n if (this._refractionTexture.boundingBoxSize) {\n const cubeTexture = this._refractionTexture;\n ubo.updateVector3(\"vRefractionPosition\", cubeTexture.boundingBoxPosition);\n ubo.updateVector3(\"vRefractionSize\", cubeTexture.boundingBoxSize);\n }\n }\n }\n // Point size\n if (this.pointsCloud) {\n ubo.updateFloat(\"pointSize\", this.pointSize);\n }\n if (defines.SPECULARTERM) {\n ubo.updateColor4(\"vSpecularColor\", this.specularColor, this.specularPower);\n }\n ubo.updateColor3(\"vEmissiveColor\", StandardMaterial.EmissiveTextureEnabled ? this.emissiveColor : Color3.BlackReadOnly);\n ubo.updateColor4(\"vDiffuseColor\", this.diffuseColor, this.alpha);\n scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);\n ubo.updateColor3(\"vAmbientColor\", this._globalAmbientColor);\n }\n // Textures\n if (scene.texturesEnabled) {\n if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {\n effect.setTexture(\"diffuseSampler\", this._diffuseTexture);\n }\n if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {\n effect.setTexture(\"ambientSampler\", this._ambientTexture);\n }\n if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {\n effect.setTexture(\"opacitySampler\", this._opacityTexture);\n }\n if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {\n if (this._reflectionTexture.isCube) {\n effect.setTexture(\"reflectionCubeSampler\", this._reflectionTexture);\n }\n else {\n effect.setTexture(\"reflection2DSampler\", this._reflectionTexture);\n }\n }\n if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {\n effect.setTexture(\"emissiveSampler\", this._emissiveTexture);\n }\n if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {\n effect.setTexture(\"lightmapSampler\", this._lightmapTexture);\n }\n if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {\n effect.setTexture(\"specularSampler\", this._specularTexture);\n }\n if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {\n effect.setTexture(\"bumpSampler\", this._bumpTexture);\n }\n if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {\n if (this._refractionTexture.isCube) {\n effect.setTexture(\"refractionCubeSampler\", this._refractionTexture);\n }\n else {\n effect.setTexture(\"refraction2DSampler\", this._refractionTexture);\n }\n }\n }\n // OIT with depth peeling\n if (this.getScene().useOrderIndependentTransparency && this.needAlphaBlendingForMesh(mesh)) {\n this.getScene().depthPeelingRenderer.bind(effect);\n }\n this._eventInfo.subMesh = subMesh;\n this._callbackPluginEventBindForSubMesh(this._eventInfo);\n // Clip plane\n bindClipPlane(effect, this, scene);\n // Colors\n this.bindEyePosition(effect);\n }\n else if (scene.getEngine()._features.needToAlwaysBindUniformBuffers) {\n this._needToBindSceneUbo = true;\n }\n if (mustRebind || !this.isFrozen) {\n // Lights\n if (scene.lightsEnabled && !this._disableLighting) {\n MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);\n }\n // View\n if ((scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) ||\n this._reflectionTexture ||\n this._refractionTexture ||\n mesh.receiveShadows ||\n defines.PREPASS) {\n this.bindView(effect);\n }\n // Fog\n MaterialHelper.BindFogParameters(scene, mesh, effect);\n // Morph targets\n if (defines.NUM_MORPH_INFLUENCERS) {\n MaterialHelper.BindMorphTargetParameters(mesh, effect);\n }\n if (defines.BAKED_VERTEX_ANIMATION_TEXTURE) {\n (_a = mesh.bakedVertexAnimationManager) === null || _a === void 0 ? void 0 : _a.bind(effect, defines.INSTANCES);\n }\n // Log. depth\n if (this.useLogarithmicDepth) {\n MaterialHelper.BindLogDepth(defines, effect, scene);\n }\n // image processing\n if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {\n this._imageProcessingConfiguration.bind(this._activeEffect);\n }\n }\n this._afterBind(mesh, this._activeEffect);\n ubo.update();\n }\n /**\n * Get the list of animatables in the material.\n * @returns the list of animatables object used in the material\n */\n getAnimatables() {\n const results = super.getAnimatables();\n if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {\n results.push(this._diffuseTexture);\n }\n if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {\n results.push(this._ambientTexture);\n }\n if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {\n results.push(this._opacityTexture);\n }\n if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {\n results.push(this._reflectionTexture);\n }\n if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {\n results.push(this._emissiveTexture);\n }\n if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {\n results.push(this._specularTexture);\n }\n if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {\n results.push(this._bumpTexture);\n }\n if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {\n results.push(this._lightmapTexture);\n }\n if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {\n results.push(this._refractionTexture);\n }\n return results;\n }\n /**\n * Gets the active textures from the material\n * @returns an array of textures\n */\n getActiveTextures() {\n const activeTextures = super.getActiveTextures();\n if (this._diffuseTexture) {\n activeTextures.push(this._diffuseTexture);\n }\n if (this._ambientTexture) {\n activeTextures.push(this._ambientTexture);\n }\n if (this._opacityTexture) {\n activeTextures.push(this._opacityTexture);\n }\n if (this._reflectionTexture) {\n activeTextures.push(this._reflectionTexture);\n }\n if (this._emissiveTexture) {\n activeTextures.push(this._emissiveTexture);\n }\n if (this._specularTexture) {\n activeTextures.push(this._specularTexture);\n }\n if (this._bumpTexture) {\n activeTextures.push(this._bumpTexture);\n }\n if (this._lightmapTexture) {\n activeTextures.push(this._lightmapTexture);\n }\n if (this._refractionTexture) {\n activeTextures.push(this._refractionTexture);\n }\n return activeTextures;\n }\n /**\n * Specifies if the material uses a texture\n * @param texture defines the texture to check against the material\n * @returns a boolean specifying if the material uses the texture\n */\n hasTexture(texture) {\n if (super.hasTexture(texture)) {\n return true;\n }\n if (this._diffuseTexture === texture) {\n return true;\n }\n if (this._ambientTexture === texture) {\n return true;\n }\n if (this._opacityTexture === texture) {\n return true;\n }\n if (this._reflectionTexture === texture) {\n return true;\n }\n if (this._emissiveTexture === texture) {\n return true;\n }\n if (this._specularTexture === texture) {\n return true;\n }\n if (this._bumpTexture === texture) {\n return true;\n }\n if (this._lightmapTexture === texture) {\n return true;\n }\n if (this._refractionTexture === texture) {\n return true;\n }\n return false;\n }\n /**\n * Disposes the material\n * @param forceDisposeEffect specifies if effects should be forcefully disposed\n * @param forceDisposeTextures specifies if textures should be forcefully disposed\n */\n dispose(forceDisposeEffect, forceDisposeTextures) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j;\n if (forceDisposeTextures) {\n (_a = this._diffuseTexture) === null || _a === void 0 ? void 0 : _a.dispose();\n (_b = this._ambientTexture) === null || _b === void 0 ? void 0 : _b.dispose();\n (_c = this._opacityTexture) === null || _c === void 0 ? void 0 : _c.dispose();\n (_d = this._reflectionTexture) === null || _d === void 0 ? void 0 : _d.dispose();\n (_e = this._emissiveTexture) === null || _e === void 0 ? void 0 : _e.dispose();\n (_f = this._specularTexture) === null || _f === void 0 ? void 0 : _f.dispose();\n (_g = this._bumpTexture) === null || _g === void 0 ? void 0 : _g.dispose();\n (_h = this._lightmapTexture) === null || _h === void 0 ? void 0 : _h.dispose();\n (_j = this._refractionTexture) === null || _j === void 0 ? void 0 : _j.dispose();\n }\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n super.dispose(forceDisposeEffect, forceDisposeTextures);\n }\n /**\n * Makes a duplicate of the material, and gives it a new name\n * @param name defines the new name for the duplicated material\n * @param cloneTexturesOnlyOnce - if a texture is used in more than one channel (e.g diffuse and opacity), only clone it once and reuse it on the other channels. Default false.\n * @param rootUrl defines the root URL to use to load textures\n * @returns the cloned material\n */\n clone(name, cloneTexturesOnlyOnce = true, rootUrl = \"\") {\n const result = SerializationHelper.Clone(() => new StandardMaterial(name, this.getScene()), this, { cloneTexturesOnlyOnce });\n result.name = name;\n result.id = name;\n this.stencil.copyTo(result.stencil);\n this._clonePlugins(result, rootUrl);\n return result;\n }\n /**\n * Creates a standard material from parsed material data\n * @param source defines the JSON representation of the material\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @returns a new standard material\n */\n static Parse(source, scene, rootUrl) {\n const material = SerializationHelper.Parse(() => new StandardMaterial(source.name, scene), source, scene, rootUrl);\n if (source.stencil) {\n material.stencil.parse(source.stencil, scene, rootUrl);\n }\n Material._parsePlugins(source, material, scene, rootUrl);\n return material;\n }\n // Flags used to enable or disable a type of texture for all Standard Materials\n /**\n * Are diffuse textures enabled in the application.\n */\n static get DiffuseTextureEnabled() {\n return MaterialFlags.DiffuseTextureEnabled;\n }\n static set DiffuseTextureEnabled(value) {\n MaterialFlags.DiffuseTextureEnabled = value;\n }\n /**\n * Are detail textures enabled in the application.\n */\n static get DetailTextureEnabled() {\n return MaterialFlags.DetailTextureEnabled;\n }\n static set DetailTextureEnabled(value) {\n MaterialFlags.DetailTextureEnabled = value;\n }\n /**\n * Are ambient textures enabled in the application.\n */\n static get AmbientTextureEnabled() {\n return MaterialFlags.AmbientTextureEnabled;\n }\n static set AmbientTextureEnabled(value) {\n MaterialFlags.AmbientTextureEnabled = value;\n }\n /**\n * Are opacity textures enabled in the application.\n */\n static get OpacityTextureEnabled() {\n return MaterialFlags.OpacityTextureEnabled;\n }\n static set OpacityTextureEnabled(value) {\n MaterialFlags.OpacityTextureEnabled = value;\n }\n /**\n * Are reflection textures enabled in the application.\n */\n static get ReflectionTextureEnabled() {\n return MaterialFlags.ReflectionTextureEnabled;\n }\n static set ReflectionTextureEnabled(value) {\n MaterialFlags.ReflectionTextureEnabled = value;\n }\n /**\n * Are emissive textures enabled in the application.\n */\n static get EmissiveTextureEnabled() {\n return MaterialFlags.EmissiveTextureEnabled;\n }\n static set EmissiveTextureEnabled(value) {\n MaterialFlags.EmissiveTextureEnabled = value;\n }\n /**\n * Are specular textures enabled in the application.\n */\n static get SpecularTextureEnabled() {\n return MaterialFlags.SpecularTextureEnabled;\n }\n static set SpecularTextureEnabled(value) {\n MaterialFlags.SpecularTextureEnabled = value;\n }\n /**\n * Are bump textures enabled in the application.\n */\n static get BumpTextureEnabled() {\n return MaterialFlags.BumpTextureEnabled;\n }\n static set BumpTextureEnabled(value) {\n MaterialFlags.BumpTextureEnabled = value;\n }\n /**\n * Are lightmap textures enabled in the application.\n */\n static get LightmapTextureEnabled() {\n return MaterialFlags.LightmapTextureEnabled;\n }\n static set LightmapTextureEnabled(value) {\n MaterialFlags.LightmapTextureEnabled = value;\n }\n /**\n * Are refraction textures enabled in the application.\n */\n static get RefractionTextureEnabled() {\n return MaterialFlags.RefractionTextureEnabled;\n }\n static set RefractionTextureEnabled(value) {\n MaterialFlags.RefractionTextureEnabled = value;\n }\n /**\n * Are color grading textures enabled in the application.\n */\n static get ColorGradingTextureEnabled() {\n return MaterialFlags.ColorGradingTextureEnabled;\n }\n static set ColorGradingTextureEnabled(value) {\n MaterialFlags.ColorGradingTextureEnabled = value;\n }\n /**\n * Are fresnels enabled in the application.\n */\n static get FresnelEnabled() {\n return MaterialFlags.FresnelEnabled;\n }\n static set FresnelEnabled(value) {\n MaterialFlags.FresnelEnabled = value;\n }\n}\n__decorate([\n serializeAsTexture(\"diffuseTexture\")\n], StandardMaterial.prototype, \"_diffuseTexture\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesAndMiscDirty\")\n], StandardMaterial.prototype, \"diffuseTexture\", void 0);\n__decorate([\n serializeAsTexture(\"ambientTexture\")\n], StandardMaterial.prototype, \"_ambientTexture\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"ambientTexture\", void 0);\n__decorate([\n serializeAsTexture(\"opacityTexture\")\n], StandardMaterial.prototype, \"_opacityTexture\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesAndMiscDirty\")\n], StandardMaterial.prototype, \"opacityTexture\", void 0);\n__decorate([\n serializeAsTexture(\"reflectionTexture\")\n], StandardMaterial.prototype, \"_reflectionTexture\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"reflectionTexture\", void 0);\n__decorate([\n serializeAsTexture(\"emissiveTexture\")\n], StandardMaterial.prototype, \"_emissiveTexture\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"emissiveTexture\", void 0);\n__decorate([\n serializeAsTexture(\"specularTexture\")\n], StandardMaterial.prototype, \"_specularTexture\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"specularTexture\", void 0);\n__decorate([\n serializeAsTexture(\"bumpTexture\")\n], StandardMaterial.prototype, \"_bumpTexture\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"bumpTexture\", void 0);\n__decorate([\n serializeAsTexture(\"lightmapTexture\")\n], StandardMaterial.prototype, \"_lightmapTexture\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"lightmapTexture\", void 0);\n__decorate([\n serializeAsTexture(\"refractionTexture\")\n], StandardMaterial.prototype, \"_refractionTexture\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"refractionTexture\", void 0);\n__decorate([\n serializeAsColor3(\"ambient\")\n], StandardMaterial.prototype, \"ambientColor\", void 0);\n__decorate([\n serializeAsColor3(\"diffuse\")\n], StandardMaterial.prototype, \"diffuseColor\", void 0);\n__decorate([\n serializeAsColor3(\"specular\")\n], StandardMaterial.prototype, \"specularColor\", void 0);\n__decorate([\n serializeAsColor3(\"emissive\")\n], StandardMaterial.prototype, \"emissiveColor\", void 0);\n__decorate([\n serialize()\n], StandardMaterial.prototype, \"specularPower\", void 0);\n__decorate([\n serialize(\"useAlphaFromDiffuseTexture\")\n], StandardMaterial.prototype, \"_useAlphaFromDiffuseTexture\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesAndMiscDirty\")\n], StandardMaterial.prototype, \"useAlphaFromDiffuseTexture\", void 0);\n__decorate([\n serialize(\"useEmissiveAsIllumination\")\n], StandardMaterial.prototype, \"_useEmissiveAsIllumination\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"useEmissiveAsIllumination\", void 0);\n__decorate([\n serialize(\"linkEmissiveWithDiffuse\")\n], StandardMaterial.prototype, \"_linkEmissiveWithDiffuse\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"linkEmissiveWithDiffuse\", void 0);\n__decorate([\n serialize(\"useSpecularOverAlpha\")\n], StandardMaterial.prototype, \"_useSpecularOverAlpha\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"useSpecularOverAlpha\", void 0);\n__decorate([\n serialize(\"useReflectionOverAlpha\")\n], StandardMaterial.prototype, \"_useReflectionOverAlpha\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"useReflectionOverAlpha\", void 0);\n__decorate([\n serialize(\"disableLighting\")\n], StandardMaterial.prototype, \"_disableLighting\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n], StandardMaterial.prototype, \"disableLighting\", void 0);\n__decorate([\n serialize(\"useObjectSpaceNormalMap\")\n], StandardMaterial.prototype, \"_useObjectSpaceNormalMap\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"useObjectSpaceNormalMap\", void 0);\n__decorate([\n serialize(\"useParallax\")\n], StandardMaterial.prototype, \"_useParallax\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"useParallax\", void 0);\n__decorate([\n serialize(\"useParallaxOcclusion\")\n], StandardMaterial.prototype, \"_useParallaxOcclusion\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"useParallaxOcclusion\", void 0);\n__decorate([\n serialize()\n], StandardMaterial.prototype, \"parallaxScaleBias\", void 0);\n__decorate([\n serialize(\"roughness\")\n], StandardMaterial.prototype, \"_roughness\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"roughness\", void 0);\n__decorate([\n serialize()\n], StandardMaterial.prototype, \"indexOfRefraction\", void 0);\n__decorate([\n serialize()\n], StandardMaterial.prototype, \"invertRefractionY\", void 0);\n__decorate([\n serialize()\n], StandardMaterial.prototype, \"alphaCutOff\", void 0);\n__decorate([\n serialize(\"useLightmapAsShadowmap\")\n], StandardMaterial.prototype, \"_useLightmapAsShadowmap\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"useLightmapAsShadowmap\", void 0);\n__decorate([\n serializeAsFresnelParameters(\"diffuseFresnelParameters\")\n], StandardMaterial.prototype, \"_diffuseFresnelParameters\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsFresnelDirty\")\n], StandardMaterial.prototype, \"diffuseFresnelParameters\", void 0);\n__decorate([\n serializeAsFresnelParameters(\"opacityFresnelParameters\")\n], StandardMaterial.prototype, \"_opacityFresnelParameters\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsFresnelAndMiscDirty\")\n], StandardMaterial.prototype, \"opacityFresnelParameters\", void 0);\n__decorate([\n serializeAsFresnelParameters(\"reflectionFresnelParameters\")\n], StandardMaterial.prototype, \"_reflectionFresnelParameters\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsFresnelDirty\")\n], StandardMaterial.prototype, \"reflectionFresnelParameters\", void 0);\n__decorate([\n serializeAsFresnelParameters(\"refractionFresnelParameters\")\n], StandardMaterial.prototype, \"_refractionFresnelParameters\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsFresnelDirty\")\n], StandardMaterial.prototype, \"refractionFresnelParameters\", void 0);\n__decorate([\n serializeAsFresnelParameters(\"emissiveFresnelParameters\")\n], StandardMaterial.prototype, \"_emissiveFresnelParameters\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsFresnelDirty\")\n], StandardMaterial.prototype, \"emissiveFresnelParameters\", void 0);\n__decorate([\n serialize(\"useReflectionFresnelFromSpecular\")\n], StandardMaterial.prototype, \"_useReflectionFresnelFromSpecular\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsFresnelDirty\")\n], StandardMaterial.prototype, \"useReflectionFresnelFromSpecular\", void 0);\n__decorate([\n serialize(\"useGlossinessFromSpecularMapAlpha\")\n], StandardMaterial.prototype, \"_useGlossinessFromSpecularMapAlpha\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"useGlossinessFromSpecularMapAlpha\", void 0);\n__decorate([\n serialize(\"maxSimultaneousLights\")\n], StandardMaterial.prototype, \"_maxSimultaneousLights\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n], StandardMaterial.prototype, \"maxSimultaneousLights\", void 0);\n__decorate([\n serialize(\"invertNormalMapX\")\n], StandardMaterial.prototype, \"_invertNormalMapX\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"invertNormalMapX\", void 0);\n__decorate([\n serialize(\"invertNormalMapY\")\n], StandardMaterial.prototype, \"_invertNormalMapY\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"invertNormalMapY\", void 0);\n__decorate([\n serialize(\"twoSidedLighting\")\n], StandardMaterial.prototype, \"_twoSidedLighting\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], StandardMaterial.prototype, \"twoSidedLighting\", void 0);\n__decorate([\n serialize()\n], StandardMaterial.prototype, \"useLogarithmicDepth\", null);\nRegisterClass(\"BABYLON.StandardMaterial\", StandardMaterial);\nScene.DefaultMaterialFactory = (scene) => {\n return new StandardMaterial(\"default material\", scene);\n};\n//# sourceMappingURL=standardMaterial.js.map","import { ThinEngine } from \"../../Engines/thinEngine.js\";\nimport { InternalTexture, InternalTextureSource } from \"../../Materials/Textures/internalTexture.js\";\nThinEngine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {\n const texture = new InternalTexture(this, InternalTextureSource.Dynamic);\n texture.baseWidth = width;\n texture.baseHeight = height;\n if (generateMipMaps) {\n width = this.needPOTTextures ? ThinEngine.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;\n height = this.needPOTTextures ? ThinEngine.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;\n }\n // this.resetTextureCache();\n texture.width = width;\n texture.height = height;\n texture.isReady = false;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n this.updateTextureSamplingMode(samplingMode, texture);\n this._internalTexturesCache.push(texture);\n return texture;\n};\nThinEngine.prototype.updateDynamicTexture = function (texture, source, invertY, premulAlpha = false, format, forceBindTexture = false, \n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nallowGPUOptimization = false) {\n if (!texture) {\n return;\n }\n const gl = this._gl;\n const target = gl.TEXTURE_2D;\n const wasPreviouslyBound = this._bindTextureDirectly(target, texture, true, forceBindTexture);\n this._unpackFlipY(invertY === undefined ? texture.invertY : invertY);\n if (premulAlpha) {\n gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);\n }\n const textureType = this._getWebGLTextureType(texture.type);\n const glformat = this._getInternalFormat(format ? format : texture.format);\n const internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, glformat);\n gl.texImage2D(target, 0, internalFormat, glformat, textureType, source);\n if (texture.generateMipMaps) {\n gl.generateMipmap(target);\n }\n if (!wasPreviouslyBound) {\n this._bindTextureDirectly(target, null);\n }\n if (premulAlpha) {\n gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);\n }\n texture.isReady = true;\n};\n//# sourceMappingURL=engine.dynamicTexture.js.map","import { Logger } from \"../../Misc/logger.js\";\nimport { Texture } from \"../../Materials/Textures/texture.js\";\n\nimport \"../../Engines/Extensions/engine.dynamicTexture.js\";\n/**\n * A class extending Texture allowing drawing on a texture\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/dynamicTexture\n */\nexport class DynamicTexture extends Texture {\n /**\n * Creates a DynamicTexture\n * @param name defines the name of the texture\n * @param options provides 3 alternatives for width and height of texture, a canvas, object with width and height properties, number for both width and height\n * @param scene defines the scene where you want the texture\n * @param generateMipMaps defines the use of MinMaps or not (default is false)\n * @param samplingMode defines the sampling mode to use (default is Texture.TRILINEAR_SAMPLINGMODE)\n * @param format defines the texture format to use (default is Engine.TEXTUREFORMAT_RGBA)\n * @param invertY defines if the texture needs to be inverted on the y axis during loading\n */\n constructor(name, options, scene = null, generateMipMaps = false, samplingMode = 3, format = 5, invertY) {\n super(null, scene, !generateMipMaps, invertY, samplingMode, undefined, undefined, undefined, undefined, format);\n this.name = name;\n this.wrapU = Texture.CLAMP_ADDRESSMODE;\n this.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._generateMipMaps = generateMipMaps;\n const engine = this._getEngine();\n if (!engine) {\n return;\n }\n if (options.getContext) {\n this._canvas = options;\n this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);\n }\n else {\n this._canvas = engine.createCanvas(1, 1);\n if (options.width || options.width === 0) {\n this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);\n }\n else {\n this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);\n }\n }\n const textureSize = this.getSize();\n if (this._canvas.width !== textureSize.width) {\n this._canvas.width = textureSize.width;\n }\n if (this._canvas.height !== textureSize.height) {\n this._canvas.height = textureSize.height;\n }\n this._context = this._canvas.getContext(\"2d\");\n }\n /**\n * Get the current class name of the texture useful for serialization or dynamic coding.\n * @returns \"DynamicTexture\"\n */\n getClassName() {\n return \"DynamicTexture\";\n }\n /**\n * Gets the current state of canRescale\n */\n get canRescale() {\n return true;\n }\n _recreate(textureSize) {\n this._canvas.width = textureSize.width;\n this._canvas.height = textureSize.height;\n this.releaseInternalTexture();\n this._texture = this._getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this.samplingMode);\n }\n /**\n * Scales the texture\n * @param ratio the scale factor to apply to both width and height\n */\n scale(ratio) {\n const textureSize = this.getSize();\n textureSize.width *= ratio;\n textureSize.height *= ratio;\n this._recreate(textureSize);\n }\n /**\n * Resizes the texture\n * @param width the new width\n * @param height the new height\n */\n scaleTo(width, height) {\n const textureSize = this.getSize();\n textureSize.width = width;\n textureSize.height = height;\n this._recreate(textureSize);\n }\n /**\n * Gets the context of the canvas used by the texture\n * @returns the canvas context of the dynamic texture\n */\n getContext() {\n return this._context;\n }\n /**\n * Clears the texture\n */\n clear() {\n const size = this.getSize();\n this._context.fillRect(0, 0, size.width, size.height);\n }\n /**\n * Updates the texture\n * @param invertY defines the direction for the Y axis (default is true - y increases downwards)\n * @param premulAlpha defines if alpha is stored as premultiplied (default is false)\n * @param allowGPUOptimization true to allow some specific GPU optimizations (subject to engine feature \"allowGPUOptimizationsForGUI\" being true)\n */\n update(invertY, premulAlpha = false, allowGPUOptimization = false) {\n this._getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined, undefined, allowGPUOptimization);\n }\n /**\n * Draws text onto the texture\n * @param text defines the text to be drawn\n * @param x defines the placement of the text from the left\n * @param y defines the placement of the text from the top when invertY is true and from the bottom when false\n * @param font defines the font to be used with font-style, font-size, font-name\n * @param color defines the color used for the text\n * @param clearColor defines the color for the canvas, use null to not overwrite canvas\n * @param invertY defines the direction for the Y axis (default is true - y increases downwards)\n * @param update defines whether texture is immediately update (default is true)\n */\n drawText(text, x, y, font, color, clearColor, invertY, update = true) {\n const size = this.getSize();\n if (clearColor) {\n this._context.fillStyle = clearColor;\n this._context.fillRect(0, 0, size.width, size.height);\n }\n this._context.font = font;\n if (x === null || x === undefined) {\n const textSize = this._context.measureText(text);\n x = (size.width - textSize.width) / 2;\n }\n if (y === null || y === undefined) {\n const fontSize = parseInt(font.replace(/\\D/g, \"\"));\n y = size.height / 2 + fontSize / 3.65;\n }\n this._context.fillStyle = color || \"\";\n this._context.fillText(text, x, y);\n if (update) {\n this.update(invertY);\n }\n }\n /**\n * Clones the texture\n * @returns the clone of the texture.\n */\n clone() {\n const scene = this.getScene();\n if (!scene) {\n return this;\n }\n const textureSize = this.getSize();\n const newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);\n // Base texture\n newTexture.hasAlpha = this.hasAlpha;\n newTexture.level = this.level;\n // Dynamic Texture\n newTexture.wrapU = this.wrapU;\n newTexture.wrapV = this.wrapV;\n return newTexture;\n }\n /**\n * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized\n * @returns a serialized dynamic texture object\n */\n serialize() {\n const scene = this.getScene();\n if (scene && !scene.isReady()) {\n Logger.Warn(\"The scene must be ready before serializing the dynamic texture\");\n }\n const serializationObject = super.serialize();\n if (DynamicTexture._IsCanvasElement(this._canvas)) {\n serializationObject.base64String = this._canvas.toDataURL();\n }\n serializationObject.invertY = this._invertY;\n serializationObject.samplingMode = this.samplingMode;\n return serializationObject;\n }\n static _IsCanvasElement(canvas) {\n return canvas.toDataURL !== undefined;\n }\n /** @internal */\n _rebuild() {\n this.update();\n }\n}\n//# sourceMappingURL=dynamicTexture.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/imageProcessingDeclaration.js\";\nimport \"./ShadersInclude/helperFunctions.js\";\nimport \"./ShadersInclude/imageProcessingFunctions.js\";\nconst name = \"imageProcessingPixelShader\";\nconst shader = `varying vec2 vUV;\runiform sampler2D textureSampler;\r#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\r{\rvec4 result=texture2D(textureSampler,vUV);\r#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\nresult.rgb=toLinearSpace(result.rgb);\r#endif\nresult=applyImageProcessing(result);\r#else\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\r#endif\n#endif\ngl_FragColor=result;\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const imageProcessingPixelShader = { name, shader };\n//# sourceMappingURL=imageProcessing.fragment.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize } from \"../Misc/decorators.js\";\nimport { ImageProcessingConfiguration } from \"../Materials/imageProcessingConfiguration.js\";\nimport { PostProcess } from \"./postProcess.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n\nimport \"../Shaders/imageProcessing.fragment.js\";\nimport \"../Shaders/postprocess.vertex.js\";\n/**\n * ImageProcessingPostProcess\n * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses#imageprocessing\n */\nexport class ImageProcessingPostProcess extends PostProcess {\n /**\n * Gets the image processing configuration used either in this material.\n */\n get imageProcessingConfiguration() {\n return this._imageProcessingConfiguration;\n }\n /**\n * Sets the Default image processing configuration used either in the this material.\n *\n * If sets to null, the scene one is in use.\n */\n set imageProcessingConfiguration(value) {\n // We are almost sure it is applied by post process as\n // We are in the post process :-)\n value.applyByPostProcess = true;\n this._attachImageProcessingConfiguration(value);\n }\n /**\n * Attaches a new image processing configuration to the PBR Material.\n * @param configuration\n * @param doNotBuild\n */\n _attachImageProcessingConfiguration(configuration, doNotBuild = false) {\n if (configuration === this._imageProcessingConfiguration) {\n return;\n }\n // Detaches observer.\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n // Pick the scene configuration if needed.\n if (!configuration) {\n let scene = null;\n const engine = this.getEngine();\n const camera = this.getCamera();\n if (camera) {\n scene = camera.getScene();\n }\n else if (engine && engine.scenes) {\n const scenes = engine.scenes;\n scene = scenes[scenes.length - 1];\n }\n else {\n scene = EngineStore.LastCreatedScene;\n }\n if (scene) {\n this._imageProcessingConfiguration = scene.imageProcessingConfiguration;\n }\n else {\n this._imageProcessingConfiguration = new ImageProcessingConfiguration();\n }\n }\n else {\n this._imageProcessingConfiguration = configuration;\n }\n // Attaches observer.\n if (this._imageProcessingConfiguration) {\n this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => {\n this._updateParameters();\n });\n }\n // Ensure the effect will be rebuilt.\n if (!doNotBuild) {\n this._updateParameters();\n }\n }\n /**\n * If the post process is supported.\n */\n get isSupported() {\n const effect = this.getEffect();\n return !effect || effect.isSupported;\n }\n /**\n * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .\n */\n get colorCurves() {\n return this.imageProcessingConfiguration.colorCurves;\n }\n /**\n * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .\n */\n set colorCurves(value) {\n this.imageProcessingConfiguration.colorCurves = value;\n }\n /**\n * Gets whether the color curves effect is enabled.\n */\n get colorCurvesEnabled() {\n return this.imageProcessingConfiguration.colorCurvesEnabled;\n }\n /**\n * Sets whether the color curves effect is enabled.\n */\n set colorCurvesEnabled(value) {\n this.imageProcessingConfiguration.colorCurvesEnabled = value;\n }\n /**\n * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.\n */\n get colorGradingTexture() {\n return this.imageProcessingConfiguration.colorGradingTexture;\n }\n /**\n * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.\n */\n set colorGradingTexture(value) {\n this.imageProcessingConfiguration.colorGradingTexture = value;\n }\n /**\n * Gets whether the color grading effect is enabled.\n */\n get colorGradingEnabled() {\n return this.imageProcessingConfiguration.colorGradingEnabled;\n }\n /**\n * Gets whether the color grading effect is enabled.\n */\n set colorGradingEnabled(value) {\n this.imageProcessingConfiguration.colorGradingEnabled = value;\n }\n /**\n * Gets exposure used in the effect.\n */\n get exposure() {\n return this.imageProcessingConfiguration.exposure;\n }\n /**\n * Sets exposure used in the effect.\n */\n set exposure(value) {\n this.imageProcessingConfiguration.exposure = value;\n }\n /**\n * Gets whether tonemapping is enabled or not.\n */\n get toneMappingEnabled() {\n return this._imageProcessingConfiguration.toneMappingEnabled;\n }\n /**\n * Sets whether tonemapping is enabled or not\n */\n set toneMappingEnabled(value) {\n this._imageProcessingConfiguration.toneMappingEnabled = value;\n }\n /**\n * Gets the type of tone mapping effect.\n */\n get toneMappingType() {\n return this._imageProcessingConfiguration.toneMappingType;\n }\n /**\n * Sets the type of tone mapping effect.\n */\n set toneMappingType(value) {\n this._imageProcessingConfiguration.toneMappingType = value;\n }\n /**\n * Gets contrast used in the effect.\n */\n get contrast() {\n return this.imageProcessingConfiguration.contrast;\n }\n /**\n * Sets contrast used in the effect.\n */\n set contrast(value) {\n this.imageProcessingConfiguration.contrast = value;\n }\n /**\n * Gets Vignette stretch size.\n */\n get vignetteStretch() {\n return this.imageProcessingConfiguration.vignetteStretch;\n }\n /**\n * Sets Vignette stretch size.\n */\n set vignetteStretch(value) {\n this.imageProcessingConfiguration.vignetteStretch = value;\n }\n /**\n * Gets Vignette center X Offset.\n * @deprecated use vignetteCenterX instead\n */\n get vignetteCentreX() {\n return this.imageProcessingConfiguration.vignetteCenterX;\n }\n /**\n * Sets Vignette center X Offset.\n * @deprecated use vignetteCenterX instead\n */\n set vignetteCentreX(value) {\n this.imageProcessingConfiguration.vignetteCenterX = value;\n }\n /**\n * Gets Vignette center Y Offset.\n * @deprecated use vignetteCenterY instead\n */\n get vignetteCentreY() {\n return this.imageProcessingConfiguration.vignetteCenterY;\n }\n /**\n * Sets Vignette center Y Offset.\n * @deprecated use vignetteCenterY instead\n */\n set vignetteCentreY(value) {\n this.imageProcessingConfiguration.vignetteCenterY = value;\n }\n /**\n * Vignette center Y Offset.\n */\n get vignetteCenterY() {\n return this.imageProcessingConfiguration.vignetteCenterY;\n }\n set vignetteCenterY(value) {\n this.imageProcessingConfiguration.vignetteCenterY = value;\n }\n /**\n * Vignette center X Offset.\n */\n get vignetteCenterX() {\n return this.imageProcessingConfiguration.vignetteCenterX;\n }\n set vignetteCenterX(value) {\n this.imageProcessingConfiguration.vignetteCenterX = value;\n }\n /**\n * Gets Vignette weight or intensity of the vignette effect.\n */\n get vignetteWeight() {\n return this.imageProcessingConfiguration.vignetteWeight;\n }\n /**\n * Sets Vignette weight or intensity of the vignette effect.\n */\n set vignetteWeight(value) {\n this.imageProcessingConfiguration.vignetteWeight = value;\n }\n /**\n * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)\n * if vignetteEnabled is set to true.\n */\n get vignetteColor() {\n return this.imageProcessingConfiguration.vignetteColor;\n }\n /**\n * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)\n * if vignetteEnabled is set to true.\n */\n set vignetteColor(value) {\n this.imageProcessingConfiguration.vignetteColor = value;\n }\n /**\n * Gets Camera field of view used by the Vignette effect.\n */\n get vignetteCameraFov() {\n return this.imageProcessingConfiguration.vignetteCameraFov;\n }\n /**\n * Sets Camera field of view used by the Vignette effect.\n */\n set vignetteCameraFov(value) {\n this.imageProcessingConfiguration.vignetteCameraFov = value;\n }\n /**\n * Gets the vignette blend mode allowing different kind of effect.\n */\n get vignetteBlendMode() {\n return this.imageProcessingConfiguration.vignetteBlendMode;\n }\n /**\n * Sets the vignette blend mode allowing different kind of effect.\n */\n set vignetteBlendMode(value) {\n this.imageProcessingConfiguration.vignetteBlendMode = value;\n }\n /**\n * Gets whether the vignette effect is enabled.\n */\n get vignetteEnabled() {\n return this.imageProcessingConfiguration.vignetteEnabled;\n }\n /**\n * Sets whether the vignette effect is enabled.\n */\n set vignetteEnabled(value) {\n this.imageProcessingConfiguration.vignetteEnabled = value;\n }\n /**\n * Gets intensity of the dithering effect.\n */\n get ditheringIntensity() {\n return this.imageProcessingConfiguration.ditheringIntensity;\n }\n /**\n * Sets intensity of the dithering effect.\n */\n set ditheringIntensity(value) {\n this.imageProcessingConfiguration.ditheringIntensity = value;\n }\n /**\n * Gets whether the dithering effect is enabled.\n */\n get ditheringEnabled() {\n return this.imageProcessingConfiguration.ditheringEnabled;\n }\n /**\n * Sets whether the dithering effect is enabled.\n */\n set ditheringEnabled(value) {\n this.imageProcessingConfiguration.ditheringEnabled = value;\n }\n /**\n * Gets whether the input of the processing is in Gamma or Linear Space.\n */\n get fromLinearSpace() {\n return this._fromLinearSpace;\n }\n /**\n * Sets whether the input of the processing is in Gamma or Linear Space.\n */\n set fromLinearSpace(value) {\n if (this._fromLinearSpace === value) {\n return;\n }\n this._fromLinearSpace = value;\n this._updateParameters();\n }\n constructor(name, options, camera = null, samplingMode, engine, reusable, textureType = 0, imageProcessingConfiguration) {\n super(name, \"imageProcessing\", [], [], options, camera, samplingMode, engine, reusable, null, textureType, \"postprocess\", null, true);\n this._fromLinearSpace = true;\n /**\n * Defines cache preventing GC.\n */\n this._defines = {\n IMAGEPROCESSING: false,\n VIGNETTE: false,\n VIGNETTEBLENDMODEMULTIPLY: false,\n VIGNETTEBLENDMODEOPAQUE: false,\n TONEMAPPING: false,\n TONEMAPPING_ACES: false,\n CONTRAST: false,\n COLORCURVES: false,\n COLORGRADING: false,\n COLORGRADING3D: false,\n FROMLINEARSPACE: false,\n SAMPLER3DGREENDEPTH: false,\n SAMPLER3DBGRMAP: false,\n DITHER: false,\n IMAGEPROCESSINGPOSTPROCESS: false,\n EXPOSURE: false,\n SKIPFINALCOLORCLAMP: false,\n };\n // Setup the configuration as forced by the constructor. This would then not force the\n // scene materials output in linear space and let untouched the default forward pass.\n if (imageProcessingConfiguration) {\n imageProcessingConfiguration.applyByPostProcess = true;\n this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);\n // This will cause the shader to be compiled\n this._updateParameters();\n }\n // Setup the default processing configuration to the scene.\n else {\n this._attachImageProcessingConfiguration(null, true);\n this.imageProcessingConfiguration.applyByPostProcess = true;\n }\n this.onApply = (effect) => {\n this.imageProcessingConfiguration.bind(effect, this.aspectRatio);\n };\n }\n /**\n * \"ImageProcessingPostProcess\"\n * @returns \"ImageProcessingPostProcess\"\n */\n getClassName() {\n return \"ImageProcessingPostProcess\";\n }\n /**\n * @internal\n */\n _updateParameters() {\n this._defines.FROMLINEARSPACE = this._fromLinearSpace;\n this.imageProcessingConfiguration.prepareDefines(this._defines, true);\n let defines = \"\";\n for (const define in this._defines) {\n if (this._defines[define]) {\n defines += `#define ${define};\\r\\n`;\n }\n }\n const samplers = [\"textureSampler\"];\n const uniforms = [\"scale\"];\n if (ImageProcessingConfiguration) {\n ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);\n ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);\n }\n this.updateEffect(defines, uniforms, samplers);\n }\n dispose(camera) {\n super.dispose(camera);\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n if (this._imageProcessingConfiguration) {\n this.imageProcessingConfiguration.applyByPostProcess = false;\n }\n }\n}\n__decorate([\n serialize()\n], ImageProcessingPostProcess.prototype, \"_fromLinearSpace\", void 0);\n//# sourceMappingURL=imageProcessingPostProcess.js.map","/**\n * Wrapper over subclasses of XRLayer.\n * @internal\n */\nexport class WebXRLayerWrapper {\n /**\n * Check if fixed foveation is supported on this device\n */\n get isFixedFoveationSupported() {\n return this.layerType == \"XRWebGLLayer\" && typeof this.layer.fixedFoveation == \"number\";\n }\n /**\n * Get the fixed foveation currently set, as specified by the webxr specs\n * If this returns null, then fixed foveation is not supported\n */\n get fixedFoveation() {\n if (this.isFixedFoveationSupported) {\n return this.layer.fixedFoveation;\n }\n return null;\n }\n /**\n * Set the fixed foveation to the specified value, as specified by the webxr specs\n * This value will be normalized to be between 0 and 1, 1 being max foveation, 0 being no foveation\n */\n set fixedFoveation(value) {\n if (this.isFixedFoveationSupported) {\n const val = Math.max(0, Math.min(1, value || 0));\n this.layer.fixedFoveation = val;\n }\n }\n constructor(\n /** The width of the layer's framebuffer. */\n getWidth, \n /** The height of the layer's framebuffer. */\n getHeight, \n /** The XR layer that this WebXRLayerWrapper wraps. */\n layer, \n /** The type of XR layer that is being wrapped. */\n layerType, \n /** Create a render target provider for the wrapped layer. */\n createRenderTargetTextureProvider) {\n this.getWidth = getWidth;\n this.getHeight = getHeight;\n this.layer = layer;\n this.layerType = layerType;\n this.createRenderTargetTextureProvider = createRenderTargetTextureProvider;\n }\n}\n//# sourceMappingURL=webXRLayerWrapper.js.map","import { WebGLHardwareTexture } from \"../Engines/WebGL/webGLHardwareTexture.js\";\nimport { InternalTexture, InternalTextureSource } from \"../Materials/Textures/internalTexture.js\";\nimport { MultiviewRenderTarget } from \"../Materials/Textures/MultiviewRenderTarget.js\";\nimport { RenderTargetTexture } from \"../Materials/Textures/renderTargetTexture.js\";\n/**\n * Provides render target textures and other important rendering information for a given XRLayer.\n * @internal\n */\nexport class WebXRLayerRenderTargetTextureProvider {\n constructor(_scene, layerWrapper) {\n this._scene = _scene;\n this.layerWrapper = layerWrapper;\n this._renderTargetTextures = new Array();\n this._engine = _scene.getEngine();\n }\n _createInternalTexture(textureSize, texture) {\n const internalTexture = new InternalTexture(this._engine, InternalTextureSource.Unknown, true);\n internalTexture.width = textureSize.width;\n internalTexture.height = textureSize.height;\n internalTexture._hardwareTexture = new WebGLHardwareTexture(texture, this._engine._gl);\n internalTexture.isReady = true;\n return internalTexture;\n }\n _createRenderTargetTexture(width, height, framebuffer, colorTexture, depthStencilTexture, multiview) {\n if (!this._engine) {\n throw new Error(\"Engine is disposed\");\n }\n const textureSize = { width, height };\n // Create render target texture from the internal texture\n const renderTargetTexture = multiview ? new MultiviewRenderTarget(this._scene, textureSize) : new RenderTargetTexture(\"XR renderTargetTexture\", textureSize, this._scene);\n const renderTargetWrapper = renderTargetTexture.renderTarget;\n renderTargetWrapper._samples = renderTargetTexture.samples;\n // Set the framebuffer, make sure it works in all scenarios - emulator, no layers and layers\n if (framebuffer || !colorTexture) {\n renderTargetWrapper._framebuffer = framebuffer;\n }\n // Create internal texture\n if (colorTexture) {\n if (multiview) {\n renderTargetWrapper._colorTextureArray = colorTexture;\n }\n else {\n const internalTexture = this._createInternalTexture(textureSize, colorTexture);\n renderTargetWrapper.setTexture(internalTexture, 0);\n renderTargetTexture._texture = internalTexture;\n }\n }\n if (depthStencilTexture) {\n if (multiview) {\n renderTargetWrapper._depthStencilTextureArray = depthStencilTexture;\n }\n else {\n renderTargetWrapper._depthStencilTexture = this._createInternalTexture(textureSize, depthStencilTexture);\n }\n }\n renderTargetTexture.disableRescaling();\n // Firefox reality fails if skipInitialClear is set to true, so make sure only modern XR implementations set it.\n if (typeof XRWebGLBinding !== \"undefined\") {\n // WebXR pre-clears textures\n renderTargetTexture.skipInitialClear = true;\n }\n this._renderTargetTextures.push(renderTargetTexture);\n return renderTargetTexture;\n }\n _destroyRenderTargetTexture(renderTargetTexture) {\n this._renderTargetTextures.splice(this._renderTargetTextures.indexOf(renderTargetTexture), 1);\n renderTargetTexture.dispose();\n }\n getFramebufferDimensions() {\n return this._framebufferDimensions;\n }\n dispose() {\n this._renderTargetTextures.forEach((rtt) => rtt.dispose());\n this._renderTargetTextures.length = 0;\n }\n}\n//# sourceMappingURL=webXRRenderTargetTextureProvider.js.map","import { WebXRLayerWrapper } from \"./webXRLayerWrapper.js\";\nimport { WebXRLayerRenderTargetTextureProvider } from \"./webXRRenderTargetTextureProvider.js\";\n/**\n * Wraps xr webgl layers.\n * @internal\n */\nexport class WebXRWebGLLayerWrapper extends WebXRLayerWrapper {\n /**\n * @param layer is the layer to be wrapped.\n * @returns a new WebXRLayerWrapper wrapping the provided XRWebGLLayer.\n */\n constructor(layer) {\n super(() => layer.framebufferWidth, () => layer.framebufferHeight, layer, \"XRWebGLLayer\", (sessionManager) => new WebXRWebGLLayerRenderTargetTextureProvider(sessionManager.scene, this));\n this.layer = layer;\n }\n}\n/**\n * Provides render target textures and other important rendering information for a given XRWebGLLayer.\n * @internal\n */\nexport class WebXRWebGLLayerRenderTargetTextureProvider extends WebXRLayerRenderTargetTextureProvider {\n constructor(scene, layerWrapper) {\n super(scene, layerWrapper);\n this.layerWrapper = layerWrapper;\n this._layer = layerWrapper.layer;\n this._framebufferDimensions = {\n framebufferWidth: this._layer.framebufferWidth,\n framebufferHeight: this._layer.framebufferHeight,\n };\n }\n trySetViewportForView(viewport, view) {\n const xrViewport = this._layer.getViewport(view);\n if (!xrViewport) {\n return false;\n }\n const framebufferWidth = this._framebufferDimensions.framebufferWidth;\n const framebufferHeight = this._framebufferDimensions.framebufferHeight;\n viewport.x = xrViewport.x / framebufferWidth;\n viewport.y = xrViewport.y / framebufferHeight;\n viewport.width = xrViewport.width / framebufferWidth;\n viewport.height = xrViewport.height / framebufferHeight;\n return true;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getRenderTargetTextureForEye(eye) {\n const layerWidth = this._layer.framebufferWidth;\n const layerHeight = this._layer.framebufferHeight;\n const framebuffer = this._layer.framebuffer;\n if (!this._rtt ||\n layerWidth !== this._framebufferDimensions.framebufferWidth ||\n layerHeight !== this._framebufferDimensions.framebufferHeight ||\n framebuffer !== this._framebuffer) {\n this._rtt = this._createRenderTargetTexture(layerWidth, layerHeight, framebuffer);\n this._framebufferDimensions.framebufferWidth = layerWidth;\n this._framebufferDimensions.framebufferHeight = layerHeight;\n this._framebuffer = framebuffer;\n }\n return this._rtt;\n }\n getRenderTargetTextureForView(view) {\n return this.getRenderTargetTextureForEye(view.eye);\n }\n}\n//# sourceMappingURL=webXRWebGLLayer.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { Tools } from \"../Misc/tools.js\";\nimport { WebXRWebGLLayerWrapper } from \"./webXRWebGLLayer.js\";\n/**\n * Configuration object for WebXR output canvas\n */\nexport class WebXRManagedOutputCanvasOptions {\n /**\n * Get the default values of the configuration object\n * @param engine defines the engine to use (can be null)\n * @returns default values of this configuration object\n */\n static GetDefaults(engine) {\n const defaults = new WebXRManagedOutputCanvasOptions();\n defaults.canvasOptions = {\n antialias: true,\n depth: true,\n stencil: engine ? engine.isStencilEnable : true,\n alpha: true,\n framebufferScaleFactor: 1,\n };\n defaults.newCanvasCssStyle = \"position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;\";\n return defaults;\n }\n}\n/**\n * Creates a canvas that is added/removed from the webpage when entering/exiting XR\n */\nexport class WebXRManagedOutputCanvas {\n /**\n * Initializes the canvas to be added/removed upon entering/exiting xr\n * @param _xrSessionManager The XR Session manager\n * @param _options optional configuration for this canvas output. defaults will be used if not provided\n */\n constructor(_xrSessionManager, _options = WebXRManagedOutputCanvasOptions.GetDefaults()) {\n this._options = _options;\n this._canvas = null;\n this._engine = null;\n /**\n * xr layer for the canvas\n */\n this.xrLayer = null;\n this._xrLayerWrapper = null;\n /**\n * Observers registered here will be triggered when the xr layer was initialized\n */\n this.onXRLayerInitObservable = new Observable();\n this._engine = _xrSessionManager.scene.getEngine();\n this._engine.onDisposeObservable.addOnce(() => {\n this._engine = null;\n });\n if (!_options.canvasElement) {\n const canvas = document.createElement(\"canvas\");\n canvas.style.cssText = this._options.newCanvasCssStyle || \"position:absolute; bottom:0px;right:0px;\";\n this._setManagedOutputCanvas(canvas);\n }\n else {\n this._setManagedOutputCanvas(_options.canvasElement);\n }\n _xrSessionManager.onXRSessionInit.add(() => {\n this._addCanvas();\n });\n _xrSessionManager.onXRSessionEnded.add(() => {\n this._removeCanvas();\n });\n }\n /**\n * Disposes of the object\n */\n dispose() {\n this._removeCanvas();\n this._setManagedOutputCanvas(null);\n }\n /**\n * Initializes a XRWebGLLayer to be used as the session's baseLayer.\n * @param xrSession xr session\n * @returns a promise that will resolve once the XR Layer has been created\n */\n async initializeXRLayerAsync(xrSession) {\n const createLayer = () => {\n this.xrLayer = new XRWebGLLayer(xrSession, this.canvasContext, this._options.canvasOptions);\n this._xrLayerWrapper = new WebXRWebGLLayerWrapper(this.xrLayer);\n this.onXRLayerInitObservable.notifyObservers(this.xrLayer);\n return this.xrLayer;\n };\n // support canvases without makeXRCompatible\n if (!this.canvasContext.makeXRCompatible) {\n return Promise.resolve(createLayer());\n }\n return this.canvasContext\n .makeXRCompatible()\n .then(\n // catch any error and continue. When using the emulator is throws this error for no apparent reason.\n () => { }, () => {\n // log the error, continue nonetheless!\n Tools.Warn(\"Error executing makeXRCompatible. This does not mean that the session will work incorrectly.\");\n })\n .then(() => {\n return createLayer();\n });\n }\n _addCanvas() {\n if (this._canvas && this._engine && this._canvas !== this._engine.getRenderingCanvas()) {\n document.body.appendChild(this._canvas);\n }\n if (this.xrLayer) {\n this._setCanvasSize(true);\n }\n else {\n this.onXRLayerInitObservable.addOnce(() => {\n this._setCanvasSize(true);\n });\n }\n }\n _removeCanvas() {\n if (this._canvas && this._engine && document.body.contains(this._canvas) && this._canvas !== this._engine.getRenderingCanvas()) {\n document.body.removeChild(this._canvas);\n }\n this._setCanvasSize(false);\n }\n _setCanvasSize(init = true, xrLayer = this._xrLayerWrapper) {\n if (!this._canvas || !this._engine) {\n return;\n }\n if (init) {\n if (xrLayer) {\n if (this._canvas !== this._engine.getRenderingCanvas()) {\n this._canvas.style.width = xrLayer.getWidth() + \"px\";\n this._canvas.style.height = xrLayer.getHeight() + \"px\";\n }\n else {\n this._engine.setSize(xrLayer.getWidth(), xrLayer.getHeight());\n }\n }\n }\n else {\n if (this._originalCanvasSize) {\n if (this._canvas !== this._engine.getRenderingCanvas()) {\n this._canvas.style.width = this._originalCanvasSize.width + \"px\";\n this._canvas.style.height = this._originalCanvasSize.height + \"px\";\n }\n else {\n this._engine.setSize(this._originalCanvasSize.width, this._originalCanvasSize.height);\n }\n }\n }\n }\n _setManagedOutputCanvas(canvas) {\n this._removeCanvas();\n if (!canvas) {\n this._canvas = null;\n this.canvasContext = null;\n }\n else {\n this._originalCanvasSize = {\n width: canvas.offsetWidth,\n height: canvas.offsetHeight,\n };\n this._canvas = canvas;\n this.canvasContext = this._canvas.getContext(\"webgl2\");\n if (!this.canvasContext) {\n this.canvasContext = this._canvas.getContext(\"webgl\");\n }\n }\n }\n}\n//# sourceMappingURL=webXRManagedOutputCanvas.js.map","import { WebXRLayerWrapper } from \"../webXRLayerWrapper.js\";\nimport { WebXRLayerRenderTargetTextureProvider } from \"../webXRRenderTargetTextureProvider.js\";\n/**\n * Wraps XRWebGLLayer's created by Babylon Native.\n * @internal\n */\nexport class NativeXRLayerWrapper extends WebXRLayerWrapper {\n constructor(layer) {\n super(() => layer.framebufferWidth, () => layer.framebufferHeight, layer, \"XRWebGLLayer\", (sessionManager) => new NativeXRLayerRenderTargetTextureProvider(sessionManager, this));\n this.layer = layer;\n }\n}\n/**\n * Provides render target textures for layers created by Babylon Native.\n * @internal\n */\nexport class NativeXRLayerRenderTargetTextureProvider extends WebXRLayerRenderTargetTextureProvider {\n constructor(sessionManager, layerWrapper) {\n super(sessionManager.scene, layerWrapper);\n this.layerWrapper = layerWrapper;\n this._nativeRTTProvider = navigator.xr.getNativeRenderTargetProvider(sessionManager.session, this._createRenderTargetTexture.bind(this), this._destroyRenderTargetTexture.bind(this));\n this._nativeLayer = layerWrapper.layer;\n }\n trySetViewportForView(viewport) {\n viewport.x = 0;\n viewport.y = 0;\n viewport.width = 1;\n viewport.height = 1;\n return true;\n }\n getRenderTargetTextureForEye(eye) {\n // TODO (rgerd): Update the contract on the BabylonNative side to call this \"getRenderTargetTextureForEye\"\n return this._nativeRTTProvider.getRenderTargetForEye(eye);\n }\n getRenderTargetTextureForView(view) {\n return this._nativeRTTProvider.getRenderTargetForEye(view.eye);\n }\n getFramebufferDimensions() {\n return {\n framebufferWidth: this._nativeLayer.framebufferWidth,\n framebufferHeight: this._nativeLayer.framebufferHeight,\n };\n }\n}\n/**\n * Creates the xr layer that will be used as the xr session's base layer.\n * @internal\n */\nexport class NativeXRRenderTarget {\n constructor(_xrSessionManager) {\n this._nativeRenderTarget = navigator.xr.getWebXRRenderTarget(_xrSessionManager.scene.getEngine());\n }\n async initializeXRLayerAsync(xrSession) {\n await this._nativeRenderTarget.initializeXRLayerAsync(xrSession);\n this.xrLayer = this._nativeRenderTarget.xrLayer;\n return this.xrLayer;\n }\n dispose() {\n /* empty */\n }\n}\n//# sourceMappingURL=nativeXRRenderTarget.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { WebXRManagedOutputCanvas, WebXRManagedOutputCanvasOptions } from \"./webXRManagedOutputCanvas.js\";\nimport { NativeXRLayerWrapper, NativeXRRenderTarget } from \"./native/nativeXRRenderTarget.js\";\nimport { WebXRWebGLLayerWrapper } from \"./webXRWebGLLayer.js\";\n/**\n * Manages an XRSession to work with Babylon's engine\n * @see https://doc.babylonjs.com/features/featuresDeepDive/webXR/webXRSessionManagers\n */\nexport class WebXRSessionManager {\n /**\n * Constructs a WebXRSessionManager, this must be initialized within a user action before usage\n * @param scene The scene which the session should be created for\n */\n constructor(\n /** The scene which the session should be created for */\n scene) {\n this.scene = scene;\n /** WebXR timestamp updated every frame */\n this.currentTimestamp = -1;\n /**\n * Used just in case of a failure to initialize an immersive session.\n * The viewer reference space is compensated using this height, creating a kind of \"viewer-floor\" reference space\n */\n this.defaultHeightCompensation = 1.7;\n /**\n * Fires every time a new xrFrame arrives which can be used to update the camera\n */\n this.onXRFrameObservable = new Observable();\n /**\n * Fires when the reference space changed\n */\n this.onXRReferenceSpaceChanged = new Observable();\n /**\n * Fires when the xr session is ended either by the device or manually done\n */\n this.onXRSessionEnded = new Observable();\n /**\n * Fires when the xr session is initialized: right after requestSession was called and returned with a successful result\n */\n this.onXRSessionInit = new Observable();\n /**\n * Are we currently in the XR loop?\n */\n this.inXRFrameLoop = false;\n /**\n * Are we in an XR session?\n */\n this.inXRSession = false;\n this._engine = scene.getEngine();\n this._onEngineDisposedObserver = this._engine.onDisposeObservable.addOnce(() => {\n this._engine = null;\n });\n scene.onDisposeObservable.addOnce(() => {\n this.dispose();\n });\n }\n /**\n * The current reference space used in this session. This reference space can constantly change!\n * It is mainly used to offset the camera's position.\n */\n get referenceSpace() {\n return this._referenceSpace;\n }\n /**\n * Set a new reference space and triggers the observable\n */\n set referenceSpace(newReferenceSpace) {\n this._referenceSpace = newReferenceSpace;\n this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace);\n }\n /**\n * The mode for the managed XR session\n */\n get sessionMode() {\n return this._sessionMode;\n }\n /**\n * Disposes of the session manager\n * This should be called explicitly by the dev, if required.\n */\n dispose() {\n var _a;\n // disposing without leaving XR? Exit XR first\n if (this.inXRSession) {\n this.exitXRAsync();\n }\n this.onXRFrameObservable.clear();\n this.onXRSessionEnded.clear();\n this.onXRReferenceSpaceChanged.clear();\n this.onXRSessionInit.clear();\n (_a = this._engine) === null || _a === void 0 ? void 0 : _a.onDisposeObservable.remove(this._onEngineDisposedObserver);\n this._engine = null;\n }\n /**\n * Stops the xrSession and restores the render loop\n * @returns Promise which resolves after it exits XR\n */\n exitXRAsync() {\n if (this.session && this.inXRSession) {\n this.inXRSession = false;\n return this.session.end().catch(() => {\n Logger.Warn(\"Could not end XR session.\");\n });\n }\n return Promise.resolve();\n }\n /**\n * Attempts to set the framebuffer-size-normalized viewport to be rendered this frame for this view.\n * In the event of a failure, the supplied viewport is not updated.\n * @param viewport the viewport to which the view will be rendered\n * @param view the view for which to set the viewport\n * @returns whether the operation was successful\n */\n trySetViewportForView(viewport, view) {\n var _a;\n return ((_a = this._baseLayerRTTProvider) === null || _a === void 0 ? void 0 : _a.trySetViewportForView(viewport, view)) || false;\n }\n /**\n * Gets the correct render target texture to be rendered this frame for this eye\n * @param eye the eye for which to get the render target\n * @returns the render target for the specified eye or null if not available\n */\n getRenderTargetTextureForEye(eye) {\n var _a;\n return ((_a = this._baseLayerRTTProvider) === null || _a === void 0 ? void 0 : _a.getRenderTargetTextureForEye(eye)) || null;\n }\n /**\n * Gets the correct render target texture to be rendered this frame for this view\n * @param view the view for which to get the render target\n * @returns the render target for the specified view or null if not available\n */\n getRenderTargetTextureForView(view) {\n var _a;\n return ((_a = this._baseLayerRTTProvider) === null || _a === void 0 ? void 0 : _a.getRenderTargetTextureForView(view)) || null;\n }\n /**\n * Creates a WebXRRenderTarget object for the XR session\n * @param options optional options to provide when creating a new render target\n * @returns a WebXR render target to which the session can render\n */\n getWebXRRenderTarget(options) {\n const engine = this.scene.getEngine();\n if (this._xrNavigator.xr.native) {\n return new NativeXRRenderTarget(this);\n }\n else {\n options = options || WebXRManagedOutputCanvasOptions.GetDefaults(engine);\n options.canvasElement = options.canvasElement || engine.getRenderingCanvas() || undefined;\n return new WebXRManagedOutputCanvas(this, options);\n }\n }\n /**\n * Initializes the manager\n * After initialization enterXR can be called to start an XR session\n * @returns Promise which resolves after it is initialized\n */\n initializeAsync() {\n // Check if the browser supports webXR\n this._xrNavigator = navigator;\n if (!this._xrNavigator.xr) {\n return Promise.reject(\"WebXR not available\");\n }\n return Promise.resolve();\n }\n /**\n * Initializes an xr session\n * @param xrSessionMode mode to initialize\n * @param xrSessionInit defines optional and required values to pass to the session builder\n * @returns a promise which will resolve once the session has been initialized\n */\n initializeSessionAsync(xrSessionMode = \"immersive-vr\", xrSessionInit = {}) {\n return this._xrNavigator.xr.requestSession(xrSessionMode, xrSessionInit).then((session) => {\n this.session = session;\n this._sessionMode = xrSessionMode;\n this.onXRSessionInit.notifyObservers(session);\n this.inXRSession = true;\n // handle when the session is ended (By calling session.end or device ends its own session eg. pressing home button on phone)\n this.session.addEventListener(\"end\", () => {\n var _a;\n this.inXRSession = false;\n // Notify frame observers\n this.onXRSessionEnded.notifyObservers(null);\n if (this._engine) {\n // make sure dimensions object is restored\n this._engine.framebufferDimensionsObject = null;\n // Restore frame buffer to avoid clear on xr framebuffer after session end\n this._engine.restoreDefaultFramebuffer();\n // Need to restart render loop as after the session is ended the last request for new frame will never call callback\n this._engine.customAnimationFrameRequester = null;\n this._engine._renderLoop();\n }\n // Dispose render target textures.\n // Only dispose on native because we can't destroy opaque textures on browser.\n if (this.isNative) {\n (_a = this._baseLayerRTTProvider) === null || _a === void 0 ? void 0 : _a.dispose();\n }\n this._baseLayerRTTProvider = null;\n this._baseLayerWrapper = null;\n }, { once: true });\n return this.session;\n });\n }\n /**\n * Checks if a session would be supported for the creation options specified\n * @param sessionMode session mode to check if supported eg. immersive-vr\n * @returns A Promise that resolves to true if supported and false if not\n */\n isSessionSupportedAsync(sessionMode) {\n return WebXRSessionManager.IsSessionSupportedAsync(sessionMode);\n }\n /**\n * Resets the reference space to the one started the session\n */\n resetReferenceSpace() {\n this.referenceSpace = this.baseReferenceSpace;\n }\n /**\n * Starts rendering to the xr layer\n */\n runXRRenderLoop() {\n var _a;\n if (!this.inXRSession || !this._engine) {\n return;\n }\n // Tell the engine's render loop to be driven by the xr session's refresh rate and provide xr pose information\n this._engine.customAnimationFrameRequester = {\n requestAnimationFrame: this.session.requestAnimationFrame.bind(this.session),\n renderFunction: (timestamp, xrFrame) => {\n var _a;\n if (!this.inXRSession || !this._engine) {\n return;\n }\n // Store the XR frame and timestamp in the session manager\n this.currentFrame = xrFrame;\n this.currentTimestamp = timestamp;\n if (xrFrame) {\n this.inXRFrameLoop = true;\n this._engine.framebufferDimensionsObject = ((_a = this._baseLayerRTTProvider) === null || _a === void 0 ? void 0 : _a.getFramebufferDimensions()) || null;\n this.onXRFrameObservable.notifyObservers(xrFrame);\n this._engine._renderLoop();\n this._engine.framebufferDimensionsObject = null;\n this.inXRFrameLoop = false;\n }\n },\n };\n this._engine.framebufferDimensionsObject = ((_a = this._baseLayerRTTProvider) === null || _a === void 0 ? void 0 : _a.getFramebufferDimensions()) || null;\n // Stop window's animation frame and trigger sessions animation frame\n if (typeof window !== \"undefined\" && window.cancelAnimationFrame) {\n window.cancelAnimationFrame(this._engine._frameHandler);\n }\n this._engine._renderLoop();\n }\n /**\n * Sets the reference space on the xr session\n * @param referenceSpaceType space to set\n * @returns a promise that will resolve once the reference space has been set\n */\n setReferenceSpaceTypeAsync(referenceSpaceType = \"local-floor\") {\n return this.session\n .requestReferenceSpace(referenceSpaceType)\n .then((referenceSpace) => {\n return referenceSpace;\n }, (rejectionReason) => {\n Logger.Error(\"XR.requestReferenceSpace failed for the following reason: \");\n Logger.Error(rejectionReason);\n Logger.Log('Defaulting to universally-supported \"viewer\" reference space type.');\n return this.session.requestReferenceSpace(\"viewer\").then((referenceSpace) => {\n const heightCompensation = new XRRigidTransform({ x: 0, y: -this.defaultHeightCompensation, z: 0 });\n return referenceSpace.getOffsetReferenceSpace(heightCompensation);\n }, (rejectionReason) => {\n Logger.Error(rejectionReason);\n throw 'XR initialization failed: required \"viewer\" reference space type not supported.';\n });\n })\n .then((referenceSpace) => {\n // create viewer reference space before setting the first reference space\n return this.session.requestReferenceSpace(\"viewer\").then((viewerReferenceSpace) => {\n this.viewerReferenceSpace = viewerReferenceSpace;\n return referenceSpace;\n });\n })\n .then((referenceSpace) => {\n // initialize the base and offset (currently the same)\n this.referenceSpace = this.baseReferenceSpace = referenceSpace;\n return this.referenceSpace;\n });\n }\n /**\n * Updates the render state of the session.\n * Note that this is deprecated in favor of WebXRSessionManager.updateRenderState().\n * @param state state to set\n * @returns a promise that resolves once the render state has been updated\n * @deprecated\n */\n updateRenderStateAsync(state) {\n return Promise.resolve(this.session.updateRenderState(state));\n }\n /**\n * @internal\n */\n _setBaseLayerWrapper(baseLayerWrapper) {\n var _a, _b;\n if (this.isNative) {\n (_a = this._baseLayerRTTProvider) === null || _a === void 0 ? void 0 : _a.dispose();\n }\n this._baseLayerWrapper = baseLayerWrapper;\n this._baseLayerRTTProvider = ((_b = this._baseLayerWrapper) === null || _b === void 0 ? void 0 : _b.createRenderTargetTextureProvider(this)) || null;\n }\n /**\n * @internal\n */\n _getBaseLayerWrapper() {\n return this._baseLayerWrapper;\n }\n /**\n * Updates the render state of the session\n * @param state state to set\n */\n updateRenderState(state) {\n if (state.baseLayer) {\n this._setBaseLayerWrapper(this.isNative ? new NativeXRLayerWrapper(state.baseLayer) : new WebXRWebGLLayerWrapper(state.baseLayer));\n }\n this.session.updateRenderState(state);\n }\n /**\n * Returns a promise that resolves with a boolean indicating if the provided session mode is supported by this browser\n * @param sessionMode defines the session to test\n * @returns a promise with boolean as final value\n */\n static IsSessionSupportedAsync(sessionMode) {\n if (!navigator.xr) {\n return Promise.resolve(false);\n }\n // When the specs are final, remove supportsSession!\n const functionToUse = navigator.xr.isSessionSupported || navigator.xr.supportsSession;\n if (!functionToUse) {\n return Promise.resolve(false);\n }\n else {\n return functionToUse\n .call(navigator.xr, sessionMode)\n .then((result) => {\n const returnValue = typeof result === \"undefined\" ? true : result;\n return Promise.resolve(returnValue);\n })\n .catch((e) => {\n Logger.Warn(e);\n return Promise.resolve(false);\n });\n }\n }\n /**\n * Returns true if Babylon.js is using the BabylonNative backend, otherwise false\n */\n get isNative() {\n var _a;\n return (_a = this._xrNavigator.xr.native) !== null && _a !== void 0 ? _a : false;\n }\n /**\n * The current frame rate as reported by the device\n */\n get currentFrameRate() {\n var _a;\n return (_a = this.session) === null || _a === void 0 ? void 0 : _a.frameRate;\n }\n /**\n * A list of supported frame rates (only available in-session!\n */\n get supportedFrameRates() {\n var _a;\n return (_a = this.session) === null || _a === void 0 ? void 0 : _a.supportedFrameRates;\n }\n /**\n * Set the framerate of the session.\n * @param rate the new framerate. This value needs to be in the supportedFrameRates array\n * @returns a promise that resolves once the framerate has been set\n */\n updateTargetFrameRate(rate) {\n return this.session.updateTargetFrameRate(rate);\n }\n /**\n * Run a callback in the xr render loop\n * @param callback the callback to call when in XR Frame\n * @param ignoreIfNotInSession if no session is currently running, run it first thing on the next session\n */\n runInXRFrame(callback, ignoreIfNotInSession = true) {\n if (this.inXRFrameLoop) {\n callback();\n }\n else if (this.inXRSession || !ignoreIfNotInSession) {\n this.onXRFrameObservable.addOnce(callback);\n }\n }\n /**\n * Check if fixed foveation is supported on this device\n */\n get isFixedFoveationSupported() {\n var _a;\n return ((_a = this._baseLayerWrapper) === null || _a === void 0 ? void 0 : _a.isFixedFoveationSupported) || false;\n }\n /**\n * Get the fixed foveation currently set, as specified by the webxr specs\n * If this returns null, then fixed foveation is not supported\n */\n get fixedFoveation() {\n var _a;\n return ((_a = this._baseLayerWrapper) === null || _a === void 0 ? void 0 : _a.fixedFoveation) || null;\n }\n /**\n * Set the fixed foveation to the specified value, as specified by the webxr specs\n * This value will be normalized to be between 0 and 1, 1 being max foveation, 0 being no foveation\n */\n set fixedFoveation(value) {\n const val = Math.max(0, Math.min(1, value || 0));\n if (this._baseLayerWrapper) {\n this._baseLayerWrapper.fixedFoveation = val;\n }\n }\n /**\n * Get the features enabled on the current session\n * This is only available in-session!\n * @see https://www.w3.org/TR/webxr/#dom-xrsession-enabledfeatures\n */\n get enabledFeatures() {\n var _a, _b;\n return (_b = (_a = this.session) === null || _a === void 0 ? void 0 : _a.enabledFeatures) !== null && _b !== void 0 ? _b : null;\n }\n}\n//# sourceMappingURL=webXRSessionManager.js.map","/**\n * States of the webXR experience\n */\nexport var WebXRState;\n(function (WebXRState) {\n /**\n * Transitioning to being in XR mode\n */\n WebXRState[WebXRState[\"ENTERING_XR\"] = 0] = \"ENTERING_XR\";\n /**\n * Transitioning to non XR mode\n */\n WebXRState[WebXRState[\"EXITING_XR\"] = 1] = \"EXITING_XR\";\n /**\n * In XR mode and presenting\n */\n WebXRState[WebXRState[\"IN_XR\"] = 2] = \"IN_XR\";\n /**\n * Not entered XR mode\n */\n WebXRState[WebXRState[\"NOT_IN_XR\"] = 3] = \"NOT_IN_XR\";\n})(WebXRState || (WebXRState = {}));\n/**\n * The state of the XR camera's tracking\n */\nexport var WebXRTrackingState;\n(function (WebXRTrackingState) {\n /**\n * No transformation received, device is not being tracked\n */\n WebXRTrackingState[WebXRTrackingState[\"NOT_TRACKING\"] = 0] = \"NOT_TRACKING\";\n /**\n * Tracking lost - using emulated position\n */\n WebXRTrackingState[WebXRTrackingState[\"TRACKING_LOST\"] = 1] = \"TRACKING_LOST\";\n /**\n * Transformation tracking works normally\n */\n WebXRTrackingState[WebXRTrackingState[\"TRACKING\"] = 2] = \"TRACKING\";\n})(WebXRTrackingState || (WebXRTrackingState = {}));\n//# sourceMappingURL=webXRTypes.js.map","import { Vector4, Vector3, Vector2 } from \"../../Maths/math.vector.js\";\nimport { Color4 } from \"../../Maths/math.color.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { Scene } from \"../../scene.js\";\nimport { Axis } from \"../../Maths/math.axis.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n/**\n * Creates the VertexData for a cylinder, cone or prism\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * height sets the height (y direction) of the cylinder, optional, default 2\n * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter\n * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter\n * * diameter sets the diameter of the top and bottom of the cone, optional default 1\n * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24\n * * subdivisions` the number of rings along the cylinder height, optional, default 1\n * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1\n * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively\n * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively\n * * hasRings when true makes each subdivision independently treated as a face for faceUV and faceColors, optional, default false\n * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.height\n * @param options.diameterTop\n * @param options.diameterBottom\n * @param options.diameter\n * @param options.tessellation\n * @param options.subdivisions\n * @param options.arc\n * @param options.faceColors\n * @param options.faceUV\n * @param options.hasRings\n * @param options.enclose\n * @param options.cap\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the cylinder, cone or prism\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function CreateCylinderVertexData(options) {\n const height = options.height || 2;\n let diameterTop = options.diameterTop === 0 ? 0 : options.diameterTop || options.diameter || 1;\n let diameterBottom = options.diameterBottom === 0 ? 0 : options.diameterBottom || options.diameter || 1;\n diameterTop = diameterTop || 0.00001; // Prevent broken normals\n diameterBottom = diameterBottom || 0.00001; // Prevent broken normals\n const tessellation = options.tessellation || 24;\n const subdivisions = options.subdivisions || 1;\n const hasRings = options.hasRings ? true : false;\n const enclose = options.enclose ? true : false;\n const cap = options.cap === 0 ? 0 : options.cap || Mesh.CAP_ALL;\n const arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;\n const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;\n const faceUV = options.faceUV || new Array(3);\n const faceColors = options.faceColors;\n // default face colors and UV if undefined\n const quadNb = arc !== 1 && enclose ? 2 : 0;\n const ringNb = hasRings ? subdivisions : 1;\n const surfaceNb = 2 + (1 + quadNb) * ringNb;\n let f;\n for (f = 0; f < surfaceNb; f++) {\n if (faceColors && faceColors[f] === undefined) {\n faceColors[f] = new Color4(1, 1, 1, 1);\n }\n }\n for (f = 0; f < surfaceNb; f++) {\n if (faceUV && faceUV[f] === undefined) {\n faceUV[f] = new Vector4(0, 0, 1, 1);\n }\n }\n const indices = new Array();\n const positions = new Array();\n const normals = new Array();\n const uvs = new Array();\n const colors = new Array();\n const angleStep = (Math.PI * 2 * arc) / tessellation;\n let angle;\n let h;\n let radius;\n const tan = (diameterBottom - diameterTop) / 2 / height;\n const ringVertex = Vector3.Zero();\n const ringNormal = Vector3.Zero();\n const ringFirstVertex = Vector3.Zero();\n const ringFirstNormal = Vector3.Zero();\n const quadNormal = Vector3.Zero();\n const Y = Axis.Y;\n // positions, normals, uvs\n let i;\n let j;\n let r;\n let ringIdx = 1;\n let s = 1; // surface index\n let cs = 0;\n let v = 0;\n for (i = 0; i <= subdivisions; i++) {\n h = i / subdivisions;\n radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;\n ringIdx = hasRings && i !== 0 && i !== subdivisions ? 2 : 1;\n for (r = 0; r < ringIdx; r++) {\n if (hasRings) {\n s += r;\n }\n if (enclose) {\n s += 2 * r;\n }\n for (j = 0; j <= tessellation; j++) {\n angle = j * angleStep;\n // position\n ringVertex.x = Math.cos(-angle) * radius;\n ringVertex.y = -height / 2 + h * height;\n ringVertex.z = Math.sin(-angle) * radius;\n // normal\n if (diameterTop === 0 && i === subdivisions) {\n // if no top cap, reuse former normals\n ringNormal.x = normals[normals.length - (tessellation + 1) * 3];\n ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];\n ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];\n }\n else {\n ringNormal.x = ringVertex.x;\n ringNormal.z = ringVertex.z;\n ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;\n ringNormal.normalize();\n }\n // keep first ring vertex values for enclose\n if (j === 0) {\n ringFirstVertex.copyFrom(ringVertex);\n ringFirstNormal.copyFrom(ringNormal);\n }\n positions.push(ringVertex.x, ringVertex.y, ringVertex.z);\n normals.push(ringNormal.x, ringNormal.y, ringNormal.z);\n if (hasRings) {\n v = cs !== s ? faceUV[s].y : faceUV[s].w;\n }\n else {\n v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;\n }\n uvs.push(faceUV[s].x + ((faceUV[s].z - faceUV[s].x) * j) / tessellation, CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v);\n if (faceColors) {\n colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);\n }\n }\n // if enclose, add four vertices and their dedicated normals\n if (arc !== 1 && enclose) {\n positions.push(ringVertex.x, ringVertex.y, ringVertex.z);\n positions.push(0, ringVertex.y, 0);\n positions.push(0, ringVertex.y, 0);\n positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);\n Vector3.CrossToRef(Y, ringNormal, quadNormal);\n quadNormal.normalize();\n normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);\n Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);\n quadNormal.normalize();\n normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);\n if (hasRings) {\n v = cs !== s ? faceUV[s + 1].y : faceUV[s + 1].w;\n }\n else {\n v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;\n }\n uvs.push(faceUV[s + 1].x, CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v);\n uvs.push(faceUV[s + 1].z, CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v);\n if (hasRings) {\n v = cs !== s ? faceUV[s + 2].y : faceUV[s + 2].w;\n }\n else {\n v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;\n }\n uvs.push(faceUV[s + 2].x, CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v);\n uvs.push(faceUV[s + 2].z, CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v);\n if (faceColors) {\n colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);\n colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);\n colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);\n colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);\n }\n }\n if (cs !== s) {\n cs = s;\n }\n }\n }\n // indices\n const e = arc !== 1 && enclose ? tessellation + 4 : tessellation; // correction of number of iteration if enclose\n i = 0;\n for (s = 0; s < subdivisions; s++) {\n let i0 = 0;\n let i1 = 0;\n let i2 = 0;\n let i3 = 0;\n for (j = 0; j < tessellation; j++) {\n i0 = i * (e + 1) + j;\n i1 = (i + 1) * (e + 1) + j;\n i2 = i * (e + 1) + (j + 1);\n i3 = (i + 1) * (e + 1) + (j + 1);\n indices.push(i0, i1, i2);\n indices.push(i3, i2, i1);\n }\n if (arc !== 1 && enclose) {\n // if enclose, add two quads\n indices.push(i0 + 2, i1 + 2, i2 + 2);\n indices.push(i3 + 2, i2 + 2, i1 + 2);\n indices.push(i0 + 4, i1 + 4, i2 + 4);\n indices.push(i3 + 4, i2 + 4, i1 + 4);\n }\n i = hasRings ? i + 2 : i + 1;\n }\n // Caps\n const createCylinderCap = (isTop) => {\n const radius = isTop ? diameterTop / 2 : diameterBottom / 2;\n if (radius === 0) {\n return;\n }\n // Cap positions, normals & uvs\n let angle;\n let circleVector;\n let i;\n const u = isTop ? faceUV[surfaceNb - 1] : faceUV[0];\n let c = null;\n if (faceColors) {\n c = isTop ? faceColors[surfaceNb - 1] : faceColors[0];\n }\n // cap center\n const vbase = positions.length / 3;\n const offset = isTop ? height / 2 : -height / 2;\n const center = new Vector3(0, offset, 0);\n positions.push(center.x, center.y, center.z);\n normals.push(0, isTop ? 1 : -1, 0);\n const v = u.y + (u.w - u.y) * 0.5;\n uvs.push(u.x + (u.z - u.x) * 0.5, CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v);\n if (c) {\n colors.push(c.r, c.g, c.b, c.a);\n }\n const textureScale = new Vector2(0.5, 0.5);\n for (i = 0; i <= tessellation; i++) {\n angle = (Math.PI * 2 * i * arc) / tessellation;\n const cos = Math.cos(-angle);\n const sin = Math.sin(-angle);\n circleVector = new Vector3(cos * radius, offset, sin * radius);\n const textureCoordinate = new Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);\n positions.push(circleVector.x, circleVector.y, circleVector.z);\n normals.push(0, isTop ? 1 : -1, 0);\n const v = u.y + (u.w - u.y) * textureCoordinate.y;\n uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v);\n if (c) {\n colors.push(c.r, c.g, c.b, c.a);\n }\n }\n // Cap indices\n for (i = 0; i < tessellation; i++) {\n if (!isTop) {\n indices.push(vbase);\n indices.push(vbase + (i + 1));\n indices.push(vbase + (i + 2));\n }\n else {\n indices.push(vbase);\n indices.push(vbase + (i + 2));\n indices.push(vbase + (i + 1));\n }\n }\n };\n // add caps to geometry based on cap parameter\n if (cap === Mesh.CAP_START || cap === Mesh.CAP_ALL) {\n createCylinderCap(false);\n }\n if (cap === Mesh.CAP_END || cap === Mesh.CAP_ALL) {\n createCylinderCap(true);\n }\n // Sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n if (faceColors) {\n vertexData.colors = colors;\n }\n return vertexData;\n}\n/**\n * Creates a cylinder or a cone mesh\n * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).\n * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).\n * * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter \"diameterBottom\" can't be zero.\n * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.\n * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).\n * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.\n * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.\n * * The parameter `cap` sets the way the cylinder is capped. Possible values : BABYLON.Mesh.NO_CAP, BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL (default).\n * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.\n * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n Color3 elements) and `faceUV` (an array of n Vector4 elements).\n * * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3\n * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7\n * * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17\n * * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface.\n * * If `enclose` is false, a ring surface is one element.\n * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.\n * * Example how to set colors and textures on a sliced cylinder : https://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.height\n * @param options.diameterTop\n * @param options.diameterBottom\n * @param options.diameter\n * @param options.tessellation\n * @param options.subdivisions\n * @param options.arc\n * @param options.faceColors\n * @param options.faceUV\n * @param options.updatable\n * @param options.hasRings\n * @param options.enclose\n * @param options.cap\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param scene defines the hosting scene\n * @returns the cylinder mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#cylinder-or-cone\n */\nexport function CreateCylinder(name, options = {}, scene) {\n const cylinder = new Mesh(name, scene);\n options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n cylinder._originalBuilderSideOrientation = options.sideOrientation;\n const vertexData = CreateCylinderVertexData(options);\n vertexData.applyToMesh(cylinder, options.updatable);\n return cylinder;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated Please use CreateCylinder directly\n */\nexport const CylinderBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateCylinder,\n};\nVertexData.CreateCylinder = CreateCylinderVertexData;\nMesh.CreateCylinder = (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) => {\n if (scene === undefined || !(scene instanceof Scene)) {\n if (scene !== undefined) {\n sideOrientation = updatable || Mesh.DEFAULTSIDE;\n updatable = scene;\n }\n scene = subdivisions;\n subdivisions = 1;\n }\n const options = {\n height,\n diameterTop,\n diameterBottom,\n tessellation,\n subdivisions,\n sideOrientation,\n updatable,\n };\n return CreateCylinder(name, options, scene);\n};\n//# sourceMappingURL=cylinderBuilder.js.map","import { Matrix, Vector3, Vector2 } from \"../../Maths/math.vector.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n/**\n * Creates the VertexData for a torus\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * diameter the diameter of the torus, optional default 1\n * * thickness the diameter of the tube forming the torus, optional default 0.5\n * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.diameter\n * @param options.thickness\n * @param options.tessellation\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the torus\n */\nexport function CreateTorusVertexData(options) {\n const indices = [];\n const positions = [];\n const normals = [];\n const uvs = [];\n const diameter = options.diameter || 1;\n const thickness = options.thickness || 0.5;\n const tessellation = options.tessellation || 16;\n const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;\n const stride = tessellation + 1;\n for (let i = 0; i <= tessellation; i++) {\n const u = i / tessellation;\n const outerAngle = (i * Math.PI * 2.0) / tessellation - Math.PI / 2.0;\n const transform = Matrix.Translation(diameter / 2.0, 0, 0).multiply(Matrix.RotationY(outerAngle));\n for (let j = 0; j <= tessellation; j++) {\n const v = 1 - j / tessellation;\n const innerAngle = (j * Math.PI * 2.0) / tessellation + Math.PI;\n const dx = Math.cos(innerAngle);\n const dy = Math.sin(innerAngle);\n // Create a vertex.\n let normal = new Vector3(dx, dy, 0);\n let position = normal.scale(thickness / 2);\n const textureCoordinate = new Vector2(u, v);\n position = Vector3.TransformCoordinates(position, transform);\n normal = Vector3.TransformNormal(normal, transform);\n positions.push(position.x, position.y, position.z);\n normals.push(normal.x, normal.y, normal.z);\n uvs.push(textureCoordinate.x, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - textureCoordinate.y : textureCoordinate.y);\n // And create indices for two triangles.\n const nextI = (i + 1) % stride;\n const nextJ = (j + 1) % stride;\n indices.push(i * stride + j);\n indices.push(i * stride + nextJ);\n indices.push(nextI * stride + j);\n indices.push(i * stride + nextJ);\n indices.push(nextI * stride + nextJ);\n indices.push(nextI * stride + j);\n }\n }\n // Sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Result\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n}\n/**\n * Creates a torus mesh\n * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)\n * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)\n * * The parameter `tessellation` sets the number of torus sides (positive integer, default 16)\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.diameter\n * @param options.thickness\n * @param options.tessellation\n * @param options.updatable\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param scene defines the hosting scene\n * @returns the torus mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#torus\n */\nexport function CreateTorus(name, options = {}, scene) {\n const torus = new Mesh(name, scene);\n options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n torus._originalBuilderSideOrientation = options.sideOrientation;\n const vertexData = CreateTorusVertexData(options);\n vertexData.applyToMesh(torus, options.updatable);\n return torus;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use CreateTorus instead\n */\nexport const TorusBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateTorus,\n};\nVertexData.CreateTorus = CreateTorusVertexData;\nMesh.CreateTorus = (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) => {\n const options = {\n diameter,\n thickness,\n tessellation,\n sideOrientation,\n updatable,\n };\n return CreateTorus(name, options, scene);\n};\n//# sourceMappingURL=torusBuilder.js.map","import { Vector3, Vector2, TmpVectors, Vector4 } from \"../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nMesh._GroundMeshParser = (parsedMesh, scene) => {\n return GroundMesh.Parse(parsedMesh, scene);\n};\n/**\n * Mesh representing the ground\n */\nexport class GroundMesh extends Mesh {\n constructor(name, scene) {\n super(name, scene);\n /** If octree should be generated */\n this.generateOctree = false;\n }\n /**\n * \"GroundMesh\"\n * @returns \"GroundMesh\"\n */\n getClassName() {\n return \"GroundMesh\";\n }\n /**\n * The minimum of x and y subdivisions\n */\n get subdivisions() {\n return Math.min(this._subdivisionsX, this._subdivisionsY);\n }\n /**\n * X subdivisions\n */\n get subdivisionsX() {\n return this._subdivisionsX;\n }\n /**\n * Y subdivisions\n */\n get subdivisionsY() {\n return this._subdivisionsY;\n }\n /**\n * This function will divide the mesh into submeshes and update an octree to help to select the right submeshes\n * for rendering, picking and collision computations. Please note that you must have a decent number of submeshes\n * to get performance improvements when using an octree.\n * @param chunksCount the number of submeshes the mesh will be divided into\n * @param octreeBlocksSize the maximum size of the octree blocks (Default: 32)\n */\n optimize(chunksCount, octreeBlocksSize = 32) {\n this._subdivisionsX = chunksCount;\n this._subdivisionsY = chunksCount;\n this.subdivide(chunksCount);\n // Call the octree system optimization if it is defined.\n const thisAsAny = this;\n if (thisAsAny.createOrUpdateSubmeshesOctree) {\n thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);\n }\n }\n /**\n * Returns a height (y) value in the World system :\n * the ground altitude at the coordinates (x, z) expressed in the World system.\n * @param x x coordinate\n * @param z z coordinate\n * @returns the ground y position if (x, z) are outside the ground surface.\n */\n getHeightAtCoordinates(x, z) {\n const world = this.getWorldMatrix();\n const invMat = TmpVectors.Matrix[5];\n world.invertToRef(invMat);\n const tmpVect = TmpVectors.Vector3[8];\n Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space\n x = tmpVect.x;\n z = tmpVect.z;\n if (x < this._minX || x >= this._maxX || z <= this._minZ || z > this._maxZ) {\n return this.position.y;\n }\n if (!this._heightQuads || this._heightQuads.length == 0) {\n this._initHeightQuads();\n this._computeHeightQuads();\n }\n const facet = this._getFacetAt(x, z);\n const y = -(facet.x * x + facet.z * z + facet.w) / facet.y;\n // return y in the World system\n Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);\n return tmpVect.y;\n }\n /**\n * Returns a normalized vector (Vector3) orthogonal to the ground\n * at the ground coordinates (x, z) expressed in the World system.\n * @param x x coordinate\n * @param z z coordinate\n * @returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.\n */\n getNormalAtCoordinates(x, z) {\n const normal = new Vector3(0.0, 1.0, 0.0);\n this.getNormalAtCoordinatesToRef(x, z, normal);\n return normal;\n }\n /**\n * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground\n * at the ground coordinates (x, z) expressed in the World system.\n * Doesn't update the reference Vector3 if (x, z) are outside the ground surface.\n * @param x x coordinate\n * @param z z coordinate\n * @param ref vector to store the result\n * @returns the GroundMesh.\n */\n getNormalAtCoordinatesToRef(x, z, ref) {\n const world = this.getWorldMatrix();\n const tmpMat = TmpVectors.Matrix[5];\n world.invertToRef(tmpMat);\n const tmpVect = TmpVectors.Vector3[8];\n Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space\n x = tmpVect.x;\n z = tmpVect.z;\n if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {\n return this;\n }\n if (!this._heightQuads || this._heightQuads.length == 0) {\n this._initHeightQuads();\n this._computeHeightQuads();\n }\n const facet = this._getFacetAt(x, z);\n Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);\n return this;\n }\n /**\n * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()\n * if the ground has been updated.\n * This can be used in the render loop.\n * @returns the GroundMesh.\n */\n updateCoordinateHeights() {\n if (!this._heightQuads || this._heightQuads.length == 0) {\n this._initHeightQuads();\n }\n this._computeHeightQuads();\n return this;\n }\n // Returns the element \"facet\" from the heightQuads array relative to (x, z) local coordinates\n _getFacetAt(x, z) {\n // retrieve col and row from x, z coordinates in the ground local system\n const col = Math.floor(((x + this._maxX) * this._subdivisionsX) / this._width);\n const row = Math.floor((-(z + this._maxZ) * this._subdivisionsY) / this._height + this._subdivisionsY);\n const quad = this._heightQuads[row * this._subdivisionsX + col];\n let facet;\n if (z < quad.slope.x * x + quad.slope.y) {\n facet = quad.facet1;\n }\n else {\n facet = quad.facet2;\n }\n return facet;\n }\n // Creates and populates the heightMap array with \"facet\" elements :\n // a quad is two triangular facets separated by a slope, so a \"facet\" element is 1 slope + 2 facets\n // slope : Vector2(c, h) = 2D diagonal line equation setting apart two triangular facets in a quad : z = cx + h\n // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0\n // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0\n // Returns the GroundMesh.\n _initHeightQuads() {\n const subdivisionsX = this._subdivisionsX;\n const subdivisionsY = this._subdivisionsY;\n this._heightQuads = new Array();\n for (let row = 0; row < subdivisionsY; row++) {\n for (let col = 0; col < subdivisionsX; col++) {\n const quad = { slope: Vector2.Zero(), facet1: new Vector4(0.0, 0.0, 0.0, 0.0), facet2: new Vector4(0.0, 0.0, 0.0, 0.0) };\n this._heightQuads[row * subdivisionsX + col] = quad;\n }\n }\n return this;\n }\n // Compute each quad element values and update the the heightMap array :\n // slope : Vector2(c, h) = 2D diagonal line equation setting apart two triangular facets in a quad : z = cx + h\n // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0\n // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0\n // Returns the GroundMesh.\n _computeHeightQuads() {\n const positions = this.getVerticesData(VertexBuffer.PositionKind);\n if (!positions) {\n return this;\n }\n const v1 = TmpVectors.Vector3[3];\n const v2 = TmpVectors.Vector3[2];\n const v3 = TmpVectors.Vector3[1];\n const v4 = TmpVectors.Vector3[0];\n const v1v2 = TmpVectors.Vector3[4];\n const v1v3 = TmpVectors.Vector3[5];\n const v1v4 = TmpVectors.Vector3[6];\n const norm1 = TmpVectors.Vector3[7];\n const norm2 = TmpVectors.Vector3[8];\n let i = 0;\n let j = 0;\n let k = 0;\n let cd = 0; // 2D slope coefficient : z = cd * x + h\n let h = 0;\n let d1 = 0; // facet plane equation : ax + by + cz + d = 0\n let d2 = 0;\n const subdivisionsX = this._subdivisionsX;\n const subdivisionsY = this._subdivisionsY;\n for (let row = 0; row < subdivisionsY; row++) {\n for (let col = 0; col < subdivisionsX; col++) {\n i = col * 3;\n j = row * (subdivisionsX + 1) * 3;\n k = (row + 1) * (subdivisionsX + 1) * 3;\n v1.x = positions[j + i];\n v1.y = positions[j + i + 1];\n v1.z = positions[j + i + 2];\n v2.x = positions[j + i + 3];\n v2.y = positions[j + i + 4];\n v2.z = positions[j + i + 5];\n v3.x = positions[k + i];\n v3.y = positions[k + i + 1];\n v3.z = positions[k + i + 2];\n v4.x = positions[k + i + 3];\n v4.y = positions[k + i + 4];\n v4.z = positions[k + i + 5];\n // 2D slope V1V4\n cd = (v4.z - v1.z) / (v4.x - v1.x);\n h = v1.z - cd * v1.x; // v1 belongs to the slope\n // facet equations :\n // we compute each facet normal vector\n // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0\n // we compute the value d by applying the equation to v1 which belongs to the plane\n // then we store the facet equation in a Vector4\n v2.subtractToRef(v1, v1v2);\n v3.subtractToRef(v1, v1v3);\n v4.subtractToRef(v1, v1v4);\n Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class\n Vector3.CrossToRef(v1v2, v1v4, norm2);\n norm1.normalize();\n norm2.normalize();\n d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);\n d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);\n const quad = this._heightQuads[row * subdivisionsX + col];\n quad.slope.copyFromFloats(cd, h);\n quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);\n quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);\n }\n }\n return this;\n }\n /**\n * Serializes this ground mesh\n * @param serializationObject object to write serialization to\n */\n serialize(serializationObject) {\n super.serialize(serializationObject);\n serializationObject.subdivisionsX = this._subdivisionsX;\n serializationObject.subdivisionsY = this._subdivisionsY;\n serializationObject.minX = this._minX;\n serializationObject.maxX = this._maxX;\n serializationObject.minZ = this._minZ;\n serializationObject.maxZ = this._maxZ;\n serializationObject.width = this._width;\n serializationObject.height = this._height;\n }\n /**\n * Parses a serialized ground mesh\n * @param parsedMesh the serialized mesh\n * @param scene the scene to create the ground mesh in\n * @returns the created ground mesh\n */\n static Parse(parsedMesh, scene) {\n const result = new GroundMesh(parsedMesh.name, scene);\n result._subdivisionsX = parsedMesh.subdivisionsX || 1;\n result._subdivisionsY = parsedMesh.subdivisionsY || 1;\n result._minX = parsedMesh.minX;\n result._maxX = parsedMesh.maxX;\n result._minZ = parsedMesh.minZ;\n result._maxZ = parsedMesh.maxZ;\n result._width = parsedMesh.width;\n result._height = parsedMesh.height;\n return result;\n }\n}\n//# sourceMappingURL=groundMesh.js.map","import { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Color3 } from \"../../Maths/math.color.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { GroundMesh } from \"../groundMesh.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nimport { EngineStore } from \"../../Engines/engineStore.js\";\nimport { Epsilon } from \"../../Maths/math.constants.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n/**\n * Creates the VertexData for a Ground\n * @param options an object used to set the following optional parameters for the Ground, required but can be empty\n * - width the width (x direction) of the ground, optional, default 1\n * - height the height (z direction) of the ground, optional, default 1\n * - subdivisions the number of subdivisions per side, optional, default 1\n * @param options.width\n * @param options.height\n * @param options.subdivisions\n * @param options.subdivisionsX\n * @param options.subdivisionsY\n * @returns the VertexData of the Ground\n */\nexport function CreateGroundVertexData(options) {\n const indices = [];\n const positions = [];\n const normals = [];\n const uvs = [];\n let row, col;\n const width = options.width || 1;\n const height = options.height || 1;\n const subdivisionsX = options.subdivisionsX || options.subdivisions || 1;\n const subdivisionsY = options.subdivisionsY || options.subdivisions || 1;\n for (row = 0; row <= subdivisionsY; row++) {\n for (col = 0; col <= subdivisionsX; col++) {\n const position = new Vector3((col * width) / subdivisionsX - width / 2.0, 0, ((subdivisionsY - row) * height) / subdivisionsY - height / 2.0);\n const normal = new Vector3(0, 1.0, 0);\n positions.push(position.x, position.y, position.z);\n normals.push(normal.x, normal.y, normal.z);\n uvs.push(col / subdivisionsX, CompatibilityOptions.UseOpenGLOrientationForUV ? row / subdivisionsY : 1.0 - row / subdivisionsY);\n }\n }\n for (row = 0; row < subdivisionsY; row++) {\n for (col = 0; col < subdivisionsX; col++) {\n indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));\n indices.push(col + 1 + row * (subdivisionsX + 1));\n indices.push(col + row * (subdivisionsX + 1));\n indices.push(col + (row + 1) * (subdivisionsX + 1));\n indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));\n indices.push(col + row * (subdivisionsX + 1));\n }\n }\n // Result\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n}\n/**\n * Creates the VertexData for a TiledGround by subdividing the ground into tiles\n * @param options an object used to set the following optional parameters for the Ground, required but can be empty\n * * xmin the ground minimum X coordinate, optional, default -1\n * * zmin the ground minimum Z coordinate, optional, default -1\n * * xmax the ground maximum X coordinate, optional, default 1\n * * zmax the ground maximum Z coordinate, optional, default 1\n * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}\n * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}\n * @param options.xmin\n * @param options.zmin\n * @param options.xmax\n * @param options.zmax\n * @param options.subdivisions\n * @param options.subdivisions.w\n * @param options.subdivisions.h\n * @param options.precision\n * @param options.precision.w\n * @param options.precision.h\n * @returns the VertexData of the TiledGround\n */\nexport function CreateTiledGroundVertexData(options) {\n const xmin = options.xmin !== undefined && options.xmin !== null ? options.xmin : -1.0;\n const zmin = options.zmin !== undefined && options.zmin !== null ? options.zmin : -1.0;\n const xmax = options.xmax !== undefined && options.xmax !== null ? options.xmax : 1.0;\n const zmax = options.zmax !== undefined && options.zmax !== null ? options.zmax : 1.0;\n const subdivisions = options.subdivisions || { w: 1, h: 1 };\n const precision = options.precision || { w: 1, h: 1 };\n const indices = new Array();\n const positions = new Array();\n const normals = new Array();\n const uvs = new Array();\n let row, col, tileRow, tileCol;\n subdivisions.h = subdivisions.h < 1 ? 1 : subdivisions.h;\n subdivisions.w = subdivisions.w < 1 ? 1 : subdivisions.w;\n precision.w = precision.w < 1 ? 1 : precision.w;\n precision.h = precision.h < 1 ? 1 : precision.h;\n const tileSize = {\n w: (xmax - xmin) / subdivisions.w,\n h: (zmax - zmin) / subdivisions.h,\n };\n function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {\n // Indices\n const base = positions.length / 3;\n const rowLength = precision.w + 1;\n for (row = 0; row < precision.h; row++) {\n for (col = 0; col < precision.w; col++) {\n const square = [base + col + row * rowLength, base + (col + 1) + row * rowLength, base + (col + 1) + (row + 1) * rowLength, base + col + (row + 1) * rowLength];\n indices.push(square[1]);\n indices.push(square[2]);\n indices.push(square[3]);\n indices.push(square[0]);\n indices.push(square[1]);\n indices.push(square[3]);\n }\n }\n // Position, normals and uvs\n const position = Vector3.Zero();\n const normal = new Vector3(0, 1.0, 0);\n for (row = 0; row <= precision.h; row++) {\n position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;\n for (col = 0; col <= precision.w; col++) {\n position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;\n position.y = 0;\n positions.push(position.x, position.y, position.z);\n normals.push(normal.x, normal.y, normal.z);\n uvs.push(col / precision.w, row / precision.h);\n }\n }\n }\n for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {\n for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {\n applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);\n }\n }\n // Result\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n}\n/**\n * Creates the VertexData of the Ground designed from a heightmap\n * @param options an object used to set the following parameters for the Ground, required and provided by CreateGroundFromHeightMap\n * * width the width (x direction) of the ground\n * * height the height (z direction) of the ground\n * * subdivisions the number of subdivisions per side\n * * minHeight the minimum altitude on the ground, optional, default 0\n * * maxHeight the maximum altitude on the ground, optional default 1\n * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)\n * * buffer the array holding the image color data\n * * bufferWidth the width of image\n * * bufferHeight the height of image\n * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)\n * @param options.width\n * @param options.height\n * @param options.subdivisions\n * @param options.minHeight\n * @param options.maxHeight\n * @param options.colorFilter\n * @param options.buffer\n * @param options.bufferWidth\n * @param options.bufferHeight\n * @param options.alphaFilter\n * @returns the VertexData of the Ground designed from a heightmap\n */\nexport function CreateGroundFromHeightMapVertexData(options) {\n const indices = [];\n const positions = [];\n const normals = [];\n const uvs = [];\n let row, col;\n const filter = options.colorFilter || new Color3(0.3, 0.59, 0.11);\n const alphaFilter = options.alphaFilter || 0.0;\n let invert = false;\n if (options.minHeight > options.maxHeight) {\n invert = true;\n const temp = options.maxHeight;\n options.maxHeight = options.minHeight;\n options.minHeight = temp;\n }\n // Vertices\n for (row = 0; row <= options.subdivisions; row++) {\n for (col = 0; col <= options.subdivisions; col++) {\n const position = new Vector3((col * options.width) / options.subdivisions - options.width / 2.0, 0, ((options.subdivisions - row) * options.height) / options.subdivisions - options.height / 2.0);\n // Compute height\n const heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;\n const heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;\n const pos = (heightMapX + heightMapY * options.bufferWidth) * 4;\n let r = options.buffer[pos] / 255.0;\n let g = options.buffer[pos + 1] / 255.0;\n let b = options.buffer[pos + 2] / 255.0;\n const a = options.buffer[pos + 3] / 255.0;\n if (invert) {\n r = 1.0 - r;\n g = 1.0 - g;\n b = 1.0 - b;\n }\n const gradient = r * filter.r + g * filter.g + b * filter.b;\n // If our alpha channel is not within our filter then we will assign a 'special' height\n // Then when building the indices, we will ignore any vertex that is using the special height\n if (a >= alphaFilter) {\n position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;\n }\n else {\n position.y = options.minHeight - Epsilon; // We can't have a height below minHeight, normally.\n }\n // Add vertex\n positions.push(position.x, position.y, position.z);\n normals.push(0, 0, 0);\n uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);\n }\n }\n // Indices\n for (row = 0; row < options.subdivisions; row++) {\n for (col = 0; col < options.subdivisions; col++) {\n // Calculate Indices\n const idx1 = col + 1 + (row + 1) * (options.subdivisions + 1);\n const idx2 = col + 1 + row * (options.subdivisions + 1);\n const idx3 = col + row * (options.subdivisions + 1);\n const idx4 = col + (row + 1) * (options.subdivisions + 1);\n // Check that all indices are visible (based on our special height)\n // Only display the vertex if all Indices are visible\n // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height\n const isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;\n const isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;\n const isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;\n if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {\n indices.push(idx1);\n indices.push(idx2);\n indices.push(idx3);\n }\n const isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;\n if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {\n indices.push(idx4);\n indices.push(idx1);\n indices.push(idx3);\n }\n }\n }\n // Normals\n VertexData.ComputeNormals(positions, indices, normals);\n // Result\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n}\n/**\n * Creates a ground mesh\n * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground\n * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.width\n * @param options.height\n * @param options.subdivisions\n * @param options.subdivisionsX\n * @param options.subdivisionsY\n * @param options.updatable\n * @param scene defines the hosting scene\n * @returns the ground mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#ground\n */\nexport function CreateGround(name, options = {}, scene) {\n const ground = new GroundMesh(name, scene);\n ground._setReady(false);\n ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;\n ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;\n ground._width = options.width || 1;\n ground._height = options.height || 1;\n ground._maxX = ground._width / 2;\n ground._maxZ = ground._height / 2;\n ground._minX = -ground._maxX;\n ground._minZ = -ground._maxZ;\n const vertexData = CreateGroundVertexData(options);\n vertexData.applyToMesh(ground, options.updatable);\n ground._setReady(true);\n return ground;\n}\n/**\n * Creates a tiled ground mesh\n * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates\n * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates\n * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile\n * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.xmin\n * @param options.zmin\n * @param options.xmax\n * @param options.zmax\n * @param options.subdivisions\n * @param options.subdivisions.w\n * @param options.subdivisions.h\n * @param options.precision\n * @param options.precision.w\n * @param options.precision.h\n * @param options.updatable\n * @param scene defines the hosting scene\n * @returns the tiled ground mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#tiled-ground\n */\nexport function CreateTiledGround(name, options, scene = null) {\n const tiledGround = new Mesh(name, scene);\n const vertexData = CreateTiledGroundVertexData(options);\n vertexData.applyToMesh(tiledGround, options.updatable);\n return tiledGround;\n}\n/**\n * Creates a ground mesh from a height map\n * * The parameter `url` sets the URL of the height map image resource.\n * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.\n * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.\n * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.\n * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.\n * * The parameter `colorFilter` (optional Color3, default (0.3, 0.59, 0.11) ) is the filter to apply to the image pixel colors to compute the height.\n * * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).\n * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n * @param name defines the name of the mesh\n * @param url defines the url to the height map\n * @param options defines the options used to create the mesh\n * @param options.width\n * @param options.height\n * @param options.subdivisions\n * @param options.minHeight\n * @param options.maxHeight\n * @param options.colorFilter\n * @param options.alphaFilter\n * @param options.updatable\n * @param options.onReady\n * @param scene defines the hosting scene\n * @returns the ground mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/height_map\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#ground-from-a-height-map\n */\nexport function CreateGroundFromHeightMap(name, url, options = {}, scene = null) {\n const width = options.width || 10.0;\n const height = options.height || 10.0;\n const subdivisions = options.subdivisions || 1 | 0;\n const minHeight = options.minHeight || 0.0;\n const maxHeight = options.maxHeight || 1.0;\n const filter = options.colorFilter || new Color3(0.3, 0.59, 0.11);\n const alphaFilter = options.alphaFilter || 0.0;\n const updatable = options.updatable;\n const onReady = options.onReady;\n scene = scene || EngineStore.LastCreatedScene;\n const ground = new GroundMesh(name, scene);\n ground._subdivisionsX = subdivisions;\n ground._subdivisionsY = subdivisions;\n ground._width = width;\n ground._height = height;\n ground._maxX = ground._width / 2.0;\n ground._maxZ = ground._height / 2.0;\n ground._minX = -ground._maxX;\n ground._minZ = -ground._maxZ;\n ground._setReady(false);\n const onload = (img) => {\n const bufferWidth = img.width;\n const bufferHeight = img.height;\n if (scene.isDisposed) {\n return;\n }\n const buffer = scene === null || scene === void 0 ? void 0 : scene.getEngine().resizeImageBitmap(img, bufferWidth, bufferHeight);\n const vertexData = CreateGroundFromHeightMapVertexData({\n width: width,\n height: height,\n subdivisions: subdivisions,\n minHeight: minHeight,\n maxHeight: maxHeight,\n colorFilter: filter,\n buffer: buffer,\n bufferWidth: bufferWidth,\n bufferHeight: bufferHeight,\n alphaFilter: alphaFilter,\n });\n vertexData.applyToMesh(ground, updatable);\n //execute ready callback, if set\n if (onReady) {\n onReady(ground);\n }\n ground._setReady(true);\n };\n Tools.LoadImage(url, onload, () => { }, scene.offlineProvider);\n return ground;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use the functions directly from the module\n */\nexport const GroundBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateGround,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateGroundFromHeightMap,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateTiledGround,\n};\nVertexData.CreateGround = CreateGroundVertexData;\nVertexData.CreateTiledGround = CreateTiledGroundVertexData;\nVertexData.CreateGroundFromHeightMap = CreateGroundFromHeightMapVertexData;\nMesh.CreateGround = (name, width, height, subdivisions, scene, updatable) => {\n const options = {\n width,\n height,\n subdivisions,\n updatable,\n };\n return CreateGround(name, options, scene);\n};\nMesh.CreateTiledGround = (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) => {\n const options = {\n xmin,\n zmin,\n xmax,\n zmax,\n subdivisions,\n precision,\n updatable,\n };\n return CreateTiledGround(name, options, scene);\n};\nMesh.CreateGroundFromHeightMap = (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) => {\n const options = {\n width,\n height,\n subdivisions,\n minHeight,\n maxHeight,\n updatable,\n onReady,\n alphaFilter,\n };\n return CreateGroundFromHeightMap(name, url, options, scene);\n};\n//# sourceMappingURL=groundBuilder.js.map","import { Logger } from \"../../Misc/logger.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { FreeCamera } from \"../../Cameras/freeCamera.js\";\nimport { TargetCamera } from \"../../Cameras/targetCamera.js\";\nimport { DeviceOrientationCamera } from \"../../Cameras/deviceOrientationCamera.js\";\nimport { VRDeviceOrientationFreeCamera } from \"../../Cameras/VR/vrDeviceOrientationFreeCamera.js\";\nimport { WebVRFreeCamera } from \"../../Cameras/VR/webVRCamera.js\";\nimport { PointerEventTypes } from \"../../Events/pointerEvents.js\";\nimport { Quaternion, Matrix, Vector3 } from \"../../Maths/math.vector.js\";\nimport { Color3, Color4 } from \"../../Maths/math.color.js\";\nimport { Gamepad } from \"../../Gamepads/gamepad.js\";\nimport { PoseEnabledController, PoseEnabledControllerType } from \"../../Gamepads/Controllers/poseEnabledController.js\";\nimport { WebVRController } from \"../../Gamepads/Controllers/webVRController.js\";\nimport { Xbox360Button } from \"../../Gamepads/xboxGamepad.js\";\nimport { Mesh } from \"../../Meshes/mesh.js\";\nimport { Ray } from \"../../Culling/ray.js\";\nimport { ImageProcessingConfiguration } from \"../../Materials/imageProcessingConfiguration.js\";\nimport { StandardMaterial } from \"../../Materials/standardMaterial.js\";\nimport { DynamicTexture } from \"../../Materials/Textures/dynamicTexture.js\";\nimport { ImageProcessingPostProcess } from \"../../PostProcesses/imageProcessingPostProcess.js\";\nimport { SineEase, EasingFunction, CircleEase } from \"../../Animations/easing.js\";\nimport { Animation } from \"../../Animations/animation.js\";\nimport { VRCameraMetrics } from \"../../Cameras/VR/vrCameraMetrics.js\";\nimport \"../../Gamepads/gamepadSceneComponent.js\";\nimport \"../../Animations/animatable.js\";\nimport { Axis } from \"../../Maths/math.axis.js\";\nimport { WebXRSessionManager } from \"../../XR/webXRSessionManager.js\";\nimport { WebXRState } from \"../../XR/webXRTypes.js\";\nimport { CreateCylinder } from \"../../Meshes/Builders/cylinderBuilder.js\";\nimport { CreateTorus } from \"../../Meshes/Builders/torusBuilder.js\";\nimport { CreateGround } from \"../../Meshes/Builders/groundBuilder.js\";\nclass VRExperienceHelperGazer {\n constructor(scene, gazeTrackerToClone = null) {\n this.scene = scene;\n /** @internal */\n this._pointerDownOnMeshAsked = false;\n /** @internal */\n this._isActionableMesh = false;\n /** @internal */\n this._teleportationRequestInitiated = false;\n /** @internal */\n this._teleportationBackRequestInitiated = false;\n /** @internal */\n this._rotationRightAsked = false;\n /** @internal */\n this._rotationLeftAsked = false;\n /** @internal */\n this._dpadPressed = true;\n /** @internal */\n this._activePointer = false;\n this._id = VRExperienceHelperGazer._IdCounter++;\n // Gaze tracker\n if (!gazeTrackerToClone) {\n this._gazeTracker = CreateTorus(\"gazeTracker\", {\n diameter: 0.0035,\n thickness: 0.0025,\n tessellation: 20,\n updatable: false,\n }, scene);\n this._gazeTracker.bakeCurrentTransformIntoVertices();\n this._gazeTracker.isPickable = false;\n this._gazeTracker.isVisible = false;\n const targetMat = new StandardMaterial(\"targetMat\", scene);\n targetMat.specularColor = Color3.Black();\n targetMat.emissiveColor = new Color3(0.7, 0.7, 0.7);\n targetMat.backFaceCulling = false;\n this._gazeTracker.material = targetMat;\n }\n else {\n this._gazeTracker = gazeTrackerToClone.clone(\"gazeTracker\");\n }\n }\n /**\n * @internal\n */\n _getForwardRay(length) {\n return new Ray(Vector3.Zero(), new Vector3(0, 0, length));\n }\n /** @internal */\n _selectionPointerDown() {\n this._pointerDownOnMeshAsked = true;\n if (this._currentHit) {\n this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });\n }\n }\n /** @internal */\n _selectionPointerUp() {\n if (this._currentHit) {\n this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });\n }\n this._pointerDownOnMeshAsked = false;\n }\n /** @internal */\n _activatePointer() {\n this._activePointer = true;\n }\n /** @internal */\n _deactivatePointer() {\n this._activePointer = false;\n }\n /**\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _updatePointerDistance(distance = 100) { }\n dispose() {\n this._interactionsEnabled = false;\n this._teleportationEnabled = false;\n if (this._gazeTracker) {\n this._gazeTracker.dispose();\n }\n }\n}\nVRExperienceHelperGazer._IdCounter = 0;\nclass VRExperienceHelperControllerGazer extends VRExperienceHelperGazer {\n constructor(webVRController, scene, gazeTrackerToClone) {\n super(scene, gazeTrackerToClone);\n this.webVRController = webVRController;\n // Laser pointer\n this._laserPointer = CreateCylinder(\"laserPointer\", {\n updatable: false,\n height: 1,\n diameterTop: 0.004,\n diameterBottom: 0.0002,\n tessellation: 20,\n subdivisions: 1,\n }, scene);\n const laserPointerMaterial = new StandardMaterial(\"laserPointerMat\", scene);\n laserPointerMaterial.emissiveColor = new Color3(0.7, 0.7, 0.7);\n laserPointerMaterial.alpha = 0.6;\n this._laserPointer.material = laserPointerMaterial;\n this._laserPointer.rotation.x = Math.PI / 2;\n this._laserPointer.position.z = -0.5;\n this._laserPointer.isVisible = false;\n this._laserPointer.isPickable = false;\n if (!webVRController.mesh) {\n // Create an empty mesh that is used prior to loading the high quality model\n const preloadMesh = new Mesh(\"preloadControllerMesh\", scene);\n const preloadPointerPose = new Mesh(PoseEnabledController.POINTING_POSE, scene);\n preloadPointerPose.rotation.x = -0.7;\n preloadMesh.addChild(preloadPointerPose);\n webVRController.attachToMesh(preloadMesh);\n }\n this._setLaserPointerParent(webVRController.mesh);\n this._meshAttachedObserver = webVRController._meshAttachedObservable.add((mesh) => {\n this._setLaserPointerParent(mesh);\n });\n }\n _getForwardRay(length) {\n return this.webVRController.getForwardRay(length);\n }\n /** @internal */\n _activatePointer() {\n super._activatePointer();\n this._laserPointer.isVisible = true;\n }\n /** @internal */\n _deactivatePointer() {\n super._deactivatePointer();\n this._laserPointer.isVisible = false;\n }\n /**\n * @internal\n */\n _setLaserPointerColor(color) {\n this._laserPointer.material.emissiveColor = color;\n }\n /**\n * @internal\n */\n _setLaserPointerLightingDisabled(disabled) {\n this._laserPointer.material.disableLighting = disabled;\n }\n /**\n * @internal\n */\n _setLaserPointerParent(mesh) {\n const makeNotPick = (root) => {\n root.isPickable = false;\n root.getChildMeshes().forEach((c) => {\n makeNotPick(c);\n });\n };\n makeNotPick(mesh);\n const meshChildren = mesh.getChildren(undefined, false);\n let laserParent = mesh;\n this.webVRController._pointingPoseNode = null;\n for (let i = 0; i < meshChildren.length; i++) {\n if (meshChildren[i].name && meshChildren[i].name.indexOf(PoseEnabledController.POINTING_POSE) >= 0) {\n laserParent = meshChildren[i];\n this.webVRController._pointingPoseNode = laserParent;\n break;\n }\n }\n this._laserPointer.parent = laserParent;\n }\n _updatePointerDistance(distance = 100) {\n this._laserPointer.scaling.y = distance;\n this._laserPointer.position.z = -distance / 2;\n }\n dispose() {\n super.dispose();\n this._laserPointer.dispose();\n if (this._meshAttachedObserver) {\n this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);\n }\n }\n}\nclass VRExperienceHelperCameraGazer extends VRExperienceHelperGazer {\n constructor(_getCamera, scene) {\n super(scene);\n this._getCamera = _getCamera;\n }\n _getForwardRay(length) {\n const camera = this._getCamera();\n if (camera) {\n return camera.getForwardRay(length);\n }\n else {\n return new Ray(Vector3.Zero(), Vector3.Forward());\n }\n }\n}\n/**\n * Event containing information after VR has been entered\n */\nexport class OnAfterEnteringVRObservableEvent {\n}\n/**\n * Helps to quickly add VR support to an existing scene.\n * See https://doc.babylonjs.com/features/featuresDeepDive/cameras/webVRHelper\n * @deprecated\n */\nexport class VRExperienceHelper {\n /** Return this.onEnteringVRObservable\n * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly\n */\n get onEnteringVR() {\n return this.onEnteringVRObservable;\n }\n /** Return this.onExitingVRObservable\n * Note: This one is for backward compatibility. Please use onExitingVRObservable directly\n */\n get onExitingVR() {\n return this.onExitingVRObservable;\n }\n /** Return this.onControllerMeshLoadedObservable\n * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly\n */\n get onControllerMeshLoaded() {\n return this.onControllerMeshLoadedObservable;\n }\n /**\n * The mesh used to display where the user is going to teleport.\n */\n get teleportationTarget() {\n return this._teleportationTarget;\n }\n /**\n * Sets the mesh to be used to display where the user is going to teleport.\n */\n set teleportationTarget(value) {\n if (value) {\n value.name = \"teleportationTarget\";\n this._isDefaultTeleportationTarget = false;\n this._teleportationTarget = value;\n }\n }\n /**\n * The mesh used to display where the user is selecting, this mesh will be cloned and set as the gazeTracker for the left and right controller\n * when set bakeCurrentTransformIntoVertices will be called on the mesh.\n * See https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/bakingTransforms\n */\n get gazeTrackerMesh() {\n return this._cameraGazer._gazeTracker;\n }\n set gazeTrackerMesh(value) {\n if (value) {\n // Dispose of existing meshes\n if (this._cameraGazer._gazeTracker) {\n this._cameraGazer._gazeTracker.dispose();\n }\n if (this._leftController && this._leftController._gazeTracker) {\n this._leftController._gazeTracker.dispose();\n }\n if (this._rightController && this._rightController._gazeTracker) {\n this._rightController._gazeTracker.dispose();\n }\n // Set and create gaze trackers on head and controllers\n this._cameraGazer._gazeTracker = value;\n this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();\n this._cameraGazer._gazeTracker.isPickable = false;\n this._cameraGazer._gazeTracker.isVisible = false;\n this._cameraGazer._gazeTracker.name = \"gazeTracker\";\n if (this._leftController) {\n this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone(\"gazeTracker\");\n }\n if (this._rightController) {\n this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone(\"gazeTracker\");\n }\n }\n }\n /**\n * The gaze tracking mesh corresponding to the left controller\n */\n get leftControllerGazeTrackerMesh() {\n if (this._leftController) {\n return this._leftController._gazeTracker;\n }\n return null;\n }\n /**\n * The gaze tracking mesh corresponding to the right controller\n */\n get rightControllerGazeTrackerMesh() {\n if (this._rightController) {\n return this._rightController._gazeTracker;\n }\n return null;\n }\n /**\n * If the ray of the gaze should be displayed.\n */\n get displayGaze() {\n return this._displayGaze;\n }\n /**\n * Sets if the ray of the gaze should be displayed.\n */\n set displayGaze(value) {\n this._displayGaze = value;\n if (!value) {\n this._cameraGazer._gazeTracker.isVisible = false;\n if (this._leftController) {\n this._leftController._gazeTracker.isVisible = false;\n }\n if (this._rightController) {\n this._rightController._gazeTracker.isVisible = false;\n }\n }\n }\n /**\n * If the ray of the LaserPointer should be displayed.\n */\n get displayLaserPointer() {\n return this._displayLaserPointer;\n }\n /**\n * Sets if the ray of the LaserPointer should be displayed.\n */\n set displayLaserPointer(value) {\n this._displayLaserPointer = value;\n if (!value) {\n if (this._rightController) {\n this._rightController._deactivatePointer();\n this._rightController._gazeTracker.isVisible = false;\n }\n if (this._leftController) {\n this._leftController._deactivatePointer();\n this._leftController._gazeTracker.isVisible = false;\n }\n }\n else {\n if (this._rightController) {\n this._rightController._activatePointer();\n }\n if (this._leftController) {\n this._leftController._activatePointer();\n }\n }\n }\n /**\n * The deviceOrientationCamera used as the camera when not in VR.\n */\n get deviceOrientationCamera() {\n return this._deviceOrientationCamera;\n }\n /**\n * Based on the current WebVR support, returns the current VR camera used.\n */\n get currentVRCamera() {\n if (this._webVRready) {\n return this._webVRCamera;\n }\n else {\n return this._scene.activeCamera;\n }\n }\n /**\n * The webVRCamera which is used when in VR.\n */\n get webVRCamera() {\n return this._webVRCamera;\n }\n /**\n * The deviceOrientationCamera that is used as a fallback when vr device is not connected.\n */\n get vrDeviceOrientationCamera() {\n return this._vrDeviceOrientationCamera;\n }\n /**\n * The html button that is used to trigger entering into VR.\n */\n get vrButton() {\n return this._btnVR;\n }\n get _teleportationRequestInitiated() {\n const result = this._cameraGazer._teleportationRequestInitiated ||\n (this._leftController !== null && this._leftController._teleportationRequestInitiated) ||\n (this._rightController !== null && this._rightController._teleportationRequestInitiated);\n return result;\n }\n /**\n * Instantiates a VRExperienceHelper.\n * Helps to quickly add VR support to an existing scene.\n * @param scene The scene the VRExperienceHelper belongs to.\n * @param webVROptions Options to modify the vr experience helper's behavior.\n */\n constructor(scene, \n /** Options to modify the vr experience helper's behavior. */\n webVROptions = {}) {\n this.webVROptions = webVROptions;\n // Can the system support WebVR, even if a headset isn't plugged in?\n this._webVRsupported = false;\n // If WebVR is supported, is a headset plugged in and are we ready to present?\n this._webVRready = false;\n // Are we waiting for the requestPresent callback to complete?\n this._webVRrequesting = false;\n // Are we presenting to the headset right now? (this is the vrDevice state)\n this._webVRpresenting = false;\n // Are we presenting in the fullscreen fallback?\n this._fullscreenVRpresenting = false;\n /**\n * Gets or sets a boolean indicating that gaze can be enabled even if pointer lock is not engage (useful on iOS where fullscreen mode and pointer lock are not supported)\n */\n this.enableGazeEvenWhenNoPointerLock = false;\n /**\n * Gets or sets a boolean indicating that the VREXperienceHelper will exit VR if double tap is detected\n */\n this.exitVROnDoubleTap = true;\n /**\n * Observable raised right before entering VR.\n */\n this.onEnteringVRObservable = new Observable();\n /**\n * Observable raised when entering VR has completed.\n */\n this.onAfterEnteringVRObservable = new Observable();\n /**\n * Observable raised when exiting VR.\n */\n this.onExitingVRObservable = new Observable();\n /**\n * Observable raised when controller mesh is loaded.\n */\n this.onControllerMeshLoadedObservable = new Observable();\n this._useCustomVRButton = false;\n this._teleportationRequested = false;\n this._teleportActive = false;\n this._floorMeshesCollection = [];\n this._teleportationMode = VRExperienceHelper.TELEPORTATIONMODE_CONSTANTTIME;\n this._teleportationTime = 122;\n this._teleportationSpeed = 20;\n this._rotationAllowed = true;\n this._teleportBackwardsVector = new Vector3(0, -1, -1);\n this._isDefaultTeleportationTarget = true;\n this._teleportationFillColor = \"#444444\";\n this._teleportationBorderColor = \"#FFFFFF\";\n this._rotationAngle = 0;\n this._haloCenter = new Vector3(0, 0, 0);\n this._padSensibilityUp = 0.65;\n this._padSensibilityDown = 0.35;\n this._leftController = null;\n this._rightController = null;\n this._gazeColor = new Color3(0.7, 0.7, 0.7);\n this._laserColor = new Color3(0.7, 0.7, 0.7);\n this._pickedLaserColor = new Color3(0.2, 0.2, 1);\n this._pickedGazeColor = new Color3(0, 0, 1);\n /**\n * Observable raised when a new mesh is selected based on meshSelectionPredicate\n */\n this.onNewMeshSelected = new Observable();\n /**\n * Observable raised when a new mesh is selected based on meshSelectionPredicate.\n * This observable will provide the mesh and the controller used to select the mesh\n */\n this.onMeshSelectedWithController = new Observable();\n /**\n * Observable raised when a new mesh is picked based on meshSelectionPredicate\n */\n this.onNewMeshPicked = new Observable();\n /**\n * Observable raised before camera teleportation\n */\n this.onBeforeCameraTeleport = new Observable();\n /**\n * Observable raised after camera teleportation\n */\n this.onAfterCameraTeleport = new Observable();\n /**\n * Observable raised when current selected mesh gets unselected\n */\n this.onSelectedMeshUnselected = new Observable();\n /**\n * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.\n */\n this.teleportationEnabled = true;\n this._teleportationInitialized = false;\n this._interactionsEnabled = false;\n this._interactionsRequested = false;\n this._displayGaze = true;\n this._displayLaserPointer = true;\n /**\n * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes\n */\n this.updateGazeTrackerScale = true;\n /**\n * If the gaze trackers color should be updated when selecting meshes\n */\n this.updateGazeTrackerColor = true;\n /**\n * If the controller laser color should be updated when selecting meshes\n */\n this.updateControllerLaserColor = true;\n /**\n * Defines whether or not Pointer lock should be requested when switching to\n * full screen.\n */\n this.requestPointerLockOnFullScreen = true;\n /**\n * Was the XR test done already. If this is true AND this.xr exists, xr is initialized.\n * If this is true and no this.xr, xr exists but is not supported, using WebVR.\n */\n this.xrTestDone = false;\n this._onResize = () => {\n this._moveButtonToBottomRight();\n if (this._fullscreenVRpresenting && this._webVRready) {\n this.exitVR();\n }\n };\n this._onFullscreenChange = () => {\n this._fullscreenVRpresenting = !!document.fullscreenElement;\n if (!this._fullscreenVRpresenting && this._inputElement) {\n this.exitVR();\n if (!this._useCustomVRButton && this._btnVR) {\n this._btnVR.style.top = this._inputElement.offsetTop + this._inputElement.offsetHeight - 70 + \"px\";\n this._btnVR.style.left = this._inputElement.offsetLeft + this._inputElement.offsetWidth - 100 + \"px\";\n // make sure the button is visible after setting its position\n this._updateButtonVisibility();\n }\n }\n };\n this._cachedAngularSensibility = { angularSensibilityX: null, angularSensibilityY: null, angularSensibility: null };\n this._beforeRender = () => {\n if (this._leftController && this._leftController._activePointer) {\n this._castRayAndSelectObject(this._leftController);\n }\n if (this._rightController && this._rightController._activePointer) {\n this._castRayAndSelectObject(this._rightController);\n }\n if (this._noControllerIsActive && (this._scene.getEngine().isPointerLock || this.enableGazeEvenWhenNoPointerLock)) {\n this._castRayAndSelectObject(this._cameraGazer);\n }\n else {\n this._cameraGazer._gazeTracker.isVisible = false;\n }\n };\n this._onNewGamepadConnected = (gamepad) => {\n if (gamepad.type !== Gamepad.POSE_ENABLED) {\n if (gamepad.leftStick) {\n gamepad.onleftstickchanged((stickValues) => {\n if (this._teleportationInitialized && this.teleportationEnabled) {\n // Listening to classic/xbox gamepad only if no VR controller is active\n if ((!this._leftController && !this._rightController) ||\n (this._leftController && !this._leftController._activePointer && this._rightController && !this._rightController._activePointer)) {\n this._checkTeleportWithRay(stickValues, this._cameraGazer);\n this._checkTeleportBackwards(stickValues, this._cameraGazer);\n }\n }\n });\n }\n if (gamepad.rightStick) {\n gamepad.onrightstickchanged((stickValues) => {\n if (this._teleportationInitialized) {\n this._checkRotate(stickValues, this._cameraGazer);\n }\n });\n }\n if (gamepad.type === Gamepad.XBOX) {\n gamepad.onbuttondown((buttonPressed) => {\n if (this._interactionsEnabled && buttonPressed === Xbox360Button.A) {\n this._cameraGazer._selectionPointerDown();\n }\n });\n gamepad.onbuttonup((buttonPressed) => {\n if (this._interactionsEnabled && buttonPressed === Xbox360Button.A) {\n this._cameraGazer._selectionPointerUp();\n }\n });\n }\n }\n else {\n const webVRController = gamepad;\n const controller = new VRExperienceHelperControllerGazer(webVRController, this._scene, this._cameraGazer._gazeTracker);\n if (webVRController.hand === \"right\" || (this._leftController && this._leftController.webVRController != webVRController)) {\n this._rightController = controller;\n }\n else {\n this._leftController = controller;\n }\n this._tryEnableInteractionOnController(controller);\n }\n };\n // This only succeeds if the controller's mesh exists for the controller so this must be called whenever new controller is connected or when mesh is loaded\n this._tryEnableInteractionOnController = (controller) => {\n if (this._interactionsRequested && !controller._interactionsEnabled) {\n this._enableInteractionOnController(controller);\n }\n if (this._teleportationRequested && !controller._teleportationEnabled) {\n this._enableTeleportationOnController(controller);\n }\n };\n this._onNewGamepadDisconnected = (gamepad) => {\n if (gamepad instanceof WebVRController) {\n if (gamepad.hand === \"left\" && this._leftController != null) {\n this._leftController.dispose();\n this._leftController = null;\n }\n if (gamepad.hand === \"right\" && this._rightController != null) {\n this._rightController.dispose();\n this._rightController = null;\n }\n }\n };\n this._workingVector = Vector3.Zero();\n this._workingQuaternion = Quaternion.Identity();\n this._workingMatrix = Matrix.Identity();\n Logger.Warn(\"WebVR is deprecated. Please avoid using this experience helper and use the WebXR experience helper instead\");\n this._scene = scene;\n this._inputElement = scene.getEngine().getInputElement();\n // check for VR support:\n const vrSupported = \"getVRDisplays\" in navigator;\n // no VR support? force XR but only when it is not set because web vr can work without the getVRDisplays\n if (!vrSupported && webVROptions.useXR === undefined) {\n webVROptions.useXR = true;\n }\n // Parse options\n if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {\n webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;\n }\n if (webVROptions.createDeviceOrientationCamera === undefined) {\n webVROptions.createDeviceOrientationCamera = true;\n }\n if (webVROptions.laserToggle === undefined) {\n webVROptions.laserToggle = true;\n }\n if (webVROptions.defaultHeight === undefined) {\n webVROptions.defaultHeight = 1.7;\n }\n if (webVROptions.useCustomVRButton) {\n this._useCustomVRButton = true;\n if (webVROptions.customVRButton) {\n this._btnVR = webVROptions.customVRButton;\n }\n }\n if (webVROptions.rayLength) {\n this._rayLength = webVROptions.rayLength;\n }\n this._defaultHeight = webVROptions.defaultHeight;\n if (webVROptions.positionScale) {\n this._rayLength *= webVROptions.positionScale;\n this._defaultHeight *= webVROptions.positionScale;\n }\n this._hasEnteredVR = false;\n // Set position\n if (this._scene.activeCamera) {\n this._position = this._scene.activeCamera.position.clone();\n }\n else {\n this._position = new Vector3(0, this._defaultHeight, 0);\n }\n // Set non-vr camera\n if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {\n this._deviceOrientationCamera = new DeviceOrientationCamera(\"deviceOrientationVRHelper\", this._position.clone(), scene);\n // Copy data from existing camera\n if (this._scene.activeCamera) {\n this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;\n this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;\n // Set rotation from previous camera\n if (this._scene.activeCamera instanceof TargetCamera && this._scene.activeCamera.rotation) {\n const targetCamera = this._scene.activeCamera;\n if (targetCamera.rotationQuaternion) {\n this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);\n }\n else {\n this._deviceOrientationCamera.rotationQuaternion.copyFrom(Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));\n }\n this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();\n }\n }\n this._scene.activeCamera = this._deviceOrientationCamera;\n if (this._inputElement) {\n this._scene.activeCamera.attachControl();\n }\n }\n else {\n this._existingCamera = this._scene.activeCamera;\n }\n if (this.webVROptions.useXR && navigator.xr) {\n // force-check XR session support\n WebXRSessionManager.IsSessionSupportedAsync(\"immersive-vr\").then((supported) => {\n if (supported) {\n Logger.Log(\"Using WebXR. It is recommended to use the WebXRDefaultExperience directly\");\n // it is possible to use XR, let's do it!\n scene\n .createDefaultXRExperienceAsync({\n floorMeshes: webVROptions.floorMeshes || [],\n })\n .then((xr) => {\n this.xr = xr;\n // connect observables\n this.xrTestDone = true;\n this._cameraGazer = new VRExperienceHelperCameraGazer(() => {\n return this.xr.baseExperience.camera;\n }, scene);\n this.xr.baseExperience.onStateChangedObservable.add((state) => {\n // support for entering / exiting\n switch (state) {\n case WebXRState.ENTERING_XR:\n this.onEnteringVRObservable.notifyObservers(this);\n if (!this._interactionsEnabled) {\n this.xr.pointerSelection.detach();\n }\n this.xr.pointerSelection.displayLaserPointer = this._displayLaserPointer;\n break;\n case WebXRState.EXITING_XR:\n this.onExitingVRObservable.notifyObservers(this);\n // resize to update width and height when exiting vr exits fullscreen\n this._scene.getEngine().resize();\n break;\n case WebXRState.IN_XR:\n this._hasEnteredVR = true;\n break;\n case WebXRState.NOT_IN_XR:\n this._hasEnteredVR = false;\n break;\n }\n });\n });\n }\n else {\n // XR not supported (thou exists), continue WebVR init\n this._completeVRInit(scene, webVROptions);\n }\n });\n }\n else {\n // no XR, continue init synchronous\n this._completeVRInit(scene, webVROptions);\n }\n }\n _completeVRInit(scene, webVROptions) {\n this.xrTestDone = true;\n // Create VR cameras\n if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {\n if (webVROptions.useMultiview) {\n if (!webVROptions.vrDeviceOrientationCameraMetrics) {\n webVROptions.vrDeviceOrientationCameraMetrics = VRCameraMetrics.GetDefault();\n }\n webVROptions.vrDeviceOrientationCameraMetrics.multiviewEnabled = true;\n }\n this._vrDeviceOrientationCamera = new VRDeviceOrientationFreeCamera(\"VRDeviceOrientationVRHelper\", this._position, this._scene, true, webVROptions.vrDeviceOrientationCameraMetrics);\n this._vrDeviceOrientationCamera.angularSensibility = Number.MAX_VALUE;\n }\n this._webVRCamera = new WebVRFreeCamera(\"WebVRHelper\", this._position, this._scene, webVROptions);\n this._webVRCamera.useStandingMatrix();\n this._cameraGazer = new VRExperienceHelperCameraGazer(() => {\n return this.currentVRCamera;\n }, scene);\n // Create default button\n if (!this._useCustomVRButton) {\n this._btnVR = document.createElement(\"BUTTON\");\n this._btnVR.className = \"babylonVRicon\";\n this._btnVR.id = \"babylonVRiconbtn\";\n this._btnVR.title = \"Click to switch to VR\";\n const url = !window.SVGSVGElement\n ? \"https://cdn.babylonjs.com/Assets/vrButton.png\"\n : \"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A\";\n let css = \".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(\" +\n url +\n \"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }\";\n css += \".babylonVRicon.vrdisplaypresenting { display: none; }\";\n // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)\n // css += \".babylonVRicon.vrdisplaysupported { }\";\n // css += \".babylonVRicon.vrdisplayready { }\";\n // css += \".babylonVRicon.vrdisplayrequesting { }\";\n const style = document.createElement(\"style\");\n style.appendChild(document.createTextNode(css));\n document.getElementsByTagName(\"head\")[0].appendChild(style);\n this._moveButtonToBottomRight();\n }\n // VR button click event\n if (this._btnVR) {\n this._btnVR.addEventListener(\"click\", () => {\n if (!this.isInVRMode) {\n this.enterVR();\n }\n else {\n this._scene.getEngine().disableVR();\n }\n });\n }\n // Window events\n const hostWindow = this._scene.getEngine().getHostWindow();\n if (!hostWindow) {\n return;\n }\n hostWindow.addEventListener(\"resize\", this._onResize);\n document.addEventListener(\"fullscreenchange\", this._onFullscreenChange, false);\n // Display vr button when headset is connected\n if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {\n this._displayVRButton();\n }\n else {\n this._scene.getEngine().onVRDisplayChangedObservable.add((e) => {\n if (e.vrDisplay) {\n this._displayVRButton();\n }\n });\n }\n // Exiting VR mode using 'ESC' key on desktop\n this._onKeyDown = (event) => {\n if (event.keyCode === 27 && this.isInVRMode) {\n this.exitVR();\n }\n };\n document.addEventListener(\"keydown\", this._onKeyDown);\n // Exiting VR mode double tapping the touch screen\n this._scene.onPrePointerObservable.add(() => {\n if (this._hasEnteredVR && this.exitVROnDoubleTap) {\n this.exitVR();\n if (this._fullscreenVRpresenting) {\n this._scene.getEngine().exitFullscreen();\n }\n }\n }, PointerEventTypes.POINTERDOUBLETAP, false);\n // Listen for WebVR display changes\n this._onVRDisplayChangedBind = (eventArgs) => this._onVRDisplayChanged(eventArgs);\n this._onVrDisplayPresentChangeBind = () => this._onVrDisplayPresentChange();\n this._onVRRequestPresentStart = () => {\n this._webVRrequesting = true;\n this._updateButtonVisibility();\n };\n this._onVRRequestPresentComplete = () => {\n this._webVRrequesting = false;\n this._updateButtonVisibility();\n };\n scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChangedBind);\n scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);\n scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);\n hostWindow.addEventListener(\"vrdisplaypresentchange\", this._onVrDisplayPresentChangeBind);\n scene.onDisposeObservable.add(() => {\n this.dispose();\n });\n // Gamepad connection events\n this._webVRCamera.onControllerMeshLoadedObservable.add((webVRController) => this._onDefaultMeshLoaded(webVRController));\n this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);\n this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);\n this._updateButtonVisibility();\n //create easing functions\n this._circleEase = new CircleEase();\n this._circleEase.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT);\n this._teleportationEasing = this._circleEase;\n // Allow clicking in the vrDeviceOrientationCamera\n scene.onPointerObservable.add((e) => {\n if (this._interactionsEnabled) {\n if (scene.activeCamera === this.vrDeviceOrientationCamera && e.event.pointerType === \"mouse\") {\n if (e.type === PointerEventTypes.POINTERDOWN) {\n this._cameraGazer._selectionPointerDown();\n }\n else if (e.type === PointerEventTypes.POINTERUP) {\n this._cameraGazer._selectionPointerUp();\n }\n }\n }\n });\n if (this.webVROptions.floorMeshes) {\n this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });\n }\n }\n // Raised when one of the controller has loaded successfully its associated default mesh\n _onDefaultMeshLoaded(webVRController) {\n if (this._leftController && this._leftController.webVRController == webVRController) {\n if (webVRController.mesh) {\n this._leftController._setLaserPointerParent(webVRController.mesh);\n }\n }\n if (this._rightController && this._rightController.webVRController == webVRController) {\n if (webVRController.mesh) {\n this._rightController._setLaserPointerParent(webVRController.mesh);\n }\n }\n try {\n this.onControllerMeshLoadedObservable.notifyObservers(webVRController);\n }\n catch (err) {\n Logger.Warn(\"Error in your custom logic onControllerMeshLoaded: \" + err);\n }\n }\n /**\n * Gets a value indicating if we are currently in VR mode.\n */\n get isInVRMode() {\n return (this.xr && this.webVROptions.useXR && this.xr.baseExperience.state === WebXRState.IN_XR) || this._webVRpresenting || this._fullscreenVRpresenting;\n }\n _onVrDisplayPresentChange() {\n const vrDisplay = this._scene.getEngine().getVRDevice();\n if (vrDisplay) {\n const wasPresenting = this._webVRpresenting;\n this._webVRpresenting = vrDisplay.isPresenting;\n if (wasPresenting && !this._webVRpresenting) {\n this.exitVR();\n }\n }\n else {\n Logger.Warn(\"Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?\");\n }\n this._updateButtonVisibility();\n }\n _onVRDisplayChanged(eventArgs) {\n this._webVRsupported = eventArgs.vrSupported;\n this._webVRready = !!eventArgs.vrDisplay;\n this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;\n this._updateButtonVisibility();\n }\n _moveButtonToBottomRight() {\n if (this._inputElement && !this._useCustomVRButton && this._btnVR) {\n const rect = this._inputElement.getBoundingClientRect();\n this._btnVR.style.top = rect.top + rect.height - 70 + \"px\";\n this._btnVR.style.left = rect.left + rect.width - 100 + \"px\";\n }\n }\n _displayVRButton() {\n if (!this._useCustomVRButton && !this._btnVRDisplayed && this._btnVR) {\n document.body.appendChild(this._btnVR);\n this._btnVRDisplayed = true;\n }\n }\n _updateButtonVisibility() {\n if (!this._btnVR || this._useCustomVRButton) {\n return;\n }\n this._btnVR.className = \"babylonVRicon\";\n if (this.isInVRMode) {\n this._btnVR.className += \" vrdisplaypresenting\";\n }\n else {\n if (this._webVRready) {\n this._btnVR.className += \" vrdisplayready\";\n }\n if (this._webVRsupported) {\n this._btnVR.className += \" vrdisplaysupported\";\n }\n if (this._webVRrequesting) {\n this._btnVR.className += \" vrdisplayrequesting\";\n }\n }\n }\n /**\n * Attempt to enter VR. If a headset is connected and ready, will request present on that.\n * Otherwise, will use the fullscreen API.\n */\n enterVR() {\n if (this.xr) {\n this.xr.baseExperience.enterXRAsync(\"immersive-vr\", \"local-floor\", this.xr.renderTarget);\n return;\n }\n if (this.onEnteringVRObservable) {\n try {\n this.onEnteringVRObservable.notifyObservers(this);\n }\n catch (err) {\n Logger.Warn(\"Error in your custom logic onEnteringVR: \" + err);\n }\n }\n if (this._scene.activeCamera) {\n this._position = this._scene.activeCamera.position.clone();\n if (this.vrDeviceOrientationCamera) {\n this.vrDeviceOrientationCamera.rotation = Quaternion.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles();\n this.vrDeviceOrientationCamera.angularSensibility = 2000;\n }\n if (this.webVRCamera) {\n const currentYRotation = this.webVRCamera.deviceRotationQuaternion.toEulerAngles().y;\n const desiredYRotation = Quaternion.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles().y;\n const delta = desiredYRotation - currentYRotation;\n const currentGlobalRotation = this.webVRCamera.rotationQuaternion.toEulerAngles().y;\n this.webVRCamera.rotationQuaternion = Quaternion.FromEulerAngles(0, currentGlobalRotation + delta, 0);\n }\n // make sure that we return to the last active camera\n this._existingCamera = this._scene.activeCamera;\n // Remove and cache angular sensability to avoid camera rotation when in VR\n if (this._existingCamera.angularSensibilityX) {\n this._cachedAngularSensibility.angularSensibilityX = this._existingCamera.angularSensibilityX;\n this._existingCamera.angularSensibilityX = Number.MAX_VALUE;\n }\n if (this._existingCamera.angularSensibilityY) {\n this._cachedAngularSensibility.angularSensibilityY = this._existingCamera.angularSensibilityY;\n this._existingCamera.angularSensibilityY = Number.MAX_VALUE;\n }\n if (this._existingCamera.angularSensibility) {\n this._cachedAngularSensibility.angularSensibility = this._existingCamera.angularSensibility;\n this._existingCamera.angularSensibility = Number.MAX_VALUE;\n }\n }\n if (this._webVRrequesting) {\n return;\n }\n // If WebVR is supported and a headset is connected\n if (this._webVRready) {\n if (!this._webVRpresenting) {\n this._scene.getEngine().onVRRequestPresentComplete.addOnce((result) => {\n this.onAfterEnteringVRObservable.notifyObservers({ success: result });\n });\n this._webVRCamera.position = this._position;\n this._scene.activeCamera = this._webVRCamera;\n }\n }\n else if (this._vrDeviceOrientationCamera) {\n this._vrDeviceOrientationCamera.position = this._position;\n if (this._scene.activeCamera) {\n this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;\n }\n this._scene.activeCamera = this._vrDeviceOrientationCamera;\n this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen);\n this._updateButtonVisibility();\n this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce(() => {\n this.onAfterEnteringVRObservable.notifyObservers({ success: true });\n });\n }\n if (this._scene.activeCamera && this._inputElement) {\n this._scene.activeCamera.attachControl();\n }\n if (this._interactionsEnabled) {\n this._scene.registerBeforeRender(this._beforeRender);\n }\n if (this._displayLaserPointer) {\n [this._leftController, this._rightController].forEach((controller) => {\n if (controller) {\n controller._activatePointer();\n }\n });\n }\n this._hasEnteredVR = true;\n }\n /**\n * Attempt to exit VR, or fullscreen.\n */\n exitVR() {\n if (this.xr) {\n this.xr.baseExperience.exitXRAsync();\n return;\n }\n if (this._hasEnteredVR) {\n if (this.onExitingVRObservable) {\n try {\n this.onExitingVRObservable.notifyObservers(this);\n }\n catch (err) {\n Logger.Warn(\"Error in your custom logic onExitingVR: \" + err);\n }\n }\n if (this._webVRpresenting) {\n this._scene.getEngine().disableVR();\n }\n if (this._scene.activeCamera) {\n this._position = this._scene.activeCamera.position.clone();\n }\n if (this.vrDeviceOrientationCamera) {\n this.vrDeviceOrientationCamera.angularSensibility = Number.MAX_VALUE;\n }\n if (this._deviceOrientationCamera) {\n this._deviceOrientationCamera.position = this._position;\n this._scene.activeCamera = this._deviceOrientationCamera;\n // Restore angular sensibility\n if (this._cachedAngularSensibility.angularSensibilityX) {\n this._deviceOrientationCamera.angularSensibilityX = this._cachedAngularSensibility.angularSensibilityX;\n this._cachedAngularSensibility.angularSensibilityX = null;\n }\n if (this._cachedAngularSensibility.angularSensibilityY) {\n this._deviceOrientationCamera.angularSensibilityY = this._cachedAngularSensibility.angularSensibilityY;\n this._cachedAngularSensibility.angularSensibilityY = null;\n }\n if (this._cachedAngularSensibility.angularSensibility) {\n this._deviceOrientationCamera.angularSensibility = this._cachedAngularSensibility.angularSensibility;\n this._cachedAngularSensibility.angularSensibility = null;\n }\n }\n else if (this._existingCamera) {\n this._existingCamera.position = this._position;\n this._scene.activeCamera = this._existingCamera;\n if (this._inputElement) {\n this._scene.activeCamera.attachControl();\n }\n // Restore angular sensibility\n if (this._cachedAngularSensibility.angularSensibilityX) {\n this._existingCamera.angularSensibilityX = this._cachedAngularSensibility.angularSensibilityX;\n this._cachedAngularSensibility.angularSensibilityX = null;\n }\n if (this._cachedAngularSensibility.angularSensibilityY) {\n this._existingCamera.angularSensibilityY = this._cachedAngularSensibility.angularSensibilityY;\n this._cachedAngularSensibility.angularSensibilityY = null;\n }\n if (this._cachedAngularSensibility.angularSensibility) {\n this._existingCamera.angularSensibility = this._cachedAngularSensibility.angularSensibility;\n this._cachedAngularSensibility.angularSensibility = null;\n }\n }\n this._updateButtonVisibility();\n if (this._interactionsEnabled) {\n this._scene.unregisterBeforeRender(this._beforeRender);\n this._cameraGazer._gazeTracker.isVisible = false;\n if (this._leftController) {\n this._leftController._gazeTracker.isVisible = false;\n }\n if (this._rightController) {\n this._rightController._gazeTracker.isVisible = false;\n }\n }\n // resize to update width and height when exiting vr exits fullscreen\n this._scene.getEngine().resize();\n [this._leftController, this._rightController].forEach((controller) => {\n if (controller) {\n controller._deactivatePointer();\n }\n });\n this._hasEnteredVR = false;\n // Update engine state to re enable non-vr camera input\n const engine = this._scene.getEngine();\n if (engine._onVrDisplayPresentChange) {\n engine._onVrDisplayPresentChange();\n }\n }\n }\n /**\n * The position of the vr experience helper.\n */\n get position() {\n return this._position;\n }\n /**\n * Sets the position of the vr experience helper.\n */\n set position(value) {\n this._position = value;\n if (this._scene.activeCamera) {\n this._scene.activeCamera.position = value;\n }\n }\n /**\n * Enables controllers and user interactions such as selecting and object or clicking on an object.\n */\n enableInteractions() {\n if (!this._interactionsEnabled) {\n this._interactionsRequested = true;\n // in XR it is enabled by default, but just to make sure, re-attach\n if (this.xr) {\n if (this.xr.baseExperience.state === WebXRState.IN_XR) {\n this.xr.pointerSelection.attach();\n }\n return;\n }\n if (this._leftController) {\n this._enableInteractionOnController(this._leftController);\n }\n if (this._rightController) {\n this._enableInteractionOnController(this._rightController);\n }\n this.raySelectionPredicate = (mesh) => {\n return mesh.isVisible && (mesh.isPickable || mesh.name === this._floorMeshName);\n };\n this.meshSelectionPredicate = () => {\n return true;\n };\n this._raySelectionPredicate = (mesh) => {\n if (this._isTeleportationFloor(mesh) ||\n (mesh.name.indexOf(\"gazeTracker\") === -1 && mesh.name.indexOf(\"teleportationTarget\") === -1 && mesh.name.indexOf(\"torusTeleportation\") === -1)) {\n return this.raySelectionPredicate(mesh);\n }\n return false;\n };\n this._interactionsEnabled = true;\n }\n }\n get _noControllerIsActive() {\n return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);\n }\n _isTeleportationFloor(mesh) {\n for (let i = 0; i < this._floorMeshesCollection.length; i++) {\n if (this._floorMeshesCollection[i].id === mesh.id) {\n return true;\n }\n }\n if (this._floorMeshName && mesh.name === this._floorMeshName) {\n return true;\n }\n return false;\n }\n /**\n * Adds a floor mesh to be used for teleportation.\n * @param floorMesh the mesh to be used for teleportation.\n */\n addFloorMesh(floorMesh) {\n if (!this._floorMeshesCollection) {\n return;\n }\n if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {\n return;\n }\n this._floorMeshesCollection.push(floorMesh);\n }\n /**\n * Removes a floor mesh from being used for teleportation.\n * @param floorMesh the mesh to be removed.\n */\n removeFloorMesh(floorMesh) {\n if (!this._floorMeshesCollection) {\n return;\n }\n const meshIndex = this._floorMeshesCollection.indexOf(floorMesh);\n if (meshIndex !== -1) {\n this._floorMeshesCollection.splice(meshIndex, 1);\n }\n }\n /**\n * Enables interactions and teleportation using the VR controllers and gaze.\n * @param vrTeleportationOptions options to modify teleportation behavior.\n */\n enableTeleportation(vrTeleportationOptions = {}) {\n if (!this._teleportationInitialized) {\n this._teleportationRequested = true;\n this.enableInteractions();\n if (this.webVROptions.useXR && (vrTeleportationOptions.floorMeshes || vrTeleportationOptions.floorMeshName)) {\n const floorMeshes = vrTeleportationOptions.floorMeshes || [];\n if (!floorMeshes.length) {\n const floorMesh = this._scene.getMeshByName(vrTeleportationOptions.floorMeshName);\n if (floorMesh) {\n floorMeshes.push(floorMesh);\n }\n }\n if (this.xr) {\n floorMeshes.forEach((mesh) => {\n this.xr.teleportation.addFloorMesh(mesh);\n });\n if (!this.xr.teleportation.attached) {\n this.xr.teleportation.attach();\n }\n return;\n }\n else if (!this.xrTestDone) {\n const waitForXr = () => {\n if (this.xrTestDone) {\n this._scene.unregisterBeforeRender(waitForXr);\n if (this.xr) {\n if (!this.xr.teleportation.attached) {\n this.xr.teleportation.attach();\n }\n }\n else {\n this.enableTeleportation(vrTeleportationOptions);\n }\n }\n };\n this._scene.registerBeforeRender(waitForXr);\n return;\n }\n }\n if (vrTeleportationOptions.floorMeshName) {\n this._floorMeshName = vrTeleportationOptions.floorMeshName;\n }\n if (vrTeleportationOptions.floorMeshes) {\n this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;\n }\n if (vrTeleportationOptions.teleportationMode) {\n this._teleportationMode = vrTeleportationOptions.teleportationMode;\n }\n if (vrTeleportationOptions.teleportationTime && vrTeleportationOptions.teleportationTime > 0) {\n this._teleportationTime = vrTeleportationOptions.teleportationTime;\n }\n if (vrTeleportationOptions.teleportationSpeed && vrTeleportationOptions.teleportationSpeed > 0) {\n this._teleportationSpeed = vrTeleportationOptions.teleportationSpeed;\n }\n if (vrTeleportationOptions.easingFunction !== undefined) {\n this._teleportationEasing = vrTeleportationOptions.easingFunction;\n }\n if (this._leftController != null) {\n this._enableTeleportationOnController(this._leftController);\n }\n if (this._rightController != null) {\n this._enableTeleportationOnController(this._rightController);\n }\n // Creates an image processing post process for the vignette not relying\n // on the main scene configuration for image processing to reduce setup and spaces\n // (gamma/linear) conflicts.\n const imageProcessingConfiguration = new ImageProcessingConfiguration();\n imageProcessingConfiguration.vignetteColor = new Color4(0, 0, 0, 0);\n imageProcessingConfiguration.vignetteEnabled = true;\n this._postProcessMove = new ImageProcessingPostProcess(\"postProcessMove\", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);\n this._webVRCamera.detachPostProcess(this._postProcessMove);\n this._teleportationInitialized = true;\n if (this._isDefaultTeleportationTarget) {\n this._createTeleportationCircles();\n this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);\n }\n }\n }\n _enableInteractionOnController(controller) {\n const controllerMesh = controller.webVRController.mesh;\n if (controllerMesh) {\n controller._interactionsEnabled = true;\n if (this.isInVRMode && this._displayLaserPointer) {\n controller._activatePointer();\n }\n if (this.webVROptions.laserToggle) {\n controller.webVRController.onMainButtonStateChangedObservable.add((stateObject) => {\n // Enabling / disabling laserPointer\n if (this._displayLaserPointer && stateObject.value === 1) {\n if (controller._activePointer) {\n controller._deactivatePointer();\n }\n else {\n controller._activatePointer();\n }\n if (this.displayGaze) {\n controller._gazeTracker.isVisible = controller._activePointer;\n }\n }\n });\n }\n controller.webVRController.onTriggerStateChangedObservable.add((stateObject) => {\n let gazer = controller;\n if (this._noControllerIsActive) {\n gazer = this._cameraGazer;\n }\n if (!gazer._pointerDownOnMeshAsked) {\n if (stateObject.value > this._padSensibilityUp) {\n gazer._selectionPointerDown();\n }\n }\n else if (stateObject.value < this._padSensibilityDown) {\n gazer._selectionPointerUp();\n }\n });\n }\n }\n _checkTeleportWithRay(stateObject, gazer) {\n // Dont teleport if another gaze already requested teleportation\n if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {\n return;\n }\n if (!gazer._teleportationRequestInitiated) {\n if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {\n gazer._activatePointer();\n gazer._teleportationRequestInitiated = true;\n }\n }\n else {\n // Listening to the proper controller values changes to confirm teleportation\n if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {\n if (this._teleportActive) {\n this.teleportCamera(this._haloCenter);\n }\n gazer._teleportationRequestInitiated = false;\n }\n }\n }\n _checkRotate(stateObject, gazer) {\n // Only rotate when user is not currently selecting a teleportation location\n if (gazer._teleportationRequestInitiated) {\n return;\n }\n if (!gazer._rotationLeftAsked) {\n if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {\n gazer._rotationLeftAsked = true;\n if (this._rotationAllowed) {\n this._rotateCamera(false);\n }\n }\n }\n else {\n if (stateObject.x > -this._padSensibilityDown) {\n gazer._rotationLeftAsked = false;\n }\n }\n if (!gazer._rotationRightAsked) {\n if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {\n gazer._rotationRightAsked = true;\n if (this._rotationAllowed) {\n this._rotateCamera(true);\n }\n }\n }\n else {\n if (stateObject.x < this._padSensibilityDown) {\n gazer._rotationRightAsked = false;\n }\n }\n }\n _checkTeleportBackwards(stateObject, gazer) {\n // Only teleport backwards when user is not currently selecting a teleportation location\n if (gazer._teleportationRequestInitiated) {\n return;\n }\n // Teleport backwards\n if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {\n if (!gazer._teleportationBackRequestInitiated) {\n if (!this.currentVRCamera) {\n return;\n }\n // Get rotation and position of the current camera\n let rotation = Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());\n let position = this.currentVRCamera.position;\n // If the camera has device position, use that instead\n if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {\n rotation = this.currentVRCamera.deviceRotationQuaternion;\n position = this.currentVRCamera.devicePosition;\n }\n // Get matrix with only the y rotation of the device rotation\n rotation.toEulerAnglesToRef(this._workingVector);\n this._workingVector.z = 0;\n this._workingVector.x = 0;\n Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);\n this._workingQuaternion.toRotationMatrix(this._workingMatrix);\n // Rotate backwards ray by device rotation to cast at the ground behind the user\n Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);\n // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff\n const ray = new Ray(position, this._workingVector);\n const hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);\n if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {\n this.teleportCamera(hit.pickedPoint);\n }\n gazer._teleportationBackRequestInitiated = true;\n }\n }\n else {\n gazer._teleportationBackRequestInitiated = false;\n }\n }\n _enableTeleportationOnController(controller) {\n const controllerMesh = controller.webVRController.mesh;\n if (controllerMesh) {\n if (!controller._interactionsEnabled) {\n this._enableInteractionOnController(controller);\n }\n controller._interactionsEnabled = true;\n controller._teleportationEnabled = true;\n if (controller.webVRController.controllerType === PoseEnabledControllerType.VIVE) {\n controller._dpadPressed = false;\n controller.webVRController.onPadStateChangedObservable.add((stateObject) => {\n controller._dpadPressed = stateObject.pressed;\n if (!controller._dpadPressed) {\n controller._rotationLeftAsked = false;\n controller._rotationRightAsked = false;\n controller._teleportationBackRequestInitiated = false;\n }\n });\n }\n controller.webVRController.onPadValuesChangedObservable.add((stateObject) => {\n if (this.teleportationEnabled) {\n this._checkTeleportBackwards(stateObject, controller);\n this._checkTeleportWithRay(stateObject, controller);\n }\n this._checkRotate(stateObject, controller);\n });\n }\n }\n _createTeleportationCircles() {\n this._teleportationTarget = CreateGround(\"teleportationTarget\", { width: 2, height: 2, subdivisions: 2 }, this._scene);\n this._teleportationTarget.isPickable = false;\n const length = 512;\n const dynamicTexture = new DynamicTexture(\"DynamicTexture\", length, this._scene, true);\n dynamicTexture.hasAlpha = true;\n const context = dynamicTexture.getContext();\n const centerX = length / 2;\n const centerY = length / 2;\n const radius = 200;\n context.beginPath();\n context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);\n context.fillStyle = this._teleportationFillColor;\n context.fill();\n context.lineWidth = 10;\n context.strokeStyle = this._teleportationBorderColor;\n context.stroke();\n context.closePath();\n dynamicTexture.update();\n const teleportationCircleMaterial = new StandardMaterial(\"TextPlaneMaterial\", this._scene);\n teleportationCircleMaterial.diffuseTexture = dynamicTexture;\n this._teleportationTarget.material = teleportationCircleMaterial;\n const torus = CreateTorus(\"torusTeleportation\", {\n diameter: 0.75,\n thickness: 0.1,\n tessellation: 25,\n updatable: false,\n }, this._scene);\n torus.isPickable = false;\n torus.parent = this._teleportationTarget;\n const animationInnerCircle = new Animation(\"animationInnerCircle\", \"position.y\", 30, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CYCLE);\n const keys = [];\n keys.push({\n frame: 0,\n value: 0,\n });\n keys.push({\n frame: 30,\n value: 0.4,\n });\n keys.push({\n frame: 60,\n value: 0,\n });\n animationInnerCircle.setKeys(keys);\n const easingFunction = new SineEase();\n easingFunction.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT);\n animationInnerCircle.setEasingFunction(easingFunction);\n torus.animations = [];\n torus.animations.push(animationInnerCircle);\n this._scene.beginAnimation(torus, 0, 60, true);\n this._hideTeleportationTarget();\n }\n _displayTeleportationTarget() {\n this._teleportActive = true;\n if (this._teleportationInitialized) {\n this._teleportationTarget.isVisible = true;\n if (this._isDefaultTeleportationTarget) {\n this._teleportationTarget.getChildren()[0].isVisible = true;\n }\n }\n }\n _hideTeleportationTarget() {\n this._teleportActive = false;\n if (this._teleportationInitialized) {\n this._teleportationTarget.isVisible = false;\n if (this._isDefaultTeleportationTarget) {\n this._teleportationTarget.getChildren()[0].isVisible = false;\n }\n }\n }\n _rotateCamera(right) {\n if (!(this.currentVRCamera instanceof FreeCamera)) {\n return;\n }\n if (right) {\n this._rotationAngle++;\n }\n else {\n this._rotationAngle--;\n }\n this.currentVRCamera.animations = [];\n const target = Quaternion.FromRotationMatrix(Matrix.RotationY((Math.PI / 4) * this._rotationAngle));\n const animationRotation = new Animation(\"animationRotation\", \"rotationQuaternion\", 90, Animation.ANIMATIONTYPE_QUATERNION, Animation.ANIMATIONLOOPMODE_CONSTANT);\n const animationRotationKeys = [];\n animationRotationKeys.push({\n frame: 0,\n value: this.currentVRCamera.rotationQuaternion,\n });\n animationRotationKeys.push({\n frame: 6,\n value: target,\n });\n animationRotation.setKeys(animationRotationKeys);\n animationRotation.setEasingFunction(this._circleEase);\n this.currentVRCamera.animations.push(animationRotation);\n this._postProcessMove.animations = [];\n const animationPP = new Animation(\"animationPP\", \"vignetteWeight\", 90, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CONSTANT);\n const vignetteWeightKeys = [];\n vignetteWeightKeys.push({\n frame: 0,\n value: 0,\n });\n vignetteWeightKeys.push({\n frame: 3,\n value: 4,\n });\n vignetteWeightKeys.push({\n frame: 6,\n value: 0,\n });\n animationPP.setKeys(vignetteWeightKeys);\n animationPP.setEasingFunction(this._circleEase);\n this._postProcessMove.animations.push(animationPP);\n const animationPP2 = new Animation(\"animationPP2\", \"vignetteStretch\", 90, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CONSTANT);\n const vignetteStretchKeys = [];\n vignetteStretchKeys.push({\n frame: 0,\n value: 0,\n });\n vignetteStretchKeys.push({\n frame: 3,\n value: 10,\n });\n vignetteStretchKeys.push({\n frame: 6,\n value: 0,\n });\n animationPP2.setKeys(vignetteStretchKeys);\n animationPP2.setEasingFunction(this._circleEase);\n this._postProcessMove.animations.push(animationPP2);\n this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;\n this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;\n this._postProcessMove.samples = 4;\n this._webVRCamera.attachPostProcess(this._postProcessMove);\n this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, () => {\n this._webVRCamera.detachPostProcess(this._postProcessMove);\n });\n this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);\n }\n _moveTeleportationSelectorTo(hit, gazer, ray) {\n if (hit.pickedPoint) {\n if (gazer._teleportationRequestInitiated) {\n this._displayTeleportationTarget();\n this._haloCenter.copyFrom(hit.pickedPoint);\n this._teleportationTarget.position.copyFrom(hit.pickedPoint);\n }\n const pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);\n if (pickNormal) {\n const axis1 = Vector3.Cross(Axis.Y, pickNormal);\n const axis2 = Vector3.Cross(pickNormal, axis1);\n Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);\n }\n this._teleportationTarget.position.y += 0.1;\n }\n }\n /**\n * Teleports the users feet to the desired location\n * @param location The location where the user's feet should be placed\n */\n teleportCamera(location) {\n if (!(this.currentVRCamera instanceof FreeCamera)) {\n return;\n }\n // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the\n // offset of the headset from the anchor.\n if (this.webVRCamera.leftCamera) {\n this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);\n this._workingVector.subtractInPlace(this.webVRCamera.position);\n location.subtractToRef(this._workingVector, this._workingVector);\n }\n else {\n this._workingVector.copyFrom(location);\n }\n // Add height to account for user's height offset\n if (this.isInVRMode) {\n this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;\n }\n else {\n this._workingVector.y += this._defaultHeight;\n }\n this.onBeforeCameraTeleport.notifyObservers(this._workingVector);\n // Animations FPS\n const FPS = 90;\n let speedRatio, lastFrame;\n if (this._teleportationMode == VRExperienceHelper.TELEPORTATIONMODE_CONSTANTSPEED) {\n lastFrame = FPS;\n const dist = Vector3.Distance(this.currentVRCamera.position, this._workingVector);\n speedRatio = this._teleportationSpeed / dist;\n }\n else {\n // teleportationMode is TELEPORTATIONMODE_CONSTANTTIME\n lastFrame = Math.round((this._teleportationTime * FPS) / 1000);\n speedRatio = 1;\n }\n // Create animation from the camera's position to the new location\n this.currentVRCamera.animations = [];\n const animationCameraTeleportation = new Animation(\"animationCameraTeleportation\", \"position\", FPS, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT);\n const animationCameraTeleportationKeys = [\n {\n frame: 0,\n value: this.currentVRCamera.position,\n },\n {\n frame: lastFrame,\n value: this._workingVector,\n },\n ];\n animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);\n animationCameraTeleportation.setEasingFunction(this._teleportationEasing);\n this.currentVRCamera.animations.push(animationCameraTeleportation);\n this._postProcessMove.animations = [];\n // Calculate the mid frame for vignette animations\n const midFrame = Math.round(lastFrame / 2);\n const animationPP = new Animation(\"animationPP\", \"vignetteWeight\", FPS, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CONSTANT);\n const vignetteWeightKeys = [];\n vignetteWeightKeys.push({\n frame: 0,\n value: 0,\n });\n vignetteWeightKeys.push({\n frame: midFrame,\n value: 8,\n });\n vignetteWeightKeys.push({\n frame: lastFrame,\n value: 0,\n });\n animationPP.setKeys(vignetteWeightKeys);\n this._postProcessMove.animations.push(animationPP);\n const animationPP2 = new Animation(\"animationPP2\", \"vignetteStretch\", FPS, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CONSTANT);\n const vignetteStretchKeys = [];\n vignetteStretchKeys.push({\n frame: 0,\n value: 0,\n });\n vignetteStretchKeys.push({\n frame: midFrame,\n value: 10,\n });\n vignetteStretchKeys.push({\n frame: lastFrame,\n value: 0,\n });\n animationPP2.setKeys(vignetteStretchKeys);\n this._postProcessMove.animations.push(animationPP2);\n this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;\n this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;\n this._webVRCamera.attachPostProcess(this._postProcessMove);\n this._scene.beginAnimation(this._postProcessMove, 0, lastFrame, false, speedRatio, () => {\n this._webVRCamera.detachPostProcess(this._postProcessMove);\n });\n this._scene.beginAnimation(this.currentVRCamera, 0, lastFrame, false, speedRatio, () => {\n this.onAfterCameraTeleport.notifyObservers(this._workingVector);\n });\n this._hideTeleportationTarget();\n }\n _convertNormalToDirectionOfRay(normal, ray) {\n if (normal) {\n const angle = Math.acos(Vector3.Dot(normal, ray.direction));\n if (angle < Math.PI / 2) {\n normal.scaleInPlace(-1);\n }\n }\n return normal;\n }\n _castRayAndSelectObject(gazer) {\n if (!(this.currentVRCamera instanceof FreeCamera)) {\n return;\n }\n const ray = gazer._getForwardRay(this._rayLength);\n const hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);\n if (hit) {\n this._scene.simulatePointerMove(hit, { pointerId: gazer._id });\n }\n gazer._currentHit = hit;\n // Moving the gazeTracker on the mesh face targetted\n if (hit && hit.pickedPoint) {\n if (this._displayGaze) {\n let multiplier = 1;\n gazer._gazeTracker.isVisible = true;\n if (gazer._isActionableMesh) {\n multiplier = 3;\n }\n if (this.updateGazeTrackerScale) {\n gazer._gazeTracker.scaling.x = hit.distance * multiplier;\n gazer._gazeTracker.scaling.y = hit.distance * multiplier;\n gazer._gazeTracker.scaling.z = hit.distance * multiplier;\n }\n const pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);\n // To avoid z-fighting\n const deltaFighting = 0.002;\n if (pickNormal) {\n const axis1 = Vector3.Cross(Axis.Y, pickNormal);\n const axis2 = Vector3.Cross(pickNormal, axis1);\n Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);\n }\n gazer._gazeTracker.position.copyFrom(hit.pickedPoint);\n if (gazer._gazeTracker.position.x < 0) {\n gazer._gazeTracker.position.x += deltaFighting;\n }\n else {\n gazer._gazeTracker.position.x -= deltaFighting;\n }\n if (gazer._gazeTracker.position.y < 0) {\n gazer._gazeTracker.position.y += deltaFighting;\n }\n else {\n gazer._gazeTracker.position.y -= deltaFighting;\n }\n if (gazer._gazeTracker.position.z < 0) {\n gazer._gazeTracker.position.z += deltaFighting;\n }\n else {\n gazer._gazeTracker.position.z -= deltaFighting;\n }\n }\n // Changing the size of the laser pointer based on the distance from the targetted point\n gazer._updatePointerDistance(hit.distance);\n }\n else {\n gazer._updatePointerDistance();\n gazer._gazeTracker.isVisible = false;\n }\n if (hit && hit.pickedMesh) {\n // The object selected is the floor, we're in a teleportation scenario\n if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {\n // Moving the teleportation area to this targetted point\n //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected\n if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {\n this._notifySelectedMeshUnselected(gazer._currentMeshSelected);\n }\n gazer._currentMeshSelected = null;\n if (gazer._teleportationRequestInitiated) {\n this._moveTeleportationSelectorTo(hit, gazer, ray);\n }\n return;\n }\n // If not, we're in a selection scenario\n //this._teleportationAllowed = false;\n if (hit.pickedMesh !== gazer._currentMeshSelected) {\n if (this.meshSelectionPredicate(hit.pickedMesh)) {\n this.onNewMeshPicked.notifyObservers(hit);\n gazer._currentMeshSelected = hit.pickedMesh;\n if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {\n this.changeGazeColor(this._pickedGazeColor);\n this.changeLaserColor(this._pickedLaserColor);\n gazer._isActionableMesh = true;\n }\n else {\n this.changeGazeColor(this._gazeColor);\n this.changeLaserColor(this._laserColor);\n gazer._isActionableMesh = false;\n }\n try {\n this.onNewMeshSelected.notifyObservers(hit.pickedMesh);\n const gazerAsControllerGazer = gazer;\n if (gazerAsControllerGazer.webVRController) {\n this.onMeshSelectedWithController.notifyObservers({ mesh: hit.pickedMesh, controller: gazerAsControllerGazer.webVRController });\n }\n }\n catch (err) {\n Logger.Warn(\"Error while raising onNewMeshSelected or onMeshSelectedWithController: \" + err);\n }\n }\n else {\n this._notifySelectedMeshUnselected(gazer._currentMeshSelected);\n gazer._currentMeshSelected = null;\n this.changeGazeColor(this._gazeColor);\n this.changeLaserColor(this._laserColor);\n }\n }\n }\n else {\n this._notifySelectedMeshUnselected(gazer._currentMeshSelected);\n gazer._currentMeshSelected = null;\n //this._teleportationAllowed = false;\n this.changeGazeColor(this._gazeColor);\n this.changeLaserColor(this._laserColor);\n }\n }\n _notifySelectedMeshUnselected(mesh) {\n if (mesh) {\n this.onSelectedMeshUnselected.notifyObservers(mesh);\n }\n }\n /**\n * Permanently set new colors for the laser pointer\n * @param color the new laser color\n * @param pickedColor the new laser color when picked mesh detected\n */\n setLaserColor(color, pickedColor = this._pickedLaserColor) {\n this._laserColor = color;\n this._pickedLaserColor = pickedColor;\n }\n /**\n * Set lighting enabled / disabled on the laser pointer of both controllers\n * @param enabled should the lighting be enabled on the laser pointer\n */\n setLaserLightingState(enabled = true) {\n if (this._leftController) {\n this._leftController._setLaserPointerLightingDisabled(!enabled);\n }\n if (this._rightController) {\n this._rightController._setLaserPointerLightingDisabled(!enabled);\n }\n }\n /**\n * Permanently set new colors for the gaze pointer\n * @param color the new gaze color\n * @param pickedColor the new gaze color when picked mesh detected\n */\n setGazeColor(color, pickedColor = this._pickedGazeColor) {\n this._gazeColor = color;\n this._pickedGazeColor = pickedColor;\n }\n /**\n * Sets the color of the laser ray from the vr controllers.\n * @param color new color for the ray.\n */\n changeLaserColor(color) {\n if (!this.updateControllerLaserColor) {\n return;\n }\n if (this._leftController) {\n this._leftController._setLaserPointerColor(color);\n }\n if (this._rightController) {\n this._rightController._setLaserPointerColor(color);\n }\n }\n /**\n * Sets the color of the ray from the vr headsets gaze.\n * @param color new color for the ray.\n */\n changeGazeColor(color) {\n if (!this.updateGazeTrackerColor) {\n return;\n }\n if (!this._cameraGazer._gazeTracker.material) {\n return;\n }\n this._cameraGazer._gazeTracker.material.emissiveColor = color;\n if (this._leftController) {\n this._leftController._gazeTracker.material.emissiveColor = color;\n }\n if (this._rightController) {\n this._rightController._gazeTracker.material.emissiveColor = color;\n }\n }\n /**\n * Exits VR and disposes of the vr experience helper\n */\n dispose() {\n if (this.isInVRMode) {\n this.exitVR();\n }\n if (this._postProcessMove) {\n this._postProcessMove.dispose();\n }\n if (this._webVRCamera) {\n this._webVRCamera.dispose();\n }\n if (this._vrDeviceOrientationCamera) {\n this._vrDeviceOrientationCamera.dispose();\n }\n if (!this._useCustomVRButton && this._btnVR && this._btnVR.parentNode) {\n document.body.removeChild(this._btnVR);\n }\n if (this._deviceOrientationCamera && this._scene.activeCamera != this._deviceOrientationCamera) {\n this._deviceOrientationCamera.dispose();\n }\n if (this._cameraGazer) {\n this._cameraGazer.dispose();\n }\n if (this._leftController) {\n this._leftController.dispose();\n }\n if (this._rightController) {\n this._rightController.dispose();\n }\n if (this._teleportationTarget) {\n this._teleportationTarget.dispose();\n }\n if (this.xr) {\n this.xr.dispose();\n }\n this._floorMeshesCollection.length = 0;\n document.removeEventListener(\"keydown\", this._onKeyDown);\n window.removeEventListener(\"vrdisplaypresentchange\", this._onVrDisplayPresentChangeBind);\n window.removeEventListener(\"resize\", this._onResize);\n document.removeEventListener(\"fullscreenchange\", this._onFullscreenChange);\n this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChangedBind);\n this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);\n this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);\n this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);\n this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);\n this._scene.unregisterBeforeRender(this._beforeRender);\n }\n /**\n * Gets the name of the VRExperienceHelper class\n * @returns \"VRExperienceHelper\"\n */\n getClassName() {\n return \"VRExperienceHelper\";\n }\n}\n/**\n * Time Constant Teleportation Mode\n */\nVRExperienceHelper.TELEPORTATIONMODE_CONSTANTTIME = 0;\n/**\n * Speed Constant Teleportation Mode\n */\nVRExperienceHelper.TELEPORTATIONMODE_CONSTANTSPEED = 1;\n//# sourceMappingURL=vrExperienceHelper.js.map","export * from \"./vrCameraMetrics.js\";\nexport * from \"./vrDeviceOrientationArcRotateCamera.js\";\nexport * from \"./vrDeviceOrientationFreeCamera.js\";\nexport * from \"./vrDeviceOrientationGamepadCamera.js\";\nexport * from \"./vrExperienceHelper.js\";\nexport * from \"./webVRCamera.js\";\n//# sourceMappingURL=index.js.map","export * from \"./stereoscopicAnaglyphRigMode.js\";\nexport * from \"./stereoscopicRigMode.js\";\nexport * from \"./vrRigMode.js\";\nexport * from \"./webVRRigMode.js\";\n//# sourceMappingURL=index.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./Inputs/index.js\";\nexport * from \"./cameraInputsManager.js\";\nexport * from \"./camera.js\";\nexport * from \"./targetCamera.js\";\nexport * from \"./freeCamera.js\";\nexport * from \"./freeCameraInputsManager.js\";\nexport * from \"./touchCamera.js\";\nexport * from \"./arcRotateCamera.js\";\nexport * from \"./arcRotateCameraInputsManager.js\";\nexport * from \"./deviceOrientationCamera.js\";\nexport * from \"./flyCamera.js\";\nexport * from \"./flyCameraInputsManager.js\";\nexport * from \"./followCamera.js\";\nexport * from \"./followCameraInputsManager.js\";\nexport * from \"./gamepadCamera.js\";\nexport * from \"./Stereoscopic/index.js\";\nexport * from \"./universalCamera.js\";\nexport * from \"./virtualJoysticksCamera.js\";\nexport * from \"./VR/index.js\";\nexport * from \"./RigModes/index.js\";\n//# sourceMappingURL=index.js.map","import { Vector3 } from \"../Maths/math.vector.js\";\nimport { Plane } from \"../Maths/math.plane.js\";\nconst intersectBoxAASphere = (boxMin, boxMax, sphereCenter, sphereRadius) => {\n if (boxMin.x > sphereCenter.x + sphereRadius) {\n return false;\n }\n if (sphereCenter.x - sphereRadius > boxMax.x) {\n return false;\n }\n if (boxMin.y > sphereCenter.y + sphereRadius) {\n return false;\n }\n if (sphereCenter.y - sphereRadius > boxMax.y) {\n return false;\n }\n if (boxMin.z > sphereCenter.z + sphereRadius) {\n return false;\n }\n if (sphereCenter.z - sphereRadius > boxMax.z) {\n return false;\n }\n return true;\n};\nconst getLowestRoot = (function () {\n const result = { root: 0, found: false };\n return function (a, b, c, maxR) {\n result.root = 0;\n result.found = false;\n const determinant = b * b - 4.0 * a * c;\n if (determinant < 0) {\n return result;\n }\n const sqrtD = Math.sqrt(determinant);\n let r1 = (-b - sqrtD) / (2.0 * a);\n let r2 = (-b + sqrtD) / (2.0 * a);\n if (r1 > r2) {\n const temp = r2;\n r2 = r1;\n r1 = temp;\n }\n if (r1 > 0 && r1 < maxR) {\n result.root = r1;\n result.found = true;\n return result;\n }\n if (r2 > 0 && r2 < maxR) {\n result.root = r2;\n result.found = true;\n return result;\n }\n return result;\n };\n})();\n/** @internal */\nexport class Collider {\n constructor() {\n // Implementation of the \"Improved Collision detection and Response\" algorithm proposed by Kasper Fauerby\n // https://www.peroxide.dk/papers/collision/collision.pdf\n this._collisionPoint = Vector3.Zero();\n this._planeIntersectionPoint = Vector3.Zero();\n this._tempVector = Vector3.Zero();\n this._tempVector2 = Vector3.Zero();\n this._tempVector3 = Vector3.Zero();\n this._tempVector4 = Vector3.Zero();\n this._edge = Vector3.Zero();\n this._baseToVertex = Vector3.Zero();\n this._destinationPoint = Vector3.Zero();\n this._slidePlaneNormal = Vector3.Zero();\n this._displacementVector = Vector3.Zero();\n /** @internal */\n this._radius = Vector3.One();\n /** @internal */\n this._retry = 0;\n /** @internal */\n this._basePointWorld = Vector3.Zero();\n this._velocityWorld = Vector3.Zero();\n this._normalizedVelocity = Vector3.Zero();\n this._collisionMask = -1;\n }\n get collisionMask() {\n return this._collisionMask;\n }\n set collisionMask(mask) {\n this._collisionMask = !isNaN(mask) ? mask : -1;\n }\n /**\n * Gets the plane normal used to compute the sliding response (in local space)\n */\n get slidePlaneNormal() {\n return this._slidePlaneNormal;\n }\n // Methods\n /**\n * @internal\n */\n _initialize(source, dir, e) {\n this._velocity = dir;\n this._velocitySquaredLength = this._velocity.lengthSquared();\n const len = Math.sqrt(this._velocitySquaredLength);\n if (len === 0 || len === 1.0) {\n this._normalizedVelocity.copyFromFloats(dir._x, dir._y, dir._z);\n }\n else {\n dir.scaleToRef(1.0 / len, this._normalizedVelocity);\n }\n this._basePoint = source;\n source.multiplyToRef(this._radius, this._basePointWorld);\n dir.multiplyToRef(this._radius, this._velocityWorld);\n this._velocityWorldLength = this._velocityWorld.length();\n this._epsilon = e;\n this.collisionFound = false;\n }\n /**\n * @internal\n */\n _checkPointInTriangle(point, pa, pb, pc, n) {\n pa.subtractToRef(point, this._tempVector);\n pb.subtractToRef(point, this._tempVector2);\n Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);\n let d = Vector3.Dot(this._tempVector4, n);\n if (d < 0) {\n return false;\n }\n pc.subtractToRef(point, this._tempVector3);\n Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);\n d = Vector3.Dot(this._tempVector4, n);\n if (d < 0) {\n return false;\n }\n Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);\n d = Vector3.Dot(this._tempVector4, n);\n return d >= 0;\n }\n /**\n * @internal\n */\n _canDoCollision(sphereCenter, sphereRadius, vecMin, vecMax) {\n const distance = Vector3.Distance(this._basePointWorld, sphereCenter);\n const max = Math.max(this._radius.x, this._radius.y, this._radius.z);\n if (distance > this._velocityWorldLength + max + sphereRadius) {\n return false;\n }\n if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max)) {\n return false;\n }\n return true;\n }\n /**\n * @internal\n */\n _testTriangle(faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial, hostMesh) {\n let t0;\n let embeddedInPlane = false;\n //defensive programming, actually not needed.\n if (!trianglePlaneArray) {\n trianglePlaneArray = [];\n }\n if (!trianglePlaneArray[faceIndex]) {\n trianglePlaneArray[faceIndex] = new Plane(0, 0, 0, 0);\n trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);\n }\n const trianglePlane = trianglePlaneArray[faceIndex];\n if (!hasMaterial && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0)) {\n return;\n }\n const signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);\n const normalDotVelocity = Vector3.Dot(trianglePlane.normal, this._velocity);\n // if DoubleSidedCheck is false(default), a double sided face will be consided 2 times.\n // if true, it discard the faces having normal not facing velocity\n if (Collider.DoubleSidedCheck && normalDotVelocity > 0.0001) {\n return;\n }\n if (normalDotVelocity == 0) {\n if (Math.abs(signedDistToTrianglePlane) >= 1.0) {\n return;\n }\n embeddedInPlane = true;\n t0 = 0;\n }\n else {\n t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;\n let t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;\n if (t0 > t1) {\n const temp = t1;\n t1 = t0;\n t0 = temp;\n }\n if (t0 > 1.0 || t1 < 0.0) {\n return;\n }\n if (t0 < 0) {\n t0 = 0;\n }\n if (t0 > 1.0) {\n t0 = 1.0;\n }\n }\n this._collisionPoint.copyFromFloats(0, 0, 0);\n let found = false;\n let t = 1.0;\n if (!embeddedInPlane) {\n this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);\n this._velocity.scaleToRef(t0, this._tempVector);\n this._planeIntersectionPoint.addInPlace(this._tempVector);\n if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {\n found = true;\n t = t0;\n this._collisionPoint.copyFrom(this._planeIntersectionPoint);\n }\n }\n if (!found) {\n let a = this._velocitySquaredLength;\n this._basePoint.subtractToRef(p1, this._tempVector);\n let b = 2.0 * Vector3.Dot(this._velocity, this._tempVector);\n let c = this._tempVector.lengthSquared() - 1.0;\n let lowestRoot = getLowestRoot(a, b, c, t);\n if (lowestRoot.found) {\n t = lowestRoot.root;\n found = true;\n this._collisionPoint.copyFrom(p1);\n }\n this._basePoint.subtractToRef(p2, this._tempVector);\n b = 2.0 * Vector3.Dot(this._velocity, this._tempVector);\n c = this._tempVector.lengthSquared() - 1.0;\n lowestRoot = getLowestRoot(a, b, c, t);\n if (lowestRoot.found) {\n t = lowestRoot.root;\n found = true;\n this._collisionPoint.copyFrom(p2);\n }\n this._basePoint.subtractToRef(p3, this._tempVector);\n b = 2.0 * Vector3.Dot(this._velocity, this._tempVector);\n c = this._tempVector.lengthSquared() - 1.0;\n lowestRoot = getLowestRoot(a, b, c, t);\n if (lowestRoot.found) {\n t = lowestRoot.root;\n found = true;\n this._collisionPoint.copyFrom(p3);\n }\n p2.subtractToRef(p1, this._edge);\n p1.subtractToRef(this._basePoint, this._baseToVertex);\n let edgeSquaredLength = this._edge.lengthSquared();\n let edgeDotVelocity = Vector3.Dot(this._edge, this._velocity);\n let edgeDotBaseToVertex = Vector3.Dot(this._edge, this._baseToVertex);\n a = edgeSquaredLength * -this._velocitySquaredLength + edgeDotVelocity * edgeDotVelocity;\n b = 2 * (edgeSquaredLength * Vector3.Dot(this._velocity, this._baseToVertex) - edgeDotVelocity * edgeDotBaseToVertex);\n c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;\n lowestRoot = getLowestRoot(a, b, c, t);\n if (lowestRoot.found) {\n const f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;\n if (f >= 0.0 && f <= 1.0) {\n t = lowestRoot.root;\n found = true;\n this._edge.scaleInPlace(f);\n p1.addToRef(this._edge, this._collisionPoint);\n }\n }\n p3.subtractToRef(p2, this._edge);\n p2.subtractToRef(this._basePoint, this._baseToVertex);\n edgeSquaredLength = this._edge.lengthSquared();\n edgeDotVelocity = Vector3.Dot(this._edge, this._velocity);\n edgeDotBaseToVertex = Vector3.Dot(this._edge, this._baseToVertex);\n a = edgeSquaredLength * -this._velocitySquaredLength + edgeDotVelocity * edgeDotVelocity;\n b = 2 * (edgeSquaredLength * Vector3.Dot(this._velocity, this._baseToVertex) - edgeDotVelocity * edgeDotBaseToVertex);\n c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;\n lowestRoot = getLowestRoot(a, b, c, t);\n if (lowestRoot.found) {\n const f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;\n if (f >= 0.0 && f <= 1.0) {\n t = lowestRoot.root;\n found = true;\n this._edge.scaleInPlace(f);\n p2.addToRef(this._edge, this._collisionPoint);\n }\n }\n p1.subtractToRef(p3, this._edge);\n p3.subtractToRef(this._basePoint, this._baseToVertex);\n edgeSquaredLength = this._edge.lengthSquared();\n edgeDotVelocity = Vector3.Dot(this._edge, this._velocity);\n edgeDotBaseToVertex = Vector3.Dot(this._edge, this._baseToVertex);\n a = edgeSquaredLength * -this._velocitySquaredLength + edgeDotVelocity * edgeDotVelocity;\n b = 2 * (edgeSquaredLength * Vector3.Dot(this._velocity, this._baseToVertex) - edgeDotVelocity * edgeDotBaseToVertex);\n c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;\n lowestRoot = getLowestRoot(a, b, c, t);\n if (lowestRoot.found) {\n const f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;\n if (f >= 0.0 && f <= 1.0) {\n t = lowestRoot.root;\n found = true;\n this._edge.scaleInPlace(f);\n p3.addToRef(this._edge, this._collisionPoint);\n }\n }\n }\n if (found) {\n const distToCollisionSquared = t * t * this._velocitySquaredLength;\n if (!this.collisionFound || distToCollisionSquared < this._nearestDistanceSquared) {\n // if collisionResponse is false, collision is not found but the collidedMesh is set anyway.\n // onCollide observable are triggered if collideMesh is set\n // this allow trigger volumes to be created.\n if (hostMesh.collisionResponse) {\n if (!this.intersectionPoint) {\n this.intersectionPoint = this._collisionPoint.clone();\n }\n else {\n this.intersectionPoint.copyFrom(this._collisionPoint);\n }\n this._nearestDistanceSquared = distToCollisionSquared;\n this._nearestDistance = Math.sqrt(distToCollisionSquared);\n this.collisionFound = true;\n }\n this.collidedMesh = hostMesh;\n }\n }\n }\n /**\n * @internal\n */\n _collide(trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial, hostMesh, invertTriangles, triangleStrip = false) {\n if (triangleStrip) {\n if (!indices || indices.length === 0) {\n for (let i = 0; i < pts.length - 2; i += 1) {\n const p1 = pts[i];\n const p2 = pts[i + 1];\n const p3 = pts[i + 2];\n // stay defensive and don't check against undefined positions.\n if (!p1 || !p2 || !p3) {\n continue;\n }\n // Handles strip faces one on two is reversed\n if ((invertTriangles ? 1 : 0) ^ i % 2) {\n this._testTriangle(i, trianglePlaneArray, p1, p2, p3, hasMaterial, hostMesh);\n }\n else {\n this._testTriangle(i, trianglePlaneArray, p2, p1, p3, hasMaterial, hostMesh);\n }\n }\n }\n else {\n for (let i = indexStart; i < indexEnd - 2; i += 1) {\n const indexA = indices[i];\n const indexB = indices[i + 1];\n const indexC = indices[i + 2];\n if (indexC === 0xffffffff) {\n i += 2;\n continue;\n }\n const p1 = pts[indexA];\n const p2 = pts[indexB];\n const p3 = pts[indexC];\n // stay defensive and don't check against undefined positions.\n if (!p1 || !p2 || !p3) {\n continue;\n }\n // Handles strip faces one on two is reversed\n if ((invertTriangles ? 1 : 0) ^ i % 2) {\n this._testTriangle(i, trianglePlaneArray, p1, p2, p3, hasMaterial, hostMesh);\n }\n else {\n this._testTriangle(i, trianglePlaneArray, p2, p1, p3, hasMaterial, hostMesh);\n }\n }\n }\n }\n else if (!indices || indices.length === 0) {\n for (let i = 0; i < pts.length; i += 3) {\n const p1 = pts[i];\n const p2 = pts[i + 1];\n const p3 = pts[i + 2];\n if (invertTriangles) {\n this._testTriangle(i, trianglePlaneArray, p1, p2, p3, hasMaterial, hostMesh);\n }\n else {\n this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial, hostMesh);\n }\n }\n }\n else {\n for (let i = indexStart; i < indexEnd; i += 3) {\n const p1 = pts[indices[i] - decal];\n const p2 = pts[indices[i + 1] - decal];\n const p3 = pts[indices[i + 2] - decal];\n if (invertTriangles) {\n this._testTriangle(i, trianglePlaneArray, p1, p2, p3, hasMaterial, hostMesh);\n }\n else {\n this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial, hostMesh);\n }\n }\n }\n }\n /**\n * @internal\n */\n _getResponse(pos, vel) {\n pos.addToRef(vel, this._destinationPoint);\n vel.scaleInPlace(this._nearestDistance / vel.length());\n this._basePoint.addToRef(vel, pos);\n pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);\n this._slidePlaneNormal.normalize();\n this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);\n pos.addInPlace(this._displacementVector);\n this.intersectionPoint.addInPlace(this._displacementVector);\n this._slidePlaneNormal.scaleInPlace(Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));\n this._destinationPoint.subtractInPlace(this._slidePlaneNormal);\n this._destinationPoint.subtractToRef(this.intersectionPoint, vel);\n }\n}\n/**\n * If true, it check for double sided faces and only returns 1 collision instead of 2\n */\nCollider.DoubleSidedCheck = false;\n//# sourceMappingURL=collider.js.map","import { Scene } from \"../scene.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { Collider } from \"./collider.js\";\n/** @internal */\nexport class DefaultCollisionCoordinator {\n constructor() {\n this._scaledPosition = Vector3.Zero();\n this._scaledVelocity = Vector3.Zero();\n this._finalPosition = Vector3.Zero();\n }\n getNewPosition(position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {\n position.divideToRef(collider._radius, this._scaledPosition);\n displacement.divideToRef(collider._radius, this._scaledVelocity);\n collider.collidedMesh = null;\n collider._retry = 0;\n collider._initialVelocity = this._scaledVelocity;\n collider._initialPosition = this._scaledPosition;\n this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);\n this._finalPosition.multiplyInPlace(collider._radius);\n //run the callback\n onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);\n }\n createCollider() {\n return new Collider();\n }\n init(scene) {\n this._scene = scene;\n }\n _collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh = null) {\n const closeDistance = Engine.CollisionsEpsilon * 10.0;\n if (collider._retry >= maximumRetry) {\n finalPosition.copyFrom(position);\n return;\n }\n // Check if this is a mesh else camera or -1\n const collisionMask = excludedMesh ? excludedMesh.collisionMask : collider.collisionMask;\n collider._initialize(position, velocity, closeDistance);\n // Check if collision detection should happen against specified list of meshes or,\n // if not specified, against all meshes in the scene\n const meshes = (excludedMesh && excludedMesh.surroundingMeshes) || this._scene.meshes;\n for (let index = 0; index < meshes.length; index++) {\n const mesh = meshes[index];\n if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && (collisionMask & mesh.collisionGroup) !== 0) {\n mesh._checkCollision(collider);\n }\n }\n if (!collider.collisionFound) {\n position.addToRef(velocity, finalPosition);\n return;\n }\n if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {\n collider._getResponse(position, velocity);\n }\n if (velocity.length() <= closeDistance) {\n finalPosition.copyFrom(position);\n return;\n }\n collider._retry++;\n this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);\n }\n}\nScene.CollisionCoordinatorFactory = () => {\n return new DefaultCollisionCoordinator();\n};\n//# sourceMappingURL=collisionCoordinator.js.map","export * from \"./collider.js\";\nexport * from \"./collisionCoordinator.js\";\nexport * from \"./pickingInfo.js\";\nexport * from \"./intersectionInfo.js\";\nexport * from \"./meshCollisionData.js\";\n//# sourceMappingURL=index.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { GetDOMTextContent, IsWindowObjectExist } from \"../Misc/domManagement.js\";\nimport { ShaderProcessor } from \"../Engines/Processors/shaderProcessor.js\";\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport { ShaderLanguage } from \"../Materials/shaderLanguage.js\";\n/**\n * Effect wrapping a compute shader and let execute (dispatch) the shader\n */\nexport class ComputeEffect {\n /**\n * Creates a compute effect that can be used to execute a compute shader\n * @param baseName Name of the effect\n * @param options Set of all options to create the effect\n * @param engine The engine the effect is created for\n * @param key Effect Key identifying uniquely compiled shader variants\n */\n constructor(baseName, options, engine, key = \"\") {\n var _a, _b;\n /**\n * Name of the effect.\n */\n this.name = null;\n /**\n * String container all the define statements that should be set on the shader.\n */\n this.defines = \"\";\n /**\n * Callback that will be called when the shader is compiled.\n */\n this.onCompiled = null;\n /**\n * Callback that will be called if an error occurs during shader compilation.\n */\n this.onError = null;\n /**\n * Unique ID of the effect.\n */\n this.uniqueId = 0;\n /**\n * Observable that will be called when the shader is compiled.\n * It is recommended to use executeWhenCompile() or to make sure that scene.isReady() is called to get this observable raised.\n */\n this.onCompileObservable = new Observable();\n /**\n * Observable that will be called if an error occurs during shader compilation.\n */\n this.onErrorObservable = new Observable();\n /**\n * Observable that will be called when effect is bound.\n */\n this.onBindObservable = new Observable();\n /**\n * @internal\n * Specifies if the effect was previously ready\n */\n this._wasPreviouslyReady = false;\n this._isReady = false;\n this._compilationError = \"\";\n /** @internal */\n this._key = \"\";\n this._computeSourceCodeOverride = \"\";\n /** @internal */\n this._pipelineContext = null;\n /** @internal */\n this._computeSourceCode = \"\";\n this._rawComputeSourceCode = \"\";\n this._shaderLanguage = ShaderLanguage.WGSL;\n this.name = baseName;\n this._key = key;\n this._engine = engine;\n this.uniqueId = ComputeEffect._UniqueIdSeed++;\n this.defines = (_a = options.defines) !== null && _a !== void 0 ? _a : \"\";\n this.onError = options.onError;\n this.onCompiled = options.onCompiled;\n this._entryPoint = (_b = options.entryPoint) !== null && _b !== void 0 ? _b : \"main\";\n this._shaderStore = ShaderStore.GetShadersStore(this._shaderLanguage);\n this._shaderRepository = ShaderStore.GetShadersRepository(this._shaderLanguage);\n this._includeShaderStore = ShaderStore.GetIncludesShadersStore(this._shaderLanguage);\n let computeSource;\n const hostDocument = IsWindowObjectExist() ? this._engine.getHostDocument() : null;\n if (baseName.computeSource) {\n computeSource = \"source:\" + baseName.computeSource;\n }\n else if (baseName.computeElement) {\n computeSource = hostDocument ? hostDocument.getElementById(baseName.computeElement) : null;\n if (!computeSource) {\n computeSource = baseName.computeElement;\n }\n }\n else {\n computeSource = baseName.compute || baseName;\n }\n const processorOptions = {\n defines: this.defines.split(\"\\n\"),\n indexParameters: undefined,\n isFragment: false,\n shouldUseHighPrecisionShader: false,\n processor: null,\n supportsUniformBuffers: this._engine.supportsUniformBuffers,\n shadersRepository: this._shaderRepository,\n includesShadersStore: this._includeShaderStore,\n version: (this._engine.version * 100).toString(),\n platformName: this._engine.shaderPlatformName,\n processingContext: null,\n isNDCHalfZRange: this._engine.isNDCHalfZRange,\n useReverseDepthBuffer: this._engine.useReverseDepthBuffer,\n };\n this._loadShader(computeSource, \"Compute\", \"\", (computeCode) => {\n ShaderProcessor.Initialize(processorOptions);\n ShaderProcessor.PreProcess(computeCode, processorOptions, (migratedCommputeCode) => {\n this._rawComputeSourceCode = computeCode;\n if (options.processFinalCode) {\n migratedCommputeCode = options.processFinalCode(migratedCommputeCode);\n }\n const finalShaders = ShaderProcessor.Finalize(migratedCommputeCode, \"\", processorOptions);\n this._useFinalCode(finalShaders.vertexCode, baseName);\n }, this._engine);\n });\n }\n _useFinalCode(migratedCommputeCode, baseName) {\n if (baseName) {\n const compute = baseName.computeElement || baseName.compute || baseName.spectorName || baseName;\n this._computeSourceCode = \"//#define SHADER_NAME compute:\" + compute + \"\\n\" + migratedCommputeCode;\n }\n else {\n this._computeSourceCode = migratedCommputeCode;\n }\n this._prepareEffect();\n }\n /**\n * Unique key for this effect\n */\n get key() {\n return this._key;\n }\n /**\n * If the effect has been compiled and prepared.\n * @returns if the effect is compiled and prepared.\n */\n isReady() {\n try {\n return this._isReadyInternal();\n }\n catch (_a) {\n return false;\n }\n }\n _isReadyInternal() {\n if (this._isReady) {\n return true;\n }\n if (this._pipelineContext) {\n return this._pipelineContext.isReady;\n }\n return false;\n }\n /**\n * The engine the effect was initialized with.\n * @returns the engine.\n */\n getEngine() {\n return this._engine;\n }\n /**\n * The pipeline context for this effect\n * @returns the associated pipeline context\n */\n getPipelineContext() {\n return this._pipelineContext;\n }\n /**\n * The error from the last compilation.\n * @returns the error string.\n */\n getCompilationError() {\n return this._compilationError;\n }\n /**\n * Adds a callback to the onCompiled observable and call the callback immediately if already ready.\n * @param func The callback to be used.\n */\n executeWhenCompiled(func) {\n if (this.isReady()) {\n func(this);\n return;\n }\n this.onCompileObservable.add((effect) => {\n func(effect);\n });\n if (!this._pipelineContext || this._pipelineContext.isAsync) {\n setTimeout(() => {\n this._checkIsReady(null);\n }, 16);\n }\n }\n _checkIsReady(previousPipelineContext) {\n try {\n if (this._isReadyInternal()) {\n return;\n }\n }\n catch (e) {\n this._processCompilationErrors(e, previousPipelineContext);\n return;\n }\n setTimeout(() => {\n this._checkIsReady(previousPipelineContext);\n }, 16);\n }\n _loadShader(shader, key, optionalKey, callback) {\n if (typeof HTMLElement !== \"undefined\") {\n // DOM element ?\n if (shader instanceof HTMLElement) {\n const shaderCode = GetDOMTextContent(shader);\n callback(shaderCode);\n return;\n }\n }\n // Direct source ?\n if (shader.substr(0, 7) === \"source:\") {\n callback(shader.substr(7));\n return;\n }\n // Base64 encoded ?\n if (shader.substr(0, 7) === \"base64:\") {\n const shaderBinary = window.atob(shader.substr(7));\n callback(shaderBinary);\n return;\n }\n // Is in local store ?\n if (this._shaderStore[shader + key + \"Shader\"]) {\n callback(this._shaderStore[shader + key + \"Shader\"]);\n return;\n }\n if (optionalKey && this._shaderStore[shader + optionalKey + \"Shader\"]) {\n callback(this._shaderStore[shader + optionalKey + \"Shader\"]);\n return;\n }\n let shaderUrl;\n if (shader[0] === \".\" || shader[0] === \"/\" || shader.indexOf(\"http\") > -1) {\n shaderUrl = shader;\n }\n else {\n shaderUrl = this._shaderRepository + shader;\n }\n this._engine._loadFile(shaderUrl + \".\" + key.toLowerCase() + \".fx\", callback);\n }\n /**\n * Gets the compute shader source code of this effect\n */\n get computeSourceCode() {\n var _a, _b;\n return this._computeSourceCodeOverride ? this._computeSourceCodeOverride : (_b = (_a = this._pipelineContext) === null || _a === void 0 ? void 0 : _a._getComputeShaderCode()) !== null && _b !== void 0 ? _b : this._computeSourceCode;\n }\n /**\n * Gets the compute shader source code before it has been processed by the preprocessor\n */\n get rawComputeSourceCode() {\n return this._rawComputeSourceCode;\n }\n /**\n * Prepares the effect\n * @internal\n */\n _prepareEffect() {\n const defines = this.defines;\n const previousPipelineContext = this._pipelineContext;\n this._isReady = false;\n try {\n const engine = this._engine;\n this._pipelineContext = engine.createComputePipelineContext();\n this._pipelineContext._name = this._key;\n engine._prepareComputePipelineContext(this._pipelineContext, this._computeSourceCodeOverride ? this._computeSourceCodeOverride : this._computeSourceCode, this._rawComputeSourceCode, this._computeSourceCodeOverride ? null : defines, this._entryPoint);\n engine._executeWhenComputeStateIsCompiled(this._pipelineContext, () => {\n this._compilationError = \"\";\n this._isReady = true;\n if (this.onCompiled) {\n this.onCompiled(this);\n }\n this.onCompileObservable.notifyObservers(this);\n this.onCompileObservable.clear();\n if (previousPipelineContext) {\n this.getEngine()._deleteComputePipelineContext(previousPipelineContext);\n }\n });\n if (this._pipelineContext.isAsync) {\n this._checkIsReady(previousPipelineContext);\n }\n }\n catch (e) {\n this._processCompilationErrors(e, previousPipelineContext);\n }\n }\n _getShaderCodeAndErrorLine(code, error) {\n const regexp = /COMPUTE SHADER ERROR: 0:(\\d+?):/;\n let errorLine = null;\n if (error && code) {\n const res = error.match(regexp);\n if (res && res.length === 2) {\n const lineNumber = parseInt(res[1]);\n const lines = code.split(\"\\n\", -1);\n if (lines.length >= lineNumber) {\n errorLine = `Offending line [${lineNumber}] in compute code: ${lines[lineNumber - 1]}`;\n }\n }\n }\n return [code, errorLine];\n }\n _processCompilationErrors(e, previousPipelineContext = null) {\n var _a;\n this._compilationError = e.message;\n // Let's go through fallbacks then\n Logger.Error(\"Unable to compile compute effect:\");\n Logger.Error(\"Defines:\\r\\n\" + this.defines);\n if (ComputeEffect.LogShaderCodeOnCompilationError) {\n let lineErrorVertex = null, code = null;\n if ((_a = this._pipelineContext) === null || _a === void 0 ? void 0 : _a._getComputeShaderCode()) {\n [code, lineErrorVertex] = this._getShaderCodeAndErrorLine(this._pipelineContext._getComputeShaderCode(), this._compilationError);\n if (code) {\n Logger.Error(\"Compute code:\");\n Logger.Error(code);\n }\n }\n if (lineErrorVertex) {\n Logger.Error(lineErrorVertex);\n }\n }\n Logger.Error(\"Error: \" + this._compilationError);\n if (previousPipelineContext) {\n this._pipelineContext = previousPipelineContext;\n this._isReady = true;\n if (this.onError) {\n this.onError(this, this._compilationError);\n }\n this.onErrorObservable.notifyObservers(this);\n }\n }\n /**\n * Release all associated resources.\n **/\n dispose() {\n if (this._pipelineContext) {\n this._pipelineContext.dispose();\n }\n this._engine._releaseComputeEffect(this);\n }\n /**\n * This function will add a new compute shader to the shader store\n * @param name the name of the shader\n * @param computeShader compute shader content\n */\n static RegisterShader(name, computeShader) {\n ShaderStore.GetShadersStore(ShaderLanguage.WGSL)[`${name}ComputeShader`] = computeShader;\n }\n}\nComputeEffect._UniqueIdSeed = 0;\n/**\n * Enable logging of the shader code when a compilation error occurs\n */\nComputeEffect.LogShaderCodeOnCompilationError = true;\n//# sourceMappingURL=computeEffect.js.map","import { ThinEngine } from \"../../Engines/thinEngine.js\";\n/** @internal */\nexport var ComputeBindingType;\n(function (ComputeBindingType) {\n ComputeBindingType[ComputeBindingType[\"Texture\"] = 0] = \"Texture\";\n ComputeBindingType[ComputeBindingType[\"StorageTexture\"] = 1] = \"StorageTexture\";\n ComputeBindingType[ComputeBindingType[\"UniformBuffer\"] = 2] = \"UniformBuffer\";\n ComputeBindingType[ComputeBindingType[\"StorageBuffer\"] = 3] = \"StorageBuffer\";\n ComputeBindingType[ComputeBindingType[\"TextureWithoutSampler\"] = 4] = \"TextureWithoutSampler\";\n ComputeBindingType[ComputeBindingType[\"Sampler\"] = 5] = \"Sampler\";\n})(ComputeBindingType || (ComputeBindingType = {}));\nThinEngine.prototype.createComputeEffect = function (baseName, options) {\n throw new Error(\"createComputeEffect: This engine does not support compute shaders!\");\n};\nThinEngine.prototype.createComputePipelineContext = function () {\n throw new Error(\"createComputePipelineContext: This engine does not support compute shaders!\");\n};\nThinEngine.prototype.createComputeContext = function () {\n return undefined;\n};\nThinEngine.prototype.computeDispatch = function (effect, context, bindings, x, y, z, bindingsMapping) {\n throw new Error(\"computeDispatch: This engine does not support compute shaders!\");\n};\nThinEngine.prototype.areAllComputeEffectsReady = function () {\n return true;\n};\nThinEngine.prototype.releaseComputeEffects = function () { };\nThinEngine.prototype._prepareComputePipelineContext = function (pipelineContext, computeSourceCode, rawComputeSourceCode, defines, entryPoint) { };\nThinEngine.prototype._rebuildComputeEffects = function () { };\nThinEngine.prototype._executeWhenComputeStateIsCompiled = function (pipelineContext, action) {\n action();\n};\nThinEngine.prototype._releaseComputeEffect = function (effect) { };\nThinEngine.prototype._deleteComputePipelineContext = function (pipelineContext) { };\n//# sourceMappingURL=engine.computeShader.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { SerializationHelper, serialize } from \"../Misc/decorators.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\nimport { ComputeBindingType } from \"../Engines/Extensions/engine.computeShader.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { UniqueIdGenerator } from \"../Misc/uniqueIdGenerator.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { TextureSampler } from \"../Materials/Textures/textureSampler.js\";\n/**\n * The ComputeShader object lets you execute a compute shader on your GPU (if supported by the engine)\n */\nexport class ComputeShader {\n /**\n * The options used to create the shader\n */\n get options() {\n return this._options;\n }\n /**\n * The shaderPath used to create the shader\n */\n get shaderPath() {\n return this._shaderPath;\n }\n /**\n * Instantiates a new compute shader.\n * @param name Defines the name of the compute shader in the scene\n * @param engine Defines the engine the compute shader belongs to\n * @param shaderPath Defines the route to the shader code in one of three ways:\n * * object: \\{ compute: \"custom\" \\}, used with ShaderStore.ShadersStoreWGSL[\"customComputeShader\"]\n * * object: \\{ computeElement: \"HTMLElementId\" \\}, used with shader code in script tags\n * * object: \\{ computeSource: \"compute shader code string\" \\}, where the string contains the shader code\n * * string: try first to find the code in ShaderStore.ShadersStoreWGSL[shaderPath + \"ComputeShader\"]. If not, assumes it is a file with name shaderPath.compute.fx in index.html folder.\n * @param options Define the options used to create the shader\n */\n constructor(name, engine, shaderPath, options = {}) {\n this._bindings = {};\n this._samplers = {};\n this._contextIsDirty = false;\n /**\n * Callback triggered when the shader is compiled\n */\n this.onCompiled = null;\n /**\n * Callback triggered when an error occurs\n */\n this.onError = null;\n this.name = name;\n this._engine = engine;\n this.uniqueId = UniqueIdGenerator.UniqueId;\n if (!this._engine.getCaps().supportComputeShaders) {\n Logger.Error(\"This engine does not support compute shaders!\");\n return;\n }\n if (!options.bindingsMapping) {\n Logger.Error(\"You must provide the binding mappings as browsers don't support reflection for wgsl shaders yet!\");\n return;\n }\n this._context = engine.createComputeContext();\n this._shaderPath = shaderPath;\n this._options = Object.assign({ bindingsMapping: {}, defines: [] }, options);\n }\n /**\n * Gets the current class name of the material e.g. \"ComputeShader\"\n * Mainly use in serialization.\n * @returns the class name\n */\n getClassName() {\n return \"ComputeShader\";\n }\n /**\n * Binds a texture to the shader\n * @param name Binding name of the texture\n * @param texture Texture to bind\n * @param bindSampler Bind the sampler corresponding to the texture (default: true). The sampler will be bound just before the binding index of the texture\n */\n setTexture(name, texture, bindSampler = true) {\n const current = this._bindings[name];\n this._bindings[name] = {\n type: bindSampler ? ComputeBindingType.Texture : ComputeBindingType.TextureWithoutSampler,\n object: texture,\n indexInGroupEntries: current === null || current === void 0 ? void 0 : current.indexInGroupEntries,\n };\n this._contextIsDirty || (this._contextIsDirty = !current || current.object !== texture || current.type !== this._bindings[name].type);\n }\n /**\n * Binds a storage texture to the shader\n * @param name Binding name of the texture\n * @param texture Texture to bind\n */\n setStorageTexture(name, texture) {\n const current = this._bindings[name];\n this._contextIsDirty || (this._contextIsDirty = !current || current.object !== texture);\n this._bindings[name] = {\n type: ComputeBindingType.StorageTexture,\n object: texture,\n indexInGroupEntries: current === null || current === void 0 ? void 0 : current.indexInGroupEntries,\n };\n }\n /**\n * Binds a uniform buffer to the shader\n * @param name Binding name of the buffer\n * @param buffer Buffer to bind\n */\n setUniformBuffer(name, buffer) {\n const current = this._bindings[name];\n this._contextIsDirty || (this._contextIsDirty = !current || current.object !== buffer);\n this._bindings[name] = {\n type: ComputeBindingType.UniformBuffer,\n object: buffer,\n indexInGroupEntries: current === null || current === void 0 ? void 0 : current.indexInGroupEntries,\n };\n }\n /**\n * Binds a storage buffer to the shader\n * @param name Binding name of the buffer\n * @param buffer Buffer to bind\n */\n setStorageBuffer(name, buffer) {\n const current = this._bindings[name];\n this._contextIsDirty || (this._contextIsDirty = !current || current.object !== buffer);\n this._bindings[name] = {\n type: ComputeBindingType.StorageBuffer,\n object: buffer,\n indexInGroupEntries: current === null || current === void 0 ? void 0 : current.indexInGroupEntries,\n };\n }\n /**\n * Binds a texture sampler to the shader\n * @param name Binding name of the sampler\n * @param sampler Sampler to bind\n */\n setTextureSampler(name, sampler) {\n const current = this._bindings[name];\n this._contextIsDirty || (this._contextIsDirty = !current || !sampler.compareSampler(current.object));\n this._bindings[name] = {\n type: ComputeBindingType.Sampler,\n object: sampler,\n indexInGroupEntries: current === null || current === void 0 ? void 0 : current.indexInGroupEntries,\n };\n }\n /**\n * Specifies that the compute shader is ready to be executed (the compute effect and all the resources are ready)\n * @returns true if the compute shader is ready to be executed\n */\n isReady() {\n let effect = this._effect;\n for (const key in this._bindings) {\n const binding = this._bindings[key], type = binding.type, object = binding.object;\n switch (type) {\n case ComputeBindingType.Texture:\n case ComputeBindingType.TextureWithoutSampler:\n case ComputeBindingType.StorageTexture: {\n const texture = object;\n if (!texture.isReady()) {\n return false;\n }\n break;\n }\n }\n }\n const defines = [];\n const shaderName = this._shaderPath;\n if (this._options.defines) {\n for (let index = 0; index < this._options.defines.length; index++) {\n defines.push(this._options.defines[index]);\n }\n }\n const join = defines.join(\"\\n\");\n if (this._cachedDefines !== join) {\n this._cachedDefines = join;\n effect = this._engine.createComputeEffect(shaderName, {\n defines: join,\n entryPoint: this._options.entryPoint,\n onCompiled: this.onCompiled,\n onError: this.onError,\n });\n this._effect = effect;\n }\n if (!effect.isReady()) {\n return false;\n }\n return true;\n }\n /**\n * Dispatches (executes) the compute shader\n * @param x Number of workgroups to execute on the X dimension\n * @param y Number of workgroups to execute on the Y dimension (default: 1)\n * @param z Number of workgroups to execute on the Z dimension (default: 1)\n * @returns True if the dispatch could be done, else false (meaning either the compute effect or at least one of the bound resources was not ready)\n */\n dispatch(x, y, z) {\n var _a;\n if (!this.isReady()) {\n return false;\n }\n // If the sampling parameters of a texture bound to the shader have changed, we must clear the compute context so that it is recreated with the updated values\n // Also, if the actual (gpu) buffer used by a uniform buffer has changed, we must clear the compute context so that it is recreated with the updated value\n for (const key in this._bindings) {\n const binding = this._bindings[key];\n if (!this._options.bindingsMapping[key]) {\n throw new Error(\"ComputeShader ('\" + this.name + \"'): No binding mapping has been provided for the property '\" + key + \"'\");\n }\n switch (binding.type) {\n case ComputeBindingType.Texture: {\n const sampler = this._samplers[key];\n const texture = binding.object;\n if (!sampler || !texture._texture || !sampler.compareSampler(texture._texture)) {\n this._samplers[key] = new TextureSampler().setParameters(texture.wrapU, texture.wrapV, texture.wrapR, texture.anisotropicFilteringLevel, texture._texture.samplingMode, (_a = texture._texture) === null || _a === void 0 ? void 0 : _a._comparisonFunction);\n this._contextIsDirty = true;\n }\n break;\n }\n case ComputeBindingType.UniformBuffer: {\n const ubo = binding.object;\n if (ubo.getBuffer() !== binding.buffer) {\n binding.buffer = ubo.getBuffer();\n this._contextIsDirty = true;\n }\n break;\n }\n }\n }\n if (this._contextIsDirty) {\n this._contextIsDirty = false;\n this._context.clear();\n }\n this._engine.computeDispatch(this._effect, this._context, this._bindings, x, y, z, this._options.bindingsMapping);\n return true;\n }\n /**\n * Waits for the compute shader to be ready and executes it\n * @param x Number of workgroups to execute on the X dimension\n * @param y Number of workgroups to execute on the Y dimension (default: 1)\n * @param z Number of workgroups to execute on the Z dimension (default: 1)\n * @param delay Delay between the retries while the shader is not ready (in milliseconds - 10 by default)\n * @returns A promise that is resolved once the shader has been sent to the GPU. Note that it does not mean that the shader execution itself is finished!\n */\n dispatchWhenReady(x, y, z, delay = 10) {\n return new Promise((resolve) => {\n const check = () => {\n if (!this.dispatch(x, y, z)) {\n setTimeout(check, delay);\n }\n else {\n resolve();\n }\n };\n check();\n });\n }\n /**\n * Serializes this compute shader in a JSON representation\n * @returns the serialized compute shader object\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this);\n serializationObject.options = this._options;\n serializationObject.shaderPath = this._shaderPath;\n serializationObject.bindings = {};\n serializationObject.textures = {};\n for (const key in this._bindings) {\n const binding = this._bindings[key];\n const object = binding.object;\n switch (binding.type) {\n case ComputeBindingType.Texture:\n case ComputeBindingType.TextureWithoutSampler:\n case ComputeBindingType.StorageTexture: {\n const serializedData = object.serialize();\n if (serializedData) {\n serializationObject.textures[key] = serializedData;\n serializationObject.bindings[key] = {\n type: binding.type,\n };\n }\n break;\n }\n case ComputeBindingType.UniformBuffer: {\n break;\n }\n }\n }\n return serializationObject;\n }\n /**\n * Creates a compute shader from parsed compute shader data\n * @param source defines the JSON representation of the compute shader\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @returns a new compute shader\n */\n static Parse(source, scene, rootUrl) {\n const compute = SerializationHelper.Parse(() => new ComputeShader(source.name, scene.getEngine(), source.shaderPath, source.options), source, scene, rootUrl);\n for (const key in source.textures) {\n const binding = source.bindings[key];\n const texture = Texture.Parse(source.textures[key], scene, rootUrl);\n if (binding.type === ComputeBindingType.Texture) {\n compute.setTexture(key, texture);\n }\n else if (binding.type === ComputeBindingType.TextureWithoutSampler) {\n compute.setTexture(key, texture, false);\n }\n else {\n compute.setStorageTexture(key, texture);\n }\n }\n return compute;\n }\n}\n__decorate([\n serialize()\n], ComputeShader.prototype, \"name\", void 0);\nRegisterClass(\"BABYLON.ComputeShader\", ComputeShader);\n//# sourceMappingURL=computeShader.js.map","export * from \"./computeEffect.js\";\nexport * from \"./computeShader.js\";\n//# sourceMappingURL=index.js.map","import { Vector3 } from \"../../Maths/math.vector.js\";\nimport { BoundingBox } from \"../../Culling/boundingBox.js\";\n/**\n * Class used to store a cell in an octree\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimizeOctrees\n */\nexport class OctreeBlock {\n /**\n * Creates a new block\n * @param minPoint defines the minimum vector (in world space) of the block's bounding box\n * @param maxPoint defines the maximum vector (in world space) of the block's bounding box\n * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)\n * @param depth defines the current depth of this block in the octree\n * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)\n * @param creationFunc defines a callback to call when an element is added to the block\n */\n constructor(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {\n /**\n * Gets the content of the current block\n */\n this.entries = new Array();\n this._boundingVectors = new Array();\n this._capacity = capacity;\n this._depth = depth;\n this._maxDepth = maxDepth;\n this._creationFunc = creationFunc;\n this._minPoint = minPoint;\n this._maxPoint = maxPoint;\n this._boundingVectors.push(minPoint.clone());\n this._boundingVectors.push(maxPoint.clone());\n this._boundingVectors.push(minPoint.clone());\n this._boundingVectors[2].x = maxPoint.x;\n this._boundingVectors.push(minPoint.clone());\n this._boundingVectors[3].y = maxPoint.y;\n this._boundingVectors.push(minPoint.clone());\n this._boundingVectors[4].z = maxPoint.z;\n this._boundingVectors.push(maxPoint.clone());\n this._boundingVectors[5].z = minPoint.z;\n this._boundingVectors.push(maxPoint.clone());\n this._boundingVectors[6].x = minPoint.x;\n this._boundingVectors.push(maxPoint.clone());\n this._boundingVectors[7].y = minPoint.y;\n }\n // Property\n /**\n * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)\n */\n get capacity() {\n return this._capacity;\n }\n /**\n * Gets the minimum vector (in world space) of the block's bounding box\n */\n get minPoint() {\n return this._minPoint;\n }\n /**\n * Gets the maximum vector (in world space) of the block's bounding box\n */\n get maxPoint() {\n return this._maxPoint;\n }\n // Methods\n /**\n * Add a new element to this block\n * @param entry defines the element to add\n */\n addEntry(entry) {\n if (this.blocks) {\n for (let index = 0; index < this.blocks.length; index++) {\n const block = this.blocks[index];\n block.addEntry(entry);\n }\n return;\n }\n this._creationFunc(entry, this);\n if (this.entries.length > this.capacity && this._depth < this._maxDepth) {\n this.createInnerBlocks();\n }\n }\n /**\n * Remove an element from this block\n * @param entry defines the element to remove\n */\n removeEntry(entry) {\n if (this.blocks) {\n for (let index = 0; index < this.blocks.length; index++) {\n const block = this.blocks[index];\n block.removeEntry(entry);\n }\n return;\n }\n const entryIndex = this.entries.indexOf(entry);\n if (entryIndex > -1) {\n this.entries.splice(entryIndex, 1);\n }\n }\n /**\n * Add an array of elements to this block\n * @param entries defines the array of elements to add\n */\n addEntries(entries) {\n for (let index = 0; index < entries.length; index++) {\n const mesh = entries[index];\n this.addEntry(mesh);\n }\n }\n /**\n * Test if the current block intersects the frustum planes and if yes, then add its content to the selection array\n * @param frustumPlanes defines the frustum planes to test\n * @param selection defines the array to store current content if selection is positive\n * @param allowDuplicate defines if the selection array can contains duplicated entries\n */\n select(frustumPlanes, selection, allowDuplicate) {\n if (BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {\n if (this.blocks) {\n for (let index = 0; index < this.blocks.length; index++) {\n const block = this.blocks[index];\n block.select(frustumPlanes, selection, allowDuplicate);\n }\n return;\n }\n if (allowDuplicate) {\n selection.concat(this.entries);\n }\n else {\n selection.concatWithNoDuplicate(this.entries);\n }\n }\n }\n /**\n * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array\n * @param sphereCenter defines the bounding sphere center\n * @param sphereRadius defines the bounding sphere radius\n * @param selection defines the array to store current content if selection is positive\n * @param allowDuplicate defines if the selection array can contains duplicated entries\n */\n intersects(sphereCenter, sphereRadius, selection, allowDuplicate) {\n if (BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {\n if (this.blocks) {\n for (let index = 0; index < this.blocks.length; index++) {\n const block = this.blocks[index];\n block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);\n }\n return;\n }\n if (allowDuplicate) {\n selection.concat(this.entries);\n }\n else {\n selection.concatWithNoDuplicate(this.entries);\n }\n }\n }\n /**\n * Test if the current block intersect with the given ray and if yes, then add its content to the selection array\n * @param ray defines the ray to test with\n * @param selection defines the array to store current content if selection is positive\n */\n intersectsRay(ray, selection) {\n if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {\n if (this.blocks) {\n for (let index = 0; index < this.blocks.length; index++) {\n const block = this.blocks[index];\n block.intersectsRay(ray, selection);\n }\n return;\n }\n selection.concatWithNoDuplicate(this.entries);\n }\n }\n /**\n * Subdivide the content into child blocks (this block will then be empty)\n */\n createInnerBlocks() {\n OctreeBlock._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);\n this.entries.splice(0);\n }\n /**\n * @internal\n */\n static _CreateBlocks(worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {\n target.blocks = new Array();\n const blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);\n // Segmenting space\n for (let x = 0; x < 2; x++) {\n for (let y = 0; y < 2; y++) {\n for (let z = 0; z < 2; z++) {\n const localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));\n const localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));\n const block = new OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);\n block.addEntries(entries);\n target.blocks.push(block);\n }\n }\n }\n }\n}\n//# sourceMappingURL=octreeBlock.js.map","import { SmartArrayNoDuplicate } from \"../../Misc/smartArray.js\";\nimport { OctreeBlock } from \"./octreeBlock.js\";\n/**\n * Octrees are a really powerful data structure that can quickly select entities based on space coordinates.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimizeOctrees\n */\nexport class Octree {\n /**\n * Creates a octree\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimizeOctrees\n * @param creationFunc function to be used to instantiate the octree\n * @param maxBlockCapacity defines the maximum number of meshes you want on your octree's leaves (default: 64)\n * @param maxDepth defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.)\n */\n constructor(creationFunc, maxBlockCapacity, \n /** Defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.) */\n maxDepth = 2) {\n this.maxDepth = maxDepth;\n /**\n * Content stored in the octree\n */\n this.dynamicContent = new Array();\n this._maxBlockCapacity = maxBlockCapacity || 64;\n this._selectionContent = new SmartArrayNoDuplicate(1024);\n this._creationFunc = creationFunc;\n }\n // Methods\n /**\n * Updates the octree by adding blocks for the passed in meshes within the min and max world parameters\n * @param worldMin worldMin for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);\n * @param worldMax worldMax for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);\n * @param entries meshes to be added to the octree blocks\n */\n update(worldMin, worldMax, entries) {\n OctreeBlock._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);\n }\n /**\n * Adds a mesh to the octree\n * @param entry Mesh to add to the octree\n */\n addMesh(entry) {\n for (let index = 0; index < this.blocks.length; index++) {\n const block = this.blocks[index];\n block.addEntry(entry);\n }\n }\n /**\n * Remove an element from the octree\n * @param entry defines the element to remove\n */\n removeMesh(entry) {\n for (let index = 0; index < this.blocks.length; index++) {\n const block = this.blocks[index];\n block.removeEntry(entry);\n }\n }\n /**\n * Selects an array of meshes within the frustum\n * @param frustumPlanes The frustum planes to use which will select all meshes within it\n * @param allowDuplicate If duplicate objects are allowed in the resulting object array\n * @returns array of meshes within the frustum\n */\n select(frustumPlanes, allowDuplicate) {\n this._selectionContent.reset();\n for (let index = 0; index < this.blocks.length; index++) {\n const block = this.blocks[index];\n block.select(frustumPlanes, this._selectionContent, allowDuplicate);\n }\n if (allowDuplicate) {\n this._selectionContent.concat(this.dynamicContent);\n }\n else {\n this._selectionContent.concatWithNoDuplicate(this.dynamicContent);\n }\n return this._selectionContent;\n }\n /**\n * Test if the octree intersect with the given bounding sphere and if yes, then add its content to the selection array\n * @param sphereCenter defines the bounding sphere center\n * @param sphereRadius defines the bounding sphere radius\n * @param allowDuplicate defines if the selection array can contains duplicated entries\n * @returns an array of objects that intersect the sphere\n */\n intersects(sphereCenter, sphereRadius, allowDuplicate) {\n this._selectionContent.reset();\n for (let index = 0; index < this.blocks.length; index++) {\n const block = this.blocks[index];\n block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);\n }\n if (allowDuplicate) {\n this._selectionContent.concat(this.dynamicContent);\n }\n else {\n this._selectionContent.concatWithNoDuplicate(this.dynamicContent);\n }\n return this._selectionContent;\n }\n /**\n * Test if the octree intersect with the given ray and if yes, then add its content to resulting array\n * @param ray defines the ray to test with\n * @returns array of intersected objects\n */\n intersectsRay(ray) {\n this._selectionContent.reset();\n for (let index = 0; index < this.blocks.length; index++) {\n const block = this.blocks[index];\n block.intersectsRay(ray, this._selectionContent);\n }\n this._selectionContent.concatWithNoDuplicate(this.dynamicContent);\n return this._selectionContent;\n }\n}\n/**\n * Adds a mesh into the octree block if it intersects the block\n * @param entry\n * @param block\n */\nOctree.CreationFuncForMeshes = (entry, block) => {\n const boundingInfo = entry.getBoundingInfo();\n if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {\n block.entries.push(entry);\n }\n};\n/**\n * Adds a submesh into the octree block if it intersects the block\n * @param entry\n * @param block\n */\nOctree.CreationFuncForSubMeshes = (entry, block) => {\n const boundingInfo = entry.getBoundingInfo();\n if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {\n block.entries.push(entry);\n }\n};\n//# sourceMappingURL=octree.js.map","import { Scene } from \"../../scene.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { AbstractMesh } from \"../../Meshes/abstractMesh.js\";\nimport { Ray } from \"../../Culling/ray.js\";\nimport { SceneComponentConstants } from \"../../sceneComponent.js\";\nimport { Octree } from \"./octree.js\";\nimport { EngineStore } from \"../../Engines/engineStore.js\";\nScene.prototype.createOrUpdateSelectionOctree = function (maxCapacity = 64, maxDepth = 2) {\n let component = this._getComponent(SceneComponentConstants.NAME_OCTREE);\n if (!component) {\n component = new OctreeSceneComponent(this);\n this._addComponent(component);\n }\n if (!this._selectionOctree) {\n this._selectionOctree = new Octree(Octree.CreationFuncForMeshes, maxCapacity, maxDepth);\n }\n const worldExtends = this.getWorldExtends();\n // Update octree\n this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);\n return this._selectionOctree;\n};\nObject.defineProperty(Scene.prototype, \"selectionOctree\", {\n get: function () {\n return this._selectionOctree;\n },\n enumerable: true,\n configurable: true,\n});\n/**\n * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.\n * Please note that you must have a decent number of submeshes to get performance improvements when using an octree\n * @param maxCapacity defines the maximum size of each block (64 by default)\n * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)\n * @returns the new octree\n * @see https://www.babylonjs-playground.com/#NA4OQ#12\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimizeOctrees\n */\nAbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity = 64, maxDepth = 2) {\n const scene = this.getScene();\n let component = scene._getComponent(SceneComponentConstants.NAME_OCTREE);\n if (!component) {\n component = new OctreeSceneComponent(scene);\n scene._addComponent(component);\n }\n if (!this._submeshesOctree) {\n this._submeshesOctree = new Octree(Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);\n }\n this.computeWorldMatrix(true);\n const boundingInfo = this.getBoundingInfo();\n // Update octree\n const bbox = boundingInfo.boundingBox;\n this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);\n return this._submeshesOctree;\n};\n/**\n * Defines the octree scene component responsible to manage any octrees\n * in a given scene.\n */\nexport class OctreeSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name help to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_OCTREE;\n /**\n * Indicates if the meshes have been checked to make sure they are isEnabled()\n */\n this.checksIsEnabled = true;\n this._tempRay = new Ray(Vector3.Zero(), new Vector3(1, 1, 1));\n scene = scene || EngineStore.LastCreatedScene;\n if (!scene) {\n return;\n }\n this.scene = scene;\n this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);\n this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);\n this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);\n this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene.onMeshRemovedObservable.add((mesh) => {\n const sceneOctree = this.scene.selectionOctree;\n if (sceneOctree !== undefined && sceneOctree !== null) {\n const index = sceneOctree.dynamicContent.indexOf(mesh);\n if (index !== -1) {\n sceneOctree.dynamicContent.splice(index, 1);\n }\n }\n });\n this.scene.onMeshImportedObservable.add((mesh) => {\n const sceneOctree = this.scene.selectionOctree;\n if (sceneOctree !== undefined && sceneOctree !== null) {\n sceneOctree.addMesh(mesh);\n }\n });\n }\n /**\n * Return the list of active meshes\n * @returns the list of active meshes\n */\n getActiveMeshCandidates() {\n var _a;\n return ((_a = this.scene._selectionOctree) === null || _a === void 0 ? void 0 : _a.select(this.scene.frustumPlanes)) || this.scene._getDefaultMeshCandidates();\n }\n /**\n * Return the list of active sub meshes\n * @param mesh The mesh to get the candidates sub meshes from\n * @returns the list of active sub meshes\n */\n getActiveSubMeshCandidates(mesh) {\n if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {\n const intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);\n return intersections;\n }\n return this.scene._getDefaultSubMeshCandidates(mesh);\n }\n /**\n * Return the list of sub meshes intersecting with a given local ray\n * @param mesh defines the mesh to find the submesh for\n * @param localRay defines the ray in local space\n * @returns the list of intersecting sub meshes\n */\n getIntersectingSubMeshCandidates(mesh, localRay) {\n if (mesh._submeshesOctree && mesh.useOctreeForPicking) {\n Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);\n const intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);\n return intersections;\n }\n return this.scene._getDefaultSubMeshCandidates(mesh);\n }\n /**\n * Return the list of sub meshes colliding with a collider\n * @param mesh defines the mesh to find the submesh for\n * @param collider defines the collider to evaluate the collision against\n * @returns the list of colliding sub meshes\n */\n getCollidingSubMeshCandidates(mesh, collider) {\n if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {\n const radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);\n const intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);\n return intersections;\n }\n return this.scene._getDefaultSubMeshCandidates(mesh);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n // Nothing to do here.\n }\n /**\n * Disposes the component and the associated resources.\n */\n dispose() {\n // Nothing to do here.\n }\n}\n//# sourceMappingURL=octreeSceneComponent.js.map","export * from \"./octree.js\";\nexport * from \"./octreeBlock.js\";\nexport * from \"./octreeSceneComponent.js\";\n//# sourceMappingURL=index.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./boundingBox.js\";\nexport * from \"./boundingInfo.js\";\nexport * from \"./boundingSphere.js\";\nexport * from \"./Octrees/index.js\";\nexport * from \"./ray.js\";\n//# sourceMappingURL=index.js.map","import { Scene } from \"../scene.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { PointerInfo, PointerEventTypes } from \"../Events/pointerEvents.js\";\nimport { PickingInfo } from \"../Collisions/pickingInfo.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { HemisphericLight } from \"../Lights/hemisphericLight.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\n/**\n * Renders a layer on top of an existing scene\n */\nexport class UtilityLayerRenderer {\n /**\n * Gets the camera that is used to render the utility layer (when not set, this will be the last active camera)\n * @param getRigParentIfPossible if the current active camera is a rig camera, should its parent camera be returned\n * @returns the camera that is used when rendering the utility layer\n */\n getRenderCamera(getRigParentIfPossible) {\n if (this._renderCamera) {\n return this._renderCamera;\n }\n else {\n let activeCam;\n if (this.originalScene.activeCameras && this.originalScene.activeCameras.length > 1) {\n activeCam = this.originalScene.activeCameras[this.originalScene.activeCameras.length - 1];\n }\n else {\n activeCam = this.originalScene.activeCamera;\n }\n if (getRigParentIfPossible && activeCam && activeCam.isRigCamera) {\n return activeCam.rigParent;\n }\n return activeCam;\n }\n }\n /**\n * Sets the camera that should be used when rendering the utility layer (If set to null the last active camera will be used)\n * @param cam the camera that should be used when rendering the utility layer\n */\n setRenderCamera(cam) {\n this._renderCamera = cam;\n }\n /**\n * @internal\n * Light which used by gizmos to get light shading\n */\n _getSharedGizmoLight() {\n if (!this._sharedGizmoLight) {\n this._sharedGizmoLight = new HemisphericLight(\"shared gizmo light\", new Vector3(0, 1, 0), this.utilityLayerScene);\n this._sharedGizmoLight.intensity = 2;\n this._sharedGizmoLight.groundColor = Color3.Gray();\n }\n return this._sharedGizmoLight;\n }\n /**\n * A shared utility layer that can be used to overlay objects into a scene (Depth map of the previous scene is cleared before drawing on top of it)\n */\n static get DefaultUtilityLayer() {\n if (UtilityLayerRenderer._DefaultUtilityLayer == null) {\n return UtilityLayerRenderer._CreateDefaultUtilityLayerFromScene(EngineStore.LastCreatedScene);\n }\n return UtilityLayerRenderer._DefaultUtilityLayer;\n }\n /**\n * Creates an utility layer, and set it as a default utility layer\n * @param scene associated scene\n * @internal\n */\n static _CreateDefaultUtilityLayerFromScene(scene) {\n UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(scene);\n UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(() => {\n UtilityLayerRenderer._DefaultUtilityLayer = null;\n });\n return UtilityLayerRenderer._DefaultUtilityLayer;\n }\n /**\n * A shared utility layer that can be used to embed objects into a scene (Depth map of the previous scene is not cleared before drawing on top of it)\n */\n static get DefaultKeepDepthUtilityLayer() {\n if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {\n UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(EngineStore.LastCreatedScene);\n UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;\n UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(() => {\n UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;\n });\n }\n return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;\n }\n /**\n * Instantiates a UtilityLayerRenderer\n * @param originalScene the original scene that will be rendered on top of\n * @param handleEvents boolean indicating if the utility layer should handle events\n */\n constructor(\n /** the original scene that will be rendered on top of */\n originalScene, handleEvents = true) {\n this.originalScene = originalScene;\n this._pointerCaptures = {};\n this._lastPointerEvents = {};\n this._sharedGizmoLight = null;\n this._renderCamera = null;\n /**\n * If the picking should be done on the utility layer prior to the actual scene (Default: true)\n */\n this.pickUtilitySceneFirst = true;\n /**\n * If the utility layer should automatically be rendered on top of existing scene\n */\n this.shouldRender = true;\n /**\n * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene\n */\n this.onlyCheckPointerDownEvents = true;\n /**\n * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)\n */\n this.processAllEvents = false;\n /**\n * Set to false to disable picking\n */\n this.pickingEnabled = true;\n /**\n * Observable raised when the pointer moves from the utility layer scene to the main scene\n */\n this.onPointerOutObservable = new Observable();\n // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app\n this.utilityLayerScene = new Scene(originalScene.getEngine(), { virtual: true });\n this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;\n this.utilityLayerScene._allowPostProcessClearColor = false;\n // Deactivate post processes\n this.utilityLayerScene.postProcessesEnabled = false;\n // Detach controls on utility scene, events will be fired by logic below to handle picking priority\n this.utilityLayerScene.detachControl();\n if (handleEvents) {\n this._originalPointerObserver = originalScene.onPrePointerObservable.add((prePointerInfo) => {\n if (!this.utilityLayerScene.activeCamera) {\n return;\n }\n if (!this.pickingEnabled) {\n return;\n }\n if (!this.processAllEvents) {\n if (prePointerInfo.type !== PointerEventTypes.POINTERMOVE &&\n prePointerInfo.type !== PointerEventTypes.POINTERUP &&\n prePointerInfo.type !== PointerEventTypes.POINTERDOWN &&\n prePointerInfo.type !== PointerEventTypes.POINTERDOUBLETAP) {\n return;\n }\n }\n this.utilityLayerScene.pointerX = originalScene.pointerX;\n this.utilityLayerScene.pointerY = originalScene.pointerY;\n const pointerEvent = prePointerInfo.event;\n if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {\n this._pointerCaptures[pointerEvent.pointerId] = false;\n return;\n }\n const getNearPickDataForScene = (scene) => {\n let scenePick = null;\n if (prePointerInfo.nearInteractionPickingInfo) {\n if (prePointerInfo.nearInteractionPickingInfo.pickedMesh.getScene() == scene) {\n scenePick = prePointerInfo.nearInteractionPickingInfo;\n }\n else {\n scenePick = new PickingInfo();\n }\n }\n else if (scene !== this.utilityLayerScene && prePointerInfo.originalPickingInfo) {\n scenePick = prePointerInfo.originalPickingInfo;\n }\n else {\n let previousActiveCamera = null;\n // If a camera is set for rendering with this layer\n // it will also be used for the ray computation\n // To preserve back compat and because scene.pick always use activeCamera\n // it's substituted temporarily and a new scenePick is forced.\n // otherwise, the ray with previously active camera is always used.\n // It's set back to previous activeCamera after operation.\n if (this._renderCamera) {\n previousActiveCamera = scene._activeCamera;\n scene._activeCamera = this._renderCamera;\n prePointerInfo.ray = null;\n }\n scenePick = prePointerInfo.ray ? scene.pickWithRay(prePointerInfo.ray) : scene.pick(originalScene.pointerX, originalScene.pointerY);\n if (previousActiveCamera) {\n scene._activeCamera = previousActiveCamera;\n }\n }\n return scenePick;\n };\n const utilityScenePick = getNearPickDataForScene(this.utilityLayerScene);\n if (!prePointerInfo.ray && utilityScenePick) {\n prePointerInfo.ray = utilityScenePick.ray;\n }\n // always fire the prepointer observable\n this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);\n // allow every non pointer down event to flow to the utility layer\n if (this.onlyCheckPointerDownEvents && prePointerInfo.type != PointerEventTypes.POINTERDOWN) {\n if (!prePointerInfo.skipOnPointerObservable) {\n this.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick), prePointerInfo.type);\n }\n if (prePointerInfo.type === PointerEventTypes.POINTERUP && this._pointerCaptures[pointerEvent.pointerId]) {\n this._pointerCaptures[pointerEvent.pointerId] = false;\n }\n return;\n }\n if (this.utilityLayerScene.autoClearDepthAndStencil || this.pickUtilitySceneFirst) {\n // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene\n if (utilityScenePick && utilityScenePick.hit) {\n if (!prePointerInfo.skipOnPointerObservable) {\n this.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick), prePointerInfo.type);\n }\n prePointerInfo.skipOnPointerObservable = true;\n }\n }\n else {\n const originalScenePick = getNearPickDataForScene(originalScene);\n const pointerEvent = prePointerInfo.event;\n // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray\n if (originalScenePick && utilityScenePick) {\n // No pick in utility scene\n if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {\n if (this.mainSceneTrackerPredicate && this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {\n // We touched an utility mesh present in the main scene\n this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent);\n prePointerInfo.skipOnPointerObservable = true;\n }\n else if (prePointerInfo.type === PointerEventTypes.POINTERDOWN) {\n this._pointerCaptures[pointerEvent.pointerId] = true;\n }\n else if (prePointerInfo.type === PointerEventTypes.POINTERMOVE || prePointerInfo.type === PointerEventTypes.POINTERUP) {\n if (this._lastPointerEvents[pointerEvent.pointerId]) {\n // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete\n this.onPointerOutObservable.notifyObservers(pointerEvent.pointerId);\n delete this._lastPointerEvents[pointerEvent.pointerId];\n }\n this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent);\n }\n }\n else if (!this._pointerCaptures[pointerEvent.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {\n // We pick something in utility scene or the pick in utility is closer than the one in main scene\n this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent);\n // If a previous utility layer set this, do not unset this\n if (!prePointerInfo.skipOnPointerObservable) {\n prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;\n }\n }\n else if (!this._pointerCaptures[pointerEvent.pointerId] && utilityScenePick.distance >= originalScenePick.distance) {\n // We have a pick in both scenes but main is closer than utility\n // We touched an utility mesh present in the main scene\n if (this.mainSceneTrackerPredicate && this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {\n this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent);\n prePointerInfo.skipOnPointerObservable = true;\n }\n else {\n if (prePointerInfo.type === PointerEventTypes.POINTERMOVE || prePointerInfo.type === PointerEventTypes.POINTERUP) {\n if (this._lastPointerEvents[pointerEvent.pointerId]) {\n // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete\n this.onPointerOutObservable.notifyObservers(pointerEvent.pointerId);\n delete this._lastPointerEvents[pointerEvent.pointerId];\n }\n }\n this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent);\n }\n }\n if (prePointerInfo.type === PointerEventTypes.POINTERUP && this._pointerCaptures[pointerEvent.pointerId]) {\n this._pointerCaptures[pointerEvent.pointerId] = false;\n }\n }\n }\n });\n // As a newly added utility layer will be rendered over the screen last, it's pointer events should be processed first\n if (this._originalPointerObserver) {\n originalScene.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver);\n }\n }\n // Render directly on top of existing scene without clearing\n this.utilityLayerScene.autoClear = false;\n this._afterRenderObserver = this.originalScene.onAfterRenderCameraObservable.add((camera) => {\n // Only render when the render camera finishes rendering\n if (this.shouldRender && camera == this.getRenderCamera()) {\n this.render();\n }\n });\n this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(() => {\n this.dispose();\n });\n this._updateCamera();\n }\n _notifyObservers(prePointerInfo, pickInfo, pointerEvent) {\n if (!prePointerInfo.skipOnPointerObservable) {\n this.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo), prePointerInfo.type);\n this._lastPointerEvents[pointerEvent.pointerId] = true;\n }\n }\n /**\n * Renders the utility layers scene on top of the original scene\n */\n render() {\n this._updateCamera();\n if (this.utilityLayerScene.activeCamera) {\n // Set the camera's scene to utility layers scene\n const oldScene = this.utilityLayerScene.activeCamera.getScene();\n const camera = this.utilityLayerScene.activeCamera;\n camera._scene = this.utilityLayerScene;\n if (camera.leftCamera) {\n camera.leftCamera._scene = this.utilityLayerScene;\n }\n if (camera.rightCamera) {\n camera.rightCamera._scene = this.utilityLayerScene;\n }\n this.utilityLayerScene.render(false);\n // Reset camera's scene back to original\n camera._scene = oldScene;\n if (camera.leftCamera) {\n camera.leftCamera._scene = oldScene;\n }\n if (camera.rightCamera) {\n camera.rightCamera._scene = oldScene;\n }\n }\n }\n /**\n * Disposes of the renderer\n */\n dispose() {\n this.onPointerOutObservable.clear();\n if (this._afterRenderObserver) {\n this.originalScene.onAfterCameraRenderObservable.remove(this._afterRenderObserver);\n }\n if (this._sceneDisposeObserver) {\n this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);\n }\n if (this._originalPointerObserver) {\n this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);\n }\n this.utilityLayerScene.dispose();\n }\n _updateCamera() {\n this.utilityLayerScene.cameraToUseForPointers = this.getRenderCamera();\n this.utilityLayerScene.activeCamera = this.getRenderCamera();\n }\n}\n/** @internal */\nUtilityLayerRenderer._DefaultUtilityLayer = null;\n/** @internal */\nUtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;\n//# sourceMappingURL=utilityLayerRenderer.js.map","import { Quaternion, Vector3, Matrix, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { Camera } from \"../Cameras/camera.js\";\nimport { UtilityLayerRenderer } from \"../Rendering/utilityLayerRenderer.js\";\nimport { PointerEventTypes } from \"../Events/pointerEvents.js\";\nimport { Light } from \"../Lights/light.js\";\n/**\n * Anchor options where the Gizmo can be positioned in relation to its anchored node\n */\nexport var GizmoAnchorPoint;\n(function (GizmoAnchorPoint) {\n /** The origin of the attached node */\n GizmoAnchorPoint[GizmoAnchorPoint[\"Origin\"] = 0] = \"Origin\";\n /** The pivot point of the attached node*/\n GizmoAnchorPoint[GizmoAnchorPoint[\"Pivot\"] = 1] = \"Pivot\";\n})(GizmoAnchorPoint || (GizmoAnchorPoint = {}));\n/**\n * Coordinates mode: Local or World. Defines how axis is aligned: either on world axis or transform local axis\n */\nexport var GizmoCoordinatesMode;\n(function (GizmoCoordinatesMode) {\n GizmoCoordinatesMode[GizmoCoordinatesMode[\"World\"] = 0] = \"World\";\n GizmoCoordinatesMode[GizmoCoordinatesMode[\"Local\"] = 1] = \"Local\";\n})(GizmoCoordinatesMode || (GizmoCoordinatesMode = {}));\n/**\n * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.\n */\nexport class Gizmo {\n /**\n * Ratio for the scale of the gizmo (Default: 1)\n */\n set scaleRatio(value) {\n this._scaleRatio = value;\n }\n get scaleRatio() {\n return this._scaleRatio;\n }\n /**\n * True when the mouse pointer is hovered a gizmo mesh\n */\n get isHovered() {\n return this._isHovered;\n }\n /**\n * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)\n * * When set, interactions will be enabled\n */\n get attachedMesh() {\n return this._attachedMesh;\n }\n set attachedMesh(value) {\n this._attachedMesh = value;\n if (value) {\n this._attachedNode = value;\n }\n this._rootMesh.setEnabled(value ? true : false);\n this._attachedNodeChanged(value);\n }\n /**\n * Node that the gizmo will be attached to. (eg. on a drag gizmo the mesh, bone or NodeTransform that will be dragged)\n * * When set, interactions will be enabled\n */\n get attachedNode() {\n return this._attachedNode;\n }\n set attachedNode(value) {\n this._attachedNode = value;\n this._attachedMesh = null;\n this._rootMesh.setEnabled(value ? true : false);\n this._attachedNodeChanged(value);\n }\n /**\n * Disposes and replaces the current meshes in the gizmo with the specified mesh\n * @param mesh The mesh to replace the default mesh of the gizmo\n */\n setCustomMesh(mesh) {\n if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {\n throw \"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)\";\n }\n this._rootMesh.getChildMeshes().forEach((c) => {\n c.dispose();\n });\n mesh.parent = this._rootMesh;\n this._customMeshSet = true;\n }\n /**\n * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)\n * NOTE: This is only possible for meshes with uniform scaling, as otherwise it's not possible to decompose the rotation\n */\n set updateGizmoRotationToMatchAttachedMesh(value) {\n this._updateGizmoRotationToMatchAttachedMesh = value;\n }\n get updateGizmoRotationToMatchAttachedMesh() {\n return this._updateGizmoRotationToMatchAttachedMesh;\n }\n /**\n * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)\n */\n set updateGizmoPositionToMatchAttachedMesh(value) {\n this._updateGizmoPositionToMatchAttachedMesh = value;\n }\n get updateGizmoPositionToMatchAttachedMesh() {\n return this._updateGizmoPositionToMatchAttachedMesh;\n }\n /**\n * Defines where the gizmo will be positioned if `updateGizmoPositionToMatchAttachedMesh` is enabled.\n * (Default: GizmoAnchorPoint.Origin)\n */\n set anchorPoint(value) {\n this._anchorPoint = value;\n }\n get anchorPoint() {\n return this._anchorPoint;\n }\n /**\n * Set the coordinate system to use. By default it's local.\n * But it's possible for a user to tweak so its local for translation and world for rotation.\n * In that case, setting the coordinate system will change `updateGizmoRotationToMatchAttachedMesh` and `updateGizmoPositionToMatchAttachedMesh`\n */\n set coordinatesMode(coordinatesMode) {\n this._coordinatesMode = coordinatesMode;\n const local = coordinatesMode == GizmoCoordinatesMode.Local;\n this.updateGizmoRotationToMatchAttachedMesh = local;\n this.updateGizmoPositionToMatchAttachedMesh = local;\n }\n get coordinatesMode() {\n return this._coordinatesMode;\n }\n /**\n * When set, the gizmo will always appear the same size no matter where the camera is (default: true)\n */\n set updateScale(value) {\n this._updateScale = value;\n }\n get updateScale() {\n return this._updateScale;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _attachedNodeChanged(value) { }\n /**\n * Creates a gizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n */\n constructor(\n /** The utility layer the gizmo will be added to */\n gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer) {\n this.gizmoLayer = gizmoLayer;\n this._attachedMesh = null;\n this._attachedNode = null;\n this._customRotationQuaternion = null;\n /**\n * Ratio for the scale of the gizmo (Default: 1)\n */\n this._scaleRatio = 1;\n /**\n * boolean updated by pointermove when a gizmo mesh is hovered\n */\n this._isHovered = false;\n /**\n * If a custom mesh has been set (Default: false)\n */\n this._customMeshSet = false;\n this._updateGizmoRotationToMatchAttachedMesh = true;\n this._updateGizmoPositionToMatchAttachedMesh = true;\n this._anchorPoint = GizmoAnchorPoint.Origin;\n this._updateScale = true;\n this._coordinatesMode = GizmoCoordinatesMode.Local;\n this._interactionsEnabled = true;\n this._rightHandtoLeftHandMatrix = Matrix.RotationY(Math.PI);\n this._rootMesh = new Mesh(\"gizmoRootNode\", gizmoLayer.utilityLayerScene);\n this._rootMesh.rotationQuaternion = Quaternion.Identity();\n this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(() => {\n this._update();\n });\n }\n /**\n * posture that the gizmo will be display\n * When set null, default value will be used (Quaternion(0, 0, 0, 1))\n */\n get customRotationQuaternion() {\n return this._customRotationQuaternion;\n }\n set customRotationQuaternion(customRotationQuaternion) {\n this._customRotationQuaternion = customRotationQuaternion;\n }\n /**\n * Updates the gizmo to match the attached mesh's position/rotation\n */\n _update() {\n if (this.attachedNode) {\n let effectiveNode = this.attachedNode;\n if (this.attachedMesh) {\n effectiveNode = this.attachedMesh || this.attachedNode;\n }\n // Position\n if (this.updateGizmoPositionToMatchAttachedMesh) {\n if (this.anchorPoint == GizmoAnchorPoint.Pivot && effectiveNode.getAbsolutePivotPoint) {\n const position = effectiveNode.getAbsolutePivotPoint();\n this._rootMesh.position.copyFrom(position);\n }\n else {\n const row = effectiveNode.getWorldMatrix().getRow(3);\n const position = row ? row.toVector3() : new Vector3(0, 0, 0);\n this._rootMesh.position.copyFrom(position);\n }\n }\n // Rotation\n if (this.updateGizmoRotationToMatchAttachedMesh) {\n const supportedNode = effectiveNode._isMesh ||\n effectiveNode.getClassName() === \"AbstractMesh\" ||\n effectiveNode.getClassName() === \"TransformNode\" ||\n effectiveNode.getClassName() === \"InstancedMesh\";\n const transformNode = supportedNode ? effectiveNode : undefined;\n effectiveNode.getWorldMatrix().decompose(undefined, this._rootMesh.rotationQuaternion, undefined, Gizmo.PreserveScaling ? transformNode : undefined);\n }\n else {\n if (this._customRotationQuaternion) {\n this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion);\n }\n else {\n this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);\n }\n }\n // Scale\n if (this.updateScale) {\n const activeCamera = this.gizmoLayer.utilityLayerScene.activeCamera;\n let cameraPosition = activeCamera.globalPosition;\n if (activeCamera.devicePosition) {\n cameraPosition = activeCamera.devicePosition;\n }\n this._rootMesh.position.subtractToRef(cameraPosition, TmpVectors.Vector3[0]);\n let scale = this.scaleRatio;\n if (activeCamera.mode == Camera.ORTHOGRAPHIC_CAMERA) {\n if (activeCamera.orthoTop && activeCamera.orthoBottom) {\n const orthoHeight = activeCamera.orthoTop - activeCamera.orthoBottom;\n scale *= orthoHeight;\n }\n }\n else {\n const camForward = activeCamera.getScene().useRightHandedSystem ? Vector3.RightHandedForwardReadOnly : Vector3.LeftHandedForwardReadOnly;\n const direction = activeCamera.getDirection(camForward);\n scale *= Vector3.Dot(TmpVectors.Vector3[0], direction);\n }\n this._rootMesh.scaling.setAll(scale);\n // Account for handedness, similar to Matrix.decompose\n if (effectiveNode._getWorldMatrixDeterminant() < 0 && !Gizmo.PreserveScaling) {\n this._rootMesh.scaling.y *= -1;\n }\n }\n else {\n this._rootMesh.scaling.setAll(this.scaleRatio);\n }\n }\n }\n /**\n * Handle position/translation when using an attached node using pivot\n */\n _handlePivot() {\n const attachedNodeTransform = this._attachedNode;\n // check there is an active pivot for the TransformNode attached\n if (attachedNodeTransform.isUsingPivotMatrix && attachedNodeTransform.isUsingPivotMatrix() && attachedNodeTransform.position) {\n // When a TransformNode has an active pivot, even without parenting,\n // translation from the world matrix is different from TransformNode.position.\n // Pivot works like a virtual parent that's using the node orientation.\n // As the world matrix is transformed by the gizmo and then decomposed to TRS\n // its translation part must be set to the Node's position.\n attachedNodeTransform.getWorldMatrix().setTranslation(attachedNodeTransform.position);\n }\n }\n /**\n * computes the rotation/scaling/position of the transform once the Node world matrix has changed.\n */\n _matrixChanged() {\n if (!this._attachedNode) {\n return;\n }\n if (this._attachedNode._isCamera) {\n const camera = this._attachedNode;\n let worldMatrix;\n let worldMatrixUC;\n if (camera.parent) {\n const parentInv = TmpVectors.Matrix[1];\n camera.parent._worldMatrix.invertToRef(parentInv);\n this._attachedNode._worldMatrix.multiplyToRef(parentInv, TmpVectors.Matrix[0]);\n worldMatrix = TmpVectors.Matrix[0];\n }\n else {\n worldMatrix = this._attachedNode._worldMatrix;\n }\n if (camera.getScene().useRightHandedSystem) {\n // avoid desync with RH matrix computation. Otherwise, rotation of PI around Y axis happens each frame resulting in axis flipped because worldMatrix is computed as inverse of viewMatrix.\n this._rightHandtoLeftHandMatrix.multiplyToRef(worldMatrix, TmpVectors.Matrix[1]);\n worldMatrixUC = TmpVectors.Matrix[1];\n }\n else {\n worldMatrixUC = worldMatrix;\n }\n worldMatrixUC.decompose(TmpVectors.Vector3[1], TmpVectors.Quaternion[0], TmpVectors.Vector3[0]);\n const inheritsTargetCamera = this._attachedNode.getClassName() === \"FreeCamera\" ||\n this._attachedNode.getClassName() === \"FlyCamera\" ||\n this._attachedNode.getClassName() === \"ArcFollowCamera\" ||\n this._attachedNode.getClassName() === \"TargetCamera\" ||\n this._attachedNode.getClassName() === \"TouchCamera\" ||\n this._attachedNode.getClassName() === \"UniversalCamera\";\n if (inheritsTargetCamera) {\n const targetCamera = this._attachedNode;\n targetCamera.rotation = TmpVectors.Quaternion[0].toEulerAngles();\n if (targetCamera.rotationQuaternion) {\n targetCamera.rotationQuaternion.copyFrom(TmpVectors.Quaternion[0]);\n targetCamera.rotationQuaternion.normalize();\n }\n }\n camera.position.copyFrom(TmpVectors.Vector3[0]);\n }\n else if (this._attachedNode._isMesh ||\n this._attachedNode.getClassName() === \"AbstractMesh\" ||\n this._attachedNode.getClassName() === \"TransformNode\" ||\n this._attachedNode.getClassName() === \"InstancedMesh\") {\n const transform = this._attachedNode;\n if (transform.parent) {\n const parentInv = TmpVectors.Matrix[0];\n const localMat = TmpVectors.Matrix[1];\n transform.parent.getWorldMatrix().invertToRef(parentInv);\n this._attachedNode.getWorldMatrix().multiplyToRef(parentInv, localMat);\n localMat.decompose(TmpVectors.Vector3[0], TmpVectors.Quaternion[0], transform.position, Gizmo.PreserveScaling ? transform : undefined);\n }\n else {\n this._attachedNode._worldMatrix.decompose(TmpVectors.Vector3[0], TmpVectors.Quaternion[0], transform.position, Gizmo.PreserveScaling ? transform : undefined);\n }\n TmpVectors.Vector3[0].scaleInPlace(1.0 / transform.scalingDeterminant);\n transform.scaling.copyFrom(TmpVectors.Vector3[0]);\n if (!transform.billboardMode) {\n if (transform.rotationQuaternion) {\n transform.rotationQuaternion.copyFrom(TmpVectors.Quaternion[0]);\n transform.rotationQuaternion.normalize();\n }\n else {\n transform.rotation = TmpVectors.Quaternion[0].toEulerAngles();\n }\n }\n }\n else if (this._attachedNode.getClassName() === \"Bone\") {\n const bone = this._attachedNode;\n const parent = bone.getParent();\n if (parent) {\n const invParent = TmpVectors.Matrix[0];\n const boneLocalMatrix = TmpVectors.Matrix[1];\n parent.getFinalMatrix().invertToRef(invParent);\n bone.getFinalMatrix().multiplyToRef(invParent, boneLocalMatrix);\n const lmat = bone.getLocalMatrix();\n lmat.copyFrom(boneLocalMatrix);\n }\n else {\n const lmat = bone.getLocalMatrix();\n lmat.copyFrom(bone.getFinalMatrix());\n }\n bone.markAsDirty();\n }\n else {\n const light = this._attachedNode;\n if (light.getTypeID) {\n const type = light.getTypeID();\n if (type === Light.LIGHTTYPEID_DIRECTIONALLIGHT || type === Light.LIGHTTYPEID_SPOTLIGHT || type === Light.LIGHTTYPEID_POINTLIGHT) {\n const parent = light.parent;\n if (parent) {\n const invParent = TmpVectors.Matrix[0];\n const nodeLocalMatrix = TmpVectors.Matrix[1];\n parent.getWorldMatrix().invertToRef(invParent);\n light.getWorldMatrix().multiplyToRef(invParent, nodeLocalMatrix);\n nodeLocalMatrix.decompose(undefined, TmpVectors.Quaternion[0], TmpVectors.Vector3[0]);\n }\n else {\n this._attachedNode._worldMatrix.decompose(undefined, TmpVectors.Quaternion[0], TmpVectors.Vector3[0]);\n }\n // setter doesn't copy values. Need a new Vector3\n light.position = new Vector3(TmpVectors.Vector3[0].x, TmpVectors.Vector3[0].y, TmpVectors.Vector3[0].z);\n if (light.direction) {\n light.direction = new Vector3(light.direction.x, light.direction.y, light.direction.z);\n }\n }\n }\n }\n }\n /**\n * refresh gizmo mesh material\n * @param gizmoMeshes\n * @param material material to apply\n */\n _setGizmoMeshMaterial(gizmoMeshes, material) {\n if (gizmoMeshes) {\n gizmoMeshes.forEach((m) => {\n m.material = material;\n if (m.color) {\n m.color = material.diffuseColor;\n }\n });\n }\n }\n /**\n * Subscribes to pointer up, down, and hover events. Used for responsive gizmos.\n * @param gizmoLayer The utility layer the gizmo will be added to\n * @param gizmoAxisCache Gizmo axis definition used for reactive gizmo UI\n * @returns {Observer} pointerObserver\n */\n static GizmoAxisPointerObserver(gizmoLayer, gizmoAxisCache) {\n let dragging = false;\n const pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add((pointerInfo) => {\n var _a, _b;\n if (pointerInfo.pickInfo) {\n // On Hover Logic\n if (pointerInfo.type === PointerEventTypes.POINTERMOVE) {\n if (dragging) {\n return;\n }\n gizmoAxisCache.forEach((cache) => {\n var _a, _b;\n if (cache.colliderMeshes && cache.gizmoMeshes) {\n const isHovered = ((_a = cache.colliderMeshes) === null || _a === void 0 ? void 0 : _a.indexOf((_b = pointerInfo === null || pointerInfo === void 0 ? void 0 : pointerInfo.pickInfo) === null || _b === void 0 ? void 0 : _b.pickedMesh)) != -1;\n const material = cache.dragBehavior.enabled ? (isHovered || cache.active ? cache.hoverMaterial : cache.material) : cache.disableMaterial;\n cache.gizmoMeshes.forEach((m) => {\n m.material = material;\n if (m.color) {\n m.color = material.diffuseColor;\n }\n });\n }\n });\n }\n // On Mouse Down\n if (pointerInfo.type === PointerEventTypes.POINTERDOWN) {\n // If user Clicked Gizmo\n if (gizmoAxisCache.has((_a = pointerInfo.pickInfo.pickedMesh) === null || _a === void 0 ? void 0 : _a.parent)) {\n dragging = true;\n const statusMap = gizmoAxisCache.get((_b = pointerInfo.pickInfo.pickedMesh) === null || _b === void 0 ? void 0 : _b.parent);\n statusMap.active = true;\n gizmoAxisCache.forEach((cache) => {\n var _a, _b;\n const isHovered = ((_a = cache.colliderMeshes) === null || _a === void 0 ? void 0 : _a.indexOf((_b = pointerInfo === null || pointerInfo === void 0 ? void 0 : pointerInfo.pickInfo) === null || _b === void 0 ? void 0 : _b.pickedMesh)) != -1;\n const material = (isHovered || cache.active) && cache.dragBehavior.enabled ? cache.hoverMaterial : cache.disableMaterial;\n cache.gizmoMeshes.forEach((m) => {\n m.material = material;\n if (m.color) {\n m.color = material.diffuseColor;\n }\n });\n });\n }\n }\n // On Mouse Up\n if (pointerInfo.type === PointerEventTypes.POINTERUP) {\n gizmoAxisCache.forEach((cache) => {\n cache.active = false;\n dragging = false;\n cache.gizmoMeshes.forEach((m) => {\n m.material = cache.dragBehavior.enabled ? cache.material : cache.disableMaterial;\n if (m.color) {\n m.color = cache.material.diffuseColor;\n }\n });\n });\n }\n }\n });\n return pointerObserver;\n }\n /**\n * Disposes of the gizmo\n */\n dispose() {\n this._rootMesh.dispose();\n if (this._beforeRenderObserver) {\n this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);\n }\n }\n}\n/**\n * When enabled, any gizmo operation will perserve scaling sign. Default is off.\n * Only valid for TransformNode derived classes (Mesh, AbstractMesh, ...)\n */\nGizmo.PreserveScaling = false;\n//# sourceMappingURL=gizmo.js.map","import { Vector3 } from \"../Maths/math.vector.js\";\nimport { StandardMaterial } from \"../Materials/standardMaterial.js\";\nimport { AxisDragGizmo } from \"../Gizmos/axisDragGizmo.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n/**\n * The Axes viewer will show 3 axes in a specific point in space\n * @see https://doc.babylonjs.com/toolsAndResources/utilities/World_Axes\n */\nexport class AxesViewer {\n /** Gets the node hierarchy used to render x-axis */\n get xAxis() {\n return this._xAxis;\n }\n /** Gets the node hierarchy used to render y-axis */\n get yAxis() {\n return this._yAxis;\n }\n /** Gets the node hierarchy used to render z-axis */\n get zAxis() {\n return this._zAxis;\n }\n /**\n * Creates a new AxesViewer\n * @param scene defines the hosting scene\n * @param scaleLines defines a number used to scale line length (1 by default)\n * @param renderingGroupId defines a number used to set the renderingGroupId of the meshes (2 by default)\n * @param xAxis defines the node hierarchy used to render the x-axis\n * @param yAxis defines the node hierarchy used to render the y-axis\n * @param zAxis defines the node hierarchy used to render the z-axis\n * @param lineThickness The line thickness to use when creating the arrow. defaults to 1.\n */\n constructor(scene, scaleLines = 1, renderingGroupId = 2, xAxis, yAxis, zAxis, lineThickness = 1) {\n this._scaleLinesFactor = 4;\n this._instanced = false;\n /**\n * Gets the hosting scene\n */\n this.scene = null;\n /**\n * Gets or sets a number used to scale line length\n */\n this.scaleLines = 1;\n scene = scene || EngineStore.LastCreatedScene;\n if (!scene) {\n return;\n }\n this.scaleLines = scaleLines;\n if (!xAxis) {\n const redColoredMaterial = new StandardMaterial(\"\", scene);\n redColoredMaterial.disableLighting = true;\n redColoredMaterial.emissiveColor = Color3.Red().scale(0.5);\n xAxis = AxisDragGizmo._CreateArrow(scene, redColoredMaterial, lineThickness);\n }\n if (!yAxis) {\n const greenColoredMaterial = new StandardMaterial(\"\", scene);\n greenColoredMaterial.disableLighting = true;\n greenColoredMaterial.emissiveColor = Color3.Green().scale(0.5);\n yAxis = AxisDragGizmo._CreateArrow(scene, greenColoredMaterial, lineThickness);\n }\n if (!zAxis) {\n const blueColoredMaterial = new StandardMaterial(\"\", scene);\n blueColoredMaterial.disableLighting = true;\n blueColoredMaterial.emissiveColor = Color3.Blue().scale(0.5);\n zAxis = AxisDragGizmo._CreateArrow(scene, blueColoredMaterial, lineThickness);\n }\n this._xAxis = xAxis;\n this._xAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor);\n this._yAxis = yAxis;\n this._yAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor);\n this._zAxis = zAxis;\n this._zAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor);\n if (renderingGroupId != null) {\n AxesViewer._SetRenderingGroupId(this._xAxis, renderingGroupId);\n AxesViewer._SetRenderingGroupId(this._yAxis, renderingGroupId);\n AxesViewer._SetRenderingGroupId(this._zAxis, renderingGroupId);\n }\n this.scene = scene;\n this.update(new Vector3(), Vector3.Right(), Vector3.Up(), Vector3.Forward());\n }\n /**\n * Force the viewer to update\n * @param position defines the position of the viewer\n * @param xaxis defines the x axis of the viewer\n * @param yaxis defines the y axis of the viewer\n * @param zaxis defines the z axis of the viewer\n */\n update(position, xaxis, yaxis, zaxis) {\n this._xAxis.position.copyFrom(position);\n this._xAxis.setDirection(xaxis);\n this._xAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor);\n this._yAxis.position.copyFrom(position);\n this._yAxis.setDirection(yaxis);\n this._yAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor);\n this._zAxis.position.copyFrom(position);\n this._zAxis.setDirection(zaxis);\n this._zAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor);\n }\n /**\n * Creates an instance of this axes viewer.\n * @returns a new axes viewer with instanced meshes\n */\n createInstance() {\n const xAxis = AxisDragGizmo._CreateArrowInstance(this.scene, this._xAxis);\n const yAxis = AxisDragGizmo._CreateArrowInstance(this.scene, this._yAxis);\n const zAxis = AxisDragGizmo._CreateArrowInstance(this.scene, this._zAxis);\n const axesViewer = new AxesViewer(this.scene, this.scaleLines, null, xAxis, yAxis, zAxis);\n axesViewer._instanced = true;\n return axesViewer;\n }\n /** Releases resources */\n dispose() {\n if (this._xAxis) {\n this._xAxis.dispose(false, !this._instanced);\n }\n if (this._yAxis) {\n this._yAxis.dispose(false, !this._instanced);\n }\n if (this._zAxis) {\n this._zAxis.dispose(false, !this._instanced);\n }\n this.scene = null;\n }\n static _SetRenderingGroupId(node, id) {\n node.getChildMeshes().forEach((mesh) => {\n mesh.renderingGroupId = id;\n });\n }\n}\n//# sourceMappingURL=axesViewer.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { TransformNode } from \"../Meshes/transformNode.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { CreateCylinder } from \"../Meshes/Builders/cylinderBuilder.js\";\nimport { PointerDragBehavior } from \"../Behaviors/Meshes/pointerDragBehavior.js\";\nimport { Gizmo } from \"./gizmo.js\";\nimport { UtilityLayerRenderer } from \"../Rendering/utilityLayerRenderer.js\";\nimport { StandardMaterial } from \"../Materials/standardMaterial.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { TmpVectors } from \"../Maths/math.vector.js\";\n/**\n * Single axis drag gizmo\n */\nexport class AxisDragGizmo extends Gizmo {\n /** Default material used to render when gizmo is not disabled or hovered */\n get coloredMaterial() {\n return this._coloredMaterial;\n }\n /** Material used to render when gizmo is hovered with mouse*/\n get hoverMaterial() {\n return this._hoverMaterial;\n }\n /** Material used to render when gizmo is disabled. typically grey.*/\n get disableMaterial() {\n return this._disableMaterial;\n }\n /**\n * @internal\n */\n static _CreateArrow(scene, material, thickness = 1, isCollider = false) {\n const arrow = new TransformNode(\"arrow\", scene);\n const cylinder = CreateCylinder(\"cylinder\", { diameterTop: 0, height: 0.075, diameterBottom: 0.0375 * (1 + (thickness - 1) / 4), tessellation: 96 }, scene);\n const line = CreateCylinder(\"cylinder\", { diameterTop: 0.005 * thickness, height: 0.275, diameterBottom: 0.005 * thickness, tessellation: 96 }, scene);\n // Position arrow pointing in its drag axis\n cylinder.parent = arrow;\n cylinder.material = material;\n cylinder.rotation.x = Math.PI / 2;\n cylinder.position.z += 0.3;\n line.parent = arrow;\n line.material = material;\n line.position.z += 0.275 / 2;\n line.rotation.x = Math.PI / 2;\n if (isCollider) {\n line.visibility = 0;\n cylinder.visibility = 0;\n }\n return arrow;\n }\n /**\n * @internal\n */\n static _CreateArrowInstance(scene, arrow) {\n const instance = new TransformNode(\"arrow\", scene);\n for (const mesh of arrow.getChildMeshes()) {\n const childInstance = mesh.createInstance(mesh.name);\n childInstance.parent = instance;\n }\n return instance;\n }\n /**\n * Creates an AxisDragGizmo\n * @param dragAxis The axis which the gizmo will be able to drag on\n * @param color The color of the gizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n * @param parent\n * @param thickness display gizmo axis thickness\n */\n constructor(dragAxis, color = Color3.Gray(), gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer, parent = null, thickness = 1) {\n var _a;\n super(gizmoLayer);\n this._pointerObserver = null;\n /**\n * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)\n */\n this.snapDistance = 0;\n /**\n * Event that fires each time the gizmo snaps to a new location.\n * * snapDistance is the the change in distance\n */\n this.onSnapObservable = new Observable();\n this._isEnabled = true;\n this._parent = null;\n this._dragging = false;\n this._parent = parent;\n // Create Material\n this._coloredMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._coloredMaterial.diffuseColor = color;\n this._coloredMaterial.specularColor = color.subtract(new Color3(0.1, 0.1, 0.1));\n this._hoverMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._hoverMaterial.diffuseColor = Color3.Yellow();\n this._disableMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._disableMaterial.diffuseColor = Color3.Gray();\n this._disableMaterial.alpha = 0.4;\n // Build Mesh + Collider\n const arrow = AxisDragGizmo._CreateArrow(gizmoLayer.utilityLayerScene, this._coloredMaterial, thickness);\n const collider = AxisDragGizmo._CreateArrow(gizmoLayer.utilityLayerScene, this._coloredMaterial, thickness + 4, true);\n // Add to Root Node\n this._gizmoMesh = new Mesh(\"\", gizmoLayer.utilityLayerScene);\n this._gizmoMesh.addChild(arrow);\n this._gizmoMesh.addChild(collider);\n this._gizmoMesh.lookAt(this._rootMesh.position.add(dragAxis));\n this._gizmoMesh.scaling.scaleInPlace(1 / 3);\n this._gizmoMesh.parent = this._rootMesh;\n let currentSnapDragDistance = 0;\n const tmpSnapEvent = { snapDistance: 0 };\n // Add drag behavior to handle events when the gizmo is dragged\n this.dragBehavior = new PointerDragBehavior({ dragAxis: dragAxis });\n this.dragBehavior.moveAttached = false;\n this.dragBehavior.updateDragPlane = false;\n this._rootMesh.addBehavior(this.dragBehavior);\n this.dragBehavior.onDragObservable.add((event) => {\n if (this.attachedNode) {\n this._handlePivot();\n // Keep world translation and use it to update world transform\n // if the node has parent, the local transform properties (position, rotation, scale)\n // will be recomputed in _matrixChanged function\n let matrixChanged = false;\n // Snapping logic\n if (this.snapDistance == 0) {\n this.attachedNode.getWorldMatrix().getTranslationToRef(TmpVectors.Vector3[2]);\n TmpVectors.Vector3[2].addInPlace(event.delta);\n if (this.dragBehavior.validateDrag(TmpVectors.Vector3[2])) {\n if (this.attachedNode.position) {\n // Required for nodes like lights\n this.attachedNode.position.addInPlaceFromFloats(event.delta.x, event.delta.y, event.delta.z);\n }\n // use _worldMatrix to not force a matrix update when calling GetWorldMatrix especially with Cameras\n this.attachedNode.getWorldMatrix().addTranslationFromFloats(event.delta.x, event.delta.y, event.delta.z);\n this.attachedNode.updateCache();\n matrixChanged = true;\n }\n }\n else {\n currentSnapDragDistance += event.dragDistance;\n if (Math.abs(currentSnapDragDistance) > this.snapDistance) {\n const dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / this.snapDistance);\n currentSnapDragDistance = currentSnapDragDistance % this.snapDistance;\n event.delta.normalizeToRef(TmpVectors.Vector3[1]);\n TmpVectors.Vector3[1].scaleInPlace(this.snapDistance * dragSteps);\n this.attachedNode.getWorldMatrix().getTranslationToRef(TmpVectors.Vector3[2]);\n TmpVectors.Vector3[2].addInPlace(TmpVectors.Vector3[1]);\n if (this.dragBehavior.validateDrag(TmpVectors.Vector3[2])) {\n this.attachedNode.getWorldMatrix().addTranslationFromFloats(TmpVectors.Vector3[1].x, TmpVectors.Vector3[1].y, TmpVectors.Vector3[1].z);\n this.attachedNode.updateCache();\n tmpSnapEvent.snapDistance = this.snapDistance * dragSteps;\n this.onSnapObservable.notifyObservers(tmpSnapEvent);\n matrixChanged = true;\n }\n }\n }\n if (matrixChanged) {\n this._matrixChanged();\n }\n }\n });\n this.dragBehavior.onDragStartObservable.add(() => {\n this._dragging = true;\n });\n this.dragBehavior.onDragEndObservable.add(() => {\n this._dragging = false;\n });\n const light = gizmoLayer._getSharedGizmoLight();\n light.includedOnlyMeshes = light.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(false));\n const cache = {\n gizmoMeshes: arrow.getChildMeshes(),\n colliderMeshes: collider.getChildMeshes(),\n material: this._coloredMaterial,\n hoverMaterial: this._hoverMaterial,\n disableMaterial: this._disableMaterial,\n active: false,\n dragBehavior: this.dragBehavior,\n };\n (_a = this._parent) === null || _a === void 0 ? void 0 : _a.addToAxisCache(collider, cache);\n this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add((pointerInfo) => {\n var _a;\n if (this._customMeshSet) {\n return;\n }\n this._isHovered = !!(cache.colliderMeshes.indexOf((_a = pointerInfo === null || pointerInfo === void 0 ? void 0 : pointerInfo.pickInfo) === null || _a === void 0 ? void 0 : _a.pickedMesh) != -1);\n if (!this._parent) {\n const material = this.dragBehavior.enabled ? (this._isHovered || this._dragging ? this._hoverMaterial : this._coloredMaterial) : this._disableMaterial;\n this._setGizmoMeshMaterial(cache.gizmoMeshes, material);\n }\n });\n this.dragBehavior.onEnabledObservable.add((newState) => {\n this._setGizmoMeshMaterial(cache.gizmoMeshes, newState ? cache.material : cache.disableMaterial);\n });\n }\n _attachedNodeChanged(value) {\n if (this.dragBehavior) {\n this.dragBehavior.enabled = value ? true : false;\n }\n }\n /**\n * If the gizmo is enabled\n */\n set isEnabled(value) {\n this._isEnabled = value;\n if (!value) {\n this.attachedMesh = null;\n this.attachedNode = null;\n }\n else {\n if (this._parent) {\n this.attachedMesh = this._parent.attachedMesh;\n this.attachedNode = this._parent.attachedNode;\n }\n }\n }\n get isEnabled() {\n return this._isEnabled;\n }\n /**\n * Disposes of the gizmo\n */\n dispose() {\n this.onSnapObservable.clear();\n this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);\n this.dragBehavior.detach();\n if (this._gizmoMesh) {\n this._gizmoMesh.dispose();\n }\n [this._coloredMaterial, this._hoverMaterial, this._disableMaterial].forEach((matl) => {\n if (matl) {\n matl.dispose();\n }\n });\n super.dispose();\n }\n}\n//# sourceMappingURL=axisDragGizmo.js.map","import { AxesViewer } from \"../Debug/axesViewer.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Axis } from \"../Maths/math.axis.js\";\n/**\n * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh\n * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8\n */\nexport class BoneAxesViewer extends AxesViewer {\n /**\n * Creates a new BoneAxesViewer\n * @param scene defines the hosting scene\n * @param bone defines the target bone\n * @param mesh defines the target mesh\n * @param scaleLines defines a scaling factor for line length (1 by default)\n */\n constructor(scene, bone, mesh, scaleLines = 1) {\n super(scene, scaleLines);\n /** Gets current position */\n this.pos = Vector3.Zero();\n /** Gets direction of X axis */\n this.xaxis = Vector3.Zero();\n /** Gets direction of Y axis */\n this.yaxis = Vector3.Zero();\n /** Gets direction of Z axis */\n this.zaxis = Vector3.Zero();\n this.mesh = mesh;\n this.bone = bone;\n }\n /**\n * Force the viewer to update\n */\n update() {\n if (!this.mesh || !this.bone) {\n return;\n }\n const bone = this.bone;\n bone.getAbsolutePositionToRef(this.mesh, this.pos);\n bone.getDirectionToRef(Axis.X, this.mesh, this.xaxis);\n bone.getDirectionToRef(Axis.Y, this.mesh, this.yaxis);\n bone.getDirectionToRef(Axis.Z, this.mesh, this.zaxis);\n super.update(this.pos, this.xaxis, this.yaxis, this.zaxis);\n }\n /** Releases resources */\n dispose() {\n if (this.mesh) {\n this.mesh = null;\n this.bone = null;\n super.dispose();\n }\n }\n}\n//# sourceMappingURL=boneAxesViewer.js.map","import { Tools } from \"../Misc/tools.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Scene } from \"../scene.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nObject.defineProperty(Scene.prototype, \"debugLayer\", {\n get: function () {\n if (!this._debugLayer) {\n this._debugLayer = new DebugLayer(this);\n }\n return this._debugLayer;\n },\n enumerable: true,\n configurable: true,\n});\n/**\n * Enum of inspector action tab\n */\nexport var DebugLayerTab;\n(function (DebugLayerTab) {\n /**\n * Properties tag (default)\n */\n DebugLayerTab[DebugLayerTab[\"Properties\"] = 0] = \"Properties\";\n /**\n * Debug tab\n */\n DebugLayerTab[DebugLayerTab[\"Debug\"] = 1] = \"Debug\";\n /**\n * Statistics tab\n */\n DebugLayerTab[DebugLayerTab[\"Statistics\"] = 2] = \"Statistics\";\n /**\n * Tools tab\n */\n DebugLayerTab[DebugLayerTab[\"Tools\"] = 3] = \"Tools\";\n /**\n * Settings tab\n */\n DebugLayerTab[DebugLayerTab[\"Settings\"] = 4] = \"Settings\";\n})(DebugLayerTab || (DebugLayerTab = {}));\n/**\n * The debug layer (aka Inspector) is the go to tool in order to better understand\n * what is happening in your scene\n * @see https://doc.babylonjs.com/toolsAndResources/inspector\n */\nexport class DebugLayer {\n /**\n * Observable triggered when a property is changed through the inspector.\n */\n get onPropertyChangedObservable() {\n if (this.BJSINSPECTOR && this.BJSINSPECTOR.Inspector) {\n return this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable;\n }\n if (!this._onPropertyChangedObservable) {\n this._onPropertyChangedObservable = new Observable();\n }\n return this._onPropertyChangedObservable;\n }\n /**\n * Observable triggered when the selection is changed through the inspector.\n */\n get onSelectionChangedObservable() {\n if (this.BJSINSPECTOR && this.BJSINSPECTOR.Inspector) {\n return this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable;\n }\n if (!this._onSelectionChangedObservable) {\n this._onSelectionChangedObservable = new Observable();\n }\n return this._onSelectionChangedObservable;\n }\n /**\n * Instantiates a new debug layer.\n * The debug layer (aka Inspector) is the go to tool in order to better understand\n * what is happening in your scene\n * @see https://doc.babylonjs.com/toolsAndResources/inspector\n * @param scene Defines the scene to inspect\n */\n constructor(scene) {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n this.BJSINSPECTOR = this._getGlobalInspector();\n this._scene = scene || EngineStore.LastCreatedScene;\n if (!this._scene) {\n return;\n }\n this._scene.onDisposeObservable.add(() => {\n // Debug layer\n if (this._scene._debugLayer) {\n this._scene._debugLayer.hide();\n }\n });\n }\n /**\n * Creates the inspector window.\n * @param config\n */\n _createInspector(config) {\n if (this.isVisible()) {\n return;\n }\n if (this._onPropertyChangedObservable) {\n for (const observer of this._onPropertyChangedObservable.observers) {\n this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(observer);\n }\n this._onPropertyChangedObservable.clear();\n this._onPropertyChangedObservable = undefined;\n }\n if (this._onSelectionChangedObservable) {\n for (const observer of this._onSelectionChangedObservable.observers) {\n this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(observer);\n }\n this._onSelectionChangedObservable.clear();\n this._onSelectionChangedObservable = undefined;\n }\n const userOptions = Object.assign({ overlay: false, showExplorer: true, showInspector: true, embedMode: false, handleResize: true, enablePopup: true }, config);\n this.BJSINSPECTOR = this.BJSINSPECTOR || this._getGlobalInspector();\n this.BJSINSPECTOR.Inspector.Show(this._scene, userOptions);\n }\n /**\n * Select a specific entity in the scene explorer and highlight a specific block in that entity property grid\n * @param entity defines the entity to select\n * @param lineContainerTitles defines the specific blocks to highlight (could be a string or an array of strings)\n */\n select(entity, lineContainerTitles) {\n if (this.BJSINSPECTOR) {\n if (lineContainerTitles) {\n if (Object.prototype.toString.call(lineContainerTitles) == \"[object String]\") {\n this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(lineContainerTitles);\n }\n else {\n this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(lineContainerTitles);\n }\n }\n this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(entity);\n }\n }\n /** Get the inspector from bundle or global */\n _getGlobalInspector() {\n // UMD Global name detection from Webpack Bundle UMD Name.\n if (typeof INSPECTOR !== \"undefined\") {\n return INSPECTOR;\n }\n // In case of module let s check the global emitted from the Inspector entry point.\n if (typeof BABYLON !== \"undefined\" && typeof BABYLON.Inspector !== \"undefined\") {\n return BABYLON;\n }\n return undefined;\n }\n /**\n * Get if the inspector is visible or not.\n * @returns true if visible otherwise, false\n */\n isVisible() {\n return this.BJSINSPECTOR && this.BJSINSPECTOR.Inspector.IsVisible;\n }\n /**\n * Hide the inspector and close its window.\n */\n hide() {\n if (this.BJSINSPECTOR) {\n this.BJSINSPECTOR.Inspector.Hide();\n }\n }\n /**\n * Update the scene in the inspector\n */\n setAsActiveScene() {\n if (this.BJSINSPECTOR) {\n this.BJSINSPECTOR.Inspector._SetNewScene(this._scene);\n }\n }\n /**\n * Launch the debugLayer.\n * @param config Define the configuration of the inspector\n * @returns a promise fulfilled when the debug layer is visible\n */\n show(config) {\n return new Promise((resolve) => {\n if (typeof this.BJSINSPECTOR == \"undefined\") {\n const inspectorUrl = config && config.inspectorURL ? config.inspectorURL : DebugLayer.InspectorURL;\n // Load inspector and add it to the DOM\n Tools.LoadScript(inspectorUrl, () => {\n this._createInspector(config);\n resolve(this);\n });\n }\n else {\n // Otherwise creates the inspector\n this._createInspector(config);\n resolve(this);\n }\n });\n }\n}\n/**\n * Define the url to get the inspector script from.\n * By default it uses the babylonjs CDN.\n * @ignoreNaming\n */\nDebugLayer.InspectorURL = `https://unpkg.com/babylonjs-inspector@${Engine.Version}/babylon.inspector.bundle.js`;\n//# sourceMappingURL=debugLayer.js.map","import { Vector4 } from \"../../Maths/math.vector.js\";\nimport { Color4 } from \"../../Maths/math.color.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n/**\n * Creates the VertexData for a box\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * size sets the width, height and depth of the box to the value of size, optional default 1\n * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size\n * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size\n * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size\n * * faceUV an array of 6 Vector4 elements used to set different images to each box side\n * * faceColors an array of 6 Color3 elements used to set different colors to each box side\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.size\n * @param options.width\n * @param options.height\n * @param options.depth\n * @param options.faceUV\n * @param options.faceColors\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.wrap\n * @param options.topBaseAt\n * @param options.bottomBaseAt\n * @returns the VertexData of the box\n */\nexport function CreateBoxVertexData(options) {\n const nbFaces = 6;\n let indices = [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];\n const normals = [\n 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,\n 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0,\n ];\n const uvs = [];\n let positions = [];\n const width = options.width || options.size || 1;\n const height = options.height || options.size || 1;\n const depth = options.depth || options.size || 1;\n const wrap = options.wrap || false;\n let topBaseAt = options.topBaseAt === void 0 ? 1 : options.topBaseAt;\n let bottomBaseAt = options.bottomBaseAt === void 0 ? 0 : options.bottomBaseAt;\n topBaseAt = (topBaseAt + 4) % 4; // places values as 0 to 3\n bottomBaseAt = (bottomBaseAt + 4) % 4; // places values as 0 to 3\n const topOrder = [2, 0, 3, 1];\n const bottomOrder = [2, 0, 1, 3];\n let topIndex = topOrder[topBaseAt];\n let bottomIndex = bottomOrder[bottomBaseAt];\n let basePositions = [\n 1, -1, 1, -1, -1, 1, -1, 1, 1, 1, 1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, 1, 1, 1, 1, -1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1,\n 1, 1, -1, 1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1, -1, -1, -1, -1, -1, -1, -1, 1,\n ];\n if (wrap) {\n indices = [2, 3, 0, 2, 0, 1, 4, 5, 6, 4, 6, 7, 9, 10, 11, 9, 11, 8, 12, 14, 15, 12, 13, 14];\n basePositions = [\n -1, 1, 1, 1, 1, 1, 1, -1, 1, -1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1, 1, 1, 1, 1, 1, -1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1, -1, -1,\n ];\n let topFaceBase = [\n [1, 1, 1],\n [-1, 1, 1],\n [-1, 1, -1],\n [1, 1, -1],\n ];\n let bottomFaceBase = [\n [-1, -1, 1],\n [1, -1, 1],\n [1, -1, -1],\n [-1, -1, -1],\n ];\n const topFaceOrder = [17, 18, 19, 16];\n const bottomFaceOrder = [22, 23, 20, 21];\n while (topIndex > 0) {\n topFaceBase.unshift(topFaceBase.pop());\n topFaceOrder.unshift(topFaceOrder.pop());\n topIndex--;\n }\n while (bottomIndex > 0) {\n bottomFaceBase.unshift(bottomFaceBase.pop());\n bottomFaceOrder.unshift(bottomFaceOrder.pop());\n bottomIndex--;\n }\n topFaceBase = topFaceBase.flat();\n bottomFaceBase = bottomFaceBase.flat();\n basePositions = basePositions.concat(topFaceBase).concat(bottomFaceBase);\n indices.push(topFaceOrder[0], topFaceOrder[2], topFaceOrder[3], topFaceOrder[0], topFaceOrder[1], topFaceOrder[2]);\n indices.push(bottomFaceOrder[0], bottomFaceOrder[2], bottomFaceOrder[3], bottomFaceOrder[0], bottomFaceOrder[1], bottomFaceOrder[2]);\n }\n const scaleArray = [width / 2, height / 2, depth / 2];\n positions = basePositions.reduce((accumulator, currentValue, currentIndex) => accumulator.concat(currentValue * scaleArray[currentIndex % 3]), []);\n const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;\n const faceUV = options.faceUV || new Array(6);\n const faceColors = options.faceColors;\n const colors = [];\n // default face colors and UV if undefined\n for (let f = 0; f < 6; f++) {\n if (faceUV[f] === undefined) {\n faceUV[f] = new Vector4(0, 0, 1, 1);\n }\n if (faceColors && faceColors[f] === undefined) {\n faceColors[f] = new Color4(1, 1, 1, 1);\n }\n }\n // Create each face in turn.\n for (let index = 0; index < nbFaces; index++) {\n uvs.push(faceUV[index].z, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - faceUV[index].w : faceUV[index].w);\n uvs.push(faceUV[index].x, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - faceUV[index].w : faceUV[index].w);\n uvs.push(faceUV[index].x, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - faceUV[index].y : faceUV[index].y);\n uvs.push(faceUV[index].z, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - faceUV[index].y : faceUV[index].y);\n if (faceColors) {\n for (let c = 0; c < 4; c++) {\n colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);\n }\n }\n }\n // sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Result\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n if (faceColors) {\n const totalColors = sideOrientation === VertexData.DOUBLESIDE ? colors.concat(colors) : colors;\n vertexData.colors = totalColors;\n }\n return vertexData;\n}\n/**\n * Creates a box mesh\n * * The parameter `size` sets the size (float) of each box side (default 1)\n * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)\n * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 Color3 elements) and `faceUV` (an array of 6 Vector4 elements)\n * * Please read this tutorial : https://doc.babylonjs.com/features/featuresDeepDive/materials/using/texturePerBoxFace\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#box\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.size\n * @param options.width\n * @param options.height\n * @param options.depth\n * @param options.faceUV\n * @param options.faceColors\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.wrap\n * @param options.topBaseAt\n * @param options.bottomBaseAt\n * @param options.updatable\n * @param scene defines the hosting scene\n * @returns the box mesh\n */\nexport function CreateBox(name, options = {}, scene = null) {\n const box = new Mesh(name, scene);\n options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n box._originalBuilderSideOrientation = options.sideOrientation;\n const vertexData = CreateBoxVertexData(options);\n vertexData.applyToMesh(box, options.updatable);\n return box;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated please use CreateBox directly\n */\nexport const BoxBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateBox,\n};\n// Side effects\nVertexData.CreateBox = CreateBoxVertexData;\nMesh.CreateBox = (name, size, scene = null, updatable, sideOrientation) => {\n const options = {\n size,\n sideOrientation,\n updatable,\n };\n return CreateBox(name, options, scene);\n};\n//# sourceMappingURL=boxBuilder.js.map","import { TmpVectors } from \"../../Maths/math.vector.js\";\nimport { Mesh, _CreationDataStorage } from \"../mesh.js\";\nimport { VertexBuffer } from \"../../Buffers/buffer.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n/**\n * Creates the VertexData for a Ribbon\n * @param options an object used to set the following optional parameters for the ribbon, required but can be empty\n * * pathArray array of paths, each of which an array of successive Vector3\n * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false\n * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false\n * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false\n * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional\n * * colors a linear array, of length 4 * number of vertices, of custom color values, optional\n * @param options.pathArray\n * @param options.closeArray\n * @param options.closePath\n * @param options.offset\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.invertUV\n * @param options.uvs\n * @param options.colors\n * @returns the VertexData of the ribbon\n */\nexport function CreateRibbonVertexData(options) {\n let pathArray = options.pathArray;\n const closeArray = options.closeArray || false;\n const closePath = options.closePath || false;\n const invertUV = options.invertUV || false;\n const defaultOffset = Math.floor(pathArray[0].length / 2);\n let offset = options.offset || defaultOffset;\n offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset\n const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;\n const customUV = options.uvs;\n const customColors = options.colors;\n const positions = [];\n const indices = [];\n const normals = [];\n const uvs = [];\n const us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id\n const vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutive paths from pathArray\n const uTotalDistance = []; // uTotalDistance[p] : total distance of path p\n const vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray\n let minlg; // minimal length among all paths from pathArray\n const lg = []; // array of path lengths : nb of vertex per path\n const idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number\n let p; // path iterator\n let i; // point iterator\n let j; // point iterator\n // if single path in pathArray\n if (pathArray.length < 2) {\n const ar1 = [];\n const ar2 = [];\n for (i = 0; i < pathArray[0].length - offset; i++) {\n ar1.push(pathArray[0][i]);\n ar2.push(pathArray[0][i + offset]);\n }\n pathArray = [ar1, ar2];\n }\n // positions and horizontal distances (u)\n let idc = 0;\n const closePathCorr = closePath ? 1 : 0; // the final index will be +1 if closePath\n let path;\n let l;\n minlg = pathArray[0].length;\n let vectlg;\n let dist;\n for (p = 0; p < pathArray.length; p++) {\n uTotalDistance[p] = 0;\n us[p] = [0];\n path = pathArray[p];\n l = path.length;\n minlg = minlg < l ? minlg : l;\n j = 0;\n while (j < l) {\n positions.push(path[j].x, path[j].y, path[j].z);\n if (j > 0) {\n vectlg = path[j].subtract(path[j - 1]).length();\n dist = vectlg + uTotalDistance[p];\n us[p].push(dist);\n uTotalDistance[p] = dist;\n }\n j++;\n }\n if (closePath) {\n // an extra hidden vertex is added in the \"positions\" array\n j--;\n positions.push(path[0].x, path[0].y, path[0].z);\n vectlg = path[j].subtract(path[0]).length();\n dist = vectlg + uTotalDistance[p];\n us[p].push(dist);\n uTotalDistance[p] = dist;\n }\n lg[p] = l + closePathCorr;\n idx[p] = idc;\n idc += l + closePathCorr;\n }\n // vertical distances (v)\n let path1;\n let path2;\n let vertex1 = null;\n let vertex2 = null;\n for (i = 0; i < minlg + closePathCorr; i++) {\n vTotalDistance[i] = 0;\n vs[i] = [0];\n for (p = 0; p < pathArray.length - 1; p++) {\n path1 = pathArray[p];\n path2 = pathArray[p + 1];\n if (i === minlg) {\n // closePath\n vertex1 = path1[0];\n vertex2 = path2[0];\n }\n else {\n vertex1 = path1[i];\n vertex2 = path2[i];\n }\n vectlg = vertex2.subtract(vertex1).length();\n dist = vectlg + vTotalDistance[i];\n vs[i].push(dist);\n vTotalDistance[i] = dist;\n }\n if (closeArray && vertex2 && vertex1) {\n path1 = pathArray[p];\n path2 = pathArray[0];\n if (i === minlg) {\n // closePath\n vertex2 = path2[0];\n }\n vectlg = vertex2.subtract(vertex1).length();\n dist = vectlg + vTotalDistance[i];\n vTotalDistance[i] = dist;\n }\n }\n // uvs\n let u;\n let v;\n if (customUV) {\n for (p = 0; p < customUV.length; p++) {\n uvs.push(customUV[p].x, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - customUV[p].y : customUV[p].y);\n }\n }\n else {\n for (p = 0; p < pathArray.length; p++) {\n for (i = 0; i < minlg + closePathCorr; i++) {\n u = uTotalDistance[p] != 0.0 ? us[p][i] / uTotalDistance[p] : 0.0;\n v = vTotalDistance[i] != 0.0 ? vs[i][p] / vTotalDistance[i] : 0.0;\n if (invertUV) {\n uvs.push(v, u);\n }\n else {\n uvs.push(u, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - v : v);\n }\n }\n }\n }\n // indices\n p = 0; // path index\n let pi = 0; // positions array index\n let l1 = lg[p] - 1; // path1 length\n let l2 = lg[p + 1] - 1; // path2 length\n let min = l1 < l2 ? l1 : l2; // current path stop index\n let shft = idx[1] - idx[0]; // shift\n const path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate\ton\n while (pi <= min && p < path1nb) {\n // stay under min and don't go over next to last path\n // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise\n indices.push(pi, pi + shft, pi + 1);\n indices.push(pi + shft + 1, pi + 1, pi + shft);\n pi += 1;\n if (pi === min) {\n // if end of one of two consecutive paths reached, go to next existing path\n p++;\n if (p === lg.length - 1) {\n // last path of pathArray reached <=> closeArray == true\n shft = idx[0] - idx[p];\n l1 = lg[p] - 1;\n l2 = lg[0] - 1;\n }\n else {\n shft = idx[p + 1] - idx[p];\n l1 = lg[p] - 1;\n l2 = lg[p + 1] - 1;\n }\n pi = idx[p];\n min = l1 < l2 ? l1 + pi : l2 + pi;\n }\n }\n // normals\n VertexData.ComputeNormals(positions, indices, normals);\n if (closePath) {\n // update both the first and last vertex normals to their average value\n let indexFirst = 0;\n let indexLast = 0;\n for (p = 0; p < pathArray.length; p++) {\n indexFirst = idx[p] * 3;\n if (p + 1 < pathArray.length) {\n indexLast = (idx[p + 1] - 1) * 3;\n }\n else {\n indexLast = normals.length - 3;\n }\n normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;\n normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;\n normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;\n normals[indexLast] = normals[indexFirst];\n normals[indexLast + 1] = normals[indexFirst + 1];\n normals[indexLast + 2] = normals[indexFirst + 2];\n }\n }\n // sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Colors\n let colors = null;\n if (customColors) {\n colors = new Float32Array(customColors.length * 4);\n for (let c = 0; c < customColors.length; c++) {\n colors[c * 4] = customColors[c].r;\n colors[c * 4 + 1] = customColors[c].g;\n colors[c * 4 + 2] = customColors[c].b;\n colors[c * 4 + 3] = customColors[c].a;\n }\n }\n // Result\n const vertexData = new VertexData();\n const positions32 = new Float32Array(positions);\n const normals32 = new Float32Array(normals);\n const uvs32 = new Float32Array(uvs);\n vertexData.indices = indices;\n vertexData.positions = positions32;\n vertexData.normals = normals32;\n vertexData.uvs = uvs32;\n if (colors) {\n vertexData.set(colors, VertexBuffer.ColorKind);\n }\n if (closePath) {\n vertexData._idx = idx;\n }\n return vertexData;\n}\n/**\n * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters\n * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry\n * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array\n * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array\n * * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path\n * * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11\n * * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#ribbon\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture\n * * The parameter `uvs` is an optional flat array of `Vector2` to update/set each ribbon vertex with its own custom UV values instead of the computed ones\n * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values\n * * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that if you set `closePath` to `true`, there's one extra vertex per path in the geometry\n * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.pathArray\n * @param options.closeArray\n * @param options.closePath\n * @param options.offset\n * @param options.updatable\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.instance\n * @param options.invertUV\n * @param options.uvs\n * @param options.colors\n * @param scene defines the hosting scene\n * @returns the ribbon mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param/ribbon_extra\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param\n */\nexport function CreateRibbon(name, options, scene = null) {\n const pathArray = options.pathArray;\n const closeArray = options.closeArray;\n const closePath = options.closePath;\n const sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n const instance = options.instance;\n const updatable = options.updatable;\n if (instance) {\n // existing ribbon instance update\n // positionFunction : ribbon case\n // only pathArray and sideOrientation parameters are taken into account for positions update\n const minimum = TmpVectors.Vector3[0].setAll(Number.MAX_VALUE);\n const maximum = TmpVectors.Vector3[1].setAll(-Number.MAX_VALUE);\n const positionFunction = (positions) => {\n let minlg = pathArray[0].length;\n const mesh = instance;\n let i = 0;\n const ns = mesh._originalBuilderSideOrientation === Mesh.DOUBLESIDE ? 2 : 1;\n for (let si = 1; si <= ns; ++si) {\n for (let p = 0; p < pathArray.length; ++p) {\n const path = pathArray[p];\n const l = path.length;\n minlg = minlg < l ? minlg : l;\n for (let j = 0; j < minlg; ++j) {\n const pathPoint = path[j];\n positions[i] = pathPoint.x;\n positions[i + 1] = pathPoint.y;\n positions[i + 2] = pathPoint.z;\n minimum.minimizeInPlaceFromFloats(pathPoint.x, pathPoint.y, pathPoint.z);\n maximum.maximizeInPlaceFromFloats(pathPoint.x, pathPoint.y, pathPoint.z);\n i += 3;\n }\n if (mesh._creationDataStorage && mesh._creationDataStorage.closePath) {\n const pathPoint = path[0];\n positions[i] = pathPoint.x;\n positions[i + 1] = pathPoint.y;\n positions[i + 2] = pathPoint.z;\n i += 3;\n }\n }\n }\n };\n const positions = instance.getVerticesData(VertexBuffer.PositionKind);\n positionFunction(positions);\n if (instance.hasBoundingInfo) {\n instance.getBoundingInfo().reConstruct(minimum, maximum, instance._worldMatrix);\n }\n else {\n instance.buildBoundingInfo(minimum, maximum, instance._worldMatrix);\n }\n instance.updateVerticesData(VertexBuffer.PositionKind, positions, false, false);\n if (options.colors) {\n const colors = instance.getVerticesData(VertexBuffer.ColorKind);\n for (let c = 0, colorIndex = 0; c < options.colors.length; c++, colorIndex += 4) {\n const color = options.colors[c];\n colors[colorIndex] = color.r;\n colors[colorIndex + 1] = color.g;\n colors[colorIndex + 2] = color.b;\n colors[colorIndex + 3] = color.a;\n }\n instance.updateVerticesData(VertexBuffer.ColorKind, colors, false, false);\n }\n if (options.uvs) {\n const uvs = instance.getVerticesData(VertexBuffer.UVKind);\n for (let i = 0; i < options.uvs.length; i++) {\n uvs[i * 2] = options.uvs[i].x;\n uvs[i * 2 + 1] = CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - options.uvs[i].y : options.uvs[i].y;\n }\n instance.updateVerticesData(VertexBuffer.UVKind, uvs, false, false);\n }\n if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {\n const indices = instance.getIndices();\n const normals = instance.getVerticesData(VertexBuffer.NormalKind);\n const params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;\n VertexData.ComputeNormals(positions, indices, normals, params);\n if (instance._creationDataStorage && instance._creationDataStorage.closePath) {\n let indexFirst = 0;\n let indexLast = 0;\n for (let p = 0; p < pathArray.length; p++) {\n indexFirst = instance._creationDataStorage.idx[p] * 3;\n if (p + 1 < pathArray.length) {\n indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3;\n }\n else {\n indexLast = normals.length - 3;\n }\n normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;\n normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;\n normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;\n normals[indexLast] = normals[indexFirst];\n normals[indexLast + 1] = normals[indexFirst + 1];\n normals[indexLast + 2] = normals[indexFirst + 2];\n }\n }\n if (!instance.areNormalsFrozen) {\n instance.updateVerticesData(VertexBuffer.NormalKind, normals, false, false);\n }\n }\n return instance;\n }\n else {\n // new ribbon creation\n const ribbon = new Mesh(name, scene);\n ribbon._originalBuilderSideOrientation = sideOrientation;\n ribbon._creationDataStorage = new _CreationDataStorage();\n const vertexData = CreateRibbonVertexData(options);\n if (closePath) {\n ribbon._creationDataStorage.idx = vertexData._idx;\n }\n ribbon._creationDataStorage.closePath = closePath;\n ribbon._creationDataStorage.closeArray = closeArray;\n vertexData.applyToMesh(ribbon, updatable);\n return ribbon;\n }\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use CreateRibbon directly\n */\nexport const RibbonBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateRibbon,\n};\nVertexData.CreateRibbon = CreateRibbonVertexData;\nMesh.CreateRibbon = (name, pathArray, closeArray = false, closePath, offset, scene, updatable = false, sideOrientation, instance) => {\n return CreateRibbon(name, {\n pathArray: pathArray,\n closeArray: closeArray,\n closePath: closePath,\n offset: offset,\n updatable: updatable,\n sideOrientation: sideOrientation,\n instance: instance,\n }, scene);\n};\n//# sourceMappingURL=ribbonBuilder.js.map","import { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n// based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473\n/**\n * Creates the VertexData for a TorusKnot\n * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty\n * * radius the radius of the torus knot, optional, default 2\n * * tube the thickness of the tube, optional, default 0.5\n * * radialSegments the number of sides on each tube segments, optional, default 32\n * * tubularSegments the number of tubes to decompose the knot into, optional, default 32\n * * p the number of windings around the z axis, optional, default 2\n * * q the number of windings around the x axis, optional, default 3\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.radius\n * @param options.tube\n * @param options.radialSegments\n * @param options.tubularSegments\n * @param options.p\n * @param options.q\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the Torus Knot\n */\nexport function CreateTorusKnotVertexData(options) {\n const indices = new Array();\n const positions = new Array();\n const normals = new Array();\n const uvs = new Array();\n const radius = options.radius || 2;\n const tube = options.tube || 0.5;\n const radialSegments = options.radialSegments || 32;\n const tubularSegments = options.tubularSegments || 32;\n const p = options.p || 2;\n const q = options.q || 3;\n const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;\n // Helper\n const getPos = (angle) => {\n const cu = Math.cos(angle);\n const su = Math.sin(angle);\n const quOverP = (q / p) * angle;\n const cs = Math.cos(quOverP);\n const tx = radius * (2 + cs) * 0.5 * cu;\n const ty = radius * (2 + cs) * su * 0.5;\n const tz = radius * Math.sin(quOverP) * 0.5;\n return new Vector3(tx, ty, tz);\n };\n // Vertices\n let i;\n let j;\n for (i = 0; i <= radialSegments; i++) {\n const modI = i % radialSegments;\n const u = (modI / radialSegments) * 2 * p * Math.PI;\n const p1 = getPos(u);\n const p2 = getPos(u + 0.01);\n const tang = p2.subtract(p1);\n let n = p2.add(p1);\n const bitan = Vector3.Cross(tang, n);\n n = Vector3.Cross(bitan, tang);\n bitan.normalize();\n n.normalize();\n for (j = 0; j < tubularSegments; j++) {\n const modJ = j % tubularSegments;\n const v = (modJ / tubularSegments) * 2 * Math.PI;\n const cx = -tube * Math.cos(v);\n const cy = tube * Math.sin(v);\n positions.push(p1.x + cx * n.x + cy * bitan.x);\n positions.push(p1.y + cx * n.y + cy * bitan.y);\n positions.push(p1.z + cx * n.z + cy * bitan.z);\n uvs.push(i / radialSegments);\n uvs.push(CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - j / tubularSegments : j / tubularSegments);\n }\n }\n for (i = 0; i < radialSegments; i++) {\n for (j = 0; j < tubularSegments; j++) {\n const jNext = (j + 1) % tubularSegments;\n const a = i * tubularSegments + j;\n const b = (i + 1) * tubularSegments + j;\n const c = (i + 1) * tubularSegments + jNext;\n const d = i * tubularSegments + jNext;\n indices.push(d);\n indices.push(b);\n indices.push(a);\n indices.push(d);\n indices.push(c);\n indices.push(b);\n }\n }\n // Normals\n VertexData.ComputeNormals(positions, indices, normals);\n // Sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Result\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n}\n/**\n * Creates a torus knot mesh\n * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)\n * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)\n * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)\n * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.radius\n * @param options.tube\n * @param options.radialSegments\n * @param options.tubularSegments\n * @param options.p\n * @param options.q\n * @param options.updatable\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param scene defines the hosting scene\n * @returns the torus knot mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#torus-knot\n */\nexport function CreateTorusKnot(name, options = {}, scene) {\n const torusKnot = new Mesh(name, scene);\n options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n torusKnot._originalBuilderSideOrientation = options.sideOrientation;\n const vertexData = CreateTorusKnotVertexData(options);\n vertexData.applyToMesh(torusKnot, options.updatable);\n return torusKnot;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use CreateTorusKnot instead\n */\nexport const TorusKnotBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateTorusKnot,\n};\nVertexData.CreateTorusKnot = CreateTorusKnotVertexData;\nMesh.CreateTorusKnot = (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) => {\n const options = {\n radius,\n tube,\n radialSegments,\n tubularSegments,\n p,\n q,\n sideOrientation,\n updatable,\n };\n return CreateTorusKnot(name, options, scene);\n};\n//# sourceMappingURL=torusKnotBuilder.js.map","import { Vector3, Matrix } from \"../../Maths/math.vector.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n/**\n * Creates the VertexData for an ellipsoid, defaults to a sphere\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * segments sets the number of horizontal strips optional, default 32\n * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1\n * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter\n * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter\n * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter\n * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1\n * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.segments\n * @param options.diameter\n * @param options.diameterX\n * @param options.diameterY\n * @param options.diameterZ\n * @param options.arc\n * @param options.slice\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.dedupTopBottomIndices\n * @returns the VertexData of the ellipsoid\n */\nexport function CreateSphereVertexData(options) {\n const segments = options.segments || 32;\n const diameterX = options.diameterX || options.diameter || 1;\n const diameterY = options.diameterY || options.diameter || 1;\n const diameterZ = options.diameterZ || options.diameter || 1;\n const arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;\n const slice = options.slice && options.slice <= 0 ? 1.0 : options.slice || 1.0;\n const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;\n const dedupTopBottomIndices = !!options.dedupTopBottomIndices;\n const radius = new Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);\n const totalZRotationSteps = 2 + segments;\n const totalYRotationSteps = 2 * totalZRotationSteps;\n const indices = [];\n const positions = [];\n const normals = [];\n const uvs = [];\n for (let zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {\n const normalizedZ = zRotationStep / totalZRotationSteps;\n const angleZ = normalizedZ * Math.PI * slice;\n for (let yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {\n const normalizedY = yRotationStep / totalYRotationSteps;\n const angleY = normalizedY * Math.PI * 2 * arc;\n const rotationZ = Matrix.RotationZ(-angleZ);\n const rotationY = Matrix.RotationY(angleY);\n const afterRotZ = Vector3.TransformCoordinates(Vector3.Up(), rotationZ);\n const complete = Vector3.TransformCoordinates(afterRotZ, rotationY);\n const vertex = complete.multiply(radius);\n const normal = complete.divide(radius).normalize();\n positions.push(vertex.x, vertex.y, vertex.z);\n normals.push(normal.x, normal.y, normal.z);\n uvs.push(normalizedY, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - normalizedZ : normalizedZ);\n }\n if (zRotationStep > 0) {\n const verticesCount = positions.length / 3;\n for (let firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); firstIndex + totalYRotationSteps + 2 < verticesCount; firstIndex++) {\n if (dedupTopBottomIndices) {\n if (zRotationStep > 1) {\n indices.push(firstIndex);\n indices.push(firstIndex + 1);\n indices.push(firstIndex + totalYRotationSteps + 1);\n }\n if (zRotationStep < totalZRotationSteps || slice < 1.0) {\n indices.push(firstIndex + totalYRotationSteps + 1);\n indices.push(firstIndex + 1);\n indices.push(firstIndex + totalYRotationSteps + 2);\n }\n }\n else {\n indices.push(firstIndex);\n indices.push(firstIndex + 1);\n indices.push(firstIndex + totalYRotationSteps + 1);\n indices.push(firstIndex + totalYRotationSteps + 1);\n indices.push(firstIndex + 1);\n indices.push(firstIndex + totalYRotationSteps + 2);\n }\n }\n }\n }\n // Sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Result\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n}\n/**\n * Creates a sphere mesh\n * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)\n * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value of `diameter`)\n * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)\n * * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio\n * * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude)\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.segments\n * @param options.diameter\n * @param options.diameterX\n * @param options.diameterY\n * @param options.diameterZ\n * @param options.arc\n * @param options.slice\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.updatable\n * @param scene defines the hosting scene\n * @returns the sphere mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#sphere\n */\nexport function CreateSphere(name, options = {}, scene = null) {\n const sphere = new Mesh(name, scene);\n options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n sphere._originalBuilderSideOrientation = options.sideOrientation;\n const vertexData = CreateSphereVertexData(options);\n vertexData.applyToMesh(sphere, options.updatable);\n return sphere;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use CreateSphere directly\n */\nexport const SphereBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateSphere,\n};\nVertexData.CreateSphere = CreateSphereVertexData;\nMesh.CreateSphere = (name, segments, diameter, scene, updatable, sideOrientation) => {\n const options = {\n segments: segments,\n diameterX: diameter,\n diameterY: diameter,\n diameterZ: diameter,\n sideOrientation: sideOrientation,\n updatable: updatable,\n };\n return CreateSphere(name, options, scene);\n};\n//# sourceMappingURL=sphereBuilder.js.map","import { VertexData } from \"../mesh.vertexData.js\";\nimport { Vector2, Vector3, Matrix } from \"../../Maths/math.vector.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n/**\n * Scripts based off of https://github.com/maximeq/three-js-capsule-geometry/blob/master/src/CapsuleBufferGeometry.js\n * @param options the constructors options used to shape the mesh.\n * @returns the capsule VertexData\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/capsule\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function CreateCapsuleVertexData(options = {\n subdivisions: 2,\n tessellation: 16,\n height: 1,\n radius: 0.25,\n capSubdivisions: 6,\n}) {\n const subdivisions = Math.max(options.subdivisions ? options.subdivisions : 2, 1);\n const tessellation = Math.max(options.tessellation ? options.tessellation : 16, 3);\n const height = Math.max(options.height ? options.height : 1, 0);\n const radius = Math.max(options.radius ? options.radius : 0.25, 0);\n const capDetail = Math.max(options.capSubdivisions ? options.capSubdivisions : 6, 1);\n const radialSegments = tessellation;\n const heightSegments = subdivisions;\n const radiusTop = Math.max(options.radiusTop ? options.radiusTop : radius, 0);\n const radiusBottom = Math.max(options.radiusBottom ? options.radiusBottom : radius, 0);\n const heightMinusCaps = height - (radiusTop + radiusBottom);\n const thetaStart = 0.0;\n const thetaLength = 2.0 * Math.PI;\n const capsTopSegments = Math.max(options.topCapSubdivisions ? options.topCapSubdivisions : capDetail, 1);\n const capsBottomSegments = Math.max(options.bottomCapSubdivisions ? options.bottomCapSubdivisions : capDetail, 1);\n const alpha = Math.acos((radiusBottom - radiusTop) / height);\n let indices = [];\n const vertices = [];\n const normals = [];\n const uvs = [];\n let index = 0;\n const indexArray = [], halfHeight = heightMinusCaps * 0.5;\n const pi2 = Math.PI * 0.5;\n let x, y;\n const normal = Vector3.Zero();\n const vertex = Vector3.Zero();\n const cosAlpha = Math.cos(alpha);\n const sinAlpha = Math.sin(alpha);\n const coneLength = new Vector2(radiusTop * sinAlpha, halfHeight + radiusTop * cosAlpha)\n .subtract(new Vector2(radiusBottom * sinAlpha, -halfHeight + radiusBottom * cosAlpha))\n .length();\n // Total length for v texture coord\n const vl = radiusTop * alpha + coneLength + radiusBottom * (pi2 - alpha);\n let v = 0;\n for (y = 0; y <= capsTopSegments; y++) {\n const indexRow = [];\n const a = pi2 - alpha * (y / capsTopSegments);\n v += (radiusTop * alpha) / capsTopSegments;\n const cosA = Math.cos(a);\n const sinA = Math.sin(a);\n // calculate the radius of the current row\n const _radius = cosA * radiusTop;\n for (x = 0; x <= radialSegments; x++) {\n const u = x / radialSegments;\n const theta = u * thetaLength + thetaStart;\n const sinTheta = Math.sin(theta);\n const cosTheta = Math.cos(theta);\n // vertex\n vertex.x = _radius * sinTheta;\n vertex.y = halfHeight + sinA * radiusTop;\n vertex.z = _radius * cosTheta;\n vertices.push(vertex.x, vertex.y, vertex.z);\n // normal\n normal.set(cosA * sinTheta, sinA, cosA * cosTheta);\n normals.push(normal.x, normal.y, normal.z);\n // uv\n uvs.push(u, CompatibilityOptions.UseOpenGLOrientationForUV ? v / vl : 1 - v / vl);\n // save index of vertex in respective row\n indexRow.push(index);\n // increase index\n index++;\n }\n // now save vertices of the row in our index array\n indexArray.push(indexRow);\n }\n const coneHeight = height - radiusTop - radiusBottom + cosAlpha * radiusTop - cosAlpha * radiusBottom;\n const slope = (sinAlpha * (radiusBottom - radiusTop)) / coneHeight;\n for (y = 1; y <= heightSegments; y++) {\n const indexRow = [];\n v += coneLength / heightSegments;\n // calculate the radius of the current row\n const _radius = sinAlpha * ((y * (radiusBottom - radiusTop)) / heightSegments + radiusTop);\n for (x = 0; x <= radialSegments; x++) {\n const u = x / radialSegments;\n const theta = u * thetaLength + thetaStart;\n const sinTheta = Math.sin(theta);\n const cosTheta = Math.cos(theta);\n // vertex\n vertex.x = _radius * sinTheta;\n vertex.y = halfHeight + cosAlpha * radiusTop - (y * coneHeight) / heightSegments;\n vertex.z = _radius * cosTheta;\n vertices.push(vertex.x, vertex.y, vertex.z);\n // normal\n normal.set(sinTheta, slope, cosTheta).normalize();\n normals.push(normal.x, normal.y, normal.z);\n // uv\n uvs.push(u, CompatibilityOptions.UseOpenGLOrientationForUV ? v / vl : 1 - v / vl);\n // save index of vertex in respective row\n indexRow.push(index);\n // increase index\n index++;\n }\n // now save vertices of the row in our index array\n indexArray.push(indexRow);\n }\n for (y = 1; y <= capsBottomSegments; y++) {\n const indexRow = [];\n const a = pi2 - alpha - (Math.PI - alpha) * (y / capsBottomSegments);\n v += (radiusBottom * alpha) / capsBottomSegments;\n const cosA = Math.cos(a);\n const sinA = Math.sin(a);\n // calculate the radius of the current row\n const _radius = cosA * radiusBottom;\n for (x = 0; x <= radialSegments; x++) {\n const u = x / radialSegments;\n const theta = u * thetaLength + thetaStart;\n const sinTheta = Math.sin(theta);\n const cosTheta = Math.cos(theta);\n // vertex\n vertex.x = _radius * sinTheta;\n vertex.y = -halfHeight + sinA * radiusBottom;\n vertex.z = _radius * cosTheta;\n vertices.push(vertex.x, vertex.y, vertex.z);\n // normal\n normal.set(cosA * sinTheta, sinA, cosA * cosTheta);\n normals.push(normal.x, normal.y, normal.z);\n // uv\n uvs.push(u, CompatibilityOptions.UseOpenGLOrientationForUV ? v / vl : 1 - v / vl);\n // save index of vertex in respective row\n indexRow.push(index);\n // increase index\n index++;\n }\n // now save vertices of the row in our index array\n indexArray.push(indexRow);\n }\n // generate indices\n for (x = 0; x < radialSegments; x++) {\n for (y = 0; y < capsTopSegments + heightSegments + capsBottomSegments; y++) {\n // we use the index array to access the correct indices\n const i1 = indexArray[y][x];\n const i2 = indexArray[y + 1][x];\n const i3 = indexArray[y + 1][x + 1];\n const i4 = indexArray[y][x + 1];\n // face one\n indices.push(i1);\n indices.push(i2);\n indices.push(i4);\n // face two\n indices.push(i2);\n indices.push(i3);\n indices.push(i4);\n }\n }\n indices = indices.reverse();\n if (options.orientation && !options.orientation.equals(Vector3.Up())) {\n const m = new Matrix();\n options.orientation\n .clone()\n .scale(Math.PI * 0.5)\n .cross(Vector3.Up())\n .toQuaternion()\n .toRotationMatrix(m);\n const v = Vector3.Zero();\n for (let i = 0; i < vertices.length; i += 3) {\n v.set(vertices[i], vertices[i + 1], vertices[i + 2]);\n Vector3.TransformCoordinatesToRef(v.clone(), m, v);\n vertices[i] = v.x;\n vertices[i + 1] = v.y;\n vertices[i + 2] = v.z;\n }\n }\n const vDat = new VertexData();\n vDat.positions = vertices;\n vDat.normals = normals;\n vDat.uvs = uvs;\n vDat.indices = indices;\n return vDat;\n}\n/**\n * Creates a capsule or a pill mesh\n * @param name defines the name of the mesh\n * @param options The constructors options.\n * @param scene The scene the mesh is scoped to.\n * @returns Capsule Mesh\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function CreateCapsule(name, options = {\n orientation: Vector3.Up(),\n subdivisions: 2,\n tessellation: 16,\n height: 1,\n radius: 0.25,\n capSubdivisions: 6,\n updatable: false,\n}, scene = null) {\n const capsule = new Mesh(name, scene);\n const vertexData = CreateCapsuleVertexData(options);\n vertexData.applyToMesh(capsule, options.updatable);\n return capsule;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated please use CreateCapsule directly\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const CapsuleBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateCapsule,\n};\n/**\n * Creates a capsule or a pill mesh\n * @param name defines the name of the mesh.\n * @param options the constructors options used to shape the mesh.\n * @param scene defines the scene the mesh is scoped to.\n * @returns the capsule mesh\n * @see https://doc.babylonjs.com/how_to/capsule_shape\n */\nMesh.CreateCapsule = (name, options, scene) => {\n return CreateCapsule(name, options, scene);\n};\nVertexData.CreateCapsule = CreateCapsuleVertexData;\n//# sourceMappingURL=capsuleBuilder.js.map","import { Mesh } from \"../mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n/**\n * Creates the VertexData of the Disc or regular Polygon\n * @param options an object used to set the following optional parameters for the disc, required but can be empty\n * * radius the radius of the disc, optional default 0.5\n * * tessellation the number of polygon sides, optional, default 64\n * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.radius\n * @param options.tessellation\n * @param options.arc\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the box\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function CreateDiscVertexData(options) {\n const positions = new Array();\n const indices = new Array();\n const normals = new Array();\n const uvs = new Array();\n const radius = options.radius || 0.5;\n const tessellation = options.tessellation || 64;\n const arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;\n const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;\n // positions and uvs\n positions.push(0, 0, 0); // disc center first\n uvs.push(0.5, 0.5);\n const theta = Math.PI * 2 * arc;\n const step = arc === 1 ? theta / tessellation : theta / (tessellation - 1);\n let a = 0;\n for (let t = 0; t < tessellation; t++) {\n const x = Math.cos(a);\n const y = Math.sin(a);\n const u = (x + 1) / 2;\n const v = (1 - y) / 2;\n positions.push(radius * x, radius * y, 0);\n uvs.push(u, CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v);\n a += step;\n }\n if (arc === 1) {\n positions.push(positions[3], positions[4], positions[5]); // close the circle\n uvs.push(uvs[2], CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - uvs[3] : uvs[3]);\n }\n //indices\n const vertexNb = positions.length / 3;\n for (let i = 1; i < vertexNb - 1; i++) {\n indices.push(i + 1, 0, i);\n }\n // result\n VertexData.ComputeNormals(positions, indices, normals);\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n}\n/**\n * Creates a plane polygonal mesh. By default, this is a disc\n * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)\n * * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc\n * * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.radius\n * @param options.tessellation\n * @param options.arc\n * @param options.updatable\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param scene defines the hosting scene\n * @returns the plane polygonal mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#disc-or-regular-polygon\n */\nexport function CreateDisc(name, options = {}, scene = null) {\n const disc = new Mesh(name, scene);\n options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n disc._originalBuilderSideOrientation = options.sideOrientation;\n const vertexData = CreateDiscVertexData(options);\n vertexData.applyToMesh(disc, options.updatable);\n return disc;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated please use CreateDisc directly\n */\nexport const DiscBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateDisc,\n};\nVertexData.CreateDisc = CreateDiscVertexData;\nMesh.CreateDisc = (name, radius, tessellation, scene = null, updatable, sideOrientation) => {\n const options = {\n radius,\n tessellation,\n sideOrientation,\n updatable,\n };\n return CreateDisc(name, options, scene);\n};\n//# sourceMappingURL=discBuilder.js.map","import { Mesh } from \"../mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\n/**\n * Creates the VertexData for a tiled plane\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/tiled_plane\n * @param options an object used to set the following optional parameters for the tiled plane, required but can be empty\n * * pattern a limited pattern arrangement depending on the number\n * * size of the box\n * * width of the box, overwrites size\n * * height of the box, overwrites size\n * * tileSize sets the width, height and depth of the tile to the value of size, optional default 1\n * * tileWidth sets the width (x direction) of the tile, overwrites the width set by size, optional, default size\n * * tileHeight sets the height (y direction) of the tile, overwrites the height set by size, optional, default size\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * alignHorizontal places whole tiles aligned to the center, left or right of a row\n * * alignVertical places whole tiles aligned to the center, left or right of a column\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * @param options.pattern\n * @param options.tileSize\n * @param options.tileWidth\n * @param options.tileHeight\n * @param options.size\n * @param options.width\n * @param options.height\n * @param options.alignHorizontal\n * @param options.alignVertical\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @returns the VertexData of the tiled plane\n */\nexport function CreateTiledPlaneVertexData(options) {\n const flipTile = options.pattern || Mesh.NO_FLIP;\n const tileWidth = options.tileWidth || options.tileSize || 1;\n const tileHeight = options.tileHeight || options.tileSize || 1;\n const alignH = options.alignHorizontal || 0;\n const alignV = options.alignVertical || 0;\n const width = options.width || options.size || 1;\n const tilesX = Math.floor(width / tileWidth);\n let offsetX = width - tilesX * tileWidth;\n const height = options.height || options.size || 1;\n const tilesY = Math.floor(height / tileHeight);\n let offsetY = height - tilesY * tileHeight;\n const halfWidth = (tileWidth * tilesX) / 2;\n const halfHeight = (tileHeight * tilesY) / 2;\n let adjustX = 0;\n let adjustY = 0;\n let startX = 0;\n let startY = 0;\n let endX = 0;\n let endY = 0;\n //Part Tiles\n if (offsetX > 0 || offsetY > 0) {\n startX = -halfWidth;\n startY = -halfHeight;\n endX = halfWidth;\n endY = halfHeight;\n switch (alignH) {\n case Mesh.CENTER:\n offsetX /= 2;\n startX -= offsetX;\n endX += offsetX;\n break;\n case Mesh.LEFT:\n endX += offsetX;\n adjustX = -offsetX / 2;\n break;\n case Mesh.RIGHT:\n startX -= offsetX;\n adjustX = offsetX / 2;\n break;\n }\n switch (alignV) {\n case Mesh.CENTER:\n offsetY /= 2;\n startY -= offsetY;\n endY += offsetY;\n break;\n case Mesh.BOTTOM:\n endY += offsetY;\n adjustY = -offsetY / 2;\n break;\n case Mesh.TOP:\n startY -= offsetY;\n adjustY = offsetY / 2;\n break;\n }\n }\n const positions = [];\n const normals = [];\n const uvBase = [];\n uvBase[0] = [0, 0, 1, 0, 1, 1, 0, 1];\n uvBase[1] = [0, 0, 1, 0, 1, 1, 0, 1];\n if (flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.ROTATE_ROW) {\n uvBase[1] = [1, 1, 0, 1, 0, 0, 1, 0];\n }\n if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.FLIP_ROW) {\n uvBase[1] = [1, 0, 0, 0, 0, 1, 1, 1];\n }\n if (flipTile === Mesh.FLIP_N_ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_ROW) {\n uvBase[1] = [0, 1, 1, 1, 1, 0, 0, 0];\n }\n let uvs = [];\n const colors = [];\n const indices = [];\n let index = 0;\n for (let y = 0; y < tilesY; y++) {\n for (let x = 0; x < tilesX; x++) {\n positions.push(-halfWidth + x * tileWidth + adjustX, -halfHeight + y * tileHeight + adjustY, 0);\n positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, -halfHeight + y * tileHeight + adjustY, 0);\n positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0);\n positions.push(-halfWidth + x * tileWidth + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0);\n indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);\n if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_TILE) {\n uvs = uvs.concat(uvBase[((x % 2) + (y % 2)) % 2]);\n }\n else if (flipTile === Mesh.FLIP_ROW || flipTile === Mesh.ROTATE_ROW || flipTile === Mesh.FLIP_N_ROTATE_ROW) {\n uvs = uvs.concat(uvBase[y % 2]);\n }\n else {\n uvs = uvs.concat(uvBase[0]);\n }\n colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);\n normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);\n index += 4;\n }\n }\n //Part Tiles\n if (offsetX > 0 || offsetY > 0) {\n const partialBottomRow = offsetY > 0 && (alignV === Mesh.CENTER || alignV === Mesh.TOP);\n const partialTopRow = offsetY > 0 && (alignV === Mesh.CENTER || alignV === Mesh.BOTTOM);\n const partialLeftCol = offsetX > 0 && (alignH === Mesh.CENTER || alignH === Mesh.RIGHT);\n const partialRightCol = offsetX > 0 && (alignH === Mesh.CENTER || alignH === Mesh.LEFT);\n let uvPart = [];\n let a, b, c, d;\n //corners\n if (partialBottomRow && partialLeftCol) {\n //bottom left corner\n positions.push(startX + adjustX, startY + adjustY, 0);\n positions.push(-halfWidth + adjustX, startY + adjustY, 0);\n positions.push(-halfWidth + adjustX, startY + offsetY + adjustY, 0);\n positions.push(startX + adjustX, startY + offsetY + adjustY, 0);\n indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);\n index += 4;\n a = 1 - offsetX / tileWidth;\n b = 1 - offsetY / tileHeight;\n c = 1;\n d = 1;\n uvPart = [a, b, c, b, c, d, a, d];\n if (flipTile === Mesh.ROTATE_ROW) {\n uvPart = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d];\n }\n if (flipTile === Mesh.FLIP_ROW) {\n uvPart = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d];\n }\n if (flipTile === Mesh.FLIP_N_ROTATE_ROW) {\n uvPart = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d];\n }\n uvs = uvs.concat(uvPart);\n colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);\n normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);\n }\n if (partialBottomRow && partialRightCol) {\n //bottom right corner\n positions.push(halfWidth + adjustX, startY + adjustY, 0);\n positions.push(endX + adjustX, startY + adjustY, 0);\n positions.push(endX + adjustX, startY + offsetY + adjustY, 0);\n positions.push(halfWidth + adjustX, startY + offsetY + adjustY, 0);\n indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);\n index += 4;\n a = 0;\n b = 1 - offsetY / tileHeight;\n c = offsetX / tileWidth;\n d = 1;\n uvPart = [a, b, c, b, c, d, a, d];\n if (flipTile === Mesh.ROTATE_ROW || (flipTile === Mesh.ROTATE_TILE && tilesX % 2 === 0)) {\n uvPart = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d];\n }\n if (flipTile === Mesh.FLIP_ROW || (flipTile === Mesh.FLIP_TILE && tilesX % 2 === 0)) {\n uvPart = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d];\n }\n if (flipTile === Mesh.FLIP_N_ROTATE_ROW || (flipTile === Mesh.FLIP_N_ROTATE_TILE && tilesX % 2 === 0)) {\n uvPart = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d];\n }\n uvs = uvs.concat(uvPart);\n colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);\n normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);\n }\n if (partialTopRow && partialLeftCol) {\n //top left corner\n positions.push(startX + adjustX, halfHeight + adjustY, 0);\n positions.push(-halfWidth + adjustX, halfHeight + adjustY, 0);\n positions.push(-halfWidth + adjustX, endY + adjustY, 0);\n positions.push(startX + adjustX, endY + adjustY, 0);\n indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);\n index += 4;\n a = 1 - offsetX / tileWidth;\n b = 0;\n c = 1;\n d = offsetY / tileHeight;\n uvPart = [a, b, c, b, c, d, a, d];\n if ((flipTile === Mesh.ROTATE_ROW && tilesY % 2 === 1) || (flipTile === Mesh.ROTATE_TILE && tilesY % 1 === 0)) {\n uvPart = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d];\n }\n if ((flipTile === Mesh.FLIP_ROW && tilesY % 2 === 1) || (flipTile === Mesh.FLIP_TILE && tilesY % 2 === 0)) {\n uvPart = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d];\n }\n if ((flipTile === Mesh.FLIP_N_ROTATE_ROW && tilesY % 2 === 1) || (flipTile === Mesh.FLIP_N_ROTATE_TILE && tilesY % 2 === 0)) {\n uvPart = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d];\n }\n uvs = uvs.concat(uvPart);\n colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);\n normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);\n }\n if (partialTopRow && partialRightCol) {\n //top right corner\n positions.push(halfWidth + adjustX, halfHeight + adjustY, 0);\n positions.push(endX + adjustX, halfHeight + adjustY, 0);\n positions.push(endX + adjustX, endY + adjustY, 0);\n positions.push(halfWidth + adjustX, endY + adjustY, 0);\n indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);\n index += 4;\n a = 0;\n b = 0;\n c = offsetX / tileWidth;\n d = offsetY / tileHeight;\n uvPart = [a, b, c, b, c, d, a, d];\n if ((flipTile === Mesh.ROTATE_ROW && tilesY % 2 === 1) || (flipTile === Mesh.ROTATE_TILE && (tilesY + tilesX) % 2 === 1)) {\n uvPart = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d];\n }\n if ((flipTile === Mesh.FLIP_ROW && tilesY % 2 === 1) || (flipTile === Mesh.FLIP_TILE && (tilesY + tilesX) % 2 === 1)) {\n uvPart = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d];\n }\n if ((flipTile === Mesh.FLIP_N_ROTATE_ROW && tilesY % 2 === 1) || (flipTile === Mesh.FLIP_N_ROTATE_TILE && (tilesY + tilesX) % 2 === 1)) {\n uvPart = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d];\n }\n uvs = uvs.concat(uvPart);\n colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);\n normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);\n }\n //part rows\n if (partialBottomRow) {\n const uvBaseBR = [];\n a = 0;\n b = 1 - offsetY / tileHeight;\n c = 1;\n d = 1;\n uvBaseBR[0] = [a, b, c, b, c, d, a, d];\n uvBaseBR[1] = [a, b, c, b, c, d, a, d];\n if (flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.ROTATE_ROW) {\n uvBaseBR[1] = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d];\n }\n if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.FLIP_ROW) {\n uvBaseBR[1] = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d];\n }\n if (flipTile === Mesh.FLIP_N_ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_ROW) {\n uvBaseBR[1] = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d];\n }\n for (let x = 0; x < tilesX; x++) {\n positions.push(-halfWidth + x * tileWidth + adjustX, startY + adjustY, 0);\n positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, startY + adjustY, 0);\n positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, startY + offsetY + adjustY, 0);\n positions.push(-halfWidth + x * tileWidth + adjustX, startY + offsetY + adjustY, 0);\n indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);\n index += 4;\n if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_TILE) {\n uvs = uvs.concat(uvBaseBR[(x + 1) % 2]);\n }\n else if (flipTile === Mesh.FLIP_ROW || flipTile === Mesh.ROTATE_ROW || flipTile === Mesh.FLIP_N_ROTATE_ROW) {\n uvs = uvs.concat(uvBaseBR[1]);\n }\n else {\n uvs = uvs.concat(uvBaseBR[0]);\n }\n colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);\n normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);\n }\n }\n if (partialTopRow) {\n const uvBaseTR = [];\n a = 0;\n b = 0;\n c = 1;\n d = offsetY / tileHeight;\n uvBaseTR[0] = [a, b, c, b, c, d, a, d];\n uvBaseTR[1] = [a, b, c, b, c, d, a, d];\n if (flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.ROTATE_ROW) {\n uvBaseTR[1] = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d];\n }\n if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.FLIP_ROW) {\n uvBaseTR[1] = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d];\n }\n if (flipTile === Mesh.FLIP_N_ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_ROW) {\n uvBaseTR[1] = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d];\n }\n for (let x = 0; x < tilesX; x++) {\n positions.push(-halfWidth + x * tileWidth + adjustX, endY - offsetY + adjustY, 0);\n positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, endY - offsetY + adjustY, 0);\n positions.push(-halfWidth + (x + 1) * tileWidth + adjustX, endY + adjustY, 0);\n positions.push(-halfWidth + x * tileWidth + adjustX, endY + adjustY, 0);\n indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);\n index += 4;\n if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_TILE) {\n uvs = uvs.concat(uvBaseTR[(x + tilesY) % 2]);\n }\n else if (flipTile === Mesh.FLIP_ROW || flipTile === Mesh.ROTATE_ROW || flipTile === Mesh.FLIP_N_ROTATE_ROW) {\n uvs = uvs.concat(uvBaseTR[tilesY % 2]);\n }\n else {\n uvs = uvs.concat(uvBaseTR[0]);\n }\n colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);\n normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);\n }\n }\n if (partialLeftCol) {\n const uvBaseLC = [];\n a = 1 - offsetX / tileWidth;\n b = 0;\n c = 1;\n d = 1;\n uvBaseLC[0] = [a, b, c, b, c, d, a, d];\n uvBaseLC[1] = [a, b, c, b, c, d, a, d];\n if (flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.ROTATE_ROW) {\n uvBaseLC[1] = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d];\n }\n if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.FLIP_ROW) {\n uvBaseLC[1] = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d];\n }\n if (flipTile === Mesh.FLIP_N_ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_ROW) {\n uvBaseLC[1] = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d];\n }\n for (let y = 0; y < tilesY; y++) {\n positions.push(startX + adjustX, -halfHeight + y * tileHeight + adjustY, 0);\n positions.push(startX + offsetX + adjustX, -halfHeight + y * tileHeight + adjustY, 0);\n positions.push(startX + offsetX + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0);\n positions.push(startX + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0);\n indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);\n index += 4;\n if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_TILE) {\n uvs = uvs.concat(uvBaseLC[(y + 1) % 2]);\n }\n else if (flipTile === Mesh.FLIP_ROW || flipTile === Mesh.ROTATE_ROW || flipTile === Mesh.FLIP_N_ROTATE_ROW) {\n uvs = uvs.concat(uvBaseLC[y % 2]);\n }\n else {\n uvs = uvs.concat(uvBaseLC[0]);\n }\n colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);\n normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);\n }\n }\n if (partialRightCol) {\n const uvBaseRC = [];\n a = 0;\n b = 0;\n c = offsetX / tileHeight;\n d = 1;\n uvBaseRC[0] = [a, b, c, b, c, d, a, d];\n uvBaseRC[1] = [a, b, c, b, c, d, a, d];\n if (flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.ROTATE_ROW) {\n uvBaseRC[1] = [1 - a, 1 - b, 1 - c, 1 - b, 1 - c, 1 - d, 1 - a, 1 - d];\n }\n if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.FLIP_ROW) {\n uvBaseRC[1] = [1 - a, b, 1 - c, b, 1 - c, d, 1 - a, d];\n }\n if (flipTile === Mesh.FLIP_N_ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_ROW) {\n uvBaseRC[1] = [a, 1 - b, c, 1 - b, c, 1 - d, a, 1 - d];\n }\n for (let y = 0; y < tilesY; y++) {\n positions.push(endX - offsetX + adjustX, -halfHeight + y * tileHeight + adjustY, 0);\n positions.push(endX + adjustX, -halfHeight + y * tileHeight + adjustY, 0);\n positions.push(endX + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0);\n positions.push(endX - offsetX + adjustX, -halfHeight + (y + 1) * tileHeight + adjustY, 0);\n indices.push(index, index + 1, index + 3, index + 1, index + 2, index + 3);\n index += 4;\n if (flipTile === Mesh.FLIP_TILE || flipTile === Mesh.ROTATE_TILE || flipTile === Mesh.FLIP_N_ROTATE_TILE) {\n uvs = uvs.concat(uvBaseRC[(y + tilesX) % 2]);\n }\n else if (flipTile === Mesh.FLIP_ROW || flipTile === Mesh.ROTATE_ROW || flipTile === Mesh.FLIP_N_ROTATE_ROW) {\n uvs = uvs.concat(uvBaseRC[y % 2]);\n }\n else {\n uvs = uvs.concat(uvBaseRC[0]);\n }\n colors.push(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);\n normals.push(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1);\n }\n }\n }\n const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;\n // sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n // Result\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n const totalColors = sideOrientation === VertexData.DOUBLESIDE ? colors.concat(colors) : colors;\n vertexData.colors = totalColors;\n return vertexData;\n}\n/**\n * Creates a tiled plane mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/tiled_plane\n * @param name defines the name of the mesh\n * @param options an object used to set the following optional parameters for the tiled plane, required but can be empty\n * * pattern a limited pattern arrangement depending on the number\n * * size of the box\n * * width of the box, overwrites size\n * * height of the box, overwrites size\n * * tileSize sets the width, height and depth of the tile to the value of size, optional default 1\n * * tileWidth sets the width (x direction) of the tile, overwrites the width set by size, optional, default size\n * * tileHeight sets the height (y direction) of the tile, overwrites the height set by size, optional, default size\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * alignHorizontal places whole tiles aligned to the center, left or right of a row\n * * alignVertical places whole tiles aligned to the center, left or right of a column\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.pattern\n * @param options.tileSize\n * @param options.tileWidth\n * @param options.tileHeight\n * @param options.size\n * @param options.width\n * @param options.height\n * @param options.alignHorizontal\n * @param options.alignVertical\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.updatable\n * @param scene defines the hosting scene\n * @returns the box mesh\n */\nexport function CreateTiledPlane(name, options, scene = null) {\n const plane = new Mesh(name, scene);\n options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n plane._originalBuilderSideOrientation = options.sideOrientation;\n const vertexData = CreateTiledPlaneVertexData(options);\n vertexData.applyToMesh(plane, options.updatable);\n return plane;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use CreateTiledPlane instead\n */\nexport const TiledPlaneBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateTiledPlane,\n};\nVertexData.CreateTiledPlane = CreateTiledPlaneVertexData;\n//# sourceMappingURL=tiledPlaneBuilder.js.map","import { SerializationHelper } from \"../Misc/decorators.js\";\nimport { Matrix, Vector3, Vector2, Vector4, Quaternion } from \"../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { MaterialHelper } from \"./materialHelper.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\nimport { Color3, Color4 } from \"../Maths/math.color.js\";\nimport { EffectFallbacks } from \"./effectFallbacks.js\";\nimport { WebRequest } from \"../Misc/webRequest.js\";\nimport { PushMaterial } from \"./pushMaterial.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n\nimport { addClipPlaneUniforms, bindClipPlane, prepareStringDefinesForClipPlanes } from \"./clipPlaneMaterialHelper.js\";\nconst onCreatedEffectParameters = { effect: null, subMesh: null };\n/**\n * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.\n *\n * This returned material effects how the mesh will look based on the code in the shaders.\n *\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/shaders/shaderMaterial\n */\nexport class ShaderMaterial extends PushMaterial {\n /**\n * Instantiate a new shader material.\n * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.\n * This returned material effects how the mesh will look based on the code in the shaders.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/shaders/shaderMaterial\n * @param name Define the name of the material in the scene\n * @param scene Define the scene the material belongs to\n * @param shaderPath Defines the route to the shader code in one of three ways:\n * * object: \\{ vertex: \"custom\", fragment: \"custom\" \\}, used with Effect.ShadersStore[\"customVertexShader\"] and Effect.ShadersStore[\"customFragmentShader\"]\n * * object: \\{ vertexElement: \"vertexShaderCode\", fragmentElement: \"fragmentShaderCode\" \\}, used with shader code in script tags\n * * object: \\{ vertexSource: \"vertex shader code string\", fragmentSource: \"fragment shader code string\" \\} using with strings containing the shaders code\n * * string: \"./COMMON_NAME\", used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in index.html folder.\n * @param options Define the options used to create the shader\n * @param storeEffectOnSubMeshes true to store effect on submeshes, false to store the effect directly in the material class.\n */\n constructor(name, scene, shaderPath, options = {}, storeEffectOnSubMeshes = true) {\n super(name, scene, storeEffectOnSubMeshes);\n this._textures = {};\n this._textureArrays = {};\n this._externalTextures = {};\n this._floats = {};\n this._ints = {};\n this._uints = {};\n this._floatsArrays = {};\n this._colors3 = {};\n this._colors3Arrays = {};\n this._colors4 = {};\n this._colors4Arrays = {};\n this._vectors2 = {};\n this._vectors3 = {};\n this._vectors4 = {};\n this._quaternions = {};\n this._quaternionsArrays = {};\n this._matrices = {};\n this._matrixArrays = {};\n this._matrices3x3 = {};\n this._matrices2x2 = {};\n this._vectors2Arrays = {};\n this._vectors3Arrays = {};\n this._vectors4Arrays = {};\n this._uniformBuffers = {};\n this._textureSamplers = {};\n this._storageBuffers = {};\n this._cachedWorldViewMatrix = new Matrix();\n this._cachedWorldViewProjectionMatrix = new Matrix();\n this._multiview = false;\n /**\n * @internal\n */\n this._materialHelperNeedsPreviousMatrices = false;\n this._shaderPath = shaderPath;\n this._options = Object.assign({ needAlphaBlending: false, needAlphaTesting: false, attributes: [\"position\", \"normal\", \"uv\"], uniforms: [\"worldViewProjection\"], uniformBuffers: [], samplers: [], externalTextures: [], samplerObjects: [], storageBuffers: [], defines: [], useClipPlane: false }, options);\n }\n /**\n * Gets the shader path used to define the shader code\n * It can be modified to trigger a new compilation\n */\n get shaderPath() {\n return this._shaderPath;\n }\n /**\n * Sets the shader path used to define the shader code\n * It can be modified to trigger a new compilation\n */\n set shaderPath(shaderPath) {\n this._shaderPath = shaderPath;\n }\n /**\n * Gets the options used to compile the shader.\n * They can be modified to trigger a new compilation\n */\n get options() {\n return this._options;\n }\n /**\n * is multiview set to true?\n */\n get isMultiview() {\n return this._multiview;\n }\n /**\n * Gets the current class name of the material e.g. \"ShaderMaterial\"\n * Mainly use in serialization.\n * @returns the class name\n */\n getClassName() {\n return \"ShaderMaterial\";\n }\n /**\n * Specifies if the material will require alpha blending\n * @returns a boolean specifying if alpha blending is needed\n */\n needAlphaBlending() {\n return this.alpha < 1.0 || this._options.needAlphaBlending;\n }\n /**\n * Specifies if this material should be rendered in alpha test mode\n * @returns a boolean specifying if an alpha test is needed.\n */\n needAlphaTesting() {\n return this._options.needAlphaTesting;\n }\n _checkUniform(uniformName) {\n if (this._options.uniforms.indexOf(uniformName) === -1) {\n this._options.uniforms.push(uniformName);\n }\n }\n /**\n * Set a texture in the shader.\n * @param name Define the name of the uniform samplers as defined in the shader\n * @param texture Define the texture to bind to this sampler\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setTexture(name, texture) {\n if (this._options.samplers.indexOf(name) === -1) {\n this._options.samplers.push(name);\n }\n this._textures[name] = texture;\n return this;\n }\n /**\n * Set a texture array in the shader.\n * @param name Define the name of the uniform sampler array as defined in the shader\n * @param textures Define the list of textures to bind to this sampler\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setTextureArray(name, textures) {\n if (this._options.samplers.indexOf(name) === -1) {\n this._options.samplers.push(name);\n }\n this._checkUniform(name);\n this._textureArrays[name] = textures;\n return this;\n }\n /**\n * Set an internal texture in the shader.\n * @param name Define the name of the uniform samplers as defined in the shader\n * @param texture Define the texture to bind to this sampler\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setExternalTexture(name, texture) {\n if (this._options.externalTextures.indexOf(name) === -1) {\n this._options.externalTextures.push(name);\n }\n this._externalTextures[name] = texture;\n return this;\n }\n /**\n * Set a float in the shader.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setFloat(name, value) {\n this._checkUniform(name);\n this._floats[name] = value;\n return this;\n }\n /**\n * Set a int in the shader.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setInt(name, value) {\n this._checkUniform(name);\n this._ints[name] = value;\n return this;\n }\n /**\n * Set a unsigned int in the shader.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setUInt(name, value) {\n this._checkUniform(name);\n this._uints[name] = value;\n return this;\n }\n /**\n * Set an array of floats in the shader.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setFloats(name, value) {\n this._checkUniform(name);\n this._floatsArrays[name] = value;\n return this;\n }\n /**\n * Set a vec3 in the shader from a Color3.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setColor3(name, value) {\n this._checkUniform(name);\n this._colors3[name] = value;\n return this;\n }\n /**\n * Set a vec3 array in the shader from a Color3 array.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setColor3Array(name, value) {\n this._checkUniform(name);\n this._colors3Arrays[name] = value.reduce((arr, color) => {\n color.toArray(arr, arr.length);\n return arr;\n }, []);\n return this;\n }\n /**\n * Set a vec4 in the shader from a Color4.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setColor4(name, value) {\n this._checkUniform(name);\n this._colors4[name] = value;\n return this;\n }\n /**\n * Set a vec4 array in the shader from a Color4 array.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setColor4Array(name, value) {\n this._checkUniform(name);\n this._colors4Arrays[name] = value.reduce((arr, color) => {\n color.toArray(arr, arr.length);\n return arr;\n }, []);\n return this;\n }\n /**\n * Set a vec2 in the shader from a Vector2.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setVector2(name, value) {\n this._checkUniform(name);\n this._vectors2[name] = value;\n return this;\n }\n /**\n * Set a vec3 in the shader from a Vector3.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setVector3(name, value) {\n this._checkUniform(name);\n this._vectors3[name] = value;\n return this;\n }\n /**\n * Set a vec4 in the shader from a Vector4.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setVector4(name, value) {\n this._checkUniform(name);\n this._vectors4[name] = value;\n return this;\n }\n /**\n * Set a vec4 in the shader from a Quaternion.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setQuaternion(name, value) {\n this._checkUniform(name);\n this._quaternions[name] = value;\n return this;\n }\n /**\n * Set a vec4 array in the shader from a Quaternion array.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setQuaternionArray(name, value) {\n this._checkUniform(name);\n this._quaternionsArrays[name] = value.reduce((arr, quaternion) => {\n quaternion.toArray(arr, arr.length);\n return arr;\n }, []);\n return this;\n }\n /**\n * Set a mat4 in the shader from a Matrix.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setMatrix(name, value) {\n this._checkUniform(name);\n this._matrices[name] = value;\n return this;\n }\n /**\n * Set a float32Array in the shader from a matrix array.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setMatrices(name, value) {\n this._checkUniform(name);\n const float32Array = new Float32Array(value.length * 16);\n for (let index = 0; index < value.length; index++) {\n const matrix = value[index];\n matrix.copyToArray(float32Array, index * 16);\n }\n this._matrixArrays[name] = float32Array;\n return this;\n }\n /**\n * Set a mat3 in the shader from a Float32Array.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setMatrix3x3(name, value) {\n this._checkUniform(name);\n this._matrices3x3[name] = value;\n return this;\n }\n /**\n * Set a mat2 in the shader from a Float32Array.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setMatrix2x2(name, value) {\n this._checkUniform(name);\n this._matrices2x2[name] = value;\n return this;\n }\n /**\n * Set a vec2 array in the shader from a number array.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setArray2(name, value) {\n this._checkUniform(name);\n this._vectors2Arrays[name] = value;\n return this;\n }\n /**\n * Set a vec3 array in the shader from a number array.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setArray3(name, value) {\n this._checkUniform(name);\n this._vectors3Arrays[name] = value;\n return this;\n }\n /**\n * Set a vec4 array in the shader from a number array.\n * @param name Define the name of the uniform as defined in the shader\n * @param value Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setArray4(name, value) {\n this._checkUniform(name);\n this._vectors4Arrays[name] = value;\n return this;\n }\n /**\n * Set a uniform buffer in the shader\n * @param name Define the name of the uniform as defined in the shader\n * @param buffer Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setUniformBuffer(name, buffer) {\n if (this._options.uniformBuffers.indexOf(name) === -1) {\n this._options.uniformBuffers.push(name);\n }\n this._uniformBuffers[name] = buffer;\n return this;\n }\n /**\n * Set a texture sampler in the shader\n * @param name Define the name of the uniform as defined in the shader\n * @param sampler Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setTextureSampler(name, sampler) {\n if (this._options.samplerObjects.indexOf(name) === -1) {\n this._options.samplerObjects.push(name);\n }\n this._textureSamplers[name] = sampler;\n return this;\n }\n /**\n * Set a storage buffer in the shader\n * @param name Define the name of the storage buffer as defined in the shader\n * @param buffer Define the value to give to the uniform\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setStorageBuffer(name, buffer) {\n if (this._options.storageBuffers.indexOf(name) === -1) {\n this._options.storageBuffers.push(name);\n }\n this._storageBuffers[name] = buffer;\n return this;\n }\n /**\n * Adds, removes, or replaces the specified shader define and value.\n * * setDefine(\"MY_DEFINE\", true); // enables a boolean define\n * * setDefine(\"MY_DEFINE\", \"0.5\"); // adds \"#define MY_DEFINE 0.5\" to the shader (or sets and replaces the value of any existing define with that name)\n * * setDefine(\"MY_DEFINE\", false); // disables and removes the define\n * Note if the active defines do change, the shader will be recompiled and this can be expensive.\n * @param define the define name e.g., \"OUTPUT_TO_SRGB\" or \"#define OUTPUT_TO_SRGB\". If the define was passed into the constructor already, the version used should match that, and in either case, it should not include any appended value.\n * @param value either the value of the define (e.g. a numerical value) or for booleans, true if the define should be enabled or false if it should be disabled\n * @returns the material itself allowing \"fluent\" like uniform updates\n */\n setDefine(define, value) {\n // First remove any existing define with this name.\n const defineName = define.trimEnd() + \" \";\n const existingDefineIdx = this.options.defines.findIndex((x) => x === define || x.startsWith(defineName));\n if (existingDefineIdx >= 0) {\n this.options.defines.splice(existingDefineIdx, 1);\n }\n // Then add the new define value. (If it's a boolean value and false, don't add it.)\n if (typeof value !== \"boolean\" || value) {\n this.options.defines.push(defineName + value);\n }\n return this;\n }\n /**\n * Specifies that the submesh is ready to be used\n * @param mesh defines the mesh to check\n * @param subMesh defines which submesh to check\n * @param useInstances specifies that instances should be used\n * @returns a boolean indicating that the submesh is ready or not\n */\n isReadyForSubMesh(mesh, subMesh, useInstances) {\n return this.isReady(mesh, useInstances, subMesh);\n }\n /**\n * Checks if the material is ready to render the requested mesh\n * @param mesh Define the mesh to render\n * @param useInstances Define whether or not the material is used with instances\n * @param subMesh defines which submesh to render\n * @returns true if ready, otherwise false\n */\n isReady(mesh, useInstances, subMesh) {\n var _a, _b, _c, _d;\n const storeEffectOnSubMeshes = subMesh && this._storeEffectOnSubMeshes;\n if (this.isFrozen) {\n if (storeEffectOnSubMeshes) {\n if (subMesh.effect && subMesh.effect._wasPreviouslyReady) {\n return true;\n }\n }\n else {\n const effect = this._drawWrapper.effect;\n if (effect && effect._wasPreviouslyReady && effect._wasPreviouslyUsingInstances === useInstances) {\n return true;\n }\n }\n }\n const scene = this.getScene();\n const engine = scene.getEngine();\n // Instances\n const defines = [];\n const attribs = [];\n const fallbacks = new EffectFallbacks();\n let shaderName = this._shaderPath, uniforms = this._options.uniforms, uniformBuffers = this._options.uniformBuffers, samplers = this._options.samplers;\n // global multiview\n if (engine.getCaps().multiview && scene.activeCamera && scene.activeCamera.outputRenderTarget && scene.activeCamera.outputRenderTarget.getViewCount() > 1) {\n this._multiview = true;\n defines.push(\"#define MULTIVIEW\");\n if (this._options.uniforms.indexOf(\"viewProjection\") !== -1 && this._options.uniforms.indexOf(\"viewProjectionR\") === -1) {\n this._options.uniforms.push(\"viewProjectionR\");\n }\n }\n for (let index = 0; index < this._options.defines.length; index++) {\n const defineToAdd = this._options.defines[index].indexOf(\"#define\") === 0 ? this._options.defines[index] : `#define ${this._options.defines[index]}`;\n defines.push(defineToAdd);\n }\n for (let index = 0; index < this._options.attributes.length; index++) {\n attribs.push(this._options.attributes[index]);\n }\n if (mesh && mesh.isVerticesDataPresent(VertexBuffer.ColorKind)) {\n attribs.push(VertexBuffer.ColorKind);\n defines.push(\"#define VERTEXCOLOR\");\n }\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n MaterialHelper.PushAttributesForInstances(attribs, this._materialHelperNeedsPreviousMatrices);\n if (mesh === null || mesh === void 0 ? void 0 : mesh.hasThinInstances) {\n defines.push(\"#define THIN_INSTANCES\");\n if (mesh && mesh.isVerticesDataPresent(VertexBuffer.ColorInstanceKind)) {\n attribs.push(VertexBuffer.ColorInstanceKind);\n defines.push(\"#define INSTANCESCOLOR\");\n }\n }\n }\n // Bones\n if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {\n attribs.push(VertexBuffer.MatricesIndicesKind);\n attribs.push(VertexBuffer.MatricesWeightsKind);\n if (mesh.numBoneInfluencers > 4) {\n attribs.push(VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(VertexBuffer.MatricesWeightsExtraKind);\n }\n const skeleton = mesh.skeleton;\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n fallbacks.addCPUSkinningFallback(0, mesh);\n if (skeleton.isUsingTextureForMatrices) {\n defines.push(\"#define BONETEXTURE\");\n if (this._options.uniforms.indexOf(\"boneTextureWidth\") === -1) {\n this._options.uniforms.push(\"boneTextureWidth\");\n }\n if (this._options.samplers.indexOf(\"boneSampler\") === -1) {\n this._options.samplers.push(\"boneSampler\");\n }\n }\n else {\n defines.push(\"#define BonesPerMesh \" + (skeleton.bones.length + 1));\n if (this._options.uniforms.indexOf(\"mBones\") === -1) {\n this._options.uniforms.push(\"mBones\");\n }\n }\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Morph\n let numInfluencers = 0;\n const manager = mesh ? mesh.morphTargetManager : null;\n if (manager) {\n const uv = manager.supportsUVs && defines.indexOf(\"#define UV1\") !== -1;\n const tangent = manager.supportsTangents && defines.indexOf(\"#define TANGENT\") !== -1;\n const normal = manager.supportsNormals && defines.indexOf(\"#define NORMAL\") !== -1;\n numInfluencers = manager.numInfluencers;\n if (uv) {\n defines.push(\"#define MORPHTARGETS_UV\");\n }\n if (tangent) {\n defines.push(\"#define MORPHTARGETS_TANGENT\");\n }\n if (normal) {\n defines.push(\"#define MORPHTARGETS_NORMAL\");\n }\n if (numInfluencers > 0) {\n defines.push(\"#define MORPHTARGETS\");\n }\n if (manager.isUsingTextureForTargets) {\n defines.push(\"#define MORPHTARGETS_TEXTURE\");\n if (this._options.uniforms.indexOf(\"morphTargetTextureIndices\") === -1) {\n this._options.uniforms.push(\"morphTargetTextureIndices\");\n }\n if (this._options.samplers.indexOf(\"morphTargets\") === -1) {\n this._options.samplers.push(\"morphTargets\");\n }\n }\n defines.push(\"#define NUM_MORPH_INFLUENCERS \" + numInfluencers);\n for (let index = 0; index < numInfluencers; index++) {\n attribs.push(VertexBuffer.PositionKind + index);\n if (normal) {\n attribs.push(VertexBuffer.NormalKind + index);\n }\n if (tangent) {\n attribs.push(VertexBuffer.TangentKind + index);\n }\n if (uv) {\n attribs.push(VertexBuffer.UVKind + \"_\" + index);\n }\n }\n if (numInfluencers > 0) {\n uniforms = uniforms.slice();\n uniforms.push(\"morphTargetInfluences\");\n uniforms.push(\"morphTargetTextureInfo\");\n uniforms.push(\"morphTargetTextureIndices\");\n }\n }\n else {\n defines.push(\"#define NUM_MORPH_INFLUENCERS 0\");\n }\n // Baked Vertex Animation\n if (mesh) {\n const bvaManager = mesh.bakedVertexAnimationManager;\n if (bvaManager && bvaManager.isEnabled) {\n defines.push(\"#define BAKED_VERTEX_ANIMATION_TEXTURE\");\n if (this._options.uniforms.indexOf(\"bakedVertexAnimationSettings\") === -1) {\n this._options.uniforms.push(\"bakedVertexAnimationSettings\");\n }\n if (this._options.uniforms.indexOf(\"bakedVertexAnimationTextureSizeInverted\") === -1) {\n this._options.uniforms.push(\"bakedVertexAnimationTextureSizeInverted\");\n }\n if (this._options.uniforms.indexOf(\"bakedVertexAnimationTime\") === -1) {\n this._options.uniforms.push(\"bakedVertexAnimationTime\");\n }\n if (this._options.samplers.indexOf(\"bakedVertexAnimationTexture\") === -1) {\n this._options.samplers.push(\"bakedVertexAnimationTexture\");\n }\n }\n MaterialHelper.PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines);\n }\n // Textures\n for (const name in this._textures) {\n if (!this._textures[name].isReady()) {\n return false;\n }\n }\n // Alpha test\n if (mesh && this._shouldTurnAlphaTestOn(mesh)) {\n defines.push(\"#define ALPHATEST\");\n }\n // Clip planes\n if (this._options.useClipPlane !== false) {\n addClipPlaneUniforms(uniforms);\n prepareStringDefinesForClipPlanes(this, scene, defines);\n }\n if (this.customShaderNameResolve) {\n uniforms = uniforms.slice();\n uniformBuffers = uniformBuffers.slice();\n samplers = samplers.slice();\n shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines, attribs);\n }\n const drawWrapper = storeEffectOnSubMeshes ? subMesh._getDrawWrapper() : this._drawWrapper;\n const previousEffect = (_a = drawWrapper === null || drawWrapper === void 0 ? void 0 : drawWrapper.effect) !== null && _a !== void 0 ? _a : null;\n const previousDefines = (_b = drawWrapper === null || drawWrapper === void 0 ? void 0 : drawWrapper.defines) !== null && _b !== void 0 ? _b : null;\n const join = defines.join(\"\\n\");\n let effect = previousEffect;\n if (previousDefines !== join) {\n effect = engine.createEffect(shaderName, {\n attributes: attribs,\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: join,\n fallbacks: fallbacks,\n onCompiled: this.onCompiled,\n onError: this.onError,\n indexParameters: { maxSimultaneousMorphTargets: numInfluencers },\n shaderLanguage: this._options.shaderLanguage,\n }, engine);\n if (storeEffectOnSubMeshes) {\n subMesh.setEffect(effect, join, this._materialContext);\n }\n else if (drawWrapper) {\n drawWrapper.setEffect(effect, join);\n }\n if (this._onEffectCreatedObservable) {\n onCreatedEffectParameters.effect = effect;\n onCreatedEffectParameters.subMesh = (_c = subMesh !== null && subMesh !== void 0 ? subMesh : mesh === null || mesh === void 0 ? void 0 : mesh.subMeshes[0]) !== null && _c !== void 0 ? _c : null;\n this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters);\n }\n }\n effect._wasPreviouslyUsingInstances = !!useInstances;\n if ((_d = !(effect === null || effect === void 0 ? void 0 : effect.isReady())) !== null && _d !== void 0 ? _d : true) {\n return false;\n }\n if (previousEffect !== effect) {\n scene.resetCachedMaterial();\n }\n effect._wasPreviouslyReady = true;\n return true;\n }\n /**\n * Binds the world matrix to the material\n * @param world defines the world transformation matrix\n * @param effectOverride - If provided, use this effect instead of internal effect\n */\n bindOnlyWorldMatrix(world, effectOverride) {\n const scene = this.getScene();\n const effect = effectOverride !== null && effectOverride !== void 0 ? effectOverride : this.getEffect();\n if (!effect) {\n return;\n }\n if (this._options.uniforms.indexOf(\"world\") !== -1) {\n effect.setMatrix(\"world\", world);\n }\n if (this._options.uniforms.indexOf(\"worldView\") !== -1) {\n world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);\n effect.setMatrix(\"worldView\", this._cachedWorldViewMatrix);\n }\n if (this._options.uniforms.indexOf(\"worldViewProjection\") !== -1) {\n world.multiplyToRef(scene.getTransformMatrix(), this._cachedWorldViewProjectionMatrix);\n effect.setMatrix(\"worldViewProjection\", this._cachedWorldViewProjectionMatrix);\n }\n }\n /**\n * Binds the submesh to this material by preparing the effect and shader to draw\n * @param world defines the world transformation matrix\n * @param mesh defines the mesh containing the submesh\n * @param subMesh defines the submesh to bind the material to\n */\n bindForSubMesh(world, mesh, subMesh) {\n var _a;\n this.bind(world, mesh, (_a = subMesh._drawWrapperOverride) === null || _a === void 0 ? void 0 : _a.effect, subMesh);\n }\n /**\n * Binds the material to the mesh\n * @param world defines the world transformation matrix\n * @param mesh defines the mesh to bind the material to\n * @param effectOverride - If provided, use this effect instead of internal effect\n * @param subMesh defines the submesh to bind the material to\n */\n bind(world, mesh, effectOverride, subMesh) {\n var _a;\n // Std values\n const storeEffectOnSubMeshes = subMesh && this._storeEffectOnSubMeshes;\n const effect = effectOverride !== null && effectOverride !== void 0 ? effectOverride : (storeEffectOnSubMeshes ? subMesh.effect : this.getEffect());\n if (!effect) {\n return;\n }\n this._activeEffect = effect;\n this.bindOnlyWorldMatrix(world, effectOverride);\n const uniformBuffers = this._options.uniformBuffers;\n let useSceneUBO = false;\n if (effect && uniformBuffers && uniformBuffers.length > 0 && this.getScene().getEngine().supportsUniformBuffers) {\n for (let i = 0; i < uniformBuffers.length; ++i) {\n const bufferName = uniformBuffers[i];\n switch (bufferName) {\n case \"Mesh\":\n if (mesh) {\n mesh.getMeshUniformBuffer().bindToEffect(effect, \"Mesh\");\n mesh.transferToEffect(world);\n }\n break;\n case \"Scene\":\n MaterialHelper.BindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());\n this.getScene().finalizeSceneUbo();\n useSceneUBO = true;\n break;\n }\n }\n }\n const mustRebind = mesh && storeEffectOnSubMeshes ? this._mustRebind(this.getScene(), effect, mesh.visibility) : this.getScene().getCachedMaterial() !== this;\n if (effect && mustRebind) {\n if (!useSceneUBO && this._options.uniforms.indexOf(\"view\") !== -1) {\n effect.setMatrix(\"view\", this.getScene().getViewMatrix());\n }\n if (!useSceneUBO && this._options.uniforms.indexOf(\"projection\") !== -1) {\n effect.setMatrix(\"projection\", this.getScene().getProjectionMatrix());\n }\n if (!useSceneUBO && this._options.uniforms.indexOf(\"viewProjection\") !== -1) {\n effect.setMatrix(\"viewProjection\", this.getScene().getTransformMatrix());\n if (this._multiview) {\n effect.setMatrix(\"viewProjectionR\", this.getScene()._transformMatrixR);\n }\n }\n if (this.getScene().activeCamera && this._options.uniforms.indexOf(\"cameraPosition\") !== -1) {\n effect.setVector3(\"cameraPosition\", this.getScene().activeCamera.globalPosition);\n }\n // Bones\n MaterialHelper.BindBonesParameters(mesh, effect);\n // Clip plane\n bindClipPlane(effect, this, this.getScene());\n let name;\n // Texture\n for (name in this._textures) {\n effect.setTexture(name, this._textures[name]);\n }\n // Texture arrays\n for (name in this._textureArrays) {\n effect.setTextureArray(name, this._textureArrays[name]);\n }\n // External texture\n for (name in this._externalTextures) {\n effect.setExternalTexture(name, this._externalTextures[name]);\n }\n // Int\n for (name in this._ints) {\n effect.setInt(name, this._ints[name]);\n }\n // UInt\n for (name in this._uints) {\n effect.setUInt(name, this._uints[name]);\n }\n // Float\n for (name in this._floats) {\n effect.setFloat(name, this._floats[name]);\n }\n // Floats\n for (name in this._floatsArrays) {\n effect.setArray(name, this._floatsArrays[name]);\n }\n // Color3\n for (name in this._colors3) {\n effect.setColor3(name, this._colors3[name]);\n }\n // Color3Array\n for (name in this._colors3Arrays) {\n effect.setArray3(name, this._colors3Arrays[name]);\n }\n // Color4\n for (name in this._colors4) {\n const color = this._colors4[name];\n effect.setFloat4(name, color.r, color.g, color.b, color.a);\n }\n // Color4Array\n for (name in this._colors4Arrays) {\n effect.setArray4(name, this._colors4Arrays[name]);\n }\n // Vector2\n for (name in this._vectors2) {\n effect.setVector2(name, this._vectors2[name]);\n }\n // Vector3\n for (name in this._vectors3) {\n effect.setVector3(name, this._vectors3[name]);\n }\n // Vector4\n for (name in this._vectors4) {\n effect.setVector4(name, this._vectors4[name]);\n }\n // Quaternion\n for (name in this._quaternions) {\n effect.setQuaternion(name, this._quaternions[name]);\n }\n // Matrix\n for (name in this._matrices) {\n effect.setMatrix(name, this._matrices[name]);\n }\n // MatrixArray\n for (name in this._matrixArrays) {\n effect.setMatrices(name, this._matrixArrays[name]);\n }\n // Matrix 3x3\n for (name in this._matrices3x3) {\n effect.setMatrix3x3(name, this._matrices3x3[name]);\n }\n // Matrix 2x2\n for (name in this._matrices2x2) {\n effect.setMatrix2x2(name, this._matrices2x2[name]);\n }\n // Vector2Array\n for (name in this._vectors2Arrays) {\n effect.setArray2(name, this._vectors2Arrays[name]);\n }\n // Vector3Array\n for (name in this._vectors3Arrays) {\n effect.setArray3(name, this._vectors3Arrays[name]);\n }\n // Vector4Array\n for (name in this._vectors4Arrays) {\n effect.setArray4(name, this._vectors4Arrays[name]);\n }\n // QuaternionArray\n for (name in this._quaternionsArrays) {\n effect.setArray4(name, this._quaternionsArrays[name]);\n }\n // Uniform buffers\n for (name in this._uniformBuffers) {\n const buffer = this._uniformBuffers[name].getBuffer();\n if (buffer) {\n effect.bindUniformBuffer(buffer, name);\n }\n }\n // Samplers\n for (name in this._textureSamplers) {\n effect.setTextureSampler(name, this._textureSamplers[name]);\n }\n // Storage buffers\n for (name in this._storageBuffers) {\n effect.setStorageBuffer(name, this._storageBuffers[name]);\n }\n }\n if (effect && mesh && (mustRebind || !this.isFrozen)) {\n // Morph targets\n const manager = mesh.morphTargetManager;\n if (manager && manager.numInfluencers > 0) {\n MaterialHelper.BindMorphTargetParameters(mesh, effect);\n }\n const bvaManager = mesh.bakedVertexAnimationManager;\n if (bvaManager && bvaManager.isEnabled) {\n (_a = mesh.bakedVertexAnimationManager) === null || _a === void 0 ? void 0 : _a.bind(effect, !!effect._wasPreviouslyUsingInstances);\n }\n }\n this._afterBind(mesh, effect);\n }\n /**\n * Gets the active textures from the material\n * @returns an array of textures\n */\n getActiveTextures() {\n const activeTextures = super.getActiveTextures();\n for (const name in this._textures) {\n activeTextures.push(this._textures[name]);\n }\n for (const name in this._textureArrays) {\n const array = this._textureArrays[name];\n for (let index = 0; index < array.length; index++) {\n activeTextures.push(array[index]);\n }\n }\n return activeTextures;\n }\n /**\n * Specifies if the material uses a texture\n * @param texture defines the texture to check against the material\n * @returns a boolean specifying if the material uses the texture\n */\n hasTexture(texture) {\n if (super.hasTexture(texture)) {\n return true;\n }\n for (const name in this._textures) {\n if (this._textures[name] === texture) {\n return true;\n }\n }\n for (const name in this._textureArrays) {\n const array = this._textureArrays[name];\n for (let index = 0; index < array.length; index++) {\n if (array[index] === texture) {\n return true;\n }\n }\n }\n return false;\n }\n /**\n * Makes a duplicate of the material, and gives it a new name\n * @param name defines the new name for the duplicated material\n * @returns the cloned material\n */\n clone(name) {\n const result = SerializationHelper.Clone(() => new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options, this._storeEffectOnSubMeshes), this);\n result.name = name;\n result.id = name;\n // Shader code path\n if (typeof result._shaderPath === \"object\") {\n result._shaderPath = Object.assign({}, result._shaderPath);\n }\n // Options\n this._options = Object.assign({}, this._options);\n Object.keys(this._options).forEach((propName) => {\n const propValue = this._options[propName];\n if (Array.isArray(propValue)) {\n this._options[propName] = propValue.slice(0);\n }\n });\n // Stencil\n this.stencil.copyTo(result.stencil);\n // Texture\n for (const key in this._textures) {\n result.setTexture(key, this._textures[key]);\n }\n // TextureArray\n for (const key in this._textureArrays) {\n result.setTextureArray(key, this._textureArrays[key]);\n }\n // External texture\n for (const key in this._externalTextures) {\n result.setExternalTexture(key, this._externalTextures[key]);\n }\n // Int\n for (const key in this._ints) {\n result.setInt(key, this._ints[key]);\n }\n // UInt\n for (const key in this._uints) {\n result.setUInt(key, this._uints[key]);\n }\n // Float\n for (const key in this._floats) {\n result.setFloat(key, this._floats[key]);\n }\n // Floats\n for (const key in this._floatsArrays) {\n result.setFloats(key, this._floatsArrays[key]);\n }\n // Color3\n for (const key in this._colors3) {\n result.setColor3(key, this._colors3[key]);\n }\n // Color3Array\n for (const key in this._colors3Arrays) {\n result._colors3Arrays[key] = this._colors3Arrays[key];\n }\n // Color4\n for (const key in this._colors4) {\n result.setColor4(key, this._colors4[key]);\n }\n // Color4Array\n for (const key in this._colors4Arrays) {\n result._colors4Arrays[key] = this._colors4Arrays[key];\n }\n // Vector2\n for (const key in this._vectors2) {\n result.setVector2(key, this._vectors2[key]);\n }\n // Vector3\n for (const key in this._vectors3) {\n result.setVector3(key, this._vectors3[key]);\n }\n // Vector4\n for (const key in this._vectors4) {\n result.setVector4(key, this._vectors4[key]);\n }\n // Quaternion\n for (const key in this._quaternions) {\n result.setQuaternion(key, this._quaternions[key]);\n }\n // QuaternionArray\n for (const key in this._quaternionsArrays) {\n result._quaternionsArrays[key] = this._quaternionsArrays[key];\n }\n // Matrix\n for (const key in this._matrices) {\n result.setMatrix(key, this._matrices[key]);\n }\n // MatrixArray\n for (const key in this._matrixArrays) {\n result._matrixArrays[key] = this._matrixArrays[key].slice();\n }\n // Matrix 3x3\n for (const key in this._matrices3x3) {\n result.setMatrix3x3(key, this._matrices3x3[key]);\n }\n // Matrix 2x2\n for (const key in this._matrices2x2) {\n result.setMatrix2x2(key, this._matrices2x2[key]);\n }\n // Vector2Array\n for (const key in this._vectors2Arrays) {\n result.setArray2(key, this._vectors2Arrays[key]);\n }\n // Vector3Array\n for (const key in this._vectors3Arrays) {\n result.setArray3(key, this._vectors3Arrays[key]);\n }\n // Vector4Array\n for (const key in this._vectors4Arrays) {\n result.setArray4(key, this._vectors4Arrays[key]);\n }\n // Uniform buffers\n for (const key in this._uniformBuffers) {\n result.setUniformBuffer(key, this._uniformBuffers[key]);\n }\n // Samplers\n for (const key in this._textureSamplers) {\n result.setTextureSampler(key, this._textureSamplers[key]);\n }\n // Storag buffers\n for (const key in this._storageBuffers) {\n result.setStorageBuffer(key, this._storageBuffers[key]);\n }\n return result;\n }\n /**\n * Disposes the material\n * @param forceDisposeEffect specifies if effects should be forcefully disposed\n * @param forceDisposeTextures specifies if textures should be forcefully disposed\n * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh\n */\n dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {\n if (forceDisposeTextures) {\n let name;\n for (name in this._textures) {\n this._textures[name].dispose();\n }\n for (name in this._textureArrays) {\n const array = this._textureArrays[name];\n for (let index = 0; index < array.length; index++) {\n array[index].dispose();\n }\n }\n }\n this._textures = {};\n super.dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh);\n }\n /**\n * Serializes this material in a JSON representation\n * @returns the serialized material object\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this);\n serializationObject.customType = \"BABYLON.ShaderMaterial\";\n serializationObject.uniqueId = this.uniqueId;\n serializationObject.options = this._options;\n serializationObject.shaderPath = this._shaderPath;\n serializationObject.storeEffectOnSubMeshes = this._storeEffectOnSubMeshes;\n let name;\n // Stencil\n serializationObject.stencil = this.stencil.serialize();\n // Texture\n serializationObject.textures = {};\n for (name in this._textures) {\n serializationObject.textures[name] = this._textures[name].serialize();\n }\n // Texture arrays\n serializationObject.textureArrays = {};\n for (name in this._textureArrays) {\n serializationObject.textureArrays[name] = [];\n const array = this._textureArrays[name];\n for (let index = 0; index < array.length; index++) {\n serializationObject.textureArrays[name].push(array[index].serialize());\n }\n }\n // Int\n serializationObject.ints = {};\n for (name in this._ints) {\n serializationObject.ints[name] = this._ints[name];\n }\n // UInt\n serializationObject.uints = {};\n for (name in this._uints) {\n serializationObject.uints[name] = this._uints[name];\n }\n // Float\n serializationObject.floats = {};\n for (name in this._floats) {\n serializationObject.floats[name] = this._floats[name];\n }\n // Floats\n serializationObject.FloatArrays = {};\n for (name in this._floatsArrays) {\n serializationObject.FloatArrays[name] = this._floatsArrays[name];\n }\n // Color3\n serializationObject.colors3 = {};\n for (name in this._colors3) {\n serializationObject.colors3[name] = this._colors3[name].asArray();\n }\n // Color3 array\n serializationObject.colors3Arrays = {};\n for (name in this._colors3Arrays) {\n serializationObject.colors3Arrays[name] = this._colors3Arrays[name];\n }\n // Color4\n serializationObject.colors4 = {};\n for (name in this._colors4) {\n serializationObject.colors4[name] = this._colors4[name].asArray();\n }\n // Color4 array\n serializationObject.colors4Arrays = {};\n for (name in this._colors4Arrays) {\n serializationObject.colors4Arrays[name] = this._colors4Arrays[name];\n }\n // Vector2\n serializationObject.vectors2 = {};\n for (name in this._vectors2) {\n serializationObject.vectors2[name] = this._vectors2[name].asArray();\n }\n // Vector3\n serializationObject.vectors3 = {};\n for (name in this._vectors3) {\n serializationObject.vectors3[name] = this._vectors3[name].asArray();\n }\n // Vector4\n serializationObject.vectors4 = {};\n for (name in this._vectors4) {\n serializationObject.vectors4[name] = this._vectors4[name].asArray();\n }\n // Quaternion\n serializationObject.quaternions = {};\n for (name in this._quaternions) {\n serializationObject.quaternions[name] = this._quaternions[name].asArray();\n }\n // Matrix\n serializationObject.matrices = {};\n for (name in this._matrices) {\n serializationObject.matrices[name] = this._matrices[name].asArray();\n }\n // MatrixArray\n serializationObject.matrixArray = {};\n for (name in this._matrixArrays) {\n serializationObject.matrixArray[name] = this._matrixArrays[name];\n }\n // Matrix 3x3\n serializationObject.matrices3x3 = {};\n for (name in this._matrices3x3) {\n serializationObject.matrices3x3[name] = this._matrices3x3[name];\n }\n // Matrix 2x2\n serializationObject.matrices2x2 = {};\n for (name in this._matrices2x2) {\n serializationObject.matrices2x2[name] = this._matrices2x2[name];\n }\n // Vector2Array\n serializationObject.vectors2Arrays = {};\n for (name in this._vectors2Arrays) {\n serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];\n }\n // Vector3Array\n serializationObject.vectors3Arrays = {};\n for (name in this._vectors3Arrays) {\n serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];\n }\n // Vector4Array\n serializationObject.vectors4Arrays = {};\n for (name in this._vectors4Arrays) {\n serializationObject.vectors4Arrays[name] = this._vectors4Arrays[name];\n }\n // QuaternionArray\n serializationObject.quaternionsArrays = {};\n for (name in this._quaternionsArrays) {\n serializationObject.quaternionsArrays[name] = this._quaternionsArrays[name];\n }\n return serializationObject;\n }\n /**\n * Creates a shader material from parsed shader material data\n * @param source defines the JSON representation of the material\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @returns a new material\n */\n static Parse(source, scene, rootUrl) {\n const material = SerializationHelper.Parse(() => new ShaderMaterial(source.name, scene, source.shaderPath, source.options, source.storeEffectOnSubMeshes), source, scene, rootUrl);\n let name;\n // Stencil\n if (source.stencil) {\n material.stencil.parse(source.stencil, scene, rootUrl);\n }\n // Texture\n for (name in source.textures) {\n material.setTexture(name, Texture.Parse(source.textures[name], scene, rootUrl));\n }\n // Texture arrays\n for (name in source.textureArrays) {\n const array = source.textureArrays[name];\n const textureArray = new Array();\n for (let index = 0; index < array.length; index++) {\n textureArray.push(Texture.Parse(array[index], scene, rootUrl));\n }\n material.setTextureArray(name, textureArray);\n }\n // Int\n for (name in source.ints) {\n material.setInt(name, source.ints[name]);\n }\n // UInt\n for (name in source.uints) {\n material.setUInt(name, source.uints[name]);\n }\n // Float\n for (name in source.floats) {\n material.setFloat(name, source.floats[name]);\n }\n // Floats\n for (name in source.floatsArrays) {\n material.setFloats(name, source.floatsArrays[name]);\n }\n // Color3\n for (name in source.colors3) {\n material.setColor3(name, Color3.FromArray(source.colors3[name]));\n }\n // Color3 arrays\n for (name in source.colors3Arrays) {\n const colors = source.colors3Arrays[name]\n .reduce((arr, num, i) => {\n if (i % 3 === 0) {\n arr.push([num]);\n }\n else {\n arr[arr.length - 1].push(num);\n }\n return arr;\n }, [])\n .map((color) => Color3.FromArray(color));\n material.setColor3Array(name, colors);\n }\n // Color4\n for (name in source.colors4) {\n material.setColor4(name, Color4.FromArray(source.colors4[name]));\n }\n // Color4 arrays\n for (name in source.colors4Arrays) {\n const colors = source.colors4Arrays[name]\n .reduce((arr, num, i) => {\n if (i % 4 === 0) {\n arr.push([num]);\n }\n else {\n arr[arr.length - 1].push(num);\n }\n return arr;\n }, [])\n .map((color) => Color4.FromArray(color));\n material.setColor4Array(name, colors);\n }\n // Vector2\n for (name in source.vectors2) {\n material.setVector2(name, Vector2.FromArray(source.vectors2[name]));\n }\n // Vector3\n for (name in source.vectors3) {\n material.setVector3(name, Vector3.FromArray(source.vectors3[name]));\n }\n // Vector4\n for (name in source.vectors4) {\n material.setVector4(name, Vector4.FromArray(source.vectors4[name]));\n }\n // Quaternion\n for (name in source.quaternions) {\n material.setQuaternion(name, Quaternion.FromArray(source.quaternions[name]));\n }\n // Matrix\n for (name in source.matrices) {\n material.setMatrix(name, Matrix.FromArray(source.matrices[name]));\n }\n // MatrixArray\n for (name in source.matrixArray) {\n material._matrixArrays[name] = new Float32Array(source.matrixArray[name]);\n }\n // Matrix 3x3\n for (name in source.matrices3x3) {\n material.setMatrix3x3(name, source.matrices3x3[name]);\n }\n // Matrix 2x2\n for (name in source.matrices2x2) {\n material.setMatrix2x2(name, source.matrices2x2[name]);\n }\n // Vector2Array\n for (name in source.vectors2Arrays) {\n material.setArray2(name, source.vectors2Arrays[name]);\n }\n // Vector3Array\n for (name in source.vectors3Arrays) {\n material.setArray3(name, source.vectors3Arrays[name]);\n }\n // Vector4Array\n for (name in source.vectors4Arrays) {\n material.setArray4(name, source.vectors4Arrays[name]);\n }\n // QuaternionArray\n for (name in source.quaternionsArrays) {\n material.setArray4(name, source.quaternionsArrays[name]);\n }\n return material;\n }\n /**\n * Creates a new ShaderMaterial from a snippet saved in a remote file\n * @param name defines the name of the ShaderMaterial to create (can be null or empty to use the one from the json data)\n * @param url defines the url to load from\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @returns a promise that will resolve to the new ShaderMaterial\n */\n static ParseFromFileAsync(name, url, scene, rootUrl = \"\") {\n return new Promise((resolve, reject) => {\n const request = new WebRequest();\n request.addEventListener(\"readystatechange\", () => {\n if (request.readyState == 4) {\n if (request.status == 200) {\n const serializationObject = JSON.parse(request.responseText);\n const output = this.Parse(serializationObject, scene || EngineStore.LastCreatedScene, rootUrl);\n if (name) {\n output.name = name;\n }\n resolve(output);\n }\n else {\n reject(\"Unable to load the ShaderMaterial\");\n }\n }\n });\n request.open(\"GET\", url);\n request.send();\n });\n }\n /**\n * Creates a ShaderMaterial from a snippet saved by the Inspector\n * @param snippetId defines the snippet to load\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @returns a promise that will resolve to the new ShaderMaterial\n */\n static ParseFromSnippetAsync(snippetId, scene, rootUrl = \"\") {\n return new Promise((resolve, reject) => {\n const request = new WebRequest();\n request.addEventListener(\"readystatechange\", () => {\n if (request.readyState == 4) {\n if (request.status == 200) {\n const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload);\n const serializationObject = JSON.parse(snippet.shaderMaterial);\n const output = this.Parse(serializationObject, scene || EngineStore.LastCreatedScene, rootUrl);\n output.snippetId = snippetId;\n resolve(output);\n }\n else {\n reject(\"Unable to load the snippet \" + snippetId);\n }\n }\n });\n request.open(\"GET\", this.SnippetUrl + \"/\" + snippetId.replace(/#/g, \"/\"));\n request.send();\n });\n }\n}\n/** Define the Url to load snippets */\nShaderMaterial.SnippetUrl = `https://snippet.babylonjs.com`;\n/**\n * Creates a ShaderMaterial from a snippet saved by the Inspector\n * @deprecated Please use ParseFromSnippetAsync instead\n * @param snippetId defines the snippet to load\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @returns a promise that will resolve to the new ShaderMaterial\n */\nShaderMaterial.CreateFromSnippetAsync = ShaderMaterial.ParseFromSnippetAsync;\nRegisterClass(\"BABYLON.ShaderMaterial\", ShaderMaterial);\n//# sourceMappingURL=shaderMaterial.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/clipPlaneFragmentDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneFragment.js\";\nconst name = \"colorPixelShader\";\nconst shader = `#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\n#define VERTEXCOLOR\nvarying vec4 vColor;\r#else\nuniform vec4 color;\r#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\ngl_FragColor=vColor;\r#else\ngl_FragColor=color;\r#endif\n#define CUSTOM_FRAGMENT_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const colorPixelShader = { name, shader };\n//# sourceMappingURL=color.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/bonesDeclaration.js\";\nimport \"./ShadersInclude/bakedVertexAnimationDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneVertexDeclaration.js\";\nimport \"./ShadersInclude/instancesDeclaration.js\";\nimport \"./ShadersInclude/instancesVertex.js\";\nimport \"./ShadersInclude/bonesVertex.js\";\nimport \"./ShadersInclude/bakedVertexAnimation.js\";\nimport \"./ShadersInclude/clipPlaneVertex.js\";\nimport \"./ShadersInclude/vertexColorMixing.js\";\nconst name = \"colorVertexShader\";\nconst shader = `attribute vec3 position;\r#ifdef VERTEXCOLOR\nattribute vec4 color;\r#endif\n#include\n#include\n#include\n#include\nuniform mat4 viewProjection;\r#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\r#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\r#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(position,1.0);\r#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {\rgl_Position=viewProjection*worldPos;\r} else {\rgl_Position=viewProjectionR*worldPos;\r}\r#else\ngl_Position=viewProjection*worldPos;\r#endif\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const colorVertexShader = { name, shader };\n//# sourceMappingURL=color.vertex.js.map","import { Color3, Color4 } from \"../Maths/math.color.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { InstancedMesh } from \"../Meshes/instancedMesh.js\";\nimport { Material } from \"../Materials/material.js\";\nimport { ShaderMaterial } from \"../Materials/shaderMaterial.js\";\nimport \"../Shaders/color.fragment.js\";\nimport \"../Shaders/color.vertex.js\";\nMesh._LinesMeshParser = (parsedMesh, scene) => {\n return LinesMesh.Parse(parsedMesh, scene);\n};\n/**\n * Line mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param\n */\nexport class LinesMesh extends Mesh {\n _isShaderMaterial(shader) {\n return shader.getClassName() === \"ShaderMaterial\";\n }\n /**\n * Creates a new LinesMesh\n * @param name defines the name\n * @param scene defines the hosting scene\n * @param parent defines the parent mesh if any\n * @param source defines the optional source LinesMesh used to clone data from\n * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.\n * When false, achieved by calling a clone(), also passing False.\n * This will make creation of children, recursive.\n * @param useVertexColor defines if this LinesMesh supports vertex color\n * @param useVertexAlpha defines if this LinesMesh supports vertex alpha\n * @param material material to use to draw the line. If not provided, will create a new one\n */\n constructor(name, scene = null, parent = null, source = null, doNotCloneChildren, \n /**\n * If vertex color should be applied to the mesh\n */\n useVertexColor, \n /**\n * If vertex alpha should be applied to the mesh\n */\n useVertexAlpha, material) {\n super(name, scene, parent, source, doNotCloneChildren);\n this.useVertexColor = useVertexColor;\n this.useVertexAlpha = useVertexAlpha;\n /**\n * Color of the line (Default: White)\n */\n this.color = new Color3(1, 1, 1);\n /**\n * Alpha of the line (Default: 1)\n */\n this.alpha = 1;\n if (source) {\n this.color = source.color.clone();\n this.alpha = source.alpha;\n this.useVertexColor = source.useVertexColor;\n this.useVertexAlpha = source.useVertexAlpha;\n }\n this.intersectionThreshold = 0.1;\n const defines = [];\n const options = {\n attributes: [VertexBuffer.PositionKind],\n uniforms: [\"world\", \"viewProjection\"],\n needAlphaBlending: true,\n defines: defines,\n useClipPlane: null,\n };\n if (useVertexAlpha === false) {\n options.needAlphaBlending = false;\n }\n else {\n options.defines.push(\"#define VERTEXALPHA\");\n }\n if (!useVertexColor) {\n options.uniforms.push(\"color\");\n this._color4 = new Color4();\n }\n else {\n options.defines.push(\"#define VERTEXCOLOR\");\n options.attributes.push(VertexBuffer.ColorKind);\n }\n if (material) {\n this.material = material;\n }\n else {\n this.material = new ShaderMaterial(\"colorShader\", this.getScene(), \"color\", options, false);\n this.material.doNotSerialize = true;\n }\n }\n isReady() {\n if (!this._lineMaterial.isReady(this, !!this._userInstancedBuffersStorage)) {\n return false;\n }\n return super.isReady();\n }\n /**\n * Returns the string \"LineMesh\"\n */\n getClassName() {\n return \"LinesMesh\";\n }\n /**\n * @internal\n */\n get material() {\n return this._lineMaterial;\n }\n /**\n * @internal\n */\n set material(value) {\n this._lineMaterial = value;\n this._lineMaterial.fillMode = Material.LineListDrawMode;\n }\n /**\n * @internal\n */\n get checkCollisions() {\n return false;\n }\n set checkCollisions(value) {\n // Just ignore it\n }\n /**\n * @internal\n */\n _bind(_subMesh, colorEffect) {\n if (!this._geometry) {\n return this;\n }\n // VBOs\n const indexToBind = this.isUnIndexed ? null : this._geometry.getIndexBuffer();\n if (!this._userInstancedBuffersStorage) {\n this._geometry._bind(colorEffect, indexToBind);\n }\n else {\n this._geometry._bind(colorEffect, indexToBind, this._userInstancedBuffersStorage.vertexBuffers, this._userInstancedBuffersStorage.vertexArrayObjects);\n }\n // Color\n if (!this.useVertexColor && this._isShaderMaterial(this._lineMaterial)) {\n const { r, g, b } = this.color;\n this._color4.set(r, g, b, this.alpha);\n this._lineMaterial.setColor4(\"color\", this._color4);\n }\n return this;\n }\n /**\n * @internal\n */\n _draw(subMesh, fillMode, instancesCount) {\n if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {\n return this;\n }\n const engine = this.getScene().getEngine();\n // Draw order\n if (this._unIndexed) {\n engine.drawArraysType(Material.LineListDrawMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);\n }\n else {\n engine.drawElementsType(Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);\n }\n return this;\n }\n /**\n * Disposes of the line mesh\n * @param doNotRecurse If children should be disposed\n * @param disposeMaterialAndTextures This parameter is not used by the LineMesh class\n * @param doNotDisposeMaterial If the material should not be disposed (default: false, meaning the material is disposed)\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n dispose(doNotRecurse, disposeMaterialAndTextures = false, doNotDisposeMaterial) {\n if (!doNotDisposeMaterial) {\n this._lineMaterial.dispose(false, false, true);\n }\n super.dispose(doNotRecurse);\n }\n /**\n * Returns a new LineMesh object cloned from the current one.\n * @param name\n * @param newParent\n * @param doNotCloneChildren\n */\n clone(name, newParent = null, doNotCloneChildren) {\n return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);\n }\n /**\n * Creates a new InstancedLinesMesh object from the mesh model.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/copies/instances\n * @param name defines the name of the new instance\n * @returns a new InstancedLinesMesh\n */\n createInstance(name) {\n const instance = new InstancedLinesMesh(name, this);\n if (this.instancedBuffers) {\n instance.instancedBuffers = {};\n for (const key in this.instancedBuffers) {\n instance.instancedBuffers[key] = this.instancedBuffers[key];\n }\n }\n return instance;\n }\n /**\n * Serializes this ground mesh\n * @param serializationObject object to write serialization to\n */\n serialize(serializationObject) {\n super.serialize(serializationObject);\n serializationObject.color = this.color.asArray();\n serializationObject.alpha = this.alpha;\n }\n /**\n * Parses a serialized ground mesh\n * @param parsedMesh the serialized mesh\n * @param scene the scene to create the ground mesh in\n * @returns the created ground mesh\n */\n static Parse(parsedMesh, scene) {\n const result = new LinesMesh(parsedMesh.name, scene);\n result.color = Color3.FromArray(parsedMesh.color);\n result.alpha = parsedMesh.alpha;\n return result;\n }\n}\n/**\n * Creates an instance based on a source LinesMesh\n */\nexport class InstancedLinesMesh extends InstancedMesh {\n constructor(name, source) {\n super(name, source);\n this.intersectionThreshold = source.intersectionThreshold;\n }\n /**\n * Returns the string \"InstancedLinesMesh\".\n */\n getClassName() {\n return \"InstancedLinesMesh\";\n }\n}\n//# sourceMappingURL=linesMesh.js.map","/* eslint-disable @typescript-eslint/naming-convention */\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { _CreationDataStorage, Mesh } from \"../mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { LinesMesh } from \"../../Meshes/linesMesh.js\";\nimport { VertexBuffer } from \"../../Buffers/buffer.js\";\nimport { Logger } from \"../../Misc/logger.js\";\n/**\n * Creates the VertexData of the LineSystem\n * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty\n * - lines an array of lines, each line being an array of successive Vector3\n * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point\n * @param options.lines\n * @param options.colors\n * @returns the VertexData of the LineSystem\n */\nexport function CreateLineSystemVertexData(options) {\n const indices = [];\n const positions = [];\n const lines = options.lines;\n const colors = options.colors;\n const vertexColors = [];\n let idx = 0;\n for (let l = 0; l < lines.length; l++) {\n const points = lines[l];\n for (let index = 0; index < points.length; index++) {\n positions.push(points[index].x, points[index].y, points[index].z);\n if (colors) {\n const color = colors[l];\n vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);\n }\n if (index > 0) {\n indices.push(idx - 1);\n indices.push(idx);\n }\n idx++;\n }\n }\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n if (colors) {\n vertexData.colors = vertexColors;\n }\n return vertexData;\n}\n/**\n * Create the VertexData for a DashedLines\n * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty\n * - points an array successive Vector3\n * - dashSize the size of the dashes relative to the dash number, optional, default 3\n * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1\n * - dashNb the intended total number of dashes, optional, default 200\n * @param options.points\n * @param options.dashSize\n * @param options.gapSize\n * @param options.dashNb\n * @returns the VertexData for the DashedLines\n */\nexport function CreateDashedLinesVertexData(options) {\n const dashSize = options.dashSize || 3;\n const gapSize = options.gapSize || 1;\n const dashNb = options.dashNb || 200;\n const points = options.points;\n const positions = new Array();\n const indices = new Array();\n const curvect = Vector3.Zero();\n let lg = 0;\n let nb = 0;\n let shft = 0;\n let dashshft = 0;\n let curshft = 0;\n let idx = 0;\n let i = 0;\n for (i = 0; i < points.length - 1; i++) {\n points[i + 1].subtractToRef(points[i], curvect);\n lg += curvect.length();\n }\n shft = lg / dashNb;\n dashshft = (dashSize * shft) / (dashSize + gapSize);\n for (i = 0; i < points.length - 1; i++) {\n points[i + 1].subtractToRef(points[i], curvect);\n nb = Math.floor(curvect.length() / shft);\n curvect.normalize();\n for (let j = 0; j < nb; j++) {\n curshft = shft * j;\n positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);\n positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);\n indices.push(idx, idx + 1);\n idx += 2;\n }\n }\n // Result\n const vertexData = new VertexData();\n vertexData.positions = positions;\n vertexData.indices = indices;\n return vertexData;\n}\n/**\n * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh\n * * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter\n * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function\n * * The parameter `lines` is an array of lines, each line being an array of successive Vector3\n * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter\n * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point\n * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)\n * * The optional parameter `material` is the material to use to draw the lines if provided. If not, a default material will be created\n * * Updating a simple Line mesh, you just need to update every line in the `lines` array : https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#lines-and-dashedlines\n * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#line-system\n * @param name defines the name of the new line system\n * @param options defines the options used to create the line system\n * @param options.lines\n * @param options.updatable\n * @param options.instance\n * @param options.colors\n * @param options.useVertexAlpha\n * @param options.material\n * @param scene defines the hosting scene\n * @returns a new line system mesh\n */\nexport function CreateLineSystem(name, options, scene) {\n const instance = options.instance;\n const lines = options.lines;\n const colors = options.colors;\n if (instance) {\n // lines update\n const positions = instance.getVerticesData(VertexBuffer.PositionKind);\n let vertexColor;\n let lineColors;\n if (colors) {\n vertexColor = instance.getVerticesData(VertexBuffer.ColorKind);\n }\n let i = 0;\n let c = 0;\n for (let l = 0; l < lines.length; l++) {\n const points = lines[l];\n for (let p = 0; p < points.length; p++) {\n positions[i] = points[p].x;\n positions[i + 1] = points[p].y;\n positions[i + 2] = points[p].z;\n if (colors && vertexColor) {\n lineColors = colors[l];\n vertexColor[c] = lineColors[p].r;\n vertexColor[c + 1] = lineColors[p].g;\n vertexColor[c + 2] = lineColors[p].b;\n vertexColor[c + 3] = lineColors[p].a;\n c += 4;\n }\n i += 3;\n }\n }\n instance.updateVerticesData(VertexBuffer.PositionKind, positions, false, false);\n if (colors && vertexColor) {\n instance.updateVerticesData(VertexBuffer.ColorKind, vertexColor, false, false);\n }\n return instance;\n }\n // line system creation\n const useVertexColor = colors ? true : false;\n const lineSystem = new LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha, options.material);\n const vertexData = CreateLineSystemVertexData(options);\n vertexData.applyToMesh(lineSystem, options.updatable);\n return lineSystem;\n}\n/**\n * Creates a line mesh\n * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter\n * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function\n * * The parameter `points` is an array successive Vector3\n * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#lines-and-dashedlines\n * * The optional parameter `colors` is an array of successive Color4, one per line point\n * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)\n * * The optional parameter `material` is the material to use to draw the lines if provided. If not, a default material will be created\n * * When updating an instance, remember that only point positions can change, not the number of points\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#lines\n * @param name defines the name of the new line system\n * @param options defines the options used to create the line system\n * @param options.points\n * @param options.updatable\n * @param options.instance\n * @param options.colors\n * @param options.useVertexAlpha\n * @param options.material\n * @param scene defines the hosting scene\n * @returns a new line mesh\n */\nexport function CreateLines(name, options, scene = null) {\n const colors = options.colors ? [options.colors] : null;\n const lines = CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha, material: options.material }, scene);\n return lines;\n}\n/**\n * Creates a dashed line mesh\n * * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter\n * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function\n * * The parameter `points` is an array successive Vector3\n * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)\n * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)\n * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)\n * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#lines-and-dashedlines\n * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)\n * * The optional parameter `material` is the material to use to draw the lines if provided. If not, a default material will be created\n * * When updating an instance, remember that only point positions can change, not the number of points\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.points\n * @param options.dashSize\n * @param options.gapSize\n * @param options.dashNb\n * @param options.updatable\n * @param options.instance\n * @param options.useVertexAlpha\n * @param options.material\n * @param scene defines the hosting scene\n * @returns the dashed line mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#dashed-lines\n */\nexport function CreateDashedLines(name, options, scene = null) {\n const points = options.points;\n const instance = options.instance;\n const gapSize = options.gapSize || 1;\n const dashSize = options.dashSize || 3;\n if (instance) {\n // dashed lines update\n const positionFunction = (positions) => {\n const curvect = Vector3.Zero();\n const nbSeg = positions.length / 6;\n let lg = 0;\n let nb = 0;\n let shft = 0;\n let dashshft = 0;\n let curshft = 0;\n let p = 0;\n let i = 0;\n let j = 0;\n for (i = 0; i < points.length - 1; i++) {\n points[i + 1].subtractToRef(points[i], curvect);\n lg += curvect.length();\n }\n shft = lg / nbSeg;\n const dashSize = instance._creationDataStorage.dashSize;\n const gapSize = instance._creationDataStorage.gapSize;\n dashshft = (dashSize * shft) / (dashSize + gapSize);\n for (i = 0; i < points.length - 1; i++) {\n points[i + 1].subtractToRef(points[i], curvect);\n nb = Math.floor(curvect.length() / shft);\n curvect.normalize();\n j = 0;\n while (j < nb && p < positions.length) {\n curshft = shft * j;\n positions[p] = points[i].x + curshft * curvect.x;\n positions[p + 1] = points[i].y + curshft * curvect.y;\n positions[p + 2] = points[i].z + curshft * curvect.z;\n positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;\n positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;\n positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;\n p += 6;\n j++;\n }\n }\n while (p < positions.length) {\n positions[p] = points[i].x;\n positions[p + 1] = points[i].y;\n positions[p + 2] = points[i].z;\n p += 3;\n }\n };\n if (options.dashNb || options.dashSize || options.gapSize || options.useVertexAlpha || options.material) {\n Logger.Warn(\"You have used an option other than points with the instance option. Please be aware that these other options will be ignored.\");\n }\n instance.updateMeshPositions(positionFunction, false);\n return instance;\n }\n // dashed lines creation\n const dashedLines = new LinesMesh(name, scene, null, undefined, undefined, undefined, options.useVertexAlpha, options.material);\n const vertexData = CreateDashedLinesVertexData(options);\n vertexData.applyToMesh(dashedLines, options.updatable);\n dashedLines._creationDataStorage = new _CreationDataStorage();\n dashedLines._creationDataStorage.dashSize = dashSize;\n dashedLines._creationDataStorage.gapSize = gapSize;\n return dashedLines;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use the functions directly from the module\n */\nexport const LinesBuilder = {\n CreateDashedLines,\n CreateLineSystem,\n CreateLines,\n};\nVertexData.CreateLineSystem = CreateLineSystemVertexData;\nVertexData.CreateDashedLines = CreateDashedLinesVertexData;\nMesh.CreateLines = (name, points, scene = null, updatable = false, instance = null) => {\n const options = {\n points,\n updatable,\n instance,\n };\n return CreateLines(name, options, scene);\n};\nMesh.CreateDashedLines = (name, points, dashSize, gapSize, dashNb, scene = null, updatable, instance) => {\n const options = {\n points,\n dashSize,\n gapSize,\n dashNb,\n updatable,\n instance,\n };\n return CreateDashedLines(name, options, scene);\n};\n//# sourceMappingURL=linesBuilder.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { Vector3, Vector2 } from \"../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { VertexData } from \"../Meshes/mesh.vertexData.js\";\nimport { Path2 } from \"../Maths/math.path.js\";\nimport { Epsilon } from \"../Maths/math.constants.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n/**\n * Vector2 wth index property\n */\nclass IndexedVector2 extends Vector2 {\n constructor(original, \n /** Index of the vector2 */\n index) {\n super(original.x, original.y);\n this.index = index;\n }\n}\n/**\n * Defines points to create a polygon\n */\nclass PolygonPoints {\n constructor() {\n this.elements = new Array();\n }\n add(originalPoints) {\n const result = new Array();\n originalPoints.forEach((point) => {\n const newPoint = new IndexedVector2(point, this.elements.length);\n result.push(newPoint);\n this.elements.push(newPoint);\n });\n return result;\n }\n computeBounds() {\n const lmin = new Vector2(this.elements[0].x, this.elements[0].y);\n const lmax = new Vector2(this.elements[0].x, this.elements[0].y);\n this.elements.forEach((point) => {\n // x\n if (point.x < lmin.x) {\n lmin.x = point.x;\n }\n else if (point.x > lmax.x) {\n lmax.x = point.x;\n }\n // y\n if (point.y < lmin.y) {\n lmin.y = point.y;\n }\n else if (point.y > lmax.y) {\n lmax.y = point.y;\n }\n });\n return {\n min: lmin,\n max: lmax,\n width: lmax.x - lmin.x,\n height: lmax.y - lmin.y,\n };\n }\n}\n/**\n * Polygon\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#non-regular-polygon\n */\nexport class Polygon {\n /**\n * Creates a rectangle\n * @param xmin bottom X coord\n * @param ymin bottom Y coord\n * @param xmax top X coord\n * @param ymax top Y coord\n * @returns points that make the resulting rectangle\n */\n static Rectangle(xmin, ymin, xmax, ymax) {\n return [new Vector2(xmin, ymin), new Vector2(xmax, ymin), new Vector2(xmax, ymax), new Vector2(xmin, ymax)];\n }\n /**\n * Creates a circle\n * @param radius radius of circle\n * @param cx scale in x\n * @param cy scale in y\n * @param numberOfSides number of sides that make up the circle\n * @returns points that make the resulting circle\n */\n static Circle(radius, cx = 0, cy = 0, numberOfSides = 32) {\n const result = new Array();\n let angle = 0;\n const increment = (Math.PI * 2) / numberOfSides;\n for (let i = 0; i < numberOfSides; i++) {\n result.push(new Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));\n angle -= increment;\n }\n return result;\n }\n /**\n * Creates a polygon from input string\n * @param input Input polygon data\n * @returns the parsed points\n */\n static Parse(input) {\n const floats = input\n .split(/[^-+eE.\\d]+/)\n .map(parseFloat)\n .filter((val) => !isNaN(val));\n let i;\n const result = [];\n for (i = 0; i < (floats.length & 0x7ffffffe); i += 2) {\n result.push(new Vector2(floats[i], floats[i + 1]));\n }\n return result;\n }\n /**\n * Starts building a polygon from x and y coordinates\n * @param x x coordinate\n * @param y y coordinate\n * @returns the started path2\n */\n static StartingAt(x, y) {\n return Path2.StartingAt(x, y);\n }\n}\n/**\n * Builds a polygon\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param/polyMeshBuilder\n */\nexport class PolygonMeshBuilder {\n _addToepoint(points) {\n for (const p of points) {\n this._epoints.push(p.x, p.y);\n }\n }\n /**\n * Creates a PolygonMeshBuilder\n * @param name name of the builder\n * @param contours Path of the polygon\n * @param scene scene to add to when creating the mesh\n * @param earcutInjection can be used to inject your own earcut reference\n */\n constructor(name, contours, scene, earcutInjection = earcut) {\n this._points = new PolygonPoints();\n this._outlinepoints = new PolygonPoints();\n this._holes = new Array();\n this._epoints = new Array();\n this._eholes = new Array();\n this.bjsEarcut = earcutInjection;\n this._name = name;\n this._scene = scene || EngineStore.LastCreatedScene;\n let points;\n if (contours instanceof Path2) {\n points = contours.getPoints();\n }\n else {\n points = contours;\n }\n this._addToepoint(points);\n this._points.add(points);\n this._outlinepoints.add(points);\n if (typeof this.bjsEarcut === \"undefined\") {\n Logger.Warn(\"Earcut was not found, the polygon will not be built.\");\n }\n }\n /**\n * Adds a hole within the polygon\n * @param hole Array of points defining the hole\n * @returns this\n */\n addHole(hole) {\n this._points.add(hole);\n const holepoints = new PolygonPoints();\n holepoints.add(hole);\n this._holes.push(holepoints);\n this._eholes.push(this._epoints.length / 2);\n this._addToepoint(hole);\n return this;\n }\n /**\n * Creates the polygon\n * @param updatable If the mesh should be updatable\n * @param depth The depth of the mesh created\n * @param smoothingThreshold Dot product threshold for smoothed normals\n * @returns the created mesh\n */\n build(updatable = false, depth = 0, smoothingThreshold = 2) {\n const result = new Mesh(this._name, this._scene);\n const vertexData = this.buildVertexData(depth, smoothingThreshold);\n result.setVerticesData(VertexBuffer.PositionKind, vertexData.positions, updatable);\n result.setVerticesData(VertexBuffer.NormalKind, vertexData.normals, updatable);\n result.setVerticesData(VertexBuffer.UVKind, vertexData.uvs, updatable);\n result.setIndices(vertexData.indices);\n return result;\n }\n /**\n * Creates the polygon\n * @param depth The depth of the mesh created\n * @param smoothingThreshold Dot product threshold for smoothed normals\n * @returns the created VertexData\n */\n buildVertexData(depth = 0, smoothingThreshold = 2) {\n const result = new VertexData();\n const normals = new Array();\n const positions = new Array();\n const uvs = new Array();\n const bounds = this._points.computeBounds();\n this._points.elements.forEach((p) => {\n normals.push(0, 1.0, 0);\n positions.push(p.x, 0, p.y);\n uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);\n });\n const indices = new Array();\n const res = this.bjsEarcut(this._epoints, this._eholes, 2);\n for (let i = 0; i < res.length; i++) {\n indices.push(res[i]);\n }\n if (depth > 0) {\n const positionscount = positions.length / 3; //get the current pointcount\n this._points.elements.forEach((p) => {\n //add the elements at the depth\n normals.push(0, -1.0, 0);\n positions.push(p.x, -depth, p.y);\n uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);\n });\n const totalCount = indices.length;\n for (let i = 0; i < totalCount; i += 3) {\n const i0 = indices[i + 0];\n const i1 = indices[i + 1];\n const i2 = indices[i + 2];\n indices.push(i2 + positionscount);\n indices.push(i1 + positionscount);\n indices.push(i0 + positionscount);\n }\n //Add the sides\n this._addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false, smoothingThreshold);\n this._holes.forEach((hole) => {\n this._addSide(positions, normals, uvs, indices, bounds, hole, depth, true, smoothingThreshold);\n });\n }\n result.indices = indices;\n result.positions = positions;\n result.normals = normals;\n result.uvs = uvs;\n return result;\n }\n /**\n * Adds a side to the polygon\n * @param positions points that make the polygon\n * @param normals normals of the polygon\n * @param uvs uvs of the polygon\n * @param indices indices of the polygon\n * @param bounds bounds of the polygon\n * @param points points of the polygon\n * @param depth depth of the polygon\n * @param flip flip of the polygon\n * @param smoothingThreshold\n */\n _addSide(positions, normals, uvs, indices, bounds, points, depth, flip, smoothingThreshold) {\n let startIndex = positions.length / 3;\n let ulength = 0;\n for (let i = 0; i < points.elements.length; i++) {\n const p = points.elements[i];\n const p1 = points.elements[(i + 1) % points.elements.length];\n positions.push(p.x, 0, p.y);\n positions.push(p.x, -depth, p.y);\n positions.push(p1.x, 0, p1.y);\n positions.push(p1.x, -depth, p1.y);\n const p0 = points.elements[(i + points.elements.length - 1) % points.elements.length];\n const p2 = points.elements[(i + 2) % points.elements.length];\n let vc = new Vector3(-(p1.y - p.y), 0, p1.x - p.x);\n let vp = new Vector3(-(p.y - p0.y), 0, p.x - p0.x);\n let vn = new Vector3(-(p2.y - p1.y), 0, p2.x - p1.x);\n if (!flip) {\n vc = vc.scale(-1);\n vp = vp.scale(-1);\n vn = vn.scale(-1);\n }\n const vc_norm = vc.normalizeToNew();\n let vp_norm = vp.normalizeToNew();\n let vn_norm = vn.normalizeToNew();\n const dotp = Vector3.Dot(vp_norm, vc_norm);\n if (dotp > smoothingThreshold) {\n if (dotp < Epsilon - 1) {\n vp_norm = new Vector3(p.x, 0, p.y).subtract(new Vector3(p1.x, 0, p1.y)).normalize();\n }\n else {\n // cheap average weighed by side length\n vp_norm = vp.add(vc).normalize();\n }\n }\n else {\n vp_norm = vc_norm;\n }\n const dotn = Vector3.Dot(vn, vc);\n if (dotn > smoothingThreshold) {\n if (dotn < Epsilon - 1) {\n // back to back\n vn_norm = new Vector3(p1.x, 0, p1.y).subtract(new Vector3(p.x, 0, p.y)).normalize();\n }\n else {\n // cheap average weighed by side length\n vn_norm = vn.add(vc).normalize();\n }\n }\n else {\n vn_norm = vc_norm;\n }\n uvs.push(ulength / bounds.width, 0);\n uvs.push(ulength / bounds.width, 1);\n ulength += vc.length();\n uvs.push(ulength / bounds.width, 0);\n uvs.push(ulength / bounds.width, 1);\n normals.push(vp_norm.x, vp_norm.y, vp_norm.z);\n normals.push(vp_norm.x, vp_norm.y, vp_norm.z);\n normals.push(vn_norm.x, vn_norm.y, vn_norm.z);\n normals.push(vn_norm.x, vn_norm.y, vn_norm.z);\n if (!flip) {\n indices.push(startIndex);\n indices.push(startIndex + 1);\n indices.push(startIndex + 2);\n indices.push(startIndex + 1);\n indices.push(startIndex + 3);\n indices.push(startIndex + 2);\n }\n else {\n indices.push(startIndex);\n indices.push(startIndex + 2);\n indices.push(startIndex + 1);\n indices.push(startIndex + 1);\n indices.push(startIndex + 2);\n indices.push(startIndex + 3);\n }\n startIndex += 4;\n }\n }\n}\n//# sourceMappingURL=polygonMesh.js.map","import { Vector2, Vector4 } from \"../../Maths/math.vector.js\";\nimport { Color4 } from \"../../Maths/math.color.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { PolygonMeshBuilder } from \"../polygonMesh.js\";\nimport { VertexBuffer } from \"../../Buffers/buffer.js\";\nimport { EngineStore } from \"../../Engines/engineStore.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n/**\n * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()\n * All parameters are provided by CreatePolygon as needed\n * @param polygon a mesh built from polygonTriangulation.build()\n * @param sideOrientation takes the values Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively\n * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively\n * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param wrp a boolean, default false, when true and fUVs used texture is wrapped around all sides, when false texture is applied side\n * @returns the VertexData of the Polygon\n */\nexport function CreatePolygonVertexData(polygon, sideOrientation, fUV, fColors, frontUVs, backUVs, wrp) {\n const faceUV = fUV || new Array(3);\n const faceColors = fColors;\n const colors = [];\n const wrap = wrp || false;\n // default face colors and UV if undefined\n for (let f = 0; f < 3; f++) {\n if (faceUV[f] === undefined) {\n faceUV[f] = new Vector4(0, 0, 1, 1);\n }\n if (faceColors && faceColors[f] === undefined) {\n faceColors[f] = new Color4(1, 1, 1, 1);\n }\n }\n const positions = polygon.getVerticesData(VertexBuffer.PositionKind);\n const normals = polygon.getVerticesData(VertexBuffer.NormalKind);\n const uvs = polygon.getVerticesData(VertexBuffer.UVKind);\n const indices = polygon.getIndices();\n const startIndex = positions.length / 9;\n let disp = 0;\n let distX = 0;\n let distZ = 0;\n let dist = 0;\n let totalLen = 0;\n const cumulate = [0];\n if (wrap) {\n for (let idx = startIndex; idx < positions.length / 3; idx += 4) {\n distX = positions[3 * (idx + 2)] - positions[3 * idx];\n distZ = positions[3 * (idx + 2) + 2] - positions[3 * idx + 2];\n dist = Math.sqrt(distX * distX + distZ * distZ);\n totalLen += dist;\n cumulate.push(totalLen);\n }\n }\n // set face colours and textures\n let idx = 0;\n let face = 0;\n for (let index = 0; index < normals.length; index += 3) {\n //Edge Face no. 1\n if (Math.abs(normals[index + 1]) < 0.001) {\n face = 1;\n }\n //Top Face no. 0\n if (Math.abs(normals[index + 1] - 1) < 0.001) {\n face = 0;\n }\n //Bottom Face no. 2\n if (Math.abs(normals[index + 1] + 1) < 0.001) {\n face = 2;\n }\n idx = index / 3;\n if (face === 1) {\n disp = idx - startIndex;\n if (disp % 4 < 1.5) {\n if (wrap) {\n uvs[2 * idx] = faceUV[face].x + ((faceUV[face].z - faceUV[face].x) * cumulate[Math.floor(disp / 4)]) / totalLen;\n }\n else {\n uvs[2 * idx] = faceUV[face].x;\n }\n }\n else {\n if (wrap) {\n uvs[2 * idx] = faceUV[face].x + ((faceUV[face].z - faceUV[face].x) * cumulate[Math.floor(disp / 4) + 1]) / totalLen;\n }\n else {\n uvs[2 * idx] = faceUV[face].z;\n }\n }\n if (disp % 2 === 0) {\n uvs[2 * idx + 1] = CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - faceUV[face].w : faceUV[face].w;\n }\n else {\n uvs[2 * idx + 1] = CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - faceUV[face].y : faceUV[face].y;\n }\n }\n else {\n uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;\n uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;\n if (CompatibilityOptions.UseOpenGLOrientationForUV) {\n uvs[2 * idx + 1] = 1.0 - uvs[2 * idx + 1];\n }\n }\n if (faceColors) {\n colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);\n }\n }\n // sides\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);\n // Result\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n if (faceColors) {\n const totalColors = sideOrientation === VertexData.DOUBLESIDE ? colors.concat(colors) : colors;\n vertexData.colors = totalColors;\n }\n return vertexData;\n}\n/**\n * Creates a polygon mesh\n * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh\n * * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors\n * * You can set the mesh side orientation with the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4)\n * * Remember you can only change the shape positions, not their number when updating a polygon\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.shape\n * @param options.holes\n * @param options.depth\n * @param options.smoothingThreshold\n * @param options.faceUV\n * @param options.faceColors\n * @param options.updatable\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.wrap\n * @param scene defines the hosting scene\n * @param earcutInjection can be used to inject your own earcut reference\n * @returns the polygon mesh\n */\nexport function CreatePolygon(name, options, scene = null, earcutInjection = earcut) {\n options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n const shape = options.shape;\n const holes = options.holes || [];\n const depth = options.depth || 0;\n const smoothingThreshold = options.smoothingThreshold || 2;\n const contours = [];\n let hole = [];\n for (let i = 0; i < shape.length; i++) {\n contours[i] = new Vector2(shape[i].x, shape[i].z);\n }\n const epsilon = 0.00000001;\n if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {\n contours.pop();\n }\n const polygonTriangulation = new PolygonMeshBuilder(name, contours, scene || EngineStore.LastCreatedScene, earcutInjection);\n for (let hNb = 0; hNb < holes.length; hNb++) {\n hole = [];\n for (let hPoint = 0; hPoint < holes[hNb].length; hPoint++) {\n hole.push(new Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));\n }\n polygonTriangulation.addHole(hole);\n }\n //updatability is set during applyToMesh; setting to true in triangulation build produces errors\n const polygon = polygonTriangulation.build(false, depth, smoothingThreshold);\n polygon._originalBuilderSideOrientation = options.sideOrientation;\n const vertexData = CreatePolygonVertexData(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs, options.wrap);\n vertexData.applyToMesh(polygon, options.updatable);\n return polygon;\n}\n/**\n * Creates an extruded polygon mesh, with depth in the Y direction.\n * * You can set different colors and different images to the top, bottom and extruded side by using the parameters `faceColors` (an array of 3 Color3 elements) and `faceUV` (an array of 3 Vector4 elements)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/texturePerBoxFace\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.shape\n * @param options.holes\n * @param options.depth\n * @param options.faceUV\n * @param options.faceColors\n * @param options.updatable\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.wrap\n * @param scene defines the hosting scene\n * @param earcutInjection can be used to inject your own earcut reference\n * @returns the polygon mesh\n */\nexport function ExtrudePolygon(name, options, scene = null, earcutInjection = earcut) {\n return CreatePolygon(name, options, scene, earcutInjection);\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use the functions directly from the module\n */\nexport const PolygonBuilder = {\n ExtrudePolygon,\n CreatePolygon,\n};\nVertexData.CreatePolygon = CreatePolygonVertexData;\nMesh.CreatePolygon = (name, shape, scene, holes, updatable, sideOrientation, earcutInjection = earcut) => {\n const options = {\n shape: shape,\n holes: holes,\n updatable: updatable,\n sideOrientation: sideOrientation,\n };\n return CreatePolygon(name, options, scene, earcutInjection);\n};\nMesh.ExtrudePolygon = (name, shape, depth, scene, holes, updatable, sideOrientation, earcutInjection = earcut) => {\n const options = {\n shape: shape,\n holes: holes,\n depth: depth,\n updatable: updatable,\n sideOrientation: sideOrientation,\n };\n return ExtrudePolygon(name, options, scene, earcutInjection);\n};\n//# sourceMappingURL=polygonBuilder.js.map","import { Vector3, TmpVectors, Matrix } from \"../../Maths/math.vector.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { CreateRibbon } from \"./ribbonBuilder.js\";\nimport { Path3D } from \"../../Maths/math.path.js\";\n/**\n * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.\n * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.\n * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.\n * * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.\n * * The parameter `scale` (float, default 1) is the value to scale the shape.\n * * The parameter `closeShape` (boolean, default false) closes the shape when true, since v5.0.0.\n * * The parameter `closePath` (boolean, default false) closes the path when true and no caps, since v5.0.0.\n * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL\n * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#extruded-shape\n * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.\n * * The optional parameter `firstNormal` (Vector3) defines the direction of the first normal of the supplied path. Consider using this for any path that is straight, and particular for paths in the xy plane.\n * * The optional `adjustFrame` (boolean, default false) will cause the internally generated Path3D tangents, normals, and binormals to be adjusted so that a) they are always well-defined, and b) they do not reverse from one path point to the next. This prevents the extruded shape from being flipped and/or rotated with resulting mesh self-intersections. This is primarily useful for straight paths that can reverse direction.\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.shape\n * @param options.path\n * @param options.scale\n * @param options.rotation\n * @param options.closeShape\n * @param options.closePath\n * @param options.cap\n * @param options.updatable\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.instance\n * @param options.invertUV\n * @param options.firstNormal\n * @param options.adjustFrame\n * @param scene defines the hosting scene\n * @returns the extruded shape mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#extruded-shapes\n */\nexport function ExtrudeShape(name, options, scene = null) {\n const path = options.path;\n const shape = options.shape;\n const scale = options.scale || 1;\n const rotation = options.rotation || 0;\n const cap = options.cap === 0 ? 0 : options.cap || Mesh.NO_CAP;\n const updatable = options.updatable;\n const sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n const instance = options.instance || null;\n const invertUV = options.invertUV || false;\n const closeShape = options.closeShape || false;\n const closePath = options.closePath || false;\n return _ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, closePath, closeShape, cap, false, scene, updatable ? true : false, sideOrientation, instance, invertUV, options.frontUVs || null, options.backUVs || null, options.firstNormal || null, options.adjustFrame ? true : false);\n}\n/**\n * Creates an custom extruded shape mesh.\n * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.\n * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.\n * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.\n * * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the beginning of the path\n * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.\n * * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the beginning of the path\n * * It must returns a float value that will be the scale value applied to the shape on each path point\n * * The parameter `closeShape` (boolean, default false) closes the shape when true, since v5.0.0.\n * * The parameter `closePath` (boolean, default false) closes the path when true and no caps, since v5.0.0.\n * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray` - depreciated in favor of closeShape\n * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray` - depreciated in favor of closePath\n * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL\n * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#extruded-shape\n * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * * The optional parameter `firstNormal` (Vector3) defines the direction of the first normal of the supplied path. It should be supplied when the path is in the xy plane, and particularly if these sections are straight, because the underlying Path3D object will pick a normal in the xy plane that causes the extrusion to be collapsed into the plane. This should be used for any path that is straight.\n * * The optional `adjustFrame` (boolean, default false) will cause the internally generated Path3D tangents, normals, and binormals to be adjusted so that a) they are always well-defined, and b) they do not reverse from one path point to the next. This prevents the extruded shape from being flipped and/or rotated with resulting mesh self-intersections. This is primarily useful for straight paths that can reverse direction.\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.shape\n * @param options.path\n * @param options.scaleFunction\n * @param options.rotationFunction\n * @param options.ribbonCloseArray\n * @param options.ribbonClosePath\n * @param options.closeShape\n * @param options.closePath\n * @param options.cap\n * @param options.updatable\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.instance\n * @param options.invertUV\n * @param options.firstNormal\n * @param options.adjustFrame\n * @param scene defines the hosting scene\n * @returns the custom extruded shape mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#custom-extruded-shapes\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#extruded-shapes\n */\nexport function ExtrudeShapeCustom(name, options, scene = null) {\n const path = options.path;\n const shape = options.shape;\n const scaleFunction = options.scaleFunction ||\n (() => {\n return 1;\n });\n const rotationFunction = options.rotationFunction ||\n (() => {\n return 0;\n });\n const ribbonCloseArray = options.closePath || options.ribbonCloseArray || false;\n const ribbonClosePath = options.closeShape || options.ribbonClosePath || false;\n const cap = options.cap === 0 ? 0 : options.cap || Mesh.NO_CAP;\n const updatable = options.updatable;\n const firstNormal = options.firstNormal || null;\n const adjustFrame = options.adjustFrame || false;\n const sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n const instance = options.instance;\n const invertUV = options.invertUV || false;\n return _ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable ? true : false, sideOrientation, instance || null, invertUV, options.frontUVs || null, options.backUVs || null, firstNormal, adjustFrame);\n}\nfunction _ExtrudeShapeGeneric(name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs, firstNormal, adjustFrame) {\n // extrusion geometry\n const extrusionPathArray = (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom, adjustFrame) => {\n const tangents = path3D.getTangents();\n const normals = path3D.getNormals();\n const binormals = path3D.getBinormals();\n const distances = path3D.getDistances();\n if (adjustFrame) {\n /* fix tangents,normals, binormals */\n for (let i = 0; i < tangents.length; i++) {\n if (tangents[i].x == 0 && tangents[i].y == 0 && tangents[i].z == 0) {\n tangents[i].copyFrom(tangents[i - 1]);\n }\n if (normals[i].x == 0 && normals[i].y == 0 && normals[i].z == 0) {\n normals[i].copyFrom(normals[i - 1]);\n }\n if (binormals[i].x == 0 && binormals[i].y == 0 && binormals[i].z == 0) {\n binormals[i].copyFrom(binormals[i - 1]);\n }\n if (i > 0) {\n let v = tangents[i - 1];\n if (Vector3.Dot(v, tangents[i]) < 0) {\n tangents[i].scaleInPlace(-1);\n }\n v = normals[i - 1];\n if (Vector3.Dot(v, normals[i]) < 0) {\n normals[i].scaleInPlace(-1);\n }\n v = binormals[i - 1];\n if (Vector3.Dot(v, binormals[i]) < 0) {\n binormals[i].scaleInPlace(-1);\n }\n }\n }\n }\n let angle = 0;\n const returnScale = () => {\n return scale !== null ? scale : 1;\n };\n const returnRotation = () => {\n return rotation !== null ? rotation : 0;\n };\n const rotate = custom && rotateFunction ? rotateFunction : returnRotation;\n const scl = custom && scaleFunction ? scaleFunction : returnScale;\n let index = cap === Mesh.NO_CAP || cap === Mesh.CAP_END ? 0 : 2;\n const rotationMatrix = TmpVectors.Matrix[0];\n for (let i = 0; i < curve.length; i++) {\n const shapePath = new Array();\n const angleStep = rotate(i, distances[i]);\n const scaleRatio = scl(i, distances[i]);\n Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);\n for (let p = 0; p < shape.length; p++) {\n const planed = tangents[i].scale(shape[p].z).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y));\n const rotated = Vector3.Zero();\n Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);\n rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);\n shapePath[p] = rotated;\n }\n shapePaths[index] = shapePath;\n angle += angleStep;\n index++;\n }\n // cap\n const capPath = (shapePath) => {\n const pointCap = Array();\n const barycenter = Vector3.Zero();\n let i;\n for (i = 0; i < shapePath.length; i++) {\n barycenter.addInPlace(shapePath[i]);\n }\n barycenter.scaleInPlace(1.0 / shapePath.length);\n for (i = 0; i < shapePath.length; i++) {\n pointCap.push(barycenter);\n }\n return pointCap;\n };\n switch (cap) {\n case Mesh.NO_CAP:\n break;\n case Mesh.CAP_START:\n shapePaths[0] = capPath(shapePaths[2]);\n shapePaths[1] = shapePaths[2];\n break;\n case Mesh.CAP_END:\n shapePaths[index] = shapePaths[index - 1];\n shapePaths[index + 1] = capPath(shapePaths[index - 1]);\n break;\n case Mesh.CAP_ALL:\n shapePaths[0] = capPath(shapePaths[2]);\n shapePaths[1] = shapePaths[2];\n shapePaths[index] = shapePaths[index - 1];\n shapePaths[index + 1] = capPath(shapePaths[index - 1]);\n break;\n default:\n break;\n }\n return shapePaths;\n };\n let path3D;\n let pathArray;\n if (instance) {\n // instance update\n const storage = instance._creationDataStorage;\n path3D = firstNormal ? storage.path3D.update(curve, firstNormal) : storage.path3D.update(curve);\n pathArray = extrusionPathArray(shape, curve, storage.path3D, storage.pathArray, scale, rotation, scaleFunction, rotateFunction, storage.cap, custom, adjustFrame);\n instance = CreateRibbon(\"\", { pathArray, closeArray: false, closePath: false, offset: 0, updatable: false, sideOrientation: 0, instance }, scene || undefined);\n return instance;\n }\n // extruded shape creation\n path3D = firstNormal ? new Path3D(curve, firstNormal) : new Path3D(curve);\n const newShapePaths = new Array();\n cap = cap < 0 || cap > 3 ? 0 : cap;\n pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom, adjustFrame);\n const extrudedGeneric = CreateRibbon(name, {\n pathArray: pathArray,\n closeArray: rbCA,\n closePath: rbCP,\n updatable: updtbl,\n sideOrientation: side,\n invertUV: invertUV,\n frontUVs: frontUVs || undefined,\n backUVs: backUVs || undefined,\n }, scene);\n extrudedGeneric._creationDataStorage.pathArray = pathArray;\n extrudedGeneric._creationDataStorage.path3D = path3D;\n extrudedGeneric._creationDataStorage.cap = cap;\n return extrudedGeneric;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated please use the functions directly from the module\n */\nexport const ShapeBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ExtrudeShape,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ExtrudeShapeCustom,\n};\nMesh.ExtrudeShape = (name, shape, path, scale, rotation, cap, scene = null, updatable, sideOrientation, instance) => {\n const options = {\n shape: shape,\n path: path,\n scale: scale,\n rotation: rotation,\n cap: cap === 0 ? 0 : cap || Mesh.NO_CAP,\n sideOrientation: sideOrientation,\n instance: instance,\n updatable: updatable,\n };\n return ExtrudeShape(name, options, scene);\n};\nMesh.ExtrudeShapeCustom = (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) => {\n const options = {\n shape: shape,\n path: path,\n scaleFunction: scaleFunction,\n rotationFunction: rotationFunction,\n ribbonCloseArray: ribbonCloseArray,\n ribbonClosePath: ribbonClosePath,\n cap: cap === 0 ? 0 : cap || Mesh.NO_CAP,\n sideOrientation: sideOrientation,\n instance: instance,\n updatable: updatable,\n };\n return ExtrudeShapeCustom(name, options, scene);\n};\n//# sourceMappingURL=shapeBuilder.js.map","import { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { CreateRibbon } from \"./ribbonBuilder.js\";\n/**\n * Creates lathe mesh.\n * The lathe is a shape with a symmetry axis : a 2D model shape is rotated around this axis to design the lathe\n * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero\n * * The parameter `radius` (positive float, default 1) is the radius value of the lathe\n * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe\n * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides\n * * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape\n * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter \"arc\"\n * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.shape\n * @param options.radius\n * @param options.tessellation\n * @param options.clip\n * @param options.arc\n * @param options.closed\n * @param options.updatable\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.cap\n * @param options.invertUV\n * @param scene defines the hosting scene\n * @returns the lathe mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#lathe\n */\nexport function CreateLathe(name, options, scene = null) {\n const arc = options.arc ? (options.arc <= 0 || options.arc > 1 ? 1.0 : options.arc) : 1.0;\n const closed = options.closed === undefined ? true : options.closed;\n const shape = options.shape;\n const radius = options.radius || 1;\n const tessellation = options.tessellation || 64;\n const clip = options.clip || 0;\n const updatable = options.updatable;\n const sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n const cap = options.cap || Mesh.NO_CAP;\n const pi2 = Math.PI * 2;\n const paths = new Array();\n const invertUV = options.invertUV || false;\n let i = 0;\n let p = 0;\n const step = (pi2 / tessellation) * arc;\n let rotated;\n let path;\n for (i = 0; i <= tessellation - clip; i++) {\n path = [];\n if (cap == Mesh.CAP_START || cap == Mesh.CAP_ALL) {\n path.push(new Vector3(0, shape[0].y, 0));\n path.push(new Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));\n }\n for (p = 0; p < shape.length; p++) {\n rotated = new Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);\n path.push(rotated);\n }\n if (cap == Mesh.CAP_END || cap == Mesh.CAP_ALL) {\n path.push(new Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius));\n path.push(new Vector3(0, shape[shape.length - 1].y, 0));\n }\n paths.push(path);\n }\n // lathe ribbon\n const lathe = CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);\n return lathe;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use the function direction from the module\n */\nexport const LatheBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateLathe,\n};\nMesh.CreateLathe = (name, shape, radius, tessellation, scene, updatable, sideOrientation) => {\n const options = {\n shape: shape,\n radius: radius,\n tessellation: tessellation,\n sideOrientation: sideOrientation,\n updatable: updatable,\n };\n return CreateLathe(name, options, scene);\n};\n//# sourceMappingURL=latheBuilder.js.map","import { Vector3, TmpVectors, Matrix } from \"../../Maths/math.vector.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { CreateRibbon } from \"./ribbonBuilder.js\";\nimport { Path3D } from \"../../Maths/math.path.js\";\n/**\n * Creates a tube mesh.\n * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters\n * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube\n * * The parameter `radius` (positive float, default 1) sets the tube radius size\n * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface\n * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overrides the parameter `radius`\n * * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. It must return a radius value (positive float)\n * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc\n * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL\n * * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter. The `path`Array HAS to have the SAME number of points as the previous one: https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#tube\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. The NUMBER of points CAN'T CHANGE, only their positions.\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.path\n * @param options.radius\n * @param options.tessellation\n * @param options.radiusFunction\n * @param options.cap\n * @param options.arc\n * @param options.updatable\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.instance\n * @param options.invertUV\n * @param scene defines the hosting scene\n * @returns the tube mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#tube\n */\nexport function CreateTube(name, options, scene = null) {\n const path = options.path;\n let instance = options.instance;\n let radius = 1.0;\n if (options.radius !== undefined) {\n radius = options.radius;\n }\n else if (instance) {\n radius = instance._creationDataStorage.radius;\n }\n const tessellation = options.tessellation || 64 | 0;\n const radiusFunction = options.radiusFunction || null;\n let cap = options.cap || Mesh.NO_CAP;\n const invertUV = options.invertUV || false;\n const updatable = options.updatable;\n const sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;\n // tube geometry\n const tubePathArray = (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) => {\n const tangents = path3D.getTangents();\n const normals = path3D.getNormals();\n const distances = path3D.getDistances();\n const pi2 = Math.PI * 2;\n const step = (pi2 / tessellation) * arc;\n const returnRadius = () => radius;\n const radiusFunctionFinal = radiusFunction || returnRadius;\n let circlePath;\n let rad;\n let normal;\n let rotated;\n const rotationMatrix = TmpVectors.Matrix[0];\n let index = cap === Mesh.NO_CAP || cap === Mesh.CAP_END ? 0 : 2;\n for (let i = 0; i < path.length; i++) {\n rad = radiusFunctionFinal(i, distances[i]); // current radius\n circlePath = Array(); // current circle array\n normal = normals[i]; // current normal\n for (let t = 0; t < tessellation; t++) {\n Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);\n rotated = circlePath[t] ? circlePath[t] : Vector3.Zero();\n Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);\n rotated.scaleInPlace(rad).addInPlace(path[i]);\n circlePath[t] = rotated;\n }\n circlePaths[index] = circlePath;\n index++;\n }\n // cap\n const capPath = (nbPoints, pathIndex) => {\n const pointCap = Array();\n for (let i = 0; i < nbPoints; i++) {\n pointCap.push(path[pathIndex]);\n }\n return pointCap;\n };\n switch (cap) {\n case Mesh.NO_CAP:\n break;\n case Mesh.CAP_START:\n circlePaths[0] = capPath(tessellation, 0);\n circlePaths[1] = circlePaths[2].slice(0);\n break;\n case Mesh.CAP_END:\n circlePaths[index] = circlePaths[index - 1].slice(0);\n circlePaths[index + 1] = capPath(tessellation, path.length - 1);\n break;\n case Mesh.CAP_ALL:\n circlePaths[0] = capPath(tessellation, 0);\n circlePaths[1] = circlePaths[2].slice(0);\n circlePaths[index] = circlePaths[index - 1].slice(0);\n circlePaths[index + 1] = capPath(tessellation, path.length - 1);\n break;\n default:\n break;\n }\n return circlePaths;\n };\n let path3D;\n let pathArray;\n if (instance) {\n // tube update\n const storage = instance._creationDataStorage;\n const arc = options.arc || storage.arc;\n path3D = storage.path3D.update(path);\n pathArray = tubePathArray(path, path3D, storage.pathArray, radius, storage.tessellation, radiusFunction, storage.cap, arc);\n instance = CreateRibbon(\"\", { pathArray: pathArray, instance: instance });\n // Update mode, no need to recreate the storage.\n storage.path3D = path3D;\n storage.pathArray = pathArray;\n storage.arc = arc;\n storage.radius = radius;\n return instance;\n }\n // tube creation\n path3D = new Path3D(path);\n const newPathArray = new Array();\n cap = cap < 0 || cap > 3 ? 0 : cap;\n pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);\n const tube = CreateRibbon(name, {\n pathArray: pathArray,\n closePath: true,\n closeArray: false,\n updatable: updatable,\n sideOrientation: sideOrientation,\n invertUV: invertUV,\n frontUVs: options.frontUVs,\n backUVs: options.backUVs,\n }, scene);\n tube._creationDataStorage.pathArray = pathArray;\n tube._creationDataStorage.path3D = path3D;\n tube._creationDataStorage.tessellation = tessellation;\n tube._creationDataStorage.cap = cap;\n tube._creationDataStorage.arc = options.arc;\n tube._creationDataStorage.radius = radius;\n return tube;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use CreateTube directly\n */\nexport const TubeBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateTube,\n};\nMesh.CreateTube = (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) => {\n const options = {\n path: path,\n radius: radius,\n tessellation: tessellation,\n radiusFunction: radiusFunction,\n arc: 1,\n cap: cap,\n updatable: updatable,\n sideOrientation: sideOrientation,\n instance: instance,\n };\n return CreateTube(name, options, scene);\n};\n//# sourceMappingURL=tubeBuilder.js.map","import { Vector4 } from \"../../Maths/math.vector.js\";\nimport { Color4 } from \"../../Maths/math.color.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n// inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html\n/**\n * Creates the VertexData for a Polyhedron\n * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty\n * * type provided types are:\n * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)\n * * 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)\n * * size the size of the IcoSphere, optional default 1\n * * sizeX allows stretching in the x direction, optional, default size\n * * sizeY allows stretching in the y direction, optional, default size\n * * sizeZ allows stretching in the z direction, optional, default size\n * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor\n * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively\n * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively\n * * flat when true creates a flat shaded mesh, optional, default true\n * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.type\n * @param options.size\n * @param options.sizeX\n * @param options.sizeY\n * @param options.sizeZ\n * @param options.custom\n * @param options.faceUV\n * @param options.faceColors\n * @param options.flat\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the Polyhedron\n */\nexport function CreatePolyhedronVertexData(options) {\n // provided polyhedron types :\n // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)\n // 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)\n const polyhedra = [];\n polyhedra[0] = {\n vertex: [\n [0, 0, 1.732051],\n [1.632993, 0, -0.5773503],\n [-0.8164966, 1.414214, -0.5773503],\n [-0.8164966, -1.414214, -0.5773503],\n ],\n face: [\n [0, 1, 2],\n [0, 2, 3],\n [0, 3, 1],\n [1, 3, 2],\n ],\n };\n polyhedra[1] = {\n vertex: [\n [0, 0, 1.414214],\n [1.414214, 0, 0],\n [0, 1.414214, 0],\n [-1.414214, 0, 0],\n [0, -1.414214, 0],\n [0, 0, -1.414214],\n ],\n face: [\n [0, 1, 2],\n [0, 2, 3],\n [0, 3, 4],\n [0, 4, 1],\n [1, 4, 5],\n [1, 5, 2],\n [2, 5, 3],\n [3, 5, 4],\n ],\n };\n polyhedra[2] = {\n vertex: [\n [0, 0, 1.070466],\n [0.7136442, 0, 0.7978784],\n [-0.3568221, 0.618034, 0.7978784],\n [-0.3568221, -0.618034, 0.7978784],\n [0.7978784, 0.618034, 0.3568221],\n [0.7978784, -0.618034, 0.3568221],\n [-0.9341724, 0.381966, 0.3568221],\n [0.1362939, 1, 0.3568221],\n [0.1362939, -1, 0.3568221],\n [-0.9341724, -0.381966, 0.3568221],\n [0.9341724, 0.381966, -0.3568221],\n [0.9341724, -0.381966, -0.3568221],\n [-0.7978784, 0.618034, -0.3568221],\n [-0.1362939, 1, -0.3568221],\n [-0.1362939, -1, -0.3568221],\n [-0.7978784, -0.618034, -0.3568221],\n [0.3568221, 0.618034, -0.7978784],\n [0.3568221, -0.618034, -0.7978784],\n [-0.7136442, 0, -0.7978784],\n [0, 0, -1.070466],\n ],\n face: [\n [0, 1, 4, 7, 2],\n [0, 2, 6, 9, 3],\n [0, 3, 8, 5, 1],\n [1, 5, 11, 10, 4],\n [2, 7, 13, 12, 6],\n [3, 9, 15, 14, 8],\n [4, 10, 16, 13, 7],\n [5, 8, 14, 17, 11],\n [6, 12, 18, 15, 9],\n [10, 11, 17, 19, 16],\n [12, 13, 16, 19, 18],\n [14, 15, 18, 19, 17],\n ],\n };\n polyhedra[3] = {\n vertex: [\n [0, 0, 1.175571],\n [1.051462, 0, 0.5257311],\n [0.3249197, 1, 0.5257311],\n [-0.8506508, 0.618034, 0.5257311],\n [-0.8506508, -0.618034, 0.5257311],\n [0.3249197, -1, 0.5257311],\n [0.8506508, 0.618034, -0.5257311],\n [0.8506508, -0.618034, -0.5257311],\n [-0.3249197, 1, -0.5257311],\n [-1.051462, 0, -0.5257311],\n [-0.3249197, -1, -0.5257311],\n [0, 0, -1.175571],\n ],\n face: [\n [0, 1, 2],\n [0, 2, 3],\n [0, 3, 4],\n [0, 4, 5],\n [0, 5, 1],\n [1, 5, 7],\n [1, 7, 6],\n [1, 6, 2],\n [2, 6, 8],\n [2, 8, 3],\n [3, 8, 9],\n [3, 9, 4],\n [4, 9, 10],\n [4, 10, 5],\n [5, 10, 7],\n [6, 7, 11],\n [6, 11, 8],\n [7, 10, 11],\n [8, 11, 9],\n [9, 11, 10],\n ],\n };\n polyhedra[4] = {\n vertex: [\n [0, 0, 1.070722],\n [0.7148135, 0, 0.7971752],\n [-0.104682, 0.7071068, 0.7971752],\n [-0.6841528, 0.2071068, 0.7971752],\n [-0.104682, -0.7071068, 0.7971752],\n [0.6101315, 0.7071068, 0.5236279],\n [1.04156, 0.2071068, 0.1367736],\n [0.6101315, -0.7071068, 0.5236279],\n [-0.3574067, 1, 0.1367736],\n [-0.7888348, -0.5, 0.5236279],\n [-0.9368776, 0.5, 0.1367736],\n [-0.3574067, -1, 0.1367736],\n [0.3574067, 1, -0.1367736],\n [0.9368776, -0.5, -0.1367736],\n [0.7888348, 0.5, -0.5236279],\n [0.3574067, -1, -0.1367736],\n [-0.6101315, 0.7071068, -0.5236279],\n [-1.04156, -0.2071068, -0.1367736],\n [-0.6101315, -0.7071068, -0.5236279],\n [0.104682, 0.7071068, -0.7971752],\n [0.6841528, -0.2071068, -0.7971752],\n [0.104682, -0.7071068, -0.7971752],\n [-0.7148135, 0, -0.7971752],\n [0, 0, -1.070722],\n ],\n face: [\n [0, 2, 3],\n [1, 6, 5],\n [4, 9, 11],\n [7, 15, 13],\n [8, 16, 10],\n [12, 14, 19],\n [17, 22, 18],\n [20, 21, 23],\n [0, 1, 5, 2],\n [0, 3, 9, 4],\n [0, 4, 7, 1],\n [1, 7, 13, 6],\n [2, 5, 12, 8],\n [2, 8, 10, 3],\n [3, 10, 17, 9],\n [4, 11, 15, 7],\n [5, 6, 14, 12],\n [6, 13, 20, 14],\n [8, 12, 19, 16],\n [9, 17, 18, 11],\n [10, 16, 22, 17],\n [11, 18, 21, 15],\n [13, 15, 21, 20],\n [14, 20, 23, 19],\n [16, 19, 23, 22],\n [18, 22, 23, 21],\n ],\n };\n polyhedra[5] = {\n vertex: [\n [0, 0, 1.322876],\n [1.309307, 0, 0.1889822],\n [-0.9819805, 0.8660254, 0.1889822],\n [0.1636634, -1.299038, 0.1889822],\n [0.3273268, 0.8660254, -0.9449112],\n [-0.8183171, -0.4330127, -0.9449112],\n ],\n face: [\n [0, 3, 1],\n [2, 4, 5],\n [0, 1, 4, 2],\n [0, 2, 5, 3],\n [1, 3, 5, 4],\n ],\n };\n polyhedra[6] = {\n vertex: [\n [0, 0, 1.159953],\n [1.013464, 0, 0.5642542],\n [-0.3501431, 0.9510565, 0.5642542],\n [-0.7715208, -0.6571639, 0.5642542],\n [0.6633206, 0.9510565, -0.03144481],\n [0.8682979, -0.6571639, -0.3996071],\n [-1.121664, 0.2938926, -0.03144481],\n [-0.2348831, -1.063314, -0.3996071],\n [0.5181548, 0.2938926, -0.9953061],\n [-0.5850262, -0.112257, -0.9953061],\n ],\n face: [\n [0, 1, 4, 2],\n [0, 2, 6, 3],\n [1, 5, 8, 4],\n [3, 6, 9, 7],\n [5, 7, 9, 8],\n [0, 3, 7, 5, 1],\n [2, 4, 8, 9, 6],\n ],\n };\n polyhedra[7] = {\n vertex: [\n [0, 0, 1.118034],\n [0.8944272, 0, 0.6708204],\n [-0.2236068, 0.8660254, 0.6708204],\n [-0.7826238, -0.4330127, 0.6708204],\n [0.6708204, 0.8660254, 0.2236068],\n [1.006231, -0.4330127, -0.2236068],\n [-1.006231, 0.4330127, 0.2236068],\n [-0.6708204, -0.8660254, -0.2236068],\n [0.7826238, 0.4330127, -0.6708204],\n [0.2236068, -0.8660254, -0.6708204],\n [-0.8944272, 0, -0.6708204],\n [0, 0, -1.118034],\n ],\n face: [\n [0, 1, 4, 2],\n [0, 2, 6, 3],\n [1, 5, 8, 4],\n [3, 6, 10, 7],\n [5, 9, 11, 8],\n [7, 10, 11, 9],\n [0, 3, 7, 9, 5, 1],\n [2, 4, 8, 11, 10, 6],\n ],\n };\n polyhedra[8] = {\n vertex: [\n [-0.729665, 0.670121, 0.319155],\n [-0.655235, -0.29213, -0.754096],\n [-0.093922, -0.607123, 0.537818],\n [0.702196, 0.595691, 0.485187],\n [0.776626, -0.36656, -0.588064],\n ],\n face: [\n [1, 4, 2],\n [0, 1, 2],\n [3, 0, 2],\n [4, 3, 2],\n [4, 1, 0, 3],\n ],\n };\n polyhedra[9] = {\n vertex: [\n [-0.868849, -0.100041, 0.61257],\n [-0.329458, 0.976099, 0.28078],\n [-0.26629, -0.013796, -0.477654],\n [-0.13392, -1.034115, 0.229829],\n [0.738834, 0.707117, -0.307018],\n [0.859683, -0.535264, -0.338508],\n ],\n face: [\n [3, 0, 2],\n [5, 3, 2],\n [4, 5, 2],\n [1, 4, 2],\n [0, 1, 2],\n [0, 3, 5, 4, 1],\n ],\n };\n polyhedra[10] = {\n vertex: [\n [-0.610389, 0.243975, 0.531213],\n [-0.187812, -0.48795, -0.664016],\n [-0.187812, 0.9759, -0.664016],\n [0.187812, -0.9759, 0.664016],\n [0.798201, 0.243975, 0.132803],\n ],\n face: [\n [1, 3, 0],\n [3, 4, 0],\n [3, 1, 4],\n [0, 2, 1],\n [0, 4, 2],\n [2, 4, 1],\n ],\n };\n polyhedra[11] = {\n vertex: [\n [-1.028778, 0.392027, -0.048786],\n [-0.640503, -0.646161, 0.621837],\n [-0.125162, -0.395663, -0.540059],\n [0.004683, 0.888447, -0.651988],\n [0.125161, 0.395663, 0.540059],\n [0.632925, -0.791376, 0.433102],\n [1.031672, 0.157063, -0.354165],\n ],\n face: [\n [3, 2, 0],\n [2, 1, 0],\n [2, 5, 1],\n [0, 4, 3],\n [0, 1, 4],\n [4, 1, 5],\n [2, 3, 6],\n [3, 4, 6],\n [5, 2, 6],\n [4, 5, 6],\n ],\n };\n polyhedra[12] = {\n vertex: [\n [-0.669867, 0.334933, -0.529576],\n [-0.669867, 0.334933, 0.529577],\n [-0.4043, 1.212901, 0],\n [-0.334933, -0.669867, -0.529576],\n [-0.334933, -0.669867, 0.529577],\n [0.334933, 0.669867, -0.529576],\n [0.334933, 0.669867, 0.529577],\n [0.4043, -1.212901, 0],\n [0.669867, -0.334933, -0.529576],\n [0.669867, -0.334933, 0.529577],\n ],\n face: [\n [8, 9, 7],\n [6, 5, 2],\n [3, 8, 7],\n [5, 0, 2],\n [4, 3, 7],\n [0, 1, 2],\n [9, 4, 7],\n [1, 6, 2],\n [9, 8, 5, 6],\n [8, 3, 0, 5],\n [3, 4, 1, 0],\n [4, 9, 6, 1],\n ],\n };\n polyhedra[13] = {\n vertex: [\n [-0.931836, 0.219976, -0.264632],\n [-0.636706, 0.318353, 0.692816],\n [-0.613483, -0.735083, -0.264632],\n [-0.326545, 0.979634, 0],\n [-0.318353, -0.636706, 0.692816],\n [-0.159176, 0.477529, -0.856368],\n [0.159176, -0.477529, -0.856368],\n [0.318353, 0.636706, 0.692816],\n [0.326545, -0.979634, 0],\n [0.613482, 0.735082, -0.264632],\n [0.636706, -0.318353, 0.692816],\n [0.931835, -0.219977, -0.264632],\n ],\n face: [\n [11, 10, 8],\n [7, 9, 3],\n [6, 11, 8],\n [9, 5, 3],\n [2, 6, 8],\n [5, 0, 3],\n [4, 2, 8],\n [0, 1, 3],\n [10, 4, 8],\n [1, 7, 3],\n [10, 11, 9, 7],\n [11, 6, 5, 9],\n [6, 2, 0, 5],\n [2, 4, 1, 0],\n [4, 10, 7, 1],\n ],\n };\n polyhedra[14] = {\n vertex: [\n [-0.93465, 0.300459, -0.271185],\n [-0.838689, -0.260219, -0.516017],\n [-0.711319, 0.717591, 0.128359],\n [-0.710334, -0.156922, 0.080946],\n [-0.599799, 0.556003, -0.725148],\n [-0.503838, -0.004675, -0.969981],\n [-0.487004, 0.26021, 0.48049],\n [-0.460089, -0.750282, -0.512622],\n [-0.376468, 0.973135, -0.325605],\n [-0.331735, -0.646985, 0.084342],\n [-0.254001, 0.831847, 0.530001],\n [-0.125239, -0.494738, -0.966586],\n [0.029622, 0.027949, 0.730817],\n [0.056536, -0.982543, -0.262295],\n [0.08085, 1.087391, 0.076037],\n [0.125583, -0.532729, 0.485984],\n [0.262625, 0.599586, 0.780328],\n [0.391387, -0.726999, -0.716259],\n [0.513854, -0.868287, 0.139347],\n [0.597475, 0.85513, 0.326364],\n [0.641224, 0.109523, 0.783723],\n [0.737185, -0.451155, 0.538891],\n [0.848705, -0.612742, -0.314616],\n [0.976075, 0.365067, 0.32976],\n [1.072036, -0.19561, 0.084927],\n ],\n face: [\n [15, 18, 21],\n [12, 20, 16],\n [6, 10, 2],\n [3, 0, 1],\n [9, 7, 13],\n [2, 8, 4, 0],\n [0, 4, 5, 1],\n [1, 5, 11, 7],\n [7, 11, 17, 13],\n [13, 17, 22, 18],\n [18, 22, 24, 21],\n [21, 24, 23, 20],\n [20, 23, 19, 16],\n [16, 19, 14, 10],\n [10, 14, 8, 2],\n [15, 9, 13, 18],\n [12, 15, 21, 20],\n [6, 12, 16, 10],\n [3, 6, 2, 0],\n [9, 3, 1, 7],\n [9, 15, 12, 6, 3],\n [22, 17, 11, 5, 4, 8, 14, 19, 23, 24],\n ],\n };\n const type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;\n const size = options.size;\n const sizeX = options.sizeX || size || 1;\n const sizeY = options.sizeY || size || 1;\n const sizeZ = options.sizeZ || size || 1;\n const data = options.custom || polyhedra[type];\n const nbfaces = data.face.length;\n const faceUV = options.faceUV || new Array(nbfaces);\n const faceColors = options.faceColors;\n const flat = options.flat === undefined ? true : options.flat;\n const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;\n const positions = new Array();\n const indices = new Array();\n const normals = new Array();\n const uvs = new Array();\n const colors = new Array();\n let index = 0;\n let faceIdx = 0; // face cursor in the array \"indexes\"\n const indexes = new Array();\n let i = 0;\n let f = 0;\n let u, v, ang, x, y, tmp;\n // default face colors and UV if undefined\n if (flat) {\n for (f = 0; f < nbfaces; f++) {\n if (faceColors && faceColors[f] === undefined) {\n faceColors[f] = new Color4(1, 1, 1, 1);\n }\n if (faceUV && faceUV[f] === undefined) {\n faceUV[f] = new Vector4(0, 0, 1, 1);\n }\n }\n }\n if (!flat) {\n for (i = 0; i < data.vertex.length; i++) {\n positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);\n uvs.push(0, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 : 0);\n }\n for (f = 0; f < nbfaces; f++) {\n for (i = 0; i < data.face[f].length - 2; i++) {\n indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);\n }\n }\n }\n else {\n for (f = 0; f < nbfaces; f++) {\n const fl = data.face[f].length; // number of vertices of the current face\n ang = (2 * Math.PI) / fl;\n x = 0.5 * Math.tan(ang / 2);\n y = 0.5;\n // positions, uvs, colors\n for (i = 0; i < fl; i++) {\n // positions\n positions.push(data.vertex[data.face[f][i]][0] * sizeX, data.vertex[data.face[f][i]][1] * sizeY, data.vertex[data.face[f][i]][2] * sizeZ);\n indexes.push(index);\n index++;\n // uvs\n u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);\n v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);\n uvs.push(u, CompatibilityOptions.UseOpenGLOrientationForUV ? 1.0 - v : v);\n tmp = x * Math.cos(ang) - y * Math.sin(ang);\n y = x * Math.sin(ang) + y * Math.cos(ang);\n x = tmp;\n // colors\n if (faceColors) {\n colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);\n }\n }\n // indices from indexes\n for (i = 0; i < fl - 2; i++) {\n indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);\n }\n faceIdx += fl;\n }\n }\n VertexData.ComputeNormals(positions, indices, normals);\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);\n const vertexData = new VertexData();\n vertexData.positions = positions;\n vertexData.indices = indices;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n if (faceColors && flat) {\n vertexData.colors = colors;\n }\n return vertexData;\n}\n/**\n * Creates a polyhedron mesh\n * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type\n * * The parameter `size` (positive float, default 1) sets the polygon size\n * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)\n * * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overrides the parameter `type`\n * * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron\n * * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`)\n * * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : https://doc.babylonjs.com/features/featuresDeepDive/materials/using/texturePerBoxFace\n * * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored\n * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE\n * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation\n * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created\n * @param name defines the name of the mesh\n * @param options defines the options used to create the mesh\n * @param options.type\n * @param options.size\n * @param options.sizeX\n * @param options.sizeY\n * @param options.sizeZ\n * @param options.custom\n * @param options.faceUV\n * @param options.faceColors\n * @param options.flat\n * @param options.updatable\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param scene defines the hosting scene\n * @returns the polyhedron mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/polyhedra\n */\nexport function CreatePolyhedron(name, options = {}, scene = null) {\n const polyhedron = new Mesh(name, scene);\n options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n polyhedron._originalBuilderSideOrientation = options.sideOrientation;\n const vertexData = CreatePolyhedronVertexData(options);\n vertexData.applyToMesh(polyhedron, options.updatable);\n return polyhedron;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use the function directly from the module\n */\nexport const PolyhedronBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreatePolyhedron,\n};\nVertexData.CreatePolyhedron = CreatePolyhedronVertexData;\nMesh.CreatePolyhedron = (name, options, scene) => {\n return CreatePolyhedron(name, options, scene);\n};\n//# sourceMappingURL=polyhedronBuilder.js.map","import { Vector3, Matrix, Vector2, TmpVectors } from \"../../Maths/math.vector.js\";\nimport { Scalar } from \"../../Maths/math.scalar.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { VertexBuffer } from \"../../Buffers/buffer.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\nconst xpAxis = new Vector3(1, 0, 0);\nconst xnAxis = new Vector3(-1, 0, 0);\nconst ypAxis = new Vector3(0, 1, 0);\nconst ynAxis = new Vector3(0, -1, 0);\nconst zpAxis = new Vector3(0, 0, 1);\nconst znAxis = new Vector3(0, 0, -1);\n/** @internal */\nclass DecalVertex {\n constructor(position = Vector3.Zero(), normal = Vector3.Up(), uv = Vector2.Zero(), vertexIdx = 0, vertexIdxForBones = 0, localPositionOverride = null, localNormalOverride = null, matrixIndicesOverride = null, matrixWeightsOverride = null) {\n this.position = position;\n this.normal = normal;\n this.uv = uv;\n this.vertexIdx = vertexIdx;\n this.vertexIdxForBones = vertexIdxForBones;\n this.localPositionOverride = localPositionOverride;\n this.localNormalOverride = localNormalOverride;\n this.matrixIndicesOverride = matrixIndicesOverride;\n this.matrixWeightsOverride = matrixWeightsOverride;\n }\n clone() {\n var _a, _b, _c, _d;\n return new DecalVertex(this.position.clone(), this.normal.clone(), this.uv.clone(), this.vertexIdx, this.vertexIdxForBones, (_a = this.localPositionOverride) === null || _a === void 0 ? void 0 : _a.slice(), (_b = this.localNormalOverride) === null || _b === void 0 ? void 0 : _b.slice(), (_c = this.matrixIndicesOverride) === null || _c === void 0 ? void 0 : _c.slice(), (_d = this.matrixWeightsOverride) === null || _d === void 0 ? void 0 : _d.slice());\n }\n}\n/**\n * Creates a decal mesh.\n * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal\n * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates\n * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates\n * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling\n * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal\n * * The parameter `captureUVS` defines if we need to capture the uvs or compute them\n * * The parameter `cullBackFaces` defines if the back faces should be removed from the decal mesh\n * * The parameter `localMode` defines that the computations should be done with the local mesh coordinates instead of the world space coordinates.\n * * Use this mode if you want the decal to be parented to the sourceMesh and move/rotate with it.\n * Note: Meshes with morph targets are not supported!\n * @param name defines the name of the mesh\n * @param sourceMesh defines the mesh where the decal must be applied\n * @param options defines the options used to create the mesh\n * @param options.position\n * @param options.normal\n * @param options.size\n * @param options.angle\n * @param options.captureUVS\n * @param options.cullBackFaces\n * @param options.localMode\n * @returns the decal mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/decals\n */\nexport function CreateDecal(name, sourceMesh, options) {\n var _a, _b, _c, _d;\n const hasSkeleton = !!sourceMesh.skeleton;\n const useLocalComputation = options.localMode || hasSkeleton;\n const meshHasOverridenMaterial = sourceMesh.overrideMaterialSideOrientation !== null && sourceMesh.overrideMaterialSideOrientation !== undefined;\n const indices = sourceMesh.getIndices();\n const positions = hasSkeleton ? sourceMesh.getPositionData(true, true) : sourceMesh.getVerticesData(VertexBuffer.PositionKind);\n const normals = hasSkeleton ? sourceMesh.getNormalsData(true, true) : sourceMesh.getVerticesData(VertexBuffer.NormalKind);\n const localPositions = useLocalComputation ? (hasSkeleton ? sourceMesh.getVerticesData(VertexBuffer.PositionKind) : positions) : null;\n const localNormals = useLocalComputation ? (hasSkeleton ? sourceMesh.getVerticesData(VertexBuffer.NormalKind) : normals) : null;\n const uvs = sourceMesh.getVerticesData(VertexBuffer.UVKind);\n const matIndices = hasSkeleton ? sourceMesh.getVerticesData(VertexBuffer.MatricesIndicesKind) : null;\n const matWeights = hasSkeleton ? sourceMesh.getVerticesData(VertexBuffer.MatricesWeightsKind) : null;\n const matIndicesExtra = hasSkeleton ? sourceMesh.getVerticesData(VertexBuffer.MatricesIndicesExtraKind) : null;\n const matWeightsExtra = hasSkeleton ? sourceMesh.getVerticesData(VertexBuffer.MatricesWeightsExtraKind) : null;\n const position = options.position || Vector3.Zero();\n let normal = options.normal || Vector3.Up();\n const size = options.size || Vector3.One();\n const angle = options.angle || 0;\n // Getting correct rotation\n if (!normal) {\n const target = new Vector3(0, 0, 1);\n const camera = sourceMesh.getScene().activeCamera;\n const cameraWorldTarget = Vector3.TransformCoordinates(target, camera.getWorldMatrix());\n normal = camera.globalPosition.subtract(cameraWorldTarget);\n }\n const yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;\n const len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);\n const pitch = Math.atan2(normal.y, len);\n const vertexData = new VertexData();\n vertexData.indices = [];\n vertexData.positions = [];\n vertexData.normals = [];\n vertexData.uvs = [];\n vertexData.matricesIndices = hasSkeleton ? [] : null;\n vertexData.matricesWeights = hasSkeleton ? [] : null;\n vertexData.matricesIndicesExtra = matIndicesExtra ? [] : null;\n vertexData.matricesWeightsExtra = matWeightsExtra ? [] : null;\n let currentVertexDataIndex = 0;\n const extractDecalVector3 = (indexId, transformMatrix) => {\n const result = new DecalVertex();\n if (!indices || !positions || !normals) {\n return result;\n }\n const vertexId = indices[indexId];\n result.vertexIdx = vertexId * 3;\n result.vertexIdxForBones = vertexId * 4;\n // Send vector to decal local world\n result.position = new Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);\n Vector3.TransformCoordinatesToRef(result.position, transformMatrix, result.position);\n // Get normal\n result.normal = new Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);\n Vector3.TransformNormalToRef(result.normal, transformMatrix, result.normal);\n if (options.captureUVS && uvs) {\n const v = uvs[vertexId * 2 + 1];\n result.uv = new Vector2(uvs[vertexId * 2], CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v);\n }\n return result;\n };\n const emptyArray = [0, 0, 0, 0];\n // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js\n const clip = (vertices, axis) => {\n if (vertices.length === 0) {\n return vertices;\n }\n const clipSize = 0.5 * Math.abs(Vector3.Dot(size, axis));\n const indexOf = (arr, val, start, num) => {\n for (let i = 0; i < num; ++i) {\n if (arr[start + i] === val) {\n return start + i;\n }\n }\n return -1;\n };\n const clipVertices = (v0, v1) => {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;\n const clipFactor = Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);\n let indices = emptyArray;\n let weights = emptyArray;\n if (matIndices && matWeights) {\n const mat0Index = v0.matrixIndicesOverride ? 0 : v0.vertexIdxForBones;\n const v0Indices = (_a = v0.matrixIndicesOverride) !== null && _a !== void 0 ? _a : matIndices;\n const v0Weights = (_b = v0.matrixWeightsOverride) !== null && _b !== void 0 ? _b : matWeights;\n const mat1Index = v1.matrixIndicesOverride ? 0 : v1.vertexIdxForBones;\n const v1Indices = (_c = v1.matrixIndicesOverride) !== null && _c !== void 0 ? _c : matIndices;\n const v1Weights = (_d = v1.matrixWeightsOverride) !== null && _d !== void 0 ? _d : matWeights;\n indices = [0, 0, 0, 0];\n weights = [0, 0, 0, 0];\n let index = 0;\n for (let i = 0; i < 4; ++i) {\n if (v0Weights[mat0Index + i] > 0) {\n const idx = indexOf(v1Indices, v0Indices[mat0Index + i], mat1Index, 4);\n indices[index] = v0Indices[mat0Index + i];\n weights[index] = Scalar.Lerp(v0Weights[mat0Index + i], idx >= 0 ? v1Weights[idx] : 0, clipFactor);\n index++;\n }\n }\n for (let i = 0; i < 4 && index < 4; ++i) {\n const ind = v1Indices[mat1Index + i];\n if (indexOf(v0Indices, ind, mat0Index, 4) !== -1)\n continue;\n indices[index] = ind;\n weights[index] = Scalar.Lerp(0, v1Weights[mat1Index + i], clipFactor);\n index++;\n }\n const sumw = weights[0] + weights[1] + weights[2] + weights[3];\n weights[0] /= sumw;\n weights[1] /= sumw;\n weights[2] /= sumw;\n weights[3] /= sumw;\n }\n const v0LocalPositionX = v0.localPositionOverride ? v0.localPositionOverride[0] : (_e = localPositions === null || localPositions === void 0 ? void 0 : localPositions[v0.vertexIdx]) !== null && _e !== void 0 ? _e : 0;\n const v0LocalPositionY = v0.localPositionOverride ? v0.localPositionOverride[1] : (_f = localPositions === null || localPositions === void 0 ? void 0 : localPositions[v0.vertexIdx + 1]) !== null && _f !== void 0 ? _f : 0;\n const v0LocalPositionZ = v0.localPositionOverride ? v0.localPositionOverride[2] : (_g = localPositions === null || localPositions === void 0 ? void 0 : localPositions[v0.vertexIdx + 2]) !== null && _g !== void 0 ? _g : 0;\n const v1LocalPositionX = v1.localPositionOverride ? v1.localPositionOverride[0] : (_h = localPositions === null || localPositions === void 0 ? void 0 : localPositions[v1.vertexIdx]) !== null && _h !== void 0 ? _h : 0;\n const v1LocalPositionY = v1.localPositionOverride ? v1.localPositionOverride[1] : (_j = localPositions === null || localPositions === void 0 ? void 0 : localPositions[v1.vertexIdx + 1]) !== null && _j !== void 0 ? _j : 0;\n const v1LocalPositionZ = v1.localPositionOverride ? v1.localPositionOverride[2] : (_k = localPositions === null || localPositions === void 0 ? void 0 : localPositions[v1.vertexIdx + 2]) !== null && _k !== void 0 ? _k : 0;\n const v0LocalNormalX = v0.localNormalOverride ? v0.localNormalOverride[0] : (_l = localNormals === null || localNormals === void 0 ? void 0 : localNormals[v0.vertexIdx]) !== null && _l !== void 0 ? _l : 0;\n const v0LocalNormalY = v0.localNormalOverride ? v0.localNormalOverride[1] : (_m = localNormals === null || localNormals === void 0 ? void 0 : localNormals[v0.vertexIdx + 1]) !== null && _m !== void 0 ? _m : 0;\n const v0LocalNormalZ = v0.localNormalOverride ? v0.localNormalOverride[2] : (_o = localNormals === null || localNormals === void 0 ? void 0 : localNormals[v0.vertexIdx + 2]) !== null && _o !== void 0 ? _o : 0;\n const v1LocalNormalX = v1.localNormalOverride ? v1.localNormalOverride[0] : (_p = localNormals === null || localNormals === void 0 ? void 0 : localNormals[v1.vertexIdx]) !== null && _p !== void 0 ? _p : 0;\n const v1LocalNormalY = v1.localNormalOverride ? v1.localNormalOverride[1] : (_q = localNormals === null || localNormals === void 0 ? void 0 : localNormals[v1.vertexIdx + 1]) !== null && _q !== void 0 ? _q : 0;\n const v1LocalNormalZ = v1.localNormalOverride ? v1.localNormalOverride[2] : (_r = localNormals === null || localNormals === void 0 ? void 0 : localNormals[v1.vertexIdx + 2]) !== null && _r !== void 0 ? _r : 0;\n const interpNormalX = v0LocalNormalX + (v1LocalNormalX - v0LocalNormalX) * clipFactor;\n const interpNormalY = v0LocalNormalY + (v1LocalNormalY - v0LocalNormalY) * clipFactor;\n const interpNormalZ = v0LocalNormalZ + (v1LocalNormalZ - v0LocalNormalZ) * clipFactor;\n const norm = Math.sqrt(interpNormalX * interpNormalX + interpNormalY * interpNormalY + interpNormalZ * interpNormalZ);\n return new DecalVertex(Vector3.Lerp(v0.position, v1.position, clipFactor), Vector3.Lerp(v0.normal, v1.normal, clipFactor).normalize(), Vector2.Lerp(v0.uv, v1.uv, clipFactor), -1, -1, localPositions\n ? [\n v0LocalPositionX + (v1LocalPositionX - v0LocalPositionX) * clipFactor,\n v0LocalPositionY + (v1LocalPositionY - v0LocalPositionY) * clipFactor,\n v0LocalPositionZ + (v1LocalPositionZ - v0LocalPositionZ) * clipFactor,\n ]\n : null, localNormals ? [interpNormalX / norm, interpNormalY / norm, interpNormalZ / norm] : null, indices, weights);\n };\n let clipResult = null;\n if (vertices.length > 3) {\n clipResult = new Array();\n }\n for (let index = 0; index < vertices.length; index += 3) {\n let total = 0;\n let nV1 = null;\n let nV2 = null;\n let nV3 = null;\n let nV4 = null;\n const d1 = Vector3.Dot(vertices[index].position, axis) - clipSize;\n const d2 = Vector3.Dot(vertices[index + 1].position, axis) - clipSize;\n const d3 = Vector3.Dot(vertices[index + 2].position, axis) - clipSize;\n const v1Out = d1 > 0;\n const v2Out = d2 > 0;\n const v3Out = d3 > 0;\n total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);\n switch (total) {\n case 0:\n if (vertices.length > 3) {\n clipResult.push(vertices[index]);\n clipResult.push(vertices[index + 1]);\n clipResult.push(vertices[index + 2]);\n }\n else {\n clipResult = vertices;\n }\n break;\n case 1:\n clipResult = clipResult !== null && clipResult !== void 0 ? clipResult : new Array();\n if (v1Out) {\n nV1 = vertices[index + 1];\n nV2 = vertices[index + 2];\n nV3 = clipVertices(vertices[index], nV1);\n nV4 = clipVertices(vertices[index], nV2);\n }\n if (v2Out) {\n nV1 = vertices[index];\n nV2 = vertices[index + 2];\n nV3 = clipVertices(vertices[index + 1], nV1);\n nV4 = clipVertices(vertices[index + 1], nV2);\n clipResult.push(nV3);\n clipResult.push(nV2.clone());\n clipResult.push(nV1.clone());\n clipResult.push(nV2.clone());\n clipResult.push(nV3.clone());\n clipResult.push(nV4);\n break;\n }\n if (v3Out) {\n nV1 = vertices[index];\n nV2 = vertices[index + 1];\n nV3 = clipVertices(vertices[index + 2], nV1);\n nV4 = clipVertices(vertices[index + 2], nV2);\n }\n if (nV1 && nV2 && nV3 && nV4) {\n clipResult.push(nV1.clone());\n clipResult.push(nV2.clone());\n clipResult.push(nV3);\n clipResult.push(nV4);\n clipResult.push(nV3.clone());\n clipResult.push(nV2.clone());\n }\n break;\n case 2:\n clipResult = clipResult !== null && clipResult !== void 0 ? clipResult : new Array();\n if (!v1Out) {\n nV1 = vertices[index].clone();\n nV2 = clipVertices(nV1, vertices[index + 1]);\n nV3 = clipVertices(nV1, vertices[index + 2]);\n clipResult.push(nV1);\n clipResult.push(nV2);\n clipResult.push(nV3);\n }\n if (!v2Out) {\n nV1 = vertices[index + 1].clone();\n nV2 = clipVertices(nV1, vertices[index + 2]);\n nV3 = clipVertices(nV1, vertices[index]);\n clipResult.push(nV1);\n clipResult.push(nV2);\n clipResult.push(nV3);\n }\n if (!v3Out) {\n nV1 = vertices[index + 2].clone();\n nV2 = clipVertices(nV1, vertices[index]);\n nV3 = clipVertices(nV1, vertices[index + 1]);\n clipResult.push(nV1);\n clipResult.push(nV2);\n clipResult.push(nV3);\n }\n break;\n case 3:\n break;\n }\n }\n return clipResult;\n };\n const sourceMeshAsMesh = sourceMesh instanceof Mesh ? sourceMesh : null;\n const matrixData = sourceMeshAsMesh === null || sourceMeshAsMesh === void 0 ? void 0 : sourceMeshAsMesh._thinInstanceDataStorage.matrixData;\n const numMatrices = (sourceMeshAsMesh === null || sourceMeshAsMesh === void 0 ? void 0 : sourceMeshAsMesh.thinInstanceCount) || 1;\n const thinInstanceMatrix = TmpVectors.Matrix[0];\n thinInstanceMatrix.copyFrom(Matrix.IdentityReadOnly);\n for (let m = 0; m < numMatrices; ++m) {\n if ((sourceMeshAsMesh === null || sourceMeshAsMesh === void 0 ? void 0 : sourceMeshAsMesh.hasThinInstances) && matrixData) {\n const ofst = m * 16;\n thinInstanceMatrix.setRowFromFloats(0, matrixData[ofst + 0], matrixData[ofst + 1], matrixData[ofst + 2], matrixData[ofst + 3]);\n thinInstanceMatrix.setRowFromFloats(1, matrixData[ofst + 4], matrixData[ofst + 5], matrixData[ofst + 6], matrixData[ofst + 7]);\n thinInstanceMatrix.setRowFromFloats(2, matrixData[ofst + 8], matrixData[ofst + 9], matrixData[ofst + 10], matrixData[ofst + 11]);\n thinInstanceMatrix.setRowFromFloats(3, matrixData[ofst + 12], matrixData[ofst + 13], matrixData[ofst + 14], matrixData[ofst + 15]);\n }\n // Matrix\n const decalWorldMatrix = Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(Matrix.Translation(position.x, position.y, position.z));\n const inverseDecalWorldMatrix = Matrix.Invert(decalWorldMatrix);\n const meshWorldMatrix = sourceMesh.getWorldMatrix();\n const transformMatrix = thinInstanceMatrix.multiply(meshWorldMatrix).multiply(inverseDecalWorldMatrix);\n const oneFaceVertices = new Array(3);\n for (let index = 0; index < indices.length; index += 3) {\n let faceVertices = oneFaceVertices;\n faceVertices[0] = extractDecalVector3(index, transformMatrix);\n if (meshHasOverridenMaterial && useLocalComputation) {\n faceVertices[1] = extractDecalVector3(index + 2, transformMatrix);\n faceVertices[2] = extractDecalVector3(index + 1, transformMatrix);\n }\n else {\n faceVertices[1] = extractDecalVector3(index + 1, transformMatrix);\n faceVertices[2] = extractDecalVector3(index + 2, transformMatrix);\n }\n if (options.cullBackFaces) {\n // If all the normals of the vertices of the face are pointing away from the view direction we discard the face.\n // As computations are done in the decal coordinate space, the viewDirection is (0,0,1), so when dot(vertexNormal, -viewDirection) <= 0 the vertex is culled\n if (-faceVertices[0].normal.z <= 0 && -faceVertices[1].normal.z <= 0 && -faceVertices[2].normal.z <= 0) {\n continue;\n }\n }\n // Clip\n faceVertices = clip(faceVertices, xpAxis);\n if (!faceVertices)\n continue;\n faceVertices = clip(faceVertices, xnAxis);\n if (!faceVertices)\n continue;\n faceVertices = clip(faceVertices, ypAxis);\n if (!faceVertices)\n continue;\n faceVertices = clip(faceVertices, ynAxis);\n if (!faceVertices)\n continue;\n faceVertices = clip(faceVertices, zpAxis);\n if (!faceVertices)\n continue;\n faceVertices = clip(faceVertices, znAxis);\n if (!faceVertices)\n continue;\n // Add UVs and get back to world\n for (let vIndex = 0; vIndex < faceVertices.length; vIndex++) {\n const vertex = faceVertices[vIndex];\n //TODO check for Int32Array | Uint32Array | Uint16Array\n vertexData.indices.push(currentVertexDataIndex);\n if (useLocalComputation) {\n if (vertex.localPositionOverride) {\n vertexData.positions[currentVertexDataIndex * 3] = vertex.localPositionOverride[0];\n vertexData.positions[currentVertexDataIndex * 3 + 1] = vertex.localPositionOverride[1];\n vertexData.positions[currentVertexDataIndex * 3 + 2] = vertex.localPositionOverride[2];\n }\n else if (localPositions) {\n vertexData.positions[currentVertexDataIndex * 3] = localPositions[vertex.vertexIdx];\n vertexData.positions[currentVertexDataIndex * 3 + 1] = localPositions[vertex.vertexIdx + 1];\n vertexData.positions[currentVertexDataIndex * 3 + 2] = localPositions[vertex.vertexIdx + 2];\n }\n if (vertex.localNormalOverride) {\n vertexData.normals[currentVertexDataIndex * 3] = vertex.localNormalOverride[0];\n vertexData.normals[currentVertexDataIndex * 3 + 1] = vertex.localNormalOverride[1];\n vertexData.normals[currentVertexDataIndex * 3 + 2] = vertex.localNormalOverride[2];\n }\n else if (localNormals) {\n vertexData.normals[currentVertexDataIndex * 3] = localNormals[vertex.vertexIdx];\n vertexData.normals[currentVertexDataIndex * 3 + 1] = localNormals[vertex.vertexIdx + 1];\n vertexData.normals[currentVertexDataIndex * 3 + 2] = localNormals[vertex.vertexIdx + 2];\n }\n }\n else {\n vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);\n vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);\n }\n if (vertexData.matricesIndices && vertexData.matricesWeights) {\n if (vertex.matrixIndicesOverride) {\n vertexData.matricesIndices[currentVertexDataIndex * 4] = vertex.matrixIndicesOverride[0];\n vertexData.matricesIndices[currentVertexDataIndex * 4 + 1] = vertex.matrixIndicesOverride[1];\n vertexData.matricesIndices[currentVertexDataIndex * 4 + 2] = vertex.matrixIndicesOverride[2];\n vertexData.matricesIndices[currentVertexDataIndex * 4 + 3] = vertex.matrixIndicesOverride[3];\n }\n else {\n if (matIndices) {\n vertexData.matricesIndices[currentVertexDataIndex * 4] = matIndices[vertex.vertexIdxForBones];\n vertexData.matricesIndices[currentVertexDataIndex * 4 + 1] = matIndices[vertex.vertexIdxForBones + 1];\n vertexData.matricesIndices[currentVertexDataIndex * 4 + 2] = matIndices[vertex.vertexIdxForBones + 2];\n vertexData.matricesIndices[currentVertexDataIndex * 4 + 3] = matIndices[vertex.vertexIdxForBones + 3];\n }\n if (matIndicesExtra && vertexData.matricesIndicesExtra) {\n vertexData.matricesIndicesExtra[currentVertexDataIndex * 4] = matIndicesExtra[vertex.vertexIdxForBones];\n vertexData.matricesIndicesExtra[currentVertexDataIndex * 4 + 1] = matIndicesExtra[vertex.vertexIdxForBones + 1];\n vertexData.matricesIndicesExtra[currentVertexDataIndex * 4 + 2] = matIndicesExtra[vertex.vertexIdxForBones + 2];\n vertexData.matricesIndicesExtra[currentVertexDataIndex * 4 + 3] = matIndicesExtra[vertex.vertexIdxForBones + 3];\n }\n }\n if (vertex.matrixWeightsOverride) {\n vertexData.matricesWeights[currentVertexDataIndex * 4] = vertex.matrixWeightsOverride[0];\n vertexData.matricesWeights[currentVertexDataIndex * 4 + 1] = vertex.matrixWeightsOverride[1];\n vertexData.matricesWeights[currentVertexDataIndex * 4 + 2] = vertex.matrixWeightsOverride[2];\n vertexData.matricesWeights[currentVertexDataIndex * 4 + 3] = vertex.matrixWeightsOverride[3];\n }\n else {\n if (matWeights) {\n vertexData.matricesWeights[currentVertexDataIndex * 4] = matWeights[vertex.vertexIdxForBones];\n vertexData.matricesWeights[currentVertexDataIndex * 4 + 1] = matWeights[vertex.vertexIdxForBones + 1];\n vertexData.matricesWeights[currentVertexDataIndex * 4 + 2] = matWeights[vertex.vertexIdxForBones + 2];\n vertexData.matricesWeights[currentVertexDataIndex * 4 + 3] = matWeights[vertex.vertexIdxForBones + 3];\n }\n if (matWeightsExtra && vertexData.matricesWeightsExtra) {\n vertexData.matricesWeightsExtra[currentVertexDataIndex * 4] = matWeightsExtra[vertex.vertexIdxForBones];\n vertexData.matricesWeightsExtra[currentVertexDataIndex * 4 + 1] = matWeightsExtra[vertex.vertexIdxForBones + 1];\n vertexData.matricesWeightsExtra[currentVertexDataIndex * 4 + 2] = matWeightsExtra[vertex.vertexIdxForBones + 2];\n vertexData.matricesWeightsExtra[currentVertexDataIndex * 4 + 3] = matWeightsExtra[vertex.vertexIdxForBones + 3];\n }\n }\n }\n if (!options.captureUVS) {\n vertexData.uvs.push(0.5 + vertex.position.x / size.x);\n const v = 0.5 + vertex.position.y / size.y;\n vertexData.uvs.push(CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - v : v);\n }\n else {\n vertex.uv.toArray(vertexData.uvs, currentVertexDataIndex * 2);\n }\n currentVertexDataIndex++;\n }\n }\n }\n // Avoid the \"Setting vertex data kind 'XXX' with an empty array\" warning when calling vertexData.applyToMesh\n if (vertexData.indices.length === 0)\n vertexData.indices = null;\n if (vertexData.positions.length === 0)\n vertexData.positions = null;\n if (vertexData.normals.length === 0)\n vertexData.normals = null;\n if (vertexData.uvs.length === 0)\n vertexData.uvs = null;\n if (((_a = vertexData.matricesIndices) === null || _a === void 0 ? void 0 : _a.length) === 0)\n vertexData.matricesIndices = null;\n if (((_b = vertexData.matricesWeights) === null || _b === void 0 ? void 0 : _b.length) === 0)\n vertexData.matricesWeights = null;\n if (((_c = vertexData.matricesIndicesExtra) === null || _c === void 0 ? void 0 : _c.length) === 0)\n vertexData.matricesIndicesExtra = null;\n if (((_d = vertexData.matricesWeightsExtra) === null || _d === void 0 ? void 0 : _d.length) === 0)\n vertexData.matricesWeightsExtra = null;\n // Return mesh\n const decal = new Mesh(name, sourceMesh.getScene());\n vertexData.applyToMesh(decal);\n if (useLocalComputation) {\n decal.skeleton = sourceMesh.skeleton;\n decal.parent = sourceMesh;\n }\n else {\n decal.position = position.clone();\n decal.rotation = new Vector3(pitch, yaw, angle);\n }\n decal.computeWorldMatrix(true);\n decal.refreshBoundingInfo(true, true);\n return decal;\n}\n/**\n * Class containing static functions to help procedurally build meshes\n * @deprecated use the function directly from the module\n */\nexport const DecalBuilder = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CreateDecal,\n};\nMesh.CreateDecal = (name, sourceMesh, position, normal, size, angle) => {\n const options = {\n position,\n normal,\n size,\n angle,\n };\n return CreateDecal(name, sourceMesh, options);\n};\n//# sourceMappingURL=decalBuilder.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { Vector3 } from \"./math.vector.js\";\n/**\n * Class representing an isovector a vector containing 2 INTEGER coordinates\n * x axis is horizontal\n * y axis is 60 deg counter clockwise from positive y axis\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class _IsoVector {\n /**\n * Creates a new isovector from the given x and y coordinates\n * @param x defines the first coordinate, must be an integer\n * @param y defines the second coordinate, must be an integer\n */\n constructor(\n /** defines the first coordinate */\n x = 0, \n /** defines the second coordinate */\n y = 0) {\n this.x = x;\n this.y = y;\n if (x !== Math.floor(x)) {\n x === Math.floor(x);\n Logger.Warn(\"x is not an integer, floor(x) used\");\n }\n if (y !== Math.floor(y)) {\n y === Math.floor(y);\n Logger.Warn(\"y is not an integer, floor(y) used\");\n }\n }\n // Operators\n /**\n * Gets a new IsoVector copied from the IsoVector\n * @returns a new IsoVector\n */\n clone() {\n return new _IsoVector(this.x, this.y);\n }\n /**\n * Rotates one IsoVector 60 degrees counter clockwise about another\n * Please note that this is an in place operation\n * @param other an IsoVector a center of rotation\n * @returns the rotated IsoVector\n */\n rotate60About(other) {\n //other IsoVector\n const x = this.x;\n this.x = other.x + other.y - this.y;\n this.y = x + this.y - other.x;\n return this;\n }\n /**\n * Rotates one IsoVector 60 degrees clockwise about another\n * Please note that this is an in place operation\n * @param other an IsoVector as center of rotation\n * @returns the rotated IsoVector\n */\n rotateNeg60About(other) {\n const x = this.x;\n this.x = x + this.y - other.y;\n this.y = other.x + other.y - x;\n return this;\n }\n /**\n * For an equilateral triangle OAB with O at isovector (0, 0) and A at isovector (m, n)\n * Rotates one IsoVector 120 degrees counter clockwise about the center of the triangle\n * Please note that this is an in place operation\n * @param m integer a measure a Primary triangle of order (m, n) m > n\n * @param n >= 0 integer a measure for a Primary triangle of order (m, n)\n * @returns the rotated IsoVector\n */\n rotate120(m, n) {\n //m, n integers\n if (m !== Math.floor(m)) {\n m === Math.floor(m);\n Logger.Warn(\"m not an integer only floor(m) used\");\n }\n if (n !== Math.floor(n)) {\n n === Math.floor(n);\n Logger.Warn(\"n not an integer only floor(n) used\");\n }\n const x = this.x;\n this.x = m - x - this.y;\n this.y = n + x;\n return this;\n }\n /**\n * For an equilateral triangle OAB with O at isovector (0, 0) and A at isovector (m, n)\n * Rotates one IsoVector 120 degrees clockwise about the center of the triangle\n * Please note that this is an in place operation\n * @param m integer a measure a Primary triangle of order (m, n) m > n\n * @param n >= 0 integer a measure for a Primary triangle of order (m, n)\n * @returns the rotated IsoVector\n */\n rotateNeg120(m, n) {\n //m, n integers\n if (m !== Math.floor(m)) {\n m === Math.floor(m);\n Logger.Warn(\"m is not an integer, floor(m) used\");\n }\n if (n !== Math.floor(n)) {\n n === Math.floor(n);\n Logger.Warn(\"n is not an integer, floor(n) used\");\n }\n const x = this.x;\n this.x = this.y - n;\n this.y = m + n - x - this.y;\n return this;\n }\n /**\n * Transforms an IsoVector to one in Cartesian 3D space based on an isovector\n * @param origin an IsoVector\n * @param isoGridSize\n * @returns Point as a Vector3\n */\n toCartesianOrigin(origin, isoGridSize) {\n const point = Vector3.Zero();\n point.x = origin.x + 2 * this.x * isoGridSize + this.y * isoGridSize;\n point.y = origin.y + Math.sqrt(3) * this.y * isoGridSize;\n return point;\n }\n // Statics\n /**\n * Gets a new IsoVector(0, 0)\n * @returns a new IsoVector\n */\n static Zero() {\n return new _IsoVector(0, 0);\n }\n}\n//# sourceMappingURL=math.isovector.js.map","import { Vector3, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Scalar } from \"../Maths/math.scalar.js\";\nimport { PHI } from \"../Maths/math.constants.js\";\nimport { _IsoVector } from \"../Maths/math.isovector.js\";\n/**\n * Class representing data for one face OAB of an equilateral icosahedron\n * When O is the isovector (0, 0), A is isovector (m, n)\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class _PrimaryIsoTriangle {\n constructor() {\n this.cartesian = [];\n this.vertices = [];\n this.max = [];\n this.min = [];\n this.closestTo = [];\n this.innerFacets = [];\n this.isoVecsABOB = [];\n this.isoVecsOBOA = [];\n this.isoVecsBAOA = [];\n this.vertexTypes = [];\n // eslint-disable-next-line @typescript-eslint/naming-convention\n this.IDATA = new PolyhedronData(\"icosahedron\", \"Regular\", [\n [0, PHI, -1],\n [-PHI, 1, 0],\n [-1, 0, -PHI],\n [1, 0, -PHI],\n [PHI, 1, 0],\n [0, PHI, 1],\n [-1, 0, PHI],\n [-PHI, -1, 0],\n [0, -PHI, -1],\n [PHI, -1, 0],\n [1, 0, PHI],\n [0, -PHI, 1],\n ], [\n [0, 2, 1],\n [0, 3, 2],\n [0, 4, 3],\n [0, 5, 4],\n [0, 1, 5],\n [7, 6, 1],\n [8, 7, 2],\n [9, 8, 3],\n [10, 9, 4],\n [6, 10, 5],\n [2, 7, 1],\n [3, 8, 2],\n [4, 9, 3],\n [5, 10, 4],\n [1, 6, 5],\n [11, 6, 7],\n [11, 7, 8],\n [11, 8, 9],\n [11, 9, 10],\n [11, 10, 6],\n ]);\n }\n /**\n * Creates the PrimaryIsoTriangle Triangle OAB\n * @param m an integer\n * @param n an integer\n */\n //operators\n setIndices() {\n let indexCount = 12; // 12 vertices already assigned\n const vecToidx = {}; //maps iso-vectors to indexCount;\n const m = this.m;\n const n = this.n;\n let g = m; // hcf of m, n when n != 0\n let m1 = 1;\n let n1 = 0;\n if (n !== 0) {\n g = Scalar.HCF(m, n);\n }\n m1 = m / g;\n n1 = n / g;\n let fr; //face to the right of current face\n let rot; //rotation about which vertex for fr\n let O;\n let A;\n let B;\n const oVec = _IsoVector.Zero();\n const aVec = new _IsoVector(m, n);\n const bVec = new _IsoVector(-n, m + n);\n const oaVec = _IsoVector.Zero();\n const abVec = _IsoVector.Zero();\n const obVec = _IsoVector.Zero();\n let verts = [];\n let idx;\n let idxR;\n let isoId;\n let isoIdR;\n const closestTo = [];\n const vDist = this.vertByDist;\n const matchIdx = (f, fr, isoId, isoIdR) => {\n idx = f + \"|\" + isoId;\n idxR = fr + \"|\" + isoIdR;\n if (!(idx in vecToidx || idxR in vecToidx)) {\n vecToidx[idx] = indexCount;\n vecToidx[idxR] = indexCount;\n indexCount++;\n }\n else if (idx in vecToidx && !(idxR in vecToidx)) {\n vecToidx[idxR] = vecToidx[idx];\n }\n else if (idxR in vecToidx && !(idx in vecToidx)) {\n vecToidx[idx] = vecToidx[idxR];\n }\n if (vDist[isoId][0] > 2) {\n closestTo[vecToidx[idx]] = [-vDist[isoId][0], vDist[isoId][1], vecToidx[idx]];\n }\n else {\n closestTo[vecToidx[idx]] = [verts[vDist[isoId][0]], vDist[isoId][1], vecToidx[idx]];\n }\n };\n this.IDATA.edgematch = [\n [1, \"B\"],\n [2, \"B\"],\n [3, \"B\"],\n [4, \"B\"],\n [0, \"B\"],\n [10, \"O\", 14, \"A\"],\n [11, \"O\", 10, \"A\"],\n [12, \"O\", 11, \"A\"],\n [13, \"O\", 12, \"A\"],\n [14, \"O\", 13, \"A\"],\n [0, \"O\"],\n [1, \"O\"],\n [2, \"O\"],\n [3, \"O\"],\n [4, \"O\"],\n [19, \"B\", 5, \"A\"],\n [15, \"B\", 6, \"A\"],\n [16, \"B\", 7, \"A\"],\n [17, \"B\", 8, \"A\"],\n [18, \"B\", 9, \"A\"],\n ];\n /***edges AB to OB***** rotation about B*/\n for (let f = 0; f < 20; f++) {\n //f current face\n verts = this.IDATA.face[f];\n O = verts[2];\n A = verts[1];\n B = verts[0];\n isoId = oVec.x + \"|\" + oVec.y;\n idx = f + \"|\" + isoId;\n if (!(idx in vecToidx)) {\n vecToidx[idx] = O;\n closestTo[O] = [verts[vDist[isoId][0]], vDist[isoId][1]];\n }\n isoId = aVec.x + \"|\" + aVec.y;\n idx = f + \"|\" + isoId;\n if (!(idx in vecToidx)) {\n vecToidx[idx] = A;\n closestTo[A] = [verts[vDist[isoId][0]], vDist[isoId][1]];\n }\n isoId = bVec.x + \"|\" + bVec.y;\n idx = f + \"|\" + isoId;\n if (!(idx in vecToidx)) {\n vecToidx[idx] = B;\n closestTo[B] = [verts[vDist[isoId][0]], vDist[isoId][1]];\n }\n //for edge vertices\n fr = this.IDATA.edgematch[f][0];\n rot = this.IDATA.edgematch[f][1];\n if (rot === \"B\") {\n for (let i = 1; i < g; i++) {\n abVec.x = m - i * (m1 + n1);\n abVec.y = n + i * m1;\n obVec.x = -i * n1;\n obVec.y = i * (m1 + n1);\n isoId = abVec.x + \"|\" + abVec.y;\n isoIdR = obVec.x + \"|\" + obVec.y;\n matchIdx(f, fr, isoId, isoIdR);\n }\n }\n if (rot === \"O\") {\n for (let i = 1; i < g; i++) {\n obVec.x = -i * n1;\n obVec.y = i * (m1 + n1);\n oaVec.x = i * m1;\n oaVec.y = i * n1;\n isoId = obVec.x + \"|\" + obVec.y;\n isoIdR = oaVec.x + \"|\" + oaVec.y;\n matchIdx(f, fr, isoId, isoIdR);\n }\n }\n fr = this.IDATA.edgematch[f][2];\n rot = this.IDATA.edgematch[f][3];\n if (rot && rot === \"A\") {\n for (let i = 1; i < g; i++) {\n oaVec.x = i * m1;\n oaVec.y = i * n1;\n abVec.x = m - (g - i) * (m1 + n1); //reversed for BA\n abVec.y = n + (g - i) * m1; //reversed for BA\n isoId = oaVec.x + \"|\" + oaVec.y;\n isoIdR = abVec.x + \"|\" + abVec.y;\n matchIdx(f, fr, isoId, isoIdR);\n }\n }\n for (let i = 0; i < this.vertices.length; i++) {\n isoId = this.vertices[i].x + \"|\" + this.vertices[i].y;\n idx = f + \"|\" + isoId;\n if (!(idx in vecToidx)) {\n vecToidx[idx] = indexCount++;\n if (vDist[isoId][0] > 2) {\n closestTo[vecToidx[idx]] = [-vDist[isoId][0], vDist[isoId][1], vecToidx[idx]];\n }\n else {\n closestTo[vecToidx[idx]] = [verts[vDist[isoId][0]], vDist[isoId][1], vecToidx[idx]];\n }\n }\n }\n }\n this.closestTo = closestTo;\n this.vecToidx = vecToidx;\n }\n calcCoeffs() {\n const m = this.m;\n const n = this.n;\n const thirdR3 = Math.sqrt(3) / 3;\n const LSQD = m * m + n * n + m * n;\n this.coau = (m + n) / LSQD;\n this.cobu = -n / LSQD;\n this.coav = (-thirdR3 * (m - n)) / LSQD;\n this.cobv = (thirdR3 * (2 * m + n)) / LSQD;\n }\n createInnerFacets() {\n const m = this.m;\n const n = this.n;\n for (let y = 0; y < n + m + 1; y++) {\n for (let x = this.min[y]; x < this.max[y] + 1; x++) {\n if (x < this.max[y] && x < this.max[y + 1] + 1) {\n this.innerFacets.push([\"|\" + x + \"|\" + y, \"|\" + x + \"|\" + (y + 1), \"|\" + (x + 1) + \"|\" + y]);\n }\n if (y > 0 && x < this.max[y - 1] && x + 1 < this.max[y] + 1) {\n this.innerFacets.push([\"|\" + x + \"|\" + y, \"|\" + (x + 1) + \"|\" + y, \"|\" + (x + 1) + \"|\" + (y - 1)]);\n }\n }\n }\n }\n edgeVecsABOB() {\n const m = this.m;\n const n = this.n;\n const B = new _IsoVector(-n, m + n);\n for (let y = 1; y < m + n; y++) {\n const point = new _IsoVector(this.min[y], y);\n const prev = new _IsoVector(this.min[y - 1], y - 1);\n const next = new _IsoVector(this.min[y + 1], y + 1);\n const pointR = point.clone();\n const prevR = prev.clone();\n const nextR = next.clone();\n pointR.rotate60About(B);\n prevR.rotate60About(B);\n nextR.rotate60About(B);\n const maxPoint = new _IsoVector(this.max[pointR.y], pointR.y);\n const maxPrev = new _IsoVector(this.max[pointR.y - 1], pointR.y - 1);\n const maxLeftPrev = new _IsoVector(this.max[pointR.y - 1] - 1, pointR.y - 1);\n if (pointR.x !== maxPoint.x || pointR.y !== maxPoint.y) {\n if (pointR.x !== maxPrev.x) {\n // type2\n //up\n this.vertexTypes.push([1, 0, 0]);\n this.isoVecsABOB.push([point, maxPrev, maxLeftPrev]);\n //down\n this.vertexTypes.push([1, 0, 0]);\n this.isoVecsABOB.push([point, maxLeftPrev, maxPoint]);\n }\n else if (pointR.y === nextR.y) {\n // type1\n //up\n this.vertexTypes.push([1, 1, 0]);\n this.isoVecsABOB.push([point, prev, maxPrev]);\n //down\n this.vertexTypes.push([1, 0, 1]);\n this.isoVecsABOB.push([point, maxPrev, next]);\n }\n else {\n // type 0\n //up\n this.vertexTypes.push([1, 1, 0]);\n this.isoVecsABOB.push([point, prev, maxPrev]);\n //down\n this.vertexTypes.push([1, 0, 0]);\n this.isoVecsABOB.push([point, maxPrev, maxPoint]);\n }\n }\n }\n }\n mapABOBtoOBOA() {\n const point = new _IsoVector(0, 0);\n for (let i = 0; i < this.isoVecsABOB.length; i++) {\n const temp = [];\n for (let j = 0; j < 3; j++) {\n point.x = this.isoVecsABOB[i][j].x;\n point.y = this.isoVecsABOB[i][j].y;\n if (this.vertexTypes[i][j] === 0) {\n point.rotateNeg120(this.m, this.n);\n }\n temp.push(point.clone());\n }\n this.isoVecsOBOA.push(temp);\n }\n }\n mapABOBtoBAOA() {\n const point = new _IsoVector(0, 0);\n for (let i = 0; i < this.isoVecsABOB.length; i++) {\n const temp = [];\n for (let j = 0; j < 3; j++) {\n point.x = this.isoVecsABOB[i][j].x;\n point.y = this.isoVecsABOB[i][j].y;\n if (this.vertexTypes[i][j] === 1) {\n point.rotate120(this.m, this.n);\n }\n temp.push(point.clone());\n }\n this.isoVecsBAOA.push(temp);\n }\n }\n // eslint-disable-next-line @typescript-eslint/naming-convention\n MapToFace(faceNb, geodesicData) {\n const F = this.IDATA.face[faceNb];\n const oidx = F[2];\n const aidx = F[1];\n const bidx = F[0];\n const O = Vector3.FromArray(this.IDATA.vertex[oidx]);\n const A = Vector3.FromArray(this.IDATA.vertex[aidx]);\n const B = Vector3.FromArray(this.IDATA.vertex[bidx]);\n const OA = A.subtract(O);\n const OB = B.subtract(O);\n const x = OA.scale(this.coau).add(OB.scale(this.cobu));\n const y = OA.scale(this.coav).add(OB.scale(this.cobv));\n const mapped = [];\n let idx;\n let tempVec = TmpVectors.Vector3[0];\n for (let i = 0; i < this.cartesian.length; i++) {\n tempVec = x.scale(this.cartesian[i].x).add(y.scale(this.cartesian[i].y)).add(O);\n mapped[i] = [tempVec.x, tempVec.y, tempVec.z];\n idx = faceNb + \"|\" + this.vertices[i].x + \"|\" + this.vertices[i].y;\n geodesicData.vertex[this.vecToidx[idx]] = [tempVec.x, tempVec.y, tempVec.z];\n }\n }\n //statics\n /**Creates a primary triangle\n * @internal\n */\n build(m, n) {\n const vertices = new Array();\n const O = _IsoVector.Zero();\n const A = new _IsoVector(m, n);\n const B = new _IsoVector(-n, m + n);\n vertices.push(O, A, B);\n //max internal isoceles triangle vertices\n for (let y = n; y < m + 1; y++) {\n for (let x = 0; x < m + 1 - y; x++) {\n vertices.push(new _IsoVector(x, y));\n }\n }\n //shared vertices along edges when needed\n if (n > 0) {\n const g = Scalar.HCF(m, n);\n const m1 = m / g;\n const n1 = n / g;\n for (let i = 1; i < g; i++) {\n vertices.push(new _IsoVector(i * m1, i * n1)); //OA\n vertices.push(new _IsoVector(-i * n1, i * (m1 + n1))); //OB\n vertices.push(new _IsoVector(m - i * (m1 + n1), n + i * m1)); // AB\n }\n //lower rows vertices and their rotations\n const ratio = m / n;\n for (let y = 1; y < n; y++) {\n for (let x = 0; x < y * ratio; x++) {\n vertices.push(new _IsoVector(x, y));\n vertices.push(new _IsoVector(x, y).rotate120(m, n));\n vertices.push(new _IsoVector(x, y).rotateNeg120(m, n));\n }\n }\n }\n //order vertices by x and then y\n vertices.sort((a, b) => {\n return a.x - b.x;\n });\n vertices.sort((a, b) => {\n return a.y - b.y;\n });\n const min = new Array(m + n + 1);\n const max = new Array(m + n + 1);\n for (let i = 0; i < min.length; i++) {\n min[i] = Infinity;\n max[i] = -Infinity;\n }\n let y = 0;\n let x = 0;\n const len = vertices.length;\n for (let i = 0; i < len; i++) {\n x = vertices[i].x;\n y = vertices[i].y;\n min[y] = Math.min(x, min[y]);\n max[y] = Math.max(x, max[y]);\n }\n //calculates the distance of a vertex from a given primary vertex\n const distFrom = (vert, primVert) => {\n const v = vert.clone();\n if (primVert === \"A\") {\n v.rotateNeg120(m, n);\n }\n if (primVert === \"B\") {\n v.rotate120(m, n);\n }\n if (v.x < 0) {\n return v.y;\n }\n return v.x + v.y;\n };\n const cartesian = [];\n const distFromO = [];\n const distFromA = [];\n const distFromB = [];\n const vertByDist = {};\n const vertData = [];\n let closest = -1;\n let dist = -1;\n for (let i = 0; i < len; i++) {\n cartesian[i] = vertices[i].toCartesianOrigin(new _IsoVector(0, 0), 0.5);\n distFromO[i] = distFrom(vertices[i], \"O\");\n distFromA[i] = distFrom(vertices[i], \"A\");\n distFromB[i] = distFrom(vertices[i], \"B\");\n if (distFromO[i] === distFromA[i] && distFromA[i] === distFromB[i]) {\n closest = 3;\n dist = distFromO[i];\n }\n else if (distFromO[i] === distFromA[i]) {\n closest = 4;\n dist = distFromO[i];\n }\n else if (distFromA[i] === distFromB[i]) {\n closest = 5;\n dist = distFromA[i];\n }\n else if (distFromB[i] === distFromO[i]) {\n closest = 6;\n dist = distFromO[i];\n }\n if (distFromO[i] < distFromA[i] && distFromO[i] < distFromB[i]) {\n closest = 2;\n dist = distFromO[i];\n }\n if (distFromA[i] < distFromO[i] && distFromA[i] < distFromB[i]) {\n closest = 1;\n dist = distFromA[i];\n }\n if (distFromB[i] < distFromA[i] && distFromB[i] < distFromO[i]) {\n closest = 0;\n dist = distFromB[i];\n }\n vertData.push([closest, dist, vertices[i].x, vertices[i].y]);\n }\n vertData.sort((a, b) => {\n return a[2] - b[2];\n });\n vertData.sort((a, b) => {\n return a[3] - b[3];\n });\n vertData.sort((a, b) => {\n return a[1] - b[1];\n });\n vertData.sort((a, b) => {\n return a[0] - b[0];\n });\n for (let v = 0; v < vertData.length; v++) {\n vertByDist[vertData[v][2] + \"|\" + vertData[v][3]] = [vertData[v][0], vertData[v][1], v];\n }\n this.m = m;\n this.n = n;\n this.vertices = vertices;\n this.vertByDist = vertByDist;\n this.cartesian = cartesian;\n this.min = min;\n this.max = max;\n return this;\n }\n}\n/** Builds Polyhedron Data\n * @internal\n */\nexport class PolyhedronData {\n constructor(name, category, vertex, face) {\n this.name = name;\n this.category = category;\n this.vertex = vertex;\n this.face = face;\n }\n}\n/**\n * This class Extends the PolyhedronData Class to provide measures for a Geodesic Polyhedron\n */\nexport class GeodesicData extends PolyhedronData {\n /**\n * @internal\n */\n innerToData(face, primTri) {\n for (let i = 0; i < primTri.innerFacets.length; i++) {\n this.face.push(primTri.innerFacets[i].map((el) => primTri.vecToidx[face + el]));\n }\n }\n /**\n * @internal\n */\n mapABOBtoDATA(faceNb, primTri) {\n const fr = primTri.IDATA.edgematch[faceNb][0];\n for (let i = 0; i < primTri.isoVecsABOB.length; i++) {\n const temp = [];\n for (let j = 0; j < 3; j++) {\n if (primTri.vertexTypes[i][j] === 0) {\n temp.push(faceNb + \"|\" + primTri.isoVecsABOB[i][j].x + \"|\" + primTri.isoVecsABOB[i][j].y);\n }\n else {\n temp.push(fr + \"|\" + primTri.isoVecsABOB[i][j].x + \"|\" + primTri.isoVecsABOB[i][j].y);\n }\n }\n this.face.push([primTri.vecToidx[temp[0]], primTri.vecToidx[temp[1]], primTri.vecToidx[temp[2]]]);\n }\n }\n /**\n * @internal\n */\n mapOBOAtoDATA(faceNb, primTri) {\n const fr = primTri.IDATA.edgematch[faceNb][0];\n for (let i = 0; i < primTri.isoVecsOBOA.length; i++) {\n const temp = [];\n for (let j = 0; j < 3; j++) {\n if (primTri.vertexTypes[i][j] === 1) {\n temp.push(faceNb + \"|\" + primTri.isoVecsOBOA[i][j].x + \"|\" + primTri.isoVecsOBOA[i][j].y);\n }\n else {\n temp.push(fr + \"|\" + primTri.isoVecsOBOA[i][j].x + \"|\" + primTri.isoVecsOBOA[i][j].y);\n }\n }\n this.face.push([primTri.vecToidx[temp[0]], primTri.vecToidx[temp[1]], primTri.vecToidx[temp[2]]]);\n }\n }\n /**\n * @internal\n */\n mapBAOAtoDATA(faceNb, primTri) {\n const fr = primTri.IDATA.edgematch[faceNb][2];\n for (let i = 0; i < primTri.isoVecsBAOA.length; i++) {\n const temp = [];\n for (let j = 0; j < 3; j++) {\n if (primTri.vertexTypes[i][j] === 1) {\n temp.push(faceNb + \"|\" + primTri.isoVecsBAOA[i][j].x + \"|\" + primTri.isoVecsBAOA[i][j].y);\n }\n else {\n temp.push(fr + \"|\" + primTri.isoVecsBAOA[i][j].x + \"|\" + primTri.isoVecsBAOA[i][j].y);\n }\n }\n this.face.push([primTri.vecToidx[temp[0]], primTri.vecToidx[temp[1]], primTri.vecToidx[temp[2]]]);\n }\n }\n /**\n * @internal\n */\n orderData(primTri) {\n const nearTo = [];\n for (let i = 0; i < 13; i++) {\n nearTo[i] = [];\n }\n const close = primTri.closestTo;\n for (let i = 0; i < close.length; i++) {\n if (close[i][0] > -1) {\n if (close[i][1] > 0) {\n nearTo[close[i][0]].push([i, close[i][1]]);\n }\n }\n else {\n nearTo[12].push([i, close[i][0]]);\n }\n }\n const near = [];\n for (let i = 0; i < 12; i++) {\n near[i] = i;\n }\n let nearIndex = 12;\n for (let i = 0; i < 12; i++) {\n nearTo[i].sort((a, b) => {\n return a[1] - b[1];\n });\n for (let j = 0; j < nearTo[i].length; j++) {\n near[nearTo[i][j][0]] = nearIndex++;\n }\n }\n for (let j = 0; j < nearTo[12].length; j++) {\n near[nearTo[12][j][0]] = nearIndex++;\n }\n for (let i = 0; i < this.vertex.length; i++) {\n this.vertex[i].push(near[i]);\n }\n this.vertex.sort((a, b) => {\n return a[3] - b[3];\n });\n for (let i = 0; i < this.vertex.length; i++) {\n this.vertex[i].pop();\n }\n for (let i = 0; i < this.face.length; i++) {\n for (let j = 0; j < this.face[i].length; j++) {\n this.face[i][j] = near[this.face[i][j]];\n }\n }\n this.sharedNodes = nearTo[12].length;\n this.poleNodes = this.vertex.length - this.sharedNodes;\n }\n /**\n * @internal\n */\n setOrder(m, faces) {\n const adjVerts = [];\n const dualFaces = [];\n let face = faces.pop();\n dualFaces.push(face);\n let index = this.face[face].indexOf(m);\n index = (index + 2) % 3;\n let v = this.face[face][index];\n adjVerts.push(v);\n let f = 0;\n while (faces.length > 0) {\n face = faces[f];\n if (this.face[face].indexOf(v) > -1) {\n // v is a vertex of face f\n index = (this.face[face].indexOf(v) + 1) % 3;\n v = this.face[face][index];\n adjVerts.push(v);\n dualFaces.push(face);\n faces.splice(f, 1);\n f = 0;\n }\n else {\n f++;\n }\n }\n this.adjacentFaces.push(adjVerts);\n return dualFaces;\n }\n /**\n * @internal\n */\n toGoldbergPolyhedronData() {\n const goldbergPolyhedronData = new PolyhedronData(\"GeoDual\", \"Goldberg\", [], []);\n goldbergPolyhedronData.name = \"GD dual\";\n const verticesNb = this.vertex.length;\n const map = new Array(verticesNb);\n for (let v = 0; v < verticesNb; v++) {\n map[v] = [];\n }\n for (let f = 0; f < this.face.length; f++) {\n for (let i = 0; i < 3; i++) {\n map[this.face[f][i]].push(f);\n }\n }\n let cx = 0;\n let cy = 0;\n let cz = 0;\n let face = [];\n let vertex = [];\n this.adjacentFaces = [];\n for (let m = 0; m < map.length; m++) {\n goldbergPolyhedronData.face[m] = this.setOrder(m, map[m].concat([]));\n map[m].forEach((el) => {\n cx = 0;\n cy = 0;\n cz = 0;\n face = this.face[el];\n for (let i = 0; i < 3; i++) {\n vertex = this.vertex[face[i]];\n cx += vertex[0];\n cy += vertex[1];\n cz += vertex[2];\n }\n goldbergPolyhedronData.vertex[el] = [cx / 3, cy / 3, cz / 3];\n });\n }\n return goldbergPolyhedronData;\n }\n //statics\n /**Builds the data for a Geodesic Polyhedron from a primary triangle\n * @param primTri the primary triangle\n * @internal\n */\n static BuildGeodesicData(primTri) {\n const geodesicData = new GeodesicData(\"Geodesic-m-n\", \"Geodesic\", [\n [0, PHI, -1],\n [-PHI, 1, 0],\n [-1, 0, -PHI],\n [1, 0, -PHI],\n [PHI, 1, 0],\n [0, PHI, 1],\n [-1, 0, PHI],\n [-PHI, -1, 0],\n [0, -PHI, -1],\n [PHI, -1, 0],\n [1, 0, PHI],\n [0, -PHI, 1],\n ], []);\n primTri.setIndices();\n primTri.calcCoeffs();\n primTri.createInnerFacets();\n primTri.edgeVecsABOB();\n primTri.mapABOBtoOBOA();\n primTri.mapABOBtoBAOA();\n for (let f = 0; f < primTri.IDATA.face.length; f++) {\n primTri.MapToFace(f, geodesicData);\n geodesicData.innerToData(f, primTri);\n if (primTri.IDATA.edgematch[f][1] === \"B\") {\n geodesicData.mapABOBtoDATA(f, primTri);\n }\n if (primTri.IDATA.edgematch[f][1] === \"O\") {\n geodesicData.mapOBOAtoDATA(f, primTri);\n }\n if (primTri.IDATA.edgematch[f][3] === \"A\") {\n geodesicData.mapBAOAtoDATA(f, primTri);\n }\n }\n geodesicData.orderData(primTri);\n const radius = 1;\n geodesicData.vertex = geodesicData.vertex.map(function (el) {\n const a = el[0];\n const b = el[1];\n const c = el[2];\n const d = Math.sqrt(a * a + b * b + c * c);\n el[0] *= radius / d;\n el[1] *= radius / d;\n el[2] *= radius / d;\n return el;\n });\n return geodesicData;\n }\n}\n//# sourceMappingURL=geodesicMesh.js.map","import { CreatePolyhedron } from \"./polyhedronBuilder.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { _PrimaryIsoTriangle, GeodesicData } from \"../geodesicMesh.js\";\n/**\n * Creates the Mesh for a Geodesic Polyhedron\n * @see https://en.wikipedia.org/wiki/Geodesic_polyhedron\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/polyhedra/geodesic_poly\n * @param name defines the name of the mesh\n * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty\n * * m number of horizontal steps along an isogrid\n * * n number of angled steps along an isogrid\n * * size the size of the Geodesic, optional default 1\n * * sizeX allows stretching in the x direction, optional, default size\n * * sizeY allows stretching in the y direction, optional, default size\n * * sizeZ allows stretching in the z direction, optional, default size\n * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively\n * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively\n * * flat when true creates a flat shaded mesh, optional, default true\n * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.n\n * @param options.size\n * @param options.sizeX\n * @param options.sizeY\n * @param options.sizeZ\n * @param options.faceUV\n * @param options.faceColors\n * @param options.flat\n * @param options.updatable\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.m\n * @param scene defines the hosting scene\n * @returns Geodesic mesh\n */\nexport function CreateGeodesic(name, options, scene = null) {\n let m = options.m || 1;\n if (m !== Math.floor(m)) {\n m === Math.floor(m);\n Logger.Warn(\"m not an integer only floor(m) used\");\n }\n let n = options.n || 0;\n if (n !== Math.floor(n)) {\n n === Math.floor(n);\n Logger.Warn(\"n not an integer only floor(n) used\");\n }\n if (n > m) {\n const temp = n;\n n = m;\n m = temp;\n Logger.Warn(\"n > m therefore m and n swapped\");\n }\n const primTri = new _PrimaryIsoTriangle();\n primTri.build(m, n);\n const geodesicData = GeodesicData.BuildGeodesicData(primTri);\n const geoOptions = {\n custom: geodesicData,\n size: options.size,\n sizeX: options.sizeX,\n sizeY: options.sizeY,\n sizeZ: options.sizeZ,\n faceUV: options.faceUV,\n faceColors: options.faceColors,\n flat: options.flat,\n updatable: options.updatable,\n sideOrientation: options.sideOrientation,\n frontUVs: options.frontUVs,\n backUVs: options.backUVs,\n };\n const geodesic = CreatePolyhedron(name, geoOptions, scene);\n return geodesic;\n}\n//# sourceMappingURL=geodesicBuilder.js.map","import { Vector3 } from \"../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { Logger } from \"../Misc/logger.js\";\nMesh._GoldbergMeshParser = (parsedMesh, scene) => {\n return GoldbergMesh.Parse(parsedMesh, scene);\n};\n/**\n * Mesh for a Goldberg Polyhedron which is made from 12 pentagonal and the rest hexagonal faces\n * @see https://en.wikipedia.org/wiki/Goldberg_polyhedron\n */\nexport class GoldbergMesh extends Mesh {\n constructor() {\n super(...arguments);\n /**\n * Defines the specific Goldberg data used in this mesh construction.\n */\n this.goldbergData = {\n faceColors: [],\n faceCenters: [],\n faceZaxis: [],\n faceXaxis: [],\n faceYaxis: [],\n nbSharedFaces: 0,\n nbUnsharedFaces: 0,\n nbFaces: 0,\n nbFacesAtPole: 0,\n adjacentFaces: [],\n };\n }\n /**\n * Gets the related Goldberg face from pole infos\n * @param poleOrShared Defines the pole index or the shared face index if the fromPole parameter is passed in\n * @param fromPole Defines an optional pole index to find the related info from\n * @returns the goldberg face number\n */\n relatedGoldbergFace(poleOrShared, fromPole) {\n if (fromPole === void 0) {\n if (poleOrShared > this.goldbergData.nbUnsharedFaces - 1) {\n Logger.Warn(\"Maximum number of unshared faces used\");\n poleOrShared = this.goldbergData.nbUnsharedFaces - 1;\n }\n return this.goldbergData.nbUnsharedFaces + poleOrShared;\n }\n if (poleOrShared > 11) {\n Logger.Warn(\"Last pole used\");\n poleOrShared = 11;\n }\n if (fromPole > this.goldbergData.nbFacesAtPole - 1) {\n Logger.Warn(\"Maximum number of faces at a pole used\");\n fromPole = this.goldbergData.nbFacesAtPole - 1;\n }\n return 12 + poleOrShared * this.goldbergData.nbFacesAtPole + fromPole;\n }\n _changeGoldbergFaceColors(colorRange) {\n for (let i = 0; i < colorRange.length; i++) {\n const min = colorRange[i][0];\n const max = colorRange[i][1];\n const col = colorRange[i][2];\n for (let f = min; f < max + 1; f++) {\n this.goldbergData.faceColors[f] = col;\n }\n }\n const newCols = [];\n for (let f = 0; f < 12; f++) {\n for (let i = 0; i < 5; i++) {\n newCols.push(this.goldbergData.faceColors[f].r, this.goldbergData.faceColors[f].g, this.goldbergData.faceColors[f].b, this.goldbergData.faceColors[f].a);\n }\n }\n for (let f = 12; f < this.goldbergData.faceColors.length; f++) {\n for (let i = 0; i < 6; i++) {\n newCols.push(this.goldbergData.faceColors[f].r, this.goldbergData.faceColors[f].g, this.goldbergData.faceColors[f].b, this.goldbergData.faceColors[f].a);\n }\n }\n return newCols;\n }\n /**\n * Set new goldberg face colors\n * @param colorRange the new color to apply to the mesh\n */\n setGoldbergFaceColors(colorRange) {\n const newCols = this._changeGoldbergFaceColors(colorRange);\n this.setVerticesData(VertexBuffer.ColorKind, newCols);\n }\n /**\n * Updates new goldberg face colors\n * @param colorRange the new color to apply to the mesh\n */\n updateGoldbergFaceColors(colorRange) {\n const newCols = this._changeGoldbergFaceColors(colorRange);\n this.updateVerticesData(VertexBuffer.ColorKind, newCols);\n }\n _changeGoldbergFaceUVs(uvRange) {\n const uvs = this.getVerticesData(VertexBuffer.UVKind);\n for (let i = 0; i < uvRange.length; i++) {\n const min = uvRange[i][0];\n const max = uvRange[i][1];\n const center = uvRange[i][2];\n const radius = uvRange[i][3];\n const angle = uvRange[i][4];\n const points5 = [];\n const points6 = [];\n let u;\n let v;\n for (let p = 0; p < 5; p++) {\n u = center.x + radius * Math.cos(angle + (p * Math.PI) / 2.5);\n v = center.y + radius * Math.sin(angle + (p * Math.PI) / 2.5);\n if (u < 0) {\n u = 0;\n }\n if (u > 1) {\n u = 1;\n }\n points5.push(u, v);\n }\n for (let p = 0; p < 6; p++) {\n u = center.x + radius * Math.cos(angle + (p * Math.PI) / 3);\n v = center.y + radius * Math.sin(angle + (p * Math.PI) / 3);\n if (u < 0) {\n u = 0;\n }\n if (u > 1) {\n u = 1;\n }\n points6.push(u, v);\n }\n for (let f = min; f < Math.min(12, max + 1); f++) {\n for (let p = 0; p < 5; p++) {\n uvs[10 * f + 2 * p] = points5[2 * p];\n uvs[10 * f + 2 * p + 1] = points5[2 * p + 1];\n }\n }\n for (let f = Math.max(12, min); f < max + 1; f++) {\n for (let p = 0; p < 6; p++) {\n //120 + 12 * (f - 12) = 12 * f - 24\n uvs[12 * f - 24 + 2 * p] = points6[2 * p];\n uvs[12 * f - 23 + 2 * p] = points6[2 * p + 1];\n }\n }\n }\n return uvs;\n }\n /**\n * set new goldberg face UVs\n * @param uvRange the new UVs to apply to the mesh\n */\n setGoldbergFaceUVs(uvRange) {\n const newUVs = this._changeGoldbergFaceUVs(uvRange);\n this.setVerticesData(VertexBuffer.UVKind, newUVs);\n }\n /**\n * Updates new goldberg face UVs\n * @param uvRange the new UVs to apply to the mesh\n */\n updateGoldbergFaceUVs(uvRange) {\n const newUVs = this._changeGoldbergFaceUVs(uvRange);\n this.updateVerticesData(VertexBuffer.UVKind, newUVs);\n }\n /**\n * Places a mesh on a particular face of the goldberg polygon\n * @param mesh Defines the mesh to position\n * @param face Defines the face to position onto\n * @param position Defines the position relative to the face we are positioning the mesh onto\n */\n placeOnGoldbergFaceAt(mesh, face, position) {\n const orientation = Vector3.RotationFromAxis(this.goldbergData.faceXaxis[face], this.goldbergData.faceYaxis[face], this.goldbergData.faceZaxis[face]);\n mesh.rotation = orientation;\n mesh.position = this.goldbergData.faceCenters[face]\n .add(this.goldbergData.faceXaxis[face].scale(position.x))\n .add(this.goldbergData.faceYaxis[face].scale(position.y))\n .add(this.goldbergData.faceZaxis[face].scale(position.z));\n }\n /**\n * Serialize current mesh\n * @param serializationObject defines the object which will receive the serialization data\n */\n serialize(serializationObject) {\n super.serialize(serializationObject);\n serializationObject.type = \"GoldbergMesh\";\n const goldbergData = {};\n goldbergData.adjacentFaces = this.goldbergData.adjacentFaces;\n goldbergData.nbSharedFaces = this.goldbergData.nbSharedFaces;\n goldbergData.nbUnsharedFaces = this.goldbergData.nbUnsharedFaces;\n goldbergData.nbFaces = this.goldbergData.nbFaces;\n goldbergData.nbFacesAtPole = this.goldbergData.nbFacesAtPole;\n if (this.goldbergData.faceColors) {\n goldbergData.faceColors = [];\n for (const color of this.goldbergData.faceColors) {\n goldbergData.faceColors.push(color.asArray());\n }\n }\n if (this.goldbergData.faceCenters) {\n goldbergData.faceCenters = [];\n for (const vector of this.goldbergData.faceCenters) {\n goldbergData.faceCenters.push(vector.asArray());\n }\n }\n if (this.goldbergData.faceZaxis) {\n goldbergData.faceZaxis = [];\n for (const vector of this.goldbergData.faceZaxis) {\n goldbergData.faceZaxis.push(vector.asArray());\n }\n }\n if (this.goldbergData.faceYaxis) {\n goldbergData.faceYaxis = [];\n for (const vector of this.goldbergData.faceYaxis) {\n goldbergData.faceYaxis.push(vector.asArray());\n }\n }\n if (this.goldbergData.faceXaxis) {\n goldbergData.faceXaxis = [];\n for (const vector of this.goldbergData.faceXaxis) {\n goldbergData.faceXaxis.push(vector.asArray());\n }\n }\n serializationObject.goldbergData = goldbergData;\n }\n /**\n * Parses a serialized goldberg mesh\n * @param parsedMesh the serialized mesh\n * @param scene the scene to create the goldberg mesh in\n * @returns the created goldberg mesh\n */\n static Parse(parsedMesh, scene) {\n const goldbergData = parsedMesh.goldbergData;\n goldbergData.faceColors = goldbergData.faceColors.map((el) => Color4.FromArray(el));\n goldbergData.faceCenters = goldbergData.faceCenters.map((el) => Vector3.FromArray(el));\n goldbergData.faceZaxis = goldbergData.faceZaxis.map((el) => Vector3.FromArray(el));\n goldbergData.faceXaxis = goldbergData.faceXaxis.map((el) => Vector3.FromArray(el));\n goldbergData.faceYaxis = goldbergData.faceYaxis.map((el) => Vector3.FromArray(el));\n const goldberg = new GoldbergMesh(parsedMesh.name, scene);\n goldberg.goldbergData = goldbergData;\n return goldberg;\n }\n}\n//# sourceMappingURL=goldbergMesh.js.map","import { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Color4 } from \"../../Maths/math.color.js\";\nimport { Mesh } from \"../../Meshes/mesh.js\";\nimport { VertexData } from \"../mesh.vertexData.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { _PrimaryIsoTriangle, GeodesicData } from \"../geodesicMesh.js\";\nimport { GoldbergMesh } from \"../goldbergMesh.js\";\nimport { CompatibilityOptions } from \"../../Compat/compatibilityOptions.js\";\n/**\n * Creates the Mesh for a Goldberg Polyhedron\n * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty\n * @param goldbergData polyhedronData defining the Goldberg polyhedron\n * @returns GoldbergSphere mesh\n */\nexport function CreateGoldbergVertexData(options, goldbergData) {\n const size = options.size;\n const sizeX = options.sizeX || size || 1;\n const sizeY = options.sizeY || size || 1;\n const sizeZ = options.sizeZ || size || 1;\n const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE;\n const positions = new Array();\n const indices = new Array();\n const normals = new Array();\n const uvs = new Array();\n let minX = Infinity;\n let maxX = -Infinity;\n let minY = Infinity;\n let maxY = -Infinity;\n for (let v = 0; v < goldbergData.vertex.length; v++) {\n minX = Math.min(minX, goldbergData.vertex[v][0] * sizeX);\n maxX = Math.max(maxX, goldbergData.vertex[v][0] * sizeX);\n minY = Math.min(minY, goldbergData.vertex[v][1] * sizeY);\n maxY = Math.max(maxY, goldbergData.vertex[v][1] * sizeY);\n }\n let index = 0;\n for (let f = 0; f < goldbergData.face.length; f++) {\n const verts = goldbergData.face[f];\n const a = Vector3.FromArray(goldbergData.vertex[verts[0]]);\n const b = Vector3.FromArray(goldbergData.vertex[verts[2]]);\n const c = Vector3.FromArray(goldbergData.vertex[verts[1]]);\n const ba = b.subtract(a);\n const ca = c.subtract(a);\n const norm = Vector3.Cross(ca, ba).normalize();\n for (let v = 0; v < verts.length; v++) {\n normals.push(norm.x, norm.y, norm.z);\n const pdata = goldbergData.vertex[verts[v]];\n positions.push(pdata[0] * sizeX, pdata[1] * sizeY, pdata[2] * sizeZ);\n const vCoord = (pdata[1] * sizeY - minY) / (maxY - minY);\n uvs.push((pdata[0] * sizeX - minX) / (maxX - minX), CompatibilityOptions.UseOpenGLOrientationForUV ? 1 - vCoord : vCoord);\n }\n for (let v = 0; v < verts.length - 2; v++) {\n indices.push(index, index + v + 2, index + v + 1);\n }\n index += verts.length;\n }\n VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);\n const vertexData = new VertexData();\n vertexData.positions = positions;\n vertexData.indices = indices;\n vertexData.normals = normals;\n vertexData.uvs = uvs;\n return vertexData;\n}\n/**\n * Creates the Mesh for a Goldberg Polyhedron which is made from 12 pentagonal and the rest hexagonal faces\n * @see https://en.wikipedia.org/wiki/Goldberg_polyhedron\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/polyhedra/goldberg_poly\n * @param name defines the name of the mesh\n * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty\n * @param scene defines the hosting scene\n * @returns Goldberg mesh\n */\nexport function CreateGoldberg(name, options, scene = null) {\n const size = options.size;\n const sizeX = options.sizeX || size || 1;\n const sizeY = options.sizeY || size || 1;\n const sizeZ = options.sizeZ || size || 1;\n let m = options.m || 1;\n if (m !== Math.floor(m)) {\n m === Math.floor(m);\n Logger.Warn(\"m not an integer only floor(m) used\");\n }\n let n = options.n || 0;\n if (n !== Math.floor(n)) {\n n === Math.floor(n);\n Logger.Warn(\"n not an integer only floor(n) used\");\n }\n if (n > m) {\n const temp = n;\n n = m;\n m = temp;\n Logger.Warn(\"n > m therefore m and n swapped\");\n }\n const primTri = new _PrimaryIsoTriangle();\n primTri.build(m, n);\n const geodesicData = GeodesicData.BuildGeodesicData(primTri);\n const goldbergData = geodesicData.toGoldbergPolyhedronData();\n const goldberg = new GoldbergMesh(name, scene);\n options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation);\n goldberg._originalBuilderSideOrientation = options.sideOrientation;\n const vertexData = CreateGoldbergVertexData(options, goldbergData);\n vertexData.applyToMesh(goldberg, options.updatable);\n goldberg.goldbergData.nbSharedFaces = geodesicData.sharedNodes;\n goldberg.goldbergData.nbUnsharedFaces = geodesicData.poleNodes;\n goldberg.goldbergData.adjacentFaces = geodesicData.adjacentFaces;\n goldberg.goldbergData.nbFaces = goldberg.goldbergData.nbSharedFaces + goldberg.goldbergData.nbUnsharedFaces;\n goldberg.goldbergData.nbFacesAtPole = (goldberg.goldbergData.nbUnsharedFaces - 12) / 12;\n for (let f = 0; f < geodesicData.vertex.length; f++) {\n goldberg.goldbergData.faceCenters.push(Vector3.FromArray(geodesicData.vertex[f]));\n goldberg.goldbergData.faceCenters[f].x *= sizeX;\n goldberg.goldbergData.faceCenters[f].y *= sizeY;\n goldberg.goldbergData.faceCenters[f].z *= sizeZ;\n goldberg.goldbergData.faceColors.push(new Color4(1, 1, 1, 1));\n }\n for (let f = 0; f < goldbergData.face.length; f++) {\n const verts = goldbergData.face[f];\n const a = Vector3.FromArray(goldbergData.vertex[verts[0]]);\n const b = Vector3.FromArray(goldbergData.vertex[verts[2]]);\n const c = Vector3.FromArray(goldbergData.vertex[verts[1]]);\n const ba = b.subtract(a);\n const ca = c.subtract(a);\n const norm = Vector3.Cross(ca, ba).normalize();\n const z = Vector3.Cross(ca, norm).normalize();\n goldberg.goldbergData.faceXaxis.push(ca.normalize());\n goldberg.goldbergData.faceYaxis.push(norm);\n goldberg.goldbergData.faceZaxis.push(z);\n }\n return goldberg;\n}\nMesh.CreateGoldberg = CreateGoldberg;\n//# sourceMappingURL=goldbergBuilder.js.map","import { Path2 } from \"../../Maths/math.path.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Mesh } from \"../mesh.js\";\nimport { ExtrudePolygon } from \"./polygonBuilder.js\";\n// Shape functions\nclass ShapePath {\n /** Create the ShapePath used to support glyphs */\n constructor(resolution) {\n this._paths = [];\n this._tempPaths = [];\n this._holes = [];\n this._resolution = resolution;\n }\n /** Move the virtual cursor to a coordinate */\n moveTo(x, y) {\n this._currentPath = new Path2(x, y);\n this._tempPaths.push(this._currentPath);\n }\n /** Draw a line from the virtual cursor to a given coordinate */\n lineTo(x, y) {\n this._currentPath.addLineTo(x, y);\n }\n /** Create a quadratic curve from the virtual cursor to a given coordinate */\n quadraticCurveTo(cpx, cpy, x, y) {\n this._currentPath.addQuadraticCurveTo(cpx, cpy, x, y, this._resolution);\n }\n /** Create a bezier curve from the virtual cursor to a given coordinate */\n bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x, y) {\n this._currentPath.addBezierCurveTo(cpx1, cpy1, cpx2, cpy2, x, y, this._resolution);\n }\n /** Extract holes based on CW / CCW */\n extractHoles() {\n for (const path of this._tempPaths) {\n if (path.area() > 0) {\n this._holes.push(path);\n }\n else {\n this._paths.push(path);\n }\n }\n if (!this._paths.length && this._holes.length) {\n const temp = this._holes;\n this._holes = this._paths;\n this._paths = temp;\n }\n this._tempPaths.length = 0;\n }\n /** Gets the list of paths */\n get paths() {\n return this._paths;\n }\n /** Gets the list of holes */\n get holes() {\n return this._holes;\n }\n}\n// Utility functions\nfunction CreateShapePath(char, scale, offsetX, offsetY, resolution, fontData) {\n const glyph = fontData.glyphs[char] || fontData.glyphs[\"?\"];\n if (!glyph) {\n // return if there is no glyph data\n return null;\n }\n const shapePath = new ShapePath(resolution);\n if (glyph.o) {\n const outline = glyph.o.split(\" \");\n for (let i = 0, l = outline.length; i < l;) {\n const action = outline[i++];\n switch (action) {\n case \"m\": {\n // moveTo\n const x = parseInt(outline[i++]) * scale + offsetX;\n const y = parseInt(outline[i++]) * scale + offsetY;\n shapePath.moveTo(x, y);\n break;\n }\n case \"l\": {\n // lineTo\n const x = parseInt(outline[i++]) * scale + offsetX;\n const y = parseInt(outline[i++]) * scale + offsetY;\n shapePath.lineTo(x, y);\n break;\n }\n case \"q\": {\n // quadraticCurveTo\n const cpx = parseInt(outline[i++]) * scale + offsetX;\n const cpy = parseInt(outline[i++]) * scale + offsetY;\n const cpx1 = parseInt(outline[i++]) * scale + offsetX;\n const cpy1 = parseInt(outline[i++]) * scale + offsetY;\n shapePath.quadraticCurveTo(cpx1, cpy1, cpx, cpy);\n break;\n }\n case \"b\": {\n // bezierCurveTo\n const cpx = parseInt(outline[i++]) * scale + offsetX;\n const cpy = parseInt(outline[i++]) * scale + offsetY;\n const cpx1 = parseInt(outline[i++]) * scale + offsetX;\n const cpy1 = parseInt(outline[i++]) * scale + offsetY;\n const cpx2 = parseInt(outline[i++]) * scale + offsetX;\n const cpy2 = parseInt(outline[i++]) * scale + offsetY;\n shapePath.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);\n break;\n }\n }\n }\n }\n // Extract holes (based on clockwise data)\n shapePath.extractHoles();\n return { offsetX: glyph.ha * scale, shapePath: shapePath };\n}\n/**\n * Creates shape paths from a text and font\n * @param text the text\n * @param size size of the font\n * @param resolution resolution of the font\n * @param fontData defines the font data (can be generated with http://gero3.github.io/facetype.js/)\n * @returns array of ShapePath objects\n */\nexport function CreateTextShapePaths(text, size, resolution, fontData) {\n const chars = Array.from(text);\n const scale = size / fontData.resolution;\n const line_height = (fontData.boundingBox.yMax - fontData.boundingBox.yMin + fontData.underlineThickness) * scale;\n const shapePaths = [];\n let offsetX = 0, offsetY = 0;\n for (let i = 0; i < chars.length; i++) {\n const char = chars[i];\n if (char === \"\\n\") {\n offsetX = 0;\n offsetY -= line_height;\n }\n else {\n const ret = CreateShapePath(char, scale, offsetX, offsetY, resolution, fontData);\n if (ret) {\n offsetX += ret.offsetX;\n shapePaths.push(ret.shapePath);\n }\n }\n }\n return shapePaths;\n}\n/**\n * Create a text mesh\n * @param name defines the name of the mesh\n * @param text defines the text to use to build the mesh\n * @param fontData defines the font data (can be generated with http://gero3.github.io/facetype.js/)\n * @param options defines options used to create the mesh\n * @param scene defines the hosting scene\n * @param earcutInjection can be used to inject your own earcut reference\n * @returns a new Mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/text\n */\nexport function CreateText(name, text, fontData, options = {\n size: 50,\n resolution: 8,\n depth: 1.0,\n}, scene = null, earcutInjection = earcut) {\n // First we need to generate the paths\n const shapePaths = CreateTextShapePaths(text, options.size || 50, options.resolution || 8, fontData);\n // And extrude them\n const meshes = [];\n for (const shapePath of shapePaths) {\n if (!shapePath.paths.length) {\n continue;\n }\n const holes = shapePath.holes.slice(); // Copy it as we will update the copy\n for (const path of shapePath.paths) {\n const holeVectors = [];\n const shapeVectors = [];\n const points = path.getPoints();\n for (const point of points) {\n shapeVectors.push(new Vector3(point.x, 0, point.y)); // ExtrudePolygon expects data on the xz plane\n }\n // Holes\n const localHolesCopy = holes.slice();\n for (const hole of localHolesCopy) {\n const points = hole.getPoints();\n let found = false;\n for (const point of points) {\n if (path.isPointInside(point)) {\n found = true;\n break;\n }\n }\n if (!found) {\n continue;\n }\n const holePoints = [];\n for (const point of points) {\n holePoints.push(new Vector3(point.x, 0, point.y)); // ExtrudePolygon expects data on the xz plane\n }\n holeVectors.push(holePoints);\n // Remove the hole as it was already used\n holes.splice(holes.indexOf(hole), 1);\n }\n // There is at least a hole but it was unaffected\n if (!holeVectors.length && holes.length) {\n for (const hole of holes) {\n const points = hole.getPoints();\n const holePoints = [];\n for (const point of points) {\n holePoints.push(new Vector3(point.x, 0, point.y)); // ExtrudePolygon expects data on the xz plane\n }\n holeVectors.push(holePoints);\n }\n }\n // Extrusion!\n const mesh = ExtrudePolygon(name, {\n shape: shapeVectors,\n holes: holeVectors.length ? holeVectors : undefined,\n depth: options.depth || 1.0,\n sideOrientation: Mesh._GetDefaultSideOrientation(options.sideOrientation || Mesh.DOUBLESIDE),\n }, scene, earcutInjection);\n meshes.push(mesh);\n }\n }\n // Then we can merge everyone into one single mesh\n const newMesh = Mesh.MergeMeshes(meshes, true, true);\n if (newMesh) {\n // Move pivot to center\n const bbox = newMesh === null || newMesh === void 0 ? void 0 : newMesh.getBoundingInfo();\n newMesh.position.x = -(bbox === null || bbox === void 0 ? void 0 : bbox.boundingBox.extendSizeWorld._x);\n newMesh.position.y = -(bbox === null || bbox === void 0 ? void 0 : bbox.boundingBox.extendSizeWorld._y);\n newMesh.position.z = -(bbox === null || bbox === void 0 ? void 0 : bbox.boundingBox.extendSizeWorld._z);\n newMesh.name = name;\n newMesh.rotation.x = -Math.PI / 2;\n newMesh.bakeCurrentTransformIntoVertices();\n }\n return newMesh;\n}\n//# sourceMappingURL=textBuilder.js.map","/* eslint-disable @typescript-eslint/naming-convention */\nimport { CreateRibbon } from \"./Builders/ribbonBuilder.js\";\nimport { CreateDisc } from \"./Builders/discBuilder.js\";\nimport { CreateBox } from \"./Builders/boxBuilder.js\";\nimport { CreateTiledBox } from \"./Builders/tiledBoxBuilder.js\";\nimport { CreateSphere } from \"./Builders/sphereBuilder.js\";\nimport { CreateCylinder } from \"./Builders/cylinderBuilder.js\";\nimport { CreateTorus } from \"./Builders/torusBuilder.js\";\nimport { CreateTorusKnot } from \"./Builders/torusKnotBuilder.js\";\nimport { CreateDashedLines, CreateLineSystem, CreateLines } from \"./Builders/linesBuilder.js\";\nimport { CreatePolygon, ExtrudePolygon } from \"./Builders/polygonBuilder.js\";\nimport { ExtrudeShape, ExtrudeShapeCustom } from \"./Builders/shapeBuilder.js\";\nimport { CreateLathe } from \"./Builders/latheBuilder.js\";\nimport { CreatePlane } from \"./Builders/planeBuilder.js\";\nimport { CreateTiledPlane } from \"./Builders/tiledPlaneBuilder.js\";\nimport { CreateGround, CreateGroundFromHeightMap, CreateTiledGround } from \"./Builders/groundBuilder.js\";\nimport { CreateTube } from \"./Builders/tubeBuilder.js\";\nimport { CreatePolyhedron } from \"./Builders/polyhedronBuilder.js\";\nimport { CreateIcoSphere } from \"./Builders/icoSphereBuilder.js\";\nimport { CreateDecal } from \"./Builders/decalBuilder.js\";\nimport { CreateCapsule } from \"./Builders/capsuleBuilder.js\";\nimport { CreateGeodesic } from \"./Builders/geodesicBuilder.js\";\nimport { CreateGoldberg } from \"./Builders/goldbergBuilder.js\";\nimport { CreateText } from \"./Builders/textBuilder.js\";\n/**\n * Class containing static functions to help procedurally build meshes\n */\nexport const MeshBuilder = {\n CreateBox,\n CreateTiledBox,\n CreateSphere,\n CreateDisc,\n CreateIcoSphere,\n CreateRibbon,\n CreateCylinder,\n CreateTorus,\n CreateTorusKnot,\n CreateLineSystem,\n CreateLines,\n CreateDashedLines,\n ExtrudeShape,\n ExtrudeShapeCustom,\n CreateLathe,\n CreateTiledPlane,\n CreatePlane,\n CreateGround,\n CreateTiledGround,\n CreateGroundFromHeightMap,\n CreatePolygon,\n ExtrudePolygon,\n CreateTube,\n CreatePolyhedron,\n CreateGeodesic,\n CreateGoldberg,\n CreateDecal,\n CreateCapsule,\n CreateText,\n};\n//# sourceMappingURL=meshBuilder.js.map","import { Mesh } from \"../Meshes/mesh.js\";\nimport { CreateBox } from \"../Meshes/Builders/boxBuilder.js\";\nimport { CreateSphere } from \"../Meshes/Builders/sphereBuilder.js\";\nimport { Matrix, Quaternion, TmpVectors, Vector3 } from \"../Maths/math.vector.js\";\nimport { Color3, Color4 } from \"../Maths/math.color.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { StandardMaterial } from \"../Materials/standardMaterial.js\";\nimport { PhysicsImpostor } from \"../Physics/v1/physicsImpostor.js\";\nimport { UtilityLayerRenderer } from \"../Rendering/utilityLayerRenderer.js\";\nimport { CreateCylinder } from \"../Meshes/Builders/cylinderBuilder.js\";\nimport { CreateCapsule } from \"../Meshes/Builders/capsuleBuilder.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { VertexData } from \"../Meshes/mesh.vertexData.js\";\nimport { MeshBuilder } from \"../Meshes/meshBuilder.js\";\n/**\n * Used to show the physics impostor around the specific mesh\n */\nexport class PhysicsViewer {\n /**\n * Creates a new PhysicsViewer\n * @param scene defines the hosting scene\n */\n constructor(scene) {\n /** @internal */\n this._impostors = [];\n /** @internal */\n this._meshes = [];\n /** @internal */\n this._bodies = [];\n this._inertiaBodies = [];\n /** @internal */\n this._bodyMeshes = [];\n /** @internal */\n this._inertiaMeshes = [];\n /** @internal */\n this._numMeshes = 0;\n /** @internal */\n this._numBodies = 0;\n this._numInertiaBodies = 0;\n this._debugMeshMeshes = new Array();\n this._scene = scene || EngineStore.LastCreatedScene;\n if (!this._scene) {\n return;\n }\n const physicEngine = this._scene.getPhysicsEngine();\n if (physicEngine) {\n this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();\n }\n this._utilityLayer = new UtilityLayerRenderer(this._scene, false);\n this._utilityLayer.pickUtilitySceneFirst = false;\n this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil = true;\n }\n /**\n * Updates the debug meshes of the physics engine.\n *\n * This code is useful for synchronizing the debug meshes of the physics engine with the physics impostor and mesh.\n * It checks if the impostor is disposed and if the plugin version is 1, then it syncs the mesh with the impostor.\n * This ensures that the debug meshes are up to date with the physics engine.\n */\n _updateDebugMeshes() {\n const plugin = this._physicsEnginePlugin;\n if ((plugin === null || plugin === void 0 ? void 0 : plugin.getPluginVersion()) === 1) {\n this._updateDebugMeshesV1();\n }\n else {\n this._updateDebugMeshesV2();\n }\n }\n /**\n * Updates the debug meshes of the physics engine.\n *\n * This method is useful for synchronizing the debug meshes with the physics impostors.\n * It iterates through the impostors and meshes, and if the plugin version is 1, it syncs the mesh with the impostor.\n * This ensures that the debug meshes accurately reflect the physics impostors, which is important for debugging the physics engine.\n */\n _updateDebugMeshesV1() {\n const plugin = this._physicsEnginePlugin;\n for (let i = 0; i < this._numMeshes; i++) {\n const impostor = this._impostors[i];\n if (!impostor) {\n continue;\n }\n if (impostor.isDisposed) {\n this.hideImpostor(this._impostors[i--]);\n }\n else {\n if (impostor.type === PhysicsImpostor.MeshImpostor) {\n continue;\n }\n const mesh = this._meshes[i];\n if (mesh && plugin) {\n plugin.syncMeshWithImpostor(mesh, impostor);\n }\n }\n }\n }\n /**\n * Updates the debug meshes of the physics engine for V2 plugin.\n *\n * This method is useful for synchronizing the debug meshes of the physics engine with the current state of the bodies.\n * It iterates through the bodies array and updates the debug meshes with the current transform of each body.\n * This ensures that the debug meshes accurately reflect the current state of the physics engine.\n */\n _updateDebugMeshesV2() {\n const plugin = this._physicsEnginePlugin;\n for (let i = 0; i < this._numBodies; i++) {\n const body = this._bodies[i];\n const transform = this._bodyMeshes[i];\n if (body && transform) {\n plugin.syncTransform(body, transform);\n }\n }\n }\n _updateInertiaMeshes() {\n for (let i = 0; i < this._numInertiaBodies; i++) {\n const body = this._inertiaBodies[i];\n const mesh = this._inertiaMeshes[i];\n if (body && mesh) {\n this._updateDebugInertia(body, mesh);\n }\n }\n }\n _updateDebugInertia(body, inertiaMesh) {\n var _a;\n const inertiaMatrixRef = Matrix.Identity();\n const transformMatrixRef = Matrix.Identity();\n const finalMatrixRef = Matrix.Identity();\n if (body._pluginDataInstances.length) {\n const inertiaAsMesh = inertiaMesh;\n const inertiaMeshMatrixData = inertiaAsMesh._thinInstanceDataStorage.matrixData;\n const bodyTransformMatrixData = body.transformNode._thinInstanceDataStorage.matrixData;\n for (let i = 0; i < body._pluginDataInstances.length; i++) {\n const props = body.getMassProperties(i);\n this._getMeshDebugInertiaMatrixToRef(props, inertiaMatrixRef);\n Matrix.FromArrayToRef(bodyTransformMatrixData, i * 16, transformMatrixRef);\n inertiaMatrixRef.multiplyToRef(transformMatrixRef, finalMatrixRef);\n finalMatrixRef.copyToArray(inertiaMeshMatrixData, i * 16);\n }\n inertiaAsMesh.thinInstanceBufferUpdated(\"matrix\");\n }\n else {\n const props = body.getMassProperties();\n this._getMeshDebugInertiaMatrixToRef(props, inertiaMatrixRef);\n (_a = body.transformNode.rotationQuaternion) === null || _a === void 0 ? void 0 : _a.toRotationMatrix(transformMatrixRef);\n transformMatrixRef.setTranslation(body.transformNode.position);\n inertiaMatrixRef.multiplyToRef(transformMatrixRef, inertiaMatrixRef);\n inertiaMatrixRef.decomposeToTransformNode(inertiaMesh);\n }\n }\n /**\n * Renders a specified physic impostor\n * @param impostor defines the impostor to render\n * @param targetMesh defines the mesh represented by the impostor\n * @returns the new debug mesh used to render the impostor\n */\n showImpostor(impostor, targetMesh) {\n if (!this._scene) {\n return null;\n }\n for (let i = 0; i < this._numMeshes; i++) {\n if (this._impostors[i] == impostor) {\n return null;\n }\n }\n const debugMesh = this._getDebugMesh(impostor, targetMesh);\n if (debugMesh) {\n this._impostors[this._numMeshes] = impostor;\n this._meshes[this._numMeshes] = debugMesh;\n if (this._numMeshes === 0) {\n this._renderFunction = this._updateDebugMeshes.bind(this);\n this._scene.registerBeforeRender(this._renderFunction);\n }\n this._numMeshes++;\n }\n return debugMesh;\n }\n /**\n * Shows a debug mesh for a given physics body.\n * @param body The physics body to show.\n * @returns The debug mesh, or null if the body is already shown.\n *\n * This function is useful for visualizing the physics body in the scene.\n * It creates a debug mesh for the given body and adds it to the scene.\n * It also registers a before render function to update the debug mesh position and rotation.\n */\n showBody(body) {\n if (!this._scene) {\n return null;\n }\n for (let i = 0; i < this._numBodies; i++) {\n if (this._bodies[i] == body) {\n return null;\n }\n }\n const debugMesh = this._getDebugBodyMesh(body);\n if (debugMesh) {\n this._bodies[this._numBodies] = body;\n this._bodyMeshes[this._numBodies] = debugMesh;\n if (this._numBodies === 0) {\n this._renderFunction = this._updateDebugMeshes.bind(this);\n this._scene.registerBeforeRender(this._renderFunction);\n }\n this._numBodies++;\n }\n return debugMesh;\n }\n /**\n * Shows a debug box corresponding to the inertia of a given body\n * @param body\n */\n showInertia(body) {\n if (!this._scene) {\n return null;\n }\n for (let i = 0; i < this._numInertiaBodies; i++) {\n if (this._inertiaBodies[i] == body) {\n return null;\n }\n }\n const debugMesh = this._getDebugInertiaMesh(body);\n if (debugMesh) {\n this._inertiaBodies[this._numInertiaBodies] = body;\n this._inertiaMeshes[this._numInertiaBodies] = debugMesh;\n if (this._numInertiaBodies === 0) {\n this._inertiaRenderFunction = this._updateInertiaMeshes.bind(this);\n this._scene.registerBeforeRender(this._inertiaRenderFunction);\n }\n this._numInertiaBodies++;\n }\n return debugMesh;\n }\n /**\n * Hides an impostor from the scene.\n * @param impostor - The impostor to hide.\n *\n * This method is useful for hiding an impostor from the scene. It removes the\n * impostor from the utility layer scene, disposes the mesh, and removes the\n * impostor from the list of impostors. If the impostor is the last one in the\n * list, it also unregisters the render function.\n */\n hideImpostor(impostor) {\n if (!impostor || !this._scene || !this._utilityLayer) {\n return;\n }\n let removed = false;\n const utilityLayerScene = this._utilityLayer.utilityLayerScene;\n for (let i = 0; i < this._numMeshes; i++) {\n if (this._impostors[i] == impostor) {\n const mesh = this._meshes[i];\n if (!mesh) {\n continue;\n }\n utilityLayerScene.removeMesh(mesh);\n mesh.dispose();\n const index = this._debugMeshMeshes.indexOf(mesh);\n if (index > -1) {\n this._debugMeshMeshes.splice(index, 1);\n }\n this._numMeshes--;\n if (this._numMeshes > 0) {\n this._meshes[i] = this._meshes[this._numMeshes];\n this._impostors[i] = this._impostors[this._numMeshes];\n this._meshes[this._numMeshes] = null;\n this._impostors[this._numMeshes] = null;\n }\n else {\n this._meshes[0] = null;\n this._impostors[0] = null;\n }\n removed = true;\n break;\n }\n }\n if (removed && this._numMeshes === 0) {\n this._scene.unregisterBeforeRender(this._renderFunction);\n }\n }\n /**\n * Hides a body from the physics engine.\n * @param body - The body to hide.\n *\n * This function is useful for hiding a body from the physics engine.\n * It removes the body from the utility layer scene and disposes the mesh associated with it.\n * It also unregisters the render function if the number of bodies is 0.\n * This is useful for hiding a body from the physics engine without deleting it.\n */\n hideBody(body) {\n if (!body || !this._scene || !this._utilityLayer) {\n return;\n }\n let removed = false;\n const utilityLayerScene = this._utilityLayer.utilityLayerScene;\n for (let i = 0; i < this._numBodies; i++) {\n if (this._bodies[i] === body) {\n const mesh = this._bodyMeshes[i];\n if (!mesh) {\n continue;\n }\n utilityLayerScene.removeMesh(mesh);\n mesh.dispose();\n this._numBodies--;\n if (this._numBodies > 0) {\n this._bodyMeshes[i] = this._bodyMeshes[this._numBodies];\n this._bodies[i] = this._bodies[this._numBodies];\n this._bodyMeshes[this._numBodies] = null;\n this._bodies[this._numBodies] = null;\n }\n else {\n this._bodyMeshes[0] = null;\n this._bodies[0] = null;\n }\n removed = true;\n break;\n }\n }\n if (removed && this._numBodies === 0) {\n this._scene.unregisterBeforeRender(this._renderFunction);\n }\n }\n hideInertia(body) {\n if (!body || !this._scene || !this._utilityLayer) {\n return;\n }\n let removed = false;\n const utilityLayerScene = this._utilityLayer.utilityLayerScene;\n for (let i = 0; i < this._numInertiaBodies; i++) {\n if (this._inertiaBodies[i] === body) {\n const mesh = this._inertiaMeshes[i];\n if (!mesh) {\n continue;\n }\n utilityLayerScene.removeMesh(mesh);\n mesh.dispose();\n this._inertiaBodies.splice(i, 1);\n this._inertiaMeshes.splice(i, 1);\n this._numInertiaBodies--;\n removed = true;\n break;\n }\n }\n if (removed && this._numInertiaBodies === 0) {\n this._scene.unregisterBeforeRender(this._inertiaRenderFunction);\n }\n }\n _getDebugMaterial(scene) {\n if (!this._debugMaterial) {\n this._debugMaterial = new StandardMaterial(\"\", scene);\n this._debugMaterial.wireframe = true;\n this._debugMaterial.emissiveColor = Color3.White();\n this._debugMaterial.disableLighting = true;\n }\n return this._debugMaterial;\n }\n _getDebugInertiaMaterial(scene) {\n if (!this._debugInertiaMaterial) {\n this._debugInertiaMaterial = new StandardMaterial(\"\", scene);\n this._debugInertiaMaterial.disableLighting = true;\n this._debugInertiaMaterial.alpha = 0.0;\n }\n return this._debugInertiaMaterial;\n }\n _getDebugBoxMesh(scene) {\n if (!this._debugBoxMesh) {\n this._debugBoxMesh = CreateBox(\"physicsBodyBoxViewMesh\", { size: 1 }, scene);\n this._debugBoxMesh.rotationQuaternion = Quaternion.Identity();\n this._debugBoxMesh.material = this._getDebugMaterial(scene);\n this._debugBoxMesh.setEnabled(false);\n }\n return this._debugBoxMesh.createInstance(\"physicsBodyBoxViewInstance\");\n }\n _getDebugSphereMesh(scene) {\n if (!this._debugSphereMesh) {\n this._debugSphereMesh = CreateSphere(\"physicsBodySphereViewMesh\", { diameter: 1 }, scene);\n this._debugSphereMesh.rotationQuaternion = Quaternion.Identity();\n this._debugSphereMesh.material = this._getDebugMaterial(scene);\n this._debugSphereMesh.setEnabled(false);\n }\n return this._debugSphereMesh.createInstance(\"physicsBodySphereViewInstance\");\n }\n _getDebugCapsuleMesh(scene) {\n if (!this._debugCapsuleMesh) {\n this._debugCapsuleMesh = CreateCapsule(\"physicsBodyCapsuleViewMesh\", { height: 1 }, scene);\n this._debugCapsuleMesh.rotationQuaternion = Quaternion.Identity();\n this._debugCapsuleMesh.material = this._getDebugMaterial(scene);\n this._debugCapsuleMesh.setEnabled(false);\n }\n return this._debugCapsuleMesh.createInstance(\"physicsBodyCapsuleViewInstance\");\n }\n _getDebugCylinderMesh(scene) {\n if (!this._debugCylinderMesh) {\n this._debugCylinderMesh = CreateCylinder(\"physicsBodyCylinderViewMesh\", { diameterTop: 1, diameterBottom: 1, height: 1 }, scene);\n this._debugCylinderMesh.rotationQuaternion = Quaternion.Identity();\n this._debugCylinderMesh.material = this._getDebugMaterial(scene);\n this._debugCylinderMesh.setEnabled(false);\n }\n return this._debugCylinderMesh.createInstance(\"physicsBodyCylinderViewInstance\");\n }\n _getDebugMeshMesh(mesh, scene) {\n const wireframeOver = new Mesh(mesh.name, scene, null, mesh);\n wireframeOver.setParent(mesh);\n wireframeOver.position = Vector3.Zero();\n wireframeOver.material = this._getDebugMaterial(scene);\n this._debugMeshMeshes.push(wireframeOver);\n return wireframeOver;\n }\n _getDebugMesh(impostor, targetMesh) {\n if (!this._utilityLayer) {\n return null;\n }\n // Only create child impostor debug meshes when evaluating the parent\n if (targetMesh && targetMesh.parent && targetMesh.parent.physicsImpostor) {\n return null;\n }\n let mesh = null;\n const utilityLayerScene = this._utilityLayer.utilityLayerScene;\n if (!impostor.physicsBody) {\n Logger.Warn(\"Unable to get physicsBody of impostor. It might be initialized later by its parent's impostor.\");\n return null;\n }\n switch (impostor.type) {\n case PhysicsImpostor.BoxImpostor:\n mesh = this._getDebugBoxMesh(utilityLayerScene);\n impostor.getBoxSizeToRef(mesh.scaling);\n break;\n case PhysicsImpostor.SphereImpostor: {\n mesh = this._getDebugSphereMesh(utilityLayerScene);\n const radius = impostor.getRadius();\n mesh.scaling.x = radius * 2;\n mesh.scaling.y = radius * 2;\n mesh.scaling.z = radius * 2;\n break;\n }\n case PhysicsImpostor.CapsuleImpostor: {\n mesh = this._getDebugCapsuleMesh(utilityLayerScene);\n const bi = impostor.object.getBoundingInfo();\n mesh.scaling.x = (bi.boundingBox.maximum.x - bi.boundingBox.minimum.x) * 2 * impostor.object.scaling.x;\n mesh.scaling.y = (bi.boundingBox.maximum.y - bi.boundingBox.minimum.y) * impostor.object.scaling.y;\n mesh.scaling.z = (bi.boundingBox.maximum.z - bi.boundingBox.minimum.z) * 2 * impostor.object.scaling.z;\n break;\n }\n case PhysicsImpostor.MeshImpostor:\n if (targetMesh) {\n mesh = this._getDebugMeshMesh(targetMesh, utilityLayerScene);\n }\n break;\n case PhysicsImpostor.NoImpostor:\n if (targetMesh) {\n // Handle compound impostors\n const childMeshes = targetMesh.getChildMeshes().filter((c) => {\n return c.physicsImpostor ? 1 : 0;\n });\n childMeshes.forEach((m) => {\n if (m.physicsImpostor && m.getClassName() === \"Mesh\") {\n const boundingInfo = m.getBoundingInfo();\n const min = boundingInfo.boundingBox.minimum;\n const max = boundingInfo.boundingBox.maximum;\n switch (m.physicsImpostor.type) {\n case PhysicsImpostor.BoxImpostor:\n mesh = this._getDebugBoxMesh(utilityLayerScene);\n mesh.position.copyFrom(min);\n mesh.position.addInPlace(max);\n mesh.position.scaleInPlace(0.5);\n break;\n case PhysicsImpostor.SphereImpostor:\n mesh = this._getDebugSphereMesh(utilityLayerScene);\n break;\n case PhysicsImpostor.CylinderImpostor:\n mesh = this._getDebugCylinderMesh(utilityLayerScene);\n break;\n default:\n mesh = null;\n break;\n }\n if (mesh) {\n mesh.scaling.x = max.x - min.x;\n mesh.scaling.y = max.y - min.y;\n mesh.scaling.z = max.z - min.z;\n mesh.parent = m;\n }\n }\n });\n }\n else {\n Logger.Warn(\"No target mesh parameter provided for NoImpostor. Skipping.\");\n }\n mesh = null;\n break;\n case PhysicsImpostor.CylinderImpostor: {\n mesh = this._getDebugCylinderMesh(utilityLayerScene);\n const bi = impostor.object.getBoundingInfo();\n mesh.scaling.x = (bi.boundingBox.maximum.x - bi.boundingBox.minimum.x) * impostor.object.scaling.x;\n mesh.scaling.y = (bi.boundingBox.maximum.y - bi.boundingBox.minimum.y) * impostor.object.scaling.y;\n mesh.scaling.z = (bi.boundingBox.maximum.z - bi.boundingBox.minimum.z) * impostor.object.scaling.z;\n break;\n }\n }\n return mesh;\n }\n /**\n * Creates a debug mesh for a given physics body\n * @param body The physics body to create the debug mesh for\n * @returns The created debug mesh or null if the utility layer is not available\n *\n * This code is useful for creating a debug mesh for a given physics body.\n * It creates a Mesh object with a VertexData object containing the positions and indices\n * of the geometry of the body. The mesh is then assigned a debug material from the utility layer scene.\n * This allows for visualizing the physics body in the scene.\n */\n _getDebugBodyMesh(body) {\n if (!this._utilityLayer) {\n return null;\n }\n const utilityLayerScene = this._utilityLayer.utilityLayerScene;\n const mesh = new Mesh(\"custom\", utilityLayerScene);\n const vertexData = new VertexData();\n const geometry = body.getGeometry();\n vertexData.positions = geometry.positions;\n vertexData.indices = geometry.indices;\n vertexData.applyToMesh(mesh);\n if (body._pluginDataInstances) {\n const instanceBuffer = new Float32Array(body._pluginDataInstances.length * 16);\n mesh.thinInstanceSetBuffer(\"matrix\", instanceBuffer, 16);\n }\n mesh.material = this._getDebugMaterial(utilityLayerScene);\n return mesh;\n }\n _getMeshDebugInertiaMatrixToRef(massProps, matrix) {\n var _a, _b, _c;\n const orientation = (_a = massProps.inertiaOrientation) !== null && _a !== void 0 ? _a : Quaternion.Identity();\n const inertiaLocal = (_b = massProps.inertia) !== null && _b !== void 0 ? _b : Vector3.Zero();\n const center = (_c = massProps.centerOfMass) !== null && _c !== void 0 ? _c : Vector3.Zero();\n const betaSqrd = (inertiaLocal.x - inertiaLocal.y + inertiaLocal.z) * 6;\n const beta = Math.sqrt(Math.max(betaSqrd, 0)); // Safety check for zeroed elements!\n const gammaSqrd = inertiaLocal.x * 12 - betaSqrd;\n const gamma = Math.sqrt(Math.max(gammaSqrd, 0)); // Safety check for zeroed elements!\n const alphaSqrd = inertiaLocal.z * 12 - betaSqrd;\n const alpha = Math.sqrt(Math.max(alphaSqrd, 0)); // Safety check for zeroed elements!\n const extents = TmpVectors.Vector3[0];\n extents.set(alpha, beta, gamma);\n const scaling = Matrix.ScalingToRef(extents.x, extents.y, extents.z, TmpVectors.Matrix[0]);\n const rotation = orientation.toRotationMatrix(TmpVectors.Matrix[1]);\n const translation = Matrix.TranslationToRef(center.x, center.y, center.z, TmpVectors.Matrix[2]);\n scaling.multiplyToRef(rotation, matrix);\n matrix.multiplyToRef(translation, matrix);\n return matrix;\n }\n _getDebugInertiaMesh(body) {\n if (!this._utilityLayer) {\n return null;\n }\n const utilityLayerScene = this._utilityLayer.utilityLayerScene;\n // The base inertia mesh is going to be a 1x1 cube that's scaled and rotated according to the inertia\n const inertiaBoxMesh = MeshBuilder.CreateBox(\"custom\", { size: 1 }, utilityLayerScene);\n const matrixRef = Matrix.Identity();\n if (body._pluginDataInstances.length) {\n const instanceBuffer = new Float32Array(body._pluginDataInstances.length * 16);\n for (let i = 0; i < body._pluginDataInstances.length; ++i) {\n const props = body.getMassProperties(i);\n this._getMeshDebugInertiaMatrixToRef(props, matrixRef);\n matrixRef.copyToArray(instanceBuffer, i * 16);\n }\n inertiaBoxMesh.thinInstanceSetBuffer(\"matrix\", instanceBuffer, 16);\n }\n else {\n const props = body.getMassProperties();\n this._getMeshDebugInertiaMatrixToRef(props, matrixRef);\n matrixRef.decomposeToTransformNode(inertiaBoxMesh);\n }\n inertiaBoxMesh.enableEdgesRendering();\n inertiaBoxMesh.edgesWidth = 2.0;\n inertiaBoxMesh.edgesColor = new Color4(1, 0, 1, 1);\n inertiaBoxMesh.material = this._getDebugInertiaMaterial(utilityLayerScene);\n return inertiaBoxMesh;\n }\n /**\n * Clean up physics debug display\n */\n dispose() {\n // impostors\n for (let index = this._numMeshes - 1; index >= 0; index--) {\n this.hideImpostor(this._impostors[0]);\n }\n // bodies\n for (let index = this._numBodies - 1; index >= 0; index--) {\n this.hideBody(this._bodies[0]);\n }\n // inertia\n for (let index = this._numInertiaBodies - 1; index >= 0; index--) {\n this.hideInertia(this._inertiaBodies[0]);\n }\n if (this._debugBoxMesh) {\n this._debugBoxMesh.dispose();\n }\n if (this._debugSphereMesh) {\n this._debugSphereMesh.dispose();\n }\n if (this._debugCylinderMesh) {\n this._debugCylinderMesh.dispose();\n }\n if (this._debugMaterial) {\n this._debugMaterial.dispose();\n }\n this._impostors.length = 0;\n this._scene = null;\n this._physicsEnginePlugin = null;\n if (this._utilityLayer) {\n this._utilityLayer.dispose();\n this._utilityLayer = null;\n }\n }\n}\n//# sourceMappingURL=physicsViewer.js.map","import { Vector3 } from \"../Maths/math.vector.js\";\nimport { CreateLines } from \"../Meshes/Builders/linesBuilder.js\";\n/**\n * As raycast might be hard to debug, the RayHelper can help rendering the different rays\n * in order to better appreciate the issue one might have.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/picking_collisions#debugging\n */\nexport class RayHelper {\n /**\n * Helper function to create a colored helper in a scene in one line.\n * @param ray Defines the ray we are currently tryin to visualize\n * @param scene Defines the scene the ray is used in\n * @param color Defines the color we want to see the ray in\n * @returns The newly created ray helper.\n */\n static CreateAndShow(ray, scene, color) {\n const helper = new RayHelper(ray);\n helper.show(scene, color);\n return helper;\n }\n /**\n * Instantiate a new ray helper.\n * As raycast might be hard to debug, the RayHelper can help rendering the different rays\n * in order to better appreciate the issue one might have.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/picking_collisions#debugging\n * @param ray Defines the ray we are currently tryin to visualize\n */\n constructor(ray) {\n this.ray = ray;\n }\n /**\n * Shows the ray we are willing to debug.\n * @param scene Defines the scene the ray needs to be rendered in\n * @param color Defines the color the ray needs to be rendered in\n */\n show(scene, color) {\n if (!this._renderFunction && this.ray) {\n const ray = this.ray;\n this._renderFunction = this._render.bind(this);\n this._scene = scene;\n this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];\n this._renderLine = CreateLines(\"ray\", { points: this._renderPoints, updatable: true }, scene);\n this._renderLine.isPickable = false;\n if (this._renderFunction) {\n this._scene.registerBeforeRender(this._renderFunction);\n }\n }\n if (color && this._renderLine) {\n this._renderLine.color.copyFrom(color);\n }\n }\n /**\n * Hides the ray we are debugging.\n */\n hide() {\n if (this._renderFunction && this._scene) {\n this._scene.unregisterBeforeRender(this._renderFunction);\n this._scene = null;\n this._renderFunction = null;\n if (this._renderLine) {\n this._renderLine.dispose();\n this._renderLine = null;\n }\n this._renderPoints = [];\n }\n }\n _render() {\n var _a;\n const ray = this.ray;\n if (!ray) {\n return;\n }\n const point = this._renderPoints[1];\n const len = Math.min(ray.length, 1000000);\n point.copyFrom(ray.direction);\n point.scaleInPlace(len);\n point.addInPlace(ray.origin);\n this._renderPoints[0].copyFrom(ray.origin);\n CreateLines(\"ray\", { points: this._renderPoints, updatable: true, instance: this._renderLine }, this._scene);\n (_a = this._renderLine) === null || _a === void 0 ? void 0 : _a.refreshBoundingInfo();\n }\n /**\n * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.\n * @param mesh Defines the mesh we want the helper attached to\n * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)\n * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)\n * @param length Defines the length of the ray\n */\n attachToMesh(mesh, meshSpaceDirection, meshSpaceOrigin, length) {\n this._attachedToMesh = mesh;\n const ray = this.ray;\n if (!ray) {\n return;\n }\n if (!ray.direction) {\n ray.direction = Vector3.Zero();\n }\n if (!ray.origin) {\n ray.origin = Vector3.Zero();\n }\n if (length) {\n ray.length = length;\n }\n if (!meshSpaceOrigin) {\n meshSpaceOrigin = Vector3.Zero();\n }\n if (!meshSpaceDirection) {\n // -1 so that this will work with Mesh.lookAt\n meshSpaceDirection = new Vector3(0, 0, -1);\n }\n if (!this._scene) {\n this._scene = mesh.getScene();\n }\n if (!this._meshSpaceDirection) {\n this._meshSpaceDirection = meshSpaceDirection.clone();\n this._meshSpaceOrigin = meshSpaceOrigin.clone();\n }\n else {\n this._meshSpaceDirection.copyFrom(meshSpaceDirection);\n this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);\n }\n if (!this._onAfterRenderObserver) {\n this._onAfterRenderObserver = this._scene.onBeforeRenderObservable.add(() => this._updateToMesh());\n this._onAfterStepObserver = this._scene.onAfterStepObservable.add(() => this._updateToMesh());\n }\n // force world matrix computation before the first ray helper computation\n this._attachedToMesh.computeWorldMatrix(true);\n this._updateToMesh();\n }\n /**\n * Detach the ray helper from the mesh it has previously been attached to.\n */\n detachFromMesh() {\n if (this._attachedToMesh && this._scene) {\n if (this._onAfterRenderObserver) {\n this._scene.onBeforeRenderObservable.remove(this._onAfterRenderObserver);\n this._scene.onAfterStepObservable.remove(this._onAfterStepObserver);\n }\n this._attachedToMesh = null;\n this._onAfterRenderObserver = null;\n this._onAfterStepObserver = null;\n this._scene = null;\n }\n }\n _updateToMesh() {\n const ray = this.ray;\n if (!this._attachedToMesh || !ray) {\n return;\n }\n if (this._attachedToMesh.isDisposed()) {\n this.detachFromMesh();\n return;\n }\n this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);\n Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);\n }\n /**\n * Dispose the helper and release its associated resources.\n */\n dispose() {\n this.hide();\n this.detachFromMesh();\n this.ray = null;\n }\n}\n//# sourceMappingURL=rayHelper.js.map","import { Vector3, Matrix, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Color3, Color4 } from \"../Maths/math.color.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { CreateLineSystem } from \"../Meshes/Builders/linesBuilder.js\";\nimport { UtilityLayerRenderer } from \"../Rendering/utilityLayerRenderer.js\";\nimport { Material } from \"../Materials/material.js\";\nimport { ShaderMaterial } from \"../Materials/shaderMaterial.js\";\nimport { DynamicTexture } from \"../Materials/Textures/dynamicTexture.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Effect } from \"../Materials/effect.js\";\nimport { CreateSphere } from \"../Meshes/Builders/sphereBuilder.js\";\nimport { ExtrudeShapeCustom } from \"../Meshes/Builders/shapeBuilder.js\";\n/**\n * Class used to render a debug view of a given skeleton\n * @see http://www.babylonjs-playground.com/#1BZJVJ#8\n */\nexport class SkeletonViewer {\n /** public static method to create a BoneWeight Shader\n * @param options The constructor options\n * @param scene The scene that the shader is scoped to\n * @returns The created ShaderMaterial\n * @see http://www.babylonjs-playground.com/#1BZJVJ#395\n */\n static CreateBoneWeightShader(options, scene) {\n var _a, _c, _d, _e, _f, _g;\n const skeleton = options.skeleton;\n const colorBase = (_a = options.colorBase) !== null && _a !== void 0 ? _a : Color3.Black();\n const colorZero = (_c = options.colorZero) !== null && _c !== void 0 ? _c : Color3.Blue();\n const colorQuarter = (_d = options.colorQuarter) !== null && _d !== void 0 ? _d : Color3.Green();\n const colorHalf = (_e = options.colorHalf) !== null && _e !== void 0 ? _e : Color3.Yellow();\n const colorFull = (_f = options.colorFull) !== null && _f !== void 0 ? _f : Color3.Red();\n const targetBoneIndex = (_g = options.targetBoneIndex) !== null && _g !== void 0 ? _g : 0;\n Effect.ShadersStore[\"boneWeights:\" + skeleton.name + \"VertexShader\"] = `precision highp float;\r\n\r\n attribute vec3 position;\r\n attribute vec2 uv;\r\n\r\n uniform mat4 view;\r\n uniform mat4 projection;\r\n uniform mat4 worldViewProjection;\r\n\r\n #include\r\n #if NUM_BONE_INFLUENCERS == 0\r\n attribute vec4 matricesIndices;\r\n attribute vec4 matricesWeights;\r\n #endif\r\n #include\r\n\r\n #include\r\n\r\n varying vec3 vColor;\r\n\r\n uniform vec3 colorBase;\r\n uniform vec3 colorZero;\r\n uniform vec3 colorQuarter;\r\n uniform vec3 colorHalf;\r\n uniform vec3 colorFull;\r\n\r\n uniform float targetBoneIndex;\r\n\r\n void main() {\r\n vec3 positionUpdated = position;\r\n\r\n #include\r\n #include\r\n #include\r\n\r\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\r\n\r\n vec3 color = colorBase;\r\n float totalWeight = 0.;\r\n if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){\r\n totalWeight += matricesWeights[0];\r\n }\r\n if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){\r\n totalWeight += matricesWeights[1];\r\n }\r\n if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){\r\n totalWeight += matricesWeights[2];\r\n }\r\n if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){\r\n totalWeight += matricesWeights[3];\r\n }\r\n\r\n color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight));\r\n color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight));\r\n color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight));\r\n color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight));\r\n vColor = color;\r\n\r\n gl_Position = projection * view * worldPos;\r\n }`;\n Effect.ShadersStore[\"boneWeights:\" + skeleton.name + \"FragmentShader\"] = `\r\n precision highp float;\r\n varying vec3 vPosition;\r\n\r\n varying vec3 vColor;\r\n\r\n void main() {\r\n vec4 color = vec4(vColor, 1.0);\r\n gl_FragColor = color;\r\n }\r\n `;\n const shader = new ShaderMaterial(\"boneWeight:\" + skeleton.name, scene, {\n vertex: \"boneWeights:\" + skeleton.name,\n fragment: \"boneWeights:\" + skeleton.name,\n }, {\n attributes: [\"position\", \"normal\", \"matricesIndices\", \"matricesWeights\"],\n uniforms: [\n \"world\",\n \"worldView\",\n \"worldViewProjection\",\n \"view\",\n \"projection\",\n \"viewProjection\",\n \"colorBase\",\n \"colorZero\",\n \"colorQuarter\",\n \"colorHalf\",\n \"colorFull\",\n \"targetBoneIndex\",\n ],\n });\n shader.setColor3(\"colorBase\", colorBase);\n shader.setColor3(\"colorZero\", colorZero);\n shader.setColor3(\"colorQuarter\", colorQuarter);\n shader.setColor3(\"colorHalf\", colorHalf);\n shader.setColor3(\"colorFull\", colorFull);\n shader.setFloat(\"targetBoneIndex\", targetBoneIndex);\n shader.getClassName = () => {\n return \"BoneWeightShader\";\n };\n shader.transparencyMode = Material.MATERIAL_OPAQUE;\n return shader;\n }\n /** public static method to create a BoneWeight Shader\n * @param options The constructor options\n * @param scene The scene that the shader is scoped to\n * @returns The created ShaderMaterial\n */\n static CreateSkeletonMapShader(options, scene) {\n var _a;\n const skeleton = options.skeleton;\n const colorMap = (_a = options.colorMap) !== null && _a !== void 0 ? _a : [\n {\n color: new Color3(1, 0.38, 0.18),\n location: 0,\n },\n {\n color: new Color3(0.59, 0.18, 1.0),\n location: 0.2,\n },\n {\n color: new Color3(0.59, 1, 0.18),\n location: 0.4,\n },\n {\n color: new Color3(1, 0.87, 0.17),\n location: 0.6,\n },\n {\n color: new Color3(1, 0.17, 0.42),\n location: 0.8,\n },\n {\n color: new Color3(0.17, 0.68, 1.0),\n location: 1.0,\n },\n ];\n const bufferWidth = skeleton.bones.length + 1;\n const colorMapBuffer = SkeletonViewer._CreateBoneMapColorBuffer(bufferWidth, colorMap, scene);\n const shader = new ShaderMaterial(\"boneWeights:\" + skeleton.name, scene, {\n vertexSource: `precision highp float;\r\n\r\n attribute vec3 position;\r\n attribute vec2 uv;\r\n\r\n uniform mat4 view;\r\n uniform mat4 projection;\r\n uniform mat4 worldViewProjection;\r\n uniform float colorMap[` +\n skeleton.bones.length * 4 +\n `];\r\n\r\n #include\r\n #if NUM_BONE_INFLUENCERS == 0\r\n attribute vec4 matricesIndices;\r\n attribute vec4 matricesWeights;\r\n #endif\r\n #include\r\n #include\r\n\r\n varying vec3 vColor;\r\n\r\n void main() {\r\n vec3 positionUpdated = position;\r\n\r\n #include\r\n #include\r\n #include\r\n\r\n vec3 color = vec3(0.);\r\n bool first = true;\r\n\r\n for (int i = 0; i < 4; i++) {\r\n int boneIdx = int(matricesIndices[i]);\r\n float boneWgt = matricesWeights[i];\r\n\r\n vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]);\r\n\r\n if (boneWgt > 0.) {\r\n if (first) {\r\n first = false;\r\n color = c;\r\n } else {\r\n color = mix(color, c, boneWgt);\r\n }\r\n }\r\n }\r\n\r\n vColor = color;\r\n\r\n vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0);\r\n\r\n gl_Position = projection * view * worldPos;\r\n }`,\n fragmentSource: `\r\n precision highp float;\r\n varying vec3 vColor;\r\n\r\n void main() {\r\n vec4 color = vec4( vColor, 1.0 );\r\n gl_FragColor = color;\r\n }\r\n `,\n }, {\n attributes: [\"position\", \"normal\", \"matricesIndices\", \"matricesWeights\"],\n uniforms: [\"world\", \"worldView\", \"worldViewProjection\", \"view\", \"projection\", \"viewProjection\", \"colorMap\"],\n });\n shader.setFloats(\"colorMap\", colorMapBuffer);\n shader.getClassName = () => {\n return \"SkeletonMapShader\";\n };\n shader.transparencyMode = Material.MATERIAL_OPAQUE;\n return shader;\n }\n /** private static method to create a BoneWeight Shader\n * @param size The size of the buffer to create (usually the bone count)\n * @param colorMap The gradient data to generate\n * @param scene The scene that the shader is scoped to\n * @returns an Array of floats from the color gradient values\n */\n static _CreateBoneMapColorBuffer(size, colorMap, scene) {\n const tempGrad = new DynamicTexture(\"temp\", { width: size, height: 1 }, scene, false);\n const ctx = tempGrad.getContext();\n const grad = ctx.createLinearGradient(0, 0, size, 0);\n colorMap.forEach((stop) => {\n grad.addColorStop(stop.location, stop.color.toHexString());\n });\n ctx.fillStyle = grad;\n ctx.fillRect(0, 0, size, 1);\n tempGrad.update();\n const buffer = [];\n const data = ctx.getImageData(0, 0, size, 1).data;\n const rUnit = 1 / 255;\n for (let i = 0; i < data.length; i++) {\n buffer.push(data[i] * rUnit);\n }\n tempGrad.dispose();\n return buffer;\n }\n /** Gets the Scene. */\n get scene() {\n return this._scene;\n }\n /** Gets the utilityLayer. */\n get utilityLayer() {\n return this._utilityLayer;\n }\n /** Checks Ready Status. */\n get isReady() {\n return this._ready;\n }\n /** Sets Ready Status. */\n set ready(value) {\n this._ready = value;\n }\n /** Gets the debugMesh */\n get debugMesh() {\n return this._debugMesh;\n }\n /** Sets the debugMesh */\n set debugMesh(value) {\n this._debugMesh = value;\n }\n /** Gets the displayMode */\n get displayMode() {\n return this.options.displayMode || SkeletonViewer.DISPLAY_LINES;\n }\n /** Sets the displayMode */\n set displayMode(value) {\n if (value > SkeletonViewer.DISPLAY_SPHERE_AND_SPURS) {\n value = SkeletonViewer.DISPLAY_LINES;\n }\n this.options.displayMode = value;\n }\n /**\n * Creates a new SkeletonViewer\n * @param skeleton defines the skeleton to render\n * @param mesh defines the mesh attached to the skeleton\n * @param scene defines the hosting scene\n * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)\n * @param renderingGroupId defines the rendering group id to use with the viewer\n * @param options All of the extra constructor options for the SkeletonViewer\n */\n constructor(\n /** defines the skeleton to render */\n skeleton, \n /** defines the mesh attached to the skeleton */\n mesh, \n /** The Scene scope*/\n scene, \n /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */\n autoUpdateBonesMatrices = true, \n /** defines the rendering group id to use with the viewer */\n renderingGroupId = 3, \n /** is the options for the viewer */\n options = {}) {\n var _a, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;\n this.skeleton = skeleton;\n this.mesh = mesh;\n this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;\n this.renderingGroupId = renderingGroupId;\n this.options = options;\n /** Gets or sets the color used to render the skeleton */\n this.color = Color3.White();\n /** Array of the points of the skeleton fo the line view. */\n this._debugLines = new Array();\n /** The local axes Meshes. */\n this._localAxes = null;\n /** If SkeletonViewer is enabled. */\n this._isEnabled = true;\n /** SkeletonViewer render observable. */\n this._obs = null;\n this._scene = scene;\n this._ready = false;\n //Defaults\n options.pauseAnimations = (_a = options.pauseAnimations) !== null && _a !== void 0 ? _a : true;\n options.returnToRest = (_c = options.returnToRest) !== null && _c !== void 0 ? _c : false;\n options.displayMode = (_d = options.displayMode) !== null && _d !== void 0 ? _d : SkeletonViewer.DISPLAY_LINES;\n options.displayOptions = (_e = options.displayOptions) !== null && _e !== void 0 ? _e : {};\n options.displayOptions.midStep = (_f = options.displayOptions.midStep) !== null && _f !== void 0 ? _f : 0.235;\n options.displayOptions.midStepFactor = (_g = options.displayOptions.midStepFactor) !== null && _g !== void 0 ? _g : 0.155;\n options.displayOptions.sphereBaseSize = (_h = options.displayOptions.sphereBaseSize) !== null && _h !== void 0 ? _h : 0.15;\n options.displayOptions.sphereScaleUnit = (_j = options.displayOptions.sphereScaleUnit) !== null && _j !== void 0 ? _j : 2;\n options.displayOptions.sphereFactor = (_k = options.displayOptions.sphereFactor) !== null && _k !== void 0 ? _k : 0.865;\n options.displayOptions.spurFollowsChild = (_l = options.displayOptions.spurFollowsChild) !== null && _l !== void 0 ? _l : false;\n options.displayOptions.showLocalAxes = (_m = options.displayOptions.showLocalAxes) !== null && _m !== void 0 ? _m : false;\n options.displayOptions.localAxesSize = (_o = options.displayOptions.localAxesSize) !== null && _o !== void 0 ? _o : 0.075;\n options.computeBonesUsingShaders = (_p = options.computeBonesUsingShaders) !== null && _p !== void 0 ? _p : true;\n options.useAllBones = (_q = options.useAllBones) !== null && _q !== void 0 ? _q : true;\n const initialMeshBoneIndices = mesh.getVerticesData(VertexBuffer.MatricesIndicesKind);\n const initialMeshBoneWeights = mesh.getVerticesData(VertexBuffer.MatricesWeightsKind);\n this._boneIndices = new Set();\n if (!options.useAllBones) {\n if (initialMeshBoneIndices && initialMeshBoneWeights) {\n for (let i = 0; i < initialMeshBoneIndices.length; ++i) {\n const index = initialMeshBoneIndices[i], weight = initialMeshBoneWeights[i];\n if (weight !== 0) {\n this._boneIndices.add(index);\n }\n }\n }\n }\n /* Create Utility Layer */\n this._utilityLayer = new UtilityLayerRenderer(this._scene, false);\n this._utilityLayer.pickUtilitySceneFirst = false;\n this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil = true;\n let displayMode = this.options.displayMode || 0;\n if (displayMode > SkeletonViewer.DISPLAY_SPHERE_AND_SPURS) {\n displayMode = SkeletonViewer.DISPLAY_LINES;\n }\n this.displayMode = displayMode;\n //Prep the Systems\n this.update();\n this._bindObs();\n }\n /** The Dynamic bindings for the update functions */\n _bindObs() {\n switch (this.displayMode) {\n case SkeletonViewer.DISPLAY_LINES: {\n this._obs = this.scene.onBeforeRenderObservable.add(() => {\n this._displayLinesUpdate();\n });\n break;\n }\n }\n }\n /** Update the viewer to sync with current skeleton state, only used to manually update. */\n update() {\n switch (this.displayMode) {\n case SkeletonViewer.DISPLAY_LINES: {\n this._displayLinesUpdate();\n break;\n }\n case SkeletonViewer.DISPLAY_SPHERES: {\n this._buildSpheresAndSpurs(true);\n break;\n }\n case SkeletonViewer.DISPLAY_SPHERE_AND_SPURS: {\n this._buildSpheresAndSpurs(false);\n break;\n }\n }\n this._buildLocalAxes();\n }\n /** Gets or sets a boolean indicating if the viewer is enabled */\n set isEnabled(value) {\n if (this.isEnabled === value) {\n return;\n }\n this._isEnabled = value;\n if (this.debugMesh) {\n this.debugMesh.setEnabled(value);\n }\n if (value && !this._obs) {\n this._bindObs();\n }\n else if (!value && this._obs) {\n this.scene.onBeforeRenderObservable.remove(this._obs);\n this._obs = null;\n }\n }\n get isEnabled() {\n return this._isEnabled;\n }\n _getBonePosition(position, bone, meshMat, x = 0, y = 0, z = 0) {\n const tmat = TmpVectors.Matrix[0];\n const parentBone = bone.getParent();\n tmat.copyFrom(bone.getLocalMatrix());\n if (x !== 0 || y !== 0 || z !== 0) {\n const tmat2 = TmpVectors.Matrix[1];\n Matrix.IdentityToRef(tmat2);\n tmat2.setTranslationFromFloats(x, y, z);\n tmat2.multiplyToRef(tmat, tmat);\n }\n if (parentBone) {\n tmat.multiplyToRef(parentBone.getAbsoluteMatrix(), tmat);\n }\n tmat.multiplyToRef(meshMat, tmat);\n position.x = tmat.m[12];\n position.y = tmat.m[13];\n position.z = tmat.m[14];\n }\n _getLinesForBonesWithLength(bones, meshMat) {\n const len = bones.length;\n const mesh = this.mesh;\n const meshPos = mesh.position;\n let idx = 0;\n for (let i = 0; i < len; i++) {\n const bone = bones[i];\n let points = this._debugLines[idx];\n if (bone._index === -1 || (!this._boneIndices.has(bone.getIndex()) && !this.options.useAllBones)) {\n continue;\n }\n if (!points) {\n points = [Vector3.Zero(), Vector3.Zero()];\n this._debugLines[idx] = points;\n }\n this._getBonePosition(points[0], bone, meshMat);\n this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);\n points[0].subtractInPlace(meshPos);\n points[1].subtractInPlace(meshPos);\n idx++;\n }\n }\n _getLinesForBonesNoLength(bones) {\n const len = bones.length;\n let boneNum = 0;\n const mesh = this.mesh;\n const meshPos = mesh.position;\n for (let i = len - 1; i >= 0; i--) {\n const childBone = bones[i];\n const parentBone = childBone.getParent();\n if (!parentBone || (!this._boneIndices.has(childBone.getIndex()) && !this.options.useAllBones)) {\n continue;\n }\n let points = this._debugLines[boneNum];\n if (!points) {\n points = [Vector3.Zero(), Vector3.Zero()];\n this._debugLines[boneNum] = points;\n }\n childBone.getAbsolutePositionToRef(mesh, points[0]);\n parentBone.getAbsolutePositionToRef(mesh, points[1]);\n points[0].subtractInPlace(meshPos);\n points[1].subtractInPlace(meshPos);\n boneNum++;\n }\n }\n /**\n * function to revert the mesh and scene back to the initial state.\n * @param animationState\n */\n _revert(animationState) {\n if (this.options.pauseAnimations) {\n this.scene.animationsEnabled = animationState;\n this.utilityLayer.utilityLayerScene.animationsEnabled = animationState;\n }\n }\n /**\n * function to get the absolute bind pose of a bone by accumulating transformations up the bone hierarchy.\n * @param bone\n * @param matrix\n */\n _getAbsoluteBindPoseToRef(bone, matrix) {\n if (bone === null || bone._index === -1) {\n matrix.copyFrom(Matrix.Identity());\n return;\n }\n this._getAbsoluteBindPoseToRef(bone.getParent(), matrix);\n bone.getBaseMatrix().multiplyToRef(matrix, matrix);\n return;\n }\n /**\n * function to build and bind sphere joint points and spur bone representations.\n * @param spheresOnly\n */\n _buildSpheresAndSpurs(spheresOnly = true) {\n var _a, _c;\n if (this._debugMesh) {\n this._debugMesh.dispose();\n this._debugMesh = null;\n this.ready = false;\n }\n this._ready = false;\n const utilityLayerScene = (_a = this.utilityLayer) === null || _a === void 0 ? void 0 : _a.utilityLayerScene;\n const bones = this.skeleton.bones;\n const spheres = [];\n const spurs = [];\n const animationState = this.scene.animationsEnabled;\n try {\n if (this.options.pauseAnimations) {\n this.scene.animationsEnabled = false;\n utilityLayerScene.animationsEnabled = false;\n }\n if (this.options.returnToRest) {\n this.skeleton.returnToRest();\n }\n if (this.autoUpdateBonesMatrices) {\n this.skeleton.computeAbsoluteMatrices();\n }\n let longestBoneLength = Number.NEGATIVE_INFINITY;\n const displayOptions = this.options.displayOptions || {};\n for (let i = 0; i < bones.length; i++) {\n const bone = bones[i];\n if (bone._index === -1 || (!this._boneIndices.has(bone.getIndex()) && !this.options.useAllBones)) {\n continue;\n }\n const boneAbsoluteBindPoseTransform = new Matrix();\n this._getAbsoluteBindPoseToRef(bone, boneAbsoluteBindPoseTransform);\n const anchorPoint = new Vector3();\n boneAbsoluteBindPoseTransform.decompose(undefined, undefined, anchorPoint);\n bone.children.forEach((bc) => {\n const childAbsoluteBindPoseTransform = new Matrix();\n bc.getBaseMatrix().multiplyToRef(boneAbsoluteBindPoseTransform, childAbsoluteBindPoseTransform);\n const childPoint = new Vector3();\n childAbsoluteBindPoseTransform.decompose(undefined, undefined, childPoint);\n const distanceFromParent = Vector3.Distance(anchorPoint, childPoint);\n if (distanceFromParent > longestBoneLength) {\n longestBoneLength = distanceFromParent;\n }\n if (spheresOnly) {\n return;\n }\n const dir = childPoint.clone().subtract(anchorPoint.clone());\n const h = dir.length();\n const up = dir.normalize().scale(h);\n const midStep = displayOptions.midStep || 0.165;\n const midStepFactor = displayOptions.midStepFactor || 0.215;\n const up0 = up.scale(midStep);\n const spur = ExtrudeShapeCustom(\"skeletonViewer\", {\n shape: [new Vector3(1, -1, 0), new Vector3(1, 1, 0), new Vector3(-1, 1, 0), new Vector3(-1, -1, 0), new Vector3(1, -1, 0)],\n path: [Vector3.Zero(), up0, up],\n scaleFunction: (i) => {\n switch (i) {\n case 0:\n case 2:\n return 0;\n case 1:\n return h * midStepFactor;\n }\n return 0;\n },\n sideOrientation: Mesh.DEFAULTSIDE,\n updatable: false,\n }, utilityLayerScene);\n const numVertices = spur.getTotalVertices();\n const mwk = [], mik = [];\n for (let i = 0; i < numVertices; i++) {\n mwk.push(1, 0, 0, 0);\n // Select verts at end of spur (ie vert 10 to 14) and bind to child\n // bone if spurFollowsChild is enabled.\n if (displayOptions.spurFollowsChild && i > 9) {\n mik.push(bc.getIndex(), 0, 0, 0);\n }\n else {\n mik.push(bone.getIndex(), 0, 0, 0);\n }\n }\n spur.position = anchorPoint.clone();\n spur.setVerticesData(VertexBuffer.MatricesWeightsKind, mwk, false);\n spur.setVerticesData(VertexBuffer.MatricesIndicesKind, mik, false);\n spur.convertToFlatShadedMesh();\n spurs.push(spur);\n });\n const sphereBaseSize = displayOptions.sphereBaseSize || 0.2;\n const sphere = CreateSphere(\"skeletonViewer\", {\n segments: 6,\n diameter: sphereBaseSize,\n updatable: true,\n }, utilityLayerScene);\n const numVertices = sphere.getTotalVertices();\n const mwk = [], mik = [];\n for (let i = 0; i < numVertices; i++) {\n mwk.push(1, 0, 0, 0);\n mik.push(bone.getIndex(), 0, 0, 0);\n }\n sphere.setVerticesData(VertexBuffer.MatricesWeightsKind, mwk, false);\n sphere.setVerticesData(VertexBuffer.MatricesIndicesKind, mik, false);\n sphere.position = anchorPoint.clone();\n spheres.push([sphere, bone]);\n }\n const sphereScaleUnit = displayOptions.sphereScaleUnit || 2;\n const sphereFactor = displayOptions.sphereFactor || 0.85;\n const meshes = [];\n for (let i = 0; i < spheres.length; i++) {\n const [sphere, bone] = spheres[i];\n const scale = 1 / (sphereScaleUnit / longestBoneLength);\n let _stepsOut = 0;\n let _b = bone;\n while (_b.getParent() && _b.getParent().getIndex() !== -1) {\n _stepsOut++;\n _b = _b.getParent();\n }\n sphere.scaling.scaleInPlace(scale * Math.pow(sphereFactor, _stepsOut));\n meshes.push(sphere);\n }\n this.debugMesh = Mesh.MergeMeshes(meshes.concat(spurs), true, true);\n if (this.debugMesh) {\n this.debugMesh.renderingGroupId = this.renderingGroupId;\n this.debugMesh.skeleton = this.skeleton;\n this.debugMesh.parent = this.mesh;\n this.debugMesh.computeBonesUsingShaders = (_c = this.options.computeBonesUsingShaders) !== null && _c !== void 0 ? _c : true;\n this.debugMesh.alwaysSelectAsActiveMesh = true;\n }\n const light = this.utilityLayer._getSharedGizmoLight();\n light.intensity = 0.7;\n this._revert(animationState);\n this.ready = true;\n }\n catch (err) {\n console.error(err);\n this._revert(animationState);\n this.dispose();\n }\n }\n _buildLocalAxes() {\n var _a;\n if (this._localAxes) {\n this._localAxes.dispose();\n }\n this._localAxes = null;\n const displayOptions = this.options.displayOptions || {};\n if (!displayOptions.showLocalAxes) {\n return;\n }\n const targetScene = this._utilityLayer.utilityLayerScene;\n const size = displayOptions.localAxesSize || 0.075;\n const lines = [];\n const colors = [];\n const red = new Color4(1, 0, 0, 1);\n const green = new Color4(0, 1, 0, 1);\n const blue = new Color4(0, 0, 1, 1);\n const mwk = [];\n const mik = [];\n const vertsPerBone = 6;\n for (const i in this.skeleton.bones) {\n const bone = this.skeleton.bones[i];\n if (bone._index === -1 || (!this._boneIndices.has(bone.getIndex()) && !this.options.useAllBones)) {\n continue;\n }\n const boneAbsoluteBindPoseTransform = new Matrix();\n const boneOrigin = new Vector3();\n this._getAbsoluteBindPoseToRef(bone, boneAbsoluteBindPoseTransform);\n boneAbsoluteBindPoseTransform.decompose(undefined, TmpVectors.Quaternion[0], boneOrigin);\n const m = new Matrix();\n TmpVectors.Quaternion[0].toRotationMatrix(m);\n const boneAxisX = Vector3.TransformCoordinates(new Vector3(0 + size, 0, 0), m);\n const boneAxisY = Vector3.TransformCoordinates(new Vector3(0, 0 + size, 0), m);\n const boneAxisZ = Vector3.TransformCoordinates(new Vector3(0, 0, 0 + size), m);\n const axisX = [boneOrigin, boneOrigin.add(boneAxisX)];\n const axisY = [boneOrigin, boneOrigin.add(boneAxisY)];\n const axisZ = [boneOrigin, boneOrigin.add(boneAxisZ)];\n const linePoints = [axisX, axisY, axisZ];\n const lineColors = [\n [red, red],\n [green, green],\n [blue, blue],\n ];\n lines.push(...linePoints);\n colors.push(...lineColors);\n for (let j = 0; j < vertsPerBone; j++) {\n mwk.push(1, 0, 0, 0);\n mik.push(bone.getIndex(), 0, 0, 0);\n }\n }\n this._localAxes = CreateLineSystem(\"localAxes\", { lines: lines, colors: colors, updatable: true }, targetScene);\n this._localAxes.setVerticesData(VertexBuffer.MatricesWeightsKind, mwk, false);\n this._localAxes.setVerticesData(VertexBuffer.MatricesIndicesKind, mik, false);\n this._localAxes.skeleton = this.skeleton;\n this._localAxes.renderingGroupId = this.renderingGroupId + 1;\n this._localAxes.parent = this.mesh;\n this._localAxes.computeBonesUsingShaders = (_a = this.options.computeBonesUsingShaders) !== null && _a !== void 0 ? _a : true;\n }\n /** Update the viewer to sync with current skeleton state, only used for the line display. */\n _displayLinesUpdate() {\n if (!this._utilityLayer) {\n return;\n }\n if (this.autoUpdateBonesMatrices) {\n this.skeleton.computeAbsoluteMatrices();\n }\n if (this.skeleton.bones[0].length === undefined) {\n this._getLinesForBonesNoLength(this.skeleton.bones);\n }\n else {\n this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());\n }\n const targetScene = this._utilityLayer.utilityLayerScene;\n if (targetScene) {\n if (!this._debugMesh) {\n this._debugMesh = CreateLineSystem(\"\", { lines: this._debugLines, updatable: true, instance: null }, targetScene);\n this._debugMesh.renderingGroupId = this.renderingGroupId;\n }\n else {\n CreateLineSystem(\"\", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, targetScene);\n }\n this._debugMesh.position.copyFrom(this.mesh.position);\n this._debugMesh.color = this.color;\n }\n }\n /** Changes the displayMode of the skeleton viewer\n * @param mode The displayMode numerical value\n */\n changeDisplayMode(mode) {\n const wasEnabled = this.isEnabled ? true : false;\n if (this.displayMode !== mode) {\n this.isEnabled = false;\n if (this._debugMesh) {\n this._debugMesh.dispose();\n this._debugMesh = null;\n this.ready = false;\n }\n this.displayMode = mode;\n this.update();\n this._bindObs();\n this.isEnabled = wasEnabled;\n }\n }\n /** Sets a display option of the skeleton viewer\n *\n * | Option | Type | Default | Description |\n * | ---------------- | ------- | ------- | ----------- |\n * | midStep | float | 0.235 | A percentage between a bone and its child that determines the widest part of a spur. Only used when `displayMode` is set to `DISPLAY_SPHERE_AND_SPURS`. |\n * | midStepFactor | float | 0.15 | Mid step width expressed as a factor of the length. A value of 0.5 makes the spur width half of the spur length. Only used when `displayMode` is set to `DISPLAY_SPHERE_AND_SPURS`. |\n * | sphereBaseSize | float | 2 | Sphere base size. Only used when `displayMode` is set to `DISPLAY_SPHERE_AND_SPURS`. |\n * | sphereScaleUnit | float | 0.865 | Sphere scale factor used to scale spheres in relation to the longest bone. Only used when `displayMode` is set to `DISPLAY_SPHERE_AND_SPURS`. |\n * | spurFollowsChild | boolean | false | Whether a spur should attach its far end to the child bone. |\n * | showLocalAxes | boolean | false | Displays local axes on all bones. |\n * | localAxesSize | float | 0.075 | Determines the length of each local axis. |\n *\n * @param option String of the option name\n * @param value The numerical option value\n */\n changeDisplayOptions(option, value) {\n const wasEnabled = this.isEnabled ? true : false;\n this.options.displayOptions[option] = value;\n this.isEnabled = false;\n if (this._debugMesh) {\n this._debugMesh.dispose();\n this._debugMesh = null;\n this.ready = false;\n }\n this.update();\n this._bindObs();\n this.isEnabled = wasEnabled;\n }\n /** Release associated resources */\n dispose() {\n this.isEnabled = false;\n if (this._debugMesh) {\n this._debugMesh.dispose();\n this._debugMesh = null;\n }\n if (this._utilityLayer) {\n this._utilityLayer.dispose();\n this._utilityLayer = null;\n }\n this.ready = false;\n }\n}\n/** public Display constants BABYLON.SkeletonViewer.DISPLAY_LINES */\nSkeletonViewer.DISPLAY_LINES = 0;\n/** public Display constants BABYLON.SkeletonViewer.DISPLAY_SPHERES */\nSkeletonViewer.DISPLAY_SPHERES = 1;\n/** public Display constants BABYLON.SkeletonViewer.DISPLAY_SPHERE_AND_SPURS */\nSkeletonViewer.DISPLAY_SPHERE_AND_SPURS = 2;\n//# sourceMappingURL=skeletonViewer.js.map","export {};\n//# sourceMappingURL=ISkeletonViewer.js.map","import { StandardMaterial } from \"../Materials/standardMaterial.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { Matrix, TmpVectors, Vector3 } from \"../Maths/math.vector.js\";\nimport { CreateLines } from \"../Meshes/Builders/linesBuilder.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { VertexData } from \"../Meshes/mesh.vertexData.js\";\nimport { TransformNode } from \"../Meshes/transformNode.js\";\n/**\n * Class used to render a debug view of the frustum for a directional light\n * @see https://playground.babylonjs.com/#7EFGSG#4\n * @since 5.0.0\n */\nexport class DirectionalLightFrustumViewer {\n /**\n * Gets or sets the transparency of the frustum planes\n */\n get transparency() {\n return this._transparency;\n }\n set transparency(alpha) {\n this._transparency = alpha;\n for (let i = 6; i < 12; ++i) {\n this._lightHelperFrustumMeshes[i].material.alpha = alpha;\n }\n }\n /**\n * true to display the edges of the frustum\n */\n get showLines() {\n return this._showLines;\n }\n set showLines(show) {\n if (this._showLines === show) {\n return;\n }\n this._showLines = show;\n for (let i = 0; i < 6; ++i) {\n this._lightHelperFrustumMeshes[i].setEnabled(show);\n }\n }\n /**\n * true to display the planes of the frustum\n */\n get showPlanes() {\n return this._showPlanes;\n }\n set showPlanes(show) {\n if (this._showPlanes === show) {\n return;\n }\n this._showPlanes = show;\n for (let i = 6; i < 12; ++i) {\n this._lightHelperFrustumMeshes[i].setEnabled(show);\n }\n }\n /**\n * Creates a new frustum viewer\n * @param light directional light to display the frustum for\n * @param camera camera used to retrieve the minZ / maxZ values if the shadowMinZ/shadowMaxZ values of the light are not setup\n */\n constructor(light, camera) {\n this._oldPosition = new Vector3(Number.NaN, Number.NaN, Number.NaN);\n this._oldDirection = new Vector3(Number.NaN, Number.NaN, Number.NaN);\n this._transparency = 0.3;\n this._showLines = true;\n this._showPlanes = true;\n this._scene = light.getScene();\n this._light = light;\n this._camera = camera;\n this._inverseViewMatrix = Matrix.Identity();\n this._lightHelperFrustumMeshes = [];\n this._createGeometry();\n this.show();\n this.update();\n }\n /**\n * Shows the frustum\n */\n show() {\n this._lightHelperFrustumMeshes.forEach((mesh, index) => {\n mesh.setEnabled((index < 6 && this._showLines) || (index >= 6 && this._showPlanes));\n });\n this._oldPosition.set(Number.NaN, Number.NaN, Number.NaN);\n this._visible = true;\n }\n /**\n * Hides the frustum\n */\n hide() {\n this._lightHelperFrustumMeshes.forEach((mesh) => {\n mesh.setEnabled(false);\n });\n this._visible = false;\n }\n /**\n * Updates the frustum.\n * Call this method to update the frustum view if the light has changed position/direction\n */\n update() {\n var _a, _b, _c, _d, _e, _f;\n if (!this._visible) {\n return;\n }\n if (this._oldPosition.equals(this._light.position) &&\n this._oldDirection.equals(this._light.direction) &&\n this._oldAutoCalc === this._light.autoCalcShadowZBounds &&\n this._oldMinZ === this._light.shadowMinZ &&\n this._oldMaxZ === this._light.shadowMaxZ) {\n return;\n }\n this._oldPosition.copyFrom(this._light.position);\n this._oldDirection.copyFrom(this._light.direction);\n this._oldAutoCalc = this._light.autoCalcShadowZBounds;\n this._oldMinZ = this._light.shadowMinZ;\n this._oldMaxZ = this._light.shadowMaxZ;\n TmpVectors.Vector3[0].set(this._light.orthoLeft, this._light.orthoBottom, this._light.shadowMinZ !== undefined ? this._light.shadowMinZ : this._camera.minZ); // min light extents\n TmpVectors.Vector3[1].set(this._light.orthoRight, this._light.orthoTop, this._light.shadowMaxZ !== undefined ? this._light.shadowMaxZ : this._camera.maxZ); // max light extents\n const invLightView = this._getInvertViewMatrix();\n TmpVectors.Vector3[2].copyFromFloats(TmpVectors.Vector3[1].x, TmpVectors.Vector3[1].y, TmpVectors.Vector3[0].z); // n1\n TmpVectors.Vector3[3].copyFromFloats(TmpVectors.Vector3[1].x, TmpVectors.Vector3[0].y, TmpVectors.Vector3[0].z); // n2\n TmpVectors.Vector3[4].copyFromFloats(TmpVectors.Vector3[0].x, TmpVectors.Vector3[0].y, TmpVectors.Vector3[0].z); // n3\n TmpVectors.Vector3[5].copyFromFloats(TmpVectors.Vector3[0].x, TmpVectors.Vector3[1].y, TmpVectors.Vector3[0].z); // n4\n Vector3.TransformCoordinatesToRef(TmpVectors.Vector3[2], invLightView, TmpVectors.Vector3[2]); // near1\n Vector3.TransformCoordinatesToRef(TmpVectors.Vector3[3], invLightView, TmpVectors.Vector3[3]); // near2\n Vector3.TransformCoordinatesToRef(TmpVectors.Vector3[4], invLightView, TmpVectors.Vector3[4]); // near3\n Vector3.TransformCoordinatesToRef(TmpVectors.Vector3[5], invLightView, TmpVectors.Vector3[5]); // near4\n TmpVectors.Vector3[6].copyFromFloats(TmpVectors.Vector3[1].x, TmpVectors.Vector3[1].y, TmpVectors.Vector3[1].z); // f1\n TmpVectors.Vector3[7].copyFromFloats(TmpVectors.Vector3[1].x, TmpVectors.Vector3[0].y, TmpVectors.Vector3[1].z); // f2\n TmpVectors.Vector3[8].copyFromFloats(TmpVectors.Vector3[0].x, TmpVectors.Vector3[0].y, TmpVectors.Vector3[1].z); // f3\n TmpVectors.Vector3[9].copyFromFloats(TmpVectors.Vector3[0].x, TmpVectors.Vector3[1].y, TmpVectors.Vector3[1].z); // f4\n Vector3.TransformCoordinatesToRef(TmpVectors.Vector3[6], invLightView, TmpVectors.Vector3[6]); // far1\n Vector3.TransformCoordinatesToRef(TmpVectors.Vector3[7], invLightView, TmpVectors.Vector3[7]); // far2\n Vector3.TransformCoordinatesToRef(TmpVectors.Vector3[8], invLightView, TmpVectors.Vector3[8]); // far3\n Vector3.TransformCoordinatesToRef(TmpVectors.Vector3[9], invLightView, TmpVectors.Vector3[9]); // far4\n CreateLines(\"nearlines\", { updatable: true, points: this._nearLinesPoints, instance: this._lightHelperFrustumMeshes[0] }, this._scene);\n CreateLines(\"farlines\", { updatable: true, points: this._farLinesPoints, instance: this._lightHelperFrustumMeshes[1] }, this._scene);\n CreateLines(\"trlines\", { updatable: true, points: this._trLinesPoints, instance: this._lightHelperFrustumMeshes[2] }, this._scene);\n CreateLines(\"brlines\", { updatable: true, points: this._brLinesPoints, instance: this._lightHelperFrustumMeshes[3] }, this._scene);\n CreateLines(\"tllines\", { updatable: true, points: this._tlLinesPoints, instance: this._lightHelperFrustumMeshes[4] }, this._scene);\n CreateLines(\"bllines\", { updatable: true, points: this._blLinesPoints, instance: this._lightHelperFrustumMeshes[5] }, this._scene);\n TmpVectors.Vector3[2].toArray(this._nearPlaneVertices, 0);\n TmpVectors.Vector3[3].toArray(this._nearPlaneVertices, 3);\n TmpVectors.Vector3[4].toArray(this._nearPlaneVertices, 6);\n TmpVectors.Vector3[5].toArray(this._nearPlaneVertices, 9);\n (_a = this._lightHelperFrustumMeshes[6].geometry) === null || _a === void 0 ? void 0 : _a.updateVerticesDataDirectly(\"position\", this._nearPlaneVertices, 0);\n TmpVectors.Vector3[6].toArray(this._farPlaneVertices, 0);\n TmpVectors.Vector3[7].toArray(this._farPlaneVertices, 3);\n TmpVectors.Vector3[8].toArray(this._farPlaneVertices, 6);\n TmpVectors.Vector3[9].toArray(this._farPlaneVertices, 9);\n (_b = this._lightHelperFrustumMeshes[7].geometry) === null || _b === void 0 ? void 0 : _b.updateVerticesDataDirectly(\"position\", this._farPlaneVertices, 0);\n TmpVectors.Vector3[2].toArray(this._rightPlaneVertices, 0);\n TmpVectors.Vector3[6].toArray(this._rightPlaneVertices, 3);\n TmpVectors.Vector3[7].toArray(this._rightPlaneVertices, 6);\n TmpVectors.Vector3[3].toArray(this._rightPlaneVertices, 9);\n (_c = this._lightHelperFrustumMeshes[8].geometry) === null || _c === void 0 ? void 0 : _c.updateVerticesDataDirectly(\"position\", this._rightPlaneVertices, 0);\n TmpVectors.Vector3[5].toArray(this._leftPlaneVertices, 0);\n TmpVectors.Vector3[9].toArray(this._leftPlaneVertices, 3);\n TmpVectors.Vector3[8].toArray(this._leftPlaneVertices, 6);\n TmpVectors.Vector3[4].toArray(this._leftPlaneVertices, 9);\n (_d = this._lightHelperFrustumMeshes[9].geometry) === null || _d === void 0 ? void 0 : _d.updateVerticesDataDirectly(\"position\", this._leftPlaneVertices, 0);\n TmpVectors.Vector3[2].toArray(this._topPlaneVertices, 0);\n TmpVectors.Vector3[6].toArray(this._topPlaneVertices, 3);\n TmpVectors.Vector3[9].toArray(this._topPlaneVertices, 6);\n TmpVectors.Vector3[5].toArray(this._topPlaneVertices, 9);\n (_e = this._lightHelperFrustumMeshes[10].geometry) === null || _e === void 0 ? void 0 : _e.updateVerticesDataDirectly(\"position\", this._topPlaneVertices, 0);\n TmpVectors.Vector3[3].toArray(this._bottomPlaneVertices, 0);\n TmpVectors.Vector3[7].toArray(this._bottomPlaneVertices, 3);\n TmpVectors.Vector3[8].toArray(this._bottomPlaneVertices, 6);\n TmpVectors.Vector3[4].toArray(this._bottomPlaneVertices, 9);\n (_f = this._lightHelperFrustumMeshes[11].geometry) === null || _f === void 0 ? void 0 : _f.updateVerticesDataDirectly(\"position\", this._bottomPlaneVertices, 0);\n }\n /**\n * Dispose of the class / remove the frustum view\n */\n dispose() {\n this._lightHelperFrustumMeshes.forEach((mesh) => {\n var _a;\n (_a = mesh.material) === null || _a === void 0 ? void 0 : _a.dispose();\n mesh.dispose();\n });\n this._rootNode.dispose();\n }\n _createGeometry() {\n this._rootNode = new TransformNode(\"directionalLightHelperRoot_\" + this._light.name, this._scene);\n this._rootNode.parent = this._light.parent;\n this._nearLinesPoints = [Vector3.ZeroReadOnly, Vector3.ZeroReadOnly, Vector3.ZeroReadOnly, Vector3.ZeroReadOnly, Vector3.ZeroReadOnly];\n const nearLines = CreateLines(\"nearlines\", { updatable: true, points: this._nearLinesPoints }, this._scene);\n nearLines.parent = this._rootNode;\n nearLines.alwaysSelectAsActiveMesh = true;\n this._farLinesPoints = [Vector3.ZeroReadOnly, Vector3.ZeroReadOnly, Vector3.ZeroReadOnly, Vector3.ZeroReadOnly, Vector3.ZeroReadOnly];\n const farLines = CreateLines(\"farlines\", { updatable: true, points: this._farLinesPoints }, this._scene);\n farLines.parent = this._rootNode;\n farLines.alwaysSelectAsActiveMesh = true;\n this._trLinesPoints = [Vector3.ZeroReadOnly, Vector3.ZeroReadOnly];\n const trLines = CreateLines(\"trlines\", { updatable: true, points: this._trLinesPoints }, this._scene);\n trLines.parent = this._rootNode;\n trLines.alwaysSelectAsActiveMesh = true;\n this._brLinesPoints = [Vector3.ZeroReadOnly, Vector3.ZeroReadOnly];\n const brLines = CreateLines(\"brlines\", { updatable: true, points: this._brLinesPoints }, this._scene);\n brLines.parent = this._rootNode;\n brLines.alwaysSelectAsActiveMesh = true;\n this._tlLinesPoints = [Vector3.ZeroReadOnly, Vector3.ZeroReadOnly];\n const tlLines = CreateLines(\"tllines\", { updatable: true, points: this._tlLinesPoints }, this._scene);\n tlLines.parent = this._rootNode;\n tlLines.alwaysSelectAsActiveMesh = true;\n this._blLinesPoints = [Vector3.ZeroReadOnly, Vector3.ZeroReadOnly];\n const blLines = CreateLines(\"bllines\", { updatable: true, points: this._blLinesPoints }, this._scene);\n blLines.parent = this._rootNode;\n blLines.alwaysSelectAsActiveMesh = true;\n this._lightHelperFrustumMeshes.push(nearLines, farLines, trLines, brLines, tlLines, blLines);\n const makePlane = (name, color, positions) => {\n const plane = new Mesh(name + \"plane\", this._scene);\n const mat = new StandardMaterial(name + \"PlaneMat\", this._scene);\n plane.material = mat;\n plane.parent = this._rootNode;\n plane.alwaysSelectAsActiveMesh = true;\n mat.emissiveColor = color;\n mat.alpha = this.transparency;\n mat.backFaceCulling = false;\n mat.disableLighting = true;\n const indices = [0, 1, 2, 0, 2, 3];\n const vertexData = new VertexData();\n vertexData.positions = positions;\n vertexData.indices = indices;\n vertexData.applyToMesh(plane, true);\n this._lightHelperFrustumMeshes.push(plane);\n };\n this._nearPlaneVertices = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n this._farPlaneVertices = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n this._rightPlaneVertices = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n this._leftPlaneVertices = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n this._topPlaneVertices = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n this._bottomPlaneVertices = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n makePlane(\"near\", new Color3(1, 0, 0), this._nearPlaneVertices);\n makePlane(\"far\", new Color3(0.3, 0, 0), this._farPlaneVertices);\n makePlane(\"right\", new Color3(0, 1, 0), this._rightPlaneVertices);\n makePlane(\"left\", new Color3(0, 0.3, 0), this._leftPlaneVertices);\n makePlane(\"top\", new Color3(0, 0, 1), this._topPlaneVertices);\n makePlane(\"bottom\", new Color3(0, 0, 0.3), this._bottomPlaneVertices);\n this._nearLinesPoints[0] = TmpVectors.Vector3[2];\n this._nearLinesPoints[1] = TmpVectors.Vector3[3];\n this._nearLinesPoints[2] = TmpVectors.Vector3[4];\n this._nearLinesPoints[3] = TmpVectors.Vector3[5];\n this._nearLinesPoints[4] = TmpVectors.Vector3[2];\n this._farLinesPoints[0] = TmpVectors.Vector3[6];\n this._farLinesPoints[1] = TmpVectors.Vector3[7];\n this._farLinesPoints[2] = TmpVectors.Vector3[8];\n this._farLinesPoints[3] = TmpVectors.Vector3[9];\n this._farLinesPoints[4] = TmpVectors.Vector3[6];\n this._trLinesPoints[0] = TmpVectors.Vector3[2];\n this._trLinesPoints[1] = TmpVectors.Vector3[6];\n this._brLinesPoints[0] = TmpVectors.Vector3[3];\n this._brLinesPoints[1] = TmpVectors.Vector3[7];\n this._tlLinesPoints[0] = TmpVectors.Vector3[4];\n this._tlLinesPoints[1] = TmpVectors.Vector3[8];\n this._blLinesPoints[0] = TmpVectors.Vector3[5];\n this._blLinesPoints[1] = TmpVectors.Vector3[9];\n }\n _getInvertViewMatrix() {\n Matrix.LookAtLHToRef(this._light.position, this._light.position.add(this._light.direction), Vector3.UpReadOnly, this._inverseViewMatrix);\n this._inverseViewMatrix.invertToRef(this._inverseViewMatrix);\n return this._inverseViewMatrix;\n }\n}\n//# sourceMappingURL=directionalLightFrustumViewer.js.map","export * from \"./axesViewer.js\";\nexport * from \"./boneAxesViewer.js\";\nexport * from \"./debugLayer.js\";\nexport * from \"./physicsViewer.js\";\nexport * from \"./rayHelper.js\";\nexport * from \"./skeletonViewer.js\";\nexport * from \"./ISkeletonViewer.js\";\nexport * from \"./directionalLightFrustumViewer.js\";\n//# sourceMappingURL=index.js.map","export {};\n//# sourceMappingURL=deviceTypes.js.map","export * from \"./InputDevices/deviceEnums.js\";\nexport * from \"./InputDevices/deviceTypes.js\";\nexport * from \"./InputDevices/deviceSource.js\";\nexport * from \"./InputDevices/deviceSourceManager.js\";\n//# sourceMappingURL=index.js.map","/* eslint-disable @typescript-eslint/naming-convention */\n/** Defines the cross module used constants to avoid circular dependencies */\nexport class Constants {\n}\n/** Defines that alpha blending is disabled */\nConstants.ALPHA_DISABLE = 0;\n/** Defines that alpha blending is SRC ALPHA * SRC + DEST */\nConstants.ALPHA_ADD = 1;\n/** Defines that alpha blending is SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */\nConstants.ALPHA_COMBINE = 2;\n/** Defines that alpha blending is DEST - SRC * DEST */\nConstants.ALPHA_SUBTRACT = 3;\n/** Defines that alpha blending is SRC * DEST */\nConstants.ALPHA_MULTIPLY = 4;\n/** Defines that alpha blending is SRC ALPHA * SRC + (1 - SRC) * DEST */\nConstants.ALPHA_MAXIMIZED = 5;\n/** Defines that alpha blending is SRC + DEST */\nConstants.ALPHA_ONEONE = 6;\n/** Defines that alpha blending is SRC + (1 - SRC ALPHA) * DEST */\nConstants.ALPHA_PREMULTIPLIED = 7;\n/**\n * Defines that alpha blending is SRC + (1 - SRC ALPHA) * DEST\n * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA\n */\nConstants.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;\n/** Defines that alpha blending is CST * SRC + (1 - CST) * DEST */\nConstants.ALPHA_INTERPOLATE = 9;\n/**\n * Defines that alpha blending is SRC + (1 - SRC) * DEST\n * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA\n */\nConstants.ALPHA_SCREENMODE = 10;\n/**\n * Defines that alpha blending is SRC + DST\n * Alpha will be set to SRC ALPHA + DST ALPHA\n */\nConstants.ALPHA_ONEONE_ONEONE = 11;\n/**\n * Defines that alpha blending is SRC * DST ALPHA + DST\n * Alpha will be set to 0\n */\nConstants.ALPHA_ALPHATOCOLOR = 12;\n/**\n * Defines that alpha blending is SRC * (1 - DST) + DST * (1 - SRC)\n */\nConstants.ALPHA_REVERSEONEMINUS = 13;\n/**\n * Defines that alpha blending is SRC + DST * (1 - SRC ALPHA)\n * Alpha will be set to SRC ALPHA + DST ALPHA * (1 - SRC ALPHA)\n */\nConstants.ALPHA_SRC_DSTONEMINUSSRCALPHA = 14;\n/**\n * Defines that alpha blending is SRC + DST\n * Alpha will be set to SRC ALPHA\n */\nConstants.ALPHA_ONEONE_ONEZERO = 15;\n/**\n * Defines that alpha blending is SRC * (1 - DST) + DST * (1 - SRC)\n * Alpha will be set to DST ALPHA\n */\nConstants.ALPHA_EXCLUSION = 16;\n/**\n * Defines that alpha blending is SRC * SRC ALPHA + DST * (1 - SRC ALPHA)\n * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DST ALPHA\n */\nConstants.ALPHA_LAYER_ACCUMULATE = 17;\n/** Defines that alpha blending equation a SUM */\nConstants.ALPHA_EQUATION_ADD = 0;\n/** Defines that alpha blending equation a SUBSTRACTION */\nConstants.ALPHA_EQUATION_SUBSTRACT = 1;\n/** Defines that alpha blending equation a REVERSE SUBSTRACTION */\nConstants.ALPHA_EQUATION_REVERSE_SUBTRACT = 2;\n/** Defines that alpha blending equation a MAX operation */\nConstants.ALPHA_EQUATION_MAX = 3;\n/** Defines that alpha blending equation a MIN operation */\nConstants.ALPHA_EQUATION_MIN = 4;\n/**\n * Defines that alpha blending equation a DARKEN operation:\n * It takes the min of the src and sums the alpha channels.\n */\nConstants.ALPHA_EQUATION_DARKEN = 5;\n/** Defines that the resource is not delayed*/\nConstants.DELAYLOADSTATE_NONE = 0;\n/** Defines that the resource was successfully delay loaded */\nConstants.DELAYLOADSTATE_LOADED = 1;\n/** Defines that the resource is currently delay loading */\nConstants.DELAYLOADSTATE_LOADING = 2;\n/** Defines that the resource is delayed and has not started loading */\nConstants.DELAYLOADSTATE_NOTLOADED = 4;\n// Depth or Stencil test Constants.\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */\nConstants.NEVER = 0x0200;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */\nConstants.ALWAYS = 0x0207;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */\nConstants.LESS = 0x0201;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */\nConstants.EQUAL = 0x0202;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */\nConstants.LEQUAL = 0x0203;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */\nConstants.GREATER = 0x0204;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */\nConstants.GEQUAL = 0x0206;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */\nConstants.NOTEQUAL = 0x0205;\n// Stencil Actions Constants.\n/** Passed to stencilOperation to specify that stencil value must be kept */\nConstants.KEEP = 0x1e00;\n/** Passed to stencilOperation to specify that stencil value must be zero */\nConstants.ZERO = 0x0000;\n/** Passed to stencilOperation to specify that stencil value must be replaced */\nConstants.REPLACE = 0x1e01;\n/** Passed to stencilOperation to specify that stencil value must be incremented */\nConstants.INCR = 0x1e02;\n/** Passed to stencilOperation to specify that stencil value must be decremented */\nConstants.DECR = 0x1e03;\n/** Passed to stencilOperation to specify that stencil value must be inverted */\nConstants.INVERT = 0x150a;\n/** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */\nConstants.INCR_WRAP = 0x8507;\n/** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */\nConstants.DECR_WRAP = 0x8508;\n/** Texture is not repeating outside of 0..1 UVs */\nConstants.TEXTURE_CLAMP_ADDRESSMODE = 0;\n/** Texture is repeating outside of 0..1 UVs */\nConstants.TEXTURE_WRAP_ADDRESSMODE = 1;\n/** Texture is repeating and mirrored */\nConstants.TEXTURE_MIRROR_ADDRESSMODE = 2;\n/** Flag to create a storage texture */\nConstants.TEXTURE_CREATIONFLAG_STORAGE = 1;\n/** ALPHA */\nConstants.TEXTUREFORMAT_ALPHA = 0;\n/** LUMINANCE */\nConstants.TEXTUREFORMAT_LUMINANCE = 1;\n/** LUMINANCE_ALPHA */\nConstants.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;\n/** RGB */\nConstants.TEXTUREFORMAT_RGB = 4;\n/** RGBA */\nConstants.TEXTUREFORMAT_RGBA = 5;\n/** RED */\nConstants.TEXTUREFORMAT_RED = 6;\n/** RED (2nd reference) */\nConstants.TEXTUREFORMAT_R = 6;\n/** RG */\nConstants.TEXTUREFORMAT_RG = 7;\n/** RED_INTEGER */\nConstants.TEXTUREFORMAT_RED_INTEGER = 8;\n/** RED_INTEGER (2nd reference) */\nConstants.TEXTUREFORMAT_R_INTEGER = 8;\n/** RG_INTEGER */\nConstants.TEXTUREFORMAT_RG_INTEGER = 9;\n/** RGB_INTEGER */\nConstants.TEXTUREFORMAT_RGB_INTEGER = 10;\n/** RGBA_INTEGER */\nConstants.TEXTUREFORMAT_RGBA_INTEGER = 11;\n/** BGRA */\nConstants.TEXTUREFORMAT_BGRA = 12;\n/** Depth 24 bits + Stencil 8 bits */\nConstants.TEXTUREFORMAT_DEPTH24_STENCIL8 = 13;\n/** Depth 32 bits float */\nConstants.TEXTUREFORMAT_DEPTH32_FLOAT = 14;\n/** Depth 16 bits */\nConstants.TEXTUREFORMAT_DEPTH16 = 15;\n/** Depth 24 bits */\nConstants.TEXTUREFORMAT_DEPTH24 = 16;\n/** Depth 24 bits unorm + Stencil 8 bits */\nConstants.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8 = 17;\n/** Depth 32 bits float + Stencil 8 bits */\nConstants.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8 = 18;\n/** Stencil 8 bits */\nConstants.TEXTUREFORMAT_STENCIL8 = 19;\n/** Compressed BC7 */\nConstants.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM = 36492;\n/** Compressed BC7 (SRGB) */\nConstants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM = 36493;\n/** Compressed BC6 unsigned float */\nConstants.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT = 36495;\n/** Compressed BC6 signed float */\nConstants.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT = 36494;\n/** Compressed BC3 */\nConstants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5 = 33779;\n/** Compressed BC3 (SRGB) */\nConstants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT = 35919;\n/** Compressed BC2 */\nConstants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3 = 33778;\n/** Compressed BC2 (SRGB) */\nConstants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT = 35918;\n/** Compressed BC1 (RGBA) */\nConstants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1 = 33777;\n/** Compressed BC1 (RGB) */\nConstants.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1 = 33776;\n/** Compressed BC1 (SRGB+A) */\nConstants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT = 35917;\n/** Compressed BC1 (SRGB) */\nConstants.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT = 35916;\n/** Compressed ASTC 4x4 */\nConstants.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4 = 37808;\n/** Compressed ASTC 4x4 (SRGB) */\nConstants.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = 37840;\n/** Compressed ETC1 (RGB) */\nConstants.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL = 36196;\n/** Compressed ETC2 (RGB) */\nConstants.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2 = 37492;\n/** Compressed ETC2 (SRGB) */\nConstants.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2 = 37493;\n/** Compressed ETC2 (RGB+A1) */\nConstants.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 37494;\n/** Compressed ETC2 (SRGB+A1)*/\nConstants.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 37495;\n/** Compressed ETC2 (RGB+A) */\nConstants.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC = 37496;\n/** Compressed ETC2 (SRGB+1) */\nConstants.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 37497;\n/** UNSIGNED_BYTE */\nConstants.TEXTURETYPE_UNSIGNED_BYTE = 0;\n/** UNSIGNED_BYTE (2nd reference) */\nConstants.TEXTURETYPE_UNSIGNED_INT = 0;\n/** FLOAT */\nConstants.TEXTURETYPE_FLOAT = 1;\n/** HALF_FLOAT */\nConstants.TEXTURETYPE_HALF_FLOAT = 2;\n/** BYTE */\nConstants.TEXTURETYPE_BYTE = 3;\n/** SHORT */\nConstants.TEXTURETYPE_SHORT = 4;\n/** UNSIGNED_SHORT */\nConstants.TEXTURETYPE_UNSIGNED_SHORT = 5;\n/** INT */\nConstants.TEXTURETYPE_INT = 6;\n/** UNSIGNED_INT */\nConstants.TEXTURETYPE_UNSIGNED_INTEGER = 7;\n/** UNSIGNED_SHORT_4_4_4_4 */\nConstants.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;\n/** UNSIGNED_SHORT_5_5_5_1 */\nConstants.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;\n/** UNSIGNED_SHORT_5_6_5 */\nConstants.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;\n/** UNSIGNED_INT_2_10_10_10_REV */\nConstants.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;\n/** UNSIGNED_INT_24_8 */\nConstants.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;\n/** UNSIGNED_INT_10F_11F_11F_REV */\nConstants.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;\n/** UNSIGNED_INT_5_9_9_9_REV */\nConstants.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;\n/** FLOAT_32_UNSIGNED_INT_24_8_REV */\nConstants.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;\n/** UNDEFINED */\nConstants.TEXTURETYPE_UNDEFINED = 16;\n/** 2D Texture target*/\nConstants.TEXTURE_2D = 3553;\n/** 2D Array Texture target */\nConstants.TEXTURE_2D_ARRAY = 35866;\n/** Cube Map Texture target */\nConstants.TEXTURE_CUBE_MAP = 34067;\n/** Cube Map Array Texture target */\nConstants.TEXTURE_CUBE_MAP_ARRAY = 0xdeadbeef;\n/** 3D Texture target */\nConstants.TEXTURE_3D = 32879;\n/** nearest is mag = nearest and min = nearest and no mip */\nConstants.TEXTURE_NEAREST_SAMPLINGMODE = 1;\n/** mag = nearest and min = nearest and mip = none */\nConstants.TEXTURE_NEAREST_NEAREST = 1;\n/** Bilinear is mag = linear and min = linear and no mip */\nConstants.TEXTURE_BILINEAR_SAMPLINGMODE = 2;\n/** mag = linear and min = linear and mip = none */\nConstants.TEXTURE_LINEAR_LINEAR = 2;\n/** Trilinear is mag = linear and min = linear and mip = linear */\nConstants.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;\n/** Trilinear is mag = linear and min = linear and mip = linear */\nConstants.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;\n/** mag = nearest and min = nearest and mip = nearest */\nConstants.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;\n/** mag = nearest and min = linear and mip = nearest */\nConstants.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;\n/** mag = nearest and min = linear and mip = linear */\nConstants.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;\n/** mag = nearest and min = linear and mip = none */\nConstants.TEXTURE_NEAREST_LINEAR = 7;\n/** nearest is mag = nearest and min = nearest and mip = linear */\nConstants.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 8;\n/** mag = linear and min = nearest and mip = nearest */\nConstants.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;\n/** mag = linear and min = nearest and mip = linear */\nConstants.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;\n/** Bilinear is mag = linear and min = linear and mip = nearest */\nConstants.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 11;\n/** mag = linear and min = nearest and mip = none */\nConstants.TEXTURE_LINEAR_NEAREST = 12;\n/** Explicit coordinates mode */\nConstants.TEXTURE_EXPLICIT_MODE = 0;\n/** Spherical coordinates mode */\nConstants.TEXTURE_SPHERICAL_MODE = 1;\n/** Planar coordinates mode */\nConstants.TEXTURE_PLANAR_MODE = 2;\n/** Cubic coordinates mode */\nConstants.TEXTURE_CUBIC_MODE = 3;\n/** Projection coordinates mode */\nConstants.TEXTURE_PROJECTION_MODE = 4;\n/** Skybox coordinates mode */\nConstants.TEXTURE_SKYBOX_MODE = 5;\n/** Inverse Cubic coordinates mode */\nConstants.TEXTURE_INVCUBIC_MODE = 6;\n/** Equirectangular coordinates mode */\nConstants.TEXTURE_EQUIRECTANGULAR_MODE = 7;\n/** Equirectangular Fixed coordinates mode */\nConstants.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;\n/** Equirectangular Fixed Mirrored coordinates mode */\nConstants.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;\n/** Offline (baking) quality for texture filtering */\nConstants.TEXTURE_FILTERING_QUALITY_OFFLINE = 4096;\n/** High quality for texture filtering */\nConstants.TEXTURE_FILTERING_QUALITY_HIGH = 64;\n/** Medium quality for texture filtering */\nConstants.TEXTURE_FILTERING_QUALITY_MEDIUM = 16;\n/** Low quality for texture filtering */\nConstants.TEXTURE_FILTERING_QUALITY_LOW = 8;\n// Texture rescaling mode\n/** Defines that texture rescaling will use a floor to find the closer power of 2 size */\nConstants.SCALEMODE_FLOOR = 1;\n/** Defines that texture rescaling will look for the nearest power of 2 size */\nConstants.SCALEMODE_NEAREST = 2;\n/** Defines that texture rescaling will use a ceil to find the closer power of 2 size */\nConstants.SCALEMODE_CEILING = 3;\n/**\n * The dirty texture flag value\n */\nConstants.MATERIAL_TextureDirtyFlag = 1;\n/**\n * The dirty light flag value\n */\nConstants.MATERIAL_LightDirtyFlag = 2;\n/**\n * The dirty fresnel flag value\n */\nConstants.MATERIAL_FresnelDirtyFlag = 4;\n/**\n * The dirty attribute flag value\n */\nConstants.MATERIAL_AttributesDirtyFlag = 8;\n/**\n * The dirty misc flag value\n */\nConstants.MATERIAL_MiscDirtyFlag = 16;\n/**\n * The dirty prepass flag value\n */\nConstants.MATERIAL_PrePassDirtyFlag = 32;\n/**\n * The all dirty flag value\n */\nConstants.MATERIAL_AllDirtyFlag = 63;\n/**\n * Returns the triangle fill mode\n */\nConstants.MATERIAL_TriangleFillMode = 0;\n/**\n * Returns the wireframe mode\n */\nConstants.MATERIAL_WireFrameFillMode = 1;\n/**\n * Returns the point fill mode\n */\nConstants.MATERIAL_PointFillMode = 2;\n/**\n * Returns the point list draw mode\n */\nConstants.MATERIAL_PointListDrawMode = 3;\n/**\n * Returns the line list draw mode\n */\nConstants.MATERIAL_LineListDrawMode = 4;\n/**\n * Returns the line loop draw mode\n */\nConstants.MATERIAL_LineLoopDrawMode = 5;\n/**\n * Returns the line strip draw mode\n */\nConstants.MATERIAL_LineStripDrawMode = 6;\n/**\n * Returns the triangle strip draw mode\n */\nConstants.MATERIAL_TriangleStripDrawMode = 7;\n/**\n * Returns the triangle fan draw mode\n */\nConstants.MATERIAL_TriangleFanDrawMode = 8;\n/**\n * Stores the clock-wise side orientation\n */\nConstants.MATERIAL_ClockWiseSideOrientation = 0;\n/**\n * Stores the counter clock-wise side orientation\n */\nConstants.MATERIAL_CounterClockWiseSideOrientation = 1;\n/**\n * Nothing\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_NothingTrigger = 0;\n/**\n * On pick\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnPickTrigger = 1;\n/**\n * On left pick\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnLeftPickTrigger = 2;\n/**\n * On right pick\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnRightPickTrigger = 3;\n/**\n * On center pick\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnCenterPickTrigger = 4;\n/**\n * On pick down\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnPickDownTrigger = 5;\n/**\n * On double pick\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnDoublePickTrigger = 6;\n/**\n * On pick up\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnPickUpTrigger = 7;\n/**\n * On pick out.\n * This trigger will only be raised if you also declared a OnPickDown\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnPickOutTrigger = 16;\n/**\n * On long press\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnLongPressTrigger = 8;\n/**\n * On pointer over\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnPointerOverTrigger = 9;\n/**\n * On pointer out\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnPointerOutTrigger = 10;\n/**\n * On every frame\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnEveryFrameTrigger = 11;\n/**\n * On intersection enter\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnIntersectionEnterTrigger = 12;\n/**\n * On intersection exit\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnIntersectionExitTrigger = 13;\n/**\n * On key down\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnKeyDownTrigger = 14;\n/**\n * On key up\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions#triggers\n */\nConstants.ACTION_OnKeyUpTrigger = 15;\n/**\n * Billboard mode will only apply to Y axis\n */\nConstants.PARTICLES_BILLBOARDMODE_Y = 2;\n/**\n * Billboard mode will apply to all axes\n */\nConstants.PARTICLES_BILLBOARDMODE_ALL = 7;\n/**\n * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction\n */\nConstants.PARTICLES_BILLBOARDMODE_STRETCHED = 8;\n/**\n * Special billboard mode where the particle will be billboard to the camera but only around the axis of the direction of particle emission\n */\nConstants.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL = 9;\n/** Default culling strategy : this is an exclusion test and it's the more accurate.\n * Test order :\n * Is the bounding sphere outside the frustum ?\n * If not, are the bounding box vertices outside the frustum ?\n * It not, then the cullable object is in the frustum.\n */\nConstants.MESHES_CULLINGSTRATEGY_STANDARD = 0;\n/** Culling strategy : Bounding Sphere Only.\n * This is an exclusion test. It's faster than the standard strategy because the bounding box is not tested.\n * It's also less accurate than the standard because some not visible objects can still be selected.\n * Test : is the bounding sphere outside the frustum ?\n * If not, then the cullable object is in the frustum.\n */\nConstants.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;\n/** Culling strategy : Optimistic Inclusion.\n * This in an inclusion test first, then the standard exclusion test.\n * This can be faster when a cullable object is expected to be almost always in the camera frustum.\n * This could also be a little slower than the standard test when the tested object center is not the frustum but one of its bounding box vertex is still inside.\n * Anyway, it's as accurate as the standard strategy.\n * Test :\n * Is the cullable object bounding sphere center in the frustum ?\n * If not, apply the default culling strategy.\n */\nConstants.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION = 2;\n/** Culling strategy : Optimistic Inclusion then Bounding Sphere Only.\n * This in an inclusion test first, then the bounding sphere only exclusion test.\n * This can be the fastest test when a cullable object is expected to be almost always in the camera frustum.\n * This could also be a little slower than the BoundingSphereOnly strategy when the tested object center is not in the frustum but its bounding sphere still intersects it.\n * It's less accurate than the standard strategy and as accurate as the BoundingSphereOnly strategy.\n * Test :\n * Is the cullable object bounding sphere center in the frustum ?\n * If not, apply the Bounding Sphere Only strategy. No Bounding Box is tested here.\n */\nConstants.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY = 3;\n/**\n * No logging while loading\n */\nConstants.SCENELOADER_NO_LOGGING = 0;\n/**\n * Minimal logging while loading\n */\nConstants.SCENELOADER_MINIMAL_LOGGING = 1;\n/**\n * Summary logging while loading\n */\nConstants.SCENELOADER_SUMMARY_LOGGING = 2;\n/**\n * Detailed logging while loading\n */\nConstants.SCENELOADER_DETAILED_LOGGING = 3;\n/**\n * Constant used to retrieve the irradiance texture index in the textures array in the prepass\n * using getIndex(Constants.PREPASS_IRRADIANCE_TEXTURE_TYPE)\n */\nConstants.PREPASS_IRRADIANCE_TEXTURE_TYPE = 0;\n/**\n * Constant used to retrieve the position texture index in the textures array in the prepass\n * using getIndex(Constants.PREPASS_POSITION_TEXTURE_INDEX)\n */\nConstants.PREPASS_POSITION_TEXTURE_TYPE = 1;\n/**\n * Constant used to retrieve the velocity texture index in the textures array in the prepass\n * using getIndex(Constants.PREPASS_VELOCITY_TEXTURE_INDEX)\n */\nConstants.PREPASS_VELOCITY_TEXTURE_TYPE = 2;\n/**\n * Constant used to retrieve the reflectivity texture index in the textures array in the prepass\n * using the getIndex(Constants.PREPASS_REFLECTIVITY_TEXTURE_TYPE)\n */\nConstants.PREPASS_REFLECTIVITY_TEXTURE_TYPE = 3;\n/**\n * Constant used to retrieve the lit color texture index in the textures array in the prepass\n * using the getIndex(Constants.PREPASS_COLOR_TEXTURE_TYPE)\n */\nConstants.PREPASS_COLOR_TEXTURE_TYPE = 4;\n/**\n * Constant used to retrieve depth index in the textures array in the prepass\n * using the getIndex(Constants.PREPASS_DEPTH_TEXTURE_TYPE)\n */\nConstants.PREPASS_DEPTH_TEXTURE_TYPE = 5;\n/**\n * Constant used to retrieve normal index in the textures array in the prepass\n * using the getIndex(Constants.PREPASS_NORMAL_TEXTURE_TYPE)\n */\nConstants.PREPASS_NORMAL_TEXTURE_TYPE = 6;\n/**\n * Constant used to retrieve albedo index in the textures array in the prepass\n * using the getIndex(Constants.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE)\n */\nConstants.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE = 7;\n/** Flag to create a readable buffer (the buffer can be the source of a copy) */\nConstants.BUFFER_CREATIONFLAG_READ = 1;\n/** Flag to create a writable buffer (the buffer can be the destination of a copy) */\nConstants.BUFFER_CREATIONFLAG_WRITE = 2;\n/** Flag to create a readable and writable buffer */\nConstants.BUFFER_CREATIONFLAG_READWRITE = 3;\n/** Flag to create a buffer suitable to be used as a uniform buffer */\nConstants.BUFFER_CREATIONFLAG_UNIFORM = 4;\n/** Flag to create a buffer suitable to be used as a vertex buffer */\nConstants.BUFFER_CREATIONFLAG_VERTEX = 8;\n/** Flag to create a buffer suitable to be used as an index buffer */\nConstants.BUFFER_CREATIONFLAG_INDEX = 16;\n/** Flag to create a buffer suitable to be used as a storage buffer */\nConstants.BUFFER_CREATIONFLAG_STORAGE = 32;\n/**\n * Prefixes used by the engine for sub mesh draw wrappers\n */\n/** @internal */\nConstants.RENDERPASS_MAIN = 0;\n/**\n * Constant used as key code for Alt key\n */\nConstants.INPUT_ALT_KEY = 18;\n/**\n * Constant used as key code for Ctrl key\n */\nConstants.INPUT_CTRL_KEY = 17;\n/**\n * Constant used as key code for Meta key (Left Win, Left Cmd)\n */\nConstants.INPUT_META_KEY1 = 91;\n/**\n * Constant used as key code for Meta key (Right Win)\n */\nConstants.INPUT_META_KEY2 = 92;\n/**\n * Constant used as key code for Meta key (Right Win, Right Cmd)\n */\nConstants.INPUT_META_KEY3 = 93;\n/**\n * Constant used as key code for Shift key\n */\nConstants.INPUT_SHIFT_KEY = 16;\n/** Standard snapshot rendering. In this mode, some form of dynamic behavior is possible (for eg, uniform buffers are still updated) */\nConstants.SNAPSHOTRENDERING_STANDARD = 0;\n/** Fast snapshot rendering. In this mode, everything is static and only some limited form of dynamic behaviour is possible */\nConstants.SNAPSHOTRENDERING_FAST = 1;\n/**\n * This is the default projection mode used by the cameras.\n * It helps recreating a feeling of perspective and better appreciate depth.\n * This is the best way to simulate real life cameras.\n */\nConstants.PERSPECTIVE_CAMERA = 0;\n/**\n * This helps creating camera with an orthographic mode.\n * Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object.\n */\nConstants.ORTHOGRAPHIC_CAMERA = 1;\n/**\n * This is the default FOV mode for perspective cameras.\n * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.\n */\nConstants.FOVMODE_VERTICAL_FIXED = 0;\n/**\n * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.\n */\nConstants.FOVMODE_HORIZONTAL_FIXED = 1;\n/**\n * This specifies there is no need for a camera rig.\n * Basically only one eye is rendered corresponding to the camera.\n */\nConstants.RIG_MODE_NONE = 0;\n/**\n * Simulates a camera Rig with one blue eye and one red eye.\n * This can be use with 3d blue and red glasses.\n */\nConstants.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;\n/**\n * Defines that both eyes of the camera will be rendered side by side with a parallel target.\n */\nConstants.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;\n/**\n * Defines that both eyes of the camera will be rendered side by side with a none parallel target.\n */\nConstants.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;\n/**\n * Defines that both eyes of the camera will be rendered over under each other.\n */\nConstants.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;\n/**\n * Defines that both eyes of the camera will be rendered on successive lines interlaced for passive 3d monitors.\n */\nConstants.RIG_MODE_STEREOSCOPIC_INTERLACED = 14;\n/**\n * Defines that both eyes of the camera should be renderered in a VR mode (carbox).\n */\nConstants.RIG_MODE_VR = 20;\n/**\n * Defines that both eyes of the camera should be renderered in a VR mode (webVR).\n */\nConstants.RIG_MODE_WEBVR = 21;\n/**\n * Custom rig mode allowing rig cameras to be populated manually with any number of cameras\n */\nConstants.RIG_MODE_CUSTOM = 22;\n/**\n * Maximum number of uv sets supported\n */\nConstants.MAX_SUPPORTED_UV_SETS = 6;\n/**\n * GL constants\n */\n/** Alpha blend equation: ADD */\nConstants.GL_ALPHA_EQUATION_ADD = 0x8006;\n/** Alpha equation: MIN */\nConstants.GL_ALPHA_EQUATION_MIN = 0x8007;\n/** Alpha equation: MAX */\nConstants.GL_ALPHA_EQUATION_MAX = 0x8008;\n/** Alpha equation: SUBTRACT */\nConstants.GL_ALPHA_EQUATION_SUBTRACT = 0x800a;\n/** Alpha equation: REVERSE_SUBTRACT */\nConstants.GL_ALPHA_EQUATION_REVERSE_SUBTRACT = 0x800b;\n/** Alpha blend function: SRC */\nConstants.GL_ALPHA_FUNCTION_SRC = 0x0300;\n/** Alpha blend function: ONE_MINUS_SRC */\nConstants.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR = 0x0301;\n/** Alpha blend function: SRC_ALPHA */\nConstants.GL_ALPHA_FUNCTION_SRC_ALPHA = 0x0302;\n/** Alpha blend function: ONE_MINUS_SRC_ALPHA */\nConstants.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA = 0x0303;\n/** Alpha blend function: DST_ALPHA */\nConstants.GL_ALPHA_FUNCTION_DST_ALPHA = 0x0304;\n/** Alpha blend function: ONE_MINUS_DST_ALPHA */\nConstants.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA = 0x0305;\n/** Alpha blend function: ONE_MINUS_DST */\nConstants.GL_ALPHA_FUNCTION_DST_COLOR = 0x0306;\n/** Alpha blend function: ONE_MINUS_DST */\nConstants.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR = 0x0307;\n/** Alpha blend function: SRC_ALPHA_SATURATED */\nConstants.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED = 0x0308;\n/** Alpha blend function: CONSTANT */\nConstants.GL_ALPHA_FUNCTION_CONSTANT_COLOR = 0x8001;\n/** Alpha blend function: ONE_MINUS_CONSTANT */\nConstants.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR = 0x8002;\n/** Alpha blend function: CONSTANT_ALPHA */\nConstants.GL_ALPHA_FUNCTION_CONSTANT_ALPHA = 0x8003;\n/** Alpha blend function: ONE_MINUS_CONSTANT_ALPHA */\nConstants.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA = 0x8004;\n/** URL to the snippet server. Points to the public snippet server by default */\nConstants.SnippetUrl = \"https://snippet.babylonjs.com\";\n//# sourceMappingURL=constants.js.map","/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { Logger } from \"../Misc/logger.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { InternalTexture, InternalTextureSource } from \"../Materials/Textures/internalTexture.js\";\n\nimport { DataBuffer } from \"../Buffers/dataBuffer.js\";\nimport { PerformanceConfigurator } from \"./performanceConfigurator.js\";\nimport { DrawWrapper } from \"../Materials/drawWrapper.js\";\nimport { RenderTargetWrapper } from \"./renderTargetWrapper.js\";\n/**\n * Options to create the null engine\n */\nexport class NullEngineOptions {\n constructor() {\n /**\n * Render width (Default: 512)\n */\n this.renderWidth = 512;\n /**\n * Render height (Default: 256)\n */\n this.renderHeight = 256;\n /**\n * Texture size (Default: 512)\n */\n this.textureSize = 512;\n /**\n * If delta time between frames should be constant\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep\n */\n this.deterministicLockstep = false;\n /**\n * Maximum about of steps between frames (Default: 4)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep\n */\n this.lockstepMaxSteps = 4;\n }\n}\n/**\n * The null engine class provides support for headless version of babylon.js.\n * This can be used in server side scenario or for testing purposes\n */\nexport class NullEngine extends Engine {\n /**\n * Gets a boolean indicating that the engine is running in deterministic lock step mode\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep\n * @returns true if engine is in deterministic lock step mode\n */\n isDeterministicLockStep() {\n return this._options.deterministicLockstep;\n }\n /**\n * Gets the max steps when engine is running in deterministic lock step\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep\n * @returns the max steps\n */\n getLockstepMaxSteps() {\n return this._options.lockstepMaxSteps;\n }\n /**\n * Gets the current hardware scaling level.\n * By default the hardware scaling level is computed from the window device ratio.\n * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.\n * @returns a number indicating the current hardware scaling level\n */\n getHardwareScalingLevel() {\n return 1.0;\n }\n constructor(options = new NullEngineOptions()) {\n super(null);\n Engine.Instances.push(this);\n if (options.deterministicLockstep === undefined) {\n options.deterministicLockstep = false;\n }\n if (options.lockstepMaxSteps === undefined) {\n options.lockstepMaxSteps = 4;\n }\n this._options = options;\n PerformanceConfigurator.SetMatrixPrecision(!!options.useHighPrecisionMatrix);\n // Init caps\n // We consider we are on a webgl1 capable device\n this._caps = {\n maxTexturesImageUnits: 16,\n maxVertexTextureImageUnits: 16,\n maxCombinedTexturesImageUnits: 32,\n maxTextureSize: 512,\n maxCubemapTextureSize: 512,\n maxRenderTextureSize: 512,\n maxVertexAttribs: 16,\n maxVaryingVectors: 16,\n maxFragmentUniformVectors: 16,\n maxVertexUniformVectors: 16,\n standardDerivatives: false,\n astc: null,\n pvrtc: null,\n etc1: null,\n etc2: null,\n bptc: null,\n maxAnisotropy: 0,\n uintIndices: false,\n fragmentDepthSupported: false,\n highPrecisionShaderSupported: true,\n colorBufferFloat: false,\n textureFloat: false,\n textureFloatLinearFiltering: false,\n textureFloatRender: false,\n textureHalfFloat: false,\n textureHalfFloatLinearFiltering: false,\n textureHalfFloatRender: false,\n textureLOD: false,\n texelFetch: false,\n drawBuffersExtension: false,\n depthTextureExtension: false,\n vertexArrayObject: false,\n instancedArrays: false,\n supportOcclusionQuery: false,\n canUseTimestampForTimerQuery: false,\n maxMSAASamples: 1,\n blendMinMax: false,\n canUseGLInstanceID: false,\n canUseGLVertexID: false,\n supportComputeShaders: false,\n supportSRGBBuffers: false,\n supportTransformFeedbacks: false,\n textureMaxLevel: false,\n texture2DArrayMaxLayerCount: 128,\n disableMorphTargetTexture: false,\n };\n this._features = {\n forceBitmapOverHTMLImageElement: false,\n supportRenderAndCopyToLodForFloatTextures: false,\n supportDepthStencilTexture: false,\n supportShadowSamplers: false,\n uniformBufferHardCheckMatrix: false,\n allowTexturePrefiltering: false,\n trackUbosInFrame: false,\n checkUbosContentBeforeUpload: false,\n supportCSM: false,\n basisNeedsPOT: false,\n support3DTextures: false,\n needTypeSuffixInShaderConstants: false,\n supportMSAA: false,\n supportSSAO2: false,\n supportExtendedTextureFormats: false,\n supportSwitchCaseInShader: false,\n supportSyncTextureRead: false,\n needsInvertingBitmap: false,\n useUBOBindingCache: false,\n needShaderCodeInlining: false,\n needToAlwaysBindUniformBuffers: false,\n supportRenderPasses: true,\n supportSpriteInstancing: false,\n _collectUbosUpdatedInFrame: false,\n };\n Logger.Log(`Babylon.js v${Engine.Version} - Null engine`);\n // Wrappers\n const theCurrentGlobal = typeof self !== \"undefined\" ? self : typeof global !== \"undefined\" ? global : window;\n if (typeof URL === \"undefined\") {\n theCurrentGlobal.URL = {\n createObjectURL: function () { },\n revokeObjectURL: function () { },\n };\n }\n if (typeof Blob === \"undefined\") {\n theCurrentGlobal.Blob = function () { };\n }\n }\n /**\n * Creates a vertex buffer\n * @param vertices the data for the vertex buffer\n * @returns the new WebGL static buffer\n */\n createVertexBuffer(vertices) {\n const buffer = new DataBuffer();\n buffer.references = 1;\n return buffer;\n }\n /**\n * Creates a new index buffer\n * @param indices defines the content of the index buffer\n * @returns a new webGL buffer\n */\n createIndexBuffer(indices) {\n const buffer = new DataBuffer();\n buffer.references = 1;\n return buffer;\n }\n /**\n * Clear the current render buffer or the current render target (if any is set up)\n * @param color defines the color to use\n * @param backBuffer defines if the back buffer must be cleared\n * @param depth defines if the depth buffer must be cleared\n * @param stencil defines if the stencil buffer must be cleared\n */\n clear(color, backBuffer, depth, stencil = false) { }\n /**\n * Gets the current render width\n * @param useScreen defines if screen size must be used (or the current render target if any)\n * @returns a number defining the current render width\n */\n getRenderWidth(useScreen = false) {\n if (!useScreen && this._currentRenderTarget) {\n return this._currentRenderTarget.width;\n }\n return this._options.renderWidth;\n }\n /**\n * Gets the current render height\n * @param useScreen defines if screen size must be used (or the current render target if any)\n * @returns a number defining the current render height\n */\n getRenderHeight(useScreen = false) {\n if (!useScreen && this._currentRenderTarget) {\n return this._currentRenderTarget.height;\n }\n return this._options.renderHeight;\n }\n /**\n * Set the WebGL's viewport\n * @param viewport defines the viewport element to be used\n * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used\n * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used\n */\n setViewport(viewport, requiredWidth, requiredHeight) {\n this._cachedViewport = viewport;\n }\n createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context) {\n return {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n __SPECTOR_rebuildProgram: null,\n };\n }\n /**\n * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names\n * @param pipelineContext defines the pipeline context to use\n * @param uniformsNames defines the list of uniform names\n * @returns an array of webGL uniform locations\n */\n getUniforms(pipelineContext, uniformsNames) {\n return [];\n }\n /**\n * Gets the lsit of active attributes for a given webGL program\n * @param pipelineContext defines the pipeline context to use\n * @param attributesNames defines the list of attribute names to get\n * @returns an array of indices indicating the offset of each attribute\n */\n getAttributes(pipelineContext, attributesNames) {\n return [];\n }\n /**\n * Binds an effect to the webGL context\n * @param effect defines the effect to bind\n */\n bindSamplers(effect) {\n this._currentEffect = null;\n }\n /**\n * Activates an effect, making it the current one (ie. the one used for rendering)\n * @param effect defines the effect to activate\n */\n enableEffect(effect) {\n effect = effect !== null && DrawWrapper.IsWrapper(effect) ? effect.effect : effect; // get only the effect, we don't need a Wrapper in the WebGL engine\n this._currentEffect = effect;\n if (!effect) {\n return;\n }\n if (effect.onBind) {\n effect.onBind(effect);\n }\n if (effect._onBindObservable) {\n effect._onBindObservable.notifyObservers(effect);\n }\n }\n /**\n * Set various states to the webGL context\n * @param culling defines culling state: true to enable culling, false to disable it\n * @param zOffset defines the value to apply to zOffset (0 by default)\n * @param force defines if states must be applied even if cache is up to date\n * @param reverseSide defines if culling must be reversed (CCW if false, CW if true)\n * @param cullBackFaces true to cull back faces, false to cull front faces (if culling is enabled)\n * @param stencil stencil states to set\n * @param zOffsetUnits defines the value to apply to zOffsetUnits (0 by default)\n */\n setState(culling, zOffset = 0, force, reverseSide = false, cullBackFaces, stencil, zOffsetUnits = 0) { }\n /**\n * Set the value of an uniform to an array of int32\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of int32 to store\n * @returns true if value was set\n */\n setIntArray(uniform, array) {\n return true;\n }\n /**\n * Set the value of an uniform to an array of int32 (stored as vec2)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of int32 to store\n * @returns true if value was set\n */\n setIntArray2(uniform, array) {\n return true;\n }\n /**\n * Set the value of an uniform to an array of int32 (stored as vec3)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of int32 to store\n * @returns true if value was set\n */\n setIntArray3(uniform, array) {\n return true;\n }\n /**\n * Set the value of an uniform to an array of int32 (stored as vec4)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of int32 to store\n * @returns true if value was set\n */\n setIntArray4(uniform, array) {\n return true;\n }\n /**\n * Set the value of an uniform to an array of float32\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of float32 to store\n * @returns true if value was set\n */\n setFloatArray(uniform, array) {\n return true;\n }\n /**\n * Set the value of an uniform to an array of float32 (stored as vec2)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of float32 to store\n * @returns true if value was set\n */\n setFloatArray2(uniform, array) {\n return true;\n }\n /**\n * Set the value of an uniform to an array of float32 (stored as vec3)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of float32 to store\n * @returns true if value was set\n */\n setFloatArray3(uniform, array) {\n return true;\n }\n /**\n * Set the value of an uniform to an array of float32 (stored as vec4)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of float32 to store\n * @returns true if value was set\n */\n setFloatArray4(uniform, array) {\n return true;\n }\n /**\n * Set the value of an uniform to an array of number\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of number to store\n * @returns true if value was set\n */\n setArray(uniform, array) {\n return true;\n }\n /**\n * Set the value of an uniform to an array of number (stored as vec2)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of number to store\n * @returns true if value was set\n */\n setArray2(uniform, array) {\n return true;\n }\n /**\n * Set the value of an uniform to an array of number (stored as vec3)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of number to store\n * @returns true if value was set\n */\n setArray3(uniform, array) {\n return true;\n }\n /**\n * Set the value of an uniform to an array of number (stored as vec4)\n * @param uniform defines the webGL uniform location where to store the value\n * @param array defines the array of number to store\n * @returns true if value was set\n */\n setArray4(uniform, array) {\n return true;\n }\n /**\n * Set the value of an uniform to an array of float32 (stored as matrices)\n * @param uniform defines the webGL uniform location where to store the value\n * @param matrices defines the array of float32 to store\n * @returns true if value was set\n */\n setMatrices(uniform, matrices) {\n return true;\n }\n /**\n * Set the value of an uniform to a matrix (3x3)\n * @param uniform defines the webGL uniform location where to store the value\n * @param matrix defines the Float32Array representing the 3x3 matrix to store\n * @returns true if value was set\n */\n setMatrix3x3(uniform, matrix) {\n return true;\n }\n /**\n * Set the value of an uniform to a matrix (2x2)\n * @param uniform defines the webGL uniform location where to store the value\n * @param matrix defines the Float32Array representing the 2x2 matrix to store\n * @returns true if value was set\n */\n setMatrix2x2(uniform, matrix) {\n return true;\n }\n /**\n * Set the value of an uniform to a number (float)\n * @param uniform defines the webGL uniform location where to store the value\n * @param value defines the float number to store\n * @returns true if value was set\n */\n setFloat(uniform, value) {\n return true;\n }\n /**\n * Set the value of an uniform to a vec2\n * @param uniform defines the webGL uniform location where to store the value\n * @param x defines the 1st component of the value\n * @param y defines the 2nd component of the value\n * @returns true if value was set\n */\n setFloat2(uniform, x, y) {\n return true;\n }\n /**\n * Set the value of an uniform to a vec3\n * @param uniform defines the webGL uniform location where to store the value\n * @param x defines the 1st component of the value\n * @param y defines the 2nd component of the value\n * @param z defines the 3rd component of the value\n * @returns true if value was set\n */\n setFloat3(uniform, x, y, z) {\n return true;\n }\n /**\n * Set the value of an uniform to a boolean\n * @param uniform defines the webGL uniform location where to store the value\n * @param bool defines the boolean to store\n * @returns true if value was set\n */\n setBool(uniform, bool) {\n return true;\n }\n /**\n * Set the value of an uniform to a vec4\n * @param uniform defines the webGL uniform location where to store the value\n * @param x defines the 1st component of the value\n * @param y defines the 2nd component of the value\n * @param z defines the 3rd component of the value\n * @param w defines the 4th component of the value\n * @returns true if value was set\n */\n setFloat4(uniform, x, y, z, w) {\n return true;\n }\n /**\n * Sets the current alpha mode\n * @param mode defines the mode to use (one of the Engine.ALPHA_XXX)\n * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/transparent_rendering\n */\n setAlphaMode(mode, noDepthWriteChange = false) {\n if (this._alphaMode === mode) {\n return;\n }\n this.alphaState.alphaBlend = mode !== 0;\n if (!noDepthWriteChange) {\n this.setDepthWrite(mode === 0);\n }\n this._alphaMode = mode;\n }\n /**\n * Bind webGl buffers directly to the webGL context\n * @param vertexBuffers defines the vertex buffer to bind\n * @param indexBuffer defines the index buffer to bind\n * @param effect defines the effect associated with the vertex buffer\n */\n bindBuffers(vertexBuffers, indexBuffer, effect) { }\n /**\n * Force the entire cache to be cleared\n * You should not have to use this function unless your engine needs to share the webGL context with another engine\n * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)\n */\n wipeCaches(bruteForce) {\n if (this.preventCacheWipeBetweenFrames) {\n return;\n }\n this.resetTextureCache();\n this._currentEffect = null;\n if (bruteForce) {\n this._currentProgram = null;\n this._stencilStateComposer.reset();\n this.depthCullingState.reset();\n this.alphaState.reset();\n }\n this._cachedVertexBuffers = null;\n this._cachedIndexBuffer = null;\n this._cachedEffectForVertexBuffers = null;\n }\n /**\n * Send a draw order\n * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)\n * @param indexStart defines the starting index\n * @param indexCount defines the number of index to draw\n * @param instancesCount defines the number of instances to draw (if instantiation is enabled)\n */\n draw(useTriangles, indexStart, indexCount, instancesCount) { }\n /**\n * Draw a list of indexed primitives\n * @param fillMode defines the primitive to use\n * @param indexStart defines the starting index\n * @param indexCount defines the number of index to draw\n * @param instancesCount defines the number of instances to draw (if instantiation is enabled)\n */\n drawElementsType(fillMode, indexStart, indexCount, instancesCount) { }\n /**\n * Draw a list of unindexed primitives\n * @param fillMode defines the primitive to use\n * @param verticesStart defines the index of first vertex to draw\n * @param verticesCount defines the count of vertices to draw\n * @param instancesCount defines the number of instances to draw (if instantiation is enabled)\n */\n drawArraysType(fillMode, verticesStart, verticesCount, instancesCount) { }\n /** @internal */\n _createTexture() {\n return {};\n }\n /**\n * @internal\n */\n _releaseTexture(texture) { }\n /**\n * Usually called from Texture.ts.\n * Passed information to create a WebGLTexture\n * @param urlArg defines a value which contains one of the following:\n * * A conventional http URL, e.g. 'http://...' or 'file://...'\n * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'\n * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'\n * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file\n * @param invertY when true, image is flipped when loaded. You probably want true. Certain compressed textures may invert this if their default is inverted (eg. ktx)\n * @param scene needed for loading to the correct scene\n * @param samplingMode mode with should be used sample / access the texture (Default: Texture.TRILINEAR_SAMPLINGMODE)\n * @param onLoad optional callback to be called upon successful completion\n * @param onError optional callback to be called upon failure\n * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob\n * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities\n * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures\n * @param forcedExtension defines the extension to use to pick the right loader\n * @param mimeType defines an optional mime type\n * @returns a InternalTexture for assignment back into BABYLON.Texture\n */\n createTexture(urlArg, noMipmap, invertY, scene, samplingMode = 3, onLoad = null, onError = null, buffer = null, fallback = null, format = null, forcedExtension = null, mimeType) {\n const texture = new InternalTexture(this, InternalTextureSource.Url);\n const url = String(urlArg);\n texture.url = url;\n texture.generateMipMaps = !noMipmap;\n texture.samplingMode = samplingMode;\n texture.invertY = invertY;\n texture.baseWidth = this._options.textureSize;\n texture.baseHeight = this._options.textureSize;\n texture.width = this._options.textureSize;\n texture.height = this._options.textureSize;\n if (format) {\n texture.format = format;\n }\n texture.isReady = true;\n if (onLoad) {\n setTimeout(() => {\n onLoad(texture);\n });\n }\n this._internalTexturesCache.push(texture);\n return texture;\n }\n /**\n * @internal\n */\n _createHardwareRenderTargetWrapper(isMulti, isCube, size) {\n const rtWrapper = new RenderTargetWrapper(isMulti, isCube, size, this);\n this._renderTargetWrapperCache.push(rtWrapper);\n return rtWrapper;\n }\n /**\n * Creates a new render target wrapper\n * @param size defines the size of the texture\n * @param options defines the options used to create the texture\n * @returns a new render target wrapper\n */\n createRenderTargetTexture(size, options) {\n const rtWrapper = this._createHardwareRenderTargetWrapper(false, false, size);\n const fullOptions = {};\n if (options !== undefined && typeof options === \"object\") {\n fullOptions.generateMipMaps = options.generateMipMaps;\n fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;\n fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;\n fullOptions.type = options.type === undefined ? 0 : options.type;\n fullOptions.samplingMode = options.samplingMode === undefined ? 3 : options.samplingMode;\n }\n else {\n fullOptions.generateMipMaps = options;\n fullOptions.generateDepthBuffer = true;\n fullOptions.generateStencilBuffer = false;\n fullOptions.type = 0;\n fullOptions.samplingMode = 3;\n }\n const texture = new InternalTexture(this, InternalTextureSource.RenderTarget);\n const width = size.width || size;\n const height = size.height || size;\n rtWrapper._generateDepthBuffer = fullOptions.generateDepthBuffer;\n rtWrapper._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = width;\n texture.height = height;\n texture.isReady = true;\n texture.samples = 1;\n texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;\n texture.samplingMode = fullOptions.samplingMode;\n texture.type = fullOptions.type;\n this._internalTexturesCache.push(texture);\n return rtWrapper;\n }\n /**\n * Creates a new render target wrapper\n * @param size defines the size of the texture\n * @param options defines the options used to create the texture\n * @returns a new render target wrapper\n */\n createRenderTargetCubeTexture(size, options) {\n const rtWrapper = this._createHardwareRenderTargetWrapper(false, true, size);\n const fullOptions = Object.assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: 0, samplingMode: 3, format: 5 }, options);\n fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;\n if (fullOptions.type === 1 && !this._caps.textureFloatLinearFiltering) {\n // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE\n fullOptions.samplingMode = 1;\n }\n else if (fullOptions.type === 2 && !this._caps.textureHalfFloatLinearFiltering) {\n // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE\n fullOptions.samplingMode = 1;\n }\n rtWrapper._generateDepthBuffer = fullOptions.generateDepthBuffer;\n rtWrapper._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;\n const texture = new InternalTexture(this, InternalTextureSource.RenderTarget);\n texture.baseWidth = size;\n texture.baseHeight = size;\n texture.width = size;\n texture.height = size;\n texture.isReady = true;\n texture.isCube = true;\n texture.samples = 1;\n texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;\n texture.samplingMode = fullOptions.samplingMode;\n texture.type = fullOptions.type;\n this._internalTexturesCache.push(texture);\n return rtWrapper;\n }\n /**\n * Update the sampling mode of a given texture\n * @param samplingMode defines the required sampling mode\n * @param texture defines the texture to update\n */\n updateTextureSamplingMode(samplingMode, texture) {\n texture.samplingMode = samplingMode;\n }\n /**\n * Creates a raw texture\n * @param data defines the data to store in the texture\n * @param width defines the width of the texture\n * @param height defines the height of the texture\n * @param format defines the format of the data\n * @param generateMipMaps defines if the engine should generate the mip levels\n * @param invertY defines if data must be stored with Y axis inverted\n * @param samplingMode defines the required sampling mode (Texture.NEAREST_SAMPLINGMODE by default)\n * @param compression defines the compression used (null by default)\n * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_INT by default)\n * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)\n * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU).\n * @returns the raw texture inside an InternalTexture\n */\n createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, compression = null, type = 0, creationFlags = 0, useSRGBBuffer = false) {\n const texture = new InternalTexture(this, InternalTextureSource.Raw);\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = width;\n texture.height = height;\n texture.format = format;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.invertY = invertY;\n texture._compression = compression;\n texture.type = type;\n texture._useSRGBBuffer = useSRGBBuffer;\n if (!this._doNotHandleContextLost) {\n texture._bufferView = data;\n }\n return texture;\n }\n /**\n * Update a raw texture\n * @param texture defines the texture to update\n * @param data defines the data to store in the texture\n * @param format defines the format of the data\n * @param invertY defines if data must be stored with Y axis inverted\n * @param compression defines the compression used (null by default)\n * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_INT by default)\n * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU).\n */\n updateRawTexture(texture, data, format, invertY, compression = null, type = 0, useSRGBBuffer = false) {\n if (texture) {\n texture._bufferView = data;\n texture.format = format;\n texture.invertY = invertY;\n texture._compression = compression;\n texture.type = type;\n texture._useSRGBBuffer = useSRGBBuffer;\n }\n }\n /**\n * Binds the frame buffer to the specified texture.\n * @param rtWrapper The render target wrapper to render to\n * @param faceIndex The face of the texture to render to in case of cube texture\n * @param requiredWidth The width of the target to render to\n * @param requiredHeight The height of the target to render to\n * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true\n */\n bindFramebuffer(rtWrapper, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {\n if (this._currentRenderTarget) {\n this.unBindFramebuffer(this._currentRenderTarget);\n }\n this._currentRenderTarget = rtWrapper;\n this._currentFramebuffer = null;\n if (this._cachedViewport && !forceFullscreenViewport) {\n this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);\n }\n }\n /**\n * Unbind the current render target texture from the webGL context\n * @param rtWrapper defines the render target wrapper to unbind\n * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated\n * @param onBeforeUnbind defines a function which will be called before the effective unbind\n */\n unBindFramebuffer(rtWrapper, disableGenerateMipMaps = false, onBeforeUnbind) {\n this._currentRenderTarget = null;\n if (onBeforeUnbind) {\n onBeforeUnbind();\n }\n this._currentFramebuffer = null;\n }\n /**\n * Creates a dynamic vertex buffer\n * @param vertices the data for the dynamic vertex buffer\n * @returns the new WebGL dynamic buffer\n */\n createDynamicVertexBuffer(vertices) {\n const buffer = new DataBuffer();\n buffer.references = 1;\n buffer.capacity = 1;\n return buffer;\n }\n /**\n * Update the content of a dynamic texture\n * @param texture defines the texture to update\n * @param canvas defines the canvas containing the source\n * @param invertY defines if data must be stored with Y axis inverted\n * @param premulAlpha defines if alpha is stored as premultiplied\n * @param format defines the format of the data\n */\n updateDynamicTexture(texture, canvas, invertY, premulAlpha = false, format) { }\n /**\n * Gets a boolean indicating if all created effects are ready\n * @returns true if all effects are ready\n */\n areAllEffectsReady() {\n return true;\n }\n /**\n * @internal\n * Get the current error code of the webGL context\n * @returns the error code\n * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError\n */\n getError() {\n return 0;\n }\n /** @internal */\n _getUnpackAlignement() {\n return 1;\n }\n /**\n * @internal\n */\n _unpackFlipY(value) { }\n /**\n * Update a dynamic index buffer\n * @param indexBuffer defines the target index buffer\n * @param indices defines the data to update\n * @param offset defines the offset in the target index buffer where update should start\n */\n updateDynamicIndexBuffer(indexBuffer, indices, offset = 0) { }\n /**\n * Updates a dynamic vertex buffer.\n * @param vertexBuffer the vertex buffer to update\n * @param vertices the data used to update the vertex buffer\n * @param byteOffset the byte offset of the data (optional)\n * @param byteLength the byte length of the data (optional)\n */\n updateDynamicVertexBuffer(vertexBuffer, vertices, byteOffset, byteLength) { }\n /**\n * @internal\n */\n _bindTextureDirectly(target, texture) {\n if (this._boundTexturesCache[this._activeChannel] !== texture) {\n this._boundTexturesCache[this._activeChannel] = texture;\n return true;\n }\n return false;\n }\n /**\n * @internal\n */\n _bindTexture(channel, texture) {\n if (channel < 0) {\n return;\n }\n this._bindTextureDirectly(0, texture);\n }\n _deleteBuffer(buffer) { }\n /**\n * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled\n */\n releaseEffects() { }\n displayLoadingUI() { }\n hideLoadingUI() { }\n set loadingUIText(_) { }\n /**\n * @internal\n */\n _uploadCompressedDataToTextureDirectly(texture, internalFormat, width, height, data, faceIndex = 0, lod = 0) { }\n /**\n * @internal\n */\n _uploadDataToTextureDirectly(texture, imageData, faceIndex = 0, lod = 0) { }\n /**\n * @internal\n */\n _uploadArrayBufferViewToTexture(texture, imageData, faceIndex = 0, lod = 0) { }\n /**\n * @internal\n */\n _uploadImageToTexture(texture, image, faceIndex = 0, lod = 0) { }\n}\n//# sourceMappingURL=nullEngine.js.map","/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { ThinEngine } from \"../../Engines/thinEngine.js\";\nThinEngine.prototype._debugPushGroup = function (groupName, targetObject) { };\nThinEngine.prototype._debugPopGroup = function (targetObject) { };\nThinEngine.prototype._debugInsertMarker = function (text, targetObject) { };\nThinEngine.prototype._debugFlushPendingCommands = function () { };\n//# sourceMappingURL=engine.debugging.js.map","/**\n * @internal\n **/\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class _TimeToken {\n constructor() {\n this._timeElapsedQueryEnded = false;\n }\n}\n//# sourceMappingURL=timeToken.js.map","import { Engine } from \"../../Engines/engine.js\";\nimport { AbstractMesh } from \"../../Meshes/abstractMesh.js\";\nimport { _TimeToken } from \"../../Instrumentation/timeToken.js\";\nimport { PerfCounter } from \"../../Misc/perfCounter.js\";\n/** @internal */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class _OcclusionDataStorage {\n constructor() {\n /** @internal */\n this.occlusionInternalRetryCounter = 0;\n /** @internal */\n this.isOcclusionQueryInProgress = false;\n /** @internal */\n this.isOccluded = false;\n /** @internal */\n this.occlusionRetryCount = -1;\n /** @internal */\n this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;\n /** @internal */\n this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;\n /** @internal */\n this.forceRenderingWhenOccluded = false;\n }\n}\nEngine.prototype.createQuery = function () {\n const query = this._gl.createQuery();\n if (!query) {\n throw new Error(\"Unable to create Occlusion Query\");\n }\n return query;\n};\nEngine.prototype.deleteQuery = function (query) {\n this._gl.deleteQuery(query);\n return this;\n};\nEngine.prototype.isQueryResultAvailable = function (query) {\n return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);\n};\nEngine.prototype.getQueryResult = function (query) {\n return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);\n};\nEngine.prototype.beginOcclusionQuery = function (algorithmType, query) {\n const glAlgorithm = this._getGlAlgorithmType(algorithmType);\n this._gl.beginQuery(glAlgorithm, query);\n return true;\n};\nEngine.prototype.endOcclusionQuery = function (algorithmType) {\n const glAlgorithm = this._getGlAlgorithmType(algorithmType);\n this._gl.endQuery(glAlgorithm);\n return this;\n};\nEngine.prototype._createTimeQuery = function () {\n const timerQuery = this.getCaps().timerQuery;\n if (timerQuery.createQueryEXT) {\n return timerQuery.createQueryEXT();\n }\n return this.createQuery();\n};\nEngine.prototype._deleteTimeQuery = function (query) {\n const timerQuery = this.getCaps().timerQuery;\n if (timerQuery.deleteQueryEXT) {\n timerQuery.deleteQueryEXT(query);\n return;\n }\n this.deleteQuery(query);\n};\nEngine.prototype._getTimeQueryResult = function (query) {\n const timerQuery = this.getCaps().timerQuery;\n if (timerQuery.getQueryObjectEXT) {\n return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);\n }\n return this.getQueryResult(query);\n};\nEngine.prototype._getTimeQueryAvailability = function (query) {\n const timerQuery = this.getCaps().timerQuery;\n if (timerQuery.getQueryObjectEXT) {\n return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);\n }\n return this.isQueryResultAvailable(query);\n};\nEngine.prototype.startTimeQuery = function () {\n const caps = this.getCaps();\n const timerQuery = caps.timerQuery;\n if (!timerQuery) {\n return null;\n }\n const token = new _TimeToken();\n this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);\n if (caps.canUseTimestampForTimerQuery) {\n token._startTimeQuery = this._createTimeQuery();\n timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);\n }\n else {\n if (this._currentNonTimestampToken) {\n return this._currentNonTimestampToken;\n }\n token._timeElapsedQuery = this._createTimeQuery();\n if (timerQuery.beginQueryEXT) {\n timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);\n }\n else {\n this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);\n }\n this._currentNonTimestampToken = token;\n }\n return token;\n};\nEngine.prototype.endTimeQuery = function (token) {\n const caps = this.getCaps();\n const timerQuery = caps.timerQuery;\n if (!timerQuery || !token) {\n return -1;\n }\n if (caps.canUseTimestampForTimerQuery) {\n if (!token._startTimeQuery) {\n return -1;\n }\n if (!token._endTimeQuery) {\n token._endTimeQuery = this._createTimeQuery();\n timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);\n }\n }\n else if (!token._timeElapsedQueryEnded) {\n if (!token._timeElapsedQuery) {\n return -1;\n }\n if (timerQuery.endQueryEXT) {\n timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);\n }\n else {\n this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);\n this._currentNonTimestampToken = null;\n }\n token._timeElapsedQueryEnded = true;\n }\n const disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);\n let available = false;\n if (token._endTimeQuery) {\n available = this._getTimeQueryAvailability(token._endTimeQuery);\n }\n else if (token._timeElapsedQuery) {\n available = this._getTimeQueryAvailability(token._timeElapsedQuery);\n }\n if (available && !disjoint) {\n let result = 0;\n if (caps.canUseTimestampForTimerQuery) {\n if (!token._startTimeQuery || !token._endTimeQuery) {\n return -1;\n }\n const timeStart = this._getTimeQueryResult(token._startTimeQuery);\n const timeEnd = this._getTimeQueryResult(token._endTimeQuery);\n result = timeEnd - timeStart;\n this._deleteTimeQuery(token._startTimeQuery);\n this._deleteTimeQuery(token._endTimeQuery);\n token._startTimeQuery = null;\n token._endTimeQuery = null;\n }\n else {\n if (!token._timeElapsedQuery) {\n return -1;\n }\n result = this._getTimeQueryResult(token._timeElapsedQuery);\n this._deleteTimeQuery(token._timeElapsedQuery);\n token._timeElapsedQuery = null;\n token._timeElapsedQueryEnded = false;\n }\n return result;\n }\n return -1;\n};\nEngine.prototype._captureGPUFrameTime = false;\nEngine.prototype._gpuFrameTime = new PerfCounter();\nEngine.prototype.getGPUFrameTimeCounter = function () {\n return this._gpuFrameTime;\n};\nEngine.prototype.captureGPUFrameTime = function (value) {\n if (value === this._captureGPUFrameTime) {\n return;\n }\n this._captureGPUFrameTime = value;\n if (value) {\n this._onBeginFrameObserver = this.onBeginFrameObservable.add(() => {\n if (!this._gpuFrameTimeToken) {\n this._gpuFrameTimeToken = this.startTimeQuery();\n }\n });\n this._onEndFrameObserver = this.onEndFrameObservable.add(() => {\n if (!this._gpuFrameTimeToken) {\n return;\n }\n const time = this.endTimeQuery(this._gpuFrameTimeToken);\n if (time > -1) {\n this._gpuFrameTimeToken = null;\n this._gpuFrameTime.fetchNewFrame();\n this._gpuFrameTime.addCount(time, true);\n }\n });\n }\n else {\n this.onBeginFrameObservable.remove(this._onBeginFrameObserver);\n this._onBeginFrameObserver = null;\n this.onEndFrameObservable.remove(this._onEndFrameObserver);\n this._onEndFrameObserver = null;\n }\n};\nEngine.prototype._getGlAlgorithmType = function (algorithmType) {\n return algorithmType === AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;\n};\nObject.defineProperty(AbstractMesh.prototype, \"isOcclusionQueryInProgress\", {\n get: function () {\n return this._occlusionDataStorage.isOcclusionQueryInProgress;\n },\n set: function (value) {\n this._occlusionDataStorage.isOcclusionQueryInProgress = value;\n },\n enumerable: false,\n configurable: true,\n});\nObject.defineProperty(AbstractMesh.prototype, \"_occlusionDataStorage\", {\n get: function () {\n if (!this.__occlusionDataStorage) {\n this.__occlusionDataStorage = new _OcclusionDataStorage();\n }\n return this.__occlusionDataStorage;\n },\n enumerable: false,\n configurable: true,\n});\nObject.defineProperty(AbstractMesh.prototype, \"isOccluded\", {\n get: function () {\n return this._occlusionDataStorage.isOccluded;\n },\n set: function (value) {\n this._occlusionDataStorage.isOccluded = value;\n },\n enumerable: true,\n configurable: true,\n});\nObject.defineProperty(AbstractMesh.prototype, \"occlusionQueryAlgorithmType\", {\n get: function () {\n return this._occlusionDataStorage.occlusionQueryAlgorithmType;\n },\n set: function (value) {\n this._occlusionDataStorage.occlusionQueryAlgorithmType = value;\n },\n enumerable: true,\n configurable: true,\n});\nObject.defineProperty(AbstractMesh.prototype, \"occlusionType\", {\n get: function () {\n return this._occlusionDataStorage.occlusionType;\n },\n set: function (value) {\n this._occlusionDataStorage.occlusionType = value;\n },\n enumerable: true,\n configurable: true,\n});\nObject.defineProperty(AbstractMesh.prototype, \"occlusionRetryCount\", {\n get: function () {\n return this._occlusionDataStorage.occlusionRetryCount;\n },\n set: function (value) {\n this._occlusionDataStorage.occlusionRetryCount = value;\n },\n enumerable: true,\n configurable: true,\n});\nObject.defineProperty(AbstractMesh.prototype, \"forceRenderingWhenOccluded\", {\n get: function () {\n return this._occlusionDataStorage.forceRenderingWhenOccluded;\n },\n set: function (value) {\n this._occlusionDataStorage.forceRenderingWhenOccluded = value;\n },\n enumerable: true,\n configurable: true,\n});\n// We also need to update AbstractMesh as there is a portion of the code there\nAbstractMesh.prototype._checkOcclusionQuery = function () {\n const dataStorage = this._occlusionDataStorage;\n if (dataStorage.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {\n dataStorage.isOccluded = false;\n return false;\n }\n const engine = this.getEngine();\n if (!engine.getCaps().supportOcclusionQuery) {\n dataStorage.isOccluded = false;\n return false;\n }\n if (!engine.isQueryResultAvailable) {\n // Occlusion query where not referenced\n dataStorage.isOccluded = false;\n return false;\n }\n if (this.isOcclusionQueryInProgress && this._occlusionQuery) {\n const isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);\n if (isOcclusionQueryAvailable) {\n const occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);\n dataStorage.isOcclusionQueryInProgress = false;\n dataStorage.occlusionInternalRetryCounter = 0;\n dataStorage.isOccluded = occlusionQueryResult > 0 ? false : true;\n }\n else {\n dataStorage.occlusionInternalRetryCounter++;\n if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {\n dataStorage.isOcclusionQueryInProgress = false;\n dataStorage.occlusionInternalRetryCounter = 0;\n // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)\n // if strict continue the last state of the object.\n dataStorage.isOccluded = dataStorage.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;\n }\n else {\n return dataStorage.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;\n }\n }\n }\n const scene = this.getScene();\n if (scene.getBoundingBoxRenderer) {\n const occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();\n if (this._occlusionQuery === null) {\n this._occlusionQuery = engine.createQuery();\n }\n if (engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery)) {\n occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);\n engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);\n this._occlusionDataStorage.isOcclusionQueryInProgress = true;\n }\n }\n return dataStorage.isOccluded;\n};\n//# sourceMappingURL=engine.query.js.map","import { ThinEngine } from \"../../Engines/thinEngine.js\";\n\nThinEngine.prototype.updateVideoTexture = function (texture, video, invertY) {\n if (!texture || texture._isDisabled) {\n return;\n }\n const glformat = this._getInternalFormat(texture.format);\n const internalFormat = this._getRGBABufferInternalSizedFormat(0, texture.format);\n const wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);\n this._unpackFlipY(!invertY); // Video are upside down by default\n try {\n // Testing video texture support\n if (this._videoTextureSupported === undefined) {\n // clear old errors just in case.\n this._gl.getError();\n this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, glformat, this._gl.UNSIGNED_BYTE, video);\n if (this._gl.getError() !== 0) {\n this._videoTextureSupported = false;\n }\n else {\n this._videoTextureSupported = true;\n }\n }\n // Copy video through the current working canvas if video texture is not supported\n if (!this._videoTextureSupported) {\n if (!texture._workingCanvas) {\n texture._workingCanvas = this.createCanvas(texture.width, texture.height);\n const context = texture._workingCanvas.getContext(\"2d\");\n if (!context) {\n throw new Error(\"Unable to get 2d context\");\n }\n texture._workingContext = context;\n texture._workingCanvas.width = texture.width;\n texture._workingCanvas.height = texture.height;\n }\n texture._workingContext.clearRect(0, 0, texture.width, texture.height);\n texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);\n this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, glformat, this._gl.UNSIGNED_BYTE, texture._workingCanvas);\n }\n else {\n this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, glformat, this._gl.UNSIGNED_BYTE, video);\n }\n if (texture.generateMipMaps) {\n this._gl.generateMipmap(this._gl.TEXTURE_2D);\n }\n if (!wasPreviouslyBound) {\n this._bindTextureDirectly(this._gl.TEXTURE_2D, null);\n }\n // this.resetTextureCache();\n texture.isReady = true;\n }\n catch (ex) {\n // Something unexpected\n // Let's disable the texture\n texture._isDisabled = true;\n }\n};\n//# sourceMappingURL=engine.videoTexture.js.map","import { InternalTexture, InternalTextureSource } from \"../../Materials/Textures/internalTexture.js\";\nimport { Logger } from \"../../Misc/logger.js\";\n\nimport { ThinEngine } from \"../thinEngine.js\";\nThinEngine.prototype.restoreSingleAttachment = function () {\n const gl = this._gl;\n this.bindAttachments([gl.BACK]);\n};\nThinEngine.prototype.restoreSingleAttachmentForRenderTarget = function () {\n const gl = this._gl;\n this.bindAttachments([gl.COLOR_ATTACHMENT0]);\n};\nThinEngine.prototype.buildTextureLayout = function (textureStatus) {\n const gl = this._gl;\n const result = [];\n for (let i = 0; i < textureStatus.length; i++) {\n if (textureStatus[i]) {\n result.push(gl[\"COLOR_ATTACHMENT\" + i]);\n }\n else {\n result.push(gl.NONE);\n }\n }\n return result;\n};\nThinEngine.prototype.bindAttachments = function (attachments) {\n const gl = this._gl;\n gl.drawBuffers(attachments);\n};\nThinEngine.prototype.unBindMultiColorAttachmentFramebuffer = function (rtWrapper, disableGenerateMipMaps = false, onBeforeUnbind) {\n this._currentRenderTarget = null;\n // If MSAA, we need to bitblt back to main texture\n const gl = this._gl;\n const attachments = rtWrapper._attachments;\n const count = attachments.length;\n if (rtWrapper._MSAAFramebuffer) {\n gl.bindFramebuffer(gl.READ_FRAMEBUFFER, rtWrapper._MSAAFramebuffer);\n gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, rtWrapper._framebuffer);\n for (let i = 0; i < count; i++) {\n const texture = rtWrapper.textures[i];\n for (let j = 0; j < count; j++) {\n attachments[j] = gl.NONE;\n }\n attachments[i] = gl[this.webGLVersion > 1 ? \"COLOR_ATTACHMENT\" + i : \"COLOR_ATTACHMENT\" + i + \"_WEBGL\"];\n gl.readBuffer(attachments[i]);\n gl.drawBuffers(attachments);\n gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);\n }\n for (let i = 0; i < count; i++) {\n attachments[i] = gl[this.webGLVersion > 1 ? \"COLOR_ATTACHMENT\" + i : \"COLOR_ATTACHMENT\" + i + \"_WEBGL\"];\n }\n gl.drawBuffers(attachments);\n }\n for (let i = 0; i < count; i++) {\n const texture = rtWrapper.textures[i];\n if ((texture === null || texture === void 0 ? void 0 : texture.generateMipMaps) && !disableGenerateMipMaps && !texture.isCube) {\n this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);\n gl.generateMipmap(gl.TEXTURE_2D);\n this._bindTextureDirectly(gl.TEXTURE_2D, null);\n }\n }\n if (onBeforeUnbind) {\n if (rtWrapper._MSAAFramebuffer) {\n // Bind the correct framebuffer\n this._bindUnboundFramebuffer(rtWrapper._framebuffer);\n }\n onBeforeUnbind();\n }\n this._bindUnboundFramebuffer(null);\n};\nThinEngine.prototype.createMultipleRenderTarget = function (size, options, initializeBuffers = true) {\n var _a;\n let generateMipMaps = false;\n let generateDepthBuffer = true;\n let generateStencilBuffer = false;\n let generateDepthTexture = false;\n let depthTextureFormat = 15;\n let textureCount = 1;\n const defaultType = 0;\n const defaultSamplingMode = 3;\n const defaultUseSRGBBuffer = false;\n const defaultFormat = 5;\n const defaultTarget = 3553;\n let types = new Array();\n let samplingModes = new Array();\n let useSRGBBuffers = new Array();\n let formats = new Array();\n let targets = new Array();\n let faceIndex = new Array();\n let layerIndex = new Array();\n let layers = new Array();\n const rtWrapper = this._createHardwareRenderTargetWrapper(true, false, size);\n if (options !== undefined) {\n generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;\n generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;\n generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;\n generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;\n textureCount = options.textureCount || 1;\n if (options.types) {\n types = options.types;\n }\n if (options.samplingModes) {\n samplingModes = options.samplingModes;\n }\n if (options.useSRGBBuffers) {\n useSRGBBuffers = options.useSRGBBuffers;\n }\n if (options.formats) {\n formats = options.formats;\n }\n if (options.targetTypes) {\n targets = options.targetTypes;\n }\n if (options.faceIndex) {\n faceIndex = options.faceIndex;\n }\n if (options.layerIndex) {\n layerIndex = options.layerIndex;\n }\n if (options.layerCounts) {\n layers = options.layerCounts;\n }\n if (this.webGLVersion > 1 &&\n (options.depthTextureFormat === 13 ||\n options.depthTextureFormat === 17 ||\n options.depthTextureFormat === 16 ||\n options.depthTextureFormat === 14 ||\n options.depthTextureFormat === 18)) {\n depthTextureFormat = options.depthTextureFormat;\n }\n }\n const gl = this._gl;\n // Create the framebuffer\n const framebuffer = gl.createFramebuffer();\n this._bindUnboundFramebuffer(framebuffer);\n const width = size.width || size;\n const height = size.height || size;\n const textures = [];\n const attachments = [];\n const useStencilTexture = this.webGLVersion > 1 &&\n generateDepthTexture &&\n (options.depthTextureFormat === 13 ||\n options.depthTextureFormat === 17 ||\n options.depthTextureFormat === 18);\n const depthStencilBuffer = this._setupFramebufferDepthAttachments(!useStencilTexture && generateStencilBuffer, !generateDepthTexture && generateDepthBuffer, width, height);\n rtWrapper._framebuffer = framebuffer;\n rtWrapper._depthStencilBuffer = depthStencilBuffer;\n rtWrapper._generateDepthBuffer = !generateDepthTexture && generateDepthBuffer;\n rtWrapper._generateStencilBuffer = !useStencilTexture && generateStencilBuffer;\n rtWrapper._attachments = attachments;\n for (let i = 0; i < textureCount; i++) {\n let samplingMode = samplingModes[i] || defaultSamplingMode;\n let type = types[i] || defaultType;\n let useSRGBBuffer = useSRGBBuffers[i] || defaultUseSRGBBuffer;\n const format = formats[i] || defaultFormat;\n const target = targets[i] || defaultTarget;\n const layerCount = (_a = layers[i]) !== null && _a !== void 0 ? _a : 1;\n if (type === 1 && !this._caps.textureFloatLinearFiltering) {\n // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE\n samplingMode = 1;\n }\n else if (type === 2 && !this._caps.textureHalfFloatLinearFiltering) {\n // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE\n samplingMode = 1;\n }\n const filters = this._getSamplingParameters(samplingMode, generateMipMaps);\n if (type === 1 && !this._caps.textureFloat) {\n type = 0;\n Logger.Warn(\"Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type\");\n }\n useSRGBBuffer = useSRGBBuffer && this._caps.supportSRGBBuffers && (this.webGLVersion > 1 || this.isWebGPU);\n const isWebGL2 = this.webGLVersion > 1;\n const attachment = gl[isWebGL2 ? \"COLOR_ATTACHMENT\" + i : \"COLOR_ATTACHMENT\" + i + \"_WEBGL\"];\n attachments.push(attachment);\n if (target === -1) {\n continue;\n }\n const texture = new InternalTexture(this, InternalTextureSource.MultiRenderTarget);\n textures[i] = texture;\n gl.activeTexture(gl[\"TEXTURE\" + i]);\n gl.bindTexture(target, texture._hardwareTexture.underlyingResource);\n gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, filters.mag);\n gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, filters.min);\n gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n const internalSizedFormat = this._getRGBABufferInternalSizedFormat(type, format, useSRGBBuffer);\n const internalFormat = this._getInternalFormat(format);\n const webGLTextureType = this._getWebGLTextureType(type);\n if (isWebGL2 && (target === 35866 || target === 32879)) {\n if (target === 35866) {\n texture.is2DArray = true;\n }\n else {\n texture.is3D = true;\n }\n texture.baseDepth = texture.depth = layerCount;\n gl.texImage3D(target, 0, internalSizedFormat, width, height, layerCount, 0, internalFormat, webGLTextureType, null);\n }\n else if (target === 34067) {\n // We have to generate all faces to complete the framebuffer\n for (let i = 0; i < 6; i++) {\n gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, internalSizedFormat, width, height, 0, internalFormat, webGLTextureType, null);\n }\n texture.isCube = true;\n }\n else {\n gl.texImage2D(gl.TEXTURE_2D, 0, internalSizedFormat, width, height, 0, internalFormat, webGLTextureType, null);\n }\n if (generateMipMaps) {\n gl.generateMipmap(target);\n }\n // Unbind\n this._bindTextureDirectly(target, null);\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = width;\n texture.height = height;\n texture.isReady = true;\n texture.samples = 1;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.type = type;\n texture._useSRGBBuffer = useSRGBBuffer;\n texture.format = format;\n this._internalTexturesCache.push(texture);\n }\n if (generateDepthTexture && this._caps.depthTextureExtension) {\n // Depth texture\n const depthTexture = new InternalTexture(this, InternalTextureSource.Depth);\n let depthTextureType = 5;\n let glDepthTextureInternalFormat = gl.DEPTH_COMPONENT16;\n let glDepthTextureFormat = gl.DEPTH_COMPONENT;\n let glDepthTextureType = gl.UNSIGNED_SHORT;\n let glDepthTextureAttachment = gl.DEPTH_ATTACHMENT;\n if (this.webGLVersion < 2) {\n glDepthTextureInternalFormat = gl.DEPTH_COMPONENT;\n }\n else {\n if (depthTextureFormat === 14) {\n depthTextureType = 1;\n glDepthTextureType = gl.FLOAT;\n glDepthTextureInternalFormat = gl.DEPTH_COMPONENT32F;\n }\n else if (depthTextureFormat === 18) {\n depthTextureType = 0;\n glDepthTextureType = gl.FLOAT_32_UNSIGNED_INT_24_8_REV;\n glDepthTextureInternalFormat = gl.DEPTH32F_STENCIL8;\n glDepthTextureFormat = gl.DEPTH_STENCIL;\n glDepthTextureAttachment = gl.DEPTH_STENCIL_ATTACHMENT;\n }\n else if (depthTextureFormat === 16) {\n depthTextureType = 0;\n glDepthTextureType = gl.UNSIGNED_INT;\n glDepthTextureInternalFormat = gl.DEPTH_COMPONENT24;\n glDepthTextureAttachment = gl.DEPTH_ATTACHMENT;\n }\n else if (depthTextureFormat === 13 || depthTextureFormat === 17) {\n depthTextureType = 12;\n glDepthTextureType = gl.UNSIGNED_INT_24_8;\n glDepthTextureInternalFormat = gl.DEPTH24_STENCIL8;\n glDepthTextureFormat = gl.DEPTH_STENCIL;\n glDepthTextureAttachment = gl.DEPTH_STENCIL_ATTACHMENT;\n }\n }\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, depthTexture._hardwareTexture.underlyingResource);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texImage2D(gl.TEXTURE_2D, 0, glDepthTextureInternalFormat, width, height, 0, glDepthTextureFormat, glDepthTextureType, null);\n gl.framebufferTexture2D(gl.FRAMEBUFFER, glDepthTextureAttachment, gl.TEXTURE_2D, depthTexture._hardwareTexture.underlyingResource, 0);\n depthTexture.baseWidth = width;\n depthTexture.baseHeight = height;\n depthTexture.width = width;\n depthTexture.height = height;\n depthTexture.isReady = true;\n depthTexture.samples = 1;\n depthTexture.generateMipMaps = generateMipMaps;\n depthTexture.samplingMode = 1;\n depthTexture.format = depthTextureFormat;\n depthTexture.type = depthTextureType;\n textures[textureCount] = depthTexture;\n this._internalTexturesCache.push(depthTexture);\n }\n rtWrapper.setTextures(textures);\n if (initializeBuffers) {\n gl.drawBuffers(attachments);\n }\n this._bindUnboundFramebuffer(null);\n rtWrapper.setLayerAndFaceIndices(layerIndex, faceIndex);\n this.resetTextureCache();\n return rtWrapper;\n};\nThinEngine.prototype.updateMultipleRenderTargetTextureSampleCount = function (rtWrapper, samples, initializeBuffers = true) {\n if (this.webGLVersion < 2 || !rtWrapper || !rtWrapper.texture) {\n return 1;\n }\n if (rtWrapper.samples === samples) {\n return samples;\n }\n const count = rtWrapper._attachments.length;\n if (count === 0) {\n return 1;\n }\n const gl = this._gl;\n samples = Math.min(samples, this.getCaps().maxMSAASamples);\n // Dispose previous render buffers\n const useDepthStencil = !!rtWrapper._depthStencilBuffer;\n if (useDepthStencil) {\n gl.deleteRenderbuffer(rtWrapper._depthStencilBuffer);\n rtWrapper._depthStencilBuffer = null;\n }\n if (rtWrapper._MSAAFramebuffer) {\n gl.deleteFramebuffer(rtWrapper._MSAAFramebuffer);\n rtWrapper._MSAAFramebuffer = null;\n }\n if (samples > 1 && typeof gl.renderbufferStorageMultisample === \"function\") {\n const framebuffer = gl.createFramebuffer();\n if (!framebuffer) {\n throw new Error(\"Unable to create multi sampled framebuffer\");\n }\n rtWrapper._MSAAFramebuffer = framebuffer;\n this._bindUnboundFramebuffer(framebuffer);\n const attachments = [];\n for (let i = 0; i < count; i++) {\n const texture = rtWrapper.textures[i];\n const hardwareTexture = texture._hardwareTexture;\n hardwareTexture.releaseMSAARenderBuffers();\n }\n for (let i = 0; i < count; i++) {\n const texture = rtWrapper.textures[i];\n const hardwareTexture = texture._hardwareTexture;\n const attachment = gl[this.webGLVersion > 1 ? \"COLOR_ATTACHMENT\" + i : \"COLOR_ATTACHMENT\" + i + \"_WEBGL\"];\n const colorRenderbuffer = this._createRenderBuffer(texture.width, texture.height, samples, -1 /* not used */, this._getRGBAMultiSampleBufferFormat(texture.type, texture.format), attachment);\n if (!colorRenderbuffer) {\n throw new Error(\"Unable to create multi sampled framebuffer\");\n }\n hardwareTexture.addMSAARenderBuffer(colorRenderbuffer);\n texture.samples = samples;\n attachments.push(attachment);\n }\n if (initializeBuffers) {\n gl.drawBuffers(attachments);\n }\n }\n else {\n this._bindUnboundFramebuffer(rtWrapper._framebuffer);\n }\n if (useDepthStencil) {\n rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(rtWrapper._generateStencilBuffer, rtWrapper._generateDepthBuffer, rtWrapper.texture.width, rtWrapper.texture.height, samples);\n }\n this._bindUnboundFramebuffer(null);\n return samples;\n};\n//# sourceMappingURL=engine.multiRender.js.map","import { ThinEngine } from \"../../Engines/thinEngine.js\";\nimport { InternalTexture, InternalTextureSource } from \"../../Materials/Textures/internalTexture.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { LoadImage } from \"../../Misc/fileTools.js\";\nimport { RandomGUID } from \"../../Misc/guid.js\";\n\nThinEngine.prototype._createDepthStencilCubeTexture = function (size, options, rtWrapper) {\n const internalTexture = new InternalTexture(this, InternalTextureSource.DepthStencil);\n internalTexture.isCube = true;\n if (this.webGLVersion === 1) {\n Logger.Error(\"Depth cube texture is not supported by WebGL 1.\");\n return internalTexture;\n }\n const internalOptions = Object.assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);\n const gl = this._gl;\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);\n this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);\n rtWrapper._depthStencilTexture = internalTexture;\n rtWrapper._depthStencilTextureWithStencil = internalOptions.generateStencil;\n // Create the depth/stencil buffer\n for (let face = 0; face < 6; face++) {\n if (internalOptions.generateStencil) {\n gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);\n }\n else {\n gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);\n }\n }\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n this._internalTexturesCache.push(internalTexture);\n return internalTexture;\n};\nThinEngine.prototype._partialLoadFile = function (url, index, loadedFiles, onfinish, onErrorCallBack = null) {\n const onload = (data) => {\n loadedFiles[index] = data;\n loadedFiles._internalCount++;\n if (loadedFiles._internalCount === 6) {\n onfinish(loadedFiles);\n }\n };\n const onerror = (request, exception) => {\n if (onErrorCallBack && request) {\n onErrorCallBack(request.status + \" \" + request.statusText, exception);\n }\n };\n this._loadFile(url, onload, undefined, undefined, true, onerror);\n};\nThinEngine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError = null) {\n const loadedFiles = [];\n loadedFiles._internalCount = 0;\n for (let index = 0; index < 6; index++) {\n this._partialLoadFile(files[index], index, loadedFiles, onfinish, onError);\n }\n};\nThinEngine.prototype._cascadeLoadImgs = function (scene, texture, onfinish, files, onError = null, mimeType) {\n const loadedImages = [];\n loadedImages._internalCount = 0;\n for (let index = 0; index < 6; index++) {\n this._partialLoadImg(files[index], index, loadedImages, scene, texture, onfinish, onError, mimeType);\n }\n};\nThinEngine.prototype._partialLoadImg = function (url, index, loadedImages, scene, texture, onfinish, onErrorCallBack = null, mimeType) {\n const tokenPendingData = RandomGUID();\n const onload = (img) => {\n loadedImages[index] = img;\n loadedImages._internalCount++;\n if (scene) {\n scene.removePendingData(tokenPendingData);\n }\n if (loadedImages._internalCount === 6 && onfinish) {\n onfinish(texture, loadedImages);\n }\n };\n const onerror = (message, exception) => {\n if (scene) {\n scene.removePendingData(tokenPendingData);\n }\n if (onErrorCallBack) {\n onErrorCallBack(message, exception);\n }\n };\n LoadImage(url, onload, onerror, scene ? scene.offlineProvider : null, mimeType);\n if (scene) {\n scene.addPendingData(tokenPendingData);\n }\n};\nThinEngine.prototype._setCubeMapTextureParams = function (texture, loadMipmap, maxLevel) {\n const gl = this._gl;\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n texture.samplingMode = loadMipmap ? 3 : 2;\n if (loadMipmap && this.getCaps().textureMaxLevel && maxLevel !== undefined && maxLevel > 0) {\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAX_LEVEL, maxLevel);\n texture._maxLodLevel = maxLevel;\n }\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n};\nThinEngine.prototype.createCubeTextureBase = function (rootUrl, scene, files, noMipmap, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = false, lodScale = 0, lodOffset = 0, fallback = null, beforeLoadCubeDataCallback = null, imageHandler = null, useSRGBBuffer = false) {\n const texture = fallback ? fallback : new InternalTexture(this, InternalTextureSource.Cube);\n texture.isCube = true;\n texture.url = rootUrl;\n texture.generateMipMaps = !noMipmap;\n texture._lodGenerationScale = lodScale;\n texture._lodGenerationOffset = lodOffset;\n texture._useSRGBBuffer = !!useSRGBBuffer && this._caps.supportSRGBBuffers && (this.webGLVersion > 1 || this.isWebGPU || !!noMipmap);\n if (texture !== fallback) {\n texture.label = rootUrl.substring(0, 60); // default label, can be overriden by the caller\n }\n if (!this._doNotHandleContextLost) {\n texture._extension = forcedExtension;\n texture._files = files;\n }\n const originalRootUrl = rootUrl;\n if (this._transformTextureUrl && !fallback) {\n rootUrl = this._transformTextureUrl(rootUrl);\n }\n const rootUrlWithoutUriParams = rootUrl.split(\"?\")[0];\n const lastDot = rootUrlWithoutUriParams.lastIndexOf(\".\");\n const extension = forcedExtension ? forcedExtension : lastDot > -1 ? rootUrlWithoutUriParams.substring(lastDot).toLowerCase() : \"\";\n let loader = null;\n for (const availableLoader of ThinEngine._TextureLoaders) {\n if (availableLoader.canLoad(extension)) {\n loader = availableLoader;\n break;\n }\n }\n const onInternalError = (request, exception) => {\n if (rootUrl === originalRootUrl) {\n if (onError && request) {\n onError(request.status + \" \" + request.statusText, exception);\n }\n }\n else {\n // fall back to the original url if the transformed url fails to load\n Logger.Warn(`Failed to load ${rootUrl}, falling back to the ${originalRootUrl}`);\n this.createCubeTextureBase(originalRootUrl, scene, files, !!noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, texture, beforeLoadCubeDataCallback, imageHandler, useSRGBBuffer);\n }\n };\n if (loader) {\n const onloaddata = (data) => {\n if (beforeLoadCubeDataCallback) {\n beforeLoadCubeDataCallback(texture, data);\n }\n loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);\n };\n if (files && files.length === 6) {\n if (loader.supportCascades) {\n this._cascadeLoadFiles(scene, (images) => onloaddata(images.map((image) => new Uint8Array(image))), files, onError);\n }\n else {\n if (onError) {\n onError(\"Textures type does not support cascades.\");\n }\n else {\n Logger.Warn(\"Texture loader does not support cascades.\");\n }\n }\n }\n else {\n this._loadFile(rootUrl, (data) => onloaddata(new Uint8Array(data)), undefined, undefined, true, onInternalError);\n }\n }\n else {\n if (!files) {\n throw new Error(\"Cannot load cubemap because files were not defined\");\n }\n this._cascadeLoadImgs(scene, texture, (texture, imgs) => {\n if (imageHandler) {\n imageHandler(texture, imgs);\n }\n }, files, onError);\n }\n this._internalTexturesCache.push(texture);\n return texture;\n};\nThinEngine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = false, lodScale = 0, lodOffset = 0, fallback = null, loaderOptions, useSRGBBuffer = false) {\n const gl = this._gl;\n return this.createCubeTextureBase(rootUrl, scene, files, !!noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback, (texture) => this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true), (texture, imgs) => {\n const width = this.needPOTTextures ? ThinEngine.GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize) : imgs[0].width;\n const height = width;\n const faces = [\n gl.TEXTURE_CUBE_MAP_POSITIVE_X,\n gl.TEXTURE_CUBE_MAP_POSITIVE_Y,\n gl.TEXTURE_CUBE_MAP_POSITIVE_Z,\n gl.TEXTURE_CUBE_MAP_NEGATIVE_X,\n gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,\n gl.TEXTURE_CUBE_MAP_NEGATIVE_Z,\n ];\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);\n this._unpackFlipY(false);\n const internalFormat = format ? this._getInternalFormat(format, texture._useSRGBBuffer) : texture._useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8_ALPHA8 : gl.RGBA;\n let texelFormat = format ? this._getInternalFormat(format) : gl.RGBA;\n if (texture._useSRGBBuffer && this.webGLVersion === 1) {\n texelFormat = internalFormat;\n }\n for (let index = 0; index < faces.length; index++) {\n if (imgs[index].width !== width || imgs[index].height !== height) {\n this._prepareWorkingCanvas();\n if (!this._workingCanvas || !this._workingContext) {\n Logger.Warn(\"Cannot create canvas to resize texture.\");\n return;\n }\n this._workingCanvas.width = width;\n this._workingCanvas.height = height;\n this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);\n gl.texImage2D(faces[index], 0, internalFormat, texelFormat, gl.UNSIGNED_BYTE, this._workingCanvas);\n }\n else {\n gl.texImage2D(faces[index], 0, internalFormat, texelFormat, gl.UNSIGNED_BYTE, imgs[index]);\n }\n }\n if (!noMipmap) {\n gl.generateMipmap(gl.TEXTURE_CUBE_MAP);\n }\n this._setCubeMapTextureParams(texture, !noMipmap);\n texture.width = width;\n texture.height = height;\n texture.isReady = true;\n if (format) {\n texture.format = format;\n }\n texture.onLoadedObservable.notifyObservers(texture);\n texture.onLoadedObservable.clear();\n if (onLoad) {\n onLoad();\n }\n }, !!useSRGBBuffer);\n};\n//# sourceMappingURL=engine.cubeTexture.js.map","import { ThinEngine } from \"../../Engines/thinEngine.js\";\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nThinEngine.prototype.setTextureSampler = function (name, sampler) {\n throw new Error(\"setTextureSampler: This engine does not support separate texture sampler objects!\");\n};\n//# sourceMappingURL=engine.textureSampler.js.map","import { Engine } from \"../engine.js\";\nimport { Observable } from \"../../Misc/observable.js\";\n/**\n * Class used to define an additional view for the engine\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/multiCanvas\n */\nexport class EngineView {\n}\nconst _onBeforeViewRenderObservable = new Observable();\nconst _onAfterViewRenderObservable = new Observable();\nObject.defineProperty(Engine.prototype, \"onBeforeViewRenderObservable\", {\n get: function () {\n return _onBeforeViewRenderObservable;\n },\n});\nObject.defineProperty(Engine.prototype, \"onAfterViewRenderObservable\", {\n get: function () {\n return _onAfterViewRenderObservable;\n },\n});\nObject.defineProperty(Engine.prototype, \"inputElement\", {\n get: function () {\n return this._inputElement;\n },\n set: function (value) {\n var _a;\n if (this._inputElement !== value) {\n this._inputElement = value;\n (_a = this._onEngineViewChanged) === null || _a === void 0 ? void 0 : _a.call(this);\n }\n },\n});\nEngine.prototype.getInputElement = function () {\n return this.inputElement || this.getRenderingCanvas();\n};\nEngine.prototype.registerView = function (canvas, camera, clearBeforeCopy) {\n if (!this.views) {\n this.views = [];\n }\n for (const view of this.views) {\n if (view.target === canvas) {\n return view;\n }\n }\n const masterCanvas = this.getRenderingCanvas();\n if (masterCanvas) {\n canvas.width = masterCanvas.width;\n canvas.height = masterCanvas.height;\n }\n const newView = { target: canvas, camera, clearBeforeCopy, enabled: true, id: (Math.random() * 100000).toFixed() };\n this.views.push(newView);\n if (camera) {\n camera.onDisposeObservable.add(() => {\n this.unRegisterView(canvas);\n });\n }\n return newView;\n};\nEngine.prototype.unRegisterView = function (canvas) {\n if (!this.views || this.views.length === 0) {\n return this;\n }\n for (const view of this.views) {\n if (view.target === canvas) {\n const index = this.views.indexOf(view);\n if (index !== -1) {\n this.views.splice(index, 1);\n }\n break;\n }\n }\n return this;\n};\nEngine.prototype._renderViewStep = function (view) {\n const canvas = view.target;\n const context = canvas.getContext(\"2d\");\n if (!context) {\n return true;\n }\n const parent = this.getRenderingCanvas();\n _onBeforeViewRenderObservable.notifyObservers(view);\n const camera = view.camera;\n let previewCamera = null;\n let scene = null;\n if (camera) {\n scene = camera.getScene();\n if (!scene || (scene.activeCameras && scene.activeCameras.length)) {\n return true;\n }\n this.activeView = view;\n previewCamera = scene.activeCamera;\n scene.activeCamera = camera;\n }\n if (view.customResize) {\n view.customResize(canvas);\n }\n else {\n // Set sizes\n const width = Math.floor(canvas.clientWidth / this._hardwareScalingLevel);\n const height = Math.floor(canvas.clientHeight / this._hardwareScalingLevel);\n const dimsChanged = width !== canvas.width || parent.width !== canvas.width || height !== canvas.height || parent.height !== canvas.height;\n if (canvas.clientWidth && canvas.clientHeight && dimsChanged) {\n canvas.width = width;\n canvas.height = height;\n this.setSize(width, height);\n }\n }\n if (!parent.width || !parent.height) {\n return false;\n }\n // Render the frame\n this._renderFrame();\n this.flushFramebuffer();\n // Copy to target\n if (view.clearBeforeCopy) {\n context.clearRect(0, 0, parent.width, parent.height);\n }\n context.drawImage(parent, 0, 0);\n // Restore\n if (previewCamera && scene) {\n scene.activeCamera = previewCamera;\n }\n _onAfterViewRenderObservable.notifyObservers(view);\n return true;\n};\nEngine.prototype._renderViews = function () {\n if (!this.views || this.views.length === 0) {\n return false;\n }\n const parent = this.getRenderingCanvas();\n if (!parent) {\n return false;\n }\n let inputElementView;\n for (const view of this.views) {\n if (!view.enabled) {\n continue;\n }\n const canvas = view.target;\n // Always render the view correspondent to the inputElement for last\n if (canvas === this.inputElement) {\n inputElementView = view;\n continue;\n }\n if (!this._renderViewStep(view)) {\n return false;\n }\n }\n if (inputElementView) {\n if (!this._renderViewStep(inputElementView)) {\n return false;\n }\n }\n this.activeView = null;\n return true;\n};\n//# sourceMappingURL=engine.views.js.map","\nimport { PostProcess } from \"../PostProcesses/postProcess.js\";\nimport \"../Shaders/rgbdDecode.fragment.js\";\nimport \"../Engines/Extensions/engine.renderTarget.js\";\nimport { ApplyPostProcess } from \"./textureTools.js\";\n/**\n * Class used to host RGBD texture specific utilities\n */\nexport class RGBDTextureTools {\n /**\n * Expand the RGBD Texture from RGBD to Half Float if possible.\n * @param texture the texture to expand.\n */\n static ExpandRGBDTexture(texture) {\n const internalTexture = texture._texture;\n if (!internalTexture || !texture.isRGBD) {\n return;\n }\n // Gets everything ready.\n const engine = internalTexture.getEngine();\n const caps = engine.getCaps();\n const isReady = internalTexture.isReady;\n let expandTexture = false;\n // If half float available we can uncompress the texture\n if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {\n expandTexture = true;\n internalTexture.type = 2;\n }\n // If full float available we can uncompress the texture\n else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {\n expandTexture = true;\n internalTexture.type = 1;\n }\n if (expandTexture) {\n // Do not use during decode.\n internalTexture.isReady = false;\n internalTexture._isRGBD = false;\n internalTexture.invertY = false;\n }\n const expandRGBDTexture = () => {\n // Expand the texture if possible\n if (expandTexture) {\n // Simply run through the decode PP.\n const rgbdPostProcess = new PostProcess(\"rgbdDecode\", \"rgbdDecode\", null, null, 1, null, 3, engine, false, undefined, internalTexture.type, undefined, null, false);\n rgbdPostProcess.externalTextureSamplerBinding = true;\n // Hold the output of the decoding.\n const expandedTexture = engine.createRenderTargetTexture(internalTexture.width, {\n generateDepthBuffer: false,\n generateMipMaps: false,\n generateStencilBuffer: false,\n samplingMode: internalTexture.samplingMode,\n type: internalTexture.type,\n format: 5,\n });\n rgbdPostProcess.getEffect().executeWhenCompiled(() => {\n // PP Render Pass\n rgbdPostProcess.onApply = (effect) => {\n effect._bindTexture(\"textureSampler\", internalTexture);\n effect.setFloat2(\"scale\", 1, 1);\n };\n texture.getScene().postProcessManager.directRender([rgbdPostProcess], expandedTexture, true);\n // Cleanup\n engine.restoreDefaultFramebuffer();\n engine._releaseTexture(internalTexture);\n if (rgbdPostProcess) {\n rgbdPostProcess.dispose();\n }\n // Internal Swap\n expandedTexture._swapAndDie(internalTexture);\n // Ready to get rolling again.\n internalTexture.isReady = true;\n });\n }\n };\n if (isReady) {\n expandRGBDTexture();\n }\n else {\n texture.onLoadObservable.addOnce(expandRGBDTexture);\n }\n }\n /**\n * Encode the texture to RGBD if possible.\n * @param internalTexture the texture to encode\n * @param scene the scene hosting the texture\n * @param outputTextureType type of the texture in which the encoding is performed\n * @returns a promise with the internalTexture having its texture replaced by the result of the processing\n */\n static EncodeTextureToRGBD(internalTexture, scene, outputTextureType = 0) {\n return ApplyPostProcess(\"rgbdEncode\", internalTexture, scene, outputTextureType, 1, 5);\n }\n}\n//# sourceMappingURL=rgbdTextureTools.js.map","import { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Scalar } from \"../../Maths/math.scalar.js\";\nimport { SphericalPolynomial, SphericalHarmonics } from \"../../Maths/sphericalPolynomial.js\";\n\nimport { ToLinearSpace } from \"../../Maths/math.constants.js\";\nimport { Color3 } from \"../../Maths/math.color.js\";\nclass FileFaceOrientation {\n constructor(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {\n this.name = name;\n this.worldAxisForNormal = worldAxisForNormal;\n this.worldAxisForFileX = worldAxisForFileX;\n this.worldAxisForFileY = worldAxisForFileY;\n }\n}\n/**\n * Helper class dealing with the extraction of spherical polynomial dataArray\n * from a cube map.\n */\nexport class CubeMapToSphericalPolynomialTools {\n /**\n * Converts a texture to the according Spherical Polynomial data.\n * This extracts the first 3 orders only as they are the only one used in the lighting.\n *\n * @param texture The texture to extract the information from.\n * @returns The Spherical Polynomial data.\n */\n static ConvertCubeMapTextureToSphericalPolynomial(texture) {\n var _a;\n if (!texture.isCube) {\n // Only supports cube Textures currently.\n return null;\n }\n (_a = texture.getScene()) === null || _a === void 0 ? void 0 : _a.getEngine().flushFramebuffer();\n const size = texture.getSize().width;\n const rightPromise = texture.readPixels(0, undefined, undefined, false);\n const leftPromise = texture.readPixels(1, undefined, undefined, false);\n let upPromise;\n let downPromise;\n if (texture.isRenderTarget) {\n upPromise = texture.readPixels(3, undefined, undefined, false);\n downPromise = texture.readPixels(2, undefined, undefined, false);\n }\n else {\n upPromise = texture.readPixels(2, undefined, undefined, false);\n downPromise = texture.readPixels(3, undefined, undefined, false);\n }\n const frontPromise = texture.readPixels(4, undefined, undefined, false);\n const backPromise = texture.readPixels(5, undefined, undefined, false);\n const gammaSpace = texture.gammaSpace;\n // Always read as RGBA.\n const format = 5;\n let type = 0;\n if (texture.textureType == 1 || texture.textureType == 2) {\n type = 1;\n }\n return new Promise((resolve) => {\n Promise.all([leftPromise, rightPromise, upPromise, downPromise, frontPromise, backPromise]).then(([left, right, up, down, front, back]) => {\n const cubeInfo = {\n size,\n right,\n left,\n up,\n down,\n front,\n back,\n format,\n type,\n gammaSpace,\n };\n resolve(this.ConvertCubeMapToSphericalPolynomial(cubeInfo));\n });\n });\n }\n /**\n * Compute the area on the unit sphere of the rectangle defined by (x,y) and the origin\n * See https://www.rorydriscoll.com/2012/01/15/cubemap-texel-solid-angle/\n * @param x\n * @param y\n */\n static _AreaElement(x, y) {\n return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));\n }\n /**\n * Converts a cubemap to the according Spherical Polynomial data.\n * This extracts the first 3 orders only as they are the only one used in the lighting.\n *\n * @param cubeInfo The Cube map to extract the information from.\n * @returns The Spherical Polynomial data.\n */\n static ConvertCubeMapToSphericalPolynomial(cubeInfo) {\n const sphericalHarmonics = new SphericalHarmonics();\n let totalSolidAngle = 0.0;\n // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.\n const du = 2.0 / cubeInfo.size;\n const dv = du;\n const halfTexel = 0.5 * du;\n // The (u,v) of the first texel is half a texel from the corner (-1,-1).\n const minUV = halfTexel - 1.0;\n for (let faceIndex = 0; faceIndex < 6; faceIndex++) {\n const fileFace = this._FileFaces[faceIndex];\n const dataArray = cubeInfo[fileFace.name];\n let v = minUV;\n // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).\n // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.\n // Because SP is still linear, so summation is fine in that basis.\n const stride = cubeInfo.format === 5 ? 4 : 3;\n for (let y = 0; y < cubeInfo.size; y++) {\n let u = minUV;\n for (let x = 0; x < cubeInfo.size; x++) {\n // World direction (not normalised)\n const worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);\n worldDirection.normalize();\n const deltaSolidAngle = this._AreaElement(u - halfTexel, v - halfTexel) -\n this._AreaElement(u - halfTexel, v + halfTexel) -\n this._AreaElement(u + halfTexel, v - halfTexel) +\n this._AreaElement(u + halfTexel, v + halfTexel);\n let r = dataArray[y * cubeInfo.size * stride + x * stride + 0];\n let g = dataArray[y * cubeInfo.size * stride + x * stride + 1];\n let b = dataArray[y * cubeInfo.size * stride + x * stride + 2];\n // Prevent NaN harmonics with extreme HDRI data.\n if (isNaN(r)) {\n r = 0;\n }\n if (isNaN(g)) {\n g = 0;\n }\n if (isNaN(b)) {\n b = 0;\n }\n // Handle Integer types.\n if (cubeInfo.type === 0) {\n r /= 255;\n g /= 255;\n b /= 255;\n }\n // Handle Gamma space textures.\n if (cubeInfo.gammaSpace) {\n r = Math.pow(Scalar.Clamp(r), ToLinearSpace);\n g = Math.pow(Scalar.Clamp(g), ToLinearSpace);\n b = Math.pow(Scalar.Clamp(b), ToLinearSpace);\n }\n // Prevent to explode in case of really high dynamic ranges.\n // sh 3 would not be enough to accurately represent it.\n const max = this.MAX_HDRI_VALUE;\n if (this.PRESERVE_CLAMPED_COLORS) {\n const currentMax = Math.max(r, g, b);\n if (currentMax > max) {\n const factor = max / currentMax;\n r *= factor;\n g *= factor;\n b *= factor;\n }\n }\n else {\n r = Scalar.Clamp(r, 0, max);\n g = Scalar.Clamp(g, 0, max);\n b = Scalar.Clamp(b, 0, max);\n }\n const color = new Color3(r, g, b);\n sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);\n totalSolidAngle += deltaSolidAngle;\n u += du;\n }\n v += dv;\n }\n }\n // Solid angle for entire sphere is 4*pi\n const sphereSolidAngle = 4.0 * Math.PI;\n // Adjust the solid angle to allow for how many faces we processed.\n const facesProcessed = 6.0;\n const expectedSolidAngle = (sphereSolidAngle * facesProcessed) / 6.0;\n // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.\n // This is needed because the numerical integration over the cube uses a\n // small angle approximation of solid angle for each texel (see deltaSolidAngle),\n // and also to compensate for accumulative error due to float precision in the summation.\n const correctionFactor = expectedSolidAngle / totalSolidAngle;\n sphericalHarmonics.scaleInPlace(correctionFactor);\n sphericalHarmonics.convertIncidentRadianceToIrradiance();\n sphericalHarmonics.convertIrradianceToLambertianRadiance();\n return SphericalPolynomial.FromHarmonics(sphericalHarmonics);\n }\n}\nCubeMapToSphericalPolynomialTools._FileFaces = [\n new FileFaceOrientation(\"right\", new Vector3(1, 0, 0), new Vector3(0, 0, -1), new Vector3(0, -1, 0)),\n new FileFaceOrientation(\"left\", new Vector3(-1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, -1, 0)),\n new FileFaceOrientation(\"up\", new Vector3(0, 1, 0), new Vector3(1, 0, 0), new Vector3(0, 0, 1)),\n new FileFaceOrientation(\"down\", new Vector3(0, -1, 0), new Vector3(1, 0, 0), new Vector3(0, 0, -1)),\n new FileFaceOrientation(\"front\", new Vector3(0, 0, 1), new Vector3(1, 0, 0), new Vector3(0, -1, 0)),\n new FileFaceOrientation(\"back\", new Vector3(0, 0, -1), new Vector3(-1, 0, 0), new Vector3(0, -1, 0)), // -Z bottom\n];\n/** @internal */\nCubeMapToSphericalPolynomialTools.MAX_HDRI_VALUE = 4096;\n/** @internal */\nCubeMapToSphericalPolynomialTools.PRESERVE_CLAMPED_COLORS = false;\n//# sourceMappingURL=cubemapToSphericalPolynomial.js.map","import { CubeMapToSphericalPolynomialTools } from \"../../Misc/HighDynamicRange/cubemapToSphericalPolynomial.js\";\nimport { BaseTexture } from \"./baseTexture.js\";\nBaseTexture.prototype.forceSphericalPolynomialsRecompute = function () {\n if (this._texture) {\n this._texture._sphericalPolynomial = null;\n this._texture._sphericalPolynomialPromise = null;\n this._texture._sphericalPolynomialComputed = false;\n }\n};\nObject.defineProperty(BaseTexture.prototype, \"sphericalPolynomial\", {\n get: function () {\n if (this._texture) {\n if (this._texture._sphericalPolynomial || this._texture._sphericalPolynomialComputed) {\n return this._texture._sphericalPolynomial;\n }\n if (this._texture.isReady) {\n if (!this._texture._sphericalPolynomialPromise) {\n this._texture._sphericalPolynomialPromise = CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);\n if (this._texture._sphericalPolynomialPromise === null) {\n this._texture._sphericalPolynomialComputed = true;\n }\n else {\n this._texture._sphericalPolynomialPromise.then((sphericalPolynomial) => {\n this._texture._sphericalPolynomial = sphericalPolynomial;\n this._texture._sphericalPolynomialComputed = true;\n });\n }\n }\n return null;\n }\n }\n return null;\n },\n set: function (value) {\n if (this._texture) {\n this._texture._sphericalPolynomial = value;\n }\n },\n enumerable: true,\n configurable: true,\n});\n//# sourceMappingURL=baseTexture.polynomial.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/helperFunctions.js\";\nconst name = \"rgbdEncodePixelShader\";\nconst shader = `varying vec2 vUV;\runiform sampler2D textureSampler;\r#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \r{\rgl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const rgbdEncodePixelShader = { name, shader };\n//# sourceMappingURL=rgbdEncode.fragment.js.map","import { Tools } from \"./tools.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Scalar } from \"../Maths/math.scalar.js\";\nimport { SphericalPolynomial } from \"../Maths/sphericalPolynomial.js\";\nimport { InternalTexture, InternalTextureSource } from \"../Materials/Textures/internalTexture.js\";\nimport { BaseTexture } from \"../Materials/Textures/baseTexture.js\";\n\nimport { Scene } from \"../scene.js\";\nimport { PostProcess } from \"../PostProcesses/postProcess.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { RGBDTextureTools } from \"./rgbdTextureTools.js\";\nimport \"../Engines/Extensions/engine.renderTargetCube.js\";\nimport \"../Engines/Extensions/engine.readTexture.js\";\nimport \"../Materials/Textures/baseTexture.polynomial.js\";\nimport \"../Shaders/rgbdEncode.fragment.js\";\nimport \"../Shaders/rgbdDecode.fragment.js\";\nimport { DumpTools } from \"../Misc/dumpTools.js\";\nconst DefaultEnvironmentTextureImageType = \"image/png\";\nconst CurrentVersion = 2;\n/**\n * Magic number identifying the env file.\n */\nconst MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];\n/**\n * Gets the environment info from an env file.\n * @param data The array buffer containing the .env bytes.\n * @returns the environment file info (the json header) if successfully parsed, normalized to the latest supported version.\n */\nexport function GetEnvInfo(data) {\n const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);\n let pos = 0;\n for (let i = 0; i < MagicBytes.length; i++) {\n if (dataView.getUint8(pos++) !== MagicBytes[i]) {\n Logger.Error(\"Not a babylon environment map\");\n return null;\n }\n }\n // Read json manifest - collect characters up to null terminator\n let manifestString = \"\";\n let charCode = 0x00;\n while ((charCode = dataView.getUint8(pos++))) {\n manifestString += String.fromCharCode(charCode);\n }\n let manifest = JSON.parse(manifestString);\n manifest = normalizeEnvInfo(manifest);\n if (manifest.specular) {\n // Extend the header with the position of the payload.\n manifest.specular.specularDataPosition = pos;\n // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.\n manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;\n }\n return manifest;\n}\n/**\n * Normalizes any supported version of the environment file info to the latest version\n * @param info environment file info on any supported version\n * @returns environment file info in the latest supported version\n * @private\n */\nexport function normalizeEnvInfo(info) {\n if (info.version > CurrentVersion) {\n throw new Error(`Unsupported babylon environment map version \"${info.version}\". Latest supported version is \"${CurrentVersion}\".`);\n }\n if (info.version === 2) {\n return info;\n }\n // Migrate a v1 info to v2\n info = Object.assign(Object.assign({}, info), { version: 2, imageType: DefaultEnvironmentTextureImageType });\n return info;\n}\n/**\n * Creates an environment texture from a loaded cube texture.\n * @param texture defines the cube texture to convert in env file\n * @param options options for the conversion process\n * @param options.imageType the mime type for the encoded images, with support for \"image/png\" (default) and \"image/webp\"\n * @param options.imageQuality the image quality of encoded WebP images.\n * @returns a promise containing the environment data if successful.\n */\nexport async function CreateEnvTextureAsync(texture, options = {}) {\n var _a, _b;\n const internalTexture = texture.getInternalTexture();\n if (!internalTexture) {\n return Promise.reject(\"The cube texture is invalid.\");\n }\n const imageType = (_a = options.imageType) !== null && _a !== void 0 ? _a : DefaultEnvironmentTextureImageType;\n const engine = internalTexture.getEngine();\n if (texture.textureType !== 2 &&\n texture.textureType !== 1 &&\n texture.textureType !== 0 &&\n texture.textureType !== 0 &&\n texture.textureType !== 7 &&\n texture.textureType !== -1) {\n return Promise.reject(\"The cube texture should allow HDR (Full Float or Half Float).\");\n }\n let textureType = 1;\n if (!engine.getCaps().textureFloatRender) {\n textureType = 2;\n if (!engine.getCaps().textureHalfFloatRender) {\n return Promise.reject(\"Env texture can only be created when the browser supports half float or full float rendering.\");\n }\n }\n // sphericalPolynomial is lazy loaded so simply accessing it should trigger the computation.\n texture.sphericalPolynomial;\n // Lets keep track of the polynomial promise so we can wait for it to be ready before generating the pixels.\n const sphericalPolynomialPromise = (_b = texture.getInternalTexture()) === null || _b === void 0 ? void 0 : _b._sphericalPolynomialPromise;\n const cubeWidth = internalTexture.width;\n const hostingScene = new Scene(engine);\n const specularTextures = {};\n // As we are going to readPixels the faces of the cube, make sure the drawing/update commands for the cube texture are fully sent to the GPU in case it is drawn for the first time in this very frame!\n engine.flushFramebuffer();\n // Read and collect all mipmaps data from the cube.\n const mipmapsCount = Scalar.ILog2(internalTexture.width);\n for (let i = 0; i <= mipmapsCount; i++) {\n const faceWidth = Math.pow(2, mipmapsCount - i);\n // All faces of the cube.\n for (let face = 0; face < 6; face++) {\n let faceData = await texture.readPixels(face, i, undefined, false);\n if (faceData && faceData.byteLength === faceData.length) {\n const faceDataFloat = new Float32Array(faceData.byteLength * 4);\n for (let i = 0; i < faceData.byteLength; i++) {\n faceDataFloat[i] = faceData[i] / 255;\n // Gamma to linear\n faceDataFloat[i] = Math.pow(faceDataFloat[i], 2.2);\n }\n faceData = faceDataFloat;\n }\n else if (faceData && texture.gammaSpace) {\n const floatData = faceData;\n for (let i = 0; i < floatData.length; i++) {\n // Gamma to linear\n floatData[i] = Math.pow(floatData[i], 2.2);\n }\n }\n const tempTexture = engine.createRawTexture(faceData, faceWidth, faceWidth, 5, false, true, 1, null, textureType);\n await RGBDTextureTools.EncodeTextureToRGBD(tempTexture, hostingScene, textureType);\n const rgbdEncodedData = await engine._readTexturePixels(tempTexture, faceWidth, faceWidth);\n const imageEncodedData = await DumpTools.DumpDataAsync(faceWidth, faceWidth, rgbdEncodedData, imageType, undefined, false, true, options.imageQuality);\n specularTextures[i * 6 + face] = imageEncodedData;\n tempTexture.dispose();\n }\n }\n // We can delete the hosting scene keeping track of all the creation objects\n hostingScene.dispose();\n // Ensure completion of the polynomial creation promise.\n if (sphericalPolynomialPromise) {\n await sphericalPolynomialPromise;\n }\n // Creates the json header for the env texture\n const info = {\n version: CurrentVersion,\n width: cubeWidth,\n imageType,\n irradiance: _CreateEnvTextureIrradiance(texture),\n specular: {\n mipmaps: [],\n lodGenerationScale: texture.lodGenerationScale,\n },\n };\n // Sets the specular image data information\n let position = 0;\n for (let i = 0; i <= mipmapsCount; i++) {\n for (let face = 0; face < 6; face++) {\n const byteLength = specularTextures[i * 6 + face].byteLength;\n info.specular.mipmaps.push({\n length: byteLength,\n position: position,\n });\n position += byteLength;\n }\n }\n // Encode the JSON as an array buffer\n const infoString = JSON.stringify(info);\n const infoBuffer = new ArrayBuffer(infoString.length + 1);\n const infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.\n for (let i = 0, strLen = infoString.length; i < strLen; i++) {\n infoView[i] = infoString.charCodeAt(i);\n }\n // Ends up with a null terminator for easier parsing\n infoView[infoString.length] = 0x00;\n // Computes the final required size and creates the storage\n const totalSize = MagicBytes.length + position + infoBuffer.byteLength;\n const finalBuffer = new ArrayBuffer(totalSize);\n const finalBufferView = new Uint8Array(finalBuffer);\n const dataView = new DataView(finalBuffer);\n // Copy the magic bytes identifying the file in\n let pos = 0;\n for (let i = 0; i < MagicBytes.length; i++) {\n dataView.setUint8(pos++, MagicBytes[i]);\n }\n // Add the json info\n finalBufferView.set(new Uint8Array(infoBuffer), pos);\n pos += infoBuffer.byteLength;\n // Finally inserts the texture data\n for (let i = 0; i <= mipmapsCount; i++) {\n for (let face = 0; face < 6; face++) {\n const dataBuffer = specularTextures[i * 6 + face];\n finalBufferView.set(new Uint8Array(dataBuffer), pos);\n pos += dataBuffer.byteLength;\n }\n }\n // Voila\n return finalBuffer;\n}\n/**\n * Creates a JSON representation of the spherical data.\n * @param texture defines the texture containing the polynomials\n * @returns the JSON representation of the spherical info\n */\nfunction _CreateEnvTextureIrradiance(texture) {\n const polynmials = texture.sphericalPolynomial;\n if (polynmials == null) {\n return null;\n }\n return {\n x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],\n y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],\n z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],\n xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],\n yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],\n zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],\n yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],\n zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],\n xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z],\n };\n}\n/**\n * Creates the ArrayBufferViews used for initializing environment texture image data.\n * @param data the image data\n * @param info parameters that determine what views will be created for accessing the underlying buffer\n * @returns the views described by info providing access to the underlying buffer\n */\nexport function CreateImageDataArrayBufferViews(data, info) {\n info = normalizeEnvInfo(info);\n const specularInfo = info.specular;\n // Double checks the enclosed info\n let mipmapsCount = Scalar.Log2(info.width);\n mipmapsCount = Math.round(mipmapsCount) + 1;\n if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {\n throw new Error(`Unsupported specular mipmaps number \"${specularInfo.mipmaps.length}\"`);\n }\n const imageData = new Array(mipmapsCount);\n for (let i = 0; i < mipmapsCount; i++) {\n imageData[i] = new Array(6);\n for (let face = 0; face < 6; face++) {\n const imageInfo = specularInfo.mipmaps[i * 6 + face];\n imageData[i][face] = new Uint8Array(data.buffer, data.byteOffset + specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);\n }\n }\n return imageData;\n}\n/**\n * Uploads the texture info contained in the env file to the GPU.\n * @param texture defines the internal texture to upload to\n * @param data defines the data to load\n * @param info defines the texture info retrieved through the GetEnvInfo method\n * @returns a promise\n */\nexport function UploadEnvLevelsAsync(texture, data, info) {\n info = normalizeEnvInfo(info);\n const specularInfo = info.specular;\n if (!specularInfo) {\n // Nothing else parsed so far\n return Promise.resolve();\n }\n texture._lodGenerationScale = specularInfo.lodGenerationScale;\n const imageData = CreateImageDataArrayBufferViews(data, info);\n return UploadLevelsAsync(texture, imageData, info.imageType);\n}\nfunction _OnImageReadyAsync(image, engine, expandTexture, rgbdPostProcess, url, face, i, generateNonLODTextures, lodTextures, cubeRtt, texture) {\n return new Promise((resolve, reject) => {\n if (expandTexture) {\n const tempTexture = engine.createTexture(null, true, true, null, 1, null, (message) => {\n reject(message);\n }, image);\n rgbdPostProcess.getEffect().executeWhenCompiled(() => {\n // Uncompress the data to a RTT\n rgbdPostProcess.externalTextureSamplerBinding = true;\n rgbdPostProcess.onApply = (effect) => {\n effect._bindTexture(\"textureSampler\", tempTexture);\n effect.setFloat2(\"scale\", 1, engine._features.needsInvertingBitmap && image instanceof ImageBitmap ? -1 : 1);\n };\n if (!engine.scenes.length) {\n return;\n }\n engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);\n // Cleanup\n engine.restoreDefaultFramebuffer();\n tempTexture.dispose();\n URL.revokeObjectURL(url);\n resolve();\n });\n }\n else {\n engine._uploadImageToTexture(texture, image, face, i);\n // Upload the face to the non lod texture support\n if (generateNonLODTextures) {\n const lodTexture = lodTextures[i];\n if (lodTexture) {\n engine._uploadImageToTexture(lodTexture._texture, image, face, 0);\n }\n }\n resolve();\n }\n });\n}\n/**\n * Uploads the levels of image data to the GPU.\n * @param texture defines the internal texture to upload to\n * @param imageData defines the array buffer views of image data [mipmap][face]\n * @param imageType the mime type of the image data\n * @returns a promise\n */\nexport function UploadLevelsAsync(texture, imageData, imageType = DefaultEnvironmentTextureImageType) {\n if (!Tools.IsExponentOfTwo(texture.width)) {\n throw new Error(\"Texture size must be a power of two\");\n }\n const mipmapsCount = Scalar.ILog2(texture.width) + 1;\n // Gets everything ready.\n const engine = texture.getEngine();\n let expandTexture = false;\n let generateNonLODTextures = false;\n let rgbdPostProcess = null;\n let cubeRtt = null;\n let lodTextures = null;\n const caps = engine.getCaps();\n texture.format = 5;\n texture.type = 0;\n texture.generateMipMaps = true;\n texture._cachedAnisotropicFilteringLevel = null;\n engine.updateTextureSamplingMode(3, texture);\n // Add extra process if texture lod is not supported\n if (!caps.textureLOD) {\n expandTexture = false;\n generateNonLODTextures = true;\n lodTextures = {};\n }\n // in webgl 1 there are no ways to either render or copy lod level information for float textures.\n else if (!engine._features.supportRenderAndCopyToLodForFloatTextures) {\n expandTexture = false;\n }\n // If half float available we can uncompress the texture\n else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {\n expandTexture = true;\n texture.type = 2;\n }\n // If full float available we can uncompress the texture\n else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {\n expandTexture = true;\n texture.type = 1;\n }\n // Expand the texture if possible\n if (expandTexture) {\n // Simply run through the decode PP\n rgbdPostProcess = new PostProcess(\"rgbdDecode\", \"rgbdDecode\", null, null, 1, null, 3, engine, false, undefined, texture.type, undefined, null, false);\n texture._isRGBD = false;\n texture.invertY = false;\n cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {\n generateDepthBuffer: false,\n generateMipMaps: true,\n generateStencilBuffer: false,\n samplingMode: 3,\n type: texture.type,\n format: 5,\n });\n }\n else {\n texture._isRGBD = true;\n texture.invertY = true;\n // In case of missing support, applies the same patch than DDS files.\n if (generateNonLODTextures) {\n const mipSlices = 3;\n const scale = texture._lodGenerationScale;\n const offset = texture._lodGenerationOffset;\n for (let i = 0; i < mipSlices; i++) {\n //compute LOD from even spacing in smoothness (matching shader calculation)\n const smoothness = i / (mipSlices - 1);\n const roughness = 1 - smoothness;\n const minLODIndex = offset; // roughness = 0\n const maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)\n const lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;\n const mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));\n const glTextureFromLod = new InternalTexture(engine, InternalTextureSource.Temp);\n glTextureFromLod.isCube = true;\n glTextureFromLod.invertY = true;\n glTextureFromLod.generateMipMaps = false;\n engine.updateTextureSamplingMode(2, glTextureFromLod);\n // Wrap in a base texture for easy binding.\n const lodTexture = new BaseTexture(null);\n lodTexture._isCube = true;\n lodTexture._texture = glTextureFromLod;\n lodTextures[mipmapIndex] = lodTexture;\n switch (i) {\n case 0:\n texture._lodTextureLow = lodTexture;\n break;\n case 1:\n texture._lodTextureMid = lodTexture;\n break;\n case 2:\n texture._lodTextureHigh = lodTexture;\n break;\n }\n }\n }\n }\n const promises = [];\n // All mipmaps up to provided number of images\n for (let i = 0; i < imageData.length; i++) {\n // All faces\n for (let face = 0; face < 6; face++) {\n // Constructs an image element from image data\n const bytes = imageData[i][face];\n const blob = new Blob([bytes], { type: imageType });\n const url = URL.createObjectURL(blob);\n let promise;\n if (typeof Image === \"undefined\" || engine._features.forceBitmapOverHTMLImageElement) {\n promise = engine.createImageBitmap(blob, { premultiplyAlpha: \"none\" }).then((img) => {\n return _OnImageReadyAsync(img, engine, expandTexture, rgbdPostProcess, url, face, i, generateNonLODTextures, lodTextures, cubeRtt, texture);\n });\n }\n else {\n const image = new Image();\n image.src = url;\n // Enqueue promise to upload to the texture.\n promise = new Promise((resolve, reject) => {\n image.onload = () => {\n _OnImageReadyAsync(image, engine, expandTexture, rgbdPostProcess, url, face, i, generateNonLODTextures, lodTextures, cubeRtt, texture)\n .then(() => resolve())\n .catch((reason) => {\n reject(reason);\n });\n };\n image.onerror = (error) => {\n reject(error);\n };\n });\n }\n promises.push(promise);\n }\n }\n // Fill remaining mipmaps with black textures.\n if (imageData.length < mipmapsCount) {\n let data;\n const size = Math.pow(2, mipmapsCount - 1 - imageData.length);\n const dataLength = size * size * 4;\n switch (texture.type) {\n case 0: {\n data = new Uint8Array(dataLength);\n break;\n }\n case 2: {\n data = new Uint16Array(dataLength);\n break;\n }\n case 1: {\n data = new Float32Array(dataLength);\n break;\n }\n }\n for (let i = imageData.length; i < mipmapsCount; i++) {\n for (let face = 0; face < 6; face++) {\n engine._uploadArrayBufferViewToTexture(texture, data, face, i);\n }\n }\n }\n // Once all done, finishes the cleanup and return\n return Promise.all(promises).then(() => {\n // Release temp RTT.\n if (cubeRtt) {\n engine._releaseTexture(texture);\n cubeRtt._swapAndDie(texture);\n }\n // Release temp Post Process.\n if (rgbdPostProcess) {\n rgbdPostProcess.dispose();\n }\n // Flag internal texture as ready in case they are in use.\n if (generateNonLODTextures) {\n if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {\n texture._lodTextureHigh._texture.isReady = true;\n }\n if (texture._lodTextureMid && texture._lodTextureMid._texture) {\n texture._lodTextureMid._texture.isReady = true;\n }\n if (texture._lodTextureLow && texture._lodTextureLow._texture) {\n texture._lodTextureLow._texture.isReady = true;\n }\n }\n });\n}\n/**\n * Uploads spherical polynomials information to the texture.\n * @param texture defines the texture we are trying to upload the information to\n * @param info defines the environment texture info retrieved through the GetEnvInfo method\n */\nexport function UploadEnvSpherical(texture, info) {\n info = normalizeEnvInfo(info);\n const irradianceInfo = info.irradiance;\n if (!irradianceInfo) {\n return;\n }\n const sp = new SphericalPolynomial();\n Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);\n Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);\n Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);\n Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);\n Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);\n Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);\n Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);\n Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);\n Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);\n texture._sphericalPolynomial = sp;\n}\n/**\n * @internal\n */\nexport function _UpdateRGBDAsync(internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {\n const proxy = internalTexture\n .getEngine()\n .createRawCubeTexture(null, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);\n const proxyPromise = UploadLevelsAsync(proxy, data).then(() => internalTexture);\n internalTexture.onRebuildCallback = (_internalTexture) => {\n return {\n proxy: proxyPromise,\n isReady: true,\n isAsync: true,\n };\n };\n internalTexture._source = InternalTextureSource.CubeRawRGBD;\n internalTexture._bufferViewArrayArray = data;\n internalTexture._lodGenerationScale = lodScale;\n internalTexture._lodGenerationOffset = lodOffset;\n internalTexture._sphericalPolynomial = sphericalPolynomial;\n return UploadLevelsAsync(internalTexture, data).then(() => {\n internalTexture.isReady = true;\n return internalTexture;\n });\n}\n/**\n * Sets of helpers addressing the serialization and deserialization of environment texture\n * stored in a BabylonJS env file.\n * Those files are usually stored as .env files.\n */\nexport const EnvironmentTextureTools = {\n /**\n * Gets the environment info from an env file.\n * @param data The array buffer containing the .env bytes.\n * @returns the environment file info (the json header) if successfully parsed, normalized to the latest supported version.\n */\n GetEnvInfo,\n /**\n * Creates an environment texture from a loaded cube texture.\n * @param texture defines the cube texture to convert in env file\n * @param options options for the conversion process\n * @param options.imageType the mime type for the encoded images, with support for \"image/png\" (default) and \"image/webp\"\n * @param options.imageQuality the image quality of encoded WebP images.\n * @returns a promise containing the environment data if successful.\n */\n CreateEnvTextureAsync,\n /**\n * Creates the ArrayBufferViews used for initializing environment texture image data.\n * @param data the image data\n * @param info parameters that determine what views will be created for accessing the underlying buffer\n * @returns the views described by info providing access to the underlying buffer\n */\n CreateImageDataArrayBufferViews,\n /**\n * Uploads the texture info contained in the env file to the GPU.\n * @param texture defines the internal texture to upload to\n * @param data defines the data to load\n * @param info defines the texture info retrieved through the GetEnvInfo method\n * @returns a promise\n */\n UploadEnvLevelsAsync,\n /**\n * Uploads the levels of image data to the GPU.\n * @param texture defines the internal texture to upload to\n * @param imageData defines the array buffer views of image data [mipmap][face]\n * @param imageType the mime type of the image data\n * @returns a promise\n */\n UploadLevelsAsync,\n /**\n * Uploads spherical polynomials information to the texture.\n * @param texture defines the texture we are trying to upload the information to\n * @param info defines the environment texture info retrieved through the GetEnvInfo method\n */\n UploadEnvSpherical,\n};\n//# sourceMappingURL=environmentTextureTools.js.map","/**\n * Extracts the characters between two markers (for eg, between \"(\" and \")\"). The function handles nested markers as well as markers inside strings (delimited by \", ' or `) and comments\n * @param markerOpen opening marker\n * @param markerClose closing marker\n * @param block code block to parse\n * @param startIndex starting index in block where the extraction must start. The character at block[startIndex] should be the markerOpen character!\n * @returns index of the last character for the extraction (or -1 if the string is invalid - no matching closing marker found). The string to extract (without the markers) is the string between startIndex + 1 and the returned value (exclusive)\n */\nexport function ExtractBetweenMarkers(markerOpen, markerClose, block, startIndex) {\n let currPos = startIndex, openMarkers = 0, waitForChar = \"\";\n while (currPos < block.length) {\n const currChar = block.charAt(currPos);\n if (!waitForChar) {\n switch (currChar) {\n case markerOpen:\n openMarkers++;\n break;\n case markerClose:\n openMarkers--;\n break;\n case '\"':\n case \"'\":\n case \"`\":\n waitForChar = currChar;\n break;\n case \"/\":\n if (currPos + 1 < block.length) {\n const nextChar = block.charAt(currPos + 1);\n if (nextChar === \"/\") {\n waitForChar = \"\\n\";\n }\n else if (nextChar === \"*\") {\n waitForChar = \"*/\";\n }\n }\n break;\n }\n }\n else {\n if (currChar === waitForChar) {\n if (waitForChar === '\"' || waitForChar === \"'\") {\n block.charAt(currPos - 1) !== \"\\\\\" && (waitForChar = \"\");\n }\n else {\n waitForChar = \"\";\n }\n }\n else if (waitForChar === \"*/\" && currChar === \"*\" && currPos + 1 < block.length) {\n block.charAt(currPos + 1) === \"/\" && (waitForChar = \"\");\n if (waitForChar === \"\") {\n currPos++;\n }\n }\n }\n currPos++;\n if (openMarkers === 0) {\n break;\n }\n }\n return openMarkers === 0 ? currPos - 1 : -1;\n}\n/**\n * Parses a string and skip whitespaces\n * @param s string to parse\n * @param index index where to start parsing\n * @returns the index after all whitespaces have been skipped\n */\nexport function SkipWhitespaces(s, index) {\n while (index < s.length) {\n const c = s[index];\n if (c !== \" \" && c !== \"\\n\" && c !== \"\\r\" && c !== \"\\t\" && c !== \"\\u000a\" && c !== \"\\u00a0\") {\n break;\n }\n index++;\n }\n return index;\n}\n/**\n * Checks if a character is an identifier character (meaning, if it is 0-9, A-Z, a-z or _)\n * @param c character to check\n * @returns true if the character is an identifier character\n */\nexport function IsIdentifierChar(c) {\n const v = c.charCodeAt(0);\n return ((v >= 48 && v <= 57) || // 0-9\n (v >= 65 && v <= 90) || // A-Z\n (v >= 97 && v <= 122) || // a-z\n v == 95); // _\n}\n/**\n * Removes the comments of a code block\n * @param block code block to parse\n * @returns block with the comments removed\n */\nexport function RemoveComments(block) {\n let currPos = 0, waitForChar = \"\", inComments = false;\n const s = [];\n while (currPos < block.length) {\n const currChar = block.charAt(currPos);\n if (!waitForChar) {\n switch (currChar) {\n case '\"':\n case \"'\":\n case \"`\":\n waitForChar = currChar;\n break;\n case \"/\":\n if (currPos + 1 < block.length) {\n const nextChar = block.charAt(currPos + 1);\n if (nextChar === \"/\") {\n waitForChar = \"\\n\";\n inComments = true;\n }\n else if (nextChar === \"*\") {\n waitForChar = \"*/\";\n inComments = true;\n }\n }\n break;\n }\n if (!inComments) {\n s.push(currChar);\n }\n }\n else {\n if (currChar === waitForChar) {\n if (waitForChar === '\"' || waitForChar === \"'\") {\n block.charAt(currPos - 1) !== \"\\\\\" && (waitForChar = \"\");\n s.push(currChar);\n }\n else {\n waitForChar = \"\";\n inComments = false;\n }\n }\n else if (waitForChar === \"*/\" && currChar === \"*\" && currPos + 1 < block.length) {\n block.charAt(currPos + 1) === \"/\" && (waitForChar = \"\");\n if (waitForChar === \"\") {\n inComments = false;\n currPos++;\n }\n }\n else {\n if (!inComments) {\n s.push(currChar);\n }\n }\n }\n currPos++;\n }\n return s.join(\"\");\n}\n/**\n * Finds the first occurrence of a character in a string going backward\n * @param s the string to parse\n * @param index starting index in the string\n * @param c the character to find\n * @returns the index of the character if found, else -1\n */\nexport function FindBackward(s, index, c) {\n while (index >= 0 && s.charAt(index) !== c) {\n index--;\n }\n return index;\n}\n/**\n * Escapes a string so that it is usable as a regular expression\n * @param s string to escape\n * @returns escaped string\n */\nexport function EscapeRegExp(s) {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n//# sourceMappingURL=codeStringParsingTools.js.map","import { EscapeRegExp, ExtractBetweenMarkers, FindBackward, IsIdentifierChar, RemoveComments, SkipWhitespaces } from \"../../Misc/codeStringParsingTools.js\";\n/**\n * Class used to inline functions in shader code\n */\nexport class ShaderCodeInliner {\n /** Gets the code after the inlining process */\n get code() {\n return this._sourceCode;\n }\n /**\n * Initializes the inliner\n * @param sourceCode shader code source to inline\n * @param numMaxIterations maximum number of iterations (used to detect recursive calls)\n */\n constructor(sourceCode, numMaxIterations = 20) {\n /** Gets or sets the debug mode */\n this.debug = false;\n this._sourceCode = sourceCode;\n this._numMaxIterations = numMaxIterations;\n this._functionDescr = [];\n this.inlineToken = \"#define inline\";\n }\n /**\n * Start the processing of the shader code\n */\n processCode() {\n if (this.debug) {\n console.log(`Start inlining process (code size=${this._sourceCode.length})...`);\n }\n this._collectFunctions();\n this._processInlining(this._numMaxIterations);\n if (this.debug) {\n console.log(\"End of inlining process.\");\n }\n }\n _collectFunctions() {\n let startIndex = 0;\n while (startIndex < this._sourceCode.length) {\n // locate the function to inline and extract its name\n const inlineTokenIndex = this._sourceCode.indexOf(this.inlineToken, startIndex);\n if (inlineTokenIndex < 0) {\n break;\n }\n const funcParamsStartIndex = this._sourceCode.indexOf(\"(\", inlineTokenIndex + this.inlineToken.length);\n if (funcParamsStartIndex < 0) {\n if (this.debug) {\n console.warn(`Could not find the opening parenthesis after the token. startIndex=${startIndex}`);\n }\n startIndex = inlineTokenIndex + this.inlineToken.length;\n continue;\n }\n const funcNameMatch = ShaderCodeInliner._RegexpFindFunctionNameAndType.exec(this._sourceCode.substring(inlineTokenIndex + this.inlineToken.length, funcParamsStartIndex));\n if (!funcNameMatch) {\n if (this.debug) {\n console.warn(`Could not extract the name/type of the function from: ${this._sourceCode.substring(inlineTokenIndex + this.inlineToken.length, funcParamsStartIndex)}`);\n }\n startIndex = inlineTokenIndex + this.inlineToken.length;\n continue;\n }\n const [funcType, funcName] = [funcNameMatch[3], funcNameMatch[4]];\n // extract the parameters of the function as a whole string (without the leading / trailing parenthesis)\n const funcParamsEndIndex = ExtractBetweenMarkers(\"(\", \")\", this._sourceCode, funcParamsStartIndex);\n if (funcParamsEndIndex < 0) {\n if (this.debug) {\n console.warn(`Could not extract the parameters the function '${funcName}' (type=${funcType}). funcParamsStartIndex=${funcParamsStartIndex}`);\n }\n startIndex = inlineTokenIndex + this.inlineToken.length;\n continue;\n }\n const funcParams = this._sourceCode.substring(funcParamsStartIndex + 1, funcParamsEndIndex);\n // extract the body of the function (with the curly brackets)\n const funcBodyStartIndex = SkipWhitespaces(this._sourceCode, funcParamsEndIndex + 1);\n if (funcBodyStartIndex === this._sourceCode.length) {\n if (this.debug) {\n console.warn(`Could not extract the body of the function '${funcName}' (type=${funcType}). funcParamsEndIndex=${funcParamsEndIndex}`);\n }\n startIndex = inlineTokenIndex + this.inlineToken.length;\n continue;\n }\n const funcBodyEndIndex = ExtractBetweenMarkers(\"{\", \"}\", this._sourceCode, funcBodyStartIndex);\n if (funcBodyEndIndex < 0) {\n if (this.debug) {\n console.warn(`Could not extract the body of the function '${funcName}' (type=${funcType}). funcBodyStartIndex=${funcBodyStartIndex}`);\n }\n startIndex = inlineTokenIndex + this.inlineToken.length;\n continue;\n }\n const funcBody = this._sourceCode.substring(funcBodyStartIndex, funcBodyEndIndex + 1);\n // process the parameters: extract each names\n const params = RemoveComments(funcParams).split(\",\");\n const paramNames = [];\n for (let p = 0; p < params.length; ++p) {\n const param = params[p].trim();\n const idx = param.lastIndexOf(\" \");\n if (idx >= 0) {\n paramNames.push(param.substring(idx + 1));\n }\n }\n if (funcType !== \"void\") {\n // for functions that return a value, we will replace \"return\" by \"tempvarname = \", tempvarname being a unique generated name\n paramNames.push(\"return\");\n }\n // collect the function\n this._functionDescr.push({\n name: funcName,\n type: funcType,\n parameters: paramNames,\n body: funcBody,\n callIndex: 0,\n });\n startIndex = funcBodyEndIndex + 1;\n // remove the function from the source code\n const partBefore = inlineTokenIndex > 0 ? this._sourceCode.substring(0, inlineTokenIndex) : \"\";\n const partAfter = funcBodyEndIndex + 1 < this._sourceCode.length - 1 ? this._sourceCode.substring(funcBodyEndIndex + 1) : \"\";\n this._sourceCode = partBefore + partAfter;\n startIndex -= funcBodyEndIndex + 1 - inlineTokenIndex;\n }\n if (this.debug) {\n console.log(`Collect functions: ${this._functionDescr.length} functions found. functionDescr=`, this._functionDescr);\n }\n }\n _processInlining(numMaxIterations = 20) {\n while (numMaxIterations-- >= 0) {\n if (!this._replaceFunctionCallsByCode()) {\n break;\n }\n }\n if (this.debug) {\n console.log(`numMaxIterations is ${numMaxIterations} after inlining process`);\n }\n return numMaxIterations >= 0;\n }\n _replaceFunctionCallsByCode() {\n let doAgain = false;\n for (const func of this._functionDescr) {\n const { name, type, parameters, body } = func;\n let startIndex = 0;\n while (startIndex < this._sourceCode.length) {\n // Look for the function name in the source code\n const functionCallIndex = this._sourceCode.indexOf(name, startIndex);\n if (functionCallIndex < 0) {\n break;\n }\n // Make sure \"name\" is not part of a bigger string\n if (functionCallIndex === 0 || IsIdentifierChar(this._sourceCode.charAt(functionCallIndex - 1))) {\n startIndex = functionCallIndex + name.length;\n continue;\n }\n // Find the opening parenthesis\n const callParamsStartIndex = SkipWhitespaces(this._sourceCode, functionCallIndex + name.length);\n if (callParamsStartIndex === this._sourceCode.length || this._sourceCode.charAt(callParamsStartIndex) !== \"(\") {\n startIndex = functionCallIndex + name.length;\n continue;\n }\n // extract the parameters of the function call as a whole string (without the leading / trailing parenthesis)\n const callParamsEndIndex = ExtractBetweenMarkers(\"(\", \")\", this._sourceCode, callParamsStartIndex);\n if (callParamsEndIndex < 0) {\n if (this.debug) {\n console.warn(`Could not extract the parameters of the function call. Function '${name}' (type=${type}). callParamsStartIndex=${callParamsStartIndex}`);\n }\n startIndex = functionCallIndex + name.length;\n continue;\n }\n const callParams = this._sourceCode.substring(callParamsStartIndex + 1, callParamsEndIndex);\n // process the parameter call: extract each names\n // this function split the parameter list used in the function call at ',' boundaries by taking care of potential parenthesis like in:\n // myfunc(a, vec2(1., 0.), 4.)\n const splitParameterCall = (s) => {\n const parameters = [];\n let curIdx = 0, startParamIdx = 0;\n while (curIdx < s.length) {\n if (s.charAt(curIdx) === \"(\") {\n const idx2 = ExtractBetweenMarkers(\"(\", \")\", s, curIdx);\n if (idx2 < 0) {\n return null;\n }\n curIdx = idx2;\n }\n else if (s.charAt(curIdx) === \",\") {\n parameters.push(s.substring(startParamIdx, curIdx));\n startParamIdx = curIdx + 1;\n }\n curIdx++;\n }\n if (startParamIdx < curIdx) {\n parameters.push(s.substring(startParamIdx, curIdx));\n }\n return parameters;\n };\n const params = splitParameterCall(RemoveComments(callParams));\n if (params === null) {\n if (this.debug) {\n console.warn(`Invalid function call: can't extract the parameters of the function call. Function '${name}' (type=${type}). callParamsStartIndex=${callParamsStartIndex}, callParams=` +\n callParams);\n }\n startIndex = functionCallIndex + name.length;\n continue;\n }\n const paramNames = [];\n for (let p = 0; p < params.length; ++p) {\n const param = params[p].trim();\n paramNames.push(param);\n }\n const retParamName = type !== \"void\" ? name + \"_\" + func.callIndex++ : null;\n if (retParamName) {\n paramNames.push(retParamName + \" =\");\n }\n if (paramNames.length !== parameters.length) {\n if (this.debug) {\n console.warn(`Invalid function call: not the same number of parameters for the call than the number expected by the function. Function '${name}' (type=${type}). function parameters=${parameters}, call parameters=${paramNames}`);\n }\n startIndex = functionCallIndex + name.length;\n continue;\n }\n startIndex = callParamsEndIndex + 1;\n // replace the function call by the body function\n const funcBody = this._replaceNames(body, parameters, paramNames);\n let partBefore = functionCallIndex > 0 ? this._sourceCode.substring(0, functionCallIndex) : \"\";\n const partAfter = callParamsEndIndex + 1 < this._sourceCode.length - 1 ? this._sourceCode.substring(callParamsEndIndex + 1) : \"\";\n if (retParamName) {\n // case where the function returns a value. We generate:\n // FUNCTYPE retParamName;\n // {function body}\n // and replace the function call by retParamName\n const injectDeclarationIndex = FindBackward(this._sourceCode, functionCallIndex - 1, \"\\n\");\n partBefore = this._sourceCode.substring(0, injectDeclarationIndex + 1);\n const partBetween = this._sourceCode.substring(injectDeclarationIndex + 1, functionCallIndex);\n this._sourceCode = partBefore + type + \" \" + retParamName + \";\\n\" + funcBody + \"\\n\" + partBetween + retParamName + partAfter;\n if (this.debug) {\n console.log(`Replace function call by code. Function '${name}' (type=${type}). injectDeclarationIndex=${injectDeclarationIndex}, call parameters=${paramNames}`);\n }\n }\n else {\n // simple case where the return value of the function is \"void\"\n this._sourceCode = partBefore + funcBody + partAfter;\n startIndex += funcBody.length - (callParamsEndIndex + 1 - functionCallIndex);\n if (this.debug) {\n console.log(`Replace function call by code. Function '${name}' (type=${type}). functionCallIndex=${functionCallIndex}, call parameters=${paramNames}`);\n }\n }\n doAgain = true;\n }\n }\n return doAgain;\n }\n _replaceNames(code, sources, destinations) {\n for (let i = 0; i < sources.length; ++i) {\n const source = new RegExp(EscapeRegExp(sources[i]), \"g\"), sourceLen = sources[i].length, destination = destinations[i];\n code = code.replace(source, (match, ...args) => {\n const offset = args[0];\n // Make sure \"source\" is not part of a bigger identifier (for eg, if source=view and we matched it with viewDirection)\n if (IsIdentifierChar(code.charAt(offset - 1)) || IsIdentifierChar(code.charAt(offset + sourceLen))) {\n return sources[i];\n }\n return destination;\n });\n }\n return code;\n }\n}\nShaderCodeInliner._RegexpFindFunctionNameAndType = /((\\s+?)(\\w+)\\s+(\\w+)\\s*?)$/;\n//# sourceMappingURL=shaderCodeInliner.js.map","export class NativePipelineContext {\n get isAsync() {\n return this.isParallelCompiled;\n }\n get isReady() {\n if (this.compilationError) {\n const message = this.compilationError.message;\n throw new Error(\"SHADER ERROR\" + (typeof message === \"string\" ? \"\\n\" + message : \"\"));\n }\n return this.isCompiled;\n }\n _getVertexShaderCode() {\n return null;\n }\n _getFragmentShaderCode() {\n return null;\n }\n // TODO: what should this do?\n _handlesSpectorRebuildCallback(onCompiled) {\n throw new Error(\"Not implemented\");\n }\n constructor(engine) {\n this.isParallelCompiled = true;\n this.isCompiled = false;\n this._valueCache = {};\n this._engine = engine;\n }\n _fillEffectInformation(effect, uniformBuffersNames, uniformsNames, uniforms, samplerList, samplers, attributesNames, attributes) {\n const engine = this._engine;\n if (engine.supportsUniformBuffers) {\n for (const name in uniformBuffersNames) {\n effect.bindUniformBlock(name, uniformBuffersNames[name]);\n }\n }\n const effectAvailableUniforms = this._engine.getUniforms(this, uniformsNames);\n effectAvailableUniforms.forEach((uniform, index) => {\n uniforms[uniformsNames[index]] = uniform;\n });\n this._uniforms = uniforms;\n let index;\n for (index = 0; index < samplerList.length; index++) {\n const sampler = effect.getUniform(samplerList[index]);\n if (sampler == null) {\n samplerList.splice(index, 1);\n index--;\n }\n }\n samplerList.forEach((name, index) => {\n samplers[name] = index;\n });\n attributes.push(...engine.getAttributes(this, attributesNames));\n }\n /**\n * Release all associated resources.\n **/\n dispose() {\n this._uniforms = {};\n }\n /**\n * @internal\n */\n _cacheMatrix(uniformName, matrix) {\n const cache = this._valueCache[uniformName];\n const flag = matrix.updateFlag;\n if (cache !== undefined && cache === flag) {\n return false;\n }\n this._valueCache[uniformName] = flag;\n return true;\n }\n /**\n * @internal\n */\n _cacheFloat2(uniformName, x, y) {\n let cache = this._valueCache[uniformName];\n if (!cache) {\n cache = [x, y];\n this._valueCache[uniformName] = cache;\n return true;\n }\n let changed = false;\n if (cache[0] !== x) {\n cache[0] = x;\n changed = true;\n }\n if (cache[1] !== y) {\n cache[1] = y;\n changed = true;\n }\n return changed;\n }\n /**\n * @internal\n */\n _cacheFloat3(uniformName, x, y, z) {\n let cache = this._valueCache[uniformName];\n if (!cache) {\n cache = [x, y, z];\n this._valueCache[uniformName] = cache;\n return true;\n }\n let changed = false;\n if (cache[0] !== x) {\n cache[0] = x;\n changed = true;\n }\n if (cache[1] !== y) {\n cache[1] = y;\n changed = true;\n }\n if (cache[2] !== z) {\n cache[2] = z;\n changed = true;\n }\n return changed;\n }\n /**\n * @internal\n */\n _cacheFloat4(uniformName, x, y, z, w) {\n let cache = this._valueCache[uniformName];\n if (!cache) {\n cache = [x, y, z, w];\n this._valueCache[uniformName] = cache;\n return true;\n }\n let changed = false;\n if (cache[0] !== x) {\n cache[0] = x;\n changed = true;\n }\n if (cache[1] !== y) {\n cache[1] = y;\n changed = true;\n }\n if (cache[2] !== z) {\n cache[2] = z;\n changed = true;\n }\n if (cache[3] !== w) {\n cache[3] = w;\n changed = true;\n }\n return changed;\n }\n /**\n * Sets an integer value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value Value to be set.\n */\n setInt(uniformName, value) {\n const cache = this._valueCache[uniformName];\n if (cache !== undefined && cache === value) {\n return;\n }\n if (this._engine.setInt(this._uniforms[uniformName], value)) {\n this._valueCache[uniformName] = value;\n }\n }\n /**\n * Sets a int2 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First int in int2.\n * @param y Second int in int2.\n */\n setInt2(uniformName, x, y) {\n if (this._cacheFloat2(uniformName, x, y)) {\n if (!this._engine.setInt2(this._uniforms[uniformName], x, y)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a int3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First int in int3.\n * @param y Second int in int3.\n * @param z Third int in int3.\n */\n setInt3(uniformName, x, y, z) {\n if (this._cacheFloat3(uniformName, x, y, z)) {\n if (!this._engine.setInt3(this._uniforms[uniformName], x, y, z)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a int4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First int in int4.\n * @param y Second int in int4.\n * @param z Third int in int4.\n * @param w Fourth int in int4.\n */\n setInt4(uniformName, x, y, z, w) {\n if (this._cacheFloat4(uniformName, x, y, z, w)) {\n if (!this._engine.setInt4(this._uniforms[uniformName], x, y, z, w)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets an int array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setIntArray(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setIntArray(this._uniforms[uniformName], array);\n }\n /**\n * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setIntArray2(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setIntArray2(this._uniforms[uniformName], array);\n }\n /**\n * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setIntArray3(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setIntArray3(this._uniforms[uniformName], array);\n }\n /**\n * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setIntArray4(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setIntArray4(this._uniforms[uniformName], array);\n }\n /**\n * Sets an unsigned integer value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value Value to be set.\n */\n setUInt(uniformName, value) {\n const cache = this._valueCache[uniformName];\n if (cache !== undefined && cache === value) {\n return;\n }\n if (this._engine.setUInt(this._uniforms[uniformName], value)) {\n this._valueCache[uniformName] = value;\n }\n }\n /**\n * Sets a unsigned int2 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First unsigned int in uint2.\n * @param y Second unsigned int in uint2.\n */\n setUInt2(uniformName, x, y) {\n if (this._cacheFloat2(uniformName, x, y)) {\n if (!this._engine.setUInt2(this._uniforms[uniformName], x, y)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a unsigned int3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First unsigned int in uint3.\n * @param y Second unsigned int in uint3.\n * @param z Third unsigned int in uint3.\n */\n setUInt3(uniformName, x, y, z) {\n if (this._cacheFloat3(uniformName, x, y, z)) {\n if (!this._engine.setUInt3(this._uniforms[uniformName], x, y, z)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a unsigned int4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First unsigned int in uint4.\n * @param y Second unsigned int in uint4.\n * @param z Third unsigned int in uint4.\n * @param w Fourth unsigned int in uint4.\n */\n setUInt4(uniformName, x, y, z, w) {\n if (this._cacheFloat4(uniformName, x, y, z, w)) {\n if (!this._engine.setUInt4(this._uniforms[uniformName], x, y, z, w)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets an unsigned int array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setUIntArray(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setUIntArray(this._uniforms[uniformName], array);\n }\n /**\n * Sets an unsigned int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setUIntArray2(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setUIntArray2(this._uniforms[uniformName], array);\n }\n /**\n * Sets an unsigned int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setUIntArray3(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setUIntArray3(this._uniforms[uniformName], array);\n }\n /**\n * Sets an unsigned int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setUIntArray4(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setUIntArray4(this._uniforms[uniformName], array);\n }\n /**\n * Sets an float array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setFloatArray(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setFloatArray(this._uniforms[uniformName], array);\n }\n /**\n * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setFloatArray2(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setFloatArray2(this._uniforms[uniformName], array);\n }\n /**\n * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setFloatArray3(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setFloatArray3(this._uniforms[uniformName], array);\n }\n /**\n * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setFloatArray4(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setFloatArray4(this._uniforms[uniformName], array);\n }\n /**\n * Sets an array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setArray(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setArray(this._uniforms[uniformName], array);\n }\n /**\n * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setArray2(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setArray2(this._uniforms[uniformName], array);\n }\n /**\n * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setArray3(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setArray3(this._uniforms[uniformName], array);\n }\n /**\n * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setArray4(uniformName, array) {\n this._valueCache[uniformName] = null;\n this._engine.setArray4(this._uniforms[uniformName], array);\n }\n /**\n * Sets matrices on a uniform variable.\n * @param uniformName Name of the variable.\n * @param matrices matrices to be set.\n */\n setMatrices(uniformName, matrices) {\n if (!matrices) {\n return;\n }\n this._valueCache[uniformName] = null;\n this._engine.setMatrices(this._uniforms[uniformName], matrices);\n }\n /**\n * Sets matrix on a uniform variable.\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n */\n setMatrix(uniformName, matrix) {\n if (this._cacheMatrix(uniformName, matrix)) {\n if (!this._engine.setMatrices(this._uniforms[uniformName], matrix.toArray())) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a 3x3 matrix on a uniform variable. (Specified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n */\n setMatrix3x3(uniformName, matrix) {\n this._valueCache[uniformName] = null;\n this._engine.setMatrix3x3(this._uniforms[uniformName], matrix);\n }\n /**\n * Sets a 2x2 matrix on a uniform variable. (Specified as [1,2,3,4] will result in [1,2][3,4] matrix)\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n */\n setMatrix2x2(uniformName, matrix) {\n this._valueCache[uniformName] = null;\n this._engine.setMatrix2x2(this._uniforms[uniformName], matrix);\n }\n /**\n * Sets a float on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value value to be set.\n * @returns this effect.\n */\n setFloat(uniformName, value) {\n const cache = this._valueCache[uniformName];\n if (cache !== undefined && cache === value) {\n return;\n }\n if (this._engine.setFloat(this._uniforms[uniformName], value)) {\n this._valueCache[uniformName] = value;\n }\n }\n /**\n * Sets a boolean on a uniform variable.\n * @param uniformName Name of the variable.\n * @param bool value to be set.\n */\n setBool(uniformName, bool) {\n const cache = this._valueCache[uniformName];\n if (cache !== undefined && cache === bool) {\n return;\n }\n if (this._engine.setInt(this._uniforms[uniformName], bool ? 1 : 0)) {\n this._valueCache[uniformName] = bool ? 1 : 0;\n }\n }\n /**\n * Sets a Vector2 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector2 vector2 to be set.\n */\n setVector2(uniformName, vector2) {\n if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {\n if (!this._engine.setFloat2(this._uniforms[uniformName], vector2.x, vector2.y)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a float2 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float2.\n * @param y Second float in float2.\n */\n setFloat2(uniformName, x, y) {\n if (this._cacheFloat2(uniformName, x, y)) {\n if (!this._engine.setFloat2(this._uniforms[uniformName], x, y)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a Vector3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector3 Value to be set.\n */\n setVector3(uniformName, vector3) {\n if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {\n if (!this._engine.setFloat3(this._uniforms[uniformName], vector3.x, vector3.y, vector3.z)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a float3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float3.\n * @param y Second float in float3.\n * @param z Third float in float3.\n */\n setFloat3(uniformName, x, y, z) {\n if (this._cacheFloat3(uniformName, x, y, z)) {\n if (!this._engine.setFloat3(this._uniforms[uniformName], x, y, z)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a Vector4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector4 Value to be set.\n */\n setVector4(uniformName, vector4) {\n if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {\n if (!this._engine.setFloat4(this._uniforms[uniformName], vector4.x, vector4.y, vector4.z, vector4.w)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a Quaternion on a uniform variable.\n * @param uniformName Name of the variable.\n * @param quaternion Value to be set.\n */\n setQuaternion(uniformName, quaternion) {\n if (this._cacheFloat4(uniformName, quaternion.x, quaternion.y, quaternion.z, quaternion.w)) {\n if (!this._engine.setFloat4(this._uniforms[uniformName], quaternion.x, quaternion.y, quaternion.z, quaternion.w)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a float4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float4.\n * @param y Second float in float4.\n * @param z Third float in float4.\n * @param w Fourth float in float4.\n * @returns this effect.\n */\n setFloat4(uniformName, x, y, z, w) {\n if (this._cacheFloat4(uniformName, x, y, z, w)) {\n if (!this._engine.setFloat4(this._uniforms[uniformName], x, y, z, w)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a Color3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param color3 Value to be set.\n */\n setColor3(uniformName, color3) {\n if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {\n if (!this._engine.setFloat3(this._uniforms[uniformName], color3.r, color3.g, color3.b)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a Color4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param color3 Value to be set.\n * @param alpha Alpha value to be set.\n */\n setColor4(uniformName, color3, alpha) {\n if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {\n if (!this._engine.setFloat4(this._uniforms[uniformName], color3.r, color3.g, color3.b, alpha)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a Color4 on a uniform variable\n * @param uniformName defines the name of the variable\n * @param color4 defines the value to be set\n */\n setDirectColor4(uniformName, color4) {\n if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {\n if (!this._engine.setFloat4(this._uniforms[uniformName], color4.r, color4.g, color4.b, color4.a)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n}\n//# sourceMappingURL=nativePipelineContext.js.map","import { RenderTargetWrapper } from \"../renderTargetWrapper.js\";\nexport class NativeRenderTargetWrapper extends RenderTargetWrapper {\n get _framebuffer() {\n return this.__framebuffer;\n }\n set _framebuffer(framebuffer) {\n if (this.__framebuffer) {\n this._engine._releaseFramebufferObjects(this.__framebuffer);\n }\n this.__framebuffer = framebuffer;\n }\n get _framebufferDepthStencil() {\n return this.__framebufferDepthStencil;\n }\n set _framebufferDepthStencil(framebufferDepthStencil) {\n if (this.__framebufferDepthStencil) {\n this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil);\n }\n this.__framebufferDepthStencil = framebufferDepthStencil;\n }\n constructor(isMulti, isCube, size, engine) {\n super(isMulti, isCube, size, engine);\n this.__framebuffer = null;\n this.__framebufferDepthStencil = null;\n this._engine = engine;\n }\n dispose(disposeOnlyFramebuffers = false) {\n this._framebuffer = null;\n this._framebufferDepthStencil = null;\n super.dispose(disposeOnlyFramebuffers);\n }\n}\n//# sourceMappingURL=nativeRenderTargetWrapper.js.map","/** @internal */\nexport class NativeHardwareTexture {\n get underlyingResource() {\n return this._nativeTexture;\n }\n constructor(existingTexture, engine) {\n this._engine = engine;\n this.set(existingTexture);\n }\n setUsage() { }\n set(hardwareTexture) {\n this._nativeTexture = hardwareTexture;\n }\n reset() {\n this._nativeTexture = null;\n }\n release() {\n if (this._nativeTexture) {\n this._engine.deleteTexture(this._nativeTexture);\n }\n this.reset();\n }\n}\n//# sourceMappingURL=nativeHardwareTexture.js.map","import { Engine } from \"../Engines/engine.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { InternalTexture, InternalTextureSource } from \"../Materials/Textures/internalTexture.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { DataBuffer } from \"../Buffers/dataBuffer.js\";\nimport { Tools } from \"../Misc/tools.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { CreateImageDataArrayBufferViews, GetEnvInfo, UploadEnvSpherical } from \"../Misc/environmentTextureTools.js\";\nimport { Logger } from \"../Misc/logger.js\";\n\nimport { ThinEngine } from \"./thinEngine.js\";\nimport { EngineStore } from \"./engineStore.js\";\nimport { ShaderCodeInliner } from \"./Processors/shaderCodeInliner.js\";\nimport { WebGL2ShaderProcessor } from \"../Engines/WebGL/webGL2ShaderProcessors.js\";\nimport { NativeDataStream } from \"./Native/nativeDataStream.js\";\nimport { RuntimeError, ErrorCodes } from \"../Misc/error.js\";\nimport { NativePipelineContext } from \"./Native/nativePipelineContext.js\";\nimport { NativeRenderTargetWrapper } from \"./Native/nativeRenderTargetWrapper.js\";\nimport { NativeHardwareTexture } from \"./Native/nativeHardwareTexture.js\";\nconst onNativeObjectInitialized = new Observable();\nif (typeof self !== \"undefined\" && !Object.prototype.hasOwnProperty.call(self, \"_native\")) {\n let __native;\n Object.defineProperty(self, \"_native\", {\n get: () => __native,\n set: (value) => {\n __native = value;\n if (__native) {\n onNativeObjectInitialized.notifyObservers(__native);\n }\n },\n });\n}\n/**\n * Returns _native only after it has been defined by BabylonNative.\n * @internal\n */\nexport function AcquireNativeObjectAsync() {\n return new Promise((resolve) => {\n if (typeof _native === \"undefined\") {\n onNativeObjectInitialized.addOnce((nativeObject) => resolve(nativeObject));\n }\n else {\n resolve(_native);\n }\n });\n}\n/**\n * Registers a constructor on the _native object. See NativeXRFrame for an example.\n * @internal\n */\nexport async function RegisterNativeTypeAsync(typeName, constructor) {\n (await AcquireNativeObjectAsync())[typeName] = constructor;\n}\n/**\n * Container for accessors for natively-stored mesh data buffers.\n */\nclass NativeDataBuffer extends DataBuffer {\n}\n/** @internal */\nclass CommandBufferEncoder {\n constructor(_engine) {\n this._engine = _engine;\n this._pending = new Array();\n this._isCommandBufferScopeActive = false;\n this._commandStream = NativeEngine._createNativeDataStream();\n this._engine.setCommandDataStream(this._commandStream);\n }\n beginCommandScope() {\n if (this._isCommandBufferScopeActive) {\n throw new Error(\"Command scope already active.\");\n }\n this._isCommandBufferScopeActive = true;\n }\n endCommandScope() {\n if (!this._isCommandBufferScopeActive) {\n throw new Error(\"Command scope is not active.\");\n }\n this._isCommandBufferScopeActive = false;\n this._submit();\n }\n startEncodingCommand(command) {\n this._commandStream.writeNativeData(command);\n }\n encodeCommandArgAsUInt32(commandArg) {\n this._commandStream.writeUint32(commandArg);\n }\n encodeCommandArgAsUInt32s(commandArg) {\n this._commandStream.writeUint32Array(commandArg);\n }\n encodeCommandArgAsInt32(commandArg) {\n this._commandStream.writeInt32(commandArg);\n }\n encodeCommandArgAsInt32s(commandArg) {\n this._commandStream.writeInt32Array(commandArg);\n }\n encodeCommandArgAsFloat32(commandArg) {\n this._commandStream.writeFloat32(commandArg);\n }\n encodeCommandArgAsFloat32s(commandArg) {\n this._commandStream.writeFloat32Array(commandArg);\n }\n encodeCommandArgAsNativeData(commandArg) {\n this._commandStream.writeNativeData(commandArg);\n this._pending.push(commandArg);\n }\n finishEncodingCommand() {\n if (!this._isCommandBufferScopeActive) {\n this._submit();\n }\n }\n _submit() {\n this._engine.submitCommands();\n this._pending.length = 0;\n }\n}\n/** @internal */\nexport class NativeEngine extends Engine {\n setHardwareScalingLevel(level) {\n super.setHardwareScalingLevel(level);\n this._engine.setHardwareScalingLevel(level);\n }\n constructor(options = {}) {\n super(null, false, undefined, options.adaptToDeviceRatio);\n this._engine = new _native.Engine();\n this._camera = _native.Camera ? new _native.Camera() : null;\n this._commandBufferEncoder = new CommandBufferEncoder(this._engine);\n this._boundBuffersVertexArray = null;\n this._currentDepthTest = _native.Engine.DEPTH_TEST_LEQUAL;\n this._stencilTest = false;\n this._stencilMask = 255;\n this._stencilFunc = 519;\n this._stencilFuncRef = 0;\n this._stencilFuncMask = 255;\n this._stencilOpStencilFail = 7680;\n this._stencilOpDepthFail = 7680;\n this._stencilOpStencilDepthPass = 7681;\n this._zOffset = 0;\n this._zOffsetUnits = 0;\n this._depthWrite = true;\n if (_native.Engine.PROTOCOL_VERSION !== NativeEngine.PROTOCOL_VERSION) {\n throw new Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${NativeEngine.PROTOCOL_VERSION} (JS)`);\n }\n this._webGLVersion = 2;\n this.disableUniformBuffers = true;\n this._shaderPlatformName = \"NATIVE\";\n // TODO: Initialize this more correctly based on the hardware capabilities.\n // Init caps\n this._caps = {\n maxTexturesImageUnits: 16,\n maxVertexTextureImageUnits: 16,\n maxCombinedTexturesImageUnits: 32,\n maxTextureSize: _native.Engine.CAPS_LIMITS_MAX_TEXTURE_SIZE,\n maxCubemapTextureSize: 512,\n maxRenderTextureSize: 512,\n maxVertexAttribs: 16,\n maxVaryingVectors: 16,\n maxFragmentUniformVectors: 16,\n maxVertexUniformVectors: 16,\n standardDerivatives: true,\n astc: null,\n pvrtc: null,\n etc1: null,\n etc2: null,\n bptc: null,\n maxAnisotropy: 16,\n uintIndices: true,\n fragmentDepthSupported: false,\n highPrecisionShaderSupported: true,\n colorBufferFloat: false,\n textureFloat: true,\n textureFloatLinearFiltering: false,\n textureFloatRender: false,\n textureHalfFloat: false,\n textureHalfFloatLinearFiltering: false,\n textureHalfFloatRender: false,\n textureLOD: true,\n texelFetch: false,\n drawBuffersExtension: false,\n depthTextureExtension: false,\n vertexArrayObject: true,\n instancedArrays: true,\n supportOcclusionQuery: false,\n canUseTimestampForTimerQuery: false,\n blendMinMax: false,\n maxMSAASamples: 1,\n canUseGLInstanceID: true,\n canUseGLVertexID: true,\n supportComputeShaders: false,\n supportSRGBBuffers: true,\n supportTransformFeedbacks: false,\n textureMaxLevel: false,\n texture2DArrayMaxLayerCount: _native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS,\n disableMorphTargetTexture: false,\n };\n this._features = {\n forceBitmapOverHTMLImageElement: false,\n supportRenderAndCopyToLodForFloatTextures: false,\n supportDepthStencilTexture: false,\n supportShadowSamplers: false,\n uniformBufferHardCheckMatrix: false,\n allowTexturePrefiltering: false,\n trackUbosInFrame: false,\n checkUbosContentBeforeUpload: false,\n supportCSM: false,\n basisNeedsPOT: false,\n support3DTextures: false,\n needTypeSuffixInShaderConstants: false,\n supportMSAA: false,\n supportSSAO2: false,\n supportExtendedTextureFormats: false,\n supportSwitchCaseInShader: false,\n supportSyncTextureRead: false,\n needsInvertingBitmap: true,\n useUBOBindingCache: true,\n needShaderCodeInlining: true,\n needToAlwaysBindUniformBuffers: false,\n supportRenderPasses: true,\n supportSpriteInstancing: false,\n _collectUbosUpdatedInFrame: false,\n };\n Tools.Log(\"Babylon Native (v\" + Engine.Version + \") launched\");\n Tools.LoadScript = function (scriptUrl, onSuccess, onError, scriptId) {\n Tools.LoadFile(scriptUrl, (data) => {\n Function(data).apply(null);\n if (onSuccess) {\n onSuccess();\n }\n }, undefined, undefined, false, (request, exception) => {\n if (onError) {\n onError(\"LoadScript Error\", exception);\n }\n });\n };\n // Wrappers\n if (typeof URL === \"undefined\") {\n window.URL = {\n createObjectURL: function () { },\n revokeObjectURL: function () { },\n };\n }\n if (typeof Blob === \"undefined\") {\n window.Blob = function (v) {\n return v;\n };\n }\n // polyfill for Chakra\n if (!Array.prototype.flat) {\n Object.defineProperty(Array.prototype, \"flat\", {\n configurable: true,\n value: function flat() {\n const depth = isNaN(arguments[0]) ? 1 : Number(arguments[0]);\n return depth\n ? Array.prototype.reduce.call(this, function (acc, cur) {\n if (Array.isArray(cur)) {\n acc.push.apply(acc, flat.call(cur, depth - 1));\n }\n else {\n acc.push(cur);\n }\n return acc;\n }, [])\n : Array.prototype.slice.call(this);\n },\n writable: true,\n });\n }\n // Currently we do not fully configure the ThinEngine on construction of NativeEngine.\n // Setup resolution scaling based on display settings.\n const devicePixelRatio = window ? window.devicePixelRatio || 1.0 : 1.0;\n this._hardwareScalingLevel = options.adaptToDeviceRatio ? 1.0 / devicePixelRatio : 1.0;\n this._engine.setHardwareScalingLevel(this._hardwareScalingLevel);\n this._lastDevicePixelRatio = devicePixelRatio;\n this.resize();\n const currentDepthFunction = this.getDepthFunction();\n if (currentDepthFunction) {\n this.setDepthFunction(currentDepthFunction);\n }\n // Shader processor\n this._shaderProcessor = new WebGL2ShaderProcessor();\n this.onNewSceneAddedObservable.add((scene) => {\n const originalRender = scene.render;\n scene.render = (...args) => {\n this._commandBufferEncoder.beginCommandScope();\n originalRender.apply(scene, args);\n this._commandBufferEncoder.endCommandScope();\n };\n });\n }\n dispose() {\n super.dispose();\n if (this._boundBuffersVertexArray) {\n this._deleteVertexArray(this._boundBuffersVertexArray);\n }\n this._engine.dispose();\n }\n /** @internal */\n static _createNativeDataStream() {\n return new NativeDataStream();\n }\n /**\n * Can be used to override the current requestAnimationFrame requester.\n * @internal\n */\n _queueNewFrame(bindedRenderFunction, requester) {\n // Use the provided requestAnimationFrame, unless the requester is the window. In that case, we will default to the Babylon Native version of requestAnimationFrame.\n if (requester.requestAnimationFrame && requester !== window) {\n requester.requestAnimationFrame(bindedRenderFunction);\n }\n else {\n this._engine.requestAnimationFrame(bindedRenderFunction);\n }\n return 0;\n }\n /**\n * Override default engine behavior.\n * @param framebuffer\n */\n _bindUnboundFramebuffer(framebuffer) {\n if (this._currentFramebuffer !== framebuffer) {\n if (this._currentFramebuffer) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n if (framebuffer) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(framebuffer);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n this._currentFramebuffer = framebuffer;\n }\n }\n /**\n * Gets host document\n * @returns the host document object\n */\n getHostDocument() {\n return null;\n }\n clear(color, backBuffer, depth, stencil = false) {\n if (this.useReverseDepthBuffer) {\n throw new Error(\"reverse depth buffer is not currently implemented\");\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(backBuffer && color ? 1 : 0);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(color ? color.r : 0);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(color ? color.g : 0);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(color ? color.b : 0);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(color ? color.a : 1);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(depth ? 1 : 0);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(1);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(stencil ? 1 : 0);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(0);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n createIndexBuffer(indices, updateable) {\n const data = this._normalizeIndexData(indices);\n const buffer = new NativeDataBuffer();\n buffer.references = 1;\n buffer.is32Bits = data.BYTES_PER_ELEMENT === 4;\n if (data.byteLength) {\n buffer.nativeIndexBuffer = this._engine.createIndexBuffer(data.buffer, data.byteOffset, data.byteLength, buffer.is32Bits, updateable !== null && updateable !== void 0 ? updateable : false);\n }\n return buffer;\n }\n createVertexBuffer(vertices, updateable) {\n const data = ArrayBuffer.isView(vertices) ? vertices : new Float32Array(vertices);\n const buffer = new NativeDataBuffer();\n buffer.references = 1;\n if (data.byteLength) {\n buffer.nativeVertexBuffer = this._engine.createVertexBuffer(data.buffer, data.byteOffset, data.byteLength, updateable !== null && updateable !== void 0 ? updateable : false);\n }\n return buffer;\n }\n _recordVertexArrayObject(vertexArray, vertexBuffers, indexBuffer, effect, overrideVertexBuffers) {\n if (indexBuffer) {\n this._engine.recordIndexBuffer(vertexArray, indexBuffer.nativeIndexBuffer);\n }\n const attributes = effect.getAttributesNames();\n for (let index = 0; index < attributes.length; index++) {\n const location = effect.getAttributeLocation(index);\n if (location >= 0) {\n const kind = attributes[index];\n let vertexBuffer = null;\n if (overrideVertexBuffers) {\n vertexBuffer = overrideVertexBuffers[kind];\n }\n if (!vertexBuffer) {\n vertexBuffer = vertexBuffers[kind];\n }\n if (vertexBuffer) {\n const buffer = vertexBuffer.getBuffer();\n if (buffer && buffer.nativeVertexBuffer) {\n this._engine.recordVertexBuffer(vertexArray, buffer.nativeVertexBuffer, location, vertexBuffer.byteOffset, vertexBuffer.byteStride, vertexBuffer.getSize(), this._getNativeAttribType(vertexBuffer.type), vertexBuffer.normalized, vertexBuffer.getInstanceDivisor());\n }\n }\n }\n }\n }\n bindBuffers(vertexBuffers, indexBuffer, effect) {\n if (this._boundBuffersVertexArray) {\n this._deleteVertexArray(this._boundBuffersVertexArray);\n }\n this._boundBuffersVertexArray = this._engine.createVertexArray();\n this._recordVertexArrayObject(this._boundBuffersVertexArray, vertexBuffers, indexBuffer, effect);\n this.bindVertexArrayObject(this._boundBuffersVertexArray);\n }\n recordVertexArrayObject(vertexBuffers, indexBuffer, effect, overrideVertexBuffers) {\n const vertexArray = this._engine.createVertexArray();\n this._recordVertexArrayObject(vertexArray, vertexBuffers, indexBuffer, effect, overrideVertexBuffers);\n return vertexArray;\n }\n _deleteVertexArray(vertexArray) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(vertexArray);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n bindVertexArrayObject(vertexArray) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(vertexArray);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n releaseVertexArrayObject(vertexArray) {\n this._deleteVertexArray(vertexArray);\n }\n getAttributes(pipelineContext, attributesNames) {\n const nativePipelineContext = pipelineContext;\n return this._engine.getAttributes(nativePipelineContext.nativeProgram, attributesNames);\n }\n /**\n * Draw a list of indexed primitives\n * @param fillMode defines the primitive to use\n * @param indexStart defines the starting index\n * @param indexCount defines the number of index to draw\n * @param instancesCount defines the number of instances to draw (if instantiation is enabled)\n */\n drawElementsType(fillMode, indexStart, indexCount, instancesCount) {\n // Apply states\n this._drawCalls.addCount(1, false);\n // TODO: Make this implementation more robust like core Engine version.\n // Render\n //var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;\n //var mult = this._uintIndicesCurrentlySet ? 4 : 2;\n // if (instancesCount) {\n // this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);\n // } else {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXED);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(fillMode);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(indexStart);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(indexCount);\n this._commandBufferEncoder.finishEncodingCommand();\n // }\n }\n /**\n * Draw a list of unindexed primitives\n * @param fillMode defines the primitive to use\n * @param verticesStart defines the index of first vertex to draw\n * @param verticesCount defines the count of vertices to draw\n * @param instancesCount defines the number of instances to draw (if instantiation is enabled)\n */\n drawArraysType(fillMode, verticesStart, verticesCount, instancesCount) {\n // Apply states\n this._drawCalls.addCount(1, false);\n // TODO: Make this implementation more robust like core Engine version.\n // if (instancesCount) {\n // this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);\n // } else {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAW);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(fillMode);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(verticesStart);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(verticesCount);\n this._commandBufferEncoder.finishEncodingCommand();\n // }\n }\n createPipelineContext() {\n return new NativePipelineContext(this);\n }\n createMaterialContext() {\n return undefined;\n }\n createDrawContext() {\n return undefined;\n }\n _preparePipelineContext(pipelineContext, vertexSourceCode, fragmentSourceCode, createAsRaw, _rawVertexSourceCode, _rawFragmentSourceCode, _rebuildRebind, defines) {\n const nativePipelineContext = pipelineContext;\n if (createAsRaw) {\n nativePipelineContext.nativeProgram = this.createRawShaderProgram();\n }\n else {\n nativePipelineContext.nativeProgram = this.createShaderProgram(pipelineContext, vertexSourceCode, fragmentSourceCode, defines);\n }\n }\n isAsync(pipelineContext) {\n return !!(pipelineContext.isAsync && this._engine.createProgramAsync);\n }\n /**\n * @internal\n */\n _executeWhenRenderingStateIsCompiled(pipelineContext, action) {\n const nativePipelineContext = pipelineContext;\n if (!this.isAsync(pipelineContext)) {\n action();\n return;\n }\n const oldHandler = nativePipelineContext.onCompiled;\n if (oldHandler) {\n nativePipelineContext.onCompiled = () => {\n oldHandler();\n action();\n };\n }\n else {\n nativePipelineContext.onCompiled = action;\n }\n }\n createRawShaderProgram() {\n throw new Error(\"Not Supported\");\n }\n createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines) {\n const nativePipelineContext = pipelineContext;\n if (nativePipelineContext.nativeProgram) {\n throw new Error(\"Tried to create a second program in the same NativePipelineContext\");\n }\n this.onBeforeShaderCompilationObservable.notifyObservers(this);\n const vertexInliner = new ShaderCodeInliner(vertexCode);\n vertexInliner.processCode();\n vertexCode = vertexInliner.code;\n const fragmentInliner = new ShaderCodeInliner(fragmentCode);\n fragmentInliner.processCode();\n fragmentCode = fragmentInliner.code;\n vertexCode = ThinEngine._ConcatenateShader(vertexCode, defines);\n fragmentCode = ThinEngine._ConcatenateShader(fragmentCode, defines);\n const onSuccess = () => {\n var _a;\n nativePipelineContext.isCompiled = true;\n (_a = nativePipelineContext.onCompiled) === null || _a === void 0 ? void 0 : _a.call(nativePipelineContext);\n this.onAfterShaderCompilationObservable.notifyObservers(this);\n };\n if (this.isAsync(pipelineContext)) {\n return this._engine.createProgramAsync(vertexCode, fragmentCode, onSuccess, (error) => {\n nativePipelineContext.compilationError = error;\n });\n }\n else {\n try {\n const program = (nativePipelineContext.nativeProgram = this._engine.createProgram(vertexCode, fragmentCode));\n onSuccess();\n return program;\n }\n catch (e) {\n const message = e === null || e === void 0 ? void 0 : e.message;\n throw new Error(\"SHADER ERROR\" + (typeof message === \"string\" ? \"\\n\" + message : \"\"));\n }\n }\n }\n /**\n * Inline functions in shader code that are marked to be inlined\n * @param code code to inline\n * @returns inlined code\n */\n inlineShaderCode(code) {\n const sci = new ShaderCodeInliner(code);\n sci.debug = false;\n sci.processCode();\n return sci.code;\n }\n _setProgram(program) {\n if (this._currentProgram !== program) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETPROGRAM);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(program);\n this._commandBufferEncoder.finishEncodingCommand();\n this._currentProgram = program;\n }\n }\n _deletePipelineContext(pipelineContext) {\n const nativePipelineContext = pipelineContext;\n if (nativePipelineContext && nativePipelineContext.nativeProgram) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(nativePipelineContext.nativeProgram);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n }\n getUniforms(pipelineContext, uniformsNames) {\n const nativePipelineContext = pipelineContext;\n return this._engine.getUniforms(nativePipelineContext.nativeProgram, uniformsNames);\n }\n bindUniformBlock(pipelineContext, blockName, index) {\n // TODO\n throw new Error(\"Not Implemented\");\n }\n bindSamplers(effect) {\n const nativePipelineContext = effect.getPipelineContext();\n this._setProgram(nativePipelineContext.nativeProgram);\n // TODO: share this with engine?\n const samplers = effect.getSamplers();\n for (let index = 0; index < samplers.length; index++) {\n const uniform = effect.getUniform(samplers[index]);\n if (uniform) {\n this._boundUniforms[index] = uniform;\n }\n }\n this._currentEffect = null;\n }\n getRenderWidth(useScreen = false) {\n if (!useScreen && this._currentRenderTarget) {\n return this._currentRenderTarget.width;\n }\n return this._engine.getRenderWidth();\n }\n getRenderHeight(useScreen = false) {\n if (!useScreen && this._currentRenderTarget) {\n return this._currentRenderTarget.height;\n }\n return this._engine.getRenderHeight();\n }\n setViewport(viewport, requiredWidth, requiredHeight) {\n this._cachedViewport = viewport;\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETVIEWPORT);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(viewport.x);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(viewport.y);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(viewport.width);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(viewport.height);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n enableScissor(x, y, width, height) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSCISSOR);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(x);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(y);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(width);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(height);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n disableScissor() {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSCISSOR);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(0);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(0);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(0);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(0);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n setState(culling, zOffset = 0, force, reverseSide = false, cullBackFaces, stencil, zOffsetUnits = 0) {\n var _a, _b;\n this._zOffset = zOffset;\n this._zOffsetUnits = zOffsetUnits;\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTATE);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(culling ? 1 : 0);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(zOffset);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(zOffsetUnits);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(((_b = (_a = this.cullBackFaces) !== null && _a !== void 0 ? _a : cullBackFaces) !== null && _b !== void 0 ? _b : true) ? 1 : 0);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(reverseSide ? 1 : 0);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n /**\n * Gets the client rect of native canvas. Needed for InputManager.\n * @returns a client rectangle\n */\n getInputElementClientRect() {\n const rect = {\n bottom: this.getRenderHeight(),\n height: this.getRenderHeight(),\n left: 0,\n right: this.getRenderWidth(),\n top: 0,\n width: this.getRenderWidth(),\n x: 0,\n y: 0,\n toJSON: () => { },\n };\n return rect;\n }\n /**\n * Set the z offset Factor to apply to current rendering\n * @param value defines the offset to apply\n */\n setZOffset(value) {\n if (value !== this._zOffset) {\n this._zOffset = value;\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSET);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer ? -value : value);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n }\n /**\n * Gets the current value of the zOffset Factor\n * @returns the current zOffset Factor state\n */\n getZOffset() {\n return this._zOffset;\n }\n /**\n * Set the z offset Units to apply to current rendering\n * @param value defines the offset to apply\n */\n setZOffsetUnits(value) {\n if (value !== this._zOffsetUnits) {\n this._zOffsetUnits = value;\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSETUNITS);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer ? -value : value);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n }\n /**\n * Gets the current value of the zOffset Units\n * @returns the current zOffset Units state\n */\n getZOffsetUnits() {\n return this._zOffsetUnits;\n }\n /**\n * Enable or disable depth buffering\n * @param enable defines the state to set\n */\n setDepthBuffer(enable) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(enable ? this._currentDepthTest : _native.Engine.DEPTH_TEST_ALWAYS);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n /**\n * Gets a boolean indicating if depth writing is enabled\n * @returns the current depth writing state\n */\n getDepthWrite() {\n return this._depthWrite;\n }\n getDepthFunction() {\n switch (this._currentDepthTest) {\n case _native.Engine.DEPTH_TEST_NEVER:\n return 512;\n case _native.Engine.DEPTH_TEST_ALWAYS:\n return 519;\n case _native.Engine.DEPTH_TEST_GREATER:\n return 516;\n case _native.Engine.DEPTH_TEST_GEQUAL:\n return 518;\n case _native.Engine.DEPTH_TEST_NOTEQUAL:\n return 517;\n case _native.Engine.DEPTH_TEST_EQUAL:\n return 514;\n case _native.Engine.DEPTH_TEST_LESS:\n return 513;\n case _native.Engine.DEPTH_TEST_LEQUAL:\n return 515;\n }\n return null;\n }\n setDepthFunction(depthFunc) {\n let nativeDepthFunc = 0;\n switch (depthFunc) {\n case 512:\n nativeDepthFunc = _native.Engine.DEPTH_TEST_NEVER;\n break;\n case 519:\n nativeDepthFunc = _native.Engine.DEPTH_TEST_ALWAYS;\n break;\n case 516:\n nativeDepthFunc = _native.Engine.DEPTH_TEST_GREATER;\n break;\n case 518:\n nativeDepthFunc = _native.Engine.DEPTH_TEST_GEQUAL;\n break;\n case 517:\n nativeDepthFunc = _native.Engine.DEPTH_TEST_NOTEQUAL;\n break;\n case 514:\n nativeDepthFunc = _native.Engine.DEPTH_TEST_EQUAL;\n break;\n case 513:\n nativeDepthFunc = _native.Engine.DEPTH_TEST_LESS;\n break;\n case 515:\n nativeDepthFunc = _native.Engine.DEPTH_TEST_LEQUAL;\n break;\n }\n this._currentDepthTest = nativeDepthFunc;\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(this._currentDepthTest);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n /**\n * Enable or disable depth writing\n * @param enable defines the state to set\n */\n setDepthWrite(enable) {\n this._depthWrite = enable;\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHWRITE);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(enable));\n this._commandBufferEncoder.finishEncodingCommand();\n }\n /**\n * Enable or disable color writing\n * @param enable defines the state to set\n */\n setColorWrite(enable) {\n this._colorWrite = enable;\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETCOLORWRITE);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(enable));\n this._commandBufferEncoder.finishEncodingCommand();\n }\n /**\n * Gets a boolean indicating if color writing is enabled\n * @returns the current color writing state\n */\n getColorWrite() {\n return this._colorWrite;\n }\n applyStencil() {\n this._setStencil(this._stencilMask, this._getStencilOpFail(this._stencilOpStencilFail), this._getStencilDepthFail(this._stencilOpDepthFail), this._getStencilDepthPass(this._stencilOpStencilDepthPass), this._getStencilFunc(this._stencilFunc), this._stencilFuncRef);\n }\n _setStencil(mask, stencilOpFail, depthOpFail, depthOpPass, func, ref) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(mask);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(stencilOpFail);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(depthOpFail);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(depthOpPass);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(func);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(ref);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n /**\n * Enable or disable the stencil buffer\n * @param enable defines if the stencil buffer must be enabled or disabled\n */\n setStencilBuffer(enable) {\n this._stencilTest = enable;\n if (enable) {\n this.applyStencil();\n }\n else {\n this._setStencil(255, _native.Engine.STENCIL_OP_FAIL_S_KEEP, _native.Engine.STENCIL_OP_FAIL_Z_KEEP, _native.Engine.STENCIL_OP_PASS_Z_KEEP, _native.Engine.STENCIL_TEST_ALWAYS, 0);\n }\n }\n /**\n * Gets a boolean indicating if stencil buffer is enabled\n * @returns the current stencil buffer state\n */\n getStencilBuffer() {\n return this._stencilTest;\n }\n /**\n * Gets the current stencil operation when stencil passes\n * @returns a number defining stencil operation to use when stencil passes\n */\n getStencilOperationPass() {\n return this._stencilOpStencilDepthPass;\n }\n /**\n * Sets the stencil operation to use when stencil passes\n * @param operation defines the stencil operation to use when stencil passes\n */\n setStencilOperationPass(operation) {\n this._stencilOpStencilDepthPass = operation;\n this.applyStencil();\n }\n /**\n * Sets the current stencil mask\n * @param mask defines the new stencil mask to use\n */\n setStencilMask(mask) {\n this._stencilMask = mask;\n this.applyStencil();\n }\n /**\n * Sets the current stencil function\n * @param stencilFunc defines the new stencil function to use\n */\n setStencilFunction(stencilFunc) {\n this._stencilFunc = stencilFunc;\n this.applyStencil();\n }\n /**\n * Sets the current stencil reference\n * @param reference defines the new stencil reference to use\n */\n setStencilFunctionReference(reference) {\n this._stencilFuncRef = reference;\n this.applyStencil();\n }\n /**\n * Sets the current stencil mask\n * @param mask defines the new stencil mask to use\n */\n setStencilFunctionMask(mask) {\n this._stencilFuncMask = mask;\n }\n /**\n * Sets the stencil operation to use when stencil fails\n * @param operation defines the stencil operation to use when stencil fails\n */\n setStencilOperationFail(operation) {\n this._stencilOpStencilFail = operation;\n this.applyStencil();\n }\n /**\n * Sets the stencil operation to use when depth fails\n * @param operation defines the stencil operation to use when depth fails\n */\n setStencilOperationDepthFail(operation) {\n this._stencilOpDepthFail = operation;\n this.applyStencil();\n }\n /**\n * Gets the current stencil mask\n * @returns a number defining the new stencil mask to use\n */\n getStencilMask() {\n return this._stencilMask;\n }\n /**\n * Gets the current stencil function\n * @returns a number defining the stencil function to use\n */\n getStencilFunction() {\n return this._stencilFunc;\n }\n /**\n * Gets the current stencil reference value\n * @returns a number defining the stencil reference value to use\n */\n getStencilFunctionReference() {\n return this._stencilFuncRef;\n }\n /**\n * Gets the current stencil mask\n * @returns a number defining the stencil mask to use\n */\n getStencilFunctionMask() {\n return this._stencilFuncMask;\n }\n /**\n * Gets the current stencil operation when stencil fails\n * @returns a number defining stencil operation to use when stencil fails\n */\n getStencilOperationFail() {\n return this._stencilOpStencilFail;\n }\n /**\n * Gets the current stencil operation when depth fails\n * @returns a number defining stencil operation to use when depth fails\n */\n getStencilOperationDepthFail() {\n return this._stencilOpDepthFail;\n }\n /**\n * Sets alpha constants used by some alpha blending modes\n * @param r defines the red component\n * @param g defines the green component\n * @param b defines the blue component\n * @param a defines the alpha component\n */\n setAlphaConstants(r, g, b, a) {\n throw new Error(\"Setting alpha blend constant color not yet implemented.\");\n }\n /**\n * Sets the current alpha mode\n * @param mode defines the mode to use (one of the BABYLON.undefined)\n * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/transparent_rendering\n */\n setAlphaMode(mode, noDepthWriteChange = false) {\n if (this._alphaMode === mode) {\n return;\n }\n const nativeMode = this._getNativeAlphaMode(mode);\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(nativeMode);\n this._commandBufferEncoder.finishEncodingCommand();\n if (!noDepthWriteChange) {\n this.setDepthWrite(mode === 0);\n }\n this._alphaMode = mode;\n }\n /**\n * Gets the current alpha mode\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/transparent_rendering\n * @returns the current alpha mode\n */\n getAlphaMode() {\n return this._alphaMode;\n }\n setInt(uniform, int) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsInt32(int);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setIntArray(uniform, array) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsInt32s(array);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setIntArray2(uniform, array) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsInt32s(array);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setIntArray3(uniform, array) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsInt32s(array);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setIntArray4(uniform, array) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsInt32s(array);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setFloatArray(uniform, array) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsFloat32s(array);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setFloatArray2(uniform, array) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsFloat32s(array);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setFloatArray3(uniform, array) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsFloat32s(array);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setFloatArray4(uniform, array) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsFloat32s(array);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setArray(uniform, array) {\n if (!uniform) {\n return false;\n }\n return this.setFloatArray(uniform, new Float32Array(array));\n }\n setArray2(uniform, array) {\n if (!uniform) {\n return false;\n }\n return this.setFloatArray2(uniform, new Float32Array(array));\n }\n setArray3(uniform, array) {\n if (!uniform) {\n return false;\n }\n return this.setFloatArray3(uniform, new Float32Array(array));\n }\n setArray4(uniform, array) {\n if (!uniform) {\n return false;\n }\n return this.setFloatArray4(uniform, new Float32Array(array));\n }\n setMatrices(uniform, matrices) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsFloat32s(matrices);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setMatrix3x3(uniform, matrix) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsFloat32s(matrix);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setMatrix2x2(uniform, matrix) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsFloat32s(matrix);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setFloat(uniform, value) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(value);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setFloat2(uniform, x, y) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT2);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(x);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(y);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setFloat3(uniform, x, y, z) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(x);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(y);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(z);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setFloat4(uniform, x, y, z, w) {\n if (!uniform) {\n return false;\n }\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(x);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(y);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(z);\n this._commandBufferEncoder.encodeCommandArgAsFloat32(w);\n this._commandBufferEncoder.finishEncodingCommand();\n return true;\n }\n setColor3(uniform, color3) {\n if (!uniform) {\n return false;\n }\n this.setFloat3(uniform, color3.r, color3.g, color3.b);\n return true;\n }\n setColor4(uniform, color3, alpha) {\n if (!uniform) {\n return false;\n }\n this.setFloat4(uniform, color3.r, color3.g, color3.b, alpha);\n return true;\n }\n wipeCaches(bruteForce) {\n if (this.preventCacheWipeBetweenFrames) {\n return;\n }\n this.resetTextureCache();\n this._currentEffect = null;\n if (bruteForce) {\n this._currentProgram = null;\n this._stencilStateComposer.reset();\n this._depthCullingState.reset();\n this._alphaState.reset();\n }\n this._cachedVertexBuffers = null;\n this._cachedIndexBuffer = null;\n this._cachedEffectForVertexBuffers = null;\n }\n _createTexture() {\n return this._engine.createTexture();\n }\n _deleteTexture(texture) {\n if (texture) {\n this._engine.deleteTexture(texture);\n }\n }\n /**\n * Update the content of a dynamic texture\n * @param texture defines the texture to update\n * @param canvas defines the canvas containing the source\n * @param invertY defines if data must be stored with Y axis inverted\n * @param premulAlpha defines if alpha is stored as premultiplied\n * @param format defines the format of the data\n */\n updateDynamicTexture(texture, canvas, invertY, premulAlpha = false, format) {\n if (premulAlpha === void 0) {\n premulAlpha = false;\n }\n if (!!texture && !!texture._hardwareTexture) {\n const source = canvas.getCanvasTexture();\n const destination = texture._hardwareTexture.underlyingResource;\n this._engine.copyTexture(destination, source);\n texture.isReady = true;\n }\n }\n createDynamicTexture(width, height, generateMipMaps, samplingMode) {\n // it's not possible to create 0x0 texture sized. Many bgfx methods assume texture size is at least 1x1(best case).\n // Worst case is getting a crash/assert.\n width = Math.max(width, 1);\n height = Math.max(height, 1);\n return this.createRawTexture(new Uint8Array(width * height * 4), width, height, 5, false, false, samplingMode);\n }\n createVideoElement(constraints) {\n // create native object depending on stream. Only NativeCamera is supported for now.\n if (this._camera) {\n return this._camera.createVideo(constraints);\n }\n return null;\n }\n updateVideoTexture(texture, video, invertY) {\n if (texture && texture._hardwareTexture && this._camera) {\n const webGLTexture = texture._hardwareTexture.underlyingResource;\n this._camera.updateVideoTexture(webGLTexture, video, invertY);\n }\n }\n createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, compression = null, type = 0, creationFlags = 0, useSRGBBuffer = false) {\n const texture = new InternalTexture(this, InternalTextureSource.Raw);\n texture.format = format;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.invertY = invertY;\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = texture.baseWidth;\n texture.height = texture.baseHeight;\n texture._compression = compression;\n texture.type = type;\n texture._useSRGBBuffer = this._getUseSRGBBuffer(useSRGBBuffer, !generateMipMaps);\n this.updateRawTexture(texture, data, format, invertY, compression, type, texture._useSRGBBuffer);\n if (texture._hardwareTexture) {\n const webGLTexture = texture._hardwareTexture.underlyingResource;\n const filter = this._getNativeSamplingMode(samplingMode);\n this._setTextureSampling(webGLTexture, filter);\n }\n this._internalTexturesCache.push(texture);\n return texture;\n }\n createRawTexture2DArray(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression = null, textureType = 0) {\n const texture = new InternalTexture(this, InternalTextureSource.Raw2DArray);\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.baseDepth = depth;\n texture.width = width;\n texture.height = height;\n texture.depth = depth;\n texture.format = format;\n texture.type = textureType;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.is2DArray = true;\n if (texture._hardwareTexture) {\n const nativeTexture = texture._hardwareTexture.underlyingResource;\n this._engine.loadRawTexture2DArray(nativeTexture, data, width, height, depth, this._getNativeTextureFormat(format, textureType), generateMipMaps, invertY);\n const filter = this._getNativeSamplingMode(samplingMode);\n this._setTextureSampling(nativeTexture, filter);\n }\n texture.isReady = true;\n this._internalTexturesCache.push(texture);\n return texture;\n }\n updateRawTexture(texture, bufferView, format, invertY, compression = null, type = 0, useSRGBBuffer = false) {\n if (!texture) {\n return;\n }\n if (bufferView && texture._hardwareTexture) {\n const underlyingResource = texture._hardwareTexture.underlyingResource;\n this._engine.loadRawTexture(underlyingResource, bufferView, texture.width, texture.height, this._getNativeTextureFormat(format, type), texture.generateMipMaps, texture.invertY);\n }\n texture.isReady = true;\n }\n // TODO: Refactor to share more logic with babylon.engine.ts version.\n /**\n * Usually called from Texture.ts.\n * Passed information to create a NativeTexture\n * @param url defines a value which contains one of the following:\n * * A conventional http URL, e.g. 'http://...' or 'file://...'\n * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'\n * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'\n * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file\n * @param invertY when true, image is flipped when loaded. You probably want true. Certain compressed textures may invert this if their default is inverted (eg. ktx)\n * @param scene needed for loading to the correct scene\n * @param samplingMode mode with should be used sample / access the texture (Default: Texture.TRILINEAR_SAMPLINGMODE)\n * @param onLoad optional callback to be called upon successful completion\n * @param onError optional callback to be called upon failure\n * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob\n * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities\n * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures\n * @param forcedExtension defines the extension to use to pick the right loader\n * @param mimeType defines an optional mime type\n * @param loaderOptions options to be passed to the loader\n * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)\n * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU).\n * @returns a InternalTexture for assignment back into BABYLON.Texture\n */\n createTexture(url, noMipmap, invertY, scene, samplingMode = 3, onLoad = null, onError = null, buffer = null, fallback = null, format = null, forcedExtension = null, mimeType, loaderOptions, creationFlags, useSRGBBuffer = false) {\n url = url || \"\";\n const fromData = url.substr(0, 5) === \"data:\";\n //const fromBlob = url.substr(0, 5) === \"blob:\";\n const isBase64 = fromData && url.indexOf(\";base64,\") !== -1;\n const texture = fallback ? fallback : new InternalTexture(this, InternalTextureSource.Url);\n const originalUrl = url;\n if (this._transformTextureUrl && !isBase64 && !fallback && !buffer) {\n url = this._transformTextureUrl(url);\n }\n // establish the file extension, if possible\n const lastDot = url.lastIndexOf(\".\");\n const extension = forcedExtension ? forcedExtension : lastDot > -1 ? url.substring(lastDot).toLowerCase() : \"\";\n let loader = null;\n for (const availableLoader of Engine._TextureLoaders) {\n if (availableLoader.canLoad(extension)) {\n loader = availableLoader;\n break;\n }\n }\n if (scene) {\n scene.addPendingData(texture);\n }\n texture.url = url;\n texture.generateMipMaps = !noMipmap;\n texture.samplingMode = samplingMode;\n texture.invertY = invertY;\n texture._useSRGBBuffer = this._getUseSRGBBuffer(useSRGBBuffer, noMipmap);\n if (!this.doNotHandleContextLost) {\n // Keep a link to the buffer only if we plan to handle context lost\n texture._buffer = buffer;\n }\n let onLoadObserver = null;\n if (onLoad && !fallback) {\n onLoadObserver = texture.onLoadedObservable.add(onLoad);\n }\n if (!fallback) {\n this._internalTexturesCache.push(texture);\n }\n const onInternalError = (message, exception) => {\n if (scene) {\n scene.removePendingData(texture);\n }\n if (url === originalUrl) {\n if (onLoadObserver) {\n texture.onLoadedObservable.remove(onLoadObserver);\n }\n if (EngineStore.UseFallbackTexture) {\n this.createTexture(EngineStore.FallbackTexture, noMipmap, texture.invertY, scene, samplingMode, null, onError, buffer, texture);\n }\n if (onError) {\n onError((message || \"Unknown error\") + (EngineStore.UseFallbackTexture ? \" - Fallback texture was used\" : \"\"), exception);\n }\n }\n else {\n // fall back to the original url if the transformed url fails to load\n Logger.Warn(`Failed to load ${url}, falling back to ${originalUrl}`);\n this.createTexture(originalUrl, noMipmap, texture.invertY, scene, samplingMode, onLoad, onError, buffer, texture, format, forcedExtension, mimeType, loaderOptions);\n }\n };\n // processing for non-image formats\n if (loader) {\n throw new Error(\"Loading textures from IInternalTextureLoader not yet implemented.\");\n }\n else {\n const onload = (data) => {\n if (!texture._hardwareTexture) {\n if (scene) {\n scene.removePendingData(texture);\n }\n return;\n }\n const underlyingResource = texture._hardwareTexture.underlyingResource;\n this._engine.loadTexture(underlyingResource, data, !noMipmap, invertY, useSRGBBuffer, () => {\n texture.baseWidth = this._engine.getTextureWidth(underlyingResource);\n texture.baseHeight = this._engine.getTextureHeight(underlyingResource);\n texture.width = texture.baseWidth;\n texture.height = texture.baseHeight;\n texture.isReady = true;\n const filter = this._getNativeSamplingMode(samplingMode);\n this._setTextureSampling(underlyingResource, filter);\n if (scene) {\n scene.removePendingData(texture);\n }\n texture.onLoadedObservable.notifyObservers(texture);\n texture.onLoadedObservable.clear();\n }, () => {\n throw new Error(\"Could not load a native texture.\");\n });\n };\n if (fromData && buffer) {\n if (buffer instanceof ArrayBuffer) {\n onload(new Uint8Array(buffer));\n }\n else if (ArrayBuffer.isView(buffer)) {\n onload(buffer);\n }\n else if (typeof buffer === \"string\") {\n onload(new Uint8Array(Tools.DecodeBase64(buffer)));\n }\n else {\n throw new Error(\"Unsupported buffer type\");\n }\n }\n else {\n if (isBase64) {\n onload(new Uint8Array(Tools.DecodeBase64(url)));\n }\n else {\n this._loadFile(url, (data) => onload(new Uint8Array(data)), undefined, undefined, true, (request, exception) => {\n onInternalError(\"Unable to load \" + (request ? request.responseURL : url, exception));\n });\n }\n }\n }\n return texture;\n }\n /**\n * Wraps an external native texture in a Babylon texture.\n * @param texture defines the external texture\n * @param hasMipMaps defines whether the external texture has mip maps\n * @param samplingMode defines the sampling mode for the external texture (default: 3)\n * @returns the babylon internal texture\n */\n wrapNativeTexture(texture, hasMipMaps = false, samplingMode = 3) {\n const hardwareTexture = new NativeHardwareTexture(texture, this._engine);\n const internalTexture = new InternalTexture(this, InternalTextureSource.Unknown, true);\n internalTexture._hardwareTexture = hardwareTexture;\n internalTexture.isReady = true;\n internalTexture.useMipMaps = hasMipMaps;\n this.updateTextureSamplingMode(samplingMode, internalTexture);\n return internalTexture;\n }\n /**\n * Wraps an external web gl texture in a Babylon texture.\n * @returns the babylon internal texture\n */\n wrapWebGLTexture() {\n throw new Error(\"wrapWebGLTexture is not supported, use wrapNativeTexture instead.\");\n }\n _createDepthStencilTexture(size, options, rtWrapper) {\n // TODO: options?\n const nativeRTWrapper = rtWrapper;\n const texture = new InternalTexture(this, InternalTextureSource.DepthStencil);\n const width = size.width || size;\n const height = size.height || size;\n const framebuffer = this._engine.createFrameBuffer(texture._hardwareTexture.underlyingResource, width, height, true, true);\n nativeRTWrapper._framebufferDepthStencil = framebuffer;\n return texture;\n }\n /**\n * @internal\n */\n _releaseFramebufferObjects(framebuffer) {\n if (framebuffer) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(framebuffer);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n }\n /**\n * @internal Engine abstraction for loading and creating an image bitmap from a given source string.\n * @param imageSource source to load the image from.\n * @param options An object that sets options for the image's extraction.\n * @returns ImageBitmap\n */\n _createImageBitmapFromSource(imageSource, options) {\n const promise = new Promise((resolve, reject) => {\n const image = this.createCanvasImage();\n image.onload = () => {\n try {\n const imageBitmap = this._engine.createImageBitmap(image);\n resolve(imageBitmap);\n }\n catch (error) {\n reject(`Error loading image ${image.src} with exception: ${error}`);\n }\n };\n image.onerror = (error) => {\n reject(`Error loading image ${image.src} with exception: ${error}`);\n };\n image.src = imageSource;\n });\n return promise;\n }\n /**\n * Engine abstraction for createImageBitmap\n * @param image source for image\n * @param options An object that sets options for the image's extraction.\n * @returns ImageBitmap\n */\n createImageBitmap(image, options) {\n return new Promise((resolve, reject) => {\n if (Array.isArray(image)) {\n const arr = image;\n if (arr.length) {\n const image = this._engine.createImageBitmap(arr[0]);\n if (image) {\n resolve(image);\n return;\n }\n }\n }\n reject(`Unsupported data for createImageBitmap.`);\n });\n }\n /**\n * Resize an image and returns the image data as an uint8array\n * @param image image to resize\n * @param bufferWidth destination buffer width\n * @param bufferHeight destination buffer height\n * @returns an uint8array containing RGBA values of bufferWidth * bufferHeight size\n */\n resizeImageBitmap(image, bufferWidth, bufferHeight) {\n return this._engine.resizeImageBitmap(image, bufferWidth, bufferHeight);\n }\n /**\n * Creates a cube texture\n * @param rootUrl defines the url where the files to load is located\n * @param scene defines the current scene\n * @param files defines the list of files to load (1 per face)\n * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)\n * @param onLoad defines an optional callback raised when the texture is loaded\n * @param onError defines an optional callback raised if there is an issue to load the texture\n * @param format defines the format of the data\n * @param forcedExtension defines the extension to use to pick the right loader\n * @param createPolynomials if a polynomial sphere should be created for the cube texture\n * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness\n * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness\n * @param fallback defines texture to use while falling back when (compressed) texture file not found.\n * @param loaderOptions options to be passed to the loader\n * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU).\n * @returns the cube texture as an InternalTexture\n */\n createCubeTexture(rootUrl, scene, files, noMipmap, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = false, lodScale = 0, lodOffset = 0, fallback = null, loaderOptions, useSRGBBuffer = false) {\n const texture = fallback ? fallback : new InternalTexture(this, InternalTextureSource.Cube);\n texture.isCube = true;\n texture.url = rootUrl;\n texture.generateMipMaps = !noMipmap;\n texture._lodGenerationScale = lodScale;\n texture._lodGenerationOffset = lodOffset;\n if (!this._doNotHandleContextLost) {\n texture._extension = forcedExtension;\n texture._files = files;\n }\n const lastDot = rootUrl.lastIndexOf(\".\");\n const extension = forcedExtension ? forcedExtension : lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : \"\";\n // TODO: use texture loader to load env files?\n if (extension === \".env\") {\n const onloaddata = (data) => {\n const info = GetEnvInfo(data);\n texture.width = info.width;\n texture.height = info.width;\n UploadEnvSpherical(texture, info);\n const specularInfo = info.specular;\n if (!specularInfo) {\n throw new Error(`Nothing else parsed so far`);\n }\n texture._lodGenerationScale = specularInfo.lodGenerationScale;\n const imageData = CreateImageDataArrayBufferViews(data, info);\n texture.format = 5;\n texture.type = 0;\n texture.generateMipMaps = true;\n texture.getEngine().updateTextureSamplingMode(Texture.TRILINEAR_SAMPLINGMODE, texture);\n texture._isRGBD = true;\n texture.invertY = true;\n this._engine.loadCubeTextureWithMips(texture._hardwareTexture.underlyingResource, imageData, false, useSRGBBuffer, () => {\n texture.isReady = true;\n if (onLoad) {\n onLoad();\n }\n }, () => {\n throw new Error(\"Could not load a native cube texture.\");\n });\n };\n if (files && files.length === 6) {\n throw new Error(`Multi-file loading not allowed on env files.`);\n }\n else {\n const onInternalError = (request, exception) => {\n if (onError && request) {\n onError(request.status + \" \" + request.statusText, exception);\n }\n };\n this._loadFile(rootUrl, (data) => onloaddata(new Uint8Array(data)), undefined, undefined, true, onInternalError);\n }\n }\n else {\n if (!files || files.length !== 6) {\n throw new Error(\"Cannot load cubemap because 6 files were not defined\");\n }\n // Reorder from [+X, +Y, +Z, -X, -Y, -Z] to [+X, -X, +Y, -Y, +Z, -Z].\n const reorderedFiles = [files[0], files[3], files[1], files[4], files[2], files[5]];\n Promise.all(reorderedFiles.map((file) => Tools.LoadFileAsync(file).then((data) => new Uint8Array(data))))\n .then((data) => {\n return new Promise((resolve, reject) => {\n this._engine.loadCubeTexture(texture._hardwareTexture.underlyingResource, data, !noMipmap, true, useSRGBBuffer, resolve, reject);\n });\n })\n .then(() => {\n texture.isReady = true;\n if (onLoad) {\n onLoad();\n }\n }, (error) => {\n if (onError) {\n onError(`Failed to load cubemap: ${error.message}`, error);\n }\n });\n }\n this._internalTexturesCache.push(texture);\n return texture;\n }\n /** @internal */\n _createHardwareTexture() {\n return new NativeHardwareTexture(this._createTexture(), this._engine);\n }\n /** @internal */\n _createHardwareRenderTargetWrapper(isMulti, isCube, size) {\n const rtWrapper = new NativeRenderTargetWrapper(isMulti, isCube, size, this);\n this._renderTargetWrapperCache.push(rtWrapper);\n return rtWrapper;\n }\n /** @internal */\n _createInternalTexture(size, options, _delayGPUTextureCreation = true, source = InternalTextureSource.Unknown) {\n var _a;\n let generateMipMaps = false;\n let type = 0;\n let samplingMode = 3;\n let format = 5;\n let useSRGBBuffer = false;\n let samples = 1;\n let label;\n if (options !== undefined && typeof options === \"object\") {\n generateMipMaps = !!options.generateMipMaps;\n type = options.type === undefined ? 0 : options.type;\n samplingMode = options.samplingMode === undefined ? 3 : options.samplingMode;\n format = options.format === undefined ? 5 : options.format;\n useSRGBBuffer = options.useSRGBBuffer === undefined ? false : options.useSRGBBuffer;\n samples = (_a = options.samples) !== null && _a !== void 0 ? _a : 1;\n label = options.label;\n }\n else {\n generateMipMaps = !!options;\n }\n useSRGBBuffer && (useSRGBBuffer = this._caps.supportSRGBBuffers && (this.webGLVersion > 1 || this.isWebGPU));\n if (type === 1 && !this._caps.textureFloatLinearFiltering) {\n // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE\n samplingMode = 1;\n }\n else if (type === 2 && !this._caps.textureHalfFloatLinearFiltering) {\n // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE\n samplingMode = 1;\n }\n if (type === 1 && !this._caps.textureFloat) {\n type = 0;\n Logger.Warn(\"Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE\");\n }\n const texture = new InternalTexture(this, source);\n const width = size.width || size;\n const height = size.height || size;\n const layers = size.layers || 0;\n if (layers !== 0) {\n throw new Error(\"Texture layers are not supported in Babylon Native\");\n }\n const nativeTexture = texture._hardwareTexture.underlyingResource;\n const nativeTextureFormat = this._getNativeTextureFormat(format, type);\n // REVIEW: We are always setting the renderTarget flag as we don't know whether the texture will be used as a render target.\n this._engine.initializeTexture(nativeTexture, width, height, generateMipMaps, nativeTextureFormat, true, useSRGBBuffer);\n this._setTextureSampling(nativeTexture, this._getNativeSamplingMode(samplingMode));\n texture._useSRGBBuffer = useSRGBBuffer;\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = width;\n texture.height = height;\n texture.depth = layers;\n texture.isReady = true;\n texture.samples = samples;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.type = type;\n texture.format = format;\n texture.label = label;\n this._internalTexturesCache.push(texture);\n return texture;\n }\n createRenderTargetTexture(size, options) {\n var _a, _b;\n const rtWrapper = this._createHardwareRenderTargetWrapper(false, false, size);\n let generateDepthBuffer = true;\n let generateStencilBuffer = false;\n let noColorAttachment = false;\n let colorAttachment = undefined;\n let samples = 1;\n if (options !== undefined && typeof options === \"object\") {\n generateDepthBuffer = (_a = options.generateDepthBuffer) !== null && _a !== void 0 ? _a : true;\n generateStencilBuffer = !!options.generateStencilBuffer;\n noColorAttachment = !!options.noColorAttachment;\n colorAttachment = options.colorAttachment;\n samples = (_b = options.samples) !== null && _b !== void 0 ? _b : 1;\n }\n const texture = colorAttachment || (noColorAttachment ? null : this._createInternalTexture(size, options, true, InternalTextureSource.RenderTarget));\n const width = size.width || size;\n const height = size.height || size;\n const framebuffer = this._engine.createFrameBuffer(texture ? texture._hardwareTexture.underlyingResource : null, width, height, generateStencilBuffer, generateDepthBuffer);\n rtWrapper._framebuffer = framebuffer;\n rtWrapper._generateDepthBuffer = generateDepthBuffer;\n rtWrapper._generateStencilBuffer = generateStencilBuffer;\n rtWrapper.setTextures(texture);\n this.updateRenderTargetTextureSampleCount(rtWrapper, samples);\n return rtWrapper;\n }\n // This function is being added for the sole purpose of overriding the ThinEngine version. The reason\n // for this is that the ThinEngine version of this function uses a WebGL2RenderingContext, which is not\n // available in Babylon Native. The return value is just a hard-coded value that is not used anywhere\n // in Babylon Native's code. This is effectively a hack/workaround so that Babylon Native doesn't crash\n // This function should be updated once the maxMSAASamples is updated as well.\n updateRenderTargetTextureSampleCount(rtWrapper, samples) {\n // TODO: Implement this function once the maxMSAASamples is updated.\n return 1;\n }\n updateTextureSamplingMode(samplingMode, texture) {\n if (texture._hardwareTexture) {\n const filter = this._getNativeSamplingMode(samplingMode);\n this._setTextureSampling(texture._hardwareTexture.underlyingResource, filter);\n }\n texture.samplingMode = samplingMode;\n }\n bindFramebuffer(texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {\n const nativeRTWrapper = texture;\n if (this._currentRenderTarget) {\n this.unBindFramebuffer(this._currentRenderTarget);\n }\n this._currentRenderTarget = texture;\n if (faceIndex) {\n throw new Error(\"Cuboid frame buffers are not yet supported in NativeEngine.\");\n }\n if (requiredWidth || requiredHeight) {\n throw new Error(\"Required width/height for frame buffers not yet supported in NativeEngine.\");\n }\n if (forceFullscreenViewport) {\n //Not supported yet but don't stop rendering\n }\n if (nativeRTWrapper._framebufferDepthStencil) {\n this._bindUnboundFramebuffer(nativeRTWrapper._framebufferDepthStencil);\n }\n else {\n this._bindUnboundFramebuffer(nativeRTWrapper._framebuffer);\n }\n }\n unBindFramebuffer(texture, disableGenerateMipMaps = false, onBeforeUnbind) {\n // NOTE: Disabling mipmap generation is not yet supported in NativeEngine.\n this._currentRenderTarget = null;\n if (onBeforeUnbind) {\n onBeforeUnbind();\n }\n this._bindUnboundFramebuffer(null);\n }\n createDynamicVertexBuffer(data) {\n return this.createVertexBuffer(data, true);\n }\n updateDynamicIndexBuffer(indexBuffer, indices, offset = 0) {\n const buffer = indexBuffer;\n const data = this._normalizeIndexData(indices);\n buffer.is32Bits = data.BYTES_PER_ELEMENT === 4;\n this._engine.updateDynamicIndexBuffer(buffer.nativeIndexBuffer, data.buffer, data.byteOffset, data.byteLength, offset);\n }\n updateDynamicVertexBuffer(vertexBuffer, verticies, byteOffset, byteLength) {\n const buffer = vertexBuffer;\n const data = ArrayBuffer.isView(verticies) ? verticies : new Float32Array(verticies);\n this._engine.updateDynamicVertexBuffer(buffer.nativeVertexBuffer, data.buffer, data.byteOffset + (byteOffset !== null && byteOffset !== void 0 ? byteOffset : 0), byteLength !== null && byteLength !== void 0 ? byteLength : data.byteLength);\n }\n // TODO: Refactor to share more logic with base Engine implementation.\n _setTexture(channel, texture, isPartOfTextureArray = false, depthStencilTexture = false) {\n const uniform = this._boundUniforms[channel];\n if (!uniform) {\n return false;\n }\n // Not ready?\n if (!texture) {\n if (this._boundTexturesCache[channel] != null) {\n this._activeChannel = channel;\n this._boundTexturesCache[channel] = null;\n }\n return false;\n }\n // Video\n if (texture.video) {\n this._activeChannel = channel;\n texture.update();\n }\n else if (texture.delayLoadState === 4) {\n // Delay loading\n texture.delayLoad();\n return false;\n }\n let internalTexture;\n if (depthStencilTexture) {\n internalTexture = texture.depthStencilTexture;\n }\n else if (texture.isReady()) {\n internalTexture = texture.getInternalTexture();\n }\n else if (texture.isCube) {\n internalTexture = this.emptyCubeTexture;\n }\n else if (texture.is3D) {\n internalTexture = this.emptyTexture3D;\n }\n else if (texture.is2DArray) {\n internalTexture = this.emptyTexture2DArray;\n }\n else {\n internalTexture = this.emptyTexture;\n }\n this._activeChannel = channel;\n if (!internalTexture || !internalTexture._hardwareTexture) {\n return false;\n }\n this._setTextureWrapMode(internalTexture._hardwareTexture.underlyingResource, this._getAddressMode(texture.wrapU), this._getAddressMode(texture.wrapV), this._getAddressMode(texture.wrapR));\n this._updateAnisotropicLevel(texture);\n this._setTextureCore(uniform, internalTexture._hardwareTexture.underlyingResource);\n return true;\n }\n // filter is a NativeFilter.XXXX value.\n _setTextureSampling(texture, filter) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(texture);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(filter);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n // addressModes are NativeAddressMode.XXXX values.\n _setTextureWrapMode(texture, addressModeU, addressModeV, addressModeW) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(texture);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(addressModeU);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(addressModeV);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(addressModeW);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n _setTextureCore(uniform, texture) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(uniform);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(texture);\n this._commandBufferEncoder.finishEncodingCommand();\n }\n // TODO: Share more of this logic with the base implementation.\n // TODO: Rename to match naming in base implementation once refactoring allows different parameters.\n _updateAnisotropicLevel(texture) {\n const internalTexture = texture.getInternalTexture();\n const value = texture.anisotropicFilteringLevel;\n if (!internalTexture || !internalTexture._hardwareTexture) {\n return;\n }\n if (internalTexture._cachedAnisotropicFilteringLevel !== value) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(internalTexture._hardwareTexture.underlyingResource);\n this._commandBufferEncoder.encodeCommandArgAsUInt32(value);\n this._commandBufferEncoder.finishEncodingCommand();\n internalTexture._cachedAnisotropicFilteringLevel = value;\n }\n }\n // Returns a NativeAddressMode.XXX value.\n _getAddressMode(wrapMode) {\n switch (wrapMode) {\n case 1:\n return _native.Engine.ADDRESS_MODE_WRAP;\n case 0:\n return _native.Engine.ADDRESS_MODE_CLAMP;\n case 2:\n return _native.Engine.ADDRESS_MODE_MIRROR;\n default:\n throw new Error(\"Unexpected wrap mode: \" + wrapMode + \".\");\n }\n }\n /**\n * @internal\n */\n _bindTexture(channel, texture) {\n const uniform = this._boundUniforms[channel];\n if (!uniform) {\n return;\n }\n if (texture && texture._hardwareTexture) {\n const underlyingResource = texture._hardwareTexture.underlyingResource;\n this._setTextureCore(uniform, underlyingResource);\n }\n }\n _deleteBuffer(buffer) {\n if (buffer.nativeIndexBuffer) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(buffer.nativeIndexBuffer);\n this._commandBufferEncoder.finishEncodingCommand();\n delete buffer.nativeIndexBuffer;\n }\n if (buffer.nativeVertexBuffer) {\n this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER);\n this._commandBufferEncoder.encodeCommandArgAsNativeData(buffer.nativeVertexBuffer);\n this._commandBufferEncoder.finishEncodingCommand();\n delete buffer.nativeVertexBuffer;\n }\n }\n /**\n * Create a canvas\n * @param width width\n * @param height height\n * @returns ICanvas interface\n */\n createCanvas(width, height) {\n if (!_native.Canvas) {\n throw new Error(\"Native Canvas plugin not available.\");\n }\n const canvas = new _native.Canvas();\n canvas.width = width;\n canvas.height = height;\n return canvas;\n }\n /**\n * Create an image to use with canvas\n * @returns IImage interface\n */\n createCanvasImage() {\n if (!_native.Canvas) {\n throw new Error(\"Native Canvas plugin not available.\");\n }\n const image = new _native.Image();\n return image;\n }\n /**\n * Update a portion of an internal texture\n * @param texture defines the texture to update\n * @param imageData defines the data to store into the texture\n * @param xOffset defines the x coordinates of the update rectangle\n * @param yOffset defines the y coordinates of the update rectangle\n * @param width defines the width of the update rectangle\n * @param height defines the height of the update rectangle\n * @param faceIndex defines the face index if texture is a cube (0 by default)\n * @param lod defines the lod level to update (0 by default)\n * @param generateMipMaps defines whether to generate mipmaps or not\n */\n updateTextureData(texture, imageData, xOffset, yOffset, width, height, faceIndex = 0, lod = 0, generateMipMaps = false) {\n throw new Error(\"updateTextureData not implemented.\");\n }\n /**\n * @internal\n */\n _uploadCompressedDataToTextureDirectly(texture, internalFormat, width, height, data, faceIndex = 0, lod = 0) {\n throw new Error(\"_uploadCompressedDataToTextureDirectly not implemented.\");\n }\n /**\n * @internal\n */\n _uploadDataToTextureDirectly(texture, imageData, faceIndex = 0, lod = 0) {\n throw new Error(\"_uploadDataToTextureDirectly not implemented.\");\n }\n /**\n * @internal\n */\n _uploadArrayBufferViewToTexture(texture, imageData, faceIndex = 0, lod = 0) {\n throw new Error(\"_uploadArrayBufferViewToTexture not implemented.\");\n }\n /**\n * @internal\n */\n _uploadImageToTexture(texture, image, faceIndex = 0, lod = 0) {\n throw new Error(\"_uploadArrayBufferViewToTexture not implemented.\");\n }\n // JavaScript-to-Native conversion helper functions.\n _getNativeSamplingMode(samplingMode) {\n switch (samplingMode) {\n case 1:\n return _native.Engine.TEXTURE_NEAREST_NEAREST;\n case 2:\n return _native.Engine.TEXTURE_LINEAR_LINEAR;\n case 3:\n return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR;\n case 4:\n return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;\n case 5:\n return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;\n case 6:\n return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;\n case 7:\n return _native.Engine.TEXTURE_NEAREST_LINEAR;\n case 8:\n return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR;\n case 9:\n return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;\n case 10:\n return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;\n case 11:\n return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST;\n case 12:\n return _native.Engine.TEXTURE_LINEAR_NEAREST;\n default:\n throw new Error(`Unsupported sampling mode: ${samplingMode}.`);\n }\n }\n _getStencilFunc(func) {\n switch (func) {\n case 513:\n return _native.Engine.STENCIL_TEST_LESS;\n case 515:\n return _native.Engine.STENCIL_TEST_LEQUAL;\n case 514:\n return _native.Engine.STENCIL_TEST_EQUAL;\n case 518:\n return _native.Engine.STENCIL_TEST_GEQUAL;\n case 516:\n return _native.Engine.STENCIL_TEST_GREATER;\n case 517:\n return _native.Engine.STENCIL_TEST_NOTEQUAL;\n case 512:\n return _native.Engine.STENCIL_TEST_NEVER;\n case 519:\n return _native.Engine.STENCIL_TEST_ALWAYS;\n default:\n throw new Error(`Unsupported stencil func mode: ${func}.`);\n }\n }\n _getStencilOpFail(opFail) {\n switch (opFail) {\n case 7680:\n return _native.Engine.STENCIL_OP_FAIL_S_KEEP;\n case 0:\n return _native.Engine.STENCIL_OP_FAIL_S_ZERO;\n case 7681:\n return _native.Engine.STENCIL_OP_FAIL_S_REPLACE;\n case 7682:\n return _native.Engine.STENCIL_OP_FAIL_S_INCR;\n case 7683:\n return _native.Engine.STENCIL_OP_FAIL_S_DECR;\n case 5386:\n return _native.Engine.STENCIL_OP_FAIL_S_INVERT;\n case 34055:\n return _native.Engine.STENCIL_OP_FAIL_S_INCRSAT;\n case 34056:\n return _native.Engine.STENCIL_OP_FAIL_S_DECRSAT;\n default:\n throw new Error(`Unsupported stencil OpFail mode: ${opFail}.`);\n }\n }\n _getStencilDepthFail(depthFail) {\n switch (depthFail) {\n case 7680:\n return _native.Engine.STENCIL_OP_FAIL_Z_KEEP;\n case 0:\n return _native.Engine.STENCIL_OP_FAIL_Z_ZERO;\n case 7681:\n return _native.Engine.STENCIL_OP_FAIL_Z_REPLACE;\n case 7682:\n return _native.Engine.STENCIL_OP_FAIL_Z_INCR;\n case 7683:\n return _native.Engine.STENCIL_OP_FAIL_Z_DECR;\n case 5386:\n return _native.Engine.STENCIL_OP_FAIL_Z_INVERT;\n case 34055:\n return _native.Engine.STENCIL_OP_FAIL_Z_INCRSAT;\n case 34056:\n return _native.Engine.STENCIL_OP_FAIL_Z_DECRSAT;\n default:\n throw new Error(`Unsupported stencil depthFail mode: ${depthFail}.`);\n }\n }\n _getStencilDepthPass(opPass) {\n switch (opPass) {\n case 7680:\n return _native.Engine.STENCIL_OP_PASS_Z_KEEP;\n case 0:\n return _native.Engine.STENCIL_OP_PASS_Z_ZERO;\n case 7681:\n return _native.Engine.STENCIL_OP_PASS_Z_REPLACE;\n case 7682:\n return _native.Engine.STENCIL_OP_PASS_Z_INCR;\n case 7683:\n return _native.Engine.STENCIL_OP_PASS_Z_DECR;\n case 5386:\n return _native.Engine.STENCIL_OP_PASS_Z_INVERT;\n case 34055:\n return _native.Engine.STENCIL_OP_PASS_Z_INCRSAT;\n case 34056:\n return _native.Engine.STENCIL_OP_PASS_Z_DECRSAT;\n default:\n throw new Error(`Unsupported stencil opPass mode: ${opPass}.`);\n }\n }\n _getNativeTextureFormat(format, type) {\n if (format == 4 && type == 0) {\n return _native.Engine.TEXTURE_FORMAT_RGB8;\n }\n else if (format == 5 && type == 0) {\n return _native.Engine.TEXTURE_FORMAT_RGBA8;\n }\n else if (format == 5 && type == 2) {\n return _native.Engine.TEXTURE_FORMAT_RGBA16F;\n }\n else if (format == 5 && type == 1) {\n return _native.Engine.TEXTURE_FORMAT_RGBA32F;\n }\n else {\n throw new RuntimeError(`Unsupported texture format or type: format ${format}, type ${type}.`, ErrorCodes.UnsupportedTextureError);\n }\n }\n _getNativeAlphaMode(mode) {\n switch (mode) {\n case 0:\n return _native.Engine.ALPHA_DISABLE;\n case 1:\n return _native.Engine.ALPHA_ADD;\n case 2:\n return _native.Engine.ALPHA_COMBINE;\n case 3:\n return _native.Engine.ALPHA_SUBTRACT;\n case 4:\n return _native.Engine.ALPHA_MULTIPLY;\n case 5:\n return _native.Engine.ALPHA_MAXIMIZED;\n case 6:\n return _native.Engine.ALPHA_ONEONE;\n case 7:\n return _native.Engine.ALPHA_PREMULTIPLIED;\n case 8:\n return _native.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;\n case 9:\n return _native.Engine.ALPHA_INTERPOLATE;\n case 10:\n return _native.Engine.ALPHA_SCREENMODE;\n default:\n throw new Error(`Unsupported alpha mode: ${mode}.`);\n }\n }\n _getNativeAttribType(type) {\n switch (type) {\n case VertexBuffer.BYTE:\n return _native.Engine.ATTRIB_TYPE_INT8;\n case VertexBuffer.UNSIGNED_BYTE:\n return _native.Engine.ATTRIB_TYPE_UINT8;\n case VertexBuffer.SHORT:\n return _native.Engine.ATTRIB_TYPE_INT16;\n case VertexBuffer.UNSIGNED_SHORT:\n return _native.Engine.ATTRIB_TYPE_UINT16;\n case VertexBuffer.FLOAT:\n return _native.Engine.ATTRIB_TYPE_FLOAT;\n default:\n throw new Error(`Unsupported attribute type: ${type}.`);\n }\n }\n getFontOffset(font) {\n // TODO\n const result = { ascent: 0, height: 0, descent: 0 };\n return result;\n }\n _readTexturePixels(texture, width, height, faceIndex, level, buffer, _flushRenderer, _noDataConversion, x, y) {\n var _a, _b, _c, _d;\n if (faceIndex !== undefined && faceIndex !== -1) {\n throw new Error(`Reading cubemap faces is not supported, but faceIndex is ${faceIndex}.`);\n }\n return this._engine\n .readTexture((_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource, level !== null && level !== void 0 ? level : 0, x !== null && x !== void 0 ? x : 0, y !== null && y !== void 0 ? y : 0, width, height, (_b = buffer === null || buffer === void 0 ? void 0 : buffer.buffer) !== null && _b !== void 0 ? _b : null, (_c = buffer === null || buffer === void 0 ? void 0 : buffer.byteOffset) !== null && _c !== void 0 ? _c : 0, (_d = buffer === null || buffer === void 0 ? void 0 : buffer.byteLength) !== null && _d !== void 0 ? _d : 0)\n .then((rawBuffer) => {\n if (!buffer) {\n buffer = new Uint8Array(rawBuffer);\n }\n return buffer;\n });\n }\n}\n// This must match the protocol version in NativeEngine.cpp\nNativeEngine.PROTOCOL_VERSION = 8;\n//# sourceMappingURL=nativeEngine.js.map","import { NativeEngine } from \"../nativeEngine.js\";\nimport { NativeDataStream } from \"./nativeDataStream.js\";\nNativeEngine._createNativeDataStream = function () {\n if (_native.NativeDataStream.VALIDATION_ENABLED) {\n return new ValidatedNativeDataStream();\n }\n else {\n return new NativeDataStream();\n }\n};\nexport class ValidatedNativeDataStream extends NativeDataStream {\n constructor() {\n super();\n }\n writeUint32(value) {\n super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32);\n super.writeUint32(value);\n }\n writeInt32(value) {\n super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32);\n super.writeInt32(value);\n }\n writeFloat32(value) {\n super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32);\n super.writeFloat32(value);\n }\n writeUint32Array(values) {\n super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32_ARRAY);\n super.writeUint32Array(values);\n }\n writeInt32Array(values) {\n super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32_ARRAY);\n super.writeInt32Array(values);\n }\n writeFloat32Array(values) {\n super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32_ARRAY);\n super.writeFloat32Array(values);\n }\n writeNativeData(handle) {\n super.writeUint32(_native.NativeDataStream.VALIDATION_NATIVE_DATA);\n super.writeNativeData(handle);\n }\n writeBoolean(value) {\n super.writeUint32(_native.NativeDataStream.VALIDATION_BOOLEAN);\n super.writeBoolean(value);\n }\n}\n//# sourceMappingURL=validatedNativeDataStream.js.map","export * from \"./nativeDataStream.js\";\nexport * from \"./validatedNativeDataStream.js\";\n//# sourceMappingURL=index.js.map","/** @internal */\n// eslint-disable-next-line import/export\nexport var PowerPreference;\n(function (PowerPreference) {\n PowerPreference[\"LowPower\"] = \"low-power\";\n PowerPreference[\"HighPerformance\"] = \"high-performance\";\n})(PowerPreference || (PowerPreference = {}));\n/** @internal */\nexport var FeatureName;\n(function (FeatureName) {\n FeatureName[\"DepthClipControl\"] = \"depth-clip-control\";\n FeatureName[\"Depth32FloatStencil8\"] = \"depth32float-stencil8\";\n FeatureName[\"TextureCompressionBC\"] = \"texture-compression-bc\";\n FeatureName[\"TextureCompressionETC2\"] = \"texture-compression-etc2\";\n FeatureName[\"TextureCompressionASTC\"] = \"texture-compression-astc\";\n FeatureName[\"TimestampQuery\"] = \"timestamp-query\";\n FeatureName[\"IndirectFirstInstance\"] = \"indirect-first-instance\";\n FeatureName[\"ShaderF16\"] = \"shader-f16\";\n FeatureName[\"RG11B10UFloatRenderable\"] = \"rg11b10ufloat-renderable\";\n FeatureName[\"BGRA8UnormStorage\"] = \"bgra8unorm-storage\";\n FeatureName[\"Float32Filterable\"] = \"float32-filterable\";\n})(FeatureName || (FeatureName = {}));\n/** @internal */\nexport var BufferMapState;\n(function (BufferMapState) {\n BufferMapState[\"Unmapped\"] = \"unmapped\";\n BufferMapState[\"Pending\"] = \"pending\";\n BufferMapState[\"Mapped\"] = \"mapped\";\n})(BufferMapState || (BufferMapState = {}));\n/** @internal */\nexport var BufferUsage;\n(function (BufferUsage) {\n BufferUsage[BufferUsage[\"MapRead\"] = 1] = \"MapRead\";\n BufferUsage[BufferUsage[\"MapWrite\"] = 2] = \"MapWrite\";\n BufferUsage[BufferUsage[\"CopySrc\"] = 4] = \"CopySrc\";\n BufferUsage[BufferUsage[\"CopyDst\"] = 8] = \"CopyDst\";\n BufferUsage[BufferUsage[\"Index\"] = 16] = \"Index\";\n BufferUsage[BufferUsage[\"Vertex\"] = 32] = \"Vertex\";\n BufferUsage[BufferUsage[\"Uniform\"] = 64] = \"Uniform\";\n BufferUsage[BufferUsage[\"Storage\"] = 128] = \"Storage\";\n BufferUsage[BufferUsage[\"Indirect\"] = 256] = \"Indirect\";\n BufferUsage[BufferUsage[\"QueryResolve\"] = 512] = \"QueryResolve\";\n})(BufferUsage || (BufferUsage = {}));\n/** @internal */\nexport var MapMode;\n(function (MapMode) {\n MapMode[MapMode[\"Read\"] = 1] = \"Read\";\n MapMode[MapMode[\"Write\"] = 2] = \"Write\";\n})(MapMode || (MapMode = {}));\n/** @internal */\nexport var TextureDimension;\n(function (TextureDimension) {\n TextureDimension[\"E1d\"] = \"1d\";\n TextureDimension[\"E2d\"] = \"2d\";\n TextureDimension[\"E3d\"] = \"3d\";\n})(TextureDimension || (TextureDimension = {}));\n/** @internal */\nexport var TextureUsage;\n(function (TextureUsage) {\n TextureUsage[TextureUsage[\"CopySrc\"] = 1] = \"CopySrc\";\n TextureUsage[TextureUsage[\"CopyDst\"] = 2] = \"CopyDst\";\n TextureUsage[TextureUsage[\"TextureBinding\"] = 4] = \"TextureBinding\";\n TextureUsage[TextureUsage[\"StorageBinding\"] = 8] = \"StorageBinding\";\n TextureUsage[TextureUsage[\"RenderAttachment\"] = 16] = \"RenderAttachment\";\n})(TextureUsage || (TextureUsage = {}));\n/** @internal */\nexport var TextureViewDimension;\n(function (TextureViewDimension) {\n TextureViewDimension[\"E1d\"] = \"1d\";\n TextureViewDimension[\"E2d\"] = \"2d\";\n TextureViewDimension[\"E2dArray\"] = \"2d-array\";\n TextureViewDimension[\"Cube\"] = \"cube\";\n TextureViewDimension[\"CubeArray\"] = \"cube-array\";\n TextureViewDimension[\"E3d\"] = \"3d\";\n})(TextureViewDimension || (TextureViewDimension = {}));\n/** @internal */\nexport var TextureAspect;\n(function (TextureAspect) {\n TextureAspect[\"All\"] = \"all\";\n TextureAspect[\"StencilOnly\"] = \"stencil-only\";\n TextureAspect[\"DepthOnly\"] = \"depth-only\";\n})(TextureAspect || (TextureAspect = {}));\n/**\n * Comments taken from https://github.com/gfx-rs/wgpu/blob/master/wgpu-types/src/lib.rs\n * @internal\n */\nexport var TextureFormat;\n(function (TextureFormat) {\n // 8-bit formats\n TextureFormat[\"R8Unorm\"] = \"r8unorm\";\n TextureFormat[\"R8Snorm\"] = \"r8snorm\";\n TextureFormat[\"R8Uint\"] = \"r8uint\";\n TextureFormat[\"R8Sint\"] = \"r8sint\";\n // 16-bit formats\n TextureFormat[\"R16Uint\"] = \"r16uint\";\n TextureFormat[\"R16Sint\"] = \"r16sint\";\n TextureFormat[\"R16Float\"] = \"r16float\";\n TextureFormat[\"RG8Unorm\"] = \"rg8unorm\";\n TextureFormat[\"RG8Snorm\"] = \"rg8snorm\";\n TextureFormat[\"RG8Uint\"] = \"rg8uint\";\n TextureFormat[\"RG8Sint\"] = \"rg8sint\";\n // 32-bit formats\n TextureFormat[\"R32Uint\"] = \"r32uint\";\n TextureFormat[\"R32Sint\"] = \"r32sint\";\n TextureFormat[\"R32Float\"] = \"r32float\";\n TextureFormat[\"RG16Uint\"] = \"rg16uint\";\n TextureFormat[\"RG16Sint\"] = \"rg16sint\";\n TextureFormat[\"RG16Float\"] = \"rg16float\";\n TextureFormat[\"RGBA8Unorm\"] = \"rgba8unorm\";\n TextureFormat[\"RGBA8UnormSRGB\"] = \"rgba8unorm-srgb\";\n TextureFormat[\"RGBA8Snorm\"] = \"rgba8snorm\";\n TextureFormat[\"RGBA8Uint\"] = \"rgba8uint\";\n TextureFormat[\"RGBA8Sint\"] = \"rgba8sint\";\n TextureFormat[\"BGRA8Unorm\"] = \"bgra8unorm\";\n TextureFormat[\"BGRA8UnormSRGB\"] = \"bgra8unorm-srgb\";\n // Packed 32-bit formats\n TextureFormat[\"RGB9E5UFloat\"] = \"rgb9e5ufloat\";\n TextureFormat[\"RGB10A2Unorm\"] = \"rgb10a2unorm\";\n TextureFormat[\"RG11B10UFloat\"] = \"rg11b10ufloat\";\n // 64-bit formats\n TextureFormat[\"RG32Uint\"] = \"rg32uint\";\n TextureFormat[\"RG32Sint\"] = \"rg32sint\";\n TextureFormat[\"RG32Float\"] = \"rg32float\";\n TextureFormat[\"RGBA16Uint\"] = \"rgba16uint\";\n TextureFormat[\"RGBA16Sint\"] = \"rgba16sint\";\n TextureFormat[\"RGBA16Float\"] = \"rgba16float\";\n // 128-bit formats\n TextureFormat[\"RGBA32Uint\"] = \"rgba32uint\";\n TextureFormat[\"RGBA32Sint\"] = \"rgba32sint\";\n TextureFormat[\"RGBA32Float\"] = \"rgba32float\";\n // Depth and stencil formats\n TextureFormat[\"Stencil8\"] = \"stencil8\";\n TextureFormat[\"Depth16Unorm\"] = \"depth16unorm\";\n TextureFormat[\"Depth24Plus\"] = \"depth24plus\";\n TextureFormat[\"Depth24PlusStencil8\"] = \"depth24plus-stencil8\";\n TextureFormat[\"Depth32Float\"] = \"depth32float\";\n // BC compressed formats usable if \"texture-compression-bc\" is both\n // supported by the device/user agent and enabled in requestDevice.\n TextureFormat[\"BC1RGBAUnorm\"] = \"bc1-rgba-unorm\";\n TextureFormat[\"BC1RGBAUnormSRGB\"] = \"bc1-rgba-unorm-srgb\";\n TextureFormat[\"BC2RGBAUnorm\"] = \"bc2-rgba-unorm\";\n TextureFormat[\"BC2RGBAUnormSRGB\"] = \"bc2-rgba-unorm-srgb\";\n TextureFormat[\"BC3RGBAUnorm\"] = \"bc3-rgba-unorm\";\n TextureFormat[\"BC3RGBAUnormSRGB\"] = \"bc3-rgba-unorm-srgb\";\n TextureFormat[\"BC4RUnorm\"] = \"bc4-r-unorm\";\n TextureFormat[\"BC4RSnorm\"] = \"bc4-r-snorm\";\n TextureFormat[\"BC5RGUnorm\"] = \"bc5-rg-unorm\";\n TextureFormat[\"BC5RGSnorm\"] = \"bc5-rg-snorm\";\n TextureFormat[\"BC6HRGBUFloat\"] = \"bc6h-rgb-ufloat\";\n TextureFormat[\"BC6HRGBFloat\"] = \"bc6h-rgb-float\";\n TextureFormat[\"BC7RGBAUnorm\"] = \"bc7-rgba-unorm\";\n TextureFormat[\"BC7RGBAUnormSRGB\"] = \"bc7-rgba-unorm-srgb\";\n // ETC2 compressed formats usable if \"texture-compression-etc2\" is both\n // supported by the device/user agent and enabled in requestDevice.\n TextureFormat[\"ETC2RGB8Unorm\"] = \"etc2-rgb8unorm\";\n TextureFormat[\"ETC2RGB8UnormSRGB\"] = \"etc2-rgb8unorm-srgb\";\n TextureFormat[\"ETC2RGB8A1Unorm\"] = \"etc2-rgb8a1unorm\";\n TextureFormat[\"ETC2RGB8A1UnormSRGB\"] = \"etc2-rgb8a1unorm-srgb\";\n TextureFormat[\"ETC2RGBA8Unorm\"] = \"etc2-rgba8unorm\";\n TextureFormat[\"ETC2RGBA8UnormSRGB\"] = \"etc2-rgba8unorm-srgb\";\n TextureFormat[\"EACR11Unorm\"] = \"eac-r11unorm\";\n TextureFormat[\"EACR11Snorm\"] = \"eac-r11snorm\";\n TextureFormat[\"EACRG11Unorm\"] = \"eac-rg11unorm\";\n TextureFormat[\"EACRG11Snorm\"] = \"eac-rg11snorm\";\n // ASTC compressed formats usable if \"texture-compression-astc\" is both\n // supported by the device/user agent and enabled in requestDevice.\n TextureFormat[\"ASTC4x4Unorm\"] = \"astc-4x4-unorm\";\n TextureFormat[\"ASTC4x4UnormSRGB\"] = \"astc-4x4-unorm-srgb\";\n TextureFormat[\"ASTC5x4Unorm\"] = \"astc-5x4-unorm\";\n TextureFormat[\"ASTC5x4UnormSRGB\"] = \"astc-5x4-unorm-srgb\";\n TextureFormat[\"ASTC5x5Unorm\"] = \"astc-5x5-unorm\";\n TextureFormat[\"ASTC5x5UnormSRGB\"] = \"astc-5x5-unorm-srgb\";\n TextureFormat[\"ASTC6x5Unorm\"] = \"astc-6x5-unorm\";\n TextureFormat[\"ASTC6x5UnormSRGB\"] = \"astc-6x5-unorm-srgb\";\n TextureFormat[\"ASTC6x6Unorm\"] = \"astc-6x6-unorm\";\n TextureFormat[\"ASTC6x6UnormSRGB\"] = \"astc-6x6-unorm-srgb\";\n TextureFormat[\"ASTC8x5Unorm\"] = \"astc-8x5-unorm\";\n TextureFormat[\"ASTC8x5UnormSRGB\"] = \"astc-8x5-unorm-srgb\";\n TextureFormat[\"ASTC8x6Unorm\"] = \"astc-8x6-unorm\";\n TextureFormat[\"ASTC8x6UnormSRGB\"] = \"astc-8x6-unorm-srgb\";\n TextureFormat[\"ASTC8x8Unorm\"] = \"astc-8x8-unorm\";\n TextureFormat[\"ASTC8x8UnormSRGB\"] = \"astc-8x8-unorm-srgb\";\n TextureFormat[\"ASTC10x5Unorm\"] = \"astc-10x5-unorm\";\n TextureFormat[\"ASTC10x5UnormSRGB\"] = \"astc-10x5-unorm-srgb\";\n TextureFormat[\"ASTC10x6Unorm\"] = \"astc-10x6-unorm\";\n TextureFormat[\"ASTC10x6UnormSRGB\"] = \"astc-10x6-unorm-srgb\";\n TextureFormat[\"ASTC10x8Unorm\"] = \"astc-10x8-unorm\";\n TextureFormat[\"ASTC10x8UnormSRGB\"] = \"astc-10x8-unorm-srgb\";\n TextureFormat[\"ASTC10x10Unorm\"] = \"astc-10x10-unorm\";\n TextureFormat[\"ASTC10x10UnormSRGB\"] = \"astc-10x10-unorm-srgb\";\n TextureFormat[\"ASTC12x10Unorm\"] = \"astc-12x10-unorm\";\n TextureFormat[\"ASTC12x10UnormSRGB\"] = \"astc-12x10-unorm-srgb\";\n TextureFormat[\"ASTC12x12Unorm\"] = \"astc-12x12-unorm\";\n TextureFormat[\"ASTC12x12UnormSRGB\"] = \"astc-12x12-unorm-srgb\";\n // \"depth24unorm-stencil8\" feature\n TextureFormat[\"Depth24UnormStencil8\"] = \"depth24unorm-stencil8\";\n // \"depth32float-stencil8\" feature\n TextureFormat[\"Depth32FloatStencil8\"] = \"depth32float-stencil8\";\n})(TextureFormat || (TextureFormat = {}));\n/** @internal */\nexport var AddressMode;\n(function (AddressMode) {\n AddressMode[\"ClampToEdge\"] = \"clamp-to-edge\";\n AddressMode[\"Repeat\"] = \"repeat\";\n AddressMode[\"MirrorRepeat\"] = \"mirror-repeat\";\n})(AddressMode || (AddressMode = {}));\n/** @internal */\nexport var FilterMode;\n(function (FilterMode) {\n FilterMode[\"Nearest\"] = \"nearest\";\n FilterMode[\"Linear\"] = \"linear\";\n})(FilterMode || (FilterMode = {}));\n/** @internal */\nexport var MipmapFilterMode;\n(function (MipmapFilterMode) {\n MipmapFilterMode[\"Nearest\"] = \"nearest\";\n MipmapFilterMode[\"Linear\"] = \"linear\";\n})(MipmapFilterMode || (MipmapFilterMode = {}));\n/** @internal */\nexport var CompareFunction;\n(function (CompareFunction) {\n CompareFunction[\"Never\"] = \"never\";\n CompareFunction[\"Less\"] = \"less\";\n CompareFunction[\"Equal\"] = \"equal\";\n CompareFunction[\"LessEqual\"] = \"less-equal\";\n CompareFunction[\"Greater\"] = \"greater\";\n CompareFunction[\"NotEqual\"] = \"not-equal\";\n CompareFunction[\"GreaterEqual\"] = \"greater-equal\";\n CompareFunction[\"Always\"] = \"always\";\n})(CompareFunction || (CompareFunction = {}));\n/** @internal */\nexport var ShaderStage;\n(function (ShaderStage) {\n ShaderStage[ShaderStage[\"Vertex\"] = 1] = \"Vertex\";\n ShaderStage[ShaderStage[\"Fragment\"] = 2] = \"Fragment\";\n ShaderStage[ShaderStage[\"Compute\"] = 4] = \"Compute\";\n})(ShaderStage || (ShaderStage = {}));\n/** @internal */\nexport var BufferBindingType;\n(function (BufferBindingType) {\n BufferBindingType[\"Uniform\"] = \"uniform\";\n BufferBindingType[\"Storage\"] = \"storage\";\n BufferBindingType[\"ReadOnlyStorage\"] = \"read-only-storage\";\n})(BufferBindingType || (BufferBindingType = {}));\n/** @internal */\nexport var SamplerBindingType;\n(function (SamplerBindingType) {\n SamplerBindingType[\"Filtering\"] = \"filtering\";\n SamplerBindingType[\"NonFiltering\"] = \"non-filtering\";\n SamplerBindingType[\"Comparison\"] = \"comparison\";\n})(SamplerBindingType || (SamplerBindingType = {}));\n/** @internal */\nexport var TextureSampleType;\n(function (TextureSampleType) {\n TextureSampleType[\"Float\"] = \"float\";\n TextureSampleType[\"UnfilterableFloat\"] = \"unfilterable-float\";\n TextureSampleType[\"Depth\"] = \"depth\";\n TextureSampleType[\"Sint\"] = \"sint\";\n TextureSampleType[\"Uint\"] = \"uint\";\n})(TextureSampleType || (TextureSampleType = {}));\n/** @internal */\nexport var StorageTextureAccess;\n(function (StorageTextureAccess) {\n StorageTextureAccess[\"WriteOnly\"] = \"write-only\";\n})(StorageTextureAccess || (StorageTextureAccess = {}));\n/** @internal */\nexport var CompilationMessageType;\n(function (CompilationMessageType) {\n CompilationMessageType[\"Error\"] = \"error\";\n CompilationMessageType[\"Warning\"] = \"warning\";\n CompilationMessageType[\"Info\"] = \"info\";\n})(CompilationMessageType || (CompilationMessageType = {}));\n/** @internal */\nexport var PipelineErrorReason;\n(function (PipelineErrorReason) {\n PipelineErrorReason[\"Validation\"] = \"validation\";\n PipelineErrorReason[\"Internal\"] = \"internal\";\n})(PipelineErrorReason || (PipelineErrorReason = {}));\n/** @internal */\nexport var AutoLayoutMode;\n(function (AutoLayoutMode) {\n AutoLayoutMode[\"Auto\"] = \"auto\";\n})(AutoLayoutMode || (AutoLayoutMode = {}));\n/** @internal */\nexport var PrimitiveTopology;\n(function (PrimitiveTopology) {\n PrimitiveTopology[\"PointList\"] = \"point-list\";\n PrimitiveTopology[\"LineList\"] = \"line-list\";\n PrimitiveTopology[\"LineStrip\"] = \"line-strip\";\n PrimitiveTopology[\"TriangleList\"] = \"triangle-list\";\n PrimitiveTopology[\"TriangleStrip\"] = \"triangle-strip\";\n})(PrimitiveTopology || (PrimitiveTopology = {}));\n/** @internal */\nexport var FrontFace;\n(function (FrontFace) {\n FrontFace[\"CCW\"] = \"ccw\";\n FrontFace[\"CW\"] = \"cw\";\n})(FrontFace || (FrontFace = {}));\n/** @internal */\nexport var CullMode;\n(function (CullMode) {\n CullMode[\"None\"] = \"none\";\n CullMode[\"Front\"] = \"front\";\n CullMode[\"Back\"] = \"back\";\n})(CullMode || (CullMode = {}));\n/** @internal */\nexport var ColorWriteFlags;\n(function (ColorWriteFlags) {\n ColorWriteFlags[ColorWriteFlags[\"Red\"] = 1] = \"Red\";\n ColorWriteFlags[ColorWriteFlags[\"Green\"] = 2] = \"Green\";\n ColorWriteFlags[ColorWriteFlags[\"Blue\"] = 4] = \"Blue\";\n ColorWriteFlags[ColorWriteFlags[\"Alpha\"] = 8] = \"Alpha\";\n ColorWriteFlags[ColorWriteFlags[\"All\"] = 15] = \"All\";\n})(ColorWriteFlags || (ColorWriteFlags = {}));\n/** @internal */\nexport var BlendFactor;\n(function (BlendFactor) {\n BlendFactor[\"Zero\"] = \"zero\";\n BlendFactor[\"One\"] = \"one\";\n BlendFactor[\"Src\"] = \"src\";\n BlendFactor[\"OneMinusSrc\"] = \"one-minus-src\";\n BlendFactor[\"SrcAlpha\"] = \"src-alpha\";\n BlendFactor[\"OneMinusSrcAlpha\"] = \"one-minus-src-alpha\";\n BlendFactor[\"Dst\"] = \"dst\";\n BlendFactor[\"OneMinusDst\"] = \"one-minus-dst\";\n BlendFactor[\"DstAlpha\"] = \"dst-alpha\";\n BlendFactor[\"OneMinusDstAlpha\"] = \"one-minus-dst-alpha\";\n BlendFactor[\"SrcAlphaSaturated\"] = \"src-alpha-saturated\";\n BlendFactor[\"Constant\"] = \"constant\";\n BlendFactor[\"OneMinusConstant\"] = \"one-minus-constant\";\n})(BlendFactor || (BlendFactor = {}));\n/** @internal */\nexport var BlendOperation;\n(function (BlendOperation) {\n BlendOperation[\"Add\"] = \"add\";\n BlendOperation[\"Subtract\"] = \"subtract\";\n BlendOperation[\"ReverseSubtract\"] = \"reverse-subtract\";\n BlendOperation[\"Min\"] = \"min\";\n BlendOperation[\"Max\"] = \"max\";\n})(BlendOperation || (BlendOperation = {}));\n/** @internal */\nexport var StencilOperation;\n(function (StencilOperation) {\n StencilOperation[\"Keep\"] = \"keep\";\n StencilOperation[\"Zero\"] = \"zero\";\n StencilOperation[\"Replace\"] = \"replace\";\n StencilOperation[\"Invert\"] = \"invert\";\n StencilOperation[\"IncrementClamp\"] = \"increment-clamp\";\n StencilOperation[\"DecrementClamp\"] = \"decrement-clamp\";\n StencilOperation[\"IncrementWrap\"] = \"increment-wrap\";\n StencilOperation[\"DecrementWrap\"] = \"decrement-wrap\";\n})(StencilOperation || (StencilOperation = {}));\n/** @internal */\nexport var IndexFormat;\n(function (IndexFormat) {\n IndexFormat[\"Uint16\"] = \"uint16\";\n IndexFormat[\"Uint32\"] = \"uint32\";\n})(IndexFormat || (IndexFormat = {}));\n/** @internal */\nexport var VertexFormat;\n(function (VertexFormat) {\n VertexFormat[\"Uint8x2\"] = \"uint8x2\";\n VertexFormat[\"Uint8x4\"] = \"uint8x4\";\n VertexFormat[\"Sint8x2\"] = \"sint8x2\";\n VertexFormat[\"Sint8x4\"] = \"sint8x4\";\n VertexFormat[\"Unorm8x2\"] = \"unorm8x2\";\n VertexFormat[\"Unorm8x4\"] = \"unorm8x4\";\n VertexFormat[\"Snorm8x2\"] = \"snorm8x2\";\n VertexFormat[\"Snorm8x4\"] = \"snorm8x4\";\n VertexFormat[\"Uint16x2\"] = \"uint16x2\";\n VertexFormat[\"Uint16x4\"] = \"uint16x4\";\n VertexFormat[\"Sint16x2\"] = \"sint16x2\";\n VertexFormat[\"Sint16x4\"] = \"sint16x4\";\n VertexFormat[\"Unorm16x2\"] = \"unorm16x2\";\n VertexFormat[\"Unorm16x4\"] = \"unorm16x4\";\n VertexFormat[\"Snorm16x2\"] = \"snorm16x2\";\n VertexFormat[\"Snorm16x4\"] = \"snorm16x4\";\n VertexFormat[\"Float16x2\"] = \"float16x2\";\n VertexFormat[\"Float16x4\"] = \"float16x4\";\n VertexFormat[\"Float32\"] = \"float32\";\n VertexFormat[\"Float32x2\"] = \"float32x2\";\n VertexFormat[\"Float32x3\"] = \"float32x3\";\n VertexFormat[\"Float32x4\"] = \"float32x4\";\n VertexFormat[\"Uint32\"] = \"uint32\";\n VertexFormat[\"Uint32x2\"] = \"uint32x2\";\n VertexFormat[\"Uint32x3\"] = \"uint32x3\";\n VertexFormat[\"Uint32x4\"] = \"uint32x4\";\n VertexFormat[\"Sint32\"] = \"sint32\";\n VertexFormat[\"Sint32x2\"] = \"sint32x2\";\n VertexFormat[\"Sint32x3\"] = \"sint32x3\";\n VertexFormat[\"Sint32x4\"] = \"sint32x4\";\n})(VertexFormat || (VertexFormat = {}));\n/** @internal */\nexport var InputStepMode;\n(function (InputStepMode) {\n InputStepMode[\"Vertex\"] = \"vertex\";\n InputStepMode[\"Instance\"] = \"instance\";\n})(InputStepMode || (InputStepMode = {}));\n/** @internal */\nexport var ComputePassTimestampLocation;\n(function (ComputePassTimestampLocation) {\n ComputePassTimestampLocation[\"Beginning\"] = \"beginning\";\n ComputePassTimestampLocation[\"End\"] = \"end\";\n})(ComputePassTimestampLocation || (ComputePassTimestampLocation = {}));\n/** @internal */\nexport var RenderPassTimestampLocation;\n(function (RenderPassTimestampLocation) {\n RenderPassTimestampLocation[\"Beginning\"] = \"beginning\";\n RenderPassTimestampLocation[\"End\"] = \"end\";\n})(RenderPassTimestampLocation || (RenderPassTimestampLocation = {}));\n/** @internal */\nexport var LoadOp;\n(function (LoadOp) {\n LoadOp[\"Load\"] = \"load\";\n LoadOp[\"Clear\"] = \"clear\";\n})(LoadOp || (LoadOp = {}));\n/** @internal */\nexport var StoreOp;\n(function (StoreOp) {\n StoreOp[\"Store\"] = \"store\";\n StoreOp[\"Discard\"] = \"discard\";\n})(StoreOp || (StoreOp = {}));\n/** @internal */\nexport var QueryType;\n(function (QueryType) {\n QueryType[\"Occlusion\"] = \"occlusion\";\n QueryType[\"Timestamp\"] = \"timestamp\";\n})(QueryType || (QueryType = {}));\n/** @internal */\nexport var CanvasAlphaMode;\n(function (CanvasAlphaMode) {\n CanvasAlphaMode[\"Opaque\"] = \"opaque\";\n CanvasAlphaMode[\"Premultiplied\"] = \"premultiplied\";\n})(CanvasAlphaMode || (CanvasAlphaMode = {}));\n/** @internal */\nexport var DeviceLostReason;\n(function (DeviceLostReason) {\n DeviceLostReason[\"Unknown\"] = \"unknown\";\n DeviceLostReason[\"Destroyed\"] = \"destroyed\";\n})(DeviceLostReason || (DeviceLostReason = {}));\n/** @internal */\nexport var ErrorFilter;\n(function (ErrorFilter) {\n ErrorFilter[\"Validation\"] = \"validation\";\n ErrorFilter[\"OutOfMemory\"] = \"out-of-memory\";\n ErrorFilter[\"Internal\"] = \"internal\";\n})(ErrorFilter || (ErrorFilter = {}));\n//# sourceMappingURL=webgpuConstants.js.map","import { ShaderLanguage } from \"../../Materials/shaderLanguage.js\";\nimport * as WebGPUConstants from \"./webgpuConstants.js\";\n/** @internal */\nexport class WebGPUShaderProcessor {\n constructor() {\n this.shaderLanguage = ShaderLanguage.GLSL;\n }\n _addUniformToLeftOverUBO(name, uniformType, preProcessors) {\n let length = 0;\n [name, uniformType, length] = this._getArraySize(name, uniformType, preProcessors);\n for (let i = 0; i < this._webgpuProcessingContext.leftOverUniforms.length; i++) {\n if (this._webgpuProcessingContext.leftOverUniforms[i].name === name) {\n return;\n }\n }\n this._webgpuProcessingContext.leftOverUniforms.push({\n name,\n type: uniformType,\n length,\n });\n }\n _buildLeftOverUBO() {\n if (!this._webgpuProcessingContext.leftOverUniforms.length) {\n return \"\";\n }\n const name = WebGPUShaderProcessor.LeftOvertUBOName;\n let availableUBO = this._webgpuProcessingContext.availableBuffers[name];\n if (!availableUBO) {\n availableUBO = {\n binding: this._webgpuProcessingContext.getNextFreeUBOBinding(),\n };\n this._webgpuProcessingContext.availableBuffers[name] = availableUBO;\n this._addBufferBindingDescription(name, availableUBO, WebGPUConstants.BufferBindingType.Uniform, true);\n this._addBufferBindingDescription(name, availableUBO, WebGPUConstants.BufferBindingType.Uniform, false);\n }\n return this._generateLeftOverUBOCode(name, availableUBO);\n }\n _collectBindingNames() {\n // collect all the binding names for faster processing in WebGPUCacheBindGroup\n for (let i = 0; i < this._webgpuProcessingContext.bindGroupLayoutEntries.length; i++) {\n const setDefinition = this._webgpuProcessingContext.bindGroupLayoutEntries[i];\n if (setDefinition === undefined) {\n this._webgpuProcessingContext.bindGroupLayoutEntries[i] = [];\n continue;\n }\n for (let j = 0; j < setDefinition.length; j++) {\n const entry = this._webgpuProcessingContext.bindGroupLayoutEntries[i][j];\n const name = this._webgpuProcessingContext.bindGroupLayoutEntryInfo[i][entry.binding].name;\n const nameInArrayOfTexture = this._webgpuProcessingContext.bindGroupLayoutEntryInfo[i][entry.binding].nameInArrayOfTexture;\n if (entry) {\n if (entry.texture || entry.externalTexture || entry.storageTexture) {\n this._webgpuProcessingContext.textureNames.push(nameInArrayOfTexture);\n }\n else if (entry.sampler) {\n this._webgpuProcessingContext.samplerNames.push(name);\n }\n else if (entry.buffer) {\n this._webgpuProcessingContext.bufferNames.push(name);\n }\n }\n }\n }\n }\n _preCreateBindGroupEntries() {\n const bindGroupEntries = this._webgpuProcessingContext.bindGroupEntries;\n for (let i = 0; i < this._webgpuProcessingContext.bindGroupLayoutEntries.length; i++) {\n const setDefinition = this._webgpuProcessingContext.bindGroupLayoutEntries[i];\n const entries = [];\n for (let j = 0; j < setDefinition.length; j++) {\n const entry = this._webgpuProcessingContext.bindGroupLayoutEntries[i][j];\n if (entry.sampler || entry.texture || entry.storageTexture || entry.externalTexture) {\n entries.push({\n binding: entry.binding,\n resource: undefined,\n });\n }\n else if (entry.buffer) {\n entries.push({\n binding: entry.binding,\n resource: {\n buffer: undefined,\n offset: 0,\n size: 0,\n },\n });\n }\n }\n bindGroupEntries[i] = entries;\n }\n }\n _addTextureBindingDescription(name, textureInfo, textureIndex, dimension, format, isVertex) {\n // eslint-disable-next-line prefer-const\n let { groupIndex, bindingIndex } = textureInfo.textures[textureIndex];\n if (!this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex]) {\n this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex] = [];\n this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex] = [];\n }\n if (!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex]) {\n let len;\n if (dimension === null) {\n len = this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex].push({\n binding: bindingIndex,\n visibility: 0,\n externalTexture: {},\n });\n }\n else if (format) {\n len = this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex].push({\n binding: bindingIndex,\n visibility: 0,\n storageTexture: {\n access: WebGPUConstants.StorageTextureAccess.WriteOnly,\n format,\n viewDimension: dimension,\n },\n });\n }\n else {\n len = this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex].push({\n binding: bindingIndex,\n visibility: 0,\n texture: {\n sampleType: textureInfo.sampleType,\n viewDimension: dimension,\n multisampled: false,\n },\n });\n }\n const textureName = textureInfo.isTextureArray ? name + textureIndex : name;\n this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex] = { name, index: len - 1, nameInArrayOfTexture: textureName };\n }\n bindingIndex = this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex].index;\n if (isVertex) {\n this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= WebGPUConstants.ShaderStage.Vertex;\n }\n else {\n this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= WebGPUConstants.ShaderStage.Fragment;\n }\n }\n _addSamplerBindingDescription(name, samplerInfo, isVertex) {\n // eslint-disable-next-line prefer-const\n let { groupIndex, bindingIndex } = samplerInfo.binding;\n if (!this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex]) {\n this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex] = [];\n this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex] = [];\n }\n if (!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex]) {\n const len = this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex].push({\n binding: bindingIndex,\n visibility: 0,\n sampler: {\n type: samplerInfo.type,\n },\n });\n this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex] = { name, index: len - 1 };\n }\n bindingIndex = this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex].index;\n if (isVertex) {\n this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= WebGPUConstants.ShaderStage.Vertex;\n }\n else {\n this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= WebGPUConstants.ShaderStage.Fragment;\n }\n }\n _addBufferBindingDescription(name, uniformBufferInfo, bufferType, isVertex) {\n // eslint-disable-next-line prefer-const\n let { groupIndex, bindingIndex } = uniformBufferInfo.binding;\n if (!this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex]) {\n this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex] = [];\n this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex] = [];\n }\n if (!this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex]) {\n const len = this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex].push({\n binding: bindingIndex,\n visibility: 0,\n buffer: {\n type: bufferType,\n },\n });\n this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex] = { name, index: len - 1 };\n }\n bindingIndex = this._webgpuProcessingContext.bindGroupLayoutEntryInfo[groupIndex][bindingIndex].index;\n if (isVertex) {\n this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= WebGPUConstants.ShaderStage.Vertex;\n }\n else {\n this._webgpuProcessingContext.bindGroupLayoutEntries[groupIndex][bindingIndex].visibility |= WebGPUConstants.ShaderStage.Fragment;\n }\n }\n _injectStartingAndEndingCode(code, mainFuncDecl, startingCode, endingCode) {\n let idx = code.indexOf(mainFuncDecl);\n if (idx < 0) {\n console.error(`No \"main\" function found in shader code! Processing aborted.`);\n return code;\n }\n if (startingCode) {\n // eslint-disable-next-line no-empty\n while (idx++ < code.length && code.charAt(idx) != \"{\") { }\n if (idx < code.length) {\n const part1 = code.substring(0, idx + 1);\n const part2 = code.substring(idx + 1);\n code = part1 + startingCode + part2;\n }\n }\n if (endingCode) {\n const lastClosingCurly = code.lastIndexOf(\"}\");\n code = code.substring(0, lastClosingCurly);\n code += endingCode + \"\\n}\";\n }\n return code;\n }\n}\nWebGPUShaderProcessor.AutoSamplerSuffix = \"Sampler\";\nWebGPUShaderProcessor.LeftOvertUBOName = \"LeftOver\";\nWebGPUShaderProcessor.InternalsUBOName = \"Internals\";\nWebGPUShaderProcessor.UniformSizes = {\n // GLSL types\n bool: 1,\n int: 1,\n float: 1,\n vec2: 2,\n ivec2: 2,\n vec3: 3,\n ivec3: 3,\n vec4: 4,\n ivec4: 4,\n mat2: 4,\n mat3: 12,\n mat4: 16,\n // WGSL types\n i32: 1,\n u32: 1,\n f32: 1,\n mat2x2: 4,\n mat3x3: 12,\n mat4x4: 16,\n};\n// eslint-disable-next-line @typescript-eslint/naming-convention\nWebGPUShaderProcessor._SamplerFunctionByWebGLSamplerType = {\n sampler2D: \"sampler2D\",\n sampler2DArray: \"sampler2DArray\",\n sampler2DShadow: \"sampler2DShadow\",\n sampler2DArrayShadow: \"sampler2DArrayShadow\",\n samplerCube: \"samplerCube\",\n sampler3D: \"sampler3D\",\n};\n// eslint-disable-next-line @typescript-eslint/naming-convention\nWebGPUShaderProcessor._TextureTypeByWebGLSamplerType = {\n sampler2D: \"texture2D\",\n sampler2DArray: \"texture2DArray\",\n sampler2DShadow: \"texture2D\",\n sampler2DArrayShadow: \"texture2DArray\",\n samplerCube: \"textureCube\",\n samplerCubeArray: \"textureCubeArray\",\n sampler3D: \"texture3D\",\n};\n// eslint-disable-next-line @typescript-eslint/naming-convention\nWebGPUShaderProcessor._GpuTextureViewDimensionByWebGPUTextureType = {\n textureCube: WebGPUConstants.TextureViewDimension.Cube,\n textureCubeArray: WebGPUConstants.TextureViewDimension.CubeArray,\n texture2D: WebGPUConstants.TextureViewDimension.E2d,\n texture2DArray: WebGPUConstants.TextureViewDimension.E2dArray,\n texture3D: WebGPUConstants.TextureViewDimension.E3d,\n};\n// if the webgl sampler type is not listed in this array, \"sampler\" is taken by default\n// eslint-disable-next-line @typescript-eslint/naming-convention\nWebGPUShaderProcessor._SamplerTypeByWebGLSamplerType = {\n sampler2DShadow: \"samplerShadow\",\n sampler2DArrayShadow: \"samplerShadow\",\n};\n// eslint-disable-next-line @typescript-eslint/naming-convention\nWebGPUShaderProcessor._IsComparisonSamplerByWebGPUSamplerType = {\n samplerShadow: true,\n samplerArrayShadow: true,\n sampler: false,\n};\n//# sourceMappingURL=webgpuShaderProcessor.js.map","import { UniformBuffer } from \"../../Materials/uniformBuffer.js\";\nimport { WebGPUShaderProcessor } from \"./webgpuShaderProcessor.js\";\n/** @internal */\nexport class WebGPUPipelineContext {\n get isAsync() {\n return false;\n }\n get isReady() {\n if (this.stages) {\n return true;\n }\n return false;\n }\n constructor(shaderProcessingContext, engine) {\n // The field is indexed by textureState. See @WebGPUMaterialContext.textureState for more information.\n this.bindGroupLayouts = {};\n this._name = \"unnamed\";\n this.shaderProcessingContext = shaderProcessingContext;\n this._leftOverUniformsByName = {};\n this.engine = engine;\n }\n _handlesSpectorRebuildCallback() {\n // Nothing to do yet for spector.\n }\n _fillEffectInformation(effect, uniformBuffersNames, uniformsNames, uniforms, samplerList, samplers, attributesNames, attributes) {\n const engine = this.engine;\n // Prevent Memory Leak by reducing the number of string, refer to the string instead of copy.\n effect._fragmentSourceCode = \"\";\n effect._vertexSourceCode = \"\";\n // this._fragmentSourceCodeOverride = \"\";\n // this._vertexSourceCodeOverride = \"\";\n const foundSamplers = this.shaderProcessingContext.availableTextures;\n let index;\n for (index = 0; index < samplerList.length; index++) {\n const name = samplerList[index];\n const sampler = foundSamplers[samplerList[index]];\n if (sampler == null || sampler == undefined) {\n samplerList.splice(index, 1);\n index--;\n }\n else {\n samplers[name] = index;\n }\n }\n for (const attr of engine.getAttributes(this, attributesNames)) {\n attributes.push(attr);\n }\n // Build the uniform layout for the left over uniforms.\n this.buildUniformLayout();\n const attributeNamesFromEffect = [];\n const attributeLocationsFromEffect = [];\n for (index = 0; index < attributesNames.length; index++) {\n const location = attributes[index];\n if (location >= 0) {\n attributeNamesFromEffect.push(attributesNames[index]);\n attributeLocationsFromEffect.push(location);\n }\n }\n this.shaderProcessingContext.attributeNamesFromEffect = attributeNamesFromEffect;\n this.shaderProcessingContext.attributeLocationsFromEffect = attributeLocationsFromEffect;\n }\n /** @internal */\n /**\n * Build the uniform buffer used in the material.\n */\n buildUniformLayout() {\n if (!this.shaderProcessingContext.leftOverUniforms.length) {\n return;\n }\n this.uniformBuffer = new UniformBuffer(this.engine, undefined, undefined, \"leftOver-\" + this._name);\n for (const leftOverUniform of this.shaderProcessingContext.leftOverUniforms) {\n const type = leftOverUniform.type.replace(/^(.*?)(<.*>)?$/, \"$1\");\n const size = WebGPUShaderProcessor.UniformSizes[type];\n this.uniformBuffer.addUniform(leftOverUniform.name, size, leftOverUniform.length);\n this._leftOverUniformsByName[leftOverUniform.name] = leftOverUniform.type;\n }\n this.uniformBuffer.create();\n }\n /**\n * Release all associated resources.\n **/\n dispose() {\n if (this.uniformBuffer) {\n this.uniformBuffer.dispose();\n }\n }\n /**\n * Sets an integer value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value Value to be set.\n */\n setInt(uniformName, value) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateInt(uniformName, value);\n }\n /**\n * Sets an int2 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First int in int2.\n * @param y Second int in int2.\n */\n setInt2(uniformName, x, y) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateInt2(uniformName, x, y);\n }\n /**\n * Sets an int3 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First int in int3.\n * @param y Second int in int3.\n * @param z Third int in int3.\n */\n setInt3(uniformName, x, y, z) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateInt3(uniformName, x, y, z);\n }\n /**\n * Sets an int4 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First int in int4.\n * @param y Second int in int4.\n * @param z Third int in int4.\n * @param w Fourth int in int4.\n */\n setInt4(uniformName, x, y, z, w) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateInt4(uniformName, x, y, z, w);\n }\n /**\n * Sets an int array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setIntArray(uniformName, array) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateIntArray(uniformName, array);\n }\n /**\n * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setIntArray2(uniformName, array) {\n this.setIntArray(uniformName, array);\n }\n /**\n * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setIntArray3(uniformName, array) {\n this.setIntArray(uniformName, array);\n }\n /**\n * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setIntArray4(uniformName, array) {\n this.setIntArray(uniformName, array);\n }\n /**\n * Sets an unsigned integer value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value Value to be set.\n */\n setUInt(uniformName, value) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateUInt(uniformName, value);\n }\n /**\n * Sets an unsigned int2 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First unsigned int in uint2.\n * @param y Second unsigned int in uint2.\n */\n setUInt2(uniformName, x, y) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateUInt2(uniformName, x, y);\n }\n /**\n * Sets an unsigned int3 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First unsigned int in uint3.\n * @param y Second unsigned int in uint3.\n * @param z Third unsigned int in uint3.\n */\n setUInt3(uniformName, x, y, z) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateUInt3(uniformName, x, y, z);\n }\n /**\n * Sets an unsigned int4 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First unsigned int in uint4.\n * @param y Second unsigned int in uint4.\n * @param z Third unsigned int in uint4.\n * @param w Fourth unsigned int in uint4.\n */\n setUInt4(uniformName, x, y, z, w) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateUInt4(uniformName, x, y, z, w);\n }\n /**\n * Sets an unsigned int array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setUIntArray(uniformName, array) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateUIntArray(uniformName, array);\n }\n /**\n * Sets an unsigned int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setUIntArray2(uniformName, array) {\n this.setUIntArray(uniformName, array);\n }\n /**\n * Sets an unsigned int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setUIntArray3(uniformName, array) {\n this.setUIntArray(uniformName, array);\n }\n /**\n * Sets an unsigned int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setUIntArray4(uniformName, array) {\n this.setUIntArray(uniformName, array);\n }\n /**\n * Sets an array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setArray(uniformName, array) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateArray(uniformName, array);\n }\n /**\n * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setArray2(uniformName, array) {\n this.setArray(uniformName, array);\n }\n /**\n * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setArray3(uniformName, array) {\n this.setArray(uniformName, array);\n }\n /**\n * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setArray4(uniformName, array) {\n this.setArray(uniformName, array);\n }\n /**\n * Sets matrices on a uniform variable.\n * @param uniformName Name of the variable.\n * @param matrices matrices to be set.\n */\n setMatrices(uniformName, matrices) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateMatrices(uniformName, matrices);\n }\n /**\n * Sets matrix on a uniform variable.\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n */\n setMatrix(uniformName, matrix) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateMatrix(uniformName, matrix);\n }\n /**\n * Sets a 3x3 matrix on a uniform variable. (Specified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n */\n setMatrix3x3(uniformName, matrix) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateMatrix3x3(uniformName, matrix);\n }\n /**\n * Sets a 2x2 matrix on a uniform variable. (Specified as [1,2,3,4] will result in [1,2][3,4] matrix)\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n */\n setMatrix2x2(uniformName, matrix) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateMatrix2x2(uniformName, matrix);\n }\n /**\n * Sets a float on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value value to be set.\n * @returns this effect.\n */\n setFloat(uniformName, value) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateFloat(uniformName, value);\n }\n /**\n * Sets a Vector2 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector2 vector2 to be set.\n */\n setVector2(uniformName, vector2) {\n this.setFloat2(uniformName, vector2.x, vector2.y);\n }\n /**\n * Sets a float2 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float2.\n * @param y Second float in float2.\n */\n setFloat2(uniformName, x, y) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateFloat2(uniformName, x, y);\n }\n /**\n * Sets a Vector3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector3 Value to be set.\n */\n setVector3(uniformName, vector3) {\n this.setFloat3(uniformName, vector3.x, vector3.y, vector3.z);\n }\n /**\n * Sets a float3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float3.\n * @param y Second float in float3.\n * @param z Third float in float3.\n */\n setFloat3(uniformName, x, y, z) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateFloat3(uniformName, x, y, z);\n }\n /**\n * Sets a Vector4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector4 Value to be set.\n */\n setVector4(uniformName, vector4) {\n this.setFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);\n }\n /**\n * Sets a Quaternion on a uniform variable.\n * @param uniformName Name of the variable.\n * @param quaternion Value to be set.\n */\n setQuaternion(uniformName, quaternion) {\n this.setFloat4(uniformName, quaternion.x, quaternion.y, quaternion.z, quaternion.w);\n }\n /**\n * Sets a float4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float4.\n * @param y Second float in float4.\n * @param z Third float in float4.\n * @param w Fourth float in float4.\n * @returns this effect.\n */\n setFloat4(uniformName, x, y, z, w) {\n if (!this.uniformBuffer || !this._leftOverUniformsByName[uniformName]) {\n return;\n }\n this.uniformBuffer.updateFloat4(uniformName, x, y, z, w);\n }\n /**\n * Sets a Color3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param color3 Value to be set.\n */\n setColor3(uniformName, color3) {\n this.setFloat3(uniformName, color3.r, color3.g, color3.b);\n }\n /**\n * Sets a Color4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param color3 Value to be set.\n * @param alpha Alpha value to be set.\n */\n setColor4(uniformName, color3, alpha) {\n this.setFloat4(uniformName, color3.r, color3.g, color3.b, alpha);\n }\n /**\n * Sets a Color4 on a uniform variable\n * @param uniformName defines the name of the variable\n * @param color4 defines the value to be set\n */\n setDirectColor4(uniformName, color4) {\n this.setFloat4(uniformName, color4.r, color4.g, color4.b, color4.a);\n }\n _getVertexShaderCode() {\n var _a;\n return (_a = this.sources) === null || _a === void 0 ? void 0 : _a.vertex;\n }\n _getFragmentShaderCode() {\n var _a;\n return (_a = this.sources) === null || _a === void 0 ? void 0 : _a.fragment;\n }\n}\n//# sourceMappingURL=webgpuPipelineContext.js.map","const _maxGroups = 4;\nconst _maxBindingsPerGroup = 1 << 16;\n// all types not listed are assumed to consume 1 location\nconst _typeToLocationSize = {\n // GLSL types\n mat2: 2,\n mat3: 3,\n mat4: 4,\n // WGSL types\n mat2x2: 2,\n mat3x3: 3,\n mat4x4: 4,\n};\n/**\n * @internal\n */\nexport class WebGPUShaderProcessingContext {\n static get KnownUBOs() {\n return WebGPUShaderProcessingContext._SimplifiedKnownBindings ? WebGPUShaderProcessingContext._SimplifiedKnownUBOs : WebGPUShaderProcessingContext._KnownUBOs;\n }\n constructor(shaderLanguage) {\n this.shaderLanguage = shaderLanguage;\n this._attributeNextLocation = 0;\n this._varyingNextLocation = 0;\n this.freeGroupIndex = 0;\n this.freeBindingIndex = 0;\n this.availableVaryings = {};\n this.availableAttributes = {};\n this.availableBuffers = {};\n this.availableTextures = {};\n this.availableSamplers = {};\n this.orderedAttributes = [];\n this.bindGroupLayoutEntries = [];\n this.bindGroupLayoutEntryInfo = [];\n this.bindGroupEntries = [];\n this.bufferNames = [];\n this.textureNames = [];\n this.samplerNames = [];\n this.leftOverUniforms = [];\n this._findStartingGroupBinding();\n }\n _findStartingGroupBinding() {\n const knownUBOs = WebGPUShaderProcessingContext.KnownUBOs;\n const groups = [];\n for (const name in knownUBOs) {\n const binding = knownUBOs[name].binding;\n if (binding.groupIndex === -1) {\n continue;\n }\n if (groups[binding.groupIndex] === undefined) {\n groups[binding.groupIndex] = binding.bindingIndex;\n }\n else {\n groups[binding.groupIndex] = Math.max(groups[binding.groupIndex], binding.bindingIndex);\n }\n }\n this.freeGroupIndex = groups.length - 1;\n if (this.freeGroupIndex === 0) {\n this.freeGroupIndex++;\n this.freeBindingIndex = 0;\n }\n else {\n this.freeBindingIndex = groups[groups.length - 1] + 1;\n }\n }\n getAttributeNextLocation(dataType, arrayLength = 0) {\n var _a;\n const index = this._attributeNextLocation;\n this._attributeNextLocation += ((_a = _typeToLocationSize[dataType]) !== null && _a !== void 0 ? _a : 1) * (arrayLength || 1);\n return index;\n }\n getVaryingNextLocation(dataType, arrayLength = 0) {\n var _a;\n const index = this._varyingNextLocation;\n this._varyingNextLocation += ((_a = _typeToLocationSize[dataType]) !== null && _a !== void 0 ? _a : 1) * (arrayLength || 1);\n return index;\n }\n getNextFreeUBOBinding() {\n return this._getNextFreeBinding(1);\n }\n _getNextFreeBinding(bindingCount) {\n if (this.freeBindingIndex > _maxBindingsPerGroup - bindingCount) {\n this.freeGroupIndex++;\n this.freeBindingIndex = 0;\n }\n if (this.freeGroupIndex === _maxGroups) {\n throw \"Too many textures or UBOs have been declared and it is not supported in WebGPU.\";\n }\n const returnValue = {\n groupIndex: this.freeGroupIndex,\n bindingIndex: this.freeBindingIndex,\n };\n this.freeBindingIndex += bindingCount;\n return returnValue;\n }\n}\n/** @internal */\nWebGPUShaderProcessingContext._SimplifiedKnownBindings = true; // if true, use only group=0,binding=0 as a known group/binding for the Scene ubo and use group=1,binding=X for all other bindings\n// if false, see _KnownUBOs for the known groups/bindings used\nWebGPUShaderProcessingContext._SimplifiedKnownUBOs = {\n Scene: { binding: { groupIndex: 0, bindingIndex: 0 } },\n Light0: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light1: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light2: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light3: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light4: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light5: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light6: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light7: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light8: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light9: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light10: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light11: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light12: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light13: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light14: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light15: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light16: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light17: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light18: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light19: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light20: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light21: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light22: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light23: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light24: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light25: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light26: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light27: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light28: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light29: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light30: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Light31: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Material: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Mesh: { binding: { groupIndex: -1, bindingIndex: -1 } },\n Internals: { binding: { groupIndex: -1, bindingIndex: -1 } },\n};\nWebGPUShaderProcessingContext._KnownUBOs = {\n Scene: { binding: { groupIndex: 0, bindingIndex: 0 } },\n Light0: { binding: { groupIndex: 1, bindingIndex: 0 } },\n Light1: { binding: { groupIndex: 1, bindingIndex: 1 } },\n Light2: { binding: { groupIndex: 1, bindingIndex: 2 } },\n Light3: { binding: { groupIndex: 1, bindingIndex: 3 } },\n Light4: { binding: { groupIndex: 1, bindingIndex: 4 } },\n Light5: { binding: { groupIndex: 1, bindingIndex: 5 } },\n Light6: { binding: { groupIndex: 1, bindingIndex: 6 } },\n Light7: { binding: { groupIndex: 1, bindingIndex: 7 } },\n Light8: { binding: { groupIndex: 1, bindingIndex: 8 } },\n Light9: { binding: { groupIndex: 1, bindingIndex: 9 } },\n Light10: { binding: { groupIndex: 1, bindingIndex: 10 } },\n Light11: { binding: { groupIndex: 1, bindingIndex: 11 } },\n Light12: { binding: { groupIndex: 1, bindingIndex: 12 } },\n Light13: { binding: { groupIndex: 1, bindingIndex: 13 } },\n Light14: { binding: { groupIndex: 1, bindingIndex: 14 } },\n Light15: { binding: { groupIndex: 1, bindingIndex: 15 } },\n Light16: { binding: { groupIndex: 1, bindingIndex: 16 } },\n Light17: { binding: { groupIndex: 1, bindingIndex: 17 } },\n Light18: { binding: { groupIndex: 1, bindingIndex: 18 } },\n Light19: { binding: { groupIndex: 1, bindingIndex: 19 } },\n Light20: { binding: { groupIndex: 1, bindingIndex: 20 } },\n Light21: { binding: { groupIndex: 1, bindingIndex: 21 } },\n Light22: { binding: { groupIndex: 1, bindingIndex: 22 } },\n Light23: { binding: { groupIndex: 1, bindingIndex: 23 } },\n Light24: { binding: { groupIndex: 1, bindingIndex: 24 } },\n Light25: { binding: { groupIndex: 1, bindingIndex: 25 } },\n Light26: { binding: { groupIndex: 1, bindingIndex: 26 } },\n Light27: { binding: { groupIndex: 1, bindingIndex: 27 } },\n Light28: { binding: { groupIndex: 1, bindingIndex: 28 } },\n Light29: { binding: { groupIndex: 1, bindingIndex: 29 } },\n Light30: { binding: { groupIndex: 1, bindingIndex: 30 } },\n Light31: { binding: { groupIndex: 1, bindingIndex: 31 } },\n Material: { binding: { groupIndex: 2, bindingIndex: 0 } },\n Mesh: { binding: { groupIndex: 2, bindingIndex: 1 } },\n Internals: { binding: { groupIndex: 2, bindingIndex: 2 } },\n};\n//# sourceMappingURL=webgpuShaderProcessingContext.js.map","import { WebGPUShaderProcessingContext } from \"./webgpuShaderProcessingContext.js\";\nimport * as WebGPUConstants from \"./webgpuConstants.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { WebGPUShaderProcessor } from \"./webgpuShaderProcessor.js\";\nimport { ShaderLanguage } from \"../../Materials/shaderLanguage.js\";\n/** @internal */\nexport class WebGPUShaderProcessorGLSL extends WebGPUShaderProcessor {\n constructor() {\n super(...arguments);\n this._missingVaryings = [];\n this._textureArrayProcessing = [];\n this._vertexIsGLES3 = false;\n this._fragmentIsGLES3 = false;\n this.shaderLanguage = ShaderLanguage.GLSL;\n this.parseGLES3 = true;\n }\n _getArraySize(name, type, preProcessors) {\n let length = 0;\n const startArray = name.indexOf(\"[\");\n const endArray = name.indexOf(\"]\");\n if (startArray > 0 && endArray > 0) {\n const lengthInString = name.substring(startArray + 1, endArray);\n length = +lengthInString;\n if (isNaN(length)) {\n length = +preProcessors[lengthInString.trim()];\n }\n name = name.substr(0, startArray);\n }\n return [name, type, length];\n }\n initializeShaders(processingContext) {\n this._webgpuProcessingContext = processingContext;\n this._missingVaryings.length = 0;\n this._textureArrayProcessing.length = 0;\n this.attributeKeywordName = undefined;\n this.varyingVertexKeywordName = undefined;\n this.varyingFragmentKeywordName = undefined;\n }\n preProcessShaderCode(code, isFragment) {\n const ubDeclaration = `// Internals UBO\\r\\nuniform ${WebGPUShaderProcessor.InternalsUBOName} {\\nfloat yFactor_;\\nfloat textureOutputHeight_;\\n};\\n`;\n const alreadyInjected = code.indexOf(\"// Internals UBO\") !== -1;\n if (isFragment) {\n this._fragmentIsGLES3 = code.indexOf(\"#version 3\") !== -1;\n if (this._fragmentIsGLES3) {\n this.varyingFragmentKeywordName = \"in\";\n }\n return alreadyInjected ? code : ubDeclaration + \"##INJECTCODE##\\n\" + code;\n }\n this._vertexIsGLES3 = code.indexOf(\"#version 3\") !== -1;\n if (this._vertexIsGLES3) {\n this.attributeKeywordName = \"in\";\n this.varyingVertexKeywordName = \"out\";\n }\n return alreadyInjected ? code : ubDeclaration + code;\n }\n varyingCheck(varying, isFragment) {\n const outRegex = /(flat\\s)?\\s*out/;\n const inRegex = /(flat\\s)?\\s*in/;\n const varyingRegex = /(flat\\s)?\\s*varying/;\n const regex = isFragment && this._fragmentIsGLES3 ? inRegex : !isFragment && this._vertexIsGLES3 ? outRegex : varyingRegex;\n return regex.test(varying);\n }\n varyingProcessor(varying, isFragment, preProcessors) {\n var _a;\n this._preProcessors = preProcessors;\n const outRegex = /\\s*(flat)?\\s*out\\s+(?:(?:highp)?|(?:lowp)?)\\s*(\\S+)\\s+(\\S+)\\s*;/gm;\n const inRegex = /\\s*(flat)?\\s*in\\s+(?:(?:highp)?|(?:lowp)?)\\s*(\\S+)\\s+(\\S+)\\s*;/gm;\n const varyingRegex = /\\s*(flat)?\\s*varying\\s+(?:(?:highp)?|(?:lowp)?)\\s*(\\S+)\\s+(\\S+)\\s*;/gm;\n const regex = isFragment && this._fragmentIsGLES3 ? inRegex : !isFragment && this._vertexIsGLES3 ? outRegex : varyingRegex;\n const match = regex.exec(varying);\n if (match !== null) {\n const interpolationQualifier = (_a = match[1]) !== null && _a !== void 0 ? _a : \"\";\n const varyingType = match[2];\n const name = match[3];\n let location;\n if (isFragment) {\n location = this._webgpuProcessingContext.availableVaryings[name];\n this._missingVaryings[location] = \"\";\n if (location === undefined) {\n Logger.Warn(`Invalid fragment shader: The varying named \"${name}\" is not declared in the vertex shader! This declaration will be ignored.`);\n }\n }\n else {\n location = this._webgpuProcessingContext.getVaryingNextLocation(varyingType, this._getArraySize(name, varyingType, preProcessors)[2]);\n this._webgpuProcessingContext.availableVaryings[name] = location;\n this._missingVaryings[location] = `layout(location = ${location}) ${interpolationQualifier} in ${varyingType} ${name};`;\n }\n varying = varying.replace(match[0], location === undefined ? \"\" : `layout(location = ${location}) ${interpolationQualifier} ${isFragment ? \"in\" : \"out\"} ${varyingType} ${name};`);\n }\n return varying;\n }\n attributeProcessor(attribute, preProcessors) {\n this._preProcessors = preProcessors;\n const inRegex = /\\s*in\\s+(\\S+)\\s+(\\S+)\\s*;/gm;\n const attribRegex = /\\s*attribute\\s+(\\S+)\\s+(\\S+)\\s*;/gm;\n const regex = this._vertexIsGLES3 ? inRegex : attribRegex;\n const match = regex.exec(attribute);\n if (match !== null) {\n const attributeType = match[1];\n const name = match[2];\n const location = this._webgpuProcessingContext.getAttributeNextLocation(attributeType, this._getArraySize(name, attributeType, preProcessors)[2]);\n this._webgpuProcessingContext.availableAttributes[name] = location;\n this._webgpuProcessingContext.orderedAttributes[location] = name;\n attribute = attribute.replace(match[0], `layout(location = ${location}) in ${attributeType} ${name};`);\n }\n return attribute;\n }\n uniformProcessor(uniform, isFragment, preProcessors) {\n var _a;\n this._preProcessors = preProcessors;\n const uniformRegex = /\\s*uniform\\s+(?:(?:highp)?|(?:lowp)?)\\s*(\\S+)\\s+(\\S+)\\s*;/gm;\n const match = uniformRegex.exec(uniform);\n if (match !== null) {\n let uniformType = match[1];\n let name = match[2];\n if (uniformType.indexOf(\"sampler\") === 0 || uniformType.indexOf(\"sampler\") === 1) {\n let arraySize = 0; // 0 means the texture is not declared as an array\n [name, uniformType, arraySize] = this._getArraySize(name, uniformType, preProcessors);\n let textureInfo = this._webgpuProcessingContext.availableTextures[name];\n if (!textureInfo) {\n textureInfo = {\n autoBindSampler: true,\n isTextureArray: arraySize > 0,\n isStorageTexture: false,\n textures: [],\n sampleType: WebGPUConstants.TextureSampleType.Float,\n };\n for (let i = 0; i < (arraySize || 1); ++i) {\n textureInfo.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding());\n }\n }\n const samplerType = (_a = WebGPUShaderProcessor._SamplerTypeByWebGLSamplerType[uniformType]) !== null && _a !== void 0 ? _a : \"sampler\";\n const isComparisonSampler = !!WebGPUShaderProcessor._IsComparisonSamplerByWebGPUSamplerType[samplerType];\n const samplerBindingType = isComparisonSampler ? WebGPUConstants.SamplerBindingType.Comparison : WebGPUConstants.SamplerBindingType.Filtering;\n const samplerName = name + WebGPUShaderProcessor.AutoSamplerSuffix;\n let samplerInfo = this._webgpuProcessingContext.availableSamplers[samplerName];\n if (!samplerInfo) {\n samplerInfo = {\n binding: this._webgpuProcessingContext.getNextFreeUBOBinding(),\n type: samplerBindingType,\n };\n }\n const componentType = uniformType.charAt(0) === \"u\" ? \"u\" : uniformType.charAt(0) === \"i\" ? \"i\" : \"\";\n if (componentType) {\n uniformType = uniformType.substr(1);\n }\n const sampleType = isComparisonSampler\n ? WebGPUConstants.TextureSampleType.Depth\n : componentType === \"u\"\n ? WebGPUConstants.TextureSampleType.Uint\n : componentType === \"i\"\n ? WebGPUConstants.TextureSampleType.Sint\n : WebGPUConstants.TextureSampleType.Float;\n textureInfo.sampleType = sampleType;\n const isTextureArray = arraySize > 0;\n const samplerGroupIndex = samplerInfo.binding.groupIndex;\n const samplerBindingIndex = samplerInfo.binding.bindingIndex;\n const samplerFunction = WebGPUShaderProcessor._SamplerFunctionByWebGLSamplerType[uniformType];\n const textureType = WebGPUShaderProcessor._TextureTypeByWebGLSamplerType[uniformType];\n const textureDimension = WebGPUShaderProcessor._GpuTextureViewDimensionByWebGPUTextureType[textureType];\n // Manage textures and samplers.\n if (!isTextureArray) {\n arraySize = 1;\n uniform = `layout(set = ${samplerGroupIndex}, binding = ${samplerBindingIndex}) uniform ${componentType}${samplerType} ${samplerName};\r\n layout(set = ${textureInfo.textures[0].groupIndex}, binding = ${textureInfo.textures[0].bindingIndex}) uniform ${textureType} ${name}Texture;\r\n #define ${name} ${componentType}${samplerFunction}(${name}Texture, ${samplerName})`;\n }\n else {\n const layouts = [];\n layouts.push(`layout(set = ${samplerGroupIndex}, binding = ${samplerBindingIndex}) uniform ${componentType}${samplerType} ${samplerName};`);\n uniform = `\\r\\n`;\n for (let i = 0; i < arraySize; ++i) {\n const textureSetIndex = textureInfo.textures[i].groupIndex;\n const textureBindingIndex = textureInfo.textures[i].bindingIndex;\n layouts.push(`layout(set = ${textureSetIndex}, binding = ${textureBindingIndex}) uniform ${textureType} ${name}Texture${i};`);\n uniform += `${i > 0 ? \"\\r\\n\" : \"\"}#define ${name}${i} ${componentType}${samplerFunction}(${name}Texture${i}, ${samplerName})`;\n }\n uniform = layouts.join(\"\\r\\n\") + uniform;\n this._textureArrayProcessing.push(name);\n }\n this._webgpuProcessingContext.availableTextures[name] = textureInfo;\n this._webgpuProcessingContext.availableSamplers[samplerName] = samplerInfo;\n this._addSamplerBindingDescription(samplerName, samplerInfo, !isFragment);\n for (let i = 0; i < arraySize; ++i) {\n this._addTextureBindingDescription(name, textureInfo, i, textureDimension, null, !isFragment);\n }\n }\n else {\n this._addUniformToLeftOverUBO(name, uniformType, preProcessors);\n uniform = \"\";\n }\n }\n return uniform;\n }\n uniformBufferProcessor(uniformBuffer, isFragment) {\n const uboRegex = /uniform\\s+(\\w+)/gm;\n const match = uboRegex.exec(uniformBuffer);\n if (match !== null) {\n const name = match[1];\n let uniformBufferInfo = this._webgpuProcessingContext.availableBuffers[name];\n if (!uniformBufferInfo) {\n const knownUBO = WebGPUShaderProcessingContext.KnownUBOs[name];\n let binding;\n if (knownUBO && knownUBO.binding.groupIndex !== -1) {\n binding = knownUBO.binding;\n }\n else {\n binding = this._webgpuProcessingContext.getNextFreeUBOBinding();\n }\n uniformBufferInfo = { binding };\n this._webgpuProcessingContext.availableBuffers[name] = uniformBufferInfo;\n }\n this._addBufferBindingDescription(name, uniformBufferInfo, WebGPUConstants.BufferBindingType.Uniform, !isFragment);\n uniformBuffer = uniformBuffer.replace(\"uniform\", `layout(set = ${uniformBufferInfo.binding.groupIndex}, binding = ${uniformBufferInfo.binding.bindingIndex}) uniform`);\n }\n return uniformBuffer;\n }\n postProcessor(code, defines, isFragment, processingContext, engine) {\n const hasDrawBuffersExtension = code.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;\n // Remove extensions\n const regex = /#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;\n code = code.replace(regex, \"\");\n // Replace instructions\n code = code.replace(/texture2D\\s*\\(/g, \"texture(\");\n if (isFragment) {\n const hasFragCoord = code.indexOf(\"gl_FragCoord\") >= 0;\n const fragCoordCode = `\r\n glFragCoord_ = gl_FragCoord;\r\n if (yFactor_ == 1.) {\r\n glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y;\r\n }\r\n `;\n const injectCode = hasFragCoord ? \"vec4 glFragCoord_;\\n\" : \"\";\n code = code.replace(/texture2DLodEXT\\s*\\(/g, \"textureLod(\");\n code = code.replace(/textureCubeLodEXT\\s*\\(/g, \"textureLod(\");\n code = code.replace(/textureCube\\s*\\(/g, \"texture(\");\n code = code.replace(/gl_FragDepthEXT/g, \"gl_FragDepth\");\n code = code.replace(/gl_FragColor/g, \"glFragColor\");\n code = code.replace(/gl_FragData/g, \"glFragData\");\n code = code.replace(/gl_FragCoord/g, \"glFragCoord_\");\n if (!this._fragmentIsGLES3) {\n code = code.replace(/void\\s+?main\\s*\\(/g, (hasDrawBuffersExtension ? \"\" : \"layout(location = 0) out vec4 glFragColor;\\n\") + \"void main(\");\n }\n else {\n const match = /^\\s*out\\s+\\S+\\s+\\S+\\s*;/gm.exec(code);\n if (match !== null) {\n code = code.substring(0, match.index) + \"layout(location = 0) \" + code.substring(match.index);\n }\n }\n code = code.replace(/dFdy/g, \"(-yFactor_)*dFdy\"); // will also handle dFdyCoarse and dFdyFine\n code = code.replace(\"##INJECTCODE##\", injectCode);\n if (hasFragCoord) {\n code = this._injectStartingAndEndingCode(code, \"void main\", fragCoordCode);\n }\n }\n else {\n code = code.replace(/gl_InstanceID/g, \"gl_InstanceIndex\");\n code = code.replace(/gl_VertexID/g, \"gl_VertexIndex\");\n const hasMultiviewExtension = defines.indexOf(\"#define MULTIVIEW\") !== -1;\n if (hasMultiviewExtension) {\n return \"#extension GL_OVR_multiview2 : require\\nlayout (num_views = 2) in;\\n\" + code;\n }\n }\n // Flip Y + convert z range from [-1,1] to [0,1]\n if (!isFragment) {\n const lastClosingCurly = code.lastIndexOf(\"}\");\n code = code.substring(0, lastClosingCurly);\n code += \"gl_Position.y *= yFactor_;\\n\";\n if (!engine.isNDCHalfZRange) {\n code += \"gl_Position.z = (gl_Position.z + gl_Position.w) / 2.0;\\n\";\n }\n code += \"}\";\n }\n return code;\n }\n _applyTextureArrayProcessing(code, name) {\n // Replaces the occurrences of name[XX] by nameXX\n const regex = new RegExp(name + \"\\\\s*\\\\[(.+)?\\\\]\", \"gm\");\n let match = regex.exec(code);\n while (match !== null) {\n const index = match[1];\n let iindex = +index;\n if (this._preProcessors && isNaN(iindex)) {\n iindex = +this._preProcessors[index.trim()];\n }\n code = code.replace(match[0], name + iindex);\n match = regex.exec(code);\n }\n return code;\n }\n _generateLeftOverUBOCode(name, uniformBufferDescription) {\n let ubo = `layout(set = ${uniformBufferDescription.binding.groupIndex}, binding = ${uniformBufferDescription.binding.bindingIndex}) uniform ${name} {\\n `;\n for (const leftOverUniform of this._webgpuProcessingContext.leftOverUniforms) {\n if (leftOverUniform.length > 0) {\n ubo += ` ${leftOverUniform.type} ${leftOverUniform.name}[${leftOverUniform.length}];\\n`;\n }\n else {\n ubo += ` ${leftOverUniform.type} ${leftOverUniform.name};\\n`;\n }\n }\n ubo += \"};\\n\\n\";\n return ubo;\n }\n finalizeShaders(vertexCode, fragmentCode) {\n // make replacements for texture names in the texture array case\n for (let i = 0; i < this._textureArrayProcessing.length; ++i) {\n const name = this._textureArrayProcessing[i];\n vertexCode = this._applyTextureArrayProcessing(vertexCode, name);\n fragmentCode = this._applyTextureArrayProcessing(fragmentCode, name);\n }\n // inject the missing varying in the fragment shader\n for (let i = 0; i < this._missingVaryings.length; ++i) {\n const decl = this._missingVaryings[i];\n if (decl && decl.length > 0) {\n fragmentCode = decl + \"\\n\" + fragmentCode;\n }\n }\n // Builds the leftover UBOs.\n const leftOverUBO = this._buildLeftOverUBO();\n vertexCode = leftOverUBO + vertexCode;\n fragmentCode = leftOverUBO + fragmentCode;\n this._collectBindingNames();\n this._preCreateBindGroupEntries();\n this._preProcessors = null;\n return { vertexCode, fragmentCode };\n }\n}\n//# sourceMappingURL=webgpuShaderProcessorsGLSL.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"bonesDeclaration\";\nconst shader = `#if NUM_BONE_INFLUENCERS>0\nattribute matricesIndices : vec4;\rattribute matricesWeights : vec4;\r#if NUM_BONE_INFLUENCERS>4\nattribute matricesIndicesExtra : vec4;\rattribute matricesWeightsExtra : vec4;\r#endif\n#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#ifdef BONETEXTURE\nvar boneSampler : texture_2d;\runiform boneTextureWidth : f32;\r#else\nuniform mBones : array;\r#ifdef BONES_VELOCITY_ENABLED\nuniform mPreviousBones : array;\r#endif\n#endif\n#ifdef BONETEXTURE\nfn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4\r{\rlet offset=i32(index) *4; \rlet m0=textureLoad(smp,vec2(offset+0,0),0);\rlet m1=textureLoad(smp,vec2(offset+1,0),0);\rlet m2=textureLoad(smp,vec2(offset+2,0),0);\rlet m3=textureLoad(smp,vec2(offset+3,0),0);\rreturn mat4x4(m0,m1,m2,m3);\r}\r#endif\n#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const bonesDeclaration = { name, shader };\n//# sourceMappingURL=bonesDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"bonesVertex\";\nconst shader = `#ifndef BAKED_VERTEX_ANIMATION_TEXTURE\n#if NUM_BONE_INFLUENCERS>0\nvar influence : mat4x4;\r#ifdef BONETEXTURE\ninfluence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0];\r#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1];\r#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2];\r#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3];\r#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0];\r#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1];\r#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2];\r#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3];\r#endif \n#else \ninfluence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0];\r#if NUM_BONE_INFLUENCERS>1\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1];\r#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2];\r#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3];\r#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0];\r#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1];\r#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2];\r#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3];\r#endif \n#endif\nfinalWorld=finalWorld*influence;\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const bonesVertex = { name, shader };\n//# sourceMappingURL=bonesVertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"bakedVertexAnimationDeclaration\";\nconst shader = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\nuniform bakedVertexAnimationTime: f32;\runiform bakedVertexAnimationTextureSizeInverted: vec2;\runiform bakedVertexAnimationSettings: vec4;\rvar bakedVertexAnimationTexture : texture_2d;\r#ifdef INSTANCES\nattribute bakedVertexAnimationSettingsInstanced : vec4;\r#endif\nfn readMatrixFromRawSamplerVAT(smp : texture_2d,index : f32,frame : f32)->mat4x4\r{\rlet offset=i32(index)*4;\rlet frameUV=i32(frame);\rlet m0=textureLoad(smp,vec2(offset+0,frameUV),0);\rlet m1=textureLoad(smp,vec2(offset+1,frameUV),0);\rlet m2=textureLoad(smp,vec2(offset+2,frameUV),0);\rlet m3=textureLoad(smp,vec2(offset+3,frameUV),0);\rreturn mat4x4(m0,m1,m2,m3);\r}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const bakedVertexAnimationDeclaration = { name, shader };\n//# sourceMappingURL=bakedVertexAnimationDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"bakedVertexAnimation\";\nconst shader = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE\n{\r#ifdef INSTANCES\nlet VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;\rlet VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;\rlet VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;\rlet VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w;\r#else\nlet VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;\rlet VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;\rlet VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;\rlet VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w;\r#endif\nlet totalFrames: f32=VATEndFrame-VATStartFrame+1.0;\rlet time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;\rlet frameCorrection: f32=select(1.0,0.0,time<1.0);\rlet numOfFrames: f32=totalFrames-frameCorrection;\rvar VATFrameNum: f32=fract(time)*numOfFrames;\rVATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;\rVATFrameNum=floor(VATFrameNum);\rVATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;\rvar VATInfluence : mat4x4;\rVATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0];\r#if NUM_BONE_INFLUENCERS>1\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1];\r#endif\n#if NUM_BONE_INFLUENCERS>2\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2];\r#endif\n#if NUM_BONE_INFLUENCERS>3\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3];\r#endif\n#if NUM_BONE_INFLUENCERS>4\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0];\r#endif\n#if NUM_BONE_INFLUENCERS>5\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1];\r#endif\n#if NUM_BONE_INFLUENCERS>6\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2];\r#endif\n#if NUM_BONE_INFLUENCERS>7\nVATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3];\r#endif\nfinalWorld=finalWorld*VATInfluence;\r}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const bakedVertexAnimation = { name, shader };\n//# sourceMappingURL=bakedVertexAnimation.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"clipPlaneFragment\";\nconst shader = `#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nif (false) {}\r#endif\n#ifdef CLIPPLANE\nelse if (fragmentInputs.fClipDistance>0.0)\r{\rdiscard;\r}\r#endif\n#ifdef CLIPPLANE2\nelse if (fragmentInputs.fClipDistance2>0.0)\r{\rdiscard;\r}\r#endif\n#ifdef CLIPPLANE3\nelse if (fragmentInputs.fClipDistance3>0.0)\r{\rdiscard;\r}\r#endif\n#ifdef CLIPPLANE4\nelse if (fragmentInputs.fClipDistance4>0.0)\r{\rdiscard;\r}\r#endif\n#ifdef CLIPPLANE5\nelse if (fragmentInputs.fClipDistance5>0.0)\r{\rdiscard;\r}\r#endif\n#ifdef CLIPPLANE6\nelse if (fragmentInputs.fClipDistance6>0.0)\r{\rdiscard;\r}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const clipPlaneFragment = { name, shader };\n//# sourceMappingURL=clipPlaneFragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"clipPlaneFragmentDeclaration\";\nconst shader = `#ifdef CLIPPLANE\nvarying fClipDistance: f32;\r#endif\n#ifdef CLIPPLANE2\nvarying fClipDistance2: f32;\r#endif\n#ifdef CLIPPLANE3\nvarying fClipDistance3: f32;\r#endif\n#ifdef CLIPPLANE4\nvarying fClipDistance4: f32;\r#endif\n#ifdef CLIPPLANE5\nvarying fClipDistance5: f32;\r#endif\n#ifdef CLIPPLANE6\nvarying fClipDistance6: f32;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const clipPlaneFragmentDeclaration = { name, shader };\n//# sourceMappingURL=clipPlaneFragmentDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"clipPlaneVertex\";\nconst shader = `#ifdef CLIPPLANE\nvertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane);\r#endif\n#ifdef CLIPPLANE2\nvertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2);\r#endif\n#ifdef CLIPPLANE3\nvertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3);\r#endif\n#ifdef CLIPPLANE4\nvertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4);\r#endif\n#ifdef CLIPPLANE5\nvertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5);\r#endif\n#ifdef CLIPPLANE6\nvertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6);\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const clipPlaneVertex = { name, shader };\n//# sourceMappingURL=clipPlaneVertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"clipPlaneVertexDeclaration\";\nconst shader = `#ifdef CLIPPLANE\nuniform vClipPlane: vec4;\rvarying fClipDistance: f32;\r#endif\n#ifdef CLIPPLANE2\nuniform vClipPlane2: vec4;\rvarying fClipDistance2: f32;\r#endif\n#ifdef CLIPPLANE3\nuniform vClipPlane3: vec4;\rvarying fClipDistance3: f32;\r#endif\n#ifdef CLIPPLANE4\nuniform vClipPlane4: vec4;\rvarying fClipDistance4: f32;\r#endif\n#ifdef CLIPPLANE5\nuniform vClipPlane5: vec4;\rvarying fClipDistance5: f32;\r#endif\n#ifdef CLIPPLANE6\nuniform vClipPlane6: vec4;\rvarying fClipDistance6: f32;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const clipPlaneVertexDeclaration = { name, shader };\n//# sourceMappingURL=clipPlaneVertexDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"instancesDeclaration\";\nconst shader = `#ifdef INSTANCES\nattribute world0 : vec4;\rattribute world1 : vec4;\rattribute world2 : vec4;\rattribute world3 : vec4;\r#ifdef INSTANCESCOLOR\nattribute instanceColor : vec4;\r#endif\n#if defined(THIN_INSTANCES) && !defined(WORLD_UBO)\nuniform world : mat4x4;\r#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nattribute previousWorld0 : vec4;\rattribute previousWorld1 : vec4;\rattribute previousWorld2 : vec4;\rattribute previousWorld3 : vec4;\r#ifdef THIN_INSTANCES\nuniform previousWorld : mat4x4;\r#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nuniform world : mat4x4;\r#endif\n#if defined(VELOCITY) || defined(PREPASS_VELOCITY)\nuniform previousWorld : mat4x4;\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const instancesDeclaration = { name, shader };\n//# sourceMappingURL=instancesDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"instancesVertex\";\nconst shader = `#ifdef INSTANCES\nvar finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3);\r#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=mat4x4(previousWorld0,previousWorld1,previousWorld2,previousWorld3);\r#endif\n#ifdef THIN_INSTANCES\n#if !defined(WORLD_UBO)\nfinalWorld=uniforms.world*finalWorld;\r#else\nfinalWorld=mesh.world*finalWorld;\r#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nfinalPreviousWorld=previousWorld*finalPreviousWorld;\r#endif\n#endif\n#else\n#if !defined(WORLD_UBO)\nvar finalWorld=uniforms.world;\r#else\nvar finalWorld=mesh.world;\r#endif\n#if defined(PREPASS_VELOCITY) || defined(VELOCITY)\nvar finalPreviousWorld=previousWorld;\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const instancesVertex = { name, shader };\n//# sourceMappingURL=instancesVertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"meshUboDeclaration\";\nconst shader = `struct Mesh {\rworld : mat4x4,\rvisibility : f32,\r};\rvar mesh : Mesh;\r#define WORLD_UBO\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const meshUboDeclaration = { name, shader };\n//# sourceMappingURL=meshUboDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"morphTargetsVertex\";\nconst shader = `#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE \nvertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;\rpositionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];\rvertexID=vertexID+1.0;\r#ifdef MORPHTARGETS_NORMAL\nnormalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];\rvertexID=vertexID+1.0;\r#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];\rvertexID=vertexID+1.0;\r#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\r#endif\n#else\npositionUpdated=positionUpdated+(position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];\r#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];\r#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}];\r#endif\n#ifdef MORPHTARGETS_UV\nuvUpdated=uvUpdated+(uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];\r#endif\n#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const morphTargetsVertex = { name, shader };\n//# sourceMappingURL=morphTargetsVertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"morphTargetsVertexDeclaration\";\nconst shader = `#ifdef MORPHTARGETS\n#ifndef MORPHTARGETS_TEXTURE\nattribute position{X} : vec3;\r#ifdef MORPHTARGETS_NORMAL\nattribute normal{X} : vec3;\r#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute tangent{X} : vec3;\r#endif\n#ifdef MORPHTARGETS_UV\nattribute uv_{X} : vec2;\r#endif\n#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const morphTargetsVertexDeclaration = { name, shader };\n//# sourceMappingURL=morphTargetsVertexDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"morphTargetsVertexGlobal\";\nconst shader = `#ifdef MORPHTARGETS\n#ifdef MORPHTARGETS_TEXTURE\nvar vertexID : f32;\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const morphTargetsVertexGlobal = { name, shader };\n//# sourceMappingURL=morphTargetsVertexGlobal.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"morphTargetsVertexGlobalDeclaration\";\nconst shader = `#ifdef MORPHTARGETS\nuniform morphTargetInfluences : array;\r#ifdef MORPHTARGETS_TEXTURE \nuniform morphTargetTextureIndices : array;\runiform morphTargetTextureInfo : vec3;\rvar morphTargets : texture_2d_array;\rvar morphTargetsSampler : sampler;\rfn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3\r{ \rlet y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);\rlet x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;\rlet textureUV=vec2((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);\rreturn textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;\r}\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const morphTargetsVertexGlobalDeclaration = { name, shader };\n//# sourceMappingURL=morphTargetsVertexGlobalDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"sceneUboDeclaration\";\nconst shader = `struct Scene {\rviewProjection : mat4x4,\r#ifdef MULTIVIEW\nviewProjectionR : mat4x4,\r#endif \nview : mat4x4,\rprojection : mat4x4,\rvEyePosition : vec4,\r};\rvar scene : Scene;\r`;\n// Sideeffect\nShaderStore.IncludesShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const sceneUboDeclaration = { name, shader };\n//# sourceMappingURL=sceneUboDeclaration.js.map","import { WebGPUShaderProcessingContext } from \"./webgpuShaderProcessingContext.js\";\nimport * as WebGPUConstants from \"./webgpuConstants.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { WebGPUShaderProcessor } from \"./webgpuShaderProcessor.js\";\nimport { RemoveComments } from \"../../Misc/codeStringParsingTools.js\";\nimport \"../../ShadersWGSL/ShadersInclude/bonesDeclaration.js\";\nimport \"../../ShadersWGSL/ShadersInclude/bonesVertex.js\";\nimport \"../../ShadersWGSL/ShadersInclude/bakedVertexAnimationDeclaration.js\";\nimport \"../../ShadersWGSL/ShadersInclude/bakedVertexAnimation.js\";\nimport \"../../ShadersWGSL/ShadersInclude/clipPlaneFragment.js\";\nimport \"../../ShadersWGSL/ShadersInclude/clipPlaneFragmentDeclaration.js\";\nimport \"../../ShadersWGSL/ShadersInclude/clipPlaneVertex.js\";\nimport \"../../ShadersWGSL/ShadersInclude/clipPlaneVertexDeclaration.js\";\nimport \"../../ShadersWGSL/ShadersInclude/instancesDeclaration.js\";\nimport \"../../ShadersWGSL/ShadersInclude/instancesVertex.js\";\nimport \"../../ShadersWGSL/ShadersInclude/meshUboDeclaration.js\";\nimport \"../../ShadersWGSL/ShadersInclude/morphTargetsVertex.js\";\nimport \"../../ShadersWGSL/ShadersInclude/morphTargetsVertexDeclaration.js\";\nimport \"../../ShadersWGSL/ShadersInclude/morphTargetsVertexGlobal.js\";\nimport \"../../ShadersWGSL/ShadersInclude/morphTargetsVertexGlobalDeclaration.js\";\nimport \"../../ShadersWGSL/ShadersInclude/sceneUboDeclaration.js\";\nimport { ShaderLanguage } from \"../../Materials/shaderLanguage.js\";\nconst builtInName_frag_depth = \"fragmentOutputs.fragDepth\";\nconst leftOverVarName = \"uniforms\";\nconst internalsVarName = \"internals\";\nconst gpuTextureViewDimensionByWebGPUTextureFunction = {\n texture_1d: WebGPUConstants.TextureViewDimension.E1d,\n texture_2d: WebGPUConstants.TextureViewDimension.E2d,\n texture_2d_array: WebGPUConstants.TextureViewDimension.E2dArray,\n texture_3d: WebGPUConstants.TextureViewDimension.E3d,\n texture_cube: WebGPUConstants.TextureViewDimension.Cube,\n texture_cube_array: WebGPUConstants.TextureViewDimension.CubeArray,\n texture_multisampled_2d: WebGPUConstants.TextureViewDimension.E2d,\n texture_depth_2d: WebGPUConstants.TextureViewDimension.E2d,\n texture_depth_2d_array: WebGPUConstants.TextureViewDimension.E2dArray,\n texture_depth_cube: WebGPUConstants.TextureViewDimension.Cube,\n texture_depth_cube_array: WebGPUConstants.TextureViewDimension.CubeArray,\n texture_depth_multisampled_2d: WebGPUConstants.TextureViewDimension.E2d,\n texture_storage_1d: WebGPUConstants.TextureViewDimension.E1d,\n texture_storage_2d: WebGPUConstants.TextureViewDimension.E2d,\n texture_storage_2d_array: WebGPUConstants.TextureViewDimension.E2dArray,\n texture_storage_3d: WebGPUConstants.TextureViewDimension.E3d,\n texture_external: null,\n};\n/** @internal */\nexport class WebGPUShaderProcessorWGSL extends WebGPUShaderProcessor {\n constructor() {\n super(...arguments);\n this.shaderLanguage = ShaderLanguage.WGSL;\n this.uniformRegexp = /uniform\\s+(\\w+)\\s*:\\s*(.+)\\s*;/;\n this.textureRegexp = /var\\s+(\\w+)\\s*:\\s*((array<\\s*)?(texture_\\w+)\\s*(<\\s*(.+)\\s*>)?\\s*(,\\s*\\w+\\s*>\\s*)?);/;\n this.noPrecision = true;\n }\n _getArraySize(name, uniformType, preProcessors) {\n let length = 0;\n const endArray = uniformType.lastIndexOf(\">\");\n if (uniformType.indexOf(\"array\") >= 0 && endArray > 0) {\n let startArray = endArray;\n while (startArray > 0 && uniformType.charAt(startArray) !== \" \" && uniformType.charAt(startArray) !== \",\") {\n startArray--;\n }\n const lengthInString = uniformType.substring(startArray + 1, endArray);\n length = +lengthInString;\n if (isNaN(length)) {\n length = +preProcessors[lengthInString.trim()];\n }\n while (startArray > 0 && (uniformType.charAt(startArray) === \" \" || uniformType.charAt(startArray) === \",\")) {\n startArray--;\n }\n uniformType = uniformType.substring(uniformType.indexOf(\"<\") + 1, startArray + 1);\n }\n return [name, uniformType, length];\n }\n initializeShaders(processingContext) {\n this._webgpuProcessingContext = processingContext;\n this._attributesWGSL = [];\n this._varyingsWGSL = [];\n this._varyingNamesWGSL = [];\n this._stridedUniformArrays = [];\n }\n preProcessShaderCode(code) {\n return (`struct ${WebGPUShaderProcessor.InternalsUBOName} {\\n yFactor_: f32,\\n textureOutputHeight_: f32,\\n};\\nvar ${internalsVarName} : ${WebGPUShaderProcessor.InternalsUBOName};\\n` +\n RemoveComments(code));\n }\n varyingProcessor(varying, isFragment, preProcessors) {\n const varyingRegex = /\\s*varying\\s+(?:(?:highp)?|(?:lowp)?)\\s*(\\S+)\\s*:\\s*(.+)\\s*;/gm;\n const match = varyingRegex.exec(varying);\n if (match !== null) {\n const varyingType = match[2];\n const name = match[1];\n let location;\n if (isFragment) {\n location = this._webgpuProcessingContext.availableVaryings[name];\n if (location === undefined) {\n Logger.Warn(`Invalid fragment shader: The varying named \"${name}\" is not declared in the vertex shader! This declaration will be ignored.`);\n }\n }\n else {\n location = this._webgpuProcessingContext.getVaryingNextLocation(varyingType, this._getArraySize(name, varyingType, preProcessors)[2]);\n this._webgpuProcessingContext.availableVaryings[name] = location;\n this._varyingsWGSL.push(` @location(${location}) ${name} : ${varyingType},`);\n this._varyingNamesWGSL.push(name);\n }\n varying = \"\";\n }\n return varying;\n }\n attributeProcessor(attribute, preProcessors) {\n const attribRegex = /\\s*attribute\\s+(\\S+)\\s*:\\s*(.+)\\s*;/gm;\n const match = attribRegex.exec(attribute);\n if (match !== null) {\n const attributeType = match[2];\n const name = match[1];\n const location = this._webgpuProcessingContext.getAttributeNextLocation(attributeType, this._getArraySize(name, attributeType, preProcessors)[2]);\n this._webgpuProcessingContext.availableAttributes[name] = location;\n this._webgpuProcessingContext.orderedAttributes[location] = name;\n this._attributesWGSL.push(`@location(${location}) ${name} : ${attributeType},`);\n attribute = \"\";\n }\n return attribute;\n }\n uniformProcessor(uniform, isFragment, preProcessors) {\n const match = this.uniformRegexp.exec(uniform);\n if (match !== null) {\n const uniformType = match[2];\n const name = match[1];\n this._addUniformToLeftOverUBO(name, uniformType, preProcessors);\n uniform = \"\";\n }\n return uniform;\n }\n textureProcessor(texture, isFragment, preProcessors) {\n const match = this.textureRegexp.exec(texture);\n if (match !== null) {\n const name = match[1]; // name of the variable\n const type = match[2]; // texture_2d or array, 5> for eg\n const isArrayOfTexture = !!match[3];\n const textureFunc = match[4]; // texture_2d, texture_depth_2d, etc\n const isStorageTexture = textureFunc.indexOf(\"storage\") > 0;\n const componentType = match[6]; // f32 or i32 or u32 or undefined\n const storageTextureFormat = isStorageTexture ? componentType.substring(0, componentType.indexOf(\",\")).trim() : null;\n let arraySize = isArrayOfTexture ? this._getArraySize(name, type, preProcessors)[2] : 0;\n let textureInfo = this._webgpuProcessingContext.availableTextures[name];\n if (!textureInfo) {\n textureInfo = {\n isTextureArray: arraySize > 0,\n isStorageTexture,\n textures: [],\n sampleType: WebGPUConstants.TextureSampleType.Float,\n };\n arraySize = arraySize || 1;\n for (let i = 0; i < arraySize; ++i) {\n textureInfo.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding());\n }\n }\n else {\n arraySize = textureInfo.textures.length;\n }\n this._webgpuProcessingContext.availableTextures[name] = textureInfo;\n const isDepthTexture = textureFunc.indexOf(\"depth\") > 0;\n const textureDimension = gpuTextureViewDimensionByWebGPUTextureFunction[textureFunc];\n const sampleType = isDepthTexture\n ? WebGPUConstants.TextureSampleType.Depth\n : componentType === \"u32\"\n ? WebGPUConstants.TextureSampleType.Uint\n : componentType === \"i32\"\n ? WebGPUConstants.TextureSampleType.Sint\n : WebGPUConstants.TextureSampleType.Float;\n textureInfo.sampleType = sampleType;\n if (textureDimension === undefined) {\n throw `Can't get the texture dimension corresponding to the texture function \"${textureFunc}\"!`;\n }\n for (let i = 0; i < arraySize; ++i) {\n const { groupIndex, bindingIndex } = textureInfo.textures[i];\n if (i === 0) {\n texture = `@group(${groupIndex}) @binding(${bindingIndex}) ${texture}`;\n }\n this._addTextureBindingDescription(name, textureInfo, i, textureDimension, storageTextureFormat, !isFragment);\n }\n }\n return texture;\n }\n postProcessor(code) {\n return code;\n }\n finalizeShaders(vertexCode, fragmentCode) {\n const fragCoordCode = fragmentCode.indexOf(\"fragmentInputs.position\") >= 0\n ? `\r\n if (internals.yFactor_ == 1.) {\r\n fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y;\r\n }\r\n `\n : \"\";\n // Add the group/binding info to the sampler declaration (var xxx: sampler|sampler_comparison)\n vertexCode = this._processSamplers(vertexCode, true);\n fragmentCode = this._processSamplers(fragmentCode, false);\n // Add the group/binding info to the uniform/storage buffer declarations (var XXX:YYY or var XXX:YYY)\n vertexCode = this._processCustomBuffers(vertexCode, true);\n fragmentCode = this._processCustomBuffers(fragmentCode, false);\n // Builds the leftover UBOs.\n const leftOverUBO = this._buildLeftOverUBO();\n vertexCode = leftOverUBO + vertexCode;\n fragmentCode = leftOverUBO + fragmentCode;\n // Vertex code\n vertexCode = vertexCode.replace(/#define /g, \"//#define \");\n vertexCode = this._processStridedUniformArrays(vertexCode);\n let vertexInputs = \"struct VertexInputs {\\n @builtin(vertex_index) vertexIndex : u32,\\n @builtin(instance_index) instanceIndex : u32,\\n\";\n if (this._attributesWGSL.length > 0) {\n vertexInputs += this._attributesWGSL.join(\"\\n\");\n }\n vertexInputs += \"\\n};\\nvar vertexInputs : VertexInputs;\\n\";\n let vertexOutputs = \"struct FragmentInputs {\\n @builtin(position) position : vec4,\\n\";\n if (this._varyingsWGSL.length > 0) {\n vertexOutputs += this._varyingsWGSL.join(\"\\n\");\n }\n vertexOutputs += \"\\n};\\nvar vertexOutputs : FragmentInputs;\\n\";\n vertexCode = vertexInputs + vertexOutputs + vertexCode;\n const vertexMainStartingCode = `\\n vertexInputs = input;\\n`;\n const vertexMainEndingCode = ` vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_;\\n return vertexOutputs;`;\n vertexCode = this._injectStartingAndEndingCode(vertexCode, \"fn main\", vertexMainStartingCode, vertexMainEndingCode);\n // fragment code\n fragmentCode = fragmentCode.replace(/#define /g, \"//#define \");\n fragmentCode = this._processStridedUniformArrays(fragmentCode);\n fragmentCode = fragmentCode.replace(/dpdy/g, \"(-internals.yFactor_)*dpdy\"); // will also handle dpdyCoarse and dpdyFine\n let fragmentInputs = \"struct FragmentInputs {\\n @builtin(position) position : vec4,\\n @builtin(front_facing) frontFacing : bool,\\n\";\n if (this._varyingsWGSL.length > 0) {\n fragmentInputs += this._varyingsWGSL.join(\"\\n\");\n }\n fragmentInputs += \"\\n};\\nvar fragmentInputs : FragmentInputs;\\n\";\n let fragmentOutputs = \"struct FragmentOutputs {\\n @location(0) color : vec4,\\n\";\n let hasFragDepth = false;\n let idx = 0;\n while (!hasFragDepth) {\n idx = fragmentCode.indexOf(builtInName_frag_depth, idx);\n if (idx < 0) {\n break;\n }\n const saveIndex = idx;\n hasFragDepth = true;\n while (idx > 1 && fragmentCode.charAt(idx) !== \"\\n\") {\n if (fragmentCode.charAt(idx) === \"/\" && fragmentCode.charAt(idx - 1) === \"/\") {\n hasFragDepth = false;\n break;\n }\n idx--;\n }\n idx = saveIndex + builtInName_frag_depth.length;\n }\n if (hasFragDepth) {\n fragmentOutputs += \" @builtin(frag_depth) fragDepth: f32,\\n\";\n }\n fragmentOutputs += \"};\\nvar fragmentOutputs : FragmentOutputs;\\n\";\n fragmentCode = fragmentInputs + fragmentOutputs + fragmentCode;\n const fragmentStartingCode = \" fragmentInputs = input;\\n \" + fragCoordCode;\n const fragmentEndingCode = \" return fragmentOutputs;\";\n fragmentCode = this._injectStartingAndEndingCode(fragmentCode, \"fn main\", fragmentStartingCode, fragmentEndingCode);\n this._collectBindingNames();\n this._preCreateBindGroupEntries();\n return { vertexCode, fragmentCode };\n }\n _generateLeftOverUBOCode(name, uniformBufferDescription) {\n let stridedArrays = \"\";\n let ubo = `struct ${name} {\\n`;\n for (const leftOverUniform of this._webgpuProcessingContext.leftOverUniforms) {\n const type = leftOverUniform.type.replace(/^(.*?)(<.*>)?$/, \"$1\");\n const size = WebGPUShaderProcessor.UniformSizes[type];\n if (leftOverUniform.length > 0) {\n if (size <= 2) {\n const stridedArrayType = `${name}_${this._stridedUniformArrays.length}_strided_arr`;\n stridedArrays += `struct ${stridedArrayType} {\r\n @size(16)\r\n el: ${type},\r\n }`;\n this._stridedUniformArrays.push(leftOverUniform.name);\n ubo += ` @align(16) ${leftOverUniform.name} : array<${stridedArrayType}, ${leftOverUniform.length}>,\\n`;\n }\n else {\n ubo += ` ${leftOverUniform.name} : array<${leftOverUniform.type}, ${leftOverUniform.length}>,\\n`;\n }\n }\n else {\n ubo += ` ${leftOverUniform.name} : ${leftOverUniform.type},\\n`;\n }\n }\n ubo += \"};\\n\";\n ubo = `${stridedArrays}\\n${ubo}`;\n ubo += `@group(${uniformBufferDescription.binding.groupIndex}) @binding(${uniformBufferDescription.binding.bindingIndex}) var ${leftOverVarName} : ${name};\\n`;\n return ubo;\n }\n _processSamplers(code, isVertex) {\n const samplerRegexp = /var\\s+(\\w+Sampler)\\s*:\\s*(sampler|sampler_comparison)\\s*;/gm;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const match = samplerRegexp.exec(code);\n if (match === null) {\n break;\n }\n const name = match[1]; // name of the variable\n const samplerType = match[2]; // sampler or sampler_comparison\n const textureName = name.indexOf(WebGPUShaderProcessor.AutoSamplerSuffix) === name.length - WebGPUShaderProcessor.AutoSamplerSuffix.length\n ? name.substring(0, name.indexOf(WebGPUShaderProcessor.AutoSamplerSuffix))\n : null;\n const samplerBindingType = samplerType === \"sampler_comparison\" ? WebGPUConstants.SamplerBindingType.Comparison : WebGPUConstants.SamplerBindingType.Filtering;\n if (textureName) {\n const textureInfo = this._webgpuProcessingContext.availableTextures[textureName];\n if (textureInfo) {\n textureInfo.autoBindSampler = true;\n }\n }\n let samplerInfo = this._webgpuProcessingContext.availableSamplers[name];\n if (!samplerInfo) {\n samplerInfo = {\n binding: this._webgpuProcessingContext.getNextFreeUBOBinding(),\n type: samplerBindingType,\n };\n this._webgpuProcessingContext.availableSamplers[name] = samplerInfo;\n }\n this._addSamplerBindingDescription(name, samplerInfo, isVertex);\n const part1 = code.substring(0, match.index);\n const insertPart = `@group(${samplerInfo.binding.groupIndex}) @binding(${samplerInfo.binding.bindingIndex}) `;\n const part2 = code.substring(match.index);\n code = part1 + insertPart + part2;\n samplerRegexp.lastIndex += insertPart.length;\n }\n return code;\n }\n _processCustomBuffers(code, isVertex) {\n const instantiateBufferRegexp = /var<\\s*(uniform|storage)\\s*(,\\s*(read|read_write)\\s*)?>\\s+(\\S+)\\s*:\\s*(\\S+)\\s*;/gm;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const match = instantiateBufferRegexp.exec(code);\n if (match === null) {\n break;\n }\n const type = match[1];\n const decoration = match[3];\n let name = match[4];\n const structName = match[5];\n let bufferInfo = this._webgpuProcessingContext.availableBuffers[name];\n if (!bufferInfo) {\n const knownUBO = type === \"uniform\" ? WebGPUShaderProcessingContext.KnownUBOs[structName] : null;\n let binding;\n if (knownUBO) {\n name = structName;\n binding = knownUBO.binding;\n if (binding.groupIndex === -1) {\n binding = this._webgpuProcessingContext.getNextFreeUBOBinding();\n }\n }\n else {\n binding = this._webgpuProcessingContext.getNextFreeUBOBinding();\n }\n bufferInfo = { binding };\n this._webgpuProcessingContext.availableBuffers[name] = bufferInfo;\n }\n this._addBufferBindingDescription(name, this._webgpuProcessingContext.availableBuffers[name], decoration === \"read_write\"\n ? WebGPUConstants.BufferBindingType.Storage\n : type === \"storage\"\n ? WebGPUConstants.BufferBindingType.ReadOnlyStorage\n : WebGPUConstants.BufferBindingType.Uniform, isVertex);\n const groupIndex = bufferInfo.binding.groupIndex;\n const bindingIndex = bufferInfo.binding.bindingIndex;\n const part1 = code.substring(0, match.index);\n const insertPart = `@group(${groupIndex}) @binding(${bindingIndex}) `;\n const part2 = code.substring(match.index);\n code = part1 + insertPart + part2;\n instantiateBufferRegexp.lastIndex += insertPart.length;\n }\n return code;\n }\n _processStridedUniformArrays(code) {\n for (const uniformArrayName of this._stridedUniformArrays) {\n code = code.replace(new RegExp(`${uniformArrayName}\\\\s*\\\\[(.*)\\\\]`, \"g\"), `${uniformArrayName}[$1].el`);\n }\n return code;\n }\n}\n//# sourceMappingURL=webgpuShaderProcessorsWGSL.js.map","import { Scalar } from \"../../Maths/math.scalar.js\";\nimport * as WebGPUConstants from \"./webgpuConstants.js\";\n/** @internal */\nexport class WebGPUHardwareTexture {\n get underlyingResource() {\n return this._webgpuTexture;\n }\n getMSAATexture(index = 0) {\n var _a, _b;\n return (_b = (_a = this._webgpuMSAATexture) === null || _a === void 0 ? void 0 : _a[index]) !== null && _b !== void 0 ? _b : null;\n }\n setMSAATexture(texture, index = -1) {\n if (!this._webgpuMSAATexture) {\n this._webgpuMSAATexture = [];\n }\n if (index === -1) {\n index = this._webgpuMSAATexture.length;\n }\n this._webgpuMSAATexture[index] = texture;\n }\n releaseMSAATexture() {\n if (this._webgpuMSAATexture) {\n for (const texture of this._webgpuMSAATexture) {\n texture === null || texture === void 0 ? void 0 : texture.destroy();\n }\n this._webgpuMSAATexture = null;\n }\n }\n constructor(existingTexture = null) {\n this.format = WebGPUConstants.TextureFormat.RGBA8Unorm;\n this.textureUsages = 0;\n this.textureAdditionalUsages = 0;\n this._webgpuTexture = existingTexture;\n this._webgpuMSAATexture = null;\n this.view = null;\n this.viewForWriting = null;\n }\n set(hardwareTexture) {\n this._webgpuTexture = hardwareTexture;\n }\n setUsage(_textureSource, generateMipMaps, isCube, width, height) {\n this.createView({\n format: this.format,\n dimension: isCube ? WebGPUConstants.TextureViewDimension.Cube : WebGPUConstants.TextureViewDimension.E2d,\n mipLevelCount: generateMipMaps ? Scalar.ILog2(Math.max(width, height)) + 1 : 1,\n baseArrayLayer: 0,\n baseMipLevel: 0,\n arrayLayerCount: isCube ? 6 : 1,\n aspect: WebGPUConstants.TextureAspect.All,\n });\n }\n createView(descriptor, createViewForWriting = false) {\n this.view = this._webgpuTexture.createView(descriptor);\n if (createViewForWriting && descriptor) {\n const saveNumMipMaps = descriptor.mipLevelCount;\n descriptor.mipLevelCount = 1;\n this.viewForWriting = this._webgpuTexture.createView(descriptor);\n descriptor.mipLevelCount = saveNumMipMaps;\n }\n }\n reset() {\n this._webgpuTexture = null;\n this._webgpuMSAATexture = null;\n this.view = null;\n this.viewForWriting = null;\n }\n release() {\n var _a, _b;\n (_a = this._webgpuTexture) === null || _a === void 0 ? void 0 : _a.destroy();\n this.releaseMSAATexture();\n (_b = this._copyInvertYTempTexture) === null || _b === void 0 ? void 0 : _b.destroy();\n this.reset();\n }\n}\n//# sourceMappingURL=webgpuHardwareTexture.js.map","/* eslint-disable @typescript-eslint/naming-convention */\n// License for the mipmap generation code:\n//\n// Copyright 2020 Brandon Jones\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\nimport * as WebGPUConstants from \"./webgpuConstants.js\";\nimport { Scalar } from \"../../Maths/math.scalar.js\";\n\nimport { InternalTextureSource } from \"../../Materials/Textures/internalTexture.js\";\nimport { WebGPUHardwareTexture } from \"./webgpuHardwareTexture.js\";\n// TODO WEBGPU improve mipmap generation by using compute shaders\n// TODO WEBGPU use WGSL instead of GLSL\nconst mipmapVertexSource = `\r\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\r\n const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));\r\n\r\n layout(location = 0) out vec2 vTex;\r\n\r\n void main() {\r\n vTex = tex[gl_VertexIndex];\r\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\r\n }\r\n `;\nconst mipmapFragmentSource = `\r\n layout(set = 0, binding = 0) uniform sampler imgSampler;\r\n layout(set = 0, binding = 1) uniform texture2D img;\r\n\r\n layout(location = 0) in vec2 vTex;\r\n layout(location = 0) out vec4 outColor;\r\n\r\n void main() {\r\n outColor = texture(sampler2D(img, imgSampler), vTex);\r\n }\r\n `;\nconst invertYPreMultiplyAlphaVertexSource = `\r\n #extension GL_EXT_samplerless_texture_functions : enable\r\n\r\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\r\n const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f));\r\n\r\n layout(set = 0, binding = 0) uniform texture2D img;\r\n\r\n #ifdef INVERTY\r\n layout(location = 0) out flat ivec2 vTextureSize;\r\n #endif\r\n\r\n void main() {\r\n #ifdef INVERTY\r\n vTextureSize = textureSize(img, 0);\r\n #endif\r\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\r\n }\r\n `;\nconst invertYPreMultiplyAlphaFragmentSource = `\r\n #extension GL_EXT_samplerless_texture_functions : enable\r\n\r\n layout(set = 0, binding = 0) uniform texture2D img;\r\n\r\n #ifdef INVERTY\r\n layout(location = 0) in flat ivec2 vTextureSize;\r\n #endif\r\n layout(location = 0) out vec4 outColor;\r\n\r\n void main() {\r\n #ifdef INVERTY\r\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0);\r\n #else\r\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\r\n #endif\r\n #ifdef PREMULTIPLYALPHA\r\n color.rgb *= color.a;\r\n #endif\r\n outColor = color;\r\n }\r\n `;\nconst invertYPreMultiplyAlphaWithOfstVertexSource = invertYPreMultiplyAlphaVertexSource;\nconst invertYPreMultiplyAlphaWithOfstFragmentSource = `\r\n #extension GL_EXT_samplerless_texture_functions : enable\r\n\r\n layout(set = 0, binding = 0) uniform texture2D img;\r\n layout(set = 0, binding = 1) uniform Params {\r\n float ofstX;\r\n float ofstY;\r\n float width;\r\n float height;\r\n };\r\n\r\n #ifdef INVERTY\r\n layout(location = 0) in flat ivec2 vTextureSize;\r\n #endif\r\n layout(location = 0) out vec4 outColor;\r\n\r\n void main() {\r\n if (gl_FragCoord.x < ofstX || gl_FragCoord.x >= ofstX + width) {\r\n discard;\r\n }\r\n if (gl_FragCoord.y < ofstY || gl_FragCoord.y >= ofstY + height) {\r\n discard;\r\n }\r\n #ifdef INVERTY\r\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, ofstY + height - (gl_FragCoord.y - ofstY)), 0);\r\n #else\r\n vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0);\r\n #endif\r\n #ifdef PREMULTIPLYALPHA\r\n color.rgb *= color.a;\r\n #endif\r\n outColor = color;\r\n }\r\n `;\nconst clearVertexSource = `\r\n const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f));\r\n\r\n void main() {\r\n gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0);\r\n }\r\n `;\nconst clearFragmentSource = `\r\n layout(set = 0, binding = 0) uniform Uniforms {\r\n uniform vec4 color;\r\n };\r\n\r\n layout(location = 0) out vec4 outColor;\r\n\r\n void main() {\r\n outColor = color;\r\n }\r\n `;\nconst copyVideoToTextureVertexSource = `\r\n struct VertexOutput {\r\n @builtin(position) Position : vec4,\r\n @location(0) fragUV : vec2\r\n }\r\n \r\n @vertex\r\n fn main(\r\n @builtin(vertex_index) VertexIndex : u32\r\n ) -> VertexOutput {\r\n var pos = array, 4>(\r\n vec2(-1.0, 1.0),\r\n vec2( 1.0, 1.0),\r\n vec2(-1.0, -1.0),\r\n vec2( 1.0, -1.0)\r\n );\r\n var tex = array, 4>(\r\n vec2(0.0, 0.0),\r\n vec2(1.0, 0.0),\r\n vec2(0.0, 1.0),\r\n vec2(1.0, 1.0)\r\n );\r\n\r\n var output: VertexOutput;\r\n\r\n output.Position = vec4(pos[VertexIndex], 0.0, 1.0);\r\n output.fragUV = tex[VertexIndex];\r\n\r\n return output;\r\n }\r\n `;\nconst copyVideoToTextureFragmentSource = `\r\n @group(0) @binding(0) var videoSampler: sampler;\r\n @group(0) @binding(1) var videoTexture: texture_external;\r\n\r\n @fragment\r\n fn main(\r\n @location(0) fragUV: vec2\r\n ) -> @location(0) vec4 {\r\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV);\r\n }\r\n `;\nconst copyVideoToTextureInvertYFragmentSource = `\r\n @group(0) @binding(0) var videoSampler: sampler;\r\n @group(0) @binding(1) var videoTexture: texture_external;\r\n\r\n @fragment\r\n fn main(\r\n @location(0) fragUV: vec2\r\n ) -> @location(0) vec4 {\r\n return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2(fragUV.x, 1.0 - fragUV.y));\r\n }\r\n `;\nvar PipelineType;\n(function (PipelineType) {\n PipelineType[PipelineType[\"MipMap\"] = 0] = \"MipMap\";\n PipelineType[PipelineType[\"InvertYPremultiplyAlpha\"] = 1] = \"InvertYPremultiplyAlpha\";\n PipelineType[PipelineType[\"Clear\"] = 2] = \"Clear\";\n PipelineType[PipelineType[\"InvertYPremultiplyAlphaWithOfst\"] = 3] = \"InvertYPremultiplyAlphaWithOfst\";\n})(PipelineType || (PipelineType = {}));\nvar VideoPipelineType;\n(function (VideoPipelineType) {\n VideoPipelineType[VideoPipelineType[\"DontInvertY\"] = 0] = \"DontInvertY\";\n VideoPipelineType[VideoPipelineType[\"InvertY\"] = 1] = \"InvertY\";\n})(VideoPipelineType || (VideoPipelineType = {}));\nconst shadersForPipelineType = [\n { vertex: mipmapVertexSource, fragment: mipmapFragmentSource },\n { vertex: invertYPreMultiplyAlphaVertexSource, fragment: invertYPreMultiplyAlphaFragmentSource },\n { vertex: clearVertexSource, fragment: clearFragmentSource },\n { vertex: invertYPreMultiplyAlphaWithOfstVertexSource, fragment: invertYPreMultiplyAlphaWithOfstFragmentSource },\n];\n/**\n * Map a (renderable) texture format (GPUTextureFormat) to an index for fast lookup (in caches for eg)\n */\nexport const renderableTextureFormatToIndex = {\n \"\": 0,\n r8unorm: 1,\n r8uint: 2,\n r8sint: 3,\n r16uint: 4,\n r16sint: 5,\n r16float: 6,\n rg8unorm: 7,\n rg8uint: 8,\n rg8sint: 9,\n r32uint: 10,\n r32sint: 11,\n r32float: 12,\n rg16uint: 13,\n rg16sint: 14,\n rg16float: 15,\n rgba8unorm: 16,\n \"rgba8unorm-srgb\": 17,\n rgba8uint: 18,\n rgba8sint: 19,\n bgra8unorm: 20,\n \"bgra8unorm-srgb\": 21,\n rgb10a2unorm: 22,\n rg32uint: 23,\n rg32sint: 24,\n rg32float: 25,\n rgba16uint: 26,\n rgba16sint: 27,\n rgba16float: 28,\n rgba32uint: 29,\n rgba32sint: 30,\n rgba32float: 31,\n stencil8: 32,\n depth16unorm: 33,\n depth24plus: 34,\n \"depth24plus-stencil8\": 35,\n depth32float: 36,\n \"depth32float-stencil8\": 37,\n};\n/** @internal */\nexport class WebGPUTextureHelper {\n static ComputeNumMipmapLevels(width, height) {\n return Scalar.ILog2(Math.max(width, height)) + 1;\n }\n //------------------------------------------------------------------------------\n // Initialization / Helpers\n //------------------------------------------------------------------------------\n constructor(device, glslang, tintWASM, bufferManager, enabledExtensions) {\n this._pipelines = {};\n this._compiledShaders = [];\n this._videoPipelines = {};\n this._videoCompiledShaders = [];\n this._deferredReleaseTextures = [];\n this._device = device;\n this._glslang = glslang;\n this._tintWASM = tintWASM;\n this._bufferManager = bufferManager;\n if (enabledExtensions.indexOf(WebGPUConstants.FeatureName.RG11B10UFloatRenderable) !== -1) {\n const keys = Object.keys(renderableTextureFormatToIndex);\n renderableTextureFormatToIndex[WebGPUConstants.TextureFormat.RG11B10UFloat] = renderableTextureFormatToIndex[keys[keys.length - 1]] + 1;\n }\n this._mipmapSampler = device.createSampler({ minFilter: WebGPUConstants.FilterMode.Linear });\n this._videoSampler = device.createSampler({ minFilter: WebGPUConstants.FilterMode.Linear });\n this._ubCopyWithOfst = this._bufferManager.createBuffer(4 * 4, WebGPUConstants.BufferUsage.Uniform | WebGPUConstants.BufferUsage.CopyDst).underlyingResource;\n this._getPipeline(WebGPUConstants.TextureFormat.RGBA8Unorm);\n this._getVideoPipeline(WebGPUConstants.TextureFormat.RGBA8Unorm);\n }\n _getPipeline(format, type = PipelineType.MipMap, params) {\n const index = type === PipelineType.MipMap\n ? 1 << 0\n : type === PipelineType.InvertYPremultiplyAlpha\n ? ((params.invertY ? 1 : 0) << 1) + ((params.premultiplyAlpha ? 1 : 0) << 2)\n : type === PipelineType.Clear\n ? 1 << 3\n : type === PipelineType.InvertYPremultiplyAlphaWithOfst\n ? ((params.invertY ? 1 : 0) << 4) + ((params.premultiplyAlpha ? 1 : 0) << 5)\n : 0;\n if (!this._pipelines[format]) {\n this._pipelines[format] = [];\n }\n let pipelineAndBGL = this._pipelines[format][index];\n if (!pipelineAndBGL) {\n let defines = \"#version 450\\r\\n\";\n if (type === PipelineType.InvertYPremultiplyAlpha || type === PipelineType.InvertYPremultiplyAlphaWithOfst) {\n if (params.invertY) {\n defines += \"#define INVERTY\\r\\n\";\n }\n if (params.premultiplyAlpha) {\n defines += \"#define PREMULTIPLYALPHA\\r\\n\";\n }\n }\n let modules = this._compiledShaders[index];\n if (!modules) {\n let vertexCode = this._glslang.compileGLSL(defines + shadersForPipelineType[type].vertex, \"vertex\");\n let fragmentCode = this._glslang.compileGLSL(defines + shadersForPipelineType[type].fragment, \"fragment\");\n if (this._tintWASM) {\n vertexCode = this._tintWASM.convertSpirV2WGSL(vertexCode);\n fragmentCode = this._tintWASM.convertSpirV2WGSL(fragmentCode);\n }\n const vertexModule = this._device.createShaderModule({\n code: vertexCode,\n });\n const fragmentModule = this._device.createShaderModule({\n code: fragmentCode,\n });\n modules = this._compiledShaders[index] = [vertexModule, fragmentModule];\n }\n const pipeline = this._device.createRenderPipeline({\n layout: WebGPUConstants.AutoLayoutMode.Auto,\n vertex: {\n module: modules[0],\n entryPoint: \"main\",\n },\n fragment: {\n module: modules[1],\n entryPoint: \"main\",\n targets: [\n {\n format,\n },\n ],\n },\n primitive: {\n topology: WebGPUConstants.PrimitiveTopology.TriangleStrip,\n stripIndexFormat: WebGPUConstants.IndexFormat.Uint16,\n },\n });\n pipelineAndBGL = this._pipelines[format][index] = [pipeline, pipeline.getBindGroupLayout(0)];\n }\n return pipelineAndBGL;\n }\n _getVideoPipeline(format, type = VideoPipelineType.DontInvertY) {\n const index = type === VideoPipelineType.InvertY ? 1 << 0 : 0;\n if (!this._videoPipelines[format]) {\n this._videoPipelines[format] = [];\n }\n let pipelineAndBGL = this._videoPipelines[format][index];\n if (!pipelineAndBGL) {\n let modules = this._videoCompiledShaders[index];\n if (!modules) {\n const vertexModule = this._device.createShaderModule({\n code: copyVideoToTextureVertexSource,\n });\n const fragmentModule = this._device.createShaderModule({\n code: index === 0 ? copyVideoToTextureFragmentSource : copyVideoToTextureInvertYFragmentSource,\n });\n modules = this._videoCompiledShaders[index] = [vertexModule, fragmentModule];\n }\n const pipeline = this._device.createRenderPipeline({\n label: `CopyVideoToTexture_${format}_${index === 0 ? \"DontInvertY\" : \"InvertY\"}`,\n layout: WebGPUConstants.AutoLayoutMode.Auto,\n vertex: {\n module: modules[0],\n entryPoint: \"main\",\n },\n fragment: {\n module: modules[1],\n entryPoint: \"main\",\n targets: [\n {\n format,\n },\n ],\n },\n primitive: {\n topology: WebGPUConstants.PrimitiveTopology.TriangleStrip,\n stripIndexFormat: WebGPUConstants.IndexFormat.Uint16,\n },\n });\n pipelineAndBGL = this._videoPipelines[format][index] = [pipeline, pipeline.getBindGroupLayout(0)];\n }\n return pipelineAndBGL;\n }\n static _GetTextureTypeFromFormat(format) {\n switch (format) {\n // One Component = 8 bits\n case WebGPUConstants.TextureFormat.R8Unorm:\n case WebGPUConstants.TextureFormat.R8Snorm:\n case WebGPUConstants.TextureFormat.R8Uint:\n case WebGPUConstants.TextureFormat.R8Sint:\n case WebGPUConstants.TextureFormat.RG8Unorm:\n case WebGPUConstants.TextureFormat.RG8Snorm:\n case WebGPUConstants.TextureFormat.RG8Uint:\n case WebGPUConstants.TextureFormat.RG8Sint:\n case WebGPUConstants.TextureFormat.RGBA8Unorm:\n case WebGPUConstants.TextureFormat.RGBA8UnormSRGB:\n case WebGPUConstants.TextureFormat.RGBA8Snorm:\n case WebGPUConstants.TextureFormat.RGBA8Uint:\n case WebGPUConstants.TextureFormat.RGBA8Sint:\n case WebGPUConstants.TextureFormat.BGRA8Unorm:\n case WebGPUConstants.TextureFormat.BGRA8UnormSRGB:\n case WebGPUConstants.TextureFormat.RGB10A2Unorm: // composite format - let's say it's byte...\n case WebGPUConstants.TextureFormat.RGB9E5UFloat: // composite format - let's say it's byte...\n case WebGPUConstants.TextureFormat.RG11B10UFloat: // composite format - let's say it's byte...\n case WebGPUConstants.TextureFormat.Depth24UnormStencil8: // composite format - let's say it's byte...\n case WebGPUConstants.TextureFormat.Depth32FloatStencil8: // composite format - let's say it's byte...\n case WebGPUConstants.TextureFormat.BC7RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC7RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.BC6HRGBUFloat:\n case WebGPUConstants.TextureFormat.BC6HRGBFloat:\n case WebGPUConstants.TextureFormat.BC5RGUnorm:\n case WebGPUConstants.TextureFormat.BC5RGSnorm:\n case WebGPUConstants.TextureFormat.BC3RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC3RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.BC2RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC2RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.BC4RUnorm:\n case WebGPUConstants.TextureFormat.BC4RSnorm:\n case WebGPUConstants.TextureFormat.BC1RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC1RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.ETC2RGB8Unorm:\n case WebGPUConstants.TextureFormat.ETC2RGB8UnormSRGB:\n case WebGPUConstants.TextureFormat.ETC2RGB8A1Unorm:\n case WebGPUConstants.TextureFormat.ETC2RGB8A1UnormSRGB:\n case WebGPUConstants.TextureFormat.ETC2RGBA8Unorm:\n case WebGPUConstants.TextureFormat.ETC2RGBA8UnormSRGB:\n case WebGPUConstants.TextureFormat.EACR11Unorm:\n case WebGPUConstants.TextureFormat.EACR11Snorm:\n case WebGPUConstants.TextureFormat.EACRG11Unorm:\n case WebGPUConstants.TextureFormat.EACRG11Snorm:\n case WebGPUConstants.TextureFormat.ASTC4x4Unorm:\n case WebGPUConstants.TextureFormat.ASTC4x4UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC5x4Unorm:\n case WebGPUConstants.TextureFormat.ASTC5x4UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC5x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC5x5UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC6x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC6x5UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC6x6Unorm:\n case WebGPUConstants.TextureFormat.ASTC6x6UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC8x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC8x5UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC8x6Unorm:\n case WebGPUConstants.TextureFormat.ASTC8x6UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC8x8Unorm:\n case WebGPUConstants.TextureFormat.ASTC8x8UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC10x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x5UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC10x6Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x6UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC10x8Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x8UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC10x10Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x10UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC12x10Unorm:\n case WebGPUConstants.TextureFormat.ASTC12x10UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC12x12Unorm:\n case WebGPUConstants.TextureFormat.ASTC12x12UnormSRGB:\n return 0;\n // One component = 16 bits\n case WebGPUConstants.TextureFormat.R16Uint:\n case WebGPUConstants.TextureFormat.R16Sint:\n case WebGPUConstants.TextureFormat.RG16Uint:\n case WebGPUConstants.TextureFormat.RG16Sint:\n case WebGPUConstants.TextureFormat.RGBA16Uint:\n case WebGPUConstants.TextureFormat.RGBA16Sint:\n case WebGPUConstants.TextureFormat.Depth16Unorm:\n return 5;\n case WebGPUConstants.TextureFormat.R16Float:\n case WebGPUConstants.TextureFormat.RG16Float:\n case WebGPUConstants.TextureFormat.RGBA16Float:\n return 2;\n // One component = 32 bits\n case WebGPUConstants.TextureFormat.R32Uint:\n case WebGPUConstants.TextureFormat.R32Sint:\n case WebGPUConstants.TextureFormat.RG32Uint:\n case WebGPUConstants.TextureFormat.RG32Sint:\n case WebGPUConstants.TextureFormat.RGBA32Uint:\n case WebGPUConstants.TextureFormat.RGBA32Sint:\n return 7;\n case WebGPUConstants.TextureFormat.R32Float:\n case WebGPUConstants.TextureFormat.RG32Float:\n case WebGPUConstants.TextureFormat.RGBA32Float:\n case WebGPUConstants.TextureFormat.Depth32Float:\n return 1;\n case WebGPUConstants.TextureFormat.Stencil8:\n throw \"No fixed size for Stencil8 format!\";\n case WebGPUConstants.TextureFormat.Depth24Plus:\n throw \"No fixed size for Depth24Plus format!\";\n case WebGPUConstants.TextureFormat.Depth24PlusStencil8:\n throw \"No fixed size for Depth24PlusStencil8 format!\";\n }\n return 0;\n }\n static _GetBlockInformationFromFormat(format) {\n switch (format) {\n // 8 bits formats\n case WebGPUConstants.TextureFormat.R8Unorm:\n case WebGPUConstants.TextureFormat.R8Snorm:\n case WebGPUConstants.TextureFormat.R8Uint:\n case WebGPUConstants.TextureFormat.R8Sint:\n return { width: 1, height: 1, length: 1 };\n // 16 bits formats\n case WebGPUConstants.TextureFormat.R16Uint:\n case WebGPUConstants.TextureFormat.R16Sint:\n case WebGPUConstants.TextureFormat.R16Float:\n case WebGPUConstants.TextureFormat.RG8Unorm:\n case WebGPUConstants.TextureFormat.RG8Snorm:\n case WebGPUConstants.TextureFormat.RG8Uint:\n case WebGPUConstants.TextureFormat.RG8Sint:\n return { width: 1, height: 1, length: 2 };\n // 32 bits formats\n case WebGPUConstants.TextureFormat.R32Uint:\n case WebGPUConstants.TextureFormat.R32Sint:\n case WebGPUConstants.TextureFormat.R32Float:\n case WebGPUConstants.TextureFormat.RG16Uint:\n case WebGPUConstants.TextureFormat.RG16Sint:\n case WebGPUConstants.TextureFormat.RG16Float:\n case WebGPUConstants.TextureFormat.RGBA8Unorm:\n case WebGPUConstants.TextureFormat.RGBA8UnormSRGB:\n case WebGPUConstants.TextureFormat.RGBA8Snorm:\n case WebGPUConstants.TextureFormat.RGBA8Uint:\n case WebGPUConstants.TextureFormat.RGBA8Sint:\n case WebGPUConstants.TextureFormat.BGRA8Unorm:\n case WebGPUConstants.TextureFormat.BGRA8UnormSRGB:\n case WebGPUConstants.TextureFormat.RGB9E5UFloat:\n case WebGPUConstants.TextureFormat.RGB10A2Unorm:\n case WebGPUConstants.TextureFormat.RG11B10UFloat:\n return { width: 1, height: 1, length: 4 };\n // 64 bits formats\n case WebGPUConstants.TextureFormat.RG32Uint:\n case WebGPUConstants.TextureFormat.RG32Sint:\n case WebGPUConstants.TextureFormat.RG32Float:\n case WebGPUConstants.TextureFormat.RGBA16Uint:\n case WebGPUConstants.TextureFormat.RGBA16Sint:\n case WebGPUConstants.TextureFormat.RGBA16Float:\n return { width: 1, height: 1, length: 8 };\n // 128 bits formats\n case WebGPUConstants.TextureFormat.RGBA32Uint:\n case WebGPUConstants.TextureFormat.RGBA32Sint:\n case WebGPUConstants.TextureFormat.RGBA32Float:\n return { width: 1, height: 1, length: 16 };\n // Depth and stencil formats\n case WebGPUConstants.TextureFormat.Stencil8:\n throw \"No fixed size for Stencil8 format!\";\n case WebGPUConstants.TextureFormat.Depth16Unorm:\n return { width: 1, height: 1, length: 2 };\n case WebGPUConstants.TextureFormat.Depth24Plus:\n throw \"No fixed size for Depth24Plus format!\";\n case WebGPUConstants.TextureFormat.Depth24PlusStencil8:\n throw \"No fixed size for Depth24PlusStencil8 format!\";\n case WebGPUConstants.TextureFormat.Depth32Float:\n return { width: 1, height: 1, length: 4 };\n case WebGPUConstants.TextureFormat.Depth24UnormStencil8:\n return { width: 1, height: 1, length: 4 };\n case WebGPUConstants.TextureFormat.Depth32FloatStencil8:\n return { width: 1, height: 1, length: 5 };\n // BC compressed formats usable if \"texture-compression-bc\" is both\n // supported by the device/user agent and enabled in requestDevice.\n case WebGPUConstants.TextureFormat.BC7RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC7RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.BC6HRGBUFloat:\n case WebGPUConstants.TextureFormat.BC6HRGBFloat:\n case WebGPUConstants.TextureFormat.BC5RGUnorm:\n case WebGPUConstants.TextureFormat.BC5RGSnorm:\n case WebGPUConstants.TextureFormat.BC3RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC3RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.BC2RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC2RGBAUnormSRGB:\n return { width: 4, height: 4, length: 16 };\n case WebGPUConstants.TextureFormat.BC4RUnorm:\n case WebGPUConstants.TextureFormat.BC4RSnorm:\n case WebGPUConstants.TextureFormat.BC1RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC1RGBAUnormSRGB:\n return { width: 4, height: 4, length: 8 };\n // ETC2 compressed formats usable if \"texture-compression-etc2\" is both\n // supported by the device/user agent and enabled in requestDevice.\n case WebGPUConstants.TextureFormat.ETC2RGB8Unorm:\n case WebGPUConstants.TextureFormat.ETC2RGB8UnormSRGB:\n case WebGPUConstants.TextureFormat.ETC2RGB8A1Unorm:\n case WebGPUConstants.TextureFormat.ETC2RGB8A1UnormSRGB:\n case WebGPUConstants.TextureFormat.EACR11Unorm:\n case WebGPUConstants.TextureFormat.EACR11Snorm:\n return { width: 4, height: 4, length: 8 };\n case WebGPUConstants.TextureFormat.ETC2RGBA8Unorm:\n case WebGPUConstants.TextureFormat.ETC2RGBA8UnormSRGB:\n case WebGPUConstants.TextureFormat.EACRG11Unorm:\n case WebGPUConstants.TextureFormat.EACRG11Snorm:\n return { width: 4, height: 4, length: 16 };\n // ASTC compressed formats usable if \"texture-compression-astc\" is both\n // supported by the device/user agent and enabled in requestDevice.\n case WebGPUConstants.TextureFormat.ASTC4x4Unorm:\n case WebGPUConstants.TextureFormat.ASTC4x4UnormSRGB:\n return { width: 4, height: 4, length: 16 };\n case WebGPUConstants.TextureFormat.ASTC5x4Unorm:\n case WebGPUConstants.TextureFormat.ASTC5x4UnormSRGB:\n return { width: 5, height: 4, length: 16 };\n case WebGPUConstants.TextureFormat.ASTC5x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC5x5UnormSRGB:\n return { width: 5, height: 5, length: 16 };\n case WebGPUConstants.TextureFormat.ASTC6x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC6x5UnormSRGB:\n return { width: 6, height: 5, length: 16 };\n case WebGPUConstants.TextureFormat.ASTC6x6Unorm:\n case WebGPUConstants.TextureFormat.ASTC6x6UnormSRGB:\n return { width: 6, height: 6, length: 16 };\n case WebGPUConstants.TextureFormat.ASTC8x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC8x5UnormSRGB:\n return { width: 8, height: 5, length: 16 };\n case WebGPUConstants.TextureFormat.ASTC8x6Unorm:\n case WebGPUConstants.TextureFormat.ASTC8x6UnormSRGB:\n return { width: 8, height: 6, length: 16 };\n case WebGPUConstants.TextureFormat.ASTC8x8Unorm:\n case WebGPUConstants.TextureFormat.ASTC8x8UnormSRGB:\n return { width: 8, height: 8, length: 16 };\n case WebGPUConstants.TextureFormat.ASTC10x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x5UnormSRGB:\n return { width: 10, height: 5, length: 16 };\n case WebGPUConstants.TextureFormat.ASTC10x6Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x6UnormSRGB:\n return { width: 10, height: 6, length: 16 };\n case WebGPUConstants.TextureFormat.ASTC10x8Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x8UnormSRGB:\n return { width: 10, height: 8, length: 16 };\n case WebGPUConstants.TextureFormat.ASTC10x10Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x10UnormSRGB:\n return { width: 10, height: 10, length: 16 };\n case WebGPUConstants.TextureFormat.ASTC12x10Unorm:\n case WebGPUConstants.TextureFormat.ASTC12x10UnormSRGB:\n return { width: 12, height: 10, length: 16 };\n case WebGPUConstants.TextureFormat.ASTC12x12Unorm:\n case WebGPUConstants.TextureFormat.ASTC12x12UnormSRGB:\n return { width: 12, height: 12, length: 16 };\n }\n return { width: 1, height: 1, length: 4 };\n }\n static _IsHardwareTexture(texture) {\n return !!texture.release;\n }\n static _IsInternalTexture(texture) {\n return !!texture.dispose;\n }\n static IsImageBitmap(imageBitmap) {\n return imageBitmap.close !== undefined;\n }\n static IsImageBitmapArray(imageBitmap) {\n return Array.isArray(imageBitmap) && imageBitmap[0].close !== undefined;\n }\n setCommandEncoder(encoder) {\n this._commandEncoderForCreation = encoder;\n }\n static IsCompressedFormat(format) {\n switch (format) {\n case WebGPUConstants.TextureFormat.BC7RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.BC7RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC6HRGBFloat:\n case WebGPUConstants.TextureFormat.BC6HRGBUFloat:\n case WebGPUConstants.TextureFormat.BC5RGSnorm:\n case WebGPUConstants.TextureFormat.BC5RGUnorm:\n case WebGPUConstants.TextureFormat.BC4RSnorm:\n case WebGPUConstants.TextureFormat.BC4RUnorm:\n case WebGPUConstants.TextureFormat.BC3RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.BC3RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC2RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.BC2RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC1RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.BC1RGBAUnorm:\n case WebGPUConstants.TextureFormat.ETC2RGB8Unorm:\n case WebGPUConstants.TextureFormat.ETC2RGB8UnormSRGB:\n case WebGPUConstants.TextureFormat.ETC2RGB8A1Unorm:\n case WebGPUConstants.TextureFormat.ETC2RGB8A1UnormSRGB:\n case WebGPUConstants.TextureFormat.ETC2RGBA8Unorm:\n case WebGPUConstants.TextureFormat.ETC2RGBA8UnormSRGB:\n case WebGPUConstants.TextureFormat.EACR11Unorm:\n case WebGPUConstants.TextureFormat.EACR11Snorm:\n case WebGPUConstants.TextureFormat.EACRG11Unorm:\n case WebGPUConstants.TextureFormat.EACRG11Snorm:\n case WebGPUConstants.TextureFormat.ASTC4x4Unorm:\n case WebGPUConstants.TextureFormat.ASTC4x4UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC5x4Unorm:\n case WebGPUConstants.TextureFormat.ASTC5x4UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC5x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC5x5UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC6x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC6x5UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC6x6Unorm:\n case WebGPUConstants.TextureFormat.ASTC6x6UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC8x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC8x5UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC8x6Unorm:\n case WebGPUConstants.TextureFormat.ASTC8x6UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC8x8Unorm:\n case WebGPUConstants.TextureFormat.ASTC8x8UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC10x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x5UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC10x6Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x6UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC10x8Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x8UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC10x10Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x10UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC12x10Unorm:\n case WebGPUConstants.TextureFormat.ASTC12x10UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC12x12Unorm:\n case WebGPUConstants.TextureFormat.ASTC12x12UnormSRGB:\n return true;\n }\n return false;\n }\n static GetWebGPUTextureFormat(type, format, useSRGBBuffer = false) {\n switch (format) {\n case 15:\n return WebGPUConstants.TextureFormat.Depth16Unorm;\n case 16:\n return WebGPUConstants.TextureFormat.Depth24Plus;\n case 13:\n return WebGPUConstants.TextureFormat.Depth24PlusStencil8;\n case 14:\n return WebGPUConstants.TextureFormat.Depth32Float;\n case 17:\n return WebGPUConstants.TextureFormat.Depth24UnormStencil8;\n case 18:\n return WebGPUConstants.TextureFormat.Depth32FloatStencil8;\n case 19:\n return WebGPUConstants.TextureFormat.Stencil8;\n case 36492:\n return useSRGBBuffer ? WebGPUConstants.TextureFormat.BC7RGBAUnormSRGB : WebGPUConstants.TextureFormat.BC7RGBAUnorm;\n case 36495:\n return WebGPUConstants.TextureFormat.BC6HRGBUFloat;\n case 36494:\n return WebGPUConstants.TextureFormat.BC6HRGBFloat;\n case 33779:\n return useSRGBBuffer ? WebGPUConstants.TextureFormat.BC3RGBAUnormSRGB : WebGPUConstants.TextureFormat.BC3RGBAUnorm;\n case 33778:\n return useSRGBBuffer ? WebGPUConstants.TextureFormat.BC2RGBAUnormSRGB : WebGPUConstants.TextureFormat.BC2RGBAUnorm;\n case 33777:\n case 33776:\n return useSRGBBuffer ? WebGPUConstants.TextureFormat.BC1RGBAUnormSRGB : WebGPUConstants.TextureFormat.BC1RGBAUnorm;\n case 37808:\n return useSRGBBuffer ? WebGPUConstants.TextureFormat.ASTC4x4UnormSRGB : WebGPUConstants.TextureFormat.ASTC4x4Unorm;\n case 36196:\n case 37492:\n return useSRGBBuffer ? WebGPUConstants.TextureFormat.ETC2RGB8UnormSRGB : WebGPUConstants.TextureFormat.ETC2RGB8Unorm;\n case 37496:\n return useSRGBBuffer ? WebGPUConstants.TextureFormat.ETC2RGBA8UnormSRGB : WebGPUConstants.TextureFormat.ETC2RGBA8Unorm;\n }\n switch (type) {\n case 3:\n switch (format) {\n case 6:\n return WebGPUConstants.TextureFormat.R8Snorm;\n case 7:\n return WebGPUConstants.TextureFormat.RG8Snorm;\n case 4:\n throw \"RGB format not supported in WebGPU\";\n case 8:\n return WebGPUConstants.TextureFormat.R8Sint;\n case 9:\n return WebGPUConstants.TextureFormat.RG8Sint;\n case 10:\n throw \"RGB_INTEGER format not supported in WebGPU\";\n case 11:\n return WebGPUConstants.TextureFormat.RGBA8Sint;\n default:\n return WebGPUConstants.TextureFormat.RGBA8Snorm;\n }\n case 0:\n switch (format) {\n case 6:\n return WebGPUConstants.TextureFormat.R8Unorm;\n case 7:\n return WebGPUConstants.TextureFormat.RG8Unorm;\n case 4:\n throw \"TEXTUREFORMAT_RGB format not supported in WebGPU\";\n case 5:\n return useSRGBBuffer ? WebGPUConstants.TextureFormat.RGBA8UnormSRGB : WebGPUConstants.TextureFormat.RGBA8Unorm;\n case 12:\n return useSRGBBuffer ? WebGPUConstants.TextureFormat.BGRA8UnormSRGB : WebGPUConstants.TextureFormat.BGRA8Unorm;\n case 8:\n return WebGPUConstants.TextureFormat.R8Uint;\n case 9:\n return WebGPUConstants.TextureFormat.RG8Uint;\n case 10:\n throw \"RGB_INTEGER format not supported in WebGPU\";\n case 11:\n return WebGPUConstants.TextureFormat.RGBA8Uint;\n case 0:\n throw \"TEXTUREFORMAT_ALPHA format not supported in WebGPU\";\n case 1:\n throw \"TEXTUREFORMAT_LUMINANCE format not supported in WebGPU\";\n case 2:\n throw \"TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU\";\n default:\n return WebGPUConstants.TextureFormat.RGBA8Unorm;\n }\n case 4:\n switch (format) {\n case 8:\n return WebGPUConstants.TextureFormat.R16Sint;\n case 9:\n return WebGPUConstants.TextureFormat.RG16Sint;\n case 10:\n throw \"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU\";\n case 11:\n return WebGPUConstants.TextureFormat.RGBA16Sint;\n default:\n return WebGPUConstants.TextureFormat.RGBA16Sint;\n }\n case 5:\n switch (format) {\n case 8:\n return WebGPUConstants.TextureFormat.R16Uint;\n case 9:\n return WebGPUConstants.TextureFormat.RG16Uint;\n case 10:\n throw \"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU\";\n case 11:\n return WebGPUConstants.TextureFormat.RGBA16Uint;\n default:\n return WebGPUConstants.TextureFormat.RGBA16Uint;\n }\n case 6:\n switch (format) {\n case 8:\n return WebGPUConstants.TextureFormat.R32Sint;\n case 9:\n return WebGPUConstants.TextureFormat.RG32Sint;\n case 10:\n throw \"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU\";\n case 11:\n return WebGPUConstants.TextureFormat.RGBA32Sint;\n default:\n return WebGPUConstants.TextureFormat.RGBA32Sint;\n }\n case 7: // Refers to UNSIGNED_INT\n switch (format) {\n case 8:\n return WebGPUConstants.TextureFormat.R32Uint;\n case 9:\n return WebGPUConstants.TextureFormat.RG32Uint;\n case 10:\n throw \"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU\";\n case 11:\n return WebGPUConstants.TextureFormat.RGBA32Uint;\n default:\n return WebGPUConstants.TextureFormat.RGBA32Uint;\n }\n case 1:\n switch (format) {\n case 6:\n return WebGPUConstants.TextureFormat.R32Float; // By default. Other possibility is R16Float.\n case 7:\n return WebGPUConstants.TextureFormat.RG32Float; // By default. Other possibility is RG16Float.\n case 4:\n throw \"TEXTUREFORMAT_RGB format not supported in WebGPU\";\n case 5:\n return WebGPUConstants.TextureFormat.RGBA32Float; // By default. Other possibility is RGBA16Float.\n default:\n return WebGPUConstants.TextureFormat.RGBA32Float;\n }\n case 2:\n switch (format) {\n case 6:\n return WebGPUConstants.TextureFormat.R16Float;\n case 7:\n return WebGPUConstants.TextureFormat.RG16Float;\n case 4:\n throw \"TEXTUREFORMAT_RGB format not supported in WebGPU\";\n case 5:\n return WebGPUConstants.TextureFormat.RGBA16Float;\n default:\n return WebGPUConstants.TextureFormat.RGBA16Float;\n }\n case 10:\n throw \"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU\";\n case 13:\n switch (format) {\n case 5:\n return WebGPUConstants.TextureFormat.RG11B10UFloat;\n case 11:\n throw \"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV\";\n default:\n return WebGPUConstants.TextureFormat.RG11B10UFloat;\n }\n case 14:\n switch (format) {\n case 5:\n return WebGPUConstants.TextureFormat.RGB9E5UFloat;\n case 11:\n throw \"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV\";\n default:\n return WebGPUConstants.TextureFormat.RGB9E5UFloat;\n }\n case 8:\n throw \"TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU\";\n case 9:\n throw \"TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU\";\n case 11:\n switch (format) {\n case 5:\n return WebGPUConstants.TextureFormat.RGB10A2Unorm;\n case 11:\n throw \"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV\";\n default:\n return WebGPUConstants.TextureFormat.RGB10A2Unorm;\n }\n }\n return useSRGBBuffer ? WebGPUConstants.TextureFormat.RGBA8UnormSRGB : WebGPUConstants.TextureFormat.RGBA8Unorm;\n }\n static GetNumChannelsFromWebGPUTextureFormat(format) {\n switch (format) {\n case WebGPUConstants.TextureFormat.R8Unorm:\n case WebGPUConstants.TextureFormat.R8Snorm:\n case WebGPUConstants.TextureFormat.R8Uint:\n case WebGPUConstants.TextureFormat.R8Sint:\n case WebGPUConstants.TextureFormat.BC4RUnorm:\n case WebGPUConstants.TextureFormat.BC4RSnorm:\n case WebGPUConstants.TextureFormat.R16Uint:\n case WebGPUConstants.TextureFormat.R16Sint:\n case WebGPUConstants.TextureFormat.Depth16Unorm:\n case WebGPUConstants.TextureFormat.R16Float:\n case WebGPUConstants.TextureFormat.R32Uint:\n case WebGPUConstants.TextureFormat.R32Sint:\n case WebGPUConstants.TextureFormat.R32Float:\n case WebGPUConstants.TextureFormat.Depth32Float:\n case WebGPUConstants.TextureFormat.Stencil8:\n case WebGPUConstants.TextureFormat.Depth24Plus:\n case WebGPUConstants.TextureFormat.EACR11Unorm:\n case WebGPUConstants.TextureFormat.EACR11Snorm:\n return 1;\n case WebGPUConstants.TextureFormat.RG8Unorm:\n case WebGPUConstants.TextureFormat.RG8Snorm:\n case WebGPUConstants.TextureFormat.RG8Uint:\n case WebGPUConstants.TextureFormat.RG8Sint:\n case WebGPUConstants.TextureFormat.Depth24UnormStencil8: // composite format - let's say it's byte...\n case WebGPUConstants.TextureFormat.Depth32FloatStencil8: // composite format - let's say it's byte...\n case WebGPUConstants.TextureFormat.BC5RGUnorm:\n case WebGPUConstants.TextureFormat.BC5RGSnorm:\n case WebGPUConstants.TextureFormat.RG16Uint:\n case WebGPUConstants.TextureFormat.RG16Sint:\n case WebGPUConstants.TextureFormat.RG16Float:\n case WebGPUConstants.TextureFormat.RG32Uint:\n case WebGPUConstants.TextureFormat.RG32Sint:\n case WebGPUConstants.TextureFormat.RG32Float:\n case WebGPUConstants.TextureFormat.Depth24PlusStencil8:\n case WebGPUConstants.TextureFormat.EACRG11Unorm:\n case WebGPUConstants.TextureFormat.EACRG11Snorm:\n return 2;\n case WebGPUConstants.TextureFormat.RGB9E5UFloat: // composite format - let's say it's byte...\n case WebGPUConstants.TextureFormat.RG11B10UFloat: // composite format - let's say it's byte...\n case WebGPUConstants.TextureFormat.BC6HRGBUFloat:\n case WebGPUConstants.TextureFormat.BC6HRGBFloat:\n case WebGPUConstants.TextureFormat.ETC2RGB8Unorm:\n case WebGPUConstants.TextureFormat.ETC2RGB8UnormSRGB:\n return 3;\n case WebGPUConstants.TextureFormat.RGBA8Unorm:\n case WebGPUConstants.TextureFormat.RGBA8UnormSRGB:\n case WebGPUConstants.TextureFormat.RGBA8Snorm:\n case WebGPUConstants.TextureFormat.RGBA8Uint:\n case WebGPUConstants.TextureFormat.RGBA8Sint:\n case WebGPUConstants.TextureFormat.BGRA8Unorm:\n case WebGPUConstants.TextureFormat.BGRA8UnormSRGB:\n case WebGPUConstants.TextureFormat.RGB10A2Unorm: // composite format - let's say it's byte...\n case WebGPUConstants.TextureFormat.BC7RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC7RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.BC3RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC3RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.BC2RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC2RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.BC1RGBAUnorm:\n case WebGPUConstants.TextureFormat.BC1RGBAUnormSRGB:\n case WebGPUConstants.TextureFormat.RGBA16Uint:\n case WebGPUConstants.TextureFormat.RGBA16Sint:\n case WebGPUConstants.TextureFormat.RGBA16Float:\n case WebGPUConstants.TextureFormat.RGBA32Uint:\n case WebGPUConstants.TextureFormat.RGBA32Sint:\n case WebGPUConstants.TextureFormat.RGBA32Float:\n case WebGPUConstants.TextureFormat.ETC2RGB8A1Unorm:\n case WebGPUConstants.TextureFormat.ETC2RGB8A1UnormSRGB:\n case WebGPUConstants.TextureFormat.ETC2RGBA8Unorm:\n case WebGPUConstants.TextureFormat.ETC2RGBA8UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC4x4Unorm:\n case WebGPUConstants.TextureFormat.ASTC4x4UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC5x4Unorm:\n case WebGPUConstants.TextureFormat.ASTC5x4UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC5x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC5x5UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC6x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC6x5UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC6x6Unorm:\n case WebGPUConstants.TextureFormat.ASTC6x6UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC8x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC8x5UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC8x6Unorm:\n case WebGPUConstants.TextureFormat.ASTC8x6UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC8x8Unorm:\n case WebGPUConstants.TextureFormat.ASTC8x8UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC10x5Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x5UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC10x6Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x6UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC10x8Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x8UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC10x10Unorm:\n case WebGPUConstants.TextureFormat.ASTC10x10UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC12x10Unorm:\n case WebGPUConstants.TextureFormat.ASTC12x10UnormSRGB:\n case WebGPUConstants.TextureFormat.ASTC12x12Unorm:\n case WebGPUConstants.TextureFormat.ASTC12x12UnormSRGB:\n return 4;\n }\n throw `Unknown format ${format}!`;\n }\n static HasStencilAspect(format) {\n switch (format) {\n case WebGPUConstants.TextureFormat.Stencil8:\n case WebGPUConstants.TextureFormat.Depth24UnormStencil8:\n case WebGPUConstants.TextureFormat.Depth32FloatStencil8:\n case WebGPUConstants.TextureFormat.Depth24PlusStencil8:\n return true;\n }\n return false;\n }\n static HasDepthAndStencilAspects(format) {\n switch (format) {\n case WebGPUConstants.TextureFormat.Depth24UnormStencil8:\n case WebGPUConstants.TextureFormat.Depth32FloatStencil8:\n case WebGPUConstants.TextureFormat.Depth24PlusStencil8:\n return true;\n }\n return false;\n }\n static GetDepthFormatOnly(format) {\n switch (format) {\n case WebGPUConstants.TextureFormat.Depth16Unorm:\n return WebGPUConstants.TextureFormat.Depth16Unorm;\n case WebGPUConstants.TextureFormat.Depth24Plus:\n return WebGPUConstants.TextureFormat.Depth24Plus;\n case WebGPUConstants.TextureFormat.Depth24PlusStencil8:\n return WebGPUConstants.TextureFormat.Depth24Plus;\n case WebGPUConstants.TextureFormat.Depth24UnormStencil8:\n return WebGPUConstants.TextureFormat.Depth24Plus;\n case WebGPUConstants.TextureFormat.Depth32Float:\n return WebGPUConstants.TextureFormat.Depth32Float;\n case WebGPUConstants.TextureFormat.Depth32FloatStencil8:\n return WebGPUConstants.TextureFormat.Depth32Float;\n }\n return format;\n }\n copyVideoToTexture(video, texture, format, invertY = false, commandEncoder) {\n var _a, _b, _c, _d;\n const useOwnCommandEncoder = commandEncoder === undefined;\n const [pipeline, bindGroupLayout] = this._getVideoPipeline(format, invertY ? VideoPipelineType.InvertY : VideoPipelineType.DontInvertY);\n if (useOwnCommandEncoder) {\n commandEncoder = this._device.createCommandEncoder({});\n }\n (_b = (_a = commandEncoder).pushDebugGroup) === null || _b === void 0 ? void 0 : _b.call(_a, `copy video to texture - invertY=${invertY}`);\n const webgpuHardwareTexture = texture._hardwareTexture;\n const renderPassDescriptor = {\n colorAttachments: [\n {\n view: webgpuHardwareTexture.underlyingResource.createView({\n format,\n dimension: WebGPUConstants.TextureViewDimension.E2d,\n mipLevelCount: 1,\n baseArrayLayer: 0,\n baseMipLevel: 0,\n arrayLayerCount: 1,\n aspect: WebGPUConstants.TextureAspect.All,\n }),\n loadOp: WebGPUConstants.LoadOp.Load,\n storeOp: WebGPUConstants.StoreOp.Store,\n },\n ],\n };\n const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);\n const descriptor = {\n layout: bindGroupLayout,\n entries: [\n {\n binding: 0,\n resource: this._videoSampler,\n },\n {\n binding: 1,\n resource: this._device.importExternalTexture({\n source: video.underlyingResource,\n }),\n },\n ],\n };\n const bindGroup = this._device.createBindGroup(descriptor);\n passEncoder.setPipeline(pipeline);\n passEncoder.setBindGroup(0, bindGroup);\n passEncoder.draw(4, 1, 0, 0);\n passEncoder.end();\n (_d = (_c = commandEncoder).popDebugGroup) === null || _d === void 0 ? void 0 : _d.call(_c);\n if (useOwnCommandEncoder) {\n this._device.queue.submit([commandEncoder.finish()]);\n commandEncoder = null;\n }\n }\n invertYPreMultiplyAlpha(gpuOrHdwTexture, width, height, format, invertY = false, premultiplyAlpha = false, faceIndex = 0, mipLevel = 0, layers = 1, ofstX = 0, ofstY = 0, rectWidth = 0, rectHeight = 0, commandEncoder, \n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n allowGPUOptimization) {\n var _a, _b, _c, _d, _e, _f;\n const useRect = rectWidth !== 0;\n const useOwnCommandEncoder = commandEncoder === undefined;\n const [pipeline, bindGroupLayout] = this._getPipeline(format, useRect ? PipelineType.InvertYPremultiplyAlphaWithOfst : PipelineType.InvertYPremultiplyAlpha, {\n invertY,\n premultiplyAlpha,\n });\n faceIndex = Math.max(faceIndex, 0);\n if (useOwnCommandEncoder) {\n commandEncoder = this._device.createCommandEncoder({});\n }\n (_b = (_a = commandEncoder).pushDebugGroup) === null || _b === void 0 ? void 0 : _b.call(_a, `internal process texture - invertY=${invertY} premultiplyAlpha=${premultiplyAlpha}`);\n let gpuTexture;\n if (WebGPUTextureHelper._IsHardwareTexture(gpuOrHdwTexture)) {\n gpuTexture = gpuOrHdwTexture.underlyingResource;\n if (!(invertY && !premultiplyAlpha && layers === 1 && faceIndex === 0)) {\n // we optimize only for the most likely case (invertY=true, premultiplyAlpha=false, layers=1, faceIndex=0) to avoid dealing with big caches\n gpuOrHdwTexture = undefined;\n }\n }\n else {\n gpuTexture = gpuOrHdwTexture;\n gpuOrHdwTexture = undefined;\n }\n if (!gpuTexture) {\n return;\n }\n if (useRect) {\n this._bufferManager.setRawData(this._ubCopyWithOfst, 0, new Float32Array([ofstX, ofstY, rectWidth, rectHeight]), 0, 4 * 4);\n }\n const webgpuHardwareTexture = gpuOrHdwTexture;\n const outputTexture = (_c = webgpuHardwareTexture === null || webgpuHardwareTexture === void 0 ? void 0 : webgpuHardwareTexture._copyInvertYTempTexture) !== null && _c !== void 0 ? _c : this.createTexture({ width, height, layers: 1 }, false, false, false, false, false, format, 1, commandEncoder, WebGPUConstants.TextureUsage.CopySrc | WebGPUConstants.TextureUsage.RenderAttachment | WebGPUConstants.TextureUsage.TextureBinding, undefined, \"TempTextureForCopyWithInvertY\");\n const renderPassDescriptor = (_d = webgpuHardwareTexture === null || webgpuHardwareTexture === void 0 ? void 0 : webgpuHardwareTexture._copyInvertYRenderPassDescr) !== null && _d !== void 0 ? _d : {\n colorAttachments: [\n {\n view: outputTexture.createView({\n format,\n dimension: WebGPUConstants.TextureViewDimension.E2d,\n baseMipLevel: 0,\n mipLevelCount: 1,\n arrayLayerCount: 1,\n baseArrayLayer: 0,\n }),\n loadOp: WebGPUConstants.LoadOp.Load,\n storeOp: WebGPUConstants.StoreOp.Store,\n },\n ],\n };\n const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);\n let bindGroup = useRect ? webgpuHardwareTexture === null || webgpuHardwareTexture === void 0 ? void 0 : webgpuHardwareTexture._copyInvertYBindGroupWithOfst : webgpuHardwareTexture === null || webgpuHardwareTexture === void 0 ? void 0 : webgpuHardwareTexture._copyInvertYBindGroup;\n if (!bindGroup) {\n const descriptor = {\n layout: bindGroupLayout,\n entries: [\n {\n binding: 0,\n resource: gpuTexture.createView({\n format,\n dimension: WebGPUConstants.TextureViewDimension.E2d,\n baseMipLevel: mipLevel,\n mipLevelCount: 1,\n arrayLayerCount: layers,\n baseArrayLayer: faceIndex,\n }),\n },\n ],\n };\n if (useRect) {\n descriptor.entries.push({\n binding: 1,\n resource: {\n buffer: this._ubCopyWithOfst,\n },\n });\n }\n bindGroup = this._device.createBindGroup(descriptor);\n }\n passEncoder.setPipeline(pipeline);\n passEncoder.setBindGroup(0, bindGroup);\n passEncoder.draw(4, 1, 0, 0);\n passEncoder.end();\n commandEncoder.copyTextureToTexture({\n texture: outputTexture,\n }, {\n texture: gpuTexture,\n mipLevel,\n origin: {\n x: 0,\n y: 0,\n z: faceIndex,\n },\n }, {\n width,\n height,\n depthOrArrayLayers: 1,\n });\n if (webgpuHardwareTexture) {\n webgpuHardwareTexture._copyInvertYTempTexture = outputTexture;\n webgpuHardwareTexture._copyInvertYRenderPassDescr = renderPassDescriptor;\n if (useRect) {\n webgpuHardwareTexture._copyInvertYBindGroupWithOfst = bindGroup;\n }\n else {\n webgpuHardwareTexture._copyInvertYBindGroup = bindGroup;\n }\n }\n else {\n this._deferredReleaseTextures.push([outputTexture, null]);\n }\n (_f = (_e = commandEncoder).popDebugGroup) === null || _f === void 0 ? void 0 : _f.call(_e);\n if (useOwnCommandEncoder) {\n this._device.queue.submit([commandEncoder.finish()]);\n commandEncoder = null;\n }\n }\n copyWithInvertY(srcTextureView, format, renderPassDescriptor, commandEncoder) {\n var _a, _b, _c, _d;\n const useOwnCommandEncoder = commandEncoder === undefined;\n const [pipeline, bindGroupLayout] = this._getPipeline(format, PipelineType.InvertYPremultiplyAlpha, { invertY: true, premultiplyAlpha: false });\n if (useOwnCommandEncoder) {\n commandEncoder = this._device.createCommandEncoder({});\n }\n (_b = (_a = commandEncoder).pushDebugGroup) === null || _b === void 0 ? void 0 : _b.call(_a, `internal copy texture with invertY`);\n const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);\n const bindGroup = this._device.createBindGroup({\n layout: bindGroupLayout,\n entries: [\n {\n binding: 0,\n resource: srcTextureView,\n },\n ],\n });\n passEncoder.setPipeline(pipeline);\n passEncoder.setBindGroup(0, bindGroup);\n passEncoder.draw(4, 1, 0, 0);\n passEncoder.end();\n (_d = (_c = commandEncoder).popDebugGroup) === null || _d === void 0 ? void 0 : _d.call(_c);\n if (useOwnCommandEncoder) {\n this._device.queue.submit([commandEncoder.finish()]);\n commandEncoder = null;\n }\n }\n //------------------------------------------------------------------------------\n // Creation\n //------------------------------------------------------------------------------\n createTexture(imageBitmap, hasMipmaps = false, generateMipmaps = false, invertY = false, premultiplyAlpha = false, is3D = false, format = WebGPUConstants.TextureFormat.RGBA8Unorm, sampleCount = 1, commandEncoder, usage = -1, additionalUsages = 0, label) {\n if (sampleCount > 1) {\n // WebGPU only supports 1 or 4\n sampleCount = 4;\n }\n const layerCount = imageBitmap.layers || 1;\n const textureSize = {\n width: imageBitmap.width,\n height: imageBitmap.height,\n depthOrArrayLayers: layerCount,\n };\n const renderAttachmentFlag = renderableTextureFormatToIndex[format] ? WebGPUConstants.TextureUsage.RenderAttachment : 0;\n const isCompressedFormat = WebGPUTextureHelper.IsCompressedFormat(format);\n const mipLevelCount = hasMipmaps ? WebGPUTextureHelper.ComputeNumMipmapLevels(imageBitmap.width, imageBitmap.height) : 1;\n const usages = usage >= 0 ? usage : WebGPUConstants.TextureUsage.CopySrc | WebGPUConstants.TextureUsage.CopyDst | WebGPUConstants.TextureUsage.TextureBinding;\n additionalUsages |= hasMipmaps && !isCompressedFormat ? WebGPUConstants.TextureUsage.CopySrc | renderAttachmentFlag : 0;\n if (!isCompressedFormat && !is3D) {\n // we don't know in advance if the texture will be updated with copyExternalImageToTexture (which requires to have those flags), so we need to force the flags all the times\n additionalUsages |= renderAttachmentFlag | WebGPUConstants.TextureUsage.CopyDst;\n }\n const gpuTexture = this._device.createTexture({\n label: `Texture${is3D ? \"3D\" : \"2D\"}_${label ? label + \"_\" : \"\"}${textureSize.width}x${textureSize.height}x${textureSize.depthOrArrayLayers}_${hasMipmaps ? \"wmips\" : \"womips\"}_${format}_samples${sampleCount}`,\n size: textureSize,\n dimension: is3D ? WebGPUConstants.TextureDimension.E3d : WebGPUConstants.TextureDimension.E2d,\n format,\n usage: usages | additionalUsages,\n sampleCount,\n mipLevelCount,\n });\n if (WebGPUTextureHelper.IsImageBitmap(imageBitmap)) {\n this.updateTexture(imageBitmap, gpuTexture, imageBitmap.width, imageBitmap.height, layerCount, format, 0, 0, invertY, premultiplyAlpha, 0, 0);\n if (hasMipmaps && generateMipmaps) {\n this.generateMipmaps(gpuTexture, format, mipLevelCount, 0, commandEncoder);\n }\n }\n return gpuTexture;\n }\n createCubeTexture(imageBitmaps, hasMipmaps = false, generateMipmaps = false, invertY = false, premultiplyAlpha = false, format = WebGPUConstants.TextureFormat.RGBA8Unorm, sampleCount = 1, commandEncoder, usage = -1, additionalUsages = 0, label) {\n if (sampleCount > 1) {\n // WebGPU only supports 1 or 4\n sampleCount = 4;\n }\n const width = WebGPUTextureHelper.IsImageBitmapArray(imageBitmaps) ? imageBitmaps[0].width : imageBitmaps.width;\n const height = WebGPUTextureHelper.IsImageBitmapArray(imageBitmaps) ? imageBitmaps[0].height : imageBitmaps.height;\n const renderAttachmentFlag = renderableTextureFormatToIndex[format] ? WebGPUConstants.TextureUsage.RenderAttachment : 0;\n const isCompressedFormat = WebGPUTextureHelper.IsCompressedFormat(format);\n const mipLevelCount = hasMipmaps ? WebGPUTextureHelper.ComputeNumMipmapLevels(width, height) : 1;\n const usages = usage >= 0 ? usage : WebGPUConstants.TextureUsage.CopySrc | WebGPUConstants.TextureUsage.CopyDst | WebGPUConstants.TextureUsage.TextureBinding;\n additionalUsages |= hasMipmaps && !isCompressedFormat ? WebGPUConstants.TextureUsage.CopySrc | renderAttachmentFlag : 0;\n if (!isCompressedFormat) {\n // we don't know in advance if the texture will be updated with copyExternalImageToTexture (which requires to have those flags), so we need to force the flags all the times\n additionalUsages |= renderAttachmentFlag | WebGPUConstants.TextureUsage.CopyDst;\n }\n const gpuTexture = this._device.createTexture({\n label: `TextureCube_${label ? label + \"_\" : \"\"}${width}x${height}x6_${hasMipmaps ? \"wmips\" : \"womips\"}_${format}_samples${sampleCount}`,\n size: {\n width,\n height,\n depthOrArrayLayers: 6,\n },\n dimension: WebGPUConstants.TextureDimension.E2d,\n format,\n usage: usages | additionalUsages,\n sampleCount,\n mipLevelCount,\n });\n if (WebGPUTextureHelper.IsImageBitmapArray(imageBitmaps)) {\n this.updateCubeTextures(imageBitmaps, gpuTexture, width, height, format, invertY, premultiplyAlpha, 0, 0);\n if (hasMipmaps && generateMipmaps) {\n this.generateCubeMipmaps(gpuTexture, format, mipLevelCount, commandEncoder);\n }\n }\n return gpuTexture;\n }\n generateCubeMipmaps(gpuTexture, format, mipLevelCount, commandEncoder) {\n var _a, _b, _c, _d;\n const useOwnCommandEncoder = commandEncoder === undefined;\n if (useOwnCommandEncoder) {\n commandEncoder = this._device.createCommandEncoder({});\n }\n (_b = (_a = commandEncoder).pushDebugGroup) === null || _b === void 0 ? void 0 : _b.call(_a, `create cube mipmaps - ${mipLevelCount} levels`);\n for (let f = 0; f < 6; ++f) {\n this.generateMipmaps(gpuTexture, format, mipLevelCount, f, commandEncoder);\n }\n (_d = (_c = commandEncoder).popDebugGroup) === null || _d === void 0 ? void 0 : _d.call(_c);\n if (useOwnCommandEncoder) {\n this._device.queue.submit([commandEncoder.finish()]);\n commandEncoder = null;\n }\n }\n generateMipmaps(gpuOrHdwTexture, format, mipLevelCount, faceIndex = 0, commandEncoder) {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n const useOwnCommandEncoder = commandEncoder === undefined;\n const [pipeline, bindGroupLayout] = this._getPipeline(format);\n faceIndex = Math.max(faceIndex, 0);\n if (useOwnCommandEncoder) {\n commandEncoder = this._device.createCommandEncoder({});\n }\n (_b = (_a = commandEncoder).pushDebugGroup) === null || _b === void 0 ? void 0 : _b.call(_a, `create mipmaps for face #${faceIndex} - ${mipLevelCount} levels`);\n let gpuTexture;\n if (WebGPUTextureHelper._IsHardwareTexture(gpuOrHdwTexture)) {\n gpuTexture = gpuOrHdwTexture.underlyingResource;\n gpuOrHdwTexture._mipmapGenRenderPassDescr = gpuOrHdwTexture._mipmapGenRenderPassDescr || [];\n gpuOrHdwTexture._mipmapGenBindGroup = gpuOrHdwTexture._mipmapGenBindGroup || [];\n }\n else {\n gpuTexture = gpuOrHdwTexture;\n gpuOrHdwTexture = undefined;\n }\n if (!gpuTexture) {\n return;\n }\n const webgpuHardwareTexture = gpuOrHdwTexture;\n for (let i = 1; i < mipLevelCount; ++i) {\n const renderPassDescriptor = (_d = (_c = webgpuHardwareTexture === null || webgpuHardwareTexture === void 0 ? void 0 : webgpuHardwareTexture._mipmapGenRenderPassDescr[faceIndex]) === null || _c === void 0 ? void 0 : _c[i - 1]) !== null && _d !== void 0 ? _d : {\n colorAttachments: [\n {\n view: gpuTexture.createView({\n format,\n dimension: WebGPUConstants.TextureViewDimension.E2d,\n baseMipLevel: i,\n mipLevelCount: 1,\n arrayLayerCount: 1,\n baseArrayLayer: faceIndex,\n }),\n loadOp: WebGPUConstants.LoadOp.Load,\n storeOp: WebGPUConstants.StoreOp.Store,\n },\n ],\n };\n if (webgpuHardwareTexture) {\n webgpuHardwareTexture._mipmapGenRenderPassDescr[faceIndex] = webgpuHardwareTexture._mipmapGenRenderPassDescr[faceIndex] || [];\n webgpuHardwareTexture._mipmapGenRenderPassDescr[faceIndex][i - 1] = renderPassDescriptor;\n }\n const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);\n const bindGroup = (_f = (_e = webgpuHardwareTexture === null || webgpuHardwareTexture === void 0 ? void 0 : webgpuHardwareTexture._mipmapGenBindGroup[faceIndex]) === null || _e === void 0 ? void 0 : _e[i - 1]) !== null && _f !== void 0 ? _f : this._device.createBindGroup({\n layout: bindGroupLayout,\n entries: [\n {\n binding: 0,\n resource: this._mipmapSampler,\n },\n {\n binding: 1,\n resource: gpuTexture.createView({\n format,\n dimension: WebGPUConstants.TextureViewDimension.E2d,\n baseMipLevel: i - 1,\n mipLevelCount: 1,\n arrayLayerCount: 1,\n baseArrayLayer: faceIndex,\n }),\n },\n ],\n });\n if (webgpuHardwareTexture) {\n webgpuHardwareTexture._mipmapGenBindGroup[faceIndex] = webgpuHardwareTexture._mipmapGenBindGroup[faceIndex] || [];\n webgpuHardwareTexture._mipmapGenBindGroup[faceIndex][i - 1] = bindGroup;\n }\n passEncoder.setPipeline(pipeline);\n passEncoder.setBindGroup(0, bindGroup);\n passEncoder.draw(4, 1, 0, 0);\n passEncoder.end();\n }\n (_h = (_g = commandEncoder).popDebugGroup) === null || _h === void 0 ? void 0 : _h.call(_g);\n if (useOwnCommandEncoder) {\n this._device.queue.submit([commandEncoder.finish()]);\n commandEncoder = null;\n }\n }\n createGPUTextureForInternalTexture(texture, width, height, depth, creationFlags) {\n if (!texture._hardwareTexture) {\n texture._hardwareTexture = new WebGPUHardwareTexture();\n }\n if (width === undefined) {\n width = texture.width;\n }\n if (height === undefined) {\n height = texture.height;\n }\n if (depth === undefined) {\n depth = texture.depth;\n }\n const gpuTextureWrapper = texture._hardwareTexture;\n const isStorageTexture = ((creationFlags !== null && creationFlags !== void 0 ? creationFlags : 0) & 1) !== 0;\n gpuTextureWrapper.format = WebGPUTextureHelper.GetWebGPUTextureFormat(texture.type, texture.format, texture._useSRGBBuffer);\n gpuTextureWrapper.textureUsages =\n texture._source === InternalTextureSource.RenderTarget || texture.source === InternalTextureSource.MultiRenderTarget\n ? WebGPUConstants.TextureUsage.TextureBinding | WebGPUConstants.TextureUsage.CopySrc | WebGPUConstants.TextureUsage.RenderAttachment\n : texture._source === InternalTextureSource.DepthStencil\n ? WebGPUConstants.TextureUsage.TextureBinding | WebGPUConstants.TextureUsage.RenderAttachment\n : -1;\n gpuTextureWrapper.textureAdditionalUsages = isStorageTexture ? WebGPUConstants.TextureUsage.StorageBinding : 0;\n const hasMipMaps = texture.generateMipMaps;\n const layerCount = depth || 1;\n let mipmapCount;\n if (texture._maxLodLevel !== null) {\n mipmapCount = texture._maxLodLevel;\n }\n else {\n mipmapCount = hasMipMaps ? WebGPUTextureHelper.ComputeNumMipmapLevels(width, height) : 1;\n }\n if (texture.isCube) {\n const gpuTexture = this.createCubeTexture({ width, height }, texture.generateMipMaps, texture.generateMipMaps, texture.invertY, false, gpuTextureWrapper.format, 1, this._commandEncoderForCreation, gpuTextureWrapper.textureUsages, gpuTextureWrapper.textureAdditionalUsages, texture.label);\n gpuTextureWrapper.set(gpuTexture);\n gpuTextureWrapper.createView({\n format: WebGPUTextureHelper.GetDepthFormatOnly(gpuTextureWrapper.format),\n dimension: WebGPUConstants.TextureViewDimension.Cube,\n mipLevelCount: mipmapCount,\n baseArrayLayer: 0,\n baseMipLevel: 0,\n arrayLayerCount: 6,\n aspect: WebGPUTextureHelper.HasDepthAndStencilAspects(gpuTextureWrapper.format) ? WebGPUConstants.TextureAspect.DepthOnly : WebGPUConstants.TextureAspect.All,\n }, isStorageTexture);\n }\n else {\n const gpuTexture = this.createTexture({ width, height, layers: layerCount }, texture.generateMipMaps, texture.generateMipMaps, texture.invertY, false, texture.is3D, gpuTextureWrapper.format, 1, this._commandEncoderForCreation, gpuTextureWrapper.textureUsages, gpuTextureWrapper.textureAdditionalUsages, texture.label);\n gpuTextureWrapper.set(gpuTexture);\n gpuTextureWrapper.createView({\n format: WebGPUTextureHelper.GetDepthFormatOnly(gpuTextureWrapper.format),\n dimension: texture.is2DArray\n ? WebGPUConstants.TextureViewDimension.E2dArray\n : texture.is3D\n ? WebGPUConstants.TextureDimension.E3d\n : WebGPUConstants.TextureViewDimension.E2d,\n mipLevelCount: mipmapCount,\n baseArrayLayer: 0,\n baseMipLevel: 0,\n arrayLayerCount: texture.is3D ? 1 : layerCount,\n aspect: WebGPUTextureHelper.HasDepthAndStencilAspects(gpuTextureWrapper.format) ? WebGPUConstants.TextureAspect.DepthOnly : WebGPUConstants.TextureAspect.All,\n }, isStorageTexture);\n }\n texture.width = texture.baseWidth = width;\n texture.height = texture.baseHeight = height;\n texture.depth = texture.baseDepth = depth;\n this.createMSAATexture(texture, texture.samples);\n return gpuTextureWrapper;\n }\n createMSAATexture(texture, samples, releaseExisting = true, index = -1) {\n const gpuTextureWrapper = texture._hardwareTexture;\n if (releaseExisting) {\n gpuTextureWrapper === null || gpuTextureWrapper === void 0 ? void 0 : gpuTextureWrapper.releaseMSAATexture();\n }\n if (!gpuTextureWrapper || (samples !== null && samples !== void 0 ? samples : 1) <= 1) {\n return;\n }\n const width = texture.width;\n const height = texture.height;\n const gpuMSAATexture = this.createTexture({ width, height, layers: 1 }, false, false, false, false, false, gpuTextureWrapper.format, samples, this._commandEncoderForCreation, WebGPUConstants.TextureUsage.RenderAttachment, 0, texture.label ? \"MSAA\" + texture.label : undefined);\n gpuTextureWrapper.setMSAATexture(gpuMSAATexture, index);\n }\n //------------------------------------------------------------------------------\n // Update\n //------------------------------------------------------------------------------\n updateCubeTextures(imageBitmaps, gpuTexture, width, height, format, invertY = false, premultiplyAlpha = false, offsetX = 0, offsetY = 0) {\n const faces = [0, 3, 1, 4, 2, 5];\n for (let f = 0; f < faces.length; ++f) {\n const imageBitmap = imageBitmaps[faces[f]];\n this.updateTexture(imageBitmap, gpuTexture, width, height, 1, format, f, 0, invertY, premultiplyAlpha, offsetX, offsetY);\n }\n }\n // TODO WEBGPU handle data source not being in the same format than the destination texture?\n updateTexture(imageBitmap, texture, width, height, layers, format, faceIndex = 0, mipLevel = 0, invertY = false, premultiplyAlpha = false, offsetX = 0, offsetY = 0, allowGPUOptimization) {\n const gpuTexture = WebGPUTextureHelper._IsInternalTexture(texture) ? texture._hardwareTexture.underlyingResource : texture;\n const blockInformation = WebGPUTextureHelper._GetBlockInformationFromFormat(format);\n const gpuOrHdwTexture = WebGPUTextureHelper._IsInternalTexture(texture) ? texture._hardwareTexture : texture;\n const textureCopyView = {\n texture: gpuTexture,\n origin: {\n x: offsetX,\n y: offsetY,\n z: Math.max(faceIndex, 0),\n },\n mipLevel: mipLevel,\n premultipliedAlpha: premultiplyAlpha,\n };\n const textureExtent = {\n width: Math.ceil(width / blockInformation.width) * blockInformation.width,\n height: Math.ceil(height / blockInformation.height) * blockInformation.height,\n depthOrArrayLayers: layers || 1,\n };\n if (imageBitmap.byteLength !== undefined) {\n imageBitmap = imageBitmap;\n const bytesPerRow = Math.ceil(width / blockInformation.width) * blockInformation.length;\n const aligned = Math.ceil(bytesPerRow / 256) * 256 === bytesPerRow;\n if (aligned) {\n const commandEncoder = this._device.createCommandEncoder({});\n const buffer = this._bufferManager.createRawBuffer(imageBitmap.byteLength, WebGPUConstants.BufferUsage.MapWrite | WebGPUConstants.BufferUsage.CopySrc, true);\n const arrayBuffer = buffer.getMappedRange();\n new Uint8Array(arrayBuffer).set(imageBitmap);\n buffer.unmap();\n commandEncoder.copyBufferToTexture({\n buffer: buffer,\n offset: 0,\n bytesPerRow,\n rowsPerImage: height,\n }, textureCopyView, textureExtent);\n this._device.queue.submit([commandEncoder.finish()]);\n this._bufferManager.releaseBuffer(buffer);\n }\n else {\n this._device.queue.writeTexture(textureCopyView, imageBitmap, {\n offset: 0,\n bytesPerRow,\n rowsPerImage: height,\n }, textureExtent);\n }\n if (invertY || premultiplyAlpha) {\n if (WebGPUTextureHelper._IsInternalTexture(texture)) {\n const dontUseRect = offsetX === 0 && offsetY === 0 && width === texture.width && height === texture.height;\n this.invertYPreMultiplyAlpha(gpuOrHdwTexture, texture.width, texture.height, format, invertY, premultiplyAlpha, faceIndex, mipLevel, layers || 1, offsetX, offsetY, dontUseRect ? 0 : width, dontUseRect ? 0 : height, undefined, allowGPUOptimization);\n }\n else {\n // we should never take this code path\n throw \"updateTexture: Can't process the texture data because a GPUTexture was provided instead of an InternalTexture!\";\n }\n }\n }\n else {\n imageBitmap = imageBitmap;\n if (invertY) {\n textureCopyView.premultipliedAlpha = false; // we are going to handle premultiplyAlpha ourselves\n // we must preprocess the image\n if (WebGPUTextureHelper._IsInternalTexture(texture) && offsetX === 0 && offsetY === 0 && width === texture.width && height === texture.height) {\n // optimization when the source image is the same size than the destination texture and offsets X/Y == 0:\n // we simply copy the source to the destination and we apply the preprocessing on the destination\n this._device.queue.copyExternalImageToTexture({ source: imageBitmap }, textureCopyView, textureExtent);\n this.invertYPreMultiplyAlpha(gpuOrHdwTexture, width, height, format, invertY, premultiplyAlpha, faceIndex, mipLevel, layers || 1, 0, 0, 0, 0, undefined, allowGPUOptimization);\n }\n else {\n // we must apply the preprocessing on the source image before copying it into the destination texture\n const commandEncoder = this._device.createCommandEncoder({});\n // create a temp texture and copy the image to it\n const srcTexture = this.createTexture({ width, height, layers: 1 }, false, false, false, false, false, format, 1, commandEncoder, WebGPUConstants.TextureUsage.CopySrc | WebGPUConstants.TextureUsage.TextureBinding, undefined, \"TempTextureForUpdateTexture\");\n this._deferredReleaseTextures.push([srcTexture, null]);\n textureExtent.depthOrArrayLayers = 1;\n this._device.queue.copyExternalImageToTexture({ source: imageBitmap }, { texture: srcTexture }, textureExtent);\n textureExtent.depthOrArrayLayers = layers || 1;\n // apply the preprocessing to this temp texture\n this.invertYPreMultiplyAlpha(srcTexture, width, height, format, invertY, premultiplyAlpha, faceIndex, mipLevel, layers || 1, 0, 0, 0, 0, commandEncoder, allowGPUOptimization);\n // copy the temp texture to the destination texture\n commandEncoder.copyTextureToTexture({ texture: srcTexture }, textureCopyView, textureExtent);\n this._device.queue.submit([commandEncoder.finish()]);\n }\n }\n else {\n // no preprocessing: direct copy to destination texture\n this._device.queue.copyExternalImageToTexture({ source: imageBitmap }, textureCopyView, textureExtent);\n }\n }\n }\n readPixels(texture, x, y, width, height, format, faceIndex = 0, mipLevel = 0, buffer = null, noDataConversion = false) {\n const blockInformation = WebGPUTextureHelper._GetBlockInformationFromFormat(format);\n const bytesPerRow = Math.ceil(width / blockInformation.width) * blockInformation.length;\n const bytesPerRowAligned = Math.ceil(bytesPerRow / 256) * 256;\n const size = bytesPerRowAligned * height;\n const gpuBuffer = this._bufferManager.createRawBuffer(size, WebGPUConstants.BufferUsage.MapRead | WebGPUConstants.BufferUsage.CopyDst);\n const commandEncoder = this._device.createCommandEncoder({});\n commandEncoder.copyTextureToBuffer({\n texture,\n mipLevel,\n origin: {\n x,\n y,\n z: Math.max(faceIndex, 0),\n },\n }, {\n buffer: gpuBuffer,\n offset: 0,\n bytesPerRow: bytesPerRowAligned,\n }, {\n width,\n height,\n depthOrArrayLayers: 1,\n });\n this._device.queue.submit([commandEncoder.finish()]);\n return this._bufferManager.readDataFromBuffer(gpuBuffer, size, width, height, bytesPerRow, bytesPerRowAligned, WebGPUTextureHelper._GetTextureTypeFromFormat(format), 0, buffer, true, noDataConversion);\n }\n //------------------------------------------------------------------------------\n // Dispose\n //------------------------------------------------------------------------------\n releaseTexture(texture) {\n if (WebGPUTextureHelper._IsInternalTexture(texture)) {\n const hardwareTexture = texture._hardwareTexture;\n const irradianceTexture = texture._irradianceTexture;\n // We can't destroy the objects just now because they could be used in the current frame - we delay the destroying after the end of the frame\n this._deferredReleaseTextures.push([hardwareTexture, irradianceTexture]);\n }\n else {\n this._deferredReleaseTextures.push([texture, null]);\n }\n }\n destroyDeferredTextures() {\n for (let i = 0; i < this._deferredReleaseTextures.length; ++i) {\n const [hardwareTexture, irradianceTexture] = this._deferredReleaseTextures[i];\n if (hardwareTexture) {\n if (WebGPUTextureHelper._IsHardwareTexture(hardwareTexture)) {\n hardwareTexture.release();\n }\n else {\n hardwareTexture.destroy();\n }\n }\n irradianceTexture === null || irradianceTexture === void 0 ? void 0 : irradianceTexture.dispose();\n }\n this._deferredReleaseTextures.length = 0;\n }\n}\n//# sourceMappingURL=webgpuTextureHelper.js.map","import { DataBuffer } from \"../../Buffers/dataBuffer.js\";\n/** @internal */\nexport class WebGPUDataBuffer extends DataBuffer {\n constructor(resource, capacity = 0) {\n super();\n this.capacity = capacity;\n this._buffer = resource;\n }\n get underlyingResource() {\n return this._buffer;\n }\n}\n//# sourceMappingURL=webgpuDataBuffer.js.map","import { WebGPUDataBuffer } from \"../../Meshes/WebGPU/webgpuDataBuffer.js\";\nimport { FromHalfFloat } from \"../../Misc/textureTools.js\";\n\nimport { allocateAndCopyTypedBuffer } from \"../Extensions/engine.readTexture.js\";\nimport * as WebGPUConstants from \"./webgpuConstants.js\";\n/** @internal */\nexport class WebGPUBufferManager {\n static _IsGPUBuffer(buffer) {\n return buffer.underlyingResource === undefined;\n }\n constructor(device) {\n this._deferredReleaseBuffers = [];\n this._device = device;\n }\n createRawBuffer(viewOrSize, flags, mappedAtCreation = false) {\n const alignedLength = viewOrSize.byteLength !== undefined ? (viewOrSize.byteLength + 3) & ~3 : (viewOrSize + 3) & ~3; // 4 bytes alignments (because of the upload which requires this)\n const verticesBufferDescriptor = {\n mappedAtCreation,\n size: alignedLength,\n usage: flags,\n };\n return this._device.createBuffer(verticesBufferDescriptor);\n }\n createBuffer(viewOrSize, flags) {\n const isView = viewOrSize.byteLength !== undefined;\n const buffer = this.createRawBuffer(viewOrSize, flags);\n const dataBuffer = new WebGPUDataBuffer(buffer);\n dataBuffer.references = 1;\n dataBuffer.capacity = isView ? viewOrSize.byteLength : viewOrSize;\n if (isView) {\n this.setSubData(dataBuffer, 0, viewOrSize);\n }\n return dataBuffer;\n }\n setRawData(buffer, dstByteOffset, src, srcByteOffset, byteLength) {\n this._device.queue.writeBuffer(buffer, dstByteOffset, src.buffer, srcByteOffset, byteLength);\n }\n setSubData(dataBuffer, dstByteOffset, src, srcByteOffset = 0, byteLength = 0) {\n const buffer = dataBuffer.underlyingResource;\n byteLength = byteLength || src.byteLength;\n byteLength = Math.min(byteLength, dataBuffer.capacity - dstByteOffset);\n // After Migration to Canary\n let chunkStart = src.byteOffset + srcByteOffset;\n let chunkEnd = chunkStart + byteLength;\n // 4 bytes alignments for upload\n const alignedLength = (byteLength + 3) & ~3;\n if (alignedLength !== byteLength) {\n const tempView = new Uint8Array(src.buffer.slice(chunkStart, chunkEnd));\n src = new Uint8Array(alignedLength);\n src.set(tempView);\n srcByteOffset = 0;\n chunkStart = 0;\n chunkEnd = alignedLength;\n byteLength = alignedLength;\n }\n // Chunk\n const maxChunk = 1024 * 1024 * 15;\n let offset = 0;\n while (chunkEnd - (chunkStart + offset) > maxChunk) {\n this._device.queue.writeBuffer(buffer, dstByteOffset + offset, src.buffer, chunkStart + offset, maxChunk);\n offset += maxChunk;\n }\n this._device.queue.writeBuffer(buffer, dstByteOffset + offset, src.buffer, chunkStart + offset, byteLength - offset);\n }\n _getHalfFloatAsFloatRGBAArrayBuffer(dataLength, arrayBuffer, destArray) {\n if (!destArray) {\n destArray = new Float32Array(dataLength);\n }\n const srcData = new Uint16Array(arrayBuffer);\n while (dataLength--) {\n destArray[dataLength] = FromHalfFloat(srcData[dataLength]);\n }\n return destArray;\n }\n readDataFromBuffer(gpuBuffer, size, width, height, bytesPerRow, bytesPerRowAligned, type = 0, offset = 0, buffer = null, destroyBuffer = true, noDataConversion = false) {\n const floatFormat = type === 1 ? 2 : type === 2 ? 1 : 0;\n return new Promise((resolve, reject) => {\n gpuBuffer.mapAsync(WebGPUConstants.MapMode.Read, offset, size).then(() => {\n const copyArrayBuffer = gpuBuffer.getMappedRange(offset, size);\n let data = buffer;\n if (noDataConversion) {\n if (data === null) {\n data = allocateAndCopyTypedBuffer(type, size, true, copyArrayBuffer);\n }\n else {\n data = allocateAndCopyTypedBuffer(type, data.buffer, undefined, copyArrayBuffer);\n }\n }\n else {\n if (data === null) {\n switch (floatFormat) {\n case 0: // byte format\n data = new Uint8Array(size);\n data.set(new Uint8Array(copyArrayBuffer));\n break;\n case 1: // half float\n // TODO WEBGPU use computer shaders (or render pass) to make the conversion?\n data = this._getHalfFloatAsFloatRGBAArrayBuffer(size / 2, copyArrayBuffer);\n break;\n case 2: // float\n data = new Float32Array(size / 4);\n data.set(new Float32Array(copyArrayBuffer));\n break;\n }\n }\n else {\n switch (floatFormat) {\n case 0: // byte format\n data = new Uint8Array(data.buffer);\n data.set(new Uint8Array(copyArrayBuffer));\n break;\n case 1: // half float\n // TODO WEBGPU use computer shaders (or render pass) to make the conversion?\n data = this._getHalfFloatAsFloatRGBAArrayBuffer(size / 2, copyArrayBuffer, buffer);\n break;\n case 2: // float\n data = new Float32Array(data.buffer);\n data.set(new Float32Array(copyArrayBuffer));\n break;\n }\n }\n }\n if (bytesPerRow !== bytesPerRowAligned) {\n // TODO WEBGPU use computer shaders (or render pass) to build the final buffer data?\n if (floatFormat === 1 && !noDataConversion) {\n // half float have been converted to float above\n bytesPerRow *= 2;\n bytesPerRowAligned *= 2;\n }\n const data2 = new Uint8Array(data.buffer);\n let offset = bytesPerRow, offset2 = 0;\n for (let y = 1; y < height; ++y) {\n offset2 = y * bytesPerRowAligned;\n for (let x = 0; x < bytesPerRow; ++x) {\n data2[offset++] = data2[offset2++];\n }\n }\n if (floatFormat !== 0 && !noDataConversion) {\n data = new Float32Array(data2.buffer, 0, offset / 4);\n }\n else {\n data = new Uint8Array(data2.buffer, 0, offset);\n }\n }\n gpuBuffer.unmap();\n if (destroyBuffer) {\n this.releaseBuffer(gpuBuffer);\n }\n resolve(data);\n }, (reason) => reject(reason));\n });\n }\n releaseBuffer(buffer) {\n if (WebGPUBufferManager._IsGPUBuffer(buffer)) {\n this._deferredReleaseBuffers.push(buffer);\n return true;\n }\n buffer.references--;\n if (buffer.references === 0) {\n this._deferredReleaseBuffers.push(buffer.underlyingResource);\n return true;\n }\n return false;\n }\n destroyDeferredBuffers() {\n for (let i = 0; i < this._deferredReleaseBuffers.length; ++i) {\n this._deferredReleaseBuffers[i].destroy();\n }\n this._deferredReleaseBuffers.length = 0;\n }\n}\n//# sourceMappingURL=webgpuBufferManager.js.map","/** @internal */\nexport class WebGPURenderPassWrapper {\n constructor() {\n this.colorAttachmentGPUTextures = [];\n this.reset();\n }\n reset(fullReset = false) {\n this.renderPass = null;\n if (fullReset) {\n this.renderPassDescriptor = null;\n this.colorAttachmentViewDescriptor = null;\n this.depthAttachmentViewDescriptor = null;\n this.colorAttachmentGPUTextures = [];\n this.depthTextureFormat = undefined;\n }\n }\n}\n//# sourceMappingURL=webgpuRenderPassWrapper.js.map","import * as WebGPUConstants from \"./webgpuConstants.js\";\n\nconst filterToBits = [\n 0 | (0 << 1) | (0 << 2),\n 0 | (0 << 1) | (0 << 2),\n 1 | (1 << 1) | (0 << 2),\n 1 | (1 << 1) | (1 << 2),\n 0 | (0 << 1) | (0 << 2),\n 0 | (1 << 1) | (0 << 2),\n 0 | (1 << 1) | (1 << 2),\n 0 | (1 << 1) | (0 << 2),\n 0 | (0 << 1) | (1 << 2),\n 1 | (0 << 1) | (0 << 2),\n 1 | (0 << 1) | (1 << 2),\n 1 | (1 << 1) | (0 << 2),\n 1 | (0 << 1) | (0 << 2), // TEXTURE_LINEAR_NEAREST\n];\n// subtract 0x01FF from the comparison function value before indexing this array!\nconst comparisonFunctionToBits = [\n (0 << 3) | (0 << 4) | (0 << 5) | (0 << 6),\n (0 << 3) | (0 << 4) | (0 << 5) | (1 << 6),\n (0 << 3) | (0 << 4) | (1 << 5) | (0 << 6),\n (0 << 3) | (0 << 4) | (1 << 5) | (1 << 6),\n (0 << 3) | (1 << 4) | (0 << 5) | (0 << 6),\n (0 << 3) | (1 << 4) | (0 << 5) | (1 << 6),\n (0 << 3) | (1 << 4) | (1 << 5) | (0 << 6),\n (0 << 3) | (1 << 4) | (1 << 5) | (1 << 6),\n (1 << 3) | (0 << 4) | (0 << 5) | (0 << 6), // ALWAYS\n];\nconst filterNoMipToBits = [\n 0 << 7,\n 1 << 7,\n 1 << 7,\n 0 << 7,\n 0 << 7,\n 0 << 7,\n 0 << 7,\n 1 << 7,\n 0 << 7,\n 0 << 7,\n 0 << 7,\n 0 << 7,\n 1 << 7, // TEXTURE_LINEAR_NEAREST\n];\n/** @internal */\nexport class WebGPUCacheSampler {\n constructor(device) {\n this._samplers = {};\n this._device = device;\n this.disabled = false;\n }\n static GetSamplerHashCode(sampler) {\n var _a, _b, _c;\n // The WebGPU spec currently only allows values 1 and 4 for anisotropy\n const anisotropy = sampler._cachedAnisotropicFilteringLevel && sampler._cachedAnisotropicFilteringLevel > 1 ? 4 : 1;\n const code = filterToBits[sampler.samplingMode] +\n comparisonFunctionToBits[(sampler._comparisonFunction || 0x0202) - 0x0200 + 1] +\n filterNoMipToBits[sampler.samplingMode] + // handle the lodMinClamp = lodMaxClamp = 0 case when no filter used for mip mapping\n (((_a = sampler._cachedWrapU) !== null && _a !== void 0 ? _a : 1) << 8) +\n (((_b = sampler._cachedWrapV) !== null && _b !== void 0 ? _b : 1) << 10) +\n (((_c = sampler._cachedWrapR) !== null && _c !== void 0 ? _c : 1) << 12) +\n ((sampler.useMipMaps ? 1 : 0) << 14) + // need to factor this in because _getSamplerFilterDescriptor depends on samplingMode AND useMipMaps!\n (anisotropy << 15);\n return code;\n }\n static _GetSamplerFilterDescriptor(sampler, anisotropy) {\n let magFilter, minFilter, mipmapFilter, lodMinClamp, lodMaxClamp;\n const useMipMaps = sampler.useMipMaps;\n switch (sampler.samplingMode) {\n case 11:\n magFilter = WebGPUConstants.FilterMode.Linear;\n minFilter = WebGPUConstants.FilterMode.Linear;\n mipmapFilter = WebGPUConstants.FilterMode.Nearest;\n if (!useMipMaps) {\n lodMinClamp = lodMaxClamp = 0;\n }\n break;\n case 3:\n case 3:\n magFilter = WebGPUConstants.FilterMode.Linear;\n minFilter = WebGPUConstants.FilterMode.Linear;\n if (!useMipMaps) {\n mipmapFilter = WebGPUConstants.FilterMode.Nearest;\n lodMinClamp = lodMaxClamp = 0;\n }\n else {\n mipmapFilter = WebGPUConstants.FilterMode.Linear;\n }\n break;\n case 8:\n magFilter = WebGPUConstants.FilterMode.Nearest;\n minFilter = WebGPUConstants.FilterMode.Nearest;\n if (!useMipMaps) {\n mipmapFilter = WebGPUConstants.FilterMode.Nearest;\n lodMinClamp = lodMaxClamp = 0;\n }\n else {\n mipmapFilter = WebGPUConstants.FilterMode.Linear;\n }\n break;\n case 4:\n magFilter = WebGPUConstants.FilterMode.Nearest;\n minFilter = WebGPUConstants.FilterMode.Nearest;\n mipmapFilter = WebGPUConstants.FilterMode.Nearest;\n if (!useMipMaps) {\n lodMinClamp = lodMaxClamp = 0;\n }\n break;\n case 5:\n magFilter = WebGPUConstants.FilterMode.Nearest;\n minFilter = WebGPUConstants.FilterMode.Linear;\n mipmapFilter = WebGPUConstants.FilterMode.Nearest;\n if (!useMipMaps) {\n lodMinClamp = lodMaxClamp = 0;\n }\n break;\n case 6:\n magFilter = WebGPUConstants.FilterMode.Nearest;\n minFilter = WebGPUConstants.FilterMode.Linear;\n if (!useMipMaps) {\n mipmapFilter = WebGPUConstants.FilterMode.Nearest;\n lodMinClamp = lodMaxClamp = 0;\n }\n else {\n mipmapFilter = WebGPUConstants.FilterMode.Linear;\n }\n break;\n case 7:\n magFilter = WebGPUConstants.FilterMode.Nearest;\n minFilter = WebGPUConstants.FilterMode.Linear;\n mipmapFilter = WebGPUConstants.FilterMode.Nearest;\n lodMinClamp = lodMaxClamp = 0;\n break;\n case 1:\n case 1:\n magFilter = WebGPUConstants.FilterMode.Nearest;\n minFilter = WebGPUConstants.FilterMode.Nearest;\n mipmapFilter = WebGPUConstants.FilterMode.Nearest;\n lodMinClamp = lodMaxClamp = 0;\n break;\n case 9:\n magFilter = WebGPUConstants.FilterMode.Linear;\n minFilter = WebGPUConstants.FilterMode.Nearest;\n mipmapFilter = WebGPUConstants.FilterMode.Nearest;\n if (!useMipMaps) {\n lodMinClamp = lodMaxClamp = 0;\n }\n break;\n case 10:\n magFilter = WebGPUConstants.FilterMode.Linear;\n minFilter = WebGPUConstants.FilterMode.Nearest;\n if (!useMipMaps) {\n mipmapFilter = WebGPUConstants.FilterMode.Nearest;\n lodMinClamp = lodMaxClamp = 0;\n }\n else {\n mipmapFilter = WebGPUConstants.FilterMode.Linear;\n }\n break;\n case 2:\n case 2:\n magFilter = WebGPUConstants.FilterMode.Linear;\n minFilter = WebGPUConstants.FilterMode.Linear;\n mipmapFilter = WebGPUConstants.FilterMode.Nearest;\n lodMinClamp = lodMaxClamp = 0;\n break;\n case 12:\n magFilter = WebGPUConstants.FilterMode.Linear;\n minFilter = WebGPUConstants.FilterMode.Nearest;\n mipmapFilter = WebGPUConstants.FilterMode.Nearest;\n lodMinClamp = lodMaxClamp = 0;\n break;\n default:\n magFilter = WebGPUConstants.FilterMode.Nearest;\n minFilter = WebGPUConstants.FilterMode.Nearest;\n mipmapFilter = WebGPUConstants.FilterMode.Nearest;\n lodMinClamp = lodMaxClamp = 0;\n break;\n }\n if (anisotropy > 1 && (lodMinClamp !== 0 || lodMaxClamp !== 0)) {\n return {\n magFilter: WebGPUConstants.FilterMode.Linear,\n minFilter: WebGPUConstants.FilterMode.Linear,\n mipmapFilter: WebGPUConstants.FilterMode.Linear,\n anisotropyEnabled: true,\n };\n }\n return {\n magFilter,\n minFilter,\n mipmapFilter,\n lodMinClamp,\n lodMaxClamp,\n };\n }\n static _GetWrappingMode(mode) {\n switch (mode) {\n case 1:\n return WebGPUConstants.AddressMode.Repeat;\n case 0:\n return WebGPUConstants.AddressMode.ClampToEdge;\n case 2:\n return WebGPUConstants.AddressMode.MirrorRepeat;\n }\n return WebGPUConstants.AddressMode.Repeat;\n }\n static _GetSamplerWrappingDescriptor(sampler) {\n return {\n addressModeU: this._GetWrappingMode(sampler._cachedWrapU),\n addressModeV: this._GetWrappingMode(sampler._cachedWrapV),\n addressModeW: this._GetWrappingMode(sampler._cachedWrapR),\n };\n }\n static _GetSamplerDescriptor(sampler) {\n // The WebGPU spec currently only allows values 1 and 4 for anisotropy\n const anisotropy = sampler.useMipMaps && sampler._cachedAnisotropicFilteringLevel && sampler._cachedAnisotropicFilteringLevel > 1 ? 4 : 1;\n const filterDescriptor = this._GetSamplerFilterDescriptor(sampler, anisotropy);\n return Object.assign(Object.assign(Object.assign({}, filterDescriptor), this._GetSamplerWrappingDescriptor(sampler)), { compare: sampler._comparisonFunction ? WebGPUCacheSampler.GetCompareFunction(sampler._comparisonFunction) : undefined, maxAnisotropy: filterDescriptor.anisotropyEnabled ? anisotropy : 1 });\n }\n static GetCompareFunction(compareFunction) {\n switch (compareFunction) {\n case 519:\n return WebGPUConstants.CompareFunction.Always;\n case 514:\n return WebGPUConstants.CompareFunction.Equal;\n case 516:\n return WebGPUConstants.CompareFunction.Greater;\n case 518:\n return WebGPUConstants.CompareFunction.GreaterEqual;\n case 513:\n return WebGPUConstants.CompareFunction.Less;\n case 515:\n return WebGPUConstants.CompareFunction.LessEqual;\n case 512:\n return WebGPUConstants.CompareFunction.Never;\n case 517:\n return WebGPUConstants.CompareFunction.NotEqual;\n default:\n return WebGPUConstants.CompareFunction.Less;\n }\n }\n getSampler(sampler, bypassCache = false, hash = 0) {\n if (this.disabled) {\n return this._device.createSampler(WebGPUCacheSampler._GetSamplerDescriptor(sampler));\n }\n if (bypassCache) {\n hash = 0;\n }\n else if (hash === 0) {\n hash = WebGPUCacheSampler.GetSamplerHashCode(sampler);\n }\n let gpuSampler = bypassCache ? undefined : this._samplers[hash];\n if (!gpuSampler) {\n gpuSampler = this._device.createSampler(WebGPUCacheSampler._GetSamplerDescriptor(sampler));\n if (!bypassCache) {\n this._samplers[hash] = gpuSampler;\n }\n }\n return gpuSampler;\n }\n}\n//# sourceMappingURL=webgpuCacheSampler.js.map","/* eslint-disable @typescript-eslint/naming-convention */\n\nimport * as WebGPUConstants from \"./webgpuConstants.js\";\nimport { VertexBuffer } from \"../../Buffers/buffer.js\";\nimport { WebGPUShaderProcessor } from \"./webgpuShaderProcessor.js\";\nimport { renderableTextureFormatToIndex, WebGPUTextureHelper } from \"./webgpuTextureHelper.js\";\nvar StatePosition;\n(function (StatePosition) {\n StatePosition[StatePosition[\"StencilReadMask\"] = 0] = \"StencilReadMask\";\n StatePosition[StatePosition[\"StencilWriteMask\"] = 1] = \"StencilWriteMask\";\n //DepthBiasClamp = 1, // not used, so remove it to improve perf\n StatePosition[StatePosition[\"DepthBias\"] = 2] = \"DepthBias\";\n StatePosition[StatePosition[\"DepthBiasSlopeScale\"] = 3] = \"DepthBiasSlopeScale\";\n StatePosition[StatePosition[\"DepthStencilState\"] = 4] = \"DepthStencilState\";\n StatePosition[StatePosition[\"MRTAttachments1\"] = 5] = \"MRTAttachments1\";\n StatePosition[StatePosition[\"MRTAttachments2\"] = 6] = \"MRTAttachments2\";\n StatePosition[StatePosition[\"RasterizationState\"] = 7] = \"RasterizationState\";\n StatePosition[StatePosition[\"ColorStates\"] = 8] = \"ColorStates\";\n StatePosition[StatePosition[\"ShaderStage\"] = 9] = \"ShaderStage\";\n StatePosition[StatePosition[\"TextureStage\"] = 10] = \"TextureStage\";\n StatePosition[StatePosition[\"VertexState\"] = 11] = \"VertexState\";\n StatePosition[StatePosition[\"NumStates\"] = 12] = \"NumStates\";\n})(StatePosition || (StatePosition = {}));\nconst alphaBlendFactorToIndex = {\n 0: 1,\n 1: 2,\n 0x0300: 3,\n 0x0301: 4,\n 0x0302: 5,\n 0x0303: 6,\n 0x0304: 7,\n 0x0305: 8,\n 0x0306: 9,\n 0x0307: 10,\n 0x0308: 11,\n 0x8001: 12,\n 0x8002: 13,\n 0x8003: 12,\n 0x8004: 13, // OneMinusBlendColor (alpha)\n};\nconst stencilOpToIndex = {\n 0x0000: 0,\n 0x1e00: 1,\n 0x1e01: 2,\n 0x1e02: 3,\n 0x1e03: 4,\n 0x150a: 5,\n 0x8507: 6,\n 0x8508: 7, // DECR_WRAP\n};\n/** @internal */\nexport class WebGPUCacheRenderPipeline {\n constructor(device, emptyVertexBuffer, useTextureStage) {\n this.mrtTextureCount = 0;\n this._device = device;\n this._useTextureStage = useTextureStage;\n this._states = new Array(30); // pre-allocate enough room so that no new allocation will take place afterwards\n this._statesLength = 0;\n this._stateDirtyLowestIndex = 0;\n this._emptyVertexBuffer = emptyVertexBuffer;\n this._mrtFormats = [];\n this._parameter = { token: undefined, pipeline: null };\n this.disabled = false;\n this.vertexBuffers = [];\n this._kMaxVertexBufferStride = device.limits.maxVertexBufferArrayStride || 2048;\n this.reset();\n }\n reset() {\n this._isDirty = true;\n this.vertexBuffers.length = 0;\n this.setAlphaToCoverage(false);\n this.resetDepthCullingState();\n this.setClampDepth(false);\n this.setDepthBias(0);\n //this.setDepthBiasClamp(0);\n this._webgpuColorFormat = [WebGPUConstants.TextureFormat.BGRA8Unorm];\n this.setColorFormat(WebGPUConstants.TextureFormat.BGRA8Unorm);\n this.setMRT([]);\n this.setAlphaBlendEnabled(false);\n this.setAlphaBlendFactors([null, null, null, null], [null, null]);\n this.setWriteMask(0xf);\n this.setDepthStencilFormat(WebGPUConstants.TextureFormat.Depth24PlusStencil8);\n this.setStencilEnabled(false);\n this.resetStencilState();\n this.setBuffers(null, null, null);\n this._setTextureState(0);\n }\n get colorFormats() {\n return this._mrtAttachments1 > 0 ? this._mrtFormats : this._webgpuColorFormat;\n }\n getRenderPipeline(fillMode, effect, sampleCount, textureState = 0) {\n if (sampleCount > 1) {\n // WebGPU only supports 1 or 4\n sampleCount = 4;\n }\n if (this.disabled) {\n const topology = WebGPUCacheRenderPipeline._GetTopology(fillMode);\n this._setVertexState(effect); // to fill this.vertexBuffers with correct data\n this._setTextureState(textureState);\n this._parameter.pipeline = this._createRenderPipeline(effect, topology, sampleCount);\n WebGPUCacheRenderPipeline.NumCacheMiss++;\n WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame++;\n return this._parameter.pipeline;\n }\n this._setShaderStage(effect.uniqueId);\n this._setRasterizationState(fillMode, sampleCount);\n this._setColorStates();\n this._setDepthStencilState();\n this._setVertexState(effect);\n this._setTextureState(textureState);\n this.lastStateDirtyLowestIndex = this._stateDirtyLowestIndex;\n if (!this._isDirty && this._parameter.pipeline) {\n this._stateDirtyLowestIndex = this._statesLength;\n WebGPUCacheRenderPipeline.NumCacheHitWithoutHash++;\n return this._parameter.pipeline;\n }\n this._getRenderPipeline(this._parameter);\n this._isDirty = false;\n this._stateDirtyLowestIndex = this._statesLength;\n if (this._parameter.pipeline) {\n WebGPUCacheRenderPipeline.NumCacheHitWithHash++;\n return this._parameter.pipeline;\n }\n const topology = WebGPUCacheRenderPipeline._GetTopology(fillMode);\n this._parameter.pipeline = this._createRenderPipeline(effect, topology, sampleCount);\n this._setRenderPipeline(this._parameter);\n WebGPUCacheRenderPipeline.NumCacheMiss++;\n WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame++;\n return this._parameter.pipeline;\n }\n endFrame() {\n WebGPUCacheRenderPipeline.NumPipelineCreationLastFrame = WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame;\n WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame = 0;\n }\n setAlphaToCoverage(enabled) {\n this._alphaToCoverageEnabled = enabled;\n }\n setFrontFace(frontFace) {\n this._frontFace = frontFace;\n }\n setCullEnabled(enabled) {\n this._cullEnabled = enabled;\n }\n setCullFace(cullFace) {\n this._cullFace = cullFace;\n }\n setClampDepth(clampDepth) {\n this._clampDepth = clampDepth;\n }\n resetDepthCullingState() {\n this.setDepthCullingState(false, 2, 1, 0, 0, true, true, 519);\n }\n setDepthCullingState(cullEnabled, frontFace, cullFace, zOffset, zOffsetUnits, depthTestEnabled, depthWriteEnabled, depthCompare) {\n this._depthWriteEnabled = depthWriteEnabled;\n this._depthTestEnabled = depthTestEnabled;\n this._depthCompare = (depthCompare !== null && depthCompare !== void 0 ? depthCompare : 519) - 0x0200;\n this._cullFace = cullFace;\n this._cullEnabled = cullEnabled;\n this._frontFace = frontFace;\n this.setDepthBiasSlopeScale(zOffset);\n this.setDepthBias(zOffsetUnits);\n }\n setDepthBias(depthBias) {\n if (this._depthBias !== depthBias) {\n this._depthBias = depthBias;\n this._states[StatePosition.DepthBias] = depthBias;\n this._isDirty = true;\n this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.DepthBias);\n }\n }\n /*public setDepthBiasClamp(depthBiasClamp: number): void {\n if (this._depthBiasClamp !== depthBiasClamp) {\n this._depthBiasClamp = depthBiasClamp;\n this._states[StatePosition.DepthBiasClamp] = depthBiasClamp.toString();\n this._isDirty = true;\n }\n }*/\n setDepthBiasSlopeScale(depthBiasSlopeScale) {\n if (this._depthBiasSlopeScale !== depthBiasSlopeScale) {\n this._depthBiasSlopeScale = depthBiasSlopeScale;\n this._states[StatePosition.DepthBiasSlopeScale] = depthBiasSlopeScale;\n this._isDirty = true;\n this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.DepthBiasSlopeScale);\n }\n }\n setColorFormat(format) {\n this._webgpuColorFormat[0] = format;\n this._colorFormat = renderableTextureFormatToIndex[format !== null && format !== void 0 ? format : \"\"];\n }\n setMRTAttachments(attachments) {\n this.mrtAttachments = attachments;\n let mask = 0;\n for (let i = 0; i < attachments.length; ++i) {\n if (attachments[i] !== 0) {\n mask += 1 << i;\n }\n }\n if (this._mrtEnabledMask !== mask) {\n this._mrtEnabledMask = mask;\n this._isDirty = true;\n this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.MRTAttachments1);\n }\n }\n setMRT(textureArray, textureCount) {\n var _a, _b;\n textureCount = textureCount !== null && textureCount !== void 0 ? textureCount : textureArray.length;\n if (textureCount > 10) {\n // If we want more than 10 attachments we need to change this method (and the StatePosition enum) but 10 seems plenty: note that WebGPU only supports 8 at the time (2021/12/13)!\n // As we need 39 different values we are using 6 bits to encode a texture format, meaning we can encode 5 texture formats in 32 bits\n // We are using 2x32 bit values to handle 10 textures\n throw \"Can't handle more than 10 attachments for a MRT in cache render pipeline!\";\n }\n this.mrtTextureArray = textureArray;\n this.mrtTextureCount = textureCount;\n this._mrtEnabledMask = 0xffff; // all textures are enabled at start (meaning we can write to them). Calls to setMRTAttachments may disable some\n const bits = [0, 0];\n let indexBits = 0, mask = 0, numRT = 0;\n for (let i = 0; i < textureCount; ++i) {\n const texture = textureArray[i];\n const gpuWrapper = texture === null || texture === void 0 ? void 0 : texture._hardwareTexture;\n this._mrtFormats[numRT] = (_a = gpuWrapper === null || gpuWrapper === void 0 ? void 0 : gpuWrapper.format) !== null && _a !== void 0 ? _a : this._webgpuColorFormat[0];\n bits[indexBits] += renderableTextureFormatToIndex[(_b = this._mrtFormats[numRT]) !== null && _b !== void 0 ? _b : \"\"] << mask;\n mask += 6;\n numRT++;\n if (mask >= 32) {\n mask = 0;\n indexBits++;\n }\n }\n this._mrtFormats.length = numRT;\n if (this._mrtAttachments1 !== bits[0] || this._mrtAttachments2 !== bits[1]) {\n this._mrtAttachments1 = bits[0];\n this._mrtAttachments2 = bits[1];\n this._states[StatePosition.MRTAttachments1] = bits[0];\n this._states[StatePosition.MRTAttachments2] = bits[1];\n this._isDirty = true;\n this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.MRTAttachments1);\n }\n }\n setAlphaBlendEnabled(enabled) {\n this._alphaBlendEnabled = enabled;\n }\n setAlphaBlendFactors(factors, operations) {\n this._alphaBlendFuncParams = factors;\n this._alphaBlendEqParams = operations;\n }\n setWriteMask(mask) {\n this._writeMask = mask;\n }\n setDepthStencilFormat(format) {\n this._webgpuDepthStencilFormat = format;\n this._depthStencilFormat = format === undefined ? 0 : renderableTextureFormatToIndex[format];\n }\n setDepthTestEnabled(enabled) {\n this._depthTestEnabled = enabled;\n }\n setDepthWriteEnabled(enabled) {\n this._depthWriteEnabled = enabled;\n }\n setDepthCompare(func) {\n this._depthCompare = (func !== null && func !== void 0 ? func : 519) - 0x0200;\n }\n setStencilEnabled(enabled) {\n this._stencilEnabled = enabled;\n }\n setStencilCompare(func) {\n this._stencilFrontCompare = (func !== null && func !== void 0 ? func : 519) - 0x0200;\n }\n setStencilDepthFailOp(op) {\n this._stencilFrontDepthFailOp = op === null ? 1 /* KEEP */ : stencilOpToIndex[op];\n }\n setStencilPassOp(op) {\n this._stencilFrontPassOp = op === null ? 2 /* REPLACE */ : stencilOpToIndex[op];\n }\n setStencilFailOp(op) {\n this._stencilFrontFailOp = op === null ? 1 /* KEEP */ : stencilOpToIndex[op];\n }\n setStencilReadMask(mask) {\n if (this._stencilReadMask !== mask) {\n this._stencilReadMask = mask;\n this._states[StatePosition.StencilReadMask] = mask;\n this._isDirty = true;\n this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.StencilReadMask);\n }\n }\n setStencilWriteMask(mask) {\n if (this._stencilWriteMask !== mask) {\n this._stencilWriteMask = mask;\n this._states[StatePosition.StencilWriteMask] = mask;\n this._isDirty = true;\n this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.StencilWriteMask);\n }\n }\n resetStencilState() {\n this.setStencilState(false, 519, 7680, 7681, 7680, 0xff, 0xff);\n }\n setStencilState(stencilEnabled, compare, depthFailOp, passOp, failOp, readMask, writeMask) {\n this._stencilEnabled = stencilEnabled;\n this._stencilFrontCompare = (compare !== null && compare !== void 0 ? compare : 519) - 0x0200;\n this._stencilFrontDepthFailOp = depthFailOp === null ? 1 /* KEEP */ : stencilOpToIndex[depthFailOp];\n this._stencilFrontPassOp = passOp === null ? 2 /* REPLACE */ : stencilOpToIndex[passOp];\n this._stencilFrontFailOp = failOp === null ? 1 /* KEEP */ : stencilOpToIndex[failOp];\n this.setStencilReadMask(readMask);\n this.setStencilWriteMask(writeMask);\n }\n setBuffers(vertexBuffers, indexBuffer, overrideVertexBuffers) {\n this._vertexBuffers = vertexBuffers;\n this._overrideVertexBuffers = overrideVertexBuffers;\n this._indexBuffer = indexBuffer;\n }\n static _GetTopology(fillMode) {\n switch (fillMode) {\n // Triangle views\n case 0:\n return WebGPUConstants.PrimitiveTopology.TriangleList;\n case 2:\n return WebGPUConstants.PrimitiveTopology.PointList;\n case 1:\n return WebGPUConstants.PrimitiveTopology.LineList;\n // Draw modes\n case 3:\n return WebGPUConstants.PrimitiveTopology.PointList;\n case 4:\n return WebGPUConstants.PrimitiveTopology.LineList;\n case 5:\n // return this._gl.LINE_LOOP;\n // TODO WEBGPU. Line Loop Mode Fallback at buffer load time.\n throw \"LineLoop is an unsupported fillmode in WebGPU\";\n case 6:\n return WebGPUConstants.PrimitiveTopology.LineStrip;\n case 7:\n return WebGPUConstants.PrimitiveTopology.TriangleStrip;\n case 8:\n // return this._gl.TRIANGLE_FAN;\n // TODO WEBGPU. Triangle Fan Mode Fallback at buffer load time.\n throw \"TriangleFan is an unsupported fillmode in WebGPU\";\n default:\n return WebGPUConstants.PrimitiveTopology.TriangleList;\n }\n }\n static _GetAphaBlendOperation(operation) {\n switch (operation) {\n case 32774:\n return WebGPUConstants.BlendOperation.Add;\n case 32778:\n return WebGPUConstants.BlendOperation.Subtract;\n case 32779:\n return WebGPUConstants.BlendOperation.ReverseSubtract;\n case 32775:\n return WebGPUConstants.BlendOperation.Min;\n case 32776:\n return WebGPUConstants.BlendOperation.Max;\n default:\n return WebGPUConstants.BlendOperation.Add;\n }\n }\n static _GetAphaBlendFactor(factor) {\n switch (factor) {\n case 0:\n return WebGPUConstants.BlendFactor.Zero;\n case 1:\n return WebGPUConstants.BlendFactor.One;\n case 768:\n return WebGPUConstants.BlendFactor.Src;\n case 769:\n return WebGPUConstants.BlendFactor.OneMinusSrc;\n case 770:\n return WebGPUConstants.BlendFactor.SrcAlpha;\n case 771:\n return WebGPUConstants.BlendFactor.OneMinusSrcAlpha;\n case 772:\n return WebGPUConstants.BlendFactor.DstAlpha;\n case 773:\n return WebGPUConstants.BlendFactor.OneMinusDstAlpha;\n case 774:\n return WebGPUConstants.BlendFactor.Dst;\n case 775:\n return WebGPUConstants.BlendFactor.OneMinusDst;\n case 776:\n return WebGPUConstants.BlendFactor.SrcAlphaSaturated;\n case 32769:\n return WebGPUConstants.BlendFactor.Constant;\n case 32770:\n return WebGPUConstants.BlendFactor.OneMinusConstant;\n case 32771:\n return WebGPUConstants.BlendFactor.Constant;\n case 32772:\n return WebGPUConstants.BlendFactor.OneMinusConstant;\n default:\n return WebGPUConstants.BlendFactor.One;\n }\n }\n static _GetCompareFunction(compareFunction) {\n switch (compareFunction) {\n case 0: // NEVER\n return WebGPUConstants.CompareFunction.Never;\n case 1: // LESS\n return WebGPUConstants.CompareFunction.Less;\n case 2: // EQUAL\n return WebGPUConstants.CompareFunction.Equal;\n case 3: // LEQUAL\n return WebGPUConstants.CompareFunction.LessEqual;\n case 4: // GREATER\n return WebGPUConstants.CompareFunction.Greater;\n case 5: // NOTEQUAL\n return WebGPUConstants.CompareFunction.NotEqual;\n case 6: // GEQUAL\n return WebGPUConstants.CompareFunction.GreaterEqual;\n case 7: // ALWAYS\n return WebGPUConstants.CompareFunction.Always;\n }\n return WebGPUConstants.CompareFunction.Never;\n }\n static _GetStencilOpFunction(operation) {\n switch (operation) {\n case 0:\n return WebGPUConstants.StencilOperation.Zero;\n case 1:\n return WebGPUConstants.StencilOperation.Keep;\n case 2:\n return WebGPUConstants.StencilOperation.Replace;\n case 3:\n return WebGPUConstants.StencilOperation.IncrementClamp;\n case 4:\n return WebGPUConstants.StencilOperation.DecrementClamp;\n case 5:\n return WebGPUConstants.StencilOperation.Invert;\n case 6:\n return WebGPUConstants.StencilOperation.IncrementWrap;\n case 7:\n return WebGPUConstants.StencilOperation.DecrementWrap;\n }\n return WebGPUConstants.StencilOperation.Keep;\n }\n static _GetVertexInputDescriptorFormat(vertexBuffer) {\n const type = vertexBuffer.type;\n const normalized = vertexBuffer.normalized;\n const size = vertexBuffer.getSize();\n switch (type) {\n case VertexBuffer.BYTE:\n switch (size) {\n case 1:\n case 2:\n return normalized ? WebGPUConstants.VertexFormat.Snorm8x2 : WebGPUConstants.VertexFormat.Sint8x2;\n case 3:\n case 4:\n return normalized ? WebGPUConstants.VertexFormat.Snorm8x4 : WebGPUConstants.VertexFormat.Sint8x4;\n }\n break;\n case VertexBuffer.UNSIGNED_BYTE:\n switch (size) {\n case 1:\n case 2:\n return normalized ? WebGPUConstants.VertexFormat.Unorm8x2 : WebGPUConstants.VertexFormat.Uint8x2;\n case 3:\n case 4:\n return normalized ? WebGPUConstants.VertexFormat.Unorm8x4 : WebGPUConstants.VertexFormat.Uint8x4;\n }\n break;\n case VertexBuffer.SHORT:\n switch (size) {\n case 1:\n case 2:\n return normalized ? WebGPUConstants.VertexFormat.Snorm16x2 : WebGPUConstants.VertexFormat.Sint16x2;\n case 3:\n case 4:\n return normalized ? WebGPUConstants.VertexFormat.Snorm16x4 : WebGPUConstants.VertexFormat.Sint16x4;\n }\n break;\n case VertexBuffer.UNSIGNED_SHORT:\n switch (size) {\n case 1:\n case 2:\n return normalized ? WebGPUConstants.VertexFormat.Unorm16x2 : WebGPUConstants.VertexFormat.Uint16x2;\n case 3:\n case 4:\n return normalized ? WebGPUConstants.VertexFormat.Unorm16x4 : WebGPUConstants.VertexFormat.Uint16x4;\n }\n break;\n case VertexBuffer.INT:\n switch (size) {\n case 1:\n return WebGPUConstants.VertexFormat.Sint32;\n case 2:\n return WebGPUConstants.VertexFormat.Sint32x2;\n case 3:\n return WebGPUConstants.VertexFormat.Sint32x3;\n case 4:\n return WebGPUConstants.VertexFormat.Sint32x4;\n }\n break;\n case VertexBuffer.UNSIGNED_INT:\n switch (size) {\n case 1:\n return WebGPUConstants.VertexFormat.Uint32;\n case 2:\n return WebGPUConstants.VertexFormat.Uint32x2;\n case 3:\n return WebGPUConstants.VertexFormat.Uint32x3;\n case 4:\n return WebGPUConstants.VertexFormat.Uint32x4;\n }\n break;\n case VertexBuffer.FLOAT:\n switch (size) {\n case 1:\n return WebGPUConstants.VertexFormat.Float32;\n case 2:\n return WebGPUConstants.VertexFormat.Float32x2;\n case 3:\n return WebGPUConstants.VertexFormat.Float32x3;\n case 4:\n return WebGPUConstants.VertexFormat.Float32x4;\n }\n break;\n }\n throw new Error(`Invalid Format '${vertexBuffer.getKind()}' - type=${type}, normalized=${normalized}, size=${size}`);\n }\n _getAphaBlendState() {\n if (!this._alphaBlendEnabled) {\n return null;\n }\n return {\n srcFactor: WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),\n dstFactor: WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),\n operation: WebGPUCacheRenderPipeline._GetAphaBlendOperation(this._alphaBlendEqParams[1]),\n };\n }\n _getColorBlendState() {\n if (!this._alphaBlendEnabled) {\n return null;\n }\n return {\n srcFactor: WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),\n dstFactor: WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),\n operation: WebGPUCacheRenderPipeline._GetAphaBlendOperation(this._alphaBlendEqParams[0]),\n };\n }\n _setShaderStage(id) {\n if (this._shaderId !== id) {\n this._shaderId = id;\n this._states[StatePosition.ShaderStage] = id;\n this._isDirty = true;\n this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.ShaderStage);\n }\n }\n _setRasterizationState(topology, sampleCount) {\n const frontFace = this._frontFace;\n const cullMode = this._cullEnabled ? this._cullFace : 0;\n const clampDepth = this._clampDepth ? 1 : 0;\n const alphaToCoverage = this._alphaToCoverageEnabled ? 1 : 0;\n const rasterizationState = frontFace - 1 + (cullMode << 1) + (clampDepth << 3) + (alphaToCoverage << 4) + (topology << 5) + (sampleCount << 8);\n if (this._rasterizationState !== rasterizationState) {\n this._rasterizationState = rasterizationState;\n this._states[StatePosition.RasterizationState] = this._rasterizationState;\n this._isDirty = true;\n this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.RasterizationState);\n }\n }\n _setColorStates() {\n let colorStates = ((this._writeMask ? 1 : 0) << 22) + (this._colorFormat << 23) + ((this._depthWriteEnabled ? 1 : 0) << 29); // this state has been moved from depthStencilState here because alpha and depth are related (generally when alpha is on, depth write is off and the other way around)\n if (this._alphaBlendEnabled) {\n colorStates +=\n ((this._alphaBlendFuncParams[0] === null ? 2 : alphaBlendFactorToIndex[this._alphaBlendFuncParams[0]]) << 0) +\n ((this._alphaBlendFuncParams[1] === null ? 2 : alphaBlendFactorToIndex[this._alphaBlendFuncParams[1]]) << 4) +\n ((this._alphaBlendFuncParams[2] === null ? 2 : alphaBlendFactorToIndex[this._alphaBlendFuncParams[2]]) << 8) +\n ((this._alphaBlendFuncParams[3] === null ? 2 : alphaBlendFactorToIndex[this._alphaBlendFuncParams[3]]) << 12) +\n ((this._alphaBlendEqParams[0] === null ? 1 : this._alphaBlendEqParams[0] - 0x8005) << 16) +\n ((this._alphaBlendEqParams[1] === null ? 1 : this._alphaBlendEqParams[1] - 0x8005) << 19);\n }\n if (colorStates !== this._colorStates) {\n this._colorStates = colorStates;\n this._states[StatePosition.ColorStates] = this._colorStates;\n this._isDirty = true;\n this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.ColorStates);\n }\n }\n _setDepthStencilState() {\n const stencilState = !this._stencilEnabled\n ? 7 /* ALWAYS */ + (1 /* KEEP */ << 3) + (1 /* KEEP */ << 6) + (1 /* KEEP */ << 9)\n : this._stencilFrontCompare + (this._stencilFrontDepthFailOp << 3) + (this._stencilFrontPassOp << 6) + (this._stencilFrontFailOp << 9);\n const depthStencilState = this._depthStencilFormat + ((this._depthTestEnabled ? this._depthCompare : 7) /* ALWAYS */ << 6) + (stencilState << 10); // stencil front - stencil back is the same\n if (this._depthStencilState !== depthStencilState) {\n this._depthStencilState = depthStencilState;\n this._states[StatePosition.DepthStencilState] = this._depthStencilState;\n this._isDirty = true;\n this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.DepthStencilState);\n }\n }\n _setVertexState(effect) {\n var _a, _b;\n const currStateLen = this._statesLength;\n let newNumStates = StatePosition.VertexState;\n const webgpuPipelineContext = effect._pipelineContext;\n const attributes = webgpuPipelineContext.shaderProcessingContext.attributeNamesFromEffect;\n const locations = webgpuPipelineContext.shaderProcessingContext.attributeLocationsFromEffect;\n let currentGPUBuffer;\n let numVertexBuffers = 0;\n for (let index = 0; index < attributes.length; index++) {\n const location = locations[index];\n let vertexBuffer = (_a = (this._overrideVertexBuffers && this._overrideVertexBuffers[attributes[index]])) !== null && _a !== void 0 ? _a : this._vertexBuffers[attributes[index]];\n if (!vertexBuffer) {\n // In WebGL it's valid to not bind a vertex buffer to an attribute, but it's not valid in WebGPU\n // So we must bind a dummy buffer when we are not given one for a specific attribute\n vertexBuffer = this._emptyVertexBuffer;\n }\n const buffer = (_b = vertexBuffer.getBuffer()) === null || _b === void 0 ? void 0 : _b.underlyingResource;\n // We optimize usage of GPUVertexBufferLayout: we will create a single GPUVertexBufferLayout for all the attributes which follow each other and which use the same GPU buffer\n // However, there are some constraints in the attribute.offset value range, so we must check for them before being able to reuse the same GPUVertexBufferLayout\n // See _getVertexInputDescriptor() below\n if (vertexBuffer._validOffsetRange === undefined) {\n const offset = vertexBuffer.byteOffset;\n const formatSize = vertexBuffer.getSize(true);\n const byteStride = vertexBuffer.byteStride;\n vertexBuffer._validOffsetRange = offset <= this._kMaxVertexBufferStride - formatSize && (byteStride === 0 || offset + formatSize <= byteStride);\n }\n if (!(currentGPUBuffer && currentGPUBuffer === buffer && vertexBuffer._validOffsetRange)) {\n // we can't combine the previous vertexBuffer with the current one\n this.vertexBuffers[numVertexBuffers++] = vertexBuffer;\n currentGPUBuffer = vertexBuffer._validOffsetRange ? buffer : null;\n }\n const vid = vertexBuffer.hashCode + (location << 7);\n this._isDirty = this._isDirty || this._states[newNumStates] !== vid;\n this._states[newNumStates++] = vid;\n }\n this.vertexBuffers.length = numVertexBuffers;\n this._statesLength = newNumStates;\n this._isDirty = this._isDirty || newNumStates !== currStateLen;\n if (this._isDirty) {\n this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.VertexState);\n }\n }\n _setTextureState(textureState) {\n if (this._textureState !== textureState) {\n this._textureState = textureState;\n this._states[StatePosition.TextureStage] = this._textureState;\n this._isDirty = true;\n this._stateDirtyLowestIndex = Math.min(this._stateDirtyLowestIndex, StatePosition.TextureStage);\n }\n }\n _createPipelineLayout(webgpuPipelineContext) {\n if (this._useTextureStage) {\n return this._createPipelineLayoutWithTextureStage(webgpuPipelineContext);\n }\n const bindGroupLayouts = [];\n const bindGroupLayoutEntries = webgpuPipelineContext.shaderProcessingContext.bindGroupLayoutEntries;\n for (let i = 0; i < bindGroupLayoutEntries.length; i++) {\n const setDefinition = bindGroupLayoutEntries[i];\n bindGroupLayouts[i] = this._device.createBindGroupLayout({\n entries: setDefinition,\n });\n }\n webgpuPipelineContext.bindGroupLayouts[0] = bindGroupLayouts;\n return this._device.createPipelineLayout({ bindGroupLayouts });\n }\n _createPipelineLayoutWithTextureStage(webgpuPipelineContext) {\n var _a;\n const shaderProcessingContext = webgpuPipelineContext.shaderProcessingContext;\n const bindGroupLayoutEntries = shaderProcessingContext.bindGroupLayoutEntries;\n let bitVal = 1;\n for (let i = 0; i < bindGroupLayoutEntries.length; i++) {\n const setDefinition = bindGroupLayoutEntries[i];\n for (let j = 0; j < setDefinition.length; j++) {\n const entry = bindGroupLayoutEntries[i][j];\n if (entry.texture) {\n const name = shaderProcessingContext.bindGroupLayoutEntryInfo[i][entry.binding].name;\n const textureInfo = shaderProcessingContext.availableTextures[name];\n const samplerInfo = textureInfo.autoBindSampler ? shaderProcessingContext.availableSamplers[name + WebGPUShaderProcessor.AutoSamplerSuffix] : null;\n let sampleType = textureInfo.sampleType;\n let samplerType = (_a = samplerInfo === null || samplerInfo === void 0 ? void 0 : samplerInfo.type) !== null && _a !== void 0 ? _a : WebGPUConstants.SamplerBindingType.Filtering;\n if (this._textureState & bitVal && sampleType !== WebGPUConstants.TextureSampleType.Depth) {\n // The texture is a 32 bits float texture but the system does not support linear filtering for them:\n // we set the sampler to \"non-filtering\" and the texture sample type to \"unfilterable-float\"\n if (textureInfo.autoBindSampler) {\n samplerType = WebGPUConstants.SamplerBindingType.NonFiltering;\n }\n sampleType = WebGPUConstants.TextureSampleType.UnfilterableFloat;\n }\n entry.texture.sampleType = sampleType;\n if (samplerInfo) {\n const binding = shaderProcessingContext.bindGroupLayoutEntryInfo[samplerInfo.binding.groupIndex][samplerInfo.binding.bindingIndex].index;\n bindGroupLayoutEntries[samplerInfo.binding.groupIndex][binding].sampler.type = samplerType;\n }\n bitVal = bitVal << 1;\n }\n }\n }\n const bindGroupLayouts = [];\n for (let i = 0; i < bindGroupLayoutEntries.length; ++i) {\n bindGroupLayouts[i] = this._device.createBindGroupLayout({\n entries: bindGroupLayoutEntries[i],\n });\n }\n webgpuPipelineContext.bindGroupLayouts[this._textureState] = bindGroupLayouts;\n return this._device.createPipelineLayout({ bindGroupLayouts });\n }\n _getVertexInputDescriptor(effect) {\n var _a, _b;\n const descriptors = [];\n const webgpuPipelineContext = effect._pipelineContext;\n const attributes = webgpuPipelineContext.shaderProcessingContext.attributeNamesFromEffect;\n const locations = webgpuPipelineContext.shaderProcessingContext.attributeLocationsFromEffect;\n let currentGPUBuffer;\n let currentGPUAttributes;\n for (let index = 0; index < attributes.length; index++) {\n const location = locations[index];\n let vertexBuffer = (_a = (this._overrideVertexBuffers && this._overrideVertexBuffers[attributes[index]])) !== null && _a !== void 0 ? _a : this._vertexBuffers[attributes[index]];\n if (!vertexBuffer) {\n // In WebGL it's valid to not bind a vertex buffer to an attribute, but it's not valid in WebGPU\n // So we must bind a dummy buffer when we are not given one for a specific attribute\n vertexBuffer = this._emptyVertexBuffer;\n }\n let buffer = (_b = vertexBuffer.getBuffer()) === null || _b === void 0 ? void 0 : _b.underlyingResource;\n // We reuse the same GPUVertexBufferLayout for all attributes that use the same underlying GPU buffer (and for attributes that follow each other in the attributes array)\n let offset = vertexBuffer.byteOffset;\n const invalidOffsetRange = !vertexBuffer._validOffsetRange;\n if (!(currentGPUBuffer && currentGPUAttributes && currentGPUBuffer === buffer) || invalidOffsetRange) {\n const vertexBufferDescriptor = {\n arrayStride: vertexBuffer.byteStride,\n stepMode: vertexBuffer.getIsInstanced() ? WebGPUConstants.InputStepMode.Instance : WebGPUConstants.InputStepMode.Vertex,\n attributes: [],\n };\n descriptors.push(vertexBufferDescriptor);\n currentGPUAttributes = vertexBufferDescriptor.attributes;\n if (invalidOffsetRange) {\n offset = 0; // the offset will be set directly in the setVertexBuffer call\n buffer = null; // buffer can't be reused\n }\n }\n currentGPUAttributes.push({\n shaderLocation: location,\n offset,\n format: WebGPUCacheRenderPipeline._GetVertexInputDescriptorFormat(vertexBuffer),\n });\n currentGPUBuffer = buffer;\n }\n return descriptors;\n }\n _createRenderPipeline(effect, topology, sampleCount) {\n var _a, _b, _c;\n const webgpuPipelineContext = effect._pipelineContext;\n const inputStateDescriptor = this._getVertexInputDescriptor(effect);\n const pipelineLayout = this._createPipelineLayout(webgpuPipelineContext);\n const colorStates = [];\n const alphaBlend = this._getAphaBlendState();\n const colorBlend = this._getColorBlendState();\n if (this._mrtAttachments1 > 0) {\n for (let i = 0; i < this._mrtFormats.length; ++i) {\n const format = this._mrtFormats[i];\n if (format) {\n const descr = {\n format,\n writeMask: (this._mrtEnabledMask & (1 << i)) !== 0 ? this._writeMask : 0,\n };\n if (alphaBlend && colorBlend) {\n descr.blend = {\n alpha: alphaBlend,\n color: colorBlend,\n };\n }\n colorStates.push(descr);\n }\n else {\n colorStates.push(null);\n }\n }\n }\n else {\n if (this._webgpuColorFormat[0]) {\n const descr = {\n format: this._webgpuColorFormat[0],\n writeMask: this._writeMask,\n };\n if (alphaBlend && colorBlend) {\n descr.blend = {\n alpha: alphaBlend,\n color: colorBlend,\n };\n }\n colorStates.push(descr);\n }\n else {\n colorStates.push(null);\n }\n }\n const stencilFrontBack = {\n compare: WebGPUCacheRenderPipeline._GetCompareFunction(this._stencilEnabled ? this._stencilFrontCompare : 7 /* ALWAYS */),\n depthFailOp: WebGPUCacheRenderPipeline._GetStencilOpFunction(this._stencilEnabled ? this._stencilFrontDepthFailOp : 1 /* KEEP */),\n failOp: WebGPUCacheRenderPipeline._GetStencilOpFunction(this._stencilEnabled ? this._stencilFrontFailOp : 1 /* KEEP */),\n passOp: WebGPUCacheRenderPipeline._GetStencilOpFunction(this._stencilEnabled ? this._stencilFrontPassOp : 1 /* KEEP */),\n };\n let stripIndexFormat = undefined;\n if (topology === WebGPUConstants.PrimitiveTopology.LineStrip || topology === WebGPUConstants.PrimitiveTopology.TriangleStrip) {\n stripIndexFormat = !this._indexBuffer || this._indexBuffer.is32Bits ? WebGPUConstants.IndexFormat.Uint32 : WebGPUConstants.IndexFormat.Uint16;\n }\n const depthStencilFormatHasStencil = this._webgpuDepthStencilFormat ? WebGPUTextureHelper.HasStencilAspect(this._webgpuDepthStencilFormat) : false;\n return this._device.createRenderPipeline({\n label: `RenderPipeline_${(_b = (_a = colorStates[0]) === null || _a === void 0 ? void 0 : _a.format) !== null && _b !== void 0 ? _b : \"nooutput\"}_${(_c = this._webgpuDepthStencilFormat) !== null && _c !== void 0 ? _c : \"nodepth\"}_samples${sampleCount}_textureState${this._textureState}`,\n layout: pipelineLayout,\n vertex: {\n module: webgpuPipelineContext.stages.vertexStage.module,\n entryPoint: webgpuPipelineContext.stages.vertexStage.entryPoint,\n buffers: inputStateDescriptor,\n },\n primitive: {\n topology,\n stripIndexFormat,\n frontFace: this._frontFace === 1 ? WebGPUConstants.FrontFace.CCW : WebGPUConstants.FrontFace.CW,\n cullMode: !this._cullEnabled ? WebGPUConstants.CullMode.None : this._cullFace === 2 ? WebGPUConstants.CullMode.Front : WebGPUConstants.CullMode.Back,\n },\n fragment: !webgpuPipelineContext.stages.fragmentStage\n ? undefined\n : {\n module: webgpuPipelineContext.stages.fragmentStage.module,\n entryPoint: webgpuPipelineContext.stages.fragmentStage.entryPoint,\n targets: colorStates,\n },\n multisample: {\n count: sampleCount,\n /*mask,\n alphaToCoverageEnabled,*/\n },\n depthStencil: this._webgpuDepthStencilFormat === undefined\n ? undefined\n : {\n depthWriteEnabled: this._depthWriteEnabled,\n depthCompare: this._depthTestEnabled ? WebGPUCacheRenderPipeline._GetCompareFunction(this._depthCompare) : WebGPUConstants.CompareFunction.Always,\n format: this._webgpuDepthStencilFormat,\n stencilFront: this._stencilEnabled && depthStencilFormatHasStencil ? stencilFrontBack : undefined,\n stencilBack: this._stencilEnabled && depthStencilFormatHasStencil ? stencilFrontBack : undefined,\n stencilReadMask: this._stencilEnabled && depthStencilFormatHasStencil ? this._stencilReadMask : undefined,\n stencilWriteMask: this._stencilEnabled && depthStencilFormatHasStencil ? this._stencilWriteMask : undefined,\n depthBias: this._depthBias,\n depthBiasClamp: this._depthBiasClamp,\n depthBiasSlopeScale: this._depthBiasSlopeScale,\n },\n });\n }\n}\nWebGPUCacheRenderPipeline.NumCacheHitWithoutHash = 0;\nWebGPUCacheRenderPipeline.NumCacheHitWithHash = 0;\nWebGPUCacheRenderPipeline.NumCacheMiss = 0;\nWebGPUCacheRenderPipeline.NumPipelineCreationLastFrame = 0;\nWebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame = 0;\n//# sourceMappingURL=webgpuCacheRenderPipeline.js.map","import { WebGPUCacheRenderPipeline } from \"./webgpuCacheRenderPipeline.js\";\n/** @internal */\nclass NodeState {\n constructor() {\n this.values = {};\n }\n count() {\n let countNode = 0, countPipeline = this.pipeline ? 1 : 0;\n for (const value in this.values) {\n const node = this.values[value];\n const [childCountNodes, childCoundPipeline] = node.count();\n countNode += childCountNodes;\n countPipeline += childCoundPipeline;\n countNode++;\n }\n return [countNode, countPipeline];\n }\n}\n/** @internal */\nexport class WebGPUCacheRenderPipelineTree extends WebGPUCacheRenderPipeline {\n static GetNodeCounts() {\n const counts = WebGPUCacheRenderPipelineTree._Cache.count();\n return { nodeCount: counts[0], pipelineCount: counts[1] };\n }\n static _GetPipelines(node, pipelines, curPath, curPathLen) {\n if (node.pipeline) {\n const path = curPath.slice();\n path.length = curPathLen;\n pipelines.push(path);\n }\n for (const value in node.values) {\n const nnode = node.values[value];\n curPath[curPathLen] = parseInt(value);\n WebGPUCacheRenderPipelineTree._GetPipelines(nnode, pipelines, curPath, curPathLen + 1);\n }\n }\n static GetPipelines() {\n const pipelines = [];\n WebGPUCacheRenderPipelineTree._GetPipelines(WebGPUCacheRenderPipelineTree._Cache, pipelines, [], 0);\n return pipelines;\n }\n constructor(device, emptyVertexBuffer, useTextureStage) {\n super(device, emptyVertexBuffer, useTextureStage);\n this._nodeStack = [];\n this._nodeStack[0] = WebGPUCacheRenderPipelineTree._Cache;\n }\n _getRenderPipeline(param) {\n let node = this._nodeStack[this._stateDirtyLowestIndex];\n for (let i = this._stateDirtyLowestIndex; i < this._statesLength; ++i) {\n let nn = node.values[this._states[i]];\n if (!nn) {\n nn = new NodeState();\n node.values[this._states[i]] = nn;\n }\n node = nn;\n this._nodeStack[i + 1] = node;\n }\n param.token = node;\n param.pipeline = node.pipeline;\n }\n _setRenderPipeline(param) {\n param.token.pipeline = param.pipeline;\n }\n}\nWebGPUCacheRenderPipelineTree._Cache = new NodeState();\n//# sourceMappingURL=webgpuCacheRenderPipelineTree.js.map","import { StencilStateComposer } from \"../../States/stencilStateComposer.js\";\n/**\n * @internal\n **/\nexport class WebGPUStencilStateComposer extends StencilStateComposer {\n constructor(cache) {\n super(false);\n this._cache = cache;\n this.reset();\n }\n get func() {\n return this._func;\n }\n set func(value) {\n if (this._func === value) {\n return;\n }\n this._func = value;\n this._cache.setStencilCompare(value);\n }\n get funcMask() {\n return this._funcMask;\n }\n set funcMask(value) {\n if (this._funcMask === value) {\n return;\n }\n this._funcMask = value;\n this._cache.setStencilReadMask(value);\n }\n get opStencilFail() {\n return this._opStencilFail;\n }\n set opStencilFail(value) {\n if (this._opStencilFail === value) {\n return;\n }\n this._opStencilFail = value;\n this._cache.setStencilFailOp(value);\n }\n get opDepthFail() {\n return this._opDepthFail;\n }\n set opDepthFail(value) {\n if (this._opDepthFail === value) {\n return;\n }\n this._opDepthFail = value;\n this._cache.setStencilDepthFailOp(value);\n }\n get opStencilDepthPass() {\n return this._opStencilDepthPass;\n }\n set opStencilDepthPass(value) {\n if (this._opStencilDepthPass === value) {\n return;\n }\n this._opStencilDepthPass = value;\n this._cache.setStencilPassOp(value);\n }\n get mask() {\n return this._mask;\n }\n set mask(value) {\n if (this._mask === value) {\n return;\n }\n this._mask = value;\n this._cache.setStencilWriteMask(value);\n }\n get enabled() {\n return this._enabled;\n }\n set enabled(value) {\n if (this._enabled === value) {\n return;\n }\n this._enabled = value;\n this._cache.setStencilEnabled(value);\n }\n reset() {\n super.reset();\n this._cache.resetStencilState();\n }\n apply() {\n var _a;\n const stencilMaterialEnabled = (_a = this.stencilMaterial) === null || _a === void 0 ? void 0 : _a.enabled;\n this.enabled = stencilMaterialEnabled ? this.stencilMaterial.enabled : this.stencilGlobal.enabled;\n if (!this.enabled) {\n return;\n }\n this.func = stencilMaterialEnabled ? this.stencilMaterial.func : this.stencilGlobal.func;\n this.funcRef = stencilMaterialEnabled ? this.stencilMaterial.funcRef : this.stencilGlobal.funcRef;\n this.funcMask = stencilMaterialEnabled ? this.stencilMaterial.funcMask : this.stencilGlobal.funcMask;\n this.opStencilFail = stencilMaterialEnabled ? this.stencilMaterial.opStencilFail : this.stencilGlobal.opStencilFail;\n this.opDepthFail = stencilMaterialEnabled ? this.stencilMaterial.opDepthFail : this.stencilGlobal.opDepthFail;\n this.opStencilDepthPass = stencilMaterialEnabled ? this.stencilMaterial.opStencilDepthPass : this.stencilGlobal.opStencilDepthPass;\n this.mask = stencilMaterialEnabled ? this.stencilMaterial.mask : this.stencilGlobal.mask;\n }\n}\n//# sourceMappingURL=webgpuStencilStateComposer.js.map","import { DepthCullingState } from \"../../States/depthCullingState.js\";\n/**\n * @internal\n **/\nexport class WebGPUDepthCullingState extends DepthCullingState {\n /**\n * Initializes the state.\n * @param cache\n */\n constructor(cache) {\n super(false);\n this._cache = cache;\n this.reset();\n }\n get zOffset() {\n return this._zOffset;\n }\n set zOffset(value) {\n if (this._zOffset === value) {\n return;\n }\n this._zOffset = value;\n this._isZOffsetDirty = true;\n this._cache.setDepthBiasSlopeScale(value);\n }\n get zOffsetUnits() {\n return this._zOffsetUnits;\n }\n set zOffsetUnits(value) {\n if (this._zOffsetUnits === value) {\n return;\n }\n this._zOffsetUnits = value;\n this._isZOffsetDirty = true;\n this._cache.setDepthBias(value);\n }\n get cullFace() {\n return this._cullFace;\n }\n set cullFace(value) {\n if (this._cullFace === value) {\n return;\n }\n this._cullFace = value;\n this._isCullFaceDirty = true;\n this._cache.setCullFace(value !== null && value !== void 0 ? value : 1);\n }\n get cull() {\n return this._cull;\n }\n set cull(value) {\n if (this._cull === value) {\n return;\n }\n this._cull = value;\n this._isCullDirty = true;\n this._cache.setCullEnabled(!!value);\n }\n get depthFunc() {\n return this._depthFunc;\n }\n set depthFunc(value) {\n if (this._depthFunc === value) {\n return;\n }\n this._depthFunc = value;\n this._isDepthFuncDirty = true;\n this._cache.setDepthCompare(value);\n }\n get depthMask() {\n return this._depthMask;\n }\n set depthMask(value) {\n if (this._depthMask === value) {\n return;\n }\n this._depthMask = value;\n this._isDepthMaskDirty = true;\n this._cache.setDepthWriteEnabled(value);\n }\n get depthTest() {\n return this._depthTest;\n }\n set depthTest(value) {\n if (this._depthTest === value) {\n return;\n }\n this._depthTest = value;\n this._isDepthTestDirty = true;\n this._cache.setDepthTestEnabled(value);\n }\n get frontFace() {\n return this._frontFace;\n }\n set frontFace(value) {\n if (this._frontFace === value) {\n return;\n }\n this._frontFace = value;\n this._isFrontFaceDirty = true;\n this._cache.setFrontFace(value !== null && value !== void 0 ? value : 2);\n }\n reset() {\n super.reset();\n this._cache.resetDepthCullingState();\n }\n apply() {\n // nothing to do\n }\n}\n//# sourceMappingURL=webgpuDepthCullingState.js.map","\nimport { InternalTexture } from \"./internalTexture.js\";\n/**\n * Class used to store an external texture (like GPUExternalTexture in WebGPU)\n */\nexport class ExternalTexture {\n /**\n * Checks if a texture is an external or internal texture\n * @param texture the external or internal texture\n * @returns true if the texture is an external texture, else false\n */\n static IsExternalTexture(texture) {\n return texture.underlyingResource !== undefined;\n }\n /**\n * Get the class name of the texture.\n * @returns \"ExternalTexture\"\n */\n getClassName() {\n return \"ExternalTexture\";\n }\n /**\n * Gets the underlying texture object\n */\n get underlyingResource() {\n return this._video;\n }\n /**\n * Constructs the texture\n * @param video The video the texture should be wrapped around\n */\n constructor(video) {\n /**\n * Gets a boolean indicating if the texture uses mipmaps\n */\n this.useMipMaps = false;\n /**\n * The type of the underlying texture is implementation dependent, so return \"UNDEFINED\" for the type\n */\n this.type = 16;\n this._video = video;\n this.uniqueId = InternalTexture._Counter++;\n }\n /**\n * Get if the texture is ready to be used (downloaded, converted, mip mapped...).\n * @returns true if fully ready\n */\n isReady() {\n return this._video.readyState >= this._video.HAVE_CURRENT_DATA;\n }\n /**\n * Dispose the texture and release its associated resources.\n */\n dispose() { }\n}\n//# sourceMappingURL=externalTexture.js.map","import { ExternalTexture } from \"../../Materials/Textures/externalTexture.js\";\n\nimport { WebGPUCacheSampler } from \"./webgpuCacheSampler.js\";\n/** @internal */\nexport class WebGPUMaterialContext {\n get forceBindGroupCreation() {\n // If there is at least one external texture to bind, we must recreate the bind groups each time\n // because we need to retrieve a new texture each frame (by calling device.importExternalTexture)\n return this._numExternalTextures > 0;\n }\n get hasFloatTextures() {\n return this._numFloatTextures > 0;\n }\n constructor() {\n this.uniqueId = WebGPUMaterialContext._Counter++;\n this.updateId = 0;\n this.textureState = 0;\n this.reset();\n }\n reset() {\n this.samplers = {};\n this.textures = {};\n this.isDirty = true;\n this._numFloatTextures = 0;\n this._numExternalTextures = 0;\n }\n setSampler(name, sampler) {\n let samplerCache = this.samplers[name];\n let currentHashCode = -1;\n if (!samplerCache) {\n this.samplers[name] = samplerCache = { sampler, hashCode: 0 };\n }\n else {\n currentHashCode = samplerCache.hashCode;\n }\n samplerCache.sampler = sampler;\n samplerCache.hashCode = sampler ? WebGPUCacheSampler.GetSamplerHashCode(sampler) : 0;\n const isDirty = currentHashCode !== samplerCache.hashCode;\n if (isDirty) {\n this.updateId++;\n }\n this.isDirty || (this.isDirty = isDirty);\n }\n setTexture(name, texture) {\n var _a, _b, _c;\n let textureCache = this.textures[name];\n let currentTextureId = -1;\n if (!textureCache) {\n this.textures[name] = textureCache = { texture, isFloatTexture: false, isExternalTexture: false };\n }\n else {\n currentTextureId = (_b = (_a = textureCache.texture) === null || _a === void 0 ? void 0 : _a.uniqueId) !== null && _b !== void 0 ? _b : -1;\n }\n if (textureCache.isExternalTexture) {\n this._numExternalTextures--;\n }\n if (textureCache.isFloatTexture) {\n this._numFloatTextures--;\n }\n if (texture) {\n textureCache.isFloatTexture = texture.type === 1;\n textureCache.isExternalTexture = ExternalTexture.IsExternalTexture(texture);\n if (textureCache.isFloatTexture) {\n this._numFloatTextures++;\n }\n if (textureCache.isExternalTexture) {\n this._numExternalTextures++;\n }\n }\n else {\n textureCache.isFloatTexture = false;\n textureCache.isExternalTexture = false;\n }\n textureCache.texture = texture;\n const isDirty = currentTextureId !== ((_c = texture === null || texture === void 0 ? void 0 : texture.uniqueId) !== null && _c !== void 0 ? _c : -1);\n if (isDirty) {\n this.updateId++;\n }\n this.isDirty || (this.isDirty = isDirty);\n }\n}\nWebGPUMaterialContext._Counter = 0;\n//# sourceMappingURL=webgpuMaterialContext.js.map","import * as WebGPUConstants from \"./webgpuConstants.js\";\n/** @internal */\nexport class WebGPUDrawContext {\n isDirty(materialContextUpdateId) {\n return this._isDirty || this._materialContextUpdateId !== materialContextUpdateId;\n }\n resetIsDirty(materialContextUpdateId) {\n this._isDirty = false;\n this._materialContextUpdateId = materialContextUpdateId;\n }\n get useInstancing() {\n return this._useInstancing;\n }\n set useInstancing(use) {\n if (this._useInstancing === use) {\n return;\n }\n if (!use) {\n if (this.indirectDrawBuffer) {\n this._bufferManager.releaseBuffer(this.indirectDrawBuffer);\n }\n this.indirectDrawBuffer = undefined;\n this._indirectDrawData = undefined;\n }\n else {\n this.indirectDrawBuffer = this._bufferManager.createRawBuffer(20, WebGPUConstants.BufferUsage.CopyDst | WebGPUConstants.BufferUsage.Indirect | WebGPUConstants.BufferUsage.Storage);\n this._indirectDrawData = new Uint32Array(5);\n this._indirectDrawData[3] = 0;\n this._indirectDrawData[4] = 0;\n }\n this._useInstancing = use;\n this._currentInstanceCount = -1;\n }\n constructor(bufferManager) {\n this._bufferManager = bufferManager;\n this.uniqueId = WebGPUDrawContext._Counter++;\n this._useInstancing = false;\n this._currentInstanceCount = 0;\n this.reset();\n }\n reset() {\n this.buffers = {};\n this._isDirty = true;\n this._materialContextUpdateId = 0;\n this.fastBundle = undefined;\n this.bindGroups = undefined;\n }\n setBuffer(name, buffer) {\n var _a;\n this._isDirty || (this._isDirty = (buffer === null || buffer === void 0 ? void 0 : buffer.uniqueId) !== ((_a = this.buffers[name]) === null || _a === void 0 ? void 0 : _a.uniqueId));\n this.buffers[name] = buffer;\n }\n setIndirectData(indexOrVertexCount, instanceCount, firstIndexOrVertex) {\n if (instanceCount === this._currentInstanceCount || !this.indirectDrawBuffer || !this._indirectDrawData) {\n // The current buffer is already up to date so do nothing\n // Note that we only check for instanceCount and not indexOrVertexCount nor firstIndexOrVertex because those values\n // are supposed to not change during the lifetime of a draw context\n return;\n }\n this._currentInstanceCount = instanceCount;\n this._indirectDrawData[0] = indexOrVertexCount;\n this._indirectDrawData[1] = instanceCount;\n this._indirectDrawData[2] = firstIndexOrVertex;\n this._bufferManager.setRawData(this.indirectDrawBuffer, 0, this._indirectDrawData, 0, 20);\n }\n dispose() {\n if (this.indirectDrawBuffer) {\n this._bufferManager.releaseBuffer(this.indirectDrawBuffer);\n this.indirectDrawBuffer = undefined;\n this._indirectDrawData = undefined;\n }\n this.fastBundle = undefined;\n this.bindGroups = undefined;\n this.buffers = undefined;\n }\n}\nWebGPUDrawContext._Counter = 0;\n//# sourceMappingURL=webgpuDrawContext.js.map","import { Logger } from \"../../Misc/logger.js\";\nclass WebGPUBindGroupCacheNode {\n constructor() {\n this.values = {};\n }\n}\n/** @internal */\nexport class WebGPUCacheBindGroups {\n static get Statistics() {\n return {\n totalCreated: WebGPUCacheBindGroups.NumBindGroupsCreatedTotal,\n lastFrameCreated: WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame,\n lookupLastFrame: WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame,\n noLookupLastFrame: WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame,\n };\n }\n constructor(device, cacheSampler, engine) {\n this.disabled = false;\n this._device = device;\n this._cacheSampler = cacheSampler;\n this._engine = engine;\n }\n endFrame() {\n WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame = WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame;\n WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame = WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame;\n WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame = WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame;\n WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame = 0;\n WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame = 0;\n WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame = 0;\n }\n /**\n * Cache is currently based on the uniform/storage buffers, samplers and textures used by the binding groups.\n * Note that all uniform buffers have an offset of 0 in Babylon and we don't have a use case where we would have the same buffer used with different capacity values:\n * that means we don't need to factor in the offset/size of the buffer in the cache, only the id\n * @param webgpuPipelineContext\n * @param drawContext\n * @param materialContext\n */\n getBindGroups(webgpuPipelineContext, drawContext, materialContext) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;\n let bindGroups = undefined;\n let node = WebGPUCacheBindGroups._Cache;\n const cacheIsDisabled = this.disabled || materialContext.forceBindGroupCreation;\n if (!cacheIsDisabled) {\n if (!drawContext.isDirty(materialContext.updateId) && !materialContext.isDirty) {\n WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame++;\n return drawContext.bindGroups;\n }\n for (const bufferName of webgpuPipelineContext.shaderProcessingContext.bufferNames) {\n const uboId = (_b = (_a = drawContext.buffers[bufferName]) === null || _a === void 0 ? void 0 : _a.uniqueId) !== null && _b !== void 0 ? _b : 0;\n let nextNode = node.values[uboId];\n if (!nextNode) {\n nextNode = new WebGPUBindGroupCacheNode();\n node.values[uboId] = nextNode;\n }\n node = nextNode;\n }\n for (const samplerName of webgpuPipelineContext.shaderProcessingContext.samplerNames) {\n const samplerHashCode = (_d = (_c = materialContext.samplers[samplerName]) === null || _c === void 0 ? void 0 : _c.hashCode) !== null && _d !== void 0 ? _d : 0;\n let nextNode = node.values[samplerHashCode];\n if (!nextNode) {\n nextNode = new WebGPUBindGroupCacheNode();\n node.values[samplerHashCode] = nextNode;\n }\n node = nextNode;\n }\n for (const textureName of webgpuPipelineContext.shaderProcessingContext.textureNames) {\n const textureId = (_g = (_f = (_e = materialContext.textures[textureName]) === null || _e === void 0 ? void 0 : _e.texture) === null || _f === void 0 ? void 0 : _f.uniqueId) !== null && _g !== void 0 ? _g : 0;\n let nextNode = node.values[textureId];\n if (!nextNode) {\n nextNode = new WebGPUBindGroupCacheNode();\n node.values[textureId] = nextNode;\n }\n node = nextNode;\n }\n bindGroups = node.bindGroups;\n }\n drawContext.resetIsDirty(materialContext.updateId);\n materialContext.isDirty = false;\n if (bindGroups) {\n drawContext.bindGroups = bindGroups;\n WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame++;\n return bindGroups;\n }\n bindGroups = [];\n drawContext.bindGroups = bindGroups;\n if (!cacheIsDisabled) {\n node.bindGroups = bindGroups;\n }\n WebGPUCacheBindGroups.NumBindGroupsCreatedTotal++;\n WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame++;\n const bindGroupLayouts = webgpuPipelineContext.bindGroupLayouts[materialContext.textureState];\n for (let i = 0; i < webgpuPipelineContext.shaderProcessingContext.bindGroupLayoutEntries.length; i++) {\n const setDefinition = webgpuPipelineContext.shaderProcessingContext.bindGroupLayoutEntries[i];\n const entries = webgpuPipelineContext.shaderProcessingContext.bindGroupEntries[i];\n for (let j = 0; j < setDefinition.length; j++) {\n const entry = webgpuPipelineContext.shaderProcessingContext.bindGroupLayoutEntries[i][j];\n const entryInfo = webgpuPipelineContext.shaderProcessingContext.bindGroupLayoutEntryInfo[i][entry.binding];\n const name = (_h = entryInfo.nameInArrayOfTexture) !== null && _h !== void 0 ? _h : entryInfo.name;\n if (entry.sampler) {\n const bindingInfo = materialContext.samplers[name];\n if (bindingInfo) {\n const sampler = bindingInfo.sampler;\n if (!sampler) {\n if (this._engine.dbgSanityChecks) {\n Logger.Error(`Trying to bind a null sampler! entry=${JSON.stringify(entry)}, name=${name}, bindingInfo=${JSON.stringify(bindingInfo, (key, value) => (key === \"texture\" ? \"\" : value))}, materialContext.uniqueId=${materialContext.uniqueId}`, 50);\n }\n continue;\n }\n entries[j].resource = this._cacheSampler.getSampler(sampler, false, bindingInfo.hashCode);\n }\n else {\n Logger.Error(`Sampler \"${name}\" could not be bound. entry=${JSON.stringify(entry)}, materialContext=${JSON.stringify(materialContext, (key, value) => key === \"texture\" || key === \"sampler\" ? \"\" : value)}`, 50);\n }\n }\n else if (entry.texture || entry.storageTexture) {\n const bindingInfo = materialContext.textures[name];\n if (bindingInfo) {\n if (this._engine.dbgSanityChecks && bindingInfo.texture === null) {\n Logger.Error(`Trying to bind a null texture! entry=${JSON.stringify(entry)}, bindingInfo=${JSON.stringify(bindingInfo, (key, value) => key === \"texture\" ? \"\" : value)}, materialContext.uniqueId=${materialContext.uniqueId}`, 50);\n continue;\n }\n const hardwareTexture = bindingInfo.texture._hardwareTexture;\n if (this._engine.dbgSanityChecks &&\n (!hardwareTexture || (entry.texture && !hardwareTexture.view) || (entry.storageTexture && !hardwareTexture.viewForWriting))) {\n Logger.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(entry)}, name=${name}, bindingInfo=${JSON.stringify(bindingInfo, (key, value) => (key === \"texture\" ? \"\" : value))}, isReady=${(_j = bindingInfo.texture) === null || _j === void 0 ? void 0 : _j.isReady}, materialContext.uniqueId=${materialContext.uniqueId}`, 50);\n continue;\n }\n entries[j].resource = entry.storageTexture ? hardwareTexture.viewForWriting : hardwareTexture.view;\n }\n else {\n Logger.Error(`Texture \"${name}\" could not be bound. entry=${JSON.stringify(entry)}, materialContext=${JSON.stringify(materialContext, (key, value) => key === \"texture\" || key === \"sampler\" ? \"\" : value)}`, 50);\n }\n }\n else if (entry.externalTexture) {\n const bindingInfo = materialContext.textures[name];\n if (bindingInfo) {\n if (this._engine.dbgSanityChecks && bindingInfo.texture === null) {\n Logger.Error(`Trying to bind a null external texture! entry=${JSON.stringify(entry)}, name=${name}, bindingInfo=${JSON.stringify(bindingInfo, (key, value) => (key === \"texture\" ? \"\" : value))}, materialContext.uniqueId=${materialContext.uniqueId}`, 50);\n continue;\n }\n const externalTexture = bindingInfo.texture.underlyingResource;\n if (this._engine.dbgSanityChecks && !externalTexture) {\n Logger.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(entry)}, name=${name}, bindingInfo=${JSON.stringify(bindingInfo, (key, value) => (key === \"texture\" ? \"\" : value))}, isReady=${(_k = bindingInfo.texture) === null || _k === void 0 ? void 0 : _k.isReady}, materialContext.uniqueId=${materialContext.uniqueId}`, 50);\n continue;\n }\n entries[j].resource = this._device.importExternalTexture({ source: externalTexture });\n }\n else {\n Logger.Error(`Texture \"${name}\" could not be bound. entry=${JSON.stringify(entry)}, materialContext=${JSON.stringify(materialContext, (key, value) => key === \"texture\" || key === \"sampler\" ? \"\" : value)}`, 50);\n }\n }\n else if (entry.buffer) {\n const dataBuffer = drawContext.buffers[name];\n if (dataBuffer) {\n const webgpuBuffer = dataBuffer.underlyingResource;\n entries[j].resource.buffer = webgpuBuffer;\n entries[j].resource.size = dataBuffer.capacity;\n }\n else {\n Logger.Error(`Can't find buffer \"${name}\". entry=${JSON.stringify(entry)}, buffers=${JSON.stringify(drawContext.buffers)}, drawContext.uniqueId=${drawContext.uniqueId}`, 50);\n }\n }\n }\n const groupLayout = bindGroupLayouts[i];\n bindGroups[i] = this._device.createBindGroup({\n layout: groupLayout,\n entries,\n });\n }\n return bindGroups;\n }\n}\nWebGPUCacheBindGroups.NumBindGroupsCreatedTotal = 0;\nWebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame = 0;\nWebGPUCacheBindGroups.NumBindGroupsLookupLastFrame = 0;\nWebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame = 0;\nWebGPUCacheBindGroups._Cache = new WebGPUBindGroupCacheNode();\nWebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame = 0;\nWebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame = 0;\nWebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame = 0;\n//# sourceMappingURL=webgpuCacheBindGroups.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"clearQuadVertexShader\";\nconst shader = `uniform float depthValue;\rconst vec2 pos[4]={\rvec2(-1.0,1.0),\rvec2(1.0,1.0),\rvec2(-1.0,-1.0),\rvec2(1.0,-1.0)\r};\r#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_VERTEX_MAIN_BEGIN\ngl_Position=vec4(pos[gl_VertexID],depthValue,1.0);\r#define CUSTOM_VERTEX_MAIN_END\n}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const clearQuadVertexShader = { name, shader };\n//# sourceMappingURL=clearQuad.vertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"clearQuadPixelShader\";\nconst shader = `uniform vec4 color;\rvoid main() {\rgl_FragColor=color;\r}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const clearQuadPixelShader = { name, shader };\n//# sourceMappingURL=clearQuad.fragment.js.map","\nimport { WebGPUCacheRenderPipelineTree } from \"./webgpuCacheRenderPipelineTree.js\";\nimport { WebGPUShaderProcessingContext } from \"./webgpuShaderProcessingContext.js\";\nimport { renderableTextureFormatToIndex, WebGPUTextureHelper } from \"./webgpuTextureHelper.js\";\nimport \"../../Shaders/clearQuad.vertex.js\";\nimport \"../../Shaders/clearQuad.fragment.js\";\n/** @internal */\nexport class WebGPUClearQuad {\n setDepthStencilFormat(format) {\n this._depthTextureFormat = format;\n this._cacheRenderPipeline.setDepthStencilFormat(format);\n }\n setColorFormat(format) {\n this._cacheRenderPipeline.setColorFormat(format);\n }\n setMRTAttachments(attachments, textureArray, textureCount) {\n this._cacheRenderPipeline.setMRT(textureArray, textureCount);\n this._cacheRenderPipeline.setMRTAttachments(attachments);\n }\n constructor(device, engine, emptyVertexBuffer) {\n this._bindGroups = {};\n this._bundleCache = {};\n this._keyTemp = [];\n this._device = device;\n this._engine = engine;\n this._cacheRenderPipeline = new WebGPUCacheRenderPipelineTree(this._device, emptyVertexBuffer, !engine._caps.textureFloatLinearFiltering);\n this._cacheRenderPipeline.setDepthTestEnabled(false);\n this._cacheRenderPipeline.setStencilReadMask(0xff);\n this._effect = engine.createEffect(\"clearQuad\", [], [\"color\", \"depthValue\"]);\n }\n clear(renderPass, clearColor, clearDepth, clearStencil, sampleCount = 1) {\n var _a, _b;\n let renderPass2;\n let bundle = null;\n let bundleKey;\n const isRTTPass = !!this._engine._currentRenderTarget;\n if (renderPass) {\n renderPass2 = renderPass;\n }\n else {\n let idx = 0;\n this._keyTemp.length = 0;\n for (let i = 0; i < this._cacheRenderPipeline.colorFormats.length; ++i) {\n this._keyTemp[idx++] = renderableTextureFormatToIndex[(_a = this._cacheRenderPipeline.colorFormats[i]) !== null && _a !== void 0 ? _a : \"\"];\n }\n const depthStencilFormatIndex = renderableTextureFormatToIndex[(_b = this._depthTextureFormat) !== null && _b !== void 0 ? _b : 0];\n this._keyTemp[idx] =\n (clearColor ? clearColor.r + clearColor.g * 256 + clearColor.b * 256 * 256 + clearColor.a * 256 * 256 * 256 : 0) +\n (clearDepth ? 2 ** 32 : 0) +\n (clearStencil ? 2 ** 33 : 0) +\n (this._engine.useReverseDepthBuffer ? 2 ** 34 : 0) +\n (isRTTPass ? 2 ** 35 : 0) +\n (sampleCount > 1 ? 2 ** 36 : 0) +\n depthStencilFormatIndex * 2 ** 37;\n bundleKey = this._keyTemp.join(\"_\");\n bundle = this._bundleCache[bundleKey];\n if (bundle) {\n return bundle;\n }\n renderPass2 = this._device.createRenderBundleEncoder({\n colorFormats: this._cacheRenderPipeline.colorFormats,\n depthStencilFormat: this._depthTextureFormat,\n sampleCount,\n });\n }\n this._cacheRenderPipeline.setDepthWriteEnabled(!!clearDepth);\n this._cacheRenderPipeline.setStencilEnabled(!!clearStencil && !!this._depthTextureFormat && WebGPUTextureHelper.HasStencilAspect(this._depthTextureFormat));\n this._cacheRenderPipeline.setStencilWriteMask(clearStencil ? 0xff : 0);\n this._cacheRenderPipeline.setStencilCompare(clearStencil ? 519 : 512);\n this._cacheRenderPipeline.setStencilPassOp(clearStencil ? 7681 : 7680);\n this._cacheRenderPipeline.setWriteMask(clearColor ? 0xf : 0);\n const pipeline = this._cacheRenderPipeline.getRenderPipeline(7, this._effect, sampleCount);\n const webgpuPipelineContext = this._effect._pipelineContext;\n if (clearColor) {\n this._effect.setDirectColor4(\"color\", clearColor);\n }\n this._effect.setFloat(\"depthValue\", this._engine.useReverseDepthBuffer ? this._engine._clearReverseDepthValue : this._engine._clearDepthValue);\n webgpuPipelineContext.uniformBuffer.update();\n const bufferInternals = isRTTPass ? this._engine._ubInvertY : this._engine._ubDontInvertY;\n const bufferLeftOver = webgpuPipelineContext.uniformBuffer.getBuffer();\n const key = bufferLeftOver.uniqueId + \"-\" + bufferInternals.uniqueId;\n let bindGroups = this._bindGroups[key];\n if (!bindGroups) {\n const bindGroupLayouts = webgpuPipelineContext.bindGroupLayouts[0];\n bindGroups = this._bindGroups[key] = [];\n bindGroups.push(this._device.createBindGroup({\n layout: bindGroupLayouts[0],\n entries: [],\n }));\n if (!WebGPUShaderProcessingContext._SimplifiedKnownBindings) {\n bindGroups.push(this._device.createBindGroup({\n layout: bindGroupLayouts[1],\n entries: [],\n }));\n }\n bindGroups.push(this._device.createBindGroup({\n layout: bindGroupLayouts[WebGPUShaderProcessingContext._SimplifiedKnownBindings ? 1 : 2],\n entries: [\n {\n binding: 0,\n resource: {\n buffer: bufferInternals.underlyingResource,\n size: bufferInternals.capacity,\n },\n },\n {\n binding: 1,\n resource: {\n buffer: bufferLeftOver.underlyingResource,\n size: bufferLeftOver.capacity,\n },\n },\n ],\n }));\n }\n renderPass2.setPipeline(pipeline);\n for (let i = 0; i < bindGroups.length; ++i) {\n renderPass2.setBindGroup(i, bindGroups[i]);\n }\n renderPass2.draw(4, 1, 0, 0);\n if (!renderPass) {\n bundle = renderPass2.finish();\n this._bundleCache[bundleKey] = bundle;\n }\n return bundle;\n }\n}\n//# sourceMappingURL=webgpuClearQuad.js.map","/** @internal */\nexport class WebGPURenderItemViewport {\n constructor(x, y, w, h) {\n this.x = Math.floor(x);\n this.y = Math.floor(y);\n this.w = Math.floor(w);\n this.h = Math.floor(h);\n }\n run(renderPass) {\n renderPass.setViewport(this.x, this.y, this.w, this.h, 0, 1);\n }\n clone() {\n return new WebGPURenderItemViewport(this.x, this.y, this.w, this.h);\n }\n}\n/** @internal */\nexport class WebGPURenderItemScissor {\n constructor(x, y, w, h) {\n this.x = x;\n this.y = y;\n this.w = w;\n this.h = h;\n }\n run(renderPass) {\n renderPass.setScissorRect(this.x, this.y, this.w, this.h);\n }\n clone() {\n return new WebGPURenderItemScissor(this.x, this.y, this.w, this.h);\n }\n}\n/** @internal */\nexport class WebGPURenderItemStencilRef {\n constructor(ref) {\n this.ref = ref;\n }\n run(renderPass) {\n renderPass.setStencilReference(this.ref);\n }\n clone() {\n return new WebGPURenderItemStencilRef(this.ref);\n }\n}\n/** @internal */\nexport class WebGPURenderItemBlendColor {\n constructor(color) {\n this.color = color;\n }\n run(renderPass) {\n renderPass.setBlendConstant(this.color);\n }\n clone() {\n return new WebGPURenderItemBlendColor(this.color);\n }\n}\n/** @internal */\nexport class WebGPURenderItemBeginOcclusionQuery {\n constructor(query) {\n this.query = query;\n }\n run(renderPass) {\n renderPass.beginOcclusionQuery(this.query);\n }\n clone() {\n return new WebGPURenderItemBeginOcclusionQuery(this.query);\n }\n}\n/** @internal */\nexport class WebGPURenderItemEndOcclusionQuery {\n constructor() { }\n run(renderPass) {\n renderPass.endOcclusionQuery();\n }\n clone() {\n return new WebGPURenderItemEndOcclusionQuery();\n }\n}\nclass WebGPURenderItemBundles {\n constructor() {\n this.bundles = [];\n }\n run(renderPass) {\n renderPass.executeBundles(this.bundles);\n }\n clone() {\n const cloned = new WebGPURenderItemBundles();\n cloned.bundles = this.bundles;\n return cloned;\n }\n}\n/** @internal */\nexport class WebGPUBundleList {\n constructor(device) {\n this.numDrawCalls = 0;\n this._device = device;\n this._list = new Array(10);\n this._listLength = 0;\n }\n addBundle(bundle) {\n if (!this._currentItemIsBundle) {\n const item = new WebGPURenderItemBundles();\n this._list[this._listLength++] = item;\n this._currentBundleList = item.bundles;\n this._currentItemIsBundle = true;\n }\n if (bundle) {\n this._currentBundleList.push(bundle);\n }\n }\n _finishBundle() {\n if (this._currentItemIsBundle && this._bundleEncoder) {\n this._currentBundleList.push(this._bundleEncoder.finish());\n this._bundleEncoder = undefined;\n this._currentItemIsBundle = false;\n }\n }\n addItem(item) {\n this._finishBundle();\n this._list[this._listLength++] = item;\n this._currentItemIsBundle = false;\n }\n getBundleEncoder(colorFormats, depthStencilFormat, sampleCount) {\n if (!this._currentItemIsBundle) {\n this.addBundle();\n this._bundleEncoder = this._device.createRenderBundleEncoder({\n colorFormats,\n depthStencilFormat,\n sampleCount,\n });\n }\n return this._bundleEncoder;\n }\n close() {\n this._finishBundle();\n }\n run(renderPass) {\n this.close();\n for (let i = 0; i < this._listLength; ++i) {\n this._list[i].run(renderPass);\n }\n }\n reset() {\n this._listLength = 0;\n this._currentItemIsBundle = false;\n this.numDrawCalls = 0;\n }\n clone() {\n this.close();\n const cloned = new WebGPUBundleList(this._device);\n cloned._list = new Array(this._listLength);\n cloned._listLength = this._listLength;\n cloned.numDrawCalls = this.numDrawCalls;\n for (let i = 0; i < this._listLength; ++i) {\n cloned._list[i] = this._list[i].clone();\n }\n return cloned;\n }\n}\n//# sourceMappingURL=webgpuBundleList.js.map","import * as WebGPUConstants from \"./webgpuConstants.js\";\n/** @internal */\nexport class WebGPUQuerySet {\n get querySet() {\n return this._querySet;\n }\n constructor(count, type, device, bufferManager, canUseMultipleBuffers = true) {\n this._dstBuffers = [];\n this._device = device;\n this._bufferManager = bufferManager;\n this._count = count;\n this._canUseMultipleBuffers = canUseMultipleBuffers;\n this._querySet = device.createQuerySet({\n type,\n count,\n });\n this._queryBuffer = bufferManager.createRawBuffer(8 * count, WebGPUConstants.BufferUsage.QueryResolve | WebGPUConstants.BufferUsage.CopySrc);\n if (!canUseMultipleBuffers) {\n this._dstBuffers.push(this._bufferManager.createRawBuffer(8 * this._count, WebGPUConstants.BufferUsage.MapRead | WebGPUConstants.BufferUsage.CopyDst));\n }\n }\n _getBuffer(firstQuery, queryCount) {\n if (!this._canUseMultipleBuffers && this._dstBuffers.length === 0) {\n return null;\n }\n const encoderResult = this._device.createCommandEncoder();\n let buffer;\n if (this._dstBuffers.length === 0) {\n buffer = this._bufferManager.createRawBuffer(8 * this._count, WebGPUConstants.BufferUsage.MapRead | WebGPUConstants.BufferUsage.CopyDst);\n }\n else {\n buffer = this._dstBuffers[this._dstBuffers.length - 1];\n this._dstBuffers.length--;\n }\n encoderResult.resolveQuerySet(this._querySet, firstQuery, queryCount, this._queryBuffer, 0);\n encoderResult.copyBufferToBuffer(this._queryBuffer, 0, buffer, 0, 8 * queryCount);\n this._device.queue.submit([encoderResult.finish()]);\n return buffer;\n }\n async readValues(firstQuery = 0, queryCount = 1) {\n const buffer = this._getBuffer(firstQuery, queryCount);\n if (buffer === null) {\n return null;\n }\n await buffer.mapAsync(WebGPUConstants.MapMode.Read);\n const arrayBuf = new BigUint64Array(buffer.getMappedRange()).slice();\n buffer.unmap();\n this._dstBuffers[this._dstBuffers.length] = buffer;\n return arrayBuf;\n }\n async readValue(firstQuery = 0) {\n const buffer = this._getBuffer(firstQuery, 1);\n if (buffer === null) {\n return null;\n }\n await buffer.mapAsync(WebGPUConstants.MapMode.Read);\n const arrayBuf = new BigUint64Array(buffer.getMappedRange());\n const value = Number(arrayBuf[0]);\n buffer.unmap();\n this._dstBuffers[this._dstBuffers.length] = buffer;\n return value;\n }\n async readTwoValuesAndSubtract(firstQuery = 0) {\n const buffer = this._getBuffer(firstQuery, 2);\n if (buffer === null) {\n return null;\n }\n await buffer.mapAsync(WebGPUConstants.MapMode.Read);\n const arrayBuf = new BigUint64Array(buffer.getMappedRange());\n const value = Number(arrayBuf[1] - arrayBuf[0]);\n buffer.unmap();\n this._dstBuffers[this._dstBuffers.length] = buffer;\n return value;\n }\n dispose() {\n this._querySet.destroy();\n this._bufferManager.releaseBuffer(this._queryBuffer);\n for (let i = 0; i < this._dstBuffers.length; ++i) {\n this._bufferManager.releaseBuffer(this._dstBuffers[i]);\n }\n }\n}\n//# sourceMappingURL=webgpuQuerySet.js.map","import * as WebGPUConstants from \"./webgpuConstants.js\";\nimport { PerfCounter } from \"../../Misc/perfCounter.js\";\nimport { WebGPUQuerySet } from \"./webgpuQuerySet.js\";\n/** @internal */\nexport class WebGPUTimestampQuery {\n get gpuFrameTimeCounter() {\n return this._gpuFrameTimeCounter;\n }\n constructor(device, bufferManager) {\n this._enabled = false;\n this._gpuFrameTimeCounter = new PerfCounter();\n this._measureDurationState = 0;\n this._device = device;\n this._bufferManager = bufferManager;\n }\n get enable() {\n return this._enabled;\n }\n set enable(value) {\n if (this._enabled === value) {\n return;\n }\n this._enabled = value;\n this._measureDurationState = 0;\n if (value) {\n this._measureDuration = new WebGPUDurationMeasure(this._device, this._bufferManager);\n }\n else {\n this._measureDuration.dispose();\n }\n }\n startFrame(commandEncoder) {\n if (this._enabled && this._measureDurationState === 0) {\n this._measureDuration.start(commandEncoder);\n this._measureDurationState = 1;\n }\n }\n endFrame(commandEncoder) {\n if (this._measureDurationState === 1) {\n this._measureDurationState = 2;\n this._measureDuration.stop(commandEncoder).then((duration) => {\n if (duration !== null && duration >= 0) {\n this._gpuFrameTimeCounter.fetchNewFrame();\n this._gpuFrameTimeCounter.addCount(duration, true);\n }\n this._measureDurationState = 0;\n });\n }\n }\n}\n/** @internal */\nexport class WebGPUDurationMeasure {\n constructor(device, bufferManager) {\n this._querySet = new WebGPUQuerySet(2, WebGPUConstants.QueryType.Timestamp, device, bufferManager);\n }\n start(encoder) {\n encoder.writeTimestamp(this._querySet.querySet, 0);\n }\n async stop(encoder) {\n encoder.writeTimestamp(this._querySet.querySet, 1);\n return this._querySet.readTwoValuesAndSubtract(0);\n }\n dispose() {\n this._querySet.dispose();\n }\n}\n//# sourceMappingURL=webgpuTimestampQuery.js.map","import * as WebGPUConstants from \"./webgpuConstants.js\";\nimport { WebGPUQuerySet } from \"./webgpuQuerySet.js\";\n/** @internal */\nexport class WebGPUOcclusionQuery {\n get querySet() {\n return this._querySet.querySet;\n }\n get hasQueries() {\n return this._currentTotalIndices !== this._availableIndices.length;\n }\n get canBeginQuery() {\n const passIndex = this._engine._getCurrentRenderPassIndex();\n switch (passIndex) {\n case 0: {\n return this._engine._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet !== undefined;\n }\n case 1: {\n return this._engine._rttRenderPassWrapper.renderPassDescriptor.occlusionQuerySet !== undefined;\n }\n }\n return false;\n }\n constructor(engine, device, bufferManager, startCount = 50, incrementCount = 100) {\n this._availableIndices = [];\n this._engine = engine;\n this._device = device;\n this._bufferManager = bufferManager;\n this._frameLastBuffer = -1;\n this._currentTotalIndices = 0;\n this._countIncrement = incrementCount;\n this._allocateNewIndices(startCount);\n }\n createQuery() {\n if (this._availableIndices.length === 0) {\n this._allocateNewIndices();\n }\n const index = this._availableIndices[this._availableIndices.length - 1];\n this._availableIndices.length--;\n return index;\n }\n deleteQuery(index) {\n this._availableIndices[this._availableIndices.length - 1] = index;\n }\n isQueryResultAvailable(index) {\n this._retrieveQueryBuffer();\n return !!this._lastBuffer && index < this._lastBuffer.length;\n }\n getQueryResult(index) {\n var _a, _b;\n return Number((_b = (_a = this._lastBuffer) === null || _a === void 0 ? void 0 : _a[index]) !== null && _b !== void 0 ? _b : -1);\n }\n _retrieveQueryBuffer() {\n if (this._lastBuffer && this._frameLastBuffer === this._engine.frameId) {\n return;\n }\n if (this._frameLastBuffer !== this._engine.frameId) {\n this._frameLastBuffer = this._engine.frameId;\n this._querySet.readValues(0, this._currentTotalIndices).then((arrayBuffer) => {\n this._lastBuffer = arrayBuffer;\n });\n }\n }\n _allocateNewIndices(numIndices) {\n numIndices = numIndices !== null && numIndices !== void 0 ? numIndices : this._countIncrement;\n this._delayQuerySetDispose();\n for (let i = 0; i < numIndices; ++i) {\n this._availableIndices.push(this._currentTotalIndices + i);\n }\n this._currentTotalIndices += numIndices;\n this._querySet = new WebGPUQuerySet(this._currentTotalIndices, WebGPUConstants.QueryType.Occlusion, this._device, this._bufferManager, false);\n }\n _delayQuerySetDispose() {\n const querySet = this._querySet;\n if (querySet) {\n // Wait a bit before disposing of the queryset, in case some queries are still running for it\n setTimeout(() => querySet.dispose, 1000);\n }\n }\n dispose() {\n var _a;\n (_a = this._querySet) === null || _a === void 0 ? void 0 : _a.dispose();\n this._availableIndices.length = 0;\n }\n}\n//# sourceMappingURL=webgpuOcclusionQuery.js.map","import { IsWindowObjectExist } from \"../../Misc/domManagement.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/** @internal */\nexport class WebGPUTintWASM {\n async initTwgsl(twgslOptions) {\n if (WebGPUTintWASM._twgsl) {\n return;\n }\n twgslOptions = twgslOptions || {};\n twgslOptions = Object.assign(Object.assign({}, WebGPUTintWASM._TWgslDefaultOptions), twgslOptions);\n if (twgslOptions.twgsl) {\n WebGPUTintWASM._twgsl = twgslOptions.twgsl;\n return Promise.resolve();\n }\n if (twgslOptions.jsPath && twgslOptions.wasmPath) {\n if (IsWindowObjectExist()) {\n await Tools.LoadScriptAsync(twgslOptions.jsPath);\n }\n else {\n importScripts(twgslOptions.jsPath);\n }\n }\n if (self.twgsl) {\n WebGPUTintWASM._twgsl = await self.twgsl(twgslOptions.wasmPath);\n return Promise.resolve();\n }\n return Promise.reject(\"twgsl is not available.\");\n }\n convertSpirV2WGSL(code, disableUniformityAnalysis = false) {\n const ccode = WebGPUTintWASM._twgsl.convertSpirV2WGSL(code);\n if (WebGPUTintWASM.ShowWGSLShaderCode) {\n console.log(ccode);\n console.log(\"***********************************************\");\n }\n return WebGPUTintWASM.DisableUniformityAnalysis || disableUniformityAnalysis ? \"diagnostic(off, derivative_uniformity);\\n\" + ccode : ccode;\n }\n}\n// Default twgsl options.\nWebGPUTintWASM._TWgslDefaultOptions = {\n jsPath: \"https://preview.babylonjs.com/twgsl/twgsl.js\",\n wasmPath: \"https://preview.babylonjs.com/twgsl/twgsl.wasm\",\n};\nWebGPUTintWASM.ShowWGSLShaderCode = false;\nWebGPUTintWASM.DisableUniformityAnalysis = false;\nWebGPUTintWASM._twgsl = null;\n//# sourceMappingURL=webgpuTintWASM.js.map","\n/** @internal */\nexport class WebGPUSnapshotRendering {\n constructor(engine, renderingMode, bundleList, bundleListRenderTarget) {\n this._record = false;\n this._play = false;\n this._mainPassBundleList = [];\n this._enabled = false;\n this._engine = engine;\n this._mode = renderingMode;\n this._bundleList = bundleList;\n this._bundleListRenderTarget = bundleListRenderTarget;\n }\n get enabled() {\n return this._enabled;\n }\n get play() {\n return this._play;\n }\n get record() {\n return this._record;\n }\n set enabled(activate) {\n this._mainPassBundleList.length = 0;\n this._record = this._enabled = activate;\n this._play = false;\n if (activate) {\n this._modeSaved = this._mode;\n this._mode = 0; // need to reset to standard for the recording pass to avoid some code being bypassed\n }\n }\n get mode() {\n return this._mode;\n }\n set mode(mode) {\n if (this._record) {\n this._modeSaved = mode;\n }\n else {\n this._mode = mode;\n }\n }\n endMainRenderPass() {\n if (this._record) {\n this._mainPassBundleList.push(this._bundleList.clone());\n }\n }\n endRenderTargetPass(currentRenderPass, gpuWrapper) {\n var _a, _b, _c, _d;\n if (this._play) {\n (_b = (_a = gpuWrapper._bundleLists) === null || _a === void 0 ? void 0 : _a[gpuWrapper._currentLayer]) === null || _b === void 0 ? void 0 : _b.run(currentRenderPass);\n if (this._mode === 1) {\n this._engine._reportDrawCall((_d = (_c = gpuWrapper._bundleLists) === null || _c === void 0 ? void 0 : _c[gpuWrapper._currentLayer]) === null || _d === void 0 ? void 0 : _d.numDrawCalls);\n }\n }\n else if (this._record) {\n if (!gpuWrapper._bundleLists) {\n gpuWrapper._bundleLists = [];\n }\n gpuWrapper._bundleLists[gpuWrapper._currentLayer] = this._bundleListRenderTarget.clone();\n gpuWrapper._bundleLists[gpuWrapper._currentLayer].run(currentRenderPass);\n this._bundleListRenderTarget.reset();\n }\n else {\n return false;\n }\n return true;\n }\n endFrame(mainRenderPass) {\n if (this._record) {\n this._mainPassBundleList.push(this._bundleList.clone());\n this._record = false;\n this._play = true;\n this._mode = this._modeSaved;\n }\n if (mainRenderPass !== null && this._play) {\n for (let i = 0; i < this._mainPassBundleList.length; ++i) {\n this._mainPassBundleList[i].run(mainRenderPass);\n if (this._mode === 1) {\n this._engine._reportDrawCall(this._mainPassBundleList[i].numDrawCalls);\n }\n }\n }\n }\n reset() {\n this.enabled = false;\n this.enabled = true;\n }\n}\n//# sourceMappingURL=webgpuSnapshotRendering.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"postprocessVertexShader\";\nconst shader = `attribute position: vec2;\runiform scale: vec2;\rvarying vUV: vec2;\rconst madd=vec2(0.5,0.5);\r#define CUSTOM_VERTEX_DEFINITIONS\n@vertex\rfn main(input : VertexInputs)->FragmentInputs {\r#define CUSTOM_VERTEX_MAIN_BEGIN\nvertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;\rvertexOutputs.position=vec4(vertexInputs.position,0.0,1.0);\r#define CUSTOM_VERTEX_MAIN_END\n}\r`;\n// Sideeffect\nShaderStore.ShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const postprocessVertexShader = { name, shader };\n//# sourceMappingURL=postprocess.vertex.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { IsWindowObjectExist } from \"../Misc/domManagement.js\";\nimport { Color4 } from \"../Maths/math.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { InternalTexture, InternalTextureSource } from \"../Materials/Textures/internalTexture.js\";\nimport { Effect } from \"../Materials/effect.js\";\n\nimport * as WebGPUConstants from \"./WebGPU/webgpuConstants.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { WebGPUPipelineContext } from \"./WebGPU/webgpuPipelineContext.js\";\nimport { WebGPUShaderProcessorGLSL } from \"./WebGPU/webgpuShaderProcessorsGLSL.js\";\nimport { WebGPUShaderProcessorWGSL } from \"./WebGPU/webgpuShaderProcessorsWGSL.js\";\nimport { WebGPUShaderProcessingContext } from \"./WebGPU/webgpuShaderProcessingContext.js\";\nimport { Tools } from \"../Misc/tools.js\";\nimport { WebGPUTextureHelper } from \"./WebGPU/webgpuTextureHelper.js\";\nimport { WebGPUBufferManager } from \"./WebGPU/webgpuBufferManager.js\";\nimport { WebGPUHardwareTexture } from \"./WebGPU/webgpuHardwareTexture.js\";\nimport { UniformBuffer } from \"../Materials/uniformBuffer.js\";\nimport { WebGPURenderPassWrapper } from \"./WebGPU/webgpuRenderPassWrapper.js\";\nimport { WebGPUCacheSampler } from \"./WebGPU/webgpuCacheSampler.js\";\nimport { WebGPUCacheRenderPipelineTree } from \"./WebGPU/webgpuCacheRenderPipelineTree.js\";\nimport { WebGPUStencilStateComposer } from \"./WebGPU/webgpuStencilStateComposer.js\";\nimport { WebGPUDepthCullingState } from \"./WebGPU/webgpuDepthCullingState.js\";\nimport { DrawWrapper } from \"../Materials/drawWrapper.js\";\nimport { WebGPUMaterialContext } from \"./WebGPU/webgpuMaterialContext.js\";\nimport { WebGPUDrawContext } from \"./WebGPU/webgpuDrawContext.js\";\nimport { WebGPUCacheBindGroups } from \"./WebGPU/webgpuCacheBindGroups.js\";\nimport { WebGPUClearQuad } from \"./WebGPU/webgpuClearQuad.js\";\nimport { WebGPURenderItemBlendColor, WebGPURenderItemScissor, WebGPURenderItemStencilRef, WebGPURenderItemViewport, WebGPUBundleList } from \"./WebGPU/webgpuBundleList.js\";\nimport { WebGPUTimestampQuery } from \"./WebGPU/webgpuTimestampQuery.js\";\nimport { WebGPUOcclusionQuery } from \"./WebGPU/webgpuOcclusionQuery.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { ShaderCodeInliner } from \"./Processors/shaderCodeInliner.js\";\nimport { WebGPUTintWASM } from \"./WebGPU/webgpuTintWASM.js\";\nimport { WebGPUShaderProcessor } from \"./WebGPU/webgpuShaderProcessor.js\";\nimport { ShaderLanguage } from \"../Materials/shaderLanguage.js\";\nimport { WebGPUSnapshotRendering } from \"./WebGPU/webgpuSnapshotRendering.js\";\nimport \"../ShadersWGSL/postprocess.vertex.js\";\nconst viewDescriptorSwapChainAntialiasing = {\n label: `TextureView_SwapChain_ResolveTarget`,\n dimension: WebGPUConstants.TextureDimension.E2d,\n format: undefined,\n mipLevelCount: 1,\n arrayLayerCount: 1,\n};\nconst viewDescriptorSwapChain = {\n label: `TextureView_SwapChain`,\n dimension: WebGPUConstants.TextureDimension.E2d,\n format: undefined,\n mipLevelCount: 1,\n arrayLayerCount: 1,\n};\nconst disableUniformityAnalysisMarker = \"/* disable_uniformity_analysis */\";\n/**\n * The web GPU engine class provides support for WebGPU version of babylon.js.\n * @since 5.0.0\n */\nexport class WebGPUEngine extends Engine {\n /**\n * Gets or sets the snapshot rendering mode\n */\n get snapshotRenderingMode() {\n return this._snapshotRendering.mode;\n }\n set snapshotRenderingMode(mode) {\n this._snapshotRendering.mode = mode;\n }\n /**\n * Creates a new snapshot at the next frame using the current snapshotRenderingMode\n */\n snapshotRenderingReset() {\n this._snapshotRendering.reset();\n }\n /**\n * Enables or disables the snapshot rendering mode\n * Note that the WebGL engine does not support snapshot rendering so setting the value won't have any effect for this engine\n */\n get snapshotRendering() {\n return this._snapshotRendering.enabled;\n }\n set snapshotRendering(activate) {\n this._snapshotRendering.enabled = activate;\n }\n /**\n * Sets this to true to disable the cache for the samplers. You should do it only for testing purpose!\n */\n get disableCacheSamplers() {\n return this._cacheSampler ? this._cacheSampler.disabled : false;\n }\n set disableCacheSamplers(disable) {\n if (this._cacheSampler) {\n this._cacheSampler.disabled = disable;\n }\n }\n /**\n * Sets this to true to disable the cache for the render pipelines. You should do it only for testing purpose!\n */\n get disableCacheRenderPipelines() {\n return this._cacheRenderPipeline ? this._cacheRenderPipeline.disabled : false;\n }\n set disableCacheRenderPipelines(disable) {\n if (this._cacheRenderPipeline) {\n this._cacheRenderPipeline.disabled = disable;\n }\n }\n /**\n * Sets this to true to disable the cache for the bind groups. You should do it only for testing purpose!\n */\n get disableCacheBindGroups() {\n return this._cacheBindGroups ? this._cacheBindGroups.disabled : false;\n }\n set disableCacheBindGroups(disable) {\n if (this._cacheBindGroups) {\n this._cacheBindGroups.disabled = disable;\n }\n }\n /**\n * Gets a Promise indicating if the engine can be instantiated (ie. if a WebGPU context can be found)\n */\n static get IsSupportedAsync() {\n return !navigator.gpu\n ? Promise.resolve(false)\n : navigator.gpu\n .requestAdapter()\n .then((adapter) => !!adapter, () => false)\n .catch(() => false);\n }\n /**\n * Not supported by WebGPU, you should call IsSupportedAsync instead!\n */\n static get IsSupported() {\n Logger.Warn(\"You must call IsSupportedAsync for WebGPU!\");\n return false;\n }\n /**\n * Gets a boolean indicating that the engine supports uniform buffers\n */\n get supportsUniformBuffers() {\n return true;\n }\n /** Gets the supported extensions by the WebGPU adapter */\n get supportedExtensions() {\n return this._adapterSupportedExtensions;\n }\n /** Gets the currently enabled extensions on the WebGPU device */\n get enabledExtensions() {\n return this._deviceEnabledExtensions;\n }\n /** Gets the supported limits by the WebGPU adapter */\n get supportedLimits() {\n return this._adapterSupportedLimits;\n }\n /** Gets the current limits of the WebGPU device */\n get currentLimits() {\n return this._deviceLimits;\n }\n /**\n * Returns a string describing the current engine\n */\n get description() {\n const description = this.name + this.version;\n return description;\n }\n /**\n * Returns the version of the engine\n */\n get version() {\n return 1;\n }\n /**\n * Gets an object containing information about the current engine context\n * @returns an object containing the vendor, the renderer and the version of the current engine context\n */\n getInfo() {\n return {\n vendor: this._adapterInfo.vendor || \"unknown vendor\",\n renderer: this._adapterInfo.architecture || \"unknown renderer\",\n version: this._adapterInfo.description || \"unknown version\",\n };\n }\n /**\n * (WebGPU only) True (default) to be in compatibility mode, meaning rendering all existing scenes without artifacts (same rendering than WebGL).\n * Setting the property to false will improve performances but may not work in some scenes if some precautions are not taken.\n * See https://doc.babylonjs.com/setup/support/webGPU/webGPUOptimization/webGPUNonCompatibilityMode for more details\n */\n get compatibilityMode() {\n return this._compatibilityMode;\n }\n set compatibilityMode(mode) {\n this._compatibilityMode = mode;\n }\n /** @internal */\n get currentSampleCount() {\n return this._currentRenderTarget ? this._currentRenderTarget.samples : this._mainPassSampleCount;\n }\n /**\n * Create a new instance of the gpu engine asynchronously\n * @param canvas Defines the canvas to use to display the result\n * @param options Defines the options passed to the engine to create the GPU context dependencies\n * @returns a promise that resolves with the created engine\n */\n static CreateAsync(canvas, options = {}) {\n const engine = new WebGPUEngine(canvas, options);\n return new Promise((resolve) => {\n engine.initAsync(options.glslangOptions, options.twgslOptions).then(() => resolve(engine));\n });\n }\n /**\n * Create a new instance of the gpu engine.\n * @param canvas Defines the canvas to use to display the result\n * @param options Defines the options passed to the engine to create the GPU context dependencies\n */\n constructor(canvas, options = {}) {\n var _a, _b;\n super(null, (_a = options.antialias) !== null && _a !== void 0 ? _a : true, options);\n // Page Life cycle and constants\n this._uploadEncoderDescriptor = { label: \"upload\" };\n this._renderEncoderDescriptor = { label: \"render\" };\n this._renderTargetEncoderDescriptor = { label: \"renderTarget\" };\n /** @internal */\n this._clearDepthValue = 1;\n /** @internal */\n this._clearReverseDepthValue = 0;\n /** @internal */\n this._clearStencilValue = 0;\n this._defaultSampleCount = 4; // Only supported value for now.\n this._glslang = null;\n this._tintWASM = null;\n this._adapterInfo = {\n vendor: \"\",\n architecture: \"\",\n device: \"\",\n description: \"\",\n };\n /** @internal */\n this._compiledComputeEffects = {};\n /** @internal */\n this._counters = {\n numEnableEffects: 0,\n numEnableDrawWrapper: 0,\n numBundleCreationNonCompatMode: 0,\n numBundleReuseNonCompatMode: 0,\n };\n /**\n * Counters from last frame\n */\n this.countersLastFrame = {\n numEnableEffects: 0,\n numEnableDrawWrapper: 0,\n numBundleCreationNonCompatMode: 0,\n numBundleReuseNonCompatMode: 0,\n };\n /**\n * Max number of uncaptured error messages to log\n */\n this.numMaxUncapturedErrors = 20;\n this._commandBuffers = [null, null, null];\n // Frame Buffer Life Cycle (recreated for each render target pass)\n /** @internal */\n this._currentRenderPass = null;\n /** @internal */\n this._mainRenderPassWrapper = new WebGPURenderPassWrapper();\n /** @internal */\n this._rttRenderPassWrapper = new WebGPURenderPassWrapper();\n /** @internal */\n this._pendingDebugCommands = [];\n /** @internal */\n this._onAfterUnbindFrameBufferObservable = new Observable();\n this._currentOverrideVertexBuffers = null;\n this._currentIndexBuffer = null;\n this._colorWriteLocal = true;\n this._forceEnableEffect = false;\n // TODO WEBGPU remove those variables when code stabilized\n /** @internal */\n this.dbgShowShaderCode = false;\n /** @internal */\n this.dbgSanityChecks = true;\n /** @internal */\n this.dbgVerboseLogsForFirstFrames = false;\n /** @internal */\n this.dbgVerboseLogsNumFrames = 10;\n /** @internal */\n this.dbgLogIfNotDrawWrapper = true;\n /** @internal */\n this.dbgShowEmptyEnableEffectCalls = true;\n /**\n * Indicates if the z range in NDC space is 0..1 (value: true) or -1..1 (value: false)\n */\n this.isNDCHalfZRange = true;\n /**\n * Indicates that the origin of the texture/framebuffer space is the bottom left corner. If false, the origin is top left\n */\n this.hasOriginBottomLeft = false;\n //------------------------------------------------------------------------------\n // Dynamic WebGPU States\n //------------------------------------------------------------------------------\n // index 0 is for main render pass, 1 for RTT render pass\n this._viewportsCurrent = [\n { x: 0, y: 0, w: 0, h: 0 },\n { x: 0, y: 0, w: 0, h: 0 },\n ];\n this._scissorsCurrent = [\n { x: 0, y: 0, w: 0, h: 0 },\n { x: 0, y: 0, w: 0, h: 0 },\n ];\n this._scissorCached = { x: 0, y: 0, z: 0, w: 0 };\n this._stencilRefsCurrent = [-1, -1];\n this._blendColorsCurrent = [\n [null, null, null, null],\n [null, null, null, null],\n ];\n this._name = \"WebGPU\";\n options.deviceDescriptor = options.deviceDescriptor || {};\n options.enableGPUDebugMarkers = (_b = options.enableGPUDebugMarkers) !== null && _b !== void 0 ? _b : false;\n Logger.Log(`Babylon.js v${Engine.Version} - ${this.description} engine`);\n if (!navigator.gpu) {\n Logger.Error(\"WebGPU is not supported by your browser.\");\n return;\n }\n options.swapChainFormat = options.swapChainFormat || navigator.gpu.getPreferredCanvasFormat();\n this._isWebGPU = true;\n this._shaderPlatformName = \"WEBGPU\";\n this._renderingCanvas = canvas;\n this._options = options;\n this._mainPassSampleCount = options.antialias ? this._defaultSampleCount : 1;\n this._setupMobileChecks();\n this._sharedInit(canvas);\n this._shaderProcessor = new WebGPUShaderProcessorGLSL();\n this._shaderProcessorWGSL = new WebGPUShaderProcessorWGSL();\n }\n //------------------------------------------------------------------------------\n // Initialization\n //------------------------------------------------------------------------------\n /**\n * Initializes the WebGPU context and dependencies.\n * @param glslangOptions Defines the GLSLang compiler options if necessary\n * @param twgslOptions Defines the Twgsl compiler options if necessary\n * @returns a promise notifying the readiness of the engine.\n */\n initAsync(glslangOptions, twgslOptions) {\n var _a;\n return this._initGlslang(glslangOptions !== null && glslangOptions !== void 0 ? glslangOptions : (_a = this._options) === null || _a === void 0 ? void 0 : _a.glslangOptions)\n .then((glslang) => {\n var _a;\n this._glslang = glslang;\n this._tintWASM = WebGPUEngine.UseTWGSL ? new WebGPUTintWASM() : null;\n return this._tintWASM\n ? this._tintWASM.initTwgsl(twgslOptions !== null && twgslOptions !== void 0 ? twgslOptions : (_a = this._options) === null || _a === void 0 ? void 0 : _a.twgslOptions).then(() => {\n return navigator.gpu.requestAdapter(this._options);\n }, (msg) => {\n Logger.Error(\"Can not initialize twgsl!\");\n Logger.Error(msg);\n throw Error(\"WebGPU initializations stopped.\");\n })\n : navigator.gpu.requestAdapter(this._options);\n }, (msg) => {\n Logger.Error(\"Can not initialize glslang!\");\n Logger.Error(msg);\n throw Error(\"WebGPU initializations stopped.\");\n })\n .then((adapter) => {\n var _a, _b, _c;\n if (!adapter) {\n throw \"Could not retrieve a WebGPU adapter (adapter is null).\";\n }\n else {\n this._adapter = adapter;\n this._adapterSupportedExtensions = [];\n (_a = this._adapter.features) === null || _a === void 0 ? void 0 : _a.forEach((feature) => this._adapterSupportedExtensions.push(feature));\n this._adapterSupportedLimits = this._adapter.limits;\n this._adapter.requestAdapterInfo().then((adapterInfo) => {\n this._adapterInfo = adapterInfo;\n });\n const deviceDescriptor = (_b = this._options.deviceDescriptor) !== null && _b !== void 0 ? _b : {};\n const requiredFeatures = (_c = deviceDescriptor === null || deviceDescriptor === void 0 ? void 0 : deviceDescriptor.requiredFeatures) !== null && _c !== void 0 ? _c : (this._options.enableAllFeatures ? this._adapterSupportedExtensions : undefined);\n if (requiredFeatures) {\n const requestedExtensions = requiredFeatures;\n const validExtensions = [];\n for (const extension of requestedExtensions) {\n if (this._adapterSupportedExtensions.indexOf(extension) !== -1) {\n validExtensions.push(extension);\n }\n }\n deviceDescriptor.requiredFeatures = validExtensions;\n }\n if (this._options.setMaximumLimits && !deviceDescriptor.requiredLimits) {\n deviceDescriptor.requiredLimits = {};\n for (const name in this._adapterSupportedLimits) {\n deviceDescriptor.requiredLimits[name] = this._adapterSupportedLimits[name];\n }\n }\n return this._adapter.requestDevice(deviceDescriptor);\n }\n })\n .then((device) => {\n var _a, _b;\n this._device = device;\n this._deviceEnabledExtensions = [];\n (_a = this._device.features) === null || _a === void 0 ? void 0 : _a.forEach((feature) => this._deviceEnabledExtensions.push(feature));\n this._deviceLimits = device.limits;\n let numUncapturedErrors = -1;\n this._device.addEventListener(\"uncapturederror\", (event) => {\n if (++numUncapturedErrors < this.numMaxUncapturedErrors) {\n Logger.Warn(`WebGPU uncaptured error (${numUncapturedErrors + 1}): ${event.error} - ${event.error.message}`);\n }\n else if (numUncapturedErrors++ === this.numMaxUncapturedErrors) {\n Logger.Warn(`WebGPU uncaptured error: too many warnings (${this.numMaxUncapturedErrors}), no more warnings will be reported to the console for this engine.`);\n }\n });\n if (!this._doNotHandleContextLost) {\n (_b = this._device.lost) === null || _b === void 0 ? void 0 : _b.then((info) => {\n if (this._isDisposed) {\n return;\n }\n this._contextWasLost = true;\n Logger.Warn(\"WebGPU context lost. \" + info);\n this.onContextLostObservable.notifyObservers(this);\n this._restoreEngineAfterContextLost(this.initAsync.bind(this));\n });\n }\n }, (e) => {\n Logger.Error(\"Could not retrieve a WebGPU device.\");\n Logger.Error(e);\n })\n .then(() => {\n this._bufferManager = new WebGPUBufferManager(this._device);\n this._textureHelper = new WebGPUTextureHelper(this._device, this._glslang, this._tintWASM, this._bufferManager, this._deviceEnabledExtensions);\n this._cacheSampler = new WebGPUCacheSampler(this._device);\n this._cacheBindGroups = new WebGPUCacheBindGroups(this._device, this._cacheSampler, this);\n this._timestampQuery = new WebGPUTimestampQuery(this._device, this._bufferManager);\n this._occlusionQuery = this._device.createQuerySet ? new WebGPUOcclusionQuery(this, this._device, this._bufferManager) : undefined;\n this._bundleList = new WebGPUBundleList(this._device);\n this._bundleListRenderTarget = new WebGPUBundleList(this._device);\n this._snapshotRendering = new WebGPUSnapshotRendering(this, this._snapshotRenderingMode, this._bundleList, this._bundleListRenderTarget);\n this._ubInvertY = this._bufferManager.createBuffer(new Float32Array([-1, 0]), WebGPUConstants.BufferUsage.Uniform | WebGPUConstants.BufferUsage.CopyDst);\n this._ubDontInvertY = this._bufferManager.createBuffer(new Float32Array([1, 0]), WebGPUConstants.BufferUsage.Uniform | WebGPUConstants.BufferUsage.CopyDst);\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n console.log(\"%c frame #\" + this._count + \" - begin\", \"background: #ffff00\");\n }\n }\n this._uploadEncoder = this._device.createCommandEncoder(this._uploadEncoderDescriptor);\n this._renderEncoder = this._device.createCommandEncoder(this._renderEncoderDescriptor);\n this._renderTargetEncoder = this._device.createCommandEncoder(this._renderTargetEncoderDescriptor);\n this._emptyVertexBuffer = new VertexBuffer(this, [0], \"\", false, false, 1, false, 0, 1);\n this._initializeLimits();\n this._cacheRenderPipeline = new WebGPUCacheRenderPipelineTree(this._device, this._emptyVertexBuffer, !this._caps.textureFloatLinearFiltering);\n this._depthCullingState = new WebGPUDepthCullingState(this._cacheRenderPipeline);\n this._stencilStateComposer = new WebGPUStencilStateComposer(this._cacheRenderPipeline);\n this._stencilStateComposer.stencilGlobal = this._stencilState;\n this._depthCullingState.depthTest = true;\n this._depthCullingState.depthFunc = 515;\n this._depthCullingState.depthMask = true;\n this._textureHelper.setCommandEncoder(this._uploadEncoder);\n this._clearQuad = new WebGPUClearQuad(this._device, this, this._emptyVertexBuffer);\n this._defaultDrawContext = this.createDrawContext();\n this._currentDrawContext = this._defaultDrawContext;\n this._defaultMaterialContext = this.createMaterialContext();\n this._currentMaterialContext = this._defaultMaterialContext;\n this._initializeContextAndSwapChain();\n this._initializeMainAttachments();\n this.resize();\n })\n .catch((e) => {\n Logger.Error(\"Can not create WebGPU Device and/or context.\");\n Logger.Error(e);\n if (console.trace) {\n console.trace();\n }\n });\n }\n _initGlslang(glslangOptions) {\n glslangOptions = glslangOptions || {};\n glslangOptions = Object.assign(Object.assign({}, WebGPUEngine._GLSLslangDefaultOptions), glslangOptions);\n if (glslangOptions.glslang) {\n return Promise.resolve(glslangOptions.glslang);\n }\n if (self.glslang) {\n return self.glslang(glslangOptions.wasmPath);\n }\n if (glslangOptions.jsPath && glslangOptions.wasmPath) {\n if (IsWindowObjectExist()) {\n return Tools.LoadScriptAsync(glslangOptions.jsPath).then(() => {\n return self.glslang(glslangOptions.wasmPath);\n });\n }\n else {\n importScripts(glslangOptions.jsPath);\n return self.glslang(glslangOptions.wasmPath);\n }\n }\n return Promise.reject(\"gslang is not available.\");\n }\n _initializeLimits() {\n // Init caps\n // TODO WEBGPU Real Capability check once limits will be working.\n this._caps = {\n maxTexturesImageUnits: this._deviceLimits.maxSampledTexturesPerShaderStage,\n maxVertexTextureImageUnits: this._deviceLimits.maxSampledTexturesPerShaderStage,\n maxCombinedTexturesImageUnits: this._deviceLimits.maxSampledTexturesPerShaderStage * 2,\n maxTextureSize: this._deviceLimits.maxTextureDimension2D,\n maxCubemapTextureSize: this._deviceLimits.maxTextureDimension2D,\n maxRenderTextureSize: this._deviceLimits.maxTextureDimension2D,\n maxVertexAttribs: this._deviceLimits.maxVertexAttributes,\n maxVaryingVectors: this._deviceLimits.maxInterStageShaderVariables,\n maxFragmentUniformVectors: Math.floor(this._deviceLimits.maxUniformBufferBindingSize / 4),\n maxVertexUniformVectors: Math.floor(this._deviceLimits.maxUniformBufferBindingSize / 4),\n standardDerivatives: true,\n astc: (this._deviceEnabledExtensions.indexOf(WebGPUConstants.FeatureName.TextureCompressionASTC) >= 0 ? true : undefined),\n s3tc: (this._deviceEnabledExtensions.indexOf(WebGPUConstants.FeatureName.TextureCompressionBC) >= 0 ? true : undefined),\n pvrtc: null,\n etc1: null,\n etc2: (this._deviceEnabledExtensions.indexOf(WebGPUConstants.FeatureName.TextureCompressionETC2) >= 0 ? true : undefined),\n bptc: this._deviceEnabledExtensions.indexOf(WebGPUConstants.FeatureName.TextureCompressionBC) >= 0 ? true : undefined,\n maxAnisotropy: 16,\n uintIndices: true,\n fragmentDepthSupported: true,\n highPrecisionShaderSupported: true,\n colorBufferFloat: true,\n textureFloat: true,\n textureFloatLinearFiltering: this._deviceEnabledExtensions.indexOf(WebGPUConstants.FeatureName.Float32Filterable) >= 0,\n textureFloatRender: true,\n textureHalfFloat: true,\n textureHalfFloatLinearFiltering: true,\n textureHalfFloatRender: true,\n textureLOD: true,\n texelFetch: true,\n drawBuffersExtension: true,\n depthTextureExtension: true,\n vertexArrayObject: false,\n instancedArrays: true,\n timerQuery: typeof BigUint64Array !== \"undefined\" && this._deviceEnabledExtensions.indexOf(WebGPUConstants.FeatureName.TimestampQuery) !== -1 ? true : undefined,\n supportOcclusionQuery: typeof BigUint64Array !== \"undefined\",\n canUseTimestampForTimerQuery: true,\n multiview: false,\n oculusMultiview: false,\n parallelShaderCompile: undefined,\n blendMinMax: true,\n maxMSAASamples: 4,\n canUseGLInstanceID: true,\n canUseGLVertexID: true,\n supportComputeShaders: true,\n supportSRGBBuffers: true,\n supportTransformFeedbacks: false,\n textureMaxLevel: true,\n texture2DArrayMaxLayerCount: this._deviceLimits.maxTextureArrayLayers,\n disableMorphTargetTexture: false,\n };\n this._caps.parallelShaderCompile = null;\n this._features = {\n forceBitmapOverHTMLImageElement: true,\n supportRenderAndCopyToLodForFloatTextures: true,\n supportDepthStencilTexture: true,\n supportShadowSamplers: true,\n uniformBufferHardCheckMatrix: false,\n allowTexturePrefiltering: true,\n trackUbosInFrame: true,\n checkUbosContentBeforeUpload: true,\n supportCSM: true,\n basisNeedsPOT: false,\n support3DTextures: true,\n needTypeSuffixInShaderConstants: true,\n supportMSAA: true,\n supportSSAO2: true,\n supportExtendedTextureFormats: true,\n supportSwitchCaseInShader: true,\n supportSyncTextureRead: false,\n needsInvertingBitmap: false,\n useUBOBindingCache: false,\n needShaderCodeInlining: true,\n needToAlwaysBindUniformBuffers: true,\n supportRenderPasses: true,\n supportSpriteInstancing: true,\n _collectUbosUpdatedInFrame: false,\n };\n }\n _initializeContextAndSwapChain() {\n if (!this._renderingCanvas) {\n throw \"The rendering canvas has not been set!\";\n }\n this._context = this._renderingCanvas.getContext(\"webgpu\");\n this._configureContext();\n this._colorFormat = this._options.swapChainFormat;\n this._mainRenderPassWrapper.colorAttachmentGPUTextures = [new WebGPUHardwareTexture()];\n this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format = this._colorFormat;\n }\n // Set default values as WebGL with depth and stencil attachment for the broadest Compat.\n _initializeMainAttachments() {\n if (!this._bufferManager) {\n return;\n }\n this.flushFramebuffer(false);\n this._mainTextureExtends = {\n width: this.getRenderWidth(true),\n height: this.getRenderHeight(true),\n depthOrArrayLayers: 1,\n };\n const bufferDataUpdate = new Float32Array([this.getRenderHeight(true)]);\n this._bufferManager.setSubData(this._ubInvertY, 4, bufferDataUpdate);\n this._bufferManager.setSubData(this._ubDontInvertY, 4, bufferDataUpdate);\n let mainColorAttachments;\n if (this._options.antialias) {\n const mainTextureDescriptor = {\n label: `Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,\n size: this._mainTextureExtends,\n mipLevelCount: 1,\n sampleCount: this._mainPassSampleCount,\n dimension: WebGPUConstants.TextureDimension.E2d,\n format: this._options.swapChainFormat,\n usage: WebGPUConstants.TextureUsage.RenderAttachment,\n };\n if (this._mainTexture) {\n this._textureHelper.releaseTexture(this._mainTexture);\n }\n this._mainTexture = this._device.createTexture(mainTextureDescriptor);\n mainColorAttachments = [\n {\n view: this._mainTexture.createView({\n label: \"TextureView_MainColor_antialiasing\",\n dimension: WebGPUConstants.TextureDimension.E2d,\n format: this._options.swapChainFormat,\n mipLevelCount: 1,\n arrayLayerCount: 1,\n }),\n clearValue: new Color4(0, 0, 0, 1),\n loadOp: WebGPUConstants.LoadOp.Clear,\n storeOp: WebGPUConstants.StoreOp.Store, // don't use StoreOp.Discard, else using several cameras with different viewports or using scissors will fail because we call beginRenderPass / endPass several times for the same color attachment!\n },\n ];\n }\n else {\n mainColorAttachments = [\n {\n view: undefined,\n clearValue: new Color4(0, 0, 0, 1),\n loadOp: WebGPUConstants.LoadOp.Clear,\n storeOp: WebGPUConstants.StoreOp.Store,\n },\n ];\n }\n this._mainRenderPassWrapper.depthTextureFormat = this.isStencilEnable ? WebGPUConstants.TextureFormat.Depth24PlusStencil8 : WebGPUConstants.TextureFormat.Depth32Float;\n this._setDepthTextureFormat(this._mainRenderPassWrapper);\n const depthTextureDescriptor = {\n label: `Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,\n size: this._mainTextureExtends,\n mipLevelCount: 1,\n sampleCount: this._mainPassSampleCount,\n dimension: WebGPUConstants.TextureDimension.E2d,\n format: this._mainRenderPassWrapper.depthTextureFormat,\n usage: WebGPUConstants.TextureUsage.RenderAttachment,\n };\n if (this._depthTexture) {\n this._textureHelper.releaseTexture(this._depthTexture);\n }\n this._depthTexture = this._device.createTexture(depthTextureDescriptor);\n const mainDepthAttachment = {\n view: this._depthTexture.createView({\n label: `TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,\n dimension: WebGPUConstants.TextureDimension.E2d,\n format: this._depthTexture.format,\n mipLevelCount: 1,\n arrayLayerCount: 1,\n }),\n depthClearValue: this._clearDepthValue,\n depthLoadOp: WebGPUConstants.LoadOp.Clear,\n depthStoreOp: WebGPUConstants.StoreOp.Store,\n stencilClearValue: this._clearStencilValue,\n stencilLoadOp: !this.isStencilEnable ? undefined : WebGPUConstants.LoadOp.Clear,\n stencilStoreOp: !this.isStencilEnable ? undefined : WebGPUConstants.StoreOp.Store,\n };\n this._mainRenderPassWrapper.renderPassDescriptor = {\n colorAttachments: mainColorAttachments,\n depthStencilAttachment: mainDepthAttachment,\n };\n }\n _configureContext() {\n this._context.configure({\n device: this._device,\n format: this._options.swapChainFormat,\n usage: WebGPUConstants.TextureUsage.RenderAttachment | WebGPUConstants.TextureUsage.CopySrc,\n alphaMode: this.premultipliedAlpha ? WebGPUConstants.CanvasAlphaMode.Premultiplied : WebGPUConstants.CanvasAlphaMode.Opaque,\n });\n }\n /**\n * Force a specific size of the canvas\n * @param width defines the new canvas' width\n * @param height defines the new canvas' height\n * @param forceSetSize true to force setting the sizes of the underlying canvas\n * @returns true if the size was changed\n */\n setSize(width, height, forceSetSize = false) {\n if (!super.setSize(width, height, forceSetSize)) {\n return false;\n }\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n console.log(\"frame #\" + this._count + \" - setSize called -\", width, height);\n }\n }\n this._initializeMainAttachments();\n if (this.snapshotRendering) {\n // reset snapshot rendering so that the next frame will record a new list of bundles\n this.snapshotRenderingReset();\n }\n return true;\n }\n /**\n * @internal\n */\n _getShaderProcessor(shaderLanguage) {\n if (shaderLanguage === ShaderLanguage.WGSL) {\n return this._shaderProcessorWGSL;\n }\n return this._shaderProcessor;\n }\n /**\n * @internal\n */\n _getShaderProcessingContext(shaderLanguage) {\n return new WebGPUShaderProcessingContext(shaderLanguage);\n }\n //------------------------------------------------------------------------------\n // Static Pipeline WebGPU States\n //------------------------------------------------------------------------------\n /** @internal */\n applyStates() {\n this._stencilStateComposer.apply();\n this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend);\n }\n /**\n * Force the entire cache to be cleared\n * You should not have to use this function unless your engine needs to share the WebGPU context with another engine\n * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)\n */\n wipeCaches(bruteForce) {\n if (this.preventCacheWipeBetweenFrames && !bruteForce) {\n return;\n }\n //this._currentEffect = null; // can't reset _currentEffect, else some crashes can occur (for eg in ProceduralTexture which calls bindFrameBuffer (which calls wipeCaches) after having called enableEffect and before drawing into the texture)\n // _forceEnableEffect = true assumes the role of _currentEffect = null\n this._forceEnableEffect = true;\n this._currentIndexBuffer = null;\n this._currentOverrideVertexBuffers = null;\n this._cacheRenderPipeline.setBuffers(null, null, null);\n if (bruteForce) {\n this._stencilStateComposer.reset();\n this._depthCullingState.reset();\n this._depthCullingState.depthFunc = 515;\n this._alphaState.reset();\n this._alphaMode = 1;\n this._alphaEquation = 0;\n this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters, this._alphaState._blendEquationParameters);\n this._cacheRenderPipeline.setAlphaBlendEnabled(false);\n this.setColorWrite(true);\n }\n this._cachedVertexBuffers = null;\n this._cachedIndexBuffer = null;\n this._cachedEffectForVertexBuffers = null;\n }\n /**\n * Enable or disable color writing\n * @param enable defines the state to set\n */\n setColorWrite(enable) {\n this._colorWriteLocal = enable;\n this._cacheRenderPipeline.setWriteMask(enable ? 0xf : 0);\n }\n /**\n * Gets a boolean indicating if color writing is enabled\n * @returns the current color writing state\n */\n getColorWrite() {\n return this._colorWriteLocal;\n }\n _resetCurrentViewport(index) {\n this._viewportsCurrent[index].x = 0;\n this._viewportsCurrent[index].y = 0;\n this._viewportsCurrent[index].w = 0;\n this._viewportsCurrent[index].h = 0;\n }\n _mustUpdateViewport(renderPass) {\n const index = renderPass === this._mainRenderPassWrapper.renderPass ? 0 : 1;\n const x = this._viewportCached.x, y = this._viewportCached.y, w = this._viewportCached.z, h = this._viewportCached.w;\n const update = this._viewportsCurrent[index].x !== x || this._viewportsCurrent[index].y !== y || this._viewportsCurrent[index].w !== w || this._viewportsCurrent[index].h !== h;\n if (update) {\n this._viewportsCurrent[index].x = this._viewportCached.x;\n this._viewportsCurrent[index].y = this._viewportCached.y;\n this._viewportsCurrent[index].w = this._viewportCached.z;\n this._viewportsCurrent[index].h = this._viewportCached.w;\n }\n return update;\n }\n _applyViewport(renderPass) {\n let y = Math.floor(this._viewportCached.y);\n const h = Math.floor(this._viewportCached.w);\n if (!this._currentRenderTarget) {\n y = this.getRenderHeight(true) - y - h;\n }\n renderPass.setViewport(Math.floor(this._viewportCached.x), y, Math.floor(this._viewportCached.z), h, 0, 1);\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n console.log(\"frame #\" + this._count + \" - viewport applied - (\", this._viewportCached.x, this._viewportCached.y, this._viewportCached.z, this._viewportCached.w, \") current pass is main pass=\" + (renderPass === this._mainRenderPassWrapper.renderPass));\n }\n }\n }\n /**\n * @internal\n */\n _viewport(x, y, width, height) {\n this._viewportCached.x = x;\n this._viewportCached.y = y;\n this._viewportCached.z = width;\n this._viewportCached.w = height;\n }\n _resetCurrentScissor(index) {\n this._scissorsCurrent[index].x = 0;\n this._scissorsCurrent[index].y = 0;\n this._scissorsCurrent[index].w = 0;\n this._scissorsCurrent[index].h = 0;\n }\n _mustUpdateScissor(renderPass) {\n const index = renderPass === this._mainRenderPassWrapper.renderPass ? 0 : 1;\n const x = this._scissorCached.x, y = this._scissorCached.y, w = this._scissorCached.z, h = this._scissorCached.w;\n const update = this._scissorsCurrent[index].x !== x || this._scissorsCurrent[index].y !== y || this._scissorsCurrent[index].w !== w || this._scissorsCurrent[index].h !== h;\n if (update) {\n this._scissorsCurrent[index].x = this._scissorCached.x;\n this._scissorsCurrent[index].y = this._scissorCached.y;\n this._scissorsCurrent[index].w = this._scissorCached.z;\n this._scissorsCurrent[index].h = this._scissorCached.w;\n }\n return update;\n }\n _applyScissor(renderPass) {\n renderPass.setScissorRect(this._scissorCached.x, this._currentRenderTarget ? this._scissorCached.y : this.getRenderHeight() - this._scissorCached.w - this._scissorCached.y, this._scissorCached.z, this._scissorCached.w);\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n console.log(\"frame #\" + this._count + \" - scissor applied - (\", this._scissorCached.x, this._scissorCached.y, this._scissorCached.z, this._scissorCached.w, \") current pass is main pass=\" + (renderPass === this._mainRenderPassWrapper.renderPass));\n }\n }\n }\n _scissorIsActive() {\n return this._scissorCached.x !== 0 || this._scissorCached.y !== 0 || this._scissorCached.z !== 0 || this._scissorCached.w !== 0;\n }\n enableScissor(x, y, width, height) {\n this._scissorCached.x = x;\n this._scissorCached.y = y;\n this._scissorCached.z = width;\n this._scissorCached.w = height;\n }\n disableScissor() {\n this._scissorCached.x = 0;\n this._scissorCached.y = 0;\n this._scissorCached.z = 0;\n this._scissorCached.w = 0;\n this._resetCurrentScissor(0);\n this._resetCurrentScissor(1);\n }\n _resetCurrentStencilRef(index) {\n this._stencilRefsCurrent[index] = -1;\n }\n _mustUpdateStencilRef(renderPass) {\n const index = renderPass === this._mainRenderPassWrapper.renderPass ? 0 : 1;\n const update = this._stencilStateComposer.funcRef !== this._stencilRefsCurrent[index];\n if (update) {\n this._stencilRefsCurrent[index] = this._stencilStateComposer.funcRef;\n }\n return update;\n }\n /**\n * @internal\n */\n _applyStencilRef(renderPass) {\n var _a;\n renderPass.setStencilReference((_a = this._stencilStateComposer.funcRef) !== null && _a !== void 0 ? _a : 0);\n }\n _resetCurrentColorBlend(index) {\n this._blendColorsCurrent[index][0] = this._blendColorsCurrent[index][1] = this._blendColorsCurrent[index][2] = this._blendColorsCurrent[index][3] = null;\n }\n _mustUpdateBlendColor(renderPass) {\n const index = renderPass === this._mainRenderPassWrapper.renderPass ? 0 : 1;\n const colorBlend = this._alphaState._blendConstants;\n const update = colorBlend[0] !== this._blendColorsCurrent[index][0] ||\n colorBlend[1] !== this._blendColorsCurrent[index][1] ||\n colorBlend[2] !== this._blendColorsCurrent[index][2] ||\n colorBlend[3] !== this._blendColorsCurrent[index][3];\n if (update) {\n this._blendColorsCurrent[index][0] = colorBlend[0];\n this._blendColorsCurrent[index][1] = colorBlend[1];\n this._blendColorsCurrent[index][2] = colorBlend[2];\n this._blendColorsCurrent[index][3] = colorBlend[3];\n }\n return update;\n }\n _applyBlendColor(renderPass) {\n renderPass.setBlendConstant(this._alphaState._blendConstants);\n }\n /**\n * Clear the current render buffer or the current render target (if any is set up)\n * @param color defines the color to use\n * @param backBuffer defines if the back buffer must be cleared\n * @param depth defines if the depth buffer must be cleared\n * @param stencil defines if the stencil buffer must be cleared\n */\n clear(color, backBuffer, depth, stencil = false) {\n // Some PGs are using color3...\n if (color && color.a === undefined) {\n color.a = 1;\n }\n const hasScissor = this._scissorIsActive();\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n console.log(\"frame #\" + this._count + \" - clear called - backBuffer=\", backBuffer, \" depth=\", depth, \" stencil=\", stencil, \" scissor is active=\", hasScissor);\n }\n }\n // We need to recreate the render pass so that the new parameters for clear color / depth / stencil are taken into account\n if (this._currentRenderTarget) {\n if (hasScissor) {\n if (!this._rttRenderPassWrapper.renderPass) {\n this._startRenderTargetRenderPass(this._currentRenderTarget, false, backBuffer ? color : null, depth, stencil);\n }\n if (!this.compatibilityMode) {\n this._bundleListRenderTarget.addItem(new WebGPURenderItemScissor(this._scissorCached.x, this._scissorCached.y, this._scissorCached.z, this._scissorCached.w));\n }\n else {\n this._applyScissor(this._currentRenderPass);\n }\n this._clearFullQuad(backBuffer ? color : null, depth, stencil);\n }\n else {\n if (this._currentRenderPass) {\n this._endRenderTargetRenderPass();\n }\n this._startRenderTargetRenderPass(this._currentRenderTarget, true, backBuffer ? color : null, depth, stencil);\n }\n }\n else {\n if (!this._mainRenderPassWrapper.renderPass || !hasScissor) {\n this._startMainRenderPass(!hasScissor, backBuffer ? color : null, depth, stencil);\n }\n if (hasScissor) {\n if (!this.compatibilityMode) {\n this._bundleList.addItem(new WebGPURenderItemScissor(this._scissorCached.x, this._scissorCached.y, this._scissorCached.z, this._scissorCached.w));\n }\n else {\n this._applyScissor(this._currentRenderPass);\n }\n this._clearFullQuad(backBuffer ? color : null, depth, stencil);\n }\n }\n }\n _clearFullQuad(clearColor, clearDepth, clearStencil) {\n var _a, _b, _c;\n const renderPass = !this.compatibilityMode ? null : this._getCurrentRenderPass();\n const renderPassIndex = this._getCurrentRenderPassIndex();\n const bundleList = renderPassIndex === 0 ? this._bundleList : this._bundleListRenderTarget;\n this._clearQuad.setColorFormat(this._colorFormat);\n this._clearQuad.setDepthStencilFormat(this._depthTextureFormat);\n this._clearQuad.setMRTAttachments((_a = this._cacheRenderPipeline.mrtAttachments) !== null && _a !== void 0 ? _a : [], (_b = this._cacheRenderPipeline.mrtTextureArray) !== null && _b !== void 0 ? _b : [], this._cacheRenderPipeline.mrtTextureCount);\n if (!this.compatibilityMode) {\n bundleList.addItem(new WebGPURenderItemStencilRef(this._clearStencilValue));\n }\n else {\n renderPass.setStencilReference(this._clearStencilValue);\n }\n const bundle = this._clearQuad.clear(renderPass, clearColor, clearDepth, clearStencil, this.currentSampleCount);\n if (!this.compatibilityMode) {\n bundleList.addBundle(bundle);\n bundleList.addItem(new WebGPURenderItemStencilRef((_c = this._stencilStateComposer.funcRef) !== null && _c !== void 0 ? _c : 0));\n this._reportDrawCall();\n }\n else {\n this._applyStencilRef(renderPass);\n }\n }\n //------------------------------------------------------------------------------\n // Vertex/Index/Storage Buffers\n //------------------------------------------------------------------------------\n /**\n * Creates a vertex buffer\n * @param data the data for the vertex buffer\n * @returns the new buffer\n */\n createVertexBuffer(data) {\n let view;\n if (data instanceof Array) {\n view = new Float32Array(data);\n }\n else if (data instanceof ArrayBuffer) {\n view = new Uint8Array(data);\n }\n else {\n view = data;\n }\n const dataBuffer = this._bufferManager.createBuffer(view, WebGPUConstants.BufferUsage.Vertex | WebGPUConstants.BufferUsage.CopyDst);\n return dataBuffer;\n }\n /**\n * Creates a vertex buffer\n * @param data the data for the dynamic vertex buffer\n * @returns the new buffer\n */\n createDynamicVertexBuffer(data) {\n return this.createVertexBuffer(data);\n }\n /**\n * Creates a new index buffer\n * @param indices defines the content of the index buffer\n * @returns a new buffer\n */\n createIndexBuffer(indices) {\n let is32Bits = true;\n let view;\n if (indices instanceof Uint32Array || indices instanceof Int32Array) {\n view = indices;\n }\n else if (indices instanceof Uint16Array) {\n view = indices;\n is32Bits = false;\n }\n else {\n if (indices.length > 65535) {\n view = new Uint32Array(indices);\n }\n else {\n view = new Uint16Array(indices);\n is32Bits = false;\n }\n }\n const dataBuffer = this._bufferManager.createBuffer(view, WebGPUConstants.BufferUsage.Index | WebGPUConstants.BufferUsage.CopyDst);\n dataBuffer.is32Bits = is32Bits;\n return dataBuffer;\n }\n /**\n * @internal\n */\n _createBuffer(data, creationFlags) {\n let view;\n if (data instanceof Array) {\n view = new Float32Array(data);\n }\n else if (data instanceof ArrayBuffer) {\n view = new Uint8Array(data);\n }\n else {\n view = data;\n }\n let flags = 0;\n if (creationFlags & 1) {\n flags |= WebGPUConstants.BufferUsage.CopySrc;\n }\n if (creationFlags & 2) {\n flags |= WebGPUConstants.BufferUsage.CopyDst;\n }\n if (creationFlags & 4) {\n flags |= WebGPUConstants.BufferUsage.Uniform;\n }\n if (creationFlags & 8) {\n flags |= WebGPUConstants.BufferUsage.Vertex;\n }\n if (creationFlags & 16) {\n flags |= WebGPUConstants.BufferUsage.Index;\n }\n if (creationFlags & 32) {\n flags |= WebGPUConstants.BufferUsage.Storage;\n }\n return this._bufferManager.createBuffer(view, flags);\n }\n /**\n * @internal\n */\n bindBuffersDirectly() {\n throw \"Not implemented on WebGPU\";\n }\n /**\n * @internal\n */\n updateAndBindInstancesBuffer() {\n throw \"Not implemented on WebGPU\";\n }\n /**\n * Bind a list of vertex buffers with the engine\n * @param vertexBuffers defines the list of vertex buffers to bind\n * @param indexBuffer defines the index buffer to bind\n * @param effect defines the effect associated with the vertex buffers\n * @param overrideVertexBuffers defines optional list of avertex buffers that overrides the entries in vertexBuffers\n */\n bindBuffers(vertexBuffers, indexBuffer, effect, overrideVertexBuffers) {\n this._currentIndexBuffer = indexBuffer;\n this._currentOverrideVertexBuffers = overrideVertexBuffers !== null && overrideVertexBuffers !== void 0 ? overrideVertexBuffers : null;\n this._cacheRenderPipeline.setBuffers(vertexBuffers, indexBuffer, this._currentOverrideVertexBuffers);\n }\n /**\n * @internal\n */\n _releaseBuffer(buffer) {\n return this._bufferManager.releaseBuffer(buffer);\n }\n //------------------------------------------------------------------------------\n // Effects\n //------------------------------------------------------------------------------\n /**\n * Create a new effect (used to store vertex/fragment shaders)\n * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)\n * @param attributesNamesOrOptions defines either a list of attribute names or an IEffectCreationOptions object\n * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use\n * @param samplers defines an array of string used to represent textures\n * @param defines defines the string containing the defines to use to compile the shaders\n * @param fallbacks defines the list of potential fallbacks to use if shader compilation fails\n * @param onCompiled defines a function to call when the effect creation is successful\n * @param onError defines a function to call when the effect creation has failed\n * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)\n * @param shaderLanguage the language the shader is written in (default: GLSL)\n * @returns the new Effect\n */\n createEffect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters, shaderLanguage = ShaderLanguage.GLSL) {\n var _a;\n const vertex = baseName.vertexElement || baseName.vertex || baseName.vertexToken || baseName.vertexSource || baseName;\n const fragment = baseName.fragmentElement || baseName.fragment || baseName.fragmentToken || baseName.fragmentSource || baseName;\n const globalDefines = this._getGlobalDefines();\n let fullDefines = (_a = defines !== null && defines !== void 0 ? defines : attributesNamesOrOptions.defines) !== null && _a !== void 0 ? _a : \"\";\n if (globalDefines) {\n fullDefines += \"\\n\" + globalDefines;\n }\n const name = vertex + \"+\" + fragment + \"@\" + fullDefines;\n if (this._compiledEffects[name]) {\n const compiledEffect = this._compiledEffects[name];\n if (onCompiled && compiledEffect.isReady()) {\n onCompiled(compiledEffect);\n }\n return compiledEffect;\n }\n const effect = new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters, name, shaderLanguage);\n this._compiledEffects[name] = effect;\n return effect;\n }\n _compileRawShaderToSpirV(source, type) {\n return this._glslang.compileGLSL(source, type);\n }\n _compileShaderToSpirV(source, type, defines, shaderVersion) {\n return this._compileRawShaderToSpirV(shaderVersion + (defines ? defines + \"\\n\" : \"\") + source, type);\n }\n _getWGSLShader(source, type, defines) {\n if (defines) {\n defines = \"//\" + defines.split(\"\\n\").join(\"\\n//\") + \"\\n\";\n }\n else {\n defines = \"\";\n }\n return defines + source;\n }\n _createPipelineStageDescriptor(vertexShader, fragmentShader, shaderLanguage, disableUniformityAnalysisInVertex, disableUniformityAnalysisInFragment) {\n if (this._tintWASM && shaderLanguage === ShaderLanguage.GLSL) {\n vertexShader = this._tintWASM.convertSpirV2WGSL(vertexShader, disableUniformityAnalysisInVertex);\n fragmentShader = this._tintWASM.convertSpirV2WGSL(fragmentShader, disableUniformityAnalysisInFragment);\n }\n return {\n vertexStage: {\n module: this._device.createShaderModule({\n code: vertexShader,\n }),\n entryPoint: \"main\",\n },\n fragmentStage: {\n module: this._device.createShaderModule({\n code: fragmentShader,\n }),\n entryPoint: \"main\",\n },\n };\n }\n _compileRawPipelineStageDescriptor(vertexCode, fragmentCode, shaderLanguage) {\n const disableUniformityAnalysisInVertex = vertexCode.indexOf(disableUniformityAnalysisMarker) >= 0;\n const disableUniformityAnalysisInFragment = fragmentCode.indexOf(disableUniformityAnalysisMarker) >= 0;\n const vertexShader = shaderLanguage === ShaderLanguage.GLSL ? this._compileRawShaderToSpirV(vertexCode, \"vertex\") : vertexCode;\n const fragmentShader = shaderLanguage === ShaderLanguage.GLSL ? this._compileRawShaderToSpirV(fragmentCode, \"fragment\") : fragmentCode;\n return this._createPipelineStageDescriptor(vertexShader, fragmentShader, shaderLanguage, disableUniformityAnalysisInVertex, disableUniformityAnalysisInFragment);\n }\n _compilePipelineStageDescriptor(vertexCode, fragmentCode, defines, shaderLanguage) {\n this.onBeforeShaderCompilationObservable.notifyObservers(this);\n const disableUniformityAnalysisInVertex = vertexCode.indexOf(disableUniformityAnalysisMarker) >= 0;\n const disableUniformityAnalysisInFragment = fragmentCode.indexOf(disableUniformityAnalysisMarker) >= 0;\n const shaderVersion = \"#version 450\\n\";\n const vertexShader = shaderLanguage === ShaderLanguage.GLSL ? this._compileShaderToSpirV(vertexCode, \"vertex\", defines, shaderVersion) : this._getWGSLShader(vertexCode, \"vertex\", defines);\n const fragmentShader = shaderLanguage === ShaderLanguage.GLSL\n ? this._compileShaderToSpirV(fragmentCode, \"fragment\", defines, shaderVersion)\n : this._getWGSLShader(fragmentCode, \"fragment\", defines);\n const program = this._createPipelineStageDescriptor(vertexShader, fragmentShader, shaderLanguage, disableUniformityAnalysisInVertex, disableUniformityAnalysisInFragment);\n this.onAfterShaderCompilationObservable.notifyObservers(this);\n return program;\n }\n /**\n * @internal\n */\n createRawShaderProgram() {\n throw \"Not available on WebGPU\";\n }\n /**\n * @internal\n */\n createShaderProgram() {\n throw \"Not available on WebGPU\";\n }\n /**\n * Inline functions in shader code that are marked to be inlined\n * @param code code to inline\n * @returns inlined code\n */\n inlineShaderCode(code) {\n const sci = new ShaderCodeInliner(code);\n sci.debug = false;\n sci.processCode();\n return sci.code;\n }\n /**\n * Creates a new pipeline context\n * @param shaderProcessingContext defines the shader processing context used during the processing if available\n * @returns the new pipeline\n */\n createPipelineContext(shaderProcessingContext) {\n return new WebGPUPipelineContext(shaderProcessingContext, this);\n }\n /**\n * Creates a new material context\n * @returns the new context\n */\n createMaterialContext() {\n return new WebGPUMaterialContext();\n }\n /**\n * Creates a new draw context\n * @returns the new context\n */\n createDrawContext() {\n return new WebGPUDrawContext(this._bufferManager);\n }\n /**\n * @internal\n */\n _preparePipelineContext(pipelineContext, vertexSourceCode, fragmentSourceCode, createAsRaw, rawVertexSourceCode, rawFragmentSourceCode, rebuildRebind, defines) {\n const webGpuContext = pipelineContext;\n const shaderLanguage = webGpuContext.shaderProcessingContext.shaderLanguage;\n if (this.dbgShowShaderCode) {\n console.log(defines);\n console.log(vertexSourceCode);\n console.log(fragmentSourceCode);\n console.log(\"***********************************************\");\n }\n webGpuContext.sources = {\n fragment: fragmentSourceCode,\n vertex: vertexSourceCode,\n rawVertex: rawVertexSourceCode,\n rawFragment: rawFragmentSourceCode,\n };\n if (createAsRaw) {\n webGpuContext.stages = this._compileRawPipelineStageDescriptor(vertexSourceCode, fragmentSourceCode, shaderLanguage);\n }\n else {\n webGpuContext.stages = this._compilePipelineStageDescriptor(vertexSourceCode, fragmentSourceCode, defines, shaderLanguage);\n }\n }\n /**\n * Gets the list of active attributes for a given WebGPU program\n * @param pipelineContext defines the pipeline context to use\n * @param attributesNames defines the list of attribute names to get\n * @returns an array of indices indicating the offset of each attribute\n */\n getAttributes(pipelineContext, attributesNames) {\n const results = new Array(attributesNames.length);\n const gpuPipelineContext = pipelineContext;\n for (let i = 0; i < attributesNames.length; i++) {\n const attributeName = attributesNames[i];\n const attributeLocation = gpuPipelineContext.shaderProcessingContext.availableAttributes[attributeName];\n if (attributeLocation === undefined) {\n continue;\n }\n results[i] = attributeLocation;\n }\n return results;\n }\n /**\n * Activates an effect, making it the current one (ie. the one used for rendering)\n * @param effect defines the effect to activate\n */\n enableEffect(effect) {\n if (!effect) {\n return;\n }\n let isNewEffect = true;\n if (!DrawWrapper.IsWrapper(effect)) {\n isNewEffect = effect !== this._currentEffect;\n this._currentEffect = effect;\n this._currentMaterialContext = this._defaultMaterialContext;\n this._currentDrawContext = this._defaultDrawContext;\n this._counters.numEnableEffects++;\n if (this.dbgLogIfNotDrawWrapper) {\n Logger.Warn(`enableEffect has been called with an Effect and not a Wrapper! effect.uniqueId=${effect.uniqueId}, effect.name=${effect.name}, effect.name.vertex=${effect.name.vertex}, effect.name.fragment=${effect.name.fragment}`, 10);\n }\n }\n else if (!effect.effect ||\n (effect.effect === this._currentEffect &&\n effect.materialContext === this._currentMaterialContext &&\n effect.drawContext === this._currentDrawContext &&\n !this._forceEnableEffect)) {\n if (!effect.effect && this.dbgShowEmptyEnableEffectCalls) {\n console.error(\"drawWrapper=\", effect);\n throw \"Invalid call to enableEffect: the effect property is empty!\";\n }\n return;\n }\n else {\n isNewEffect = effect.effect !== this._currentEffect;\n this._currentEffect = effect.effect;\n this._currentMaterialContext = effect.materialContext;\n this._currentDrawContext = effect.drawContext;\n this._counters.numEnableDrawWrapper++;\n if (!this._currentMaterialContext) {\n console.error(\"drawWrapper=\", effect);\n throw `Invalid call to enableEffect: the materialContext property is empty!`;\n }\n }\n this._stencilStateComposer.stencilMaterial = undefined;\n this._forceEnableEffect = isNewEffect || this._forceEnableEffect ? false : this._forceEnableEffect;\n if (isNewEffect) {\n if (this._currentEffect.onBind) {\n this._currentEffect.onBind(this._currentEffect);\n }\n if (this._currentEffect._onBindObservable) {\n this._currentEffect._onBindObservable.notifyObservers(this._currentEffect);\n }\n }\n }\n /**\n * @internal\n */\n _releaseEffect(effect) {\n if (this._compiledEffects[effect._key]) {\n delete this._compiledEffects[effect._key];\n this._deletePipelineContext(effect.getPipelineContext());\n }\n }\n /**\n * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled\n */\n releaseEffects() {\n for (const name in this._compiledEffects) {\n const webGPUPipelineContext = this._compiledEffects[name].getPipelineContext();\n this._deletePipelineContext(webGPUPipelineContext);\n }\n this._compiledEffects = {};\n }\n _deletePipelineContext(pipelineContext) {\n const webgpuPipelineContext = pipelineContext;\n if (webgpuPipelineContext) {\n pipelineContext.dispose();\n }\n }\n //------------------------------------------------------------------------------\n // Textures\n //------------------------------------------------------------------------------\n /**\n * Gets a boolean indicating that only power of 2 textures are supported\n * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them\n */\n get needPOTTextures() {\n return false;\n }\n /** @internal */\n _createHardwareTexture() {\n return new WebGPUHardwareTexture();\n }\n /**\n * @internal\n */\n _releaseTexture(texture) {\n const index = this._internalTexturesCache.indexOf(texture);\n if (index !== -1) {\n this._internalTexturesCache.splice(index, 1);\n }\n this._textureHelper.releaseTexture(texture);\n }\n /**\n * @internal\n */\n _getRGBABufferInternalSizedFormat() {\n return 5;\n }\n updateTextureComparisonFunction(texture, comparisonFunction) {\n texture._comparisonFunction = comparisonFunction;\n }\n /**\n * Creates an internal texture without binding it to a framebuffer\n * @internal\n * @param size defines the size of the texture\n * @param options defines the options used to create the texture\n * @param delayGPUTextureCreation true to delay the texture creation the first time it is really needed. false to create it right away\n * @param source source type of the texture\n * @returns a new internal texture\n */\n _createInternalTexture(size, options, delayGPUTextureCreation = true, source = InternalTextureSource.Unknown) {\n var _a, _b, _c;\n const fullOptions = {};\n if (options !== undefined && typeof options === \"object\") {\n fullOptions.generateMipMaps = options.generateMipMaps;\n fullOptions.type = options.type === undefined ? 0 : options.type;\n fullOptions.samplingMode = options.samplingMode === undefined ? 3 : options.samplingMode;\n fullOptions.format = options.format === undefined ? 5 : options.format;\n fullOptions.samples = (_a = options.samples) !== null && _a !== void 0 ? _a : 1;\n fullOptions.creationFlags = (_b = options.creationFlags) !== null && _b !== void 0 ? _b : 0;\n fullOptions.useSRGBBuffer = (_c = options.useSRGBBuffer) !== null && _c !== void 0 ? _c : false;\n fullOptions.label = options.label;\n }\n else {\n fullOptions.generateMipMaps = options;\n fullOptions.type = 0;\n fullOptions.samplingMode = 3;\n fullOptions.format = 5;\n fullOptions.samples = 1;\n fullOptions.creationFlags = 0;\n fullOptions.useSRGBBuffer = false;\n }\n if (fullOptions.type === 1 && !this._caps.textureFloatLinearFiltering) {\n fullOptions.samplingMode = 1;\n }\n else if (fullOptions.type === 2 && !this._caps.textureHalfFloatLinearFiltering) {\n fullOptions.samplingMode = 1;\n }\n if (fullOptions.type === 1 && !this._caps.textureFloat) {\n fullOptions.type = 0;\n Logger.Warn(\"Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE\");\n }\n const texture = new InternalTexture(this, source);\n const width = size.width || size;\n const height = size.height || size;\n const layers = size.layers || 0;\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = width;\n texture.height = height;\n texture.depth = layers;\n texture.isReady = true;\n texture.samples = fullOptions.samples;\n texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;\n texture.samplingMode = fullOptions.samplingMode;\n texture.type = fullOptions.type;\n texture.format = fullOptions.format;\n texture.is2DArray = layers > 0;\n texture._cachedWrapU = 0;\n texture._cachedWrapV = 0;\n texture._useSRGBBuffer = fullOptions.useSRGBBuffer;\n texture.label = fullOptions.label;\n this._internalTexturesCache.push(texture);\n if (!delayGPUTextureCreation) {\n this._textureHelper.createGPUTextureForInternalTexture(texture, width, height, layers || 1, fullOptions.creationFlags);\n }\n return texture;\n }\n /**\n * Usually called from Texture.ts.\n * Passed information to create a hardware texture\n * @param url defines a value which contains one of the following:\n * * A conventional http URL, e.g. 'http://...' or 'file://...'\n * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'\n * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'\n * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file\n * @param invertY when true, image is flipped when loaded. You probably want true. Certain compressed textures may invert this if their default is inverted (eg. ktx)\n * @param scene needed for loading to the correct scene\n * @param samplingMode mode with should be used sample / access the texture (Default: Texture.TRILINEAR_SAMPLINGMODE)\n * @param onLoad optional callback to be called upon successful completion\n * @param onError optional callback to be called upon failure\n * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob\n * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities\n * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures\n * @param forcedExtension defines the extension to use to pick the right loader\n * @param mimeType defines an optional mime type\n * @param loaderOptions options to be passed to the loader\n * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg)\n * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU).\n * @returns a InternalTexture for assignment back into BABYLON.Texture\n */\n createTexture(url, noMipmap, invertY, scene, samplingMode = 3, onLoad = null, onError = null, buffer = null, fallback = null, format = null, forcedExtension = null, mimeType, loaderOptions, creationFlags, useSRGBBuffer) {\n return this._createTextureBase(url, noMipmap, invertY, scene, samplingMode, onLoad, onError, (texture, extension, scene, img, invertY, noMipmap, isCompressed, processFunction) => {\n var _a;\n const imageBitmap = img; // we will never get an HTMLImageElement in WebGPU\n texture.baseWidth = imageBitmap.width;\n texture.baseHeight = imageBitmap.height;\n texture.width = imageBitmap.width;\n texture.height = imageBitmap.height;\n texture.format = format !== null && format !== void 0 ? format : -1;\n processFunction(texture.width, texture.height, imageBitmap, extension, texture, () => { });\n if (!((_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource)) {\n // the texture could have been created before reaching this point so don't recreate it if already existing\n const gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, imageBitmap.width, imageBitmap.height, undefined, creationFlags);\n if (WebGPUTextureHelper.IsImageBitmap(imageBitmap)) {\n this._textureHelper.updateTexture(imageBitmap, texture, imageBitmap.width, imageBitmap.height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, false, 0, 0);\n if (!noMipmap && !isCompressed) {\n this._generateMipmaps(texture, this._uploadEncoder);\n }\n }\n }\n else if (!noMipmap && !isCompressed) {\n this._generateMipmaps(texture, this._uploadEncoder);\n }\n if (scene) {\n scene.removePendingData(texture);\n }\n texture.isReady = true;\n texture.onLoadedObservable.notifyObservers(texture);\n texture.onLoadedObservable.clear();\n }, () => false, buffer, fallback, format, forcedExtension, mimeType, loaderOptions, useSRGBBuffer);\n }\n /**\n * Wraps an external web gpu texture in a Babylon texture.\n * @param texture defines the external texture\n * @returns the babylon internal texture\n */\n wrapWebGPUTexture(texture) {\n const hardwareTexture = new WebGPUHardwareTexture(texture);\n const internalTexture = new InternalTexture(this, InternalTextureSource.Unknown, true);\n internalTexture._hardwareTexture = hardwareTexture;\n internalTexture.isReady = true;\n return internalTexture;\n }\n /**\n * Wraps an external web gl texture in a Babylon texture.\n * @returns the babylon internal texture\n */\n wrapWebGLTexture() {\n throw new Error(\"wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.\");\n }\n generateMipMapsForCubemap(texture) {\n var _a;\n if (texture.generateMipMaps) {\n const gpuTexture = (_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource;\n if (!gpuTexture) {\n this._textureHelper.createGPUTextureForInternalTexture(texture);\n }\n this._generateMipmaps(texture, texture.source === InternalTextureSource.RenderTarget || texture.source === InternalTextureSource.MultiRenderTarget ? this._renderTargetEncoder : undefined);\n }\n }\n /**\n * Update the sampling mode of a given texture\n * @param samplingMode defines the required sampling mode\n * @param texture defines the texture to update\n * @param generateMipMaps defines whether to generate mipmaps for the texture\n */\n updateTextureSamplingMode(samplingMode, texture, generateMipMaps = false) {\n if (generateMipMaps) {\n texture.generateMipMaps = true;\n this._generateMipmaps(texture);\n }\n texture.samplingMode = samplingMode;\n }\n /**\n * Update the sampling mode of a given texture\n * @param texture defines the texture to update\n * @param wrapU defines the texture wrap mode of the u coordinates\n * @param wrapV defines the texture wrap mode of the v coordinates\n * @param wrapR defines the texture wrap mode of the r coordinates\n */\n updateTextureWrappingMode(texture, wrapU, wrapV = null, wrapR = null) {\n if (wrapU !== null) {\n texture._cachedWrapU = wrapU;\n }\n if (wrapV !== null) {\n texture._cachedWrapV = wrapV;\n }\n if ((texture.is2DArray || texture.is3D) && wrapR !== null) {\n texture._cachedWrapR = wrapR;\n }\n }\n /**\n * Update the dimensions of a texture\n * @param texture texture to update\n * @param width new width of the texture\n * @param height new height of the texture\n * @param depth new depth of the texture\n */\n updateTextureDimensions(texture, width, height, depth = 1) {\n if (!texture._hardwareTexture) {\n // the gpu texture is not created yet, so when it is it will be created with the right dimensions\n return;\n }\n if (texture.width === width && texture.height === height && texture.depth === depth) {\n return;\n }\n const additionalUsages = texture._hardwareTexture.textureAdditionalUsages;\n texture._hardwareTexture.release(); // don't defer the releasing! Else we will release at the end of this frame the gpu texture we are about to create in the next line...\n this._textureHelper.createGPUTextureForInternalTexture(texture, width, height, depth, additionalUsages);\n }\n /**\n * @internal\n */\n _setInternalTexture(name, texture, baseName) {\n baseName = baseName !== null && baseName !== void 0 ? baseName : name;\n if (this._currentEffect) {\n const webgpuPipelineContext = this._currentEffect._pipelineContext;\n const availableTexture = webgpuPipelineContext.shaderProcessingContext.availableTextures[baseName];\n this._currentMaterialContext.setTexture(name, texture);\n if (availableTexture && availableTexture.autoBindSampler) {\n const samplerName = baseName + WebGPUShaderProcessor.AutoSamplerSuffix;\n this._currentMaterialContext.setSampler(samplerName, texture); // we can safely cast to InternalTexture because ExternalTexture always has autoBindSampler = false\n }\n }\n }\n /**\n * Sets a texture to the according uniform.\n * @param channel The texture channel\n * @param unused unused parameter\n * @param texture The texture to apply\n * @param name The name of the uniform in the effect\n */\n setTexture(channel, unused, texture, name) {\n this._setTexture(channel, texture, false, false, name, name);\n }\n /**\n * Sets an array of texture to the WebGPU context\n * @param channel defines the channel where the texture array must be set\n * @param unused unused parameter\n * @param textures defines the array of textures to bind\n * @param name name of the channel\n */\n setTextureArray(channel, unused, textures, name) {\n for (let index = 0; index < textures.length; index++) {\n this._setTexture(-1, textures[index], true, false, name + index.toString(), name);\n }\n }\n _setTexture(channel, texture, \n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isPartOfTextureArray = false, depthStencilTexture = false, name = \"\", baseName) {\n // name == baseName for a texture that is not part of a texture array\n // Else, name is something like 'myTexture0' / 'myTexture1' / ... and baseName is 'myTexture'\n // baseName is used to look up the texture in the shaderProcessingContext.availableTextures map\n // name is used to look up the texture in the _currentMaterialContext.textures map\n baseName = baseName !== null && baseName !== void 0 ? baseName : name;\n if (this._currentEffect) {\n if (!texture) {\n this._currentMaterialContext.setTexture(name, null);\n return false;\n }\n // Video\n if (texture.video) {\n texture.update();\n }\n else if (texture.delayLoadState === 4) {\n // Delay loading\n texture.delayLoad();\n return false;\n }\n let internalTexture = null;\n if (depthStencilTexture) {\n internalTexture = texture.depthStencilTexture;\n }\n else if (texture.isReady()) {\n internalTexture = texture.getInternalTexture();\n }\n else if (texture.isCube) {\n internalTexture = this.emptyCubeTexture;\n }\n else if (texture.is3D) {\n internalTexture = this.emptyTexture3D;\n }\n else if (texture.is2DArray) {\n internalTexture = this.emptyTexture2DArray;\n }\n else {\n internalTexture = this.emptyTexture;\n }\n if (internalTexture && !internalTexture.isMultiview) {\n // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.\n if (internalTexture.isCube && internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {\n internalTexture._cachedCoordinatesMode = texture.coordinatesMode;\n const textureWrapMode = texture.coordinatesMode !== 3 && texture.coordinatesMode !== 5\n ? 1\n : 0;\n texture.wrapU = textureWrapMode;\n texture.wrapV = textureWrapMode;\n }\n internalTexture._cachedWrapU = texture.wrapU;\n internalTexture._cachedWrapV = texture.wrapV;\n if (internalTexture.is3D) {\n internalTexture._cachedWrapR = texture.wrapR;\n }\n this._setAnisotropicLevel(0, internalTexture, texture.anisotropicFilteringLevel);\n }\n this._setInternalTexture(name, internalTexture, baseName);\n }\n else {\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n console.log(\"frame #\" + this._count + \" - _setTexture called with a null _currentEffect! texture=\", texture);\n }\n }\n }\n return true;\n }\n /**\n * @internal\n */\n _setAnisotropicLevel(target, internalTexture, anisotropicFilteringLevel) {\n if (internalTexture._cachedAnisotropicFilteringLevel !== anisotropicFilteringLevel) {\n internalTexture._cachedAnisotropicFilteringLevel = Math.min(anisotropicFilteringLevel, this._caps.maxAnisotropy);\n }\n }\n /**\n * @internal\n */\n _bindTexture(channel, texture, name) {\n if (channel === undefined) {\n return;\n }\n this._setInternalTexture(name, texture);\n }\n /**\n * Generates the mipmaps for a texture\n * @param texture texture to generate the mipmaps for\n */\n generateMipmaps(texture) {\n this._generateMipmaps(texture, this._renderTargetEncoder);\n }\n /**\n * @internal\n */\n _generateMipmaps(texture, commandEncoder) {\n const gpuHardwareTexture = texture._hardwareTexture;\n if (!gpuHardwareTexture) {\n return;\n }\n // try as much as possible to use the command encoder corresponding to the current pass.\n // If not possible (because the pass is started - generateMipmaps itself creates a pass and it's not allowed to have a pass inside a pass), use _uploadEncoder\n commandEncoder =\n commandEncoder !== null && commandEncoder !== void 0 ? commandEncoder : (this._currentRenderTarget && !this._currentRenderPass ? this._renderTargetEncoder : !this._currentRenderPass ? this._renderEncoder : this._uploadEncoder);\n const format = texture._hardwareTexture.format;\n const mipmapCount = WebGPUTextureHelper.ComputeNumMipmapLevels(texture.width, texture.height);\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n console.log(\"frame #\" + this._count + \" - generate mipmaps called - width=\", texture.width, \"height=\", texture.height, \"isCube=\", texture.isCube);\n }\n }\n if (texture.isCube) {\n this._textureHelper.generateCubeMipmaps(gpuHardwareTexture, format, mipmapCount, commandEncoder);\n }\n else {\n this._textureHelper.generateMipmaps(gpuHardwareTexture, format, mipmapCount, 0, commandEncoder);\n }\n }\n /**\n * Update a portion of an internal texture\n * @param texture defines the texture to update\n * @param imageData defines the data to store into the texture\n * @param xOffset defines the x coordinates of the update rectangle\n * @param yOffset defines the y coordinates of the update rectangle\n * @param width defines the width of the update rectangle\n * @param height defines the height of the update rectangle\n * @param faceIndex defines the face index if texture is a cube (0 by default)\n * @param lod defines the lod level to update (0 by default)\n * @param generateMipMaps defines whether to generate mipmaps or not\n */\n updateTextureData(texture, imageData, xOffset, yOffset, width, height, faceIndex = 0, lod = 0, generateMipMaps = false) {\n var _a;\n let gpuTextureWrapper = texture._hardwareTexture;\n if (!((_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource)) {\n gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture);\n }\n const data = new Uint8Array(imageData.buffer, imageData.byteOffset, imageData.byteLength);\n this._textureHelper.updateTexture(data, texture, width, height, texture.depth, gpuTextureWrapper.format, faceIndex, lod, texture.invertY, false, xOffset, yOffset);\n if (generateMipMaps) {\n this._generateMipmaps(texture, this._renderTargetEncoder);\n }\n }\n /**\n * @internal\n */\n _uploadCompressedDataToTextureDirectly(texture, internalFormat, width, height, imageData, faceIndex = 0, lod = 0) {\n var _a;\n let gpuTextureWrapper = texture._hardwareTexture;\n if (!((_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource)) {\n texture.format = internalFormat;\n gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, width, height);\n }\n const data = new Uint8Array(imageData.buffer, imageData.byteOffset, imageData.byteLength);\n this._textureHelper.updateTexture(data, texture, width, height, texture.depth, gpuTextureWrapper.format, faceIndex, lod, false, false, 0, 0);\n }\n /**\n * @internal\n */\n _uploadDataToTextureDirectly(texture, imageData, faceIndex = 0, lod = 0, babylonInternalFormat, useTextureWidthAndHeight = false) {\n var _a;\n const lodMaxWidth = Math.round(Math.log(texture.width) * Math.LOG2E);\n const lodMaxHeight = Math.round(Math.log(texture.height) * Math.LOG2E);\n const width = useTextureWidthAndHeight ? texture.width : Math.pow(2, Math.max(lodMaxWidth - lod, 0));\n const height = useTextureWidthAndHeight ? texture.height : Math.pow(2, Math.max(lodMaxHeight - lod, 0));\n let gpuTextureWrapper = texture._hardwareTexture;\n if (!((_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource)) {\n gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, width, height);\n }\n const data = new Uint8Array(imageData.buffer, imageData.byteOffset, imageData.byteLength);\n this._textureHelper.updateTexture(data, texture, width, height, texture.depth, gpuTextureWrapper.format, faceIndex, lod, texture.invertY, false, 0, 0);\n }\n /**\n * @internal\n */\n _uploadArrayBufferViewToTexture(texture, imageData, faceIndex = 0, lod = 0) {\n this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);\n }\n /**\n * @internal\n */\n _uploadImageToTexture(texture, image, faceIndex = 0, lod = 0) {\n var _a;\n let gpuTextureWrapper = texture._hardwareTexture;\n if (!((_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource)) {\n gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture);\n }\n if (image instanceof HTMLImageElement) {\n throw \"WebGPU engine: HTMLImageElement not supported in _uploadImageToTexture!\";\n }\n const bitmap = image; // in WebGPU we will always get an ImageBitmap, not an HTMLImageElement\n const width = Math.ceil(texture.width / (1 << lod));\n const height = Math.ceil(texture.height / (1 << lod));\n this._textureHelper.updateTexture(bitmap, texture, width, height, texture.depth, gpuTextureWrapper.format, faceIndex, lod, texture.invertY, false, 0, 0);\n }\n /**\n * Reads pixels from the current frame buffer. Please note that this function can be slow\n * @param x defines the x coordinate of the rectangle where pixels must be read\n * @param y defines the y coordinate of the rectangle where pixels must be read\n * @param width defines the width of the rectangle where pixels must be read\n * @param height defines the height of the rectangle where pixels must be read\n * @param hasAlpha defines whether the output should have alpha or not (defaults to true)\n * @param flushRenderer true to flush the renderer from the pending commands before reading the pixels\n * @returns a ArrayBufferView promise (Uint8Array) containing RGBA colors\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n readPixels(x, y, width, height, hasAlpha = true, flushRenderer = true) {\n const renderPassWrapper = this._rttRenderPassWrapper.renderPass ? this._rttRenderPassWrapper : this._mainRenderPassWrapper;\n const hardwareTexture = renderPassWrapper.colorAttachmentGPUTextures[0];\n if (!hardwareTexture) {\n // we are calling readPixels for a render pass with no color texture bound\n return Promise.resolve(new Uint8Array(0));\n }\n const gpuTexture = hardwareTexture.underlyingResource;\n const gpuTextureFormat = hardwareTexture.format;\n if (!gpuTexture) {\n // we are calling readPixels before startMainRenderPass has been called and no RTT is bound, so swapChainTexture is not setup yet!\n return Promise.resolve(new Uint8Array(0));\n }\n if (flushRenderer) {\n this.flushFramebuffer();\n }\n return this._textureHelper.readPixels(gpuTexture, x, y, width, height, gpuTextureFormat);\n }\n //------------------------------------------------------------------------------\n // Frame management\n //------------------------------------------------------------------------------\n /**\n * Begin a new frame\n */\n beginFrame() {\n super.beginFrame();\n }\n /**\n * End the current frame\n */\n endFrame() {\n this._snapshotRendering.endFrame(this._mainRenderPassWrapper.renderPass);\n this._endMainRenderPass();\n this._timestampQuery.endFrame(this._renderEncoder);\n this.flushFramebuffer(false);\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n console.log(\"frame #\" + this._count + \" - counters\");\n }\n }\n this._textureHelper.destroyDeferredTextures();\n this._bufferManager.destroyDeferredBuffers();\n if (this._features._collectUbosUpdatedInFrame) {\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n const list = [];\n for (const name in UniformBuffer._UpdatedUbosInFrame) {\n list.push(name + \":\" + UniformBuffer._UpdatedUbosInFrame[name]);\n }\n console.log(\"frame #\" + this._count + \" - updated ubos -\", list.join(\", \"));\n }\n }\n UniformBuffer._UpdatedUbosInFrame = {};\n }\n this.countersLastFrame.numEnableEffects = this._counters.numEnableEffects;\n this.countersLastFrame.numEnableDrawWrapper = this._counters.numEnableDrawWrapper;\n this.countersLastFrame.numBundleCreationNonCompatMode = this._counters.numBundleCreationNonCompatMode;\n this.countersLastFrame.numBundleReuseNonCompatMode = this._counters.numBundleReuseNonCompatMode;\n this._counters.numEnableEffects = 0;\n this._counters.numEnableDrawWrapper = 0;\n this._counters.numBundleCreationNonCompatMode = 0;\n this._counters.numBundleReuseNonCompatMode = 0;\n this._cacheRenderPipeline.endFrame();\n this._cacheBindGroups.endFrame();\n this._pendingDebugCommands.length = 0;\n super.endFrame();\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (this._count < this.dbgVerboseLogsNumFrames) {\n console.log(\"%c frame #\" + this._count + \" - end\", \"background: #ffff00\");\n }\n if (this._count < this.dbgVerboseLogsNumFrames) {\n this._count++;\n if (this._count !== this.dbgVerboseLogsNumFrames) {\n console.log(\"%c frame #\" + this._count + \" - begin\", \"background: #ffff00\");\n }\n }\n }\n }\n /**\n * Force a WebGPU flush (ie. a flush of all waiting commands)\n * @param reopenPass true to reopen at the end of the function the pass that was active when entering the function\n */\n flushFramebuffer(reopenPass = true) {\n // we need to end the current render pass (main or rtt) if any as we are not allowed to submit the command buffers when being in a pass\n const currentRenderPassIsNULL = !this._currentRenderPass;\n let currentPasses = 0; // 0 if no pass, 1 for rtt, 2 for main pass\n if (this._currentRenderPass && this._currentRenderTarget) {\n currentPasses |= 1;\n this._endRenderTargetRenderPass();\n }\n if (this._mainRenderPassWrapper.renderPass) {\n currentPasses |= 2;\n this._endMainRenderPass();\n }\n this._commandBuffers[0] = this._uploadEncoder.finish();\n this._commandBuffers[1] = this._renderTargetEncoder.finish();\n this._commandBuffers[2] = this._renderEncoder.finish();\n this._device.queue.submit(this._commandBuffers);\n this._uploadEncoder = this._device.createCommandEncoder(this._uploadEncoderDescriptor);\n this._renderEncoder = this._device.createCommandEncoder(this._renderEncoderDescriptor);\n this._renderTargetEncoder = this._device.createCommandEncoder(this._renderTargetEncoderDescriptor);\n this._timestampQuery.startFrame(this._uploadEncoder);\n this._textureHelper.setCommandEncoder(this._uploadEncoder);\n this._bundleList.reset();\n this._bundleListRenderTarget.reset();\n // restart the render pass\n if (reopenPass) {\n if (currentPasses & 2) {\n this._startMainRenderPass(false);\n }\n if (currentPasses & 1) {\n this._startRenderTargetRenderPass(this._currentRenderTarget, false, null, false, false);\n }\n if (currentRenderPassIsNULL && this._currentRenderTarget) {\n this._currentRenderPass = null;\n }\n }\n }\n /** @internal */\n _currentFrameBufferIsDefaultFrameBuffer() {\n return this._currentRenderTarget === null;\n }\n //------------------------------------------------------------------------------\n // Render Pass\n //------------------------------------------------------------------------------\n _startRenderTargetRenderPass(renderTargetWrapper, setClearStates, clearColor, clearDepth, clearStencil) {\n var _a, _b, _c, _d, _e, _f, _g;\n const rtWrapper = renderTargetWrapper;\n const depthStencilTexture = rtWrapper._depthStencilTexture;\n const gpuDepthStencilWrapper = depthStencilTexture === null || depthStencilTexture === void 0 ? void 0 : depthStencilTexture._hardwareTexture;\n const gpuDepthStencilTexture = gpuDepthStencilWrapper === null || gpuDepthStencilWrapper === void 0 ? void 0 : gpuDepthStencilWrapper.underlyingResource;\n const gpuDepthStencilMSAATexture = gpuDepthStencilWrapper === null || gpuDepthStencilWrapper === void 0 ? void 0 : gpuDepthStencilWrapper.getMSAATexture();\n const depthTextureView = gpuDepthStencilTexture === null || gpuDepthStencilTexture === void 0 ? void 0 : gpuDepthStencilTexture.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor);\n const depthMSAATextureView = gpuDepthStencilMSAATexture === null || gpuDepthStencilMSAATexture === void 0 ? void 0 : gpuDepthStencilMSAATexture.createView(this._rttRenderPassWrapper.depthAttachmentViewDescriptor);\n const depthTextureHasStencil = gpuDepthStencilWrapper ? WebGPUTextureHelper.HasStencilAspect(gpuDepthStencilWrapper.format) : false;\n const colorAttachments = [];\n if (this.useReverseDepthBuffer) {\n this.setDepthFunctionToGreaterOrEqual();\n }\n const mustClearColor = setClearStates && clearColor;\n const mustClearDepth = setClearStates && clearDepth;\n const mustClearStencil = setClearStates && clearStencil;\n if (rtWrapper._attachments && rtWrapper.isMulti) {\n // multi render targets\n if (!this._mrtAttachments || this._mrtAttachments.length === 0) {\n this._mrtAttachments = rtWrapper._defaultAttachments;\n }\n for (let i = 0; i < this._mrtAttachments.length; ++i) {\n const index = this._mrtAttachments[i]; // if index == 0 it means the texture should not be written to => at render pass creation time, it means we should not clear it\n const mrtTexture = rtWrapper.textures[i];\n const gpuMRTWrapper = mrtTexture === null || mrtTexture === void 0 ? void 0 : mrtTexture._hardwareTexture;\n const gpuMRTTexture = gpuMRTWrapper === null || gpuMRTWrapper === void 0 ? void 0 : gpuMRTWrapper.underlyingResource;\n if (gpuMRTWrapper && gpuMRTTexture) {\n const gpuMSAATexture = gpuMRTWrapper.getMSAATexture(i);\n const layerIndex = (_b = (_a = rtWrapper.layerIndices) === null || _a === void 0 ? void 0 : _a[i]) !== null && _b !== void 0 ? _b : 0;\n const faceIndex = (_d = (_c = rtWrapper.faceIndices) === null || _c === void 0 ? void 0 : _c[i]) !== null && _d !== void 0 ? _d : 0;\n const viewDescriptor = Object.assign(Object.assign({}, this._rttRenderPassWrapper.colorAttachmentViewDescriptor), { format: gpuMRTWrapper.format, baseArrayLayer: mrtTexture.isCube ? layerIndex * 6 + faceIndex : layerIndex });\n const msaaViewDescriptor = Object.assign(Object.assign({}, this._rttRenderPassWrapper.colorAttachmentViewDescriptor), { format: gpuMRTWrapper.format, baseArrayLayer: 0 });\n const colorTextureView = gpuMRTTexture.createView(viewDescriptor);\n const colorMSAATextureView = gpuMSAATexture === null || gpuMSAATexture === void 0 ? void 0 : gpuMSAATexture.createView(msaaViewDescriptor);\n colorAttachments.push({\n view: colorMSAATextureView ? colorMSAATextureView : colorTextureView,\n resolveTarget: gpuMSAATexture ? colorTextureView : undefined,\n clearValue: index !== 0 && mustClearColor ? clearColor : undefined,\n loadOp: index !== 0 && mustClearColor ? WebGPUConstants.LoadOp.Clear : WebGPUConstants.LoadOp.Load,\n storeOp: WebGPUConstants.StoreOp.Store,\n });\n }\n }\n this._cacheRenderPipeline.setMRT(rtWrapper.textures, this._mrtAttachments.length);\n this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments);\n }\n else {\n // single render target\n const internalTexture = rtWrapper.texture;\n if (internalTexture) {\n const gpuWrapper = internalTexture._hardwareTexture;\n const gpuTexture = gpuWrapper.underlyingResource;\n const gpuMSAATexture = gpuWrapper.getMSAATexture();\n const colorTextureView = gpuTexture.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor);\n const colorMSAATextureView = gpuMSAATexture === null || gpuMSAATexture === void 0 ? void 0 : gpuMSAATexture.createView(this._rttRenderPassWrapper.colorAttachmentViewDescriptor);\n colorAttachments.push({\n view: colorMSAATextureView ? colorMSAATextureView : colorTextureView,\n resolveTarget: gpuMSAATexture ? colorTextureView : undefined,\n clearValue: mustClearColor ? clearColor : undefined,\n loadOp: mustClearColor ? WebGPUConstants.LoadOp.Clear : WebGPUConstants.LoadOp.Load,\n storeOp: WebGPUConstants.StoreOp.Store,\n });\n }\n else {\n colorAttachments.push(null);\n }\n }\n (_e = this._debugPushGroup) === null || _e === void 0 ? void 0 : _e.call(this, \"render target pass\", 1);\n this._rttRenderPassWrapper.renderPassDescriptor = {\n colorAttachments,\n depthStencilAttachment: depthStencilTexture && gpuDepthStencilTexture\n ? {\n view: depthMSAATextureView ? depthMSAATextureView : depthTextureView,\n depthClearValue: mustClearDepth ? (this.useReverseDepthBuffer ? this._clearReverseDepthValue : this._clearDepthValue) : undefined,\n depthLoadOp: mustClearDepth ? WebGPUConstants.LoadOp.Clear : WebGPUConstants.LoadOp.Load,\n depthStoreOp: WebGPUConstants.StoreOp.Store,\n stencilClearValue: rtWrapper._depthStencilTextureWithStencil && mustClearStencil ? this._clearStencilValue : undefined,\n stencilLoadOp: !depthTextureHasStencil\n ? undefined\n : rtWrapper._depthStencilTextureWithStencil && mustClearStencil\n ? WebGPUConstants.LoadOp.Clear\n : WebGPUConstants.LoadOp.Load,\n stencilStoreOp: !depthTextureHasStencil ? undefined : WebGPUConstants.StoreOp.Store,\n }\n : undefined,\n occlusionQuerySet: ((_f = this._occlusionQuery) === null || _f === void 0 ? void 0 : _f.hasQueries) ? this._occlusionQuery.querySet : undefined,\n };\n this._rttRenderPassWrapper.renderPass = this._renderTargetEncoder.beginRenderPass(this._rttRenderPassWrapper.renderPassDescriptor);\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n const internalTexture = rtWrapper.texture;\n console.log(\"frame #\" + this._count + \" - render target begin pass - internalTexture.uniqueId=\", internalTexture.uniqueId, \"width=\", internalTexture.width, \"height=\", internalTexture.height, this._rttRenderPassWrapper.renderPassDescriptor);\n }\n }\n this._currentRenderPass = this._rttRenderPassWrapper.renderPass;\n (_g = this._debugFlushPendingCommands) === null || _g === void 0 ? void 0 : _g.call(this);\n this._resetCurrentViewport(1);\n this._resetCurrentScissor(1);\n this._resetCurrentStencilRef(1);\n this._resetCurrentColorBlend(1);\n if (!gpuDepthStencilWrapper || !WebGPUTextureHelper.HasStencilAspect(gpuDepthStencilWrapper.format)) {\n this._stencilStateComposer.enabled = false;\n }\n }\n /** @internal */\n _endRenderTargetRenderPass() {\n var _a, _b, _c, _d;\n if (this._currentRenderPass) {\n const gpuWrapper = (_a = this._currentRenderTarget.texture) === null || _a === void 0 ? void 0 : _a._hardwareTexture;\n if (gpuWrapper && !this._snapshotRendering.endRenderTargetPass(this._currentRenderPass, gpuWrapper) && !this.compatibilityMode) {\n this._bundleListRenderTarget.run(this._currentRenderPass);\n this._bundleListRenderTarget.reset();\n }\n this._currentRenderPass.end();\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n console.log(\"frame #\" + this._count + \" - render target end pass - internalTexture.uniqueId=\", (_c = (_b = this._currentRenderTarget) === null || _b === void 0 ? void 0 : _b.texture) === null || _c === void 0 ? void 0 : _c.uniqueId);\n }\n }\n (_d = this._debugPopGroup) === null || _d === void 0 ? void 0 : _d.call(this, 1);\n this._resetCurrentViewport(1);\n this._viewport(0, 0, 0, 0);\n this._resetCurrentScissor(1);\n this._resetCurrentStencilRef(1);\n this._resetCurrentColorBlend(1);\n this._currentRenderPass = null;\n this._rttRenderPassWrapper.reset();\n }\n }\n _getCurrentRenderPass() {\n if (this._currentRenderTarget && !this._currentRenderPass) {\n // delayed creation of the render target pass, but we now need to create it as we are requested the render pass\n this._startRenderTargetRenderPass(this._currentRenderTarget, false, null, false, false);\n }\n else if (!this._currentRenderPass) {\n this._startMainRenderPass(false);\n }\n return this._currentRenderPass;\n }\n /** @internal */\n _getCurrentRenderPassIndex() {\n return this._currentRenderPass === null ? -1 : this._currentRenderPass === this._mainRenderPassWrapper.renderPass ? 0 : 1;\n }\n _startMainRenderPass(setClearStates, clearColor, clearDepth, clearStencil) {\n var _a, _b, _c;\n if (this._mainRenderPassWrapper.renderPass) {\n this.flushFramebuffer(false);\n }\n if (this.useReverseDepthBuffer) {\n this.setDepthFunctionToGreaterOrEqual();\n }\n const mustClearColor = setClearStates && clearColor;\n const mustClearDepth = setClearStates && clearDepth;\n const mustClearStencil = setClearStates && clearStencil;\n this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].clearValue = mustClearColor ? clearColor : undefined;\n this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].loadOp = mustClearColor ? WebGPUConstants.LoadOp.Clear : WebGPUConstants.LoadOp.Load;\n this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthClearValue = mustClearDepth\n ? this.useReverseDepthBuffer\n ? this._clearReverseDepthValue\n : this._clearDepthValue\n : undefined;\n this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.depthLoadOp = mustClearDepth ? WebGPUConstants.LoadOp.Clear : WebGPUConstants.LoadOp.Load;\n this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilClearValue = mustClearStencil ? this._clearStencilValue : undefined;\n this._mainRenderPassWrapper.renderPassDescriptor.depthStencilAttachment.stencilLoadOp = !this.isStencilEnable\n ? undefined\n : mustClearStencil\n ? WebGPUConstants.LoadOp.Clear\n : WebGPUConstants.LoadOp.Load;\n this._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet = ((_a = this._occlusionQuery) === null || _a === void 0 ? void 0 : _a.hasQueries) ? this._occlusionQuery.querySet : undefined;\n const swapChainTexture = this._context.getCurrentTexture();\n this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].set(swapChainTexture);\n // Resolve in case of MSAA\n if (this._options.antialias) {\n viewDescriptorSwapChainAntialiasing.format = swapChainTexture.format;\n this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].resolveTarget = swapChainTexture.createView(viewDescriptorSwapChainAntialiasing);\n }\n else {\n viewDescriptorSwapChain.format = swapChainTexture.format;\n this._mainRenderPassWrapper.renderPassDescriptor.colorAttachments[0].view = swapChainTexture.createView(viewDescriptorSwapChain);\n }\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n console.log(\"frame #\" + this._count + \" - main begin pass - texture width=\" + this._mainTextureExtends.width, \" height=\" + this._mainTextureExtends.height, this._mainRenderPassWrapper.renderPassDescriptor);\n }\n }\n (_b = this._debugPushGroup) === null || _b === void 0 ? void 0 : _b.call(this, \"main pass\", 0);\n this._currentRenderPass = this._renderEncoder.beginRenderPass(this._mainRenderPassWrapper.renderPassDescriptor);\n this._mainRenderPassWrapper.renderPass = this._currentRenderPass;\n (_c = this._debugFlushPendingCommands) === null || _c === void 0 ? void 0 : _c.call(this);\n this._resetCurrentViewport(0);\n this._resetCurrentScissor(0);\n this._resetCurrentStencilRef(0);\n this._resetCurrentColorBlend(0);\n if (!this._isStencilEnable) {\n this._stencilStateComposer.enabled = false;\n }\n }\n _endMainRenderPass() {\n var _a;\n if (this._mainRenderPassWrapper.renderPass !== null) {\n this._snapshotRendering.endMainRenderPass();\n if (!this.compatibilityMode && !this._snapshotRendering.play) {\n this._bundleList.run(this._mainRenderPassWrapper.renderPass);\n this._bundleList.reset();\n }\n this._mainRenderPassWrapper.renderPass.end();\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n console.log(\"frame #\" + this._count + \" - main end pass\");\n }\n }\n (_a = this._debugPopGroup) === null || _a === void 0 ? void 0 : _a.call(this, 0);\n this._resetCurrentViewport(0);\n this._resetCurrentScissor(0);\n this._resetCurrentStencilRef(0);\n this._resetCurrentColorBlend(0);\n if (this._mainRenderPassWrapper.renderPass === this._currentRenderPass) {\n this._currentRenderPass = null;\n }\n this._mainRenderPassWrapper.reset(false);\n }\n }\n /**\n * Binds the frame buffer to the specified texture.\n * @param texture The render target wrapper to render to\n * @param faceIndex The face of the texture to render to in case of cube texture\n * @param requiredWidth The width of the target to render to\n * @param requiredHeight The height of the target to render to\n * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true\n * @param lodLevel defines the lod level to bind to the frame buffer\n * @param layer defines the 2d array index to bind to frame buffer to\n */\n bindFramebuffer(texture, faceIndex = 0, requiredWidth, requiredHeight, forceFullscreenViewport, lodLevel = 0, layer = 0) {\n var _a, _b;\n const hardwareTexture = (_a = texture.texture) === null || _a === void 0 ? void 0 : _a._hardwareTexture;\n if (this._currentRenderTarget) {\n this.unBindFramebuffer(this._currentRenderTarget);\n }\n this._currentRenderTarget = texture;\n if (hardwareTexture) {\n hardwareTexture._currentLayer = texture.isCube ? layer * 6 + faceIndex : layer;\n }\n this._rttRenderPassWrapper.colorAttachmentGPUTextures[0] = hardwareTexture;\n this._rttRenderPassWrapper.depthTextureFormat = this._currentRenderTarget._depthStencilTexture\n ? WebGPUTextureHelper.GetWebGPUTextureFormat(-1, this._currentRenderTarget._depthStencilTexture.format)\n : undefined;\n this._setDepthTextureFormat(this._rttRenderPassWrapper);\n this._setColorFormat(this._rttRenderPassWrapper);\n this._rttRenderPassWrapper.colorAttachmentViewDescriptor = {\n format: this._colorFormat,\n dimension: WebGPUConstants.TextureViewDimension.E2d,\n mipLevelCount: 1,\n baseArrayLayer: texture.isCube ? layer * 6 + faceIndex : layer,\n baseMipLevel: lodLevel,\n arrayLayerCount: 1,\n aspect: WebGPUConstants.TextureAspect.All,\n };\n this._rttRenderPassWrapper.depthAttachmentViewDescriptor = {\n format: this._depthTextureFormat,\n dimension: WebGPUConstants.TextureViewDimension.E2d,\n mipLevelCount: 1,\n baseArrayLayer: texture.isCube ? layer * 6 + faceIndex : layer,\n baseMipLevel: 0,\n arrayLayerCount: 1,\n aspect: WebGPUConstants.TextureAspect.All,\n };\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n console.log(\"frame #\" + this._count + \" - bindFramebuffer called - internalTexture.uniqueId=\", (_b = texture.texture) === null || _b === void 0 ? void 0 : _b.uniqueId, \"face=\", faceIndex, \"lodLevel=\", lodLevel, \"layer=\", layer, this._rttRenderPassWrapper.colorAttachmentViewDescriptor, this._rttRenderPassWrapper.depthAttachmentViewDescriptor);\n }\n }\n this._currentRenderPass = null; // lazy creation of the render pass, hoping the render pass will be created by a call to clear()...\n if (this.snapshotRendering && this.snapshotRenderingMode === 1) {\n // force the creation of the render pass as we know in fast snapshot rendering mode clear() won't be called\n this._getCurrentRenderPass();\n }\n if (this._cachedViewport && !forceFullscreenViewport) {\n this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);\n }\n else {\n if (!requiredWidth) {\n requiredWidth = texture.width;\n if (lodLevel) {\n requiredWidth = requiredWidth / Math.pow(2, lodLevel);\n }\n }\n if (!requiredHeight) {\n requiredHeight = texture.height;\n if (lodLevel) {\n requiredHeight = requiredHeight / Math.pow(2, lodLevel);\n }\n }\n this._viewport(0, 0, requiredWidth, requiredHeight);\n }\n this.wipeCaches();\n }\n /**\n * Unbind the current render target texture from the WebGPU context\n * @param texture defines the render target wrapper to unbind\n * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated\n * @param onBeforeUnbind defines a function which will be called before the effective unbind\n */\n unBindFramebuffer(texture, disableGenerateMipMaps = false, onBeforeUnbind) {\n var _a, _b;\n const saveCRT = this._currentRenderTarget;\n this._currentRenderTarget = null; // to be iso with thinEngine, this._currentRenderTarget must be null when onBeforeUnbind is called\n if (onBeforeUnbind) {\n onBeforeUnbind();\n }\n this._currentRenderTarget = saveCRT;\n if (this._currentRenderPass && this._currentRenderPass !== this._mainRenderPassWrapper.renderPass) {\n this._endRenderTargetRenderPass();\n }\n if (((_a = texture.texture) === null || _a === void 0 ? void 0 : _a.generateMipMaps) && !disableGenerateMipMaps && !texture.isCube) {\n this._generateMipmaps(texture.texture);\n }\n this._currentRenderTarget = null;\n this._onAfterUnbindFrameBufferObservable.notifyObservers(this);\n if (this.dbgVerboseLogsForFirstFrames) {\n if (this._count === undefined) {\n this._count = 0;\n }\n if (!this._count || this._count < this.dbgVerboseLogsNumFrames) {\n console.log(\"frame #\" + this._count + \" - unBindFramebuffer called - internalTexture.uniqueId=\", (_b = texture.texture) === null || _b === void 0 ? void 0 : _b.uniqueId);\n }\n }\n this._mrtAttachments = [];\n this._cacheRenderPipeline.setMRT([]);\n this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments);\n this._currentRenderPass = this._mainRenderPassWrapper.renderPass;\n this._setDepthTextureFormat(this._mainRenderPassWrapper);\n this._setColorFormat(this._mainRenderPassWrapper);\n }\n /**\n * Unbind the current render target and bind the default framebuffer\n */\n restoreDefaultFramebuffer() {\n if (this._currentRenderTarget) {\n this.unBindFramebuffer(this._currentRenderTarget);\n }\n else {\n this._currentRenderPass = this._mainRenderPassWrapper.renderPass;\n this._setDepthTextureFormat(this._mainRenderPassWrapper);\n this._setColorFormat(this._mainRenderPassWrapper);\n }\n if (this._currentRenderPass) {\n if (this._cachedViewport) {\n this.setViewport(this._cachedViewport);\n }\n }\n this.wipeCaches();\n }\n //------------------------------------------------------------------------------\n // Render\n //------------------------------------------------------------------------------\n /**\n * @internal\n */\n _setColorFormat(wrapper) {\n var _a, _b;\n const format = (_b = (_a = wrapper.colorAttachmentGPUTextures[0]) === null || _a === void 0 ? void 0 : _a.format) !== null && _b !== void 0 ? _b : null;\n this._cacheRenderPipeline.setColorFormat(format);\n if (this._colorFormat === format) {\n return;\n }\n this._colorFormat = format;\n }\n /**\n * @internal\n */\n _setDepthTextureFormat(wrapper) {\n this._cacheRenderPipeline.setDepthStencilFormat(wrapper.depthTextureFormat);\n if (this._depthTextureFormat === wrapper.depthTextureFormat) {\n return;\n }\n this._depthTextureFormat = wrapper.depthTextureFormat;\n }\n setDitheringState() {\n // Does not exist in WebGPU\n }\n setRasterizerState() {\n // Does not exist in WebGPU\n }\n /**\n * Set various states to the webGL context\n * @param culling defines culling state: true to enable culling, false to disable it\n * @param zOffset defines the value to apply to zOffset (0 by default)\n * @param force defines if states must be applied even if cache is up to date\n * @param reverseSide defines if culling must be reversed (CCW if false, CW if true)\n * @param cullBackFaces true to cull back faces, false to cull front faces (if culling is enabled)\n * @param stencil stencil states to set\n * @param zOffsetUnits defines the value to apply to zOffsetUnits (0 by default)\n */\n setState(culling, zOffset = 0, force, reverseSide = false, cullBackFaces, stencil, zOffsetUnits = 0) {\n var _a, _b;\n // Culling\n if (this._depthCullingState.cull !== culling || force) {\n this._depthCullingState.cull = culling;\n }\n // Cull face\n const cullFace = ((_b = (_a = this.cullBackFaces) !== null && _a !== void 0 ? _a : cullBackFaces) !== null && _b !== void 0 ? _b : true) ? 1 : 2;\n if (this._depthCullingState.cullFace !== cullFace || force) {\n this._depthCullingState.cullFace = cullFace;\n }\n // Z offset\n this.setZOffset(zOffset);\n this.setZOffsetUnits(zOffsetUnits);\n // Front face\n const frontFace = reverseSide ? (this._currentRenderTarget ? 1 : 2) : this._currentRenderTarget ? 2 : 1;\n if (this._depthCullingState.frontFace !== frontFace || force) {\n this._depthCullingState.frontFace = frontFace;\n }\n this._stencilStateComposer.stencilMaterial = stencil;\n }\n _applyRenderPassChanges(renderPass, bundleList) {\n var _a;\n const mustUpdateViewport = this._mustUpdateViewport(renderPass);\n const mustUpdateScissor = this._mustUpdateScissor(renderPass);\n const mustUpdateStencilRef = !this._stencilStateComposer.enabled ? false : this._mustUpdateStencilRef(renderPass);\n const mustUpdateBlendColor = !this._alphaState.alphaBlend ? false : this._mustUpdateBlendColor(renderPass);\n if (bundleList) {\n if (mustUpdateViewport) {\n bundleList.addItem(new WebGPURenderItemViewport(this._viewportCached.x, this._viewportCached.y, this._viewportCached.z, this._viewportCached.w));\n }\n if (mustUpdateScissor) {\n bundleList.addItem(new WebGPURenderItemScissor(this._scissorCached.x, this._scissorCached.y, this._scissorCached.z, this._scissorCached.w));\n }\n if (mustUpdateStencilRef) {\n bundleList.addItem(new WebGPURenderItemStencilRef((_a = this._stencilStateComposer.funcRef) !== null && _a !== void 0 ? _a : 0));\n }\n if (mustUpdateBlendColor) {\n bundleList.addItem(new WebGPURenderItemBlendColor(this._alphaState._blendConstants.slice()));\n }\n }\n else {\n if (mustUpdateViewport) {\n this._applyViewport(renderPass);\n }\n if (mustUpdateScissor) {\n this._applyScissor(renderPass);\n }\n if (mustUpdateStencilRef) {\n this._applyStencilRef(renderPass);\n }\n if (mustUpdateBlendColor) {\n this._applyBlendColor(renderPass);\n }\n }\n }\n _draw(drawType, fillMode, start, count, instancesCount) {\n var _a;\n const renderPass = this._getCurrentRenderPass();\n const renderPassIndex = this._getCurrentRenderPassIndex();\n const bundleList = renderPassIndex === 0 ? this._bundleList : this._bundleListRenderTarget;\n this.applyStates();\n const webgpuPipelineContext = this._currentEffect._pipelineContext;\n this.bindUniformBufferBase(this._currentRenderTarget ? this._ubInvertY : this._ubDontInvertY, 0, WebGPUShaderProcessor.InternalsUBOName);\n if (webgpuPipelineContext.uniformBuffer) {\n webgpuPipelineContext.uniformBuffer.update();\n this.bindUniformBufferBase(webgpuPipelineContext.uniformBuffer.getBuffer(), 0, WebGPUShaderProcessor.LeftOvertUBOName);\n }\n if (this._snapshotRendering.play) {\n this._reportDrawCall();\n return;\n }\n if (!this.compatibilityMode &&\n (this._currentDrawContext.isDirty(this._currentMaterialContext.updateId) || this._currentMaterialContext.isDirty || this._currentMaterialContext.forceBindGroupCreation)) {\n this._currentDrawContext.fastBundle = undefined;\n }\n const useFastPath = !this.compatibilityMode && this._currentDrawContext.fastBundle;\n let renderPass2 = renderPass;\n if (useFastPath || this._snapshotRendering.record) {\n this._applyRenderPassChanges(renderPass, bundleList);\n if (!this._snapshotRendering.record) {\n this._counters.numBundleReuseNonCompatMode++;\n if (this._currentDrawContext.indirectDrawBuffer) {\n this._currentDrawContext.setIndirectData(count, instancesCount || 1, start);\n }\n bundleList.addBundle(this._currentDrawContext.fastBundle);\n this._reportDrawCall();\n return;\n }\n renderPass2 = bundleList.getBundleEncoder(this._cacheRenderPipeline.colorFormats, this._depthTextureFormat, this.currentSampleCount); // for snapshot recording mode\n bundleList.numDrawCalls++;\n }\n let textureState = 0;\n if (!this._caps.textureFloatLinearFiltering && this._currentMaterialContext.hasFloatTextures) {\n let bitVal = 1;\n for (let i = 0; i < webgpuPipelineContext.shaderProcessingContext.textureNames.length; ++i) {\n const textureName = webgpuPipelineContext.shaderProcessingContext.textureNames[i];\n const texture = (_a = this._currentMaterialContext.textures[textureName]) === null || _a === void 0 ? void 0 : _a.texture;\n if ((texture === null || texture === void 0 ? void 0 : texture.type) === 1) {\n textureState |= bitVal;\n }\n bitVal = bitVal << 1;\n }\n }\n this._currentMaterialContext.textureState = textureState;\n const pipeline = this._cacheRenderPipeline.getRenderPipeline(fillMode, this._currentEffect, this.currentSampleCount, textureState);\n const bindGroups = this._cacheBindGroups.getBindGroups(webgpuPipelineContext, this._currentDrawContext, this._currentMaterialContext);\n if (!this._snapshotRendering.record) {\n this._applyRenderPassChanges(renderPass, !this.compatibilityMode ? bundleList : null);\n if (!this.compatibilityMode) {\n this._counters.numBundleCreationNonCompatMode++;\n renderPass2 = this._device.createRenderBundleEncoder({\n colorFormats: this._cacheRenderPipeline.colorFormats,\n depthStencilFormat: this._depthTextureFormat,\n sampleCount: this.currentSampleCount,\n });\n }\n }\n // bind pipeline\n renderPass2.setPipeline(pipeline);\n // bind index/vertex buffers\n if (this._currentIndexBuffer) {\n renderPass2.setIndexBuffer(this._currentIndexBuffer.underlyingResource, this._currentIndexBuffer.is32Bits ? WebGPUConstants.IndexFormat.Uint32 : WebGPUConstants.IndexFormat.Uint16, 0);\n }\n const vertexBuffers = this._cacheRenderPipeline.vertexBuffers;\n for (let index = 0; index < vertexBuffers.length; index++) {\n const vertexBuffer = vertexBuffers[index];\n const buffer = vertexBuffer.getBuffer();\n if (buffer) {\n renderPass2.setVertexBuffer(index, buffer.underlyingResource, vertexBuffer._validOffsetRange ? 0 : vertexBuffer.byteOffset);\n }\n }\n // bind bind groups\n for (let i = 0; i < bindGroups.length; i++) {\n renderPass2.setBindGroup(i, bindGroups[i]);\n }\n // draw\n const nonCompatMode = !this.compatibilityMode && !this._snapshotRendering.record;\n if (nonCompatMode && this._currentDrawContext.indirectDrawBuffer) {\n this._currentDrawContext.setIndirectData(count, instancesCount || 1, start);\n if (drawType === 0) {\n renderPass2.drawIndexedIndirect(this._currentDrawContext.indirectDrawBuffer, 0);\n }\n else {\n renderPass2.drawIndirect(this._currentDrawContext.indirectDrawBuffer, 0);\n }\n }\n else if (drawType === 0) {\n renderPass2.drawIndexed(count, instancesCount || 1, start, 0, 0);\n }\n else {\n renderPass2.draw(count, instancesCount || 1, start, 0);\n }\n if (nonCompatMode) {\n this._currentDrawContext.fastBundle = renderPass2.finish();\n bundleList.addBundle(this._currentDrawContext.fastBundle);\n }\n this._reportDrawCall();\n }\n /**\n * Draw a list of indexed primitives\n * @param fillMode defines the primitive to use\n * @param indexStart defines the starting index\n * @param indexCount defines the number of index to draw\n * @param instancesCount defines the number of instances to draw (if instantiation is enabled)\n */\n drawElementsType(fillMode, indexStart, indexCount, instancesCount = 1) {\n this._draw(0, fillMode, indexStart, indexCount, instancesCount);\n }\n /**\n * Draw a list of unindexed primitives\n * @param fillMode defines the primitive to use\n * @param verticesStart defines the index of first vertex to draw\n * @param verticesCount defines the count of vertices to draw\n * @param instancesCount defines the number of instances to draw (if instantiation is enabled)\n */\n drawArraysType(fillMode, verticesStart, verticesCount, instancesCount = 1) {\n this._currentIndexBuffer = null;\n this._draw(1, fillMode, verticesStart, verticesCount, instancesCount);\n }\n //------------------------------------------------------------------------------\n // Dispose\n //------------------------------------------------------------------------------\n /**\n * Dispose and release all associated resources\n */\n dispose() {\n var _a, _b;\n this._isDisposed = true;\n (_a = this._mainTexture) === null || _a === void 0 ? void 0 : _a.destroy();\n (_b = this._depthTexture) === null || _b === void 0 ? void 0 : _b.destroy();\n this._device.destroy();\n super.dispose();\n }\n //------------------------------------------------------------------------------\n // Misc\n //------------------------------------------------------------------------------\n /**\n * Gets the current render width\n * @param useScreen defines if screen size must be used (or the current render target if any)\n * @returns a number defining the current render width\n */\n getRenderWidth(useScreen = false) {\n var _a, _b;\n if (!useScreen && this._currentRenderTarget) {\n return this._currentRenderTarget.width;\n }\n return (_b = (_a = this._renderingCanvas) === null || _a === void 0 ? void 0 : _a.width) !== null && _b !== void 0 ? _b : 0;\n }\n /**\n * Gets the current render height\n * @param useScreen defines if screen size must be used (or the current render target if any)\n * @returns a number defining the current render height\n */\n getRenderHeight(useScreen = false) {\n var _a, _b;\n if (!useScreen && this._currentRenderTarget) {\n return this._currentRenderTarget.height;\n }\n return (_b = (_a = this._renderingCanvas) === null || _a === void 0 ? void 0 : _a.height) !== null && _b !== void 0 ? _b : 0;\n }\n //------------------------------------------------------------------------------\n // Errors\n //------------------------------------------------------------------------------\n /**\n * Get the current error code of the WebGPU context\n * @returns the error code\n */\n getError() {\n // TODO WEBGPU. from the webgpu errors.\n return 0;\n }\n //------------------------------------------------------------------------------\n // Unused WebGPU\n //------------------------------------------------------------------------------\n /**\n * @internal\n */\n bindSamplers() { }\n /**\n * @internal\n */\n _bindTextureDirectly() {\n return false;\n }\n /**\n * Gets a boolean indicating if all created effects are ready\n * @returns always true - No parallel shader compilation\n */\n areAllEffectsReady() {\n return true;\n }\n /**\n * @internal\n */\n _executeWhenRenderingStateIsCompiled(pipelineContext, action) {\n // No parallel shader compilation.\n // No Async, so direct launch\n action();\n }\n /**\n * @internal\n */\n _isRenderingStateCompiled() {\n // No parallel shader compilation.\n return true;\n }\n /** @internal */\n _getUnpackAlignement() {\n return 1;\n }\n /**\n * @internal\n */\n _unpackFlipY() { }\n /**\n * @internal\n */\n _bindUnboundFramebuffer() {\n throw \"_bindUnboundFramebuffer is not implementedin WebGPU! You probably want to use restoreDefaultFramebuffer or unBindFramebuffer instead\";\n }\n // TODO WEBGPU. All of the below should go once engine split with baseEngine.\n /**\n * @internal\n */\n _getSamplingParameters() {\n throw \"_getSamplingParameters is not available in WebGPU\";\n }\n /**\n * @internal\n */\n getUniforms() {\n return [];\n }\n /**\n * @internal\n */\n setIntArray() {\n return false;\n }\n /**\n * @internal\n */\n setIntArray2() {\n return false;\n }\n /**\n * @internal\n */\n setIntArray3() {\n return false;\n }\n /**\n * @internal\n */\n setIntArray4() {\n return false;\n }\n /**\n * @internal\n */\n setArray() {\n return false;\n }\n /**\n * @internal\n */\n setArray2() {\n return false;\n }\n /**\n * @internal\n */\n setArray3() {\n return false;\n }\n /**\n * @internal\n */\n setArray4() {\n return false;\n }\n /**\n * @internal\n */\n setMatrices() {\n return false;\n }\n /**\n * @internal\n */\n setMatrix3x3() {\n return false;\n }\n /**\n * @internal\n */\n setMatrix2x2() {\n return false;\n }\n /**\n * @internal\n */\n setFloat() {\n return false;\n }\n /**\n * @internal\n */\n setFloat2() {\n return false;\n }\n /**\n * @internal\n */\n setFloat3() {\n return false;\n }\n /**\n * @internal\n */\n setFloat4() {\n return false;\n }\n}\n// Default glslang options.\nWebGPUEngine._GLSLslangDefaultOptions = {\n jsPath: \"https://preview.babylonjs.com/glslang/glslang.js\",\n wasmPath: \"https://preview.babylonjs.com/glslang/glslang.wasm\",\n};\n/** true to enable using TintWASM to convert Spir-V to WGSL */\nWebGPUEngine.UseTWGSL = true;\n//# sourceMappingURL=webgpuEngine.js.map","\nimport { Engine } from \"../../engine.js\";\nimport { WebGPUEngine } from \"../../webgpuEngine.js\";\nWebGPUEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange = false) {\n if (this._alphaMode === mode && ((mode === 0 && !this._alphaState.alphaBlend) || (mode !== 0 && this._alphaState.alphaBlend))) {\n if (!noDepthWriteChange) {\n // Make sure we still have the correct depth mask according to the alpha mode (a transparent material could have forced writting to the depth buffer, for instance)\n const depthMask = mode === 0;\n if (this.depthCullingState.depthMask !== depthMask) {\n this.setDepthWrite(depthMask);\n this._cacheRenderPipeline.setDepthWriteEnabled(depthMask);\n }\n }\n return;\n }\n switch (mode) {\n case 0:\n this._alphaState.alphaBlend = false;\n break;\n case 7:\n this._alphaState.setAlphaBlendFunctionParameters(1, 771, 1, 1);\n this._alphaState.alphaBlend = true;\n break;\n case 8:\n this._alphaState.setAlphaBlendFunctionParameters(1, 771, 1, 771);\n this._alphaState.alphaBlend = true;\n break;\n case 2:\n this._alphaState.setAlphaBlendFunctionParameters(770, 771, 1, 1);\n this._alphaState.alphaBlend = true;\n break;\n case 6:\n this._alphaState.setAlphaBlendFunctionParameters(1, 1, 0, 1);\n this._alphaState.alphaBlend = true;\n break;\n case 1:\n this._alphaState.setAlphaBlendFunctionParameters(770, 1, 0, 1);\n this._alphaState.alphaBlend = true;\n break;\n case 3:\n this._alphaState.setAlphaBlendFunctionParameters(0, 769, 1, 1);\n this._alphaState.alphaBlend = true;\n break;\n case 4:\n this._alphaState.setAlphaBlendFunctionParameters(774, 0, 1, 1);\n this._alphaState.alphaBlend = true;\n break;\n case 5:\n this._alphaState.setAlphaBlendFunctionParameters(770, 769, 1, 1);\n this._alphaState.alphaBlend = true;\n break;\n case 9:\n this._alphaState.setAlphaBlendFunctionParameters(32769, 32770, 32771, 32772);\n this._alphaState.alphaBlend = true;\n break;\n case 10:\n this._alphaState.setAlphaBlendFunctionParameters(1, 769, 1, 771);\n this._alphaState.alphaBlend = true;\n break;\n case 11:\n this._alphaState.setAlphaBlendFunctionParameters(1, 1, 1, 1);\n this._alphaState.alphaBlend = true;\n break;\n case 12:\n this._alphaState.setAlphaBlendFunctionParameters(772, 1, 0, 0);\n this._alphaState.alphaBlend = true;\n break;\n case 13:\n this._alphaState.setAlphaBlendFunctionParameters(775, 769, 773, 771);\n this._alphaState.alphaBlend = true;\n break;\n case 14:\n this._alphaState.setAlphaBlendFunctionParameters(1, 771, 1, 771);\n this._alphaState.alphaBlend = true;\n break;\n case 15:\n this._alphaState.setAlphaBlendFunctionParameters(1, 1, 1, 0);\n this._alphaState.alphaBlend = true;\n break;\n case 16:\n this._alphaState.setAlphaBlendFunctionParameters(775, 769, 0, 1);\n this._alphaState.alphaBlend = true;\n break;\n case 17:\n // Same as ALPHA_COMBINE but accumulates (1 - alpha) values in the alpha channel for a later readout in order independant transparency\n this._alphaState.setAlphaBlendFunctionParameters(770, 771, 1, 771);\n this._alphaState.alphaBlend = true;\n break;\n }\n if (!noDepthWriteChange) {\n this.setDepthWrite(mode === Engine.ALPHA_DISABLE);\n this._cacheRenderPipeline.setDepthWriteEnabled(mode === Engine.ALPHA_DISABLE);\n }\n this._alphaMode = mode;\n this._cacheRenderPipeline.setAlphaBlendEnabled(this._alphaState.alphaBlend);\n this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters, this._alphaState._blendEquationParameters);\n};\nWebGPUEngine.prototype.setAlphaEquation = function (equation) {\n Engine.prototype.setAlphaEquation.call(this, equation);\n this._cacheRenderPipeline.setAlphaBlendFactors(this._alphaState._blendFunctionParameters, this._alphaState._blendEquationParameters);\n};\n//# sourceMappingURL=engine.alpha.js.map","import { Logger } from \"../../Misc/logger.js\";\nimport { ComputeBindingType } from \"../Extensions/engine.computeShader.js\";\nimport * as WebGPUConstants from \"./webgpuConstants.js\";\n/** @internal */\nexport class WebGPUComputeContext {\n getBindGroups(bindings, computePipeline, bindingsMapping) {\n if (!bindingsMapping) {\n throw new Error(\"WebGPUComputeContext.getBindGroups: bindingsMapping is required until browsers support reflection for wgsl shaders!\");\n }\n if (this._bindGroups.length === 0) {\n const bindGroupEntriesExist = this._bindGroupEntries.length > 0;\n for (const key in bindings) {\n const binding = bindings[key], location = bindingsMapping[key], group = location.group, index = location.binding, type = binding.type, object = binding.object;\n let indexInGroupEntries = binding.indexInGroupEntries;\n let entries = this._bindGroupEntries[group];\n if (!entries) {\n entries = this._bindGroupEntries[group] = [];\n }\n switch (type) {\n case ComputeBindingType.Sampler: {\n const sampler = object;\n if (indexInGroupEntries !== undefined && bindGroupEntriesExist) {\n entries[indexInGroupEntries].resource = this._cacheSampler.getSampler(sampler);\n }\n else {\n binding.indexInGroupEntries = entries.length;\n entries.push({\n binding: index,\n resource: this._cacheSampler.getSampler(sampler),\n });\n }\n break;\n }\n case ComputeBindingType.Texture:\n case ComputeBindingType.TextureWithoutSampler: {\n const texture = object;\n const hardwareTexture = texture._texture._hardwareTexture;\n if (indexInGroupEntries !== undefined && bindGroupEntriesExist) {\n if (type === ComputeBindingType.Texture) {\n entries[indexInGroupEntries++].resource = this._cacheSampler.getSampler(texture._texture);\n }\n entries[indexInGroupEntries].resource = hardwareTexture.view;\n }\n else {\n binding.indexInGroupEntries = entries.length;\n if (type === ComputeBindingType.Texture) {\n entries.push({\n binding: index - 1,\n resource: this._cacheSampler.getSampler(texture._texture),\n });\n }\n entries.push({\n binding: index,\n resource: hardwareTexture.view,\n });\n }\n break;\n }\n case ComputeBindingType.StorageTexture: {\n const texture = object;\n const hardwareTexture = texture._texture._hardwareTexture;\n if ((hardwareTexture.textureAdditionalUsages & WebGPUConstants.TextureUsage.StorageBinding) === 0) {\n Logger.Error(`computeDispatch: The texture (name=${texture.name}, uniqueId=${texture.uniqueId}) is not a storage texture!`, 50);\n }\n if (indexInGroupEntries !== undefined && bindGroupEntriesExist) {\n entries[indexInGroupEntries].resource = hardwareTexture.viewForWriting;\n }\n else {\n binding.indexInGroupEntries = entries.length;\n entries.push({\n binding: index,\n resource: hardwareTexture.viewForWriting,\n });\n }\n break;\n }\n case ComputeBindingType.UniformBuffer:\n case ComputeBindingType.StorageBuffer: {\n const buffer = type === ComputeBindingType.UniformBuffer ? object : object;\n const dataBuffer = buffer.getBuffer();\n const webgpuBuffer = dataBuffer.underlyingResource;\n if (indexInGroupEntries !== undefined && bindGroupEntriesExist) {\n entries[indexInGroupEntries].resource.buffer = webgpuBuffer;\n entries[indexInGroupEntries].resource.size = dataBuffer.capacity;\n }\n else {\n binding.indexInGroupEntries = entries.length;\n entries.push({\n binding: index,\n resource: {\n buffer: webgpuBuffer,\n offset: 0,\n size: dataBuffer.capacity,\n },\n });\n }\n break;\n }\n }\n }\n for (let i = 0; i < this._bindGroupEntries.length; ++i) {\n const entries = this._bindGroupEntries[i];\n if (!entries) {\n this._bindGroups[i] = undefined;\n continue;\n }\n this._bindGroups[i] = this._device.createBindGroup({\n layout: computePipeline.getBindGroupLayout(i),\n entries,\n });\n }\n this._bindGroups.length = this._bindGroupEntries.length;\n }\n return this._bindGroups;\n }\n constructor(device, cacheSampler) {\n this._device = device;\n this._cacheSampler = cacheSampler;\n this.uniqueId = WebGPUComputeContext._Counter++;\n this._bindGroupEntries = [];\n this.clear();\n }\n clear() {\n this._bindGroups = [];\n // Don't reset _bindGroupEntries if they have already been created, they are still ok even if we have to clear _bindGroups (the layout of the compute shader can't change once created)\n }\n}\nWebGPUComputeContext._Counter = 0;\n//# sourceMappingURL=webgpuComputeContext.js.map","/** @internal */\nexport class WebGPUComputePipelineContext {\n get isAsync() {\n return false;\n }\n get isReady() {\n if (this.stage) {\n return true;\n }\n return false;\n }\n constructor(engine) {\n this._name = \"unnamed\";\n this.engine = engine;\n }\n _getComputeShaderCode() {\n var _a;\n return (_a = this.sources) === null || _a === void 0 ? void 0 : _a.compute;\n }\n dispose() { }\n}\n//# sourceMappingURL=webgpuComputePipelineContext.js.map","import { ComputeEffect } from \"../../../Compute/computeEffect.js\";\nimport { WebGPUEngine } from \"../../webgpuEngine.js\";\nimport { WebGPUComputeContext } from \"../webgpuComputeContext.js\";\nimport { WebGPUComputePipelineContext } from \"../webgpuComputePipelineContext.js\";\nimport * as WebGPUConstants from \"../webgpuConstants.js\";\nWebGPUEngine.prototype.createComputeContext = function () {\n return new WebGPUComputeContext(this._device, this._cacheSampler);\n};\nWebGPUEngine.prototype.createComputeEffect = function (baseName, options) {\n const compute = baseName.computeElement || baseName.compute || baseName.computeToken || baseName.computeSource || baseName;\n const name = compute + \"@\" + options.defines;\n if (this._compiledComputeEffects[name]) {\n const compiledEffect = this._compiledComputeEffects[name];\n if (options.onCompiled && compiledEffect.isReady()) {\n options.onCompiled(compiledEffect);\n }\n return compiledEffect;\n }\n const effect = new ComputeEffect(baseName, options, this, name);\n this._compiledComputeEffects[name] = effect;\n return effect;\n};\nWebGPUEngine.prototype.createComputePipelineContext = function () {\n return new WebGPUComputePipelineContext(this);\n};\nWebGPUEngine.prototype.areAllComputeEffectsReady = function () {\n for (const key in this._compiledComputeEffects) {\n const effect = this._compiledComputeEffects[key];\n if (!effect.isReady()) {\n return false;\n }\n }\n return true;\n};\nWebGPUEngine.prototype.computeDispatch = function (effect, context, bindings, x, y, z, bindingsMapping) {\n if (this._currentRenderTarget) {\n // A render target pass is currently in effect (meaning beingRenderPass has been called on the command encoder this._renderTargetEncoder): we are not allowed to open\n // another pass on this command encoder (even if it's a compute pass) until endPass has been called, so we need to defer the compute pass for after the current render target pass is closed\n this._onAfterUnbindFrameBufferObservable.addOnce(() => {\n this.computeDispatch(effect, context, bindings, x, y, z, bindingsMapping);\n });\n return;\n }\n const contextPipeline = effect._pipelineContext;\n const computeContext = context;\n if (!contextPipeline.computePipeline) {\n contextPipeline.computePipeline = this._device.createComputePipeline({\n layout: WebGPUConstants.AutoLayoutMode.Auto,\n compute: contextPipeline.stage,\n });\n }\n const commandEncoder = this._renderTargetEncoder;\n const computePass = commandEncoder.beginComputePass();\n computePass.setPipeline(contextPipeline.computePipeline);\n const bindGroups = computeContext.getBindGroups(bindings, contextPipeline.computePipeline, bindingsMapping);\n for (let i = 0; i < bindGroups.length; ++i) {\n const bindGroup = bindGroups[i];\n if (!bindGroup) {\n continue;\n }\n computePass.setBindGroup(i, bindGroup);\n }\n computePass.dispatchWorkgroups(x, y, z);\n computePass.end();\n};\nWebGPUEngine.prototype.releaseComputeEffects = function () {\n for (const name in this._compiledComputeEffects) {\n const webGPUPipelineContextCompute = this._compiledComputeEffects[name].getPipelineContext();\n this._deleteComputePipelineContext(webGPUPipelineContextCompute);\n }\n this._compiledComputeEffects = {};\n};\nWebGPUEngine.prototype._prepareComputePipelineContext = function (pipelineContext, computeSourceCode, rawComputeSourceCode, defines, entryPoint) {\n const webGpuContext = pipelineContext;\n if (this.dbgShowShaderCode) {\n console.log(defines);\n console.log(computeSourceCode);\n }\n webGpuContext.sources = {\n compute: computeSourceCode,\n rawCompute: rawComputeSourceCode,\n };\n webGpuContext.stage = this._createComputePipelineStageDescriptor(computeSourceCode, defines, entryPoint);\n};\nWebGPUEngine.prototype._releaseComputeEffect = function (effect) {\n if (this._compiledComputeEffects[effect._key]) {\n delete this._compiledComputeEffects[effect._key];\n this._deleteComputePipelineContext(effect.getPipelineContext());\n }\n};\nWebGPUEngine.prototype._rebuildComputeEffects = function () {\n for (const key in this._compiledComputeEffects) {\n const effect = this._compiledComputeEffects[key];\n effect._pipelineContext = null;\n effect._wasPreviouslyReady = false;\n effect._prepareEffect();\n }\n};\nWebGPUEngine.prototype._deleteComputePipelineContext = function (pipelineContext) {\n const webgpuPipelineContext = pipelineContext;\n if (webgpuPipelineContext) {\n pipelineContext.dispose();\n }\n};\nWebGPUEngine.prototype._createComputePipelineStageDescriptor = function (computeShader, defines, entryPoint) {\n if (defines) {\n defines = \"//\" + defines.split(\"\\n\").join(\"\\n//\") + \"\\n\";\n }\n else {\n defines = \"\";\n }\n return {\n module: this._device.createShaderModule({\n code: defines + computeShader,\n }),\n entryPoint,\n };\n};\n//# sourceMappingURL=engine.computeShader.js.map","import { InternalTexture, InternalTextureSource } from \"../../../Materials/Textures/internalTexture.js\";\n\nimport { WebGPUEngine } from \"../../webgpuEngine.js\";\nWebGPUEngine.prototype._createDepthStencilCubeTexture = function (size, options) {\n const internalTexture = new InternalTexture(this, InternalTextureSource.DepthStencil);\n internalTexture.isCube = true;\n const internalOptions = Object.assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false, samples: 1 }, options);\n // TODO WEBGPU allow to choose the format?\n internalTexture.format = internalOptions.generateStencil ? 13 : 14;\n this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction, internalOptions.samples);\n this._textureHelper.createGPUTextureForInternalTexture(internalTexture);\n this._internalTexturesCache.push(internalTexture);\n return internalTexture;\n};\nWebGPUEngine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = false, lodScale = 0, lodOffset = 0, fallback = null, useSRGBBuffer = false) {\n return this.createCubeTextureBase(rootUrl, scene, files, !!noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback, null, (texture, imgs) => {\n const imageBitmaps = imgs; // we will always get an ImageBitmap array in WebGPU\n const width = imageBitmaps[0].width;\n const height = width;\n this._setCubeMapTextureParams(texture, !noMipmap);\n texture.format = format !== null && format !== void 0 ? format : -1;\n const gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, width, height);\n this._textureHelper.updateCubeTextures(imageBitmaps, gpuTextureWrapper.underlyingResource, width, height, gpuTextureWrapper.format, false, false, 0, 0);\n if (!noMipmap) {\n this._generateMipmaps(texture, this._uploadEncoder);\n }\n texture.isReady = true;\n texture.onLoadedObservable.notifyObservers(texture);\n texture.onLoadedObservable.clear();\n if (onLoad) {\n onLoad();\n }\n }, !!useSRGBBuffer);\n};\nWebGPUEngine.prototype._setCubeMapTextureParams = function (texture, loadMipmap, maxLevel) {\n texture.samplingMode = loadMipmap ? 3 : 2;\n texture._cachedWrapU = 0;\n texture._cachedWrapV = 0;\n if (maxLevel) {\n texture._maxLodLevel = maxLevel;\n }\n};\n//# sourceMappingURL=engine.cubeTexture.js.map","import { WebGPUEngine } from \"../../webgpuEngine.js\";\nWebGPUEngine.prototype._debugPushGroup = function (groupName, targetObject) {\n if (!this._options.enableGPUDebugMarkers) {\n return;\n }\n if (targetObject === 0 || targetObject === 1) {\n const encoder = targetObject === 0 ? this._renderEncoder : this._renderTargetEncoder;\n encoder.pushDebugGroup(groupName);\n }\n else if (this._currentRenderPass) {\n this._currentRenderPass.pushDebugGroup(groupName);\n }\n else {\n this._pendingDebugCommands.push([\"push\", groupName]);\n }\n};\nWebGPUEngine.prototype._debugPopGroup = function (targetObject) {\n if (!this._options.enableGPUDebugMarkers) {\n return;\n }\n if (targetObject === 0 || targetObject === 1) {\n const encoder = targetObject === 0 ? this._renderEncoder : this._renderTargetEncoder;\n encoder.popDebugGroup();\n }\n else if (this._currentRenderPass) {\n this._currentRenderPass.popDebugGroup();\n }\n else {\n this._pendingDebugCommands.push([\"pop\", null]);\n }\n};\nWebGPUEngine.prototype._debugInsertMarker = function (text, targetObject) {\n if (!this._options.enableGPUDebugMarkers) {\n return;\n }\n if (targetObject === 0 || targetObject === 1) {\n const encoder = targetObject === 0 ? this._renderEncoder : this._renderTargetEncoder;\n encoder.insertDebugMarker(text);\n }\n else if (this._currentRenderPass) {\n this._currentRenderPass.insertDebugMarker(text);\n }\n else {\n this._pendingDebugCommands.push([\"insert\", text]);\n }\n};\nWebGPUEngine.prototype._debugFlushPendingCommands = function () {\n for (let i = 0; i < this._pendingDebugCommands.length; ++i) {\n const [name, param] = this._pendingDebugCommands[i];\n switch (name) {\n case \"push\":\n this._debugPushGroup(param);\n break;\n case \"pop\":\n this._debugPopGroup();\n break;\n case \"insert\":\n this._debugInsertMarker(param);\n break;\n }\n }\n this._pendingDebugCommands.length = 0;\n};\n//# sourceMappingURL=engine.debugging.js.map","import { WebGPUEngine } from \"../../webgpuEngine.js\";\nWebGPUEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset = 0) {\n const gpuBuffer = indexBuffer;\n let view;\n if (indexBuffer.is32Bits) {\n view = indices instanceof Uint32Array ? indices : new Uint32Array(indices);\n }\n else {\n view = indices instanceof Uint16Array ? indices : new Uint16Array(indices);\n }\n this._bufferManager.setSubData(gpuBuffer, offset, view);\n};\nWebGPUEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {\n const dataBuffer = vertexBuffer;\n if (byteOffset === undefined) {\n byteOffset = 0;\n }\n let view;\n if (byteLength === undefined) {\n if (data instanceof Array) {\n view = new Float32Array(data);\n }\n else if (data instanceof ArrayBuffer) {\n view = new Uint8Array(data);\n }\n else {\n view = data;\n }\n byteLength = view.byteLength;\n }\n else {\n if (data instanceof Array) {\n view = new Float32Array(data);\n }\n else if (data instanceof ArrayBuffer) {\n view = new Uint8Array(data);\n }\n else {\n view = data;\n }\n }\n this._bufferManager.setSubData(dataBuffer, byteOffset, view, 0, byteLength);\n};\n//# sourceMappingURL=engine.dynamicBuffer.js.map","import { WebGPUEngine } from \"../../webgpuEngine.js\";\nWebGPUEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha = false, format, forceBindTexture, allowGPUOptimization) {\n var _a;\n if (!texture) {\n return;\n }\n const width = canvas.width, height = canvas.height;\n let gpuTextureWrapper = texture._hardwareTexture;\n if (!((_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource)) {\n gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture, width, height);\n }\n this._textureHelper.updateTexture(canvas, texture, width, height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, premulAlpha, 0, 0, allowGPUOptimization);\n if (texture.generateMipMaps) {\n this._generateMipmaps(texture, this._uploadEncoder);\n }\n texture.isReady = true;\n};\n//# sourceMappingURL=engine.dynamicTexture.js.map","import { WebGPUEngine } from \"../../webgpuEngine.js\";\nimport { WebGPUExternalTexture } from \"../webgpuExternalTexture.js\";\nimport { Effect } from \"../../../Materials/effect.js\";\nEffect.prototype.setExternalTexture = function (name, texture) {\n this._engine.setExternalTexture(name, texture);\n};\nWebGPUEngine.prototype.createExternalTexture = function (video) {\n const texture = new WebGPUExternalTexture(video);\n return texture;\n};\nWebGPUEngine.prototype.setExternalTexture = function (name, texture) {\n if (!texture) {\n this._currentMaterialContext.setTexture(name, null);\n return;\n }\n this._setInternalTexture(name, texture);\n};\n//# sourceMappingURL=engine.externalTexture.js.map","import { ExternalTexture } from \"../../Materials/Textures/externalTexture.js\";\n/**\n * Nothing specific to WebGPU in this class, but the spec is not final yet so let's remove it later on\n * if it is not needed\n * @internal\n **/\nexport class WebGPUExternalTexture extends ExternalTexture {\n constructor(video) {\n super(video);\n }\n}\n//# sourceMappingURL=webgpuExternalTexture.js.map","import { InternalTexture, InternalTextureSource } from \"../../../Materials/Textures/internalTexture.js\";\nimport { Logger } from \"../../../Misc/logger.js\";\n\nimport { WebGPUEngine } from \"../../webgpuEngine.js\";\nWebGPUEngine.prototype.unBindMultiColorAttachmentFramebuffer = function (rtWrapper, disableGenerateMipMaps = false, onBeforeUnbind) {\n if (onBeforeUnbind) {\n onBeforeUnbind();\n }\n const attachments = rtWrapper._attachments;\n const count = attachments.length;\n if (this._currentRenderPass && this._currentRenderPass !== this._mainRenderPassWrapper.renderPass) {\n this._endRenderTargetRenderPass();\n }\n for (let i = 0; i < count; i++) {\n const texture = rtWrapper.textures[i];\n if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {\n this._generateMipmaps(texture);\n }\n }\n this._currentRenderTarget = null;\n this._mrtAttachments = [];\n this._cacheRenderPipeline.setMRT([]);\n this._cacheRenderPipeline.setMRTAttachments(this._mrtAttachments);\n this._currentRenderPass = this._mainRenderPassWrapper.renderPass;\n this._setDepthTextureFormat(this._mainRenderPassWrapper);\n this._setColorFormat(this._mainRenderPassWrapper);\n};\nWebGPUEngine.prototype.createMultipleRenderTarget = function (size, options, initializeBuffers) {\n var _a, _b;\n let generateMipMaps = false;\n let generateDepthBuffer = true;\n let generateStencilBuffer = false;\n let generateDepthTexture = false;\n let depthTextureFormat = 15;\n let textureCount = 1;\n const defaultType = 0;\n const defaultSamplingMode = 3;\n const defaultUseSRGBBuffer = false;\n const defaultFormat = 5;\n const defaultTarget = 3553;\n let types = new Array();\n let samplingModes = new Array();\n let useSRGBBuffers = new Array();\n let formats = new Array();\n let targets = new Array();\n let faceIndex = new Array();\n let layerIndex = new Array();\n let layers = new Array();\n const rtWrapper = this._createHardwareRenderTargetWrapper(true, false, size);\n if (options !== undefined) {\n generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;\n generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;\n generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;\n generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;\n textureCount = options.textureCount || 1;\n depthTextureFormat = (_a = options.depthTextureFormat) !== null && _a !== void 0 ? _a : 15;\n if (options.types) {\n types = options.types;\n }\n if (options.samplingModes) {\n samplingModes = options.samplingModes;\n }\n if (options.useSRGBBuffers) {\n useSRGBBuffers = options.useSRGBBuffers;\n }\n if (options.formats) {\n formats = options.formats;\n }\n if (options.targetTypes) {\n targets = options.targetTypes;\n }\n if (options.faceIndex) {\n faceIndex = options.faceIndex;\n }\n if (options.layerIndex) {\n layerIndex = options.layerIndex;\n }\n if (options.layerCounts) {\n layers = options.layerCounts;\n }\n }\n const width = size.width || size;\n const height = size.height || size;\n let depthStencilTexture = null;\n if (generateDepthBuffer || generateStencilBuffer || generateDepthTexture) {\n if (!generateDepthTexture) {\n // The caller doesn't want a depth texture, so we are free to use the depth texture format we want.\n // So, we will align with what the WebGL engine does\n if (generateDepthBuffer && generateStencilBuffer) {\n depthTextureFormat = 13;\n }\n else if (generateDepthBuffer) {\n depthTextureFormat = 14;\n }\n else {\n depthTextureFormat = 19;\n }\n }\n depthStencilTexture = rtWrapper.createDepthStencilTexture(0, false, generateStencilBuffer, 1, depthTextureFormat);\n }\n const textures = [];\n const attachments = [];\n const defaultAttachments = [];\n rtWrapper._generateDepthBuffer = generateDepthBuffer;\n rtWrapper._generateStencilBuffer = generateStencilBuffer;\n rtWrapper._attachments = attachments;\n rtWrapper._defaultAttachments = defaultAttachments;\n for (let i = 0; i < textureCount; i++) {\n let samplingMode = samplingModes[i] || defaultSamplingMode;\n let type = types[i] || defaultType;\n const format = formats[i] || defaultFormat;\n const useSRGBBuffer = (useSRGBBuffers[i] || defaultUseSRGBBuffer) && this._caps.supportSRGBBuffers;\n const target = targets[i] || defaultTarget;\n const layerCount = (_b = layers[i]) !== null && _b !== void 0 ? _b : 1;\n if (type === 1 && !this._caps.textureFloatLinearFiltering) {\n // if floating point linear (FLOAT) then force to NEAREST_SAMPLINGMODE\n samplingMode = 1;\n }\n else if (type === 2 && !this._caps.textureHalfFloatLinearFiltering) {\n // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE\n samplingMode = 1;\n }\n if (type === 1 && !this._caps.textureFloat) {\n type = 0;\n Logger.Warn(\"Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type\");\n }\n attachments.push(i + 1);\n defaultAttachments.push(initializeBuffers ? i + 1 : i === 0 ? 1 : 0);\n if (target === -1) {\n continue;\n }\n const texture = new InternalTexture(this, InternalTextureSource.MultiRenderTarget);\n textures[i] = texture;\n switch (target) {\n case 34067:\n texture.isCube = true;\n break;\n case 32879:\n texture.is3D = true;\n texture.baseDepth = texture.depth = layerCount;\n break;\n case 35866:\n texture.is2DArray = true;\n texture.baseDepth = texture.depth = layerCount;\n break;\n }\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = width;\n texture.height = height;\n texture.isReady = true;\n texture.samples = 1;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.type = type;\n texture._cachedWrapU = 0;\n texture._cachedWrapV = 0;\n texture._useSRGBBuffer = useSRGBBuffer;\n texture.format = format;\n this._internalTexturesCache.push(texture);\n this._textureHelper.createGPUTextureForInternalTexture(texture);\n }\n if (depthStencilTexture) {\n depthStencilTexture.incrementReferences();\n textures[textureCount] = depthStencilTexture;\n this._internalTexturesCache.push(depthStencilTexture);\n }\n rtWrapper.setTextures(textures);\n rtWrapper.setLayerAndFaceIndices(layerIndex, faceIndex);\n return rtWrapper;\n};\nWebGPUEngine.prototype.updateMultipleRenderTargetTextureSampleCount = function (rtWrapper, samples) {\n if (!rtWrapper || !rtWrapper.textures || rtWrapper.textures[0].samples === samples) {\n return samples;\n }\n const count = rtWrapper.textures.length;\n if (count === 0) {\n return 1;\n }\n samples = Math.min(samples, this.getCaps().maxMSAASamples);\n for (let i = 0; i < count; ++i) {\n const texture = rtWrapper.textures[i];\n const gpuTextureWrapper = texture._hardwareTexture;\n gpuTextureWrapper === null || gpuTextureWrapper === void 0 ? void 0 : gpuTextureWrapper.releaseMSAATexture();\n }\n // Note that rtWrapper.textures can't have null textures, lastTextureIsDepthTexture can't be true if rtWrapper._depthStencilTexture is null\n const lastTextureIsDepthTexture = rtWrapper._depthStencilTexture === rtWrapper.textures[count - 1];\n for (let i = 0; i < count; ++i) {\n const texture = rtWrapper.textures[i];\n this._textureHelper.createMSAATexture(texture, samples, false, i === count - 1 && lastTextureIsDepthTexture ? 0 : i);\n texture.samples = samples;\n }\n // Note that the last texture of textures is the depth texture if the depth texture has been generated by the MRT class and so the MSAA texture\n // will be recreated for this texture by the loop above: in that case, there's no need to create the MSAA texture for rtWrapper._depthStencilTexture\n // because rtWrapper._depthStencilTexture is the same texture than the depth texture\n if (rtWrapper._depthStencilTexture && !lastTextureIsDepthTexture) {\n this._textureHelper.createMSAATexture(rtWrapper._depthStencilTexture, samples);\n rtWrapper._depthStencilTexture.samples = samples;\n }\n return samples;\n};\nWebGPUEngine.prototype.bindAttachments = function (attachments) {\n if (attachments.length === 0 || !this._currentRenderTarget) {\n return;\n }\n this._mrtAttachments = attachments;\n if (this._currentRenderPass) {\n // the render pass has already been created, we need to call setMRTAttachments to update the state of the attachments\n this._cacheRenderPipeline.setMRTAttachments(attachments);\n }\n else {\n // the render pass is not created yet so we don't need to call setMRTAttachments: it will be called as part of the render pass creation (see WebGPUEngine._startRenderTargetRenderPass)\n }\n};\nWebGPUEngine.prototype.buildTextureLayout = function (textureStatus) {\n const result = [];\n for (let i = 0; i < textureStatus.length; i++) {\n if (textureStatus[i]) {\n result.push(i + 1);\n }\n else {\n result.push(0);\n }\n }\n return result;\n};\nWebGPUEngine.prototype.restoreSingleAttachment = function () {\n // not sure what to do, probably nothing... This function and restoreSingleAttachmentForRenderTarget are not called in Babylon.js so it's hard to know the use case\n};\nWebGPUEngine.prototype.restoreSingleAttachmentForRenderTarget = function () {\n // not sure what to do, probably nothing... This function and restoreSingleAttachment are not called in Babylon.js so it's hard to know the use case\n};\n//# sourceMappingURL=engine.multiRender.js.map","import { WebGPUEngine } from \"../../webgpuEngine.js\";\nimport { WebGPURenderItemBeginOcclusionQuery, WebGPURenderItemEndOcclusionQuery } from \"../webgpuBundleList.js\";\nWebGPUEngine.prototype.getGPUFrameTimeCounter = function () {\n return this._timestampQuery.gpuFrameTimeCounter;\n};\nWebGPUEngine.prototype.captureGPUFrameTime = function (value) {\n this._timestampQuery.enable = value && !!this._caps.timerQuery;\n};\nWebGPUEngine.prototype.createQuery = function () {\n return this._occlusionQuery.createQuery();\n};\nWebGPUEngine.prototype.deleteQuery = function (query) {\n this._occlusionQuery.deleteQuery(query);\n return this;\n};\nWebGPUEngine.prototype.isQueryResultAvailable = function (query) {\n return this._occlusionQuery.isQueryResultAvailable(query);\n};\nWebGPUEngine.prototype.getQueryResult = function (query) {\n return this._occlusionQuery.getQueryResult(query);\n};\nWebGPUEngine.prototype.beginOcclusionQuery = function (algorithmType, query) {\n var _a;\n if (this.compatibilityMode) {\n if (this._occlusionQuery.canBeginQuery) {\n (_a = this._currentRenderPass) === null || _a === void 0 ? void 0 : _a.beginOcclusionQuery(query);\n return true;\n }\n }\n else {\n const renderPassIndex = this._getCurrentRenderPassIndex();\n const bundleList = renderPassIndex === 0 ? this._bundleList : this._bundleListRenderTarget;\n bundleList.addItem(new WebGPURenderItemBeginOcclusionQuery(query));\n return true;\n }\n return false;\n};\nWebGPUEngine.prototype.endOcclusionQuery = function () {\n var _a;\n if (this.compatibilityMode) {\n (_a = this._currentRenderPass) === null || _a === void 0 ? void 0 : _a.endOcclusionQuery();\n }\n else {\n const renderPassIndex = this._getCurrentRenderPassIndex();\n const bundleList = renderPassIndex === 0 ? this._bundleList : this._bundleListRenderTarget;\n bundleList.addItem(new WebGPURenderItemEndOcclusionQuery());\n }\n return this;\n};\n//# sourceMappingURL=engine.query.js.map","import { InternalTexture, InternalTextureSource } from \"../../../Materials/Textures/internalTexture.js\";\n\nimport { WebGPUEngine } from \"../../webgpuEngine.js\";\nimport { Logger } from \"../../../Misc/logger.js\";\nWebGPUEngine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression = null, type = 0, creationFlags = 0, useSRGBBuffer = false) {\n const texture = new InternalTexture(this, InternalTextureSource.Raw);\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.width = width;\n texture.height = height;\n texture.format = format;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.invertY = invertY;\n texture._compression = compression;\n texture.type = type;\n texture._useSRGBBuffer = useSRGBBuffer;\n if (!this._doNotHandleContextLost) {\n texture._bufferView = data;\n }\n this._textureHelper.createGPUTextureForInternalTexture(texture, width, height, undefined, creationFlags);\n this.updateRawTexture(texture, data, format, invertY, compression, type, useSRGBBuffer);\n this._internalTexturesCache.push(texture);\n return texture;\n};\nWebGPUEngine.prototype.updateRawTexture = function (texture, bufferView, format, invertY, compression = null, type = 0, useSRGBBuffer = false) {\n if (!texture) {\n return;\n }\n if (!this._doNotHandleContextLost) {\n texture._bufferView = bufferView;\n texture.invertY = invertY;\n texture._compression = compression;\n texture._useSRGBBuffer = useSRGBBuffer;\n }\n if (bufferView) {\n const gpuTextureWrapper = texture._hardwareTexture;\n const needConversion = format === 4;\n if (needConversion) {\n bufferView = _convertRGBtoRGBATextureData(bufferView, texture.width, texture.height, type);\n }\n const data = new Uint8Array(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength);\n this._textureHelper.updateTexture(data, texture, texture.width, texture.height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, false, 0, 0);\n if (texture.generateMipMaps) {\n this._generateMipmaps(texture, this._uploadEncoder);\n }\n }\n texture.isReady = true;\n};\nWebGPUEngine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression = null) {\n const texture = new InternalTexture(this, InternalTextureSource.CubeRaw);\n if (type === 1 && !this._caps.textureFloatLinearFiltering) {\n generateMipMaps = false;\n samplingMode = 1;\n Logger.Warn(\"Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.\");\n }\n else if (type === 2 && !this._caps.textureHalfFloatLinearFiltering) {\n generateMipMaps = false;\n samplingMode = 1;\n Logger.Warn(\"Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.\");\n }\n else if (type === 1 && !this._caps.textureFloatRender) {\n generateMipMaps = false;\n Logger.Warn(\"Render to float textures is not supported. Mipmap generation forced to false.\");\n }\n else if (type === 2 && !this._caps.colorBufferFloat) {\n generateMipMaps = false;\n Logger.Warn(\"Render to half float textures is not supported. Mipmap generation forced to false.\");\n }\n texture.isCube = true;\n texture.format = format === 4 ? 5 : format;\n texture.type = type;\n texture.generateMipMaps = generateMipMaps;\n texture.width = size;\n texture.height = size;\n texture.samplingMode = samplingMode;\n if (!this._doNotHandleContextLost) {\n texture._bufferViewArray = data;\n }\n texture.invertY = invertY;\n texture._compression = compression;\n texture._cachedWrapU = 0;\n texture._cachedWrapV = 0;\n this._textureHelper.createGPUTextureForInternalTexture(texture);\n if (data) {\n this.updateRawCubeTexture(texture, data, format, type, invertY, compression);\n }\n texture.isReady = true;\n return texture;\n};\nWebGPUEngine.prototype.updateRawCubeTexture = function (texture, bufferView, format, type, invertY, compression = null) {\n texture._bufferViewArray = bufferView;\n texture.invertY = invertY;\n texture._compression = compression;\n const gpuTextureWrapper = texture._hardwareTexture;\n const needConversion = format === 4;\n const data = [];\n for (let i = 0; i < bufferView.length; ++i) {\n let faceData = bufferView[i];\n if (needConversion) {\n faceData = _convertRGBtoRGBATextureData(bufferView[i], texture.width, texture.height, type);\n }\n data.push(new Uint8Array(faceData.buffer, faceData.byteOffset, faceData.byteLength));\n }\n this._textureHelper.updateCubeTextures(data, gpuTextureWrapper.underlyingResource, texture.width, texture.height, gpuTextureWrapper.format, invertY, false, 0, 0);\n if (texture.generateMipMaps) {\n this._generateMipmaps(texture, this._uploadEncoder);\n }\n texture.isReady = true;\n};\nWebGPUEngine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad = null, onError = null, samplingMode = 3, invertY = false) {\n const texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode, null);\n scene === null || scene === void 0 ? void 0 : scene.addPendingData(texture);\n texture.url = url;\n this._internalTexturesCache.push(texture);\n const onerror = (request, exception) => {\n scene === null || scene === void 0 ? void 0 : scene.removePendingData(texture);\n if (onError && request) {\n onError(request.status + \" \" + request.statusText, exception);\n }\n };\n const internalCallback = (data) => {\n const width = texture.width;\n const faceDataArrays = callback(data);\n if (!faceDataArrays) {\n return;\n }\n const faces = [0, 2, 4, 1, 3, 5];\n if (mipmapGenerator) {\n const needConversion = format === 4;\n const mipData = mipmapGenerator(faceDataArrays);\n const gpuTextureWrapper = texture._hardwareTexture;\n const faces = [0, 1, 2, 3, 4, 5];\n for (let level = 0; level < mipData.length; level++) {\n const mipSize = width >> level;\n const allFaces = [];\n for (let faceIndex = 0; faceIndex < 6; faceIndex++) {\n let mipFaceData = mipData[level][faces[faceIndex]];\n if (needConversion) {\n mipFaceData = _convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);\n }\n allFaces.push(new Uint8Array(mipFaceData.buffer, mipFaceData.byteOffset, mipFaceData.byteLength));\n }\n this._textureHelper.updateCubeTextures(allFaces, gpuTextureWrapper.underlyingResource, mipSize, mipSize, gpuTextureWrapper.format, invertY, false, 0, 0);\n }\n }\n else {\n const allFaces = [];\n for (let faceIndex = 0; faceIndex < 6; faceIndex++) {\n allFaces.push(faceDataArrays[faces[faceIndex]]);\n }\n this.updateRawCubeTexture(texture, allFaces, format, type, invertY);\n }\n texture.isReady = true;\n scene === null || scene === void 0 ? void 0 : scene.removePendingData(texture);\n if (onLoad) {\n onLoad();\n }\n };\n this._loadFile(url, (data) => {\n internalCallback(data);\n }, undefined, scene === null || scene === void 0 ? void 0 : scene.offlineProvider, true, onerror);\n return texture;\n};\nWebGPUEngine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression = null, textureType = 0, creationFlags = 0) {\n const source = InternalTextureSource.Raw3D;\n const texture = new InternalTexture(this, source);\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.baseDepth = depth;\n texture.width = width;\n texture.height = height;\n texture.depth = depth;\n texture.format = format;\n texture.type = textureType;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.is3D = true;\n if (!this._doNotHandleContextLost) {\n texture._bufferView = data;\n }\n this._textureHelper.createGPUTextureForInternalTexture(texture, width, height, undefined, creationFlags);\n this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);\n this._internalTexturesCache.push(texture);\n return texture;\n};\nWebGPUEngine.prototype.updateRawTexture3D = function (texture, bufferView, format, invertY, compression = null, textureType = 0) {\n if (!this._doNotHandleContextLost) {\n texture._bufferView = bufferView;\n texture.format = format;\n texture.invertY = invertY;\n texture._compression = compression;\n }\n if (bufferView) {\n const gpuTextureWrapper = texture._hardwareTexture;\n const needConversion = format === 4;\n if (needConversion) {\n bufferView = _convertRGBtoRGBATextureData(bufferView, texture.width, texture.height, textureType);\n }\n const data = new Uint8Array(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength);\n this._textureHelper.updateTexture(data, texture, texture.width, texture.height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, false, 0, 0);\n if (texture.generateMipMaps) {\n this._generateMipmaps(texture, this._uploadEncoder);\n }\n }\n texture.isReady = true;\n};\nWebGPUEngine.prototype.createRawTexture2DArray = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression = null, textureType = 0, creationFlags = 0) {\n const source = InternalTextureSource.Raw2DArray;\n const texture = new InternalTexture(this, source);\n texture.baseWidth = width;\n texture.baseHeight = height;\n texture.baseDepth = depth;\n texture.width = width;\n texture.height = height;\n texture.depth = depth;\n texture.format = format;\n texture.type = textureType;\n texture.generateMipMaps = generateMipMaps;\n texture.samplingMode = samplingMode;\n texture.is2DArray = true;\n if (!this._doNotHandleContextLost) {\n texture._bufferView = data;\n }\n this._textureHelper.createGPUTextureForInternalTexture(texture, width, height, depth, creationFlags);\n this.updateRawTexture2DArray(texture, data, format, invertY, compression, textureType);\n this._internalTexturesCache.push(texture);\n return texture;\n};\nWebGPUEngine.prototype.updateRawTexture2DArray = function (texture, bufferView, format, invertY, compression = null, textureType = 0) {\n if (!this._doNotHandleContextLost) {\n texture._bufferView = bufferView;\n texture.format = format;\n texture.invertY = invertY;\n texture._compression = compression;\n }\n if (bufferView) {\n const gpuTextureWrapper = texture._hardwareTexture;\n const needConversion = format === 4;\n if (needConversion) {\n bufferView = _convertRGBtoRGBATextureData(bufferView, texture.width, texture.height, textureType);\n }\n const data = new Uint8Array(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength);\n this._textureHelper.updateTexture(data, texture, texture.width, texture.height, texture.depth, gpuTextureWrapper.format, 0, 0, invertY, false, 0, 0);\n if (texture.generateMipMaps) {\n this._generateMipmaps(texture, this._uploadEncoder);\n }\n }\n texture.isReady = true;\n};\n/**\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nfunction _convertRGBtoRGBATextureData(rgbData, width, height, textureType) {\n // Create new RGBA data container.\n let rgbaData;\n let val1 = 1;\n if (textureType === 1) {\n rgbaData = new Float32Array(width * height * 4);\n }\n else if (textureType === 2) {\n rgbaData = new Uint16Array(width * height * 4);\n val1 = 15360; // 15360 is the encoding of 1 in half float\n }\n else if (textureType === 7) {\n rgbaData = new Uint32Array(width * height * 4);\n }\n else {\n rgbaData = new Uint8Array(width * height * 4);\n }\n // Convert each pixel.\n for (let x = 0; x < width; x++) {\n for (let y = 0; y < height; y++) {\n const index = (y * width + x) * 3;\n const newIndex = (y * width + x) * 4;\n // Map Old Value to new value.\n rgbaData[newIndex + 0] = rgbData[index + 0];\n rgbaData[newIndex + 1] = rgbData[index + 1];\n rgbaData[newIndex + 2] = rgbData[index + 2];\n // Add fully opaque alpha channel.\n rgbaData[newIndex + 3] = val1;\n }\n }\n return rgbaData;\n}\n//# sourceMappingURL=engine.rawTexture.js.map","import { RenderTargetWrapper } from \"../renderTargetWrapper.js\";\n/** @internal */\nexport class WebGPURenderTargetWrapper extends RenderTargetWrapper {\n}\n//# sourceMappingURL=webgpuRenderTargetWrapper.js.map","import { WebGPUEngine } from \"../../webgpuEngine.js\";\nWebGPUEngine.prototype._readTexturePixels = function (texture, width, height, faceIndex = -1, level = 0, buffer = null, flushRenderer = true, noDataConversion = false, x = 0, y = 0) {\n const gpuTextureWrapper = texture._hardwareTexture;\n if (flushRenderer) {\n this.flushFramebuffer();\n }\n return this._textureHelper.readPixels(gpuTextureWrapper.underlyingResource, x, y, width, height, gpuTextureWrapper.format, faceIndex, level, buffer, noDataConversion);\n};\nWebGPUEngine.prototype._readTexturePixelsSync = function () {\n throw \"_readTexturePixelsSync is unsupported in WebGPU!\";\n};\n//# sourceMappingURL=engine.readTexture.js.map","import { InternalTexture, InternalTextureSource } from \"../../../Materials/Textures/internalTexture.js\";\n\nimport { WebGPUEngine } from \"../../webgpuEngine.js\";\nimport { WebGPURenderTargetWrapper } from \"../webgpuRenderTargetWrapper.js\";\nWebGPUEngine.prototype._createHardwareRenderTargetWrapper = function (isMulti, isCube, size) {\n const rtWrapper = new WebGPURenderTargetWrapper(isMulti, isCube, size, this);\n this._renderTargetWrapperCache.push(rtWrapper);\n return rtWrapper;\n};\nWebGPUEngine.prototype.createRenderTargetTexture = function (size, options) {\n var _a, _b;\n const rtWrapper = this._createHardwareRenderTargetWrapper(false, false, size);\n const fullOptions = {};\n if (options !== undefined && typeof options === \"object\") {\n fullOptions.generateMipMaps = options.generateMipMaps;\n fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;\n fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;\n fullOptions.samplingMode = options.samplingMode === undefined ? 3 : options.samplingMode;\n fullOptions.creationFlags = (_a = options.creationFlags) !== null && _a !== void 0 ? _a : 0;\n fullOptions.noColorAttachment = !!options.noColorAttachment;\n fullOptions.samples = options.samples;\n fullOptions.label = options.label;\n }\n else {\n fullOptions.generateMipMaps = options;\n fullOptions.generateDepthBuffer = true;\n fullOptions.generateStencilBuffer = false;\n fullOptions.samplingMode = 3;\n fullOptions.creationFlags = 0;\n fullOptions.noColorAttachment = false;\n }\n const texture = fullOptions.noColorAttachment ? null : this._createInternalTexture(size, options, true, InternalTextureSource.RenderTarget);\n rtWrapper._samples = (_b = fullOptions.samples) !== null && _b !== void 0 ? _b : 1;\n rtWrapper._generateDepthBuffer = fullOptions.generateDepthBuffer;\n rtWrapper._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;\n rtWrapper.setTextures(texture);\n if (rtWrapper._generateDepthBuffer || rtWrapper._generateStencilBuffer) {\n rtWrapper.createDepthStencilTexture(0, this._caps.textureFloatLinearFiltering &&\n (fullOptions.samplingMode === undefined ||\n fullOptions.samplingMode === 2 ||\n fullOptions.samplingMode === 2 ||\n fullOptions.samplingMode === 3 ||\n fullOptions.samplingMode === 3 ||\n fullOptions.samplingMode === 5 ||\n fullOptions.samplingMode === 6 ||\n fullOptions.samplingMode === 7 ||\n fullOptions.samplingMode === 11), rtWrapper._generateStencilBuffer, rtWrapper.samples, fullOptions.generateStencilBuffer ? 13 : 14, fullOptions.label ? fullOptions.label + \"-DepthStencil\" : undefined);\n }\n if (texture) {\n if (options !== undefined && typeof options === \"object\" && options.createMipMaps && !fullOptions.generateMipMaps) {\n texture.generateMipMaps = true;\n }\n this._textureHelper.createGPUTextureForInternalTexture(texture, undefined, undefined, undefined, fullOptions.creationFlags);\n if (options !== undefined && typeof options === \"object\" && options.createMipMaps && !fullOptions.generateMipMaps) {\n texture.generateMipMaps = false;\n }\n }\n return rtWrapper;\n};\nWebGPUEngine.prototype._createDepthStencilTexture = function (size, options) {\n const internalTexture = new InternalTexture(this, InternalTextureSource.DepthStencil);\n internalTexture.label = options.label;\n const internalOptions = Object.assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false, samples: 1, depthTextureFormat: options.generateStencil ? 13 : 14 }, options);\n internalTexture.format = internalOptions.depthTextureFormat;\n this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction, internalOptions.samples);\n this._textureHelper.createGPUTextureForInternalTexture(internalTexture);\n this._internalTexturesCache.push(internalTexture);\n return internalTexture;\n};\nWebGPUEngine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction, samples = 1) {\n const width = size.width || size;\n const height = size.height || size;\n const layers = size.layers || 0;\n internalTexture.baseWidth = width;\n internalTexture.baseHeight = height;\n internalTexture.width = width;\n internalTexture.height = height;\n internalTexture.is2DArray = layers > 0;\n internalTexture.depth = layers;\n internalTexture.isReady = true;\n internalTexture.samples = samples;\n internalTexture.generateMipMaps = false;\n internalTexture.samplingMode = bilinearFiltering ? 2 : 1;\n internalTexture.type = 1;\n internalTexture._comparisonFunction = comparisonFunction;\n internalTexture._cachedWrapU = 0;\n internalTexture._cachedWrapV = 0;\n};\nWebGPUEngine.prototype.updateRenderTargetTextureSampleCount = function (rtWrapper, samples) {\n if (!rtWrapper || !rtWrapper.texture || rtWrapper.samples === samples) {\n return samples;\n }\n samples = Math.min(samples, this.getCaps().maxMSAASamples);\n this._textureHelper.createMSAATexture(rtWrapper.texture, samples);\n if (rtWrapper._depthStencilTexture) {\n this._textureHelper.createMSAATexture(rtWrapper._depthStencilTexture, samples);\n rtWrapper._depthStencilTexture.samples = samples;\n }\n rtWrapper._samples = samples;\n rtWrapper.texture.samples = samples;\n return samples;\n};\n//# sourceMappingURL=engine.renderTarget.js.map","import { InternalTexture, InternalTextureSource } from \"../../../Materials/Textures/internalTexture.js\";\n\nimport { WebGPUEngine } from \"../../webgpuEngine.js\";\nWebGPUEngine.prototype.createRenderTargetCubeTexture = function (size, options) {\n const rtWrapper = this._createHardwareRenderTargetWrapper(false, true, size);\n const fullOptions = Object.assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: 0, samplingMode: 3, format: 5, samples: 1 }, options);\n fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;\n rtWrapper._generateDepthBuffer = fullOptions.generateDepthBuffer;\n rtWrapper._generateStencilBuffer = fullOptions.generateStencilBuffer;\n const texture = new InternalTexture(this, InternalTextureSource.RenderTarget);\n texture.width = size;\n texture.height = size;\n texture.depth = 0;\n texture.isReady = true;\n texture.isCube = true;\n texture.samples = fullOptions.samples;\n texture.generateMipMaps = fullOptions.generateMipMaps;\n texture.samplingMode = fullOptions.samplingMode;\n texture.type = fullOptions.type;\n texture.format = fullOptions.format;\n this._internalTexturesCache.push(texture);\n rtWrapper.setTextures(texture);\n if (rtWrapper._generateDepthBuffer || rtWrapper._generateStencilBuffer) {\n rtWrapper.createDepthStencilTexture(0, fullOptions.samplingMode === undefined ||\n fullOptions.samplingMode === 2 ||\n fullOptions.samplingMode === 2 ||\n fullOptions.samplingMode === 3 ||\n fullOptions.samplingMode === 3 ||\n fullOptions.samplingMode === 5 ||\n fullOptions.samplingMode === 6 ||\n fullOptions.samplingMode === 7 ||\n fullOptions.samplingMode === 11, rtWrapper._generateStencilBuffer, rtWrapper.samples);\n }\n if (options && options.createMipMaps && !fullOptions.generateMipMaps) {\n texture.generateMipMaps = true;\n }\n this._textureHelper.createGPUTextureForInternalTexture(texture);\n if (options && options.createMipMaps && !fullOptions.generateMipMaps) {\n texture.generateMipMaps = false;\n }\n return rtWrapper;\n};\n//# sourceMappingURL=engine.renderTargetCube.js.map","import { WebGPUEngine } from \"../../webgpuEngine.js\";\nimport { Effect } from \"../../../Materials/effect.js\";\nEffect.prototype.setTextureSampler = function (name, sampler) {\n this._engine.setTextureSampler(name, sampler);\n};\nWebGPUEngine.prototype.setTextureSampler = function (name, sampler) {\n var _a;\n (_a = this._currentMaterialContext) === null || _a === void 0 ? void 0 : _a.setSampler(name, sampler);\n};\n//# sourceMappingURL=engine.textureSampler.js.map","\nimport { WebGPUEngine } from \"../../webgpuEngine.js\";\nimport * as WebGPUConstants from \"../webgpuConstants.js\";\nimport { Effect } from \"../../../Materials/effect.js\";\nEffect.prototype.setStorageBuffer = function (name, buffer) {\n this._engine.setStorageBuffer(name, buffer);\n};\nWebGPUEngine.prototype.createStorageBuffer = function (data, creationFlags) {\n return this._createBuffer(data, creationFlags | 32);\n};\nWebGPUEngine.prototype.updateStorageBuffer = function (buffer, data, byteOffset, byteLength) {\n const dataBuffer = buffer;\n if (byteOffset === undefined) {\n byteOffset = 0;\n }\n let view;\n if (byteLength === undefined) {\n if (data instanceof Array) {\n view = new Float32Array(data);\n }\n else if (data instanceof ArrayBuffer) {\n view = new Uint8Array(data);\n }\n else {\n view = data;\n }\n byteLength = view.byteLength;\n }\n else {\n if (data instanceof Array) {\n view = new Float32Array(data);\n }\n else if (data instanceof ArrayBuffer) {\n view = new Uint8Array(data);\n }\n else {\n view = data;\n }\n }\n this._bufferManager.setSubData(dataBuffer, byteOffset, view, 0, byteLength);\n};\nWebGPUEngine.prototype.readFromStorageBuffer = function (storageBuffer, offset, size, buffer) {\n size = size || storageBuffer.capacity;\n const gpuBuffer = this._bufferManager.createRawBuffer(size, WebGPUConstants.BufferUsage.MapRead | WebGPUConstants.BufferUsage.CopyDst);\n this._renderTargetEncoder.copyBufferToBuffer(storageBuffer.underlyingResource, offset !== null && offset !== void 0 ? offset : 0, gpuBuffer, 0, size);\n return new Promise((resolve, reject) => {\n // we are using onEndFrameObservable because we need to map the gpuBuffer AFTER the command buffers\n // have been submitted, else we get the error: \"Buffer used in a submit while mapped\"\n this.onEndFrameObservable.addOnce(() => {\n gpuBuffer.mapAsync(WebGPUConstants.MapMode.Read, 0, size).then(() => {\n const copyArrayBuffer = gpuBuffer.getMappedRange(0, size);\n let data = buffer;\n if (data === undefined) {\n data = new Uint8Array(size);\n data.set(new Uint8Array(copyArrayBuffer));\n }\n else {\n const ctor = data.constructor; // we want to create result data with the same type as buffer (Uint8Array, Float32Array, ...)\n data = new ctor(data.buffer);\n data.set(new ctor(copyArrayBuffer));\n }\n gpuBuffer.unmap();\n this._bufferManager.releaseBuffer(gpuBuffer);\n resolve(data);\n }, (reason) => reject(reason));\n });\n });\n};\nWebGPUEngine.prototype.setStorageBuffer = function (name, buffer) {\n var _a, _b;\n (_a = this._currentDrawContext) === null || _a === void 0 ? void 0 : _a.setBuffer(name, (_b = buffer === null || buffer === void 0 ? void 0 : buffer.getBuffer()) !== null && _b !== void 0 ? _b : null);\n};\n//# sourceMappingURL=engine.storageBuffer.js.map","import { WebGPUEngine } from \"../../webgpuEngine.js\";\nimport * as WebGPUConstants from \"../webgpuConstants.js\";\nWebGPUEngine.prototype.createUniformBuffer = function (elements) {\n let view;\n if (elements instanceof Array) {\n view = new Float32Array(elements);\n }\n else {\n view = elements;\n }\n const dataBuffer = this._bufferManager.createBuffer(view, WebGPUConstants.BufferUsage.Uniform | WebGPUConstants.BufferUsage.CopyDst);\n return dataBuffer;\n};\nWebGPUEngine.prototype.createDynamicUniformBuffer = function (elements) {\n return this.createUniformBuffer(elements);\n};\nWebGPUEngine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {\n if (offset === undefined) {\n offset = 0;\n }\n const dataBuffer = uniformBuffer;\n let view;\n if (count === undefined) {\n if (elements instanceof Float32Array) {\n view = elements;\n }\n else {\n view = new Float32Array(elements);\n }\n count = view.byteLength;\n }\n else {\n if (elements instanceof Float32Array) {\n view = elements;\n }\n else {\n view = new Float32Array(elements);\n }\n }\n this._bufferManager.setSubData(dataBuffer, offset, view, 0, count);\n};\nWebGPUEngine.prototype.bindUniformBufferBase = function (buffer, location, name) {\n this._currentDrawContext.setBuffer(name, buffer);\n};\nWebGPUEngine.prototype.bindUniformBlock = function () { };\n//# sourceMappingURL=engine.uniformBuffer.js.map","import { WebGPUEngine } from \"../../webgpuEngine.js\";\nfunction IsExternalTexture(texture) {\n return texture && texture.underlyingResource !== undefined ? true : false;\n}\nWebGPUEngine.prototype.updateVideoTexture = function (texture, video, invertY) {\n var _a;\n if (!texture || texture._isDisabled) {\n return;\n }\n if (this._videoTextureSupported === undefined) {\n this._videoTextureSupported = true;\n }\n let gpuTextureWrapper = texture._hardwareTexture;\n if (!((_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource)) {\n gpuTextureWrapper = this._textureHelper.createGPUTextureForInternalTexture(texture);\n }\n if (IsExternalTexture(video)) {\n this._textureHelper.copyVideoToTexture(video, texture, gpuTextureWrapper.format, !invertY);\n if (texture.generateMipMaps) {\n this._generateMipmaps(texture, this._uploadEncoder);\n }\n texture.isReady = true;\n }\n else if (video) {\n this.createImageBitmap(video)\n .then((bitmap) => {\n this._textureHelper.updateTexture(bitmap, texture, texture.width, texture.height, texture.depth, gpuTextureWrapper.format, 0, 0, !invertY, false, 0, 0);\n if (texture.generateMipMaps) {\n this._generateMipmaps(texture, this._uploadEncoder);\n }\n texture.isReady = true;\n })\n .catch(() => {\n // Sometimes createImageBitmap(video) fails with \"Failed to execute 'createImageBitmap' on 'Window': The provided element's player has no current data.\"\n // Just keep going on\n texture.isReady = true;\n });\n }\n};\n//# sourceMappingURL=engine.videoTexture.js.map","import \"./engine.alpha.js\";\nimport \"./engine.computeShader.js\";\nimport \"./engine.cubeTexture.js\";\nimport \"./engine.debugging.js\";\nimport \"./engine.dynamicBuffer.js\";\nimport \"./engine.dynamicTexture.js\";\nimport \"./engine.externalTexture.js\";\nimport \"./engine.multiRender.js\";\nimport \"./engine.query.js\";\nimport \"./engine.rawTexture.js\";\nimport \"./engine.readTexture.js\";\nimport \"./engine.renderTarget.js\";\nimport \"./engine.renderTargetCube.js\";\nimport \"./engine.textureSampler.js\";\nimport \"./engine.storageBuffer.js\";\nimport \"./engine.uniformBuffer.js\";\nimport \"./engine.videoTexture.js\";\n//# sourceMappingURL=index.js.map","export {};\n//# sourceMappingURL=IPipelineContext.js.map","export {};\n//# sourceMappingURL=ICanvas.js.map","export {};\n//# sourceMappingURL=engineFeatures.js.map","import { Engine } from \"./engine.js\";\nimport { NullEngine } from \"./nullEngine.js\";\nimport { WebGPUEngine } from \"./webgpuEngine.js\";\n/**\n * Helper class to create the best engine depending on the current hardware\n */\nexport class EngineFactory {\n /**\n * Creates an engine based on the capabilities of the underlying hardware\n * @param canvas Defines the canvas to use to display the result\n * @param options Defines the options passed to the engine to create the context dependencies\n * @returns a promise that resolves with the created engine\n */\n static CreateAsync(canvas, options) {\n return WebGPUEngine.IsSupportedAsync.then((supported) => {\n if (supported) {\n return WebGPUEngine.CreateAsync(canvas, options);\n }\n else if (Engine.IsSupported) {\n return new Promise((resolve) => {\n resolve(new Engine(canvas, undefined, options));\n });\n }\n return new Promise((resolve) => {\n resolve(new NullEngine(options));\n });\n });\n }\n}\n//# sourceMappingURL=engineFactory.js.map","export {};\n//# sourceMappingURL=IMaterialContext.js.map","export {};\n//# sourceMappingURL=IDrawContext.js.map","export {};\n//# sourceMappingURL=iShaderProcessor.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./constants.js\";\nexport * from \"./engineCapabilities.js\";\nexport * from \"./instancingAttributeInfo.js\";\nexport * from \"./thinEngine.js\";\nexport * from \"./engine.js\";\nexport * from \"./engineStore.js\";\nexport * from \"./nullEngine.js\";\nexport * from \"./Extensions/index.js\";\nexport * from \"./Native/index.js\";\nexport * from \"./WebGPU/Extensions/index.js\";\nexport * from \"./IPipelineContext.js\";\nexport * from \"./ICanvas.js\";\nexport * from \"./WebGL/webGLPipelineContext.js\";\nexport * from \"./WebGL/webGLHardwareTexture.js\";\nexport * from \"./WebGPU/webgpuConstants.js\";\nexport * from \"./webgpuEngine.js\";\nexport * from \"./WebGPU/webgpuCacheRenderPipeline.js\";\nexport * from \"./WebGPU/webgpuCacheRenderPipelineTree.js\";\nexport * from \"./WebGPU/webgpuCacheBindGroups.js\";\nexport * from \"./WebGPU/webgpuCacheSampler.js\";\nexport * from \"./WebGPU/webgpuDrawContext.js\";\nexport * from \"./WebGPU/webgpuTintWASM.js\";\nexport * from \"./WebGL/webGL2ShaderProcessors.js\";\nexport * from \"./nativeEngine.js\";\nexport * from \"./Processors/shaderCodeInliner.js\";\nexport * from \"./performanceConfigurator.js\";\nexport * from \"./engineFeatures.js\";\nexport * from \"./engineFactory.js\";\nexport * from \"./IMaterialContext.js\";\nexport * from \"./IDrawContext.js\";\nexport * from \"./shaderStore.js\";\nexport * from \"./renderTargetWrapper.js\";\nexport * from \"./Processors/iShaderProcessor.js\";\n//# sourceMappingURL=index.js.map","/**\n * Gather the list of clipboard event types as constants.\n */\nexport class ClipboardEventTypes {\n}\n/**\n * The clipboard event is fired when a copy command is active (pressed).\n */\nClipboardEventTypes.COPY = 0x01; //\n/**\n * The clipboard event is fired when a cut command is active (pressed).\n */\nClipboardEventTypes.CUT = 0x02;\n/**\n * The clipboard event is fired when a paste command is active (pressed).\n */\nClipboardEventTypes.PASTE = 0x03;\n/**\n * This class is used to store clipboard related info for the onClipboardObservable event.\n */\nexport class ClipboardInfo {\n /**\n *Creates an instance of ClipboardInfo.\n * @param type Defines the type of event (BABYLON.ClipboardEventTypes)\n * @param event Defines the related dom event\n */\n constructor(\n /**\n * Defines the type of event (BABYLON.ClipboardEventTypes)\n */\n type, \n /**\n * Defines the related dom event\n */\n event) {\n this.type = type;\n this.event = event;\n }\n /**\n * Get the clipboard event's type from the keycode.\n * @param keyCode Defines the keyCode for the current keyboard event.\n * @returns {number}\n */\n static GetTypeFromCharacter(keyCode) {\n const charCode = keyCode;\n //TODO: add codes for extended ASCII\n switch (charCode) {\n case 67:\n return ClipboardEventTypes.COPY;\n case 86:\n return ClipboardEventTypes.PASTE;\n case 88:\n return ClipboardEventTypes.CUT;\n default:\n return -1;\n }\n }\n}\n//# sourceMappingURL=clipboardEvents.js.map","export * from \"./keyboardEvents.js\";\nexport * from \"./pointerEvents.js\";\nexport * from \"./clipboardEvents.js\";\nexport * from \"./deviceInputEvents.js\";\n//# sourceMappingURL=index.js.map","import { Logger } from \"../../Misc/logger.js\";\nimport { SceneLoader } from \"../../Loading/sceneLoader.js\";\nimport { WebVRController } from \"./webVRController.js\";\nimport { PoseEnabledControllerType, PoseEnabledControllerHelper } from \"./poseEnabledController.js\";\n/**\n * Google Daydream controller\n */\nexport class DaydreamController extends WebVRController {\n /**\n * Creates a new DaydreamController from a gamepad\n * @param vrGamepad the gamepad that the controller should be created from\n */\n constructor(vrGamepad) {\n super(vrGamepad);\n this.controllerType = PoseEnabledControllerType.DAYDREAM;\n }\n /**\n * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.\n * @param scene scene in which to add meshes\n * @param meshLoaded optional callback function that will be called if the mesh loads successfully.\n */\n initControllerMesh(scene, meshLoaded) {\n SceneLoader.ImportMesh(\"\", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, (newMeshes) => {\n this._defaultModel = newMeshes[1];\n this.attachToMesh(this._defaultModel);\n if (meshLoaded) {\n meshLoaded(this._defaultModel);\n }\n });\n }\n /**\n * Called once for each button that changed state since the last frame\n * @param buttonIdx Which button index changed\n * @param state New state of the button\n */\n _handleButtonChange(buttonIdx, state) {\n // Daydream controller only has 1 GamepadButton (on the trackpad).\n if (buttonIdx === 0) {\n const observable = this.onTriggerStateChangedObservable;\n if (observable) {\n observable.notifyObservers(state);\n }\n }\n else {\n // If the app or home buttons are ever made available\n Logger.Warn(`Unrecognized Daydream button index: ${buttonIdx}`);\n }\n }\n}\n/**\n * Base Url for the controller model.\n */\nDaydreamController.MODEL_BASE_URL = \"https://controllers.babylonjs.com/generic/\";\n/**\n * File name for the controller model.\n */\nDaydreamController.MODEL_FILENAME = \"generic.babylon\";\n/**\n * Gamepad Id prefix used to identify Daydream Controller.\n */\nDaydreamController.GAMEPAD_ID_PREFIX = \"Daydream\"; // id is 'Daydream Controller'\nPoseEnabledControllerHelper._ControllerFactories.push({\n canCreate: (gamepadInfo) => {\n return gamepadInfo.id.indexOf(DaydreamController.GAMEPAD_ID_PREFIX) === 0;\n },\n create: (gamepadInfo) => {\n return new DaydreamController(gamepadInfo);\n },\n});\n//# sourceMappingURL=daydreamController.js.map","import { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Mesh } from \"../../Meshes/mesh.js\";\nimport { SceneLoader } from \"../../Loading/sceneLoader.js\";\nimport { WebVRController } from \"./webVRController.js\";\nimport { PoseEnabledControllerType, PoseEnabledControllerHelper } from \"./poseEnabledController.js\";\n/**\n * Gear VR Controller\n */\nexport class GearVRController extends WebVRController {\n /**\n * Creates a new GearVRController from a gamepad\n * @param vrGamepad the gamepad that the controller should be created from\n */\n constructor(vrGamepad) {\n super(vrGamepad);\n this._buttonIndexToObservableNameMap = [\n \"onPadStateChangedObservable\",\n \"onTriggerStateChangedObservable\", // Trigger\n ];\n this.controllerType = PoseEnabledControllerType.GEAR_VR;\n // Initial starting position defaults to where hand would be (incase of only 3dof controller)\n this._calculatedPosition = new Vector3(this.hand == \"left\" ? -0.15 : 0.15, -0.5, 0.25);\n this._disableTrackPosition(this._calculatedPosition);\n }\n /**\n * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.\n * @param scene scene in which to add meshes\n * @param meshLoaded optional callback function that will be called if the mesh loads successfully.\n */\n initControllerMesh(scene, meshLoaded) {\n SceneLoader.ImportMesh(\"\", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, (newMeshes) => {\n // Offset the controller so it will rotate around the users wrist\n const mesh = new Mesh(\"\", scene);\n newMeshes[1].parent = mesh;\n newMeshes[1].position.z = -0.15;\n this._defaultModel = mesh;\n this.attachToMesh(this._defaultModel);\n if (meshLoaded) {\n meshLoaded(this._defaultModel);\n }\n });\n }\n /**\n * Called once for each button that changed state since the last frame\n * @param buttonIdx Which button index changed\n * @param state New state of the button\n */\n _handleButtonChange(buttonIdx, state) {\n if (buttonIdx < this._buttonIndexToObservableNameMap.length) {\n const observableName = this._buttonIndexToObservableNameMap[buttonIdx];\n // Only emit events for buttons that we know how to map from index to observable\n const observable = this[observableName];\n if (observable) {\n observable.notifyObservers(state);\n }\n }\n }\n}\n/**\n * Base Url for the controller model.\n */\nGearVRController.MODEL_BASE_URL = \"https://controllers.babylonjs.com/generic/\";\n/**\n * File name for the controller model.\n */\nGearVRController.MODEL_FILENAME = \"generic.babylon\";\n/**\n * Gamepad Id prefix used to identify this controller.\n */\nGearVRController.GAMEPAD_ID_PREFIX = \"Gear VR\"; // id is 'Gear VR Controller'\nPoseEnabledControllerHelper._ControllerFactories.push({\n canCreate: (gamepadInfo) => {\n return gamepadInfo.id.indexOf(GearVRController.GAMEPAD_ID_PREFIX) === 0 || gamepadInfo.id.indexOf(\"Oculus Go\") !== -1 || gamepadInfo.id.indexOf(\"Vive Focus\") !== -1;\n },\n create: (gamepadInfo) => {\n return new GearVRController(gamepadInfo);\n },\n});\n//# sourceMappingURL=gearVRController.js.map","import { SceneLoader } from \"../../Loading/sceneLoader.js\";\nimport { WebVRController } from \"./webVRController.js\";\nimport { PoseEnabledControllerHelper } from \"./poseEnabledController.js\";\n/**\n * Generic Controller\n */\nexport class GenericController extends WebVRController {\n /**\n * Creates a new GenericController from a gamepad\n * @param vrGamepad the gamepad that the controller should be created from\n */\n constructor(vrGamepad) {\n super(vrGamepad);\n }\n /**\n * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.\n * @param scene scene in which to add meshes\n * @param meshLoaded optional callback function that will be called if the mesh loads successfully.\n */\n initControllerMesh(scene, meshLoaded) {\n SceneLoader.ImportMesh(\"\", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, (newMeshes) => {\n this._defaultModel = newMeshes[1];\n this.attachToMesh(this._defaultModel);\n if (meshLoaded) {\n meshLoaded(this._defaultModel);\n }\n });\n }\n /**\n * Called once for each button that changed state since the last frame\n * @param buttonIdx Which button index changed\n * @param state New state of the button\n */\n _handleButtonChange(buttonIdx, state) {\n console.log(\"Button id: \" + buttonIdx + \"state: \");\n console.dir(state);\n }\n}\n/**\n * Base Url for the controller model.\n */\nGenericController.MODEL_BASE_URL = \"https://controllers.babylonjs.com/generic/\";\n/**\n * File name for the controller model.\n */\nGenericController.MODEL_FILENAME = \"generic.babylon\";\nPoseEnabledControllerHelper._DefaultControllerFactory = (gamepadInfo) => new GenericController(gamepadInfo);\n//# sourceMappingURL=genericController.js.map","import { Observable } from \"../../Misc/observable.js\";\nimport { SceneLoader } from \"../../Loading/sceneLoader.js\";\nimport { WebVRController } from \"./webVRController.js\";\nimport { PoseEnabledControllerType, PoseEnabledControllerHelper } from \"./poseEnabledController.js\";\nimport { EngineStore } from \"../../Engines/engineStore.js\";\n/**\n * Oculus Touch Controller\n */\nexport class OculusTouchController extends WebVRController {\n /**\n * Creates a new OculusTouchController from a gamepad\n * @param vrGamepad the gamepad that the controller should be created from\n */\n constructor(vrGamepad) {\n super(vrGamepad);\n /**\n * Fired when the secondary trigger on this controller is modified\n */\n this.onSecondaryTriggerStateChangedObservable = new Observable();\n /**\n * Fired when the thumb rest on this controller is modified\n */\n this.onThumbRestChangedObservable = new Observable();\n this.controllerType = PoseEnabledControllerType.OCULUS;\n }\n /**\n * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.\n * @param scene scene in which to add meshes\n * @param meshLoaded optional callback function that will be called if the mesh loads successfully.\n */\n initControllerMesh(scene, meshLoaded) {\n let meshName;\n // Hand\n if (this.hand === \"left\") {\n meshName = OculusTouchController.MODEL_LEFT_FILENAME;\n }\n else {\n // Right is the default if no hand is specified\n meshName = OculusTouchController.MODEL_RIGHT_FILENAME;\n }\n SceneLoader.ImportMesh(\"\", OculusTouchController._IsQuest ? OculusTouchController.QUEST_MODEL_BASE_URL : OculusTouchController.MODEL_BASE_URL, meshName, scene, (newMeshes) => {\n /*\n Parent Mesh name: oculus_touch_left\n - body\n - trigger\n - thumbstick\n - grip\n - button_y\n - button_x\n - button_enter\n */\n this._defaultModel = OculusTouchController._IsQuest ? newMeshes[0] : newMeshes[1];\n this.attachToMesh(this._defaultModel);\n if (meshLoaded) {\n meshLoaded(this._defaultModel);\n }\n });\n }\n /**\n * Fired when the A button on this controller is modified\n */\n get onAButtonStateChangedObservable() {\n if (this.hand === \"right\") {\n return this.onMainButtonStateChangedObservable;\n }\n else {\n throw new Error(\"No A button on left hand\");\n }\n }\n /**\n * Fired when the B button on this controller is modified\n */\n get onBButtonStateChangedObservable() {\n if (this.hand === \"right\") {\n return this.onSecondaryButtonStateChangedObservable;\n }\n else {\n throw new Error(\"No B button on left hand\");\n }\n }\n /**\n * Fired when the X button on this controller is modified\n */\n get onXButtonStateChangedObservable() {\n if (this.hand === \"left\") {\n return this.onMainButtonStateChangedObservable;\n }\n else {\n throw new Error(\"No X button on right hand\");\n }\n }\n /**\n * Fired when the Y button on this controller is modified\n */\n get onYButtonStateChangedObservable() {\n if (this.hand === \"left\") {\n return this.onSecondaryButtonStateChangedObservable;\n }\n else {\n throw new Error(\"No Y button on right hand\");\n }\n }\n /**\n * Called once for each button that changed state since the last frame\n * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick\n * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)\n * 2) secondary trigger (same)\n * 3) A (right) X (left), touch, pressed = value\n * 4) B / Y\n * 5) thumb rest\n * @param buttonIdx Which button index changed\n * @param state New state of the button\n */\n _handleButtonChange(buttonIdx, state) {\n const notifyObject = state; //{ state: state, changes: changes };\n const triggerDirection = this.hand === \"right\" ? -1 : 1;\n switch (buttonIdx) {\n case 0:\n this.onPadStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 1: // index trigger\n if (!OculusTouchController._IsQuest && this._defaultModel) {\n this._defaultModel.getChildren()[3].rotation.x = -notifyObject.value * 0.2;\n this._defaultModel.getChildren()[3].position.y = -notifyObject.value * 0.005;\n this._defaultModel.getChildren()[3].position.z = -notifyObject.value * 0.005;\n }\n this.onTriggerStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 2: // secondary trigger\n if (!OculusTouchController._IsQuest && this._defaultModel) {\n this._defaultModel.getChildren()[4].position.x = triggerDirection * notifyObject.value * 0.0035;\n }\n this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 3:\n if (!OculusTouchController._IsQuest && this._defaultModel) {\n if (notifyObject.pressed) {\n this._defaultModel.getChildren()[1].position.y = -0.001;\n }\n else {\n this._defaultModel.getChildren()[1].position.y = 0;\n }\n }\n this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 4:\n if (!OculusTouchController._IsQuest && this._defaultModel) {\n if (notifyObject.pressed) {\n this._defaultModel.getChildren()[2].position.y = -0.001;\n }\n else {\n this._defaultModel.getChildren()[2].position.y = 0;\n }\n }\n this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 5:\n this.onThumbRestChangedObservable.notifyObservers(notifyObject);\n return;\n }\n }\n}\n/**\n * Base Url for the controller model.\n */\nOculusTouchController.MODEL_BASE_URL = \"https://controllers.babylonjs.com/oculus/\";\n/**\n * File name for the left controller model.\n */\nOculusTouchController.MODEL_LEFT_FILENAME = \"left.babylon\";\n/**\n * File name for the right controller model.\n */\nOculusTouchController.MODEL_RIGHT_FILENAME = \"right.babylon\";\n/**\n * Base Url for the Quest controller model.\n */\nOculusTouchController.QUEST_MODEL_BASE_URL = \"https://controllers.babylonjs.com/oculusQuest/\";\n/**\n * @internal\n * If the controllers are running on a device that needs the updated Quest controller models\n */\nOculusTouchController._IsQuest = false;\nPoseEnabledControllerHelper._ControllerFactories.push({\n canCreate: (gamepadInfo) => {\n // If the headset reports being an Oculus Quest, use the Quest controller models\n if (EngineStore.LastCreatedEngine && EngineStore.LastCreatedEngine._vrDisplay && EngineStore.LastCreatedEngine._vrDisplay.displayName === \"Oculus Quest\") {\n OculusTouchController._IsQuest = true;\n }\n return gamepadInfo.id.indexOf(\"Oculus Touch\") !== -1;\n },\n create: (gamepadInfo) => {\n return new OculusTouchController(gamepadInfo);\n },\n});\n//# sourceMappingURL=oculusTouchController.js.map","import { SceneLoader } from \"../../Loading/sceneLoader.js\";\nimport { WebVRController } from \"./webVRController.js\";\nimport { PoseEnabledControllerType, PoseEnabledControllerHelper } from \"./poseEnabledController.js\";\n/**\n * Vive Controller\n */\nexport class ViveController extends WebVRController {\n /**\n * Creates a new ViveController from a gamepad\n * @param vrGamepad the gamepad that the controller should be created from\n */\n constructor(vrGamepad) {\n super(vrGamepad);\n this.controllerType = PoseEnabledControllerType.VIVE;\n this._invertLeftStickY = true;\n }\n /**\n * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.\n * @param scene scene in which to add meshes\n * @param meshLoaded optional callback function that will be called if the mesh loads successfully.\n */\n initControllerMesh(scene, meshLoaded) {\n SceneLoader.ImportMesh(\"\", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, (newMeshes) => {\n /*\n Parent Mesh name: ViveWand\n - body\n - r_gripper\n - l_gripper\n - menu_button\n - system_button\n - trackpad\n - trigger\n - LED\n */\n this._defaultModel = newMeshes[1];\n this.attachToMesh(this._defaultModel);\n if (meshLoaded) {\n meshLoaded(this._defaultModel);\n }\n });\n }\n /**\n * Fired when the left button on this controller is modified\n */\n get onLeftButtonStateChangedObservable() {\n return this.onMainButtonStateChangedObservable;\n }\n /**\n * Fired when the right button on this controller is modified\n */\n get onRightButtonStateChangedObservable() {\n return this.onMainButtonStateChangedObservable;\n }\n /**\n * Fired when the menu button on this controller is modified\n */\n get onMenuButtonStateChangedObservable() {\n return this.onSecondaryButtonStateChangedObservable;\n }\n /**\n * Called once for each button that changed state since the last frame\n * Vive mapping:\n * 0: touchpad\n * 1: trigger\n * 2: left AND right buttons\n * 3: menu button\n * @param buttonIdx Which button index changed\n * @param state New state of the button\n */\n _handleButtonChange(buttonIdx, state) {\n const notifyObject = state; //{ state: state, changes: changes };\n switch (buttonIdx) {\n case 0:\n this.onPadStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 1: // index trigger\n if (this._defaultModel) {\n this._defaultModel.getChildren()[6].rotation.x = -notifyObject.value * 0.15;\n }\n this.onTriggerStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 2: // left AND right button\n this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);\n return;\n case 3:\n if (this._defaultModel) {\n if (notifyObject.pressed) {\n this._defaultModel.getChildren()[2].position.y = -0.001;\n }\n else {\n this._defaultModel.getChildren()[2].position.y = 0;\n }\n }\n this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);\n return;\n }\n }\n}\n/**\n * Base Url for the controller model.\n */\nViveController.MODEL_BASE_URL = \"https://controllers.babylonjs.com/vive/\";\n/**\n * File name for the controller model.\n */\nViveController.MODEL_FILENAME = \"wand.babylon\";\nPoseEnabledControllerHelper._ControllerFactories.push({\n canCreate: (gamepadInfo) => {\n return gamepadInfo.id.toLowerCase().indexOf(\"openvr\") !== -1;\n },\n create: (gamepadInfo) => {\n return new ViveController(gamepadInfo);\n },\n});\n//# sourceMappingURL=viveController.js.map","import { Logger } from \"../../Misc/logger.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { Quaternion, Vector3 } from \"../../Maths/math.vector.js\";\nimport { Mesh } from \"../../Meshes/mesh.js\";\nimport { Ray } from \"../../Culling/ray.js\";\nimport { SceneLoader } from \"../../Loading/sceneLoader.js\";\nimport { WebVRController } from \"./webVRController.js\";\nimport { GenericController } from \"./genericController.js\";\nimport { PoseEnabledController, PoseEnabledControllerType, PoseEnabledControllerHelper } from \"./poseEnabledController.js\";\n/**\n * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh\n */\nclass LoadedMeshInfo {\n constructor() {\n /**\n * Map of the button meshes contained in the controller\n */\n this.buttonMeshes = {};\n /**\n * Map of the axis meshes contained in the controller\n */\n this.axisMeshes = {};\n }\n}\n/**\n * Defines the WindowsMotionController object that the state of the windows motion controller\n */\nexport class WindowsMotionController extends WebVRController {\n /**\n * Creates a new WindowsMotionController from a gamepad\n * @param vrGamepad the gamepad that the controller should be created from\n */\n constructor(vrGamepad) {\n super(vrGamepad);\n this._mapping = {\n // Semantic button names\n buttons: [\"thumbstick\", \"trigger\", \"grip\", \"menu\", \"trackpad\"],\n // trigger, grip, trackpad, thumbstick, menu\n // A mapping of the button name to glTF model node name\n // that should be transformed by button value.\n buttonMeshNames: {\n trigger: \"SELECT\",\n menu: \"MENU\",\n grip: \"GRASP\",\n thumbstick: \"THUMBSTICK_PRESS\",\n trackpad: \"TOUCHPAD_PRESS\",\n },\n // This mapping is used to translate from the Motion Controller to Babylon semantics\n buttonObservableNames: {\n trigger: \"onTriggerStateChangedObservable\",\n menu: \"onSecondaryButtonStateChangedObservable\",\n grip: \"onMainButtonStateChangedObservable\",\n thumbstick: \"onPadStateChangedObservable\",\n trackpad: \"onTrackpadChangedObservable\",\n },\n // A mapping of the axis name to glTF model node name\n // that should be transformed by axis value.\n // This array mirrors the browserGamepad.axes array, such that\n // the mesh corresponding to axis 0 is in this array index 0.\n axisMeshNames: [\"THUMBSTICK_X\", \"THUMBSTICK_Y\", \"TOUCHPAD_TOUCH_X\", \"TOUCHPAD_TOUCH_Y\"],\n // upside down in webxr\n pointingPoseMeshName: PoseEnabledController.POINTING_POSE,\n };\n /**\n * Fired when the trackpad on this controller is clicked\n */\n this.onTrackpadChangedObservable = new Observable();\n /**\n * Fired when the trackpad on this controller is modified\n */\n this.onTrackpadValuesChangedObservable = new Observable();\n /**\n * The current x and y values of this controller's trackpad\n */\n this.trackpad = { x: 0, y: 0 };\n this.controllerType = PoseEnabledControllerType.WINDOWS;\n this._loadedMeshInfo = null;\n }\n /**\n * Fired when the trigger on this controller is modified\n */\n get onTriggerButtonStateChangedObservable() {\n return this.onTriggerStateChangedObservable;\n }\n /**\n * Fired when the menu button on this controller is modified\n */\n get onMenuButtonStateChangedObservable() {\n return this.onSecondaryButtonStateChangedObservable;\n }\n /**\n * Fired when the grip button on this controller is modified\n */\n get onGripButtonStateChangedObservable() {\n return this.onMainButtonStateChangedObservable;\n }\n /**\n * Fired when the thumbstick button on this controller is modified\n */\n get onThumbstickButtonStateChangedObservable() {\n return this.onPadStateChangedObservable;\n }\n /**\n * Fired when the touchpad button on this controller is modified\n */\n get onTouchpadButtonStateChangedObservable() {\n return this.onTrackpadChangedObservable;\n }\n /**\n * Fired when the touchpad values on this controller are modified\n */\n get onTouchpadValuesChangedObservable() {\n return this.onTrackpadValuesChangedObservable;\n }\n _updateTrackpad() {\n if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {\n this.trackpad.x = this.browserGamepad[\"axes\"][this._mapping.axisMeshNames.indexOf(\"TOUCHPAD_TOUCH_X\")];\n this.trackpad.y = this.browserGamepad[\"axes\"][this._mapping.axisMeshNames.indexOf(\"TOUCHPAD_TOUCH_Y\")];\n this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);\n }\n }\n /**\n * Called once per frame by the engine.\n */\n update() {\n super.update();\n if (this.browserGamepad.axes) {\n this._updateTrackpad();\n // Only need to animate axes if there is a loaded mesh\n if (this._loadedMeshInfo) {\n for (let axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {\n this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);\n }\n }\n }\n }\n /**\n * Called once for each button that changed state since the last frame\n * @param buttonIdx Which button index changed\n * @param state New state of the button\n */\n _handleButtonChange(buttonIdx, state) {\n const buttonName = this._mapping.buttons[buttonIdx];\n if (!buttonName) {\n return;\n }\n // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames\n this._updateTrackpad();\n // Only emit events for buttons that we know how to map from index to name\n const observable = this[this._mapping.buttonObservableNames[buttonName]];\n if (observable) {\n observable.notifyObservers(state);\n }\n this._lerpButtonTransform(buttonName, state.value);\n }\n /**\n * Moves the buttons on the controller mesh based on their current state\n * @param buttonName the name of the button to move\n * @param buttonValue the value of the button which determines the buttons new position\n */\n _lerpButtonTransform(buttonName, buttonValue) {\n // If there is no loaded mesh, there is nothing to transform.\n if (!this._loadedMeshInfo) {\n return;\n }\n const meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];\n if (!meshInfo || !meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {\n return;\n }\n Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);\n Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);\n }\n /**\n * Moves the axis on the controller mesh based on its current state\n * @param axis the index of the axis\n * @param axisValue the value of the axis which determines the meshes new position\n * @internal\n */\n _lerpAxisTransform(axis, axisValue) {\n if (!this._loadedMeshInfo) {\n return;\n }\n const meshInfo = this._loadedMeshInfo.axisMeshes[axis];\n if (!meshInfo) {\n return;\n }\n if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {\n return;\n }\n // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)\n const lerpValue = axisValue * 0.5 + 0.5;\n Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);\n Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);\n }\n /**\n * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.\n * @param scene scene in which to add meshes\n * @param meshLoaded optional callback function that will be called if the mesh loads successfully.\n * @param forceDefault\n */\n initControllerMesh(scene, meshLoaded, forceDefault = false) {\n let path;\n let filename;\n // Checking if GLB loader is present\n if (SceneLoader.IsPluginForExtensionAvailable(\".glb\")) {\n // Determine the device specific folder based on the ID suffix\n let device = \"default\";\n if (this.id && !forceDefault) {\n const match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);\n device = (match && match[0]) || device;\n }\n // Hand\n if (this.hand === \"left\") {\n filename = WindowsMotionController.MODEL_LEFT_FILENAME;\n }\n else {\n // Right is the default if no hand is specified\n filename = WindowsMotionController.MODEL_RIGHT_FILENAME;\n }\n path = WindowsMotionController.MODEL_BASE_URL + device + \"/\";\n }\n else {\n Logger.Warn(\"You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models\");\n path = GenericController.MODEL_BASE_URL;\n filename = GenericController.MODEL_FILENAME;\n }\n SceneLoader.ImportMesh(\"\", path, filename, scene, (meshes) => {\n // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.\n this._loadedMeshInfo = this._processModel(scene, meshes);\n if (!this._loadedMeshInfo) {\n return;\n }\n this._defaultModel = this._loadedMeshInfo.rootNode;\n this.attachToMesh(this._defaultModel);\n if (meshLoaded) {\n meshLoaded(this._defaultModel);\n }\n }, null, (scene, message) => {\n Logger.Log(message);\n Logger.Warn(\"Failed to retrieve controller model from the remote server: \" + path + filename);\n if (!forceDefault) {\n this.initControllerMesh(scene, meshLoaded, true);\n }\n });\n }\n /**\n * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that\n * can be transformed by button presses and axes values, based on this._mapping.\n *\n * @param scene scene in which the meshes exist\n * @param meshes list of meshes that make up the controller model to process\n * @returns structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.\n */\n _processModel(scene, meshes) {\n let loadedMeshInfo = null;\n // Create a new mesh to contain the glTF hierarchy\n const parentMesh = new Mesh(this.id + \" \" + this.hand, scene);\n // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'\n let childMesh = null;\n for (let i = 0; i < meshes.length; i++) {\n const mesh = meshes[i];\n if (!mesh.parent) {\n // Exclude controller meshes from picking results\n mesh.isPickable = false;\n // Handle root node, attach to the new parentMesh\n childMesh = mesh;\n break;\n }\n }\n if (childMesh) {\n childMesh.setParent(parentMesh);\n // Create our mesh info. Note that this method will always return non-null.\n loadedMeshInfo = this._createMeshInfo(parentMesh);\n }\n else {\n Logger.Warn(\"Could not find root node in model file.\");\n }\n return loadedMeshInfo;\n }\n _createMeshInfo(rootNode) {\n const loadedMeshInfo = new LoadedMeshInfo();\n let i;\n loadedMeshInfo.rootNode = rootNode;\n // Reset the caches\n loadedMeshInfo.buttonMeshes = {};\n loadedMeshInfo.axisMeshes = {};\n // Button Meshes\n for (i = 0; i < this._mapping.buttons.length; i++) {\n const buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];\n if (!buttonMeshName) {\n Logger.Log(\"Skipping unknown button at index: \" + i + \" with mapped name: \" + this._mapping.buttons[i]);\n continue;\n }\n const buttonMesh = getChildByName(rootNode, buttonMeshName);\n if (!buttonMesh) {\n Logger.Warn(\"Missing button mesh with name: \" + buttonMeshName);\n continue;\n }\n const buttonMeshInfo = {\n index: i,\n value: getImmediateChildByName(buttonMesh, \"VALUE\"),\n pressed: getImmediateChildByName(buttonMesh, \"PRESSED\"),\n unpressed: getImmediateChildByName(buttonMesh, \"UNPRESSED\"),\n };\n if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {\n loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;\n }\n else {\n // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.\n Logger.Warn(\"Missing button submesh under mesh with name: \" +\n buttonMeshName +\n \"(VALUE: \" +\n !!buttonMeshInfo.value +\n \", PRESSED: \" +\n !!buttonMeshInfo.pressed +\n \", UNPRESSED:\" +\n !!buttonMeshInfo.unpressed +\n \")\");\n }\n }\n // Axis Meshes\n for (i = 0; i < this._mapping.axisMeshNames.length; i++) {\n const axisMeshName = this._mapping.axisMeshNames[i];\n if (!axisMeshName) {\n Logger.Log(\"Skipping unknown axis at index: \" + i);\n continue;\n }\n const axisMesh = getChildByName(rootNode, axisMeshName);\n if (!axisMesh) {\n Logger.Warn(\"Missing axis mesh with name: \" + axisMeshName);\n continue;\n }\n const axisMeshInfo = {\n index: i,\n value: getImmediateChildByName(axisMesh, \"VALUE\"),\n min: getImmediateChildByName(axisMesh, \"MIN\"),\n max: getImmediateChildByName(axisMesh, \"MAX\"),\n };\n if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {\n loadedMeshInfo.axisMeshes[i] = axisMeshInfo;\n }\n else {\n // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.\n Logger.Warn(\"Missing axis submesh under mesh with name: \" +\n axisMeshName +\n \"(VALUE: \" +\n !!axisMeshInfo.value +\n \", MIN: \" +\n !!axisMeshInfo.min +\n \", MAX:\" +\n !!axisMeshInfo.max +\n \")\");\n }\n }\n // Pointing Ray\n loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);\n if (!loadedMeshInfo.pointingPoseNode) {\n Logger.Warn(\"Missing pointing pose mesh with name: \" + this._mapping.pointingPoseMeshName);\n }\n else {\n this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;\n }\n return loadedMeshInfo;\n // Look through all children recursively. This will return null if no mesh exists with the given name.\n function getChildByName(node, name) {\n return node.getChildren((n) => n.name === name, false)[0];\n }\n // Look through only immediate children. This will return null if no mesh exists with the given name.\n function getImmediateChildByName(node, name) {\n return node.getChildren((n) => n.name == name, true)[0];\n }\n }\n /**\n * Gets the ray of the controller in the direction the controller is pointing\n * @param length the length the resulting ray should be\n * @returns a ray in the direction the controller is pointing\n */\n getForwardRay(length = 100) {\n if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {\n return super.getForwardRay(length);\n }\n const m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();\n const origin = m.getTranslation();\n const forward = new Vector3(0, 0, -1);\n const forwardWorld = Vector3.TransformNormal(forward, m);\n const direction = Vector3.Normalize(forwardWorld);\n return new Ray(origin, direction, length);\n }\n /**\n * Disposes of the controller\n */\n dispose() {\n super.dispose();\n this.onTrackpadChangedObservable.clear();\n this.onTrackpadValuesChangedObservable.clear();\n }\n}\n/**\n * The base url used to load the left and right controller models\n */\nWindowsMotionController.MODEL_BASE_URL = \"https://controllers.babylonjs.com/microsoft/\";\n/**\n * The name of the left controller model file\n */\nWindowsMotionController.MODEL_LEFT_FILENAME = \"left.glb\";\n/**\n * The name of the right controller model file\n */\nWindowsMotionController.MODEL_RIGHT_FILENAME = \"right.glb\";\n/**\n * The controller name prefix for this controller type\n */\nWindowsMotionController.GAMEPAD_ID_PREFIX = \"Spatial Controller (Spatial Interaction Source) \";\n/**\n * The controller id pattern for this controller type\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nWindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;\n/**\n * This class represents a new windows motion controller in XR.\n */\nexport class XRWindowsMotionController extends WindowsMotionController {\n /**\n * Construct a new XR-Based windows motion controller\n *\n * @param gamepadInfo the gamepad object from the browser\n */\n constructor(gamepadInfo) {\n super(gamepadInfo);\n /**\n * Changing the original WIndowsMotionController mapping to fir the new mapping\n */\n this._mapping = {\n // Semantic button names\n buttons: [\"trigger\", \"grip\", \"trackpad\", \"thumbstick\", \"menu\"],\n // trigger, grip, trackpad, thumbstick, menu\n // A mapping of the button name to glTF model node name\n // that should be transformed by button value.\n buttonMeshNames: {\n trigger: \"SELECT\",\n menu: \"MENU\",\n grip: \"GRASP\",\n thumbstick: \"THUMBSTICK_PRESS\",\n trackpad: \"TOUCHPAD_PRESS\",\n },\n // This mapping is used to translate from the Motion Controller to Babylon semantics\n buttonObservableNames: {\n trigger: \"onTriggerStateChangedObservable\",\n menu: \"onSecondaryButtonStateChangedObservable\",\n grip: \"onMainButtonStateChangedObservable\",\n thumbstick: \"onThumbstickStateChangedObservable\",\n trackpad: \"onTrackpadChangedObservable\",\n },\n // A mapping of the axis name to glTF model node name\n // that should be transformed by axis value.\n // This array mirrors the browserGamepad.axes array, such that\n // the mesh corresponding to axis 0 is in this array index 0.\n axisMeshNames: [\"TOUCHPAD_TOUCH_X\", \"TOUCHPAD_TOUCH_Y\", \"THUMBSTICK_X\", \"THUMBSTICK_Y\"],\n // upside down in webxr\n pointingPoseMeshName: PoseEnabledController.POINTING_POSE,\n };\n /**\n * holds the thumbstick values (X,Y)\n */\n this.thumbstickValues = { x: 0, y: 0 };\n /**\n * Fired when the thumbstick on this controller is clicked\n */\n this.onThumbstickStateChangedObservable = new Observable();\n /**\n * Fired when the thumbstick on this controller is modified\n */\n this.onThumbstickValuesChangedObservable = new Observable();\n /**\n * Fired when the touchpad button on this controller is modified\n */\n this.onTrackpadChangedObservable = this.onPadStateChangedObservable;\n /**\n * Fired when the touchpad values on this controller are modified\n */\n this.onTrackpadValuesChangedObservable = this.onPadValuesChangedObservable;\n }\n /**\n * Fired when the thumbstick button on this controller is modified\n * here to prevent breaking changes\n */\n get onThumbstickButtonStateChangedObservable() {\n return this.onThumbstickStateChangedObservable;\n }\n /**\n * updating the thumbstick(!) and not the trackpad.\n * This is named this way due to the difference between WebVR and XR and to avoid\n * changing the parent class.\n */\n _updateTrackpad() {\n if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.thumbstickValues.x || this.browserGamepad.axes[3] != this.thumbstickValues.y)) {\n this.trackpad.x = this.browserGamepad[\"axes\"][2];\n this.trackpad.y = this.browserGamepad[\"axes\"][3];\n this.onThumbstickValuesChangedObservable.notifyObservers(this.trackpad);\n }\n }\n /**\n * Disposes the class with joy\n */\n dispose() {\n super.dispose();\n this.onThumbstickStateChangedObservable.clear();\n this.onThumbstickValuesChangedObservable.clear();\n }\n}\nPoseEnabledControllerHelper._ControllerFactories.push({\n canCreate: (gamepadInfo) => {\n return gamepadInfo.id.indexOf(WindowsMotionController.GAMEPAD_ID_PREFIX) === 0;\n },\n create: (gamepadInfo) => {\n return new WindowsMotionController(gamepadInfo);\n },\n});\n//# sourceMappingURL=windowsMotionController.js.map","export * from \"./daydreamController.js\";\nexport * from \"./gearVRController.js\";\nexport * from \"./genericController.js\";\nexport * from \"./oculusTouchController.js\";\nexport * from \"./poseEnabledController.js\";\nexport * from \"./viveController.js\";\nexport * from \"./webVRController.js\";\nexport * from \"./windowsMotionController.js\";\n//# sourceMappingURL=index.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./Controllers/index.js\";\nexport * from \"./gamepad.js\";\nexport * from \"./gamepadManager.js\";\nexport * from \"./gamepadSceneComponent.js\";\nexport * from \"./xboxGamepad.js\";\nexport * from \"./dualShockGamepad.js\";\n//# sourceMappingURL=index.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { Vector3, Matrix, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { CreateBox } from \"../Meshes/Builders/boxBuilder.js\";\nimport { CreateCylinder } from \"../Meshes/Builders/cylinderBuilder.js\";\nimport { StandardMaterial } from \"../Materials/standardMaterial.js\";\nimport { PointerDragBehavior } from \"../Behaviors/Meshes/pointerDragBehavior.js\";\nimport { Gizmo } from \"./gizmo.js\";\nimport { UtilityLayerRenderer } from \"../Rendering/utilityLayerRenderer.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\n/**\n * Single axis scale gizmo\n */\nexport class AxisScaleGizmo extends Gizmo {\n /** Default material used to render when gizmo is not disabled or hovered */\n get coloredMaterial() {\n return this._coloredMaterial;\n }\n /** Material used to render when gizmo is hovered with mouse*/\n get hoverMaterial() {\n return this._hoverMaterial;\n }\n /** Material used to render when gizmo is disabled. typically grey.*/\n get disableMaterial() {\n return this._disableMaterial;\n }\n /**\n * Creates an AxisScaleGizmo\n * @param dragAxis The axis which the gizmo will be able to scale on\n * @param color The color of the gizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n * @param parent\n * @param thickness display gizmo axis thickness\n */\n constructor(dragAxis, color = Color3.Gray(), gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer, parent = null, thickness = 1) {\n var _a, _b, _c, _d, _e, _f, _g;\n super(gizmoLayer);\n this._pointerObserver = null;\n /**\n * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)\n */\n this.snapDistance = 0;\n /**\n * Event that fires each time the gizmo snaps to a new location.\n * * snapDistance is the the change in distance\n */\n this.onSnapObservable = new Observable();\n /**\n * If the scaling operation should be done on all axis (default: false)\n */\n this.uniformScaling = false;\n /**\n * Custom sensitivity value for the drag strength\n */\n this.sensitivity = 1;\n /**\n * The magnitude of the drag strength (scaling factor)\n */\n this.dragScale = 1;\n this._isEnabled = true;\n this._parent = null;\n this._dragging = false;\n this._tmpVector = new Vector3(0, 0, 0);\n this._parent = parent;\n // Create Material\n this._coloredMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._coloredMaterial.diffuseColor = color;\n this._coloredMaterial.specularColor = color.subtract(new Color3(0.1, 0.1, 0.1));\n this._hoverMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._hoverMaterial.diffuseColor = Color3.Yellow();\n this._disableMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._disableMaterial.diffuseColor = Color3.Gray();\n this._disableMaterial.alpha = 0.4;\n // Build mesh + Collider\n this._gizmoMesh = new Mesh(\"axis\", gizmoLayer.utilityLayerScene);\n const { arrowMesh, arrowTail } = this._createGizmoMesh(this._gizmoMesh, thickness);\n const collider = this._createGizmoMesh(this._gizmoMesh, thickness + 4, true);\n this._gizmoMesh.lookAt(this._rootMesh.position.add(dragAxis));\n this._rootMesh.addChild(this._gizmoMesh, Gizmo.PreserveScaling);\n this._gizmoMesh.scaling.scaleInPlace(1 / 3);\n // Closure of initial prop values for resetting\n const nodePosition = arrowMesh.position.clone();\n const linePosition = arrowTail.position.clone();\n const lineScale = arrowTail.scaling.clone();\n const increaseGizmoMesh = (dragDistance) => {\n const dragStrength = dragDistance * (3 / this._rootMesh.scaling.length()) * 6;\n arrowMesh.position.z += dragStrength / 3.5;\n arrowTail.scaling.y += dragStrength;\n this.dragScale = arrowTail.scaling.y;\n arrowTail.position.z = arrowMesh.position.z / 2;\n };\n const resetGizmoMesh = () => {\n arrowMesh.position.set(nodePosition.x, nodePosition.y, nodePosition.z);\n arrowTail.position.set(linePosition.x, linePosition.y, linePosition.z);\n arrowTail.scaling.set(lineScale.x, lineScale.y, lineScale.z);\n this.dragScale = arrowTail.scaling.y;\n this._dragging = false;\n };\n // Add drag behavior to handle events when the gizmo is dragged\n this.dragBehavior = new PointerDragBehavior({ dragAxis: dragAxis });\n this.dragBehavior.moveAttached = false;\n this.dragBehavior.updateDragPlane = false;\n this._rootMesh.addBehavior(this.dragBehavior);\n let currentSnapDragDistance = 0;\n const tmpSnapEvent = { snapDistance: 0 };\n this.dragBehavior.onDragObservable.add((event) => {\n if (this.attachedNode) {\n this._handlePivot();\n // Drag strength is modified by the scale of the gizmo (eg. for small objects like boombox the strength will be increased to match the behavior of larger objects)\n const dragStrength = this.sensitivity * event.dragDistance * ((this.scaleRatio * 3) / this._rootMesh.scaling.length());\n const tmpVector = this._tmpVector;\n // Snapping logic\n let snapped = false;\n let dragSteps = 0;\n if (this.uniformScaling) {\n tmpVector.setAll(0.57735); // 1 / sqrt(3)\n }\n else {\n tmpVector.copyFrom(dragAxis);\n }\n if (this.snapDistance == 0) {\n tmpVector.scaleToRef(dragStrength, tmpVector);\n }\n else {\n currentSnapDragDistance += dragStrength;\n if (Math.abs(currentSnapDragDistance) > this.snapDistance) {\n dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / this.snapDistance);\n if (currentSnapDragDistance < 0) {\n dragSteps *= -1;\n }\n currentSnapDragDistance = currentSnapDragDistance % this.snapDistance;\n tmpVector.scaleToRef(this.snapDistance * dragSteps, tmpVector);\n snapped = true;\n }\n else {\n tmpVector.scaleInPlace(0);\n }\n }\n Matrix.ScalingToRef(1 + tmpVector.x, 1 + tmpVector.y, 1 + tmpVector.z, TmpVectors.Matrix[2]);\n TmpVectors.Matrix[2].multiplyToRef(this.attachedNode.getWorldMatrix(), TmpVectors.Matrix[1]);\n const transformNode = this.attachedNode._isMesh ? this.attachedNode : undefined;\n TmpVectors.Matrix[1].decompose(TmpVectors.Vector3[1], undefined, undefined, Gizmo.PreserveScaling ? transformNode : undefined);\n const maxScale = 100000;\n if (Math.abs(TmpVectors.Vector3[1].x) < maxScale && Math.abs(TmpVectors.Vector3[1].y) < maxScale && Math.abs(TmpVectors.Vector3[1].z) < maxScale) {\n this.attachedNode.getWorldMatrix().copyFrom(TmpVectors.Matrix[1]);\n }\n if (snapped) {\n tmpSnapEvent.snapDistance = this.snapDistance * dragSteps;\n this.onSnapObservable.notifyObservers(tmpSnapEvent);\n }\n this._matrixChanged();\n }\n });\n // On Drag Listener: to move gizmo mesh with user action\n this.dragBehavior.onDragStartObservable.add(() => {\n this._dragging = true;\n });\n this.dragBehavior.onDragObservable.add((e) => increaseGizmoMesh(e.dragDistance));\n this.dragBehavior.onDragEndObservable.add(resetGizmoMesh);\n // Listeners for Universal Scalar\n (_c = (_b = (_a = parent === null || parent === void 0 ? void 0 : parent.uniformScaleGizmo) === null || _a === void 0 ? void 0 : _a.dragBehavior) === null || _b === void 0 ? void 0 : _b.onDragObservable) === null || _c === void 0 ? void 0 : _c.add((e) => increaseGizmoMesh(e.delta.y));\n (_f = (_e = (_d = parent === null || parent === void 0 ? void 0 : parent.uniformScaleGizmo) === null || _d === void 0 ? void 0 : _d.dragBehavior) === null || _e === void 0 ? void 0 : _e.onDragEndObservable) === null || _f === void 0 ? void 0 : _f.add(resetGizmoMesh);\n const cache = {\n gizmoMeshes: [arrowMesh, arrowTail],\n colliderMeshes: [collider.arrowMesh, collider.arrowTail],\n material: this._coloredMaterial,\n hoverMaterial: this._hoverMaterial,\n disableMaterial: this._disableMaterial,\n active: false,\n dragBehavior: this.dragBehavior,\n };\n (_g = this._parent) === null || _g === void 0 ? void 0 : _g.addToAxisCache(this._gizmoMesh, cache);\n this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add((pointerInfo) => {\n var _a;\n if (this._customMeshSet) {\n return;\n }\n this._isHovered = !!(cache.colliderMeshes.indexOf((_a = pointerInfo === null || pointerInfo === void 0 ? void 0 : pointerInfo.pickInfo) === null || _a === void 0 ? void 0 : _a.pickedMesh) != -1);\n if (!this._parent) {\n const material = this.dragBehavior.enabled ? (this._isHovered || this._dragging ? this._hoverMaterial : this._coloredMaterial) : this._disableMaterial;\n this._setGizmoMeshMaterial(cache.gizmoMeshes, material);\n }\n });\n this.dragBehavior.onEnabledObservable.add((newState) => {\n this._setGizmoMeshMaterial(cache.gizmoMeshes, newState ? this._coloredMaterial : this._disableMaterial);\n });\n const light = gizmoLayer._getSharedGizmoLight();\n light.includedOnlyMeshes = light.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes());\n }\n /**\n * Create Geometry for Gizmo\n * @param parentMesh\n * @param thickness\n * @param isCollider\n */\n _createGizmoMesh(parentMesh, thickness, isCollider = false) {\n const arrowMesh = CreateBox(\"yPosMesh\", { size: 0.4 * (1 + (thickness - 1) / 4) }, this.gizmoLayer.utilityLayerScene);\n const arrowTail = CreateCylinder(\"cylinder\", { diameterTop: 0.005 * thickness, height: 0.275, diameterBottom: 0.005 * thickness, tessellation: 96 }, this.gizmoLayer.utilityLayerScene);\n // Position arrow pointing in its drag axis\n arrowMesh.scaling.scaleInPlace(0.1);\n arrowMesh.material = this._coloredMaterial;\n arrowMesh.rotation.x = Math.PI / 2;\n arrowMesh.position.z += 0.3;\n arrowTail.material = this._coloredMaterial;\n arrowTail.position.z += 0.275 / 2;\n arrowTail.rotation.x = Math.PI / 2;\n if (isCollider) {\n arrowMesh.visibility = 0;\n arrowTail.visibility = 0;\n }\n parentMesh.addChild(arrowMesh);\n parentMesh.addChild(arrowTail);\n return { arrowMesh, arrowTail };\n }\n _attachedNodeChanged(value) {\n if (this.dragBehavior) {\n this.dragBehavior.enabled = value ? true : false;\n }\n }\n /**\n * If the gizmo is enabled\n */\n set isEnabled(value) {\n this._isEnabled = value;\n if (!value) {\n this.attachedMesh = null;\n this.attachedNode = null;\n }\n else {\n if (this._parent) {\n this.attachedMesh = this._parent.attachedMesh;\n this.attachedNode = this._parent.attachedNode;\n }\n }\n }\n get isEnabled() {\n return this._isEnabled;\n }\n /**\n * Disposes of the gizmo\n */\n dispose() {\n this.onSnapObservable.clear();\n this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);\n this.dragBehavior.detach();\n if (this._gizmoMesh) {\n this._gizmoMesh.dispose();\n }\n [this._coloredMaterial, this._hoverMaterial, this._disableMaterial].forEach((matl) => {\n if (matl) {\n matl.dispose();\n }\n });\n super.dispose();\n }\n /**\n * Disposes and replaces the current meshes in the gizmo with the specified mesh\n * @param mesh The mesh to replace the default mesh of the gizmo\n * @param useGizmoMaterial If the gizmo's default material should be used (default: false)\n */\n setCustomMesh(mesh, useGizmoMaterial = false) {\n super.setCustomMesh(mesh);\n if (useGizmoMaterial) {\n this._rootMesh.getChildMeshes().forEach((m) => {\n m.material = this._coloredMaterial;\n if (m.color) {\n m.color = this._coloredMaterial.diffuseColor;\n }\n });\n this._customMeshSet = false;\n }\n }\n}\n//# sourceMappingURL=axisScaleGizmo.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { Quaternion, Matrix, Vector3 } from \"../Maths/math.vector.js\";\nimport { AbstractMesh } from \"../Meshes/abstractMesh.js\";\nimport { CreateSphere } from \"../Meshes/Builders/sphereBuilder.js\";\nimport { CreateBox } from \"../Meshes/Builders/boxBuilder.js\";\nimport { CreateLines } from \"../Meshes/Builders/linesBuilder.js\";\nimport { PointerDragBehavior } from \"../Behaviors/Meshes/pointerDragBehavior.js\";\nimport { Gizmo } from \"./gizmo.js\";\nimport { UtilityLayerRenderer } from \"../Rendering/utilityLayerRenderer.js\";\nimport { StandardMaterial } from \"../Materials/standardMaterial.js\";\nimport { PivotTools } from \"../Misc/pivotTools.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { Epsilon } from \"../Maths/math.constants.js\";\n/**\n * Bounding box gizmo\n */\nexport class BoundingBoxGizmo extends Gizmo {\n /**\n * Sets the axis factor\n * @param factor the Vector3 value\n */\n set axisFactor(factor) {\n this._axisFactor = factor;\n // update scale cube visibility\n const scaleBoxes = this._scaleBoxesParent.getChildMeshes();\n let index = 0;\n for (let i = 0; i < 3; i++) {\n for (let j = 0; j < 3; j++) {\n for (let k = 0; k < 3; k++) {\n const zeroAxisCount = (i === 1 ? 1 : 0) + (j === 1 ? 1 : 0) + (k === 1 ? 1 : 0);\n if (zeroAxisCount === 1 || zeroAxisCount === 3) {\n continue;\n }\n if (scaleBoxes[index]) {\n const dragAxis = new Vector3(i - 1, j - 1, k - 1);\n dragAxis.multiplyInPlace(this._axisFactor);\n scaleBoxes[index].setEnabled(dragAxis.lengthSquared() > Epsilon);\n }\n index++;\n }\n }\n }\n }\n /**\n * Gets the axis factor\n * @returns the Vector3 factor value\n */\n get axisFactor() {\n return this._axisFactor;\n }\n /**\n * Sets scale drag speed value\n * @param value the new speed value\n */\n set scaleDragSpeed(value) {\n this._scaleDragSpeed = value;\n }\n /**\n * Gets scale drag speed\n * @returns the scale speed number\n */\n get scaleDragSpeed() {\n return this._scaleDragSpeed;\n }\n /** Default material used to render when gizmo is not disabled or hovered */\n get coloredMaterial() {\n return this._coloredMaterial;\n }\n /** Material used to render when gizmo is hovered with mouse*/\n get hoverMaterial() {\n return this._hoverColoredMaterial;\n }\n /**\n * Get the pointerDragBehavior\n */\n get pointerDragBehavior() {\n return this._pointerDragBehavior;\n }\n /**\n * Sets the color of the bounding box gizmo\n * @param color the color to set\n */\n setColor(color) {\n this._coloredMaterial.emissiveColor = color;\n this._hoverColoredMaterial.emissiveColor = color.clone().add(new Color3(0.3, 0.3, 0.3));\n this._lineBoundingBox.getChildren().forEach((l) => {\n if (l.color) {\n l.color = color;\n }\n });\n }\n /**\n * Creates an BoundingBoxGizmo\n * @param color The color of the gizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n */\n constructor(color = Color3.Gray(), gizmoLayer = UtilityLayerRenderer.DefaultKeepDepthUtilityLayer) {\n super(gizmoLayer);\n this._boundingDimensions = new Vector3(1, 1, 1);\n this._renderObserver = null;\n this._pointerObserver = null;\n this._scaleDragSpeed = 0.2;\n this._tmpQuaternion = new Quaternion();\n this._tmpVector = new Vector3(0, 0, 0);\n this._tmpRotationMatrix = new Matrix();\n /**\n * If child meshes should be ignored when calculating the bounding box. This should be set to true to avoid perf hits with heavily nested meshes (Default: false)\n */\n this.ignoreChildren = false;\n /**\n * Returns true if a descendant should be included when computing the bounding box. When null, all descendants are included. If ignoreChildren is set this will be ignored. (Default: null)\n */\n this.includeChildPredicate = null;\n /**\n * The size of the rotation spheres attached to the bounding box (Default: 0.1)\n */\n this.rotationSphereSize = 0.1;\n /**\n * The size of the scale boxes attached to the bounding box (Default: 0.1)\n */\n this.scaleBoxSize = 0.1;\n /**\n * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false)\n * Note : fixedDragMeshScreenSize takes precedence over fixedDragMeshBoundsSize if both are true\n */\n this.fixedDragMeshScreenSize = false;\n /**\n * If set, the rotation spheres and scale boxes will increase in size based on the size of the bounding box\n * Note : fixedDragMeshScreenSize takes precedence over fixedDragMeshBoundsSize if both are true\n */\n this.fixedDragMeshBoundsSize = false;\n /**\n * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)\n */\n this.fixedDragMeshScreenSizeDistanceFactor = 10;\n /**\n * Fired when a rotation sphere or scale box is dragged\n */\n this.onDragStartObservable = new Observable();\n /**\n * Fired when a scale box is dragged\n */\n this.onScaleBoxDragObservable = new Observable();\n /**\n * Fired when a scale box drag is ended\n */\n this.onScaleBoxDragEndObservable = new Observable();\n /**\n * Fired when a rotation sphere is dragged\n */\n this.onRotationSphereDragObservable = new Observable();\n /**\n * Fired when a rotation sphere drag is ended\n */\n this.onRotationSphereDragEndObservable = new Observable();\n /**\n * Relative bounding box pivot used when scaling the attached node. When null object with scale from the opposite corner. 0.5,0.5,0.5 for center and 0.5,0,0.5 for bottom (Default: null)\n */\n this.scalePivot = null;\n /**\n * Scale factor used for masking some axis\n */\n this._axisFactor = new Vector3(1, 1, 1);\n this._existingMeshScale = new Vector3();\n // Dragging\n this._dragMesh = null;\n this._pointerDragBehavior = new PointerDragBehavior();\n // Do not update the gizmo's scale so it has a fixed size to the object its attached to\n this.updateScale = false;\n this._anchorMesh = new AbstractMesh(\"anchor\", gizmoLayer.utilityLayerScene);\n // Create Materials\n this._coloredMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._coloredMaterial.disableLighting = true;\n this._hoverColoredMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._hoverColoredMaterial.disableLighting = true;\n // Build bounding box out of lines\n this._lineBoundingBox = new AbstractMesh(\"\", gizmoLayer.utilityLayerScene);\n this._lineBoundingBox.rotationQuaternion = new Quaternion();\n const lines = [];\n lines.push(CreateLines(\"lines\", { points: [new Vector3(0, 0, 0), new Vector3(this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));\n lines.push(CreateLines(\"lines\", { points: [new Vector3(0, 0, 0), new Vector3(0, this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));\n lines.push(CreateLines(\"lines\", { points: [new Vector3(0, 0, 0), new Vector3(0, 0, this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));\n lines.push(CreateLines(\"lines\", { points: [new Vector3(this._boundingDimensions.x, 0, 0), new Vector3(this._boundingDimensions.x, this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));\n lines.push(CreateLines(\"lines\", { points: [new Vector3(this._boundingDimensions.x, 0, 0), new Vector3(this._boundingDimensions.x, 0, this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));\n lines.push(CreateLines(\"lines\", { points: [new Vector3(0, this._boundingDimensions.y, 0), new Vector3(this._boundingDimensions.x, this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));\n lines.push(CreateLines(\"lines\", { points: [new Vector3(0, this._boundingDimensions.y, 0), new Vector3(0, this._boundingDimensions.y, this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));\n lines.push(CreateLines(\"lines\", { points: [new Vector3(0, 0, this._boundingDimensions.z), new Vector3(this._boundingDimensions.x, 0, this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));\n lines.push(CreateLines(\"lines\", { points: [new Vector3(0, 0, this._boundingDimensions.z), new Vector3(0, this._boundingDimensions.y, this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));\n lines.push(CreateLines(\"lines\", {\n points: [\n new Vector3(this._boundingDimensions.x, this._boundingDimensions.y, this._boundingDimensions.z),\n new Vector3(0, this._boundingDimensions.y, this._boundingDimensions.z),\n ],\n }, gizmoLayer.utilityLayerScene));\n lines.push(CreateLines(\"lines\", {\n points: [\n new Vector3(this._boundingDimensions.x, this._boundingDimensions.y, this._boundingDimensions.z),\n new Vector3(this._boundingDimensions.x, 0, this._boundingDimensions.z),\n ],\n }, gizmoLayer.utilityLayerScene));\n lines.push(CreateLines(\"lines\", {\n points: [\n new Vector3(this._boundingDimensions.x, this._boundingDimensions.y, this._boundingDimensions.z),\n new Vector3(this._boundingDimensions.x, this._boundingDimensions.y, 0),\n ],\n }, gizmoLayer.utilityLayerScene));\n lines.forEach((l) => {\n l.color = color;\n l.position.addInPlace(new Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));\n l.isPickable = false;\n this._lineBoundingBox.addChild(l);\n });\n this._rootMesh.addChild(this._lineBoundingBox);\n this.setColor(color);\n // Create rotation spheres\n this._rotateSpheresParent = new AbstractMesh(\"\", gizmoLayer.utilityLayerScene);\n this._rotateSpheresParent.rotationQuaternion = new Quaternion();\n for (let i = 0; i < 12; i++) {\n const sphere = CreateSphere(\"\", { diameter: 1 }, gizmoLayer.utilityLayerScene);\n sphere.rotationQuaternion = new Quaternion();\n sphere.material = this._coloredMaterial;\n sphere.isNearGrabbable = true;\n // Drag behavior\n const _dragBehavior = new PointerDragBehavior({});\n _dragBehavior.moveAttached = false;\n _dragBehavior.updateDragPlane = false;\n sphere.addBehavior(_dragBehavior);\n const startingTurnDirection = new Vector3(1, 0, 0);\n let totalTurnAmountOfDrag = 0;\n _dragBehavior.onDragStartObservable.add(() => {\n startingTurnDirection.copyFrom(sphere.forward);\n totalTurnAmountOfDrag = 0;\n });\n _dragBehavior.onDragObservable.add((event) => {\n this.onRotationSphereDragObservable.notifyObservers({});\n if (this.attachedMesh) {\n const originalParent = this.attachedMesh.parent;\n if (originalParent && originalParent.scaling && originalParent.scaling.isNonUniformWithinEpsilon(0.001)) {\n Logger.Warn(\"BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling\");\n return;\n }\n PivotTools._RemoveAndStorePivotPoint(this.attachedMesh);\n const worldDragDirection = startingTurnDirection;\n // Project the world right on to the drag plane\n const toSub = event.dragPlaneNormal.scale(Vector3.Dot(event.dragPlaneNormal, worldDragDirection));\n const dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();\n // project drag delta on to the resulting drag axis and rotate based on that\n let projectDist = Vector3.Dot(dragAxis, event.delta) < 0 ? Math.abs(event.delta.length()) : -Math.abs(event.delta.length());\n // Make rotation relative to size of mesh.\n projectDist = (projectDist / this._boundingDimensions.length()) * this._anchorMesh.scaling.length();\n // Rotate based on axis\n if (!this.attachedMesh.rotationQuaternion) {\n this.attachedMesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);\n }\n if (!this._anchorMesh.rotationQuaternion) {\n this._anchorMesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);\n }\n // Do not allow the object to turn more than a full circle\n totalTurnAmountOfDrag += projectDist;\n if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {\n if (i >= 8) {\n Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, this._tmpQuaternion);\n }\n else if (i >= 4) {\n Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, this._tmpQuaternion);\n }\n else {\n Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, this._tmpQuaternion);\n }\n // Rotate around center of bounding box\n this._anchorMesh.addChild(this.attachedMesh, Gizmo.PreserveScaling);\n if (this._anchorMesh.getScene().useRightHandedSystem) {\n this._tmpQuaternion.conjugateInPlace();\n }\n this._anchorMesh.rotationQuaternion.multiplyToRef(this._tmpQuaternion, this._anchorMesh.rotationQuaternion);\n this._anchorMesh.removeChild(this.attachedMesh, Gizmo.PreserveScaling);\n this.attachedMesh.setParent(originalParent, Gizmo.PreserveScaling);\n }\n this.updateBoundingBox();\n PivotTools._RestorePivotPoint(this.attachedMesh);\n }\n this._updateDummy();\n });\n // Selection/deselection\n _dragBehavior.onDragStartObservable.add(() => {\n this.onDragStartObservable.notifyObservers({});\n this._selectNode(sphere);\n });\n _dragBehavior.onDragEndObservable.add((event) => {\n this.onRotationSphereDragEndObservable.notifyObservers({});\n this._selectNode(null);\n this._updateDummy();\n this._unhoverMeshOnTouchUp(event.pointerInfo, sphere);\n });\n this._rotateSpheresParent.addChild(sphere);\n }\n this._rootMesh.addChild(this._rotateSpheresParent);\n // Create scale cubes\n this._scaleBoxesParent = new AbstractMesh(\"\", gizmoLayer.utilityLayerScene);\n this._scaleBoxesParent.rotationQuaternion = new Quaternion();\n for (let i = 0; i < 3; i++) {\n for (let j = 0; j < 3; j++) {\n for (let k = 0; k < 3; k++) {\n // create box for relevant axis\n const zeroAxisCount = (i === 1 ? 1 : 0) + (j === 1 ? 1 : 0) + (k === 1 ? 1 : 0);\n if (zeroAxisCount === 1 || zeroAxisCount === 3) {\n continue;\n }\n const box = CreateBox(\"\", { size: 1 }, gizmoLayer.utilityLayerScene);\n box.material = this._coloredMaterial;\n box._internalMetadata = zeroAxisCount === 2; // None homogenous scale handle\n box.isNearGrabbable = true;\n // Dragging logic\n const dragAxis = new Vector3(i - 1, j - 1, k - 1).normalize();\n const _dragBehavior = new PointerDragBehavior({ dragAxis: dragAxis });\n _dragBehavior.updateDragPlane = false;\n _dragBehavior.moveAttached = false;\n box.addBehavior(_dragBehavior);\n _dragBehavior.onDragObservable.add((event) => {\n this.onScaleBoxDragObservable.notifyObservers({});\n if (this.attachedMesh) {\n const originalParent = this.attachedMesh.parent;\n if (originalParent && originalParent.scaling && originalParent.scaling.isNonUniformWithinEpsilon(0.001)) {\n Logger.Warn(\"BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling\");\n return;\n }\n PivotTools._RemoveAndStorePivotPoint(this.attachedMesh);\n const relativeDragDistance = (event.dragDistance / this._boundingDimensions.length()) * this._anchorMesh.scaling.length();\n const deltaScale = new Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);\n if (zeroAxisCount === 2) {\n // scale on 1 axis when using the anchor box in the face middle\n deltaScale.x *= Math.abs(dragAxis.x);\n deltaScale.y *= Math.abs(dragAxis.y);\n deltaScale.z *= Math.abs(dragAxis.z);\n }\n deltaScale.scaleInPlace(this._scaleDragSpeed);\n deltaScale.multiplyInPlace(this._axisFactor);\n this.updateBoundingBox();\n if (this.scalePivot) {\n this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(this._tmpRotationMatrix);\n // Move anchor to desired pivot point (Bottom left corner + dimension/2)\n this._boundingDimensions.scaleToRef(0.5, this._tmpVector);\n Vector3.TransformCoordinatesToRef(this._tmpVector, this._tmpRotationMatrix, this._tmpVector);\n this._anchorMesh.position.subtractInPlace(this._tmpVector);\n this._boundingDimensions.multiplyToRef(this.scalePivot, this._tmpVector);\n Vector3.TransformCoordinatesToRef(this._tmpVector, this._tmpRotationMatrix, this._tmpVector);\n this._anchorMesh.position.addInPlace(this._tmpVector);\n }\n else {\n // Scale from the position of the opposite corner\n box.absolutePosition.subtractToRef(this._anchorMesh.position, this._tmpVector);\n this._anchorMesh.position.subtractInPlace(this._tmpVector);\n }\n this._anchorMesh.addChild(this.attachedMesh, Gizmo.PreserveScaling);\n this._anchorMesh.scaling.addInPlace(deltaScale);\n if (this._anchorMesh.scaling.x < 0 || this._anchorMesh.scaling.y < 0 || this._anchorMesh.scaling.z < 0) {\n this._anchorMesh.scaling.subtractInPlace(deltaScale);\n }\n this._anchorMesh.removeChild(this.attachedMesh, Gizmo.PreserveScaling);\n this.attachedMesh.setParent(originalParent, Gizmo.PreserveScaling);\n PivotTools._RestorePivotPoint(this.attachedMesh);\n }\n this._updateDummy();\n });\n // Selection/deselection\n _dragBehavior.onDragStartObservable.add(() => {\n this.onDragStartObservable.notifyObservers({});\n this._selectNode(box);\n });\n _dragBehavior.onDragEndObservable.add((event) => {\n this.onScaleBoxDragEndObservable.notifyObservers({});\n this._selectNode(null);\n this._updateDummy();\n this._unhoverMeshOnTouchUp(event.pointerInfo, box);\n });\n this._scaleBoxesParent.addChild(box);\n }\n }\n }\n this._rootMesh.addChild(this._scaleBoxesParent);\n // Hover color change\n const pointerIds = new Array();\n this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add((pointerInfo) => {\n if (!pointerIds[pointerInfo.event.pointerId]) {\n this._rotateSpheresParent\n .getChildMeshes()\n .concat(this._scaleBoxesParent.getChildMeshes())\n .forEach((mesh) => {\n if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {\n pointerIds[pointerInfo.event.pointerId] = mesh;\n mesh.material = this._hoverColoredMaterial;\n }\n });\n }\n else {\n if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {\n pointerIds[pointerInfo.event.pointerId].material = this._coloredMaterial;\n delete pointerIds[pointerInfo.event.pointerId];\n }\n }\n });\n // Update bounding box positions\n this._renderObserver = this.gizmoLayer.originalScene.onBeforeRenderObservable.add(() => {\n // Only update the bounding box if scaling has changed\n if (this.attachedMesh && !this._existingMeshScale.equals(this.attachedMesh.scaling)) {\n this.updateBoundingBox();\n }\n else if (this.fixedDragMeshScreenSize || this.fixedDragMeshBoundsSize) {\n this._updateRotationSpheres();\n this._updateScaleBoxes();\n }\n // If drag mesh is enabled and dragging, update the attached mesh pose to match the drag mesh\n if (this._dragMesh && this.attachedMesh && this._pointerDragBehavior.dragging) {\n this._lineBoundingBox.position.rotateByQuaternionToRef(this._rootMesh.rotationQuaternion, this._tmpVector);\n this.attachedMesh.setAbsolutePosition(this._dragMesh.position.add(this._tmpVector.scale(-1)));\n }\n });\n this.updateBoundingBox();\n }\n _attachedNodeChanged(value) {\n if (value) {\n // Reset anchor mesh to match attached mesh's scale\n // This is needed to avoid invalid box/sphere position on first drag\n this._anchorMesh.scaling.setAll(1);\n PivotTools._RemoveAndStorePivotPoint(value);\n const originalParent = value.parent;\n this._anchorMesh.addChild(value, Gizmo.PreserveScaling);\n this._anchorMesh.removeChild(value, Gizmo.PreserveScaling);\n value.setParent(originalParent, Gizmo.PreserveScaling);\n PivotTools._RestorePivotPoint(value);\n this.updateBoundingBox();\n value.getChildMeshes(false).forEach((m) => {\n m.markAsDirty(\"scaling\");\n });\n this.gizmoLayer.utilityLayerScene.onAfterRenderObservable.addOnce(() => {\n this._updateDummy();\n });\n }\n }\n _selectNode(selectedMesh) {\n this._rotateSpheresParent\n .getChildMeshes()\n .concat(this._scaleBoxesParent.getChildMeshes())\n .forEach((m) => {\n m.isVisible = !selectedMesh || m == selectedMesh;\n });\n }\n _unhoverMeshOnTouchUp(pointerInfo, selectedMesh) {\n // force unhover mesh if not a mouse event\n if ((pointerInfo === null || pointerInfo === void 0 ? void 0 : pointerInfo.event) instanceof PointerEvent && (pointerInfo === null || pointerInfo === void 0 ? void 0 : pointerInfo.event.pointerType) === \"touch\") {\n selectedMesh.material = this._coloredMaterial;\n }\n }\n /**\n * returns an array containing all boxes used for scaling (in increasing x, y and z orders)\n */\n getScaleBoxes() {\n return this._scaleBoxesParent.getChildMeshes();\n }\n /**\n * Updates the bounding box information for the Gizmo\n */\n updateBoundingBox() {\n if (this.attachedMesh) {\n PivotTools._RemoveAndStorePivotPoint(this.attachedMesh);\n // Store original parent\n const originalParent = this.attachedMesh.parent;\n this.attachedMesh.setParent(null, Gizmo.PreserveScaling);\n this._update();\n // Rotate based on axis\n if (!this.attachedMesh.rotationQuaternion) {\n this.attachedMesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);\n }\n if (!this._anchorMesh.rotationQuaternion) {\n this._anchorMesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);\n }\n this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);\n // Store original position and reset mesh to origin before computing the bounding box\n this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);\n this._tmpVector.copyFrom(this.attachedMesh.position);\n this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);\n this.attachedMesh.position.set(0, 0, 0);\n // Update bounding dimensions/positions\n const boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);\n boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);\n // Update gizmo to match bounding box scaling and rotation\n // The position set here is the offset from the origin for the boundingbox when the attached mesh is at the origin\n // The position of the gizmo is then set to the attachedMesh in gizmo._update\n this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);\n this._lineBoundingBox.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);\n this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);\n this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);\n this._lineBoundingBox.computeWorldMatrix();\n this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);\n // Restore position/rotation values\n this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);\n this.attachedMesh.position.copyFrom(this._tmpVector);\n // Restore original parent\n this.attachedMesh.setParent(originalParent, Gizmo.PreserveScaling);\n }\n this._updateRotationSpheres();\n this._updateScaleBoxes();\n if (this.attachedMesh) {\n this._existingMeshScale.copyFrom(this.attachedMesh.scaling);\n PivotTools._RestorePivotPoint(this.attachedMesh);\n }\n }\n _updateRotationSpheres() {\n const rotateSpheres = this._rotateSpheresParent.getChildMeshes();\n for (let i = 0; i < 3; i++) {\n for (let j = 0; j < 2; j++) {\n for (let k = 0; k < 2; k++) {\n const index = i * 4 + j * 2 + k;\n if (i == 0) {\n rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);\n rotateSpheres[index].position.addInPlace(new Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));\n rotateSpheres[index].lookAt(Vector3.Cross(rotateSpheres[index].position.normalizeToNew(), Vector3.Right()).normalizeToNew().add(rotateSpheres[index].position));\n }\n if (i == 1) {\n rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);\n rotateSpheres[index].position.addInPlace(new Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));\n rotateSpheres[index].lookAt(Vector3.Cross(rotateSpheres[index].position.normalizeToNew(), Vector3.Up()).normalizeToNew().add(rotateSpheres[index].position));\n }\n if (i == 2) {\n rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);\n rotateSpheres[index].position.addInPlace(new Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));\n rotateSpheres[index].lookAt(Vector3.Cross(rotateSpheres[index].position.normalizeToNew(), Vector3.Forward()).normalizeToNew().add(rotateSpheres[index].position));\n }\n if (this.fixedDragMeshScreenSize && this.gizmoLayer.utilityLayerScene.activeCamera) {\n rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);\n const distanceFromCamera = (this.rotationSphereSize * this._tmpVector.length()) / this.fixedDragMeshScreenSizeDistanceFactor;\n rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);\n }\n else if (this.fixedDragMeshBoundsSize) {\n rotateSpheres[index].scaling.set(this.rotationSphereSize * this._boundingDimensions.x, this.rotationSphereSize * this._boundingDimensions.y, this.rotationSphereSize * this._boundingDimensions.z);\n }\n else {\n rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);\n }\n }\n }\n }\n }\n _updateScaleBoxes() {\n const scaleBoxes = this._scaleBoxesParent.getChildMeshes();\n let index = 0;\n for (let i = 0; i < 3; i++) {\n for (let j = 0; j < 3; j++) {\n for (let k = 0; k < 3; k++) {\n const zeroAxisCount = (i === 1 ? 1 : 0) + (j === 1 ? 1 : 0) + (k === 1 ? 1 : 0);\n if (zeroAxisCount === 1 || zeroAxisCount === 3) {\n continue;\n }\n if (scaleBoxes[index]) {\n scaleBoxes[index].position.set(this._boundingDimensions.x * (i / 2), this._boundingDimensions.y * (j / 2), this._boundingDimensions.z * (k / 2));\n scaleBoxes[index].position.addInPlace(new Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));\n if (this.fixedDragMeshScreenSize && this.gizmoLayer.utilityLayerScene.activeCamera) {\n scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);\n const distanceFromCamera = (this.scaleBoxSize * this._tmpVector.length()) / this.fixedDragMeshScreenSizeDistanceFactor;\n scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);\n }\n else if (this.fixedDragMeshBoundsSize) {\n scaleBoxes[index].scaling.set(this.scaleBoxSize * this._boundingDimensions.x, this.scaleBoxSize * this._boundingDimensions.y, this.scaleBoxSize * this._boundingDimensions.z);\n }\n else {\n scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);\n }\n }\n index++;\n }\n }\n }\n }\n /**\n * Enables rotation on the specified axis and disables rotation on the others\n * @param axis The list of axis that should be enabled (eg. \"xy\" or \"xyz\")\n */\n setEnabledRotationAxis(axis) {\n this._rotateSpheresParent.getChildMeshes().forEach((m, i) => {\n if (i < 4) {\n m.setEnabled(axis.indexOf(\"x\") != -1);\n }\n else if (i < 8) {\n m.setEnabled(axis.indexOf(\"y\") != -1);\n }\n else {\n m.setEnabled(axis.indexOf(\"z\") != -1);\n }\n });\n }\n /**\n * Enables/disables scaling\n * @param enable if scaling should be enabled\n * @param homogeneousScaling defines if scaling should only be homogeneous\n */\n setEnabledScaling(enable, homogeneousScaling = false) {\n this._scaleBoxesParent.getChildMeshes().forEach((m) => {\n let enableMesh = enable;\n // Disable heterogeneous scale handles if requested.\n if (homogeneousScaling && m._internalMetadata === true) {\n enableMesh = false;\n }\n m.setEnabled(enableMesh);\n });\n }\n _updateDummy() {\n if (this._dragMesh) {\n this._dragMesh.position.copyFrom(this._lineBoundingBox.getAbsolutePosition());\n this._dragMesh.scaling.copyFrom(this._lineBoundingBox.scaling);\n this._dragMesh.rotationQuaternion.copyFrom(this._rootMesh.rotationQuaternion);\n }\n }\n /**\n * Enables a pointer drag behavior on the bounding box of the gizmo\n */\n enableDragBehavior() {\n this._dragMesh = CreateBox(\"dummy\", { size: 1 }, this.gizmoLayer.utilityLayerScene);\n this._dragMesh.visibility = 0;\n this._dragMesh.rotationQuaternion = new Quaternion();\n this._pointerDragBehavior.useObjectOrientationForDragging = false;\n this._dragMesh.addBehavior(this._pointerDragBehavior);\n }\n /**\n * Disposes of the gizmo\n */\n dispose() {\n this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);\n this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);\n this._lineBoundingBox.dispose();\n this._rotateSpheresParent.dispose();\n this._scaleBoxesParent.dispose();\n if (this._dragMesh) {\n this._dragMesh.dispose();\n }\n super.dispose();\n }\n /**\n * Makes a mesh not pickable and wraps the mesh inside of a bounding box mesh that is pickable. (This is useful to avoid picking within complex geometry)\n * @param mesh the mesh to wrap in the bounding box mesh and make not pickable\n * @returns the bounding box mesh with the passed in mesh as a child\n */\n static MakeNotPickableAndWrapInBoundingBox(mesh) {\n const makeNotPickable = (root) => {\n root.isPickable = false;\n root.getChildMeshes().forEach((c) => {\n makeNotPickable(c);\n });\n };\n makeNotPickable(mesh);\n // Reset position to get bounding box from origin with no rotation\n if (!mesh.rotationQuaternion) {\n mesh.rotationQuaternion = Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);\n }\n const oldPos = mesh.position.clone();\n const oldRot = mesh.rotationQuaternion.clone();\n mesh.rotationQuaternion.set(0, 0, 0, 1);\n mesh.position.set(0, 0, 0);\n // Update bounding dimensions/positions\n const box = CreateBox(\"box\", { size: 1 }, mesh.getScene());\n const boundingMinMax = mesh.getHierarchyBoundingVectors();\n boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);\n // Adjust scale to avoid undefined behavior when adding child\n if (box.scaling.y === 0) {\n box.scaling.y = Epsilon;\n }\n if (box.scaling.x === 0) {\n box.scaling.x = Epsilon;\n }\n if (box.scaling.z === 0) {\n box.scaling.z = Epsilon;\n }\n box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);\n // Restore original positions\n mesh.addChild(box);\n mesh.rotationQuaternion.copyFrom(oldRot);\n mesh.position.copyFrom(oldPos);\n // Reverse parenting\n mesh.removeChild(box);\n box.addChild(mesh);\n box.visibility = 0;\n return box;\n }\n /**\n * CustomMeshes are not supported by this gizmo\n */\n setCustomMesh() {\n Logger.Error(\"Custom meshes are not supported on this gizmo\");\n }\n}\n//# sourceMappingURL=boundingBoxGizmo.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { Quaternion, Matrix, Vector3, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport \"../Meshes/Builders/linesBuilder.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { PointerDragBehavior } from \"../Behaviors/Meshes/pointerDragBehavior.js\";\nimport { Gizmo } from \"./gizmo.js\";\nimport { UtilityLayerRenderer } from \"../Rendering/utilityLayerRenderer.js\";\nimport { StandardMaterial } from \"../Materials/standardMaterial.js\";\nimport { ShaderMaterial } from \"../Materials/shaderMaterial.js\";\nimport { Effect } from \"../Materials/effect.js\";\nimport { CreatePlane } from \"../Meshes/Builders/planeBuilder.js\";\nimport { CreateTorus } from \"../Meshes/Builders/torusBuilder.js\";\nimport { Epsilon } from \"../Maths/math.constants.js\";\nimport { Logger } from \"../Misc/logger.js\";\n/**\n * Single plane rotation gizmo\n */\nexport class PlaneRotationGizmo extends Gizmo {\n /** Default material used to render when gizmo is not disabled or hovered */\n get coloredMaterial() {\n return this._coloredMaterial;\n }\n /** Material used to render when gizmo is hovered with mouse*/\n get hoverMaterial() {\n return this._hoverMaterial;\n }\n /** Material used to render when gizmo is disabled. typically grey.*/\n get disableMaterial() {\n return this._disableMaterial;\n }\n /**\n * Creates a PlaneRotationGizmo\n * @param planeNormal The normal of the plane which the gizmo will be able to rotate on\n * @param color The color of the gizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n * @param tessellation Amount of tessellation to be used when creating rotation circles\n * @param parent\n * @param useEulerRotation Use and update Euler angle instead of quaternion\n * @param thickness display gizmo axis thickness\n */\n constructor(planeNormal, color = Color3.Gray(), gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer, tessellation = 32, parent = null, \n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n useEulerRotation = false, thickness = 1) {\n var _a;\n super(gizmoLayer);\n this._pointerObserver = null;\n /**\n * Rotation distance in radians that the gizmo will snap to (Default: 0)\n */\n this.snapDistance = 0;\n /**\n * Event that fires each time the gizmo snaps to a new location.\n * * snapDistance is the the change in distance\n */\n this.onSnapObservable = new Observable();\n /**\n * Accumulated relative angle value for rotation on the axis. Reset to 0 when a dragStart occurs\n */\n this.angle = 0;\n this._isEnabled = true;\n this._parent = null;\n this._dragging = false;\n this._angles = new Vector3();\n this._parent = parent;\n // Create Material\n this._coloredMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._coloredMaterial.diffuseColor = color;\n this._coloredMaterial.specularColor = color.subtract(new Color3(0.1, 0.1, 0.1));\n this._hoverMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._hoverMaterial.diffuseColor = Color3.Yellow();\n this._disableMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._disableMaterial.diffuseColor = Color3.Gray();\n this._disableMaterial.alpha = 0.4;\n // Build mesh on root node\n this._gizmoMesh = new Mesh(\"\", gizmoLayer.utilityLayerScene);\n const { rotationMesh, collider } = this._createGizmoMesh(this._gizmoMesh, thickness, tessellation);\n // Setup Rotation Circle\n this._rotationDisplayPlane = CreatePlane(\"rotationDisplay\", { size: 0.6, updatable: false }, this.gizmoLayer.utilityLayerScene);\n this._rotationDisplayPlane.rotation.z = Math.PI * 0.5;\n this._rotationDisplayPlane.parent = this._gizmoMesh;\n this._rotationDisplayPlane.setEnabled(false);\n Effect.ShadersStore[\"rotationGizmoVertexShader\"] = PlaneRotationGizmo._RotationGizmoVertexShader;\n Effect.ShadersStore[\"rotationGizmoFragmentShader\"] = PlaneRotationGizmo._RotationGizmoFragmentShader;\n this._rotationShaderMaterial = new ShaderMaterial(\"shader\", this.gizmoLayer.utilityLayerScene, {\n vertex: \"rotationGizmo\",\n fragment: \"rotationGizmo\",\n }, {\n attributes: [\"position\", \"uv\"],\n uniforms: [\"worldViewProjection\", \"angles\"],\n });\n this._rotationShaderMaterial.backFaceCulling = false;\n this._rotationDisplayPlane.material = this._rotationShaderMaterial;\n this._rotationDisplayPlane.visibility = 0.999;\n this._gizmoMesh.lookAt(this._rootMesh.position.add(planeNormal));\n this._rootMesh.addChild(this._gizmoMesh, Gizmo.PreserveScaling);\n this._gizmoMesh.scaling.scaleInPlace(1 / 3);\n // Add drag behavior to handle events when the gizmo is dragged\n this.dragBehavior = new PointerDragBehavior({ dragPlaneNormal: planeNormal });\n this.dragBehavior.moveAttached = false;\n this.dragBehavior.maxDragAngle = PlaneRotationGizmo.MaxDragAngle;\n this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;\n this._rootMesh.addBehavior(this.dragBehavior);\n // Closures for drag logic\n const lastDragPosition = new Vector3();\n const rotationMatrix = new Matrix();\n const planeNormalTowardsCamera = new Vector3();\n let localPlaneNormalTowardsCamera = new Vector3();\n this.dragBehavior.onDragStartObservable.add((e) => {\n if (this.attachedNode) {\n lastDragPosition.copyFrom(e.dragPlanePoint);\n this._rotationDisplayPlane.setEnabled(true);\n this._rotationDisplayPlane.getWorldMatrix().invertToRef(rotationMatrix);\n Vector3.TransformCoordinatesToRef(e.dragPlanePoint, rotationMatrix, lastDragPosition);\n this._angles.x = Math.atan2(lastDragPosition.y, lastDragPosition.x) + Math.PI;\n this._angles.y = 0;\n this._angles.z = this.updateGizmoRotationToMatchAttachedMesh ? 1 : 0;\n this._dragging = true;\n lastDragPosition.copyFrom(e.dragPlanePoint);\n this._rotationShaderMaterial.setVector3(\"angles\", this._angles);\n this.angle = 0;\n }\n });\n this.dragBehavior.onDragEndObservable.add(() => {\n this._dragging = false;\n this._rotationDisplayPlane.setEnabled(false);\n });\n const tmpSnapEvent = { snapDistance: 0 };\n let currentSnapDragDistance = 0;\n const tmpMatrix = new Matrix();\n const amountToRotate = new Quaternion();\n this.dragBehavior.onDragObservable.add((event) => {\n if (this.attachedNode) {\n // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)\n const nodeScale = new Vector3(1, 1, 1);\n const nodeQuaternion = new Quaternion(0, 0, 0, 1);\n const nodeTranslation = new Vector3(0, 0, 0);\n this._handlePivot();\n this.attachedNode.getWorldMatrix().decompose(nodeScale, nodeQuaternion, nodeTranslation);\n // uniform scaling of absolute value of components\n // (-1,1,1) is uniform but (1,1.001,1) is not\n const uniformScaling = Math.abs(Math.abs(nodeScale.x) - Math.abs(nodeScale.y)) <= Epsilon && Math.abs(Math.abs(nodeScale.x) - Math.abs(nodeScale.z)) <= Epsilon;\n if (!uniformScaling && this.updateGizmoRotationToMatchAttachedMesh) {\n Logger.Warn(\"Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false.\");\n return;\n }\n nodeQuaternion.normalize();\n const nodeTranslationForOperation = this.updateGizmoPositionToMatchAttachedMesh ? nodeTranslation : this._rootMesh.absolutePosition;\n const newVector = event.dragPlanePoint.subtract(nodeTranslationForOperation).normalize();\n const originalVector = lastDragPosition.subtract(nodeTranslationForOperation).normalize();\n const cross = Vector3.Cross(newVector, originalVector);\n const dot = Vector3.Dot(newVector, originalVector);\n let angle = Math.atan2(cross.length(), dot);\n planeNormalTowardsCamera.copyFrom(planeNormal);\n localPlaneNormalTowardsCamera.copyFrom(planeNormal);\n if (this.updateGizmoRotationToMatchAttachedMesh) {\n nodeQuaternion.toRotationMatrix(rotationMatrix);\n localPlaneNormalTowardsCamera = Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);\n }\n // Flip up vector depending on which side the camera is on\n let cameraFlipped = false;\n if (gizmoLayer.utilityLayerScene.activeCamera) {\n const camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(nodeTranslationForOperation).normalize();\n if (Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {\n planeNormalTowardsCamera.scaleInPlace(-1);\n localPlaneNormalTowardsCamera.scaleInPlace(-1);\n cameraFlipped = true;\n }\n }\n const halfCircleSide = Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;\n if (halfCircleSide) {\n angle = -angle;\n }\n // Snapping logic\n let snapped = false;\n if (this.snapDistance != 0) {\n currentSnapDragDistance += angle;\n if (Math.abs(currentSnapDragDistance) > this.snapDistance) {\n let dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / this.snapDistance);\n if (currentSnapDragDistance < 0) {\n dragSteps *= -1;\n }\n currentSnapDragDistance = currentSnapDragDistance % this.snapDistance;\n angle = this.snapDistance * dragSteps;\n snapped = true;\n }\n else {\n angle = 0;\n }\n }\n // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)\n const quaternionCoefficient = Math.sin(angle / 2);\n amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));\n // If the meshes local scale is inverted (eg. loaded gltf file parent with z scale of -1) the rotation needs to be inverted on the y axis\n if (tmpMatrix.determinant() > 0) {\n const tmpVector = new Vector3();\n amountToRotate.toEulerAnglesToRef(tmpVector);\n Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);\n }\n if (this.updateGizmoRotationToMatchAttachedMesh) {\n // Rotate selected mesh quaternion over fixed axis\n nodeQuaternion.multiplyToRef(amountToRotate, nodeQuaternion);\n // recompose matrix\n Matrix.ComposeToRef(nodeScale, nodeQuaternion, nodeTranslation, this.attachedNode.getWorldMatrix());\n }\n else {\n // Rotate selected mesh quaternion over rotated axis\n amountToRotate.toRotationMatrix(TmpVectors.Matrix[0]);\n const translation = this.attachedNode.getWorldMatrix().getTranslation();\n this.attachedNode.getWorldMatrix().multiplyToRef(TmpVectors.Matrix[0], this.attachedNode.getWorldMatrix());\n this.attachedNode.getWorldMatrix().setTranslation(translation);\n }\n lastDragPosition.copyFrom(event.dragPlanePoint);\n if (snapped) {\n tmpSnapEvent.snapDistance = angle;\n this.onSnapObservable.notifyObservers(tmpSnapEvent);\n }\n this._angles.y += angle;\n this.angle += cameraFlipped ? -angle : angle;\n this._rotationShaderMaterial.setVector3(\"angles\", this._angles);\n this._matrixChanged();\n }\n });\n const light = gizmoLayer._getSharedGizmoLight();\n light.includedOnlyMeshes = light.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(false));\n const cache = {\n colliderMeshes: [collider],\n gizmoMeshes: [rotationMesh],\n material: this._coloredMaterial,\n hoverMaterial: this._hoverMaterial,\n disableMaterial: this._disableMaterial,\n active: false,\n dragBehavior: this.dragBehavior,\n };\n (_a = this._parent) === null || _a === void 0 ? void 0 : _a.addToAxisCache(this._gizmoMesh, cache);\n this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add((pointerInfo) => {\n var _a;\n if (this._customMeshSet) {\n return;\n }\n // updating here the maxangle because ondragstart is too late (value already used) and the updated value is not taken into account\n this.dragBehavior.maxDragAngle = PlaneRotationGizmo.MaxDragAngle;\n this._isHovered = !!(cache.colliderMeshes.indexOf((_a = pointerInfo === null || pointerInfo === void 0 ? void 0 : pointerInfo.pickInfo) === null || _a === void 0 ? void 0 : _a.pickedMesh) != -1);\n if (!this._parent) {\n const material = cache.dragBehavior.enabled ? (this._isHovered || this._dragging ? this._hoverMaterial : this._coloredMaterial) : this._disableMaterial;\n this._setGizmoMeshMaterial(cache.gizmoMeshes, material);\n }\n });\n this.dragBehavior.onEnabledObservable.add((newState) => {\n this._setGizmoMeshMaterial(cache.gizmoMeshes, newState ? this._coloredMaterial : this._disableMaterial);\n });\n }\n /**\n * Create Geometry for Gizmo\n * @param parentMesh\n * @param thickness\n * @param tessellation\n */\n _createGizmoMesh(parentMesh, thickness, tessellation) {\n const collider = CreateTorus(\"ignore\", {\n diameter: 0.6,\n thickness: 0.03 * thickness,\n tessellation,\n }, this.gizmoLayer.utilityLayerScene);\n collider.visibility = 0;\n const rotationMesh = CreateTorus(\"\", {\n diameter: 0.6,\n thickness: 0.005 * thickness,\n tessellation,\n }, this.gizmoLayer.utilityLayerScene);\n rotationMesh.material = this._coloredMaterial;\n // Position arrow pointing in its drag axis\n rotationMesh.rotation.x = Math.PI / 2;\n collider.rotation.x = Math.PI / 2;\n parentMesh.addChild(rotationMesh, Gizmo.PreserveScaling);\n parentMesh.addChild(collider, Gizmo.PreserveScaling);\n return { rotationMesh, collider };\n }\n _attachedNodeChanged(value) {\n if (this.dragBehavior) {\n this.dragBehavior.enabled = value ? true : false;\n }\n }\n /**\n * If the gizmo is enabled\n */\n set isEnabled(value) {\n this._isEnabled = value;\n if (!value) {\n this.attachedMesh = null;\n }\n else {\n if (this._parent) {\n this.attachedMesh = this._parent.attachedMesh;\n }\n }\n }\n get isEnabled() {\n return this._isEnabled;\n }\n /**\n * Disposes of the gizmo\n */\n dispose() {\n this.onSnapObservable.clear();\n this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);\n this.dragBehavior.detach();\n if (this._gizmoMesh) {\n this._gizmoMesh.dispose();\n }\n if (this._rotationDisplayPlane) {\n this._rotationDisplayPlane.dispose();\n }\n if (this._rotationShaderMaterial) {\n this._rotationShaderMaterial.dispose();\n }\n [this._coloredMaterial, this._hoverMaterial, this._disableMaterial].forEach((matl) => {\n if (matl) {\n matl.dispose();\n }\n });\n super.dispose();\n }\n}\n/**\n * The maximum angle between the camera and the rotation allowed for interaction\n * If a rotation plane appears 'flat', a lower value allows interaction.\n */\nPlaneRotationGizmo.MaxDragAngle = (Math.PI * 9) / 20;\nPlaneRotationGizmo._RotationGizmoVertexShader = `\r\n precision highp float;\r\n attribute vec3 position;\r\n attribute vec2 uv;\r\n uniform mat4 worldViewProjection;\r\n varying vec3 vPosition;\r\n varying vec2 vUV;\r\n void main(void) {\r\n gl_Position = worldViewProjection * vec4(position, 1.0);\r\n vUV = uv;\r\n }`;\nPlaneRotationGizmo._RotationGizmoFragmentShader = `\r\n precision highp float;\r\n varying vec2 vUV;\r\n varying vec3 vPosition;\r\n uniform vec3 angles;\r\n #define twopi 6.283185307\r\n void main(void) {\r\n vec2 uv = vUV - vec2(0.5);\r\n float angle = atan(uv.y, uv.x) + 3.141592;\r\n float delta = gl_FrontFacing ? angles.y : -angles.y;\r\n float begin = angles.x - delta * angles.z;\r\n float start = (begin < (begin + delta)) ? begin : (begin + delta);\r\n float end = (begin > (begin + delta)) ? begin : (begin + delta);\r\n float len = sqrt(dot(uv,uv));\r\n float opacity = 1. - step(0.5, len);\r\n\r\n float base = abs(floor(start / twopi)) * twopi;\r\n start += base;\r\n end += base;\r\n\r\n float intensity = 0.;\r\n for (int i = 0; i < 5; i++)\r\n {\r\n intensity += max(step(start, angle) - step(end, angle), 0.);\r\n angle += twopi;\r\n }\r\n gl_FragColor = vec4(1.,1.,0., min(intensity * 0.25, 0.8)) * opacity;\r\n }`;\n//# sourceMappingURL=planeRotationGizmo.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { Gizmo } from \"./gizmo.js\";\nimport { PlaneRotationGizmo } from \"./planeRotationGizmo.js\";\nimport { UtilityLayerRenderer } from \"../Rendering/utilityLayerRenderer.js\";\n/**\n * Gizmo that enables rotating a mesh along 3 axis\n */\nexport class RotationGizmo extends Gizmo {\n get attachedMesh() {\n return this._meshAttached;\n }\n set attachedMesh(mesh) {\n this._meshAttached = mesh;\n this._nodeAttached = mesh;\n this._checkBillboardTransform();\n [this.xGizmo, this.yGizmo, this.zGizmo].forEach((gizmo) => {\n if (gizmo.isEnabled) {\n gizmo.attachedMesh = mesh;\n }\n else {\n gizmo.attachedMesh = null;\n }\n });\n }\n get attachedNode() {\n return this._nodeAttached;\n }\n set attachedNode(node) {\n this._meshAttached = null;\n this._nodeAttached = node;\n this._checkBillboardTransform();\n [this.xGizmo, this.yGizmo, this.zGizmo].forEach((gizmo) => {\n if (gizmo.isEnabled) {\n gizmo.attachedNode = node;\n }\n else {\n gizmo.attachedNode = null;\n }\n });\n }\n _checkBillboardTransform() {\n if (this._nodeAttached && this._nodeAttached.billboardMode) {\n console.log(\"Rotation Gizmo will not work with transforms in billboard mode.\");\n }\n }\n /**\n * True when the mouse pointer is hovering a gizmo mesh\n */\n get isHovered() {\n let hovered = false;\n [this.xGizmo, this.yGizmo, this.zGizmo].forEach((gizmo) => {\n hovered = hovered || gizmo.isHovered;\n });\n return hovered;\n }\n /**\n * Creates a RotationGizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n * @param tessellation Amount of tessellation to be used when creating rotation circles\n * @param useEulerRotation Use and update Euler angle instead of quaternion\n * @param thickness display gizmo axis thickness\n * @param gizmoManager Gizmo manager\n * @param options More options\n */\n constructor(gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer, tessellation = 32, useEulerRotation = false, thickness = 1, gizmoManager, options) {\n super(gizmoLayer);\n /** Fires an event when any of it's sub gizmos are dragged */\n this.onDragStartObservable = new Observable();\n /** Fires an event when any of it's sub gizmos are released from dragging */\n this.onDragEndObservable = new Observable();\n this._observables = [];\n /** Node Caching for quick lookup */\n this._gizmoAxisCache = new Map();\n const xColor = options && options.xOptions && options.xOptions.color ? options.xOptions.color : Color3.Red().scale(0.5);\n const yColor = options && options.yOptions && options.yOptions.color ? options.yOptions.color : Color3.Green().scale(0.5);\n const zColor = options && options.zOptions && options.zOptions.color ? options.zOptions.color : Color3.Blue().scale(0.5);\n this.xGizmo = new PlaneRotationGizmo(new Vector3(1, 0, 0), xColor, gizmoLayer, tessellation, this, useEulerRotation, thickness);\n this.yGizmo = new PlaneRotationGizmo(new Vector3(0, 1, 0), yColor, gizmoLayer, tessellation, this, useEulerRotation, thickness);\n this.zGizmo = new PlaneRotationGizmo(new Vector3(0, 0, 1), zColor, gizmoLayer, tessellation, this, useEulerRotation, thickness);\n // Relay drag events and set update scale\n [this.xGizmo, this.yGizmo, this.zGizmo].forEach((gizmo) => {\n //must set updateScale on each gizmo, as setting it on root RotationGizmo doesnt prevent individual gizmos from updating\n //currently updateScale is a property with no getter/setter, so no good way to override behavior at runtime, so we will at least set it on startup\n if (options && options.updateScale != undefined) {\n gizmo.updateScale = options.updateScale;\n }\n gizmo.dragBehavior.onDragStartObservable.add(() => {\n this.onDragStartObservable.notifyObservers({});\n });\n gizmo.dragBehavior.onDragEndObservable.add(() => {\n this.onDragEndObservable.notifyObservers({});\n });\n });\n this.attachedMesh = null;\n this.attachedNode = null;\n if (gizmoManager) {\n gizmoManager.addToAxisCache(this._gizmoAxisCache);\n }\n else {\n // Only subscribe to pointer event if gizmoManager isnt\n Gizmo.GizmoAxisPointerObserver(gizmoLayer, this._gizmoAxisCache);\n }\n }\n /**\n * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)\n * NOTE: This is only possible for meshes with uniform scaling, as otherwise it's not possible to decompose the rotation\n */\n set updateGizmoRotationToMatchAttachedMesh(value) {\n if (this.xGizmo) {\n this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;\n this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;\n this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;\n }\n }\n get updateGizmoRotationToMatchAttachedMesh() {\n return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;\n }\n set updateGizmoPositionToMatchAttachedMesh(value) {\n if (this.xGizmo) {\n this.xGizmo.updateGizmoPositionToMatchAttachedMesh = value;\n this.yGizmo.updateGizmoPositionToMatchAttachedMesh = value;\n this.zGizmo.updateGizmoPositionToMatchAttachedMesh = value;\n }\n }\n get updateGizmoPositionToMatchAttachedMesh() {\n return this.xGizmo.updateGizmoPositionToMatchAttachedMesh;\n }\n set anchorPoint(value) {\n this._anchorPoint = value;\n [this.xGizmo, this.yGizmo, this.zGizmo].forEach((gizmo) => {\n gizmo.anchorPoint = value;\n });\n }\n get anchorPoint() {\n return this._anchorPoint;\n }\n /**\n * Set the coordinate system to use. By default it's local.\n * But it's possible for a user to tweak so its local for translation and world for rotation.\n * In that case, setting the coordinate system will change `updateGizmoRotationToMatchAttachedMesh` and `updateGizmoPositionToMatchAttachedMesh`\n */\n set coordinatesMode(coordinatesMode) {\n [this.xGizmo, this.yGizmo, this.zGizmo].forEach((gizmo) => {\n gizmo.coordinatesMode = coordinatesMode;\n });\n }\n set updateScale(value) {\n if (this.xGizmo) {\n this.xGizmo.updateScale = value;\n this.yGizmo.updateScale = value;\n this.zGizmo.updateScale = value;\n }\n }\n get updateScale() {\n return this.xGizmo.updateScale;\n }\n /**\n * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)\n */\n set snapDistance(value) {\n if (this.xGizmo) {\n this.xGizmo.snapDistance = value;\n this.yGizmo.snapDistance = value;\n this.zGizmo.snapDistance = value;\n }\n }\n get snapDistance() {\n return this.xGizmo.snapDistance;\n }\n /**\n * Ratio for the scale of the gizmo (Default: 1)\n */\n set scaleRatio(value) {\n if (this.xGizmo) {\n this.xGizmo.scaleRatio = value;\n this.yGizmo.scaleRatio = value;\n this.zGizmo.scaleRatio = value;\n }\n }\n get scaleRatio() {\n return this.xGizmo.scaleRatio;\n }\n /**\n * Builds Gizmo Axis Cache to enable features such as hover state preservation and graying out other axis during manipulation\n * @param mesh Axis gizmo mesh\n * @param cache Gizmo axis definition used for reactive gizmo UI\n */\n addToAxisCache(mesh, cache) {\n this._gizmoAxisCache.set(mesh, cache);\n }\n /**\n * Disposes of the gizmo\n */\n dispose() {\n this.xGizmo.dispose();\n this.yGizmo.dispose();\n this.zGizmo.dispose();\n this.onDragStartObservable.clear();\n this.onDragEndObservable.clear();\n this._observables.forEach((obs) => {\n this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(obs);\n });\n }\n /**\n * CustomMeshes are not supported by this gizmo\n */\n setCustomMesh() {\n Logger.Error(\"Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)\");\n }\n}\n//# sourceMappingURL=rotationGizmo.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { TransformNode } from \"../Meshes/transformNode.js\";\nimport { CreatePlane } from \"../Meshes/Builders/planeBuilder.js\";\nimport { PointerDragBehavior } from \"../Behaviors/Meshes/pointerDragBehavior.js\";\nimport { Gizmo } from \"./gizmo.js\";\nimport { UtilityLayerRenderer } from \"../Rendering/utilityLayerRenderer.js\";\nimport { StandardMaterial } from \"../Materials/standardMaterial.js\";\n/**\n * Single plane drag gizmo\n */\nexport class PlaneDragGizmo extends Gizmo {\n /** Default material used to render when gizmo is not disabled or hovered */\n get coloredMaterial() {\n return this._coloredMaterial;\n }\n /** Material used to render when gizmo is hovered with mouse*/\n get hoverMaterial() {\n return this._hoverMaterial;\n }\n /** Material used to render when gizmo is disabled. typically grey.*/\n get disableMaterial() {\n return this._disableMaterial;\n }\n /**\n * @internal\n */\n static _CreatePlane(scene, material) {\n const plane = new TransformNode(\"plane\", scene);\n //make sure plane is double sided\n const dragPlane = CreatePlane(\"dragPlane\", { width: 0.1375, height: 0.1375, sideOrientation: 2 }, scene);\n dragPlane.material = material;\n dragPlane.parent = plane;\n return plane;\n }\n /**\n * Creates a PlaneDragGizmo\n * @param dragPlaneNormal The axis normal to which the gizmo will be able to drag on\n * @param color The color of the gizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n * @param parent\n */\n constructor(dragPlaneNormal, color = Color3.Gray(), gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer, parent = null) {\n var _a;\n super(gizmoLayer);\n this._pointerObserver = null;\n /**\n * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)\n */\n this.snapDistance = 0;\n /**\n * Event that fires each time the gizmo snaps to a new location.\n * * snapDistance is the the change in distance\n */\n this.onSnapObservable = new Observable();\n this._isEnabled = false;\n this._parent = null;\n this._dragging = false;\n this._parent = parent;\n // Create Material\n this._coloredMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._coloredMaterial.diffuseColor = color;\n this._coloredMaterial.specularColor = color.subtract(new Color3(0.1, 0.1, 0.1));\n this._hoverMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._hoverMaterial.diffuseColor = Color3.Yellow();\n this._disableMaterial = new StandardMaterial(\"\", gizmoLayer.utilityLayerScene);\n this._disableMaterial.diffuseColor = Color3.Gray();\n this._disableMaterial.alpha = 0.4;\n // Build plane mesh on root node\n this._gizmoMesh = PlaneDragGizmo._CreatePlane(gizmoLayer.utilityLayerScene, this._coloredMaterial);\n this._gizmoMesh.lookAt(this._rootMesh.position.add(dragPlaneNormal));\n this._gizmoMesh.scaling.scaleInPlace(1 / 3);\n this._gizmoMesh.parent = this._rootMesh;\n let currentSnapDragDistance = 0;\n const tmpVector = new Vector3();\n const tmpSnapEvent = { snapDistance: 0 };\n // Add dragPlaneNormal drag behavior to handle events when the gizmo is dragged\n this.dragBehavior = new PointerDragBehavior({ dragPlaneNormal: dragPlaneNormal });\n this.dragBehavior.moveAttached = false;\n this._rootMesh.addBehavior(this.dragBehavior);\n this.dragBehavior.onDragObservable.add((event) => {\n if (this.attachedNode) {\n this._handlePivot();\n // Keep world translation and use it to update world transform\n // if the node has parent, the local transform properties (position, rotation, scale)\n // will be recomputed in _matrixChanged function\n // Snapping logic\n if (this.snapDistance == 0) {\n this.attachedNode.getWorldMatrix().addTranslationFromFloats(event.delta.x, event.delta.y, event.delta.z);\n }\n else {\n currentSnapDragDistance += event.dragDistance;\n if (Math.abs(currentSnapDragDistance) > this.snapDistance) {\n const dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / this.snapDistance);\n currentSnapDragDistance = currentSnapDragDistance % this.snapDistance;\n event.delta.normalizeToRef(tmpVector);\n tmpVector.scaleInPlace(this.snapDistance * dragSteps);\n this.attachedNode.getWorldMatrix().addTranslationFromFloats(tmpVector.x, tmpVector.y, tmpVector.z);\n tmpSnapEvent.snapDistance = this.snapDistance * dragSteps;\n this.onSnapObservable.notifyObservers(tmpSnapEvent);\n }\n }\n this._matrixChanged();\n }\n });\n this.dragBehavior.onDragStartObservable.add(() => {\n this._dragging = true;\n });\n this.dragBehavior.onDragEndObservable.add(() => {\n this._dragging = false;\n });\n const light = gizmoLayer._getSharedGizmoLight();\n light.includedOnlyMeshes = light.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(false));\n const cache = {\n gizmoMeshes: this._gizmoMesh.getChildMeshes(),\n colliderMeshes: this._gizmoMesh.getChildMeshes(),\n material: this._coloredMaterial,\n hoverMaterial: this._hoverMaterial,\n disableMaterial: this._disableMaterial,\n active: false,\n dragBehavior: this.dragBehavior,\n };\n (_a = this._parent) === null || _a === void 0 ? void 0 : _a.addToAxisCache(this._gizmoMesh, cache);\n this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add((pointerInfo) => {\n var _a;\n if (this._customMeshSet) {\n return;\n }\n this._isHovered = !!(cache.colliderMeshes.indexOf((_a = pointerInfo === null || pointerInfo === void 0 ? void 0 : pointerInfo.pickInfo) === null || _a === void 0 ? void 0 : _a.pickedMesh) != -1);\n if (!this._parent) {\n const material = cache.dragBehavior.enabled ? (this._isHovered || this._dragging ? this._hoverMaterial : this._coloredMaterial) : this._disableMaterial;\n this._setGizmoMeshMaterial(cache.gizmoMeshes, material);\n }\n });\n this.dragBehavior.onEnabledObservable.add((newState) => {\n this._setGizmoMeshMaterial(cache.gizmoMeshes, newState ? this._coloredMaterial : this._disableMaterial);\n });\n }\n _attachedNodeChanged(value) {\n if (this.dragBehavior) {\n this.dragBehavior.enabled = value ? true : false;\n }\n }\n /**\n * If the gizmo is enabled\n */\n set isEnabled(value) {\n this._isEnabled = value;\n if (!value) {\n this.attachedNode = null;\n }\n else {\n if (this._parent) {\n this.attachedNode = this._parent.attachedNode;\n }\n }\n }\n get isEnabled() {\n return this._isEnabled;\n }\n /**\n * Disposes of the gizmo\n */\n dispose() {\n this.onSnapObservable.clear();\n this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);\n this.dragBehavior.detach();\n super.dispose();\n if (this._gizmoMesh) {\n this._gizmoMesh.dispose();\n }\n [this._coloredMaterial, this._hoverMaterial, this._disableMaterial].forEach((matl) => {\n if (matl) {\n matl.dispose();\n }\n });\n }\n}\n//# sourceMappingURL=planeDragGizmo.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { Gizmo } from \"./gizmo.js\";\nimport { AxisDragGizmo } from \"./axisDragGizmo.js\";\nimport { PlaneDragGizmo } from \"./planeDragGizmo.js\";\nimport { UtilityLayerRenderer } from \"../Rendering/utilityLayerRenderer.js\";\n/**\n * Gizmo that enables dragging a mesh along 3 axis\n */\nexport class PositionGizmo extends Gizmo {\n get attachedMesh() {\n return this._meshAttached;\n }\n set attachedMesh(mesh) {\n this._meshAttached = mesh;\n this._nodeAttached = mesh;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => {\n if (gizmo.isEnabled) {\n gizmo.attachedMesh = mesh;\n }\n else {\n gizmo.attachedMesh = null;\n }\n });\n }\n get attachedNode() {\n return this._nodeAttached;\n }\n set attachedNode(node) {\n this._meshAttached = null;\n this._nodeAttached = node;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => {\n if (gizmo.isEnabled) {\n gizmo.attachedNode = node;\n }\n else {\n gizmo.attachedNode = null;\n }\n });\n }\n /**\n * True when the mouse pointer is hovering a gizmo mesh\n */\n get isHovered() {\n let hovered = false;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => {\n hovered = hovered || gizmo.isHovered;\n });\n return hovered;\n }\n /**\n * Creates a PositionGizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n @param thickness display gizmo axis thickness\n * @param gizmoManager\n */\n constructor(gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer, thickness = 1, gizmoManager) {\n super(gizmoLayer);\n /**\n * protected variables\n */\n this._meshAttached = null;\n this._nodeAttached = null;\n this._observables = [];\n /** Node Caching for quick lookup */\n this._gizmoAxisCache = new Map();\n /** Fires an event when any of it's sub gizmos are dragged */\n this.onDragStartObservable = new Observable();\n /** Fires an event when any of it's sub gizmos are released from dragging */\n this.onDragEndObservable = new Observable();\n /**\n * If set to true, planar drag is enabled\n */\n this._planarGizmoEnabled = false;\n this.xGizmo = new AxisDragGizmo(new Vector3(1, 0, 0), Color3.Red().scale(0.5), gizmoLayer, this, thickness);\n this.yGizmo = new AxisDragGizmo(new Vector3(0, 1, 0), Color3.Green().scale(0.5), gizmoLayer, this, thickness);\n this.zGizmo = new AxisDragGizmo(new Vector3(0, 0, 1), Color3.Blue().scale(0.5), gizmoLayer, this, thickness);\n this.xPlaneGizmo = new PlaneDragGizmo(new Vector3(1, 0, 0), Color3.Red().scale(0.5), this.gizmoLayer, this);\n this.yPlaneGizmo = new PlaneDragGizmo(new Vector3(0, 1, 0), Color3.Green().scale(0.5), this.gizmoLayer, this);\n this.zPlaneGizmo = new PlaneDragGizmo(new Vector3(0, 0, 1), Color3.Blue().scale(0.5), this.gizmoLayer, this);\n // Relay drag events\n [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => {\n gizmo.dragBehavior.onDragStartObservable.add(() => {\n this.onDragStartObservable.notifyObservers({});\n });\n gizmo.dragBehavior.onDragEndObservable.add(() => {\n this.onDragEndObservable.notifyObservers({});\n });\n });\n this.attachedMesh = null;\n if (gizmoManager) {\n gizmoManager.addToAxisCache(this._gizmoAxisCache);\n }\n else {\n // Only subscribe to pointer event if gizmoManager isnt\n Gizmo.GizmoAxisPointerObserver(gizmoLayer, this._gizmoAxisCache);\n }\n }\n /**\n * If the planar drag gizmo is enabled\n * setting this will enable/disable XY, XZ and YZ planes regardless of individual gizmo settings.\n */\n set planarGizmoEnabled(value) {\n this._planarGizmoEnabled = value;\n [this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.isEnabled = value;\n if (value) {\n if (gizmo.attachedMesh) {\n gizmo.attachedMesh = this.attachedMesh;\n }\n else {\n gizmo.attachedNode = this.attachedNode;\n }\n }\n }\n }, this);\n }\n get planarGizmoEnabled() {\n return this._planarGizmoEnabled;\n }\n /**\n * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)\n * NOTE: This is only possible for meshes with uniform scaling, as otherwise it's not possible to decompose the rotation\n */\n set updateGizmoRotationToMatchAttachedMesh(value) {\n this._updateGizmoRotationToMatchAttachedMesh = value;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.updateGizmoRotationToMatchAttachedMesh = value;\n }\n });\n }\n get updateGizmoRotationToMatchAttachedMesh() {\n return this._updateGizmoRotationToMatchAttachedMesh;\n }\n set updateGizmoPositionToMatchAttachedMesh(value) {\n this._updateGizmoPositionToMatchAttachedMesh = value;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.updateGizmoPositionToMatchAttachedMesh = value;\n }\n });\n }\n get updateGizmoPositionToMatchAttachedMesh() {\n return this._updateGizmoPositionToMatchAttachedMesh;\n }\n set anchorPoint(value) {\n this._anchorPoint = value;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => {\n gizmo.anchorPoint = value;\n });\n }\n get anchorPoint() {\n return this._anchorPoint;\n }\n /**\n * Set the coordinate system to use. By default it's local.\n * But it's possible for a user to tweak so its local for translation and world for rotation.\n * In that case, setting the coordinate system will change `updateGizmoRotationToMatchAttachedMesh` and `updateGizmoPositionToMatchAttachedMesh`\n */\n set coordinatesMode(coordinatesMode) {\n [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => {\n gizmo.coordinatesMode = coordinatesMode;\n });\n }\n set updateScale(value) {\n if (this.xGizmo) {\n this.xGizmo.updateScale = value;\n this.yGizmo.updateScale = value;\n this.zGizmo.updateScale = value;\n }\n }\n get updateScale() {\n return this.xGizmo.updateScale;\n }\n /**\n * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)\n */\n set snapDistance(value) {\n this._snapDistance = value;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.snapDistance = value;\n }\n });\n }\n get snapDistance() {\n return this._snapDistance;\n }\n /**\n * Ratio for the scale of the gizmo (Default: 1)\n */\n set scaleRatio(value) {\n this._scaleRatio = value;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.scaleRatio = value;\n }\n });\n }\n get scaleRatio() {\n return this._scaleRatio;\n }\n /**\n * Builds Gizmo Axis Cache to enable features such as hover state preservation and graying out other axis during manipulation\n * @param mesh Axis gizmo mesh\n * @param cache Gizmo axis definition used for reactive gizmo UI\n */\n addToAxisCache(mesh, cache) {\n this._gizmoAxisCache.set(mesh, cache);\n }\n /**\n * Disposes of the gizmo\n */\n dispose() {\n [this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.dispose();\n }\n });\n this._observables.forEach((obs) => {\n this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(obs);\n });\n this.onDragStartObservable.clear();\n this.onDragEndObservable.clear();\n }\n /**\n * CustomMeshes are not supported by this gizmo\n */\n setCustomMesh() {\n Logger.Error(\"Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo,gizmo.xPlaneGizmo, gizmo.yPlaneGizmo, gizmo.zPlaneGizmo)\");\n }\n}\n//# sourceMappingURL=positionGizmo.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { CreatePolyhedron } from \"../Meshes/Builders/polyhedronBuilder.js\";\nimport { Gizmo } from \"./gizmo.js\";\nimport { AxisScaleGizmo } from \"./axisScaleGizmo.js\";\nimport { UtilityLayerRenderer } from \"../Rendering/utilityLayerRenderer.js\";\nimport { StandardMaterial } from \"../Materials/standardMaterial.js\";\n/**\n * Gizmo that enables scaling a mesh along 3 axis\n */\nexport class ScaleGizmo extends Gizmo {\n /** Default material used to render when gizmo is not disabled or hovered */\n get coloredMaterial() {\n return this._coloredMaterial;\n }\n /** Material used to render when gizmo is hovered with mouse*/\n get hoverMaterial() {\n return this._hoverMaterial;\n }\n /** Material used to render when gizmo is disabled. typically grey.*/\n get disableMaterial() {\n return this._disableMaterial;\n }\n get attachedMesh() {\n return this._meshAttached;\n }\n set attachedMesh(mesh) {\n this._meshAttached = mesh;\n this._nodeAttached = mesh;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => {\n if (gizmo.isEnabled) {\n gizmo.attachedMesh = mesh;\n }\n else {\n gizmo.attachedMesh = null;\n }\n });\n }\n get attachedNode() {\n return this._nodeAttached;\n }\n set attachedNode(node) {\n this._meshAttached = null;\n this._nodeAttached = node;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => {\n if (gizmo.isEnabled) {\n gizmo.attachedNode = node;\n }\n else {\n gizmo.attachedNode = null;\n }\n });\n }\n set updateScale(value) {\n if (this.xGizmo) {\n this.xGizmo.updateScale = value;\n this.yGizmo.updateScale = value;\n this.zGizmo.updateScale = value;\n }\n }\n get updateScale() {\n return this.xGizmo.updateScale;\n }\n /**\n * True when the mouse pointer is hovering a gizmo mesh\n */\n get isHovered() {\n let hovered = false;\n [this.xGizmo, this.yGizmo, this.zGizmo].forEach((gizmo) => {\n hovered = hovered || gizmo.isHovered;\n });\n return hovered;\n }\n /**\n * Creates a ScaleGizmo\n * @param gizmoLayer The utility layer the gizmo will be added to\n * @param thickness display gizmo axis thickness\n * @param gizmoManager\n */\n constructor(gizmoLayer = UtilityLayerRenderer.DefaultUtilityLayer, thickness = 1, gizmoManager) {\n super(gizmoLayer);\n this._meshAttached = null;\n this._nodeAttached = null;\n this._sensitivity = 1;\n this._observables = [];\n /** Node Caching for quick lookup */\n this._gizmoAxisCache = new Map();\n /** Fires an event when any of it's sub gizmos are dragged */\n this.onDragStartObservable = new Observable();\n /** Fires an event when any of it's sub gizmos are released from dragging */\n this.onDragEndObservable = new Observable();\n this.uniformScaleGizmo = this._createUniformScaleMesh();\n this.xGizmo = new AxisScaleGizmo(new Vector3(1, 0, 0), Color3.Red().scale(0.5), gizmoLayer, this, thickness);\n this.yGizmo = new AxisScaleGizmo(new Vector3(0, 1, 0), Color3.Green().scale(0.5), gizmoLayer, this, thickness);\n this.zGizmo = new AxisScaleGizmo(new Vector3(0, 0, 1), Color3.Blue().scale(0.5), gizmoLayer, this, thickness);\n // Relay drag events\n [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => {\n gizmo.dragBehavior.onDragStartObservable.add(() => {\n this.onDragStartObservable.notifyObservers({});\n });\n gizmo.dragBehavior.onDragEndObservable.add(() => {\n this.onDragEndObservable.notifyObservers({});\n });\n });\n this.attachedMesh = null;\n this.attachedNode = null;\n if (gizmoManager) {\n gizmoManager.addToAxisCache(this._gizmoAxisCache);\n }\n else {\n // Only subscribe to pointer event if gizmoManager isnt\n Gizmo.GizmoAxisPointerObserver(gizmoLayer, this._gizmoAxisCache);\n }\n }\n /** Create Geometry for Gizmo */\n _createUniformScaleMesh() {\n this._coloredMaterial = new StandardMaterial(\"\", this.gizmoLayer.utilityLayerScene);\n this._coloredMaterial.diffuseColor = Color3.Gray();\n this._hoverMaterial = new StandardMaterial(\"\", this.gizmoLayer.utilityLayerScene);\n this._hoverMaterial.diffuseColor = Color3.Yellow();\n this._disableMaterial = new StandardMaterial(\"\", this.gizmoLayer.utilityLayerScene);\n this._disableMaterial.diffuseColor = Color3.Gray();\n this._disableMaterial.alpha = 0.4;\n const uniformScaleGizmo = new AxisScaleGizmo(new Vector3(0, 1, 0), Color3.Gray().scale(0.5), this.gizmoLayer, this);\n uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;\n uniformScaleGizmo.uniformScaling = true;\n this._uniformScalingMesh = CreatePolyhedron(\"uniform\", { type: 1 }, uniformScaleGizmo.gizmoLayer.utilityLayerScene);\n this._uniformScalingMesh.scaling.scaleInPlace(0.01);\n this._uniformScalingMesh.visibility = 0;\n this._octahedron = CreatePolyhedron(\"\", { type: 1 }, uniformScaleGizmo.gizmoLayer.utilityLayerScene);\n this._octahedron.scaling.scaleInPlace(0.007);\n this._uniformScalingMesh.addChild(this._octahedron);\n uniformScaleGizmo.setCustomMesh(this._uniformScalingMesh, true);\n const light = this.gizmoLayer._getSharedGizmoLight();\n light.includedOnlyMeshes = light.includedOnlyMeshes.concat(this._octahedron);\n const cache = {\n gizmoMeshes: [this._octahedron, this._uniformScalingMesh],\n colliderMeshes: [this._uniformScalingMesh],\n material: this._coloredMaterial,\n hoverMaterial: this._hoverMaterial,\n disableMaterial: this._disableMaterial,\n active: false,\n dragBehavior: uniformScaleGizmo.dragBehavior,\n };\n this.addToAxisCache(uniformScaleGizmo._rootMesh, cache);\n return uniformScaleGizmo;\n }\n set updateGizmoRotationToMatchAttachedMesh(value) {\n if (!value) {\n Logger.Warn(\"Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.\");\n }\n else {\n this._updateGizmoRotationToMatchAttachedMesh = value;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.updateGizmoRotationToMatchAttachedMesh = value;\n }\n });\n }\n }\n get updateGizmoRotationToMatchAttachedMesh() {\n return this._updateGizmoRotationToMatchAttachedMesh;\n }\n set anchorPoint(value) {\n this._anchorPoint = value;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.anchorPoint = value;\n }\n });\n }\n get anchorPoint() {\n return this._anchorPoint;\n }\n /**\n * Set the coordinate system to use. By default it's local.\n * But it's possible for a user to tweak so its local for translation and world for rotation.\n * In that case, setting the coordinate system will change `updateGizmoRotationToMatchAttachedMesh` and `updateGizmoPositionToMatchAttachedMesh`\n */\n set coordinatesMode(coordinatesMode) {\n [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => {\n gizmo.coordinatesMode = coordinatesMode;\n });\n }\n /**\n * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)\n */\n set snapDistance(value) {\n this._snapDistance = value;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.snapDistance = value;\n }\n });\n }\n get snapDistance() {\n return this._snapDistance;\n }\n /**\n * Ratio for the scale of the gizmo (Default: 1)\n */\n set scaleRatio(value) {\n this._scaleRatio = value;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.scaleRatio = value;\n }\n });\n }\n get scaleRatio() {\n return this._scaleRatio;\n }\n /**\n * Sensitivity factor for dragging (Default: 1)\n */\n set sensitivity(value) {\n this._sensitivity = value;\n [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.sensitivity = value;\n }\n });\n }\n get sensitivity() {\n return this._sensitivity;\n }\n /**\n * Builds Gizmo Axis Cache to enable features such as hover state preservation and graying out other axis during manipulation\n * @param mesh Axis gizmo mesh\n * @param cache Gizmo axis definition used for reactive gizmo UI\n */\n addToAxisCache(mesh, cache) {\n this._gizmoAxisCache.set(mesh, cache);\n }\n /**\n * Disposes of the gizmo\n */\n dispose() {\n [this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.dispose();\n }\n });\n this._observables.forEach((obs) => {\n this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(obs);\n });\n this.onDragStartObservable.clear();\n this.onDragEndObservable.clear();\n [this._uniformScalingMesh, this._octahedron].forEach((msh) => {\n if (msh) {\n msh.dispose();\n }\n });\n [this._coloredMaterial, this._hoverMaterial, this._disableMaterial].forEach((matl) => {\n if (matl) {\n matl.dispose();\n }\n });\n }\n}\n//# sourceMappingURL=scaleGizmo.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { PointerEventTypes } from \"../Events/pointerEvents.js\";\nimport { AbstractMesh } from \"../Meshes/abstractMesh.js\";\nimport { UtilityLayerRenderer } from \"../Rendering/utilityLayerRenderer.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { SixDofDragBehavior } from \"../Behaviors/Meshes/sixDofDragBehavior.js\";\nimport { Gizmo, GizmoCoordinatesMode } from \"./gizmo.js\";\nimport { RotationGizmo } from \"./rotationGizmo.js\";\nimport { PositionGizmo } from \"./positionGizmo.js\";\nimport { ScaleGizmo } from \"./scaleGizmo.js\";\nimport { BoundingBoxGizmo } from \"./boundingBoxGizmo.js\";\n/**\n * Helps setup gizmo's in the scene to rotate/scale/position nodes\n */\nexport class GizmoManager {\n /**\n * Utility layer that the bounding box gizmo belongs to\n */\n get keepDepthUtilityLayer() {\n return this._defaultKeepDepthUtilityLayer;\n }\n /**\n * Utility layer that all gizmos besides bounding box belong to\n */\n get utilityLayer() {\n return this._defaultUtilityLayer;\n }\n /**\n * True when the mouse pointer is hovering a gizmo mesh\n */\n get isHovered() {\n let hovered = false;\n for (const key in this.gizmos) {\n const gizmo = this.gizmos[key];\n if (gizmo && gizmo.isHovered) {\n hovered = true;\n break;\n }\n }\n return hovered;\n }\n /**\n * Ratio for the scale of the gizmo (Default: 1)\n */\n set scaleRatio(value) {\n this._scaleRatio = value;\n [this.gizmos.positionGizmo, this.gizmos.rotationGizmo, this.gizmos.scaleGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.scaleRatio = value;\n }\n });\n }\n get scaleRatio() {\n return this._scaleRatio;\n }\n /**\n * Set the coordinate system to use. By default it's local.\n * But it's possible for a user to tweak so its local for translation and world for rotation.\n * In that case, setting the coordinate system will change `updateGizmoRotationToMatchAttachedMesh` and `updateGizmoPositionToMatchAttachedMesh`\n */\n set coordinatesMode(coordinatesMode) {\n this._coordinatesMode = coordinatesMode;\n [this.gizmos.positionGizmo, this.gizmos.rotationGizmo, this.gizmos.scaleGizmo].forEach((gizmo) => {\n if (gizmo) {\n gizmo.coordinatesMode = coordinatesMode;\n }\n });\n }\n get coordinatesMode() {\n return this._coordinatesMode;\n }\n /**\n * Instantiates a gizmo manager\n * @param _scene the scene to overlay the gizmos on top of\n * @param thickness display gizmo axis thickness\n * @param utilityLayer the layer where gizmos are rendered\n * @param keepDepthUtilityLayer the layer where occluded gizmos are rendered\n */\n constructor(_scene, thickness = 1, utilityLayer = UtilityLayerRenderer.DefaultUtilityLayer, keepDepthUtilityLayer = UtilityLayerRenderer.DefaultKeepDepthUtilityLayer) {\n this._scene = _scene;\n /** When true, the gizmo will be detached from the current object when a pointer down occurs with an empty picked mesh */\n this.clearGizmoOnEmptyPointerEvent = false;\n /** When true (default), picking to attach a new mesh is enabled. This works in sync with inspector autopicking. */\n this.enableAutoPicking = true;\n /** Fires an event when the manager is attached to a mesh */\n this.onAttachedToMeshObservable = new Observable();\n /** Fires an event when the manager is attached to a node */\n this.onAttachedToNodeObservable = new Observable();\n this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };\n this._pointerObservers = [];\n this._attachedMesh = null;\n this._attachedNode = null;\n this._boundingBoxColor = Color3.FromHexString(\"#0984e3\");\n this._thickness = 1;\n this._scaleRatio = 1;\n this._coordinatesMode = GizmoCoordinatesMode.Local;\n /** Node Caching for quick lookup */\n this._gizmoAxisCache = new Map();\n /**\n * When bounding box gizmo is enabled, this can be used to track drag/end events\n */\n this.boundingBoxDragBehavior = new SixDofDragBehavior();\n /**\n * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)\n */\n this.attachableMeshes = null;\n /**\n * Array of nodes which will have the gizmo attached when a pointer selected them. If null, all nodes are attachable. (Default: null)\n */\n this.attachableNodes = null;\n /**\n * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh/attachToNode. (Default: true)\n */\n this.usePointerToAttachGizmos = true;\n this._defaultUtilityLayer = utilityLayer;\n this._defaultKeepDepthUtilityLayer = keepDepthUtilityLayer;\n this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;\n this._thickness = thickness;\n this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };\n const attachToMeshPointerObserver = this._attachToMeshPointerObserver(_scene);\n const gizmoAxisPointerObserver = Gizmo.GizmoAxisPointerObserver(this._defaultUtilityLayer, this._gizmoAxisCache);\n this._pointerObservers = [attachToMeshPointerObserver, gizmoAxisPointerObserver];\n }\n /**\n * Subscribes to pointer down events, for attaching and detaching mesh\n * @param scene The scene layer the observer will be added to\n */\n _attachToMeshPointerObserver(scene) {\n // Instantiate/dispose gizmos based on pointer actions\n const pointerObserver = scene.onPointerObservable.add((pointerInfo) => {\n if (!this.usePointerToAttachGizmos) {\n return;\n }\n if (pointerInfo.type == PointerEventTypes.POINTERDOWN) {\n if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {\n if (this.enableAutoPicking) {\n let node = pointerInfo.pickInfo.pickedMesh;\n if (this.attachableMeshes == null) {\n // Attach to the most parent node\n while (node && node.parent != null) {\n node = node.parent;\n }\n }\n else {\n // Attach to the parent node that is an attachableMesh\n let found = false;\n this.attachableMeshes.forEach((mesh) => {\n if (node && (node == mesh || node.isDescendantOf(mesh))) {\n node = mesh;\n found = true;\n }\n });\n if (!found) {\n node = null;\n }\n }\n if (node instanceof AbstractMesh) {\n if (this._attachedMesh != node) {\n this.attachToMesh(node);\n }\n }\n else {\n if (this.clearGizmoOnEmptyPointerEvent) {\n this.attachToMesh(null);\n }\n }\n }\n }\n else {\n if (this.clearGizmoOnEmptyPointerEvent) {\n this.attachToMesh(null);\n }\n }\n }\n });\n return pointerObserver;\n }\n /**\n * Attaches a set of gizmos to the specified mesh\n * @param mesh The mesh the gizmo's should be attached to\n */\n attachToMesh(mesh) {\n if (this._attachedMesh) {\n this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);\n }\n if (this._attachedNode) {\n this._attachedNode.removeBehavior(this.boundingBoxDragBehavior);\n }\n this._attachedMesh = mesh;\n this._attachedNode = null;\n for (const key in this.gizmos) {\n const gizmo = this.gizmos[key];\n if (gizmo && this._gizmosEnabled[key]) {\n gizmo.attachedMesh = mesh;\n }\n }\n if (this.boundingBoxGizmoEnabled && this._attachedMesh) {\n this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);\n }\n this.onAttachedToMeshObservable.notifyObservers(mesh);\n }\n /**\n * Attaches a set of gizmos to the specified node\n * @param node The node the gizmo's should be attached to\n */\n attachToNode(node) {\n if (this._attachedMesh) {\n this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);\n }\n if (this._attachedNode) {\n this._attachedNode.removeBehavior(this.boundingBoxDragBehavior);\n }\n this._attachedMesh = null;\n this._attachedNode = node;\n for (const key in this.gizmos) {\n const gizmo = this.gizmos[key];\n if (gizmo && this._gizmosEnabled[key]) {\n gizmo.attachedNode = node;\n }\n }\n if (this.boundingBoxGizmoEnabled && this._attachedNode) {\n this._attachedNode.addBehavior(this.boundingBoxDragBehavior);\n }\n this.onAttachedToNodeObservable.notifyObservers(node);\n }\n /**\n * If the position gizmo is enabled\n */\n set positionGizmoEnabled(value) {\n if (value) {\n if (!this.gizmos.positionGizmo) {\n this.gizmos.positionGizmo = new PositionGizmo(this._defaultUtilityLayer, this._thickness, this);\n }\n if (this._attachedNode) {\n this.gizmos.positionGizmo.attachedNode = this._attachedNode;\n }\n else {\n this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;\n }\n }\n else if (this.gizmos.positionGizmo) {\n this.gizmos.positionGizmo.attachedNode = null;\n }\n this._gizmosEnabled.positionGizmo = value;\n }\n get positionGizmoEnabled() {\n return this._gizmosEnabled.positionGizmo;\n }\n /**\n * If the rotation gizmo is enabled\n */\n set rotationGizmoEnabled(value) {\n if (value) {\n if (!this.gizmos.rotationGizmo) {\n this.gizmos.rotationGizmo = new RotationGizmo(this._defaultUtilityLayer, 32, false, this._thickness, this);\n }\n if (this._attachedNode) {\n this.gizmos.rotationGizmo.attachedNode = this._attachedNode;\n }\n else {\n this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;\n }\n }\n else if (this.gizmos.rotationGizmo) {\n this.gizmos.rotationGizmo.attachedNode = null;\n }\n this._gizmosEnabled.rotationGizmo = value;\n }\n get rotationGizmoEnabled() {\n return this._gizmosEnabled.rotationGizmo;\n }\n /**\n * If the scale gizmo is enabled\n */\n set scaleGizmoEnabled(value) {\n if (value) {\n this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new ScaleGizmo(this._defaultUtilityLayer, this._thickness, this);\n if (this._attachedNode) {\n this.gizmos.scaleGizmo.attachedNode = this._attachedNode;\n }\n else {\n this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;\n }\n }\n else if (this.gizmos.scaleGizmo) {\n this.gizmos.scaleGizmo.attachedNode = null;\n }\n this._gizmosEnabled.scaleGizmo = value;\n }\n get scaleGizmoEnabled() {\n return this._gizmosEnabled.scaleGizmo;\n }\n /**\n * If the boundingBox gizmo is enabled\n */\n set boundingBoxGizmoEnabled(value) {\n if (value) {\n this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BoundingBoxGizmo(this._boundingBoxColor, this._defaultKeepDepthUtilityLayer);\n if (this._attachedMesh) {\n this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;\n }\n else {\n this.gizmos.boundingBoxGizmo.attachedNode = this._attachedNode;\n }\n if (this._attachedMesh) {\n this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);\n this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);\n }\n else if (this._attachedNode) {\n this._attachedNode.removeBehavior(this.boundingBoxDragBehavior);\n this._attachedNode.addBehavior(this.boundingBoxDragBehavior);\n }\n }\n else if (this.gizmos.boundingBoxGizmo) {\n if (this._attachedMesh) {\n this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);\n }\n else if (this._attachedNode) {\n this._attachedNode.removeBehavior(this.boundingBoxDragBehavior);\n }\n this.gizmos.boundingBoxGizmo.attachedNode = null;\n }\n this._gizmosEnabled.boundingBoxGizmo = value;\n }\n get boundingBoxGizmoEnabled() {\n return this._gizmosEnabled.boundingBoxGizmo;\n }\n /**\n * Builds Gizmo Axis Cache to enable features such as hover state preservation and graying out other axis during manipulation\n * @param gizmoAxisCache Gizmo axis definition used for reactive gizmo UI\n */\n addToAxisCache(gizmoAxisCache) {\n if (gizmoAxisCache.size > 0) {\n gizmoAxisCache.forEach((v, k) => {\n this._gizmoAxisCache.set(k, v);\n });\n }\n }\n /**\n * Disposes of the gizmo manager\n */\n dispose() {\n var _a, _b;\n this._pointerObservers.forEach((observer) => {\n this._scene.onPointerObservable.remove(observer);\n });\n for (const key in this.gizmos) {\n const gizmo = this.gizmos[key];\n if (gizmo) {\n gizmo.dispose();\n }\n }\n if (this._defaultKeepDepthUtilityLayer !== UtilityLayerRenderer._DefaultKeepDepthUtilityLayer) {\n (_a = this._defaultKeepDepthUtilityLayer) === null || _a === void 0 ? void 0 : _a.dispose();\n }\n if (this._defaultUtilityLayer !== UtilityLayerRenderer._DefaultUtilityLayer) {\n (_b = this._defaultUtilityLayer) === null || _b === void 0 ? void 0 : _b.dispose();\n }\n this.boundingBoxDragBehavior.detach();\n this.onAttachedToMeshObservable.clear();\n }\n}\n//# sourceMappingURL=gizmoManager.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize, serializeAsTexture } from \"../Misc/decorators.js\";\nimport { Matrix, Vector3 } from \"../Maths/math.vector.js\";\nimport { Node } from \"../node.js\";\nimport { Light } from \"./light.js\";\nimport { ShadowLight } from \"./shadowLight.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nNode.AddNodeConstructor(\"Light_Type_2\", (name, scene) => {\n return () => new SpotLight(name, Vector3.Zero(), Vector3.Zero(), 0, 0, scene);\n});\n/**\n * A spot light is defined by a position, a direction, an angle, and an exponent.\n * These values define a cone of light starting from the position, emitting toward the direction.\n * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,\n * and the exponent defines the speed of the decay of the light with distance (reach).\n * Documentation: https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction\n */\nexport class SpotLight extends ShadowLight {\n /**\n * Gets the cone angle of the spot light in Radians.\n */\n get angle() {\n return this._angle;\n }\n /**\n * Sets the cone angle of the spot light in Radians.\n */\n set angle(value) {\n this._angle = value;\n this._cosHalfAngle = Math.cos(value * 0.5);\n this._projectionTextureProjectionLightDirty = true;\n this.forceProjectionMatrixCompute();\n this._computeAngleValues();\n }\n /**\n * Only used in gltf falloff mode, this defines the angle where\n * the directional falloff will start before cutting at angle which could be seen\n * as outer angle.\n */\n get innerAngle() {\n return this._innerAngle;\n }\n /**\n * Only used in gltf falloff mode, this defines the angle where\n * the directional falloff will start before cutting at angle which could be seen\n * as outer angle.\n */\n set innerAngle(value) {\n this._innerAngle = value;\n this._computeAngleValues();\n }\n /**\n * Allows scaling the angle of the light for shadow generation only.\n */\n get shadowAngleScale() {\n return this._shadowAngleScale;\n }\n /**\n * Allows scaling the angle of the light for shadow generation only.\n */\n set shadowAngleScale(value) {\n this._shadowAngleScale = value;\n this.forceProjectionMatrixCompute();\n }\n /**\n * Allows reading the projection texture\n */\n get projectionTextureMatrix() {\n return this._projectionTextureMatrix;\n }\n /**\n * Gets the near clip of the Spotlight for texture projection.\n */\n get projectionTextureLightNear() {\n return this._projectionTextureLightNear;\n }\n /**\n * Sets the near clip of the Spotlight for texture projection.\n */\n set projectionTextureLightNear(value) {\n this._projectionTextureLightNear = value;\n this._projectionTextureProjectionLightDirty = true;\n }\n /**\n * Gets the far clip of the Spotlight for texture projection.\n */\n get projectionTextureLightFar() {\n return this._projectionTextureLightFar;\n }\n /**\n * Sets the far clip of the Spotlight for texture projection.\n */\n set projectionTextureLightFar(value) {\n this._projectionTextureLightFar = value;\n this._projectionTextureProjectionLightDirty = true;\n }\n /**\n * Gets the Up vector of the Spotlight for texture projection.\n */\n get projectionTextureUpDirection() {\n return this._projectionTextureUpDirection;\n }\n /**\n * Sets the Up vector of the Spotlight for texture projection.\n */\n set projectionTextureUpDirection(value) {\n this._projectionTextureUpDirection = value;\n this._projectionTextureProjectionLightDirty = true;\n }\n /**\n * Gets the projection texture of the light.\n */\n get projectionTexture() {\n return this._projectionTexture;\n }\n /**\n * Sets the projection texture of the light.\n */\n set projectionTexture(value) {\n if (this._projectionTexture === value) {\n return;\n }\n this._projectionTexture = value;\n this._projectionTextureDirty = true;\n if (this._projectionTexture && !this._projectionTexture.isReady()) {\n if (SpotLight._IsProceduralTexture(this._projectionTexture)) {\n this._projectionTexture.getEffect().executeWhenCompiled(() => {\n this._markMeshesAsLightDirty();\n });\n }\n else if (SpotLight._IsTexture(this._projectionTexture)) {\n this._projectionTexture.onLoadObservable.addOnce(() => {\n this._markMeshesAsLightDirty();\n });\n }\n }\n }\n static _IsProceduralTexture(texture) {\n return texture.onGeneratedObservable !== undefined;\n }\n static _IsTexture(texture) {\n return texture.onLoadObservable !== undefined;\n }\n /**\n * Gets or sets the light projection matrix as used by the projection texture\n */\n get projectionTextureProjectionLightMatrix() {\n return this._projectionTextureProjectionLightMatrix;\n }\n set projectionTextureProjectionLightMatrix(projection) {\n this._projectionTextureProjectionLightMatrix = projection;\n this._projectionTextureProjectionLightDirty = false;\n this._projectionTextureDirty = true;\n }\n /**\n * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.\n * It can cast shadows.\n * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction\n * @param name The light friendly name\n * @param position The position of the spot light in the scene\n * @param direction The direction of the light in the scene\n * @param angle The cone angle of the light in Radians\n * @param exponent The light decay speed with the distance from the emission spot\n * @param scene The scene the lights belongs to\n */\n constructor(name, position, direction, angle, exponent, scene) {\n super(name, scene);\n this._innerAngle = 0;\n this._projectionTextureMatrix = Matrix.Zero();\n this._projectionTextureLightNear = 1e-6;\n this._projectionTextureLightFar = 1000.0;\n this._projectionTextureUpDirection = Vector3.Up();\n this._projectionTextureViewLightDirty = true;\n this._projectionTextureProjectionLightDirty = true;\n this._projectionTextureDirty = true;\n this._projectionTextureViewTargetVector = Vector3.Zero();\n this._projectionTextureViewLightMatrix = Matrix.Zero();\n this._projectionTextureProjectionLightMatrix = Matrix.Zero();\n this._projectionTextureScalingMatrix = Matrix.FromValues(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);\n this.position = position;\n this.direction = direction;\n this.angle = angle;\n this.exponent = exponent;\n }\n /**\n * Returns the string \"SpotLight\".\n * @returns the class name\n */\n getClassName() {\n return \"SpotLight\";\n }\n /**\n * Returns the integer 2.\n * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x\n */\n getTypeID() {\n return Light.LIGHTTYPEID_SPOTLIGHT;\n }\n /**\n * Overrides the direction setter to recompute the projection texture view light Matrix.\n * @param value\n */\n _setDirection(value) {\n super._setDirection(value);\n this._projectionTextureViewLightDirty = true;\n }\n /**\n * Overrides the position setter to recompute the projection texture view light Matrix.\n * @param value\n */\n _setPosition(value) {\n super._setPosition(value);\n this._projectionTextureViewLightDirty = true;\n }\n /**\n * Sets the passed matrix \"matrix\" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0.\n * Returns the SpotLight.\n * @param matrix\n * @param viewMatrix\n * @param renderList\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList) {\n const activeCamera = this.getScene().activeCamera;\n if (!activeCamera) {\n return;\n }\n this._shadowAngleScale = this._shadowAngleScale || 1;\n const angle = this._shadowAngleScale * this._angle;\n const minZ = this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;\n const maxZ = this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;\n const useReverseDepthBuffer = this.getScene().getEngine().useReverseDepthBuffer;\n Matrix.PerspectiveFovLHToRef(angle, 1.0, useReverseDepthBuffer ? maxZ : minZ, useReverseDepthBuffer ? minZ : maxZ, matrix, true, this._scene.getEngine().isNDCHalfZRange, undefined, useReverseDepthBuffer);\n }\n _computeProjectionTextureViewLightMatrix() {\n this._projectionTextureViewLightDirty = false;\n this._projectionTextureDirty = true;\n this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);\n Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);\n }\n _computeProjectionTextureProjectionLightMatrix() {\n this._projectionTextureProjectionLightDirty = false;\n this._projectionTextureDirty = true;\n const lightFar = this.projectionTextureLightFar;\n const lightNear = this.projectionTextureLightNear;\n const P = lightFar / (lightFar - lightNear);\n const Q = -P * lightNear;\n const S = 1.0 / Math.tan(this._angle / 2.0);\n const A = 1.0;\n Matrix.FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, this._projectionTextureProjectionLightMatrix);\n }\n /**\n * Main function for light texture projection matrix computing.\n */\n _computeProjectionTextureMatrix() {\n this._projectionTextureDirty = false;\n this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);\n if (this._projectionTexture instanceof Texture) {\n const u = this._projectionTexture.uScale / 2.0;\n const v = this._projectionTexture.vScale / 2.0;\n Matrix.FromValuesToRef(u, 0.0, 0.0, 0.0, 0.0, v, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0, this._projectionTextureScalingMatrix);\n }\n this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);\n }\n _buildUniformLayout() {\n this._uniformBuffer.addUniform(\"vLightData\", 4);\n this._uniformBuffer.addUniform(\"vLightDiffuse\", 4);\n this._uniformBuffer.addUniform(\"vLightSpecular\", 4);\n this._uniformBuffer.addUniform(\"vLightDirection\", 3);\n this._uniformBuffer.addUniform(\"vLightFalloff\", 4);\n this._uniformBuffer.addUniform(\"shadowsInfo\", 3);\n this._uniformBuffer.addUniform(\"depthValues\", 2);\n this._uniformBuffer.create();\n }\n _computeAngleValues() {\n this._lightAngleScale = 1.0 / Math.max(0.001, Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle);\n this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;\n }\n /**\n * Sets the passed Effect \"effect\" with the Light textures.\n * @param effect The effect to update\n * @param lightIndex The index of the light in the effect to update\n * @returns The light\n */\n transferTexturesToEffect(effect, lightIndex) {\n if (this.projectionTexture && this.projectionTexture.isReady()) {\n if (this._projectionTextureViewLightDirty) {\n this._computeProjectionTextureViewLightMatrix();\n }\n if (this._projectionTextureProjectionLightDirty) {\n this._computeProjectionTextureProjectionLightMatrix();\n }\n if (this._projectionTextureDirty) {\n this._computeProjectionTextureMatrix();\n }\n effect.setMatrix(\"textureProjectionMatrix\" + lightIndex, this._projectionTextureMatrix);\n effect.setTexture(\"projectionLightSampler\" + lightIndex, this.projectionTexture);\n }\n return this;\n }\n /**\n * Sets the passed Effect object with the SpotLight transformed position (or position if not parented) and normalized direction.\n * @param effect The effect to update\n * @param lightIndex The index of the light in the effect to update\n * @returns The spot light\n */\n transferToEffect(effect, lightIndex) {\n let normalizeDirection;\n if (this.computeTransformedInformation()) {\n this._uniformBuffer.updateFloat4(\"vLightData\", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);\n normalizeDirection = Vector3.Normalize(this.transformedDirection);\n }\n else {\n this._uniformBuffer.updateFloat4(\"vLightData\", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);\n normalizeDirection = Vector3.Normalize(this.direction);\n }\n this._uniformBuffer.updateFloat4(\"vLightDirection\", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);\n this._uniformBuffer.updateFloat4(\"vLightFalloff\", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);\n return this;\n }\n transferToNodeMaterialEffect(effect, lightDataUniformName) {\n let normalizeDirection;\n if (this.computeTransformedInformation()) {\n normalizeDirection = Vector3.Normalize(this.transformedDirection);\n }\n else {\n normalizeDirection = Vector3.Normalize(this.direction);\n }\n if (this.getScene().useRightHandedSystem) {\n effect.setFloat3(lightDataUniformName, -normalizeDirection.x, -normalizeDirection.y, -normalizeDirection.z);\n }\n else {\n effect.setFloat3(lightDataUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z);\n }\n return this;\n }\n /**\n * Disposes the light and the associated resources.\n */\n dispose() {\n super.dispose();\n if (this._projectionTexture) {\n this._projectionTexture.dispose();\n }\n }\n /**\n * Gets the minZ used for shadow according to both the scene and the light.\n * @param activeCamera The camera we are returning the min for\n * @returns the depth min z\n */\n getDepthMinZ(activeCamera) {\n const engine = this._scene.getEngine();\n const minZ = this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;\n return engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? minZ : this._scene.getEngine().isNDCHalfZRange ? 0 : minZ;\n }\n /**\n * Gets the maxZ used for shadow according to both the scene and the light.\n * @param activeCamera The camera we are returning the max for\n * @returns the depth max z\n */\n getDepthMaxZ(activeCamera) {\n const engine = this._scene.getEngine();\n const maxZ = this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;\n return engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : maxZ;\n }\n /**\n * Prepares the list of defines specific to the light type.\n * @param defines the list of defines\n * @param lightIndex defines the index of the light for the effect\n */\n prepareLightSpecificDefines(defines, lightIndex) {\n defines[\"SPOTLIGHT\" + lightIndex] = true;\n defines[\"PROJECTEDLIGHTTEXTURE\" + lightIndex] = this.projectionTexture && this.projectionTexture.isReady() ? true : false;\n }\n}\n__decorate([\n serialize()\n], SpotLight.prototype, \"angle\", null);\n__decorate([\n serialize()\n], SpotLight.prototype, \"innerAngle\", null);\n__decorate([\n serialize()\n], SpotLight.prototype, \"shadowAngleScale\", null);\n__decorate([\n serialize()\n], SpotLight.prototype, \"exponent\", void 0);\n__decorate([\n serialize()\n], SpotLight.prototype, \"projectionTextureLightNear\", null);\n__decorate([\n serialize()\n], SpotLight.prototype, \"projectionTextureLightFar\", null);\n__decorate([\n serialize()\n], SpotLight.prototype, \"projectionTextureUpDirection\", null);\n__decorate([\n serializeAsTexture(\"projectedLightTexture\")\n], SpotLight.prototype, \"_projectionTexture\", void 0);\n//# sourceMappingURL=spotLight.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize, serializeAsMatrix, SerializationHelper, serializeAsVector3 } from \"../../Misc/decorators.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nimport { Matrix, TmpVectors, Vector3 } from \"../../Maths/math.vector.js\";\nimport { BaseTexture } from \"../../Materials/Textures/baseTexture.js\";\nimport { Texture } from \"../../Materials/Textures/texture.js\";\n\nimport { GetClass, RegisterClass } from \"../../Misc/typeStore.js\";\nimport \"../../Engines/Extensions/engine.cubeTexture.js\";\nimport { Observable } from \"../../Misc/observable.js\";\n/**\n * Class for creating a cube texture\n */\nexport class CubeTexture extends BaseTexture {\n /**\n * Gets or sets the size of the bounding box associated with the cube texture\n * When defined, the cubemap will switch to local mode\n * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity\n * @example https://www.babylonjs-playground.com/#RNASML\n */\n set boundingBoxSize(value) {\n if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {\n return;\n }\n this._boundingBoxSize = value;\n const scene = this.getScene();\n if (scene) {\n scene.markAllMaterialsAsDirty(1);\n }\n }\n /**\n * Returns the bounding box size\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#using-local-cubemap-mode\n */\n get boundingBoxSize() {\n return this._boundingBoxSize;\n }\n /**\n * Sets texture matrix rotation angle around Y axis in radians.\n */\n set rotationY(value) {\n this._rotationY = value;\n this.setReflectionTextureMatrix(Matrix.RotationY(this._rotationY));\n }\n /**\n * Gets texture matrix rotation angle around Y axis radians.\n */\n get rotationY() {\n return this._rotationY;\n }\n /**\n * Are mip maps generated for this texture or not.\n */\n get noMipmap() {\n return this._noMipmap;\n }\n /**\n * Gets the forced extension (if any)\n */\n get forcedExtension() {\n return this._forcedExtension;\n }\n /**\n * Creates a cube texture from an array of image urls\n * @param files defines an array of image urls\n * @param scene defines the hosting scene\n * @param noMipmap specifies if mip maps are not used\n * @returns a cube texture\n */\n static CreateFromImages(files, scene, noMipmap) {\n let rootUrlKey = \"\";\n files.forEach((url) => (rootUrlKey += url));\n return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);\n }\n /**\n * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.\n * @param url defines the url of the prefiltered texture\n * @param scene defines the scene the texture is attached to\n * @param forcedExtension defines the extension of the file if different from the url\n * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary\n * @returns the prefiltered texture\n */\n static CreateFromPrefilteredData(url, scene, forcedExtension = null, createPolynomials = true) {\n const oldValue = scene.useDelayedTextureLoading;\n scene.useDelayedTextureLoading = false;\n const result = new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);\n scene.useDelayedTextureLoading = oldValue;\n return result;\n }\n /**\n * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well\n * as prefiltered data.\n * @param rootUrl defines the url of the texture or the root name of the six images\n * @param sceneOrEngine defines the scene or engine the texture is attached to\n * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...\n * @param noMipmap defines if mipmaps should be created or not\n * @param files defines the six files to load for the different faces in that order: px, py, pz, nx, ny, nz\n * @param onLoad defines a callback triggered at the end of the file load if no errors occurred\n * @param onError defines a callback triggered in case of error during load\n * @param format defines the internal format to use for the texture once loaded\n * @param prefiltered defines whether or not the texture is created from prefiltered data\n * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name\n * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary\n * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness\n * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness\n * @param loaderOptions options to be passed to the loader\n * @param useSRGBBuffer Defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU) (default: false)\n * @returns the cube texture\n */\n constructor(rootUrl, sceneOrEngine, extensions = null, noMipmap = false, files = null, onLoad = null, onError = null, format = 5, prefiltered = false, forcedExtension = null, createPolynomials = false, lodScale = 0.8, lodOffset = 0, loaderOptions, useSRGBBuffer) {\n var _a;\n super(sceneOrEngine);\n this._lodScale = 0.8;\n this._lodOffset = 0;\n /**\n * Observable triggered once the texture has been loaded.\n */\n this.onLoadObservable = new Observable();\n /**\n * Gets or sets the center of the bounding box associated with the cube texture.\n * It must define where the camera used to render the texture was set\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#using-local-cubemap-mode\n */\n this.boundingBoxPosition = Vector3.Zero();\n this._rotationY = 0;\n /** @internal */\n this._files = null;\n this._forcedExtension = null;\n this._extensions = null;\n this._textureMatrixRefraction = new Matrix();\n this.name = rootUrl;\n this.url = rootUrl;\n this._noMipmap = noMipmap;\n this.hasAlpha = false;\n this._format = format;\n this.isCube = true;\n this._textureMatrix = Matrix.Identity();\n this._createPolynomials = createPolynomials;\n this.coordinatesMode = Texture.CUBIC_MODE;\n this._extensions = extensions;\n this._files = files;\n this._forcedExtension = forcedExtension;\n this._loaderOptions = loaderOptions;\n this._useSRGBBuffer = useSRGBBuffer;\n this._lodScale = lodScale;\n this._lodOffset = lodOffset;\n if (!rootUrl && !files) {\n return;\n }\n this.updateURL(rootUrl, forcedExtension, onLoad, prefiltered, onError, extensions, (_a = this.getScene()) === null || _a === void 0 ? void 0 : _a.useDelayedTextureLoading, files);\n }\n /**\n * Get the current class name of the texture useful for serialization or dynamic coding.\n * @returns \"CubeTexture\"\n */\n getClassName() {\n return \"CubeTexture\";\n }\n /**\n * Update the url (and optional buffer) of this texture if url was null during construction.\n * @param url the url of the texture\n * @param forcedExtension defines the extension to use\n * @param onLoad callback called when the texture is loaded (defaults to null)\n * @param prefiltered Defines whether the updated texture is prefiltered or not\n * @param onError callback called if there was an error during the loading process (defaults to null)\n * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...\n * @param delayLoad defines if the texture should be loaded now (false by default)\n * @param files defines the six files to load for the different faces in that order: px, py, pz, nx, ny, nz\n */\n updateURL(url, forcedExtension, onLoad = null, prefiltered = false, onError = null, extensions = null, delayLoad = false, files = null) {\n if (!this.name || this.name.startsWith(\"data:\")) {\n this.name = url;\n }\n this.url = url;\n if (forcedExtension) {\n this._forcedExtension = forcedExtension;\n }\n const lastDot = url.lastIndexOf(\".\");\n const extension = forcedExtension ? forcedExtension : lastDot > -1 ? url.substring(lastDot).toLowerCase() : \"\";\n const isDDS = extension.indexOf(\".dds\") === 0;\n const isEnv = extension.indexOf(\".env\") === 0;\n const isBasis = extension.indexOf(\".basis\") === 0;\n if (isEnv) {\n this.gammaSpace = false;\n this._prefiltered = false;\n this.anisotropicFilteringLevel = 1;\n }\n else {\n this._prefiltered = prefiltered;\n if (prefiltered) {\n this.gammaSpace = false;\n this.anisotropicFilteringLevel = 1;\n }\n }\n if (files) {\n this._files = files;\n }\n else {\n if (!isBasis && !isEnv && !isDDS && !extensions) {\n extensions = [\"_px.jpg\", \"_py.jpg\", \"_pz.jpg\", \"_nx.jpg\", \"_ny.jpg\", \"_nz.jpg\"];\n }\n this._files = this._files || [];\n this._files.length = 0;\n if (extensions) {\n for (let index = 0; index < extensions.length; index++) {\n this._files.push(url + extensions[index]);\n }\n this._extensions = extensions;\n }\n }\n if (delayLoad) {\n this.delayLoadState = 4;\n this._delayedOnLoad = onLoad;\n this._delayedOnError = onError;\n }\n else {\n this._loadTexture(onLoad, onError);\n }\n }\n /**\n * Delays loading of the cube texture\n * @param forcedExtension defines the extension to use\n */\n delayLoad(forcedExtension) {\n if (this.delayLoadState !== 4) {\n return;\n }\n if (forcedExtension) {\n this._forcedExtension = forcedExtension;\n }\n this.delayLoadState = 1;\n this._loadTexture(this._delayedOnLoad, this._delayedOnError);\n }\n /**\n * Returns the reflection texture matrix\n * @returns the reflection texture matrix\n */\n getReflectionTextureMatrix() {\n return this._textureMatrix;\n }\n /**\n * Sets the reflection texture matrix\n * @param value Reflection texture matrix\n */\n setReflectionTextureMatrix(value) {\n var _a, _b;\n if (value.updateFlag === this._textureMatrix.updateFlag) {\n return;\n }\n if (value.isIdentity() !== this._textureMatrix.isIdentity()) {\n (_a = this.getScene()) === null || _a === void 0 ? void 0 : _a.markAllMaterialsAsDirty(1, (mat) => mat.getActiveTextures().indexOf(this) !== -1);\n }\n this._textureMatrix = value;\n if (!((_b = this.getScene()) === null || _b === void 0 ? void 0 : _b.useRightHandedSystem)) {\n return;\n }\n const scale = TmpVectors.Vector3[0];\n const quat = TmpVectors.Quaternion[0];\n const trans = TmpVectors.Vector3[1];\n this._textureMatrix.decompose(scale, quat, trans);\n quat.z *= -1; // these two operations correspond to negating the x and y euler angles\n quat.w *= -1;\n Matrix.ComposeToRef(scale, quat, trans, this._textureMatrixRefraction);\n }\n /**\n * Gets a suitable rotate/transform matrix when the texture is used for refraction.\n * There's a separate function from getReflectionTextureMatrix because refraction requires a special configuration of the matrix in right-handed mode.\n * @returns The refraction matrix\n */\n getRefractionTextureMatrix() {\n var _a;\n return ((_a = this.getScene()) === null || _a === void 0 ? void 0 : _a.useRightHandedSystem) ? this._textureMatrixRefraction : this._textureMatrix;\n }\n _loadTexture(onLoad = null, onError = null) {\n var _a;\n const scene = this.getScene();\n const oldTexture = this._texture;\n this._texture = this._getFromCache(this.url, this._noMipmap, undefined, undefined, this._useSRGBBuffer, this.isCube);\n const onLoadProcessing = () => {\n var _a;\n this.onLoadObservable.notifyObservers(this);\n if (oldTexture) {\n oldTexture.dispose();\n (_a = this.getScene()) === null || _a === void 0 ? void 0 : _a.markAllMaterialsAsDirty(1);\n }\n if (onLoad) {\n onLoad();\n }\n };\n const errorHandler = (message, exception) => {\n this._loadingError = true;\n this._errorObject = { message, exception };\n if (onError) {\n onError(message, exception);\n }\n Texture.OnTextureLoadErrorObservable.notifyObservers(this);\n };\n if (!this._texture) {\n if (this._prefiltered) {\n this._texture = this._getEngine().createPrefilteredCubeTexture(this.url, scene, this._lodScale, this._lodOffset, onLoad, errorHandler, this._format, this._forcedExtension, this._createPolynomials);\n }\n else {\n this._texture = this._getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, onLoad, errorHandler, this._format, this._forcedExtension, false, this._lodScale, this._lodOffset, null, this._loaderOptions, !!this._useSRGBBuffer);\n }\n (_a = this._texture) === null || _a === void 0 ? void 0 : _a.onLoadedObservable.add(() => this.onLoadObservable.notifyObservers(this));\n }\n else {\n if (this._texture.isReady) {\n Tools.SetImmediate(() => onLoadProcessing());\n }\n else {\n this._texture.onLoadedObservable.add(() => onLoadProcessing());\n }\n }\n }\n /**\n * Parses text to create a cube texture\n * @param parsedTexture define the serialized text to read from\n * @param scene defines the hosting scene\n * @param rootUrl defines the root url of the cube texture\n * @returns a cube texture\n */\n static Parse(parsedTexture, scene, rootUrl) {\n const texture = SerializationHelper.Parse(() => {\n var _a;\n let prefiltered = false;\n if (parsedTexture.prefiltered) {\n prefiltered = parsedTexture.prefiltered;\n }\n return new CubeTexture(rootUrl + ((_a = parsedTexture.url) !== null && _a !== void 0 ? _a : parsedTexture.name), scene, parsedTexture.extensions, false, parsedTexture.files || null, null, null, undefined, prefiltered, parsedTexture.forcedExtension);\n }, parsedTexture, scene);\n // Local Cubemaps\n if (parsedTexture.boundingBoxPosition) {\n texture.boundingBoxPosition = Vector3.FromArray(parsedTexture.boundingBoxPosition);\n }\n if (parsedTexture.boundingBoxSize) {\n texture.boundingBoxSize = Vector3.FromArray(parsedTexture.boundingBoxSize);\n }\n // Animations\n if (parsedTexture.animations) {\n for (let animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {\n const parsedAnimation = parsedTexture.animations[animationIndex];\n const internalClass = GetClass(\"BABYLON.Animation\");\n if (internalClass) {\n texture.animations.push(internalClass.Parse(parsedAnimation));\n }\n }\n }\n return texture;\n }\n /**\n * Makes a clone, or deep copy, of the cube texture\n * @returns a new cube texture\n */\n clone() {\n let uniqueId = 0;\n const newCubeTexture = SerializationHelper.Clone(() => {\n const cubeTexture = new CubeTexture(this.url, this.getScene() || this._getEngine(), this._extensions, this._noMipmap, this._files);\n uniqueId = cubeTexture.uniqueId;\n return cubeTexture;\n }, this);\n newCubeTexture.uniqueId = uniqueId;\n return newCubeTexture;\n }\n}\n__decorate([\n serialize()\n], CubeTexture.prototype, \"url\", void 0);\n__decorate([\n serializeAsVector3()\n], CubeTexture.prototype, \"boundingBoxPosition\", void 0);\n__decorate([\n serializeAsVector3()\n], CubeTexture.prototype, \"boundingBoxSize\", null);\n__decorate([\n serialize(\"rotationY\")\n], CubeTexture.prototype, \"rotationY\", null);\n__decorate([\n serialize(\"files\")\n], CubeTexture.prototype, \"_files\", void 0);\n__decorate([\n serialize(\"forcedExtension\")\n], CubeTexture.prototype, \"_forcedExtension\", void 0);\n__decorate([\n serialize(\"extensions\")\n], CubeTexture.prototype, \"_extensions\", void 0);\n__decorate([\n serializeAsMatrix(\"textureMatrix\")\n], CubeTexture.prototype, \"_textureMatrix\", void 0);\n__decorate([\n serializeAsMatrix(\"textureMatrixRefraction\")\n], CubeTexture.prototype, \"_textureMatrixRefraction\", void 0);\nTexture._CubeTextureParser = CubeTexture.Parse;\n// Some exporters relies on Tools.Instantiate\nRegisterClass(\"BABYLON.CubeTexture\", CubeTexture);\n//# sourceMappingURL=cubeTexture.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"backgroundFragmentDeclaration\";\nconst shader = `uniform vec4 vEyePosition;\runiform vec4 vPrimaryColor;\r#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\r#endif\nuniform float shadowLevel;\runiform float alpha;\r#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\r#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\runiform mat4 reflectionMatrix;\runiform vec3 vReflectionMicrosurfaceInfos;\r#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\r#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\r#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const backgroundFragmentDeclaration = { name, shader };\n//# sourceMappingURL=backgroundFragmentDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nimport \"./sceneUboDeclaration.js\";\nconst name = \"backgroundUboDeclaration\";\nconst shader = `layout(std140,column_major) uniform;\runiform Material\r{\runiform vec4 vPrimaryColor;\runiform vec4 vPrimaryColorShadow;\runiform vec2 vDiffuseInfos;\runiform vec2 vReflectionInfos;\runiform mat4 diffuseMatrix;\runiform mat4 reflectionMatrix;\runiform vec3 vReflectionMicrosurfaceInfos;\runiform float fFovMultiplier;\runiform float pointSize;\runiform float shadowLevel;\runiform float alpha;\r#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\r#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\r#endif\n};\r#include\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const backgroundUboDeclaration = { name, shader };\n//# sourceMappingURL=backgroundUboDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/backgroundFragmentDeclaration.js\";\nimport \"./ShadersInclude/backgroundUboDeclaration.js\";\nimport \"./ShadersInclude/helperFunctions.js\";\nimport \"./ShadersInclude/reflectionFunction.js\";\nimport \"./ShadersInclude/imageProcessingDeclaration.js\";\nimport \"./ShadersInclude/lightFragmentDeclaration.js\";\nimport \"./ShadersInclude/lightUboDeclaration.js\";\nimport \"./ShadersInclude/lightsFragmentFunctions.js\";\nimport \"./ShadersInclude/shadowsFragmentFunctions.js\";\nimport \"./ShadersInclude/imageProcessingFunctions.js\";\nimport \"./ShadersInclude/clipPlaneFragmentDeclaration.js\";\nimport \"./ShadersInclude/fogFragmentDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneFragment.js\";\nimport \"./ShadersInclude/lightFragment.js\";\nimport \"./ShadersInclude/fogFragment.js\";\nconst name = \"backgroundPixelShader\";\nconst shader = `#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\r#include<__decl__backgroundFragment>\n#include\n#define RECIPROCAL_PI2 0.15915494\nvarying vec3 vPositionW;\r#ifdef MAINUV1\nvarying vec2 vMainUV1;\r#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \r#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\r#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV==1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV==2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\r#endif\nuniform sampler2D diffuseSampler;\r#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\r#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\runiform samplerCube reflectionSamplerHigh;\r#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\r#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\runiform samplerCube reflectionSamplerHigh;\r#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\r#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\r#endif\n#endif\n#include\n#endif\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include\n#include\n#include\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\r{\rfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\rreturn reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));\r}\r#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\r#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\r#else\nvec3 normalW=vec3(0.0,1.0,0.0);\r#endif\nfloat shadow=1.;\rfloat globalShadow=0.;\rfloat shadowLightCount=0.;\r#include[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\r#else\nglobalShadow=1.0;\r#endif\n#ifndef BACKMAT_SHADOWONLY\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\r#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\r#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\r#endif\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\r#else\nvec2 reflectionCoords=reflectionVector.xy;\r#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\r#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\r#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\r#ifdef TEXTURELODSUPPORT\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\rreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\r#else\nfloat lodReflectionNormalized=saturate(reflectionLOD);\rfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\rvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\rif(lodReflectionNormalizedDoubled<1.0){\rreflectionColor=mix(\rsampleReflection(reflectionSamplerHigh,reflectionCoords),\rreflectionSpecularMid,\rlodReflectionNormalizedDoubled\r);\r} else {\rreflectionColor=mix(\rreflectionSpecularMid,\rsampleReflection(reflectionSamplerLow,reflectionCoords),\rlodReflectionNormalizedDoubled-1.0\r);\r}\r#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\rreflectionColor=reflectionSample;\r#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\r#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\r#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\r#endif\nreflectionColor.rgb*=vReflectionInfos.x;\r#endif\nvec3 diffuseColor=vec3(1.,1.,1.);\rfloat finalAlpha=alpha;\r#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\r#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\r#endif\ndiffuseMap.rgb*=vDiffuseInfos.y;\r#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\r#endif\ndiffuseColor=diffuseMap.rgb;\r#endif\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\r#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\r#endif\ncolorBase=max(colorBase,0.0);\r#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\r#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\r#else\nvec3 mainColor=vPrimaryColor.rgb;\r#endif\nvec3 finalColor=colorBase*mainColor;\r#endif\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\rvec3 reflectionReflectance0=vReflectionControl.yyy;\rvec3 reflectionReflectance90=vReflectionControl.zzz;\rfloat VdotN=dot(normalize(vEyePosition.xyz),normalW);\rvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);\rreflectionAmount*=planarReflectionFresnel;\r#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);\rreflectionDistanceFalloff*=reflectionDistanceFalloff;\rreflectionAmount*=reflectionDistanceFalloff;\r#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount));\r#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));\rconst float startAngle=0.1;\rfloat fadeFactor=saturate(viewAngleToFloor/startAngle);\rfinalAlpha*=fadeFactor*fadeFactor;\r#endif\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\r#endif\nvec4 color=vec4(finalColor,finalAlpha);\r#else\nvec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha);\r#endif\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n#if !defined(SKIPFINALCOLORCLAMP)\ncolor.rgb=clamp(color.rgb,0.,30.0);\r#endif\n#else\ncolor=applyImageProcessing(color);\r#endif\n#ifdef PREMULTIPLYALPHA\ncolor.rgb*=color.a;\r#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\rcolor=max(color,0.0);\r#endif\ngl_FragColor=color;\r#define CUSTOM_FRAGMENT_MAIN_END\n}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const backgroundPixelShader = { name, shader };\n//# sourceMappingURL=background.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"backgroundVertexDeclaration\";\nconst shader = `uniform mat4 view;\runiform mat4 viewProjection;\runiform float shadowLevel;\r#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\runiform vec2 vDiffuseInfos;\r#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\runiform mat4 reflectionMatrix;\runiform vec3 vReflectionMicrosurfaceInfos;\runiform float fFovMultiplier;\r#endif\n#ifdef POINTSIZE\nuniform float pointSize;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const backgroundVertexDeclaration = { name, shader };\n//# sourceMappingURL=backgroundVertexDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/backgroundVertexDeclaration.js\";\nimport \"./ShadersInclude/backgroundUboDeclaration.js\";\nimport \"./ShadersInclude/helperFunctions.js\";\nimport \"./ShadersInclude/bonesDeclaration.js\";\nimport \"./ShadersInclude/bakedVertexAnimationDeclaration.js\";\nimport \"./ShadersInclude/instancesDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneVertexDeclaration.js\";\nimport \"./ShadersInclude/fogVertexDeclaration.js\";\nimport \"./ShadersInclude/lightVxFragmentDeclaration.js\";\nimport \"./ShadersInclude/lightVxUboDeclaration.js\";\nimport \"./ShadersInclude/instancesVertex.js\";\nimport \"./ShadersInclude/bonesVertex.js\";\nimport \"./ShadersInclude/bakedVertexAnimation.js\";\nimport \"./ShadersInclude/clipPlaneVertex.js\";\nimport \"./ShadersInclude/fogVertex.js\";\nimport \"./ShadersInclude/shadowsVertex.js\";\nconst name = \"backgroundVertexShader\";\nconst shader = `precision highp float;\r#include<__decl__backgroundVertex>\n#include\nattribute vec3 position;\r#ifdef NORMAL\nattribute vec3 normal;\r#endif\n#include\n#include\n#include\nvarying vec3 vPositionW;\r#ifdef NORMAL\nvarying vec3 vNormalW;\r#endif\n#ifdef UV1\nattribute vec2 uv;\r#endif\n#ifdef UV2\nattribute vec2 uv2;\r#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\r#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\r#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nvarying vec2 vDiffuseUV;\r#endif\n#include\n#include\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\r#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\r#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_VERTEX_MAIN_BEGIN\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\r#endif\n#include\n#include\n#include\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {\rgl_Position=viewProjection*finalWorld*vec4(position,1.0);\r} else {\rgl_Position=viewProjectionR*finalWorld*vec4(position,1.0);\r}\r#else\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\r#endif\nvec4 worldPos=finalWorld*vec4(position,1.0);\rvPositionW=vec3(worldPos);\r#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\r#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\r#endif\nvNormalW=normalize(normalWorld*normal);\r#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\r#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\rvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\rif (fFovMultiplier<=1.0) {\rvDirectionW=normalize(segment);\r} else {\rvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\r}\r#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\r#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\r#endif\n#ifdef MAINUV1\nvMainUV1=uv;\r#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\r#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0\nif (vDiffuseInfos.x==0.)\r{\rvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\r}\relse\r{\rvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\r}\r#endif\n#include\n#include\n#include[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\nvColor=color;\r#endif\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\r#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const backgroundVertexShader = { name, shader };\n//# sourceMappingURL=background.vertex.js.map","import { __decorate } from \"../../tslib.es6.js\";\n/* eslint-disable @typescript-eslint/naming-convention */\nimport { SerializationHelper, serialize, serializeAsColor3, expandToProperty, serializeAsTexture, serializeAsVector3, serializeAsImageProcessingConfiguration, } from \"../../Misc/decorators.js\";\nimport { SmartArray } from \"../../Misc/smartArray.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { Vector3, Vector4 } from \"../../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../../Buffers/buffer.js\";\nimport { MaterialHelper } from \"../../Materials/materialHelper.js\";\nimport { MaterialDefines } from \"../../Materials/materialDefines.js\";\nimport { PushMaterial } from \"../../Materials/pushMaterial.js\";\nimport { ImageProcessingConfiguration } from \"../../Materials/imageProcessingConfiguration.js\";\nimport { Texture } from \"../../Materials/Textures/texture.js\";\n\nimport { RegisterClass } from \"../../Misc/typeStore.js\";\nimport { MaterialFlags } from \"../materialFlags.js\";\nimport { Color3 } from \"../../Maths/math.color.js\";\nimport \"../../Shaders/background.fragment.js\";\nimport \"../../Shaders/background.vertex.js\";\nimport { EffectFallbacks } from \"../effectFallbacks.js\";\nimport { addClipPlaneUniforms, bindClipPlane } from \"../clipPlaneMaterialHelper.js\";\n/**\n * Background material defines definition.\n * @internal Mainly internal Use\n */\nclass BackgroundMaterialDefines extends MaterialDefines {\n /**\n * Constructor of the defines.\n */\n constructor() {\n super();\n /**\n * True if the diffuse texture is in use.\n */\n this.DIFFUSE = false;\n /**\n * The direct UV channel to use.\n */\n this.DIFFUSEDIRECTUV = 0;\n /**\n * True if the diffuse texture is in gamma space.\n */\n this.GAMMADIFFUSE = false;\n /**\n * True if the diffuse texture has opacity in the alpha channel.\n */\n this.DIFFUSEHASALPHA = false;\n /**\n * True if you want the material to fade to transparent at grazing angle.\n */\n this.OPACITYFRESNEL = false;\n /**\n * True if an extra blur needs to be added in the reflection.\n */\n this.REFLECTIONBLUR = false;\n /**\n * True if you want the material to fade to reflection at grazing angle.\n */\n this.REFLECTIONFRESNEL = false;\n /**\n * True if you want the material to falloff as far as you move away from the scene center.\n */\n this.REFLECTIONFALLOFF = false;\n /**\n * False if the current Webgl implementation does not support the texture lod extension.\n */\n this.TEXTURELODSUPPORT = false;\n /**\n * True to ensure the data are premultiplied.\n */\n this.PREMULTIPLYALPHA = false;\n /**\n * True if the texture contains cooked RGB values and not gray scaled multipliers.\n */\n this.USERGBCOLOR = false;\n /**\n * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color\n * stays aligned with the desired configuration.\n */\n this.USEHIGHLIGHTANDSHADOWCOLORS = false;\n /**\n * True if only shadows must be rendered\n */\n this.BACKMAT_SHADOWONLY = false;\n /**\n * True to add noise in order to reduce the banding effect.\n */\n this.NOISE = false;\n /**\n * is the reflection texture in BGR color scheme?\n * Mainly used to solve a bug in ios10 video tag\n */\n this.REFLECTIONBGR = false;\n this.IMAGEPROCESSING = false;\n this.VIGNETTE = false;\n this.VIGNETTEBLENDMODEMULTIPLY = false;\n this.VIGNETTEBLENDMODEOPAQUE = false;\n this.TONEMAPPING = false;\n this.TONEMAPPING_ACES = false;\n this.CONTRAST = false;\n this.COLORCURVES = false;\n this.COLORGRADING = false;\n this.COLORGRADING3D = false;\n this.SAMPLER3DGREENDEPTH = false;\n this.SAMPLER3DBGRMAP = false;\n this.DITHER = false;\n this.IMAGEPROCESSINGPOSTPROCESS = false;\n this.SKIPFINALCOLORCLAMP = false;\n this.EXPOSURE = false;\n this.MULTIVIEW = false;\n // Reflection.\n this.REFLECTION = false;\n this.REFLECTIONMAP_3D = false;\n this.REFLECTIONMAP_SPHERICAL = false;\n this.REFLECTIONMAP_PLANAR = false;\n this.REFLECTIONMAP_CUBIC = false;\n this.REFLECTIONMAP_PROJECTION = false;\n this.REFLECTIONMAP_SKYBOX = false;\n this.REFLECTIONMAP_EXPLICIT = false;\n this.REFLECTIONMAP_EQUIRECTANGULAR = false;\n this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;\n this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;\n this.INVERTCUBICMAP = false;\n this.REFLECTIONMAP_OPPOSITEZ = false;\n this.LODINREFLECTIONALPHA = false;\n this.GAMMAREFLECTION = false;\n this.RGBDREFLECTION = false;\n this.EQUIRECTANGULAR_RELFECTION_FOV = false;\n // Default BJS.\n this.MAINUV1 = false;\n this.MAINUV2 = false;\n this.UV1 = false;\n this.UV2 = false;\n this.CLIPPLANE = false;\n this.CLIPPLANE2 = false;\n this.CLIPPLANE3 = false;\n this.CLIPPLANE4 = false;\n this.CLIPPLANE5 = false;\n this.CLIPPLANE6 = false;\n this.POINTSIZE = false;\n this.FOG = false;\n this.NORMAL = false;\n this.NUM_BONE_INFLUENCERS = 0;\n this.BonesPerMesh = 0;\n this.INSTANCES = false;\n this.SHADOWFLOAT = false;\n this.LOGARITHMICDEPTH = false;\n this.NONUNIFORMSCALING = false;\n this.ALPHATEST = false;\n this.rebuild();\n }\n}\n/**\n * Background material used to create an efficient environment around your scene.\n */\nexport class BackgroundMaterial extends PushMaterial {\n /**\n * Experimental Internal Use Only.\n *\n * Key light Color in \"perceptual value\" meaning the color you would like to see on screen.\n * This acts as a helper to set the primary color to a more \"human friendly\" value.\n * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the\n * output color as close as possible from the chosen value.\n * (This does not account for contrast color grading and color curves as they are considered post effect and not directly\n * part of lighting setup.)\n */\n get _perceptualColor() {\n return this.__perceptualColor;\n }\n set _perceptualColor(value) {\n this.__perceptualColor = value;\n this._computePrimaryColorFromPerceptualColor();\n this._markAllSubMeshesAsLightsDirty();\n }\n /**\n * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.\n * The color opposite to the primary color is used at the level chosen to define what the black area would look.\n */\n get primaryColorShadowLevel() {\n return this._primaryColorShadowLevel;\n }\n set primaryColorShadowLevel(value) {\n this._primaryColorShadowLevel = value;\n this._computePrimaryColors();\n this._markAllSubMeshesAsLightsDirty();\n }\n /**\n * Defines the level of the highlights (highlight area of the reflection map) in order to help scaling the colors.\n * The primary color is used at the level chosen to define what the white area would look.\n */\n get primaryColorHighlightLevel() {\n return this._primaryColorHighlightLevel;\n }\n set primaryColorHighlightLevel(value) {\n this._primaryColorHighlightLevel = value;\n this._computePrimaryColors();\n this._markAllSubMeshesAsLightsDirty();\n }\n /**\n * Sets the reflection reflectance fresnel values according to the default standard\n * empirically know to work well :-)\n */\n set reflectionStandardFresnelWeight(value) {\n let reflectionWeight = value;\n if (reflectionWeight < 0.5) {\n reflectionWeight = reflectionWeight * 2.0;\n this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;\n this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;\n }\n else {\n reflectionWeight = reflectionWeight * 2.0 - 1.0;\n this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;\n this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;\n }\n }\n /**\n * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values \"zoom in\" and higher values \"zoom out\".\n * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.\n * Recommended to be keep at 1.0 except for special cases.\n */\n get fovMultiplier() {\n return this._fovMultiplier;\n }\n set fovMultiplier(value) {\n if (isNaN(value)) {\n value = 1.0;\n }\n this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));\n }\n /**\n * Attaches a new image processing configuration to the PBR Material.\n * @param configuration (if null the scene configuration will be use)\n */\n _attachImageProcessingConfiguration(configuration) {\n if (configuration === this._imageProcessingConfiguration) {\n return;\n }\n // Detaches observer.\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n // Pick the scene configuration if needed.\n if (!configuration) {\n this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;\n }\n else {\n this._imageProcessingConfiguration = configuration;\n }\n // Attaches observer.\n if (this._imageProcessingConfiguration) {\n this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => {\n this._computePrimaryColorFromPerceptualColor();\n this._markAllSubMeshesAsImageProcessingDirty();\n });\n }\n }\n /**\n * Gets the image processing configuration used either in this material.\n */\n get imageProcessingConfiguration() {\n return this._imageProcessingConfiguration;\n }\n /**\n * Sets the Default image processing configuration used either in the this material.\n *\n * If sets to null, the scene one is in use.\n */\n set imageProcessingConfiguration(value) {\n this._attachImageProcessingConfiguration(value);\n // Ensure the effect will be rebuilt.\n this._markAllSubMeshesAsTexturesDirty();\n }\n /**\n * Gets whether the color curves effect is enabled.\n */\n get cameraColorCurvesEnabled() {\n return this.imageProcessingConfiguration.colorCurvesEnabled;\n }\n /**\n * Sets whether the color curves effect is enabled.\n */\n set cameraColorCurvesEnabled(value) {\n this.imageProcessingConfiguration.colorCurvesEnabled = value;\n }\n /**\n * Gets whether the color grading effect is enabled.\n */\n get cameraColorGradingEnabled() {\n return this.imageProcessingConfiguration.colorGradingEnabled;\n }\n /**\n * Gets whether the color grading effect is enabled.\n */\n set cameraColorGradingEnabled(value) {\n this.imageProcessingConfiguration.colorGradingEnabled = value;\n }\n /**\n * Gets whether tonemapping is enabled or not.\n */\n get cameraToneMappingEnabled() {\n return this._imageProcessingConfiguration.toneMappingEnabled;\n }\n /**\n * Sets whether tonemapping is enabled or not\n */\n set cameraToneMappingEnabled(value) {\n this._imageProcessingConfiguration.toneMappingEnabled = value;\n }\n /**\n * The camera exposure used on this material.\n * This property is here and not in the camera to allow controlling exposure without full screen post process.\n * This corresponds to a photographic exposure.\n */\n get cameraExposure() {\n return this._imageProcessingConfiguration.exposure;\n }\n /**\n * The camera exposure used on this material.\n * This property is here and not in the camera to allow controlling exposure without full screen post process.\n * This corresponds to a photographic exposure.\n */\n set cameraExposure(value) {\n this._imageProcessingConfiguration.exposure = value;\n }\n /**\n * Gets The camera contrast used on this material.\n */\n get cameraContrast() {\n return this._imageProcessingConfiguration.contrast;\n }\n /**\n * Sets The camera contrast used on this material.\n */\n set cameraContrast(value) {\n this._imageProcessingConfiguration.contrast = value;\n }\n /**\n * Gets the Color Grading 2D Lookup Texture.\n */\n get cameraColorGradingTexture() {\n return this._imageProcessingConfiguration.colorGradingTexture;\n }\n /**\n * Sets the Color Grading 2D Lookup Texture.\n */\n set cameraColorGradingTexture(value) {\n this.imageProcessingConfiguration.colorGradingTexture = value;\n }\n /**\n * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\n get cameraColorCurves() {\n return this.imageProcessingConfiguration.colorCurves;\n }\n /**\n * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\n set cameraColorCurves(value) {\n this.imageProcessingConfiguration.colorCurves = value;\n }\n /**\n * Instantiates a Background Material in the given scene\n * @param name The friendly name of the material\n * @param scene The scene to add the material to\n */\n constructor(name, scene) {\n super(name, scene);\n /**\n * Key light Color (multiply against the environment texture)\n */\n this.primaryColor = Color3.White();\n this._primaryColorShadowLevel = 0;\n this._primaryColorHighlightLevel = 0;\n /**\n * Reflection Texture used in the material.\n * Should be author in a specific way for the best result (refer to the documentation).\n */\n this.reflectionTexture = null;\n /**\n * Reflection Texture level of blur.\n *\n * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the\n * texture twice.\n */\n this.reflectionBlur = 0;\n /**\n * Diffuse Texture used in the material.\n * Should be author in a specific way for the best result (refer to the documentation).\n */\n this.diffuseTexture = null;\n this._shadowLights = null;\n /**\n * Specify the list of lights casting shadow on the material.\n * All scene shadow lights will be included if null.\n */\n this.shadowLights = null;\n /**\n * Helps adjusting the shadow to a softer level if required.\n * 0 means black shadows and 1 means no shadows.\n */\n this.shadowLevel = 0;\n /**\n * In case of opacity Fresnel or reflection falloff, this is use as a scene center.\n * It is usually zero but might be interesting to modify according to your setup.\n */\n this.sceneCenter = Vector3.Zero();\n /**\n * This helps specifying that the material is falling off to the sky box at grazing angle.\n * This helps ensuring a nice transition when the camera goes under the ground.\n */\n this.opacityFresnel = true;\n /**\n * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.\n * This helps adding a mirror texture on the ground.\n */\n this.reflectionFresnel = false;\n /**\n * This helps specifying the falloff radius off the reflection texture from the sceneCenter.\n * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.\n */\n this.reflectionFalloffDistance = 0.0;\n /**\n * This specifies the weight of the reflection against the background in case of reflection Fresnel.\n */\n this.reflectionAmount = 1.0;\n /**\n * This specifies the weight of the reflection at grazing angle.\n */\n this.reflectionReflectance0 = 0.05;\n /**\n * This specifies the weight of the reflection at a perpendicular point of view.\n */\n this.reflectionReflectance90 = 0.5;\n /**\n * Helps to directly use the maps channels instead of their level.\n */\n this.useRGBColor = true;\n /**\n * This helps reducing the banding effect that could occur on the background.\n */\n this.enableNoise = false;\n this._fovMultiplier = 1.0;\n /**\n * Enable the FOV adjustment feature controlled by fovMultiplier.\n */\n this.useEquirectangularFOV = false;\n this._maxSimultaneousLights = 4;\n /**\n * Number of Simultaneous lights allowed on the material.\n */\n this.maxSimultaneousLights = 4;\n this._shadowOnly = false;\n /**\n * Make the material only render shadows\n */\n this.shadowOnly = false;\n /**\n * Keep track of the image processing observer to allow dispose and replace.\n */\n this._imageProcessingObserver = null;\n /**\n * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.\n * Setting this flag to true (not done automatically!) will convert it back to RGB.\n */\n this.switchToBGR = false;\n // Temp values kept as cache in the material.\n this._renderTargets = new SmartArray(16);\n this._reflectionControls = Vector4.Zero();\n this._white = Color3.White();\n this._primaryShadowColor = Color3.Black();\n this._primaryHighlightColor = Color3.Black();\n // Setup the default processing configuration to the scene.\n this._attachImageProcessingConfiguration(null);\n this.getRenderTargetTextures = () => {\n this._renderTargets.reset();\n if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {\n this._renderTargets.push(this._diffuseTexture);\n }\n if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {\n this._renderTargets.push(this._reflectionTexture);\n }\n return this._renderTargets;\n };\n }\n /**\n * Gets a boolean indicating that current material needs to register RTT\n */\n get hasRenderTargetTextures() {\n if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {\n return true;\n }\n if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {\n return true;\n }\n return false;\n }\n /**\n * The entire material has been created in order to prevent overdraw.\n * @returns false\n */\n needAlphaTesting() {\n return true;\n }\n /**\n * The entire material has been created in order to prevent overdraw.\n * @returns true if blending is enable\n */\n needAlphaBlending() {\n return this.alpha < 1 || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha) || this._shadowOnly;\n }\n /**\n * Checks whether the material is ready to be rendered for a given mesh.\n * @param mesh The mesh to render\n * @param subMesh The submesh to check against\n * @param useInstances Specify wether or not the material is used with instances\n * @returns true if all the dependencies are ready (Textures, Effects...)\n */\n isReadyForSubMesh(mesh, subMesh, useInstances = false) {\n if (subMesh.effect && this.isFrozen) {\n if (subMesh.effect._wasPreviouslyReady && subMesh.effect._wasPreviouslyUsingInstances === useInstances) {\n return true;\n }\n }\n if (!subMesh.materialDefines) {\n subMesh.materialDefines = new BackgroundMaterialDefines();\n }\n const scene = this.getScene();\n const defines = subMesh.materialDefines;\n if (this._isReadyForSubMesh(subMesh)) {\n return true;\n }\n const engine = scene.getEngine();\n // Lights\n MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);\n defines._needNormals = true;\n // Multiview\n MaterialHelper.PrepareDefinesForMultiview(scene, defines);\n // Textures\n if (defines._areTexturesDirty) {\n defines._needUVs = false;\n if (scene.texturesEnabled) {\n if (scene.getEngine().getCaps().textureLOD) {\n defines.TEXTURELODSUPPORT = true;\n }\n if (this._diffuseTexture && MaterialFlags.DiffuseTextureEnabled) {\n if (!this._diffuseTexture.isReadyOrNotBlocking()) {\n return false;\n }\n MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, \"DIFFUSE\");\n defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;\n defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;\n defines.OPACITYFRESNEL = this._opacityFresnel;\n }\n else {\n defines.DIFFUSE = false;\n defines.DIFFUSEDIRECTUV = 0;\n defines.DIFFUSEHASALPHA = false;\n defines.GAMMADIFFUSE = false;\n defines.OPACITYFRESNEL = false;\n }\n const reflectionTexture = this._reflectionTexture;\n if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {\n if (!reflectionTexture.isReadyOrNotBlocking()) {\n return false;\n }\n defines.REFLECTION = true;\n defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;\n defines.RGBDREFLECTION = reflectionTexture.isRGBD;\n defines.REFLECTIONBLUR = this._reflectionBlur > 0;\n defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;\n defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;\n defines.REFLECTIONBGR = this.switchToBGR;\n if (reflectionTexture.coordinatesMode === Texture.INVCUBIC_MODE) {\n defines.INVERTCUBICMAP = true;\n }\n defines.REFLECTIONMAP_3D = reflectionTexture.isCube;\n defines.REFLECTIONMAP_OPPOSITEZ = defines.REFLECTIONMAP_3D && this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;\n switch (reflectionTexture.coordinatesMode) {\n case Texture.EXPLICIT_MODE:\n defines.REFLECTIONMAP_EXPLICIT = true;\n break;\n case Texture.PLANAR_MODE:\n defines.REFLECTIONMAP_PLANAR = true;\n break;\n case Texture.PROJECTION_MODE:\n defines.REFLECTIONMAP_PROJECTION = true;\n break;\n case Texture.SKYBOX_MODE:\n defines.REFLECTIONMAP_SKYBOX = true;\n break;\n case Texture.SPHERICAL_MODE:\n defines.REFLECTIONMAP_SPHERICAL = true;\n break;\n case Texture.EQUIRECTANGULAR_MODE:\n defines.REFLECTIONMAP_EQUIRECTANGULAR = true;\n break;\n case Texture.FIXED_EQUIRECTANGULAR_MODE:\n defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;\n break;\n case Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:\n defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;\n break;\n case Texture.CUBIC_MODE:\n case Texture.INVCUBIC_MODE:\n default:\n defines.REFLECTIONMAP_CUBIC = true;\n break;\n }\n if (this.reflectionFresnel) {\n defines.REFLECTIONFRESNEL = true;\n defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;\n this._reflectionControls.x = this.reflectionAmount;\n this._reflectionControls.y = this.reflectionReflectance0;\n this._reflectionControls.z = this.reflectionReflectance90;\n this._reflectionControls.w = 1 / this.reflectionFalloffDistance;\n }\n else {\n defines.REFLECTIONFRESNEL = false;\n defines.REFLECTIONFALLOFF = false;\n }\n }\n else {\n defines.REFLECTION = false;\n defines.REFLECTIONFRESNEL = false;\n defines.REFLECTIONFALLOFF = false;\n defines.REFLECTIONBLUR = false;\n defines.REFLECTIONMAP_3D = false;\n defines.REFLECTIONMAP_SPHERICAL = false;\n defines.REFLECTIONMAP_PLANAR = false;\n defines.REFLECTIONMAP_CUBIC = false;\n defines.REFLECTIONMAP_PROJECTION = false;\n defines.REFLECTIONMAP_SKYBOX = false;\n defines.REFLECTIONMAP_EXPLICIT = false;\n defines.REFLECTIONMAP_EQUIRECTANGULAR = false;\n defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;\n defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;\n defines.INVERTCUBICMAP = false;\n defines.REFLECTIONMAP_OPPOSITEZ = false;\n defines.LODINREFLECTIONALPHA = false;\n defines.GAMMAREFLECTION = false;\n defines.RGBDREFLECTION = false;\n }\n }\n defines.PREMULTIPLYALPHA = this.alphaMode === 7 || this.alphaMode === 8;\n defines.USERGBCOLOR = this._useRGBColor;\n defines.NOISE = this._enableNoise;\n }\n if (defines._areLightsDirty) {\n defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);\n defines.BACKMAT_SHADOWONLY = this._shadowOnly;\n }\n if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {\n if (!this._imageProcessingConfiguration.isReady()) {\n return false;\n }\n this._imageProcessingConfiguration.prepareDefines(defines);\n }\n // Misc.\n MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);\n // Values that need to be evaluated on every frame\n MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, this, defines, useInstances, null, subMesh.getRenderingMesh().hasThinInstances);\n // Attribs\n if (MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {\n if (mesh) {\n if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {\n mesh.createNormals(true);\n Logger.Warn(\"BackgroundMaterial: Normals have been created for the mesh: \" + mesh.name);\n }\n }\n }\n // Get correct effect\n if (defines.isDirty) {\n defines.markAsProcessed();\n scene.resetCachedMaterial();\n // Fallbacks\n const fallbacks = new EffectFallbacks();\n if (defines.FOG) {\n fallbacks.addFallback(0, \"FOG\");\n }\n if (defines.POINTSIZE) {\n fallbacks.addFallback(1, \"POINTSIZE\");\n }\n if (defines.MULTIVIEW) {\n fallbacks.addFallback(0, \"MULTIVIEW\");\n }\n MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);\n //Attributes\n const attribs = [VertexBuffer.PositionKind];\n if (defines.NORMAL) {\n attribs.push(VertexBuffer.NormalKind);\n }\n if (defines.UV1) {\n attribs.push(VertexBuffer.UVKind);\n }\n if (defines.UV2) {\n attribs.push(VertexBuffer.UV2Kind);\n }\n MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);\n MaterialHelper.PrepareAttributesForInstances(attribs, defines);\n const uniforms = [\n \"world\",\n \"view\",\n \"viewProjection\",\n \"vEyePosition\",\n \"vLightsType\",\n \"vFogInfos\",\n \"vFogColor\",\n \"pointSize\",\n \"mBones\",\n \"vPrimaryColor\",\n \"vPrimaryColorShadow\",\n \"vReflectionInfos\",\n \"reflectionMatrix\",\n \"vReflectionMicrosurfaceInfos\",\n \"fFovMultiplier\",\n \"shadowLevel\",\n \"alpha\",\n \"vBackgroundCenter\",\n \"vReflectionControl\",\n \"vDiffuseInfos\",\n \"diffuseMatrix\",\n ];\n addClipPlaneUniforms(uniforms);\n const samplers = [\"diffuseSampler\", \"reflectionSampler\", \"reflectionSamplerLow\", \"reflectionSamplerHigh\"];\n const uniformBuffers = [\"Material\", \"Scene\"];\n if (ImageProcessingConfiguration) {\n ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);\n ImageProcessingConfiguration.PrepareSamplers(samplers, defines);\n }\n MaterialHelper.PrepareUniformsAndSamplersList({\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: defines,\n maxSimultaneousLights: this._maxSimultaneousLights,\n });\n const join = defines.toString();\n const effect = scene.getEngine().createEffect(\"background\", {\n attributes: attribs,\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: join,\n fallbacks: fallbacks,\n onCompiled: this.onCompiled,\n onError: this.onError,\n indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights },\n }, engine);\n subMesh.setEffect(effect, defines, this._materialContext);\n this.buildUniformLayout();\n }\n if (!subMesh.effect || !subMesh.effect.isReady()) {\n return false;\n }\n defines._renderId = scene.getRenderId();\n subMesh.effect._wasPreviouslyReady = true;\n subMesh.effect._wasPreviouslyUsingInstances = useInstances;\n this._checkScenePerformancePriority();\n return true;\n }\n /**\n * Compute the primary color according to the chosen perceptual color.\n */\n _computePrimaryColorFromPerceptualColor() {\n if (!this.__perceptualColor) {\n return;\n }\n this._primaryColor.copyFrom(this.__perceptualColor);\n // Revert gamma space.\n this._primaryColor.toLinearSpaceToRef(this._primaryColor, this.getScene().getEngine().useExactSrgbConversions);\n // Revert image processing configuration.\n if (this._imageProcessingConfiguration) {\n // Revert Exposure.\n this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);\n }\n this._computePrimaryColors();\n }\n /**\n * Compute the highlights and shadow colors according to their chosen levels.\n */\n _computePrimaryColors() {\n if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {\n return;\n }\n // Find the highlight color based on the configuration.\n this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);\n this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);\n // Find the shadow color based on the configuration.\n this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);\n this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);\n this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);\n }\n /**\n * Build the uniform buffer used in the material.\n */\n buildUniformLayout() {\n // Order is important !\n this._uniformBuffer.addUniform(\"vPrimaryColor\", 4);\n this._uniformBuffer.addUniform(\"vPrimaryColorShadow\", 4);\n this._uniformBuffer.addUniform(\"vDiffuseInfos\", 2);\n this._uniformBuffer.addUniform(\"vReflectionInfos\", 2);\n this._uniformBuffer.addUniform(\"diffuseMatrix\", 16);\n this._uniformBuffer.addUniform(\"reflectionMatrix\", 16);\n this._uniformBuffer.addUniform(\"vReflectionMicrosurfaceInfos\", 3);\n this._uniformBuffer.addUniform(\"fFovMultiplier\", 1);\n this._uniformBuffer.addUniform(\"pointSize\", 1);\n this._uniformBuffer.addUniform(\"shadowLevel\", 1);\n this._uniformBuffer.addUniform(\"alpha\", 1);\n this._uniformBuffer.addUniform(\"vBackgroundCenter\", 3);\n this._uniformBuffer.addUniform(\"vReflectionControl\", 4);\n this._uniformBuffer.create();\n }\n /**\n * Unbind the material.\n */\n unbind() {\n if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {\n this._uniformBuffer.setTexture(\"diffuseSampler\", null);\n }\n if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {\n this._uniformBuffer.setTexture(\"reflectionSampler\", null);\n }\n super.unbind();\n }\n /**\n * Bind only the world matrix to the material.\n * @param world The world matrix to bind.\n */\n bindOnlyWorldMatrix(world) {\n this._activeEffect.setMatrix(\"world\", world);\n }\n /**\n * Bind the material for a dedicated submeh (every used meshes will be considered opaque).\n * @param world The world matrix to bind.\n * @param mesh\n * @param subMesh The submesh to bind for.\n */\n bindForSubMesh(world, mesh, subMesh) {\n const scene = this.getScene();\n const defines = subMesh.materialDefines;\n if (!defines) {\n return;\n }\n const effect = subMesh.effect;\n if (!effect) {\n return;\n }\n this._activeEffect = effect;\n // Matrices\n this.bindOnlyWorldMatrix(world);\n // Bones\n MaterialHelper.BindBonesParameters(mesh, this._activeEffect);\n const mustRebind = this._mustRebind(scene, effect, mesh.visibility);\n if (mustRebind) {\n this._uniformBuffer.bindToEffect(effect, \"Material\");\n this.bindViewProjection(effect);\n const reflectionTexture = this._reflectionTexture;\n if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {\n // Texture uniforms\n if (scene.texturesEnabled) {\n if (this._diffuseTexture && MaterialFlags.DiffuseTextureEnabled) {\n this._uniformBuffer.updateFloat2(\"vDiffuseInfos\", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);\n MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, \"diffuse\");\n }\n if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {\n this._uniformBuffer.updateMatrix(\"reflectionMatrix\", reflectionTexture.getReflectionTextureMatrix());\n this._uniformBuffer.updateFloat2(\"vReflectionInfos\", reflectionTexture.level, this._reflectionBlur);\n this._uniformBuffer.updateFloat3(\"vReflectionMicrosurfaceInfos\", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);\n }\n }\n if (this.shadowLevel > 0) {\n this._uniformBuffer.updateFloat(\"shadowLevel\", this.shadowLevel);\n }\n this._uniformBuffer.updateFloat(\"alpha\", this.alpha);\n // Point size\n if (this.pointsCloud) {\n this._uniformBuffer.updateFloat(\"pointSize\", this.pointSize);\n }\n if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {\n this._uniformBuffer.updateColor4(\"vPrimaryColor\", this._primaryHighlightColor, 1.0);\n this._uniformBuffer.updateColor4(\"vPrimaryColorShadow\", this._primaryShadowColor, 1.0);\n }\n else {\n this._uniformBuffer.updateColor4(\"vPrimaryColor\", this._primaryColor, 1.0);\n }\n }\n this._uniformBuffer.updateFloat(\"fFovMultiplier\", this._fovMultiplier);\n // Textures\n if (scene.texturesEnabled) {\n if (this._diffuseTexture && MaterialFlags.DiffuseTextureEnabled) {\n this._uniformBuffer.setTexture(\"diffuseSampler\", this._diffuseTexture);\n }\n if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {\n if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {\n this._uniformBuffer.setTexture(\"reflectionSampler\", reflectionTexture);\n }\n else if (!defines.REFLECTIONBLUR) {\n this._uniformBuffer.setTexture(\"reflectionSampler\", reflectionTexture);\n }\n else {\n this._uniformBuffer.setTexture(\"reflectionSampler\", reflectionTexture._lodTextureMid || reflectionTexture);\n this._uniformBuffer.setTexture(\"reflectionSamplerLow\", reflectionTexture._lodTextureLow || reflectionTexture);\n this._uniformBuffer.setTexture(\"reflectionSamplerHigh\", reflectionTexture._lodTextureHigh || reflectionTexture);\n }\n if (defines.REFLECTIONFRESNEL) {\n this._uniformBuffer.updateFloat3(\"vBackgroundCenter\", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);\n this._uniformBuffer.updateFloat4(\"vReflectionControl\", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);\n }\n }\n }\n // Clip plane\n bindClipPlane(this._activeEffect, this, scene);\n scene.bindEyePosition(effect);\n }\n else if (scene.getEngine()._features.needToAlwaysBindUniformBuffers) {\n this._uniformBuffer.bindToEffect(effect, \"Material\");\n this._needToBindSceneUbo = true;\n }\n if (mustRebind || !this.isFrozen) {\n if (scene.lightsEnabled) {\n MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights);\n }\n // View\n this.bindView(effect);\n // Fog\n MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);\n // image processing\n if (this._imageProcessingConfiguration) {\n this._imageProcessingConfiguration.bind(this._activeEffect);\n }\n }\n this._afterBind(mesh, this._activeEffect);\n this._uniformBuffer.update();\n }\n /**\n * Checks to see if a texture is used in the material.\n * @param texture - Base texture to use.\n * @returns - Boolean specifying if a texture is used in the material.\n */\n hasTexture(texture) {\n if (super.hasTexture(texture)) {\n return true;\n }\n if (this._reflectionTexture === texture) {\n return true;\n }\n if (this._diffuseTexture === texture) {\n return true;\n }\n return false;\n }\n /**\n * Dispose the material.\n * @param forceDisposeEffect Force disposal of the associated effect.\n * @param forceDisposeTextures Force disposal of the associated textures.\n */\n dispose(forceDisposeEffect = false, forceDisposeTextures = false) {\n if (forceDisposeTextures) {\n if (this.diffuseTexture) {\n this.diffuseTexture.dispose();\n }\n if (this.reflectionTexture) {\n this.reflectionTexture.dispose();\n }\n }\n this._renderTargets.dispose();\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n super.dispose(forceDisposeEffect);\n }\n /**\n * Clones the material.\n * @param name The cloned name.\n * @returns The cloned material.\n */\n clone(name) {\n return SerializationHelper.Clone(() => new BackgroundMaterial(name, this.getScene()), this);\n }\n /**\n * Serializes the current material to its JSON representation.\n * @returns The JSON representation.\n */\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.customType = \"BABYLON.BackgroundMaterial\";\n return serializationObject;\n }\n /**\n * Gets the class name of the material\n * @returns \"BackgroundMaterial\"\n */\n getClassName() {\n return \"BackgroundMaterial\";\n }\n /**\n * Parse a JSON input to create back a background material.\n * @param source The JSON data to parse\n * @param scene The scene to create the parsed material in\n * @param rootUrl The root url of the assets the material depends upon\n * @returns the instantiated BackgroundMaterial.\n */\n static Parse(source, scene, rootUrl) {\n return SerializationHelper.Parse(() => new BackgroundMaterial(source.name, scene), source, scene, rootUrl);\n }\n}\n/**\n * Standard reflectance value at parallel view angle.\n */\nBackgroundMaterial.StandardReflectance0 = 0.05;\n/**\n * Standard reflectance value at grazing angle.\n */\nBackgroundMaterial.StandardReflectance90 = 0.5;\n__decorate([\n serializeAsColor3()\n], BackgroundMaterial.prototype, \"_primaryColor\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n], BackgroundMaterial.prototype, \"primaryColor\", void 0);\n__decorate([\n serializeAsColor3()\n], BackgroundMaterial.prototype, \"__perceptualColor\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_primaryColorShadowLevel\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_primaryColorHighlightLevel\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n], BackgroundMaterial.prototype, \"primaryColorHighlightLevel\", null);\n__decorate([\n serializeAsTexture()\n], BackgroundMaterial.prototype, \"_reflectionTexture\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"reflectionTexture\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_reflectionBlur\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"reflectionBlur\", void 0);\n__decorate([\n serializeAsTexture()\n], BackgroundMaterial.prototype, \"_diffuseTexture\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"diffuseTexture\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"shadowLights\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_shadowLevel\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"shadowLevel\", void 0);\n__decorate([\n serializeAsVector3()\n], BackgroundMaterial.prototype, \"_sceneCenter\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"sceneCenter\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_opacityFresnel\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"opacityFresnel\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_reflectionFresnel\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"reflectionFresnel\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_reflectionFalloffDistance\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"reflectionFalloffDistance\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_reflectionAmount\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"reflectionAmount\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_reflectionReflectance0\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"reflectionReflectance0\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_reflectionReflectance90\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"reflectionReflectance90\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_useRGBColor\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"useRGBColor\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_enableNoise\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"enableNoise\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_maxSimultaneousLights\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], BackgroundMaterial.prototype, \"maxSimultaneousLights\", void 0);\n__decorate([\n serialize()\n], BackgroundMaterial.prototype, \"_shadowOnly\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n], BackgroundMaterial.prototype, \"shadowOnly\", void 0);\n__decorate([\n serializeAsImageProcessingConfiguration()\n], BackgroundMaterial.prototype, \"_imageProcessingConfiguration\", void 0);\nRegisterClass(\"BABYLON.BackgroundMaterial\", BackgroundMaterial);\n//# sourceMappingURL=backgroundMaterial.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { ArcRotateCamera } from \"../Cameras/arcRotateCamera.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Color3, Color4 } from \"../Maths/math.color.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { BaseTexture } from \"../Materials/Textures/baseTexture.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { MirrorTexture } from \"../Materials/Textures/mirrorTexture.js\";\nimport { CubeTexture } from \"../Materials/Textures/cubeTexture.js\";\nimport { BackgroundMaterial } from \"../Materials/Background/backgroundMaterial.js\";\n\nimport { CreatePlane } from \"../Meshes/Builders/planeBuilder.js\";\nimport { CreateBox } from \"../Meshes/Builders/boxBuilder.js\";\nimport { Plane } from \"../Maths/math.plane.js\";\n/**\n * The EnvironmentHelper class can be used to add a fully featured non-expensive background to your scene.\n * It includes by default a skybox and a ground relying on the BackgroundMaterial.\n * It also helps with the default setup of your ImageProcessingConfiguration.\n */\nexport class EnvironmentHelper {\n /**\n * Creates the default options for the helper.\n * @param scene The scene the environment helper belongs to.\n */\n static _GetDefaultOptions(scene) {\n return {\n createGround: true,\n groundSize: 15,\n groundTexture: this._GroundTextureCDNUrl,\n groundColor: new Color3(0.2, 0.2, 0.3).toLinearSpace(scene.getEngine().useExactSrgbConversions).scale(3),\n groundOpacity: 0.9,\n enableGroundShadow: true,\n groundShadowLevel: 0.5,\n enableGroundMirror: false,\n groundMirrorSizeRatio: 0.3,\n groundMirrorBlurKernel: 64,\n groundMirrorAmount: 1,\n groundMirrorFresnelWeight: 1,\n groundMirrorFallOffDistance: 0,\n groundMirrorTextureType: 0,\n groundYBias: 0.00001,\n createSkybox: true,\n skyboxSize: 20,\n skyboxTexture: this._SkyboxTextureCDNUrl,\n skyboxColor: new Color3(0.2, 0.2, 0.3).toLinearSpace(scene.getEngine().useExactSrgbConversions).scale(3),\n backgroundYRotation: 0,\n sizeAuto: true,\n rootPosition: Vector3.Zero(),\n setupImageProcessing: true,\n environmentTexture: this._EnvironmentTextureCDNUrl,\n cameraExposure: 0.8,\n cameraContrast: 1.2,\n toneMappingEnabled: true,\n };\n }\n /**\n * Gets the root mesh created by the helper.\n */\n get rootMesh() {\n return this._rootMesh;\n }\n /**\n * Gets the skybox created by the helper.\n */\n get skybox() {\n return this._skybox;\n }\n /**\n * Gets the skybox texture created by the helper.\n */\n get skyboxTexture() {\n return this._skyboxTexture;\n }\n /**\n * Gets the skybox material created by the helper.\n */\n get skyboxMaterial() {\n return this._skyboxMaterial;\n }\n /**\n * Gets the ground mesh created by the helper.\n */\n get ground() {\n return this._ground;\n }\n /**\n * Gets the ground texture created by the helper.\n */\n get groundTexture() {\n return this._groundTexture;\n }\n /**\n * Gets the ground mirror created by the helper.\n */\n get groundMirror() {\n return this._groundMirror;\n }\n /**\n * Gets the ground mirror render list to helps pushing the meshes\n * you wish in the ground reflection.\n */\n get groundMirrorRenderList() {\n if (this._groundMirror) {\n return this._groundMirror.renderList;\n }\n return null;\n }\n /**\n * Gets the ground material created by the helper.\n */\n get groundMaterial() {\n return this._groundMaterial;\n }\n /**\n * constructor\n * @param options Defines the options we want to customize the helper\n * @param scene The scene to add the material to\n */\n constructor(options, scene) {\n this._errorHandler = (message, exception) => {\n this.onErrorObservable.notifyObservers({ message: message, exception: exception });\n };\n this._options = Object.assign(Object.assign({}, EnvironmentHelper._GetDefaultOptions(scene)), options);\n this._scene = scene;\n this.onErrorObservable = new Observable();\n this._setupBackground();\n this._setupImageProcessing();\n }\n /**\n * Updates the background according to the new options\n * @param options\n */\n updateOptions(options) {\n const newOptions = Object.assign(Object.assign({}, this._options), options);\n if (this._ground && !newOptions.createGround) {\n this._ground.dispose();\n this._ground = null;\n }\n if (this._groundMaterial && !newOptions.createGround) {\n this._groundMaterial.dispose();\n this._groundMaterial = null;\n }\n if (this._groundTexture) {\n if (this._options.groundTexture != newOptions.groundTexture) {\n this._groundTexture.dispose();\n this._groundTexture = null;\n }\n }\n if (this._skybox && !newOptions.createSkybox) {\n this._skybox.dispose();\n this._skybox = null;\n }\n if (this._skyboxMaterial && !newOptions.createSkybox) {\n this._skyboxMaterial.dispose();\n this._skyboxMaterial = null;\n }\n if (this._skyboxTexture) {\n if (this._options.skyboxTexture != newOptions.skyboxTexture) {\n this._skyboxTexture.dispose();\n this._skyboxTexture = null;\n }\n }\n if (this._groundMirror && !newOptions.enableGroundMirror) {\n this._groundMirror.dispose();\n this._groundMirror = null;\n }\n if (this._scene.environmentTexture) {\n if (this._options.environmentTexture != newOptions.environmentTexture) {\n this._scene.environmentTexture.dispose();\n }\n }\n this._options = newOptions;\n this._setupBackground();\n this._setupImageProcessing();\n }\n /**\n * Sets the primary color of all the available elements.\n * @param color the main color to affect to the ground and the background\n */\n setMainColor(color) {\n if (this.groundMaterial) {\n this.groundMaterial.primaryColor = color;\n }\n if (this.skyboxMaterial) {\n this.skyboxMaterial.primaryColor = color;\n }\n if (this.groundMirror) {\n this.groundMirror.clearColor = new Color4(color.r, color.g, color.b, 1.0);\n }\n }\n /**\n * Setup the image processing according to the specified options.\n */\n _setupImageProcessing() {\n if (this._options.setupImageProcessing) {\n this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;\n this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;\n this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;\n this._setupEnvironmentTexture();\n }\n }\n /**\n * Setup the environment texture according to the specified options.\n */\n _setupEnvironmentTexture() {\n if (this._scene.environmentTexture) {\n return;\n }\n if (this._options.environmentTexture instanceof BaseTexture) {\n this._scene.environmentTexture = this._options.environmentTexture;\n return;\n }\n const environmentTexture = CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);\n this._scene.environmentTexture = environmentTexture;\n }\n /**\n * Setup the background according to the specified options.\n */\n _setupBackground() {\n if (!this._rootMesh) {\n this._rootMesh = new Mesh(\"BackgroundHelper\", this._scene);\n }\n this._rootMesh.rotation.y = this._options.backgroundYRotation;\n const sceneSize = this._getSceneSize();\n if (this._options.createGround) {\n this._setupGround(sceneSize);\n this._setupGroundMaterial();\n this._setupGroundDiffuseTexture();\n if (this._options.enableGroundMirror) {\n this._setupGroundMirrorTexture(sceneSize);\n }\n this._setupMirrorInGroundMaterial();\n }\n if (this._options.createSkybox) {\n this._setupSkybox(sceneSize);\n this._setupSkyboxMaterial();\n this._setupSkyboxReflectionTexture();\n }\n this._rootMesh.position.x = sceneSize.rootPosition.x;\n this._rootMesh.position.z = sceneSize.rootPosition.z;\n this._rootMesh.position.y = sceneSize.rootPosition.y;\n }\n /**\n * Get the scene sizes according to the setup.\n */\n _getSceneSize() {\n let groundSize = this._options.groundSize;\n let skyboxSize = this._options.skyboxSize;\n let rootPosition = this._options.rootPosition;\n if (!this._scene.meshes || this._scene.meshes.length === 1) {\n // 1 only means the root of the helper.\n return { groundSize, skyboxSize, rootPosition };\n }\n const sceneExtends = this._scene.getWorldExtends((mesh) => {\n return mesh !== this._ground && mesh !== this._rootMesh && mesh !== this._skybox;\n });\n const sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);\n if (this._options.sizeAuto) {\n if (this._scene.activeCamera instanceof ArcRotateCamera && this._scene.activeCamera.upperRadiusLimit) {\n groundSize = this._scene.activeCamera.upperRadiusLimit * 2;\n skyboxSize = groundSize;\n }\n const sceneDiagonalLenght = sceneDiagonal.length();\n if (sceneDiagonalLenght > groundSize) {\n groundSize = sceneDiagonalLenght * 2;\n skyboxSize = groundSize;\n }\n // 10 % bigger.\n groundSize *= 1.1;\n skyboxSize *= 1.5;\n rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));\n rootPosition.y = sceneExtends.min.y - this._options.groundYBias;\n }\n return { groundSize, skyboxSize, rootPosition };\n }\n /**\n * Setup the ground according to the specified options.\n * @param sceneSize\n */\n _setupGround(sceneSize) {\n if (!this._ground || this._ground.isDisposed()) {\n this._ground = CreatePlane(\"BackgroundPlane\", { size: sceneSize.groundSize }, this._scene);\n this._ground.rotation.x = Math.PI / 2; // Face up by default.\n this._ground.parent = this._rootMesh;\n this._ground.onDisposeObservable.add(() => {\n this._ground = null;\n });\n }\n this._ground.receiveShadows = this._options.enableGroundShadow;\n }\n /**\n * Setup the ground material according to the specified options.\n */\n _setupGroundMaterial() {\n if (!this._groundMaterial) {\n this._groundMaterial = new BackgroundMaterial(\"BackgroundPlaneMaterial\", this._scene);\n }\n this._groundMaterial.alpha = this._options.groundOpacity;\n this._groundMaterial.alphaMode = 8;\n this._groundMaterial.shadowLevel = this._options.groundShadowLevel;\n this._groundMaterial.primaryColor = this._options.groundColor;\n this._groundMaterial.useRGBColor = false;\n this._groundMaterial.enableNoise = true;\n if (this._ground) {\n this._ground.material = this._groundMaterial;\n }\n }\n /**\n * Setup the ground diffuse texture according to the specified options.\n */\n _setupGroundDiffuseTexture() {\n if (!this._groundMaterial) {\n return;\n }\n if (this._groundTexture) {\n return;\n }\n if (this._options.groundTexture instanceof BaseTexture) {\n this._groundMaterial.diffuseTexture = this._options.groundTexture;\n return;\n }\n this._groundTexture = new Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);\n this._groundTexture.gammaSpace = false;\n this._groundTexture.hasAlpha = true;\n this._groundMaterial.diffuseTexture = this._groundTexture;\n }\n /**\n * Setup the ground mirror texture according to the specified options.\n * @param sceneSize\n */\n _setupGroundMirrorTexture(sceneSize) {\n const wrapping = Texture.CLAMP_ADDRESSMODE;\n if (!this._groundMirror) {\n this._groundMirror = new MirrorTexture(\"BackgroundPlaneMirrorTexture\", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, Texture.BILINEAR_SAMPLINGMODE, true);\n this._groundMirror.mirrorPlane = new Plane(0, -1, 0, sceneSize.rootPosition.y);\n this._groundMirror.anisotropicFilteringLevel = 1;\n this._groundMirror.wrapU = wrapping;\n this._groundMirror.wrapV = wrapping;\n if (this._groundMirror.renderList) {\n for (let i = 0; i < this._scene.meshes.length; i++) {\n const mesh = this._scene.meshes[i];\n if (mesh !== this._ground && mesh !== this._skybox && mesh !== this._rootMesh) {\n this._groundMirror.renderList.push(mesh);\n }\n }\n }\n }\n const gammaGround = this._options.groundColor.toGammaSpace(this._scene.getEngine().useExactSrgbConversions);\n this._groundMirror.clearColor = new Color4(gammaGround.r, gammaGround.g, gammaGround.b, 1);\n this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;\n }\n /**\n * Setup the ground to receive the mirror texture.\n */\n _setupMirrorInGroundMaterial() {\n if (this._groundMaterial) {\n this._groundMaterial.reflectionTexture = this._groundMirror;\n this._groundMaterial.reflectionFresnel = true;\n this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;\n this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;\n this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;\n }\n }\n /**\n * Setup the skybox according to the specified options.\n * @param sceneSize\n */\n _setupSkybox(sceneSize) {\n if (!this._skybox || this._skybox.isDisposed()) {\n this._skybox = CreateBox(\"BackgroundSkybox\", { size: sceneSize.skyboxSize, sideOrientation: Mesh.BACKSIDE }, this._scene);\n this._skybox.onDisposeObservable.add(() => {\n this._skybox = null;\n });\n }\n this._skybox.parent = this._rootMesh;\n }\n /**\n * Setup the skybox material according to the specified options.\n */\n _setupSkyboxMaterial() {\n if (!this._skybox) {\n return;\n }\n if (!this._skyboxMaterial) {\n this._skyboxMaterial = new BackgroundMaterial(\"BackgroundSkyboxMaterial\", this._scene);\n }\n this._skyboxMaterial.useRGBColor = false;\n this._skyboxMaterial.primaryColor = this._options.skyboxColor;\n this._skyboxMaterial.enableNoise = true;\n this._skybox.material = this._skyboxMaterial;\n }\n /**\n * Setup the skybox reflection texture according to the specified options.\n */\n _setupSkyboxReflectionTexture() {\n if (!this._skyboxMaterial) {\n return;\n }\n if (this._skyboxTexture) {\n return;\n }\n if (this._options.skyboxTexture instanceof BaseTexture) {\n this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;\n return;\n }\n this._skyboxTexture = new CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);\n this._skyboxTexture.coordinatesMode = Texture.SKYBOX_MODE;\n this._skyboxTexture.gammaSpace = false;\n this._skyboxMaterial.reflectionTexture = this._skyboxTexture;\n }\n /**\n * Dispose all the elements created by the Helper.\n */\n dispose() {\n if (this._groundMaterial) {\n this._groundMaterial.dispose(true, true);\n }\n if (this._skyboxMaterial) {\n this._skyboxMaterial.dispose(true, true);\n }\n this._rootMesh.dispose(false);\n }\n}\n/**\n * Default ground texture URL.\n */\nEnvironmentHelper._GroundTextureCDNUrl = \"https://assets.babylonjs.com/environments/backgroundGround.png\";\n/**\n * Default skybox texture URL.\n */\nEnvironmentHelper._SkyboxTextureCDNUrl = \"https://assets.babylonjs.com/environments/backgroundSkybox.dds\";\n/**\n * Default environment texture URL.\n */\nEnvironmentHelper._EnvironmentTextureCDNUrl = \"https://assets.babylonjs.com/environments/environmentSpecular.env\";\n//# sourceMappingURL=environmentHelper.js.map","import { TransformNode } from \"../Meshes/transformNode.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { BackgroundMaterial } from \"../Materials/Background/backgroundMaterial.js\";\nimport { CreateSphere } from \"../Meshes/Builders/sphereBuilder.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Axis } from \"../Maths/math.js\";\n/**\n * Display a 360/180 degree texture on an approximately spherical surface, useful for VR applications or skyboxes.\n * As a subclass of TransformNode, this allow parenting to the camera or multiple textures with different locations in the scene.\n * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.\n * Potential additions to this helper include zoom and and non-infinite distance rendering effects.\n */\nexport class TextureDome extends TransformNode {\n /**\n * Gets the texture being displayed on the sphere\n */\n get texture() {\n return this._texture;\n }\n /**\n * Sets the texture being displayed on the sphere\n */\n set texture(newTexture) {\n if (this._texture === newTexture) {\n return;\n }\n this._texture = newTexture;\n if (this._useDirectMapping) {\n this._texture.wrapU = Texture.CLAMP_ADDRESSMODE;\n this._texture.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._material.diffuseTexture = this._texture;\n }\n else {\n this._texture.coordinatesMode = Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation\n this._texture.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._material.reflectionTexture = this._texture;\n }\n this._changeTextureMode(this._textureMode);\n }\n /**\n * Gets the mesh used for the dome.\n */\n get mesh() {\n return this._mesh;\n }\n /**\n * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values \"zoom in\" and higher values \"zoom out\".\n * Also see the options.resolution property.\n */\n get fovMultiplier() {\n return this._material.fovMultiplier;\n }\n set fovMultiplier(value) {\n this._material.fovMultiplier = value;\n }\n /**\n * Gets or set the current texture mode for the texture. It can be:\n * * TextureDome.MODE_MONOSCOPIC : Define the texture source as a Monoscopic panoramic 360.\n * * TextureDome.MODE_TOPBOTTOM : Define the texture source as a Stereoscopic TopBottom/OverUnder panoramic 360.\n * * TextureDome.MODE_SIDEBYSIDE : Define the texture source as a Stereoscopic Side by Side panoramic 360.\n */\n get textureMode() {\n return this._textureMode;\n }\n /**\n * Sets the current texture mode for the texture. It can be:\n * * TextureDome.MODE_MONOSCOPIC : Define the texture source as a Monoscopic panoramic 360.\n * * TextureDome.MODE_TOPBOTTOM : Define the texture source as a Stereoscopic TopBottom/OverUnder panoramic 360.\n * * TextureDome.MODE_SIDEBYSIDE : Define the texture source as a Stereoscopic Side by Side panoramic 360.\n */\n set textureMode(value) {\n if (this._textureMode === value) {\n return;\n }\n this._changeTextureMode(value);\n }\n /**\n * Is it a 180 degrees dome (half dome) or 360 texture (full dome)\n */\n get halfDome() {\n return this._halfDome;\n }\n /**\n * Set the halfDome mode. If set, only the front (180 degrees) will be displayed and the back will be blacked out.\n */\n set halfDome(enabled) {\n this._halfDome = enabled;\n this._halfDomeMask.setEnabled(enabled);\n this._changeTextureMode(this._textureMode);\n }\n /**\n * Set the cross-eye mode. If set, images that can be seen when crossing eyes will render correctly\n */\n set crossEye(enabled) {\n this._crossEye = enabled;\n this._changeTextureMode(this._textureMode);\n }\n /**\n * Is it a cross-eye texture?\n */\n get crossEye() {\n return this._crossEye;\n }\n /**\n * The background material of this dome.\n */\n get material() {\n return this._material;\n }\n /**\n * Create an instance of this class and pass through the parameters to the relevant classes- Texture, StandardMaterial, and Mesh.\n * @param name Element's name, child elements will append suffixes for their own names.\n * @param textureUrlOrElement defines the url(s) or the (video) HTML element to use\n * @param options An object containing optional or exposed sub element properties\n * @param options.resolution\n * @param options.clickToPlay\n * @param options.autoPlay\n * @param options.loop\n * @param options.size\n * @param options.poster\n * @param options.faceForward\n * @param options.useDirectMapping\n * @param options.halfDomeMode\n * @param options.crossEyeMode\n * @param options.generateMipMaps\n * @param options.mesh\n * @param scene\n * @param onError\n */\n constructor(name, textureUrlOrElement, options, scene, \n // eslint-disable-next-line @typescript-eslint/naming-convention\n onError = null) {\n super(name, scene);\n this.onError = onError;\n this._halfDome = false;\n this._crossEye = false;\n this._useDirectMapping = false;\n this._textureMode = TextureDome.MODE_MONOSCOPIC;\n /**\n * Oberserver used in Stereoscopic VR Mode.\n */\n this._onBeforeCameraRenderObserver = null;\n /**\n * Observable raised when an error occurred while loading the texture\n */\n this.onLoadErrorObservable = new Observable();\n /**\n * Observable raised when the texture finished loading\n */\n this.onLoadObservable = new Observable();\n scene = this.getScene();\n // set defaults and manage values\n name = name || \"textureDome\";\n options.resolution = Math.abs(options.resolution) | 0 || 32;\n options.clickToPlay = Boolean(options.clickToPlay);\n options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);\n options.loop = options.loop === undefined ? true : Boolean(options.loop);\n options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);\n if (options.useDirectMapping === undefined) {\n this._useDirectMapping = true;\n }\n else {\n this._useDirectMapping = options.useDirectMapping;\n }\n if (options.faceForward === undefined) {\n options.faceForward = true;\n }\n this._setReady(false);\n if (!options.mesh) {\n this._mesh = CreateSphere(name + \"_mesh\", { segments: options.resolution, diameter: options.size, updatable: false, sideOrientation: Mesh.BACKSIDE }, scene);\n }\n else {\n this._mesh = options.mesh;\n }\n // configure material\n const material = (this._material = new BackgroundMaterial(name + \"_material\", scene));\n material.useEquirectangularFOV = true;\n material.fovMultiplier = 1.0;\n material.opacityFresnel = false;\n const texture = this._initTexture(textureUrlOrElement, scene, options);\n this.texture = texture;\n // configure mesh\n this._mesh.material = material;\n this._mesh.parent = this;\n // create a (disabled until needed) mask to cover unneeded segments of 180 texture.\n this._halfDomeMask = CreateSphere(\"\", { slice: 0.5, diameter: options.size * 0.98, segments: options.resolution * 2, sideOrientation: Mesh.BACKSIDE }, scene);\n this._halfDomeMask.rotate(Axis.X, -Math.PI / 2);\n // set the parent, so it will always be positioned correctly AND will be disposed when the main sphere is disposed\n this._halfDomeMask.parent = this._mesh;\n this._halfDome = !!options.halfDomeMode;\n // enable or disable according to the settings\n this._halfDomeMask.setEnabled(this._halfDome);\n this._crossEye = !!options.crossEyeMode;\n // create\n this._texture.anisotropicFilteringLevel = 1;\n this._texture.onLoadObservable.addOnce(() => {\n this._setReady(true);\n });\n // Initial rotation\n if (options.faceForward && scene.activeCamera) {\n const camera = scene.activeCamera;\n const forward = Vector3.Forward();\n const direction = Vector3.TransformNormal(forward, camera.getViewMatrix());\n direction.normalize();\n this.rotation.y = Math.acos(Vector3.Dot(forward, direction));\n }\n this._changeTextureMode(this._textureMode);\n }\n _changeTextureMode(value) {\n this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);\n this._textureMode = value;\n // Default Setup and Reset.\n this._texture.uScale = 1;\n this._texture.vScale = 1;\n this._texture.uOffset = 0;\n this._texture.vOffset = 0;\n this._texture.vAng = 0;\n switch (value) {\n case TextureDome.MODE_MONOSCOPIC:\n if (this._halfDome) {\n this._texture.uScale = 2;\n this._texture.uOffset = -1;\n }\n break;\n case TextureDome.MODE_SIDEBYSIDE: {\n // in half-dome mode the uScale should be double of 360 texture\n // Use 0.99999 to boost perf by not switching program\n this._texture.uScale = this._halfDome ? 0.99999 : 0.5;\n const rightOffset = this._halfDome ? 0.0 : 0.5;\n const leftOffset = this._halfDome ? -0.5 : 0.0;\n this._onBeforeCameraRenderObserver = this._scene.onBeforeCameraRenderObservable.add((camera) => {\n let isRightCamera = camera.isRightCamera;\n if (this._crossEye) {\n isRightCamera = !isRightCamera;\n }\n if (isRightCamera) {\n this._texture.uOffset = rightOffset;\n }\n else {\n this._texture.uOffset = leftOffset;\n }\n });\n break;\n }\n case TextureDome.MODE_TOPBOTTOM:\n // in half-dome mode the vScale should be double of 360 texture\n // Use 0.99999 to boost perf by not switching program\n this._texture.vScale = this._halfDome ? 0.99999 : 0.5;\n this._onBeforeCameraRenderObserver = this._scene.onBeforeCameraRenderObservable.add((camera) => {\n let isRightCamera = camera.isRightCamera;\n // allow \"cross-eye\" if left and right were switched in this mode\n if (this._crossEye) {\n isRightCamera = !isRightCamera;\n }\n this._texture.vOffset = isRightCamera ? 0.5 : 0.0;\n });\n break;\n }\n }\n /**\n * Releases resources associated with this node.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n dispose(doNotRecurse, disposeMaterialAndTextures = false) {\n this._texture.dispose();\n this._mesh.dispose();\n this._material.dispose();\n this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);\n this.onLoadErrorObservable.clear();\n this.onLoadObservable.clear();\n super.dispose(doNotRecurse, disposeMaterialAndTextures);\n }\n}\n/**\n * Define the source as a Monoscopic panoramic 360/180.\n */\nTextureDome.MODE_MONOSCOPIC = 0;\n/**\n * Define the source as a Stereoscopic TopBottom/OverUnder panoramic 360/180.\n */\nTextureDome.MODE_TOPBOTTOM = 1;\n/**\n * Define the source as a Stereoscopic Side by Side panoramic 360/180.\n */\nTextureDome.MODE_SIDEBYSIDE = 2;\n//# sourceMappingURL=textureDome.js.map","import { Texture } from \"../Materials/Textures/texture.js\";\nimport { TextureDome } from \"./textureDome.js\";\n/**\n * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.\n * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.\n * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.\n * Potential additions to this helper include zoom and and non-infinite distance rendering effects.\n */\nexport class PhotoDome extends TextureDome {\n /**\n * Gets or sets the texture being displayed on the sphere\n */\n get photoTexture() {\n return this.texture;\n }\n /**\n * sets the texture being displayed on the sphere\n */\n set photoTexture(value) {\n this.texture = value;\n }\n /**\n * Gets the current video mode for the video. It can be:\n * * TextureDome.MODE_MONOSCOPIC : Define the texture source as a Monoscopic panoramic 360.\n * * TextureDome.MODE_TOPBOTTOM : Define the texture source as a Stereoscopic TopBottom/OverUnder panoramic 360.\n * * TextureDome.MODE_SIDEBYSIDE : Define the texture source as a Stereoscopic Side by Side panoramic 360.\n */\n get imageMode() {\n return this.textureMode;\n }\n /**\n * Sets the current video mode for the video. It can be:\n * * TextureDome.MODE_MONOSCOPIC : Define the texture source as a Monoscopic panoramic 360.\n * * TextureDome.MODE_TOPBOTTOM : Define the texture source as a Stereoscopic TopBottom/OverUnder panoramic 360.\n * * TextureDome.MODE_SIDEBYSIDE : Define the texture source as a Stereoscopic Side by Side panoramic 360.\n */\n set imageMode(value) {\n this.textureMode = value;\n }\n _initTexture(urlsOrElement, scene, options) {\n return new Texture(urlsOrElement, scene, !options.generateMipMaps, !this._useDirectMapping, undefined, () => {\n this.onLoadObservable.notifyObservers();\n }, (message, exception) => {\n this.onLoadErrorObservable.notifyObservers(message || \"Unknown error occured\");\n if (this.onError) {\n this.onError(message, exception);\n }\n });\n }\n}\n/**\n * Define the image as a Monoscopic panoramic 360 image.\n */\nPhotoDome.MODE_MONOSCOPIC = TextureDome.MODE_MONOSCOPIC;\n/**\n * Define the image as a Stereoscopic TopBottom/OverUnder panoramic 360 image.\n */\nPhotoDome.MODE_TOPBOTTOM = TextureDome.MODE_TOPBOTTOM;\n/**\n * Define the image as a Stereoscopic Side by Side panoramic 360 image.\n */\nPhotoDome.MODE_SIDEBYSIDE = TextureDome.MODE_SIDEBYSIDE;\n//# sourceMappingURL=photoDome.js.map","import { Texture } from \"../Materials/Textures/texture.js\";\nimport { RGBDTextureTools } from \"./rgbdTextureTools.js\";\nimport { Tools } from \"./tools.js\";\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst _environmentBRDFBase64Texture = \"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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DC1MOya3j/sAiAGcrEtqtgjBD6wEzSDc7D8o6C8rIqAZyPk+NQoNLAZ1hR64Yl1FBY648smUYKnSg1Xwk/0DyRyArByMUobyByhCcPnOaPyoegREFS4jNfYAw+IHCjdC1J2WDZBke/OyN85J24WiXwDYPoJyYuCD238ulvuzwt6KgHf0shWKsqCFFGjB/w8HU8eeTED9wAAAAABJRU5ErkJggg==\";\nlet _instanceNumber = 0;\n/**\n * Gets a default environment BRDF for MS-BRDF Height Correlated BRDF\n * @param scene defines the hosting scene\n * @returns the environment BRDF texture\n */\nexport const GetEnvironmentBRDFTexture = (scene) => {\n if (!scene.environmentBRDFTexture) {\n // Forces Delayed Texture Loading to prevent undefined error whilst setting RGBD values.\n const useDelayedTextureLoading = scene.useDelayedTextureLoading;\n scene.useDelayedTextureLoading = false;\n const previousState = scene._blockEntityCollection;\n scene._blockEntityCollection = false;\n const texture = Texture.CreateFromBase64String(_environmentBRDFBase64Texture, \"EnvironmentBRDFTexture\" + _instanceNumber++, scene, true, false, Texture.BILINEAR_SAMPLINGMODE);\n scene._blockEntityCollection = previousState;\n // BRDF Texture should not be cached here due to pre processing and redundant scene caches.\n const texturesCache = scene.getEngine().getLoadedTexturesCache();\n const index = texturesCache.indexOf(texture.getInternalTexture());\n if (index !== -1) {\n texturesCache.splice(index, 1);\n }\n texture.isRGBD = true;\n texture.wrapU = Texture.CLAMP_ADDRESSMODE;\n texture.wrapV = Texture.CLAMP_ADDRESSMODE;\n scene.environmentBRDFTexture = texture;\n scene.useDelayedTextureLoading = useDelayedTextureLoading;\n RGBDTextureTools.ExpandRGBDTexture(texture);\n const observer = scene.getEngine().onContextRestoredObservable.add(() => {\n texture.isRGBD = true;\n const checkReady = () => {\n if (texture.isReady()) {\n RGBDTextureTools.ExpandRGBDTexture(texture);\n }\n else {\n Tools.SetImmediate(checkReady);\n }\n };\n checkReady();\n });\n scene.onDisposeObservable.add(() => {\n scene.getEngine().onContextRestoredObservable.remove(observer);\n });\n }\n return scene.environmentBRDFTexture;\n};\n/**\n * Class used to host texture specific utilities\n */\nexport const BRDFTextureTools = {\n /**\n * Gets a default environment BRDF for MS-BRDF Height Correlated BRDF\n * @param scene defines the hosting scene\n * @returns the environment BRDF texture\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n GetEnvironmentBRDFTexture,\n};\n//# sourceMappingURL=brdfTextureTools.js.map","import { __decorate } from \"../../tslib.es6.js\";\n/* eslint-disable @typescript-eslint/naming-convention */\n\nimport { serialize, expandToProperty } from \"../../Misc/decorators.js\";\nimport { MaterialDefines } from \"../materialDefines.js\";\nimport { MaterialPluginBase } from \"../materialPluginBase.js\";\n/**\n * @internal\n */\nexport class MaterialBRDFDefines extends MaterialDefines {\n constructor() {\n super(...arguments);\n this.BRDF_V_HEIGHT_CORRELATED = false;\n this.MS_BRDF_ENERGY_CONSERVATION = false;\n this.SPHERICAL_HARMONICS = false;\n this.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION = false;\n }\n}\n/**\n * Plugin that implements the BRDF component of the PBR material\n */\nexport class PBRBRDFConfiguration extends MaterialPluginBase {\n /** @internal */\n _markAllSubMeshesAsMiscDirty() {\n this._internalMarkAllSubMeshesAsMiscDirty();\n }\n constructor(material, addToPluginList = true) {\n super(material, \"PBRBRDF\", 90, new MaterialBRDFDefines(), addToPluginList);\n this._useEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION;\n /**\n * Defines if the material uses energy conservation.\n */\n this.useEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION;\n this._useSmithVisibilityHeightCorrelated = PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED;\n /**\n * LEGACY Mode set to false\n * Defines if the material uses height smith correlated visibility term.\n * If you intent to not use our default BRDF, you need to load a separate BRDF Texture for the PBR\n * You can either load https://assets.babylonjs.com/environments/uncorrelatedBRDF.png\n * or https://assets.babylonjs.com/environments/uncorrelatedBRDF.dds to have more precision\n * Not relying on height correlated will also disable energy conservation.\n */\n this.useSmithVisibilityHeightCorrelated = PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED;\n this._useSphericalHarmonics = PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS;\n /**\n * LEGACY Mode set to false\n * Defines if the material uses spherical harmonics vs spherical polynomials for the\n * diffuse part of the IBL.\n * The harmonics despite a tiny bigger cost has been proven to provide closer results\n * to the ground truth.\n */\n this.useSphericalHarmonics = PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS;\n this._useSpecularGlossinessInputEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION;\n /**\n * Defines if the material uses energy conservation, when the specular workflow is active.\n * If activated, the albedo color is multiplied with (1. - maxChannel(specular color)).\n * If deactivated, a material is only physically plausible, when (albedo color + specular color) < 1.\n * In the deactivated case, the material author has to ensure energy conservation, for a physically plausible rendering.\n */\n this.useSpecularGlossinessInputEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION;\n this._internalMarkAllSubMeshesAsMiscDirty = material._dirtyCallbacks[16];\n this._enable(true);\n }\n prepareDefines(defines) {\n defines.BRDF_V_HEIGHT_CORRELATED = this._useSmithVisibilityHeightCorrelated;\n defines.MS_BRDF_ENERGY_CONSERVATION = this._useEnergyConservation && this._useSmithVisibilityHeightCorrelated;\n defines.SPHERICAL_HARMONICS = this._useSphericalHarmonics;\n defines.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION = this._useSpecularGlossinessInputEnergyConservation;\n }\n getClassName() {\n return \"PBRBRDFConfiguration\";\n }\n}\n/**\n * Default value used for the energy conservation.\n * This should only be changed to adapt to the type of texture in scene.environmentBRDFTexture.\n */\nPBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION = true;\n/**\n * Default value used for the Smith Visibility Height Correlated mode.\n * This should only be changed to adapt to the type of texture in scene.environmentBRDFTexture.\n */\nPBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED = true;\n/**\n * Default value used for the IBL diffuse part.\n * This can help switching back to the polynomials mode globally which is a tiny bit\n * less GPU intensive at the drawback of a lower quality.\n */\nPBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS = true;\n/**\n * Default value used for activating energy conservation for the specular workflow.\n * If activated, the albedo color is multiplied with (1. - maxChannel(specular color)).\n * If deactivated, a material is only physically plausible, when (albedo color + specular color) < 1.\n */\nPBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION = true;\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsMiscDirty\")\n], PBRBRDFConfiguration.prototype, \"useEnergyConservation\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsMiscDirty\")\n], PBRBRDFConfiguration.prototype, \"useSmithVisibilityHeightCorrelated\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsMiscDirty\")\n], PBRBRDFConfiguration.prototype, \"useSphericalHarmonics\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsMiscDirty\")\n], PBRBRDFConfiguration.prototype, \"useSpecularGlossinessInputEnergyConservation\", void 0);\n//# sourceMappingURL=pbrBRDFConfiguration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nimport \"./decalFragmentDeclaration.js\";\nconst name = \"pbrFragmentDeclaration\";\nconst shader = `uniform vec4 vEyePosition;\runiform vec3 vReflectionColor;\runiform vec4 vAlbedoColor;\runiform vec4 vLightingIntensity;\runiform vec4 vReflectivityColor;\runiform vec4 vMetallicReflectanceFactors;\runiform vec3 vEmissiveColor;\runiform float visibility;\runiform vec3 vAmbientColor;\r#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\r#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\r#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\runiform vec2 vTangentSpaceParams;\r#endif\n#ifdef OPACITY\nuniform vec2 vOpacityInfos;\r#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\r#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\r#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\r#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\r#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS)\nuniform mat4 view;\r#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\r#ifdef REALTIME_FILTERING\nuniform vec2 vReflectionFilteringInfo;\r#endif\nuniform mat4 reflectionMatrix;\runiform vec3 vReflectionMicrosurfaceInfos;\r#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\runiform vec3 vReflectionSize; \r#endif\n#endif\n#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC)\nuniform vec3 vRefractionPosition;\runiform vec3 vRefractionSize; \r#endif\n#ifdef CLEARCOAT\nuniform vec2 vClearCoatParams;\runiform vec4 vClearCoatRefractionParams;\r#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform vec4 vClearCoatInfos;\r#endif\n#ifdef CLEARCOAT_TEXTURE\nuniform mat4 clearCoatMatrix;\r#endif\n#ifdef CLEARCOAT_TEXTURE_ROUGHNESS\nuniform mat4 clearCoatRoughnessMatrix;\r#endif\n#ifdef CLEARCOAT_BUMP\nuniform vec2 vClearCoatBumpInfos;\runiform vec2 vClearCoatTangentSpaceParams;\runiform mat4 clearCoatBumpMatrix;\r#endif\n#ifdef CLEARCOAT_TINT\nuniform vec4 vClearCoatTintParams;\runiform float clearCoatColorAtDistance;\r#ifdef CLEARCOAT_TINT_TEXTURE\nuniform vec2 vClearCoatTintInfos;\runiform mat4 clearCoatTintMatrix;\r#endif\n#endif\n#endif\n#ifdef IRIDESCENCE\nuniform vec4 vIridescenceParams;\r#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)\nuniform vec4 vIridescenceInfos;\r#endif\n#ifdef IRIDESCENCE_TEXTURE\nuniform mat4 iridescenceMatrix;\r#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nuniform mat4 iridescenceThicknessMatrix;\r#endif\n#endif\n#ifdef ANISOTROPIC\nuniform vec3 vAnisotropy;\r#ifdef ANISOTROPIC_TEXTURE\nuniform vec2 vAnisotropyInfos;\runiform mat4 anisotropyMatrix;\r#endif\n#endif\n#ifdef SHEEN\nuniform vec4 vSheenColor;\r#ifdef SHEEN_ROUGHNESS\nuniform float vSheenRoughness;\r#endif\n#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform vec4 vSheenInfos;\r#endif\n#ifdef SHEEN_TEXTURE\nuniform mat4 sheenMatrix;\r#endif\n#ifdef SHEEN_TEXTURE_ROUGHNESS\nuniform mat4 sheenRoughnessMatrix;\r#endif\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\nuniform vec4 vRefractionMicrosurfaceInfos;\runiform vec4 vRefractionInfos;\runiform mat4 refractionMatrix;\r#ifdef REALTIME_FILTERING\nuniform vec2 vRefractionFilteringInfo;\r#endif\n#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nuniform vec2 vThicknessInfos;\runiform mat4 thicknessMatrix;\r#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nuniform vec2 vRefractionIntensityInfos;\runiform mat4 refractionIntensityMatrix;\r#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nuniform vec2 vTranslucencyIntensityInfos;\runiform mat4 translucencyIntensityMatrix;\r#endif\nuniform vec2 vThicknessParam;\runiform vec3 vDiffusionDistance;\runiform vec4 vTintColor;\runiform vec3 vSubSurfaceIntensity;\r#endif\n#ifdef PREPASS\n#ifdef SS_SCATTERING\nuniform float scatteringDiffusionProfile;\r#endif\n#endif\n#if DEBUGMODE>0\nuniform vec2 vDebugMode;\r#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\r#endif\n#include\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nuniform vec3 vSphericalL00;\runiform vec3 vSphericalL1_1;\runiform vec3 vSphericalL10;\runiform vec3 vSphericalL11;\runiform vec3 vSphericalL2_2;\runiform vec3 vSphericalL2_1;\runiform vec3 vSphericalL20;\runiform vec3 vSphericalL21;\runiform vec3 vSphericalL22;\r#else\nuniform vec3 vSphericalX;\runiform vec3 vSphericalY;\runiform vec3 vSphericalZ;\runiform vec3 vSphericalXX_ZZ;\runiform vec3 vSphericalYY_ZZ;\runiform vec3 vSphericalZZ;\runiform vec3 vSphericalXY;\runiform vec3 vSphericalYZ;\runiform vec3 vSphericalZX;\r#endif\n#endif\n#define ADDITIONAL_FRAGMENT_DECLARATION\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrFragmentDeclaration = { name, shader };\n//# sourceMappingURL=pbrFragmentDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nimport \"./samplerFragmentDeclaration.js\";\nimport \"./samplerFragmentAlternateDeclaration.js\";\nconst name = \"pbrFragmentSamplersDeclaration\";\nconst shader = `#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL)\nuniform sampler2D clearCoatRoughnessSampler;\r#endif\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL)\nuniform sampler2D sheenRoughnessSampler;\r#endif\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy)\n#endif\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\r#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\runiform samplerCube reflectionSamplerHigh;\r#endif\n#ifdef USEIRRADIANCEMAP\nuniform samplerCube irradianceSampler;\r#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\r#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D reflectionSamplerLow;\runiform sampler2D reflectionSamplerHigh;\r#endif\n#ifdef USEIRRADIANCEMAP\nuniform sampler2D irradianceSampler;\r#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\r#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\r#endif\n#endif\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\r#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\n#ifdef SS_REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\r#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\runiform samplerCube refractionSamplerHigh;\r#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\r#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform sampler2D refractionSamplerLow;\runiform sampler2D refractionSamplerHigh;\r#endif\n#endif\n#endif\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity)\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrFragmentSamplersDeclaration = { name, shader };\n//# sourceMappingURL=pbrFragmentSamplersDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"subSurfaceScatteringFunctions\";\nconst shader = `bool testLightingForSSS(float diffusionProfile)\r{\rreturn diffusionProfile<1.;\r}`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const subSurfaceScatteringFunctions = { name, shader };\n//# sourceMappingURL=subSurfaceScatteringFunctions.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrHelperFunctions\";\nconst shader = `#define RECIPROCAL_PI2 0.15915494\n#define RECIPROCAL_PI 0.31830988618\n#define MINIMUMVARIANCE 0.0005\nfloat convertRoughnessToAverageSlope(float roughness)\r{\rreturn square(roughness)+MINIMUMVARIANCE;\r}\rfloat fresnelGrazingReflectance(float reflectance0) {\rfloat reflectance90=saturate(reflectance0*25.0);\rreturn reflectance90;\r}\rvec2 getAARoughnessFactors(vec3 normalVector) {\r#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalVector.xyz);\rvec3 nDfdy=dFdy(normalVector.xyz);\rfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\rfloat geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);\rfloat geometricAlphaGFactor=sqrt(slopeSquare);\rgeometricAlphaGFactor*=0.75;\rreturn vec2(geometricRoughnessFactor,geometricAlphaGFactor);\r#else\nreturn vec2(0.);\r#endif\n}\r#ifdef ANISOTROPIC\n#ifdef ANISOTROPIC_LEGACY\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {\rfloat alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);\rfloat alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);\rreturn vec2(alphaT,alphaB);\r}\rvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {\rvec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;\rvec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);\rvec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);\rvec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));\rreturn anisotropicNormal;\r}\r#else\nvec2 getAnisotropicRoughness(float alphaG,float anisotropy) {\rfloat alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);\rfloat alphaB=max(alphaG,MINIMUMVARIANCE);\rreturn vec2(alphaT,alphaB);\r}\rvec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {\rvec3 bentNormal=cross(B,V);\rbentNormal=normalize(cross(bentNormal,B));\rfloat a=square(square(1.0-anisotropy*(1.0-roughness)));\rbentNormal=normalize(mix(bentNormal,N,a));\rreturn bentNormal;\r}\r#endif\n#endif\n#if defined(CLEARCOAT) || defined(SS_REFRACTION)\nvec3 cocaLambert(vec3 alpha,float distance) {\rreturn exp(-alpha*distance);\r}\rvec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {\rreturn cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));\r}\rvec3 computeColorAtDistanceInMedia(vec3 color,float distance) {\rreturn -log(color)/distance;\r}\rvec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {\rvec3 clearCoatAbsorption=mix(vec3(1.0),\rcocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness),\rclearCoatIntensity);\rreturn clearCoatAbsorption;\r}\r#endif\n#ifdef MICROSURFACEAUTOMATIC\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\r{\rconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\rfloat reflectivityLuminance=getLuminance(reflectivityColor);\rfloat reflectivityLuma=sqrt(reflectivityLuminance);\rmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\rreturn microSurface;\r}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrHelperFunctions = { name, shader };\n//# sourceMappingURL=pbrHelperFunctions.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"hdrFilteringFunctions\";\nconst shader = `#ifdef NUM_SAMPLES\n#if NUM_SAMPLES>0\n#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nfloat radicalInverse_VdC(uint bits) \r{\rbits=(bits<<16u) | (bits>>16u);\rbits=((bits & 0x55555555u)<<1u) | ((bits & 0xAAAAAAAAu)>>1u);\rbits=((bits & 0x33333333u)<<2u) | ((bits & 0xCCCCCCCCu)>>2u);\rbits=((bits & 0x0F0F0F0Fu)<<4u) | ((bits & 0xF0F0F0F0u)>>4u);\rbits=((bits & 0x00FF00FFu)<<8u) | ((bits & 0xFF00FF00u)>>8u);\rreturn float(bits)*2.3283064365386963e-10; \r}\rvec2 hammersley(uint i,uint N)\r{\rreturn vec2(float(i)/float(N),radicalInverse_VdC(i));\r}\r#else\nfloat vanDerCorpus(int n,int base)\r{\rfloat invBase=1.0/float(base);\rfloat denom =1.0;\rfloat result =0.0;\rfor(int i=0; i<32; ++i)\r{\rif(n>0)\r{\rdenom =mod(float(n),2.0);\rresult+=denom*invBase;\rinvBase=invBase/2.0;\rn =int(float(n)/2.0);\r}\r}\rreturn result;\r}\rvec2 hammersley(int i,int N)\r{\rreturn vec2(float(i)/float(N),vanDerCorpus(i,2));\r}\r#endif\nfloat log4(float x) {\rreturn log2(x)/2.;\r}\rconst float NUM_SAMPLES_FLOAT=float(NUM_SAMPLES);\rconst float NUM_SAMPLES_FLOAT_INVERSED=1./NUM_SAMPLES_FLOAT;\rconst float K=4.;\r#define inline\nvec3 irradiance(samplerCube inputTexture,vec3 inputN,vec2 filteringInfo)\r{\rvec3 n=normalize(inputN);\rvec3 result=vec3(0.0);\rvec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);\rtangent=normalize(cross(tangent,n));\rvec3 bitangent=cross(n,tangent);\rmat3 tbn=mat3(tangent,bitangent,n);\rfloat maxLevel=filteringInfo.y;\rfloat dim0=filteringInfo.x;\rfloat omegaP=(4.*PI)/(6.*dim0*dim0);\r#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nfor(uint i=0u; i0.) {\rfloat pdf_inversed=PI/NoL;\rfloat omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;\rfloat l=log4(omegaS)-log4(omegaP)+log4(K);\rfloat mipLevel=clamp(l,0.0,maxLevel);\rvec3 c=textureCubeLodEXT(inputTexture,tbn*Ls,mipLevel).rgb;\r#ifdef GAMMA_INPUT\nc=toLinearSpace(c);\r#endif\nresult+=c;\r}\r}\rresult=result*NUM_SAMPLES_FLOAT_INVERSED;\rreturn result;\r}\r#define inline\nvec3 radiance(float alphaG,samplerCube inputTexture,vec3 inputN,vec2 filteringInfo)\r{\rvec3 n=normalize(inputN);\rif (alphaG==0.) {\rvec3 c=textureCube(inputTexture,n).rgb;\r#ifdef GAMMA_INPUT\nc=toLinearSpace(c);\r#endif\nreturn c;\r} else {\rvec3 result=vec3(0.);\rvec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);\rtangent=normalize(cross(tangent,n));\rvec3 bitangent=cross(n,tangent);\rmat3 tbn=mat3(tangent,bitangent,n);\rfloat maxLevel=filteringInfo.y;\rfloat dim0=filteringInfo.x;\rfloat omegaP=(4.*PI)/(6.*dim0*dim0);\rfloat weight=0.;\r#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\nfor(uint i=0u; i0.) {\rfloat pdf_inversed=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);\rfloat omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;\rfloat l=log4(omegaS)-log4(omegaP)+log4(K);\rfloat mipLevel=clamp(float(l),0.0,maxLevel);\rweight+=NoL;\rvec3 c=textureCubeLodEXT(inputTexture,tbn*L,mipLevel).rgb;\r#ifdef GAMMA_INPUT\nc=toLinearSpace(c);\r#endif\nresult+=c*NoL;\r}\r}\rresult=result/weight;\rreturn result;\r}\r}\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const hdrFilteringFunctions = { name, shader };\n//# sourceMappingURL=hdrFilteringFunctions.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrDirectLightingFunctions\";\nconst shader = `#define CLEARCOATREFLECTANCE90 1.0\nstruct lightingInfo\r{\rvec3 diffuse;\r#ifdef SPECULARTERM\nvec3 specular;\r#endif\n#ifdef CLEARCOAT\nvec4 clearCoat;\r#endif\n#ifdef SHEEN\nvec3 sheen;\r#endif\n};\rfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance) {\r#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\nfloat lightRoughness=lightRadius/lightDistance;\rfloat totalRoughness=saturate(lightRoughness+roughness);\rreturn totalRoughness;\r#else\nreturn roughness;\r#endif\n}\rvec3 computeHemisphericDiffuseLighting(preLightingInfo info,vec3 lightColor,vec3 groundColor) {\rreturn mix(groundColor,lightColor,info.NdotL);\r}\rvec3 computeDiffuseLighting(preLightingInfo info,vec3 lightColor) {\rfloat diffuseTerm=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);\rreturn diffuseTerm*info.attenuation*info.NdotL*lightColor;\r}\r#define inline\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\rvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\rstrq/=strq.w;\rvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\rreturn toLinearSpace(textureColor);\r}\r#ifdef SS_TRANSLUCENCY\nvec3 computeDiffuseAndTransmittedLighting(preLightingInfo info,vec3 lightColor,vec3 transmittance) {\rfloat NdotL=absEps(info.NdotLUnclamped);\rfloat wrapNdotL=computeWrappedDiffuseNdotL(NdotL,0.02);\rfloat trAdapt=step(0.,info.NdotLUnclamped);\rvec3 transmittanceNdotL=mix(transmittance*wrapNdotL,vec3(wrapNdotL),trAdapt);\rfloat diffuseTerm=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);\rreturn diffuseTerm*transmittanceNdotL*info.attenuation*lightColor;\r}\r#endif\n#ifdef SPECULARTERM\nvec3 computeSpecularLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {\rfloat NdotH=saturateEps(dot(N,info.H));\rfloat roughness=max(info.roughness,geometricRoughnessFactor);\rfloat alphaG=convertRoughnessToAverageSlope(roughness);\rvec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90);\r#ifdef IRIDESCENCE\nfresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);\r#endif\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\r#ifdef BRDF_V_HEIGHT_CORRELATED\nfloat smithVisibility=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG);\r#else\nfloat smithVisibility=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG);\r#endif\nvec3 specTerm=fresnel*distribution*smithVisibility;\rreturn specTerm*info.attenuation*info.NdotL*lightColor;\r}\r#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) {\rfloat NdotH=saturateEps(dot(N,info.H));\rfloat TdotH=dot(T,info.H);\rfloat BdotH=dot(B,info.H);\rfloat TdotV=dot(T,V);\rfloat BdotV=dot(B,V);\rfloat TdotL=dot(T,info.L);\rfloat BdotL=dot(B,info.L);\rfloat alphaG=convertRoughnessToAverageSlope(info.roughness);\rvec2 alphaTB=getAnisotropicRoughness(alphaG,anisotropy);\ralphaTB=max(alphaTB,square(geometricRoughnessFactor));\rvec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90);\r#ifdef IRIDESCENCE\nfresnel=mix(fresnel,reflectance0,info.iridescenceIntensity);\r#endif\nfloat distribution=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);\rfloat smithVisibility=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);\rvec3 specTerm=fresnel*distribution*smithVisibility;\rreturn specTerm*info.attenuation*info.NdotL*lightColor;\r}\r#endif\n#ifdef CLEARCOAT\nvec4 computeClearCoatLighting(preLightingInfo info,vec3 Ncc,float geometricRoughnessFactor,float clearCoatIntensity,vec3 lightColor) {\rfloat NccdotL=saturateEps(dot(Ncc,info.L));\rfloat NccdotH=saturateEps(dot(Ncc,info.H));\rfloat clearCoatRoughness=max(info.roughness,geometricRoughnessFactor);\rfloat alphaG=convertRoughnessToAverageSlope(clearCoatRoughness);\rfloat fresnel=fresnelSchlickGGX(info.VdotH,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);\rfresnel*=clearCoatIntensity;\rfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);\rfloat kelemenVisibility=visibility_Kelemen(info.VdotH);\rfloat clearCoatTerm=fresnel*distribution*kelemenVisibility;\rreturn vec4(\rclearCoatTerm*info.attenuation*NccdotL*lightColor,\r1.0-fresnel\r);\r}\rvec3 computeClearCoatLightingAbsorption(float NdotVRefract,vec3 L,vec3 Ncc,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {\rvec3 LRefract=-refract(L,Ncc,vClearCoatRefractionParams.y);\rfloat NdotLRefract=saturateEps(dot(Ncc,LRefract));\rvec3 absorption=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);\rreturn absorption;\r}\r#endif\n#ifdef SHEEN\nvec3 computeSheenLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {\rfloat NdotH=saturateEps(dot(N,info.H));\rfloat roughness=max(info.roughness,geometricRoughnessFactor);\rfloat alphaG=convertRoughnessToAverageSlope(roughness);\rfloat fresnel=1.;\rfloat distribution=normalDistributionFunction_CharlieSheen(NdotH,alphaG);\r/*#ifdef SHEEN_SOFTER\rfloat visibility=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG);\r#else */\nfloat visibility=visibility_Ashikhmin(info.NdotL,info.NdotV);\r/* #endif */\rfloat sheenTerm=fresnel*distribution*visibility;\rreturn sheenTerm*info.attenuation*info.NdotL*lightColor;\r}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrDirectLightingFunctions = { name, shader };\n//# sourceMappingURL=pbrDirectLightingFunctions.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrIBLFunctions\";\nconst shader = `#if defined(REFLECTION) || defined(SS_REFRACTION)\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float microsurfaceAverageSlope) {\rfloat microsurfaceAverageSlopeTexels=cubeMapDimensionPixels*microsurfaceAverageSlope;\rfloat lod=log2(microsurfaceAverageSlopeTexels);\rreturn lod;\r}\rfloat getLinearLodFromRoughness(float cubeMapDimensionPixels,float roughness) {\rfloat lod=log2(cubeMapDimensionPixels)*roughness;\rreturn lod;\r}\r#endif\n#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION)\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\rfloat temp=NdotVUnclamped+ambientOcclusion;\rreturn saturate(square(temp)-1.0+ambientOcclusion);\r}\r#endif\n#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION)\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal,vec3 geometricNormal) {\rvec3 reflection=reflect(view,normal);\rfloat temp=saturate(1.0+1.1*dot(reflection,geometricNormal));\rreturn square(temp);\r}\r#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) {\rfloat microsurfaceAverageSlope=alphaG;\rmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\rreturn getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);\r}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrIBLFunctions = { name, shader };\n//# sourceMappingURL=pbrIBLFunctions.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nimport \"./decalFragment.js\";\nconst name = \"pbrBlockAlbedoOpacity\";\nconst shader = `struct albedoOpacityOutParams\r{\rvec3 surfaceAlbedo;\rfloat alpha;\r};\r#define pbr_inline\nvoid albedoOpacityBlock(\rin vec4 vAlbedoColor,\r#ifdef ALBEDO\nin vec4 albedoTexture,\rin vec2 albedoInfos,\r#endif\n#ifdef OPACITY\nin vec4 opacityMap,\rin vec2 vOpacityInfos,\r#endif\n#ifdef DETAIL\nin vec4 detailColor,\rin vec4 vDetailInfos,\r#endif\n#ifdef DECAL\nin vec4 decalColor,\rin vec4 vDecalInfos,\r#endif\nout albedoOpacityOutParams outParams\r)\r{\rvec3 surfaceAlbedo=vAlbedoColor.rgb;\rfloat alpha=vAlbedoColor.a;\r#ifdef ALBEDO\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\r#endif\n#ifdef GAMMAALBEDO\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\r#else\nsurfaceAlbedo*=albedoTexture.rgb;\r#endif\nsurfaceAlbedo*=albedoInfos.y;\r#endif\n#include\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nsurfaceAlbedo*=vColor.rgb;\r#endif\n#ifdef DETAIL\nfloat detailAlbedo=2.0*mix(0.5,detailColor.r,vDetailInfos.y);\rsurfaceAlbedo.rgb=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo; \r#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALBEDO\n#ifdef OPACITY\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\r#else\nalpha*=opacityMap.a;\r#endif\nalpha*=vOpacityInfos.y;\r#endif\n#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nalpha*=vColor.a;\r#endif\n#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST \n#if DEBUGMODE != 88\nif (alpha0\nvec4 surfaceMetallicColorMap;\rvec4 surfaceReflectivityColorMap;\rvec2 metallicRoughness;\rvec3 metallicF0;\r#endif\n};\r#define pbr_inline\nvoid reflectivityBlock(\rin vec4 vReflectivityColor,\r#ifdef METALLICWORKFLOW\nin vec3 surfaceAlbedo,\rin vec4 metallicReflectanceFactors,\r#endif\n#ifdef REFLECTIVITY\nin vec3 reflectivityInfos,\rin vec4 surfaceMetallicOrReflectivityColorMap,\r#endif\n#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\nin vec3 ambientOcclusionColorIn,\r#endif\n#ifdef MICROSURFACEMAP\nin vec4 microSurfaceTexel,\r#endif\n#ifdef DETAIL\nin vec4 detailColor,\rin vec4 vDetailInfos,\r#endif\nout reflectivityOutParams outParams\r)\r{\rfloat microSurface=vReflectivityColor.a;\rvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\r#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\r#ifdef REFLECTIVITY\n#if DEBUGMODE>0\noutParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap;\r#endif\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);\routParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z);\r#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b;\r#else\nmetallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r;\r#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a;\r#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g;\r#endif\n#endif\n#endif\n#ifdef DETAIL\nfloat detailRoughness=mix(0.5,detailColor.b,vDetailInfos.w);\rfloat loLerp=mix(0.,metallicRoughness.g,detailRoughness*2.);\rfloat hiLerp=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);\rmetallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5));\r#endif\n#ifdef MICROSURFACEMAP\nmetallicRoughness.g*=microSurfaceTexel.r;\r#endif\n#if DEBUGMODE>0\noutParams.metallicRoughness=metallicRoughness;\r#endif\n#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS\nmicroSurface=1.0-metallicRoughness.g;\rvec3 baseColor=surfaceAlbedo;\r#ifdef FROSTBITE_REFLECTANCE\noutParams.surfaceAlbedo=baseColor.rgb*(1.0-metallicRoughness.r);\rsurfaceReflectivityColor=mix(0.16*reflectance*reflectance,baseColor,metallicRoughness.r);\r#else\nvec3 metallicF0=metallicReflectanceFactors.rgb;\r#if DEBUGMODE>0\noutParams.metallicF0=metallicF0;\r#endif\noutParams.surfaceAlbedo=mix(baseColor.rgb*(1.0-metallicF0),vec3(0.,0.,0.),metallicRoughness.r);\rsurfaceReflectivityColor=mix(metallicF0,baseColor,metallicRoughness.r);\r#endif\n#else\n#ifdef REFLECTIVITY\nsurfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb;\r#if DEBUGMODE>0\noutParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap;\r#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceMetallicOrReflectivityColorMap.a;\rmicroSurface*=reflectivityInfos.z;\r#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\r#endif\n#ifdef MICROSURFACEMAP\nmicroSurface*=microSurfaceTexel.r;\r#endif\n#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE\n#endif\n#endif\n#endif\nmicroSurface=saturate(microSurface);\rfloat roughness=1.-microSurface;\routParams.microSurface=microSurface;\routParams.roughness=roughness;\routParams.surfaceReflectivityColor=surfaceReflectivityColor;\r}\r`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockReflectivity = { name, shader };\n//# sourceMappingURL=pbrBlockReflectivity.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockAmbientOcclusion\";\nconst shader = `struct ambientOcclusionOutParams\r{\rvec3 ambientOcclusionColor;\r#if DEBUGMODE>0\nvec3 ambientOcclusionColorMap;\r#endif\n};\r#define pbr_inline\nvoid ambientOcclusionBlock(\r#ifdef AMBIENT\nin vec3 ambientOcclusionColorMap_,\rin vec4 vAmbientInfos,\r#endif\nout ambientOcclusionOutParams outParams\r)\r{\rvec3 ambientOcclusionColor=vec3(1.,1.,1.);\r#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=ambientOcclusionColorMap_*vAmbientInfos.y;\r#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\r#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\r#if DEBUGMODE>0\noutParams.ambientOcclusionColorMap=ambientOcclusionColorMap;\r#endif\n#endif\noutParams.ambientOcclusionColor=ambientOcclusionColor;\r}\r`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockAmbientOcclusion = { name, shader };\n//# sourceMappingURL=pbrBlockAmbientOcclusion.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockAlphaFresnel\";\nconst shader = `#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\nstruct alphaFresnelOutParams\r{\rfloat alpha;\r};\r#define pbr_inline\nvoid alphaFresnelBlock(\rin vec3 normalW,\rin vec3 viewDirectionW,\rin float alpha,\rin float microSurface,\rout alphaFresnelOutParams outParams\r)\r{\rfloat opacityPerceptual=alpha;\r#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\r#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\r#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\rvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\routParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\r#ifdef ALPHATEST\nif (outParams.alpha0\nvec3 anisotropyMapData;\r#endif\n};\r#define pbr_inline\nvoid anisotropicBlock(\rin vec3 vAnisotropy,\rin float roughness,\r#ifdef ANISOTROPIC_TEXTURE\nin vec3 anisotropyMapData,\r#endif\nin mat3 TBN,\rin vec3 normalW,\rin vec3 viewDirectionW,\rout anisotropicOutParams outParams\r)\r{\rfloat anisotropy=vAnisotropy.b;\rvec3 anisotropyDirection=vec3(vAnisotropy.xy,0.);\r#ifdef ANISOTROPIC_TEXTURE\nanisotropy*=anisotropyMapData.b;\r#if DEBUGMODE>0\noutParams.anisotropyMapData=anisotropyMapData;\r#endif\nanisotropyMapData.rg=anisotropyMapData.rg*2.0-1.0;\r#ifdef ANISOTROPIC_LEGACY\nanisotropyDirection.rg*=anisotropyMapData.rg;\r#else\nanisotropyDirection.xy=mat2(anisotropyDirection.x,anisotropyDirection.y,-anisotropyDirection.y,anisotropyDirection.x)*normalize(anisotropyMapData.rg);\r#endif\n#endif\nmat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));\rvec3 anisotropicTangent=normalize(anisoTBN*anisotropyDirection);\rvec3 anisotropicBitangent=normalize(cross(anisoTBN[2],anisotropicTangent));\routParams.anisotropy=anisotropy;\routParams.anisotropicTangent=anisotropicTangent;\routParams.anisotropicBitangent=anisotropicBitangent;\routParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy,roughness);\r}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockAnisotropic = { name, shader };\n//# sourceMappingURL=pbrBlockAnisotropic.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockReflection\";\nconst shader = `#ifdef REFLECTION\nstruct reflectionOutParams\r{\rvec4 environmentRadiance;\rvec3 environmentIrradiance;\r#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords;\r#else\nvec2 reflectionCoords;\r#endif\n#ifdef SS_TRANSLUCENCY\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\nvec3 irradianceVector;\r#endif\n#endif\n#endif\n};\r#define pbr_inline\nvoid createReflectionCoords(\rin vec3 vPositionW,\rin vec3 normalW,\r#ifdef ANISOTROPIC\nin anisotropicOutParams anisotropicOut,\r#endif\n#ifdef REFLECTIONMAP_3D\nout vec3 reflectionCoords\r#else\nout vec2 reflectionCoords\r#endif\n)\r{\r#ifdef ANISOTROPIC\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),anisotropicOut.anisotropicNormal);\r#else\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\r#endif\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\r#endif\n#ifdef REFLECTIONMAP_3D\nreflectionCoords=reflectionVector;\r#else\nreflectionCoords=reflectionVector.xy;\r#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\r#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\r#endif\n}\r#define pbr_inline\n#define inline\nvoid sampleReflectionTexture(\rin float alphaG,\rin vec3 vReflectionMicrosurfaceInfos,\rin vec2 vReflectionInfos,\rin vec3 vReflectionColor,\r#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nin float NdotVUnclamped,\r#endif\n#ifdef LINEARSPECULARREFLECTION\nin float roughness,\r#endif\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSampler,\rconst vec3 reflectionCoords,\r#else\nin sampler2D reflectionSampler,\rconst vec2 reflectionCoords,\r#endif\n#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSamplerLow,\rin samplerCube reflectionSamplerHigh,\r#else\nin sampler2D reflectionSamplerLow,\rin sampler2D reflectionSamplerHigh,\r#endif\n#endif\n#ifdef REALTIME_FILTERING\nin vec2 vReflectionFilteringInfo,\r#endif\nout vec4 environmentRadiance\r)\r{\r#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\r#elif defined(LINEARSPECULARREFLECTION)\nfloat reflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness);\r#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG);\r#endif\n#ifdef LODBASEDMICROSFURACE\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\r#ifdef LODINREFLECTIONALPHA\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\rfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\r#else\nfloat requestedReflectionLOD=reflectionLOD;\r#endif\n#ifdef REALTIME_FILTERING\nenvironmentRadiance=vec4(radiance(alphaG,reflectionSampler,reflectionCoords,vReflectionFilteringInfo),1.0);\r#else\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\r#endif\n#else\nfloat lodReflectionNormalized=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));\rfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\rvec4 environmentMid=sampleReflection(reflectionSampler,reflectionCoords);\rif (lodReflectionNormalizedDoubled<1.0){\renvironmentRadiance=mix(\rsampleReflection(reflectionSamplerHigh,reflectionCoords),\renvironmentMid,\rlodReflectionNormalizedDoubled\r);\r} else {\renvironmentRadiance=mix(\renvironmentMid,\rsampleReflection(reflectionSamplerLow,reflectionCoords),\rlodReflectionNormalizedDoubled-1.0\r);\r}\r#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\r#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\r#endif\nenvironmentRadiance.rgb*=vReflectionInfos.x;\renvironmentRadiance.rgb*=vReflectionColor.rgb;\r}\r#define pbr_inline\n#define inline\nvoid reflectionBlock(\rin vec3 vPositionW,\rin vec3 normalW,\rin float alphaG,\rin vec3 vReflectionMicrosurfaceInfos,\rin vec2 vReflectionInfos,\rin vec3 vReflectionColor,\r#ifdef ANISOTROPIC\nin anisotropicOutParams anisotropicOut,\r#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nin float NdotVUnclamped,\r#endif\n#ifdef LINEARSPECULARREFLECTION\nin float roughness,\r#endif\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSampler,\r#else\nin sampler2D reflectionSampler,\r#endif\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nin vec3 vEnvironmentIrradiance,\r#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\nin mat4 reflectionMatrix,\r#endif\n#endif\n#ifdef USEIRRADIANCEMAP\n#ifdef REFLECTIONMAP_3D\nin samplerCube irradianceSampler,\r#else\nin sampler2D irradianceSampler,\r#endif\n#endif\n#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSamplerLow,\rin samplerCube reflectionSamplerHigh,\r#else\nin sampler2D reflectionSamplerLow,\rin sampler2D reflectionSamplerHigh,\r#endif\n#endif\n#ifdef REALTIME_FILTERING\nin vec2 vReflectionFilteringInfo,\r#endif\nout reflectionOutParams outParams\r)\r{\rvec4 environmentRadiance=vec4(0.,0.,0.,0.);\r#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=vec3(0.);\r#else\nvec2 reflectionCoords=vec2(0.);\r#endif\ncreateReflectionCoords(\rvPositionW,\rnormalW,\r#ifdef ANISOTROPIC\nanisotropicOut,\r#endif\nreflectionCoords\r);\rsampleReflectionTexture(\ralphaG,\rvReflectionMicrosurfaceInfos,\rvReflectionInfos,\rvReflectionColor,\r#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nNdotVUnclamped,\r#endif\n#ifdef LINEARSPECULARREFLECTION\nroughness,\r#endif\n#ifdef REFLECTIONMAP_3D\nreflectionSampler,\rreflectionCoords,\r#else\nreflectionSampler,\rreflectionCoords,\r#endif\n#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\rreflectionSamplerHigh,\r#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\r#endif\nenvironmentRadiance\r);\rvec3 environmentIrradiance=vec3(0.,0.,0.);\r#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\r#else\n#ifdef ANISOTROPIC\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(anisotropicOut.anisotropicNormal,0)).xyz;\r#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\r#endif\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\r#endif\n#ifdef INVERTCUBICMAP\nirradianceVector.y*=-1.0;\r#endif\n#if defined(REALTIME_FILTERING)\nenvironmentIrradiance=irradiance(reflectionSampler,irradianceVector,vReflectionFilteringInfo);\r#else\nenvironmentIrradiance=computeEnvironmentIrradiance(irradianceVector);\r#endif\n#ifdef SS_TRANSLUCENCY\noutParams.irradianceVector=irradianceVector;\r#endif\n#endif\n#elif defined(USEIRRADIANCEMAP)\nvec4 environmentIrradiance4=sampleReflection(irradianceSampler,reflectionCoords);\renvironmentIrradiance=environmentIrradiance4.rgb;\r#ifdef RGBDREFLECTION\nenvironmentIrradiance.rgb=fromRGBD(environmentIrradiance4);\r#endif\n#ifdef GAMMAREFLECTION\nenvironmentIrradiance.rgb=toLinearSpace(environmentIrradiance.rgb);\r#endif\n#endif\nenvironmentIrradiance*=vReflectionColor.rgb;\routParams.environmentRadiance=environmentRadiance;\routParams.environmentIrradiance=environmentIrradiance;\routParams.reflectionCoords=reflectionCoords;\r}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockReflection = { name, shader };\n//# sourceMappingURL=pbrBlockReflection.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockSheen\";\nconst shader = `#ifdef SHEEN\nstruct sheenOutParams\r{\rfloat sheenIntensity;\rvec3 sheenColor;\rfloat sheenRoughness;\r#ifdef SHEEN_LINKWITHALBEDO\nvec3 surfaceAlbedo;\r#endif\n#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\nfloat sheenAlbedoScaling;\r#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nvec3 finalSheenRadianceScaled;\r#endif\n#if DEBUGMODE>0\nvec4 sheenMapData;\rvec3 sheenEnvironmentReflectance;\r#endif\n};\r#define pbr_inline\n#define inline\nvoid sheenBlock(\rin vec4 vSheenColor,\r#ifdef SHEEN_ROUGHNESS\nin float vSheenRoughness,\r#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)\nin vec4 sheenMapRoughnessData,\r#endif\n#endif\nin float roughness,\r#ifdef SHEEN_TEXTURE\nin vec4 sheenMapData,\rin float sheenMapLevel,\r#endif\nin float reflectance,\r#ifdef SHEEN_LINKWITHALBEDO\nin vec3 baseColor,\rin vec3 surfaceAlbedo,\r#endif\n#ifdef ENVIRONMENTBRDF\nin float NdotV,\rin vec3 environmentBrdf,\r#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nin vec2 AARoughnessFactors,\rin vec3 vReflectionMicrosurfaceInfos,\rin vec2 vReflectionInfos,\rin vec3 vReflectionColor,\rin vec4 vLightingIntensity,\r#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSampler,\rin vec3 reflectionCoords,\r#else\nin sampler2D reflectionSampler,\rin vec2 reflectionCoords,\r#endif\nin float NdotVUnclamped,\r#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSamplerLow,\rin samplerCube reflectionSamplerHigh,\r#else\nin sampler2D reflectionSamplerLow,\rin sampler2D reflectionSamplerHigh,\r#endif\n#endif\n#ifdef REALTIME_FILTERING\nin vec2 vReflectionFilteringInfo,\r#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)\nin float seo,\r#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)\nin float eho,\r#endif\n#endif\nout sheenOutParams outParams\r)\r{\rfloat sheenIntensity=vSheenColor.a;\r#ifdef SHEEN_TEXTURE\n#if DEBUGMODE>0\noutParams.sheenMapData=sheenMapData;\r#endif\n#endif\n#ifdef SHEEN_LINKWITHALBEDO\nfloat sheenFactor=pow5(1.0-sheenIntensity);\rvec3 sheenColor=baseColor.rgb*(1.0-sheenFactor);\rfloat sheenRoughness=sheenIntensity;\routParams.surfaceAlbedo=surfaceAlbedo*sheenFactor;\r#ifdef SHEEN_TEXTURE\nsheenIntensity*=sheenMapData.a;\r#endif\n#else\nvec3 sheenColor=vSheenColor.rgb;\r#ifdef SHEEN_TEXTURE\n#ifdef SHEEN_GAMMATEXTURE\nsheenColor.rgb*=toLinearSpace(sheenMapData.rgb);\r#else\nsheenColor.rgb*=sheenMapData.rgb;\r#endif\nsheenColor.rgb*=sheenMapLevel;\r#endif\n#ifdef SHEEN_ROUGHNESS\nfloat sheenRoughness=vSheenRoughness;\r#ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE\n#if defined(SHEEN_TEXTURE)\nsheenRoughness*=sheenMapData.a;\r#endif\n#elif defined(SHEEN_TEXTURE_ROUGHNESS)\n#ifdef SHEEN_TEXTURE_ROUGHNESS_IDENTICAL\nsheenRoughness*=sheenMapData.a;\r#else\nsheenRoughness*=sheenMapRoughnessData.a;\r#endif\n#endif\n#else\nfloat sheenRoughness=roughness;\r#ifdef SHEEN_TEXTURE\nsheenIntensity*=sheenMapData.a;\r#endif\n#endif\n#if !defined(SHEEN_ALBEDOSCALING)\nsheenIntensity*=(1.-reflectance);\r#endif\nsheenColor*=sheenIntensity;\r#endif\n#ifdef ENVIRONMENTBRDF\n/*#ifdef SHEEN_SOFTER\rvec3 environmentSheenBrdf=vec3(0.,0.,getBRDFLookupCharlieSheen(NdotV,sheenRoughness));\r#else*/\n#ifdef SHEEN_ROUGHNESS\nvec3 environmentSheenBrdf=getBRDFLookup(NdotV,sheenRoughness);\r#else\nvec3 environmentSheenBrdf=environmentBrdf;\r#endif\n/*#endif*/\r#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nfloat sheenAlphaG=convertRoughnessToAverageSlope(sheenRoughness);\r#ifdef SPECULARAA\nsheenAlphaG+=AARoughnessFactors.y;\r#endif\nvec4 environmentSheenRadiance=vec4(0.,0.,0.,0.);\rsampleReflectionTexture(\rsheenAlphaG,\rvReflectionMicrosurfaceInfos,\rvReflectionInfos,\rvReflectionColor,\r#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nNdotVUnclamped,\r#endif\n#ifdef LINEARSPECULARREFLECTION\nsheenRoughness,\r#endif\nreflectionSampler,\rreflectionCoords,\r#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\rreflectionSamplerHigh,\r#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\r#endif\nenvironmentSheenRadiance\r);\rvec3 sheenEnvironmentReflectance=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf);\r#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)\nsheenEnvironmentReflectance*=seo;\r#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)\nsheenEnvironmentReflectance*=eho;\r#endif\n#if DEBUGMODE>0\noutParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance;\r#endif\noutParams.finalSheenRadianceScaled=\renvironmentSheenRadiance.rgb *\rsheenEnvironmentReflectance *\rvLightingIntensity.z;\r#endif\n#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\noutParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b;\r#endif\noutParams.sheenIntensity=sheenIntensity;\routParams.sheenColor=sheenColor;\routParams.sheenRoughness=sheenRoughness;\r}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockSheen = { name, shader };\n//# sourceMappingURL=pbrBlockSheen.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockClearcoat\";\nconst shader = `struct clearcoatOutParams\r{\rvec3 specularEnvironmentR0;\rfloat conservationFactor;\rvec3 clearCoatNormalW;\rvec2 clearCoatAARoughnessFactors;\rfloat clearCoatIntensity;\rfloat clearCoatRoughness;\r#ifdef REFLECTION\nvec3 finalClearCoatRadianceScaled;\r#endif\n#ifdef CLEARCOAT_TINT\nvec3 absorption;\rfloat clearCoatNdotVRefract;\rvec3 clearCoatColor;\rfloat clearCoatThickness;\r#endif\n#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nvec3 energyConservationFactorClearCoat;\r#endif\n#if DEBUGMODE>0\nmat3 TBNClearCoat;\rvec2 clearCoatMapData;\rvec4 clearCoatTintMapData;\rvec4 environmentClearCoatRadiance;\rfloat clearCoatNdotV;\rvec3 clearCoatEnvironmentReflectance;\r#endif\n};\r#ifdef CLEARCOAT\n#define pbr_inline\n#define inline\nvoid clearcoatBlock(\rin vec3 vPositionW,\rin vec3 geometricNormalW,\rin vec3 viewDirectionW,\rin vec2 vClearCoatParams,\r#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\nin vec4 clearCoatMapRoughnessData,\r#endif\nin vec3 specularEnvironmentR0,\r#ifdef CLEARCOAT_TEXTURE\nin vec2 clearCoatMapData,\r#endif\n#ifdef CLEARCOAT_TINT\nin vec4 vClearCoatTintParams,\rin float clearCoatColorAtDistance,\rin vec4 vClearCoatRefractionParams,\r#ifdef CLEARCOAT_TINT_TEXTURE\nin vec4 clearCoatTintMapData,\r#endif\n#endif\n#ifdef CLEARCOAT_BUMP\nin vec2 vClearCoatBumpInfos,\rin vec4 clearCoatBumpMapData,\rin vec2 vClearCoatBumpUV,\r#if defined(TANGENT) && defined(NORMAL)\nin mat3 vTBN,\r#else\nin vec2 vClearCoatTangentSpaceParams,\r#endif\n#ifdef OBJECTSPACE_NORMALMAP\nin mat4 normalMatrix,\r#endif\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nin vec3 faceNormal,\r#endif\n#ifdef REFLECTION\nin vec3 vReflectionMicrosurfaceInfos,\rin vec2 vReflectionInfos,\rin vec3 vReflectionColor,\rin vec4 vLightingIntensity,\r#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSampler,\r#else\nin sampler2D reflectionSampler,\r#endif\n#ifndef LODBASEDMICROSFURACE\n#ifdef REFLECTIONMAP_3D\nin samplerCube reflectionSamplerLow,\rin samplerCube reflectionSamplerHigh,\r#else\nin sampler2D reflectionSamplerLow,\rin sampler2D reflectionSamplerHigh,\r#endif\n#endif\n#ifdef REALTIME_FILTERING\nin vec2 vReflectionFilteringInfo,\r#endif\n#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n#ifdef RADIANCEOCCLUSION\nin float ambientMonochrome,\r#endif\n#endif\n#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)\nin float frontFacingMultiplier,\r#endif\nout clearcoatOutParams outParams\r)\r{\rfloat clearCoatIntensity=vClearCoatParams.x;\rfloat clearCoatRoughness=vClearCoatParams.y;\r#ifdef CLEARCOAT_TEXTURE\nclearCoatIntensity*=clearCoatMapData.x;\r#ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE\nclearCoatRoughness*=clearCoatMapData.y;\r#endif\n#if DEBUGMODE>0\noutParams.clearCoatMapData=clearCoatMapData;\r#endif\n#endif\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\n#ifdef CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL\nclearCoatRoughness*=clearCoatMapData.y;\r#else\nclearCoatRoughness*=clearCoatMapRoughnessData.y;\r#endif\n#endif\noutParams.clearCoatIntensity=clearCoatIntensity;\routParams.clearCoatRoughness=clearCoatRoughness;\r#ifdef CLEARCOAT_TINT\nvec3 clearCoatColor=vClearCoatTintParams.rgb;\rfloat clearCoatThickness=vClearCoatTintParams.a;\r#ifdef CLEARCOAT_TINT_TEXTURE\n#ifdef CLEARCOAT_TINT_GAMMATEXTURE\nclearCoatColor*=toLinearSpace(clearCoatTintMapData.rgb);\r#else\nclearCoatColor*=clearCoatTintMapData.rgb;\r#endif\nclearCoatThickness*=clearCoatTintMapData.a;\r#if DEBUGMODE>0\noutParams.clearCoatTintMapData=clearCoatTintMapData;\r#endif\n#endif\noutParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);\routParams.clearCoatThickness=clearCoatThickness;\r#endif\n#ifdef CLEARCOAT_REMAP_F0\nvec3 specularEnvironmentR0Updated=getR0RemappedForClearCoat(specularEnvironmentR0);\r#else\nvec3 specularEnvironmentR0Updated=specularEnvironmentR0;\r#endif\noutParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);\rvec3 clearCoatNormalW=geometricNormalW;\r#ifdef CLEARCOAT_BUMP\n#ifdef NORMALXYSCALE\nfloat clearCoatNormalScale=1.0;\r#else\nfloat clearCoatNormalScale=vClearCoatBumpInfos.y;\r#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBNClearCoat=vTBN;\r#else\nvec2 TBNClearCoatUV=vClearCoatBumpUV*frontFacingMultiplier;\rmat3 TBNClearCoat=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams);\r#endif\n#if DEBUGMODE>0\noutParams.TBNClearCoat=TBNClearCoat;\r#endif\n#ifdef OBJECTSPACE_NORMALMAP\nclearCoatNormalW=normalize(clearCoatBumpMapData.xyz *2.0-1.0);\rclearCoatNormalW=normalize(mat3(normalMatrix)*clearCoatNormalW);\r#else\nclearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y);\r#endif\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nclearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal));\r#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nclearCoatNormalW=clearCoatNormalW*frontFacingMultiplier;\r#endif\noutParams.clearCoatNormalW=clearCoatNormalW;\routParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);\rfloat clearCoatNdotVUnclamped=dot(clearCoatNormalW,viewDirectionW);\rfloat clearCoatNdotV=absEps(clearCoatNdotVUnclamped);\r#if DEBUGMODE>0\noutParams.clearCoatNdotV=clearCoatNdotV;\r#endif\n#ifdef CLEARCOAT_TINT\nvec3 clearCoatVRefract=refract(-viewDirectionW,clearCoatNormalW,vClearCoatRefractionParams.y);\routParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract));\r#endif\n#if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION))\nvec3 environmentClearCoatBrdf=getBRDFLookup(clearCoatNdotV,clearCoatRoughness);\r#endif\n#if defined(REFLECTION)\nfloat clearCoatAlphaG=convertRoughnessToAverageSlope(clearCoatRoughness);\r#ifdef SPECULARAA\nclearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y;\r#endif\nvec4 environmentClearCoatRadiance=vec4(0.,0.,0.,0.);\rvec3 clearCoatReflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),clearCoatNormalW);\r#ifdef REFLECTIONMAP_OPPOSITEZ\nclearCoatReflectionVector.z*=-1.0;\r#endif\n#ifdef REFLECTIONMAP_3D\nvec3 clearCoatReflectionCoords=clearCoatReflectionVector;\r#else\nvec2 clearCoatReflectionCoords=clearCoatReflectionVector.xy;\r#ifdef REFLECTIONMAP_PROJECTION\nclearCoatReflectionCoords/=clearCoatReflectionVector.z;\r#endif\nclearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y;\r#endif\nsampleReflectionTexture(\rclearCoatAlphaG,\rvReflectionMicrosurfaceInfos,\rvReflectionInfos,\rvReflectionColor,\r#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nclearCoatNdotVUnclamped,\r#endif\n#ifdef LINEARSPECULARREFLECTION\nclearCoatRoughness,\r#endif\nreflectionSampler,\rclearCoatReflectionCoords,\r#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\rreflectionSamplerHigh,\r#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\r#endif\nenvironmentClearCoatRadiance\r);\r#if DEBUGMODE>0\noutParams.environmentClearCoatRadiance=environmentClearCoatRadiance;\r#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\nvec3 clearCoatEnvironmentReflectance=getReflectanceFromBRDFLookup(vec3(vClearCoatRefractionParams.x),environmentClearCoatBrdf);\r#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat clearCoatEho=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);\rclearCoatEnvironmentReflectance*=clearCoatEho;\r#endif\n#endif\n#endif\n#else\nvec3 clearCoatEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV,vec3(1.),vec3(1.),sqrt(1.-clearCoatRoughness));\r#endif\nclearCoatEnvironmentReflectance*=clearCoatIntensity;\r#if DEBUGMODE>0\noutParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance;\r#endif\noutParams.finalClearCoatRadianceScaled=\renvironmentClearCoatRadiance.rgb *\rclearCoatEnvironmentReflectance *\rvLightingIntensity.z;\r#endif\n#if defined(CLEARCOAT_TINT)\noutParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity);\r#endif\nfloat fresnelIBLClearCoat=fresnelSchlickGGX(clearCoatNdotV,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);\rfresnelIBLClearCoat*=clearCoatIntensity;\routParams.conservationFactor=(1.-fresnelIBLClearCoat);\r#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\noutParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf);\r#endif\n}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockClearcoat = { name, shader };\n//# sourceMappingURL=pbrBlockClearcoat.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockIridescence\";\nconst shader = `struct iridescenceOutParams\r{\rfloat iridescenceIntensity;\rfloat iridescenceIOR;\rfloat iridescenceThickness;\rvec3 specularEnvironmentR0;\r};\r#ifdef IRIDESCENCE\n#define pbr_inline\n#define inline\nvoid iridescenceBlock(\rin vec4 vIridescenceParams,\rin float viewAngle,\rin vec3 specularEnvironmentR0,\r#ifdef IRIDESCENCE_TEXTURE\nin vec2 iridescenceMapData,\r#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nin vec2 iridescenceThicknessMapData,\r#endif\n#ifdef CLEARCOAT\nin float NdotVUnclamped,\r#ifdef CLEARCOAT_TEXTURE\nin vec2 clearCoatMapData,\r#endif\n#endif\nout iridescenceOutParams outParams\r)\r{\rfloat iridescenceIntensity=vIridescenceParams.x;\rfloat iridescenceIOR=vIridescenceParams.y;\rfloat iridescenceThicknessMin=vIridescenceParams.z;\rfloat iridescenceThicknessMax=vIridescenceParams.w;\rfloat iridescenceThicknessWeight=1.;\r#ifdef IRIDESCENCE_TEXTURE\niridescenceIntensity*=iridescenceMapData.x;\r#ifdef IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE\niridescenceThicknessWeight=iridescenceMapData.g;\r#endif\n#endif\n#if defined(IRIDESCENCE_THICKNESS_TEXTURE)\niridescenceThicknessWeight=iridescenceThicknessMapData.g;\r#endif\nfloat iridescenceThickness=mix(iridescenceThicknessMin,iridescenceThicknessMax,iridescenceThicknessWeight);\rfloat topIor=1.; \r#ifdef CLEARCOAT\nfloat clearCoatIntensity=vClearCoatParams.x;\r#ifdef CLEARCOAT_TEXTURE\nclearCoatIntensity*=clearCoatMapData.x;\r#endif\ntopIor=mix(1.0,vClearCoatRefractionParams.w-1.,clearCoatIntensity);\rviewAngle=sqrt(1.0+square(1.0/topIor)*(square(NdotVUnclamped)-1.0));\r#endif\nvec3 iridescenceFresnel=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);\routParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);\routParams.iridescenceIntensity=iridescenceIntensity;\routParams.iridescenceThickness=iridescenceThickness;\routParams.iridescenceIOR=iridescenceIOR;\r}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockIridescence = { name, shader };\n//# sourceMappingURL=pbrBlockIridescence.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockSubSurface\";\nconst shader = `struct subSurfaceOutParams\r{\rvec3 specularEnvironmentReflectance;\r#ifdef SS_REFRACTION\nvec3 finalRefraction;\rvec3 surfaceAlbedo;\r#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nfloat alpha;\r#endif\n#ifdef REFLECTION\nfloat refractionFactorForIrradiance;\r#endif\n#endif\n#ifdef SS_TRANSLUCENCY\nvec3 transmittance;\rfloat translucencyIntensity;\r#ifdef REFLECTION\nvec3 refractionIrradiance;\r#endif\n#endif\n#if DEBUGMODE>0\nvec4 thicknessMap;\rvec4 environmentRefraction;\rvec3 refractionTransmittance;\r#endif\n};\r#ifdef SUBSURFACE\n#define pbr_inline\n#define inline\nvoid subSurfaceBlock(\rin vec3 vSubSurfaceIntensity,\rin vec2 vThicknessParam,\rin vec4 vTintColor,\rin vec3 normalW,\rin vec3 specularEnvironmentReflectance,\r#ifdef SS_THICKNESSANDMASK_TEXTURE\nin vec4 thicknessMap,\r#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nin vec4 refractionIntensityMap,\r#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nin vec4 translucencyIntensityMap,\r#endif\n#ifdef REFLECTION\n#ifdef SS_TRANSLUCENCY\nin mat4 reflectionMatrix,\r#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\nin vec3 irradianceVector_,\r#endif\n#if defined(REALTIME_FILTERING)\nin samplerCube reflectionSampler,\rin vec2 vReflectionFilteringInfo,\r#endif\n#endif\n#ifdef USEIRRADIANCEMAP\n#ifdef REFLECTIONMAP_3D\nin samplerCube irradianceSampler,\r#else\nin sampler2D irradianceSampler,\r#endif\n#endif\n#endif\n#endif\n#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)\nin vec3 surfaceAlbedo,\r#endif\n#ifdef SS_REFRACTION\nin vec3 vPositionW,\rin vec3 viewDirectionW,\rin mat4 view,\rin vec4 vRefractionInfos,\rin mat4 refractionMatrix,\rin vec4 vRefractionMicrosurfaceInfos,\rin vec4 vLightingIntensity,\r#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nin float alpha,\r#endif\n#ifdef SS_LODINREFRACTIONALPHA\nin float NdotVUnclamped,\r#endif\n#ifdef SS_LINEARSPECULARREFRACTION\nin float roughness,\r#endif\nin float alphaG,\r#ifdef SS_REFRACTIONMAP_3D\nin samplerCube refractionSampler,\r#ifndef LODBASEDMICROSFURACE\nin samplerCube refractionSamplerLow,\rin samplerCube refractionSamplerHigh,\r#endif\n#else\nin sampler2D refractionSampler,\r#ifndef LODBASEDMICROSFURACE\nin sampler2D refractionSamplerLow,\rin sampler2D refractionSamplerHigh,\r#endif\n#endif\n#ifdef ANISOTROPIC\nin anisotropicOutParams anisotropicOut,\r#endif\n#ifdef REALTIME_FILTERING\nin vec2 vRefractionFilteringInfo,\r#endif\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\nin vec3 refractionPosition,\rin vec3 refractionSize,\r#endif\n#endif\n#ifdef SS_TRANSLUCENCY\nin vec3 vDiffusionDistance,\r#endif\nout subSurfaceOutParams outParams\r)\r{\routParams.specularEnvironmentReflectance=specularEnvironmentReflectance;\r#ifdef SS_REFRACTION\nfloat refractionIntensity=vSubSurfaceIntensity.x;\r#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nrefractionIntensity*=(1.0-alpha);\routParams.alpha=1.0;\r#endif\n#endif\n#ifdef SS_TRANSLUCENCY\nfloat translucencyIntensity=vSubSurfaceIntensity.y;\r#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\n#if defined(SS_USE_GLTF_TEXTURES)\nfloat thickness=thicknessMap.g*vThicknessParam.y+vThicknessParam.x;\r#else\nfloat thickness=thicknessMap.r*vThicknessParam.y+vThicknessParam.x;\r#endif\n#if DEBUGMODE>0\noutParams.thicknessMap=thicknessMap;\r#endif\n#ifdef SS_MASK_FROM_THICKNESS_TEXTURE\n#if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE)\n#if defined(SS_USE_GLTF_TEXTURES)\nrefractionIntensity*=thicknessMap.r;\r#else\nrefractionIntensity*=thicknessMap.g;\r#endif\n#endif\n#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE)\ntranslucencyIntensity*=thicknessMap.b;\r#endif\n#endif\n#else\nfloat thickness=vThicknessParam.y;\r#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\n#ifdef SS_USE_GLTF_TEXTURES\nrefractionIntensity*=refractionIntensityMap.r;\r#else\nrefractionIntensity*=refractionIntensityMap.g;\r#endif\n#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\ntranslucencyIntensity*=translucencyIntensityMap.b;\r#endif\n#ifdef SS_TRANSLUCENCY\nthickness=maxEps(thickness);\rvec3 transmittance=transmittanceBRDF_Burley(vTintColor.rgb,vDiffusionDistance,thickness);\rtransmittance*=translucencyIntensity;\routParams.transmittance=transmittance;\routParams.translucencyIntensity=translucencyIntensity;\r#endif\n#ifdef SS_REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\r#ifdef ANISOTROPIC\nvec3 refractionVector=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,vRefractionInfos.y);\r#else\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\r#endif\n#ifdef SS_REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\r#endif\n#ifdef SS_REFRACTIONMAP_3D\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\nrefractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition);\r#endif\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\rvec3 refractionCoords=refractionVector;\rrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\r#else\n#ifdef SS_USE_THICKNESS_AS_DEPTH\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*thickness,1.0)));\r#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\r#endif\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\rrefractionCoords.y=1.0-refractionCoords.y;\r#endif\n#ifdef SS_HAS_THICKNESS\nfloat ior=vRefractionInfos.y;\r#else\nfloat ior=vRefractionMicrosurfaceInfos.w;\r#endif\n#ifdef SS_LODINREFRACTIONALPHA\nfloat refractionAlphaG=alphaG;\rrefractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));\rfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped);\r#elif defined(SS_LINEARSPECULARREFRACTION)\nfloat refractionRoughness=alphaG;\rrefractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));\rfloat refractionLOD=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness);\r#else\nfloat refractionAlphaG=alphaG;\rrefractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));\rfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG);\r#endif\n#ifdef LODBASEDMICROSFURACE\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\r#ifdef SS_LODINREFRACTIONALPHA\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\rfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\r#else\nfloat requestedRefractionLOD=refractionLOD;\r#endif\n#if defined(REALTIME_FILTERING) && defined(SS_REFRACTIONMAP_3D)\nenvironmentRefraction=vec4(radiance(alphaG,refractionSampler,refractionCoords,vRefractionFilteringInfo),1.0);\r#else\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\r#endif\n#else\nfloat lodRefractionNormalized=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));\rfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\rvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\rif (lodRefractionNormalizedDoubled<1.0){\renvironmentRefraction=mix(\rsampleRefraction(refractionSamplerHigh,refractionCoords),\renvironmentRefractionMid,\rlodRefractionNormalizedDoubled\r);\r} else {\renvironmentRefraction=mix(\renvironmentRefractionMid,\rsampleRefraction(refractionSamplerLow,refractionCoords),\rlodRefractionNormalizedDoubled-1.0\r);\r}\r#endif\n#ifdef SS_RGBDREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\r#endif\n#ifdef SS_GAMMAREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\r#endif\nenvironmentRefraction.rgb*=vRefractionInfos.x;\r#endif\n#ifdef SS_REFRACTION\nvec3 refractionTransmittance=vec3(refractionIntensity);\r#ifdef SS_THICKNESSANDMASK_TEXTURE\nvec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);\rrefractionTransmittance*=cocaLambert(volumeAlbedo,thickness);\r#elif defined(SS_LINKREFRACTIONTOTRANSPARENCY)\nfloat maxChannel=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);\rvec3 volumeAlbedo=saturate(maxChannel*surfaceAlbedo);\renvironmentRefraction.rgb*=volumeAlbedo;\r#else\nvec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);\rrefractionTransmittance*=cocaLambert(volumeAlbedo,vThicknessParam.y);\r#endif\n#ifdef SS_ALBEDOFORREFRACTIONTINT\nenvironmentRefraction.rgb*=surfaceAlbedo.rgb;\r#endif\noutParams.surfaceAlbedo=surfaceAlbedo*(1.-refractionIntensity);\r#ifdef REFLECTION\noutParams.refractionFactorForIrradiance=(1.-refractionIntensity);\r#endif\n#ifdef UNUSED_MULTIPLEBOUNCES\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\routParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity);\r#endif\nrefractionTransmittance*=1.0-outParams.specularEnvironmentReflectance;\r#if DEBUGMODE>0\noutParams.refractionTransmittance=refractionTransmittance;\r#endif\noutParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z;\r#if DEBUGMODE>0\noutParams.environmentRefraction=environmentRefraction;\r#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;\r#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\r#endif\n#ifdef INVERTCUBICMAP\nirradianceVector.y*=-1.0;\r#endif\n#else\nvec3 irradianceVector=irradianceVector_;\r#endif\n#if defined(USESPHERICALFROMREFLECTIONMAP)\n#if defined(REALTIME_FILTERING)\nvec3 refractionIrradiance=irradiance(reflectionSampler,-irradianceVector,vReflectionFilteringInfo);\r#else\nvec3 refractionIrradiance=computeEnvironmentIrradiance(-irradianceVector);\r#endif\n#elif defined(USEIRRADIANCEMAP)\n#ifdef REFLECTIONMAP_3D\nvec3 irradianceCoords=irradianceVector;\r#else\nvec2 irradianceCoords=irradianceVector.xy;\r#ifdef REFLECTIONMAP_PROJECTION\nirradianceCoords/=irradianceVector.z;\r#endif\nirradianceCoords.y=1.0-irradianceCoords.y;\r#endif\nvec4 refractionIrradiance=sampleReflection(irradianceSampler,-irradianceCoords);\r#ifdef RGBDREFLECTION\nrefractionIrradiance.rgb=fromRGBD(refractionIrradiance);\r#endif\n#ifdef GAMMAREFLECTION\nrefractionIrradiance.rgb=toLinearSpace(refractionIrradiance.rgb);\r#endif\n#else\nvec4 refractionIrradiance=vec4(0.);\r#endif\nrefractionIrradiance.rgb*=transmittance;\r#ifdef SS_ALBEDOFORTRANSLUCENCYTINT\nrefractionIrradiance.rgb*=surfaceAlbedo.rgb;\r#endif\noutParams.refractionIrradiance=refractionIrradiance.rgb;\r#endif\n}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockSubSurface = { name, shader };\n//# sourceMappingURL=pbrBlockSubSurface.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockNormalGeometric\";\nconst shader = `vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\r#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\r#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\r#endif\nvec3 geometricNormalW=normalW;\r#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\ngeometricNormalW=gl_FrontFacing ? geometricNormalW : -geometricNormalW;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockNormalGeometric = { name, shader };\n//# sourceMappingURL=pbrBlockNormalGeometric.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockNormalFinal\";\nconst shader = `#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\r#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\r#endif\nnormalW*=sign(dot(normalW,faceNormal));\r#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockNormalFinal = { name, shader };\n//# sourceMappingURL=pbrBlockNormalFinal.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockLightmapInit\";\nconst shader = `#ifdef LIGHTMAP\nvec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset);\r#ifdef RGBDLIGHTMAP\nlightmapColor.rgb=fromRGBD(lightmapColor);\r#endif\n#ifdef GAMMALIGHTMAP\nlightmapColor.rgb=toLinearSpace(lightmapColor.rgb);\r#endif\nlightmapColor.rgb*=vLightmapInfos.y;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockLightmapInit = { name, shader };\n//# sourceMappingURL=pbrBlockLightmapInit.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockGeometryInfo\";\nconst shader = `float NdotVUnclamped=dot(normalW,viewDirectionW);\rfloat NdotV=absEps(NdotVUnclamped);\rfloat alphaG=convertRoughnessToAverageSlope(roughness);\rvec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz);\r#ifdef SPECULARAA\nalphaG+=AARoughnessFactors.y;\r#endif\n#if defined(ENVIRONMENTBRDF)\nvec3 environmentBrdf=getBRDFLookup(NdotV,roughness);\r#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=aoOut.ambientOcclusionColor.r;\r#else\nfloat ambientMonochrome=getLuminance(aoOut.ambientOcclusionColor);\r#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\r#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW);\r#endif\n#endif\n#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockGeometryInfo = { name, shader };\n//# sourceMappingURL=pbrBlockGeometryInfo.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockReflectance0\";\nconst shader = `float reflectance=max(max(reflectivityOut.surfaceReflectivityColor.r,reflectivityOut.surfaceReflectivityColor.g),reflectivityOut.surfaceReflectivityColor.b);\rvec3 specularEnvironmentR0=reflectivityOut.surfaceReflectivityColor.rgb;\r#ifdef METALLICWORKFLOW\nvec3 specularEnvironmentR90=vec3(metallicReflectanceFactors.a);\r#else \nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\r#endif\n#ifdef ALPHAFRESNEL\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\rspecularEnvironmentR90=specularEnvironmentR90*reflectance90;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockReflectance0 = { name, shader };\n//# sourceMappingURL=pbrBlockReflectance0.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockReflectance\";\nconst shader = `#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\nvec3 specularEnvironmentReflectance=getReflectanceFromBRDFLookup(clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,environmentBrdf);\r#ifdef RADIANCEOCCLUSION\nspecularEnvironmentReflectance*=seo;\r#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nspecularEnvironmentReflectance*=eho;\r#endif\n#endif\n#endif\n#else\nvec3 specularEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\r#endif\n#ifdef CLEARCOAT\nspecularEnvironmentReflectance*=clearcoatOut.conservationFactor;\r#if defined(CLEARCOAT_TINT)\nspecularEnvironmentReflectance*=clearcoatOut.absorption;\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockReflectance = { name, shader };\n//# sourceMappingURL=pbrBlockReflectance.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockDirectLighting\";\nconst shader = `vec3 diffuseBase=vec3(0.,0.,0.);\r#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\r#endif\n#ifdef CLEARCOAT\nvec3 clearCoatBase=vec3(0.,0.,0.);\r#endif\n#ifdef SHEEN\nvec3 sheenBase=vec3(0.,0.,0.);\r#endif\npreLightingInfo preInfo;\rlightingInfo info;\rfloat shadow=1.; \r#if defined(CLEARCOAT) && defined(CLEARCOAT_TINT)\nvec3 absorption=vec3(0.);\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockDirectLighting = { name, shader };\n//# sourceMappingURL=pbrBlockDirectLighting.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockFinalLitComponents\";\nconst shader = `#if defined(ENVIRONMENTBRDF)\n#ifdef MS_BRDF_ENERGY_CONSERVATION\nvec3 energyConservationFactor=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf);\r#endif\n#endif\n#ifndef METALLICWORKFLOW\n#ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\r#endif\n#endif\n#if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF)\nsurfaceAlbedo.rgb=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb;\r#endif\n#ifdef REFLECTION\nvec3 finalIrradiance=reflectionOut.environmentIrradiance;\r#if defined(CLEARCOAT)\nfinalIrradiance*=clearcoatOut.conservationFactor;\r#if defined(CLEARCOAT_TINT)\nfinalIrradiance*=clearcoatOut.absorption;\r#endif\n#endif\n#if defined(SS_REFRACTION)\nfinalIrradiance*=subSurfaceOut.refractionFactorForIrradiance;\r#endif\n#if defined(SS_TRANSLUCENCY)\nfinalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);\rfinalIrradiance+=subSurfaceOut.refractionIrradiance;\r#endif\nfinalIrradiance*=surfaceAlbedo.rgb;\rfinalIrradiance*=vLightingIntensity.z;\rfinalIrradiance*=aoOut.ambientOcclusionColor;\r#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\rfinalSpecular=max(finalSpecular,0.0);\rvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\r#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nfinalSpecularScaled*=energyConservationFactor;\r#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\nfinalSpecularScaled*=sheenOut.sheenAlbedoScaling;\r#endif\n#endif\n#ifdef REFLECTION\nvec3 finalRadiance=reflectionOut.environmentRadiance.rgb;\rfinalRadiance*=subSurfaceOut.specularEnvironmentReflectance;\rvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\r#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nfinalRadianceScaled*=energyConservationFactor;\r#endif\n#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING)\nfinalRadianceScaled*=sheenOut.sheenAlbedoScaling;\r#endif\n#endif\n#ifdef SHEEN\nvec3 finalSheen=sheenBase*sheenOut.sheenColor;\rfinalSheen=max(finalSheen,0.0);\rvec3 finalSheenScaled=finalSheen*vLightingIntensity.x*vLightingIntensity.w;\r#if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nsheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor;\r#if defined(CLEARCOAT_TINT)\nsheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption;\r#endif\n#endif\n#endif\n#ifdef CLEARCOAT\nvec3 finalClearCoat=clearCoatBase;\rfinalClearCoat=max(finalClearCoat,0.0);\rvec3 finalClearCoatScaled=finalClearCoat*vLightingIntensity.x*vLightingIntensity.w;\r#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION)\nfinalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat;\r#endif\n#ifdef SS_REFRACTION\nsubSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor;\r#ifdef CLEARCOAT_TINT\nsubSurfaceOut.finalRefraction*=clearcoatOut.absorption;\r#endif\n#endif\n#endif\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\r#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\r#if defined(CLEARCOAT)\nluminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled);\r#endif\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\r#endif\n#if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalClearCoatScaled);\r#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA)\nalpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha);\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockFinalLitComponents = { name, shader };\n//# sourceMappingURL=pbrBlockFinalLitComponents.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockFinalUnlitComponents\";\nconst shader = `vec3 finalDiffuse=diffuseBase;\rfinalDiffuse*=surfaceAlbedo.rgb;\rfinalDiffuse=max(finalDiffuse,0.0);\rfinalDiffuse*=vLightingIntensity.x;\rvec3 finalAmbient=vAmbientColor;\rfinalAmbient*=surfaceAlbedo.rgb;\rvec3 finalEmissive=vEmissiveColor;\r#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\r#ifdef GAMMAEMISSIVE\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\r#else\nfinalEmissive*=emissiveColorTex.rgb;\r#endif\nfinalEmissive*= vEmissiveInfos.y;\r#endif\nfinalEmissive*=vLightingIntensity.y;\r#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),aoOut.ambientOcclusionColor,vAmbientInfos.w);\r#else\nvec3 ambientOcclusionForDirectDiffuse=aoOut.ambientOcclusionColor;\r#endif\nfinalAmbient*=aoOut.ambientOcclusionColor;\rfinalDiffuse*=ambientOcclusionForDirectDiffuse;\r`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockFinalUnlitComponents = { name, shader };\n//# sourceMappingURL=pbrBlockFinalUnlitComponents.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockFinalColorComposition\";\nconst shader = `vec4 finalColor=vec4(\r#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance +\r#endif\n#ifdef SPECULARTERM\nfinalSpecularScaled +\r#endif\n#ifdef SHEEN\nfinalSheenScaled +\r#endif\n#ifdef CLEARCOAT\nfinalClearCoatScaled +\r#endif\n#ifdef REFLECTION\nfinalRadianceScaled +\r#if defined(SHEEN) && defined(ENVIRONMENTBRDF)\nsheenOut.finalSheenRadianceScaled +\r#endif\n#ifdef CLEARCOAT\nclearcoatOut.finalClearCoatRadianceScaled +\r#endif\n#endif\n#ifdef SS_REFRACTION\nsubSurfaceOut.finalRefraction +\r#endif\n#endif\nfinalAmbient +\rfinalDiffuse,\ralpha);\r#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor.rgb;\r#else\nfinalColor.rgb+=lightmapColor.rgb;\r#endif\n#endif\n#endif\nfinalColor.rgb+=finalEmissive;\r#define CUSTOM_FRAGMENT_BEFORE_FOG\nfinalColor=max(finalColor,0.0);\r`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockFinalColorComposition = { name, shader };\n//# sourceMappingURL=pbrBlockFinalColorComposition.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrBlockImageProcessing\";\nconst shader = `#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING)\n#if !defined(SKIPFINALCOLORCLAMP)\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\r#endif\n#else\nfinalColor=applyImageProcessing(finalColor);\r#endif\nfinalColor.a*=visibility;\r#ifdef PREMULTIPLYALPHA\nfinalColor.rgb*=finalColor.a;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrBlockImageProcessing = { name, shader };\n//# sourceMappingURL=pbrBlockImageProcessing.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"pbrDebug\";\nconst shader = `#if DEBUGMODE>0\nif (vClipSpacePosition.x/vClipSpacePosition.w>=vDebugMode.x) {\r#if DEBUGMODE==1\ngl_FragColor.rgb=vPositionW.rgb;\r#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==2 && defined(NORMAL)\ngl_FragColor.rgb=vNormalW.rgb;\r#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==3 && defined(BUMP) || DEBUGMODE==3 && defined(PARALLAX) || DEBUGMODE==3 && defined(ANISOTROPIC)\ngl_FragColor.rgb=TBN[0];\r#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==4 && defined(BUMP) || DEBUGMODE==4 && defined(PARALLAX) || DEBUGMODE==4 && defined(ANISOTROPIC)\ngl_FragColor.rgb=TBN[1];\r#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==5\ngl_FragColor.rgb=normalW;\r#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==6 && defined(MAINUV1)\ngl_FragColor.rgb=vec3(vMainUV1,0.0);\r#elif DEBUGMODE==7 && defined(MAINUV2)\ngl_FragColor.rgb=vec3(vMainUV2,0.0);\r#elif DEBUGMODE==8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)\ngl_FragColor.rgb=clearcoatOut.TBNClearCoat[0];\r#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP)\ngl_FragColor.rgb=clearcoatOut.TBNClearCoat[1];\r#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==10 && defined(CLEARCOAT)\ngl_FragColor.rgb=clearcoatOut.clearCoatNormalW;\r#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==11 && defined(ANISOTROPIC)\ngl_FragColor.rgb=anisotropicOut.anisotropicNormal;\r#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==12 && defined(ANISOTROPIC)\ngl_FragColor.rgb=anisotropicOut.anisotropicTangent;\r#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==13 && defined(ANISOTROPIC)\ngl_FragColor.rgb=anisotropicOut.anisotropicBitangent;\r#define DEBUGMODE_NORMALIZE\n#elif DEBUGMODE==20 && defined(ALBEDO)\ngl_FragColor.rgb=albedoTexture.rgb;\r#elif DEBUGMODE==21 && defined(AMBIENT)\ngl_FragColor.rgb=aoOut.ambientOcclusionColorMap.rgb;\r#elif DEBUGMODE==22 && defined(OPACITY)\ngl_FragColor.rgb=opacityMap.rgb;\r#elif DEBUGMODE==23 && defined(EMISSIVE)\ngl_FragColor.rgb=emissiveColorTex.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==24 && defined(LIGHTMAP)\ngl_FragColor.rgb=lightmapColor.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW)\ngl_FragColor.rgb=reflectivityOut.surfaceMetallicColorMap.rgb;\r#elif DEBUGMODE==26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW)\ngl_FragColor.rgb=reflectivityOut.surfaceReflectivityColorMap.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE)\ngl_FragColor.rgb=vec3(clearcoatOut.clearCoatMapData.rg,0.0);\r#elif DEBUGMODE==28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)\ngl_FragColor.rgb=clearcoatOut.clearCoatTintMapData.rgb;\r#elif DEBUGMODE==29 && defined(SHEEN) && defined(SHEEN_TEXTURE)\ngl_FragColor.rgb=sheenOut.sheenMapData.rgb;\r#elif DEBUGMODE==30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE)\ngl_FragColor.rgb=anisotropicOut.anisotropyMapData.rgb;\r#elif DEBUGMODE==31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE)\ngl_FragColor.rgb=subSurfaceOut.thicknessMap.rgb;\r#elif DEBUGMODE==40 && defined(SS_REFRACTION)\ngl_FragColor.rgb=subSurfaceOut.environmentRefraction.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==41 && defined(REFLECTION)\ngl_FragColor.rgb=reflectionOut.environmentRadiance.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==42 && defined(CLEARCOAT) && defined(REFLECTION)\ngl_FragColor.rgb=clearcoatOut.environmentClearCoatRadiance.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==50\ngl_FragColor.rgb=diffuseBase.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==51 && defined(SPECULARTERM)\ngl_FragColor.rgb=specularBase.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==52 && defined(CLEARCOAT)\ngl_FragColor.rgb=clearCoatBase.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==53 && defined(SHEEN)\ngl_FragColor.rgb=sheenBase.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==54 && defined(REFLECTION)\ngl_FragColor.rgb=reflectionOut.environmentIrradiance.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==60\ngl_FragColor.rgb=surfaceAlbedo.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==61\ngl_FragColor.rgb=clearcoatOut.specularEnvironmentR0;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==62 && defined(METALLICWORKFLOW)\ngl_FragColor.rgb=vec3(reflectivityOut.metallicRoughness.r);\r#elif DEBUGMODE==71 && defined(METALLICWORKFLOW)\ngl_FragColor.rgb=reflectivityOut.metallicF0;\r#elif DEBUGMODE==63\ngl_FragColor.rgb=vec3(roughness);\r#elif DEBUGMODE==64\ngl_FragColor.rgb=vec3(alphaG);\r#elif DEBUGMODE==65\ngl_FragColor.rgb=vec3(NdotV);\r#elif DEBUGMODE==66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT)\ngl_FragColor.rgb=clearcoatOut.clearCoatColor.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==67 && defined(CLEARCOAT)\ngl_FragColor.rgb=vec3(clearcoatOut.clearCoatRoughness);\r#elif DEBUGMODE==68 && defined(CLEARCOAT)\ngl_FragColor.rgb=vec3(clearcoatOut.clearCoatNdotV);\r#elif DEBUGMODE==69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY)\ngl_FragColor.rgb=subSurfaceOut.transmittance;\r#elif DEBUGMODE==70 && defined(SUBSURFACE) && defined(SS_REFRACTION)\ngl_FragColor.rgb=subSurfaceOut.refractionTransmittance;\r#elif DEBUGMODE==72\ngl_FragColor.rgb=vec3(microSurface);\r#elif DEBUGMODE==73\ngl_FragColor.rgb=vAlbedoColor.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==74 && !defined(METALLICWORKFLOW)\ngl_FragColor.rgb=vReflectivityColor.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==75\ngl_FragColor.rgb=vEmissiveColor.rgb;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==80 && defined(RADIANCEOCCLUSION)\ngl_FragColor.rgb=vec3(seo);\r#elif DEBUGMODE==81 && defined(HORIZONOCCLUSION)\ngl_FragColor.rgb=vec3(eho);\r#elif DEBUGMODE==82 && defined(MS_BRDF_ENERGY_CONSERVATION)\ngl_FragColor.rgb=vec3(energyConservationFactor);\r#elif DEBUGMODE==83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\ngl_FragColor.rgb=specularEnvironmentReflectance;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\ngl_FragColor.rgb=clearcoatOut.clearCoatEnvironmentReflectance;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==85 && defined(SHEEN) && defined(REFLECTION)\ngl_FragColor.rgb=sheenOut.sheenEnvironmentReflectance;\r#define DEBUGMODE_GAMMA\n#elif DEBUGMODE==86 && defined(ALPHABLEND)\ngl_FragColor.rgb=vec3(luminanceOverAlpha);\r#elif DEBUGMODE==87\ngl_FragColor.rgb=vec3(alpha);\r#elif DEBUGMODE==88 && defined(ALBEDO)\ngl_FragColor.rgb=vec3(albedoTexture.a);\r#else\nfloat stripeWidth=30.;\rfloat stripePos=floor((gl_FragCoord.x+gl_FragCoord.y)/stripeWidth);\rfloat whichColor=mod(stripePos,2.);\rvec3 color1=vec3(.6,.2,.2);\rvec3 color2=vec3(.3,.1,.1);\rgl_FragColor.rgb=mix(color1,color2,whichColor);\r#endif\ngl_FragColor.rgb*=vDebugMode.y;\r#ifdef DEBUGMODE_NORMALIZE\ngl_FragColor.rgb=normalize(gl_FragColor.rgb)*0.5+0.5;\r#endif\n#ifdef DEBUGMODE_GAMMA\ngl_FragColor.rgb=toGammaSpace(gl_FragColor.rgb);\r#endif\ngl_FragColor.a=1.0;\r#ifdef PREPASS\ngl_FragData[0]=toLinearSpace(gl_FragColor); \rgl_FragData[1]=vec4(0.,0.,0.,0.); \r#endif\nreturn;\r}\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrDebug = { name, shader };\n//# sourceMappingURL=pbrDebug.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/prePassDeclaration.js\";\nimport \"./ShadersInclude/oitDeclaration.js\";\nimport \"./ShadersInclude/pbrFragmentDeclaration.js\";\nimport \"./ShadersInclude/pbrUboDeclaration.js\";\nimport \"./ShadersInclude/pbrFragmentExtraDeclaration.js\";\nimport \"./ShadersInclude/lightFragmentDeclaration.js\";\nimport \"./ShadersInclude/lightUboDeclaration.js\";\nimport \"./ShadersInclude/pbrFragmentSamplersDeclaration.js\";\nimport \"./ShadersInclude/imageProcessingDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneFragmentDeclaration.js\";\nimport \"./ShadersInclude/logDepthDeclaration.js\";\nimport \"./ShadersInclude/fogFragmentDeclaration.js\";\nimport \"./ShadersInclude/helperFunctions.js\";\nimport \"./ShadersInclude/subSurfaceScatteringFunctions.js\";\nimport \"./ShadersInclude/importanceSampling.js\";\nimport \"./ShadersInclude/pbrHelperFunctions.js\";\nimport \"./ShadersInclude/imageProcessingFunctions.js\";\nimport \"./ShadersInclude/shadowsFragmentFunctions.js\";\nimport \"./ShadersInclude/harmonicsFunctions.js\";\nimport \"./ShadersInclude/pbrDirectLightingSetupFunctions.js\";\nimport \"./ShadersInclude/pbrDirectLightingFalloffFunctions.js\";\nimport \"./ShadersInclude/pbrBRDFFunctions.js\";\nimport \"./ShadersInclude/hdrFilteringFunctions.js\";\nimport \"./ShadersInclude/pbrDirectLightingFunctions.js\";\nimport \"./ShadersInclude/pbrIBLFunctions.js\";\nimport \"./ShadersInclude/bumpFragmentMainFunctions.js\";\nimport \"./ShadersInclude/bumpFragmentFunctions.js\";\nimport \"./ShadersInclude/reflectionFunction.js\";\nimport \"./ShadersInclude/pbrBlockAlbedoOpacity.js\";\nimport \"./ShadersInclude/pbrBlockReflectivity.js\";\nimport \"./ShadersInclude/pbrBlockAmbientOcclusion.js\";\nimport \"./ShadersInclude/pbrBlockAlphaFresnel.js\";\nimport \"./ShadersInclude/pbrBlockAnisotropic.js\";\nimport \"./ShadersInclude/pbrBlockReflection.js\";\nimport \"./ShadersInclude/pbrBlockSheen.js\";\nimport \"./ShadersInclude/pbrBlockClearcoat.js\";\nimport \"./ShadersInclude/pbrBlockIridescence.js\";\nimport \"./ShadersInclude/pbrBlockSubSurface.js\";\nimport \"./ShadersInclude/clipPlaneFragment.js\";\nimport \"./ShadersInclude/pbrBlockNormalGeometric.js\";\nimport \"./ShadersInclude/bumpFragment.js\";\nimport \"./ShadersInclude/pbrBlockNormalFinal.js\";\nimport \"./ShadersInclude/depthPrePass.js\";\nimport \"./ShadersInclude/pbrBlockLightmapInit.js\";\nimport \"./ShadersInclude/pbrBlockGeometryInfo.js\";\nimport \"./ShadersInclude/pbrBlockReflectance0.js\";\nimport \"./ShadersInclude/pbrBlockReflectance.js\";\nimport \"./ShadersInclude/pbrBlockDirectLighting.js\";\nimport \"./ShadersInclude/lightFragment.js\";\nimport \"./ShadersInclude/pbrBlockFinalLitComponents.js\";\nimport \"./ShadersInclude/pbrBlockFinalUnlitComponents.js\";\nimport \"./ShadersInclude/pbrBlockFinalColorComposition.js\";\nimport \"./ShadersInclude/logDepthFragment.js\";\nimport \"./ShadersInclude/fogFragment.js\";\nimport \"./ShadersInclude/pbrBlockImageProcessing.js\";\nimport \"./ShadersInclude/oitFragment.js\";\nimport \"./ShadersInclude/pbrDebug.js\";\nconst name = \"pbrPixelShader\";\nconst shader = `#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[SCENE_MRT_COUNT]\nprecision highp float;\r#include\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE\n#endif\n#include<__decl__pbrFragment>\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#ifdef REFLECTION\n#include\n#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n#include\nvoid main(void) {\r#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#include\n#include\n#include\nalbedoOpacityOutParams albedoOpacityOut;\r#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\r#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\r#endif\n#ifdef DECAL\nvec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset);\r#endif\nalbedoOpacityBlock(\rvAlbedoColor,\r#ifdef ALBEDO\nalbedoTexture,\rvAlbedoInfos,\r#endif\n#ifdef OPACITY\nopacityMap,\rvOpacityInfos,\r#endif\n#ifdef DETAIL\ndetailColor,\rvDetailInfos,\r#endif\n#ifdef DECAL\ndecalColor,\rvDecalInfos,\r#endif\nalbedoOpacityOut\r);\rvec3 surfaceAlbedo=albedoOpacityOut.surfaceAlbedo;\rfloat alpha=albedoOpacityOut.alpha;\r#define CUSTOM_FRAGMENT_UPDATE_ALPHA\n#include\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\nambientOcclusionOutParams aoOut;\r#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb;\r#endif\nambientOcclusionBlock(\r#ifdef AMBIENT\nambientOcclusionColorMap,\rvAmbientInfos,\r#endif\naoOut\r);\r#include\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\r#else\nvec3 baseColor=surfaceAlbedo;\rreflectivityOutParams reflectivityOut;\r#if defined(REFLECTIVITY)\nvec4 surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\rvec4 baseReflectivity=surfaceMetallicOrReflectivityColorMap;\r#ifndef METALLICWORKFLOW\n#ifdef REFLECTIVITY_GAMMA\nsurfaceMetallicOrReflectivityColorMap=toLinearSpace(surfaceMetallicOrReflectivityColorMap);\r#endif\nsurfaceMetallicOrReflectivityColorMap.rgb*=vReflectivityInfos.y;\r#endif\n#endif\n#if defined(MICROSURFACEMAP)\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\r#endif\n#ifdef METALLICWORKFLOW\nvec4 metallicReflectanceFactors=vMetallicReflectanceFactors;\r#ifdef REFLECTANCE\nvec4 reflectanceFactorsMap=texture2D(reflectanceSampler,vReflectanceUV+uvOffset);\r#ifdef REFLECTANCE_GAMMA\nreflectanceFactorsMap=toLinearSpace(reflectanceFactorsMap);\r#endif\nmetallicReflectanceFactors.rgb*=reflectanceFactorsMap.rgb;\r#endif\n#ifdef METALLIC_REFLECTANCE\nvec4 metallicReflectanceFactorsMap=texture2D(metallicReflectanceSampler,vMetallicReflectanceUV+uvOffset);\r#ifdef METALLIC_REFLECTANCE_GAMMA\nmetallicReflectanceFactorsMap=toLinearSpace(metallicReflectanceFactorsMap);\r#endif\n#ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY\nmetallicReflectanceFactors.rgb*=metallicReflectanceFactorsMap.rgb;\r#endif\nmetallicReflectanceFactors*=metallicReflectanceFactorsMap.a;\r#endif\n#endif\nreflectivityBlock(\rvReflectivityColor,\r#ifdef METALLICWORKFLOW\nsurfaceAlbedo,\rmetallicReflectanceFactors,\r#endif\n#ifdef REFLECTIVITY\nvReflectivityInfos,\rsurfaceMetallicOrReflectivityColorMap,\r#endif\n#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\naoOut.ambientOcclusionColor,\r#endif\n#ifdef MICROSURFACEMAP\nmicroSurfaceTexel,\r#endif\n#ifdef DETAIL\ndetailColor,\rvDetailInfos,\r#endif\nreflectivityOut\r);\rfloat microSurface=reflectivityOut.microSurface;\rfloat roughness=reflectivityOut.roughness;\r#ifdef METALLICWORKFLOW\nsurfaceAlbedo=reflectivityOut.surfaceAlbedo;\r#endif\n#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\naoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor;\r#endif\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\nalphaFresnelOutParams alphaFresnelOut;\ralphaFresnelBlock(\rnormalW,\rviewDirectionW,\ralpha,\rmicroSurface,\ralphaFresnelOut\r);\ralpha=alphaFresnelOut.alpha;\r#endif\n#endif\n#include\n#ifdef ANISOTROPIC\nanisotropicOutParams anisotropicOut;\r#ifdef ANISOTROPIC_TEXTURE\nvec3 anisotropyMapData=texture2D(anisotropySampler,vAnisotropyUV+uvOffset).rgb*vAnisotropyInfos.y;\r#endif\nanisotropicBlock(\rvAnisotropy,\rroughness,\r#ifdef ANISOTROPIC_TEXTURE\nanisotropyMapData,\r#endif\nTBN,\rnormalW,\rviewDirectionW,\ranisotropicOut\r);\r#endif\n#ifdef REFLECTION\nreflectionOutParams reflectionOut;\r#ifndef USE_CUSTOM_REFLECTION\nreflectionBlock(\rvPositionW,\rnormalW,\ralphaG,\rvReflectionMicrosurfaceInfos,\rvReflectionInfos,\rvReflectionColor,\r#ifdef ANISOTROPIC\nanisotropicOut,\r#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nNdotVUnclamped,\r#endif\n#ifdef LINEARSPECULARREFLECTION\nroughness,\r#endif\nreflectionSampler,\r#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nvEnvironmentIrradiance,\r#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\nreflectionMatrix,\r#endif\n#endif\n#ifdef USEIRRADIANCEMAP\nirradianceSampler,\r#endif\n#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\rreflectionSamplerHigh,\r#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\r#endif\nreflectionOut\r);\r#else\n#define CUSTOM_REFLECTION\n#endif\n#endif\n#include\n#ifdef SHEEN\nsheenOutParams sheenOut;\r#ifdef SHEEN_TEXTURE\nvec4 sheenMapData=texture2D(sheenSampler,vSheenUV+uvOffset);\r#endif\n#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)\nvec4 sheenMapRoughnessData=texture2D(sheenRoughnessSampler,vSheenRoughnessUV+uvOffset)*vSheenInfos.w;\r#endif\nsheenBlock(\rvSheenColor,\r#ifdef SHEEN_ROUGHNESS\nvSheenRoughness,\r#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE)\nsheenMapRoughnessData,\r#endif\n#endif\nroughness,\r#ifdef SHEEN_TEXTURE\nsheenMapData,\rvSheenInfos.y,\r#endif\nreflectance,\r#ifdef SHEEN_LINKWITHALBEDO\nbaseColor,\rsurfaceAlbedo,\r#endif\n#ifdef ENVIRONMENTBRDF\nNdotV,\renvironmentBrdf,\r#endif\n#if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\nAARoughnessFactors,\rvReflectionMicrosurfaceInfos,\rvReflectionInfos,\rvReflectionColor,\rvLightingIntensity,\rreflectionSampler,\rreflectionOut.reflectionCoords,\rNdotVUnclamped,\r#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\rreflectionSamplerHigh,\r#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\r#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION)\nseo,\r#endif\n#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D)\neho,\r#endif\n#endif\nsheenOut\r);\r#ifdef SHEEN_LINKWITHALBEDO\nsurfaceAlbedo=sheenOut.surfaceAlbedo;\r#endif\n#endif\n#ifdef CLEARCOAT\n#ifdef CLEARCOAT_TEXTURE\nvec2 clearCoatMapData=texture2D(clearCoatSampler,vClearCoatUV+uvOffset).rg*vClearCoatInfos.y;\r#endif\n#endif\n#ifdef IRIDESCENCE\niridescenceOutParams iridescenceOut;\r#ifdef IRIDESCENCE_TEXTURE\nvec2 iridescenceMapData=texture2D(iridescenceSampler,vIridescenceUV+uvOffset).rg*vIridescenceInfos.y;\r#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nvec2 iridescenceThicknessMapData=texture2D(iridescenceThicknessSampler,vIridescenceThicknessUV+uvOffset).rg*vIridescenceInfos.w;\r#endif\niridescenceBlock(\rvIridescenceParams,\rNdotV,\rspecularEnvironmentR0,\r#ifdef IRIDESCENCE_TEXTURE\niridescenceMapData,\r#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\niridescenceThicknessMapData,\r#endif\n#ifdef CLEARCOAT\nNdotVUnclamped,\r#ifdef CLEARCOAT_TEXTURE\nclearCoatMapData,\r#endif\n#endif\niridescenceOut\r);\rfloat iridescenceIntensity=iridescenceOut.iridescenceIntensity;\rspecularEnvironmentR0=iridescenceOut.specularEnvironmentR0;\r#endif\nclearcoatOutParams clearcoatOut;\r#ifdef CLEARCOAT\n#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\nvec4 clearCoatMapRoughnessData=texture2D(clearCoatRoughnessSampler,vClearCoatRoughnessUV+uvOffset)*vClearCoatInfos.w;\r#endif\n#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE)\nvec4 clearCoatTintMapData=texture2D(clearCoatTintSampler,vClearCoatTintUV+uvOffset);\r#endif\n#ifdef CLEARCOAT_BUMP\nvec4 clearCoatBumpMapData=texture2D(clearCoatBumpSampler,vClearCoatBumpUV+uvOffset);\r#endif\nclearcoatBlock(\rvPositionW,\rgeometricNormalW,\rviewDirectionW,\rvClearCoatParams,\r#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE)\nclearCoatMapRoughnessData,\r#endif\nspecularEnvironmentR0,\r#ifdef CLEARCOAT_TEXTURE\nclearCoatMapData,\r#endif\n#ifdef CLEARCOAT_TINT\nvClearCoatTintParams,\rclearCoatColorAtDistance,\rvClearCoatRefractionParams,\r#ifdef CLEARCOAT_TINT_TEXTURE\nclearCoatTintMapData,\r#endif\n#endif\n#ifdef CLEARCOAT_BUMP\nvClearCoatBumpInfos,\rclearCoatBumpMapData,\rvClearCoatBumpUV,\r#if defined(TANGENT) && defined(NORMAL)\nvTBN,\r#else\nvClearCoatTangentSpaceParams,\r#endif\n#ifdef OBJECTSPACE_NORMALMAP\nnormalMatrix,\r#endif\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nfaceNormal,\r#endif\n#ifdef REFLECTION\nvReflectionMicrosurfaceInfos,\rvReflectionInfos,\rvReflectionColor,\rvLightingIntensity,\rreflectionSampler,\r#ifndef LODBASEDMICROSFURACE\nreflectionSamplerLow,\rreflectionSamplerHigh,\r#endif\n#ifdef REALTIME_FILTERING\nvReflectionFilteringInfo,\r#endif\n#endif\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n#ifdef RADIANCEOCCLUSION\nambientMonochrome,\r#endif\n#endif\n#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)\n(gl_FrontFacing ? 1. : -1.),\r#endif\nclearcoatOut\r);\r#else\nclearcoatOut.specularEnvironmentR0=specularEnvironmentR0;\r#endif\n#include\nsubSurfaceOutParams subSurfaceOut;\r#ifdef SUBSURFACE\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nvec4 thicknessMap=texture2D(thicknessSampler,vThicknessUV+uvOffset);\r#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nvec4 refractionIntensityMap=texture2D(refractionIntensitySampler,vRefractionIntensityUV+uvOffset);\r#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nvec4 translucencyIntensityMap=texture2D(translucencyIntensitySampler,vTranslucencyIntensityUV+uvOffset);\r#endif\nsubSurfaceBlock(\rvSubSurfaceIntensity,\rvThicknessParam,\rvTintColor,\rnormalW,\rspecularEnvironmentReflectance,\r#ifdef SS_THICKNESSANDMASK_TEXTURE\nthicknessMap,\r#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nrefractionIntensityMap,\r#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\ntranslucencyIntensityMap,\r#endif\n#ifdef REFLECTION\n#ifdef SS_TRANSLUCENCY\nreflectionMatrix,\r#ifdef USESPHERICALFROMREFLECTIONMAP\n#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\nreflectionOut.irradianceVector,\r#endif\n#if defined(REALTIME_FILTERING)\nreflectionSampler,\rvReflectionFilteringInfo,\r#endif\n#endif\n#ifdef USEIRRADIANCEMAP\nirradianceSampler,\r#endif\n#endif\n#endif\n#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)\nsurfaceAlbedo,\r#endif\n#ifdef SS_REFRACTION\nvPositionW,\rviewDirectionW,\rview,\rvRefractionInfos,\rrefractionMatrix,\rvRefractionMicrosurfaceInfos,\rvLightingIntensity,\r#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nalpha,\r#endif\n#ifdef SS_LODINREFRACTIONALPHA\nNdotVUnclamped,\r#endif\n#ifdef SS_LINEARSPECULARREFRACTION\nroughness,\r#endif\nalphaG,\rrefractionSampler,\r#ifndef LODBASEDMICROSFURACE\nrefractionSamplerLow,\rrefractionSamplerHigh,\r#endif\n#ifdef ANISOTROPIC\nanisotropicOut,\r#endif\n#ifdef REALTIME_FILTERING\nvRefractionFilteringInfo,\r#endif\n#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\nvRefractionPosition,\rvRefractionSize,\r#endif\n#endif\n#ifdef SS_TRANSLUCENCY\nvDiffusionDistance,\r#endif\nsubSurfaceOut\r);\r#ifdef SS_REFRACTION\nsurfaceAlbedo=subSurfaceOut.surfaceAlbedo;\r#ifdef SS_LINKREFRACTIONTOTRANSPARENCY\nalpha=subSurfaceOut.alpha;\r#endif\n#endif\n#else\nsubSurfaceOut.specularEnvironmentReflectance=specularEnvironmentReflectance;\r#endif\n#include\n#include[0..maxSimultaneousLights]\n#include\n#endif \n#include\n#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION\n#include\n#include\n#include(color,finalColor)\n#include\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\n#ifdef PREPASS\nfloat writeGeometryInfo=finalColor.a>0.4 ? 1.0 : 0.0;\r#ifdef PREPASS_POSITION\ngl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo);\r#endif\n#ifdef PREPASS_VELOCITY\nvec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;\rvec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;\rvec2 velocity=abs(a-b);\rvelocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;\rgl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo);\r#endif\n#ifdef PREPASS_ALBEDO_SQRT\nvec3 sqAlbedo=sqrt(surfaceAlbedo); \r#endif\n#ifdef PREPASS_IRRADIANCE\nvec3 irradiance=finalDiffuse;\r#ifndef UNLIT\n#ifdef REFLECTION\nirradiance+=finalIrradiance;\r#endif\n#endif\n#ifdef SS_SCATTERING\ngl_FragData[0]=vec4(finalColor.rgb-irradiance,finalColor.a); \rirradiance/=sqAlbedo;\r#else\ngl_FragData[0]=finalColor; \rfloat scatteringDiffusionProfile=255.;\r#endif\ngl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(clamp(irradiance,vec3(0.),vec3(1.)),writeGeometryInfo*scatteringDiffusionProfile/255.); \r#else\ngl_FragData[0]=vec4(finalColor.rgb,finalColor.a);\r#endif\n#ifdef PREPASS_DEPTH\ngl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); \r#endif\n#ifdef PREPASS_NORMAL\ngl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); \r#endif\n#ifdef PREPASS_ALBEDO_SQRT\ngl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqAlbedo,writeGeometryInfo); \r#endif\n#ifdef PREPASS_REFLECTIVITY\n#ifndef UNLIT\ngl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(specularEnvironmentR0,microSurface)*writeGeometryInfo;\r#else\ngl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4( 0.0,0.0,0.0,1.0 )*writeGeometryInfo;\r#endif\n#endif\n#endif\n#if !defined(PREPASS) || defined(WEBGL2)\ngl_FragColor=finalColor;\r#endif\n#include\n#if ORDER_INDEPENDENT_TRANSPARENCY\nif (fragDepth==nearestDepth) {\rfrontColor.rgb+=finalColor.rgb*finalColor.a*alphaMultiplier;\rfrontColor.a=1.0-alphaMultiplier*(1.0-finalColor.a);\r} else {\rbackColor+=finalColor;\r}\r#endif\n#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const pbrPixelShader = { name, shader };\n//# sourceMappingURL=pbr.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nimport \"./decalVertexDeclaration.js\";\nconst name = \"pbrVertexDeclaration\";\nconst shader = `uniform mat4 view;\runiform mat4 viewProjection;\r#ifdef ALBEDO\nuniform mat4 albedoMatrix;\runiform vec2 vAlbedoInfos;\r#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\runiform vec4 vAmbientInfos;\r#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\runiform vec2 vOpacityInfos;\r#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\runiform mat4 emissiveMatrix;\r#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\runiform mat4 lightmapMatrix;\r#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\runiform mat4 reflectivityMatrix;\r#endif\n#ifdef METALLIC_REFLECTANCE\nuniform vec2 vMetallicReflectanceInfos;\runiform mat4 metallicReflectanceMatrix;\r#endif\n#ifdef REFLECTANCE\nuniform vec2 vReflectanceInfos;\runiform mat4 reflectanceMatrix;\r#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\runiform mat4 microSurfaceSamplerMatrix;\r#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\runiform mat4 bumpMatrix;\r#endif\n#ifdef POINTSIZE\nuniform float pointSize;\r#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\runiform mat4 reflectionMatrix;\r#endif\n#ifdef CLEARCOAT\n#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS)\nuniform vec4 vClearCoatInfos;\r#endif\n#ifdef CLEARCOAT_TEXTURE\nuniform mat4 clearCoatMatrix;\r#endif\n#ifdef CLEARCOAT_TEXTURE_ROUGHNESS\nuniform mat4 clearCoatRoughnessMatrix;\r#endif\n#ifdef CLEARCOAT_BUMP\nuniform vec2 vClearCoatBumpInfos;\runiform mat4 clearCoatBumpMatrix;\r#endif\n#ifdef CLEARCOAT_TINT_TEXTURE\nuniform vec2 vClearCoatTintInfos;\runiform mat4 clearCoatTintMatrix;\r#endif\n#endif\n#ifdef IRIDESCENCE\n#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE)\nuniform vec4 vIridescenceInfos;\r#endif\n#ifdef IRIDESCENCE_TEXTURE\nuniform mat4 iridescenceMatrix;\r#endif\n#ifdef IRIDESCENCE_THICKNESS_TEXTURE\nuniform mat4 iridescenceThicknessMatrix;\r#endif\n#endif\n#ifdef ANISOTROPIC\n#ifdef ANISOTROPIC_TEXTURE\nuniform vec2 vAnisotropyInfos;\runiform mat4 anisotropyMatrix;\r#endif\n#endif\n#ifdef SHEEN\n#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS)\nuniform vec4 vSheenInfos;\r#endif\n#ifdef SHEEN_TEXTURE\nuniform mat4 sheenMatrix;\r#endif\n#ifdef SHEEN_TEXTURE_ROUGHNESS\nuniform mat4 sheenRoughnessMatrix;\r#endif\n#endif\n#ifdef SUBSURFACE\n#ifdef SS_REFRACTION\nuniform vec4 vRefractionInfos;\runiform mat4 refractionMatrix;\r#endif\n#ifdef SS_THICKNESSANDMASK_TEXTURE\nuniform vec2 vThicknessInfos;\runiform mat4 thicknessMatrix;\r#endif\n#ifdef SS_REFRACTIONINTENSITY_TEXTURE\nuniform vec2 vRefractionIntensityInfos;\runiform mat4 refractionIntensityMatrix;\r#endif\n#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE\nuniform vec2 vTranslucencyIntensityInfos;\runiform mat4 translucencyIntensityMatrix;\r#endif\n#endif\n#ifdef NORMAL\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifdef SPHERICAL_HARMONICS\nuniform vec3 vSphericalL00;\runiform vec3 vSphericalL1_1;\runiform vec3 vSphericalL10;\runiform vec3 vSphericalL11;\runiform vec3 vSphericalL2_2;\runiform vec3 vSphericalL2_1;\runiform vec3 vSphericalL20;\runiform vec3 vSphericalL21;\runiform vec3 vSphericalL22;\r#else\nuniform vec3 vSphericalX;\runiform vec3 vSphericalY;\runiform vec3 vSphericalZ;\runiform vec3 vSphericalXX_ZZ;\runiform vec3 vSphericalYY_ZZ;\runiform vec3 vSphericalZZ;\runiform vec3 vSphericalXY;\runiform vec3 vSphericalYZ;\runiform vec3 vSphericalZX;\r#endif\n#endif\n#endif\n#endif\n#ifdef DETAIL\nuniform vec4 vDetailInfos;\runiform mat4 detailMatrix;\r#endif\n#include\n#define ADDITIONAL_VERTEX_DECLARATION\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const pbrVertexDeclaration = { name, shader };\n//# sourceMappingURL=pbrVertexDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/pbrVertexDeclaration.js\";\nimport \"./ShadersInclude/pbrUboDeclaration.js\";\nimport \"./ShadersInclude/uvAttributeDeclaration.js\";\nimport \"./ShadersInclude/mainUVVaryingDeclaration.js\";\nimport \"./ShadersInclude/helperFunctions.js\";\nimport \"./ShadersInclude/bonesDeclaration.js\";\nimport \"./ShadersInclude/bakedVertexAnimationDeclaration.js\";\nimport \"./ShadersInclude/instancesDeclaration.js\";\nimport \"./ShadersInclude/prePassVertexDeclaration.js\";\nimport \"./ShadersInclude/samplerVertexDeclaration.js\";\nimport \"./ShadersInclude/harmonicsFunctions.js\";\nimport \"./ShadersInclude/bumpVertexDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneVertexDeclaration.js\";\nimport \"./ShadersInclude/fogVertexDeclaration.js\";\nimport \"./ShadersInclude/lightVxFragmentDeclaration.js\";\nimport \"./ShadersInclude/lightVxUboDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexGlobalDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexDeclaration.js\";\nimport \"./ShadersInclude/logDepthDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexGlobal.js\";\nimport \"./ShadersInclude/morphTargetsVertex.js\";\nimport \"./ShadersInclude/instancesVertex.js\";\nimport \"./ShadersInclude/bonesVertex.js\";\nimport \"./ShadersInclude/bakedVertexAnimation.js\";\nimport \"./ShadersInclude/prePassVertex.js\";\nimport \"./ShadersInclude/uvVariableDeclaration.js\";\nimport \"./ShadersInclude/samplerVertexImplementation.js\";\nimport \"./ShadersInclude/bumpVertex.js\";\nimport \"./ShadersInclude/clipPlaneVertex.js\";\nimport \"./ShadersInclude/fogVertex.js\";\nimport \"./ShadersInclude/shadowsVertex.js\";\nimport \"./ShadersInclude/vertexColorMixing.js\";\nimport \"./ShadersInclude/logDepthVertex.js\";\nconst name = \"pbrVertexShader\";\nconst shader = `precision highp float;\r#include<__decl__pbrVertex>\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\r#ifdef NORMAL\nattribute vec3 normal;\r#endif\n#ifdef TANGENT\nattribute vec4 tangent;\r#endif\n#ifdef UV1\nattribute vec2 uv;\r#endif\n#include[2..7]\n#include[1..7]\n#ifdef VERTEXCOLOR\nattribute vec4 color;\r#endif\n#include\n#include\n#include\n#include\n#include\n#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance)\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness)\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness)\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy)\n#endif\n#ifdef SUBSURFACE\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity)\n#endif\nvarying vec3 vPositionW;\r#if DEBUGMODE>0\nvarying vec4 vClipSpacePosition;\r#endif\n#ifdef NORMAL\nvarying vec3 vNormalW;\r#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\r#include\n#endif\n#endif\n#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES)\nvarying vec4 vColor;\r#endif\n#include\n#include\n#include\n#include<__decl__lightVxFragment>[0..maxSimultaneousLights]\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\r#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\r#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\r#ifdef NORMAL\nvec3 normalUpdated=normal;\r#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\r#endif\n#ifdef UV1\nvec2 uvUpdated=uv;\r#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\r#endif\n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include\n#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED)\nvCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\rvPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0);\r#endif\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\rvPositionW=vec3(worldPos);\r#include\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\r#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));\rvNormalW=normalize(normalWorld*vNormalW);\r#else\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\r#endif\nvNormalW=normalize(normalWorld*normalUpdated);\r#endif\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\r#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\r#endif\nvEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector);\r#endif\n#endif\n#define CUSTOM_VERTEX_UPDATE_WORLDPOS\n#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {\rgl_Position=viewProjection*worldPos;\r} else {\rgl_Position=viewProjectionR*worldPos;\r}\r#else\ngl_Position=viewProjection*worldPos;\r#endif\n#if DEBUGMODE>0\nvClipSpacePosition=gl_Position;\r#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\r#endif\n#ifndef UV1\nvec2 uvUpdated=vec2(0.,0.);\r#endif\n#ifdef MAINUV1\nvMainUV1=uvUpdated;\r#endif\n#include[2..7]\n#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x)\n#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x)\n#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x)\n#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x)\n#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x)\n#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x)\n#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x)\n#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x)\n#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x)\n#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x)\n#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x)\n#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x)\n#ifdef CLEARCOAT\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x)\n#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z)\n#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x)\n#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x)\n#endif\n#ifdef IRIDESCENCE\n#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x)\n#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z)\n#endif\n#ifdef SHEEN\n#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x)\n#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.z)\n#endif\n#ifdef ANISOTROPIC\n#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x)\n#endif\n#ifdef SUBSURFACE\n#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x)\n#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x)\n#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x)\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#include\n#if defined(POINTSIZE) && !defined(WEBGPU)\ngl_PointSize=pointSize;\r#endif\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const pbrVertexShader = { name, shader };\n//# sourceMappingURL=pbr.vertex.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize, serializeAsTexture, expandToProperty, serializeAsColor3 } from \"../../Misc/decorators.js\";\nimport { Color3 } from \"../../Maths/math.color.js\";\nimport { MaterialFlags } from \"../materialFlags.js\";\nimport { MaterialHelper } from \"../../Materials/materialHelper.js\";\n\nimport { MaterialPluginBase } from \"../materialPluginBase.js\";\nimport { MaterialDefines } from \"../materialDefines.js\";\n/**\n * @internal\n */\nexport class MaterialClearCoatDefines extends MaterialDefines {\n constructor() {\n super(...arguments);\n this.CLEARCOAT = false;\n this.CLEARCOAT_DEFAULTIOR = false;\n this.CLEARCOAT_TEXTURE = false;\n this.CLEARCOAT_TEXTURE_ROUGHNESS = false;\n this.CLEARCOAT_TEXTUREDIRECTUV = 0;\n this.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV = 0;\n this.CLEARCOAT_BUMP = false;\n this.CLEARCOAT_BUMPDIRECTUV = 0;\n this.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE = false;\n this.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL = false;\n this.CLEARCOAT_REMAP_F0 = false;\n this.CLEARCOAT_TINT = false;\n this.CLEARCOAT_TINT_TEXTURE = false;\n this.CLEARCOAT_TINT_TEXTUREDIRECTUV = 0;\n this.CLEARCOAT_TINT_GAMMATEXTURE = false;\n }\n}\n/**\n * Plugin that implements the clear coat component of the PBR material\n */\nexport class PBRClearCoatConfiguration extends MaterialPluginBase {\n /** @internal */\n _markAllSubMeshesAsTexturesDirty() {\n this._enable(this._isEnabled);\n this._internalMarkAllSubMeshesAsTexturesDirty();\n }\n constructor(material, addToPluginList = true) {\n super(material, \"PBRClearCoat\", 100, new MaterialClearCoatDefines(), addToPluginList);\n this._isEnabled = false;\n /**\n * Defines if the clear coat is enabled in the material.\n */\n this.isEnabled = false;\n /**\n * Defines the clear coat layer strength (between 0 and 1) it defaults to 1.\n */\n this.intensity = 1;\n /**\n * Defines the clear coat layer roughness.\n */\n this.roughness = 0;\n this._indexOfRefraction = PBRClearCoatConfiguration._DefaultIndexOfRefraction;\n /**\n * Defines the index of refraction of the clear coat.\n * This defaults to 1.5 corresponding to a 0.04 f0 or a 4% reflectance at normal incidence\n * The default fits with a polyurethane material.\n * Changing the default value is more performance intensive.\n */\n this.indexOfRefraction = PBRClearCoatConfiguration._DefaultIndexOfRefraction;\n this._texture = null;\n /**\n * Stores the clear coat values in a texture (red channel is intensity and green channel is roughness)\n * If useRoughnessFromMainTexture is false, the green channel of texture is not used and the green channel of textureRoughness is used instead\n * if textureRoughness is not empty, else no texture roughness is used\n */\n this.texture = null;\n this._useRoughnessFromMainTexture = true;\n /**\n * Indicates that the green channel of the texture property will be used for roughness (default: true)\n * If false, the green channel from textureRoughness is used for roughness\n */\n this.useRoughnessFromMainTexture = true;\n this._textureRoughness = null;\n /**\n * Stores the clear coat roughness in a texture (green channel)\n * Not used if useRoughnessFromMainTexture is true\n */\n this.textureRoughness = null;\n this._remapF0OnInterfaceChange = true;\n /**\n * Defines if the F0 value should be remapped to account for the interface change in the material.\n */\n this.remapF0OnInterfaceChange = true;\n this._bumpTexture = null;\n /**\n * Define the clear coat specific bump texture.\n */\n this.bumpTexture = null;\n this._isTintEnabled = false;\n /**\n * Defines if the clear coat tint is enabled in the material.\n */\n this.isTintEnabled = false;\n /**\n * Defines the clear coat tint of the material.\n * This is only use if tint is enabled\n */\n this.tintColor = Color3.White();\n /**\n * Defines the distance at which the tint color should be found in the\n * clear coat media.\n * This is only use if tint is enabled\n */\n this.tintColorAtDistance = 1;\n /**\n * Defines the clear coat layer thickness.\n * This is only use if tint is enabled\n */\n this.tintThickness = 1;\n this._tintTexture = null;\n /**\n * Stores the clear tint values in a texture.\n * rgb is tint\n * a is a thickness factor\n */\n this.tintTexture = null;\n this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];\n }\n isReadyForSubMesh(defines, scene, engine) {\n if (!this._isEnabled) {\n return true;\n }\n const disableBumpMap = this._material._disableBumpMap;\n if (defines._areTexturesDirty) {\n if (scene.texturesEnabled) {\n if (this._texture && MaterialFlags.ClearCoatTextureEnabled) {\n if (!this._texture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._textureRoughness && MaterialFlags.ClearCoatTextureEnabled) {\n if (!this._textureRoughness.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (engine.getCaps().standardDerivatives && this._bumpTexture && MaterialFlags.ClearCoatBumpTextureEnabled && !disableBumpMap) {\n // Bump texture cannot be not blocking.\n if (!this._bumpTexture.isReady()) {\n return false;\n }\n }\n if (this._isTintEnabled && this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled) {\n if (!this._tintTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n }\n }\n return true;\n }\n prepareDefinesBeforeAttributes(defines, scene) {\n var _a;\n if (this._isEnabled) {\n defines.CLEARCOAT = true;\n defines.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE = this._useRoughnessFromMainTexture;\n defines.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL =\n this._texture !== null && this._texture._texture === ((_a = this._textureRoughness) === null || _a === void 0 ? void 0 : _a._texture) && this._texture.checkTransformsAreIdentical(this._textureRoughness);\n defines.CLEARCOAT_REMAP_F0 = this._remapF0OnInterfaceChange;\n if (defines._areTexturesDirty) {\n if (scene.texturesEnabled) {\n if (this._texture && MaterialFlags.ClearCoatTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._texture, defines, \"CLEARCOAT_TEXTURE\");\n }\n else {\n defines.CLEARCOAT_TEXTURE = false;\n }\n if (this._textureRoughness && MaterialFlags.ClearCoatTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._textureRoughness, defines, \"CLEARCOAT_TEXTURE_ROUGHNESS\");\n }\n else {\n defines.CLEARCOAT_TEXTURE_ROUGHNESS = false;\n }\n if (this._bumpTexture && MaterialFlags.ClearCoatBumpTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, \"CLEARCOAT_BUMP\");\n }\n else {\n defines.CLEARCOAT_BUMP = false;\n }\n defines.CLEARCOAT_DEFAULTIOR = this._indexOfRefraction === PBRClearCoatConfiguration._DefaultIndexOfRefraction;\n if (this._isTintEnabled) {\n defines.CLEARCOAT_TINT = true;\n if (this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._tintTexture, defines, \"CLEARCOAT_TINT_TEXTURE\");\n defines.CLEARCOAT_TINT_GAMMATEXTURE = this._tintTexture.gammaSpace;\n }\n else {\n defines.CLEARCOAT_TINT_TEXTURE = false;\n }\n }\n else {\n defines.CLEARCOAT_TINT = false;\n defines.CLEARCOAT_TINT_TEXTURE = false;\n }\n }\n }\n }\n else {\n defines.CLEARCOAT = false;\n defines.CLEARCOAT_TEXTURE = false;\n defines.CLEARCOAT_TEXTURE_ROUGHNESS = false;\n defines.CLEARCOAT_BUMP = false;\n defines.CLEARCOAT_TINT = false;\n defines.CLEARCOAT_TINT_TEXTURE = false;\n defines.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE = false;\n defines.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL = false;\n defines.CLEARCOAT_DEFAULTIOR = false;\n defines.CLEARCOAT_TEXTUREDIRECTUV = 0;\n defines.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV = 0;\n defines.CLEARCOAT_BUMPDIRECTUV = 0;\n defines.CLEARCOAT_REMAP_F0 = false;\n defines.CLEARCOAT_TINT_TEXTUREDIRECTUV = 0;\n defines.CLEARCOAT_TINT_GAMMATEXTURE = false;\n }\n }\n bindForSubMesh(uniformBuffer, scene, engine, subMesh) {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n if (!this._isEnabled) {\n return;\n }\n const defines = subMesh.materialDefines;\n const isFrozen = this._material.isFrozen;\n const disableBumpMap = this._material._disableBumpMap;\n const invertNormalMapX = this._material._invertNormalMapX;\n const invertNormalMapY = this._material._invertNormalMapY;\n const identicalTextures = defines.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL;\n if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {\n if (identicalTextures && MaterialFlags.ClearCoatTextureEnabled) {\n uniformBuffer.updateFloat4(\"vClearCoatInfos\", this._texture.coordinatesIndex, this._texture.level, -1, -1);\n MaterialHelper.BindTextureMatrix(this._texture, uniformBuffer, \"clearCoat\");\n }\n else if ((this._texture || this._textureRoughness) && MaterialFlags.ClearCoatTextureEnabled) {\n uniformBuffer.updateFloat4(\"vClearCoatInfos\", (_b = (_a = this._texture) === null || _a === void 0 ? void 0 : _a.coordinatesIndex) !== null && _b !== void 0 ? _b : 0, (_d = (_c = this._texture) === null || _c === void 0 ? void 0 : _c.level) !== null && _d !== void 0 ? _d : 0, (_f = (_e = this._textureRoughness) === null || _e === void 0 ? void 0 : _e.coordinatesIndex) !== null && _f !== void 0 ? _f : 0, (_h = (_g = this._textureRoughness) === null || _g === void 0 ? void 0 : _g.level) !== null && _h !== void 0 ? _h : 0);\n if (this._texture) {\n MaterialHelper.BindTextureMatrix(this._texture, uniformBuffer, \"clearCoat\");\n }\n if (this._textureRoughness && !identicalTextures && !defines.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) {\n MaterialHelper.BindTextureMatrix(this._textureRoughness, uniformBuffer, \"clearCoatRoughness\");\n }\n }\n if (this._bumpTexture && engine.getCaps().standardDerivatives && MaterialFlags.ClearCoatTextureEnabled && !disableBumpMap) {\n uniformBuffer.updateFloat2(\"vClearCoatBumpInfos\", this._bumpTexture.coordinatesIndex, this._bumpTexture.level);\n MaterialHelper.BindTextureMatrix(this._bumpTexture, uniformBuffer, \"clearCoatBump\");\n if (scene._mirroredCameraPosition) {\n uniformBuffer.updateFloat2(\"vClearCoatTangentSpaceParams\", invertNormalMapX ? 1.0 : -1.0, invertNormalMapY ? 1.0 : -1.0);\n }\n else {\n uniformBuffer.updateFloat2(\"vClearCoatTangentSpaceParams\", invertNormalMapX ? -1.0 : 1.0, invertNormalMapY ? -1.0 : 1.0);\n }\n }\n if (this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled) {\n uniformBuffer.updateFloat2(\"vClearCoatTintInfos\", this._tintTexture.coordinatesIndex, this._tintTexture.level);\n MaterialHelper.BindTextureMatrix(this._tintTexture, uniformBuffer, \"clearCoatTint\");\n }\n // Clear Coat General params\n uniformBuffer.updateFloat2(\"vClearCoatParams\", this.intensity, this.roughness);\n // Clear Coat Refraction params\n const a = 1 - this._indexOfRefraction;\n const b = 1 + this._indexOfRefraction;\n const f0 = Math.pow(-a / b, 2); // Schlicks approx: (ior1 - ior2) / (ior1 + ior2) where ior2 for air is close to vacuum = 1.\n const eta = 1 / this._indexOfRefraction;\n uniformBuffer.updateFloat4(\"vClearCoatRefractionParams\", f0, eta, a, b);\n if (this._isTintEnabled) {\n uniformBuffer.updateFloat4(\"vClearCoatTintParams\", this.tintColor.r, this.tintColor.g, this.tintColor.b, Math.max(0.00001, this.tintThickness));\n uniformBuffer.updateFloat(\"clearCoatColorAtDistance\", Math.max(0.00001, this.tintColorAtDistance));\n }\n }\n // Textures\n if (scene.texturesEnabled) {\n if (this._texture && MaterialFlags.ClearCoatTextureEnabled) {\n uniformBuffer.setTexture(\"clearCoatSampler\", this._texture);\n }\n if (this._textureRoughness && !identicalTextures && !defines.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE && MaterialFlags.ClearCoatTextureEnabled) {\n uniformBuffer.setTexture(\"clearCoatRoughnessSampler\", this._textureRoughness);\n }\n if (this._bumpTexture && engine.getCaps().standardDerivatives && MaterialFlags.ClearCoatBumpTextureEnabled && !disableBumpMap) {\n uniformBuffer.setTexture(\"clearCoatBumpSampler\", this._bumpTexture);\n }\n if (this._isTintEnabled && this._tintTexture && MaterialFlags.ClearCoatTintTextureEnabled) {\n uniformBuffer.setTexture(\"clearCoatTintSampler\", this._tintTexture);\n }\n }\n }\n hasTexture(texture) {\n if (this._texture === texture) {\n return true;\n }\n if (this._textureRoughness === texture) {\n return true;\n }\n if (this._bumpTexture === texture) {\n return true;\n }\n if (this._tintTexture === texture) {\n return true;\n }\n return false;\n }\n getActiveTextures(activeTextures) {\n if (this._texture) {\n activeTextures.push(this._texture);\n }\n if (this._textureRoughness) {\n activeTextures.push(this._textureRoughness);\n }\n if (this._bumpTexture) {\n activeTextures.push(this._bumpTexture);\n }\n if (this._tintTexture) {\n activeTextures.push(this._tintTexture);\n }\n }\n getAnimatables(animatables) {\n if (this._texture && this._texture.animations && this._texture.animations.length > 0) {\n animatables.push(this._texture);\n }\n if (this._textureRoughness && this._textureRoughness.animations && this._textureRoughness.animations.length > 0) {\n animatables.push(this._textureRoughness);\n }\n if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {\n animatables.push(this._bumpTexture);\n }\n if (this._tintTexture && this._tintTexture.animations && this._tintTexture.animations.length > 0) {\n animatables.push(this._tintTexture);\n }\n }\n dispose(forceDisposeTextures) {\n var _a, _b, _c, _d;\n if (forceDisposeTextures) {\n (_a = this._texture) === null || _a === void 0 ? void 0 : _a.dispose();\n (_b = this._textureRoughness) === null || _b === void 0 ? void 0 : _b.dispose();\n (_c = this._bumpTexture) === null || _c === void 0 ? void 0 : _c.dispose();\n (_d = this._tintTexture) === null || _d === void 0 ? void 0 : _d.dispose();\n }\n }\n getClassName() {\n return \"PBRClearCoatConfiguration\";\n }\n addFallbacks(defines, fallbacks, currentRank) {\n if (defines.CLEARCOAT_BUMP) {\n fallbacks.addFallback(currentRank++, \"CLEARCOAT_BUMP\");\n }\n if (defines.CLEARCOAT_TINT) {\n fallbacks.addFallback(currentRank++, \"CLEARCOAT_TINT\");\n }\n if (defines.CLEARCOAT) {\n fallbacks.addFallback(currentRank++, \"CLEARCOAT\");\n }\n return currentRank;\n }\n getSamplers(samplers) {\n samplers.push(\"clearCoatSampler\", \"clearCoatRoughnessSampler\", \"clearCoatBumpSampler\", \"clearCoatTintSampler\");\n }\n getUniforms() {\n return {\n ubo: [\n { name: \"vClearCoatParams\", size: 2, type: \"vec2\" },\n { name: \"vClearCoatRefractionParams\", size: 4, type: \"vec4\" },\n { name: \"vClearCoatInfos\", size: 4, type: \"vec4\" },\n { name: \"clearCoatMatrix\", size: 16, type: \"mat4\" },\n { name: \"clearCoatRoughnessMatrix\", size: 16, type: \"mat4\" },\n { name: \"vClearCoatBumpInfos\", size: 2, type: \"vec2\" },\n { name: \"vClearCoatTangentSpaceParams\", size: 2, type: \"vec2\" },\n { name: \"clearCoatBumpMatrix\", size: 16, type: \"mat4\" },\n { name: \"vClearCoatTintParams\", size: 4, type: \"vec4\" },\n { name: \"clearCoatColorAtDistance\", size: 1, type: \"float\" },\n { name: \"vClearCoatTintInfos\", size: 2, type: \"vec2\" },\n { name: \"clearCoatTintMatrix\", size: 16, type: \"mat4\" },\n ],\n };\n }\n}\n/**\n * This defaults to 1.5 corresponding to a 0.04 f0 or a 4% reflectance at normal incidence\n * The default fits with a polyurethane material.\n * @internal\n */\nPBRClearCoatConfiguration._DefaultIndexOfRefraction = 1.5;\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRClearCoatConfiguration.prototype, \"isEnabled\", void 0);\n__decorate([\n serialize()\n], PBRClearCoatConfiguration.prototype, \"intensity\", void 0);\n__decorate([\n serialize()\n], PBRClearCoatConfiguration.prototype, \"roughness\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRClearCoatConfiguration.prototype, \"indexOfRefraction\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRClearCoatConfiguration.prototype, \"texture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRClearCoatConfiguration.prototype, \"useRoughnessFromMainTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRClearCoatConfiguration.prototype, \"textureRoughness\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRClearCoatConfiguration.prototype, \"remapF0OnInterfaceChange\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRClearCoatConfiguration.prototype, \"bumpTexture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRClearCoatConfiguration.prototype, \"isTintEnabled\", void 0);\n__decorate([\n serializeAsColor3()\n], PBRClearCoatConfiguration.prototype, \"tintColor\", void 0);\n__decorate([\n serialize()\n], PBRClearCoatConfiguration.prototype, \"tintColorAtDistance\", void 0);\n__decorate([\n serialize()\n], PBRClearCoatConfiguration.prototype, \"tintThickness\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRClearCoatConfiguration.prototype, \"tintTexture\", void 0);\n//# sourceMappingURL=pbrClearCoatConfiguration.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize, serializeAsTexture, expandToProperty } from \"../../Misc/decorators.js\";\nimport { MaterialFlags } from \"../materialFlags.js\";\nimport { MaterialHelper } from \"../../Materials/materialHelper.js\";\n\nimport { MaterialPluginBase } from \"../materialPluginBase.js\";\nimport { MaterialDefines } from \"../materialDefines.js\";\n/**\n * @internal\n */\nexport class MaterialIridescenceDefines extends MaterialDefines {\n constructor() {\n super(...arguments);\n this.IRIDESCENCE = false;\n this.IRIDESCENCE_TEXTURE = false;\n this.IRIDESCENCE_TEXTUREDIRECTUV = 0;\n this.IRIDESCENCE_THICKNESS_TEXTURE = false;\n this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV = 0;\n this.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE = false;\n }\n}\n/**\n * Plugin that implements the iridescence (thin film) component of the PBR material\n */\nexport class PBRIridescenceConfiguration extends MaterialPluginBase {\n /** @internal */\n _markAllSubMeshesAsTexturesDirty() {\n this._enable(this._isEnabled);\n this._internalMarkAllSubMeshesAsTexturesDirty();\n }\n constructor(material, addToPluginList = true) {\n super(material, \"PBRIridescence\", 110, new MaterialIridescenceDefines(), addToPluginList);\n this._isEnabled = false;\n /**\n * Defines if the iridescence is enabled in the material.\n */\n this.isEnabled = false;\n /**\n * Defines the iridescence layer strength (between 0 and 1) it defaults to 1.\n */\n this.intensity = 1;\n /**\n * Defines the minimum thickness of the thin-film layer given in nanometers (nm).\n */\n this.minimumThickness = PBRIridescenceConfiguration._DefaultMinimumThickness;\n /**\n * Defines the maximum thickness of the thin-film layer given in nanometers (nm). This will be the thickness used if not thickness texture has been set.\n */\n this.maximumThickness = PBRIridescenceConfiguration._DefaultMaximumThickness;\n /**\n * Defines the maximum thickness of the thin-film layer given in nanometers (nm).\n */\n this.indexOfRefraction = PBRIridescenceConfiguration._DefaultIndexOfRefraction;\n this._texture = null;\n /**\n * Stores the iridescence intensity in a texture (red channel)\n */\n this.texture = null;\n this._thicknessTexture = null;\n /**\n * Stores the iridescence thickness in a texture (green channel)\n */\n this.thicknessTexture = null;\n this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];\n }\n isReadyForSubMesh(defines, scene) {\n if (!this._isEnabled) {\n return true;\n }\n if (defines._areTexturesDirty) {\n if (scene.texturesEnabled) {\n if (this._texture && MaterialFlags.IridescenceTextureEnabled) {\n if (!this._texture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._thicknessTexture && MaterialFlags.IridescenceTextureEnabled) {\n if (!this._thicknessTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n }\n }\n return true;\n }\n prepareDefinesBeforeAttributes(defines, scene) {\n var _a;\n if (this._isEnabled) {\n defines.IRIDESCENCE = true;\n defines.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE =\n this._texture !== null && this._texture._texture === ((_a = this._thicknessTexture) === null || _a === void 0 ? void 0 : _a._texture) && this._texture.checkTransformsAreIdentical(this._thicknessTexture);\n if (defines._areTexturesDirty) {\n if (scene.texturesEnabled) {\n if (this._texture && MaterialFlags.IridescenceTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._texture, defines, \"IRIDESCENCE_TEXTURE\");\n }\n else {\n defines.IRIDESCENCE_TEXTURE = false;\n }\n if (!defines.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE && this._thicknessTexture && MaterialFlags.IridescenceTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._thicknessTexture, defines, \"IRIDESCENCE_THICKNESS_TEXTURE\");\n }\n else {\n defines.IRIDESCENCE_THICKNESS_TEXTURE = false;\n }\n }\n }\n }\n else {\n defines.IRIDESCENCE = false;\n defines.IRIDESCENCE_TEXTURE = false;\n defines.IRIDESCENCE_THICKNESS_TEXTURE = false;\n defines.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE = false;\n defines.IRIDESCENCE_TEXTUREDIRECTUV = 0;\n defines.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV = 0;\n }\n }\n bindForSubMesh(uniformBuffer, scene, engine, subMesh) {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n if (!this._isEnabled) {\n return;\n }\n const defines = subMesh.materialDefines;\n const isFrozen = this._material.isFrozen;\n const identicalTextures = defines.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE;\n if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {\n if (identicalTextures && MaterialFlags.IridescenceTextureEnabled) {\n uniformBuffer.updateFloat4(\"vIridescenceInfos\", this._texture.coordinatesIndex, this._texture.level, -1, -1);\n MaterialHelper.BindTextureMatrix(this._texture, uniformBuffer, \"iridescence\");\n }\n else if ((this._texture || this._thicknessTexture) && MaterialFlags.IridescenceTextureEnabled) {\n uniformBuffer.updateFloat4(\"vIridescenceInfos\", (_b = (_a = this._texture) === null || _a === void 0 ? void 0 : _a.coordinatesIndex) !== null && _b !== void 0 ? _b : 0, (_d = (_c = this._texture) === null || _c === void 0 ? void 0 : _c.level) !== null && _d !== void 0 ? _d : 0, (_f = (_e = this._thicknessTexture) === null || _e === void 0 ? void 0 : _e.coordinatesIndex) !== null && _f !== void 0 ? _f : 0, (_h = (_g = this._thicknessTexture) === null || _g === void 0 ? void 0 : _g.level) !== null && _h !== void 0 ? _h : 0);\n if (this._texture) {\n MaterialHelper.BindTextureMatrix(this._texture, uniformBuffer, \"iridescence\");\n }\n if (this._thicknessTexture && !identicalTextures && !defines.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE) {\n MaterialHelper.BindTextureMatrix(this._thicknessTexture, uniformBuffer, \"iridescenceThickness\");\n }\n }\n // Clear Coat General params\n uniformBuffer.updateFloat4(\"vIridescenceParams\", this.intensity, this.indexOfRefraction, this.minimumThickness, this.maximumThickness);\n }\n // Textures\n if (scene.texturesEnabled) {\n if (this._texture && MaterialFlags.IridescenceTextureEnabled) {\n uniformBuffer.setTexture(\"iridescenceSampler\", this._texture);\n }\n if (this._thicknessTexture && !identicalTextures && !defines.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE && MaterialFlags.IridescenceTextureEnabled) {\n uniformBuffer.setTexture(\"iridescenceThicknessSampler\", this._thicknessTexture);\n }\n }\n }\n hasTexture(texture) {\n if (this._texture === texture) {\n return true;\n }\n if (this._thicknessTexture === texture) {\n return true;\n }\n return false;\n }\n getActiveTextures(activeTextures) {\n if (this._texture) {\n activeTextures.push(this._texture);\n }\n if (this._thicknessTexture) {\n activeTextures.push(this._thicknessTexture);\n }\n }\n getAnimatables(animatables) {\n if (this._texture && this._texture.animations && this._texture.animations.length > 0) {\n animatables.push(this._texture);\n }\n if (this._thicknessTexture && this._thicknessTexture.animations && this._thicknessTexture.animations.length > 0) {\n animatables.push(this._thicknessTexture);\n }\n }\n dispose(forceDisposeTextures) {\n var _a, _b;\n if (forceDisposeTextures) {\n (_a = this._texture) === null || _a === void 0 ? void 0 : _a.dispose();\n (_b = this._thicknessTexture) === null || _b === void 0 ? void 0 : _b.dispose();\n }\n }\n getClassName() {\n return \"PBRIridescenceConfiguration\";\n }\n addFallbacks(defines, fallbacks, currentRank) {\n if (defines.IRIDESCENCE) {\n fallbacks.addFallback(currentRank++, \"IRIDESCENCE\");\n }\n return currentRank;\n }\n getSamplers(samplers) {\n samplers.push(\"iridescenceSampler\", \"iridescenceThicknessSampler\");\n }\n getUniforms() {\n return {\n ubo: [\n { name: \"vIridescenceParams\", size: 4, type: \"vec4\" },\n { name: \"vIridescenceInfos\", size: 4, type: \"vec4\" },\n { name: \"iridescenceMatrix\", size: 16, type: \"mat4\" },\n { name: \"iridescenceThicknessMatrix\", size: 16, type: \"mat4\" },\n ],\n };\n }\n}\n/**\n * The default minimum thickness of the thin-film layer given in nanometers (nm).\n * Defaults to 100 nm.\n * @internal\n */\nPBRIridescenceConfiguration._DefaultMinimumThickness = 100;\n/**\n * The default maximum thickness of the thin-film layer given in nanometers (nm).\n * Defaults to 400 nm.\n * @internal\n */\nPBRIridescenceConfiguration._DefaultMaximumThickness = 400;\n/**\n * The default index of refraction of the thin-film layer.\n * Defaults to 1.3\n * @internal\n */\nPBRIridescenceConfiguration._DefaultIndexOfRefraction = 1.3;\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRIridescenceConfiguration.prototype, \"isEnabled\", void 0);\n__decorate([\n serialize()\n], PBRIridescenceConfiguration.prototype, \"intensity\", void 0);\n__decorate([\n serialize()\n], PBRIridescenceConfiguration.prototype, \"minimumThickness\", void 0);\n__decorate([\n serialize()\n], PBRIridescenceConfiguration.prototype, \"maximumThickness\", void 0);\n__decorate([\n serialize()\n], PBRIridescenceConfiguration.prototype, \"indexOfRefraction\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRIridescenceConfiguration.prototype, \"texture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRIridescenceConfiguration.prototype, \"thicknessTexture\", void 0);\n//# sourceMappingURL=pbrIridescenceConfiguration.js.map","import { __decorate } from \"../../tslib.es6.js\";\n/* eslint-disable @typescript-eslint/naming-convention */\nimport { serialize, expandToProperty, serializeAsVector2, serializeAsTexture } from \"../../Misc/decorators.js\";\nimport { VertexBuffer } from \"../../Buffers/buffer.js\";\nimport { Vector2 } from \"../../Maths/math.vector.js\";\nimport { MaterialFlags } from \"../../Materials/materialFlags.js\";\nimport { MaterialHelper } from \"../../Materials/materialHelper.js\";\nimport { MaterialPluginBase } from \"../materialPluginBase.js\";\n\nimport { MaterialDefines } from \"../materialDefines.js\";\n/**\n * @internal\n */\nexport class MaterialAnisotropicDefines extends MaterialDefines {\n constructor() {\n super(...arguments);\n this.ANISOTROPIC = false;\n this.ANISOTROPIC_TEXTURE = false;\n this.ANISOTROPIC_TEXTUREDIRECTUV = 0;\n this.ANISOTROPIC_LEGACY = false;\n this.MAINUV1 = false;\n }\n}\n/**\n * Plugin that implements the anisotropic component of the PBR material\n */\nexport class PBRAnisotropicConfiguration extends MaterialPluginBase {\n /**\n * Sets the anisotropy direction as an angle.\n */\n set angle(value) {\n this.direction.x = Math.cos(value);\n this.direction.y = Math.sin(value);\n }\n /**\n * Gets the anisotropy angle value in radians.\n * @returns the anisotropy angle value in radians.\n */\n get angle() {\n return Math.atan2(this.direction.y, this.direction.x);\n }\n /** @internal */\n _markAllSubMeshesAsTexturesDirty() {\n this._enable(this._isEnabled);\n this._internalMarkAllSubMeshesAsTexturesDirty();\n }\n /** @internal */\n _markAllSubMeshesAsMiscDirty() {\n this._enable(this._isEnabled);\n this._internalMarkAllSubMeshesAsMiscDirty();\n }\n constructor(material, addToPluginList = true) {\n super(material, \"PBRAnisotropic\", 110, new MaterialAnisotropicDefines(), addToPluginList);\n this._isEnabled = false;\n /**\n * Defines if the anisotropy is enabled in the material.\n */\n this.isEnabled = false;\n /**\n * Defines the anisotropy strength (between 0 and 1) it defaults to 1.\n */\n this.intensity = 1;\n /**\n * Defines if the effect is along the tangents, bitangents or in between.\n * By default, the effect is \"stretching\" the highlights along the tangents.\n */\n this.direction = new Vector2(1, 0);\n this._texture = null;\n /**\n * Stores the anisotropy values in a texture.\n * rg is direction (like normal from -1 to 1)\n * b is a intensity\n */\n this.texture = null;\n this._legacy = false;\n /**\n * Defines if the anisotropy is in legacy mode for backwards compatibility before 6.4.0.\n */\n this.legacy = false;\n this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];\n this._internalMarkAllSubMeshesAsMiscDirty = material._dirtyCallbacks[16];\n }\n isReadyForSubMesh(defines, scene) {\n if (!this._isEnabled) {\n return true;\n }\n if (defines._areTexturesDirty) {\n if (scene.texturesEnabled) {\n if (this._texture && MaterialFlags.AnisotropicTextureEnabled) {\n if (!this._texture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n }\n }\n return true;\n }\n prepareDefinesBeforeAttributes(defines, scene, mesh) {\n if (this._isEnabled) {\n defines.ANISOTROPIC = this._isEnabled;\n if (this._isEnabled && !mesh.isVerticesDataPresent(VertexBuffer.TangentKind)) {\n defines._needUVs = true;\n defines.MAINUV1 = true;\n }\n if (defines._areTexturesDirty) {\n if (scene.texturesEnabled) {\n if (this._texture && MaterialFlags.AnisotropicTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._texture, defines, \"ANISOTROPIC_TEXTURE\");\n }\n else {\n defines.ANISOTROPIC_TEXTURE = false;\n }\n }\n }\n if (defines._areMiscDirty) {\n defines.ANISOTROPIC_LEGACY = this._legacy;\n }\n }\n else {\n defines.ANISOTROPIC = false;\n defines.ANISOTROPIC_TEXTURE = false;\n defines.ANISOTROPIC_TEXTUREDIRECTUV = 0;\n defines.ANISOTROPIC_LEGACY = false;\n }\n }\n bindForSubMesh(uniformBuffer, scene) {\n if (!this._isEnabled) {\n return;\n }\n const isFrozen = this._material.isFrozen;\n if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {\n if (this._texture && MaterialFlags.AnisotropicTextureEnabled) {\n uniformBuffer.updateFloat2(\"vAnisotropyInfos\", this._texture.coordinatesIndex, this._texture.level);\n MaterialHelper.BindTextureMatrix(this._texture, uniformBuffer, \"anisotropy\");\n }\n // Anisotropy\n uniformBuffer.updateFloat3(\"vAnisotropy\", this.direction.x, this.direction.y, this.intensity);\n }\n // Textures\n if (scene.texturesEnabled) {\n if (this._texture && MaterialFlags.AnisotropicTextureEnabled) {\n uniformBuffer.setTexture(\"anisotropySampler\", this._texture);\n }\n }\n }\n hasTexture(texture) {\n if (this._texture === texture) {\n return true;\n }\n return false;\n }\n getActiveTextures(activeTextures) {\n if (this._texture) {\n activeTextures.push(this._texture);\n }\n }\n getAnimatables(animatables) {\n if (this._texture && this._texture.animations && this._texture.animations.length > 0) {\n animatables.push(this._texture);\n }\n }\n dispose(forceDisposeTextures) {\n if (forceDisposeTextures) {\n if (this._texture) {\n this._texture.dispose();\n }\n }\n }\n getClassName() {\n return \"PBRAnisotropicConfiguration\";\n }\n addFallbacks(defines, fallbacks, currentRank) {\n if (defines.ANISOTROPIC) {\n fallbacks.addFallback(currentRank++, \"ANISOTROPIC\");\n }\n return currentRank;\n }\n getSamplers(samplers) {\n samplers.push(\"anisotropySampler\");\n }\n getUniforms() {\n return {\n ubo: [\n { name: \"vAnisotropy\", size: 3, type: \"vec3\" },\n { name: \"vAnisotropyInfos\", size: 2, type: \"vec2\" },\n { name: \"anisotropyMatrix\", size: 16, type: \"mat4\" },\n ],\n };\n }\n /**\n * Parses a anisotropy Configuration from a serialized object.\n * @param source - Serialized object.\n * @param scene Defines the scene we are parsing for\n * @param rootUrl Defines the rootUrl to load from\n */\n parse(source, scene, rootUrl) {\n super.parse(source, scene, rootUrl);\n // Backward compatibility\n if (source.legacy === undefined) {\n this.legacy = true;\n }\n }\n}\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRAnisotropicConfiguration.prototype, \"isEnabled\", void 0);\n__decorate([\n serialize()\n], PBRAnisotropicConfiguration.prototype, \"intensity\", void 0);\n__decorate([\n serializeAsVector2()\n], PBRAnisotropicConfiguration.prototype, \"direction\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRAnisotropicConfiguration.prototype, \"texture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsMiscDirty\")\n], PBRAnisotropicConfiguration.prototype, \"legacy\", void 0);\n//# sourceMappingURL=pbrAnisotropicConfiguration.js.map","import { __decorate } from \"../../tslib.es6.js\";\n/* eslint-disable @typescript-eslint/naming-convention */\nimport { serialize, expandToProperty, serializeAsColor3, serializeAsTexture } from \"../../Misc/decorators.js\";\nimport { Color3 } from \"../../Maths/math.color.js\";\nimport { MaterialFlags } from \"../../Materials/materialFlags.js\";\nimport { MaterialHelper } from \"../../Materials/materialHelper.js\";\n\nimport { MaterialPluginBase } from \"../materialPluginBase.js\";\nimport { MaterialDefines } from \"../materialDefines.js\";\n/**\n * @internal\n */\nexport class MaterialSheenDefines extends MaterialDefines {\n constructor() {\n super(...arguments);\n this.SHEEN = false;\n this.SHEEN_TEXTURE = false;\n this.SHEEN_GAMMATEXTURE = false;\n this.SHEEN_TEXTURE_ROUGHNESS = false;\n this.SHEEN_TEXTUREDIRECTUV = 0;\n this.SHEEN_TEXTURE_ROUGHNESSDIRECTUV = 0;\n this.SHEEN_LINKWITHALBEDO = false;\n this.SHEEN_ROUGHNESS = false;\n this.SHEEN_ALBEDOSCALING = false;\n this.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE = false;\n this.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL = false;\n }\n}\n/**\n * Plugin that implements the sheen component of the PBR material.\n */\nexport class PBRSheenConfiguration extends MaterialPluginBase {\n /** @internal */\n _markAllSubMeshesAsTexturesDirty() {\n this._enable(this._isEnabled);\n this._internalMarkAllSubMeshesAsTexturesDirty();\n }\n constructor(material, addToPluginList = true) {\n super(material, \"Sheen\", 120, new MaterialSheenDefines(), addToPluginList);\n this._isEnabled = false;\n /**\n * Defines if the material uses sheen.\n */\n this.isEnabled = false;\n this._linkSheenWithAlbedo = false;\n /**\n * Defines if the sheen is linked to the sheen color.\n */\n this.linkSheenWithAlbedo = false;\n /**\n * Defines the sheen intensity.\n */\n this.intensity = 1;\n /**\n * Defines the sheen color.\n */\n this.color = Color3.White();\n this._texture = null;\n /**\n * Stores the sheen tint values in a texture.\n * rgb is tint\n * a is a intensity or roughness if the roughness property has been defined and useRoughnessFromTexture is true (in that case, textureRoughness won't be used)\n * If the roughness property has been defined and useRoughnessFromTexture is false then the alpha channel is not used to modulate roughness\n */\n this.texture = null;\n this._useRoughnessFromMainTexture = true;\n /**\n * Indicates that the alpha channel of the texture property will be used for roughness.\n * Has no effect if the roughness (and texture!) property is not defined\n */\n this.useRoughnessFromMainTexture = true;\n this._roughness = null;\n /**\n * Defines the sheen roughness.\n * It is not taken into account if linkSheenWithAlbedo is true.\n * To stay backward compatible, material roughness is used instead if sheen roughness = null\n */\n this.roughness = null;\n this._textureRoughness = null;\n /**\n * Stores the sheen roughness in a texture.\n * alpha channel is the roughness. This texture won't be used if the texture property is not empty and useRoughnessFromTexture is true\n */\n this.textureRoughness = null;\n this._albedoScaling = false;\n /**\n * If true, the sheen effect is layered above the base BRDF with the albedo-scaling technique.\n * It allows the strength of the sheen effect to not depend on the base color of the material,\n * making it easier to setup and tweak the effect\n */\n this.albedoScaling = false;\n this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];\n }\n isReadyForSubMesh(defines, scene) {\n if (!this._isEnabled) {\n return true;\n }\n if (defines._areTexturesDirty) {\n if (scene.texturesEnabled) {\n if (this._texture && MaterialFlags.SheenTextureEnabled) {\n if (!this._texture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._textureRoughness && MaterialFlags.SheenTextureEnabled) {\n if (!this._textureRoughness.isReadyOrNotBlocking()) {\n return false;\n }\n }\n }\n }\n return true;\n }\n prepareDefinesBeforeAttributes(defines, scene) {\n var _a;\n if (this._isEnabled) {\n defines.SHEEN = true;\n defines.SHEEN_LINKWITHALBEDO = this._linkSheenWithAlbedo;\n defines.SHEEN_ROUGHNESS = this._roughness !== null;\n defines.SHEEN_ALBEDOSCALING = this._albedoScaling;\n defines.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE = this._useRoughnessFromMainTexture;\n defines.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL =\n this._texture !== null && this._texture._texture === ((_a = this._textureRoughness) === null || _a === void 0 ? void 0 : _a._texture) && this._texture.checkTransformsAreIdentical(this._textureRoughness);\n if (defines._areTexturesDirty) {\n if (scene.texturesEnabled) {\n if (this._texture && MaterialFlags.SheenTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._texture, defines, \"SHEEN_TEXTURE\");\n defines.SHEEN_GAMMATEXTURE = this._texture.gammaSpace;\n }\n else {\n defines.SHEEN_TEXTURE = false;\n }\n if (this._textureRoughness && MaterialFlags.SheenTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._textureRoughness, defines, \"SHEEN_TEXTURE_ROUGHNESS\");\n }\n else {\n defines.SHEEN_TEXTURE_ROUGHNESS = false;\n }\n }\n }\n }\n else {\n defines.SHEEN = false;\n defines.SHEEN_TEXTURE = false;\n defines.SHEEN_TEXTURE_ROUGHNESS = false;\n defines.SHEEN_LINKWITHALBEDO = false;\n defines.SHEEN_ROUGHNESS = false;\n defines.SHEEN_ALBEDOSCALING = false;\n defines.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE = false;\n defines.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL = false;\n defines.SHEEN_GAMMATEXTURE = false;\n defines.SHEEN_TEXTUREDIRECTUV = 0;\n defines.SHEEN_TEXTURE_ROUGHNESSDIRECTUV = 0;\n }\n }\n bindForSubMesh(uniformBuffer, scene, engine, subMesh) {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n if (!this._isEnabled) {\n return;\n }\n const defines = subMesh.materialDefines;\n const isFrozen = this._material.isFrozen;\n const identicalTextures = defines.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL;\n if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {\n if (identicalTextures && MaterialFlags.SheenTextureEnabled) {\n uniformBuffer.updateFloat4(\"vSheenInfos\", this._texture.coordinatesIndex, this._texture.level, -1, -1);\n MaterialHelper.BindTextureMatrix(this._texture, uniformBuffer, \"sheen\");\n }\n else if ((this._texture || this._textureRoughness) && MaterialFlags.SheenTextureEnabled) {\n uniformBuffer.updateFloat4(\"vSheenInfos\", (_b = (_a = this._texture) === null || _a === void 0 ? void 0 : _a.coordinatesIndex) !== null && _b !== void 0 ? _b : 0, (_d = (_c = this._texture) === null || _c === void 0 ? void 0 : _c.level) !== null && _d !== void 0 ? _d : 0, (_f = (_e = this._textureRoughness) === null || _e === void 0 ? void 0 : _e.coordinatesIndex) !== null && _f !== void 0 ? _f : 0, (_h = (_g = this._textureRoughness) === null || _g === void 0 ? void 0 : _g.level) !== null && _h !== void 0 ? _h : 0);\n if (this._texture) {\n MaterialHelper.BindTextureMatrix(this._texture, uniformBuffer, \"sheen\");\n }\n if (this._textureRoughness && !identicalTextures && !defines.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) {\n MaterialHelper.BindTextureMatrix(this._textureRoughness, uniformBuffer, \"sheenRoughness\");\n }\n }\n // Sheen\n uniformBuffer.updateFloat4(\"vSheenColor\", this.color.r, this.color.g, this.color.b, this.intensity);\n if (this._roughness !== null) {\n uniformBuffer.updateFloat(\"vSheenRoughness\", this._roughness);\n }\n }\n // Textures\n if (scene.texturesEnabled) {\n if (this._texture && MaterialFlags.SheenTextureEnabled) {\n uniformBuffer.setTexture(\"sheenSampler\", this._texture);\n }\n if (this._textureRoughness && !identicalTextures && !defines.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE && MaterialFlags.SheenTextureEnabled) {\n uniformBuffer.setTexture(\"sheenRoughnessSampler\", this._textureRoughness);\n }\n }\n }\n hasTexture(texture) {\n if (this._texture === texture) {\n return true;\n }\n if (this._textureRoughness === texture) {\n return true;\n }\n return false;\n }\n getActiveTextures(activeTextures) {\n if (this._texture) {\n activeTextures.push(this._texture);\n }\n if (this._textureRoughness) {\n activeTextures.push(this._textureRoughness);\n }\n }\n getAnimatables(animatables) {\n if (this._texture && this._texture.animations && this._texture.animations.length > 0) {\n animatables.push(this._texture);\n }\n if (this._textureRoughness && this._textureRoughness.animations && this._textureRoughness.animations.length > 0) {\n animatables.push(this._textureRoughness);\n }\n }\n dispose(forceDisposeTextures) {\n var _a, _b;\n if (forceDisposeTextures) {\n (_a = this._texture) === null || _a === void 0 ? void 0 : _a.dispose();\n (_b = this._textureRoughness) === null || _b === void 0 ? void 0 : _b.dispose();\n }\n }\n getClassName() {\n return \"PBRSheenConfiguration\";\n }\n addFallbacks(defines, fallbacks, currentRank) {\n if (defines.SHEEN) {\n fallbacks.addFallback(currentRank++, \"SHEEN\");\n }\n return currentRank;\n }\n getSamplers(samplers) {\n samplers.push(\"sheenSampler\", \"sheenRoughnessSampler\");\n }\n getUniforms() {\n return {\n ubo: [\n { name: \"vSheenColor\", size: 4, type: \"vec4\" },\n { name: \"vSheenRoughness\", size: 1, type: \"float\" },\n { name: \"vSheenInfos\", size: 4, type: \"vec4\" },\n { name: \"sheenMatrix\", size: 16, type: \"mat4\" },\n { name: \"sheenRoughnessMatrix\", size: 16, type: \"mat4\" },\n ],\n };\n }\n}\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSheenConfiguration.prototype, \"isEnabled\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSheenConfiguration.prototype, \"linkSheenWithAlbedo\", void 0);\n__decorate([\n serialize()\n], PBRSheenConfiguration.prototype, \"intensity\", void 0);\n__decorate([\n serializeAsColor3()\n], PBRSheenConfiguration.prototype, \"color\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSheenConfiguration.prototype, \"texture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSheenConfiguration.prototype, \"useRoughnessFromMainTexture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSheenConfiguration.prototype, \"roughness\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSheenConfiguration.prototype, \"textureRoughness\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSheenConfiguration.prototype, \"albedoScaling\", void 0);\n//# sourceMappingURL=pbrSheenConfiguration.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize, serializeAsTexture, expandToProperty, serializeAsColor3 } from \"../../Misc/decorators.js\";\nimport { Color3 } from \"../../Maths/math.color.js\";\nimport { MaterialFlags } from \"../materialFlags.js\";\nimport { MaterialHelper } from \"../../Materials/materialHelper.js\";\nimport { Scalar } from \"../../Maths/math.scalar.js\";\nimport { TmpVectors } from \"../../Maths/math.vector.js\";\nimport { MaterialPluginBase } from \"../materialPluginBase.js\";\n\nimport { MaterialDefines } from \"../materialDefines.js\";\n/**\n * @internal\n */\nexport class MaterialSubSurfaceDefines extends MaterialDefines {\n constructor() {\n super(...arguments);\n this.SUBSURFACE = false;\n this.SS_REFRACTION = false;\n this.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE = false;\n this.SS_TRANSLUCENCY = false;\n this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE = false;\n this.SS_SCATTERING = false;\n this.SS_THICKNESSANDMASK_TEXTURE = false;\n this.SS_THICKNESSANDMASK_TEXTUREDIRECTUV = 0;\n this.SS_HAS_THICKNESS = false;\n this.SS_REFRACTIONINTENSITY_TEXTURE = false;\n this.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV = 0;\n this.SS_TRANSLUCENCYINTENSITY_TEXTURE = false;\n this.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV = 0;\n this.SS_REFRACTIONMAP_3D = false;\n this.SS_REFRACTIONMAP_OPPOSITEZ = false;\n this.SS_LODINREFRACTIONALPHA = false;\n this.SS_GAMMAREFRACTION = false;\n this.SS_RGBDREFRACTION = false;\n this.SS_LINEARSPECULARREFRACTION = false;\n this.SS_LINKREFRACTIONTOTRANSPARENCY = false;\n this.SS_ALBEDOFORREFRACTIONTINT = false;\n this.SS_ALBEDOFORTRANSLUCENCYTINT = false;\n this.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = false;\n this.SS_USE_THICKNESS_AS_DEPTH = false;\n this.SS_MASK_FROM_THICKNESS_TEXTURE = false;\n this.SS_USE_GLTF_TEXTURES = false;\n }\n}\n/**\n * Plugin that implements the sub surface component of the PBR material\n */\nexport class PBRSubSurfaceConfiguration extends MaterialPluginBase {\n /**\n * Diffusion profile for subsurface scattering.\n * Useful for better scattering in the skins or foliages.\n */\n get scatteringDiffusionProfile() {\n if (!this._scene.subSurfaceConfiguration) {\n return null;\n }\n return this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex];\n }\n set scatteringDiffusionProfile(c) {\n if (!this._scene.enableSubSurfaceForPrePass()) {\n // Not supported\n return;\n }\n // addDiffusionProfile automatically checks for doubles\n if (c) {\n this._scatteringDiffusionProfileIndex = this._scene.subSurfaceConfiguration.addDiffusionProfile(c);\n }\n }\n /**\n * Index of refraction of the material's volume.\n * https://en.wikipedia.org/wiki/List_of_refractive_indices\n *\n * This ONLY impacts refraction. If not provided or given a non-valid value,\n * the volume will use the same IOR as the surface.\n */\n get volumeIndexOfRefraction() {\n if (this._volumeIndexOfRefraction >= 1.0) {\n return this._volumeIndexOfRefraction;\n }\n return this._indexOfRefraction;\n }\n set volumeIndexOfRefraction(value) {\n if (value >= 1.0) {\n this._volumeIndexOfRefraction = value;\n }\n else {\n this._volumeIndexOfRefraction = -1.0;\n }\n }\n /** @internal */\n _markAllSubMeshesAsTexturesDirty() {\n this._enable(this._isRefractionEnabled || this._isTranslucencyEnabled || this._isScatteringEnabled);\n this._internalMarkAllSubMeshesAsTexturesDirty();\n }\n /** @internal */\n _markScenePrePassDirty() {\n this._internalMarkAllSubMeshesAsTexturesDirty();\n this._internalMarkScenePrePassDirty();\n }\n constructor(material, addToPluginList = true) {\n super(material, \"PBRSubSurface\", 130, new MaterialSubSurfaceDefines(), addToPluginList);\n this._isRefractionEnabled = false;\n /**\n * Defines if the refraction is enabled in the material.\n */\n this.isRefractionEnabled = false;\n this._isTranslucencyEnabled = false;\n /**\n * Defines if the translucency is enabled in the material.\n */\n this.isTranslucencyEnabled = false;\n this._isScatteringEnabled = false;\n /**\n * Defines if the sub surface scattering is enabled in the material.\n */\n this.isScatteringEnabled = false;\n this._scatteringDiffusionProfileIndex = 0;\n /**\n * Defines the refraction intensity of the material.\n * The refraction when enabled replaces the Diffuse part of the material.\n * The intensity helps transitioning between diffuse and refraction.\n */\n this.refractionIntensity = 1;\n /**\n * Defines the translucency intensity of the material.\n * When translucency has been enabled, this defines how much of the \"translucency\"\n * is added to the diffuse part of the material.\n */\n this.translucencyIntensity = 1;\n /**\n * When enabled, transparent surfaces will be tinted with the albedo colour (independent of thickness)\n */\n this.useAlbedoToTintRefraction = false;\n /**\n * When enabled, translucent surfaces will be tinted with the albedo colour (independent of thickness)\n */\n this.useAlbedoToTintTranslucency = false;\n this._thicknessTexture = null;\n /**\n * Stores the average thickness of a mesh in a texture (The texture is holding the values linearly).\n * The red (or green if useGltfStyleTextures=true) channel of the texture should contain the thickness remapped between 0 and 1.\n * 0 would mean minimumThickness\n * 1 would mean maximumThickness\n * The other channels might be use as a mask to vary the different effects intensity.\n */\n this.thicknessTexture = null;\n this._refractionTexture = null;\n /**\n * Defines the texture to use for refraction.\n */\n this.refractionTexture = null;\n /** @internal */\n this._indexOfRefraction = 1.5;\n /**\n * Index of refraction of the material base layer.\n * https://en.wikipedia.org/wiki/List_of_refractive_indices\n *\n * This does not only impact refraction but also the Base F0 of Dielectric Materials.\n *\n * From dielectric fresnel rules: F0 = square((iorT - iorI) / (iorT + iorI))\n */\n this.indexOfRefraction = 1.5;\n this._volumeIndexOfRefraction = -1.0;\n this._invertRefractionY = false;\n /**\n * Controls if refraction needs to be inverted on Y. This could be useful for procedural texture.\n */\n this.invertRefractionY = false;\n /** @internal */\n this._linkRefractionWithTransparency = false;\n /**\n * This parameters will make the material used its opacity to control how much it is refracting against not.\n * Materials half opaque for instance using refraction could benefit from this control.\n */\n this.linkRefractionWithTransparency = false;\n /**\n * Defines the minimum thickness stored in the thickness map.\n * If no thickness map is defined, this value will be used to simulate thickness.\n */\n this.minimumThickness = 0;\n /**\n * Defines the maximum thickness stored in the thickness map.\n */\n this.maximumThickness = 1;\n /**\n * Defines that the thickness should be used as a measure of the depth volume.\n */\n this.useThicknessAsDepth = false;\n /**\n * Defines the volume tint of the material.\n * This is used for both translucency and scattering.\n */\n this.tintColor = Color3.White();\n /**\n * Defines the distance at which the tint color should be found in the media.\n * This is used for refraction only.\n */\n this.tintColorAtDistance = 1;\n /**\n * Defines how far each channel transmit through the media.\n * It is defined as a color to simplify it selection.\n */\n this.diffusionDistance = Color3.White();\n this._useMaskFromThicknessTexture = false;\n /**\n * Stores the intensity of the different subsurface effects in the thickness texture.\n * Note that if refractionIntensityTexture and/or translucencyIntensityTexture is provided it takes precedence over thicknessTexture + useMaskFromThicknessTexture\n * * the green (red if useGltfStyleTextures = true) channel is the refraction intensity.\n * * the blue channel is the translucency intensity.\n */\n this.useMaskFromThicknessTexture = false;\n this._refractionIntensityTexture = null;\n /**\n * Stores the intensity of the refraction. If provided, it takes precedence over thicknessTexture + useMaskFromThicknessTexture\n * * the green (red if useGltfStyleTextures = true) channel is the refraction intensity.\n */\n this.refractionIntensityTexture = null;\n this._translucencyIntensityTexture = null;\n /**\n * Stores the intensity of the translucency. If provided, it takes precedence over thicknessTexture + useMaskFromThicknessTexture\n * * the blue channel is the translucency intensity.\n */\n this.translucencyIntensityTexture = null;\n this._useGltfStyleTextures = false;\n /**\n * Use channels layout used by glTF:\n * * thicknessTexture: the green (instead of red) channel is the thickness\n * * thicknessTexture/refractionIntensityTexture: the red (instead of green) channel is the refraction intensity\n * * thicknessTexture/translucencyIntensityTexture: no change, use the blue channel for the translucency intensity\n */\n this.useGltfStyleTextures = false;\n this._scene = material.getScene();\n this.registerForExtraEvents = true;\n this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];\n this._internalMarkScenePrePassDirty = material._dirtyCallbacks[32];\n }\n isReadyForSubMesh(defines, scene) {\n if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled) {\n return true;\n }\n if (defines._areTexturesDirty) {\n if (scene.texturesEnabled) {\n if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) {\n if (!this._thicknessTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n const refractionTexture = this._getRefractionTexture(scene);\n if (refractionTexture && MaterialFlags.RefractionTextureEnabled) {\n if (!refractionTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n }\n }\n return true;\n }\n prepareDefinesBeforeAttributes(defines, scene) {\n if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled) {\n defines.SUBSURFACE = false;\n defines.SS_TRANSLUCENCY = false;\n defines.SS_SCATTERING = false;\n defines.SS_REFRACTION = false;\n defines.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE = false;\n defines.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE = false;\n defines.SS_THICKNESSANDMASK_TEXTURE = false;\n defines.SS_THICKNESSANDMASK_TEXTUREDIRECTUV = 0;\n defines.SS_HAS_THICKNESS = false;\n defines.SS_REFRACTIONINTENSITY_TEXTURE = false;\n defines.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV = 0;\n defines.SS_TRANSLUCENCYINTENSITY_TEXTURE = false;\n defines.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV = 0;\n defines.SS_REFRACTIONMAP_3D = false;\n defines.SS_REFRACTIONMAP_OPPOSITEZ = false;\n defines.SS_LODINREFRACTIONALPHA = false;\n defines.SS_GAMMAREFRACTION = false;\n defines.SS_RGBDREFRACTION = false;\n defines.SS_LINEARSPECULARREFRACTION = false;\n defines.SS_LINKREFRACTIONTOTRANSPARENCY = false;\n defines.SS_ALBEDOFORREFRACTIONTINT = false;\n defines.SS_ALBEDOFORTRANSLUCENCYTINT = false;\n defines.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = false;\n defines.SS_USE_THICKNESS_AS_DEPTH = false;\n defines.SS_MASK_FROM_THICKNESS_TEXTURE = false;\n defines.SS_USE_GLTF_TEXTURES = false;\n return;\n }\n if (defines._areTexturesDirty) {\n defines.SUBSURFACE = true;\n defines.SS_TRANSLUCENCY = this._isTranslucencyEnabled;\n defines.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE = false;\n defines.SS_SCATTERING = this._isScatteringEnabled;\n defines.SS_THICKNESSANDMASK_TEXTURE = false;\n defines.SS_REFRACTIONINTENSITY_TEXTURE = false;\n defines.SS_TRANSLUCENCYINTENSITY_TEXTURE = false;\n defines.SS_HAS_THICKNESS = false;\n defines.SS_MASK_FROM_THICKNESS_TEXTURE = false;\n defines.SS_USE_GLTF_TEXTURES = false;\n defines.SS_REFRACTION = false;\n defines.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE = false;\n defines.SS_REFRACTIONMAP_3D = false;\n defines.SS_GAMMAREFRACTION = false;\n defines.SS_RGBDREFRACTION = false;\n defines.SS_LINEARSPECULARREFRACTION = false;\n defines.SS_REFRACTIONMAP_OPPOSITEZ = false;\n defines.SS_LODINREFRACTIONALPHA = false;\n defines.SS_LINKREFRACTIONTOTRANSPARENCY = false;\n defines.SS_ALBEDOFORREFRACTIONTINT = false;\n defines.SS_ALBEDOFORTRANSLUCENCYTINT = false;\n defines.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = false;\n defines.SS_USE_THICKNESS_AS_DEPTH = false;\n const refractionIntensityTextureIsThicknessTexture = !!this._thicknessTexture &&\n !!this._refractionIntensityTexture &&\n this._refractionIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture) &&\n this._refractionIntensityTexture._texture === this._thicknessTexture._texture;\n const translucencyIntensityTextureIsThicknessTexture = !!this._thicknessTexture &&\n !!this._translucencyIntensityTexture &&\n this._translucencyIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture) &&\n this._translucencyIntensityTexture._texture === this._thicknessTexture._texture;\n // if true, it means the refraction/translucency textures are the same than the thickness texture so there's no need to pass them to the shader, only thicknessTexture\n const useOnlyThicknessTexture = (refractionIntensityTextureIsThicknessTexture || !this._refractionIntensityTexture) &&\n (translucencyIntensityTextureIsThicknessTexture || !this._translucencyIntensityTexture);\n if (defines._areTexturesDirty) {\n if (scene.texturesEnabled) {\n if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._thicknessTexture, defines, \"SS_THICKNESSANDMASK_TEXTURE\");\n }\n if (this._refractionIntensityTexture && MaterialFlags.RefractionIntensityTextureEnabled && !useOnlyThicknessTexture) {\n MaterialHelper.PrepareDefinesForMergedUV(this._refractionIntensityTexture, defines, \"SS_REFRACTIONINTENSITY_TEXTURE\");\n }\n if (this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled && !useOnlyThicknessTexture) {\n MaterialHelper.PrepareDefinesForMergedUV(this._translucencyIntensityTexture, defines, \"SS_TRANSLUCENCYINTENSITY_TEXTURE\");\n }\n }\n }\n defines.SS_HAS_THICKNESS = this.maximumThickness - this.minimumThickness !== 0.0;\n defines.SS_MASK_FROM_THICKNESS_TEXTURE =\n (this._useMaskFromThicknessTexture || !!this._refractionIntensityTexture || !!this._translucencyIntensityTexture) && useOnlyThicknessTexture;\n defines.SS_USE_GLTF_TEXTURES = this._useGltfStyleTextures;\n defines.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE = (this._useMaskFromThicknessTexture || !!this._refractionIntensityTexture) && useOnlyThicknessTexture;\n defines.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE = (this._useMaskFromThicknessTexture || !!this._translucencyIntensityTexture) && useOnlyThicknessTexture;\n if (this._isRefractionEnabled) {\n if (scene.texturesEnabled) {\n const refractionTexture = this._getRefractionTexture(scene);\n if (refractionTexture && MaterialFlags.RefractionTextureEnabled) {\n defines.SS_REFRACTION = true;\n defines.SS_REFRACTIONMAP_3D = refractionTexture.isCube;\n defines.SS_GAMMAREFRACTION = refractionTexture.gammaSpace;\n defines.SS_RGBDREFRACTION = refractionTexture.isRGBD;\n defines.SS_LINEARSPECULARREFRACTION = refractionTexture.linearSpecularLOD;\n defines.SS_REFRACTIONMAP_OPPOSITEZ = this._scene.useRightHandedSystem && refractionTexture.isCube ? !refractionTexture.invertZ : refractionTexture.invertZ;\n defines.SS_LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;\n defines.SS_LINKREFRACTIONTOTRANSPARENCY = this._linkRefractionWithTransparency;\n defines.SS_ALBEDOFORREFRACTIONTINT = this.useAlbedoToTintRefraction;\n defines.SS_USE_LOCAL_REFRACTIONMAP_CUBIC = refractionTexture.isCube && refractionTexture.boundingBoxSize;\n defines.SS_USE_THICKNESS_AS_DEPTH = this.useThicknessAsDepth;\n }\n }\n }\n if (this._isTranslucencyEnabled) {\n defines.SS_ALBEDOFORTRANSLUCENCYTINT = this.useAlbedoToTintTranslucency;\n }\n }\n }\n /**\n * Binds the material data (this function is called even if mustRebind() returns false)\n * @param uniformBuffer defines the Uniform buffer to fill in.\n * @param scene defines the scene the material belongs to.\n * @param engine defines the engine the material belongs to.\n * @param subMesh the submesh to bind data for\n */\n hardBindForSubMesh(uniformBuffer, scene, engine, subMesh) {\n if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled) {\n return;\n }\n subMesh.getRenderingMesh().getWorldMatrix().decompose(TmpVectors.Vector3[0]);\n const thicknessScale = Math.max(Math.abs(TmpVectors.Vector3[0].x), Math.abs(TmpVectors.Vector3[0].y), Math.abs(TmpVectors.Vector3[0].z));\n uniformBuffer.updateFloat2(\"vThicknessParam\", this.minimumThickness * thicknessScale, (this.maximumThickness - this.minimumThickness) * thicknessScale);\n }\n bindForSubMesh(uniformBuffer, scene, engine, subMesh) {\n if (!this._isRefractionEnabled && !this._isTranslucencyEnabled && !this._isScatteringEnabled) {\n return;\n }\n const defines = subMesh.materialDefines;\n const isFrozen = this._material.isFrozen;\n const realTimeFiltering = this._material.realTimeFiltering;\n const lodBasedMicrosurface = defines.LODBASEDMICROSFURACE;\n const refractionTexture = this._getRefractionTexture(scene);\n if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {\n if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) {\n uniformBuffer.updateFloat2(\"vThicknessInfos\", this._thicknessTexture.coordinatesIndex, this._thicknessTexture.level);\n MaterialHelper.BindTextureMatrix(this._thicknessTexture, uniformBuffer, \"thickness\");\n }\n if (this._refractionIntensityTexture && MaterialFlags.RefractionIntensityTextureEnabled && defines.SS_REFRACTIONINTENSITY_TEXTURE) {\n uniformBuffer.updateFloat2(\"vRefractionIntensityInfos\", this._refractionIntensityTexture.coordinatesIndex, this._refractionIntensityTexture.level);\n MaterialHelper.BindTextureMatrix(this._refractionIntensityTexture, uniformBuffer, \"refractionIntensity\");\n }\n if (this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled && defines.SS_TRANSLUCENCYINTENSITY_TEXTURE) {\n uniformBuffer.updateFloat2(\"vTranslucencyIntensityInfos\", this._translucencyIntensityTexture.coordinatesIndex, this._translucencyIntensityTexture.level);\n MaterialHelper.BindTextureMatrix(this._translucencyIntensityTexture, uniformBuffer, \"translucencyIntensity\");\n }\n if (refractionTexture && MaterialFlags.RefractionTextureEnabled) {\n uniformBuffer.updateMatrix(\"refractionMatrix\", refractionTexture.getRefractionTextureMatrix());\n let depth = 1.0;\n if (!refractionTexture.isCube) {\n if (refractionTexture.depth) {\n depth = refractionTexture.depth;\n }\n }\n const width = refractionTexture.getSize().width;\n const refractionIor = this.volumeIndexOfRefraction;\n uniformBuffer.updateFloat4(\"vRefractionInfos\", refractionTexture.level, 1 / refractionIor, depth, this._invertRefractionY ? -1 : 1);\n uniformBuffer.updateFloat4(\"vRefractionMicrosurfaceInfos\", width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset, 1.0 / this.indexOfRefraction);\n if (realTimeFiltering) {\n uniformBuffer.updateFloat2(\"vRefractionFilteringInfo\", width, Scalar.Log2(width));\n }\n if (refractionTexture.boundingBoxSize) {\n const cubeTexture = refractionTexture;\n uniformBuffer.updateVector3(\"vRefractionPosition\", cubeTexture.boundingBoxPosition);\n uniformBuffer.updateVector3(\"vRefractionSize\", cubeTexture.boundingBoxSize);\n }\n }\n if (this._isScatteringEnabled) {\n uniformBuffer.updateFloat(\"scatteringDiffusionProfile\", this._scatteringDiffusionProfileIndex);\n }\n uniformBuffer.updateColor3(\"vDiffusionDistance\", this.diffusionDistance);\n uniformBuffer.updateFloat4(\"vTintColor\", this.tintColor.r, this.tintColor.g, this.tintColor.b, Math.max(0.00001, this.tintColorAtDistance));\n uniformBuffer.updateFloat3(\"vSubSurfaceIntensity\", this.refractionIntensity, this.translucencyIntensity, 0);\n }\n // Textures\n if (scene.texturesEnabled) {\n if (this._thicknessTexture && MaterialFlags.ThicknessTextureEnabled) {\n uniformBuffer.setTexture(\"thicknessSampler\", this._thicknessTexture);\n }\n if (this._refractionIntensityTexture && MaterialFlags.RefractionIntensityTextureEnabled && defines.SS_REFRACTIONINTENSITY_TEXTURE) {\n uniformBuffer.setTexture(\"refractionIntensitySampler\", this._refractionIntensityTexture);\n }\n if (this._translucencyIntensityTexture && MaterialFlags.TranslucencyIntensityTextureEnabled && defines.SS_TRANSLUCENCYINTENSITY_TEXTURE) {\n uniformBuffer.setTexture(\"translucencyIntensitySampler\", this._translucencyIntensityTexture);\n }\n if (refractionTexture && MaterialFlags.RefractionTextureEnabled) {\n if (lodBasedMicrosurface) {\n uniformBuffer.setTexture(\"refractionSampler\", refractionTexture);\n }\n else {\n uniformBuffer.setTexture(\"refractionSampler\", refractionTexture._lodTextureMid || refractionTexture);\n uniformBuffer.setTexture(\"refractionSamplerLow\", refractionTexture._lodTextureLow || refractionTexture);\n uniformBuffer.setTexture(\"refractionSamplerHigh\", refractionTexture._lodTextureHigh || refractionTexture);\n }\n }\n }\n }\n /**\n * Returns the texture used for refraction or null if none is used.\n * @param scene defines the scene the material belongs to.\n * @returns - Refraction texture if present. If no refraction texture and refraction\n * is linked with transparency, returns environment texture. Otherwise, returns null.\n */\n _getRefractionTexture(scene) {\n if (this._refractionTexture) {\n return this._refractionTexture;\n }\n if (this._isRefractionEnabled) {\n return scene.environmentTexture;\n }\n return null;\n }\n /**\n * Returns true if alpha blending should be disabled.\n */\n get disableAlphaBlending() {\n return this._isRefractionEnabled && this._linkRefractionWithTransparency;\n }\n /**\n * Fills the list of render target textures.\n * @param renderTargets the list of render targets to update\n */\n fillRenderTargetTextures(renderTargets) {\n if (MaterialFlags.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {\n renderTargets.push(this._refractionTexture);\n }\n }\n hasTexture(texture) {\n if (this._thicknessTexture === texture) {\n return true;\n }\n if (this._refractionTexture === texture) {\n return true;\n }\n return false;\n }\n hasRenderTargetTextures() {\n if (MaterialFlags.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {\n return true;\n }\n return false;\n }\n getActiveTextures(activeTextures) {\n if (this._thicknessTexture) {\n activeTextures.push(this._thicknessTexture);\n }\n if (this._refractionTexture) {\n activeTextures.push(this._refractionTexture);\n }\n }\n getAnimatables(animatables) {\n if (this._thicknessTexture && this._thicknessTexture.animations && this._thicknessTexture.animations.length > 0) {\n animatables.push(this._thicknessTexture);\n }\n if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {\n animatables.push(this._refractionTexture);\n }\n }\n dispose(forceDisposeTextures) {\n if (forceDisposeTextures) {\n if (this._thicknessTexture) {\n this._thicknessTexture.dispose();\n }\n if (this._refractionTexture) {\n this._refractionTexture.dispose();\n }\n }\n }\n getClassName() {\n return \"PBRSubSurfaceConfiguration\";\n }\n addFallbacks(defines, fallbacks, currentRank) {\n if (defines.SS_SCATTERING) {\n fallbacks.addFallback(currentRank++, \"SS_SCATTERING\");\n }\n if (defines.SS_TRANSLUCENCY) {\n fallbacks.addFallback(currentRank++, \"SS_TRANSLUCENCY\");\n }\n return currentRank;\n }\n getSamplers(samplers) {\n samplers.push(\"thicknessSampler\", \"refractionIntensitySampler\", \"translucencyIntensitySampler\", \"refractionSampler\", \"refractionSamplerLow\", \"refractionSamplerHigh\");\n }\n getUniforms() {\n return {\n ubo: [\n { name: \"vRefractionMicrosurfaceInfos\", size: 4, type: \"vec4\" },\n { name: \"vRefractionFilteringInfo\", size: 2, type: \"vec2\" },\n { name: \"vTranslucencyIntensityInfos\", size: 2, type: \"vec2\" },\n { name: \"vRefractionInfos\", size: 4, type: \"vec4\" },\n { name: \"refractionMatrix\", size: 16, type: \"mat4\" },\n { name: \"vThicknessInfos\", size: 2, type: \"vec2\" },\n { name: \"vRefractionIntensityInfos\", size: 2, type: \"vec2\" },\n { name: \"thicknessMatrix\", size: 16, type: \"mat4\" },\n { name: \"refractionIntensityMatrix\", size: 16, type: \"mat4\" },\n { name: \"translucencyIntensityMatrix\", size: 16, type: \"mat4\" },\n { name: \"vThicknessParam\", size: 2, type: \"vec2\" },\n { name: \"vDiffusionDistance\", size: 3, type: \"vec3\" },\n { name: \"vTintColor\", size: 4, type: \"vec4\" },\n { name: \"vSubSurfaceIntensity\", size: 3, type: \"vec3\" },\n { name: \"vRefractionPosition\", size: 3, type: \"vec3\" },\n { name: \"vRefractionSize\", size: 3, type: \"vec3\" },\n { name: \"scatteringDiffusionProfile\", size: 1, type: \"float\" },\n ],\n };\n }\n}\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSubSurfaceConfiguration.prototype, \"isRefractionEnabled\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSubSurfaceConfiguration.prototype, \"isTranslucencyEnabled\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markScenePrePassDirty\")\n], PBRSubSurfaceConfiguration.prototype, \"isScatteringEnabled\", void 0);\n__decorate([\n serialize()\n], PBRSubSurfaceConfiguration.prototype, \"_scatteringDiffusionProfileIndex\", void 0);\n__decorate([\n serialize()\n], PBRSubSurfaceConfiguration.prototype, \"refractionIntensity\", void 0);\n__decorate([\n serialize()\n], PBRSubSurfaceConfiguration.prototype, \"translucencyIntensity\", void 0);\n__decorate([\n serialize()\n], PBRSubSurfaceConfiguration.prototype, \"useAlbedoToTintRefraction\", void 0);\n__decorate([\n serialize()\n], PBRSubSurfaceConfiguration.prototype, \"useAlbedoToTintTranslucency\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSubSurfaceConfiguration.prototype, \"thicknessTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSubSurfaceConfiguration.prototype, \"refractionTexture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSubSurfaceConfiguration.prototype, \"indexOfRefraction\", void 0);\n__decorate([\n serialize()\n], PBRSubSurfaceConfiguration.prototype, \"_volumeIndexOfRefraction\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSubSurfaceConfiguration.prototype, \"volumeIndexOfRefraction\", null);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSubSurfaceConfiguration.prototype, \"invertRefractionY\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSubSurfaceConfiguration.prototype, \"linkRefractionWithTransparency\", void 0);\n__decorate([\n serialize()\n], PBRSubSurfaceConfiguration.prototype, \"minimumThickness\", void 0);\n__decorate([\n serialize()\n], PBRSubSurfaceConfiguration.prototype, \"maximumThickness\", void 0);\n__decorate([\n serialize()\n], PBRSubSurfaceConfiguration.prototype, \"useThicknessAsDepth\", void 0);\n__decorate([\n serializeAsColor3()\n], PBRSubSurfaceConfiguration.prototype, \"tintColor\", void 0);\n__decorate([\n serialize()\n], PBRSubSurfaceConfiguration.prototype, \"tintColorAtDistance\", void 0);\n__decorate([\n serializeAsColor3()\n], PBRSubSurfaceConfiguration.prototype, \"diffusionDistance\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSubSurfaceConfiguration.prototype, \"useMaskFromThicknessTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSubSurfaceConfiguration.prototype, \"refractionIntensityTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSubSurfaceConfiguration.prototype, \"translucencyIntensityTexture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRSubSurfaceConfiguration.prototype, \"useGltfStyleTextures\", void 0);\n//# sourceMappingURL=pbrSubSurfaceConfiguration.js.map","import { __decorate } from \"../../tslib.es6.js\";\n/* eslint-disable @typescript-eslint/naming-convention */\nimport { serialize, serializeAsImageProcessingConfiguration, expandToProperty } from \"../../Misc/decorators.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { SmartArray } from \"../../Misc/smartArray.js\";\nimport { GetEnvironmentBRDFTexture } from \"../../Misc/brdfTextureTools.js\";\nimport { Scene } from \"../../scene.js\";\nimport { Vector4 } from \"../../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../../Buffers/buffer.js\";\nimport { PBRBRDFConfiguration } from \"./pbrBRDFConfiguration.js\";\nimport { PrePassConfiguration } from \"../prePassConfiguration.js\";\nimport { Color3, TmpColors } from \"../../Maths/math.color.js\";\nimport { Scalar } from \"../../Maths/math.scalar.js\";\nimport { ImageProcessingConfiguration } from \"../../Materials/imageProcessingConfiguration.js\";\nimport { Material } from \"../../Materials/material.js\";\nimport { MaterialPluginEvent } from \"../materialPluginEvent.js\";\nimport { MaterialDefines } from \"../../Materials/materialDefines.js\";\nimport { PushMaterial } from \"../../Materials/pushMaterial.js\";\nimport { MaterialHelper } from \"../../Materials/materialHelper.js\";\nimport { Texture } from \"../../Materials/Textures/texture.js\";\nimport { MaterialFlags } from \"../materialFlags.js\";\n\nimport \"../../Materials/Textures/baseTexture.polynomial.js\";\nimport \"../../Shaders/pbr.fragment.js\";\nimport \"../../Shaders/pbr.vertex.js\";\nimport { EffectFallbacks } from \"../effectFallbacks.js\";\nimport { PBRClearCoatConfiguration } from \"./pbrClearCoatConfiguration.js\";\nimport { PBRIridescenceConfiguration } from \"./pbrIridescenceConfiguration.js\";\nimport { PBRAnisotropicConfiguration } from \"./pbrAnisotropicConfiguration.js\";\nimport { PBRSheenConfiguration } from \"./pbrSheenConfiguration.js\";\nimport { PBRSubSurfaceConfiguration } from \"./pbrSubSurfaceConfiguration.js\";\nimport { DetailMapConfiguration } from \"../material.detailMapConfiguration.js\";\nimport { addClipPlaneUniforms, bindClipPlane } from \"../clipPlaneMaterialHelper.js\";\nconst onCreatedEffectParameters = { effect: null, subMesh: null };\n/**\n * Manages the defines for the PBR Material.\n * @internal\n */\nexport class PBRMaterialDefines extends MaterialDefines {\n /**\n * Initializes the PBR Material defines.\n * @param externalProperties The external properties\n */\n constructor(externalProperties) {\n super(externalProperties);\n this.PBR = true;\n this.NUM_SAMPLES = \"0\";\n this.REALTIME_FILTERING = false;\n this.MAINUV1 = false;\n this.MAINUV2 = false;\n this.MAINUV3 = false;\n this.MAINUV4 = false;\n this.MAINUV5 = false;\n this.MAINUV6 = false;\n this.UV1 = false;\n this.UV2 = false;\n this.UV3 = false;\n this.UV4 = false;\n this.UV5 = false;\n this.UV6 = false;\n this.ALBEDO = false;\n this.GAMMAALBEDO = false;\n this.ALBEDODIRECTUV = 0;\n this.VERTEXCOLOR = false;\n this.BAKED_VERTEX_ANIMATION_TEXTURE = false;\n this.AMBIENT = false;\n this.AMBIENTDIRECTUV = 0;\n this.AMBIENTINGRAYSCALE = false;\n this.OPACITY = false;\n this.VERTEXALPHA = false;\n this.OPACITYDIRECTUV = 0;\n this.OPACITYRGB = false;\n this.ALPHATEST = false;\n this.DEPTHPREPASS = false;\n this.ALPHABLEND = false;\n this.ALPHAFROMALBEDO = false;\n this.ALPHATESTVALUE = \"0.5\";\n this.SPECULAROVERALPHA = false;\n this.RADIANCEOVERALPHA = false;\n this.ALPHAFRESNEL = false;\n this.LINEARALPHAFRESNEL = false;\n this.PREMULTIPLYALPHA = false;\n this.EMISSIVE = false;\n this.EMISSIVEDIRECTUV = 0;\n this.GAMMAEMISSIVE = false;\n this.REFLECTIVITY = false;\n this.REFLECTIVITY_GAMMA = false;\n this.REFLECTIVITYDIRECTUV = 0;\n this.SPECULARTERM = false;\n this.MICROSURFACEFROMREFLECTIVITYMAP = false;\n this.MICROSURFACEAUTOMATIC = false;\n this.LODBASEDMICROSFURACE = false;\n this.MICROSURFACEMAP = false;\n this.MICROSURFACEMAPDIRECTUV = 0;\n this.METALLICWORKFLOW = false;\n this.ROUGHNESSSTOREINMETALMAPALPHA = false;\n this.ROUGHNESSSTOREINMETALMAPGREEN = false;\n this.METALLNESSSTOREINMETALMAPBLUE = false;\n this.AOSTOREINMETALMAPRED = false;\n this.METALLIC_REFLECTANCE = false;\n this.METALLIC_REFLECTANCE_GAMMA = false;\n this.METALLIC_REFLECTANCEDIRECTUV = 0;\n this.METALLIC_REFLECTANCE_USE_ALPHA_ONLY = false;\n this.REFLECTANCE = false;\n this.REFLECTANCE_GAMMA = false;\n this.REFLECTANCEDIRECTUV = 0;\n this.ENVIRONMENTBRDF = false;\n this.ENVIRONMENTBRDF_RGBD = false;\n this.NORMAL = false;\n this.TANGENT = false;\n this.BUMP = false;\n this.BUMPDIRECTUV = 0;\n this.OBJECTSPACE_NORMALMAP = false;\n this.PARALLAX = false;\n this.PARALLAXOCCLUSION = false;\n this.NORMALXYSCALE = true;\n this.LIGHTMAP = false;\n this.LIGHTMAPDIRECTUV = 0;\n this.USELIGHTMAPASSHADOWMAP = false;\n this.GAMMALIGHTMAP = false;\n this.RGBDLIGHTMAP = false;\n this.REFLECTION = false;\n this.REFLECTIONMAP_3D = false;\n this.REFLECTIONMAP_SPHERICAL = false;\n this.REFLECTIONMAP_PLANAR = false;\n this.REFLECTIONMAP_CUBIC = false;\n this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;\n this.REFLECTIONMAP_PROJECTION = false;\n this.REFLECTIONMAP_SKYBOX = false;\n this.REFLECTIONMAP_EXPLICIT = false;\n this.REFLECTIONMAP_EQUIRECTANGULAR = false;\n this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;\n this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;\n this.INVERTCUBICMAP = false;\n this.USESPHERICALFROMREFLECTIONMAP = false;\n this.USEIRRADIANCEMAP = false;\n this.USESPHERICALINVERTEX = false;\n this.REFLECTIONMAP_OPPOSITEZ = false;\n this.LODINREFLECTIONALPHA = false;\n this.GAMMAREFLECTION = false;\n this.RGBDREFLECTION = false;\n this.LINEARSPECULARREFLECTION = false;\n this.RADIANCEOCCLUSION = false;\n this.HORIZONOCCLUSION = false;\n this.INSTANCES = false;\n this.THIN_INSTANCES = false;\n this.INSTANCESCOLOR = false;\n this.PREPASS = false;\n this.PREPASS_IRRADIANCE = false;\n this.PREPASS_IRRADIANCE_INDEX = -1;\n this.PREPASS_ALBEDO_SQRT = false;\n this.PREPASS_ALBEDO_SQRT_INDEX = -1;\n this.PREPASS_DEPTH = false;\n this.PREPASS_DEPTH_INDEX = -1;\n this.PREPASS_NORMAL = false;\n this.PREPASS_NORMAL_INDEX = -1;\n this.PREPASS_POSITION = false;\n this.PREPASS_POSITION_INDEX = -1;\n this.PREPASS_VELOCITY = false;\n this.PREPASS_VELOCITY_INDEX = -1;\n this.PREPASS_REFLECTIVITY = false;\n this.PREPASS_REFLECTIVITY_INDEX = -1;\n this.SCENE_MRT_COUNT = 0;\n this.NUM_BONE_INFLUENCERS = 0;\n this.BonesPerMesh = 0;\n this.BONETEXTURE = false;\n this.BONES_VELOCITY_ENABLED = false;\n this.NONUNIFORMSCALING = false;\n this.MORPHTARGETS = false;\n this.MORPHTARGETS_NORMAL = false;\n this.MORPHTARGETS_TANGENT = false;\n this.MORPHTARGETS_UV = false;\n this.NUM_MORPH_INFLUENCERS = 0;\n this.MORPHTARGETS_TEXTURE = false;\n this.IMAGEPROCESSING = false;\n this.VIGNETTE = false;\n this.VIGNETTEBLENDMODEMULTIPLY = false;\n this.VIGNETTEBLENDMODEOPAQUE = false;\n this.TONEMAPPING = false;\n this.TONEMAPPING_ACES = false;\n this.CONTRAST = false;\n this.COLORCURVES = false;\n this.COLORGRADING = false;\n this.COLORGRADING3D = false;\n this.SAMPLER3DGREENDEPTH = false;\n this.SAMPLER3DBGRMAP = false;\n this.DITHER = false;\n this.IMAGEPROCESSINGPOSTPROCESS = false;\n this.SKIPFINALCOLORCLAMP = false;\n this.EXPOSURE = false;\n this.MULTIVIEW = false;\n this.ORDER_INDEPENDENT_TRANSPARENCY = false;\n this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS = false;\n this.USEPHYSICALLIGHTFALLOFF = false;\n this.USEGLTFLIGHTFALLOFF = false;\n this.TWOSIDEDLIGHTING = false;\n this.SHADOWFLOAT = false;\n this.CLIPPLANE = false;\n this.CLIPPLANE2 = false;\n this.CLIPPLANE3 = false;\n this.CLIPPLANE4 = false;\n this.CLIPPLANE5 = false;\n this.CLIPPLANE6 = false;\n this.POINTSIZE = false;\n this.FOG = false;\n this.LOGARITHMICDEPTH = false;\n this.CAMERA_ORTHOGRAPHIC = false;\n this.CAMERA_PERSPECTIVE = false;\n this.FORCENORMALFORWARD = false;\n this.SPECULARAA = false;\n this.UNLIT = false;\n this.DEBUGMODE = 0;\n this.rebuild();\n }\n /**\n * Resets the PBR Material defines.\n */\n reset() {\n super.reset();\n this.ALPHATESTVALUE = \"0.5\";\n this.PBR = true;\n this.NORMALXYSCALE = true;\n }\n}\n/**\n * The Physically based material base class of BJS.\n *\n * This offers the main features of a standard PBR material.\n * For more information, please refer to the documentation :\n * https://doc.babylonjs.com/features/featuresDeepDive/materials/using/introToPBR\n */\nexport class PBRBaseMaterial extends PushMaterial {\n /**\n * Enables realtime filtering on the texture.\n */\n get realTimeFiltering() {\n return this._realTimeFiltering;\n }\n set realTimeFiltering(b) {\n this._realTimeFiltering = b;\n this.markAsDirty(1);\n }\n /**\n * Quality switch for realtime filtering\n */\n get realTimeFilteringQuality() {\n return this._realTimeFilteringQuality;\n }\n set realTimeFilteringQuality(n) {\n this._realTimeFilteringQuality = n;\n this.markAsDirty(1);\n }\n /**\n * Can this material render to several textures at once\n */\n get canRenderToMRT() {\n return true;\n }\n /**\n * Attaches a new image processing configuration to the PBR Material.\n * @param configuration\n */\n _attachImageProcessingConfiguration(configuration) {\n if (configuration === this._imageProcessingConfiguration) {\n return;\n }\n // Detaches observer.\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n // Pick the scene configuration if needed.\n if (!configuration) {\n this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;\n }\n else {\n this._imageProcessingConfiguration = configuration;\n }\n // Attaches observer.\n if (this._imageProcessingConfiguration) {\n this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => {\n this._markAllSubMeshesAsImageProcessingDirty();\n });\n }\n }\n /**\n * Instantiates a new PBRMaterial instance.\n *\n * @param name The material name\n * @param scene The scene the material will be use in.\n */\n constructor(name, scene) {\n super(name, scene);\n /**\n * Intensity of the direct lights e.g. the four lights available in your scene.\n * This impacts both the direct diffuse and specular highlights.\n * @internal\n */\n this._directIntensity = 1.0;\n /**\n * Intensity of the emissive part of the material.\n * This helps controlling the emissive effect without modifying the emissive color.\n * @internal\n */\n this._emissiveIntensity = 1.0;\n /**\n * Intensity of the environment e.g. how much the environment will light the object\n * either through harmonics for rough material or through the reflection for shiny ones.\n * @internal\n */\n this._environmentIntensity = 1.0;\n /**\n * This is a special control allowing the reduction of the specular highlights coming from the\n * four lights of the scene. Those highlights may not be needed in full environment lighting.\n * @internal\n */\n this._specularIntensity = 1.0;\n /**\n * This stores the direct, emissive, environment, and specular light intensities into a Vector4.\n */\n this._lightingInfos = new Vector4(this._directIntensity, this._emissiveIntensity, this._environmentIntensity, this._specularIntensity);\n /**\n * Debug Control allowing disabling the bump map on this material.\n * @internal\n */\n this._disableBumpMap = false;\n /**\n * AKA Diffuse Texture in standard nomenclature.\n * @internal\n */\n this._albedoTexture = null;\n /**\n * AKA Occlusion Texture in other nomenclature.\n * @internal\n */\n this._ambientTexture = null;\n /**\n * AKA Occlusion Texture Intensity in other nomenclature.\n * @internal\n */\n this._ambientTextureStrength = 1.0;\n /**\n * Defines how much the AO map is occluding the analytical lights (point spot...).\n * 1 means it completely occludes it\n * 0 mean it has no impact\n * @internal\n */\n this._ambientTextureImpactOnAnalyticalLights = PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;\n /**\n * Stores the alpha values in a texture.\n * @internal\n */\n this._opacityTexture = null;\n /**\n * Stores the reflection values in a texture.\n * @internal\n */\n this._reflectionTexture = null;\n /**\n * Stores the emissive values in a texture.\n * @internal\n */\n this._emissiveTexture = null;\n /**\n * AKA Specular texture in other nomenclature.\n * @internal\n */\n this._reflectivityTexture = null;\n /**\n * Used to switch from specular/glossiness to metallic/roughness workflow.\n * @internal\n */\n this._metallicTexture = null;\n /**\n * Specifies the metallic scalar of the metallic/roughness workflow.\n * Can also be used to scale the metalness values of the metallic texture.\n * @internal\n */\n this._metallic = null;\n /**\n * Specifies the roughness scalar of the metallic/roughness workflow.\n * Can also be used to scale the roughness values of the metallic texture.\n * @internal\n */\n this._roughness = null;\n /**\n * In metallic workflow, specifies an F0 factor to help configuring the material F0.\n * By default the indexOfrefraction is used to compute F0;\n *\n * This is used as a factor against the default reflectance at normal incidence to tweak it.\n *\n * F0 = defaultF0 * metallicF0Factor * metallicReflectanceColor;\n * F90 = metallicReflectanceColor;\n * @internal\n */\n this._metallicF0Factor = 1;\n /**\n * In metallic workflow, specifies an F90 color to help configuring the material F90.\n * By default the F90 is always 1;\n *\n * Please note that this factor is also used as a factor against the default reflectance at normal incidence.\n *\n * F0 = defaultF0 * metallicF0Factor * metallicReflectanceColor\n * F90 = metallicReflectanceColor;\n * @internal\n */\n this._metallicReflectanceColor = Color3.White();\n /**\n * Specifies that only the A channel from _metallicReflectanceTexture should be used.\n * If false, both RGB and A channels will be used\n * @internal\n */\n this._useOnlyMetallicFromMetallicReflectanceTexture = false;\n /**\n * Defines to store metallicReflectanceColor in RGB and metallicF0Factor in A\n * This is multiply against the scalar values defined in the material.\n * @internal\n */\n this._metallicReflectanceTexture = null;\n /**\n * Defines to store reflectanceColor in RGB\n * This is multiplied against the scalar values defined in the material.\n * If both _reflectanceTexture and _metallicReflectanceTexture textures are provided and _useOnlyMetallicFromMetallicReflectanceTexture\n * is false, _metallicReflectanceTexture takes precedence and _reflectanceTexture is not used\n * @internal\n */\n this._reflectanceTexture = null;\n /**\n * Used to enable roughness/glossiness fetch from a separate channel depending on the current mode.\n * Gray Scale represents roughness in metallic mode and glossiness in specular mode.\n * @internal\n */\n this._microSurfaceTexture = null;\n /**\n * Stores surface normal data used to displace a mesh in a texture.\n * @internal\n */\n this._bumpTexture = null;\n /**\n * Stores the pre-calculated light information of a mesh in a texture.\n * @internal\n */\n this._lightmapTexture = null;\n /**\n * The color of a material in ambient lighting.\n * @internal\n */\n this._ambientColor = new Color3(0, 0, 0);\n /**\n * AKA Diffuse Color in other nomenclature.\n * @internal\n */\n this._albedoColor = new Color3(1, 1, 1);\n /**\n * AKA Specular Color in other nomenclature.\n * @internal\n */\n this._reflectivityColor = new Color3(1, 1, 1);\n /**\n * The color applied when light is reflected from a material.\n * @internal\n */\n this._reflectionColor = new Color3(1, 1, 1);\n /**\n * The color applied when light is emitted from a material.\n * @internal\n */\n this._emissiveColor = new Color3(0, 0, 0);\n /**\n * AKA Glossiness in other nomenclature.\n * @internal\n */\n this._microSurface = 0.9;\n /**\n * Specifies that the material will use the light map as a show map.\n * @internal\n */\n this._useLightmapAsShadowmap = false;\n /**\n * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal\n * makes the reflect vector face the model (under horizon).\n * @internal\n */\n this._useHorizonOcclusion = true;\n /**\n * This parameters will enable/disable radiance occlusion by preventing the radiance to lit\n * too much the area relying on ambient texture to define their ambient occlusion.\n * @internal\n */\n this._useRadianceOcclusion = true;\n /**\n * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.\n * @internal\n */\n this._useAlphaFromAlbedoTexture = false;\n /**\n * Specifies that the material will keeps the specular highlights over a transparent surface (only the most luminous ones).\n * A car glass is a good example of that. When sun reflects on it you can not see what is behind.\n * @internal\n */\n this._useSpecularOverAlpha = true;\n /**\n * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.\n * @internal\n */\n this._useMicroSurfaceFromReflectivityMapAlpha = false;\n /**\n * Specifies if the metallic texture contains the roughness information in its alpha channel.\n * @internal\n */\n this._useRoughnessFromMetallicTextureAlpha = true;\n /**\n * Specifies if the metallic texture contains the roughness information in its green channel.\n * @internal\n */\n this._useRoughnessFromMetallicTextureGreen = false;\n /**\n * Specifies if the metallic texture contains the metallness information in its blue channel.\n * @internal\n */\n this._useMetallnessFromMetallicTextureBlue = false;\n /**\n * Specifies if the metallic texture contains the ambient occlusion information in its red channel.\n * @internal\n */\n this._useAmbientOcclusionFromMetallicTextureRed = false;\n /**\n * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.\n * @internal\n */\n this._useAmbientInGrayScale = false;\n /**\n * In case the reflectivity map does not contain the microsurface information in its alpha channel,\n * The material will try to infer what glossiness each pixel should be.\n * @internal\n */\n this._useAutoMicroSurfaceFromReflectivityMap = false;\n /**\n * Defines the falloff type used in this material.\n * It by default is Physical.\n * @internal\n */\n this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;\n /**\n * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most luminous ones).\n * A car glass is a good example of that. When the street lights reflects on it you can not see what is behind.\n * @internal\n */\n this._useRadianceOverAlpha = true;\n /**\n * Allows using an object space normal map (instead of tangent space).\n * @internal\n */\n this._useObjectSpaceNormalMap = false;\n /**\n * Allows using the bump map in parallax mode.\n * @internal\n */\n this._useParallax = false;\n /**\n * Allows using the bump map in parallax occlusion mode.\n * @internal\n */\n this._useParallaxOcclusion = false;\n /**\n * Controls the scale bias of the parallax mode.\n * @internal\n */\n this._parallaxScaleBias = 0.05;\n /**\n * If sets to true, disables all the lights affecting the material.\n * @internal\n */\n this._disableLighting = false;\n /**\n * Number of Simultaneous lights allowed on the material.\n * @internal\n */\n this._maxSimultaneousLights = 4;\n /**\n * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).\n * @internal\n */\n this._invertNormalMapX = false;\n /**\n * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).\n * @internal\n */\n this._invertNormalMapY = false;\n /**\n * If sets to true and backfaceCulling is false, normals will be flipped on the backside.\n * @internal\n */\n this._twoSidedLighting = false;\n /**\n * Defines the alpha limits in alpha test mode.\n * @internal\n */\n this._alphaCutOff = 0.4;\n /**\n * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.\n * @internal\n */\n this._forceAlphaTest = false;\n /**\n * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.\n * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)\n * @internal\n */\n this._useAlphaFresnel = false;\n /**\n * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.\n * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)\n * @internal\n */\n this._useLinearAlphaFresnel = false;\n /**\n * Specifies the environment BRDF texture used to compute the scale and offset roughness values\n * from cos theta and roughness:\n * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf\n * @internal\n */\n this._environmentBRDFTexture = null;\n /**\n * Force the shader to compute irradiance in the fragment shader in order to take bump in account.\n * @internal\n */\n this._forceIrradianceInFragment = false;\n this._realTimeFiltering = false;\n this._realTimeFilteringQuality = 8;\n /**\n * Force normal to face away from face.\n * @internal\n */\n this._forceNormalForward = false;\n /**\n * Enables specular anti aliasing in the PBR shader.\n * It will both interacts on the Geometry for analytical and IBL lighting.\n * It also prefilter the roughness map based on the bump values.\n * @internal\n */\n this._enableSpecularAntiAliasing = false;\n /**\n * Keep track of the image processing observer to allow dispose and replace.\n */\n this._imageProcessingObserver = null;\n /**\n * Stores the available render targets.\n */\n this._renderTargets = new SmartArray(16);\n /**\n * Sets the global ambient color for the material used in lighting calculations.\n */\n this._globalAmbientColor = new Color3(0, 0, 0);\n /**\n * Enables the use of logarithmic depth buffers, which is good for wide depth buffers.\n */\n this._useLogarithmicDepth = false;\n /**\n * If set to true, no lighting calculations will be applied.\n */\n this._unlit = false;\n this._debugMode = 0;\n /**\n * @internal\n * This is reserved for the inspector.\n * Defines the material debug mode.\n * It helps seeing only some components of the material while troubleshooting.\n */\n this.debugMode = 0;\n /**\n * @internal\n * This is reserved for the inspector.\n * Specify from where on screen the debug mode should start.\n * The value goes from -1 (full screen) to 1 (not visible)\n * It helps with side by side comparison against the final render\n * This defaults to -1\n */\n this.debugLimit = -1;\n /**\n * @internal\n * This is reserved for the inspector.\n * As the default viewing range might not be enough (if the ambient is really small for instance)\n * You can use the factor to better multiply the final value.\n */\n this.debugFactor = 1;\n this._cacheHasRenderTargetTextures = false;\n this.brdf = new PBRBRDFConfiguration(this);\n this.clearCoat = new PBRClearCoatConfiguration(this);\n this.iridescence = new PBRIridescenceConfiguration(this);\n this.anisotropy = new PBRAnisotropicConfiguration(this);\n this.sheen = new PBRSheenConfiguration(this);\n this.subSurface = new PBRSubSurfaceConfiguration(this);\n this.detailMap = new DetailMapConfiguration(this);\n // Setup the default processing configuration to the scene.\n this._attachImageProcessingConfiguration(null);\n this.getRenderTargetTextures = () => {\n this._renderTargets.reset();\n if (MaterialFlags.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {\n this._renderTargets.push(this._reflectionTexture);\n }\n this._eventInfo.renderTargets = this._renderTargets;\n this._callbackPluginEventFillRenderTargetTextures(this._eventInfo);\n return this._renderTargets;\n };\n this._environmentBRDFTexture = GetEnvironmentBRDFTexture(this.getScene());\n this.prePassConfiguration = new PrePassConfiguration();\n }\n /**\n * Gets a boolean indicating that current material needs to register RTT\n */\n get hasRenderTargetTextures() {\n if (MaterialFlags.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {\n return true;\n }\n return this._cacheHasRenderTargetTextures;\n }\n /**\n * Can this material render to prepass\n */\n get isPrePassCapable() {\n return !this.disableDepthWrite;\n }\n /**\n * Gets the name of the material class.\n */\n getClassName() {\n return \"PBRBaseMaterial\";\n }\n /**\n * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.\n */\n get useLogarithmicDepth() {\n return this._useLogarithmicDepth;\n }\n /**\n * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.\n */\n set useLogarithmicDepth(value) {\n this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;\n }\n /**\n * Returns true if alpha blending should be disabled.\n */\n get _disableAlphaBlending() {\n var _a;\n return (this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_OPAQUE ||\n this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_ALPHATEST ||\n ((_a = this.subSurface) === null || _a === void 0 ? void 0 : _a.disableAlphaBlending));\n }\n /**\n * Specifies whether or not this material should be rendered in alpha blend mode.\n */\n needAlphaBlending() {\n if (this._disableAlphaBlending) {\n return false;\n }\n return this.alpha < 1.0 || this._opacityTexture != null || this._shouldUseAlphaFromAlbedoTexture();\n }\n /**\n * Specifies whether or not this material should be rendered in alpha test mode.\n */\n needAlphaTesting() {\n var _a;\n if (this._forceAlphaTest) {\n return true;\n }\n if ((_a = this.subSurface) === null || _a === void 0 ? void 0 : _a.disableAlphaBlending) {\n return false;\n }\n return this._hasAlphaChannel() && (this._transparencyMode == null || this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_ALPHATEST);\n }\n /**\n * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.\n */\n _shouldUseAlphaFromAlbedoTexture() {\n return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== PBRBaseMaterial.PBRMATERIAL_OPAQUE;\n }\n /**\n * Specifies whether or not there is a usable alpha channel for transparency.\n */\n _hasAlphaChannel() {\n return (this._albedoTexture != null && this._albedoTexture.hasAlpha) || this._opacityTexture != null;\n }\n /**\n * Gets the texture used for the alpha test.\n */\n getAlphaTestTexture() {\n return this._albedoTexture;\n }\n /**\n * Specifies that the submesh is ready to be used.\n * @param mesh - BJS mesh.\n * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.\n * @param useInstances - Specifies that instances should be used.\n * @returns - boolean indicating that the submesh is ready or not.\n */\n isReadyForSubMesh(mesh, subMesh, useInstances) {\n var _a;\n if (!this._uniformBufferLayoutBuilt) {\n this.buildUniformLayout();\n }\n if (subMesh.effect && this.isFrozen) {\n if (subMesh.effect._wasPreviouslyReady && subMesh.effect._wasPreviouslyUsingInstances === useInstances) {\n return true;\n }\n }\n if (!subMesh.materialDefines) {\n this._callbackPluginEventGeneric(MaterialPluginEvent.GetDefineNames, this._eventInfo);\n subMesh.materialDefines = new PBRMaterialDefines(this._eventInfo.defineNames);\n }\n const defines = subMesh.materialDefines;\n if (this._isReadyForSubMesh(subMesh)) {\n return true;\n }\n const scene = this.getScene();\n const engine = scene.getEngine();\n if (defines._areTexturesDirty) {\n this._eventInfo.hasRenderTargetTextures = false;\n this._callbackPluginEventHasRenderTargetTextures(this._eventInfo);\n this._cacheHasRenderTargetTextures = this._eventInfo.hasRenderTargetTextures;\n if (scene.texturesEnabled) {\n if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) {\n if (!this._albedoTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) {\n if (!this._ambientTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) {\n if (!this._opacityTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n const reflectionTexture = this._getReflectionTexture();\n if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {\n if (!reflectionTexture.isReadyOrNotBlocking()) {\n return false;\n }\n if (reflectionTexture.irradianceTexture) {\n if (!reflectionTexture.irradianceTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n else {\n // Not ready until spherical are ready too.\n if (!reflectionTexture.sphericalPolynomial && ((_a = reflectionTexture.getInternalTexture()) === null || _a === void 0 ? void 0 : _a._sphericalPolynomialPromise)) {\n return false;\n }\n }\n }\n if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) {\n if (!this._lightmapTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) {\n if (!this._emissiveTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (MaterialFlags.SpecularTextureEnabled) {\n if (this._metallicTexture) {\n if (!this._metallicTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n else if (this._reflectivityTexture) {\n if (!this._reflectivityTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._metallicReflectanceTexture) {\n if (!this._metallicReflectanceTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._reflectanceTexture) {\n if (!this._reflectanceTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n if (this._microSurfaceTexture) {\n if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {\n return false;\n }\n }\n }\n if (engine.getCaps().standardDerivatives && this._bumpTexture && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) {\n // Bump texture cannot be not blocking.\n if (!this._bumpTexture.isReady()) {\n return false;\n }\n }\n if (this._environmentBRDFTexture && MaterialFlags.ReflectionTextureEnabled) {\n // This is blocking.\n if (!this._environmentBRDFTexture.isReady()) {\n return false;\n }\n }\n }\n }\n this._eventInfo.isReadyForSubMesh = true;\n this._eventInfo.defines = defines;\n this._eventInfo.subMesh = subMesh;\n this._callbackPluginEventIsReadyForSubMesh(this._eventInfo);\n if (!this._eventInfo.isReadyForSubMesh) {\n return false;\n }\n if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {\n if (!this._imageProcessingConfiguration.isReady()) {\n return false;\n }\n }\n if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {\n mesh.createNormals(true);\n Logger.Warn(\"PBRMaterial: Normals have been created for the mesh: \" + mesh.name);\n }\n const previousEffect = subMesh.effect;\n const lightDisposed = defines._areLightsDisposed;\n let effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances, null, subMesh.getRenderingMesh().hasThinInstances);\n let forceWasNotReadyPreviously = false;\n if (effect) {\n if (this._onEffectCreatedObservable) {\n onCreatedEffectParameters.effect = effect;\n onCreatedEffectParameters.subMesh = subMesh;\n this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters);\n }\n // Use previous effect while new one is compiling\n if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {\n effect = previousEffect;\n defines.markAsUnprocessed();\n forceWasNotReadyPreviously = this.isFrozen;\n if (lightDisposed) {\n // re register in case it takes more than one frame.\n defines._areLightsDisposed = true;\n return false;\n }\n }\n else {\n scene.resetCachedMaterial();\n subMesh.setEffect(effect, defines, this._materialContext);\n }\n }\n if (!subMesh.effect || !subMesh.effect.isReady()) {\n return false;\n }\n defines._renderId = scene.getRenderId();\n subMesh.effect._wasPreviouslyReady = forceWasNotReadyPreviously ? false : true;\n subMesh.effect._wasPreviouslyUsingInstances = !!useInstances;\n this._checkScenePerformancePriority();\n return true;\n }\n /**\n * Specifies if the material uses metallic roughness workflow.\n * @returns boolean specifying if the material uses metallic roughness workflow.\n */\n isMetallicWorkflow() {\n if (this._metallic != null || this._roughness != null || this._metallicTexture) {\n return true;\n }\n return false;\n }\n _prepareEffect(mesh, defines, onCompiled = null, onError = null, useInstances = null, useClipPlane = null, useThinInstances) {\n this._prepareDefines(mesh, defines, useInstances, useClipPlane, useThinInstances);\n if (!defines.isDirty) {\n return null;\n }\n defines.markAsProcessed();\n const scene = this.getScene();\n const engine = scene.getEngine();\n // Fallbacks\n const fallbacks = new EffectFallbacks();\n let fallbackRank = 0;\n if (defines.USESPHERICALINVERTEX) {\n fallbacks.addFallback(fallbackRank++, \"USESPHERICALINVERTEX\");\n }\n if (defines.FOG) {\n fallbacks.addFallback(fallbackRank, \"FOG\");\n }\n if (defines.SPECULARAA) {\n fallbacks.addFallback(fallbackRank, \"SPECULARAA\");\n }\n if (defines.POINTSIZE) {\n fallbacks.addFallback(fallbackRank, \"POINTSIZE\");\n }\n if (defines.LOGARITHMICDEPTH) {\n fallbacks.addFallback(fallbackRank, \"LOGARITHMICDEPTH\");\n }\n if (defines.PARALLAX) {\n fallbacks.addFallback(fallbackRank, \"PARALLAX\");\n }\n if (defines.PARALLAXOCCLUSION) {\n fallbacks.addFallback(fallbackRank++, \"PARALLAXOCCLUSION\");\n }\n if (defines.ENVIRONMENTBRDF) {\n fallbacks.addFallback(fallbackRank++, \"ENVIRONMENTBRDF\");\n }\n if (defines.TANGENT) {\n fallbacks.addFallback(fallbackRank++, \"TANGENT\");\n }\n if (defines.BUMP) {\n fallbacks.addFallback(fallbackRank++, \"BUMP\");\n }\n fallbackRank = MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);\n if (defines.SPECULARTERM) {\n fallbacks.addFallback(fallbackRank++, \"SPECULARTERM\");\n }\n if (defines.USESPHERICALFROMREFLECTIONMAP) {\n fallbacks.addFallback(fallbackRank++, \"USESPHERICALFROMREFLECTIONMAP\");\n }\n if (defines.USEIRRADIANCEMAP) {\n fallbacks.addFallback(fallbackRank++, \"USEIRRADIANCEMAP\");\n }\n if (defines.LIGHTMAP) {\n fallbacks.addFallback(fallbackRank++, \"LIGHTMAP\");\n }\n if (defines.NORMAL) {\n fallbacks.addFallback(fallbackRank++, \"NORMAL\");\n }\n if (defines.AMBIENT) {\n fallbacks.addFallback(fallbackRank++, \"AMBIENT\");\n }\n if (defines.EMISSIVE) {\n fallbacks.addFallback(fallbackRank++, \"EMISSIVE\");\n }\n if (defines.VERTEXCOLOR) {\n fallbacks.addFallback(fallbackRank++, \"VERTEXCOLOR\");\n }\n if (defines.MORPHTARGETS) {\n fallbacks.addFallback(fallbackRank++, \"MORPHTARGETS\");\n }\n if (defines.MULTIVIEW) {\n fallbacks.addFallback(0, \"MULTIVIEW\");\n }\n //Attributes\n const attribs = [VertexBuffer.PositionKind];\n if (defines.NORMAL) {\n attribs.push(VertexBuffer.NormalKind);\n }\n if (defines.TANGENT) {\n attribs.push(VertexBuffer.TangentKind);\n }\n for (let i = 1; i <= 6; ++i) {\n if (defines[\"UV\" + i]) {\n attribs.push(`uv${i === 1 ? \"\" : i}`);\n }\n }\n if (defines.VERTEXCOLOR) {\n attribs.push(VertexBuffer.ColorKind);\n }\n if (defines.INSTANCESCOLOR) {\n attribs.push(VertexBuffer.ColorInstanceKind);\n }\n MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);\n MaterialHelper.PrepareAttributesForInstances(attribs, defines);\n MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);\n MaterialHelper.PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines);\n let shaderName = \"pbr\";\n const uniforms = [\n \"world\",\n \"view\",\n \"viewProjection\",\n \"vEyePosition\",\n \"vLightsType\",\n \"vAmbientColor\",\n \"vAlbedoColor\",\n \"vReflectivityColor\",\n \"vMetallicReflectanceFactors\",\n \"vEmissiveColor\",\n \"visibility\",\n \"vReflectionColor\",\n \"vFogInfos\",\n \"vFogColor\",\n \"pointSize\",\n \"vAlbedoInfos\",\n \"vAmbientInfos\",\n \"vOpacityInfos\",\n \"vReflectionInfos\",\n \"vReflectionPosition\",\n \"vReflectionSize\",\n \"vEmissiveInfos\",\n \"vReflectivityInfos\",\n \"vReflectionFilteringInfo\",\n \"vMetallicReflectanceInfos\",\n \"vReflectanceInfos\",\n \"vMicroSurfaceSamplerInfos\",\n \"vBumpInfos\",\n \"vLightmapInfos\",\n \"mBones\",\n \"albedoMatrix\",\n \"ambientMatrix\",\n \"opacityMatrix\",\n \"reflectionMatrix\",\n \"emissiveMatrix\",\n \"reflectivityMatrix\",\n \"normalMatrix\",\n \"microSurfaceSamplerMatrix\",\n \"bumpMatrix\",\n \"lightmapMatrix\",\n \"metallicReflectanceMatrix\",\n \"reflectanceMatrix\",\n \"vLightingIntensity\",\n \"logarithmicDepthConstant\",\n \"vSphericalX\",\n \"vSphericalY\",\n \"vSphericalZ\",\n \"vSphericalXX_ZZ\",\n \"vSphericalYY_ZZ\",\n \"vSphericalZZ\",\n \"vSphericalXY\",\n \"vSphericalYZ\",\n \"vSphericalZX\",\n \"vSphericalL00\",\n \"vSphericalL1_1\",\n \"vSphericalL10\",\n \"vSphericalL11\",\n \"vSphericalL2_2\",\n \"vSphericalL2_1\",\n \"vSphericalL20\",\n \"vSphericalL21\",\n \"vSphericalL22\",\n \"vReflectionMicrosurfaceInfos\",\n \"vTangentSpaceParams\",\n \"boneTextureWidth\",\n \"vDebugMode\",\n \"morphTargetTextureInfo\",\n \"morphTargetTextureIndices\",\n ];\n const samplers = [\n \"albedoSampler\",\n \"reflectivitySampler\",\n \"ambientSampler\",\n \"emissiveSampler\",\n \"bumpSampler\",\n \"lightmapSampler\",\n \"opacitySampler\",\n \"reflectionSampler\",\n \"reflectionSamplerLow\",\n \"reflectionSamplerHigh\",\n \"irradianceSampler\",\n \"microSurfaceSampler\",\n \"environmentBrdfSampler\",\n \"boneSampler\",\n \"metallicReflectanceSampler\",\n \"reflectanceSampler\",\n \"morphTargets\",\n \"oitDepthSampler\",\n \"oitFrontColorSampler\",\n ];\n const uniformBuffers = [\"Material\", \"Scene\", \"Mesh\"];\n this._eventInfo.fallbacks = fallbacks;\n this._eventInfo.fallbackRank = fallbackRank;\n this._eventInfo.defines = defines;\n this._eventInfo.uniforms = uniforms;\n this._eventInfo.attributes = attribs;\n this._eventInfo.samplers = samplers;\n this._eventInfo.uniformBuffersNames = uniformBuffers;\n this._eventInfo.customCode = undefined;\n this._eventInfo.mesh = mesh;\n this._callbackPluginEventGeneric(MaterialPluginEvent.PrepareEffect, this._eventInfo);\n PrePassConfiguration.AddUniforms(uniforms);\n PrePassConfiguration.AddSamplers(samplers);\n addClipPlaneUniforms(uniforms);\n if (ImageProcessingConfiguration) {\n ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);\n ImageProcessingConfiguration.PrepareSamplers(samplers, defines);\n }\n MaterialHelper.PrepareUniformsAndSamplersList({\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: defines,\n maxSimultaneousLights: this._maxSimultaneousLights,\n });\n const csnrOptions = {};\n if (this.customShaderNameResolve) {\n shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines, attribs, csnrOptions);\n }\n const join = defines.toString();\n const effect = engine.createEffect(shaderName, {\n attributes: attribs,\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: join,\n fallbacks: fallbacks,\n onCompiled: onCompiled,\n onError: onError,\n indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS },\n processFinalCode: csnrOptions.processFinalCode,\n processCodeAfterIncludes: this._eventInfo.customCode,\n multiTarget: defines.PREPASS,\n }, engine);\n this._eventInfo.customCode = undefined;\n return effect;\n }\n _prepareDefines(mesh, defines, useInstances = null, useClipPlane = null, useThinInstances = false) {\n var _a;\n const scene = this.getScene();\n const engine = scene.getEngine();\n // Lights\n MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);\n defines._needNormals = true;\n // Multiview\n MaterialHelper.PrepareDefinesForMultiview(scene, defines);\n // PrePass\n const oit = this.needAlphaBlendingForMesh(mesh) && this.getScene().useOrderIndependentTransparency;\n MaterialHelper.PrepareDefinesForPrePass(scene, defines, this.canRenderToMRT && !oit);\n // Order independant transparency\n MaterialHelper.PrepareDefinesForOIT(scene, defines, oit);\n // Textures\n defines.METALLICWORKFLOW = this.isMetallicWorkflow();\n if (defines._areTexturesDirty) {\n defines._needUVs = false;\n for (let i = 1; i <= 6; ++i) {\n defines[\"MAINUV\" + i] = false;\n }\n if (scene.texturesEnabled) {\n defines.ALBEDODIRECTUV = 0;\n defines.AMBIENTDIRECTUV = 0;\n defines.OPACITYDIRECTUV = 0;\n defines.EMISSIVEDIRECTUV = 0;\n defines.REFLECTIVITYDIRECTUV = 0;\n defines.MICROSURFACEMAPDIRECTUV = 0;\n defines.METALLIC_REFLECTANCEDIRECTUV = 0;\n defines.REFLECTANCEDIRECTUV = 0;\n defines.BUMPDIRECTUV = 0;\n defines.LIGHTMAPDIRECTUV = 0;\n if (engine.getCaps().textureLOD) {\n defines.LODBASEDMICROSFURACE = true;\n }\n if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, \"ALBEDO\");\n defines.GAMMAALBEDO = this._albedoTexture.gammaSpace;\n }\n else {\n defines.ALBEDO = false;\n }\n if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, \"AMBIENT\");\n defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;\n }\n else {\n defines.AMBIENT = false;\n }\n if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, \"OPACITY\");\n defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;\n }\n else {\n defines.OPACITY = false;\n }\n const reflectionTexture = this._getReflectionTexture();\n if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {\n defines.REFLECTION = true;\n defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;\n defines.RGBDREFLECTION = reflectionTexture.isRGBD;\n defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;\n defines.LINEARSPECULARREFLECTION = reflectionTexture.linearSpecularLOD;\n if (this.realTimeFiltering && this.realTimeFilteringQuality > 0) {\n defines.NUM_SAMPLES = \"\" + this.realTimeFilteringQuality;\n if (engine._features.needTypeSuffixInShaderConstants) {\n defines.NUM_SAMPLES = defines.NUM_SAMPLES + \"u\";\n }\n defines.REALTIME_FILTERING = true;\n }\n else {\n defines.REALTIME_FILTERING = false;\n }\n defines.INVERTCUBICMAP = reflectionTexture.coordinatesMode === Texture.INVCUBIC_MODE;\n defines.REFLECTIONMAP_3D = reflectionTexture.isCube;\n defines.REFLECTIONMAP_OPPOSITEZ = defines.REFLECTIONMAP_3D && this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;\n defines.REFLECTIONMAP_CUBIC = false;\n defines.REFLECTIONMAP_EXPLICIT = false;\n defines.REFLECTIONMAP_PLANAR = false;\n defines.REFLECTIONMAP_PROJECTION = false;\n defines.REFLECTIONMAP_SKYBOX = false;\n defines.REFLECTIONMAP_SPHERICAL = false;\n defines.REFLECTIONMAP_EQUIRECTANGULAR = false;\n defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;\n defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;\n switch (reflectionTexture.coordinatesMode) {\n case Texture.EXPLICIT_MODE:\n defines.REFLECTIONMAP_EXPLICIT = true;\n break;\n case Texture.PLANAR_MODE:\n defines.REFLECTIONMAP_PLANAR = true;\n break;\n case Texture.PROJECTION_MODE:\n defines.REFLECTIONMAP_PROJECTION = true;\n break;\n case Texture.SKYBOX_MODE:\n defines.REFLECTIONMAP_SKYBOX = true;\n break;\n case Texture.SPHERICAL_MODE:\n defines.REFLECTIONMAP_SPHERICAL = true;\n break;\n case Texture.EQUIRECTANGULAR_MODE:\n defines.REFLECTIONMAP_EQUIRECTANGULAR = true;\n break;\n case Texture.FIXED_EQUIRECTANGULAR_MODE:\n defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;\n break;\n case Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:\n defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;\n break;\n case Texture.CUBIC_MODE:\n case Texture.INVCUBIC_MODE:\n default:\n defines.REFLECTIONMAP_CUBIC = true;\n defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;\n break;\n }\n if (reflectionTexture.coordinatesMode !== Texture.SKYBOX_MODE) {\n if (reflectionTexture.irradianceTexture) {\n defines.USEIRRADIANCEMAP = true;\n defines.USESPHERICALFROMREFLECTIONMAP = false;\n }\n // Assume using spherical polynomial if the reflection texture is a cube map\n else if (reflectionTexture.isCube) {\n defines.USESPHERICALFROMREFLECTIONMAP = true;\n defines.USEIRRADIANCEMAP = false;\n if (this._forceIrradianceInFragment || this.realTimeFiltering || engine.getCaps().maxVaryingVectors <= 8) {\n defines.USESPHERICALINVERTEX = false;\n }\n else {\n defines.USESPHERICALINVERTEX = true;\n }\n }\n }\n }\n else {\n defines.REFLECTION = false;\n defines.REFLECTIONMAP_3D = false;\n defines.REFLECTIONMAP_SPHERICAL = false;\n defines.REFLECTIONMAP_PLANAR = false;\n defines.REFLECTIONMAP_CUBIC = false;\n defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;\n defines.REFLECTIONMAP_PROJECTION = false;\n defines.REFLECTIONMAP_SKYBOX = false;\n defines.REFLECTIONMAP_EXPLICIT = false;\n defines.REFLECTIONMAP_EQUIRECTANGULAR = false;\n defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;\n defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;\n defines.INVERTCUBICMAP = false;\n defines.USESPHERICALFROMREFLECTIONMAP = false;\n defines.USEIRRADIANCEMAP = false;\n defines.USESPHERICALINVERTEX = false;\n defines.REFLECTIONMAP_OPPOSITEZ = false;\n defines.LODINREFLECTIONALPHA = false;\n defines.GAMMAREFLECTION = false;\n defines.RGBDREFLECTION = false;\n defines.LINEARSPECULARREFLECTION = false;\n }\n if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, \"LIGHTMAP\");\n defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;\n defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;\n defines.RGBDLIGHTMAP = this._lightmapTexture.isRGBD;\n }\n else {\n defines.LIGHTMAP = false;\n }\n if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) {\n MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, \"EMISSIVE\");\n defines.GAMMAEMISSIVE = this._emissiveTexture.gammaSpace;\n }\n else {\n defines.EMISSIVE = false;\n }\n if (MaterialFlags.SpecularTextureEnabled) {\n if (this._metallicTexture) {\n MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, \"REFLECTIVITY\");\n defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;\n defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;\n defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;\n defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;\n defines.REFLECTIVITY_GAMMA = false;\n }\n else if (this._reflectivityTexture) {\n MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, \"REFLECTIVITY\");\n defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;\n defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;\n defines.REFLECTIVITY_GAMMA = this._reflectivityTexture.gammaSpace;\n }\n else {\n defines.REFLECTIVITY = false;\n }\n if (this._metallicReflectanceTexture || this._reflectanceTexture) {\n const identicalTextures = this._metallicReflectanceTexture !== null &&\n this._metallicReflectanceTexture._texture === ((_a = this._reflectanceTexture) === null || _a === void 0 ? void 0 : _a._texture) &&\n this._metallicReflectanceTexture.checkTransformsAreIdentical(this._reflectanceTexture);\n defines.METALLIC_REFLECTANCE_USE_ALPHA_ONLY = this._useOnlyMetallicFromMetallicReflectanceTexture && !identicalTextures;\n if (this._metallicReflectanceTexture) {\n MaterialHelper.PrepareDefinesForMergedUV(this._metallicReflectanceTexture, defines, \"METALLIC_REFLECTANCE\");\n defines.METALLIC_REFLECTANCE_GAMMA = this._metallicReflectanceTexture.gammaSpace;\n }\n else {\n defines.METALLIC_REFLECTANCE = false;\n }\n if (this._reflectanceTexture &&\n !identicalTextures &&\n (!this._metallicReflectanceTexture || (this._metallicReflectanceTexture && this._useOnlyMetallicFromMetallicReflectanceTexture))) {\n MaterialHelper.PrepareDefinesForMergedUV(this._reflectanceTexture, defines, \"REFLECTANCE\");\n defines.REFLECTANCE_GAMMA = this._reflectanceTexture.gammaSpace;\n }\n else {\n defines.REFLECTANCE = false;\n }\n }\n else {\n defines.METALLIC_REFLECTANCE = false;\n defines.REFLECTANCE = false;\n }\n if (this._microSurfaceTexture) {\n MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, \"MICROSURFACEMAP\");\n }\n else {\n defines.MICROSURFACEMAP = false;\n }\n }\n else {\n defines.REFLECTIVITY = false;\n defines.MICROSURFACEMAP = false;\n }\n if (engine.getCaps().standardDerivatives && this._bumpTexture && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) {\n MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, \"BUMP\");\n if (this._useParallax && this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) {\n defines.PARALLAX = true;\n defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;\n }\n else {\n defines.PARALLAX = false;\n }\n defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;\n }\n else {\n defines.BUMP = false;\n defines.PARALLAX = false;\n defines.PARALLAXOCCLUSION = false;\n defines.OBJECTSPACE_NORMALMAP = false;\n }\n if (this._environmentBRDFTexture && MaterialFlags.ReflectionTextureEnabled) {\n defines.ENVIRONMENTBRDF = true;\n defines.ENVIRONMENTBRDF_RGBD = this._environmentBRDFTexture.isRGBD;\n }\n else {\n defines.ENVIRONMENTBRDF = false;\n defines.ENVIRONMENTBRDF_RGBD = false;\n }\n if (this._shouldUseAlphaFromAlbedoTexture()) {\n defines.ALPHAFROMALBEDO = true;\n }\n else {\n defines.ALPHAFROMALBEDO = false;\n }\n }\n defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;\n if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {\n defines.USEPHYSICALLIGHTFALLOFF = false;\n defines.USEGLTFLIGHTFALLOFF = false;\n }\n else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {\n defines.USEPHYSICALLIGHTFALLOFF = false;\n defines.USEGLTFLIGHTFALLOFF = true;\n }\n else {\n defines.USEPHYSICALLIGHTFALLOFF = true;\n defines.USEGLTFLIGHTFALLOFF = false;\n }\n defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;\n if (!this.backFaceCulling && this._twoSidedLighting) {\n defines.TWOSIDEDLIGHTING = true;\n }\n else {\n defines.TWOSIDEDLIGHTING = false;\n }\n defines.SPECULARAA = engine.getCaps().standardDerivatives && this._enableSpecularAntiAliasing;\n }\n if (defines._areTexturesDirty || defines._areMiscDirty) {\n defines.ALPHATESTVALUE = `${this._alphaCutOff}${this._alphaCutOff % 1 === 0 ? \".\" : \"\"}`;\n defines.PREMULTIPLYALPHA = this.alphaMode === 7 || this.alphaMode === 8;\n defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);\n defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;\n defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;\n }\n if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {\n this._imageProcessingConfiguration.prepareDefines(defines);\n }\n defines.FORCENORMALFORWARD = this._forceNormalForward;\n defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;\n defines.HORIZONOCCLUSION = this._useHorizonOcclusion;\n // Misc.\n if (defines._areMiscDirty) {\n MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);\n defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(VertexBuffer.NormalKind));\n defines.DEBUGMODE = this._debugMode;\n }\n // Values that need to be evaluated on every frame\n MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, this, defines, useInstances ? true : false, useClipPlane, useThinInstances);\n // External config\n this._eventInfo.defines = defines;\n this._eventInfo.mesh = mesh;\n this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo);\n // Attribs\n MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== PBRBaseMaterial.PBRMATERIAL_OPAQUE);\n // External config\n this._callbackPluginEventPrepareDefines(this._eventInfo);\n }\n /**\n * Force shader compilation\n * @param mesh\n * @param onCompiled\n * @param options\n */\n forceCompilation(mesh, onCompiled, options) {\n const localOptions = Object.assign({ clipPlane: false, useInstances: false }, options);\n if (!this._uniformBufferLayoutBuilt) {\n this.buildUniformLayout();\n }\n this._callbackPluginEventGeneric(MaterialPluginEvent.GetDefineNames, this._eventInfo);\n const defines = new PBRMaterialDefines(this._eventInfo.defineNames);\n const effect = this._prepareEffect(mesh, defines, undefined, undefined, localOptions.useInstances, localOptions.clipPlane, mesh.hasThinInstances);\n if (this._onEffectCreatedObservable) {\n onCreatedEffectParameters.effect = effect;\n onCreatedEffectParameters.subMesh = null;\n this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters);\n }\n if (effect.isReady()) {\n if (onCompiled) {\n onCompiled(this);\n }\n }\n else {\n effect.onCompileObservable.add(() => {\n if (onCompiled) {\n onCompiled(this);\n }\n });\n }\n }\n /**\n * Initializes the uniform buffer layout for the shader.\n */\n buildUniformLayout() {\n // Order is important !\n const ubo = this._uniformBuffer;\n ubo.addUniform(\"vAlbedoInfos\", 2);\n ubo.addUniform(\"vAmbientInfos\", 4);\n ubo.addUniform(\"vOpacityInfos\", 2);\n ubo.addUniform(\"vEmissiveInfos\", 2);\n ubo.addUniform(\"vLightmapInfos\", 2);\n ubo.addUniform(\"vReflectivityInfos\", 3);\n ubo.addUniform(\"vMicroSurfaceSamplerInfos\", 2);\n ubo.addUniform(\"vReflectionInfos\", 2);\n ubo.addUniform(\"vReflectionFilteringInfo\", 2);\n ubo.addUniform(\"vReflectionPosition\", 3);\n ubo.addUniform(\"vReflectionSize\", 3);\n ubo.addUniform(\"vBumpInfos\", 3);\n ubo.addUniform(\"albedoMatrix\", 16);\n ubo.addUniform(\"ambientMatrix\", 16);\n ubo.addUniform(\"opacityMatrix\", 16);\n ubo.addUniform(\"emissiveMatrix\", 16);\n ubo.addUniform(\"lightmapMatrix\", 16);\n ubo.addUniform(\"reflectivityMatrix\", 16);\n ubo.addUniform(\"microSurfaceSamplerMatrix\", 16);\n ubo.addUniform(\"bumpMatrix\", 16);\n ubo.addUniform(\"vTangentSpaceParams\", 2);\n ubo.addUniform(\"reflectionMatrix\", 16);\n ubo.addUniform(\"vReflectionColor\", 3);\n ubo.addUniform(\"vAlbedoColor\", 4);\n ubo.addUniform(\"vLightingIntensity\", 4);\n ubo.addUniform(\"vReflectionMicrosurfaceInfos\", 3);\n ubo.addUniform(\"pointSize\", 1);\n ubo.addUniform(\"vReflectivityColor\", 4);\n ubo.addUniform(\"vEmissiveColor\", 3);\n ubo.addUniform(\"vAmbientColor\", 3);\n ubo.addUniform(\"vDebugMode\", 2);\n ubo.addUniform(\"vMetallicReflectanceFactors\", 4);\n ubo.addUniform(\"vMetallicReflectanceInfos\", 2);\n ubo.addUniform(\"metallicReflectanceMatrix\", 16);\n ubo.addUniform(\"vReflectanceInfos\", 2);\n ubo.addUniform(\"reflectanceMatrix\", 16);\n ubo.addUniform(\"vSphericalL00\", 3);\n ubo.addUniform(\"vSphericalL1_1\", 3);\n ubo.addUniform(\"vSphericalL10\", 3);\n ubo.addUniform(\"vSphericalL11\", 3);\n ubo.addUniform(\"vSphericalL2_2\", 3);\n ubo.addUniform(\"vSphericalL2_1\", 3);\n ubo.addUniform(\"vSphericalL20\", 3);\n ubo.addUniform(\"vSphericalL21\", 3);\n ubo.addUniform(\"vSphericalL22\", 3);\n ubo.addUniform(\"vSphericalX\", 3);\n ubo.addUniform(\"vSphericalY\", 3);\n ubo.addUniform(\"vSphericalZ\", 3);\n ubo.addUniform(\"vSphericalXX_ZZ\", 3);\n ubo.addUniform(\"vSphericalYY_ZZ\", 3);\n ubo.addUniform(\"vSphericalZZ\", 3);\n ubo.addUniform(\"vSphericalXY\", 3);\n ubo.addUniform(\"vSphericalYZ\", 3);\n ubo.addUniform(\"vSphericalZX\", 3);\n super.buildUniformLayout();\n }\n /**\n * Binds the submesh data.\n * @param world - The world matrix.\n * @param mesh - The BJS mesh.\n * @param subMesh - A submesh of the BJS mesh.\n */\n bindForSubMesh(world, mesh, subMesh) {\n var _a, _b, _c, _d;\n const scene = this.getScene();\n const defines = subMesh.materialDefines;\n if (!defines) {\n return;\n }\n const effect = subMesh.effect;\n if (!effect) {\n return;\n }\n this._activeEffect = effect;\n // Matrices Mesh.\n mesh.getMeshUniformBuffer().bindToEffect(effect, \"Mesh\");\n mesh.transferToEffect(world);\n const engine = scene.getEngine();\n // Binding unconditionally\n this._uniformBuffer.bindToEffect(effect, \"Material\");\n this.prePassConfiguration.bindForSubMesh(this._activeEffect, scene, mesh, world, this.isFrozen);\n this._eventInfo.subMesh = subMesh;\n this._callbackPluginEventHardBindForSubMesh(this._eventInfo);\n // Normal Matrix\n if (defines.OBJECTSPACE_NORMALMAP) {\n world.toNormalMatrix(this._normalMatrix);\n this.bindOnlyNormalMatrix(this._normalMatrix);\n }\n const mustRebind = effect._forceRebindOnNextCall || this._mustRebind(scene, effect, mesh.visibility);\n // Bones\n MaterialHelper.BindBonesParameters(mesh, this._activeEffect, this.prePassConfiguration);\n let reflectionTexture = null;\n const ubo = this._uniformBuffer;\n if (mustRebind) {\n this.bindViewProjection(effect);\n reflectionTexture = this._getReflectionTexture();\n if (!ubo.useUbo || !this.isFrozen || !ubo.isSync || effect._forceRebindOnNextCall) {\n // Texture uniforms\n if (scene.texturesEnabled) {\n if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) {\n ubo.updateFloat2(\"vAlbedoInfos\", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);\n MaterialHelper.BindTextureMatrix(this._albedoTexture, ubo, \"albedo\");\n }\n if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) {\n ubo.updateFloat4(\"vAmbientInfos\", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);\n MaterialHelper.BindTextureMatrix(this._ambientTexture, ubo, \"ambient\");\n }\n if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) {\n ubo.updateFloat2(\"vOpacityInfos\", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);\n MaterialHelper.BindTextureMatrix(this._opacityTexture, ubo, \"opacity\");\n }\n if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {\n ubo.updateMatrix(\"reflectionMatrix\", reflectionTexture.getReflectionTextureMatrix());\n ubo.updateFloat2(\"vReflectionInfos\", reflectionTexture.level, 0);\n if (reflectionTexture.boundingBoxSize) {\n const cubeTexture = reflectionTexture;\n ubo.updateVector3(\"vReflectionPosition\", cubeTexture.boundingBoxPosition);\n ubo.updateVector3(\"vReflectionSize\", cubeTexture.boundingBoxSize);\n }\n if (this.realTimeFiltering) {\n const width = reflectionTexture.getSize().width;\n ubo.updateFloat2(\"vReflectionFilteringInfo\", width, Scalar.Log2(width));\n }\n if (!defines.USEIRRADIANCEMAP) {\n const polynomials = reflectionTexture.sphericalPolynomial;\n if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {\n if (defines.SPHERICAL_HARMONICS) {\n const preScaledHarmonics = polynomials.preScaledHarmonics;\n ubo.updateVector3(\"vSphericalL00\", preScaledHarmonics.l00);\n ubo.updateVector3(\"vSphericalL1_1\", preScaledHarmonics.l1_1);\n ubo.updateVector3(\"vSphericalL10\", preScaledHarmonics.l10);\n ubo.updateVector3(\"vSphericalL11\", preScaledHarmonics.l11);\n ubo.updateVector3(\"vSphericalL2_2\", preScaledHarmonics.l2_2);\n ubo.updateVector3(\"vSphericalL2_1\", preScaledHarmonics.l2_1);\n ubo.updateVector3(\"vSphericalL20\", preScaledHarmonics.l20);\n ubo.updateVector3(\"vSphericalL21\", preScaledHarmonics.l21);\n ubo.updateVector3(\"vSphericalL22\", preScaledHarmonics.l22);\n }\n else {\n ubo.updateFloat3(\"vSphericalX\", polynomials.x.x, polynomials.x.y, polynomials.x.z);\n ubo.updateFloat3(\"vSphericalY\", polynomials.y.x, polynomials.y.y, polynomials.y.z);\n ubo.updateFloat3(\"vSphericalZ\", polynomials.z.x, polynomials.z.y, polynomials.z.z);\n ubo.updateFloat3(\"vSphericalXX_ZZ\", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);\n ubo.updateFloat3(\"vSphericalYY_ZZ\", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);\n ubo.updateFloat3(\"vSphericalZZ\", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);\n ubo.updateFloat3(\"vSphericalXY\", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);\n ubo.updateFloat3(\"vSphericalYZ\", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);\n ubo.updateFloat3(\"vSphericalZX\", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);\n }\n }\n }\n ubo.updateFloat3(\"vReflectionMicrosurfaceInfos\", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);\n }\n if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) {\n ubo.updateFloat2(\"vEmissiveInfos\", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);\n MaterialHelper.BindTextureMatrix(this._emissiveTexture, ubo, \"emissive\");\n }\n if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) {\n ubo.updateFloat2(\"vLightmapInfos\", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);\n MaterialHelper.BindTextureMatrix(this._lightmapTexture, ubo, \"lightmap\");\n }\n if (MaterialFlags.SpecularTextureEnabled) {\n if (this._metallicTexture) {\n ubo.updateFloat3(\"vReflectivityInfos\", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);\n MaterialHelper.BindTextureMatrix(this._metallicTexture, ubo, \"reflectivity\");\n }\n else if (this._reflectivityTexture) {\n ubo.updateFloat3(\"vReflectivityInfos\", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);\n MaterialHelper.BindTextureMatrix(this._reflectivityTexture, ubo, \"reflectivity\");\n }\n if (this._metallicReflectanceTexture) {\n ubo.updateFloat2(\"vMetallicReflectanceInfos\", this._metallicReflectanceTexture.coordinatesIndex, this._metallicReflectanceTexture.level);\n MaterialHelper.BindTextureMatrix(this._metallicReflectanceTexture, ubo, \"metallicReflectance\");\n }\n if (this._reflectanceTexture && defines.REFLECTANCE) {\n ubo.updateFloat2(\"vReflectanceInfos\", this._reflectanceTexture.coordinatesIndex, this._reflectanceTexture.level);\n MaterialHelper.BindTextureMatrix(this._reflectanceTexture, ubo, \"reflectance\");\n }\n if (this._microSurfaceTexture) {\n ubo.updateFloat2(\"vMicroSurfaceSamplerInfos\", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);\n MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, ubo, \"microSurfaceSampler\");\n }\n }\n if (this._bumpTexture && engine.getCaps().standardDerivatives && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) {\n ubo.updateFloat3(\"vBumpInfos\", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);\n MaterialHelper.BindTextureMatrix(this._bumpTexture, ubo, \"bump\");\n if (scene._mirroredCameraPosition) {\n ubo.updateFloat2(\"vTangentSpaceParams\", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);\n }\n else {\n ubo.updateFloat2(\"vTangentSpaceParams\", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);\n }\n }\n }\n // Point size\n if (this.pointsCloud) {\n ubo.updateFloat(\"pointSize\", this.pointSize);\n }\n // Colors\n if (defines.METALLICWORKFLOW) {\n TmpColors.Color3[0].r = this._metallic === undefined || this._metallic === null ? 1 : this._metallic;\n TmpColors.Color3[0].g = this._roughness === undefined || this._roughness === null ? 1 : this._roughness;\n ubo.updateColor4(\"vReflectivityColor\", TmpColors.Color3[0], 1);\n const ior = (_b = (_a = this.subSurface) === null || _a === void 0 ? void 0 : _a._indexOfRefraction) !== null && _b !== void 0 ? _b : 1.5;\n const outsideIOR = 1; // consider air as clear coat and other layers would remap in the shader.\n // We are here deriving our default reflectance from a common value for none metallic surface.\n // Based of the schlick fresnel approximation model\n // for dielectrics.\n const f0 = Math.pow((ior - outsideIOR) / (ior + outsideIOR), 2);\n // Tweak the default F0 and F90 based on our given setup\n this._metallicReflectanceColor.scaleToRef(f0 * this._metallicF0Factor, TmpColors.Color3[0]);\n const metallicF90 = this._metallicF0Factor;\n ubo.updateColor4(\"vMetallicReflectanceFactors\", TmpColors.Color3[0], metallicF90);\n }\n else {\n ubo.updateColor4(\"vReflectivityColor\", this._reflectivityColor, this._microSurface);\n }\n ubo.updateColor3(\"vEmissiveColor\", MaterialFlags.EmissiveTextureEnabled ? this._emissiveColor : Color3.BlackReadOnly);\n ubo.updateColor3(\"vReflectionColor\", this._reflectionColor);\n if (!defines.SS_REFRACTION && ((_c = this.subSurface) === null || _c === void 0 ? void 0 : _c._linkRefractionWithTransparency)) {\n ubo.updateColor4(\"vAlbedoColor\", this._albedoColor, 1);\n }\n else {\n ubo.updateColor4(\"vAlbedoColor\", this._albedoColor, this.alpha);\n }\n // Misc\n this._lightingInfos.x = this._directIntensity;\n this._lightingInfos.y = this._emissiveIntensity;\n this._lightingInfos.z = this._environmentIntensity * scene.environmentIntensity;\n this._lightingInfos.w = this._specularIntensity;\n ubo.updateVector4(\"vLightingIntensity\", this._lightingInfos);\n // Colors\n scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);\n ubo.updateColor3(\"vAmbientColor\", this._globalAmbientColor);\n ubo.updateFloat2(\"vDebugMode\", this.debugLimit, this.debugFactor);\n }\n // Textures\n if (scene.texturesEnabled) {\n if (this._albedoTexture && MaterialFlags.DiffuseTextureEnabled) {\n ubo.setTexture(\"albedoSampler\", this._albedoTexture);\n }\n if (this._ambientTexture && MaterialFlags.AmbientTextureEnabled) {\n ubo.setTexture(\"ambientSampler\", this._ambientTexture);\n }\n if (this._opacityTexture && MaterialFlags.OpacityTextureEnabled) {\n ubo.setTexture(\"opacitySampler\", this._opacityTexture);\n }\n if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) {\n if (defines.LODBASEDMICROSFURACE) {\n ubo.setTexture(\"reflectionSampler\", reflectionTexture);\n }\n else {\n ubo.setTexture(\"reflectionSampler\", reflectionTexture._lodTextureMid || reflectionTexture);\n ubo.setTexture(\"reflectionSamplerLow\", reflectionTexture._lodTextureLow || reflectionTexture);\n ubo.setTexture(\"reflectionSamplerHigh\", reflectionTexture._lodTextureHigh || reflectionTexture);\n }\n if (defines.USEIRRADIANCEMAP) {\n ubo.setTexture(\"irradianceSampler\", reflectionTexture.irradianceTexture);\n }\n }\n if (defines.ENVIRONMENTBRDF) {\n ubo.setTexture(\"environmentBrdfSampler\", this._environmentBRDFTexture);\n }\n if (this._emissiveTexture && MaterialFlags.EmissiveTextureEnabled) {\n ubo.setTexture(\"emissiveSampler\", this._emissiveTexture);\n }\n if (this._lightmapTexture && MaterialFlags.LightmapTextureEnabled) {\n ubo.setTexture(\"lightmapSampler\", this._lightmapTexture);\n }\n if (MaterialFlags.SpecularTextureEnabled) {\n if (this._metallicTexture) {\n ubo.setTexture(\"reflectivitySampler\", this._metallicTexture);\n }\n else if (this._reflectivityTexture) {\n ubo.setTexture(\"reflectivitySampler\", this._reflectivityTexture);\n }\n if (this._metallicReflectanceTexture) {\n ubo.setTexture(\"metallicReflectanceSampler\", this._metallicReflectanceTexture);\n }\n if (this._reflectanceTexture && defines.REFLECTANCE) {\n ubo.setTexture(\"reflectanceSampler\", this._reflectanceTexture);\n }\n if (this._microSurfaceTexture) {\n ubo.setTexture(\"microSurfaceSampler\", this._microSurfaceTexture);\n }\n }\n if (this._bumpTexture && engine.getCaps().standardDerivatives && MaterialFlags.BumpTextureEnabled && !this._disableBumpMap) {\n ubo.setTexture(\"bumpSampler\", this._bumpTexture);\n }\n }\n // OIT with depth peeling\n if (this.getScene().useOrderIndependentTransparency && this.needAlphaBlendingForMesh(mesh)) {\n this.getScene().depthPeelingRenderer.bind(effect);\n }\n this._eventInfo.subMesh = subMesh;\n this._callbackPluginEventBindForSubMesh(this._eventInfo);\n // Clip plane\n bindClipPlane(this._activeEffect, this, scene);\n this.bindEyePosition(effect);\n }\n else if (scene.getEngine()._features.needToAlwaysBindUniformBuffers) {\n this._needToBindSceneUbo = true;\n }\n if (mustRebind || !this.isFrozen) {\n // Lights\n if (scene.lightsEnabled && !this._disableLighting) {\n MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights);\n }\n // View\n if ((scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) || reflectionTexture || mesh.receiveShadows || defines.PREPASS) {\n this.bindView(effect);\n }\n // Fog\n MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);\n // Morph targets\n if (defines.NUM_MORPH_INFLUENCERS) {\n MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);\n }\n if (defines.BAKED_VERTEX_ANIMATION_TEXTURE) {\n (_d = mesh.bakedVertexAnimationManager) === null || _d === void 0 ? void 0 : _d.bind(effect, defines.INSTANCES);\n }\n // image processing\n this._imageProcessingConfiguration.bind(this._activeEffect);\n // Log. depth\n MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);\n }\n this._afterBind(mesh, this._activeEffect);\n ubo.update();\n }\n /**\n * Returns the animatable textures.\n * If material have animatable metallic texture, then reflectivity texture will not be returned, even if it has animations.\n * @returns - Array of animatable textures.\n */\n getAnimatables() {\n const results = super.getAnimatables();\n if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {\n results.push(this._albedoTexture);\n }\n if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {\n results.push(this._ambientTexture);\n }\n if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {\n results.push(this._opacityTexture);\n }\n if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {\n results.push(this._reflectionTexture);\n }\n if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {\n results.push(this._emissiveTexture);\n }\n if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {\n results.push(this._metallicTexture);\n }\n else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {\n results.push(this._reflectivityTexture);\n }\n if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {\n results.push(this._bumpTexture);\n }\n if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {\n results.push(this._lightmapTexture);\n }\n if (this._metallicReflectanceTexture && this._metallicReflectanceTexture.animations && this._metallicReflectanceTexture.animations.length > 0) {\n results.push(this._metallicReflectanceTexture);\n }\n if (this._reflectanceTexture && this._reflectanceTexture.animations && this._reflectanceTexture.animations.length > 0) {\n results.push(this._reflectanceTexture);\n }\n if (this._microSurfaceTexture && this._microSurfaceTexture.animations && this._microSurfaceTexture.animations.length > 0) {\n results.push(this._microSurfaceTexture);\n }\n return results;\n }\n /**\n * Returns the texture used for reflections.\n * @returns - Reflection texture if present. Otherwise, returns the environment texture.\n */\n _getReflectionTexture() {\n if (this._reflectionTexture) {\n return this._reflectionTexture;\n }\n return this.getScene().environmentTexture;\n }\n /**\n * Returns an array of the actively used textures.\n * @returns - Array of BaseTextures\n */\n getActiveTextures() {\n const activeTextures = super.getActiveTextures();\n if (this._albedoTexture) {\n activeTextures.push(this._albedoTexture);\n }\n if (this._ambientTexture) {\n activeTextures.push(this._ambientTexture);\n }\n if (this._opacityTexture) {\n activeTextures.push(this._opacityTexture);\n }\n if (this._reflectionTexture) {\n activeTextures.push(this._reflectionTexture);\n }\n if (this._emissiveTexture) {\n activeTextures.push(this._emissiveTexture);\n }\n if (this._reflectivityTexture) {\n activeTextures.push(this._reflectivityTexture);\n }\n if (this._metallicTexture) {\n activeTextures.push(this._metallicTexture);\n }\n if (this._metallicReflectanceTexture) {\n activeTextures.push(this._metallicReflectanceTexture);\n }\n if (this._reflectanceTexture) {\n activeTextures.push(this._reflectanceTexture);\n }\n if (this._microSurfaceTexture) {\n activeTextures.push(this._microSurfaceTexture);\n }\n if (this._bumpTexture) {\n activeTextures.push(this._bumpTexture);\n }\n if (this._lightmapTexture) {\n activeTextures.push(this._lightmapTexture);\n }\n return activeTextures;\n }\n /**\n * Checks to see if a texture is used in the material.\n * @param texture - Base texture to use.\n * @returns - Boolean specifying if a texture is used in the material.\n */\n hasTexture(texture) {\n if (super.hasTexture(texture)) {\n return true;\n }\n if (this._albedoTexture === texture) {\n return true;\n }\n if (this._ambientTexture === texture) {\n return true;\n }\n if (this._opacityTexture === texture) {\n return true;\n }\n if (this._reflectionTexture === texture) {\n return true;\n }\n if (this._emissiveTexture === texture) {\n return true;\n }\n if (this._reflectivityTexture === texture) {\n return true;\n }\n if (this._metallicTexture === texture) {\n return true;\n }\n if (this._metallicReflectanceTexture === texture) {\n return true;\n }\n if (this._reflectanceTexture === texture) {\n return true;\n }\n if (this._microSurfaceTexture === texture) {\n return true;\n }\n if (this._bumpTexture === texture) {\n return true;\n }\n if (this._lightmapTexture === texture) {\n return true;\n }\n return false;\n }\n /**\n * Sets the required values to the prepass renderer.\n * It can't be sets when subsurface scattering of this material is disabled.\n * When scene have ability to enable subsurface prepass effect, it will enable.\n */\n setPrePassRenderer() {\n var _a;\n if (!((_a = this.subSurface) === null || _a === void 0 ? void 0 : _a.isScatteringEnabled)) {\n return false;\n }\n const subSurfaceConfiguration = this.getScene().enableSubSurfaceForPrePass();\n if (subSurfaceConfiguration) {\n subSurfaceConfiguration.enabled = true;\n }\n return true;\n }\n /**\n * Disposes the resources of the material.\n * @param forceDisposeEffect - Forces the disposal of effects.\n * @param forceDisposeTextures - Forces the disposal of all textures.\n */\n dispose(forceDisposeEffect, forceDisposeTextures) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;\n if (forceDisposeTextures) {\n if (this._environmentBRDFTexture && this.getScene().environmentBRDFTexture !== this._environmentBRDFTexture) {\n this._environmentBRDFTexture.dispose();\n }\n (_a = this._albedoTexture) === null || _a === void 0 ? void 0 : _a.dispose();\n (_b = this._ambientTexture) === null || _b === void 0 ? void 0 : _b.dispose();\n (_c = this._opacityTexture) === null || _c === void 0 ? void 0 : _c.dispose();\n (_d = this._reflectionTexture) === null || _d === void 0 ? void 0 : _d.dispose();\n (_e = this._emissiveTexture) === null || _e === void 0 ? void 0 : _e.dispose();\n (_f = this._metallicTexture) === null || _f === void 0 ? void 0 : _f.dispose();\n (_g = this._reflectivityTexture) === null || _g === void 0 ? void 0 : _g.dispose();\n (_h = this._bumpTexture) === null || _h === void 0 ? void 0 : _h.dispose();\n (_j = this._lightmapTexture) === null || _j === void 0 ? void 0 : _j.dispose();\n (_k = this._metallicReflectanceTexture) === null || _k === void 0 ? void 0 : _k.dispose();\n (_l = this._reflectanceTexture) === null || _l === void 0 ? void 0 : _l.dispose();\n (_m = this._microSurfaceTexture) === null || _m === void 0 ? void 0 : _m.dispose();\n }\n this._renderTargets.dispose();\n if (this._imageProcessingConfiguration && this._imageProcessingObserver) {\n this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);\n }\n super.dispose(forceDisposeEffect, forceDisposeTextures);\n }\n}\n/**\n * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.\n */\nPBRBaseMaterial.PBRMATERIAL_OPAQUE = Material.MATERIAL_OPAQUE;\n/**\n * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.\n */\nPBRBaseMaterial.PBRMATERIAL_ALPHATEST = Material.MATERIAL_ALPHATEST;\n/**\n * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.\n */\nPBRBaseMaterial.PBRMATERIAL_ALPHABLEND = Material.MATERIAL_ALPHABLEND;\n/**\n * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.\n * They are also discarded below the alpha cutoff threshold to improve performances.\n */\nPBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND = Material.MATERIAL_ALPHATESTANDBLEND;\n/**\n * Defines the default value of how much AO map is occluding the analytical lights\n * (point spot...).\n */\nPBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 0;\n/**\n * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.\n */\nPBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;\n/**\n * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document\n * to enhance interoperability with other engines.\n */\nPBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;\n/**\n * PBRMaterialLightFalloff Standard: light is falling off like in the standard material\n * to enhance interoperability with other materials.\n */\nPBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;\n__decorate([\n serializeAsImageProcessingConfiguration()\n], PBRBaseMaterial.prototype, \"_imageProcessingConfiguration\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsMiscDirty\")\n], PBRBaseMaterial.prototype, \"debugMode\", void 0);\n__decorate([\n serialize()\n], PBRBaseMaterial.prototype, \"useLogarithmicDepth\", null);\n//# sourceMappingURL=pbrBaseMaterial.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize, SerializationHelper, serializeAsColor3, expandToProperty, serializeAsTexture } from \"../../Misc/decorators.js\";\nimport { GetEnvironmentBRDFTexture } from \"../../Misc/brdfTextureTools.js\";\nimport { Color3 } from \"../../Maths/math.color.js\";\nimport { PBRBaseMaterial } from \"./pbrBaseMaterial.js\";\nimport { RegisterClass } from \"../../Misc/typeStore.js\";\nimport { Material } from \"../material.js\";\n/**\n * The Physically based material of BJS.\n *\n * This offers the main features of a standard PBR material.\n * For more information, please refer to the documentation :\n * https://doc.babylonjs.com/features/featuresDeepDive/materials/using/introToPBR\n */\nexport class PBRMaterial extends PBRBaseMaterial {\n /**\n * Stores the refracted light information in a texture.\n */\n get refractionTexture() {\n return this.subSurface.refractionTexture;\n }\n set refractionTexture(value) {\n this.subSurface.refractionTexture = value;\n if (value) {\n this.subSurface.isRefractionEnabled = true;\n }\n else if (!this.subSurface.linkRefractionWithTransparency) {\n this.subSurface.isRefractionEnabled = false;\n }\n }\n /**\n * Index of refraction of the material base layer.\n * https://en.wikipedia.org/wiki/List_of_refractive_indices\n *\n * This does not only impact refraction but also the Base F0 of Dielectric Materials.\n *\n * From dielectric fresnel rules: F0 = square((iorT - iorI) / (iorT + iorI))\n */\n get indexOfRefraction() {\n return this.subSurface.indexOfRefraction;\n }\n set indexOfRefraction(value) {\n this.subSurface.indexOfRefraction = value;\n }\n /**\n * Controls if refraction needs to be inverted on Y. This could be useful for procedural texture.\n */\n get invertRefractionY() {\n return this.subSurface.invertRefractionY;\n }\n set invertRefractionY(value) {\n this.subSurface.invertRefractionY = value;\n }\n /**\n * This parameters will make the material used its opacity to control how much it is refracting against not.\n * Materials half opaque for instance using refraction could benefit from this control.\n */\n get linkRefractionWithTransparency() {\n return this.subSurface.linkRefractionWithTransparency;\n }\n set linkRefractionWithTransparency(value) {\n this.subSurface.linkRefractionWithTransparency = value;\n if (value) {\n this.subSurface.isRefractionEnabled = true;\n }\n }\n /**\n * BJS is using an hardcoded light falloff based on a manually sets up range.\n * In PBR, one way to represents the falloff is to use the inverse squared root algorithm.\n * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.\n */\n get usePhysicalLightFalloff() {\n return this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;\n }\n /**\n * BJS is using an hardcoded light falloff based on a manually sets up range.\n * In PBR, one way to represents the falloff is to use the inverse squared root algorithm.\n * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.\n */\n set usePhysicalLightFalloff(value) {\n if (value !== this.usePhysicalLightFalloff) {\n // Ensure the effect will be rebuilt.\n this._markAllSubMeshesAsTexturesDirty();\n if (value) {\n this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;\n }\n else {\n this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_STANDARD;\n }\n }\n }\n /**\n * In order to support the falloff compatibility with gltf, a special mode has been added\n * to reproduce the gltf light falloff.\n */\n get useGLTFLightFalloff() {\n return this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF;\n }\n /**\n * In order to support the falloff compatibility with gltf, a special mode has been added\n * to reproduce the gltf light falloff.\n */\n set useGLTFLightFalloff(value) {\n if (value !== this.useGLTFLightFalloff) {\n // Ensure the effect will be rebuilt.\n this._markAllSubMeshesAsTexturesDirty();\n if (value) {\n this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_GLTF;\n }\n else {\n this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_STANDARD;\n }\n }\n }\n /**\n * Gets the image processing configuration used either in this material.\n */\n get imageProcessingConfiguration() {\n return this._imageProcessingConfiguration;\n }\n /**\n * Sets the Default image processing configuration used either in the this material.\n *\n * If sets to null, the scene one is in use.\n */\n set imageProcessingConfiguration(value) {\n this._attachImageProcessingConfiguration(value);\n // Ensure the effect will be rebuilt.\n this._markAllSubMeshesAsTexturesDirty();\n }\n /**\n * Gets whether the color curves effect is enabled.\n */\n get cameraColorCurvesEnabled() {\n return this.imageProcessingConfiguration.colorCurvesEnabled;\n }\n /**\n * Sets whether the color curves effect is enabled.\n */\n set cameraColorCurvesEnabled(value) {\n this.imageProcessingConfiguration.colorCurvesEnabled = value;\n }\n /**\n * Gets whether the color grading effect is enabled.\n */\n get cameraColorGradingEnabled() {\n return this.imageProcessingConfiguration.colorGradingEnabled;\n }\n /**\n * Gets whether the color grading effect is enabled.\n */\n set cameraColorGradingEnabled(value) {\n this.imageProcessingConfiguration.colorGradingEnabled = value;\n }\n /**\n * Gets whether tonemapping is enabled or not.\n */\n get cameraToneMappingEnabled() {\n return this._imageProcessingConfiguration.toneMappingEnabled;\n }\n /**\n * Sets whether tonemapping is enabled or not\n */\n set cameraToneMappingEnabled(value) {\n this._imageProcessingConfiguration.toneMappingEnabled = value;\n }\n /**\n * The camera exposure used on this material.\n * This property is here and not in the camera to allow controlling exposure without full screen post process.\n * This corresponds to a photographic exposure.\n */\n get cameraExposure() {\n return this._imageProcessingConfiguration.exposure;\n }\n /**\n * The camera exposure used on this material.\n * This property is here and not in the camera to allow controlling exposure without full screen post process.\n * This corresponds to a photographic exposure.\n */\n set cameraExposure(value) {\n this._imageProcessingConfiguration.exposure = value;\n }\n /**\n * Gets The camera contrast used on this material.\n */\n get cameraContrast() {\n return this._imageProcessingConfiguration.contrast;\n }\n /**\n * Sets The camera contrast used on this material.\n */\n set cameraContrast(value) {\n this._imageProcessingConfiguration.contrast = value;\n }\n /**\n * Gets the Color Grading 2D Lookup Texture.\n */\n get cameraColorGradingTexture() {\n return this._imageProcessingConfiguration.colorGradingTexture;\n }\n /**\n * Sets the Color Grading 2D Lookup Texture.\n */\n set cameraColorGradingTexture(value) {\n this._imageProcessingConfiguration.colorGradingTexture = value;\n }\n /**\n * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\n get cameraColorCurves() {\n return this._imageProcessingConfiguration.colorCurves;\n }\n /**\n * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\n set cameraColorCurves(value) {\n this._imageProcessingConfiguration.colorCurves = value;\n }\n /**\n * Instantiates a new PBRMaterial instance.\n *\n * @param name The material name\n * @param scene The scene the material will be use in.\n */\n constructor(name, scene) {\n super(name, scene);\n /**\n * Intensity of the direct lights e.g. the four lights available in your scene.\n * This impacts both the direct diffuse and specular highlights.\n */\n this.directIntensity = 1.0;\n /**\n * Intensity of the emissive part of the material.\n * This helps controlling the emissive effect without modifying the emissive color.\n */\n this.emissiveIntensity = 1.0;\n /**\n * Intensity of the environment e.g. how much the environment will light the object\n * either through harmonics for rough material or through the reflection for shiny ones.\n */\n this.environmentIntensity = 1.0;\n /**\n * This is a special control allowing the reduction of the specular highlights coming from the\n * four lights of the scene. Those highlights may not be needed in full environment lighting.\n */\n this.specularIntensity = 1.0;\n /**\n * Debug Control allowing disabling the bump map on this material.\n */\n this.disableBumpMap = false;\n /**\n * AKA Occlusion Texture Intensity in other nomenclature.\n */\n this.ambientTextureStrength = 1.0;\n /**\n * Defines how much the AO map is occluding the analytical lights (point spot...).\n * 1 means it completely occludes it\n * 0 mean it has no impact\n */\n this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;\n /**\n * In metallic workflow, specifies an F0 factor to help configuring the material F0.\n * By default the indexOfrefraction is used to compute F0;\n *\n * This is used as a factor against the default reflectance at normal incidence to tweak it.\n *\n * F0 = defaultF0 * metallicF0Factor * metallicReflectanceColor;\n * F90 = metallicReflectanceColor;\n */\n this.metallicF0Factor = 1;\n /**\n * In metallic workflow, specifies an F90 color to help configuring the material F90.\n * By default the F90 is always 1;\n *\n * Please note that this factor is also used as a factor against the default reflectance at normal incidence.\n *\n * F0 = defaultF0 * metallicF0Factor * metallicReflectanceColor\n * F90 = metallicReflectanceColor;\n */\n this.metallicReflectanceColor = Color3.White();\n /**\n * Specifies that only the A channel from metallicReflectanceTexture should be used.\n * If false, both RGB and A channels will be used\n */\n this.useOnlyMetallicFromMetallicReflectanceTexture = false;\n /**\n * The color of a material in ambient lighting.\n */\n this.ambientColor = new Color3(0, 0, 0);\n /**\n * AKA Diffuse Color in other nomenclature.\n */\n this.albedoColor = new Color3(1, 1, 1);\n /**\n * AKA Specular Color in other nomenclature.\n */\n this.reflectivityColor = new Color3(1, 1, 1);\n /**\n * The color reflected from the material.\n */\n this.reflectionColor = new Color3(1.0, 1.0, 1.0);\n /**\n * The color emitted from the material.\n */\n this.emissiveColor = new Color3(0, 0, 0);\n /**\n * AKA Glossiness in other nomenclature.\n */\n this.microSurface = 1.0;\n /**\n * If true, the light map contains occlusion information instead of lighting info.\n */\n this.useLightmapAsShadowmap = false;\n /**\n * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.\n */\n this.useAlphaFromAlbedoTexture = false;\n /**\n * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.\n */\n this.forceAlphaTest = false;\n /**\n * Defines the alpha limits in alpha test mode.\n */\n this.alphaCutOff = 0.4;\n /**\n * Specifies that the material will keep the specular highlights over a transparent surface (only the most luminous ones).\n * A car glass is a good example of that. When sun reflects on it you can not see what is behind.\n */\n this.useSpecularOverAlpha = true;\n /**\n * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.\n */\n this.useMicroSurfaceFromReflectivityMapAlpha = false;\n /**\n * Specifies if the metallic texture contains the roughness information in its alpha channel.\n */\n this.useRoughnessFromMetallicTextureAlpha = true;\n /**\n * Specifies if the metallic texture contains the roughness information in its green channel.\n */\n this.useRoughnessFromMetallicTextureGreen = false;\n /**\n * Specifies if the metallic texture contains the metallness information in its blue channel.\n */\n this.useMetallnessFromMetallicTextureBlue = false;\n /**\n * Specifies if the metallic texture contains the ambient occlusion information in its red channel.\n */\n this.useAmbientOcclusionFromMetallicTextureRed = false;\n /**\n * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.\n */\n this.useAmbientInGrayScale = false;\n /**\n * In case the reflectivity map does not contain the microsurface information in its alpha channel,\n * The material will try to infer what glossiness each pixel should be.\n */\n this.useAutoMicroSurfaceFromReflectivityMap = false;\n /**\n * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most luminous ones).\n * A car glass is a good example of that. When the street lights reflects on it you can not see what is behind.\n */\n this.useRadianceOverAlpha = true;\n /**\n * Allows using an object space normal map (instead of tangent space).\n */\n this.useObjectSpaceNormalMap = false;\n /**\n * Allows using the bump map in parallax mode.\n */\n this.useParallax = false;\n /**\n * Allows using the bump map in parallax occlusion mode.\n */\n this.useParallaxOcclusion = false;\n /**\n * Controls the scale bias of the parallax mode.\n */\n this.parallaxScaleBias = 0.05;\n /**\n * If sets to true, disables all the lights affecting the material.\n */\n this.disableLighting = false;\n /**\n * Force the shader to compute irradiance in the fragment shader in order to take bump in account.\n */\n this.forceIrradianceInFragment = false;\n /**\n * Number of Simultaneous lights allowed on the material.\n */\n this.maxSimultaneousLights = 4;\n /**\n * If sets to true, x component of normal map value will invert (x = 1.0 - x).\n */\n this.invertNormalMapX = false;\n /**\n * If sets to true, y component of normal map value will invert (y = 1.0 - y).\n */\n this.invertNormalMapY = false;\n /**\n * If sets to true and backfaceCulling is false, normals will be flipped on the backside.\n */\n this.twoSidedLighting = false;\n /**\n * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.\n * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)\n */\n this.useAlphaFresnel = false;\n /**\n * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.\n * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)\n */\n this.useLinearAlphaFresnel = false;\n /**\n * Let user defines the brdf lookup texture used for IBL.\n * A default 8bit version is embedded but you could point at :\n * * Default texture: https://assets.babylonjs.com/environments/correlatedMSBRDF_RGBD.png\n * * Default 16bit pixel depth texture: https://assets.babylonjs.com/environments/correlatedMSBRDF.dds\n * * LEGACY Default None correlated https://assets.babylonjs.com/environments/uncorrelatedBRDF_RGBD.png\n * * LEGACY Default None correlated 16bit pixel depth https://assets.babylonjs.com/environments/uncorrelatedBRDF.dds\n */\n this.environmentBRDFTexture = null;\n /**\n * Force normal to face away from face.\n */\n this.forceNormalForward = false;\n /**\n * Enables specular anti aliasing in the PBR shader.\n * It will both interacts on the Geometry for analytical and IBL lighting.\n * It also prefilter the roughness map based on the bump values.\n */\n this.enableSpecularAntiAliasing = false;\n /**\n * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal\n * makes the reflect vector face the model (under horizon).\n */\n this.useHorizonOcclusion = true;\n /**\n * This parameters will enable/disable radiance occlusion by preventing the radiance to lit\n * too much the area relying on ambient texture to define their ambient occlusion.\n */\n this.useRadianceOcclusion = true;\n /**\n * If set to true, no lighting calculations will be applied.\n */\n this.unlit = false;\n this._environmentBRDFTexture = GetEnvironmentBRDFTexture(this.getScene());\n }\n /**\n * Returns the name of this material class.\n */\n getClassName() {\n return \"PBRMaterial\";\n }\n /**\n * Makes a duplicate of the current material.\n * @param name - name to use for the new material.\n * @param cloneTexturesOnlyOnce - if a texture is used in more than one channel (e.g diffuse and opacity), only clone it once and reuse it on the other channels. Default false.\n * @param rootUrl defines the root URL to use to load textures\n */\n clone(name, cloneTexturesOnlyOnce = true, rootUrl = \"\") {\n const clone = SerializationHelper.Clone(() => new PBRMaterial(name, this.getScene()), this, { cloneTexturesOnlyOnce });\n clone.id = name;\n clone.name = name;\n this.stencil.copyTo(clone.stencil);\n this._clonePlugins(clone, rootUrl);\n return clone;\n }\n /**\n * Serializes this PBR Material.\n * @returns - An object with the serialized material.\n */\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.customType = \"BABYLON.PBRMaterial\";\n return serializationObject;\n }\n // Statics\n /**\n * Parses a PBR Material from a serialized object.\n * @param source - Serialized object.\n * @param scene - BJS scene instance.\n * @param rootUrl - url for the scene object\n * @returns - PBRMaterial\n */\n static Parse(source, scene, rootUrl) {\n const material = SerializationHelper.Parse(() => new PBRMaterial(source.name, scene), source, scene, rootUrl);\n if (source.stencil) {\n material.stencil.parse(source.stencil, scene, rootUrl);\n }\n Material._parsePlugins(source, material, scene, rootUrl);\n // The code block below ensures backward compatibility with serialized materials before plugins are automatically serialized.\n if (source.clearCoat) {\n material.clearCoat.parse(source.clearCoat, scene, rootUrl);\n }\n if (source.anisotropy) {\n material.anisotropy.parse(source.anisotropy, scene, rootUrl);\n }\n if (source.brdf) {\n material.brdf.parse(source.brdf, scene, rootUrl);\n }\n if (source.sheen) {\n material.sheen.parse(source.sheen, scene, rootUrl);\n }\n if (source.subSurface) {\n material.subSurface.parse(source.subSurface, scene, rootUrl);\n }\n if (source.iridescence) {\n material.iridescence.parse(source.iridescence, scene, rootUrl);\n }\n return material;\n }\n}\n/**\n * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.\n */\nPBRMaterial.PBRMATERIAL_OPAQUE = PBRBaseMaterial.PBRMATERIAL_OPAQUE;\n/**\n * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.\n */\nPBRMaterial.PBRMATERIAL_ALPHATEST = PBRBaseMaterial.PBRMATERIAL_ALPHATEST;\n/**\n * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.\n */\nPBRMaterial.PBRMATERIAL_ALPHABLEND = PBRBaseMaterial.PBRMATERIAL_ALPHABLEND;\n/**\n * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.\n * They are also discarded below the alpha cutoff threshold to improve performances.\n */\nPBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = PBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND;\n/**\n * Defines the default value of how much AO map is occluding the analytical lights\n * (point spot...).\n */\nPBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"directIntensity\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"emissiveIntensity\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"environmentIntensity\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"specularIntensity\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"disableBumpMap\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"albedoTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"ambientTexture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"ambientTextureStrength\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"ambientTextureImpactOnAnalyticalLights\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesAndMiscDirty\")\n], PBRMaterial.prototype, \"opacityTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"reflectionTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"emissiveTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"reflectivityTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"metallicTexture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"metallic\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"roughness\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"metallicF0Factor\", void 0);\n__decorate([\n serializeAsColor3(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"metallicReflectanceColor\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useOnlyMetallicFromMetallicReflectanceTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"metallicReflectanceTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"reflectanceTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"microSurfaceTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"bumpTexture\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", null)\n], PBRMaterial.prototype, \"lightmapTexture\", void 0);\n__decorate([\n serializeAsColor3(\"ambient\"),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"ambientColor\", void 0);\n__decorate([\n serializeAsColor3(\"albedo\"),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"albedoColor\", void 0);\n__decorate([\n serializeAsColor3(\"reflectivity\"),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"reflectivityColor\", void 0);\n__decorate([\n serializeAsColor3(\"reflection\"),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"reflectionColor\", void 0);\n__decorate([\n serializeAsColor3(\"emissive\"),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"emissiveColor\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"microSurface\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useLightmapAsShadowmap\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesAndMiscDirty\")\n], PBRMaterial.prototype, \"useAlphaFromAlbedoTexture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesAndMiscDirty\")\n], PBRMaterial.prototype, \"forceAlphaTest\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesAndMiscDirty\")\n], PBRMaterial.prototype, \"alphaCutOff\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useSpecularOverAlpha\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useMicroSurfaceFromReflectivityMapAlpha\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useRoughnessFromMetallicTextureAlpha\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useRoughnessFromMetallicTextureGreen\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useMetallnessFromMetallicTextureBlue\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useAmbientOcclusionFromMetallicTextureRed\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useAmbientInGrayScale\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useAutoMicroSurfaceFromReflectivityMap\", void 0);\n__decorate([\n serialize()\n], PBRMaterial.prototype, \"usePhysicalLightFalloff\", null);\n__decorate([\n serialize()\n], PBRMaterial.prototype, \"useGLTFLightFalloff\", null);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useRadianceOverAlpha\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useObjectSpaceNormalMap\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useParallax\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useParallaxOcclusion\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"parallaxScaleBias\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n], PBRMaterial.prototype, \"disableLighting\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"forceIrradianceInFragment\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n], PBRMaterial.prototype, \"maxSimultaneousLights\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"invertNormalMapX\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"invertNormalMapY\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"twoSidedLighting\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useAlphaFresnel\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useLinearAlphaFresnel\", void 0);\n__decorate([\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"environmentBRDFTexture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"forceNormalForward\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"enableSpecularAntiAliasing\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useHorizonOcclusion\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMaterial.prototype, \"useRadianceOcclusion\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsMiscDirty\")\n], PBRMaterial.prototype, \"unlit\", void 0);\nRegisterClass(\"BABYLON.PBRMaterial\", PBRMaterial);\n//# sourceMappingURL=pbrMaterial.js.map","/* eslint-disable @typescript-eslint/naming-convention */\nimport { Scalar } from \"../Maths/math.scalar.js\";\nimport { SphericalPolynomial } from \"../Maths/sphericalPolynomial.js\";\n\nimport { InternalTexture, InternalTextureSource } from \"../Materials/Textures/internalTexture.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { CubeMapToSphericalPolynomialTools } from \"../Misc/HighDynamicRange/cubemapToSphericalPolynomial.js\";\nimport { BaseTexture } from \"../Materials/Textures/baseTexture.js\";\nimport { ThinEngine } from \"../Engines/thinEngine.js\";\nimport { FromHalfFloat, ToHalfFloat } from \"./textureTools.js\";\nimport \"../Engines/Extensions/engine.cubeTexture.js\";\n// Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html\n// All values and structures referenced from:\n// http://msdn.microsoft.com/en-us/library/bb943991.aspx/\nconst DDS_MAGIC = 0x20534444;\nconst //DDSD_CAPS = 0x1,\n//DDSD_HEIGHT = 0x2,\n//DDSD_WIDTH = 0x4,\n//DDSD_PITCH = 0x8,\n//DDSD_PIXELFORMAT = 0x1000,\nDDSD_MIPMAPCOUNT = 0x20000;\n//DDSD_LINEARSIZE = 0x80000,\n//DDSD_DEPTH = 0x800000;\n// var DDSCAPS_COMPLEX = 0x8,\n// DDSCAPS_MIPMAP = 0x400000,\n// DDSCAPS_TEXTURE = 0x1000;\nconst DDSCAPS2_CUBEMAP = 0x200;\n// DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,\n// DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,\n// DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,\n// DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,\n// DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,\n// DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,\n// DDSCAPS2_VOLUME = 0x200000;\nconst //DDPF_ALPHAPIXELS = 0x1,\n//DDPF_ALPHA = 0x2,\nDDPF_FOURCC = 0x4, DDPF_RGB = 0x40, \n//DDPF_YUV = 0x200,\nDDPF_LUMINANCE = 0x20000;\nfunction FourCCToInt32(value) {\n return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);\n}\nfunction Int32ToFourCC(value) {\n return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);\n}\nconst FOURCC_DXT1 = FourCCToInt32(\"DXT1\");\nconst FOURCC_DXT3 = FourCCToInt32(\"DXT3\");\nconst FOURCC_DXT5 = FourCCToInt32(\"DXT5\");\nconst FOURCC_DX10 = FourCCToInt32(\"DX10\");\nconst FOURCC_D3DFMT_R16G16B16A16F = 113;\nconst FOURCC_D3DFMT_R32G32B32A32F = 116;\nconst DXGI_FORMAT_R32G32B32A32_FLOAT = 2;\nconst DXGI_FORMAT_R16G16B16A16_FLOAT = 10;\nconst DXGI_FORMAT_B8G8R8X8_UNORM = 88;\nconst headerLengthInt = 31; // The header length in 32 bit ints\n// Offsets into the header array\nconst off_magic = 0;\nconst off_size = 1;\nconst off_flags = 2;\nconst off_height = 3;\nconst off_width = 4;\nconst off_mipmapCount = 7;\nconst off_pfFlags = 20;\nconst off_pfFourCC = 21;\nconst off_RGBbpp = 22;\nconst off_RMask = 23;\nconst off_GMask = 24;\nconst off_BMask = 25;\nconst off_AMask = 26;\n// var off_caps1 = 27;\nconst off_caps2 = 28;\n// var off_caps3 = 29;\n// var off_caps4 = 30;\nconst off_dxgiFormat = 32;\n/**\n * Class used to provide DDS decompression tools\n */\nexport class DDSTools {\n /**\n * Gets DDS information from an array buffer\n * @param data defines the array buffer view to read data from\n * @returns the DDS information\n */\n static GetDDSInfo(data) {\n const header = new Int32Array(data.buffer, data.byteOffset, headerLengthInt);\n const extendedHeader = new Int32Array(data.buffer, data.byteOffset, headerLengthInt + 4);\n let mipmapCount = 1;\n if (header[off_flags] & DDSD_MIPMAPCOUNT) {\n mipmapCount = Math.max(1, header[off_mipmapCount]);\n }\n const fourCC = header[off_pfFourCC];\n const dxgiFormat = fourCC === FOURCC_DX10 ? extendedHeader[off_dxgiFormat] : 0;\n let textureType = 0;\n switch (fourCC) {\n case FOURCC_D3DFMT_R16G16B16A16F:\n textureType = 2;\n break;\n case FOURCC_D3DFMT_R32G32B32A32F:\n textureType = 1;\n break;\n case FOURCC_DX10:\n if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {\n textureType = 2;\n break;\n }\n if (dxgiFormat === DXGI_FORMAT_R32G32B32A32_FLOAT) {\n textureType = 1;\n break;\n }\n }\n return {\n width: header[off_width],\n height: header[off_height],\n mipmapCount: mipmapCount,\n isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,\n isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,\n isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,\n isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,\n isCompressed: fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5,\n dxgiFormat: dxgiFormat,\n textureType: textureType,\n };\n }\n static _GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) {\n const destArray = new Float32Array(dataLength);\n const srcData = new Uint16Array(arrayBuffer, dataOffset);\n let index = 0;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const srcPos = (x + y * width) * 4;\n destArray[index] = FromHalfFloat(srcData[srcPos]);\n destArray[index + 1] = FromHalfFloat(srcData[srcPos + 1]);\n destArray[index + 2] = FromHalfFloat(srcData[srcPos + 2]);\n if (DDSTools.StoreLODInAlphaChannel) {\n destArray[index + 3] = lod;\n }\n else {\n destArray[index + 3] = FromHalfFloat(srcData[srcPos + 3]);\n }\n index += 4;\n }\n }\n return destArray;\n }\n static _GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) {\n if (DDSTools.StoreLODInAlphaChannel) {\n const destArray = new Uint16Array(dataLength);\n const srcData = new Uint16Array(arrayBuffer, dataOffset);\n let index = 0;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const srcPos = (x + y * width) * 4;\n destArray[index] = srcData[srcPos];\n destArray[index + 1] = srcData[srcPos + 1];\n destArray[index + 2] = srcData[srcPos + 2];\n destArray[index + 3] = ToHalfFloat(lod);\n index += 4;\n }\n }\n return destArray;\n }\n return new Uint16Array(arrayBuffer, dataOffset, dataLength);\n }\n static _GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) {\n if (DDSTools.StoreLODInAlphaChannel) {\n const destArray = new Float32Array(dataLength);\n const srcData = new Float32Array(arrayBuffer, dataOffset);\n let index = 0;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const srcPos = (x + y * width) * 4;\n destArray[index] = srcData[srcPos];\n destArray[index + 1] = srcData[srcPos + 1];\n destArray[index + 2] = srcData[srcPos + 2];\n destArray[index + 3] = lod;\n index += 4;\n }\n }\n return destArray;\n }\n return new Float32Array(arrayBuffer, dataOffset, dataLength);\n }\n static _GetFloatAsHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) {\n const destArray = new Uint16Array(dataLength);\n const srcData = new Float32Array(arrayBuffer, dataOffset);\n let index = 0;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n destArray[index] = ToHalfFloat(srcData[index]);\n destArray[index + 1] = ToHalfFloat(srcData[index + 1]);\n destArray[index + 2] = ToHalfFloat(srcData[index + 2]);\n if (DDSTools.StoreLODInAlphaChannel) {\n destArray[index + 3] = ToHalfFloat(lod);\n }\n else {\n destArray[index + 3] = ToHalfFloat(srcData[index + 3]);\n }\n index += 4;\n }\n }\n return destArray;\n }\n static _GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) {\n const destArray = new Uint8Array(dataLength);\n const srcData = new Float32Array(arrayBuffer, dataOffset);\n let index = 0;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const srcPos = (x + y * width) * 4;\n destArray[index] = Scalar.Clamp(srcData[srcPos]) * 255;\n destArray[index + 1] = Scalar.Clamp(srcData[srcPos + 1]) * 255;\n destArray[index + 2] = Scalar.Clamp(srcData[srcPos + 2]) * 255;\n if (DDSTools.StoreLODInAlphaChannel) {\n destArray[index + 3] = lod;\n }\n else {\n destArray[index + 3] = Scalar.Clamp(srcData[srcPos + 3]) * 255;\n }\n index += 4;\n }\n }\n return destArray;\n }\n static _GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) {\n const destArray = new Uint8Array(dataLength);\n const srcData = new Uint16Array(arrayBuffer, dataOffset);\n let index = 0;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const srcPos = (x + y * width) * 4;\n destArray[index] = Scalar.Clamp(FromHalfFloat(srcData[srcPos])) * 255;\n destArray[index + 1] = Scalar.Clamp(FromHalfFloat(srcData[srcPos + 1])) * 255;\n destArray[index + 2] = Scalar.Clamp(FromHalfFloat(srcData[srcPos + 2])) * 255;\n if (DDSTools.StoreLODInAlphaChannel) {\n destArray[index + 3] = lod;\n }\n else {\n destArray[index + 3] = Scalar.Clamp(FromHalfFloat(srcData[srcPos + 3])) * 255;\n }\n index += 4;\n }\n }\n return destArray;\n }\n static _GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {\n const byteArray = new Uint8Array(dataLength);\n const srcData = new Uint8Array(arrayBuffer, dataOffset);\n let index = 0;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const srcPos = (x + y * width) * 4;\n byteArray[index] = srcData[srcPos + rOffset];\n byteArray[index + 1] = srcData[srcPos + gOffset];\n byteArray[index + 2] = srcData[srcPos + bOffset];\n byteArray[index + 3] = srcData[srcPos + aOffset];\n index += 4;\n }\n }\n return byteArray;\n }\n static _ExtractLongWordOrder(value) {\n if (value === 0 || value === 255 || value === -16777216) {\n return 0;\n }\n return 1 + DDSTools._ExtractLongWordOrder(value >> 8);\n }\n static _GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {\n const byteArray = new Uint8Array(dataLength);\n const srcData = new Uint8Array(arrayBuffer, dataOffset);\n let index = 0;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const srcPos = (x + y * width) * 3;\n byteArray[index] = srcData[srcPos + rOffset];\n byteArray[index + 1] = srcData[srcPos + gOffset];\n byteArray[index + 2] = srcData[srcPos + bOffset];\n index += 3;\n }\n }\n return byteArray;\n }\n static _GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer) {\n const byteArray = new Uint8Array(dataLength);\n const srcData = new Uint8Array(arrayBuffer, dataOffset);\n let index = 0;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const srcPos = x + y * width;\n byteArray[index] = srcData[srcPos];\n index++;\n }\n }\n return byteArray;\n }\n /**\n * Uploads DDS Levels to a Babylon Texture\n * @internal\n */\n static UploadDDSLevels(engine, texture, data, info, loadMipmaps, faces, lodIndex = -1, currentFace, destTypeMustBeFilterable = true) {\n let sphericalPolynomialFaces = null;\n if (info.sphericalPolynomial) {\n sphericalPolynomialFaces = new Array();\n }\n const ext = !!engine.getCaps().s3tc;\n // TODO WEBGPU Once generateMipMaps is split into generateMipMaps + hasMipMaps in InternalTexture this line can be removed\n texture.generateMipMaps = loadMipmaps;\n const header = new Int32Array(data.buffer, data.byteOffset, headerLengthInt);\n let fourCC, width, height, dataLength = 0, dataOffset;\n let byteArray, mipmapCount, mip;\n let internalCompressedFormat = 0;\n let blockBytes = 1;\n if (header[off_magic] !== DDS_MAGIC) {\n Logger.Error(\"Invalid magic number in DDS header\");\n return;\n }\n if (!info.isFourCC && !info.isRGB && !info.isLuminance) {\n Logger.Error(\"Unsupported format, must contain a FourCC, RGB or LUMINANCE code\");\n return;\n }\n if (info.isCompressed && !ext) {\n Logger.Error(\"Compressed textures are not supported on this platform.\");\n return;\n }\n let bpp = header[off_RGBbpp];\n dataOffset = header[off_size] + 4;\n let computeFormats = false;\n if (info.isFourCC) {\n fourCC = header[off_pfFourCC];\n switch (fourCC) {\n case FOURCC_DXT1:\n blockBytes = 8;\n internalCompressedFormat = 33777;\n break;\n case FOURCC_DXT3:\n blockBytes = 16;\n internalCompressedFormat = 33778;\n break;\n case FOURCC_DXT5:\n blockBytes = 16;\n internalCompressedFormat = 33779;\n break;\n case FOURCC_D3DFMT_R16G16B16A16F:\n computeFormats = true;\n bpp = 64;\n break;\n case FOURCC_D3DFMT_R32G32B32A32F:\n computeFormats = true;\n bpp = 128;\n break;\n case FOURCC_DX10: {\n // There is an additionnal header so dataOffset need to be changed\n dataOffset += 5 * 4; // 5 uints\n let supported = false;\n switch (info.dxgiFormat) {\n case DXGI_FORMAT_R16G16B16A16_FLOAT:\n computeFormats = true;\n bpp = 64;\n supported = true;\n break;\n case DXGI_FORMAT_R32G32B32A32_FLOAT:\n computeFormats = true;\n bpp = 128;\n supported = true;\n break;\n case DXGI_FORMAT_B8G8R8X8_UNORM:\n info.isRGB = true;\n info.isFourCC = false;\n bpp = 32;\n supported = true;\n break;\n }\n if (supported) {\n break;\n }\n }\n // eslint-disable-next-line no-fallthrough\n default:\n console.error(\"Unsupported FourCC code:\", Int32ToFourCC(fourCC));\n return;\n }\n }\n const rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);\n const gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);\n const bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);\n const aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);\n if (computeFormats) {\n internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);\n }\n mipmapCount = 1;\n if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {\n mipmapCount = Math.max(1, header[off_mipmapCount]);\n }\n const startFace = currentFace || 0;\n const caps = engine.getCaps();\n for (let face = startFace; face < faces; face++) {\n width = header[off_width];\n height = header[off_height];\n for (mip = 0; mip < mipmapCount; ++mip) {\n if (lodIndex === -1 || lodIndex === mip) {\n // In case of fixed LOD, if the lod has just been uploaded, early exit.\n const i = lodIndex === -1 ? mip : 0;\n if (!info.isCompressed && info.isFourCC) {\n texture.format = 5;\n dataLength = width * height * 4;\n let floatArray = null;\n if (engine._badOS || engine._badDesktopOS || (!caps.textureHalfFloat && !caps.textureFloat)) {\n // Required because iOS has many issues with float and half float generation\n if (bpp === 128) {\n floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i);\n if (sphericalPolynomialFaces && i == 0) {\n sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i));\n }\n }\n else if (bpp === 64) {\n floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i);\n if (sphericalPolynomialFaces && i == 0) {\n sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i));\n }\n }\n texture.type = 0;\n }\n else {\n const floatAvailable = caps.textureFloat && ((destTypeMustBeFilterable && caps.textureFloatLinearFiltering) || !destTypeMustBeFilterable);\n const halfFloatAvailable = caps.textureHalfFloat && ((destTypeMustBeFilterable && caps.textureHalfFloatLinearFiltering) || !destTypeMustBeFilterable);\n const destType = (bpp === 128 || (bpp === 64 && !halfFloatAvailable)) && floatAvailable\n ? 1\n : (bpp === 64 || (bpp === 128 && !floatAvailable)) && halfFloatAvailable\n ? 2\n : 0;\n let dataGetter;\n let dataGetterPolynomial = null;\n switch (bpp) {\n case 128: {\n switch (destType) {\n case 1:\n dataGetter = DDSTools._GetFloatRGBAArrayBuffer;\n dataGetterPolynomial = null;\n break;\n case 2:\n dataGetter = DDSTools._GetFloatAsHalfFloatRGBAArrayBuffer;\n dataGetterPolynomial = DDSTools._GetFloatRGBAArrayBuffer;\n break;\n case 0:\n dataGetter = DDSTools._GetFloatAsUIntRGBAArrayBuffer;\n dataGetterPolynomial = DDSTools._GetFloatRGBAArrayBuffer;\n break;\n }\n break;\n }\n default: {\n // 64 bpp\n switch (destType) {\n case 1:\n dataGetter = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer;\n dataGetterPolynomial = null;\n break;\n case 2:\n dataGetter = DDSTools._GetHalfFloatRGBAArrayBuffer;\n dataGetterPolynomial = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer;\n break;\n case 0:\n dataGetter = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer;\n dataGetterPolynomial = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer;\n break;\n }\n break;\n }\n }\n texture.type = destType;\n floatArray = dataGetter(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i);\n if (sphericalPolynomialFaces && i == 0) {\n sphericalPolynomialFaces.push(dataGetterPolynomial ? dataGetterPolynomial(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i) : floatArray);\n }\n }\n if (floatArray) {\n engine._uploadDataToTextureDirectly(texture, floatArray, face, i);\n }\n }\n else if (info.isRGB) {\n texture.type = 0;\n if (bpp === 24) {\n texture.format = 4;\n dataLength = width * height * 3;\n byteArray = DDSTools._GetRGBArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, rOffset, gOffset, bOffset);\n engine._uploadDataToTextureDirectly(texture, byteArray, face, i);\n }\n else {\n // 32\n texture.format = 5;\n dataLength = width * height * 4;\n byteArray = DDSTools._GetRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, rOffset, gOffset, bOffset, aOffset);\n engine._uploadDataToTextureDirectly(texture, byteArray, face, i);\n }\n }\n else if (info.isLuminance) {\n const unpackAlignment = engine._getUnpackAlignement();\n const unpaddedRowSize = width;\n const paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;\n dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;\n byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer);\n texture.format = 1;\n texture.type = 0;\n engine._uploadDataToTextureDirectly(texture, byteArray, face, i);\n }\n else {\n dataLength = (((Math.max(4, width) / 4) * Math.max(4, height)) / 4) * blockBytes;\n byteArray = new Uint8Array(data.buffer, data.byteOffset + dataOffset, dataLength);\n texture.type = 0;\n engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);\n }\n }\n dataOffset += bpp ? width * height * (bpp / 8) : dataLength;\n width *= 0.5;\n height *= 0.5;\n width = Math.max(1.0, width);\n height = Math.max(1.0, height);\n }\n if (currentFace !== undefined) {\n // Loading a single face\n break;\n }\n }\n if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {\n info.sphericalPolynomial = CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({\n size: header[off_width],\n right: sphericalPolynomialFaces[0],\n left: sphericalPolynomialFaces[1],\n up: sphericalPolynomialFaces[2],\n down: sphericalPolynomialFaces[3],\n front: sphericalPolynomialFaces[4],\n back: sphericalPolynomialFaces[5],\n format: 5,\n type: 1,\n gammaSpace: false,\n });\n }\n else {\n info.sphericalPolynomial = undefined;\n }\n }\n}\n/**\n * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default)\n */\nDDSTools.StoreLODInAlphaChannel = false;\n/**\n * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)\n * @param rootUrl defines the url where the file to load is located\n * @param scene defines the current scene\n * @param lodScale defines scale to apply to the mip map selection\n * @param lodOffset defines offset to apply to the mip map selection\n * @param onLoad defines an optional callback raised when the texture is loaded\n * @param onError defines an optional callback raised if there is an issue to load the texture\n * @param format defines the format of the data\n * @param forcedExtension defines the extension to use to pick the right loader\n * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture\n * @returns the cube texture as an InternalTexture\n */\nThinEngine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = true) {\n const callback = (loadData) => {\n if (!loadData) {\n if (onLoad) {\n onLoad(null);\n }\n return;\n }\n const texture = loadData.texture;\n if (!createPolynomials) {\n texture._sphericalPolynomial = new SphericalPolynomial();\n }\n else if (loadData.info.sphericalPolynomial) {\n texture._sphericalPolynomial = loadData.info.sphericalPolynomial;\n }\n texture._source = InternalTextureSource.CubePrefiltered;\n if (this.getCaps().textureLOD) {\n // Do not add extra process if texture lod is supported.\n if (onLoad) {\n onLoad(texture);\n }\n return;\n }\n const mipSlices = 3;\n const gl = this._gl;\n const width = loadData.width;\n if (!width) {\n return;\n }\n const textures = [];\n for (let i = 0; i < mipSlices; i++) {\n //compute LOD from even spacing in smoothness (matching shader calculation)\n const smoothness = i / (mipSlices - 1);\n const roughness = 1 - smoothness;\n const minLODIndex = lodOffset; // roughness = 0\n const maxLODIndex = Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1\n const lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;\n const mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));\n const glTextureFromLod = new InternalTexture(this, InternalTextureSource.Temp);\n glTextureFromLod.type = texture.type;\n glTextureFromLod.format = texture.format;\n glTextureFromLod.width = Math.pow(2, Math.max(Scalar.Log2(width) - mipmapIndex, 0));\n glTextureFromLod.height = glTextureFromLod.width;\n glTextureFromLod.isCube = true;\n glTextureFromLod._cachedWrapU = 0;\n glTextureFromLod._cachedWrapV = 0;\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);\n glTextureFromLod.samplingMode = 2;\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n if (loadData.isDDS) {\n const info = loadData.info;\n const data = loadData.data;\n this._unpackFlipY(info.isCompressed);\n DDSTools.UploadDDSLevels(this, glTextureFromLod, data, info, true, 6, mipmapIndex);\n }\n else {\n Logger.Warn(\"DDS is the only prefiltered cube map supported so far.\");\n }\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n // Wrap in a base texture for easy binding.\n const lodTexture = new BaseTexture(scene);\n lodTexture._isCube = true;\n lodTexture._texture = glTextureFromLod;\n glTextureFromLod.isReady = true;\n textures.push(lodTexture);\n }\n texture._lodTextureHigh = textures[2];\n texture._lodTextureMid = textures[1];\n texture._lodTextureLow = textures[0];\n if (onLoad) {\n onLoad(texture);\n }\n };\n return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);\n};\n//# sourceMappingURL=dds.js.map","import { SphericalPolynomial } from \"../../../Maths/sphericalPolynomial.js\";\nimport { Engine } from \"../../../Engines/engine.js\";\nimport { DDSTools } from \"../../../Misc/dds.js\";\n/**\n * Implementation of the DDS Texture Loader.\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class _DDSTextureLoader {\n constructor() {\n /**\n * Defines whether the loader supports cascade loading the different faces.\n */\n this.supportCascades = true;\n }\n /**\n * This returns if the loader support the current file information.\n * @param extension defines the file extension of the file being loaded\n * @returns true if the loader can load the specified file\n */\n canLoad(extension) {\n return extension.endsWith(\".dds\");\n }\n /**\n * Uploads the cube texture data to the WebGL texture. It has already been bound.\n * @param imgs contains the cube maps\n * @param texture defines the BabylonJS internal texture\n * @param createPolynomials will be true if polynomials have been requested\n * @param onLoad defines the callback to trigger once the texture is ready\n */\n loadCubeData(imgs, texture, createPolynomials, onLoad) {\n const engine = texture.getEngine();\n let info;\n let loadMipmap = false;\n let maxLevel = 1000;\n if (Array.isArray(imgs)) {\n for (let index = 0; index < imgs.length; index++) {\n const data = imgs[index];\n info = DDSTools.GetDDSInfo(data);\n texture.width = info.width;\n texture.height = info.height;\n loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;\n engine._unpackFlipY(info.isCompressed);\n DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6, -1, index);\n if (!info.isFourCC && info.mipmapCount === 1) {\n engine.generateMipMapsForCubemap(texture);\n }\n else {\n maxLevel = info.mipmapCount - 1;\n }\n }\n }\n else {\n const data = imgs;\n info = DDSTools.GetDDSInfo(data);\n texture.width = info.width;\n texture.height = info.height;\n if (createPolynomials) {\n info.sphericalPolynomial = new SphericalPolynomial();\n }\n loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;\n engine._unpackFlipY(info.isCompressed);\n DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);\n if (!info.isFourCC && info.mipmapCount === 1) {\n // Do not unbind as we still need to set the parameters.\n engine.generateMipMapsForCubemap(texture, false);\n }\n else {\n maxLevel = info.mipmapCount - 1;\n }\n }\n engine._setCubeMapTextureParams(texture, loadMipmap, maxLevel);\n texture.isReady = true;\n texture.onLoadedObservable.notifyObservers(texture);\n texture.onLoadedObservable.clear();\n if (onLoad) {\n onLoad({ isDDS: true, width: texture.width, info, data: imgs, texture });\n }\n }\n /**\n * Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param callback defines the method to call once ready to upload\n */\n loadData(data, texture, callback) {\n const info = DDSTools.GetDDSInfo(data);\n const loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && info.width >> (info.mipmapCount - 1) === 1;\n callback(info.width, info.height, loadMipmap, info.isFourCC, () => {\n DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);\n });\n }\n}\n// Register the loader.\nEngine._TextureLoaders.push(new _DDSTextureLoader());\n//# sourceMappingURL=ddsTextureLoader.js.map","import { GetEnvInfo, UploadEnvLevelsAsync, UploadEnvSpherical } from \"../../../Misc/environmentTextureTools.js\";\nimport { Engine } from \"../../../Engines/engine.js\";\n/**\n * Implementation of the ENV Texture Loader.\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class _ENVTextureLoader {\n constructor() {\n /**\n * Defines whether the loader supports cascade loading the different faces.\n */\n this.supportCascades = false;\n }\n /**\n * This returns if the loader support the current file information.\n * @param extension defines the file extension of the file being loaded\n * @returns true if the loader can load the specified file\n */\n canLoad(extension) {\n return extension.endsWith(\".env\");\n }\n /**\n * Uploads the cube texture data to the WebGL texture. It has already been bound.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param createPolynomials will be true if polynomials have been requested\n * @param onLoad defines the callback to trigger once the texture is ready\n * @param onError defines the callback to trigger in case of error\n */\n loadCubeData(data, texture, createPolynomials, onLoad, onError) {\n if (Array.isArray(data)) {\n return;\n }\n const info = GetEnvInfo(data);\n if (info) {\n texture.width = info.width;\n texture.height = info.width;\n try {\n UploadEnvSpherical(texture, info);\n UploadEnvLevelsAsync(texture, data, info).then(() => {\n texture.isReady = true;\n texture.onLoadedObservable.notifyObservers(texture);\n texture.onLoadedObservable.clear();\n if (onLoad) {\n onLoad();\n }\n }, (reason) => {\n onError === null || onError === void 0 ? void 0 : onError(\"Can not upload environment levels\", reason);\n });\n }\n catch (e) {\n onError === null || onError === void 0 ? void 0 : onError(\"Can not upload environment file\", e);\n }\n }\n else if (onError) {\n onError(\"Can not parse the environment file\", null);\n }\n }\n /**\n * Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback.\n */\n loadData() {\n throw \".env not supported in 2d.\";\n }\n}\n// Register the loader.\nEngine._TextureLoaders.push(new _ENVTextureLoader());\n//# sourceMappingURL=envTextureLoader.js.map","/* eslint-disable @typescript-eslint/naming-convention */\nimport { Logger } from \"../Misc/logger.js\";\n/**\n * for description see https://www.khronos.org/opengles/sdk/tools/KTX/\n * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/\n */\nexport class KhronosTextureContainer {\n /**\n * Creates a new KhronosTextureContainer\n * @param data contents of the KTX container file\n * @param facesExpected should be either 1 or 6, based whether a cube texture or or\n */\n constructor(\n /** contents of the KTX container file */\n data, facesExpected) {\n this.data = data;\n /**\n * If the container has been made invalid (eg. constructor failed to correctly load array buffer)\n */\n this.isInvalid = false;\n if (!KhronosTextureContainer.IsValid(data)) {\n this.isInvalid = true;\n Logger.Error(\"texture missing KTX identifier\");\n return;\n }\n // load the reset of the header in native 32 bit uint\n const dataSize = Uint32Array.BYTES_PER_ELEMENT;\n const headerDataView = new DataView(this.data.buffer, this.data.byteOffset + 12, 13 * dataSize);\n const endianness = headerDataView.getUint32(0, true);\n const littleEndian = endianness === 0x04030201;\n this.glType = headerDataView.getUint32(1 * dataSize, littleEndian); // must be 0 for compressed textures\n this.glTypeSize = headerDataView.getUint32(2 * dataSize, littleEndian); // must be 1 for compressed textures\n this.glFormat = headerDataView.getUint32(3 * dataSize, littleEndian); // must be 0 for compressed textures\n this.glInternalFormat = headerDataView.getUint32(4 * dataSize, littleEndian); // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)\n this.glBaseInternalFormat = headerDataView.getUint32(5 * dataSize, littleEndian); // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)\n this.pixelWidth = headerDataView.getUint32(6 * dataSize, littleEndian); // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)\n this.pixelHeight = headerDataView.getUint32(7 * dataSize, littleEndian); // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)\n this.pixelDepth = headerDataView.getUint32(8 * dataSize, littleEndian); // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)\n this.numberOfArrayElements = headerDataView.getUint32(9 * dataSize, littleEndian); // used for texture arrays\n this.numberOfFaces = headerDataView.getUint32(10 * dataSize, littleEndian); // used for cubemap textures, should either be 1 or 6\n this.numberOfMipmapLevels = headerDataView.getUint32(11 * dataSize, littleEndian); // number of levels; disregard possibility of 0 for compressed textures\n this.bytesOfKeyValueData = headerDataView.getUint32(12 * dataSize, littleEndian); // the amount of space after the header for meta-data\n // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.\n if (this.glType !== 0) {\n Logger.Error(\"only compressed formats currently supported\");\n this.isInvalid = true;\n return;\n }\n else {\n // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.\n this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);\n }\n if (this.pixelHeight === 0 || this.pixelDepth !== 0) {\n Logger.Error(\"only 2D textures currently supported\");\n this.isInvalid = true;\n return;\n }\n if (this.numberOfArrayElements !== 0) {\n Logger.Error(\"texture arrays not currently supported\");\n this.isInvalid = true;\n return;\n }\n if (this.numberOfFaces !== facesExpected) {\n Logger.Error(\"number of faces expected\" + facesExpected + \", but found \" + this.numberOfFaces);\n this.isInvalid = true;\n return;\n }\n // we now have a completely validated file, so could use existence of loadType as success\n // would need to make this more elaborate & adjust checks above to support more than one load type\n this.loadType = KhronosTextureContainer.COMPRESSED_2D;\n }\n /**\n * Uploads KTX content to a Babylon Texture.\n * It is assumed that the texture has already been created & is currently bound\n * @internal\n */\n uploadLevels(texture, loadMipmaps) {\n switch (this.loadType) {\n case KhronosTextureContainer.COMPRESSED_2D:\n this._upload2DCompressedLevels(texture, loadMipmaps);\n break;\n case KhronosTextureContainer.TEX_2D:\n case KhronosTextureContainer.COMPRESSED_3D:\n case KhronosTextureContainer.TEX_3D:\n }\n }\n _upload2DCompressedLevels(texture, loadMipmaps) {\n // initialize width & height for level 1\n let dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;\n let width = this.pixelWidth;\n let height = this.pixelHeight;\n const mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;\n for (let level = 0; level < mipmapCount; level++) {\n const imageSize = new Int32Array(this.data.buffer, this.data.byteOffset + dataOffset, 1)[0]; // size per face, since not supporting array cubemaps\n dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.\n for (let face = 0; face < this.numberOfFaces; face++) {\n const byteArray = new Uint8Array(this.data.buffer, this.data.byteOffset + dataOffset, imageSize);\n const engine = texture.getEngine();\n engine._uploadCompressedDataToTextureDirectly(texture, texture.format, width, height, byteArray, face, level);\n dataOffset += imageSize; // add size of the image for the next face/mipmap\n dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image\n }\n width = Math.max(1.0, width * 0.5);\n height = Math.max(1.0, height * 0.5);\n }\n }\n /**\n * Checks if the given data starts with a KTX file identifier.\n * @param data the data to check\n * @returns true if the data is a KTX file or false otherwise\n */\n static IsValid(data) {\n if (data.byteLength >= 12) {\n // '«', 'K', 'T', 'X', ' ', '1', '1', '»', '\\r', '\\n', '\\x1A', '\\n'\n const identifier = new Uint8Array(data.buffer, data.byteOffset, 12);\n if (identifier[0] === 0xab &&\n identifier[1] === 0x4b &&\n identifier[2] === 0x54 &&\n identifier[3] === 0x58 &&\n identifier[4] === 0x20 &&\n identifier[5] === 0x31 &&\n identifier[6] === 0x31 &&\n identifier[7] === 0xbb &&\n identifier[8] === 0x0d &&\n identifier[9] === 0x0a &&\n identifier[10] === 0x1a &&\n identifier[11] === 0x0a) {\n return true;\n }\n }\n return false;\n }\n}\nKhronosTextureContainer.HEADER_LEN = 12 + 13 * 4; // identifier + header elements (not including key value meta-data pairs)\n// load types\nKhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()\nKhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()\nKhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()\nKhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()\n//# sourceMappingURL=khronosTextureContainer.js.map","/**\n * Helper class to push actions to a pool of workers.\n */\nexport class WorkerPool {\n /**\n * Constructor\n * @param workers Array of workers to use for actions\n */\n constructor(workers) {\n this._pendingActions = new Array();\n this._workerInfos = workers.map((worker) => ({\n workerPromise: Promise.resolve(worker),\n idle: true,\n }));\n }\n /**\n * Terminates all workers and clears any pending actions.\n */\n dispose() {\n for (const workerInfo of this._workerInfos) {\n workerInfo.workerPromise.then((worker) => {\n worker.terminate();\n });\n }\n this._workerInfos.length = 0;\n this._pendingActions.length = 0;\n }\n /**\n * Pushes an action to the worker pool. If all the workers are active, the action will be\n * pended until a worker has completed its action.\n * @param action The action to perform. Call onComplete when the action is complete.\n */\n push(action) {\n if (!this._executeOnIdleWorker(action)) {\n this._pendingActions.push(action);\n }\n }\n _executeOnIdleWorker(action) {\n for (const workerInfo of this._workerInfos) {\n if (workerInfo.idle) {\n this._execute(workerInfo, action);\n return true;\n }\n }\n return false;\n }\n _execute(workerInfo, action) {\n workerInfo.idle = false;\n workerInfo.workerPromise.then((worker) => {\n action(worker, () => {\n const nextAction = this._pendingActions.shift();\n if (nextAction) {\n this._execute(workerInfo, nextAction);\n }\n else {\n workerInfo.idle = true;\n }\n });\n });\n }\n}\n/**\n * Similar to the WorkerPool class except it creates and destroys workers automatically with a maximum of `maxWorkers` workers.\n * Workers are terminated when it is idle for at least `idleTimeElapsedBeforeRelease` milliseconds.\n */\nexport class AutoReleaseWorkerPool extends WorkerPool {\n constructor(maxWorkers, createWorkerAsync, options = AutoReleaseWorkerPool.DefaultOptions) {\n super([]);\n this._maxWorkers = maxWorkers;\n this._createWorkerAsync = createWorkerAsync;\n this._options = options;\n }\n push(action) {\n if (!this._executeOnIdleWorker(action)) {\n if (this._workerInfos.length < this._maxWorkers) {\n const workerInfo = {\n workerPromise: this._createWorkerAsync(),\n idle: false,\n };\n this._workerInfos.push(workerInfo);\n this._execute(workerInfo, action);\n }\n else {\n this._pendingActions.push(action);\n }\n }\n }\n _execute(workerInfo, action) {\n // Reset the idle timeout.\n if (workerInfo.timeoutId) {\n clearTimeout(workerInfo.timeoutId);\n delete workerInfo.timeoutId;\n }\n super._execute(workerInfo, (worker, onComplete) => {\n action(worker, () => {\n onComplete();\n if (workerInfo.idle) {\n // Schedule the worker to be terminated after the elapsed time.\n workerInfo.timeoutId = setTimeout(() => {\n workerInfo.workerPromise.then((worker) => {\n worker.terminate();\n });\n const indexOf = this._workerInfos.indexOf(workerInfo);\n if (indexOf !== -1) {\n this._workerInfos.splice(indexOf, 1);\n }\n }, this._options.idleTimeElapsedBeforeRelease);\n }\n });\n });\n }\n}\n/**\n * Default options for the constructor.\n * Override to change the defaults.\n */\nAutoReleaseWorkerPool.DefaultOptions = {\n idleTimeElapsedBeforeRelease: 1000,\n};\n//# sourceMappingURL=workerPool.js.map","export var SourceTextureFormat;\n(function (SourceTextureFormat) {\n SourceTextureFormat[SourceTextureFormat[\"ETC1S\"] = 0] = \"ETC1S\";\n SourceTextureFormat[SourceTextureFormat[\"UASTC4x4\"] = 1] = \"UASTC4x4\";\n})(SourceTextureFormat || (SourceTextureFormat = {}));\nexport var TranscodeTarget;\n(function (TranscodeTarget) {\n TranscodeTarget[TranscodeTarget[\"ASTC_4X4_RGBA\"] = 0] = \"ASTC_4X4_RGBA\";\n TranscodeTarget[TranscodeTarget[\"BC7_RGBA\"] = 1] = \"BC7_RGBA\";\n TranscodeTarget[TranscodeTarget[\"BC3_RGBA\"] = 2] = \"BC3_RGBA\";\n TranscodeTarget[TranscodeTarget[\"BC1_RGB\"] = 3] = \"BC1_RGB\";\n TranscodeTarget[TranscodeTarget[\"PVRTC1_4_RGBA\"] = 4] = \"PVRTC1_4_RGBA\";\n TranscodeTarget[TranscodeTarget[\"PVRTC1_4_RGB\"] = 5] = \"PVRTC1_4_RGB\";\n TranscodeTarget[TranscodeTarget[\"ETC2_RGBA\"] = 6] = \"ETC2_RGBA\";\n TranscodeTarget[TranscodeTarget[\"ETC1_RGB\"] = 7] = \"ETC1_RGB\";\n TranscodeTarget[TranscodeTarget[\"RGBA32\"] = 8] = \"RGBA32\";\n TranscodeTarget[TranscodeTarget[\"R8\"] = 9] = \"R8\";\n TranscodeTarget[TranscodeTarget[\"RG8\"] = 10] = \"RG8\";\n})(TranscodeTarget || (TranscodeTarget = {}));\nexport var EngineFormat;\n(function (EngineFormat) {\n EngineFormat[EngineFormat[\"COMPRESSED_RGBA_BPTC_UNORM_EXT\"] = 36492] = \"COMPRESSED_RGBA_BPTC_UNORM_EXT\";\n EngineFormat[EngineFormat[\"COMPRESSED_RGBA_ASTC_4X4_KHR\"] = 37808] = \"COMPRESSED_RGBA_ASTC_4X4_KHR\";\n EngineFormat[EngineFormat[\"COMPRESSED_RGB_S3TC_DXT1_EXT\"] = 33776] = \"COMPRESSED_RGB_S3TC_DXT1_EXT\";\n EngineFormat[EngineFormat[\"COMPRESSED_RGBA_S3TC_DXT5_EXT\"] = 33779] = \"COMPRESSED_RGBA_S3TC_DXT5_EXT\";\n EngineFormat[EngineFormat[\"COMPRESSED_RGBA_PVRTC_4BPPV1_IMG\"] = 35842] = \"COMPRESSED_RGBA_PVRTC_4BPPV1_IMG\";\n EngineFormat[EngineFormat[\"COMPRESSED_RGB_PVRTC_4BPPV1_IMG\"] = 35840] = \"COMPRESSED_RGB_PVRTC_4BPPV1_IMG\";\n EngineFormat[EngineFormat[\"COMPRESSED_RGBA8_ETC2_EAC\"] = 37496] = \"COMPRESSED_RGBA8_ETC2_EAC\";\n EngineFormat[EngineFormat[\"COMPRESSED_RGB8_ETC2\"] = 37492] = \"COMPRESSED_RGB8_ETC2\";\n EngineFormat[EngineFormat[\"COMPRESSED_RGB_ETC1_WEBGL\"] = 36196] = \"COMPRESSED_RGB_ETC1_WEBGL\";\n EngineFormat[EngineFormat[\"RGBA8Format\"] = 32856] = \"RGBA8Format\";\n EngineFormat[EngineFormat[\"R8Format\"] = 33321] = \"R8Format\";\n EngineFormat[EngineFormat[\"RG8Format\"] = 33323] = \"RG8Format\";\n})(EngineFormat || (EngineFormat = {}));\n//# sourceMappingURL=ktx2decoderTypes.js.map","\nimport { AutoReleaseWorkerPool } from \"./workerPool.js\";\nimport { Tools } from \"./tools.js\";\nimport { EngineFormat, TranscodeTarget } from \"../Materials/Textures/ktx2decoderTypes.js\";\nfunction getAbsoluteUrlOrNull(url) {\n return url ? Tools.GetAbsoluteUrl(url) : null;\n}\nfunction applyConfig(urls) {\n if (urls.wasmUASTCToASTC !== null) {\n KTX2DECODER.LiteTranscoder_UASTC_ASTC.WasmModuleURL = urls.wasmUASTCToASTC;\n }\n if (urls.wasmUASTCToBC7 !== null) {\n KTX2DECODER.LiteTranscoder_UASTC_BC7.WasmModuleURL = urls.wasmUASTCToBC7;\n }\n if (urls.wasmUASTCToRGBA_UNORM !== null) {\n KTX2DECODER.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL = urls.wasmUASTCToRGBA_UNORM;\n }\n if (urls.wasmUASTCToRGBA_SRGB !== null) {\n KTX2DECODER.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL = urls.wasmUASTCToRGBA_SRGB;\n }\n if (urls.wasmUASTCToR8_UNORM !== null) {\n KTX2DECODER.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL = urls.wasmUASTCToR8_UNORM;\n }\n if (urls.wasmUASTCToRG8_UNORM !== null) {\n KTX2DECODER.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL = urls.wasmUASTCToRG8_UNORM;\n }\n if (urls.jsMSCTranscoder !== null) {\n KTX2DECODER.MSCTranscoder.JSModuleURL = urls.jsMSCTranscoder;\n }\n if (urls.wasmMSCTranscoder !== null) {\n KTX2DECODER.MSCTranscoder.WasmModuleURL = urls.wasmMSCTranscoder;\n }\n if (urls.wasmZSTDDecoder !== null) {\n KTX2DECODER.ZSTDDecoder.WasmModuleURL = urls.wasmZSTDDecoder;\n }\n}\n/**\n * Class that defines the default KTX2 decoder options.\n *\n * This class is useful for providing options to the KTX2 decoder to control how the source data is transcoded.\n */\nexport class DefaultKTX2DecoderOptions {\n constructor() {\n this._isDirty = true;\n this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC = true;\n this._ktx2DecoderOptions = {};\n }\n /**\n * Gets the dirty flag\n */\n get isDirty() {\n return this._isDirty;\n }\n /**\n * force a (uncompressed) RGBA transcoded format if transcoding a UASTC source format and ASTC + BC7 are not available as a compressed transcoded format\n */\n get useRGBAIfASTCBC7NotAvailableWhenUASTC() {\n return this._useRGBAIfASTCBC7NotAvailableWhenUASTC;\n }\n set useRGBAIfASTCBC7NotAvailableWhenUASTC(value) {\n if (this._useRGBAIfASTCBC7NotAvailableWhenUASTC === value) {\n return;\n }\n this._useRGBAIfASTCBC7NotAvailableWhenUASTC = value;\n this._isDirty = true;\n }\n /**\n * force a (uncompressed) RGBA transcoded format if transcoding a UASTC source format and only BC1 or BC3 are available as a compressed transcoded format.\n * This property is true by default to favor speed over memory, because currently transcoding from UASTC to BC1/3 is slow because the transcoder transcodes\n * to uncompressed and then recompresses the texture\n */\n get useRGBAIfOnlyBC1BC3AvailableWhenUASTC() {\n return this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC;\n }\n set useRGBAIfOnlyBC1BC3AvailableWhenUASTC(value) {\n if (this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC === value) {\n return;\n }\n this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC = value;\n this._isDirty = true;\n }\n /**\n * force to always use (uncompressed) RGBA for transcoded format\n */\n get forceRGBA() {\n return this._forceRGBA;\n }\n set forceRGBA(value) {\n if (this._forceRGBA === value) {\n return;\n }\n this._forceRGBA = value;\n this._isDirty = true;\n }\n /**\n * force to always use (uncompressed) R8 for transcoded format\n */\n get forceR8() {\n return this._forceR8;\n }\n set forceR8(value) {\n if (this._forceR8 === value) {\n return;\n }\n this._forceR8 = value;\n this._isDirty = true;\n }\n /**\n * force to always use (uncompressed) RG8 for transcoded format\n */\n get forceRG8() {\n return this._forceRG8;\n }\n set forceRG8(value) {\n if (this._forceRG8 === value) {\n return;\n }\n this._forceRG8 = value;\n this._isDirty = true;\n }\n /**\n * list of transcoders to bypass when looking for a suitable transcoder. The available transcoders are:\n * UniversalTranscoder_UASTC_ASTC\n * UniversalTranscoder_UASTC_BC7\n * UniversalTranscoder_UASTC_RGBA_UNORM\n * UniversalTranscoder_UASTC_RGBA_SRGB\n * UniversalTranscoder_UASTC_R8_UNORM\n * UniversalTranscoder_UASTC_RG8_UNORM\n * MSCTranscoder\n */\n get bypassTranscoders() {\n return this._bypassTranscoders;\n }\n set bypassTranscoders(value) {\n if (this._bypassTranscoders === value) {\n return;\n }\n this._bypassTranscoders = value;\n this._isDirty = true;\n }\n /** @internal */\n _getKTX2DecoderOptions() {\n if (!this._isDirty) {\n return this._ktx2DecoderOptions;\n }\n this._isDirty = false;\n const options = {\n useRGBAIfASTCBC7NotAvailableWhenUASTC: this._useRGBAIfASTCBC7NotAvailableWhenUASTC,\n forceRGBA: this._forceRGBA,\n forceR8: this._forceR8,\n forceRG8: this._forceRG8,\n bypassTranscoders: this._bypassTranscoders,\n };\n if (this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC) {\n options.transcodeFormatDecisionTree = {\n UASTC: {\n transcodeFormat: [TranscodeTarget.BC1_RGB, TranscodeTarget.BC3_RGBA],\n yes: {\n transcodeFormat: TranscodeTarget.RGBA32,\n engineFormat: EngineFormat.RGBA8Format,\n roundToMultiple4: false,\n },\n },\n };\n }\n this._ktx2DecoderOptions = options;\n return options;\n }\n}\n/**\n * Class for loading KTX2 files\n */\nexport class KhronosTextureContainer2 {\n static GetDefaultNumWorkers() {\n if (typeof navigator !== \"object\" || !navigator.hardwareConcurrency) {\n return 1;\n }\n // Use 50% of the available logical processors but capped at 4.\n return Math.min(Math.floor(navigator.hardwareConcurrency * 0.5), 4);\n }\n static _Initialize(numWorkers) {\n if (KhronosTextureContainer2._WorkerPoolPromise || KhronosTextureContainer2._DecoderModulePromise) {\n return;\n }\n const urls = {\n jsDecoderModule: Tools.GetAbsoluteUrl(this.URLConfig.jsDecoderModule),\n wasmUASTCToASTC: getAbsoluteUrlOrNull(this.URLConfig.wasmUASTCToASTC),\n wasmUASTCToBC7: getAbsoluteUrlOrNull(this.URLConfig.wasmUASTCToBC7),\n wasmUASTCToRGBA_UNORM: getAbsoluteUrlOrNull(this.URLConfig.wasmUASTCToRGBA_UNORM),\n wasmUASTCToRGBA_SRGB: getAbsoluteUrlOrNull(this.URLConfig.wasmUASTCToRGBA_SRGB),\n wasmUASTCToR8_UNORM: getAbsoluteUrlOrNull(this.URLConfig.wasmUASTCToR8_UNORM),\n wasmUASTCToRG8_UNORM: getAbsoluteUrlOrNull(this.URLConfig.wasmUASTCToRG8_UNORM),\n jsMSCTranscoder: getAbsoluteUrlOrNull(this.URLConfig.jsMSCTranscoder),\n wasmMSCTranscoder: getAbsoluteUrlOrNull(this.URLConfig.wasmMSCTranscoder),\n wasmZSTDDecoder: getAbsoluteUrlOrNull(this.URLConfig.wasmZSTDDecoder),\n };\n if (numWorkers && typeof Worker === \"function\" && typeof URL !== \"undefined\") {\n KhronosTextureContainer2._WorkerPoolPromise = new Promise((resolve) => {\n const workerContent = `${applyConfig}(${workerFunc})()`;\n const workerBlobUrl = URL.createObjectURL(new Blob([workerContent], { type: \"application/javascript\" }));\n resolve(new AutoReleaseWorkerPool(numWorkers, () => new Promise((resolve, reject) => {\n const worker = new Worker(workerBlobUrl);\n const onError = (error) => {\n worker.removeEventListener(\"error\", onError);\n worker.removeEventListener(\"message\", onMessage);\n reject(error);\n };\n const onMessage = (message) => {\n if (message.data.action === \"init\") {\n worker.removeEventListener(\"error\", onError);\n worker.removeEventListener(\"message\", onMessage);\n resolve(worker);\n }\n };\n worker.addEventListener(\"error\", onError);\n worker.addEventListener(\"message\", onMessage);\n worker.postMessage({\n action: \"init\",\n urls: urls,\n });\n })));\n });\n }\n else if (typeof KTX2DECODER === \"undefined\") {\n KhronosTextureContainer2._DecoderModulePromise = Tools.LoadScriptAsync(urls.jsDecoderModule).then(() => {\n KTX2DECODER.MSCTranscoder.UseFromWorkerThread = false;\n KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread = true;\n applyConfig(urls);\n return new KTX2DECODER.KTX2Decoder();\n });\n }\n else {\n KTX2DECODER.MSCTranscoder.UseFromWorkerThread = false;\n KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread = true;\n KhronosTextureContainer2._DecoderModulePromise = Promise.resolve(new KTX2DECODER.KTX2Decoder());\n }\n }\n /**\n * Constructor\n * @param engine The engine to use\n * @param numWorkers The number of workers for async operations. Specify `0` to disable web workers and run synchronously in the current context.\n */\n constructor(engine, numWorkers = KhronosTextureContainer2.DefaultNumWorkers) {\n this._engine = engine;\n KhronosTextureContainer2._Initialize(numWorkers);\n }\n /**\n * @internal\n */\n uploadAsync(data, internalTexture, options) {\n const caps = this._engine.getCaps();\n const compressedTexturesCaps = {\n astc: !!caps.astc,\n bptc: !!caps.bptc,\n s3tc: !!caps.s3tc,\n pvrtc: !!caps.pvrtc,\n etc2: !!caps.etc2,\n etc1: !!caps.etc1,\n };\n if (KhronosTextureContainer2._WorkerPoolPromise) {\n return KhronosTextureContainer2._WorkerPoolPromise.then((workerPool) => {\n return new Promise((resolve, reject) => {\n workerPool.push((worker, onComplete) => {\n const onError = (error) => {\n worker.removeEventListener(\"error\", onError);\n worker.removeEventListener(\"message\", onMessage);\n reject(error);\n onComplete();\n };\n const onMessage = (message) => {\n if (message.data.action === \"decoded\") {\n worker.removeEventListener(\"error\", onError);\n worker.removeEventListener(\"message\", onMessage);\n if (!message.data.success) {\n reject({ message: message.data.msg });\n }\n else {\n try {\n this._createTexture(message.data.decodedData, internalTexture, options);\n resolve();\n }\n catch (err) {\n reject({ message: err });\n }\n }\n onComplete();\n }\n };\n worker.addEventListener(\"error\", onError);\n worker.addEventListener(\"message\", onMessage);\n worker.postMessage({ action: \"setDefaultDecoderOptions\", options: KhronosTextureContainer2.DefaultDecoderOptions._getKTX2DecoderOptions() });\n const dataCopy = new Uint8Array(data.byteLength);\n dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));\n worker.postMessage({ action: \"decode\", data: dataCopy, caps: compressedTexturesCaps, options }, [dataCopy.buffer]);\n });\n });\n });\n }\n else if (KhronosTextureContainer2._DecoderModulePromise) {\n return KhronosTextureContainer2._DecoderModulePromise.then((decoder) => {\n if (KhronosTextureContainer2.DefaultDecoderOptions.isDirty) {\n KTX2DECODER.KTX2Decoder.DefaultDecoderOptions = KhronosTextureContainer2.DefaultDecoderOptions._getKTX2DecoderOptions();\n }\n return new Promise((resolve, reject) => {\n decoder\n .decode(data, caps)\n .then((data) => {\n this._createTexture(data, internalTexture);\n resolve();\n })\n .catch((reason) => {\n reject({ message: reason });\n });\n });\n });\n }\n throw new Error(\"KTX2 decoder module is not available\");\n }\n _createTexture(data, internalTexture, options) {\n const oglTexture2D = 3553; // gl.TEXTURE_2D\n this._engine._bindTextureDirectly(oglTexture2D, internalTexture);\n if (options) {\n // return back some information about the decoded data\n options.transcodedFormat = data.transcodedFormat;\n options.isInGammaSpace = data.isInGammaSpace;\n options.hasAlpha = data.hasAlpha;\n options.transcoderName = data.transcoderName;\n }\n let isUncompressedFormat = true;\n switch (data.transcodedFormat) {\n case 0x8058 /* RGBA8 */:\n internalTexture.type = 0;\n internalTexture.format = 5;\n break;\n case 0x8229 /* R8 */:\n internalTexture.type = 0;\n internalTexture.format = 6;\n break;\n case 0x822b /* RG8 */:\n internalTexture.type = 0;\n internalTexture.format = 7;\n break;\n default:\n internalTexture.format = data.transcodedFormat;\n isUncompressedFormat = false;\n break;\n }\n internalTexture._gammaSpace = data.isInGammaSpace;\n internalTexture.generateMipMaps = data.mipmaps.length > 1;\n if (data.errors) {\n throw new Error(\"KTX2 container - could not transcode the data. \" + data.errors);\n }\n for (let t = 0; t < data.mipmaps.length; ++t) {\n const mipmap = data.mipmaps[t];\n if (!mipmap || !mipmap.data) {\n throw new Error(\"KTX2 container - could not transcode one of the image\");\n }\n if (isUncompressedFormat) {\n // uncompressed RGBA / R8 / RG8\n internalTexture.width = mipmap.width; // need to set width/height so that the call to _uploadDataToTextureDirectly uses the right dimensions\n internalTexture.height = mipmap.height;\n this._engine._uploadDataToTextureDirectly(internalTexture, mipmap.data, 0, t, undefined, true);\n }\n else {\n this._engine._uploadCompressedDataToTextureDirectly(internalTexture, data.transcodedFormat, mipmap.width, mipmap.height, mipmap.data, 0, t);\n }\n }\n internalTexture._extension = \".ktx2\";\n internalTexture.width = data.mipmaps[0].width;\n internalTexture.height = data.mipmaps[0].height;\n internalTexture.isReady = true;\n this._engine._bindTextureDirectly(oglTexture2D, null);\n }\n /**\n * Checks if the given data starts with a KTX2 file identifier.\n * @param data the data to check\n * @returns true if the data is a KTX2 file or false otherwise\n */\n static IsValid(data) {\n if (data.byteLength >= 12) {\n // '«', 'K', 'T', 'X', ' ', '2', '0', '»', '\\r', '\\n', '\\x1A', '\\n'\n const identifier = new Uint8Array(data.buffer, data.byteOffset, 12);\n if (identifier[0] === 0xab &&\n identifier[1] === 0x4b &&\n identifier[2] === 0x54 &&\n identifier[3] === 0x58 &&\n identifier[4] === 0x20 &&\n identifier[5] === 0x32 &&\n identifier[6] === 0x30 &&\n identifier[7] === 0xbb &&\n identifier[8] === 0x0d &&\n identifier[9] === 0x0a &&\n identifier[10] === 0x1a &&\n identifier[11] === 0x0a) {\n return true;\n }\n }\n return false;\n }\n}\n/**\n * URLs to use when loading the KTX2 decoder module as well as its dependencies\n * If a url is null, the default url is used (pointing to https://preview.babylonjs.com)\n * Note that jsDecoderModule can't be null and that the other dependencies will only be loaded if necessary\n * Urls you can change:\n * URLConfig.jsDecoderModule\n * URLConfig.wasmUASTCToASTC\n * URLConfig.wasmUASTCToBC7\n * URLConfig.wasmUASTCToRGBA_UNORM\n * URLConfig.wasmUASTCToRGBA_SRGB\n * URLConfig.wasmUASTCToR8_UNORM\n * URLConfig.wasmUASTCToRG8_UNORM\n * URLConfig.jsMSCTranscoder\n * URLConfig.wasmMSCTranscoder\n * URLConfig.wasmZSTDDecoder\n * You can see their default values in this PG: https://playground.babylonjs.com/#EIJH8L#29\n */\nKhronosTextureContainer2.URLConfig = {\n jsDecoderModule: \"https://preview.babylonjs.com/babylon.ktx2Decoder.js\",\n wasmUASTCToASTC: null,\n wasmUASTCToBC7: null,\n wasmUASTCToRGBA_UNORM: null,\n wasmUASTCToRGBA_SRGB: null,\n wasmUASTCToR8_UNORM: null,\n wasmUASTCToRG8_UNORM: null,\n jsMSCTranscoder: null,\n wasmMSCTranscoder: null,\n wasmZSTDDecoder: null,\n};\n/**\n * Default number of workers used to handle data decoding\n */\nKhronosTextureContainer2.DefaultNumWorkers = KhronosTextureContainer2.GetDefaultNumWorkers();\n/**\n * Default configuration for the KTX2 decoder.\n * The options defined in this way have priority over those passed when creating a KTX2 texture with new Texture(...).\n */\nKhronosTextureContainer2.DefaultDecoderOptions = new DefaultKTX2DecoderOptions();\nfunction workerFunc() {\n let ktx2Decoder;\n onmessage = (event) => {\n if (!event.data) {\n return;\n }\n switch (event.data.action) {\n case \"init\": {\n const urls = event.data.urls;\n importScripts(urls.jsDecoderModule);\n applyConfig(urls);\n ktx2Decoder = new KTX2DECODER.KTX2Decoder();\n postMessage({ action: \"init\" });\n break;\n }\n case \"setDefaultDecoderOptions\": {\n KTX2DECODER.KTX2Decoder.DefaultDecoderOptions = event.data.options;\n break;\n }\n case \"decode\":\n ktx2Decoder\n .decode(event.data.data, event.data.caps, event.data.options)\n .then((data) => {\n const buffers = [];\n for (let mip = 0; mip < data.mipmaps.length; ++mip) {\n const mipmap = data.mipmaps[mip];\n if (mipmap && mipmap.data) {\n buffers.push(mipmap.data.buffer);\n }\n }\n postMessage({ action: \"decoded\", success: true, decodedData: data }, buffers);\n })\n .catch((reason) => {\n postMessage({ action: \"decoded\", success: false, msg: reason });\n });\n break;\n }\n };\n}\n//# sourceMappingURL=khronosTextureContainer2.js.map","import { KhronosTextureContainer } from \"../../../Misc/khronosTextureContainer.js\";\nimport { KhronosTextureContainer2 } from \"../../../Misc/khronosTextureContainer2.js\";\nimport { Engine } from \"../../../Engines/engine.js\";\nimport { Logger } from \"../../../Misc/logger.js\";\n\nfunction mapSRGBToLinear(format) {\n switch (format) {\n case 35916:\n return 33776;\n case 35918:\n return 33778;\n case 35919:\n return 33779;\n case 37493:\n return 37492;\n case 37497:\n return 37496;\n case 37495:\n return 37494;\n case 37840:\n return 37808;\n case 36493:\n return 36492;\n }\n return null;\n}\n/**\n * Implementation of the KTX Texture Loader.\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class _KTXTextureLoader {\n constructor() {\n /**\n * Defines whether the loader supports cascade loading the different faces.\n */\n this.supportCascades = false;\n }\n /**\n * This returns if the loader support the current file information.\n * @param extension defines the file extension of the file being loaded\n * @param mimeType defines the optional mime type of the file being loaded\n * @returns true if the loader can load the specified file\n */\n canLoad(extension, mimeType) {\n // The \".ktx2\" file extension is still up for debate: https://github.com/KhronosGroup/KTX-Specification/issues/18\n return extension.endsWith(\".ktx\") || extension.endsWith(\".ktx2\") || mimeType === \"image/ktx\" || mimeType === \"image/ktx2\";\n }\n /**\n * Uploads the cube texture data to the WebGL texture. It has already been bound.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param createPolynomials will be true if polynomials have been requested\n * @param onLoad defines the callback to trigger once the texture is ready\n */\n loadCubeData(data, texture, createPolynomials, onLoad) {\n if (Array.isArray(data)) {\n return;\n }\n // Need to invert vScale as invertY via UNPACK_FLIP_Y_WEBGL is not supported by compressed texture\n texture._invertVScale = !texture.invertY;\n const engine = texture.getEngine();\n const ktx = new KhronosTextureContainer(data, 6);\n const loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;\n engine._unpackFlipY(true);\n ktx.uploadLevels(texture, texture.generateMipMaps);\n texture.width = ktx.pixelWidth;\n texture.height = ktx.pixelHeight;\n engine._setCubeMapTextureParams(texture, loadMipmap, ktx.numberOfMipmapLevels - 1);\n texture.isReady = true;\n texture.onLoadedObservable.notifyObservers(texture);\n texture.onLoadedObservable.clear();\n if (onLoad) {\n onLoad();\n }\n }\n /**\n * Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param callback defines the method to call once ready to upload\n * @param options\n */\n loadData(data, texture, callback, options) {\n if (KhronosTextureContainer.IsValid(data)) {\n // Need to invert vScale as invertY via UNPACK_FLIP_Y_WEBGL is not supported by compressed texture\n texture._invertVScale = !texture.invertY;\n const ktx = new KhronosTextureContainer(data, 1);\n const mappedFormat = mapSRGBToLinear(ktx.glInternalFormat);\n if (mappedFormat) {\n texture.format = mappedFormat;\n texture._useSRGBBuffer = texture.getEngine()._getUseSRGBBuffer(true, texture.generateMipMaps);\n texture._gammaSpace = true;\n }\n else {\n texture.format = ktx.glInternalFormat;\n }\n callback(ktx.pixelWidth, ktx.pixelHeight, texture.generateMipMaps, true, () => {\n ktx.uploadLevels(texture, texture.generateMipMaps);\n }, ktx.isInvalid);\n }\n else if (KhronosTextureContainer2.IsValid(data)) {\n const ktx2 = new KhronosTextureContainer2(texture.getEngine());\n ktx2.uploadAsync(data, texture, options).then(() => {\n callback(texture.width, texture.height, texture.generateMipMaps, true, () => { }, false);\n }, (error) => {\n Logger.Warn(`Failed to load KTX2 texture data: ${error.message}`);\n callback(0, 0, false, false, () => { }, true);\n });\n }\n else {\n Logger.Error(\"texture missing KTX identifier\");\n callback(0, 0, false, false, () => { }, true);\n }\n }\n}\n// Register the loader.\nEngine._TextureLoaders.unshift(new _KTXTextureLoader());\n//# sourceMappingURL=ktxTextureLoader.js.map","import { Vector3, Matrix, Quaternion, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Camera } from \"../Cameras/camera.js\";\nimport { FreeCamera } from \"../Cameras/freeCamera.js\";\nimport { TargetCamera } from \"../Cameras/targetCamera.js\";\nimport { Viewport } from \"../Maths/math.viewport.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { WebXRTrackingState } from \"./webXRTypes.js\";\n/**\n * WebXR Camera which holds the views for the xrSession\n * @see https://doc.babylonjs.com/features/featuresDeepDive/webXR/webXRCamera\n */\nexport class WebXRCamera extends FreeCamera {\n /**\n * Creates a new webXRCamera, this should only be set at the camera after it has been updated by the xrSessionManager\n * @param name the name of the camera\n * @param scene the scene to add the camera to\n * @param _xrSessionManager a constructed xr session manager\n */\n constructor(name, scene, _xrSessionManager) {\n super(name, Vector3.Zero(), scene);\n this._xrSessionManager = _xrSessionManager;\n this._firstFrame = false;\n this._referenceQuaternion = Quaternion.Identity();\n this._referencedPosition = new Vector3();\n this._trackingState = WebXRTrackingState.NOT_TRACKING;\n /**\n * Observable raised before camera teleportation\n */\n this.onBeforeCameraTeleport = new Observable();\n /**\n * Observable raised after camera teleportation\n */\n this.onAfterCameraTeleport = new Observable();\n /**\n * Notifies when the camera's tracking state has changed.\n * Notice - will also be triggered when tracking has started (at the beginning of the session)\n */\n this.onTrackingStateChanged = new Observable();\n /**\n * Should position compensation execute on first frame.\n * This is used when copying the position from a native (non XR) camera\n */\n this.compensateOnFirstFrame = true;\n this._rotate180 = new Quaternion(0, 1, 0, 0);\n // Initial camera configuration\n this.minZ = 0.1;\n this.rotationQuaternion = new Quaternion();\n this.cameraRigMode = Camera.RIG_MODE_CUSTOM;\n this.updateUpVectorFromRotation = true;\n this._updateNumberOfRigCameras(1);\n // freeze projection matrix, which will be copied later\n this.freezeProjectionMatrix();\n this._xrSessionManager.onXRSessionInit.add(() => {\n this._referencedPosition.copyFromFloats(0, 0, 0);\n this._referenceQuaternion.copyFromFloats(0, 0, 0, 1);\n // first frame - camera's y position should be 0 for the correct offset\n this._firstFrame = this.compensateOnFirstFrame;\n });\n // Check transformation changes on each frame. Callback is added to be first so that the transformation will be\n // applied to the rest of the elements using the referenceSpace object\n this._xrSessionManager.onXRFrameObservable.add(() => {\n if (this._firstFrame) {\n this._updateFromXRSession();\n }\n this._updateReferenceSpace();\n this._updateFromXRSession();\n }, undefined, true);\n }\n /**\n * Get the current XR tracking state of the camera\n */\n get trackingState() {\n return this._trackingState;\n }\n _setTrackingState(newState) {\n if (this._trackingState !== newState) {\n this._trackingState = newState;\n this.onTrackingStateChanged.notifyObservers(newState);\n }\n }\n /**\n * Return the user's height, unrelated to the current ground.\n * This will be the y position of this camera, when ground level is 0.\n */\n get realWorldHeight() {\n const basePose = this._xrSessionManager.currentFrame && this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace);\n if (basePose && basePose.transform) {\n return basePose.transform.position.y;\n }\n else {\n return 0;\n }\n }\n /** @internal */\n _updateForDualEyeDebugging( /*pupilDistance = 0.01*/) {\n // Create initial camera rigs\n this._updateNumberOfRigCameras(2);\n this.rigCameras[0].viewport = new Viewport(0, 0, 0.5, 1.0);\n // this.rigCameras[0].position.x = -pupilDistance / 2;\n this.rigCameras[0].outputRenderTarget = null;\n this.rigCameras[1].viewport = new Viewport(0.5, 0, 0.5, 1.0);\n // this.rigCameras[1].position.x = pupilDistance / 2;\n this.rigCameras[1].outputRenderTarget = null;\n }\n /**\n * Sets this camera's transformation based on a non-vr camera\n * @param otherCamera the non-vr camera to copy the transformation from\n * @param resetToBaseReferenceSpace should XR reset to the base reference space\n */\n setTransformationFromNonVRCamera(otherCamera = this.getScene().activeCamera, resetToBaseReferenceSpace = true) {\n if (!otherCamera || otherCamera === this) {\n return;\n }\n const mat = otherCamera.computeWorldMatrix();\n mat.decompose(undefined, this.rotationQuaternion, this.position);\n // set the ground level\n this.position.y = 0;\n Quaternion.FromEulerAnglesToRef(0, this.rotationQuaternion.toEulerAngles().y, 0, this.rotationQuaternion);\n this._firstFrame = true;\n if (resetToBaseReferenceSpace) {\n this._xrSessionManager.resetReferenceSpace();\n }\n }\n /**\n * Gets the current instance class name (\"WebXRCamera\").\n * @returns the class name\n */\n getClassName() {\n return \"WebXRCamera\";\n }\n /**\n * Set the target for the camera to look at.\n * Note that this only rotates around the Y axis, as opposed to the default behavior of other cameras\n * @param target the target to set the camera to look at\n */\n setTarget(target) {\n // only rotate around the y axis!\n const tmpVector = TmpVectors.Vector3[1];\n target.subtractToRef(this.position, tmpVector);\n tmpVector.y = 0;\n tmpVector.normalize();\n const yRotation = Math.atan2(tmpVector.x, tmpVector.z);\n this.rotationQuaternion.toEulerAnglesToRef(tmpVector);\n Quaternion.FromEulerAnglesToRef(tmpVector.x, yRotation, tmpVector.z, this.rotationQuaternion);\n }\n dispose() {\n super.dispose();\n this._lastXRViewerPose = undefined;\n }\n _updateFromXRSession() {\n const pose = this._xrSessionManager.currentFrame && this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);\n this._lastXRViewerPose = pose || undefined;\n if (!pose) {\n this._setTrackingState(WebXRTrackingState.NOT_TRACKING);\n return;\n }\n // Set the tracking state. if it didn't change it is a no-op\n const trackingState = pose.emulatedPosition ? WebXRTrackingState.TRACKING_LOST : WebXRTrackingState.TRACKING;\n this._setTrackingState(trackingState);\n // check min/max Z and update if not the same as in cache\n if (this.minZ !== this._cache.minZ || this.maxZ !== this._cache.maxZ) {\n const xrRenderState = {\n // if maxZ is 0 it should be \"Infinity\", but it doesn't work with the WebXR API. Setting to a large number.\n depthFar: this.maxZ || 10000,\n depthNear: this.minZ,\n };\n this._xrSessionManager.updateRenderState(xrRenderState);\n this._cache.minZ = this.minZ;\n this._cache.maxZ = this.maxZ;\n }\n if (pose.transform) {\n const orientation = pose.transform.orientation;\n if (pose.transform.orientation.x === undefined) {\n // Babylon native polyfill can return an undefined orientation value\n // When not initialized\n return;\n }\n const pos = pose.transform.position;\n this._referencedPosition.set(pos.x, pos.y, pos.z);\n this._referenceQuaternion.set(orientation.x, orientation.y, orientation.z, orientation.w);\n if (!this._scene.useRightHandedSystem) {\n this._referencedPosition.z *= -1;\n this._referenceQuaternion.z *= -1;\n this._referenceQuaternion.w *= -1;\n }\n if (this._firstFrame) {\n this._firstFrame = false;\n // we have the XR reference, now use this to find the offset to get the camera to be\n // in the right position\n // set the height to correlate to the current height\n this.position.y += this._referencedPosition.y;\n // avoid using the head rotation on the first frame.\n this._referenceQuaternion.copyFromFloats(0, 0, 0, 1);\n }\n else {\n // update position and rotation as reference\n this.rotationQuaternion.copyFrom(this._referenceQuaternion);\n this.position.copyFrom(this._referencedPosition);\n }\n }\n // Update camera rigs\n if (this.rigCameras.length !== pose.views.length) {\n this._updateNumberOfRigCameras(pose.views.length);\n }\n pose.views.forEach((view, i) => {\n var _a;\n const currentRig = this.rigCameras[i];\n // update right and left, where applicable\n if (!currentRig.isLeftCamera && !currentRig.isRightCamera) {\n if (view.eye === \"right\") {\n currentRig._isRightCamera = true;\n }\n else if (view.eye === \"left\") {\n currentRig._isLeftCamera = true;\n }\n }\n // Update view/projection matrix\n const pos = view.transform.position;\n const orientation = view.transform.orientation;\n currentRig.parent = this.parent;\n currentRig.position.set(pos.x, pos.y, pos.z);\n currentRig.rotationQuaternion.set(orientation.x, orientation.y, orientation.z, orientation.w);\n if (!this._scene.useRightHandedSystem) {\n currentRig.position.z *= -1;\n currentRig.rotationQuaternion.z *= -1;\n currentRig.rotationQuaternion.w *= -1;\n }\n else {\n currentRig.rotationQuaternion.multiplyInPlace(this._rotate180);\n }\n Matrix.FromFloat32ArrayToRefScaled(view.projectionMatrix, 0, 1, currentRig._projectionMatrix);\n if (!this._scene.useRightHandedSystem) {\n currentRig._projectionMatrix.toggleProjectionMatrixHandInPlace();\n }\n // first camera?\n if (i === 0) {\n this._projectionMatrix.copyFrom(currentRig._projectionMatrix);\n }\n const renderTargetTexture = this._xrSessionManager.getRenderTargetTextureForView(view);\n this._renderingMultiview = ((_a = renderTargetTexture === null || renderTargetTexture === void 0 ? void 0 : renderTargetTexture._texture) === null || _a === void 0 ? void 0 : _a.isMultiview) || false;\n if (this._renderingMultiview) {\n // For multiview, the render target texture is the same per-view (just the slice index is different),\n // so we only need to set the output render target once for the rig parent.\n if (i == 0) {\n this._xrSessionManager.trySetViewportForView(this.viewport, view);\n this.outputRenderTarget = renderTargetTexture;\n }\n }\n else {\n // Update viewport\n this._xrSessionManager.trySetViewportForView(currentRig.viewport, view);\n // Set cameras to render to the session's render target\n currentRig.outputRenderTarget = renderTargetTexture || this._xrSessionManager.getRenderTargetTextureForView(view);\n }\n // Replicate parent rig camera behavior\n currentRig.layerMask = this.layerMask;\n });\n }\n _updateNumberOfRigCameras(viewCount = 1) {\n while (this.rigCameras.length < viewCount) {\n const newCamera = new TargetCamera(\"XR-RigCamera: \" + this.rigCameras.length, Vector3.Zero(), this.getScene());\n newCamera.minZ = 0.1;\n newCamera.rotationQuaternion = new Quaternion();\n newCamera.updateUpVectorFromRotation = true;\n newCamera.isRigCamera = true;\n newCamera.rigParent = this;\n // do not compute projection matrix, provided by XR\n newCamera.freezeProjectionMatrix();\n this.rigCameras.push(newCamera);\n }\n while (this.rigCameras.length > viewCount) {\n const removedCamera = this.rigCameras.pop();\n if (removedCamera) {\n removedCamera.dispose();\n }\n }\n }\n _updateReferenceSpace() {\n // were position & rotation updated OUTSIDE of the xr update loop\n if (!this.position.equals(this._referencedPosition) || !this.rotationQuaternion.equals(this._referenceQuaternion)) {\n const referencedMat = TmpVectors.Matrix[0];\n const poseMat = TmpVectors.Matrix[1];\n const transformMat = TmpVectors.Matrix[2];\n Matrix.ComposeToRef(WebXRCamera._ScaleReadOnly, this._referenceQuaternion, this._referencedPosition, referencedMat);\n Matrix.ComposeToRef(WebXRCamera._ScaleReadOnly, this.rotationQuaternion, this.position, poseMat);\n referencedMat.invert().multiplyToRef(poseMat, transformMat);\n transformMat.invert();\n if (!this._scene.useRightHandedSystem) {\n transformMat.toggleModelMatrixHandInPlace();\n }\n transformMat.decompose(undefined, this._referenceQuaternion, this._referencedPosition);\n const transform = new XRRigidTransform({\n x: this._referencedPosition.x,\n y: this._referencedPosition.y,\n z: this._referencedPosition.z,\n }, {\n x: this._referenceQuaternion.x,\n y: this._referenceQuaternion.y,\n z: this._referenceQuaternion.z,\n w: this._referenceQuaternion.w,\n });\n this._xrSessionManager.referenceSpace = this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(transform);\n }\n }\n}\nWebXRCamera._ScaleReadOnly = Vector3.One();\n//# sourceMappingURL=webXRCamera.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { WebXRSessionManager } from \"./webXRSessionManager.js\";\nimport { WebXRCamera } from \"./webXRCamera.js\";\nimport { WebXRState } from \"./webXRTypes.js\";\nimport { WebXRFeatureName, WebXRFeaturesManager } from \"./webXRFeaturesManager.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { UniversalCamera } from \"../Cameras/universalCamera.js\";\nimport { Quaternion, Vector3 } from \"../Maths/math.vector.js\";\n/**\n * Base set of functionality needed to create an XR experience (WebXRSessionManager, Camera, StateManagement, etc.)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/webXR/webXRExperienceHelpers\n */\nexport class WebXRExperienceHelper {\n /**\n * Creates a WebXRExperienceHelper\n * @param _scene The scene the helper should be created in\n */\n constructor(_scene) {\n this._scene = _scene;\n this._nonVRCamera = null;\n this._attachedToElement = false;\n this._spectatorCamera = null;\n this._originalSceneAutoClear = true;\n this._supported = false;\n this._spectatorMode = false;\n this._lastTimestamp = 0;\n /**\n * Observers registered here will be triggered after the camera's initial transformation is set\n * This can be used to set a different ground level or an extra rotation.\n *\n * Note that ground level is considered to be at 0. The height defined by the XR camera will be added\n * to the position set after this observable is done executing.\n */\n this.onInitialXRPoseSetObservable = new Observable();\n /**\n * Fires when the state of the experience helper has changed\n */\n this.onStateChangedObservable = new Observable();\n /**\n * The current state of the XR experience (eg. transitioning, in XR or not in XR)\n */\n this.state = WebXRState.NOT_IN_XR;\n this.sessionManager = new WebXRSessionManager(_scene);\n this.camera = new WebXRCamera(\"webxr\", _scene, this.sessionManager);\n this.featuresManager = new WebXRFeaturesManager(this.sessionManager);\n _scene.onDisposeObservable.addOnce(() => {\n this.dispose();\n });\n }\n /**\n * Creates the experience helper\n * @param scene the scene to attach the experience helper to\n * @returns a promise for the experience helper\n */\n static CreateAsync(scene) {\n const helper = new WebXRExperienceHelper(scene);\n return helper.sessionManager\n .initializeAsync()\n .then(() => {\n helper._supported = true;\n return helper;\n })\n .catch((e) => {\n helper._setState(WebXRState.NOT_IN_XR);\n helper.dispose();\n throw e;\n });\n }\n /**\n * Disposes of the experience helper\n */\n dispose() {\n var _a;\n this.exitXRAsync();\n this.camera.dispose();\n this.onStateChangedObservable.clear();\n this.onInitialXRPoseSetObservable.clear();\n this.sessionManager.dispose();\n (_a = this._spectatorCamera) === null || _a === void 0 ? void 0 : _a.dispose();\n if (this._nonVRCamera) {\n this._scene.activeCamera = this._nonVRCamera;\n }\n }\n /**\n * Enters XR mode (This must be done within a user interaction in most browsers eg. button click)\n * @param sessionMode options for the XR session\n * @param referenceSpaceType frame of reference of the XR session\n * @param renderTarget the output canvas that will be used to enter XR mode\n * @param sessionCreationOptions optional XRSessionInit object to init the session with\n * @returns promise that resolves after xr mode has entered\n */\n async enterXRAsync(sessionMode, referenceSpaceType, renderTarget = this.sessionManager.getWebXRRenderTarget(), sessionCreationOptions = {}) {\n var _a, _b, _c;\n if (!this._supported) {\n throw \"WebXR not supported in this browser or environment\";\n }\n this._setState(WebXRState.ENTERING_XR);\n if (referenceSpaceType !== \"viewer\" && referenceSpaceType !== \"local\") {\n sessionCreationOptions.optionalFeatures = sessionCreationOptions.optionalFeatures || [];\n sessionCreationOptions.optionalFeatures.push(referenceSpaceType);\n }\n sessionCreationOptions = await this.featuresManager._extendXRSessionInitObject(sessionCreationOptions);\n // we currently recommend \"unbounded\" space in AR (#7959)\n if (sessionMode === \"immersive-ar\" && referenceSpaceType !== \"unbounded\") {\n Logger.Warn(\"We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode\");\n }\n // make sure that the session mode is supported\n try {\n await this.sessionManager.initializeSessionAsync(sessionMode, sessionCreationOptions);\n await this.sessionManager.setReferenceSpaceTypeAsync(referenceSpaceType);\n const baseLayer = await renderTarget.initializeXRLayerAsync(this.sessionManager.session);\n const xrRenderState = {\n // if maxZ is 0 it should be \"Infinity\", but it doesn't work with the WebXR API. Setting to a large number.\n depthFar: this.camera.maxZ || 10000,\n depthNear: this.camera.minZ,\n };\n // The layers feature will have already initialized the xr session's layers on session init.\n if (!this.featuresManager.getEnabledFeature(WebXRFeatureName.LAYERS)) {\n xrRenderState.baseLayer = baseLayer;\n }\n this.sessionManager.updateRenderState(xrRenderState);\n // run the render loop\n this.sessionManager.runXRRenderLoop();\n // Cache pre xr scene settings\n this._originalSceneAutoClear = this._scene.autoClear;\n this._nonVRCamera = this._scene.activeCamera;\n this._attachedToElement = !!((_b = (_a = this._nonVRCamera) === null || _a === void 0 ? void 0 : _a.inputs) === null || _b === void 0 ? void 0 : _b.attachedToElement);\n (_c = this._nonVRCamera) === null || _c === void 0 ? void 0 : _c.detachControl();\n this._scene.activeCamera = this.camera;\n // do not compensate when AR session is used\n if (sessionMode !== \"immersive-ar\") {\n this._nonXRToXRCamera();\n }\n else {\n // Kept here, TODO - check if needed\n this._scene.autoClear = false;\n this.camera.compensateOnFirstFrame = false;\n // reset the camera's position to the origin\n this.camera.position.set(0, 0, 0);\n this.camera.rotationQuaternion.set(0, 0, 0, 1);\n this.onInitialXRPoseSetObservable.notifyObservers(this.camera);\n }\n this.sessionManager.onXRSessionEnded.addOnce(() => {\n // when using the back button and not the exit button (default on mobile), the session is ending but the EXITING state was not set\n if (this.state !== WebXRState.EXITING_XR) {\n this._setState(WebXRState.EXITING_XR);\n }\n // Reset camera rigs output render target to ensure sessions render target is not drawn after it ends\n this.camera.rigCameras.forEach((c) => {\n c.outputRenderTarget = null;\n });\n // Restore scene settings\n this._scene.autoClear = this._originalSceneAutoClear;\n this._scene.activeCamera = this._nonVRCamera;\n if (this._attachedToElement && this._nonVRCamera) {\n this._nonVRCamera.attachControl(!!this._nonVRCamera.inputs.noPreventDefault);\n }\n if (sessionMode !== \"immersive-ar\" && this.camera.compensateOnFirstFrame) {\n if (this._nonVRCamera.setPosition) {\n this._nonVRCamera.setPosition(this.camera.position);\n }\n else {\n this._nonVRCamera.position.copyFrom(this.camera.position);\n }\n }\n this._setState(WebXRState.NOT_IN_XR);\n });\n // Wait until the first frame arrives before setting state to in xr\n this.sessionManager.onXRFrameObservable.addOnce(() => {\n this._setState(WebXRState.IN_XR);\n });\n return this.sessionManager;\n }\n catch (e) {\n console.log(e);\n console.log(e.message);\n this._setState(WebXRState.NOT_IN_XR);\n throw e;\n }\n }\n /**\n * Exits XR mode and returns the scene to its original state\n * @returns promise that resolves after xr mode has exited\n */\n exitXRAsync() {\n // only exit if state is IN_XR\n if (this.state !== WebXRState.IN_XR) {\n return Promise.resolve();\n }\n this._setState(WebXRState.EXITING_XR);\n return this.sessionManager.exitXRAsync();\n }\n /**\n * Enable spectator mode for desktop VR experiences.\n * When spectator mode is enabled a camera will be attached to the desktop canvas and will\n * display the first rig camera's view on the desktop canvas.\n * Please note that this will degrade performance, as it requires another camera render.\n * It is also not recommended to enable this in devices like the quest, as it brings no benefit there.\n * @param options giving WebXRSpectatorModeOption for specutator camera to setup when the spectator mode is enabled.\n */\n enableSpectatorMode(options) {\n if (!this._spectatorMode) {\n this._spectatorMode = true;\n this._switchSpectatorMode(options);\n }\n }\n /**\n * Disable spectator mode for desktop VR experiences.\n */\n disableSpecatatorMode() {\n if (this._spectatorMode) {\n this._spectatorMode = false;\n this._switchSpectatorMode();\n }\n }\n _switchSpectatorMode(options) {\n const fps = (options === null || options === void 0 ? void 0 : options.fps) ? options.fps : 1000.0;\n const refreshRate = (1.0 / fps) * 1000.0;\n const cameraIndex = (options === null || options === void 0 ? void 0 : options.preferredCameraIndex) ? options === null || options === void 0 ? void 0 : options.preferredCameraIndex : 0;\n const updateSpectatorCamera = () => {\n if (this._spectatorCamera) {\n const delta = this.sessionManager.currentTimestamp - this._lastTimestamp;\n if (delta >= refreshRate) {\n this._lastTimestamp = this.sessionManager.currentTimestamp;\n this._spectatorCamera.position.copyFrom(this.camera.rigCameras[cameraIndex].globalPosition);\n this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[cameraIndex].absoluteRotation);\n }\n }\n };\n if (this._spectatorMode) {\n if (cameraIndex >= this.camera.rigCameras.length) {\n throw new Error(\"the preferred camera index is beyond the length of rig camera array.\");\n }\n const onStateChanged = () => {\n if (this.state === WebXRState.IN_XR) {\n this._spectatorCamera = new UniversalCamera(\"webxr-spectator\", Vector3.Zero(), this._scene);\n this._spectatorCamera.rotationQuaternion = new Quaternion();\n this._scene.activeCameras = [this.camera, this._spectatorCamera];\n this.sessionManager.onXRFrameObservable.add(updateSpectatorCamera);\n this._scene.onAfterRenderCameraObservable.add((camera) => {\n if (camera === this.camera) {\n // reset the dimensions object for correct resizing\n this._scene.getEngine().framebufferDimensionsObject = null;\n }\n });\n }\n else if (this.state === WebXRState.EXITING_XR) {\n this.sessionManager.onXRFrameObservable.removeCallback(updateSpectatorCamera);\n this._scene.activeCameras = null;\n }\n };\n this.onStateChangedObservable.add(onStateChanged);\n onStateChanged();\n }\n else {\n this.sessionManager.onXRFrameObservable.removeCallback(updateSpectatorCamera);\n this._scene.activeCameras = [this.camera];\n }\n }\n _nonXRToXRCamera() {\n this.camera.setTransformationFromNonVRCamera(this._nonVRCamera);\n this.onInitialXRPoseSetObservable.notifyObservers(this.camera);\n }\n _setState(val) {\n if (this.state === val) {\n return;\n }\n this.state = val;\n this.onStateChangedObservable.notifyObservers(this.state);\n }\n}\n//# sourceMappingURL=webXRExperienceHelper.js.map","import { Observable } from \"../../Misc/observable.js\";\n/**\n * This class represents a single component (for example button or thumbstick) of a motion controller\n */\nexport class WebXRControllerComponent {\n /**\n * Creates a new component for a motion controller.\n * It is created by the motion controller itself\n *\n * @param id the id of this component\n * @param type the type of the component\n * @param _buttonIndex index in the buttons array of the gamepad\n * @param _axesIndices indices of the values in the axes array of the gamepad\n */\n constructor(\n /**\n * the id of this component\n */\n id, \n /**\n * the type of the component\n */\n type, _buttonIndex = -1, _axesIndices = []) {\n this.id = id;\n this.type = type;\n this._buttonIndex = _buttonIndex;\n this._axesIndices = _axesIndices;\n this._axes = {\n x: 0,\n y: 0,\n };\n this._changes = {};\n this._currentValue = 0;\n this._hasChanges = false;\n this._pressed = false;\n this._touched = false;\n /**\n * If axes are available for this component (like a touchpad or thumbstick) the observers will be notified when\n * the axes data changes\n */\n this.onAxisValueChangedObservable = new Observable();\n /**\n * Observers registered here will be triggered when the state of a button changes\n * State change is either pressed / touched / value\n */\n this.onButtonStateChangedObservable = new Observable();\n }\n /**\n * The current axes data. If this component has no axes it will still return an object { x: 0, y: 0 }\n */\n get axes() {\n return this._axes;\n }\n /**\n * Get the changes. Elements will be populated only if they changed with their previous and current value\n */\n get changes() {\n return this._changes;\n }\n /**\n * Return whether or not the component changed the last frame\n */\n get hasChanges() {\n return this._hasChanges;\n }\n /**\n * is the button currently pressed\n */\n get pressed() {\n return this._pressed;\n }\n /**\n * is the button currently touched\n */\n get touched() {\n return this._touched;\n }\n /**\n * Get the current value of this component\n */\n get value() {\n return this._currentValue;\n }\n /**\n * Dispose this component\n */\n dispose() {\n this.onAxisValueChangedObservable.clear();\n this.onButtonStateChangedObservable.clear();\n }\n /**\n * Are there axes correlating to this component\n * @returns true is axes data is available\n */\n isAxes() {\n return this._axesIndices.length !== 0;\n }\n /**\n * Is this component a button (hence - pressable)\n * @returns true if can be pressed\n */\n isButton() {\n return this._buttonIndex !== -1;\n }\n /**\n * update this component using the gamepad object it is in. Called on every frame\n * @param nativeController the native gamepad controller object\n */\n update(nativeController) {\n let buttonUpdated = false;\n let axesUpdate = false;\n this._hasChanges = false;\n this._changes = {};\n if (this.isButton()) {\n const button = nativeController.buttons[this._buttonIndex];\n // defensive, in case a profile was forced\n if (!button) {\n return;\n }\n if (this._currentValue !== button.value) {\n this.changes.value = {\n current: button.value,\n previous: this._currentValue,\n };\n buttonUpdated = true;\n this._currentValue = button.value;\n }\n if (this._touched !== button.touched) {\n this.changes.touched = {\n current: button.touched,\n previous: this._touched,\n };\n buttonUpdated = true;\n this._touched = button.touched;\n }\n if (this._pressed !== button.pressed) {\n this.changes.pressed = {\n current: button.pressed,\n previous: this._pressed,\n };\n buttonUpdated = true;\n this._pressed = button.pressed;\n }\n }\n if (this.isAxes()) {\n if (this._axes.x !== nativeController.axes[this._axesIndices[0]]) {\n this.changes.axes = {\n current: {\n x: nativeController.axes[this._axesIndices[0]],\n y: this._axes.y,\n },\n previous: {\n x: this._axes.x,\n y: this._axes.y,\n },\n };\n this._axes.x = nativeController.axes[this._axesIndices[0]];\n axesUpdate = true;\n }\n if (this._axes.y !== nativeController.axes[this._axesIndices[1]]) {\n if (this.changes.axes) {\n this.changes.axes.current.y = nativeController.axes[this._axesIndices[1]];\n }\n else {\n this.changes.axes = {\n current: {\n x: this._axes.x,\n y: nativeController.axes[this._axesIndices[1]],\n },\n previous: {\n x: this._axes.x,\n y: this._axes.y,\n },\n };\n }\n this._axes.y = nativeController.axes[this._axesIndices[1]];\n axesUpdate = true;\n }\n }\n if (buttonUpdated) {\n this._hasChanges = true;\n this.onButtonStateChangedObservable.notifyObservers(this);\n }\n if (axesUpdate) {\n this._hasChanges = true;\n this.onAxisValueChangedObservable.notifyObservers(this._axes);\n }\n }\n}\n/**\n * button component type\n */\nWebXRControllerComponent.BUTTON_TYPE = \"button\";\n/**\n * squeeze component type\n */\nWebXRControllerComponent.SQUEEZE_TYPE = \"squeeze\";\n/**\n * Thumbstick component type\n */\nWebXRControllerComponent.THUMBSTICK_TYPE = \"thumbstick\";\n/**\n * Touchpad component type\n */\nWebXRControllerComponent.TOUCHPAD_TYPE = \"touchpad\";\n/**\n * trigger component type\n */\nWebXRControllerComponent.TRIGGER_TYPE = \"trigger\";\n//# sourceMappingURL=webXRControllerComponent.js.map","import { WebXRControllerComponent } from \"./webXRControllerComponent.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { SceneLoader } from \"../../Loading/sceneLoader.js\";\nimport { Quaternion, Vector3 } from \"../../Maths/math.vector.js\";\nimport { Mesh } from \"../../Meshes/mesh.js\";\n/**\n * An Abstract Motion controller\n * This class receives an xrInput and a profile layout and uses those to initialize the components\n * Each component has an observable to check for changes in value and state\n */\nexport class WebXRAbstractMotionController {\n /**\n * constructs a new abstract motion controller\n * @param scene the scene to which the model of the controller will be added\n * @param layout The profile layout to load\n * @param gamepadObject The gamepad object correlating to this controller\n * @param handedness handedness (left/right/none) of this controller\n * @param _doNotLoadControllerMesh set this flag to ignore the mesh loading\n * @param _controllerCache a cache holding controller models already loaded in this session\n */\n constructor(\n // eslint-disable-next-line @typescript-eslint/naming-convention\n scene, \n // eslint-disable-next-line @typescript-eslint/naming-convention\n layout, \n /**\n * The gamepad object correlating to this controller\n */\n gamepadObject, \n /**\n * handedness (left/right/none) of this controller\n */\n handedness, \n /**\n * @internal\n */\n _doNotLoadControllerMesh = false, _controllerCache) {\n this.scene = scene;\n this.layout = layout;\n this.gamepadObject = gamepadObject;\n this.handedness = handedness;\n this._doNotLoadControllerMesh = _doNotLoadControllerMesh;\n this._controllerCache = _controllerCache;\n this._initComponent = (id) => {\n if (!id) {\n return;\n }\n const componentDef = this.layout.components[id];\n const type = componentDef.type;\n const buttonIndex = componentDef.gamepadIndices.button;\n // search for axes\n const axes = [];\n if (componentDef.gamepadIndices.xAxis !== undefined && componentDef.gamepadIndices.yAxis !== undefined) {\n axes.push(componentDef.gamepadIndices.xAxis, componentDef.gamepadIndices.yAxis);\n }\n this.components[id] = new WebXRControllerComponent(id, type, buttonIndex, axes);\n };\n this._modelReady = false;\n /**\n * A map of components (WebXRControllerComponent) in this motion controller\n * Components have a ComponentType and can also have both button and axis definitions\n */\n this.components = {};\n /**\n * Disable the model's animation. Can be set at any time.\n */\n this.disableAnimation = false;\n /**\n * Observers registered here will be triggered when the model of this controller is done loading\n */\n this.onModelLoadedObservable = new Observable();\n // initialize the components\n if (layout.components) {\n Object.keys(layout.components).forEach(this._initComponent);\n }\n // Model is loaded in WebXRInput\n }\n /**\n * Dispose this controller, the model mesh and all its components\n */\n dispose() {\n this.getComponentIds().forEach((id) => this.getComponent(id).dispose());\n if (this.rootMesh) {\n this.rootMesh.getChildren(undefined, true).forEach((node) => {\n node.setEnabled(false);\n });\n this.rootMesh.dispose(!!this._controllerCache, !this._controllerCache);\n }\n }\n /**\n * Returns all components of specific type\n * @param type the type to search for\n * @returns an array of components with this type\n */\n getAllComponentsOfType(type) {\n return this.getComponentIds()\n .map((id) => this.components[id])\n .filter((component) => component.type === type);\n }\n /**\n * get a component based an its component id as defined in layout.components\n * @param id the id of the component\n * @returns the component correlates to the id or undefined if not found\n */\n getComponent(id) {\n return this.components[id];\n }\n /**\n * Get the list of components available in this motion controller\n * @returns an array of strings correlating to available components\n */\n getComponentIds() {\n return Object.keys(this.components);\n }\n /**\n * Get the first component of specific type\n * @param type type of component to find\n * @returns a controller component or null if not found\n */\n getComponentOfType(type) {\n return this.getAllComponentsOfType(type)[0] || null;\n }\n /**\n * Get the main (Select) component of this controller as defined in the layout\n * @returns the main component of this controller\n */\n getMainComponent() {\n return this.getComponent(this.layout.selectComponentId);\n }\n /**\n * Loads the model correlating to this controller\n * When the mesh is loaded, the onModelLoadedObservable will be triggered\n * @returns A promise fulfilled with the result of the model loading\n */\n async loadModel() {\n const useGeneric = !this._getModelLoadingConstraints();\n let loadingParams = this._getGenericFilenameAndPath();\n // Checking if GLB loader is present\n if (useGeneric) {\n Logger.Warn(\"Falling back to generic models\");\n }\n else {\n loadingParams = this._getFilenameAndPath();\n }\n return new Promise((resolve, reject) => {\n const meshesLoaded = (meshes) => {\n if (useGeneric) {\n this._getGenericParentMesh(meshes);\n }\n else {\n this._setRootMesh(meshes);\n }\n this._processLoadedModel(meshes);\n this._modelReady = true;\n this.onModelLoadedObservable.notifyObservers(this);\n resolve(true);\n };\n if (this._controllerCache) {\n // look for it in the cache\n const found = this._controllerCache.filter((c) => {\n return c.filename === loadingParams.filename && c.path === loadingParams.path;\n });\n if (found[0]) {\n found[0].meshes.forEach((mesh) => mesh.setEnabled(true));\n meshesLoaded(found[0].meshes);\n return;\n // found, don't continue to load\n }\n }\n SceneLoader.ImportMesh(\"\", loadingParams.path, loadingParams.filename, this.scene, (meshes) => {\n if (this._controllerCache) {\n this._controllerCache.push(Object.assign(Object.assign({}, loadingParams), { meshes }));\n }\n meshesLoaded(meshes);\n }, null, (_scene, message) => {\n Logger.Log(message);\n Logger.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${loadingParams.path}${loadingParams.filename}`);\n reject(message);\n });\n });\n }\n /**\n * Update this model using the current XRFrame\n * @param xrFrame the current xr frame to use and update the model\n */\n updateFromXRFrame(xrFrame) {\n this.getComponentIds().forEach((id) => this.getComponent(id).update(this.gamepadObject));\n this.updateModel(xrFrame);\n }\n /**\n * Backwards compatibility due to a deeply-integrated typo\n */\n get handness() {\n return this.handedness;\n }\n /**\n * Pulse (vibrate) this controller\n * If the controller does not support pulses, this function will fail silently and return Promise directly after called\n * Consecutive calls to this function will cancel the last pulse call\n *\n * @param value the strength of the pulse in 0.0...1.0 range\n * @param duration Duration of the pulse in milliseconds\n * @param hapticActuatorIndex optional index of actuator (will usually be 0)\n * @returns a promise that will send true when the pulse has ended and false if the device doesn't support pulse or an error accrued\n */\n pulse(value, duration, hapticActuatorIndex = 0) {\n if (this.gamepadObject.hapticActuators && this.gamepadObject.hapticActuators[hapticActuatorIndex]) {\n return this.gamepadObject.hapticActuators[hapticActuatorIndex].pulse(value, duration);\n }\n else {\n return Promise.resolve(false);\n }\n }\n // Look through all children recursively. This will return null if no mesh exists with the given name.\n _getChildByName(node, name) {\n return node.getChildren((n) => n.name === name, false)[0];\n }\n // Look through only immediate children. This will return null if no mesh exists with the given name.\n _getImmediateChildByName(node, name) {\n return node.getChildren((n) => n.name == name, true)[0];\n }\n /**\n * Moves the axis on the controller mesh based on its current state\n * @param axisMap\n * @param axisValue the value of the axis which determines the meshes new position\n * @internal\n */\n _lerpTransform(axisMap, axisValue, fixValueCoordinates) {\n if (!axisMap.minMesh || !axisMap.maxMesh || !axisMap.valueMesh) {\n return;\n }\n if (!axisMap.minMesh.rotationQuaternion || !axisMap.maxMesh.rotationQuaternion || !axisMap.valueMesh.rotationQuaternion) {\n return;\n }\n // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)\n const lerpValue = fixValueCoordinates ? axisValue * 0.5 + 0.5 : axisValue;\n Quaternion.SlerpToRef(axisMap.minMesh.rotationQuaternion, axisMap.maxMesh.rotationQuaternion, lerpValue, axisMap.valueMesh.rotationQuaternion);\n Vector3.LerpToRef(axisMap.minMesh.position, axisMap.maxMesh.position, lerpValue, axisMap.valueMesh.position);\n }\n /**\n * Update the model itself with the current frame data\n * @param xrFrame the frame to use for updating the model mesh\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n updateModel(xrFrame) {\n if (!this._modelReady) {\n return;\n }\n this._updateModel(xrFrame);\n }\n _getGenericFilenameAndPath() {\n return {\n filename: \"generic.babylon\",\n path: \"https://controllers.babylonjs.com/generic/\",\n };\n }\n _getGenericParentMesh(meshes) {\n this.rootMesh = new Mesh(this.profileId + \" \" + this.handedness, this.scene);\n meshes.forEach((mesh) => {\n if (!mesh.parent) {\n mesh.isPickable = false;\n mesh.setParent(this.rootMesh);\n }\n });\n this.rootMesh.rotationQuaternion = Quaternion.FromEulerAngles(0, Math.PI, 0);\n }\n}\n//# sourceMappingURL=webXRAbstractMotionController.js.map","import { WebXRAbstractMotionController } from \"./webXRAbstractMotionController.js\";\nimport { Mesh } from \"../../Meshes/mesh.js\";\nimport { Quaternion } from \"../../Maths/math.vector.js\";\n/**\n * A generic trigger-only motion controller for WebXR\n */\nexport class WebXRGenericTriggerMotionController extends WebXRAbstractMotionController {\n constructor(scene, gamepadObject, handedness) {\n super(scene, GenericTriggerLayout[handedness], gamepadObject, handedness);\n this.profileId = WebXRGenericTriggerMotionController.ProfileId;\n }\n _getFilenameAndPath() {\n return {\n filename: \"generic.babylon\",\n path: \"https://controllers.babylonjs.com/generic/\",\n };\n }\n _getModelLoadingConstraints() {\n return true;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _processLoadedModel(meshes) {\n // nothing to do\n }\n _setRootMesh(meshes) {\n this.rootMesh = new Mesh(this.profileId + \" \" + this.handedness, this.scene);\n meshes.forEach((mesh) => {\n mesh.isPickable = false;\n if (!mesh.parent) {\n mesh.setParent(this.rootMesh);\n }\n });\n this.rootMesh.rotationQuaternion = Quaternion.FromEulerAngles(0, Math.PI, 0);\n }\n _updateModel() {\n // no-op\n }\n}\n/**\n * Static version of the profile id of this controller\n */\nWebXRGenericTriggerMotionController.ProfileId = \"generic-trigger\";\n// https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/generic/generic-trigger-touchpad-thumbstick.json\nconst GenericTriggerLayout = {\n left: {\n selectComponentId: \"xr-standard-trigger\",\n components: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n \"xr-standard-trigger\": {\n type: \"trigger\",\n gamepadIndices: {\n button: 0,\n },\n rootNodeName: \"xr_standard_trigger\",\n visualResponses: {},\n },\n },\n gamepadMapping: \"xr-standard\",\n rootNodeName: \"generic-trigger-left\",\n assetPath: \"left.glb\",\n },\n right: {\n selectComponentId: \"xr-standard-trigger\",\n components: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n \"xr-standard-trigger\": {\n type: \"trigger\",\n gamepadIndices: {\n button: 0,\n },\n rootNodeName: \"xr_standard_trigger\",\n visualResponses: {},\n },\n },\n gamepadMapping: \"xr-standard\",\n rootNodeName: \"generic-trigger-right\",\n assetPath: \"right.glb\",\n },\n none: {\n selectComponentId: \"xr-standard-trigger\",\n components: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n \"xr-standard-trigger\": {\n type: \"trigger\",\n gamepadIndices: {\n button: 0,\n },\n rootNodeName: \"xr_standard_trigger\",\n visualResponses: {},\n },\n },\n gamepadMapping: \"xr-standard\",\n rootNodeName: \"generic-trigger-none\",\n assetPath: \"none.glb\",\n },\n};\n//# sourceMappingURL=webXRGenericMotionController.js.map","import { WebXRAbstractMotionController } from \"./webXRAbstractMotionController.js\";\nimport { SceneLoader } from \"../../Loading/sceneLoader.js\";\nimport { Mesh } from \"../../Meshes/mesh.js\";\nimport { Axis, Space } from \"../../Maths/math.axis.js\";\nimport { Color3 } from \"../../Maths/math.color.js\";\nimport { WebXRControllerComponent } from \"./webXRControllerComponent.js\";\nimport { CreateSphere } from \"../../Meshes/Builders/sphereBuilder.js\";\nimport { StandardMaterial } from \"../../Materials/standardMaterial.js\";\nimport { Logger } from \"../../Misc/logger.js\";\n/**\n * A profiled motion controller has its profile loaded from an online repository.\n * The class is responsible of loading the model, mapping the keys and enabling model-animations\n */\nexport class WebXRProfiledMotionController extends WebXRAbstractMotionController {\n constructor(scene, xrInput, _profile, _repositoryUrl, \n // eslint-disable-next-line @typescript-eslint/naming-convention\n controllerCache) {\n super(scene, _profile.layouts[xrInput.handedness || \"none\"], xrInput.gamepad, xrInput.handedness, undefined, controllerCache);\n this._repositoryUrl = _repositoryUrl;\n this.controllerCache = controllerCache;\n this._buttonMeshMapping = {};\n this._touchDots = {};\n this.profileId = _profile.profileId;\n }\n dispose() {\n super.dispose();\n if (!this.controllerCache) {\n Object.keys(this._touchDots).forEach((visResKey) => {\n this._touchDots[visResKey].dispose();\n });\n }\n }\n _getFilenameAndPath() {\n return {\n filename: this.layout.assetPath,\n path: `${this._repositoryUrl}/profiles/${this.profileId}/`,\n };\n }\n _getModelLoadingConstraints() {\n const glbLoaded = SceneLoader.IsPluginForExtensionAvailable(\".glb\");\n if (!glbLoaded) {\n Logger.Warn(\"glTF / glb loader was not registered, using generic controller instead\");\n }\n return glbLoaded;\n }\n _processLoadedModel(_meshes) {\n this.getComponentIds().forEach((type) => {\n const componentInLayout = this.layout.components[type];\n this._buttonMeshMapping[type] = {\n mainMesh: this._getChildByName(this.rootMesh, componentInLayout.rootNodeName),\n states: {},\n };\n Object.keys(componentInLayout.visualResponses).forEach((visualResponseKey) => {\n const visResponse = componentInLayout.visualResponses[visualResponseKey];\n if (visResponse.valueNodeProperty === \"transform\") {\n this._buttonMeshMapping[type].states[visualResponseKey] = {\n valueMesh: this._getChildByName(this.rootMesh, visResponse.valueNodeName),\n minMesh: this._getChildByName(this.rootMesh, visResponse.minNodeName),\n maxMesh: this._getChildByName(this.rootMesh, visResponse.maxNodeName),\n };\n }\n else {\n // visibility, usually for touchpads\n const nameOfMesh = componentInLayout.type === WebXRControllerComponent.TOUCHPAD_TYPE && componentInLayout.touchPointNodeName\n ? componentInLayout.touchPointNodeName\n : visResponse.valueNodeName;\n this._buttonMeshMapping[type].states[visualResponseKey] = {\n valueMesh: this._getChildByName(this.rootMesh, nameOfMesh),\n };\n if (componentInLayout.type === WebXRControllerComponent.TOUCHPAD_TYPE && !this._touchDots[visualResponseKey]) {\n const dot = CreateSphere(visualResponseKey + \"dot\", {\n diameter: 0.0015,\n segments: 8,\n }, this.scene);\n dot.material = new StandardMaterial(visualResponseKey + \"mat\", this.scene);\n dot.material.diffuseColor = Color3.Red();\n dot.parent = this._buttonMeshMapping[type].states[visualResponseKey].valueMesh || null;\n dot.isVisible = false;\n this._touchDots[visualResponseKey] = dot;\n }\n }\n });\n });\n }\n _setRootMesh(meshes) {\n this.rootMesh = new Mesh(this.profileId + \"-\" + this.handedness, this.scene);\n this.rootMesh.isPickable = false;\n let rootMesh;\n // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'\n for (let i = 0; i < meshes.length; i++) {\n const mesh = meshes[i];\n mesh.isPickable = false;\n if (!mesh.parent) {\n // Handle root node, attach to the new parentMesh\n rootMesh = mesh;\n }\n }\n if (rootMesh) {\n rootMesh.setParent(this.rootMesh);\n }\n if (!this.scene.useRightHandedSystem) {\n this.rootMesh.rotate(Axis.Y, Math.PI, Space.WORLD);\n }\n }\n _updateModel(_xrFrame) {\n if (this.disableAnimation) {\n return;\n }\n this.getComponentIds().forEach((id) => {\n const component = this.getComponent(id);\n if (!component.hasChanges) {\n return;\n }\n const meshes = this._buttonMeshMapping[id];\n const componentInLayout = this.layout.components[id];\n Object.keys(componentInLayout.visualResponses).forEach((visualResponseKey) => {\n const visResponse = componentInLayout.visualResponses[visualResponseKey];\n let value = component.value;\n if (visResponse.componentProperty === \"xAxis\") {\n value = component.axes.x;\n }\n else if (visResponse.componentProperty === \"yAxis\") {\n value = component.axes.y;\n }\n if (visResponse.valueNodeProperty === \"transform\") {\n this._lerpTransform(meshes.states[visualResponseKey], value, visResponse.componentProperty !== \"button\");\n }\n else {\n // visibility\n const valueMesh = meshes.states[visualResponseKey].valueMesh;\n if (valueMesh) {\n valueMesh.isVisible = component.touched || component.pressed;\n }\n if (this._touchDots[visualResponseKey]) {\n this._touchDots[visualResponseKey].isVisible = component.touched || component.pressed;\n }\n }\n });\n });\n }\n}\n//# sourceMappingURL=webXRProfiledMotionController.js.map","import { WebXRGenericTriggerMotionController } from \"./webXRGenericMotionController.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nimport { WebXRProfiledMotionController } from \"./webXRProfiledMotionController.js\";\n/**\n * The MotionController Manager manages all registered motion controllers and loads the right one when needed.\n *\n * When this repository is complete: https://github.com/immersive-web/webxr-input-profiles/tree/master/packages/assets\n * it should be replaced with auto-loaded controllers.\n *\n * When using a model try to stay as generic as possible. Eventually there will be no need in any of the controller classes\n */\nconst controllerCache = [];\n/**\n * Motion controller manager is managing the different webxr profiles and makes sure the right\n * controller is being loaded.\n */\nexport class WebXRMotionControllerManager {\n /**\n * Clear the cache used for profile loading and reload when requested again\n */\n static ClearProfilesCache() {\n this._ProfilesList = null;\n this._ProfileLoadingPromises = {};\n }\n /**\n * Register the default fallbacks.\n * This function is called automatically when this file is imported.\n */\n static DefaultFallbacks() {\n this.RegisterFallbacksForProfileId(\"google-daydream\", [\"generic-touchpad\"]);\n this.RegisterFallbacksForProfileId(\"htc-vive-focus\", [\"generic-trigger-touchpad\"]);\n this.RegisterFallbacksForProfileId(\"htc-vive\", [\"generic-trigger-squeeze-touchpad\"]);\n this.RegisterFallbacksForProfileId(\"magicleap-one\", [\"generic-trigger-squeeze-touchpad\"]);\n this.RegisterFallbacksForProfileId(\"windows-mixed-reality\", [\"generic-trigger-squeeze-touchpad-thumbstick\"]);\n this.RegisterFallbacksForProfileId(\"microsoft-mixed-reality\", [\"windows-mixed-reality\", \"generic-trigger-squeeze-touchpad-thumbstick\"]);\n this.RegisterFallbacksForProfileId(\"oculus-go\", [\"generic-trigger-touchpad\"]);\n this.RegisterFallbacksForProfileId(\"oculus-touch-v2\", [\"oculus-touch\", \"generic-trigger-squeeze-thumbstick\"]);\n this.RegisterFallbacksForProfileId(\"oculus-touch\", [\"generic-trigger-squeeze-thumbstick\"]);\n this.RegisterFallbacksForProfileId(\"samsung-gearvr\", [\"windows-mixed-reality\", \"generic-trigger-squeeze-touchpad-thumbstick\"]);\n this.RegisterFallbacksForProfileId(\"samsung-odyssey\", [\"generic-touchpad\"]);\n this.RegisterFallbacksForProfileId(\"valve-index\", [\"generic-trigger-squeeze-touchpad-thumbstick\"]);\n this.RegisterFallbacksForProfileId(\"generic-hand-select\", [\"generic-trigger\"]);\n }\n /**\n * Find a fallback profile if the profile was not found. There are a few predefined generic profiles.\n * @param profileId the profile to which a fallback needs to be found\n * @returns an array with corresponding fallback profiles\n */\n static FindFallbackWithProfileId(profileId) {\n const returnArray = this._Fallbacks[profileId] || [];\n returnArray.unshift(profileId);\n return returnArray;\n }\n /**\n * When acquiring a new xrInput object (usually by the WebXRInput class), match it with the correct profile.\n * The order of search:\n *\n * 1) Iterate the profiles array of the xr input and try finding a corresponding motion controller\n * 2) (If not found) search in the gamepad id and try using it (legacy versions only)\n * 3) search for registered fallbacks (should be redundant, nonetheless it makes sense to check)\n * 4) return the generic trigger controller if none were found\n *\n * @param xrInput the xrInput to which a new controller is initialized\n * @param scene the scene to which the model will be added\n * @param forceProfile force a certain profile for this controller\n * @returns A promise that fulfils with the motion controller class for this profile id or the generic standard class if none was found\n */\n static GetMotionControllerWithXRInput(xrInput, scene, forceProfile) {\n const profileArray = [];\n if (forceProfile) {\n profileArray.push(forceProfile);\n }\n profileArray.push(...(xrInput.profiles || []));\n // emulator support\n if (profileArray.length && !profileArray[0]) {\n // remove the first \"undefined\" that the emulator is adding\n profileArray.pop();\n }\n // legacy support - try using the gamepad id\n if (xrInput.gamepad && xrInput.gamepad.id) {\n switch (xrInput.gamepad.id) {\n case xrInput.gamepad.id.match(/oculus touch/gi) ? xrInput.gamepad.id : undefined:\n // oculus in gamepad id\n profileArray.push(\"oculus-touch-v2\");\n break;\n }\n }\n // make sure microsoft/windows mixed reality works correctly\n const windowsMRIdx = profileArray.indexOf(\"windows-mixed-reality\");\n if (windowsMRIdx !== -1) {\n profileArray.splice(windowsMRIdx, 0, \"microsoft-mixed-reality\");\n }\n if (!profileArray.length) {\n profileArray.push(\"generic-trigger\");\n }\n if (this.UseOnlineRepository) {\n const firstFunction = this.PrioritizeOnlineRepository ? this._LoadProfileFromRepository : this._LoadProfilesFromAvailableControllers;\n const secondFunction = this.PrioritizeOnlineRepository ? this._LoadProfilesFromAvailableControllers : this._LoadProfileFromRepository;\n return firstFunction.call(this, profileArray, xrInput, scene).catch(() => {\n return secondFunction.call(this, profileArray, xrInput, scene);\n });\n }\n else {\n // use only available functions\n return this._LoadProfilesFromAvailableControllers(profileArray, xrInput, scene);\n }\n }\n /**\n * Register a new controller based on its profile. This function will be called by the controller classes themselves.\n *\n * If you are missing a profile, make sure it is imported in your source, otherwise it will not register.\n *\n * @param type the profile type to register\n * @param constructFunction the function to be called when loading this profile\n */\n static RegisterController(type, constructFunction) {\n this._AvailableControllers[type] = constructFunction;\n }\n /**\n * Register a fallback to a specific profile.\n * @param profileId the profileId that will receive the fallbacks\n * @param fallbacks A list of fallback profiles\n */\n static RegisterFallbacksForProfileId(profileId, fallbacks) {\n if (this._Fallbacks[profileId]) {\n this._Fallbacks[profileId].push(...fallbacks);\n }\n else {\n this._Fallbacks[profileId] = fallbacks;\n }\n }\n /**\n * Will update the list of profiles available in the repository\n * @returns a promise that resolves to a map of profiles available online\n */\n static UpdateProfilesList() {\n this._ProfilesList = Tools.LoadFileAsync(this.BaseRepositoryUrl + \"/profiles/profilesList.json\", false).then((data) => {\n return JSON.parse(data.toString());\n });\n return this._ProfilesList;\n }\n /**\n * Clear the controller's cache (usually happens at the end of a session)\n */\n static ClearControllerCache() {\n controllerCache.forEach((cacheItem) => {\n cacheItem.meshes.forEach((mesh) => {\n mesh.dispose(false, true);\n });\n });\n controllerCache.length = 0;\n }\n static _LoadProfileFromRepository(profileArray, xrInput, scene) {\n return Promise.resolve()\n .then(() => {\n if (!this._ProfilesList) {\n return this.UpdateProfilesList();\n }\n else {\n return this._ProfilesList;\n }\n })\n .then((profilesList) => {\n // load the right profile\n for (let i = 0; i < profileArray.length; ++i) {\n // defensive\n if (!profileArray[i]) {\n continue;\n }\n if (profilesList[profileArray[i]]) {\n return profileArray[i];\n }\n }\n throw new Error(`neither controller ${profileArray[0]} nor all fallbacks were found in the repository,`);\n })\n .then((profileToLoad) => {\n // load the profile\n if (!this._ProfileLoadingPromises[profileToLoad]) {\n this._ProfileLoadingPromises[profileToLoad] = Tools.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${profileToLoad}/profile.json`, false).then((data) => JSON.parse(data));\n }\n return this._ProfileLoadingPromises[profileToLoad];\n })\n .then((profile) => {\n return new WebXRProfiledMotionController(scene, xrInput, profile, this.BaseRepositoryUrl, this.DisableControllerCache ? undefined : controllerCache);\n });\n }\n static _LoadProfilesFromAvailableControllers(profileArray, xrInput, scene) {\n // check fallbacks\n for (let i = 0; i < profileArray.length; ++i) {\n // defensive\n if (!profileArray[i]) {\n continue;\n }\n const fallbacks = this.FindFallbackWithProfileId(profileArray[i]);\n for (let j = 0; j < fallbacks.length; ++j) {\n const constructionFunction = this._AvailableControllers[fallbacks[j]];\n if (constructionFunction) {\n return Promise.resolve(constructionFunction(xrInput, scene));\n }\n }\n }\n throw new Error(`no controller requested was found in the available controllers list`);\n }\n}\nWebXRMotionControllerManager._AvailableControllers = {};\nWebXRMotionControllerManager._Fallbacks = {};\n// cache for loading\nWebXRMotionControllerManager._ProfileLoadingPromises = {};\n/**\n * The base URL of the online controller repository. Can be changed at any time.\n */\nWebXRMotionControllerManager.BaseRepositoryUrl = \"https://immersive-web.github.io/webxr-input-profiles/packages/viewer/dist\";\n/**\n * Which repository gets priority - local or online\n */\nWebXRMotionControllerManager.PrioritizeOnlineRepository = true;\n/**\n * Use the online repository, or use only locally-defined controllers\n */\nWebXRMotionControllerManager.UseOnlineRepository = true;\n/**\n * Disable the controller cache and load the models each time a new WebXRProfileMotionController is loaded.\n * Defaults to true.\n */\nWebXRMotionControllerManager.DisableControllerCache = true;\n// register the generic profile(s) here so we will at least have them\nWebXRMotionControllerManager.RegisterController(WebXRGenericTriggerMotionController.ProfileId, (xrInput, scene) => {\n return new WebXRGenericTriggerMotionController(scene, xrInput.gamepad, xrInput.handedness);\n});\n// register fallbacks\nWebXRMotionControllerManager.DefaultFallbacks();\n//# sourceMappingURL=webXRMotionControllerManager.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { AbstractMesh } from \"../Meshes/abstractMesh.js\";\nimport { Quaternion, Vector3 } from \"../Maths/math.vector.js\";\nimport { WebXRMotionControllerManager } from \"./motionController/webXRMotionControllerManager.js\";\nimport { Tools } from \"../Misc/tools.js\";\nlet idCount = 0;\n/**\n * Represents an XR controller\n */\nexport class WebXRInputSource {\n /**\n * Creates the input source object\n * @see https://doc.babylonjs.com/features/featuresDeepDive/webXR/webXRInputControllerSupport\n * @param _scene the scene which the controller should be associated to\n * @param inputSource the underlying input source for the controller\n * @param _options options for this controller creation\n */\n constructor(_scene, \n /** The underlying input source for the controller */\n inputSource, _options = {}) {\n this._scene = _scene;\n this.inputSource = inputSource;\n this._options = _options;\n this._tmpVector = new Vector3();\n this._disposed = false;\n /**\n * Event that fires when the controller is removed/disposed.\n * The object provided as event data is this controller, after associated assets were disposed.\n * uniqueId is still available.\n */\n this.onDisposeObservable = new Observable();\n /**\n * Will be triggered when the mesh associated with the motion controller is done loading.\n * It is also possible that this will never trigger (!) if no mesh was loaded, or if the developer decides to load a different mesh\n * A shortened version of controller -> motion controller -> on mesh loaded.\n */\n this.onMeshLoadedObservable = new Observable();\n /**\n * Observers registered here will trigger when a motion controller profile was assigned to this xr controller\n */\n this.onMotionControllerInitObservable = new Observable();\n this._uniqueId = `controller-${idCount++}-${inputSource.targetRayMode}-${inputSource.handedness}`;\n this.pointer = new AbstractMesh(`${this._uniqueId}-pointer`, _scene);\n this.pointer.rotationQuaternion = new Quaternion();\n if (this.inputSource.gripSpace) {\n this.grip = new AbstractMesh(`${this._uniqueId}-grip`, this._scene);\n this.grip.rotationQuaternion = new Quaternion();\n }\n this._tmpVector.set(0, 0, this._scene.useRightHandedSystem ? -1.0 : 1.0);\n // for now only load motion controllers if gamepad object available\n if (this.inputSource.gamepad && this.inputSource.targetRayMode === \"tracked-pointer\") {\n WebXRMotionControllerManager.GetMotionControllerWithXRInput(inputSource, _scene, this._options.forceControllerProfile).then((motionController) => {\n this.motionController = motionController;\n this.onMotionControllerInitObservable.notifyObservers(motionController);\n // should the model be loaded?\n if (!this._options.doNotLoadControllerMesh && !this.motionController._doNotLoadControllerMesh) {\n this.motionController.loadModel().then((success) => {\n var _a;\n if (success && this.motionController && this.motionController.rootMesh) {\n if (this._options.renderingGroupId) {\n // anything other than 0?\n this.motionController.rootMesh.renderingGroupId = this._options.renderingGroupId;\n this.motionController.rootMesh.getChildMeshes(false).forEach((mesh) => (mesh.renderingGroupId = this._options.renderingGroupId));\n }\n this.onMeshLoadedObservable.notifyObservers(this.motionController.rootMesh);\n this.motionController.rootMesh.parent = this.grip || this.pointer;\n this.motionController.disableAnimation = !!this._options.disableMotionControllerAnimation;\n }\n // make sure to dispose is the controller is already disposed\n if (this._disposed) {\n (_a = this.motionController) === null || _a === void 0 ? void 0 : _a.dispose();\n }\n });\n }\n }, () => {\n Tools.Warn(`Could not find a matching motion controller for the registered input source`);\n });\n }\n }\n /**\n * Get this controllers unique id\n */\n get uniqueId() {\n return this._uniqueId;\n }\n /**\n * Disposes of the object\n */\n dispose() {\n if (this.grip) {\n this.grip.dispose(true);\n }\n if (this.motionController) {\n this.motionController.dispose();\n }\n this.pointer.dispose(true);\n this.onMotionControllerInitObservable.clear();\n this.onMeshLoadedObservable.clear();\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n this._disposed = true;\n }\n /**\n * Gets a world space ray coming from the pointer or grip\n * @param result the resulting ray\n * @param gripIfAvailable use the grip mesh instead of the pointer, if available\n */\n getWorldPointerRayToRef(result, gripIfAvailable = false) {\n const object = gripIfAvailable && this.grip ? this.grip : this.pointer;\n Vector3.TransformNormalToRef(this._tmpVector, object.getWorldMatrix(), result.direction);\n result.direction.normalize();\n result.origin.copyFrom(object.absolutePosition);\n result.length = 1000;\n }\n /**\n * Updates the controller pose based on the given XRFrame\n * @param xrFrame xr frame to update the pose with\n * @param referenceSpace reference space to use\n * @param xrCamera the xr camera, used for parenting\n */\n updateFromXRFrame(xrFrame, referenceSpace, xrCamera) {\n const pose = xrFrame.getPose(this.inputSource.targetRaySpace, referenceSpace);\n this._lastXRPose = pose;\n // Update the pointer mesh\n if (pose) {\n const pos = pose.transform.position;\n this.pointer.position.set(pos.x, pos.y, pos.z);\n const orientation = pose.transform.orientation;\n this.pointer.rotationQuaternion.set(orientation.x, orientation.y, orientation.z, orientation.w);\n if (!this._scene.useRightHandedSystem) {\n this.pointer.position.z *= -1;\n this.pointer.rotationQuaternion.z *= -1;\n this.pointer.rotationQuaternion.w *= -1;\n }\n this.pointer.parent = xrCamera.parent;\n }\n // Update the grip mesh if it exists\n if (this.inputSource.gripSpace && this.grip) {\n const pose = xrFrame.getPose(this.inputSource.gripSpace, referenceSpace);\n if (pose) {\n const pos = pose.transform.position;\n const orientation = pose.transform.orientation;\n this.grip.position.set(pos.x, pos.y, pos.z);\n this.grip.rotationQuaternion.set(orientation.x, orientation.y, orientation.z, orientation.w);\n if (!this._scene.useRightHandedSystem) {\n this.grip.position.z *= -1;\n this.grip.rotationQuaternion.z *= -1;\n this.grip.rotationQuaternion.w *= -1;\n }\n }\n this.grip.parent = xrCamera.parent;\n }\n if (this.motionController) {\n // either update buttons only or also position, if in gamepad mode\n this.motionController.updateFromXRFrame(xrFrame);\n }\n }\n}\n//# sourceMappingURL=webXRInputSource.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { WebXRInputSource } from \"./webXRInputSource.js\";\nimport { WebXRMotionControllerManager } from \"./motionController/webXRMotionControllerManager.js\";\n/**\n * XR input used to track XR inputs such as controllers/rays\n */\nexport class WebXRInput {\n /**\n * Initializes the WebXRInput\n * @param xrSessionManager the xr session manager for this session\n * @param xrCamera the WebXR camera for this session. Mainly used for teleportation\n * @param _options = initialization options for this xr input\n */\n constructor(\n /**\n * the xr session manager for this session\n */\n xrSessionManager, \n /**\n * the WebXR camera for this session. Mainly used for teleportation\n */\n xrCamera, _options = {}) {\n this.xrSessionManager = xrSessionManager;\n this.xrCamera = xrCamera;\n this._options = _options;\n /**\n * XR controllers being tracked\n */\n this.controllers = [];\n /**\n * Event when a controller has been connected/added\n */\n this.onControllerAddedObservable = new Observable();\n /**\n * Event when a controller has been removed/disconnected\n */\n this.onControllerRemovedObservable = new Observable();\n this._onInputSourcesChange = (event) => {\n this._addAndRemoveControllers(event.added, event.removed);\n };\n // Remove controllers when exiting XR\n this._sessionEndedObserver = this.xrSessionManager.onXRSessionEnded.add(() => {\n this._addAndRemoveControllers([], this.controllers.map((c) => {\n return c.inputSource;\n }));\n });\n this._sessionInitObserver = this.xrSessionManager.onXRSessionInit.add((session) => {\n session.addEventListener(\"inputsourceschange\", this._onInputSourcesChange);\n });\n this._frameObserver = this.xrSessionManager.onXRFrameObservable.add((frame) => {\n // Update controller pose info\n this.controllers.forEach((controller) => {\n controller.updateFromXRFrame(frame, this.xrSessionManager.referenceSpace, this.xrCamera);\n });\n });\n if (this._options.customControllersRepositoryURL) {\n WebXRMotionControllerManager.BaseRepositoryUrl = this._options.customControllersRepositoryURL;\n }\n WebXRMotionControllerManager.UseOnlineRepository = !this._options.disableOnlineControllerRepository;\n if (WebXRMotionControllerManager.UseOnlineRepository) {\n // pre-load the profiles list to load the controllers quicker afterwards\n try {\n WebXRMotionControllerManager.UpdateProfilesList().catch(() => {\n WebXRMotionControllerManager.UseOnlineRepository = false;\n });\n }\n catch (e) {\n WebXRMotionControllerManager.UseOnlineRepository = false;\n }\n }\n }\n _addAndRemoveControllers(addInputs, removeInputs) {\n // Add controllers if they don't already exist\n const sources = this.controllers.map((c) => {\n return c.inputSource;\n });\n for (const input of addInputs) {\n if (sources.indexOf(input) === -1) {\n const controller = new WebXRInputSource(this.xrSessionManager.scene, input, Object.assign(Object.assign({}, (this._options.controllerOptions || {})), { forceControllerProfile: this._options.forceInputProfile, doNotLoadControllerMesh: this._options.doNotLoadControllerMeshes, disableMotionControllerAnimation: this._options.disableControllerAnimation }));\n this.controllers.push(controller);\n this.onControllerAddedObservable.notifyObservers(controller);\n }\n }\n // Remove and dispose of controllers to be disposed\n const keepControllers = [];\n const removedControllers = [];\n this.controllers.forEach((c) => {\n if (removeInputs.indexOf(c.inputSource) === -1) {\n keepControllers.push(c);\n }\n else {\n removedControllers.push(c);\n }\n });\n this.controllers = keepControllers;\n removedControllers.forEach((c) => {\n this.onControllerRemovedObservable.notifyObservers(c);\n c.dispose();\n });\n }\n /**\n * Disposes of the object\n */\n dispose() {\n this.controllers.forEach((c) => {\n c.dispose();\n });\n this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver);\n this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver);\n this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver);\n this.onControllerAddedObservable.clear();\n this.onControllerRemovedObservable.clear();\n // clear the controller cache\n WebXRMotionControllerManager.ClearControllerCache();\n }\n}\n//# sourceMappingURL=webXRInput.js.map","import { WebXRFeaturesManager, WebXRFeatureName } from \"../webXRFeaturesManager.js\";\nimport { Matrix, Vector3 } from \"../../Maths/math.vector.js\";\nimport { Color3 } from \"../../Maths/math.color.js\";\nimport { Axis } from \"../../Maths/math.axis.js\";\nimport { StandardMaterial } from \"../../Materials/standardMaterial.js\";\nimport { CreateCylinder } from \"../../Meshes/Builders/cylinderBuilder.js\";\nimport { CreateTorus } from \"../../Meshes/Builders/torusBuilder.js\";\nimport { Ray } from \"../../Culling/ray.js\";\nimport { PickingInfo } from \"../../Collisions/pickingInfo.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nimport { UtilityLayerRenderer } from \"../../Rendering/utilityLayerRenderer.js\";\nimport { Viewport } from \"../../Maths/math.viewport.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * A module that will enable pointer selection for motion controllers of XR Input Sources\n */\nexport class WebXRControllerPointerSelection extends WebXRAbstractFeature {\n /**\n * constructs a new background remover module\n * @param _xrSessionManager the session manager for this module\n * @param _options read-only options to be used in this module\n */\n constructor(_xrSessionManager, _options) {\n super(_xrSessionManager);\n this._options = _options;\n this._attachController = (xrController) => {\n if (this._controllers[xrController.uniqueId]) {\n // already attached\n return;\n }\n const { laserPointer, selectionMesh } = this._generateNewMeshPair(xrController.pointer);\n // get two new meshes\n this._controllers[xrController.uniqueId] = {\n xrController,\n laserPointer,\n selectionMesh,\n meshUnderPointer: null,\n pick: null,\n tmpRay: new Ray(new Vector3(), new Vector3()),\n disabledByNearInteraction: false,\n id: WebXRControllerPointerSelection._IdCounter++,\n };\n if (this._attachedController) {\n if (!this._options.enablePointerSelectionOnAllControllers &&\n this._options.preferredHandedness &&\n xrController.inputSource.handedness === this._options.preferredHandedness) {\n this._attachedController = xrController.uniqueId;\n }\n }\n else {\n if (!this._options.enablePointerSelectionOnAllControllers) {\n this._attachedController = xrController.uniqueId;\n }\n }\n switch (xrController.inputSource.targetRayMode) {\n case \"tracked-pointer\":\n return this._attachTrackedPointerRayMode(xrController);\n case \"gaze\":\n return this._attachGazeMode(xrController);\n case \"screen\":\n return this._attachScreenRayMode(xrController);\n }\n };\n this._controllers = {};\n this._tmpVectorForPickCompare = new Vector3();\n /**\n * Disable lighting on the laser pointer (so it will always be visible)\n */\n this.disablePointerLighting = true;\n /**\n * Disable lighting on the selection mesh (so it will always be visible)\n */\n this.disableSelectionMeshLighting = true;\n /**\n * Should the laser pointer be displayed\n */\n this.displayLaserPointer = true;\n /**\n * Should the selection mesh be displayed (The ring at the end of the laser pointer)\n */\n this.displaySelectionMesh = true;\n /**\n * This color will be set to the laser pointer when selection is triggered\n */\n this.laserPointerPickedColor = new Color3(0.9, 0.9, 0.9);\n /**\n * Default color of the laser pointer\n */\n this.laserPointerDefaultColor = new Color3(0.7, 0.7, 0.7);\n /**\n * default color of the selection ring\n */\n this.selectionMeshDefaultColor = new Color3(0.8, 0.8, 0.8);\n /**\n * This color will be applied to the selection ring when selection is triggered\n */\n this.selectionMeshPickedColor = new Color3(0.3, 0.3, 1.0);\n this._identityMatrix = Matrix.Identity();\n this._screenCoordinatesRef = Vector3.Zero();\n this._viewportRef = new Viewport(0, 0, 0, 0);\n this._scene = this._xrSessionManager.scene;\n }\n /**\n * attach this feature\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n attach() {\n if (!super.attach()) {\n return false;\n }\n this._options.xrInput.controllers.forEach(this._attachController);\n this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController);\n this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, (controller) => {\n // REMOVE the controller\n this._detachController(controller.uniqueId);\n });\n this._scene.constantlyUpdateMeshUnderPointer = true;\n if (this._options.gazeCamera) {\n const webXRCamera = this._options.gazeCamera;\n const { laserPointer, selectionMesh } = this._generateNewMeshPair(webXRCamera);\n this._controllers[\"camera\"] = {\n webXRCamera,\n laserPointer,\n selectionMesh,\n meshUnderPointer: null,\n pick: null,\n tmpRay: new Ray(new Vector3(), new Vector3()),\n disabledByNearInteraction: false,\n id: WebXRControllerPointerSelection._IdCounter++,\n };\n this._attachGazeMode();\n }\n return true;\n }\n /**\n * detach this feature.\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n detach() {\n if (!super.detach()) {\n return false;\n }\n Object.keys(this._controllers).forEach((controllerId) => {\n this._detachController(controllerId);\n });\n return true;\n }\n /**\n * Will get the mesh under a specific pointer.\n * `scene.meshUnderPointer` will only return one mesh - either left or right.\n * @param controllerId the controllerId to check\n * @returns The mesh under pointer or null if no mesh is under the pointer\n */\n getMeshUnderPointer(controllerId) {\n if (this._controllers[controllerId]) {\n return this._controllers[controllerId].meshUnderPointer;\n }\n else {\n return null;\n }\n }\n /**\n * Get the xr controller that correlates to the pointer id in the pointer event\n *\n * @param id the pointer id to search for\n * @returns the controller that correlates to this id or null if not found\n */\n getXRControllerByPointerId(id) {\n const keys = Object.keys(this._controllers);\n for (let i = 0; i < keys.length; ++i) {\n if (this._controllers[keys[i]].id === id) {\n return this._controllers[keys[i]].xrController || null;\n }\n }\n return null;\n }\n /**\n * @internal\n */\n _getPointerSelectionDisabledByPointerId(id) {\n const keys = Object.keys(this._controllers);\n for (let i = 0; i < keys.length; ++i) {\n if (this._controllers[keys[i]].id === id) {\n return this._controllers[keys[i]].disabledByNearInteraction;\n }\n }\n return true;\n }\n /**\n * @internal\n */\n _setPointerSelectionDisabledByPointerId(id, state) {\n const keys = Object.keys(this._controllers);\n for (let i = 0; i < keys.length; ++i) {\n if (this._controllers[keys[i]].id === id) {\n this._controllers[keys[i]].disabledByNearInteraction = state;\n return;\n }\n }\n }\n _onXRFrame(_xrFrame) {\n Object.keys(this._controllers).forEach((id) => {\n // only do this for the selected pointer\n const controllerData = this._controllers[id];\n if ((!this._options.enablePointerSelectionOnAllControllers && id !== this._attachedController) || controllerData.disabledByNearInteraction) {\n controllerData.selectionMesh.isVisible = false;\n controllerData.laserPointer.isVisible = false;\n controllerData.pick = null;\n return;\n }\n controllerData.laserPointer.isVisible = this.displayLaserPointer;\n let controllerGlobalPosition;\n // Every frame check collisions/input\n if (controllerData.xrController) {\n controllerGlobalPosition = controllerData.xrController.pointer.position;\n controllerData.xrController.getWorldPointerRayToRef(controllerData.tmpRay);\n }\n else if (controllerData.webXRCamera) {\n controllerGlobalPosition = controllerData.webXRCamera.position;\n controllerData.webXRCamera.getForwardRayToRef(controllerData.tmpRay);\n }\n else {\n return;\n }\n if (this._options.maxPointerDistance) {\n controllerData.tmpRay.length = this._options.maxPointerDistance;\n }\n // update pointerX and pointerY of the scene. Only if the flag is set to true!\n if (!this._options.disableScenePointerVectorUpdate && controllerGlobalPosition) {\n const scene = this._xrSessionManager.scene;\n const camera = this._options.xrInput.xrCamera;\n if (camera) {\n camera.viewport.toGlobalToRef(scene.getEngine().getRenderWidth(), scene.getEngine().getRenderHeight(), this._viewportRef);\n Vector3.ProjectToRef(controllerGlobalPosition, this._identityMatrix, scene.getTransformMatrix(), this._viewportRef, this._screenCoordinatesRef);\n // stay safe\n if (typeof this._screenCoordinatesRef.x === \"number\" &&\n typeof this._screenCoordinatesRef.y === \"number\" &&\n !isNaN(this._screenCoordinatesRef.x) &&\n !isNaN(this._screenCoordinatesRef.y)) {\n scene.pointerX = this._screenCoordinatesRef.x;\n scene.pointerY = this._screenCoordinatesRef.y;\n controllerData.screenCoordinates = {\n x: this._screenCoordinatesRef.x,\n y: this._screenCoordinatesRef.y,\n };\n }\n }\n }\n let utilityScenePick = null;\n if (this._utilityLayerScene) {\n utilityScenePick = this._utilityLayerScene.pickWithRay(controllerData.tmpRay, this._utilityLayerScene.pointerMovePredicate || this.raySelectionPredicate);\n }\n const originalScenePick = this._scene.pickWithRay(controllerData.tmpRay, this._scene.pointerMovePredicate || this.raySelectionPredicate);\n if (!utilityScenePick || !utilityScenePick.hit) {\n // No hit in utility scene\n controllerData.pick = originalScenePick;\n }\n else if (!originalScenePick || !originalScenePick.hit) {\n // No hit in original scene\n controllerData.pick = utilityScenePick;\n }\n else if (utilityScenePick.distance < originalScenePick.distance) {\n // Hit is closer in utility scene\n controllerData.pick = utilityScenePick;\n }\n else {\n // Hit is closer in original scene\n controllerData.pick = originalScenePick;\n }\n if (controllerData.pick && controllerData.xrController) {\n controllerData.pick.aimTransform = controllerData.xrController.pointer;\n controllerData.pick.gripTransform = controllerData.xrController.grip || null;\n }\n const pick = controllerData.pick;\n if (pick && pick.pickedPoint && pick.hit) {\n // Update laser state\n this._updatePointerDistance(controllerData.laserPointer, pick.distance);\n // Update cursor state\n controllerData.selectionMesh.position.copyFrom(pick.pickedPoint);\n controllerData.selectionMesh.scaling.x = Math.sqrt(pick.distance);\n controllerData.selectionMesh.scaling.y = Math.sqrt(pick.distance);\n controllerData.selectionMesh.scaling.z = Math.sqrt(pick.distance);\n // To avoid z-fighting\n const pickNormal = this._convertNormalToDirectionOfRay(pick.getNormal(true), controllerData.tmpRay);\n const deltaFighting = 0.001;\n controllerData.selectionMesh.position.copyFrom(pick.pickedPoint);\n if (pickNormal) {\n const axis1 = Vector3.Cross(Axis.Y, pickNormal);\n const axis2 = Vector3.Cross(pickNormal, axis1);\n Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, controllerData.selectionMesh.rotation);\n controllerData.selectionMesh.position.addInPlace(pickNormal.scale(deltaFighting));\n }\n controllerData.selectionMesh.isVisible = true && this.displaySelectionMesh;\n controllerData.meshUnderPointer = pick.pickedMesh;\n }\n else {\n controllerData.selectionMesh.isVisible = false;\n this._updatePointerDistance(controllerData.laserPointer, 1);\n controllerData.meshUnderPointer = null;\n }\n });\n }\n get _utilityLayerScene() {\n return this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene;\n }\n _attachGazeMode(xrController) {\n const controllerData = this._controllers[(xrController && xrController.uniqueId) || \"camera\"];\n // attached when touched, detaches when raised\n const timeToSelect = this._options.timeToSelect || 3000;\n const sceneToRenderTo = this._options.useUtilityLayer ? this._utilityLayerScene : this._scene;\n let oldPick = new PickingInfo();\n const discMesh = CreateTorus(\"selection\", {\n diameter: 0.0035 * 15,\n thickness: 0.0025 * 6,\n tessellation: 20,\n }, sceneToRenderTo);\n discMesh.isVisible = false;\n discMesh.isPickable = false;\n discMesh.parent = controllerData.selectionMesh;\n let timer = 0;\n let downTriggered = false;\n const pointerEventInit = {\n pointerId: controllerData.id,\n pointerType: \"xr\",\n };\n controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {\n if (!controllerData.pick) {\n return;\n }\n this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates);\n controllerData.laserPointer.material.alpha = 0;\n discMesh.isVisible = false;\n if (controllerData.pick.hit) {\n if (!this._pickingMoved(oldPick, controllerData.pick)) {\n if (timer > timeToSelect / 10) {\n discMesh.isVisible = true;\n }\n timer += this._scene.getEngine().getDeltaTime();\n if (timer >= timeToSelect) {\n this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);\n // this pointerdown event is not setting the controllerData.pointerDownTriggered to avoid a pointerUp event when this feature is detached\n downTriggered = true;\n // pointer up right after down, if disable on touch out\n if (this._options.disablePointerUpOnTouchOut) {\n this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);\n }\n discMesh.isVisible = false;\n }\n else {\n const scaleFactor = 1 - timer / timeToSelect;\n discMesh.scaling.set(scaleFactor, scaleFactor, scaleFactor);\n }\n }\n else {\n if (downTriggered) {\n if (!this._options.disablePointerUpOnTouchOut) {\n this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);\n }\n }\n downTriggered = false;\n timer = 0;\n }\n }\n else {\n downTriggered = false;\n timer = 0;\n }\n this._scene.simulatePointerMove(controllerData.pick, pointerEventInit);\n oldPick = controllerData.pick;\n });\n if (this._options.renderingGroupId !== undefined) {\n discMesh.renderingGroupId = this._options.renderingGroupId;\n }\n if (xrController) {\n xrController.onDisposeObservable.addOnce(() => {\n if (controllerData.pick && !this._options.disablePointerUpOnTouchOut && downTriggered) {\n this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);\n controllerData.finalPointerUpTriggered = true;\n }\n discMesh.dispose();\n });\n }\n }\n _attachScreenRayMode(xrController) {\n const controllerData = this._controllers[xrController.uniqueId];\n let downTriggered = false;\n const pointerEventInit = {\n pointerId: controllerData.id,\n pointerType: \"xr\",\n };\n controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {\n this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates);\n if (!controllerData.pick || (this._options.disablePointerUpOnTouchOut && downTriggered)) {\n return;\n }\n if (!downTriggered) {\n this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);\n controllerData.pointerDownTriggered = true;\n downTriggered = true;\n if (this._options.disablePointerUpOnTouchOut) {\n this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);\n }\n }\n else {\n this._scene.simulatePointerMove(controllerData.pick, pointerEventInit);\n }\n });\n xrController.onDisposeObservable.addOnce(() => {\n this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates);\n this._xrSessionManager.runInXRFrame(() => {\n if (controllerData.pick && !controllerData.finalPointerUpTriggered && downTriggered && !this._options.disablePointerUpOnTouchOut) {\n this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);\n controllerData.finalPointerUpTriggered = true;\n }\n });\n });\n }\n _attachTrackedPointerRayMode(xrController) {\n const controllerData = this._controllers[xrController.uniqueId];\n if (this._options.forceGazeMode) {\n return this._attachGazeMode(xrController);\n }\n const pointerEventInit = {\n pointerId: controllerData.id,\n pointerType: \"xr\",\n };\n controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {\n controllerData.laserPointer.material.disableLighting = this.disablePointerLighting;\n controllerData.selectionMesh.material.disableLighting = this.disableSelectionMeshLighting;\n if (controllerData.pick) {\n this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates);\n this._scene.simulatePointerMove(controllerData.pick, pointerEventInit);\n }\n });\n if (xrController.inputSource.gamepad) {\n const init = (motionController) => {\n if (this._options.overrideButtonId) {\n controllerData.selectionComponent = motionController.getComponent(this._options.overrideButtonId);\n }\n if (!controllerData.selectionComponent) {\n controllerData.selectionComponent = motionController.getMainComponent();\n }\n controllerData.onButtonChangedObserver = controllerData.selectionComponent.onButtonStateChangedObservable.add((component) => {\n if (component.changes.pressed) {\n const pressed = component.changes.pressed.current;\n if (controllerData.pick) {\n if (this._options.enablePointerSelectionOnAllControllers || xrController.uniqueId === this._attachedController) {\n this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates);\n if (pressed) {\n this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);\n controllerData.pointerDownTriggered = true;\n controllerData.selectionMesh.material.emissiveColor = this.selectionMeshPickedColor;\n controllerData.laserPointer.material.emissiveColor = this.laserPointerPickedColor;\n }\n else {\n this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);\n controllerData.selectionMesh.material.emissiveColor = this.selectionMeshDefaultColor;\n controllerData.laserPointer.material.emissiveColor = this.laserPointerDefaultColor;\n }\n }\n }\n else {\n if (pressed && !this._options.enablePointerSelectionOnAllControllers && !this._options.disableSwitchOnClick) {\n this._attachedController = xrController.uniqueId;\n }\n }\n }\n });\n };\n if (xrController.motionController) {\n init(xrController.motionController);\n }\n else {\n xrController.onMotionControllerInitObservable.add(init);\n }\n }\n else {\n // use the select and squeeze events\n const selectStartListener = (event) => {\n this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates);\n if (controllerData.xrController && event.inputSource === controllerData.xrController.inputSource && controllerData.pick) {\n this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);\n controllerData.pointerDownTriggered = true;\n controllerData.selectionMesh.material.emissiveColor = this.selectionMeshPickedColor;\n controllerData.laserPointer.material.emissiveColor = this.laserPointerPickedColor;\n }\n };\n const selectEndListener = (event) => {\n this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates);\n if (controllerData.xrController && event.inputSource === controllerData.xrController.inputSource && controllerData.pick) {\n this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);\n controllerData.selectionMesh.material.emissiveColor = this.selectionMeshDefaultColor;\n controllerData.laserPointer.material.emissiveColor = this.laserPointerDefaultColor;\n }\n };\n controllerData.eventListeners = {\n selectend: selectEndListener,\n selectstart: selectStartListener,\n };\n this._xrSessionManager.session.addEventListener(\"selectstart\", selectStartListener);\n this._xrSessionManager.session.addEventListener(\"selectend\", selectEndListener);\n }\n }\n _convertNormalToDirectionOfRay(normal, ray) {\n if (normal) {\n const angle = Math.acos(Vector3.Dot(normal, ray.direction));\n if (angle < Math.PI / 2) {\n normal.scaleInPlace(-1);\n }\n }\n return normal;\n }\n _detachController(xrControllerUniqueId) {\n const controllerData = this._controllers[xrControllerUniqueId];\n if (!controllerData) {\n return;\n }\n if (controllerData.selectionComponent) {\n if (controllerData.onButtonChangedObserver) {\n controllerData.selectionComponent.onButtonStateChangedObservable.remove(controllerData.onButtonChangedObserver);\n }\n }\n if (controllerData.onFrameObserver) {\n this._xrSessionManager.onXRFrameObservable.remove(controllerData.onFrameObserver);\n }\n if (controllerData.eventListeners) {\n Object.keys(controllerData.eventListeners).forEach((eventName) => {\n const func = controllerData.eventListeners && controllerData.eventListeners[eventName];\n if (func) {\n // For future reference - this is an issue in the WebXR typings.\n this._xrSessionManager.session.removeEventListener(eventName, func);\n }\n });\n }\n if (!controllerData.finalPointerUpTriggered && controllerData.pointerDownTriggered) {\n // Stay safe and fire a pointerup, in case it wasn't already triggered\n const pointerEventInit = {\n pointerId: controllerData.id,\n pointerType: \"xr\",\n };\n this._xrSessionManager.runInXRFrame(() => {\n this._augmentPointerInit(pointerEventInit, controllerData.id, controllerData.screenCoordinates);\n this._scene.simulatePointerUp(controllerData.pick || new PickingInfo(), pointerEventInit);\n controllerData.finalPointerUpTriggered = true;\n });\n }\n this._xrSessionManager.scene.onBeforeRenderObservable.addOnce(() => {\n try {\n controllerData.selectionMesh.dispose();\n controllerData.laserPointer.dispose();\n // remove from the map\n delete this._controllers[xrControllerUniqueId];\n if (this._attachedController === xrControllerUniqueId) {\n // check for other controllers\n const keys = Object.keys(this._controllers);\n if (keys.length) {\n this._attachedController = keys[0];\n }\n else {\n this._attachedController = \"\";\n }\n }\n }\n catch (e) {\n Tools.Warn(\"controller already detached.\");\n }\n });\n }\n _generateNewMeshPair(meshParent) {\n const sceneToRenderTo = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._scene;\n const laserPointer = this._options.customLasterPointerMeshGenerator\n ? this._options.customLasterPointerMeshGenerator()\n : CreateCylinder(\"laserPointer\", {\n height: 1,\n diameterTop: 0.0002,\n diameterBottom: 0.004,\n tessellation: 20,\n subdivisions: 1,\n }, sceneToRenderTo);\n laserPointer.parent = meshParent;\n const laserPointerMaterial = new StandardMaterial(\"laserPointerMat\", sceneToRenderTo);\n laserPointerMaterial.emissiveColor = this.laserPointerDefaultColor;\n laserPointerMaterial.alpha = 0.7;\n laserPointer.material = laserPointerMaterial;\n laserPointer.rotation.x = Math.PI / 2;\n this._updatePointerDistance(laserPointer, 1);\n laserPointer.isPickable = false;\n laserPointer.isVisible = false;\n // Create a gaze tracker for the XR controller\n const selectionMesh = this._options.customSelectionMeshGenerator\n ? this._options.customSelectionMeshGenerator()\n : CreateTorus(\"gazeTracker\", {\n diameter: 0.0035 * 3,\n thickness: 0.0025 * 3,\n tessellation: 20,\n }, sceneToRenderTo);\n selectionMesh.bakeCurrentTransformIntoVertices();\n selectionMesh.isPickable = false;\n selectionMesh.isVisible = false;\n const targetMat = new StandardMaterial(\"targetMat\", sceneToRenderTo);\n targetMat.specularColor = Color3.Black();\n targetMat.emissiveColor = this.selectionMeshDefaultColor;\n targetMat.backFaceCulling = false;\n selectionMesh.material = targetMat;\n if (this._options.renderingGroupId !== undefined) {\n laserPointer.renderingGroupId = this._options.renderingGroupId;\n selectionMesh.renderingGroupId = this._options.renderingGroupId;\n }\n return {\n laserPointer,\n selectionMesh,\n };\n }\n _pickingMoved(oldPick, newPick) {\n var _a;\n if (!oldPick.hit || !newPick.hit) {\n return true;\n }\n if (!oldPick.pickedMesh || !oldPick.pickedPoint || !newPick.pickedMesh || !newPick.pickedPoint) {\n return true;\n }\n if (oldPick.pickedMesh !== newPick.pickedMesh) {\n return true;\n }\n (_a = oldPick.pickedPoint) === null || _a === void 0 ? void 0 : _a.subtractToRef(newPick.pickedPoint, this._tmpVectorForPickCompare);\n this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x), Math.abs(this._tmpVectorForPickCompare.y), Math.abs(this._tmpVectorForPickCompare.z));\n const delta = (this._options.gazeModePointerMovedFactor || 1) * 0.01 * newPick.distance;\n const length = this._tmpVectorForPickCompare.length();\n if (length > delta) {\n return true;\n }\n return false;\n }\n _updatePointerDistance(_laserPointer, distance = 100) {\n _laserPointer.scaling.y = distance;\n // a bit of distance from the controller\n if (this._scene.useRightHandedSystem) {\n distance *= -1;\n }\n _laserPointer.position.z = distance / 2 + 0.05;\n }\n _augmentPointerInit(pointerEventInit, id, screenCoordinates) {\n pointerEventInit.pointerId = id;\n pointerEventInit.pointerType = \"xr\";\n if (screenCoordinates) {\n pointerEventInit.screenX = screenCoordinates.x;\n pointerEventInit.screenY = screenCoordinates.y;\n }\n }\n /** @internal */\n get lasterPointerDefaultColor() {\n // here due to a typo\n return this.laserPointerDefaultColor;\n }\n}\nWebXRControllerPointerSelection._IdCounter = 200;\n/**\n * The module's name\n */\nWebXRControllerPointerSelection.Name = WebXRFeatureName.POINTER_SELECTION;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRControllerPointerSelection.Version = 1;\n//register the plugin\nWebXRFeaturesManager.AddWebXRFeature(WebXRControllerPointerSelection.Name, (xrSessionManager, options) => {\n return () => new WebXRControllerPointerSelection(xrSessionManager, options);\n}, WebXRControllerPointerSelection.Version, true);\n//# sourceMappingURL=WebXRControllerPointerSelection.js.map","\nimport { TmpVectors, Vector3 } from \"../Maths/math.vector.js\";\nimport { SubMesh } from \"./subMesh.js\";\n/**\n * @internal\n */\nSubMesh.prototype._projectOnTrianglesToRef = function (vector, positions, indices, step, checkStopper, ref) {\n // Triangles test\n const proj = TmpVectors.Vector3[0];\n const tmp = TmpVectors.Vector3[1];\n let distance = +Infinity;\n for (let index = this.indexStart; index < this.indexStart + this.indexCount - (3 - step); index += step) {\n const indexA = indices[index];\n const indexB = indices[index + 1];\n const indexC = indices[index + 2];\n if (checkStopper && indexC === 0xffffffff) {\n index += 2;\n continue;\n }\n const p0 = positions[indexA];\n const p1 = positions[indexB];\n const p2 = positions[indexC];\n // stay defensive and don't check against undefined positions.\n if (!p0 || !p1 || !p2) {\n continue;\n }\n const tmpDist = Vector3.ProjectOnTriangleToRef(vector, p0, p1, p2, tmp);\n if (tmpDist < distance) {\n proj.copyFrom(tmp);\n distance = tmpDist;\n }\n }\n ref.copyFrom(proj);\n return distance;\n};\n/**\n * @internal\n */\nSubMesh.prototype._projectOnUnIndexedTrianglesToRef = function (vector, positions, indices, ref) {\n // Triangles test\n const proj = TmpVectors.Vector3[0];\n const tmp = TmpVectors.Vector3[1];\n let distance = +Infinity;\n for (let index = this.verticesStart; index < this.verticesStart + this.verticesCount; index += 3) {\n const p0 = positions[index];\n const p1 = positions[index + 1];\n const p2 = positions[index + 2];\n const tmpDist = Vector3.ProjectOnTriangleToRef(vector, p0, p1, p2, tmp);\n if (tmpDist < distance) {\n proj.copyFrom(tmp);\n distance = tmpDist;\n }\n }\n ref.copyFrom(proj);\n return distance;\n};\nSubMesh.prototype.projectToRef = function (vector, positions, indices, ref) {\n const material = this.getMaterial();\n if (!material) {\n return -1;\n }\n let step = 3;\n let checkStopper = false;\n switch (material.fillMode) {\n case 3:\n case 5:\n case 6:\n case 8:\n return -1;\n case 7:\n step = 1;\n checkStopper = true;\n break;\n default:\n break;\n }\n // LineMesh first as it's also a Mesh...\n if (material.fillMode === 4) {\n return -1;\n }\n else {\n // Check if mesh is unindexed\n if (!indices.length && this._mesh._unIndexed) {\n return this._projectOnUnIndexedTrianglesToRef(vector, positions, indices, ref);\n }\n return this._projectOnTrianglesToRef(vector, positions, indices, step, checkStopper, ref);\n }\n};\n//# sourceMappingURL=subMesh.project.js.map","import { WebXRFeaturesManager, WebXRFeatureName } from \"../webXRFeaturesManager.js\";\nimport { CreateSphere } from \"../../Meshes/Builders/sphereBuilder.js\";\nimport { Vector3, Quaternion, TmpVectors } from \"../../Maths/math.vector.js\";\nimport { Ray } from \"../../Culling/ray.js\";\nimport { PickingInfo } from \"../../Collisions/pickingInfo.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nimport { UtilityLayerRenderer } from \"../../Rendering/utilityLayerRenderer.js\";\nimport { BoundingSphere } from \"../../Culling/boundingSphere.js\";\nimport { StandardMaterial } from \"../../Materials/standardMaterial.js\";\nimport { Color3 } from \"../../Maths/math.color.js\";\nimport { NodeMaterial } from \"../../Materials/Node/nodeMaterial.js\";\nimport { Animation } from \"../../Animations/animation.js\";\nimport { QuadraticEase, EasingFunction } from \"../../Animations/easing.js\";\n// side effects\nimport \"../../Meshes/subMesh.project.js\";\n// Tracks the interaction animation state when using a motion controller with a near interaction orb\nvar ControllerOrbAnimationState;\n(function (ControllerOrbAnimationState) {\n /**\n * Orb is invisible\n */\n ControllerOrbAnimationState[ControllerOrbAnimationState[\"DEHYDRATED\"] = 0] = \"DEHYDRATED\";\n /**\n * Orb is visible and inside the hover range\n */\n ControllerOrbAnimationState[ControllerOrbAnimationState[\"HOVER\"] = 1] = \"HOVER\";\n /**\n * Orb is visible and touching a near interaction target\n */\n ControllerOrbAnimationState[ControllerOrbAnimationState[\"TOUCH\"] = 2] = \"TOUCH\";\n})(ControllerOrbAnimationState || (ControllerOrbAnimationState = {}));\n/**\n * Where should the near interaction mesh be attached to when using a motion controller for near interaction\n */\nexport var WebXRNearControllerMode;\n(function (WebXRNearControllerMode) {\n /**\n * Motion controllers will not support near interaction\n */\n WebXRNearControllerMode[WebXRNearControllerMode[\"DISABLED\"] = 0] = \"DISABLED\";\n /**\n * The interaction point for motion controllers will be inside of them\n */\n WebXRNearControllerMode[WebXRNearControllerMode[\"CENTERED_ON_CONTROLLER\"] = 1] = \"CENTERED_ON_CONTROLLER\";\n /**\n * The interaction point for motion controllers will be in front of the controller\n */\n WebXRNearControllerMode[WebXRNearControllerMode[\"CENTERED_IN_FRONT\"] = 2] = \"CENTERED_IN_FRONT\";\n})(WebXRNearControllerMode || (WebXRNearControllerMode = {}));\n/**\n * A module that will enable near interaction near interaction for hands and motion controllers of XR Input Sources\n */\nexport class WebXRNearInteraction extends WebXRAbstractFeature {\n /**\n * constructs a new background remover module\n * @param _xrSessionManager the session manager for this module\n * @param _options read-only options to be used in this module\n */\n constructor(_xrSessionManager, _options) {\n super(_xrSessionManager);\n this._options = _options;\n this._tmpRay = new Ray(new Vector3(), new Vector3());\n this._attachController = (xrController) => {\n if (this._controllers[xrController.uniqueId]) {\n // already attached\n return;\n }\n // get two new meshes\n const { touchCollisionMesh, touchCollisionMeshFunction, hydrateCollisionMeshFunction } = this._generateNewTouchPointMesh();\n const selectionMesh = this._generateVisualCue();\n this._controllers[xrController.uniqueId] = {\n xrController,\n meshUnderPointer: null,\n nearInteractionTargetMesh: null,\n pick: null,\n stalePick: null,\n touchCollisionMesh,\n touchCollisionMeshFunction: touchCollisionMeshFunction,\n hydrateCollisionMeshFunction: hydrateCollisionMeshFunction,\n currentAnimationState: ControllerOrbAnimationState.DEHYDRATED,\n grabRay: new Ray(new Vector3(), new Vector3()),\n hoverInteraction: false,\n nearInteraction: false,\n grabInteraction: false,\n id: WebXRNearInteraction._IdCounter++,\n pickedPointVisualCue: selectionMesh,\n };\n if (this._attachedController) {\n if (!this._options.enableNearInteractionOnAllControllers &&\n this._options.preferredHandedness &&\n xrController.inputSource.handedness === this._options.preferredHandedness) {\n this._attachedController = xrController.uniqueId;\n }\n }\n else {\n if (!this._options.enableNearInteractionOnAllControllers) {\n this._attachedController = xrController.uniqueId;\n }\n }\n switch (xrController.inputSource.targetRayMode) {\n case \"tracked-pointer\":\n return this._attachNearInteractionMode(xrController);\n case \"gaze\":\n return null;\n case \"screen\":\n return null;\n }\n };\n this._controllers = {};\n this._farInteractionFeature = null;\n /**\n * default color of the selection ring\n */\n this.selectionMeshDefaultColor = new Color3(0.8, 0.8, 0.8);\n /**\n * This color will be applied to the selection ring when selection is triggered\n */\n this.selectionMeshPickedColor = new Color3(0.3, 0.3, 1.0);\n this._hoverRadius = 0.1;\n this._pickRadius = 0.02;\n this._controllerPickRadius = 0.03; // The radius is slightly larger here to make it easier to manipulate since it's not tied to the hand position\n this._nearGrabLengthScale = 5;\n this._scene = this._xrSessionManager.scene;\n if (this._options.nearInteractionControllerMode === undefined) {\n this._options.nearInteractionControllerMode = WebXRNearControllerMode.CENTERED_IN_FRONT;\n }\n if (this._options.farInteractionFeature) {\n this._farInteractionFeature = this._options.farInteractionFeature;\n }\n }\n /**\n * Attach this feature\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n attach() {\n if (!super.attach()) {\n return false;\n }\n this._options.xrInput.controllers.forEach(this._attachController);\n this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController);\n this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, (controller) => {\n // REMOVE the controller\n this._detachController(controller.uniqueId);\n });\n this._scene.constantlyUpdateMeshUnderPointer = true;\n return true;\n }\n /**\n * Detach this feature.\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n detach() {\n if (!super.detach()) {\n return false;\n }\n Object.keys(this._controllers).forEach((controllerId) => {\n this._detachController(controllerId);\n });\n return true;\n }\n /**\n * Will get the mesh under a specific pointer.\n * `scene.meshUnderPointer` will only return one mesh - either left or right.\n * @param controllerId the controllerId to check\n * @returns The mesh under pointer or null if no mesh is under the pointer\n */\n getMeshUnderPointer(controllerId) {\n if (this._controllers[controllerId]) {\n return this._controllers[controllerId].meshUnderPointer;\n }\n else {\n return null;\n }\n }\n /**\n * Get the xr controller that correlates to the pointer id in the pointer event\n *\n * @param id the pointer id to search for\n * @returns the controller that correlates to this id or null if not found\n */\n getXRControllerByPointerId(id) {\n const keys = Object.keys(this._controllers);\n for (let i = 0; i < keys.length; ++i) {\n if (this._controllers[keys[i]].id === id) {\n return this._controllers[keys[i]].xrController || null;\n }\n }\n return null;\n }\n /**\n * This function sets webXRControllerPointerSelection feature that will be disabled when\n * the hover range is reached for a mesh and will be reattached when not in hover range.\n * This is used to remove the selection rays when moving.\n * @param farInteractionFeature the feature to disable when finger is in hover range for a mesh\n */\n setFarInteractionFeature(farInteractionFeature) {\n this._farInteractionFeature = farInteractionFeature;\n }\n /**\n * Filter used for near interaction pick and hover\n * @param mesh\n */\n _nearPickPredicate(mesh) {\n return mesh.isEnabled() && mesh.isVisible && mesh.isPickable && mesh.isNearPickable;\n }\n /**\n * Filter used for near interaction grab\n * @param mesh\n */\n _nearGrabPredicate(mesh) {\n return mesh.isEnabled() && mesh.isVisible && mesh.isPickable && mesh.isNearGrabbable;\n }\n /**\n * Filter used for any near interaction\n * @param mesh\n */\n _nearInteractionPredicate(mesh) {\n return mesh.isEnabled() && mesh.isVisible && mesh.isPickable && (mesh.isNearPickable || mesh.isNearGrabbable);\n }\n _controllerAvailablePredicate(mesh, controllerId) {\n let parent = mesh;\n while (parent) {\n if (parent.reservedDataStore && parent.reservedDataStore.nearInteraction && parent.reservedDataStore.nearInteraction.excludedControllerId === controllerId) {\n return false;\n }\n parent = parent.parent;\n }\n return true;\n }\n _handleTransitionAnimation(controllerData, newState) {\n var _a;\n if (controllerData.currentAnimationState === newState ||\n this._options.nearInteractionControllerMode !== WebXRNearControllerMode.CENTERED_IN_FRONT ||\n !!((_a = controllerData.xrController) === null || _a === void 0 ? void 0 : _a.inputSource.hand)) {\n return;\n }\n // Don't always break to allow for animation fallthrough on rare cases of multi-transitions\n if (newState > controllerData.currentAnimationState) {\n switch (controllerData.currentAnimationState) {\n case ControllerOrbAnimationState.DEHYDRATED: {\n controllerData.hydrateCollisionMeshFunction(true);\n if (newState === ControllerOrbAnimationState.HOVER) {\n break;\n }\n }\n // eslint-disable-next-line no-fallthrough\n case ControllerOrbAnimationState.HOVER: {\n controllerData.touchCollisionMeshFunction(true);\n if (newState === ControllerOrbAnimationState.TOUCH) {\n break;\n }\n }\n }\n }\n else {\n switch (controllerData.currentAnimationState) {\n case ControllerOrbAnimationState.TOUCH: {\n controllerData.touchCollisionMeshFunction(false);\n if (newState === ControllerOrbAnimationState.HOVER) {\n break;\n }\n }\n // eslint-disable-next-line no-fallthrough\n case ControllerOrbAnimationState.HOVER: {\n controllerData.hydrateCollisionMeshFunction(false);\n if (newState === ControllerOrbAnimationState.DEHYDRATED) {\n break;\n }\n }\n }\n }\n controllerData.currentAnimationState = newState;\n }\n _processTouchPoint(id, position, orientation) {\n var _a;\n const controllerData = this._controllers[id];\n // Position and orientation could be temporary values, se we take care of them before calling any functions that use temporary vectors/quaternions\n controllerData.grabRay.origin.copyFrom(position);\n orientation.toEulerAnglesToRef(TmpVectors.Vector3[0]);\n controllerData.grabRay.direction.copyFrom(TmpVectors.Vector3[0]);\n if (this._options.nearInteractionControllerMode === WebXRNearControllerMode.CENTERED_IN_FRONT && !((_a = controllerData.xrController) === null || _a === void 0 ? void 0 : _a.inputSource.hand)) {\n // offset the touch point in the direction the transform is facing\n controllerData.xrController.getWorldPointerRayToRef(this._tmpRay);\n controllerData.grabRay.origin.addInPlace(this._tmpRay.direction.scale(0.05));\n }\n controllerData.grabRay.length = this._nearGrabLengthScale * this._hoverRadius;\n controllerData.touchCollisionMesh.position.copyFrom(controllerData.grabRay.origin);\n }\n _onXRFrame(_xrFrame) {\n Object.keys(this._controllers).forEach((id) => {\n var _a;\n // only do this for the selected pointer\n const controllerData = this._controllers[id];\n const handData = (_a = controllerData.xrController) === null || _a === void 0 ? void 0 : _a.inputSource.hand;\n // If near interaction is not enabled/available for this controller, return early\n if ((!this._options.enableNearInteractionOnAllControllers && id !== this._attachedController) ||\n !controllerData.xrController ||\n (!handData && (!this._options.nearInteractionControllerMode || !controllerData.xrController.inputSource.gamepad))) {\n controllerData.pick = null;\n return;\n }\n controllerData.hoverInteraction = false;\n controllerData.nearInteraction = false;\n // Every frame check collisions/input\n if (controllerData.xrController) {\n if (handData) {\n const xrIndexTip = handData.get(\"index-finger-tip\");\n if (xrIndexTip) {\n const indexTipPose = _xrFrame.getJointPose(xrIndexTip, this._xrSessionManager.referenceSpace);\n if (indexTipPose && indexTipPose.transform) {\n const axisRHSMultiplier = this._scene.useRightHandedSystem ? 1 : -1;\n TmpVectors.Vector3[0].set(indexTipPose.transform.position.x, indexTipPose.transform.position.y, indexTipPose.transform.position.z * axisRHSMultiplier);\n TmpVectors.Quaternion[0].set(indexTipPose.transform.orientation.x, indexTipPose.transform.orientation.y, indexTipPose.transform.orientation.z * axisRHSMultiplier, indexTipPose.transform.orientation.w * axisRHSMultiplier);\n this._processTouchPoint(id, TmpVectors.Vector3[0], TmpVectors.Quaternion[0]);\n }\n }\n }\n else if (controllerData.xrController.inputSource.gamepad && this._options.nearInteractionControllerMode !== WebXRNearControllerMode.DISABLED) {\n let controllerPose = controllerData.xrController.pointer;\n if (controllerData.xrController.grip && this._options.nearInteractionControllerMode === WebXRNearControllerMode.CENTERED_ON_CONTROLLER) {\n controllerPose = controllerData.xrController.grip;\n }\n this._processTouchPoint(id, controllerPose.position, controllerPose.rotationQuaternion);\n }\n }\n else {\n return;\n }\n const accuratePickInfo = (originalScenePick, utilityScenePick) => {\n let pick = null;\n if (!utilityScenePick || !utilityScenePick.hit) {\n // No hit in utility scene\n pick = originalScenePick;\n }\n else if (!originalScenePick || !originalScenePick.hit) {\n // No hit in original scene\n pick = utilityScenePick;\n }\n else if (utilityScenePick.distance < originalScenePick.distance) {\n // Hit is closer in utility scene\n pick = utilityScenePick;\n }\n else {\n // Hit is closer in original scene\n pick = originalScenePick;\n }\n return pick;\n };\n const populateNearInteractionInfo = (nearInteractionInfo) => {\n let result = new PickingInfo();\n let nearInteractionAtOrigin = false;\n const nearInteraction = nearInteractionInfo && nearInteractionInfo.pickedPoint && nearInteractionInfo.hit;\n if (nearInteractionInfo === null || nearInteractionInfo === void 0 ? void 0 : nearInteractionInfo.pickedPoint) {\n nearInteractionAtOrigin = nearInteractionInfo.pickedPoint.x === 0 && nearInteractionInfo.pickedPoint.y === 0 && nearInteractionInfo.pickedPoint.z === 0;\n }\n if (nearInteraction && !nearInteractionAtOrigin) {\n result = nearInteractionInfo;\n }\n return result;\n };\n // Don't perform touch logic while grabbing, to prevent triggering touch interactions while in the middle of a grab interaction\n // Dont update cursor logic either - the cursor should already be visible for the grab to be in range,\n // and in order to maintain its position on the target mesh it is parented for the duration of the grab.\n if (!controllerData.grabInteraction) {\n let pick = null;\n // near interaction hover\n let utilitySceneHoverPick = null;\n if (this._options.useUtilityLayer && this._utilityLayerScene) {\n utilitySceneHoverPick = this._pickWithSphere(controllerData, this._hoverRadius, this._utilityLayerScene, (mesh) => this._nearInteractionPredicate(mesh));\n }\n const originalSceneHoverPick = this._pickWithSphere(controllerData, this._hoverRadius, this._scene, (mesh) => this._nearInteractionPredicate(mesh));\n const hoverPickInfo = accuratePickInfo(originalSceneHoverPick, utilitySceneHoverPick);\n if (hoverPickInfo && hoverPickInfo.hit) {\n pick = populateNearInteractionInfo(hoverPickInfo);\n if (pick.hit) {\n controllerData.hoverInteraction = true;\n }\n }\n // near interaction pick\n if (controllerData.hoverInteraction) {\n let utilitySceneNearPick = null;\n const radius = handData ? this._pickRadius : this._controllerPickRadius;\n if (this._options.useUtilityLayer && this._utilityLayerScene) {\n utilitySceneNearPick = this._pickWithSphere(controllerData, radius, this._utilityLayerScene, (mesh) => this._nearPickPredicate(mesh));\n }\n const originalSceneNearPick = this._pickWithSphere(controllerData, radius, this._scene, (mesh) => this._nearPickPredicate(mesh));\n const pickInfo = accuratePickInfo(originalSceneNearPick, utilitySceneNearPick);\n const nearPick = populateNearInteractionInfo(pickInfo);\n if (nearPick.hit) {\n // Near pick takes precedence over hover interaction\n pick = nearPick;\n controllerData.nearInteraction = true;\n }\n }\n controllerData.stalePick = controllerData.pick;\n controllerData.pick = pick;\n // Update mesh under pointer\n if (controllerData.pick && controllerData.pick.pickedPoint && controllerData.pick.hit) {\n controllerData.meshUnderPointer = controllerData.pick.pickedMesh;\n controllerData.pickedPointVisualCue.position.copyFrom(controllerData.pick.pickedPoint);\n controllerData.pickedPointVisualCue.isVisible = true;\n if (this._farInteractionFeature && this._farInteractionFeature.attached) {\n this._farInteractionFeature._setPointerSelectionDisabledByPointerId(controllerData.id, true);\n }\n }\n else {\n controllerData.meshUnderPointer = null;\n controllerData.pickedPointVisualCue.isVisible = false;\n if (this._farInteractionFeature && this._farInteractionFeature.attached) {\n this._farInteractionFeature._setPointerSelectionDisabledByPointerId(controllerData.id, false);\n }\n }\n }\n // Update the interaction animation. Only updates if the visible touch mesh is active\n let state = ControllerOrbAnimationState.DEHYDRATED;\n if (controllerData.grabInteraction || controllerData.nearInteraction) {\n state = ControllerOrbAnimationState.TOUCH;\n }\n else if (controllerData.hoverInteraction) {\n state = ControllerOrbAnimationState.HOVER;\n }\n this._handleTransitionAnimation(controllerData, state);\n });\n }\n get _utilityLayerScene() {\n return this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene;\n }\n _generateVisualCue() {\n const sceneToRenderTo = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._scene;\n const selectionMesh = CreateSphere(\"nearInteraction\", {\n diameter: 0.0035 * 3,\n }, sceneToRenderTo);\n selectionMesh.bakeCurrentTransformIntoVertices();\n selectionMesh.isPickable = false;\n selectionMesh.isVisible = false;\n selectionMesh.rotationQuaternion = Quaternion.Identity();\n const targetMat = new StandardMaterial(\"targetMat\", sceneToRenderTo);\n targetMat.specularColor = Color3.Black();\n targetMat.emissiveColor = this.selectionMeshDefaultColor;\n targetMat.backFaceCulling = false;\n selectionMesh.material = targetMat;\n return selectionMesh;\n }\n _isControllerReadyForNearInteraction(id) {\n if (this._farInteractionFeature) {\n return this._farInteractionFeature._getPointerSelectionDisabledByPointerId(id);\n }\n return true;\n }\n _attachNearInteractionMode(xrController) {\n const controllerData = this._controllers[xrController.uniqueId];\n const pointerEventInit = {\n pointerId: controllerData.id,\n pointerType: \"xr-near\",\n };\n controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {\n if ((!this._options.enableNearInteractionOnAllControllers && xrController.uniqueId !== this._attachedController) ||\n !controllerData.xrController ||\n (!controllerData.xrController.inputSource.hand && (!this._options.nearInteractionControllerMode || !controllerData.xrController.inputSource.gamepad))) {\n return;\n }\n if (controllerData.pick) {\n controllerData.pick.ray = controllerData.grabRay;\n }\n if (controllerData.pick && this._isControllerReadyForNearInteraction(controllerData.id)) {\n this._scene.simulatePointerMove(controllerData.pick, pointerEventInit);\n }\n // Near pick pointer event\n if (controllerData.nearInteraction && controllerData.pick && controllerData.pick.hit) {\n if (!controllerData.nearInteractionTargetMesh) {\n this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);\n controllerData.nearInteractionTargetMesh = controllerData.meshUnderPointer;\n }\n }\n else if (controllerData.nearInteractionTargetMesh && controllerData.stalePick) {\n this._scene.simulatePointerUp(controllerData.stalePick, pointerEventInit);\n controllerData.nearInteractionTargetMesh = null;\n }\n });\n const grabCheck = (pressed) => {\n if (this._options.enableNearInteractionOnAllControllers ||\n (xrController.uniqueId === this._attachedController && this._isControllerReadyForNearInteraction(controllerData.id))) {\n if (controllerData.pick) {\n controllerData.pick.ray = controllerData.grabRay;\n }\n if (pressed && controllerData.pick && controllerData.meshUnderPointer && this._nearGrabPredicate(controllerData.meshUnderPointer)) {\n controllerData.grabInteraction = true;\n controllerData.pickedPointVisualCue.isVisible = false;\n this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);\n }\n else if (!pressed && controllerData.pick && controllerData.grabInteraction) {\n this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);\n controllerData.grabInteraction = false;\n controllerData.pickedPointVisualCue.isVisible = true;\n }\n }\n else {\n if (pressed && !this._options.enableNearInteractionOnAllControllers && !this._options.disableSwitchOnClick) {\n this._attachedController = xrController.uniqueId;\n }\n }\n };\n if (xrController.inputSource.gamepad) {\n const init = (motionController) => {\n controllerData.squeezeComponent = motionController.getComponent(\"grasp\");\n if (controllerData.squeezeComponent) {\n controllerData.onSqueezeButtonChangedObserver = controllerData.squeezeComponent.onButtonStateChangedObservable.add((component) => {\n if (component.changes.pressed) {\n const pressed = component.changes.pressed.current;\n grabCheck(pressed);\n }\n });\n }\n else {\n controllerData.selectionComponent = motionController.getMainComponent();\n controllerData.onButtonChangedObserver = controllerData.selectionComponent.onButtonStateChangedObservable.add((component) => {\n if (component.changes.pressed) {\n const pressed = component.changes.pressed.current;\n grabCheck(pressed);\n }\n });\n }\n };\n if (xrController.motionController) {\n init(xrController.motionController);\n }\n else {\n xrController.onMotionControllerInitObservable.add(init);\n }\n }\n else {\n // use the select and squeeze events\n const selectStartListener = (event) => {\n if (controllerData.xrController &&\n event.inputSource === controllerData.xrController.inputSource &&\n controllerData.pick &&\n this._isControllerReadyForNearInteraction(controllerData.id) &&\n controllerData.meshUnderPointer &&\n this._nearGrabPredicate(controllerData.meshUnderPointer)) {\n controllerData.grabInteraction = true;\n controllerData.pickedPointVisualCue.isVisible = false;\n this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);\n }\n };\n const selectEndListener = (event) => {\n if (controllerData.xrController &&\n event.inputSource === controllerData.xrController.inputSource &&\n controllerData.pick &&\n this._isControllerReadyForNearInteraction(controllerData.id)) {\n this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);\n controllerData.grabInteraction = false;\n controllerData.pickedPointVisualCue.isVisible = true;\n }\n };\n controllerData.eventListeners = {\n selectend: selectEndListener,\n selectstart: selectStartListener,\n };\n this._xrSessionManager.session.addEventListener(\"selectstart\", selectStartListener);\n this._xrSessionManager.session.addEventListener(\"selectend\", selectEndListener);\n }\n }\n _detachController(xrControllerUniqueId) {\n const controllerData = this._controllers[xrControllerUniqueId];\n if (!controllerData) {\n return;\n }\n if (controllerData.squeezeComponent) {\n if (controllerData.onSqueezeButtonChangedObserver) {\n controllerData.squeezeComponent.onButtonStateChangedObservable.remove(controllerData.onSqueezeButtonChangedObserver);\n }\n }\n if (controllerData.selectionComponent) {\n if (controllerData.onButtonChangedObserver) {\n controllerData.selectionComponent.onButtonStateChangedObservable.remove(controllerData.onButtonChangedObserver);\n }\n }\n if (controllerData.onFrameObserver) {\n this._xrSessionManager.onXRFrameObservable.remove(controllerData.onFrameObserver);\n }\n if (controllerData.eventListeners) {\n Object.keys(controllerData.eventListeners).forEach((eventName) => {\n const func = controllerData.eventListeners && controllerData.eventListeners[eventName];\n if (func) {\n this._xrSessionManager.session.removeEventListener(eventName, func);\n }\n });\n }\n controllerData.touchCollisionMesh.dispose();\n controllerData.pickedPointVisualCue.dispose();\n this._xrSessionManager.runInXRFrame(() => {\n // Fire a pointerup\n const pointerEventInit = {\n pointerId: controllerData.id,\n pointerType: \"xr-near\",\n };\n this._scene.simulatePointerUp(new PickingInfo(), pointerEventInit);\n });\n // remove from the map\n delete this._controllers[xrControllerUniqueId];\n if (this._attachedController === xrControllerUniqueId) {\n // check for other controllers\n const keys = Object.keys(this._controllers);\n if (keys.length) {\n this._attachedController = keys[0];\n }\n else {\n this._attachedController = \"\";\n }\n }\n }\n _generateNewTouchPointMesh() {\n // populate information for near hover, pick and pinch\n const meshCreationScene = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._scene;\n const touchCollisionMesh = CreateSphere(\"PickSphere\", { diameter: 1 }, meshCreationScene);\n touchCollisionMesh.isVisible = false;\n // Generate the material for the touch mesh visuals\n if (this._options.motionControllerOrbMaterial) {\n touchCollisionMesh.material = this._options.motionControllerOrbMaterial;\n }\n else {\n NodeMaterial.ParseFromSnippetAsync(\"8RUNKL#3\", meshCreationScene).then((nodeMaterial) => {\n touchCollisionMesh.material = nodeMaterial;\n });\n }\n const easingFunction = new QuadraticEase();\n easingFunction.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT);\n // Adjust the visual size based off of the size of the touch collision orb.\n // Having the size perfectly match for hover gives a more accurate tell for when the user will start interacting with the target\n // Sizes for other states are somewhat arbitrary, as they are based on what feels nice during an interaction\n const hoverSizeVec = new Vector3(this._controllerPickRadius, this._controllerPickRadius, this._controllerPickRadius);\n const touchSize = this._controllerPickRadius * (4 / 3);\n const touchSizeVec = new Vector3(touchSize, touchSize, touchSize);\n const hydrateTransitionSize = this._controllerPickRadius * (7 / 6);\n const hydrateTransitionSizeVec = new Vector3(hydrateTransitionSize, hydrateTransitionSize, hydrateTransitionSize);\n const touchHoverTransitionSize = this._controllerPickRadius * (4 / 5);\n const touchHoverTransitionSizeVec = new Vector3(touchHoverTransitionSize, touchHoverTransitionSize, touchHoverTransitionSize);\n const hoverTouchTransitionSize = this._controllerPickRadius * (3 / 2);\n const hoverTouchTransitionSizeVec = new Vector3(hoverTouchTransitionSize, hoverTouchTransitionSize, hoverTouchTransitionSize);\n const touchKeys = [\n { frame: 0, value: hoverSizeVec },\n { frame: 10, value: hoverTouchTransitionSizeVec },\n { frame: 18, value: touchSizeVec },\n ];\n const releaseKeys = [\n { frame: 0, value: touchSizeVec },\n { frame: 10, value: touchHoverTransitionSizeVec },\n { frame: 18, value: hoverSizeVec },\n ];\n const hydrateKeys = [\n { frame: 0, value: Vector3.ZeroReadOnly },\n { frame: 12, value: hydrateTransitionSizeVec },\n { frame: 15, value: hoverSizeVec },\n ];\n const dehydrateKeys = [\n { frame: 0, value: hoverSizeVec },\n { frame: 10, value: Vector3.ZeroReadOnly },\n { frame: 15, value: Vector3.ZeroReadOnly },\n ];\n const touchAction = new Animation(\"touch\", \"scaling\", 60, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT);\n const releaseAction = new Animation(\"release\", \"scaling\", 60, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT);\n const hydrateAction = new Animation(\"hydrate\", \"scaling\", 60, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT);\n const dehydrateAction = new Animation(\"dehydrate\", \"scaling\", 60, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT);\n touchAction.setEasingFunction(easingFunction);\n releaseAction.setEasingFunction(easingFunction);\n hydrateAction.setEasingFunction(easingFunction);\n dehydrateAction.setEasingFunction(easingFunction);\n touchAction.setKeys(touchKeys);\n releaseAction.setKeys(releaseKeys);\n hydrateAction.setKeys(hydrateKeys);\n dehydrateAction.setKeys(dehydrateKeys);\n const touchCollisionMeshFunction = (isTouch) => {\n const action = isTouch ? touchAction : releaseAction;\n meshCreationScene.beginDirectAnimation(touchCollisionMesh, [action], 0, 18, false, 1);\n };\n const hydrateCollisionMeshFunction = (isHydration) => {\n const action = isHydration ? hydrateAction : dehydrateAction;\n if (isHydration) {\n touchCollisionMesh.isVisible = true;\n }\n meshCreationScene.beginDirectAnimation(touchCollisionMesh, [action], 0, 15, false, 1, () => {\n if (!isHydration) {\n touchCollisionMesh.isVisible = false;\n }\n });\n };\n return { touchCollisionMesh, touchCollisionMeshFunction, hydrateCollisionMeshFunction };\n }\n _pickWithSphere(controllerData, radius, sceneToUse, predicate) {\n const pickingInfo = new PickingInfo();\n pickingInfo.distance = +Infinity;\n if (controllerData.touchCollisionMesh && controllerData.xrController) {\n const position = controllerData.touchCollisionMesh.position;\n const sphere = BoundingSphere.CreateFromCenterAndRadius(position, radius);\n for (let meshIndex = 0; meshIndex < sceneToUse.meshes.length; meshIndex++) {\n const mesh = sceneToUse.meshes[meshIndex];\n if (!predicate(mesh) || !this._controllerAvailablePredicate(mesh, controllerData.xrController.uniqueId)) {\n continue;\n }\n const result = WebXRNearInteraction.PickMeshWithSphere(mesh, sphere);\n if (result && result.hit && result.distance < pickingInfo.distance) {\n pickingInfo.hit = result.hit;\n pickingInfo.pickedMesh = mesh;\n pickingInfo.pickedPoint = result.pickedPoint;\n pickingInfo.aimTransform = controllerData.xrController.pointer;\n pickingInfo.gripTransform = controllerData.xrController.grip || null;\n pickingInfo.originMesh = controllerData.touchCollisionMesh;\n pickingInfo.distance = result.distance;\n }\n }\n }\n return pickingInfo;\n }\n /**\n * Picks a mesh with a sphere\n * @param mesh the mesh to pick\n * @param sphere picking sphere in world coordinates\n * @param skipBoundingInfo a boolean indicating if we should skip the bounding info check\n * @returns the picking info\n */\n static PickMeshWithSphere(mesh, sphere, skipBoundingInfo = false) {\n const subMeshes = mesh.subMeshes;\n const pi = new PickingInfo();\n const boundingInfo = mesh.getBoundingInfo();\n if (!mesh._generatePointsArray()) {\n return pi;\n }\n if (!mesh.subMeshes || !boundingInfo) {\n return pi;\n }\n if (!skipBoundingInfo && !BoundingSphere.Intersects(boundingInfo.boundingSphere, sphere)) {\n return pi;\n }\n const result = TmpVectors.Vector3[0];\n const tmpVec = TmpVectors.Vector3[1];\n let distance = +Infinity;\n let tmp, tmpDistanceSphereToCenter, tmpDistanceSurfaceToCenter;\n const center = TmpVectors.Vector3[2];\n const worldToMesh = TmpVectors.Matrix[0];\n worldToMesh.copyFrom(mesh.getWorldMatrix());\n worldToMesh.invert();\n Vector3.TransformCoordinatesToRef(sphere.center, worldToMesh, center);\n for (let index = 0; index < subMeshes.length; index++) {\n const subMesh = subMeshes[index];\n subMesh.projectToRef(center, mesh._positions, mesh.getIndices(), tmpVec);\n Vector3.TransformCoordinatesToRef(tmpVec, mesh.getWorldMatrix(), tmpVec);\n tmp = Vector3.Distance(tmpVec, sphere.center);\n // Check for finger inside of mesh\n tmpDistanceSurfaceToCenter = Vector3.Distance(tmpVec, mesh.getAbsolutePosition());\n tmpDistanceSphereToCenter = Vector3.Distance(sphere.center, mesh.getAbsolutePosition());\n if (tmpDistanceSphereToCenter !== -1 && tmpDistanceSurfaceToCenter !== -1 && tmpDistanceSurfaceToCenter > tmpDistanceSphereToCenter) {\n tmp = 0;\n tmpVec.copyFrom(sphere.center);\n }\n if (tmp !== -1 && tmp < distance) {\n distance = tmp;\n result.copyFrom(tmpVec);\n }\n }\n if (distance < sphere.radius) {\n pi.hit = true;\n pi.distance = distance;\n pi.pickedMesh = mesh;\n pi.pickedPoint = result.clone();\n }\n return pi;\n }\n}\nWebXRNearInteraction._IdCounter = 200;\n/**\n * The module's name\n */\nWebXRNearInteraction.Name = WebXRFeatureName.NEAR_INTERACTION;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRNearInteraction.Version = 1;\n//Register the plugin\nWebXRFeaturesManager.AddWebXRFeature(WebXRNearInteraction.Name, (xrSessionManager, options) => {\n return () => new WebXRNearInteraction(xrSessionManager, options);\n}, WebXRNearInteraction.Version, true);\n//# sourceMappingURL=WebXRNearInteraction.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { WebXRState } from \"./webXRTypes.js\";\nimport { Tools } from \"../Misc/tools.js\";\n/**\n * Button which can be used to enter a different mode of XR\n */\nexport class WebXREnterExitUIButton {\n /**\n * Creates a WebXREnterExitUIButton\n * @param element button element\n * @param sessionMode XR initialization session mode\n * @param referenceSpaceType the type of reference space to be used\n */\n constructor(\n /** button element */\n element, \n /** XR initialization options for the button */\n sessionMode, \n /** Reference space type */\n referenceSpaceType) {\n this.element = element;\n this.sessionMode = sessionMode;\n this.referenceSpaceType = referenceSpaceType;\n }\n /**\n * Extendable function which can be used to update the button's visuals when the state changes\n * @param activeButton the current active button in the UI\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n update(activeButton) { }\n}\n/**\n * Options to create the webXR UI\n */\nexport class WebXREnterExitUIOptions {\n}\n/**\n * UI to allow the user to enter/exit XR mode\n */\nexport class WebXREnterExitUI {\n /**\n * Construct a new EnterExit UI class\n *\n * @param _scene babylon scene object to use\n * @param options (read-only) version of the options passed to this UI\n */\n constructor(_scene, \n /** version of the options passed to this UI */\n options) {\n this._scene = _scene;\n this.options = options;\n this._activeButton = null;\n this._buttons = [];\n /**\n * Fired every time the active button is changed.\n *\n * When xr is entered via a button that launches xr that button will be the callback parameter\n *\n * When exiting xr the callback parameter will be null)\n */\n this.activeButtonChangedObservable = new Observable();\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this._onSessionGranted = (evt) => {\n // This section is for future reference.\n // As per specs, evt.session.mode should have the supported session mode, but no browser supports it for now.\n // // check if the session granted is the same as the one requested\n // const grantedMode = (evt.session as any).mode;\n // if (grantedMode) {\n // this._buttons.some((btn, idx) => {\n // if (btn.sessionMode === grantedMode) {\n // this._enterXRWithButtonIndex(idx);\n // return true;\n // }\n // return false;\n // });\n // } else\n if (this._helper) {\n this._enterXRWithButtonIndex(0);\n }\n };\n this.overlay = document.createElement(\"div\");\n this.overlay.classList.add(\"xr-button-overlay\");\n // prepare for session granted event\n if (!options.ignoreSessionGrantedEvent && navigator.xr) {\n navigator.xr.addEventListener(\"sessiongranted\", this._onSessionGranted);\n }\n // if served over HTTP, warn people.\n // Hopefully the browsers will catch up\n if (typeof window !== \"undefined\") {\n if (window.location && window.location.protocol === \"http:\" && window.location.hostname !== \"localhost\") {\n Tools.Warn(\"WebXR can only be served over HTTPS\");\n throw new Error(\"WebXR can only be served over HTTPS\");\n }\n }\n if (options.customButtons) {\n this._buttons = options.customButtons;\n }\n else {\n this.overlay.style.cssText = \"z-index:11;position: absolute; right: 20px;bottom: 50px;\";\n const sessionMode = options.sessionMode || \"immersive-vr\";\n const referenceSpaceType = options.referenceSpaceType || \"local-floor\";\n const url = typeof SVGSVGElement === \"undefined\"\n ? \"https://cdn.babylonjs.com/Assets/vrButton.png\"\n : \"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A\";\n let css = \".babylonVRicon { color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(\" +\n url +\n \"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }\";\n css += '.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: \"EXIT\"} .xr-error::after { content: \"ERROR\"}';\n const style = document.createElement(\"style\");\n style.appendChild(document.createTextNode(css));\n document.getElementsByTagName(\"head\")[0].appendChild(style);\n const hmdBtn = document.createElement(\"button\");\n hmdBtn.className = \"babylonVRicon\";\n hmdBtn.title = `${sessionMode} - ${referenceSpaceType}`;\n this._buttons.push(new WebXREnterExitUIButton(hmdBtn, sessionMode, referenceSpaceType));\n this._buttons[this._buttons.length - 1].update = function (activeButton) {\n this.element.style.display = activeButton === null || activeButton === this ? \"\" : \"none\";\n hmdBtn.className = \"babylonVRicon\" + (activeButton === this ? \" vrdisplaypresenting\" : \"\");\n };\n this._updateButtons(null);\n }\n const renderCanvas = _scene.getEngine().getInputElement();\n if (renderCanvas && renderCanvas.parentNode) {\n renderCanvas.parentNode.appendChild(this.overlay);\n _scene.onDisposeObservable.addOnce(() => {\n this.dispose();\n });\n }\n }\n /**\n * Set the helper to be used with this UI component.\n * The UI is bound to an experience helper. If not provided the UI can still be used but the events should be registered by the developer.\n *\n * @param helper the experience helper to attach\n * @param renderTarget an optional render target (in case it is created outside of the helper scope)\n * @returns a promise that resolves when the ui is ready\n */\n async setHelperAsync(helper, renderTarget) {\n this._helper = helper;\n this._renderTarget = renderTarget;\n const supportedPromises = this._buttons.map((btn) => {\n return helper.sessionManager.isSessionSupportedAsync(btn.sessionMode);\n });\n helper.onStateChangedObservable.add((state) => {\n if (state == WebXRState.NOT_IN_XR) {\n this._updateButtons(null);\n }\n });\n const results = await Promise.all(supportedPromises);\n results.forEach((supported, i) => {\n if (supported) {\n this.overlay.appendChild(this._buttons[i].element);\n this._buttons[i].element.onclick = this._enterXRWithButtonIndex.bind(this, i);\n }\n else {\n Tools.Warn(`Session mode \"${this._buttons[i].sessionMode}\" not supported in browser`);\n }\n });\n }\n /**\n * Creates UI to allow the user to enter/exit XR mode\n * @param scene the scene to add the ui to\n * @param helper the xr experience helper to enter/exit xr with\n * @param options options to configure the UI\n * @returns the created ui\n */\n static async CreateAsync(scene, helper, options) {\n const ui = new WebXREnterExitUI(scene, options);\n await ui.setHelperAsync(helper, options.renderTarget || undefined);\n return ui;\n }\n async _enterXRWithButtonIndex(idx = 0) {\n if (this._helper.state == WebXRState.IN_XR) {\n await this._helper.exitXRAsync();\n this._updateButtons(null);\n }\n else if (this._helper.state == WebXRState.NOT_IN_XR) {\n try {\n await this._helper.enterXRAsync(this._buttons[idx].sessionMode, this._buttons[idx].referenceSpaceType, this._renderTarget, {\n optionalFeatures: this.options.optionalFeatures,\n requiredFeatures: this.options.requiredFeatures,\n });\n this._updateButtons(this._buttons[idx]);\n }\n catch (e) {\n // make sure button is visible\n this._updateButtons(null);\n const element = this._buttons[idx].element;\n const prevTitle = element.title;\n element.title = \"Error entering XR session : \" + prevTitle;\n element.classList.add(\"xr-error\");\n if (this.options.onError) {\n this.options.onError(e);\n }\n }\n }\n }\n /**\n * Disposes of the XR UI component\n */\n dispose() {\n const renderCanvas = this._scene.getEngine().getInputElement();\n if (renderCanvas && renderCanvas.parentNode && renderCanvas.parentNode.contains(this.overlay)) {\n renderCanvas.parentNode.removeChild(this.overlay);\n }\n this.activeButtonChangedObservable.clear();\n navigator.xr.removeEventListener(\"sessiongranted\", this._onSessionGranted);\n }\n _updateButtons(activeButton) {\n this._activeButton = activeButton;\n this._buttons.forEach((b) => {\n b.update(this._activeButton);\n });\n this.activeButtonChangedObservable.notifyObservers(this._activeButton);\n }\n}\n//# sourceMappingURL=webXREnterExitUI.js.map","import { Observable } from \"../Misc/observable.js\";\n/**\n * The current state of the timer\n */\nexport var TimerState;\n(function (TimerState) {\n /**\n * Timer initialized, not yet started\n */\n TimerState[TimerState[\"INIT\"] = 0] = \"INIT\";\n /**\n * Timer started and counting\n */\n TimerState[TimerState[\"STARTED\"] = 1] = \"STARTED\";\n /**\n * Timer ended (whether aborted or time reached)\n */\n TimerState[TimerState[\"ENDED\"] = 2] = \"ENDED\";\n})(TimerState || (TimerState = {}));\n/**\n * A simple version of the timer. Will take options and start the timer immediately after calling it\n *\n * @param options options with which to initialize this timer\n */\nexport function setAndStartTimer(options) {\n var _a;\n let timer = 0;\n const startTime = Date.now();\n options.observableParameters = (_a = options.observableParameters) !== null && _a !== void 0 ? _a : {};\n const observer = options.contextObservable.add((payload) => {\n const now = Date.now();\n timer = now - startTime;\n const data = {\n startTime,\n currentTime: now,\n deltaTime: timer,\n completeRate: timer / options.timeout,\n payload,\n };\n options.onTick && options.onTick(data);\n if (options.breakCondition && options.breakCondition()) {\n options.contextObservable.remove(observer);\n options.onAborted && options.onAborted(data);\n }\n if (timer >= options.timeout) {\n options.contextObservable.remove(observer);\n options.onEnded && options.onEnded(data);\n }\n }, options.observableParameters.mask, options.observableParameters.insertFirst, options.observableParameters.scope);\n return observer;\n}\n/**\n * An advanced implementation of a timer class\n */\nexport class AdvancedTimer {\n /**\n * Will construct a new advanced timer based on the options provided. Timer will not start until start() is called.\n * @param options construction options for this advanced timer\n */\n constructor(options) {\n var _a, _b;\n /**\n * Will notify each time the timer calculates the remaining time\n */\n this.onEachCountObservable = new Observable();\n /**\n * Will trigger when the timer was aborted due to the break condition\n */\n this.onTimerAbortedObservable = new Observable();\n /**\n * Will trigger when the timer ended successfully\n */\n this.onTimerEndedObservable = new Observable();\n /**\n * Will trigger when the timer state has changed\n */\n this.onStateChangedObservable = new Observable();\n this._observer = null;\n this._breakOnNextTick = false;\n this._tick = (payload) => {\n const now = Date.now();\n this._timer = now - this._startTime;\n const data = {\n startTime: this._startTime,\n currentTime: now,\n deltaTime: this._timer,\n completeRate: this._timer / this._timeToEnd,\n payload,\n };\n const shouldBreak = this._breakOnNextTick || this._breakCondition(data);\n if (shouldBreak || this._timer >= this._timeToEnd) {\n this._stop(data, shouldBreak);\n }\n else {\n this.onEachCountObservable.notifyObservers(data);\n }\n };\n this._setState(TimerState.INIT);\n this._contextObservable = options.contextObservable;\n this._observableParameters = (_a = options.observableParameters) !== null && _a !== void 0 ? _a : {};\n this._breakCondition = (_b = options.breakCondition) !== null && _b !== void 0 ? _b : (() => false);\n this._timeToEnd = options.timeout;\n if (options.onEnded) {\n this.onTimerEndedObservable.add(options.onEnded);\n }\n if (options.onTick) {\n this.onEachCountObservable.add(options.onTick);\n }\n if (options.onAborted) {\n this.onTimerAbortedObservable.add(options.onAborted);\n }\n }\n /**\n * set a breaking condition for this timer. Default is to never break during count\n * @param predicate the new break condition. Returns true to break, false otherwise\n */\n set breakCondition(predicate) {\n this._breakCondition = predicate;\n }\n /**\n * Reset ALL associated observables in this advanced timer\n */\n clearObservables() {\n this.onEachCountObservable.clear();\n this.onTimerAbortedObservable.clear();\n this.onTimerEndedObservable.clear();\n this.onStateChangedObservable.clear();\n }\n /**\n * Will start a new iteration of this timer. Only one instance of this timer can run at a time.\n *\n * @param timeToEnd how much time to measure until timer ended\n */\n start(timeToEnd = this._timeToEnd) {\n if (this._state === TimerState.STARTED) {\n throw new Error(\"Timer already started. Please stop it before starting again\");\n }\n this._timeToEnd = timeToEnd;\n this._startTime = Date.now();\n this._timer = 0;\n this._observer = this._contextObservable.add(this._tick, this._observableParameters.mask, this._observableParameters.insertFirst, this._observableParameters.scope);\n this._setState(TimerState.STARTED);\n }\n /**\n * Will force a stop on the next tick.\n */\n stop() {\n if (this._state !== TimerState.STARTED) {\n return;\n }\n this._breakOnNextTick = true;\n }\n /**\n * Dispose this timer, clearing all resources\n */\n dispose() {\n if (this._observer) {\n this._contextObservable.remove(this._observer);\n }\n this.clearObservables();\n }\n _setState(newState) {\n this._state = newState;\n this.onStateChangedObservable.notifyObservers(this._state);\n }\n _stop(data, aborted = false) {\n this._contextObservable.remove(this._observer);\n this._setState(TimerState.ENDED);\n if (aborted) {\n this.onTimerAbortedObservable.notifyObservers(data);\n }\n else {\n this.onTimerEndedObservable.notifyObservers(data);\n }\n }\n}\n//# sourceMappingURL=timer.js.map","import { WebXRFeaturesManager, WebXRFeatureName } from \"../webXRFeaturesManager.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { WebXRControllerComponent } from \"../motionController/webXRControllerComponent.js\";\nimport { Vector3, Quaternion } from \"../../Maths/math.vector.js\";\nimport { Ray } from \"../../Culling/ray.js\";\nimport { DynamicTexture } from \"../../Materials/Textures/dynamicTexture.js\";\nimport { CreateCylinder } from \"../../Meshes/Builders/cylinderBuilder.js\";\nimport { SineEase, EasingFunction } from \"../../Animations/easing.js\";\nimport { Animation } from \"../../Animations/animation.js\";\nimport { Axis } from \"../../Maths/math.axis.js\";\nimport { StandardMaterial } from \"../../Materials/standardMaterial.js\";\nimport { CreateGround } from \"../../Meshes/Builders/groundBuilder.js\";\nimport { CreateTorus } from \"../../Meshes/Builders/torusBuilder.js\";\nimport { Curve3 } from \"../../Maths/math.path.js\";\nimport { CreateLines } from \"../../Meshes/Builders/linesBuilder.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nimport { Color3, Color4 } from \"../../Maths/math.color.js\";\nimport { UtilityLayerRenderer } from \"../../Rendering/utilityLayerRenderer.js\";\nimport { PointerEventTypes } from \"../../Events/pointerEvents.js\";\nimport { setAndStartTimer } from \"../../Misc/timer.js\";\n/**\n * This is a teleportation feature to be used with WebXR-enabled motion controllers.\n * When enabled and attached, the feature will allow a user to move around and rotate in the scene using\n * the input of the attached controllers.\n */\nexport class WebXRMotionControllerTeleportation extends WebXRAbstractFeature {\n /**\n * Is rotation enabled when moving forward?\n * Disabling this feature will prevent the user from deciding the direction when teleporting\n */\n get rotationEnabled() {\n return this._rotationEnabled;\n }\n /**\n * Sets whether rotation is enabled or not\n * @param enabled is rotation enabled when teleportation is shown\n */\n set rotationEnabled(enabled) {\n this._rotationEnabled = enabled;\n if (this._options.teleportationTargetMesh) {\n const children = this._options.teleportationTargetMesh.getChildMeshes(false, (node) => node.name === \"rotationCone\");\n if (children[0]) {\n children[0].setEnabled(enabled);\n }\n }\n }\n /**\n * Exposes the currently set teleportation target mesh.\n */\n get teleportationTargetMesh() {\n return this._options.teleportationTargetMesh || null;\n }\n /**\n * constructs a new teleportation system\n * @param _xrSessionManager an instance of WebXRSessionManager\n * @param _options configuration object for this feature\n */\n constructor(_xrSessionManager, _options) {\n super(_xrSessionManager);\n this._options = _options;\n this._controllers = {};\n this._snappedToPoint = false;\n this._cachedColor4White = new Color4(1, 1, 1, 1);\n this._tmpRay = new Ray(new Vector3(), new Vector3());\n this._tmpVector = new Vector3();\n this._tmpQuaternion = new Quaternion();\n /**\n * Skip the next teleportation. This can be controlled by the user to prevent the user from teleportation\n * to sections that are not yet \"unlocked\", but should still show the teleportation mesh.\n */\n this.skipNextTeleportation = false;\n /**\n * Is movement backwards enabled\n */\n this.backwardsMovementEnabled = true;\n /**\n * Distance to travel when moving backwards\n */\n this.backwardsTeleportationDistance = 0.7;\n /**\n * The distance from the user to the inspection point in the direction of the controller\n * A higher number will allow the user to move further\n * defaults to 5 (meters, in xr units)\n */\n this.parabolicCheckRadius = 5;\n /**\n * Should the module support parabolic ray on top of direct ray\n * If enabled, the user will be able to point \"at the sky\" and move according to predefined radius distance\n * Very helpful when moving between floors / different heights\n */\n this.parabolicRayEnabled = true;\n /**\n * The second type of ray - straight line.\n * Should it be enabled or should the parabolic line be the only one.\n */\n this.straightRayEnabled = true;\n /**\n * How much rotation should be applied when rotating right and left\n */\n this.rotationAngle = Math.PI / 8;\n /**\n * This observable will notify when the target mesh position was updated.\n * The picking info it provides contains the point to which the target mesh will move ()\n */\n this.onTargetMeshPositionUpdatedObservable = new Observable();\n /**\n * Is teleportation enabled. Can be used to allow rotation only.\n */\n this.teleportationEnabled = true;\n this._rotationEnabled = true;\n this._attachController = (xrController) => {\n if (this._controllers[xrController.uniqueId] || (this._options.forceHandedness && xrController.inputSource.handedness !== this._options.forceHandedness)) {\n // already attached\n return;\n }\n this._controllers[xrController.uniqueId] = {\n xrController,\n teleportationState: {\n forward: false,\n backwards: false,\n rotating: false,\n currentRotation: 0,\n baseRotation: 0,\n blocked: false,\n },\n };\n const controllerData = this._controllers[xrController.uniqueId];\n // motion controller only available to gamepad-enabled input sources.\n if (controllerData.xrController.inputSource.targetRayMode === \"tracked-pointer\" && controllerData.xrController.inputSource.gamepad) {\n // motion controller support\n const initMotionController = () => {\n if (xrController.motionController) {\n const movementController = xrController.motionController.getComponentOfType(WebXRControllerComponent.THUMBSTICK_TYPE) ||\n xrController.motionController.getComponentOfType(WebXRControllerComponent.TOUCHPAD_TYPE);\n if (!movementController || this._options.useMainComponentOnly) {\n // use trigger to move on long press\n const mainComponent = xrController.motionController.getMainComponent();\n if (!mainComponent) {\n return;\n }\n controllerData.teleportationComponent = mainComponent;\n controllerData.onButtonChangedObserver = mainComponent.onButtonStateChangedObservable.add(() => {\n if (!this.teleportationEnabled) {\n return;\n }\n // did \"pressed\" changed?\n if (mainComponent.changes.pressed) {\n if (mainComponent.changes.pressed.current) {\n // simulate \"forward\" thumbstick push\n controllerData.teleportationState.forward = true;\n this._currentTeleportationControllerId = controllerData.xrController.uniqueId;\n controllerData.teleportationState.baseRotation = this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y;\n controllerData.teleportationState.currentRotation = 0;\n const timeToSelect = this._options.timeToTeleport || 3000;\n setAndStartTimer({\n timeout: timeToSelect,\n contextObservable: this._xrSessionManager.onXRFrameObservable,\n breakCondition: () => !mainComponent.pressed,\n onEnded: () => {\n if (this._currentTeleportationControllerId === controllerData.xrController.uniqueId && controllerData.teleportationState.forward) {\n this._teleportForward(xrController.uniqueId);\n }\n },\n });\n }\n else {\n controllerData.teleportationState.forward = false;\n this._currentTeleportationControllerId = \"\";\n }\n }\n });\n }\n else {\n controllerData.teleportationComponent = movementController;\n // use thumbstick (or touchpad if thumbstick not available)\n controllerData.onAxisChangedObserver = movementController.onAxisValueChangedObservable.add((axesData) => {\n if (axesData.y <= 0.7 && controllerData.teleportationState.backwards) {\n controllerData.teleportationState.backwards = false;\n }\n if (axesData.y > 0.7 && !controllerData.teleportationState.forward && this.backwardsMovementEnabled && !this.snapPointsOnly) {\n // teleport backwards\n // General gist: Go Back N units, cast a ray towards the floor. If collided, move.\n if (!controllerData.teleportationState.backwards) {\n controllerData.teleportationState.backwards = true;\n // teleport backwards ONCE\n this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion);\n this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector);\n // get only the y rotation\n this._tmpVector.x = 0;\n this._tmpVector.z = 0;\n // get the quaternion\n Quaternion.FromEulerVectorToRef(this._tmpVector, this._tmpQuaternion);\n this._tmpVector.set(0, 0, this.backwardsTeleportationDistance * (this._xrSessionManager.scene.useRightHandedSystem ? 1.0 : -1.0));\n this._tmpVector.rotateByQuaternionToRef(this._tmpQuaternion, this._tmpVector);\n this._tmpVector.addInPlace(this._options.xrInput.xrCamera.position);\n this._tmpRay.origin.copyFrom(this._tmpVector);\n // This will prevent the user from \"falling\" to a lower platform!\n // TODO - should this be a flag? 'allow falling to lower platforms'?\n this._tmpRay.length = this._options.xrInput.xrCamera.realWorldHeight + 0.1;\n // Right handed system had here \"1\" instead of -1. This is unneeded.\n this._tmpRay.direction.set(0, -1, 0);\n const pick = this._xrSessionManager.scene.pickWithRay(this._tmpRay, (o) => {\n return this._floorMeshes.indexOf(o) !== -1;\n });\n // pick must exist, but stay safe\n if (pick && pick.pickedPoint) {\n // Teleport the users feet to where they targeted. Ignore the Y axis.\n // If the \"falling to lower platforms\" feature is implemented the Y axis should be set here as well\n this._options.xrInput.xrCamera.position.x = pick.pickedPoint.x;\n this._options.xrInput.xrCamera.position.z = pick.pickedPoint.z;\n }\n }\n }\n if (axesData.y < -0.7 && !this._currentTeleportationControllerId && !controllerData.teleportationState.rotating && this.teleportationEnabled) {\n controllerData.teleportationState.forward = true;\n this._currentTeleportationControllerId = controllerData.xrController.uniqueId;\n controllerData.teleportationState.baseRotation = this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y;\n }\n if (axesData.x) {\n if (!controllerData.teleportationState.forward) {\n if (!controllerData.teleportationState.rotating && Math.abs(axesData.x) > 0.7) {\n // rotate in the right direction positive is right\n controllerData.teleportationState.rotating = true;\n const rotation = this.rotationAngle * (axesData.x > 0 ? 1 : -1) * (this._xrSessionManager.scene.useRightHandedSystem ? -1 : 1);\n Quaternion.FromEulerAngles(0, rotation, 0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion, this._options.xrInput.xrCamera.rotationQuaternion);\n }\n }\n else {\n if (this._currentTeleportationControllerId === controllerData.xrController.uniqueId) {\n // set the rotation of the forward movement\n if (this.rotationEnabled) {\n setTimeout(() => {\n controllerData.teleportationState.currentRotation = Math.atan2(axesData.x, axesData.y * (this._xrSessionManager.scene.useRightHandedSystem ? 1 : -1));\n });\n }\n else {\n controllerData.teleportationState.currentRotation = 0;\n }\n }\n }\n }\n else {\n controllerData.teleportationState.rotating = false;\n }\n if (axesData.x === 0 && axesData.y === 0) {\n if (controllerData.teleportationState.blocked) {\n controllerData.teleportationState.blocked = false;\n this._setTargetMeshVisibility(false);\n }\n if (controllerData.teleportationState.forward) {\n this._teleportForward(xrController.uniqueId);\n }\n }\n });\n }\n }\n };\n if (xrController.motionController) {\n initMotionController();\n }\n else {\n xrController.onMotionControllerInitObservable.addOnce(() => {\n initMotionController();\n });\n }\n }\n else {\n this._xrSessionManager.scene.onPointerObservable.add((pointerInfo) => {\n if (pointerInfo.type === PointerEventTypes.POINTERDOWN) {\n controllerData.teleportationState.forward = true;\n this._currentTeleportationControllerId = controllerData.xrController.uniqueId;\n controllerData.teleportationState.baseRotation = this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y;\n controllerData.teleportationState.currentRotation = 0;\n const timeToSelect = this._options.timeToTeleport || 3000;\n setAndStartTimer({\n timeout: timeToSelect,\n contextObservable: this._xrSessionManager.onXRFrameObservable,\n onEnded: () => {\n if (this._currentTeleportationControllerId === controllerData.xrController.uniqueId && controllerData.teleportationState.forward) {\n this._teleportForward(xrController.uniqueId);\n }\n },\n });\n }\n else if (pointerInfo.type === PointerEventTypes.POINTERUP) {\n controllerData.teleportationState.forward = false;\n this._currentTeleportationControllerId = \"\";\n }\n });\n }\n };\n // create default mesh if not provided\n if (!this._options.teleportationTargetMesh) {\n this._createDefaultTargetMesh();\n }\n this._floorMeshes = this._options.floorMeshes || [];\n this._snapToPositions = this._options.snapPositions || [];\n this._blockedRayColor = this._options.blockedRayColor || new Color4(1, 0, 0, 0.75);\n this._setTargetMeshVisibility(false);\n }\n /**\n * Get the snapPointsOnly flag\n */\n get snapPointsOnly() {\n return !!this._options.snapPointsOnly;\n }\n /**\n * Sets the snapPointsOnly flag\n * @param snapToPoints should teleportation be exclusively to snap points\n */\n set snapPointsOnly(snapToPoints) {\n this._options.snapPointsOnly = snapToPoints;\n }\n /**\n * Add a new mesh to the floor meshes array\n * @param mesh the mesh to use as floor mesh\n */\n addFloorMesh(mesh) {\n this._floorMeshes.push(mesh);\n }\n /**\n * Add a mesh to the list of meshes blocking the teleportation ray\n * @param mesh The mesh to add to the teleportation-blocking meshes\n */\n addBlockerMesh(mesh) {\n this._options.pickBlockerMeshes = this._options.pickBlockerMeshes || [];\n this._options.pickBlockerMeshes.push(mesh);\n }\n /**\n * Add a new snap-to point to fix teleportation to this position\n * @param newSnapPoint The new Snap-To point\n */\n addSnapPoint(newSnapPoint) {\n this._snapToPositions.push(newSnapPoint);\n }\n attach() {\n if (!super.attach()) {\n return false;\n }\n // Safety reset\n this._currentTeleportationControllerId = \"\";\n this._options.xrInput.controllers.forEach(this._attachController);\n this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController);\n this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, (controller) => {\n // REMOVE the controller\n this._detachController(controller.uniqueId);\n });\n return true;\n }\n detach() {\n if (!super.detach()) {\n return false;\n }\n Object.keys(this._controllers).forEach((controllerId) => {\n this._detachController(controllerId);\n });\n this._setTargetMeshVisibility(false);\n this._currentTeleportationControllerId = \"\";\n this._controllers = {};\n return true;\n }\n dispose() {\n super.dispose();\n this._options.teleportationTargetMesh && this._options.teleportationTargetMesh.dispose(false, true);\n }\n /**\n * Remove a mesh from the floor meshes array\n * @param mesh the mesh to remove\n */\n removeFloorMesh(mesh) {\n const index = this._floorMeshes.indexOf(mesh);\n if (index !== -1) {\n this._floorMeshes.splice(index, 1);\n }\n }\n /**\n * Remove a mesh from the blocker meshes array\n * @param mesh the mesh to remove\n */\n removeBlockerMesh(mesh) {\n this._options.pickBlockerMeshes = this._options.pickBlockerMeshes || [];\n const index = this._options.pickBlockerMeshes.indexOf(mesh);\n if (index !== -1) {\n this._options.pickBlockerMeshes.splice(index, 1);\n }\n }\n /**\n * Remove a mesh from the floor meshes array using its name\n * @param name the mesh name to remove\n */\n removeFloorMeshByName(name) {\n const mesh = this._xrSessionManager.scene.getMeshByName(name);\n if (mesh) {\n this.removeFloorMesh(mesh);\n }\n }\n /**\n * This function will iterate through the array, searching for this point or equal to it. It will then remove it from the snap-to array\n * @param snapPointToRemove the point (or a clone of it) to be removed from the array\n * @returns was the point found and removed or not\n */\n removeSnapPoint(snapPointToRemove) {\n // check if the object is in the array\n let index = this._snapToPositions.indexOf(snapPointToRemove);\n // if not found as an object, compare to the points\n if (index === -1) {\n for (let i = 0; i < this._snapToPositions.length; ++i) {\n // equals? index is i, break the loop\n if (this._snapToPositions[i].equals(snapPointToRemove)) {\n index = i;\n break;\n }\n }\n }\n // index is not -1? remove the object\n if (index !== -1) {\n this._snapToPositions.splice(index, 1);\n return true;\n }\n return false;\n }\n /**\n * This function sets a selection feature that will be disabled when\n * the forward ray is shown and will be reattached when hidden.\n * This is used to remove the selection rays when moving.\n * @param selectionFeature the feature to disable when forward movement is enabled\n */\n setSelectionFeature(selectionFeature) {\n this._selectionFeature = selectionFeature;\n }\n _onXRFrame(_xrFrame) {\n const frame = this._xrSessionManager.currentFrame;\n const scene = this._xrSessionManager.scene;\n if (!this.attach || !frame) {\n return;\n }\n // render target if needed\n const targetMesh = this._options.teleportationTargetMesh;\n if (this._currentTeleportationControllerId) {\n if (!targetMesh) {\n return;\n }\n targetMesh.rotationQuaternion = targetMesh.rotationQuaternion || new Quaternion();\n const controllerData = this._controllers[this._currentTeleportationControllerId];\n if (controllerData && controllerData.teleportationState.forward) {\n // set the rotation\n Quaternion.RotationYawPitchRollToRef(controllerData.teleportationState.currentRotation + controllerData.teleportationState.baseRotation, 0, 0, targetMesh.rotationQuaternion);\n // set the ray and position\n let hitPossible = false;\n controllerData.xrController.getWorldPointerRayToRef(this._tmpRay);\n if (this.straightRayEnabled) {\n // first check if direct ray possible\n // pick grounds that are LOWER only. upper will use parabolic path\n const pick = scene.pickWithRay(this._tmpRay, (o) => {\n // check for mesh-blockers\n if (this._options.pickBlockerMeshes && this._options.pickBlockerMeshes.indexOf(o) !== -1) {\n return true;\n }\n const index = this._floorMeshes.indexOf(o);\n if (index === -1) {\n return false;\n }\n return this._floorMeshes[index].absolutePosition.y < this._options.xrInput.xrCamera.globalPosition.y;\n });\n if (pick && pick.pickedMesh && this._options.pickBlockerMeshes && this._options.pickBlockerMeshes.indexOf(pick.pickedMesh) !== -1) {\n controllerData.teleportationState.blocked = true;\n this._setTargetMeshVisibility(false);\n this._showParabolicPath(pick);\n return;\n }\n else if (pick && pick.pickedPoint) {\n controllerData.teleportationState.blocked = false;\n hitPossible = true;\n this._setTargetMeshPosition(pick);\n this._setTargetMeshVisibility(true);\n this._showParabolicPath(pick);\n }\n }\n // straight ray is still the main ray, but disabling the straight line will force parabolic line.\n if (this.parabolicRayEnabled && !hitPossible) {\n // radius compensation according to pointer rotation around X\n const xRotation = controllerData.xrController.pointer.rotationQuaternion.toEulerAngles().x;\n const compensation = 1 + (Math.PI / 2 - Math.abs(xRotation));\n // check parabolic ray\n const radius = this.parabolicCheckRadius * compensation;\n this._tmpRay.origin.addToRef(this._tmpRay.direction.scale(radius * 2), this._tmpVector);\n this._tmpVector.y = this._tmpRay.origin.y;\n this._tmpRay.origin.addInPlace(this._tmpRay.direction.scale(radius));\n this._tmpVector.subtractToRef(this._tmpRay.origin, this._tmpRay.direction);\n this._tmpRay.direction.normalize();\n const pick = scene.pickWithRay(this._tmpRay, (o) => {\n // check for mesh-blockers\n if (this._options.pickBlockerMeshes && this._options.pickBlockerMeshes.indexOf(o) !== -1) {\n return true;\n }\n return this._floorMeshes.indexOf(o) !== -1;\n });\n if (pick && pick.pickedMesh && this._options.pickBlockerMeshes && this._options.pickBlockerMeshes.indexOf(pick.pickedMesh) !== -1) {\n controllerData.teleportationState.blocked = true;\n this._setTargetMeshVisibility(false);\n this._showParabolicPath(pick);\n return;\n }\n else if (pick && pick.pickedPoint) {\n controllerData.teleportationState.blocked = false;\n hitPossible = true;\n this._setTargetMeshPosition(pick);\n this._setTargetMeshVisibility(true);\n this._showParabolicPath(pick);\n }\n }\n // if needed, set visible:\n this._setTargetMeshVisibility(hitPossible);\n }\n else {\n this._setTargetMeshVisibility(false);\n }\n }\n else {\n this._disposeBezierCurve();\n this._setTargetMeshVisibility(false);\n }\n }\n _createDefaultTargetMesh() {\n // set defaults\n this._options.defaultTargetMeshOptions = this._options.defaultTargetMeshOptions || {};\n const sceneToRenderTo = this._options.useUtilityLayer\n ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene\n : this._xrSessionManager.scene;\n const teleportationTarget = CreateGround(\"teleportationTarget\", { width: 2, height: 2, subdivisions: 2 }, sceneToRenderTo);\n teleportationTarget.isPickable = false;\n if (this._options.defaultTargetMeshOptions.teleportationCircleMaterial) {\n teleportationTarget.material = this._options.defaultTargetMeshOptions.teleportationCircleMaterial;\n }\n else {\n const length = 512;\n const dynamicTexture = new DynamicTexture(\"teleportationPlaneDynamicTexture\", length, sceneToRenderTo, true);\n dynamicTexture.hasAlpha = true;\n const context = dynamicTexture.getContext();\n const centerX = length / 2;\n const centerY = length / 2;\n const radius = 200;\n context.beginPath();\n context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);\n context.fillStyle = this._options.defaultTargetMeshOptions.teleportationFillColor || \"#444444\";\n context.fill();\n context.lineWidth = 10;\n context.strokeStyle = this._options.defaultTargetMeshOptions.teleportationBorderColor || \"#FFFFFF\";\n context.stroke();\n context.closePath();\n dynamicTexture.update();\n const teleportationCircleMaterial = new StandardMaterial(\"teleportationPlaneMaterial\", sceneToRenderTo);\n teleportationCircleMaterial.diffuseTexture = dynamicTexture;\n teleportationTarget.material = teleportationCircleMaterial;\n }\n const torus = CreateTorus(\"torusTeleportation\", {\n diameter: 0.75,\n thickness: 0.1,\n tessellation: 20,\n }, sceneToRenderTo);\n torus.isPickable = false;\n torus.parent = teleportationTarget;\n if (!this._options.defaultTargetMeshOptions.disableAnimation) {\n const animationInnerCircle = new Animation(\"animationInnerCircle\", \"position.y\", 30, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CYCLE);\n const keys = [];\n keys.push({\n frame: 0,\n value: 0,\n });\n keys.push({\n frame: 30,\n value: 0.4,\n });\n keys.push({\n frame: 60,\n value: 0,\n });\n animationInnerCircle.setKeys(keys);\n const easingFunction = new SineEase();\n easingFunction.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT);\n animationInnerCircle.setEasingFunction(easingFunction);\n torus.animations = [];\n torus.animations.push(animationInnerCircle);\n sceneToRenderTo.beginAnimation(torus, 0, 60, true);\n }\n const cone = CreateCylinder(\"rotationCone\", { diameterTop: 0, tessellation: 4 }, sceneToRenderTo);\n cone.isPickable = false;\n cone.scaling.set(0.5, 0.12, 0.2);\n cone.rotate(Axis.X, Math.PI / 2);\n cone.position.z = 0.6;\n cone.parent = torus;\n if (this._options.defaultTargetMeshOptions.torusArrowMaterial) {\n torus.material = this._options.defaultTargetMeshOptions.torusArrowMaterial;\n cone.material = this._options.defaultTargetMeshOptions.torusArrowMaterial;\n }\n else {\n const torusConeMaterial = new StandardMaterial(\"torusConsMat\", sceneToRenderTo);\n torusConeMaterial.disableLighting = !!this._options.defaultTargetMeshOptions.disableLighting;\n if (torusConeMaterial.disableLighting) {\n torusConeMaterial.emissiveColor = new Color3(0.3, 0.3, 1.0);\n }\n else {\n torusConeMaterial.diffuseColor = new Color3(0.3, 0.3, 1.0);\n }\n torusConeMaterial.alpha = 0.9;\n torus.material = torusConeMaterial;\n cone.material = torusConeMaterial;\n this._teleportationRingMaterial = torusConeMaterial;\n }\n if (this._options.renderingGroupId !== undefined) {\n teleportationTarget.renderingGroupId = this._options.renderingGroupId;\n torus.renderingGroupId = this._options.renderingGroupId;\n cone.renderingGroupId = this._options.renderingGroupId;\n }\n this._options.teleportationTargetMesh = teleportationTarget;\n // hide the teleportation target mesh right after creating it.\n this._setTargetMeshVisibility(false);\n }\n _detachController(xrControllerUniqueId) {\n const controllerData = this._controllers[xrControllerUniqueId];\n if (!controllerData) {\n return;\n }\n if (controllerData.teleportationComponent) {\n if (controllerData.onAxisChangedObserver) {\n controllerData.teleportationComponent.onAxisValueChangedObservable.remove(controllerData.onAxisChangedObserver);\n }\n if (controllerData.onButtonChangedObserver) {\n controllerData.teleportationComponent.onButtonStateChangedObservable.remove(controllerData.onButtonChangedObserver);\n }\n }\n // remove from the map\n delete this._controllers[xrControllerUniqueId];\n }\n _findClosestSnapPointWithRadius(realPosition, radius = this._options.snapToPositionRadius || 0.8) {\n let closestPoint = null;\n let closestDistance = Number.MAX_VALUE;\n if (this._snapToPositions.length) {\n const radiusSquared = radius * radius;\n this._snapToPositions.forEach((position) => {\n const dist = Vector3.DistanceSquared(position, realPosition);\n if (dist <= radiusSquared && dist < closestDistance) {\n closestDistance = dist;\n closestPoint = position;\n }\n });\n }\n return closestPoint;\n }\n _setTargetMeshPosition(pickInfo) {\n const newPosition = pickInfo.pickedPoint;\n if (!this._options.teleportationTargetMesh || !newPosition) {\n return;\n }\n const snapPosition = this._findClosestSnapPointWithRadius(newPosition);\n this._snappedToPoint = !!snapPosition;\n if (this.snapPointsOnly && !this._snappedToPoint && this._teleportationRingMaterial) {\n this._teleportationRingMaterial.diffuseColor.set(1.0, 0.3, 0.3);\n }\n else if (this.snapPointsOnly && this._snappedToPoint && this._teleportationRingMaterial) {\n this._teleportationRingMaterial.diffuseColor.set(0.3, 0.3, 1.0);\n }\n this._options.teleportationTargetMesh.position.copyFrom(snapPosition || newPosition);\n this._options.teleportationTargetMesh.position.y += 0.01;\n this.onTargetMeshPositionUpdatedObservable.notifyObservers(pickInfo);\n }\n _setTargetMeshVisibility(visible, force) {\n if (!this._options.teleportationTargetMesh) {\n return;\n }\n if (this._options.teleportationTargetMesh.isVisible === visible && !force) {\n return;\n }\n this._options.teleportationTargetMesh.isVisible = visible;\n this._options.teleportationTargetMesh.getChildren(undefined, false).forEach((m) => {\n m.isVisible = visible;\n });\n if (!visible) {\n if (this._quadraticBezierCurve) {\n this._quadraticBezierCurve.dispose();\n this._quadraticBezierCurve = null;\n }\n if (this._selectionFeature) {\n this._selectionFeature.attach();\n }\n }\n else {\n if (this._selectionFeature) {\n this._selectionFeature.detach();\n }\n }\n }\n _disposeBezierCurve() {\n if (this._quadraticBezierCurve) {\n this._quadraticBezierCurve.dispose();\n this._quadraticBezierCurve = null;\n }\n }\n _showParabolicPath(pickInfo) {\n if (!pickInfo.pickedPoint || !this._currentTeleportationControllerId) {\n return;\n }\n const sceneToRenderTo = this._options.useUtilityLayer\n ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene\n : this._xrSessionManager.scene;\n const controllerData = this._controllers[this._currentTeleportationControllerId];\n const quadraticBezierVectors = Curve3.CreateQuadraticBezier(controllerData.xrController.pointer.absolutePosition, pickInfo.ray.origin, pickInfo.pickedPoint, 25);\n const color = controllerData.teleportationState.blocked ? this._blockedRayColor : undefined;\n const colorsArray = new Array(26).fill(color || this._cachedColor4White);\n if (!this._options.generateRayPathMesh) {\n this._quadraticBezierCurve = CreateLines(\"teleportation path line\", { points: quadraticBezierVectors.getPoints(), instance: this._quadraticBezierCurve, updatable: true, colors: colorsArray }, sceneToRenderTo);\n }\n else {\n this._quadraticBezierCurve = this._options.generateRayPathMesh(quadraticBezierVectors.getPoints(), pickInfo);\n }\n this._quadraticBezierCurve.isPickable = false;\n if (this._options.renderingGroupId !== undefined) {\n this._quadraticBezierCurve.renderingGroupId = this._options.renderingGroupId;\n }\n }\n _teleportForward(controllerId) {\n const controllerData = this._controllers[controllerId];\n if (!controllerData || !controllerData.teleportationState.forward || !this.teleportationEnabled) {\n return;\n }\n controllerData.teleportationState.forward = false;\n this._currentTeleportationControllerId = \"\";\n if (this.snapPointsOnly && !this._snappedToPoint) {\n return;\n }\n if (this.skipNextTeleportation) {\n this.skipNextTeleportation = false;\n return;\n }\n // do the movement forward here\n if (this._options.teleportationTargetMesh && this._options.teleportationTargetMesh.isVisible) {\n const height = this._options.xrInput.xrCamera.realWorldHeight;\n this._options.xrInput.xrCamera.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position);\n this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position);\n this._options.xrInput.xrCamera.position.y += height;\n Quaternion.FromEulerAngles(0, controllerData.teleportationState.currentRotation - (this._xrSessionManager.scene.useRightHandedSystem ? Math.PI : 0), 0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion, this._options.xrInput.xrCamera.rotationQuaternion);\n this._options.xrInput.xrCamera.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position);\n }\n }\n}\n/**\n * The module's name\n */\nWebXRMotionControllerTeleportation.Name = WebXRFeatureName.TELEPORTATION;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the webxr specs version\n */\nWebXRMotionControllerTeleportation.Version = 1;\nWebXRFeaturesManager.AddWebXRFeature(WebXRMotionControllerTeleportation.Name, (xrSessionManager, options) => {\n return () => new WebXRMotionControllerTeleportation(xrSessionManager, options);\n}, WebXRMotionControllerTeleportation.Version, true);\n//# sourceMappingURL=WebXRControllerTeleportation.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { Scene } from \"../scene.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { StandardMaterial } from \"../Materials/standardMaterial.js\";\nimport { PBRMaterial } from \"../Materials/PBR/pbrMaterial.js\";\nimport { HemisphericLight } from \"../Lights/hemisphericLight.js\";\nimport { EnvironmentHelper } from \"./environmentHelper.js\";\nimport { FreeCamera } from \"../Cameras/freeCamera.js\";\nimport { ArcRotateCamera } from \"../Cameras/arcRotateCamera.js\";\nimport { VRExperienceHelper } from \"../Cameras/VR/vrExperienceHelper.js\";\nimport \"../Materials/Textures/Loaders/ddsTextureLoader.js\";\nimport \"../Materials/Textures/Loaders/envTextureLoader.js\";\nimport \"../Materials/Textures/Loaders/ktxTextureLoader.js\";\nimport { CreateBox } from \"../Meshes/Builders/boxBuilder.js\";\nimport { WebXRDefaultExperience } from \"../XR/webXRDefaultExperience.js\";\n/** @internal */\n// eslint-disable-next-line no-var\nexport var _forceSceneHelpersToBundle = true;\nScene.prototype.createDefaultLight = function (replace = false) {\n // Dispose existing light in replace mode.\n if (replace) {\n if (this.lights) {\n for (let i = 0; i < this.lights.length; i++) {\n this.lights[i].dispose();\n }\n }\n }\n // Light\n if (this.lights.length === 0) {\n new HemisphericLight(\"default light\", Vector3.Up(), this);\n }\n};\nScene.prototype.createDefaultCamera = function (createArcRotateCamera = false, replace = false, attachCameraControls = false) {\n // Dispose existing camera in replace mode.\n if (replace) {\n if (this.activeCamera) {\n this.activeCamera.dispose();\n this.activeCamera = null;\n }\n }\n // Camera\n if (!this.activeCamera) {\n const worldExtends = this.getWorldExtends((mesh) => mesh.isVisible && mesh.isEnabled());\n const worldSize = worldExtends.max.subtract(worldExtends.min);\n const worldCenter = worldExtends.min.add(worldSize.scale(0.5));\n let camera;\n let radius = worldSize.length() * 1.5;\n // empty scene scenario!\n if (!isFinite(radius)) {\n radius = 1;\n worldCenter.copyFromFloats(0, 0, 0);\n }\n if (createArcRotateCamera) {\n const arcRotateCamera = new ArcRotateCamera(\"default camera\", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);\n arcRotateCamera.lowerRadiusLimit = radius * 0.01;\n arcRotateCamera.wheelPrecision = 100 / radius;\n camera = arcRotateCamera;\n }\n else {\n const freeCamera = new FreeCamera(\"default camera\", new Vector3(worldCenter.x, worldCenter.y, -radius), this);\n freeCamera.setTarget(worldCenter);\n camera = freeCamera;\n }\n camera.minZ = radius * 0.01;\n camera.maxZ = radius * 1000;\n camera.speed = radius * 0.2;\n this.activeCamera = camera;\n if (attachCameraControls) {\n camera.attachControl();\n }\n }\n};\nScene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera = false, replace = false, attachCameraControls = false) {\n this.createDefaultLight(replace);\n this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);\n};\nScene.prototype.createDefaultSkybox = function (environmentTexture, pbr = false, scale = 1000, blur = 0, setGlobalEnvTexture = true) {\n if (!environmentTexture) {\n Logger.Warn(\"Can not create default skybox without environment texture.\");\n return null;\n }\n if (setGlobalEnvTexture) {\n if (environmentTexture) {\n this.environmentTexture = environmentTexture;\n }\n }\n // Skybox\n const hdrSkybox = CreateBox(\"hdrSkyBox\", { size: scale }, this);\n if (pbr) {\n const hdrSkyboxMaterial = new PBRMaterial(\"skyBox\", this);\n hdrSkyboxMaterial.backFaceCulling = false;\n hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();\n if (hdrSkyboxMaterial.reflectionTexture) {\n hdrSkyboxMaterial.reflectionTexture.coordinatesMode = Texture.SKYBOX_MODE;\n }\n hdrSkyboxMaterial.microSurface = 1.0 - blur;\n hdrSkyboxMaterial.disableLighting = true;\n hdrSkyboxMaterial.twoSidedLighting = true;\n hdrSkybox.material = hdrSkyboxMaterial;\n }\n else {\n const skyboxMaterial = new StandardMaterial(\"skyBox\", this);\n skyboxMaterial.backFaceCulling = false;\n skyboxMaterial.reflectionTexture = environmentTexture.clone();\n if (skyboxMaterial.reflectionTexture) {\n skyboxMaterial.reflectionTexture.coordinatesMode = Texture.SKYBOX_MODE;\n }\n skyboxMaterial.disableLighting = true;\n hdrSkybox.material = skyboxMaterial;\n }\n hdrSkybox.isPickable = false;\n hdrSkybox.infiniteDistance = true;\n hdrSkybox.ignoreCameraMaxZ = true;\n return hdrSkybox;\n};\nScene.prototype.createDefaultEnvironment = function (options) {\n if (EnvironmentHelper) {\n return new EnvironmentHelper(options, this);\n }\n return null;\n};\nScene.prototype.createDefaultVRExperience = function (webVROptions = {}) {\n return new VRExperienceHelper(this, webVROptions);\n};\nScene.prototype.createDefaultXRExperienceAsync = function (options = {}) {\n return WebXRDefaultExperience.CreateAsync(this, options).then((helper) => {\n return helper;\n });\n};\n//# sourceMappingURL=sceneHelpers.js.map","import { WebXRExperienceHelper } from \"./webXRExperienceHelper.js\";\nimport { WebXRInput } from \"./webXRInput.js\";\nimport { WebXRControllerPointerSelection } from \"./features/WebXRControllerPointerSelection.js\";\nimport { WebXRNearInteraction } from \"./features/WebXRNearInteraction.js\";\nimport { WebXREnterExitUI } from \"./webXREnterExitUI.js\";\nimport { WebXRMotionControllerTeleportation } from \"./features/WebXRControllerTeleportation.js\";\nimport { Logger } from \"../Misc/logger.js\";\n/**\n * Options for the default xr helper\n */\nexport class WebXRDefaultExperienceOptions {\n}\n/**\n * Default experience which provides a similar setup to the previous webVRExperience\n */\nexport class WebXRDefaultExperience {\n constructor() { }\n /**\n * Creates the default xr experience\n * @param scene scene\n * @param options options for basic configuration\n * @returns resulting WebXRDefaultExperience\n */\n static CreateAsync(scene, options = {}) {\n const result = new WebXRDefaultExperience();\n scene.onDisposeObservable.addOnce(() => {\n result.dispose();\n });\n // init the UI right after construction\n if (!options.disableDefaultUI) {\n const uiOptions = Object.assign({ renderTarget: result.renderTarget }, (options.uiOptions || {}));\n if (options.optionalFeatures) {\n if (typeof options.optionalFeatures === \"boolean\") {\n uiOptions.optionalFeatures = [\"hit-test\", \"anchors\", \"plane-detection\", \"hand-tracking\"];\n }\n else {\n uiOptions.optionalFeatures = options.optionalFeatures;\n }\n }\n result.enterExitUI = new WebXREnterExitUI(scene, uiOptions);\n }\n // Create base experience\n return WebXRExperienceHelper.CreateAsync(scene)\n .then((xrHelper) => {\n result.baseExperience = xrHelper;\n if (options.ignoreNativeCameraTransformation) {\n result.baseExperience.camera.compensateOnFirstFrame = false;\n }\n // Add controller support\n result.input = new WebXRInput(xrHelper.sessionManager, xrHelper.camera, Object.assign({ controllerOptions: {\n renderingGroupId: options.renderingGroupId,\n } }, (options.inputOptions || {})));\n if (!options.disablePointerSelection) {\n // Add default pointer selection\n const pointerSelectionOptions = Object.assign(Object.assign({}, options.pointerSelectionOptions), { xrInput: result.input, renderingGroupId: options.renderingGroupId });\n result.pointerSelection = (result.baseExperience.featuresManager.enableFeature(WebXRControllerPointerSelection.Name, options.useStablePlugins ? \"stable\" : \"latest\", pointerSelectionOptions));\n if (!options.disableTeleportation) {\n // Add default teleportation, including rotation\n result.teleportation = result.baseExperience.featuresManager.enableFeature(WebXRMotionControllerTeleportation.Name, options.useStablePlugins ? \"stable\" : \"latest\", Object.assign({ floorMeshes: options.floorMeshes, xrInput: result.input, renderingGroupId: options.renderingGroupId }, options.teleportationOptions));\n result.teleportation.setSelectionFeature(result.pointerSelection);\n }\n }\n if (!options.disableNearInteraction) {\n // Add default pointer selection\n result.nearInteraction = result.baseExperience.featuresManager.enableFeature(WebXRNearInteraction.Name, options.useStablePlugins ? \"stable\" : \"latest\", Object.assign({ xrInput: result.input, farInteractionFeature: result.pointerSelection, renderingGroupId: options.renderingGroupId, useUtilityLayer: true, enableNearInteractionOnAllControllers: true }, options.nearInteractionOptions));\n }\n // Create the WebXR output target\n result.renderTarget = result.baseExperience.sessionManager.getWebXRRenderTarget(options.outputCanvasOptions);\n if (!options.disableDefaultUI) {\n // Create ui for entering/exiting xr\n return result.enterExitUI.setHelperAsync(result.baseExperience, result.renderTarget);\n }\n else {\n return;\n }\n })\n .then(() => {\n return result;\n })\n .catch((error) => {\n Logger.Error(\"Error initializing XR\");\n Logger.Error(error);\n return result;\n });\n }\n /**\n * Disposes of the experience helper\n */\n dispose() {\n if (this.baseExperience) {\n this.baseExperience.dispose();\n }\n if (this.input) {\n this.input.dispose();\n }\n if (this.enterExitUI) {\n this.enterExitUI.dispose();\n }\n if (this.renderTarget) {\n this.renderTarget.dispose();\n }\n }\n}\n//# sourceMappingURL=webXRDefaultExperience.js.map","import { Observable } from \"../../Misc/observable.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { Texture } from \"../../Materials/Textures/texture.js\";\n\nimport \"../../Engines/Extensions/engine.videoTexture.js\";\nimport \"../../Engines/Extensions/engine.dynamicTexture.js\";\nfunction removeSource(video) {\n // Remove any elements, etc.\n while (video.firstChild) {\n video.removeChild(video.firstChild);\n }\n // detach srcObject\n video.srcObject = null;\n // Set a blank src (https://html.spec.whatwg.org/multipage/media.html#best-practices-for-authors-using-media-elements)\n video.src = \"\";\n // Prevent non-important errors maybe (https://twitter.com/beraliv/status/1205214277956775936)\n video.removeAttribute(\"src\");\n}\n/**\n * If you want to display a video in your scene, this is the special texture for that.\n * This special texture works similar to other textures, with the exception of a few parameters.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/videoTexture\n */\nexport class VideoTexture extends Texture {\n /**\n * Event triggered when a dom action is required by the user to play the video.\n * This happens due to recent changes in browser policies preventing video to auto start.\n */\n get onUserActionRequestedObservable() {\n if (!this._onUserActionRequestedObservable) {\n this._onUserActionRequestedObservable = new Observable();\n }\n return this._onUserActionRequestedObservable;\n }\n _processError(reason) {\n this._errorFound = true;\n if (this._onError) {\n this._onError(reason === null || reason === void 0 ? void 0 : reason.message);\n }\n else {\n Logger.Error(reason === null || reason === void 0 ? void 0 : reason.message);\n }\n }\n _handlePlay() {\n this._errorFound = false;\n this.video.play().catch((reason) => {\n if ((reason === null || reason === void 0 ? void 0 : reason.name) === \"NotAllowedError\") {\n if (this._onUserActionRequestedObservable && this._onUserActionRequestedObservable.hasObservers()) {\n this._onUserActionRequestedObservable.notifyObservers(this);\n return;\n }\n else if (!this.video.muted) {\n Logger.Warn(\"Unable to autoplay a video with sound. Trying again with muted turned true\");\n this.video.muted = true;\n this._errorFound = false;\n this.video.play().catch((otherReason) => {\n this._processError(otherReason);\n });\n return;\n }\n }\n this._processError(reason);\n });\n }\n /**\n * Creates a video texture.\n * If you want to display a video in your scene, this is the special texture for that.\n * This special texture works similar to other textures, with the exception of a few parameters.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/videoTexture\n * @param name optional name, will detect from video source, if not defined\n * @param src can be used to provide an url, array of urls or an already setup HTML video element.\n * @param scene is obviously the current scene.\n * @param generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).\n * @param invertY is false by default but can be used to invert video on Y axis\n * @param samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default\n * @param settings allows finer control over video usage\n * @param onError defines a callback triggered when an error occurred during the loading session\n * @param format defines the texture format to use (Engine.TEXTUREFORMAT_RGBA by default)\n */\n constructor(name, src, scene, generateMipMaps = false, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, settings = {}, onError, format = 5) {\n var _a, _b;\n super(null, scene, !generateMipMaps, invertY);\n this._onUserActionRequestedObservable = null;\n this._stillImageCaptured = false;\n this._displayingPosterTexture = false;\n this._frameId = -1;\n this._currentSrc = null;\n this._errorFound = false;\n this._resizeInternalTexture = () => {\n var _a;\n // Cleanup the old texture before replacing it\n if (this._texture != null) {\n this._texture.dispose();\n }\n if (!this._getEngine().needPOTTextures || (Tools.IsExponentOfTwo(this.video.videoWidth) && Tools.IsExponentOfTwo(this.video.videoHeight))) {\n this.wrapU = Texture.WRAP_ADDRESSMODE;\n this.wrapV = Texture.WRAP_ADDRESSMODE;\n }\n else {\n this.wrapU = Texture.CLAMP_ADDRESSMODE;\n this.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._generateMipMaps = false;\n }\n this._texture = this._getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this.samplingMode);\n this._texture.format = (_a = this._format) !== null && _a !== void 0 ? _a : 5;\n // Reset the frame ID and update the new texture to ensure it pulls in the current video frame\n this._frameId = -1;\n this._updateInternalTexture();\n };\n this._createInternalTexture = () => {\n if (this._texture != null) {\n if (this._displayingPosterTexture) {\n this._displayingPosterTexture = false;\n }\n else {\n return;\n }\n }\n this.video.addEventListener(\"resize\", this._resizeInternalTexture);\n this._resizeInternalTexture();\n if (!this.video.autoplay && !this._settings.poster && !this._settings.independentVideoSource) {\n const oldHandler = this.video.onplaying;\n const oldMuted = this.video.muted;\n this.video.muted = true;\n this.video.onplaying = () => {\n this.video.muted = oldMuted;\n this.video.onplaying = oldHandler;\n this._updateInternalTexture();\n if (!this._errorFound) {\n this.video.pause();\n }\n if (this.onLoadObservable.hasObservers()) {\n this.onLoadObservable.notifyObservers(this);\n }\n };\n this._handlePlay();\n }\n else {\n this._updateInternalTexture();\n if (this.onLoadObservable.hasObservers()) {\n this.onLoadObservable.notifyObservers(this);\n }\n }\n };\n this._reset = () => {\n if (this._texture == null) {\n return;\n }\n if (!this._displayingPosterTexture) {\n this._texture.dispose();\n this._texture = null;\n }\n };\n this._updateInternalTexture = () => {\n if (this._texture == null) {\n return;\n }\n if (this.video.readyState < this.video.HAVE_CURRENT_DATA) {\n return;\n }\n if (this._displayingPosterTexture) {\n return;\n }\n const frameId = this.getScene().getFrameId();\n if (this._frameId === frameId) {\n return;\n }\n this._frameId = frameId;\n this._getEngine().updateVideoTexture(this._texture, this._externalTexture ? this._externalTexture : this.video, this._invertY);\n };\n this._settings = Object.assign({ autoPlay: true, loop: true, autoUpdateTexture: true }, settings);\n this._onError = onError;\n this._generateMipMaps = generateMipMaps;\n this._initialSamplingMode = samplingMode;\n this.autoUpdateTexture = this._settings.autoUpdateTexture;\n this._currentSrc = src;\n this.name = name || this._getName(src);\n this.video = this._getVideo(src);\n this._externalTexture = (_b = (_a = this._engine) === null || _a === void 0 ? void 0 : _a.createExternalTexture(this.video)) !== null && _b !== void 0 ? _b : null;\n if (!this._settings.independentVideoSource) {\n if (this._settings.poster) {\n this.video.poster = this._settings.poster;\n }\n if (this._settings.autoPlay !== undefined) {\n this.video.autoplay = this._settings.autoPlay;\n }\n if (this._settings.loop !== undefined) {\n this.video.loop = this._settings.loop;\n }\n if (this._settings.muted !== undefined) {\n this.video.muted = this._settings.muted;\n }\n this.video.setAttribute(\"playsinline\", \"\");\n this.video.addEventListener(\"paused\", this._updateInternalTexture);\n this.video.addEventListener(\"seeked\", this._updateInternalTexture);\n this.video.addEventListener(\"emptied\", this._reset);\n if (this._settings.autoPlay) {\n this._handlePlay();\n }\n }\n this._createInternalTextureOnEvent = this._settings.poster && !this._settings.autoPlay ? \"play\" : \"canplay\";\n this.video.addEventListener(this._createInternalTextureOnEvent, this._createInternalTexture);\n this._format = format;\n const videoHasEnoughData = this.video.readyState >= this.video.HAVE_CURRENT_DATA;\n if (this._settings.poster && (!this._settings.autoPlay || !videoHasEnoughData)) {\n this._texture = this._getEngine().createTexture(this._settings.poster, false, !this.invertY, scene);\n this._displayingPosterTexture = true;\n }\n else if (videoHasEnoughData) {\n this._createInternalTexture();\n }\n }\n /**\n * Get the current class name of the video texture useful for serialization or dynamic coding.\n * @returns \"VideoTexture\"\n */\n getClassName() {\n return \"VideoTexture\";\n }\n _getName(src) {\n if (src instanceof HTMLVideoElement) {\n return src.currentSrc;\n }\n if (typeof src === \"object\") {\n return src.toString();\n }\n return src;\n }\n _getVideo(src) {\n if (src.isNative) {\n return src;\n }\n if (src instanceof HTMLVideoElement) {\n Tools.SetCorsBehavior(src.currentSrc, src);\n return src;\n }\n const video = document.createElement(\"video\");\n if (typeof src === \"string\") {\n Tools.SetCorsBehavior(src, video);\n video.src = src;\n }\n else {\n Tools.SetCorsBehavior(src[0], video);\n src.forEach((url) => {\n const source = document.createElement(\"source\");\n source.src = url;\n video.appendChild(source);\n });\n }\n this.onDisposeObservable.addOnce(() => {\n removeSource(video);\n });\n return video;\n }\n /**\n * @internal Internal method to initiate `update`.\n */\n _rebuild() {\n this.update();\n }\n /**\n * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.\n */\n update() {\n if (!this.autoUpdateTexture) {\n // Expecting user to call `updateTexture` manually\n return;\n }\n this.updateTexture(true);\n }\n /**\n * Update Texture in `manual` mode. Does not do anything if not visible or paused.\n * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or otherwise.\n */\n updateTexture(isVisible) {\n if (!isVisible) {\n return;\n }\n if (this.video.paused && this._stillImageCaptured) {\n return;\n }\n this._stillImageCaptured = true;\n this._updateInternalTexture();\n }\n /**\n * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.\n * @param url New url.\n */\n updateURL(url) {\n this.video.src = url;\n this._currentSrc = url;\n }\n /**\n * Clones the texture.\n * @returns the cloned texture\n */\n clone() {\n return new VideoTexture(this.name, this._currentSrc, this.getScene(), this._generateMipMaps, this.invertY, this.samplingMode, this._settings);\n }\n /**\n * Dispose the texture and release its associated resources.\n */\n dispose() {\n var _a;\n super.dispose();\n this._currentSrc = null;\n if (this._onUserActionRequestedObservable) {\n this._onUserActionRequestedObservable.clear();\n this._onUserActionRequestedObservable = null;\n }\n this.video.removeEventListener(this._createInternalTextureOnEvent, this._createInternalTexture);\n if (!this._settings.independentVideoSource) {\n this.video.removeEventListener(\"paused\", this._updateInternalTexture);\n this.video.removeEventListener(\"seeked\", this._updateInternalTexture);\n this.video.removeEventListener(\"emptied\", this._reset);\n this.video.removeEventListener(\"resize\", this._resizeInternalTexture);\n this.video.pause();\n }\n (_a = this._externalTexture) === null || _a === void 0 ? void 0 : _a.dispose();\n }\n /**\n * Creates a video texture straight from a stream.\n * @param scene Define the scene the texture should be created in\n * @param stream Define the stream the texture should be created from\n * @param constraints video constraints\n * @param invertY Defines if the video should be stored with invert Y set to true (true by default)\n * @returns The created video texture as a promise\n */\n static CreateFromStreamAsync(scene, stream, constraints, invertY = true) {\n const video = scene.getEngine().createVideoElement(constraints);\n if (scene.getEngine()._badOS) {\n // Yes... I know and I hope to remove it soon...\n document.body.appendChild(video);\n video.style.transform = \"scale(0.0001, 0.0001)\";\n video.style.opacity = \"0\";\n video.style.position = \"fixed\";\n video.style.bottom = \"0px\";\n video.style.right = \"0px\";\n }\n video.setAttribute(\"autoplay\", \"\");\n video.setAttribute(\"muted\", \"true\");\n video.setAttribute(\"playsinline\", \"\");\n video.muted = true;\n if (video.isNative) {\n // No additional configuration needed for native\n }\n else if (video.mozSrcObject !== undefined) {\n // hack for Firefox < 19\n video.mozSrcObject = stream;\n }\n else {\n if (typeof video.srcObject == \"object\") {\n video.srcObject = stream;\n }\n else {\n // older API. See https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL#using_object_urls_for_media_streams\n video.src = window.URL && window.URL.createObjectURL(stream);\n }\n }\n return new Promise((resolve) => {\n const onPlaying = () => {\n const videoTexture = new VideoTexture(\"video\", video, scene, true, invertY, undefined, undefined, undefined, 4);\n if (scene.getEngine()._badOS) {\n videoTexture.onDisposeObservable.addOnce(() => {\n video.remove();\n });\n }\n videoTexture.onDisposeObservable.addOnce(() => {\n removeSource(video);\n });\n resolve(videoTexture);\n video.removeEventListener(\"playing\", onPlaying);\n };\n video.addEventListener(\"playing\", onPlaying);\n video.play();\n });\n }\n /**\n * Creates a video texture straight from your WebCam video feed.\n * @param scene Define the scene the texture should be created in\n * @param constraints Define the constraints to use to create the web cam feed from WebRTC\n * @param audioConstaints Define the audio constraints to use to create the web cam feed from WebRTC\n * @param invertY Defines if the video should be stored with invert Y set to true (true by default)\n * @returns The created video texture as a promise\n */\n static async CreateFromWebCamAsync(scene, constraints, audioConstaints = false, invertY = true) {\n if (navigator.mediaDevices) {\n const stream = await navigator.mediaDevices.getUserMedia({\n video: constraints,\n audio: audioConstaints,\n });\n const videoTexture = await this.CreateFromStreamAsync(scene, stream, constraints, invertY);\n videoTexture.onDisposeObservable.addOnce(() => {\n stream.getTracks().forEach((track) => {\n track.stop();\n });\n });\n return videoTexture;\n }\n return Promise.reject(\"No support for userMedia on this device\");\n }\n /**\n * Creates a video texture straight from your WebCam video feed.\n * @param scene Defines the scene the texture should be created in\n * @param onReady Defines a callback to triggered once the texture will be ready\n * @param constraints Defines the constraints to use to create the web cam feed from WebRTC\n * @param audioConstaints Defines the audio constraints to use to create the web cam feed from WebRTC\n * @param invertY Defines if the video should be stored with invert Y set to true (true by default)\n */\n static CreateFromWebCam(scene, onReady, constraints, audioConstaints = false, invertY = true) {\n this.CreateFromWebCamAsync(scene, constraints, audioConstaints, invertY)\n .then(function (videoTexture) {\n if (onReady) {\n onReady(videoTexture);\n }\n })\n .catch(function (err) {\n Logger.Error(err.name);\n });\n }\n}\n//# sourceMappingURL=videoTexture.js.map","import { Texture } from \"../Materials/Textures/texture.js\";\nimport { VideoTexture } from \"../Materials/Textures/videoTexture.js\";\nimport { TextureDome } from \"./textureDome.js\";\nimport { PointerEventTypes } from \"../Events/pointerEvents.js\";\n/**\n * Display a 360/180 degree video on an approximately spherical surface, useful for VR applications or skyboxes.\n * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.\n * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.\n * Potential additions to this helper include zoom and and non-infinite distance rendering effects.\n */\nexport class VideoDome extends TextureDome {\n /**\n * Get the video texture associated with this video dome\n */\n get videoTexture() {\n return this._texture;\n }\n /**\n * Get the video mode of this dome\n */\n get videoMode() {\n return this.textureMode;\n }\n /**\n * Set the video mode of this dome.\n * @see textureMode\n */\n set videoMode(value) {\n this.textureMode = value;\n }\n _initTexture(urlsOrElement, scene, options) {\n const tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };\n const texture = new VideoTexture((this.name || \"videoDome\") + \"_texture\", urlsOrElement, scene, options.generateMipMaps, this._useDirectMapping, Texture.TRILINEAR_SAMPLINGMODE, tempOptions);\n // optional configuration\n if (options.clickToPlay) {\n this._pointerObserver = scene.onPointerObservable.add((data) => {\n var _a;\n ((_a = data.pickInfo) === null || _a === void 0 ? void 0 : _a.pickedMesh) === this.mesh && this._texture.video.play();\n }, PointerEventTypes.POINTERDOWN);\n }\n this._textureObserver = texture.onLoadObservable.add(() => {\n this.onLoadObservable.notifyObservers();\n });\n return texture;\n }\n /**\n * Releases resources associated with this node.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n dispose(doNotRecurse, disposeMaterialAndTextures = false) {\n this._texture.onLoadObservable.remove(this._textureObserver);\n this._scene.onPointerObservable.remove(this._pointerObserver);\n super.dispose(doNotRecurse, disposeMaterialAndTextures);\n }\n}\n/**\n * Define the video source as a Monoscopic panoramic 360 video.\n */\nVideoDome.MODE_MONOSCOPIC = TextureDome.MODE_MONOSCOPIC;\n/**\n * Define the video source as a Stereoscopic TopBottom/OverUnder panoramic 360 video.\n */\nVideoDome.MODE_TOPBOTTOM = TextureDome.MODE_TOPBOTTOM;\n/**\n * Define the video source as a Stereoscopic Side by Side panoramic 360 video.\n */\nVideoDome.MODE_SIDEBYSIDE = TextureDome.MODE_SIDEBYSIDE;\n//# sourceMappingURL=videoDome.js.map","export * from \"./environmentHelper.js\";\nexport * from \"./photoDome.js\";\nexport * from \"./sceneHelpers.js\";\nexport * from \"./videoDome.js\";\n//# sourceMappingURL=index.js.map","import { PerfCounter } from \"../Misc/perfCounter.js\";\n/**\n * This class can be used to get instrumentation data from a Babylon engine\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#engineinstrumentation\n */\nexport class EngineInstrumentation {\n // Properties\n /**\n * Gets the perf counter used for GPU frame time\n */\n get gpuFrameTimeCounter() {\n return this.engine.getGPUFrameTimeCounter();\n }\n /**\n * Gets the GPU frame time capture status\n */\n get captureGPUFrameTime() {\n return this._captureGPUFrameTime;\n }\n /**\n * Enable or disable the GPU frame time capture\n */\n set captureGPUFrameTime(value) {\n if (value === this._captureGPUFrameTime) {\n return;\n }\n this._captureGPUFrameTime = value;\n this.engine.captureGPUFrameTime(value);\n }\n /**\n * Gets the perf counter used for shader compilation time\n */\n get shaderCompilationTimeCounter() {\n return this._shaderCompilationTime;\n }\n /**\n * Gets the shader compilation time capture status\n */\n get captureShaderCompilationTime() {\n return this._captureShaderCompilationTime;\n }\n /**\n * Enable or disable the shader compilation time capture\n */\n set captureShaderCompilationTime(value) {\n if (value === this._captureShaderCompilationTime) {\n return;\n }\n this._captureShaderCompilationTime = value;\n if (value) {\n this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(() => {\n this._shaderCompilationTime.fetchNewFrame();\n this._shaderCompilationTime.beginMonitoring();\n });\n this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(() => {\n this._shaderCompilationTime.endMonitoring();\n });\n }\n else {\n this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);\n this._onBeforeShaderCompilationObserver = null;\n this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);\n this._onAfterShaderCompilationObserver = null;\n }\n }\n /**\n * Instantiates a new engine instrumentation.\n * This class can be used to get instrumentation data from a Babylon engine\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#engineinstrumentation\n * @param engine Defines the engine to instrument\n */\n constructor(\n /**\n * Define the instrumented engine.\n */\n engine) {\n this.engine = engine;\n this._captureGPUFrameTime = false;\n this._captureShaderCompilationTime = false;\n this._shaderCompilationTime = new PerfCounter();\n // Observers\n this._onBeginFrameObserver = null;\n this._onEndFrameObserver = null;\n this._onBeforeShaderCompilationObserver = null;\n this._onAfterShaderCompilationObserver = null;\n }\n /**\n * Dispose and release associated resources.\n */\n dispose() {\n this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);\n this._onBeginFrameObserver = null;\n this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);\n this._onEndFrameObserver = null;\n this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);\n this._onBeforeShaderCompilationObserver = null;\n this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);\n this._onAfterShaderCompilationObserver = null;\n this.engine = null;\n }\n}\n//# sourceMappingURL=engineInstrumentation.js.map","import { Tools } from \"../Misc/tools.js\";\nimport { PerfCounter } from \"../Misc/perfCounter.js\";\n/**\n * This class can be used to get instrumentation data from a Babylon engine\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#sceneinstrumentation\n */\nexport class SceneInstrumentation {\n // Properties\n /**\n * Gets the perf counter used for active meshes evaluation time\n */\n get activeMeshesEvaluationTimeCounter() {\n return this._activeMeshesEvaluationTime;\n }\n /**\n * Gets the active meshes evaluation time capture status\n */\n get captureActiveMeshesEvaluationTime() {\n return this._captureActiveMeshesEvaluationTime;\n }\n /**\n * Enable or disable the active meshes evaluation time capture\n */\n set captureActiveMeshesEvaluationTime(value) {\n if (value === this._captureActiveMeshesEvaluationTime) {\n return;\n }\n this._captureActiveMeshesEvaluationTime = value;\n if (value) {\n this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(() => {\n Tools.StartPerformanceCounter(\"Active meshes evaluation\");\n this._activeMeshesEvaluationTime.beginMonitoring();\n });\n this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(() => {\n Tools.EndPerformanceCounter(\"Active meshes evaluation\");\n this._activeMeshesEvaluationTime.endMonitoring(false);\n });\n }\n else {\n this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);\n this._onBeforeActiveMeshesEvaluationObserver = null;\n this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);\n this._onAfterActiveMeshesEvaluationObserver = null;\n }\n }\n /**\n * Gets the perf counter used for render targets render time\n */\n get renderTargetsRenderTimeCounter() {\n return this._renderTargetsRenderTime;\n }\n /**\n * Gets the render targets render time capture status\n */\n get captureRenderTargetsRenderTime() {\n return this._captureRenderTargetsRenderTime;\n }\n /**\n * Enable or disable the render targets render time capture\n */\n set captureRenderTargetsRenderTime(value) {\n if (value === this._captureRenderTargetsRenderTime) {\n return;\n }\n this._captureRenderTargetsRenderTime = value;\n if (value) {\n this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(() => {\n Tools.StartPerformanceCounter(\"Render targets rendering\");\n this._renderTargetsRenderTime.beginMonitoring();\n });\n this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(() => {\n Tools.EndPerformanceCounter(\"Render targets rendering\");\n this._renderTargetsRenderTime.endMonitoring(false);\n });\n }\n else {\n this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);\n this._onBeforeRenderTargetsRenderObserver = null;\n this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);\n this._onAfterRenderTargetsRenderObserver = null;\n }\n }\n /**\n * Gets the perf counter used for particles render time\n */\n get particlesRenderTimeCounter() {\n return this._particlesRenderTime;\n }\n /**\n * Gets the particles render time capture status\n */\n get captureParticlesRenderTime() {\n return this._captureParticlesRenderTime;\n }\n /**\n * Enable or disable the particles render time capture\n */\n set captureParticlesRenderTime(value) {\n if (value === this._captureParticlesRenderTime) {\n return;\n }\n this._captureParticlesRenderTime = value;\n if (value) {\n this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(() => {\n Tools.StartPerformanceCounter(\"Particles\");\n this._particlesRenderTime.beginMonitoring();\n });\n this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(() => {\n Tools.EndPerformanceCounter(\"Particles\");\n this._particlesRenderTime.endMonitoring(false);\n });\n }\n else {\n this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);\n this._onBeforeParticlesRenderingObserver = null;\n this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);\n this._onAfterParticlesRenderingObserver = null;\n }\n }\n /**\n * Gets the perf counter used for sprites render time\n */\n get spritesRenderTimeCounter() {\n return this._spritesRenderTime;\n }\n /**\n * Gets the sprites render time capture status\n */\n get captureSpritesRenderTime() {\n return this._captureSpritesRenderTime;\n }\n /**\n * Enable or disable the sprites render time capture\n */\n set captureSpritesRenderTime(value) {\n if (value === this._captureSpritesRenderTime) {\n return;\n }\n this._captureSpritesRenderTime = value;\n if (!this.scene.spriteManagers) {\n return;\n }\n if (value) {\n this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(() => {\n Tools.StartPerformanceCounter(\"Sprites\");\n this._spritesRenderTime.beginMonitoring();\n });\n this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(() => {\n Tools.EndPerformanceCounter(\"Sprites\");\n this._spritesRenderTime.endMonitoring(false);\n });\n }\n else {\n this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);\n this._onBeforeSpritesRenderingObserver = null;\n this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);\n this._onAfterSpritesRenderingObserver = null;\n }\n }\n /**\n * Gets the perf counter used for physics time\n */\n get physicsTimeCounter() {\n return this._physicsTime;\n }\n /**\n * Gets the physics time capture status\n */\n get capturePhysicsTime() {\n return this._capturePhysicsTime;\n }\n /**\n * Enable or disable the physics time capture\n */\n set capturePhysicsTime(value) {\n if (value === this._capturePhysicsTime) {\n return;\n }\n if (!this.scene.onBeforePhysicsObservable) {\n return;\n }\n this._capturePhysicsTime = value;\n if (value) {\n this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(() => {\n Tools.StartPerformanceCounter(\"Physics\");\n this._physicsTime.beginMonitoring();\n });\n this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(() => {\n Tools.EndPerformanceCounter(\"Physics\");\n this._physicsTime.endMonitoring();\n });\n }\n else {\n this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);\n this._onBeforePhysicsObserver = null;\n this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);\n this._onAfterPhysicsObserver = null;\n }\n }\n /**\n * Gets the perf counter used for animations time\n */\n get animationsTimeCounter() {\n return this._animationsTime;\n }\n /**\n * Gets the animations time capture status\n */\n get captureAnimationsTime() {\n return this._captureAnimationsTime;\n }\n /**\n * Enable or disable the animations time capture\n */\n set captureAnimationsTime(value) {\n if (value === this._captureAnimationsTime) {\n return;\n }\n this._captureAnimationsTime = value;\n if (value) {\n this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(() => {\n this._animationsTime.endMonitoring();\n });\n }\n else {\n this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);\n this._onAfterAnimationsObserver = null;\n }\n }\n /**\n * Gets the perf counter used for frame time capture\n */\n get frameTimeCounter() {\n return this._frameTime;\n }\n /**\n * Gets the frame time capture status\n */\n get captureFrameTime() {\n return this._captureFrameTime;\n }\n /**\n * Enable or disable the frame time capture\n */\n set captureFrameTime(value) {\n this._captureFrameTime = value;\n }\n /**\n * Gets the perf counter used for inter-frames time capture\n */\n get interFrameTimeCounter() {\n return this._interFrameTime;\n }\n /**\n * Gets the inter-frames time capture status\n */\n get captureInterFrameTime() {\n return this._captureInterFrameTime;\n }\n /**\n * Enable or disable the inter-frames time capture\n */\n set captureInterFrameTime(value) {\n this._captureInterFrameTime = value;\n }\n /**\n * Gets the perf counter used for render time capture\n */\n get renderTimeCounter() {\n return this._renderTime;\n }\n /**\n * Gets the render time capture status\n */\n get captureRenderTime() {\n return this._captureRenderTime;\n }\n /**\n * Enable or disable the render time capture\n */\n set captureRenderTime(value) {\n if (value === this._captureRenderTime) {\n return;\n }\n this._captureRenderTime = value;\n if (value) {\n this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(() => {\n this._renderTime.beginMonitoring();\n Tools.StartPerformanceCounter(\"Main render\");\n });\n this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(() => {\n this._renderTime.endMonitoring(false);\n Tools.EndPerformanceCounter(\"Main render\");\n });\n }\n else {\n this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);\n this._onBeforeDrawPhaseObserver = null;\n this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);\n this._onAfterDrawPhaseObserver = null;\n }\n }\n /**\n * Gets the perf counter used for camera render time capture\n */\n get cameraRenderTimeCounter() {\n return this._cameraRenderTime;\n }\n /**\n * Gets the camera render time capture status\n */\n get captureCameraRenderTime() {\n return this._captureCameraRenderTime;\n }\n /**\n * Enable or disable the camera render time capture\n */\n set captureCameraRenderTime(value) {\n if (value === this._captureCameraRenderTime) {\n return;\n }\n this._captureCameraRenderTime = value;\n if (value) {\n this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add((camera) => {\n this._cameraRenderTime.beginMonitoring();\n Tools.StartPerformanceCounter(`Rendering camera ${camera.name}`);\n });\n this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add((camera) => {\n this._cameraRenderTime.endMonitoring(false);\n Tools.EndPerformanceCounter(`Rendering camera ${camera.name}`);\n });\n }\n else {\n this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);\n this._onBeforeCameraRenderObserver = null;\n this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);\n this._onAfterCameraRenderObserver = null;\n }\n }\n /**\n * Gets the perf counter used for draw calls\n */\n get drawCallsCounter() {\n return this.scene.getEngine()._drawCalls;\n }\n /**\n * Instantiates a new scene instrumentation.\n * This class can be used to get instrumentation data from a Babylon engine\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#sceneinstrumentation\n * @param scene Defines the scene to instrument\n */\n constructor(\n /**\n * Defines the scene to instrument\n */\n scene) {\n this.scene = scene;\n this._captureActiveMeshesEvaluationTime = false;\n this._activeMeshesEvaluationTime = new PerfCounter();\n this._captureRenderTargetsRenderTime = false;\n this._renderTargetsRenderTime = new PerfCounter();\n this._captureFrameTime = false;\n this._frameTime = new PerfCounter();\n this._captureRenderTime = false;\n this._renderTime = new PerfCounter();\n this._captureInterFrameTime = false;\n this._interFrameTime = new PerfCounter();\n this._captureParticlesRenderTime = false;\n this._particlesRenderTime = new PerfCounter();\n this._captureSpritesRenderTime = false;\n this._spritesRenderTime = new PerfCounter();\n this._capturePhysicsTime = false;\n this._physicsTime = new PerfCounter();\n this._captureAnimationsTime = false;\n this._animationsTime = new PerfCounter();\n this._captureCameraRenderTime = false;\n this._cameraRenderTime = new PerfCounter();\n // Observers\n this._onBeforeActiveMeshesEvaluationObserver = null;\n this._onAfterActiveMeshesEvaluationObserver = null;\n this._onBeforeRenderTargetsRenderObserver = null;\n this._onAfterRenderTargetsRenderObserver = null;\n this._onAfterRenderObserver = null;\n this._onBeforeDrawPhaseObserver = null;\n this._onAfterDrawPhaseObserver = null;\n this._onBeforeAnimationsObserver = null;\n this._onBeforeParticlesRenderingObserver = null;\n this._onAfterParticlesRenderingObserver = null;\n this._onBeforeSpritesRenderingObserver = null;\n this._onAfterSpritesRenderingObserver = null;\n this._onBeforePhysicsObserver = null;\n this._onAfterPhysicsObserver = null;\n this._onAfterAnimationsObserver = null;\n this._onBeforeCameraRenderObserver = null;\n this._onAfterCameraRenderObserver = null;\n // Before render\n this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(() => {\n if (this._captureActiveMeshesEvaluationTime) {\n this._activeMeshesEvaluationTime.fetchNewFrame();\n }\n if (this._captureRenderTargetsRenderTime) {\n this._renderTargetsRenderTime.fetchNewFrame();\n }\n if (this._captureFrameTime) {\n Tools.StartPerformanceCounter(\"Scene rendering\");\n this._frameTime.beginMonitoring();\n }\n if (this._captureInterFrameTime) {\n this._interFrameTime.endMonitoring();\n }\n if (this._captureParticlesRenderTime) {\n this._particlesRenderTime.fetchNewFrame();\n }\n if (this._captureSpritesRenderTime) {\n this._spritesRenderTime.fetchNewFrame();\n }\n if (this._captureAnimationsTime) {\n this._animationsTime.beginMonitoring();\n }\n if (this._captureRenderTime) {\n this._renderTime.fetchNewFrame();\n }\n if (this._captureCameraRenderTime) {\n this._cameraRenderTime.fetchNewFrame();\n }\n this.scene.getEngine()._drawCalls.fetchNewFrame();\n });\n // After render\n this._onAfterRenderObserver = scene.onAfterRenderObservable.add(() => {\n if (this._captureFrameTime) {\n Tools.EndPerformanceCounter(\"Scene rendering\");\n this._frameTime.endMonitoring();\n }\n if (this._captureRenderTime) {\n this._renderTime.endMonitoring(false);\n }\n if (this._captureInterFrameTime) {\n this._interFrameTime.beginMonitoring();\n }\n if (this._captureActiveMeshesEvaluationTime) {\n this._activeMeshesEvaluationTime.endFrame();\n }\n if (this._captureRenderTargetsRenderTime) {\n this._renderTargetsRenderTime.endFrame();\n }\n if (this._captureParticlesRenderTime) {\n this._particlesRenderTime.endFrame();\n }\n if (this._captureSpritesRenderTime) {\n this._spritesRenderTime.endFrame();\n }\n if (this._captureRenderTime) {\n this._renderTime.endFrame();\n }\n if (this._captureCameraRenderTime) {\n this._cameraRenderTime.endFrame();\n }\n });\n }\n /**\n * Dispose and release associated resources.\n */\n dispose() {\n this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);\n this._onAfterRenderObserver = null;\n this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);\n this._onBeforeActiveMeshesEvaluationObserver = null;\n this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);\n this._onAfterActiveMeshesEvaluationObserver = null;\n this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);\n this._onBeforeRenderTargetsRenderObserver = null;\n this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);\n this._onAfterRenderTargetsRenderObserver = null;\n this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);\n this._onBeforeAnimationsObserver = null;\n this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);\n this._onBeforeParticlesRenderingObserver = null;\n this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);\n this._onAfterParticlesRenderingObserver = null;\n if (this._onBeforeSpritesRenderingObserver) {\n this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);\n this._onBeforeSpritesRenderingObserver = null;\n }\n if (this._onAfterSpritesRenderingObserver) {\n this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);\n this._onAfterSpritesRenderingObserver = null;\n }\n this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);\n this._onBeforeDrawPhaseObserver = null;\n this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);\n this._onAfterDrawPhaseObserver = null;\n if (this._onBeforePhysicsObserver) {\n this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);\n this._onBeforePhysicsObserver = null;\n }\n if (this._onAfterPhysicsObserver) {\n this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);\n this._onAfterPhysicsObserver = null;\n }\n this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);\n this._onAfterAnimationsObserver = null;\n this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);\n this._onBeforeCameraRenderObserver = null;\n this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);\n this._onAfterCameraRenderObserver = null;\n this.scene = null;\n }\n}\n//# sourceMappingURL=sceneInstrumentation.js.map","export * from \"./engineInstrumentation.js\";\nexport * from \"./sceneInstrumentation.js\";\nexport * from \"./timeToken.js\";\n//# sourceMappingURL=index.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/helperFunctions.js\";\nimport \"./ShadersInclude/clipPlaneFragmentDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneFragment.js\";\nconst name = \"glowMapGenerationPixelShader\";\nconst shader = `#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR)\n#include\n#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;\runiform sampler2D diffuseSampler;\r#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;\runiform sampler2D opacitySampler;\runiform float opacityIntensity;\r#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\runiform sampler2D emissiveSampler;\r#endif\n#ifdef VERTEXALPHA\nvarying vec4 vColor;\r#endif\nuniform vec4 glowColor;\runiform float glowIntensity;\r#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\r{\r#include\nvec4 finalColor=glowColor;\r#ifdef DIFFUSE\nvec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse);\r#ifdef DIFFUSE_ISLINEAR\nalbedoTexture=toGammaSpace(albedoTexture);\r#endif\n#ifdef GLOW\nfinalColor.a*=albedoTexture.a;\r#endif\n#ifdef HIGHLIGHT\nfinalColor.a=albedoTexture.a;\r#endif\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vUVOpacity);\r#ifdef OPACITYRGB\nfinalColor.a*=getLuminance(opacityMap.rgb);\r#else\nfinalColor.a*=opacityMap.a;\r#endif\nfinalColor.a*=opacityIntensity;\r#endif\n#ifdef VERTEXALPHA\nfinalColor.a*=vColor.a;\r#endif\n#ifdef ALPHATEST\nif (finalColor.a\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform mat4 viewProjection;\rvarying vec4 vPosition;\r#ifdef UV1\nattribute vec2 uv;\r#endif\n#ifdef UV2\nattribute vec2 uv2;\r#endif\n#ifdef DIFFUSE\nvarying vec2 vUVDiffuse;\runiform mat4 diffuseMatrix;\r#endif\n#ifdef OPACITY\nvarying vec2 vUVOpacity;\runiform mat4 opacityMatrix;\r#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\runiform mat4 emissiveMatrix;\r#endif\n#ifdef VERTEXALPHA\nattribute vec4 color;\rvarying vec4 vColor;\r#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\r{\rvec3 positionUpdated=position;\r#ifdef UV1\nvec2 uvUpdated=uv;\r#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\r#ifdef CUBEMAP\nvPosition=worldPos;\rgl_Position=viewProjection*finalWorld*vec4(position,1.0);\r#else\nvPosition=viewProjection*worldPos;\rgl_Position=vPosition;\r#endif\n#ifdef DIFFUSE\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\r#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\r#endif\n#endif\n#ifdef OPACITY\n#ifdef OPACITYUV1\nvUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0));\r#endif\n#ifdef OPACITYUV2\nvUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\r#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0));\r#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\r#endif\n#endif\n#ifdef VERTEXALPHA\nvColor=color;\r#endif\n#include\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const glowMapGenerationVertexShader = { name, shader };\n//# sourceMappingURL=glowMapGeneration.vertex.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize, serializeAsColor4, serializeAsCameraReference } from \"../Misc/decorators.js\";\nimport { Tools } from \"../Misc/tools.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { RenderTargetTexture } from \"../Materials/Textures/renderTargetTexture.js\";\nimport { Material } from \"../Materials/material.js\";\nimport { MaterialHelper } from \"../Materials/materialHelper.js\";\n\nimport \"../Shaders/glowMapGeneration.fragment.js\";\nimport \"../Shaders/glowMapGeneration.vertex.js\";\nimport { _WarnImport } from \"../Misc/devTools.js\";\nimport { EffectFallbacks } from \"../Materials/effectFallbacks.js\";\nimport { DrawWrapper } from \"../Materials/drawWrapper.js\";\nimport { addClipPlaneUniforms, bindClipPlane, prepareStringDefinesForClipPlanes } from \"../Materials/clipPlaneMaterialHelper.js\";\n/**\n * The effect layer Helps adding post process effect blended with the main pass.\n *\n * This can be for instance use to generate glow or highlight effects on the scene.\n *\n * The effect layer class can not be used directly and is intented to inherited from to be\n * customized per effects.\n */\nexport class EffectLayer {\n /**\n * Gets the camera attached to the layer.\n */\n get camera() {\n return this._effectLayerOptions.camera;\n }\n /**\n * Gets the rendering group id the layer should render in.\n */\n get renderingGroupId() {\n return this._effectLayerOptions.renderingGroupId;\n }\n set renderingGroupId(renderingGroupId) {\n this._effectLayerOptions.renderingGroupId = renderingGroupId;\n }\n /**\n * Gets the main texture where the effect is rendered\n */\n get mainTexture() {\n return this._mainTexture;\n }\n /**\n * Sets a specific material to be used to render a mesh/a list of meshes in the layer\n * @param mesh mesh or array of meshes\n * @param material material to use by the layer when rendering the mesh(es). If undefined is passed, the specific material created by the layer will be used.\n */\n setMaterialForRendering(mesh, material) {\n this._mainTexture.setMaterialForRendering(mesh, material);\n if (Array.isArray(mesh)) {\n for (let i = 0; i < mesh.length; ++i) {\n const currentMesh = mesh[i];\n if (!material) {\n delete this._materialForRendering[currentMesh.uniqueId];\n }\n else {\n this._materialForRendering[currentMesh.uniqueId] = [currentMesh, material];\n }\n }\n }\n else {\n if (!material) {\n delete this._materialForRendering[mesh.uniqueId];\n }\n else {\n this._materialForRendering[mesh.uniqueId] = [mesh, material];\n }\n }\n }\n /**\n * Gets the intensity of the effect for a specific mesh.\n * @param mesh The mesh to get the effect intensity for\n * @returns The intensity of the effect for the mesh\n */\n getEffectIntensity(mesh) {\n var _a;\n return (_a = this._effectIntensity[mesh.uniqueId]) !== null && _a !== void 0 ? _a : 1;\n }\n /**\n * Sets the intensity of the effect for a specific mesh.\n * @param mesh The mesh to set the effect intensity for\n * @param intensity The intensity of the effect for the mesh\n */\n setEffectIntensity(mesh, intensity) {\n this._effectIntensity[mesh.uniqueId] = intensity;\n }\n /**\n * Instantiates a new effect Layer and references it in the scene.\n * @param name The name of the layer\n * @param scene The scene to use the layer in\n */\n constructor(\n /** The Friendly of the effect in the scene */\n name, scene) {\n this._vertexBuffers = {};\n this._maxSize = 0;\n this._mainTextureDesiredSize = { width: 0, height: 0 };\n this._shouldRender = true;\n this._postProcesses = [];\n this._textures = [];\n this._emissiveTextureAndColor = { texture: null, color: new Color4() };\n this._effectIntensity = {};\n /**\n * The clear color of the texture used to generate the glow map.\n */\n this.neutralColor = new Color4();\n /**\n * Specifies whether the highlight layer is enabled or not.\n */\n this.isEnabled = true;\n /**\n * Specifies if the bounding boxes should be rendered normally or if they should undergo the effect of the layer\n */\n this.disableBoundingBoxesFromEffectLayer = false;\n /**\n * An event triggered when the effect layer has been disposed.\n */\n this.onDisposeObservable = new Observable();\n /**\n * An event triggered when the effect layer is about rendering the main texture with the glowy parts.\n */\n this.onBeforeRenderMainTextureObservable = new Observable();\n /**\n * An event triggered when the generated texture is being merged in the scene.\n */\n this.onBeforeComposeObservable = new Observable();\n /**\n * An event triggered when the mesh is rendered into the effect render target.\n */\n this.onBeforeRenderMeshToEffect = new Observable();\n /**\n * An event triggered after the mesh has been rendered into the effect render target.\n */\n this.onAfterRenderMeshToEffect = new Observable();\n /**\n * An event triggered when the generated texture has been merged in the scene.\n */\n this.onAfterComposeObservable = new Observable();\n /**\n * An event triggered when the effect layer changes its size.\n */\n this.onSizeChangedObservable = new Observable();\n this._materialForRendering = {};\n this.name = name;\n this._scene = scene || EngineStore.LastCreatedScene;\n EffectLayer._SceneComponentInitialization(this._scene);\n this._engine = this._scene.getEngine();\n this._maxSize = this._engine.getCaps().maxTextureSize;\n this._scene.effectLayers.push(this);\n this._mergeDrawWrapper = [];\n // Generate Buffers\n this._generateIndexBuffer();\n this._generateVertexBuffer();\n }\n /**\n * Number of times _internalRender will be called. Some effect layers need to render the mesh several times, so they should override this method with the number of times the mesh should be rendered\n * @returns Number of times a mesh must be rendered in the layer\n */\n _numInternalDraws() {\n return 1;\n }\n /**\n * Initializes the effect layer with the required options.\n * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)\n */\n _init(options) {\n // Adapt options\n this._effectLayerOptions = Object.assign({ mainTextureRatio: 0.5, alphaBlendingMode: 2, camera: null, renderingGroupId: -1, mainTextureType: 0 }, options);\n this._setMainTextureSize();\n this._createMainTexture();\n this._createTextureAndPostProcesses();\n }\n /**\n * Generates the index buffer of the full screen quad blending to the main canvas.\n */\n _generateIndexBuffer() {\n // Indices\n const indices = [];\n indices.push(0);\n indices.push(1);\n indices.push(2);\n indices.push(0);\n indices.push(2);\n indices.push(3);\n this._indexBuffer = this._engine.createIndexBuffer(indices);\n }\n /**\n * Generates the vertex buffer of the full screen quad blending to the main canvas.\n */\n _generateVertexBuffer() {\n // VBO\n const vertices = [];\n vertices.push(1, 1);\n vertices.push(-1, 1);\n vertices.push(-1, -1);\n vertices.push(1, -1);\n const vertexBuffer = new VertexBuffer(this._engine, vertices, VertexBuffer.PositionKind, false, false, 2);\n this._vertexBuffers[VertexBuffer.PositionKind] = vertexBuffer;\n }\n /**\n * Sets the main texture desired size which is the closest power of two\n * of the engine canvas size.\n */\n _setMainTextureSize() {\n if (this._effectLayerOptions.mainTextureFixedSize) {\n this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;\n this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;\n }\n else {\n this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;\n this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;\n this._mainTextureDesiredSize.width = this._engine.needPOTTextures\n ? Engine.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize)\n : this._mainTextureDesiredSize.width;\n this._mainTextureDesiredSize.height = this._engine.needPOTTextures\n ? Engine.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize)\n : this._mainTextureDesiredSize.height;\n }\n this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);\n this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);\n }\n /**\n * Creates the main texture for the effect layer.\n */\n _createMainTexture() {\n this._mainTexture = new RenderTargetTexture(\"EffectLayerMainRTT\", {\n width: this._mainTextureDesiredSize.width,\n height: this._mainTextureDesiredSize.height,\n }, this._scene, false, true, this._effectLayerOptions.mainTextureType);\n this._mainTexture.activeCamera = this._effectLayerOptions.camera;\n this._mainTexture.wrapU = Texture.CLAMP_ADDRESSMODE;\n this._mainTexture.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._mainTexture.anisotropicFilteringLevel = 1;\n this._mainTexture.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);\n this._mainTexture.renderParticles = false;\n this._mainTexture.renderList = null;\n this._mainTexture.ignoreCameraViewport = true;\n for (const id in this._materialForRendering) {\n const [mesh, material] = this._materialForRendering[id];\n this._mainTexture.setMaterialForRendering(mesh, material);\n }\n this._mainTexture.customIsReadyFunction = (mesh, refreshRate, preWarm) => {\n if ((preWarm || refreshRate === 0) && mesh.subMeshes) {\n for (let i = 0; i < mesh.subMeshes.length; ++i) {\n const subMesh = mesh.subMeshes[i];\n const material = subMesh.getMaterial();\n const renderingMesh = subMesh.getRenderingMesh();\n if (!material) {\n continue;\n }\n const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());\n const hardwareInstancedRendering = batch.hardwareInstancedRendering[subMesh._id] || renderingMesh.hasThinInstances;\n this._setEmissiveTextureAndColor(renderingMesh, subMesh, material);\n if (!this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {\n return false;\n }\n }\n }\n return true;\n };\n // Custom render function\n this._mainTexture.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => {\n this.onBeforeRenderMainTextureObservable.notifyObservers(this);\n let index;\n const engine = this._scene.getEngine();\n if (depthOnlySubMeshes.length) {\n engine.setColorWrite(false);\n for (index = 0; index < depthOnlySubMeshes.length; index++) {\n this._renderSubMesh(depthOnlySubMeshes.data[index]);\n }\n engine.setColorWrite(true);\n }\n for (index = 0; index < opaqueSubMeshes.length; index++) {\n this._renderSubMesh(opaqueSubMeshes.data[index]);\n }\n for (index = 0; index < alphaTestSubMeshes.length; index++) {\n this._renderSubMesh(alphaTestSubMeshes.data[index]);\n }\n const previousAlphaMode = engine.getAlphaMode();\n for (index = 0; index < transparentSubMeshes.length; index++) {\n this._renderSubMesh(transparentSubMeshes.data[index], true);\n }\n engine.setAlphaMode(previousAlphaMode);\n };\n this._mainTexture.onClearObservable.add((engine) => {\n engine.clear(this.neutralColor, true, true, true);\n });\n // Prevent package size in es6 (getBoundingBoxRenderer might not be present)\n if (this._scene.getBoundingBoxRenderer) {\n const boundingBoxRendererEnabled = this._scene.getBoundingBoxRenderer().enabled;\n this._mainTexture.onBeforeBindObservable.add(() => {\n this._scene.getBoundingBoxRenderer().enabled = !this.disableBoundingBoxesFromEffectLayer && boundingBoxRendererEnabled;\n });\n this._mainTexture.onAfterUnbindObservable.add(() => {\n this._scene.getBoundingBoxRenderer().enabled = boundingBoxRendererEnabled;\n });\n }\n }\n /**\n * Adds specific effects defines.\n * @param defines The defines to add specifics to.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _addCustomEffectDefines(defines) {\n // Nothing to add by default.\n }\n /**\n * Checks for the readiness of the element composing the layer.\n * @param subMesh the mesh to check for\n * @param useInstances specify whether or not to use instances to render the mesh\n * @param emissiveTexture the associated emissive texture used to generate the glow\n * @returns true if ready otherwise, false\n */\n _isReady(subMesh, useInstances, emissiveTexture) {\n var _a;\n const engine = this._scene.getEngine();\n const mesh = subMesh.getMesh();\n const renderingMaterial = (_a = mesh._internalAbstractMeshDataInfo._materialForRenderPass) === null || _a === void 0 ? void 0 : _a[engine.currentRenderPassId];\n if (renderingMaterial) {\n return renderingMaterial.isReadyForSubMesh(mesh, subMesh, useInstances);\n }\n const material = subMesh.getMaterial();\n if (!material) {\n return false;\n }\n if (this._useMeshMaterial(subMesh.getRenderingMesh())) {\n return material.isReadyForSubMesh(subMesh.getMesh(), subMesh, useInstances);\n }\n const defines = [];\n const attribs = [VertexBuffer.PositionKind];\n let uv1 = false;\n let uv2 = false;\n // Diffuse\n if (material) {\n const needAlphaTest = material.needAlphaTesting();\n const diffuseTexture = material.getAlphaTestTexture();\n const needAlphaBlendFromDiffuse = diffuseTexture && diffuseTexture.hasAlpha && (material.useAlphaFromDiffuseTexture || material._useAlphaFromAlbedoTexture);\n if (diffuseTexture && (needAlphaTest || needAlphaBlendFromDiffuse)) {\n defines.push(\"#define DIFFUSE\");\n if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) && diffuseTexture.coordinatesIndex === 1) {\n defines.push(\"#define DIFFUSEUV2\");\n uv2 = true;\n }\n else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {\n defines.push(\"#define DIFFUSEUV1\");\n uv1 = true;\n }\n if (needAlphaTest) {\n defines.push(\"#define ALPHATEST\");\n defines.push(\"#define ALPHATESTVALUE 0.4\");\n }\n if (!diffuseTexture.gammaSpace) {\n defines.push(\"#define DIFFUSE_ISLINEAR\");\n }\n }\n const opacityTexture = material.opacityTexture;\n if (opacityTexture) {\n defines.push(\"#define OPACITY\");\n if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) && opacityTexture.coordinatesIndex === 1) {\n defines.push(\"#define OPACITYUV2\");\n uv2 = true;\n }\n else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {\n defines.push(\"#define OPACITYUV1\");\n uv1 = true;\n }\n }\n }\n // Emissive\n if (emissiveTexture) {\n defines.push(\"#define EMISSIVE\");\n if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) && emissiveTexture.coordinatesIndex === 1) {\n defines.push(\"#define EMISSIVEUV2\");\n uv2 = true;\n }\n else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {\n defines.push(\"#define EMISSIVEUV1\");\n uv1 = true;\n }\n if (!emissiveTexture.gammaSpace) {\n defines.push(\"#define EMISSIVE_ISLINEAR\");\n }\n }\n // Vertex\n if (mesh.useVertexColors && mesh.isVerticesDataPresent(VertexBuffer.ColorKind) && mesh.hasVertexAlpha && material.transparencyMode !== Material.MATERIAL_OPAQUE) {\n attribs.push(VertexBuffer.ColorKind);\n defines.push(\"#define VERTEXALPHA\");\n }\n if (uv1) {\n attribs.push(VertexBuffer.UVKind);\n defines.push(\"#define UV1\");\n }\n if (uv2) {\n attribs.push(VertexBuffer.UV2Kind);\n defines.push(\"#define UV2\");\n }\n // Bones\n const fallbacks = new EffectFallbacks();\n if (mesh.useBones && mesh.computeBonesUsingShaders) {\n attribs.push(VertexBuffer.MatricesIndicesKind);\n attribs.push(VertexBuffer.MatricesWeightsKind);\n if (mesh.numBoneInfluencers > 4) {\n attribs.push(VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(VertexBuffer.MatricesWeightsExtraKind);\n }\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n const skeleton = mesh.skeleton;\n if (skeleton && skeleton.isUsingTextureForMatrices) {\n defines.push(\"#define BONETEXTURE\");\n }\n else {\n defines.push(\"#define BonesPerMesh \" + (skeleton ? skeleton.bones.length + 1 : 0));\n }\n if (mesh.numBoneInfluencers > 0) {\n fallbacks.addCPUSkinningFallback(0, mesh);\n }\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Morph targets\n const manager = mesh.morphTargetManager;\n let morphInfluencers = 0;\n if (manager) {\n if (manager.numInfluencers > 0) {\n defines.push(\"#define MORPHTARGETS\");\n morphInfluencers = manager.numInfluencers;\n defines.push(\"#define NUM_MORPH_INFLUENCERS \" + morphInfluencers);\n if (manager.isUsingTextureForTargets) {\n defines.push(\"#define MORPHTARGETS_TEXTURE\");\n }\n MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, morphInfluencers);\n }\n }\n // Instances\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n MaterialHelper.PushAttributesForInstances(attribs);\n if (subMesh.getRenderingMesh().hasThinInstances) {\n defines.push(\"#define THIN_INSTANCES\");\n }\n }\n // ClipPlanes\n prepareStringDefinesForClipPlanes(material, this._scene, defines);\n this._addCustomEffectDefines(defines);\n // Get correct effect\n const drawWrapper = subMesh._getDrawWrapper(undefined, true);\n const cachedDefines = drawWrapper.defines;\n const join = defines.join(\"\\n\");\n if (cachedDefines !== join) {\n const uniforms = [\n \"world\",\n \"mBones\",\n \"viewProjection\",\n \"glowColor\",\n \"morphTargetInfluences\",\n \"boneTextureWidth\",\n \"diffuseMatrix\",\n \"emissiveMatrix\",\n \"opacityMatrix\",\n \"opacityIntensity\",\n \"morphTargetTextureInfo\",\n \"morphTargetTextureIndices\",\n \"glowIntensity\",\n ];\n addClipPlaneUniforms(uniforms);\n drawWrapper.setEffect(this._engine.createEffect(\"glowMapGeneration\", attribs, uniforms, [\"diffuseSampler\", \"emissiveSampler\", \"opacitySampler\", \"boneSampler\", \"morphTargets\"], join, fallbacks, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers }), join);\n }\n return drawWrapper.effect.isReady();\n }\n /**\n * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.\n */\n render() {\n for (let i = 0; i < this._postProcesses.length; i++) {\n if (!this._postProcesses[i].isReady()) {\n return;\n }\n }\n const engine = this._scene.getEngine();\n const numDraws = this._numInternalDraws();\n // Check\n let isReady = true;\n for (let i = 0; i < numDraws; ++i) {\n let currentEffect = this._mergeDrawWrapper[i];\n if (!currentEffect) {\n currentEffect = this._mergeDrawWrapper[i] = new DrawWrapper(this._engine);\n currentEffect.setEffect(this._createMergeEffect());\n }\n isReady = isReady && currentEffect.effect.isReady();\n }\n if (!isReady) {\n return;\n }\n this.onBeforeComposeObservable.notifyObservers(this);\n const previousAlphaMode = engine.getAlphaMode();\n for (let i = 0; i < numDraws; ++i) {\n const currentEffect = this._mergeDrawWrapper[i];\n // Render\n engine.enableEffect(currentEffect);\n engine.setState(false);\n // VBOs\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect.effect);\n // Go Blend.\n engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);\n // Blends the map on the main canvas.\n this._internalRender(currentEffect.effect, i);\n }\n // Restore Alpha\n engine.setAlphaMode(previousAlphaMode);\n this.onAfterComposeObservable.notifyObservers(this);\n // Handle size changes.\n const size = this._mainTexture.getSize();\n this._setMainTextureSize();\n if ((size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) &&\n this._mainTextureDesiredSize.width !== 0 &&\n this._mainTextureDesiredSize.height !== 0) {\n // Recreate RTT and post processes on size change.\n this.onSizeChangedObservable.notifyObservers(this);\n this._disposeTextureAndPostProcesses();\n this._createMainTexture();\n this._createTextureAndPostProcesses();\n }\n }\n /**\n * Determine if a given mesh will be used in the current effect.\n * @param mesh mesh to test\n * @returns true if the mesh will be used\n */\n hasMesh(mesh) {\n if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {\n return true;\n }\n return false;\n }\n /**\n * Returns true if the layer contains information to display, otherwise false.\n * @returns true if the glow layer should be rendered\n */\n shouldRender() {\n return this.isEnabled && this._shouldRender;\n }\n /**\n * Returns true if the mesh should render, otherwise false.\n * @param mesh The mesh to render\n * @returns true if it should render otherwise false\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _shouldRenderMesh(mesh) {\n return true;\n }\n /**\n * Returns true if the mesh can be rendered, otherwise false.\n * @param mesh The mesh to render\n * @param material The material used on the mesh\n * @returns true if it can be rendered otherwise false\n */\n _canRenderMesh(mesh, material) {\n return !material.needAlphaBlendingForMesh(mesh);\n }\n /**\n * Returns true if the mesh should render, otherwise false.\n * @returns true if it should render otherwise false\n */\n _shouldRenderEmissiveTextureForMesh() {\n return true;\n }\n /**\n * Renders the submesh passed in parameter to the generation map.\n * @param subMesh\n * @param enableAlphaMode\n */\n _renderSubMesh(subMesh, enableAlphaMode = false) {\n var _a, _b;\n if (!this.shouldRender()) {\n return;\n }\n const material = subMesh.getMaterial();\n const ownerMesh = subMesh.getMesh();\n const replacementMesh = subMesh.getReplacementMesh();\n const renderingMesh = subMesh.getRenderingMesh();\n const effectiveMesh = subMesh.getEffectiveMesh();\n const scene = this._scene;\n const engine = scene.getEngine();\n effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;\n if (!material) {\n return;\n }\n // Do not block in blend mode.\n if (!this._canRenderMesh(renderingMesh, material)) {\n return;\n }\n // Culling\n let sideOrientation = (_a = renderingMesh.overrideMaterialSideOrientation) !== null && _a !== void 0 ? _a : material.sideOrientation;\n const mainDeterminant = effectiveMesh._getWorldMatrixDeterminant();\n if (mainDeterminant < 0) {\n sideOrientation = sideOrientation === Material.ClockWiseSideOrientation ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation;\n }\n const reverse = sideOrientation === Material.ClockWiseSideOrientation;\n engine.setState(material.backFaceCulling, material.zOffset, undefined, reverse, material.cullBackFaces, undefined, material.zOffsetUnits);\n // Managing instances\n const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!replacementMesh);\n if (batch.mustReturn) {\n return;\n }\n // Early Exit per mesh\n if (!this._shouldRenderMesh(renderingMesh)) {\n return;\n }\n const hardwareInstancedRendering = batch.hardwareInstancedRendering[subMesh._id] || renderingMesh.hasThinInstances;\n this._setEmissiveTextureAndColor(renderingMesh, subMesh, material);\n this.onBeforeRenderMeshToEffect.notifyObservers(ownerMesh);\n if (this._useMeshMaterial(renderingMesh)) {\n renderingMesh.render(subMesh, enableAlphaMode, replacementMesh || undefined);\n }\n else if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {\n const renderingMaterial = (_b = effectiveMesh._internalAbstractMeshDataInfo._materialForRenderPass) === null || _b === void 0 ? void 0 : _b[engine.currentRenderPassId];\n let drawWrapper = subMesh._getDrawWrapper();\n if (!drawWrapper && renderingMaterial) {\n drawWrapper = renderingMaterial._getDrawWrapper();\n }\n if (!drawWrapper) {\n return;\n }\n const effect = drawWrapper.effect;\n engine.enableEffect(drawWrapper);\n if (!hardwareInstancedRendering) {\n renderingMesh._bind(subMesh, effect, material.fillMode);\n }\n if (!renderingMaterial) {\n effect.setMatrix(\"viewProjection\", scene.getTransformMatrix());\n effect.setMatrix(\"world\", effectiveMesh.getWorldMatrix());\n effect.setFloat4(\"glowColor\", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);\n }\n else {\n renderingMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), effectiveMesh, subMesh);\n }\n if (!renderingMaterial) {\n const needAlphaTest = material.needAlphaTesting();\n const diffuseTexture = material.getAlphaTestTexture();\n const needAlphaBlendFromDiffuse = diffuseTexture && diffuseTexture.hasAlpha && (material.useAlphaFromDiffuseTexture || material._useAlphaFromAlbedoTexture);\n if (diffuseTexture && (needAlphaTest || needAlphaBlendFromDiffuse)) {\n effect.setTexture(\"diffuseSampler\", diffuseTexture);\n const textureMatrix = diffuseTexture.getTextureMatrix();\n if (textureMatrix) {\n effect.setMatrix(\"diffuseMatrix\", textureMatrix);\n }\n }\n const opacityTexture = material.opacityTexture;\n if (opacityTexture) {\n effect.setTexture(\"opacitySampler\", opacityTexture);\n effect.setFloat(\"opacityIntensity\", opacityTexture.level);\n const textureMatrix = opacityTexture.getTextureMatrix();\n if (textureMatrix) {\n effect.setMatrix(\"opacityMatrix\", textureMatrix);\n }\n }\n // Glow emissive only\n if (this._emissiveTextureAndColor.texture) {\n effect.setTexture(\"emissiveSampler\", this._emissiveTextureAndColor.texture);\n effect.setMatrix(\"emissiveMatrix\", this._emissiveTextureAndColor.texture.getTextureMatrix());\n }\n // Bones\n if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) {\n const skeleton = renderingMesh.skeleton;\n if (skeleton.isUsingTextureForMatrices) {\n const boneTexture = skeleton.getTransformMatrixTexture(renderingMesh);\n if (!boneTexture) {\n return;\n }\n effect.setTexture(\"boneSampler\", boneTexture);\n effect.setFloat(\"boneTextureWidth\", 4.0 * (skeleton.bones.length + 1));\n }\n else {\n effect.setMatrices(\"mBones\", skeleton.getTransformMatrices(renderingMesh));\n }\n }\n // Morph targets\n MaterialHelper.BindMorphTargetParameters(renderingMesh, effect);\n if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) {\n renderingMesh.morphTargetManager._bind(effect);\n }\n // Alpha mode\n if (enableAlphaMode) {\n engine.setAlphaMode(material.alphaMode);\n }\n // Intensity of effect\n effect.setFloat(\"glowIntensity\", this.getEffectIntensity(renderingMesh));\n // Clip planes\n bindClipPlane(effect, material, scene);\n }\n // Draw\n renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, world) => effect.setMatrix(\"world\", world));\n }\n else {\n // Need to reset refresh rate of the main map\n this._mainTexture.resetRefreshCounter();\n }\n this.onAfterRenderMeshToEffect.notifyObservers(ownerMesh);\n }\n /**\n * Defines whether the current material of the mesh should be use to render the effect.\n * @param mesh defines the current mesh to render\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _useMeshMaterial(mesh) {\n return false;\n }\n /**\n * Rebuild the required buffers.\n * @internal Internal use only.\n */\n _rebuild() {\n const vb = this._vertexBuffers[VertexBuffer.PositionKind];\n if (vb) {\n vb._rebuild();\n }\n this._generateIndexBuffer();\n }\n /**\n * Dispose only the render target textures and post process.\n */\n _disposeTextureAndPostProcesses() {\n this._mainTexture.dispose();\n for (let i = 0; i < this._postProcesses.length; i++) {\n if (this._postProcesses[i]) {\n this._postProcesses[i].dispose();\n }\n }\n this._postProcesses = [];\n for (let i = 0; i < this._textures.length; i++) {\n if (this._textures[i]) {\n this._textures[i].dispose();\n }\n }\n this._textures = [];\n }\n /**\n * Dispose the highlight layer and free resources.\n */\n dispose() {\n const vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];\n if (vertexBuffer) {\n vertexBuffer.dispose();\n this._vertexBuffers[VertexBuffer.PositionKind] = null;\n }\n if (this._indexBuffer) {\n this._scene.getEngine()._releaseBuffer(this._indexBuffer);\n this._indexBuffer = null;\n }\n for (const drawWrapper of this._mergeDrawWrapper) {\n drawWrapper.dispose();\n }\n this._mergeDrawWrapper = [];\n // Clean textures and post processes\n this._disposeTextureAndPostProcesses();\n // Remove from scene\n const index = this._scene.effectLayers.indexOf(this, 0);\n if (index > -1) {\n this._scene.effectLayers.splice(index, 1);\n }\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n this.onBeforeRenderMainTextureObservable.clear();\n this.onBeforeComposeObservable.clear();\n this.onBeforeRenderMeshToEffect.clear();\n this.onAfterRenderMeshToEffect.clear();\n this.onAfterComposeObservable.clear();\n this.onSizeChangedObservable.clear();\n }\n /**\n * Gets the class name of the effect layer\n * @returns the string with the class name of the effect layer\n */\n getClassName() {\n return \"EffectLayer\";\n }\n /**\n * Creates an effect layer from parsed effect layer data\n * @param parsedEffectLayer defines effect layer data\n * @param scene defines the current scene\n * @param rootUrl defines the root URL containing the effect layer information\n * @returns a parsed effect Layer\n */\n static Parse(parsedEffectLayer, scene, rootUrl) {\n const effectLayerType = Tools.Instantiate(parsedEffectLayer.customType);\n return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);\n }\n}\n/**\n * @internal\n */\nEffectLayer._SceneComponentInitialization = (_) => {\n throw _WarnImport(\"EffectLayerSceneComponent\");\n};\n__decorate([\n serialize()\n], EffectLayer.prototype, \"name\", void 0);\n__decorate([\n serializeAsColor4()\n], EffectLayer.prototype, \"neutralColor\", void 0);\n__decorate([\n serialize()\n], EffectLayer.prototype, \"isEnabled\", void 0);\n__decorate([\n serializeAsCameraReference()\n], EffectLayer.prototype, \"camera\", null);\n__decorate([\n serialize()\n], EffectLayer.prototype, \"renderingGroupId\", null);\n__decorate([\n serialize()\n], EffectLayer.prototype, \"disableBoundingBoxesFromEffectLayer\", void 0);\n//# sourceMappingURL=effectLayer.js.map","import { Camera } from \"../Cameras/camera.js\";\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { EffectLayer } from \"./effectLayer.js\";\nimport { AbstractScene } from \"../abstractScene.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n// Adds the parser to the scene parsers.\nAbstractScene.AddParser(SceneComponentConstants.NAME_EFFECTLAYER, (parsedData, scene, container, rootUrl) => {\n if (parsedData.effectLayers) {\n if (!container.effectLayers) {\n container.effectLayers = new Array();\n }\n for (let index = 0; index < parsedData.effectLayers.length; index++) {\n const effectLayer = EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);\n container.effectLayers.push(effectLayer);\n }\n }\n});\nAbstractScene.prototype.removeEffectLayer = function (toRemove) {\n const index = this.effectLayers.indexOf(toRemove);\n if (index !== -1) {\n this.effectLayers.splice(index, 1);\n }\n return index;\n};\nAbstractScene.prototype.addEffectLayer = function (newEffectLayer) {\n this.effectLayers.push(newEffectLayer);\n};\n/**\n * Defines the layer scene component responsible to manage any effect layers\n * in a given scene.\n */\nexport class EffectLayerSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpful to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_EFFECTLAYER;\n this._renderEffects = false;\n this._needStencil = false;\n this._previousStencilState = false;\n this.scene = scene || EngineStore.LastCreatedScene;\n if (!this.scene) {\n return;\n }\n this._engine = this.scene.getEngine();\n this.scene.effectLayers = new Array();\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene._isReadyForMeshStage.registerStep(SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);\n this.scene._cameraDrawRenderTargetStage.registerStep(SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);\n this.scene._beforeCameraDrawStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);\n this.scene._afterRenderingGroupDrawStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);\n this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);\n this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n const layers = this.scene.effectLayers;\n for (const effectLayer of layers) {\n effectLayer._rebuild();\n }\n }\n /**\n * Serializes the component data to the specified json object\n * @param serializationObject The object to serialize to\n */\n serialize(serializationObject) {\n // Effect layers\n serializationObject.effectLayers = [];\n const layers = this.scene.effectLayers;\n for (const effectLayer of layers) {\n if (effectLayer.serialize) {\n serializationObject.effectLayers.push(effectLayer.serialize());\n }\n }\n }\n /**\n * Adds all the elements from the container to the scene\n * @param container the container holding the elements\n */\n addFromContainer(container) {\n if (!container.effectLayers) {\n return;\n }\n container.effectLayers.forEach((o) => {\n this.scene.addEffectLayer(o);\n });\n }\n /**\n * Removes all the elements in the container from the scene\n * @param container contains the elements to remove\n * @param dispose if the removed element should be disposed (default: false)\n */\n removeFromContainer(container, dispose) {\n if (!container.effectLayers) {\n return;\n }\n container.effectLayers.forEach((o) => {\n this.scene.removeEffectLayer(o);\n if (dispose) {\n o.dispose();\n }\n });\n }\n /**\n * Disposes the component and the associated resources.\n */\n dispose() {\n const layers = this.scene.effectLayers;\n while (layers.length) {\n layers[0].dispose();\n }\n }\n _isReadyForMesh(mesh, hardwareInstancedRendering) {\n const currentRenderPassId = this._engine.currentRenderPassId;\n const layers = this.scene.effectLayers;\n for (const layer of layers) {\n if (!layer.hasMesh(mesh)) {\n continue;\n }\n const renderTarget = layer._mainTexture;\n this._engine.currentRenderPassId = renderTarget.renderPassId;\n for (const subMesh of mesh.subMeshes) {\n if (!layer.isReady(subMesh, hardwareInstancedRendering)) {\n this._engine.currentRenderPassId = currentRenderPassId;\n return false;\n }\n }\n }\n this._engine.currentRenderPassId = currentRenderPassId;\n return true;\n }\n _renderMainTexture(camera) {\n this._renderEffects = false;\n this._needStencil = false;\n let needRebind = false;\n const layers = this.scene.effectLayers;\n if (layers && layers.length > 0) {\n this._previousStencilState = this._engine.getStencilBuffer();\n for (const effectLayer of layers) {\n if (effectLayer.shouldRender() &&\n (!effectLayer.camera ||\n (effectLayer.camera.cameraRigMode === Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||\n (effectLayer.camera.cameraRigMode !== Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {\n this._renderEffects = true;\n this._needStencil = this._needStencil || effectLayer.needStencil();\n const renderTarget = effectLayer._mainTexture;\n if (renderTarget._shouldRender()) {\n this.scene.incrementRenderId();\n renderTarget.render(false, false);\n needRebind = true;\n }\n }\n }\n this.scene.incrementRenderId();\n }\n return needRebind;\n }\n _setStencil() {\n // Activate effect Layer stencil\n if (this._needStencil) {\n this._engine.setStencilBuffer(true);\n }\n }\n _setStencilBack() {\n // Restore effect Layer stencil\n if (this._needStencil) {\n this._engine.setStencilBuffer(this._previousStencilState);\n }\n }\n _draw(renderingGroupId) {\n if (this._renderEffects) {\n this._engine.setDepthBuffer(false);\n const layers = this.scene.effectLayers;\n for (let i = 0; i < layers.length; i++) {\n const effectLayer = layers[i];\n if (effectLayer.renderingGroupId === renderingGroupId) {\n if (effectLayer.shouldRender()) {\n effectLayer.render();\n }\n }\n }\n this._engine.setDepthBuffer(true);\n }\n }\n _drawCamera() {\n if (this._renderEffects) {\n this._draw(-1);\n }\n }\n _drawRenderingGroup(index) {\n if (!this.scene._isInIntermediateRendering() && this._renderEffects) {\n this._draw(index);\n }\n }\n}\nEffectLayer._SceneComponentInitialization = (scene) => {\n let component = scene._getComponent(SceneComponentConstants.NAME_EFFECTLAYER);\n if (!component) {\n component = new EffectLayerSceneComponent(scene);\n scene._addComponent(component);\n }\n};\n//# sourceMappingURL=effectLayerSceneComponent.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"glowMapMergePixelShader\";\nconst shader = `varying vec2 vUV;\runiform sampler2D textureSampler;\r#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\r#endif\nuniform float offset;\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\r#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\rbaseColor*=offset;\r#else\nbaseColor.a=abs(offset-baseColor.a);\r#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\rbaseColor.a=alpha;\rbaseColor.rgb=baseColor.rgb*alpha;\r#endif\n#endif\n#if LDR\nbaseColor=clamp(baseColor,0.,1.0);\r#endif\ngl_FragColor=baseColor;\r#define CUSTOM_FRAGMENT_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const glowMapMergePixelShader = { name, shader };\n//# sourceMappingURL=glowMapMerge.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"glowMapMergeVertexShader\";\nconst shader = `attribute vec2 position;\rvarying vec2 vUV;\rconst vec2 madd=vec2(0.5,0.5);\r#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=position*madd+madd;\rgl_Position=vec4(position,0.0,1.0);\r#define CUSTOM_VERTEX_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const glowMapMergeVertexShader = { name, shader };\n//# sourceMappingURL=glowMapMerge.vertex.js.map","import { __decorate } from \"../tslib.es6.js\";\n/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { serialize, SerializationHelper } from \"../Misc/decorators.js\";\nimport { Vector2 } from \"../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { RenderTargetTexture } from \"../Materials/Textures/renderTargetTexture.js\";\nimport { Material } from \"../Materials/material.js\";\nimport { BlurPostProcess } from \"../PostProcesses/blurPostProcess.js\";\nimport { EffectLayer } from \"./effectLayer.js\";\nimport { AbstractScene } from \"../abstractScene.js\";\n\nimport { RegisterClass } from \"../Misc/typeStore.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport \"../Shaders/glowMapMerge.fragment.js\";\nimport \"../Shaders/glowMapMerge.vertex.js\";\nimport \"../Layers/effectLayerSceneComponent.js\";\nAbstractScene.prototype.getGlowLayerByName = function (name) {\n var _a;\n for (let index = 0; index < ((_a = this.effectLayers) === null || _a === void 0 ? void 0 : _a.length); index++) {\n if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {\n return this.effectLayers[index];\n }\n }\n return null;\n};\n/**\n * The glow layer Helps adding a glow effect around the emissive parts of a mesh.\n *\n * Once instantiated in a scene, by default, all the emissive meshes will glow.\n *\n * Documentation: https://doc.babylonjs.com/features/featuresDeepDive/mesh/glowLayer\n */\nexport class GlowLayer extends EffectLayer {\n /**\n * Sets the kernel size of the blur.\n */\n set blurKernelSize(value) {\n if (value === this._options.blurKernelSize) {\n return;\n }\n this._options.blurKernelSize = value;\n const effectiveKernel = this._getEffectiveBlurKernelSize();\n this._horizontalBlurPostprocess1.kernel = effectiveKernel;\n this._verticalBlurPostprocess1.kernel = effectiveKernel;\n this._horizontalBlurPostprocess2.kernel = effectiveKernel;\n this._verticalBlurPostprocess2.kernel = effectiveKernel;\n }\n /**\n * Gets the kernel size of the blur.\n */\n get blurKernelSize() {\n return this._options.blurKernelSize;\n }\n /**\n * Sets the glow intensity.\n */\n set intensity(value) {\n this._intensity = value;\n }\n /**\n * Gets the glow intensity.\n */\n get intensity() {\n return this._intensity;\n }\n /**\n * Instantiates a new glow Layer and references it to the scene.\n * @param name The name of the layer\n * @param scene The scene to use the layer in\n * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)\n */\n constructor(name, scene, options) {\n super(name, scene);\n this._intensity = 1.0;\n this._includedOnlyMeshes = [];\n this._excludedMeshes = [];\n this._meshesUsingTheirOwnMaterials = [];\n this.neutralColor = new Color4(0, 0, 0, 1);\n // Adapt options\n this._options = Object.assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1, ldrMerge: false, alphaBlendingMode: 1, mainTextureType: 0 }, options);\n // Initialize the layer\n this._init({\n alphaBlendingMode: this._options.alphaBlendingMode,\n camera: this._options.camera,\n mainTextureFixedSize: this._options.mainTextureFixedSize,\n mainTextureRatio: this._options.mainTextureRatio,\n renderingGroupId: this._options.renderingGroupId,\n mainTextureType: this._options.mainTextureType,\n });\n }\n /**\n * Get the effect name of the layer.\n * @returns The effect name\n */\n getEffectName() {\n return GlowLayer.EffectName;\n }\n /**\n * Create the merge effect. This is the shader use to blit the information back\n * to the main canvas at the end of the scene rendering.\n */\n _createMergeEffect() {\n let defines = \"#define EMISSIVE \\n\";\n if (this._options.ldrMerge) {\n defines += \"#define LDR \\n\";\n }\n // Effect\n return this._engine.createEffect(\"glowMapMerge\", [VertexBuffer.PositionKind], [\"offset\"], [\"textureSampler\", \"textureSampler2\"], defines);\n }\n /**\n * Creates the render target textures and post processes used in the glow layer.\n */\n _createTextureAndPostProcesses() {\n let blurTextureWidth = this._mainTextureDesiredSize.width;\n let blurTextureHeight = this._mainTextureDesiredSize.height;\n blurTextureWidth = this._engine.needPOTTextures ? Engine.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;\n blurTextureHeight = this._engine.needPOTTextures ? Engine.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;\n let textureType = 0;\n if (this._engine.getCaps().textureHalfFloatRender) {\n textureType = 2;\n }\n else {\n textureType = 0;\n }\n this._blurTexture1 = new RenderTargetTexture(\"GlowLayerBlurRTT\", {\n width: blurTextureWidth,\n height: blurTextureHeight,\n }, this._scene, false, true, textureType);\n this._blurTexture1.wrapU = Texture.CLAMP_ADDRESSMODE;\n this._blurTexture1.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._blurTexture1.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);\n this._blurTexture1.renderParticles = false;\n this._blurTexture1.ignoreCameraViewport = true;\n const blurTextureWidth2 = Math.floor(blurTextureWidth / 2);\n const blurTextureHeight2 = Math.floor(blurTextureHeight / 2);\n this._blurTexture2 = new RenderTargetTexture(\"GlowLayerBlurRTT2\", {\n width: blurTextureWidth2,\n height: blurTextureHeight2,\n }, this._scene, false, true, textureType);\n this._blurTexture2.wrapU = Texture.CLAMP_ADDRESSMODE;\n this._blurTexture2.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._blurTexture2.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);\n this._blurTexture2.renderParticles = false;\n this._blurTexture2.ignoreCameraViewport = true;\n this._textures = [this._blurTexture1, this._blurTexture2];\n const effectiveKernel = this._getEffectiveBlurKernelSize();\n this._horizontalBlurPostprocess1 = new BlurPostProcess(\"GlowLayerHBP1\", new Vector2(1.0, 0), effectiveKernel, {\n width: blurTextureWidth,\n height: blurTextureHeight,\n }, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);\n this._horizontalBlurPostprocess1.width = blurTextureWidth;\n this._horizontalBlurPostprocess1.height = blurTextureHeight;\n this._horizontalBlurPostprocess1.externalTextureSamplerBinding = true;\n this._horizontalBlurPostprocess1.onApplyObservable.add((effect) => {\n effect.setTexture(\"textureSampler\", this._mainTexture);\n });\n this._verticalBlurPostprocess1 = new BlurPostProcess(\"GlowLayerVBP1\", new Vector2(0, 1.0), effectiveKernel, {\n width: blurTextureWidth,\n height: blurTextureHeight,\n }, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);\n this._horizontalBlurPostprocess2 = new BlurPostProcess(\"GlowLayerHBP2\", new Vector2(1.0, 0), effectiveKernel, {\n width: blurTextureWidth2,\n height: blurTextureHeight2,\n }, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);\n this._horizontalBlurPostprocess2.width = blurTextureWidth2;\n this._horizontalBlurPostprocess2.height = blurTextureHeight2;\n this._horizontalBlurPostprocess2.externalTextureSamplerBinding = true;\n this._horizontalBlurPostprocess2.onApplyObservable.add((effect) => {\n effect.setTexture(\"textureSampler\", this._blurTexture1);\n });\n this._verticalBlurPostprocess2 = new BlurPostProcess(\"GlowLayerVBP2\", new Vector2(0, 1.0), effectiveKernel, {\n width: blurTextureWidth2,\n height: blurTextureHeight2,\n }, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);\n this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];\n this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];\n this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];\n this._mainTexture.samples = this._options.mainTextureSamples;\n this._mainTexture.onAfterUnbindObservable.add(() => {\n const internalTexture = this._blurTexture1.renderTarget;\n if (internalTexture) {\n this._scene.postProcessManager.directRender(this._postProcesses1, internalTexture, true);\n const internalTexture2 = this._blurTexture2.renderTarget;\n if (internalTexture2) {\n this._scene.postProcessManager.directRender(this._postProcesses2, internalTexture2, true);\n }\n this._engine.unBindFramebuffer(internalTexture2 !== null && internalTexture2 !== void 0 ? internalTexture2 : internalTexture, true);\n }\n });\n // Prevent autoClear.\n this._postProcesses.map((pp) => {\n pp.autoClear = false;\n });\n }\n /**\n * @returns The blur kernel size used by the glow.\n * Note: The value passed in the options is divided by 2 for back compatibility.\n */\n _getEffectiveBlurKernelSize() {\n return this._options.blurKernelSize / 2;\n }\n /**\n * Checks for the readiness of the element composing the layer.\n * @param subMesh the mesh to check for\n * @param useInstances specify whether or not to use instances to render the mesh\n * @returns true if ready otherwise, false\n */\n isReady(subMesh, useInstances) {\n const material = subMesh.getMaterial();\n const mesh = subMesh.getRenderingMesh();\n if (!material || !mesh) {\n return false;\n }\n const emissiveTexture = material.emissiveTexture;\n return super._isReady(subMesh, useInstances, emissiveTexture);\n }\n /**\n * Returns whether or not the layer needs stencil enabled during the mesh rendering.\n */\n needStencil() {\n return false;\n }\n /**\n * Returns true if the mesh can be rendered, otherwise false.\n * @param mesh The mesh to render\n * @param material The material used on the mesh\n * @returns true if it can be rendered otherwise false\n */\n _canRenderMesh(mesh, material) {\n return true;\n }\n /**\n * Implementation specific of rendering the generating effect on the main canvas.\n * @param effect The effect used to render through\n */\n _internalRender(effect) {\n // Texture\n effect.setTexture(\"textureSampler\", this._blurTexture1);\n effect.setTexture(\"textureSampler2\", this._blurTexture2);\n effect.setFloat(\"offset\", this._intensity);\n // Cache\n const engine = this._engine;\n const previousStencilBuffer = engine.getStencilBuffer();\n // Draw order\n engine.setStencilBuffer(false);\n engine.drawElementsType(Material.TriangleFillMode, 0, 6);\n // Draw order\n engine.setStencilBuffer(previousStencilBuffer);\n }\n /**\n * Sets the required values for both the emissive texture and and the main color.\n * @param mesh\n * @param subMesh\n * @param material\n */\n _setEmissiveTextureAndColor(mesh, subMesh, material) {\n var _a;\n let textureLevel = 1.0;\n if (this.customEmissiveTextureSelector) {\n this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);\n }\n else {\n if (material) {\n this._emissiveTextureAndColor.texture = material.emissiveTexture;\n if (this._emissiveTextureAndColor.texture) {\n textureLevel = this._emissiveTextureAndColor.texture.level;\n }\n }\n else {\n this._emissiveTextureAndColor.texture = null;\n }\n }\n if (this.customEmissiveColorSelector) {\n this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);\n }\n else {\n if (material.emissiveColor) {\n const emissiveIntensity = (_a = material.emissiveIntensity) !== null && _a !== void 0 ? _a : 1;\n textureLevel *= emissiveIntensity;\n this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, material.alpha);\n }\n else {\n this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);\n }\n }\n }\n /**\n * Returns true if the mesh should render, otherwise false.\n * @param mesh The mesh to render\n * @returns true if it should render otherwise false\n */\n _shouldRenderMesh(mesh) {\n return this.hasMesh(mesh);\n }\n /**\n * Adds specific effects defines.\n * @param defines The defines to add specifics to.\n */\n _addCustomEffectDefines(defines) {\n defines.push(\"#define GLOW\");\n }\n /**\n * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.\n * @param mesh The mesh to exclude from the glow layer\n */\n addExcludedMesh(mesh) {\n if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {\n this._excludedMeshes.push(mesh.uniqueId);\n }\n }\n /**\n * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.\n * @param mesh The mesh to remove\n */\n removeExcludedMesh(mesh) {\n const index = this._excludedMeshes.indexOf(mesh.uniqueId);\n if (index !== -1) {\n this._excludedMeshes.splice(index, 1);\n }\n }\n /**\n * Add a mesh in the inclusion list to impact or being impacted by the glow layer.\n * @param mesh The mesh to include in the glow layer\n */\n addIncludedOnlyMesh(mesh) {\n if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {\n this._includedOnlyMeshes.push(mesh.uniqueId);\n }\n }\n /**\n * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.\n * @param mesh The mesh to remove\n */\n removeIncludedOnlyMesh(mesh) {\n const index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);\n if (index !== -1) {\n this._includedOnlyMeshes.splice(index, 1);\n }\n }\n /**\n * Determine if a given mesh will be used in the glow layer\n * @param mesh The mesh to test\n * @returns true if the mesh will be highlighted by the current glow layer\n */\n hasMesh(mesh) {\n if (!super.hasMesh(mesh)) {\n return false;\n }\n // Included Mesh\n if (this._includedOnlyMeshes.length) {\n return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;\n }\n // Excluded Mesh\n if (this._excludedMeshes.length) {\n return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;\n }\n return true;\n }\n /**\n * Defines whether the current material of the mesh should be use to render the effect.\n * @param mesh defines the current mesh to render\n */\n _useMeshMaterial(mesh) {\n if (this._meshesUsingTheirOwnMaterials.length == 0) {\n return false;\n }\n return this._meshesUsingTheirOwnMaterials.indexOf(mesh.uniqueId) > -1;\n }\n /**\n * Add a mesh to be rendered through its own material and not with emissive only.\n * @param mesh The mesh for which we need to use its material\n */\n referenceMeshToUseItsOwnMaterial(mesh) {\n mesh.resetDrawCache(this._mainTexture.renderPassId);\n this._meshesUsingTheirOwnMaterials.push(mesh.uniqueId);\n mesh.onDisposeObservable.add(() => {\n this._disposeMesh(mesh);\n });\n }\n /**\n * Remove a mesh from being rendered through its own material and not with emissive only.\n * @param mesh The mesh for which we need to not use its material\n */\n unReferenceMeshFromUsingItsOwnMaterial(mesh) {\n let index = this._meshesUsingTheirOwnMaterials.indexOf(mesh.uniqueId);\n while (index >= 0) {\n this._meshesUsingTheirOwnMaterials.splice(index, 1);\n index = this._meshesUsingTheirOwnMaterials.indexOf(mesh.uniqueId);\n }\n mesh.resetDrawCache(this._mainTexture.renderPassId);\n }\n /**\n * Free any resources and references associated to a mesh.\n * Internal use\n * @param mesh The mesh to free.\n * @internal\n */\n _disposeMesh(mesh) {\n this.removeIncludedOnlyMesh(mesh);\n this.removeExcludedMesh(mesh);\n }\n /**\n * Gets the class name of the effect layer\n * @returns the string with the class name of the effect layer\n */\n getClassName() {\n return \"GlowLayer\";\n }\n /**\n * Serializes this glow layer\n * @returns a serialized glow layer object\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this);\n serializationObject.customType = \"BABYLON.GlowLayer\";\n let index;\n // Included meshes\n serializationObject.includedMeshes = [];\n if (this._includedOnlyMeshes.length) {\n for (index = 0; index < this._includedOnlyMeshes.length; index++) {\n const mesh = this._scene.getMeshByUniqueId(this._includedOnlyMeshes[index]);\n if (mesh) {\n serializationObject.includedMeshes.push(mesh.id);\n }\n }\n }\n // Excluded meshes\n serializationObject.excludedMeshes = [];\n if (this._excludedMeshes.length) {\n for (index = 0; index < this._excludedMeshes.length; index++) {\n const mesh = this._scene.getMeshByUniqueId(this._excludedMeshes[index]);\n if (mesh) {\n serializationObject.excludedMeshes.push(mesh.id);\n }\n }\n }\n return serializationObject;\n }\n /**\n * Creates a Glow Layer from parsed glow layer data\n * @param parsedGlowLayer defines glow layer data\n * @param scene defines the current scene\n * @param rootUrl defines the root URL containing the glow layer information\n * @returns a parsed Glow Layer\n */\n static Parse(parsedGlowLayer, scene, rootUrl) {\n const gl = SerializationHelper.Parse(() => new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options), parsedGlowLayer, scene, rootUrl);\n let index;\n // Excluded meshes\n for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {\n const mesh = scene.getMeshById(parsedGlowLayer.excludedMeshes[index]);\n if (mesh) {\n gl.addExcludedMesh(mesh);\n }\n }\n // Included meshes\n for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {\n const mesh = scene.getMeshById(parsedGlowLayer.includedMeshes[index]);\n if (mesh) {\n gl.addIncludedOnlyMesh(mesh);\n }\n }\n return gl;\n }\n}\n/**\n * Effect Name of the layer.\n */\nGlowLayer.EffectName = \"GlowLayer\";\n/**\n * The default blur kernel size used for the glow.\n */\nGlowLayer.DefaultBlurKernelSize = 32;\n/**\n * The default texture size ratio used for the glow.\n */\nGlowLayer.DefaultTextureRatio = 0.5;\n__decorate([\n serialize()\n], GlowLayer.prototype, \"blurKernelSize\", null);\n__decorate([\n serialize()\n], GlowLayer.prototype, \"intensity\", null);\n__decorate([\n serialize(\"options\")\n], GlowLayer.prototype, \"_options\", void 0);\nRegisterClass(\"BABYLON.GlowLayer\", GlowLayer);\n//# sourceMappingURL=glowLayer.js.map","import { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n/**\n * Defines the layer scene component responsible to manage any layers\n * in a given scene.\n */\nexport class LayerSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpful to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_LAYER;\n this.scene = scene || EngineStore.LastCreatedScene;\n if (!this.scene) {\n return;\n }\n this._engine = this.scene.getEngine();\n this.scene.layers = new Array();\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene._beforeCameraDrawStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawCameraBackground);\n this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawCameraForegroundWithPostProcessing);\n this.scene._afterCameraPostProcessStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERAPOSTPROCESS_LAYER, this, this._drawCameraForegroundWithoutPostProcessing);\n this.scene._beforeRenderTargetDrawStage.registerStep(SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_LAYER, this, this._drawRenderTargetBackground);\n this.scene._afterRenderTargetDrawStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_LAYER, this, this._drawRenderTargetForegroundWithPostProcessing);\n this.scene._afterRenderTargetPostProcessStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER, this, this._drawRenderTargetForegroundWithoutPostProcessing);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n const layers = this.scene.layers;\n for (const layer of layers) {\n layer._rebuild();\n }\n }\n /**\n * Disposes the component and the associated resources.\n */\n dispose() {\n const layers = this.scene.layers;\n while (layers.length) {\n layers[0].dispose();\n }\n }\n _draw(predicate) {\n const layers = this.scene.layers;\n if (layers.length) {\n this._engine.setDepthBuffer(false);\n for (const layer of layers) {\n if (predicate(layer)) {\n layer.render();\n }\n }\n this._engine.setDepthBuffer(true);\n }\n }\n _drawCameraPredicate(layer, isBackground, applyPostProcess, cameraLayerMask) {\n return (!layer.renderOnlyInRenderTargetTextures &&\n layer.isBackground === isBackground &&\n layer.applyPostProcess === applyPostProcess &&\n (layer.layerMask & cameraLayerMask) !== 0);\n }\n _drawCameraBackground(camera) {\n this._draw((layer) => {\n return this._drawCameraPredicate(layer, true, true, camera.layerMask);\n });\n }\n _drawCameraForegroundWithPostProcessing(camera) {\n this._draw((layer) => {\n return this._drawCameraPredicate(layer, false, true, camera.layerMask);\n });\n }\n _drawCameraForegroundWithoutPostProcessing(camera) {\n this._draw((layer) => {\n return this._drawCameraPredicate(layer, false, false, camera.layerMask);\n });\n }\n _drawRenderTargetPredicate(layer, isBackground, applyPostProcess, cameraLayerMask, renderTargetTexture) {\n return (layer.renderTargetTextures.length > 0 &&\n layer.isBackground === isBackground &&\n layer.applyPostProcess === applyPostProcess &&\n layer.renderTargetTextures.indexOf(renderTargetTexture) > -1 &&\n (layer.layerMask & cameraLayerMask) !== 0);\n }\n _drawRenderTargetBackground(renderTarget) {\n this._draw((layer) => {\n return this._drawRenderTargetPredicate(layer, true, true, this.scene.activeCamera.layerMask, renderTarget);\n });\n }\n _drawRenderTargetForegroundWithPostProcessing(renderTarget) {\n this._draw((layer) => {\n return this._drawRenderTargetPredicate(layer, false, true, this.scene.activeCamera.layerMask, renderTarget);\n });\n }\n _drawRenderTargetForegroundWithoutPostProcessing(renderTarget) {\n this._draw((layer) => {\n return this._drawRenderTargetPredicate(layer, false, false, this.scene.activeCamera.layerMask, renderTarget);\n });\n }\n /**\n * Adds all the elements from the container to the scene\n * @param container the container holding the elements\n */\n addFromContainer(container) {\n if (!container.layers) {\n return;\n }\n container.layers.forEach((layer) => {\n this.scene.layers.push(layer);\n });\n }\n /**\n * Removes all the elements in the container from the scene\n * @param container contains the elements to remove\n * @param dispose if the removed element should be disposed (default: false)\n */\n removeFromContainer(container, dispose = false) {\n if (!container.layers) {\n return;\n }\n container.layers.forEach((layer) => {\n const index = this.scene.layers.indexOf(layer);\n if (index !== -1) {\n this.scene.layers.splice(index, 1);\n }\n if (dispose) {\n layer.dispose();\n }\n });\n }\n}\n//# sourceMappingURL=layerSceneComponent.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"glowBlurPostProcessPixelShader\";\nconst shader = `varying vec2 vUV;\runiform sampler2D textureSampler;\runiform vec2 screenSize;\runiform vec2 direction;\runiform float blurWidth;\rfloat getLuminance(vec3 color)\r{\rreturn dot(color,vec3(0.2126,0.7152,0.0722));\r}\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\r{\rfloat weights[7];\rweights[0]=0.05;\rweights[1]=0.1;\rweights[2]=0.2;\rweights[3]=0.3;\rweights[4]=0.2;\rweights[5]=0.1;\rweights[6]=0.05;\rvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\rvec2 texelStep=texelSize*direction*blurWidth;\rvec2 start=vUV-3.0*texelStep;\rvec4 baseColor=vec4(0.,0.,0.,0.);\rvec2 texelOffset=vec2(0.,0.);\rfor (int i=0; i<7; i++)\r{\rvec4 texel=texture2D(textureSampler,start+texelOffset);\rbaseColor.a+=texel.a*weights[i];\rfloat luminance=getLuminance(baseColor.rgb);\rfloat luminanceTexel=getLuminance(texel.rgb);\rfloat choice=step(luminanceTexel,luminance);\rbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\rtexelOffset+=texelStep;\r}\rgl_FragColor=baseColor;\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const glowBlurPostProcessPixelShader = { name, shader };\n//# sourceMappingURL=glowBlurPostProcess.fragment.js.map","import { __decorate } from \"../tslib.es6.js\";\n/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { serialize, SerializationHelper } from \"../Misc/decorators.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Vector2 } from \"../Maths/math.vector.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Material } from \"../Materials/material.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { RenderTargetTexture } from \"../Materials/Textures/renderTargetTexture.js\";\nimport { PostProcess } from \"../PostProcesses/postProcess.js\";\nimport { PassPostProcess } from \"../PostProcesses/passPostProcess.js\";\nimport { BlurPostProcess } from \"../PostProcesses/blurPostProcess.js\";\nimport { EffectLayer } from \"./effectLayer.js\";\nimport { AbstractScene } from \"../abstractScene.js\";\n\nimport { Logger } from \"../Misc/logger.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\nimport { Color4, Color3 } from \"../Maths/math.color.js\";\nimport \"../Shaders/glowMapMerge.fragment.js\";\nimport \"../Shaders/glowMapMerge.vertex.js\";\nimport \"../Shaders/glowBlurPostProcess.fragment.js\";\nimport \"../Layers/effectLayerSceneComponent.js\";\nAbstractScene.prototype.getHighlightLayerByName = function (name) {\n var _a;\n for (let index = 0; index < ((_a = this.effectLayers) === null || _a === void 0 ? void 0 : _a.length); index++) {\n if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {\n return this.effectLayers[index];\n }\n }\n return null;\n};\n/**\n * Special Glow Blur post process only blurring the alpha channel\n * It enforces keeping the most luminous color in the color channel.\n */\nclass GlowBlurPostProcess extends PostProcess {\n constructor(name, direction, kernel, options, camera, samplingMode = Texture.BILINEAR_SAMPLINGMODE, engine, reusable) {\n super(name, \"glowBlurPostProcess\", [\"screenSize\", \"direction\", \"blurWidth\"], null, options, camera, samplingMode, engine, reusable);\n this.direction = direction;\n this.kernel = kernel;\n this.onApplyObservable.add((effect) => {\n effect.setFloat2(\"screenSize\", this.width, this.height);\n effect.setVector2(\"direction\", this.direction);\n effect.setFloat(\"blurWidth\", this.kernel);\n });\n }\n}\n/**\n * The highlight layer Helps adding a glow effect around a mesh.\n *\n * Once instantiated in a scene, simply use the addMesh or removeMesh method to add or remove\n * glowy meshes to your scene.\n *\n * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!\n */\nexport class HighlightLayer extends EffectLayer {\n /**\n * Specifies the horizontal size of the blur.\n */\n set blurHorizontalSize(value) {\n this._horizontalBlurPostprocess.kernel = value;\n this._options.blurHorizontalSize = value;\n }\n /**\n * Specifies the vertical size of the blur.\n */\n set blurVerticalSize(value) {\n this._verticalBlurPostprocess.kernel = value;\n this._options.blurVerticalSize = value;\n }\n /**\n * Gets the horizontal size of the blur.\n */\n get blurHorizontalSize() {\n return this._horizontalBlurPostprocess.kernel;\n }\n /**\n * Gets the vertical size of the blur.\n */\n get blurVerticalSize() {\n return this._verticalBlurPostprocess.kernel;\n }\n /**\n * Instantiates a new highlight Layer and references it to the scene..\n * @param name The name of the layer\n * @param scene The scene to use the layer in\n * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)\n */\n constructor(name, scene, options) {\n super(name, scene);\n this.name = name;\n /**\n * Specifies whether or not the inner glow is ACTIVE in the layer.\n */\n this.innerGlow = true;\n /**\n * Specifies whether or not the outer glow is ACTIVE in the layer.\n */\n this.outerGlow = true;\n /**\n * An event triggered when the highlight layer is being blurred.\n */\n this.onBeforeBlurObservable = new Observable();\n /**\n * An event triggered when the highlight layer has been blurred.\n */\n this.onAfterBlurObservable = new Observable();\n this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;\n this._meshes = {};\n this._excludedMeshes = {};\n this.neutralColor = HighlightLayer.NeutralColor;\n // Warn on stencil\n if (!this._engine.isStencilEnable) {\n Logger.Warn(\"Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }\");\n }\n // Adapt options\n this._options = Object.assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: 2, camera: null, renderingGroupId: -1, mainTextureType: 0 }, options);\n // Initialize the layer\n this._init({\n alphaBlendingMode: this._options.alphaBlendingMode,\n camera: this._options.camera,\n mainTextureFixedSize: this._options.mainTextureFixedSize,\n mainTextureRatio: this._options.mainTextureRatio,\n renderingGroupId: this._options.renderingGroupId,\n mainTextureType: this._options.mainTextureType,\n });\n // Do not render as long as no meshes have been added\n this._shouldRender = false;\n }\n /**\n * Get the effect name of the layer.\n * @returns The effect name\n */\n getEffectName() {\n return HighlightLayer.EffectName;\n }\n _numInternalDraws() {\n return 2; // we need two rendering, one for the inner glow and the other for the outer glow\n }\n /**\n * Create the merge effect. This is the shader use to blit the information back\n * to the main canvas at the end of the scene rendering.\n */\n _createMergeEffect() {\n // Effect\n return this._engine.createEffect(\"glowMapMerge\", [VertexBuffer.PositionKind], [\"offset\"], [\"textureSampler\"], this._options.isStroke ? \"#define STROKE \\n\" : undefined);\n }\n /**\n * Creates the render target textures and post processes used in the highlight layer.\n */\n _createTextureAndPostProcesses() {\n let blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;\n let blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;\n blurTextureWidth = this._engine.needPOTTextures ? Engine.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;\n blurTextureHeight = this._engine.needPOTTextures ? Engine.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;\n let textureType = 0;\n if (this._engine.getCaps().textureHalfFloatRender) {\n textureType = 2;\n }\n else {\n textureType = 0;\n }\n this._blurTexture = new RenderTargetTexture(\"HighlightLayerBlurRTT\", {\n width: blurTextureWidth,\n height: blurTextureHeight,\n }, this._scene, false, true, textureType);\n this._blurTexture.wrapU = Texture.CLAMP_ADDRESSMODE;\n this._blurTexture.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._blurTexture.anisotropicFilteringLevel = 16;\n this._blurTexture.updateSamplingMode(Texture.TRILINEAR_SAMPLINGMODE);\n this._blurTexture.renderParticles = false;\n this._blurTexture.ignoreCameraViewport = true;\n this._textures = [this._blurTexture];\n if (this._options.alphaBlendingMode === 2) {\n this._downSamplePostprocess = new PassPostProcess(\"HighlightLayerPPP\", this._options.blurTextureSizeRatio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());\n this._downSamplePostprocess.externalTextureSamplerBinding = true;\n this._downSamplePostprocess.onApplyObservable.add((effect) => {\n effect.setTexture(\"textureSampler\", this._mainTexture);\n });\n this._horizontalBlurPostprocess = new GlowBlurPostProcess(\"HighlightLayerHBP\", new Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());\n this._horizontalBlurPostprocess.onApplyObservable.add((effect) => {\n effect.setFloat2(\"screenSize\", blurTextureWidth, blurTextureHeight);\n });\n this._verticalBlurPostprocess = new GlowBlurPostProcess(\"HighlightLayerVBP\", new Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());\n this._verticalBlurPostprocess.onApplyObservable.add((effect) => {\n effect.setFloat2(\"screenSize\", blurTextureWidth, blurTextureHeight);\n });\n this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];\n }\n else {\n this._horizontalBlurPostprocess = new BlurPostProcess(\"HighlightLayerHBP\", new Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {\n width: blurTextureWidth,\n height: blurTextureHeight,\n }, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);\n this._horizontalBlurPostprocess.width = blurTextureWidth;\n this._horizontalBlurPostprocess.height = blurTextureHeight;\n this._horizontalBlurPostprocess.externalTextureSamplerBinding = true;\n this._horizontalBlurPostprocess.onApplyObservable.add((effect) => {\n effect.setTexture(\"textureSampler\", this._mainTexture);\n });\n this._verticalBlurPostprocess = new BlurPostProcess(\"HighlightLayerVBP\", new Vector2(0, 1.0), this._options.blurVerticalSize / 2, {\n width: blurTextureWidth,\n height: blurTextureHeight,\n }, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);\n this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];\n }\n this._mainTexture.onAfterUnbindObservable.add(() => {\n this.onBeforeBlurObservable.notifyObservers(this);\n const internalTexture = this._blurTexture.renderTarget;\n if (internalTexture) {\n this._scene.postProcessManager.directRender(this._postProcesses, internalTexture, true);\n this._engine.unBindFramebuffer(internalTexture, true);\n }\n this.onAfterBlurObservable.notifyObservers(this);\n });\n // Prevent autoClear.\n this._postProcesses.map((pp) => {\n pp.autoClear = false;\n });\n }\n /**\n * Returns whether or not the layer needs stencil enabled during the mesh rendering.\n */\n needStencil() {\n return true;\n }\n /**\n * Checks for the readiness of the element composing the layer.\n * @param subMesh the mesh to check for\n * @param useInstances specify whether or not to use instances to render the mesh\n * @returns true if ready otherwise, false\n */\n isReady(subMesh, useInstances) {\n const material = subMesh.getMaterial();\n const mesh = subMesh.getRenderingMesh();\n if (!material || !mesh || !this._meshes) {\n return false;\n }\n let emissiveTexture = null;\n const highlightLayerMesh = this._meshes[mesh.uniqueId];\n if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {\n emissiveTexture = material.emissiveTexture;\n }\n return super._isReady(subMesh, useInstances, emissiveTexture);\n }\n /**\n * Implementation specific of rendering the generating effect on the main canvas.\n * @param effect The effect used to render through\n * @param renderIndex\n */\n _internalRender(effect, renderIndex) {\n // Texture\n effect.setTexture(\"textureSampler\", this._blurTexture);\n // Cache\n const engine = this._engine;\n engine.cacheStencilState();\n // Stencil operations\n engine.setStencilOperationPass(7681);\n engine.setStencilOperationFail(7680);\n engine.setStencilOperationDepthFail(7680);\n // Draw order\n engine.setStencilMask(0x00);\n engine.setStencilBuffer(true);\n engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);\n // 2 passes inner outer\n if (this.outerGlow && renderIndex === 0) {\n // the outer glow is rendered the first time _internalRender is called, so when renderIndex == 0 (and only if outerGlow is enabled)\n effect.setFloat(\"offset\", 0);\n engine.setStencilFunction(517);\n engine.drawElementsType(Material.TriangleFillMode, 0, 6);\n }\n if (this.innerGlow && renderIndex === 1) {\n // the inner glow is rendered the second time _internalRender is called, so when renderIndex == 1 (and only if innerGlow is enabled)\n effect.setFloat(\"offset\", 1);\n engine.setStencilFunction(514);\n engine.drawElementsType(Material.TriangleFillMode, 0, 6);\n }\n // Restore Cache\n engine.restoreStencilState();\n }\n /**\n * Returns true if the layer contains information to display, otherwise false.\n */\n shouldRender() {\n if (super.shouldRender()) {\n return this._meshes ? true : false;\n }\n return false;\n }\n /**\n * Returns true if the mesh should render, otherwise false.\n * @param mesh The mesh to render\n * @returns true if it should render otherwise false\n */\n _shouldRenderMesh(mesh) {\n // Excluded Mesh\n if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {\n return false;\n }\n if (!super.hasMesh(mesh)) {\n return false;\n }\n return true;\n }\n /**\n * Returns true if the mesh can be rendered, otherwise false.\n * @param mesh The mesh to render\n * @param material The material used on the mesh\n * @returns true if it can be rendered otherwise false\n */\n _canRenderMesh(mesh, material) {\n // all meshes can be rendered in the highlight layer, even transparent ones\n return true;\n }\n /**\n * Adds specific effects defines.\n * @param defines The defines to add specifics to.\n */\n _addCustomEffectDefines(defines) {\n defines.push(\"#define HIGHLIGHT\");\n }\n /**\n * Sets the required values for both the emissive texture and and the main color.\n * @param mesh\n * @param subMesh\n * @param material\n */\n _setEmissiveTextureAndColor(mesh, subMesh, material) {\n const highlightLayerMesh = this._meshes[mesh.uniqueId];\n if (highlightLayerMesh) {\n this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);\n }\n else {\n this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);\n }\n if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {\n this._emissiveTextureAndColor.texture = material.emissiveTexture;\n this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);\n }\n else {\n this._emissiveTextureAndColor.texture = null;\n }\n }\n /**\n * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.\n * @param mesh The mesh to exclude from the highlight layer\n */\n addExcludedMesh(mesh) {\n if (!this._excludedMeshes) {\n return;\n }\n const meshExcluded = this._excludedMeshes[mesh.uniqueId];\n if (!meshExcluded) {\n const obj = {\n mesh: mesh,\n beforeBind: null,\n afterRender: null,\n stencilState: false,\n };\n obj.beforeBind = mesh.onBeforeBindObservable.add((mesh) => {\n obj.stencilState = mesh.getEngine().getStencilBuffer();\n mesh.getEngine().setStencilBuffer(false);\n });\n obj.afterRender = mesh.onAfterRenderObservable.add((mesh) => {\n mesh.getEngine().setStencilBuffer(obj.stencilState);\n });\n this._excludedMeshes[mesh.uniqueId] = obj;\n }\n }\n /**\n * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.\n * @param mesh The mesh to highlight\n */\n removeExcludedMesh(mesh) {\n if (!this._excludedMeshes) {\n return;\n }\n const meshExcluded = this._excludedMeshes[mesh.uniqueId];\n if (meshExcluded) {\n if (meshExcluded.beforeBind) {\n mesh.onBeforeBindObservable.remove(meshExcluded.beforeBind);\n }\n if (meshExcluded.afterRender) {\n mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);\n }\n }\n this._excludedMeshes[mesh.uniqueId] = null;\n }\n /**\n * Determine if a given mesh will be highlighted by the current HighlightLayer\n * @param mesh mesh to test\n * @returns true if the mesh will be highlighted by the current HighlightLayer\n */\n hasMesh(mesh) {\n if (!this._meshes) {\n return false;\n }\n if (!super.hasMesh(mesh)) {\n return false;\n }\n return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;\n }\n /**\n * Add a mesh in the highlight layer in order to make it glow with the chosen color.\n * @param mesh The mesh to highlight\n * @param color The color of the highlight\n * @param glowEmissiveOnly Extract the glow from the emissive texture\n */\n addMesh(mesh, color, glowEmissiveOnly = false) {\n if (!this._meshes) {\n return;\n }\n const meshHighlight = this._meshes[mesh.uniqueId];\n if (meshHighlight) {\n meshHighlight.color = color;\n }\n else {\n this._meshes[mesh.uniqueId] = {\n mesh: mesh,\n color: color,\n // Lambda required for capture due to Observable this context\n observerHighlight: mesh.onBeforeBindObservable.add((mesh) => {\n if (this.isEnabled) {\n if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {\n this._defaultStencilReference(mesh);\n }\n else {\n mesh.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference);\n }\n }\n }),\n observerDefault: mesh.onAfterRenderObservable.add((mesh) => {\n if (this.isEnabled) {\n this._defaultStencilReference(mesh);\n }\n }),\n glowEmissiveOnly: glowEmissiveOnly,\n };\n mesh.onDisposeObservable.add(() => {\n this._disposeMesh(mesh);\n });\n }\n this._shouldRender = true;\n }\n /**\n * Remove a mesh from the highlight layer in order to make it stop glowing.\n * @param mesh The mesh to highlight\n */\n removeMesh(mesh) {\n if (!this._meshes) {\n return;\n }\n const meshHighlight = this._meshes[mesh.uniqueId];\n if (meshHighlight) {\n if (meshHighlight.observerHighlight) {\n mesh.onBeforeBindObservable.remove(meshHighlight.observerHighlight);\n }\n if (meshHighlight.observerDefault) {\n mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);\n }\n delete this._meshes[mesh.uniqueId];\n }\n this._shouldRender = false;\n for (const meshHighlightToCheck in this._meshes) {\n if (this._meshes[meshHighlightToCheck]) {\n this._shouldRender = true;\n break;\n }\n }\n }\n /**\n * Remove all the meshes currently referenced in the highlight layer\n */\n removeAllMeshes() {\n if (!this._meshes) {\n return;\n }\n for (const uniqueId in this._meshes) {\n if (Object.prototype.hasOwnProperty.call(this._meshes, uniqueId)) {\n const mesh = this._meshes[uniqueId];\n if (mesh) {\n this.removeMesh(mesh.mesh);\n }\n }\n }\n }\n /**\n * Force the stencil to the normal expected value for none glowing parts\n * @param mesh\n */\n _defaultStencilReference(mesh) {\n mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);\n }\n /**\n * Free any resources and references associated to a mesh.\n * Internal use\n * @param mesh The mesh to free.\n * @internal\n */\n _disposeMesh(mesh) {\n this.removeMesh(mesh);\n this.removeExcludedMesh(mesh);\n }\n /**\n * Dispose the highlight layer and free resources.\n */\n dispose() {\n if (this._meshes) {\n // Clean mesh references\n for (const id in this._meshes) {\n const meshHighlight = this._meshes[id];\n if (meshHighlight && meshHighlight.mesh) {\n if (meshHighlight.observerHighlight) {\n meshHighlight.mesh.onBeforeBindObservable.remove(meshHighlight.observerHighlight);\n }\n if (meshHighlight.observerDefault) {\n meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);\n }\n }\n }\n this._meshes = null;\n }\n if (this._excludedMeshes) {\n for (const id in this._excludedMeshes) {\n const meshHighlight = this._excludedMeshes[id];\n if (meshHighlight) {\n if (meshHighlight.beforeBind) {\n meshHighlight.mesh.onBeforeBindObservable.remove(meshHighlight.beforeBind);\n }\n if (meshHighlight.afterRender) {\n meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);\n }\n }\n }\n this._excludedMeshes = null;\n }\n super.dispose();\n }\n /**\n * Gets the class name of the effect layer\n * @returns the string with the class name of the effect layer\n */\n getClassName() {\n return \"HighlightLayer\";\n }\n /**\n * Serializes this Highlight layer\n * @returns a serialized Highlight layer object\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this);\n serializationObject.customType = \"BABYLON.HighlightLayer\";\n // Highlighted meshes\n serializationObject.meshes = [];\n if (this._meshes) {\n for (const m in this._meshes) {\n const mesh = this._meshes[m];\n if (mesh) {\n serializationObject.meshes.push({\n glowEmissiveOnly: mesh.glowEmissiveOnly,\n color: mesh.color.asArray(),\n meshId: mesh.mesh.id,\n });\n }\n }\n }\n // Excluded meshes\n serializationObject.excludedMeshes = [];\n if (this._excludedMeshes) {\n for (const e in this._excludedMeshes) {\n const excludedMesh = this._excludedMeshes[e];\n if (excludedMesh) {\n serializationObject.excludedMeshes.push(excludedMesh.mesh.id);\n }\n }\n }\n return serializationObject;\n }\n /**\n * Creates a Highlight layer from parsed Highlight layer data\n * @param parsedHightlightLayer defines the Highlight layer data\n * @param scene defines the current scene\n * @param rootUrl defines the root URL containing the Highlight layer information\n * @returns a parsed Highlight layer\n */\n static Parse(parsedHightlightLayer, scene, rootUrl) {\n const hl = SerializationHelper.Parse(() => new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options), parsedHightlightLayer, scene, rootUrl);\n let index;\n // Excluded meshes\n for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {\n const mesh = scene.getMeshById(parsedHightlightLayer.excludedMeshes[index]);\n if (mesh) {\n hl.addExcludedMesh(mesh);\n }\n }\n // Included meshes\n for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {\n const highlightedMesh = parsedHightlightLayer.meshes[index];\n const mesh = scene.getMeshById(highlightedMesh.meshId);\n if (mesh) {\n hl.addMesh(mesh, Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);\n }\n }\n return hl;\n }\n}\n/**\n * Effect Name of the highlight layer.\n */\nHighlightLayer.EffectName = \"HighlightLayer\";\n/**\n * The neutral color used during the preparation of the glow effect.\n * This is black by default as the blend operation is a blend operation.\n */\nHighlightLayer.NeutralColor = new Color4(0, 0, 0, 0);\n/**\n * Stencil value used for glowing meshes.\n */\nHighlightLayer.GlowingMeshStencilReference = 0x02;\n/**\n * Stencil value used for the other meshes in the scene.\n */\nHighlightLayer.NormalMeshStencilReference = 0x01;\n__decorate([\n serialize()\n], HighlightLayer.prototype, \"innerGlow\", void 0);\n__decorate([\n serialize()\n], HighlightLayer.prototype, \"outerGlow\", void 0);\n__decorate([\n serialize()\n], HighlightLayer.prototype, \"blurHorizontalSize\", null);\n__decorate([\n serialize()\n], HighlightLayer.prototype, \"blurVerticalSize\", null);\n__decorate([\n serialize(\"options\")\n], HighlightLayer.prototype, \"_options\", void 0);\nRegisterClass(\"BABYLON.HighlightLayer\", HighlightLayer);\n//# sourceMappingURL=highlightLayer.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { Vector2 } from \"../Maths/math.vector.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Material } from \"../Materials/material.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { LayerSceneComponent } from \"./layerSceneComponent.js\";\n\nimport { DrawWrapper } from \"../Materials/drawWrapper.js\";\nimport \"../Shaders/layer.fragment.js\";\nimport \"../Shaders/layer.vertex.js\";\n/**\n * This represents a full screen 2d layer.\n * This can be useful to display a picture in the background of your scene for instance.\n * @see https://www.babylonjs-playground.com/#08A2BS#1\n */\nexport class Layer {\n /**\n * Determines if the layer is drawn before (true) or after (false) post-processing.\n * If the layer is background, it is always before.\n */\n set applyPostProcess(value) {\n this._applyPostProcess = value;\n }\n get applyPostProcess() {\n return this.isBackground || this._applyPostProcess;\n }\n /**\n * Back compatibility with callback before the onDisposeObservable existed.\n * The set callback will be triggered when the layer has been disposed.\n */\n set onDispose(callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n }\n /**\n * Back compatibility with callback before the onBeforeRenderObservable existed.\n * The set callback will be triggered just before rendering the layer.\n */\n set onBeforeRender(callback) {\n if (this._onBeforeRenderObserver) {\n this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);\n }\n this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);\n }\n /**\n * Back compatibility with callback before the onAfterRenderObservable existed.\n * The set callback will be triggered just after rendering the layer.\n */\n set onAfterRender(callback) {\n if (this._onAfterRenderObserver) {\n this.onAfterRenderObservable.remove(this._onAfterRenderObserver);\n }\n this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);\n }\n /**\n * Instantiates a new layer.\n * This represents a full screen 2d layer.\n * This can be useful to display a picture in the background of your scene for instance.\n * @see https://www.babylonjs-playground.com/#08A2BS#1\n * @param name Define the name of the layer in the scene\n * @param imgUrl Define the url of the texture to display in the layer\n * @param scene Define the scene the layer belongs to\n * @param isBackground Defines whether the layer is displayed in front or behind the scene\n * @param color Defines a color for the layer\n */\n constructor(\n /**\n * Define the name of the layer.\n */\n name, imgUrl, scene, isBackground, color) {\n this.name = name;\n this._applyPostProcess = true;\n /**\n * Define the scale of the layer in order to zoom in out of the texture.\n */\n this.scale = new Vector2(1, 1);\n /**\n * Define an offset for the layer in order to shift the texture.\n */\n this.offset = new Vector2(0, 0);\n /**\n * Define the alpha blending mode used in the layer in case the texture or color has an alpha.\n */\n this.alphaBlendingMode = 2;\n /**\n * Define a mask to restrict the layer to only some of the scene cameras.\n */\n this.layerMask = 0x0fffffff;\n /**\n * Define the list of render target the layer is visible into.\n */\n this.renderTargetTextures = [];\n /**\n * Define if the layer is only used in renderTarget or if it also\n * renders in the main frame buffer of the canvas.\n */\n this.renderOnlyInRenderTargetTextures = false;\n /**\n * Define if the layer is enabled (ie. should be displayed). Default: true\n */\n this.isEnabled = true;\n this._vertexBuffers = {};\n /**\n * An event triggered when the layer is disposed.\n */\n this.onDisposeObservable = new Observable();\n /**\n * An event triggered before rendering the scene\n */\n this.onBeforeRenderObservable = new Observable();\n /**\n * An event triggered after rendering the scene\n */\n this.onAfterRenderObservable = new Observable();\n this.texture = imgUrl ? new Texture(imgUrl, scene, true) : null;\n this.isBackground = isBackground === undefined ? true : isBackground;\n this.color = color === undefined ? new Color4(1, 1, 1, 1) : color;\n this._scene = (scene || EngineStore.LastCreatedScene);\n let layerComponent = this._scene._getComponent(SceneComponentConstants.NAME_LAYER);\n if (!layerComponent) {\n layerComponent = new LayerSceneComponent(this._scene);\n this._scene._addComponent(layerComponent);\n }\n this._scene.layers.push(this);\n const engine = this._scene.getEngine();\n this._drawWrapper = new DrawWrapper(engine);\n // VBO\n const vertices = [];\n vertices.push(1, 1);\n vertices.push(-1, 1);\n vertices.push(-1, -1);\n vertices.push(1, -1);\n const vertexBuffer = new VertexBuffer(engine, vertices, VertexBuffer.PositionKind, false, false, 2);\n this._vertexBuffers[VertexBuffer.PositionKind] = vertexBuffer;\n this._createIndexBuffer();\n }\n _createIndexBuffer() {\n const engine = this._scene.getEngine();\n // Indices\n const indices = [];\n indices.push(0);\n indices.push(1);\n indices.push(2);\n indices.push(0);\n indices.push(2);\n indices.push(3);\n this._indexBuffer = engine.createIndexBuffer(indices);\n }\n /** @internal */\n _rebuild() {\n const vb = this._vertexBuffers[VertexBuffer.PositionKind];\n if (vb) {\n vb._rebuild();\n }\n this._createIndexBuffer();\n }\n /**\n * Checks if the layer is ready to be rendered\n * @returns true if the layer is ready. False otherwise.\n */\n isReady() {\n var _a;\n const engine = this._scene.getEngine();\n let defines = \"\";\n if (this.alphaTest) {\n defines = \"#define ALPHATEST\";\n }\n if (this.texture && !this.texture.gammaSpace) {\n defines += \"\\r\\n#define LINEAR\";\n }\n if (this._previousDefines !== defines) {\n this._previousDefines = defines;\n this._drawWrapper.effect = engine.createEffect(\"layer\", [VertexBuffer.PositionKind], [\"textureMatrix\", \"color\", \"scale\", \"offset\"], [\"textureSampler\"], defines);\n }\n const currentEffect = this._drawWrapper.effect;\n return (currentEffect === null || currentEffect === void 0 ? void 0 : currentEffect.isReady()) && ((_a = this.texture) === null || _a === void 0 ? void 0 : _a.isReady());\n }\n /**\n * Renders the layer in the scene.\n */\n render() {\n if (!this.isEnabled) {\n return;\n }\n const engine = this._scene.getEngine();\n // Check\n if (!this.isReady()) {\n return;\n }\n const currentEffect = this._drawWrapper.effect;\n this.onBeforeRenderObservable.notifyObservers(this);\n // Render\n engine.enableEffect(this._drawWrapper);\n engine.setState(false);\n // Texture\n currentEffect.setTexture(\"textureSampler\", this.texture);\n currentEffect.setMatrix(\"textureMatrix\", this.texture.getTextureMatrix());\n // Color\n currentEffect.setFloat4(\"color\", this.color.r, this.color.g, this.color.b, this.color.a);\n // Scale / offset\n currentEffect.setVector2(\"offset\", this.offset);\n currentEffect.setVector2(\"scale\", this.scale);\n // VBOs\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);\n // Draw order\n if (!this.alphaTest) {\n engine.setAlphaMode(this.alphaBlendingMode);\n engine.drawElementsType(Material.TriangleFillMode, 0, 6);\n engine.setAlphaMode(0);\n }\n else {\n engine.drawElementsType(Material.TriangleFillMode, 0, 6);\n }\n this.onAfterRenderObservable.notifyObservers(this);\n }\n /**\n * Disposes and releases the associated resources.\n */\n dispose() {\n const vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];\n if (vertexBuffer) {\n vertexBuffer.dispose();\n this._vertexBuffers[VertexBuffer.PositionKind] = null;\n }\n if (this._indexBuffer) {\n this._scene.getEngine()._releaseBuffer(this._indexBuffer);\n this._indexBuffer = null;\n }\n if (this.texture) {\n this.texture.dispose();\n this.texture = null;\n }\n // Clean RTT list\n this.renderTargetTextures = [];\n // Remove from scene\n const index = this._scene.layers.indexOf(this);\n this._scene.layers.splice(index, 1);\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n this.onAfterRenderObservable.clear();\n this.onBeforeRenderObservable.clear();\n }\n}\n//# sourceMappingURL=layer.js.map","export * from \"./effectLayer.js\";\nexport * from \"./effectLayerSceneComponent.js\";\nexport * from \"./glowLayer.js\";\nexport * from \"./highlightLayer.js\";\nexport * from \"./layer.js\";\nexport * from \"./layerSceneComponent.js\";\n//# sourceMappingURL=index.js.map","import { Color3 } from \"../Maths/math.color.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\n\nimport { DrawWrapper } from \"../Materials/drawWrapper.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\n/**\n * This represents one of the lens effect in a `lensFlareSystem`.\n * It controls one of the individual texture used in the effect.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare\n */\nexport class LensFlare {\n /**\n * Creates a new Lens Flare.\n * This represents one of the lens effect in a `lensFlareSystem`.\n * It controls one of the individual texture used in the effect.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare\n * @param size Define the size of the lens flare (a floating value between 0 and 1)\n * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.\n * @param color Define the lens color\n * @param imgUrl Define the lens texture url\n * @param system Define the `lensFlareSystem` this flare is part of\n * @returns The newly created Lens Flare\n */\n static AddFlare(size, position, color, imgUrl, system) {\n return new LensFlare(size, position, color, imgUrl, system);\n }\n /**\n * Instantiates a new Lens Flare.\n * This represents one of the lens effect in a `lensFlareSystem`.\n * It controls one of the individual texture used in the effect.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare\n * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)\n * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.\n * @param color Define the lens color\n * @param imgUrl Define the lens texture url\n * @param system Define the `lensFlareSystem` this flare is part of\n */\n constructor(\n /**\n * Define the size of the lens flare in the system (a floating value between 0 and 1)\n */\n size, \n /**\n * Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.\n */\n position, color, imgUrl, system) {\n this.size = size;\n this.position = position;\n /**\n * Define the alpha mode to render this particular lens.\n */\n this.alphaMode = 6;\n this.color = color || new Color3(1, 1, 1);\n this.texture = imgUrl ? new Texture(imgUrl, system.getScene(), true) : null;\n this._system = system;\n const engine = system.scene.getEngine();\n this._drawWrapper = new DrawWrapper(engine);\n this._drawWrapper.effect = engine.createEffect(\"lensFlare\", [VertexBuffer.PositionKind], [\"color\", \"viewportMatrix\"], [\"textureSampler\"], \"\");\n system.lensFlares.push(this);\n }\n /**\n * Dispose and release the lens flare with its associated resources.\n */\n dispose() {\n if (this.texture) {\n this.texture.dispose();\n }\n // Remove from scene\n const index = this._system.lensFlares.indexOf(this);\n this._system.lensFlares.splice(index, 1);\n }\n}\n//# sourceMappingURL=lensFlare.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"lensFlarePixelShader\";\nconst shader = `varying vec2 vUV;\runiform sampler2D textureSampler;\runiform vec4 color;\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec4 baseColor=texture2D(textureSampler,vUV);\rgl_FragColor=baseColor*color;\r#define CUSTOM_FRAGMENT_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const lensFlarePixelShader = { name, shader };\n//# sourceMappingURL=lensFlare.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"lensFlareVertexShader\";\nconst shader = `attribute vec2 position;\runiform mat4 viewportMatrix;\rvarying vec2 vUV;\rconst vec2 madd=vec2(0.5,0.5);\r#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=position*madd+madd;\rgl_Position=viewportMatrix*vec4(position,0.0,1.0);\r#define CUSTOM_VERTEX_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const lensFlareVertexShader = { name, shader };\n//# sourceMappingURL=lensFlare.vertex.js.map","import { Tools } from \"../Misc/tools.js\";\nimport { Matrix, Vector3 } from \"../Maths/math.vector.js\";\nimport { Scalar } from \"../Maths/math.scalar.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Ray } from \"../Culling/ray.js\";\nimport { Material } from \"../Materials/material.js\";\nimport { LensFlare } from \"./lensFlare.js\";\n\nimport \"../Shaders/lensFlare.fragment.js\";\nimport \"../Shaders/lensFlare.vertex.js\";\nimport { _WarnImport } from \"../Misc/devTools.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\n/**\n * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.\n * It is usually composed of several `lensFlare`.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare\n */\nexport class LensFlareSystem {\n /** Gets the scene */\n get scene() {\n return this._scene;\n }\n /**\n * Instantiates a lens flare system.\n * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.\n * It is usually composed of several `lensFlare`.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare\n * @param name Define the name of the lens flare system in the scene\n * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).\n * @param scene Define the scene the lens flare system belongs to\n */\n constructor(\n /**\n * Define the name of the lens flare system\n */\n name, emitter, scene) {\n this.name = name;\n /**\n * List of lens flares used in this system.\n */\n this.lensFlares = new Array();\n /**\n * Define a limit from the border the lens flare can be visible.\n */\n this.borderLimit = 300;\n /**\n * Define a viewport border we do not want to see the lens flare in.\n */\n this.viewportBorder = 0;\n /**\n * Restricts the rendering of the effect to only the camera rendering this layer mask.\n */\n this.layerMask = 0x0fffffff;\n this._vertexBuffers = {};\n this._isEnabled = true;\n this._scene = scene || EngineStore.LastCreatedScene;\n LensFlareSystem._SceneComponentInitialization(this._scene);\n this._emitter = emitter;\n this.id = name;\n scene.lensFlareSystems.push(this);\n this.meshesSelectionPredicate = (m) => (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && (m.layerMask & scene.activeCamera.layerMask) != 0);\n const engine = scene.getEngine();\n // VBO\n const vertices = [];\n vertices.push(1, 1);\n vertices.push(-1, 1);\n vertices.push(-1, -1);\n vertices.push(1, -1);\n this._vertexBuffers[VertexBuffer.PositionKind] = new VertexBuffer(engine, vertices, VertexBuffer.PositionKind, false, false, 2);\n // Indices\n this._createIndexBuffer();\n }\n _createIndexBuffer() {\n const indices = [];\n indices.push(0);\n indices.push(1);\n indices.push(2);\n indices.push(0);\n indices.push(2);\n indices.push(3);\n this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);\n }\n /**\n * Define if the lens flare system is enabled.\n */\n get isEnabled() {\n return this._isEnabled;\n }\n set isEnabled(value) {\n this._isEnabled = value;\n }\n /**\n * Get the scene the effects belongs to.\n * @returns the scene holding the lens flare system\n */\n getScene() {\n return this._scene;\n }\n /**\n * Get the emitter of the lens flare system.\n * It defines the source of the lens flares (it can be a camera, a light or a mesh).\n * @returns the emitter of the lens flare system\n */\n getEmitter() {\n return this._emitter;\n }\n /**\n * Set the emitter of the lens flare system.\n * It defines the source of the lens flares (it can be a camera, a light or a mesh).\n * @param newEmitter Define the new emitter of the system\n */\n setEmitter(newEmitter) {\n this._emitter = newEmitter;\n }\n /**\n * Get the lens flare system emitter position.\n * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).\n * @returns the position\n */\n getEmitterPosition() {\n return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;\n }\n /**\n * @internal\n */\n computeEffectivePosition(globalViewport) {\n let position = this.getEmitterPosition();\n position = Vector3.Project(position, Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);\n this._positionX = position.x;\n this._positionY = position.y;\n position = Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());\n if (this.viewportBorder > 0) {\n globalViewport.x -= this.viewportBorder;\n globalViewport.y -= this.viewportBorder;\n globalViewport.width += this.viewportBorder * 2;\n globalViewport.height += this.viewportBorder * 2;\n position.x += this.viewportBorder;\n position.y += this.viewportBorder;\n this._positionX += this.viewportBorder;\n this._positionY += this.viewportBorder;\n }\n const rhs = this._scene.useRightHandedSystem;\n const okZ = (position.z > 0 && !rhs) || (position.z < 0 && rhs);\n if (okZ) {\n if (this._positionX > globalViewport.x && this._positionX < globalViewport.x + globalViewport.width) {\n if (this._positionY > globalViewport.y && this._positionY < globalViewport.y + globalViewport.height) {\n return true;\n }\n }\n return true;\n }\n return false;\n }\n /** @internal */\n _isVisible() {\n if (!this._isEnabled || !this._scene.activeCamera) {\n return false;\n }\n const emitterPosition = this.getEmitterPosition();\n const direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);\n const distance = direction.length();\n direction.normalize();\n const ray = new Ray(this._scene.activeCamera.globalPosition, direction);\n const pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);\n return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;\n }\n /**\n * @internal\n */\n render() {\n if (!this._scene.activeCamera) {\n return false;\n }\n const engine = this._scene.getEngine();\n const viewport = this._scene.activeCamera.viewport;\n const globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));\n // Position\n if (!this.computeEffectivePosition(globalViewport)) {\n return false;\n }\n // Visibility\n if (!this._isVisible()) {\n return false;\n }\n // Intensity\n let awayX;\n let awayY;\n if (this._positionX < this.borderLimit + globalViewport.x) {\n awayX = this.borderLimit + globalViewport.x - this._positionX;\n }\n else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {\n awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;\n }\n else {\n awayX = 0;\n }\n if (this._positionY < this.borderLimit + globalViewport.y) {\n awayY = this.borderLimit + globalViewport.y - this._positionY;\n }\n else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {\n awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;\n }\n else {\n awayY = 0;\n }\n let away = awayX > awayY ? awayX : awayY;\n away -= this.viewportBorder;\n if (away > this.borderLimit) {\n away = this.borderLimit;\n }\n let intensity = 1.0 - Scalar.Clamp(away / this.borderLimit, 0, 1);\n if (intensity < 0) {\n return false;\n }\n if (intensity > 1.0) {\n intensity = 1.0;\n }\n if (this.viewportBorder > 0) {\n globalViewport.x += this.viewportBorder;\n globalViewport.y += this.viewportBorder;\n globalViewport.width -= this.viewportBorder * 2;\n globalViewport.height -= this.viewportBorder * 2;\n this._positionX -= this.viewportBorder;\n this._positionY -= this.viewportBorder;\n }\n // Position\n const centerX = globalViewport.x + globalViewport.width / 2;\n const centerY = globalViewport.y + globalViewport.height / 2;\n const distX = centerX - this._positionX;\n const distY = centerY - this._positionY;\n // Effects\n engine.setState(false);\n engine.setDepthBuffer(false);\n // Flares\n for (let index = 0; index < this.lensFlares.length; index++) {\n const flare = this.lensFlares[index];\n if (!flare._drawWrapper.effect.isReady() || (flare.texture && !flare.texture.isReady())) {\n continue;\n }\n engine.enableEffect(flare._drawWrapper);\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, flare._drawWrapper.effect);\n engine.setAlphaMode(flare.alphaMode);\n const x = centerX - distX * flare.position;\n const y = centerY - distY * flare.position;\n const cw = flare.size;\n const ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);\n const cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;\n const cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));\n const viewportMatrix = Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);\n flare._drawWrapper.effect.setMatrix(\"viewportMatrix\", viewportMatrix);\n // Texture\n flare._drawWrapper.effect.setTexture(\"textureSampler\", flare.texture);\n // Color\n flare._drawWrapper.effect.setFloat4(\"color\", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);\n // Draw order\n engine.drawElementsType(Material.TriangleFillMode, 0, 6);\n }\n engine.setDepthBuffer(true);\n engine.setAlphaMode(0);\n return true;\n }\n /**\n * Rebuilds the lens flare system\n */\n rebuild() {\n var _a;\n this._createIndexBuffer();\n for (const key in this._vertexBuffers) {\n (_a = this._vertexBuffers[key]) === null || _a === void 0 ? void 0 : _a._rebuild();\n }\n }\n /**\n * Dispose and release the lens flare with its associated resources.\n */\n dispose() {\n const vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];\n if (vertexBuffer) {\n vertexBuffer.dispose();\n this._vertexBuffers[VertexBuffer.PositionKind] = null;\n }\n if (this._indexBuffer) {\n this._scene.getEngine()._releaseBuffer(this._indexBuffer);\n this._indexBuffer = null;\n }\n while (this.lensFlares.length) {\n this.lensFlares[0].dispose();\n }\n // Remove from scene\n const index = this._scene.lensFlareSystems.indexOf(this);\n this._scene.lensFlareSystems.splice(index, 1);\n }\n /**\n * Parse a lens flare system from a JSON representation\n * @param parsedLensFlareSystem Define the JSON to parse\n * @param scene Define the scene the parsed system should be instantiated in\n * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures\n * @returns the parsed system\n */\n static Parse(parsedLensFlareSystem, scene, rootUrl) {\n const emitter = scene.getLastEntryById(parsedLensFlareSystem.emitterId);\n const name = parsedLensFlareSystem.name || \"lensFlareSystem#\" + parsedLensFlareSystem.emitterId;\n const lensFlareSystem = new LensFlareSystem(name, emitter, scene);\n lensFlareSystem.id = parsedLensFlareSystem.id || name;\n lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;\n for (let index = 0; index < parsedLensFlareSystem.flares.length; index++) {\n const parsedFlare = parsedLensFlareSystem.flares[index];\n LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : \"\", lensFlareSystem);\n }\n return lensFlareSystem;\n }\n /**\n * Serialize the current Lens Flare System into a JSON representation.\n * @returns the serialized JSON\n */\n serialize() {\n const serializationObject = {};\n serializationObject.id = this.id;\n serializationObject.name = this.name;\n serializationObject.emitterId = this.getEmitter().id;\n serializationObject.borderLimit = this.borderLimit;\n serializationObject.flares = [];\n for (let index = 0; index < this.lensFlares.length; index++) {\n const flare = this.lensFlares[index];\n serializationObject.flares.push({\n size: flare.size,\n position: flare.position,\n color: flare.color.asArray(),\n textureName: Tools.GetFilename(flare.texture ? flare.texture.name : \"\"),\n });\n }\n return serializationObject;\n }\n}\n/**\n * @internal\n */\nLensFlareSystem._SceneComponentInitialization = (_) => {\n throw _WarnImport(\"LensFlareSystemSceneComponent\");\n};\n//# sourceMappingURL=lensFlareSystem.js.map","import { Tools } from \"../Misc/tools.js\";\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { AbstractScene } from \"../abstractScene.js\";\nimport { LensFlareSystem } from \"./lensFlareSystem.js\";\n// Adds the parser to the scene parsers.\nAbstractScene.AddParser(SceneComponentConstants.NAME_LENSFLARESYSTEM, (parsedData, scene, container, rootUrl) => {\n // Lens flares\n if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {\n if (!container.lensFlareSystems) {\n container.lensFlareSystems = new Array();\n }\n for (let index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {\n const parsedLensFlareSystem = parsedData.lensFlareSystems[index];\n const lf = LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);\n container.lensFlareSystems.push(lf);\n }\n }\n});\nAbstractScene.prototype.getLensFlareSystemByName = function (name) {\n for (let index = 0; index < this.lensFlareSystems.length; index++) {\n if (this.lensFlareSystems[index].name === name) {\n return this.lensFlareSystems[index];\n }\n }\n return null;\n};\nAbstractScene.prototype.getLensFlareSystemById = function (id) {\n for (let index = 0; index < this.lensFlareSystems.length; index++) {\n if (this.lensFlareSystems[index].id === id) {\n return this.lensFlareSystems[index];\n }\n }\n return null;\n};\nAbstractScene.prototype.getLensFlareSystemByID = function (id) {\n return this.getLensFlareSystemById(id);\n};\nAbstractScene.prototype.removeLensFlareSystem = function (toRemove) {\n const index = this.lensFlareSystems.indexOf(toRemove);\n if (index !== -1) {\n this.lensFlareSystems.splice(index, 1);\n }\n return index;\n};\nAbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {\n this.lensFlareSystems.push(newLensFlareSystem);\n};\n/**\n * Defines the lens flare scene component responsible to manage any lens flares\n * in a given scene.\n */\nexport class LensFlareSystemSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpful to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_LENSFLARESYSTEM;\n this.scene = scene;\n scene.lensFlareSystems = new Array();\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n for (let index = 0; index < this.scene.lensFlareSystems.length; index++) {\n this.scene.lensFlareSystems[index].rebuild();\n }\n }\n /**\n * Adds all the elements from the container to the scene\n * @param container the container holding the elements\n */\n addFromContainer(container) {\n if (!container.lensFlareSystems) {\n return;\n }\n container.lensFlareSystems.forEach((o) => {\n this.scene.addLensFlareSystem(o);\n });\n }\n /**\n * Removes all the elements in the container from the scene\n * @param container contains the elements to remove\n * @param dispose if the removed element should be disposed (default: false)\n */\n removeFromContainer(container, dispose) {\n if (!container.lensFlareSystems) {\n return;\n }\n container.lensFlareSystems.forEach((o) => {\n this.scene.removeLensFlareSystem(o);\n if (dispose) {\n o.dispose();\n }\n });\n }\n /**\n * Serializes the component data to the specified json object\n * @param serializationObject The object to serialize to\n */\n serialize(serializationObject) {\n // Lens flares\n serializationObject.lensFlareSystems = [];\n const lensFlareSystems = this.scene.lensFlareSystems;\n for (const lensFlareSystem of lensFlareSystems) {\n serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());\n }\n }\n /**\n * Disposes the component and the associated resources.\n */\n dispose() {\n const lensFlareSystems = this.scene.lensFlareSystems;\n while (lensFlareSystems.length) {\n lensFlareSystems[0].dispose();\n }\n }\n _draw(camera) {\n // Lens flares\n if (this.scene.lensFlaresEnabled) {\n const lensFlareSystems = this.scene.lensFlareSystems;\n Tools.StartPerformanceCounter(\"Lens flares\", lensFlareSystems.length > 0);\n for (const lensFlareSystem of lensFlareSystems) {\n if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {\n lensFlareSystem.render();\n }\n }\n Tools.EndPerformanceCounter(\"Lens flares\", lensFlareSystems.length > 0);\n }\n }\n}\nLensFlareSystem._SceneComponentInitialization = (scene) => {\n let component = scene._getComponent(SceneComponentConstants.NAME_LENSFLARESYSTEM);\n if (!component) {\n component = new LensFlareSystemSceneComponent(scene);\n scene._addComponent(component);\n }\n};\n//# sourceMappingURL=lensFlareSystemSceneComponent.js.map","export * from \"./lensFlare.js\";\nexport * from \"./lensFlareSystem.js\";\nexport * from \"./lensFlareSystemSceneComponent.js\";\n//# sourceMappingURL=index.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"bayerDitherFunctions\";\nconst shader = `float bayerDither2(vec2 _P) {\rreturn mod(2.0*_P.y+_P.x+1.0,4.0);\r}\rfloat bayerDither4(vec2 _P) {\rvec2 P1=mod(_P,2.0); \rvec2 P2=floor(0.5*mod(_P,4.0)); \rreturn 4.0*bayerDither2(P1)+bayerDither2(P2);\r}\rfloat bayerDither8(vec2 _P) {\rvec2 P1=mod(_P,2.0); \rvec2 P2=floor(0.5 *mod(_P,4.0)); \rvec2 P4=floor(0.25*mod(_P,8.0)); \rreturn 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);\r}\r`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const bayerDitherFunctions = { name, shader };\n//# sourceMappingURL=bayerDitherFunctions.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nimport \"./packingFunctions.js\";\nimport \"./bayerDitherFunctions.js\";\nconst name = \"shadowMapFragmentExtraDeclaration\";\nconst shader = `#if SM_FLOAT==0\n#include\n#endif\n#if SM_SOFTTRANSPARENTSHADOW==1\n#include\nuniform float softTransparentShadowSM;\r#endif\nvarying float vDepthMetricSM;\r#if SM_USEDISTANCE==1\nuniform vec3 lightDataSM;\rvarying vec3 vPositionWSM;\r#endif\nuniform vec3 biasAndScaleSM;\runiform vec2 depthValuesSM;\r#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const shadowMapFragmentExtraDeclaration = { name, shader };\n//# sourceMappingURL=shadowMapFragmentExtraDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"shadowMapVertexNormalBias\";\nconst shader = `#if SM_NORMALBIAS==1\n#if SM_DIRECTIONINLIGHTDATA==1\nvec3 worldLightDirSM=normalize(-lightDataSM.xyz);\r#else\nvec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;\rvec3 worldLightDirSM=normalize(directionToLightSM);\r#endif\nfloat ndlSM=dot(vNormalW,worldLightDirSM);\rfloat sinNLSM=sqrt(1.0-ndlSM*ndlSM);\rfloat normalBiasSM=biasAndScaleSM.y*sinNLSM;\rworldPos.xyz-=vNormalW*normalBiasSM;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const shadowMapVertexNormalBias = { name, shader };\n//# sourceMappingURL=shadowMapVertexNormalBias.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"shadowMapVertexMetric\";\nconst shader = `#if SM_USEDISTANCE==1\nvPositionWSM=worldPos.xyz;\r#endif\n#if SM_DEPTHTEXTURE==1\n#ifdef IS_NDC_HALF_ZRANGE\n#define BIASFACTOR 0.5\n#else\n#define BIASFACTOR 1.0\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\r#else\ngl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR;\r#endif\n#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nzSM=gl_Position.z;\rgl_Position.z=0.0;\r#elif SM_USEDISTANCE==0\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\r#else\nvDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\r#endif\n#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const shadowMapVertexMetric = { name, shader };\n//# sourceMappingURL=shadowMapVertexMetric.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"shadowMapFragment\";\nconst shader = `float depthSM=vDepthMetricSM;\r#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\n#if SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\r#else\n#ifdef USE_REVERSE_DEPTHBUFFER\ndepthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\r#else\ndepthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\r#endif\n#endif\n#ifdef USE_REVERSE_DEPTHBUFFER\ngl_FragDepth=clamp(1.0-depthSM,0.0,1.0);\r#else\ngl_FragDepth=clamp(depthSM,0.0,1.0); \r#endif\n#elif SM_USEDISTANCE==1\ndepthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x;\r#endif\n#if SM_ESM==1\ndepthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.);\r#endif\n#if SM_FLOAT==1\ngl_FragColor=vec4(depthSM,1.0,1.0,1.0);\r#else\ngl_FragColor=pack(depthSM);\r#endif\nreturn;`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const shadowMapFragment = { name, shader };\n//# sourceMappingURL=shadowMapFragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/shadowMapFragmentExtraDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneFragmentDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneFragment.js\";\nimport \"./ShadersInclude/shadowMapFragment.js\";\nconst name = \"shadowMapPixelShader\";\nconst shader = `#include\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;\runiform sampler2D diffuseSampler;\r#endif\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\r{\r#include\n#ifdef ALPHATEXTURE\nfloat alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a;\r#ifdef ALPHATESTVALUE\nif (alphaFromAlphaTexture=softTransparentShadowSM*alphaFromAlphaTexture) discard;\r#else\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM) discard;\r#endif\n#endif\n#include\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const shadowMapPixelShader = { name, shader };\n//# sourceMappingURL=shadowMap.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"sceneVertexDeclaration\";\nconst shader = `uniform mat4 viewProjection;\r#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\r#endif\nuniform mat4 view;\runiform mat4 projection;\runiform vec4 vEyePosition;\r`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const sceneVertexDeclaration = { name, shader };\n//# sourceMappingURL=sceneVertexDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"meshVertexDeclaration\";\nconst shader = `uniform mat4 world;\runiform float visibility;\r`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const meshVertexDeclaration = { name, shader };\n//# sourceMappingURL=meshVertexDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nimport \"./sceneVertexDeclaration.js\";\nimport \"./meshVertexDeclaration.js\";\nconst name = \"shadowMapVertexDeclaration\";\nconst shader = `#include\n#include\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const shadowMapVertexDeclaration = { name, shader };\n//# sourceMappingURL=shadowMapVertexDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nimport \"./sceneUboDeclaration.js\";\nimport \"./meshUboDeclaration.js\";\nconst name = \"shadowMapUboDeclaration\";\nconst shader = `layout(std140,column_major) uniform;\r#include\n#include\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const shadowMapUboDeclaration = { name, shader };\n//# sourceMappingURL=shadowMapUboDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"shadowMapVertexExtraDeclaration\";\nconst shader = `#if SM_NORMALBIAS==1\nuniform vec3 lightDataSM;\r#endif\nuniform vec3 biasAndScaleSM;\runiform vec2 depthValuesSM;\rvarying float vDepthMetricSM;\r#if SM_USEDISTANCE==1\nvarying vec3 vPositionWSM;\r#endif\n#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1\nvarying float zSM;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const shadowMapVertexExtraDeclaration = { name, shader };\n//# sourceMappingURL=shadowMapVertexExtraDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/bonesDeclaration.js\";\nimport \"./ShadersInclude/bakedVertexAnimationDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexGlobalDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexDeclaration.js\";\nimport \"./ShadersInclude/helperFunctions.js\";\nimport \"./ShadersInclude/shadowMapVertexDeclaration.js\";\nimport \"./ShadersInclude/shadowMapUboDeclaration.js\";\nimport \"./ShadersInclude/shadowMapVertexExtraDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneVertexDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexGlobal.js\";\nimport \"./ShadersInclude/morphTargetsVertex.js\";\nimport \"./ShadersInclude/instancesVertex.js\";\nimport \"./ShadersInclude/bonesVertex.js\";\nimport \"./ShadersInclude/bakedVertexAnimation.js\";\nimport \"./ShadersInclude/shadowMapVertexNormalBias.js\";\nimport \"./ShadersInclude/shadowMapVertexMetric.js\";\nimport \"./ShadersInclude/clipPlaneVertex.js\";\nconst name = \"shadowMapVertexShader\";\nconst shader = `attribute vec3 position;\r#ifdef NORMAL\nattribute vec3 normal;\r#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef INSTANCES\nattribute vec4 world0;\rattribute vec4 world1;\rattribute vec4 world2;\rattribute vec4 world3;\r#endif\n#include\n#include<__decl__shadowMapVertex>\n#ifdef ALPHATEXTURE\nvarying vec2 vUV;\runiform mat4 diffuseMatrix;\r#ifdef UV1\nattribute vec2 uv;\r#endif\n#ifdef UV2\nattribute vec2 uv2;\r#endif\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\r{\rvec3 positionUpdated=position;\r#ifdef UV1\nvec2 uvUpdated=uv;\r#endif\n#ifdef NORMAL\nvec3 normalUpdated=normal;\r#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\r#ifdef NORMAL\nmat3 normWorldSM=mat3(finalWorld);\r#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));\rvNormalW=normalize(normWorldSM*vNormalW);\r#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\r#endif\nvec3 vNormalW=normalize(normWorldSM*normalUpdated);\r#endif\n#endif\n#include\ngl_Position=viewProjection*worldPos;\r#include\n#ifdef ALPHATEXTURE\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\r#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\r#endif\n#endif\n#include\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const shadowMapVertexShader = { name, shader };\n//# sourceMappingURL=shadowMap.vertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"depthBoxBlurPixelShader\";\nconst shader = `varying vec2 vUV;\runiform sampler2D textureSampler;\runiform vec2 screenSize;\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\r{\rvec4 colorDepth=vec4(0.0);\rfor (int x=-OFFSET; x<=OFFSET; x++)\rfor (int y=-OFFSET; y<=OFFSET; y++)\rcolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\rgl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const depthBoxBlurPixelShader = { name, shader };\n//# sourceMappingURL=depthBoxBlur.fragment.js.map","import { Matrix, Vector3, Vector2 } from \"../../Maths/math.vector.js\";\nimport { Color4 } from \"../../Maths/math.color.js\";\nimport { VertexBuffer } from \"../../Buffers/buffer.js\";\nimport { Light } from \"../../Lights/light.js\";\nimport { MaterialHelper } from \"../../Materials/materialHelper.js\";\nimport { Texture } from \"../../Materials/Textures/texture.js\";\nimport { RenderTargetTexture } from \"../../Materials/Textures/renderTargetTexture.js\";\nimport { PostProcess } from \"../../PostProcesses/postProcess.js\";\nimport { BlurPostProcess } from \"../../PostProcesses/blurPostProcess.js\";\n\nimport { Observable } from \"../../Misc/observable.js\";\nimport { _WarnImport } from \"../../Misc/devTools.js\";\nimport { EffectFallbacks } from \"../../Materials/effectFallbacks.js\";\nimport { RenderingManager } from \"../../Rendering/renderingManager.js\";\nimport { DrawWrapper } from \"../../Materials/drawWrapper.js\";\nimport \"../../Shaders/shadowMap.fragment.js\";\nimport \"../../Shaders/shadowMap.vertex.js\";\nimport \"../../Shaders/depthBoxBlur.fragment.js\";\nimport \"../../Shaders/ShadersInclude/shadowMapFragmentSoftTransparentShadow.js\";\nimport { addClipPlaneUniforms, bindClipPlane, prepareStringDefinesForClipPlanes } from \"../../Materials/clipPlaneMaterialHelper.js\";\n/**\n * Default implementation IShadowGenerator.\n * This is the main object responsible of generating shadows in the framework.\n * Documentation: https://doc.babylonjs.com/features/featuresDeepDive/lights/shadows\n */\nexport class ShadowGenerator {\n /**\n * Gets the bias: offset applied on the depth preventing acnea (in light direction).\n */\n get bias() {\n return this._bias;\n }\n /**\n * Sets the bias: offset applied on the depth preventing acnea (in light direction).\n */\n set bias(bias) {\n this._bias = bias;\n }\n /**\n * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportional to the light/normal angle).\n */\n get normalBias() {\n return this._normalBias;\n }\n /**\n * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportional to the light/normal angle).\n */\n set normalBias(normalBias) {\n this._normalBias = normalBias;\n }\n /**\n * Gets the blur box offset: offset applied during the blur pass.\n * Only useful if useKernelBlur = false\n */\n get blurBoxOffset() {\n return this._blurBoxOffset;\n }\n /**\n * Sets the blur box offset: offset applied during the blur pass.\n * Only useful if useKernelBlur = false\n */\n set blurBoxOffset(value) {\n if (this._blurBoxOffset === value) {\n return;\n }\n this._blurBoxOffset = value;\n this._disposeBlurPostProcesses();\n }\n /**\n * Gets the blur scale: scale of the blurred texture compared to the main shadow map.\n * 2 means half of the size.\n */\n get blurScale() {\n return this._blurScale;\n }\n /**\n * Sets the blur scale: scale of the blurred texture compared to the main shadow map.\n * 2 means half of the size.\n */\n set blurScale(value) {\n if (this._blurScale === value) {\n return;\n }\n this._blurScale = value;\n this._disposeBlurPostProcesses();\n }\n /**\n * Gets the blur kernel: kernel size of the blur pass.\n * Only useful if useKernelBlur = true\n */\n get blurKernel() {\n return this._blurKernel;\n }\n /**\n * Sets the blur kernel: kernel size of the blur pass.\n * Only useful if useKernelBlur = true\n */\n set blurKernel(value) {\n if (this._blurKernel === value) {\n return;\n }\n this._blurKernel = value;\n this._disposeBlurPostProcesses();\n }\n /**\n * Gets whether the blur pass is a kernel blur (if true) or box blur.\n * Only useful in filtered mode (useBlurExponentialShadowMap...)\n */\n get useKernelBlur() {\n return this._useKernelBlur;\n }\n /**\n * Sets whether the blur pass is a kernel blur (if true) or box blur.\n * Only useful in filtered mode (useBlurExponentialShadowMap...)\n */\n set useKernelBlur(value) {\n if (this._useKernelBlur === value) {\n return;\n }\n this._useKernelBlur = value;\n this._disposeBlurPostProcesses();\n }\n /**\n * Gets the depth scale used in ESM mode.\n */\n get depthScale() {\n return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();\n }\n /**\n * Sets the depth scale used in ESM mode.\n * This can override the scale stored on the light.\n */\n set depthScale(value) {\n this._depthScale = value;\n }\n _validateFilter(filter) {\n return filter;\n }\n /**\n * Gets the current mode of the shadow generator (normal, PCF, ESM...).\n * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE\n */\n get filter() {\n return this._filter;\n }\n /**\n * Sets the current mode of the shadow generator (normal, PCF, ESM...).\n * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE\n */\n set filter(value) {\n value = this._validateFilter(value);\n // Blurring the cubemap is going to be too expensive. Reverting to unblurred version\n if (this._light.needCube()) {\n if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {\n this.useExponentialShadowMap = true;\n return;\n }\n else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {\n this.useCloseExponentialShadowMap = true;\n return;\n }\n // PCF on cubemap would also be expensive\n else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {\n this.usePoissonSampling = true;\n return;\n }\n }\n // Weblg1 fallback for PCF.\n if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {\n if (!this._scene.getEngine()._features.supportShadowSamplers) {\n this.usePoissonSampling = true;\n return;\n }\n }\n if (this._filter === value) {\n return;\n }\n this._filter = value;\n this._disposeBlurPostProcesses();\n this._applyFilterValues();\n this._light._markMeshesAsLightDirty();\n }\n /**\n * Gets if the current filter is set to Poisson Sampling.\n */\n get usePoissonSampling() {\n return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;\n }\n /**\n * Sets the current filter to Poisson Sampling.\n */\n set usePoissonSampling(value) {\n const filter = this._validateFilter(ShadowGenerator.FILTER_POISSONSAMPLING);\n if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {\n return;\n }\n this.filter = value ? filter : ShadowGenerator.FILTER_NONE;\n }\n /**\n * Gets if the current filter is set to ESM.\n */\n get useExponentialShadowMap() {\n return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;\n }\n /**\n * Sets the current filter is to ESM.\n */\n set useExponentialShadowMap(value) {\n const filter = this._validateFilter(ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP);\n if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {\n return;\n }\n this.filter = value ? filter : ShadowGenerator.FILTER_NONE;\n }\n /**\n * Gets if the current filter is set to filtered ESM.\n */\n get useBlurExponentialShadowMap() {\n return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;\n }\n /**\n * Gets if the current filter is set to filtered ESM.\n */\n set useBlurExponentialShadowMap(value) {\n const filter = this._validateFilter(ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP);\n if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {\n return;\n }\n this.filter = value ? filter : ShadowGenerator.FILTER_NONE;\n }\n /**\n * Gets if the current filter is set to \"close ESM\" (using the inverse of the\n * exponential to prevent steep falloff artifacts).\n */\n get useCloseExponentialShadowMap() {\n return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;\n }\n /**\n * Sets the current filter to \"close ESM\" (using the inverse of the\n * exponential to prevent steep falloff artifacts).\n */\n set useCloseExponentialShadowMap(value) {\n const filter = this._validateFilter(ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP);\n if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {\n return;\n }\n this.filter = value ? filter : ShadowGenerator.FILTER_NONE;\n }\n /**\n * Gets if the current filter is set to filtered \"close ESM\" (using the inverse of the\n * exponential to prevent steep falloff artifacts).\n */\n get useBlurCloseExponentialShadowMap() {\n return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;\n }\n /**\n * Sets the current filter to filtered \"close ESM\" (using the inverse of the\n * exponential to prevent steep falloff artifacts).\n */\n set useBlurCloseExponentialShadowMap(value) {\n const filter = this._validateFilter(ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);\n if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {\n return;\n }\n this.filter = value ? filter : ShadowGenerator.FILTER_NONE;\n }\n /**\n * Gets if the current filter is set to \"PCF\" (percentage closer filtering).\n */\n get usePercentageCloserFiltering() {\n return this.filter === ShadowGenerator.FILTER_PCF;\n }\n /**\n * Sets the current filter to \"PCF\" (percentage closer filtering).\n */\n set usePercentageCloserFiltering(value) {\n const filter = this._validateFilter(ShadowGenerator.FILTER_PCF);\n if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {\n return;\n }\n this.filter = value ? filter : ShadowGenerator.FILTER_NONE;\n }\n /**\n * Gets the PCF or PCSS Quality.\n * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.\n */\n get filteringQuality() {\n return this._filteringQuality;\n }\n /**\n * Sets the PCF or PCSS Quality.\n * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.\n */\n set filteringQuality(filteringQuality) {\n if (this._filteringQuality === filteringQuality) {\n return;\n }\n this._filteringQuality = filteringQuality;\n this._disposeBlurPostProcesses();\n this._applyFilterValues();\n this._light._markMeshesAsLightDirty();\n }\n /**\n * Gets if the current filter is set to \"PCSS\" (contact hardening).\n */\n get useContactHardeningShadow() {\n return this.filter === ShadowGenerator.FILTER_PCSS;\n }\n /**\n * Sets the current filter to \"PCSS\" (contact hardening).\n */\n set useContactHardeningShadow(value) {\n const filter = this._validateFilter(ShadowGenerator.FILTER_PCSS);\n if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {\n return;\n }\n this.filter = value ? filter : ShadowGenerator.FILTER_NONE;\n }\n /**\n * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.\n * Using a ratio helps keeping shape stability independently of the map size.\n *\n * It does not account for the light projection as it was having too much\n * instability during the light setup or during light position changes.\n *\n * Only valid if useContactHardeningShadow is true.\n */\n get contactHardeningLightSizeUVRatio() {\n return this._contactHardeningLightSizeUVRatio;\n }\n /**\n * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.\n * Using a ratio helps keeping shape stability independently of the map size.\n *\n * It does not account for the light projection as it was having too much\n * instability during the light setup or during light position changes.\n *\n * Only valid if useContactHardeningShadow is true.\n */\n set contactHardeningLightSizeUVRatio(contactHardeningLightSizeUVRatio) {\n this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;\n }\n /** Gets or sets the actual darkness of a shadow */\n get darkness() {\n return this._darkness;\n }\n set darkness(value) {\n this.setDarkness(value);\n }\n /**\n * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.\n * 0 means strongest and 1 would means no shadow.\n * @returns the darkness.\n */\n getDarkness() {\n return this._darkness;\n }\n /**\n * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.\n * @param darkness The darkness value 0 means strongest and 1 would means no shadow.\n * @returns the shadow generator allowing fluent coding.\n */\n setDarkness(darkness) {\n if (darkness >= 1.0) {\n this._darkness = 1.0;\n }\n else if (darkness <= 0.0) {\n this._darkness = 0.0;\n }\n else {\n this._darkness = darkness;\n }\n return this;\n }\n /** Gets or sets the ability to have transparent shadow */\n get transparencyShadow() {\n return this._transparencyShadow;\n }\n set transparencyShadow(value) {\n this.setTransparencyShadow(value);\n }\n /**\n * Sets the ability to have transparent shadow (boolean).\n * @param transparent True if transparent else False\n * @returns the shadow generator allowing fluent coding\n */\n setTransparencyShadow(transparent) {\n this._transparencyShadow = transparent;\n return this;\n }\n /**\n * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).\n * @returns The render target texture if present otherwise, null\n */\n getShadowMap() {\n return this._shadowMap;\n }\n /**\n * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).\n * @returns The render target texture if the shadow map is present otherwise, null\n */\n getShadowMapForRendering() {\n if (this._shadowMap2) {\n return this._shadowMap2;\n }\n return this._shadowMap;\n }\n /**\n * Gets the class name of that object\n * @returns \"ShadowGenerator\"\n */\n getClassName() {\n return ShadowGenerator.CLASSNAME;\n }\n /**\n * Helper function to add a mesh and its descendants to the list of shadow casters.\n * @param mesh Mesh to add\n * @param includeDescendants boolean indicating if the descendants should be added. Default to true\n * @returns the Shadow Generator itself\n */\n addShadowCaster(mesh, includeDescendants = true) {\n if (!this._shadowMap) {\n return this;\n }\n if (!this._shadowMap.renderList) {\n this._shadowMap.renderList = [];\n }\n if (this._shadowMap.renderList.indexOf(mesh) === -1) {\n this._shadowMap.renderList.push(mesh);\n }\n if (includeDescendants) {\n for (const childMesh of mesh.getChildMeshes()) {\n if (this._shadowMap.renderList.indexOf(childMesh) === -1) {\n this._shadowMap.renderList.push(childMesh);\n }\n }\n }\n return this;\n }\n /**\n * Helper function to remove a mesh and its descendants from the list of shadow casters\n * @param mesh Mesh to remove\n * @param includeDescendants boolean indicating if the descendants should be removed. Default to true\n * @returns the Shadow Generator itself\n */\n removeShadowCaster(mesh, includeDescendants = true) {\n if (!this._shadowMap || !this._shadowMap.renderList) {\n return this;\n }\n const index = this._shadowMap.renderList.indexOf(mesh);\n if (index !== -1) {\n this._shadowMap.renderList.splice(index, 1);\n }\n if (includeDescendants) {\n for (const child of mesh.getChildren()) {\n this.removeShadowCaster(child);\n }\n }\n return this;\n }\n /**\n * Returns the associated light object.\n * @returns the light generating the shadow\n */\n getLight() {\n return this._light;\n }\n _getCamera() {\n var _a;\n return (_a = this._camera) !== null && _a !== void 0 ? _a : this._scene.activeCamera;\n }\n /**\n * Gets or sets the size of the texture what stores the shadows\n */\n get mapSize() {\n return this._mapSize;\n }\n set mapSize(size) {\n this._mapSize = size;\n this._light._markMeshesAsLightDirty();\n this.recreateShadowMap();\n }\n /**\n * Creates a ShadowGenerator object.\n * A ShadowGenerator is the required tool to use the shadows.\n * Each light casting shadows needs to use its own ShadowGenerator.\n * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/shadows\n * @param mapSize The size of the texture what stores the shadows. Example : 1024.\n * @param light The light object generating the shadows.\n * @param usefullFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.\n * @param camera Camera associated with this shadow generator (default: null). If null, takes the scene active camera at the time we need to access it\n */\n constructor(mapSize, light, usefullFloatFirst, camera) {\n /**\n * Observable triggered before the shadow is rendered. Can be used to update internal effect state\n */\n this.onBeforeShadowMapRenderObservable = new Observable();\n /**\n * Observable triggered after the shadow is rendered. Can be used to restore internal effect state\n */\n this.onAfterShadowMapRenderObservable = new Observable();\n /**\n * Observable triggered before a mesh is rendered in the shadow map.\n * Can be used to update internal effect state (that you can get from the onBeforeShadowMapRenderObservable)\n */\n this.onBeforeShadowMapRenderMeshObservable = new Observable();\n /**\n * Observable triggered after a mesh is rendered in the shadow map.\n * Can be used to update internal effect state (that you can get from the onAfterShadowMapRenderObservable)\n */\n this.onAfterShadowMapRenderMeshObservable = new Observable();\n this._bias = 0.00005;\n this._normalBias = 0;\n this._blurBoxOffset = 1;\n this._blurScale = 2;\n this._blurKernel = 1;\n this._useKernelBlur = false;\n this._filter = ShadowGenerator.FILTER_NONE;\n this._filteringQuality = ShadowGenerator.QUALITY_HIGH;\n this._contactHardeningLightSizeUVRatio = 0.1;\n this._darkness = 0;\n this._transparencyShadow = false;\n /**\n * Enables or disables shadows with varying strength based on the transparency\n * When it is enabled, the strength of the shadow is taken equal to mesh.visibility\n * If you enabled an alpha texture on your material, the alpha value red from the texture is also combined to compute the strength:\n * mesh.visibility * alphaTexture.a\n * The texture used is the diffuse by default, but it can be set to the opacity by setting useOpacityTextureForTransparentShadow\n * Note that by definition transparencyShadow must be set to true for enableSoftTransparentShadow to work!\n */\n this.enableSoftTransparentShadow = false;\n /**\n * If this is true, use the opacity texture's alpha channel for transparent shadows instead of the diffuse one\n */\n this.useOpacityTextureForTransparentShadow = false;\n /**\n * Controls the extent to which the shadows fade out at the edge of the frustum\n */\n this.frustumEdgeFalloff = 0;\n /**\n * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.\n * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.\n * It might on the other hand introduce peter panning.\n */\n this.forceBackFacesOnly = false;\n this._lightDirection = Vector3.Zero();\n this._viewMatrix = Matrix.Zero();\n this._projectionMatrix = Matrix.Zero();\n this._transformMatrix = Matrix.Zero();\n this._cachedPosition = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._cachedDirection = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._currentFaceIndex = 0;\n this._currentFaceIndexCache = 0;\n this._defaultTextureMatrix = Matrix.Identity();\n this._mapSize = mapSize;\n this._light = light;\n this._scene = light.getScene();\n this._camera = camera !== null && camera !== void 0 ? camera : null;\n let shadowGenerators = light._shadowGenerators;\n if (!shadowGenerators) {\n shadowGenerators = light._shadowGenerators = new Map();\n }\n shadowGenerators.set(this._camera, this);\n this.id = light.id;\n this._useUBO = this._scene.getEngine().supportsUniformBuffers;\n if (this._useUBO) {\n this._sceneUBOs = [];\n this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light \"${this._light.name}\")`));\n }\n ShadowGenerator._SceneComponentInitialization(this._scene);\n // Texture type fallback from float to int if not supported.\n const caps = this._scene.getEngine().getCaps();\n if (!usefullFloatFirst) {\n if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {\n this._textureType = 2;\n }\n else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {\n this._textureType = 1;\n }\n else {\n this._textureType = 0;\n }\n }\n else {\n if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {\n this._textureType = 1;\n }\n else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {\n this._textureType = 2;\n }\n else {\n this._textureType = 0;\n }\n }\n this._initializeGenerator();\n this._applyFilterValues();\n }\n _initializeGenerator() {\n this._light._markMeshesAsLightDirty();\n this._initializeShadowMap();\n }\n _createTargetRenderTexture() {\n const engine = this._scene.getEngine();\n if (engine._features.supportDepthStencilTexture) {\n this._shadowMap = new RenderTargetTexture(this._light.name + \"_shadowMap\", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);\n this._shadowMap.createDepthStencilTexture(engine.useReverseDepthBuffer ? 516 : 513, true);\n }\n else {\n this._shadowMap = new RenderTargetTexture(this._light.name + \"_shadowMap\", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());\n }\n this._shadowMap.noPrePassRenderer = true;\n }\n _initializeShadowMap() {\n this._createTargetRenderTexture();\n if (this._shadowMap === null) {\n return;\n }\n this._shadowMap.wrapU = Texture.CLAMP_ADDRESSMODE;\n this._shadowMap.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._shadowMap.anisotropicFilteringLevel = 1;\n this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);\n this._shadowMap.renderParticles = false;\n this._shadowMap.ignoreCameraViewport = true;\n if (this._storedUniqueId) {\n this._shadowMap.uniqueId = this._storedUniqueId;\n }\n // Custom render function.\n this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);\n // Force the mesh is ready function to true as we are double checking it\n // in the custom render function. Also it prevents side effects and useless\n // shader variations in DEPTHPREPASS mode.\n this._shadowMap.customIsReadyFunction = () => {\n return true;\n };\n const engine = this._scene.getEngine();\n this._shadowMap.onBeforeBindObservable.add(() => {\n var _a;\n this._currentSceneUBO = this._scene.getSceneUniformBuffer();\n (_a = engine._debugPushGroup) === null || _a === void 0 ? void 0 : _a.call(engine, `shadow map generation for pass id ${engine.currentRenderPassId}`, 1);\n });\n // Record Face Index before render.\n this._shadowMap.onBeforeRenderObservable.add((faceIndex) => {\n if (this._sceneUBOs) {\n this._scene.setSceneUniformBuffer(this._sceneUBOs[0]);\n }\n this._currentFaceIndex = faceIndex;\n if (this._filter === ShadowGenerator.FILTER_PCF) {\n engine.setColorWrite(false);\n }\n this.getTransformMatrix(); // generate the view/projection matrix\n this._scene.setTransformMatrix(this._viewMatrix, this._projectionMatrix);\n if (this._useUBO) {\n this._scene.getSceneUniformBuffer().unbindEffect();\n this._scene.finalizeSceneUbo();\n }\n });\n // Blur if required after render.\n this._shadowMap.onAfterUnbindObservable.add(() => {\n var _a, _b;\n if (this._sceneUBOs) {\n this._scene.setSceneUniformBuffer(this._currentSceneUBO);\n }\n this._scene.updateTransformMatrix(); // restore the view/projection matrices of the active camera\n if (this._filter === ShadowGenerator.FILTER_PCF) {\n engine.setColorWrite(true);\n }\n if (!this.useBlurExponentialShadowMap && !this.useBlurCloseExponentialShadowMap) {\n (_a = engine._debugPopGroup) === null || _a === void 0 ? void 0 : _a.call(engine, 1);\n return;\n }\n const shadowMap = this.getShadowMapForRendering();\n if (shadowMap) {\n this._scene.postProcessManager.directRender(this._blurPostProcesses, shadowMap.renderTarget, true);\n engine.unBindFramebuffer(shadowMap.renderTarget, true);\n (_b = engine._debugPopGroup) === null || _b === void 0 ? void 0 : _b.call(engine, 1);\n }\n });\n // Clear according to the chosen filter.\n const clearZero = new Color4(0, 0, 0, 0);\n const clearOne = new Color4(1.0, 1.0, 1.0, 1.0);\n this._shadowMap.onClearObservable.add((engine) => {\n if (this._filter === ShadowGenerator.FILTER_PCF) {\n engine.clear(clearOne, false, true, false);\n }\n else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {\n engine.clear(clearZero, true, true, false);\n }\n else {\n engine.clear(clearOne, true, true, false);\n }\n });\n // Recreate on resize.\n this._shadowMap.onResizeObservable.add((rtt) => {\n this._storedUniqueId = this._shadowMap.uniqueId;\n this._mapSize = rtt.getRenderSize();\n this._light._markMeshesAsLightDirty();\n this.recreateShadowMap();\n });\n // Ensures rendering groupids do not erase the depth buffer\n // or we would lose the shadows information.\n for (let i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {\n this._shadowMap.setRenderingAutoClearDepthStencil(i, false);\n }\n }\n _initializeBlurRTTAndPostProcesses() {\n const engine = this._scene.getEngine();\n const targetSize = this._mapSize / this.blurScale;\n if (!this.useKernelBlur || this.blurScale !== 1.0) {\n this._shadowMap2 = new RenderTargetTexture(this._light.name + \"_shadowMap2\", targetSize, this._scene, false, true, this._textureType, undefined, undefined, false);\n this._shadowMap2.wrapU = Texture.CLAMP_ADDRESSMODE;\n this._shadowMap2.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._shadowMap2.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);\n }\n if (this.useKernelBlur) {\n this._kernelBlurXPostprocess = new BlurPostProcess(this._light.name + \"KernelBlurX\", new Vector2(1, 0), this.blurKernel, 1.0, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);\n this._kernelBlurXPostprocess.width = targetSize;\n this._kernelBlurXPostprocess.height = targetSize;\n this._kernelBlurXPostprocess.externalTextureSamplerBinding = true;\n this._kernelBlurXPostprocess.onApplyObservable.add((effect) => {\n effect.setTexture(\"textureSampler\", this._shadowMap);\n });\n this._kernelBlurYPostprocess = new BlurPostProcess(this._light.name + \"KernelBlurY\", new Vector2(0, 1), this.blurKernel, 1.0, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);\n this._kernelBlurXPostprocess.autoClear = false;\n this._kernelBlurYPostprocess.autoClear = false;\n if (this._textureType === 0) {\n this._kernelBlurXPostprocess.packedFloat = true;\n this._kernelBlurYPostprocess.packedFloat = true;\n }\n this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];\n }\n else {\n this._boxBlurPostprocess = new PostProcess(this._light.name + \"DepthBoxBlur\", \"depthBoxBlur\", [\"screenSize\", \"boxOffset\"], [], 1.0, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, \"#define OFFSET \" + this._blurBoxOffset, this._textureType);\n this._boxBlurPostprocess.externalTextureSamplerBinding = true;\n this._boxBlurPostprocess.onApplyObservable.add((effect) => {\n effect.setFloat2(\"screenSize\", targetSize, targetSize);\n effect.setTexture(\"textureSampler\", this._shadowMap);\n });\n this._boxBlurPostprocess.autoClear = false;\n this._blurPostProcesses = [this._boxBlurPostprocess];\n }\n }\n _renderForShadowMap(opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {\n let index;\n if (depthOnlySubMeshes.length) {\n for (index = 0; index < depthOnlySubMeshes.length; index++) {\n this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);\n }\n }\n for (index = 0; index < opaqueSubMeshes.length; index++) {\n this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);\n }\n for (index = 0; index < alphaTestSubMeshes.length; index++) {\n this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);\n }\n if (this._transparencyShadow) {\n for (index = 0; index < transparentSubMeshes.length; index++) {\n this._renderSubMeshForShadowMap(transparentSubMeshes.data[index], true);\n }\n }\n else {\n for (index = 0; index < transparentSubMeshes.length; index++) {\n transparentSubMeshes.data[index].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate = false;\n }\n }\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _bindCustomEffectForRenderSubMeshForShadowMap(subMesh, effect, mesh) {\n effect.setMatrix(\"viewProjection\", this.getTransformMatrix());\n }\n _renderSubMeshForShadowMap(subMesh, isTransparent = false) {\n var _a, _b;\n const renderingMesh = subMesh.getRenderingMesh();\n const effectiveMesh = subMesh.getEffectiveMesh();\n const scene = this._scene;\n const engine = scene.getEngine();\n const material = subMesh.getMaterial();\n effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;\n if (!material || subMesh.verticesCount === 0 || subMesh._renderId === scene.getRenderId()) {\n return;\n }\n // Culling\n const detNeg = effectiveMesh._getWorldMatrixDeterminant() < 0;\n let sideOrientation = (_a = renderingMesh.overrideMaterialSideOrientation) !== null && _a !== void 0 ? _a : material.sideOrientation;\n if (detNeg) {\n sideOrientation =\n sideOrientation === 0 ? 1 : 0;\n }\n const reverseSideOrientation = sideOrientation === 0;\n engine.setState(material.backFaceCulling, undefined, undefined, reverseSideOrientation, material.cullBackFaces);\n // Managing instances\n const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());\n if (batch.mustReturn) {\n return;\n }\n const hardwareInstancedRendering = engine.getCaps().instancedArrays &&\n ((batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined) || renderingMesh.hasThinInstances);\n if (this.customAllowRendering && !this.customAllowRendering(subMesh)) {\n return;\n }\n if (this.isReady(subMesh, hardwareInstancedRendering, isTransparent)) {\n subMesh._renderId = scene.getRenderId();\n const shadowDepthWrapper = material.shadowDepthWrapper;\n const drawWrapper = (_b = shadowDepthWrapper === null || shadowDepthWrapper === void 0 ? void 0 : shadowDepthWrapper.getEffect(subMesh, this, engine.currentRenderPassId)) !== null && _b !== void 0 ? _b : subMesh._getDrawWrapper();\n const effect = DrawWrapper.GetEffect(drawWrapper);\n engine.enableEffect(drawWrapper);\n if (!hardwareInstancedRendering) {\n renderingMesh._bind(subMesh, effect, material.fillMode);\n }\n this.getTransformMatrix(); // make sure _cachedDirection et _cachedPosition are up to date\n effect.setFloat3(\"biasAndScaleSM\", this.bias, this.normalBias, this.depthScale);\n if (this.getLight().getTypeID() === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {\n effect.setVector3(\"lightDataSM\", this._cachedDirection);\n }\n else {\n effect.setVector3(\"lightDataSM\", this._cachedPosition);\n }\n const camera = this._getCamera();\n if (camera) {\n effect.setFloat2(\"depthValuesSM\", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera));\n }\n if (isTransparent && this.enableSoftTransparentShadow) {\n effect.setFloat(\"softTransparentShadowSM\", effectiveMesh.visibility * material.alpha);\n }\n if (shadowDepthWrapper) {\n subMesh._setMainDrawWrapperOverride(drawWrapper);\n if (shadowDepthWrapper.standalone) {\n shadowDepthWrapper.baseMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), renderingMesh, subMesh);\n }\n else {\n material.bindForSubMesh(effectiveMesh.getWorldMatrix(), renderingMesh, subMesh);\n }\n subMesh._setMainDrawWrapperOverride(null);\n }\n else {\n // Alpha test\n if (this._opacityTexture) {\n effect.setTexture(\"diffuseSampler\", this._opacityTexture);\n effect.setMatrix(\"diffuseMatrix\", this._opacityTexture.getTextureMatrix() || this._defaultTextureMatrix);\n }\n // Bones\n if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) {\n const skeleton = renderingMesh.skeleton;\n if (skeleton.isUsingTextureForMatrices) {\n const boneTexture = skeleton.getTransformMatrixTexture(renderingMesh);\n if (!boneTexture) {\n return;\n }\n effect.setTexture(\"boneSampler\", boneTexture);\n effect.setFloat(\"boneTextureWidth\", 4.0 * (skeleton.bones.length + 1));\n }\n else {\n effect.setMatrices(\"mBones\", skeleton.getTransformMatrices(renderingMesh));\n }\n }\n // Morph targets\n MaterialHelper.BindMorphTargetParameters(renderingMesh, effect);\n if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) {\n renderingMesh.morphTargetManager._bind(effect);\n }\n // Clip planes\n bindClipPlane(effect, material, scene);\n }\n if (!this._useUBO && !shadowDepthWrapper) {\n this._bindCustomEffectForRenderSubMeshForShadowMap(subMesh, effect, effectiveMesh);\n }\n MaterialHelper.BindSceneUniformBuffer(effect, this._scene.getSceneUniformBuffer());\n this._scene.getSceneUniformBuffer().bindUniformBuffer();\n const world = effectiveMesh.getWorldMatrix();\n // In the non hardware instanced mode, the Mesh ubo update is done by the callback passed to renderingMesh._processRendering (see below)\n if (hardwareInstancedRendering) {\n effectiveMesh.getMeshUniformBuffer().bindToEffect(effect, \"Mesh\");\n effectiveMesh.transferToEffect(world);\n }\n if (this.forceBackFacesOnly) {\n engine.setState(true, 0, false, true, material.cullBackFaces);\n }\n // Observables\n this.onBeforeShadowMapRenderMeshObservable.notifyObservers(renderingMesh);\n this.onBeforeShadowMapRenderObservable.notifyObservers(effect);\n // Draw\n renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, worldOverride) => {\n if (effectiveMesh !== renderingMesh && !isInstance) {\n renderingMesh.getMeshUniformBuffer().bindToEffect(effect, \"Mesh\");\n renderingMesh.transferToEffect(worldOverride);\n }\n else {\n effectiveMesh.getMeshUniformBuffer().bindToEffect(effect, \"Mesh\");\n effectiveMesh.transferToEffect(isInstance ? worldOverride : world);\n }\n });\n if (this.forceBackFacesOnly) {\n engine.setState(true, 0, false, false, material.cullBackFaces);\n }\n // Observables\n this.onAfterShadowMapRenderObservable.notifyObservers(effect);\n this.onAfterShadowMapRenderMeshObservable.notifyObservers(renderingMesh);\n }\n else {\n // Need to reset refresh rate of the shadowMap\n if (this._shadowMap) {\n this._shadowMap.resetRefreshCounter();\n }\n }\n }\n _applyFilterValues() {\n if (!this._shadowMap) {\n return;\n }\n if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {\n this._shadowMap.updateSamplingMode(Texture.NEAREST_SAMPLINGMODE);\n }\n else {\n this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);\n }\n }\n /**\n * Forces all the attached effect to compile to enable rendering only once ready vs. lazily compiling effects.\n * @param onCompiled Callback triggered at the and of the effects compilation\n * @param options Sets of optional options forcing the compilation with different modes\n */\n forceCompilation(onCompiled, options) {\n const localOptions = Object.assign({ useInstances: false }, options);\n const shadowMap = this.getShadowMap();\n if (!shadowMap) {\n if (onCompiled) {\n onCompiled(this);\n }\n return;\n }\n const renderList = shadowMap.renderList;\n if (!renderList) {\n if (onCompiled) {\n onCompiled(this);\n }\n return;\n }\n const subMeshes = new Array();\n for (const mesh of renderList) {\n subMeshes.push(...mesh.subMeshes);\n }\n if (subMeshes.length === 0) {\n if (onCompiled) {\n onCompiled(this);\n }\n return;\n }\n let currentIndex = 0;\n const checkReady = () => {\n var _a, _b;\n if (!this._scene || !this._scene.getEngine()) {\n return;\n }\n while (this.isReady(subMeshes[currentIndex], localOptions.useInstances, (_b = (_a = subMeshes[currentIndex].getMaterial()) === null || _a === void 0 ? void 0 : _a.needAlphaBlendingForMesh(subMeshes[currentIndex].getMesh())) !== null && _b !== void 0 ? _b : false)) {\n currentIndex++;\n if (currentIndex >= subMeshes.length) {\n if (onCompiled) {\n onCompiled(this);\n }\n return;\n }\n }\n setTimeout(checkReady, 16);\n };\n checkReady();\n }\n /**\n * Forces all the attached effect to compile to enable rendering only once ready vs. lazily compiling effects.\n * @param options Sets of optional options forcing the compilation with different modes\n * @returns A promise that resolves when the compilation completes\n */\n forceCompilationAsync(options) {\n return new Promise((resolve) => {\n this.forceCompilation(() => {\n resolve();\n }, options);\n });\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _isReadyCustomDefines(defines, subMesh, useInstances) { }\n _prepareShadowDefines(subMesh, useInstances, defines, isTransparent) {\n defines.push(\"#define SM_LIGHTTYPE_\" + this._light.getClassName().toUpperCase());\n defines.push(\"#define SM_FLOAT \" + (this._textureType !== 0 ? \"1\" : \"0\"));\n defines.push(\"#define SM_ESM \" + (this.useExponentialShadowMap || this.useBlurExponentialShadowMap ? \"1\" : \"0\"));\n defines.push(\"#define SM_DEPTHTEXTURE \" + (this.usePercentageCloserFiltering || this.useContactHardeningShadow ? \"1\" : \"0\"));\n const mesh = subMesh.getMesh();\n // Normal bias.\n defines.push(\"#define SM_NORMALBIAS \" + (this.normalBias && mesh.isVerticesDataPresent(VertexBuffer.NormalKind) ? \"1\" : \"0\"));\n defines.push(\"#define SM_DIRECTIONINLIGHTDATA \" + (this.getLight().getTypeID() === Light.LIGHTTYPEID_DIRECTIONALLIGHT ? \"1\" : \"0\"));\n // Point light\n defines.push(\"#define SM_USEDISTANCE \" + (this._light.needCube() ? \"1\" : \"0\"));\n // Soft transparent shadows\n defines.push(\"#define SM_SOFTTRANSPARENTSHADOW \" + (this.enableSoftTransparentShadow && isTransparent ? \"1\" : \"0\"));\n this._isReadyCustomDefines(defines, subMesh, useInstances);\n return defines;\n }\n /**\n * Determine whether the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).\n * @param subMesh The submesh we want to render in the shadow map\n * @param useInstances Defines whether will draw in the map using instances\n * @param isTransparent Indicates that isReady is called for a transparent subMesh\n * @returns true if ready otherwise, false\n */\n isReady(subMesh, useInstances, isTransparent) {\n var _a;\n const material = subMesh.getMaterial(), shadowDepthWrapper = material === null || material === void 0 ? void 0 : material.shadowDepthWrapper;\n this._opacityTexture = null;\n if (!material) {\n return false;\n }\n const defines = [];\n this._prepareShadowDefines(subMesh, useInstances, defines, isTransparent);\n if (shadowDepthWrapper) {\n if (!shadowDepthWrapper.isReadyForSubMesh(subMesh, defines, this, useInstances, this._scene.getEngine().currentRenderPassId)) {\n return false;\n }\n }\n else {\n const subMeshEffect = subMesh._getDrawWrapper(undefined, true);\n let effect = subMeshEffect.effect;\n let cachedDefines = subMeshEffect.defines;\n const attribs = [VertexBuffer.PositionKind];\n const mesh = subMesh.getMesh();\n // Normal bias.\n if (this.normalBias && mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {\n attribs.push(VertexBuffer.NormalKind);\n defines.push(\"#define NORMAL\");\n if (mesh.nonUniformScaling) {\n defines.push(\"#define NONUNIFORMSCALING\");\n }\n }\n // Alpha test\n const needAlphaTesting = material.needAlphaTesting();\n if (needAlphaTesting || material.needAlphaBlending()) {\n if (this.useOpacityTextureForTransparentShadow) {\n this._opacityTexture = material.opacityTexture;\n }\n else {\n this._opacityTexture = material.getAlphaTestTexture();\n }\n if (this._opacityTexture) {\n if (!this._opacityTexture.isReady()) {\n return false;\n }\n const alphaCutOff = (_a = material.alphaCutOff) !== null && _a !== void 0 ? _a : ShadowGenerator.DEFAULT_ALPHA_CUTOFF;\n defines.push(\"#define ALPHATEXTURE\");\n if (needAlphaTesting) {\n defines.push(`#define ALPHATESTVALUE ${alphaCutOff}${alphaCutOff % 1 === 0 ? \".\" : \"\"}`);\n }\n if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {\n attribs.push(VertexBuffer.UVKind);\n defines.push(\"#define UV1\");\n }\n if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {\n if (this._opacityTexture.coordinatesIndex === 1) {\n attribs.push(VertexBuffer.UV2Kind);\n defines.push(\"#define UV2\");\n }\n }\n }\n }\n // Bones\n const fallbacks = new EffectFallbacks();\n if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {\n attribs.push(VertexBuffer.MatricesIndicesKind);\n attribs.push(VertexBuffer.MatricesWeightsKind);\n if (mesh.numBoneInfluencers > 4) {\n attribs.push(VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(VertexBuffer.MatricesWeightsExtraKind);\n }\n const skeleton = mesh.skeleton;\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n if (mesh.numBoneInfluencers > 0) {\n fallbacks.addCPUSkinningFallback(0, mesh);\n }\n if (skeleton.isUsingTextureForMatrices) {\n defines.push(\"#define BONETEXTURE\");\n }\n else {\n defines.push(\"#define BonesPerMesh \" + (skeleton.bones.length + 1));\n }\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Morph targets\n const manager = mesh.morphTargetManager;\n let morphInfluencers = 0;\n if (manager) {\n if (manager.numInfluencers > 0) {\n defines.push(\"#define MORPHTARGETS\");\n morphInfluencers = manager.numInfluencers;\n defines.push(\"#define NUM_MORPH_INFLUENCERS \" + morphInfluencers);\n if (manager.isUsingTextureForTargets) {\n defines.push(\"#define MORPHTARGETS_TEXTURE\");\n }\n MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, morphInfluencers);\n }\n }\n // ClipPlanes\n prepareStringDefinesForClipPlanes(material, this._scene, defines);\n // Instances\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n MaterialHelper.PushAttributesForInstances(attribs);\n if (subMesh.getRenderingMesh().hasThinInstances) {\n defines.push(\"#define THIN_INSTANCES\");\n }\n }\n if (this.customShaderOptions) {\n if (this.customShaderOptions.defines) {\n for (const define of this.customShaderOptions.defines) {\n if (defines.indexOf(define) === -1) {\n defines.push(define);\n }\n }\n }\n }\n // Get correct effect\n const join = defines.join(\"\\n\");\n if (cachedDefines !== join) {\n cachedDefines = join;\n let shaderName = \"shadowMap\";\n const uniforms = [\n \"world\",\n \"mBones\",\n \"viewProjection\",\n \"diffuseMatrix\",\n \"lightDataSM\",\n \"depthValuesSM\",\n \"biasAndScaleSM\",\n \"morphTargetInfluences\",\n \"boneTextureWidth\",\n \"softTransparentShadowSM\",\n \"morphTargetTextureInfo\",\n \"morphTargetTextureIndices\",\n ];\n const samplers = [\"diffuseSampler\", \"boneSampler\", \"morphTargets\"];\n const uniformBuffers = [\"Scene\", \"Mesh\"];\n addClipPlaneUniforms(uniforms);\n // Custom shader?\n if (this.customShaderOptions) {\n shaderName = this.customShaderOptions.shaderName;\n if (this.customShaderOptions.attributes) {\n for (const attrib of this.customShaderOptions.attributes) {\n if (attribs.indexOf(attrib) === -1) {\n attribs.push(attrib);\n }\n }\n }\n if (this.customShaderOptions.uniforms) {\n for (const uniform of this.customShaderOptions.uniforms) {\n if (uniforms.indexOf(uniform) === -1) {\n uniforms.push(uniform);\n }\n }\n }\n if (this.customShaderOptions.samplers) {\n for (const sampler of this.customShaderOptions.samplers) {\n if (samplers.indexOf(sampler) === -1) {\n samplers.push(sampler);\n }\n }\n }\n }\n const engine = this._scene.getEngine();\n effect = engine.createEffect(shaderName, {\n attributes: attribs,\n uniformsNames: uniforms,\n uniformBuffersNames: uniformBuffers,\n samplers: samplers,\n defines: join,\n fallbacks: fallbacks,\n onCompiled: null,\n onError: null,\n indexParameters: { maxSimultaneousMorphTargets: morphInfluencers },\n }, engine);\n subMeshEffect.setEffect(effect, cachedDefines);\n }\n if (!effect.isReady()) {\n return false;\n }\n }\n if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {\n if (!this._blurPostProcesses || !this._blurPostProcesses.length) {\n this._initializeBlurRTTAndPostProcesses();\n }\n }\n if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {\n return false;\n }\n if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {\n return false;\n }\n if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {\n return false;\n }\n return true;\n }\n /**\n * Prepare all the defines in a material relying on a shadow map at the specified light index.\n * @param defines Defines of the material we want to update\n * @param lightIndex Index of the light in the enabled light list of the material\n */\n prepareDefines(defines, lightIndex) {\n const scene = this._scene;\n const light = this._light;\n if (!scene.shadowsEnabled || !light.shadowEnabled) {\n return;\n }\n defines[\"SHADOW\" + lightIndex] = true;\n if (this.useContactHardeningShadow) {\n defines[\"SHADOWPCSS\" + lightIndex] = true;\n if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {\n defines[\"SHADOWLOWQUALITY\" + lightIndex] = true;\n }\n else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {\n defines[\"SHADOWMEDIUMQUALITY\" + lightIndex] = true;\n }\n // else default to high.\n }\n else if (this.usePercentageCloserFiltering) {\n defines[\"SHADOWPCF\" + lightIndex] = true;\n if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {\n defines[\"SHADOWLOWQUALITY\" + lightIndex] = true;\n }\n else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {\n defines[\"SHADOWMEDIUMQUALITY\" + lightIndex] = true;\n }\n // else default to high.\n }\n else if (this.usePoissonSampling) {\n defines[\"SHADOWPOISSON\" + lightIndex] = true;\n }\n else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {\n defines[\"SHADOWESM\" + lightIndex] = true;\n }\n else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {\n defines[\"SHADOWCLOSEESM\" + lightIndex] = true;\n }\n if (light.needCube()) {\n defines[\"SHADOWCUBE\" + lightIndex] = true;\n }\n }\n /**\n * Binds the shadow related information inside of an effect (information like near, far, darkness...\n * defined in the generator but impacting the effect).\n * @param lightIndex Index of the light in the enabled light list of the material owning the effect\n * @param effect The effect we are binding the information for\n */\n bindShadowLight(lightIndex, effect) {\n const light = this._light;\n const scene = this._scene;\n if (!scene.shadowsEnabled || !light.shadowEnabled) {\n return;\n }\n const camera = this._getCamera();\n if (!camera) {\n return;\n }\n const shadowMap = this.getShadowMap();\n if (!shadowMap) {\n return;\n }\n if (!light.needCube()) {\n effect.setMatrix(\"lightMatrix\" + lightIndex, this.getTransformMatrix());\n }\n // Only PCF uses depth stencil texture.\n if (this._filter === ShadowGenerator.FILTER_PCF) {\n effect.setDepthStencilTexture(\"shadowSampler\" + lightIndex, this.getShadowMapForRendering());\n light._uniformBuffer.updateFloat4(\"shadowsInfo\", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);\n }\n else if (this._filter === ShadowGenerator.FILTER_PCSS) {\n effect.setDepthStencilTexture(\"shadowSampler\" + lightIndex, this.getShadowMapForRendering());\n effect.setTexture(\"depthSampler\" + lightIndex, this.getShadowMapForRendering());\n light._uniformBuffer.updateFloat4(\"shadowsInfo\", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);\n }\n else {\n effect.setTexture(\"shadowSampler\" + lightIndex, this.getShadowMapForRendering());\n light._uniformBuffer.updateFloat4(\"shadowsInfo\", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);\n }\n light._uniformBuffer.updateFloat2(\"depthValues\", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);\n }\n /**\n * Gets the transformation matrix used to project the meshes into the map from the light point of view.\n * (eq to shadow projection matrix * light transform matrix)\n * @returns The transform matrix used to create the shadow map\n */\n getTransformMatrix() {\n const scene = this._scene;\n if (this._currentRenderId === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {\n return this._transformMatrix;\n }\n this._currentRenderId = scene.getRenderId();\n this._currentFaceIndexCache = this._currentFaceIndex;\n let lightPosition = this._light.position;\n if (this._light.computeTransformedInformation()) {\n lightPosition = this._light.transformedPosition;\n }\n Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);\n if (Math.abs(Vector3.Dot(this._lightDirection, Vector3.Up())) === 1.0) {\n this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light\n }\n if (this._light.needProjectionMatrixCompute() ||\n !this._cachedPosition ||\n !this._cachedDirection ||\n !lightPosition.equals(this._cachedPosition) ||\n !this._lightDirection.equals(this._cachedDirection)) {\n this._cachedPosition.copyFrom(lightPosition);\n this._cachedDirection.copyFrom(this._lightDirection);\n Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), Vector3.Up(), this._viewMatrix);\n const shadowMap = this.getShadowMap();\n if (shadowMap) {\n const renderList = shadowMap.renderList;\n if (renderList) {\n this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);\n }\n }\n this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);\n }\n return this._transformMatrix;\n }\n /**\n * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between\n * Cube and 2D textures for instance.\n */\n recreateShadowMap() {\n const shadowMap = this._shadowMap;\n if (!shadowMap) {\n return;\n }\n // Track render list.\n const renderList = shadowMap.renderList;\n // Clean up existing data.\n this._disposeRTTandPostProcesses();\n // Reinitializes.\n this._initializeGenerator();\n // Reaffect the filter to ensure a correct fallback if necessary.\n this.filter = this._filter;\n // Reaffect the filter.\n this._applyFilterValues();\n // Reaffect Render List.\n if (renderList) {\n // Note: don't do this._shadowMap!.renderList = renderList;\n // The renderList hooked array is accessing the old RenderTargetTexture (see RenderTargetTexture._hookArray), which is disposed at this point (by the call to _disposeRTTandPostProcesses)\n if (!this._shadowMap.renderList) {\n this._shadowMap.renderList = [];\n }\n for (const mesh of renderList) {\n this._shadowMap.renderList.push(mesh);\n }\n }\n else {\n this._shadowMap.renderList = null;\n }\n }\n _disposeBlurPostProcesses() {\n if (this._shadowMap2) {\n this._shadowMap2.dispose();\n this._shadowMap2 = null;\n }\n if (this._boxBlurPostprocess) {\n this._boxBlurPostprocess.dispose();\n this._boxBlurPostprocess = null;\n }\n if (this._kernelBlurXPostprocess) {\n this._kernelBlurXPostprocess.dispose();\n this._kernelBlurXPostprocess = null;\n }\n if (this._kernelBlurYPostprocess) {\n this._kernelBlurYPostprocess.dispose();\n this._kernelBlurYPostprocess = null;\n }\n this._blurPostProcesses = [];\n }\n _disposeRTTandPostProcesses() {\n if (this._shadowMap) {\n this._shadowMap.dispose();\n this._shadowMap = null;\n }\n this._disposeBlurPostProcesses();\n }\n _disposeSceneUBOs() {\n if (this._sceneUBOs) {\n for (const ubo of this._sceneUBOs) {\n ubo.dispose();\n }\n this._sceneUBOs = [];\n }\n }\n /**\n * Disposes the ShadowGenerator.\n * Returns nothing.\n */\n dispose() {\n this._disposeRTTandPostProcesses();\n this._disposeSceneUBOs();\n if (this._light) {\n if (this._light._shadowGenerators) {\n const iterator = this._light._shadowGenerators.entries();\n for (let entry = iterator.next(); entry.done !== true; entry = iterator.next()) {\n const [camera, shadowGenerator] = entry.value;\n if (shadowGenerator === this) {\n this._light._shadowGenerators.delete(camera);\n }\n }\n if (this._light._shadowGenerators.size === 0) {\n this._light._shadowGenerators = null;\n }\n }\n this._light._markMeshesAsLightDirty();\n }\n this.onBeforeShadowMapRenderMeshObservable.clear();\n this.onBeforeShadowMapRenderObservable.clear();\n this.onAfterShadowMapRenderMeshObservable.clear();\n this.onAfterShadowMapRenderObservable.clear();\n }\n /**\n * Serializes the shadow generator setup to a json object.\n * @returns The serialized JSON object\n */\n serialize() {\n var _a;\n const serializationObject = {};\n const shadowMap = this.getShadowMap();\n if (!shadowMap) {\n return serializationObject;\n }\n serializationObject.className = this.getClassName();\n serializationObject.lightId = this._light.id;\n serializationObject.cameraId = (_a = this._camera) === null || _a === void 0 ? void 0 : _a.id;\n serializationObject.id = this.id;\n serializationObject.mapSize = shadowMap.getRenderSize();\n serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;\n serializationObject.darkness = this.getDarkness();\n serializationObject.transparencyShadow = this._transparencyShadow;\n serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;\n serializationObject.bias = this.bias;\n serializationObject.normalBias = this.normalBias;\n serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;\n serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;\n serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;\n serializationObject.filteringQuality = this.filteringQuality;\n serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;\n serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;\n serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;\n serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;\n serializationObject.usePoissonSampling = this.usePoissonSampling;\n serializationObject.depthScale = this.depthScale;\n serializationObject.blurBoxOffset = this.blurBoxOffset;\n serializationObject.blurKernel = this.blurKernel;\n serializationObject.blurScale = this.blurScale;\n serializationObject.useKernelBlur = this.useKernelBlur;\n serializationObject.renderList = [];\n if (shadowMap.renderList) {\n for (let meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {\n const mesh = shadowMap.renderList[meshIndex];\n serializationObject.renderList.push(mesh.id);\n }\n }\n return serializationObject;\n }\n /**\n * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.\n * @param parsedShadowGenerator The JSON object to parse\n * @param scene The scene to create the shadow map for\n * @param constr A function that builds a shadow generator or undefined to create an instance of the default shadow generator\n * @returns The parsed shadow generator\n */\n static Parse(parsedShadowGenerator, scene, constr) {\n const light = scene.getLightById(parsedShadowGenerator.lightId);\n const camera = parsedShadowGenerator.cameraId !== undefined ? scene.getCameraById(parsedShadowGenerator.cameraId) : null;\n const shadowGenerator = constr ? constr(parsedShadowGenerator.mapSize, light, camera) : new ShadowGenerator(parsedShadowGenerator.mapSize, light, undefined, camera);\n const shadowMap = shadowGenerator.getShadowMap();\n for (let meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {\n const meshes = scene.getMeshesById(parsedShadowGenerator.renderList[meshIndex]);\n meshes.forEach(function (mesh) {\n if (!shadowMap) {\n return;\n }\n if (!shadowMap.renderList) {\n shadowMap.renderList = [];\n }\n shadowMap.renderList.push(mesh);\n });\n }\n if (parsedShadowGenerator.id !== undefined) {\n shadowGenerator.id = parsedShadowGenerator.id;\n }\n shadowGenerator.forceBackFacesOnly = !!parsedShadowGenerator.forceBackFacesOnly;\n if (parsedShadowGenerator.darkness !== undefined) {\n shadowGenerator.setDarkness(parsedShadowGenerator.darkness);\n }\n if (parsedShadowGenerator.transparencyShadow) {\n shadowGenerator.setTransparencyShadow(true);\n }\n if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {\n shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;\n }\n if (parsedShadowGenerator.bias !== undefined) {\n shadowGenerator.bias = parsedShadowGenerator.bias;\n }\n if (parsedShadowGenerator.normalBias !== undefined) {\n shadowGenerator.normalBias = parsedShadowGenerator.normalBias;\n }\n if (parsedShadowGenerator.usePercentageCloserFiltering) {\n shadowGenerator.usePercentageCloserFiltering = true;\n }\n else if (parsedShadowGenerator.useContactHardeningShadow) {\n shadowGenerator.useContactHardeningShadow = true;\n }\n else if (parsedShadowGenerator.usePoissonSampling) {\n shadowGenerator.usePoissonSampling = true;\n }\n else if (parsedShadowGenerator.useExponentialShadowMap) {\n shadowGenerator.useExponentialShadowMap = true;\n }\n else if (parsedShadowGenerator.useBlurExponentialShadowMap) {\n shadowGenerator.useBlurExponentialShadowMap = true;\n }\n else if (parsedShadowGenerator.useCloseExponentialShadowMap) {\n shadowGenerator.useCloseExponentialShadowMap = true;\n }\n else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {\n shadowGenerator.useBlurCloseExponentialShadowMap = true;\n }\n // Backward compat\n else if (parsedShadowGenerator.useVarianceShadowMap) {\n shadowGenerator.useExponentialShadowMap = true;\n }\n else if (parsedShadowGenerator.useBlurVarianceShadowMap) {\n shadowGenerator.useBlurExponentialShadowMap = true;\n }\n if (parsedShadowGenerator.contactHardeningLightSizeUVRatio !== undefined) {\n shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;\n }\n if (parsedShadowGenerator.filteringQuality !== undefined) {\n shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;\n }\n if (parsedShadowGenerator.depthScale) {\n shadowGenerator.depthScale = parsedShadowGenerator.depthScale;\n }\n if (parsedShadowGenerator.blurScale) {\n shadowGenerator.blurScale = parsedShadowGenerator.blurScale;\n }\n if (parsedShadowGenerator.blurBoxOffset) {\n shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;\n }\n if (parsedShadowGenerator.useKernelBlur) {\n shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;\n }\n if (parsedShadowGenerator.blurKernel) {\n shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;\n }\n return shadowGenerator;\n }\n}\n/**\n * Name of the shadow generator class\n */\nShadowGenerator.CLASSNAME = \"ShadowGenerator\";\n/**\n * Shadow generator mode None: no filtering applied.\n */\nShadowGenerator.FILTER_NONE = 0;\n/**\n * Shadow generator mode ESM: Exponential Shadow Mapping.\n * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)\n */\nShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;\n/**\n * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.\n * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)\n */\nShadowGenerator.FILTER_POISSONSAMPLING = 2;\n/**\n * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.\n * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)\n */\nShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;\n/**\n * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing\n * edge artifacts on steep falloff.\n * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)\n */\nShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;\n/**\n * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing\n * edge artifacts on steep falloff.\n * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)\n */\nShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;\n/**\n * Shadow generator mode PCF: Percentage Closer Filtering\n * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1\n * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)\n */\nShadowGenerator.FILTER_PCF = 6;\n/**\n * Shadow generator mode PCSS: Percentage Closering Soft Shadow.\n * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1\n * Contact Hardening\n */\nShadowGenerator.FILTER_PCSS = 7;\n/**\n * Reserved for PCF and PCSS\n * Highest Quality.\n *\n * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.\n *\n * Execute PCSS with 32 taps blocker search and 64 taps PCF.\n */\nShadowGenerator.QUALITY_HIGH = 0;\n/**\n * Reserved for PCF and PCSS\n * Good tradeoff for quality/perf cross devices\n *\n * Execute PCF on a 3*3 kernel.\n *\n * Execute PCSS with 16 taps blocker search and 32 taps PCF.\n */\nShadowGenerator.QUALITY_MEDIUM = 1;\n/**\n * Reserved for PCF and PCSS\n * The lowest quality but the fastest.\n *\n * Execute PCF on a 1*1 kernel.\n *\n * Execute PCSS with 16 taps blocker search and 16 taps PCF.\n */\nShadowGenerator.QUALITY_LOW = 2;\n/**\n * Defines the default alpha cutoff value used for transparent alpha tested materials.\n */\nShadowGenerator.DEFAULT_ALPHA_CUTOFF = 0.5;\n/**\n * @internal\n */\nShadowGenerator._SceneComponentInitialization = (_) => {\n throw _WarnImport(\"ShadowGeneratorSceneComponent\");\n};\n//# sourceMappingURL=shadowGenerator.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"shadowMapFragmentSoftTransparentShadow\";\nconst shader = `#if SM_SOFTTRANSPARENTSHADOW==1\nif ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const shadowMapFragmentSoftTransparentShadow = { name, shader };\n//# sourceMappingURL=shadowMapFragmentSoftTransparentShadow.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/clipPlaneFragmentDeclaration.js\";\nimport \"./ShadersInclude/packingFunctions.js\";\nimport \"./ShadersInclude/clipPlaneFragment.js\";\nconst name = \"depthPixelShader\";\nconst shader = `#ifdef ALPHATEST\nvarying vec2 vUV;\runiform sampler2D diffuseSampler;\r#endif\n#include\nvarying float vDepthMetric;\r#ifdef PACKED\n#include\n#endif\n#ifdef STORE_CAMERASPACE_Z\nvarying vec4 vViewPos;\r#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\r{\r#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\rdiscard;\r#endif\n#ifdef STORE_CAMERASPACE_Z\n#ifdef PACKED\ngl_FragColor=pack(vViewPos.z);\r#else\ngl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0);\r#endif\n#else\n#ifdef NONLINEARDEPTH\n#ifdef PACKED\ngl_FragColor=pack(gl_FragCoord.z);\r#else\ngl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0);\r#endif\n#else\n#ifdef PACKED\ngl_FragColor=pack(vDepthMetric);\r#else\ngl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0);\r#endif\n#endif\n#endif\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const depthPixelShader = { name, shader };\n//# sourceMappingURL=depth.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/bonesDeclaration.js\";\nimport \"./ShadersInclude/bakedVertexAnimationDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexGlobalDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneVertexDeclaration.js\";\nimport \"./ShadersInclude/instancesDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexGlobal.js\";\nimport \"./ShadersInclude/morphTargetsVertex.js\";\nimport \"./ShadersInclude/instancesVertex.js\";\nimport \"./ShadersInclude/bonesVertex.js\";\nimport \"./ShadersInclude/bakedVertexAnimation.js\";\nimport \"./ShadersInclude/clipPlaneVertex.js\";\nconst name = \"depthVertexShader\";\nconst shader = `attribute vec3 position;\r#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nuniform mat4 viewProjection;\runiform vec2 depthValues;\r#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\runiform mat4 diffuseMatrix;\r#ifdef UV1\nattribute vec2 uv;\r#endif\n#ifdef UV2\nattribute vec2 uv2;\r#endif\n#endif\n#ifdef STORE_CAMERASPACE_Z\nuniform mat4 view;\rvarying vec4 vViewPos;\r#endif\nvarying float vDepthMetric;\r#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\r{\rvec3 positionUpdated=position;\r#ifdef UV1\nvec2 uvUpdated=uv;\r#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\r#include\ngl_Position=viewProjection*worldPos;\r#ifdef STORE_CAMERASPACE_Z\nvViewPos=view*worldPos;\r#else\n#ifdef USE_REVERSE_DEPTHBUFFER\nvDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y));\r#else\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\r#endif\n#endif\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\r#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\r#endif\n#endif\n}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const depthVertexShader = { name, shader };\n//# sourceMappingURL=depth.vertex.js.map","import { Color4 } from \"../Maths/math.color.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { RenderTargetTexture } from \"../Materials/Textures/renderTargetTexture.js\";\nimport { MaterialHelper } from \"../Materials/materialHelper.js\";\nimport { Camera } from \"../Cameras/camera.js\";\n\nimport \"../Shaders/depth.fragment.js\";\nimport \"../Shaders/depth.vertex.js\";\nimport { _WarnImport } from \"../Misc/devTools.js\";\nimport { addClipPlaneUniforms, bindClipPlane, prepareStringDefinesForClipPlanes } from \"../Materials/clipPlaneMaterialHelper.js\";\n/**\n * This represents a depth renderer in Babylon.\n * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing\n */\nexport class DepthRenderer {\n /**\n * Sets a specific material to be used to render a mesh/a list of meshes by the depth renderer\n * @param mesh mesh or array of meshes\n * @param material material to use by the depth render when rendering the mesh(es). If undefined is passed, the specific material created by the depth renderer will be used.\n */\n setMaterialForRendering(mesh, material) {\n this._depthMap.setMaterialForRendering(mesh, material);\n }\n /**\n * Instantiates a depth renderer\n * @param scene The scene the renderer belongs to\n * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)\n * @param camera The camera to be used to render the depth map (default: scene's active camera)\n * @param storeNonLinearDepth Defines whether the depth is stored linearly like in Babylon Shadows or directly like glFragCoord.z\n * @param samplingMode The sampling mode to be used with the render target (Linear, Nearest...) (default: TRILINEAR_SAMPLINGMODE)\n * @param storeCameraSpaceZ Defines whether the depth stored is the Z coordinate in camera space. If true, storeNonLinearDepth has no effect. (Default: false)\n * @param name Name of the render target (default: DepthRenderer)\n */\n constructor(scene, type = 1, camera = null, storeNonLinearDepth = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, storeCameraSpaceZ = false, name) {\n /** Enable or disable the depth renderer. When disabled, the depth texture is not updated */\n this.enabled = true;\n /** Force writing the transparent objects into the depth map */\n this.forceDepthWriteTransparentMeshes = false;\n /**\n * Specifies that the depth renderer will only be used within\n * the camera it is created for.\n * This can help forcing its rendering during the camera processing.\n */\n this.useOnlyInActiveCamera = false;\n /** If true, reverse the culling of materials before writing to the depth texture.\n * So, basically, when \"true\", back facing instead of front facing faces are rasterized into the texture\n */\n this.reverseCulling = false;\n this._scene = scene;\n this._storeNonLinearDepth = storeNonLinearDepth;\n this._storeCameraSpaceZ = storeCameraSpaceZ;\n this.isPacked = type === 0;\n if (this.isPacked) {\n this.clearColor = new Color4(1.0, 1.0, 1.0, 1.0);\n }\n else {\n this.clearColor = new Color4(storeCameraSpaceZ ? 1e8 : 1.0, 0.0, 0.0, 1.0);\n }\n DepthRenderer._SceneComponentInitialization(this._scene);\n const engine = scene.getEngine();\n this._camera = camera;\n if (samplingMode !== Texture.NEAREST_SAMPLINGMODE) {\n if (type === 1 && !engine._caps.textureFloatLinearFiltering) {\n samplingMode = Texture.NEAREST_SAMPLINGMODE;\n }\n if (type === 2 && !engine._caps.textureHalfFloatLinearFiltering) {\n samplingMode = Texture.NEAREST_SAMPLINGMODE;\n }\n }\n // Render target\n const format = this.isPacked || !engine._features.supportExtendedTextureFormats ? 5 : 6;\n this._depthMap = new RenderTargetTexture(name !== null && name !== void 0 ? name : \"DepthRenderer\", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type, false, samplingMode, undefined, undefined, undefined, format);\n this._depthMap.wrapU = Texture.CLAMP_ADDRESSMODE;\n this._depthMap.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._depthMap.refreshRate = 1;\n this._depthMap.renderParticles = false;\n this._depthMap.renderList = null;\n this._depthMap.noPrePassRenderer = true;\n // Camera to get depth map from to support multiple concurrent cameras\n this._depthMap.activeCamera = this._camera;\n this._depthMap.ignoreCameraViewport = true;\n this._depthMap.useCameraPostProcesses = false;\n // set default depth value to 1.0 (far away)\n this._depthMap.onClearObservable.add((engine) => {\n engine.clear(this.clearColor, true, true, true);\n });\n this._depthMap.onBeforeBindObservable.add(() => {\n var _a;\n (_a = engine._debugPushGroup) === null || _a === void 0 ? void 0 : _a.call(engine, \"depth renderer\", 1);\n });\n this._depthMap.onAfterUnbindObservable.add(() => {\n var _a;\n (_a = engine._debugPopGroup) === null || _a === void 0 ? void 0 : _a.call(engine, 1);\n });\n this._depthMap.customIsReadyFunction = (mesh, refreshRate, preWarm) => {\n if ((preWarm || refreshRate === 0) && mesh.subMeshes) {\n for (let i = 0; i < mesh.subMeshes.length; ++i) {\n const subMesh = mesh.subMeshes[i];\n const renderingMesh = subMesh.getRenderingMesh();\n const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());\n const hardwareInstancedRendering = engine.getCaps().instancedArrays &&\n ((batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined) || renderingMesh.hasThinInstances);\n if (!this.isReady(subMesh, hardwareInstancedRendering)) {\n return false;\n }\n }\n }\n return true;\n };\n // Custom render function\n const renderSubMesh = (subMesh) => {\n var _a, _b;\n const renderingMesh = subMesh.getRenderingMesh();\n const effectiveMesh = subMesh.getEffectiveMesh();\n const scene = this._scene;\n const engine = scene.getEngine();\n const material = subMesh.getMaterial();\n effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;\n if (!material || effectiveMesh.infiniteDistance || material.disableDepthWrite || subMesh.verticesCount === 0 || subMesh._renderId === scene.getRenderId()) {\n return;\n }\n // Culling\n const detNeg = effectiveMesh._getWorldMatrixDeterminant() < 0;\n let sideOrientation = (_a = renderingMesh.overrideMaterialSideOrientation) !== null && _a !== void 0 ? _a : material.sideOrientation;\n if (detNeg) {\n sideOrientation =\n sideOrientation === 0\n ? 1\n : 0;\n }\n const reverseSideOrientation = sideOrientation === 0;\n engine.setState(material.backFaceCulling, 0, false, reverseSideOrientation, this.reverseCulling ? !material.cullBackFaces : material.cullBackFaces);\n // Managing instances\n const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());\n if (batch.mustReturn) {\n return;\n }\n const hardwareInstancedRendering = engine.getCaps().instancedArrays &&\n ((batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined) || renderingMesh.hasThinInstances);\n const camera = this._camera || scene.activeCamera;\n if (this.isReady(subMesh, hardwareInstancedRendering) && camera) {\n subMesh._renderId = scene.getRenderId();\n const renderingMaterial = (_b = effectiveMesh._internalAbstractMeshDataInfo._materialForRenderPass) === null || _b === void 0 ? void 0 : _b[engine.currentRenderPassId];\n let drawWrapper = subMesh._getDrawWrapper();\n if (!drawWrapper && renderingMaterial) {\n drawWrapper = renderingMaterial._getDrawWrapper();\n }\n const cameraIsOrtho = camera.mode === Camera.ORTHOGRAPHIC_CAMERA;\n if (!drawWrapper) {\n return;\n }\n const effect = drawWrapper.effect;\n engine.enableEffect(drawWrapper);\n if (!hardwareInstancedRendering) {\n renderingMesh._bind(subMesh, effect, material.fillMode);\n }\n if (!renderingMaterial) {\n effect.setMatrix(\"viewProjection\", scene.getTransformMatrix());\n effect.setMatrix(\"world\", effectiveMesh.getWorldMatrix());\n if (this._storeCameraSpaceZ) {\n effect.setMatrix(\"view\", scene.getViewMatrix());\n }\n }\n else {\n renderingMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), effectiveMesh, subMesh);\n }\n let minZ, maxZ;\n if (cameraIsOrtho) {\n minZ = !engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : 1;\n maxZ = engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : 1;\n }\n else {\n minZ = engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? camera.minZ : engine.isNDCHalfZRange ? 0 : camera.minZ;\n maxZ = engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : camera.maxZ;\n }\n effect.setFloat2(\"depthValues\", minZ, minZ + maxZ);\n if (!renderingMaterial) {\n // Alpha test\n if (material.needAlphaTesting()) {\n const alphaTexture = material.getAlphaTestTexture();\n if (alphaTexture) {\n effect.setTexture(\"diffuseSampler\", alphaTexture);\n effect.setMatrix(\"diffuseMatrix\", alphaTexture.getTextureMatrix());\n }\n }\n // Bones\n if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) {\n const skeleton = renderingMesh.skeleton;\n if (skeleton.isUsingTextureForMatrices) {\n const boneTexture = skeleton.getTransformMatrixTexture(renderingMesh);\n if (!boneTexture) {\n return;\n }\n effect.setTexture(\"boneSampler\", boneTexture);\n effect.setFloat(\"boneTextureWidth\", 4.0 * (skeleton.bones.length + 1));\n }\n else {\n effect.setMatrices(\"mBones\", skeleton.getTransformMatrices(renderingMesh));\n }\n }\n // Clip planes\n bindClipPlane(effect, material, scene);\n // Morph targets\n MaterialHelper.BindMorphTargetParameters(renderingMesh, effect);\n if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) {\n renderingMesh.morphTargetManager._bind(effect);\n }\n }\n // Draw\n renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, world) => effect.setMatrix(\"world\", world));\n }\n };\n this._depthMap.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => {\n let index;\n if (depthOnlySubMeshes.length) {\n for (index = 0; index < depthOnlySubMeshes.length; index++) {\n renderSubMesh(depthOnlySubMeshes.data[index]);\n }\n }\n for (index = 0; index < opaqueSubMeshes.length; index++) {\n renderSubMesh(opaqueSubMeshes.data[index]);\n }\n for (index = 0; index < alphaTestSubMeshes.length; index++) {\n renderSubMesh(alphaTestSubMeshes.data[index]);\n }\n if (this.forceDepthWriteTransparentMeshes) {\n for (index = 0; index < transparentSubMeshes.length; index++) {\n renderSubMesh(transparentSubMeshes.data[index]);\n }\n }\n else {\n for (index = 0; index < transparentSubMeshes.length; index++) {\n transparentSubMeshes.data[index].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate = false;\n }\n }\n };\n }\n /**\n * Creates the depth rendering effect and checks if the effect is ready.\n * @param subMesh The submesh to be used to render the depth map of\n * @param useInstances If multiple world instances should be used\n * @returns if the depth renderer is ready to render the depth map\n */\n isReady(subMesh, useInstances) {\n var _a;\n const engine = this._scene.getEngine();\n const mesh = subMesh.getMesh();\n const scene = mesh.getScene();\n const renderingMaterial = (_a = mesh._internalAbstractMeshDataInfo._materialForRenderPass) === null || _a === void 0 ? void 0 : _a[engine.currentRenderPassId];\n if (renderingMaterial) {\n return renderingMaterial.isReadyForSubMesh(mesh, subMesh, useInstances);\n }\n const material = subMesh.getMaterial();\n if (!material || material.disableDepthWrite) {\n return false;\n }\n const defines = [];\n const attribs = [VertexBuffer.PositionKind];\n // Alpha test\n if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {\n defines.push(\"#define ALPHATEST\");\n if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {\n attribs.push(VertexBuffer.UVKind);\n defines.push(\"#define UV1\");\n }\n if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {\n attribs.push(VertexBuffer.UV2Kind);\n defines.push(\"#define UV2\");\n }\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders) {\n attribs.push(VertexBuffer.MatricesIndicesKind);\n attribs.push(VertexBuffer.MatricesWeightsKind);\n if (mesh.numBoneInfluencers > 4) {\n attribs.push(VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(VertexBuffer.MatricesWeightsExtraKind);\n }\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n defines.push(\"#define BonesPerMesh \" + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));\n const skeleton = subMesh.getRenderingMesh().skeleton;\n if (skeleton === null || skeleton === void 0 ? void 0 : skeleton.isUsingTextureForMatrices) {\n defines.push(\"#define BONETEXTURE\");\n }\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Morph targets\n const morphTargetManager = mesh.morphTargetManager;\n let numMorphInfluencers = 0;\n if (morphTargetManager) {\n if (morphTargetManager.numInfluencers > 0) {\n numMorphInfluencers = morphTargetManager.numInfluencers;\n defines.push(\"#define MORPHTARGETS\");\n defines.push(\"#define NUM_MORPH_INFLUENCERS \" + numMorphInfluencers);\n if (morphTargetManager.isUsingTextureForTargets) {\n defines.push(\"#define MORPHTARGETS_TEXTURE\");\n }\n MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, numMorphInfluencers);\n }\n }\n // Instances\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n MaterialHelper.PushAttributesForInstances(attribs);\n if (subMesh.getRenderingMesh().hasThinInstances) {\n defines.push(\"#define THIN_INSTANCES\");\n }\n }\n // None linear depth\n if (this._storeNonLinearDepth) {\n defines.push(\"#define NONLINEARDEPTH\");\n }\n // Store camera space Z coordinate instead of NDC Z\n if (this._storeCameraSpaceZ) {\n defines.push(\"#define STORE_CAMERASPACE_Z\");\n }\n // Float Mode\n if (this.isPacked) {\n defines.push(\"#define PACKED\");\n }\n // Clip planes\n prepareStringDefinesForClipPlanes(material, scene, defines);\n // Get correct effect\n const drawWrapper = subMesh._getDrawWrapper(undefined, true);\n const cachedDefines = drawWrapper.defines;\n const join = defines.join(\"\\n\");\n if (cachedDefines !== join) {\n const uniforms = [\n \"world\",\n \"mBones\",\n \"boneTextureWidth\",\n \"viewProjection\",\n \"view\",\n \"diffuseMatrix\",\n \"depthValues\",\n \"morphTargetInfluences\",\n \"morphTargetTextureInfo\",\n \"morphTargetTextureIndices\",\n ];\n addClipPlaneUniforms(uniforms);\n drawWrapper.setEffect(engine.createEffect(\"depth\", attribs, uniforms, [\"diffuseSampler\", \"morphTargets\", \"boneSampler\"], join, undefined, undefined, undefined, {\n maxSimultaneousMorphTargets: numMorphInfluencers,\n }), join);\n }\n return drawWrapper.effect.isReady();\n }\n /**\n * Gets the texture which the depth map will be written to.\n * @returns The depth map texture\n */\n getDepthMap() {\n return this._depthMap;\n }\n /**\n * Disposes of the depth renderer.\n */\n dispose() {\n const keysToDelete = [];\n for (const key in this._scene._depthRenderer) {\n const depthRenderer = this._scene._depthRenderer[key];\n if (depthRenderer === this) {\n keysToDelete.push(key);\n }\n }\n if (keysToDelete.length > 0) {\n this._depthMap.dispose();\n for (const key of keysToDelete) {\n delete this._scene._depthRenderer[key];\n }\n }\n }\n}\n/**\n * @internal\n */\nDepthRenderer._SceneComponentInitialization = (_) => {\n throw _WarnImport(\"DepthRendererSceneComponent\");\n};\n//# sourceMappingURL=depthRenderer.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"minmaxReduxPixelShader\";\nconst shader = `varying vec2 vUV;\runiform sampler2D textureSampler;\r#if defined(INITIAL)\nuniform sampler2D sourceTexture;\runiform vec2 texSize;\rvoid main(void)\r{\rivec2 coord=ivec2(vUV*(texSize-1.0));\rfloat f1=texelFetch(sourceTexture,coord,0).r;\rfloat f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;\rfloat f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;\rfloat f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;\rfloat minz=min(min(min(f1,f2),f3),f4);\r#ifdef DEPTH_REDUX\nfloat maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4);\r#else\nfloat maxz=max(max(max(f1,f2),f3),f4);\r#endif\nglFragColor=vec4(minz,maxz,0.,0.);\r}\r#elif defined(MAIN)\nuniform vec2 texSize;\rvoid main(void)\r{\rivec2 coord=ivec2(vUV*(texSize-1.0));\rvec2 f1=texelFetch(textureSampler,coord,0).rg;\rvec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;\rvec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;\rvec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;\rfloat minz=min(min(min(f1.x,f2.x),f3.x),f4.x);\rfloat maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);\rglFragColor=vec4(minz,maxz,0.,0.);\r}\r#elif defined(ONEBEFORELAST)\nuniform ivec2 texSize;\rvoid main(void)\r{\rivec2 coord=ivec2(vUV*vec2(texSize-1));\rvec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;\rvec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;\rvec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;\rvec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;\rfloat minz=min(f1.x,f2.x);\rfloat maxz=max(f1.y,f2.y);\rglFragColor=vec4(minz,maxz,0.,0.);\r}\r#elif defined(LAST)\nvoid main(void)\r{\rglFragColor=vec4(0.);\rif (true) { \rdiscard;\r}\r}\r#endif\n`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const minmaxReduxPixelShader = { name, shader };\n//# sourceMappingURL=minmaxRedux.fragment.js.map","\nimport { Observable } from \"./observable.js\";\nimport { PostProcess } from \"../PostProcesses/postProcess.js\";\nimport { PostProcessManager } from \"../PostProcesses/postProcessManager.js\";\nimport \"../Shaders/minmaxRedux.fragment.js\";\n/**\n * This class computes a min/max reduction from a texture: it means it computes the minimum\n * and maximum values from all values of the texture.\n * It is performed on the GPU for better performances, thanks to a succession of post processes.\n * The source values are read from the red channel of the texture.\n */\nexport class MinMaxReducer {\n /**\n * Creates a min/max reducer\n * @param camera The camera to use for the post processes\n */\n constructor(camera) {\n /**\n * Observable triggered when the computation has been performed\n */\n this.onAfterReductionPerformed = new Observable();\n this._forceFullscreenViewport = true;\n this._activated = false;\n this._camera = camera;\n this._postProcessManager = new PostProcessManager(camera.getScene());\n this._onContextRestoredObserver = camera.getEngine().onContextRestoredObservable.add(() => {\n this._postProcessManager._rebuild();\n });\n }\n /**\n * Gets the texture used to read the values from.\n */\n get sourceTexture() {\n return this._sourceTexture;\n }\n /**\n * Sets the source texture to read the values from.\n * One must indicate if the texture is a depth texture or not through the depthRedux parameter\n * because in such textures '1' value must not be taken into account to compute the maximum\n * as this value is used to clear the texture.\n * Note that the computation is not activated by calling this function, you must call activate() for that!\n * @param sourceTexture The texture to read the values from. The values should be in the red channel.\n * @param depthRedux Indicates if the texture is a depth texture or not\n * @param type The type of the textures created for the reduction (defaults to TEXTURETYPE_HALF_FLOAT)\n * @param forceFullscreenViewport Forces the post processes used for the reduction to be applied without taking into account viewport (defaults to true)\n */\n setSourceTexture(sourceTexture, depthRedux, type = 2, forceFullscreenViewport = true) {\n if (sourceTexture === this._sourceTexture) {\n return;\n }\n this.dispose(false);\n this._sourceTexture = sourceTexture;\n this._reductionSteps = [];\n this._forceFullscreenViewport = forceFullscreenViewport;\n const scene = this._camera.getScene();\n // create the first step\n const reductionInitial = new PostProcess(\"Initial reduction phase\", \"minmaxRedux\", // shader\n [\"texSize\"], [\"sourceTexture\"], // textures\n 1.0, // options\n null, // camera\n 1, // sampling\n scene.getEngine(), // engine\n false, // reusable\n \"#define INITIAL\" + (depthRedux ? \"\\n#define DEPTH_REDUX\" : \"\"), // defines\n type, undefined, undefined, undefined, 7);\n reductionInitial.autoClear = false;\n reductionInitial.forceFullscreenViewport = forceFullscreenViewport;\n let w = this._sourceTexture.getRenderWidth(), h = this._sourceTexture.getRenderHeight();\n reductionInitial.onApply = ((w, h) => {\n return (effect) => {\n effect.setTexture(\"sourceTexture\", this._sourceTexture);\n effect.setFloat2(\"texSize\", w, h);\n };\n })(w, h);\n this._reductionSteps.push(reductionInitial);\n let index = 1;\n // create the additional steps\n while (w > 1 || h > 1) {\n w = Math.max(Math.round(w / 2), 1);\n h = Math.max(Math.round(h / 2), 1);\n const reduction = new PostProcess(\"Reduction phase \" + index, \"minmaxRedux\", // shader\n [\"texSize\"], null, { width: w, height: h }, // options\n null, // camera\n 1, // sampling\n scene.getEngine(), // engine\n false, // reusable\n \"#define \" + (w == 1 && h == 1 ? \"LAST\" : w == 1 || h == 1 ? \"ONEBEFORELAST\" : \"MAIN\"), // defines\n type, undefined, undefined, undefined, 7);\n reduction.autoClear = false;\n reduction.forceFullscreenViewport = forceFullscreenViewport;\n reduction.onApply = ((w, h) => {\n return (effect) => {\n if (w == 1 || h == 1) {\n effect.setInt2(\"texSize\", w, h);\n }\n else {\n effect.setFloat2(\"texSize\", w, h);\n }\n };\n })(w, h);\n this._reductionSteps.push(reduction);\n index++;\n if (w == 1 && h == 1) {\n const func = (w, h, reduction) => {\n const buffer = new Float32Array(4 * w * h), minmax = { min: 0, max: 0 };\n return () => {\n scene.getEngine()._readTexturePixels(reduction.inputTexture.texture, w, h, -1, 0, buffer, false);\n minmax.min = buffer[0];\n minmax.max = buffer[1];\n this.onAfterReductionPerformed.notifyObservers(minmax);\n };\n };\n reduction.onAfterRenderObservable.add(func(w, h, reduction));\n }\n }\n }\n /**\n * Defines the refresh rate of the computation.\n * Use 0 to compute just once, 1 to compute on every frame, 2 to compute every two frames and so on...\n */\n get refreshRate() {\n return this._sourceTexture ? this._sourceTexture.refreshRate : -1;\n }\n set refreshRate(value) {\n if (this._sourceTexture) {\n this._sourceTexture.refreshRate = value;\n }\n }\n /**\n * Gets the activation status of the reducer\n */\n get activated() {\n return this._activated;\n }\n /**\n * Activates the reduction computation.\n * When activated, the observers registered in onAfterReductionPerformed are\n * called after the computation is performed\n */\n activate() {\n if (this._onAfterUnbindObserver || !this._sourceTexture) {\n return;\n }\n this._onAfterUnbindObserver = this._sourceTexture.onAfterUnbindObservable.add(() => {\n var _a, _b;\n const engine = this._camera.getScene().getEngine();\n (_a = engine._debugPushGroup) === null || _a === void 0 ? void 0 : _a.call(engine, `min max reduction`, 1);\n this._reductionSteps[0].activate(this._camera);\n this._postProcessManager.directRender(this._reductionSteps, this._reductionSteps[0].inputTexture, this._forceFullscreenViewport);\n engine.unBindFramebuffer(this._reductionSteps[0].inputTexture, false);\n (_b = engine._debugPopGroup) === null || _b === void 0 ? void 0 : _b.call(engine, 1);\n });\n this._activated = true;\n }\n /**\n * Deactivates the reduction computation.\n */\n deactivate() {\n if (!this._onAfterUnbindObserver || !this._sourceTexture) {\n return;\n }\n this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);\n this._onAfterUnbindObserver = null;\n this._activated = false;\n }\n /**\n * Disposes the min/max reducer\n * @param disposeAll true to dispose all the resources. You should always call this function with true as the parameter (or without any parameter as it is the default one). This flag is meant to be used internally.\n */\n dispose(disposeAll = true) {\n if (disposeAll) {\n this.onAfterReductionPerformed.clear();\n if (this._onContextRestoredObserver) {\n this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver);\n this._onContextRestoredObserver = null;\n }\n }\n this.deactivate();\n if (this._reductionSteps) {\n for (let i = 0; i < this._reductionSteps.length; ++i) {\n this._reductionSteps[i].dispose();\n }\n this._reductionSteps = null;\n }\n if (this._postProcessManager && disposeAll) {\n this._postProcessManager.dispose();\n }\n this._sourceTexture = null;\n }\n}\n//# sourceMappingURL=minMaxReducer.js.map","\nimport { DepthRenderer } from \"../Rendering/depthRenderer.js\";\nimport { MinMaxReducer } from \"./minMaxReducer.js\";\n/**\n * This class is a small wrapper around the MinMaxReducer class to compute the min/max values of a depth texture\n */\nexport class DepthReducer extends MinMaxReducer {\n /**\n * Gets the depth renderer used for the computation.\n * Note that the result is null if you provide your own renderer when calling setDepthRenderer.\n */\n get depthRenderer() {\n return this._depthRenderer;\n }\n /**\n * Creates a depth reducer\n * @param camera The camera used to render the depth texture\n */\n constructor(camera) {\n super(camera);\n }\n /**\n * Sets the depth renderer to use to generate the depth map\n * @param depthRenderer The depth renderer to use. If not provided, a new one will be created automatically\n * @param type The texture type of the depth map (default: TEXTURETYPE_HALF_FLOAT)\n * @param forceFullscreenViewport Forces the post processes used for the reduction to be applied without taking into account viewport (defaults to true)\n */\n setDepthRenderer(depthRenderer = null, type = 2, forceFullscreenViewport = true) {\n const scene = this._camera.getScene();\n if (this._depthRenderer) {\n delete scene._depthRenderer[this._depthRendererId];\n this._depthRenderer.dispose();\n this._depthRenderer = null;\n }\n if (depthRenderer === null) {\n if (!scene._depthRenderer) {\n scene._depthRenderer = {};\n }\n depthRenderer = this._depthRenderer = new DepthRenderer(scene, type, this._camera, false, 1);\n depthRenderer.enabled = false;\n this._depthRendererId = \"minmax\" + this._camera.id;\n scene._depthRenderer[this._depthRendererId] = depthRenderer;\n }\n super.setSourceTexture(depthRenderer.getDepthMap(), true, type, forceFullscreenViewport);\n }\n /**\n * @internal\n */\n setSourceTexture(sourceTexture, depthRedux, type = 2, forceFullscreenViewport = true) {\n super.setSourceTexture(sourceTexture, depthRedux, type, forceFullscreenViewport);\n }\n /**\n * Activates the reduction computation.\n * When activated, the observers registered in onAfterReductionPerformed are\n * called after the computation is performed\n */\n activate() {\n if (this._depthRenderer) {\n this._depthRenderer.enabled = true;\n }\n super.activate();\n }\n /**\n * Deactivates the reduction computation.\n */\n deactivate() {\n super.deactivate();\n if (this._depthRenderer) {\n this._depthRenderer.enabled = false;\n }\n }\n /**\n * Disposes the depth reducer\n * @param disposeAll true to dispose all the resources. You should always call this function with true as the parameter (or without any parameter as it is the default one). This flag is meant to be used internally.\n */\n dispose(disposeAll = true) {\n super.dispose(disposeAll);\n if (this._depthRenderer && disposeAll) {\n const scene = this._depthRenderer.getDepthMap().getScene();\n if (scene) {\n delete scene._depthRenderer[this._depthRendererId];\n }\n this._depthRenderer.dispose();\n this._depthRenderer = null;\n }\n }\n}\n//# sourceMappingURL=depthReducer.js.map","import { Matrix, Vector3 } from \"../../Maths/math.vector.js\";\nimport { RenderTargetTexture } from \"../../Materials/Textures/renderTargetTexture.js\";\n\nimport \"../../Shaders/shadowMap.fragment.js\";\nimport \"../../Shaders/shadowMap.vertex.js\";\nimport \"../../Shaders/depthBoxBlur.fragment.js\";\nimport { _WarnImport } from \"../../Misc/devTools.js\";\nimport { ShadowGenerator } from \"./shadowGenerator.js\";\nimport { BoundingInfo } from \"../../Culling/boundingInfo.js\";\nimport { DepthReducer } from \"../../Misc/depthReducer.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { EngineStore } from \"../../Engines/engineStore.js\";\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst UpDir = Vector3.Up();\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst ZeroVec = Vector3.Zero();\nconst tmpv1 = new Vector3(), tmpv2 = new Vector3(), tmpMatrix = new Matrix();\n/**\n * A CSM implementation allowing casting shadows on large scenes.\n * Documentation : https://doc.babylonjs.com/babylon101/cascadedShadows\n * Based on: https://github.com/TheRealMJP/Shadows and https://johanmedestrom.wordpress.com/2016/03/18/opengl-cascaded-shadow-maps/\n */\nexport class CascadedShadowGenerator extends ShadowGenerator {\n _validateFilter(filter) {\n if (filter === ShadowGenerator.FILTER_NONE || filter === ShadowGenerator.FILTER_PCF || filter === ShadowGenerator.FILTER_PCSS) {\n return filter;\n }\n console.error('Unsupported filter \"' + filter + '\"!');\n return ShadowGenerator.FILTER_NONE;\n }\n /**\n * Gets or set the number of cascades used by the CSM.\n */\n get numCascades() {\n return this._numCascades;\n }\n set numCascades(value) {\n value = Math.min(Math.max(value, CascadedShadowGenerator.MIN_CASCADES_COUNT), CascadedShadowGenerator.MAX_CASCADES_COUNT);\n if (value === this._numCascades) {\n return;\n }\n this._numCascades = value;\n this.recreateShadowMap();\n this._recreateSceneUBOs();\n }\n /**\n * Enables or disables the shadow casters bounding info computation.\n * If your shadow casters don't move, you can disable this feature.\n * If it is enabled, the bounding box computation is done every frame.\n */\n get freezeShadowCastersBoundingInfo() {\n return this._freezeShadowCastersBoundingInfo;\n }\n set freezeShadowCastersBoundingInfo(freeze) {\n if (this._freezeShadowCastersBoundingInfoObservable && freeze) {\n this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable);\n this._freezeShadowCastersBoundingInfoObservable = null;\n }\n if (!this._freezeShadowCastersBoundingInfoObservable && !freeze) {\n this._freezeShadowCastersBoundingInfoObservable = this._scene.onBeforeRenderObservable.add(this._computeShadowCastersBoundingInfo.bind(this));\n }\n this._freezeShadowCastersBoundingInfo = freeze;\n if (freeze) {\n this._computeShadowCastersBoundingInfo();\n }\n }\n _computeShadowCastersBoundingInfo() {\n this._scbiMin.copyFromFloats(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._scbiMax.copyFromFloats(Number.MIN_VALUE, Number.MIN_VALUE, Number.MIN_VALUE);\n if (this._shadowMap && this._shadowMap.renderList) {\n const renderList = this._shadowMap.renderList;\n for (let meshIndex = 0; meshIndex < renderList.length; meshIndex++) {\n const mesh = renderList[meshIndex];\n if (!mesh) {\n continue;\n }\n const boundingInfo = mesh.getBoundingInfo(), boundingBox = boundingInfo.boundingBox;\n this._scbiMin.minimizeInPlace(boundingBox.minimumWorld);\n this._scbiMax.maximizeInPlace(boundingBox.maximumWorld);\n }\n const meshes = this._scene.meshes;\n for (let meshIndex = 0; meshIndex < meshes.length; meshIndex++) {\n const mesh = meshes[meshIndex];\n if (!mesh || !mesh.isVisible || !mesh.isEnabled || !mesh.receiveShadows) {\n continue;\n }\n const boundingInfo = mesh.getBoundingInfo(), boundingBox = boundingInfo.boundingBox;\n this._scbiMin.minimizeInPlace(boundingBox.minimumWorld);\n this._scbiMax.maximizeInPlace(boundingBox.maximumWorld);\n }\n }\n this._shadowCastersBoundingInfo.reConstruct(this._scbiMin, this._scbiMax);\n }\n /**\n * Gets or sets the shadow casters bounding info.\n * If you provide your own shadow casters bounding info, first enable freezeShadowCastersBoundingInfo\n * so that the system won't overwrite the bounds you provide\n */\n get shadowCastersBoundingInfo() {\n return this._shadowCastersBoundingInfo;\n }\n set shadowCastersBoundingInfo(boundingInfo) {\n this._shadowCastersBoundingInfo = boundingInfo;\n }\n /**\n * Sets the minimal and maximal distances to use when computing the cascade breaks.\n *\n * The values of min / max are typically the depth zmin and zmax values of your scene, for a given frame.\n * If you don't know these values, simply leave them to their defaults and don't call this function.\n * @param min minimal distance for the breaks (default to 0.)\n * @param max maximal distance for the breaks (default to 1.)\n */\n setMinMaxDistance(min, max) {\n if (this._minDistance === min && this._maxDistance === max) {\n return;\n }\n if (min > max) {\n min = 0;\n max = 1;\n }\n if (min < 0) {\n min = 0;\n }\n if (max > 1) {\n max = 1;\n }\n this._minDistance = min;\n this._maxDistance = max;\n this._breaksAreDirty = true;\n }\n /** Gets the minimal distance used in the cascade break computation */\n get minDistance() {\n return this._minDistance;\n }\n /** Gets the maximal distance used in the cascade break computation */\n get maxDistance() {\n return this._maxDistance;\n }\n /**\n * Gets the class name of that object\n * @returns \"CascadedShadowGenerator\"\n */\n getClassName() {\n return CascadedShadowGenerator.CLASSNAME;\n }\n /**\n * Gets a cascade minimum extents\n * @param cascadeIndex index of the cascade\n * @returns the minimum cascade extents\n */\n getCascadeMinExtents(cascadeIndex) {\n return cascadeIndex >= 0 && cascadeIndex < this._numCascades ? this._cascadeMinExtents[cascadeIndex] : null;\n }\n /**\n * Gets a cascade maximum extents\n * @param cascadeIndex index of the cascade\n * @returns the maximum cascade extents\n */\n getCascadeMaxExtents(cascadeIndex) {\n return cascadeIndex >= 0 && cascadeIndex < this._numCascades ? this._cascadeMaxExtents[cascadeIndex] : null;\n }\n /**\n * Gets the shadow max z distance. It's the limit beyond which shadows are not displayed.\n * It defaults to camera.maxZ\n */\n get shadowMaxZ() {\n if (!this._getCamera()) {\n return 0;\n }\n return this._shadowMaxZ;\n }\n /**\n * Sets the shadow max z distance.\n */\n set shadowMaxZ(value) {\n const camera = this._getCamera();\n if (!camera) {\n this._shadowMaxZ = value;\n return;\n }\n if (this._shadowMaxZ === value || value < camera.minZ || value > camera.maxZ) {\n return;\n }\n this._shadowMaxZ = value;\n this._light._markMeshesAsLightDirty();\n this._breaksAreDirty = true;\n }\n /**\n * Gets or sets the debug flag.\n * When enabled, the cascades are materialized by different colors on the screen.\n */\n get debug() {\n return this._debug;\n }\n set debug(dbg) {\n this._debug = dbg;\n this._light._markMeshesAsLightDirty();\n }\n /**\n * Gets or sets the depth clamping value.\n *\n * When enabled, it improves the shadow quality because the near z plane of the light frustum don't need to be adjusted\n * to account for the shadow casters far away.\n *\n * Note that this property is incompatible with PCSS filtering, so it won't be used in that case.\n */\n get depthClamp() {\n return this._depthClamp;\n }\n set depthClamp(value) {\n this._depthClamp = value;\n }\n /**\n * Gets or sets the percentage of blending between two cascades (value between 0. and 1.).\n * It defaults to 0.1 (10% blending).\n */\n get cascadeBlendPercentage() {\n return this._cascadeBlendPercentage;\n }\n set cascadeBlendPercentage(value) {\n this._cascadeBlendPercentage = value;\n this._light._markMeshesAsLightDirty();\n }\n /**\n * Gets or set the lambda parameter.\n * This parameter is used to split the camera frustum and create the cascades.\n * It's a value between 0. and 1.: If 0, the split is a uniform split of the frustum, if 1 it is a logarithmic split.\n * For all values in-between, it's a linear combination of the uniform and logarithm split algorithm.\n */\n get lambda() {\n return this._lambda;\n }\n set lambda(value) {\n const lambda = Math.min(Math.max(value, 0), 1);\n if (this._lambda == lambda) {\n return;\n }\n this._lambda = lambda;\n this._breaksAreDirty = true;\n }\n /**\n * Gets the view matrix corresponding to a given cascade\n * @param cascadeNum cascade to retrieve the view matrix from\n * @returns the cascade view matrix\n */\n getCascadeViewMatrix(cascadeNum) {\n return cascadeNum >= 0 && cascadeNum < this._numCascades ? this._viewMatrices[cascadeNum] : null;\n }\n /**\n * Gets the projection matrix corresponding to a given cascade\n * @param cascadeNum cascade to retrieve the projection matrix from\n * @returns the cascade projection matrix\n */\n getCascadeProjectionMatrix(cascadeNum) {\n return cascadeNum >= 0 && cascadeNum < this._numCascades ? this._projectionMatrices[cascadeNum] : null;\n }\n /**\n * Gets the transformation matrix corresponding to a given cascade\n * @param cascadeNum cascade to retrieve the transformation matrix from\n * @returns the cascade transformation matrix\n */\n getCascadeTransformMatrix(cascadeNum) {\n return cascadeNum >= 0 && cascadeNum < this._numCascades ? this._transformMatrices[cascadeNum] : null;\n }\n /**\n * Sets the depth renderer to use when autoCalcDepthBounds is enabled.\n *\n * Note that if no depth renderer is set, a new one will be automatically created internally when necessary.\n *\n * You should call this function if you already have a depth renderer enabled in your scene, to avoid\n * doing multiple depth rendering each frame. If you provide your own depth renderer, make sure it stores linear depth!\n * @param depthRenderer The depth renderer to use when autoCalcDepthBounds is enabled. If you pass null or don't call this function at all, a depth renderer will be automatically created\n */\n setDepthRenderer(depthRenderer) {\n this._depthRenderer = depthRenderer;\n if (this._depthReducer) {\n this._depthReducer.setDepthRenderer(this._depthRenderer);\n }\n }\n /**\n * Gets or sets the autoCalcDepthBounds property.\n *\n * When enabled, a depth rendering pass is first performed (with an internally created depth renderer or with the one\n * you provide by calling setDepthRenderer). Then, a min/max reducing is applied on the depth map to compute the\n * minimal and maximal depth of the map and those values are used as inputs for the setMinMaxDistance() function.\n * It can greatly enhance the shadow quality, at the expense of more GPU works.\n * When using this option, you should increase the value of the lambda parameter, and even set it to 1 for best results.\n */\n get autoCalcDepthBounds() {\n return this._autoCalcDepthBounds;\n }\n set autoCalcDepthBounds(value) {\n const camera = this._getCamera();\n if (!camera) {\n return;\n }\n this._autoCalcDepthBounds = value;\n if (!value) {\n if (this._depthReducer) {\n this._depthReducer.deactivate();\n }\n this.setMinMaxDistance(0, 1);\n return;\n }\n if (!this._depthReducer) {\n this._depthReducer = new DepthReducer(camera);\n this._depthReducer.onAfterReductionPerformed.add((minmax) => {\n let min = minmax.min, max = minmax.max;\n if (min >= max) {\n min = 0;\n max = 1;\n }\n if (min != this._minDistance || max != this._maxDistance) {\n this.setMinMaxDistance(min, max);\n }\n });\n this._depthReducer.setDepthRenderer(this._depthRenderer);\n }\n this._depthReducer.activate();\n }\n /**\n * Defines the refresh rate of the min/max computation used when autoCalcDepthBounds is set to true\n * Use 0 to compute just once, 1 to compute on every frame, 2 to compute every two frames and so on...\n * Note that if you provided your own depth renderer through a call to setDepthRenderer, you are responsible\n * for setting the refresh rate on the renderer yourself!\n */\n get autoCalcDepthBoundsRefreshRate() {\n var _a, _b, _c;\n return (_c = (_b = (_a = this._depthReducer) === null || _a === void 0 ? void 0 : _a.depthRenderer) === null || _b === void 0 ? void 0 : _b.getDepthMap().refreshRate) !== null && _c !== void 0 ? _c : -1;\n }\n set autoCalcDepthBoundsRefreshRate(value) {\n var _a;\n if ((_a = this._depthReducer) === null || _a === void 0 ? void 0 : _a.depthRenderer) {\n this._depthReducer.depthRenderer.getDepthMap().refreshRate = value;\n }\n }\n /**\n * Create the cascade breaks according to the lambda, shadowMaxZ and min/max distance properties, as well as the camera near and far planes.\n * This function is automatically called when updating lambda, shadowMaxZ and min/max distances, however you should call it yourself if\n * you change the camera near/far planes!\n */\n splitFrustum() {\n this._breaksAreDirty = true;\n }\n _splitFrustum() {\n const camera = this._getCamera();\n if (!camera) {\n return;\n }\n const near = camera.minZ, far = camera.maxZ || this._shadowMaxZ, // account for infinite far plane (ie. maxZ = 0)\n cameraRange = far - near, minDistance = this._minDistance, maxDistance = this._shadowMaxZ < far && this._shadowMaxZ >= near ? Math.min((this._shadowMaxZ - near) / (far - near), this._maxDistance) : this._maxDistance;\n const minZ = near + minDistance * cameraRange, maxZ = near + maxDistance * cameraRange;\n const range = maxZ - minZ, ratio = maxZ / minZ;\n for (let cascadeIndex = 0; cascadeIndex < this._cascades.length; ++cascadeIndex) {\n const p = (cascadeIndex + 1) / this._numCascades, log = minZ * ratio ** p, uniform = minZ + range * p;\n const d = this._lambda * (log - uniform) + uniform;\n this._cascades[cascadeIndex].prevBreakDistance = cascadeIndex === 0 ? minDistance : this._cascades[cascadeIndex - 1].breakDistance;\n this._cascades[cascadeIndex].breakDistance = (d - near) / cameraRange;\n this._viewSpaceFrustumsZ[cascadeIndex] = d;\n this._frustumLengths[cascadeIndex] = (this._cascades[cascadeIndex].breakDistance - this._cascades[cascadeIndex].prevBreakDistance) * cameraRange;\n }\n this._breaksAreDirty = false;\n }\n _computeMatrices() {\n const scene = this._scene;\n const camera = this._getCamera();\n if (!camera) {\n return;\n }\n Vector3.NormalizeToRef(this._light.getShadowDirection(0), this._lightDirection);\n if (Math.abs(Vector3.Dot(this._lightDirection, Vector3.Up())) === 1.0) {\n this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light\n }\n this._cachedDirection.copyFrom(this._lightDirection);\n const useReverseDepthBuffer = scene.getEngine().useReverseDepthBuffer;\n for (let cascadeIndex = 0; cascadeIndex < this._numCascades; ++cascadeIndex) {\n this._computeFrustumInWorldSpace(cascadeIndex);\n this._computeCascadeFrustum(cascadeIndex);\n this._cascadeMaxExtents[cascadeIndex].subtractToRef(this._cascadeMinExtents[cascadeIndex], tmpv1); // tmpv1 = cascadeExtents\n // Get position of the shadow camera\n this._frustumCenter[cascadeIndex].addToRef(this._lightDirection.scale(this._cascadeMinExtents[cascadeIndex].z), this._shadowCameraPos[cascadeIndex]);\n // Come up with a new orthographic camera for the shadow caster\n Matrix.LookAtLHToRef(this._shadowCameraPos[cascadeIndex], this._frustumCenter[cascadeIndex], UpDir, this._viewMatrices[cascadeIndex]);\n let minZ = 0, maxZ = tmpv1.z;\n // Try to tighten minZ and maxZ based on the bounding box of the shadow casters\n const boundingInfo = this._shadowCastersBoundingInfo;\n boundingInfo.update(this._viewMatrices[cascadeIndex]);\n maxZ = Math.min(maxZ, boundingInfo.boundingBox.maximumWorld.z);\n if (!this._depthClamp || this.filter === ShadowGenerator.FILTER_PCSS) {\n // If we don't use depth clamping, we must set minZ so that all shadow casters are in the light frustum\n minZ = Math.min(minZ, boundingInfo.boundingBox.minimumWorld.z);\n }\n else {\n // If using depth clamping, we can adjust minZ to reduce the [minZ, maxZ] range (and get some additional precision in the shadow map)\n minZ = Math.max(minZ, boundingInfo.boundingBox.minimumWorld.z);\n }\n Matrix.OrthoOffCenterLHToRef(this._cascadeMinExtents[cascadeIndex].x, this._cascadeMaxExtents[cascadeIndex].x, this._cascadeMinExtents[cascadeIndex].y, this._cascadeMaxExtents[cascadeIndex].y, useReverseDepthBuffer ? maxZ : minZ, useReverseDepthBuffer ? minZ : maxZ, this._projectionMatrices[cascadeIndex], scene.getEngine().isNDCHalfZRange);\n this._cascadeMinExtents[cascadeIndex].z = minZ;\n this._cascadeMaxExtents[cascadeIndex].z = maxZ;\n this._viewMatrices[cascadeIndex].multiplyToRef(this._projectionMatrices[cascadeIndex], this._transformMatrices[cascadeIndex]);\n // Create the rounding matrix, by projecting the world-space origin and determining\n // the fractional offset in texel space\n Vector3.TransformCoordinatesToRef(ZeroVec, this._transformMatrices[cascadeIndex], tmpv1); // tmpv1 = shadowOrigin\n tmpv1.scaleInPlace(this._mapSize / 2);\n tmpv2.copyFromFloats(Math.round(tmpv1.x), Math.round(tmpv1.y), Math.round(tmpv1.z)); // tmpv2 = roundedOrigin\n tmpv2.subtractInPlace(tmpv1).scaleInPlace(2 / this._mapSize); // tmpv2 = roundOffset\n Matrix.TranslationToRef(tmpv2.x, tmpv2.y, 0.0, tmpMatrix);\n this._projectionMatrices[cascadeIndex].multiplyToRef(tmpMatrix, this._projectionMatrices[cascadeIndex]);\n this._viewMatrices[cascadeIndex].multiplyToRef(this._projectionMatrices[cascadeIndex], this._transformMatrices[cascadeIndex]);\n this._transformMatrices[cascadeIndex].copyToArray(this._transformMatricesAsArray, cascadeIndex * 16);\n }\n }\n // Get the 8 points of the view frustum in world space\n _computeFrustumInWorldSpace(cascadeIndex) {\n const camera = this._getCamera();\n if (!camera) {\n return;\n }\n const prevSplitDist = this._cascades[cascadeIndex].prevBreakDistance, splitDist = this._cascades[cascadeIndex].breakDistance;\n const isNDCHalfZRange = this._scene.getEngine().isNDCHalfZRange;\n camera.getViewMatrix(); // make sure the transformation matrix we get when calling 'getTransformationMatrix()' is calculated with an up to date view matrix\n const cameraInfiniteFarPlane = camera.maxZ === 0;\n const saveCameraMaxZ = camera.maxZ;\n if (cameraInfiniteFarPlane) {\n camera.maxZ = this._shadowMaxZ;\n camera.getProjectionMatrix(true);\n }\n const invViewProj = Matrix.Invert(camera.getTransformationMatrix());\n if (cameraInfiniteFarPlane) {\n camera.maxZ = saveCameraMaxZ;\n camera.getProjectionMatrix(true);\n }\n const cornerIndexOffset = this._scene.getEngine().useReverseDepthBuffer ? 4 : 0;\n for (let cornerIndex = 0; cornerIndex < CascadedShadowGenerator._FrustumCornersNDCSpace.length; ++cornerIndex) {\n tmpv1.copyFrom(CascadedShadowGenerator._FrustumCornersNDCSpace[(cornerIndex + cornerIndexOffset) % CascadedShadowGenerator._FrustumCornersNDCSpace.length]);\n if (isNDCHalfZRange && tmpv1.z === -1) {\n tmpv1.z = 0;\n }\n Vector3.TransformCoordinatesToRef(tmpv1, invViewProj, this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]);\n }\n // Get the corners of the current cascade slice of the view frustum\n for (let cornerIndex = 0; cornerIndex < CascadedShadowGenerator._FrustumCornersNDCSpace.length / 2; ++cornerIndex) {\n tmpv1.copyFrom(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex + 4]).subtractInPlace(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]);\n tmpv2.copyFrom(tmpv1).scaleInPlace(prevSplitDist); // near corner ray\n tmpv1.scaleInPlace(splitDist); // far corner ray\n tmpv1.addInPlace(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]);\n this._frustumCornersWorldSpace[cascadeIndex][cornerIndex + 4].copyFrom(tmpv1);\n this._frustumCornersWorldSpace[cascadeIndex][cornerIndex].addInPlace(tmpv2);\n }\n }\n _computeCascadeFrustum(cascadeIndex) {\n this._cascadeMinExtents[cascadeIndex].copyFromFloats(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._cascadeMaxExtents[cascadeIndex].copyFromFloats(Number.MIN_VALUE, Number.MIN_VALUE, Number.MIN_VALUE);\n this._frustumCenter[cascadeIndex].copyFromFloats(0, 0, 0);\n const camera = this._getCamera();\n if (!camera) {\n return;\n }\n // Calculate the centroid of the view frustum slice\n for (let cornerIndex = 0; cornerIndex < this._frustumCornersWorldSpace[cascadeIndex].length; ++cornerIndex) {\n this._frustumCenter[cascadeIndex].addInPlace(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]);\n }\n this._frustumCenter[cascadeIndex].scaleInPlace(1 / this._frustumCornersWorldSpace[cascadeIndex].length);\n if (this.stabilizeCascades) {\n // Calculate the radius of a bounding sphere surrounding the frustum corners\n let sphereRadius = 0;\n for (let cornerIndex = 0; cornerIndex < this._frustumCornersWorldSpace[cascadeIndex].length; ++cornerIndex) {\n const dist = this._frustumCornersWorldSpace[cascadeIndex][cornerIndex].subtractToRef(this._frustumCenter[cascadeIndex], tmpv1).length();\n sphereRadius = Math.max(sphereRadius, dist);\n }\n sphereRadius = Math.ceil(sphereRadius * 16) / 16;\n this._cascadeMaxExtents[cascadeIndex].copyFromFloats(sphereRadius, sphereRadius, sphereRadius);\n this._cascadeMinExtents[cascadeIndex].copyFromFloats(-sphereRadius, -sphereRadius, -sphereRadius);\n }\n else {\n // Create a temporary view matrix for the light\n const lightCameraPos = this._frustumCenter[cascadeIndex];\n this._frustumCenter[cascadeIndex].addToRef(this._lightDirection, tmpv1); // tmpv1 = look at\n Matrix.LookAtLHToRef(lightCameraPos, tmpv1, UpDir, tmpMatrix); // matrix = lightView\n // Calculate an AABB around the frustum corners\n for (let cornerIndex = 0; cornerIndex < this._frustumCornersWorldSpace[cascadeIndex].length; ++cornerIndex) {\n Vector3.TransformCoordinatesToRef(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex], tmpMatrix, tmpv1);\n this._cascadeMinExtents[cascadeIndex].minimizeInPlace(tmpv1);\n this._cascadeMaxExtents[cascadeIndex].maximizeInPlace(tmpv1);\n }\n }\n }\n _recreateSceneUBOs() {\n this._disposeSceneUBOs();\n if (this._sceneUBOs) {\n for (let i = 0; i < this._numCascades; ++i) {\n this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for CSM Shadow Generator (light \"${this._light.name}\" cascade #${i})`));\n }\n }\n }\n /**\n * Support test.\n */\n static get IsSupported() {\n const engine = EngineStore.LastCreatedEngine;\n if (!engine) {\n return false;\n }\n return engine._features.supportCSM;\n }\n /**\n * Creates a Cascaded Shadow Generator object.\n * A ShadowGenerator is the required tool to use the shadows.\n * Each directional light casting shadows needs to use its own ShadowGenerator.\n * Documentation : https://doc.babylonjs.com/babylon101/cascadedShadows\n * @param mapSize The size of the texture what stores the shadows. Example : 1024.\n * @param light The directional light object generating the shadows.\n * @param usefulFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.\n * @param camera Camera associated with this shadow generator (default: null). If null, takes the scene active camera at the time we need to access it\n */\n constructor(mapSize, light, usefulFloatFirst, camera) {\n if (!CascadedShadowGenerator.IsSupported) {\n Logger.Error(\"CascadedShadowMap is not supported by the current engine.\");\n return;\n }\n super(mapSize, light, usefulFloatFirst, camera);\n this.usePercentageCloserFiltering = true;\n }\n _initializeGenerator() {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v;\n this.penumbraDarkness = (_a = this.penumbraDarkness) !== null && _a !== void 0 ? _a : 1.0;\n this._numCascades = (_b = this._numCascades) !== null && _b !== void 0 ? _b : CascadedShadowGenerator.DEFAULT_CASCADES_COUNT;\n this.stabilizeCascades = (_c = this.stabilizeCascades) !== null && _c !== void 0 ? _c : false;\n this._freezeShadowCastersBoundingInfoObservable = (_d = this._freezeShadowCastersBoundingInfoObservable) !== null && _d !== void 0 ? _d : null;\n this.freezeShadowCastersBoundingInfo = (_e = this.freezeShadowCastersBoundingInfo) !== null && _e !== void 0 ? _e : false;\n this._scbiMin = (_f = this._scbiMin) !== null && _f !== void 0 ? _f : new Vector3(0, 0, 0);\n this._scbiMax = (_g = this._scbiMax) !== null && _g !== void 0 ? _g : new Vector3(0, 0, 0);\n this._shadowCastersBoundingInfo = (_h = this._shadowCastersBoundingInfo) !== null && _h !== void 0 ? _h : new BoundingInfo(new Vector3(0, 0, 0), new Vector3(0, 0, 0));\n this._breaksAreDirty = (_j = this._breaksAreDirty) !== null && _j !== void 0 ? _j : true;\n this._minDistance = (_k = this._minDistance) !== null && _k !== void 0 ? _k : 0;\n this._maxDistance = (_l = this._maxDistance) !== null && _l !== void 0 ? _l : 1;\n this._currentLayer = (_m = this._currentLayer) !== null && _m !== void 0 ? _m : 0;\n this._shadowMaxZ = (_q = (_o = this._shadowMaxZ) !== null && _o !== void 0 ? _o : (_p = this._getCamera()) === null || _p === void 0 ? void 0 : _p.maxZ) !== null && _q !== void 0 ? _q : 10000;\n this._debug = (_r = this._debug) !== null && _r !== void 0 ? _r : false;\n this._depthClamp = (_s = this._depthClamp) !== null && _s !== void 0 ? _s : true;\n this._cascadeBlendPercentage = (_t = this._cascadeBlendPercentage) !== null && _t !== void 0 ? _t : 0.1;\n this._lambda = (_u = this._lambda) !== null && _u !== void 0 ? _u : 0.5;\n this._autoCalcDepthBounds = (_v = this._autoCalcDepthBounds) !== null && _v !== void 0 ? _v : false;\n this._recreateSceneUBOs();\n super._initializeGenerator();\n }\n _createTargetRenderTexture() {\n const engine = this._scene.getEngine();\n const size = { width: this._mapSize, height: this._mapSize, layers: this.numCascades };\n this._shadowMap = new RenderTargetTexture(this._light.name + \"_CSMShadowMap\", size, this._scene, false, true, this._textureType, false, undefined, false, false, undefined /*, 6*/);\n this._shadowMap.createDepthStencilTexture(engine.useReverseDepthBuffer ? 516 : 513, true);\n this._shadowMap.noPrePassRenderer = true;\n }\n _initializeShadowMap() {\n super._initializeShadowMap();\n if (this._shadowMap === null) {\n return;\n }\n this._transformMatricesAsArray = new Float32Array(this._numCascades * 16);\n this._viewSpaceFrustumsZ = new Array(this._numCascades);\n this._frustumLengths = new Array(this._numCascades);\n this._lightSizeUVCorrection = new Array(this._numCascades * 2);\n this._depthCorrection = new Array(this._numCascades);\n this._cascades = [];\n this._viewMatrices = [];\n this._projectionMatrices = [];\n this._transformMatrices = [];\n this._cascadeMinExtents = [];\n this._cascadeMaxExtents = [];\n this._frustumCenter = [];\n this._shadowCameraPos = [];\n this._frustumCornersWorldSpace = [];\n for (let cascadeIndex = 0; cascadeIndex < this._numCascades; ++cascadeIndex) {\n this._cascades[cascadeIndex] = {\n prevBreakDistance: 0,\n breakDistance: 0,\n };\n this._viewMatrices[cascadeIndex] = Matrix.Zero();\n this._projectionMatrices[cascadeIndex] = Matrix.Zero();\n this._transformMatrices[cascadeIndex] = Matrix.Zero();\n this._cascadeMinExtents[cascadeIndex] = new Vector3();\n this._cascadeMaxExtents[cascadeIndex] = new Vector3();\n this._frustumCenter[cascadeIndex] = new Vector3();\n this._shadowCameraPos[cascadeIndex] = new Vector3();\n this._frustumCornersWorldSpace[cascadeIndex] = new Array(CascadedShadowGenerator._FrustumCornersNDCSpace.length);\n for (let i = 0; i < CascadedShadowGenerator._FrustumCornersNDCSpace.length; ++i) {\n this._frustumCornersWorldSpace[cascadeIndex][i] = new Vector3();\n }\n }\n const engine = this._scene.getEngine();\n this._shadowMap.onBeforeBindObservable.clear();\n this._shadowMap.onBeforeRenderObservable.clear();\n this._shadowMap.onBeforeRenderObservable.add((layer) => {\n if (this._sceneUBOs) {\n this._scene.setSceneUniformBuffer(this._sceneUBOs[layer]);\n }\n this._currentLayer = layer;\n if (this._filter === ShadowGenerator.FILTER_PCF) {\n engine.setColorWrite(false);\n }\n this._scene.setTransformMatrix(this.getCascadeViewMatrix(layer), this.getCascadeProjectionMatrix(layer));\n if (this._useUBO) {\n this._scene.getSceneUniformBuffer().unbindEffect();\n this._scene.finalizeSceneUbo();\n }\n });\n this._shadowMap.onBeforeBindObservable.add(() => {\n var _a;\n this._currentSceneUBO = this._scene.getSceneUniformBuffer();\n (_a = engine._debugPushGroup) === null || _a === void 0 ? void 0 : _a.call(engine, `cascaded shadow map generation for pass id ${engine.currentRenderPassId}`, 1);\n if (this._breaksAreDirty) {\n this._splitFrustum();\n }\n this._computeMatrices();\n });\n this._splitFrustum();\n }\n _bindCustomEffectForRenderSubMeshForShadowMap(subMesh, effect) {\n effect.setMatrix(\"viewProjection\", this.getCascadeTransformMatrix(this._currentLayer));\n }\n _isReadyCustomDefines(defines) {\n defines.push(\"#define SM_DEPTHCLAMP \" + (this._depthClamp && this._filter !== ShadowGenerator.FILTER_PCSS ? \"1\" : \"0\"));\n }\n /**\n * Prepare all the defines in a material relying on a shadow map at the specified light index.\n * @param defines Defines of the material we want to update\n * @param lightIndex Index of the light in the enabled light list of the material\n */\n prepareDefines(defines, lightIndex) {\n super.prepareDefines(defines, lightIndex);\n const scene = this._scene;\n const light = this._light;\n if (!scene.shadowsEnabled || !light.shadowEnabled) {\n return;\n }\n defines[\"SHADOWCSM\" + lightIndex] = true;\n defines[\"SHADOWCSMDEBUG\" + lightIndex] = this.debug;\n defines[\"SHADOWCSMNUM_CASCADES\" + lightIndex] = this.numCascades;\n defines[\"SHADOWCSM_RIGHTHANDED\" + lightIndex] = scene.useRightHandedSystem;\n const camera = this._getCamera();\n if (camera && this._shadowMaxZ <= (camera.maxZ || this._shadowMaxZ)) {\n defines[\"SHADOWCSMUSESHADOWMAXZ\" + lightIndex] = true;\n }\n if (this.cascadeBlendPercentage === 0) {\n defines[\"SHADOWCSMNOBLEND\" + lightIndex] = true;\n }\n }\n /**\n * Binds the shadow related information inside of an effect (information like near, far, darkness...\n * defined in the generator but impacting the effect).\n * @param lightIndex Index of the light in the enabled light list of the material owning the effect\n * @param effect The effect we are binfing the information for\n */\n bindShadowLight(lightIndex, effect) {\n const light = this._light;\n const scene = this._scene;\n if (!scene.shadowsEnabled || !light.shadowEnabled) {\n return;\n }\n const camera = this._getCamera();\n if (!camera) {\n return;\n }\n const shadowMap = this.getShadowMap();\n if (!shadowMap) {\n return;\n }\n const width = shadowMap.getSize().width;\n effect.setMatrices(\"lightMatrix\" + lightIndex, this._transformMatricesAsArray);\n effect.setArray(\"viewFrustumZ\" + lightIndex, this._viewSpaceFrustumsZ);\n effect.setFloat(\"cascadeBlendFactor\" + lightIndex, this.cascadeBlendPercentage === 0 ? 10000 : 1 / this.cascadeBlendPercentage);\n effect.setArray(\"frustumLengths\" + lightIndex, this._frustumLengths);\n // Only PCF uses depth stencil texture.\n if (this._filter === ShadowGenerator.FILTER_PCF) {\n effect.setDepthStencilTexture(\"shadowSampler\" + lightIndex, shadowMap);\n light._uniformBuffer.updateFloat4(\"shadowsInfo\", this.getDarkness(), width, 1 / width, this.frustumEdgeFalloff, lightIndex);\n }\n else if (this._filter === ShadowGenerator.FILTER_PCSS) {\n for (let cascadeIndex = 0; cascadeIndex < this._numCascades; ++cascadeIndex) {\n this._lightSizeUVCorrection[cascadeIndex * 2 + 0] =\n cascadeIndex === 0\n ? 1\n : (this._cascadeMaxExtents[0].x - this._cascadeMinExtents[0].x) / (this._cascadeMaxExtents[cascadeIndex].x - this._cascadeMinExtents[cascadeIndex].x); // x correction\n this._lightSizeUVCorrection[cascadeIndex * 2 + 1] =\n cascadeIndex === 0\n ? 1\n : (this._cascadeMaxExtents[0].y - this._cascadeMinExtents[0].y) / (this._cascadeMaxExtents[cascadeIndex].y - this._cascadeMinExtents[cascadeIndex].y); // y correction\n this._depthCorrection[cascadeIndex] =\n cascadeIndex === 0\n ? 1\n : (this._cascadeMaxExtents[cascadeIndex].z - this._cascadeMinExtents[cascadeIndex].z) / (this._cascadeMaxExtents[0].z - this._cascadeMinExtents[0].z);\n }\n effect.setDepthStencilTexture(\"shadowSampler\" + lightIndex, shadowMap);\n effect.setTexture(\"depthSampler\" + lightIndex, shadowMap);\n effect.setArray2(\"lightSizeUVCorrection\" + lightIndex, this._lightSizeUVCorrection);\n effect.setArray(\"depthCorrection\" + lightIndex, this._depthCorrection);\n effect.setFloat(\"penumbraDarkness\" + lightIndex, this.penumbraDarkness);\n light._uniformBuffer.updateFloat4(\"shadowsInfo\", this.getDarkness(), 1 / width, this._contactHardeningLightSizeUVRatio * width, this.frustumEdgeFalloff, lightIndex);\n }\n else {\n effect.setTexture(\"shadowSampler\" + lightIndex, shadowMap);\n light._uniformBuffer.updateFloat4(\"shadowsInfo\", this.getDarkness(), width, 1 / width, this.frustumEdgeFalloff, lightIndex);\n }\n light._uniformBuffer.updateFloat2(\"depthValues\", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);\n }\n /**\n * Gets the transformation matrix of the first cascade used to project the meshes into the map from the light point of view.\n * (eq to view projection * shadow projection matrices)\n * @returns The transform matrix used to create the shadow map\n */\n getTransformMatrix() {\n return this.getCascadeTransformMatrix(0);\n }\n /**\n * Disposes the ShadowGenerator.\n * Returns nothing.\n */\n dispose() {\n super.dispose();\n if (this._freezeShadowCastersBoundingInfoObservable) {\n this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable);\n this._freezeShadowCastersBoundingInfoObservable = null;\n }\n if (this._depthReducer) {\n this._depthReducer.dispose();\n this._depthReducer = null;\n }\n }\n /**\n * Serializes the shadow generator setup to a json object.\n * @returns The serialized JSON object\n */\n serialize() {\n const serializationObject = super.serialize();\n const shadowMap = this.getShadowMap();\n if (!shadowMap) {\n return serializationObject;\n }\n serializationObject.numCascades = this._numCascades;\n serializationObject.debug = this._debug;\n serializationObject.stabilizeCascades = this.stabilizeCascades;\n serializationObject.lambda = this._lambda;\n serializationObject.cascadeBlendPercentage = this.cascadeBlendPercentage;\n serializationObject.depthClamp = this._depthClamp;\n serializationObject.autoCalcDepthBounds = this.autoCalcDepthBounds;\n serializationObject.shadowMaxZ = this._shadowMaxZ;\n serializationObject.penumbraDarkness = this.penumbraDarkness;\n serializationObject.freezeShadowCastersBoundingInfo = this._freezeShadowCastersBoundingInfo;\n serializationObject.minDistance = this.minDistance;\n serializationObject.maxDistance = this.maxDistance;\n serializationObject.renderList = [];\n if (shadowMap.renderList) {\n for (let meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {\n const mesh = shadowMap.renderList[meshIndex];\n serializationObject.renderList.push(mesh.id);\n }\n }\n return serializationObject;\n }\n /**\n * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.\n * @param parsedShadowGenerator The JSON object to parse\n * @param scene The scene to create the shadow map for\n * @returns The parsed shadow generator\n */\n static Parse(parsedShadowGenerator, scene) {\n const shadowGenerator = ShadowGenerator.Parse(parsedShadowGenerator, scene, (mapSize, light, camera) => new CascadedShadowGenerator(mapSize, light, undefined, camera));\n if (parsedShadowGenerator.numCascades !== undefined) {\n shadowGenerator.numCascades = parsedShadowGenerator.numCascades;\n }\n if (parsedShadowGenerator.debug !== undefined) {\n shadowGenerator.debug = parsedShadowGenerator.debug;\n }\n if (parsedShadowGenerator.stabilizeCascades !== undefined) {\n shadowGenerator.stabilizeCascades = parsedShadowGenerator.stabilizeCascades;\n }\n if (parsedShadowGenerator.lambda !== undefined) {\n shadowGenerator.lambda = parsedShadowGenerator.lambda;\n }\n if (parsedShadowGenerator.cascadeBlendPercentage !== undefined) {\n shadowGenerator.cascadeBlendPercentage = parsedShadowGenerator.cascadeBlendPercentage;\n }\n if (parsedShadowGenerator.depthClamp !== undefined) {\n shadowGenerator.depthClamp = parsedShadowGenerator.depthClamp;\n }\n if (parsedShadowGenerator.autoCalcDepthBounds !== undefined) {\n shadowGenerator.autoCalcDepthBounds = parsedShadowGenerator.autoCalcDepthBounds;\n }\n if (parsedShadowGenerator.shadowMaxZ !== undefined) {\n shadowGenerator.shadowMaxZ = parsedShadowGenerator.shadowMaxZ;\n }\n if (parsedShadowGenerator.penumbraDarkness !== undefined) {\n shadowGenerator.penumbraDarkness = parsedShadowGenerator.penumbraDarkness;\n }\n if (parsedShadowGenerator.freezeShadowCastersBoundingInfo !== undefined) {\n shadowGenerator.freezeShadowCastersBoundingInfo = parsedShadowGenerator.freezeShadowCastersBoundingInfo;\n }\n if (parsedShadowGenerator.minDistance !== undefined && parsedShadowGenerator.maxDistance !== undefined) {\n shadowGenerator.setMinMaxDistance(parsedShadowGenerator.minDistance, parsedShadowGenerator.maxDistance);\n }\n return shadowGenerator;\n }\n}\nCascadedShadowGenerator._FrustumCornersNDCSpace = [\n new Vector3(-1.0, +1.0, -1.0),\n new Vector3(+1.0, +1.0, -1.0),\n new Vector3(+1.0, -1.0, -1.0),\n new Vector3(-1.0, -1.0, -1.0),\n new Vector3(-1.0, +1.0, +1.0),\n new Vector3(+1.0, +1.0, +1.0),\n new Vector3(+1.0, -1.0, +1.0),\n new Vector3(-1.0, -1.0, +1.0),\n];\n/**\n * Name of the CSM class\n */\nCascadedShadowGenerator.CLASSNAME = \"CascadedShadowGenerator\";\n/**\n * Defines the default number of cascades used by the CSM.\n */\nCascadedShadowGenerator.DEFAULT_CASCADES_COUNT = 4;\n/**\n * Defines the minimum number of cascades used by the CSM.\n */\nCascadedShadowGenerator.MIN_CASCADES_COUNT = 2;\n/**\n * Defines the maximum number of cascades used by the CSM.\n */\nCascadedShadowGenerator.MAX_CASCADES_COUNT = 4;\n/**\n * @internal\n */\nCascadedShadowGenerator._SceneComponentInitialization = (_) => {\n throw _WarnImport(\"ShadowGeneratorSceneComponent\");\n};\n//# sourceMappingURL=cascadedShadowGenerator.js.map","import { ShadowGenerator } from \"./shadowGenerator.js\";\nimport { CascadedShadowGenerator } from \"./cascadedShadowGenerator.js\";\nimport { SceneComponentConstants } from \"../../sceneComponent.js\";\nimport { AbstractScene } from \"../../abstractScene.js\";\n// Adds the parser to the scene parsers.\nAbstractScene.AddParser(SceneComponentConstants.NAME_SHADOWGENERATOR, (parsedData, scene) => {\n // Shadows\n if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {\n for (let index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {\n const parsedShadowGenerator = parsedData.shadowGenerators[index];\n if (parsedShadowGenerator.className === CascadedShadowGenerator.CLASSNAME) {\n CascadedShadowGenerator.Parse(parsedShadowGenerator, scene);\n }\n else {\n ShadowGenerator.Parse(parsedShadowGenerator, scene);\n }\n // SG would be available on their associated lights\n }\n }\n});\n/**\n * Defines the shadow generator component responsible to manage any shadow generators\n * in a given scene.\n */\nexport class ShadowGeneratorSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpful to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_SHADOWGENERATOR;\n this.scene = scene;\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene._gatherRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n // Nothing To Do Here.\n }\n /**\n * Serializes the component data to the specified json object\n * @param serializationObject The object to serialize to\n */\n serialize(serializationObject) {\n // Shadows\n serializationObject.shadowGenerators = [];\n const lights = this.scene.lights;\n for (const light of lights) {\n const shadowGenerators = light.getShadowGenerators();\n if (shadowGenerators) {\n const iterator = shadowGenerators.values();\n for (let key = iterator.next(); key.done !== true; key = iterator.next()) {\n const shadowGenerator = key.value;\n serializationObject.shadowGenerators.push(shadowGenerator.serialize());\n }\n }\n }\n }\n /**\n * Adds all the elements from the container to the scene\n * @param container the container holding the elements\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n addFromContainer(container) {\n // Nothing To Do Here. (directly attached to a light)\n }\n /**\n * Removes all the elements in the container from the scene\n * @param container contains the elements to remove\n * @param dispose if the removed element should be disposed (default: false)\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n removeFromContainer(container, dispose) {\n // Nothing To Do Here. (directly attached to a light)\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n dispose() {\n // Nothing To Do Here.\n }\n _gatherRenderTargets(renderTargets) {\n // Shadows\n const scene = this.scene;\n if (this.scene.shadowsEnabled) {\n for (let lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {\n const light = scene.lights[lightIndex];\n const shadowGenerators = light.getShadowGenerators();\n if (light.isEnabled() && light.shadowEnabled && shadowGenerators) {\n const iterator = shadowGenerators.values();\n for (let key = iterator.next(); key.done !== true; key = iterator.next()) {\n const shadowGenerator = key.value;\n const shadowMap = shadowGenerator.getShadowMap();\n if (scene.textures.indexOf(shadowMap) !== -1) {\n renderTargets.push(shadowMap);\n }\n }\n }\n }\n }\n }\n}\nShadowGenerator._SceneComponentInitialization = (scene) => {\n let component = scene._getComponent(SceneComponentConstants.NAME_SHADOWGENERATOR);\n if (!component) {\n component = new ShadowGeneratorSceneComponent(scene);\n scene._addComponent(component);\n }\n};\n//# sourceMappingURL=shadowGeneratorSceneComponent.js.map","export * from \"./shadowGenerator.js\";\nexport * from \"./cascadedShadowGenerator.js\";\nexport * from \"./shadowGeneratorSceneComponent.js\";\n//# sourceMappingURL=index.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize } from \"../Misc/decorators.js\";\nimport { Matrix, Vector3 } from \"../Maths/math.vector.js\";\nimport { Node } from \"../node.js\";\nimport { Light } from \"./light.js\";\nimport { ShadowLight } from \"./shadowLight.js\";\nNode.AddNodeConstructor(\"Light_Type_0\", (name, scene) => {\n return () => new PointLight(name, Vector3.Zero(), scene);\n});\n/**\n * A point light is a light defined by an unique point in world space.\n * The light is emitted in every direction from this point.\n * A good example of a point light is a standard light bulb.\n * Documentation: https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction\n */\nexport class PointLight extends ShadowLight {\n /**\n * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback\n * This specifies what angle the shadow will use to be created.\n *\n * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.\n */\n get shadowAngle() {\n return this._shadowAngle;\n }\n /**\n * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback\n * This specifies what angle the shadow will use to be created.\n *\n * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.\n */\n set shadowAngle(value) {\n this._shadowAngle = value;\n this.forceProjectionMatrixCompute();\n }\n /**\n * Gets the direction if it has been set.\n * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback\n */\n get direction() {\n return this._direction;\n }\n /**\n * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback\n */\n set direction(value) {\n const previousNeedCube = this.needCube();\n this._direction = value;\n if (this.needCube() !== previousNeedCube && this._shadowGenerators) {\n const iterator = this._shadowGenerators.values();\n for (let key = iterator.next(); key.done !== true; key = iterator.next()) {\n const shadowGenerator = key.value;\n shadowGenerator.recreateShadowMap();\n }\n }\n }\n /**\n * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.\n * A PointLight emits the light in every direction.\n * It can cast shadows.\n * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :\n * ```javascript\n * var pointLight = new PointLight(\"pl\", camera.position, scene);\n * ```\n * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction\n * @param name The light friendly name\n * @param position The position of the point light in the scene\n * @param scene The scene the lights belongs to\n */\n constructor(name, position, scene) {\n super(name, scene);\n this._shadowAngle = Math.PI / 2;\n this.position = position;\n }\n /**\n * Returns the string \"PointLight\"\n * @returns the class name\n */\n getClassName() {\n return \"PointLight\";\n }\n /**\n * Returns the integer 0.\n * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x\n */\n getTypeID() {\n return Light.LIGHTTYPEID_POINTLIGHT;\n }\n /**\n * Specifies whether or not the shadowmap should be a cube texture.\n * @returns true if the shadowmap needs to be a cube texture.\n */\n needCube() {\n return !this.direction;\n }\n /**\n * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).\n * @param faceIndex The index of the face we are computed the direction to generate shadow\n * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true\n */\n getShadowDirection(faceIndex) {\n if (this.direction) {\n return super.getShadowDirection(faceIndex);\n }\n else {\n switch (faceIndex) {\n case 0:\n return new Vector3(1.0, 0.0, 0.0);\n case 1:\n return new Vector3(-1.0, 0.0, 0.0);\n case 2:\n return new Vector3(0.0, -1.0, 0.0);\n case 3:\n return new Vector3(0.0, 1.0, 0.0);\n case 4:\n return new Vector3(0.0, 0.0, 1.0);\n case 5:\n return new Vector3(0.0, 0.0, -1.0);\n }\n }\n return Vector3.Zero();\n }\n /**\n * Sets the passed matrix \"matrix\" as a left-handed perspective projection matrix with the following settings :\n * - fov = PI / 2\n * - aspect ratio : 1.0\n * - z-near and far equal to the active camera minZ and maxZ.\n * Returns the PointLight.\n * @param matrix\n * @param viewMatrix\n * @param renderList\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList) {\n const activeCamera = this.getScene().activeCamera;\n if (!activeCamera) {\n return;\n }\n const minZ = this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;\n const maxZ = this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;\n const useReverseDepthBuffer = this.getScene().getEngine().useReverseDepthBuffer;\n Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, useReverseDepthBuffer ? maxZ : minZ, useReverseDepthBuffer ? minZ : maxZ, matrix, true, this._scene.getEngine().isNDCHalfZRange, undefined, useReverseDepthBuffer);\n }\n _buildUniformLayout() {\n this._uniformBuffer.addUniform(\"vLightData\", 4);\n this._uniformBuffer.addUniform(\"vLightDiffuse\", 4);\n this._uniformBuffer.addUniform(\"vLightSpecular\", 4);\n this._uniformBuffer.addUniform(\"vLightFalloff\", 4);\n this._uniformBuffer.addUniform(\"shadowsInfo\", 3);\n this._uniformBuffer.addUniform(\"depthValues\", 2);\n this._uniformBuffer.create();\n }\n /**\n * Sets the passed Effect \"effect\" with the PointLight transformed position (or position, if none) and passed name (string).\n * @param effect The effect to update\n * @param lightIndex The index of the light in the effect to update\n * @returns The point light\n */\n transferToEffect(effect, lightIndex) {\n if (this.computeTransformedInformation()) {\n this._uniformBuffer.updateFloat4(\"vLightData\", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);\n }\n else {\n this._uniformBuffer.updateFloat4(\"vLightData\", this.position.x, this.position.y, this.position.z, 0, lightIndex);\n }\n this._uniformBuffer.updateFloat4(\"vLightFalloff\", this.range, this._inverseSquaredRange, 0, 0, lightIndex);\n return this;\n }\n transferToNodeMaterialEffect(effect, lightDataUniformName) {\n if (this.computeTransformedInformation()) {\n effect.setFloat3(lightDataUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z);\n }\n else {\n effect.setFloat3(lightDataUniformName, this.position.x, this.position.y, this.position.z);\n }\n return this;\n }\n /**\n * Prepares the list of defines specific to the light type.\n * @param defines the list of defines\n * @param lightIndex defines the index of the light for the effect\n */\n prepareLightSpecificDefines(defines, lightIndex) {\n defines[\"POINTLIGHT\" + lightIndex] = true;\n }\n}\n__decorate([\n serialize()\n], PointLight.prototype, \"shadowAngle\", null);\n//# sourceMappingURL=pointLight.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./light.js\";\nexport * from \"./shadowLight.js\";\nexport * from \"./Shadows/index.js\";\nexport * from \"./directionalLight.js\";\nexport * from \"./hemisphericLight.js\";\nexport * from \"./pointLight.js\";\nexport * from \"./spotLight.js\";\n//# sourceMappingURL=index.js.map","import { Engine } from \"../Engines/engine.js\";\n/**\n * Class used for the default loading screen\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen\n */\nexport class DefaultLoadingScreen {\n /**\n * Creates a new default loading screen\n * @param _renderingCanvas defines the canvas used to render the scene\n * @param _loadingText defines the default text to display\n * @param _loadingDivBackgroundColor defines the default background color\n */\n constructor(_renderingCanvas, _loadingText = \"\", _loadingDivBackgroundColor = \"black\") {\n this._renderingCanvas = _renderingCanvas;\n this._loadingText = _loadingText;\n this._loadingDivBackgroundColor = _loadingDivBackgroundColor;\n // Resize\n this._resizeLoadingUI = () => {\n const canvasRect = this._renderingCanvas.getBoundingClientRect();\n const canvasPositioning = window.getComputedStyle(this._renderingCanvas).position;\n if (!this._loadingDiv) {\n return;\n }\n this._loadingDiv.style.position = canvasPositioning === \"fixed\" ? \"fixed\" : \"absolute\";\n this._loadingDiv.style.left = canvasRect.left + \"px\";\n this._loadingDiv.style.top = canvasRect.top + \"px\";\n this._loadingDiv.style.width = canvasRect.width + \"px\";\n this._loadingDiv.style.height = canvasRect.height + \"px\";\n };\n }\n /**\n * Function called to display the loading screen\n */\n displayLoadingUI() {\n if (this._loadingDiv) {\n // Do not add a loading screen if there is already one\n return;\n }\n this._loadingDiv = document.createElement(\"div\");\n this._loadingDiv.id = \"babylonjsLoadingDiv\";\n this._loadingDiv.style.opacity = \"0\";\n this._loadingDiv.style.transition = \"opacity 1.5s ease\";\n this._loadingDiv.style.pointerEvents = \"none\";\n this._loadingDiv.style.display = \"grid\";\n this._loadingDiv.style.gridTemplateRows = \"100%\";\n this._loadingDiv.style.gridTemplateColumns = \"100%\";\n this._loadingDiv.style.justifyItems = \"center\";\n this._loadingDiv.style.alignItems = \"center\";\n // Loading text\n this._loadingTextDiv = document.createElement(\"div\");\n this._loadingTextDiv.style.position = \"absolute\";\n this._loadingTextDiv.style.left = \"0\";\n this._loadingTextDiv.style.top = \"50%\";\n this._loadingTextDiv.style.marginTop = \"80px\";\n this._loadingTextDiv.style.width = \"100%\";\n this._loadingTextDiv.style.height = \"20px\";\n this._loadingTextDiv.style.fontFamily = \"Arial\";\n this._loadingTextDiv.style.fontSize = \"14px\";\n this._loadingTextDiv.style.color = \"white\";\n this._loadingTextDiv.style.textAlign = \"center\";\n this._loadingTextDiv.style.zIndex = \"1\";\n this._loadingTextDiv.innerHTML = \"Loading\";\n this._loadingDiv.appendChild(this._loadingTextDiv);\n //set the predefined text\n this._loadingTextDiv.innerHTML = this._loadingText;\n // Generating keyframes\n this._style = document.createElement(\"style\");\n this._style.type = \"text/css\";\n const keyFrames = `@-webkit-keyframes spin1 {\\\r\n 0% { -webkit-transform: rotate(0deg);}\r\n 100% { -webkit-transform: rotate(360deg);}\r\n }\\\r\n @keyframes spin1 {\\\r\n 0% { transform: rotate(0deg);}\r\n 100% { transform: rotate(360deg);}\r\n }`;\n this._style.innerHTML = keyFrames;\n document.getElementsByTagName(\"head\")[0].appendChild(this._style);\n const svgSupport = !!window.SVGSVGElement;\n // Loading img\n const imgBack = new Image();\n if (!DefaultLoadingScreen.DefaultLogoUrl) {\n imgBack.src = !svgSupport\n ? \"https://cdn.babylonjs.com/Assets/babylonLogo.png\"\n : `data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+`;\n }\n else {\n imgBack.src = DefaultLoadingScreen.DefaultLogoUrl;\n }\n imgBack.style.width = \"150px\";\n imgBack.style.gridColumn = \"1\";\n imgBack.style.gridRow = \"1\";\n imgBack.style.top = \"50%\";\n imgBack.style.left = \"50%\";\n imgBack.style.transform = \"translate(-50%, -50%)\";\n imgBack.style.position = \"absolute\";\n const imageSpinnerContainer = document.createElement(\"div\");\n imageSpinnerContainer.style.width = \"300px\";\n imageSpinnerContainer.style.gridColumn = \"1\";\n imageSpinnerContainer.style.gridRow = \"1\";\n imageSpinnerContainer.style.top = \"50%\";\n imageSpinnerContainer.style.left = \"50%\";\n imageSpinnerContainer.style.transform = \"translate(-50%, -50%)\";\n imageSpinnerContainer.style.position = \"absolute\";\n // Loading spinner\n const imgSpinner = new Image();\n if (!DefaultLoadingScreen.DefaultSpinnerUrl) {\n imgSpinner.src = !svgSupport\n ? \"https://cdn.babylonjs.com/Assets/loadingIcon.png\"\n : `data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==`;\n }\n else {\n imgSpinner.src = DefaultLoadingScreen.DefaultSpinnerUrl;\n }\n imgSpinner.style.animation = \"spin1 0.75s infinite linear\";\n imgSpinner.style.webkitAnimation = \"spin1 0.75s infinite linear\";\n imgSpinner.style.transformOrigin = \"50% 50%\";\n imgSpinner.style.webkitTransformOrigin = \"50% 50%\";\n if (!svgSupport) {\n const logoSize = { w: 16, h: 18.5 };\n const loadingSize = { w: 30, h: 30 };\n // set styling correctly\n imgBack.style.width = `${logoSize.w}vh`;\n imgBack.style.height = `${logoSize.h}vh`;\n imgBack.style.left = `calc(50% - ${logoSize.w / 2}vh)`;\n imgBack.style.top = `calc(50% - ${logoSize.h / 2}vh)`;\n imgSpinner.style.width = `${loadingSize.w}vh`;\n imgSpinner.style.height = `${loadingSize.h}vh`;\n imgSpinner.style.left = `calc(50% - ${loadingSize.w / 2}vh)`;\n imgSpinner.style.top = `calc(50% - ${loadingSize.h / 2}vh)`;\n }\n imageSpinnerContainer.appendChild(imgSpinner);\n this._loadingDiv.appendChild(imgBack);\n this._loadingDiv.appendChild(imageSpinnerContainer);\n this._resizeLoadingUI();\n window.addEventListener(\"resize\", this._resizeLoadingUI);\n this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;\n document.body.appendChild(this._loadingDiv);\n this._loadingDiv.style.opacity = \"1\";\n }\n /**\n * Function called to hide the loading screen\n */\n hideLoadingUI() {\n if (!this._loadingDiv) {\n return;\n }\n const onTransitionEnd = () => {\n if (this._loadingTextDiv) {\n this._loadingTextDiv.remove();\n this._loadingTextDiv = null;\n }\n if (this._loadingDiv) {\n this._loadingDiv.remove();\n this._loadingDiv = null;\n }\n if (this._style) {\n this._style.remove();\n this._style = null;\n }\n window.removeEventListener(\"resize\", this._resizeLoadingUI);\n };\n this._loadingDiv.style.opacity = \"0\";\n this._loadingDiv.addEventListener(\"transitionend\", onTransitionEnd);\n }\n /**\n * Gets or sets the text to display while loading\n */\n set loadingUIText(text) {\n this._loadingText = text;\n if (this._loadingTextDiv) {\n this._loadingTextDiv.innerHTML = this._loadingText;\n }\n }\n get loadingUIText() {\n return this._loadingText;\n }\n /**\n * Gets or sets the color to use for the background\n */\n get loadingUIBackgroundColor() {\n return this._loadingDivBackgroundColor;\n }\n set loadingUIBackgroundColor(color) {\n this._loadingDivBackgroundColor = color;\n if (!this._loadingDiv) {\n return;\n }\n this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;\n }\n}\n/** Gets or sets the logo url to use for the default loading screen */\nDefaultLoadingScreen.DefaultLogoUrl = \"\";\n/** Gets or sets the spinner url to use for the default loading screen */\nDefaultLoadingScreen.DefaultSpinnerUrl = \"\";\nEngine.DefaultLoadingScreenFactory = (canvas) => {\n return new DefaultLoadingScreen(canvas);\n};\n//# sourceMappingURL=loadingScreen.js.map","import { Vector3 } from \"../../Maths/math.vector.js\";\n\n/**\n * Helper class useful to convert panorama picture to their cubemap representation in 6 faces.\n */\nexport class PanoramaToCubeMapTools {\n /**\n * Converts a panorama stored in RGB right to left up to down format into a cubemap (6 faces).\n *\n * @param float32Array The source data.\n * @param inputWidth The width of the input panorama.\n * @param inputHeight The height of the input panorama.\n * @param size The willing size of the generated cubemap (each faces will be size * size pixels)\n * @returns The cubemap data\n */\n static ConvertPanoramaToCubemap(float32Array, inputWidth, inputHeight, size, supersample = false) {\n if (!float32Array) {\n throw \"ConvertPanoramaToCubemap: input cannot be null\";\n }\n if (float32Array.length != inputWidth * inputHeight * 3) {\n throw \"ConvertPanoramaToCubemap: input size is wrong\";\n }\n const textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight, supersample);\n const textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight, supersample);\n const textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight, supersample);\n const textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight, supersample);\n const textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight, supersample);\n const textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight, supersample);\n return {\n front: textureFront,\n back: textureBack,\n left: textureLeft,\n right: textureRight,\n up: textureUp,\n down: textureDown,\n size: size,\n type: 1,\n format: 4,\n gammaSpace: false,\n };\n }\n static CreateCubemapTexture(texSize, faceData, float32Array, inputWidth, inputHeight, supersample = false) {\n const buffer = new ArrayBuffer(texSize * texSize * 4 * 3);\n const textureArray = new Float32Array(buffer);\n // If supersampling, determine number of samples needed when source texture width is divided for 4 cube faces\n const samples = supersample ? Math.max(1, Math.round(inputWidth / 4 / texSize)) : 1;\n const sampleFactor = 1 / samples;\n const sampleFactorSqr = sampleFactor * sampleFactor;\n const rotDX1 = faceData[1].subtract(faceData[0]).scale(sampleFactor / texSize);\n const rotDX2 = faceData[3].subtract(faceData[2]).scale(sampleFactor / texSize);\n const dy = 1 / texSize;\n let fy = 0;\n for (let y = 0; y < texSize; y++) {\n for (let sy = 0; sy < samples; sy++) {\n let xv1 = faceData[0];\n let xv2 = faceData[2];\n for (let x = 0; x < texSize; x++) {\n for (let sx = 0; sx < samples; sx++) {\n const v = xv2.subtract(xv1).scale(fy).add(xv1);\n v.normalize();\n const color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);\n // 3 channels per pixels\n textureArray[y * texSize * 3 + x * 3 + 0] += color.r * sampleFactorSqr;\n textureArray[y * texSize * 3 + x * 3 + 1] += color.g * sampleFactorSqr;\n textureArray[y * texSize * 3 + x * 3 + 2] += color.b * sampleFactorSqr;\n xv1 = xv1.add(rotDX1);\n xv2 = xv2.add(rotDX2);\n }\n }\n fy += dy * sampleFactor;\n }\n }\n return textureArray;\n }\n static CalcProjectionSpherical(vDir, float32Array, inputWidth, inputHeight) {\n let theta = Math.atan2(vDir.z, vDir.x);\n const phi = Math.acos(vDir.y);\n while (theta < -Math.PI) {\n theta += 2 * Math.PI;\n }\n while (theta > Math.PI) {\n theta -= 2 * Math.PI;\n }\n let dx = theta / Math.PI;\n const dy = phi / Math.PI;\n // recenter.\n dx = dx * 0.5 + 0.5;\n let px = Math.round(dx * inputWidth);\n if (px < 0) {\n px = 0;\n }\n else if (px >= inputWidth) {\n px = inputWidth - 1;\n }\n let py = Math.round(dy * inputHeight);\n if (py < 0) {\n py = 0;\n }\n else if (py >= inputHeight) {\n py = inputHeight - 1;\n }\n const inputY = inputHeight - py - 1;\n const r = float32Array[inputY * inputWidth * 3 + px * 3 + 0];\n const g = float32Array[inputY * inputWidth * 3 + px * 3 + 1];\n const b = float32Array[inputY * inputWidth * 3 + px * 3 + 2];\n return {\n r: r,\n g: g,\n b: b,\n };\n }\n}\nPanoramaToCubeMapTools.FACE_LEFT = [new Vector3(-1.0, -1.0, -1.0), new Vector3(1.0, -1.0, -1.0), new Vector3(-1.0, 1.0, -1.0), new Vector3(1.0, 1.0, -1.0)];\nPanoramaToCubeMapTools.FACE_RIGHT = [new Vector3(1.0, -1.0, 1.0), new Vector3(-1.0, -1.0, 1.0), new Vector3(1.0, 1.0, 1.0), new Vector3(-1.0, 1.0, 1.0)];\nPanoramaToCubeMapTools.FACE_FRONT = [new Vector3(1.0, -1.0, -1.0), new Vector3(1.0, -1.0, 1.0), new Vector3(1.0, 1.0, -1.0), new Vector3(1.0, 1.0, 1.0)];\nPanoramaToCubeMapTools.FACE_BACK = [new Vector3(-1.0, -1.0, 1.0), new Vector3(-1.0, -1.0, -1.0), new Vector3(-1.0, 1.0, 1.0), new Vector3(-1.0, 1.0, -1.0)];\nPanoramaToCubeMapTools.FACE_DOWN = [new Vector3(1.0, 1.0, -1.0), new Vector3(1.0, 1.0, 1.0), new Vector3(-1.0, 1.0, -1.0), new Vector3(-1.0, 1.0, 1.0)];\nPanoramaToCubeMapTools.FACE_UP = [new Vector3(-1.0, -1.0, -1.0), new Vector3(-1.0, -1.0, 1.0), new Vector3(1.0, -1.0, -1.0), new Vector3(1.0, -1.0, 1.0)];\n//# sourceMappingURL=panoramaToCubemap.js.map","import { PanoramaToCubeMapTools } from \"./panoramaToCubemap.js\";\n/**\n * This groups tools to convert HDR texture to native colors array.\n */\nexport class HDRTools {\n static _Ldexp(mantissa, exponent) {\n if (exponent > 1023) {\n return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);\n }\n if (exponent < -1074) {\n return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);\n }\n return mantissa * Math.pow(2, exponent);\n }\n static _Rgbe2float(float32array, red, green, blue, exponent, index) {\n if (exponent > 0) {\n /*nonzero pixel*/\n exponent = this._Ldexp(1.0, exponent - (128 + 8));\n float32array[index + 0] = red * exponent;\n float32array[index + 1] = green * exponent;\n float32array[index + 2] = blue * exponent;\n }\n else {\n float32array[index + 0] = 0;\n float32array[index + 1] = 0;\n float32array[index + 2] = 0;\n }\n }\n static _ReadStringLine(uint8array, startIndex) {\n let line = \"\";\n let character = \"\";\n for (let i = startIndex; i < uint8array.length - startIndex; i++) {\n character = String.fromCharCode(uint8array[i]);\n if (character == \"\\n\") {\n break;\n }\n line += character;\n }\n return line;\n }\n /**\n * Reads header information from an RGBE texture stored in a native array.\n * More information on this format are available here:\n * https://en.wikipedia.org/wiki/RGBE_image_format\n *\n * @param uint8array The binary file stored in native array.\n * @returns The header information.\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static RGBE_ReadHeader(uint8array) {\n let height = 0;\n let width = 0;\n let line = this._ReadStringLine(uint8array, 0);\n if (line[0] != \"#\" || line[1] != \"?\") {\n throw \"Bad HDR Format.\";\n }\n let endOfHeader = false;\n let findFormat = false;\n let lineIndex = 0;\n do {\n lineIndex += line.length + 1;\n line = this._ReadStringLine(uint8array, lineIndex);\n if (line == \"FORMAT=32-bit_rle_rgbe\") {\n findFormat = true;\n }\n else if (line.length == 0) {\n endOfHeader = true;\n }\n } while (!endOfHeader);\n if (!findFormat) {\n throw \"HDR Bad header format, unsupported FORMAT\";\n }\n lineIndex += line.length + 1;\n line = this._ReadStringLine(uint8array, lineIndex);\n const sizeRegexp = /^-Y (.*) \\+X (.*)$/g;\n const match = sizeRegexp.exec(line);\n // TODO. Support +Y and -X if needed.\n if (!match || match.length < 3) {\n throw \"HDR Bad header format, no size\";\n }\n width = parseInt(match[2]);\n height = parseInt(match[1]);\n if (width < 8 || width > 0x7fff) {\n throw \"HDR Bad header format, unsupported size\";\n }\n lineIndex += line.length + 1;\n return {\n height: height,\n width: width,\n dataPosition: lineIndex,\n };\n }\n /**\n * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.\n * This RGBE texture needs to store the information as a panorama.\n *\n * More information on this format are available here:\n * https://en.wikipedia.org/wiki/RGBE_image_format\n *\n * @param buffer The binary file stored in an array buffer.\n * @param size The expected size of the extracted cubemap.\n * @returns The Cube Map information.\n */\n static GetCubeMapTextureData(buffer, size, supersample = false) {\n const uint8array = new Uint8Array(buffer);\n const hdrInfo = this.RGBE_ReadHeader(uint8array);\n const data = this.RGBE_ReadPixels(uint8array, hdrInfo);\n const cubeMapData = PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size, supersample);\n return cubeMapData;\n }\n /**\n * Returns the pixels data extracted from an RGBE texture.\n * This pixels will be stored left to right up to down in the R G B order in one array.\n *\n * More information on this format are available here:\n * https://en.wikipedia.org/wiki/RGBE_image_format\n *\n * @param uint8array The binary file stored in an array buffer.\n * @param hdrInfo The header information of the file.\n * @returns The pixels data in RGB right to left up to down order.\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static RGBE_ReadPixels(uint8array, hdrInfo) {\n return this._RGBEReadPixelsRLE(uint8array, hdrInfo);\n }\n static _RGBEReadPixelsRLE(uint8array, hdrInfo) {\n let num_scanlines = hdrInfo.height;\n const scanline_width = hdrInfo.width;\n let a, b, c, d, count;\n let dataIndex = hdrInfo.dataPosition;\n let index = 0, endIndex = 0, i = 0;\n const scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E\n const scanLineArray = new Uint8Array(scanLineArrayBuffer);\n // 3 channels of 4 bytes per pixel in float.\n const resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);\n const resultArray = new Float32Array(resultBuffer);\n // read in each successive scanline\n while (num_scanlines > 0) {\n a = uint8array[dataIndex++];\n b = uint8array[dataIndex++];\n c = uint8array[dataIndex++];\n d = uint8array[dataIndex++];\n if (a != 2 || b != 2 || c & 0x80 || hdrInfo.width < 8 || hdrInfo.width > 32767) {\n return this._RGBEReadPixelsNOTRLE(uint8array, hdrInfo);\n }\n if (((c << 8) | d) != scanline_width) {\n throw \"HDR Bad header format, wrong scan line width\";\n }\n index = 0;\n // read each of the four channels for the scanline into the buffer\n for (i = 0; i < 4; i++) {\n endIndex = (i + 1) * scanline_width;\n while (index < endIndex) {\n a = uint8array[dataIndex++];\n b = uint8array[dataIndex++];\n if (a > 128) {\n // a run of the same value\n count = a - 128;\n if (count == 0 || count > endIndex - index) {\n throw \"HDR Bad Format, bad scanline data (run)\";\n }\n while (count-- > 0) {\n scanLineArray[index++] = b;\n }\n }\n else {\n // a non-run\n count = a;\n if (count == 0 || count > endIndex - index) {\n throw \"HDR Bad Format, bad scanline data (non-run)\";\n }\n scanLineArray[index++] = b;\n if (--count > 0) {\n for (let j = 0; j < count; j++) {\n scanLineArray[index++] = uint8array[dataIndex++];\n }\n }\n }\n }\n }\n // now convert data from buffer into floats\n for (i = 0; i < scanline_width; i++) {\n a = scanLineArray[i];\n b = scanLineArray[i + scanline_width];\n c = scanLineArray[i + 2 * scanline_width];\n d = scanLineArray[i + 3 * scanline_width];\n this._Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);\n }\n num_scanlines--;\n }\n return resultArray;\n }\n static _RGBEReadPixelsNOTRLE(uint8array, hdrInfo) {\n // this file is not run length encoded\n // read values sequentially\n let num_scanlines = hdrInfo.height;\n const scanline_width = hdrInfo.width;\n let a, b, c, d, i;\n let dataIndex = hdrInfo.dataPosition;\n // 3 channels of 4 bytes per pixel in float.\n const resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);\n const resultArray = new Float32Array(resultBuffer);\n // read in each successive scanline\n while (num_scanlines > 0) {\n for (i = 0; i < hdrInfo.width; i++) {\n a = uint8array[dataIndex++];\n b = uint8array[dataIndex++];\n c = uint8array[dataIndex++];\n d = uint8array[dataIndex++];\n this._Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);\n }\n num_scanlines--;\n }\n return resultArray;\n }\n}\n//# sourceMappingURL=hdr.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"hdrFilteringVertexShader\";\nconst shader = `attribute vec2 position;\rvarying vec3 direction;\runiform vec3 up;\runiform vec3 right;\runiform vec3 front;\r#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_VERTEX_MAIN_BEGIN\nmat3 view=mat3(up,right,front);\rdirection=view*vec3(position,1.0);\rgl_Position=vec4(position,0.0,1.0);\r#define CUSTOM_VERTEX_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const hdrFilteringVertexShader = { name, shader };\n//# sourceMappingURL=hdrFiltering.vertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/helperFunctions.js\";\nimport \"./ShadersInclude/importanceSampling.js\";\nimport \"./ShadersInclude/pbrBRDFFunctions.js\";\nimport \"./ShadersInclude/hdrFilteringFunctions.js\";\nconst name = \"hdrFilteringPixelShader\";\nconst shader = `#include\n#include\n#include\n#include\nuniform float alphaG;\runiform samplerCube inputTexture;\runiform vec2 vFilteringInfo;\runiform float hdrScale;\rvarying vec3 direction;\rvoid main() {\rvec3 color=radiance(alphaG,inputTexture,direction,vFilteringInfo);\rgl_FragColor=vec4(color*hdrScale,1.0);\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const hdrFilteringPixelShader = { name, shader };\n//# sourceMappingURL=hdrFiltering.fragment.js.map","import { Vector3 } from \"../../../Maths/math.js\";\nimport { Scalar } from \"../../../Maths/math.scalar.js\";\n\nimport { EffectWrapper, EffectRenderer } from \"../../../Materials/effectRenderer.js\";\nimport \"../../../Shaders/hdrFiltering.vertex.js\";\nimport \"../../../Shaders/hdrFiltering.fragment.js\";\nimport { Logger } from \"../../../Misc/logger.js\";\n/**\n * Filters HDR maps to get correct renderings of PBR reflections\n */\nexport class HDRFiltering {\n /**\n * Instantiates HDR filter for reflection maps\n *\n * @param engine Thin engine\n * @param options Options\n */\n constructor(engine, options = {}) {\n this._lodGenerationOffset = 0;\n this._lodGenerationScale = 0.8;\n /**\n * Quality switch for prefiltering. Should be set to `4096` unless\n * you care about baking speed.\n */\n this.quality = 4096;\n /**\n * Scales pixel intensity for the input HDR map.\n */\n this.hdrScale = 1;\n // pass\n this._engine = engine;\n this.hdrScale = options.hdrScale || this.hdrScale;\n this.quality = options.quality || this.quality;\n }\n _createRenderTarget(size) {\n let textureType = 0;\n if (this._engine.getCaps().textureHalfFloatRender) {\n textureType = 2;\n }\n else if (this._engine.getCaps().textureFloatRender) {\n textureType = 1;\n }\n const rtWrapper = this._engine.createRenderTargetCubeTexture(size, {\n format: 5,\n type: textureType,\n createMipMaps: true,\n generateMipMaps: false,\n generateDepthBuffer: false,\n generateStencilBuffer: false,\n samplingMode: 1,\n });\n this._engine.updateTextureWrappingMode(rtWrapper.texture, 0, 0, 0);\n this._engine.updateTextureSamplingMode(3, rtWrapper.texture, true);\n return rtWrapper;\n }\n _prefilterInternal(texture) {\n const width = texture.getSize().width;\n const mipmapsCount = Scalar.ILog2(width) + 1;\n const effect = this._effectWrapper.effect;\n const outputTexture = this._createRenderTarget(width);\n this._effectRenderer.setViewport();\n const intTexture = texture.getInternalTexture();\n if (intTexture) {\n // Just in case generate fresh clean mips.\n this._engine.updateTextureSamplingMode(3, intTexture, true);\n }\n this._effectRenderer.applyEffectWrapper(this._effectWrapper);\n const directions = [\n [new Vector3(0, 0, -1), new Vector3(0, -1, 0), new Vector3(1, 0, 0)],\n [new Vector3(0, 0, 1), new Vector3(0, -1, 0), new Vector3(-1, 0, 0)],\n [new Vector3(1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 1, 0)],\n [new Vector3(1, 0, 0), new Vector3(0, 0, -1), new Vector3(0, -1, 0)],\n [new Vector3(1, 0, 0), new Vector3(0, -1, 0), new Vector3(0, 0, 1)],\n [new Vector3(-1, 0, 0), new Vector3(0, -1, 0), new Vector3(0, 0, -1)], // NegativeZ\n ];\n effect.setFloat(\"hdrScale\", this.hdrScale);\n effect.setFloat2(\"vFilteringInfo\", texture.getSize().width, mipmapsCount);\n effect.setTexture(\"inputTexture\", texture);\n for (let face = 0; face < 6; face++) {\n effect.setVector3(\"up\", directions[face][0]);\n effect.setVector3(\"right\", directions[face][1]);\n effect.setVector3(\"front\", directions[face][2]);\n for (let lod = 0; lod < mipmapsCount; lod++) {\n this._engine.bindFramebuffer(outputTexture, face, undefined, undefined, true, lod);\n this._effectRenderer.applyEffectWrapper(this._effectWrapper);\n let alpha = Math.pow(2, (lod - this._lodGenerationOffset) / this._lodGenerationScale) / width;\n if (lod === 0) {\n alpha = 0;\n }\n effect.setFloat(\"alphaG\", alpha);\n this._effectRenderer.draw();\n }\n }\n // Cleanup\n this._effectRenderer.restoreStates();\n this._engine.restoreDefaultFramebuffer();\n this._engine._releaseTexture(texture._texture);\n // Internal Swap\n const type = outputTexture.texture.type;\n const format = outputTexture.texture.format;\n outputTexture._swapAndDie(texture._texture);\n texture._texture.type = type;\n texture._texture.format = format;\n // New settings\n texture.gammaSpace = false;\n texture.lodGenerationOffset = this._lodGenerationOffset;\n texture.lodGenerationScale = this._lodGenerationScale;\n texture._prefiltered = true;\n return texture;\n }\n _createEffect(texture, onCompiled) {\n const defines = [];\n if (texture.gammaSpace) {\n defines.push(\"#define GAMMA_INPUT\");\n }\n defines.push(\"#define NUM_SAMPLES \" + this.quality + \"u\"); // unsigned int\n const effectWrapper = new EffectWrapper({\n engine: this._engine,\n name: \"hdrFiltering\",\n vertexShader: \"hdrFiltering\",\n fragmentShader: \"hdrFiltering\",\n samplerNames: [\"inputTexture\"],\n uniformNames: [\"vSampleDirections\", \"vWeights\", \"up\", \"right\", \"front\", \"vFilteringInfo\", \"hdrScale\", \"alphaG\"],\n useShaderStore: true,\n defines,\n onCompiled: onCompiled,\n });\n return effectWrapper;\n }\n /**\n * Get a value indicating if the filter is ready to be used\n * @param texture Texture to filter\n * @returns true if the filter is ready\n */\n isReady(texture) {\n return texture.isReady() && this._effectWrapper.effect.isReady();\n }\n /**\n * Prefilters a cube texture to have mipmap levels representing roughness values.\n * Prefiltering will be invoked at the end of next rendering pass.\n * This has to be done once the map is loaded, and has not been prefiltered by a third party software.\n * See http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf for more information\n * @param texture Texture to filter\n * @param onFinished Callback when filtering is done\n * @returns Promise called when prefiltering is done\n */\n prefilter(texture, onFinished = null) {\n if (!this._engine._features.allowTexturePrefiltering) {\n Logger.Warn(\"HDR prefiltering is not available in WebGL 1., you can use real time filtering instead.\");\n return Promise.reject(\"HDR prefiltering is not available in WebGL 1., you can use real time filtering instead.\");\n }\n return new Promise((resolve) => {\n this._effectRenderer = new EffectRenderer(this._engine);\n this._effectWrapper = this._createEffect(texture);\n this._effectWrapper.effect.executeWhenCompiled(() => {\n this._prefilterInternal(texture);\n this._effectRenderer.dispose();\n this._effectWrapper.dispose();\n resolve();\n if (onFinished) {\n onFinished();\n }\n });\n });\n }\n}\n//# sourceMappingURL=hdrFiltering.js.map","import { Matrix, Vector3 } from \"../../Maths/math.vector.js\";\nimport { BaseTexture } from \"../../Materials/Textures/baseTexture.js\";\nimport { Texture } from \"../../Materials/Textures/texture.js\";\n\nimport { HDRTools } from \"../../Misc/HighDynamicRange/hdr.js\";\nimport { CubeMapToSphericalPolynomialTools } from \"../../Misc/HighDynamicRange/cubemapToSphericalPolynomial.js\";\nimport { RegisterClass } from \"../../Misc/typeStore.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nimport { ToGammaSpace } from \"../../Maths/math.constants.js\";\nimport { HDRFiltering } from \"../../Materials/Textures/Filtering/hdrFiltering.js\";\nimport { ToHalfFloat } from \"../../Misc/textureTools.js\";\nimport \"../../Engines/Extensions/engine.rawTexture.js\";\nimport \"../../Materials/Textures/baseTexture.polynomial.js\";\n/**\n * This represents a texture coming from an HDR input.\n *\n * The only supported format is currently panorama picture stored in RGBE format.\n * Example of such files can be found on Poly Haven: https://polyhaven.com/hdris\n */\nexport class HDRCubeTexture extends BaseTexture {\n /**\n * Sets whether or not the texture is blocking during loading.\n */\n set isBlocking(value) {\n this._isBlocking = value;\n }\n /**\n * Gets whether or not the texture is blocking during loading.\n */\n get isBlocking() {\n return this._isBlocking;\n }\n /**\n * Sets texture matrix rotation angle around Y axis in radians.\n */\n set rotationY(value) {\n this._rotationY = value;\n this.setReflectionTextureMatrix(Matrix.RotationY(this._rotationY));\n }\n /**\n * Gets texture matrix rotation angle around Y axis radians.\n */\n get rotationY() {\n return this._rotationY;\n }\n /**\n * Gets or sets the size of the bounding box associated with the cube texture\n * When defined, the cubemap will switch to local mode\n * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity\n * @example https://www.babylonjs-playground.com/#RNASML\n */\n set boundingBoxSize(value) {\n if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {\n return;\n }\n this._boundingBoxSize = value;\n const scene = this.getScene();\n if (scene) {\n scene.markAllMaterialsAsDirty(1);\n }\n }\n get boundingBoxSize() {\n return this._boundingBoxSize;\n }\n /**\n * Instantiates an HDRTexture from the following parameters.\n *\n * @param url The location of the HDR raw data (Panorama stored in RGBE format)\n * @param sceneOrEngine The scene or engine the texture will be used in\n * @param size The cubemap desired size (the more it increases the longer the generation will be)\n * @param noMipmap Forces to not generate the mipmap if true\n * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process\n * @param gammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)\n * @param prefilterOnLoad Prefilters HDR texture to allow use of this texture as a PBR reflection texture.\n * @param onLoad\n * @param onError\n */\n constructor(url, sceneOrEngine, size, noMipmap = false, generateHarmonics = true, gammaSpace = false, prefilterOnLoad = false, onLoad = null, onError = null, supersample = false) {\n var _a;\n super(sceneOrEngine);\n this._generateHarmonics = true;\n this._onError = null;\n this._isBlocking = true;\n this._rotationY = 0;\n /**\n * Gets or sets the center of the bounding box associated with the cube texture\n * It must define where the camera used to render the texture was set\n */\n this.boundingBoxPosition = Vector3.Zero();\n /**\n * Observable triggered once the texture has been loaded.\n */\n this.onLoadObservable = new Observable();\n if (!url) {\n return;\n }\n this._coordinatesMode = Texture.CUBIC_MODE;\n this.name = url;\n this.url = url;\n this.hasAlpha = false;\n this.isCube = true;\n this._textureMatrix = Matrix.Identity();\n this._prefilterOnLoad = prefilterOnLoad;\n this._onLoad = () => {\n this.onLoadObservable.notifyObservers(this);\n if (onLoad) {\n onLoad();\n }\n };\n this._onError = onError;\n this.gammaSpace = gammaSpace;\n this._noMipmap = noMipmap;\n this._size = size;\n this._supersample = supersample;\n this._generateHarmonics = generateHarmonics;\n this._texture = this._getFromCache(url, this._noMipmap, undefined, undefined, undefined, this.isCube);\n if (!this._texture) {\n if (!((_a = this.getScene()) === null || _a === void 0 ? void 0 : _a.useDelayedTextureLoading)) {\n this._loadTexture();\n }\n else {\n this.delayLoadState = 4;\n }\n }\n else {\n if (this._texture.isReady) {\n Tools.SetImmediate(() => this._onLoad());\n }\n else {\n this._texture.onLoadedObservable.add(this._onLoad);\n }\n }\n }\n /**\n * Get the current class name of the texture useful for serialization or dynamic coding.\n * @returns \"HDRCubeTexture\"\n */\n getClassName() {\n return \"HDRCubeTexture\";\n }\n /**\n * Occurs when the file is raw .hdr file.\n */\n _loadTexture() {\n const engine = this._getEngine();\n const caps = engine.getCaps();\n let textureType = 0;\n if (caps.textureFloat && caps.textureFloatLinearFiltering) {\n textureType = 1;\n }\n else if (caps.textureHalfFloat && caps.textureHalfFloatLinearFiltering) {\n textureType = 2;\n }\n const callback = (buffer) => {\n this.lodGenerationOffset = 0.0;\n this.lodGenerationScale = 0.8;\n // Extract the raw linear data.\n const data = HDRTools.GetCubeMapTextureData(buffer, this._size, this._supersample);\n // Generate harmonics if needed.\n if (this._generateHarmonics) {\n const sphericalPolynomial = CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);\n this.sphericalPolynomial = sphericalPolynomial;\n }\n const results = [];\n let byteArray = null;\n let shortArray = null;\n // Push each faces.\n for (let j = 0; j < 6; j++) {\n // Create fallback array\n if (textureType === 2) {\n shortArray = new Uint16Array(this._size * this._size * 3);\n }\n else if (textureType === 0) {\n // 3 channels of 1 bytes per pixel in bytes.\n byteArray = new Uint8Array(this._size * this._size * 3);\n }\n const dataFace = data[HDRCubeTexture._FacesMapping[j]];\n // If special cases.\n if (this.gammaSpace || shortArray || byteArray) {\n for (let i = 0; i < this._size * this._size; i++) {\n // Put in gamma space if requested.\n if (this.gammaSpace) {\n dataFace[i * 3 + 0] = Math.pow(dataFace[i * 3 + 0], ToGammaSpace);\n dataFace[i * 3 + 1] = Math.pow(dataFace[i * 3 + 1], ToGammaSpace);\n dataFace[i * 3 + 2] = Math.pow(dataFace[i * 3 + 2], ToGammaSpace);\n }\n // Convert to half float texture for fallback.\n if (shortArray) {\n shortArray[i * 3 + 0] = ToHalfFloat(dataFace[i * 3 + 0]);\n shortArray[i * 3 + 1] = ToHalfFloat(dataFace[i * 3 + 1]);\n shortArray[i * 3 + 2] = ToHalfFloat(dataFace[i * 3 + 2]);\n }\n // Convert to int texture for fallback.\n if (byteArray) {\n let r = Math.max(dataFace[i * 3 + 0] * 255, 0);\n let g = Math.max(dataFace[i * 3 + 1] * 255, 0);\n let b = Math.max(dataFace[i * 3 + 2] * 255, 0);\n // May use luminance instead if the result is not accurate.\n const max = Math.max(Math.max(r, g), b);\n if (max > 255) {\n const scale = 255 / max;\n r *= scale;\n g *= scale;\n b *= scale;\n }\n byteArray[i * 3 + 0] = r;\n byteArray[i * 3 + 1] = g;\n byteArray[i * 3 + 2] = b;\n }\n }\n }\n if (shortArray) {\n results.push(shortArray);\n }\n else if (byteArray) {\n results.push(byteArray);\n }\n else {\n results.push(dataFace);\n }\n }\n return results;\n };\n if (engine._features.allowTexturePrefiltering && this._prefilterOnLoad) {\n const previousOnLoad = this._onLoad;\n const hdrFiltering = new HDRFiltering(engine);\n this._onLoad = () => {\n hdrFiltering.prefilter(this, previousOnLoad);\n };\n }\n this._texture = engine.createRawCubeTextureFromUrl(this.url, this.getScene(), this._size, 4, textureType, this._noMipmap, callback, null, this._onLoad, this._onError);\n }\n clone() {\n const newTexture = new HDRCubeTexture(this.url, this.getScene() || this._getEngine(), this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);\n // Base texture\n newTexture.level = this.level;\n newTexture.wrapU = this.wrapU;\n newTexture.wrapV = this.wrapV;\n newTexture.coordinatesIndex = this.coordinatesIndex;\n newTexture.coordinatesMode = this.coordinatesMode;\n return newTexture;\n }\n // Methods\n delayLoad() {\n if (this.delayLoadState !== 4) {\n return;\n }\n this.delayLoadState = 1;\n this._texture = this._getFromCache(this.url, this._noMipmap);\n if (!this._texture) {\n this._loadTexture();\n }\n }\n /**\n * Get the texture reflection matrix used to rotate/transform the reflection.\n * @returns the reflection matrix\n */\n getReflectionTextureMatrix() {\n return this._textureMatrix;\n }\n /**\n * Set the texture reflection matrix used to rotate/transform the reflection.\n * @param value Define the reflection matrix to set\n */\n setReflectionTextureMatrix(value) {\n var _a;\n this._textureMatrix = value;\n if (value.updateFlag === this._textureMatrix.updateFlag) {\n return;\n }\n if (value.isIdentity() !== this._textureMatrix.isIdentity()) {\n (_a = this.getScene()) === null || _a === void 0 ? void 0 : _a.markAllMaterialsAsDirty(1, (mat) => mat.getActiveTextures().indexOf(this) !== -1);\n }\n }\n /**\n * Dispose the texture and release its associated resources.\n */\n dispose() {\n this.onLoadObservable.clear();\n super.dispose();\n }\n /**\n * Parses a JSON representation of an HDR Texture in order to create the texture\n * @param parsedTexture Define the JSON representation\n * @param scene Define the scene the texture should be created in\n * @param rootUrl Define the root url in case we need to load relative dependencies\n * @returns the newly created texture after parsing\n */\n static Parse(parsedTexture, scene, rootUrl) {\n let texture = null;\n if (parsedTexture.name && !parsedTexture.isRenderTarget) {\n texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);\n texture.name = parsedTexture.name;\n texture.hasAlpha = parsedTexture.hasAlpha;\n texture.level = parsedTexture.level;\n texture.coordinatesMode = parsedTexture.coordinatesMode;\n texture.isBlocking = parsedTexture.isBlocking;\n }\n if (texture) {\n if (parsedTexture.boundingBoxPosition) {\n texture.boundingBoxPosition = Vector3.FromArray(parsedTexture.boundingBoxPosition);\n }\n if (parsedTexture.boundingBoxSize) {\n texture.boundingBoxSize = Vector3.FromArray(parsedTexture.boundingBoxSize);\n }\n if (parsedTexture.rotationY) {\n texture.rotationY = parsedTexture.rotationY;\n }\n }\n return texture;\n }\n serialize() {\n if (!this.name) {\n return null;\n }\n const serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.hasAlpha = this.hasAlpha;\n serializationObject.isCube = true;\n serializationObject.level = this.level;\n serializationObject.size = this._size;\n serializationObject.coordinatesMode = this.coordinatesMode;\n serializationObject.useInGammaSpace = this.gammaSpace;\n serializationObject.generateHarmonics = this._generateHarmonics;\n serializationObject.customType = \"BABYLON.HDRCubeTexture\";\n serializationObject.noMipmap = this._noMipmap;\n serializationObject.isBlocking = this._isBlocking;\n serializationObject.rotationY = this._rotationY;\n return serializationObject;\n }\n}\nHDRCubeTexture._FacesMapping = [\"right\", \"left\", \"up\", \"down\", \"front\", \"back\"];\nRegisterClass(\"BABYLON.HDRCubeTexture\", HDRCubeTexture);\n//# sourceMappingURL=hdrCubeTexture.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { serialize, SerializationHelper } from \"../Misc/decorators.js\";\nimport { GetClass } from \"../Misc/typeStore.js\";\n/**\n * Defines a target to use with MorphTargetManager\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/morphTargets\n */\nexport class MorphTarget {\n /**\n * Gets or sets the influence of this target (ie. its weight in the overall morphing)\n */\n get influence() {\n return this._influence;\n }\n set influence(influence) {\n if (this._influence === influence) {\n return;\n }\n const previous = this._influence;\n this._influence = influence;\n if (this.onInfluenceChanged.hasObservers()) {\n this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);\n }\n }\n /**\n * Gets or sets the animation properties override\n */\n get animationPropertiesOverride() {\n if (!this._animationPropertiesOverride && this._scene) {\n return this._scene.animationPropertiesOverride;\n }\n return this._animationPropertiesOverride;\n }\n set animationPropertiesOverride(value) {\n this._animationPropertiesOverride = value;\n }\n /**\n * Creates a new MorphTarget\n * @param name defines the name of the target\n * @param influence defines the influence to use\n * @param scene defines the scene the morphtarget belongs to\n */\n constructor(\n /** defines the name of the target */\n name, influence = 0, scene = null) {\n this.name = name;\n /**\n * Gets or sets the list of animations\n */\n this.animations = new Array();\n this._positions = null;\n this._normals = null;\n this._tangents = null;\n this._uvs = null;\n this._uniqueId = 0;\n /**\n * Observable raised when the influence changes\n */\n this.onInfluenceChanged = new Observable();\n /** @internal */\n this._onDataLayoutChanged = new Observable();\n this._animationPropertiesOverride = null;\n this._scene = scene || EngineStore.LastCreatedScene;\n this.influence = influence;\n if (this._scene) {\n this._uniqueId = this._scene.getUniqueId();\n }\n }\n /**\n * Gets the unique ID of this manager\n */\n get uniqueId() {\n return this._uniqueId;\n }\n /**\n * Gets a boolean defining if the target contains position data\n */\n get hasPositions() {\n return !!this._positions;\n }\n /**\n * Gets a boolean defining if the target contains normal data\n */\n get hasNormals() {\n return !!this._normals;\n }\n /**\n * Gets a boolean defining if the target contains tangent data\n */\n get hasTangents() {\n return !!this._tangents;\n }\n /**\n * Gets a boolean defining if the target contains texture coordinates data\n */\n get hasUVs() {\n return !!this._uvs;\n }\n /**\n * Affects position data to this target\n * @param data defines the position data to use\n */\n setPositions(data) {\n const hadPositions = this.hasPositions;\n this._positions = data;\n if (hadPositions !== this.hasPositions) {\n this._onDataLayoutChanged.notifyObservers(undefined);\n }\n }\n /**\n * Gets the position data stored in this target\n * @returns a FloatArray containing the position data (or null if not present)\n */\n getPositions() {\n return this._positions;\n }\n /**\n * Affects normal data to this target\n * @param data defines the normal data to use\n */\n setNormals(data) {\n const hadNormals = this.hasNormals;\n this._normals = data;\n if (hadNormals !== this.hasNormals) {\n this._onDataLayoutChanged.notifyObservers(undefined);\n }\n }\n /**\n * Gets the normal data stored in this target\n * @returns a FloatArray containing the normal data (or null if not present)\n */\n getNormals() {\n return this._normals;\n }\n /**\n * Affects tangent data to this target\n * @param data defines the tangent data to use\n */\n setTangents(data) {\n const hadTangents = this.hasTangents;\n this._tangents = data;\n if (hadTangents !== this.hasTangents) {\n this._onDataLayoutChanged.notifyObservers(undefined);\n }\n }\n /**\n * Gets the tangent data stored in this target\n * @returns a FloatArray containing the tangent data (or null if not present)\n */\n getTangents() {\n return this._tangents;\n }\n /**\n * Affects texture coordinates data to this target\n * @param data defines the texture coordinates data to use\n */\n setUVs(data) {\n const hadUVs = this.hasUVs;\n this._uvs = data;\n if (hadUVs !== this.hasUVs) {\n this._onDataLayoutChanged.notifyObservers(undefined);\n }\n }\n /**\n * Gets the texture coordinates data stored in this target\n * @returns a FloatArray containing the texture coordinates data (or null if not present)\n */\n getUVs() {\n return this._uvs;\n }\n /**\n * Clone the current target\n * @returns a new MorphTarget\n */\n clone() {\n const newOne = SerializationHelper.Clone(() => new MorphTarget(this.name, this.influence, this._scene), this);\n newOne._positions = this._positions;\n newOne._normals = this._normals;\n newOne._tangents = this._tangents;\n newOne._uvs = this._uvs;\n return newOne;\n }\n /**\n * Serializes the current target into a Serialization object\n * @returns the serialized object\n */\n serialize() {\n const serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.influence = this.influence;\n serializationObject.positions = Array.prototype.slice.call(this.getPositions());\n if (this.id != null) {\n serializationObject.id = this.id;\n }\n if (this.hasNormals) {\n serializationObject.normals = Array.prototype.slice.call(this.getNormals());\n }\n if (this.hasTangents) {\n serializationObject.tangents = Array.prototype.slice.call(this.getTangents());\n }\n if (this.hasUVs) {\n serializationObject.uvs = Array.prototype.slice.call(this.getUVs());\n }\n // Animations\n SerializationHelper.AppendSerializedAnimations(this, serializationObject);\n return serializationObject;\n }\n /**\n * Returns the string \"MorphTarget\"\n * @returns \"MorphTarget\"\n */\n getClassName() {\n return \"MorphTarget\";\n }\n // Statics\n /**\n * Creates a new target from serialized data\n * @param serializationObject defines the serialized data to use\n * @param scene defines the hosting scene\n * @returns a new MorphTarget\n */\n static Parse(serializationObject, scene) {\n const result = new MorphTarget(serializationObject.name, serializationObject.influence);\n result.setPositions(serializationObject.positions);\n if (serializationObject.id != null) {\n result.id = serializationObject.id;\n }\n if (serializationObject.normals) {\n result.setNormals(serializationObject.normals);\n }\n if (serializationObject.tangents) {\n result.setTangents(serializationObject.tangents);\n }\n if (serializationObject.uvs) {\n result.setUVs(serializationObject.uvs);\n }\n // Animations\n if (serializationObject.animations) {\n for (let animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {\n const parsedAnimation = serializationObject.animations[animationIndex];\n const internalClass = GetClass(\"BABYLON.Animation\");\n if (internalClass) {\n result.animations.push(internalClass.Parse(parsedAnimation));\n }\n }\n if (serializationObject.autoAnimate && scene) {\n scene.beginAnimation(result, serializationObject.autoAnimateFrom, serializationObject.autoAnimateTo, serializationObject.autoAnimateLoop, serializationObject.autoAnimateSpeed || 1.0);\n }\n }\n return result;\n }\n /**\n * Creates a MorphTarget from mesh data\n * @param mesh defines the source mesh\n * @param name defines the name to use for the new target\n * @param influence defines the influence to attach to the target\n * @returns a new MorphTarget\n */\n static FromMesh(mesh, name, influence) {\n if (!name) {\n name = mesh.name;\n }\n const result = new MorphTarget(name, influence, mesh.getScene());\n result.setPositions(mesh.getVerticesData(VertexBuffer.PositionKind));\n if (mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) {\n result.setNormals(mesh.getVerticesData(VertexBuffer.NormalKind));\n }\n if (mesh.isVerticesDataPresent(VertexBuffer.TangentKind)) {\n result.setTangents(mesh.getVerticesData(VertexBuffer.TangentKind));\n }\n if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {\n result.setUVs(mesh.getVerticesData(VertexBuffer.UVKind));\n }\n return result;\n }\n}\n__decorate([\n serialize()\n], MorphTarget.prototype, \"id\", void 0);\n//# sourceMappingURL=morphTarget.js.map","import { Texture } from \"./texture.js\";\n\nimport \"../../Engines/Extensions/engine.rawTexture.js\";\n/**\n * Class used to store 2D array textures containing user data\n */\nexport class RawTexture2DArray extends Texture {\n /**\n * Gets the number of layers of the texture\n */\n get depth() {\n return this._depth;\n }\n /**\n * Create a new RawTexture2DArray\n * @param data defines the data of the texture\n * @param width defines the width of the texture\n * @param height defines the height of the texture\n * @param depth defines the number of layers of the texture\n * @param format defines the texture format to use\n * @param scene defines the hosting scene\n * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)\n * @param invertY defines if texture must be stored with Y axis inverted\n * @param samplingMode defines the sampling mode to use (Texture.TRILINEAR_SAMPLINGMODE by default)\n * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)\n */\n constructor(data, width, height, depth, \n /** Gets or sets the texture format to use */\n format, scene, generateMipMaps = true, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, textureType = 0) {\n super(null, scene, !generateMipMaps, invertY);\n this.format = format;\n this._texture = scene.getEngine().createRawTexture2DArray(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, null, textureType);\n this._depth = depth;\n this.is2DArray = true;\n }\n /**\n * Update the texture with new data\n * @param data defines the data to store in the texture\n */\n update(data) {\n if (!this._texture) {\n return;\n }\n this._getEngine().updateRawTexture2DArray(this._texture, data, this._texture.format, this._texture.invertY, null, this._texture.type);\n }\n /**\n * Creates a RGBA texture from some data.\n * @param data Define the texture data\n * @param width Define the width of the texture\n * @param height Define the height of the texture\n * @param depth defines the number of layers of the texture\n * @param scene defines the scene the texture will belong to\n * @param generateMipMaps Define whether or not to create mip maps for the texture\n * @param invertY define if the data should be flipped on Y when uploaded to the GPU\n * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)\n * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)\n * @returns the RGBA texture\n */\n static CreateRGBATexture(data, width, height, depth, scene, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0) {\n return new RawTexture2DArray(data, width, height, depth, 5, scene, generateMipMaps, invertY, samplingMode, type);\n }\n}\n//# sourceMappingURL=rawTexture2DArray.js.map","import { SmartArray } from \"../Misc/smartArray.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { MorphTarget } from \"./morphTarget.js\";\n\nimport { RawTexture2DArray } from \"../Materials/Textures/rawTexture2DArray.js\";\n/**\n * This class is used to deform meshes using morphing between different targets\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/morphTargets\n */\nexport class MorphTargetManager {\n /**\n * Sets a boolean indicating that adding new target or updating an existing target will not update the underlying data buffers\n */\n set areUpdatesFrozen(block) {\n if (block) {\n this._blockCounter++;\n }\n else {\n this._blockCounter--;\n if (this._blockCounter <= 0) {\n this._blockCounter = 0;\n this._syncActiveTargets(true);\n }\n }\n }\n get areUpdatesFrozen() {\n return this._blockCounter > 0;\n }\n /**\n * Creates a new MorphTargetManager\n * @param scene defines the current scene\n */\n constructor(scene = null) {\n this._targets = new Array();\n this._targetInfluenceChangedObservers = new Array();\n this._targetDataLayoutChangedObservers = new Array();\n this._activeTargets = new SmartArray(16);\n this._supportsNormals = false;\n this._supportsTangents = false;\n this._supportsUVs = false;\n this._vertexCount = 0;\n this._textureVertexStride = 0;\n this._textureWidth = 0;\n this._textureHeight = 1;\n this._uniqueId = 0;\n this._tempInfluences = new Array();\n this._canUseTextureForTargets = false;\n this._blockCounter = 0;\n /** @internal */\n this._parentContainer = null;\n /**\n * Gets or sets a boolean indicating if influencers must be optimized (eg. recompiling the shader if less influencers are used)\n */\n this.optimizeInfluencers = true;\n /**\n * Gets or sets a boolean indicating if normals must be morphed\n */\n this.enableNormalMorphing = true;\n /**\n * Gets or sets a boolean indicating if tangents must be morphed\n */\n this.enableTangentMorphing = true;\n /**\n * Gets or sets a boolean indicating if UV must be morphed\n */\n this.enableUVMorphing = true;\n this._useTextureToStoreTargets = true;\n if (!scene) {\n scene = EngineStore.LastCreatedScene;\n }\n this._scene = scene;\n if (this._scene) {\n this._scene.addMorphTargetManager(this);\n this._uniqueId = this._scene.getUniqueId();\n const engineCaps = this._scene.getEngine().getCaps();\n this._canUseTextureForTargets =\n engineCaps.canUseGLVertexID && engineCaps.textureFloat && engineCaps.maxVertexTextureImageUnits > 0 && engineCaps.texture2DArrayMaxLayerCount > 1;\n }\n }\n /**\n * Gets the unique ID of this manager\n */\n get uniqueId() {\n return this._uniqueId;\n }\n /**\n * Gets the number of vertices handled by this manager\n */\n get vertexCount() {\n return this._vertexCount;\n }\n /**\n * Gets a boolean indicating if this manager supports morphing of normals\n */\n get supportsNormals() {\n return this._supportsNormals && this.enableNormalMorphing;\n }\n /**\n * Gets a boolean indicating if this manager supports morphing of tangents\n */\n get supportsTangents() {\n return this._supportsTangents && this.enableTangentMorphing;\n }\n /**\n * Gets a boolean indicating if this manager supports morphing of texture coordinates\n */\n get supportsUVs() {\n return this._supportsUVs && this.enableUVMorphing;\n }\n /**\n * Gets the number of targets stored in this manager\n */\n get numTargets() {\n return this._targets.length;\n }\n /**\n * Gets the number of influencers (ie. the number of targets with influences > 0)\n */\n get numInfluencers() {\n return this._activeTargets.length;\n }\n /**\n * Gets the list of influences (one per target)\n */\n get influences() {\n return this._influences;\n }\n /**\n * Gets or sets a boolean indicating that targets should be stored as a texture instead of using vertex attributes (default is true).\n * Please note that this option is not available if the hardware does not support it\n */\n get useTextureToStoreTargets() {\n return this._useTextureToStoreTargets;\n }\n set useTextureToStoreTargets(value) {\n this._useTextureToStoreTargets = value;\n }\n /**\n * Gets a boolean indicating that the targets are stored into a texture (instead of as attributes)\n */\n get isUsingTextureForTargets() {\n var _a;\n return (MorphTargetManager.EnableTextureStorage &&\n this.useTextureToStoreTargets &&\n this._canUseTextureForTargets &&\n !((_a = this._scene) === null || _a === void 0 ? void 0 : _a.getEngine().getCaps().disableMorphTargetTexture));\n }\n /**\n * Gets the active target at specified index. An active target is a target with an influence > 0\n * @param index defines the index to check\n * @returns the requested target\n */\n getActiveTarget(index) {\n return this._activeTargets.data[index];\n }\n /**\n * Gets the target at specified index\n * @param index defines the index to check\n * @returns the requested target\n */\n getTarget(index) {\n return this._targets[index];\n }\n /**\n * Add a new target to this manager\n * @param target defines the target to add\n */\n addTarget(target) {\n this._targets.push(target);\n this._targetInfluenceChangedObservers.push(target.onInfluenceChanged.add((needUpdate) => {\n this._syncActiveTargets(needUpdate);\n }));\n this._targetDataLayoutChangedObservers.push(target._onDataLayoutChanged.add(() => {\n this._syncActiveTargets(true);\n }));\n this._syncActiveTargets(true);\n }\n /**\n * Removes a target from the manager\n * @param target defines the target to remove\n */\n removeTarget(target) {\n const index = this._targets.indexOf(target);\n if (index >= 0) {\n this._targets.splice(index, 1);\n target.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(index, 1)[0]);\n target._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(index, 1)[0]);\n this._syncActiveTargets(true);\n }\n if (this._scene) {\n this._scene.stopAnimation(target);\n }\n }\n /**\n * @internal\n */\n _bind(effect) {\n effect.setFloat3(\"morphTargetTextureInfo\", this._textureVertexStride, this._textureWidth, this._textureHeight);\n effect.setFloatArray(\"morphTargetTextureIndices\", this._morphTargetTextureIndices);\n effect.setTexture(\"morphTargets\", this._targetStoreTexture);\n }\n /**\n * Clone the current manager\n * @returns a new MorphTargetManager\n */\n clone() {\n const copy = new MorphTargetManager(this._scene);\n for (const target of this._targets) {\n copy.addTarget(target.clone());\n }\n copy.enableNormalMorphing = this.enableNormalMorphing;\n copy.enableTangentMorphing = this.enableTangentMorphing;\n copy.enableUVMorphing = this.enableUVMorphing;\n return copy;\n }\n /**\n * Serializes the current manager into a Serialization object\n * @returns the serialized object\n */\n serialize() {\n const serializationObject = {};\n serializationObject.id = this.uniqueId;\n serializationObject.targets = [];\n for (const target of this._targets) {\n serializationObject.targets.push(target.serialize());\n }\n return serializationObject;\n }\n _syncActiveTargets(needUpdate) {\n if (this.areUpdatesFrozen) {\n return;\n }\n let influenceCount = 0;\n this._activeTargets.reset();\n this._supportsNormals = true;\n this._supportsTangents = true;\n this._supportsUVs = true;\n this._vertexCount = 0;\n if (this._scene && this._targets.length > this._scene.getEngine().getCaps().texture2DArrayMaxLayerCount) {\n this.useTextureToStoreTargets = false;\n }\n if (!this._morphTargetTextureIndices || this._morphTargetTextureIndices.length !== this._targets.length) {\n this._morphTargetTextureIndices = new Float32Array(this._targets.length);\n }\n let targetIndex = -1;\n for (const target of this._targets) {\n targetIndex++;\n if (target.influence === 0 && this.optimizeInfluencers) {\n continue;\n }\n if (this._activeTargets.length >= MorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode && !this.isUsingTextureForTargets) {\n break;\n }\n this._activeTargets.push(target);\n this._morphTargetTextureIndices[influenceCount] = targetIndex;\n this._tempInfluences[influenceCount++] = target.influence;\n this._supportsNormals = this._supportsNormals && target.hasNormals;\n this._supportsTangents = this._supportsTangents && target.hasTangents;\n this._supportsUVs = this._supportsUVs && target.hasUVs;\n const positions = target.getPositions();\n if (positions) {\n const vertexCount = positions.length / 3;\n if (this._vertexCount === 0) {\n this._vertexCount = vertexCount;\n }\n else if (this._vertexCount !== vertexCount) {\n Logger.Error(\"Incompatible target. Targets must all have the same vertices count.\");\n return;\n }\n }\n }\n if (this._morphTargetTextureIndices.length !== influenceCount) {\n this._morphTargetTextureIndices = this._morphTargetTextureIndices.slice(0, influenceCount);\n }\n if (!this._influences || this._influences.length !== influenceCount) {\n this._influences = new Float32Array(influenceCount);\n }\n for (let index = 0; index < influenceCount; index++) {\n this._influences[index] = this._tempInfluences[index];\n }\n if (needUpdate) {\n this.synchronize();\n }\n }\n /**\n * Synchronize the targets with all the meshes using this morph target manager\n */\n synchronize() {\n if (!this._scene || this.areUpdatesFrozen) {\n return;\n }\n if (this.isUsingTextureForTargets && this._vertexCount) {\n this._textureVertexStride = 1;\n if (this._supportsNormals) {\n this._textureVertexStride++;\n }\n if (this._supportsTangents) {\n this._textureVertexStride++;\n }\n if (this._supportsUVs) {\n this._textureVertexStride++;\n }\n this._textureWidth = this._vertexCount * this._textureVertexStride;\n this._textureHeight = 1;\n const maxTextureSize = this._scene.getEngine().getCaps().maxTextureSize;\n if (this._textureWidth > maxTextureSize) {\n this._textureHeight = Math.ceil(this._textureWidth / maxTextureSize);\n this._textureWidth = maxTextureSize;\n }\n let mustUpdateTexture = true;\n if (this._targetStoreTexture) {\n const textureSize = this._targetStoreTexture.getSize();\n if (textureSize.width === this._textureWidth && textureSize.height === this._textureHeight && this._targetStoreTexture.depth === this._targets.length) {\n mustUpdateTexture = false;\n }\n }\n if (mustUpdateTexture) {\n if (this._targetStoreTexture) {\n this._targetStoreTexture.dispose();\n }\n const targetCount = this._targets.length;\n const data = new Float32Array(targetCount * this._textureWidth * this._textureHeight * 4);\n let offset = 0;\n for (let index = 0; index < targetCount; index++) {\n const target = this._targets[index];\n const positions = target.getPositions();\n const normals = target.getNormals();\n const uvs = target.getUVs();\n const tangents = target.getTangents();\n if (!positions) {\n if (index === 0) {\n Logger.Error(\"Invalid morph target. Target must have positions.\");\n }\n return;\n }\n offset = index * this._textureWidth * this._textureHeight * 4;\n for (let vertex = 0; vertex < this._vertexCount; vertex++) {\n data[offset] = positions[vertex * 3];\n data[offset + 1] = positions[vertex * 3 + 1];\n data[offset + 2] = positions[vertex * 3 + 2];\n offset += 4;\n if (normals) {\n data[offset] = normals[vertex * 3];\n data[offset + 1] = normals[vertex * 3 + 1];\n data[offset + 2] = normals[vertex * 3 + 2];\n offset += 4;\n }\n if (uvs) {\n data[offset] = uvs[vertex * 2];\n data[offset + 1] = uvs[vertex * 2 + 1];\n offset += 4;\n }\n if (tangents) {\n data[offset] = tangents[vertex * 3];\n data[offset + 1] = tangents[vertex * 3 + 1];\n data[offset + 2] = tangents[vertex * 3 + 2];\n offset += 4;\n }\n }\n }\n this._targetStoreTexture = RawTexture2DArray.CreateRGBATexture(data, this._textureWidth, this._textureHeight, targetCount, this._scene, false, false, 1, 1);\n }\n }\n // Flag meshes as dirty to resync with the active targets\n for (const mesh of this._scene.meshes) {\n if (mesh.morphTargetManager === this) {\n mesh._syncGeometryWithMorphTargetManager();\n }\n }\n }\n /**\n * Release all resources\n */\n dispose() {\n if (this._targetStoreTexture) {\n this._targetStoreTexture.dispose();\n }\n this._targetStoreTexture = null;\n // Remove from scene\n if (this._scene) {\n this._scene.removeMorphTargetManager(this);\n if (this._parentContainer) {\n const index = this._parentContainer.morphTargetManagers.indexOf(this);\n if (index > -1) {\n this._parentContainer.morphTargetManagers.splice(index, 1);\n }\n this._parentContainer = null;\n }\n for (const morph of this._targets) {\n this._scene.stopAnimation(morph);\n }\n }\n }\n // Statics\n /**\n * Creates a new MorphTargetManager from serialized data\n * @param serializationObject defines the serialized data\n * @param scene defines the hosting scene\n * @returns the new MorphTargetManager\n */\n static Parse(serializationObject, scene) {\n const result = new MorphTargetManager(scene);\n result._uniqueId = serializationObject.id;\n for (const targetData of serializationObject.targets) {\n result.addTarget(MorphTarget.Parse(targetData, scene));\n }\n return result;\n }\n}\n/** Enable storing morph target data into textures when set to true (true by default) */\nMorphTargetManager.EnableTextureStorage = true;\n/** Maximum number of active morph targets supported in the \"vertex attribute\" mode (i.e., not the \"texture\" mode) */\nMorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode = 8;\n//# sourceMappingURL=morphTargetManager.js.map","import { Vector3 } from \"../Maths/math.vector.js\";\n/**\n * Holds the data for the raycast result\n * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine\n */\nexport class PhysicsRaycastResult {\n constructor() {\n this._hasHit = false;\n this._hitDistance = 0;\n this._hitNormalWorld = Vector3.Zero();\n this._hitPointWorld = Vector3.Zero();\n this._rayFromWorld = Vector3.Zero();\n this._rayToWorld = Vector3.Zero();\n this._triangleIndex = -1;\n }\n /**\n * Gets if there was a hit\n */\n get hasHit() {\n return this._hasHit;\n }\n /**\n * Gets the distance from the hit\n */\n get hitDistance() {\n return this._hitDistance;\n }\n /**\n * Gets the hit normal/direction in the world\n */\n get hitNormalWorld() {\n return this._hitNormalWorld;\n }\n /**\n * Gets the hit point in the world\n */\n get hitPointWorld() {\n return this._hitPointWorld;\n }\n /**\n * Gets the ray \"start point\" of the ray in the world\n */\n get rayFromWorld() {\n return this._rayFromWorld;\n }\n /**\n * Gets the ray \"end point\" of the ray in the world\n */\n get rayToWorld() {\n return this._rayToWorld;\n }\n /*\n * The index of the original triangle which was hit. Will be -1 if contact point is not on a mesh shape\n */\n get triangleIndex() {\n return this._triangleIndex;\n }\n /**\n * Sets the hit data (normal & point in world space)\n * @param hitNormalWorld defines the normal in world space\n * @param hitPointWorld defines the point in world space\n */\n setHitData(hitNormalWorld, hitPointWorld, triangleIndex) {\n this._hasHit = true;\n this._hitNormalWorld.set(hitNormalWorld.x, hitNormalWorld.y, hitNormalWorld.z);\n this._hitPointWorld.set(hitPointWorld.x, hitPointWorld.y, hitPointWorld.z);\n this._triangleIndex = triangleIndex !== null && triangleIndex !== void 0 ? triangleIndex : -1;\n }\n /**\n * Sets the distance from the start point to the hit point\n * @param distance\n */\n setHitDistance(distance) {\n this._hitDistance = distance;\n }\n /**\n * Calculates the distance manually\n */\n calculateHitDistance() {\n this._hitDistance = Vector3.Distance(this._rayFromWorld, this._hitPointWorld);\n }\n /**\n * Resets all the values to default\n * @param from The from point on world space\n * @param to The to point on world space\n */\n reset(from = Vector3.Zero(), to = Vector3.Zero()) {\n this._rayFromWorld.copyFrom(from);\n this._rayToWorld.copyFrom(to);\n this._hasHit = false;\n this._hitDistance = 0;\n this._hitNormalWorld.setAll(0);\n this._hitPointWorld.setAll(0);\n this._triangleIndex = -1;\n }\n}\n//# sourceMappingURL=physicsRaycastResult.js.map","import { Vector3 } from \"../../Maths/math.vector.js\";\nimport { _WarnImport } from \"../../Misc/devTools.js\";\n/**\n * Class used to control physics engine\n * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine\n */\nexport class PhysicsEngine {\n /**\n *\n * @returns version\n */\n getPluginVersion() {\n return this._physicsPlugin.getPluginVersion();\n }\n /**\n * Factory used to create the default physics plugin.\n * @returns The default physics plugin\n */\n static DefaultPluginFactory() {\n throw _WarnImport(\"CannonJSPlugin\");\n }\n /**\n * Creates a new Physics Engine\n * @param gravity defines the gravity vector used by the simulation\n * @param _physicsPlugin defines the plugin to use (CannonJS by default)\n */\n constructor(gravity, _physicsPlugin = PhysicsEngine.DefaultPluginFactory()) {\n this._physicsPlugin = _physicsPlugin;\n /**\n * Global value used to control the smallest number supported by the simulation\n */\n this._impostors = [];\n this._joints = [];\n this._subTimeStep = 0;\n this._uniqueIdCounter = 0;\n if (!this._physicsPlugin.isSupported()) {\n throw new Error(\"Physics Engine \" + this._physicsPlugin.name + \" cannot be found. \" + \"Please make sure it is included.\");\n }\n gravity = gravity || new Vector3(0, -9.807, 0);\n this.setGravity(gravity);\n this.setTimeStep();\n }\n /**\n * Sets the gravity vector used by the simulation\n * @param gravity defines the gravity vector to use\n */\n setGravity(gravity) {\n this.gravity = gravity;\n this._physicsPlugin.setGravity(this.gravity);\n }\n /**\n * Set the time step of the physics engine.\n * Default is 1/60.\n * To slow it down, enter 1/600 for example.\n * To speed it up, 1/30\n * @param newTimeStep defines the new timestep to apply to this world.\n */\n setTimeStep(newTimeStep = 1 / 60) {\n this._physicsPlugin.setTimeStep(newTimeStep);\n }\n /**\n * Get the time step of the physics engine.\n * @returns the current time step\n */\n getTimeStep() {\n return this._physicsPlugin.getTimeStep();\n }\n /**\n * Set the sub time step of the physics engine.\n * Default is 0 meaning there is no sub steps\n * To increase physics resolution precision, set a small value (like 1 ms)\n * @param subTimeStep defines the new sub timestep used for physics resolution.\n */\n setSubTimeStep(subTimeStep = 0) {\n this._subTimeStep = subTimeStep;\n }\n /**\n * Get the sub time step of the physics engine.\n * @returns the current sub time step\n */\n getSubTimeStep() {\n return this._subTimeStep;\n }\n /**\n * Release all resources\n */\n dispose() {\n this._impostors.forEach(function (impostor) {\n impostor.dispose();\n });\n this._physicsPlugin.dispose();\n }\n /**\n * Gets the name of the current physics plugin\n * @returns the name of the plugin\n */\n getPhysicsPluginName() {\n return this._physicsPlugin.name;\n }\n /**\n * Adding a new impostor for the impostor tracking.\n * This will be done by the impostor itself.\n * @param impostor the impostor to add\n */\n addImpostor(impostor) {\n this._impostors.push(impostor);\n impostor.uniqueId = this._uniqueIdCounter++;\n //if no parent, generate the body\n if (!impostor.parent) {\n this._physicsPlugin.generatePhysicsBody(impostor);\n }\n }\n /**\n * Remove an impostor from the engine.\n * This impostor and its mesh will not longer be updated by the physics engine.\n * @param impostor the impostor to remove\n */\n removeImpostor(impostor) {\n const index = this._impostors.indexOf(impostor);\n if (index > -1) {\n const removed = this._impostors.splice(index, 1);\n //Is it needed?\n if (removed.length) {\n this.getPhysicsPlugin().removePhysicsBody(impostor);\n }\n }\n }\n /**\n * Add a joint to the physics engine\n * @param mainImpostor defines the main impostor to which the joint is added.\n * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint\n * @param joint defines the joint that will connect both impostors.\n */\n addJoint(mainImpostor, connectedImpostor, joint) {\n const impostorJoint = {\n mainImpostor: mainImpostor,\n connectedImpostor: connectedImpostor,\n joint: joint,\n };\n joint.physicsPlugin = this._physicsPlugin;\n this._joints.push(impostorJoint);\n this._physicsPlugin.generateJoint(impostorJoint);\n }\n /**\n * Removes a joint from the simulation\n * @param mainImpostor defines the impostor used with the joint\n * @param connectedImpostor defines the other impostor connected to the main one by the joint\n * @param joint defines the joint to remove\n */\n removeJoint(mainImpostor, connectedImpostor, joint) {\n const matchingJoints = this._joints.filter(function (impostorJoint) {\n return impostorJoint.connectedImpostor === connectedImpostor && impostorJoint.joint === joint && impostorJoint.mainImpostor === mainImpostor;\n });\n if (matchingJoints.length) {\n this._physicsPlugin.removeJoint(matchingJoints[0]);\n //TODO remove it from the list as well\n }\n }\n /**\n * Called by the scene. No need to call it.\n * @param delta defines the timespan between frames\n */\n _step(delta) {\n //check if any mesh has no body / requires an update\n this._impostors.forEach((impostor) => {\n if (impostor.isBodyInitRequired()) {\n this._physicsPlugin.generatePhysicsBody(impostor);\n }\n });\n if (delta > 0.1) {\n delta = 0.1;\n }\n else if (delta <= 0) {\n delta = 1.0 / 60.0;\n }\n this._physicsPlugin.executeStep(delta, this._impostors);\n }\n /**\n * Gets the current plugin used to run the simulation\n * @returns current plugin\n */\n getPhysicsPlugin() {\n return this._physicsPlugin;\n }\n /**\n * Gets the list of physic impostors\n * @returns an array of PhysicsImpostor\n */\n getImpostors() {\n return this._impostors;\n }\n /**\n * Gets the impostor for a physics enabled object\n * @param object defines the object impersonated by the impostor\n * @returns the PhysicsImpostor or null if not found\n */\n getImpostorForPhysicsObject(object) {\n for (let i = 0; i < this._impostors.length; ++i) {\n if (this._impostors[i].object === object) {\n return this._impostors[i];\n }\n }\n return null;\n }\n /**\n * Gets the impostor for a physics body object\n * @param body defines physics body used by the impostor\n * @returns the PhysicsImpostor or null if not found\n */\n getImpostorWithPhysicsBody(body) {\n for (let i = 0; i < this._impostors.length; ++i) {\n if (this._impostors[i].physicsBody === body) {\n return this._impostors[i];\n }\n }\n return null;\n }\n /**\n * Does a raycast in the physics world\n * @param from when should the ray start?\n * @param to when should the ray end?\n * @returns PhysicsRaycastResult\n */\n raycast(from, to) {\n return this._physicsPlugin.raycast(from, to);\n }\n /**\n * Does a raycast in the physics world\n * @param from when should the ray start?\n * @param to when should the ray end?\n * @param result resulting PhysicsRaycastResult\n */\n raycastToRef(from, to, result) {\n return this._physicsPlugin.raycastToRef(from, to, result);\n }\n}\n//# sourceMappingURL=physicsEngine.js.map","import { Logger } from \"../../../Misc/logger.js\";\nimport { Vector3, Matrix, Quaternion } from \"../../../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../../../Buffers/buffer.js\";\nimport { PhysicsImpostor } from \"..//physicsImpostor.js\";\nimport { PhysicsJoint } from \"../physicsJoint.js\";\nimport { PhysicsRaycastResult } from \"../../physicsRaycastResult.js\";\nimport { PhysicsEngine } from \"../physicsEngine.js\";\nimport { Epsilon } from \"../../../Maths/math.constants.js\";\n/** @internal */\nexport class CannonJSPlugin {\n constructor(_useDeltaForWorldStep = true, iterations = 10, cannonInjection = CANNON) {\n this._useDeltaForWorldStep = _useDeltaForWorldStep;\n this.name = \"CannonJSPlugin\";\n this._physicsMaterials = new Array();\n this._fixedTimeStep = 1 / 60;\n this._physicsBodiesToRemoveAfterStep = new Array();\n this._firstFrame = true;\n this._tmpQuaternion = new Quaternion();\n this._minus90X = new Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);\n this._plus90X = new Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);\n this._tmpPosition = Vector3.Zero();\n this._tmpDeltaPosition = Vector3.Zero();\n this._tmpUnityRotation = new Quaternion();\n this.BJSCANNON = cannonInjection;\n if (!this.isSupported()) {\n Logger.Error(\"CannonJS is not available. Please make sure you included the js file.\");\n return;\n }\n this._extendNamespace();\n this.world = new this.BJSCANNON.World();\n this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();\n this.world.solver.iterations = iterations;\n this._cannonRaycastResult = new this.BJSCANNON.RaycastResult();\n this._raycastResult = new PhysicsRaycastResult();\n }\n /**\n *\n * @returns plugin version\n */\n getPluginVersion() {\n return 1;\n }\n setGravity(gravity) {\n const vec = gravity;\n this.world.gravity.set(vec.x, vec.y, vec.z);\n }\n setTimeStep(timeStep) {\n this._fixedTimeStep = timeStep;\n }\n getTimeStep() {\n return this._fixedTimeStep;\n }\n executeStep(delta, impostors) {\n // due to cannon's architecture, the first frame's before-step is skipped.\n if (this._firstFrame) {\n this._firstFrame = false;\n for (const impostor of impostors) {\n if (!(impostor.type == PhysicsImpostor.HeightmapImpostor || impostor.type === PhysicsImpostor.PlaneImpostor)) {\n impostor.beforeStep();\n }\n }\n }\n this.world.step(this._useDeltaForWorldStep ? delta : this._fixedTimeStep);\n this._removeMarkedPhysicsBodiesFromWorld();\n }\n _removeMarkedPhysicsBodiesFromWorld() {\n if (this._physicsBodiesToRemoveAfterStep.length > 0) {\n this._physicsBodiesToRemoveAfterStep.forEach((physicsBody) => {\n if (typeof this.world.removeBody === \"function\") {\n this.world.removeBody(physicsBody);\n }\n else {\n this.world.remove(physicsBody);\n }\n });\n this._physicsBodiesToRemoveAfterStep.length = 0;\n }\n }\n applyImpulse(impostor, force, contactPoint) {\n const worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);\n const impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);\n impostor.physicsBody.applyImpulse(impulse, worldPoint);\n }\n applyForce(impostor, force, contactPoint) {\n const worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);\n const impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);\n impostor.physicsBody.applyForce(impulse, worldPoint);\n }\n generatePhysicsBody(impostor) {\n // When calling forceUpdate generatePhysicsBody is called again, ensure that the updated body does not instantly collide with removed body\n this._removeMarkedPhysicsBodiesFromWorld();\n //parent-child relationship. Does this impostor have a parent impostor?\n if (impostor.parent) {\n if (impostor.physicsBody) {\n this.removePhysicsBody(impostor);\n //TODO is that needed?\n impostor.forceUpdate();\n }\n return;\n }\n //should a new body be created for this impostor?\n if (impostor.isBodyInitRequired()) {\n const shape = this._createShape(impostor);\n if (!shape) {\n Logger.Warn(\"It was not possible to create a physics body for this object.\");\n return;\n }\n //unregister events if body is being changed\n const oldBody = impostor.physicsBody;\n if (oldBody) {\n this.removePhysicsBody(impostor);\n }\n //create the body and material\n const material = this._addMaterial(\"mat-\" + impostor.uniqueId, impostor.getParam(\"friction\"), impostor.getParam(\"restitution\"));\n const bodyCreationObject = {\n mass: impostor.getParam(\"mass\"),\n material: material,\n };\n // A simple extend, in case native options were used.\n const nativeOptions = impostor.getParam(\"nativeOptions\");\n for (const key in nativeOptions) {\n if (Object.prototype.hasOwnProperty.call(nativeOptions, key)) {\n bodyCreationObject[key] = nativeOptions[key];\n }\n }\n impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);\n impostor.physicsBody.addEventListener(\"collide\", impostor.onCollide);\n this.world.addEventListener(\"preStep\", impostor.beforeStep);\n this.world.addEventListener(\"postStep\", impostor.afterStep);\n impostor.physicsBody.addShape(shape);\n if (typeof this.world.addBody === \"function\") {\n this.world.addBody(impostor.physicsBody);\n }\n else {\n this.world.add(impostor.physicsBody);\n }\n //try to keep the body moving in the right direction by taking old properties.\n //Should be tested!\n if (oldBody) {\n [\"force\", \"torque\", \"velocity\", \"angularVelocity\"].forEach(function (param) {\n const vec = oldBody[param];\n impostor.physicsBody[param].set(vec.x, vec.y, vec.z);\n });\n }\n this._processChildMeshes(impostor);\n }\n //now update the body's transformation\n this._updatePhysicsBodyTransformation(impostor);\n }\n _processChildMeshes(mainImpostor) {\n const meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];\n const mainRotation = mainImpostor.object.rotationQuaternion;\n if (mainRotation) {\n mainRotation.conjugateToRef(this._tmpQuaternion);\n }\n else {\n this._tmpQuaternion.set(0, 0, 0, 1);\n }\n if (meshChildren.length) {\n const processMesh = (mesh) => {\n if (!mesh.rotationQuaternion) {\n return;\n }\n const childImpostor = mesh.getPhysicsImpostor();\n if (childImpostor) {\n const parent = childImpostor.parent;\n if (parent !== mainImpostor && mesh.parent) {\n const pPosition = mesh.getAbsolutePosition().subtract(mesh.parent.getAbsolutePosition());\n const q = mesh.rotationQuaternion.multiply(this._tmpQuaternion);\n if (childImpostor.physicsBody) {\n this.removePhysicsBody(childImpostor);\n childImpostor.physicsBody = null;\n }\n childImpostor.parent = mainImpostor;\n childImpostor.resetUpdateFlags();\n mainImpostor.physicsBody.addShape(this._createShape(childImpostor), new this.BJSCANNON.Vec3(pPosition.x, pPosition.y, pPosition.z), new this.BJSCANNON.Quaternion(q.x, q.y, q.z, q.w));\n //Add the mass of the children.\n mainImpostor.physicsBody.mass += childImpostor.getParam(\"mass\");\n }\n }\n mesh.getChildMeshes(true)\n .filter((m) => !!m.physicsImpostor)\n .forEach(processMesh);\n };\n meshChildren.filter((m) => !!m.physicsImpostor).forEach(processMesh);\n }\n }\n removePhysicsBody(impostor) {\n impostor.physicsBody.removeEventListener(\"collide\", impostor.onCollide);\n this.world.removeEventListener(\"preStep\", impostor.beforeStep);\n this.world.removeEventListener(\"postStep\", impostor.afterStep);\n // Only remove the physics body after the physics step to avoid disrupting cannon's internal state\n if (this._physicsBodiesToRemoveAfterStep.indexOf(impostor.physicsBody) === -1) {\n this._physicsBodiesToRemoveAfterStep.push(impostor.physicsBody);\n }\n }\n generateJoint(impostorJoint) {\n const mainBody = impostorJoint.mainImpostor.physicsBody;\n const connectedBody = impostorJoint.connectedImpostor.physicsBody;\n if (!mainBody || !connectedBody) {\n return;\n }\n let constraint;\n const jointData = impostorJoint.joint.jointData;\n //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html\n const constraintData = {\n pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().set(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z) : null,\n pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().set(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z) : null,\n axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().set(jointData.mainAxis.x, jointData.mainAxis.y, jointData.mainAxis.z) : null,\n axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().set(jointData.connectedAxis.x, jointData.connectedAxis.y, jointData.connectedAxis.z) : null,\n maxForce: jointData.nativeParams.maxForce,\n collideConnected: !!jointData.collision,\n };\n switch (impostorJoint.joint.type) {\n case PhysicsJoint.HingeJoint:\n case PhysicsJoint.Hinge2Joint:\n constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);\n break;\n case PhysicsJoint.DistanceJoint:\n constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);\n break;\n case PhysicsJoint.SpringJoint: {\n const springData = jointData;\n constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {\n restLength: springData.length,\n stiffness: springData.stiffness,\n damping: springData.damping,\n localAnchorA: constraintData.pivotA,\n localAnchorB: constraintData.pivotB,\n });\n break;\n }\n case PhysicsJoint.LockJoint:\n constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);\n break;\n case PhysicsJoint.PointToPointJoint:\n case PhysicsJoint.BallAndSocketJoint:\n default:\n constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotB, constraintData.maxForce);\n break;\n }\n //set the collideConnected flag after the creation, since DistanceJoint ignores it.\n constraint.collideConnected = !!jointData.collision;\n impostorJoint.joint.physicsJoint = constraint;\n //don't add spring as constraint, as it is not one.\n if (impostorJoint.joint.type !== PhysicsJoint.SpringJoint) {\n this.world.addConstraint(constraint);\n }\n else {\n impostorJoint.joint.jointData.forceApplicationCallback =\n impostorJoint.joint.jointData.forceApplicationCallback ||\n function () {\n constraint.applyForce();\n };\n impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);\n }\n }\n removeJoint(impostorJoint) {\n if (impostorJoint.joint.type !== PhysicsJoint.SpringJoint) {\n this.world.removeConstraint(impostorJoint.joint.physicsJoint);\n }\n else {\n impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);\n }\n }\n _addMaterial(name, friction, restitution) {\n let index;\n let mat;\n for (index = 0; index < this._physicsMaterials.length; index++) {\n mat = this._physicsMaterials[index];\n if (mat.friction === friction && mat.restitution === restitution) {\n return mat;\n }\n }\n const currentMat = new this.BJSCANNON.Material(name);\n currentMat.friction = friction;\n currentMat.restitution = restitution;\n this._physicsMaterials.push(currentMat);\n return currentMat;\n }\n _checkWithEpsilon(value) {\n return value < Epsilon ? Epsilon : value;\n }\n _createShape(impostor) {\n const object = impostor.object;\n let returnValue;\n const impostorExtents = impostor.getObjectExtents();\n switch (impostor.type) {\n case PhysicsImpostor.SphereImpostor: {\n const radiusX = impostorExtents.x;\n const radiusY = impostorExtents.y;\n const radiusZ = impostorExtents.z;\n returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);\n break;\n }\n //TMP also for cylinder - TODO Cannon supports cylinder natively.\n case PhysicsImpostor.CylinderImpostor: {\n let nativeParams = impostor.getParam(\"nativeOptions\");\n if (!nativeParams) {\n nativeParams = {};\n }\n const radiusTop = nativeParams.radiusTop !== undefined ? nativeParams.radiusTop : this._checkWithEpsilon(impostorExtents.x) / 2;\n const radiusBottom = nativeParams.radiusBottom !== undefined ? nativeParams.radiusBottom : this._checkWithEpsilon(impostorExtents.x) / 2;\n const height = nativeParams.height !== undefined ? nativeParams.height : this._checkWithEpsilon(impostorExtents.y);\n const numSegments = nativeParams.numSegments !== undefined ? nativeParams.numSegments : 16;\n returnValue = new this.BJSCANNON.Cylinder(radiusTop, radiusBottom, height, numSegments);\n // Rotate 90 degrees as this shape is horizontal in cannon\n const quat = new this.BJSCANNON.Quaternion();\n quat.setFromAxisAngle(new this.BJSCANNON.Vec3(1, 0, 0), -Math.PI / 2);\n const translation = new this.BJSCANNON.Vec3(0, 0, 0);\n returnValue.transformAllPoints(translation, quat);\n break;\n }\n case PhysicsImpostor.BoxImpostor: {\n const box = impostorExtents.scale(0.5);\n returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));\n break;\n }\n case PhysicsImpostor.PlaneImpostor:\n Logger.Warn(\"Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead\");\n returnValue = new this.BJSCANNON.Plane();\n break;\n case PhysicsImpostor.MeshImpostor: {\n // should transform the vertex data to world coordinates!!\n const rawVerts = object.getVerticesData ? object.getVerticesData(VertexBuffer.PositionKind) : [];\n const rawFaces = object.getIndices ? object.getIndices() : [];\n if (!rawVerts) {\n Logger.Warn(\"Tried to create a MeshImpostor for an object without vertices. This will fail.\");\n return;\n }\n // get only scale! so the object could transform correctly.\n const oldPosition = object.position.clone();\n const oldRotation = object.rotation && object.rotation.clone();\n const oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();\n object.position.copyFromFloats(0, 0, 0);\n object.rotation && object.rotation.copyFromFloats(0, 0, 0);\n object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());\n object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();\n const transform = object.computeWorldMatrix(true);\n // convert rawVerts to object space\n const transformedVertices = new Array();\n let index;\n for (index = 0; index < rawVerts.length; index += 3) {\n Vector3.TransformCoordinates(Vector3.FromArray(rawVerts, index), transform).toArray(transformedVertices, index);\n }\n Logger.Warn(\"MeshImpostor only collides against spheres.\");\n returnValue = new this.BJSCANNON.Trimesh(transformedVertices, rawFaces);\n //now set back the transformation!\n object.position.copyFrom(oldPosition);\n oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);\n oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);\n break;\n }\n case PhysicsImpostor.HeightmapImpostor: {\n const oldPosition2 = object.position.clone();\n const oldRotation2 = object.rotation && object.rotation.clone();\n const oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();\n object.position.copyFromFloats(0, 0, 0);\n object.rotation && object.rotation.copyFromFloats(0, 0, 0);\n object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());\n object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();\n object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);\n returnValue = this._createHeightmap(object);\n object.position.copyFrom(oldPosition2);\n oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);\n oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);\n object.computeWorldMatrix(true);\n break;\n }\n case PhysicsImpostor.ParticleImpostor:\n returnValue = new this.BJSCANNON.Particle();\n break;\n case PhysicsImpostor.NoImpostor:\n returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(0, 0, 0));\n break;\n }\n return returnValue;\n }\n _createHeightmap(object, pointDepth) {\n let pos = object.getVerticesData(VertexBuffer.PositionKind);\n const transform = object.computeWorldMatrix(true);\n // convert rawVerts to object space\n const transformedVertices = new Array();\n let index;\n for (index = 0; index < pos.length; index += 3) {\n Vector3.TransformCoordinates(Vector3.FromArray(pos, index), transform).toArray(transformedVertices, index);\n }\n pos = transformedVertices;\n const matrix = new Array();\n //For now pointDepth will not be used and will be automatically calculated.\n //Future reference - try and find the best place to add a reference to the pointDepth variable.\n const arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);\n const boundingInfo = object.getBoundingInfo();\n const dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);\n const minY = boundingInfo.boundingBox.extendSizeWorld.z;\n const elementSize = (dim * 2) / arraySize;\n for (let i = 0; i < pos.length; i = i + 3) {\n const x = Math.round(pos[i + 0] / elementSize + arraySize / 2);\n const z = Math.round((pos[i + 1] / elementSize - arraySize / 2) * -1);\n const y = -pos[i + 2] + minY;\n if (!matrix[x]) {\n matrix[x] = [];\n }\n if (!matrix[x][z]) {\n matrix[x][z] = y;\n }\n matrix[x][z] = Math.max(y, matrix[x][z]);\n }\n for (let x = 0; x <= arraySize; ++x) {\n if (!matrix[x]) {\n let loc = 1;\n while (!matrix[(x + loc) % arraySize]) {\n loc++;\n }\n matrix[x] = matrix[(x + loc) % arraySize].slice();\n //console.log(\"missing x\", x);\n }\n for (let z = 0; z <= arraySize; ++z) {\n if (!matrix[x][z]) {\n let loc = 1;\n let newValue;\n while (newValue === undefined) {\n newValue = matrix[x][(z + loc++) % arraySize];\n }\n matrix[x][z] = newValue;\n }\n }\n }\n const shape = new this.BJSCANNON.Heightfield(matrix, {\n elementSize: elementSize,\n });\n //For future reference, needed for body transformation\n shape.minY = minY;\n return shape;\n }\n _updatePhysicsBodyTransformation(impostor) {\n const object = impostor.object;\n //make sure it is updated...\n object.computeWorldMatrix && object.computeWorldMatrix(true);\n if (!object.getBoundingInfo()) {\n return;\n }\n const center = impostor.getObjectCenter();\n //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)\n // The delta between the mesh position and the mesh bounding box center\n this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));\n this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);\n this._tmpPosition.copyFrom(center);\n let quaternion = object.rotationQuaternion;\n if (!quaternion) {\n return;\n }\n //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.\n //ideally these would be rotated at time of creation like cylinder but they dont extend ConvexPolyhedron\n if (impostor.type === PhysicsImpostor.PlaneImpostor || impostor.type === PhysicsImpostor.HeightmapImpostor) {\n //-90 DEG in X, precalculated\n quaternion = quaternion.multiply(this._minus90X);\n //Invert! (Precalculated, 90 deg in X)\n //No need to clone. this will never change.\n impostor.setDeltaRotation(this._plus90X);\n }\n //If it is a heightfield, if should be centered.\n if (impostor.type === PhysicsImpostor.HeightmapImpostor) {\n const mesh = object;\n let boundingInfo = mesh.getBoundingInfo();\n //calculate the correct body position:\n const rotationQuaternion = mesh.rotationQuaternion;\n mesh.rotationQuaternion = this._tmpUnityRotation;\n mesh.computeWorldMatrix(true);\n //get original center with no rotation\n const c = center.clone();\n let oldPivot = mesh.getPivotMatrix();\n if (oldPivot) {\n // create a copy the pivot Matrix as it is modified in place\n oldPivot = oldPivot.clone();\n }\n else {\n oldPivot = Matrix.Identity();\n }\n //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)\n const p = Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);\n mesh.setPreTransformMatrix(p);\n mesh.computeWorldMatrix(true);\n // force bounding box recomputation\n boundingInfo = mesh.getBoundingInfo();\n //calculate the translation\n const translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();\n this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);\n //add it inverted to the delta\n this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));\n this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;\n //rotation is back\n mesh.rotationQuaternion = rotationQuaternion;\n mesh.setPreTransformMatrix(oldPivot);\n mesh.computeWorldMatrix(true);\n }\n else if (impostor.type === PhysicsImpostor.MeshImpostor) {\n this._tmpDeltaPosition.copyFromFloats(0, 0, 0);\n }\n impostor.setDeltaPosition(this._tmpDeltaPosition);\n //Now update the impostor object\n impostor.physicsBody.position.set(this._tmpPosition.x, this._tmpPosition.y, this._tmpPosition.z);\n impostor.physicsBody.quaternion.set(quaternion.x, quaternion.y, quaternion.z, quaternion.w);\n }\n setTransformationFromPhysicsBody(impostor) {\n impostor.object.position.set(impostor.physicsBody.position.x, impostor.physicsBody.position.y, impostor.physicsBody.position.z);\n if (impostor.object.rotationQuaternion) {\n const q = impostor.physicsBody.quaternion;\n impostor.object.rotationQuaternion.set(q.x, q.y, q.z, q.w);\n }\n }\n setPhysicsBodyTransformation(impostor, newPosition, newRotation) {\n impostor.physicsBody.position.set(newPosition.x, newPosition.y, newPosition.z);\n impostor.physicsBody.quaternion.set(newRotation.x, newRotation.y, newRotation.z, newRotation.w);\n }\n isSupported() {\n return this.BJSCANNON !== undefined;\n }\n setLinearVelocity(impostor, velocity) {\n impostor.physicsBody.velocity.set(velocity.x, velocity.y, velocity.z);\n }\n setAngularVelocity(impostor, velocity) {\n impostor.physicsBody.angularVelocity.set(velocity.x, velocity.y, velocity.z);\n }\n getLinearVelocity(impostor) {\n const v = impostor.physicsBody.velocity;\n if (!v) {\n return null;\n }\n return new Vector3(v.x, v.y, v.z);\n }\n getAngularVelocity(impostor) {\n const v = impostor.physicsBody.angularVelocity;\n if (!v) {\n return null;\n }\n return new Vector3(v.x, v.y, v.z);\n }\n setBodyMass(impostor, mass) {\n impostor.physicsBody.mass = mass;\n impostor.physicsBody.updateMassProperties();\n }\n getBodyMass(impostor) {\n return impostor.physicsBody.mass;\n }\n getBodyFriction(impostor) {\n return impostor.physicsBody.material.friction;\n }\n setBodyFriction(impostor, friction) {\n impostor.physicsBody.material.friction = friction;\n }\n getBodyRestitution(impostor) {\n return impostor.physicsBody.material.restitution;\n }\n setBodyRestitution(impostor, restitution) {\n impostor.physicsBody.material.restitution = restitution;\n }\n sleepBody(impostor) {\n impostor.physicsBody.sleep();\n }\n wakeUpBody(impostor) {\n impostor.physicsBody.wakeUp();\n }\n updateDistanceJoint(joint, maxDistance) {\n joint.physicsJoint.distance = maxDistance;\n }\n setMotor(joint, speed, maxForce, motorIndex) {\n if (!motorIndex) {\n joint.physicsJoint.enableMotor();\n joint.physicsJoint.setMotorSpeed(speed);\n if (maxForce) {\n this.setLimit(joint, maxForce);\n }\n }\n }\n setLimit(joint, minForce, maxForce) {\n joint.physicsJoint.motorEquation.maxForce = maxForce;\n joint.physicsJoint.motorEquation.minForce = minForce === void 0 ? -minForce : minForce;\n }\n syncMeshWithImpostor(mesh, impostor) {\n const body = impostor.physicsBody;\n mesh.position.x = body.position.x;\n mesh.position.y = body.position.y;\n mesh.position.z = body.position.z;\n if (mesh.rotationQuaternion) {\n mesh.rotationQuaternion.x = body.quaternion.x;\n mesh.rotationQuaternion.y = body.quaternion.y;\n mesh.rotationQuaternion.z = body.quaternion.z;\n mesh.rotationQuaternion.w = body.quaternion.w;\n }\n }\n getRadius(impostor) {\n const shape = impostor.physicsBody.shapes[0];\n return shape.boundingSphereRadius;\n }\n getBoxSizeToRef(impostor, result) {\n const shape = impostor.physicsBody.shapes[0];\n result.x = shape.halfExtents.x * 2;\n result.y = shape.halfExtents.y * 2;\n result.z = shape.halfExtents.z * 2;\n }\n dispose() { }\n _extendNamespace() {\n //this will force cannon to execute at least one step when using interpolation\n const step_tmp1 = new this.BJSCANNON.Vec3();\n const engine = this.BJSCANNON;\n this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {\n maxSubSteps = maxSubSteps || 10;\n timeSinceLastCalled = timeSinceLastCalled || 0;\n if (timeSinceLastCalled === 0) {\n this.internalStep(dt);\n this.time += dt;\n }\n else {\n let internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);\n internalSteps = Math.min(internalSteps, maxSubSteps) || 1;\n const t0 = performance.now();\n for (let i = 0; i !== internalSteps; i++) {\n this.internalStep(dt);\n if (performance.now() - t0 > dt * 1000) {\n break;\n }\n }\n this.time += timeSinceLastCalled;\n const h = this.time % dt;\n const h_div_dt = h / dt;\n const interpvelo = step_tmp1;\n const bodies = this.bodies;\n for (let j = 0; j !== bodies.length; j++) {\n const b = bodies[j];\n if (b.type !== engine.Body.STATIC && b.sleepState !== engine.Body.SLEEPING) {\n b.position.vsub(b.previousPosition, interpvelo);\n interpvelo.scale(h_div_dt, interpvelo);\n b.position.vadd(interpvelo, b.interpolatedPosition);\n }\n else {\n b.interpolatedPosition.set(b.position.x, b.position.y, b.position.z);\n b.interpolatedQuaternion.set(b.quaternion.x, b.quaternion.y, b.quaternion.z, b.quaternion.w);\n }\n }\n }\n };\n }\n /**\n * Does a raycast in the physics world\n * @param from when should the ray start?\n * @param to when should the ray end?\n * @returns PhysicsRaycastResult\n */\n raycast(from, to) {\n this._raycastResult.reset(from, to);\n this.raycastToRef(from, to, this._raycastResult);\n return this._raycastResult;\n }\n /**\n * Does a raycast in the physics world\n * @param from when should the ray start?\n * @param to when should the ray end?\n * @param result resulting PhysicsRaycastResult\n */\n raycastToRef(from, to, result) {\n this._cannonRaycastResult.reset();\n this.world.raycastClosest(from, to, {}, this._cannonRaycastResult);\n result.reset(from, to);\n if (this._cannonRaycastResult.hasHit) {\n // TODO: do we also want to get the body it hit?\n result.setHitData({\n x: this._cannonRaycastResult.hitNormalWorld.x,\n y: this._cannonRaycastResult.hitNormalWorld.y,\n z: this._cannonRaycastResult.hitNormalWorld.z,\n }, {\n x: this._cannonRaycastResult.hitPointWorld.x,\n y: this._cannonRaycastResult.hitPointWorld.y,\n z: this._cannonRaycastResult.hitPointWorld.z,\n });\n result.setHitDistance(this._cannonRaycastResult.distance);\n }\n }\n}\nPhysicsEngine.DefaultPluginFactory = () => {\n return new CannonJSPlugin();\n};\n//# sourceMappingURL=cannonJSPlugin.js.map","import { PhysicsImpostor } from \"../physicsImpostor.js\";\nimport { PhysicsJoint } from \"../physicsJoint.js\";\nimport { Vector3, Quaternion } from \"../../../Maths/math.vector.js\";\nimport { Logger } from \"../../../Misc/logger.js\";\nimport { PhysicsRaycastResult } from \"../../physicsRaycastResult.js\";\nimport { Epsilon } from \"../../../Maths/math.constants.js\";\n/** @internal */\nexport class OimoJSPlugin {\n constructor(_useDeltaForWorldStep = true, iterations, oimoInjection = OIMO) {\n this._useDeltaForWorldStep = _useDeltaForWorldStep;\n this.name = \"OimoJSPlugin\";\n this._fixedTimeStep = 1 / 60;\n this._tmpImpostorsArray = [];\n this._tmpPositionVector = Vector3.Zero();\n this.BJSOIMO = oimoInjection;\n this.world = new this.BJSOIMO.World({\n iterations: iterations,\n });\n this.world.clear();\n this._raycastResult = new PhysicsRaycastResult();\n }\n /**\n *\n * @returns plugin version\n */\n getPluginVersion() {\n return 1;\n }\n setGravity(gravity) {\n this.world.gravity.set(gravity.x, gravity.y, gravity.z);\n }\n setTimeStep(timeStep) {\n this.world.timeStep = timeStep;\n }\n getTimeStep() {\n return this.world.timeStep;\n }\n executeStep(delta, impostors) {\n impostors.forEach(function (impostor) {\n impostor.beforeStep();\n });\n this.world.timeStep = this._useDeltaForWorldStep ? delta : this._fixedTimeStep;\n this.world.step();\n impostors.forEach((impostor) => {\n impostor.afterStep();\n //update the ordered impostors array\n this._tmpImpostorsArray[impostor.uniqueId] = impostor;\n });\n //check for collisions\n let contact = this.world.contacts;\n while (contact !== null) {\n if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {\n contact = contact.next;\n continue;\n }\n //is this body colliding with any other? get the impostor\n const mainImpostor = this._tmpImpostorsArray[+contact.body1.name];\n const collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];\n if (!mainImpostor || !collidingImpostor) {\n contact = contact.next;\n continue;\n }\n mainImpostor.onCollide({ body: collidingImpostor.physicsBody, point: null, distance: 0, impulse: 0, normal: null });\n collidingImpostor.onCollide({ body: mainImpostor.physicsBody, point: null, distance: 0, impulse: 0, normal: null });\n contact = contact.next;\n }\n }\n applyImpulse(impostor, force, contactPoint) {\n const mass = impostor.physicsBody.mass;\n impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));\n }\n applyForce(impostor, force, contactPoint) {\n Logger.Warn(\"Oimo doesn't support applying force. Using impulse instead.\");\n this.applyImpulse(impostor, force, contactPoint);\n }\n generatePhysicsBody(impostor) {\n //parent-child relationship. Does this impostor has a parent impostor?\n if (impostor.parent) {\n if (impostor.physicsBody) {\n this.removePhysicsBody(impostor);\n //TODO is that needed?\n impostor.forceUpdate();\n }\n return;\n }\n if (impostor.isBodyInitRequired()) {\n const bodyConfig = {\n name: impostor.uniqueId,\n //Oimo must have mass, also for static objects.\n config: [impostor.getParam(\"mass\") || 0.001, impostor.getParam(\"friction\"), impostor.getParam(\"restitution\")],\n size: [],\n type: [],\n pos: [],\n posShape: [],\n rot: [],\n rotShape: [],\n move: impostor.getParam(\"mass\") !== 0,\n density: impostor.getParam(\"mass\"),\n friction: impostor.getParam(\"friction\"),\n restitution: impostor.getParam(\"restitution\"),\n //Supporting older versions of Oimo\n world: this.world,\n };\n const impostors = [impostor];\n const addToArray = (parent) => {\n if (!parent.getChildMeshes) {\n return;\n }\n parent.getChildMeshes().forEach(function (m) {\n if (m.physicsImpostor) {\n impostors.push(m.physicsImpostor);\n //m.physicsImpostor._init();\n }\n });\n };\n addToArray(impostor.object);\n const checkWithEpsilon = (value) => {\n return Math.max(value, Epsilon);\n };\n const globalQuaternion = new Quaternion();\n impostors.forEach((i) => {\n if (!i.object.rotationQuaternion) {\n return;\n }\n //get the correct bounding box\n const oldQuaternion = i.object.rotationQuaternion;\n globalQuaternion.copyFrom(oldQuaternion);\n i.object.rotationQuaternion.set(0, 0, 0, 1);\n i.object.computeWorldMatrix(true);\n const rot = globalQuaternion.toEulerAngles();\n const impostorExtents = i.getObjectExtents();\n // eslint-disable-next-line no-loss-of-precision\n const radToDeg = 57.295779513082320876;\n if (i === impostor) {\n const center = impostor.getObjectCenter();\n impostor.object.getAbsolutePivotPoint().subtractToRef(center, this._tmpPositionVector);\n this._tmpPositionVector.divideInPlace(impostor.object.scaling);\n //Can also use Array.prototype.push.apply\n bodyConfig.pos.push(center.x);\n bodyConfig.pos.push(center.y);\n bodyConfig.pos.push(center.z);\n bodyConfig.posShape.push(0, 0, 0);\n bodyConfig.rotShape.push(0, 0, 0);\n }\n else {\n const localPosition = i.object.position.clone();\n bodyConfig.posShape.push(localPosition.x);\n bodyConfig.posShape.push(localPosition.y);\n bodyConfig.posShape.push(localPosition.z);\n // bodyConfig.pos.push(0, 0, 0);\n bodyConfig.rotShape.push(rot.x * radToDeg, rot.y * radToDeg, rot.z * radToDeg);\n }\n i.object.rotationQuaternion.copyFrom(globalQuaternion);\n // register mesh\n switch (i.type) {\n case PhysicsImpostor.ParticleImpostor:\n Logger.Warn(\"No Particle support in OIMO.js. using SphereImpostor instead\");\n // eslint-disable-next-line no-fallthrough\n case PhysicsImpostor.SphereImpostor: {\n const radiusX = impostorExtents.x;\n const radiusY = impostorExtents.y;\n const radiusZ = impostorExtents.z;\n const size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;\n bodyConfig.type.push(\"sphere\");\n //due to the way oimo works with compounds, add 3 times\n bodyConfig.size.push(size);\n bodyConfig.size.push(size);\n bodyConfig.size.push(size);\n break;\n }\n case PhysicsImpostor.CylinderImpostor: {\n const sizeX = checkWithEpsilon(impostorExtents.x) / 2;\n const sizeY = checkWithEpsilon(impostorExtents.y);\n bodyConfig.type.push(\"cylinder\");\n bodyConfig.size.push(sizeX);\n bodyConfig.size.push(sizeY);\n //due to the way oimo works with compounds, add one more value.\n bodyConfig.size.push(sizeY);\n break;\n }\n case PhysicsImpostor.PlaneImpostor:\n case PhysicsImpostor.BoxImpostor:\n default: {\n const sizeX = checkWithEpsilon(impostorExtents.x);\n const sizeY = checkWithEpsilon(impostorExtents.y);\n const sizeZ = checkWithEpsilon(impostorExtents.z);\n bodyConfig.type.push(\"box\");\n //if (i === impostor) {\n bodyConfig.size.push(sizeX);\n bodyConfig.size.push(sizeY);\n bodyConfig.size.push(sizeZ);\n //} else {\n // bodyConfig.size.push(0,0,0);\n //}\n break;\n }\n }\n //actually not needed, but hey...\n i.object.rotationQuaternion = oldQuaternion;\n });\n impostor.physicsBody = this.world.add(bodyConfig);\n // set the quaternion, ignoring the previously defined (euler) rotation\n impostor.physicsBody.resetQuaternion(globalQuaternion);\n // update with delta 0, so the body will receive the new rotation.\n impostor.physicsBody.updatePosition(0);\n }\n else {\n this._tmpPositionVector.copyFromFloats(0, 0, 0);\n }\n impostor.setDeltaPosition(this._tmpPositionVector);\n //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);\n //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);\n }\n removePhysicsBody(impostor) {\n //impostor.physicsBody.dispose();\n this.world.removeRigidBody(impostor.physicsBody);\n }\n generateJoint(impostorJoint) {\n const mainBody = impostorJoint.mainImpostor.physicsBody;\n const connectedBody = impostorJoint.connectedImpostor.physicsBody;\n if (!mainBody || !connectedBody) {\n return;\n }\n const jointData = impostorJoint.joint.jointData;\n const options = jointData.nativeParams || {};\n let type;\n const nativeJointData = {\n body1: mainBody,\n body2: connectedBody,\n axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),\n axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),\n pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),\n pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),\n min: options.min,\n max: options.max,\n collision: options.collision || jointData.collision,\n spring: options.spring,\n //supporting older version of Oimo\n world: this.world,\n };\n switch (impostorJoint.joint.type) {\n case PhysicsJoint.BallAndSocketJoint:\n type = \"jointBall\";\n break;\n case PhysicsJoint.SpringJoint: {\n Logger.Warn(\"OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead\");\n const springData = jointData;\n nativeJointData.min = springData.length || nativeJointData.min;\n //Max should also be set, just make sure it is at least min\n nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);\n }\n // eslint-disable-next-line no-fallthrough\n case PhysicsJoint.DistanceJoint:\n type = \"jointDistance\";\n nativeJointData.max = jointData.maxDistance;\n break;\n case PhysicsJoint.PrismaticJoint:\n type = \"jointPrisme\";\n break;\n case PhysicsJoint.SliderJoint:\n type = \"jointSlide\";\n break;\n case PhysicsJoint.WheelJoint:\n type = \"jointWheel\";\n break;\n case PhysicsJoint.HingeJoint:\n default:\n type = \"jointHinge\";\n break;\n }\n nativeJointData.type = type;\n impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);\n }\n removeJoint(impostorJoint) {\n //Bug in Oimo prevents us from disposing a joint in the playground\n //joint.joint.physicsJoint.dispose();\n //So we will bruteforce it!\n try {\n this.world.removeJoint(impostorJoint.joint.physicsJoint);\n }\n catch (e) {\n Logger.Warn(e);\n }\n }\n isSupported() {\n return this.BJSOIMO !== undefined;\n }\n setTransformationFromPhysicsBody(impostor) {\n if (!impostor.physicsBody.sleeping) {\n if (impostor.physicsBody.shapes.next) {\n let parent = impostor.physicsBody.shapes;\n while (parent.next) {\n parent = parent.next;\n }\n impostor.object.position.set(parent.position.x, parent.position.y, parent.position.z);\n }\n else {\n const pos = impostor.physicsBody.getPosition();\n impostor.object.position.set(pos.x, pos.y, pos.z);\n }\n if (impostor.object.rotationQuaternion) {\n const quat = impostor.physicsBody.getQuaternion();\n impostor.object.rotationQuaternion.set(quat.x, quat.y, quat.z, quat.w);\n }\n }\n }\n setPhysicsBodyTransformation(impostor, newPosition, newRotation) {\n const body = impostor.physicsBody;\n // disable bidirectional for compound meshes\n if (impostor.physicsBody.shapes.next) {\n return;\n }\n body.position.set(newPosition.x, newPosition.y, newPosition.z);\n body.orientation.set(newRotation.x, newRotation.y, newRotation.z, newRotation.w);\n body.syncShapes();\n body.awake();\n }\n /*private _getLastShape(body: any): any {\n var lastShape = body.shapes;\n while (lastShape.next) {\n lastShape = lastShape.next;\n }\n return lastShape;\n }*/\n setLinearVelocity(impostor, velocity) {\n impostor.physicsBody.linearVelocity.set(velocity.x, velocity.y, velocity.z);\n }\n setAngularVelocity(impostor, velocity) {\n impostor.physicsBody.angularVelocity.set(velocity.x, velocity.y, velocity.z);\n }\n getLinearVelocity(impostor) {\n const v = impostor.physicsBody.linearVelocity;\n if (!v) {\n return null;\n }\n return new Vector3(v.x, v.y, v.z);\n }\n getAngularVelocity(impostor) {\n const v = impostor.physicsBody.angularVelocity;\n if (!v) {\n return null;\n }\n return new Vector3(v.x, v.y, v.z);\n }\n setBodyMass(impostor, mass) {\n const staticBody = mass === 0;\n //this will actually set the body's density and not its mass.\n //But this is how oimo treats the mass variable.\n impostor.physicsBody.shapes.density = staticBody ? 1 : mass;\n impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);\n }\n getBodyMass(impostor) {\n return impostor.physicsBody.shapes.density;\n }\n getBodyFriction(impostor) {\n return impostor.physicsBody.shapes.friction;\n }\n setBodyFriction(impostor, friction) {\n impostor.physicsBody.shapes.friction = friction;\n }\n getBodyRestitution(impostor) {\n return impostor.physicsBody.shapes.restitution;\n }\n setBodyRestitution(impostor, restitution) {\n impostor.physicsBody.shapes.restitution = restitution;\n }\n sleepBody(impostor) {\n impostor.physicsBody.sleep();\n }\n wakeUpBody(impostor) {\n impostor.physicsBody.awake();\n }\n updateDistanceJoint(joint, maxDistance, minDistance) {\n joint.physicsJoint.limitMotor.upperLimit = maxDistance;\n if (minDistance !== void 0) {\n joint.physicsJoint.limitMotor.lowerLimit = minDistance;\n }\n }\n setMotor(joint, speed, force, motorIndex) {\n if (force !== undefined) {\n Logger.Warn(\"OimoJS plugin currently has unexpected behavior when using setMotor with force parameter\");\n }\n else {\n force = 1e6;\n }\n speed *= -1;\n //TODO separate rotational and transational motors.\n const motor = motorIndex\n ? joint.physicsJoint.rotationalLimitMotor2\n : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;\n if (motor) {\n motor.setMotor(speed, force);\n }\n }\n setLimit(joint, upperLimit, lowerLimit, motorIndex) {\n //TODO separate rotational and transational motors.\n const motor = motorIndex\n ? joint.physicsJoint.rotationalLimitMotor2\n : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;\n if (motor) {\n motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);\n }\n }\n syncMeshWithImpostor(mesh, impostor) {\n const body = impostor.physicsBody;\n mesh.position.x = body.position.x;\n mesh.position.y = body.position.y;\n mesh.position.z = body.position.z;\n if (mesh.rotationQuaternion) {\n mesh.rotationQuaternion.x = body.orientation.x;\n mesh.rotationQuaternion.y = body.orientation.y;\n mesh.rotationQuaternion.z = body.orientation.z;\n mesh.rotationQuaternion.w = body.orientation.w;\n }\n }\n getRadius(impostor) {\n return impostor.physicsBody.shapes.radius;\n }\n getBoxSizeToRef(impostor, result) {\n const shape = impostor.physicsBody.shapes;\n result.x = shape.halfWidth * 2;\n result.y = shape.halfHeight * 2;\n result.z = shape.halfDepth * 2;\n }\n dispose() {\n this.world.clear();\n }\n /**\n * Does a raycast in the physics world\n * @param from when should the ray start?\n * @param to when should the ray end?\n * @returns PhysicsRaycastResult\n */\n raycast(from, to) {\n Logger.Warn(\"raycast is not currently supported by the Oimo physics plugin\");\n this._raycastResult.reset(from, to);\n return this._raycastResult;\n }\n /**\n * Does a raycast in the physics world\n * @param from when should the ray start?\n * @param to when should the ray end?\n * @param result resulting PhysicsRaycastResult\n */\n raycastToRef(from, to, result) {\n Logger.Warn(\"raycast is not currently supported by the Oimo physics plugin\");\n result.reset(from, to);\n }\n}\n//# sourceMappingURL=oimoJSPlugin.js.map","import { Quaternion, Vector3, Matrix } from \"../../../Maths/math.vector.js\";\nimport { Logger } from \"../../../Misc/logger.js\";\nimport { PhysicsImpostor } from \"../physicsImpostor.js\";\nimport { PhysicsJoint } from \"../physicsJoint.js\";\nimport { VertexBuffer } from \"../../../Buffers/buffer.js\";\nimport { VertexData } from \"../../../Meshes/mesh.vertexData.js\";\nimport { ExtrudeShape } from \"../../../Meshes/Builders/shapeBuilder.js\";\nimport { CreateLines } from \"../../../Meshes/Builders/linesBuilder.js\";\nimport { PhysicsRaycastResult } from \"../../physicsRaycastResult.js\";\nimport { Scalar } from \"../../../Maths/math.scalar.js\";\nimport { Epsilon } from \"../../../Maths/math.constants.js\";\n/**\n * AmmoJS Physics plugin\n * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine\n * @see https://github.com/kripken/ammo.js/\n */\nexport class AmmoJSPlugin {\n /**\n * Initializes the ammoJS plugin\n * @param _useDeltaForWorldStep if the time between frames should be used when calculating physics steps (Default: true)\n * @param ammoInjection can be used to inject your own ammo reference\n * @param overlappingPairCache can be used to specify your own overlapping pair cache\n */\n constructor(_useDeltaForWorldStep = true, ammoInjection = Ammo, overlappingPairCache = null) {\n this._useDeltaForWorldStep = _useDeltaForWorldStep;\n /**\n * Reference to the Ammo library\n */\n this.bjsAMMO = {};\n /**\n * Name of the plugin\n */\n this.name = \"AmmoJSPlugin\";\n this._timeStep = 1 / 60;\n this._fixedTimeStep = 1 / 60;\n this._maxSteps = 5;\n this._tmpQuaternion = new Quaternion();\n this._tmpContactCallbackResult = false;\n this._tmpContactPoint = new Vector3();\n this._tmpContactNormal = new Vector3();\n this._tmpVec3 = new Vector3();\n this._tmpMatrix = new Matrix();\n if (typeof ammoInjection === \"function\") {\n Logger.Error(\"AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.\");\n return;\n }\n else {\n this.bjsAMMO = ammoInjection;\n }\n if (!this.isSupported()) {\n Logger.Error(\"AmmoJS is not available. Please make sure you included the js file.\");\n return;\n }\n // Initialize the physics world\n this._collisionConfiguration = new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration();\n this._dispatcher = new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration);\n this._overlappingPairCache = overlappingPairCache || new this.bjsAMMO.btDbvtBroadphase();\n this._solver = new this.bjsAMMO.btSequentialImpulseConstraintSolver();\n this._softBodySolver = new this.bjsAMMO.btDefaultSoftBodySolver();\n this.world = new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher, this._overlappingPairCache, this._solver, this._collisionConfiguration, this._softBodySolver);\n this._tmpAmmoConcreteContactResultCallback = new this.bjsAMMO.ConcreteContactResultCallback();\n this._tmpAmmoConcreteContactResultCallback.addSingleResult = (contactPoint) => {\n contactPoint = this.bjsAMMO.wrapPointer(contactPoint, this.bjsAMMO.btManifoldPoint);\n const worldPoint = contactPoint.getPositionWorldOnA();\n const worldNormal = contactPoint.m_normalWorldOnB;\n this._tmpContactPoint.x = worldPoint.x();\n this._tmpContactPoint.y = worldPoint.y();\n this._tmpContactPoint.z = worldPoint.z();\n this._tmpContactNormal.x = worldNormal.x();\n this._tmpContactNormal.y = worldNormal.y();\n this._tmpContactNormal.z = worldNormal.z();\n this._tmpContactImpulse = contactPoint.getAppliedImpulse();\n this._tmpContactDistance = contactPoint.getDistance();\n this._tmpContactCallbackResult = true;\n };\n this._raycastResult = new PhysicsRaycastResult();\n // Create temp ammo variables\n this._tmpAmmoTransform = new this.bjsAMMO.btTransform();\n this._tmpAmmoTransform.setIdentity();\n this._tmpAmmoQuaternion = new this.bjsAMMO.btQuaternion(0, 0, 0, 1);\n this._tmpAmmoVectorA = new this.bjsAMMO.btVector3(0, 0, 0);\n this._tmpAmmoVectorB = new this.bjsAMMO.btVector3(0, 0, 0);\n this._tmpAmmoVectorC = new this.bjsAMMO.btVector3(0, 0, 0);\n this._tmpAmmoVectorD = new this.bjsAMMO.btVector3(0, 0, 0);\n }\n /**\n *\n * @returns plugin version\n */\n getPluginVersion() {\n return 1;\n }\n /**\n * Sets the gravity of the physics world (m/(s^2))\n * @param gravity Gravity to set\n */\n setGravity(gravity) {\n this._tmpAmmoVectorA.setValue(gravity.x, gravity.y, gravity.z);\n this.world.setGravity(this._tmpAmmoVectorA);\n this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA);\n }\n /**\n * Amount of time to step forward on each frame (only used if useDeltaForWorldStep is false in the constructor)\n * @param timeStep timestep to use in seconds\n */\n setTimeStep(timeStep) {\n this._timeStep = timeStep;\n }\n /**\n * Increment to step forward in the physics engine (If timeStep is set to 1/60 and fixedTimeStep is set to 1/120 the physics engine should run 2 steps per frame) (Default: 1/60)\n * @param fixedTimeStep fixedTimeStep to use in seconds\n */\n setFixedTimeStep(fixedTimeStep) {\n this._fixedTimeStep = fixedTimeStep;\n }\n /**\n * Sets the maximum number of steps by the physics engine per frame (Default: 5)\n * @param maxSteps the maximum number of steps by the physics engine per frame\n */\n setMaxSteps(maxSteps) {\n this._maxSteps = maxSteps;\n }\n /**\n * Gets the current timestep (only used if useDeltaForWorldStep is false in the constructor)\n * @returns the current timestep in seconds\n */\n getTimeStep() {\n return this._timeStep;\n }\n // Ammo's contactTest and contactPairTest take a callback that runs synchronously, wrap them so that they are easier to consume\n _isImpostorInContact(impostor) {\n this._tmpContactCallbackResult = false;\n this.world.contactTest(impostor.physicsBody, this._tmpAmmoConcreteContactResultCallback);\n return this._tmpContactCallbackResult;\n }\n // Ammo's collision events have some weird quirks\n // contactPairTest fires too many events as it fires events even when objects are close together but contactTest does not\n // so only fire event if both contactTest and contactPairTest have a hit\n _isImpostorPairInContact(impostorA, impostorB) {\n this._tmpContactCallbackResult = false;\n this.world.contactPairTest(impostorA.physicsBody, impostorB.physicsBody, this._tmpAmmoConcreteContactResultCallback);\n return this._tmpContactCallbackResult;\n }\n // Ammo's behavior when maxSteps > 0 does not behave as described in docs\n // @see http://www.bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World\n //\n // When maxSteps is 0 do the entire simulation in one step\n // When maxSteps is > 0, run up to maxStep times, if on the last step the (remaining step - fixedTimeStep) is < fixedTimeStep, the remainder will be used for the step. (eg. if remainder is 1.001 and fixedTimeStep is 1 the last step will be 1.001, if instead it did 2 steps (1, 0.001) issues occuered when having a tiny step in ammo)\n // Note: To get deterministic physics, timeStep would always need to be divisible by fixedTimeStep\n _stepSimulation(timeStep = 1 / 60, maxSteps = 10, fixedTimeStep = 1 / 60) {\n if (maxSteps == 0) {\n this.world.stepSimulation(timeStep, 0);\n }\n else {\n while (maxSteps > 0 && timeStep > 0) {\n if (timeStep - fixedTimeStep < fixedTimeStep) {\n this.world.stepSimulation(timeStep, 0);\n timeStep = 0;\n }\n else {\n timeStep -= fixedTimeStep;\n this.world.stepSimulation(fixedTimeStep, 0);\n }\n maxSteps--;\n }\n }\n }\n /**\n * Moves the physics simulation forward delta seconds and updates the given physics imposters\n * Prior to the step the imposters physics location is set to the position of the babylon meshes\n * After the step the babylon meshes are set to the position of the physics imposters\n * @param delta amount of time to step forward\n * @param impostors array of imposters to update before/after the step\n */\n executeStep(delta, impostors) {\n for (const impostor of impostors) {\n // Update physics world objects to match babylon world\n if (!impostor.soft) {\n impostor.beforeStep();\n }\n }\n this._stepSimulation(this._useDeltaForWorldStep ? delta : this._timeStep, this._maxSteps, this._fixedTimeStep);\n for (const mainImpostor of impostors) {\n // After physics update make babylon world objects match physics world objects\n if (mainImpostor.soft) {\n this._afterSoftStep(mainImpostor);\n }\n else {\n mainImpostor.afterStep();\n }\n // Handle collision event\n if (mainImpostor._onPhysicsCollideCallbacks.length > 0) {\n if (this._isImpostorInContact(mainImpostor)) {\n for (const collideCallback of mainImpostor._onPhysicsCollideCallbacks) {\n for (const otherImpostor of collideCallback.otherImpostors) {\n if (mainImpostor.physicsBody.isActive() || otherImpostor.physicsBody.isActive()) {\n if (this._isImpostorPairInContact(mainImpostor, otherImpostor)) {\n mainImpostor.onCollide({\n body: otherImpostor.physicsBody,\n point: this._tmpContactPoint,\n distance: this._tmpContactDistance,\n impulse: this._tmpContactImpulse,\n normal: this._tmpContactNormal,\n });\n otherImpostor.onCollide({\n body: mainImpostor.physicsBody,\n point: this._tmpContactPoint,\n distance: this._tmpContactDistance,\n impulse: this._tmpContactImpulse,\n normal: this._tmpContactNormal,\n });\n }\n }\n }\n }\n }\n }\n }\n }\n /**\n * Update babylon mesh to match physics world object\n * @param impostor imposter to match\n */\n _afterSoftStep(impostor) {\n if (impostor.type === PhysicsImpostor.RopeImpostor) {\n this._ropeStep(impostor);\n }\n else {\n this._softbodyOrClothStep(impostor);\n }\n }\n /**\n * Update babylon mesh vertices vertices to match physics world softbody or cloth\n * @param impostor imposter to match\n */\n _ropeStep(impostor) {\n const bodyVertices = impostor.physicsBody.get_m_nodes();\n const nbVertices = bodyVertices.size();\n let node;\n let nodePositions;\n let x, y, z;\n const path = new Array();\n for (let n = 0; n < nbVertices; n++) {\n node = bodyVertices.at(n);\n nodePositions = node.get_m_x();\n x = nodePositions.x();\n y = nodePositions.y();\n z = nodePositions.z();\n path.push(new Vector3(x, y, z));\n }\n const object = impostor.object;\n const shape = impostor.getParam(\"shape\");\n if (impostor._isFromLine) {\n impostor.object = CreateLines(\"lines\", { points: path, instance: object });\n }\n else {\n impostor.object = ExtrudeShape(\"ext\", { shape: shape, path: path, instance: object });\n }\n }\n /**\n * Update babylon mesh vertices vertices to match physics world softbody or cloth\n * @param impostor imposter to match\n */\n _softbodyOrClothStep(impostor) {\n const normalDirection = impostor.type === PhysicsImpostor.ClothImpostor ? 1 : -1;\n const object = impostor.object;\n let vertexPositions = object.getVerticesData(VertexBuffer.PositionKind);\n if (!vertexPositions) {\n vertexPositions = [];\n }\n let vertexNormals = object.getVerticesData(VertexBuffer.NormalKind);\n if (!vertexNormals) {\n vertexNormals = [];\n }\n const nbVertices = vertexPositions.length / 3;\n const bodyVertices = impostor.physicsBody.get_m_nodes();\n let node;\n let nodePositions;\n let x, y, z;\n let nx, ny, nz;\n for (let n = 0; n < nbVertices; n++) {\n node = bodyVertices.at(n);\n nodePositions = node.get_m_x();\n x = nodePositions.x();\n y = nodePositions.y();\n z = nodePositions.z() * normalDirection;\n const nodeNormals = node.get_m_n();\n nx = nodeNormals.x();\n ny = nodeNormals.y();\n nz = nodeNormals.z() * normalDirection;\n vertexPositions[3 * n] = x;\n vertexPositions[3 * n + 1] = y;\n vertexPositions[3 * n + 2] = z;\n vertexNormals[3 * n] = nx;\n vertexNormals[3 * n + 1] = ny;\n vertexNormals[3 * n + 2] = nz;\n }\n const vertex_data = new VertexData();\n vertex_data.positions = vertexPositions;\n vertex_data.normals = vertexNormals;\n vertex_data.uvs = object.getVerticesData(VertexBuffer.UVKind);\n vertex_data.colors = object.getVerticesData(VertexBuffer.ColorKind);\n if (object && object.getIndices) {\n vertex_data.indices = object.getIndices();\n }\n vertex_data.applyToMesh(object);\n }\n /**\n * Applies an impulse on the imposter\n * @param impostor imposter to apply impulse to\n * @param force amount of force to be applied to the imposter\n * @param contactPoint the location to apply the impulse on the imposter\n */\n applyImpulse(impostor, force, contactPoint) {\n if (!impostor.soft) {\n impostor.physicsBody.activate();\n const worldPoint = this._tmpAmmoVectorA;\n const impulse = this._tmpAmmoVectorB;\n // Convert contactPoint relative to center of mass\n if (impostor.object && impostor.object.getWorldMatrix) {\n contactPoint.subtractInPlace(impostor.object.getWorldMatrix().getTranslation());\n }\n worldPoint.setValue(contactPoint.x, contactPoint.y, contactPoint.z);\n impulse.setValue(force.x, force.y, force.z);\n impostor.physicsBody.applyImpulse(impulse, worldPoint);\n }\n else {\n Logger.Warn(\"Cannot be applied to a soft body\");\n }\n }\n /**\n * Applies a force on the imposter\n * @param impostor imposter to apply force\n * @param force amount of force to be applied to the imposter\n * @param contactPoint the location to apply the force on the imposter\n */\n applyForce(impostor, force, contactPoint) {\n if (!impostor.soft) {\n impostor.physicsBody.activate();\n const worldPoint = this._tmpAmmoVectorA;\n const impulse = this._tmpAmmoVectorB;\n // Convert contactPoint relative to center of mass\n if (impostor.object && impostor.object.getWorldMatrix) {\n const localTranslation = impostor.object.getWorldMatrix().getTranslation();\n worldPoint.setValue(contactPoint.x - localTranslation.x, contactPoint.y - localTranslation.y, contactPoint.z - localTranslation.z);\n }\n else {\n worldPoint.setValue(contactPoint.x, contactPoint.y, contactPoint.z);\n }\n impulse.setValue(force.x, force.y, force.z);\n impostor.physicsBody.applyForce(impulse, worldPoint);\n }\n else {\n Logger.Warn(\"Cannot be applied to a soft body\");\n }\n }\n /**\n * Creates a physics body using the plugin\n * @param impostor the imposter to create the physics body on\n */\n generatePhysicsBody(impostor) {\n // Note: this method will not be called on child imposotrs for compound impostors\n impostor._pluginData.toDispose = [];\n //parent-child relationship\n if (impostor.parent) {\n if (impostor.physicsBody) {\n this.removePhysicsBody(impostor);\n impostor.forceUpdate();\n }\n return;\n }\n if (impostor.isBodyInitRequired()) {\n const colShape = this._createShape(impostor);\n const mass = impostor.getParam(\"mass\");\n impostor._pluginData.mass = mass;\n if (impostor.soft) {\n colShape.get_m_cfg().set_collisions(0x11);\n colShape.get_m_cfg().set_kDP(impostor.getParam(\"damping\"));\n this.bjsAMMO.castObject(colShape, this.bjsAMMO.btCollisionObject).getCollisionShape().setMargin(impostor.getParam(\"margin\"));\n colShape.setActivationState(AmmoJSPlugin._DISABLE_DEACTIVATION_FLAG);\n this.world.addSoftBody(colShape, 1, -1);\n impostor.physicsBody = colShape;\n impostor._pluginData.toDispose.push(colShape);\n this.setBodyPressure(impostor, 0);\n if (impostor.type === PhysicsImpostor.SoftbodyImpostor) {\n this.setBodyPressure(impostor, impostor.getParam(\"pressure\"));\n }\n this.setBodyStiffness(impostor, impostor.getParam(\"stiffness\"));\n this.setBodyVelocityIterations(impostor, impostor.getParam(\"velocityIterations\"));\n this.setBodyPositionIterations(impostor, impostor.getParam(\"positionIterations\"));\n }\n else {\n const localInertia = new this.bjsAMMO.btVector3(0, 0, 0);\n const startTransform = new this.bjsAMMO.btTransform();\n impostor.object.computeWorldMatrix(true);\n startTransform.setIdentity();\n if (mass !== 0) {\n colShape.calculateLocalInertia(mass, localInertia);\n }\n this._tmpAmmoVectorA.setValue(impostor.object.position.x, impostor.object.position.y, impostor.object.position.z);\n this._tmpAmmoQuaternion.setValue(impostor.object.rotationQuaternion.x, impostor.object.rotationQuaternion.y, impostor.object.rotationQuaternion.z, impostor.object.rotationQuaternion.w);\n startTransform.setOrigin(this._tmpAmmoVectorA);\n startTransform.setRotation(this._tmpAmmoQuaternion);\n const myMotionState = new this.bjsAMMO.btDefaultMotionState(startTransform);\n const rbInfo = new this.bjsAMMO.btRigidBodyConstructionInfo(mass, myMotionState, colShape, localInertia);\n const body = new this.bjsAMMO.btRigidBody(rbInfo);\n // Make objects kinematic if it's mass is 0\n if (mass === 0) {\n body.setCollisionFlags(body.getCollisionFlags() | AmmoJSPlugin._KINEMATIC_FLAG);\n body.setActivationState(AmmoJSPlugin._DISABLE_DEACTIVATION_FLAG);\n }\n // Disable collision if NoImpostor, but keep collision if shape is btCompoundShape\n if (impostor.type == PhysicsImpostor.NoImpostor && !colShape.getChildShape) {\n body.setCollisionFlags(body.getCollisionFlags() | AmmoJSPlugin._DISABLE_COLLISION_FLAG);\n }\n // compute delta position: compensate the difference between shape center and mesh origin\n if (impostor.type !== PhysicsImpostor.MeshImpostor && impostor.type !== PhysicsImpostor.NoImpostor) {\n const boundingInfo = impostor.object.getBoundingInfo();\n this._tmpVec3.copyFrom(impostor.object.getAbsolutePosition());\n this._tmpVec3.subtractInPlace(boundingInfo.boundingBox.centerWorld);\n this._tmpVec3.x /= impostor.object.scaling.x;\n this._tmpVec3.y /= impostor.object.scaling.y;\n this._tmpVec3.z /= impostor.object.scaling.z;\n impostor.setDeltaPosition(this._tmpVec3);\n }\n const group = impostor.getParam(\"group\");\n const mask = impostor.getParam(\"mask\");\n if (group && mask) {\n this.world.addRigidBody(body, group, mask);\n }\n else {\n this.world.addRigidBody(body);\n }\n impostor.physicsBody = body;\n impostor._pluginData.toDispose = impostor._pluginData.toDispose.concat([body, rbInfo, myMotionState, startTransform, localInertia, colShape]);\n }\n this.setBodyRestitution(impostor, impostor.getParam(\"restitution\"));\n this.setBodyFriction(impostor, impostor.getParam(\"friction\"));\n }\n }\n /**\n * Removes the physics body from the imposter and disposes of the body's memory\n * @param impostor imposter to remove the physics body from\n */\n removePhysicsBody(impostor) {\n if (this.world) {\n if (impostor.soft) {\n this.world.removeSoftBody(impostor.physicsBody);\n }\n else {\n this.world.removeRigidBody(impostor.physicsBody);\n }\n if (impostor._pluginData) {\n impostor._pluginData.toDispose.forEach((d) => {\n this.bjsAMMO.destroy(d);\n });\n impostor._pluginData.toDispose = [];\n }\n }\n }\n /**\n * Generates a joint\n * @param impostorJoint the imposter joint to create the joint with\n */\n generateJoint(impostorJoint) {\n const mainBody = impostorJoint.mainImpostor.physicsBody;\n const connectedBody = impostorJoint.connectedImpostor.physicsBody;\n if (!mainBody || !connectedBody) {\n return;\n }\n const jointData = impostorJoint.joint.jointData;\n if (!jointData.mainPivot) {\n jointData.mainPivot = new Vector3(0, 0, 0);\n }\n if (!jointData.connectedPivot) {\n jointData.connectedPivot = new Vector3(0, 0, 0);\n }\n let joint;\n switch (impostorJoint.joint.type) {\n case PhysicsJoint.DistanceJoint: {\n const distance = jointData.maxDistance;\n if (distance) {\n jointData.mainPivot = new Vector3(0, -distance / 2, 0);\n jointData.connectedPivot = new Vector3(0, distance / 2, 0);\n }\n joint = new this.bjsAMMO.btPoint2PointConstraint(mainBody, connectedBody, new this.bjsAMMO.btVector3(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z), new this.bjsAMMO.btVector3(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z));\n break;\n }\n case PhysicsJoint.HingeJoint: {\n if (!jointData.mainAxis) {\n jointData.mainAxis = new Vector3(0, 0, 0);\n }\n if (!jointData.connectedAxis) {\n jointData.connectedAxis = new Vector3(0, 0, 0);\n }\n const mainAxis = new this.bjsAMMO.btVector3(jointData.mainAxis.x, jointData.mainAxis.y, jointData.mainAxis.z);\n const connectedAxis = new this.bjsAMMO.btVector3(jointData.connectedAxis.x, jointData.connectedAxis.y, jointData.connectedAxis.z);\n joint = new this.bjsAMMO.btHingeConstraint(mainBody, connectedBody, new this.bjsAMMO.btVector3(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z), new this.bjsAMMO.btVector3(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z), mainAxis, connectedAxis);\n break;\n }\n case PhysicsJoint.BallAndSocketJoint:\n joint = new this.bjsAMMO.btPoint2PointConstraint(mainBody, connectedBody, new this.bjsAMMO.btVector3(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z), new this.bjsAMMO.btVector3(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z));\n break;\n default:\n Logger.Warn(\"JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint\");\n joint = new this.bjsAMMO.btPoint2PointConstraint(mainBody, connectedBody, new this.bjsAMMO.btVector3(jointData.mainPivot.x, jointData.mainPivot.y, jointData.mainPivot.z), new this.bjsAMMO.btVector3(jointData.connectedPivot.x, jointData.connectedPivot.y, jointData.connectedPivot.z));\n break;\n }\n this.world.addConstraint(joint, !impostorJoint.joint.jointData.collision);\n impostorJoint.joint.physicsJoint = joint;\n }\n /**\n * Removes a joint\n * @param impostorJoint the imposter joint to remove the joint from\n */\n removeJoint(impostorJoint) {\n if (this.world) {\n this.world.removeConstraint(impostorJoint.joint.physicsJoint);\n }\n }\n // adds all verticies (including child verticies) to the triangle mesh\n _addMeshVerts(btTriangleMesh, topLevelObject, object) {\n let triangleCount = 0;\n if (object && object.getIndices && object.getWorldMatrix && object.getChildMeshes) {\n let indices = object.getIndices();\n if (!indices) {\n indices = [];\n }\n let vertexPositions = object.getVerticesData(VertexBuffer.PositionKind);\n if (!vertexPositions) {\n vertexPositions = [];\n }\n let localMatrix;\n if (topLevelObject && topLevelObject !== object) {\n // top level matrix used for shape transform doesn't take scale into account.\n // Moreover, every children vertex position must be in that space.\n // So, each vertex position here is transform by (mesh world matrix * toplevelMatrix -1)\n let topLevelQuaternion;\n if (topLevelObject.rotationQuaternion) {\n topLevelQuaternion = topLevelObject.rotationQuaternion;\n }\n else if (topLevelObject.rotation) {\n topLevelQuaternion = Quaternion.FromEulerAngles(topLevelObject.rotation.x, topLevelObject.rotation.y, topLevelObject.rotation.z);\n }\n else {\n topLevelQuaternion = Quaternion.Identity();\n }\n const topLevelMatrix = Matrix.Compose(Vector3.One(), topLevelQuaternion, topLevelObject.position);\n topLevelMatrix.invertToRef(this._tmpMatrix);\n const wm = object.computeWorldMatrix(false);\n localMatrix = wm.multiply(this._tmpMatrix);\n }\n else {\n // current top level is same as object level -> only use local scaling\n Matrix.ScalingToRef(object.scaling.x, object.scaling.y, object.scaling.z, this._tmpMatrix);\n localMatrix = this._tmpMatrix;\n }\n const faceCount = indices.length / 3;\n for (let i = 0; i < faceCount; i++) {\n const triPoints = [];\n for (let point = 0; point < 3; point++) {\n let v = new Vector3(vertexPositions[indices[i * 3 + point] * 3 + 0], vertexPositions[indices[i * 3 + point] * 3 + 1], vertexPositions[indices[i * 3 + point] * 3 + 2]);\n v = Vector3.TransformCoordinates(v, localMatrix);\n let vec;\n if (point == 0) {\n vec = this._tmpAmmoVectorA;\n }\n else if (point == 1) {\n vec = this._tmpAmmoVectorB;\n }\n else {\n vec = this._tmpAmmoVectorC;\n }\n vec.setValue(v.x, v.y, v.z);\n triPoints.push(vec);\n }\n btTriangleMesh.addTriangle(triPoints[0], triPoints[1], triPoints[2]);\n triangleCount++;\n }\n object.getChildMeshes().forEach((m) => {\n triangleCount += this._addMeshVerts(btTriangleMesh, topLevelObject, m);\n });\n }\n return triangleCount;\n }\n /**\n * Initialise the soft body vertices to match its object's (mesh) vertices\n * Softbody vertices (nodes) are in world space and to match this\n * The object's position and rotation is set to zero and so its vertices are also then set in world space\n * @param impostor to create the softbody for\n */\n _softVertexData(impostor) {\n const object = impostor.object;\n if (object && object.getIndices && object.getWorldMatrix && object.getChildMeshes) {\n let indices = object.getIndices();\n if (!indices) {\n indices = [];\n }\n let vertexPositions = object.getVerticesData(VertexBuffer.PositionKind);\n if (!vertexPositions) {\n vertexPositions = [];\n }\n let vertexNormals = object.getVerticesData(VertexBuffer.NormalKind);\n if (!vertexNormals) {\n vertexNormals = [];\n }\n object.computeWorldMatrix(false);\n const newPoints = [];\n const newNorms = [];\n for (let i = 0; i < vertexPositions.length; i += 3) {\n let v = new Vector3(vertexPositions[i], vertexPositions[i + 1], vertexPositions[i + 2]);\n let n = new Vector3(vertexNormals[i], vertexNormals[i + 1], vertexNormals[i + 2]);\n v = Vector3.TransformCoordinates(v, object.getWorldMatrix());\n n = Vector3.TransformNormal(n, object.getWorldMatrix());\n newPoints.push(v.x, v.y, v.z);\n newNorms.push(n.x, n.y, n.z);\n }\n const vertex_data = new VertexData();\n vertex_data.positions = newPoints;\n vertex_data.normals = newNorms;\n vertex_data.uvs = object.getVerticesData(VertexBuffer.UVKind);\n vertex_data.colors = object.getVerticesData(VertexBuffer.ColorKind);\n if (object && object.getIndices) {\n vertex_data.indices = object.getIndices();\n }\n vertex_data.applyToMesh(object);\n object.position = Vector3.Zero();\n object.rotationQuaternion = null;\n object.rotation = Vector3.Zero();\n object.computeWorldMatrix(true);\n return vertex_data;\n }\n return VertexData.ExtractFromMesh(object);\n }\n /**\n * Create an impostor's soft body\n * @param impostor to create the softbody for\n */\n _createSoftbody(impostor) {\n const object = impostor.object;\n if (object && object.getIndices) {\n let indices = object.getIndices();\n if (!indices) {\n indices = [];\n }\n const vertex_data = this._softVertexData(impostor);\n const vertexPositions = vertex_data.positions;\n const vertexNormals = vertex_data.normals;\n if (vertexPositions === null || vertexNormals === null) {\n return new this.bjsAMMO.btCompoundShape();\n }\n else {\n const triPoints = [];\n const triNorms = [];\n for (let i = 0; i < vertexPositions.length; i += 3) {\n const v = new Vector3(vertexPositions[i], vertexPositions[i + 1], vertexPositions[i + 2]);\n const n = new Vector3(vertexNormals[i], vertexNormals[i + 1], vertexNormals[i + 2]);\n triPoints.push(v.x, v.y, -v.z);\n triNorms.push(n.x, n.y, -n.z);\n }\n const softBody = new this.bjsAMMO.btSoftBodyHelpers().CreateFromTriMesh(this.world.getWorldInfo(), triPoints, object.getIndices(), indices.length / 3, true);\n const nbVertices = vertexPositions.length / 3;\n const bodyVertices = softBody.get_m_nodes();\n let node;\n let nodeNormals;\n for (let i = 0; i < nbVertices; i++) {\n node = bodyVertices.at(i);\n nodeNormals = node.get_m_n();\n nodeNormals.setX(triNorms[3 * i]);\n nodeNormals.setY(triNorms[3 * i + 1]);\n nodeNormals.setZ(triNorms[3 * i + 2]);\n }\n return softBody;\n }\n }\n }\n /**\n * Create cloth for an impostor\n * @param impostor to create the softbody for\n */\n _createCloth(impostor) {\n const object = impostor.object;\n if (object && object.getIndices) {\n let indices = object.getIndices();\n if (!indices) {\n indices = [];\n }\n const vertex_data = this._softVertexData(impostor);\n const vertexPositions = vertex_data.positions;\n const vertexNormals = vertex_data.normals;\n if (vertexPositions === null || vertexNormals === null) {\n return new this.bjsAMMO.btCompoundShape();\n }\n else {\n const len = vertexPositions.length;\n const segments = Math.sqrt(len / 3);\n impostor.segments = segments;\n const segs = segments - 1;\n this._tmpAmmoVectorA.setValue(vertexPositions[0], vertexPositions[1], vertexPositions[2]);\n this._tmpAmmoVectorB.setValue(vertexPositions[3 * segs], vertexPositions[3 * segs + 1], vertexPositions[3 * segs + 2]);\n this._tmpAmmoVectorD.setValue(vertexPositions[len - 3], vertexPositions[len - 2], vertexPositions[len - 1]);\n this._tmpAmmoVectorC.setValue(vertexPositions[len - 3 - 3 * segs], vertexPositions[len - 2 - 3 * segs], vertexPositions[len - 1 - 3 * segs]);\n const clothBody = new this.bjsAMMO.btSoftBodyHelpers().CreatePatch(this.world.getWorldInfo(), this._tmpAmmoVectorA, this._tmpAmmoVectorB, this._tmpAmmoVectorC, this._tmpAmmoVectorD, segments, segments, impostor.getParam(\"fixedPoints\"), true);\n return clothBody;\n }\n }\n }\n /**\n * Create rope for an impostor\n * @param impostor to create the softbody for\n */\n _createRope(impostor) {\n let len;\n let segments;\n const vertex_data = this._softVertexData(impostor);\n const vertexPositions = vertex_data.positions;\n const vertexNormals = vertex_data.normals;\n if (vertexPositions === null || vertexNormals === null) {\n return new this.bjsAMMO.btCompoundShape();\n }\n //force the mesh to be updatable\n vertex_data.applyToMesh(impostor.object, true);\n impostor._isFromLine = true;\n // If in lines mesh all normals will be zero\n const vertexSquared = vertexNormals.map((x) => x * x);\n const reducer = (accumulator, currentValue) => accumulator + currentValue;\n const reduced = vertexSquared.reduce(reducer);\n if (reduced === 0) {\n // line mesh\n len = vertexPositions.length;\n segments = len / 3 - 1;\n this._tmpAmmoVectorA.setValue(vertexPositions[0], vertexPositions[1], vertexPositions[2]);\n this._tmpAmmoVectorB.setValue(vertexPositions[len - 3], vertexPositions[len - 2], vertexPositions[len - 1]);\n }\n else {\n //extruded mesh\n impostor._isFromLine = false;\n const pathVectors = impostor.getParam(\"path\");\n const shape = impostor.getParam(\"shape\");\n if (shape === null) {\n Logger.Warn(\"No shape available for extruded mesh\");\n return new this.bjsAMMO.btCompoundShape();\n }\n len = pathVectors.length;\n segments = len - 1;\n this._tmpAmmoVectorA.setValue(pathVectors[0].x, pathVectors[0].y, pathVectors[0].z);\n this._tmpAmmoVectorB.setValue(pathVectors[len - 1].x, pathVectors[len - 1].y, pathVectors[len - 1].z);\n }\n impostor.segments = segments;\n let fixedPoints = impostor.getParam(\"fixedPoints\");\n fixedPoints = fixedPoints > 3 ? 3 : fixedPoints;\n const ropeBody = new this.bjsAMMO.btSoftBodyHelpers().CreateRope(this.world.getWorldInfo(), this._tmpAmmoVectorA, this._tmpAmmoVectorB, segments - 1, fixedPoints);\n ropeBody.get_m_cfg().set_collisions(0x11);\n return ropeBody;\n }\n /**\n * Create a custom physics impostor shape using the plugin's onCreateCustomShape handler\n * @param impostor to create the custom physics shape for\n */\n _createCustom(impostor) {\n let returnValue = null;\n if (this.onCreateCustomShape) {\n returnValue = this.onCreateCustomShape(impostor);\n }\n if (returnValue == null) {\n returnValue = new this.bjsAMMO.btCompoundShape();\n }\n return returnValue;\n }\n // adds all verticies (including child verticies) to the convex hull shape\n _addHullVerts(btConvexHullShape, topLevelObject, object) {\n let triangleCount = 0;\n if (object && object.getIndices && object.getWorldMatrix && object.getChildMeshes) {\n let indices = object.getIndices();\n if (!indices) {\n indices = [];\n }\n let vertexPositions = object.getVerticesData(VertexBuffer.PositionKind);\n if (!vertexPositions) {\n vertexPositions = [];\n }\n object.computeWorldMatrix(false);\n const faceCount = indices.length / 3;\n for (let i = 0; i < faceCount; i++) {\n const triPoints = [];\n for (let point = 0; point < 3; point++) {\n let v = new Vector3(vertexPositions[indices[i * 3 + point] * 3 + 0], vertexPositions[indices[i * 3 + point] * 3 + 1], vertexPositions[indices[i * 3 + point] * 3 + 2]);\n // Adjust for initial scaling\n Matrix.ScalingToRef(object.scaling.x, object.scaling.y, object.scaling.z, this._tmpMatrix);\n v = Vector3.TransformCoordinates(v, this._tmpMatrix);\n let vec;\n if (point == 0) {\n vec = this._tmpAmmoVectorA;\n }\n else if (point == 1) {\n vec = this._tmpAmmoVectorB;\n }\n else {\n vec = this._tmpAmmoVectorC;\n }\n vec.setValue(v.x, v.y, v.z);\n triPoints.push(vec);\n }\n btConvexHullShape.addPoint(triPoints[0], true);\n btConvexHullShape.addPoint(triPoints[1], true);\n btConvexHullShape.addPoint(triPoints[2], true);\n triangleCount++;\n }\n object.getChildMeshes().forEach((m) => {\n triangleCount += this._addHullVerts(btConvexHullShape, topLevelObject, m);\n });\n }\n return triangleCount;\n }\n _createShape(impostor, ignoreChildren = false) {\n const object = impostor.object;\n let returnValue;\n const impostorExtents = impostor.getObjectExtents();\n if (!ignoreChildren) {\n const meshChildren = impostor.object.getChildMeshes ? impostor.object.getChildMeshes(true) : [];\n returnValue = new this.bjsAMMO.btCompoundShape();\n // Add shape of all children to the compound shape\n let childrenAdded = 0;\n meshChildren.forEach((childMesh) => {\n const childImpostor = childMesh.getPhysicsImpostor();\n if (childImpostor) {\n if (childImpostor.type == PhysicsImpostor.MeshImpostor) {\n throw \"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)\";\n }\n const shape = this._createShape(childImpostor);\n // Position needs to be scaled based on parent's scaling\n const parentMat = childMesh.parent.getWorldMatrix().clone();\n const s = new Vector3();\n parentMat.decompose(s);\n this._tmpAmmoTransform.getOrigin().setValue(childMesh.position.x * s.x, childMesh.position.y * s.y, childMesh.position.z * s.z);\n this._tmpAmmoQuaternion.setValue(childMesh.rotationQuaternion.x, childMesh.rotationQuaternion.y, childMesh.rotationQuaternion.z, childMesh.rotationQuaternion.w);\n this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion);\n returnValue.addChildShape(this._tmpAmmoTransform, shape);\n childImpostor.dispose();\n childrenAdded++;\n }\n });\n if (childrenAdded > 0) {\n // Add parents shape as a child if present\n if (impostor.type != PhysicsImpostor.NoImpostor) {\n const shape = this._createShape(impostor, true);\n if (shape) {\n this._tmpAmmoTransform.getOrigin().setValue(0, 0, 0);\n this._tmpAmmoQuaternion.setValue(0, 0, 0, 1);\n this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion);\n returnValue.addChildShape(this._tmpAmmoTransform, shape);\n }\n }\n return returnValue;\n }\n else {\n // If no children with impostors create the actual shape below instead\n this.bjsAMMO.destroy(returnValue);\n returnValue = null;\n }\n }\n switch (impostor.type) {\n case PhysicsImpostor.SphereImpostor:\n // Is there a better way to compare floats number? With an epsilon or with a Math function\n if (Scalar.WithinEpsilon(impostorExtents.x, impostorExtents.y, 0.0001) && Scalar.WithinEpsilon(impostorExtents.x, impostorExtents.z, 0.0001)) {\n returnValue = new this.bjsAMMO.btSphereShape(impostorExtents.x / 2);\n }\n else {\n // create a btMultiSphereShape because it's not possible to set a local scaling on a btSphereShape\n const positions = [new this.bjsAMMO.btVector3(0, 0, 0)];\n const radii = [1];\n returnValue = new this.bjsAMMO.btMultiSphereShape(positions, radii, 1);\n returnValue.setLocalScaling(new this.bjsAMMO.btVector3(impostorExtents.x / 2, impostorExtents.y / 2, impostorExtents.z / 2));\n }\n break;\n case PhysicsImpostor.CapsuleImpostor:\n {\n // https://pybullet.org/Bullet/BulletFull/classbtCapsuleShape.html#details\n // Height is just the height between the center of each 'sphere' of the capsule caps\n const capRadius = impostorExtents.x / 2;\n returnValue = new this.bjsAMMO.btCapsuleShape(capRadius, impostorExtents.y - capRadius * 2);\n }\n break;\n case PhysicsImpostor.CylinderImpostor:\n this._tmpAmmoVectorA.setValue(impostorExtents.x / 2, impostorExtents.y / 2, impostorExtents.z / 2);\n returnValue = new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);\n break;\n case PhysicsImpostor.PlaneImpostor:\n case PhysicsImpostor.BoxImpostor:\n this._tmpAmmoVectorA.setValue(impostorExtents.x / 2, impostorExtents.y / 2, impostorExtents.z / 2);\n returnValue = new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);\n break;\n case PhysicsImpostor.MeshImpostor: {\n if (impostor.getParam(\"mass\") == 0) {\n // Only create btBvhTriangleMeshShape if the impostor is static\n // See https://pybullet.org/Bullet/phpBB3/viewtopic.php?t=7283\n if (this.onCreateCustomMeshImpostor) {\n returnValue = this.onCreateCustomMeshImpostor(impostor);\n }\n else {\n const triMesh = new this.bjsAMMO.btTriangleMesh();\n impostor._pluginData.toDispose.push(triMesh);\n const triangleCount = this._addMeshVerts(triMesh, object, object);\n if (triangleCount == 0) {\n returnValue = new this.bjsAMMO.btCompoundShape();\n }\n else {\n returnValue = new this.bjsAMMO.btBvhTriangleMeshShape(triMesh);\n }\n }\n break;\n }\n }\n // Otherwise create convexHullImpostor\n // eslint-disable-next-line no-fallthrough\n case PhysicsImpostor.ConvexHullImpostor: {\n if (this.onCreateCustomConvexHullImpostor) {\n returnValue = this.onCreateCustomConvexHullImpostor(impostor);\n }\n else {\n const convexHull = new this.bjsAMMO.btConvexHullShape();\n const triangleCount = this._addHullVerts(convexHull, object, object);\n if (triangleCount == 0) {\n // Cleanup Unused Convex Hull Shape\n impostor._pluginData.toDispose.push(convexHull);\n returnValue = new this.bjsAMMO.btCompoundShape();\n }\n else {\n returnValue = convexHull;\n }\n }\n break;\n }\n case PhysicsImpostor.NoImpostor:\n // Fill with sphere but collision is disabled on the rigid body in generatePhysicsBody, using an empty shape caused unexpected movement with joints\n returnValue = new this.bjsAMMO.btSphereShape(impostorExtents.x / 2);\n break;\n case PhysicsImpostor.CustomImpostor:\n // Only usable when the plugin's onCreateCustomShape is set\n returnValue = this._createCustom(impostor);\n break;\n case PhysicsImpostor.SoftbodyImpostor:\n // Only usable with a mesh that has sufficient and shared vertices\n returnValue = this._createSoftbody(impostor);\n break;\n case PhysicsImpostor.ClothImpostor:\n // Only usable with a ground mesh that has sufficient and shared vertices\n returnValue = this._createCloth(impostor);\n break;\n case PhysicsImpostor.RopeImpostor:\n // Only usable with a line mesh or an extruded mesh that is updatable\n returnValue = this._createRope(impostor);\n break;\n default:\n Logger.Warn(\"The impostor type is not currently supported by the ammo plugin.\");\n break;\n }\n return returnValue;\n }\n /**\n * Sets the mesh body position/rotation from the babylon impostor\n * @param impostor imposter containing the physics body and babylon object\n */\n setTransformationFromPhysicsBody(impostor) {\n impostor.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform);\n impostor.object.position.set(this._tmpAmmoTransform.getOrigin().x(), this._tmpAmmoTransform.getOrigin().y(), this._tmpAmmoTransform.getOrigin().z());\n if (!impostor.object.rotationQuaternion) {\n if (impostor.object.rotation) {\n this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(), this._tmpAmmoTransform.getRotation().y(), this._tmpAmmoTransform.getRotation().z(), this._tmpAmmoTransform.getRotation().w());\n this._tmpQuaternion.toEulerAnglesToRef(impostor.object.rotation);\n }\n }\n else {\n impostor.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(), this._tmpAmmoTransform.getRotation().y(), this._tmpAmmoTransform.getRotation().z(), this._tmpAmmoTransform.getRotation().w());\n }\n }\n /**\n * Sets the babylon object's position/rotation from the physics body's position/rotation\n * @param impostor imposter containing the physics body and babylon object\n * @param newPosition new position\n * @param newRotation new rotation\n */\n setPhysicsBodyTransformation(impostor, newPosition, newRotation) {\n const trans = impostor.physicsBody.getWorldTransform();\n // If rotation/position has changed update and activate rigged body\n if (Math.abs(trans.getOrigin().x() - newPosition.x) > Epsilon ||\n Math.abs(trans.getOrigin().y() - newPosition.y) > Epsilon ||\n Math.abs(trans.getOrigin().z() - newPosition.z) > Epsilon ||\n Math.abs(trans.getRotation().x() - newRotation.x) > Epsilon ||\n Math.abs(trans.getRotation().y() - newRotation.y) > Epsilon ||\n Math.abs(trans.getRotation().z() - newRotation.z) > Epsilon ||\n Math.abs(trans.getRotation().w() - newRotation.w) > Epsilon) {\n this._tmpAmmoVectorA.setValue(newPosition.x, newPosition.y, newPosition.z);\n trans.setOrigin(this._tmpAmmoVectorA);\n this._tmpAmmoQuaternion.setValue(newRotation.x, newRotation.y, newRotation.z, newRotation.w);\n trans.setRotation(this._tmpAmmoQuaternion);\n impostor.physicsBody.setWorldTransform(trans);\n if (impostor.mass == 0) {\n // Kinematic objects must be updated using motion state\n const motionState = impostor.physicsBody.getMotionState();\n if (motionState) {\n motionState.setWorldTransform(trans);\n }\n }\n else {\n impostor.physicsBody.activate();\n }\n }\n }\n /**\n * If this plugin is supported\n * @returns true if its supported\n */\n isSupported() {\n return this.bjsAMMO !== undefined;\n }\n /**\n * Sets the linear velocity of the physics body\n * @param impostor imposter to set the velocity on\n * @param velocity velocity to set\n */\n setLinearVelocity(impostor, velocity) {\n this._tmpAmmoVectorA.setValue(velocity.x, velocity.y, velocity.z);\n if (impostor.soft) {\n impostor.physicsBody.linearVelocity(this._tmpAmmoVectorA);\n }\n else {\n impostor.physicsBody.setLinearVelocity(this._tmpAmmoVectorA);\n }\n }\n /**\n * Sets the angular velocity of the physics body\n * @param impostor imposter to set the velocity on\n * @param velocity velocity to set\n */\n setAngularVelocity(impostor, velocity) {\n this._tmpAmmoVectorA.setValue(velocity.x, velocity.y, velocity.z);\n if (impostor.soft) {\n impostor.physicsBody.angularVelocity(this._tmpAmmoVectorA);\n }\n else {\n impostor.physicsBody.setAngularVelocity(this._tmpAmmoVectorA);\n }\n }\n /**\n * gets the linear velocity\n * @param impostor imposter to get linear velocity from\n * @returns linear velocity\n */\n getLinearVelocity(impostor) {\n let v;\n if (impostor.soft) {\n v = impostor.physicsBody.linearVelocity();\n }\n else {\n v = impostor.physicsBody.getLinearVelocity();\n }\n if (!v) {\n return null;\n }\n const result = new Vector3(v.x(), v.y(), v.z());\n this.bjsAMMO.destroy(v);\n return result;\n }\n /**\n * gets the angular velocity\n * @param impostor imposter to get angular velocity from\n * @returns angular velocity\n */\n getAngularVelocity(impostor) {\n let v;\n if (impostor.soft) {\n v = impostor.physicsBody.angularVelocity();\n }\n else {\n v = impostor.physicsBody.getAngularVelocity();\n }\n if (!v) {\n return null;\n }\n const result = new Vector3(v.x(), v.y(), v.z());\n this.bjsAMMO.destroy(v);\n return result;\n }\n /**\n * Sets the mass of physics body\n * @param impostor imposter to set the mass on\n * @param mass mass to set\n */\n setBodyMass(impostor, mass) {\n if (impostor.soft) {\n impostor.physicsBody.setTotalMass(mass, false);\n }\n else {\n impostor.physicsBody.setMassProps(mass);\n }\n impostor._pluginData.mass = mass;\n }\n /**\n * Gets the mass of the physics body\n * @param impostor imposter to get the mass from\n * @returns mass\n */\n getBodyMass(impostor) {\n return impostor._pluginData.mass || 0;\n }\n /**\n * Gets friction of the impostor\n * @param impostor impostor to get friction from\n * @returns friction value\n */\n getBodyFriction(impostor) {\n return impostor._pluginData.friction || 0;\n }\n /**\n * Sets friction of the impostor\n * @param impostor impostor to set friction on\n * @param friction friction value\n */\n setBodyFriction(impostor, friction) {\n if (impostor.soft) {\n impostor.physicsBody.get_m_cfg().set_kDF(friction);\n }\n else {\n impostor.physicsBody.setFriction(friction);\n }\n impostor._pluginData.friction = friction;\n }\n /**\n * Gets restitution of the impostor\n * @param impostor impostor to get restitution from\n * @returns restitution value\n */\n getBodyRestitution(impostor) {\n return impostor._pluginData.restitution || 0;\n }\n /**\n * Sets restitution of the impostor\n * @param impostor impostor to set resitution on\n * @param restitution resitution value\n */\n setBodyRestitution(impostor, restitution) {\n impostor.physicsBody.setRestitution(restitution);\n impostor._pluginData.restitution = restitution;\n }\n /**\n * Gets pressure inside the impostor\n * @param impostor impostor to get pressure from\n * @returns pressure value\n */\n getBodyPressure(impostor) {\n if (!impostor.soft) {\n Logger.Warn(\"Pressure is not a property of a rigid body\");\n return 0;\n }\n return impostor._pluginData.pressure || 0;\n }\n /**\n * Sets pressure inside a soft body impostor\n * Cloth and rope must remain 0 pressure\n * @param impostor impostor to set pressure on\n * @param pressure pressure value\n */\n setBodyPressure(impostor, pressure) {\n if (impostor.soft) {\n if (impostor.type === PhysicsImpostor.SoftbodyImpostor) {\n impostor.physicsBody.get_m_cfg().set_kPR(pressure);\n impostor._pluginData.pressure = pressure;\n }\n else {\n impostor.physicsBody.get_m_cfg().set_kPR(0);\n impostor._pluginData.pressure = 0;\n }\n }\n else {\n Logger.Warn(\"Pressure can only be applied to a softbody\");\n }\n }\n /**\n * Gets stiffness of the impostor\n * @param impostor impostor to get stiffness from\n * @returns pressure value\n */\n getBodyStiffness(impostor) {\n if (!impostor.soft) {\n Logger.Warn(\"Stiffness is not a property of a rigid body\");\n return 0;\n }\n return impostor._pluginData.stiffness || 0;\n }\n /**\n * Sets stiffness of the impostor\n * @param impostor impostor to set stiffness on\n * @param stiffness stiffness value from 0 to 1\n */\n setBodyStiffness(impostor, stiffness) {\n if (impostor.soft) {\n stiffness = stiffness < 0 ? 0 : stiffness;\n stiffness = stiffness > 1 ? 1 : stiffness;\n impostor.physicsBody.get_m_materials().at(0).set_m_kLST(stiffness);\n impostor._pluginData.stiffness = stiffness;\n }\n else {\n Logger.Warn(\"Stiffness cannot be applied to a rigid body\");\n }\n }\n /**\n * Gets velocityIterations of the impostor\n * @param impostor impostor to get velocity iterations from\n * @returns velocityIterations value\n */\n getBodyVelocityIterations(impostor) {\n if (!impostor.soft) {\n Logger.Warn(\"Velocity iterations is not a property of a rigid body\");\n return 0;\n }\n return impostor._pluginData.velocityIterations || 0;\n }\n /**\n * Sets velocityIterations of the impostor\n * @param impostor impostor to set velocity iterations on\n * @param velocityIterations velocityIterations value\n */\n setBodyVelocityIterations(impostor, velocityIterations) {\n if (impostor.soft) {\n velocityIterations = velocityIterations < 0 ? 0 : velocityIterations;\n impostor.physicsBody.get_m_cfg().set_viterations(velocityIterations);\n impostor._pluginData.velocityIterations = velocityIterations;\n }\n else {\n Logger.Warn(\"Velocity iterations cannot be applied to a rigid body\");\n }\n }\n /**\n * Gets positionIterations of the impostor\n * @param impostor impostor to get position iterations from\n * @returns positionIterations value\n */\n getBodyPositionIterations(impostor) {\n if (!impostor.soft) {\n Logger.Warn(\"Position iterations is not a property of a rigid body\");\n return 0;\n }\n return impostor._pluginData.positionIterations || 0;\n }\n /**\n * Sets positionIterations of the impostor\n * @param impostor impostor to set position on\n * @param positionIterations positionIterations value\n */\n setBodyPositionIterations(impostor, positionIterations) {\n if (impostor.soft) {\n positionIterations = positionIterations < 0 ? 0 : positionIterations;\n impostor.physicsBody.get_m_cfg().set_piterations(positionIterations);\n impostor._pluginData.positionIterations = positionIterations;\n }\n else {\n Logger.Warn(\"Position iterations cannot be applied to a rigid body\");\n }\n }\n /**\n * Append an anchor to a cloth object\n * @param impostor is the cloth impostor to add anchor to\n * @param otherImpostor is the rigid impostor to anchor to\n * @param width ratio across width from 0 to 1\n * @param height ratio up height from 0 to 1\n * @param influence the elasticity between cloth impostor and anchor from 0, very stretchy to 1, little stretch\n * @param noCollisionBetweenLinkedBodies when true collisions between soft impostor and anchor are ignored; default false\n */\n appendAnchor(impostor, otherImpostor, width, height, influence = 1, noCollisionBetweenLinkedBodies = false) {\n const segs = impostor.segments;\n const nbAcross = Math.round((segs - 1) * width);\n const nbUp = Math.round((segs - 1) * height);\n const nbDown = segs - 1 - nbUp;\n const node = nbAcross + segs * nbDown;\n impostor.physicsBody.appendAnchor(node, otherImpostor.physicsBody, noCollisionBetweenLinkedBodies, influence);\n }\n /**\n * Append an hook to a rope object\n * @param impostor is the rope impostor to add hook to\n * @param otherImpostor is the rigid impostor to hook to\n * @param length ratio along the rope from 0 to 1\n * @param influence the elasticity between soft impostor and anchor from 0, very stretchy to 1, little stretch\n * @param noCollisionBetweenLinkedBodies when true collisions between soft impostor and anchor are ignored; default false\n */\n appendHook(impostor, otherImpostor, length, influence = 1, noCollisionBetweenLinkedBodies = false) {\n const node = Math.round(impostor.segments * length);\n impostor.physicsBody.appendAnchor(node, otherImpostor.physicsBody, noCollisionBetweenLinkedBodies, influence);\n }\n /**\n * Sleeps the physics body and stops it from being active\n * @param impostor impostor to sleep\n */\n sleepBody(impostor) {\n impostor.physicsBody.forceActivationState(0);\n }\n /**\n * Activates the physics body\n * @param impostor impostor to activate\n */\n wakeUpBody(impostor) {\n impostor.physicsBody.activate();\n }\n /**\n * Updates the distance parameters of the joint\n */\n updateDistanceJoint() {\n Logger.Warn(\"updateDistanceJoint is not currently supported by the Ammo physics plugin\");\n }\n /**\n * Sets a motor on the joint\n * @param joint joint to set motor on\n * @param speed speed of the motor\n * @param maxForce maximum force of the motor\n */\n setMotor(joint, speed, maxForce) {\n joint.physicsJoint.enableAngularMotor(true, speed, maxForce);\n }\n /**\n * Sets the motors limit\n */\n setLimit() {\n Logger.Warn(\"setLimit is not currently supported by the Ammo physics plugin\");\n }\n /**\n * Syncs the position and rotation of a mesh with the impostor\n * @param mesh mesh to sync\n * @param impostor impostor to update the mesh with\n */\n syncMeshWithImpostor(mesh, impostor) {\n const body = impostor.physicsBody;\n body.getMotionState().getWorldTransform(this._tmpAmmoTransform);\n mesh.position.x = this._tmpAmmoTransform.getOrigin().x();\n mesh.position.y = this._tmpAmmoTransform.getOrigin().y();\n mesh.position.z = this._tmpAmmoTransform.getOrigin().z();\n if (mesh.rotationQuaternion) {\n mesh.rotationQuaternion.x = this._tmpAmmoTransform.getRotation().x();\n mesh.rotationQuaternion.y = this._tmpAmmoTransform.getRotation().y();\n mesh.rotationQuaternion.z = this._tmpAmmoTransform.getRotation().z();\n mesh.rotationQuaternion.w = this._tmpAmmoTransform.getRotation().w();\n }\n }\n /**\n * Gets the radius of the impostor\n * @param impostor impostor to get radius from\n * @returns the radius\n */\n getRadius(impostor) {\n const extents = impostor.getObjectExtents();\n return extents.x / 2;\n }\n /**\n * Gets the box size of the impostor\n * @param impostor impostor to get box size from\n * @param result the resulting box size\n */\n getBoxSizeToRef(impostor, result) {\n const extents = impostor.getObjectExtents();\n result.x = extents.x;\n result.y = extents.y;\n result.z = extents.z;\n }\n /**\n * Disposes of the impostor\n */\n dispose() {\n // Dispose of world\n this.bjsAMMO.destroy(this.world);\n this.bjsAMMO.destroy(this._solver);\n this.bjsAMMO.destroy(this._overlappingPairCache);\n this.bjsAMMO.destroy(this._dispatcher);\n this.bjsAMMO.destroy(this._collisionConfiguration);\n // Dispose of temp variables\n this.bjsAMMO.destroy(this._tmpAmmoVectorA);\n this.bjsAMMO.destroy(this._tmpAmmoVectorB);\n this.bjsAMMO.destroy(this._tmpAmmoVectorC);\n this.bjsAMMO.destroy(this._tmpAmmoTransform);\n this.bjsAMMO.destroy(this._tmpAmmoQuaternion);\n this.bjsAMMO.destroy(this._tmpAmmoConcreteContactResultCallback);\n this.world = null;\n }\n /**\n * Does a raycast in the physics world\n * @param from where should the ray start?\n * @param to where should the ray end?\n * @returns PhysicsRaycastResult\n */\n raycast(from, to) {\n this.raycastToRef(from, to, this._raycastResult);\n return this._raycastResult;\n }\n /**\n * Does a raycast in the physics world\n * @param from when should the ray start?\n * @param to when should the ray end?\n * @param result resulting PhysicsRaycastResult\n */\n raycastToRef(from, to, result) {\n this._tmpAmmoVectorRCA = new this.bjsAMMO.btVector3(from.x, from.y, from.z);\n this._tmpAmmoVectorRCB = new this.bjsAMMO.btVector3(to.x, to.y, to.z);\n const rayCallback = new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA, this._tmpAmmoVectorRCB);\n this.world.rayTest(this._tmpAmmoVectorRCA, this._tmpAmmoVectorRCB, rayCallback);\n result.reset(from, to);\n if (rayCallback.hasHit()) {\n // TODO: do we want/need the body? If so, set all the data\n /*\n var rigidBody = this.bjsAMMO.btRigidBody.prototype.upcast(\n rayCallback.get_m_collisionObject()\n );\n var body = {};\n */\n result.setHitData({\n x: rayCallback.get_m_hitNormalWorld().x(),\n y: rayCallback.get_m_hitNormalWorld().y(),\n z: rayCallback.get_m_hitNormalWorld().z(),\n }, {\n x: rayCallback.get_m_hitPointWorld().x(),\n y: rayCallback.get_m_hitPointWorld().y(),\n z: rayCallback.get_m_hitPointWorld().z(),\n });\n result.calculateHitDistance();\n }\n this.bjsAMMO.destroy(rayCallback);\n this.bjsAMMO.destroy(this._tmpAmmoVectorRCA);\n this.bjsAMMO.destroy(this._tmpAmmoVectorRCB);\n }\n}\nAmmoJSPlugin._DISABLE_COLLISION_FLAG = 4;\nAmmoJSPlugin._KINEMATIC_FLAG = 2;\nAmmoJSPlugin._DISABLE_DEACTIVATION_FLAG = 4;\n//# sourceMappingURL=ammoJSPlugin.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serializeAsMeshReference, serializeAsVector3, SerializationHelper } from \"../Misc/decorators.js\";\nimport { RenderTargetTexture } from \"../Materials/Textures/renderTargetTexture.js\";\nimport { Matrix, Vector3 } from \"../Maths/math.vector.js\";\nimport { AbstractScene } from \"../abstractScene.js\";\n\nAbstractScene.prototype.removeReflectionProbe = function (toRemove) {\n if (!this.reflectionProbes) {\n return -1;\n }\n const index = this.reflectionProbes.indexOf(toRemove);\n if (index !== -1) {\n this.reflectionProbes.splice(index, 1);\n }\n return index;\n};\nAbstractScene.prototype.addReflectionProbe = function (newReflectionProbe) {\n if (!this.reflectionProbes) {\n this.reflectionProbes = [];\n }\n this.reflectionProbes.push(newReflectionProbe);\n};\n/**\n * Class used to generate realtime reflection / refraction cube textures\n * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/reflectionProbes\n */\nexport class ReflectionProbe {\n /**\n * Creates a new reflection probe\n * @param name defines the name of the probe\n * @param size defines the texture resolution (for each face)\n * @param scene defines the hosting scene\n * @param generateMipMaps defines if mip maps should be generated automatically (true by default)\n * @param useFloat defines if HDR data (float data) should be used to store colors (false by default)\n * @param linearSpace defines if the probe should be generated in linear space or not (false by default)\n */\n constructor(\n /** defines the name of the probe */\n name, size, scene, generateMipMaps = true, useFloat = false, linearSpace = false) {\n this.name = name;\n this._viewMatrix = Matrix.Identity();\n this._target = Vector3.Zero();\n this._add = Vector3.Zero();\n this._invertYAxis = false;\n /** Gets or sets probe position (center of the cube map) */\n this.position = Vector3.Zero();\n /**\n * Gets or sets an object used to store user defined information for the reflection probe.\n */\n this.metadata = null;\n /** @internal */\n this._parentContainer = null;\n this._scene = scene;\n if (scene.getEngine().supportsUniformBuffers) {\n this._sceneUBOs = [];\n for (let i = 0; i < 6; ++i) {\n this._sceneUBOs.push(scene.createSceneUniformBuffer(`Scene for Reflection Probe (name \"${name}\") face #${i}`));\n }\n }\n // Create the scene field if not exist.\n if (!this._scene.reflectionProbes) {\n this._scene.reflectionProbes = new Array();\n }\n this._scene.reflectionProbes.push(this);\n let textureType = 0;\n if (useFloat) {\n const caps = this._scene.getEngine().getCaps();\n if (caps.textureHalfFloatRender) {\n textureType = 2;\n }\n else if (caps.textureFloatRender) {\n textureType = 1;\n }\n }\n this._renderTargetTexture = new RenderTargetTexture(name, size, scene, generateMipMaps, true, textureType, true);\n this._renderTargetTexture.gammaSpace = !linearSpace;\n this._renderTargetTexture.invertZ = scene.useRightHandedSystem;\n const useReverseDepthBuffer = scene.getEngine().useReverseDepthBuffer;\n this._renderTargetTexture.onBeforeRenderObservable.add((faceIndex) => {\n if (this._sceneUBOs) {\n scene.setSceneUniformBuffer(this._sceneUBOs[faceIndex]);\n scene.getSceneUniformBuffer().unbindEffect();\n }\n switch (faceIndex) {\n case 0:\n this._add.copyFromFloats(1, 0, 0);\n break;\n case 1:\n this._add.copyFromFloats(-1, 0, 0);\n break;\n case 2:\n this._add.copyFromFloats(0, this._invertYAxis ? 1 : -1, 0);\n break;\n case 3:\n this._add.copyFromFloats(0, this._invertYAxis ? -1 : 1, 0);\n break;\n case 4:\n this._add.copyFromFloats(0, 0, scene.useRightHandedSystem ? -1 : 1);\n break;\n case 5:\n this._add.copyFromFloats(0, 0, scene.useRightHandedSystem ? 1 : -1);\n break;\n }\n if (this._attachedMesh) {\n this.position.copyFrom(this._attachedMesh.getAbsolutePosition());\n }\n this.position.addToRef(this._add, this._target);\n const lookAtFunction = scene.useRightHandedSystem ? Matrix.LookAtRHToRef : Matrix.LookAtLHToRef;\n const perspectiveFunction = scene.useRightHandedSystem ? Matrix.PerspectiveFovRH : Matrix.PerspectiveFovLH;\n lookAtFunction(this.position, this._target, Vector3.Up(), this._viewMatrix);\n if (scene.activeCamera) {\n this._projectionMatrix = perspectiveFunction(Math.PI / 2, 1, useReverseDepthBuffer ? scene.activeCamera.maxZ : scene.activeCamera.minZ, useReverseDepthBuffer ? scene.activeCamera.minZ : scene.activeCamera.maxZ, this._scene.getEngine().isNDCHalfZRange);\n scene.setTransformMatrix(this._viewMatrix, this._projectionMatrix);\n if (scene.activeCamera.isRigCamera && !this._renderTargetTexture.activeCamera) {\n this._renderTargetTexture.activeCamera = scene.activeCamera.rigParent || null;\n }\n }\n scene._forcedViewPosition = this.position;\n });\n let currentApplyByPostProcess;\n this._renderTargetTexture.onBeforeBindObservable.add(() => {\n var _a, _b;\n this._currentSceneUBO = scene.getSceneUniformBuffer();\n (_b = (_a = scene.getEngine())._debugPushGroup) === null || _b === void 0 ? void 0 : _b.call(_a, `reflection probe generation for ${name}`, 1);\n currentApplyByPostProcess = this._scene.imageProcessingConfiguration.applyByPostProcess;\n if (linearSpace) {\n scene.imageProcessingConfiguration.applyByPostProcess = true;\n }\n });\n this._renderTargetTexture.onAfterUnbindObservable.add(() => {\n var _a, _b;\n scene.imageProcessingConfiguration.applyByPostProcess = currentApplyByPostProcess;\n scene._forcedViewPosition = null;\n if (this._sceneUBOs) {\n scene.setSceneUniformBuffer(this._currentSceneUBO);\n }\n scene.updateTransformMatrix(true);\n (_b = (_a = scene.getEngine())._debugPopGroup) === null || _b === void 0 ? void 0 : _b.call(_a, 1);\n });\n }\n /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */\n get samples() {\n return this._renderTargetTexture.samples;\n }\n set samples(value) {\n this._renderTargetTexture.samples = value;\n }\n /** Gets or sets the refresh rate to use (on every frame by default) */\n get refreshRate() {\n return this._renderTargetTexture.refreshRate;\n }\n set refreshRate(value) {\n this._renderTargetTexture.refreshRate = value;\n }\n /**\n * Gets the hosting scene\n * @returns a Scene\n */\n getScene() {\n return this._scene;\n }\n /** Gets the internal CubeTexture used to render to */\n get cubeTexture() {\n return this._renderTargetTexture;\n }\n /** Gets the list of meshes to render */\n get renderList() {\n return this._renderTargetTexture.renderList;\n }\n /**\n * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)\n * @param mesh defines the mesh to attach to\n */\n attachToMesh(mesh) {\n this._attachedMesh = mesh;\n }\n /**\n * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups\n * @param renderingGroupId The rendering group id corresponding to its index\n * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.\n */\n setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil) {\n this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);\n }\n /**\n * Clean all associated resources\n */\n dispose() {\n const index = this._scene.reflectionProbes.indexOf(this);\n if (index !== -1) {\n // Remove from the scene if found\n this._scene.reflectionProbes.splice(index, 1);\n }\n if (this._parentContainer) {\n const index = this._parentContainer.reflectionProbes.indexOf(this);\n if (index > -1) {\n this._parentContainer.reflectionProbes.splice(index, 1);\n }\n this._parentContainer = null;\n }\n if (this._renderTargetTexture) {\n this._renderTargetTexture.dispose();\n this._renderTargetTexture = null;\n }\n if (this._sceneUBOs) {\n for (const ubo of this._sceneUBOs) {\n ubo.dispose();\n }\n this._sceneUBOs = [];\n }\n }\n /**\n * Converts the reflection probe information to a readable string for debug purpose.\n * @param fullDetails Supports for multiple levels of logging within scene loading\n * @returns the human readable reflection probe info\n */\n toString(fullDetails) {\n let ret = \"Name: \" + this.name;\n if (fullDetails) {\n ret += \", position: \" + this.position.toString();\n if (this._attachedMesh) {\n ret += \", attached mesh: \" + this._attachedMesh.name;\n }\n }\n return ret;\n }\n /**\n * Get the class name of the refection probe.\n * @returns \"ReflectionProbe\"\n */\n getClassName() {\n return \"ReflectionProbe\";\n }\n /**\n * Serialize the reflection probe to a JSON representation we can easily use in the respective Parse function.\n * @returns The JSON representation of the texture\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this, this._renderTargetTexture.serialize());\n serializationObject.isReflectionProbe = true;\n serializationObject.metadata = this.metadata;\n return serializationObject;\n }\n /**\n * Parse the JSON representation of a reflection probe in order to recreate the reflection probe in the given scene.\n * @param parsedReflectionProbe Define the JSON representation of the reflection probe\n * @param scene Define the scene the parsed reflection probe should be instantiated in\n * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies\n * @returns The parsed reflection probe if successful\n */\n static Parse(parsedReflectionProbe, scene, rootUrl) {\n let reflectionProbe = null;\n if (scene.reflectionProbes) {\n for (let index = 0; index < scene.reflectionProbes.length; index++) {\n const rp = scene.reflectionProbes[index];\n if (rp.name === parsedReflectionProbe.name) {\n reflectionProbe = rp;\n break;\n }\n }\n }\n reflectionProbe = SerializationHelper.Parse(() => reflectionProbe || new ReflectionProbe(parsedReflectionProbe.name, parsedReflectionProbe.renderTargetSize, scene, parsedReflectionProbe._generateMipMaps), parsedReflectionProbe, scene, rootUrl);\n reflectionProbe.cubeTexture._waitingRenderList = parsedReflectionProbe.renderList;\n if (parsedReflectionProbe._attachedMesh) {\n reflectionProbe.attachToMesh(scene.getMeshById(parsedReflectionProbe._attachedMesh));\n }\n if (parsedReflectionProbe.metadata) {\n reflectionProbe.metadata = parsedReflectionProbe.metadata;\n }\n return reflectionProbe;\n }\n}\n__decorate([\n serializeAsMeshReference()\n], ReflectionProbe.prototype, \"_attachedMesh\", void 0);\n__decorate([\n serializeAsVector3()\n], ReflectionProbe.prototype, \"position\", void 0);\n//# sourceMappingURL=reflectionProbe.js.map","import { Logger } from \"../../Misc/logger.js\";\nimport { Camera } from \"../../Cameras/camera.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { Color3, Color4 } from \"../../Maths/math.color.js\";\nimport { Mesh } from \"../../Meshes/mesh.js\";\nimport { Geometry } from \"../../Meshes/geometry.js\";\nimport { TransformNode } from \"../../Meshes/transformNode.js\";\nimport { Material } from \"../../Materials/material.js\";\nimport { MultiMaterial } from \"../../Materials/multiMaterial.js\";\nimport { CubeTexture } from \"../../Materials/Textures/cubeTexture.js\";\nimport { HDRCubeTexture } from \"../../Materials/Textures/hdrCubeTexture.js\";\nimport { AnimationGroup } from \"../../Animations/animationGroup.js\";\nimport { Light } from \"../../Lights/light.js\";\nimport { SceneComponentConstants } from \"../../sceneComponent.js\";\nimport { SceneLoader } from \"../../Loading/sceneLoader.js\";\nimport { AbstractScene } from \"../../abstractScene.js\";\nimport { AssetContainer } from \"../../assetContainer.js\";\nimport { ActionManager } from \"../../Actions/actionManager.js\";\nimport { Skeleton } from \"../../Bones/skeleton.js\";\nimport { MorphTargetManager } from \"../../Morph/morphTargetManager.js\";\nimport { CannonJSPlugin } from \"../../Physics/v1/Plugins/cannonJSPlugin.js\";\nimport { OimoJSPlugin } from \"../../Physics/v1/Plugins/oimoJSPlugin.js\";\nimport { AmmoJSPlugin } from \"../../Physics/v1/Plugins/ammoJSPlugin.js\";\nimport { ReflectionProbe } from \"../../Probes/reflectionProbe.js\";\nimport { GetClass } from \"../../Misc/typeStore.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nimport { PostProcess } from \"../../PostProcesses/postProcess.js\";\n/** @internal */\n// eslint-disable-next-line @typescript-eslint/naming-convention, no-var\nexport var _BabylonLoaderRegistered = true;\n/**\n * Helps setting up some configuration for the babylon file loader.\n */\nexport class BabylonFileLoaderConfiguration {\n}\n/**\n * The loader does not allow injecting custom physics engine into the plugins.\n * Unfortunately in ES6, we need to manually inject them into the plugin.\n * So you could set this variable to your engine import to make it work.\n */\nBabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine = undefined;\nlet tempIndexContainer = {};\nlet tempMaterialIndexContainer = {};\nconst parseMaterialByPredicate = (predicate, parsedData, scene, rootUrl) => {\n if (!parsedData.materials) {\n return null;\n }\n for (let index = 0, cache = parsedData.materials.length; index < cache; index++) {\n const parsedMaterial = parsedData.materials[index];\n if (predicate(parsedMaterial)) {\n return { parsedMaterial, material: Material.Parse(parsedMaterial, scene, rootUrl) };\n }\n }\n return null;\n};\nconst isDescendantOf = (mesh, names, hierarchyIds) => {\n for (const i in names) {\n if (mesh.name === names[i]) {\n hierarchyIds.push(mesh.id);\n return true;\n }\n }\n if (mesh.parentId !== undefined && hierarchyIds.indexOf(mesh.parentId) !== -1) {\n hierarchyIds.push(mesh.id);\n return true;\n }\n return false;\n};\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst logOperation = (operation, producer) => {\n return (operation +\n \" of \" +\n (producer ? producer.file + \" from \" + producer.name + \" version: \" + producer.version + \", exporter version: \" + producer.exporter_version : \"unknown\"));\n};\nconst loadDetailLevels = (scene, mesh) => {\n const mastermesh = mesh;\n // Every value specified in the ids array of the lod data points to another mesh which should be used as the lower LOD level.\n // The distances (or coverages) array values specified are used along with the lod mesh ids as a hint to determine the switching threshold for the various LODs.\n if (mesh._waitingData.lods) {\n if (mesh._waitingData.lods.ids && mesh._waitingData.lods.ids.length > 0) {\n const lodmeshes = mesh._waitingData.lods.ids;\n const wasenabled = mastermesh.isEnabled(false);\n if (mesh._waitingData.lods.distances) {\n const distances = mesh._waitingData.lods.distances;\n if (distances.length >= lodmeshes.length) {\n const culling = distances.length > lodmeshes.length ? distances[distances.length - 1] : 0;\n mastermesh.setEnabled(false);\n for (let index = 0; index < lodmeshes.length; index++) {\n const lodid = lodmeshes[index];\n const lodmesh = scene.getMeshById(lodid);\n if (lodmesh != null) {\n mastermesh.addLODLevel(distances[index], lodmesh);\n }\n }\n if (culling > 0) {\n mastermesh.addLODLevel(culling, null);\n }\n if (wasenabled === true) {\n mastermesh.setEnabled(true);\n }\n }\n else {\n Tools.Warn(\"Invalid level of detail distances for \" + mesh.name);\n }\n }\n }\n mesh._waitingData.lods = null;\n }\n};\nconst findParent = (parentId, parentInstanceIndex, scene) => {\n if (typeof parentId !== \"number\") {\n const parentEntry = scene.getLastEntryById(parentId);\n if (parentEntry && parentInstanceIndex !== undefined && parentInstanceIndex !== null) {\n const instance = parentEntry.instances[parseInt(parentInstanceIndex)];\n return instance;\n }\n return parentEntry;\n }\n const parent = tempIndexContainer[parentId];\n if (parent && parentInstanceIndex !== undefined && parentInstanceIndex !== null) {\n const instance = parent.instances[parseInt(parentInstanceIndex)];\n return instance;\n }\n return parent;\n};\nconst findMaterial = (materialId, scene) => {\n if (typeof materialId !== \"number\") {\n return scene.getLastMaterialById(materialId, true);\n }\n return tempMaterialIndexContainer[materialId];\n};\nconst loadAssetContainer = (scene, data, rootUrl, onError, addToScene = false) => {\n const container = new AssetContainer(scene);\n // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details\n // when SceneLoader.debugLogging = true (default), or exception encountered.\n // Everything stored in var log instead of writing separate lines to support only writing in exception,\n // and avoid problems with multiple concurrent .babylon loads.\n let log = \"importScene has failed JSON parse\";\n try {\n // eslint-disable-next-line no-var\n var parsedData = JSON.parse(data);\n log = \"\";\n const fullDetails = SceneLoader.loggingLevel === SceneLoader.DETAILED_LOGGING;\n let index;\n let cache;\n // Environment texture\n if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {\n // PBR needed for both HDR texture (gamma space) & a sky box\n const isPBR = parsedData.isPBR !== undefined ? parsedData.isPBR : true;\n if (parsedData.environmentTextureType && parsedData.environmentTextureType === \"BABYLON.HDRCubeTexture\") {\n const hdrSize = parsedData.environmentTextureSize ? parsedData.environmentTextureSize : 128;\n const hdrTexture = new HDRCubeTexture((parsedData.environmentTexture.match(/https?:\\/\\//g) ? \"\" : rootUrl) + parsedData.environmentTexture, scene, hdrSize, true, !isPBR, undefined, parsedData.environmentTexturePrefilterOnLoad);\n if (parsedData.environmentTextureRotationY) {\n hdrTexture.rotationY = parsedData.environmentTextureRotationY;\n }\n scene.environmentTexture = hdrTexture;\n }\n else {\n if (typeof parsedData.environmentTexture === \"object\") {\n const environmentTexture = CubeTexture.Parse(parsedData.environmentTexture, scene, rootUrl);\n scene.environmentTexture = environmentTexture;\n }\n else if (parsedData.environmentTexture.endsWith(\".env\")) {\n const compressedTexture = new CubeTexture((parsedData.environmentTexture.match(/https?:\\/\\//g) ? \"\" : rootUrl) + parsedData.environmentTexture, scene, parsedData.environmentTextureForcedExtension);\n if (parsedData.environmentTextureRotationY) {\n compressedTexture.rotationY = parsedData.environmentTextureRotationY;\n }\n scene.environmentTexture = compressedTexture;\n }\n else {\n const cubeTexture = CubeTexture.CreateFromPrefilteredData((parsedData.environmentTexture.match(/https?:\\/\\//g) ? \"\" : rootUrl) + parsedData.environmentTexture, scene, parsedData.environmentTextureForcedExtension);\n if (parsedData.environmentTextureRotationY) {\n cubeTexture.rotationY = parsedData.environmentTextureRotationY;\n }\n scene.environmentTexture = cubeTexture;\n }\n }\n if (parsedData.createDefaultSkybox === true) {\n const skyboxScale = scene.activeCamera !== undefined && scene.activeCamera !== null ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;\n const skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;\n scene.createDefaultSkybox(scene.environmentTexture, isPBR, skyboxScale, skyboxBlurLevel);\n }\n container.environmentTexture = scene.environmentTexture;\n }\n // Environment Intensity\n if (parsedData.environmentIntensity !== undefined && parsedData.environmentIntensity !== null) {\n scene.environmentIntensity = parsedData.environmentIntensity;\n }\n // Lights\n if (parsedData.lights !== undefined && parsedData.lights !== null) {\n for (index = 0, cache = parsedData.lights.length; index < cache; index++) {\n const parsedLight = parsedData.lights[index];\n const light = Light.Parse(parsedLight, scene);\n if (light) {\n tempIndexContainer[parsedLight.uniqueId] = light;\n container.lights.push(light);\n light._parentContainer = container;\n log += index === 0 ? \"\\n\\tLights:\" : \"\";\n log += \"\\n\\t\\t\" + light.toString(fullDetails);\n }\n }\n }\n // Reflection probes\n if (parsedData.reflectionProbes !== undefined && parsedData.reflectionProbes !== null) {\n for (index = 0, cache = parsedData.reflectionProbes.length; index < cache; index++) {\n const parsedReflectionProbe = parsedData.reflectionProbes[index];\n const reflectionProbe = ReflectionProbe.Parse(parsedReflectionProbe, scene, rootUrl);\n if (reflectionProbe) {\n container.reflectionProbes.push(reflectionProbe);\n reflectionProbe._parentContainer = container;\n log += index === 0 ? \"\\n\\tReflection Probes:\" : \"\";\n log += \"\\n\\t\\t\" + reflectionProbe.toString(fullDetails);\n }\n }\n }\n // Animations\n if (parsedData.animations !== undefined && parsedData.animations !== null) {\n for (index = 0, cache = parsedData.animations.length; index < cache; index++) {\n const parsedAnimation = parsedData.animations[index];\n const internalClass = GetClass(\"BABYLON.Animation\");\n if (internalClass) {\n const animation = internalClass.Parse(parsedAnimation);\n scene.animations.push(animation);\n container.animations.push(animation);\n log += index === 0 ? \"\\n\\tAnimations:\" : \"\";\n log += \"\\n\\t\\t\" + animation.toString(fullDetails);\n }\n }\n }\n // Materials\n if (parsedData.materials !== undefined && parsedData.materials !== null) {\n for (index = 0, cache = parsedData.materials.length; index < cache; index++) {\n const parsedMaterial = parsedData.materials[index];\n const mat = Material.Parse(parsedMaterial, scene, rootUrl);\n if (mat) {\n tempMaterialIndexContainer[parsedMaterial.uniqueId || parsedMaterial.id] = mat;\n container.materials.push(mat);\n mat._parentContainer = container;\n log += index === 0 ? \"\\n\\tMaterials:\" : \"\";\n log += \"\\n\\t\\t\" + mat.toString(fullDetails);\n // Textures\n const textures = mat.getActiveTextures();\n textures.forEach((t) => {\n if (container.textures.indexOf(t) == -1) {\n container.textures.push(t);\n t._parentContainer = container;\n }\n });\n }\n }\n }\n if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {\n for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {\n const parsedMultiMaterial = parsedData.multiMaterials[index];\n const mmat = MultiMaterial.ParseMultiMaterial(parsedMultiMaterial, scene);\n tempMaterialIndexContainer[parsedMultiMaterial.uniqueId || parsedMultiMaterial.id] = mmat;\n container.multiMaterials.push(mmat);\n mmat._parentContainer = container;\n log += index === 0 ? \"\\n\\tMultiMaterials:\" : \"\";\n log += \"\\n\\t\\t\" + mmat.toString(fullDetails);\n // Textures\n const textures = mmat.getActiveTextures();\n textures.forEach((t) => {\n if (container.textures.indexOf(t) == -1) {\n container.textures.push(t);\n t._parentContainer = container;\n }\n });\n }\n }\n // Morph targets\n if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {\n for (const managerData of parsedData.morphTargetManagers) {\n const manager = MorphTargetManager.Parse(managerData, scene);\n container.morphTargetManagers.push(manager);\n manager._parentContainer = container;\n }\n }\n // Skeletons\n if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {\n for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {\n const parsedSkeleton = parsedData.skeletons[index];\n const skeleton = Skeleton.Parse(parsedSkeleton, scene);\n container.skeletons.push(skeleton);\n skeleton._parentContainer = container;\n log += index === 0 ? \"\\n\\tSkeletons:\" : \"\";\n log += \"\\n\\t\\t\" + skeleton.toString(fullDetails);\n }\n }\n // Geometries\n const geometries = parsedData.geometries;\n if (geometries !== undefined && geometries !== null) {\n const addedGeometry = new Array();\n // VertexData\n const vertexData = geometries.vertexData;\n if (vertexData !== undefined && vertexData !== null) {\n for (index = 0, cache = vertexData.length; index < cache; index++) {\n const parsedVertexData = vertexData[index];\n addedGeometry.push(Geometry.Parse(parsedVertexData, scene, rootUrl));\n }\n }\n addedGeometry.forEach((g) => {\n if (g) {\n container.geometries.push(g);\n g._parentContainer = container;\n }\n });\n }\n // Transform nodes\n if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {\n for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {\n const parsedTransformNode = parsedData.transformNodes[index];\n const node = TransformNode.Parse(parsedTransformNode, scene, rootUrl);\n tempIndexContainer[parsedTransformNode.uniqueId] = node;\n container.transformNodes.push(node);\n node._parentContainer = container;\n }\n }\n // Meshes\n if (parsedData.meshes !== undefined && parsedData.meshes !== null) {\n for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {\n const parsedMesh = parsedData.meshes[index];\n const mesh = Mesh.Parse(parsedMesh, scene, rootUrl);\n tempIndexContainer[parsedMesh.uniqueId] = mesh;\n container.meshes.push(mesh);\n mesh._parentContainer = container;\n if (mesh.hasInstances) {\n for (const instance of mesh.instances) {\n container.meshes.push(instance);\n instance._parentContainer = container;\n }\n }\n log += index === 0 ? \"\\n\\tMeshes:\" : \"\";\n log += \"\\n\\t\\t\" + mesh.toString(fullDetails);\n }\n }\n // Cameras\n if (parsedData.cameras !== undefined && parsedData.cameras !== null) {\n for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {\n const parsedCamera = parsedData.cameras[index];\n const camera = Camera.Parse(parsedCamera, scene);\n tempIndexContainer[parsedCamera.uniqueId] = camera;\n container.cameras.push(camera);\n camera._parentContainer = container;\n log += index === 0 ? \"\\n\\tCameras:\" : \"\";\n log += \"\\n\\t\\t\" + camera.toString(fullDetails);\n }\n }\n // Postprocesses\n if (parsedData.postProcesses !== undefined && parsedData.postProcesses !== null) {\n for (index = 0, cache = parsedData.postProcesses.length; index < cache; index++) {\n const parsedPostProcess = parsedData.postProcesses[index];\n const postProcess = PostProcess.Parse(parsedPostProcess, scene, rootUrl);\n if (postProcess) {\n container.postProcesses.push(postProcess);\n postProcess._parentContainer = container;\n log += index === 0 ? \"\\nPostprocesses:\" : \"\";\n log += \"\\n\\t\\t\" + postProcess.toString();\n }\n }\n }\n // Animation Groups\n if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {\n for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {\n const parsedAnimationGroup = parsedData.animationGroups[index];\n const animationGroup = AnimationGroup.Parse(parsedAnimationGroup, scene);\n container.animationGroups.push(animationGroup);\n animationGroup._parentContainer = container;\n log += index === 0 ? \"\\n\\tAnimationGroups:\" : \"\";\n log += \"\\n\\t\\t\" + animationGroup.toString(fullDetails);\n }\n }\n // Browsing all the graph to connect the dots\n for (index = 0, cache = scene.cameras.length; index < cache; index++) {\n const camera = scene.cameras[index];\n if (camera._waitingParentId !== null) {\n camera.parent = findParent(camera._waitingParentId, camera._waitingParentInstanceIndex, scene);\n camera._waitingParentId = null;\n camera._waitingParentInstanceIndex = null;\n }\n }\n for (index = 0, cache = scene.lights.length; index < cache; index++) {\n const light = scene.lights[index];\n if (light && light._waitingParentId !== null) {\n light.parent = findParent(light._waitingParentId, light._waitingParentInstanceIndex, scene);\n light._waitingParentId = null;\n light._waitingParentInstanceIndex = null;\n }\n }\n // Connect parents & children and parse actions and lods\n for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {\n const transformNode = scene.transformNodes[index];\n if (transformNode._waitingParentId !== null) {\n transformNode.parent = findParent(transformNode._waitingParentId, transformNode._waitingParentInstanceIndex, scene);\n transformNode._waitingParentId = null;\n transformNode._waitingParentInstanceIndex = null;\n }\n }\n for (index = 0, cache = scene.meshes.length; index < cache; index++) {\n const mesh = scene.meshes[index];\n if (mesh._waitingParentId !== null) {\n mesh.parent = findParent(mesh._waitingParentId, mesh._waitingParentInstanceIndex, scene);\n mesh._waitingParentId = null;\n mesh._waitingParentInstanceIndex = null;\n }\n if (mesh._waitingData.lods) {\n loadDetailLevels(scene, mesh);\n }\n }\n // link multimats with materials\n scene.multiMaterials.forEach((multimat) => {\n multimat._waitingSubMaterialsUniqueIds.forEach((subMaterial) => {\n multimat.subMaterials.push(findMaterial(subMaterial, scene));\n });\n multimat._waitingSubMaterialsUniqueIds = [];\n });\n // link meshes with materials\n scene.meshes.forEach((mesh) => {\n if (mesh._waitingMaterialId !== null) {\n mesh.material = findMaterial(mesh._waitingMaterialId, scene);\n mesh._waitingMaterialId = null;\n }\n });\n // link skeleton transform nodes\n for (index = 0, cache = scene.skeletons.length; index < cache; index++) {\n const skeleton = scene.skeletons[index];\n if (skeleton._hasWaitingData) {\n if (skeleton.bones != null) {\n skeleton.bones.forEach((bone) => {\n if (bone._waitingTransformNodeId) {\n const linkTransformNode = scene.getLastEntryById(bone._waitingTransformNodeId);\n if (linkTransformNode) {\n bone.linkTransformNode(linkTransformNode);\n }\n bone._waitingTransformNodeId = null;\n }\n });\n }\n skeleton._hasWaitingData = null;\n }\n }\n // freeze world matrix application\n for (index = 0, cache = scene.meshes.length; index < cache; index++) {\n const currentMesh = scene.meshes[index];\n if (currentMesh._waitingData.freezeWorldMatrix) {\n currentMesh.freezeWorldMatrix();\n currentMesh._waitingData.freezeWorldMatrix = null;\n }\n else {\n currentMesh.computeWorldMatrix(true);\n }\n }\n // Lights exclusions / inclusions\n for (index = 0, cache = scene.lights.length; index < cache; index++) {\n const light = scene.lights[index];\n // Excluded check\n if (light._excludedMeshesIds.length > 0) {\n for (let excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {\n const excludedMesh = scene.getMeshById(light._excludedMeshesIds[excludedIndex]);\n if (excludedMesh) {\n light.excludedMeshes.push(excludedMesh);\n }\n }\n light._excludedMeshesIds = [];\n }\n // Included check\n if (light._includedOnlyMeshesIds.length > 0) {\n for (let includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {\n const includedOnlyMesh = scene.getMeshById(light._includedOnlyMeshesIds[includedOnlyIndex]);\n if (includedOnlyMesh) {\n light.includedOnlyMeshes.push(includedOnlyMesh);\n }\n }\n light._includedOnlyMeshesIds = [];\n }\n }\n scene.geometries.forEach((g) => {\n g._loadedUniqueId = \"\";\n });\n AbstractScene.Parse(parsedData, scene, container, rootUrl);\n // Actions (scene) Done last as it can access other objects.\n for (index = 0, cache = scene.meshes.length; index < cache; index++) {\n const mesh = scene.meshes[index];\n if (mesh._waitingData.actions) {\n ActionManager.Parse(mesh._waitingData.actions, mesh, scene);\n mesh._waitingData.actions = null;\n }\n }\n if (parsedData.actions !== undefined && parsedData.actions !== null) {\n ActionManager.Parse(parsedData.actions, null, scene);\n }\n }\n catch (err) {\n const msg = logOperation(\"loadAssets\", parsedData ? parsedData.producer : \"Unknown\") + log;\n if (onError) {\n onError(msg, err);\n }\n else {\n Logger.Log(msg);\n throw err;\n }\n }\n finally {\n tempIndexContainer = {};\n tempMaterialIndexContainer = {};\n if (!addToScene) {\n container.removeAllFromScene();\n }\n if (log !== null && SceneLoader.loggingLevel !== SceneLoader.NO_LOGGING) {\n Logger.Log(logOperation(\"loadAssets\", parsedData ? parsedData.producer : \"Unknown\") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? log : \"\"));\n }\n }\n return container;\n};\nSceneLoader.RegisterPlugin({\n name: \"babylon.js\",\n extensions: \".babylon\",\n canDirectLoad: (data) => {\n if (data.indexOf(\"babylon\") !== -1) {\n // We consider that the producer string is filled\n return true;\n }\n return false;\n },\n importMesh: (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) => {\n var _a;\n // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details\n // when SceneLoader.debugLogging = true (default), or exception encountered.\n // Everything stored in var log instead of writing separate lines to support only writing in exception,\n // and avoid problems with multiple concurrent .babylon loads.\n let log = \"importMesh has failed JSON parse\";\n try {\n // eslint-disable-next-line no-var\n var parsedData = JSON.parse(data);\n log = \"\";\n const fullDetails = SceneLoader.loggingLevel === SceneLoader.DETAILED_LOGGING;\n if (!meshesNames) {\n meshesNames = null;\n }\n else if (!Array.isArray(meshesNames)) {\n meshesNames = [meshesNames];\n }\n const hierarchyIds = new Array();\n const parsedIdToNodeMap = new Map();\n // Transform nodes (the overall idea is to load all of them as this is super fast and then get rid of the ones we don't need)\n const loadedTransformNodes = [];\n if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {\n for (let index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {\n const parsedJSONTransformNode = parsedData.transformNodes[index];\n const parsedTransformNode = TransformNode.Parse(parsedJSONTransformNode, scene, rootUrl);\n loadedTransformNodes.push(parsedTransformNode);\n parsedIdToNodeMap.set(parsedTransformNode._waitingParsedUniqueId, parsedTransformNode);\n parsedTransformNode._waitingParsedUniqueId = null;\n }\n }\n if (parsedData.meshes !== undefined && parsedData.meshes !== null) {\n const loadedSkeletonsIds = [];\n const loadedMaterialsIds = [];\n const loadedMaterialsUniqueIds = [];\n const loadedMorphTargetsIds = [];\n for (let index = 0, cache = parsedData.meshes.length; index < cache; index++) {\n const parsedMesh = parsedData.meshes[index];\n if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {\n if (meshesNames !== null) {\n // Remove found mesh name from list.\n delete meshesNames[meshesNames.indexOf(parsedMesh.name)];\n }\n //Geometry?\n if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {\n //does the file contain geometries?\n if (parsedData.geometries !== undefined && parsedData.geometries !== null) {\n //find the correct geometry and add it to the scene\n let found = false;\n [\"boxes\", \"spheres\", \"cylinders\", \"toruses\", \"grounds\", \"planes\", \"torusKnots\", \"vertexData\"].forEach((geometryType) => {\n if (found === true || !parsedData.geometries[geometryType] || !Array.isArray(parsedData.geometries[geometryType])) {\n return;\n }\n else {\n parsedData.geometries[geometryType].forEach((parsedGeometryData) => {\n if (parsedGeometryData.id === parsedMesh.geometryId) {\n switch (geometryType) {\n case \"vertexData\":\n Geometry.Parse(parsedGeometryData, scene, rootUrl);\n break;\n }\n found = true;\n }\n });\n }\n });\n if (found === false) {\n Logger.Warn(\"Geometry not found for mesh \" + parsedMesh.id);\n }\n }\n }\n // Material ?\n if (parsedMesh.materialUniqueId || parsedMesh.materialId) {\n // if we have a unique ID, look up and store in loadedMaterialsUniqueIds, else use loadedMaterialsIds\n const materialArray = parsedMesh.materialUniqueId ? loadedMaterialsUniqueIds : loadedMaterialsIds;\n let materialFound = materialArray.indexOf(parsedMesh.materialUniqueId || parsedMesh.materialId) !== -1;\n if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {\n // Loads a submaterial of a multimaterial\n const loadSubMaterial = (subMatId, predicate) => {\n materialArray.push(subMatId);\n const mat = parseMaterialByPredicate(predicate, parsedData, scene, rootUrl);\n if (mat && mat.material) {\n tempMaterialIndexContainer[mat.parsedMaterial.uniqueId || mat.parsedMaterial.id] = mat.material;\n log += \"\\n\\tMaterial \" + mat.material.toString(fullDetails);\n }\n };\n for (let multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {\n const parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];\n if ((parsedMesh.materialUniqueId && parsedMultiMaterial.uniqueId === parsedMesh.materialUniqueId) ||\n parsedMultiMaterial.id === parsedMesh.materialId) {\n if (parsedMultiMaterial.materialsUniqueIds) {\n // if the materials inside the multimat are stored by unique id\n parsedMultiMaterial.materialsUniqueIds.forEach((subMatId) => loadSubMaterial(subMatId, (parsedMaterial) => parsedMaterial.uniqueId === subMatId));\n }\n else {\n // if the mats are stored by id instead\n parsedMultiMaterial.materials.forEach((subMatId) => loadSubMaterial(subMatId, (parsedMaterial) => parsedMaterial.id === subMatId));\n }\n materialArray.push(parsedMultiMaterial.uniqueId || parsedMultiMaterial.id);\n const mmat = MultiMaterial.ParseMultiMaterial(parsedMultiMaterial, scene);\n tempMaterialIndexContainer[parsedMultiMaterial.uniqueId || parsedMultiMaterial.id] = mmat;\n if (mmat) {\n materialFound = true;\n log += \"\\n\\tMulti-Material \" + mmat.toString(fullDetails);\n }\n break;\n }\n }\n }\n if (materialFound === false) {\n materialArray.push(parsedMesh.materialUniqueId || parsedMesh.materialId);\n const mat = parseMaterialByPredicate((parsedMaterial) => (parsedMesh.materialUniqueId && parsedMaterial.uniqueId === parsedMesh.materialUniqueId) || parsedMaterial.id === parsedMesh.materialId, parsedData, scene, rootUrl);\n if (!mat || !mat.material) {\n Logger.Warn(\"Material not found for mesh \" + parsedMesh.id);\n }\n else {\n tempMaterialIndexContainer[mat.parsedMaterial.uniqueId || mat.parsedMaterial.id] = mat.material;\n log += \"\\n\\tMaterial \" + mat.material.toString(fullDetails);\n }\n }\n }\n // Skeleton ?\n if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {\n const skeletonAlreadyLoaded = loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1;\n if (!skeletonAlreadyLoaded) {\n for (let skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {\n const parsedSkeleton = parsedData.skeletons[skeletonIndex];\n if (parsedSkeleton.id === parsedMesh.skeletonId) {\n const skeleton = Skeleton.Parse(parsedSkeleton, scene);\n skeletons.push(skeleton);\n loadedSkeletonsIds.push(parsedSkeleton.id);\n log += \"\\n\\tSkeleton \" + skeleton.toString(fullDetails);\n }\n }\n }\n }\n // Morph targets ?\n if (parsedMesh.morphTargetManagerId > -1 && parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {\n const morphTargetAlreadyLoaded = loadedMorphTargetsIds.indexOf(parsedMesh.morphTargetManagerId) > -1;\n if (!morphTargetAlreadyLoaded) {\n for (let morphTargetIndex = 0, morphTargetCache = parsedData.morphTargetManagers.length; morphTargetIndex < morphTargetCache; morphTargetIndex++) {\n const parsedMorphTarget = parsedData.morphTargetManagers[morphTargetIndex];\n if (parsedMorphTarget.id === parsedMesh.morphTargetManagerId) {\n const morphTarget = MorphTargetManager.Parse(parsedMorphTarget, scene);\n loadedMorphTargetsIds.push(morphTarget.uniqueId);\n log += \"\\nMorph target \" + morphTarget.toString();\n }\n }\n }\n }\n const mesh = Mesh.Parse(parsedMesh, scene, rootUrl);\n meshes.push(mesh);\n parsedIdToNodeMap.set(mesh._waitingParsedUniqueId, mesh);\n mesh._waitingParsedUniqueId = null;\n log += \"\\n\\tMesh \" + mesh.toString(fullDetails);\n }\n }\n // link multimats with materials\n scene.multiMaterials.forEach((multimat) => {\n multimat._waitingSubMaterialsUniqueIds.forEach((subMaterial) => {\n multimat.subMaterials.push(findMaterial(subMaterial, scene));\n });\n multimat._waitingSubMaterialsUniqueIds = [];\n });\n // link meshes with materials\n scene.meshes.forEach((mesh) => {\n if (mesh._waitingMaterialId !== null) {\n mesh.material = findMaterial(mesh._waitingMaterialId, scene);\n mesh._waitingMaterialId = null;\n }\n });\n // Connecting parents and lods\n for (let index = 0, cache = scene.transformNodes.length; index < cache; index++) {\n const transformNode = scene.transformNodes[index];\n if (transformNode._waitingParentId !== null) {\n let parent = parsedIdToNodeMap.get(parseInt(transformNode._waitingParentId)) || null;\n if (parent === null) {\n parent = scene.getLastEntryById(transformNode._waitingParentId);\n }\n let parentNode = parent;\n if (transformNode._waitingParentInstanceIndex) {\n parentNode = parent.instances[parseInt(transformNode._waitingParentInstanceIndex)];\n transformNode._waitingParentInstanceIndex = null;\n }\n transformNode.parent = parentNode;\n transformNode._waitingParentId = null;\n }\n }\n let currentMesh;\n for (let index = 0, cache = scene.meshes.length; index < cache; index++) {\n currentMesh = scene.meshes[index];\n if (currentMesh._waitingParentId) {\n let parent = parsedIdToNodeMap.get(parseInt(currentMesh._waitingParentId)) || null;\n if (parent === null) {\n parent = scene.getLastEntryById(currentMesh._waitingParentId);\n }\n let parentNode = parent;\n if (currentMesh._waitingParentInstanceIndex) {\n parentNode = parent.instances[parseInt(currentMesh._waitingParentInstanceIndex)];\n currentMesh._waitingParentInstanceIndex = null;\n }\n currentMesh.parent = parentNode;\n if (((_a = currentMesh.parent) === null || _a === void 0 ? void 0 : _a.getClassName()) === \"TransformNode\") {\n const loadedTransformNodeIndex = loadedTransformNodes.indexOf(currentMesh.parent);\n if (loadedTransformNodeIndex > -1) {\n loadedTransformNodes.splice(loadedTransformNodeIndex, 1);\n }\n }\n currentMesh._waitingParentId = null;\n }\n if (currentMesh._waitingData.lods) {\n loadDetailLevels(scene, currentMesh);\n }\n }\n // Remove unused transform nodes\n for (const transformNode of loadedTransformNodes) {\n transformNode.dispose();\n }\n // link skeleton transform nodes\n for (let index = 0, cache = scene.skeletons.length; index < cache; index++) {\n const skeleton = scene.skeletons[index];\n if (skeleton._hasWaitingData) {\n if (skeleton.bones != null) {\n skeleton.bones.forEach((bone) => {\n if (bone._waitingTransformNodeId) {\n const linkTransformNode = scene.getLastEntryById(bone._waitingTransformNodeId);\n if (linkTransformNode) {\n bone.linkTransformNode(linkTransformNode);\n }\n bone._waitingTransformNodeId = null;\n }\n });\n }\n skeleton._hasWaitingData = null;\n }\n }\n // freeze and compute world matrix application\n for (let index = 0, cache = scene.meshes.length; index < cache; index++) {\n currentMesh = scene.meshes[index];\n if (currentMesh._waitingData.freezeWorldMatrix) {\n currentMesh.freezeWorldMatrix();\n currentMesh._waitingData.freezeWorldMatrix = null;\n }\n else {\n currentMesh.computeWorldMatrix(true);\n }\n }\n }\n // Particles\n if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {\n const parser = AbstractScene.GetIndividualParser(SceneComponentConstants.NAME_PARTICLESYSTEM);\n if (parser) {\n for (let index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {\n const parsedParticleSystem = parsedData.particleSystems[index];\n if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {\n particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));\n }\n }\n }\n }\n scene.geometries.forEach((g) => {\n g._loadedUniqueId = \"\";\n });\n return true;\n }\n catch (err) {\n const msg = logOperation(\"importMesh\", parsedData ? parsedData.producer : \"Unknown\") + log;\n if (onError) {\n onError(msg, err);\n }\n else {\n Logger.Log(msg);\n throw err;\n }\n }\n finally {\n if (log !== null && SceneLoader.loggingLevel !== SceneLoader.NO_LOGGING) {\n Logger.Log(logOperation(\"importMesh\", parsedData ? parsedData.producer : \"Unknown\") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? log : \"\"));\n }\n tempMaterialIndexContainer = {};\n }\n return false;\n },\n load: (scene, data, rootUrl, onError) => {\n // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details\n // when SceneLoader.debugLogging = true (default), or exception encountered.\n // Everything stored in var log instead of writing separate lines to support only writing in exception,\n // and avoid problems with multiple concurrent .babylon loads.\n let log = \"importScene has failed JSON parse\";\n try {\n // eslint-disable-next-line no-var\n var parsedData = JSON.parse(data);\n log = \"\";\n // Scene\n if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {\n scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !SceneLoader.ForceFullSceneLoadingForIncremental;\n }\n if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {\n scene.autoClear = parsedData.autoClear;\n }\n if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {\n scene.clearColor = Color4.FromArray(parsedData.clearColor);\n }\n if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {\n scene.ambientColor = Color3.FromArray(parsedData.ambientColor);\n }\n if (parsedData.gravity !== undefined && parsedData.gravity !== null) {\n scene.gravity = Vector3.FromArray(parsedData.gravity);\n }\n if (parsedData.useRightHandedSystem !== undefined) {\n scene.useRightHandedSystem = !!parsedData.useRightHandedSystem;\n }\n // Fog\n if (parsedData.fogMode && parsedData.fogMode !== 0) {\n scene.fogMode = parsedData.fogMode;\n scene.fogColor = Color3.FromArray(parsedData.fogColor);\n scene.fogStart = parsedData.fogStart;\n scene.fogEnd = parsedData.fogEnd;\n scene.fogDensity = parsedData.fogDensity;\n log += \"\\tFog mode for scene: \";\n switch (scene.fogMode) {\n // getters not compiling, so using hardcoded\n case 1:\n log += \"exp\\n\";\n break;\n case 2:\n log += \"exp2\\n\";\n break;\n case 3:\n log += \"linear\\n\";\n break;\n }\n }\n //Physics\n if (parsedData.physicsEnabled) {\n let physicsPlugin;\n if (parsedData.physicsEngine === \"cannon\" || parsedData.physicsEngine === CannonJSPlugin.name) {\n physicsPlugin = new CannonJSPlugin(undefined, undefined, BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine);\n }\n else if (parsedData.physicsEngine === \"oimo\" || parsedData.physicsEngine === OimoJSPlugin.name) {\n physicsPlugin = new OimoJSPlugin(undefined, BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine);\n }\n else if (parsedData.physicsEngine === \"ammo\" || parsedData.physicsEngine === AmmoJSPlugin.name) {\n physicsPlugin = new AmmoJSPlugin(undefined, BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine, undefined);\n }\n log = \"\\tPhysics engine \" + (parsedData.physicsEngine ? parsedData.physicsEngine : \"oimo\") + \" enabled\\n\";\n //else - default engine, which is currently oimo\n const physicsGravity = parsedData.physicsGravity ? Vector3.FromArray(parsedData.physicsGravity) : null;\n scene.enablePhysics(physicsGravity, physicsPlugin);\n }\n // Metadata\n if (parsedData.metadata !== undefined && parsedData.metadata !== null) {\n scene.metadata = parsedData.metadata;\n }\n //collisions, if defined. otherwise, default is true\n if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {\n scene.collisionsEnabled = parsedData.collisionsEnabled;\n }\n const container = loadAssetContainer(scene, data, rootUrl, onError, true);\n if (!container) {\n return false;\n }\n if (parsedData.autoAnimate) {\n scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);\n }\n if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {\n scene.setActiveCameraById(parsedData.activeCameraID);\n }\n // Finish\n return true;\n }\n catch (err) {\n const msg = logOperation(\"importScene\", parsedData ? parsedData.producer : \"Unknown\") + log;\n if (onError) {\n onError(msg, err);\n }\n else {\n Logger.Log(msg);\n throw err;\n }\n }\n finally {\n if (log !== null && SceneLoader.loggingLevel !== SceneLoader.NO_LOGGING) {\n Logger.Log(logOperation(\"importScene\", parsedData ? parsedData.producer : \"Unknown\") + (SceneLoader.loggingLevel !== SceneLoader.MINIMAL_LOGGING ? log : \"\"));\n }\n }\n return false;\n },\n loadAssetContainer: (scene, data, rootUrl, onError) => {\n const container = loadAssetContainer(scene, data, rootUrl, onError);\n return container;\n },\n});\n//# sourceMappingURL=babylonFileLoader.js.map","export {};\n//# sourceMappingURL=iEffectFallbacks.js.map","import { DeepCopier } from \"../Misc/deepCopier.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { SerializationHelper } from \"../Misc/decorators.js\";\n\n/**\n * This represents all the required information to add a fresnel effect on a material:\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/fresnelParameters\n */\nexport class FresnelParameters {\n /**\n * Define if the fresnel effect is enable or not.\n */\n get isEnabled() {\n return this._isEnabled;\n }\n set isEnabled(value) {\n if (this._isEnabled === value) {\n return;\n }\n this._isEnabled = value;\n Engine.MarkAllMaterialsAsDirty(4 | 16);\n }\n /**\n * Creates a new FresnelParameters object.\n *\n * @param options provide your own settings to optionally to override defaults\n */\n constructor(options = {}) {\n this._isEnabled = true;\n this.bias = options.bias === undefined ? 0 : options.bias;\n this.power = options.power === undefined ? 1 : options.power;\n this.leftColor = options.leftColor || Color3.White();\n this.rightColor = options.rightColor || Color3.Black();\n if (options.isEnabled === false) {\n this.isEnabled = false;\n }\n }\n /**\n * Clones the current fresnel and its values\n * @returns a clone fresnel configuration\n */\n clone() {\n const newFresnelParameters = new FresnelParameters();\n DeepCopier.DeepCopy(this, newFresnelParameters);\n return newFresnelParameters;\n }\n /**\n * Determines equality between FresnelParameters objects\n * @param otherFresnelParameters defines the second operand\n * @returns true if the power, bias, leftColor, rightColor and isEnabled values are equal to the given ones\n */\n equals(otherFresnelParameters) {\n return (otherFresnelParameters &&\n this.bias === otherFresnelParameters.bias &&\n this.power === otherFresnelParameters.power &&\n this.leftColor.equals(otherFresnelParameters.leftColor) &&\n this.rightColor.equals(otherFresnelParameters.rightColor) &&\n this.isEnabled === otherFresnelParameters.isEnabled);\n }\n /**\n * Serializes the current fresnel parameters to a JSON representation.\n * @returns the JSON serialization\n */\n serialize() {\n return {\n isEnabled: this.isEnabled,\n leftColor: this.leftColor.asArray(),\n rightColor: this.rightColor.asArray(),\n bias: this.bias,\n power: this.power,\n };\n }\n /**\n * Parse a JSON object and deserialize it to a new Fresnel parameter object.\n * @param parsedFresnelParameters Define the JSON representation\n * @returns the parsed parameters\n */\n static Parse(parsedFresnelParameters) {\n return new FresnelParameters({\n isEnabled: parsedFresnelParameters.isEnabled,\n leftColor: Color3.FromArray(parsedFresnelParameters.leftColor),\n rightColor: Color3.FromArray(parsedFresnelParameters.rightColor),\n bias: parsedFresnelParameters.bias,\n power: parsedFresnelParameters.power || 1.0,\n });\n }\n}\n// References the dependencies.\nSerializationHelper._FresnelParametersParser = FresnelParameters.Parse;\n//# sourceMappingURL=fresnelParameters.js.map","export * from \"./babylonFileLoader.js\";\n//# sourceMappingURL=index.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./loadingScreen.js\";\nexport * from \"./Plugins/index.js\";\nexport * from \"./sceneLoader.js\";\nexport * from \"./sceneLoaderFlags.js\";\n//# sourceMappingURL=index.js.map","export * from \"./backgroundMaterial.js\";\n//# sourceMappingURL=index.js.map","import { Color4 } from \"../../Maths/math.color.js\";\nimport { ShaderMaterial } from \"../shaderMaterial.js\";\nimport \"../../Shaders/color.fragment.js\";\nimport \"../../Shaders/color.vertex.js\";\n/**\n * A material to use for fast depth-only rendering.\n * @since 5.0.0\n */\nexport class OcclusionMaterial extends ShaderMaterial {\n constructor(name, scene) {\n super(name, scene, \"color\", {\n attributes: [\"position\"],\n uniforms: [\"world\", \"viewProjection\", \"color\"],\n });\n this.disableColorWrite = true;\n this.forceDepthWrite = true;\n this.setColor4(\"color\", new Color4(0, 0, 0, 1));\n }\n}\n//# sourceMappingURL=occlusionMaterial.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize, serializeAsColor3, expandToProperty, serializeAsTexture } from \"../../Misc/decorators.js\";\nimport { Color3 } from \"../../Maths/math.color.js\";\nimport { PBRBaseMaterial } from \"./pbrBaseMaterial.js\";\n/**\n * The Physically based simple base material of BJS.\n *\n * This enables better naming and convention enforcements on top of the pbrMaterial.\n * It is used as the base class for both the specGloss and metalRough conventions.\n */\nexport class PBRBaseSimpleMaterial extends PBRBaseMaterial {\n /**\n * Gets the current double sided mode.\n */\n get doubleSided() {\n return this._twoSidedLighting;\n }\n /**\n * If sets to true and backfaceCulling is false, normals will be flipped on the backside.\n */\n set doubleSided(value) {\n if (this._twoSidedLighting === value) {\n return;\n }\n this._twoSidedLighting = value;\n this.backFaceCulling = !value;\n this._markAllSubMeshesAsTexturesDirty();\n }\n /**\n * Instantiates a new PBRMaterial instance.\n *\n * @param name The material name\n * @param scene The scene the material will be use in.\n */\n constructor(name, scene) {\n super(name, scene);\n /**\n * Number of Simultaneous lights allowed on the material.\n */\n this.maxSimultaneousLights = 4;\n /**\n * If sets to true, disables all the lights affecting the material.\n */\n this.disableLighting = false;\n /**\n * If sets to true, x component of normal map value will invert (x = 1.0 - x).\n */\n this.invertNormalMapX = false;\n /**\n * If sets to true, y component of normal map value will invert (y = 1.0 - y).\n */\n this.invertNormalMapY = false;\n /**\n * Emissivie color used to self-illuminate the model.\n */\n this.emissiveColor = new Color3(0, 0, 0);\n /**\n * Occlusion Channel Strength.\n */\n this.occlusionStrength = 1.0;\n /**\n * If true, the light map contains occlusion information instead of lighting info.\n */\n this.useLightmapAsShadowmap = false;\n this._useAlphaFromAlbedoTexture = true;\n this._useAmbientInGrayScale = true;\n }\n getClassName() {\n return \"PBRBaseSimpleMaterial\";\n }\n}\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n], PBRBaseSimpleMaterial.prototype, \"maxSimultaneousLights\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsLightsDirty\")\n], PBRBaseSimpleMaterial.prototype, \"disableLighting\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_reflectionTexture\")\n], PBRBaseSimpleMaterial.prototype, \"environmentTexture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRBaseSimpleMaterial.prototype, \"invertNormalMapX\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRBaseSimpleMaterial.prototype, \"invertNormalMapY\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_bumpTexture\")\n], PBRBaseSimpleMaterial.prototype, \"normalTexture\", void 0);\n__decorate([\n serializeAsColor3(\"emissive\"),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRBaseSimpleMaterial.prototype, \"emissiveColor\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRBaseSimpleMaterial.prototype, \"emissiveTexture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_ambientTextureStrength\")\n], PBRBaseSimpleMaterial.prototype, \"occlusionStrength\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_ambientTexture\")\n], PBRBaseSimpleMaterial.prototype, \"occlusionTexture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_alphaCutOff\")\n], PBRBaseSimpleMaterial.prototype, \"alphaCutOff\", void 0);\n__decorate([\n serialize()\n], PBRBaseSimpleMaterial.prototype, \"doubleSided\", null);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", null)\n], PBRBaseSimpleMaterial.prototype, \"lightmapTexture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRBaseSimpleMaterial.prototype, \"useLightmapAsShadowmap\", void 0);\n//# sourceMappingURL=pbrBaseSimpleMaterial.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize, SerializationHelper, serializeAsColor3, expandToProperty, serializeAsTexture } from \"../../Misc/decorators.js\";\nimport { PBRBaseSimpleMaterial } from \"./pbrBaseSimpleMaterial.js\";\nimport { RegisterClass } from \"../../Misc/typeStore.js\";\n/**\n * The PBR material of BJS following the metal roughness convention.\n *\n * This fits to the PBR convention in the GLTF definition:\n * https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Archived/KHR_materials_pbrSpecularGlossiness/README.md\n */\nexport class PBRMetallicRoughnessMaterial extends PBRBaseSimpleMaterial {\n /**\n * Instantiates a new PBRMetalRoughnessMaterial instance.\n *\n * @param name The material name\n * @param scene The scene the material will be use in.\n */\n constructor(name, scene) {\n super(name, scene);\n this._useRoughnessFromMetallicTextureAlpha = false;\n this._useRoughnessFromMetallicTextureGreen = true;\n this._useMetallnessFromMetallicTextureBlue = true;\n this.metallic = 1.0;\n this.roughness = 1.0;\n }\n /**\n * Return the current class name of the material.\n */\n getClassName() {\n return \"PBRMetallicRoughnessMaterial\";\n }\n /**\n * Makes a duplicate of the current material.\n * @param name - name to use for the new material.\n */\n clone(name) {\n const clone = SerializationHelper.Clone(() => new PBRMetallicRoughnessMaterial(name, this.getScene()), this);\n clone.id = name;\n clone.name = name;\n this.clearCoat.copyTo(clone.clearCoat);\n this.anisotropy.copyTo(clone.anisotropy);\n this.brdf.copyTo(clone.brdf);\n this.sheen.copyTo(clone.sheen);\n this.subSurface.copyTo(clone.subSurface);\n return clone;\n }\n /**\n * Serialize the material to a parsable JSON object.\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this);\n serializationObject.customType = \"BABYLON.PBRMetallicRoughnessMaterial\";\n serializationObject.clearCoat = this.clearCoat.serialize();\n serializationObject.anisotropy = this.anisotropy.serialize();\n serializationObject.brdf = this.brdf.serialize();\n serializationObject.sheen = this.sheen.serialize();\n serializationObject.subSurface = this.subSurface.serialize();\n serializationObject.iridescence = this.iridescence.serialize();\n return serializationObject;\n }\n /**\n * Parses a JSON object corresponding to the serialize function.\n * @param source\n * @param scene\n * @param rootUrl\n */\n static Parse(source, scene, rootUrl) {\n const material = SerializationHelper.Parse(() => new PBRMetallicRoughnessMaterial(source.name, scene), source, scene, rootUrl);\n if (source.clearCoat) {\n material.clearCoat.parse(source.clearCoat, scene, rootUrl);\n }\n if (source.anisotropy) {\n material.anisotropy.parse(source.anisotropy, scene, rootUrl);\n }\n if (source.brdf) {\n material.brdf.parse(source.brdf, scene, rootUrl);\n }\n if (source.sheen) {\n material.sheen.parse(source.sheen, scene, rootUrl);\n }\n if (source.subSurface) {\n material.subSurface.parse(source.subSurface, scene, rootUrl);\n }\n if (source.iridescence) {\n material.iridescence.parse(source.iridescence, scene, rootUrl);\n }\n return material;\n }\n}\n__decorate([\n serializeAsColor3(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_albedoColor\")\n], PBRMetallicRoughnessMaterial.prototype, \"baseColor\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_albedoTexture\")\n], PBRMetallicRoughnessMaterial.prototype, \"baseTexture\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMetallicRoughnessMaterial.prototype, \"metallic\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], PBRMetallicRoughnessMaterial.prototype, \"roughness\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_metallicTexture\")\n], PBRMetallicRoughnessMaterial.prototype, \"metallicRoughnessTexture\", void 0);\nRegisterClass(\"BABYLON.PBRMetallicRoughnessMaterial\", PBRMetallicRoughnessMaterial);\n//# sourceMappingURL=pbrMetallicRoughnessMaterial.js.map","import { __decorate } from \"../../tslib.es6.js\";\nimport { serialize, SerializationHelper, serializeAsColor3, expandToProperty, serializeAsTexture } from \"../../Misc/decorators.js\";\nimport { PBRBaseSimpleMaterial } from \"./pbrBaseSimpleMaterial.js\";\nimport { RegisterClass } from \"../../Misc/typeStore.js\";\n/**\n * The PBR material of BJS following the specular glossiness convention.\n *\n * This fits to the PBR convention in the GLTF definition:\n * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness\n */\nexport class PBRSpecularGlossinessMaterial extends PBRBaseSimpleMaterial {\n /**\n * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.\n */\n get useMicroSurfaceFromReflectivityMapAlpha() {\n return this._useMicroSurfaceFromReflectivityMapAlpha;\n }\n /**\n * Instantiates a new PBRSpecularGlossinessMaterial instance.\n *\n * @param name The material name\n * @param scene The scene the material will be use in.\n */\n constructor(name, scene) {\n super(name, scene);\n this._useMicroSurfaceFromReflectivityMapAlpha = true;\n }\n /**\n * Return the current class name of the material.\n */\n getClassName() {\n return \"PBRSpecularGlossinessMaterial\";\n }\n /**\n * Makes a duplicate of the current material.\n * @param name - name to use for the new material.\n */\n clone(name) {\n const clone = SerializationHelper.Clone(() => new PBRSpecularGlossinessMaterial(name, this.getScene()), this);\n clone.id = name;\n clone.name = name;\n this.clearCoat.copyTo(clone.clearCoat);\n this.anisotropy.copyTo(clone.anisotropy);\n this.brdf.copyTo(clone.brdf);\n this.sheen.copyTo(clone.sheen);\n this.subSurface.copyTo(clone.subSurface);\n return clone;\n }\n /**\n * Serialize the material to a parsable JSON object.\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this);\n serializationObject.customType = \"BABYLON.PBRSpecularGlossinessMaterial\";\n serializationObject.clearCoat = this.clearCoat.serialize();\n serializationObject.anisotropy = this.anisotropy.serialize();\n serializationObject.brdf = this.brdf.serialize();\n serializationObject.sheen = this.sheen.serialize();\n serializationObject.subSurface = this.subSurface.serialize();\n serializationObject.iridescence = this.iridescence.serialize();\n return serializationObject;\n }\n /**\n * Parses a JSON object corresponding to the serialize function.\n * @param source\n * @param scene\n * @param rootUrl\n */\n static Parse(source, scene, rootUrl) {\n const material = SerializationHelper.Parse(() => new PBRSpecularGlossinessMaterial(source.name, scene), source, scene, rootUrl);\n if (source.clearCoat) {\n material.clearCoat.parse(source.clearCoat, scene, rootUrl);\n }\n if (source.anisotropy) {\n material.anisotropy.parse(source.anisotropy, scene, rootUrl);\n }\n if (source.brdf) {\n material.brdf.parse(source.brdf, scene, rootUrl);\n }\n if (source.sheen) {\n material.sheen.parse(source.sheen, scene, rootUrl);\n }\n if (source.subSurface) {\n material.subSurface.parse(source.subSurface, scene, rootUrl);\n }\n if (source.iridescence) {\n material.iridescence.parse(source.iridescence, scene, rootUrl);\n }\n return material;\n }\n}\n__decorate([\n serializeAsColor3(\"diffuse\"),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_albedoColor\")\n], PBRSpecularGlossinessMaterial.prototype, \"diffuseColor\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_albedoTexture\")\n], PBRSpecularGlossinessMaterial.prototype, \"diffuseTexture\", void 0);\n__decorate([\n serializeAsColor3(\"specular\"),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_reflectivityColor\")\n], PBRSpecularGlossinessMaterial.prototype, \"specularColor\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_microSurface\")\n], PBRSpecularGlossinessMaterial.prototype, \"glossiness\", void 0);\n__decorate([\n serializeAsTexture(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\", \"_reflectivityTexture\")\n], PBRSpecularGlossinessMaterial.prototype, \"specularGlossinessTexture\", void 0);\nRegisterClass(\"BABYLON.PBRSpecularGlossinessMaterial\", PBRSpecularGlossinessMaterial);\n//# sourceMappingURL=pbrSpecularGlossinessMaterial.js.map","export * from \"./pbrAnisotropicConfiguration.js\";\nexport * from \"./pbrBaseMaterial.js\";\nexport * from \"./pbrBaseSimpleMaterial.js\";\nexport * from \"./pbrClearCoatConfiguration.js\";\nexport * from \"./pbrIridescenceConfiguration.js\";\nexport * from \"./pbrMaterial.js\";\nexport * from \"./pbrMetallicRoughnessMaterial.js\";\nexport * from \"./pbrSpecularGlossinessMaterial.js\";\nexport * from \"./pbrSheenConfiguration.js\";\nexport * from \"./pbrSubSurfaceConfiguration.js\";\n//# sourceMappingURL=index.js.map","import { Matrix } from \"../../Maths/math.vector.js\";\nimport { BaseTexture } from \"../../Materials/Textures/baseTexture.js\";\n\nimport { RegisterClass } from \"../../Misc/typeStore.js\";\n// Ensures Raw texture are included\nimport \"../../Engines/Extensions/engine.rawTexture.js\";\n/**\n * This represents a color grading texture. This acts as a lookup table LUT, useful during post process\n * It can help converting any input color in a desired output one. This can then be used to create effects\n * from sepia, black and white to sixties or futuristic rendering...\n *\n * The only supported format is currently 3dl.\n * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table\n */\nexport class ColorGradingTexture extends BaseTexture {\n /**\n * Instantiates a ColorGradingTexture from the following parameters.\n *\n * @param url The location of the color grading data (currently only supporting 3dl)\n * @param sceneOrEngine The scene or engine the texture will be used in\n * @param onLoad defines a callback triggered when the texture has been loaded\n */\n constructor(url, sceneOrEngine, onLoad = null) {\n super(sceneOrEngine);\n if (!url) {\n return;\n }\n this._textureMatrix = Matrix.Identity();\n this.name = url;\n this.url = url;\n this._onLoad = onLoad;\n this._texture = this._getFromCache(url, true);\n if (!this._texture) {\n const scene = this.getScene();\n if (scene) {\n if (!scene.useDelayedTextureLoading) {\n this._loadTexture();\n }\n else {\n this.delayLoadState = 4;\n }\n }\n else {\n this._loadTexture();\n }\n }\n else {\n this._triggerOnLoad();\n }\n }\n /**\n * Fires the onload event from the constructor if requested.\n */\n _triggerOnLoad() {\n if (this._onLoad) {\n this._onLoad();\n }\n }\n /**\n * Returns the texture matrix used in most of the material.\n * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).\n */\n getTextureMatrix() {\n return this._textureMatrix;\n }\n /**\n * Occurs when the file being loaded is a .3dl LUT file.\n */\n _load3dlTexture() {\n const engine = this._getEngine();\n let texture;\n if (!engine._features.support3DTextures) {\n texture = engine.createRawTexture(null, 1, 1, 5, false, false, 2, null, 0);\n }\n else {\n texture = engine.createRawTexture3D(null, 1, 1, 1, 5, false, false, 2, null, 0);\n }\n this._texture = texture;\n this._texture.isReady = false;\n this.isCube = false;\n this.is3D = engine._features.support3DTextures;\n this.wrapU = 0;\n this.wrapV = 0;\n this.wrapR = 0;\n this.anisotropicFilteringLevel = 1;\n const callback = (text) => {\n if (typeof text !== \"string\") {\n return;\n }\n let data = null;\n let tempData = null;\n let line;\n const lines = text.split(\"\\n\");\n let size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;\n let maxColor = 0;\n for (let i = 0; i < lines.length; i++) {\n line = lines[i];\n if (!ColorGradingTexture._NoneEmptyLineRegex.test(line)) {\n continue;\n }\n if (line.indexOf(\"#\") === 0) {\n continue;\n }\n const words = line.split(\" \");\n if (size === 0) {\n // Number of space + one\n size = words.length;\n data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8\n tempData = new Float32Array(size * size * size * 4);\n continue;\n }\n if (size != 0) {\n const r = Math.max(parseInt(words[0]), 0);\n const g = Math.max(parseInt(words[1]), 0);\n const b = Math.max(parseInt(words[2]), 0);\n maxColor = Math.max(r, maxColor);\n maxColor = Math.max(g, maxColor);\n maxColor = Math.max(b, maxColor);\n const pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;\n if (tempData) {\n tempData[pixelStorageIndex + 0] = r;\n tempData[pixelStorageIndex + 1] = g;\n tempData[pixelStorageIndex + 2] = b;\n }\n // Keep for reference in case of back compat problems.\n // pixelIndexSlice++;\n // if (pixelIndexSlice % size == 0) {\n // pixelIndexH++;\n // pixelIndexSlice = 0;\n // if (pixelIndexH % size == 0) {\n // pixelIndexW++;\n // pixelIndexH = 0;\n // }\n // }\n pixelIndexH++;\n if (pixelIndexH % size == 0) {\n pixelIndexSlice++;\n pixelIndexH = 0;\n if (pixelIndexSlice % size == 0) {\n pixelIndexW++;\n pixelIndexSlice = 0;\n }\n }\n }\n }\n if (tempData && data) {\n for (let i = 0; i < tempData.length; i++) {\n if (i > 0 && (i + 1) % 4 === 0) {\n data[i] = 255;\n }\n else {\n const value = tempData[i];\n data[i] = (value / maxColor) * 255;\n }\n }\n }\n if (texture.is3D) {\n texture.updateSize(size, size, size);\n engine.updateRawTexture3D(texture, data, 5, false);\n }\n else {\n texture.updateSize(size * size, size);\n engine.updateRawTexture(texture, data, 5, false);\n }\n texture.isReady = true;\n this._triggerOnLoad();\n };\n const scene = this.getScene();\n if (scene) {\n scene._loadFile(this.url, callback);\n }\n else {\n engine._loadFile(this.url, callback);\n }\n return this._texture;\n }\n /**\n * Starts the loading process of the texture.\n */\n _loadTexture() {\n if (this.url && this.url.toLocaleLowerCase().indexOf(\".3dl\") == this.url.length - 4) {\n this._load3dlTexture();\n }\n }\n /**\n * Clones the color grading texture.\n */\n clone() {\n const newTexture = new ColorGradingTexture(this.url, this.getScene() || this._getEngine());\n // Base texture\n newTexture.level = this.level;\n return newTexture;\n }\n /**\n * Called during delayed load for textures.\n */\n delayLoad() {\n if (this.delayLoadState !== 4) {\n return;\n }\n this.delayLoadState = 1;\n this._texture = this._getFromCache(this.url, true);\n if (!this._texture) {\n this._loadTexture();\n }\n }\n /**\n * Parses a color grading texture serialized by Babylon.\n * @param parsedTexture The texture information being parsedTexture\n * @param scene The scene to load the texture in\n * @returns A color grading texture\n */\n static Parse(parsedTexture, scene) {\n let texture = null;\n if (parsedTexture.name && !parsedTexture.isRenderTarget) {\n texture = new ColorGradingTexture(parsedTexture.name, scene);\n texture.name = parsedTexture.name;\n texture.level = parsedTexture.level;\n }\n return texture;\n }\n /**\n * Serializes the LUT texture to json format.\n */\n serialize() {\n if (!this.name) {\n return null;\n }\n const serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.level = this.level;\n serializationObject.customType = \"BABYLON.ColorGradingTexture\";\n return serializationObject;\n }\n}\n/**\n * Empty line regex stored for GC.\n */\nColorGradingTexture._NoneEmptyLineRegex = /\\S+/;\nRegisterClass(\"BABYLON.ColorGradingTexture\", ColorGradingTexture);\n//# sourceMappingURL=colorGradingTexture.js.map","import { PanoramaToCubeMapTools } from \"../../Misc/HighDynamicRange/panoramaToCubemap.js\";\nimport { BaseTexture } from \"./baseTexture.js\";\nimport { Texture } from \"./texture.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nimport \"../../Engines/Extensions/engine.rawTexture.js\";\n\nimport { LoadImage } from \"../../Misc/fileTools.js\";\n/**\n * This represents a texture coming from an equirectangular image supported by the web browser canvas.\n */\nexport class EquiRectangularCubeTexture extends BaseTexture {\n /**\n * Instantiates an EquiRectangularCubeTexture from the following parameters.\n * @param url The location of the image\n * @param scene The scene the texture will be used in\n * @param size The cubemap desired size (the more it increases the longer the generation will be)\n * @param noMipmap Forces to not generate the mipmap if true\n * @param gammaSpace Specifies if the texture will be used in gamma or linear space\n * (the PBR material requires those textures in linear space, but the standard material would require them in Gamma space)\n * @param onLoad — defines a callback called when texture is loaded\n * @param onError — defines a callback called if there is an error\n */\n constructor(url, scene, size, noMipmap = false, gammaSpace = true, onLoad = null, onError = null, supersample = false) {\n super(scene);\n this._onLoad = null;\n this._onError = null;\n if (!url) {\n throw new Error(\"Image url is not set\");\n }\n this._coordinatesMode = Texture.CUBIC_MODE;\n this.name = url;\n this.url = url;\n this._size = size;\n this._supersample = supersample;\n this._noMipmap = noMipmap;\n this.gammaSpace = gammaSpace;\n this._onLoad = onLoad;\n this._onError = onError;\n this.hasAlpha = false;\n this.isCube = true;\n this._texture = this._getFromCache(url, this._noMipmap, undefined, undefined, undefined, this.isCube);\n if (!this._texture) {\n if (!scene.useDelayedTextureLoading) {\n this._loadImage(this._loadTexture.bind(this), this._onError);\n }\n else {\n this.delayLoadState = 4;\n }\n }\n else if (onLoad) {\n if (this._texture.isReady) {\n Tools.SetImmediate(() => onLoad());\n }\n else {\n this._texture.onLoadedObservable.add(onLoad);\n }\n }\n }\n /**\n * Load the image data, by putting the image on a canvas and extracting its buffer.\n * @param loadTextureCallback\n * @param onError\n */\n _loadImage(loadTextureCallback, onError) {\n const canvas = document.createElement(\"canvas\");\n LoadImage(this.url, (image) => {\n this._width = image.width;\n this._height = image.height;\n canvas.width = this._width;\n canvas.height = this._height;\n const ctx = canvas.getContext(\"2d\");\n ctx.drawImage(image, 0, 0);\n const imageData = ctx.getImageData(0, 0, image.width, image.height);\n this._buffer = imageData.data.buffer;\n canvas.remove();\n loadTextureCallback();\n }, (_, e) => {\n if (onError) {\n onError(`${this.getClassName()} could not be loaded`, e);\n }\n }, null);\n }\n /**\n * Convert the image buffer into a cubemap and create a CubeTexture.\n */\n _loadTexture() {\n const scene = this.getScene();\n const callback = () => {\n const imageData = this._getFloat32ArrayFromArrayBuffer(this._buffer);\n // Extract the raw linear data.\n const data = PanoramaToCubeMapTools.ConvertPanoramaToCubemap(imageData, this._width, this._height, this._size, this._supersample);\n const results = [];\n // Push each faces.\n for (let i = 0; i < 6; i++) {\n const dataFace = data[EquiRectangularCubeTexture._FacesMapping[i]];\n results.push(dataFace);\n }\n return results;\n };\n if (!scene) {\n return;\n }\n this._texture = scene\n .getEngine()\n .createRawCubeTextureFromUrl(this.url, scene, this._size, 4, scene.getEngine().getCaps().textureFloat ? 1 : 7, this._noMipmap, callback, null, this._onLoad, this._onError);\n }\n /**\n * Convert the ArrayBuffer into a Float32Array and drop the transparency channel.\n * @param buffer The ArrayBuffer that should be converted.\n * @returns The buffer as Float32Array.\n */\n _getFloat32ArrayFromArrayBuffer(buffer) {\n const dataView = new DataView(buffer);\n const floatImageData = new Float32Array((buffer.byteLength * 3) / 4);\n let k = 0;\n for (let i = 0; i < buffer.byteLength; i++) {\n // We drop the transparency channel, because we do not need/want it\n if ((i + 1) % 4 !== 0) {\n floatImageData[k++] = dataView.getUint8(i) / 255;\n }\n }\n return floatImageData;\n }\n /**\n * Get the current class name of the texture useful for serialization or dynamic coding.\n * @returns \"EquiRectangularCubeTexture\"\n */\n getClassName() {\n return \"EquiRectangularCubeTexture\";\n }\n /**\n * Create a clone of the current EquiRectangularCubeTexture and return it.\n * @returns A clone of the current EquiRectangularCubeTexture.\n */\n clone() {\n const scene = this.getScene();\n if (!scene) {\n return this;\n }\n const newTexture = new EquiRectangularCubeTexture(this.url, scene, this._size, this._noMipmap, this.gammaSpace);\n // Base texture\n newTexture.level = this.level;\n newTexture.wrapU = this.wrapU;\n newTexture.wrapV = this.wrapV;\n newTexture.coordinatesIndex = this.coordinatesIndex;\n newTexture.coordinatesMode = this.coordinatesMode;\n return newTexture;\n }\n}\n/** The six faces of the cube. */\nEquiRectangularCubeTexture._FacesMapping = [\"right\", \"left\", \"up\", \"down\", \"front\", \"back\"];\n//# sourceMappingURL=equiRectangularCubeTexture.js.map","import { BaseTexture } from \"../../Materials/Textures/baseTexture.js\";\n\nimport { Matrix } from \"../../Maths/math.vector.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport \"../../Engines/Extensions/engine.dynamicTexture.js\";\nimport \"../../Engines/Extensions/engine.videoTexture.js\";\nimport \"../../Engines/Extensions/engine.externalTexture.js\";\n/**\n * This represents the smallest workload to use an already existing element (Canvas or Video) as a texture.\n * To be as efficient as possible depending on your constraints nothing aside the first upload\n * is automatically managed.\n * It is a cheap VideoTexture or DynamicTexture if you prefer to keep full control of the elements\n * in your application.\n *\n * As the update is not automatic, you need to call them manually.\n */\nexport class HtmlElementTexture extends BaseTexture {\n /**\n * Instantiates a HtmlElementTexture from the following parameters.\n *\n * @param name Defines the name of the texture\n * @param element Defines the video or canvas the texture is filled with\n * @param options Defines the other none mandatory texture creation options\n */\n constructor(name, element, options) {\n var _a, _b;\n super(options.scene || options.engine);\n /**\n * Observable triggered once the texture has been loaded.\n */\n this.onLoadObservable = new Observable();\n if (!element || (!options.engine && !options.scene)) {\n return;\n }\n options = Object.assign(Object.assign({}, HtmlElementTexture._DefaultOptions), options);\n this._generateMipMaps = options.generateMipMaps;\n this._samplingMode = options.samplingMode;\n this._textureMatrix = Matrix.Identity();\n this._format = options.format;\n this.name = name;\n this.element = element;\n this._isVideo = !!element.getVideoPlaybackQuality;\n this._externalTexture = this._isVideo ? (_b = (_a = this._engine) === null || _a === void 0 ? void 0 : _a.createExternalTexture(element)) !== null && _b !== void 0 ? _b : null : null;\n this.anisotropicFilteringLevel = 1;\n this._createInternalTexture();\n }\n _createInternalTexture() {\n let width = 0;\n let height = 0;\n if (this._isVideo) {\n width = this.element.videoWidth;\n height = this.element.videoHeight;\n }\n else {\n width = this.element.width;\n height = this.element.height;\n }\n const engine = this._getEngine();\n if (engine) {\n this._texture = engine.createDynamicTexture(width, height, this._generateMipMaps, this._samplingMode);\n this._texture.format = this._format;\n }\n this.update();\n }\n /**\n * Returns the texture matrix used in most of the material.\n */\n getTextureMatrix() {\n return this._textureMatrix;\n }\n /**\n * Updates the content of the texture.\n * @param invertY Defines whether the texture should be inverted on Y (false by default on video and true on canvas)\n */\n update(invertY = null) {\n const engine = this._getEngine();\n if (this._texture == null || engine == null) {\n return;\n }\n const wasReady = this.isReady();\n if (this._isVideo) {\n const videoElement = this.element;\n if (videoElement.readyState < videoElement.HAVE_CURRENT_DATA) {\n return;\n }\n engine.updateVideoTexture(this._texture, this._externalTexture ? this._externalTexture : videoElement, invertY === null ? true : invertY);\n }\n else {\n const canvasElement = this.element;\n engine.updateDynamicTexture(this._texture, canvasElement, invertY === null ? true : invertY, false, this._format);\n }\n if (!wasReady && this.isReady()) {\n this.onLoadObservable.notifyObservers(this);\n }\n }\n /**\n * Dispose the texture and release its associated resources.\n */\n dispose() {\n this.onLoadObservable.clear();\n super.dispose();\n }\n}\nHtmlElementTexture._DefaultOptions = {\n generateMipMaps: false,\n samplingMode: 2,\n format: 5,\n engine: null,\n scene: null,\n};\n//# sourceMappingURL=htmlElementTexture.js.map","export {};\n//# sourceMappingURL=internalTextureLoader.js.map","import { Logger } from \"../Misc/logger.js\";\n//private static _TYPE_NO_DATA = 0;\nconst _TYPE_INDEXED = 1;\nconst _TYPE_RGB = 2;\nconst _TYPE_GREY = 3;\nconst _TYPE_RLE_INDEXED = 9;\nconst _TYPE_RLE_RGB = 10;\nconst _TYPE_RLE_GREY = 11;\nconst _ORIGIN_MASK = 0x30;\nconst _ORIGIN_SHIFT = 0x04;\nconst _ORIGIN_BL = 0x00;\nconst _ORIGIN_BR = 0x01;\nconst _ORIGIN_UL = 0x02;\nconst _ORIGIN_UR = 0x03;\n/**\n * Gets the header of a TGA file\n * @param data defines the TGA data\n * @returns the header\n */\nexport function GetTGAHeader(data) {\n let offset = 0;\n const header = {\n id_length: data[offset++],\n colormap_type: data[offset++],\n image_type: data[offset++],\n colormap_index: data[offset++] | (data[offset++] << 8),\n colormap_length: data[offset++] | (data[offset++] << 8),\n colormap_size: data[offset++],\n origin: [data[offset++] | (data[offset++] << 8), data[offset++] | (data[offset++] << 8)],\n width: data[offset++] | (data[offset++] << 8),\n height: data[offset++] | (data[offset++] << 8),\n pixel_size: data[offset++],\n flags: data[offset++],\n };\n return header;\n}\n/**\n * Uploads TGA content to a Babylon Texture\n * @internal\n */\nexport function UploadContent(texture, data) {\n // Not enough data to contain header ?\n if (data.length < 19) {\n Logger.Error(\"Unable to load TGA file - Not enough data to contain header\");\n return;\n }\n // Read Header\n let offset = 18;\n const header = GetTGAHeader(data);\n // Assume it's a valid Targa file.\n if (header.id_length + offset > data.length) {\n Logger.Error(\"Unable to load TGA file - Not enough data\");\n return;\n }\n // Skip not needed data\n offset += header.id_length;\n let use_rle = false;\n let use_pal = false;\n let use_grey = false;\n // Get some informations.\n switch (header.image_type) {\n case _TYPE_RLE_INDEXED:\n use_rle = true;\n // eslint-disable-next-line no-fallthrough\n case _TYPE_INDEXED:\n use_pal = true;\n break;\n case _TYPE_RLE_RGB:\n use_rle = true;\n // eslint-disable-next-line no-fallthrough\n case _TYPE_RGB:\n // use_rgb = true;\n break;\n case _TYPE_RLE_GREY:\n use_rle = true;\n // eslint-disable-next-line no-fallthrough\n case _TYPE_GREY:\n use_grey = true;\n break;\n }\n let pixel_data;\n // var numAlphaBits = header.flags & 0xf;\n const pixel_size = header.pixel_size >> 3;\n const pixel_total = header.width * header.height * pixel_size;\n // Read palettes\n let palettes;\n if (use_pal) {\n palettes = data.subarray(offset, (offset += header.colormap_length * (header.colormap_size >> 3)));\n }\n // Read LRE\n if (use_rle) {\n pixel_data = new Uint8Array(pixel_total);\n let c, count, i;\n let localOffset = 0;\n const pixels = new Uint8Array(pixel_size);\n while (offset < pixel_total && localOffset < pixel_total) {\n c = data[offset++];\n count = (c & 0x7f) + 1;\n // RLE pixels\n if (c & 0x80) {\n // Bind pixel tmp array\n for (i = 0; i < pixel_size; ++i) {\n pixels[i] = data[offset++];\n }\n // Copy pixel array\n for (i = 0; i < count; ++i) {\n pixel_data.set(pixels, localOffset + i * pixel_size);\n }\n localOffset += pixel_size * count;\n }\n // Raw pixels\n else {\n count *= pixel_size;\n for (i = 0; i < count; ++i) {\n pixel_data[localOffset + i] = data[offset++];\n }\n localOffset += count;\n }\n }\n }\n // RAW Pixels\n else {\n pixel_data = data.subarray(offset, (offset += use_pal ? header.width * header.height : pixel_total));\n }\n // Load to texture\n let x_start, y_start, x_step, y_step, y_end, x_end;\n switch ((header.flags & _ORIGIN_MASK) >> _ORIGIN_SHIFT) {\n default:\n case _ORIGIN_UL:\n x_start = 0;\n x_step = 1;\n x_end = header.width;\n y_start = 0;\n y_step = 1;\n y_end = header.height;\n break;\n case _ORIGIN_BL:\n x_start = 0;\n x_step = 1;\n x_end = header.width;\n y_start = header.height - 1;\n y_step = -1;\n y_end = -1;\n break;\n case _ORIGIN_UR:\n x_start = header.width - 1;\n x_step = -1;\n x_end = -1;\n y_start = 0;\n y_step = 1;\n y_end = header.height;\n break;\n case _ORIGIN_BR:\n x_start = header.width - 1;\n x_step = -1;\n x_end = -1;\n y_start = header.height - 1;\n y_step = -1;\n y_end = -1;\n break;\n }\n // Load the specify method\n const func = \"_getImageData\" + (use_grey ? \"Grey\" : \"\") + header.pixel_size + \"bits\";\n const imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);\n const engine = texture.getEngine();\n engine._uploadDataToTextureDirectly(texture, imageData);\n}\n/**\n * @internal\n */\nfunction _getImageData8bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {\n const image = pixel_data, colormap = palettes;\n const width = header.width, height = header.height;\n let color, i = 0, x, y;\n const imageData = new Uint8Array(width * height * 4);\n for (y = y_start; y !== y_end; y += y_step) {\n for (x = x_start; x !== x_end; x += x_step, i++) {\n color = image[i];\n imageData[(x + width * y) * 4 + 3] = 255;\n imageData[(x + width * y) * 4 + 2] = colormap[color * 3 + 0];\n imageData[(x + width * y) * 4 + 1] = colormap[color * 3 + 1];\n imageData[(x + width * y) * 4 + 0] = colormap[color * 3 + 2];\n }\n }\n return imageData;\n}\n/**\n * @internal\n */\nfunction _getImageData16bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {\n const image = pixel_data;\n const width = header.width, height = header.height;\n let color, i = 0, x, y;\n const imageData = new Uint8Array(width * height * 4);\n for (y = y_start; y !== y_end; y += y_step) {\n for (x = x_start; x !== x_end; x += x_step, i += 2) {\n color = image[i + 0] + (image[i + 1] << 8); // Inversed ?\n const r = ((((color & 0x7c00) >> 10) * 255) / 0x1f) | 0;\n const g = ((((color & 0x03e0) >> 5) * 255) / 0x1f) | 0;\n const b = (((color & 0x001f) * 255) / 0x1f) | 0;\n imageData[(x + width * y) * 4 + 0] = r;\n imageData[(x + width * y) * 4 + 1] = g;\n imageData[(x + width * y) * 4 + 2] = b;\n imageData[(x + width * y) * 4 + 3] = color & 0x8000 ? 0 : 255;\n }\n }\n return imageData;\n}\n/**\n * @internal\n */\nfunction _getImageData24bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {\n const image = pixel_data;\n const width = header.width, height = header.height;\n let i = 0, x, y;\n const imageData = new Uint8Array(width * height * 4);\n for (y = y_start; y !== y_end; y += y_step) {\n for (x = x_start; x !== x_end; x += x_step, i += 3) {\n imageData[(x + width * y) * 4 + 3] = 255;\n imageData[(x + width * y) * 4 + 2] = image[i + 0];\n imageData[(x + width * y) * 4 + 1] = image[i + 1];\n imageData[(x + width * y) * 4 + 0] = image[i + 2];\n }\n }\n return imageData;\n}\n/**\n * @internal\n */\nfunction _getImageData32bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {\n const image = pixel_data;\n const width = header.width, height = header.height;\n let i = 0, x, y;\n const imageData = new Uint8Array(width * height * 4);\n for (y = y_start; y !== y_end; y += y_step) {\n for (x = x_start; x !== x_end; x += x_step, i += 4) {\n imageData[(x + width * y) * 4 + 2] = image[i + 0];\n imageData[(x + width * y) * 4 + 1] = image[i + 1];\n imageData[(x + width * y) * 4 + 0] = image[i + 2];\n imageData[(x + width * y) * 4 + 3] = image[i + 3];\n }\n }\n return imageData;\n}\n/**\n * @internal\n */\nfunction _getImageDataGrey8bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {\n const image = pixel_data;\n const width = header.width, height = header.height;\n let color, i = 0, x, y;\n const imageData = new Uint8Array(width * height * 4);\n for (y = y_start; y !== y_end; y += y_step) {\n for (x = x_start; x !== x_end; x += x_step, i++) {\n color = image[i];\n imageData[(x + width * y) * 4 + 0] = color;\n imageData[(x + width * y) * 4 + 1] = color;\n imageData[(x + width * y) * 4 + 2] = color;\n imageData[(x + width * y) * 4 + 3] = 255;\n }\n }\n return imageData;\n}\n/**\n * @internal\n */\nfunction _getImageDataGrey16bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {\n const image = pixel_data;\n const width = header.width, height = header.height;\n let i = 0, x, y;\n const imageData = new Uint8Array(width * height * 4);\n for (y = y_start; y !== y_end; y += y_step) {\n for (x = x_start; x !== x_end; x += x_step, i += 2) {\n imageData[(x + width * y) * 4 + 0] = image[i + 0];\n imageData[(x + width * y) * 4 + 1] = image[i + 0];\n imageData[(x + width * y) * 4 + 2] = image[i + 0];\n imageData[(x + width * y) * 4 + 3] = image[i + 1];\n }\n }\n return imageData;\n}\n/**\n * Based on jsTGALoader - Javascript loader for TGA file\n * By Vincent Thibault\n * @see http://blog.robrowser.com/javascript-tga-loader.html\n */\nexport const TGATools = {\n /**\n * Gets the header of a TGA file\n * @param data defines the TGA data\n * @returns the header\n */\n GetTGAHeader,\n /**\n * Uploads TGA content to a Babylon Texture\n * @internal\n */\n UploadContent,\n /** @internal */\n _getImageData8bits,\n /** @internal */\n _getImageData16bits,\n /** @internal */\n _getImageData24bits,\n /** @internal */\n _getImageData32bits,\n /** @internal */\n _getImageDataGrey8bits,\n /** @internal */\n _getImageDataGrey16bits,\n};\n//# sourceMappingURL=tga.js.map","import { GetTGAHeader, UploadContent } from \"../../../Misc/tga.js\";\nimport { Engine } from \"../../../Engines/engine.js\";\n/**\n * Implementation of the TGA Texture Loader.\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class _TGATextureLoader {\n constructor() {\n /**\n * Defines whether the loader supports cascade loading the different faces.\n */\n this.supportCascades = false;\n }\n /**\n * This returns if the loader support the current file information.\n * @param extension defines the file extension of the file being loaded\n * @returns true if the loader can load the specified file\n */\n canLoad(extension) {\n return extension.endsWith(\".tga\");\n }\n /**\n * Uploads the cube texture data to the WebGL texture. It has already been bound.\n */\n loadCubeData() {\n throw \".env not supported in Cube.\";\n }\n /**\n * Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param callback defines the method to call once ready to upload\n */\n loadData(data, texture, callback) {\n const bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n const header = GetTGAHeader(bytes);\n callback(header.width, header.height, texture.generateMipMaps, false, () => {\n UploadContent(texture, bytes);\n });\n }\n}\n// Register the loader.\nEngine._TextureLoaders.push(new _TGATextureLoader());\n//# sourceMappingURL=tgaTextureLoader.js.map","import { HDRTools } from \"../../../Misc/HighDynamicRange/hdr.js\";\nimport { Engine } from \"../../../Engines/engine.js\";\n\n/**\n * Implementation of the HDR Texture Loader.\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class _HDRTextureLoader {\n constructor() {\n /**\n * Defines whether the loader supports cascade loading the different faces.\n */\n this.supportCascades = false;\n }\n /**\n * This returns if the loader support the current file information.\n * @param extension defines the file extension of the file being loaded\n * @returns true if the loader can load the specified file\n */\n canLoad(extension) {\n return extension.endsWith(\".hdr\");\n }\n /**\n * Uploads the cube texture data to the WebGL texture. It has already been bound.\n */\n loadCubeData() {\n throw \".env not supported in Cube.\";\n }\n /**\n * Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param callback defines the method to call once ready to upload\n */\n loadData(data, texture, callback) {\n const uint8array = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n const hdrInfo = HDRTools.RGBE_ReadHeader(uint8array);\n const pixelsDataRGB32 = HDRTools.RGBE_ReadPixels(uint8array, hdrInfo);\n const pixels = hdrInfo.width * hdrInfo.height;\n const pixelsDataRGBA32 = new Float32Array(pixels * 4);\n for (let i = 0; i < pixels; i += 1) {\n pixelsDataRGBA32[i * 4] = pixelsDataRGB32[i * 3];\n pixelsDataRGBA32[i * 4 + 1] = pixelsDataRGB32[i * 3 + 1];\n pixelsDataRGBA32[i * 4 + 2] = pixelsDataRGB32[i * 3 + 2];\n pixelsDataRGBA32[i * 4 + 3] = 1;\n }\n callback(hdrInfo.width, hdrInfo.height, texture.generateMipMaps, false, () => {\n const engine = texture.getEngine();\n texture.type = 1;\n texture.format = 5;\n texture._gammaSpace = false;\n engine._uploadDataToTextureDirectly(texture, pixelsDataRGBA32);\n });\n }\n}\n// Register the loader.\nEngine._TextureLoaders.push(new _HDRTextureLoader());\n//# sourceMappingURL=hdrTextureLoader.js.map","import { Tools } from \"./tools.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { InternalTexture, InternalTextureSource } from \"../Materials/Textures/internalTexture.js\";\nimport { Scalar } from \"../Maths/math.scalar.js\";\n\n/**\n * Info about the .basis files\n */\nclass BasisFileInfo {\n}\n/**\n * Result of transcoding a basis file\n */\nclass TranscodeResult {\n}\n/**\n * Configuration options for the Basis transcoder\n */\nexport class BasisTranscodeConfiguration {\n}\n/**\n * @internal\n * Enum of basis transcoder formats\n */\nvar BASIS_FORMATS;\n(function (BASIS_FORMATS) {\n BASIS_FORMATS[BASIS_FORMATS[\"cTFETC1\"] = 0] = \"cTFETC1\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFETC2\"] = 1] = \"cTFETC2\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFBC1\"] = 2] = \"cTFBC1\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFBC3\"] = 3] = \"cTFBC3\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFBC4\"] = 4] = \"cTFBC4\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFBC5\"] = 5] = \"cTFBC5\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFBC7\"] = 6] = \"cTFBC7\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFPVRTC1_4_RGB\"] = 8] = \"cTFPVRTC1_4_RGB\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFPVRTC1_4_RGBA\"] = 9] = \"cTFPVRTC1_4_RGBA\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFASTC_4x4\"] = 10] = \"cTFASTC_4x4\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFATC_RGB\"] = 11] = \"cTFATC_RGB\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFATC_RGBA_INTERPOLATED_ALPHA\"] = 12] = \"cTFATC_RGBA_INTERPOLATED_ALPHA\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFRGBA32\"] = 13] = \"cTFRGBA32\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFRGB565\"] = 14] = \"cTFRGB565\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFBGR565\"] = 15] = \"cTFBGR565\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFRGBA4444\"] = 16] = \"cTFRGBA4444\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFFXT1_RGB\"] = 17] = \"cTFFXT1_RGB\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFPVRTC2_4_RGB\"] = 18] = \"cTFPVRTC2_4_RGB\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFPVRTC2_4_RGBA\"] = 19] = \"cTFPVRTC2_4_RGBA\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFETC2_EAC_R11\"] = 20] = \"cTFETC2_EAC_R11\";\n BASIS_FORMATS[BASIS_FORMATS[\"cTFETC2_EAC_RG11\"] = 21] = \"cTFETC2_EAC_RG11\";\n})(BASIS_FORMATS || (BASIS_FORMATS = {}));\n/**\n * Used to load .Basis files\n * See https://github.com/BinomialLLC/basis_universal/tree/master/webgl\n */\nexport const BasisToolsOptions = {\n /**\n * URL to use when loading the basis transcoder\n */\n JSModuleURL: \"https://cdn.babylonjs.com/basisTranscoder/1/basis_transcoder.js\",\n /**\n * URL to use when loading the wasm module for the transcoder\n */\n WasmModuleURL: \"https://cdn.babylonjs.com/basisTranscoder/1/basis_transcoder.wasm\",\n};\n/**\n * Get the internal format to be passed to texImage2D corresponding to the .basis format value\n * @param basisFormat format chosen from GetSupportedTranscodeFormat\n * @param engine\n * @returns internal format corresponding to the Basis format\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport const GetInternalFormatFromBasisFormat = (basisFormat, engine) => {\n let format;\n switch (basisFormat) {\n case BASIS_FORMATS.cTFETC1:\n format = 36196;\n break;\n case BASIS_FORMATS.cTFBC1:\n format = 33776;\n break;\n case BASIS_FORMATS.cTFBC4:\n format = 33779;\n break;\n case BASIS_FORMATS.cTFASTC_4x4:\n format = 37808;\n break;\n case BASIS_FORMATS.cTFETC2:\n format = 37496;\n break;\n case BASIS_FORMATS.cTFBC7:\n format = 36492;\n break;\n }\n if (format === undefined) {\n throw \"The chosen Basis transcoder format is not currently supported\";\n }\n return format;\n};\nlet _WorkerPromise = null;\nlet _Worker = null;\nlet _actionId = 0;\nconst _IgnoreSupportedFormats = false;\nconst _CreateWorkerAsync = () => {\n if (!_WorkerPromise) {\n _WorkerPromise = new Promise((res, reject) => {\n if (_Worker) {\n res(_Worker);\n }\n else {\n Tools.LoadFileAsync(BasisToolsOptions.WasmModuleURL)\n .then((wasmBinary) => {\n if (typeof URL !== \"function\") {\n return reject(\"Basis transcoder requires an environment with a URL constructor\");\n }\n const workerBlobUrl = URL.createObjectURL(new Blob([`(${workerFunc})()`], { type: \"application/javascript\" }));\n _Worker = new Worker(workerBlobUrl);\n const initHandler = (msg) => {\n if (msg.data.action === \"init\") {\n _Worker.removeEventListener(\"message\", initHandler);\n res(_Worker);\n }\n else if (msg.data.action === \"error\") {\n reject(msg.data.error || \"error initializing worker\");\n }\n };\n _Worker.addEventListener(\"message\", initHandler);\n _Worker.postMessage({ action: \"init\", url: BasisToolsOptions.JSModuleURL, wasmBinary: wasmBinary });\n })\n .catch(reject);\n }\n });\n }\n return _WorkerPromise;\n};\n/**\n * Transcodes a loaded image file to compressed pixel data\n * @param data image data to transcode\n * @param config configuration options for the transcoding\n * @returns a promise resulting in the transcoded image\n */\nexport const TranscodeAsync = (data, config) => {\n const dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;\n return new Promise((res, rej) => {\n _CreateWorkerAsync().then(() => {\n const actionId = _actionId++;\n const messageHandler = (msg) => {\n if (msg.data.action === \"transcode\" && msg.data.id === actionId) {\n _Worker.removeEventListener(\"message\", messageHandler);\n if (!msg.data.success) {\n rej(\"Transcode is not supported on this device\");\n }\n else {\n res(msg.data);\n }\n }\n };\n _Worker.addEventListener(\"message\", messageHandler);\n const dataViewCopy = new Uint8Array(dataView.byteLength);\n dataViewCopy.set(new Uint8Array(dataView.buffer, dataView.byteOffset, dataView.byteLength));\n _Worker.postMessage({ action: \"transcode\", id: actionId, imageData: dataViewCopy, config: config, ignoreSupportedFormats: _IgnoreSupportedFormats }, [\n dataViewCopy.buffer,\n ]);\n }, (error) => {\n rej(error);\n });\n });\n};\n/**\n * Binds a texture according to its underlying target.\n * @param texture texture to bind\n * @param engine the engine to bind the texture in\n */\nconst BindTexture = (texture, engine) => {\n var _a, _b;\n let target = (_a = engine._gl) === null || _a === void 0 ? void 0 : _a.TEXTURE_2D;\n if (texture.isCube) {\n target = (_b = engine._gl) === null || _b === void 0 ? void 0 : _b.TEXTURE_CUBE_MAP;\n }\n engine._bindTextureDirectly(target, texture, true);\n};\n/**\n * Loads a texture from the transcode result\n * @param texture texture load to\n * @param transcodeResult the result of transcoding the basis file to load from\n */\nexport const LoadTextureFromTranscodeResult = (texture, transcodeResult) => {\n const engine = texture.getEngine();\n for (let i = 0; i < transcodeResult.fileInfo.images.length; i++) {\n const rootImage = transcodeResult.fileInfo.images[i].levels[0];\n texture._invertVScale = texture.invertY;\n if (transcodeResult.format === -1 || transcodeResult.format === BASIS_FORMATS.cTFRGB565) {\n // No compatable compressed format found, fallback to RGB\n texture.type = 10;\n texture.format = 4;\n if (engine._features.basisNeedsPOT && (Scalar.Log2(rootImage.width) % 1 !== 0 || Scalar.Log2(rootImage.height) % 1 !== 0)) {\n // Create non power of two texture\n const source = new InternalTexture(engine, InternalTextureSource.Temp);\n texture._invertVScale = texture.invertY;\n source.type = 10;\n source.format = 4;\n // Fallback requires aligned width/height\n source.width = (rootImage.width + 3) & ~3;\n source.height = (rootImage.height + 3) & ~3;\n BindTexture(source, engine);\n engine._uploadDataToTextureDirectly(source, new Uint16Array(rootImage.transcodedPixels.buffer), i, 0, 4, true);\n // Resize to power of two\n engine._rescaleTexture(source, texture, engine.scenes[0], engine._getInternalFormat(4), () => {\n engine._releaseTexture(source);\n BindTexture(texture, engine);\n });\n }\n else {\n // Fallback is already inverted\n texture._invertVScale = !texture.invertY;\n // Upload directly\n texture.width = (rootImage.width + 3) & ~3;\n texture.height = (rootImage.height + 3) & ~3;\n texture.samplingMode = 2;\n BindTexture(texture, engine);\n engine._uploadDataToTextureDirectly(texture, new Uint16Array(rootImage.transcodedPixels.buffer), i, 0, 4, true);\n }\n }\n else {\n texture.width = rootImage.width;\n texture.height = rootImage.height;\n texture.generateMipMaps = transcodeResult.fileInfo.images[i].levels.length > 1;\n const format = BasisTools.GetInternalFormatFromBasisFormat(transcodeResult.format, engine);\n texture.format = format;\n BindTexture(texture, engine);\n // Upload all mip levels in the file\n transcodeResult.fileInfo.images[i].levels.forEach((level, index) => {\n engine._uploadCompressedDataToTextureDirectly(texture, format, level.width, level.height, level.transcodedPixels, i, index);\n });\n if (engine._features.basisNeedsPOT && (Scalar.Log2(texture.width) % 1 !== 0 || Scalar.Log2(texture.height) % 1 !== 0)) {\n Tools.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.\");\n texture._cachedWrapU = Texture.CLAMP_ADDRESSMODE;\n texture._cachedWrapV = Texture.CLAMP_ADDRESSMODE;\n }\n }\n }\n};\n/**\n * Used to load .Basis files\n * See https://github.com/BinomialLLC/basis_universal/tree/master/webgl\n */\nexport const BasisTools = {\n /**\n * URL to use when loading the basis transcoder\n */\n JSModuleURL: BasisToolsOptions.JSModuleURL,\n /**\n * URL to use when loading the wasm module for the transcoder\n */\n WasmModuleURL: BasisToolsOptions.WasmModuleURL,\n /**\n * Get the internal format to be passed to texImage2D corresponding to the .basis format value\n * @param basisFormat format chosen from GetSupportedTranscodeFormat\n * @returns internal format corresponding to the Basis format\n */\n GetInternalFormatFromBasisFormat,\n /**\n * Transcodes a loaded image file to compressed pixel data\n * @param data image data to transcode\n * @param config configuration options for the transcoding\n * @returns a promise resulting in the transcoded image\n */\n TranscodeAsync,\n /**\n * Loads a texture from the transcode result\n * @param texture texture load to\n * @param transcodeResult the result of transcoding the basis file to load from\n */\n LoadTextureFromTranscodeResult,\n};\nfunction workerFunc() {\n const _BASIS_FORMAT = {\n cTFETC1: 0,\n cTFETC2: 1,\n cTFBC1: 2,\n cTFBC3: 3,\n cTFBC4: 4,\n cTFBC5: 5,\n cTFBC7: 6,\n cTFPVRTC1_4_RGB: 8,\n cTFPVRTC1_4_RGBA: 9,\n cTFASTC_4x4: 10,\n cTFATC_RGB: 11,\n cTFATC_RGBA_INTERPOLATED_ALPHA: 12,\n cTFRGBA32: 13,\n cTFRGB565: 14,\n cTFBGR565: 15,\n cTFRGBA4444: 16,\n cTFFXT1_RGB: 17,\n cTFPVRTC2_4_RGB: 18,\n cTFPVRTC2_4_RGBA: 19,\n cTFETC2_EAC_R11: 20,\n cTFETC2_EAC_RG11: 21,\n };\n let transcoderModulePromise = null;\n onmessage = (event) => {\n if (event.data.action === \"init\") {\n // Load the transcoder if it hasn't been yet\n if (!transcoderModulePromise) {\n // make sure we loaded the script correctly\n try {\n importScripts(event.data.url);\n }\n catch (e) {\n postMessage({ action: \"error\", error: e });\n }\n transcoderModulePromise = BASIS({\n // Override wasm binary\n wasmBinary: event.data.wasmBinary,\n });\n }\n if (transcoderModulePromise !== null) {\n transcoderModulePromise.then((m) => {\n BASIS = m;\n m.initializeBasis();\n postMessage({ action: \"init\" });\n });\n }\n }\n else if (event.data.action === \"transcode\") {\n // Transcode the basis image and return the resulting pixels\n const config = event.data.config;\n const imgData = event.data.imageData;\n const loadedFile = new BASIS.BasisFile(imgData);\n const fileInfo = GetFileInfo(loadedFile);\n let format = event.data.ignoreSupportedFormats ? null : GetSupportedTranscodeFormat(event.data.config, fileInfo);\n let needsConversion = false;\n if (format === null) {\n needsConversion = true;\n format = fileInfo.hasAlpha ? _BASIS_FORMAT.cTFBC3 : _BASIS_FORMAT.cTFBC1;\n }\n // Begin transcode\n let success = true;\n if (!loadedFile.startTranscoding()) {\n success = false;\n }\n const buffers = [];\n for (let imageIndex = 0; imageIndex < fileInfo.images.length; imageIndex++) {\n if (!success) {\n break;\n }\n const image = fileInfo.images[imageIndex];\n if (config.loadSingleImage === undefined || config.loadSingleImage === imageIndex) {\n let mipCount = image.levels.length;\n if (config.loadMipmapLevels === false) {\n mipCount = 1;\n }\n for (let levelIndex = 0; levelIndex < mipCount; levelIndex++) {\n const levelInfo = image.levels[levelIndex];\n const pixels = TranscodeLevel(loadedFile, imageIndex, levelIndex, format, needsConversion);\n if (!pixels) {\n success = false;\n break;\n }\n levelInfo.transcodedPixels = pixels;\n buffers.push(levelInfo.transcodedPixels.buffer);\n }\n }\n }\n // Close file\n loadedFile.close();\n loadedFile.delete();\n if (needsConversion) {\n format = -1;\n }\n if (!success) {\n postMessage({ action: \"transcode\", success: success, id: event.data.id });\n }\n else {\n postMessage({ action: \"transcode\", success: success, id: event.data.id, fileInfo: fileInfo, format: format }, buffers);\n }\n }\n };\n /**\n * Detects the supported transcode format for the file\n * @param config transcode config\n * @param fileInfo info about the file\n * @returns the chosed format or null if none are supported\n */\n function GetSupportedTranscodeFormat(config, fileInfo) {\n let format = null;\n if (config.supportedCompressionFormats) {\n if (config.supportedCompressionFormats.astc) {\n format = _BASIS_FORMAT.cTFASTC_4x4;\n }\n else if (config.supportedCompressionFormats.bc7) {\n format = _BASIS_FORMAT.cTFBC7;\n }\n else if (config.supportedCompressionFormats.s3tc) {\n format = fileInfo.hasAlpha ? _BASIS_FORMAT.cTFBC3 : _BASIS_FORMAT.cTFBC1;\n }\n else if (config.supportedCompressionFormats.pvrtc) {\n format = fileInfo.hasAlpha ? _BASIS_FORMAT.cTFPVRTC1_4_RGBA : _BASIS_FORMAT.cTFPVRTC1_4_RGB;\n }\n else if (config.supportedCompressionFormats.etc2) {\n format = _BASIS_FORMAT.cTFETC2;\n }\n else if (config.supportedCompressionFormats.etc1) {\n format = _BASIS_FORMAT.cTFETC1;\n }\n else {\n format = _BASIS_FORMAT.cTFRGB565;\n }\n }\n return format;\n }\n /**\n * Retrieves information about the basis file eg. dimensions\n * @param basisFile the basis file to get the info from\n * @returns information about the basis file\n */\n function GetFileInfo(basisFile) {\n const hasAlpha = basisFile.getHasAlpha();\n const imageCount = basisFile.getNumImages();\n const images = [];\n for (let i = 0; i < imageCount; i++) {\n const imageInfo = {\n levels: [],\n };\n const levelCount = basisFile.getNumLevels(i);\n for (let level = 0; level < levelCount; level++) {\n const levelInfo = {\n width: basisFile.getImageWidth(i, level),\n height: basisFile.getImageHeight(i, level),\n };\n imageInfo.levels.push(levelInfo);\n }\n images.push(imageInfo);\n }\n const info = { hasAlpha, images };\n return info;\n }\n function TranscodeLevel(loadedFile, imageIndex, levelIndex, format, convertToRgb565) {\n const dstSize = loadedFile.getImageTranscodedSizeInBytes(imageIndex, levelIndex, format);\n let dst = new Uint8Array(dstSize);\n if (!loadedFile.transcodeImage(dst, imageIndex, levelIndex, format, 1, 0)) {\n return null;\n }\n // If no supported format is found, load as dxt and convert to rgb565\n if (convertToRgb565) {\n const alignedWidth = (loadedFile.getImageWidth(imageIndex, levelIndex) + 3) & ~3;\n const alignedHeight = (loadedFile.getImageHeight(imageIndex, levelIndex) + 3) & ~3;\n dst = ConvertDxtToRgb565(dst, 0, alignedWidth, alignedHeight);\n }\n return dst;\n }\n /**\n * From https://github.com/BinomialLLC/basis_universal/blob/master/webgl/texture/dxt-to-rgb565.js\n * An unoptimized version of dxtToRgb565. Also, the floating\n * point math used to compute the colors actually results in\n * slightly different colors compared to hardware DXT decoders.\n * @param src dxt src pixels\n * @param srcByteOffset offset for the start of src\n * @param width aligned width of the image\n * @param height aligned height of the image\n * @returns the converted pixels\n */\n function ConvertDxtToRgb565(src, srcByteOffset, width, height) {\n const c = new Uint16Array(4);\n const dst = new Uint16Array(width * height);\n const blockWidth = width / 4;\n const blockHeight = height / 4;\n for (let blockY = 0; blockY < blockHeight; blockY++) {\n for (let blockX = 0; blockX < blockWidth; blockX++) {\n const i = srcByteOffset + 8 * (blockY * blockWidth + blockX);\n c[0] = src[i] | (src[i + 1] << 8);\n c[1] = src[i + 2] | (src[i + 3] << 8);\n c[2] =\n ((2 * (c[0] & 0x1f) + 1 * (c[1] & 0x1f)) / 3) |\n (((2 * (c[0] & 0x7e0) + 1 * (c[1] & 0x7e0)) / 3) & 0x7e0) |\n (((2 * (c[0] & 0xf800) + 1 * (c[1] & 0xf800)) / 3) & 0xf800);\n c[3] =\n ((2 * (c[1] & 0x1f) + 1 * (c[0] & 0x1f)) / 3) |\n (((2 * (c[1] & 0x7e0) + 1 * (c[0] & 0x7e0)) / 3) & 0x7e0) |\n (((2 * (c[1] & 0xf800) + 1 * (c[0] & 0xf800)) / 3) & 0xf800);\n for (let row = 0; row < 4; row++) {\n const m = src[i + 4 + row];\n let dstI = (blockY * 4 + row) * width + blockX * 4;\n dst[dstI++] = c[m & 0x3];\n dst[dstI++] = c[(m >> 2) & 0x3];\n dst[dstI++] = c[(m >> 4) & 0x3];\n dst[dstI++] = c[(m >> 6) & 0x3];\n }\n }\n }\n return dst;\n }\n}\nObject.defineProperty(BasisTools, \"JSModuleURL\", {\n get: function () {\n return BasisToolsOptions.JSModuleURL;\n },\n set: function (value) {\n BasisToolsOptions.JSModuleURL = value;\n },\n});\nObject.defineProperty(BasisTools, \"WasmModuleURL\", {\n get: function () {\n return BasisToolsOptions.WasmModuleURL;\n },\n set: function (value) {\n BasisToolsOptions.WasmModuleURL = value;\n },\n});\n//# sourceMappingURL=basis.js.map","import { Engine } from \"../../../Engines/engine.js\";\nimport { LoadTextureFromTranscodeResult, TranscodeAsync } from \"../../../Misc/basis.js\";\nimport { Tools } from \"../../../Misc/tools.js\";\n/**\n * Loader for .basis file format\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class _BasisTextureLoader {\n constructor() {\n /**\n * Defines whether the loader supports cascade loading the different faces.\n */\n this.supportCascades = false;\n }\n /**\n * This returns if the loader support the current file information.\n * @param extension defines the file extension of the file being loaded\n * @returns true if the loader can load the specified file\n */\n canLoad(extension) {\n return extension.endsWith(\".basis\");\n }\n /**\n * Uploads the cube texture data to the WebGL texture. It has already been bound.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param createPolynomials will be true if polynomials have been requested\n * @param onLoad defines the callback to trigger once the texture is ready\n * @param onError defines the callback to trigger in case of error\n */\n loadCubeData(data, texture, createPolynomials, onLoad, onError) {\n if (Array.isArray(data)) {\n return;\n }\n const caps = texture.getEngine().getCaps();\n const transcodeConfig = {\n supportedCompressionFormats: {\n etc1: caps.etc1 ? true : false,\n s3tc: caps.s3tc ? true : false,\n pvrtc: caps.pvrtc ? true : false,\n etc2: caps.etc2 ? true : false,\n astc: caps.astc ? true : false,\n bc7: caps.bptc ? true : false,\n },\n };\n TranscodeAsync(data, transcodeConfig)\n .then((result) => {\n const hasMipmap = result.fileInfo.images[0].levels.length > 1 && texture.generateMipMaps;\n LoadTextureFromTranscodeResult(texture, result);\n texture.getEngine()._setCubeMapTextureParams(texture, hasMipmap);\n texture.isReady = true;\n texture.onLoadedObservable.notifyObservers(texture);\n texture.onLoadedObservable.clear();\n if (onLoad) {\n onLoad();\n }\n })\n .catch((err) => {\n const errorMessage = \"Failed to transcode Basis file, transcoding may not be supported on this device\";\n Tools.Warn(errorMessage);\n texture.isReady = true;\n if (onError) {\n onError(err);\n }\n });\n }\n /**\n * Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback.\n * @param data contains the texture data\n * @param texture defines the BabylonJS internal texture\n * @param callback defines the method to call once ready to upload\n */\n loadData(data, texture, callback) {\n const caps = texture.getEngine().getCaps();\n const transcodeConfig = {\n supportedCompressionFormats: {\n etc1: caps.etc1 ? true : false,\n s3tc: caps.s3tc ? true : false,\n pvrtc: caps.pvrtc ? true : false,\n etc2: caps.etc2 ? true : false,\n astc: caps.astc ? true : false,\n bc7: caps.bptc ? true : false,\n },\n };\n TranscodeAsync(data, transcodeConfig)\n .then((result) => {\n const rootImage = result.fileInfo.images[0].levels[0];\n const hasMipmap = result.fileInfo.images[0].levels.length > 1 && texture.generateMipMaps;\n callback(rootImage.width, rootImage.height, hasMipmap, result.format !== -1, () => {\n LoadTextureFromTranscodeResult(texture, result);\n });\n })\n .catch((err) => {\n Tools.Warn(\"Failed to transcode Basis file, transcoding may not be supported on this device\");\n Tools.Warn(`Failed to transcode Basis file: ${err}`);\n callback(0, 0, false, false, () => { }, true);\n });\n }\n}\n// Register the loader.\nEngine._TextureLoaders.push(new _BasisTextureLoader());\n//# sourceMappingURL=basisTextureLoader.js.map","export * from \"./ddsTextureLoader.js\";\nexport * from \"./envTextureLoader.js\";\nexport * from \"./ktxTextureLoader.js\";\nexport * from \"./tgaTextureLoader.js\";\nexport * from \"./hdrTextureLoader.js\";\nexport * from \"./basisTextureLoader.js\";\n//# sourceMappingURL=index.js.map","import { Texture } from \"../../Materials/Textures/texture.js\";\nimport { RenderTargetTexture } from \"../../Materials/Textures/renderTargetTexture.js\";\n\nimport \"../../Engines/Extensions/engine.multiRender.js\";\n/**\n * A multi render target, like a render target provides the ability to render to a texture.\n * Unlike the render target, it can render to several draw buffers in one draw.\n * This is specially interesting in deferred rendering or for any effects requiring more than\n * just one color from a single pass.\n */\nexport class MultiRenderTarget extends RenderTargetTexture {\n /**\n * Get if draw buffers are currently supported by the used hardware and browser.\n */\n get isSupported() {\n var _a, _b;\n return (_b = (_a = this._engine) === null || _a === void 0 ? void 0 : _a.getCaps().drawBuffersExtension) !== null && _b !== void 0 ? _b : false;\n }\n /**\n * Get the list of textures generated by the multi render target.\n */\n get textures() {\n return this._textures;\n }\n /**\n * Gets the number of textures in this MRT. This number can be different from `_textures.length` in case a depth texture is generated.\n */\n get count() {\n return this._count;\n }\n /**\n * Get the depth texture generated by the multi render target if options.generateDepthTexture has been set\n */\n get depthTexture() {\n return this._textures[this._textures.length - 1];\n }\n /**\n * Set the wrapping mode on U of all the textures we are rendering to.\n * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)\n */\n set wrapU(wrap) {\n if (this._textures) {\n for (let i = 0; i < this._textures.length; i++) {\n this._textures[i].wrapU = wrap;\n }\n }\n }\n /**\n * Set the wrapping mode on V of all the textures we are rendering to.\n * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)\n */\n set wrapV(wrap) {\n if (this._textures) {\n for (let i = 0; i < this._textures.length; i++) {\n this._textures[i].wrapV = wrap;\n }\n }\n }\n /**\n * Instantiate a new multi render target texture.\n * A multi render target, like a render target provides the ability to render to a texture.\n * Unlike the render target, it can render to several draw buffers in one draw.\n * This is specially interesting in deferred rendering or for any effects requiring more than\n * just one color from a single pass.\n * @param name Define the name of the texture\n * @param size Define the size of the buffers to render to\n * @param count Define the number of target we are rendering into\n * @param scene Define the scene the texture belongs to\n * @param options Define the options used to create the multi render target\n * @param textureNames Define the names to set to the textures (if count > 0 - optional)\n */\n constructor(name, size, count, scene, options, textureNames) {\n const generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;\n const generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;\n const depthTextureFormat = options && options.depthTextureFormat ? options.depthTextureFormat : 15;\n const doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;\n const drawOnlyOnFirstAttachmentByDefault = options && options.drawOnlyOnFirstAttachmentByDefault ? options.drawOnlyOnFirstAttachmentByDefault : false;\n super(name, size, scene, generateMipMaps, doNotChangeAspectRatio, undefined, undefined, undefined, undefined, undefined, undefined, undefined, true);\n if (!this.isSupported) {\n this.dispose();\n return;\n }\n this._textureNames = textureNames;\n const types = [];\n const samplingModes = [];\n const useSRGBBuffers = [];\n const formats = [];\n const targetTypes = [];\n const faceIndex = [];\n const layerIndex = [];\n const layerCounts = [];\n this._initTypes(count, types, samplingModes, useSRGBBuffers, formats, targetTypes, faceIndex, layerIndex, layerCounts, options);\n const generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;\n const generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;\n this._multiRenderTargetOptions = {\n samplingModes: samplingModes,\n generateMipMaps: generateMipMaps,\n generateDepthBuffer: generateDepthBuffer,\n generateStencilBuffer: generateStencilBuffer,\n generateDepthTexture: generateDepthTexture,\n depthTextureFormat: depthTextureFormat,\n types: types,\n textureCount: count,\n useSRGBBuffers: useSRGBBuffers,\n formats: formats,\n targetTypes: targetTypes,\n faceIndex: faceIndex,\n layerIndex: layerIndex,\n layerCounts: layerCounts,\n };\n this._count = count;\n this._drawOnlyOnFirstAttachmentByDefault = drawOnlyOnFirstAttachmentByDefault;\n if (count > 0) {\n this._createInternalTextures();\n this._createTextures(textureNames);\n }\n }\n _initTypes(count, types, samplingModes, useSRGBBuffers, formats, targets, faceIndex, layerIndex, layerCounts, options) {\n for (let i = 0; i < count; i++) {\n if (options && options.types && options.types[i] !== undefined) {\n types.push(options.types[i]);\n }\n else {\n types.push(options && options.defaultType ? options.defaultType : 0);\n }\n if (options && options.samplingModes && options.samplingModes[i] !== undefined) {\n samplingModes.push(options.samplingModes[i]);\n }\n else {\n samplingModes.push(Texture.BILINEAR_SAMPLINGMODE);\n }\n if (options && options.useSRGBBuffers && options.useSRGBBuffers[i] !== undefined) {\n useSRGBBuffers.push(options.useSRGBBuffers[i]);\n }\n else {\n useSRGBBuffers.push(false);\n }\n if (options && options.formats && options.formats[i] !== undefined) {\n formats.push(options.formats[i]);\n }\n else {\n formats.push(5);\n }\n if (options && options.targetTypes && options.targetTypes[i] !== undefined) {\n targets.push(options.targetTypes[i]);\n }\n else {\n targets.push(3553);\n }\n if (options && options.faceIndex && options.faceIndex[i] !== undefined) {\n faceIndex.push(options.faceIndex[i]);\n }\n else {\n faceIndex.push(0);\n }\n if (options && options.layerIndex && options.layerIndex[i] !== undefined) {\n layerIndex.push(options.layerIndex[i]);\n }\n else {\n layerIndex.push(0);\n }\n if (options && options.layerCounts && options.layerCounts[i] !== undefined) {\n layerCounts.push(options.layerCounts[i]);\n }\n else {\n layerCounts.push(1);\n }\n }\n }\n _createInternaTextureIndexMapping() {\n const mapMainInternalTexture2Index = {};\n const mapInternalTexture2MainIndex = [];\n if (!this._renderTarget) {\n return mapInternalTexture2MainIndex;\n }\n const internalTextures = this._renderTarget.textures;\n for (let i = 0; i < internalTextures.length; i++) {\n const texture = internalTextures[i];\n if (!texture) {\n continue;\n }\n const mainIndex = mapMainInternalTexture2Index[texture.uniqueId];\n if (mainIndex !== undefined) {\n mapInternalTexture2MainIndex[i] = mainIndex;\n }\n else {\n mapMainInternalTexture2Index[texture.uniqueId] = i;\n }\n }\n return mapInternalTexture2MainIndex;\n }\n /**\n * @internal\n */\n _rebuild(forceFullRebuild = false, textureNames) {\n if (this._count < 1) {\n return;\n }\n const mapInternalTexture2MainIndex = this._createInternaTextureIndexMapping();\n this.releaseInternalTextures();\n this._createInternalTextures();\n if (forceFullRebuild) {\n this._releaseTextures();\n this._createTextures(textureNames);\n }\n const internalTextures = this._renderTarget.textures;\n for (let i = 0; i < internalTextures.length; i++) {\n const texture = this._textures[i];\n if (mapInternalTexture2MainIndex[i] !== undefined) {\n this._renderTarget.setTexture(internalTextures[mapInternalTexture2MainIndex[i]], i);\n }\n texture._texture = internalTextures[i];\n if (texture._texture) {\n texture._noMipmap = !texture._texture.useMipMaps;\n texture._useSRGBBuffer = texture._texture._useSRGBBuffer;\n }\n }\n if (this.samples !== 1) {\n this._renderTarget.setSamples(this.samples, !this._drawOnlyOnFirstAttachmentByDefault, true);\n }\n }\n _createInternalTextures() {\n this._renderTarget = this._getEngine().createMultipleRenderTarget(this._size, this._multiRenderTargetOptions, !this._drawOnlyOnFirstAttachmentByDefault);\n this._texture = this._renderTarget.texture;\n }\n _releaseTextures() {\n if (this._textures) {\n for (let i = 0; i < this._textures.length; i++) {\n this._textures[i]._texture = null; // internal textures are released by a call to releaseInternalTextures()\n this._textures[i].dispose();\n }\n }\n }\n _createTextures(textureNames) {\n const internalTextures = this._renderTarget.textures;\n this._textures = [];\n for (let i = 0; i < internalTextures.length; i++) {\n const texture = new Texture(null, this.getScene());\n if (textureNames === null || textureNames === void 0 ? void 0 : textureNames[i]) {\n texture.name = textureNames[i];\n }\n texture._texture = internalTextures[i];\n if (texture._texture) {\n texture._noMipmap = !texture._texture.useMipMaps;\n texture._useSRGBBuffer = texture._texture._useSRGBBuffer;\n }\n this._textures.push(texture);\n }\n }\n /**\n * Replaces an internal texture within the MRT. Useful to share textures between MultiRenderTarget.\n * @param texture The new texture to set in the MRT\n * @param index The index of the texture to replace\n * @param disposePrevious Set to true if the previous internal texture should be disposed\n */\n setInternalTexture(texture, index, disposePrevious = true) {\n var _a, _b;\n if (!this.renderTarget) {\n return;\n }\n if (index === 0) {\n this._texture = texture;\n }\n this.renderTarget.setTexture(texture, index, disposePrevious);\n if (!this.textures[index]) {\n this.textures[index] = new Texture(null, this.getScene());\n this.textures[index].name = (_b = (_a = this._textureNames) === null || _a === void 0 ? void 0 : _a[index]) !== null && _b !== void 0 ? _b : this.textures[index].name;\n }\n this.textures[index]._texture = texture;\n this.textures[index]._noMipmap = !texture.useMipMaps;\n this.textures[index]._useSRGBBuffer = texture._useSRGBBuffer;\n this._count = this.renderTarget.textures ? this.renderTarget.textures.length : 0;\n if (this._multiRenderTargetOptions.types) {\n this._multiRenderTargetOptions.types[index] = texture.type;\n }\n if (this._multiRenderTargetOptions.samplingModes) {\n this._multiRenderTargetOptions.samplingModes[index] = texture.samplingMode;\n }\n if (this._multiRenderTargetOptions.useSRGBBuffers) {\n this._multiRenderTargetOptions.useSRGBBuffers[index] = texture._useSRGBBuffer;\n }\n if (this._multiRenderTargetOptions.targetTypes && this._multiRenderTargetOptions.targetTypes[index] !== -1) {\n let target = 0;\n if (texture.is2DArray) {\n target = 35866;\n }\n else if (texture.isCube) {\n target = 34067;\n } /*else if (texture.isCubeArray) {\n target = 3735928559;\n }*/\n else if (texture.is3D) {\n target = 32879;\n }\n else {\n target = 3553;\n }\n this._multiRenderTargetOptions.targetTypes[index] = target;\n }\n }\n /**\n * Changes an attached texture's face index or layer.\n * @param index The index of the texture to modify the attachment of\n * @param layerIndex The layer index of the texture to be attached to the framebuffer\n * @param faceIndex The face index of the texture to be attached to the framebuffer\n */\n setLayerAndFaceIndex(index, layerIndex = -1, faceIndex = -1) {\n if (!this.textures[index] || !this.renderTarget) {\n return;\n }\n if (this._multiRenderTargetOptions.layerIndex) {\n this._multiRenderTargetOptions.layerIndex[index] = layerIndex;\n }\n if (this._multiRenderTargetOptions.faceIndex) {\n this._multiRenderTargetOptions.faceIndex[index] = faceIndex;\n }\n this.renderTarget.setLayerAndFaceIndex(index, layerIndex, faceIndex);\n }\n /**\n * Changes every attached texture's face index or layer.\n * @param layerIndices The layer indices of the texture to be attached to the framebuffer\n * @param faceIndices The face indices of the texture to be attached to the framebuffer\n */\n setLayerAndFaceIndices(layerIndices, faceIndices) {\n if (!this.renderTarget) {\n return;\n }\n this._multiRenderTargetOptions.layerIndex = layerIndices;\n this._multiRenderTargetOptions.faceIndex = faceIndices;\n this.renderTarget.setLayerAndFaceIndices(layerIndices, faceIndices);\n }\n /**\n * Define the number of samples used if MSAA is enabled.\n */\n get samples() {\n return this._samples;\n }\n set samples(value) {\n if (this._renderTarget) {\n this._samples = this._renderTarget.setSamples(value);\n }\n else {\n // In case samples are set with 0 textures created, we must save the desired samples value\n this._samples = value;\n }\n }\n /**\n * Resize all the textures in the multi render target.\n * Be careful as it will recreate all the data in the new texture.\n * @param size Define the new size\n */\n resize(size) {\n this._processSizeParameter(size, false);\n this._rebuild(undefined, this._textureNames);\n }\n /**\n * Changes the number of render targets in this MRT\n * Be careful as it will recreate all the data in the new texture.\n * @param count new texture count\n * @param options Specifies texture types and sampling modes for new textures\n * @param textureNames Specifies the names of the textures (optional)\n */\n updateCount(count, options, textureNames) {\n this._multiRenderTargetOptions.textureCount = count;\n this._count = count;\n const types = [];\n const samplingModes = [];\n const useSRGBBuffers = [];\n const formats = [];\n const targetTypes = [];\n const faceIndex = [];\n const layerIndex = [];\n const layerCounts = [];\n this._textureNames = textureNames;\n this._initTypes(count, types, samplingModes, useSRGBBuffers, formats, targetTypes, faceIndex, layerIndex, layerCounts, options);\n this._multiRenderTargetOptions.types = types;\n this._multiRenderTargetOptions.samplingModes = samplingModes;\n this._multiRenderTargetOptions.useSRGBBuffers = useSRGBBuffers;\n this._multiRenderTargetOptions.formats = formats;\n this._multiRenderTargetOptions.targetTypes = targetTypes;\n this._multiRenderTargetOptions.faceIndex = faceIndex;\n this._multiRenderTargetOptions.layerIndex = layerIndex;\n this._multiRenderTargetOptions.layerCounts = layerCounts;\n this._rebuild(true, textureNames);\n }\n _unbindFrameBuffer(engine, faceIndex) {\n if (this._renderTarget) {\n engine.unBindMultiColorAttachmentFramebuffer(this._renderTarget, this.isCube, () => {\n this.onAfterRenderObservable.notifyObservers(faceIndex);\n });\n }\n }\n /**\n * Dispose the render targets and their associated resources\n * @param doNotDisposeInternalTextures\n */\n dispose(doNotDisposeInternalTextures = false) {\n this._releaseTextures();\n if (!doNotDisposeInternalTextures) {\n this.releaseInternalTextures();\n }\n else {\n // Prevent internal texture dispose in super.dispose\n this._texture = null;\n }\n super.dispose();\n }\n /**\n * Release all the underlying texture used as draw buffers.\n */\n releaseInternalTextures() {\n var _a, _b;\n const internalTextures = (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.textures;\n if (!internalTextures) {\n return;\n }\n for (let i = internalTextures.length - 1; i >= 0; i--) {\n this._textures[i]._texture = null;\n }\n (_b = this._renderTarget) === null || _b === void 0 ? void 0 : _b.dispose();\n this._renderTarget = null;\n }\n}\n//# sourceMappingURL=multiRenderTarget.js.map","/**\n * This is a support class for frame Data on texture packer sets.\n */\nexport class TexturePackerFrame {\n /**\n * Initializes a texture package frame.\n * @param id The numerical frame identifier\n * @param scale Scalar Vector2 for UV frame\n * @param offset Vector2 for the frame position in UV units.\n * @returns TexturePackerFrame\n */\n constructor(id, scale, offset) {\n this.id = id;\n this.scale = scale;\n this.offset = offset;\n }\n}\n//# sourceMappingURL=frame.js.map","import { Engine } from \"../../../Engines/engine.js\";\nimport { VertexBuffer } from \"../../../Buffers/buffer.js\";\nimport { Texture } from \"../texture.js\";\nimport { DynamicTexture } from \"../dynamicTexture.js\";\nimport { Vector2 } from \"../../../Maths/math.vector.js\";\nimport { Color3, Color4 } from \"../../../Maths/math.color.js\";\nimport { TexturePackerFrame } from \"./frame.js\";\nimport { Logger } from \"../../../Misc/logger.js\";\nimport { Tools } from \"../../../Misc/tools.js\";\n/**\n * This is a support class that generates a series of packed texture sets.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction\n */\nexport class TexturePacker {\n /**\n * Initializes a texture package series from an array of meshes or a single mesh.\n * @param name The name of the package\n * @param meshes The target meshes to compose the package from\n * @param options The arguments that texture packer should follow while building.\n * @param scene The scene which the textures are scoped to.\n * @returns TexturePacker\n */\n constructor(name, meshes, options, scene) {\n var _b, _c, _d, _e, _g, _h, _j, _k, _l, _m, _o, _p, _q;\n this.name = name;\n this.meshes = meshes;\n this.scene = scene;\n /**\n * Run through the options and set what ever defaults are needed that where not declared.\n */\n this.options = options;\n this.options.map = (_b = this.options.map) !== null && _b !== void 0 ? _b : [\n \"ambientTexture\",\n \"bumpTexture\",\n \"diffuseTexture\",\n \"emissiveTexture\",\n \"lightmapTexture\",\n \"opacityTexture\",\n \"reflectionTexture\",\n \"refractionTexture\",\n \"specularTexture\",\n ];\n this.options.uvsIn = (_c = this.options.uvsIn) !== null && _c !== void 0 ? _c : VertexBuffer.UVKind;\n this.options.uvsOut = (_d = this.options.uvsOut) !== null && _d !== void 0 ? _d : VertexBuffer.UVKind;\n this.options.layout = (_e = this.options.layout) !== null && _e !== void 0 ? _e : TexturePacker.LAYOUT_STRIP;\n if (this.options.layout === TexturePacker.LAYOUT_COLNUM) {\n this.options.colnum = (_g = this.options.colnum) !== null && _g !== void 0 ? _g : 8;\n }\n this.options.updateInputMeshes = (_h = this.options.updateInputMeshes) !== null && _h !== void 0 ? _h : true;\n this.options.disposeSources = (_j = this.options.disposeSources) !== null && _j !== void 0 ? _j : true;\n this._expecting = 0;\n this.options.fillBlanks = (_k = this.options.fillBlanks) !== null && _k !== void 0 ? _k : true;\n if (this.options.fillBlanks === true) {\n this.options.customFillColor = (_l = this.options.customFillColor) !== null && _l !== void 0 ? _l : \"black\";\n }\n this.options.frameSize = (_m = this.options.frameSize) !== null && _m !== void 0 ? _m : 256;\n this.options.paddingRatio = (_o = this.options.paddingRatio) !== null && _o !== void 0 ? _o : 0.0115;\n this._paddingValue = Math.ceil(this.options.frameSize * this.options.paddingRatio);\n //Make it an even padding Number.\n if (this._paddingValue % 2 !== 0) {\n this._paddingValue++;\n }\n this.options.paddingMode = (_p = this.options.paddingMode) !== null && _p !== void 0 ? _p : TexturePacker.SUBUV_WRAP;\n if (this.options.paddingMode === TexturePacker.SUBUV_COLOR) {\n this.options.paddingColor = (_q = this.options.paddingColor) !== null && _q !== void 0 ? _q : new Color4(0, 0, 0, 1.0);\n }\n this.sets = {};\n this.frames = [];\n return this;\n }\n /**\n * Starts the package process\n * @param resolve The promises resolution function\n * @returns TexturePacker\n */\n _createFrames(resolve) {\n const dtSize = this._calculateSize();\n const dtUnits = new Vector2(1, 1).divide(dtSize);\n let doneCount = 0;\n const expecting = this._expecting;\n const meshLength = this.meshes.length;\n const sKeys = Object.keys(this.sets);\n for (let i = 0; i < sKeys.length; i++) {\n const setName = sKeys[i];\n const dt = new DynamicTexture(this.name + \".TexturePack.\" + setName + \"Set\", { width: dtSize.x, height: dtSize.y }, this.scene, true, //Generate Mips\n Texture.TRILINEAR_SAMPLINGMODE, Engine.TEXTUREFORMAT_RGBA);\n const dtx = dt.getContext();\n dtx.fillStyle = \"rgba(0,0,0,0)\";\n dtx.fillRect(0, 0, dtSize.x, dtSize.y);\n dt.update(false);\n this.sets[setName] = dt;\n }\n const baseSize = this.options.frameSize || 256;\n const padding = this._paddingValue;\n const tcs = baseSize + 2 * padding;\n const done = () => {\n this._calculateMeshUVFrames(baseSize, padding, dtSize, dtUnits, this.options.updateInputMeshes || false);\n };\n //Update the Textures\n for (let i = 0; i < meshLength; i++) {\n const m = this.meshes[i];\n const mat = m.material;\n //Check if the material has the texture\n //Create a temporary canvas the same size as 1 frame\n //Then apply the texture to the center and the 8 offsets\n //Copy the Context and place in the correct frame on the DT\n for (let j = 0; j < sKeys.length; j++) {\n const tempTexture = new DynamicTexture(\"temp\", tcs, this.scene, true);\n const tcx = tempTexture.getContext();\n const offset = this._getFrameOffset(i);\n const updateDt = () => {\n doneCount++;\n tempTexture.update(false);\n const iDat = tcx.getImageData(0, 0, tcs, tcs);\n //Update Set\n const dt = this.sets[setName];\n const dtx = dt.getContext();\n dtx.putImageData(iDat, dtSize.x * offset.x, dtSize.y * offset.y);\n tempTexture.dispose();\n dt.update(false);\n if (doneCount == expecting) {\n done();\n resolve();\n return;\n }\n };\n const setName = sKeys[j] || \"_blank\";\n if (!mat || mat[setName] === null) {\n tcx.fillStyle = \"rgba(0,0,0,0)\";\n if (this.options.fillBlanks) {\n tcx.fillStyle = this.options.customFillColor;\n }\n tcx.fillRect(0, 0, tcs, tcs);\n updateDt();\n }\n else {\n const setTexture = mat[setName];\n const img = new Image();\n if (setTexture instanceof DynamicTexture) {\n img.src = setTexture.getContext().canvas.toDataURL(\"image/png\");\n }\n else {\n img.src = setTexture.url;\n }\n Tools.SetCorsBehavior(img.src, img);\n img.onload = () => {\n tcx.fillStyle = \"rgba(0,0,0,0)\";\n tcx.fillRect(0, 0, tcs, tcs);\n tempTexture.update(false);\n tcx.setTransform(1, 0, 0, -1, 0, 0);\n const cellOffsets = [0, 0, 1, 0, 1, 1, 0, 1, -1, 1, -1, 0, -1 - 1, 0, -1, 1, -1];\n switch (this.options.paddingMode) {\n //Wrap Mode\n case 0:\n for (let i = 0; i < 9; i++) {\n tcx.drawImage(img, 0, 0, img.width, img.height, padding + baseSize * cellOffsets[i], padding + baseSize * cellOffsets[i + 1] - tcs, baseSize, baseSize);\n }\n break;\n //Extend Mode\n case 1:\n for (let i = 0; i < padding; i++) {\n tcx.drawImage(img, 0, 0, img.width, img.height, i + baseSize * cellOffsets[0], padding - tcs, baseSize, baseSize);\n tcx.drawImage(img, 0, 0, img.width, img.height, padding * 2 - i, padding - tcs, baseSize, baseSize);\n tcx.drawImage(img, 0, 0, img.width, img.height, padding, i - tcs, baseSize, baseSize);\n tcx.drawImage(img, 0, 0, img.width, img.height, padding, padding * 2 - i - tcs, baseSize, baseSize);\n }\n tcx.drawImage(img, 0, 0, img.width, img.height, padding + baseSize * cellOffsets[0], padding + baseSize * cellOffsets[1] - tcs, baseSize, baseSize);\n break;\n //Color Mode\n case 2:\n tcx.fillStyle = (this.options.paddingColor || Color3.Black()).toHexString();\n tcx.fillRect(0, 0, tcs, -tcs);\n tcx.clearRect(padding, padding, baseSize, baseSize);\n tcx.drawImage(img, 0, 0, img.width, img.height, padding + baseSize * cellOffsets[0], padding + baseSize * cellOffsets[1] - tcs, baseSize, baseSize);\n break;\n }\n tcx.setTransform(1, 0, 0, 1, 0, 0);\n updateDt();\n };\n }\n }\n }\n }\n /**\n * Calculates the Size of the Channel Sets\n * @returns Vector2\n */\n _calculateSize() {\n const meshLength = this.meshes.length || 0;\n const baseSize = this.options.frameSize || 0;\n const padding = this._paddingValue || 0;\n switch (this.options.layout) {\n case 0: {\n //STRIP_LAYOUT\n return new Vector2(baseSize * meshLength + 2 * padding * meshLength, baseSize + 2 * padding);\n }\n case 1: {\n //POWER2\n const sqrtCount = Math.max(2, Math.ceil(Math.sqrt(meshLength)));\n const size = baseSize * sqrtCount + 2 * padding * sqrtCount;\n return new Vector2(size, size);\n }\n case 2: {\n //COLNUM\n const cols = this.options.colnum || 1;\n const rowCnt = Math.max(1, Math.ceil(meshLength / cols));\n return new Vector2(baseSize * cols + 2 * padding * cols, baseSize * rowCnt + 2 * padding * rowCnt);\n }\n }\n return Vector2.Zero();\n }\n /**\n * Calculates the UV data for the frames.\n * @param baseSize the base frameSize\n * @param padding the base frame padding\n * @param dtSize size of the Dynamic Texture for that channel\n * @param dtUnits is 1/dtSize\n * @param update flag to update the input meshes\n */\n _calculateMeshUVFrames(baseSize, padding, dtSize, dtUnits, update) {\n const meshLength = this.meshes.length;\n for (let i = 0; i < meshLength; i++) {\n const m = this.meshes[i];\n const scale = new Vector2(baseSize / dtSize.x, baseSize / dtSize.y);\n const pOffset = dtUnits.clone().scale(padding);\n const frameOffset = this._getFrameOffset(i);\n const offset = frameOffset.add(pOffset);\n const frame = new TexturePackerFrame(i, scale, offset);\n this.frames.push(frame);\n //Update Output UVs\n if (update) {\n this._updateMeshUV(m, i);\n this._updateTextureReferences(m);\n }\n }\n }\n /**\n * Calculates the frames Offset.\n * @param index of the frame\n * @returns Vector2\n */\n _getFrameOffset(index) {\n const meshLength = this.meshes.length;\n let uvStep, yStep, xStep;\n switch (this.options.layout) {\n case 0: {\n //STRIP_LAYOUT\n uvStep = 1 / meshLength;\n return new Vector2(index * uvStep, 0);\n }\n case 1: {\n //POWER2\n const sqrtCount = Math.max(2, Math.ceil(Math.sqrt(meshLength)));\n yStep = Math.floor(index / sqrtCount);\n xStep = index - yStep * sqrtCount;\n uvStep = 1 / sqrtCount;\n return new Vector2(xStep * uvStep, yStep * uvStep);\n }\n case 2: {\n //COLNUM\n const cols = this.options.colnum || 1;\n const rowCnt = Math.max(1, Math.ceil(meshLength / cols));\n xStep = Math.floor(index / rowCnt);\n yStep = index - xStep * rowCnt;\n uvStep = new Vector2(1 / cols, 1 / rowCnt);\n return new Vector2(xStep * uvStep.x, yStep * uvStep.y);\n }\n }\n return Vector2.Zero();\n }\n /**\n * Updates a Mesh to the frame data\n * @param mesh that is the target\n * @param frameID or the frame index\n */\n _updateMeshUV(mesh, frameID) {\n const frame = this.frames[frameID];\n const uvIn = mesh.getVerticesData(this.options.uvsIn || VertexBuffer.UVKind);\n const uvOut = [];\n let toCount = 0;\n if (uvIn.length) {\n toCount = uvIn.length || 0;\n }\n for (let i = 0; i < toCount; i += 2) {\n uvOut.push(uvIn[i] * frame.scale.x + frame.offset.x, uvIn[i + 1] * frame.scale.y + frame.offset.y);\n }\n mesh.setVerticesData(this.options.uvsOut || VertexBuffer.UVKind, uvOut);\n }\n /**\n * Updates a Meshes materials to use the texture packer channels\n * @param m is the mesh to target\n * @param force all channels on the packer to be set.\n */\n _updateTextureReferences(m, force = false) {\n const mat = m.material;\n const sKeys = Object.keys(this.sets);\n const _dispose = (_t) => {\n if (_t.dispose) {\n _t.dispose();\n }\n };\n for (let i = 0; i < sKeys.length; i++) {\n const setName = sKeys[i];\n if (!force) {\n if (!mat) {\n return;\n }\n if (mat[setName] !== null) {\n _dispose(mat[setName]);\n mat[setName] = this.sets[setName];\n }\n }\n else {\n if (mat[setName] !== null) {\n _dispose(mat[setName]);\n }\n mat[setName] = this.sets[setName];\n }\n }\n }\n /**\n * Public method to set a Mesh to a frame\n * @param m that is the target\n * @param frameID or the frame index\n * @param updateMaterial trigger for if the Meshes attached Material be updated?\n */\n setMeshToFrame(m, frameID, updateMaterial = false) {\n this._updateMeshUV(m, frameID);\n if (updateMaterial) {\n this._updateTextureReferences(m, true);\n }\n }\n /**\n * Starts the async promise to compile the texture packer.\n * @returns Promise\n */\n processAsync() {\n return new Promise((resolve, reject) => {\n try {\n if (this.meshes.length === 0) {\n //Must be a JSON load!\n resolve();\n return;\n }\n let done = 0;\n const doneCheck = (mat) => {\n done++;\n //Check Status of all Textures on all meshes, till they are ready.\n if (this.options.map) {\n for (let j = 0; j < this.options.map.length; j++) {\n const index = this.options.map[j];\n const t = mat[index];\n if (t !== null) {\n if (!this.sets[this.options.map[j]]) {\n this.sets[this.options.map[j]] = true;\n }\n this._expecting++;\n }\n }\n if (done === this.meshes.length) {\n this._createFrames(resolve);\n }\n }\n };\n for (let i = 0; i < this.meshes.length; i++) {\n const mesh = this.meshes[i];\n const material = mesh.material;\n if (!material) {\n done++;\n if (done === this.meshes.length) {\n return this._createFrames(resolve);\n }\n continue;\n }\n material.forceCompilationAsync(mesh).then(() => {\n doneCheck(material);\n });\n }\n }\n catch (e) {\n return reject(e);\n }\n });\n }\n /**\n * Disposes all textures associated with this packer\n */\n dispose() {\n const sKeys = Object.keys(this.sets);\n for (let i = 0; i < sKeys.length; i++) {\n const channel = sKeys[i];\n this.sets[channel].dispose();\n }\n }\n /**\n * Starts the download process for all the channels converting them to base64 data and embedding it all in a JSON file.\n * @param imageType is the image type to use.\n * @param quality of the image if downloading as jpeg, Ranges from >0 to 1.\n */\n download(imageType = \"png\", quality = 1) {\n setTimeout(() => {\n const pack = {\n name: this.name,\n sets: {},\n options: {},\n frames: [],\n };\n const sKeys = Object.keys(this.sets);\n const oKeys = Object.keys(this.options);\n try {\n for (let i = 0; i < sKeys.length; i++) {\n const channel = sKeys[i];\n const dt = this.sets[channel];\n pack.sets[channel] = dt.getContext().canvas.toDataURL(\"image/\" + imageType, quality);\n }\n for (let i = 0; i < oKeys.length; i++) {\n const opt = oKeys[i];\n pack.options[opt] = this.options[opt];\n }\n for (let i = 0; i < this.frames.length; i++) {\n const _f = this.frames[i];\n pack.frames.push(_f.scale.x, _f.scale.y, _f.offset.x, _f.offset.y);\n }\n }\n catch (err) {\n Logger.Warn(\"Unable to download: \" + err);\n return;\n }\n const data = \"data:text/json;charset=utf-8,\" + encodeURIComponent(JSON.stringify(pack, null, 4));\n const _a = document.createElement(\"a\");\n _a.setAttribute(\"href\", data);\n _a.setAttribute(\"download\", this.name + \"_texurePackage.json\");\n document.body.appendChild(_a);\n _a.click();\n _a.remove();\n }, 0);\n }\n /**\n * Public method to load a texturePacker JSON file.\n * @param data of the JSON file in string format.\n */\n updateFromJSON(data) {\n try {\n const parsedData = JSON.parse(data);\n this.name = parsedData.name;\n const _options = Object.keys(parsedData.options);\n for (let i = 0; i < _options.length; i++) {\n this.options[_options[i]] = parsedData.options[_options[i]];\n }\n for (let i = 0; i < parsedData.frames.length; i += 4) {\n const frame = new TexturePackerFrame(i / 4, new Vector2(parsedData.frames[i], parsedData.frames[i + 1]), new Vector2(parsedData.frames[i + 2], parsedData.frames[i + 3]));\n this.frames.push(frame);\n }\n const channels = Object.keys(parsedData.sets);\n for (let i = 0; i < channels.length; i++) {\n const _t = new Texture(parsedData.sets[channels[i]], this.scene, false, false);\n this.sets[channels[i]] = _t;\n }\n }\n catch (err) {\n Logger.Warn(\"Unable to update from JSON: \" + err);\n }\n }\n}\n/** Packer Layout Constant 0 */\nTexturePacker.LAYOUT_STRIP = 0;\n/** Packer Layout Constant 1 */\nTexturePacker.LAYOUT_POWER2 = 1;\n/** Packer Layout Constant 2 */\nTexturePacker.LAYOUT_COLNUM = 2;\n/** Packer Layout Constant 0 */\nTexturePacker.SUBUV_WRAP = 0;\n/** Packer Layout Constant 1 */\nTexturePacker.SUBUV_EXTEND = 1;\n/** Packer Layout Constant 2 */\nTexturePacker.SUBUV_COLOR = 2;\n//# sourceMappingURL=packer.js.map","export * from \"./packer.js\";\nexport * from \"./frame.js\";\n//# sourceMappingURL=index.js.map","import { Logger } from \"../../../Misc/logger.js\";\nimport { Vector3, Vector2 } from \"../../../Maths/math.vector.js\";\nimport { Color4, Color3 } from \"../../../Maths/math.color.js\";\nimport { Texture } from \"../../../Materials/Textures/texture.js\";\nimport { ProceduralTexture } from \"./proceduralTexture.js\";\nimport { WebRequest } from \"../../../Misc/webRequest.js\";\n/**\n * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.\n * Custom Procedural textures are the easiest way to create your own procedural in your application.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/proceduralTextures#creating-custom-procedural-textures\n */\nexport class CustomProceduralTexture extends ProceduralTexture {\n /**\n * Instantiates a new Custom Procedural Texture.\n * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.\n * Custom Procedural textures are the easiest way to create your own procedural in your application.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/proceduralTextures#creating-custom-procedural-textures\n * @param name Define the name of the texture\n * @param texturePath Define the folder path containing all the custom texture related files (config, shaders...)\n * @param size Define the size of the texture to create\n * @param scene Define the scene the texture belongs to\n * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture\n * @param generateMipMaps Define if the texture should creates mip maps or not\n * @param skipJson Define a boolena indicating that there is no json config file to load\n */\n constructor(name, texturePath, size, scene, fallbackTexture, generateMipMaps, skipJson) {\n super(name, size, null, scene, fallbackTexture, generateMipMaps);\n this._animate = true;\n this._time = 0;\n this._texturePath = texturePath;\n if (!skipJson) {\n //Try to load json\n this._loadJson(texturePath);\n }\n else {\n this.setFragment(this._texturePath);\n }\n this.refreshRate = 1;\n }\n _loadJson(jsonUrl) {\n const noConfigFile = () => {\n try {\n this.setFragment(this._texturePath);\n }\n catch (ex) {\n Logger.Log(\"No json or ShaderStore or DOM element found for CustomProceduralTexture\");\n }\n };\n const configFileUrl = jsonUrl + \"/config.json\";\n const xhr = new WebRequest();\n xhr.open(\"GET\", configFileUrl);\n xhr.addEventListener(\"load\", () => {\n if (xhr.status === 200 || (xhr.responseText && xhr.responseText.length > 0)) {\n try {\n this._config = JSON.parse(xhr.response);\n this.updateShaderUniforms();\n this.updateTextures();\n this.setFragment(this._texturePath + \"/custom\");\n this._animate = this._config.animate;\n this.refreshRate = this._config.refreshrate;\n }\n catch (ex) {\n noConfigFile();\n }\n }\n else {\n noConfigFile();\n }\n }, false);\n xhr.addEventListener(\"error\", () => {\n noConfigFile();\n }, false);\n try {\n xhr.send();\n }\n catch (ex) {\n Logger.Error(\"CustomProceduralTexture: Error on XHR send request.\");\n }\n }\n /**\n * Is the texture ready to be used ? (rendered at least once)\n * @returns true if ready, otherwise, false.\n */\n isReady() {\n if (!super.isReady()) {\n return false;\n }\n for (const name in this._textures) {\n const texture = this._textures[name];\n if (!texture.isReady()) {\n return false;\n }\n }\n return true;\n }\n /**\n * Render the texture to its associated render target.\n * @param useCameraPostProcess Define if camera post process should be applied to the texture\n */\n render(useCameraPostProcess) {\n const scene = this.getScene();\n if (this._animate && scene) {\n this._time += scene.getAnimationRatio() * 0.03;\n this.updateShaderUniforms();\n }\n super.render(useCameraPostProcess);\n }\n /**\n * Update the list of dependant textures samplers in the shader.\n */\n updateTextures() {\n for (let i = 0; i < this._config.sampler2Ds.length; i++) {\n this.setTexture(this._config.sampler2Ds[i].sample2Dname, new Texture(this._texturePath + \"/\" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));\n }\n }\n /**\n * Update the uniform values of the procedural texture in the shader.\n */\n updateShaderUniforms() {\n if (this._config) {\n for (let j = 0; j < this._config.uniforms.length; j++) {\n const uniform = this._config.uniforms[j];\n switch (uniform.type) {\n case \"float\":\n this.setFloat(uniform.name, uniform.value);\n break;\n case \"color3\":\n this.setColor3(uniform.name, new Color3(uniform.r, uniform.g, uniform.b));\n break;\n case \"color4\":\n this.setColor4(uniform.name, new Color4(uniform.r, uniform.g, uniform.b, uniform.a));\n break;\n case \"vector2\":\n this.setVector2(uniform.name, new Vector2(uniform.x, uniform.y));\n break;\n case \"vector3\":\n this.setVector3(uniform.name, new Vector3(uniform.x, uniform.y, uniform.z));\n break;\n }\n }\n }\n this.setFloat(\"time\", this._time);\n }\n /**\n * Define if the texture animates or not.\n */\n get animate() {\n return this._animate;\n }\n set animate(value) {\n this._animate = value;\n }\n}\n//# sourceMappingURL=customProceduralTexture.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"noisePixelShader\";\nconst shader = `uniform float brightness;\runiform float persistence;\runiform float timeScale;\rvarying vec2 vUV;\rvec2 hash22(vec2 p)\r{\rp=p*mat2(127.1,311.7,269.5,183.3);\rp=-1.0+2.0*fract(sin(p)*43758.5453123);\rreturn sin(p*6.283+timeScale);\r}\rfloat interpolationNoise(vec2 p)\r{\rvec2 pi=floor(p);\rvec2 pf=p-pi;\rvec2 w=pf*pf*(3.-2.*pf);\rfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\rfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\rfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\rfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\rfloat xm1=mix(f00,f10,w.x);\rfloat xm2=mix(f01,f11,w.x);\rfloat ym=mix(xm1,xm2,w.y); \rreturn ym;\r}\rfloat perlinNoise2D(float x,float y)\r{\rfloat sum=0.0;\rfloat frequency=0.0;\rfloat amplitude=0.0;\rfor(int i=0; i { });\n }\n /**\n * Clones the raw cube texture.\n * @returns a new cube texture\n */\n clone() {\n return SerializationHelper.Clone(() => {\n const scene = this.getScene();\n const internalTexture = this._texture;\n const texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);\n if (internalTexture.source === InternalTextureSource.CubeRawRGBD) {\n texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);\n }\n return texture;\n }, this);\n }\n}\n//# sourceMappingURL=rawCubeTexture.js.map","import { Texture } from \"./texture.js\";\n\nimport \"../../Engines/Extensions/engine.rawTexture.js\";\n/**\n * Class used to store 3D textures containing user data\n */\nexport class RawTexture3D extends Texture {\n /**\n * Create a new RawTexture3D\n * @param data defines the data of the texture\n * @param width defines the width of the texture\n * @param height defines the height of the texture\n * @param depth defines the depth of the texture\n * @param format defines the texture format to use\n * @param scene defines the hosting scene\n * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)\n * @param invertY defines if texture must be stored with Y axis inverted\n * @param samplingMode defines the sampling mode to use (Texture.TRILINEAR_SAMPLINGMODE by default)\n * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)\n */\n constructor(data, width, height, depth, \n /** Gets or sets the texture format to use */\n format, scene, generateMipMaps = true, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, textureType = 0) {\n super(null, scene, !generateMipMaps, invertY);\n this.format = format;\n this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, null, textureType);\n this.is3D = true;\n }\n /**\n * Update the texture with new data\n * @param data defines the data to store in the texture\n */\n update(data) {\n if (!this._texture) {\n return;\n }\n this._getEngine().updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, null, this._texture.type);\n }\n}\n//# sourceMappingURL=rawTexture3D.js.map","import { Plane } from \"../../Maths/math.plane.js\";\nimport { RenderTargetTexture } from \"../../Materials/Textures/renderTargetTexture.js\";\n/**\n * Creates a refraction texture used by refraction channel of the standard material.\n * It is like a mirror but to see through a material.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#refractiontexture\n */\nexport class RefractionTexture extends RenderTargetTexture {\n /**\n * Creates a refraction texture used by refraction channel of the standard material.\n * It is like a mirror but to see through a material.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#refraction\n * @param name Define the texture name\n * @param size Define the size of the underlying texture\n * @param scene Define the scene the refraction belongs to\n * @param generateMipMaps Define if we need to generate mips level for the refraction\n */\n constructor(name, size, scene, generateMipMaps) {\n super(name, size, scene, generateMipMaps, true);\n /**\n * Define the reflection plane we want to use. The refractionPlane is usually set to the constructed refractor.\n * It is possible to directly set the refractionPlane by directly using a Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the refractionPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the refractor as stated in the doc.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/reflectionTexture#refraction\n */\n this.refractionPlane = new Plane(0, 1, 0, 1);\n /**\n * Define how deep under the surface we should see.\n */\n this.depth = 2.0;\n this.onBeforeRenderObservable.add(() => {\n this.getScene().clipPlane = this.refractionPlane;\n });\n this.onAfterRenderObservable.add(() => {\n this.getScene().clipPlane = null;\n });\n }\n /**\n * Clone the refraction texture.\n * @returns the cloned texture\n */\n clone() {\n const scene = this.getScene();\n if (!scene) {\n return this;\n }\n const textureSize = this.getSize();\n const newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);\n // Base texture\n newTexture.hasAlpha = this.hasAlpha;\n newTexture.level = this.level;\n // Refraction Texture\n newTexture.refractionPlane = this.refractionPlane.clone();\n if (this.renderList) {\n newTexture.renderList = this.renderList.slice(0);\n }\n newTexture.depth = this.depth;\n return newTexture;\n }\n /**\n * Serialize the texture to a JSON representation you could use in Parse later on\n * @returns the serialized JSON representation\n */\n serialize() {\n if (!this.name) {\n return null;\n }\n const serializationObject = super.serialize();\n serializationObject.mirrorPlane = this.refractionPlane.asArray();\n serializationObject.depth = this.depth;\n return serializationObject;\n }\n}\n//# sourceMappingURL=refractionTexture.js.map","import { ThinTexture } from \"./thinTexture.js\";\n/**\n * This is a tiny helper class to wrap a RenderTargetWrapper in a texture\n * usable as the input of an effect.\n */\nexport class ThinRenderTargetTexture extends ThinTexture {\n /**\n * Gets the render target wrapper associated with this render target\n */\n get renderTarget() {\n return this._renderTarget;\n }\n /**\n * Instantiates a new ThinRenderTargetTexture.\n * Tiny helper class to wrap a RenderTargetWrapper in a texture.\n * This can be used as an internal texture wrapper in ThinEngine to benefit from the cache and to hold on the associated RTT\n * @param engine Define the internalTexture to wrap\n * @param size Define the size of the RTT to create\n * @param options Define rendertarget options\n */\n constructor(engine, size, options) {\n super(null);\n this._renderTarget = null;\n this._engine = engine;\n this._renderTargetOptions = options;\n this.resize(size);\n }\n /**\n * Resize the texture to a new desired size.\n * Be careful as it will recreate all the data in the new texture.\n * @param size Define the new size. It can be:\n * - a number for squared texture,\n * - an object containing { width: number, height: number }\n */\n resize(size) {\n var _a;\n (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.dispose();\n this._renderTarget = null;\n this._texture = null;\n this._size = size;\n if (this._engine) {\n this._renderTarget = this._engine.createRenderTargetTexture(this._size, this._renderTargetOptions);\n }\n this._texture = this.renderTarget.texture;\n }\n /**\n * Get the underlying lower level texture from Babylon.\n * @returns the internal texture\n */\n getInternalTexture() {\n return this._texture;\n }\n /**\n * Get the class name of the texture.\n * @returns \"ThinRenderTargetTexture\"\n */\n getClassName() {\n return \"ThinRenderTargetTexture\";\n }\n /**\n * Dispose the texture and release its associated resources.\n * @param disposeOnlyFramebuffers\n */\n dispose(disposeOnlyFramebuffers = false) {\n var _a;\n (_a = this._renderTarget) === null || _a === void 0 ? void 0 : _a.dispose(true);\n this._renderTarget = null;\n if (!disposeOnlyFramebuffers) {\n super.dispose();\n }\n }\n}\n//# sourceMappingURL=thinRenderTargetTexture.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./baseTexture.js\";\n// eslint-disable-next-line import/export\nexport * from \"./baseTexture.polynomial.js\";\nexport * from \"./colorGradingTexture.js\";\nexport * from \"./cubeTexture.js\";\nexport * from \"./dynamicTexture.js\";\nexport * from \"./equiRectangularCubeTexture.js\";\nexport * from \"./externalTexture.js\";\nexport * from \"./Filtering/hdrFiltering.js\";\nexport * from \"./hdrCubeTexture.js\";\nexport * from \"./htmlElementTexture.js\";\nexport * from \"./internalTexture.js\";\nexport * from \"./internalTextureLoader.js\";\nexport * from \"./Loaders/index.js\";\nexport * from \"./mirrorTexture.js\";\nexport * from \"./multiRenderTarget.js\";\nexport * from \"./Packer/index.js\";\nexport * from \"./Procedurals/index.js\";\nexport * from \"./rawCubeTexture.js\";\nexport * from \"./rawTexture.js\";\nexport * from \"./rawTexture2DArray.js\";\nexport * from \"./rawTexture3D.js\";\nexport * from \"./refractionTexture.js\";\nexport * from \"./renderTargetTexture.js\";\nexport * from \"./textureSampler.js\";\nexport * from \"./texture.js\";\nexport * from \"./thinTexture.js\";\nexport * from \"./thinRenderTargetTexture.js\";\nexport * from \"./videoTexture.js\";\nexport * from \"./ktx2decoderTypes.js\";\n//# sourceMappingURL=index.js.map","export * from \"./nodeMaterialBlockTargets.js\";\nexport * from \"./nodeMaterialBlockConnectionPointTypes.js\";\nexport * from \"./nodeMaterialBlockConnectionPointMode.js\";\nexport * from \"./nodeMaterialSystemValues.js\";\nexport * from \"./nodeMaterialModes.js\";\n//# sourceMappingURL=index.js.map","import { NodeMaterialConnectionPoint, NodeMaterialConnectionPointCompatibilityStates } from \"./nodeMaterialBlockConnectionPoint.js\";\n/**\n * Defines a connection point to be used for points with a custom object type\n */\nexport class NodeMaterialConnectionPointCustomObject extends NodeMaterialConnectionPoint {\n /**\n * Creates a new connection point\n * @param name defines the connection point name\n * @param ownerBlock defines the block hosting this connection point\n * @param direction defines the direction of the connection point\n * @param _blockType\n * @param _blockName\n */\n constructor(name, ownerBlock, direction, \n // @internal\n _blockType, _blockName) {\n super(name, ownerBlock, direction);\n this._blockType = _blockType;\n this._blockName = _blockName;\n this.needDualDirectionValidation = true;\n }\n /**\n * Gets a number indicating if the current point can be connected to another point\n * @param connectionPoint defines the other connection point\n * @returns a number defining the compatibility state\n */\n checkCompatibilityState(connectionPoint) {\n return connectionPoint instanceof NodeMaterialConnectionPointCustomObject && connectionPoint._blockName === this._blockName\n ? NodeMaterialConnectionPointCompatibilityStates.Compatible\n : NodeMaterialConnectionPointCompatibilityStates.TypeIncompatible;\n }\n /**\n * Creates a block suitable to be used as an input for this input point.\n * If null is returned, a block based on the point type will be created.\n * @returns The returned string parameter is the name of the output point of NodeMaterialBlock (first parameter of the returned array) that can be connected to the input\n */\n createCustomInputBlock() {\n return [new this._blockType(this._blockName), this.name];\n }\n}\n//# sourceMappingURL=nodeMaterialConnectionPointCustomObject.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialSystemValues } from \"../../Enums/nodeMaterialSystemValues.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { MaterialHelper } from \"../../../materialHelper.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport \"../../../../Shaders/ShadersInclude/bonesDeclaration.js\";\nimport \"../../../../Shaders/ShadersInclude/bonesVertex.js\";\n/**\n * Block used to add support for vertex skinning (bones)\n */\nexport class BonesBlock extends NodeMaterialBlock {\n /**\n * Creates a new BonesBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Vertex);\n this.registerInput(\"matricesIndices\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerInput(\"matricesWeights\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerInput(\"matricesIndicesExtra\", NodeMaterialBlockConnectionPointTypes.Vector4, true);\n this.registerInput(\"matricesWeightsExtra\", NodeMaterialBlockConnectionPointTypes.Vector4, true);\n this.registerInput(\"world\", NodeMaterialBlockConnectionPointTypes.Matrix);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Matrix);\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"boneSampler\");\n state._excludeVariableName(\"boneTextureWidth\");\n state._excludeVariableName(\"mBones\");\n state._excludeVariableName(\"BonesPerMesh\");\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"BonesBlock\";\n }\n /**\n * Gets the matrix indices input component\n */\n get matricesIndices() {\n return this._inputs[0];\n }\n /**\n * Gets the matrix weights input component\n */\n get matricesWeights() {\n return this._inputs[1];\n }\n /**\n * Gets the extra matrix indices input component\n */\n get matricesIndicesExtra() {\n return this._inputs[2];\n }\n /**\n * Gets the extra matrix weights input component\n */\n get matricesWeightsExtra() {\n return this._inputs[3];\n }\n /**\n * Gets the world input component\n */\n get world() {\n return this._inputs[4];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n autoConfigure(material) {\n if (!this.matricesIndices.isConnected) {\n let matricesIndicesInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"matricesIndices\");\n if (!matricesIndicesInput) {\n matricesIndicesInput = new InputBlock(\"matricesIndices\");\n matricesIndicesInput.setAsAttribute(\"matricesIndices\");\n }\n matricesIndicesInput.output.connectTo(this.matricesIndices);\n }\n if (!this.matricesWeights.isConnected) {\n let matricesWeightsInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"matricesWeights\");\n if (!matricesWeightsInput) {\n matricesWeightsInput = new InputBlock(\"matricesWeights\");\n matricesWeightsInput.setAsAttribute(\"matricesWeights\");\n }\n matricesWeightsInput.output.connectTo(this.matricesWeights);\n }\n if (!this.world.isConnected) {\n let worldInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.World);\n if (!worldInput) {\n worldInput = new InputBlock(\"world\");\n worldInput.setAsSystemValue(NodeMaterialSystemValues.World);\n }\n worldInput.output.connectTo(this.world);\n }\n }\n provideFallbacks(mesh, fallbacks) {\n if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {\n fallbacks.addCPUSkinningFallback(0, mesh);\n }\n }\n bind(effect, nodeMaterial, mesh) {\n MaterialHelper.BindBonesParameters(mesh, effect);\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n if (!defines._areAttributesDirty) {\n return;\n }\n MaterialHelper.PrepareDefinesForBones(mesh, defines);\n }\n _buildBlock(state) {\n super._buildBlock(state);\n // Register for compilation fallbacks\n state.sharedData.blocksWithFallbacks.push(this);\n // Register for binding\n state.sharedData.forcedBindableBlocks.push(this);\n // Register for defines\n state.sharedData.blocksWithDefines.push(this);\n // Register internal uniforms and samplers\n state.uniforms.push(\"boneTextureWidth\");\n state.uniforms.push(\"mBones\");\n state.samplers.push(\"boneSampler\");\n // Emit code\n const comments = `//${this.name}`;\n state._emitFunctionFromInclude(\"bonesDeclaration\", comments, {\n removeAttributes: true,\n removeUniforms: false,\n removeVaryings: true,\n removeIfDef: false,\n });\n const influenceVariablename = state._getFreeVariableName(\"influence\");\n state.compilationString += state._emitCodeFromInclude(\"bonesVertex\", comments, {\n replaceStrings: [\n {\n search: /finalWorld=finalWorld\\*influence;/,\n replace: \"\",\n },\n {\n search: /influence/gm,\n replace: influenceVariablename,\n },\n ],\n });\n const output = this._outputs[0];\n const worldInput = this.world;\n state.compilationString += `#if NUM_BONE_INFLUENCERS>0\\r\\n`;\n state.compilationString += this._declareOutput(output, state) + ` = ${worldInput.associatedVariableName} * ${influenceVariablename};\\r\\n`;\n state.compilationString += `#else\\r\\n`;\n state.compilationString += this._declareOutput(output, state) + ` = ${worldInput.associatedVariableName};\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.BonesBlock\", BonesBlock);\n//# sourceMappingURL=bonesBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialSystemValues } from \"../../Enums/nodeMaterialSystemValues.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\n/**\n * Block used to add support for instances\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/copies/instances\n */\nexport class InstancesBlock extends NodeMaterialBlock {\n /**\n * Creates a new InstancesBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Vertex);\n this.registerInput(\"world0\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerInput(\"world1\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerInput(\"world2\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerInput(\"world3\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerInput(\"world\", NodeMaterialBlockConnectionPointTypes.Matrix, true);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Matrix);\n this.registerOutput(\"instanceID\", NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"InstancesBlock\";\n }\n /**\n * Gets the first world row input component\n */\n get world0() {\n return this._inputs[0];\n }\n /**\n * Gets the second world row input component\n */\n get world1() {\n return this._inputs[1];\n }\n /**\n * Gets the third world row input component\n */\n get world2() {\n return this._inputs[2];\n }\n /**\n * Gets the forth world row input component\n */\n get world3() {\n return this._inputs[3];\n }\n /**\n * Gets the world input component\n */\n get world() {\n return this._inputs[4];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n /**\n * Gets the instanceID component\n */\n get instanceID() {\n return this._outputs[1];\n }\n autoConfigure(material) {\n if (!this.world0.connectedPoint) {\n let world0Input = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"world0\");\n if (!world0Input) {\n world0Input = new InputBlock(\"world0\");\n world0Input.setAsAttribute(\"world0\");\n }\n world0Input.output.connectTo(this.world0);\n }\n if (!this.world1.connectedPoint) {\n let world1Input = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"world1\");\n if (!world1Input) {\n world1Input = new InputBlock(\"world1\");\n world1Input.setAsAttribute(\"world1\");\n }\n world1Input.output.connectTo(this.world1);\n }\n if (!this.world2.connectedPoint) {\n let world2Input = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"world2\");\n if (!world2Input) {\n world2Input = new InputBlock(\"world2\");\n world2Input.setAsAttribute(\"world2\");\n }\n world2Input.output.connectTo(this.world2);\n }\n if (!this.world3.connectedPoint) {\n let world3Input = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"world3\");\n if (!world3Input) {\n world3Input = new InputBlock(\"world3\");\n world3Input.setAsAttribute(\"world3\");\n }\n world3Input.output.connectTo(this.world3);\n }\n if (!this.world.connectedPoint) {\n let worldInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"world\");\n if (!worldInput) {\n worldInput = new InputBlock(\"world\");\n worldInput.setAsSystemValue(NodeMaterialSystemValues.World);\n }\n worldInput.output.connectTo(this.world);\n }\n this.world.define = \"!INSTANCES || THIN_INSTANCES\";\n }\n prepareDefines(mesh, nodeMaterial, defines, useInstances = false, subMesh) {\n let changed = false;\n if (defines[\"INSTANCES\"] !== useInstances) {\n defines.setValue(\"INSTANCES\", useInstances);\n changed = true;\n }\n if (subMesh && defines[\"THIN_INSTANCES\"] !== !!(subMesh === null || subMesh === void 0 ? void 0 : subMesh.getRenderingMesh().hasThinInstances)) {\n defines.setValue(\"THIN_INSTANCES\", !!(subMesh === null || subMesh === void 0 ? void 0 : subMesh.getRenderingMesh().hasThinInstances));\n changed = true;\n }\n if (changed) {\n defines.markAsUnprocessed();\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const engine = state.sharedData.scene.getEngine();\n // Register for defines\n state.sharedData.blocksWithDefines.push(this);\n // Emit code\n const output = this._outputs[0];\n const instanceID = this._outputs[1];\n const world0 = this.world0;\n const world1 = this.world1;\n const world2 = this.world2;\n const world3 = this.world3;\n state.compilationString += `#ifdef INSTANCES\\r\\n`;\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = mat4(${world0.associatedVariableName}, ${world1.associatedVariableName}, ${world2.associatedVariableName}, ${world3.associatedVariableName});\\r\\n`;\n state.compilationString += `#ifdef THIN_INSTANCES\\r\\n`;\n state.compilationString += `${output.associatedVariableName} = ${this.world.associatedVariableName} * ${output.associatedVariableName};\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n if (engine._caps.canUseGLInstanceID) {\n state.compilationString += this._declareOutput(instanceID, state) + ` = float(gl_InstanceID);\\r\\n`;\n }\n else {\n state.compilationString += this._declareOutput(instanceID, state) + ` = 0.0;\\r\\n`;\n }\n state.compilationString += `#else\\r\\n`;\n state.compilationString += this._declareOutput(output, state) + ` = ${this.world.associatedVariableName};\\r\\n`;\n state.compilationString += this._declareOutput(instanceID, state) + ` = 0.0;\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.InstancesBlock\", InstancesBlock);\n//# sourceMappingURL=instancesBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { MaterialHelper } from \"../../../materialHelper.js\";\nimport { VertexBuffer } from \"../../../../Buffers/buffer.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport \"../../../../Shaders/ShadersInclude/morphTargetsVertexDeclaration.js\";\nimport \"../../../../Shaders/ShadersInclude/morphTargetsVertexGlobalDeclaration.js\";\n/**\n * Block used to add morph targets support to vertex shader\n */\nexport class MorphTargetsBlock extends NodeMaterialBlock {\n /**\n * Create a new MorphTargetsBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Vertex);\n this.registerInput(\"position\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerInput(\"normal\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerInput(\"tangent\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.tangent.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color4 | NodeMaterialBlockConnectionPointTypes.Vector4 | NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerInput(\"uv\", NodeMaterialBlockConnectionPointTypes.Vector2);\n this.registerOutput(\"positionOutput\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerOutput(\"normalOutput\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerOutput(\"tangentOutput\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerOutput(\"uvOutput\", NodeMaterialBlockConnectionPointTypes.Vector2);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"MorphTargetsBlock\";\n }\n /**\n * Gets the position input component\n */\n get position() {\n return this._inputs[0];\n }\n /**\n * Gets the normal input component\n */\n get normal() {\n return this._inputs[1];\n }\n /**\n * Gets the tangent input component\n */\n get tangent() {\n return this._inputs[2];\n }\n /**\n * Gets the tangent input component\n */\n get uv() {\n return this._inputs[3];\n }\n /**\n * Gets the position output component\n */\n get positionOutput() {\n return this._outputs[0];\n }\n /**\n * Gets the normal output component\n */\n get normalOutput() {\n return this._outputs[1];\n }\n /**\n * Gets the tangent output component\n */\n get tangentOutput() {\n return this._outputs[2];\n }\n /**\n * Gets the tangent output component\n */\n get uvOutput() {\n return this._outputs[3];\n }\n initialize(state) {\n state._excludeVariableName(\"morphTargetInfluences\");\n }\n autoConfigure(material) {\n if (!this.position.isConnected) {\n let positionInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"position\");\n if (!positionInput) {\n positionInput = new InputBlock(\"position\");\n positionInput.setAsAttribute();\n }\n positionInput.output.connectTo(this.position);\n }\n if (!this.normal.isConnected) {\n let normalInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"normal\");\n if (!normalInput) {\n normalInput = new InputBlock(\"normal\");\n normalInput.setAsAttribute(\"normal\");\n }\n normalInput.output.connectTo(this.normal);\n }\n if (!this.tangent.isConnected) {\n let tangentInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"tangent\");\n if (!tangentInput) {\n tangentInput = new InputBlock(\"tangent\");\n tangentInput.setAsAttribute(\"tangent\");\n }\n tangentInput.output.connectTo(this.tangent);\n }\n if (!this.uv.isConnected) {\n let uvInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"uv\");\n if (!uvInput) {\n uvInput = new InputBlock(\"uv\");\n uvInput.setAsAttribute(\"uv\");\n }\n uvInput.output.connectTo(this.uv);\n }\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n if (mesh.morphTargetManager) {\n const morphTargetManager = mesh.morphTargetManager;\n if ((morphTargetManager === null || morphTargetManager === void 0 ? void 0 : morphTargetManager.isUsingTextureForTargets) && morphTargetManager.numInfluencers !== defines[\"NUM_MORPH_INFLUENCERS\"]) {\n defines.markAsAttributesDirty();\n }\n }\n if (!defines._areAttributesDirty) {\n return;\n }\n MaterialHelper.PrepareDefinesForMorphTargets(mesh, defines);\n }\n bind(effect, nodeMaterial, mesh) {\n if (mesh && mesh.morphTargetManager && mesh.morphTargetManager.numInfluencers > 0) {\n MaterialHelper.BindMorphTargetParameters(mesh, effect);\n if (mesh.morphTargetManager.isUsingTextureForTargets) {\n mesh.morphTargetManager._bind(effect);\n }\n }\n }\n replaceRepeatableContent(vertexShaderState, fragmentShaderState, mesh, defines) {\n const position = this.position;\n const normal = this.normal;\n const tangent = this.tangent;\n const uv = this.uv;\n const positionOutput = this.positionOutput;\n const normalOutput = this.normalOutput;\n const tangentOutput = this.tangentOutput;\n const uvOutput = this.uvOutput;\n const state = vertexShaderState;\n const repeatCount = defines.NUM_MORPH_INFLUENCERS;\n const manager = mesh.morphTargetManager;\n const hasNormals = manager && manager.supportsNormals && defines[\"NORMAL\"];\n const hasTangents = manager && manager.supportsTangents && defines[\"TANGENT\"];\n const hasUVs = manager && manager.supportsUVs && defines[\"UV1\"];\n let injectionCode = \"\";\n if ((manager === null || manager === void 0 ? void 0 : manager.isUsingTextureForTargets) && repeatCount > 0) {\n injectionCode += `float vertexID;\\r\\n`;\n }\n for (let index = 0; index < repeatCount; index++) {\n injectionCode += `#ifdef MORPHTARGETS\\r\\n`;\n if (manager === null || manager === void 0 ? void 0 : manager.isUsingTextureForTargets) {\n injectionCode += `vertexID = float(gl_VertexID) * morphTargetTextureInfo.x;\\r\\n`;\n injectionCode += `${positionOutput.associatedVariableName} += (readVector3FromRawSampler(${index}, vertexID) - ${position.associatedVariableName}) * morphTargetInfluences[${index}];\\r\\n`;\n injectionCode += `vertexID += 1.0;\\r\\n`;\n }\n else {\n injectionCode += `${positionOutput.associatedVariableName} += (position${index} - ${position.associatedVariableName}) * morphTargetInfluences[${index}];\\r\\n`;\n }\n if (hasNormals) {\n injectionCode += `#ifdef MORPHTARGETS_NORMAL\\r\\n`;\n if (manager === null || manager === void 0 ? void 0 : manager.isUsingTextureForTargets) {\n injectionCode += `${normalOutput.associatedVariableName} += (readVector3FromRawSampler(${index}, vertexID) - ${normal.associatedVariableName}) * morphTargetInfluences[${index}];\\r\\n`;\n injectionCode += `vertexID += 1.0;\\r\\n`;\n }\n else {\n injectionCode += `${normalOutput.associatedVariableName} += (normal${index} - ${normal.associatedVariableName}) * morphTargetInfluences[${index}];\\r\\n`;\n }\n injectionCode += `#endif\\r\\n`;\n }\n if (hasUVs) {\n injectionCode += `#ifdef MORPHTARGETS_UV\\r\\n`;\n if (manager === null || manager === void 0 ? void 0 : manager.isUsingTextureForTargets) {\n injectionCode += `${uvOutput.associatedVariableName} += (readVector3FromRawSampler(${index}, vertexID).xy - ${uv.associatedVariableName}) * morphTargetInfluences[${index}];\\r\\n`;\n injectionCode += `vertexID += 1.0;\\r\\n`;\n }\n else {\n injectionCode += `${uvOutput.associatedVariableName}.xy += (uv_${index} - ${uv.associatedVariableName}.xy) * morphTargetInfluences[${index}];\\r\\n`;\n }\n injectionCode += `#endif\\r\\n`;\n }\n if (hasTangents) {\n injectionCode += `#ifdef MORPHTARGETS_TANGENT\\r\\n`;\n if (manager === null || manager === void 0 ? void 0 : manager.isUsingTextureForTargets) {\n injectionCode += `${tangentOutput.associatedVariableName}.xyz += (readVector3FromRawSampler(${index}, vertexID) - ${tangent.associatedVariableName}.xyz) * morphTargetInfluences[${index}];\\r\\n`;\n }\n else {\n injectionCode += `${tangentOutput.associatedVariableName}.xyz += (tangent${index} - ${tangent.associatedVariableName}.xyz) * morphTargetInfluences[${index}];\\r\\n`;\n }\n if (tangent.type === NodeMaterialBlockConnectionPointTypes.Vector4) {\n injectionCode += `${tangentOutput.associatedVariableName}.w = ${tangent.associatedVariableName}.w;\\r\\n`;\n }\n else {\n injectionCode += `${tangentOutput.associatedVariableName}.w = 1.;\\r\\n`;\n }\n injectionCode += `#endif\\r\\n`;\n }\n injectionCode += `#endif\\r\\n`;\n }\n state.compilationString = state.compilationString.replace(this._repeatableContentAnchor, injectionCode);\n if (repeatCount > 0) {\n for (let index = 0; index < repeatCount; index++) {\n state.attributes.push(VertexBuffer.PositionKind + index);\n if (hasNormals) {\n state.attributes.push(VertexBuffer.NormalKind + index);\n }\n if (hasTangents) {\n state.attributes.push(VertexBuffer.TangentKind + index);\n }\n if (hasUVs) {\n state.attributes.push(VertexBuffer.UVKind + \"_\" + index);\n }\n }\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n // Register for defines\n state.sharedData.blocksWithDefines.push(this);\n // Register for binding\n state.sharedData.bindableBlocks.push(this);\n // Register for repeatable content generation\n state.sharedData.repeatableContentBlocks.push(this);\n // Emit code\n const position = this.position;\n const normal = this.normal;\n const tangent = this.tangent;\n const uv = this.uv;\n const positionOutput = this.positionOutput;\n const normalOutput = this.normalOutput;\n const tangentOutput = this.tangentOutput;\n const uvOutput = this.uvOutput;\n const comments = `//${this.name}`;\n state.uniforms.push(\"morphTargetInfluences\");\n state.uniforms.push(\"morphTargetTextureInfo\");\n state.uniforms.push(\"morphTargetTextureIndices\");\n state.samplers.push(\"morphTargets\");\n state._emitFunctionFromInclude(\"morphTargetsVertexGlobalDeclaration\", comments);\n state._emitFunctionFromInclude(\"morphTargetsVertexDeclaration\", comments, {\n repeatKey: \"maxSimultaneousMorphTargets\",\n });\n state.compilationString += `${this._declareOutput(positionOutput, state)} = ${position.associatedVariableName};\\r\\n`;\n state.compilationString += `#ifdef NORMAL\\r\\n`;\n state.compilationString += `${this._declareOutput(normalOutput, state)} = ${normal.associatedVariableName};\\r\\n`;\n state.compilationString += `#else\\r\\n`;\n state.compilationString += `${this._declareOutput(normalOutput, state)} = vec3(0., 0., 0.);\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n state.compilationString += `#ifdef TANGENT\\r\\n`;\n state.compilationString += `${this._declareOutput(tangentOutput, state)} = ${tangent.associatedVariableName};\\r\\n`;\n state.compilationString += `#else\\r\\n`;\n state.compilationString += `${this._declareOutput(tangentOutput, state)} = vec4(0., 0., 0., 0.);\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n state.compilationString += `#ifdef UV1\\r\\n`;\n state.compilationString += `${this._declareOutput(uvOutput, state)} = ${uv.associatedVariableName};\\r\\n`;\n state.compilationString += `#else\\r\\n`;\n state.compilationString += `${this._declareOutput(uvOutput, state)} = vec2(0., 0.);\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n // Repeatable content\n this._repeatableContentAnchor = state._repeatableContentAnchor;\n state.compilationString += this._repeatableContentAnchor;\n return this;\n }\n}\nRegisterClass(\"BABYLON.MorphTargetsBlock\", MorphTargetsBlock);\n//# sourceMappingURL=morphTargetsBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { PointLight } from \"../../../../Lights/pointLight.js\";\n/**\n * Block used to get data information from a light\n */\nexport class LightInformationBlock extends NodeMaterialBlock {\n /**\n * Creates a new LightInformationBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Vertex);\n this.registerInput(\"worldPosition\", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex);\n this.registerOutput(\"direction\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerOutput(\"color\", NodeMaterialBlockConnectionPointTypes.Color3);\n this.registerOutput(\"intensity\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"shadowBias\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"shadowNormalBias\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"shadowDepthScale\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"shadowDepthRange\", NodeMaterialBlockConnectionPointTypes.Vector2);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"LightInformationBlock\";\n }\n /**\n * Gets the world position input component\n */\n get worldPosition() {\n return this._inputs[0];\n }\n /**\n * Gets the direction output component\n */\n get direction() {\n return this._outputs[0];\n }\n /**\n * Gets the direction output component\n */\n get color() {\n return this._outputs[1];\n }\n /**\n * Gets the direction output component\n */\n get intensity() {\n return this._outputs[2];\n }\n /**\n * Gets the shadow bias output component\n */\n get shadowBias() {\n return this._outputs[3];\n }\n /**\n * Gets the shadow normal bias output component\n */\n get shadowNormalBias() {\n return this._outputs[4];\n }\n /**\n * Gets the shadow depth scale component\n */\n get shadowDepthScale() {\n return this._outputs[5];\n }\n /**\n * Gets the shadow depth range component\n */\n get shadowDepthRange() {\n return this._outputs[6];\n }\n bind(effect, nodeMaterial, mesh) {\n if (!mesh) {\n return;\n }\n if (this.light && this.light.isDisposed()) {\n this.light = null;\n }\n let light = this.light;\n const scene = nodeMaterial.getScene();\n if (!light && scene.lights.length) {\n light = this.light = scene.lights[0];\n this._forcePrepareDefines = true;\n }\n if (!light || !light.isEnabled) {\n effect.setFloat3(this._lightDataUniformName, 0, 0, 0);\n effect.setFloat4(this._lightColorUniformName, 0, 0, 0, 0);\n return;\n }\n light.transferToNodeMaterialEffect(effect, this._lightDataUniformName);\n effect.setColor4(this._lightColorUniformName, light.diffuse, light.intensity);\n const generator = light.getShadowGenerator();\n if (this.shadowBias.hasEndpoints || this.shadowNormalBias.hasEndpoints || this.shadowDepthScale.hasEndpoints) {\n if (generator) {\n effect.setFloat3(this._lightShadowUniformName, generator.bias, generator.normalBias, generator.depthScale);\n }\n else {\n effect.setFloat3(this._lightShadowUniformName, 0, 0, 0);\n }\n }\n if (this.shadowDepthRange) {\n if (generator && scene.activeCamera) {\n const shadowLight = light;\n effect.setFloat2(this._lightShadowExtraUniformName, shadowLight.getDepthMinZ(scene.activeCamera), shadowLight.getDepthMinZ(scene.activeCamera) + shadowLight.getDepthMaxZ(scene.activeCamera));\n }\n else {\n effect.setFloat2(this._lightShadowExtraUniformName, 0, 0);\n }\n }\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n if (!defines._areLightsDirty && !this._forcePrepareDefines) {\n return;\n }\n this._forcePrepareDefines = false;\n const light = this.light;\n defines.setValue(this._lightTypeDefineName, light && light instanceof PointLight ? true : false, true);\n }\n _buildBlock(state) {\n super._buildBlock(state);\n state.sharedData.bindableBlocks.push(this);\n state.sharedData.blocksWithDefines.push(this);\n const direction = this.direction;\n const color = this.color;\n const intensity = this.intensity;\n const shadowBias = this.shadowBias;\n const shadowNormalBias = this.shadowNormalBias;\n const shadowDepthScale = this.shadowDepthScale;\n const shadowDepthRange = this.shadowDepthRange;\n this._lightDataUniformName = state._getFreeVariableName(\"lightData\");\n this._lightColorUniformName = state._getFreeVariableName(\"lightColor\");\n this._lightShadowUniformName = state._getFreeVariableName(\"shadowData\");\n this._lightShadowExtraUniformName = state._getFreeVariableName(\"shadowExtraData\");\n this._lightTypeDefineName = state._getFreeDefineName(\"LIGHTPOINTTYPE\");\n state._emitUniformFromString(this._lightDataUniformName, \"vec3\");\n state._emitUniformFromString(this._lightColorUniformName, \"vec4\");\n state.compilationString += `#ifdef ${this._lightTypeDefineName}\\r\\n`;\n state.compilationString += this._declareOutput(direction, state) + ` = normalize(${this.worldPosition.associatedVariableName}.xyz - ${this._lightDataUniformName});\\r\\n`;\n state.compilationString += `#else\\r\\n`;\n state.compilationString += this._declareOutput(direction, state) + ` = ${this._lightDataUniformName};\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n state.compilationString += this._declareOutput(color, state) + ` = ${this._lightColorUniformName}.rgb;\\r\\n`;\n state.compilationString += this._declareOutput(intensity, state) + ` = ${this._lightColorUniformName}.a;\\r\\n`;\n if (shadowBias.hasEndpoints || shadowNormalBias.hasEndpoints || shadowDepthScale.hasEndpoints) {\n state._emitUniformFromString(this._lightShadowUniformName, \"vec3\");\n if (shadowBias.hasEndpoints) {\n state.compilationString += this._declareOutput(shadowBias, state) + ` = ${this._lightShadowUniformName}.x;\\r\\n`;\n }\n if (shadowNormalBias.hasEndpoints) {\n state.compilationString += this._declareOutput(shadowNormalBias, state) + ` = ${this._lightShadowUniformName}.y;\\r\\n`;\n }\n if (shadowDepthScale.hasEndpoints) {\n state.compilationString += this._declareOutput(shadowDepthScale, state) + ` = ${this._lightShadowUniformName}.z;\\r\\n`;\n }\n }\n if (shadowDepthRange.hasEndpoints) {\n state._emitUniformFromString(this._lightShadowExtraUniformName, \"vec2\");\n state.compilationString += this._declareOutput(shadowDepthRange, state) + ` = ${this._lightShadowUniformName};\\r\\n`;\n }\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n if (this.light) {\n serializationObject.lightId = this.light.id;\n }\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n if (serializationObject.lightId) {\n this.light = scene.getLightById(serializationObject.lightId);\n }\n }\n}\nRegisterClass(\"BABYLON.LightInformationBlock\", LightInformationBlock);\n//# sourceMappingURL=lightInformationBlock.js.map","export * from \"./vertexOutputBlock.js\";\nexport * from \"./bonesBlock.js\";\nexport * from \"./instancesBlock.js\";\nexport * from \"./morphTargetsBlock.js\";\nexport * from \"./lightInformationBlock.js\";\n//# sourceMappingURL=index.js.map","import { __decorate } from \"../../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../../nodeMaterialDecorator.js\";\nimport \"../../../../Shaders/ShadersInclude/helperFunctions.js\";\nimport \"../../../../Shaders/ShadersInclude/imageProcessingDeclaration.js\";\nimport \"../../../../Shaders/ShadersInclude/imageProcessingFunctions.js\";\n/**\n * Block used to add image processing support to fragment shader\n */\nexport class ImageProcessingBlock extends NodeMaterialBlock {\n /**\n * Create a new ImageProcessingBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n /**\n * Defines if the input should be converted to linear space (default: true)\n */\n this.convertInputToLinearSpace = true;\n this.registerInput(\"color\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Color4);\n this.registerOutput(\"rgb\", NodeMaterialBlockConnectionPointTypes.Color3);\n this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 |\n NodeMaterialBlockConnectionPointTypes.Color4 |\n NodeMaterialBlockConnectionPointTypes.Vector3 |\n NodeMaterialBlockConnectionPointTypes.Vector4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ImageProcessingBlock\";\n }\n /**\n * Gets the color input component\n */\n get color() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n /**\n * Gets the rgb component\n */\n get rgb() {\n return this._outputs[1];\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"exposureLinear\");\n state._excludeVariableName(\"contrast\");\n state._excludeVariableName(\"vInverseScreenSize\");\n state._excludeVariableName(\"vignetteSettings1\");\n state._excludeVariableName(\"vignetteSettings2\");\n state._excludeVariableName(\"vCameraColorCurveNegative\");\n state._excludeVariableName(\"vCameraColorCurveNeutral\");\n state._excludeVariableName(\"vCameraColorCurvePositive\");\n state._excludeVariableName(\"txColorTransform\");\n state._excludeVariableName(\"colorTransformSettings\");\n state._excludeVariableName(\"ditherIntensity\");\n }\n isReady(mesh, nodeMaterial, defines) {\n if (defines._areImageProcessingDirty && nodeMaterial.imageProcessingConfiguration) {\n if (!nodeMaterial.imageProcessingConfiguration.isReady()) {\n return false;\n }\n }\n return true;\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n if (defines._areImageProcessingDirty && nodeMaterial.imageProcessingConfiguration) {\n nodeMaterial.imageProcessingConfiguration.prepareDefines(defines);\n }\n }\n bind(effect, nodeMaterial, mesh) {\n if (!mesh) {\n return;\n }\n if (!nodeMaterial.imageProcessingConfiguration) {\n return;\n }\n nodeMaterial.imageProcessingConfiguration.bind(effect);\n }\n _buildBlock(state) {\n var _a;\n super._buildBlock(state);\n // Register for defines\n state.sharedData.blocksWithDefines.push(this);\n // Register for blocking\n state.sharedData.blockingBlocks.push(this);\n // Register for binding\n state.sharedData.bindableBlocks.push(this);\n // Uniforms\n state.uniforms.push(\"exposureLinear\");\n state.uniforms.push(\"contrast\");\n state.uniforms.push(\"vInverseScreenSize\");\n state.uniforms.push(\"vignetteSettings1\");\n state.uniforms.push(\"vignetteSettings2\");\n state.uniforms.push(\"vCameraColorCurveNegative\");\n state.uniforms.push(\"vCameraColorCurveNeutral\");\n state.uniforms.push(\"vCameraColorCurvePositive\");\n state.uniforms.push(\"txColorTransform\");\n state.uniforms.push(\"colorTransformSettings\");\n state.uniforms.push(\"ditherIntensity\");\n // Emit code\n const color = this.color;\n const output = this._outputs[0];\n const comments = `//${this.name}`;\n state._emitFunctionFromInclude(\"helperFunctions\", comments);\n state._emitFunctionFromInclude(\"imageProcessingDeclaration\", comments);\n state._emitFunctionFromInclude(\"imageProcessingFunctions\", comments);\n if ((_a = color.connectedPoint) === null || _a === void 0 ? void 0 : _a.isConnected) {\n if (color.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Color4 || color.connectedPoint.type === NodeMaterialBlockConnectionPointTypes.Vector4) {\n state.compilationString += `${this._declareOutput(output, state)} = ${color.associatedVariableName};\\r\\n`;\n }\n else {\n state.compilationString += `${this._declareOutput(output, state)} = vec4(${color.associatedVariableName}, 1.0);\\r\\n`;\n }\n state.compilationString += `#ifdef IMAGEPROCESSINGPOSTPROCESS\\r\\n`;\n if (this.convertInputToLinearSpace) {\n state.compilationString += `${output.associatedVariableName}.rgb = toLinearSpace(${color.associatedVariableName}.rgb);\\r\\n`;\n }\n state.compilationString += `#else\\r\\n`;\n state.compilationString += `#ifdef IMAGEPROCESSING\\r\\n`;\n if (this.convertInputToLinearSpace) {\n state.compilationString += `${output.associatedVariableName}.rgb = toLinearSpace(${color.associatedVariableName}.rgb);\\r\\n`;\n }\n state.compilationString += `${output.associatedVariableName} = applyImageProcessing(${output.associatedVariableName});\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n if (this.rgb.hasEndpoints) {\n state.compilationString += this._declareOutput(this.rgb, state) + ` = ${this.output.associatedVariableName}.xyz;\\r\\n`;\n }\n }\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n codeString += `${this._codeVariableName}.convertInputToLinearSpace = ${this.convertInputToLinearSpace};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.convertInputToLinearSpace = this.convertInputToLinearSpace;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n var _a;\n super._deserialize(serializationObject, scene, rootUrl);\n this.convertInputToLinearSpace = (_a = serializationObject.convertInputToLinearSpace) !== null && _a !== void 0 ? _a : true;\n }\n}\n__decorate([\n editableInPropertyPage(\"Convert input to linear space\", PropertyTypeForEdition.Boolean, \"ADVANCED\")\n], ImageProcessingBlock.prototype, \"convertInputToLinearSpace\", void 0);\nRegisterClass(\"BABYLON.ImageProcessingBlock\", ImageProcessingBlock);\n//# sourceMappingURL=imageProcessingBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../../nodeMaterialBlockConnectionPoint.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../../nodeMaterialConnectionPointCustomObject.js\";\nimport { NodeMaterialSystemValues } from \"../../Enums/nodeMaterialSystemValues.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\n/**\n * Block used to implement TBN matrix\n */\nexport class TBNBlock extends NodeMaterialBlock {\n /**\n * Create a new TBNBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment, true);\n this.registerInput(\"normal\", NodeMaterialBlockConnectionPointTypes.AutoDetect, false);\n this.normal.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color4 | NodeMaterialBlockConnectionPointTypes.Vector4 | NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerInput(\"tangent\", NodeMaterialBlockConnectionPointTypes.Vector4, false);\n this.registerInput(\"world\", NodeMaterialBlockConnectionPointTypes.Matrix, false);\n this.registerOutput(\"TBN\", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"TBN\", this, NodeMaterialConnectionPointDirection.Output, TBNBlock, \"TBNBlock\"));\n this.registerOutput(\"row0\", NodeMaterialBlockConnectionPointTypes.Vector3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"row1\", NodeMaterialBlockConnectionPointTypes.Vector3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"row2\", NodeMaterialBlockConnectionPointTypes.Vector3, NodeMaterialBlockTargets.Fragment);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"TBNBlock\";\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"tbnNormal\");\n state._excludeVariableName(\"tbnTangent\");\n state._excludeVariableName(\"tbnBitangent\");\n state._excludeVariableName(\"TBN\");\n }\n /**\n * Gets the normal input component\n */\n get normal() {\n return this._inputs[0];\n }\n /**\n * Gets the tangent input component\n */\n get tangent() {\n return this._inputs[1];\n }\n /**\n * Gets the world matrix input component\n */\n get world() {\n return this._inputs[2];\n }\n /**\n * Gets the TBN output component\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n get TBN() {\n return this._outputs[0];\n }\n /**\n * Gets the row0 of the output matrix\n */\n get row0() {\n return this._outputs[1];\n }\n /**\n * Gets the row1 of the output matrix\n */\n get row1() {\n return this._outputs[2];\n }\n /**\n * Gets the row2 of the output matrix\n */\n get row2() {\n return this._outputs[3];\n }\n get target() {\n return NodeMaterialBlockTargets.Fragment;\n }\n set target(value) { }\n autoConfigure(material) {\n if (!this.world.isConnected) {\n let worldInput = material.getInputBlockByPredicate((b) => b.isSystemValue && b.systemValue === NodeMaterialSystemValues.World);\n if (!worldInput) {\n worldInput = new InputBlock(\"world\");\n worldInput.setAsSystemValue(NodeMaterialSystemValues.World);\n }\n worldInput.output.connectTo(this.world);\n }\n if (!this.normal.isConnected) {\n let normalInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"normal\");\n if (!normalInput) {\n normalInput = new InputBlock(\"normal\");\n normalInput.setAsAttribute(\"normal\");\n }\n normalInput.output.connectTo(this.normal);\n }\n if (!this.tangent.isConnected) {\n let tangentInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"tangent\" && b.type === NodeMaterialBlockConnectionPointTypes.Vector4);\n if (!tangentInput) {\n tangentInput = new InputBlock(\"tangent\");\n tangentInput.setAsAttribute(\"tangent\");\n }\n tangentInput.output.connectTo(this.tangent);\n }\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n var _a, _b, _c, _d;\n const normal = this.normal;\n const tangent = this.tangent;\n let normalAvailable = normal.isConnected;\n if (((_a = normal.connectInputBlock) === null || _a === void 0 ? void 0 : _a.isAttribute) && !mesh.isVerticesDataPresent((_b = normal.connectInputBlock) === null || _b === void 0 ? void 0 : _b.name)) {\n normalAvailable = false;\n }\n let tangentAvailable = tangent.isConnected;\n if (((_c = tangent.connectInputBlock) === null || _c === void 0 ? void 0 : _c.isAttribute) && !mesh.isVerticesDataPresent((_d = tangent.connectInputBlock) === null || _d === void 0 ? void 0 : _d.name)) {\n tangentAvailable = false;\n }\n const useTBNBlock = normalAvailable && tangentAvailable;\n defines.setValue(\"TBNBLOCK\", useTBNBlock, true);\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const normal = this.normal;\n const tangent = this.tangent;\n const world = this.world;\n const TBN = this.TBN;\n const row0 = this.row0;\n const row1 = this.row1;\n const row2 = this.row2;\n // Fragment\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n state.compilationString += `\r\n // ${this.name}\r\n vec3 tbnNormal = normalize(${normal.associatedVariableName}).xyz;\r\n vec3 tbnTangent = normalize(${tangent.associatedVariableName}.xyz);\r\n vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${tangent.associatedVariableName}.w;\r\n mat3 ${TBN.associatedVariableName} = mat3(${world.associatedVariableName}) * mat3(tbnTangent, tbnBitangent, tbnNormal);\r\n `;\n if (row0.hasEndpoints) {\n state.compilationString +=\n this._declareOutput(row0, state) +\n ` = vec3(${TBN.associatedVariableName}[0][0], ${TBN.associatedVariableName}[0][1], ${TBN.associatedVariableName}[0][2]);\\r\\n`;\n }\n if (row1.hasEndpoints) {\n state.compilationString +=\n this._declareOutput(row1, state) + ` = vec3(${TBN.associatedVariableName}[1[0], ${TBN.associatedVariableName}[1][1], ${TBN.associatedVariableName}[1][2]);\\r\\n`;\n }\n if (row2.hasEndpoints) {\n state.compilationString +=\n this._declareOutput(row2, state) +\n ` = vec3(${TBN.associatedVariableName}[2][0], ${TBN.associatedVariableName}[2][1], ${TBN.associatedVariableName}[2][2]);\\r\\n`;\n }\n state.sharedData.blocksWithDefines.push(this);\n }\n return this;\n }\n}\nRegisterClass(\"BABYLON.TBNBlock\", TBNBlock);\n//# sourceMappingURL=TBNBlock.js.map","import { __decorate } from \"../../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../../nodeMaterialBlockConnectionPoint.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../../nodeMaterialDecorator.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../../nodeMaterialConnectionPointCustomObject.js\";\nimport { TBNBlock } from \"./TBNBlock.js\";\nimport \"../../../../Shaders/ShadersInclude/bumpFragmentMainFunctions.js\";\nimport \"../../../../Shaders/ShadersInclude/bumpFragmentFunctions.js\";\nimport \"../../../../Shaders/ShadersInclude/bumpFragment.js\";\n/**\n * Block used to perturb normals based on a normal map\n */\nexport class PerturbNormalBlock extends NodeMaterialBlock {\n /**\n * Create a new PerturbNormalBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this._tangentSpaceParameterName = \"\";\n this._tangentCorrectionFactorName = \"\";\n this._worldMatrixName = \"\";\n /** Gets or sets a boolean indicating that normal should be inverted on X axis */\n this.invertX = false;\n /** Gets or sets a boolean indicating that normal should be inverted on Y axis */\n this.invertY = false;\n /** Gets or sets a boolean indicating that parallax occlusion should be enabled */\n this.useParallaxOcclusion = false;\n /** Gets or sets a boolean indicating that sampling mode is in Object space */\n this.useObjectSpaceNormalMap = false;\n this._isUnique = true;\n // Vertex\n this.registerInput(\"worldPosition\", NodeMaterialBlockConnectionPointTypes.Vector4, false);\n this.registerInput(\"worldNormal\", NodeMaterialBlockConnectionPointTypes.Vector4, false);\n this.registerInput(\"worldTangent\", NodeMaterialBlockConnectionPointTypes.Vector4, true);\n this.registerInput(\"uv\", NodeMaterialBlockConnectionPointTypes.Vector2, false);\n this.registerInput(\"normalMapColor\", NodeMaterialBlockConnectionPointTypes.Color3, false);\n this.registerInput(\"strength\", NodeMaterialBlockConnectionPointTypes.Float, false);\n this.registerInput(\"viewDirection\", NodeMaterialBlockConnectionPointTypes.Vector3, true);\n this.registerInput(\"parallaxScale\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"parallaxHeight\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"TBN\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject(\"TBN\", this, NodeMaterialConnectionPointDirection.Input, TBNBlock, \"TBNBlock\"));\n this.registerInput(\"world\", NodeMaterialBlockConnectionPointTypes.Matrix, true);\n // Fragment\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerOutput(\"uvOffset\", NodeMaterialBlockConnectionPointTypes.Vector2);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"PerturbNormalBlock\";\n }\n /**\n * Gets the world position input component\n */\n get worldPosition() {\n return this._inputs[0];\n }\n /**\n * Gets the world normal input component\n */\n get worldNormal() {\n return this._inputs[1];\n }\n /**\n * Gets the world tangent input component\n */\n get worldTangent() {\n return this._inputs[2];\n }\n /**\n * Gets the uv input component\n */\n get uv() {\n return this._inputs[3];\n }\n /**\n * Gets the normal map color input component\n */\n get normalMapColor() {\n return this._inputs[4];\n }\n /**\n * Gets the strength input component\n */\n get strength() {\n return this._inputs[5];\n }\n /**\n * Gets the view direction input component\n */\n get viewDirection() {\n return this._inputs[6];\n }\n /**\n * Gets the parallax scale input component\n */\n get parallaxScale() {\n return this._inputs[7];\n }\n /**\n * Gets the parallax height input component\n */\n get parallaxHeight() {\n return this._inputs[8];\n }\n /**\n * Gets the TBN input component\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n get TBN() {\n return this._inputs[9];\n }\n /**\n * Gets the World input component\n */\n get world() {\n return this._inputs[10];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n /**\n * Gets the uv offset output component\n */\n get uvOffset() {\n return this._outputs[1];\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n const normalSamplerName = this.normalMapColor.connectedPoint._ownerBlock.samplerName;\n const useParallax = this.viewDirection.isConnected && ((this.useParallaxOcclusion && normalSamplerName) || (!this.useParallaxOcclusion && this.parallaxHeight.isConnected));\n defines.setValue(\"BUMP\", true);\n defines.setValue(\"PARALLAX\", useParallax, true);\n defines.setValue(\"PARALLAXOCCLUSION\", this.useParallaxOcclusion, true);\n defines.setValue(\"OBJECTSPACE_NORMALMAP\", this.useObjectSpaceNormalMap, true);\n }\n bind(effect, nodeMaterial, mesh) {\n if (nodeMaterial.getScene()._mirroredCameraPosition) {\n effect.setFloat2(this._tangentSpaceParameterName, this.invertX ? 1.0 : -1.0, this.invertY ? 1.0 : -1.0);\n }\n else {\n effect.setFloat2(this._tangentSpaceParameterName, this.invertX ? -1.0 : 1.0, this.invertY ? -1.0 : 1.0);\n }\n if (mesh) {\n effect.setFloat(this._tangentCorrectionFactorName, mesh.getWorldMatrix().determinant() < 0 ? -1 : 1);\n if (this.useObjectSpaceNormalMap && !this.world.isConnected) {\n // World default to the mesh world matrix\n effect.setMatrix(this._worldMatrixName, mesh.getWorldMatrix());\n }\n }\n }\n autoConfigure(material) {\n if (!this.uv.isConnected) {\n let uvInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"uv\");\n if (!uvInput) {\n uvInput = new InputBlock(\"uv\");\n uvInput.setAsAttribute();\n }\n uvInput.output.connectTo(this.uv);\n }\n if (!this.strength.isConnected) {\n const strengthInput = new InputBlock(\"strength\");\n strengthInput.value = 1.0;\n strengthInput.output.connectTo(this.strength);\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const comments = `//${this.name}`;\n const uv = this.uv;\n const worldPosition = this.worldPosition;\n const worldNormal = this.worldNormal;\n const worldTangent = this.worldTangent;\n state.sharedData.blocksWithDefines.push(this);\n state.sharedData.bindableBlocks.push(this);\n this._tangentSpaceParameterName = state._getFreeDefineName(\"tangentSpaceParameter\");\n state._emitUniformFromString(this._tangentSpaceParameterName, \"vec2\");\n this._tangentCorrectionFactorName = state._getFreeDefineName(\"tangentCorrectionFactor\");\n state._emitUniformFromString(this._tangentCorrectionFactorName, \"float\");\n this._worldMatrixName = state._getFreeDefineName(\"perturbNormalWorldMatrix\");\n state._emitUniformFromString(this._worldMatrixName, \"mat4\");\n let normalSamplerName = null;\n if (this.normalMapColor.connectedPoint) {\n normalSamplerName = this.normalMapColor.connectedPoint._ownerBlock.samplerName;\n }\n const useParallax = this.viewDirection.isConnected && ((this.useParallaxOcclusion && normalSamplerName) || (!this.useParallaxOcclusion && this.parallaxHeight.isConnected));\n const replaceForParallaxInfos = !this.parallaxScale.isConnectedToInputBlock\n ? \"0.05\"\n : this.parallaxScale.connectInputBlock.isConstant\n ? state._emitFloat(this.parallaxScale.connectInputBlock.value)\n : this.parallaxScale.associatedVariableName;\n const replaceForBumpInfos = this.strength.isConnectedToInputBlock && this.strength.connectInputBlock.isConstant\n ? `\\r\\n#if !defined(NORMALXYSCALE)\\r\\n1.0/\\r\\n#endif\\r\\n${state._emitFloat(this.strength.connectInputBlock.value)}`\n : `\\r\\n#if !defined(NORMALXYSCALE)\\r\\n1.0/\\r\\n#endif\\r\\n${this.strength.associatedVariableName}`;\n state._emitExtension(\"derivatives\", \"#extension GL_OES_standard_derivatives : enable\");\n const tangentReplaceString = { search: /defined\\(TANGENT\\)/g, replace: worldTangent.isConnected ? \"defined(TANGENT)\" : \"defined(IGNORE)\" };\n const tbnVarying = { search: /varying mat3 vTBN/g, replace: \"\" };\n const normalMatrixReplaceString = { search: /uniform mat4 normalMatrix;/g, replace: \"\" };\n const TBN = this.TBN;\n if (TBN.isConnected) {\n state.compilationString += `\r\n #ifdef TBNBLOCK\r\n mat3 vTBN = ${TBN.associatedVariableName};\r\n #endif\r\n `;\n }\n else if (worldTangent.isConnected) {\n state.compilationString += `vec3 tbnNormal = normalize(${worldNormal.associatedVariableName}.xyz);\\r\\n`;\n state.compilationString += `vec3 tbnTangent = normalize(${worldTangent.associatedVariableName}.xyz);\\r\\n`;\n state.compilationString += `vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};\\r\\n`;\n state.compilationString += `mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\\r\\n`;\n }\n state._emitFunctionFromInclude(\"bumpFragmentMainFunctions\", comments, {\n replaceStrings: [tangentReplaceString, tbnVarying, normalMatrixReplaceString],\n });\n state._emitFunctionFromInclude(\"bumpFragmentFunctions\", comments, {\n replaceStrings: [\n { search: /#include\\(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump\\)/g, replace: \"\" },\n { search: /uniform sampler2D bumpSampler;/g, replace: \"\" },\n {\n search: /vec2 parallaxOcclusion\\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\\)/g,\n replace: \"#define inline\\r\\nvec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale, sampler2D bumpSampler)\",\n },\n { search: /vec2 parallaxOffset\\(vec3 viewDir,float heightScale\\)/g, replace: \"vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)\" },\n { search: /texture2D\\(bumpSampler,vBumpUV\\)\\.w/g, replace: \"height_\" },\n ],\n });\n const uvForPerturbNormal = !useParallax || !normalSamplerName ? this.normalMapColor.associatedVariableName : `texture2D(${normalSamplerName}, ${uv.associatedVariableName} + uvOffset).xyz`;\n state.compilationString += this._declareOutput(this.output, state) + \" = vec4(0.);\\r\\n\";\n state.compilationString += state._emitCodeFromInclude(\"bumpFragment\", comments, {\n replaceStrings: [\n { search: /texture2D\\(bumpSampler,vBumpUV\\)/g, replace: `${uvForPerturbNormal}` },\n {\n search: /#define CUSTOM_FRAGMENT_BUMP_FRAGMENT/g,\n replace: `mat4 normalMatrix = toNormalMatrix(${this.world.isConnected ? this.world.associatedVariableName : this._worldMatrixName});`,\n },\n { search: /perturbNormal\\(TBN,texture2D\\(bumpSampler,vBumpUV\\+uvOffset\\).xyz,vBumpInfos.y\\)/g, replace: `perturbNormal(TBN, ${uvForPerturbNormal}, vBumpInfos.y)` },\n {\n search: /parallaxOcclusion\\(invTBN\\*-viewDirectionW,invTBN\\*normalW,vBumpUV,vBumpInfos.z\\)/g,\n replace: `parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ${useParallax && this.useParallaxOcclusion ? normalSamplerName : \"bumpSampler\"})`,\n },\n {\n search: /parallaxOffset\\(invTBN\\*viewDirectionW,vBumpInfos\\.z\\)/g,\n replace: `parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ${useParallax ? this.parallaxHeight.associatedVariableName : \"0.\"})`,\n },\n { search: /vTangentSpaceParams/g, replace: this._tangentSpaceParameterName },\n { search: /vBumpInfos.y/g, replace: replaceForBumpInfos },\n { search: /vBumpInfos.z/g, replace: replaceForParallaxInfos },\n { search: /vBumpUV/g, replace: uv.associatedVariableName },\n { search: /vPositionW/g, replace: worldPosition.associatedVariableName + \".xyz\" },\n { search: /normalW=/g, replace: this.output.associatedVariableName + \".xyz = \" },\n { search: /mat3\\(normalMatrix\\)\\*normalW/g, replace: \"mat3(normalMatrix) * \" + this.output.associatedVariableName + \".xyz\" },\n { search: /normalW/g, replace: worldNormal.associatedVariableName + \".xyz\" },\n { search: /viewDirectionW/g, replace: useParallax ? this.viewDirection.associatedVariableName : \"vec3(0.)\" },\n tangentReplaceString,\n ],\n });\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.invertX = ${this.invertX};\\r\\n`;\n codeString += `${this._codeVariableName}.invertY = ${this.invertY};\\r\\n`;\n codeString += `${this._codeVariableName}.useParallaxOcclusion = ${this.useParallaxOcclusion};\\r\\n`;\n codeString += `${this._codeVariableName}.useObjectSpaceNormalMap = ${this.useObjectSpaceNormalMap};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.invertX = this.invertX;\n serializationObject.invertY = this.invertY;\n serializationObject.useParallaxOcclusion = this.useParallaxOcclusion;\n serializationObject.useObjectSpaceNormalMap = this.useObjectSpaceNormalMap;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.invertX = serializationObject.invertX;\n this.invertY = serializationObject.invertY;\n this.useParallaxOcclusion = !!serializationObject.useParallaxOcclusion;\n this.useObjectSpaceNormalMap = !!serializationObject.useObjectSpaceNormalMap;\n }\n}\n__decorate([\n editableInPropertyPage(\"Invert X axis\", PropertyTypeForEdition.Boolean, \"PROPERTIES\", { notifiers: { update: false } })\n], PerturbNormalBlock.prototype, \"invertX\", void 0);\n__decorate([\n editableInPropertyPage(\"Invert Y axis\", PropertyTypeForEdition.Boolean, \"PROPERTIES\", { notifiers: { update: false } })\n], PerturbNormalBlock.prototype, \"invertY\", void 0);\n__decorate([\n editableInPropertyPage(\"Use parallax occlusion\", PropertyTypeForEdition.Boolean)\n], PerturbNormalBlock.prototype, \"useParallaxOcclusion\", void 0);\n__decorate([\n editableInPropertyPage(\"Object Space Mode\", PropertyTypeForEdition.Boolean, \"PROPERTIES\", { notifiers: { update: false } })\n], PerturbNormalBlock.prototype, \"useObjectSpaceNormalMap\", void 0);\nRegisterClass(\"BABYLON.PerturbNormalBlock\", PerturbNormalBlock);\n//# sourceMappingURL=perturbNormalBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\n/**\n * Block used to discard a pixel if a value is smaller than a cutoff\n */\nexport class DiscardBlock extends NodeMaterialBlock {\n /**\n * Create a new DiscardBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment, true);\n this.registerInput(\"value\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"cutoff\", NodeMaterialBlockConnectionPointTypes.Float, true);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"DiscardBlock\";\n }\n /**\n * Gets the color input component\n */\n get value() {\n return this._inputs[0];\n }\n /**\n * Gets the cutoff input component\n */\n get cutoff() {\n return this._inputs[1];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n state.sharedData.hints.needAlphaTesting = true;\n if (!this.cutoff.isConnected || !this.value.isConnected) {\n return;\n }\n state.compilationString += `if (${this.value.associatedVariableName} < ${this.cutoff.associatedVariableName}) discard;\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.DiscardBlock\", DiscardBlock);\n//# sourceMappingURL=discardBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\n/**\n * Block used to test if the fragment shader is front facing\n */\nexport class FrontFacingBlock extends NodeMaterialBlock {\n /**\n * Creates a new FrontFacingBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"FrontFacingBlock\";\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (state.target === NodeMaterialBlockTargets.Vertex) {\n throw \"FrontFacingBlock must only be used in a fragment shader\";\n }\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = gl_FrontFacing ? 1.0 : 0.0;\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.FrontFacingBlock\", FrontFacingBlock);\n//# sourceMappingURL=frontFacingBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\n/**\n * Block used to get the derivative value on x and y of a given input\n */\nexport class DerivativeBlock extends NodeMaterialBlock {\n /**\n * Create a new DerivativeBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.AutoDetect, false);\n this.registerOutput(\"dx\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this.registerOutput(\"dy\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._outputs[1]._typeConnectionSource = this._inputs[0];\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"DerivativeBlock\";\n }\n /**\n * Gets the input component\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the derivative output on x\n */\n get dx() {\n return this._outputs[0];\n }\n /**\n * Gets the derivative output on y\n */\n get dy() {\n return this._outputs[1];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const dx = this._outputs[0];\n const dy = this._outputs[1];\n state._emitExtension(\"derivatives\", \"#extension GL_OES_standard_derivatives : enable\");\n if (dx.hasEndpoints) {\n state.compilationString += this._declareOutput(dx, state) + ` = dFdx(${this.input.associatedVariableName});\\r\\n`;\n }\n if (dy.hasEndpoints) {\n state.compilationString += this._declareOutput(dy, state) + ` = dFdy(${this.input.associatedVariableName});\\r\\n`;\n }\n return this;\n }\n}\nRegisterClass(\"BABYLON.DerivativeBlock\", DerivativeBlock);\n//# sourceMappingURL=derivativeBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\n/**\n * Block used to make gl_FragCoord available\n */\nexport class FragCoordBlock extends NodeMaterialBlock {\n /**\n * Creates a new FragCoordBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"xy\", NodeMaterialBlockConnectionPointTypes.Vector2, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"xyz\", NodeMaterialBlockConnectionPointTypes.Vector3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"xyzw\", NodeMaterialBlockConnectionPointTypes.Vector4, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"x\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"y\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"z\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"w\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"FragCoordBlock\";\n }\n /**\n * Gets the xy component\n */\n get xy() {\n return this._outputs[0];\n }\n /**\n * Gets the xyz component\n */\n get xyz() {\n return this._outputs[1];\n }\n /**\n * Gets the xyzw component\n */\n get xyzw() {\n return this._outputs[2];\n }\n /**\n * Gets the x component\n */\n get x() {\n return this._outputs[3];\n }\n /**\n * Gets the y component\n */\n get y() {\n return this._outputs[4];\n }\n /**\n * Gets the z component\n */\n get z() {\n return this._outputs[5];\n }\n /**\n * Gets the w component\n */\n get output() {\n return this._outputs[6];\n }\n // eslint-disable-next-line @typescript-eslint/naming-convention\n writeOutputs(state) {\n let code = \"\";\n for (const output of this._outputs) {\n if (output.hasEndpoints) {\n code += `${this._declareOutput(output, state)} = gl_FragCoord.${output.name};\\r\\n`;\n }\n }\n return code;\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (state.target === NodeMaterialBlockTargets.Vertex) {\n throw \"FragCoordBlock must only be used in a fragment shader\";\n }\n state.compilationString += this.writeOutputs(state);\n return this;\n }\n}\nRegisterClass(\"BABYLON.FragCoordBlock\", FragCoordBlock);\n//# sourceMappingURL=fragCoordBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\n/**\n * Block used to get the screen sizes\n */\nexport class ScreenSizeBlock extends NodeMaterialBlock {\n /**\n * Creates a new ScreenSizeBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"xy\", NodeMaterialBlockConnectionPointTypes.Vector2, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"x\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"y\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ScreenSizeBlock\";\n }\n /**\n * Gets the xy component\n */\n get xy() {\n return this._outputs[0];\n }\n /**\n * Gets the x component\n */\n get x() {\n return this._outputs[1];\n }\n /**\n * Gets the y component\n */\n get y() {\n return this._outputs[2];\n }\n bind(effect) {\n const engine = this._scene.getEngine();\n effect.setFloat2(this._varName, engine.getRenderWidth(), engine.getRenderHeight());\n }\n // eslint-disable-next-line @typescript-eslint/naming-convention\n writeOutputs(state, varName) {\n let code = \"\";\n for (const output of this._outputs) {\n if (output.hasEndpoints) {\n code += `${this._declareOutput(output, state)} = ${varName}.${output.name};\\r\\n`;\n }\n }\n return code;\n }\n _buildBlock(state) {\n super._buildBlock(state);\n this._scene = state.sharedData.scene;\n if (state.target === NodeMaterialBlockTargets.Vertex) {\n throw \"ScreenSizeBlock must only be used in a fragment shader\";\n }\n state.sharedData.bindableBlocks.push(this);\n this._varName = state._getFreeVariableName(\"screenSize\");\n state._emitUniformFromString(this._varName, \"vec2\");\n state.compilationString += this.writeOutputs(state, this._varName);\n return this;\n }\n}\nRegisterClass(\"BABYLON.ScreenSizeBlock\", ScreenSizeBlock);\n//# sourceMappingURL=screenSizeBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { NodeMaterialSystemValues } from \"../../Enums/nodeMaterialSystemValues.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\n/**\n * Block used to transform a vector3 or a vector4 into screen space\n */\nexport class ScreenSpaceBlock extends NodeMaterialBlock {\n /**\n * Creates a new ScreenSpaceBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"vector\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"worldViewProjection\", NodeMaterialBlockConnectionPointTypes.Matrix);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Vector2);\n this.registerOutput(\"x\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"y\", NodeMaterialBlockConnectionPointTypes.Float);\n this.inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ScreenSpaceBlock\";\n }\n /**\n * Gets the vector input\n */\n get vector() {\n return this._inputs[0];\n }\n /**\n * Gets the worldViewProjection transform input\n */\n get worldViewProjection() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n /**\n * Gets the x output component\n */\n get x() {\n return this._outputs[1];\n }\n /**\n * Gets the y output component\n */\n get y() {\n return this._outputs[2];\n }\n autoConfigure(material) {\n if (!this.worldViewProjection.isConnected) {\n let worldViewProjectionInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.WorldViewProjection);\n if (!worldViewProjectionInput) {\n worldViewProjectionInput = new InputBlock(\"worldViewProjection\");\n worldViewProjectionInput.setAsSystemValue(NodeMaterialSystemValues.WorldViewProjection);\n }\n worldViewProjectionInput.output.connectTo(this.worldViewProjection);\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const vector = this.vector;\n const worldViewProjection = this.worldViewProjection;\n if (!vector.connectedPoint) {\n return;\n }\n const worldViewProjectionName = worldViewProjection.associatedVariableName;\n const tempVariableName = state._getFreeVariableName(\"screenSpaceTemp\");\n switch (vector.connectedPoint.type) {\n case NodeMaterialBlockConnectionPointTypes.Vector3:\n state.compilationString += `vec4 ${tempVariableName} = ${worldViewProjectionName} * vec4(${vector.associatedVariableName}, 1.0);\\r\\n`;\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector4:\n state.compilationString += `vec4 ${tempVariableName} = ${worldViewProjectionName} * ${vector.associatedVariableName};\\r\\n`;\n break;\n }\n state.compilationString += `${tempVariableName}.xy /= ${tempVariableName}.w;`;\n state.compilationString += `${tempVariableName}.xy = ${tempVariableName}.xy * 0.5 + vec2(0.5, 0.5);`;\n if (this.output.hasEndpoints) {\n state.compilationString += this._declareOutput(this.output, state) + ` = ${tempVariableName}.xy;\\r\\n`;\n }\n if (this.x.hasEndpoints) {\n state.compilationString += this._declareOutput(this.x, state) + ` = ${tempVariableName}.x;\\r\\n`;\n }\n if (this.y.hasEndpoints) {\n state.compilationString += this._declareOutput(this.y, state) + ` = ${tempVariableName}.y;\\r\\n`;\n }\n return this;\n }\n}\nRegisterClass(\"BABYLON.ScreenSpaceBlock\", ScreenSpaceBlock);\n//# sourceMappingURL=screenSpaceBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { Vector2 } from \"../../../../Maths/math.vector.js\";\n/**\n * Block used to generate a twirl\n */\nexport class TwirlBlock extends NodeMaterialBlock {\n /**\n * Creates a new TwirlBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.Vector2);\n this.registerInput(\"strength\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerInput(\"center\", NodeMaterialBlockConnectionPointTypes.Vector2);\n this.registerInput(\"offset\", NodeMaterialBlockConnectionPointTypes.Vector2);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Vector2);\n this.registerOutput(\"x\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"y\", NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"TwirlBlock\";\n }\n /**\n * Gets the input component\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the strength component\n */\n get strength() {\n return this._inputs[1];\n }\n /**\n * Gets the center component\n */\n get center() {\n return this._inputs[2];\n }\n /**\n * Gets the offset component\n */\n get offset() {\n return this._inputs[3];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n /**\n * Gets the x output component\n */\n get x() {\n return this._outputs[1];\n }\n /**\n * Gets the y output component\n */\n get y() {\n return this._outputs[2];\n }\n autoConfigure() {\n if (!this.center.isConnected) {\n const centerInput = new InputBlock(\"center\");\n centerInput.value = new Vector2(0.5, 0.5);\n centerInput.output.connectTo(this.center);\n }\n if (!this.strength.isConnected) {\n const strengthInput = new InputBlock(\"strength\");\n strengthInput.value = 1.0;\n strengthInput.output.connectTo(this.strength);\n }\n if (!this.offset.isConnected) {\n const offsetInput = new InputBlock(\"offset\");\n offsetInput.value = new Vector2(0, 0);\n offsetInput.output.connectTo(this.offset);\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const tempDelta = state._getFreeVariableName(\"delta\");\n const tempAngle = state._getFreeVariableName(\"angle\");\n const tempX = state._getFreeVariableName(\"x\");\n const tempY = state._getFreeVariableName(\"y\");\n const tempResult = state._getFreeVariableName(\"result\");\n state.compilationString += `\r\n vec2 ${tempDelta} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName};\r\n float ${tempAngle} = ${this.strength.associatedVariableName} * length(${tempDelta});\r\n float ${tempX} = cos(${tempAngle}) * ${tempDelta}.x - sin(${tempAngle}) * ${tempDelta}.y;\r\n float ${tempY} = sin(${tempAngle}) * ${tempDelta}.x + cos(${tempAngle}) * ${tempDelta}.y;\r\n vec2 ${tempResult} = vec2(${tempX} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${tempY} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y);\r\n `;\n if (this.output.hasEndpoints) {\n state.compilationString += this._declareOutput(this.output, state) + ` = ${tempResult};\\r\\n`;\n }\n if (this.x.hasEndpoints) {\n state.compilationString += this._declareOutput(this.x, state) + ` = ${tempResult}.x;\\r\\n`;\n }\n if (this.y.hasEndpoints) {\n state.compilationString += this._declareOutput(this.y, state) + ` = ${tempResult}.y;\\r\\n`;\n }\n return this;\n }\n}\nRegisterClass(\"BABYLON.TwirlBlock\", TwirlBlock);\n//# sourceMappingURL=twirlBlock.js.map","import { __decorate } from \"../../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../../nodeMaterialDecorator.js\";\n/**\n * Block used to convert a height vector to a normal\n */\nexport class HeightToNormalBlock extends NodeMaterialBlock {\n /**\n * Creates a new HeightToNormalBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n /**\n * Defines if the output should be generated in world or tangent space.\n * Note that in tangent space the result is also scaled by 0.5 and offsetted by 0.5 so that it can directly be used as a PerturbNormal.normalMapColor input\n */\n this.generateInWorldSpace = false;\n /**\n * Defines that the worldNormal input will be normalized by the HeightToNormal block before being used\n */\n this.automaticNormalizationNormal = true;\n /**\n * Defines that the worldTangent input will be normalized by the HeightToNormal block before being used\n */\n this.automaticNormalizationTangent = true;\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerInput(\"worldPosition\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerInput(\"worldNormal\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerInput(\"worldTangent\", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerOutput(\"xyz\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this._inputs[3].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"HeightToNormalBlock\";\n }\n /**\n * Gets the input component\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the position component\n */\n get worldPosition() {\n return this._inputs[1];\n }\n /**\n * Gets the normal component\n */\n get worldNormal() {\n return this._inputs[2];\n }\n /**\n * Gets the tangent component\n */\n get worldTangent() {\n return this._inputs[3];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n /**\n * Gets the xyz component\n */\n get xyz() {\n return this._outputs[1];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n if (!this.generateInWorldSpace && !this.worldTangent.isConnected) {\n console.error(`You must connect the 'worldTangent' input of the ${this.name} block!`);\n }\n const startCode = this.generateInWorldSpace\n ? \"\"\n : `\r\n vec3 biTangent = cross(normal, tangent);\r\n mat3 TBN = mat3(tangent, biTangent, normal);\r\n `;\n const endCode = this.generateInWorldSpace\n ? \"\"\n : `\r\n result = TBN * result;\r\n result = result * vec3(0.5) + vec3(0.5);\r\n `;\n const heightToNormal = `\r\n vec4 heightToNormal(in float height, in vec3 position, in vec3 tangent, in vec3 normal) {\r\n ${startCode}\r\n ${this.automaticNormalizationTangent ? \"tangent = normalize(tangent);\" : \"\"}\r\n ${this.automaticNormalizationNormal ? \"normal = normalize(normal);\" : \"\"}\r\n vec3 worlddX = dFdx(position);\r\n vec3 worlddY = dFdy(position);\r\n vec3 crossX = cross(normal, worlddX);\r\n vec3 crossY = cross(normal, worlddY);\r\n float d = abs(dot(crossY, worlddX));\r\n vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d));\r\n inToNormal.y *= -1.0;\r\n vec3 result = normalize((d * normal) - inToNormal);\r\n ${endCode}\r\n return vec4(result, 0.);\r\n }`;\n state._emitExtension(\"derivatives\", \"#extension GL_OES_standard_derivatives : enable\");\n state._emitFunction(\"heightToNormal\", heightToNormal, \"// heightToNormal\");\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = heightToNormal(${this.input.associatedVariableName}, ${this.worldPosition.associatedVariableName}, ${this.worldTangent.isConnected ? this.worldTangent.associatedVariableName : \"vec3(0.)\"}.xyz, ${this.worldNormal.associatedVariableName});\\r\\n`;\n if (this.xyz.hasEndpoints) {\n state.compilationString += this._declareOutput(this.xyz, state) + ` = ${this.output.associatedVariableName}.xyz;\\r\\n`;\n }\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n codeString += `${this._codeVariableName}.generateInWorldSpace = ${this.generateInWorldSpace};\\r\\n`;\n codeString += `${this._codeVariableName}.automaticNormalizationNormal = ${this.automaticNormalizationNormal};\\r\\n`;\n codeString += `${this._codeVariableName}.automaticNormalizationTangent = ${this.automaticNormalizationTangent};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.generateInWorldSpace = this.generateInWorldSpace;\n serializationObject.automaticNormalizationNormal = this.automaticNormalizationNormal;\n serializationObject.automaticNormalizationTangent = this.automaticNormalizationTangent;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.generateInWorldSpace = serializationObject.generateInWorldSpace;\n this.automaticNormalizationNormal = serializationObject.automaticNormalizationNormal;\n this.automaticNormalizationTangent = serializationObject.automaticNormalizationTangent;\n }\n}\n__decorate([\n editableInPropertyPage(\"Generate in world space instead of tangent space\", PropertyTypeForEdition.Boolean, \"PROPERTIES\", { notifiers: { update: true } })\n], HeightToNormalBlock.prototype, \"generateInWorldSpace\", void 0);\n__decorate([\n editableInPropertyPage(\"Force normalization for the worldNormal input\", PropertyTypeForEdition.Boolean, \"PROPERTIES\", { notifiers: { update: true } })\n], HeightToNormalBlock.prototype, \"automaticNormalizationNormal\", void 0);\n__decorate([\n editableInPropertyPage(\"Force normalization for the worldTangent input\", PropertyTypeForEdition.Boolean, \"PROPERTIES\", { notifiers: { update: true } })\n], HeightToNormalBlock.prototype, \"automaticNormalizationTangent\", void 0);\nRegisterClass(\"BABYLON.HeightToNormalBlock\", HeightToNormalBlock);\n//# sourceMappingURL=heightToNormalBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\n/**\n * Block used to write the fragment depth\n */\nexport class FragDepthBlock extends NodeMaterialBlock {\n /**\n * Create a new FragDepthBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment, true);\n this.registerInput(\"depth\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"worldPos\", NodeMaterialBlockConnectionPointTypes.Vector4, true);\n this.registerInput(\"viewProjection\", NodeMaterialBlockConnectionPointTypes.Matrix, true);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"FragDepthBlock\";\n }\n /**\n * Gets the depth input component\n */\n get depth() {\n return this._inputs[0];\n }\n /**\n * Gets the worldPos input component\n */\n get worldPos() {\n return this._inputs[1];\n }\n /**\n * Gets the viewProjection input component\n */\n get viewProjection() {\n return this._inputs[2];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (this.depth.isConnected) {\n state.compilationString += `gl_FragDepth = ${this.depth.associatedVariableName};\\r\\n`;\n }\n else if (this.worldPos.isConnected && this.viewProjection.isConnected) {\n state.compilationString += `\r\n vec4 p = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName};\r\n float v = p.z / p.w;\r\n #ifndef IS_NDC_HALF_ZRANGE\r\n v = v * 0.5 + 0.5;\r\n #endif\r\n gl_FragDepth = v;\r\n \r\n `;\n }\n else {\n console.warn(\"FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!\");\n }\n return this;\n }\n}\nRegisterClass(\"BABYLON.FragDepthBlock\", FragDepthBlock);\n//# sourceMappingURL=fragDepthBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\n/**\n * Block used to output the depth to a shadow map\n */\nexport class ShadowMapBlock extends NodeMaterialBlock {\n /**\n * Create a new ShadowMapBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"worldPosition\", NodeMaterialBlockConnectionPointTypes.Vector4, false);\n this.registerInput(\"viewProjection\", NodeMaterialBlockConnectionPointTypes.Matrix, false);\n this.registerInput(\"worldNormal\", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);\n this.registerOutput(\"depth\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.worldNormal.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ShadowMapBlock\";\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"vPositionWSM\");\n state._excludeVariableName(\"lightDataSM\");\n state._excludeVariableName(\"biasAndScaleSM\");\n state._excludeVariableName(\"depthValuesSM\");\n state._excludeVariableName(\"clipPos\");\n state._excludeVariableName(\"worldPos\");\n state._excludeVariableName(\"zSM\");\n }\n /**\n * Gets the world position input component\n */\n get worldPosition() {\n return this._inputs[0];\n }\n /**\n * Gets the view x projection input component\n */\n get viewProjection() {\n return this._inputs[1];\n }\n /**\n * Gets the world normal input component\n */\n get worldNormal() {\n return this._inputs[2];\n }\n /**\n * Gets the depth output component\n */\n get depth() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const comments = `//${this.name}`;\n state._emitUniformFromString(\"biasAndScaleSM\", \"vec3\");\n state._emitUniformFromString(\"lightDataSM\", \"vec3\");\n state._emitUniformFromString(\"depthValuesSM\", \"vec2\");\n state._emitFunctionFromInclude(\"packingFunctions\", comments);\n state.compilationString += `vec4 worldPos = ${this.worldPosition.associatedVariableName};\\r\\n`;\n state.compilationString += `vec3 vPositionWSM;\\r\\n`;\n state.compilationString += `float vDepthMetricSM = 0.0;\\r\\n`;\n state.compilationString += `float zSM;\\r\\n`;\n if (this.worldNormal.isConnected) {\n state.compilationString += `vec3 vNormalW = ${this.worldNormal.associatedVariableName}.xyz;\\r\\n`;\n state.compilationString += state._emitCodeFromInclude(\"shadowMapVertexNormalBias\", comments);\n }\n state.compilationString += `vec4 clipPos = ${this.viewProjection.associatedVariableName} * worldPos;\\r\\n`;\n state.compilationString += state._emitCodeFromInclude(\"shadowMapVertexMetric\", comments, {\n replaceStrings: [\n {\n search: /gl_Position/g,\n replace: \"clipPos\",\n },\n ],\n });\n state.compilationString += state._emitCodeFromInclude(\"shadowMapFragment\", comments, {\n replaceStrings: [\n {\n search: /return;/g,\n replace: \"\",\n },\n ],\n });\n state.compilationString += `\r\n #if SM_DEPTHTEXTURE == 1\r\n #ifdef IS_NDC_HALF_ZRANGE\r\n gl_FragDepth = (clipPos.z / clipPos.w);\r\n #else\r\n gl_FragDepth = (clipPos.z / clipPos.w) * 0.5 + 0.5;\r\n #endif\r\n #endif\r\n `;\n state.compilationString += `${this._declareOutput(this.depth, state)} = vec3(depthSM, 1., 1.);\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.ShadowMapBlock\", ShadowMapBlock);\n//# sourceMappingURL=shadowMapBlock.js.map","export * from \"./fragmentOutputBlock.js\";\nexport * from \"./imageProcessingBlock.js\";\nexport * from \"./perturbNormalBlock.js\";\nexport * from \"./discardBlock.js\";\nexport * from \"./frontFacingBlock.js\";\nexport * from \"./derivativeBlock.js\";\nexport * from \"./fragCoordBlock.js\";\nexport * from \"./screenSizeBlock.js\";\nexport * from \"./screenSpaceBlock.js\";\nexport * from \"./twirlBlock.js\";\nexport * from \"./TBNBlock.js\";\nexport * from \"./heightToNormalBlock.js\";\nexport * from \"./fragDepthBlock.js\";\nexport * from \"./shadowMapBlock.js\";\n//# sourceMappingURL=index.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialSystemValues } from \"../../Enums/nodeMaterialSystemValues.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { MaterialHelper } from \"../../../materialHelper.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport \"../../../../Shaders/ShadersInclude/fogFragmentDeclaration.js\";\n/**\n * Block used to add support for scene fog\n */\nexport class FogBlock extends NodeMaterialBlock {\n /**\n * Create a new FogBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.VertexAndFragment, false);\n // Vertex\n this.registerInput(\"worldPosition\", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex);\n this.registerInput(\"view\", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Vertex);\n // Fragment\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"fogColor\", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.input.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Color4);\n this.fogColor.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Color4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"FogBlock\";\n }\n /**\n * Gets the world position input component\n */\n get worldPosition() {\n return this._inputs[0];\n }\n /**\n * Gets the view input component\n */\n get view() {\n return this._inputs[1];\n }\n /**\n * Gets the color input component\n */\n get input() {\n return this._inputs[2];\n }\n /**\n * Gets the fog color input component\n */\n get fogColor() {\n return this._inputs[3];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n autoConfigure(material) {\n if (!this.view.isConnected) {\n let viewInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.View);\n if (!viewInput) {\n viewInput = new InputBlock(\"view\");\n viewInput.setAsSystemValue(NodeMaterialSystemValues.View);\n }\n viewInput.output.connectTo(this.view);\n }\n if (!this.fogColor.isConnected) {\n let fogColorInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.FogColor);\n if (!fogColorInput) {\n fogColorInput = new InputBlock(\"fogColor\", undefined, NodeMaterialBlockConnectionPointTypes.Color3);\n fogColorInput.setAsSystemValue(NodeMaterialSystemValues.FogColor);\n }\n fogColorInput.output.connectTo(this.fogColor);\n }\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n const scene = mesh.getScene();\n defines.setValue(\"FOG\", nodeMaterial.fogEnabled && MaterialHelper.GetFogState(mesh, scene));\n }\n bind(effect, nodeMaterial, mesh) {\n if (!mesh) {\n return;\n }\n const scene = mesh.getScene();\n effect.setFloat4(this._fogParameters, scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n state.sharedData.blocksWithDefines.push(this);\n state.sharedData.bindableBlocks.push(this);\n state._emitFunctionFromInclude(\"fogFragmentDeclaration\", `//${this.name}`, {\n removeUniforms: true,\n removeVaryings: true,\n removeIfDef: false,\n replaceStrings: [{ search: /float CalcFogFactor\\(\\)/, replace: \"float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)\" }],\n });\n const tempFogVariablename = state._getFreeVariableName(\"fog\");\n const color = this.input;\n const fogColor = this.fogColor;\n this._fogParameters = state._getFreeVariableName(\"fogParameters\");\n const output = this._outputs[0];\n state._emitUniformFromString(this._fogParameters, \"vec4\");\n state.compilationString += `#ifdef FOG\\r\\n`;\n state.compilationString += `float ${tempFogVariablename} = CalcFogFactor(${this._fogDistanceName}, ${this._fogParameters});\\r\\n`;\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = ${tempFogVariablename} * ${color.associatedVariableName}.rgb + (1.0 - ${tempFogVariablename}) * ${fogColor.associatedVariableName}.rgb;\\r\\n`;\n state.compilationString += `#else\\r\\n${this._declareOutput(output, state)} = ${color.associatedVariableName}.rgb;\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n }\n else {\n const worldPos = this.worldPosition;\n const view = this.view;\n this._fogDistanceName = state._getFreeVariableName(\"vFogDistance\");\n state._emitVaryingFromString(this._fogDistanceName, \"vec3\");\n state.compilationString += `${this._fogDistanceName} = (${view.associatedVariableName} * ${worldPos.associatedVariableName}).xyz;\\r\\n`;\n }\n return this;\n }\n}\nRegisterClass(\"BABYLON.FogBlock\", FogBlock);\n//# sourceMappingURL=fogBlock.js.map","import { __decorate } from \"../../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { MaterialHelper } from \"../../../materialHelper.js\";\nimport { NodeMaterialSystemValues } from \"../../Enums/nodeMaterialSystemValues.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../../nodeMaterialDecorator.js\";\nimport \"../../../../Shaders/ShadersInclude/lightFragmentDeclaration.js\";\nimport \"../../../../Shaders/ShadersInclude/lightVxFragmentDeclaration.js\";\nimport \"../../../../Shaders/ShadersInclude/lightUboDeclaration.js\";\nimport \"../../../../Shaders/ShadersInclude/lightVxUboDeclaration.js\";\nimport \"../../../../Shaders/ShadersInclude/lightFragment.js\";\nimport \"../../../../Shaders/ShadersInclude/helperFunctions.js\";\nimport \"../../../../Shaders/ShadersInclude/lightsFragmentFunctions.js\";\nimport \"../../../../Shaders/ShadersInclude/shadowsFragmentFunctions.js\";\nimport \"../../../../Shaders/ShadersInclude/shadowsVertex.js\";\n/**\n * Block used to add light in the fragment shader\n */\nexport class LightBlock extends NodeMaterialBlock {\n static _OnGenerateOnlyFragmentCodeChanged(block, _propertyName) {\n const that = block;\n if (that.worldPosition.isConnected) {\n that.generateOnlyFragmentCode = !that.generateOnlyFragmentCode;\n console.error(\"The worldPosition input must not be connected to be able to switch!\");\n return false;\n }\n that._setTarget();\n return true;\n }\n _setTarget() {\n this._setInitialTarget(this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.VertexAndFragment);\n this.getInputByName(\"worldPosition\").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex;\n }\n /**\n * Create a new LightBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.VertexAndFragment);\n this._lightId = 0;\n /** Indicates that no code should be generated in the vertex shader. Can be useful in some specific circumstances (like when doing ray marching for eg) */\n this.generateOnlyFragmentCode = false;\n this._isUnique = true;\n this.registerInput(\"worldPosition\", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex);\n this.registerInput(\"worldNormal\", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"cameraPosition\", NodeMaterialBlockConnectionPointTypes.Vector3, false, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"glossiness\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"glossPower\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"diffuseColor\", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"specularColor\", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"view\", NodeMaterialBlockConnectionPointTypes.Matrix, true);\n this.registerOutput(\"diffuseOutput\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"specularOutput\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"shadow\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"LightBlock\";\n }\n /**\n * Gets the world position input component\n */\n get worldPosition() {\n return this._inputs[0];\n }\n /**\n * Gets the world normal input component\n */\n get worldNormal() {\n return this._inputs[1];\n }\n /**\n * Gets the camera (or eye) position component\n */\n get cameraPosition() {\n return this._inputs[2];\n }\n /**\n * Gets the glossiness component\n */\n get glossiness() {\n return this._inputs[3];\n }\n /**\n * Gets the glossiness power component\n */\n get glossPower() {\n return this._inputs[4];\n }\n /**\n * Gets the diffuse color component\n */\n get diffuseColor() {\n return this._inputs[5];\n }\n /**\n * Gets the specular color component\n */\n get specularColor() {\n return this._inputs[6];\n }\n /**\n * Gets the view matrix component\n */\n get view() {\n return this._inputs[7];\n }\n /**\n * Gets the diffuse output component\n */\n get diffuseOutput() {\n return this._outputs[0];\n }\n /**\n * Gets the specular output component\n */\n get specularOutput() {\n return this._outputs[1];\n }\n /**\n * Gets the shadow output component\n */\n get shadow() {\n return this._outputs[2];\n }\n autoConfigure(material) {\n if (!this.cameraPosition.isConnected) {\n let cameraPositionInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.CameraPosition);\n if (!cameraPositionInput) {\n cameraPositionInput = new InputBlock(\"cameraPosition\");\n cameraPositionInput.setAsSystemValue(NodeMaterialSystemValues.CameraPosition);\n }\n cameraPositionInput.output.connectTo(this.cameraPosition);\n }\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n if (!defines._areLightsDirty) {\n return;\n }\n const scene = mesh.getScene();\n if (!this.light) {\n MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, nodeMaterial.maxSimultaneousLights);\n }\n else {\n const state = {\n needNormals: false,\n needRebuild: false,\n lightmapMode: false,\n shadowEnabled: false,\n specularEnabled: false,\n };\n MaterialHelper.PrepareDefinesForLight(scene, mesh, this.light, this._lightId, defines, true, state);\n if (state.needRebuild) {\n defines.rebuild();\n }\n }\n }\n updateUniformsAndSamples(state, nodeMaterial, defines, uniformBuffers) {\n for (let lightIndex = 0; lightIndex < nodeMaterial.maxSimultaneousLights; lightIndex++) {\n if (!defines[\"LIGHT\" + lightIndex]) {\n break;\n }\n const onlyUpdateBuffersList = state.uniforms.indexOf(\"vLightData\" + lightIndex) >= 0;\n MaterialHelper.PrepareUniformsAndSamplersForLight(lightIndex, state.uniforms, state.samplers, defines[\"PROJECTEDLIGHTTEXTURE\" + lightIndex], uniformBuffers, onlyUpdateBuffersList);\n }\n }\n bind(effect, nodeMaterial, mesh) {\n if (!mesh) {\n return;\n }\n const scene = mesh.getScene();\n if (!this.light) {\n MaterialHelper.BindLights(scene, mesh, effect, true, nodeMaterial.maxSimultaneousLights);\n }\n else {\n MaterialHelper.BindLight(this.light, this._lightId, scene, effect, true);\n }\n }\n _injectVertexCode(state) {\n const worldPos = this.worldPosition;\n const comments = `//${this.name}`;\n // Declaration\n if (!this.light) {\n // Emit for all lights\n state._emitFunctionFromInclude(state.supportUniformBuffers ? \"lightVxUboDeclaration\" : \"lightVxFragmentDeclaration\", comments, {\n repeatKey: \"maxSimultaneousLights\",\n });\n this._lightId = 0;\n state.sharedData.dynamicUniformBlocks.push(this);\n }\n else {\n this._lightId = (state.counters[\"lightCounter\"] !== undefined ? state.counters[\"lightCounter\"] : -1) + 1;\n state.counters[\"lightCounter\"] = this._lightId;\n state._emitFunctionFromInclude(state.supportUniformBuffers ? \"lightVxUboDeclaration\" : \"lightVxFragmentDeclaration\", comments, {\n replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }],\n }, this._lightId.toString());\n }\n // Inject code in vertex\n const worldPosVaryingName = \"v_\" + worldPos.associatedVariableName;\n if (state._emitVaryingFromString(worldPosVaryingName, \"vec4\")) {\n state.compilationString += `${worldPosVaryingName} = ${worldPos.associatedVariableName};\\r\\n`;\n }\n if (this.light) {\n state.compilationString += state._emitCodeFromInclude(\"shadowsVertex\", comments, {\n replaceStrings: [\n { search: /{X}/g, replace: this._lightId.toString() },\n { search: /worldPos/g, replace: worldPos.associatedVariableName },\n ],\n });\n }\n else {\n state.compilationString += `vec4 worldPos = ${worldPos.associatedVariableName};\\r\\n`;\n if (this.view.isConnected) {\n state.compilationString += `mat4 view = ${this.view.associatedVariableName};\\r\\n`;\n }\n state.compilationString += state._emitCodeFromInclude(\"shadowsVertex\", comments, {\n repeatKey: \"maxSimultaneousLights\",\n });\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (state.target !== NodeMaterialBlockTargets.Fragment) {\n // Vertex\n this._injectVertexCode(state);\n return;\n }\n if (this.generateOnlyFragmentCode) {\n state.sharedData.dynamicUniformBlocks.push(this);\n }\n // Fragment\n state.sharedData.forcedBindableBlocks.push(this);\n state.sharedData.blocksWithDefines.push(this);\n const comments = `//${this.name}`;\n const worldPos = this.worldPosition;\n let worldPosVariableName = worldPos.associatedVariableName;\n if (this.generateOnlyFragmentCode) {\n worldPosVariableName = state._getFreeVariableName(\"globalWorldPos\");\n state._emitFunction(\"light_globalworldpos\", `vec3 ${worldPosVariableName};\\r\\n`, comments);\n state.compilationString += `${worldPosVariableName} = ${worldPos.associatedVariableName}.xyz;\\r\\n`;\n state.compilationString += state._emitCodeFromInclude(\"shadowsVertex\", comments, {\n repeatKey: \"maxSimultaneousLights\",\n substitutionVars: this.generateOnlyFragmentCode ? `worldPos,${worldPos.associatedVariableName}` : undefined,\n });\n }\n else {\n worldPosVariableName = \"v_\" + worldPosVariableName + \".xyz\";\n }\n state._emitFunctionFromInclude(\"helperFunctions\", comments);\n state._emitFunctionFromInclude(\"lightsFragmentFunctions\", comments, {\n replaceStrings: [{ search: /vPositionW/g, replace: worldPosVariableName }],\n });\n state._emitFunctionFromInclude(\"shadowsFragmentFunctions\", comments, {\n replaceStrings: [{ search: /vPositionW/g, replace: worldPosVariableName }],\n });\n if (!this.light) {\n // Emit for all lights\n state._emitFunctionFromInclude(state.supportUniformBuffers ? \"lightUboDeclaration\" : \"lightFragmentDeclaration\", comments, {\n repeatKey: \"maxSimultaneousLights\",\n substitutionVars: this.generateOnlyFragmentCode ? \"varying,\" : undefined,\n });\n }\n else {\n state._emitFunctionFromInclude(state.supportUniformBuffers ? \"lightUboDeclaration\" : \"lightFragmentDeclaration\", comments, {\n replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }],\n }, this._lightId.toString());\n }\n // Code\n if (this._lightId === 0) {\n if (state._registerTempVariable(\"viewDirectionW\")) {\n state.compilationString += `vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${worldPosVariableName});\\r\\n`;\n }\n state.compilationString += `lightingInfo info;\\r\\n`;\n state.compilationString += `float shadow = 1.;\\r\\n`;\n state.compilationString += `float glossiness = ${this.glossiness.isConnected ? this.glossiness.associatedVariableName : \"1.0\"} * ${this.glossPower.isConnected ? this.glossPower.associatedVariableName : \"1024.0\"};\\r\\n`;\n state.compilationString += `vec3 diffuseBase = vec3(0., 0., 0.);\\r\\n`;\n state.compilationString += `vec3 specularBase = vec3(0., 0., 0.);\\r\\n`;\n state.compilationString += `vec3 normalW = ${this.worldNormal.associatedVariableName}.xyz;\\r\\n`;\n }\n if (this.light) {\n state.compilationString += state._emitCodeFromInclude(\"lightFragment\", comments, {\n replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }],\n });\n }\n else {\n state.compilationString += state._emitCodeFromInclude(\"lightFragment\", comments, {\n repeatKey: \"maxSimultaneousLights\",\n });\n }\n const diffuseOutput = this.diffuseOutput;\n const specularOutput = this.specularOutput;\n state.compilationString +=\n this._declareOutput(diffuseOutput, state) + ` = diffuseBase${this.diffuseColor.isConnected ? \" * \" + this.diffuseColor.associatedVariableName : \"\"};\\r\\n`;\n if (specularOutput.hasEndpoints) {\n state.compilationString +=\n this._declareOutput(specularOutput, state) + ` = specularBase${this.specularColor.isConnected ? \" * \" + this.specularColor.associatedVariableName : \"\"};\\r\\n`;\n }\n if (this.shadow.hasEndpoints) {\n state.compilationString += this._declareOutput(this.shadow, state) + ` = shadow;\\r\\n`;\n }\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.generateOnlyFragmentCode = this.generateOnlyFragmentCode;\n if (this.light) {\n serializationObject.lightId = this.light.id;\n }\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n if (serializationObject.lightId) {\n this.light = scene.getLightById(serializationObject.lightId);\n }\n this.generateOnlyFragmentCode = serializationObject.generateOnlyFragmentCode;\n this._setTarget();\n }\n}\n__decorate([\n editableInPropertyPage(\"Generate only fragment code\", PropertyTypeForEdition.Boolean, \"ADVANCED\", {\n notifiers: { rebuild: true, update: true, onValidation: LightBlock._OnGenerateOnlyFragmentCodeChanged },\n })\n], LightBlock.prototype, \"generateOnlyFragmentCode\", void 0);\nRegisterClass(\"BABYLON.LightBlock\", LightBlock);\n//# sourceMappingURL=lightBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../../nodeMaterialBlockConnectionPoint.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { Texture } from \"../../../Textures/texture.js\";\n\nimport { NodeMaterial } from \"../../nodeMaterial.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../../nodeMaterialConnectionPointCustomObject.js\";\nimport { EngineStore } from \"../../../../Engines/engineStore.js\";\n/**\n * Block used to provide an image for a TextureBlock\n */\nexport class ImageSourceBlock extends NodeMaterialBlock {\n /**\n * Gets or sets the texture associated with the node\n */\n get texture() {\n return this._texture;\n }\n set texture(texture) {\n var _a;\n if (this._texture === texture) {\n return;\n }\n const scene = (_a = texture === null || texture === void 0 ? void 0 : texture.getScene()) !== null && _a !== void 0 ? _a : EngineStore.LastCreatedScene;\n if (!texture && scene) {\n scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(this._texture);\n });\n }\n this._texture = texture;\n if (texture && scene) {\n scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(texture);\n });\n }\n }\n /**\n * Gets the sampler name associated with this image source\n */\n get samplerName() {\n return this._samplerName;\n }\n /**\n * Creates a new ImageSourceBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.VertexAndFragment);\n this.registerOutput(\"source\", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject(\"source\", this, NodeMaterialConnectionPointDirection.Output, ImageSourceBlock, \"ImageSourceBlock\"));\n }\n bind(effect) {\n if (!this.texture) {\n return;\n }\n effect.setTexture(this._samplerName, this.texture);\n }\n isReady() {\n if (this.texture && !this.texture.isReadyOrNotBlocking()) {\n return false;\n }\n return true;\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ImageSourceBlock\";\n }\n /**\n * Gets the output component\n */\n get source() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (state.target === NodeMaterialBlockTargets.Vertex) {\n this._samplerName = state._getFreeVariableName(this.name + \"Sampler\");\n // Declarations\n state.sharedData.blockingBlocks.push(this);\n state.sharedData.textureBlocks.push(this);\n state.sharedData.bindableBlocks.push(this);\n }\n state._emit2DSampler(this._samplerName);\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n if (!this.texture) {\n return codeString;\n }\n codeString += `${this._codeVariableName}.texture = new BABYLON.Texture(\"${this.texture.name}\", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\\r\\n`;\n codeString += `${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n if (this.texture && !this.texture.isRenderTarget && this.texture.getClassName() !== \"VideoTexture\") {\n serializationObject.texture = this.texture.serialize();\n }\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n if (serializationObject.texture && !NodeMaterial.IgnoreTexturesAtLoadTime && serializationObject.texture.url !== undefined) {\n rootUrl = serializationObject.texture.url.indexOf(\"data:\") === 0 ? \"\" : rootUrl;\n this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl);\n }\n }\n}\nRegisterClass(\"BABYLON.ImageSourceBlock\", ImageSourceBlock);\n//# sourceMappingURL=imageSourceBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../../nodeMaterialBlockConnectionPoint.js\";\nimport { NodeMaterial } from \"../../nodeMaterial.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { Texture } from \"../../../Textures/texture.js\";\nimport { NodeMaterialModes } from \"../../Enums/nodeMaterialModes.js\";\n\nimport \"../../../../Shaders/ShadersInclude/helperFunctions.js\";\nimport { ImageSourceBlock } from \"./imageSourceBlock.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../../nodeMaterialConnectionPointCustomObject.js\";\nimport { EngineStore } from \"../../../../Engines/engineStore.js\";\n/**\n * Block used to read a texture from a sampler\n */\nexport class TextureBlock extends NodeMaterialBlock {\n /**\n * Gets or sets the texture associated with the node\n */\n get texture() {\n var _a;\n if (this.source.isConnected) {\n return ((_a = this.source.connectedPoint) === null || _a === void 0 ? void 0 : _a.ownerBlock).texture;\n }\n return this._texture;\n }\n set texture(texture) {\n var _a;\n if (this._texture === texture) {\n return;\n }\n const scene = (_a = texture === null || texture === void 0 ? void 0 : texture.getScene()) !== null && _a !== void 0 ? _a : EngineStore.LastCreatedScene;\n if (!texture && scene) {\n scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(this._texture);\n });\n }\n this._texture = texture;\n if (texture && scene) {\n scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(texture);\n });\n }\n }\n /**\n * Gets the sampler name associated with this texture\n */\n get samplerName() {\n if (this._imageSource) {\n return this._imageSource.samplerName;\n }\n return this._samplerName;\n }\n /**\n * Gets a boolean indicating that this block is linked to an ImageSourceBlock\n */\n get hasImageSource() {\n return this.source.isConnected;\n }\n /**\n * Gets or sets a boolean indicating if content needs to be converted to gamma space\n */\n set convertToGammaSpace(value) {\n var _a;\n if (value === this._convertToGammaSpace) {\n return;\n }\n this._convertToGammaSpace = value;\n if (this.texture) {\n const scene = (_a = this.texture.getScene()) !== null && _a !== void 0 ? _a : EngineStore.LastCreatedScene;\n scene === null || scene === void 0 ? void 0 : scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(this.texture);\n });\n }\n }\n get convertToGammaSpace() {\n return this._convertToGammaSpace;\n }\n /**\n * Gets or sets a boolean indicating if content needs to be converted to linear space\n */\n set convertToLinearSpace(value) {\n var _a;\n if (value === this._convertToLinearSpace) {\n return;\n }\n this._convertToLinearSpace = value;\n if (this.texture) {\n const scene = (_a = this.texture.getScene()) !== null && _a !== void 0 ? _a : EngineStore.LastCreatedScene;\n scene === null || scene === void 0 ? void 0 : scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(this.texture);\n });\n }\n }\n get convertToLinearSpace() {\n return this._convertToLinearSpace;\n }\n /**\n * Create a new TextureBlock\n * @param name defines the block name\n * @param fragmentOnly\n */\n constructor(name, fragmentOnly = false) {\n super(name, fragmentOnly ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.VertexAndFragment);\n this._convertToGammaSpace = false;\n this._convertToLinearSpace = false;\n /**\n * Gets or sets a boolean indicating if multiplication of texture with level should be disabled\n */\n this.disableLevelMultiplication = false;\n this._fragmentOnly = fragmentOnly;\n this.registerInput(\"uv\", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.VertexAndFragment);\n this.registerInput(\"source\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject(\"source\", this, NodeMaterialConnectionPointDirection.Input, ImageSourceBlock, \"ImageSourceBlock\"));\n this.registerInput(\"layer\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"lod\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerOutput(\"rgba\", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"rgb\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"r\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"g\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"b\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"a\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"level\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector2 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);\n this._inputs[0]._prioritizeVertex = !fragmentOnly;\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"TextureBlock\";\n }\n /**\n * Gets the uv input component\n */\n get uv() {\n return this._inputs[0];\n }\n /**\n * Gets the source input component\n */\n get source() {\n return this._inputs[1];\n }\n /**\n * Gets the layer input component\n */\n get layer() {\n return this._inputs[2];\n }\n /**\n * Gets the LOD input component\n */\n get lod() {\n return this._inputs[3];\n }\n /**\n * Gets the rgba output component\n */\n get rgba() {\n return this._outputs[0];\n }\n /**\n * Gets the rgb output component\n */\n get rgb() {\n return this._outputs[1];\n }\n /**\n * Gets the r output component\n */\n get r() {\n return this._outputs[2];\n }\n /**\n * Gets the g output component\n */\n get g() {\n return this._outputs[3];\n }\n /**\n * Gets the b output component\n */\n get b() {\n return this._outputs[4];\n }\n /**\n * Gets the a output component\n */\n get a() {\n return this._outputs[5];\n }\n /**\n * Gets the level output component\n */\n get level() {\n return this._outputs[6];\n }\n get target() {\n if (this._fragmentOnly) {\n return NodeMaterialBlockTargets.Fragment;\n }\n // TextureBlock has a special optimizations for uvs that come from the vertex shaders as they can be packed into a single varyings.\n // But we need to detect uvs coming from fragment then\n if (!this.uv.isConnected) {\n return NodeMaterialBlockTargets.VertexAndFragment;\n }\n if (this.uv.sourceBlock.isInput) {\n return NodeMaterialBlockTargets.VertexAndFragment;\n }\n let parent = this.uv.connectedPoint;\n while (parent) {\n if (parent.target === NodeMaterialBlockTargets.Fragment) {\n return NodeMaterialBlockTargets.Fragment;\n }\n if (parent.target === NodeMaterialBlockTargets.Vertex) {\n return NodeMaterialBlockTargets.VertexAndFragment;\n }\n if (parent.target === NodeMaterialBlockTargets.Neutral || parent.target === NodeMaterialBlockTargets.VertexAndFragment) {\n const parentBlock = parent.ownerBlock;\n if (parentBlock.target === NodeMaterialBlockTargets.Fragment) {\n return NodeMaterialBlockTargets.Fragment;\n }\n parent = null;\n for (const input of parentBlock.inputs) {\n if (input.connectedPoint) {\n parent = input.connectedPoint;\n break;\n }\n }\n }\n }\n return NodeMaterialBlockTargets.VertexAndFragment;\n }\n set target(value) { }\n autoConfigure(material) {\n if (!this.uv.isConnected) {\n if (material.mode === NodeMaterialModes.PostProcess) {\n const uvInput = material.getBlockByPredicate((b) => b.name === \"uv\");\n if (uvInput) {\n uvInput.connectTo(this);\n }\n }\n else {\n const attributeName = material.mode === NodeMaterialModes.Particle ? \"particle_uv\" : \"uv\";\n let uvInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === attributeName);\n if (!uvInput) {\n uvInput = new InputBlock(\"uv\");\n uvInput.setAsAttribute(attributeName);\n }\n uvInput.output.connectTo(this.uv);\n }\n }\n }\n initializeDefines(mesh, nodeMaterial, defines) {\n if (!defines._areTexturesDirty) {\n return;\n }\n if (this._mainUVDefineName !== undefined) {\n defines.setValue(this._mainUVDefineName, false, true);\n }\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n if (!defines._areTexturesDirty) {\n return;\n }\n if (!this.texture || !this.texture.getTextureMatrix) {\n if (this._isMixed) {\n defines.setValue(this._defineName, false, true);\n defines.setValue(this._mainUVDefineName, true, true);\n }\n return;\n }\n const toGamma = this.convertToGammaSpace && this.texture && !this.texture.gammaSpace;\n const toLinear = this.convertToLinearSpace && this.texture && this.texture.gammaSpace;\n // Not a bug... Name defines the texture space not the required conversion\n defines.setValue(this._linearDefineName, toGamma, true);\n defines.setValue(this._gammaDefineName, toLinear, true);\n if (this._isMixed) {\n if (!this.texture.getTextureMatrix().isIdentityAs3x2()) {\n defines.setValue(this._defineName, true);\n if (defines[this._mainUVDefineName] == undefined) {\n defines.setValue(this._mainUVDefineName, false, true);\n }\n }\n else {\n defines.setValue(this._defineName, false, true);\n defines.setValue(this._mainUVDefineName, true, true);\n }\n }\n }\n isReady() {\n if (this.texture && !this.texture.isReadyOrNotBlocking()) {\n return false;\n }\n return true;\n }\n bind(effect) {\n if (!this.texture) {\n return;\n }\n if (this._isMixed) {\n effect.setFloat(this._textureInfoName, this.texture.level);\n effect.setMatrix(this._textureTransformName, this.texture.getTextureMatrix());\n }\n if (!this._imageSource) {\n effect.setTexture(this._samplerName, this.texture);\n }\n }\n get _isMixed() {\n return this.target !== NodeMaterialBlockTargets.Fragment;\n }\n _injectVertexCode(state) {\n const uvInput = this.uv;\n // Inject code in vertex\n this._defineName = state._getFreeDefineName(\"UVTRANSFORM\");\n this._mainUVDefineName = \"VMAIN\" + uvInput.associatedVariableName.toUpperCase();\n this._mainUVName = \"vMain\" + uvInput.associatedVariableName;\n this._transformedUVName = state._getFreeVariableName(\"transformedUV\");\n this._textureTransformName = state._getFreeVariableName(\"textureTransform\");\n this._textureInfoName = state._getFreeVariableName(\"textureInfoName\");\n this.level.associatedVariableName = this._textureInfoName;\n state._emitVaryingFromString(this._transformedUVName, \"vec2\", this._defineName);\n state._emitVaryingFromString(this._mainUVName, \"vec2\", this._mainUVDefineName);\n state._emitUniformFromString(this._textureTransformName, \"mat4\", this._defineName);\n state.compilationString += `#ifdef ${this._defineName}\\r\\n`;\n state.compilationString += `${this._transformedUVName} = vec2(${this._textureTransformName} * vec4(${uvInput.associatedVariableName}.xy, 1.0, 0.0));\\r\\n`;\n state.compilationString += `#elif defined(${this._mainUVDefineName})\\r\\n`;\n state.compilationString += `${this._mainUVName} = ${uvInput.associatedVariableName}.xy;\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n if (!this._outputs.some((o) => o.isConnectedInVertexShader)) {\n return;\n }\n this._writeTextureRead(state, true);\n for (const output of this._outputs) {\n if (output.hasEndpoints && output.name !== \"level\") {\n this._writeOutput(state, output, output.name, true);\n }\n }\n }\n _getUVW(uvName) {\n var _a, _b, _c;\n let coords = uvName;\n const is2DArrayTexture = (_c = (_b = (_a = this._texture) === null || _a === void 0 ? void 0 : _a._texture) === null || _b === void 0 ? void 0 : _b.is2DArray) !== null && _c !== void 0 ? _c : false;\n if (is2DArrayTexture) {\n const layerValue = this.layer.isConnected ? this.layer.associatedVariableName : \"0\";\n coords = `vec3(${uvName}, ${layerValue})`;\n }\n return coords;\n }\n get _samplerFunc() {\n return this.lod.isConnected ? \"texture2DLodEXT\" : \"texture2D\";\n }\n get _samplerLodSuffix() {\n return this.lod.isConnected ? `, ${this.lod.associatedVariableName}` : \"\";\n }\n _generateTextureLookup(state) {\n const samplerName = this.samplerName;\n state.compilationString += `#ifdef ${this._defineName}\\r\\n`;\n state.compilationString += `vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${samplerName}, ${this._getUVW(this._transformedUVName)}${this._samplerLodSuffix});\\r\\n`;\n state.compilationString += `#elif defined(${this._mainUVDefineName})\\r\\n`;\n state.compilationString += `vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${samplerName}, ${this._getUVW(this._mainUVName ? this._mainUVName : this.uv.associatedVariableName)}${this._samplerLodSuffix});\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n }\n _writeTextureRead(state, vertexMode = false) {\n const uvInput = this.uv;\n if (vertexMode) {\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n return;\n }\n this._generateTextureLookup(state);\n return;\n }\n if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {\n state.compilationString += `vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${this.samplerName}, ${this._getUVW(uvInput.associatedVariableName)}${this._samplerLodSuffix});\\r\\n`;\n return;\n }\n this._generateTextureLookup(state);\n }\n _generateConversionCode(state, output, swizzle) {\n if (swizzle !== \"a\") {\n // no conversion if the output is \"a\" (alpha)\n if (!this.texture || !this.texture.gammaSpace) {\n state.compilationString += `#ifdef ${this._linearDefineName}\r\n ${output.associatedVariableName} = toGammaSpace(${output.associatedVariableName});\r\n #endif\r\n `;\n }\n state.compilationString += `#ifdef ${this._gammaDefineName}\r\n ${output.associatedVariableName} = toLinearSpace(${output.associatedVariableName});\r\n #endif\r\n `;\n }\n }\n _writeOutput(state, output, swizzle, vertexMode = false) {\n if (vertexMode) {\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n return;\n }\n state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\\r\\n`;\n this._generateConversionCode(state, output, swizzle);\n return;\n }\n if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {\n state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\\r\\n`;\n this._generateConversionCode(state, output, swizzle);\n return;\n }\n let complement = \"\";\n if (!this.disableLevelMultiplication) {\n complement = ` * ${this._textureInfoName}`;\n }\n state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle}${complement};\\r\\n`;\n this._generateConversionCode(state, output, swizzle);\n }\n _buildBlock(state) {\n var _a, _b, _c, _d;\n super._buildBlock(state);\n if (this.source.isConnected) {\n this._imageSource = this.source.connectedPoint.ownerBlock;\n }\n else {\n this._imageSource = null;\n }\n if (state.target === NodeMaterialBlockTargets.Vertex || this._fragmentOnly || state.target === NodeMaterialBlockTargets.Fragment) {\n this._tempTextureRead = state._getFreeVariableName(\"tempTextureRead\");\n this._linearDefineName = state._getFreeDefineName(\"ISLINEAR\");\n this._gammaDefineName = state._getFreeDefineName(\"ISGAMMA\");\n }\n if ((!this._isMixed && state.target === NodeMaterialBlockTargets.Fragment) || (this._isMixed && state.target === NodeMaterialBlockTargets.Vertex)) {\n if (!this._imageSource) {\n this._samplerName = state._getFreeVariableName(this.name + \"Sampler\");\n if ((_b = (_a = this._texture) === null || _a === void 0 ? void 0 : _a._texture) === null || _b === void 0 ? void 0 : _b.is2DArray) {\n state._emit2DArraySampler(this._samplerName);\n }\n else {\n state._emit2DSampler(this._samplerName);\n }\n }\n // Declarations\n state.sharedData.blockingBlocks.push(this);\n state.sharedData.textureBlocks.push(this);\n state.sharedData.blocksWithDefines.push(this);\n state.sharedData.bindableBlocks.push(this);\n }\n if (state.target !== NodeMaterialBlockTargets.Fragment) {\n // Vertex\n this._injectVertexCode(state);\n return;\n }\n // Fragment\n if (!this._outputs.some((o) => o.isConnectedInFragmentShader)) {\n return;\n }\n if (this._isMixed && !this._imageSource) {\n // Reexport the sampler\n if ((_d = (_c = this._texture) === null || _c === void 0 ? void 0 : _c._texture) === null || _d === void 0 ? void 0 : _d.is2DArray) {\n state._emit2DArraySampler(this._samplerName);\n }\n else {\n state._emit2DSampler(this._samplerName);\n }\n }\n const comments = `//${this.name}`;\n state._emitFunctionFromInclude(\"helperFunctions\", comments);\n if (this._isMixed) {\n state._emitUniformFromString(this._textureInfoName, \"float\");\n }\n this._writeTextureRead(state);\n for (const output of this._outputs) {\n if (output.hasEndpoints && output.name !== \"level\") {\n this._writeOutput(state, output, output.name);\n }\n }\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n codeString += `${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\\r\\n`;\n codeString += `${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\\r\\n`;\n codeString += `${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\\r\\n`;\n if (!this.texture) {\n return codeString;\n }\n codeString += `${this._codeVariableName}.texture = new BABYLON.Texture(\"${this.texture.name}\", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\\r\\n`;\n codeString += `${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.convertToGammaSpace = this.convertToGammaSpace;\n serializationObject.convertToLinearSpace = this.convertToLinearSpace;\n serializationObject.fragmentOnly = this._fragmentOnly;\n serializationObject.disableLevelMultiplication = this.disableLevelMultiplication;\n if (!this.hasImageSource && this.texture && !this.texture.isRenderTarget && this.texture.getClassName() !== \"VideoTexture\") {\n serializationObject.texture = this.texture.serialize();\n }\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.convertToGammaSpace = serializationObject.convertToGammaSpace;\n this.convertToLinearSpace = !!serializationObject.convertToLinearSpace;\n this._fragmentOnly = !!serializationObject.fragmentOnly;\n this.disableLevelMultiplication = !!serializationObject.disableLevelMultiplication;\n if (serializationObject.texture && !NodeMaterial.IgnoreTexturesAtLoadTime && serializationObject.texture.url !== undefined) {\n rootUrl = serializationObject.texture.url.indexOf(\"data:\") === 0 ? \"\" : rootUrl;\n this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl);\n }\n }\n}\nRegisterClass(\"BABYLON.TextureBlock\", TextureBlock);\n//# sourceMappingURL=textureBlock.js.map","import { __decorate } from \"../../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { NodeMaterial } from \"../../nodeMaterial.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { NodeMaterialSystemValues } from \"../../Enums/nodeMaterialSystemValues.js\";\n\nimport \"../../../../Shaders/ShadersInclude/reflectionFunction.js\";\nimport { CubeTexture } from \"../../../Textures/cubeTexture.js\";\nimport { Texture } from \"../../../Textures/texture.js\";\nimport { EngineStore } from \"../../../../Engines/engineStore.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../../nodeMaterialDecorator.js\";\n/**\n * Base block used to read a reflection texture from a sampler\n */\nexport class ReflectionTextureBaseBlock extends NodeMaterialBlock {\n /**\n * Gets or sets the texture associated with the node\n */\n get texture() {\n return this._texture;\n }\n set texture(texture) {\n var _a;\n if (this._texture === texture) {\n return;\n }\n const scene = (_a = texture === null || texture === void 0 ? void 0 : texture.getScene()) !== null && _a !== void 0 ? _a : EngineStore.LastCreatedScene;\n if (!texture && scene) {\n scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(this._texture);\n });\n }\n this._texture = texture;\n if (texture && scene) {\n scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(texture);\n });\n }\n }\n static _OnGenerateOnlyFragmentCodeChanged(block, _propertyName) {\n const that = block;\n return that._onGenerateOnlyFragmentCodeChanged();\n }\n _onGenerateOnlyFragmentCodeChanged() {\n this._setTarget();\n return true;\n }\n _setTarget() {\n this._setInitialTarget(this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.VertexAndFragment);\n }\n /**\n * Create a new ReflectionTextureBaseBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.VertexAndFragment);\n /** Indicates that no code should be generated in the vertex shader. Can be useful in some specific circumstances (like when doing ray marching for eg) */\n this.generateOnlyFragmentCode = false;\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ReflectionTextureBaseBlock\";\n }\n _getTexture() {\n return this.texture;\n }\n autoConfigure(material) {\n if (!this.position.isConnected) {\n let positionInput = material.getInputBlockByPredicate((b) => b.isAttribute && b.name === \"position\");\n if (!positionInput) {\n positionInput = new InputBlock(\"position\");\n positionInput.setAsAttribute();\n }\n positionInput.output.connectTo(this.position);\n }\n if (!this.world.isConnected) {\n let worldInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.World);\n if (!worldInput) {\n worldInput = new InputBlock(\"world\");\n worldInput.setAsSystemValue(NodeMaterialSystemValues.World);\n }\n worldInput.output.connectTo(this.world);\n }\n if (this.view && !this.view.isConnected) {\n let viewInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.View);\n if (!viewInput) {\n viewInput = new InputBlock(\"view\");\n viewInput.setAsSystemValue(NodeMaterialSystemValues.View);\n }\n viewInput.output.connectTo(this.view);\n }\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n if (!defines._areTexturesDirty) {\n return;\n }\n const texture = this._getTexture();\n if (!texture || !texture.getTextureMatrix) {\n return;\n }\n defines.setValue(this._define3DName, texture.isCube, true);\n defines.setValue(this._defineLocalCubicName, texture.boundingBoxSize ? true : false, true);\n defines.setValue(this._defineExplicitName, texture.coordinatesMode === 0, true);\n defines.setValue(this._defineSkyboxName, texture.coordinatesMode === 5, true);\n defines.setValue(this._defineCubicName, texture.coordinatesMode === 3 || texture.coordinatesMode === 6, true);\n defines.setValue(\"INVERTCUBICMAP\", texture.coordinatesMode === 6, true);\n defines.setValue(this._defineSphericalName, texture.coordinatesMode === 1, true);\n defines.setValue(this._definePlanarName, texture.coordinatesMode === 2, true);\n defines.setValue(this._defineProjectionName, texture.coordinatesMode === 4, true);\n defines.setValue(this._defineEquirectangularName, texture.coordinatesMode === 7, true);\n defines.setValue(this._defineEquirectangularFixedName, texture.coordinatesMode === 8, true);\n defines.setValue(this._defineMirroredEquirectangularFixedName, texture.coordinatesMode === 9, true);\n }\n isReady() {\n const texture = this._getTexture();\n if (texture && !texture.isReadyOrNotBlocking()) {\n return false;\n }\n return true;\n }\n bind(effect, nodeMaterial, mesh) {\n const texture = this._getTexture();\n if (!mesh || !texture) {\n return;\n }\n effect.setMatrix(this._reflectionMatrixName, texture.getReflectionTextureMatrix());\n if (texture.isCube) {\n effect.setTexture(this._cubeSamplerName, texture);\n }\n else {\n effect.setTexture(this._2DSamplerName, texture);\n }\n if (texture.boundingBoxSize) {\n const cubeTexture = texture;\n effect.setVector3(this._reflectionPositionName, cubeTexture.boundingBoxPosition);\n effect.setVector3(this._reflectionSizeName, cubeTexture.boundingBoxSize);\n }\n }\n /**\n * Gets the code to inject in the vertex shader\n * @param state current state of the node material building\n * @returns the shader code\n */\n handleVertexSide(state) {\n if (this.generateOnlyFragmentCode && state.target === NodeMaterialBlockTargets.Vertex) {\n return \"\";\n }\n this._define3DName = state._getFreeDefineName(\"REFLECTIONMAP_3D\");\n this._defineCubicName = state._getFreeDefineName(\"REFLECTIONMAP_CUBIC\");\n this._defineSphericalName = state._getFreeDefineName(\"REFLECTIONMAP_SPHERICAL\");\n this._definePlanarName = state._getFreeDefineName(\"REFLECTIONMAP_PLANAR\");\n this._defineProjectionName = state._getFreeDefineName(\"REFLECTIONMAP_PROJECTION\");\n this._defineExplicitName = state._getFreeDefineName(\"REFLECTIONMAP_EXPLICIT\");\n this._defineEquirectangularName = state._getFreeDefineName(\"REFLECTIONMAP_EQUIRECTANGULAR\");\n this._defineLocalCubicName = state._getFreeDefineName(\"USE_LOCAL_REFLECTIONMAP_CUBIC\");\n this._defineMirroredEquirectangularFixedName = state._getFreeDefineName(\"REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\");\n this._defineEquirectangularFixedName = state._getFreeDefineName(\"REFLECTIONMAP_EQUIRECTANGULAR_FIXED\");\n this._defineSkyboxName = state._getFreeDefineName(\"REFLECTIONMAP_SKYBOX\");\n this._defineOppositeZ = state._getFreeDefineName(\"REFLECTIONMAP_OPPOSITEZ\");\n this._reflectionMatrixName = state._getFreeVariableName(\"reflectionMatrix\");\n state._emitUniformFromString(this._reflectionMatrixName, \"mat4\");\n let code = \"\";\n this._worldPositionNameInFragmentOnlyMode = state._getFreeVariableName(\"worldPosition\");\n const worldPosVaryingName = this.generateOnlyFragmentCode ? this._worldPositionNameInFragmentOnlyMode : \"v_\" + this.worldPosition.associatedVariableName;\n if (this.generateOnlyFragmentCode || state._emitVaryingFromString(worldPosVaryingName, \"vec4\")) {\n code += `${this.generateOnlyFragmentCode ? \"vec4 \" : \"\"}${worldPosVaryingName} = ${this.worldPosition.associatedVariableName};\\r\\n`;\n }\n this._positionUVWName = state._getFreeVariableName(\"positionUVW\");\n this._directionWName = state._getFreeVariableName(\"directionW\");\n if (this.generateOnlyFragmentCode || state._emitVaryingFromString(this._positionUVWName, \"vec3\", this._defineSkyboxName)) {\n code += `#ifdef ${this._defineSkyboxName}\\r\\n`;\n code += `${this.generateOnlyFragmentCode ? \"vec3 \" : \"\"}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz;\\r\\n`;\n code += `#endif\\r\\n`;\n }\n if (this.generateOnlyFragmentCode ||\n state._emitVaryingFromString(this._directionWName, \"vec3\", `defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`)) {\n code += `#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})\\r\\n`;\n code += `${this.generateOnlyFragmentCode ? \"vec3 \" : \"\"}${this._directionWName} = normalize(vec3(${this.world.associatedVariableName} * vec4(${this.position.associatedVariableName}.xyz, 0.0)));\\r\\n`;\n code += `#endif\\r\\n`;\n }\n return code;\n }\n /**\n * Handles the inits for the fragment code path\n * @param state node material build state\n */\n handleFragmentSideInits(state) {\n state.sharedData.blockingBlocks.push(this);\n state.sharedData.textureBlocks.push(this);\n // Samplers\n this._cubeSamplerName = state._getFreeVariableName(this.name + \"CubeSampler\");\n state.samplers.push(this._cubeSamplerName);\n this._2DSamplerName = state._getFreeVariableName(this.name + \"2DSampler\");\n state.samplers.push(this._2DSamplerName);\n state._samplerDeclaration += `#ifdef ${this._define3DName}\\r\\n`;\n state._samplerDeclaration += `uniform samplerCube ${this._cubeSamplerName};\\r\\n`;\n state._samplerDeclaration += `#else\\r\\n`;\n state._samplerDeclaration += `uniform sampler2D ${this._2DSamplerName};\\r\\n`;\n state._samplerDeclaration += `#endif\\r\\n`;\n // Fragment\n state.sharedData.blocksWithDefines.push(this);\n state.sharedData.bindableBlocks.push(this);\n const comments = `//${this.name}`;\n state._emitFunction(\"ReciprocalPI\", \"#define RECIPROCAL_PI2 0.15915494\", \"\");\n state._emitFunctionFromInclude(\"helperFunctions\", comments);\n state._emitFunctionFromInclude(\"reflectionFunction\", comments, {\n replaceStrings: [{ search: /vec3 computeReflectionCoords/g, replace: \"void DUMMYFUNC\" }],\n });\n this._reflectionColorName = state._getFreeVariableName(\"reflectionColor\");\n this._reflectionVectorName = state._getFreeVariableName(\"reflectionUVW\");\n this._reflectionCoordsName = state._getFreeVariableName(\"reflectionCoords\");\n this._reflectionPositionName = state._getFreeVariableName(\"vReflectionPosition\");\n state._emitUniformFromString(this._reflectionPositionName, \"vec3\");\n this._reflectionSizeName = state._getFreeVariableName(\"vReflectionPosition\");\n state._emitUniformFromString(this._reflectionSizeName, \"vec3\");\n }\n /**\n * Generates the reflection coords code for the fragment code path\n * @param worldNormalVarName name of the world normal variable\n * @param worldPos name of the world position variable. If not provided, will use the world position connected to this block\n * @param onlyReflectionVector if true, generates code only for the reflection vector computation, not for the reflection coordinates\n * @param doNotEmitInvertZ if true, does not emit the invertZ code\n * @returns the shader code\n */\n handleFragmentSideCodeReflectionCoords(worldNormalVarName, worldPos, onlyReflectionVector = false, doNotEmitInvertZ = false) {\n if (!worldPos) {\n worldPos = this.generateOnlyFragmentCode ? this._worldPositionNameInFragmentOnlyMode : `v_${this.worldPosition.associatedVariableName}`;\n }\n const reflectionMatrix = this._reflectionMatrixName;\n const direction = `normalize(${this._directionWName})`;\n const positionUVW = `${this._positionUVWName}`;\n const vEyePosition = `${this.cameraPosition.associatedVariableName}`;\n const view = `${this.view.associatedVariableName}`;\n worldNormalVarName += \".xyz\";\n let code = `\r\n #ifdef ${this._defineMirroredEquirectangularFixedName}\r\n vec3 ${this._reflectionVectorName} = computeMirroredFixedEquirectangularCoords(${worldPos}, ${worldNormalVarName}, ${direction});\r\n #endif\r\n\r\n #ifdef ${this._defineEquirectangularFixedName}\r\n vec3 ${this._reflectionVectorName} = computeFixedEquirectangularCoords(${worldPos}, ${worldNormalVarName}, ${direction});\r\n #endif\r\n\r\n #ifdef ${this._defineEquirectangularName}\r\n vec3 ${this._reflectionVectorName} = computeEquirectangularCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix});\r\n #endif\r\n\r\n #ifdef ${this._defineSphericalName}\r\n vec3 ${this._reflectionVectorName} = computeSphericalCoords(${worldPos}, ${worldNormalVarName}, ${view}, ${reflectionMatrix});\r\n #endif\r\n\r\n #ifdef ${this._definePlanarName}\r\n vec3 ${this._reflectionVectorName} = computePlanarCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix});\r\n #endif\r\n\r\n #ifdef ${this._defineCubicName}\r\n #ifdef ${this._defineLocalCubicName}\r\n vec3 ${this._reflectionVectorName} = computeCubicLocalCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix}, ${this._reflectionSizeName}, ${this._reflectionPositionName});\r\n #else\r\n vec3 ${this._reflectionVectorName} = computeCubicCoords(${worldPos}, ${worldNormalVarName}, ${vEyePosition}.xyz, ${reflectionMatrix});\r\n #endif\r\n #endif\r\n\r\n #ifdef ${this._defineProjectionName}\r\n vec3 ${this._reflectionVectorName} = computeProjectionCoords(${worldPos}, ${view}, ${reflectionMatrix});\r\n #endif\r\n\r\n #ifdef ${this._defineSkyboxName}\r\n vec3 ${this._reflectionVectorName} = computeSkyBoxCoords(${positionUVW}, ${reflectionMatrix});\r\n #endif\r\n\r\n #ifdef ${this._defineExplicitName}\r\n vec3 ${this._reflectionVectorName} = vec3(0, 0, 0);\r\n #endif\\r\\n`;\n if (!doNotEmitInvertZ) {\n code += `#ifdef ${this._defineOppositeZ}\r\n ${this._reflectionVectorName}.z *= -1.0;\r\n #endif\\r\\n`;\n }\n if (!onlyReflectionVector) {\n code += `\r\n #ifdef ${this._define3DName}\r\n vec3 ${this._reflectionCoordsName} = ${this._reflectionVectorName};\r\n #else\r\n vec2 ${this._reflectionCoordsName} = ${this._reflectionVectorName}.xy;\r\n #ifdef ${this._defineProjectionName}\r\n ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z;\r\n #endif\r\n ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y;\r\n #endif\\r\\n`;\n }\n return code;\n }\n /**\n * Generates the reflection color code for the fragment code path\n * @param lodVarName name of the lod variable\n * @param swizzleLookupTexture swizzle to use for the final color variable\n * @returns the shader code\n */\n handleFragmentSideCodeReflectionColor(lodVarName, swizzleLookupTexture = \".rgb\") {\n const colorType = \"vec\" + (swizzleLookupTexture.length === 0 ? \"4\" : swizzleLookupTexture.length - 1);\n let code = `${colorType} ${this._reflectionColorName};\r\n #ifdef ${this._define3DName}\\r\\n`;\n if (lodVarName) {\n code += `${this._reflectionColorName} = textureCubeLodEXT(${this._cubeSamplerName}, ${this._reflectionVectorName}, ${lodVarName})${swizzleLookupTexture};\\r\\n`;\n }\n else {\n code += `${this._reflectionColorName} = textureCube(${this._cubeSamplerName}, ${this._reflectionVectorName})${swizzleLookupTexture};\\r\\n`;\n }\n code += `\r\n #else\\r\\n`;\n if (lodVarName) {\n code += `${this._reflectionColorName} = texture2DLodEXT(${this._2DSamplerName}, ${this._reflectionCoordsName}, ${lodVarName})${swizzleLookupTexture};\\r\\n`;\n }\n else {\n code += `${this._reflectionColorName} = texture2D(${this._2DSamplerName}, ${this._reflectionCoordsName})${swizzleLookupTexture};\\r\\n`;\n }\n code += `#endif\\r\\n`;\n return code;\n }\n /**\n * Generates the code corresponding to the connected output points\n * @param state node material build state\n * @param varName name of the variable to output\n * @returns the shader code\n */\n writeOutputs(state, varName) {\n let code = \"\";\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n for (const output of this._outputs) {\n if (output.hasEndpoints) {\n code += `${this._declareOutput(output, state)} = ${varName}.${output.name};\\r\\n`;\n }\n }\n }\n return code;\n }\n _buildBlock(state) {\n super._buildBlock(state);\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n if (!this.texture) {\n return codeString;\n }\n if (this.texture.isCube) {\n const forcedExtension = this.texture.forcedExtension;\n codeString += `${this._codeVariableName}.texture = new BABYLON.CubeTexture(\"${this.texture.name}\", undefined, undefined, ${this.texture.noMipmap}, null, undefined, undefined, undefined, ${this.texture._prefiltered}, ${forcedExtension ? '\"' + forcedExtension + '\"' : \"null\"});\\r\\n`;\n }\n else {\n codeString += `${this._codeVariableName}.texture = new BABYLON.Texture(\"${this.texture.name}\", null);\\r\\n`;\n }\n codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n if (this.texture && !this.texture.isRenderTarget) {\n serializationObject.texture = this.texture.serialize();\n }\n serializationObject.generateOnlyFragmentCode = this.generateOnlyFragmentCode;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n if (serializationObject.texture && !NodeMaterial.IgnoreTexturesAtLoadTime) {\n rootUrl = serializationObject.texture.url.indexOf(\"data:\") === 0 ? \"\" : rootUrl;\n if (serializationObject.texture.isCube) {\n this.texture = CubeTexture.Parse(serializationObject.texture, scene, rootUrl);\n }\n else {\n this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl);\n }\n }\n this.generateOnlyFragmentCode = serializationObject.generateOnlyFragmentCode;\n this._setTarget();\n }\n}\n__decorate([\n editableInPropertyPage(\"Generate only fragment code\", PropertyTypeForEdition.Boolean, \"ADVANCED\", {\n notifiers: { rebuild: true, update: true, onValidation: ReflectionTextureBaseBlock._OnGenerateOnlyFragmentCodeChanged },\n })\n], ReflectionTextureBaseBlock.prototype, \"generateOnlyFragmentCode\", void 0);\nRegisterClass(\"BABYLON.ReflectionTextureBaseBlock\", ReflectionTextureBaseBlock);\n//# sourceMappingURL=reflectionTextureBaseBlock.js.map","import { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { NodeMaterialSystemValues } from \"../../Enums/nodeMaterialSystemValues.js\";\nimport { ReflectionTextureBaseBlock } from \"./reflectionTextureBaseBlock.js\";\n/**\n * Block used to read a reflection texture from a sampler\n */\nexport class ReflectionTextureBlock extends ReflectionTextureBaseBlock {\n _onGenerateOnlyFragmentCodeChanged() {\n if (this.position.isConnected) {\n this.generateOnlyFragmentCode = !this.generateOnlyFragmentCode;\n console.error(\"The position input must not be connected to be able to switch!\");\n return false;\n }\n if (this.worldPosition.isConnected) {\n this.generateOnlyFragmentCode = !this.generateOnlyFragmentCode;\n console.error(\"The worldPosition input must not be connected to be able to switch!\");\n return false;\n }\n this._setTarget();\n return true;\n }\n _setTarget() {\n super._setTarget();\n this.getInputByName(\"position\").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex;\n this.getInputByName(\"worldPosition\").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex;\n }\n /**\n * Create a new ReflectionTextureBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name);\n this.registerInput(\"position\", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.Vertex);\n this.registerInput(\"worldPosition\", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex);\n this.registerInput(\"worldNormal\", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Fragment); // Flagging as fragment as the normal can be changed by fragment code\n this.registerInput(\"world\", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Vertex);\n this.registerInput(\"cameraPosition\", NodeMaterialBlockConnectionPointTypes.Vector3, false, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"view\", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"rgb\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"rgba\", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"r\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"g\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"b\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"a\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ReflectionTextureBlock\";\n }\n /**\n * Gets the world position input component\n */\n get position() {\n return this._inputs[0];\n }\n /**\n * Gets the world position input component\n */\n get worldPosition() {\n return this._inputs[1];\n }\n /**\n * Gets the world normal input component\n */\n get worldNormal() {\n return this._inputs[2];\n }\n /**\n * Gets the world input component\n */\n get world() {\n return this._inputs[3];\n }\n /**\n * Gets the camera (or eye) position component\n */\n get cameraPosition() {\n return this._inputs[4];\n }\n /**\n * Gets the view input component\n */\n get view() {\n return this._inputs[5];\n }\n /**\n * Gets the rgb output component\n */\n get rgb() {\n return this._outputs[0];\n }\n /**\n * Gets the rgba output component\n */\n get rgba() {\n return this._outputs[1];\n }\n /**\n * Gets the r output component\n */\n get r() {\n return this._outputs[2];\n }\n /**\n * Gets the g output component\n */\n get g() {\n return this._outputs[3];\n }\n /**\n * Gets the b output component\n */\n get b() {\n return this._outputs[4];\n }\n /**\n * Gets the a output component\n */\n get a() {\n return this._outputs[5];\n }\n autoConfigure(material) {\n super.autoConfigure(material);\n if (!this.cameraPosition.isConnected) {\n let cameraPositionInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.CameraPosition);\n if (!cameraPositionInput) {\n cameraPositionInput = new InputBlock(\"cameraPosition\");\n cameraPositionInput.setAsSystemValue(NodeMaterialSystemValues.CameraPosition);\n }\n cameraPositionInput.output.connectTo(this.cameraPosition);\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (!this.texture) {\n state.compilationString += this.writeOutputs(state, \"vec4(0.)\");\n return this;\n }\n if (state.target !== NodeMaterialBlockTargets.Fragment) {\n state.compilationString += this.handleVertexSide(state);\n return this;\n }\n if (this.generateOnlyFragmentCode) {\n state.compilationString += this.handleVertexSide(state);\n }\n this.handleFragmentSideInits(state);\n const normalWUnit = state._getFreeVariableName(\"normalWUnit\");\n state.compilationString += `vec4 ${normalWUnit} = normalize(${this.worldNormal.associatedVariableName});\\r\\n`;\n state.compilationString += this.handleFragmentSideCodeReflectionCoords(normalWUnit);\n state.compilationString += this.handleFragmentSideCodeReflectionColor(undefined, \"\");\n state.compilationString += this.writeOutputs(state, this._reflectionColorName);\n return this;\n }\n}\nRegisterClass(\"BABYLON.ReflectionTextureBlock\", ReflectionTextureBlock);\n//# sourceMappingURL=reflectionTextureBlock.js.map","import { __decorate } from \"../../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../../nodeMaterialDecorator.js\";\n/**\n * Block used to retrieve the depth (zbuffer) of the scene\n * @since 5.0.0\n */\nexport class SceneDepthBlock extends NodeMaterialBlock {\n /**\n * Create a new SceneDepthBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.VertexAndFragment);\n /**\n * Defines if the depth renderer should be setup in non linear mode\n */\n this.useNonLinearDepth = false;\n /**\n * Defines if the depth renderer should be setup in camera space Z mode (if set, useNonLinearDepth has no effect)\n */\n this.storeCameraSpaceZ = false;\n /**\n * Defines if the depth renderer should be setup in full 32 bits float mode\n */\n this.force32itsFloat = false;\n this._isUnique = true;\n this.registerInput(\"uv\", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.VertexAndFragment);\n this.registerOutput(\"depth\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector2 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);\n this._inputs[0]._prioritizeVertex = false;\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"SceneDepthBlock\";\n }\n /**\n * Gets the uv input component\n */\n get uv() {\n return this._inputs[0];\n }\n /**\n * Gets the depth output component\n */\n get depth() {\n return this._outputs[0];\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"textureSampler\");\n }\n get target() {\n if (!this.uv.isConnected) {\n return NodeMaterialBlockTargets.VertexAndFragment;\n }\n if (this.uv.sourceBlock.isInput) {\n return NodeMaterialBlockTargets.VertexAndFragment;\n }\n return NodeMaterialBlockTargets.Fragment;\n }\n _getTexture(scene) {\n const depthRenderer = scene.enableDepthRenderer(undefined, this.useNonLinearDepth, this.force32itsFloat, undefined, this.storeCameraSpaceZ);\n return depthRenderer.getDepthMap();\n }\n bind(effect, nodeMaterial) {\n const texture = this._getTexture(nodeMaterial.getScene());\n effect.setTexture(this._samplerName, texture);\n }\n _injectVertexCode(state) {\n const uvInput = this.uv;\n if (uvInput.connectedPoint.ownerBlock.isInput) {\n const uvInputOwnerBlock = uvInput.connectedPoint.ownerBlock;\n if (!uvInputOwnerBlock.isAttribute) {\n state._emitUniformFromString(uvInput.associatedVariableName, \"vec\" + (uvInput.type === NodeMaterialBlockConnectionPointTypes.Vector3 ? \"3\" : uvInput.type === NodeMaterialBlockConnectionPointTypes.Vector4 ? \"4\" : \"2\"));\n }\n }\n this._mainUVName = \"vMain\" + uvInput.associatedVariableName;\n state._emitVaryingFromString(this._mainUVName, \"vec2\");\n state.compilationString += `${this._mainUVName} = ${uvInput.associatedVariableName}.xy;\\r\\n`;\n if (!this._outputs.some((o) => o.isConnectedInVertexShader)) {\n return;\n }\n this._writeTextureRead(state, true);\n for (const output of this._outputs) {\n if (output.hasEndpoints) {\n this._writeOutput(state, output, \"r\", true);\n }\n }\n }\n _writeTextureRead(state, vertexMode = false) {\n const uvInput = this.uv;\n if (vertexMode) {\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n return;\n }\n state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${uvInput.associatedVariableName}.xy);\\r\\n`;\n return;\n }\n if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {\n state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${uvInput.associatedVariableName}.xy);\\r\\n`;\n return;\n }\n state.compilationString += `vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName});\\r\\n`;\n }\n _writeOutput(state, output, swizzle, vertexMode = false) {\n if (vertexMode) {\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n return;\n }\n state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\\r\\n`;\n return;\n }\n if (this.uv.ownerBlock.target === NodeMaterialBlockTargets.Fragment) {\n state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\\r\\n`;\n return;\n }\n state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle};\\r\\n`;\n }\n _buildBlock(state) {\n super._buildBlock(state);\n this._samplerName = state._getFreeVariableName(this.name + \"Sampler\");\n this._tempTextureRead = state._getFreeVariableName(\"tempTextureRead\");\n if (state.sharedData.bindableBlocks.indexOf(this) < 0) {\n state.sharedData.bindableBlocks.push(this);\n }\n if (state.target !== NodeMaterialBlockTargets.Fragment) {\n // Vertex\n state._emit2DSampler(this._samplerName);\n this._injectVertexCode(state);\n return;\n }\n // Fragment\n if (!this._outputs.some((o) => o.isConnectedInFragmentShader)) {\n return;\n }\n state._emit2DSampler(this._samplerName);\n this._writeTextureRead(state);\n for (const output of this._outputs) {\n if (output.hasEndpoints) {\n this._writeOutput(state, output, \"r\");\n }\n }\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.useNonLinearDepth = this.useNonLinearDepth;\n serializationObject.storeCameraSpaceZ = this.storeCameraSpaceZ;\n serializationObject.force32itsFloat = this.force32itsFloat;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.useNonLinearDepth = serializationObject.useNonLinearDepth;\n this.storeCameraSpaceZ = !!serializationObject.storeCameraSpaceZ;\n this.force32itsFloat = serializationObject.force32itsFloat;\n }\n}\n__decorate([\n editableInPropertyPage(\"Use non linear depth\", PropertyTypeForEdition.Boolean, \"ADVANCED\", {\n notifiers: {\n activatePreviewCommand: true,\n callback: (scene, block) => {\n const sceneDepthBlock = block;\n let retVal = false;\n if (sceneDepthBlock.useNonLinearDepth) {\n sceneDepthBlock.storeCameraSpaceZ = false;\n retVal = true;\n }\n scene.disableDepthRenderer();\n return retVal;\n },\n },\n })\n], SceneDepthBlock.prototype, \"useNonLinearDepth\", void 0);\n__decorate([\n editableInPropertyPage(\"Store Camera space Z\", PropertyTypeForEdition.Boolean, \"ADVANCED\", {\n notifiers: {\n activatePreviewCommand: true,\n callback: (scene, block) => {\n const sceneDepthBlock = block;\n let retVal = false;\n if (sceneDepthBlock.storeCameraSpaceZ) {\n sceneDepthBlock.useNonLinearDepth = false;\n retVal = true;\n }\n scene.disableDepthRenderer();\n return retVal;\n },\n },\n })\n], SceneDepthBlock.prototype, \"storeCameraSpaceZ\", void 0);\n__decorate([\n editableInPropertyPage(\"Force 32 bits float\", PropertyTypeForEdition.Boolean, \"ADVANCED\", {\n notifiers: { activatePreviewCommand: true, callback: (scene) => scene.disableDepthRenderer() },\n })\n], SceneDepthBlock.prototype, \"force32itsFloat\", void 0);\nRegisterClass(\"BABYLON.SceneDepthBlock\", SceneDepthBlock);\n//# sourceMappingURL=sceneDepthBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { bindClipPlane } from \"../../../../Materials/clipPlaneMaterialHelper.js\";\n/**\n * Block used to implement clip planes\n */\nexport class ClipPlanesBlock extends NodeMaterialBlock {\n /**\n * Create a new ClipPlanesBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.VertexAndFragment, true);\n this.registerInput(\"worldPosition\", NodeMaterialBlockConnectionPointTypes.Vector4, false);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ClipPlanesBlock\";\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"vClipPlane\");\n state._excludeVariableName(\"fClipDistance\");\n state._excludeVariableName(\"vClipPlane2\");\n state._excludeVariableName(\"fClipDistance2\");\n state._excludeVariableName(\"vClipPlane3\");\n state._excludeVariableName(\"fClipDistance3\");\n state._excludeVariableName(\"vClipPlane4\");\n state._excludeVariableName(\"fClipDistance4\");\n state._excludeVariableName(\"vClipPlane5\");\n state._excludeVariableName(\"fClipDistance5\");\n state._excludeVariableName(\"vClipPlane6\");\n state._excludeVariableName(\"fClipDistance6\");\n }\n /**\n * Gets the worldPosition input component\n */\n get worldPosition() {\n return this._inputs[0];\n }\n get target() {\n return NodeMaterialBlockTargets.VertexAndFragment;\n }\n set target(value) { }\n prepareDefines(mesh, nodeMaterial, defines) {\n var _a, _b, _c, _d, _e, _f;\n const scene = mesh.getScene();\n const useClipPlane1 = ((_a = nodeMaterial.clipPlane) !== null && _a !== void 0 ? _a : scene.clipPlane) ? true : false;\n const useClipPlane2 = ((_b = nodeMaterial.clipPlane2) !== null && _b !== void 0 ? _b : scene.clipPlane2) ? true : false;\n const useClipPlane3 = ((_c = nodeMaterial.clipPlane3) !== null && _c !== void 0 ? _c : scene.clipPlane3) ? true : false;\n const useClipPlane4 = ((_d = nodeMaterial.clipPlane4) !== null && _d !== void 0 ? _d : scene.clipPlane4) ? true : false;\n const useClipPlane5 = ((_e = nodeMaterial.clipPlane5) !== null && _e !== void 0 ? _e : scene.clipPlane5) ? true : false;\n const useClipPlane6 = ((_f = nodeMaterial.clipPlane6) !== null && _f !== void 0 ? _f : scene.clipPlane6) ? true : false;\n defines.setValue(\"CLIPPLANE\", useClipPlane1, true);\n defines.setValue(\"CLIPPLANE2\", useClipPlane2, true);\n defines.setValue(\"CLIPPLANE3\", useClipPlane3, true);\n defines.setValue(\"CLIPPLANE4\", useClipPlane4, true);\n defines.setValue(\"CLIPPLANE5\", useClipPlane5, true);\n defines.setValue(\"CLIPPLANE6\", useClipPlane6, true);\n }\n bind(effect, nodeMaterial, mesh) {\n if (!mesh) {\n return;\n }\n const scene = mesh.getScene();\n bindClipPlane(effect, nodeMaterial, scene);\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const comments = `//${this.name}`;\n if (state.target !== NodeMaterialBlockTargets.Fragment) {\n // Vertex\n const worldPos = this.worldPosition;\n state._emitFunctionFromInclude(\"clipPlaneVertexDeclaration\", comments, {\n replaceStrings: [{ search: /uniform vec4 vClipPlane\\d*;/g, replace: \"\" }],\n });\n state.compilationString += state._emitCodeFromInclude(\"clipPlaneVertex\", comments, {\n replaceStrings: [{ search: /worldPos/g, replace: worldPos.associatedVariableName }],\n });\n state._emitUniformFromString(\"vClipPlane\", \"vec4\");\n state._emitUniformFromString(\"vClipPlane2\", \"vec4\");\n state._emitUniformFromString(\"vClipPlane3\", \"vec4\");\n state._emitUniformFromString(\"vClipPlane4\", \"vec4\");\n state._emitUniformFromString(\"vClipPlane5\", \"vec4\");\n state._emitUniformFromString(\"vClipPlane6\", \"vec4\");\n return;\n }\n // Fragment\n state.sharedData.bindableBlocks.push(this);\n state.sharedData.blocksWithDefines.push(this);\n state._emitFunctionFromInclude(\"clipPlaneFragmentDeclaration\", comments);\n state.compilationString += state._emitCodeFromInclude(\"clipPlaneFragment\", comments);\n return this;\n }\n}\nRegisterClass(\"BABYLON.ClipPlanesBlock\", ClipPlanesBlock);\n//# sourceMappingURL=clipPlanesBlock.js.map","export * from \"./fogBlock.js\";\nexport * from \"./lightBlock.js\";\nexport * from \"./textureBlock.js\";\nexport * from \"./reflectionTextureBlock.js\";\nexport * from \"./currentScreenBlock.js\";\nexport * from \"./sceneDepthBlock.js\";\nexport * from \"./imageSourceBlock.js\";\nexport * from \"./clipPlanesBlock.js\";\n//# sourceMappingURL=index.js.map","export * from \"./inputBlock.js\";\nexport * from \"./animatedInputBlockTypes.js\";\n//# sourceMappingURL=index.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to add 2 vectors\n */\nexport class AddBlock extends NodeMaterialBlock {\n /**\n * Creates a new AddBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"left\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"right\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._linkConnectionTypes(0, 1);\n this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"AddBlock\";\n }\n /**\n * Gets the left operand input component\n */\n get left() {\n return this._inputs[0];\n }\n /**\n * Gets the right operand input component\n */\n get right() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = ${this.left.associatedVariableName} + ${this.right.associatedVariableName};\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.AddBlock\", AddBlock);\n//# sourceMappingURL=addBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to apply a cross product between 2 vectors\n */\nexport class CrossBlock extends NodeMaterialBlock {\n /**\n * Creates a new CrossBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"left\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"right\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this._linkConnectionTypes(0, 1);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2);\n this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"CrossBlock\";\n }\n /**\n * Gets the left operand input component\n */\n get left() {\n return this._inputs[0];\n }\n /**\n * Gets the right operand input component\n */\n get right() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = cross(${this.left.associatedVariableName}.xyz, ${this.right.associatedVariableName}.xyz);\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.CrossBlock\", CrossBlock);\n//# sourceMappingURL=crossBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../nodeMaterialBlockConnectionPoint.js\";\nimport { ImageSourceBlock } from \"./Dual/imageSourceBlock.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../nodeMaterialConnectionPointCustomObject.js\";\n/**\n * Custom block created from user-defined json\n */\nexport class CustomBlock extends NodeMaterialBlock {\n /**\n * Gets or sets the options for this custom block\n */\n get options() {\n return this._options;\n }\n set options(options) {\n this._deserializeOptions(options);\n }\n /**\n * Creates a new CustomBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"CustomBlock\";\n }\n _buildBlock(state) {\n super._buildBlock(state);\n let code = this._code;\n let functionName = this._options.functionName;\n // Replace the TYPE_XXX placeholders (if any)\n this._inputs.forEach((input) => {\n const rexp = new RegExp(\"\\\\{TYPE_\" + input.name + \"\\\\}\", \"gm\");\n const type = state._getGLType(input.type);\n code = code.replace(rexp, type);\n functionName = functionName.replace(rexp, type);\n });\n this._outputs.forEach((output) => {\n const rexp = new RegExp(\"\\\\{TYPE_\" + output.name + \"\\\\}\", \"gm\");\n const type = state._getGLType(output.type);\n code = code.replace(rexp, type);\n functionName = functionName.replace(rexp, type);\n });\n state._emitFunction(functionName, code, \"\");\n // Declare the output variables\n this._outputs.forEach((output) => {\n state.compilationString += this._declareOutput(output, state) + \";\\r\\n\";\n });\n // Generate the function call\n state.compilationString += functionName + \"(\";\n let hasInput = false;\n this._inputs.forEach((input, index) => {\n var _a, _b, _c;\n if (index > 0) {\n state.compilationString += \", \";\n }\n if (this._inputSamplers && this._inputSamplers.indexOf(input.name) !== -1) {\n state.compilationString += (_c = (_b = (_a = input.connectedPoint) === null || _a === void 0 ? void 0 : _a.ownerBlock) === null || _b === void 0 ? void 0 : _b.samplerName) !== null && _c !== void 0 ? _c : input.associatedVariableName;\n }\n else {\n state.compilationString += input.associatedVariableName;\n }\n hasInput = true;\n });\n this._outputs.forEach((output, index) => {\n if (index > 0 || hasInput) {\n state.compilationString += \", \";\n }\n state.compilationString += output.associatedVariableName;\n });\n state.compilationString += \");\\r\\n\";\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n codeString += `${this._codeVariableName}.options = ${JSON.stringify(this._options)};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.options = this._options;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n this._deserializeOptions(serializationObject.options);\n super._deserialize(serializationObject, scene, rootUrl);\n }\n _deserializeOptions(options) {\n var _a, _b, _c;\n this._options = options;\n this._code = options.code.join(\"\\r\\n\") + \"\\r\\n\";\n this.name = this.name || options.name;\n this.target = NodeMaterialBlockTargets[options.target];\n (_a = options.inParameters) === null || _a === void 0 ? void 0 : _a.forEach((input, index) => {\n const type = NodeMaterialBlockConnectionPointTypes[input.type];\n if (input.type === \"sampler2D\" || input.type === \"samplerCube\") {\n this._inputSamplers = this._inputSamplers || [];\n this._inputSamplers.push(input.name);\n this.registerInput(input.name, NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject(input.name, this, NodeMaterialConnectionPointDirection.Input, ImageSourceBlock, \"ImageSourceBlock\"));\n }\n else {\n this.registerInput(input.name, type);\n }\n Object.defineProperty(this, input.name, {\n get: function () {\n return this._inputs[index];\n },\n enumerable: true,\n configurable: true,\n });\n });\n (_b = options.outParameters) === null || _b === void 0 ? void 0 : _b.forEach((output, index) => {\n this.registerOutput(output.name, NodeMaterialBlockConnectionPointTypes[output.type]);\n Object.defineProperty(this, output.name, {\n get: function () {\n return this._outputs[index];\n },\n enumerable: true,\n configurable: true,\n });\n if (output.type === \"BasedOnInput\") {\n this._outputs[index]._typeConnectionSource = this._findInputByName(output.typeFromInput)[0];\n }\n });\n (_c = options.inLinkedConnectionTypes) === null || _c === void 0 ? void 0 : _c.forEach((connection) => {\n this._linkConnectionTypes(this._findInputByName(connection.input1)[1], this._findInputByName(connection.input2)[1]);\n });\n }\n _findInputByName(name) {\n if (!name) {\n return null;\n }\n for (let i = 0; i < this._inputs.length; i++) {\n if (this._inputs[i].name === name) {\n return [this._inputs[i], i];\n }\n }\n return null;\n }\n}\nRegisterClass(\"BABYLON.CustomBlock\", CustomBlock);\n//# sourceMappingURL=customBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to apply a dot product between 2 vectors\n */\nexport class DotBlock extends NodeMaterialBlock {\n /**\n * Creates a new DotBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"left\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"right\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Float);\n this._linkConnectionTypes(0, 1);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"DotBlock\";\n }\n /**\n * Gets the left operand input component\n */\n get left() {\n return this._inputs[0];\n }\n /**\n * Gets the right operand input component\n */\n get right() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = dot(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.DotBlock\", DotBlock);\n//# sourceMappingURL=dotBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to create a Color3/4 out of individual inputs (one for each component)\n */\nexport class ColorMergerBlock extends NodeMaterialBlock {\n /**\n * Create a new ColorMergerBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n /**\n * Gets or sets the swizzle for r (meaning which component to affect to the output.r)\n */\n this.rSwizzle = \"r\";\n /**\n * Gets or sets the swizzle for g (meaning which component to affect to the output.g)\n */\n this.gSwizzle = \"g\";\n /**\n * Gets or sets the swizzle for b (meaning which component to affect to the output.b)\n */\n this.bSwizzle = \"b\";\n /**\n * Gets or sets the swizzle for a (meaning which component to affect to the output.a)\n */\n this.aSwizzle = \"a\";\n this.registerInput(\"rgb \", NodeMaterialBlockConnectionPointTypes.Color3, true);\n this.registerInput(\"r\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"g\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"b\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"a\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerOutput(\"rgba\", NodeMaterialBlockConnectionPointTypes.Color4);\n this.registerOutput(\"rgb\", NodeMaterialBlockConnectionPointTypes.Color3);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ColorMergerBlock\";\n }\n /**\n * Gets the rgb component (input)\n */\n get rgbIn() {\n return this._inputs[0];\n }\n /**\n * Gets the r component (input)\n */\n get r() {\n return this._inputs[1];\n }\n /**\n * Gets the g component (input)\n */\n get g() {\n return this._inputs[2];\n }\n /**\n * Gets the b component (input)\n */\n get b() {\n return this._inputs[3];\n }\n /**\n * Gets the a component (input)\n */\n get a() {\n return this._inputs[4];\n }\n /**\n * Gets the rgba component (output)\n */\n get rgba() {\n return this._outputs[0];\n }\n /**\n * Gets the rgb component (output)\n */\n get rgbOut() {\n return this._outputs[1];\n }\n /**\n * Gets the rgb component (output)\n * @deprecated Please use rgbOut instead.\n */\n get rgb() {\n return this.rgbOut;\n }\n _inputRename(name) {\n if (name === \"rgb \") {\n return \"rgbIn\";\n }\n return name;\n }\n _buildSwizzle(len) {\n const swizzle = this.rSwizzle + this.gSwizzle + this.bSwizzle + this.aSwizzle;\n return \".\" + swizzle.substr(0, len);\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const rInput = this.r;\n const gInput = this.g;\n const bInput = this.b;\n const aInput = this.a;\n const rgbInput = this.rgbIn;\n const color4Output = this._outputs[0];\n const color3Output = this._outputs[1];\n if (rgbInput.isConnected) {\n if (color4Output.hasEndpoints) {\n state.compilationString +=\n this._declareOutput(color4Output, state) +\n ` = vec4(${rgbInput.associatedVariableName}, ${aInput.isConnected ? this._writeVariable(aInput) : \"0.0\"})${this._buildSwizzle(4)};\\r\\n`;\n }\n if (color3Output.hasEndpoints) {\n state.compilationString += this._declareOutput(color3Output, state) + ` = ${rgbInput.associatedVariableName}${this._buildSwizzle(3)};\\r\\n`;\n }\n }\n else {\n if (color4Output.hasEndpoints) {\n state.compilationString +=\n this._declareOutput(color4Output, state) +\n ` = vec4(${rInput.isConnected ? this._writeVariable(rInput) : \"0.0\"}, ${gInput.isConnected ? this._writeVariable(gInput) : \"0.0\"}, ${bInput.isConnected ? this._writeVariable(bInput) : \"0.0\"}, ${aInput.isConnected ? this._writeVariable(aInput) : \"0.0\"})${this._buildSwizzle(4)};\\r\\n`;\n }\n if (color3Output.hasEndpoints) {\n state.compilationString +=\n this._declareOutput(color3Output, state) +\n ` = vec3(${rInput.isConnected ? this._writeVariable(rInput) : \"0.0\"}, ${gInput.isConnected ? this._writeVariable(gInput) : \"0.0\"}, ${bInput.isConnected ? this._writeVariable(bInput) : \"0.0\"})${this._buildSwizzle(3)};\\r\\n`;\n }\n }\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.rSwizzle = this.rSwizzle;\n serializationObject.gSwizzle = this.gSwizzle;\n serializationObject.bSwizzle = this.bSwizzle;\n serializationObject.aSwizzle = this.aSwizzle;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n var _a, _b, _c, _d;\n super._deserialize(serializationObject, scene, rootUrl);\n this.rSwizzle = (_a = serializationObject.rSwizzle) !== null && _a !== void 0 ? _a : \"r\";\n this.gSwizzle = (_b = serializationObject.gSwizzle) !== null && _b !== void 0 ? _b : \"g\";\n this.bSwizzle = (_c = serializationObject.bSwizzle) !== null && _c !== void 0 ? _c : \"b\";\n this.aSwizzle = (_d = serializationObject.aSwizzle) !== null && _d !== void 0 ? _d : \"a\";\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n codeString += `${this._codeVariableName}.rSwizzle = \"${this.rSwizzle}\";\\r\\n`;\n codeString += `${this._codeVariableName}.gSwizzle = \"${this.gSwizzle}\";\\r\\n`;\n codeString += `${this._codeVariableName}.bSwizzle = \"${this.bSwizzle}\";\\r\\n`;\n codeString += `${this._codeVariableName}.aSwizzle = \"${this.aSwizzle}\";\\r\\n`;\n return codeString;\n }\n}\nRegisterClass(\"BABYLON.ColorMergerBlock\", ColorMergerBlock);\n//# sourceMappingURL=colorMergerBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to expand a Vector3/4 into 4 outputs (one for each component)\n */\nexport class VectorSplitterBlock extends NodeMaterialBlock {\n /**\n * Create a new VectorSplitterBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"xyzw\", NodeMaterialBlockConnectionPointTypes.Vector4, true);\n this.registerInput(\"xyz \", NodeMaterialBlockConnectionPointTypes.Vector3, true);\n this.registerInput(\"xy \", NodeMaterialBlockConnectionPointTypes.Vector2, true);\n this.registerOutput(\"xyz\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerOutput(\"xy\", NodeMaterialBlockConnectionPointTypes.Vector2);\n this.registerOutput(\"zw\", NodeMaterialBlockConnectionPointTypes.Vector2);\n this.registerOutput(\"x\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"y\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"z\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"w\", NodeMaterialBlockConnectionPointTypes.Float);\n this.inputsAreExclusive = true;\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"VectorSplitterBlock\";\n }\n /**\n * Gets the xyzw component (input)\n */\n get xyzw() {\n return this._inputs[0];\n }\n /**\n * Gets the xyz component (input)\n */\n get xyzIn() {\n return this._inputs[1];\n }\n /**\n * Gets the xy component (input)\n */\n get xyIn() {\n return this._inputs[2];\n }\n /**\n * Gets the xyz component (output)\n */\n get xyzOut() {\n return this._outputs[0];\n }\n /**\n * Gets the xy component (output)\n */\n get xyOut() {\n return this._outputs[1];\n }\n /**\n * Gets the zw component (output)\n */\n get zw() {\n return this._outputs[2];\n }\n /**\n * Gets the x component (output)\n */\n get x() {\n return this._outputs[3];\n }\n /**\n * Gets the y component (output)\n */\n get y() {\n return this._outputs[4];\n }\n /**\n * Gets the z component (output)\n */\n get z() {\n return this._outputs[5];\n }\n /**\n * Gets the w component (output)\n */\n get w() {\n return this._outputs[6];\n }\n _inputRename(name) {\n switch (name) {\n case \"xy \":\n return \"xyIn\";\n case \"xyz \":\n return \"xyzIn\";\n default:\n return name;\n }\n }\n _outputRename(name) {\n switch (name) {\n case \"xy\":\n return \"xyOut\";\n case \"xyz\":\n return \"xyzOut\";\n default:\n return name;\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const input = this.xyzw.isConnected ? this.xyzw : this.xyzIn.isConnected ? this.xyzIn : this.xyIn;\n const xyzOutput = this._outputs[0];\n const xyOutput = this._outputs[1];\n const zwOutput = this._outputs[2];\n const xOutput = this._outputs[3];\n const yOutput = this._outputs[4];\n const zOutput = this._outputs[5];\n const wOutput = this._outputs[6];\n if (xyzOutput.hasEndpoints) {\n if (input === this.xyIn) {\n state.compilationString += this._declareOutput(xyzOutput, state) + ` = vec3(${input.associatedVariableName}, 0.0);\\r\\n`;\n }\n else {\n state.compilationString += this._declareOutput(xyzOutput, state) + ` = ${input.associatedVariableName}.xyz;\\r\\n`;\n }\n }\n if (zwOutput.hasEndpoints && this.xyzw.isConnected) {\n state.compilationString += this._declareOutput(zwOutput, state) + ` = ${this.xyzw.associatedVariableName}.zw;\\r\\n`;\n }\n if (xyOutput.hasEndpoints) {\n state.compilationString += this._declareOutput(xyOutput, state) + ` = ${input.associatedVariableName}.xy;\\r\\n`;\n }\n if (xOutput.hasEndpoints) {\n state.compilationString += this._declareOutput(xOutput, state) + ` = ${input.associatedVariableName}.x;\\r\\n`;\n }\n if (yOutput.hasEndpoints) {\n state.compilationString += this._declareOutput(yOutput, state) + ` = ${input.associatedVariableName}.y;\\r\\n`;\n }\n if (zOutput.hasEndpoints) {\n state.compilationString += this._declareOutput(zOutput, state) + ` = ${input.associatedVariableName}.z;\\r\\n`;\n }\n if (wOutput.hasEndpoints) {\n state.compilationString += this._declareOutput(wOutput, state) + ` = ${input.associatedVariableName}.w;\\r\\n`;\n }\n return this;\n }\n}\nRegisterClass(\"BABYLON.VectorSplitterBlock\", VectorSplitterBlock);\n//# sourceMappingURL=vectorSplitterBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to lerp between 2 values\n */\nexport class LerpBlock extends NodeMaterialBlock {\n /**\n * Creates a new LerpBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"left\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"right\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"gradient\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._linkConnectionTypes(0, 1);\n this._linkConnectionTypes(1, 2, true);\n this._inputs[2].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"LerpBlock\";\n }\n /**\n * Gets the left operand input component\n */\n get left() {\n return this._inputs[0];\n }\n /**\n * Gets the right operand input component\n */\n get right() {\n return this._inputs[1];\n }\n /**\n * Gets the gradient operand input component\n */\n get gradient() {\n return this._inputs[2];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString +=\n this._declareOutput(output, state) + ` = mix(${this.left.associatedVariableName} , ${this.right.associatedVariableName}, ${this.gradient.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.LerpBlock\", LerpBlock);\n//# sourceMappingURL=lerpBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to step a value\n */\nexport class StepBlock extends NodeMaterialBlock {\n /**\n * Creates a new StepBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"value\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerInput(\"edge\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"StepBlock\";\n }\n /**\n * Gets the value operand input component\n */\n get value() {\n return this._inputs[0];\n }\n /**\n * Gets the edge operand input component\n */\n get edge() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = step(${this.edge.associatedVariableName}, ${this.value.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.StepBlock\", StepBlock);\n//# sourceMappingURL=stepBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to divide 2 vectors\n */\nexport class DivideBlock extends NodeMaterialBlock {\n /**\n * Creates a new DivideBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"left\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"right\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._linkConnectionTypes(0, 1);\n this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"DivideBlock\";\n }\n /**\n * Gets the left operand input component\n */\n get left() {\n return this._inputs[0];\n }\n /**\n * Gets the right operand input component\n */\n get right() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = ${this.left.associatedVariableName} / ${this.right.associatedVariableName};\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.DivideBlock\", DivideBlock);\n//# sourceMappingURL=divideBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to subtract 2 vectors\n */\nexport class SubtractBlock extends NodeMaterialBlock {\n /**\n * Creates a new SubtractBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"left\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"right\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._linkConnectionTypes(0, 1);\n this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[1].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"SubtractBlock\";\n }\n /**\n * Gets the left operand input component\n */\n get left() {\n return this._inputs[0];\n }\n /**\n * Gets the right operand input component\n */\n get right() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = ${this.left.associatedVariableName} - ${this.right.associatedVariableName};\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.SubtractBlock\", SubtractBlock);\n//# sourceMappingURL=subtractBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to get the opposite (1 - x) of a value\n */\nexport class OneMinusBlock extends NodeMaterialBlock {\n /**\n * Creates a new OneMinusBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._outputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"OneMinusBlock\";\n }\n /**\n * Gets the input component\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = 1. - ${this.input.associatedVariableName};\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.OneMinusBlock\", OneMinusBlock);\nRegisterClass(\"BABYLON.OppositeBlock\", OneMinusBlock); // Backward compatibility\n//# sourceMappingURL=oneMinusBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { NodeMaterialSystemValues } from \"../Enums/nodeMaterialSystemValues.js\";\nimport { InputBlock } from \"./Input/inputBlock.js\";\n/**\n * Block used to get the view direction\n */\nexport class ViewDirectionBlock extends NodeMaterialBlock {\n /**\n * Creates a new ViewDirectionBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"worldPosition\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerInput(\"cameraPosition\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Vector3);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ViewDirectionBlock\";\n }\n /**\n * Gets the world position component\n */\n get worldPosition() {\n return this._inputs[0];\n }\n /**\n * Gets the camera position component\n */\n get cameraPosition() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n autoConfigure(material) {\n if (!this.cameraPosition.isConnected) {\n let cameraPositionInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.CameraPosition);\n if (!cameraPositionInput) {\n cameraPositionInput = new InputBlock(\"cameraPosition\");\n cameraPositionInput.setAsSystemValue(NodeMaterialSystemValues.CameraPosition);\n }\n cameraPositionInput.output.connectTo(this.cameraPosition);\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString +=\n this._declareOutput(output, state) + ` = normalize(${this.cameraPosition.associatedVariableName} - ${this.worldPosition.associatedVariableName}.xyz);\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.ViewDirectionBlock\", ViewDirectionBlock);\n//# sourceMappingURL=viewDirectionBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { InputBlock } from \"./Input/inputBlock.js\";\nimport \"../../../Shaders/ShadersInclude/fresnelFunction.js\";\nimport { ViewDirectionBlock } from \"./viewDirectionBlock.js\";\n/**\n * Block used to compute fresnel value\n */\nexport class FresnelBlock extends NodeMaterialBlock {\n /**\n * Create a new FresnelBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"worldNormal\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerInput(\"viewDirection\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerInput(\"bias\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerInput(\"power\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"fresnel\", NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"FresnelBlock\";\n }\n /**\n * Gets the world normal input component\n */\n get worldNormal() {\n return this._inputs[0];\n }\n /**\n * Gets the view direction input component\n */\n get viewDirection() {\n return this._inputs[1];\n }\n /**\n * Gets the bias input component\n */\n get bias() {\n return this._inputs[2];\n }\n /**\n * Gets the camera (or eye) position component\n */\n get power() {\n return this._inputs[3];\n }\n /**\n * Gets the fresnel output component\n */\n get fresnel() {\n return this._outputs[0];\n }\n autoConfigure(material) {\n if (!this.viewDirection.isConnected) {\n const viewDirectionInput = new ViewDirectionBlock(\"View direction\");\n viewDirectionInput.output.connectTo(this.viewDirection);\n viewDirectionInput.autoConfigure(material);\n }\n if (!this.bias.isConnected) {\n const biasInput = new InputBlock(\"bias\");\n biasInput.value = 0;\n biasInput.output.connectTo(this.bias);\n }\n if (!this.power.isConnected) {\n const powerInput = new InputBlock(\"power\");\n powerInput.value = 1;\n powerInput.output.connectTo(this.power);\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const comments = `//${this.name}`;\n state._emitFunctionFromInclude(\"fresnelFunction\", comments, { removeIfDef: true });\n state.compilationString +=\n this._declareOutput(this.fresnel, state) +\n ` = computeFresnelTerm(${this.viewDirection.associatedVariableName}.xyz, ${this.worldNormal.associatedVariableName}.xyz, ${this.bias.associatedVariableName}, ${this.power.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.FresnelBlock\", FresnelBlock);\n//# sourceMappingURL=fresnelBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to get the max of 2 values\n */\nexport class MaxBlock extends NodeMaterialBlock {\n /**\n * Creates a new MaxBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"left\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"right\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._linkConnectionTypes(0, 1);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"MaxBlock\";\n }\n /**\n * Gets the left operand input component\n */\n get left() {\n return this._inputs[0];\n }\n /**\n * Gets the right operand input component\n */\n get right() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = max(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.MaxBlock\", MaxBlock);\n//# sourceMappingURL=maxBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to get negative version of a value (i.e. x * -1)\n */\nexport class NegateBlock extends NodeMaterialBlock {\n /**\n * Creates a new NegateBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"value\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"NegateBlock\";\n }\n /**\n * Gets the value input component\n */\n get value() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = -1.0 * ${this.value.associatedVariableName};\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.NegateBlock\", NegateBlock);\n//# sourceMappingURL=negateBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to get the min of 2 values\n */\nexport class MinBlock extends NodeMaterialBlock {\n /**\n * Creates a new MinBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"left\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"right\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._linkConnectionTypes(0, 1);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"MinBlock\";\n }\n /**\n * Gets the left operand input component\n */\n get left() {\n return this._inputs[0];\n }\n /**\n * Gets the right operand input component\n */\n get right() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = min(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.MinBlock\", MinBlock);\n//# sourceMappingURL=minBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to get the distance between 2 values\n */\nexport class DistanceBlock extends NodeMaterialBlock {\n /**\n * Creates a new DistanceBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"left\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"right\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Float);\n this._linkConnectionTypes(0, 1);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"DistanceBlock\";\n }\n /**\n * Gets the left operand input component\n */\n get left() {\n return this._inputs[0];\n }\n /**\n * Gets the right operand input component\n */\n get right() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = length(${this.left.associatedVariableName} - ${this.right.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.DistanceBlock\", DistanceBlock);\n//# sourceMappingURL=distanceBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to get the length of a vector\n */\nexport class LengthBlock extends NodeMaterialBlock {\n /**\n * Creates a new LengthBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"value\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"LengthBlock\";\n }\n /**\n * Gets the value input component\n */\n get value() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = length(${this.value.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.LengthBlock\", LengthBlock);\n//# sourceMappingURL=lengthBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to get the value of the first parameter raised to the power of the second\n */\nexport class PowBlock extends NodeMaterialBlock {\n /**\n * Creates a new PowBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"value\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"power\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._linkConnectionTypes(0, 1);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"PowBlock\";\n }\n /**\n * Gets the value operand input component\n */\n get value() {\n return this._inputs[0];\n }\n /**\n * Gets the power operand input component\n */\n get power() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = pow(${this.value.associatedVariableName}, ${this.power.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.PowBlock\", PowBlock);\n//# sourceMappingURL=powBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport \"../../../Shaders/ShadersInclude/helperFunctions.js\";\n/**\n * Block used to get a random number\n */\nexport class RandomNumberBlock extends NodeMaterialBlock {\n /**\n * Creates a new RandomNumberBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"seed\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector2 |\n NodeMaterialBlockConnectionPointTypes.Vector3 |\n NodeMaterialBlockConnectionPointTypes.Vector4 |\n NodeMaterialBlockConnectionPointTypes.Color3 |\n NodeMaterialBlockConnectionPointTypes.Color4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"RandomNumberBlock\";\n }\n /**\n * Gets the seed input component\n */\n get seed() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n const comments = `//${this.name}`;\n state._emitFunctionFromInclude(\"helperFunctions\", comments);\n state.compilationString += this._declareOutput(output, state) + ` = getRand(${this.seed.associatedVariableName}.xy);\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.RandomNumberBlock\", RandomNumberBlock);\n//# sourceMappingURL=randomNumberBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to compute arc tangent of 2 values\n */\nexport class ArcTan2Block extends NodeMaterialBlock {\n /**\n * Creates a new ArcTan2Block\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"x\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerInput(\"y\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ArcTan2Block\";\n }\n /**\n * Gets the x operand input component\n */\n get x() {\n return this._inputs[0];\n }\n /**\n * Gets the y operand input component\n */\n get y() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = atan(${this.x.associatedVariableName}, ${this.y.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.ArcTan2Block\", ArcTan2Block);\n//# sourceMappingURL=arcTan2Block.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to smooth step a value\n */\nexport class SmoothStepBlock extends NodeMaterialBlock {\n /**\n * Creates a new SmoothStepBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"value\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"edge0\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerInput(\"edge1\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"SmoothStepBlock\";\n }\n /**\n * Gets the value operand input component\n */\n get value() {\n return this._inputs[0];\n }\n /**\n * Gets the first edge operand input component\n */\n get edge0() {\n return this._inputs[1];\n }\n /**\n * Gets the second edge operand input component\n */\n get edge1() {\n return this._inputs[2];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = smoothstep(${this.edge0.associatedVariableName}, ${this.edge1.associatedVariableName}, ${this.value.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.SmoothStepBlock\", SmoothStepBlock);\n//# sourceMappingURL=smoothStepBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to get the reciprocal (1 / x) of a value\n */\nexport class ReciprocalBlock extends NodeMaterialBlock {\n /**\n * Creates a new ReciprocalBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ReciprocalBlock\";\n }\n /**\n * Gets the input component\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n if (this.input.type === NodeMaterialBlockConnectionPointTypes.Matrix) {\n state.compilationString += this._declareOutput(output, state) + ` = inverse(${this.input.associatedVariableName});\\r\\n`;\n }\n else {\n state.compilationString += this._declareOutput(output, state) + ` = 1. / ${this.input.associatedVariableName};\\r\\n`;\n }\n return this;\n }\n}\nRegisterClass(\"BABYLON.ReciprocalBlock\", ReciprocalBlock);\n//# sourceMappingURL=reciprocalBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to replace a color by another one\n */\nexport class ReplaceColorBlock extends NodeMaterialBlock {\n /**\n * Creates a new ReplaceColorBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"value\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"reference\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"distance\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerInput(\"replacement\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._linkConnectionTypes(0, 1);\n this._linkConnectionTypes(0, 3);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n this._inputs[3].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[3].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ReplaceColorBlock\";\n }\n /**\n * Gets the value input component\n */\n get value() {\n return this._inputs[0];\n }\n /**\n * Gets the reference input component\n */\n get reference() {\n return this._inputs[1];\n }\n /**\n * Gets the distance input component\n */\n get distance() {\n return this._inputs[2];\n }\n /**\n * Gets the replacement input component\n */\n get replacement() {\n return this._inputs[3];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + `;\\r\\n`;\n state.compilationString += `if (length(${this.value.associatedVariableName} - ${this.reference.associatedVariableName}) < ${this.distance.associatedVariableName}) {\\r\\n`;\n state.compilationString += `${output.associatedVariableName} = ${this.replacement.associatedVariableName};\\r\\n`;\n state.compilationString += `} else {\\r\\n`;\n state.compilationString += `${output.associatedVariableName} = ${this.value.associatedVariableName};\\r\\n`;\n state.compilationString += `}\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.ReplaceColorBlock\", ReplaceColorBlock);\n//# sourceMappingURL=replaceColorBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to posterize a value\n * @see https://en.wikipedia.org/wiki/Posterization\n */\nexport class PosterizeBlock extends NodeMaterialBlock {\n /**\n * Creates a new PosterizeBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"value\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"steps\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._linkConnectionTypes(0, 1);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n this._inputs[1].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"PosterizeBlock\";\n }\n /**\n * Gets the value input component\n */\n get value() {\n return this._inputs[0];\n }\n /**\n * Gets the steps input component\n */\n get steps() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = floor(${this.value.associatedVariableName} / (1.0 / ${this.steps.associatedVariableName})) * (1.0 / ${this.steps.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.PosterizeBlock\", PosterizeBlock);\n//# sourceMappingURL=posterizeBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Operations supported by the Wave block\n */\nexport var WaveBlockKind;\n(function (WaveBlockKind) {\n /** SawTooth */\n WaveBlockKind[WaveBlockKind[\"SawTooth\"] = 0] = \"SawTooth\";\n /** Square */\n WaveBlockKind[WaveBlockKind[\"Square\"] = 1] = \"Square\";\n /** Triangle */\n WaveBlockKind[WaveBlockKind[\"Triangle\"] = 2] = \"Triangle\";\n})(WaveBlockKind || (WaveBlockKind = {}));\n/**\n * Block used to apply wave operation to floats\n */\nexport class WaveBlock extends NodeMaterialBlock {\n /**\n * Creates a new WaveBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n /**\n * Gets or sets the kibnd of wave to be applied by the block\n */\n this.kind = WaveBlockKind.SawTooth;\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"WaveBlock\";\n }\n /**\n * Gets the input component\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n switch (this.kind) {\n case WaveBlockKind.SawTooth: {\n state.compilationString += this._declareOutput(output, state) + ` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName});\\r\\n`;\n break;\n }\n case WaveBlockKind.Square: {\n state.compilationString += this._declareOutput(output, state) + ` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName}));\\r\\n`;\n break;\n }\n case WaveBlockKind.Triangle: {\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0;\\r\\n`;\n break;\n }\n }\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.kind = this.kind;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.kind = serializationObject.kind;\n }\n}\nRegisterClass(\"BABYLON.WaveBlock\", WaveBlock);\n//# sourceMappingURL=waveBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { Color3 } from \"../../../Maths/math.color.js\";\nimport { Observable } from \"../../../Misc/observable.js\";\n/**\n * Class used to store a color step for the GradientBlock\n */\nexport class GradientBlockColorStep {\n /**\n * Gets value indicating which step this color is associated with (between 0 and 1)\n */\n get step() {\n return this._step;\n }\n /**\n * Sets a value indicating which step this color is associated with (between 0 and 1)\n */\n set step(val) {\n this._step = val;\n }\n /**\n * Gets the color associated with this step\n */\n get color() {\n return this._color;\n }\n /**\n * Sets the color associated with this step\n */\n set color(val) {\n this._color = val;\n }\n /**\n * Creates a new GradientBlockColorStep\n * @param step defines a value indicating which step this color is associated with (between 0 and 1)\n * @param color defines the color associated with this step\n */\n constructor(step, color) {\n this.step = step;\n this.color = color;\n }\n}\n/**\n * Block used to return a color from a gradient based on an input value between 0 and 1\n */\nexport class GradientBlock extends NodeMaterialBlock {\n /** calls observable when the value is changed*/\n colorStepsUpdated() {\n this.onValueChangedObservable.notifyObservers(this);\n }\n /**\n * Creates a new GradientBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n /**\n * Gets or sets the list of color steps\n */\n this.colorSteps = [new GradientBlockColorStep(0, Color3.Black()), new GradientBlockColorStep(1.0, Color3.White())];\n /** Gets an observable raised when the value is changed */\n this.onValueChangedObservable = new Observable();\n this.registerInput(\"gradient\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Color3);\n this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Float |\n NodeMaterialBlockConnectionPointTypes.Vector2 |\n NodeMaterialBlockConnectionPointTypes.Vector3 |\n NodeMaterialBlockConnectionPointTypes.Vector4 |\n NodeMaterialBlockConnectionPointTypes.Color3 |\n NodeMaterialBlockConnectionPointTypes.Color4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"GradientBlock\";\n }\n /**\n * Gets the gradient input component\n */\n get gradient() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _writeColorConstant(index) {\n const step = this.colorSteps[index];\n return `vec3(${step.color.r}, ${step.color.g}, ${step.color.b})`;\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n if (!this.colorSteps.length || !this.gradient.connectedPoint) {\n state.compilationString += this._declareOutput(output, state) + ` = vec3(0., 0., 0.);\\r\\n`;\n return;\n }\n const tempColor = state._getFreeVariableName(\"gradientTempColor\");\n const tempPosition = state._getFreeVariableName(\"gradientTempPosition\");\n state.compilationString += `vec3 ${tempColor} = ${this._writeColorConstant(0)};\\r\\n`;\n state.compilationString += `float ${tempPosition};\\r\\n`;\n let gradientSource = this.gradient.associatedVariableName;\n if (this.gradient.connectedPoint.type !== NodeMaterialBlockConnectionPointTypes.Float) {\n gradientSource += \".x\";\n }\n for (let index = 1; index < this.colorSteps.length; index++) {\n const step = this.colorSteps[index];\n const previousStep = this.colorSteps[index - 1];\n state.compilationString += `${tempPosition} = clamp((${gradientSource} - ${state._emitFloat(previousStep.step)}) / (${state._emitFloat(step.step)} - ${state._emitFloat(previousStep.step)}), 0.0, 1.0) * step(${state._emitFloat(index)}, ${state._emitFloat(this.colorSteps.length - 1)});\\r\\n`;\n state.compilationString += `${tempColor} = mix(${tempColor}, ${this._writeColorConstant(index)}, ${tempPosition});\\r\\n`;\n }\n state.compilationString += this._declareOutput(output, state) + ` = ${tempColor};\\r\\n`;\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.colorSteps = [];\n for (const step of this.colorSteps) {\n serializationObject.colorSteps.push({\n step: step.step,\n color: {\n r: step.color.r,\n g: step.color.g,\n b: step.color.b,\n },\n });\n }\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.colorSteps.length = 0;\n for (const step of serializationObject.colorSteps) {\n this.colorSteps.push(new GradientBlockColorStep(step.step, new Color3(step.color.r, step.color.g, step.color.b)));\n }\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n codeString += `${this._codeVariableName}.colorSteps = [];\\r\\n`;\n for (const colorStep of this.colorSteps) {\n codeString += `${this._codeVariableName}.colorSteps.push(new BABYLON.GradientBlockColorStep(${colorStep.step}, new BABYLON.Color3(${colorStep.color.r}, ${colorStep.color.g}, ${colorStep.color.b})));\\r\\n`;\n }\n return codeString;\n }\n}\nRegisterClass(\"BABYLON.GradientBlock\", GradientBlock);\n//# sourceMappingURL=gradientBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to normalize lerp between 2 values\n */\nexport class NLerpBlock extends NodeMaterialBlock {\n /**\n * Creates a new NLerpBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"left\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"right\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"gradient\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._linkConnectionTypes(0, 1);\n this._linkConnectionTypes(1, 2, true);\n this._inputs[2].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"NLerpBlock\";\n }\n /**\n * Gets the left operand input component\n */\n get left() {\n return this._inputs[0];\n }\n /**\n * Gets the right operand input component\n */\n get right() {\n return this._inputs[1];\n }\n /**\n * Gets the gradient operand input component\n */\n get gradient() {\n return this._inputs[2];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = normalize(mix(${this.left.associatedVariableName} , ${this.right.associatedVariableName}, ${this.gradient.associatedVariableName}));\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.NLerpBlock\", NLerpBlock);\n//# sourceMappingURL=nLerpBlock.js.map","import { __decorate } from \"../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../nodeMaterialDecorator.js\";\n/**\n * block used to Generate a Worley Noise 3D Noise Pattern\n */\n// Source: https://github.com/Erkaman/glsl-worley\n// Converted to BJS by Pryme8\n//\n// Worley Noise 3D\n// Return vec2 value range of -1.0->1.0, F1-F2 respectivly\nexport class WorleyNoise3DBlock extends NodeMaterialBlock {\n /**\n * Creates a new WorleyNoise3DBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n /** Gets or sets a boolean indicating that normal should be inverted on X axis */\n this.manhattanDistance = false;\n this.registerInput(\"seed\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerInput(\"jitter\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Vector2);\n this.registerOutput(\"x\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"y\", NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"WorleyNoise3DBlock\";\n }\n /**\n * Gets the seed input component\n */\n get seed() {\n return this._inputs[0];\n }\n /**\n * Gets the jitter input component\n */\n get jitter() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n /**\n * Gets the x component\n */\n get x() {\n return this._outputs[1];\n }\n /**\n * Gets the y component\n */\n get y() {\n return this._outputs[2];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (!this.seed.isConnected) {\n return;\n }\n if (!this.output.hasEndpoints && !this.x.hasEndpoints && !this.y.hasEndpoints) {\n return;\n }\n let functionString = `vec3 permute(vec3 x){\\r\\n`;\n functionString += ` return mod((34.0 * x + 1.0) * x, 289.0);\\r\\n`;\n functionString += `}\\r\\n\\r\\n`;\n functionString += `vec3 dist(vec3 x, vec3 y, vec3 z, bool manhattanDistance){\\r\\n`;\n functionString += ` return manhattanDistance ? abs(x) + abs(y) + abs(z) : (x * x + y * y + z * z);\\r\\n`;\n functionString += `}\\r\\n\\r\\n`;\n functionString += `vec2 worley(vec3 P, float jitter, bool manhattanDistance){\\r\\n`;\n functionString += ` float K = 0.142857142857; // 1/7\\r\\n`;\n functionString += ` float Ko = 0.428571428571; // 1/2-K/2\\r\\n`;\n functionString += ` float K2 = 0.020408163265306; // 1/(7*7)\\r\\n`;\n functionString += ` float Kz = 0.166666666667; // 1/6\\r\\n`;\n functionString += ` float Kzo = 0.416666666667; // 1/2-1/6*2\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 Pi = mod(floor(P), 289.0);\\r\\n`;\n functionString += ` vec3 Pf = fract(P) - 0.5;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 Pfx = Pf.x + vec3(1.0, 0.0, -1.0);\\r\\n`;\n functionString += ` vec3 Pfy = Pf.y + vec3(1.0, 0.0, -1.0);\\r\\n`;\n functionString += ` vec3 Pfz = Pf.z + vec3(1.0, 0.0, -1.0);\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 p = permute(Pi.x + vec3(-1.0, 0.0, 1.0));\\r\\n`;\n functionString += ` vec3 p1 = permute(p + Pi.y - 1.0);\\r\\n`;\n functionString += ` vec3 p2 = permute(p + Pi.y);\\r\\n`;\n functionString += ` vec3 p3 = permute(p + Pi.y + 1.0);\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 p11 = permute(p1 + Pi.z - 1.0);\\r\\n`;\n functionString += ` vec3 p12 = permute(p1 + Pi.z);\\r\\n`;\n functionString += ` vec3 p13 = permute(p1 + Pi.z + 1.0);\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 p21 = permute(p2 + Pi.z - 1.0);\\r\\n`;\n functionString += ` vec3 p22 = permute(p2 + Pi.z);\\r\\n`;\n functionString += ` vec3 p23 = permute(p2 + Pi.z + 1.0);\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 p31 = permute(p3 + Pi.z - 1.0);\\r\\n`;\n functionString += ` vec3 p32 = permute(p3 + Pi.z);\\r\\n`;\n functionString += ` vec3 p33 = permute(p3 + Pi.z + 1.0);\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 ox11 = fract(p11*K) - Ko;\\r\\n`;\n functionString += ` vec3 oy11 = mod(floor(p11*K), 7.0)*K - Ko;\\r\\n`;\n functionString += ` vec3 oz11 = floor(p11*K2)*Kz - Kzo; // p11 < 289 guaranteed\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 ox12 = fract(p12*K) - Ko;\\r\\n`;\n functionString += ` vec3 oy12 = mod(floor(p12*K), 7.0)*K - Ko;\\r\\n`;\n functionString += ` vec3 oz12 = floor(p12*K2)*Kz - Kzo;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 ox13 = fract(p13*K) - Ko;\\r\\n`;\n functionString += ` vec3 oy13 = mod(floor(p13*K), 7.0)*K - Ko;\\r\\n`;\n functionString += ` vec3 oz13 = floor(p13*K2)*Kz - Kzo;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 ox21 = fract(p21*K) - Ko;\\r\\n`;\n functionString += ` vec3 oy21 = mod(floor(p21*K), 7.0)*K - Ko;\\r\\n`;\n functionString += ` vec3 oz21 = floor(p21*K2)*Kz - Kzo;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 ox22 = fract(p22*K) - Ko;\\r\\n`;\n functionString += ` vec3 oy22 = mod(floor(p22*K), 7.0)*K - Ko;\\r\\n`;\n functionString += ` vec3 oz22 = floor(p22*K2)*Kz - Kzo;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 ox23 = fract(p23*K) - Ko;\\r\\n`;\n functionString += ` vec3 oy23 = mod(floor(p23*K), 7.0)*K - Ko;\\r\\n`;\n functionString += ` vec3 oz23 = floor(p23*K2)*Kz - Kzo;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 ox31 = fract(p31*K) - Ko;\\r\\n`;\n functionString += ` vec3 oy31 = mod(floor(p31*K), 7.0)*K - Ko;\\r\\n`;\n functionString += ` vec3 oz31 = floor(p31*K2)*Kz - Kzo;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 ox32 = fract(p32*K) - Ko;\\r\\n`;\n functionString += ` vec3 oy32 = mod(floor(p32*K), 7.0)*K - Ko;\\r\\n`;\n functionString += ` vec3 oz32 = floor(p32*K2)*Kz - Kzo;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 ox33 = fract(p33*K) - Ko;\\r\\n`;\n functionString += ` vec3 oy33 = mod(floor(p33*K), 7.0)*K - Ko;\\r\\n`;\n functionString += ` vec3 oz33 = floor(p33*K2)*Kz - Kzo;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 dx11 = Pfx + jitter*ox11;\\r\\n`;\n functionString += ` vec3 dy11 = Pfy.x + jitter*oy11;\\r\\n`;\n functionString += ` vec3 dz11 = Pfz.x + jitter*oz11;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 dx12 = Pfx + jitter*ox12;\\r\\n`;\n functionString += ` vec3 dy12 = Pfy.x + jitter*oy12;\\r\\n`;\n functionString += ` vec3 dz12 = Pfz.y + jitter*oz12;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 dx13 = Pfx + jitter*ox13;\\r\\n`;\n functionString += ` vec3 dy13 = Pfy.x + jitter*oy13;\\r\\n`;\n functionString += ` vec3 dz13 = Pfz.z + jitter*oz13;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 dx21 = Pfx + jitter*ox21;\\r\\n`;\n functionString += ` vec3 dy21 = Pfy.y + jitter*oy21;\\r\\n`;\n functionString += ` vec3 dz21 = Pfz.x + jitter*oz21;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 dx22 = Pfx + jitter*ox22;\\r\\n`;\n functionString += ` vec3 dy22 = Pfy.y + jitter*oy22;\\r\\n`;\n functionString += ` vec3 dz22 = Pfz.y + jitter*oz22;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 dx23 = Pfx + jitter*ox23;\\r\\n`;\n functionString += ` vec3 dy23 = Pfy.y + jitter*oy23;\\r\\n`;\n functionString += ` vec3 dz23 = Pfz.z + jitter*oz23;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 dx31 = Pfx + jitter*ox31;\\r\\n`;\n functionString += ` vec3 dy31 = Pfy.z + jitter*oy31;\\r\\n`;\n functionString += ` vec3 dz31 = Pfz.x + jitter*oz31;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 dx32 = Pfx + jitter*ox32;\\r\\n`;\n functionString += ` vec3 dy32 = Pfy.z + jitter*oy32;\\r\\n`;\n functionString += ` vec3 dz32 = Pfz.y + jitter*oz32;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 dx33 = Pfx + jitter*ox33;\\r\\n`;\n functionString += ` vec3 dy33 = Pfy.z + jitter*oy33;\\r\\n`;\n functionString += ` vec3 dz33 = Pfz.z + jitter*oz33;\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 d11 = dist(dx11, dy11, dz11, manhattanDistance);\\r\\n`;\n functionString += ` vec3 d12 =dist(dx12, dy12, dz12, manhattanDistance);\\r\\n`;\n functionString += ` vec3 d13 = dist(dx13, dy13, dz13, manhattanDistance);\\r\\n`;\n functionString += ` vec3 d21 = dist(dx21, dy21, dz21, manhattanDistance);\\r\\n`;\n functionString += ` vec3 d22 = dist(dx22, dy22, dz22, manhattanDistance);\\r\\n`;\n functionString += ` vec3 d23 = dist(dx23, dy23, dz23, manhattanDistance);\\r\\n`;\n functionString += ` vec3 d31 = dist(dx31, dy31, dz31, manhattanDistance);\\r\\n`;\n functionString += ` vec3 d32 = dist(dx32, dy32, dz32, manhattanDistance);\\r\\n`;\n functionString += ` vec3 d33 = dist(dx33, dy33, dz33, manhattanDistance);\\r\\n`;\n functionString += `\\r\\n`;\n functionString += ` vec3 d1a = min(d11, d12);\\r\\n`;\n functionString += ` d12 = max(d11, d12);\\r\\n`;\n functionString += ` d11 = min(d1a, d13); // Smallest now not in d12 or d13\\r\\n`;\n functionString += ` d13 = max(d1a, d13);\\r\\n`;\n functionString += ` d12 = min(d12, d13); // 2nd smallest now not in d13\\r\\n`;\n functionString += ` vec3 d2a = min(d21, d22);\\r\\n`;\n functionString += ` d22 = max(d21, d22);\\r\\n`;\n functionString += ` d21 = min(d2a, d23); // Smallest now not in d22 or d23\\r\\n`;\n functionString += ` d23 = max(d2a, d23);\\r\\n`;\n functionString += ` d22 = min(d22, d23); // 2nd smallest now not in d23\\r\\n`;\n functionString += ` vec3 d3a = min(d31, d32);\\r\\n`;\n functionString += ` d32 = max(d31, d32);\\r\\n`;\n functionString += ` d31 = min(d3a, d33); // Smallest now not in d32 or d33\\r\\n`;\n functionString += ` d33 = max(d3a, d33);\\r\\n`;\n functionString += ` d32 = min(d32, d33); // 2nd smallest now not in d33\\r\\n`;\n functionString += ` vec3 da = min(d11, d21);\\r\\n`;\n functionString += ` d21 = max(d11, d21);\\r\\n`;\n functionString += ` d11 = min(da, d31); // Smallest now in d11\\r\\n`;\n functionString += ` d31 = max(da, d31); // 2nd smallest now not in d31\\r\\n`;\n functionString += ` d11.xy = (d11.x < d11.y) ? d11.xy : d11.yx;\\r\\n`;\n functionString += ` d11.xz = (d11.x < d11.z) ? d11.xz : d11.zx; // d11.x now smallest\\r\\n`;\n functionString += ` d12 = min(d12, d21); // 2nd smallest now not in d21\\r\\n`;\n functionString += ` d12 = min(d12, d22); // nor in d22\\r\\n`;\n functionString += ` d12 = min(d12, d31); // nor in d31\\r\\n`;\n functionString += ` d12 = min(d12, d32); // nor in d32\\r\\n`;\n functionString += ` d11.yz = min(d11.yz,d12.xy); // nor in d12.yz\\r\\n`;\n functionString += ` d11.y = min(d11.y,d12.z); // Only two more to go\\r\\n`;\n functionString += ` d11.y = min(d11.y,d11.z); // Done! (Phew!)\\r\\n`;\n functionString += ` return sqrt(d11.xy); // F1, F2\\r\\n`;\n functionString += `}\\r\\n\\r\\n`;\n state._emitFunction(\"worley3D\", functionString, \"// Worley3D\");\n const tempVariable = state._getFreeVariableName(\"worleyTemp\");\n state.compilationString += `vec2 ${tempVariable} = worley(${this.seed.associatedVariableName}, ${this.jitter.associatedVariableName}, ${this.manhattanDistance});\\r\\n`;\n if (this.output.hasEndpoints) {\n state.compilationString += this._declareOutput(this.output, state) + ` = ${tempVariable};\\r\\n`;\n }\n if (this.x.hasEndpoints) {\n state.compilationString += this._declareOutput(this.x, state) + ` = ${tempVariable}.x;\\r\\n`;\n }\n if (this.y.hasEndpoints) {\n state.compilationString += this._declareOutput(this.y, state) + ` = ${tempVariable}.y;\\r\\n`;\n }\n return this;\n }\n /**\n * Exposes the properties to the UI?\n */\n _dumpPropertiesCode() {\n const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.manhattanDistance = ${this.manhattanDistance};\\r\\n`;\n return codeString;\n }\n /**\n * Exposes the properties to the Serialize?\n */\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.manhattanDistance = this.manhattanDistance;\n return serializationObject;\n }\n /**\n * Exposes the properties to the deserialize?\n * @param serializationObject\n * @param scene\n * @param rootUrl\n */\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.manhattanDistance = serializationObject.manhattanDistance;\n }\n}\n__decorate([\n editableInPropertyPage(\"Use Manhattan Distance\", PropertyTypeForEdition.Boolean, \"PROPERTIES\", { notifiers: { update: false } })\n], WorleyNoise3DBlock.prototype, \"manhattanDistance\", void 0);\nRegisterClass(\"BABYLON.WorleyNoise3DBlock\", WorleyNoise3DBlock);\n//# sourceMappingURL=worleyNoise3DBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * block used to Generate a Simplex Perlin 3d Noise Pattern\n */\n//\n// Wombat\n// An efficient texture-free GLSL procedural noise library\n// Source: https://github.com/BrianSharpe/Wombat\n// Derived from: https://github.com/BrianSharpe/GPU-Noise-Lib\n//\n// I'm not one for copyrights. Use the code however you wish.\n// All I ask is that credit be given back to the blog or myself when appropriate.\n// And also to let me know if you come up with any changes, improvements, thoughts or interesting uses for this stuff. :)\n// Thanks!\n//\n// Brian Sharpe\n// brisharpe CIRCLE_A yahoo DOT com\n// http://briansharpe.wordpress.com\n// https://github.com/BrianSharpe\n//\n//\n// This is a modified version of Stefan Gustavson's and Ian McEwan's work at http://github.com/ashima/webgl-noise\n// Modifications are...\n// - faster random number generation\n// - analytical final normalization\n// - space scaled can have an approx feature size of 1.0\n// - filter kernel changed to fix discontinuities at tetrahedron boundaries\n//\n// Converted to BJS by Pryme8\n//\n// Simplex Perlin Noise 3D\n// Return value range of -1.0->1.0\n//\nexport class SimplexPerlin3DBlock extends NodeMaterialBlock {\n /**\n * Creates a new SimplexPerlin3DBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"seed\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"SimplexPerlin3DBlock\";\n }\n /**\n * Gets the seed operand input component\n */\n get seed() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (!this.seed.isConnected) {\n return;\n }\n if (!this._outputs[0].hasEndpoints) {\n return;\n }\n let functionString = `const float SKEWFACTOR = 1.0/3.0;\\r\\n`;\n functionString += `const float UNSKEWFACTOR = 1.0/6.0;\\r\\n`;\n functionString += `const float SIMPLEX_CORNER_POS = 0.5;\\r\\n`;\n functionString += `const float SIMPLEX_TETRAHADRON_HEIGHT = 0.70710678118654752440084436210485;\\r\\n`;\n functionString += `float SimplexPerlin3D( vec3 P ){\\r\\n`;\n functionString += ` P.x = P == vec3(0., 0., 0.) ? 0.00001 : P.x;\\r\\n`;\n functionString += ` P *= SIMPLEX_TETRAHADRON_HEIGHT;\\r\\n`;\n functionString += ` vec3 Pi = floor( P + dot( P, vec3( SKEWFACTOR) ) );`;\n functionString += ` vec3 x0 = P - Pi + dot(Pi, vec3( UNSKEWFACTOR ) );\\r\\n`;\n functionString += ` vec3 g = step(x0.yzx, x0.xyz);\\r\\n`;\n functionString += ` vec3 l = 1.0 - g;\\r\\n`;\n functionString += ` vec3 Pi_1 = min( g.xyz, l.zxy );\\r\\n`;\n functionString += ` vec3 Pi_2 = max( g.xyz, l.zxy );\\r\\n`;\n functionString += ` vec3 x1 = x0 - Pi_1 + UNSKEWFACTOR;\\r\\n`;\n functionString += ` vec3 x2 = x0 - Pi_2 + SKEWFACTOR;\\r\\n`;\n functionString += ` vec3 x3 = x0 - SIMPLEX_CORNER_POS;\\r\\n`;\n functionString += ` vec4 v1234_x = vec4( x0.x, x1.x, x2.x, x3.x );\\r\\n`;\n functionString += ` vec4 v1234_y = vec4( x0.y, x1.y, x2.y, x3.y );\\r\\n`;\n functionString += ` vec4 v1234_z = vec4( x0.z, x1.z, x2.z, x3.z );\\r\\n`;\n functionString += ` Pi.xyz = Pi.xyz - floor(Pi.xyz * ( 1.0 / 69.0 )) * 69.0;\\r\\n`;\n functionString += ` vec3 Pi_inc1 = step( Pi, vec3( 69.0 - 1.5 ) ) * ( Pi + 1.0 );\\r\\n`;\n functionString += ` vec4 Pt = vec4( Pi.xy, Pi_inc1.xy ) + vec2( 50.0, 161.0 ).xyxy;\\r\\n`;\n functionString += ` Pt *= Pt;\\r\\n`;\n functionString += ` vec4 V1xy_V2xy = mix( Pt.xyxy, Pt.zwzw, vec4( Pi_1.xy, Pi_2.xy ) );\\r\\n`;\n functionString += ` Pt = vec4( Pt.x, V1xy_V2xy.xz, Pt.z ) * vec4( Pt.y, V1xy_V2xy.yw, Pt.w );\\r\\n`;\n functionString += ` const vec3 SOMELARGEFLOATS = vec3( 635.298681, 682.357502, 668.926525 );\\r\\n`;\n functionString += ` const vec3 ZINC = vec3( 48.500388, 65.294118, 63.934599 );\\r\\n`;\n functionString += ` vec3 lowz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi.zzz * ZINC.xyz ) );\\r\\n`;\n functionString += ` vec3 highz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi_inc1.zzz * ZINC.xyz ) );\\r\\n`;\n functionString += ` Pi_1 = ( Pi_1.z < 0.5 ) ? lowz_mods : highz_mods;\\r\\n`;\n functionString += ` Pi_2 = ( Pi_2.z < 0.5 ) ? lowz_mods : highz_mods;\\r\\n`;\n functionString += ` vec4 hash_0 = fract( Pt * vec4( lowz_mods.x, Pi_1.x, Pi_2.x, highz_mods.x ) ) - 0.49999;\\r\\n`;\n functionString += ` vec4 hash_1 = fract( Pt * vec4( lowz_mods.y, Pi_1.y, Pi_2.y, highz_mods.y ) ) - 0.49999;\\r\\n`;\n functionString += ` vec4 hash_2 = fract( Pt * vec4( lowz_mods.z, Pi_1.z, Pi_2.z, highz_mods.z ) ) - 0.49999;\\r\\n`;\n functionString += ` vec4 grad_results = inversesqrt( hash_0 * hash_0 + hash_1 * hash_1 + hash_2 * hash_2 ) * ( hash_0 * v1234_x + hash_1 * v1234_y + hash_2 * v1234_z );\\r\\n`;\n functionString += ` const float FINAL_NORMALIZATION = 37.837227241611314102871574478976;\\r\\n`;\n functionString += ` vec4 kernel_weights = v1234_x * v1234_x + v1234_y * v1234_y + v1234_z * v1234_z;\\r\\n`;\n functionString += ` kernel_weights = max(0.5 - kernel_weights, 0.0);\\r\\n`;\n functionString += ` kernel_weights = kernel_weights*kernel_weights*kernel_weights;\\r\\n`;\n functionString += ` return dot( kernel_weights, grad_results ) * FINAL_NORMALIZATION;\\r\\n`;\n functionString += `}\\r\\n`;\n state._emitFunction(\"SimplexPerlin3D\", functionString, \"// SimplexPerlin3D\");\n state.compilationString += this._declareOutput(this._outputs[0], state) + ` = SimplexPerlin3D(${this.seed.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.SimplexPerlin3DBlock\", SimplexPerlin3DBlock);\n//# sourceMappingURL=simplexPerlin3DBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to blend normals\n */\nexport class NormalBlendBlock extends NodeMaterialBlock {\n /**\n * Creates a new NormalBlendBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"normalMap0\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"normalMap1\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 |\n NodeMaterialBlockConnectionPointTypes.Color4 |\n NodeMaterialBlockConnectionPointTypes.Vector3 |\n NodeMaterialBlockConnectionPointTypes.Vector4);\n this._inputs[1].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 |\n NodeMaterialBlockConnectionPointTypes.Color4 |\n NodeMaterialBlockConnectionPointTypes.Vector3 |\n NodeMaterialBlockConnectionPointTypes.Vector4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"NormalBlendBlock\";\n }\n /**\n * Gets the first input component\n */\n get normalMap0() {\n return this._inputs[0];\n }\n /**\n * Gets the second input component\n */\n get normalMap1() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n const input0 = this._inputs[0];\n const input1 = this._inputs[1];\n const stepR = state._getFreeVariableName(\"stepR\");\n const stepG = state._getFreeVariableName(\"stepG\");\n state.compilationString += `float ${stepR} = step(0.5, ${input0.associatedVariableName}.r);\\r\\n`;\n state.compilationString += `float ${stepG} = step(0.5, ${input0.associatedVariableName}.g);\\r\\n`;\n state.compilationString += this._declareOutput(output, state) + `;\\r\\n`;\n state.compilationString += `${output.associatedVariableName}.r = (1.0 - ${stepR}) * ${input0.associatedVariableName}.r * ${input1.associatedVariableName}.r * 2.0 + ${stepR} * (1.0 - (1.0 - ${input0.associatedVariableName}.r) * (1.0 - ${input1.associatedVariableName}.r) * 2.0);\\r\\n`;\n state.compilationString += `${output.associatedVariableName}.g = (1.0 - ${stepG}) * ${input0.associatedVariableName}.g * ${input1.associatedVariableName}.g * 2.0 + ${stepG} * (1.0 - (1.0 - ${input0.associatedVariableName}.g) * (1.0 - ${input1.associatedVariableName}.g) * 2.0);\\r\\n`;\n state.compilationString += `${output.associatedVariableName}.b = ${input0.associatedVariableName}.b * ${input1.associatedVariableName}.b;\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.NormalBlendBlock\", NormalBlendBlock);\n//# sourceMappingURL=normalBlendBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { InputBlock } from \"./Input/inputBlock.js\";\n/**\n * Block used to rotate a 2d vector by a given angle\n */\nexport class Rotate2dBlock extends NodeMaterialBlock {\n /**\n * Creates a new Rotate2dBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.Vector2);\n this.registerInput(\"angle\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Vector2);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"Rotate2dBlock\";\n }\n /**\n * Gets the input vector\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the input angle\n */\n get angle() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n autoConfigure() {\n if (!this.angle.isConnected) {\n const angleInput = new InputBlock(\"angle\");\n angleInput.value = 0;\n angleInput.output.connectTo(this.angle);\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n const angle = this.angle;\n const input = this.input;\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = vec2(cos(${angle.associatedVariableName}) * ${input.associatedVariableName}.x - sin(${angle.associatedVariableName}) * ${input.associatedVariableName}.y, sin(${angle.associatedVariableName}) * ${input.associatedVariableName}.x + cos(${angle.associatedVariableName}) * ${input.associatedVariableName}.y);\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.Rotate2dBlock\", Rotate2dBlock);\n//# sourceMappingURL=rotate2dBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to get the reflected vector from a direction and a normal\n */\nexport class ReflectBlock extends NodeMaterialBlock {\n /**\n * Creates a new ReflectBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"incident\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"normal\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 |\n NodeMaterialBlockConnectionPointTypes.Vector4 |\n NodeMaterialBlockConnectionPointTypes.Color3 |\n NodeMaterialBlockConnectionPointTypes.Color4);\n this._inputs[1].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 |\n NodeMaterialBlockConnectionPointTypes.Vector4 |\n NodeMaterialBlockConnectionPointTypes.Color3 |\n NodeMaterialBlockConnectionPointTypes.Color4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ReflectBlock\";\n }\n /**\n * Gets the incident component\n */\n get incident() {\n return this._inputs[0];\n }\n /**\n * Gets the normal component\n */\n get normal() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = reflect(${this.incident.associatedVariableName}.xyz, ${this.normal.associatedVariableName}.xyz);\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.ReflectBlock\", ReflectBlock);\n//# sourceMappingURL=reflectBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to get the refracted vector from a direction and a normal\n */\nexport class RefractBlock extends NodeMaterialBlock {\n /**\n * Creates a new RefractBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"incident\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"normal\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"ior\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Vector3);\n this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 |\n NodeMaterialBlockConnectionPointTypes.Vector4 |\n NodeMaterialBlockConnectionPointTypes.Color3 |\n NodeMaterialBlockConnectionPointTypes.Color4);\n this._inputs[1].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Vector3 |\n NodeMaterialBlockConnectionPointTypes.Vector4 |\n NodeMaterialBlockConnectionPointTypes.Color3 |\n NodeMaterialBlockConnectionPointTypes.Color4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"RefractBlock\";\n }\n /**\n * Gets the incident component\n */\n get incident() {\n return this._inputs[0];\n }\n /**\n * Gets the normal component\n */\n get normal() {\n return this._inputs[1];\n }\n /**\n * Gets the index of refraction component\n */\n get ior() {\n return this._inputs[2];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = refract(${this.incident.associatedVariableName}.xyz, ${this.normal.associatedVariableName}.xyz, ${this.ior.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.RefractBlock\", RefractBlock);\n//# sourceMappingURL=refractBlock.js.map","import { __decorate } from \"../../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../../nodeMaterialBlockConnectionPoint.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../../nodeMaterialDecorator.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../../nodeMaterialConnectionPointCustomObject.js\";\n/**\n * Block used to implement the sheen module of the PBR material\n */\nexport class SheenBlock extends NodeMaterialBlock {\n /**\n * Create a new SheenBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n /**\n * If true, the sheen effect is layered above the base BRDF with the albedo-scaling technique.\n * It allows the strength of the sheen effect to not depend on the base color of the material,\n * making it easier to setup and tweak the effect\n */\n this.albedoScaling = false;\n /**\n * Defines if the sheen is linked to the sheen color.\n */\n this.linkSheenWithAlbedo = false;\n this._isUnique = true;\n this.registerInput(\"intensity\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"color\", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"roughness\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"sheen\", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"sheen\", this, NodeMaterialConnectionPointDirection.Output, SheenBlock, \"SheenBlock\"));\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"sheenOut\");\n state._excludeVariableName(\"sheenMapData\");\n state._excludeVariableName(\"vSheenColor\");\n state._excludeVariableName(\"vSheenRoughness\");\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"SheenBlock\";\n }\n /**\n * Gets the intensity input component\n */\n get intensity() {\n return this._inputs[0];\n }\n /**\n * Gets the color input component\n */\n get color() {\n return this._inputs[1];\n }\n /**\n * Gets the roughness input component\n */\n get roughness() {\n return this._inputs[2];\n }\n /**\n * Gets the sheen object output component\n */\n get sheen() {\n return this._outputs[0];\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n super.prepareDefines(mesh, nodeMaterial, defines);\n defines.setValue(\"SHEEN\", true);\n defines.setValue(\"SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE\", true, true);\n defines.setValue(\"SHEEN_LINKWITHALBEDO\", this.linkSheenWithAlbedo, true);\n defines.setValue(\"SHEEN_ROUGHNESS\", this.roughness.isConnected, true);\n defines.setValue(\"SHEEN_ALBEDOSCALING\", this.albedoScaling, true);\n }\n /**\n * Gets the main code of the block (fragment side)\n * @param reflectionBlock instance of a ReflectionBlock null if the code must be generated without an active reflection module\n * @returns the shader code\n */\n getCode(reflectionBlock) {\n let code = \"\";\n const color = this.color.isConnected ? this.color.associatedVariableName : \"vec3(1.)\";\n const intensity = this.intensity.isConnected ? this.intensity.associatedVariableName : \"1.\";\n const roughness = this.roughness.isConnected ? this.roughness.associatedVariableName : \"0.\";\n const texture = \"vec4(0.)\";\n code = `#ifdef SHEEN\r\n sheenOutParams sheenOut;\r\n\r\n vec4 vSheenColor = vec4(${color}, ${intensity});\r\n\r\n sheenBlock(\r\n vSheenColor,\r\n #ifdef SHEEN_ROUGHNESS\r\n ${roughness},\r\n #endif\r\n roughness,\r\n #ifdef SHEEN_TEXTURE\r\n ${texture},\r\n 1.0,\r\n #endif\r\n reflectance,\r\n #ifdef SHEEN_LINKWITHALBEDO\r\n baseColor,\r\n surfaceAlbedo,\r\n #endif\r\n #ifdef ENVIRONMENTBRDF\r\n NdotV,\r\n environmentBrdf,\r\n #endif\r\n #if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\r\n AARoughnessFactors,\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._vReflectionMicrosurfaceInfosName},\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._vReflectionInfosName},\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock.reflectionColor},\r\n vLightingIntensity,\r\n #ifdef ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName}\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName},\r\n #else\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._2DSamplerName},\r\n #endif\r\n reflectionOut.reflectionCoords,\r\n NdotVUnclamped,\r\n #ifndef LODBASEDMICROSFURACE\r\n #ifdef ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName}\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName},\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName},\r\n #else\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._2DSamplerName},\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._2DSamplerName},\r\n #endif\r\n #endif\r\n #if !defined(${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName}) && defined(RADIANCEOCCLUSION)\r\n seo,\r\n #endif\r\n #if !defined(${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName}) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName})\r\n eho,\r\n #endif\r\n #endif\r\n sheenOut\r\n );\r\n\r\n #ifdef SHEEN_LINKWITHALBEDO\r\n surfaceAlbedo = sheenOut.surfaceAlbedo;\r\n #endif\r\n #endif\\r\\n`;\n return code;\n }\n _buildBlock(state) {\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n state.sharedData.blocksWithDefines.push(this);\n }\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n codeString += `${this._codeVariableName}.albedoScaling = ${this.albedoScaling};\\r\\n`;\n codeString += `${this._codeVariableName}.linkSheenWithAlbedo = ${this.linkSheenWithAlbedo};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.albedoScaling = this.albedoScaling;\n serializationObject.linkSheenWithAlbedo = this.linkSheenWithAlbedo;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.albedoScaling = serializationObject.albedoScaling;\n this.linkSheenWithAlbedo = serializationObject.linkSheenWithAlbedo;\n }\n}\n__decorate([\n editableInPropertyPage(\"Albedo scaling\", PropertyTypeForEdition.Boolean, \"PROPERTIES\", { notifiers: { update: true } })\n], SheenBlock.prototype, \"albedoScaling\", void 0);\n__decorate([\n editableInPropertyPage(\"Link sheen with albedo\", PropertyTypeForEdition.Boolean, \"PROPERTIES\", { notifiers: { update: true } })\n], SheenBlock.prototype, \"linkSheenWithAlbedo\", void 0);\nRegisterClass(\"BABYLON.SheenBlock\", SheenBlock);\n//# sourceMappingURL=sheenBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to desaturate a color\n */\nexport class DesaturateBlock extends NodeMaterialBlock {\n /**\n * Creates a new DesaturateBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"color\", NodeMaterialBlockConnectionPointTypes.Color3);\n this.registerInput(\"level\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Color3);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"DesaturateBlock\";\n }\n /**\n * Gets the color operand input component\n */\n get color() {\n return this._inputs[0];\n }\n /**\n * Gets the level operand input component\n */\n get level() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n const color = this.color;\n const colorName = color.associatedVariableName;\n const tempMin = state._getFreeVariableName(\"colorMin\");\n const tempMax = state._getFreeVariableName(\"colorMax\");\n const tempMerge = state._getFreeVariableName(\"colorMerge\");\n state.compilationString += `float ${tempMin} = min(min(${colorName}.x, ${colorName}.y), ${colorName}.z);\\r\\n`;\n state.compilationString += `float ${tempMax} = max(max(${colorName}.x, ${colorName}.y), ${colorName}.z);\\r\\n`;\n state.compilationString += `float ${tempMerge} = 0.5 * (${tempMin} + ${tempMax});\\r\\n`;\n state.compilationString +=\n this._declareOutput(output, state) + ` = mix(${colorName}, vec3(${tempMerge}, ${tempMerge}, ${tempMerge}), ${this.level.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.DesaturateBlock\", DesaturateBlock);\n//# sourceMappingURL=desaturateBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../../nodeMaterialBlockConnectionPoint.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../../nodeMaterialConnectionPointCustomObject.js\";\nimport { TBNBlock } from \"../Fragment/TBNBlock.js\";\n/**\n * Block used to implement the anisotropy module of the PBR material\n */\nexport class AnisotropyBlock extends NodeMaterialBlock {\n /**\n * Create a new AnisotropyBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this._tangentCorrectionFactorName = \"\";\n this._isUnique = true;\n this.registerInput(\"intensity\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"direction\", NodeMaterialBlockConnectionPointTypes.Vector2, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"uv\", NodeMaterialBlockConnectionPointTypes.Vector2, true); // need this property and the next one in case there's no PerturbNormal block connected to the main PBR block\n this.registerInput(\"worldTangent\", NodeMaterialBlockConnectionPointTypes.Vector4, true);\n this.registerInput(\"TBN\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject(\"TBN\", this, NodeMaterialConnectionPointDirection.Input, TBNBlock, \"TBNBlock\"));\n this.registerInput(\"roughness\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"anisotropy\", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"anisotropy\", this, NodeMaterialConnectionPointDirection.Output, AnisotropyBlock, \"AnisotropyBlock\"));\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"anisotropicOut\");\n state._excludeVariableName(\"TBN\");\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"AnisotropyBlock\";\n }\n /**\n * Gets the intensity input component\n */\n get intensity() {\n return this._inputs[0];\n }\n /**\n * Gets the direction input component\n */\n get direction() {\n return this._inputs[1];\n }\n /**\n * Gets the uv input component\n */\n get uv() {\n return this._inputs[2];\n }\n /**\n * Gets the worldTangent input component\n */\n get worldTangent() {\n return this._inputs[3];\n }\n /**\n * Gets the TBN input component\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n get TBN() {\n return this._inputs[4];\n }\n /**\n * Gets the roughness input component\n */\n get roughness() {\n return this._inputs[5];\n }\n /**\n * Gets the anisotropy object output component\n */\n get anisotropy() {\n return this._outputs[0];\n }\n _generateTBNSpace(state) {\n let code = \"\";\n const comments = `//${this.name}`;\n const uv = this.uv;\n const worldPosition = this.worldPositionConnectionPoint;\n const worldNormal = this.worldNormalConnectionPoint;\n const worldTangent = this.worldTangent;\n if (!uv.isConnected) {\n // we must set the uv input as optional because we may not end up in this method (in case a PerturbNormal block is linked to the PBR material)\n // in which case uv is not required. But if we do come here, we do need the uv, so we have to raise an error but not with throw, else\n // it will stop the building of the node material and will lead to errors in the editor!\n console.error(\"You must connect the 'uv' input of the Anisotropy block!\");\n }\n state._emitExtension(\"derivatives\", \"#extension GL_OES_standard_derivatives : enable\");\n const tangentReplaceString = { search: /defined\\(TANGENT\\)/g, replace: worldTangent.isConnected ? \"defined(TANGENT)\" : \"defined(IGNORE)\" };\n const TBN = this.TBN;\n if (TBN.isConnected) {\n state.compilationString += `\r\n #ifdef TBNBLOCK\r\n mat3 vTBN = ${TBN.associatedVariableName};\r\n #endif\r\n `;\n }\n else if (worldTangent.isConnected) {\n code += `vec3 tbnNormal = normalize(${worldNormal.associatedVariableName}.xyz);\\r\\n`;\n code += `vec3 tbnTangent = normalize(${worldTangent.associatedVariableName}.xyz);\\r\\n`;\n code += `vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};\\r\\n`;\n code += `mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\\r\\n`;\n }\n code += `\r\n #if defined(${worldTangent.isConnected ? \"TANGENT\" : \"IGNORE\"}) && defined(NORMAL)\r\n mat3 TBN = vTBN;\r\n #else\r\n mat3 TBN = cotangent_frame(${worldNormal.associatedVariableName + \".xyz\"}, ${\"v_\" + worldPosition.associatedVariableName + \".xyz\"}, ${uv.isConnected ? uv.associatedVariableName : \"vec2(0.)\"}, vec2(1., 1.));\r\n #endif\\r\\n`;\n state._emitFunctionFromInclude(\"bumpFragmentMainFunctions\", comments, {\n replaceStrings: [tangentReplaceString],\n });\n return code;\n }\n /**\n * Gets the main code of the block (fragment side)\n * @param state current state of the node material building\n * @param generateTBNSpace if true, the code needed to create the TBN coordinate space is generated\n * @returns the shader code\n */\n getCode(state, generateTBNSpace = false) {\n let code = \"\";\n if (generateTBNSpace) {\n code += this._generateTBNSpace(state);\n }\n const intensity = this.intensity.isConnected ? this.intensity.associatedVariableName : \"1.0\";\n const direction = this.direction.isConnected ? this.direction.associatedVariableName : \"vec2(1., 0.)\";\n const roughness = this.roughness.isConnected ? this.roughness.associatedVariableName : \"0.\";\n code += `anisotropicOutParams anisotropicOut;\r\n anisotropicBlock(\r\n vec3(${direction}, ${intensity}),\r\n ${roughness},\r\n #ifdef ANISOTROPIC_TEXTURE\r\n vec3(0.),\r\n #endif\r\n TBN,\r\n normalW,\r\n viewDirectionW,\r\n anisotropicOut\r\n );\\r\\n`;\n return code;\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n super.prepareDefines(mesh, nodeMaterial, defines);\n defines.setValue(\"ANISOTROPIC\", true);\n defines.setValue(\"ANISOTROPIC_TEXTURE\", false, true);\n defines.setValue(\"ANISOTROPIC_LEGACY\", !this.roughness.isConnected);\n }\n bind(effect, nodeMaterial, mesh) {\n super.bind(effect, nodeMaterial, mesh);\n if (mesh) {\n effect.setFloat(this._tangentCorrectionFactorName, mesh.getWorldMatrix().determinant() < 0 ? -1 : 1);\n }\n }\n _buildBlock(state) {\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n state.sharedData.blocksWithDefines.push(this);\n state.sharedData.bindableBlocks.push(this);\n this._tangentCorrectionFactorName = state._getFreeDefineName(\"tangentCorrectionFactor\");\n state._emitUniformFromString(this._tangentCorrectionFactorName, \"float\");\n }\n return this;\n }\n}\nRegisterClass(\"BABYLON.AnisotropyBlock\", AnisotropyBlock);\n//# sourceMappingURL=anisotropyBlock.js.map","import { __decorate } from \"../../../../tslib.es6.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../../nodeMaterialBlockConnectionPoint.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../../nodeMaterialConnectionPointCustomObject.js\";\nimport { ReflectionTextureBaseBlock } from \"../Dual/reflectionTextureBaseBlock.js\";\nimport { Texture } from \"../../../Textures/texture.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../../nodeMaterialDecorator.js\";\nimport { Scalar } from \"../../../../Maths/math.scalar.js\";\n/**\n * Block used to implement the reflection module of the PBR material\n */\nexport class ReflectionBlock extends ReflectionTextureBaseBlock {\n _onGenerateOnlyFragmentCodeChanged() {\n if (this.position.isConnected) {\n this.generateOnlyFragmentCode = !this.generateOnlyFragmentCode;\n console.error(\"The position input must not be connected to be able to switch!\");\n return false;\n }\n this._setTarget();\n return true;\n }\n _setTarget() {\n super._setTarget();\n this.getInputByName(\"position\").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex;\n if (this.generateOnlyFragmentCode) {\n this.forceIrradianceInFragment = true;\n }\n }\n /**\n * Create a new ReflectionBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name);\n /**\n * Defines if the material uses spherical harmonics vs spherical polynomials for the\n * diffuse part of the IBL.\n */\n this.useSphericalHarmonics = true;\n /**\n * Force the shader to compute irradiance in the fragment shader in order to take bump in account.\n */\n this.forceIrradianceInFragment = false;\n this._isUnique = true;\n this.registerInput(\"position\", NodeMaterialBlockConnectionPointTypes.AutoDetect, false, NodeMaterialBlockTargets.Vertex);\n this.registerInput(\"world\", NodeMaterialBlockConnectionPointTypes.Matrix, false, NodeMaterialBlockTargets.Vertex);\n this.registerInput(\"color\", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"reflection\", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"reflection\", this, NodeMaterialConnectionPointDirection.Output, ReflectionBlock, \"ReflectionBlock\"));\n this.position.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ReflectionBlock\";\n }\n /**\n * Gets the position input component\n */\n get position() {\n return this._inputs[0];\n }\n /**\n * Gets the world position input component\n */\n get worldPosition() {\n return this.worldPositionConnectionPoint;\n }\n /**\n * Gets the world normal input component\n */\n get worldNormal() {\n return this.worldNormalConnectionPoint;\n }\n /**\n * Gets the world input component\n */\n get world() {\n return this._inputs[1];\n }\n /**\n * Gets the camera (or eye) position component\n */\n get cameraPosition() {\n return this.cameraPositionConnectionPoint;\n }\n /**\n * Gets the view input component\n */\n get view() {\n return this.viewConnectionPoint;\n }\n /**\n * Gets the color input component\n */\n get color() {\n return this._inputs[2];\n }\n /**\n * Gets the reflection object output component\n */\n get reflection() {\n return this._outputs[0];\n }\n /**\n * Returns true if the block has a texture (either its own texture or the environment texture from the scene, if set)\n */\n get hasTexture() {\n return !!this._getTexture();\n }\n /**\n * Gets the reflection color (either the name of the variable if the color input is connected, else a default value)\n */\n get reflectionColor() {\n return this.color.isConnected ? this.color.associatedVariableName : \"vec3(1., 1., 1.)\";\n }\n _getTexture() {\n if (this.texture) {\n return this.texture;\n }\n return this._scene.environmentTexture;\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n super.prepareDefines(mesh, nodeMaterial, defines);\n const reflectionTexture = this._getTexture();\n const reflection = reflectionTexture && reflectionTexture.getTextureMatrix;\n defines.setValue(\"REFLECTION\", reflection, true);\n if (!reflection) {\n return;\n }\n defines.setValue(this._defineLODReflectionAlpha, reflectionTexture.lodLevelInAlpha, true);\n defines.setValue(this._defineLinearSpecularReflection, reflectionTexture.linearSpecularLOD, true);\n defines.setValue(this._defineOppositeZ, this._scene.useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ, true);\n defines.setValue(\"SPHERICAL_HARMONICS\", this.useSphericalHarmonics, true);\n defines.setValue(\"GAMMAREFLECTION\", reflectionTexture.gammaSpace, true);\n defines.setValue(\"RGBDREFLECTION\", reflectionTexture.isRGBD, true);\n if (reflectionTexture && reflectionTexture.coordinatesMode !== Texture.SKYBOX_MODE) {\n if (reflectionTexture.isCube) {\n defines.setValue(\"USESPHERICALFROMREFLECTIONMAP\", true);\n defines.setValue(\"USEIRRADIANCEMAP\", false);\n if (this.forceIrradianceInFragment || this._scene.getEngine().getCaps().maxVaryingVectors <= 8) {\n defines.setValue(\"USESPHERICALINVERTEX\", false);\n }\n else {\n defines.setValue(\"USESPHERICALINVERTEX\", true);\n }\n }\n }\n }\n bind(effect, nodeMaterial, mesh, subMesh) {\n super.bind(effect, nodeMaterial, mesh);\n const reflectionTexture = this._getTexture();\n if (!reflectionTexture || !subMesh) {\n return;\n }\n if (reflectionTexture.isCube) {\n effect.setTexture(this._cubeSamplerName, reflectionTexture);\n }\n else {\n effect.setTexture(this._2DSamplerName, reflectionTexture);\n }\n const width = reflectionTexture.getSize().width;\n effect.setFloat3(this._vReflectionMicrosurfaceInfosName, width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);\n effect.setFloat2(this._vReflectionFilteringInfoName, width, Scalar.Log2(width));\n const defines = subMesh.materialDefines;\n const polynomials = reflectionTexture.sphericalPolynomial;\n if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {\n if (defines.SPHERICAL_HARMONICS) {\n const preScaledHarmonics = polynomials.preScaledHarmonics;\n effect.setVector3(\"vSphericalL00\", preScaledHarmonics.l00);\n effect.setVector3(\"vSphericalL1_1\", preScaledHarmonics.l1_1);\n effect.setVector3(\"vSphericalL10\", preScaledHarmonics.l10);\n effect.setVector3(\"vSphericalL11\", preScaledHarmonics.l11);\n effect.setVector3(\"vSphericalL2_2\", preScaledHarmonics.l2_2);\n effect.setVector3(\"vSphericalL2_1\", preScaledHarmonics.l2_1);\n effect.setVector3(\"vSphericalL20\", preScaledHarmonics.l20);\n effect.setVector3(\"vSphericalL21\", preScaledHarmonics.l21);\n effect.setVector3(\"vSphericalL22\", preScaledHarmonics.l22);\n }\n else {\n effect.setFloat3(\"vSphericalX\", polynomials.x.x, polynomials.x.y, polynomials.x.z);\n effect.setFloat3(\"vSphericalY\", polynomials.y.x, polynomials.y.y, polynomials.y.z);\n effect.setFloat3(\"vSphericalZ\", polynomials.z.x, polynomials.z.y, polynomials.z.z);\n effect.setFloat3(\"vSphericalXX_ZZ\", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);\n effect.setFloat3(\"vSphericalYY_ZZ\", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);\n effect.setFloat3(\"vSphericalZZ\", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);\n effect.setFloat3(\"vSphericalXY\", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);\n effect.setFloat3(\"vSphericalYZ\", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);\n effect.setFloat3(\"vSphericalZX\", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);\n }\n }\n }\n /**\n * Gets the code to inject in the vertex shader\n * @param state current state of the node material building\n * @returns the shader code\n */\n handleVertexSide(state) {\n let code = super.handleVertexSide(state);\n state._emitFunctionFromInclude(\"harmonicsFunctions\", `//${this.name}`, {\n replaceStrings: [\n { search: /uniform vec3 vSphericalL00;[\\s\\S]*?uniform vec3 vSphericalL22;/g, replace: \"\" },\n { search: /uniform vec3 vSphericalX;[\\s\\S]*?uniform vec3 vSphericalZX;/g, replace: \"\" },\n ],\n });\n const reflectionVectorName = state._getFreeVariableName(\"reflectionVector\");\n this._vEnvironmentIrradianceName = state._getFreeVariableName(\"vEnvironmentIrradiance\");\n state._emitVaryingFromString(this._vEnvironmentIrradianceName, \"vec3\", \"defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\");\n state._emitUniformFromString(\"vSphericalL00\", \"vec3\", \"SPHERICAL_HARMONICS\");\n state._emitUniformFromString(\"vSphericalL1_1\", \"vec3\", \"SPHERICAL_HARMONICS\");\n state._emitUniformFromString(\"vSphericalL10\", \"vec3\", \"SPHERICAL_HARMONICS\");\n state._emitUniformFromString(\"vSphericalL11\", \"vec3\", \"SPHERICAL_HARMONICS\");\n state._emitUniformFromString(\"vSphericalL2_2\", \"vec3\", \"SPHERICAL_HARMONICS\");\n state._emitUniformFromString(\"vSphericalL2_1\", \"vec3\", \"SPHERICAL_HARMONICS\");\n state._emitUniformFromString(\"vSphericalL20\", \"vec3\", \"SPHERICAL_HARMONICS\");\n state._emitUniformFromString(\"vSphericalL21\", \"vec3\", \"SPHERICAL_HARMONICS\");\n state._emitUniformFromString(\"vSphericalL22\", \"vec3\", \"SPHERICAL_HARMONICS\");\n state._emitUniformFromString(\"vSphericalX\", \"vec3\", \"SPHERICAL_HARMONICS\", true);\n state._emitUniformFromString(\"vSphericalY\", \"vec3\", \"SPHERICAL_HARMONICS\", true);\n state._emitUniformFromString(\"vSphericalZ\", \"vec3\", \"SPHERICAL_HARMONICS\", true);\n state._emitUniformFromString(\"vSphericalXX_ZZ\", \"vec3\", \"SPHERICAL_HARMONICS\", true);\n state._emitUniformFromString(\"vSphericalYY_ZZ\", \"vec3\", \"SPHERICAL_HARMONICS\", true);\n state._emitUniformFromString(\"vSphericalZZ\", \"vec3\", \"SPHERICAL_HARMONICS\", true);\n state._emitUniformFromString(\"vSphericalXY\", \"vec3\", \"SPHERICAL_HARMONICS\", true);\n state._emitUniformFromString(\"vSphericalYZ\", \"vec3\", \"SPHERICAL_HARMONICS\", true);\n state._emitUniformFromString(\"vSphericalZX\", \"vec3\", \"SPHERICAL_HARMONICS\", true);\n code += `#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\r\n vec3 ${reflectionVectorName} = vec3(${this._reflectionMatrixName} * vec4(normalize(${this.worldNormal.associatedVariableName}).xyz, 0)).xyz;\r\n #ifdef ${this._defineOppositeZ}\r\n ${reflectionVectorName}.z *= -1.0;\r\n #endif\r\n ${this._vEnvironmentIrradianceName} = computeEnvironmentIrradiance(${reflectionVectorName});\r\n #endif\\r\\n`;\n return code;\n }\n /**\n * Gets the main code of the block (fragment side)\n * @param state current state of the node material building\n * @param normalVarName name of the existing variable corresponding to the normal\n * @returns the shader code\n */\n getCode(state, normalVarName) {\n let code = \"\";\n this.handleFragmentSideInits(state);\n state._emitFunctionFromInclude(\"harmonicsFunctions\", `//${this.name}`, {\n replaceStrings: [\n { search: /uniform vec3 vSphericalL00;[\\s\\S]*?uniform vec3 vSphericalL22;/g, replace: \"\" },\n { search: /uniform vec3 vSphericalX;[\\s\\S]*?uniform vec3 vSphericalZX;/g, replace: \"\" },\n ],\n });\n state._emitFunction(\"sampleReflection\", `\r\n #ifdef ${this._define3DName}\r\n #define sampleReflection(s, c) textureCube(s, c)\r\n #else\r\n #define sampleReflection(s, c) texture2D(s, c)\r\n #endif\\r\\n`, `//${this.name}`);\n state._emitFunction(\"sampleReflectionLod\", `\r\n #ifdef ${this._define3DName}\r\n #define sampleReflectionLod(s, c, l) textureCubeLodEXT(s, c, l)\r\n #else\r\n #define sampleReflectionLod(s, c, l) texture2DLodEXT(s, c, l)\r\n #endif\\r\\n`, `//${this.name}`);\n const computeReflectionCoordsFunc = `\r\n vec3 computeReflectionCoordsPBR(vec4 worldPos, vec3 worldNormal) {\r\n ${this.handleFragmentSideCodeReflectionCoords(\"worldNormal\", \"worldPos\", true, true)}\r\n return ${this._reflectionVectorName};\r\n }\\r\\n`;\n state._emitFunction(\"computeReflectionCoordsPBR\", computeReflectionCoordsFunc, `//${this.name}`);\n this._vReflectionMicrosurfaceInfosName = state._getFreeVariableName(\"vReflectionMicrosurfaceInfos\");\n state._emitUniformFromString(this._vReflectionMicrosurfaceInfosName, \"vec3\");\n this._vReflectionInfosName = state._getFreeVariableName(\"vReflectionInfos\");\n this._vReflectionFilteringInfoName = state._getFreeVariableName(\"vReflectionFilteringInfo\");\n state._emitUniformFromString(this._vReflectionFilteringInfoName, \"vec2\");\n code += `#ifdef REFLECTION\r\n vec2 ${this._vReflectionInfosName} = vec2(1., 0.);\r\n\r\n reflectionOutParams reflectionOut;\r\n\r\n reflectionBlock(\r\n ${this.generateOnlyFragmentCode ? this._worldPositionNameInFragmentOnlyMode : \"v_\" + this.worldPosition.associatedVariableName}.xyz,\r\n ${normalVarName},\r\n alphaG,\r\n ${this._vReflectionMicrosurfaceInfosName},\r\n ${this._vReflectionInfosName},\r\n ${this.reflectionColor},\r\n #ifdef ANISOTROPIC\r\n anisotropicOut,\r\n #endif\r\n #if defined(${this._defineLODReflectionAlpha}) && !defined(${this._defineSkyboxName})\r\n NdotVUnclamped,\r\n #endif\r\n #ifdef ${this._defineLinearSpecularReflection}\r\n roughness,\r\n #endif\r\n #ifdef ${this._define3DName}\r\n ${this._cubeSamplerName},\r\n #else\r\n ${this._2DSamplerName},\r\n #endif\r\n #if defined(NORMAL) && defined(USESPHERICALINVERTEX)\r\n ${this._vEnvironmentIrradianceName},\r\n #endif\r\n #ifdef USESPHERICALFROMREFLECTIONMAP\r\n #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\r\n ${this._reflectionMatrixName},\r\n #endif\r\n #endif\r\n #ifdef USEIRRADIANCEMAP\r\n irradianceSampler, // ** not handled **\r\n #endif\r\n #ifndef LODBASEDMICROSFURACE\r\n #ifdef ${this._define3DName}\r\n ${this._cubeSamplerName},\r\n ${this._cubeSamplerName},\r\n #else\r\n ${this._2DSamplerName},\r\n ${this._2DSamplerName},\r\n #endif\r\n #endif\r\n #ifdef REALTIME_FILTERING\r\n ${this._vReflectionFilteringInfoName},\r\n #endif\r\n reflectionOut\r\n );\r\n #endif\\r\\n`;\n return code;\n }\n _buildBlock(state) {\n this._scene = state.sharedData.scene;\n if (state.target !== NodeMaterialBlockTargets.Fragment) {\n this._defineLODReflectionAlpha = state._getFreeDefineName(\"LODINREFLECTIONALPHA\");\n this._defineLinearSpecularReflection = state._getFreeDefineName(\"LINEARSPECULARREFLECTION\");\n }\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n if (this.texture) {\n codeString += `${this._codeVariableName}.texture.gammaSpace = ${this.texture.gammaSpace};\\r\\n`;\n }\n codeString += `${this._codeVariableName}.useSphericalHarmonics = ${this.useSphericalHarmonics};\\r\\n`;\n codeString += `${this._codeVariableName}.forceIrradianceInFragment = ${this.forceIrradianceInFragment};\\r\\n`;\n return codeString;\n }\n serialize() {\n var _a, _b;\n const serializationObject = super.serialize();\n serializationObject.useSphericalHarmonics = this.useSphericalHarmonics;\n serializationObject.forceIrradianceInFragment = this.forceIrradianceInFragment;\n serializationObject.gammaSpace = (_b = (_a = this.texture) === null || _a === void 0 ? void 0 : _a.gammaSpace) !== null && _b !== void 0 ? _b : true;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.useSphericalHarmonics = serializationObject.useSphericalHarmonics;\n this.forceIrradianceInFragment = serializationObject.forceIrradianceInFragment;\n if (this.texture) {\n this.texture.gammaSpace = serializationObject.gammaSpace;\n }\n }\n}\n__decorate([\n editableInPropertyPage(\"Spherical Harmonics\", PropertyTypeForEdition.Boolean, \"ADVANCED\", { notifiers: { update: true } })\n], ReflectionBlock.prototype, \"useSphericalHarmonics\", void 0);\n__decorate([\n editableInPropertyPage(\"Force irradiance in fragment\", PropertyTypeForEdition.Boolean, \"ADVANCED\", { notifiers: { update: true } })\n], ReflectionBlock.prototype, \"forceIrradianceInFragment\", void 0);\nRegisterClass(\"BABYLON.ReflectionBlock\", ReflectionBlock);\n//# sourceMappingURL=reflectionBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../../nodeMaterialBlockConnectionPoint.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../../nodeMaterialConnectionPointCustomObject.js\";\nimport { PBRIridescenceConfiguration } from \"../../../../Materials/PBR/pbrIridescenceConfiguration.js\";\n/**\n * Block used to implement the iridescence module of the PBR material\n */\nexport class IridescenceBlock extends NodeMaterialBlock {\n /**\n * Create a new IridescenceBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this._isUnique = true;\n this.registerInput(\"intensity\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"indexOfRefraction\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"thickness\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"iridescence\", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"iridescence\", this, NodeMaterialConnectionPointDirection.Output, IridescenceBlock, \"IridescenceBlock\"));\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"iridescenceOut\");\n state._excludeVariableName(\"vIridescenceParams\");\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"IridescenceBlock\";\n }\n /**\n * Gets the intensity input component\n */\n get intensity() {\n return this._inputs[0];\n }\n /**\n * Gets the indexOfRefraction input component\n */\n get indexOfRefraction() {\n return this._inputs[1];\n }\n /**\n * Gets the thickness input component\n */\n get thickness() {\n return this._inputs[2];\n }\n /**\n * Gets the iridescence object output component\n */\n get iridescence() {\n return this._outputs[0];\n }\n autoConfigure() {\n if (!this.intensity.isConnected) {\n const intensityInput = new InputBlock(\"Iridescence intensity\", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float);\n intensityInput.value = 1;\n intensityInput.output.connectTo(this.intensity);\n const indexOfRefractionInput = new InputBlock(\"Iridescence ior\", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float);\n indexOfRefractionInput.value = 1.3;\n indexOfRefractionInput.output.connectTo(this.indexOfRefraction);\n const thicknessInput = new InputBlock(\"Iridescence thickness\", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float);\n thicknessInput.value = 400;\n thicknessInput.output.connectTo(this.thickness);\n }\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n super.prepareDefines(mesh, nodeMaterial, defines);\n defines.setValue(\"IRIDESCENCE\", true, true);\n defines.setValue(\"IRIDESCENCE_TEXTURE\", false, true);\n defines.setValue(\"IRIDESCENCE_THICKNESS_TEXTURE\", false, true);\n }\n /**\n * Gets the main code of the block (fragment side)\n * @param iridescenceBlock instance of a IridescenceBlock or null if the code must be generated without an active iridescence module\n * @returns the shader code\n */\n static GetCode(iridescenceBlock) {\n let code = \"\";\n const intensityName = (iridescenceBlock === null || iridescenceBlock === void 0 ? void 0 : iridescenceBlock.intensity.isConnected) ? iridescenceBlock.intensity.associatedVariableName : \"1.\";\n const indexOfRefraction = (iridescenceBlock === null || iridescenceBlock === void 0 ? void 0 : iridescenceBlock.indexOfRefraction.isConnected)\n ? iridescenceBlock.indexOfRefraction.associatedVariableName\n : PBRIridescenceConfiguration._DefaultIndexOfRefraction;\n const thickness = (iridescenceBlock === null || iridescenceBlock === void 0 ? void 0 : iridescenceBlock.thickness.isConnected) ? iridescenceBlock.thickness.associatedVariableName : PBRIridescenceConfiguration._DefaultMaximumThickness;\n code += `iridescenceOutParams iridescenceOut;\r\n\r\n #ifdef IRIDESCENCE\r\n iridescenceBlock(\r\n vec4(${intensityName}, ${indexOfRefraction}, 1., ${thickness}),\r\n NdotV,\r\n specularEnvironmentR0,\r\n #ifdef CLEARCOAT\r\n NdotVUnclamped,\r\n #endif\r\n iridescenceOut\r\n );\r\n\r\n float iridescenceIntensity = iridescenceOut.iridescenceIntensity;\r\n specularEnvironmentR0 = iridescenceOut.specularEnvironmentR0;\r\n #endif\\r\\n`;\n return code;\n }\n _buildBlock(state) {\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n state.sharedData.bindableBlocks.push(this);\n state.sharedData.blocksWithDefines.push(this);\n }\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n }\n}\nRegisterClass(\"BABYLON.IridescenceBlock\", IridescenceBlock);\n//# sourceMappingURL=iridescenceBlock.js.map","import { __decorate } from \"../../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../../nodeMaterialBlockConnectionPoint.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../../nodeMaterialConnectionPointCustomObject.js\";\nimport { PBRClearCoatConfiguration } from \"../../../PBR/pbrClearCoatConfiguration.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../../nodeMaterialDecorator.js\";\nimport { TBNBlock } from \"../Fragment/TBNBlock.js\";\n/**\n * Block used to implement the clear coat module of the PBR material\n */\nexport class ClearCoatBlock extends NodeMaterialBlock {\n /**\n * Create a new ClearCoatBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this._tangentCorrectionFactorName = \"\";\n /**\n * Defines if the F0 value should be remapped to account for the interface change in the material.\n */\n this.remapF0OnInterfaceChange = true;\n this._isUnique = true;\n this.registerInput(\"intensity\", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"roughness\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"indexOfRefraction\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"normalMapColor\", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"uv\", NodeMaterialBlockConnectionPointTypes.Vector2, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"tintColor\", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"tintAtDistance\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"tintThickness\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"worldTangent\", NodeMaterialBlockConnectionPointTypes.Vector4, true);\n this.registerInput(\"worldNormal\", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);\n this.worldNormal.addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color4 | NodeMaterialBlockConnectionPointTypes.Vector4 | NodeMaterialBlockConnectionPointTypes.Vector3);\n this.registerInput(\"TBN\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject(\"TBN\", this, NodeMaterialConnectionPointDirection.Input, TBNBlock, \"TBNBlock\"));\n this.registerOutput(\"clearcoat\", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"clearcoat\", this, NodeMaterialConnectionPointDirection.Output, ClearCoatBlock, \"ClearCoatBlock\"));\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"clearcoatOut\");\n state._excludeVariableName(\"vClearCoatParams\");\n state._excludeVariableName(\"vClearCoatTintParams\");\n state._excludeVariableName(\"vClearCoatRefractionParams\");\n state._excludeVariableName(\"vClearCoatTangentSpaceParams\");\n state._excludeVariableName(\"vGeometricNormaClearCoatW\");\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ClearCoatBlock\";\n }\n /**\n * Gets the intensity input component\n */\n get intensity() {\n return this._inputs[0];\n }\n /**\n * Gets the roughness input component\n */\n get roughness() {\n return this._inputs[1];\n }\n /**\n * Gets the ior input component\n */\n get indexOfRefraction() {\n return this._inputs[2];\n }\n /**\n * Gets the bump texture input component\n */\n get normalMapColor() {\n return this._inputs[3];\n }\n /**\n * Gets the uv input component\n */\n get uv() {\n return this._inputs[4];\n }\n /**\n * Gets the tint color input component\n */\n get tintColor() {\n return this._inputs[5];\n }\n /**\n * Gets the tint \"at distance\" input component\n */\n get tintAtDistance() {\n return this._inputs[6];\n }\n /**\n * Gets the tint thickness input component\n */\n get tintThickness() {\n return this._inputs[7];\n }\n /**\n * Gets the world tangent input component\n */\n get worldTangent() {\n return this._inputs[8];\n }\n /**\n * Gets the world normal input component\n */\n get worldNormal() {\n return this._inputs[9];\n }\n /**\n * Gets the TBN input component\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n get TBN() {\n return this._inputs[10];\n }\n /**\n * Gets the clear coat object output component\n */\n get clearcoat() {\n return this._outputs[0];\n }\n autoConfigure() {\n if (!this.intensity.isConnected) {\n const intensityInput = new InputBlock(\"ClearCoat intensity\", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float);\n intensityInput.value = 1;\n intensityInput.output.connectTo(this.intensity);\n }\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n super.prepareDefines(mesh, nodeMaterial, defines);\n defines.setValue(\"CLEARCOAT\", true);\n defines.setValue(\"CLEARCOAT_TEXTURE\", false, true);\n defines.setValue(\"CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE\", true, true);\n defines.setValue(\"CLEARCOAT_TINT\", this.tintColor.isConnected || this.tintThickness.isConnected || this.tintAtDistance.isConnected, true);\n defines.setValue(\"CLEARCOAT_BUMP\", this.normalMapColor.isConnected, true);\n defines.setValue(\"CLEARCOAT_DEFAULTIOR\", this.indexOfRefraction.isConnected ? this.indexOfRefraction.connectInputBlock.value === PBRClearCoatConfiguration._DefaultIndexOfRefraction : true, true);\n defines.setValue(\"CLEARCOAT_REMAP_F0\", this.remapF0OnInterfaceChange, true);\n }\n bind(effect, nodeMaterial, mesh) {\n var _a, _b;\n super.bind(effect, nodeMaterial, mesh);\n // Clear Coat Refraction params\n const indexOfRefraction = (_b = (_a = this.indexOfRefraction.connectInputBlock) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : PBRClearCoatConfiguration._DefaultIndexOfRefraction;\n const a = 1 - indexOfRefraction;\n const b = 1 + indexOfRefraction;\n const f0 = Math.pow(-a / b, 2); // Schlicks approx: (ior1 - ior2) / (ior1 + ior2) where ior2 for air is close to vacuum = 1.\n const eta = 1 / indexOfRefraction;\n effect.setFloat4(\"vClearCoatRefractionParams\", f0, eta, a, b);\n // Clear Coat tangent space params\n const mainPBRBlock = this.clearcoat.hasEndpoints ? this.clearcoat.endpoints[0].ownerBlock : null;\n const perturbedNormalBlock = (mainPBRBlock === null || mainPBRBlock === void 0 ? void 0 : mainPBRBlock.perturbedNormal.isConnected) ? mainPBRBlock.perturbedNormal.connectedPoint.ownerBlock : null;\n if (this._scene._mirroredCameraPosition) {\n effect.setFloat2(\"vClearCoatTangentSpaceParams\", (perturbedNormalBlock === null || perturbedNormalBlock === void 0 ? void 0 : perturbedNormalBlock.invertX) ? 1.0 : -1.0, (perturbedNormalBlock === null || perturbedNormalBlock === void 0 ? void 0 : perturbedNormalBlock.invertY) ? 1.0 : -1.0);\n }\n else {\n effect.setFloat2(\"vClearCoatTangentSpaceParams\", (perturbedNormalBlock === null || perturbedNormalBlock === void 0 ? void 0 : perturbedNormalBlock.invertX) ? -1.0 : 1.0, (perturbedNormalBlock === null || perturbedNormalBlock === void 0 ? void 0 : perturbedNormalBlock.invertY) ? -1.0 : 1.0);\n }\n if (mesh) {\n effect.setFloat(this._tangentCorrectionFactorName, mesh.getWorldMatrix().determinant() < 0 ? -1 : 1);\n }\n }\n _generateTBNSpace(state, worldPositionVarName, worldNormalVarName) {\n let code = \"\";\n const comments = `//${this.name}`;\n const worldTangent = this.worldTangent;\n state._emitExtension(\"derivatives\", \"#extension GL_OES_standard_derivatives : enable\");\n const tangentReplaceString = { search: /defined\\(TANGENT\\)/g, replace: worldTangent.isConnected ? \"defined(TANGENT)\" : \"defined(IGNORE)\" };\n const TBN = this.TBN;\n if (TBN.isConnected) {\n state.compilationString += `\r\n #ifdef TBNBLOCK\r\n mat3 vTBN = ${TBN.associatedVariableName};\r\n #endif\r\n `;\n }\n else if (worldTangent.isConnected) {\n code += `vec3 tbnNormal = normalize(${worldNormalVarName}.xyz);\\r\\n`;\n code += `vec3 tbnTangent = normalize(${worldTangent.associatedVariableName}.xyz);\\r\\n`;\n code += `vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName};\\r\\n`;\n code += `mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\\r\\n`;\n }\n state._emitFunctionFromInclude(\"bumpFragmentMainFunctions\", comments, {\n replaceStrings: [tangentReplaceString],\n });\n return code;\n }\n /**\n * Gets the main code of the block (fragment side)\n * @param state current state of the node material building\n * @param ccBlock instance of a ClearCoatBlock or null if the code must be generated without an active clear coat module\n * @param reflectionBlock instance of a ReflectionBlock null if the code must be generated without an active reflection module\n * @param worldPosVarName name of the variable holding the world position\n * @param generateTBNSpace if true, the code needed to create the TBN coordinate space is generated\n * @param vTBNAvailable indicate that the vTBN variable is already existing because it has already been generated by another block (PerturbNormal or Anisotropy)\n * @param worldNormalVarName name of the variable holding the world normal\n * @returns the shader code\n */\n static GetCode(state, ccBlock, reflectionBlock, worldPosVarName, generateTBNSpace, vTBNAvailable, worldNormalVarName) {\n let code = \"\";\n const intensity = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.intensity.isConnected) ? ccBlock.intensity.associatedVariableName : \"1.\";\n const roughness = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.roughness.isConnected) ? ccBlock.roughness.associatedVariableName : \"0.\";\n const normalMapColor = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.normalMapColor.isConnected) ? ccBlock.normalMapColor.associatedVariableName : \"vec3(0.)\";\n const uv = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.uv.isConnected) ? ccBlock.uv.associatedVariableName : \"vec2(0.)\";\n const tintColor = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.tintColor.isConnected) ? ccBlock.tintColor.associatedVariableName : \"vec3(1.)\";\n const tintThickness = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.tintThickness.isConnected) ? ccBlock.tintThickness.associatedVariableName : \"1.\";\n const tintAtDistance = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.tintAtDistance.isConnected) ? ccBlock.tintAtDistance.associatedVariableName : \"1.\";\n const tintTexture = \"vec4(0.)\";\n if (ccBlock) {\n state._emitUniformFromString(\"vClearCoatRefractionParams\", \"vec4\");\n state._emitUniformFromString(\"vClearCoatTangentSpaceParams\", \"vec2\");\n const normalShading = ccBlock.worldNormal;\n code += `vec3 vGeometricNormaClearCoatW = ${normalShading.isConnected ? \"normalize(\" + normalShading.associatedVariableName + \".xyz)\" : \"geometricNormalW\"};\\r\\n`;\n }\n else {\n code += `vec3 vGeometricNormaClearCoatW = geometricNormalW;\\r\\n`;\n }\n if (generateTBNSpace && ccBlock) {\n code += ccBlock._generateTBNSpace(state, worldPosVarName, worldNormalVarName);\n vTBNAvailable = ccBlock.worldTangent.isConnected;\n }\n code += `clearcoatOutParams clearcoatOut;\r\n\r\n #ifdef CLEARCOAT\r\n vec2 vClearCoatParams = vec2(${intensity}, ${roughness});\r\n vec4 vClearCoatTintParams = vec4(${tintColor}, ${tintThickness});\r\n\r\n clearcoatBlock(\r\n ${worldPosVarName}.xyz,\r\n vGeometricNormaClearCoatW,\r\n viewDirectionW,\r\n vClearCoatParams,\r\n specularEnvironmentR0,\r\n #ifdef CLEARCOAT_TEXTURE\r\n vec2(0.),\r\n #endif\r\n #ifdef CLEARCOAT_TINT\r\n vClearCoatTintParams,\r\n ${tintAtDistance},\r\n vClearCoatRefractionParams,\r\n #ifdef CLEARCOAT_TINT_TEXTURE\r\n ${tintTexture},\r\n #endif\r\n #endif\r\n #ifdef CLEARCOAT_BUMP\r\n vec2(0., 1.),\r\n vec4(${normalMapColor}, 0.),\r\n ${uv},\r\n #if defined(${vTBNAvailable ? \"TANGENT\" : \"IGNORE\"}) && defined(NORMAL)\r\n vTBN,\r\n #else\r\n vClearCoatTangentSpaceParams,\r\n #endif\r\n #ifdef OBJECTSPACE_NORMALMAP\r\n normalMatrix,\r\n #endif\r\n #endif\r\n #if defined(FORCENORMALFORWARD) && defined(NORMAL)\r\n faceNormal,\r\n #endif\r\n #ifdef REFLECTION\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._vReflectionMicrosurfaceInfosName},\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._vReflectionInfosName},\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock.reflectionColor},\r\n vLightingIntensity,\r\n #ifdef ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName}\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName},\r\n #else\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._2DSamplerName},\r\n #endif\r\n #ifndef LODBASEDMICROSFURACE\r\n #ifdef ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName}\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName},\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName},\r\n #else\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._2DSamplerName},\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._2DSamplerName},\r\n #endif\r\n #endif\r\n #endif\r\n #if defined(ENVIRONMENTBRDF) && !defined(${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName})\r\n #ifdef RADIANCEOCCLUSION\r\n ambientMonochrome,\r\n #endif\r\n #endif\r\n #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING)\r\n (gl_FrontFacing ? 1. : -1.),\r\n #endif\r\n clearcoatOut\r\n );\r\n #else\r\n clearcoatOut.specularEnvironmentR0 = specularEnvironmentR0;\r\n #endif\\r\\n`;\n return code;\n }\n _buildBlock(state) {\n this._scene = state.sharedData.scene;\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n state.sharedData.bindableBlocks.push(this);\n state.sharedData.blocksWithDefines.push(this);\n this._tangentCorrectionFactorName = state._getFreeDefineName(\"tangentCorrectionFactor\");\n state._emitUniformFromString(this._tangentCorrectionFactorName, \"float\");\n }\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n codeString += `${this._codeVariableName}.remapF0OnInterfaceChange = ${this.remapF0OnInterfaceChange};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.remapF0OnInterfaceChange = this.remapF0OnInterfaceChange;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n var _a;\n super._deserialize(serializationObject, scene, rootUrl);\n this.remapF0OnInterfaceChange = (_a = serializationObject.remapF0OnInterfaceChange) !== null && _a !== void 0 ? _a : true;\n }\n}\n__decorate([\n editableInPropertyPage(\"Remap F0 on interface change\", PropertyTypeForEdition.Boolean, \"ADVANCED\")\n], ClearCoatBlock.prototype, \"remapF0OnInterfaceChange\", void 0);\nRegisterClass(\"BABYLON.ClearCoatBlock\", ClearCoatBlock);\n//# sourceMappingURL=clearCoatBlock.js.map","import { __decorate } from \"../../../../tslib.es6.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../../nodeMaterialBlockConnectionPoint.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../../nodeMaterialConnectionPointCustomObject.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../../nodeMaterialDecorator.js\";\nimport { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { CubeTexture } from \"../../../Textures/cubeTexture.js\";\nimport { Texture } from \"../../../Textures/texture.js\";\nimport { NodeMaterialSystemValues } from \"../../Enums/nodeMaterialSystemValues.js\";\nimport { Scalar } from \"../../../../Maths/math.scalar.js\";\n/**\n * Block used to implement the refraction part of the sub surface module of the PBR material\n */\nexport class RefractionBlock extends NodeMaterialBlock {\n /**\n * Create a new RefractionBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n /**\n * This parameters will make the material used its opacity to control how much it is refracting against not.\n * Materials half opaque for instance using refraction could benefit from this control.\n */\n this.linkRefractionWithTransparency = false;\n /**\n * Controls if refraction needs to be inverted on Y. This could be useful for procedural texture.\n */\n this.invertRefractionY = false;\n /**\n * Controls if refraction needs to be inverted on Y. This could be useful for procedural texture.\n */\n this.useThicknessAsDepth = false;\n this._isUnique = true;\n this.registerInput(\"intensity\", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"tintAtDistance\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"volumeIndexOfRefraction\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"refraction\", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"refraction\", this, NodeMaterialConnectionPointDirection.Output, RefractionBlock, \"RefractionBlock\"));\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"vRefractionPosition\");\n state._excludeVariableName(\"vRefractionSize\");\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"RefractionBlock\";\n }\n /**\n * Gets the intensity input component\n */\n get intensity() {\n return this._inputs[0];\n }\n /**\n * Gets the tint at distance input component\n */\n get tintAtDistance() {\n return this._inputs[1];\n }\n /**\n * Gets the volume index of refraction input component\n */\n get volumeIndexOfRefraction() {\n return this._inputs[2];\n }\n /**\n * Gets the view input component\n */\n get view() {\n return this.viewConnectionPoint;\n }\n /**\n * Gets the refraction object output component\n */\n get refraction() {\n return this._outputs[0];\n }\n /**\n * Returns true if the block has a texture\n */\n get hasTexture() {\n return !!this._getTexture();\n }\n _getTexture() {\n if (this.texture) {\n return this.texture;\n }\n return this._scene.environmentTexture;\n }\n autoConfigure(material) {\n if (!this.intensity.isConnected) {\n const intensityInput = new InputBlock(\"Refraction intensity\", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float);\n intensityInput.value = 1;\n intensityInput.output.connectTo(this.intensity);\n }\n if (this.view && !this.view.isConnected) {\n let viewInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.View);\n if (!viewInput) {\n viewInput = new InputBlock(\"view\");\n viewInput.setAsSystemValue(NodeMaterialSystemValues.View);\n }\n viewInput.output.connectTo(this.view);\n }\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n super.prepareDefines(mesh, nodeMaterial, defines);\n const refractionTexture = this._getTexture();\n const refraction = refractionTexture && refractionTexture.getTextureMatrix;\n defines.setValue(\"SS_REFRACTION\", refraction, true);\n if (!refraction) {\n return;\n }\n defines.setValue(this._define3DName, refractionTexture.isCube, true);\n defines.setValue(this._defineLODRefractionAlpha, refractionTexture.lodLevelInAlpha, true);\n defines.setValue(this._defineLinearSpecularRefraction, refractionTexture.linearSpecularLOD, true);\n defines.setValue(this._defineOppositeZ, this._scene.useRightHandedSystem && refractionTexture.isCube ? !refractionTexture.invertZ : refractionTexture.invertZ, true);\n defines.setValue(\"SS_LINKREFRACTIONTOTRANSPARENCY\", this.linkRefractionWithTransparency, true);\n defines.setValue(\"SS_GAMMAREFRACTION\", refractionTexture.gammaSpace, true);\n defines.setValue(\"SS_RGBDREFRACTION\", refractionTexture.isRGBD, true);\n defines.setValue(\"SS_USE_LOCAL_REFRACTIONMAP_CUBIC\", refractionTexture.boundingBoxSize ? true : false, true);\n defines.setValue(\"SS_USE_THICKNESS_AS_DEPTH\", this.useThicknessAsDepth, true);\n }\n isReady() {\n const texture = this._getTexture();\n if (texture && !texture.isReadyOrNotBlocking()) {\n return false;\n }\n return true;\n }\n bind(effect, nodeMaterial, mesh) {\n var _a, _b, _c, _d;\n super.bind(effect, nodeMaterial, mesh);\n const refractionTexture = this._getTexture();\n if (!refractionTexture) {\n return;\n }\n if (refractionTexture.isCube) {\n effect.setTexture(this._cubeSamplerName, refractionTexture);\n }\n else {\n effect.setTexture(this._2DSamplerName, refractionTexture);\n }\n effect.setMatrix(this._refractionMatrixName, refractionTexture.getRefractionTextureMatrix());\n let depth = 1.0;\n if (!refractionTexture.isCube) {\n if (refractionTexture.depth) {\n depth = refractionTexture.depth;\n }\n }\n const indexOfRefraction = (_d = (_b = (_a = this.volumeIndexOfRefraction.connectInputBlock) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : (_c = this.indexOfRefractionConnectionPoint.connectInputBlock) === null || _c === void 0 ? void 0 : _c.value) !== null && _d !== void 0 ? _d : 1.5;\n effect.setFloat4(this._vRefractionInfosName, refractionTexture.level, 1 / indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);\n effect.setFloat4(this._vRefractionMicrosurfaceInfosName, refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset, 1 / indexOfRefraction);\n const width = refractionTexture.getSize().width;\n effect.setFloat2(this._vRefractionFilteringInfoName, width, Scalar.Log2(width));\n if (refractionTexture.boundingBoxSize) {\n const cubeTexture = refractionTexture;\n effect.setVector3(\"vRefractionPosition\", cubeTexture.boundingBoxPosition);\n effect.setVector3(\"vRefractionSize\", cubeTexture.boundingBoxSize);\n }\n }\n /**\n * Gets the main code of the block (fragment side)\n * @param state current state of the node material building\n * @returns the shader code\n */\n getCode(state) {\n const code = \"\";\n state.sharedData.blockingBlocks.push(this);\n state.sharedData.textureBlocks.push(this);\n // Samplers\n this._cubeSamplerName = state._getFreeVariableName(this.name + \"CubeSampler\");\n state.samplers.push(this._cubeSamplerName);\n this._2DSamplerName = state._getFreeVariableName(this.name + \"2DSampler\");\n state.samplers.push(this._2DSamplerName);\n this._define3DName = state._getFreeDefineName(\"SS_REFRACTIONMAP_3D\");\n state._samplerDeclaration += `#ifdef ${this._define3DName}\\r\\n`;\n state._samplerDeclaration += `uniform samplerCube ${this._cubeSamplerName};\\r\\n`;\n state._samplerDeclaration += `#else\\r\\n`;\n state._samplerDeclaration += `uniform sampler2D ${this._2DSamplerName};\\r\\n`;\n state._samplerDeclaration += `#endif\\r\\n`;\n // Fragment\n state.sharedData.blocksWithDefines.push(this);\n state.sharedData.bindableBlocks.push(this);\n this._defineLODRefractionAlpha = state._getFreeDefineName(\"SS_LODINREFRACTIONALPHA\");\n this._defineLinearSpecularRefraction = state._getFreeDefineName(\"SS_LINEARSPECULARREFRACTION\");\n this._defineOppositeZ = state._getFreeDefineName(\"SS_REFRACTIONMAP_OPPOSITEZ\");\n this._refractionMatrixName = state._getFreeVariableName(\"refractionMatrix\");\n state._emitUniformFromString(this._refractionMatrixName, \"mat4\");\n state._emitFunction(\"sampleRefraction\", `\r\n #ifdef ${this._define3DName}\r\n #define sampleRefraction(s, c) textureCube(s, c)\r\n #else\r\n #define sampleRefraction(s, c) texture2D(s, c)\r\n #endif\\r\\n`, `//${this.name}`);\n state._emitFunction(\"sampleRefractionLod\", `\r\n #ifdef ${this._define3DName}\r\n #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l)\r\n #else\r\n #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l)\r\n #endif\\r\\n`, `//${this.name}`);\n this._vRefractionMicrosurfaceInfosName = state._getFreeVariableName(\"vRefractionMicrosurfaceInfos\");\n state._emitUniformFromString(this._vRefractionMicrosurfaceInfosName, \"vec4\");\n this._vRefractionInfosName = state._getFreeVariableName(\"vRefractionInfos\");\n state._emitUniformFromString(this._vRefractionInfosName, \"vec4\");\n this._vRefractionFilteringInfoName = state._getFreeVariableName(\"vRefractionFilteringInfo\");\n state._emitUniformFromString(this._vRefractionFilteringInfoName, \"vec2\");\n state._emitUniformFromString(\"vRefractionPosition\", \"vec3\");\n state._emitUniformFromString(\"vRefractionSize\", \"vec3\");\n return code;\n }\n _buildBlock(state) {\n this._scene = state.sharedData.scene;\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n if (this.texture) {\n if (this.texture.isCube) {\n codeString = `${this._codeVariableName}.texture = new BABYLON.CubeTexture(\"${this.texture.name}\");\\r\\n`;\n }\n else {\n codeString = `${this._codeVariableName}.texture = new BABYLON.Texture(\"${this.texture.name}\");\\r\\n`;\n }\n codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\\r\\n`;\n }\n codeString += `${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency};\\r\\n`;\n codeString += `${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY};\\r\\n`;\n codeString += `${this._codeVariableName}.useThicknessAsDepth = ${this.useThicknessAsDepth};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n if (this.texture && !this.texture.isRenderTarget) {\n serializationObject.texture = this.texture.serialize();\n }\n serializationObject.linkRefractionWithTransparency = this.linkRefractionWithTransparency;\n serializationObject.invertRefractionY = this.invertRefractionY;\n serializationObject.useThicknessAsDepth = this.useThicknessAsDepth;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n if (serializationObject.texture) {\n rootUrl = serializationObject.texture.url.indexOf(\"data:\") === 0 ? \"\" : rootUrl;\n if (serializationObject.texture.isCube) {\n this.texture = CubeTexture.Parse(serializationObject.texture, scene, rootUrl);\n }\n else {\n this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl);\n }\n }\n this.linkRefractionWithTransparency = serializationObject.linkRefractionWithTransparency;\n this.invertRefractionY = serializationObject.invertRefractionY;\n this.useThicknessAsDepth = !!serializationObject.useThicknessAsDepth;\n }\n}\n__decorate([\n editableInPropertyPage(\"Link refraction to transparency\", PropertyTypeForEdition.Boolean, \"ADVANCED\", { notifiers: { update: true } })\n], RefractionBlock.prototype, \"linkRefractionWithTransparency\", void 0);\n__decorate([\n editableInPropertyPage(\"Invert refraction Y\", PropertyTypeForEdition.Boolean, \"ADVANCED\", { notifiers: { update: true } })\n], RefractionBlock.prototype, \"invertRefractionY\", void 0);\n__decorate([\n editableInPropertyPage(\"Use thickness as depth\", PropertyTypeForEdition.Boolean, \"ADVANCED\", { notifiers: { update: true } })\n], RefractionBlock.prototype, \"useThicknessAsDepth\", void 0);\nRegisterClass(\"BABYLON.RefractionBlock\", RefractionBlock);\n//# sourceMappingURL=refractionBlock.js.map","import { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../../nodeMaterialBlockConnectionPoint.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../../nodeMaterialConnectionPointCustomObject.js\";\nimport { RefractionBlock } from \"./refractionBlock.js\";\n/**\n * Block used to implement the sub surface module of the PBR material\n */\nexport class SubSurfaceBlock extends NodeMaterialBlock {\n /**\n * Create a new SubSurfaceBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Fragment);\n this._isUnique = true;\n this.registerInput(\"thickness\", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"tintColor\", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"translucencyIntensity\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"translucencyDiffusionDist\", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"refraction\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"refraction\", this, NodeMaterialConnectionPointDirection.Input, RefractionBlock, \"RefractionBlock\"));\n this.registerOutput(\"subsurface\", NodeMaterialBlockConnectionPointTypes.Object, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"subsurface\", this, NodeMaterialConnectionPointDirection.Output, SubSurfaceBlock, \"SubSurfaceBlock\"));\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"subSurfaceOut\");\n state._excludeVariableName(\"vThicknessParam\");\n state._excludeVariableName(\"vTintColor\");\n state._excludeVariableName(\"vSubSurfaceIntensity\");\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"SubSurfaceBlock\";\n }\n /**\n * Gets the thickness component\n */\n get thickness() {\n return this._inputs[0];\n }\n /**\n * Gets the tint color input component\n */\n get tintColor() {\n return this._inputs[1];\n }\n /**\n * Gets the translucency intensity input component\n */\n get translucencyIntensity() {\n return this._inputs[2];\n }\n /**\n * Gets the translucency diffusion distance input component\n */\n get translucencyDiffusionDist() {\n return this._inputs[3];\n }\n /**\n * Gets the refraction object parameters\n */\n get refraction() {\n return this._inputs[4];\n }\n /**\n * Gets the sub surface object output component\n */\n get subsurface() {\n return this._outputs[0];\n }\n autoConfigure() {\n if (!this.thickness.isConnected) {\n const thicknessInput = new InputBlock(\"SubSurface thickness\", NodeMaterialBlockTargets.Fragment, NodeMaterialBlockConnectionPointTypes.Float);\n thicknessInput.value = 0;\n thicknessInput.output.connectTo(this.thickness);\n }\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n super.prepareDefines(mesh, nodeMaterial, defines);\n const translucencyEnabled = this.translucencyDiffusionDist.isConnected || this.translucencyIntensity.isConnected;\n defines.setValue(\"SUBSURFACE\", translucencyEnabled || this.refraction.isConnected, true);\n defines.setValue(\"SS_TRANSLUCENCY\", translucencyEnabled, true);\n defines.setValue(\"SS_THICKNESSANDMASK_TEXTURE\", false, true);\n defines.setValue(\"SS_REFRACTIONINTENSITY_TEXTURE\", false, true);\n defines.setValue(\"SS_TRANSLUCENCYINTENSITY_TEXTURE\", false, true);\n defines.setValue(\"SS_MASK_FROM_THICKNESS_TEXTURE\", false, true);\n defines.setValue(\"SS_USE_GLTF_TEXTURES\", false, true);\n }\n /**\n * Gets the main code of the block (fragment side)\n * @param state current state of the node material building\n * @param ssBlock instance of a SubSurfaceBlock or null if the code must be generated without an active sub surface module\n * @param reflectionBlock instance of a ReflectionBlock null if the code must be generated without an active reflection module\n * @param worldPosVarName name of the variable holding the world position\n * @returns the shader code\n */\n static GetCode(state, ssBlock, reflectionBlock, worldPosVarName) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;\n let code = \"\";\n const thickness = (ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.thickness.isConnected) ? ssBlock.thickness.associatedVariableName : \"0.\";\n const tintColor = (ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.tintColor.isConnected) ? ssBlock.tintColor.associatedVariableName : \"vec3(1.)\";\n const translucencyIntensity = (ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.translucencyIntensity.isConnected) ? ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.translucencyIntensity.associatedVariableName : \"1.\";\n const translucencyDiffusionDistance = (ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.translucencyDiffusionDist.isConnected) ? ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.translucencyDiffusionDist.associatedVariableName : \"vec3(1.)\";\n const refractionBlock = ((ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.refraction.isConnected) ? (_a = ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.refraction.connectedPoint) === null || _a === void 0 ? void 0 : _a.ownerBlock : null);\n const refractionTintAtDistance = (refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock.tintAtDistance.isConnected) ? refractionBlock.tintAtDistance.associatedVariableName : \"1.\";\n const refractionIntensity = (refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock.intensity.isConnected) ? refractionBlock.intensity.associatedVariableName : \"1.\";\n const refractionView = (refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock.view.isConnected) ? refractionBlock.view.associatedVariableName : \"\";\n code += (_b = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock.getCode(state)) !== null && _b !== void 0 ? _b : \"\";\n code += `subSurfaceOutParams subSurfaceOut;\r\n\r\n #ifdef SUBSURFACE\r\n vec2 vThicknessParam = vec2(0., ${thickness});\r\n vec4 vTintColor = vec4(${tintColor}, ${refractionTintAtDistance});\r\n vec3 vSubSurfaceIntensity = vec3(${refractionIntensity}, ${translucencyIntensity}, 0.);\r\n\r\n subSurfaceBlock(\r\n vSubSurfaceIntensity,\r\n vThicknessParam,\r\n vTintColor,\r\n normalW,\r\n specularEnvironmentReflectance,\r\n #ifdef SS_THICKNESSANDMASK_TEXTURE\r\n vec4(0.),\r\n #endif\r\n #ifdef REFLECTION\r\n #ifdef SS_TRANSLUCENCY\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._reflectionMatrixName},\r\n #ifdef USESPHERICALFROMREFLECTIONMAP\r\n #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\r\n reflectionOut.irradianceVector,\r\n #endif\r\n #if defined(REALTIME_FILTERING)\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName},\r\n ${reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._vReflectionFilteringInfoName},\r\n #endif\r\n #endif\r\n #ifdef USEIRRADIANCEMAP\r\n irradianceSampler,\r\n #endif\r\n #endif\r\n #endif\r\n #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY)\r\n surfaceAlbedo,\r\n #endif\r\n #ifdef SS_REFRACTION\r\n ${worldPosVarName}.xyz,\r\n viewDirectionW,\r\n ${refractionView},\r\n ${(_c = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._vRefractionInfosName) !== null && _c !== void 0 ? _c : \"\"},\r\n ${(_d = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._refractionMatrixName) !== null && _d !== void 0 ? _d : \"\"},\r\n ${(_e = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._vRefractionMicrosurfaceInfosName) !== null && _e !== void 0 ? _e : \"\"},\r\n vLightingIntensity,\r\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\r\n alpha,\r\n #endif\r\n #ifdef ${(_f = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._defineLODRefractionAlpha) !== null && _f !== void 0 ? _f : \"IGNORE\"}\r\n NdotVUnclamped,\r\n #endif\r\n #ifdef ${(_g = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._defineLinearSpecularRefraction) !== null && _g !== void 0 ? _g : \"IGNORE\"}\r\n roughness,\r\n #endif\r\n alphaG,\r\n #ifdef ${(_h = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._define3DName) !== null && _h !== void 0 ? _h : \"IGNORE\"}\r\n ${(_j = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._cubeSamplerName) !== null && _j !== void 0 ? _j : \"\"},\r\n #else\r\n ${(_k = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._2DSamplerName) !== null && _k !== void 0 ? _k : \"\"},\r\n #endif\r\n #ifndef LODBASEDMICROSFURACE\r\n #ifdef ${(_l = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._define3DName) !== null && _l !== void 0 ? _l : \"IGNORE\"}\r\n ${(_m = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._cubeSamplerName) !== null && _m !== void 0 ? _m : \"\"},\r\n ${(_o = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._cubeSamplerName) !== null && _o !== void 0 ? _o : \"\"},\r\n #else\r\n ${(_p = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._2DSamplerName) !== null && _p !== void 0 ? _p : \"\"},\r\n ${(_q = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._2DSamplerName) !== null && _q !== void 0 ? _q : \"\"},\r\n #endif\r\n #endif\r\n #ifdef ANISOTROPIC\r\n anisotropicOut,\r\n #endif\r\n #ifdef REALTIME_FILTERING\r\n ${(_r = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._vRefractionFilteringInfoName) !== null && _r !== void 0 ? _r : \"\"},\r\n #endif\r\n #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC\r\n vRefractionPosition,\r\n vRefractionSize,\r\n #endif\r\n #endif\r\n #ifdef SS_TRANSLUCENCY\r\n ${translucencyDiffusionDistance},\r\n #endif\r\n subSurfaceOut\r\n );\r\n\r\n #ifdef SS_REFRACTION\r\n surfaceAlbedo = subSurfaceOut.surfaceAlbedo;\r\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\r\n alpha = subSurfaceOut.alpha;\r\n #endif\r\n #endif\r\n #else\r\n subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance;\r\n #endif\\r\\n`;\n return code;\n }\n _buildBlock(state) {\n if (state.target === NodeMaterialBlockTargets.Fragment) {\n state.sharedData.blocksWithDefines.push(this);\n }\n return this;\n }\n}\nRegisterClass(\"BABYLON.SubSurfaceBlock\", SubSurfaceBlock);\n//# sourceMappingURL=subSurfaceBlock.js.map","import { __decorate } from \"../../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../../nodeMaterialBlockConnectionPoint.js\";\nimport { MaterialHelper } from \"../../../materialHelper.js\";\nimport { NodeMaterialBlockTargets } from \"../../Enums/nodeMaterialBlockTargets.js\";\nimport { NodeMaterialSystemValues } from \"../../Enums/nodeMaterialSystemValues.js\";\nimport { InputBlock } from \"../Input/inputBlock.js\";\nimport { RegisterClass } from \"../../../../Misc/typeStore.js\";\nimport { PBRBaseMaterial } from \"../../../PBR/pbrBaseMaterial.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../../nodeMaterialDecorator.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../../nodeMaterialConnectionPointCustomObject.js\";\nimport { SheenBlock } from \"./sheenBlock.js\";\nimport { GetEnvironmentBRDFTexture } from \"../../../../Misc/brdfTextureTools.js\";\nimport { MaterialFlags } from \"../../../materialFlags.js\";\nimport { AnisotropyBlock } from \"./anisotropyBlock.js\";\nimport { ReflectionBlock } from \"./reflectionBlock.js\";\nimport { ClearCoatBlock } from \"./clearCoatBlock.js\";\nimport { IridescenceBlock } from \"./iridescenceBlock.js\";\nimport { SubSurfaceBlock } from \"./subSurfaceBlock.js\";\n\nimport { Color3, TmpColors } from \"../../../../Maths/math.color.js\";\nconst mapOutputToVariable = {\n ambientClr: [\"finalAmbient\", \"\"],\n diffuseDir: [\"finalDiffuse\", \"\"],\n specularDir: [\"finalSpecularScaled\", \"!defined(UNLIT) && defined(SPECULARTERM)\"],\n clearcoatDir: [\"finalClearCoatScaled\", \"!defined(UNLIT) && defined(CLEARCOAT)\"],\n sheenDir: [\"finalSheenScaled\", \"!defined(UNLIT) && defined(SHEEN)\"],\n diffuseInd: [\"finalIrradiance\", \"!defined(UNLIT) && defined(REFLECTION)\"],\n specularInd: [\"finalRadianceScaled\", \"!defined(UNLIT) && defined(REFLECTION)\"],\n clearcoatInd: [\"clearcoatOut.finalClearCoatRadianceScaled\", \"!defined(UNLIT) && defined(REFLECTION) && defined(CLEARCOAT)\"],\n sheenInd: [\"sheenOut.finalSheenRadianceScaled\", \"!defined(UNLIT) && defined(REFLECTION) && defined(SHEEN) && defined(ENVIRONMENTBRDF)\"],\n refraction: [\"subSurfaceOut.finalRefraction\", \"!defined(UNLIT) && defined(SS_REFRACTION)\"],\n lighting: [\"finalColor.rgb\", \"\"],\n shadow: [\"shadow\", \"\"],\n alpha: [\"alpha\", \"\"],\n};\n/**\n * Block used to implement the PBR metallic/roughness model\n */\nexport class PBRMetallicRoughnessBlock extends NodeMaterialBlock {\n static _OnGenerateOnlyFragmentCodeChanged(block, _propertyName) {\n const that = block;\n if (that.worldPosition.isConnected) {\n that.generateOnlyFragmentCode = !that.generateOnlyFragmentCode;\n console.error(\"The worldPosition input must not be connected to be able to switch!\");\n return false;\n }\n that._setTarget();\n return true;\n }\n _setTarget() {\n this._setInitialTarget(this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.VertexAndFragment);\n this.getInputByName(\"worldPosition\").target = this.generateOnlyFragmentCode ? NodeMaterialBlockTargets.Fragment : NodeMaterialBlockTargets.Vertex;\n }\n /**\n * Create a new ReflectionBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.VertexAndFragment);\n this._environmentBRDFTexture = null;\n this._metallicReflectanceColor = Color3.White();\n this._metallicF0Factor = 1;\n /**\n * Intensity of the direct lights e.g. the four lights available in your scene.\n * This impacts both the direct diffuse and specular highlights.\n */\n this.directIntensity = 1.0;\n /**\n * Intensity of the environment e.g. how much the environment will light the object\n * either through harmonics for rough material or through the reflection for shiny ones.\n */\n this.environmentIntensity = 1.0;\n /**\n * This is a special control allowing the reduction of the specular highlights coming from the\n * four lights of the scene. Those highlights may not be needed in full environment lighting.\n */\n this.specularIntensity = 1.0;\n /**\n * Defines the falloff type used in this material.\n * It by default is Physical.\n */\n this.lightFalloff = 0;\n /**\n * Specifies that alpha test should be used\n */\n this.useAlphaTest = false;\n /**\n * Defines the alpha limits in alpha test mode.\n */\n this.alphaTestCutoff = 0.5;\n /**\n * Specifies that alpha blending should be used\n */\n this.useAlphaBlending = false;\n /**\n * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most luminous ones).\n * A car glass is a good example of that. When the street lights reflects on it you can not see what is behind.\n */\n this.useRadianceOverAlpha = true;\n /**\n * Specifies that the material will keeps the specular highlights over a transparent surface (only the most luminous ones).\n * A car glass is a good example of that. When sun reflects on it you can not see what is behind.\n */\n this.useSpecularOverAlpha = true;\n /**\n * Enables specular anti aliasing in the PBR shader.\n * It will both interacts on the Geometry for analytical and IBL lighting.\n * It also prefilter the roughness map based on the bump values.\n */\n this.enableSpecularAntiAliasing = false;\n /**\n * Enables realtime filtering on the texture.\n */\n this.realTimeFiltering = false;\n /**\n * Quality switch for realtime filtering\n */\n this.realTimeFilteringQuality = 8;\n /**\n * Defines if the material uses energy conservation.\n */\n this.useEnergyConservation = true;\n /**\n * This parameters will enable/disable radiance occlusion by preventing the radiance to lit\n * too much the area relying on ambient texture to define their ambient occlusion.\n */\n this.useRadianceOcclusion = true;\n /**\n * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal\n * makes the reflect vector face the model (under horizon).\n */\n this.useHorizonOcclusion = true;\n /**\n * If set to true, no lighting calculations will be applied.\n */\n this.unlit = false;\n /**\n * Force normal to face away from face.\n */\n this.forceNormalForward = false;\n /** Indicates that no code should be generated in the vertex shader. Can be useful in some specific circumstances (like when doing ray marching for eg) */\n this.generateOnlyFragmentCode = false;\n /**\n * Defines the material debug mode.\n * It helps seeing only some components of the material while troubleshooting.\n */\n this.debugMode = 0;\n /**\n * Specify from where on screen the debug mode should start.\n * The value goes from -1 (full screen) to 1 (not visible)\n * It helps with side by side comparison against the final render\n * This defaults to 0\n */\n this.debugLimit = 0;\n /**\n * As the default viewing range might not be enough (if the ambient is really small for instance)\n * You can use the factor to better multiply the final value.\n */\n this.debugFactor = 1;\n this._isUnique = true;\n this.registerInput(\"worldPosition\", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Vertex);\n this.registerInput(\"worldNormal\", NodeMaterialBlockConnectionPointTypes.Vector4, false, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"view\", NodeMaterialBlockConnectionPointTypes.Matrix, false);\n this.registerInput(\"cameraPosition\", NodeMaterialBlockConnectionPointTypes.Vector3, false, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"perturbedNormal\", NodeMaterialBlockConnectionPointTypes.Vector4, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"baseColor\", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"metallic\", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"roughness\", NodeMaterialBlockConnectionPointTypes.Float, false, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"ambientOcc\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"opacity\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"indexOfRefraction\", NodeMaterialBlockConnectionPointTypes.Float, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"ambientColor\", NodeMaterialBlockConnectionPointTypes.Color3, true, NodeMaterialBlockTargets.Fragment);\n this.registerInput(\"reflection\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"reflection\", this, NodeMaterialConnectionPointDirection.Input, ReflectionBlock, \"ReflectionBlock\"));\n this.registerInput(\"clearcoat\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"clearcoat\", this, NodeMaterialConnectionPointDirection.Input, ClearCoatBlock, \"ClearCoatBlock\"));\n this.registerInput(\"sheen\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"sheen\", this, NodeMaterialConnectionPointDirection.Input, SheenBlock, \"SheenBlock\"));\n this.registerInput(\"subsurface\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"subsurface\", this, NodeMaterialConnectionPointDirection.Input, SubSurfaceBlock, \"SubSurfaceBlock\"));\n this.registerInput(\"anisotropy\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"anisotropy\", this, NodeMaterialConnectionPointDirection.Input, AnisotropyBlock, \"AnisotropyBlock\"));\n this.registerInput(\"iridescence\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.Fragment, new NodeMaterialConnectionPointCustomObject(\"iridescence\", this, NodeMaterialConnectionPointDirection.Input, IridescenceBlock, \"IridescenceBlock\"));\n this.registerOutput(\"ambientClr\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"diffuseDir\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"specularDir\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"clearcoatDir\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"sheenDir\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"diffuseInd\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"specularInd\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"clearcoatInd\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"sheenInd\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"refraction\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"lighting\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"shadow\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n this.registerOutput(\"alpha\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Fragment);\n }\n /**\n * Initialize the block and prepare the context for build\n * @param state defines the state that will be used for the build\n */\n initialize(state) {\n state._excludeVariableName(\"vLightingIntensity\");\n state._excludeVariableName(\"geometricNormalW\");\n state._excludeVariableName(\"normalW\");\n state._excludeVariableName(\"faceNormal\");\n state._excludeVariableName(\"albedoOpacityOut\");\n state._excludeVariableName(\"surfaceAlbedo\");\n state._excludeVariableName(\"alpha\");\n state._excludeVariableName(\"aoOut\");\n state._excludeVariableName(\"baseColor\");\n state._excludeVariableName(\"reflectivityOut\");\n state._excludeVariableName(\"microSurface\");\n state._excludeVariableName(\"roughness\");\n state._excludeVariableName(\"NdotVUnclamped\");\n state._excludeVariableName(\"NdotV\");\n state._excludeVariableName(\"alphaG\");\n state._excludeVariableName(\"AARoughnessFactors\");\n state._excludeVariableName(\"environmentBrdf\");\n state._excludeVariableName(\"ambientMonochrome\");\n state._excludeVariableName(\"seo\");\n state._excludeVariableName(\"eho\");\n state._excludeVariableName(\"environmentRadiance\");\n state._excludeVariableName(\"irradianceVector\");\n state._excludeVariableName(\"environmentIrradiance\");\n state._excludeVariableName(\"diffuseBase\");\n state._excludeVariableName(\"specularBase\");\n state._excludeVariableName(\"preInfo\");\n state._excludeVariableName(\"info\");\n state._excludeVariableName(\"shadow\");\n state._excludeVariableName(\"finalDiffuse\");\n state._excludeVariableName(\"finalAmbient\");\n state._excludeVariableName(\"ambientOcclusionForDirectDiffuse\");\n state._excludeVariableName(\"finalColor\");\n state._excludeVariableName(\"vClipSpacePosition\");\n state._excludeVariableName(\"vDebugMode\");\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"PBRMetallicRoughnessBlock\";\n }\n /**\n * Gets the world position input component\n */\n get worldPosition() {\n return this._inputs[0];\n }\n /**\n * Gets the world normal input component\n */\n get worldNormal() {\n return this._inputs[1];\n }\n /**\n * Gets the view matrix parameter\n */\n get view() {\n return this._inputs[2];\n }\n /**\n * Gets the camera position input component\n */\n get cameraPosition() {\n return this._inputs[3];\n }\n /**\n * Gets the perturbed normal input component\n */\n get perturbedNormal() {\n return this._inputs[4];\n }\n /**\n * Gets the base color input component\n */\n get baseColor() {\n return this._inputs[5];\n }\n /**\n * Gets the metallic input component\n */\n get metallic() {\n return this._inputs[6];\n }\n /**\n * Gets the roughness input component\n */\n get roughness() {\n return this._inputs[7];\n }\n /**\n * Gets the ambient occlusion input component\n */\n get ambientOcc() {\n return this._inputs[8];\n }\n /**\n * Gets the opacity input component\n */\n get opacity() {\n return this._inputs[9];\n }\n /**\n * Gets the index of refraction input component\n */\n get indexOfRefraction() {\n return this._inputs[10];\n }\n /**\n * Gets the ambient color input component\n */\n get ambientColor() {\n return this._inputs[11];\n }\n /**\n * Gets the reflection object parameters\n */\n get reflection() {\n return this._inputs[12];\n }\n /**\n * Gets the clear coat object parameters\n */\n get clearcoat() {\n return this._inputs[13];\n }\n /**\n * Gets the sheen object parameters\n */\n get sheen() {\n return this._inputs[14];\n }\n /**\n * Gets the sub surface object parameters\n */\n get subsurface() {\n return this._inputs[15];\n }\n /**\n * Gets the anisotropy object parameters\n */\n get anisotropy() {\n return this._inputs[16];\n }\n /**\n * Gets the iridescence object parameters\n */\n get iridescence() {\n return this._inputs[17];\n }\n /**\n * Gets the ambient output component\n */\n get ambientClr() {\n return this._outputs[0];\n }\n /**\n * Gets the diffuse output component\n */\n get diffuseDir() {\n return this._outputs[1];\n }\n /**\n * Gets the specular output component\n */\n get specularDir() {\n return this._outputs[2];\n }\n /**\n * Gets the clear coat output component\n */\n get clearcoatDir() {\n return this._outputs[3];\n }\n /**\n * Gets the sheen output component\n */\n get sheenDir() {\n return this._outputs[4];\n }\n /**\n * Gets the indirect diffuse output component\n */\n get diffuseInd() {\n return this._outputs[5];\n }\n /**\n * Gets the indirect specular output component\n */\n get specularInd() {\n return this._outputs[6];\n }\n /**\n * Gets the indirect clear coat output component\n */\n get clearcoatInd() {\n return this._outputs[7];\n }\n /**\n * Gets the indirect sheen output component\n */\n get sheenInd() {\n return this._outputs[8];\n }\n /**\n * Gets the refraction output component\n */\n get refraction() {\n return this._outputs[9];\n }\n /**\n * Gets the global lighting output component\n */\n get lighting() {\n return this._outputs[10];\n }\n /**\n * Gets the shadow output component\n */\n get shadow() {\n return this._outputs[11];\n }\n /**\n * Gets the alpha output component\n */\n get alpha() {\n return this._outputs[12];\n }\n autoConfigure(material) {\n if (!this.cameraPosition.isConnected) {\n let cameraPositionInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.CameraPosition);\n if (!cameraPositionInput) {\n cameraPositionInput = new InputBlock(\"cameraPosition\");\n cameraPositionInput.setAsSystemValue(NodeMaterialSystemValues.CameraPosition);\n }\n cameraPositionInput.output.connectTo(this.cameraPosition);\n }\n if (!this.view.isConnected) {\n let viewInput = material.getInputBlockByPredicate((b) => b.systemValue === NodeMaterialSystemValues.View);\n if (!viewInput) {\n viewInput = new InputBlock(\"view\");\n viewInput.setAsSystemValue(NodeMaterialSystemValues.View);\n }\n viewInput.output.connectTo(this.view);\n }\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n // General\n defines.setValue(\"PBR\", true);\n defines.setValue(\"METALLICWORKFLOW\", true);\n defines.setValue(\"DEBUGMODE\", this.debugMode, true);\n defines.setValue(\"NORMALXYSCALE\", true);\n defines.setValue(\"BUMP\", this.perturbedNormal.isConnected, true);\n defines.setValue(\"LODBASEDMICROSFURACE\", this._scene.getEngine().getCaps().textureLOD);\n // Albedo & Opacity\n defines.setValue(\"ALBEDO\", false, true);\n defines.setValue(\"OPACITY\", this.opacity.isConnected, true);\n // Ambient occlusion\n defines.setValue(\"AMBIENT\", true, true);\n defines.setValue(\"AMBIENTINGRAYSCALE\", false, true);\n // Reflectivity\n defines.setValue(\"REFLECTIVITY\", false, true);\n defines.setValue(\"AOSTOREINMETALMAPRED\", false, true);\n defines.setValue(\"METALLNESSSTOREINMETALMAPBLUE\", false, true);\n defines.setValue(\"ROUGHNESSSTOREINMETALMAPALPHA\", false, true);\n defines.setValue(\"ROUGHNESSSTOREINMETALMAPGREEN\", false, true);\n // Lighting & colors\n if (this.lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {\n defines.setValue(\"USEPHYSICALLIGHTFALLOFF\", false);\n defines.setValue(\"USEGLTFLIGHTFALLOFF\", false);\n }\n else if (this.lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {\n defines.setValue(\"USEPHYSICALLIGHTFALLOFF\", false);\n defines.setValue(\"USEGLTFLIGHTFALLOFF\", true);\n }\n else {\n defines.setValue(\"USEPHYSICALLIGHTFALLOFF\", true);\n defines.setValue(\"USEGLTFLIGHTFALLOFF\", false);\n }\n // Transparency\n const alphaTestCutOffString = this.alphaTestCutoff.toString();\n defines.setValue(\"ALPHABLEND\", this.useAlphaBlending, true);\n defines.setValue(\"ALPHAFROMALBEDO\", false, true);\n defines.setValue(\"ALPHATEST\", this.useAlphaTest, true);\n defines.setValue(\"ALPHATESTVALUE\", alphaTestCutOffString.indexOf(\".\") < 0 ? alphaTestCutOffString + \".\" : alphaTestCutOffString, true);\n defines.setValue(\"OPACITYRGB\", false, true);\n // Rendering\n defines.setValue(\"RADIANCEOVERALPHA\", this.useRadianceOverAlpha, true);\n defines.setValue(\"SPECULAROVERALPHA\", this.useSpecularOverAlpha, true);\n defines.setValue(\"SPECULARAA\", this._scene.getEngine().getCaps().standardDerivatives && this.enableSpecularAntiAliasing, true);\n defines.setValue(\"REALTIME_FILTERING\", this.realTimeFiltering, true);\n const scene = mesh.getScene();\n const engine = scene.getEngine();\n if (engine._features.needTypeSuffixInShaderConstants) {\n defines.setValue(\"NUM_SAMPLES\", this.realTimeFilteringQuality + \"u\", true);\n }\n else {\n defines.setValue(\"NUM_SAMPLES\", \"\" + this.realTimeFilteringQuality, true);\n }\n // Advanced\n defines.setValue(\"BRDF_V_HEIGHT_CORRELATED\", true);\n defines.setValue(\"MS_BRDF_ENERGY_CONSERVATION\", this.useEnergyConservation, true);\n defines.setValue(\"RADIANCEOCCLUSION\", this.useRadianceOcclusion, true);\n defines.setValue(\"HORIZONOCCLUSION\", this.useHorizonOcclusion, true);\n defines.setValue(\"UNLIT\", this.unlit, true);\n defines.setValue(\"FORCENORMALFORWARD\", this.forceNormalForward, true);\n if (this._environmentBRDFTexture && MaterialFlags.ReflectionTextureEnabled) {\n defines.setValue(\"ENVIRONMENTBRDF\", true);\n defines.setValue(\"ENVIRONMENTBRDF_RGBD\", this._environmentBRDFTexture.isRGBD, true);\n }\n else {\n defines.setValue(\"ENVIRONMENTBRDF\", false);\n defines.setValue(\"ENVIRONMENTBRDF_RGBD\", false);\n }\n if (defines._areImageProcessingDirty && nodeMaterial.imageProcessingConfiguration) {\n nodeMaterial.imageProcessingConfiguration.prepareDefines(defines);\n }\n if (!defines._areLightsDirty) {\n return;\n }\n if (!this.light) {\n // Lights\n MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, nodeMaterial.maxSimultaneousLights);\n defines._needNormals = true;\n // Multiview\n MaterialHelper.PrepareDefinesForMultiview(scene, defines);\n }\n else {\n const state = {\n needNormals: false,\n needRebuild: false,\n lightmapMode: false,\n shadowEnabled: false,\n specularEnabled: false,\n };\n MaterialHelper.PrepareDefinesForLight(scene, mesh, this.light, this._lightId, defines, true, state);\n if (state.needRebuild) {\n defines.rebuild();\n }\n }\n }\n updateUniformsAndSamples(state, nodeMaterial, defines, uniformBuffers) {\n for (let lightIndex = 0; lightIndex < nodeMaterial.maxSimultaneousLights; lightIndex++) {\n if (!defines[\"LIGHT\" + lightIndex]) {\n break;\n }\n const onlyUpdateBuffersList = state.uniforms.indexOf(\"vLightData\" + lightIndex) >= 0;\n MaterialHelper.PrepareUniformsAndSamplersForLight(lightIndex, state.uniforms, state.samplers, defines[\"PROJECTEDLIGHTTEXTURE\" + lightIndex], uniformBuffers, onlyUpdateBuffersList);\n }\n }\n isReady(mesh, nodeMaterial, defines) {\n if (this._environmentBRDFTexture && !this._environmentBRDFTexture.isReady()) {\n return false;\n }\n if (defines._areImageProcessingDirty && nodeMaterial.imageProcessingConfiguration) {\n if (!nodeMaterial.imageProcessingConfiguration.isReady()) {\n return false;\n }\n }\n return true;\n }\n bind(effect, nodeMaterial, mesh) {\n var _a, _b;\n if (!mesh) {\n return;\n }\n const scene = mesh.getScene();\n if (!this.light) {\n MaterialHelper.BindLights(scene, mesh, effect, true, nodeMaterial.maxSimultaneousLights);\n }\n else {\n MaterialHelper.BindLight(this.light, this._lightId, scene, effect, true);\n }\n effect.setTexture(this._environmentBrdfSamplerName, this._environmentBRDFTexture);\n effect.setFloat2(\"vDebugMode\", this.debugLimit, this.debugFactor);\n const ambientScene = this._scene.ambientColor;\n if (ambientScene) {\n effect.setColor3(\"ambientFromScene\", ambientScene);\n }\n const invertNormal = scene.useRightHandedSystem === (scene._mirroredCameraPosition != null);\n effect.setFloat(this._invertNormalName, invertNormal ? -1 : 1);\n effect.setFloat4(\"vLightingIntensity\", this.directIntensity, 1, this.environmentIntensity * this._scene.environmentIntensity, this.specularIntensity);\n // reflectivity bindings\n const outsideIOR = 1; // consider air as clear coat and other layers would remap in the shader.\n const ior = (_b = (_a = this.indexOfRefraction.connectInputBlock) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : 1.5;\n // We are here deriving our default reflectance from a common value for none metallic surface.\n // Based of the schlick fresnel approximation model\n // for dielectrics.\n const f0 = Math.pow((ior - outsideIOR) / (ior + outsideIOR), 2);\n // Tweak the default F0 and F90 based on our given setup\n this._metallicReflectanceColor.scaleToRef(f0 * this._metallicF0Factor, TmpColors.Color3[0]);\n const metallicF90 = this._metallicF0Factor;\n effect.setColor4(this._vMetallicReflectanceFactorsName, TmpColors.Color3[0], metallicF90);\n if (nodeMaterial.imageProcessingConfiguration) {\n nodeMaterial.imageProcessingConfiguration.bind(effect);\n }\n }\n _injectVertexCode(state) {\n var _a, _b;\n const worldPos = this.worldPosition;\n const comments = `//${this.name}`;\n // Declaration\n if (!this.light) {\n // Emit for all lights\n state._emitFunctionFromInclude(state.supportUniformBuffers ? \"lightVxUboDeclaration\" : \"lightVxFragmentDeclaration\", comments, {\n repeatKey: \"maxSimultaneousLights\",\n });\n this._lightId = 0;\n state.sharedData.dynamicUniformBlocks.push(this);\n }\n else {\n this._lightId = (state.counters[\"lightCounter\"] !== undefined ? state.counters[\"lightCounter\"] : -1) + 1;\n state.counters[\"lightCounter\"] = this._lightId;\n state._emitFunctionFromInclude(state.supportUniformBuffers ? \"lightVxUboDeclaration\" : \"lightVxFragmentDeclaration\", comments, {\n replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }],\n }, this._lightId.toString());\n }\n // Inject code in vertex\n const worldPosVaryingName = \"v_\" + worldPos.associatedVariableName;\n if (state._emitVaryingFromString(worldPosVaryingName, \"vec4\")) {\n state.compilationString += `${worldPosVaryingName} = ${worldPos.associatedVariableName};\\r\\n`;\n }\n const reflectionBlock = this.reflection.isConnected ? (_a = this.reflection.connectedPoint) === null || _a === void 0 ? void 0 : _a.ownerBlock : null;\n if (reflectionBlock) {\n reflectionBlock.viewConnectionPoint = this.view;\n }\n state.compilationString += (_b = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock.handleVertexSide(state)) !== null && _b !== void 0 ? _b : \"\";\n if (state._emitVaryingFromString(\"vClipSpacePosition\", \"vec4\", \"defined(IGNORE) || DEBUGMODE > 0\")) {\n state._injectAtEnd += `#if DEBUGMODE > 0\\r\\n`;\n state._injectAtEnd += `vClipSpacePosition = gl_Position;\\r\\n`;\n state._injectAtEnd += `#endif\\r\\n`;\n }\n if (this.light) {\n state.compilationString += state._emitCodeFromInclude(\"shadowsVertex\", comments, {\n replaceStrings: [\n { search: /{X}/g, replace: this._lightId.toString() },\n { search: /worldPos/g, replace: worldPos.associatedVariableName },\n ],\n });\n }\n else {\n state.compilationString += `vec4 worldPos = ${worldPos.associatedVariableName};\\r\\n`;\n if (this.view.isConnected) {\n state.compilationString += `mat4 view = ${this.view.associatedVariableName};\\r\\n`;\n }\n state.compilationString += state._emitCodeFromInclude(\"shadowsVertex\", comments, {\n repeatKey: \"maxSimultaneousLights\",\n });\n }\n }\n _getAlbedoOpacityCode() {\n let code = `albedoOpacityOutParams albedoOpacityOut;\\r\\n`;\n const albedoColor = this.baseColor.isConnected ? this.baseColor.associatedVariableName : \"vec3(1.)\";\n const opacity = this.opacity.isConnected ? this.opacity.associatedVariableName : \"1.\";\n code += `albedoOpacityBlock(\r\n vec4(${albedoColor}, 1.),\r\n #ifdef ALBEDO\r\n vec4(1.),\r\n vec2(1., 1.),\r\n #endif\r\n #ifdef OPACITY\r\n vec4(${opacity}),\r\n vec2(1., 1.),\r\n #endif\r\n albedoOpacityOut\r\n );\r\n\r\n vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo;\r\n float alpha = albedoOpacityOut.alpha;\\r\\n`;\n return code;\n }\n _getAmbientOcclusionCode() {\n let code = `ambientOcclusionOutParams aoOut;\\r\\n`;\n const ao = this.ambientOcc.isConnected ? this.ambientOcc.associatedVariableName : \"1.\";\n code += `ambientOcclusionBlock(\r\n #ifdef AMBIENT\r\n vec3(${ao}),\r\n vec4(0., 1.0, 1.0, 0.),\r\n #endif\r\n aoOut\r\n );\\r\\n`;\n return code;\n }\n _getReflectivityCode(state) {\n let code = `reflectivityOutParams reflectivityOut;\\r\\n`;\n const aoIntensity = \"1.\";\n this._vMetallicReflectanceFactorsName = state._getFreeVariableName(\"vMetallicReflectanceFactors\");\n state._emitUniformFromString(this._vMetallicReflectanceFactorsName, \"vec4\");\n code += `vec3 baseColor = surfaceAlbedo;\r\n\r\n reflectivityBlock(\r\n vec4(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.),\r\n #ifdef METALLICWORKFLOW\r\n surfaceAlbedo,\r\n ${this._vMetallicReflectanceFactorsName},\r\n #endif\r\n #ifdef REFLECTIVITY\r\n vec3(0., 0., ${aoIntensity}),\r\n vec4(1.),\r\n #endif\r\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\r\n aoOut.ambientOcclusionColor,\r\n #endif\r\n #ifdef MICROSURFACEMAP\r\n microSurfaceTexel, <== not handled!\r\n #endif\r\n reflectivityOut\r\n );\r\n\r\n float microSurface = reflectivityOut.microSurface;\r\n float roughness = reflectivityOut.roughness;\r\n\r\n #ifdef METALLICWORKFLOW\r\n surfaceAlbedo = reflectivityOut.surfaceAlbedo;\r\n #endif\r\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\r\n aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor;\r\n #endif\\r\\n`;\n return code;\n }\n _buildBlock(state) {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16;\n super._buildBlock(state);\n this._scene = state.sharedData.scene;\n if (!this._environmentBRDFTexture) {\n this._environmentBRDFTexture = GetEnvironmentBRDFTexture(this._scene);\n }\n const reflectionBlock = this.reflection.isConnected ? (_a = this.reflection.connectedPoint) === null || _a === void 0 ? void 0 : _a.ownerBlock : null;\n if (reflectionBlock) {\n // Need those variables to be setup when calling _injectVertexCode\n reflectionBlock.worldPositionConnectionPoint = this.worldPosition;\n reflectionBlock.cameraPositionConnectionPoint = this.cameraPosition;\n reflectionBlock.worldNormalConnectionPoint = this.worldNormal;\n reflectionBlock.viewConnectionPoint = this.view;\n }\n if (state.target !== NodeMaterialBlockTargets.Fragment) {\n // Vertex\n this._injectVertexCode(state);\n return this;\n }\n // Fragment\n state.sharedData.forcedBindableBlocks.push(this);\n state.sharedData.blocksWithDefines.push(this);\n state.sharedData.blockingBlocks.push(this);\n if (this.generateOnlyFragmentCode) {\n state.sharedData.dynamicUniformBlocks.push(this);\n }\n const comments = `//${this.name}`;\n const normalShading = this.perturbedNormal;\n let worldPosVarName = this.worldPosition.associatedVariableName;\n if (this.generateOnlyFragmentCode) {\n worldPosVarName = state._getFreeVariableName(\"globalWorldPos\");\n state._emitFunction(\"pbr_globalworldpos\", `vec3 ${worldPosVarName};\\r\\n`, comments);\n state.compilationString += `${worldPosVarName} = ${this.worldPosition.associatedVariableName}.xyz;\\r\\n`;\n state.compilationString += state._emitCodeFromInclude(\"shadowsVertex\", comments, {\n repeatKey: \"maxSimultaneousLights\",\n substitutionVars: this.generateOnlyFragmentCode ? `worldPos,${this.worldPosition.associatedVariableName}` : undefined,\n });\n state.compilationString += `#if DEBUGMODE > 0\\r\\n`;\n state.compilationString += `vec4 vClipSpacePosition = vec4((vec2(gl_FragCoord.xy) / vec2(1.0)) * 2.0 - 1.0, 0.0, 1.0);\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n }\n else {\n worldPosVarName = \"v_\" + worldPosVarName;\n }\n this._environmentBrdfSamplerName = state._getFreeVariableName(\"environmentBrdfSampler\");\n state._emit2DSampler(this._environmentBrdfSamplerName);\n state.sharedData.hints.needAlphaBlending = state.sharedData.hints.needAlphaBlending || this.useAlphaBlending;\n state.sharedData.hints.needAlphaTesting = state.sharedData.hints.needAlphaTesting || this.useAlphaTest;\n state._emitExtension(\"lod\", \"#extension GL_EXT_shader_texture_lod : enable\", \"defined(LODBASEDMICROSFURACE)\");\n state._emitExtension(\"derivatives\", \"#extension GL_OES_standard_derivatives : enable\");\n state._emitUniformFromString(\"vDebugMode\", \"vec2\", \"defined(IGNORE) || DEBUGMODE > 0\");\n state._emitUniformFromString(\"ambientFromScene\", \"vec3\");\n // Image processing uniforms\n state.uniforms.push(\"exposureLinear\");\n state.uniforms.push(\"contrast\");\n state.uniforms.push(\"vInverseScreenSize\");\n state.uniforms.push(\"vignetteSettings1\");\n state.uniforms.push(\"vignetteSettings2\");\n state.uniforms.push(\"vCameraColorCurveNegative\");\n state.uniforms.push(\"vCameraColorCurveNeutral\");\n state.uniforms.push(\"vCameraColorCurvePositive\");\n state.uniforms.push(\"txColorTransform\");\n state.uniforms.push(\"colorTransformSettings\");\n state.uniforms.push(\"ditherIntensity\");\n //\n // Includes\n //\n if (!this.light) {\n // Emit for all lights\n state._emitFunctionFromInclude(state.supportUniformBuffers ? \"lightUboDeclaration\" : \"lightFragmentDeclaration\", comments, {\n repeatKey: \"maxSimultaneousLights\",\n substitutionVars: this.generateOnlyFragmentCode ? \"varying,\" : undefined,\n });\n }\n else {\n state._emitFunctionFromInclude(state.supportUniformBuffers ? \"lightUboDeclaration\" : \"lightFragmentDeclaration\", comments, {\n replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }],\n }, this._lightId.toString());\n }\n state._emitFunctionFromInclude(\"helperFunctions\", comments);\n state._emitFunctionFromInclude(\"importanceSampling\", comments);\n state._emitFunctionFromInclude(\"pbrHelperFunctions\", comments);\n state._emitFunctionFromInclude(\"imageProcessingDeclaration\", comments);\n state._emitFunctionFromInclude(\"imageProcessingFunctions\", comments);\n state._emitFunctionFromInclude(\"shadowsFragmentFunctions\", comments, {\n replaceStrings: [{ search: /vPositionW/g, replace: worldPosVarName + \".xyz\" }],\n });\n state._emitFunctionFromInclude(\"pbrDirectLightingSetupFunctions\", comments, {\n replaceStrings: [{ search: /vPositionW/g, replace: worldPosVarName + \".xyz\" }],\n });\n state._emitFunctionFromInclude(\"pbrDirectLightingFalloffFunctions\", comments);\n state._emitFunctionFromInclude(\"pbrBRDFFunctions\", comments, {\n replaceStrings: [{ search: /REFLECTIONMAP_SKYBOX/g, replace: (_b = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName) !== null && _b !== void 0 ? _b : \"REFLECTIONMAP_SKYBOX\" }],\n });\n state._emitFunctionFromInclude(\"hdrFilteringFunctions\", comments);\n state._emitFunctionFromInclude(\"pbrDirectLightingFunctions\", comments, {\n replaceStrings: [{ search: /vPositionW/g, replace: worldPosVarName + \".xyz\" }],\n });\n state._emitFunctionFromInclude(\"pbrIBLFunctions\", comments);\n state._emitFunctionFromInclude(\"pbrBlockAlbedoOpacity\", comments);\n state._emitFunctionFromInclude(\"pbrBlockReflectivity\", comments);\n state._emitFunctionFromInclude(\"pbrBlockAmbientOcclusion\", comments);\n state._emitFunctionFromInclude(\"pbrBlockAlphaFresnel\", comments);\n state._emitFunctionFromInclude(\"pbrBlockAnisotropic\", comments);\n //\n // code\n //\n state._emitUniformFromString(\"vLightingIntensity\", \"vec4\");\n if (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock.generateOnlyFragmentCode) {\n state.compilationString += reflectionBlock.handleVertexSide(state);\n }\n // _____________________________ Geometry Information ____________________________\n this._vNormalWName = state._getFreeVariableName(\"vNormalW\");\n state.compilationString += `vec4 ${this._vNormalWName} = normalize(${this.worldNormal.associatedVariableName});\\r\\n`;\n if (state._registerTempVariable(\"viewDirectionW\")) {\n state.compilationString += `vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${worldPosVarName}.xyz);\\r\\n`;\n }\n state.compilationString += `vec3 geometricNormalW = ${this._vNormalWName}.xyz;\\r\\n`;\n state.compilationString += `vec3 normalW = ${normalShading.isConnected ? \"normalize(\" + normalShading.associatedVariableName + \".xyz)\" : \"geometricNormalW\"};\\r\\n`;\n this._invertNormalName = state._getFreeVariableName(\"invertNormal\");\n state._emitUniformFromString(this._invertNormalName, \"float\");\n state.compilationString += state._emitCodeFromInclude(\"pbrBlockNormalFinal\", comments, {\n replaceStrings: [\n { search: /vPositionW/g, replace: worldPosVarName + \".xyz\" },\n { search: /vEyePosition.w/g, replace: this._invertNormalName },\n ],\n });\n // _____________________________ Albedo & Opacity ______________________________\n state.compilationString += this._getAlbedoOpacityCode();\n state.compilationString += state._emitCodeFromInclude(\"depthPrePass\", comments);\n // _____________________________ AO _______________________________\n state.compilationString += this._getAmbientOcclusionCode();\n state.compilationString += state._emitCodeFromInclude(\"pbrBlockLightmapInit\", comments);\n // _____________________________ UNLIT _______________________________\n state.compilationString += `#ifdef UNLIT\r\n vec3 diffuseBase = vec3(1., 1., 1.);\r\n #else\\r\\n`;\n // _____________________________ Reflectivity _______________________________\n state.compilationString += this._getReflectivityCode(state);\n // _____________________________ Geometry info _________________________________\n state.compilationString += state._emitCodeFromInclude(\"pbrBlockGeometryInfo\", comments, {\n replaceStrings: [\n { search: /REFLECTIONMAP_SKYBOX/g, replace: (_c = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName) !== null && _c !== void 0 ? _c : \"REFLECTIONMAP_SKYBOX\" },\n { search: /REFLECTIONMAP_3D/g, replace: (_d = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) !== null && _d !== void 0 ? _d : \"REFLECTIONMAP_3D\" },\n ],\n });\n // _____________________________ Anisotropy _______________________________________\n const anisotropyBlock = this.anisotropy.isConnected ? (_e = this.anisotropy.connectedPoint) === null || _e === void 0 ? void 0 : _e.ownerBlock : null;\n if (anisotropyBlock) {\n anisotropyBlock.worldPositionConnectionPoint = this.worldPosition;\n anisotropyBlock.worldNormalConnectionPoint = this.worldNormal;\n state.compilationString += anisotropyBlock.getCode(state, !this.perturbedNormal.isConnected);\n }\n // _____________________________ Reflection _______________________________________\n if (reflectionBlock && reflectionBlock.hasTexture) {\n state.compilationString += reflectionBlock.getCode(state, anisotropyBlock ? \"anisotropicOut.anisotropicNormal\" : \"normalW\");\n }\n state._emitFunctionFromInclude(\"pbrBlockReflection\", comments, {\n replaceStrings: [\n { search: /computeReflectionCoords/g, replace: \"computeReflectionCoordsPBR\" },\n { search: /REFLECTIONMAP_3D/g, replace: (_f = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) !== null && _f !== void 0 ? _f : \"REFLECTIONMAP_3D\" },\n { search: /REFLECTIONMAP_OPPOSITEZ/g, replace: (_g = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineOppositeZ) !== null && _g !== void 0 ? _g : \"REFLECTIONMAP_OPPOSITEZ\" },\n { search: /REFLECTIONMAP_PROJECTION/g, replace: (_h = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineProjectionName) !== null && _h !== void 0 ? _h : \"REFLECTIONMAP_PROJECTION\" },\n { search: /REFLECTIONMAP_SKYBOX/g, replace: (_j = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName) !== null && _j !== void 0 ? _j : \"REFLECTIONMAP_SKYBOX\" },\n { search: /LODINREFLECTIONALPHA/g, replace: (_k = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineLODReflectionAlpha) !== null && _k !== void 0 ? _k : \"LODINREFLECTIONALPHA\" },\n { search: /LINEARSPECULARREFLECTION/g, replace: (_l = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineLinearSpecularReflection) !== null && _l !== void 0 ? _l : \"LINEARSPECULARREFLECTION\" },\n { search: /vReflectionFilteringInfo/g, replace: (_m = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._vReflectionFilteringInfoName) !== null && _m !== void 0 ? _m : \"vReflectionFilteringInfo\" },\n ],\n });\n // ___________________ Compute Reflectance aka R0 F0 info _________________________\n state.compilationString += state._emitCodeFromInclude(\"pbrBlockReflectance0\", comments, {\n replaceStrings: [{ search: /metallicReflectanceFactors/g, replace: this._vMetallicReflectanceFactorsName }],\n });\n // ________________________________ Sheen ______________________________\n const sheenBlock = this.sheen.isConnected ? (_o = this.sheen.connectedPoint) === null || _o === void 0 ? void 0 : _o.ownerBlock : null;\n if (sheenBlock) {\n state.compilationString += sheenBlock.getCode(reflectionBlock);\n }\n state._emitFunctionFromInclude(\"pbrBlockSheen\", comments, {\n replaceStrings: [\n { search: /REFLECTIONMAP_3D/g, replace: (_p = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) !== null && _p !== void 0 ? _p : \"REFLECTIONMAP_3D\" },\n { search: /REFLECTIONMAP_SKYBOX/g, replace: (_q = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName) !== null && _q !== void 0 ? _q : \"REFLECTIONMAP_SKYBOX\" },\n { search: /LODINREFLECTIONALPHA/g, replace: (_r = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineLODReflectionAlpha) !== null && _r !== void 0 ? _r : \"LODINREFLECTIONALPHA\" },\n { search: /LINEARSPECULARREFLECTION/g, replace: (_s = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineLinearSpecularReflection) !== null && _s !== void 0 ? _s : \"LINEARSPECULARREFLECTION\" },\n ],\n });\n // _____________________________ Iridescence _______________________________\n const iridescenceBlock = this.iridescence.isConnected ? (_t = this.iridescence.connectedPoint) === null || _t === void 0 ? void 0 : _t.ownerBlock : null;\n state.compilationString += IridescenceBlock.GetCode(iridescenceBlock);\n state._emitFunctionFromInclude(\"pbrBlockIridescence\", comments, {\n replaceStrings: [],\n });\n // _____________________________ Clear Coat ____________________________\n const clearcoatBlock = this.clearcoat.isConnected ? (_u = this.clearcoat.connectedPoint) === null || _u === void 0 ? void 0 : _u.ownerBlock : null;\n const generateTBNSpace = !this.perturbedNormal.isConnected && !this.anisotropy.isConnected;\n const isTangentConnectedToPerturbNormal = this.perturbedNormal.isConnected && ((_w = ((_v = this.perturbedNormal.connectedPoint) === null || _v === void 0 ? void 0 : _v.ownerBlock).worldTangent) === null || _w === void 0 ? void 0 : _w.isConnected);\n const isTangentConnectedToAnisotropy = this.anisotropy.isConnected && ((_x = this.anisotropy.connectedPoint) === null || _x === void 0 ? void 0 : _x.ownerBlock).worldTangent.isConnected;\n let vTBNAvailable = isTangentConnectedToPerturbNormal || (!this.perturbedNormal.isConnected && isTangentConnectedToAnisotropy);\n state.compilationString += ClearCoatBlock.GetCode(state, clearcoatBlock, reflectionBlock, worldPosVarName, generateTBNSpace, vTBNAvailable, this.worldNormal.associatedVariableName);\n if (generateTBNSpace) {\n vTBNAvailable = (_y = clearcoatBlock === null || clearcoatBlock === void 0 ? void 0 : clearcoatBlock.worldTangent.isConnected) !== null && _y !== void 0 ? _y : false;\n }\n state._emitFunctionFromInclude(\"pbrBlockClearcoat\", comments, {\n replaceStrings: [\n { search: /computeReflectionCoords/g, replace: \"computeReflectionCoordsPBR\" },\n { search: /REFLECTIONMAP_3D/g, replace: (_z = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) !== null && _z !== void 0 ? _z : \"REFLECTIONMAP_3D\" },\n { search: /REFLECTIONMAP_OPPOSITEZ/g, replace: (_0 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineOppositeZ) !== null && _0 !== void 0 ? _0 : \"REFLECTIONMAP_OPPOSITEZ\" },\n { search: /REFLECTIONMAP_PROJECTION/g, replace: (_1 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineProjectionName) !== null && _1 !== void 0 ? _1 : \"REFLECTIONMAP_PROJECTION\" },\n { search: /REFLECTIONMAP_SKYBOX/g, replace: (_2 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName) !== null && _2 !== void 0 ? _2 : \"REFLECTIONMAP_SKYBOX\" },\n { search: /LODINREFLECTIONALPHA/g, replace: (_3 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineLODReflectionAlpha) !== null && _3 !== void 0 ? _3 : \"LODINREFLECTIONALPHA\" },\n { search: /LINEARSPECULARREFLECTION/g, replace: (_4 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineLinearSpecularReflection) !== null && _4 !== void 0 ? _4 : \"LINEARSPECULARREFLECTION\" },\n { search: /defined\\(TANGENT\\)/g, replace: vTBNAvailable ? \"defined(TANGENT)\" : \"defined(IGNORE)\" },\n ],\n });\n // _________________________ Specular Environment Reflectance __________________________\n state.compilationString += state._emitCodeFromInclude(\"pbrBlockReflectance\", comments, {\n replaceStrings: [\n { search: /REFLECTIONMAP_SKYBOX/g, replace: (_5 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName) !== null && _5 !== void 0 ? _5 : \"REFLECTIONMAP_SKYBOX\" },\n { search: /REFLECTIONMAP_3D/g, replace: (_6 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) !== null && _6 !== void 0 ? _6 : \"REFLECTIONMAP_3D\" },\n ],\n });\n // ___________________________________ SubSurface ______________________________________\n const subsurfaceBlock = this.subsurface.isConnected ? (_7 = this.subsurface.connectedPoint) === null || _7 === void 0 ? void 0 : _7.ownerBlock : null;\n const refractionBlock = this.subsurface.isConnected\n ? (_9 = ((_8 = this.subsurface.connectedPoint) === null || _8 === void 0 ? void 0 : _8.ownerBlock).refraction.connectedPoint) === null || _9 === void 0 ? void 0 : _9.ownerBlock\n : null;\n if (refractionBlock) {\n refractionBlock.viewConnectionPoint = this.view;\n refractionBlock.indexOfRefractionConnectionPoint = this.indexOfRefraction;\n }\n state.compilationString += SubSurfaceBlock.GetCode(state, subsurfaceBlock, reflectionBlock, worldPosVarName);\n state._emitFunctionFromInclude(\"pbrBlockSubSurface\", comments, {\n replaceStrings: [\n { search: /REFLECTIONMAP_3D/g, replace: (_10 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) !== null && _10 !== void 0 ? _10 : \"REFLECTIONMAP_3D\" },\n { search: /REFLECTIONMAP_OPPOSITEZ/g, replace: (_11 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineOppositeZ) !== null && _11 !== void 0 ? _11 : \"REFLECTIONMAP_OPPOSITEZ\" },\n { search: /REFLECTIONMAP_PROJECTION/g, replace: (_12 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineProjectionName) !== null && _12 !== void 0 ? _12 : \"REFLECTIONMAP_PROJECTION\" },\n { search: /SS_REFRACTIONMAP_3D/g, replace: (_13 = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._define3DName) !== null && _13 !== void 0 ? _13 : \"SS_REFRACTIONMAP_3D\" },\n { search: /SS_LODINREFRACTIONALPHA/g, replace: (_14 = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._defineLODRefractionAlpha) !== null && _14 !== void 0 ? _14 : \"SS_LODINREFRACTIONALPHA\" },\n { search: /SS_LINEARSPECULARREFRACTION/g, replace: (_15 = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._defineLinearSpecularRefraction) !== null && _15 !== void 0 ? _15 : \"SS_LINEARSPECULARREFRACTION\" },\n { search: /SS_REFRACTIONMAP_OPPOSITEZ/g, replace: (_16 = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._defineOppositeZ) !== null && _16 !== void 0 ? _16 : \"SS_REFRACTIONMAP_OPPOSITEZ\" },\n ],\n });\n // _____________________________ Direct Lighting Info __________________________________\n state.compilationString += state._emitCodeFromInclude(\"pbrBlockDirectLighting\", comments);\n if (this.light) {\n state.compilationString += state._emitCodeFromInclude(\"lightFragment\", comments, {\n replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }],\n });\n }\n else {\n state.compilationString += state._emitCodeFromInclude(\"lightFragment\", comments, {\n repeatKey: \"maxSimultaneousLights\",\n });\n }\n // _____________________________ Compute Final Lit Components ________________________\n state.compilationString += state._emitCodeFromInclude(\"pbrBlockFinalLitComponents\", comments);\n // _____________________________ UNLIT (2) ________________________\n state.compilationString += `#endif\\r\\n`; // UNLIT\n // _____________________________ Compute Final Unlit Components ________________________\n const aoColor = this.ambientColor.isConnected ? this.ambientColor.associatedVariableName : \"vec3(0., 0., 0.)\";\n let aoDirectLightIntensity = PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();\n if (aoDirectLightIntensity.indexOf(\".\") === -1) {\n aoDirectLightIntensity += \".\";\n }\n state.compilationString += state._emitCodeFromInclude(\"pbrBlockFinalUnlitComponents\", comments, {\n replaceStrings: [\n { search: /vec3 finalEmissive[\\s\\S]*?finalEmissive\\*=vLightingIntensity\\.y;/g, replace: \"\" },\n { search: /vAmbientColor/g, replace: aoColor + \" * ambientFromScene\" },\n { search: /vAmbientInfos\\.w/g, replace: aoDirectLightIntensity },\n ],\n });\n // _____________________________ Output Final Color Composition ________________________\n state.compilationString += state._emitCodeFromInclude(\"pbrBlockFinalColorComposition\", comments, {\n replaceStrings: [{ search: /finalEmissive/g, replace: \"vec3(0.)\" }],\n });\n // _____________________________ Apply image processing ________________________\n state.compilationString += state._emitCodeFromInclude(\"pbrBlockImageProcessing\", comments, {\n replaceStrings: [{ search: /visibility/g, replace: \"1.\" }],\n });\n // _____________________________ Generate debug code ________________________\n state.compilationString += state._emitCodeFromInclude(\"pbrDebug\", comments, {\n replaceStrings: [\n { search: /vNormalW/g, replace: this._vNormalWName },\n { search: /vPositionW/g, replace: worldPosVarName },\n { search: /albedoTexture\\.rgb;/g, replace: \"vec3(1.);\\r\\ngl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb);\\r\\n\" },\n ],\n });\n // _____________________________ Generate end points ________________________\n for (const output of this._outputs) {\n if (output.hasEndpoints) {\n const remap = mapOutputToVariable[output.name];\n if (remap) {\n const [varName, conditions] = remap;\n if (conditions) {\n state.compilationString += `#if ${conditions}\\r\\n`;\n }\n state.compilationString += `${this._declareOutput(output, state)} = ${varName};\\r\\n`;\n if (conditions) {\n state.compilationString += `#else\\r\\n`;\n state.compilationString += `${this._declareOutput(output, state)} = vec3(0.);\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n }\n }\n else {\n console.error(`There's no remapping for the ${output.name} end point! No code generated`);\n }\n }\n }\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n codeString += `${this._codeVariableName}.lightFalloff = ${this.lightFalloff};\\r\\n`;\n codeString += `${this._codeVariableName}.useAlphaTest = ${this.useAlphaTest};\\r\\n`;\n codeString += `${this._codeVariableName}.alphaTestCutoff = ${this.alphaTestCutoff};\\r\\n`;\n codeString += `${this._codeVariableName}.useAlphaBlending = ${this.useAlphaBlending};\\r\\n`;\n codeString += `${this._codeVariableName}.useRadianceOverAlpha = ${this.useRadianceOverAlpha};\\r\\n`;\n codeString += `${this._codeVariableName}.useSpecularOverAlpha = ${this.useSpecularOverAlpha};\\r\\n`;\n codeString += `${this._codeVariableName}.enableSpecularAntiAliasing = ${this.enableSpecularAntiAliasing};\\r\\n`;\n codeString += `${this._codeVariableName}.realTimeFiltering = ${this.realTimeFiltering};\\r\\n`;\n codeString += `${this._codeVariableName}.realTimeFilteringQuality = ${this.realTimeFilteringQuality};\\r\\n`;\n codeString += `${this._codeVariableName}.useEnergyConservation = ${this.useEnergyConservation};\\r\\n`;\n codeString += `${this._codeVariableName}.useRadianceOcclusion = ${this.useRadianceOcclusion};\\r\\n`;\n codeString += `${this._codeVariableName}.useHorizonOcclusion = ${this.useHorizonOcclusion};\\r\\n`;\n codeString += `${this._codeVariableName}.unlit = ${this.unlit};\\r\\n`;\n codeString += `${this._codeVariableName}.forceNormalForward = ${this.forceNormalForward};\\r\\n`;\n codeString += `${this._codeVariableName}.debugMode = ${this.debugMode};\\r\\n`;\n codeString += `${this._codeVariableName}.debugLimit = ${this.debugLimit};\\r\\n`;\n codeString += `${this._codeVariableName}.debugFactor = ${this.debugFactor};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n if (this.light) {\n serializationObject.lightId = this.light.id;\n }\n serializationObject.lightFalloff = this.lightFalloff;\n serializationObject.useAlphaTest = this.useAlphaTest;\n serializationObject.alphaTestCutoff = this.alphaTestCutoff;\n serializationObject.useAlphaBlending = this.useAlphaBlending;\n serializationObject.useRadianceOverAlpha = this.useRadianceOverAlpha;\n serializationObject.useSpecularOverAlpha = this.useSpecularOverAlpha;\n serializationObject.enableSpecularAntiAliasing = this.enableSpecularAntiAliasing;\n serializationObject.realTimeFiltering = this.realTimeFiltering;\n serializationObject.realTimeFilteringQuality = this.realTimeFilteringQuality;\n serializationObject.useEnergyConservation = this.useEnergyConservation;\n serializationObject.useRadianceOcclusion = this.useRadianceOcclusion;\n serializationObject.useHorizonOcclusion = this.useHorizonOcclusion;\n serializationObject.unlit = this.unlit;\n serializationObject.forceNormalForward = this.forceNormalForward;\n serializationObject.debugMode = this.debugMode;\n serializationObject.debugLimit = this.debugLimit;\n serializationObject.debugFactor = this.debugFactor;\n serializationObject.generateOnlyFragmentCode = this.generateOnlyFragmentCode;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n var _a, _b;\n super._deserialize(serializationObject, scene, rootUrl);\n if (serializationObject.lightId) {\n this.light = scene.getLightById(serializationObject.lightId);\n }\n this.lightFalloff = (_a = serializationObject.lightFalloff) !== null && _a !== void 0 ? _a : 0;\n this.useAlphaTest = serializationObject.useAlphaTest;\n this.alphaTestCutoff = serializationObject.alphaTestCutoff;\n this.useAlphaBlending = serializationObject.useAlphaBlending;\n this.useRadianceOverAlpha = serializationObject.useRadianceOverAlpha;\n this.useSpecularOverAlpha = serializationObject.useSpecularOverAlpha;\n this.enableSpecularAntiAliasing = serializationObject.enableSpecularAntiAliasing;\n this.realTimeFiltering = !!serializationObject.realTimeFiltering;\n this.realTimeFilteringQuality = (_b = serializationObject.realTimeFilteringQuality) !== null && _b !== void 0 ? _b : 8;\n this.useEnergyConservation = serializationObject.useEnergyConservation;\n this.useRadianceOcclusion = serializationObject.useRadianceOcclusion;\n this.useHorizonOcclusion = serializationObject.useHorizonOcclusion;\n this.unlit = serializationObject.unlit;\n this.forceNormalForward = !!serializationObject.forceNormalForward;\n this.debugMode = serializationObject.debugMode;\n this.debugLimit = serializationObject.debugLimit;\n this.debugFactor = serializationObject.debugFactor;\n this.generateOnlyFragmentCode = !!serializationObject.generateOnlyFragmentCode;\n this._setTarget();\n }\n}\n__decorate([\n editableInPropertyPage(\"Direct lights\", PropertyTypeForEdition.Float, \"INTENSITY\", { min: 0, max: 1, notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"directIntensity\", void 0);\n__decorate([\n editableInPropertyPage(\"Environment lights\", PropertyTypeForEdition.Float, \"INTENSITY\", { min: 0, max: 1, notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"environmentIntensity\", void 0);\n__decorate([\n editableInPropertyPage(\"Specular highlights\", PropertyTypeForEdition.Float, \"INTENSITY\", { min: 0, max: 1, notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"specularIntensity\", void 0);\n__decorate([\n editableInPropertyPage(\"Light falloff\", PropertyTypeForEdition.List, \"LIGHTING & COLORS\", {\n notifiers: { update: true },\n options: [\n { label: \"Physical\", value: PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL },\n { label: \"GLTF\", value: PBRBaseMaterial.LIGHTFALLOFF_GLTF },\n { label: \"Standard\", value: PBRBaseMaterial.LIGHTFALLOFF_STANDARD },\n ],\n })\n], PBRMetallicRoughnessBlock.prototype, \"lightFalloff\", void 0);\n__decorate([\n editableInPropertyPage(\"Alpha Testing\", PropertyTypeForEdition.Boolean, \"OPACITY\")\n], PBRMetallicRoughnessBlock.prototype, \"useAlphaTest\", void 0);\n__decorate([\n editableInPropertyPage(\"Alpha CutOff\", PropertyTypeForEdition.Float, \"OPACITY\", { min: 0, max: 1, notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"alphaTestCutoff\", void 0);\n__decorate([\n editableInPropertyPage(\"Alpha blending\", PropertyTypeForEdition.Boolean, \"OPACITY\")\n], PBRMetallicRoughnessBlock.prototype, \"useAlphaBlending\", void 0);\n__decorate([\n editableInPropertyPage(\"Radiance over alpha\", PropertyTypeForEdition.Boolean, \"RENDERING\", { notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"useRadianceOverAlpha\", void 0);\n__decorate([\n editableInPropertyPage(\"Specular over alpha\", PropertyTypeForEdition.Boolean, \"RENDERING\", { notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"useSpecularOverAlpha\", void 0);\n__decorate([\n editableInPropertyPage(\"Specular anti-aliasing\", PropertyTypeForEdition.Boolean, \"RENDERING\", { notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"enableSpecularAntiAliasing\", void 0);\n__decorate([\n editableInPropertyPage(\"Realtime filtering\", PropertyTypeForEdition.Boolean, \"RENDERING\", { notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"realTimeFiltering\", void 0);\n__decorate([\n editableInPropertyPage(\"Realtime filtering quality\", PropertyTypeForEdition.List, \"RENDERING\", {\n notifiers: { update: true },\n options: [\n { label: \"Low\", value: 8 },\n { label: \"Medium\", value: 16 },\n { label: \"High\", value: 64 },\n ],\n })\n], PBRMetallicRoughnessBlock.prototype, \"realTimeFilteringQuality\", void 0);\n__decorate([\n editableInPropertyPage(\"Energy Conservation\", PropertyTypeForEdition.Boolean, \"ADVANCED\", { notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"useEnergyConservation\", void 0);\n__decorate([\n editableInPropertyPage(\"Radiance occlusion\", PropertyTypeForEdition.Boolean, \"ADVANCED\", { notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"useRadianceOcclusion\", void 0);\n__decorate([\n editableInPropertyPage(\"Horizon occlusion\", PropertyTypeForEdition.Boolean, \"ADVANCED\", { notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"useHorizonOcclusion\", void 0);\n__decorate([\n editableInPropertyPage(\"Unlit\", PropertyTypeForEdition.Boolean, \"ADVANCED\", { notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"unlit\", void 0);\n__decorate([\n editableInPropertyPage(\"Force normal forward\", PropertyTypeForEdition.Boolean, \"ADVANCED\", { notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"forceNormalForward\", void 0);\n__decorate([\n editableInPropertyPage(\"Generate only fragment code\", PropertyTypeForEdition.Boolean, \"ADVANCED\", {\n notifiers: { rebuild: true, update: true, onValidation: PBRMetallicRoughnessBlock._OnGenerateOnlyFragmentCodeChanged },\n })\n], PBRMetallicRoughnessBlock.prototype, \"generateOnlyFragmentCode\", void 0);\n__decorate([\n editableInPropertyPage(\"Debug mode\", PropertyTypeForEdition.List, \"DEBUG\", {\n notifiers: { update: true },\n options: [\n { label: \"None\", value: 0 },\n // Geometry\n { label: \"Normalized position\", value: 1 },\n { label: \"Normals\", value: 2 },\n { label: \"Tangents\", value: 3 },\n { label: \"Bitangents\", value: 4 },\n { label: \"Bump Normals\", value: 5 },\n //{ label: \"UV1\", value: 6 },\n //{ label: \"UV2\", value: 7 },\n { label: \"ClearCoat Normals\", value: 8 },\n { label: \"ClearCoat Tangents\", value: 9 },\n { label: \"ClearCoat Bitangents\", value: 10 },\n { label: \"Anisotropic Normals\", value: 11 },\n { label: \"Anisotropic Tangents\", value: 12 },\n { label: \"Anisotropic Bitangents\", value: 13 },\n // Maps\n //{ label: \"Emissive Map\", value: 23 },\n //{ label: \"Light Map\", value: 24 },\n // Env\n { label: \"Env Refraction\", value: 40 },\n { label: \"Env Reflection\", value: 41 },\n { label: \"Env Clear Coat\", value: 42 },\n // Lighting\n { label: \"Direct Diffuse\", value: 50 },\n { label: \"Direct Specular\", value: 51 },\n { label: \"Direct Clear Coat\", value: 52 },\n { label: \"Direct Sheen\", value: 53 },\n { label: \"Env Irradiance\", value: 54 },\n // Lighting Params\n { label: \"Surface Albedo\", value: 60 },\n { label: \"Reflectance 0\", value: 61 },\n { label: \"Metallic\", value: 62 },\n { label: \"Metallic F0\", value: 71 },\n { label: \"Roughness\", value: 63 },\n { label: \"AlphaG\", value: 64 },\n { label: \"NdotV\", value: 65 },\n { label: \"ClearCoat Color\", value: 66 },\n { label: \"ClearCoat Roughness\", value: 67 },\n { label: \"ClearCoat NdotV\", value: 68 },\n { label: \"Transmittance\", value: 69 },\n { label: \"Refraction Transmittance\", value: 70 },\n // Misc\n { label: \"SEO\", value: 80 },\n { label: \"EHO\", value: 81 },\n { label: \"Energy Factor\", value: 82 },\n { label: \"Specular Reflectance\", value: 83 },\n { label: \"Clear Coat Reflectance\", value: 84 },\n { label: \"Sheen Reflectance\", value: 85 },\n { label: \"Luminance Over Alpha\", value: 86 },\n { label: \"Alpha\", value: 87 },\n ],\n })\n], PBRMetallicRoughnessBlock.prototype, \"debugMode\", void 0);\n__decorate([\n editableInPropertyPage(\"Split position\", PropertyTypeForEdition.Float, \"DEBUG\", { min: -1, max: 1, notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"debugLimit\", void 0);\n__decorate([\n editableInPropertyPage(\"Output factor\", PropertyTypeForEdition.Float, \"DEBUG\", { min: 0, max: 5, notifiers: { update: true } })\n], PBRMetallicRoughnessBlock.prototype, \"debugFactor\", void 0);\nRegisterClass(\"BABYLON.PBRMetallicRoughnessBlock\", PBRMetallicRoughnessBlock);\n//# sourceMappingURL=pbrMetallicRoughnessBlock.js.map","export * from \"./pbrMetallicRoughnessBlock.js\";\nexport * from \"./sheenBlock.js\";\nexport * from \"./anisotropyBlock.js\";\nexport * from \"./reflectionBlock.js\";\nexport * from \"./clearCoatBlock.js\";\nexport * from \"./refractionBlock.js\";\nexport * from \"./subSurfaceBlock.js\";\n//# sourceMappingURL=index.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to compute value of one parameter modulo another\n */\nexport class ModBlock extends NodeMaterialBlock {\n /**\n * Creates a new ModBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"left\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"right\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._linkConnectionTypes(0, 1);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ModBlock\";\n }\n /**\n * Gets the left operand input component\n */\n get left() {\n return this._inputs[0];\n }\n /**\n * Gets the right operand input component\n */\n get right() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = mod(${this.left.associatedVariableName}, ${this.right.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.ModBlock\", ModBlock);\n//# sourceMappingURL=modBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { InputBlock } from \"./Input/inputBlock.js\";\nimport { Vector4 } from \"../../../Maths/math.vector.js\";\n/**\n * Block used to build a matrix from 4 Vector4\n */\nexport class MatrixBuilderBlock extends NodeMaterialBlock {\n /**\n * Creates a new MatrixBuilder\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"row0\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerInput(\"row1\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerInput(\"row2\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerInput(\"row3\", NodeMaterialBlockConnectionPointTypes.Vector4);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Matrix);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"MatrixBuilder\";\n }\n /**\n * Gets the row0 vector\n */\n get row0() {\n return this._inputs[0];\n }\n /**\n * Gets the row1 vector\n */\n get row1() {\n return this._inputs[1];\n }\n /**\n * Gets the row2 vector\n */\n get row2() {\n return this._inputs[2];\n }\n /**\n * Gets the row3 vector\n */\n get row3() {\n return this._inputs[3];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n autoConfigure() {\n if (!this.row0.isConnected) {\n const row0Input = new InputBlock(\"row0\");\n row0Input.value = new Vector4(1, 0, 0, 0);\n row0Input.output.connectTo(this.row0);\n }\n if (!this.row1.isConnected) {\n const row1Input = new InputBlock(\"row1\");\n row1Input.value = new Vector4(0, 1, 0, 0);\n row1Input.output.connectTo(this.row1);\n }\n if (!this.row2.isConnected) {\n const row2Input = new InputBlock(\"row2\");\n row2Input.value = new Vector4(0, 0, 1, 0);\n row2Input.output.connectTo(this.row2);\n }\n if (!this.row3.isConnected) {\n const row3Input = new InputBlock(\"row3\");\n row3Input.value = new Vector4(0, 0, 0, 1);\n row3Input.output.connectTo(this.row3);\n }\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n const row0 = this.row0;\n const row1 = this.row1;\n const row2 = this.row2;\n const row3 = this.row3;\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = mat4(${row0.associatedVariableName}, ${row1.associatedVariableName}, ${row2.associatedVariableName}, ${row3.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.MatrixBuilder\", MatrixBuilderBlock);\n//# sourceMappingURL=matrixBuilderBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Operations supported by the ConditionalBlock block\n */\nexport var ConditionalBlockConditions;\n(function (ConditionalBlockConditions) {\n /** Equal */\n ConditionalBlockConditions[ConditionalBlockConditions[\"Equal\"] = 0] = \"Equal\";\n /** NotEqual */\n ConditionalBlockConditions[ConditionalBlockConditions[\"NotEqual\"] = 1] = \"NotEqual\";\n /** LessThan */\n ConditionalBlockConditions[ConditionalBlockConditions[\"LessThan\"] = 2] = \"LessThan\";\n /** GreaterThan */\n ConditionalBlockConditions[ConditionalBlockConditions[\"GreaterThan\"] = 3] = \"GreaterThan\";\n /** LessOrEqual */\n ConditionalBlockConditions[ConditionalBlockConditions[\"LessOrEqual\"] = 4] = \"LessOrEqual\";\n /** GreaterOrEqual */\n ConditionalBlockConditions[ConditionalBlockConditions[\"GreaterOrEqual\"] = 5] = \"GreaterOrEqual\";\n /** Logical Exclusive OR */\n ConditionalBlockConditions[ConditionalBlockConditions[\"Xor\"] = 6] = \"Xor\";\n /** Logical Or */\n ConditionalBlockConditions[ConditionalBlockConditions[\"Or\"] = 7] = \"Or\";\n /** Logical And */\n ConditionalBlockConditions[ConditionalBlockConditions[\"And\"] = 8] = \"And\";\n})(ConditionalBlockConditions || (ConditionalBlockConditions = {}));\n/**\n * Block used to apply conditional operation between floats\n * @since 5.0.0\n */\nexport class ConditionalBlock extends NodeMaterialBlock {\n /**\n * Creates a new ConditionalBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n /**\n * Gets or sets the condition applied by the block\n */\n this.condition = ConditionalBlockConditions.LessThan;\n this.registerInput(\"a\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerInput(\"b\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerInput(\"true\", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);\n this.registerInput(\"false\", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._linkConnectionTypes(2, 3);\n this._outputs[0]._typeConnectionSource = this._inputs[2];\n this._outputs[0]._defaultConnectionPointType = NodeMaterialBlockConnectionPointTypes.Float;\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ConditionalBlock\";\n }\n /**\n * Gets the first operand component\n */\n get a() {\n return this._inputs[0];\n }\n /**\n * Gets the second operand component\n */\n get b() {\n return this._inputs[1];\n }\n /**\n * Gets the value to return if condition is true\n */\n get true() {\n return this._inputs[2];\n }\n /**\n * Gets the value to return if condition is false\n */\n get false() {\n return this._inputs[3];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n const trueStatement = this.true.isConnected ? this.true.associatedVariableName : \"1.0\";\n const falseStatement = this.false.isConnected ? this.false.associatedVariableName : \"0.0\";\n switch (this.condition) {\n case ConditionalBlockConditions.Equal: {\n state.compilationString +=\n this._declareOutput(output, state) + ` = ${this.a.associatedVariableName} == ${this.b.associatedVariableName} ? ${trueStatement} : ${falseStatement};\\r\\n`;\n break;\n }\n case ConditionalBlockConditions.NotEqual: {\n state.compilationString +=\n this._declareOutput(output, state) + ` = ${this.a.associatedVariableName} != ${this.b.associatedVariableName} ? ${trueStatement} : ${falseStatement};\\r\\n`;\n break;\n }\n case ConditionalBlockConditions.LessThan: {\n state.compilationString +=\n this._declareOutput(output, state) + ` = ${this.a.associatedVariableName} < ${this.b.associatedVariableName} ? ${trueStatement} : ${falseStatement};\\r\\n`;\n break;\n }\n case ConditionalBlockConditions.LessOrEqual: {\n state.compilationString +=\n this._declareOutput(output, state) + ` = ${this.a.associatedVariableName} <= ${this.b.associatedVariableName} ? ${trueStatement} : ${falseStatement};\\r\\n`;\n break;\n }\n case ConditionalBlockConditions.GreaterThan: {\n state.compilationString +=\n this._declareOutput(output, state) + ` = ${this.a.associatedVariableName} > ${this.b.associatedVariableName} ? ${trueStatement} : ${falseStatement};\\r\\n`;\n break;\n }\n case ConditionalBlockConditions.GreaterOrEqual: {\n state.compilationString +=\n this._declareOutput(output, state) + ` = ${this.a.associatedVariableName} >= ${this.b.associatedVariableName} ? ${trueStatement} : ${falseStatement};\\r\\n`;\n break;\n }\n case ConditionalBlockConditions.Xor: {\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = (mod(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 2.0) > 0.0) ? ${trueStatement} : ${falseStatement};\\r\\n`;\n break;\n }\n case ConditionalBlockConditions.Or: {\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = (min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0) ? ${trueStatement} : ${falseStatement};\\r\\n`;\n break;\n }\n case ConditionalBlockConditions.And: {\n state.compilationString +=\n this._declareOutput(output, state) +\n ` = (${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0) ? ${trueStatement} : ${falseStatement};\\r\\n`;\n break;\n }\n }\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.condition = this.condition;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.condition = serializationObject.condition;\n }\n _dumpPropertiesCode() {\n const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.condition = BABYLON.ConditionalBlockConditions.${ConditionalBlockConditions[this.condition]};\\r\\n`;\n return codeString;\n }\n}\nRegisterClass(\"BABYLON.ConditionalBlock\", ConditionalBlock);\n//# sourceMappingURL=conditionalBlock.js.map","import { __decorate } from \"../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../nodeMaterialDecorator.js\";\n/**\n * block used to Generate Fractal Brownian Motion Clouds\n */\nexport class CloudBlock extends NodeMaterialBlock {\n /**\n * Creates a new CloudBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n /** Gets or sets the number of octaves */\n this.octaves = 6.0;\n this.registerInput(\"seed\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"chaos\", NodeMaterialBlockConnectionPointTypes.AutoDetect, true);\n this.registerInput(\"offsetX\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"offsetY\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"offsetZ\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Float);\n this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector2);\n this._inputs[0].acceptedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Vector3);\n this._linkConnectionTypes(0, 1);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"CloudBlock\";\n }\n /**\n * Gets the seed input component\n */\n get seed() {\n return this._inputs[0];\n }\n /**\n * Gets the chaos input component\n */\n get chaos() {\n return this._inputs[1];\n }\n /**\n * Gets the offset X input component\n */\n get offsetX() {\n return this._inputs[2];\n }\n /**\n * Gets the offset Y input component\n */\n get offsetY() {\n return this._inputs[3];\n }\n /**\n * Gets the offset Z input component\n */\n get offsetZ() {\n return this._inputs[4];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n var _a, _b;\n super._buildBlock(state);\n if (!this.seed.isConnected) {\n return;\n }\n if (!this._outputs[0].hasEndpoints) {\n return;\n }\n const functionString = `\r\n\r\n float cloudRandom(in float p) { p = fract(p * 0.011); p *= p + 7.5; p *= p + p; return fract(p); }\r\n\r\n // Based on Morgan McGuire @morgan3d\r\n // https://www.shadertoy.com/view/4dS3Wd\r\n float cloudNoise(in vec2 x, in vec2 chaos) {\r\n vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.);\r\n\r\n vec2 i = floor(x);\r\n vec2 f = fract(x);\r\n\r\n float n = dot(i, step);\r\n\r\n vec2 u = f * f * (3.0 - 2.0 * f);\r\n return mix(\r\n mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x),\r\n mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x),\r\n u.y\r\n );\r\n }\r\n\r\n float cloudNoise(in vec3 x, in vec3 chaos) {\r\n vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.);\r\n\r\n vec3 i = floor(x);\r\n vec3 f = fract(x);\r\n\r\n float n = dot(i, step);\r\n\r\n vec3 u = f * f * (3.0 - 2.0 * f);\r\n return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x),\r\n mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y),\r\n mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x),\r\n mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z);\r\n }`;\n const fractalBrownianString = `\r\n float fbm(in vec2 st, in vec2 chaos) {\r\n // Initial values\r\n float value = 0.0;\r\n float amplitude = .5;\r\n float frequency = 0.;\r\n\r\n // Loop of octaves\r\n for (int i = 0; i < OCTAVES; i++) {\r\n value += amplitude * cloudNoise(st, chaos);\r\n st *= 2.0;\r\n amplitude *= 0.5;\r\n }\r\n return value;\r\n }\r\n\r\n float fbm(in vec3 x, in vec3 chaos) {\r\n // Initial values\r\n float value = 0.0;\r\n float amplitude = 0.5;\r\n for (int i = 0; i < OCTAVES; ++i) {\r\n value += amplitude * cloudNoise(x, chaos);\r\n x = x * 2.0;\r\n amplitude *= 0.5;\r\n }\r\n return value;\r\n }`;\n const fbmNewName = `fbm${this.octaves}`;\n state._emitFunction(\"CloudBlockCode\", functionString, \"// CloudBlockCode\");\n state._emitFunction(\"CloudBlockCodeFBM\" + this.octaves, fractalBrownianString.replace(/fbm/gi, fbmNewName).replace(/OCTAVES/gi, (this.octaves | 0).toString()), \"// CloudBlockCode FBM\");\n const localVariable = state._getFreeVariableName(\"st\");\n const seedType = ((_a = this.seed.connectedPoint) === null || _a === void 0 ? void 0 : _a.type) === NodeMaterialBlockConnectionPointTypes.Vector2 ? \"vec2\" : \"vec3\";\n state.compilationString += `${seedType} ${localVariable} = ${this.seed.associatedVariableName};\\r\\n`;\n if (this.offsetX.isConnected) {\n state.compilationString += `${localVariable}.x += 0.1 * ${this.offsetX.associatedVariableName};\\r\\n`;\n }\n if (this.offsetY.isConnected) {\n state.compilationString += `${localVariable}.y += 0.1 * ${this.offsetY.associatedVariableName};\\r\\n`;\n }\n if (this.offsetZ.isConnected && seedType === \"vec3\") {\n state.compilationString += `${localVariable}.z += 0.1 * ${this.offsetZ.associatedVariableName};\\r\\n`;\n }\n let chaosValue = \"\";\n if (this.chaos.isConnected) {\n chaosValue = this.chaos.associatedVariableName;\n }\n else {\n chaosValue = ((_b = this.seed.connectedPoint) === null || _b === void 0 ? void 0 : _b.type) === NodeMaterialBlockConnectionPointTypes.Vector2 ? \"vec2(0., 0.)\" : \"vec3(0., 0., 0.)\";\n }\n state.compilationString += this._declareOutput(this._outputs[0], state) + ` = ${fbmNewName}(${localVariable}, ${chaosValue});\\r\\n`;\n return this;\n }\n _dumpPropertiesCode() {\n const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.octaves = ${this.octaves};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.octaves = this.octaves;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.octaves = serializationObject.octaves;\n }\n}\n__decorate([\n editableInPropertyPage(\"Octaves\", PropertyTypeForEdition.Int)\n], CloudBlock.prototype, \"octaves\", void 0);\nRegisterClass(\"BABYLON.CloudBlock\", CloudBlock);\n//# sourceMappingURL=cloudBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * block used to Generate a Voronoi Noise Pattern\n */\nexport class VoronoiNoiseBlock extends NodeMaterialBlock {\n /**\n * Creates a new VoronoiNoiseBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"seed\", NodeMaterialBlockConnectionPointTypes.Vector2);\n this.registerInput(\"offset\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerInput(\"density\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Float);\n this.registerOutput(\"cells\", NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"VoronoiNoiseBlock\";\n }\n /**\n * Gets the seed input component\n */\n get seed() {\n return this._inputs[0];\n }\n /**\n * Gets the offset input component\n */\n get offset() {\n return this._inputs[1];\n }\n /**\n * Gets the density input component\n */\n get density() {\n return this._inputs[2];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n /**\n * Gets the output component\n */\n get cells() {\n return this._outputs[1];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (!this.seed.isConnected) {\n return;\n }\n let functionString = `vec2 voronoiRandom(vec2 seed, float offset){\r\n mat2 m = mat2(15.27, 47.63, 99.41, 89.98);\r\n vec2 uv = fract(sin(m * seed) * 46839.32);\r\n return vec2(sin(uv.y * offset) * 0.5 + 0.5, cos(uv.x * offset) * 0.5 + 0.5);\r\n }\r\n `;\n state._emitFunction(\"voronoiRandom\", functionString, \"// Voronoi random generator\");\n functionString = `void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){\r\n vec2 g = floor(seed * density);\r\n vec2 f = fract(seed * density);\r\n float t = 8.0;\r\n vec3 res = vec3(8.0, 0.0, 0.0);\r\n\r\n for(int y=-1; y<=1; y++)\r\n {\r\n for(int x=-1; x<=1; x++)\r\n {\r\n vec2 lattice = vec2(x,y);\r\n vec2 randomOffset = voronoiRandom(lattice + g, offset);\r\n float d = distance(lattice + randomOffset, f);\r\n if(d < res.x)\r\n {\r\n res = vec3(d, randomOffset.x, randomOffset.y);\r\n outValue = res.x;\r\n cells = res.y;\r\n }\r\n }\r\n }\r\n }\r\n `;\n state._emitFunction(\"voronoi\", functionString, \"// Voronoi\");\n const tempOutput = state._getFreeVariableName(\"tempOutput\");\n const tempCells = state._getFreeVariableName(\"tempCells\");\n state.compilationString += `float ${tempOutput} = 0.0;\\r\\n`;\n state.compilationString += `float ${tempCells} = 0.0;\\r\\n`;\n state.compilationString += `voronoi(${this.seed.associatedVariableName}, ${this.offset.associatedVariableName}, ${this.density.associatedVariableName}, ${tempOutput}, ${tempCells});\\r\\n`;\n if (this.output.hasEndpoints) {\n state.compilationString += this._declareOutput(this.output, state) + ` = ${tempOutput};\\r\\n`;\n }\n if (this.cells.hasEndpoints) {\n state.compilationString += this._declareOutput(this.cells, state) + ` = ${tempCells};\\r\\n`;\n }\n return this;\n }\n}\nRegisterClass(\"BABYLON.VoronoiNoiseBlock\", VoronoiNoiseBlock);\n//# sourceMappingURL=voronoiNoiseBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used as a pass through\n */\nexport class ElbowBlock extends NodeMaterialBlock {\n /**\n * Creates a new ElbowBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"ElbowBlock\";\n }\n /**\n * Gets the input component\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n /**\n * Gets or sets the target of the block\n */\n get target() {\n const input = this._inputs[0];\n if (input.isConnected) {\n const block = input.connectedPoint.ownerBlock;\n if (block.target !== NodeMaterialBlockTargets.VertexAndFragment) {\n return block.target;\n }\n if (input.connectedPoint.target !== NodeMaterialBlockTargets.VertexAndFragment) {\n return input.connectedPoint.target;\n }\n }\n return this._target;\n }\n set target(value) {\n if ((this._target & value) !== 0) {\n return;\n }\n this._target = value;\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n const input = this._inputs[0];\n state.compilationString += this._declareOutput(output, state) + ` = ${input.associatedVariableName};\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.ElbowBlock\", ElbowBlock);\n//# sourceMappingURL=elbowBlock.js.map","import { __decorate } from \"../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { NodeMaterialConnectionPointDirection } from \"../nodeMaterialBlockConnectionPoint.js\";\nimport { NodeMaterial } from \"../nodeMaterial.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { Texture } from \"../../Textures/texture.js\";\n\nimport \"../../../Shaders/ShadersInclude/helperFunctions.js\";\nimport { ImageSourceBlock } from \"./Dual/imageSourceBlock.js\";\nimport { NodeMaterialConnectionPointCustomObject } from \"../nodeMaterialConnectionPointCustomObject.js\";\nimport { EngineStore } from \"../../../Engines/engineStore.js\";\nimport { editableInPropertyPage, PropertyTypeForEdition } from \"../nodeMaterialDecorator.js\";\n/**\n * Block used to read a texture with triplanar mapping (see \"boxmap\" in https://iquilezles.org/articles/biplanar/)\n */\nexport class TriPlanarBlock extends NodeMaterialBlock {\n /**\n * Gets or sets the texture associated with the node\n */\n get texture() {\n var _a;\n if (this.source.isConnected) {\n return ((_a = this.source.connectedPoint) === null || _a === void 0 ? void 0 : _a.ownerBlock).texture;\n }\n return this._texture;\n }\n set texture(texture) {\n var _a;\n if (this._texture === texture) {\n return;\n }\n const scene = (_a = texture === null || texture === void 0 ? void 0 : texture.getScene()) !== null && _a !== void 0 ? _a : EngineStore.LastCreatedScene;\n if (!texture && scene) {\n scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(this._texture);\n });\n }\n this._texture = texture;\n if (texture && scene) {\n scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(texture);\n });\n }\n }\n /**\n * Gets the textureY associated with the node\n */\n get textureY() {\n var _a;\n if (this.sourceY.isConnected) {\n return ((_a = this.sourceY.connectedPoint) === null || _a === void 0 ? void 0 : _a.ownerBlock).texture;\n }\n return null;\n }\n /**\n * Gets the textureZ associated with the node\n */\n get textureZ() {\n var _a, _b;\n if ((_a = this.sourceZ) === null || _a === void 0 ? void 0 : _a.isConnected) {\n return ((_b = this.sourceY.connectedPoint) === null || _b === void 0 ? void 0 : _b.ownerBlock).texture;\n }\n return null;\n }\n _getImageSourceBlock(connectionPoint) {\n return (connectionPoint === null || connectionPoint === void 0 ? void 0 : connectionPoint.isConnected) ? connectionPoint.connectedPoint.ownerBlock : null;\n }\n /**\n * Gets the sampler name associated with this texture\n */\n get samplerName() {\n const imageSourceBlock = this._getImageSourceBlock(this.source);\n if (imageSourceBlock) {\n return imageSourceBlock.samplerName;\n }\n return this._samplerName;\n }\n /**\n * Gets the samplerY name associated with this texture\n */\n get samplerYName() {\n var _a, _b;\n return (_b = (_a = this._getImageSourceBlock(this.sourceY)) === null || _a === void 0 ? void 0 : _a.samplerName) !== null && _b !== void 0 ? _b : null;\n }\n /**\n * Gets the samplerZ name associated with this texture\n */\n get samplerZName() {\n var _a, _b;\n return (_b = (_a = this._getImageSourceBlock(this.sourceZ)) === null || _a === void 0 ? void 0 : _a.samplerName) !== null && _b !== void 0 ? _b : null;\n }\n /**\n * Gets a boolean indicating that this block is linked to an ImageSourceBlock\n */\n get hasImageSource() {\n return this.source.isConnected;\n }\n /**\n * Gets or sets a boolean indicating if content needs to be converted to gamma space\n */\n set convertToGammaSpace(value) {\n var _a;\n if (value === this._convertToGammaSpace) {\n return;\n }\n this._convertToGammaSpace = value;\n if (this.texture) {\n const scene = (_a = this.texture.getScene()) !== null && _a !== void 0 ? _a : EngineStore.LastCreatedScene;\n scene === null || scene === void 0 ? void 0 : scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(this.texture);\n });\n }\n }\n get convertToGammaSpace() {\n return this._convertToGammaSpace;\n }\n /**\n * Gets or sets a boolean indicating if content needs to be converted to linear space\n */\n set convertToLinearSpace(value) {\n var _a;\n if (value === this._convertToLinearSpace) {\n return;\n }\n this._convertToLinearSpace = value;\n if (this.texture) {\n const scene = (_a = this.texture.getScene()) !== null && _a !== void 0 ? _a : EngineStore.LastCreatedScene;\n scene === null || scene === void 0 ? void 0 : scene.markAllMaterialsAsDirty(1, (mat) => {\n return mat.hasTexture(this.texture);\n });\n }\n }\n get convertToLinearSpace() {\n return this._convertToLinearSpace;\n }\n /**\n * Create a new TriPlanarBlock\n * @param name defines the block name\n */\n constructor(name, hideSourceZ = false) {\n super(name, NodeMaterialBlockTargets.Neutral);\n /**\n * Project the texture(s) for a better fit to a cube\n */\n this.projectAsCube = false;\n this._convertToGammaSpace = false;\n this._convertToLinearSpace = false;\n /**\n * Gets or sets a boolean indicating if multiplication of texture with level should be disabled\n */\n this.disableLevelMultiplication = false;\n this.registerInput(\"position\", NodeMaterialBlockConnectionPointTypes.AutoDetect, false);\n this.registerInput(\"normal\", NodeMaterialBlockConnectionPointTypes.AutoDetect, false);\n this.registerInput(\"sharpness\", NodeMaterialBlockConnectionPointTypes.Float, true);\n this.registerInput(\"source\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject(\"source\", this, NodeMaterialConnectionPointDirection.Input, ImageSourceBlock, \"ImageSourceBlock\"));\n this.registerInput(\"sourceY\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject(\"sourceY\", this, NodeMaterialConnectionPointDirection.Input, ImageSourceBlock, \"ImageSourceBlock\"));\n if (!hideSourceZ) {\n this.registerInput(\"sourceZ\", NodeMaterialBlockConnectionPointTypes.Object, true, NodeMaterialBlockTargets.VertexAndFragment, new NodeMaterialConnectionPointCustomObject(\"sourceZ\", this, NodeMaterialConnectionPointDirection.Input, ImageSourceBlock, \"ImageSourceBlock\"));\n }\n this.registerOutput(\"rgba\", NodeMaterialBlockConnectionPointTypes.Color4, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"rgb\", NodeMaterialBlockConnectionPointTypes.Color3, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"r\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"g\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"b\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"a\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this.registerOutput(\"level\", NodeMaterialBlockConnectionPointTypes.Float, NodeMaterialBlockTargets.Neutral);\n this._inputs[0].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);\n this._inputs[1].addExcludedConnectionPointFromAllowedTypes(NodeMaterialBlockConnectionPointTypes.Color3 | NodeMaterialBlockConnectionPointTypes.Vector3 | NodeMaterialBlockConnectionPointTypes.Vector4);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"TriPlanarBlock\";\n }\n /**\n * Gets the position input component\n */\n get position() {\n return this._inputs[0];\n }\n /**\n * Gets the normal input component\n */\n get normal() {\n return this._inputs[1];\n }\n /**\n * Gets the sharpness input component\n */\n get sharpness() {\n return this._inputs[2];\n }\n /**\n * Gets the source input component\n */\n get source() {\n return this._inputs[3];\n }\n /**\n * Gets the sourceY input component\n */\n get sourceY() {\n return this._inputs[4];\n }\n /**\n * Gets the sourceZ input component\n */\n get sourceZ() {\n return this._inputs[5];\n }\n /**\n * Gets the rgba output component\n */\n get rgba() {\n return this._outputs[0];\n }\n /**\n * Gets the rgb output component\n */\n get rgb() {\n return this._outputs[1];\n }\n /**\n * Gets the r output component\n */\n get r() {\n return this._outputs[2];\n }\n /**\n * Gets the g output component\n */\n get g() {\n return this._outputs[3];\n }\n /**\n * Gets the b output component\n */\n get b() {\n return this._outputs[4];\n }\n /**\n * Gets the a output component\n */\n get a() {\n return this._outputs[5];\n }\n /**\n * Gets the level output component\n */\n get level() {\n return this._outputs[6];\n }\n prepareDefines(mesh, nodeMaterial, defines) {\n if (!defines._areTexturesDirty) {\n return;\n }\n const toGamma = this.convertToGammaSpace && this.texture && !this.texture.gammaSpace;\n const toLinear = this.convertToLinearSpace && this.texture && this.texture.gammaSpace;\n // Not a bug... Name defines the texture space not the required conversion\n defines.setValue(this._linearDefineName, toGamma, true);\n defines.setValue(this._gammaDefineName, toLinear, true);\n }\n isReady() {\n if (this.texture && !this.texture.isReadyOrNotBlocking()) {\n return false;\n }\n return true;\n }\n bind(effect) {\n if (!this.texture) {\n return;\n }\n effect.setFloat(this._textureInfoName, this.texture.level);\n if (!this._imageSource) {\n effect.setTexture(this._samplerName, this.texture);\n }\n }\n _generateTextureLookup(state) {\n var _a, _b;\n const samplerName = this.samplerName;\n const samplerYName = (_a = this.samplerYName) !== null && _a !== void 0 ? _a : samplerName;\n const samplerZName = (_b = this.samplerZName) !== null && _b !== void 0 ? _b : samplerName;\n const sharpness = this.sharpness.isConnected ? this.sharpness.associatedVariableName : \"1.0\";\n const x = state._getFreeVariableName(\"x\");\n const y = state._getFreeVariableName(\"y\");\n const z = state._getFreeVariableName(\"z\");\n const w = state._getFreeVariableName(\"w\");\n const n = state._getFreeVariableName(\"n\");\n const uvx = state._getFreeVariableName(\"uvx\");\n const uvy = state._getFreeVariableName(\"uvy\");\n const uvz = state._getFreeVariableName(\"uvz\");\n state.compilationString += `\r\n vec3 ${n} = ${this.normal.associatedVariableName}.xyz;\r\n\r\n vec2 ${uvx} = ${this.position.associatedVariableName}.yz;\r\n vec2 ${uvy} = ${this.position.associatedVariableName}.zx;\r\n vec2 ${uvz} = ${this.position.associatedVariableName}.xy;\r\n `;\n if (this.projectAsCube) {\n state.compilationString += `\r\n ${uvx}.xy = ${uvx}.yx;\r\n\r\n if (${n}.x >= 0.0) {\r\n ${uvx}.x = -${uvx}.x;\r\n }\r\n if (${n}.y < 0.0) {\r\n ${uvy}.y = -${uvy}.y;\r\n }\r\n if (${n}.z < 0.0) {\r\n ${uvz}.x = -${uvz}.x;\r\n }\r\n `;\n }\n state.compilationString += `\r\n vec4 ${x} = texture2D(${samplerName}, ${uvx});\r\n vec4 ${y} = texture2D(${samplerYName}, ${uvy});\r\n vec4 ${z} = texture2D(${samplerZName}, ${uvz});\r\n \r\n // blend weights\r\n vec3 ${w} = pow(abs(${n}), vec3(${sharpness}));\r\n\r\n // blend and return\r\n vec4 ${this._tempTextureRead} = (${x}*${w}.x + ${y}*${w}.y + ${z}*${w}.z) / (${w}.x + ${w}.y + ${w}.z); \r\n `;\n }\n _generateConversionCode(state, output, swizzle) {\n if (swizzle !== \"a\") {\n // no conversion if the output is \"a\" (alpha)\n if (!this.texture || !this.texture.gammaSpace) {\n state.compilationString += `#ifdef ${this._linearDefineName}\r\n ${output.associatedVariableName} = toGammaSpace(${output.associatedVariableName});\r\n #endif\r\n `;\n }\n state.compilationString += `#ifdef ${this._gammaDefineName}\r\n ${output.associatedVariableName} = toLinearSpace(${output.associatedVariableName});\r\n #endif\r\n `;\n }\n }\n _writeOutput(state, output, swizzle) {\n let complement = \"\";\n if (!this.disableLevelMultiplication) {\n complement = ` * ${this._textureInfoName}`;\n }\n state.compilationString += `${this._declareOutput(output, state)} = ${this._tempTextureRead}.${swizzle}${complement};\\r\\n`;\n this._generateConversionCode(state, output, swizzle);\n }\n _buildBlock(state) {\n super._buildBlock(state);\n if (this.source.isConnected) {\n this._imageSource = this.source.connectedPoint.ownerBlock;\n }\n else {\n this._imageSource = null;\n }\n this._textureInfoName = state._getFreeVariableName(\"textureInfoName\");\n this.level.associatedVariableName = this._textureInfoName;\n this._tempTextureRead = state._getFreeVariableName(\"tempTextureRead\");\n this._linearDefineName = state._getFreeDefineName(\"ISLINEAR\");\n this._gammaDefineName = state._getFreeDefineName(\"ISGAMMA\");\n if (!this._imageSource) {\n this._samplerName = state._getFreeVariableName(this.name + \"Sampler\");\n state._emit2DSampler(this._samplerName);\n }\n // Declarations\n state.sharedData.blockingBlocks.push(this);\n state.sharedData.textureBlocks.push(this);\n state.sharedData.blocksWithDefines.push(this);\n state.sharedData.bindableBlocks.push(this);\n const comments = `//${this.name}`;\n state._emitFunctionFromInclude(\"helperFunctions\", comments);\n state._emitUniformFromString(this._textureInfoName, \"float\");\n this._generateTextureLookup(state);\n for (const output of this._outputs) {\n if (output.hasEndpoints && output.name !== \"level\") {\n this._writeOutput(state, output, output.name);\n }\n }\n return this;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n codeString += `${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace};\\r\\n`;\n codeString += `${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace};\\r\\n`;\n codeString += `${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication};\\r\\n`;\n codeString += `${this._codeVariableName}.projectAsCube = ${this.projectAsCube};\\r\\n`;\n if (!this.texture) {\n return codeString;\n }\n codeString += `${this._codeVariableName}.texture = new BABYLON.Texture(\"${this.texture.name}\", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode});\\r\\n`;\n codeString += `${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.uAng = ${this.texture.uAng};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.vAng = ${this.texture.vAng};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.wAng = ${this.texture.wAng};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.uScale = ${this.texture.uScale};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.vScale = ${this.texture.vScale};\\r\\n`;\n codeString += `${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode};\\r\\n`;\n return codeString;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.convertToGammaSpace = this.convertToGammaSpace;\n serializationObject.convertToLinearSpace = this.convertToLinearSpace;\n serializationObject.disableLevelMultiplication = this.disableLevelMultiplication;\n serializationObject.projectAsCube = this.projectAsCube;\n if (!this.hasImageSource && this.texture && !this.texture.isRenderTarget && this.texture.getClassName() !== \"VideoTexture\") {\n serializationObject.texture = this.texture.serialize();\n }\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.convertToGammaSpace = serializationObject.convertToGammaSpace;\n this.convertToLinearSpace = !!serializationObject.convertToLinearSpace;\n this.disableLevelMultiplication = !!serializationObject.disableLevelMultiplication;\n this.projectAsCube = !!serializationObject.projectAsCube;\n if (serializationObject.texture && !NodeMaterial.IgnoreTexturesAtLoadTime && serializationObject.texture.url !== undefined) {\n rootUrl = serializationObject.texture.url.indexOf(\"data:\") === 0 ? \"\" : rootUrl;\n this.texture = Texture.Parse(serializationObject.texture, scene, rootUrl);\n }\n }\n}\n__decorate([\n editableInPropertyPage(\"Project as cube\", PropertyTypeForEdition.Boolean, \"ADVANCED\", { notifiers: { update: true } })\n], TriPlanarBlock.prototype, \"projectAsCube\", void 0);\nRegisterClass(\"BABYLON.TriPlanarBlock\", TriPlanarBlock);\n//# sourceMappingURL=triPlanarBlock.js.map","import { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { TriPlanarBlock } from \"./triPlanarBlock.js\";\n/**\n * Block used to read a texture with triplanar mapping (see https://iquilezles.org/articles/biplanar/)\n */\nexport class BiPlanarBlock extends TriPlanarBlock {\n /**\n * Create a new BiPlanarBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, true);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"BiPlanarBlock\";\n }\n _generateTextureLookup(state) {\n var _a;\n const samplerName = this.samplerName;\n const samplerYName = (_a = this.samplerYName) !== null && _a !== void 0 ? _a : this.samplerName;\n const sharpness = this.sharpness.isConnected ? this.sharpness.associatedVariableName : \"1.0\";\n const dpdx = state._getFreeVariableName(\"dpdx\");\n const dpdy = state._getFreeVariableName(\"dpdy\");\n const n = state._getFreeVariableName(\"n\");\n const ma = state._getFreeVariableName(\"ma\");\n const mi = state._getFreeVariableName(\"mi\");\n const me = state._getFreeVariableName(\"me\");\n const x = state._getFreeVariableName(\"x\");\n const y = state._getFreeVariableName(\"y\");\n const w = state._getFreeVariableName(\"y\");\n state.compilationString += `\r\n // grab coord derivatives for texturing\r\n vec3 ${dpdx} = dFdx(${this.position.associatedVariableName}.xyz);\r\n vec3 ${dpdy} = dFdy(${this.position.associatedVariableName}.xyz);\r\n vec3 ${n} = abs(${this.normal.associatedVariableName}.xyz);\r\n \r\n // determine major axis (in x; yz are following axis)\r\n ivec3 ${ma} = (${n}.x>${n}.y && ${n}.x>${n}.z) ? ivec3(0,1,2) :\r\n (${n}.y>${n}.z) ? ivec3(1,2,0) :\r\n ivec3(2,0,1) ;\r\n // determine minor axis (in x; yz are following axis)\r\n ivec3 ${mi} = (${n}.x<${n}.y && ${n}.x<${n}.z) ? ivec3(0,1,2) :\r\n (${n}.y<${n}.z) ? ivec3(1,2,0) :\r\n ivec3(2,0,1) ;\r\n // determine median axis (in x; yz are following axis)\r\n ivec3 ${me} = ivec3(3) - ${mi} - ${ma};\r\n \r\n // project+fetch\r\n vec4 ${x} = textureGrad( ${samplerName}, vec2( ${this.position.associatedVariableName}[${ma}.y], ${this.position.associatedVariableName}[${ma}.z]), \r\n vec2(${dpdx}[${ma}.y],${dpdx}[${ma}.z]), \r\n vec2(${dpdy}[${ma}.y],${dpdy}[${ma}.z]) );\r\n vec4 ${y} = textureGrad( ${samplerYName}, vec2( ${this.position.associatedVariableName}[${me}.y], ${this.position.associatedVariableName}[${me}.z]), \r\n vec2(${dpdx}[${me}.y],${dpdx}[${me}.z]),\r\n vec2(${dpdy}[${me}.y],${dpdy}[${me}.z]) );\r\n \r\n // blend factors\r\n vec2 ${w} = vec2(${n}[${ma}.x],${n}[${me}.x]);\r\n // make local support\r\n ${w} = clamp( (${w}-0.5773)/(1.0-0.5773), 0.0, 1.0 );\r\n // shape transition\r\n ${w} = pow( ${w}, vec2(${sharpness}/8.0) );\r\n // blend and return\r\n vec4 ${this._tempTextureRead} = (${x}*${w}.x + ${y}*${w}.y) / (${w}.x + ${w}.y);\r\n `;\n }\n}\nRegisterClass(\"BABYLON.BiPlanarBlock\", BiPlanarBlock);\n//# sourceMappingURL=biPlanarBlock.js.map","import { __decorate } from \"../../../tslib.es6.js\";\nimport { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { InputBlock } from \"./Input/inputBlock.js\";\nimport { MorphTargetsBlock } from \"./Vertex/morphTargetsBlock.js\";\nimport { PropertyTypeForEdition, editableInPropertyPage } from \"../nodeMaterialDecorator.js\";\nexport var MeshAttributeExistsBlockTypes;\n(function (MeshAttributeExistsBlockTypes) {\n MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes[\"None\"] = 0] = \"None\";\n MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes[\"Normal\"] = 1] = \"Normal\";\n MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes[\"Tangent\"] = 2] = \"Tangent\";\n MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes[\"VertexColor\"] = 3] = \"VertexColor\";\n MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes[\"UV1\"] = 4] = \"UV1\";\n MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes[\"UV2\"] = 5] = \"UV2\";\n MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes[\"UV3\"] = 6] = \"UV3\";\n MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes[\"UV4\"] = 7] = \"UV4\";\n MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes[\"UV5\"] = 8] = \"UV5\";\n MeshAttributeExistsBlockTypes[MeshAttributeExistsBlockTypes[\"UV6\"] = 9] = \"UV6\";\n})(MeshAttributeExistsBlockTypes || (MeshAttributeExistsBlockTypes = {}));\n/**\n * Block used to check if Mesh attribute of specified type exists\n * and provide an alternative fallback input for to use in such case\n */\nexport class MeshAttributeExistsBlock extends NodeMaterialBlock {\n /**\n * Creates a new MeshAttributeExistsBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n /**\n * Defines which mesh attribute to use\n */\n this.attributeType = MeshAttributeExistsBlockTypes.None;\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerInput(\"fallback\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._linkConnectionTypes(0, 1);\n // Try to auto determine attributeType\n this._inputs[0].onConnectionObservable.add((other) => {\n var _a;\n if (this.attributeType) {\n // But only if not already specified\n return;\n }\n const sourceBlock = other.ownerBlock;\n if (sourceBlock instanceof InputBlock && sourceBlock.isAttribute) {\n switch (sourceBlock.name) {\n case \"color\":\n this.attributeType = MeshAttributeExistsBlockTypes.VertexColor;\n break;\n case \"normal\":\n this.attributeType = MeshAttributeExistsBlockTypes.Normal;\n break;\n case \"tangent\":\n this.attributeType = MeshAttributeExistsBlockTypes.Tangent;\n break;\n case \"uv\":\n this.attributeType = MeshAttributeExistsBlockTypes.UV1;\n break;\n case \"uv2\":\n this.attributeType = MeshAttributeExistsBlockTypes.UV2;\n break;\n case \"uv3\":\n this.attributeType = MeshAttributeExistsBlockTypes.UV3;\n break;\n case \"uv4\":\n this.attributeType = MeshAttributeExistsBlockTypes.UV4;\n break;\n case \"uv5\":\n this.attributeType = MeshAttributeExistsBlockTypes.UV5;\n break;\n case \"uv6\":\n this.attributeType = MeshAttributeExistsBlockTypes.UV6;\n break;\n }\n }\n else if (sourceBlock instanceof MorphTargetsBlock) {\n switch ((_a = this.input.connectedPoint) === null || _a === void 0 ? void 0 : _a.name) {\n case \"normalOutput\":\n this.attributeType = MeshAttributeExistsBlockTypes.Normal;\n break;\n case \"tangentOutput\":\n this.attributeType = MeshAttributeExistsBlockTypes.Tangent;\n break;\n case \"uvOutput\":\n this.attributeType = MeshAttributeExistsBlockTypes.UV1;\n break;\n }\n }\n });\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"MeshAttributeExistsBlock\";\n }\n /**\n * Gets the input component\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the fallback component when speciefied attribute doesn't exist\n */\n get fallback() {\n return this._inputs[1];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n let attributeDefine = null;\n switch (this.attributeType) {\n case MeshAttributeExistsBlockTypes.VertexColor:\n attributeDefine = \"VERTEXCOLOR_NME\";\n break;\n case MeshAttributeExistsBlockTypes.Normal:\n attributeDefine = \"NORMAL\";\n break;\n case MeshAttributeExistsBlockTypes.Tangent:\n attributeDefine = \"TANGENT\";\n break;\n case MeshAttributeExistsBlockTypes.UV1:\n attributeDefine = \"UV1\";\n break;\n case MeshAttributeExistsBlockTypes.UV2:\n attributeDefine = \"UV2\";\n break;\n case MeshAttributeExistsBlockTypes.UV3:\n attributeDefine = \"UV3\";\n break;\n case MeshAttributeExistsBlockTypes.UV4:\n attributeDefine = \"UV4\";\n break;\n case MeshAttributeExistsBlockTypes.UV5:\n attributeDefine = \"UV5\";\n break;\n case MeshAttributeExistsBlockTypes.UV6:\n attributeDefine = \"UV6\";\n break;\n }\n const output = this._declareOutput(this.output, state);\n if (attributeDefine) {\n state.compilationString += `#ifdef ${attributeDefine}\\r\\n`;\n }\n state.compilationString += `${output} = ${this.input.associatedVariableName};\\r\\n`;\n if (attributeDefine) {\n state.compilationString += `#else\\r\\n`;\n state.compilationString += `${output} = ${this.fallback.associatedVariableName};\\r\\n`;\n state.compilationString += `#endif\\r\\n`;\n }\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.attributeType = this.attributeType;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n var _a;\n super._deserialize(serializationObject, scene, rootUrl);\n this.attributeType = (_a = serializationObject.attributeType) !== null && _a !== void 0 ? _a : MeshAttributeExistsBlockTypes.None;\n }\n _dumpPropertiesCode() {\n let codeString = super._dumpPropertiesCode();\n codeString += `${this._codeVariableName}.attributeType = ${this.attributeType};\\r\\n`;\n return codeString;\n }\n}\n__decorate([\n editableInPropertyPage(\"Attribute lookup\", PropertyTypeForEdition.List, undefined, {\n notifiers: { update: true },\n options: [\n { label: \"(None)\", value: MeshAttributeExistsBlockTypes.None },\n { label: \"Normal\", value: MeshAttributeExistsBlockTypes.Normal },\n { label: \"Tangent\", value: MeshAttributeExistsBlockTypes.Tangent },\n { label: \"Vertex Color\", value: MeshAttributeExistsBlockTypes.VertexColor },\n { label: \"UV1\", value: MeshAttributeExistsBlockTypes.UV1 },\n { label: \"UV2\", value: MeshAttributeExistsBlockTypes.UV2 },\n { label: \"UV3\", value: MeshAttributeExistsBlockTypes.UV3 },\n { label: \"UV4\", value: MeshAttributeExistsBlockTypes.UV4 },\n { label: \"UV5\", value: MeshAttributeExistsBlockTypes.UV5 },\n { label: \"UV6\", value: MeshAttributeExistsBlockTypes.UV6 },\n ],\n })\n], MeshAttributeExistsBlock.prototype, \"attributeType\", void 0);\nRegisterClass(\"BABYLON.MeshAttributeExistsBlock\", MeshAttributeExistsBlock);\n//# sourceMappingURL=meshAttributeExistsBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to compute the determinant of a matrix\n */\nexport class MatrixDeterminantBlock extends NodeMaterialBlock {\n /**\n * Creates a new MatrixDeterminantBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.Matrix);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Float);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"MatrixDeterminantBlock\";\n }\n /**\n * Gets the input matrix\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this.output;\n const input = this.input;\n state.compilationString += this._declareOutput(output, state) + `${output.associatedVariableName} = determinant(${input.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.MatrixDeterminantBlock\", MatrixDeterminantBlock);\n//# sourceMappingURL=matrixDeterminantBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Block used to transpose a matrix\n */\nexport class MatrixTransposeBlock extends NodeMaterialBlock {\n /**\n * Creates a new MatrixTransposeBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.Matrix);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.Matrix);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"MatrixTransposeBlock\";\n }\n /**\n * Gets the input matrix\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this.output;\n const input = this.input;\n state.compilationString += this._declareOutput(output, state) + `${output.associatedVariableName} = transpose(${input.associatedVariableName});\\r\\n`;\n return this;\n }\n}\nRegisterClass(\"BABYLON.MatrixTransposeBlock\", MatrixTransposeBlock);\n//# sourceMappingURL=matrixTransposeBlock.js.map","import { NodeMaterialBlock } from \"../nodeMaterialBlock.js\";\nimport { NodeMaterialBlockConnectionPointTypes } from \"../Enums/nodeMaterialBlockConnectionPointTypes.js\";\nimport { NodeMaterialBlockTargets } from \"../Enums/nodeMaterialBlockTargets.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\n/**\n * Types of curves supported by the Curve block\n */\nexport var CurveBlockTypes;\n(function (CurveBlockTypes) {\n /** EaseInSine */\n CurveBlockTypes[CurveBlockTypes[\"EaseInSine\"] = 0] = \"EaseInSine\";\n /** EaseOutSine */\n CurveBlockTypes[CurveBlockTypes[\"EaseOutSine\"] = 1] = \"EaseOutSine\";\n /** EaseInOutSine */\n CurveBlockTypes[CurveBlockTypes[\"EaseInOutSine\"] = 2] = \"EaseInOutSine\";\n /** EaseInQuad */\n CurveBlockTypes[CurveBlockTypes[\"EaseInQuad\"] = 3] = \"EaseInQuad\";\n /** EaseOutQuad */\n CurveBlockTypes[CurveBlockTypes[\"EaseOutQuad\"] = 4] = \"EaseOutQuad\";\n /** EaseInOutQuad */\n CurveBlockTypes[CurveBlockTypes[\"EaseInOutQuad\"] = 5] = \"EaseInOutQuad\";\n /** EaseInCubic */\n CurveBlockTypes[CurveBlockTypes[\"EaseInCubic\"] = 6] = \"EaseInCubic\";\n /** EaseOutCubic */\n CurveBlockTypes[CurveBlockTypes[\"EaseOutCubic\"] = 7] = \"EaseOutCubic\";\n /** EaseInOutCubic */\n CurveBlockTypes[CurveBlockTypes[\"EaseInOutCubic\"] = 8] = \"EaseInOutCubic\";\n /** EaseInQuart */\n CurveBlockTypes[CurveBlockTypes[\"EaseInQuart\"] = 9] = \"EaseInQuart\";\n /** EaseOutQuart */\n CurveBlockTypes[CurveBlockTypes[\"EaseOutQuart\"] = 10] = \"EaseOutQuart\";\n /** EaseInOutQuart */\n CurveBlockTypes[CurveBlockTypes[\"EaseInOutQuart\"] = 11] = \"EaseInOutQuart\";\n /** EaseInQuint */\n CurveBlockTypes[CurveBlockTypes[\"EaseInQuint\"] = 12] = \"EaseInQuint\";\n /** EaseOutQuint */\n CurveBlockTypes[CurveBlockTypes[\"EaseOutQuint\"] = 13] = \"EaseOutQuint\";\n /** EaseInOutQuint */\n CurveBlockTypes[CurveBlockTypes[\"EaseInOutQuint\"] = 14] = \"EaseInOutQuint\";\n /** EaseInExpo */\n CurveBlockTypes[CurveBlockTypes[\"EaseInExpo\"] = 15] = \"EaseInExpo\";\n /** EaseOutExpo */\n CurveBlockTypes[CurveBlockTypes[\"EaseOutExpo\"] = 16] = \"EaseOutExpo\";\n /** EaseInOutExpo */\n CurveBlockTypes[CurveBlockTypes[\"EaseInOutExpo\"] = 17] = \"EaseInOutExpo\";\n /** EaseInCirc */\n CurveBlockTypes[CurveBlockTypes[\"EaseInCirc\"] = 18] = \"EaseInCirc\";\n /** EaseOutCirc */\n CurveBlockTypes[CurveBlockTypes[\"EaseOutCirc\"] = 19] = \"EaseOutCirc\";\n /** EaseInOutCirc */\n CurveBlockTypes[CurveBlockTypes[\"EaseInOutCirc\"] = 20] = \"EaseInOutCirc\";\n /** EaseInBack */\n CurveBlockTypes[CurveBlockTypes[\"EaseInBack\"] = 21] = \"EaseInBack\";\n /** EaseOutBack */\n CurveBlockTypes[CurveBlockTypes[\"EaseOutBack\"] = 22] = \"EaseOutBack\";\n /** EaseInOutBack */\n CurveBlockTypes[CurveBlockTypes[\"EaseInOutBack\"] = 23] = \"EaseInOutBack\";\n /** EaseInElastic */\n CurveBlockTypes[CurveBlockTypes[\"EaseInElastic\"] = 24] = \"EaseInElastic\";\n /** EaseOutElastic */\n CurveBlockTypes[CurveBlockTypes[\"EaseOutElastic\"] = 25] = \"EaseOutElastic\";\n /** EaseInOutElastic */\n CurveBlockTypes[CurveBlockTypes[\"EaseInOutElastic\"] = 26] = \"EaseInOutElastic\";\n})(CurveBlockTypes || (CurveBlockTypes = {}));\n/**\n * Block used to apply curve operation\n */\nexport class CurveBlock extends NodeMaterialBlock {\n /**\n * Creates a new CurveBlock\n * @param name defines the block name\n */\n constructor(name) {\n super(name, NodeMaterialBlockTargets.Neutral);\n /**\n * Gets or sets the type of the curve applied by the block\n */\n this.type = CurveBlockTypes.EaseInOutSine;\n this.registerInput(\"input\", NodeMaterialBlockConnectionPointTypes.AutoDetect);\n this.registerOutput(\"output\", NodeMaterialBlockConnectionPointTypes.BasedOnInput);\n this._outputs[0]._typeConnectionSource = this._inputs[0];\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Matrix);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Object);\n this._inputs[0].excludedConnectionPointTypes.push(NodeMaterialBlockConnectionPointTypes.Int);\n }\n /**\n * Gets the current class name\n * @returns the class name\n */\n getClassName() {\n return \"CurveBlock\";\n }\n /**\n * Gets the input component\n */\n get input() {\n return this._inputs[0];\n }\n /**\n * Gets the output component\n */\n get output() {\n return this._outputs[0];\n }\n _duplicateEntry(entry, component) {\n return `ret.${component} = ${entry.replace(/VAL/g, \"v.\" + component)}`;\n }\n _duplicateEntryDirect(entry) {\n return `return ${entry.replace(/VAL/g, \"v\")}`;\n }\n _duplicateVector(entry, inputType) {\n if (inputType === \"float\") {\n return this._duplicateEntryDirect(entry);\n }\n const size = parseInt(inputType.replace(\"vec\", \"\"));\n let code = `\r\n vec${size} ret = vec${size}(0.0);\r\n `;\n for (let i = 1; i <= size; i++) {\n code += this._duplicateEntry(entry, i === 1 ? \"x\" : i === 2 ? \"y\" : i === 3 ? \"z\" : \"w\") + \";\\r\\n\";\n }\n code += \"return ret;\\r\\n\";\n return code;\n }\n _buildBlock(state) {\n super._buildBlock(state);\n const output = this._outputs[0];\n let registeredFunction = \"\";\n let registeredFunctionName = \"\";\n let inputType = \"\";\n switch (this.input.type) {\n case NodeMaterialBlockConnectionPointTypes.Float:\n inputType = \"float\";\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector2:\n inputType = \"vec2\";\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector3:\n case NodeMaterialBlockConnectionPointTypes.Color3:\n inputType = \"vec3\";\n break;\n case NodeMaterialBlockConnectionPointTypes.Vector4:\n case NodeMaterialBlockConnectionPointTypes.Color4:\n inputType = \"vec4\";\n break;\n }\n registeredFunctionName = CurveBlockTypes[this.type] + \"_\" + inputType;\n switch (this.type) {\n case CurveBlockTypes.EaseInSine:\n registeredFunction = `return 1.0 - cos((v * 3.1415) / 2.0)`;\n break;\n case CurveBlockTypes.EaseOutSine:\n registeredFunction = `return sin((v * 3.1415) / 2.0)`;\n break;\n case CurveBlockTypes.EaseInOutSine:\n registeredFunction = `return -(cos(v * 3.1415) - 1.0) / 2.0`;\n break;\n case CurveBlockTypes.EaseInQuad:\n registeredFunction = `return v * v`;\n break;\n case CurveBlockTypes.EaseOutQuad:\n registeredFunction = `return (1.0 - v) * (1.0 - v)`;\n break;\n case CurveBlockTypes.EaseInOutQuad: {\n const entry = \"VAL < 0.5 ? 2.0 * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInCubic:\n registeredFunction = `return v * v * v`;\n break;\n case CurveBlockTypes.EaseOutCubic: {\n const entry = \"1.0 - pow(1.0 - VAL, 3.0)\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInOutCubic: {\n const entry = \"VAL < 0.5 ? 4.0 * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInQuart:\n registeredFunction = `return v * v * v * v`;\n break;\n case CurveBlockTypes.EaseOutQuart: {\n const entry = \"1.0 - pow(1.0 - VAL, 4.0)\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInOutQuart: {\n const entry = \"VAL < 0.5 ? 8.0 * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInQuint:\n registeredFunction = `return v * v * v * v * v`;\n break;\n case CurveBlockTypes.EaseOutQuint: {\n const entry = \"1.0 - pow(1.0 - VAL, 5.0)\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInOutQuint: {\n const entry = \"VAL < 0.5 ? 16.0 * VAL * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInExpo: {\n const entry = \"VAL == 0.0 ? 0.0 : pow(2.0, 10.0 * VAL - 10.0)\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseOutExpo: {\n const entry = \"VAL == 1.0 ? 1.0 : 1.0 - pow(2.0, -10.0 * VAL)\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInOutExpo: {\n const entry = \"VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : VAL < 0.5 ? pow(2.0, 20.0 * VAL - 10.0) / 2.0 : (2.0 - pow(2.0, -20.0 * VAL + 10.0)) / 2.0\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInCirc: {\n const entry = \"1.0 - sqrt(1.0 - pow(VAL, 2.0))\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseOutCirc: {\n const entry = \"sqrt(1.0 - pow(VAL - 1.0, 2.0))\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInOutCirc: {\n const entry = \"VAL < 0.5 ? (1.0 - sqrt(1.0 - pow(2.0 * VAL, 2.0))) / 2.0 : (sqrt(1.0 - pow(-2.0 * VAL + 2.0, 2.0)) + 1.0) / 2.0\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInBack: {\n registeredFunction = \"return 2.70158 * v * v * v - 1.70158 * v * v\";\n break;\n }\n case CurveBlockTypes.EaseOutBack: {\n const entry = \"2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInOutBack: {\n const entry = \"VAL < 0.5 ? (pow(2.0 * VAL, 2.0) * ((3.5949095) * 2.0 * VAL - 2.5949095)) / 2.0 : (pow(2.0 * VAL - 2.0, 2.0) * (3.5949095 * (VAL * 2.0 - 2.0) + 3.5949095) + 2.0) / 2.0\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInElastic: {\n const entry = \"VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : -pow(2.0, 10.0 * VAL - 10.0) * sin((VAL * 10.0 - 10.75) * ((2.0 * 3.1415) / 3.0))\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseOutElastic: {\n const entry = \"VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : pow(2.0, -10.0 * VAL) * sin((VAL * 10.0 - 0.75) * ((2.0 * 3.1415) / 3.0)) + 1.0\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n case CurveBlockTypes.EaseInOutElastic: {\n const entry = \"VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : VAL < 0.5 ? -(pow(2.0, 20.0 * VAL - 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 : (pow(2.0, -20.0 * VAL + 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 + 1.0\";\n registeredFunction = this._duplicateVector(entry, inputType);\n break;\n }\n }\n state._emitFunction(registeredFunctionName, `${inputType} ${registeredFunctionName}(${inputType} v) {${registeredFunction};}\\r\\n`, \"\");\n state.compilationString += this._declareOutput(output, state) + ` = ${registeredFunctionName}(${this.input.associatedVariableName});\\r\\n`;\n return this;\n }\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.curveType = this.type;\n return serializationObject;\n }\n _deserialize(serializationObject, scene, rootUrl) {\n super._deserialize(serializationObject, scene, rootUrl);\n this.type = serializationObject.curveType;\n }\n _dumpPropertiesCode() {\n const codeString = super._dumpPropertiesCode() + `${this._codeVariableName}.type = BABYLON.CurveBlockTypes.${CurveBlockTypes[this.type]};\\r\\n`;\n return codeString;\n }\n}\nRegisterClass(\"BABYLON.CurveBlock\", CurveBlock);\n//# sourceMappingURL=curveBlock.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./Vertex/index.js\";\nexport * from \"./Fragment/index.js\";\nexport * from \"./Dual/index.js\";\nexport * from \"./Input/index.js\";\nexport * from \"./multiplyBlock.js\";\nexport * from \"./addBlock.js\";\nexport * from \"./scaleBlock.js\";\nexport * from \"./clampBlock.js\";\nexport * from \"./crossBlock.js\";\nexport * from \"./customBlock.js\";\nexport * from \"./dotBlock.js\";\nexport * from \"./transformBlock.js\";\nexport * from \"./remapBlock.js\";\nexport * from \"./normalizeBlock.js\";\nexport * from \"./trigonometryBlock.js\";\nexport * from \"./colorMergerBlock.js\";\nexport * from \"./vectorMergerBlock.js\";\nexport * from \"./colorSplitterBlock.js\";\nexport * from \"./vectorSplitterBlock.js\";\nexport * from \"./lerpBlock.js\";\nexport * from \"./divideBlock.js\";\nexport * from \"./subtractBlock.js\";\nexport * from \"./stepBlock.js\";\nexport * from \"./oneMinusBlock.js\";\nexport * from \"./viewDirectionBlock.js\";\nexport * from \"./fresnelBlock.js\";\nexport * from \"./maxBlock.js\";\nexport * from \"./minBlock.js\";\nexport * from \"./distanceBlock.js\";\nexport * from \"./lengthBlock.js\";\nexport * from \"./negateBlock.js\";\nexport * from \"./powBlock.js\";\nexport * from \"./randomNumberBlock.js\";\nexport * from \"./arcTan2Block.js\";\nexport * from \"./smoothStepBlock.js\";\nexport * from \"./reciprocalBlock.js\";\nexport * from \"./replaceColorBlock.js\";\nexport * from \"./posterizeBlock.js\";\nexport * from \"./waveBlock.js\";\nexport * from \"./gradientBlock.js\";\nexport * from \"./nLerpBlock.js\";\nexport * from \"./worleyNoise3DBlock.js\";\nexport * from \"./simplexPerlin3DBlock.js\";\nexport * from \"./normalBlendBlock.js\";\nexport * from \"./rotate2dBlock.js\";\nexport * from \"./reflectBlock.js\";\nexport * from \"./refractBlock.js\";\nexport * from \"./desaturateBlock.js\";\nexport * from \"./PBR/index.js\";\nexport * from \"./Particle/index.js\";\nexport * from \"./modBlock.js\";\nexport * from \"./matrixBuilderBlock.js\";\nexport * from \"./conditionalBlock.js\";\nexport * from \"./cloudBlock.js\";\nexport * from \"./voronoiNoiseBlock.js\";\nexport * from \"./elbowBlock.js\";\nexport * from \"./triPlanarBlock.js\";\nexport * from \"./biPlanarBlock.js\";\nexport * from \"./matrixDeterminantBlock.js\";\nexport * from \"./matrixTransposeBlock.js\";\nexport * from \"./meshAttributeExistsBlock.js\";\nexport * from \"./curveBlock.js\";\n//# sourceMappingURL=index.js.map","import { Effect } from \"./effect.js\";\nimport { RandomGUID } from \"../Misc/guid.js\";\nimport { DrawWrapper } from \"./drawWrapper.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nclass MapMap {\n constructor() {\n this.mm = new Map();\n }\n get(a, b) {\n const m = this.mm.get(a);\n if (m !== undefined) {\n return m.get(b);\n }\n return undefined;\n }\n set(a, b, v) {\n let m = this.mm.get(a);\n if (m === undefined) {\n this.mm.set(a, (m = new Map()));\n }\n m.set(b, v);\n }\n}\n/**\n * Class that can be used to wrap a base material to generate accurate shadows when using custom vertex/fragment code in the base material\n */\nexport class ShadowDepthWrapper {\n /** Gets the standalone status of the wrapper */\n get standalone() {\n var _a, _b;\n return (_b = (_a = this._options) === null || _a === void 0 ? void 0 : _a.standalone) !== null && _b !== void 0 ? _b : false;\n }\n /** Gets the base material the wrapper is built upon */\n get baseMaterial() {\n return this._baseMaterial;\n }\n /** Gets the doNotInjectCode status of the wrapper */\n get doNotInjectCode() {\n var _a, _b;\n return (_b = (_a = this._options) === null || _a === void 0 ? void 0 : _a.doNotInjectCode) !== null && _b !== void 0 ? _b : false;\n }\n /**\n * Instantiate a new shadow depth wrapper.\n * It works by injecting some specific code in the vertex/fragment shaders of the base material and is used by a shadow generator to\n * generate the shadow depth map. For more information, please refer to the documentation:\n * https://doc.babylonjs.com/features/featuresDeepDive/lights/shadows\n * @param baseMaterial Material to wrap\n * @param scene Define the scene the material belongs to\n * @param options Options used to create the wrapper\n */\n constructor(baseMaterial, scene, options) {\n this._baseMaterial = baseMaterial;\n this._scene = scene !== null && scene !== void 0 ? scene : EngineStore.LastCreatedScene;\n this._options = options;\n this._subMeshToEffect = new Map();\n this._subMeshToDepthWrapper = new MapMap();\n this._meshes = new Map();\n // Register for onEffectCreated to store the effect of the base material when it is (re)generated. This effect will be used\n // to create the depth effect later on\n this._onEffectCreatedObserver = this._baseMaterial.onEffectCreatedObservable.add((params) => {\n var _a;\n const mesh = (_a = params.subMesh) === null || _a === void 0 ? void 0 : _a.getMesh();\n if (mesh && !this._meshes.has(mesh)) {\n // Register for mesh onDispose to clean up our internal maps when a mesh is disposed\n this._meshes.set(mesh, mesh.onDisposeObservable.add((mesh) => {\n const iterator = this._subMeshToEffect.keys();\n for (let key = iterator.next(); key.done !== true; key = iterator.next()) {\n const subMesh = key.value;\n if ((subMesh === null || subMesh === void 0 ? void 0 : subMesh.getMesh()) === mesh) {\n this._subMeshToEffect.delete(subMesh);\n this._subMeshToDepthWrapper.mm.delete(subMesh);\n }\n }\n }));\n }\n this._subMeshToEffect.set(params.subMesh, [params.effect, this._scene.getEngine().currentRenderPassId]);\n this._subMeshToDepthWrapper.mm.delete(params.subMesh); // trigger a depth effect recreation\n });\n }\n /**\n * Gets the effect to use to generate the depth map\n * @param subMesh subMesh to get the effect for\n * @param shadowGenerator shadow generator to get the effect for\n * @param passIdForDrawWrapper Id of the pass for which the effect from the draw wrapper must be retrieved from\n * @returns the effect to use to generate the depth map for the subMesh + shadow generator specified\n */\n getEffect(subMesh, shadowGenerator, passIdForDrawWrapper) {\n var _a;\n const entry = (_a = this._subMeshToDepthWrapper.mm.get(subMesh)) === null || _a === void 0 ? void 0 : _a.get(shadowGenerator);\n if (!entry) {\n return null;\n }\n let drawWrapper = entry.drawWrapper[passIdForDrawWrapper];\n if (!drawWrapper) {\n drawWrapper = entry.drawWrapper[passIdForDrawWrapper] = new DrawWrapper(this._scene.getEngine());\n drawWrapper.setEffect(entry.mainDrawWrapper.effect, entry.mainDrawWrapper.defines);\n }\n return drawWrapper;\n }\n /**\n * Specifies that the submesh is ready to be used for depth rendering\n * @param subMesh submesh to check\n * @param defines the list of defines to take into account when checking the effect\n * @param shadowGenerator combined with subMesh, it defines the effect to check\n * @param useInstances specifies that instances should be used\n * @param passIdForDrawWrapper Id of the pass for which the draw wrapper should be created\n * @returns a boolean indicating that the submesh is ready or not\n */\n isReadyForSubMesh(subMesh, defines, shadowGenerator, useInstances, passIdForDrawWrapper) {\n var _a, _b;\n if (this.standalone) {\n // will ensure the effect is (re)created for the base material\n if (!this._baseMaterial.isReadyForSubMesh(subMesh.getMesh(), subMesh, useInstances)) {\n return false;\n }\n }\n return (_b = (_a = this._makeEffect(subMesh, defines, shadowGenerator, passIdForDrawWrapper)) === null || _a === void 0 ? void 0 : _a.isReady()) !== null && _b !== void 0 ? _b : false;\n }\n /**\n * Disposes the resources\n */\n dispose() {\n this._baseMaterial.onEffectCreatedObservable.remove(this._onEffectCreatedObserver);\n this._onEffectCreatedObserver = null;\n const iterator = this._meshes.entries();\n for (let entry = iterator.next(); entry.done !== true; entry = iterator.next()) {\n const [mesh, observer] = entry.value;\n mesh.onDisposeObservable.remove(observer);\n }\n }\n _makeEffect(subMesh, defines, shadowGenerator, passIdForDrawWrapper) {\n var _a, _b, _c;\n const engine = this._scene.getEngine();\n const origEffectAndRenderPassId = this._subMeshToEffect.get(subMesh);\n if (!origEffectAndRenderPassId) {\n return null;\n }\n const [origEffect, origRenderPassId] = origEffectAndRenderPassId;\n let params = this._subMeshToDepthWrapper.get(subMesh, shadowGenerator);\n if (!params) {\n const mainDrawWrapper = new DrawWrapper(engine);\n mainDrawWrapper.defines = (_b = (_a = subMesh._getDrawWrapper(origRenderPassId)) === null || _a === void 0 ? void 0 : _a.defines) !== null && _b !== void 0 ? _b : null;\n params = {\n drawWrapper: [],\n mainDrawWrapper,\n depthDefines: \"\",\n token: RandomGUID(),\n };\n params.drawWrapper[passIdForDrawWrapper] = mainDrawWrapper;\n this._subMeshToDepthWrapper.set(subMesh, shadowGenerator, params);\n }\n const join = defines.join(\"\\n\");\n if (params.mainDrawWrapper.effect) {\n if (join === params.depthDefines) {\n // we already created the depth effect and it is still up to date for this submesh + shadow generator\n return params.mainDrawWrapper.effect;\n }\n }\n params.depthDefines = join;\n const uniforms = origEffect.getUniformNames().slice();\n // the depth effect is either out of date or has not been created yet\n let vertexCode = origEffect.vertexSourceCodeBeforeMigration, fragmentCode = origEffect.fragmentSourceCodeBeforeMigration;\n if (!this.doNotInjectCode) {\n // vertex code\n const vertexNormalBiasCode = this._options && this._options.remappedVariables\n ? `#include(${this._options.remappedVariables.join(\",\")})`\n : Effect.IncludesShadersStore[\"shadowMapVertexNormalBias\"], vertexMetricCode = this._options && this._options.remappedVariables\n ? `#include(${this._options.remappedVariables.join(\",\")})`\n : Effect.IncludesShadersStore[\"shadowMapVertexMetric\"], fragmentSoftTransparentShadow = this._options && this._options.remappedVariables\n ? `#include(${this._options.remappedVariables.join(\",\")})`\n : Effect.IncludesShadersStore[\"shadowMapFragmentSoftTransparentShadow\"], fragmentBlockCode = Effect.IncludesShadersStore[\"shadowMapFragment\"];\n vertexCode = vertexCode.replace(/void\\s+?main/g, Effect.IncludesShadersStore[\"shadowMapVertexExtraDeclaration\"] + \"\\r\\nvoid main\");\n vertexCode = vertexCode.replace(/#define SHADOWDEPTH_NORMALBIAS|#define CUSTOM_VERTEX_UPDATE_WORLDPOS/g, vertexNormalBiasCode);\n if (vertexCode.indexOf(\"#define SHADOWDEPTH_METRIC\") !== -1) {\n vertexCode = vertexCode.replace(/#define SHADOWDEPTH_METRIC/g, vertexMetricCode);\n }\n else {\n vertexCode = vertexCode.replace(/}\\s*$/g, vertexMetricCode + \"\\r\\n}\");\n }\n vertexCode = vertexCode.replace(/#define SHADER_NAME.*?\\n|out vec4 glFragColor;\\n/g, \"\");\n // fragment code\n const hasLocationForSoftTransparentShadow = fragmentCode.indexOf(\"#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW\") >= 0 || fragmentCode.indexOf(\"#define CUSTOM_FRAGMENT_BEFORE_FOG\") >= 0;\n const hasLocationForFragment = fragmentCode.indexOf(\"#define SHADOWDEPTH_FRAGMENT\") !== -1;\n let fragmentCodeToInjectAtEnd = \"\";\n if (!hasLocationForSoftTransparentShadow) {\n fragmentCodeToInjectAtEnd = fragmentSoftTransparentShadow + \"\\r\\n\";\n }\n else {\n fragmentCode = fragmentCode.replace(/#define SHADOWDEPTH_SOFTTRANSPARENTSHADOW|#define CUSTOM_FRAGMENT_BEFORE_FOG/g, fragmentSoftTransparentShadow);\n }\n fragmentCode = fragmentCode.replace(/void\\s+?main/g, Effect.IncludesShadersStore[\"shadowMapFragmentExtraDeclaration\"] + \"\\r\\nvoid main\");\n if (hasLocationForFragment) {\n fragmentCode = fragmentCode.replace(/#define SHADOWDEPTH_FRAGMENT/g, fragmentBlockCode);\n }\n else {\n fragmentCodeToInjectAtEnd += fragmentBlockCode + \"\\r\\n\";\n }\n if (fragmentCodeToInjectAtEnd) {\n fragmentCode = fragmentCode.replace(/}\\s*$/g, fragmentCodeToInjectAtEnd + \"}\");\n }\n uniforms.push(\"biasAndScaleSM\", \"depthValuesSM\", \"lightDataSM\", \"softTransparentShadowSM\");\n }\n params.mainDrawWrapper.effect = engine.createEffect({\n vertexSource: vertexCode,\n fragmentSource: fragmentCode,\n vertexToken: params.token,\n fragmentToken: params.token,\n }, {\n attributes: origEffect.getAttributesNames(),\n uniformsNames: uniforms,\n uniformBuffersNames: origEffect.getUniformBuffersNames(),\n samplers: origEffect.getSamplers(),\n defines: join + \"\\n\" + origEffect.defines.replace(\"#define SHADOWS\", \"\").replace(/#define SHADOW\\d/g, \"\"),\n indexParameters: origEffect.getIndexParameters(),\n }, engine);\n for (let id = 0; id < params.drawWrapper.length; ++id) {\n if (id !== passIdForDrawWrapper) {\n (_c = params.drawWrapper[id]) === null || _c === void 0 ? void 0 : _c.setEffect(params.mainDrawWrapper.effect, params.mainDrawWrapper.defines);\n }\n }\n return params.mainDrawWrapper.effect;\n }\n}\n//# sourceMappingURL=shadowDepthWrapper.js.map","/**\n * Root class for all node material optimizers\n */\nexport class NodeMaterialOptimizer {\n /**\n * Function used to optimize a NodeMaterial graph\n * @param _vertexOutputNodes defines the list of output nodes for the vertex shader\n * @param _fragmentOutputNodes defines the list of output nodes for the fragment shader\n */\n optimize(_vertexOutputNodes, _fragmentOutputNodes) {\n // Do nothing by default\n }\n}\n//# sourceMappingURL=nodeMaterialOptimizer.js.map","export * from \"./nodeMaterialOptimizer.js\";\n//# sourceMappingURL=index.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./Enums/index.js\";\nexport * from \"./nodeMaterialConnectionPointCustomObject.js\";\nexport * from \"./nodeMaterialBlockConnectionPoint.js\";\nexport * from \"./nodeMaterialBlock.js\";\nexport * from \"./nodeMaterial.js\";\nexport * from \"./Blocks/index.js\";\nexport * from \"./Optimizers/index.js\";\nexport * from \"./nodeMaterialDecorator.js\";\n//# sourceMappingURL=index.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize, expandToProperty } from \"../Misc/decorators.js\";\nimport { MaterialDefines } from \"./materialDefines.js\";\nimport { MaterialPluginBase } from \"./materialPluginBase.js\";\n\nimport { MaterialFlags } from \"./materialFlags.js\";\nimport { MaterialHelper } from \"./materialHelper.js\";\n/**\n * @internal\n */\nexport class DecalMapDefines extends MaterialDefines {\n constructor() {\n super(...arguments);\n this.DECAL = false;\n this.DECALDIRECTUV = 0;\n this.DECAL_SMOOTHALPHA = false;\n this.GAMMADECAL = false;\n }\n}\n/**\n * Plugin that implements the decal map component of a material\n * @since 5.49.1\n */\nexport class DecalMapConfiguration extends MaterialPluginBase {\n /** @internal */\n _markAllSubMeshesAsTexturesDirty() {\n this._enable(this._isEnabled);\n this._internalMarkAllSubMeshesAsTexturesDirty();\n }\n /**\n * Creates a new DecalMapConfiguration\n * @param material The material to attach the decal map plugin to\n * @param addToPluginList If the plugin should be added to the material plugin list\n */\n constructor(material, addToPluginList = true) {\n super(material, \"DecalMap\", 150, new DecalMapDefines(), addToPluginList);\n this._isEnabled = false;\n /**\n * Enables or disables the decal map on this material\n */\n this.isEnabled = false;\n this._smoothAlpha = false;\n /**\n * Enables or disables the smooth alpha mode on this material. Default: false.\n * When enabled, the alpha value used to blend the decal map will be the squared value and will produce a smoother result.\n */\n this.smoothAlpha = false;\n this.registerForExtraEvents = true; // because we override the hardBindForSubMesh method\n this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1];\n }\n isReadyForSubMesh(defines, scene, engine, subMesh) {\n const decalMap = subMesh.getMesh().decalMap;\n if (!this._isEnabled || !(decalMap === null || decalMap === void 0 ? void 0 : decalMap.texture) || !MaterialFlags.DecalMapEnabled || !scene.texturesEnabled) {\n return true;\n }\n return decalMap.isReady();\n }\n prepareDefines(defines, scene, mesh) {\n const decalMap = mesh.decalMap;\n if (!this._isEnabled || !(decalMap === null || decalMap === void 0 ? void 0 : decalMap.texture) || !MaterialFlags.DecalMapEnabled || !scene.texturesEnabled) {\n const isDirty = defines.DECAL;\n if (isDirty) {\n defines.markAsTexturesDirty();\n }\n defines.DECAL = false;\n }\n else {\n const isDirty = !defines.DECAL || defines.GAMMADECAL !== decalMap.texture.gammaSpace;\n if (isDirty) {\n defines.markAsTexturesDirty();\n }\n defines.DECAL = true;\n defines.GAMMADECAL = decalMap.texture.gammaSpace;\n defines.DECAL_SMOOTHALPHA = this._smoothAlpha;\n MaterialHelper.PrepareDefinesForMergedUV(decalMap.texture, defines, \"DECAL\");\n }\n }\n /**\n * Note that we override hardBindForSubMesh and not bindForSubMesh because the material can be shared by multiple meshes,\n * in which case mustRebind could return false even though the decal map is different for each mesh: that's because the decal map\n * is not part of the material but hosted by the decalMap of the mesh instead.\n */\n hardBindForSubMesh(uniformBuffer, scene, _engine, subMesh) {\n const decalMap = subMesh.getMesh().decalMap;\n if (!this._isEnabled || !(decalMap === null || decalMap === void 0 ? void 0 : decalMap.texture) || !MaterialFlags.DecalMapEnabled || !scene.texturesEnabled) {\n return;\n }\n const isFrozen = this._material.isFrozen;\n const texture = decalMap.texture;\n if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {\n uniformBuffer.updateFloat4(\"vDecalInfos\", texture.coordinatesIndex, 0, 0, 0);\n MaterialHelper.BindTextureMatrix(texture, uniformBuffer, \"decal\");\n }\n uniformBuffer.setTexture(\"decalSampler\", texture);\n }\n getClassName() {\n return \"DecalMapConfiguration\";\n }\n getSamplers(samplers) {\n samplers.push(\"decalSampler\");\n }\n getUniforms() {\n return {\n ubo: [\n { name: \"vDecalInfos\", size: 4, type: \"vec4\" },\n { name: \"decalMatrix\", size: 16, type: \"mat4\" },\n ],\n };\n }\n}\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], DecalMapConfiguration.prototype, \"isEnabled\", void 0);\n__decorate([\n serialize(),\n expandToProperty(\"_markAllSubMeshesAsTexturesDirty\")\n], DecalMapConfiguration.prototype, \"smoothAlpha\", void 0);\n//# sourceMappingURL=material.decalMapConfiguration.js.map","import { DetailMapConfiguration } from \"./material.detailMapConfiguration.js\";\nimport { PBRAnisotropicConfiguration } from \"./PBR/pbrAnisotropicConfiguration.js\";\nimport { PBRBaseMaterial } from \"./PBR/pbrBaseMaterial.js\";\nimport { PBRBRDFConfiguration } from \"./PBR/pbrBRDFConfiguration.js\";\nimport { PBRClearCoatConfiguration } from \"./PBR/pbrClearCoatConfiguration.js\";\nimport { PBRIridescenceConfiguration } from \"./PBR/pbrIridescenceConfiguration.js\";\nimport { PBRSheenConfiguration } from \"./PBR/pbrSheenConfiguration.js\";\nimport { PBRSubSurfaceConfiguration } from \"./PBR/pbrSubSurfaceConfiguration.js\";\nimport { StandardMaterial } from \"./standardMaterial.js\";\n/**\n * Creates an instance of the anisotropic plugin\n * @param material parent material the plugin will be created for\n * @returns the plugin instance or null if the plugin is incompatible with material\n */\nexport function createPBRAnisotropicPlugin(material) {\n if (material instanceof PBRBaseMaterial) {\n return new PBRAnisotropicConfiguration(material);\n }\n return null;\n}\n/**\n * Creates an instance of the brdf plugin\n * @param material parent material the plugin will be created for\n * @returns the plugin instance or null if the plugin is incompatible with material\n */\nexport function createPBRBRDFPlugin(material) {\n if (material instanceof PBRBaseMaterial) {\n return new PBRBRDFConfiguration(material);\n }\n return null;\n}\n/**\n * Creates an instance of the clear coat plugin\n * @param material parent material the plugin will be created for\n * @returns the plugin instance or null if the plugin is incompatible with material\n */\nexport function createPBRClearCoatPlugin(material) {\n if (material instanceof PBRBaseMaterial) {\n return new PBRClearCoatConfiguration(material);\n }\n return null;\n}\n/**\n * Creates an instance of the iridescence plugin\n * @param material parent material the plugin will be created for\n * @returns the plugin instance or null if the plugin is incompatible with material\n */\nexport function createPBRIridescencePlugin(material) {\n if (material instanceof PBRBaseMaterial) {\n return new PBRIridescenceConfiguration(material);\n }\n return null;\n}\n/**\n * Creates an instance of the sheen plugin\n * @param material parent material the plugin will be created for\n * @returns the plugin instance or null if the plugin is incompatible with material\n */\nexport function createPBRSheenPlugin(material) {\n if (material instanceof PBRBaseMaterial) {\n return new PBRSheenConfiguration(material);\n }\n return null;\n}\n/**\n * Creates an instance of the sub surface plugin\n * @param material parent material the plugin will be created for\n * @returns the plugin instance or null if the plugin is incompatible with material\n */\nexport function createPBRSubSurfacePlugin(material) {\n if (material instanceof PBRBaseMaterial) {\n return new PBRSubSurfaceConfiguration(material);\n }\n return null;\n}\n/**\n * Creates an instance of the detail map plugin\n * @param material parent material the plugin will be created for\n * @returns the plugin instance or null if the plugin is incompatible with material\n */\nexport function createDetailMapPlugin(material) {\n if (material instanceof PBRBaseMaterial || material instanceof StandardMaterial) {\n return new DetailMapConfiguration(material);\n }\n return null;\n}\n//# sourceMappingURL=materialPluginFactoryExport.js.map","import { Engine } from \"../Engines/engine.js\";\nimport { RawTexture } from \"./Textures/rawTexture.js\";\nimport { MaterialPluginBase } from \"./materialPluginBase.js\";\nimport { TmpVectors } from \"../Maths/math.vector.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { MaterialDefines } from \"./materialDefines.js\";\nimport { DeepCopier } from \"../Misc/deepCopier.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\nexport var GreasedLineMeshMaterialType;\n(function (GreasedLineMeshMaterialType) {\n GreasedLineMeshMaterialType[GreasedLineMeshMaterialType[\"MATERIAL_TYPE_STANDARD\"] = 0] = \"MATERIAL_TYPE_STANDARD\";\n GreasedLineMeshMaterialType[GreasedLineMeshMaterialType[\"MATERIAL_TYPE_PBR\"] = 1] = \"MATERIAL_TYPE_PBR\";\n})(GreasedLineMeshMaterialType || (GreasedLineMeshMaterialType = {}));\nexport var GreasedLineMeshColorMode;\n(function (GreasedLineMeshColorMode) {\n GreasedLineMeshColorMode[GreasedLineMeshColorMode[\"COLOR_MODE_SET\"] = 0] = \"COLOR_MODE_SET\";\n GreasedLineMeshColorMode[GreasedLineMeshColorMode[\"COLOR_MODE_ADD\"] = 1] = \"COLOR_MODE_ADD\";\n GreasedLineMeshColorMode[GreasedLineMeshColorMode[\"COLOR_MODE_MULTIPLY\"] = 2] = \"COLOR_MODE_MULTIPLY\";\n})(GreasedLineMeshColorMode || (GreasedLineMeshColorMode = {}));\nexport var GreasedLineMeshColorDistributionType;\n(function (GreasedLineMeshColorDistributionType) {\n GreasedLineMeshColorDistributionType[GreasedLineMeshColorDistributionType[\"COLOR_DISTRIBUTION_TYPE_SEGMENT\"] = 0] = \"COLOR_DISTRIBUTION_TYPE_SEGMENT\";\n GreasedLineMeshColorDistributionType[GreasedLineMeshColorDistributionType[\"COLOR_DISTRIBUTION_TYPE_LINE\"] = 1] = \"COLOR_DISTRIBUTION_TYPE_LINE\";\n})(GreasedLineMeshColorDistributionType || (GreasedLineMeshColorDistributionType = {}));\n/**\n * @internal\n */\nexport class MaterialGreasedLineDefines extends MaterialDefines {\n constructor() {\n super(...arguments);\n /**\n * The material has a color option specified\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n this.GREASED_LINE_HAS_COLOR = false;\n /**\n * The material's size attenuation optiom\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n this.GREASED_LINE_SIZE_ATTENUATION = false;\n /**\n * The type of color distribution is set to line this value equals to true.\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n this.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE = false;\n }\n}\n/**\n * GreasedLinePluginMaterial for GreasedLineMesh\n */\nexport class GreasedLinePluginMaterial extends MaterialPluginBase {\n constructor(material, _scene, options) {\n var _a, _b, _c;\n options = options !== null && options !== void 0 ? options : {};\n const defines = new MaterialGreasedLineDefines();\n defines.GREASED_LINE_HAS_COLOR = !!options.color;\n defines.GREASED_LINE_SIZE_ATTENUATION = (_a = options.sizeAttenuation) !== null && _a !== void 0 ? _a : false;\n defines.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE = options.colorDistributionType === GreasedLineMeshColorDistributionType.COLOR_DISTRIBUTION_TYPE_LINE;\n super(material, GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME, 200, defines);\n this._scene = _scene;\n this._dashArray = 0;\n this._options = options;\n this._scene = (_b = this._scene) !== null && _b !== void 0 ? _b : material.getScene();\n this._engine = this._scene.getEngine();\n if (options.colors) {\n this._createColorsTexture(`${material.name}-colors-texture`, options.colors);\n }\n else {\n GreasedLinePluginMaterial._PrepareEmptyColorsTexture(_scene);\n }\n this.setDashCount((_c = options.dashCount) !== null && _c !== void 0 ? _c : 1); // calculate the _dashArray value\n this._enable(true); // always enabled\n }\n /**\n * Get the shader attributes\n * @param attributes array which will be filled with the attributes\n */\n getAttributes(attributes) {\n attributes.push(\"grl_offsets\");\n attributes.push(\"grl_previousAndSide\");\n attributes.push(\"grl_nextAndCounters\");\n attributes.push(\"grl_widths\");\n attributes.push(\"grl_colorPointers\");\n }\n /**\n * Get the shader samplers\n * @param samplers\n */\n getSamplers(samplers) {\n samplers.push(\"grl_colors\");\n }\n /**\n * Get the shader textures\n * @param activeTextures\n */\n getActiveTextures(activeTextures) {\n if (this._colorsTexture) {\n activeTextures.push(this._colorsTexture);\n }\n }\n /**\n * Get the shader uniforms\n * @returns uniforms\n */\n getUniforms() {\n const ubo = [\n { name: \"grl_projection\", size: 16, type: \"mat4\" },\n { name: \"grl_singleColor\", size: 3, type: \"vec3\" },\n { name: \"grl_resolution_lineWidth\", size: 3, type: \"vec3\" },\n { name: \"grl_dashOptions\", size: 4, type: \"vec4\" },\n { name: \"grl_colorMode_visibility_colorsWidth_useColors\", size: 4, type: \"vec4\" },\n ];\n return {\n ubo,\n vertex: `\r\n uniform vec3 grl_resolution_lineWidth;\r\n uniform mat4 grl_projection;\r\n `,\n fragment: `\r\n uniform vec4 grl_dashOptions;\r\n uniform vec4 grl_colorMode_visibility_colorsWidth_useColors;\r\n uniform vec3 grl_singleColor;\r\n `,\n };\n }\n // only getter, it doesn't make sense to use this plugin on a mesh other than GreasedLineMesh\n // and it doesn't make sense to disable it on the mesh\n get isEnabled() {\n return true;\n }\n /**\n * Bind the uniform buffer\n * @param uniformBuffer\n */\n bindForSubMesh(uniformBuffer) {\n var _a, _b, _c, _d, _e, _f, _g;\n const activeCamera = this._scene.activeCamera;\n if (activeCamera) {\n const projection = activeCamera.getProjectionMatrix();\n uniformBuffer.updateMatrix(\"grl_projection\", projection);\n }\n else {\n throw Error(\"GreasedLinePluginMaterial requires an active camera.\");\n }\n const resolutionLineWidth = TmpVectors.Vector3[0];\n if (this._options.resolution) {\n resolutionLineWidth.x = this._options.resolution.x;\n resolutionLineWidth.y = this._options.resolution.y;\n }\n else {\n resolutionLineWidth.x = this._engine.getRenderWidth();\n resolutionLineWidth.y = this._engine.getRenderHeight();\n }\n resolutionLineWidth.z = this._options.width ? this._options.width : this._options.sizeAttenuation ? 1 : 0.1;\n uniformBuffer.updateVector3(\"grl_resolution_lineWidth\", resolutionLineWidth);\n const dashOptions = TmpVectors.Vector4[0];\n dashOptions.x = GreasedLinePluginMaterial._BooleanToNumber(this._options.useDash);\n dashOptions.y = (_a = this._dashArray) !== null && _a !== void 0 ? _a : 0;\n dashOptions.z = (_b = this._options.dashOffset) !== null && _b !== void 0 ? _b : 0;\n dashOptions.w = (_c = this._options.dashRatio) !== null && _c !== void 0 ? _c : 0.5;\n uniformBuffer.updateVector4(\"grl_dashOptions\", dashOptions);\n const colorModeVisibilityColorsWidthUseColors = TmpVectors.Vector4[1];\n colorModeVisibilityColorsWidthUseColors.x = (_d = this._options.colorMode) !== null && _d !== void 0 ? _d : GreasedLineMeshColorMode.COLOR_MODE_SET;\n colorModeVisibilityColorsWidthUseColors.y = (_e = this._options.visibility) !== null && _e !== void 0 ? _e : 1;\n colorModeVisibilityColorsWidthUseColors.z = this._colorsTexture ? this._colorsTexture.getSize().width : 0;\n colorModeVisibilityColorsWidthUseColors.w = GreasedLinePluginMaterial._BooleanToNumber(this._options.useColors);\n uniformBuffer.updateVector4(\"grl_colorMode_visibility_colorsWidth_useColors\", colorModeVisibilityColorsWidthUseColors);\n if (this._options.color) {\n uniformBuffer.updateColor3(\"grl_singleColor\", (_f = this._options.color) !== null && _f !== void 0 ? _f : Color3.White());\n }\n uniformBuffer.setTexture(\"grl_colors\", (_g = this._colorsTexture) !== null && _g !== void 0 ? _g : GreasedLinePluginMaterial._EmptyColorsTexture);\n }\n /**\n * Prepare the defines\n * @param defines\n * @param _scene\n * @param _mesh\n */\n prepareDefines(defines, _scene, _mesh) {\n var _a;\n const options = this._options;\n defines.GREASED_LINE_HAS_COLOR = !!options.color;\n defines.GREASED_LINE_SIZE_ATTENUATION = (_a = options.sizeAttenuation) !== null && _a !== void 0 ? _a : false;\n defines.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE = options.colorDistributionType === GreasedLineMeshColorDistributionType.COLOR_DISTRIBUTION_TYPE_LINE;\n }\n /**\n * Get the class name\n * @returns class name\n */\n getClassName() {\n return GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME;\n }\n /**\n * Get shader code\n * @param shaderType vertex/fragment\n * @returns shader code\n */\n getCustomCode(shaderType) {\n if (shaderType === \"vertex\") {\n return {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CUSTOM_VERTEX_DEFINITIONS: `\r\n attribute vec4 grl_previousAndSide;\r\n attribute vec4 grl_nextAndCounters;\r\n attribute float grl_widths;\r\n attribute vec3 grl_offsets;\r\n attribute float grl_colorPointers;\r\n\r\n varying float grlCounters;\r\n varying float grlColorPointer;\r\n\r\n vec2 grlFix( vec4 i, float aspect ) {\r\n vec2 res = i.xy / i.w;\r\n res.x *= aspect;\r\n return res;\r\n }\r\n `,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CUSTOM_VERTEX_UPDATE_POSITION: `\r\n vec3 grlPositionOffset = grl_offsets;\r\n positionUpdated += grlPositionOffset;\r\n `,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CUSTOM_VERTEX_MAIN_END: `\r\n vec2 grlResolution = grl_resolution_lineWidth.xy;\r\n float grlBaseWidth = grl_resolution_lineWidth.z;\r\n\r\n grlColorPointer = grl_colorPointers;\r\n\r\n vec3 grlPrevious = grl_previousAndSide.xyz;\r\n float grlSide = grl_previousAndSide.w;\r\n\r\n vec3 grlNext = grl_nextAndCounters.xyz;\r\n grlCounters = grl_nextAndCounters.w;\r\n\r\n float grlAspect = grlResolution.x / grlResolution.y;\r\n\r\n mat4 grlMatrix = viewProjection * world;\r\n vec4 grlFinalPosition = grlMatrix * vec4( positionUpdated , 1.0 );\r\n vec4 grlPrevPos = grlMatrix * vec4( grlPrevious + grlPositionOffset, 1.0 );\r\n vec4 grlNextPos = grlMatrix * vec4( grlNext + grlPositionOffset, 1.0 );\r\n\r\n vec2 grlCurrentP = grlFix( grlFinalPosition, grlAspect );\r\n vec2 grlPrevP = grlFix( grlPrevPos, grlAspect );\r\n vec2 grlNextP = grlFix( grlNextPos, grlAspect );\r\n\r\n float grlWidth = grlBaseWidth * grl_widths;\r\n\r\n vec2 grlDir;\r\n if( grlNextP == grlCurrentP ) grlDir = normalize( grlCurrentP - grlPrevP );\r\n else if( grlPrevP == grlCurrentP ) grlDir = normalize( grlNextP - grlCurrentP );\r\n else {\r\n vec2 grlDir1 = normalize( grlCurrentP - grlPrevP );\r\n vec2 grlDir2 = normalize( grlNextP - grlCurrentP );\r\n grlDir = normalize( grlDir1 + grlDir2 );\r\n }\r\n vec4 grlNormal = vec4( -grlDir.y, grlDir.x, 0., 1. );\r\n grlNormal.xy *= .5 * grlWidth;\r\n grlNormal *= grl_projection;\r\n #ifdef GREASED_LINE_SIZE_ATTENUATION\r\n grlNormal.xy *= grlFinalPosition.w;\r\n grlNormal.xy /= ( vec4( grlResolution, 0., 1. ) * grl_projection ).xy;\r\n #endif\r\n grlFinalPosition.xy += grlNormal.xy * grlSide;\r\n gl_Position = grlFinalPosition;\r\n\r\n vPositionW = vec3(grlFinalPosition);\r\n\r\n `,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n \"!gl_Position\\\\=viewProjection\\\\*worldPos;\": \"//\", // remove\n };\n }\n if (shaderType === \"fragment\") {\n return {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CUSTOM_FRAGMENT_DEFINITIONS: `\r\n varying float grlCounters;\r\n varying float grlColorPointer;\r\n uniform sampler2D grl_colors;\r\n `,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n CUSTOM_FRAGMENT_MAIN_END: `\r\n float grlColorMode = grl_colorMode_visibility_colorsWidth_useColors.x;\r\n float grlVisibility = grl_colorMode_visibility_colorsWidth_useColors.y;\r\n float grlColorsWidth = grl_colorMode_visibility_colorsWidth_useColors.z;\r\n float grlUseColors = grl_colorMode_visibility_colorsWidth_useColors.w;\r\n\r\n float grlUseDash = grl_dashOptions.x;\r\n float grlDashArray = grl_dashOptions.y;\r\n float grlDashOffset = grl_dashOptions.z;\r\n float grlDashRatio = grl_dashOptions.w;\r\n\r\n gl_FragColor.a *= step(grlCounters, grlVisibility);\r\n if( gl_FragColor.a == 0. ) discard;\r\n\r\n if(grlUseDash == 1.){\r\n gl_FragColor.a *= ceil(mod(grlCounters + grlDashOffset, grlDashArray) - (grlDashArray * grlDashRatio));\r\n if (gl_FragColor.a == 0.) discard;\r\n }\r\n\r\n #ifdef GREASED_LINE_HAS_COLOR\r\n if (grlColorMode == ${GreasedLineMeshColorMode.COLOR_MODE_SET}.) {\r\n gl_FragColor.rgb = grl_singleColor;\r\n } else if (grlColorMode == ${GreasedLineMeshColorMode.COLOR_MODE_ADD}.) {\r\n gl_FragColor.rgb += grl_singleColor;\r\n } else if (grlColorMode == ${GreasedLineMeshColorMode.COLOR_MODE_MULTIPLY}.) {\r\n gl_FragColor.rgb *= grl_singleColor;\r\n }\r\n #else\r\n if (grlUseColors == 1.) {\r\n #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE\r\n vec4 grlColor = texture2D(grl_colors, vec2(grlCounters, 0.), 0.);\r\n #else\r\n vec4 grlColor = texture2D(grl_colors, vec2(grlColorPointer/grlColorsWidth, 0.), 0.);\r\n #endif\r\n if (grlColorMode == ${GreasedLineMeshColorMode.COLOR_MODE_SET}.) {\r\n gl_FragColor = grlColor;\r\n } else if (grlColorMode == ${GreasedLineMeshColorMode.COLOR_MODE_ADD}.) {\r\n gl_FragColor += grlColor;\r\n } else if (grlColorMode == ${GreasedLineMeshColorMode.COLOR_MODE_MULTIPLY}.) {\r\n gl_FragColor *= grlColor;\r\n }\r\n }\r\n #endif\r\n `,\n };\n }\n return null;\n }\n /**\n * Converts boolean to number.\n * @param bool\n * @returns 1 if true, 0 if false.\n */\n static _BooleanToNumber(bool) {\n return bool ? 1 : 0;\n }\n /**\n * Converts an array of Color3 to Uint8Array\n * @param colors Arrray of Color3\n * @returns Uin8Array of colors [r, g, b, a, r, g, b, a, ...]\n */\n static _Color3toRGBAUint8(colors) {\n const colorTable = new Uint8Array(colors.length * 4);\n for (let i = 0, j = 0; i < colors.length; i++) {\n colorTable[j++] = colors[i].r * 255;\n colorTable[j++] = colors[i].g * 255;\n colorTable[j++] = colors[i].b * 255;\n colorTable[j++] = 255;\n }\n return colorTable;\n }\n /**\n * Creates a RawTexture from an RGBA color array and sets it on the plugin material instance.\n * @param name name of the texture\n * @param colors Uint8Array of colors\n */\n _createColorsTexture(name, colors) {\n var _a;\n const colorsArray = GreasedLinePluginMaterial._Color3toRGBAUint8(colors);\n this._colorsTexture = new RawTexture(colorsArray, colors.length, 1, Engine.TEXTUREFORMAT_RGBA, this._scene, false, true, (_a = this._options.colorsSampling) !== null && _a !== void 0 ? _a : RawTexture.NEAREST_NEAREST);\n this._colorsTexture.name = name;\n }\n /**\n * Disposes the plugin material.\n */\n dispose() {\n var _a;\n (_a = this._colorsTexture) === null || _a === void 0 ? void 0 : _a.dispose();\n super.dispose();\n }\n /**\n * Sets whether to use the colors option to colorize the line.\n * @param value true if use the colors, otherwise false\n */\n setUseColors(value) {\n this._options.useColors = value;\n }\n /**\n * Creates or updates the colors texture\n * @param colors color table RGBA\n * @param lazy if lazy, the colors are not updated\n * @param forceUpdate force creation of a new texture\n * @returns\n */\n setColors(colors, lazy = false, forceUpdate = false) {\n var _a, _b, _c, _d;\n if (colors === null || colors.length === 0) {\n (_a = this._colorsTexture) === null || _a === void 0 ? void 0 : _a.dispose();\n return;\n }\n const origColorsCount = (_c = (_b = this._options.colors) === null || _b === void 0 ? void 0 : _b.length) !== null && _c !== void 0 ? _c : 0;\n this._options.colors = colors;\n if (lazy && !forceUpdate) {\n return;\n }\n if (this._colorsTexture && origColorsCount === colors.length && !forceUpdate) {\n const colorArray = GreasedLinePluginMaterial._Color3toRGBAUint8(colors);\n this._colorsTexture.update(colorArray);\n }\n else {\n (_d = this._colorsTexture) === null || _d === void 0 ? void 0 : _d.dispose();\n this._createColorsTexture(`${this._material.name}-colors-texture`, colors);\n }\n }\n /**\n * Updates the material. Use when material created in lazy mode.\n */\n updateLazy() {\n if (this._options.colors) {\n this.setColors(this._options.colors, false, true);\n }\n }\n /**\n * Gets the plugin material options\n * @returns the plugin material options @see GreasedLineMaterialOptions\n */\n getOptions() {\n return this._options;\n }\n /**\n * Sets the line length visibility.\n * 0 - 0% of the line will be visible\n * 1 - 100% of the line will be visible\n * @param value\n */\n setVisibility(value) {\n this._options.visibility = value;\n }\n /**\n * Turns on/off dashmode\n * @param value\n */\n setUseDash(value) {\n this._options.useDash = value;\n }\n /**\n * Sets the dash array.\n * @param value dash array\n */\n setDashCount(value) {\n this._options.dashCount = value;\n this._dashArray = 1 / value;\n }\n /**\n * Sets the dash ratio\n * @param value dash length ratio 0..1 (0.5 = half empty, half drawn)\n */\n setDashRatio(value) {\n this._options.dashRatio = value;\n }\n /**\n * Sets the dash offset\n * @param value the dashes will be offset by this value\n */\n setDashOffset(value) {\n this._options.dashOffset = value;\n }\n /**\n * Sets line base width. At each point the line width is calculated by widths[pointIndex] * width\n * @param value base width\n */\n setWidth(value) {\n this._options.width = value;\n }\n /**\n * Turn on/off attenuation of the width option and widths array.\n * @param value false means 1 unit in width = 1 unit on scene, true means 1 unit in width is reduced on the screen to make better looking lines\n */\n setSizeAttenuation(value) {\n this._options.sizeAttenuation = value;\n this.markAllDefinesAsDirty();\n }\n /**\n * Sets the color of the line. If set the whole line will be mixed with this color according to the colorMode option.\n * @param value color\n */\n setColor(value, doNotMarkDirty = false) {\n if ((this._options.color === undefined && value !== undefined) || (this._options.color !== undefined && value === undefined)) {\n this._options.color = value;\n !doNotMarkDirty && this.markAllDefinesAsDirty();\n }\n else {\n this._options.color = value;\n }\n }\n /**\n * Sets the mixing mode of the color paramater. Default value is GreasedLineMeshColorMode.SET\n * @see GreasedLineMeshColorMode\n * @param value color mode\n */\n setColorMode(value) {\n this._options.colorMode = value;\n }\n /**\n * Serializes this plugin material\n * @returns serializationObjec\n */\n serialize() {\n const serializationObject = super.serialize();\n serializationObject.materialOptions = {};\n DeepCopier.DeepCopy(this._options, serializationObject.materialOptions);\n return serializationObject;\n }\n /**\n * Parses a serialized objects\n * @param source serialized object\n * @param scene scene\n * @param rootUrl root url for textures\n */\n parse(source, scene, rootUrl) {\n var _a;\n super.parse(source, scene, rootUrl);\n this._options = source.materialOptions;\n (_a = this._colorsTexture) === null || _a === void 0 ? void 0 : _a.dispose();\n if (this._options.colors) {\n this._createColorsTexture(`${this._material.name}-colors-texture`, this._options.colors);\n }\n else {\n GreasedLinePluginMaterial._PrepareEmptyColorsTexture(scene);\n }\n this._options.color && this.setColor(this._options.color, true);\n this._options.colorMode && this.setColorMode(this._options.colorMode);\n this._options.useColors && this.setUseColors(this._options.useColors);\n this._options.visibility && this.setVisibility(this._options.visibility);\n this._options.useDash && this.setUseDash(this._options.useDash);\n this._options.dashCount && this.setDashCount(this._options.dashCount);\n this._options.dashRatio && this.setDashRatio(this._options.dashRatio);\n this._options.dashOffset && this.setDashOffset(this._options.dashOffset);\n this._options.width && this.setWidth(this._options.width);\n this._options.sizeAttenuation && this.setSizeAttenuation(this._options.sizeAttenuation);\n this.markAllDefinesAsDirty();\n }\n /**\n * A minimum size texture for the colors sampler2D when there is no colors texture defined yet.\n * For fast switching using the useColors property without the need to use defines.\n * @param scene Scene\n */\n static _PrepareEmptyColorsTexture(scene) {\n if (!this._EmptyColorsTexture) {\n const colorsArray = new Uint8Array(4);\n this._EmptyColorsTexture = new RawTexture(colorsArray, 1, 1, Engine.TEXTUREFORMAT_RGBA, scene, false, false, RawTexture.NEAREST_NEAREST);\n this._EmptyColorsTexture.name = \"grlEmptyColorsTexture\";\n }\n }\n}\n/**\n * Plugin name\n */\nGreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME = \"GreasedLinePluginMaterial\";\nRegisterClass(`BABYLON.${GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME}`, GreasedLinePluginMaterial);\n//# sourceMappingURL=greasedLinePluginMaterial.js.map","import { DecalMapConfiguration } from \"./material.decalMapConfiguration.js\";\nimport { StandardMaterial } from \"./standardMaterial.js\";\nObject.defineProperty(StandardMaterial.prototype, \"decalMap\", {\n get: function () {\n if (!this._decalMap) {\n if (this._uniformBufferLayoutBuilt) {\n // Material already used to display a mesh, so it's invalid to add the decal map plugin at that point\n // Returns null instead of having new DecalMapConfiguration throws an exception\n return null;\n }\n this._decalMap = new DecalMapConfiguration(this);\n }\n return this._decalMap;\n },\n enumerable: true,\n configurable: true,\n});\n//# sourceMappingURL=standardMaterial.decalMap.js.map","import { DecalMapConfiguration } from \"../material.decalMapConfiguration.js\";\nimport { PBRBaseMaterial } from \"./pbrBaseMaterial.js\";\nObject.defineProperty(PBRBaseMaterial.prototype, \"decalMap\", {\n get: function () {\n if (!this._decalMap) {\n if (this._uniformBufferLayoutBuilt) {\n // Material already used to display a mesh, so it's invalid to add the decal map plugin at that point\n // Returns null instead of having new DecalMapConfiguration throws an exception\n return null;\n }\n this._decalMap = new DecalMapConfiguration(this);\n }\n return this._decalMap;\n },\n enumerable: true,\n configurable: true,\n});\n//# sourceMappingURL=pbrMaterial.decalMap.js.map","import { AbstractMesh } from \"../Meshes/abstractMesh.js\";\nObject.defineProperty(AbstractMesh.prototype, \"decalMap\", {\n get: function () {\n return this._decalMap;\n },\n set: function (decalMap) {\n this._decalMap = decalMap;\n },\n enumerable: true,\n configurable: true,\n});\n//# sourceMappingURL=abstractMesh.decalMap.js.map","import \"./standardMaterial.decalMap.js\";\nimport \"./PBR/pbrMaterial.decalMap.js\";\nimport \"../Meshes/abstractMesh.decalMap.js\";\n//# sourceMappingURL=material.decalMap.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./Background/index.js\";\nexport * from \"./colorCurves.js\";\nexport * from \"./iEffectFallbacks.js\";\nexport * from \"./effectFallbacks.js\";\nexport * from \"./effect.js\";\nexport * from \"./fresnelParameters.js\";\nexport * from \"./imageProcessingConfiguration.js\";\nexport * from \"./material.js\";\nexport * from \"./materialDefines.js\";\nexport * from \"./clipPlaneMaterialHelper.js\";\nexport * from \"./materialHelper.js\";\nexport * from \"./multiMaterial.js\";\nexport * from \"./Occlusion/index.js\";\nexport * from \"./PBR/index.js\";\nexport * from \"./pushMaterial.js\";\nexport * from \"./shaderLanguage.js\";\nexport * from \"./shaderMaterial.js\";\nexport * from \"./standardMaterial.js\";\nexport * from \"./Textures/index.js\";\nexport * from \"./uniformBuffer.js\";\nexport * from \"./materialFlags.js\";\nexport * from \"./Node/index.js\";\nexport * from \"./effectRenderer.js\";\nexport * from \"./shadowDepthWrapper.js\";\nexport * from \"./drawWrapper.js\";\nexport * from \"./materialPluginBase.js\";\nexport * from \"./materialPluginManager.js\";\nexport * from \"./materialPluginEvent.js\";\nexport * from \"./material.detailMapConfiguration.js\";\nexport * from \"./material.decalMapConfiguration.js\";\nexport * from \"./materialPluginFactoryExport.js\";\nexport * from \"./greasedLinePluginMaterial.js\";\nimport \"./material.decalMap.js\";\n//# sourceMappingURL=index.js.map","import { Vector2, Vector3 } from \"./math.vector.js\";\n/**\n * Class used to store (r, theta) vector representation\n */\nexport class Polar {\n /**\n * Creates a new Polar object\n * @param radius the radius of the vector\n * @param theta the angle of the vector\n */\n constructor(radius, theta) {\n this.radius = radius;\n this.theta = theta;\n }\n /**\n * Gets the class name\n * @returns the string \"Polar\"\n */\n getClassName() {\n return \"Polar\";\n }\n /**\n * Converts the current polar to a string\n * @returns the current polar as a string\n */\n toString() {\n return JSON.stringify(this);\n }\n /**\n * Converts the current polar to an array\n * @reutrns the current polar as an array\n */\n asArray() {\n return [this.radius, this.theta];\n }\n /**\n * Adds the current Polar and the given Polar and stores the result\n * @param polar the polar to add\n * @param ref the polar to store the result in\n * @returns the updated ref\n */\n addToRef(polar, ref) {\n ref.radius = this.radius + polar.radius;\n ref.theta = this.theta + polar.theta;\n return ref;\n }\n /**\n * Adds the current Polar and the given Polar\n * @param polar the polar to add\n * @returns the sum polar\n */\n add(polar) {\n const ref = new Polar(0, 0);\n this.addToRef(polar, ref);\n return ref;\n }\n /**\n * Adds the given polar to the current polar\n * @param polar the polar to add\n * @returns the current polar\n */\n addInPlace(polar) {\n this.addToRef(polar, this);\n return this;\n }\n /**\n * Adds the provided values to the current polar\n * @param radius the amount to add to the radius\n * @param theta the amount to add to the theta\n * @returns the current polar\n */\n addInPlaceFromFloats(radius, theta) {\n this.radius += radius;\n this.theta += theta;\n return this;\n }\n /**\n * Subtracts the given Polar from the current Polar and stores the result\n * @param polar the polar to subtract\n * @param ref the polar to store the result in\n * @returns the updated ref\n */\n subtractToRef(polar, ref) {\n ref.radius = this.radius - polar.radius;\n ref.theta = this.theta - polar.theta;\n return ref;\n }\n /**\n * Subtracts the given Polar from the current Polar\n * @param polar the polar to subtract\n * @returns the difference polar\n */\n subtract(polar) {\n const ref = new Polar(0, 0);\n this.subtractToRef(polar, ref);\n return ref;\n }\n /**\n * Subtracts the given Polar from the current Polar\n * @param polar the polar to subtract\n * @returns the current polar\n */\n subtractInPlace(polar) {\n this.subtractToRef(polar, this);\n return this;\n }\n /**\n * Subtracts the given floats from the current polar\n * @param radius the amount to subtract from the radius\n * @param theta the amount to subtract from the theta\n * @param ref the polar to store the result in\n * @returns the updated ref\n */\n subtractFromFloatsToRef(radius, theta, ref) {\n ref.radius = this.radius - radius;\n ref.theta = this.theta - theta;\n return ref;\n }\n /**\n * Subtracts the given floats from the current polar\n * @param radius the amount to subtract from the radius\n * @param theta the amount to subtract from the theta\n * @returns the difference polar\n */\n subtractFromFloats(radius, theta) {\n const ref = new Polar(0, 0);\n this.subtractFromFloatsToRef(radius, theta, ref);\n return ref;\n }\n /**\n * Multiplies the given Polar with the current Polar and stores the result\n * @param polar the polar to multiply\n * @param ref the polar to store the result in\n * @returns the updated ref\n */\n multiplyToRef(polar, ref) {\n ref.radius = this.radius * polar.radius;\n ref.theta = this.theta * polar.theta;\n return ref;\n }\n /**\n * Multiplies the given Polar with the current Polar\n * @param polar the polar to multiply\n * @returns the product polar\n */\n multiply(polar) {\n const ref = new Polar(0, 0);\n this.multiplyToRef(polar, ref);\n return ref;\n }\n /**\n * Multiplies the given Polar with the current Polar\n * @param polar the polar to multiply\n * @returns the current polar\n */\n multiplyInPlace(polar) {\n this.multiplyToRef(polar, this);\n return this;\n }\n /**\n * Divides the current Polar by the given Polar and stores the result\n * @param polar the polar to divide\n * @param ref the polar to store the result in\n * @returns the updated ref\n */\n divideToRef(polar, ref) {\n ref.radius = this.radius / polar.radius;\n ref.theta = this.theta / polar.theta;\n return ref;\n }\n /**\n * Divides the current Polar by the given Polar\n * @param polar the polar to divide\n * @returns the quotient polar\n */\n divide(polar) {\n const ref = new Polar(0, 0);\n this.divideToRef(polar, ref);\n return ref;\n }\n /**\n * Divides the current Polar by the given Polar\n * @param polar the polar to divide\n * @returns the current polar\n */\n divideInPlace(polar) {\n this.divideToRef(polar, this);\n return this;\n }\n /**\n * Clones the current polar\n * @returns a clone of the current polar\n */\n clone() {\n return new Polar(this.radius, this.theta);\n }\n /**\n * Copies the source polar into the current polar\n * @param source the polar to copy from\n * @returns the current polar\n */\n copyFrom(source) {\n this.radius = source.radius;\n this.theta = source.theta;\n return this;\n }\n /**\n * Copies the given values into the current polar\n * @param radius the radius to use\n * @param theta the theta to use\n * @returns the current polar\n */\n copyFromFloats(radius, theta) {\n this.radius = radius;\n this.theta = theta;\n return this;\n }\n /**\n * Scales the current polar and stores the result\n * @param scale defines the multiplication factor\n * @param ref where to store the result\n * @returns the updated ref\n */\n scaleToRef(scale, ref) {\n ref.radius = this.radius * scale;\n ref.theta = this.theta * scale;\n return ref;\n }\n /**\n * Scales the current polar and returns a new polar with the scaled coordinates\n * @param scale defines the multiplication factor\n * @returns the scaled polar\n */\n scale(scale) {\n const ref = new Polar(0, 0);\n this.scaleToRef(scale, ref);\n return ref;\n }\n /**\n * Scales the current polar\n * @param scale defines the multiplication factor\n * @returns the current polar\n */\n scaleInPlace(scale) {\n this.scaleToRef(scale, this);\n return this;\n }\n /**\n * Sets the values of the current polar\n * @param radius the new radius\n * @param theta the new theta\n * @returns the current polar\n */\n set(radius, theta) {\n this.radius = radius;\n this.theta = theta;\n return this;\n }\n /**\n * Sets the values of the current polar\n * @param value the new values\n * @returns the current polar\n */\n setAll(value) {\n this.set(value, value);\n return this;\n }\n /**\n * Gets the rectangular coordinates of the current Polar\n * @param ref the reference to assign the result\n * @returns the updated reference\n */\n toVector2ToRef(ref) {\n const x = this.radius * Math.cos(this.theta);\n const y = this.radius * Math.sin(this.theta);\n ref.set(x, y);\n return ref;\n }\n /**\n * Gets the rectangular coordinates of the current Polar\n * @returns the rectangular coordinates\n */\n toVector2() {\n const ref = new Vector2(0, 0);\n return this.toVector2ToRef(ref);\n }\n /**\n * Converts a given Vector2 to its polar coordinates\n * @param v the Vector2 to convert\n * @param ref the reference to assign the result\n * @returns the updated reference\n */\n static FromVector2ToRef(v, ref) {\n const theta = Math.sign(v.y) * Math.acos(v.x / v.length());\n ref.radius = v.length();\n ref.theta = theta;\n return ref;\n }\n /**\n * Converts a given Vector2 to its polar coordinates\n * @param v the Vector2 to convert\n * @returns a Polar\n */\n static FromVector2(v) {\n const polar = new Polar(0, 0);\n Polar.FromVector2ToRef(v, polar);\n return polar;\n }\n /**\n * Converts an array of floats to a polar\n * @param array the array to convert\n * @returns the converted polar\n */\n static FromArray(array) {\n return new Polar(array[0], array[1]);\n }\n}\n/**\n * Class used for (radius, theta, phi) vector representation.\n */\nexport class Spherical {\n /**\n * @param radius spherical radius\n * @param theta angle from positive y axis to radial line from 0 to PI (vertical)\n * @param phi angle from positive x axis measured anticlockwise from -PI to PI (horizontal)\n */\n constructor(radius, theta, phi) {\n this.radius = radius;\n this.theta = theta;\n this.phi = phi;\n }\n /**\n * Gets the class name\n * @returns the string \"Spherical\"\n */\n getClassName() {\n return \"Spherical\";\n }\n /**\n * Converts the current spherical to a string\n * @returns the current spherical as a string\n */\n toString() {\n return JSON.stringify(this);\n }\n /**\n * Converts the current spherical to an array\n * @reutrns the current spherical as an array\n */\n asArray() {\n return [this.radius, this.theta, this.phi];\n }\n /**\n * Adds the current Spherical and the given Spherical and stores the result\n * @param spherical the spherical to add\n * @param ref the spherical to store the result in\n * @returns the updated ref\n */\n addToRef(spherical, ref) {\n ref.radius = this.radius + spherical.radius;\n ref.theta = this.theta + spherical.theta;\n ref.phi = this.phi + spherical.phi;\n return ref;\n }\n /**\n * Adds the current Spherical and the given Spherical\n * @param spherical the spherical to add\n * @returns the sum spherical\n */\n add(spherical) {\n const ref = new Spherical(0, 0, 0);\n this.addToRef(spherical, ref);\n return ref;\n }\n /**\n * Adds the given spherical to the current spherical\n * @param spherical the spherical to add\n * @returns the current spherical\n */\n addInPlace(spherical) {\n this.addToRef(spherical, this);\n return this;\n }\n /**\n * Adds the provided values to the current spherical\n * @param radius the amount to add to the radius\n * @param theta the amount to add to the theta\n * @param phi the amount to add to the phi\n * @returns the current spherical\n */\n addInPlaceFromFloats(radius, theta, phi) {\n this.radius += radius;\n this.theta += theta;\n this.phi += phi;\n return this;\n }\n /**\n * Subtracts the given Spherical from the current Spherical and stores the result\n * @param spherical the spherical to subtract\n * @param ref the spherical to store the result in\n * @returns the updated ref\n */\n subtractToRef(spherical, ref) {\n ref.radius = this.radius - spherical.radius;\n ref.theta = this.theta - spherical.theta;\n ref.phi = this.phi - spherical.phi;\n return ref;\n }\n /**\n * Subtracts the given Spherical from the current Spherical\n * @param spherical the spherical to subtract\n * @returns the difference spherical\n */\n subtract(spherical) {\n const ref = new Spherical(0, 0, 0);\n this.subtractToRef(spherical, ref);\n return ref;\n }\n /**\n * Subtracts the given Spherical from the current Spherical\n * @param spherical the spherical to subtract\n * @returns the current spherical\n */\n subtractInPlace(spherical) {\n this.subtractToRef(spherical, this);\n return this;\n }\n /**\n * Subtracts the given floats from the current spherical\n * @param radius the amount to subtract from the radius\n * @param theta the amount to subtract from the theta\n * @param phi the amount to subtract from the phi\n * @param ref the spherical to store the result in\n * @returns the updated ref\n */\n subtractFromFloatsToRef(radius, theta, phi, ref) {\n ref.radius = this.radius - radius;\n ref.theta = this.theta - theta;\n ref.phi = this.phi - phi;\n return ref;\n }\n /**\n * Subtracts the given floats from the current spherical\n * @param radius the amount to subtract from the radius\n * @param theta the amount to subtract from the theta\n * @param phi the amount to subtract from the phi\n * @returns the difference spherical\n */\n subtractFromFloats(radius, theta, phi) {\n const ref = new Spherical(0, 0, 0);\n this.subtractFromFloatsToRef(radius, theta, phi, ref);\n return ref;\n }\n /**\n * Multiplies the given Spherical with the current Spherical and stores the result\n * @param spherical the spherical to multiply\n * @param ref the spherical to store the result in\n * @returns the updated ref\n */\n multiplyToRef(spherical, ref) {\n ref.radius = this.radius * spherical.radius;\n ref.theta = this.theta * spherical.theta;\n ref.phi = this.phi * spherical.phi;\n return ref;\n }\n /**\n * Multiplies the given Spherical with the current Spherical\n * @param spherical the spherical to multiply\n * @returns the product spherical\n */\n multiply(spherical) {\n const ref = new Spherical(0, 0, 0);\n this.multiplyToRef(spherical, ref);\n return ref;\n }\n /**\n * Multiplies the given Spherical with the current Spherical\n * @param spherical the spherical to multiply\n * @returns the current spherical\n */\n multiplyInPlace(spherical) {\n this.multiplyToRef(spherical, this);\n return this;\n }\n /**\n * Divides the current Spherical by the given Spherical and stores the result\n * @param spherical the spherical to divide\n * @param ref the spherical to store the result in\n * @returns the updated ref\n */\n divideToRef(spherical, ref) {\n ref.radius = this.radius / spherical.radius;\n ref.theta = this.theta / spherical.theta;\n ref.phi = this.phi / spherical.phi;\n return ref;\n }\n /**\n * Divides the current Spherical by the given Spherical\n * @param spherical the spherical to divide\n * @returns the quotient spherical\n */\n divide(spherical) {\n const ref = new Spherical(0, 0, 0);\n this.divideToRef(spherical, ref);\n return ref;\n }\n /**\n * Divides the current Spherical by the given Spherical\n * @param spherical the spherical to divide\n * @returns the current spherical\n */\n divideInPlace(spherical) {\n this.divideToRef(spherical, this);\n return this;\n }\n /**\n * Clones the current spherical\n * @returns a clone of the current spherical\n */\n clone() {\n return new Spherical(this.radius, this.theta, this.phi);\n }\n /**\n * Copies the source spherical into the current spherical\n * @param source the spherical to copy from\n * @returns the current spherical\n */\n copyFrom(source) {\n this.radius = source.radius;\n this.theta = source.theta;\n this.phi = source.phi;\n return this;\n }\n /**\n * Copies the given values into the current spherical\n * @param radius the radius to use\n * @param theta the theta to use\n * @param phi the phi to use\n * @returns the current spherical\n */\n copyFromFloats(radius, theta, phi) {\n this.radius = radius;\n this.theta = theta;\n this.phi = phi;\n return this;\n }\n /**\n * Scales the current spherical and stores the result\n * @param scale defines the multiplication factor\n * @param ref where to store the result\n * @returns the updated ref\n */\n scaleToRef(scale, ref) {\n ref.radius = this.radius * scale;\n ref.theta = this.theta * scale;\n ref.phi = this.phi * scale;\n return ref;\n }\n /**\n * Scales the current spherical and returns a new spherical with the scaled coordinates\n * @param scale defines the multiplication factor\n * @returns the scaled spherical\n */\n scale(scale) {\n const ref = new Spherical(0, 0, 0);\n this.scaleToRef(scale, ref);\n return ref;\n }\n /**\n * Scales the current spherical\n * @param scale defines the multiplication factor\n * @returns the current spherical\n */\n scaleInPlace(scale) {\n this.scaleToRef(scale, this);\n return this;\n }\n /**\n * Sets the values of the current spherical\n * @param radius the new radius\n * @param theta the new theta\n * @param phi the new phi\n * @returns the current spherical\n */\n set(radius, theta, phi) {\n this.radius = radius;\n this.theta = theta;\n this.phi = phi;\n return this;\n }\n /**\n * Sets the values of the current spherical\n * @param value the new values\n * @returns the current spherical\n */\n setAll(value) {\n this.set(value, value, value);\n return this;\n }\n /**\n * Assigns the rectangular coordinates of the current Spherical to a Vector3\n * @param ref the Vector3 to update\n * @returns the updated Vector3\n */\n toVector3ToRef(ref) {\n const x = this.radius * Math.sin(this.theta) * Math.cos(this.phi);\n const y = this.radius * Math.cos(this.theta);\n const z = this.radius * Math.sin(this.theta) * Math.sin(this.phi);\n ref.set(x, y, z);\n return ref;\n }\n /**\n * Gets a Vector3 from the current spherical coordinates\n * @returns the (x, y,z) form of the current Spherical\n */\n toVector3() {\n const ref = new Vector3(0, 0, 0);\n return this.toVector3ToRef(ref);\n }\n /**\n * Assigns the spherical coordinates from a Vector3\n * @param vector the vector to convert\n * @param ref the Spherical to update\n * @returns the updated ref\n */\n static FromVector3ToRef(vector, ref) {\n ref.radius = vector.length();\n ref.theta = Math.acos(vector.y / ref.radius);\n ref.phi = Math.atan2(vector.z, vector.x);\n return ref;\n }\n /**\n * Gets a Spherical from a Vector3\n * @param vector defines the vector in (x, y, z) coordinate space\n * @returns a new Spherical\n */\n static FromVector3(vector) {\n const spherical = new Spherical(0, 0, 0);\n Spherical.FromVector3ToRef(vector, spherical);\n return spherical;\n }\n /**\n * Converts an array of floats to a spherical\n * @param array the array to convert\n * @returns the converted spherical\n */\n static FromArray(array) {\n return new Spherical(array[0], array[1], array[2]);\n }\n}\n//# sourceMappingURL=math.polar.js.map","export * from \"./math.scalar.js\";\nexport * from \"./math.functions.js\";\nexport * from \"./math.polar.js\";\nexport * from \"./math.js\";\nexport * from \"./sphericalPolynomial.js\";\n//# sourceMappingURL=index.js.map","/* eslint-disable @typescript-eslint/naming-convention */\nimport { Tools } from \"../../Misc/tools.js\";\nimport { AutoReleaseWorkerPool } from \"../../Misc/workerPool.js\";\nimport { VertexData } from \"../../Meshes/mesh.vertexData.js\";\nfunction createDecoderAsync(wasmBinary) {\n return new Promise((resolve) => {\n DracoDecoderModule({ wasmBinary: wasmBinary }).then((module) => {\n resolve({ module: module });\n });\n });\n}\nfunction decodeMesh(decoderModule, dataView, attributes, onIndicesData, onAttributeData, dividers) {\n const buffer = new decoderModule.DecoderBuffer();\n buffer.Init(dataView, dataView.byteLength);\n const decoder = new decoderModule.Decoder();\n let geometry;\n let status;\n try {\n const type = decoder.GetEncodedGeometryType(buffer);\n switch (type) {\n case decoderModule.TRIANGULAR_MESH:\n geometry = new decoderModule.Mesh();\n status = decoder.DecodeBufferToMesh(buffer, geometry);\n break;\n case decoderModule.POINT_CLOUD:\n geometry = new decoderModule.PointCloud();\n status = decoder.DecodeBufferToPointCloud(buffer, geometry);\n break;\n default:\n throw new Error(`Invalid geometry type ${type}`);\n }\n if (!status.ok() || !geometry.ptr) {\n throw new Error(status.error_msg());\n }\n if (type === decoderModule.TRIANGULAR_MESH) {\n const numFaces = geometry.num_faces();\n const numIndices = numFaces * 3;\n const byteLength = numIndices * 4;\n const ptr = decoderModule._malloc(byteLength);\n try {\n decoder.GetTrianglesUInt32Array(geometry, byteLength, ptr);\n const indices = new Uint32Array(numIndices);\n indices.set(new Uint32Array(decoderModule.HEAPF32.buffer, ptr, numIndices));\n onIndicesData(indices);\n }\n finally {\n decoderModule._free(ptr);\n }\n }\n const processAttribute = (kind, attribute, divider = 1) => {\n const numComponents = attribute.num_components();\n const numPoints = geometry.num_points();\n const numValues = numPoints * numComponents;\n const byteLength = numValues * Float32Array.BYTES_PER_ELEMENT;\n const ptr = decoderModule._malloc(byteLength);\n try {\n decoder.GetAttributeDataArrayForAllPoints(geometry, attribute, decoderModule.DT_FLOAT32, byteLength, ptr);\n const values = new Float32Array(decoderModule.HEAPF32.buffer, ptr, numValues);\n if (kind === \"color\" && numComponents === 3) {\n const babylonData = new Float32Array(numPoints * 4);\n for (let i = 0, j = 0; i < babylonData.length; i += 4, j += numComponents) {\n babylonData[i + 0] = values[j + 0];\n babylonData[i + 1] = values[j + 1];\n babylonData[i + 2] = values[j + 2];\n babylonData[i + 3] = 1;\n }\n onAttributeData(kind, babylonData);\n }\n else {\n const babylonData = new Float32Array(numValues);\n babylonData.set(new Float32Array(decoderModule.HEAPF32.buffer, ptr, numValues));\n if (divider !== 1) {\n for (let i = 0; i < babylonData.length; i++) {\n babylonData[i] = babylonData[i] / divider;\n }\n }\n onAttributeData(kind, babylonData);\n }\n }\n finally {\n decoderModule._free(ptr);\n }\n };\n if (attributes) {\n for (const kind in attributes) {\n const id = attributes[kind];\n const attribute = decoder.GetAttributeByUniqueId(geometry, id);\n const divider = (dividers && dividers[kind]) || 1;\n processAttribute(kind, attribute, divider);\n }\n }\n else {\n const nativeAttributeTypes = {\n position: \"POSITION\",\n normal: \"NORMAL\",\n color: \"COLOR\",\n uv: \"TEX_COORD\",\n };\n for (const kind in nativeAttributeTypes) {\n const id = decoder.GetAttributeId(geometry, decoderModule[nativeAttributeTypes[kind]]);\n if (id !== -1) {\n const attribute = decoder.GetAttribute(geometry, id);\n processAttribute(kind, attribute);\n }\n }\n }\n }\n finally {\n if (geometry) {\n decoderModule.destroy(geometry);\n }\n decoderModule.destroy(decoder);\n decoderModule.destroy(buffer);\n }\n}\n/**\n * The worker function that gets converted to a blob url to pass into a worker.\n */\nfunction worker() {\n let decoderPromise;\n onmessage = (event) => {\n const data = event.data;\n switch (data.id) {\n case \"init\": {\n const decoder = data.decoder;\n if (decoder.url) {\n importScripts(decoder.url);\n decoderPromise = DracoDecoderModule({ wasmBinary: decoder.wasmBinary });\n }\n postMessage(\"done\");\n break;\n }\n case \"decodeMesh\": {\n if (!decoderPromise) {\n throw new Error(\"Draco decoder module is not available\");\n }\n decoderPromise.then((decoder) => {\n decodeMesh(decoder, data.dataView, data.attributes, (indices) => {\n postMessage({ id: \"indices\", value: indices }, [indices.buffer]);\n }, (kind, data) => {\n postMessage({ id: kind, value: data }, [data.buffer]);\n });\n postMessage(\"done\");\n });\n break;\n }\n }\n };\n}\n/**\n * Draco compression (https://google.github.io/draco/)\n *\n * This class wraps the Draco module.\n *\n * **Encoder**\n *\n * The encoder is not currently implemented.\n *\n * **Decoder**\n *\n * By default, the configuration points to a copy of the Draco decoder files for glTF from the babylon.js preview cdn https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js.\n *\n * To update the configuration, use the following code:\n * ```javascript\n * DracoCompression.Configuration = {\n * decoder: {\n * wasmUrl: \"\",\n * wasmBinaryUrl: \"\",\n * fallbackUrl: \"\",\n * }\n * };\n * ```\n *\n * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support WebAssembly or only support the JavaScript version.\n * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.\n * Use `DracoCompression.DecoderAvailable` to determine if the decoder configuration is available for the current context.\n *\n * To decode Draco compressed data, get the default DracoCompression object and call decodeMeshAsync:\n * ```javascript\n * var vertexData = await DracoCompression.Default.decodeMeshAsync(data);\n * ```\n *\n * @see https://playground.babylonjs.com/#DMZIBD#0\n */\nexport class DracoCompression {\n /**\n * Returns true if the decoder configuration is available.\n */\n static get DecoderAvailable() {\n const decoder = DracoCompression.Configuration.decoder;\n return !!((decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === \"object\") || decoder.fallbackUrl);\n }\n static GetDefaultNumWorkers() {\n if (typeof navigator !== \"object\" || !navigator.hardwareConcurrency) {\n return 1;\n }\n // Use 50% of the available logical processors but capped at 4.\n return Math.min(Math.floor(navigator.hardwareConcurrency * 0.5), 4);\n }\n /**\n * Default instance for the draco compression object.\n */\n static get Default() {\n if (!DracoCompression._Default) {\n DracoCompression._Default = new DracoCompression();\n }\n return DracoCompression._Default;\n }\n /**\n * Constructor\n * @param numWorkers The number of workers for async operations. Specify `0` to disable web workers and run synchronously in the current context.\n */\n constructor(numWorkers = DracoCompression.DefaultNumWorkers) {\n const decoder = DracoCompression.Configuration.decoder;\n const decoderInfo = decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === \"object\"\n ? {\n url: Tools.GetAbsoluteUrl(decoder.wasmUrl),\n wasmBinaryPromise: Tools.LoadFileAsync(Tools.GetAbsoluteUrl(decoder.wasmBinaryUrl)),\n }\n : {\n url: Tools.GetAbsoluteUrl(decoder.fallbackUrl),\n wasmBinaryPromise: Promise.resolve(undefined),\n };\n if (numWorkers && typeof Worker === \"function\" && typeof URL === \"function\") {\n this._workerPoolPromise = decoderInfo.wasmBinaryPromise.then((decoderWasmBinary) => {\n const workerContent = `${decodeMesh}(${worker})()`;\n const workerBlobUrl = URL.createObjectURL(new Blob([workerContent], { type: \"application/javascript\" }));\n return new AutoReleaseWorkerPool(numWorkers, () => {\n return new Promise((resolve, reject) => {\n const worker = new Worker(workerBlobUrl);\n const onError = (error) => {\n worker.removeEventListener(\"error\", onError);\n worker.removeEventListener(\"message\", onMessage);\n reject(error);\n };\n const onMessage = (message) => {\n if (message.data === \"done\") {\n worker.removeEventListener(\"error\", onError);\n worker.removeEventListener(\"message\", onMessage);\n resolve(worker);\n }\n };\n worker.addEventListener(\"error\", onError);\n worker.addEventListener(\"message\", onMessage);\n worker.postMessage({\n id: \"init\",\n decoder: {\n url: decoderInfo.url,\n wasmBinary: decoderWasmBinary,\n },\n });\n });\n });\n });\n }\n else {\n this._decoderModulePromise = decoderInfo.wasmBinaryPromise.then((decoderWasmBinary) => {\n if (!decoderInfo.url) {\n throw new Error(\"Draco decoder module is not available\");\n }\n return Tools.LoadScriptAsync(decoderInfo.url).then(() => {\n return createDecoderAsync(decoderWasmBinary);\n });\n });\n }\n }\n /**\n * Stop all async operations and release resources.\n */\n dispose() {\n if (this._workerPoolPromise) {\n this._workerPoolPromise.then((workerPool) => {\n workerPool.dispose();\n });\n }\n delete this._workerPoolPromise;\n delete this._decoderModulePromise;\n }\n /**\n * Returns a promise that resolves when ready. Call this manually to ensure draco compression is ready before use.\n * @returns a promise that resolves when ready\n */\n whenReadyAsync() {\n if (this._workerPoolPromise) {\n return this._workerPoolPromise.then(() => { });\n }\n if (this._decoderModulePromise) {\n return this._decoderModulePromise.then(() => { });\n }\n return Promise.resolve();\n }\n /**\n * Decode Draco compressed mesh data to vertex data.\n * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data\n * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids\n * @param dividers a list of optional dividers for normalization\n * @returns A promise that resolves with the decoded vertex data\n */\n decodeMeshAsync(data, attributes, dividers) {\n const dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;\n if (this._workerPoolPromise) {\n return this._workerPoolPromise.then((workerPool) => {\n return new Promise((resolve, reject) => {\n workerPool.push((worker, onComplete) => {\n const vertexData = new VertexData();\n const onError = (error) => {\n worker.removeEventListener(\"error\", onError);\n worker.removeEventListener(\"message\", onMessage);\n reject(error);\n onComplete();\n };\n const onMessage = (message) => {\n if (message.data === \"done\") {\n worker.removeEventListener(\"error\", onError);\n worker.removeEventListener(\"message\", onMessage);\n resolve(vertexData);\n onComplete();\n }\n else if (message.data.id === \"indices\") {\n vertexData.indices = message.data.value;\n }\n else {\n // check normalization\n const divider = dividers && dividers[message.data.id] ? dividers[message.data.id] : 1;\n if (divider !== 1) {\n // normalize\n for (let i = 0; i < message.data.value.length; i++) {\n message.data.value[i] = message.data.value[i] / divider;\n }\n }\n vertexData.set(message.data.value, message.data.id);\n }\n };\n worker.addEventListener(\"error\", onError);\n worker.addEventListener(\"message\", onMessage);\n const dataViewCopy = new Uint8Array(dataView.byteLength);\n dataViewCopy.set(new Uint8Array(dataView.buffer, dataView.byteOffset, dataView.byteLength));\n worker.postMessage({ id: \"decodeMesh\", dataView: dataViewCopy, attributes: attributes }, [dataViewCopy.buffer]);\n });\n });\n });\n }\n if (this._decoderModulePromise) {\n return this._decoderModulePromise.then((decoder) => {\n const vertexData = new VertexData();\n decodeMesh(decoder.module, dataView, attributes, (indices) => {\n vertexData.indices = indices;\n }, (kind, data) => {\n vertexData.set(data, kind);\n }, dividers);\n return vertexData;\n });\n }\n throw new Error(\"Draco decoder module is not available\");\n }\n}\n/**\n * The configuration. Defaults to the following urls:\n * - wasmUrl: \"https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js\"\n * - wasmBinaryUrl: \"https://preview.babylonjs.com/draco_decoder_gltf.wasm\"\n * - fallbackUrl: \"https://preview.babylonjs.com/draco_decoder_gltf.js\"\n */\nDracoCompression.Configuration = {\n decoder: {\n wasmUrl: \"https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js\",\n wasmBinaryUrl: \"https://preview.babylonjs.com/draco_decoder_gltf.wasm\",\n fallbackUrl: \"https://preview.babylonjs.com/draco_decoder_gltf.js\",\n },\n};\n/**\n * Default number of workers to create when creating the draco compression object.\n */\nDracoCompression.DefaultNumWorkers = DracoCompression.GetDefaultNumWorkers();\nDracoCompression._Default = null;\n//# sourceMappingURL=dracoCompression.js.map","import { Tools } from \"../../Misc/tools.js\";\n/**\n * Meshopt compression (https://github.com/zeux/meshoptimizer)\n *\n * This class wraps the meshopt library from https://github.com/zeux/meshoptimizer/tree/master/js.\n *\n * **Encoder**\n *\n * The encoder is not currently implemented.\n *\n * **Decoder**\n *\n * By default, the configuration points to a copy of the meshopt files on the Babylon.js preview CDN (e.g. https://preview.babylonjs.com/meshopt_decoder.js).\n *\n * To update the configuration, use the following code:\n * ```javascript\n * MeshoptCompression.Configuration = {\n * decoder: {\n * url: \"\"\n * }\n * };\n * ```\n */\nexport class MeshoptCompression {\n /**\n * Default instance for the meshoptimizer object.\n */\n static get Default() {\n if (!MeshoptCompression._Default) {\n MeshoptCompression._Default = new MeshoptCompression();\n }\n return MeshoptCompression._Default;\n }\n /**\n * Constructor\n */\n constructor() {\n const decoder = MeshoptCompression.Configuration.decoder;\n this._decoderModulePromise = Tools.LoadScriptAsync(Tools.GetAbsoluteUrl(decoder.url)).then(() => {\n // Wait for WebAssembly compilation before resolving promise\n return MeshoptDecoder.ready;\n });\n }\n /**\n * Stop all async operations and release resources.\n */\n dispose() {\n delete this._decoderModulePromise;\n }\n /**\n * Decode meshopt data.\n * @see https://github.com/zeux/meshoptimizer/tree/master/js#decoder\n * @param source The input data.\n * @param count The number of elements.\n * @param stride The stride in bytes.\n * @param mode The compression mode.\n * @param filter The compression filter.\n * @returns a Promise that resolves to the decoded data\n */\n decodeGltfBufferAsync(source, count, stride, mode, filter) {\n return this._decoderModulePromise.then(() => {\n const result = new Uint8Array(count * stride);\n MeshoptDecoder.decodeGltfBuffer(result, count, stride, source, mode, filter);\n return result;\n });\n }\n}\n/**\n * The configuration. Defaults to the following:\n * ```javascript\n * decoder: {\n * url: \"https://preview.babylonjs.com/meshopt_decoder.js\"\n * }\n * ```\n */\nMeshoptCompression.Configuration = {\n decoder: {\n url: \"https://preview.babylonjs.com/meshopt_decoder.js\",\n },\n};\nMeshoptCompression._Default = null;\n//# sourceMappingURL=meshoptCompression.js.map","export * from \"./dracoCompression.js\";\nexport * from \"./meshoptCompression.js\";\n//# sourceMappingURL=index.js.map","import { Quaternion, Matrix, Vector3, Vector2 } from \"../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { SubMesh } from \"../Meshes/subMesh.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\n\n/**\n * Unique ID when we import meshes from Babylon to CSG\n */\nlet currentCSGMeshId = 0;\n/**\n * Represents a vertex of a polygon. Use your own vertex class instead of this\n * one to provide additional features like texture coordinates and vertex\n * colors. Custom vertex classes need to provide a `pos` property and `clone()`,\n * `flip()`, and `interpolate()` methods that behave analogous to the ones\n * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience\n * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`\n * is not used anywhere else.\n * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes\n */\nclass Vertex {\n /**\n * Initializes the vertex\n * @param pos The position of the vertex\n * @param normal The normal of the vertex\n * @param uv The texture coordinate of the vertex\n * @param vertColor The RGBA color of the vertex\n */\n constructor(\n /**\n * The position of the vertex\n */\n pos, \n /**\n * The normal of the vertex\n */\n normal, \n /**\n * The texture coordinate of the vertex\n */\n uv, \n /**\n * The texture coordinate of the vertex\n */\n vertColor) {\n this.pos = pos;\n this.normal = normal;\n this.uv = uv;\n this.vertColor = vertColor;\n }\n /**\n * Make a clone, or deep copy, of the vertex\n * @returns A new Vertex\n */\n clone() {\n var _a, _b;\n return new Vertex(this.pos.clone(), this.normal.clone(), (_a = this.uv) === null || _a === void 0 ? void 0 : _a.clone(), (_b = this.vertColor) === null || _b === void 0 ? void 0 : _b.clone());\n }\n /**\n * Invert all orientation-specific data (e.g. vertex normal). Called when the\n * orientation of a polygon is flipped.\n */\n flip() {\n this.normal = this.normal.scale(-1);\n }\n /**\n * Create a new vertex between this vertex and `other` by linearly\n * interpolating all properties using a parameter of `t`. Subclasses should\n * override this to interpolate additional properties.\n * @param other the vertex to interpolate against\n * @param t The factor used to linearly interpolate between the vertices\n */\n interpolate(other, t) {\n return new Vertex(Vector3.Lerp(this.pos, other.pos, t), Vector3.Lerp(this.normal, other.normal, t), this.uv && other.uv ? Vector2.Lerp(this.uv, other.uv, t) : undefined, this.vertColor && other.vertColor ? Color4.Lerp(this.vertColor, other.vertColor, t) : undefined);\n }\n}\n/**\n * Represents a plane in 3D space.\n */\nclass Plane {\n /**\n * Initializes the plane\n * @param normal The normal for the plane\n * @param w\n */\n constructor(normal, w) {\n this.normal = normal;\n this.w = w;\n }\n /**\n * Construct a plane from three points\n * @param a Point a\n * @param b Point b\n * @param c Point c\n */\n static FromPoints(a, b, c) {\n const v0 = c.subtract(a);\n const v1 = b.subtract(a);\n if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {\n return null;\n }\n const n = Vector3.Normalize(Vector3.Cross(v0, v1));\n return new Plane(n, Vector3.Dot(n, a));\n }\n /**\n * Clone, or make a deep copy of the plane\n * @returns a new Plane\n */\n clone() {\n return new Plane(this.normal.clone(), this.w);\n }\n /**\n * Flip the face of the plane\n */\n flip() {\n this.normal.scaleInPlace(-1);\n this.w = -this.w;\n }\n /**\n * Split `polygon` by this plane if needed, then put the polygon or polygon\n * fragments in the appropriate lists. Coplanar polygons go into either\n `* coplanarFront` or `coplanarBack` depending on their orientation with\n * respect to this plane. Polygons in front or in back of this plane go into\n * either `front` or `back`\n * @param polygon The polygon to be split\n * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane\n * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane\n * @param front Will contain the polygons in front of the plane\n * @param back Will contain the polygons begind the plane\n */\n splitPolygon(polygon, coplanarFront, coplanarBack, front, back) {\n const COPLANAR = 0;\n const FRONT = 1;\n const BACK = 2;\n const SPANNING = 3;\n // Classify each point as well as the entire polygon into one of the above\n // four classes.\n let polygonType = 0;\n const types = [];\n let i;\n let t;\n for (i = 0; i < polygon.vertices.length; i++) {\n t = Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;\n const type = t < -Plane.EPSILON ? BACK : t > Plane.EPSILON ? FRONT : COPLANAR;\n polygonType |= type;\n types.push(type);\n }\n // Put the polygon in the correct list, splitting it when necessary\n switch (polygonType) {\n case COPLANAR:\n (Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);\n break;\n case FRONT:\n front.push(polygon);\n break;\n case BACK:\n back.push(polygon);\n break;\n case SPANNING: {\n const f = [], b = [];\n for (i = 0; i < polygon.vertices.length; i++) {\n const j = (i + 1) % polygon.vertices.length;\n const ti = types[i], tj = types[j];\n const vi = polygon.vertices[i], vj = polygon.vertices[j];\n if (ti !== BACK) {\n f.push(vi);\n }\n if (ti !== FRONT) {\n b.push(ti !== BACK ? vi.clone() : vi);\n }\n if ((ti | tj) === SPANNING) {\n t = (this.w - Vector3.Dot(this.normal, vi.pos)) / Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));\n const v = vi.interpolate(vj, t);\n f.push(v);\n b.push(v.clone());\n }\n }\n let poly;\n if (f.length >= 3) {\n poly = new Polygon(f, polygon.shared);\n if (poly.plane) {\n front.push(poly);\n }\n }\n if (b.length >= 3) {\n poly = new Polygon(b, polygon.shared);\n if (poly.plane) {\n back.push(poly);\n }\n }\n break;\n }\n }\n }\n}\n/**\n * `CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a\n * point is on the plane\n */\nPlane.EPSILON = 1e-5;\n/**\n * Represents a convex polygon. The vertices used to initialize a polygon must\n * be coplanar and form a convex loop.\n *\n * Each convex polygon has a `shared` property, which is shared between all\n * polygons that are clones of each other or were split from the same polygon.\n * This can be used to define per-polygon properties (such as surface color)\n */\nclass Polygon {\n /**\n * Initializes the polygon\n * @param vertices The vertices of the polygon\n * @param shared The properties shared across all polygons\n */\n constructor(vertices, shared) {\n this.vertices = vertices;\n this.shared = shared;\n this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);\n }\n /**\n * Clones, or makes a deep copy, or the polygon\n */\n clone() {\n const vertices = this.vertices.map((v) => v.clone());\n return new Polygon(vertices, this.shared);\n }\n /**\n * Flips the faces of the polygon\n */\n flip() {\n this.vertices.reverse().map((v) => {\n v.flip();\n });\n this.plane.flip();\n }\n}\n/**\n * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons\n * by picking a polygon to split along. That polygon (and all other coplanar\n * polygons) are added directly to that node and the other polygons are added to\n * the front and/or back subtrees. This is not a leafy BSP tree since there is\n * no distinction between internal and leaf nodes\n */\nclass Node {\n /**\n * Initializes the node\n * @param polygons A collection of polygons held in the node\n */\n constructor(polygons) {\n this._plane = null;\n this._front = null;\n this._back = null;\n this._polygons = new Array();\n if (polygons) {\n this.build(polygons);\n }\n }\n /**\n * Clones, or makes a deep copy, of the node\n * @returns The cloned node\n */\n clone() {\n const node = new Node();\n node._plane = this._plane && this._plane.clone();\n node._front = this._front && this._front.clone();\n node._back = this._back && this._back.clone();\n node._polygons = this._polygons.map((p) => p.clone());\n return node;\n }\n /**\n * Convert solid space to empty space and empty space to solid space\n */\n invert() {\n for (let i = 0; i < this._polygons.length; i++) {\n this._polygons[i].flip();\n }\n if (this._plane) {\n this._plane.flip();\n }\n if (this._front) {\n this._front.invert();\n }\n if (this._back) {\n this._back.invert();\n }\n const temp = this._front;\n this._front = this._back;\n this._back = temp;\n }\n /**\n * Recursively remove all polygons in `polygons` that are inside this BSP\n * tree.\n * @param polygons Polygons to remove from the BSP\n * @returns Polygons clipped from the BSP\n */\n clipPolygons(polygons) {\n if (!this._plane) {\n return polygons.slice();\n }\n let front = new Array(), back = new Array();\n for (let i = 0; i < polygons.length; i++) {\n this._plane.splitPolygon(polygons[i], front, back, front, back);\n }\n if (this._front) {\n front = this._front.clipPolygons(front);\n }\n if (this._back) {\n back = this._back.clipPolygons(back);\n }\n else {\n back = [];\n }\n return front.concat(back);\n }\n /**\n * Remove all polygons in this BSP tree that are inside the other BSP tree\n * `bsp`.\n * @param bsp BSP containing polygons to remove from this BSP\n */\n clipTo(bsp) {\n this._polygons = bsp.clipPolygons(this._polygons);\n if (this._front) {\n this._front.clipTo(bsp);\n }\n if (this._back) {\n this._back.clipTo(bsp);\n }\n }\n /**\n * Return a list of all polygons in this BSP tree\n * @returns List of all polygons in this BSP tree\n */\n allPolygons() {\n let polygons = this._polygons.slice();\n if (this._front) {\n polygons = polygons.concat(this._front.allPolygons());\n }\n if (this._back) {\n polygons = polygons.concat(this._back.allPolygons());\n }\n return polygons;\n }\n /**\n * Build a BSP tree out of `polygons`. When called on an existing tree, the\n * new polygons are filtered down to the bottom of the tree and become new\n * nodes there. Each set of polygons is partitioned using the first polygon\n * (no heuristic is used to pick a good split)\n * @param polygons Polygons used to construct the BSP tree\n */\n build(polygons) {\n if (!polygons.length) {\n return;\n }\n if (!this._plane) {\n this._plane = polygons[0].plane.clone();\n }\n const front = new Array(), back = new Array();\n for (let i = 0; i < polygons.length; i++) {\n this._plane.splitPolygon(polygons[i], this._polygons, this._polygons, front, back);\n }\n if (front.length) {\n if (!this._front) {\n this._front = new Node();\n }\n this._front.build(front);\n }\n if (back.length) {\n if (!this._back) {\n this._back = new Node();\n }\n this._back.build(back);\n }\n }\n}\n/**\n * Class for building Constructive Solid Geometry\n */\nexport class CSG {\n constructor() {\n this._polygons = new Array();\n }\n /**\n * Convert the Mesh to CSG\n * @param mesh The Mesh to convert to CSG\n * @param absolute If true, the final (local) matrix transformation is set to the identity and not to that of `mesh`. It can help when dealing with right-handed meshes (default: false)\n * @returns A new CSG from the Mesh\n */\n static FromMesh(mesh, absolute = false) {\n let vertex, normal, uv = undefined, position, vertColor = undefined, polygon, vertices;\n const polygons = new Array();\n let matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;\n let invertWinding = false;\n if (mesh instanceof Mesh) {\n mesh.computeWorldMatrix(true);\n matrix = mesh.getWorldMatrix();\n meshPosition = mesh.position.clone();\n meshRotation = mesh.rotation.clone();\n if (mesh.rotationQuaternion) {\n meshRotationQuaternion = mesh.rotationQuaternion.clone();\n }\n meshScaling = mesh.scaling.clone();\n if (mesh.material && absolute) {\n invertWinding = mesh.material.sideOrientation === 0;\n }\n }\n else {\n throw \"BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh\";\n }\n const indices = mesh.getIndices(), positions = mesh.getVerticesData(VertexBuffer.PositionKind), normals = mesh.getVerticesData(VertexBuffer.NormalKind), uvs = mesh.getVerticesData(VertexBuffer.UVKind), vertColors = mesh.getVerticesData(VertexBuffer.ColorKind);\n const subMeshes = mesh.subMeshes;\n for (let sm = 0, sml = subMeshes.length; sm < sml; sm++) {\n for (let i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {\n vertices = [];\n for (let j = 0; j < 3; j++) {\n const indexIndices = j === 0 ? i + j : invertWinding ? i + 3 - j : i + j;\n const sourceNormal = new Vector3(normals[indices[indexIndices] * 3], normals[indices[indexIndices] * 3 + 1], normals[indices[indexIndices] * 3 + 2]);\n if (uvs) {\n uv = new Vector2(uvs[indices[indexIndices] * 2], uvs[indices[indexIndices] * 2 + 1]);\n }\n if (vertColors) {\n vertColor = new Color4(vertColors[indices[indexIndices] * 4], vertColors[indices[indexIndices] * 4 + 1], vertColors[indices[indexIndices] * 4 + 2], vertColors[indices[indexIndices] * 4 + 3]);\n }\n const sourcePosition = new Vector3(positions[indices[indexIndices] * 3], positions[indices[indexIndices] * 3 + 1], positions[indices[indexIndices] * 3 + 2]);\n position = Vector3.TransformCoordinates(sourcePosition, matrix);\n normal = Vector3.TransformNormal(sourceNormal, matrix);\n vertex = new Vertex(position, normal, uv, vertColor);\n vertices.push(vertex);\n }\n polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });\n // To handle the case of degenerated triangle\n // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated\n if (polygon.plane) {\n polygons.push(polygon);\n }\n }\n }\n const csg = CSG._FromPolygons(polygons);\n csg.matrix = absolute ? Matrix.Identity() : matrix;\n csg.position = absolute ? Vector3.Zero() : meshPosition;\n csg.rotation = absolute ? Vector3.Zero() : meshRotation;\n csg.scaling = absolute ? Vector3.One() : meshScaling;\n csg.rotationQuaternion = absolute && meshRotationQuaternion ? Quaternion.Identity() : meshRotationQuaternion;\n currentCSGMeshId++;\n return csg;\n }\n /**\n * Construct a CSG solid from a list of `CSG.Polygon` instances.\n * @param polygons Polygons used to construct a CSG solid\n */\n static _FromPolygons(polygons) {\n const csg = new CSG();\n csg._polygons = polygons;\n return csg;\n }\n /**\n * Clones, or makes a deep copy, of the CSG\n * @returns A new CSG\n */\n clone() {\n const csg = new CSG();\n csg._polygons = this._polygons.map((p) => p.clone());\n csg.copyTransformAttributes(this);\n return csg;\n }\n /**\n * Unions this CSG with another CSG\n * @param csg The CSG to union against this CSG\n * @returns The unioned CSG\n */\n union(csg) {\n const a = new Node(this.clone()._polygons);\n const b = new Node(csg.clone()._polygons);\n a.clipTo(b);\n b.clipTo(a);\n b.invert();\n b.clipTo(a);\n b.invert();\n a.build(b.allPolygons());\n return CSG._FromPolygons(a.allPolygons()).copyTransformAttributes(this);\n }\n /**\n * Unions this CSG with another CSG in place\n * @param csg The CSG to union against this CSG\n */\n unionInPlace(csg) {\n const a = new Node(this._polygons);\n const b = new Node(csg._polygons);\n a.clipTo(b);\n b.clipTo(a);\n b.invert();\n b.clipTo(a);\n b.invert();\n a.build(b.allPolygons());\n this._polygons = a.allPolygons();\n }\n /**\n * Subtracts this CSG with another CSG\n * @param csg The CSG to subtract against this CSG\n * @returns A new CSG\n */\n subtract(csg) {\n const a = new Node(this.clone()._polygons);\n const b = new Node(csg.clone()._polygons);\n a.invert();\n a.clipTo(b);\n b.clipTo(a);\n b.invert();\n b.clipTo(a);\n b.invert();\n a.build(b.allPolygons());\n a.invert();\n return CSG._FromPolygons(a.allPolygons()).copyTransformAttributes(this);\n }\n /**\n * Subtracts this CSG with another CSG in place\n * @param csg The CSG to subtract against this CSG\n */\n subtractInPlace(csg) {\n const a = new Node(this._polygons);\n const b = new Node(csg._polygons);\n a.invert();\n a.clipTo(b);\n b.clipTo(a);\n b.invert();\n b.clipTo(a);\n b.invert();\n a.build(b.allPolygons());\n a.invert();\n this._polygons = a.allPolygons();\n }\n /**\n * Intersect this CSG with another CSG\n * @param csg The CSG to intersect against this CSG\n * @returns A new CSG\n */\n intersect(csg) {\n const a = new Node(this.clone()._polygons);\n const b = new Node(csg.clone()._polygons);\n a.invert();\n b.clipTo(a);\n b.invert();\n a.clipTo(b);\n b.clipTo(a);\n a.build(b.allPolygons());\n a.invert();\n return CSG._FromPolygons(a.allPolygons()).copyTransformAttributes(this);\n }\n /**\n * Intersects this CSG with another CSG in place\n * @param csg The CSG to intersect against this CSG\n */\n intersectInPlace(csg) {\n const a = new Node(this._polygons);\n const b = new Node(csg._polygons);\n a.invert();\n b.clipTo(a);\n b.invert();\n a.clipTo(b);\n b.clipTo(a);\n a.build(b.allPolygons());\n a.invert();\n this._polygons = a.allPolygons();\n }\n /**\n * Return a new CSG solid with solid and empty space switched. This solid is\n * not modified.\n * @returns A new CSG solid with solid and empty space switched\n */\n inverse() {\n const csg = this.clone();\n csg.inverseInPlace();\n return csg;\n }\n /**\n * Inverses the CSG in place\n */\n inverseInPlace() {\n this._polygons.map((p) => {\n p.flip();\n });\n }\n /**\n * This is used to keep meshes transformations so they can be restored\n * when we build back a Babylon Mesh\n * NB : All CSG operations are performed in world coordinates\n * @param csg The CSG to copy the transform attributes from\n * @returns This CSG\n */\n copyTransformAttributes(csg) {\n this.matrix = csg.matrix;\n this.position = csg.position;\n this.rotation = csg.rotation;\n this.scaling = csg.scaling;\n this.rotationQuaternion = csg.rotationQuaternion;\n return this;\n }\n /**\n * Build Raw mesh from CSG\n * Coordinates here are in world space\n * @param name The name of the mesh geometry\n * @param scene The Scene\n * @param keepSubMeshes Specifies if the submeshes should be kept\n * @returns A new Mesh\n */\n buildMeshGeometry(name, scene, keepSubMeshes) {\n const matrix = this.matrix.clone();\n matrix.invert();\n const mesh = new Mesh(name, scene);\n const vertices = [];\n const indices = [];\n const normals = [];\n let uvs = null;\n let vertColors = null;\n const vertex = Vector3.Zero();\n const normal = Vector3.Zero();\n const uv = Vector2.Zero();\n const vertColor = new Color4(0, 0, 0, 0);\n const polygons = this._polygons;\n const polygonIndices = [0, 0, 0];\n let polygon;\n const vertice_dict = {};\n let vertex_idx;\n let currentIndex = 0;\n const subMeshDict = {};\n let subMeshObj;\n if (keepSubMeshes) {\n // Sort Polygons, since subMeshes are indices range\n polygons.sort((a, b) => {\n if (a.shared.meshId === b.shared.meshId) {\n return a.shared.subMeshId - b.shared.subMeshId;\n }\n else {\n return a.shared.meshId - b.shared.meshId;\n }\n });\n }\n for (let i = 0, il = polygons.length; i < il; i++) {\n polygon = polygons[i];\n // Building SubMeshes\n if (!subMeshDict[polygon.shared.meshId]) {\n subMeshDict[polygon.shared.meshId] = {};\n }\n if (!subMeshDict[polygon.shared.meshId][polygon.shared.subMeshId]) {\n subMeshDict[polygon.shared.meshId][polygon.shared.subMeshId] = {\n indexStart: +Infinity,\n indexEnd: -Infinity,\n materialIndex: polygon.shared.materialIndex,\n };\n }\n subMeshObj = subMeshDict[polygon.shared.meshId][polygon.shared.subMeshId];\n for (let j = 2, jl = polygon.vertices.length; j < jl; j++) {\n polygonIndices[0] = 0;\n polygonIndices[1] = j - 1;\n polygonIndices[2] = j;\n for (let k = 0; k < 3; k++) {\n vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);\n normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);\n if (polygon.vertices[polygonIndices[k]].uv) {\n if (!uvs) {\n uvs = [];\n }\n uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);\n }\n if (polygon.vertices[polygonIndices[k]].vertColor) {\n if (!vertColors) {\n vertColors = [];\n }\n vertColor.copyFrom(polygon.vertices[polygonIndices[k]].vertColor);\n }\n const localVertex = Vector3.TransformCoordinates(vertex, matrix);\n const localNormal = Vector3.TransformNormal(normal, matrix);\n vertex_idx = vertice_dict[localVertex.x + \",\" + localVertex.y + \",\" + localVertex.z];\n let areUvsDifferent = false;\n if (uvs && !(uvs[vertex_idx * 2] === uv.x || uvs[vertex_idx * 2 + 1] === uv.y)) {\n areUvsDifferent = true;\n }\n let areColorsDifferent = false;\n if (vertColors &&\n !(vertColors[vertex_idx * 4] === vertColor.r ||\n vertColors[vertex_idx * 4 + 1] === vertColor.g ||\n vertColors[vertex_idx * 4 + 2] === vertColor.b ||\n vertColors[vertex_idx * 4 + 3] === vertColor.a)) {\n areColorsDifferent = true;\n }\n // Check if 2 points can be merged\n if (!(typeof vertex_idx !== \"undefined\" &&\n normals[vertex_idx * 3] === localNormal.x &&\n normals[vertex_idx * 3 + 1] === localNormal.y &&\n normals[vertex_idx * 3 + 2] === localNormal.z) ||\n areUvsDifferent ||\n areColorsDifferent) {\n vertices.push(localVertex.x, localVertex.y, localVertex.z);\n if (uvs) {\n uvs.push(uv.x, uv.y);\n }\n normals.push(normal.x, normal.y, normal.z);\n if (vertColors) {\n vertColors.push(vertColor.r, vertColor.g, vertColor.b, vertColor.a);\n }\n vertex_idx = vertice_dict[localVertex.x + \",\" + localVertex.y + \",\" + localVertex.z] = vertices.length / 3 - 1;\n }\n indices.push(vertex_idx);\n subMeshObj.indexStart = Math.min(currentIndex, subMeshObj.indexStart);\n subMeshObj.indexEnd = Math.max(currentIndex, subMeshObj.indexEnd);\n currentIndex++;\n }\n }\n }\n mesh.setVerticesData(VertexBuffer.PositionKind, vertices);\n mesh.setVerticesData(VertexBuffer.NormalKind, normals);\n if (uvs) {\n mesh.setVerticesData(VertexBuffer.UVKind, uvs);\n }\n if (vertColors) {\n mesh.setVerticesData(VertexBuffer.ColorKind, vertColors);\n }\n mesh.setIndices(indices, null);\n if (keepSubMeshes) {\n // We offset the materialIndex by the previous number of materials in the CSG mixed meshes\n let materialIndexOffset = 0, materialMaxIndex;\n mesh.subMeshes = new Array();\n for (const m in subMeshDict) {\n materialMaxIndex = -1;\n for (const sm in subMeshDict[m]) {\n subMeshObj = subMeshDict[m][sm];\n SubMesh.CreateFromIndices(subMeshObj.materialIndex + materialIndexOffset, subMeshObj.indexStart, subMeshObj.indexEnd - subMeshObj.indexStart + 1, mesh);\n materialMaxIndex = Math.max(subMeshObj.materialIndex, materialMaxIndex);\n }\n materialIndexOffset += ++materialMaxIndex;\n }\n }\n return mesh;\n }\n /**\n * Build Mesh from CSG taking material and transforms into account\n * @param name The name of the Mesh\n * @param material The material of the Mesh\n * @param scene The Scene\n * @param keepSubMeshes Specifies if submeshes should be kept\n * @returns The new Mesh\n */\n toMesh(name, material = null, scene, keepSubMeshes) {\n const mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);\n mesh.material = material;\n mesh.position.copyFrom(this.position);\n mesh.rotation.copyFrom(this.rotation);\n if (this.rotationQuaternion) {\n mesh.rotationQuaternion = this.rotationQuaternion.clone();\n }\n mesh.scaling.copyFrom(this.scaling);\n mesh.computeWorldMatrix(true);\n return mesh;\n }\n}\n//# sourceMappingURL=csg.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/bonesDeclaration.js\";\nimport \"./ShadersInclude/bakedVertexAnimationDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexGlobalDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexDeclaration.js\";\nimport \"./ShadersInclude/instancesDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexGlobal.js\";\nimport \"./ShadersInclude/morphTargetsVertex.js\";\nimport \"./ShadersInclude/instancesVertex.js\";\nimport \"./ShadersInclude/bonesVertex.js\";\nimport \"./ShadersInclude/bakedVertexAnimation.js\";\nconst name = \"meshUVSpaceRendererVertexShader\";\nconst shader = `precision highp float;\rattribute vec3 position;\rattribute vec3 normal;\rattribute vec2 uv;\runiform mat4 projMatrix;\rvarying vec2 vDecalTC;\r#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nvoid main(void) {\rvec3 positionUpdated=position;\rvec3 normalUpdated=normal;\r#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\rmat3 normWorldSM=mat3(finalWorld);\rvec3 vNormalW;\r#if defined(INSTANCES) && defined(THIN_INSTANCES)\nvNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));\rvNormalW=normalize(normWorldSM*vNormalW);\r#else\n#ifdef NONUNIFORMSCALING\nnormWorldSM=transposeMat3(inverseMat3(normWorldSM));\r#endif\nvNormalW=normalize(normWorldSM*normalUpdated);\r#endif\nvec3 normalView=normalize((projMatrix*vec4(vNormalW,0.0)).xyz);\rvec3 decalTC=(projMatrix*worldPos).xyz;\rvDecalTC=decalTC.xy;\rgl_Position=vec4(uv*2.0-1.0,normalView.z>0.0 ? 2. : decalTC.z,1.0);\r}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const meshUVSpaceRendererVertexShader = { name, shader };\n//# sourceMappingURL=meshUVSpaceRenderer.vertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"meshUVSpaceRendererPixelShader\";\nconst shader = `precision highp float;\rvarying vec2 vDecalTC;\runiform sampler2D textureSampler;\rvoid main(void) {\rif (vDecalTC.x<0. || vDecalTC.x>1. || vDecalTC.y<0. || vDecalTC.y>1.) {\rdiscard;\r}\rgl_FragColor=texture2D(textureSampler,vDecalTC);\r}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const meshUVSpaceRendererPixelShader = { name, shader };\n//# sourceMappingURL=meshUVSpaceRenderer.fragment.js.map","import { Matrix } from \"../Maths/math.vector.js\";\n\nimport { ShaderMaterial } from \"../Materials/shaderMaterial.js\";\nimport { RenderTargetTexture } from \"../Materials/Textures/renderTargetTexture.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport \"../Shaders/meshUVSpaceRenderer.vertex.js\";\nimport \"../Shaders/meshUVSpaceRenderer.fragment.js\";\n/**\n * Class used to render in the mesh UV space\n * @since 5.49.1\n */\nexport class MeshUVSpaceRenderer {\n static _GetShader(scene) {\n if (!scene._meshUVSpaceRendererShader) {\n const shader = new ShaderMaterial(\"meshUVSpaceRendererShader\", scene, {\n vertex: \"meshUVSpaceRenderer\",\n fragment: \"meshUVSpaceRenderer\",\n }, {\n attributes: [\"position\", \"normal\", \"uv\"],\n uniforms: [\"world\", \"projMatrix\"],\n samplers: [\"textureSampler\"],\n needAlphaBlending: true,\n });\n shader.backFaceCulling = false;\n shader.alphaMode = 2;\n scene.onDisposeObservable.add(() => {\n var _a;\n (_a = scene._meshUVSpaceRendererShader) === null || _a === void 0 ? void 0 : _a.dispose();\n scene._meshUVSpaceRendererShader = null;\n });\n scene._meshUVSpaceRendererShader = shader;\n }\n return scene._meshUVSpaceRendererShader;\n }\n static _IsRenderTargetTexture(texture) {\n return texture.renderList !== undefined;\n }\n /**\n * Creates a new MeshUVSpaceRenderer\n * @param mesh The mesh used for the source UV space\n * @param scene The scene the mesh belongs to\n * @param options The options to use when creating the texture\n */\n constructor(mesh, scene, options) {\n this._textureCreatedInternally = false;\n /**\n * Clear color of the texture\n */\n this.clearColor = new Color4(0, 0, 0, 0);\n this._mesh = mesh;\n this._scene = scene;\n this._options = Object.assign({ width: 1024, height: 1024, textureType: 0, generateMipMaps: true, optimizeUVAllocation: true }, options);\n }\n /**\n * Checks if the texture is ready to be used\n * @returns true if the texture is ready to be used\n */\n isReady() {\n if (!this.texture) {\n this._createDiffuseRTT();\n }\n return MeshUVSpaceRenderer._IsRenderTargetTexture(this.texture) ? this.texture.isReadyForRendering() : this.texture.isReady();\n }\n /**\n * Projects and renders a texture in the mesh UV space\n * @param texture The texture\n * @param position The position of the center of projection (world space coordinates)\n * @param normal The direction of the projection (world space coordinates)\n * @param size The size of the projection\n * @param angle The rotation angle around the direction of the projection\n */\n renderTexture(texture, position, normal, size, angle = 0) {\n if (!this.texture) {\n this._createDiffuseRTT();\n }\n if (MeshUVSpaceRenderer._IsRenderTargetTexture(this.texture)) {\n const matrix = this._createProjectionMatrix(position, normal, size, angle);\n const shader = MeshUVSpaceRenderer._GetShader(this._scene);\n shader.setTexture(\"textureSampler\", texture);\n shader.setMatrix(\"projMatrix\", matrix);\n this.texture.render();\n }\n }\n /**\n * Clears the texture map\n */\n clear() {\n if (MeshUVSpaceRenderer._IsRenderTargetTexture(this.texture) && this.texture.renderTarget) {\n const engine = this._scene.getEngine();\n engine.bindFramebuffer(this.texture.renderTarget);\n engine.clear(this.clearColor, true, true, true);\n engine.unBindFramebuffer(this.texture.renderTarget);\n }\n }\n /**\n * Disposes of the ressources\n */\n dispose() {\n if (this._textureCreatedInternally) {\n this.texture.dispose();\n this._textureCreatedInternally = false;\n }\n }\n _createDiffuseRTT() {\n this._textureCreatedInternally = true;\n const texture = this._createRenderTargetTexture(this._options.width, this._options.height);\n texture.setMaterialForRendering(this._mesh, MeshUVSpaceRenderer._GetShader(this._scene));\n this.texture = texture;\n }\n _createRenderTargetTexture(width, height) {\n const rtt = new RenderTargetTexture(this._mesh.name + \"_uvspaceTexture\", { width, height }, this._scene, this._options.generateMipMaps, true, this._options.textureType, false, this._options.generateMipMaps ? 3 : 2, false, false, false, 5);\n rtt.optimizeUVAllocation = !!this._options.optimizeUVAllocation;\n rtt.onClearObservable.addOnce(() => {\n this._scene.getEngine().clear(this.clearColor, true, true, true);\n rtt.onClearObservable.add(() => { }); // this disables clearing the texture for the next frames\n });\n rtt.renderList = [this._mesh];\n return rtt;\n }\n _createProjectionMatrix(position, normal, size, angle = 0) {\n const yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;\n const len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);\n const pitch = Math.atan2(normal.y, len);\n const p = position.add(normal.scale(size.z * 0.5));\n const projWorldMatrix = Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(Matrix.Translation(p.x, p.y, p.z));\n const inverseProjWorldMatrix = Matrix.Invert(projWorldMatrix);\n const projMatrix = Matrix.FromArray([2 / size.x, 0, 0, 0, 0, 2 / size.y, 0, 0, 0, 0, 1 / size.z, 0, 0, 0, 0, 1]);\n const screenMatrix = Matrix.FromArray([0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 1, 0, 0.5, 0.5, 0.0, 1]);\n return inverseProjWorldMatrix.multiply(projMatrix).multiply(screenMatrix);\n }\n}\n//# sourceMappingURL=meshUVSpaceRenderer.js.map","import { AbstractMesh } from \"../Meshes/abstractMesh.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { VertexData } from \"../Meshes/mesh.vertexData.js\";\n/**\n * Class used to create a trail following a mesh\n */\nexport class TrailMesh extends Mesh {\n /**\n * Creates a new TrailMesh.\n * @param name The value used by scene.getMeshByName() to do a lookup.\n * @param generator The mesh or transform node to generate a trail.\n * @param scene The scene to add this mesh to.\n * @param diameter Diameter of trailing mesh. Default is 1.\n * @param length Length of trailing mesh. Default is 60.\n * @param autoStart Automatically start trailing mesh. Default true.\n */\n constructor(name, generator, scene, diameter = 1, length = 60, autoStart = true) {\n super(name, scene);\n this._sectionPolygonPointsCount = 4;\n this._running = false;\n this._autoStart = autoStart;\n this._generator = generator;\n this.diameter = diameter;\n this._length = length;\n this._sectionVectors = [];\n this._sectionNormalVectors = [];\n for (let i = 0; i < this._sectionPolygonPointsCount; i++) {\n this._sectionVectors[i] = Vector3.Zero();\n this._sectionNormalVectors[i] = Vector3.Zero();\n }\n this._createMesh();\n }\n /**\n * \"TrailMesh\"\n * @returns \"TrailMesh\"\n */\n getClassName() {\n return \"TrailMesh\";\n }\n _createMesh() {\n const data = new VertexData();\n const positions = [];\n const normals = [];\n const indices = [];\n let meshCenter = Vector3.Zero();\n if (this._generator instanceof AbstractMesh && this._generator.hasBoundingInfo) {\n meshCenter = this._generator.getBoundingInfo().boundingBox.centerWorld;\n }\n else {\n meshCenter = this._generator.position;\n }\n const alpha = (2 * Math.PI) / this._sectionPolygonPointsCount;\n for (let i = 0; i < this._sectionPolygonPointsCount; i++) {\n positions.push(meshCenter.x + Math.cos(i * alpha) * this.diameter, meshCenter.y + Math.sin(i * alpha) * this.diameter, meshCenter.z);\n }\n for (let i = 1; i <= this._length; i++) {\n for (let j = 0; j < this._sectionPolygonPointsCount; j++) {\n positions.push(meshCenter.x + Math.cos(j * alpha) * this.diameter, meshCenter.y + Math.sin(j * alpha) * this.diameter, meshCenter.z);\n }\n const l = positions.length / 3 - 2 * this._sectionPolygonPointsCount;\n for (let j = 0; j < this._sectionPolygonPointsCount - 1; j++) {\n indices.push(l + j, l + j + this._sectionPolygonPointsCount, l + j + this._sectionPolygonPointsCount + 1);\n indices.push(l + j, l + j + this._sectionPolygonPointsCount + 1, l + j + 1);\n }\n indices.push(l + this._sectionPolygonPointsCount - 1, l + this._sectionPolygonPointsCount - 1 + this._sectionPolygonPointsCount, l + this._sectionPolygonPointsCount);\n indices.push(l + this._sectionPolygonPointsCount - 1, l + this._sectionPolygonPointsCount, l);\n }\n VertexData.ComputeNormals(positions, indices, normals);\n data.positions = positions;\n data.normals = normals;\n data.indices = indices;\n data.applyToMesh(this, true);\n if (this._autoStart) {\n this.start();\n }\n }\n /**\n * Start trailing mesh.\n */\n start() {\n if (!this._running) {\n this._running = true;\n this._beforeRenderObserver = this.getScene().onBeforeRenderObservable.add(() => {\n this.update();\n });\n }\n }\n /**\n * Stop trailing mesh.\n */\n stop() {\n if (this._beforeRenderObserver && this._running) {\n this._running = false;\n this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver);\n }\n }\n /**\n * Update trailing mesh geometry.\n */\n update() {\n const positions = this.getVerticesData(VertexBuffer.PositionKind);\n const normals = this.getVerticesData(VertexBuffer.NormalKind);\n const wm = this._generator.getWorldMatrix();\n if (positions && normals) {\n for (let i = 3 * this._sectionPolygonPointsCount; i < positions.length; i++) {\n positions[i - 3 * this._sectionPolygonPointsCount] = positions[i] - (normals[i] / this._length) * this.diameter;\n }\n for (let i = 3 * this._sectionPolygonPointsCount; i < normals.length; i++) {\n normals[i - 3 * this._sectionPolygonPointsCount] = normals[i];\n }\n const l = positions.length - 3 * this._sectionPolygonPointsCount;\n const alpha = (2 * Math.PI) / this._sectionPolygonPointsCount;\n for (let i = 0; i < this._sectionPolygonPointsCount; i++) {\n this._sectionVectors[i].copyFromFloats(Math.cos(i * alpha) * this.diameter, Math.sin(i * alpha) * this.diameter, 0);\n this._sectionNormalVectors[i].copyFromFloats(Math.cos(i * alpha), Math.sin(i * alpha), 0);\n Vector3.TransformCoordinatesToRef(this._sectionVectors[i], wm, this._sectionVectors[i]);\n Vector3.TransformNormalToRef(this._sectionNormalVectors[i], wm, this._sectionNormalVectors[i]);\n }\n for (let i = 0; i < this._sectionPolygonPointsCount; i++) {\n positions[l + 3 * i] = this._sectionVectors[i].x;\n positions[l + 3 * i + 1] = this._sectionVectors[i].y;\n positions[l + 3 * i + 2] = this._sectionVectors[i].z;\n normals[l + 3 * i] = this._sectionNormalVectors[i].x;\n normals[l + 3 * i + 1] = this._sectionNormalVectors[i].y;\n normals[l + 3 * i + 2] = this._sectionNormalVectors[i].z;\n }\n this.updateVerticesData(VertexBuffer.PositionKind, positions, true, false);\n this.updateVerticesData(VertexBuffer.NormalKind, normals, true, false);\n }\n }\n /**\n * Returns a new TrailMesh object.\n * @param name is a string, the name given to the new mesh\n * @param newGenerator use new generator object for cloned trail mesh\n * @returns a new mesh\n */\n clone(name = \"\", newGenerator) {\n return new TrailMesh(name, newGenerator === undefined ? this._generator : newGenerator, this.getScene(), this.diameter, this._length, this._autoStart);\n }\n /**\n * Serializes this trail mesh\n * @param serializationObject object to write serialization to\n */\n serialize(serializationObject) {\n super.serialize(serializationObject);\n }\n /**\n * Parses a serialized trail mesh\n * @param parsedMesh the serialized mesh\n * @param scene the scene to create the trail mesh in\n * @returns the created trail mesh\n */\n static Parse(parsedMesh, scene) {\n var _a;\n return new TrailMesh(parsedMesh.name, parsedMesh._generator, scene, (_a = parsedMesh.diameter) !== null && _a !== void 0 ? _a : parsedMesh._diameter, parsedMesh._length, parsedMesh._autoStart);\n }\n}\n//# sourceMappingURL=trailMesh.js.map","import { Vector3 } from \"../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { SubMesh } from \"../Meshes/subMesh.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { AsyncLoop } from \"../Misc/tools.js\";\nimport { Epsilon } from \"../Maths/math.constants.js\";\n/**\n * Class used to specify simplification options\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/simplifyingMeshes\n */\nexport class SimplificationSettings {\n /**\n * Creates a SimplificationSettings\n * @param quality expected quality\n * @param distance distance when this optimized version should be used\n * @param optimizeMesh already optimized mesh\n */\n constructor(\n /** expected quality */\n quality, \n /** distance when this optimized version should be used */\n distance, \n /** already optimized mesh */\n optimizeMesh) {\n this.quality = quality;\n this.distance = distance;\n this.optimizeMesh = optimizeMesh;\n }\n}\n/**\n * Queue used to order the simplification tasks\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/simplifyingMeshes\n */\nexport class SimplificationQueue {\n /**\n * Creates a new queue\n */\n constructor() {\n this.running = false;\n this._simplificationArray = [];\n }\n /**\n * Adds a new simplification task\n * @param task defines a task to add\n */\n addTask(task) {\n this._simplificationArray.push(task);\n }\n /**\n * Execute next task\n */\n executeNext() {\n const task = this._simplificationArray.pop();\n if (task) {\n this.running = true;\n this.runSimplification(task);\n }\n else {\n this.running = false;\n }\n }\n /**\n * Execute a simplification task\n * @param task defines the task to run\n */\n runSimplification(task) {\n if (task.parallelProcessing) {\n //parallel simplifier\n task.settings.forEach((setting) => {\n const simplifier = this._getSimplifier(task);\n simplifier.simplify(setting, (newMesh) => {\n if (setting.distance !== undefined) {\n task.mesh.addLODLevel(setting.distance, newMesh);\n }\n newMesh.isVisible = true;\n //check if it is the last\n if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {\n //all done, run the success callback.\n task.successCallback();\n }\n this.executeNext();\n });\n });\n }\n else {\n //single simplifier.\n const simplifier = this._getSimplifier(task);\n const runDecimation = (setting, callback) => {\n simplifier.simplify(setting, (newMesh) => {\n if (setting.distance !== undefined) {\n task.mesh.addLODLevel(setting.distance, newMesh);\n }\n newMesh.isVisible = true;\n //run the next quality level\n callback();\n });\n };\n AsyncLoop.Run(task.settings.length, (loop) => {\n runDecimation(task.settings[loop.index], () => {\n loop.executeNext();\n });\n }, () => {\n //execution ended, run the success callback.\n if (task.successCallback) {\n task.successCallback();\n }\n this.executeNext();\n });\n }\n }\n _getSimplifier(task) {\n switch (task.simplificationType) {\n case SimplificationType.QUADRATIC:\n default:\n return new QuadraticErrorSimplification(task.mesh);\n }\n }\n}\n/**\n * The implemented types of simplification\n * At the moment only Quadratic Error Decimation is implemented\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/simplifyingMeshes\n */\nexport var SimplificationType;\n(function (SimplificationType) {\n /** Quadratic error decimation */\n SimplificationType[SimplificationType[\"QUADRATIC\"] = 0] = \"QUADRATIC\";\n})(SimplificationType || (SimplificationType = {}));\nclass DecimationTriangle {\n constructor(_vertices) {\n this._vertices = _vertices;\n this.error = new Array(4);\n this.deleted = false;\n this.isDirty = false;\n this.deletePending = false;\n this.borderFactor = 0;\n }\n}\nclass DecimationVertex {\n constructor(position, id) {\n this.position = position;\n this.id = id;\n this.isBorder = true;\n this.q = new QuadraticMatrix();\n this.triangleCount = 0;\n this.triangleStart = 0;\n this.originalOffsets = [];\n }\n updatePosition(newPosition) {\n this.position.copyFrom(newPosition);\n }\n}\nclass QuadraticMatrix {\n constructor(data) {\n this.data = new Array(10);\n for (let i = 0; i < 10; ++i) {\n if (data && data[i]) {\n this.data[i] = data[i];\n }\n else {\n this.data[i] = 0;\n }\n }\n }\n det(a11, a12, a13, a21, a22, a23, a31, a32, a33) {\n const det = this.data[a11] * this.data[a22] * this.data[a33] +\n this.data[a13] * this.data[a21] * this.data[a32] +\n this.data[a12] * this.data[a23] * this.data[a31] -\n this.data[a13] * this.data[a22] * this.data[a31] -\n this.data[a11] * this.data[a23] * this.data[a32] -\n this.data[a12] * this.data[a21] * this.data[a33];\n return det;\n }\n addInPlace(matrix) {\n for (let i = 0; i < 10; ++i) {\n this.data[i] += matrix.data[i];\n }\n }\n addArrayInPlace(data) {\n for (let i = 0; i < 10; ++i) {\n this.data[i] += data[i];\n }\n }\n add(matrix) {\n const m = new QuadraticMatrix();\n for (let i = 0; i < 10; ++i) {\n m.data[i] = this.data[i] + matrix.data[i];\n }\n return m;\n }\n static FromData(a, b, c, d) {\n return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));\n }\n //returning an array to avoid garbage collection\n static DataFromNumbers(a, b, c, d) {\n return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];\n }\n}\nclass Reference {\n constructor(vertexId, triangleId) {\n this.vertexId = vertexId;\n this.triangleId = triangleId;\n }\n}\n/**\n * An implementation of the Quadratic Error simplification algorithm.\n * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf\n * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS\n * @author RaananW\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/simplifyingMeshes\n */\nexport class QuadraticErrorSimplification {\n /**\n * Creates a new QuadraticErrorSimplification\n * @param _mesh defines the target mesh\n */\n constructor(_mesh) {\n this._mesh = _mesh;\n /** Gets or sets the number pf sync iterations */\n this.syncIterations = 5000;\n this.aggressiveness = 7;\n this.decimationIterations = 100;\n this.boundingBoxEpsilon = Epsilon;\n }\n /**\n * Simplification of a given mesh according to the given settings.\n * Since this requires computation, it is assumed that the function runs async.\n * @param settings The settings of the simplification, including quality and distance\n * @param successCallback A callback that will be called after the mesh was simplified.\n */\n simplify(settings, successCallback) {\n this._initDecimatedMesh();\n //iterating through the submeshes array, one after the other.\n AsyncLoop.Run(this._mesh.subMeshes.length, (loop) => {\n this._initWithMesh(loop.index, () => {\n this._runDecimation(settings, loop.index, () => {\n loop.executeNext();\n });\n }, settings.optimizeMesh);\n }, () => {\n setTimeout(() => {\n successCallback(this._reconstructedMesh);\n }, 0);\n });\n }\n _runDecimation(settings, submeshIndex, successCallback) {\n const targetCount = ~~(this._triangles.length * settings.quality);\n let deletedTriangles = 0;\n const triangleCount = this._triangles.length;\n const iterationFunction = (iteration, callback) => {\n setTimeout(() => {\n if (iteration % 5 === 0) {\n this._updateMesh(iteration === 0);\n }\n for (let i = 0; i < this._triangles.length; ++i) {\n this._triangles[i].isDirty = false;\n }\n const threshold = 0.000000001 * Math.pow(iteration + 3, this.aggressiveness);\n const trianglesIterator = (i) => {\n const tIdx = ~~((this._triangles.length / 2 + i) % this._triangles.length);\n const t = this._triangles[tIdx];\n if (!t) {\n return;\n }\n if (t.error[3] > threshold || t.deleted || t.isDirty) {\n return;\n }\n for (let j = 0; j < 3; ++j) {\n if (t.error[j] < threshold) {\n const deleted0 = [];\n const deleted1 = [];\n const v0 = t._vertices[j];\n const v1 = t._vertices[(j + 1) % 3];\n if (v0.isBorder || v1.isBorder) {\n continue;\n }\n const p = Vector3.Zero();\n // var n = Vector3.Zero();\n // var uv = Vector2.Zero();\n // var color = new Color4(0, 0, 0, 1);\n this._calculateError(v0, v1, p);\n const delTr = new Array();\n if (this._isFlipped(v0, v1, p, deleted0, delTr)) {\n continue;\n }\n if (this._isFlipped(v1, v0, p, deleted1, delTr)) {\n continue;\n }\n if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0) {\n continue;\n }\n const uniqueArray = new Array();\n delTr.forEach((deletedT) => {\n if (uniqueArray.indexOf(deletedT) === -1) {\n deletedT.deletePending = true;\n uniqueArray.push(deletedT);\n }\n });\n if (uniqueArray.length % 2 !== 0) {\n continue;\n }\n v0.q = v1.q.add(v0.q);\n v0.updatePosition(p);\n const tStart = this._references.length;\n deletedTriangles = this._updateTriangles(v0, v0, deleted0, deletedTriangles);\n deletedTriangles = this._updateTriangles(v0, v1, deleted1, deletedTriangles);\n const tCount = this._references.length - tStart;\n if (tCount <= v0.triangleCount) {\n if (tCount) {\n for (let c = 0; c < tCount; c++) {\n this._references[v0.triangleStart + c] = this._references[tStart + c];\n }\n }\n }\n else {\n v0.triangleStart = tStart;\n }\n v0.triangleCount = tCount;\n break;\n }\n }\n };\n AsyncLoop.SyncAsyncForLoop(this._triangles.length, this.syncIterations, trianglesIterator, callback, () => {\n return triangleCount - deletedTriangles <= targetCount;\n });\n }, 0);\n };\n AsyncLoop.Run(this.decimationIterations, (loop) => {\n if (triangleCount - deletedTriangles <= targetCount) {\n loop.breakLoop();\n }\n else {\n iterationFunction(loop.index, () => {\n loop.executeNext();\n });\n }\n }, () => {\n setTimeout(() => {\n //reconstruct this part of the mesh\n this._reconstructMesh(submeshIndex);\n successCallback();\n }, 0);\n });\n }\n _initWithMesh(submeshIndex, callback, optimizeMesh) {\n this._vertices = [];\n this._triangles = [];\n const positionData = this._mesh.getVerticesData(VertexBuffer.PositionKind);\n const indices = this._mesh.getIndices();\n const submesh = this._mesh.subMeshes[submeshIndex];\n const findInVertices = (positionToSearch) => {\n if (optimizeMesh) {\n for (let ii = 0; ii < this._vertices.length; ++ii) {\n if (this._vertices[ii].position.equalsWithEpsilon(positionToSearch, 0.0001)) {\n return this._vertices[ii];\n }\n }\n }\n return null;\n };\n const vertexReferences = [];\n const vertexInit = (i) => {\n if (!positionData) {\n return;\n }\n const offset = i + submesh.verticesStart;\n const position = Vector3.FromArray(positionData, offset * 3);\n const vertex = findInVertices(position) || new DecimationVertex(position, this._vertices.length);\n vertex.originalOffsets.push(offset);\n if (vertex.id === this._vertices.length) {\n this._vertices.push(vertex);\n }\n vertexReferences.push(vertex.id);\n };\n //var totalVertices = mesh.getTotalVertices();\n const totalVertices = submesh.verticesCount;\n AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, () => {\n const indicesInit = (i) => {\n if (!indices) {\n return;\n }\n const offset = submesh.indexStart / 3 + i;\n const pos = offset * 3;\n const i0 = indices[pos + 0];\n const i1 = indices[pos + 1];\n const i2 = indices[pos + 2];\n const v0 = this._vertices[vertexReferences[i0 - submesh.verticesStart]];\n const v1 = this._vertices[vertexReferences[i1 - submesh.verticesStart]];\n const v2 = this._vertices[vertexReferences[i2 - submesh.verticesStart]];\n const triangle = new DecimationTriangle([v0, v1, v2]);\n triangle.originalOffset = pos;\n this._triangles.push(triangle);\n };\n AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, this.syncIterations, indicesInit, () => {\n this._init(callback);\n });\n });\n }\n _init(callback) {\n const triangleInit1 = (i) => {\n const t = this._triangles[i];\n t.normal = Vector3.Cross(t._vertices[1].position.subtract(t._vertices[0].position), t._vertices[2].position.subtract(t._vertices[0].position)).normalize();\n for (let j = 0; j < 3; j++) {\n t._vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -Vector3.Dot(t.normal, t._vertices[0].position)));\n }\n };\n AsyncLoop.SyncAsyncForLoop(this._triangles.length, this.syncIterations, triangleInit1, () => {\n const triangleInit2 = (i) => {\n const t = this._triangles[i];\n for (let j = 0; j < 3; ++j) {\n t.error[j] = this._calculateError(t._vertices[j], t._vertices[(j + 1) % 3]);\n }\n t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);\n };\n AsyncLoop.SyncAsyncForLoop(this._triangles.length, this.syncIterations, triangleInit2, () => {\n callback();\n });\n });\n }\n _reconstructMesh(submeshIndex) {\n const newTriangles = [];\n let i;\n for (i = 0; i < this._vertices.length; ++i) {\n this._vertices[i].triangleCount = 0;\n }\n let t;\n let j;\n for (i = 0; i < this._triangles.length; ++i) {\n if (!this._triangles[i].deleted) {\n t = this._triangles[i];\n for (j = 0; j < 3; ++j) {\n t._vertices[j].triangleCount = 1;\n }\n newTriangles.push(t);\n }\n }\n const newPositionData = (this._reconstructedMesh.getVerticesData(VertexBuffer.PositionKind) || []);\n const newNormalData = (this._reconstructedMesh.getVerticesData(VertexBuffer.NormalKind) || []);\n const newUVsData = (this._reconstructedMesh.getVerticesData(VertexBuffer.UVKind) || []);\n const newColorsData = (this._reconstructedMesh.getVerticesData(VertexBuffer.ColorKind) || []);\n const normalData = this._mesh.getVerticesData(VertexBuffer.NormalKind);\n const uvs = this._mesh.getVerticesData(VertexBuffer.UVKind);\n const colorsData = this._mesh.getVerticesData(VertexBuffer.ColorKind);\n let vertexCount = 0;\n for (i = 0; i < this._vertices.length; ++i) {\n const vertex = this._vertices[i];\n vertex.id = vertexCount;\n if (vertex.triangleCount) {\n vertex.originalOffsets.forEach((originalOffset) => {\n newPositionData.push(vertex.position.x);\n newPositionData.push(vertex.position.y);\n newPositionData.push(vertex.position.z);\n if (normalData && normalData.length) {\n newNormalData.push(normalData[originalOffset * 3]);\n newNormalData.push(normalData[originalOffset * 3 + 1]);\n newNormalData.push(normalData[originalOffset * 3 + 2]);\n }\n if (uvs && uvs.length) {\n newUVsData.push(uvs[originalOffset * 2]);\n newUVsData.push(uvs[originalOffset * 2 + 1]);\n }\n if (colorsData && colorsData.length) {\n newColorsData.push(colorsData[originalOffset * 4]);\n newColorsData.push(colorsData[originalOffset * 4 + 1]);\n newColorsData.push(colorsData[originalOffset * 4 + 2]);\n newColorsData.push(colorsData[originalOffset * 4 + 3]);\n }\n ++vertexCount;\n });\n }\n }\n const startingIndex = this._reconstructedMesh.getTotalIndices();\n const startingVertex = this._reconstructedMesh.getTotalVertices();\n const submeshesArray = this._reconstructedMesh.subMeshes;\n this._reconstructedMesh.subMeshes = [];\n const newIndicesArray = this._reconstructedMesh.getIndices(); //[];\n const originalIndices = this._mesh.getIndices();\n for (i = 0; i < newTriangles.length; ++i) {\n t = newTriangles[i]; //now get the new referencing point for each vertex\n [0, 1, 2].forEach((idx) => {\n const id = originalIndices[t.originalOffset + idx];\n let offset = t._vertices[idx].originalOffsets.indexOf(id);\n if (offset < 0) {\n offset = 0;\n }\n newIndicesArray.push(t._vertices[idx].id + offset + startingVertex);\n });\n }\n //overwriting the old vertex buffers and indices.\n this._reconstructedMesh.setIndices(newIndicesArray);\n this._reconstructedMesh.setVerticesData(VertexBuffer.PositionKind, newPositionData);\n if (newNormalData.length > 0) {\n this._reconstructedMesh.setVerticesData(VertexBuffer.NormalKind, newNormalData);\n }\n if (newUVsData.length > 0) {\n this._reconstructedMesh.setVerticesData(VertexBuffer.UVKind, newUVsData);\n }\n if (newColorsData.length > 0) {\n this._reconstructedMesh.setVerticesData(VertexBuffer.ColorKind, newColorsData);\n }\n //create submesh\n const originalSubmesh = this._mesh.subMeshes[submeshIndex];\n if (submeshIndex > 0) {\n this._reconstructedMesh.subMeshes = [];\n submeshesArray.forEach((submesh) => {\n SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, \n /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());\n });\n SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, \n /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);\n }\n }\n _initDecimatedMesh() {\n this._reconstructedMesh = new Mesh(this._mesh.name + \"Decimated\", this._mesh.getScene());\n this._reconstructedMesh.material = this._mesh.material;\n this._reconstructedMesh.parent = this._mesh.parent;\n this._reconstructedMesh.isVisible = false;\n this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;\n }\n _isFlipped(vertex1, vertex2, point, deletedArray, delTr) {\n for (let i = 0; i < vertex1.triangleCount; ++i) {\n const t = this._triangles[this._references[vertex1.triangleStart + i].triangleId];\n if (t.deleted) {\n continue;\n }\n const s = this._references[vertex1.triangleStart + i].vertexId;\n const v1 = t._vertices[(s + 1) % 3];\n const v2 = t._vertices[(s + 2) % 3];\n if (v1 === vertex2 || v2 === vertex2) {\n deletedArray[i] = true;\n delTr.push(t);\n continue;\n }\n let d1 = v1.position.subtract(point);\n d1 = d1.normalize();\n let d2 = v2.position.subtract(point);\n d2 = d2.normalize();\n if (Math.abs(Vector3.Dot(d1, d2)) > 0.999) {\n return true;\n }\n const normal = Vector3.Cross(d1, d2).normalize();\n deletedArray[i] = false;\n if (Vector3.Dot(normal, t.normal) < 0.2) {\n return true;\n }\n }\n return false;\n }\n _updateTriangles(origVertex, vertex, deletedArray, deletedTriangles) {\n let newDeleted = deletedTriangles;\n for (let i = 0; i < vertex.triangleCount; ++i) {\n const ref = this._references[vertex.triangleStart + i];\n const t = this._triangles[ref.triangleId];\n if (t.deleted) {\n continue;\n }\n if (deletedArray[i] && t.deletePending) {\n t.deleted = true;\n newDeleted++;\n continue;\n }\n t._vertices[ref.vertexId] = origVertex;\n t.isDirty = true;\n t.error[0] = this._calculateError(t._vertices[0], t._vertices[1]) + t.borderFactor / 2;\n t.error[1] = this._calculateError(t._vertices[1], t._vertices[2]) + t.borderFactor / 2;\n t.error[2] = this._calculateError(t._vertices[2], t._vertices[0]) + t.borderFactor / 2;\n t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);\n this._references.push(ref);\n }\n return newDeleted;\n }\n _identifyBorder() {\n for (let i = 0; i < this._vertices.length; ++i) {\n const vCount = [];\n const vId = [];\n const v = this._vertices[i];\n let j;\n for (j = 0; j < v.triangleCount; ++j) {\n const triangle = this._triangles[this._references[v.triangleStart + j].triangleId];\n for (let ii = 0; ii < 3; ii++) {\n let ofs = 0;\n const vv = triangle._vertices[ii];\n while (ofs < vCount.length) {\n if (vId[ofs] === vv.id) {\n break;\n }\n ++ofs;\n }\n if (ofs === vCount.length) {\n vCount.push(1);\n vId.push(vv.id);\n }\n else {\n vCount[ofs]++;\n }\n }\n }\n for (j = 0; j < vCount.length; ++j) {\n if (vCount[j] === 1) {\n this._vertices[vId[j]].isBorder = true;\n }\n else {\n this._vertices[vId[j]].isBorder = false;\n }\n }\n }\n }\n _updateMesh(identifyBorders = false) {\n let i;\n if (!identifyBorders) {\n const newTrianglesVector = [];\n for (i = 0; i < this._triangles.length; ++i) {\n if (!this._triangles[i].deleted) {\n newTrianglesVector.push(this._triangles[i]);\n }\n }\n this._triangles = newTrianglesVector;\n }\n for (i = 0; i < this._vertices.length; ++i) {\n this._vertices[i].triangleCount = 0;\n this._vertices[i].triangleStart = 0;\n }\n let t;\n let j;\n let v;\n for (i = 0; i < this._triangles.length; ++i) {\n t = this._triangles[i];\n for (j = 0; j < 3; ++j) {\n v = t._vertices[j];\n v.triangleCount++;\n }\n }\n let tStart = 0;\n for (i = 0; i < this._vertices.length; ++i) {\n this._vertices[i].triangleStart = tStart;\n tStart += this._vertices[i].triangleCount;\n this._vertices[i].triangleCount = 0;\n }\n const newReferences = new Array(this._triangles.length * 3);\n for (i = 0; i < this._triangles.length; ++i) {\n t = this._triangles[i];\n for (j = 0; j < 3; ++j) {\n v = t._vertices[j];\n newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);\n v.triangleCount++;\n }\n }\n this._references = newReferences;\n if (identifyBorders) {\n this._identifyBorder();\n }\n }\n _vertexError(q, point) {\n const x = point.x;\n const y = point.y;\n const z = point.z;\n return (q.data[0] * x * x +\n 2 * q.data[1] * x * y +\n 2 * q.data[2] * x * z +\n 2 * q.data[3] * x +\n q.data[4] * y * y +\n 2 * q.data[5] * y * z +\n 2 * q.data[6] * y +\n q.data[7] * z * z +\n 2 * q.data[8] * z +\n q.data[9]);\n }\n _calculateError(vertex1, vertex2, pointResult) {\n const q = vertex1.q.add(vertex2.q);\n const border = vertex1.isBorder && vertex2.isBorder;\n let error = 0;\n const qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);\n if (qDet !== 0 && !border) {\n if (!pointResult) {\n pointResult = Vector3.Zero();\n }\n pointResult.x = (-1 / qDet) * q.det(1, 2, 3, 4, 5, 6, 5, 7, 8);\n pointResult.y = (1 / qDet) * q.det(0, 2, 3, 1, 5, 6, 2, 7, 8);\n pointResult.z = (-1 / qDet) * q.det(0, 1, 3, 1, 4, 6, 2, 5, 8);\n error = this._vertexError(q, pointResult);\n }\n else {\n const p3 = vertex1.position.add(vertex2.position).divide(new Vector3(2, 2, 2));\n //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();\n const error1 = this._vertexError(q, vertex1.position);\n const error2 = this._vertexError(q, vertex2.position);\n const error3 = this._vertexError(q, p3);\n error = Math.min(error1, error2, error3);\n if (error === error1) {\n if (pointResult) {\n pointResult.copyFrom(vertex1.position);\n }\n }\n else if (error === error2) {\n if (pointResult) {\n pointResult.copyFrom(vertex2.position);\n }\n }\n else {\n if (pointResult) {\n pointResult.copyFrom(p3);\n }\n }\n }\n return error;\n }\n}\n//# sourceMappingURL=meshSimplification.js.map","import { Vector3 } from \"../Maths/math.vector.js\";\nimport { GreasedLinePluginMaterial } from \"../Materials/greasedLinePluginMaterial.js\";\nimport { Mesh } from \"./mesh.js\";\nimport { Buffer, VertexBuffer } from \"../Buffers/buffer.js\";\nimport { VertexData } from \"./mesh.vertexData.js\";\nimport { PickingInfo } from \"../Collisions/pickingInfo.js\";\nimport { DeepCopier } from \"../Misc/deepCopier.js\";\nimport { GreasedLineTools } from \"../Misc/greasedLineTools.js\";\nMesh._GreasedLineMeshParser = (parsedMesh, scene) => {\n return GreasedLineMesh.Parse(parsedMesh, scene);\n};\n/**\n * GreasedLine\n */\nexport class GreasedLineMesh extends Mesh {\n constructor(name, scene, _options) {\n var _a, _b, _c, _d;\n super(name, scene, null, null, false, false);\n this.name = name;\n this._options = _options;\n this._lazy = false;\n this._updatable = false;\n /**\n * Treshold used to pick the mesh\n */\n this.intersectionThreshold = 0.1;\n this._lazy = (_a = _options.lazy) !== null && _a !== void 0 ? _a : false;\n this._updatable = (_b = _options.updatable) !== null && _b !== void 0 ? _b : false;\n this._vertexPositions = [];\n this._indices = [];\n this._uvs = [];\n this._points = [];\n this._colorPointers = (_c = _options.colorPointers) !== null && _c !== void 0 ? _c : [];\n this._previousAndSide = [];\n this._nextAndCounters = [];\n _options.widths = (_d = _options.widths) !== null && _d !== void 0 ? _d : new Array(_options.points.length).fill(1);\n if (_options.points) {\n this.addPoints(GreasedLineMesh.ConvertPoints(_options.points));\n }\n }\n /**\n * \"GreasedLineMesh\"\n * @returns \"GreasedLineMesh\"\n */\n getClassName() {\n return \"GreasedLineMesh\";\n }\n /**\n * Converts GreasedLinePoints to number[][]\n * @param points GreasedLinePoints\n * @returns number[][] with x, y, z coordinates of the points, like [[x, y, z, x, y, z, ...], [x, y, z, ...]]\n */\n static ConvertPoints(points) {\n if (points.length && Array.isArray(points) && typeof points[0] === \"number\") {\n return [points];\n }\n else if (points.length && Array.isArray(points[0]) && typeof points[0][0] === \"number\") {\n return points;\n }\n else if (points.length && !Array.isArray(points[0]) && points[0] instanceof Vector3) {\n const positions = [];\n for (let j = 0; j < points.length; j++) {\n const p = points[j];\n positions.push(p.x, p.y, p.z);\n }\n return [positions];\n }\n else if (points.length > 0 && Array.isArray(points[0]) && points[0].length > 0 && points[0][0] instanceof Vector3) {\n const positions = [];\n const vectorPoints = points;\n vectorPoints.forEach((p) => {\n positions.push(p.flatMap((p2) => [p2.x, p2.y, p2.z]));\n });\n return positions;\n }\n else if (points instanceof Float32Array) {\n return [Array.from(points)];\n }\n else if (points.length && points[0] instanceof Float32Array) {\n const positions = [];\n points.forEach((p) => {\n positions.push(Array.from(p));\n });\n return positions;\n }\n return [];\n }\n /**\n * Updated a lazy line. Rerenders the line and updates boundinfo as well.\n */\n updateLazy() {\n var _a;\n this.setPoints(this._points);\n if (!this._options.colorPointers) {\n this._updateColorPointers();\n }\n this._createVertexBuffers();\n this.refreshBoundingInfo();\n (_a = this.greasedLineMaterial) === null || _a === void 0 ? void 0 : _a.updateLazy();\n }\n /**\n * Dispose the line and it's resources\n */\n dispose() {\n super.dispose();\n }\n /**\n *\n * @returns true if the mesh was created in lazy mode\n */\n isLazy() {\n return this._lazy;\n }\n /**\n *\n * @returns options of the line\n */\n get options() {\n return this._options;\n }\n /**\n * Sets point offets\n * @param offsets offset table [x,y,z, x,y,z, ....]\n */\n setOffsets(offsets) {\n if (!this._offsetsBuffer) {\n this._createOffsetsBuffer(offsets);\n }\n else {\n this._offsetsBuffer && this._offsetsBuffer.update(offsets);\n }\n }\n /**\n * Sets widths at each line point\n * @param widths width table [widthUpper,widthLower, widthUpper,widthLower, ...]\n */\n setSegmentWidths(widths) {\n this._options.widths = widths;\n if (!this._lazy) {\n this._widthsBuffer && this._widthsBuffer.update(widths);\n }\n }\n /**\n * Sets the color pointer\n * @param colorPointers arra of color pointer in the colors array. One pointer for every vertex is needed.\n */\n setColorPointers(colorPointers) {\n if (!this._lazy) {\n this._colorPointersBuffer && this._colorPointersBuffer.update(colorPointers);\n }\n }\n /**\n * Gets the pluginMaterial associated with line\n */\n get greasedLineMaterial() {\n var _a, _b;\n return (_b = (_a = this.material) === null || _a === void 0 ? void 0 : _a.pluginManager) === null || _b === void 0 ? void 0 : _b.getPlugin(GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME);\n }\n /**\n * Adds new points to the line. It doesn't rerenders the line if in lazy mode.\n * @param points points table\n */\n addPoints(points) {\n const numberPoints = points;\n this._points.push(...numberPoints);\n if (!this._lazy) {\n this.setPoints(this._points);\n }\n }\n _updateColorPointers() {\n let colorPointer = 0;\n this._colorPointers = [];\n this._points.forEach((p) => {\n for (let jj = 0; jj < p.length; jj += 3) {\n this._colorPointers.push(colorPointer);\n this._colorPointers.push(colorPointer++);\n }\n });\n }\n /**\n * Sets line points and rerenders the line.\n * @param points points table\n */\n setPoints(points) {\n this._points = points;\n this._options.points = points;\n this._initGreasedLine();\n let indiceOffset = 0;\n points.forEach((p) => {\n var _a;\n const counters = [];\n const positions = [];\n const indices = [];\n const totalLength = GreasedLineTools.GetLineLength(p);\n for (let j = 0, jj = 0; jj < p.length; j++, jj += 3) {\n const partialLine = p.slice(0, jj + 3);\n const partialLineLength = GreasedLineTools.GetLineLength(partialLine);\n const c = partialLineLength / totalLength;\n positions.push(p[jj], p[jj + 1], p[jj + 2]);\n positions.push(p[jj], p[jj + 1], p[jj + 2]);\n counters.push(c);\n counters.push(c);\n if (jj < p.length - 3) {\n const n = j * 2 + indiceOffset;\n indices.push(n, n + 1, n + 2);\n indices.push(n + 2, n + 1, n + 3);\n }\n }\n indiceOffset += (p.length / 3) * 2;\n const previous = [];\n const next = [];\n const side = [];\n let uvs = [];\n this._preprocess(positions, previous, next, side, uvs);\n this._vertexPositions.push(...positions);\n this._indices.push(...indices);\n for (let i = 0; i < side.length; i++) {\n this._previousAndSide.push(previous[i * 3], previous[i * 3 + 1], previous[i * 3 + 2], side[i]);\n this._nextAndCounters.push(next[i * 3], next[i * 3 + 1], next[i * 3 + 2], counters[i]);\n }\n uvs = (_a = this._options.uvs) !== null && _a !== void 0 ? _a : uvs;\n this._uvs.push(...uvs);\n });\n if (!this._lazy) {\n if (!this._options.colorPointers) {\n this._updateColorPointers();\n }\n this._createVertexBuffers();\n this.refreshBoundingInfo();\n }\n }\n /**\n * Clones the GreasedLineMesh.\n * @param name new line name\n * @param newParent new parent node\n * @returns cloned line\n */\n clone(name = `${this.name}-cloned`, newParent) {\n const lineOptions = {};\n DeepCopier.DeepCopy(this._options, lineOptions, [\"instance\"]);\n const cloned = new GreasedLineMesh(name, this._scene, lineOptions);\n if (newParent) {\n cloned.parent = newParent;\n }\n cloned.material = this.material;\n return cloned;\n }\n /**\n * Serializes this GreasedLineMesh\n * @param serializationObject object to write serialization to\n */\n serialize(serializationObject) {\n super.serialize(serializationObject);\n serializationObject.type = this.getClassName();\n serializationObject.lineOptions = this._options;\n }\n /**\n * Parses a serialized GreasedLineMesh\n * @param parsedMesh the serialized GreasedLineMesh\n * @param scene the scene to create the GreasedLineMesh in\n * @returns the created GreasedLineMesh\n */\n static Parse(parsedMesh, scene) {\n const lineOptions = parsedMesh.lineOptions;\n const name = parsedMesh.name;\n const result = new GreasedLineMesh(name, scene, lineOptions);\n return result;\n }\n /**\n * Checks whether a ray is intersecting this GreasedLineMesh\n * @param ray ray to check the intersection of this mesh with\n * @param fastCheck not supported\n * @param trianglePredicate not supported\n * @param onlyBoundingInfo defines a boolean indicating if picking should only happen using bounding info (false by default)\n * @param worldToUse not supported\n * @param skipBoundingInfo a boolean indicating if we should skip the bounding info check\n * @returns the picking info\n */\n intersects(ray, fastCheck, trianglePredicate, onlyBoundingInfo = false, worldToUse, skipBoundingInfo = false) {\n const pickingInfo = new PickingInfo();\n const intersections = this.findAllIntersections(ray, fastCheck, trianglePredicate, onlyBoundingInfo, worldToUse, skipBoundingInfo, true);\n if ((intersections === null || intersections === void 0 ? void 0 : intersections.length) === 1) {\n const intersection = intersections[0];\n pickingInfo.hit = true;\n pickingInfo.distance = intersection.distance;\n pickingInfo.ray = ray;\n pickingInfo.pickedMesh = this;\n pickingInfo.pickedPoint = intersection.point;\n }\n return pickingInfo;\n }\n /**\n * Gets all intersections of a ray and the line\n * @param ray Ray to check the intersection of this mesh with\n * @param _fastCheck not supported\n * @param _trianglePredicate not supported\n * @param onlyBoundingInfo defines a boolean indicating if picking should only happen using bounding info (false by default)\n * @param _worldToUse not supported\n * @param skipBoundingInfo a boolean indicating if we should skip the bounding info check\n * @param firstOnly If true, the first and only intersection is immediatelly returned if found\n * @returns intersection(s)\n */\n findAllIntersections(ray, _fastCheck, _trianglePredicate, onlyBoundingInfo = false, _worldToUse, skipBoundingInfo = false, firstOnly = false) {\n var _a, _b;\n if (onlyBoundingInfo && !skipBoundingInfo && ray.intersectsSphere(this._boundingSphere, this.intersectionThreshold) === false) {\n return;\n }\n const indices = this.getIndices();\n const positions = this.getVerticesData(VertexBuffer.PositionKind);\n const widths = this._options.widths;\n const lineWidth = (_b = (_a = this.greasedLineMaterial) === null || _a === void 0 ? void 0 : _a.getOptions().width) !== null && _b !== void 0 ? _b : 1;\n const intersects = [];\n if (indices && positions && widths) {\n let i = 0, l = 0;\n for (i = 0, l = indices.length - 1; i < l; i += 3) {\n const a = indices[i];\n const b = indices[i + 1];\n GreasedLineMesh._V_START.fromArray(positions, a * 3);\n GreasedLineMesh._V_END.fromArray(positions, b * 3);\n if (this._offsets) {\n GreasedLineMesh._V_OFFSET_START.fromArray(this._offsets, a * 3);\n GreasedLineMesh._V_OFFSET_END.fromArray(this._offsets, b * 3);\n GreasedLineMesh._V_START.addInPlace(GreasedLineMesh._V_OFFSET_START);\n GreasedLineMesh._V_END.addInPlace(GreasedLineMesh._V_OFFSET_END);\n }\n const iFloored = Math.floor(i / 3);\n const width = widths[iFloored] !== undefined ? widths[iFloored] : 1;\n const precision = (this.intersectionThreshold * (lineWidth * width)) / 2;\n const distance = ray.intersectionSegment(GreasedLineMesh._V_START, GreasedLineMesh._V_END, precision);\n if (distance !== -1) {\n intersects.push({\n distance: distance,\n point: ray.direction.normalize().multiplyByFloats(distance, distance, distance).add(ray.origin),\n });\n if (firstOnly) {\n return intersects;\n }\n }\n }\n i = l;\n }\n return intersects;\n }\n _initGreasedLine() {\n this._vertexPositions = [];\n this._previousAndSide = [];\n this._nextAndCounters = [];\n this._indices = [];\n this._uvs = [];\n }\n get _boundingSphere() {\n return this.getBoundingInfo().boundingSphere;\n }\n static _CompareV3(positionIdx1, positionIdx2, positions) {\n const arrayIdx1 = positionIdx1 * 6;\n const arrayIdx2 = positionIdx2 * 6;\n return positions[arrayIdx1] === positions[arrayIdx2] && positions[arrayIdx1 + 1] === positions[arrayIdx2 + 1] && positions[arrayIdx1 + 2] === positions[arrayIdx2 + 2];\n }\n static _CopyV3(positionIdx, positions) {\n const arrayIdx = positionIdx * 6;\n return [positions[arrayIdx], positions[arrayIdx + 1], positions[arrayIdx + 2]];\n }\n _preprocess(positions, previous, next, side, uvs) {\n const l = positions.length / 6;\n let v = [];\n if (GreasedLineMesh._CompareV3(0, l - 1, positions)) {\n v = GreasedLineMesh._CopyV3(l - 2, positions);\n }\n else {\n v = GreasedLineMesh._CopyV3(0, positions);\n }\n previous.push(v[0], v[1], v[2]);\n previous.push(v[0], v[1], v[2]);\n for (let j = 0; j < l; j++) {\n side.push(1);\n side.push(-1);\n // uvs\n if (!this._options.uvs) {\n uvs.push(j / (l - 1), 0);\n uvs.push(j / (l - 1), 1);\n }\n if (j < l - 1) {\n v = GreasedLineMesh._CopyV3(j, positions);\n previous.push(v[0], v[1], v[2]);\n previous.push(v[0], v[1], v[2]);\n }\n if (j > 0) {\n v = GreasedLineMesh._CopyV3(j, positions);\n next.push(v[0], v[1], v[2]);\n next.push(v[0], v[1], v[2]);\n }\n }\n if (GreasedLineMesh._CompareV3(l - 1, 0, positions)) {\n v = GreasedLineMesh._CopyV3(1, positions);\n }\n else {\n v = GreasedLineMesh._CopyV3(l - 1, positions);\n }\n next.push(v[0], v[1], v[2]);\n next.push(v[0], v[1], v[2]);\n return {\n previous,\n next,\n uvs,\n side,\n };\n }\n _createVertexBuffers() {\n const vertexData = new VertexData();\n vertexData.positions = this._vertexPositions;\n vertexData.indices = this._indices;\n vertexData.uvs = this._uvs;\n vertexData.applyToMesh(this, this._options.updatable);\n const engine = this._scene.getEngine();\n const previousAndSideBuffer = new Buffer(engine, this._previousAndSide, false, 4);\n this.setVerticesBuffer(previousAndSideBuffer.createVertexBuffer(\"grl_previousAndSide\", 0, 4));\n const nextAndCountersBuffer = new Buffer(engine, this._nextAndCounters, false, 4);\n this.setVerticesBuffer(nextAndCountersBuffer.createVertexBuffer(\"grl_nextAndCounters\", 0, 4));\n const widthBuffer = new Buffer(engine, this._options.widths, this._updatable, 1);\n this.setVerticesBuffer(widthBuffer.createVertexBuffer(\"grl_widths\", 0, 1));\n this._widthsBuffer = widthBuffer;\n const colorPointersBuffer = new Buffer(engine, this._colorPointers, this._updatable, 1);\n this.setVerticesBuffer(colorPointersBuffer.createVertexBuffer(\"grl_colorPointers\", 0, 1));\n this._colorPointersBuffer = colorPointersBuffer;\n }\n _createOffsetsBuffer(offsets) {\n const engine = this._scene.getEngine();\n const offsetBuffer = new Buffer(engine, offsets, this._updatable, 3);\n this.setVerticesBuffer(offsetBuffer.createVertexBuffer(\"grl_offsets\", 0, 3));\n this._offsetsBuffer = offsetBuffer;\n }\n}\nGreasedLineMesh._V_START = new Vector3();\nGreasedLineMesh._V_END = new Vector3();\nGreasedLineMesh._V_OFFSET_START = new Vector3();\nGreasedLineMesh._V_OFFSET_END = new Vector3();\n//# sourceMappingURL=greasedLineMesh.js.map","/* eslint-disable import/export */\n/* eslint-disable import/no-internal-modules */\nexport * from \"./abstractMesh.js\";\nimport \"./abstractMesh.decalMap.js\";\nexport * from \"./Compression/index.js\";\nexport * from \"./csg.js\";\nexport * from \"./meshUVSpaceRenderer.js\";\nexport * from \"./geometry.js\";\nexport * from \"./groundMesh.js\";\nexport * from \"./goldbergMesh.js\";\nexport * from \"./trailMesh.js\";\nexport * from \"./instancedMesh.js\";\nexport * from \"./linesMesh.js\";\nexport * from \"./mesh.js\";\nexport * from \"./mesh.vertexData.js\";\nexport * from \"./meshBuilder.js\";\nexport * from \"./meshSimplification.js\";\nexport * from \"./meshSimplificationSceneComponent.js\";\nexport * from \"./polygonMesh.js\";\nexport * from \"./geodesicMesh.js\";\nexport * from \"./subMesh.js\";\nexport * from \"./subMesh.project.js\";\nexport * from \"./meshLODLevel.js\";\nexport * from \"./transformNode.js\";\nexport * from \"./Builders/index.js\";\nexport * from \"./WebGL/webGLDataBuffer.js\";\nexport * from \"./WebGPU/webgpuDataBuffer.js\";\nexport * from \"./greasedLineMesh.js\";\nimport \"./thinInstanceMesh.js\";\n// eslint-disable-next-line no-duplicate-imports\nexport * from \"./thinInstanceMesh.js\";\n//# sourceMappingURL=index.js.map","import { Scene } from \"../scene.js\";\nimport { Mesh } from \"./mesh.js\";\nimport { SimplificationQueue, SimplificationType } from \"./meshSimplification.js\";\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nObject.defineProperty(Scene.prototype, \"simplificationQueue\", {\n get: function () {\n if (!this._simplificationQueue) {\n this._simplificationQueue = new SimplificationQueue();\n let component = this._getComponent(SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);\n if (!component) {\n component = new SimplicationQueueSceneComponent(this);\n this._addComponent(component);\n }\n }\n return this._simplificationQueue;\n },\n set: function (value) {\n this._simplificationQueue = value;\n },\n enumerable: true,\n configurable: true,\n});\nMesh.prototype.simplify = function (settings, parallelProcessing = true, simplificationType = SimplificationType.QUADRATIC, successCallback) {\n this.getScene().simplificationQueue.addTask({\n settings: settings,\n parallelProcessing: parallelProcessing,\n mesh: this,\n simplificationType: simplificationType,\n successCallback: successCallback,\n });\n return this;\n};\n/**\n * Defines the simplification queue scene component responsible to help scheduling the various simplification task\n * created in a scene\n */\nexport class SimplicationQueueSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpfull to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;\n this.scene = scene;\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene._beforeCameraUpdateStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n // Nothing to do for this component\n }\n /**\n * Disposes the component and the associated resources\n */\n dispose() {\n // Nothing to do for this component\n }\n _beforeCameraUpdate() {\n if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {\n this.scene._simplificationQueue.executeNext();\n }\n }\n}\n//# sourceMappingURL=meshSimplificationSceneComponent.js.map","import { Curve3 } from \"../Maths/math.path.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { TmpVectors, Vector3 } from \"../Maths/math.vector.js\";\nimport { CreateTextShapePaths } from \"../Meshes/Builders/textBuilder.js\";\n/**\n * Tool functions for GreasedLine\n */\nexport class GreasedLineTools {\n /**\n * Gets mesh triangles as line positions\n * @param meshes array of meshes\n * @param omitZeroLengthLines do not generate a line when the distance if the vertices in the triangle equals to zero\n * @returns array of arrays of points\n */\n static MeshesToLines(meshes, omitZeroLengthLines = true) {\n const points = [];\n meshes.forEach((m) => {\n const vertices = m.getVerticesData(VertexBuffer.PositionKind);\n const indices = m.getIndices();\n if (vertices && indices) {\n for (let i = 0, ii = 0; i < indices.length; i++) {\n const vi1 = indices[ii++] * 3;\n const vi2 = indices[ii++] * 3;\n const vi3 = indices[ii++] * 3;\n const p1 = new Vector3(vertices[vi1], vertices[vi1 + 1], vertices[vi1 + 2]);\n const p2 = new Vector3(vertices[vi2], vertices[vi2 + 1], vertices[vi2 + 2]);\n const p3 = new Vector3(vertices[vi3], vertices[vi3 + 1], vertices[vi3 + 2]);\n if (omitZeroLengthLines && p1.lengthSquared() + p2.lengthSquared() + p3.lengthSquared() === 0) {\n continue;\n }\n points.push([p1, p2, p3, p1]);\n }\n }\n });\n return points;\n }\n /**\n * Converts number coordinates to Vector3s\n * @param points number array of x, y, z, x, y z, ... coordinates\n * @returns Vector3 array\n */\n static ToVector3Array(points) {\n const array = [];\n for (let i = 0; i < points.length; i += 3) {\n array.push(new Vector3(points[i], points[i + 1], points[i + 2]));\n }\n return array;\n }\n /**\n * Gets a number array from a Vector3 array.\n * You can you for example to convert your Vector3[] offsets to the required number[] for the offsets option.\n * @param points Vector3 array\n * @returns an array of x, y, z coordinates as numbers [x, y, z, x, y, z, x, y, z, ....]\n */\n static ToNumberArray(points) {\n return points.flatMap((v) => [v.x, v.y, v.z]);\n }\n /**\n * Calculates the sum of points of every line and the number of points in each line.\n * This function is useful when you are drawing multiple lines in one mesh and you want\n * to know the counts. For example for creating an offsets table.\n * @param points point array\n * @returns points count info\n */\n static GetPointsCountInfo(points) {\n const counts = new Array(points.length);\n let total = 0;\n for (let n = points.length; n--;) {\n counts[n] = points[n].length / 3;\n total += counts[n];\n }\n return { total, counts };\n }\n /**\n * Gets the length of the line counting all it's segments length\n * @param data array of line points\n * @returns length of the line\n */\n static GetLineLength(data) {\n if (data.length === 0) {\n return 0;\n }\n let points;\n if (typeof data[0] === \"number\") {\n points = GreasedLineTools.ToVector3Array(data);\n }\n else {\n points = data;\n }\n const tmp = TmpVectors.Vector3[0];\n let length = 0;\n for (let index = 0; index < points.length - 1; index++) {\n const point1 = points[index];\n const point2 = points[index + 1];\n length += point2.subtractToRef(point1, tmp).length();\n }\n return length;\n }\n /**\n * Divides a segment into smaller segments.\n * A segment is a part of the line between it's two points.\n * @param point1 first point of the line\n * @param point2 second point of the line\n * @param segmentCount number of segments we want to have in the divided line\n * @returns\n */\n static SegmentizeSegmentByCount(point1, point2, segmentCount) {\n const dividedLinePoints = [];\n const diff = point2.subtract(point1);\n const divisor = TmpVectors.Vector3[0];\n divisor.setAll(segmentCount);\n const segmentVector = TmpVectors.Vector3[1];\n diff.divideToRef(divisor, segmentVector);\n let nextPoint = point1.clone();\n dividedLinePoints.push(nextPoint);\n for (let index = 0; index < segmentCount; index++) {\n nextPoint = nextPoint.clone();\n dividedLinePoints.push(nextPoint.addInPlace(segmentVector));\n }\n return dividedLinePoints;\n }\n /**\n * Divides a line into segments.\n * A segment is a part of the line between it's two points.\n * @param what line points\n * @param segmentLength length of each segment of the resulting line (distance between two line points)\n * @returns line point\n */\n static SegmentizeLineBySegmentLength(what, segmentLength) {\n const subLines = what[0] instanceof Vector3 ? GreasedLineTools.GetLineSegments(what) : what;\n const points = [];\n subLines.forEach((s) => {\n if (s.length > segmentLength) {\n const segments = GreasedLineTools.SegmentizeSegmentByCount(s.point1, s.point2, Math.ceil(s.length / segmentLength));\n segments.forEach((seg) => {\n points.push(seg);\n });\n }\n else {\n points.push(s.point1);\n points.push(s.point2);\n }\n });\n return points;\n }\n /**\n * Divides a line into segments.\n * A segment is a part of the line between it's two points.\n * @param what line points\n * @param segmentCount number of segments\n * @returns line point\n */\n static SegmentizeLineBySegmentCount(what, segmentCount) {\n const segmentLength = GreasedLineTools.GetLineLength(what) / segmentCount;\n return GreasedLineTools.SegmentizeLineBySegmentLength(what, segmentLength);\n }\n /**\n * Gets line segments.\n * A segment is a part of the line between it's two points.\n * @param points line points\n * @returns segments information of the line segment including starting point, ending point and the distance between them\n */\n static GetLineSegments(points) {\n const segments = [];\n for (let index = 0; index < points.length - 1; index++) {\n const point1 = points[index];\n const point2 = points[index + 1];\n const length = point2.subtract(point1).length();\n segments.push({ point1, point2, length });\n }\n return segments;\n }\n /**\n * Gets the minimum and the maximum length of a line segment in the line.\n * A segment is a part of the line between it's two points.\n * @param points line points\n * @returns\n */\n static GetMinMaxSegmentLength(points) {\n const subLines = GreasedLineTools.GetLineSegments(points);\n const sorted = subLines.sort((s) => s.length);\n return {\n min: sorted[0].length,\n max: sorted[sorted.length - 1].length,\n };\n }\n /**\n * Finds the last visible position in world space of the line according to the visibility parameter\n * @param lineSegments segments of the line\n * @param lineLength total length of the line\n * @param visbility normalized value of visibility\n * @returns world space coordinate of the last visible piece of the line\n */\n static GetPositionOnLineByVisibility(lineSegments, lineLength, visbility, localSpace = false) {\n const lengthVisibilityRatio = lineLength * visbility;\n let sumSegmentLengths = 0;\n let segmentIndex = 0;\n const lineSegmentsLength = lineSegments.length;\n for (let i = 0; i < lineSegmentsLength; i++) {\n if (lengthVisibilityRatio <= sumSegmentLengths + lineSegments[i].length) {\n segmentIndex = i;\n break;\n }\n sumSegmentLengths += lineSegments[i].length;\n }\n const s = (lengthVisibilityRatio - sumSegmentLengths) / lineSegments[segmentIndex].length;\n lineSegments[segmentIndex].point2.subtractToRef(lineSegments[segmentIndex].point1, TmpVectors.Vector3[0]);\n TmpVectors.Vector3[1] = TmpVectors.Vector3[0].multiplyByFloats(s, s, s);\n if (!localSpace) {\n TmpVectors.Vector3[1].addInPlace(lineSegments[segmentIndex].point1);\n }\n return TmpVectors.Vector3[1].clone();\n }\n /**\n * Creates lines in a shape of circle/arc.\n * A segment is a part of the line between it's two points.\n * @param radiusX radiusX of the circle\n * @param segments number of segments in the circle\n * @param z z coordinate of the points. Defaults to 0.\n * @param radiusY radiusY of the circle - you can draw an oval if using different values\n * @param segmentAngle angle offset of the segments. Defaults to Math.PI * 2 / segments. Change this value to draw a part of the circle.\n * @returns line points\n */\n static GetCircleLinePoints(radiusX, segments, z = 0, radiusY = radiusX, segmentAngle = (Math.PI * 2) / segments) {\n const points = [];\n for (let i = 0; i <= segments; i++) {\n points.push(new Vector3(Math.cos(i * segmentAngle) * radiusX, Math.sin(i * segmentAngle) * radiusY, z));\n }\n return points;\n }\n /**\n * Gets line points in a shape of a bezier curve\n * @param p0 bezier point0\n * @param p1 bezier point1\n * @param p2 bezier point2\n * @param segments number of segments in the curve\n * @returns\n */\n static GetBezierLinePoints(p0, p1, p2, segments) {\n return Curve3.CreateQuadraticBezier(p0, p1, p2, segments)\n .getPoints()\n .flatMap((v) => [v.x, v.y, v.z]);\n }\n /**\n *\n * @param position position of the arrow cap (mainly you want to create a triangle, set widthUp and widthDown to the same value and omit widthStartUp and widthStartDown)\n * @param direction direction which the arrow points to\n * @param length length (size) of the arrow cap itself\n * @param widthUp the arrow width above the line\n * @param widthDown the arrow width belove the line\n * @param widthStartUp the arrow width at the start of the arrow above the line. In most scenarios this is 0.\n * @param widthStartDown the arrow width at the start of the arrow below the line. In most scenarios this is 0.\n * @returns\n */\n static GetArrowCap(position, direction, length, widthUp, widthDown, widthStartUp = 0, widthStartDown = 0) {\n const points = [position.clone(), position.add(direction.multiplyByFloats(length, length, length))];\n const widths = [widthUp, widthDown, widthStartUp, widthStartDown];\n return {\n points,\n widths,\n };\n }\n /**\n * Gets 3D positions of points from a text and font\n * @param text Text\n * @param size Size of the font\n * @param resolution Resolution of the font\n * @param fontData defines the font data (can be generated with http://gero3.github.io/facetype.js/)\n * @param z z coordinate\n * @param includeInner include the inner parts of the font in the result. Default true. If false, only the outlines will be returned.\n * @returns number[][] of 3D positions\n */\n static GetPointsFromText(text, size, resolution, fontData, z = 0, includeInner = true) {\n const allPoints = [];\n const shapePaths = CreateTextShapePaths(text, size, resolution, fontData);\n for (const sp of shapePaths) {\n for (const p of sp.paths) {\n const points = [];\n const points2d = p.getPoints();\n for (const p2d of points2d) {\n points.push(p2d.x, p2d.y, z);\n }\n allPoints.push(points);\n }\n if (includeInner) {\n for (const h of sp.holes) {\n const holes = [];\n const points2d = h.getPoints();\n for (const p2d of points2d) {\n holes.push(p2d.x, p2d.y, z);\n }\n allPoints.push(holes);\n }\n }\n }\n return allPoints;\n }\n}\n//# sourceMappingURL=greasedLineTools.js.map","import { Color3 } from \"../../Maths/math.color.js\";\nimport { GreasedLineMeshColorMode, GreasedLineMeshMaterialType, GreasedLinePluginMaterial } from \"../../Materials/greasedLinePluginMaterial.js\";\nimport { StandardMaterial } from \"./../../Materials/standardMaterial.js\";\nimport { PBRMaterial } from \"../../Materials/PBR/pbrMaterial.js\";\nimport { GreasedLineMesh } from \"../greasedLineMesh.js\";\nimport { EngineStore } from \"../../Engines/engineStore.js\";\nexport var GreasedLineMeshColorDistribution;\n(function (GreasedLineMeshColorDistribution) {\n GreasedLineMeshColorDistribution[GreasedLineMeshColorDistribution[\"COLOR_DISTRIBUTION_NONE\"] = 0] = \"COLOR_DISTRIBUTION_NONE\";\n GreasedLineMeshColorDistribution[GreasedLineMeshColorDistribution[\"COLOR_DISTRIBUTION_REPEAT\"] = 1] = \"COLOR_DISTRIBUTION_REPEAT\";\n GreasedLineMeshColorDistribution[GreasedLineMeshColorDistribution[\"COLOR_DISTRIBUTION_EVEN\"] = 2] = \"COLOR_DISTRIBUTION_EVEN\";\n GreasedLineMeshColorDistribution[GreasedLineMeshColorDistribution[\"COLOR_DISTRIBUTION_START\"] = 3] = \"COLOR_DISTRIBUTION_START\";\n GreasedLineMeshColorDistribution[GreasedLineMeshColorDistribution[\"COLOR_DISTRIBUTION_END\"] = 4] = \"COLOR_DISTRIBUTION_END\";\n GreasedLineMeshColorDistribution[GreasedLineMeshColorDistribution[\"COLOR_DISTRIBUTION_START_END\"] = 5] = \"COLOR_DISTRIBUTION_START_END\";\n})(GreasedLineMeshColorDistribution || (GreasedLineMeshColorDistribution = {}));\nexport var GreasedLineMeshWidthDistribution;\n(function (GreasedLineMeshWidthDistribution) {\n GreasedLineMeshWidthDistribution[GreasedLineMeshWidthDistribution[\"WIDTH_DISTRIBUTION_NONE\"] = 0] = \"WIDTH_DISTRIBUTION_NONE\";\n GreasedLineMeshWidthDistribution[GreasedLineMeshWidthDistribution[\"WIDTH_DISTRIBUTION_REPEAT\"] = 1] = \"WIDTH_DISTRIBUTION_REPEAT\";\n GreasedLineMeshWidthDistribution[GreasedLineMeshWidthDistribution[\"WIDTH_DISTRIBUTION_EVEN\"] = 2] = \"WIDTH_DISTRIBUTION_EVEN\";\n GreasedLineMeshWidthDistribution[GreasedLineMeshWidthDistribution[\"WIDTH_DISTRIBUTION_START\"] = 3] = \"WIDTH_DISTRIBUTION_START\";\n GreasedLineMeshWidthDistribution[GreasedLineMeshWidthDistribution[\"WIDTH_DISTRIBUTION_END\"] = 4] = \"WIDTH_DISTRIBUTION_END\";\n GreasedLineMeshWidthDistribution[GreasedLineMeshWidthDistribution[\"WIDTH_DISTRIBUTION_START_END\"] = 5] = \"WIDTH_DISTRIBUTION_START_END\";\n})(GreasedLineMeshWidthDistribution || (GreasedLineMeshWidthDistribution = {}));\n/**\n * Builder class for create GreasedLineMeshes\n */\n/**\n * Creates a new @see GreasedLinePluginMaterial\n * @param name name of the material\n * @param options material options @see GreasedLineMaterialOptions\n * @param scene scene or null to use the last scene\n * @returns StandardMaterial or PBRMaterial with the @see GreasedLinePluginMaterial attached to it\n */\nexport function CreateGreasedLineMaterial(name, options, scene) {\n scene = (scene !== null && scene !== void 0 ? scene : EngineStore.LastCreatedScene);\n const material = options.materialType === GreasedLineMeshMaterialType.MATERIAL_TYPE_PBR ? new PBRMaterial(name, scene) : new StandardMaterial(name, scene);\n new GreasedLinePluginMaterial(material, scene, options);\n return material;\n}\n/**\n * Creates a GreasedLine mesh\n * @param name name of the mesh\n * @param options options for the mesh\n * @param materialOptions material options for the mesh\n * @param scene scene where the mesh will be created\n * @returns instance of GreasedLineMesh\n */\nexport function CreateGreasedLine(name, options, materialOptions, scene) {\n var _a, _b, _c, _d, _e, _f;\n scene = (scene !== null && scene !== void 0 ? scene : EngineStore.LastCreatedScene);\n let instance;\n const allPoints = GreasedLineMesh.ConvertPoints(options.points);\n let length = 0;\n if (Array.isArray(allPoints[0])) {\n allPoints.forEach((points) => {\n length += points.length / 3;\n });\n }\n options.widthDistribution = (_a = options.widthDistribution) !== null && _a !== void 0 ? _a : GreasedLineMeshWidthDistribution.WIDTH_DISTRIBUTION_START;\n materialOptions = materialOptions !== null && materialOptions !== void 0 ? materialOptions : {\n color: Color3.White(),\n };\n materialOptions.createAndAssignMaterial = (_b = materialOptions.createAndAssignMaterial) !== null && _b !== void 0 ? _b : true;\n materialOptions.colorDistribution = (_c = materialOptions === null || materialOptions === void 0 ? void 0 : materialOptions.colorDistribution) !== null && _c !== void 0 ? _c : GreasedLineMeshColorDistribution.COLOR_DISTRIBUTION_START;\n const widths = CompleteGreasedLineWidthTable(length, (_d = options.widths) !== null && _d !== void 0 ? _d : [], options.widthDistribution);\n const colors = (materialOptions === null || materialOptions === void 0 ? void 0 : materialOptions.colors)\n ? CompleteGreasedLineColorTable(length, materialOptions.colors, materialOptions.colorDistribution, (_e = materialOptions.color) !== null && _e !== void 0 ? _e : Color3.White())\n : undefined;\n // create new mesh if instance is not defined\n if (!options.instance) {\n const initialGreasedLineOptions = {\n points: allPoints,\n updatable: options.updatable,\n widths,\n lazy: options.lazy,\n };\n instance = new GreasedLineMesh(name, scene, initialGreasedLineOptions);\n if (materialOptions) {\n const initialMaterialOptions = {\n materialType: materialOptions.materialType,\n dashCount: materialOptions.dashCount,\n dashOffset: materialOptions.dashOffset,\n dashRatio: materialOptions.dashRatio,\n resolution: materialOptions.resolution,\n sizeAttenuation: materialOptions.sizeAttenuation,\n useColors: materialOptions.useColors,\n useDash: materialOptions.useDash,\n visibility: materialOptions.visibility,\n width: materialOptions.width,\n color: materialOptions.color,\n colorMode: (_f = materialOptions.colorMode) !== null && _f !== void 0 ? _f : GreasedLineMeshColorMode.COLOR_MODE_SET,\n colorsSampling: materialOptions.colorsSampling,\n colorDistributionType: materialOptions.colorDistributionType,\n };\n if (colors) {\n initialMaterialOptions.colors = colors;\n }\n else if (!materialOptions.color) {\n // if we don't have a color table nor a color assign it a default white color\n initialMaterialOptions.color = Color3.White();\n }\n if (materialOptions.createAndAssignMaterial) {\n const material = materialOptions.materialType === GreasedLineMeshMaterialType.MATERIAL_TYPE_PBR ? new PBRMaterial(name, scene) : new StandardMaterial(name, scene);\n new GreasedLinePluginMaterial(material, scene, initialMaterialOptions);\n instance.material = material;\n }\n }\n }\n else {\n // update the data on the mesh instance\n instance = options.instance;\n const currentWidths = instance.options.widths;\n if (currentWidths) {\n const newWidths = [...currentWidths];\n newWidths.push(...widths);\n instance.setSegmentWidths(newWidths);\n }\n else {\n instance.setSegmentWidths(widths);\n }\n instance.options.instance = instance;\n instance.addPoints(allPoints);\n }\n // add colors\n // it will merge if any colors already on the instance\n if (colors && options.instance) {\n if (options.instance.material instanceof StandardMaterial || instance.material instanceof PBRMaterial) {\n if (options.instance.greasedLineMaterial) {\n const currentColors = options.instance.greasedLineMaterial.getOptions().colors;\n if (currentColors) {\n const newColors = currentColors.concat(colors);\n options.instance.greasedLineMaterial.setColors(newColors, instance.isLazy());\n }\n }\n }\n }\n return instance;\n}\n/**\n * Completes the width table/fills the missing entries. It means it creates a width entry for every point of the line mesh.\n * You can provide more points the widths when creating the mesh. This function will fill the empty entries.\n * The algorithm used to fill the empty entries can be\n * GreasedLineMeshWidthDistribution.REPEAT - the width table will be repeatedly copied to the empty values [wL, wU] = [wL, wU, wL, wU, wL, wU, wL, wU, ...]\n * GreasedLineMeshWidthDistribution.EVEN - the width table will be evenly copied to the empty values [wL, wU] = [wL, wL, wL, wL, wU, wU, wU, wU]\n * GreasedLineMeshWidthDistribution.START - the width table will be copied at the start of the empty values\n * and rest will be filled width the default width upper and default width lower values [wU, wL] = [wL, wU, dwL, dwU, dwL, dwU, dwL, dwU]\n * GreasedLineMeshWidthDistribution.END - the width table will be copied at the end of the empty values\n * and rest will be filled width the default values [wL, wU] = [wL, wU, dwL, dwU, dwL, dwU, wL, wU]\n * @param pointCount number of points of the line mesh\n * @param widths array of widths [widhtLower, widthUpper, widthLower, widthUpper ...]. Two widths (lower/upper) per point.\n * @param widthsDistribution how to distribute widths if the widths array has fewer entries than pointCount\n * @param defaultWidthUpper the default value which will be used to fill empty width entries - upper width\n * @param defaultWidthLower the default value which will be used to fill empty width entries - lower width\n * @returns completed width table.\n */\nexport function CompleteGreasedLineWidthTable(pointCount, widths, widthsDistribution, defaultWidthUpper = 1, defaultWidthLower = 1) {\n const missingCount = pointCount - widths.length / 2;\n const widthsData = [];\n if (missingCount < 0) {\n return widths.slice(0, pointCount * 2);\n }\n // is the width table shorter than the point table?\n if (missingCount > 0) {\n // it is, fill in the missing elements\n if (widthsDistribution === GreasedLineMeshWidthDistribution.WIDTH_DISTRIBUTION_START_END) {\n const halfCount = Math.floor(widths.length / 2);\n // start sector\n for (let i = 0, j = 0; i < halfCount - 1; i++) {\n widthsData.push(widths[j++]);\n widthsData.push(widths[j++]);\n }\n // middle sector\n const widthL = widths[halfCount / 2];\n const widthU = widths[halfCount / 2 + 1];\n for (let i = 0; i < missingCount; i++) {\n widthsData.push(widthU);\n widthsData.push(widthL);\n }\n // end sector\n for (let i = halfCount; i < widths.length; i += 2) {\n widthsData.push(widths[i]);\n widthsData.push(widths[i + 1]);\n }\n }\n else if (widthsDistribution === GreasedLineMeshWidthDistribution.WIDTH_DISTRIBUTION_START) {\n // start sector\n for (let i = 0; i < widths.length; i += 2) {\n widthsData.push(widths[i]);\n widthsData.push(widths[i + 1]);\n }\n // end sector\n for (let i = 0; i < missingCount; i++) {\n widthsData.push(defaultWidthUpper);\n widthsData.push(defaultWidthLower);\n }\n }\n else if (widthsDistribution === GreasedLineMeshWidthDistribution.WIDTH_DISTRIBUTION_END) {\n // start sector\n for (let i = 0; i < missingCount; i++) {\n widthsData.push(defaultWidthUpper);\n widthsData.push(defaultWidthLower);\n }\n // end sector\n for (let i = 0; i < widths.length; i += 2) {\n widthsData.push(widths[i]);\n widthsData.push(widths[i + 1]);\n }\n }\n else if (widthsDistribution === GreasedLineMeshWidthDistribution.WIDTH_DISTRIBUTION_REPEAT) {\n let i = 0;\n for (let x = 0; x < pointCount; x++) {\n widthsData.push(widths[i++]);\n widthsData.push(widths[i++]);\n if (i === widths.length) {\n i = 0;\n }\n }\n }\n else if (widthsDistribution === GreasedLineMeshWidthDistribution.WIDTH_DISTRIBUTION_EVEN) {\n let j = 0;\n const widthsectorLength = widths.length / ((pointCount - 1) * 2);\n for (let x = 0; x < pointCount; x++) {\n const i = Math.floor(j);\n widthsData.push(widths[i]);\n widthsData.push(widths[i + 1]);\n j += widthsectorLength;\n }\n }\n }\n else {\n for (let i = 0; i < widths.length; i++) {\n widthsData.push(widths[i]);\n }\n }\n return widthsData;\n}\n/**\n * Completes the color table/fill the missing color entries. It means it creates a color entry for every point of the line mesh.\n * You can provide more points the colors when creating the mesh. This function will fill the empty entries.\n * The algorithm used to fill the empty entries can be\n * GreasedLineMesColorhDistribution.REPEAT - the color table will be repeatedly copied to the empty values [c1, c2] = [c1, c2, c1, c2, c1, c2, c1, c2]\n * GreasedLineMesColorhDistribution.EVEN - the color table will be evenly copied to the empty values [c1, c2] = [c1, c1, c1, c1, c2, c2, c2, c2]\n * GreasedLineMesColorhDistribution.START - the color table will be copied at the start of the empty values\n * and rest will be filled color the default color value [c1, c2] = [c1, c2, dc, dc, dc, dc, dc, dc]\n * GreasedLineMesColorhDistribution.START_END - the color table will be copied at the start and the end of the empty values\n * and rest will be filled color the default color value [c1, c2] = [c1, c2, dc, dc, dc, dc, c1, c2]\n * @param pointCount number of points of the line mesh\n * @param colors array of Color3 for the color table\n * @param colorDistribution how to distribute colors if the colors array has fewer entries than pointCount\n * @param defaultColor default color to be used to fill empty entries in the color table\n * @returns completed array of Color3s\n */\nexport function CompleteGreasedLineColorTable(pointCount, colors, colorDistribution, defaultColor) {\n const missingCount = pointCount - colors.length;\n if (missingCount < 0) {\n return colors.slice(0, pointCount);\n }\n const colorsData = [];\n // is the color table shorter than the point table?\n if (missingCount > 0) {\n // it is, fill in the missing elements\n if (colorDistribution === GreasedLineMeshColorDistribution.COLOR_DISTRIBUTION_START_END) {\n const halfCount = Math.floor(colors.length / 2);\n // start sector\n for (let i = 0; i < halfCount; i++) {\n colorsData.push(colors[i]);\n }\n // middle sector\n for (let i = 0; i < missingCount - 1; i++) {\n colorsData.push(defaultColor);\n }\n // end sector\n for (let i = halfCount; i < colors.length; i++) {\n colorsData.push(colors[i]);\n }\n }\n else if (colorDistribution === GreasedLineMeshColorDistribution.COLOR_DISTRIBUTION_START) {\n // start sector\n for (let i = 0; i < colors.length; i++) {\n colorsData.push(colors[i]);\n }\n // end sector\n for (let i = 0; i < missingCount; i++) {\n colorsData.push(defaultColor);\n }\n }\n else if (colorDistribution === GreasedLineMeshColorDistribution.COLOR_DISTRIBUTION_END) {\n // start sector\n for (let i = 0; i < missingCount - 1; i++) {\n colorsData.push(defaultColor);\n }\n // end sector\n for (let i = 0; i < colors.length; i++) {\n colorsData.push(colors[i]);\n }\n }\n else if (colorDistribution === GreasedLineMeshColorDistribution.COLOR_DISTRIBUTION_REPEAT) {\n let i = 0;\n for (let x = 0; x < pointCount; x++) {\n colorsData.push(colors[i]);\n i++;\n if (i === colors.length) {\n i = 0;\n }\n }\n }\n else if (colorDistribution === GreasedLineMeshColorDistribution.COLOR_DISTRIBUTION_EVEN) {\n let j = 0;\n const colorSectorLength = colors.length / (pointCount - 1);\n for (let x = 0; x < pointCount - 1; x++) {\n const i = Math.floor(j);\n colorsData.push(colors[i]);\n j += colorSectorLength;\n }\n }\n else if (colorDistribution === GreasedLineMeshColorDistribution.COLOR_DISTRIBUTION_NONE) {\n for (let i = 0; i < colors.length; i++) {\n colorsData.push(colors[i]);\n }\n }\n }\n else {\n for (let i = 0; i < pointCount; i++) {\n colorsData.push(colors[i]);\n }\n }\n return colorsData;\n}\n//# sourceMappingURL=greasedLineBuilder.js.map","import { Mesh } from \"../Meshes/mesh.js\";\nimport { VertexBuffer, Buffer } from \"../Buffers/buffer.js\";\nimport { Matrix, Vector3, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { BoundingInfo } from \"../Culling/boundingInfo.js\";\nMesh.prototype.thinInstanceAdd = function (matrix, refresh = true) {\n if (!this.getScene().getEngine().getCaps().instancedArrays) {\n Logger.Error(\"Thin Instances are not supported on this device as Instanced Array extension not supported\");\n return -1;\n }\n this._thinInstanceUpdateBufferSize(\"matrix\", Array.isArray(matrix) ? matrix.length : 1);\n const index = this._thinInstanceDataStorage.instancesCount;\n if (Array.isArray(matrix)) {\n for (let i = 0; i < matrix.length; ++i) {\n this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++, matrix[i], i === matrix.length - 1 && refresh);\n }\n }\n else {\n this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++, matrix, refresh);\n }\n return index;\n};\nMesh.prototype.thinInstanceAddSelf = function (refresh = true) {\n return this.thinInstanceAdd(Matrix.IdentityReadOnly, refresh);\n};\nMesh.prototype.thinInstanceRegisterAttribute = function (kind, stride) {\n // preserve backward compatibility\n if (kind === VertexBuffer.ColorKind) {\n kind = VertexBuffer.ColorInstanceKind;\n }\n this.removeVerticesData(kind);\n this._thinInstanceInitializeUserStorage();\n this._userThinInstanceBuffersStorage.strides[kind] = stride;\n this._userThinInstanceBuffersStorage.sizes[kind] = stride * Math.max(32, this._thinInstanceDataStorage.instancesCount); // Initial size\n this._userThinInstanceBuffersStorage.data[kind] = new Float32Array(this._userThinInstanceBuffersStorage.sizes[kind]);\n this._userThinInstanceBuffersStorage.vertexBuffers[kind] = new VertexBuffer(this.getEngine(), this._userThinInstanceBuffersStorage.data[kind], kind, true, false, stride, true);\n this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[kind]);\n};\nMesh.prototype.thinInstanceSetMatrixAt = function (index, matrix, refresh = true) {\n if (!this._thinInstanceDataStorage.matrixData || index >= this._thinInstanceDataStorage.instancesCount) {\n return false;\n }\n const matrixData = this._thinInstanceDataStorage.matrixData;\n matrix.copyToArray(matrixData, index * 16);\n if (this._thinInstanceDataStorage.worldMatrices) {\n this._thinInstanceDataStorage.worldMatrices[index] = matrix;\n }\n if (refresh) {\n this.thinInstanceBufferUpdated(\"matrix\");\n if (!this.doNotSyncBoundingInfo) {\n this.thinInstanceRefreshBoundingInfo(false);\n }\n }\n return true;\n};\nMesh.prototype.thinInstanceSetAttributeAt = function (kind, index, value, refresh = true) {\n // preserve backward compatibility\n if (kind === VertexBuffer.ColorKind) {\n kind = VertexBuffer.ColorInstanceKind;\n }\n if (!this._userThinInstanceBuffersStorage || !this._userThinInstanceBuffersStorage.data[kind] || index >= this._thinInstanceDataStorage.instancesCount) {\n return false;\n }\n this._thinInstanceUpdateBufferSize(kind, 0); // make sur the buffer for the kind attribute is big enough\n this._userThinInstanceBuffersStorage.data[kind].set(value, index * this._userThinInstanceBuffersStorage.strides[kind]);\n if (refresh) {\n this.thinInstanceBufferUpdated(kind);\n }\n return true;\n};\nObject.defineProperty(Mesh.prototype, \"thinInstanceCount\", {\n get: function () {\n return this._thinInstanceDataStorage.instancesCount;\n },\n set: function (value) {\n var _a, _b;\n const matrixData = (_a = this._thinInstanceDataStorage.matrixData) !== null && _a !== void 0 ? _a : (_b = this.source) === null || _b === void 0 ? void 0 : _b._thinInstanceDataStorage.matrixData;\n const numMaxInstances = matrixData ? matrixData.length / 16 : 0;\n if (value <= numMaxInstances) {\n this._thinInstanceDataStorage.instancesCount = value;\n }\n },\n enumerable: true,\n configurable: true,\n});\nMesh.prototype._thinInstanceCreateMatrixBuffer = function (kind, buffer, staticBuffer = false) {\n // preserve backward compatibility\n if (kind === VertexBuffer.ColorKind) {\n kind = VertexBuffer.ColorInstanceKind;\n }\n const matrixBuffer = new Buffer(this.getEngine(), buffer, !staticBuffer, 16, false, true);\n for (let i = 0; i < 4; i++) {\n this.setVerticesBuffer(matrixBuffer.createVertexBuffer(kind + i, i * 4, 4));\n }\n return matrixBuffer;\n};\nMesh.prototype.thinInstanceSetBuffer = function (kind, buffer, stride = 0, staticBuffer = false) {\n var _a, _b, _c;\n stride = stride || 16;\n if (kind === \"matrix\") {\n (_a = this._thinInstanceDataStorage.matrixBuffer) === null || _a === void 0 ? void 0 : _a.dispose();\n this._thinInstanceDataStorage.matrixBuffer = null;\n this._thinInstanceDataStorage.matrixBufferSize = buffer ? buffer.length : 32 * stride;\n this._thinInstanceDataStorage.matrixData = buffer;\n this._thinInstanceDataStorage.worldMatrices = null;\n if (buffer !== null) {\n this._thinInstanceDataStorage.instancesCount = buffer.length / stride;\n this._thinInstanceDataStorage.matrixBuffer = this._thinInstanceCreateMatrixBuffer(\"world\", buffer, staticBuffer);\n if (!this.doNotSyncBoundingInfo) {\n this.thinInstanceRefreshBoundingInfo(false);\n }\n }\n else {\n this._thinInstanceDataStorage.instancesCount = 0;\n if (!this.doNotSyncBoundingInfo) {\n // mesh has no more thin instances, so need to recompute the bounding box because it's the regular mesh that will now be displayed\n this.refreshBoundingInfo();\n }\n }\n }\n else if (kind === \"previousMatrix\") {\n (_b = this._thinInstanceDataStorage.previousMatrixBuffer) === null || _b === void 0 ? void 0 : _b.dispose();\n this._thinInstanceDataStorage.previousMatrixBuffer = null;\n this._thinInstanceDataStorage.previousMatrixData = buffer;\n if (buffer !== null) {\n this._thinInstanceDataStorage.previousMatrixBuffer = this._thinInstanceCreateMatrixBuffer(\"previousWorld\", buffer, staticBuffer);\n }\n }\n else {\n // color for instanced mesh is ColorInstanceKind and not ColorKind because of native that needs to do the differenciation\n // hot switching kind here to preserve backward compatibility\n if (kind === VertexBuffer.ColorKind) {\n kind = VertexBuffer.ColorInstanceKind;\n }\n if (buffer === null) {\n if ((_c = this._userThinInstanceBuffersStorage) === null || _c === void 0 ? void 0 : _c.data[kind]) {\n this.removeVerticesData(kind);\n delete this._userThinInstanceBuffersStorage.data[kind];\n delete this._userThinInstanceBuffersStorage.strides[kind];\n delete this._userThinInstanceBuffersStorage.sizes[kind];\n delete this._userThinInstanceBuffersStorage.vertexBuffers[kind];\n }\n }\n else {\n this._thinInstanceInitializeUserStorage();\n this._userThinInstanceBuffersStorage.data[kind] = buffer;\n this._userThinInstanceBuffersStorage.strides[kind] = stride;\n this._userThinInstanceBuffersStorage.sizes[kind] = buffer.length;\n this._userThinInstanceBuffersStorage.vertexBuffers[kind] = new VertexBuffer(this.getEngine(), buffer, kind, !staticBuffer, false, stride, true);\n this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[kind]);\n }\n }\n};\nMesh.prototype.thinInstanceBufferUpdated = function (kind) {\n var _a, _b, _c;\n if (kind === \"matrix\") {\n (_a = this._thinInstanceDataStorage.matrixBuffer) === null || _a === void 0 ? void 0 : _a.updateDirectly(this._thinInstanceDataStorage.matrixData, 0, this._thinInstanceDataStorage.instancesCount);\n }\n else if (kind === \"previousMatrix\") {\n (_b = this._thinInstanceDataStorage.previousMatrixBuffer) === null || _b === void 0 ? void 0 : _b.updateDirectly(this._thinInstanceDataStorage.previousMatrixData, 0, this._thinInstanceDataStorage.instancesCount);\n }\n else {\n // preserve backward compatibility\n if (kind === VertexBuffer.ColorKind) {\n kind = VertexBuffer.ColorInstanceKind;\n }\n if ((_c = this._userThinInstanceBuffersStorage) === null || _c === void 0 ? void 0 : _c.vertexBuffers[kind]) {\n this._userThinInstanceBuffersStorage.vertexBuffers[kind].updateDirectly(this._userThinInstanceBuffersStorage.data[kind], 0);\n }\n }\n};\nMesh.prototype.thinInstancePartialBufferUpdate = function (kind, data, offset) {\n var _a;\n if (kind === \"matrix\") {\n if (this._thinInstanceDataStorage.matrixBuffer) {\n this._thinInstanceDataStorage.matrixBuffer.updateDirectly(data, offset);\n }\n }\n else {\n // preserve backward compatibility\n if (kind === VertexBuffer.ColorKind) {\n kind = VertexBuffer.ColorInstanceKind;\n }\n if ((_a = this._userThinInstanceBuffersStorage) === null || _a === void 0 ? void 0 : _a.vertexBuffers[kind]) {\n this._userThinInstanceBuffersStorage.vertexBuffers[kind].updateDirectly(data, offset);\n }\n }\n};\nMesh.prototype.thinInstanceGetWorldMatrices = function () {\n if (!this._thinInstanceDataStorage.matrixData || !this._thinInstanceDataStorage.matrixBuffer) {\n return [];\n }\n const matrixData = this._thinInstanceDataStorage.matrixData;\n if (!this._thinInstanceDataStorage.worldMatrices) {\n this._thinInstanceDataStorage.worldMatrices = new Array();\n for (let i = 0; i < this._thinInstanceDataStorage.instancesCount; ++i) {\n this._thinInstanceDataStorage.worldMatrices[i] = Matrix.FromArray(matrixData, i * 16);\n }\n }\n return this._thinInstanceDataStorage.worldMatrices;\n};\nMesh.prototype.thinInstanceRefreshBoundingInfo = function (forceRefreshParentInfo = false, applySkeleton = false, applyMorph = false) {\n if (!this._thinInstanceDataStorage.matrixData || !this._thinInstanceDataStorage.matrixBuffer) {\n return;\n }\n const vectors = this._thinInstanceDataStorage.boundingVectors;\n if (forceRefreshParentInfo || !this.rawBoundingInfo) {\n vectors.length = 0;\n this.refreshBoundingInfo(applySkeleton, applyMorph);\n const boundingInfo = this.getBoundingInfo();\n this.rawBoundingInfo = new BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);\n }\n const boundingInfo = this.getBoundingInfo();\n const matrixData = this._thinInstanceDataStorage.matrixData;\n if (vectors.length === 0) {\n for (let v = 0; v < boundingInfo.boundingBox.vectors.length; ++v) {\n vectors.push(boundingInfo.boundingBox.vectors[v].clone());\n }\n }\n TmpVectors.Vector3[0].setAll(Number.POSITIVE_INFINITY); // min\n TmpVectors.Vector3[1].setAll(Number.NEGATIVE_INFINITY); // max\n for (let i = 0; i < this._thinInstanceDataStorage.instancesCount; ++i) {\n Matrix.FromArrayToRef(matrixData, i * 16, TmpVectors.Matrix[0]);\n for (let v = 0; v < vectors.length; ++v) {\n Vector3.TransformCoordinatesToRef(vectors[v], TmpVectors.Matrix[0], TmpVectors.Vector3[2]);\n TmpVectors.Vector3[0].minimizeInPlace(TmpVectors.Vector3[2]);\n TmpVectors.Vector3[1].maximizeInPlace(TmpVectors.Vector3[2]);\n }\n }\n boundingInfo.reConstruct(TmpVectors.Vector3[0], TmpVectors.Vector3[1]);\n this._updateBoundingInfo();\n};\nMesh.prototype._thinInstanceUpdateBufferSize = function (kind, numInstances = 1) {\n var _a, _b, _c;\n // preserve backward compatibility\n if (kind === VertexBuffer.ColorKind) {\n kind = VertexBuffer.ColorInstanceKind;\n }\n const kindIsMatrix = kind === \"matrix\";\n if (!kindIsMatrix && (!this._userThinInstanceBuffersStorage || !this._userThinInstanceBuffersStorage.strides[kind])) {\n return;\n }\n const stride = kindIsMatrix ? 16 : this._userThinInstanceBuffersStorage.strides[kind];\n const currentSize = kindIsMatrix ? this._thinInstanceDataStorage.matrixBufferSize : this._userThinInstanceBuffersStorage.sizes[kind];\n let data = kindIsMatrix ? this._thinInstanceDataStorage.matrixData : this._userThinInstanceBuffersStorage.data[kind];\n const bufferSize = (this._thinInstanceDataStorage.instancesCount + numInstances) * stride;\n let newSize = currentSize;\n while (newSize < bufferSize) {\n newSize *= 2;\n }\n if (!data || currentSize != newSize) {\n if (!data) {\n data = new Float32Array(newSize);\n }\n else {\n const newData = new Float32Array(newSize);\n newData.set(data, 0);\n data = newData;\n }\n if (kindIsMatrix) {\n (_a = this._thinInstanceDataStorage.matrixBuffer) === null || _a === void 0 ? void 0 : _a.dispose();\n this._thinInstanceDataStorage.matrixBuffer = this._thinInstanceCreateMatrixBuffer(\"world\", data, false);\n this._thinInstanceDataStorage.matrixData = data;\n this._thinInstanceDataStorage.matrixBufferSize = newSize;\n if (this._scene.needsPreviousWorldMatrices && !this._thinInstanceDataStorage.previousMatrixData) {\n (_b = this._thinInstanceDataStorage.previousMatrixBuffer) === null || _b === void 0 ? void 0 : _b.dispose();\n this._thinInstanceDataStorage.previousMatrixBuffer = this._thinInstanceCreateMatrixBuffer(\"previousWorld\", data, false);\n }\n }\n else {\n (_c = this._userThinInstanceBuffersStorage.vertexBuffers[kind]) === null || _c === void 0 ? void 0 : _c.dispose();\n this._userThinInstanceBuffersStorage.data[kind] = data;\n this._userThinInstanceBuffersStorage.sizes[kind] = newSize;\n this._userThinInstanceBuffersStorage.vertexBuffers[kind] = new VertexBuffer(this.getEngine(), data, kind, true, false, stride, true);\n this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[kind]);\n }\n }\n};\nMesh.prototype._thinInstanceInitializeUserStorage = function () {\n if (!this._userThinInstanceBuffersStorage) {\n this._userThinInstanceBuffersStorage = {\n data: {},\n sizes: {},\n vertexBuffers: {},\n strides: {},\n };\n }\n};\nMesh.prototype._disposeThinInstanceSpecificData = function () {\n var _a;\n if ((_a = this._thinInstanceDataStorage) === null || _a === void 0 ? void 0 : _a.matrixBuffer) {\n this._thinInstanceDataStorage.matrixBuffer.dispose();\n this._thinInstanceDataStorage.matrixBuffer = null;\n }\n};\n//# sourceMappingURL=thinInstanceMesh.js.map","export {};\n//# sourceMappingURL=INavigationEngine.js.map","import { Logger } from \"../../Misc/logger.js\";\nimport { VertexData } from \"../../Meshes/mesh.vertexData.js\";\nimport { Mesh } from \"../../Meshes/mesh.js\";\nimport { Epsilon, Vector3, Matrix } from \"../../Maths/math.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { VertexBuffer } from \"../../Buffers/buffer.js\";\n/**\n * RecastJS navigation plugin\n */\nexport class RecastJSPlugin {\n /**\n * Initializes the recastJS plugin\n * @param recastInjection can be used to inject your own recast reference\n */\n constructor(recastInjection = Recast) {\n /**\n * Reference to the Recast library\n */\n this.bjsRECAST = {};\n /**\n * plugin name\n */\n this.name = \"RecastJSPlugin\";\n this._maximumSubStepCount = 10;\n this._timeStep = 1 / 60;\n this._timeFactor = 1;\n this._worker = null;\n if (typeof recastInjection === \"function\") {\n Logger.Error(\"RecastJS is not ready. Please make sure you await Recast() before using the plugin.\");\n }\n else {\n this.bjsRECAST = recastInjection;\n }\n if (!this.isSupported()) {\n Logger.Error(\"RecastJS is not available. Please make sure you included the js file.\");\n return;\n }\n this.setTimeStep();\n this._tempVec1 = new this.bjsRECAST.Vec3();\n this._tempVec2 = new this.bjsRECAST.Vec3();\n }\n /**\n * Set worker URL to be used when generating a new navmesh\n * @param workerURL url string\n * @returns boolean indicating if worker is created\n */\n setWorkerURL(workerURL) {\n if (window && window.Worker) {\n this._worker = new Worker(workerURL);\n return true;\n }\n return false;\n }\n /**\n * Set the time step of the navigation tick update.\n * Default is 1/60.\n * A value of 0 will disable fixed time update\n * @param newTimeStep the new timestep to apply to this world.\n */\n setTimeStep(newTimeStep = 1 / 60) {\n this._timeStep = newTimeStep;\n }\n /**\n * Get the time step of the navigation tick update.\n * @returns the current time step\n */\n getTimeStep() {\n return this._timeStep;\n }\n /**\n * If delta time in navigation tick update is greater than the time step\n * a number of sub iterations are done. If more iterations are need to reach deltatime\n * they will be discarded.\n * A value of 0 will set to no maximum and update will use as many substeps as needed\n * @param newStepCount the maximum number of iterations\n */\n setMaximumSubStepCount(newStepCount = 10) {\n this._maximumSubStepCount = newStepCount;\n }\n /**\n * Get the maximum number of iterations per navigation tick update\n * @returns the maximum number of iterations\n */\n getMaximumSubStepCount() {\n return this._maximumSubStepCount;\n }\n /**\n * Time factor applied when updating crowd agents (default 1). A value of 0 will pause crowd updates.\n * @param value the time factor applied at update\n */\n set timeFactor(value) {\n this._timeFactor = Math.max(value, 0);\n }\n /**\n * Get the time factor used for crowd agent update\n * @returns the time factor\n */\n get timeFactor() {\n return this._timeFactor;\n }\n /**\n * Creates a navigation mesh\n * @param meshes array of all the geometry used to compute the navigation mesh\n * @param parameters bunch of parameters used to filter geometry\n * @param completion callback when data is available from the worker. Not used without a worker\n */\n createNavMesh(meshes, parameters, completion) {\n if (this._worker && !completion) {\n console.warn(\"A worker is avaible but no completion callback. Defaulting to blocking navmesh creation\");\n }\n else if (!this._worker && completion) {\n console.warn(\"A completion callback is avaible but no worker. Defaulting to blocking navmesh creation\");\n }\n this.navMesh = new this.bjsRECAST.NavMesh();\n let index;\n let tri;\n let pt;\n const indices = [];\n const positions = [];\n let offset = 0;\n for (index = 0; index < meshes.length; index++) {\n if (meshes[index]) {\n const mesh = meshes[index];\n const meshIndices = mesh.getIndices();\n if (!meshIndices) {\n continue;\n }\n const meshPositions = mesh.getVerticesData(VertexBuffer.PositionKind, false, false);\n if (!meshPositions) {\n continue;\n }\n const worldMatrices = [];\n const worldMatrix = mesh.computeWorldMatrix(true);\n if (mesh.hasThinInstances) {\n const thinMatrices = mesh.thinInstanceGetWorldMatrices();\n for (let instanceIndex = 0; instanceIndex < thinMatrices.length; instanceIndex++) {\n const tmpMatrix = new Matrix();\n const thinMatrix = thinMatrices[instanceIndex];\n thinMatrix.multiplyToRef(worldMatrix, tmpMatrix);\n worldMatrices.push(tmpMatrix);\n }\n }\n else {\n worldMatrices.push(worldMatrix);\n }\n for (let matrixIndex = 0; matrixIndex < worldMatrices.length; matrixIndex++) {\n const wm = worldMatrices[matrixIndex];\n for (tri = 0; tri < meshIndices.length; tri++) {\n indices.push(meshIndices[tri] + offset);\n }\n const transformed = Vector3.Zero();\n const position = Vector3.Zero();\n for (pt = 0; pt < meshPositions.length; pt += 3) {\n Vector3.FromArrayToRef(meshPositions, pt, position);\n Vector3.TransformCoordinatesToRef(position, wm, transformed);\n positions.push(transformed.x, transformed.y, transformed.z);\n }\n offset += meshPositions.length / 3;\n }\n }\n }\n if (this._worker && completion) {\n // spawn worker and send message\n this._worker.postMessage([positions, offset, indices, indices.length, parameters]);\n this._worker.onmessage = function (e) {\n completion(e.data);\n };\n }\n else {\n // blocking calls\n const rc = new this.bjsRECAST.rcConfig();\n rc.cs = parameters.cs;\n rc.ch = parameters.ch;\n rc.borderSize = parameters.borderSize ? parameters.borderSize : 0;\n rc.tileSize = parameters.tileSize ? parameters.tileSize : 0;\n rc.walkableSlopeAngle = parameters.walkableSlopeAngle;\n rc.walkableHeight = parameters.walkableHeight;\n rc.walkableClimb = parameters.walkableClimb;\n rc.walkableRadius = parameters.walkableRadius;\n rc.maxEdgeLen = parameters.maxEdgeLen;\n rc.maxSimplificationError = parameters.maxSimplificationError;\n rc.minRegionArea = parameters.minRegionArea;\n rc.mergeRegionArea = parameters.mergeRegionArea;\n rc.maxVertsPerPoly = parameters.maxVertsPerPoly;\n rc.detailSampleDist = parameters.detailSampleDist;\n rc.detailSampleMaxError = parameters.detailSampleMaxError;\n this.navMesh.build(positions, offset, indices, indices.length, rc);\n }\n }\n /**\n * Create a navigation mesh debug mesh\n * @param scene is where the mesh will be added\n * @returns debug display mesh\n */\n createDebugNavMesh(scene) {\n let tri;\n let pt;\n const debugNavMesh = this.navMesh.getDebugNavMesh();\n const triangleCount = debugNavMesh.getTriangleCount();\n const indices = [];\n const positions = [];\n for (tri = 0; tri < triangleCount * 3; tri++) {\n indices.push(tri);\n }\n for (tri = 0; tri < triangleCount; tri++) {\n for (pt = 0; pt < 3; pt++) {\n const point = debugNavMesh.getTriangle(tri).getPoint(pt);\n positions.push(point.x, point.y, point.z);\n }\n }\n const mesh = new Mesh(\"NavMeshDebug\", scene);\n const vertexData = new VertexData();\n vertexData.indices = indices;\n vertexData.positions = positions;\n vertexData.applyToMesh(mesh, false);\n return mesh;\n }\n /**\n * Get a navigation mesh constrained position, closest to the parameter position\n * @param position world position\n * @returns the closest point to position constrained by the navigation mesh\n */\n getClosestPoint(position) {\n this._tempVec1.x = position.x;\n this._tempVec1.y = position.y;\n this._tempVec1.z = position.z;\n const ret = this.navMesh.getClosestPoint(this._tempVec1);\n const pr = new Vector3(ret.x, ret.y, ret.z);\n return pr;\n }\n /**\n * Get a navigation mesh constrained position, closest to the parameter position\n * @param position world position\n * @param result output the closest point to position constrained by the navigation mesh\n */\n getClosestPointToRef(position, result) {\n this._tempVec1.x = position.x;\n this._tempVec1.y = position.y;\n this._tempVec1.z = position.z;\n const ret = this.navMesh.getClosestPoint(this._tempVec1);\n result.set(ret.x, ret.y, ret.z);\n }\n /**\n * Get a navigation mesh constrained position, within a particular radius\n * @param position world position\n * @param maxRadius the maximum distance to the constrained world position\n * @returns the closest point to position constrained by the navigation mesh\n */\n getRandomPointAround(position, maxRadius) {\n this._tempVec1.x = position.x;\n this._tempVec1.y = position.y;\n this._tempVec1.z = position.z;\n const ret = this.navMesh.getRandomPointAround(this._tempVec1, maxRadius);\n const pr = new Vector3(ret.x, ret.y, ret.z);\n return pr;\n }\n /**\n * Get a navigation mesh constrained position, within a particular radius\n * @param position world position\n * @param maxRadius the maximum distance to the constrained world position\n * @param result output the closest point to position constrained by the navigation mesh\n */\n getRandomPointAroundToRef(position, maxRadius, result) {\n this._tempVec1.x = position.x;\n this._tempVec1.y = position.y;\n this._tempVec1.z = position.z;\n const ret = this.navMesh.getRandomPointAround(this._tempVec1, maxRadius);\n result.set(ret.x, ret.y, ret.z);\n }\n /**\n * Compute the final position from a segment made of destination-position\n * @param position world position\n * @param destination world position\n * @returns the resulting point along the navmesh\n */\n moveAlong(position, destination) {\n this._tempVec1.x = position.x;\n this._tempVec1.y = position.y;\n this._tempVec1.z = position.z;\n this._tempVec2.x = destination.x;\n this._tempVec2.y = destination.y;\n this._tempVec2.z = destination.z;\n const ret = this.navMesh.moveAlong(this._tempVec1, this._tempVec2);\n const pr = new Vector3(ret.x, ret.y, ret.z);\n return pr;\n }\n /**\n * Compute the final position from a segment made of destination-position\n * @param position world position\n * @param destination world position\n * @param result output the resulting point along the navmesh\n */\n moveAlongToRef(position, destination, result) {\n this._tempVec1.x = position.x;\n this._tempVec1.y = position.y;\n this._tempVec1.z = position.z;\n this._tempVec2.x = destination.x;\n this._tempVec2.y = destination.y;\n this._tempVec2.z = destination.z;\n const ret = this.navMesh.moveAlong(this._tempVec1, this._tempVec2);\n result.set(ret.x, ret.y, ret.z);\n }\n /**\n * Compute a navigation path from start to end. Returns an empty array if no path can be computed\n * @param start world position\n * @param end world position\n * @returns array containing world position composing the path\n */\n computePath(start, end) {\n let pt;\n this._tempVec1.x = start.x;\n this._tempVec1.y = start.y;\n this._tempVec1.z = start.z;\n this._tempVec2.x = end.x;\n this._tempVec2.y = end.y;\n this._tempVec2.z = end.z;\n const navPath = this.navMesh.computePath(this._tempVec1, this._tempVec2);\n const pointCount = navPath.getPointCount();\n const positions = [];\n for (pt = 0; pt < pointCount; pt++) {\n const p = navPath.getPoint(pt);\n positions.push(new Vector3(p.x, p.y, p.z));\n }\n return positions;\n }\n /**\n * Create a new Crowd so you can add agents\n * @param maxAgents the maximum agent count in the crowd\n * @param maxAgentRadius the maximum radius an agent can have\n * @param scene to attach the crowd to\n * @returns the crowd you can add agents to\n */\n createCrowd(maxAgents, maxAgentRadius, scene) {\n const crowd = new RecastJSCrowd(this, maxAgents, maxAgentRadius, scene);\n return crowd;\n }\n /**\n * Set the Bounding box extent for doing spatial queries (getClosestPoint, getRandomPointAround, ...)\n * The queries will try to find a solution within those bounds\n * default is (1,1,1)\n * @param extent x,y,z value that define the extent around the queries point of reference\n */\n setDefaultQueryExtent(extent) {\n this._tempVec1.x = extent.x;\n this._tempVec1.y = extent.y;\n this._tempVec1.z = extent.z;\n this.navMesh.setDefaultQueryExtent(this._tempVec1);\n }\n /**\n * Get the Bounding box extent specified by setDefaultQueryExtent\n * @returns the box extent values\n */\n getDefaultQueryExtent() {\n const p = this.navMesh.getDefaultQueryExtent();\n return new Vector3(p.x, p.y, p.z);\n }\n /**\n * build the navmesh from a previously saved state using getNavmeshData\n * @param data the Uint8Array returned by getNavmeshData\n */\n buildFromNavmeshData(data) {\n const nDataBytes = data.length * data.BYTES_PER_ELEMENT;\n const dataPtr = this.bjsRECAST._malloc(nDataBytes);\n const dataHeap = new Uint8Array(this.bjsRECAST.HEAPU8.buffer, dataPtr, nDataBytes);\n dataHeap.set(data);\n const buf = new this.bjsRECAST.NavmeshData();\n buf.dataPointer = dataHeap.byteOffset;\n buf.size = data.length;\n this.navMesh = new this.bjsRECAST.NavMesh();\n this.navMesh.buildFromNavmeshData(buf);\n // Free memory\n this.bjsRECAST._free(dataHeap.byteOffset);\n }\n /**\n * returns the navmesh data that can be used later. The navmesh must be built before retrieving the data\n * @returns data the Uint8Array that can be saved and reused\n */\n getNavmeshData() {\n const navmeshData = this.navMesh.getNavmeshData();\n const arrView = new Uint8Array(this.bjsRECAST.HEAPU8.buffer, navmeshData.dataPointer, navmeshData.size);\n const ret = new Uint8Array(navmeshData.size);\n ret.set(arrView);\n this.navMesh.freeNavmeshData(navmeshData);\n return ret;\n }\n /**\n * Get the Bounding box extent result specified by setDefaultQueryExtent\n * @param result output the box extent values\n */\n getDefaultQueryExtentToRef(result) {\n const p = this.navMesh.getDefaultQueryExtent();\n result.set(p.x, p.y, p.z);\n }\n /**\n * Disposes\n */\n dispose() { }\n /**\n * Creates a cylinder obstacle and add it to the navigation\n * @param position world position\n * @param radius cylinder radius\n * @param height cylinder height\n * @returns the obstacle freshly created\n */\n addCylinderObstacle(position, radius, height) {\n this._tempVec1.x = position.x;\n this._tempVec1.y = position.y;\n this._tempVec1.z = position.z;\n return this.navMesh.addCylinderObstacle(this._tempVec1, radius, height);\n }\n /**\n * Creates an oriented box obstacle and add it to the navigation\n * @param position world position\n * @param extent box size\n * @param angle angle in radians of the box orientation on Y axis\n * @returns the obstacle freshly created\n */\n addBoxObstacle(position, extent, angle) {\n this._tempVec1.x = position.x;\n this._tempVec1.y = position.y;\n this._tempVec1.z = position.z;\n this._tempVec2.x = extent.x;\n this._tempVec2.y = extent.y;\n this._tempVec2.z = extent.z;\n return this.navMesh.addBoxObstacle(this._tempVec1, this._tempVec2, angle);\n }\n /**\n * Removes an obstacle created by addCylinderObstacle or addBoxObstacle\n * @param obstacle obstacle to remove from the navigation\n */\n removeObstacle(obstacle) {\n this.navMesh.removeObstacle(obstacle);\n }\n /**\n * If this plugin is supported\n * @returns true if plugin is supported\n */\n isSupported() {\n return this.bjsRECAST !== undefined;\n }\n}\n/**\n * Recast detour crowd implementation\n */\nexport class RecastJSCrowd {\n /**\n * Constructor\n * @param plugin recastJS plugin\n * @param maxAgents the maximum agent count in the crowd\n * @param maxAgentRadius the maximum radius an agent can have\n * @param scene to attach the crowd to\n * @returns the crowd you can add agents to\n */\n constructor(plugin, maxAgents, maxAgentRadius, scene) {\n /**\n * Link to the detour crowd\n */\n this.recastCrowd = {};\n /**\n * One transform per agent\n */\n this.transforms = new Array();\n /**\n * All agents created\n */\n this.agents = new Array();\n /**\n * agents reach radius\n */\n this.reachRadii = new Array();\n /**\n * true when a destination is active for an agent and notifier hasn't been notified of reach\n */\n this._agentDestinationArmed = new Array();\n /**\n * agent current target\n */\n this._agentDestination = new Array();\n /**\n * Observer for crowd updates\n */\n this._onBeforeAnimationsObserver = null;\n /**\n * Fires each time an agent is in reach radius of its destination\n */\n this.onReachTargetObservable = new Observable();\n this.bjsRECASTPlugin = plugin;\n this.recastCrowd = new this.bjsRECASTPlugin.bjsRECAST.Crowd(maxAgents, maxAgentRadius, this.bjsRECASTPlugin.navMesh.getNavMesh());\n this._scene = scene;\n this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(() => {\n this.update(scene.getEngine().getDeltaTime() * 0.001 * plugin.timeFactor);\n });\n }\n /**\n * Add a new agent to the crowd with the specified parameter a corresponding transformNode.\n * You can attach anything to that node. The node position is updated in the scene update tick.\n * @param pos world position that will be constrained by the navigation mesh\n * @param parameters agent parameters\n * @param transform hooked to the agent that will be update by the scene\n * @returns agent index\n */\n addAgent(pos, parameters, transform) {\n const agentParams = new this.bjsRECASTPlugin.bjsRECAST.dtCrowdAgentParams();\n agentParams.radius = parameters.radius;\n agentParams.height = parameters.height;\n agentParams.maxAcceleration = parameters.maxAcceleration;\n agentParams.maxSpeed = parameters.maxSpeed;\n agentParams.collisionQueryRange = parameters.collisionQueryRange;\n agentParams.pathOptimizationRange = parameters.pathOptimizationRange;\n agentParams.separationWeight = parameters.separationWeight;\n agentParams.updateFlags = 7;\n agentParams.obstacleAvoidanceType = 0;\n agentParams.queryFilterType = 0;\n agentParams.userData = 0;\n const agentIndex = this.recastCrowd.addAgent(new this.bjsRECASTPlugin.bjsRECAST.Vec3(pos.x, pos.y, pos.z), agentParams);\n this.transforms.push(transform);\n this.agents.push(agentIndex);\n this.reachRadii.push(parameters.reachRadius ? parameters.reachRadius : parameters.radius);\n this._agentDestinationArmed.push(false);\n this._agentDestination.push(new Vector3(0, 0, 0));\n return agentIndex;\n }\n /**\n * Returns the agent position in world space\n * @param index agent index returned by addAgent\n * @returns world space position\n */\n getAgentPosition(index) {\n const agentPos = this.recastCrowd.getAgentPosition(index);\n return new Vector3(agentPos.x, agentPos.y, agentPos.z);\n }\n /**\n * Returns the agent position result in world space\n * @param index agent index returned by addAgent\n * @param result output world space position\n */\n getAgentPositionToRef(index, result) {\n const agentPos = this.recastCrowd.getAgentPosition(index);\n result.set(agentPos.x, agentPos.y, agentPos.z);\n }\n /**\n * Returns the agent velocity in world space\n * @param index agent index returned by addAgent\n * @returns world space velocity\n */\n getAgentVelocity(index) {\n const agentVel = this.recastCrowd.getAgentVelocity(index);\n return new Vector3(agentVel.x, agentVel.y, agentVel.z);\n }\n /**\n * Returns the agent velocity result in world space\n * @param index agent index returned by addAgent\n * @param result output world space velocity\n */\n getAgentVelocityToRef(index, result) {\n const agentVel = this.recastCrowd.getAgentVelocity(index);\n result.set(agentVel.x, agentVel.y, agentVel.z);\n }\n /**\n * Returns the agent next target point on the path\n * @param index agent index returned by addAgent\n * @returns world space position\n */\n getAgentNextTargetPath(index) {\n const pathTargetPos = this.recastCrowd.getAgentNextTargetPath(index);\n return new Vector3(pathTargetPos.x, pathTargetPos.y, pathTargetPos.z);\n }\n /**\n * Returns the agent next target point on the path\n * @param index agent index returned by addAgent\n * @param result output world space position\n */\n getAgentNextTargetPathToRef(index, result) {\n const pathTargetPos = this.recastCrowd.getAgentNextTargetPath(index);\n result.set(pathTargetPos.x, pathTargetPos.y, pathTargetPos.z);\n }\n /**\n * Gets the agent state\n * @param index agent index returned by addAgent\n * @returns agent state\n */\n getAgentState(index) {\n return this.recastCrowd.getAgentState(index);\n }\n /**\n * returns true if the agent in over an off mesh link connection\n * @param index agent index returned by addAgent\n * @returns true if over an off mesh link connection\n */\n overOffmeshConnection(index) {\n return this.recastCrowd.overOffmeshConnection(index);\n }\n /**\n * Asks a particular agent to go to a destination. That destination is constrained by the navigation mesh\n * @param index agent index returned by addAgent\n * @param destination targeted world position\n */\n agentGoto(index, destination) {\n this.recastCrowd.agentGoto(index, new this.bjsRECASTPlugin.bjsRECAST.Vec3(destination.x, destination.y, destination.z));\n // arm observer\n const item = this.agents.indexOf(index);\n if (item > -1) {\n this._agentDestinationArmed[item] = true;\n this._agentDestination[item].set(destination.x, destination.y, destination.z);\n }\n }\n /**\n * Teleport the agent to a new position\n * @param index agent index returned by addAgent\n * @param destination targeted world position\n */\n agentTeleport(index, destination) {\n this.recastCrowd.agentTeleport(index, new this.bjsRECASTPlugin.bjsRECAST.Vec3(destination.x, destination.y, destination.z));\n }\n /**\n * Update agent parameters\n * @param index agent index returned by addAgent\n * @param parameters agent parameters\n */\n updateAgentParameters(index, parameters) {\n const agentParams = this.recastCrowd.getAgentParameters(index);\n if (parameters.radius !== undefined) {\n agentParams.radius = parameters.radius;\n }\n if (parameters.height !== undefined) {\n agentParams.height = parameters.height;\n }\n if (parameters.maxAcceleration !== undefined) {\n agentParams.maxAcceleration = parameters.maxAcceleration;\n }\n if (parameters.maxSpeed !== undefined) {\n agentParams.maxSpeed = parameters.maxSpeed;\n }\n if (parameters.collisionQueryRange !== undefined) {\n agentParams.collisionQueryRange = parameters.collisionQueryRange;\n }\n if (parameters.pathOptimizationRange !== undefined) {\n agentParams.pathOptimizationRange = parameters.pathOptimizationRange;\n }\n if (parameters.separationWeight !== undefined) {\n agentParams.separationWeight = parameters.separationWeight;\n }\n this.recastCrowd.setAgentParameters(index, agentParams);\n }\n /**\n * remove a particular agent previously created\n * @param index agent index returned by addAgent\n */\n removeAgent(index) {\n this.recastCrowd.removeAgent(index);\n const item = this.agents.indexOf(index);\n if (item > -1) {\n this.agents.splice(item, 1);\n this.transforms.splice(item, 1);\n this.reachRadii.splice(item, 1);\n this._agentDestinationArmed.splice(item, 1);\n this._agentDestination.splice(item, 1);\n }\n }\n /**\n * get the list of all agents attached to this crowd\n * @returns list of agent indices\n */\n getAgents() {\n return this.agents;\n }\n /**\n * Tick update done by the Scene. Agent position/velocity/acceleration is updated by this function\n * @param deltaTime in seconds\n */\n update(deltaTime) {\n // update obstacles\n this.bjsRECASTPlugin.navMesh.update();\n if (deltaTime <= Epsilon) {\n return;\n }\n // update crowd\n const timeStep = this.bjsRECASTPlugin.getTimeStep();\n const maxStepCount = this.bjsRECASTPlugin.getMaximumSubStepCount();\n if (timeStep <= Epsilon) {\n this.recastCrowd.update(deltaTime);\n }\n else {\n let iterationCount = Math.floor(deltaTime / timeStep);\n if (maxStepCount && iterationCount > maxStepCount) {\n iterationCount = maxStepCount;\n }\n if (iterationCount < 1) {\n iterationCount = 1;\n }\n const step = deltaTime / iterationCount;\n for (let i = 0; i < iterationCount; i++) {\n this.recastCrowd.update(step);\n }\n }\n // update transforms\n for (let index = 0; index < this.agents.length; index++) {\n // update transform position\n const agentIndex = this.agents[index];\n const agentPosition = this.getAgentPosition(agentIndex);\n this.transforms[index].position = agentPosition;\n // check agent reach destination\n if (this._agentDestinationArmed[index]) {\n const dx = agentPosition.x - this._agentDestination[index].x;\n const dz = agentPosition.z - this._agentDestination[index].z;\n const radius = this.reachRadii[index];\n const groundY = this._agentDestination[index].y - this.reachRadii[index];\n const ceilingY = this._agentDestination[index].y + this.reachRadii[index];\n const distanceXZSquared = dx * dx + dz * dz;\n if (agentPosition.y > groundY && agentPosition.y < ceilingY && distanceXZSquared < radius * radius) {\n this.onReachTargetObservable.notifyObservers({ agentIndex: agentIndex, destination: this._agentDestination[index] });\n this._agentDestinationArmed[index] = false;\n }\n }\n }\n }\n /**\n * Set the Bounding box extent for doing spatial queries (getClosestPoint, getRandomPointAround, ...)\n * The queries will try to find a solution within those bounds\n * default is (1,1,1)\n * @param extent x,y,z value that define the extent around the queries point of reference\n */\n setDefaultQueryExtent(extent) {\n const ext = new this.bjsRECASTPlugin.bjsRECAST.Vec3(extent.x, extent.y, extent.z);\n this.recastCrowd.setDefaultQueryExtent(ext);\n }\n /**\n * Get the Bounding box extent specified by setDefaultQueryExtent\n * @returns the box extent values\n */\n getDefaultQueryExtent() {\n const p = this.recastCrowd.getDefaultQueryExtent();\n return new Vector3(p.x, p.y, p.z);\n }\n /**\n * Get the Bounding box extent result specified by setDefaultQueryExtent\n * @param result output the box extent values\n */\n getDefaultQueryExtentToRef(result) {\n const p = this.recastCrowd.getDefaultQueryExtent();\n result.set(p.x, p.y, p.z);\n }\n /**\n * Get the next corner points composing the path (max 4 points)\n * @param index agent index returned by addAgent\n * @returns array containing world position composing the path\n */\n getCorners(index) {\n let pt;\n const navPath = this.recastCrowd.getCorners(index);\n const pointCount = navPath.getPointCount();\n const positions = [];\n for (pt = 0; pt < pointCount; pt++) {\n const p = navPath.getPoint(pt);\n positions.push(new Vector3(p.x, p.y, p.z));\n }\n return positions;\n }\n /**\n * Release all resources\n */\n dispose() {\n this.recastCrowd.destroy();\n this._scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);\n this._onBeforeAnimationsObserver = null;\n this.onReachTargetObservable.clear();\n }\n}\n//# sourceMappingURL=recastJSPlugin.js.map","import { Tools } from \"../Misc/tools.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { GetTGAHeader } from \"../Misc/tga.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { WebRequest } from \"../Misc/webRequest.js\";\n// Sets the default offline provider to Babylon.js\nEngine.OfflineProviderFactory = (urlToScene, callbackManifestChecked, disableManifestCheck = false) => {\n return new Database(urlToScene, callbackManifestChecked, disableManifestCheck);\n};\n/**\n * Class used to enable access to IndexedDB\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimizeCached\n */\nexport class Database {\n /**\n * Gets a boolean indicating if scene must be saved in the database\n */\n get enableSceneOffline() {\n return this._enableSceneOffline;\n }\n /**\n * Gets a boolean indicating if textures must be saved in the database\n */\n get enableTexturesOffline() {\n return this._enableTexturesOffline;\n }\n /**\n * Creates a new Database\n * @param urlToScene defines the url to load the scene\n * @param callbackManifestChecked defines the callback to use when manifest is checked\n * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)\n */\n constructor(urlToScene, callbackManifestChecked, disableManifestCheck = false) {\n // Handling various flavors of prefixed version of IndexedDB\n this._idbFactory = (typeof indexedDB !== \"undefined\" ? indexedDB : undefined);\n this._currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);\n this._db = null;\n this._enableSceneOffline = false;\n this._enableTexturesOffline = false;\n this._manifestVersionFound = 0;\n this._mustUpdateRessources = false;\n this._hasReachedQuota = false;\n if (!Database.IDBStorageEnabled) {\n callbackManifestChecked(true);\n }\n else {\n if (disableManifestCheck) {\n this._enableSceneOffline = true;\n this._enableTexturesOffline = true;\n this._manifestVersionFound = 1;\n Tools.SetImmediate(() => {\n callbackManifestChecked(true);\n });\n }\n else {\n this._checkManifestFile(callbackManifestChecked);\n }\n }\n }\n _checkManifestFile(callbackManifestChecked) {\n const noManifestFile = () => {\n this._enableSceneOffline = false;\n this._enableTexturesOffline = false;\n callbackManifestChecked(false);\n };\n const createManifestURL = () => {\n try {\n // make sure we have a valid URL.\n if (typeof URL === \"function\" && this._currentSceneUrl.indexOf(\"http\") === 0) {\n // we don't have the base url, so the URL string must have a protocol\n const url = new URL(this._currentSceneUrl);\n url.pathname += \".manifest\";\n return url.toString();\n }\n }\n catch (e) {\n // defensive - if this fails for any reason, fall back to the older method\n }\n return `${this._currentSceneUrl}.manifest`;\n };\n let timeStampUsed = false;\n let manifestURL = createManifestURL();\n const xhr = new WebRequest();\n if (navigator.onLine) {\n // Adding a timestamp to by-pass browsers' cache\n timeStampUsed = true;\n manifestURL = manifestURL + (manifestURL.match(/\\?/) == null ? \"?\" : \"&\") + Date.now();\n }\n xhr.open(\"GET\", manifestURL);\n xhr.addEventListener(\"load\", () => {\n if (xhr.status === 200 || Database._ValidateXHRData(xhr, 1)) {\n try {\n const manifestFile = JSON.parse(xhr.response);\n this._enableSceneOffline = manifestFile.enableSceneOffline;\n this._enableTexturesOffline = manifestFile.enableTexturesOffline && Database._IsUASupportingBlobStorage;\n if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {\n this._manifestVersionFound = manifestFile.version;\n }\n callbackManifestChecked(true);\n }\n catch (ex) {\n noManifestFile();\n }\n }\n else {\n noManifestFile();\n }\n }, false);\n xhr.addEventListener(\"error\", () => {\n if (timeStampUsed) {\n timeStampUsed = false;\n // Let's retry without the timeStamp\n // It could fail when coupled with HTML5 Offline API\n const retryManifestURL = createManifestURL();\n xhr.open(\"GET\", retryManifestURL);\n xhr.send();\n }\n else {\n noManifestFile();\n }\n }, false);\n try {\n xhr.send();\n }\n catch (ex) {\n Logger.Error(\"Error on XHR send request.\");\n callbackManifestChecked(false);\n }\n }\n /**\n * Open the database and make it available\n * @param successCallback defines the callback to call on success\n * @param errorCallback defines the callback to call on error\n */\n open(successCallback, errorCallback) {\n const handleError = () => {\n this._isSupported = false;\n if (errorCallback) {\n errorCallback();\n }\n };\n if (!this._idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {\n // Your browser doesn't support IndexedDB\n this._isSupported = false;\n if (errorCallback) {\n errorCallback();\n }\n }\n else {\n // If the DB hasn't been opened or created yet\n if (!this._db) {\n this._hasReachedQuota = false;\n this._isSupported = true;\n const request = this._idbFactory.open(\"babylonjs\", 1);\n // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB\n request.onerror = () => {\n handleError();\n };\n // executes when a version change transaction cannot complete due to other active transactions\n request.onblocked = () => {\n Logger.Error(\"IDB request blocked. Please reload the page.\");\n handleError();\n };\n // DB has been opened successfully\n request.onsuccess = () => {\n this._db = request.result;\n successCallback();\n };\n // Initialization of the DB. Creating Scenes & Textures stores\n request.onupgradeneeded = (event) => {\n this._db = event.target.result;\n if (this._db) {\n try {\n this._db.createObjectStore(\"scenes\", { keyPath: \"sceneUrl\" });\n this._db.createObjectStore(\"versions\", { keyPath: \"sceneUrl\" });\n this._db.createObjectStore(\"textures\", { keyPath: \"textureUrl\" });\n }\n catch (ex) {\n Logger.Error(\"Error while creating object stores. Exception: \" + ex.message);\n handleError();\n }\n }\n };\n }\n // DB has already been created and opened\n else {\n if (successCallback) {\n successCallback();\n }\n }\n }\n }\n /**\n * Loads an image from the database\n * @param url defines the url to load from\n * @param image defines the target DOM image\n */\n loadImage(url, image) {\n const completeURL = Database._ReturnFullUrlLocation(url);\n const saveAndLoadImage = () => {\n if (!this._hasReachedQuota && this._db !== null) {\n // the texture is not yet in the DB, let's try to save it\n this._saveImageIntoDBAsync(completeURL, image);\n }\n // If the texture is not in the DB and we've reached the DB quota limit\n // let's load it directly from the web\n else {\n image.src = url;\n }\n };\n if (!this._mustUpdateRessources) {\n this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);\n }\n // First time we're download the images or update requested in the manifest file by a version change\n else {\n saveAndLoadImage();\n }\n }\n _loadImageFromDBAsync(url, image, notInDBCallback) {\n if (this._isSupported && this._db !== null) {\n let texture;\n const transaction = this._db.transaction([\"textures\"]);\n transaction.onabort = () => {\n image.src = url;\n };\n transaction.oncomplete = () => {\n let blobTextureURL;\n if (texture && typeof URL === \"function\") {\n blobTextureURL = URL.createObjectURL(texture.data);\n image.onerror = () => {\n Logger.Error(\"Error loading image from blob URL: \" + blobTextureURL + \" switching back to web url: \" + url);\n image.src = url;\n };\n image.src = blobTextureURL;\n }\n else {\n notInDBCallback();\n }\n };\n const getRequest = transaction.objectStore(\"textures\").get(url);\n getRequest.onsuccess = (event) => {\n texture = event.target.result;\n };\n getRequest.onerror = () => {\n Logger.Error(\"Error loading texture \" + url + \" from DB.\");\n image.src = url;\n };\n }\n else {\n Logger.Error(\"Error: IndexedDB not supported by your browser or BabylonJS Database is not open.\");\n image.src = url;\n }\n }\n _saveImageIntoDBAsync(url, image) {\n let blob;\n if (this._isSupported) {\n // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on\n const generateBlobUrl = () => {\n let blobTextureURL;\n if (blob && typeof URL === \"function\") {\n try {\n blobTextureURL = URL.createObjectURL(blob);\n }\n catch (ex) {\n // Chrome is raising a type error if we're setting the oneTimeOnly parameter\n blobTextureURL = URL.createObjectURL(blob);\n }\n }\n if (blobTextureURL) {\n image.src = blobTextureURL;\n }\n };\n if (Database._IsUASupportingBlobStorage) {\n // Create XHR\n const xhr = new WebRequest();\n xhr.open(\"GET\", url);\n xhr.responseType = \"blob\";\n xhr.addEventListener(\"load\", () => {\n if (xhr.status === 200 && this._db) {\n // Blob as response\n blob = xhr.response;\n const transaction = this._db.transaction([\"textures\"], \"readwrite\");\n // the transaction could abort because of a QuotaExceededError error\n transaction.onabort = (event) => {\n try {\n //backwards compatibility with ts 1.0, srcElement doesn't have an \"error\" according to ts 1.3\n const srcElement = event.target;\n const error = srcElement.error;\n if (error && error.name === \"QuotaExceededError\") {\n this._hasReachedQuota = true;\n }\n }\n catch (ex) { }\n generateBlobUrl();\n };\n transaction.oncomplete = () => {\n generateBlobUrl();\n };\n const newTexture = { textureUrl: url, data: blob };\n try {\n // Put the blob into the dabase\n const addRequest = transaction.objectStore(\"textures\").put(newTexture);\n addRequest.onsuccess = () => { };\n addRequest.onerror = () => {\n generateBlobUrl();\n };\n }\n catch (ex) {\n // \"DataCloneError\" generated by Chrome when you try to inject blob into IndexedDB\n if (ex.code === 25) {\n Database._IsUASupportingBlobStorage = false;\n this._enableTexturesOffline = false;\n }\n image.src = url;\n }\n }\n else {\n image.src = url;\n }\n }, false);\n xhr.addEventListener(\"error\", () => {\n Logger.Error(\"Error in XHR request in BABYLON.Database.\");\n image.src = url;\n }, false);\n xhr.send();\n }\n else {\n image.src = url;\n }\n }\n else {\n Logger.Error(\"Error: IndexedDB not supported by your browser or Babylon.js database is not open.\");\n image.src = url;\n }\n }\n _checkVersionFromDB(url, versionLoaded) {\n const updateVersion = () => {\n // the version is not yet in the DB or we need to update it\n this._saveVersionIntoDBAsync(url, versionLoaded);\n };\n this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);\n }\n _loadVersionFromDBAsync(url, callback, updateInDBCallback) {\n if (this._isSupported && this._db) {\n let version;\n try {\n const transaction = this._db.transaction([\"versions\"]);\n transaction.oncomplete = () => {\n if (version) {\n // If the version in the JSON file is different from the version in DB\n if (this._manifestVersionFound !== version.data) {\n this._mustUpdateRessources = true;\n updateInDBCallback();\n }\n else {\n callback(version.data);\n }\n }\n // version was not found in DB\n else {\n this._mustUpdateRessources = true;\n updateInDBCallback();\n }\n };\n transaction.onabort = () => {\n callback(-1);\n };\n const getRequest = transaction.objectStore(\"versions\").get(url);\n getRequest.onsuccess = (event) => {\n version = event.target.result;\n };\n getRequest.onerror = () => {\n Logger.Error(\"Error loading version for scene \" + url + \" from DB.\");\n callback(-1);\n };\n }\n catch (ex) {\n Logger.Error(\"Error while accessing 'versions' object store (READ OP). Exception: \" + ex.message);\n callback(-1);\n }\n }\n else {\n Logger.Error(\"Error: IndexedDB not supported by your browser or Babylon.js database is not open.\");\n callback(-1);\n }\n }\n _saveVersionIntoDBAsync(url, callback) {\n if (this._isSupported && !this._hasReachedQuota && this._db) {\n try {\n // Open a transaction to the database\n const transaction = this._db.transaction([\"versions\"], \"readwrite\");\n // the transaction could abort because of a QuotaExceededError error\n transaction.onabort = (event) => {\n try {\n //backwards compatibility with ts 1.0, srcElement doesn't have an \"error\" according to ts 1.3\n const error = event.target[\"error\"];\n if (error && error.name === \"QuotaExceededError\") {\n this._hasReachedQuota = true;\n }\n }\n catch (ex) { }\n callback(-1);\n };\n transaction.oncomplete = () => {\n callback(this._manifestVersionFound);\n };\n const newVersion = { sceneUrl: url, data: this._manifestVersionFound };\n // Put the scene into the database\n const addRequest = transaction.objectStore(\"versions\").put(newVersion);\n addRequest.onsuccess = () => { };\n addRequest.onerror = () => {\n Logger.Error(\"Error in DB add version request in BABYLON.Database.\");\n };\n }\n catch (ex) {\n Logger.Error(\"Error while accessing 'versions' object store (WRITE OP). Exception: \" + ex.message);\n callback(-1);\n }\n }\n else {\n callback(-1);\n }\n }\n /**\n * Loads a file from database\n * @param url defines the URL to load from\n * @param sceneLoaded defines a callback to call on success\n * @param progressCallBack defines a callback to call when progress changed\n * @param errorCallback defines a callback to call on error\n * @param useArrayBuffer defines a boolean to use array buffer instead of text string\n */\n loadFile(url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {\n const completeUrl = Database._ReturnFullUrlLocation(url);\n const saveAndLoadFile = () => {\n // the scene is not yet in the DB, let's try to save it\n this._saveFileAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);\n };\n this._checkVersionFromDB(completeUrl, (version) => {\n if (version !== -1) {\n if (!this._mustUpdateRessources) {\n this._loadFileAsync(completeUrl, sceneLoaded, saveAndLoadFile);\n }\n else {\n this._saveFileAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);\n }\n }\n else {\n if (errorCallback) {\n errorCallback();\n }\n }\n });\n }\n _loadFileAsync(url, callback, notInDBCallback) {\n if (this._isSupported && this._db) {\n let targetStore;\n if (url.indexOf(\".babylon\") !== -1) {\n targetStore = \"scenes\";\n }\n else {\n targetStore = \"textures\";\n }\n let file;\n const transaction = this._db.transaction([targetStore]);\n transaction.oncomplete = () => {\n if (file) {\n callback(file.data);\n }\n // file was not found in DB\n else {\n notInDBCallback();\n }\n };\n transaction.onabort = () => {\n notInDBCallback();\n };\n const getRequest = transaction.objectStore(targetStore).get(url);\n getRequest.onsuccess = (event) => {\n file = event.target.result;\n };\n getRequest.onerror = () => {\n Logger.Error(\"Error loading file \" + url + \" from DB.\");\n notInDBCallback();\n };\n }\n else {\n Logger.Error(\"Error: IndexedDB not supported by your browser or BabylonJS Database is not open.\");\n callback();\n }\n }\n _saveFileAsync(url, callback, progressCallback, useArrayBuffer, errorCallback) {\n if (this._isSupported) {\n let targetStore;\n if (url.indexOf(\".babylon\") !== -1) {\n targetStore = \"scenes\";\n }\n else {\n targetStore = \"textures\";\n }\n // Create XHR\n const xhr = new WebRequest();\n let fileData;\n xhr.open(\"GET\", url + (url.match(/\\?/) == null ? \"?\" : \"&\") + Date.now());\n if (useArrayBuffer) {\n xhr.responseType = \"arraybuffer\";\n }\n if (progressCallback) {\n xhr.onprogress = progressCallback;\n }\n xhr.addEventListener(\"load\", () => {\n if (xhr.status === 200 || (xhr.status < 400 && Database._ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {\n // Blob as response\n fileData = !useArrayBuffer ? xhr.responseText : xhr.response;\n if (!this._hasReachedQuota && this._db) {\n // Open a transaction to the database\n const transaction = this._db.transaction([targetStore], \"readwrite\");\n // the transaction could abort because of a QuotaExceededError error\n transaction.onabort = (event) => {\n try {\n //backwards compatibility with ts 1.0, srcElement doesn't have an \"error\" according to ts 1.3\n const error = event.target[\"error\"];\n if (error && error.name === \"QuotaExceededError\") {\n this._hasReachedQuota = true;\n }\n }\n catch (ex) { }\n callback(fileData);\n };\n transaction.oncomplete = () => {\n callback(fileData);\n };\n let newFile;\n if (targetStore === \"scenes\") {\n newFile = { sceneUrl: url, data: fileData, version: this._manifestVersionFound };\n }\n else {\n newFile = { textureUrl: url, data: fileData };\n }\n try {\n // Put the scene into the database\n const addRequest = transaction.objectStore(targetStore).put(newFile);\n addRequest.onsuccess = () => { };\n addRequest.onerror = () => {\n Logger.Error(\"Error in DB add file request in BABYLON.Database.\");\n };\n }\n catch (ex) {\n callback(fileData);\n }\n }\n else {\n callback(fileData);\n }\n }\n else {\n if (xhr.status >= 400 && errorCallback) {\n errorCallback(xhr);\n }\n else {\n callback();\n }\n }\n }, false);\n xhr.addEventListener(\"error\", () => {\n Logger.Error(\"error on XHR request.\");\n errorCallback && errorCallback();\n }, false);\n xhr.send();\n }\n else {\n Logger.Error(\"Error: IndexedDB not supported by your browser or Babylon.js database is not open.\");\n errorCallback && errorCallback();\n }\n }\n /**\n * Validates if xhr data is correct\n * @param xhr defines the request to validate\n * @param dataType defines the expected data type\n * @returns true if data is correct\n */\n static _ValidateXHRData(xhr, dataType = 7) {\n // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all\n try {\n if (dataType & 1) {\n if (xhr.responseText && xhr.responseText.length > 0) {\n return true;\n }\n else if (dataType === 1) {\n return false;\n }\n }\n if (dataType & 2) {\n // Check header width and height since there is no \"TGA\" magic number\n const tgaHeader = GetTGAHeader(xhr.response);\n if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {\n return true;\n }\n else if (dataType === 2) {\n return false;\n }\n }\n if (dataType & 4) {\n // Check for the \"DDS\" magic number\n const ddsHeader = new Uint8Array(xhr.response, 0, 3);\n if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {\n return true;\n }\n else {\n return false;\n }\n }\n }\n catch (e) {\n // Global protection\n }\n return false;\n }\n}\n/** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */\nDatabase._IsUASupportingBlobStorage = true;\n/**\n * Gets a boolean indicating if Database storage is enabled (off by default)\n */\nDatabase.IDBStorageEnabled = false;\nDatabase._ParseURL = (url) => {\n const a = document.createElement(\"a\");\n a.href = url;\n const urlWithoutHash = url.substring(0, url.lastIndexOf(\"#\"));\n const fileName = url.substring(urlWithoutHash.lastIndexOf(\"/\") + 1, url.length);\n const absLocation = url.substring(0, url.indexOf(fileName, 0));\n return absLocation;\n};\nDatabase._ReturnFullUrlLocation = (url) => {\n if (url.indexOf(\"http:/\") === -1 && url.indexOf(\"https:/\") === -1 && typeof window !== \"undefined\") {\n return Database._ParseURL(window.location.href) + url;\n }\n else {\n return url;\n }\n};\n//# sourceMappingURL=database.js.map","/** @internal */\nexport class UniformBufferEffectCommonAccessor {\n _isUbo(uboOrEffect) {\n return uboOrEffect.addUniform !== undefined;\n }\n constructor(uboOrEffect) {\n if (this._isUbo(uboOrEffect)) {\n this.setMatrix3x3 = uboOrEffect.updateMatrix3x3.bind(uboOrEffect);\n this.setMatrix2x2 = uboOrEffect.updateMatrix2x2.bind(uboOrEffect);\n this.setFloat = uboOrEffect.updateFloat.bind(uboOrEffect);\n this.setFloat2 = uboOrEffect.updateFloat2.bind(uboOrEffect);\n this.setFloat3 = uboOrEffect.updateFloat3.bind(uboOrEffect);\n this.setFloat4 = uboOrEffect.updateFloat4.bind(uboOrEffect);\n this.setFloatArray = uboOrEffect.updateFloatArray.bind(uboOrEffect);\n this.setArray = uboOrEffect.updateArray.bind(uboOrEffect);\n this.setIntArray = uboOrEffect.updateIntArray.bind(uboOrEffect);\n this.setMatrix = uboOrEffect.updateMatrix.bind(uboOrEffect);\n this.setMatrices = uboOrEffect.updateMatrices.bind(uboOrEffect);\n this.setVector3 = uboOrEffect.updateVector3.bind(uboOrEffect);\n this.setVector4 = uboOrEffect.updateVector4.bind(uboOrEffect);\n this.setColor3 = uboOrEffect.updateColor3.bind(uboOrEffect);\n this.setColor4 = uboOrEffect.updateColor4.bind(uboOrEffect);\n this.setDirectColor4 = uboOrEffect.updateDirectColor4.bind(uboOrEffect);\n this.setInt = uboOrEffect.updateInt.bind(uboOrEffect);\n this.setInt2 = uboOrEffect.updateInt2.bind(uboOrEffect);\n this.setInt3 = uboOrEffect.updateInt3.bind(uboOrEffect);\n this.setInt4 = uboOrEffect.updateInt4.bind(uboOrEffect);\n }\n else {\n this.setMatrix3x3 = uboOrEffect.setMatrix3x3.bind(uboOrEffect);\n this.setMatrix2x2 = uboOrEffect.setMatrix2x2.bind(uboOrEffect);\n this.setFloat = uboOrEffect.setFloat.bind(uboOrEffect);\n this.setFloat2 = uboOrEffect.setFloat2.bind(uboOrEffect);\n this.setFloat3 = uboOrEffect.setFloat3.bind(uboOrEffect);\n this.setFloat4 = uboOrEffect.setFloat4.bind(uboOrEffect);\n this.setFloatArray = uboOrEffect.setFloatArray.bind(uboOrEffect);\n this.setArray = uboOrEffect.setArray.bind(uboOrEffect);\n this.setIntArray = uboOrEffect.setIntArray.bind(uboOrEffect);\n this.setMatrix = uboOrEffect.setMatrix.bind(uboOrEffect);\n this.setMatrices = uboOrEffect.setMatrices.bind(uboOrEffect);\n this.setVector3 = uboOrEffect.setVector3.bind(uboOrEffect);\n this.setVector4 = uboOrEffect.setVector4.bind(uboOrEffect);\n this.setColor3 = uboOrEffect.setColor3.bind(uboOrEffect);\n this.setColor4 = uboOrEffect.setColor4.bind(uboOrEffect);\n this.setDirectColor4 = uboOrEffect.setDirectColor4.bind(uboOrEffect);\n this.setInt = uboOrEffect.setInt.bind(uboOrEffect);\n this.setInt2 = uboOrEffect.setInt2.bind(uboOrEffect);\n this.setInt3 = uboOrEffect.setInt3.bind(uboOrEffect);\n this.setInt4 = uboOrEffect.setInt4.bind(uboOrEffect);\n }\n }\n}\n//# sourceMappingURL=uniformBufferEffectCommonAccessor.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"gpuUpdateParticlesPixelShader\";\nconst shader = `#version 300 es\nvoid main() {\rdiscard;\r}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const gpuUpdateParticlesPixelShader = { name, shader };\n//# sourceMappingURL=gpuUpdateParticles.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"gpuUpdateParticlesVertexShader\";\nconst shader = `#version 300 es\n#define PI 3.14159\nuniform float currentCount;\runiform float timeDelta;\runiform float stopFactor;\r#ifndef LOCAL\nuniform mat4 emitterWM;\r#endif\nuniform vec2 lifeTime;\runiform vec2 emitPower;\runiform vec2 sizeRange;\runiform vec4 scaleRange;\r#ifndef COLORGRADIENTS\nuniform vec4 color1;\runiform vec4 color2;\r#endif\nuniform vec3 gravity;\runiform sampler2D randomSampler;\runiform sampler2D randomSampler2;\runiform vec4 angleRange;\r#ifdef BOXEMITTER\nuniform vec3 direction1;\runiform vec3 direction2;\runiform vec3 minEmitBox;\runiform vec3 maxEmitBox;\r#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\runiform vec3 direction2;\r#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\runiform float radiusRange;\runiform float directionRandomizer;\r#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\runiform float radiusRange;\r#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\runiform vec3 direction2;\r#else\nuniform float directionRandomizer;\r#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\runiform float height;\runiform float radiusRange;\r#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\runiform vec3 direction2;\r#else\nuniform float directionRandomizer;\r#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\runiform float coneAngle;\runiform vec2 height;\runiform float directionRandomizer;\r#endif\nin vec3 position;\r#ifdef CUSTOMEMITTER\nin vec3 initialPosition;\r#endif\nin float age;\rin float life;\rin vec4 seed;\rin vec3 size;\r#ifndef COLORGRADIENTS\nin vec4 color;\r#endif\nin vec3 direction;\r#ifndef BILLBOARD\nin vec3 initialDirection;\r#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\r#else\nin vec2 angle;\r#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\r#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\r#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;\rin vec3 noiseCoordinates2;\r#endif\nout vec3 outPosition;\r#ifdef CUSTOMEMITTER\nout vec3 outInitialPosition;\r#endif\nout float outAge;\rout float outLife;\rout vec4 outSeed;\rout vec3 outSize;\r#ifndef COLORGRADIENTS\nout vec4 outColor;\r#endif\nout vec3 outDirection;\r#ifndef BILLBOARD\nout vec3 outInitialDirection;\r#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\r#else\nout vec2 outAngle;\r#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\r#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\r#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;\rout vec3 outNoiseCoordinates2;\r#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\r#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\r#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\r#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\runiform float limitVelocityDamping;\r#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\r#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\runiform sampler2D noiseSampler;\r#endif\n#ifdef ANIMATESHEET\nuniform vec4 cellInfos;\r#endif\nvec3 getRandomVec3(float offset) {\rreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\r}\rvec4 getRandomVec4(float offset) {\rreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\r}\rvoid main() {\rfloat newAge=age+timeDelta; \rif (newAge>=life && stopFactor != 0.) {\rvec3 newPosition;\rvec3 newDirection;\rvec4 randoms=getRandomVec4(seed.x);\routLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\routAge=newAge-life;\routSeed=seed;\r#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\r#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\r#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\routSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \r#ifndef COLORGRADIENTS\noutColor=color1+(color2-color1)*randoms.b;\r#endif\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\routAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\r#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\r#endif \n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\rvec3 randoms3=getRandomVec3(seed.z);\rnewPosition=vec3(0,0,0);\rnewDirection=direction1+(direction2-direction1)*randoms3;\r#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\rvec3 randoms3=getRandomVec3(seed.z);\rnewPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\rnewDirection=direction1+(direction2-direction1)*randoms3; \r#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\rvec3 randoms3=getRandomVec3(seed.z);\rfloat phi=2.0*PI*randoms2.x;\rfloat theta=acos(2.0*randoms2.y-1.0);\rfloat randX=cos(phi)*sin(theta);\rfloat randY=cos(theta);\rfloat randZ=sin(phi)*sin(theta);\rnewPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\rnewDirection=newPosition+directionRandomizer*randoms3; \r#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\rvec3 randoms3=getRandomVec3(seed.z);\rfloat phi=2.0*PI*randoms2.x;\rfloat theta=acos(2.0*randoms2.y-1.0);\rfloat randX=cos(phi)*sin(theta);\rfloat randY=cos(theta);\rfloat randZ=sin(phi)*sin(theta);\rnewPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\r#ifdef DIRECTEDSPHEREEMITTER\nnewDirection=normalize(direction1+(direction2-direction1)*randoms3);\r#else\nnewDirection=normalize(newPosition+directionRandomizer*randoms3);\r#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\rvec3 randoms3=getRandomVec3(seed.z);\rfloat yPos=(randoms2.x-0.5)*height;\rfloat angle=randoms2.y*PI*2.;\rfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\rfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\rfloat xPos=positionRadius*cos(angle);\rfloat zPos=positionRadius*sin(angle);\rnewPosition=vec3(xPos,yPos,zPos);\r#ifdef DIRECTEDCYLINDEREMITTER\nnewDirection=direction1+(direction2-direction1)*randoms3;\r#else\nangle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;\rnewDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));\rnewDirection=normalize(newDirection);\r#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\rfloat s=2.0*PI*randoms2.x;\r#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.0001;\r#else\nfloat h=randoms2.y*height.y;\rh=1.-h*h; \r#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\rlRadius=lRadius*h;\rfloat randX=lRadius*sin(s);\rfloat randZ=lRadius*cos(s);\rfloat randY=h *height.x;\rnewPosition=vec3(randX,randY,randZ); \rif (abs(cos(coneAngle))==1.0) {\rnewDirection=vec3(0.,1.0,0.);\r} else {\rvec3 randoms3=getRandomVec3(seed.z);\rnewDirection=normalize(newPosition+directionRandomizer*randoms3); \r}\r#elif defined(CUSTOMEMITTER)\nnewPosition=initialPosition;\routInitialPosition=initialPosition;\r#else \nnewPosition=vec3(0.,0.,0.);\rnewDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\r#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\r#ifdef LOCAL\noutPosition=newPosition;\r#else\noutPosition=(emitterWM*vec4(newPosition,1.)).xyz;\r#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\r#ifndef BILLBOARD \noutInitialDirection=direction;\r#endif\n#else\n#ifdef LOCAL\nvec3 initial=newDirection;\r#else \nvec3 initial=(emitterWM*vec4(newDirection,0.)).xyz;\r#endif\noutDirection=initial*power;\r#ifndef BILLBOARD \noutInitialDirection=initial;\r#endif\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\r#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\r#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\routNoiseCoordinates2=noiseCoordinates2;\r#endif\n} else {\rfloat directionScale=timeDelta;\routAge=newAge;\rfloat ageGradient=newAge/life;\r#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\r#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\r#endif\n#if defined(CUSTOMEMITTER)\noutPosition=position+(direction-position)*ageGradient; \routInitialPosition=initialPosition;\r#else\noutPosition=position+direction*directionScale;\r#endif\noutLife=life;\routSeed=seed;\r#ifndef COLORGRADIENTS \noutColor=color;\r#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\routSize.yz=size.yz;\r#else\noutSize=size;\r#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\r#endif\n#ifdef CUSTOMEMITTER\noutDirection=direction;\r#else\nvec3 updatedDirection=direction+gravity*timeDelta;\r#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\rfloat currentVelocity=length(updatedDirection);\rif (currentVelocity>limitVelocity) {\rupdatedDirection=updatedDirection*limitVelocityDamping;\r}\r#endif\noutDirection=updatedDirection;\r#ifdef NOISE\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\rfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\rfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\rvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\routDirection=outDirection+force*timeDelta;\routNoiseCoordinates1=noiseCoordinates1;\routNoiseCoordinates2=noiseCoordinates2;\r#endif \n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\routAngle=angle+angularSpeed*timeDelta;\r#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\r#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\rfloat dist=cellInfos.y-cellInfos.x;\r#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\roffsetAge+=cellStartOffset;\r#else\nfloat cellStartOffset=0.;\r#endif \nfloat ratio=0.;\rif (cellInfos.w==1.0) {\rratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);\r}\relse {\rratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);\r}\routCellIndex=float(int(cellInfos.x+ratio*dist));\r#endif\n}\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const gpuUpdateParticlesVertexShader = { name, shader };\n//# sourceMappingURL=gpuUpdateParticles.vertex.js.map","import { Effect } from \"../Materials/effect.js\";\nimport { CustomParticleEmitter } from \"./EmitterTypes/customParticleEmitter.js\";\nimport { UniformBufferEffectCommonAccessor } from \"../Materials/uniformBufferEffectCommonAccessor.js\";\n\nimport { RegisterClass } from \"../Misc/typeStore.js\";\nimport \"../Shaders/gpuUpdateParticles.fragment.js\";\nimport \"../Shaders/gpuUpdateParticles.vertex.js\";\n/** @internal */\nexport class WebGL2ParticleSystem {\n constructor(parent, engine) {\n this._renderVAO = [];\n this._updateVAO = [];\n this.alignDataInBuffer = false;\n this._parent = parent;\n this._engine = engine;\n this._updateEffectOptions = {\n attributes: [\n \"position\",\n \"initialPosition\",\n \"age\",\n \"life\",\n \"seed\",\n \"size\",\n \"color\",\n \"direction\",\n \"initialDirection\",\n \"angle\",\n \"cellIndex\",\n \"cellStartOffset\",\n \"noiseCoordinates1\",\n \"noiseCoordinates2\",\n ],\n uniformsNames: [\n \"currentCount\",\n \"timeDelta\",\n \"emitterWM\",\n \"lifeTime\",\n \"color1\",\n \"color2\",\n \"sizeRange\",\n \"scaleRange\",\n \"gravity\",\n \"emitPower\",\n \"direction1\",\n \"direction2\",\n \"minEmitBox\",\n \"maxEmitBox\",\n \"radius\",\n \"directionRandomizer\",\n \"height\",\n \"coneAngle\",\n \"stopFactor\",\n \"angleRange\",\n \"radiusRange\",\n \"cellInfos\",\n \"noiseStrength\",\n \"limitVelocityDamping\",\n ],\n uniformBuffersNames: [],\n samplers: [\n \"randomSampler\",\n \"randomSampler2\",\n \"sizeGradientSampler\",\n \"angularSpeedGradientSampler\",\n \"velocityGradientSampler\",\n \"limitVelocityGradientSampler\",\n \"noiseSampler\",\n \"dragGradientSampler\",\n ],\n defines: \"\",\n fallbacks: null,\n onCompiled: null,\n onError: null,\n indexParameters: null,\n maxSimultaneousLights: 0,\n transformFeedbackVaryings: [],\n };\n }\n isUpdateBufferCreated() {\n return !!this._updateEffect;\n }\n isUpdateBufferReady() {\n var _a, _b;\n return (_b = (_a = this._updateEffect) === null || _a === void 0 ? void 0 : _a.isReady()) !== null && _b !== void 0 ? _b : false;\n }\n createUpdateBuffer(defines) {\n this._updateEffectOptions.transformFeedbackVaryings = [\"outPosition\"];\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outAge\");\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outSize\");\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outLife\");\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outSeed\");\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outDirection\");\n if (this._parent.particleEmitterType instanceof CustomParticleEmitter) {\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outInitialPosition\");\n }\n if (!this._parent._colorGradientsTexture) {\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outColor\");\n }\n if (!this._parent._isBillboardBased) {\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outInitialDirection\");\n }\n if (this._parent.noiseTexture) {\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outNoiseCoordinates1\");\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outNoiseCoordinates2\");\n }\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outAngle\");\n if (this._parent.isAnimationSheetEnabled) {\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outCellIndex\");\n if (this._parent.spriteRandomStartCell) {\n this._updateEffectOptions.transformFeedbackVaryings.push(\"outCellStartOffset\");\n }\n }\n this._updateEffectOptions.defines = defines;\n this._updateEffect = new Effect(\"gpuUpdateParticles\", this._updateEffectOptions, this._engine);\n return new UniformBufferEffectCommonAccessor(this._updateEffect);\n }\n createVertexBuffers(updateBuffer, renderVertexBuffers) {\n this._updateVAO.push(this._createUpdateVAO(updateBuffer));\n this._renderVAO.push(this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._parent._getWrapper(this._parent.blendMode).effect));\n this._engine.bindArrayBuffer(null);\n }\n createParticleBuffer(data) {\n return data;\n }\n bindDrawBuffers(index) {\n this._engine.bindVertexArrayObject(this._renderVAO[index], null);\n }\n preUpdateParticleBuffer() {\n const engine = this._engine;\n this._engine.enableEffect(this._updateEffect);\n if (!engine.setState) {\n throw new Error(\"GPU particles cannot work without a full Engine. ThinEngine is not supported\");\n }\n }\n updateParticleBuffer(index, targetBuffer, currentActiveCount) {\n this._updateEffect.setTexture(\"randomSampler\", this._parent._randomTexture);\n this._updateEffect.setTexture(\"randomSampler2\", this._parent._randomTexture2);\n if (this._parent._sizeGradientsTexture) {\n this._updateEffect.setTexture(\"sizeGradientSampler\", this._parent._sizeGradientsTexture);\n }\n if (this._parent._angularSpeedGradientsTexture) {\n this._updateEffect.setTexture(\"angularSpeedGradientSampler\", this._parent._angularSpeedGradientsTexture);\n }\n if (this._parent._velocityGradientsTexture) {\n this._updateEffect.setTexture(\"velocityGradientSampler\", this._parent._velocityGradientsTexture);\n }\n if (this._parent._limitVelocityGradientsTexture) {\n this._updateEffect.setTexture(\"limitVelocityGradientSampler\", this._parent._limitVelocityGradientsTexture);\n }\n if (this._parent._dragGradientsTexture) {\n this._updateEffect.setTexture(\"dragGradientSampler\", this._parent._dragGradientsTexture);\n }\n if (this._parent.noiseTexture) {\n this._updateEffect.setTexture(\"noiseSampler\", this._parent.noiseTexture);\n }\n // Bind source VAO\n this._engine.bindVertexArrayObject(this._updateVAO[index], null);\n // Update\n const engine = this._engine;\n engine.bindTransformFeedbackBuffer(targetBuffer.getBuffer());\n engine.setRasterizerState(false);\n engine.beginTransformFeedback(true);\n engine.drawArraysType(3, 0, currentActiveCount);\n engine.endTransformFeedback();\n engine.setRasterizerState(true);\n engine.bindTransformFeedbackBuffer(null);\n }\n releaseBuffers() { }\n releaseVertexBuffers() {\n for (let index = 0; index < this._updateVAO.length; index++) {\n this._engine.releaseVertexArrayObject(this._updateVAO[index]);\n }\n this._updateVAO.length = 0;\n for (let index = 0; index < this._renderVAO.length; index++) {\n this._engine.releaseVertexArrayObject(this._renderVAO[index]);\n }\n this._renderVAO.length = 0;\n }\n _createUpdateVAO(source) {\n const updateVertexBuffers = {};\n updateVertexBuffers[\"position\"] = source.createVertexBuffer(\"position\", 0, 3);\n let offset = 3;\n updateVertexBuffers[\"age\"] = source.createVertexBuffer(\"age\", offset, 1);\n offset += 1;\n updateVertexBuffers[\"size\"] = source.createVertexBuffer(\"size\", offset, 3);\n offset += 3;\n updateVertexBuffers[\"life\"] = source.createVertexBuffer(\"life\", offset, 1);\n offset += 1;\n updateVertexBuffers[\"seed\"] = source.createVertexBuffer(\"seed\", offset, 4);\n offset += 4;\n updateVertexBuffers[\"direction\"] = source.createVertexBuffer(\"direction\", offset, 3);\n offset += 3;\n if (this._parent.particleEmitterType instanceof CustomParticleEmitter) {\n updateVertexBuffers[\"initialPosition\"] = source.createVertexBuffer(\"initialPosition\", offset, 3);\n offset += 3;\n }\n if (!this._parent._colorGradientsTexture) {\n updateVertexBuffers[\"color\"] = source.createVertexBuffer(\"color\", offset, 4);\n offset += 4;\n }\n if (!this._parent._isBillboardBased) {\n updateVertexBuffers[\"initialDirection\"] = source.createVertexBuffer(\"initialDirection\", offset, 3);\n offset += 3;\n }\n if (this._parent.noiseTexture) {\n updateVertexBuffers[\"noiseCoordinates1\"] = source.createVertexBuffer(\"noiseCoordinates1\", offset, 3);\n offset += 3;\n updateVertexBuffers[\"noiseCoordinates2\"] = source.createVertexBuffer(\"noiseCoordinates2\", offset, 3);\n offset += 3;\n }\n if (this._parent._angularSpeedGradientsTexture) {\n updateVertexBuffers[\"angle\"] = source.createVertexBuffer(\"angle\", offset, 1);\n offset += 1;\n }\n else {\n updateVertexBuffers[\"angle\"] = source.createVertexBuffer(\"angle\", offset, 2);\n offset += 2;\n }\n if (this._parent._isAnimationSheetEnabled) {\n updateVertexBuffers[\"cellIndex\"] = source.createVertexBuffer(\"cellIndex\", offset, 1);\n offset += 1;\n if (this._parent.spriteRandomStartCell) {\n updateVertexBuffers[\"cellStartOffset\"] = source.createVertexBuffer(\"cellStartOffset\", offset, 1);\n offset += 1;\n }\n }\n const vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);\n this._engine.bindArrayBuffer(null);\n return vao;\n }\n}\nRegisterClass(\"BABYLON.WebGL2ParticleSystem\", WebGL2ParticleSystem);\n//# sourceMappingURL=webgl2ParticleSystem.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"gpuUpdateParticlesComputeShader\";\nconst shader = `struct Particle {\rposition : vec3,\rage : f32,\rsize : vec3,\rlife : f32,\rseed : vec4,\rdirection : vec3,\rdummy0: f32,\r#ifdef CUSTOMEMITTER\ninitialPosition : vec3,\rdummy1: f32,\r#endif\n#ifndef COLORGRADIENTS\ncolor : vec4,\r#endif\n#ifndef BILLBOARD\ninitialDirection : vec3,\rdummy2: f32,\r#endif\n#ifdef NOISE\nnoiseCoordinates1 : vec3,\rdummy3: f32,\rnoiseCoordinates2 : vec3,\rdummy4: f32,\r#endif\n#ifdef ANGULARSPEEDGRADIENTS\nangle : f32,\r#else\nangle : vec2,\r#endif\n#ifdef ANIMATESHEET\ncellIndex : f32,\r#ifdef ANIMATESHEETRANDOMSTART\ncellStartOffset : f32,\r#endif\n#endif\n};\rstruct Particles {\rparticles : array,\r};\rstruct SimParams {\rcurrentCount : f32,\rtimeDelta : f32,\rstopFactor : f32,\rrandomTextureSize: i32,\rlifeTime : vec2,\remitPower : vec2,\r#ifndef COLORGRADIENTS\ncolor1 : vec4,\rcolor2 : vec4,\r#endif\nsizeRange : vec2,\rscaleRange : vec4,\rangleRange : vec4,\rgravity : vec3,\r#ifdef LIMITVELOCITYGRADIENTS\nlimitVelocityDamping : f32,\r#endif\n#ifdef ANIMATESHEET\ncellInfos : vec4,\r#endif\n#ifdef NOISE\nnoiseStrength : vec3,\r#endif\n#ifndef LOCAL\nemitterWM : mat4x4,\r#endif\n#ifdef BOXEMITTER\ndirection1 : vec3,\rdirection2 : vec3,\rminEmitBox : vec3,\rmaxEmitBox : vec3,\r#endif\n#ifdef CONEEMITTER\nradius : vec2,\rconeAngle : f32,\rheight : vec2,\rdirectionRandomizer : f32,\r#endif\n#ifdef CYLINDEREMITTER\nradius : f32,\rheight : f32,\rradiusRange : f32,\r#ifdef DIRECTEDCYLINDEREMITTER\ndirection1 : vec3,\rdirection2 : vec3,\r#else\ndirectionRandomizer : f32,\r#endif\n#endif\n#ifdef HEMISPHERICEMITTER\nradius : f32,\rradiusRange : f32,\rdirectionRandomizer : f32,\r#endif\n#ifdef POINTEMITTER\ndirection1 : vec3,\rdirection2 : vec3,\r#endif\n#ifdef SPHEREEMITTER\nradius : f32,\rradiusRange : f32,\r#ifdef DIRECTEDSPHEREEMITTER\ndirection1 : vec3,\rdirection2 : vec3,\r#else\ndirectionRandomizer : f32,\r#endif\n#endif\n};\r@binding(0) @group(0) var params : SimParams;\r@binding(1) @group(0) var particlesIn : Particles;\r@binding(2) @group(0) var particlesOut : Particles;\r@binding(3) @group(0) var randomTexture : texture_2d;\r@binding(4) @group(0) var randomTexture2 : texture_2d;\r#ifdef SIZEGRADIENTS\n@binding(0) @group(1) var sizeGradientSampler : sampler;\r@binding(1) @group(1) var sizeGradientTexture : texture_2d;\r#endif \n#ifdef ANGULARSPEEDGRADIENTS\n@binding(2) @group(1) var angularSpeedGradientSampler : sampler;\r@binding(3) @group(1) var angularSpeedGradientTexture : texture_2d;\r#endif \n#ifdef VELOCITYGRADIENTS\n@binding(4) @group(1) var velocityGradientSampler : sampler;\r@binding(5) @group(1) var velocityGradientTexture : texture_2d;\r#endif\n#ifdef LIMITVELOCITYGRADIENTS\n@binding(6) @group(1) var limitVelocityGradientSampler : sampler;\r@binding(7) @group(1) var limitVelocityGradientTexture : texture_2d;\r#endif\n#ifdef DRAGGRADIENTS\n@binding(8) @group(1) var dragGradientSampler : sampler;\r@binding(9) @group(1) var dragGradientTexture : texture_2d;\r#endif\n#ifdef NOISE\n@binding(10) @group(1) var noiseSampler : sampler;\r@binding(11) @group(1) var noiseTexture : texture_2d;\r#endif\nfn getRandomVec3(offset : f32,vertexID : f32)->vec3 {\rreturn textureLoad(randomTexture2,vec2(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0).rgb;\r}\rfn getRandomVec4(offset : f32,vertexID : f32)->vec4 {\rreturn textureLoad(randomTexture,vec2(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0);\r}\r@compute @workgroup_size(64)\rfn main(@builtin(global_invocation_id) GlobalInvocationID : vec3) {\rlet index : u32=GlobalInvocationID.x;\rlet vertexID : f32=f32(index);\rif (index>=u32(params.currentCount)) {\rreturn;\r}\rlet PI : f32=3.14159;\rlet timeDelta : f32=params.timeDelta;\rlet newAge : f32=particlesIn.particles[index].age+timeDelta;\rlet life : f32=particlesIn.particles[index].life;\rlet seed : vec4=particlesIn.particles[index].seed;\rlet direction : vec3=particlesIn.particles[index].direction;\rif (newAge>=life && params.stopFactor != 0.) {\rvar newPosition : vec3;\rvar newDirection : vec3;\rlet randoms : vec4=getRandomVec4(seed.x,vertexID);\rlet outLife : f32=params.lifeTime.x+(params.lifeTime.y-params.lifeTime.x)*randoms.r;\rparticlesOut.particles[index].life=outLife;\rparticlesOut.particles[index].age=newAge-life;\rparticlesOut.particles[index].seed=seed;\rvar sizex : f32;\r#ifdef SIZEGRADIENTS \nsizex=textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2(0.,0.),0.).r;\r#else\nsizex=params.sizeRange.x+(params.sizeRange.y-params.sizeRange.x)*randoms.g;\r#endif\nparticlesOut.particles[index].size=vec3(\rsizex,\rparams.scaleRange.x+(params.scaleRange.y-params.scaleRange.x)*randoms.b,\rparams.scaleRange.z+(params.scaleRange.w-params.scaleRange.z)*randoms.a);\r#ifndef COLORGRADIENTS\nparticlesOut.particles[index].color=params.color1+(params.color2-params.color1)*randoms.b;\r#endif\n#ifndef ANGULARSPEEDGRADIENTS \nparticlesOut.particles[index].angle=vec2(\rparams.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r,\rparams.angleRange.x+(params.angleRange.y-params.angleRange.x)*randoms.a);\r#else\nparticlesOut.particles[index].angle=params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r;\r#endif \n#if defined(POINTEMITTER)\nlet randoms2 : vec3=getRandomVec3(seed.y,vertexID);\rlet randoms3 : vec3=getRandomVec3(seed.z,vertexID);\rnewPosition=vec3(0.,0.,0.);\rnewDirection=params.direction1+(params.direction2-params.direction1)*randoms3;\r#elif defined(BOXEMITTER)\nlet randoms2 : vec3=getRandomVec3(seed.y,vertexID);\rlet randoms3 : vec3=getRandomVec3(seed.z,vertexID);\rnewPosition=params.minEmitBox+(params.maxEmitBox-params.minEmitBox)*randoms2;\rnewDirection=params.direction1+(params.direction2-params.direction1)*randoms3; \r#elif defined(HEMISPHERICEMITTER)\nlet randoms2 : vec3=getRandomVec3(seed.y,vertexID);\rlet randoms3 : vec3=getRandomVec3(seed.z,vertexID);\rlet phi : f32=2.0*PI*randoms2.x;\rlet theta : f32=acos(-1.0+2.0*randoms2.y);\rlet randX : f32=cos(phi)*sin(theta);\rlet randY : f32=cos(theta);\rlet randZ : f32=sin(phi)*sin(theta);\rnewPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\rnewDirection=normalize(newPosition+params.directionRandomizer*randoms3);\r#elif defined(SPHEREEMITTER)\nlet randoms2 : vec3=getRandomVec3(seed.y,vertexID);\rlet randoms3 : vec3=getRandomVec3(seed.z,vertexID);\rlet phi : f32=2.0*PI*randoms2.x;\rlet theta : f32=acos(-1.0+2.0*randoms2.y);\rlet randX : f32=cos(phi)*sin(theta);\rlet randY : f32=cos(theta);\rlet randZ : f32=sin(phi)*sin(theta);\rnewPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3(randX,randY,randZ);\r#ifdef DIRECTEDSPHEREEMITTER\nnewDirection=normalize(params.direction1+(params.direction2-params.direction1)*randoms3);\r#else\nnewDirection=normalize(newPosition+params.directionRandomizer*randoms3);\r#endif\n#elif defined(CYLINDEREMITTER)\nlet randoms2 : vec3=getRandomVec3(seed.y,vertexID);\rlet randoms3 : vec3=getRandomVec3(seed.z,vertexID);\rlet yPos : f32=(-0.5+randoms2.x)*params.height;\rvar angle : f32=randoms2.y*PI*2.;\rlet inverseRadiusRangeSquared : f32=(1.-params.radiusRange)*(1.-params.radiusRange);\rlet positionRadius : f32=params.radius*sqrt(inverseRadiusRangeSquared+randoms2.z*(1.-inverseRadiusRangeSquared));\rlet xPos : f32=positionRadius*cos(angle);\rlet zPos : f32=positionRadius*sin(angle);\rnewPosition=vec3(xPos,yPos,zPos);\r#ifdef DIRECTEDCYLINDEREMITTER\nnewDirection=params.direction1+(params.direction2-params.direction1)*randoms3;\r#else\nangle=angle+(-0.5+randoms3.x)*PI*params.directionRandomizer;\rnewDirection=vec3(cos(angle),(-0.5+randoms3.y)*params.directionRandomizer,sin(angle));\rnewDirection=normalize(newDirection);\r#endif\n#elif defined(CONEEMITTER)\nlet randoms2 : vec3=getRandomVec3(seed.y,vertexID);\rlet s : f32=2.0*PI*randoms2.x;\r#ifdef CONEEMITTERSPAWNPOINT\nlet h : f32=0.0001;\r#else\nvar h : f32=randoms2.y*params.height.y;\rh=1.-h*h; \r#endif\nvar lRadius : f32=params.radius.x-params.radius.x*randoms2.z*params.radius.y;\rlRadius=lRadius*h;\rlet randX : f32=lRadius*sin(s);\rlet randZ : f32=lRadius*cos(s);\rlet randY : f32=h *params.height.x;\rnewPosition=vec3(randX,randY,randZ); \rif (abs(cos(params.coneAngle))==1.0) {\rnewDirection=vec3(0.,1.0,0.);\r} else {\rlet randoms3 : vec3=getRandomVec3(seed.z,vertexID);\rnewDirection=normalize(newPosition+params.directionRandomizer*randoms3); \r}\r#elif defined(CUSTOMEMITTER)\nnewPosition=particlesIn.particles[index].initialPosition;\rparticlesOut.particles[index].initialPosition=newPosition;\r#else \nnewPosition=vec3(0.,0.,0.);\rnewDirection=2.0*(getRandomVec3(seed.w,vertexID)-vec3(0.5,0.5,0.5));\r#endif\nlet power : f32=params.emitPower.x+(params.emitPower.y-params.emitPower.x)*randoms.a;\r#ifdef LOCAL\nparticlesOut.particles[index].position=newPosition;\r#else\nparticlesOut.particles[index].position=(params.emitterWM*vec4(newPosition,1.)).xyz;\r#endif\n#ifdef CUSTOMEMITTER\nparticlesOut.particles[index].direction=direction;\r#ifndef BILLBOARD \nparticlesOut.particles[index].initialDirection=direction;\r#endif\n#else\n#ifdef LOCAL\nlet initial : vec3=newDirection;\r#else \nlet initial : vec3=(params.emitterWM*vec4(newDirection,0.)).xyz;\r#endif\nparticlesOut.particles[index].direction=initial*power;\r#ifndef BILLBOARD \nparticlesOut.particles[index].initialDirection=initial;\r#endif\n#endif\n#ifdef ANIMATESHEET \nparticlesOut.particles[index].cellIndex=params.cellInfos.x;\r#ifdef ANIMATESHEETRANDOMSTART\nparticlesOut.particles[index].cellStartOffset=randoms.a*outLife;\r#endif \n#endif\n#ifdef NOISE\nparticlesOut.particles[index].noiseCoordinates1=particlesIn.particles[index].noiseCoordinates1;\rparticlesOut.particles[index].noiseCoordinates2=particlesIn.particles[index].noiseCoordinates2;\r#endif\n} else {\rvar directionScale : f32=timeDelta;\rparticlesOut.particles[index].age=newAge;\rlet ageGradient : f32=newAge/life;\r#ifdef VELOCITYGRADIENTS\ndirectionScale=directionScale*textureSampleLevel(velocityGradientTexture,velocityGradientSampler,vec2(ageGradient,0.),0.).r;\r#endif\n#ifdef DRAGGRADIENTS\ndirectionScale=directionScale*(1.0-textureSampleLevel(dragGradientTexture,dragGradientSampler,vec2(ageGradient,0.),0.).r);\r#endif\nlet position : vec3=particlesIn.particles[index].position;\r#if defined(CUSTOMEMITTER)\nparticlesOut.particles[index].position=position+(direction-position)*ageGradient; \rparticlesOut.particles[index].initialPosition=particlesIn.particles[index].initialPosition;\r#else\nparticlesOut.particles[index].position=position+direction*directionScale;\r#endif\nparticlesOut.particles[index].life=life;\rparticlesOut.particles[index].seed=seed;\r#ifndef COLORGRADIENTS \nparticlesOut.particles[index].color=particlesIn.particles[index].color;\r#endif\n#ifdef SIZEGRADIENTS\nparticlesOut.particles[index].size=vec3(\rtextureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2(ageGradient,0.),0.).r,\rparticlesIn.particles[index].size.yz);\r#else\nparticlesOut.particles[index].size=particlesIn.particles[index].size;\r#endif \n#ifndef BILLBOARD \nparticlesOut.particles[index].initialDirection=particlesIn.particles[index].initialDirection;\r#endif\n#ifdef CUSTOMEMITTER\nparticlesOut.particles[index].direction=direction;\r#else\nvar updatedDirection : vec3=direction+params.gravity*timeDelta;\r#ifdef LIMITVELOCITYGRADIENTS\nlet limitVelocity : f32=textureSampleLevel(limitVelocityGradientTexture,limitVelocityGradientSampler,vec2(ageGradient,0.),0.).r;\rlet currentVelocity : f32=length(updatedDirection);\rif (currentVelocity>limitVelocity) {\rupdatedDirection=updatedDirection*params.limitVelocityDamping;\r}\r#endif\nparticlesOut.particles[index].direction=updatedDirection;\r#ifdef NOISE\nlet noiseCoordinates1 : vec3=particlesIn.particles[index].noiseCoordinates1;\rlet noiseCoordinates2 : vec3=particlesIn.particles[index].noiseCoordinates2;\rlet fetchedR : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;\rlet fetchedG : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;\rlet fetchedB : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;\rlet force : vec3=vec3(-1.+2.*fetchedR,-1.+2.*fetchedG,-1.+2.*fetchedB)*params.noiseStrength;\rparticlesOut.particles[index].direction=particlesOut.particles[index].direction+force*timeDelta;\rparticlesOut.particles[index].noiseCoordinates1=noiseCoordinates1;\rparticlesOut.particles[index].noiseCoordinates2=noiseCoordinates2;\r#endif \n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nlet angularSpeed : f32=textureSampleLevel(angularSpeedGradientTexture,angularSpeedGradientSampler,vec2(ageGradient,0.),0.).r;\rparticlesOut.particles[index].angle=particlesIn.particles[index].angle+angularSpeed*timeDelta;\r#else\nlet angle : vec2=particlesIn.particles[index].angle;\rparticlesOut.particles[index].angle=vec2(angle.x+angle.y*timeDelta,angle.y);\r#endif\n#ifdef ANIMATESHEET \nvar offsetAge : f32=particlesOut.particles[index].age;\rlet dist : f32=params.cellInfos.y-params.cellInfos.x;\r#ifdef ANIMATESHEETRANDOMSTART\nlet cellStartOffset : f32=particlesIn.particles[index].cellStartOffset;\rparticlesOut.particles[index].cellStartOffset=cellStartOffset;\roffsetAge=offsetAge+cellStartOffset;\r#else\nlet cellStartOffset : f32=0.;\r#endif \nvar ratio : f32;\rif (params.cellInfos.w==1.0) {\rratio=clamp(((cellStartOffset+params.cellInfos.z*offsetAge) % life)/life,0.,1.0);\r}\relse {\rratio=clamp((cellStartOffset+params.cellInfos.z*offsetAge)/life,0.,1.0);\r}\rparticlesOut.particles[index].cellIndex=f32(i32(params.cellInfos.x+ratio*dist));\r#endif\n}\r}\r`;\n// Sideeffect\nShaderStore.ShadersStoreWGSL[name] = shader;\n/** @internal */\nexport const gpuUpdateParticlesComputeShader = { name, shader };\n//# sourceMappingURL=gpuUpdateParticles.compute.js.map","import { Vector2, Vector3, TmpVectors, Vector4 } from \"../Maths/math.vector.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { Scalar } from \"../Maths/math.scalar.js\";\n/**\n * A particle represents one of the element emitted by a particle system.\n * This is mainly define by its coordinates, direction, velocity and age.\n */\nexport class Particle {\n /**\n * Creates a new instance Particle\n * @param particleSystem the particle system the particle belongs to\n */\n constructor(\n /**\n * The particle system the particle belongs to.\n */\n particleSystem) {\n this.particleSystem = particleSystem;\n /**\n * The world position of the particle in the scene.\n */\n this.position = Vector3.Zero();\n /**\n * The world direction of the particle in the scene.\n */\n this.direction = Vector3.Zero();\n /**\n * The color of the particle.\n */\n this.color = new Color4(0, 0, 0, 0);\n /**\n * The color change of the particle per step.\n */\n this.colorStep = new Color4(0, 0, 0, 0);\n /**\n * Defines how long will the life of the particle be.\n */\n this.lifeTime = 1.0;\n /**\n * The current age of the particle.\n */\n this.age = 0;\n /**\n * The current size of the particle.\n */\n this.size = 0;\n /**\n * The current scale of the particle.\n */\n this.scale = new Vector2(1, 1);\n /**\n * The current angle of the particle.\n */\n this.angle = 0;\n /**\n * Defines how fast is the angle changing.\n */\n this.angularSpeed = 0;\n /**\n * Defines the cell index used by the particle to be rendered from a sprite.\n */\n this.cellIndex = 0;\n /** @internal */\n this._attachedSubEmitters = null;\n /** @internal */\n this._currentColor1 = new Color4(0, 0, 0, 0);\n /** @internal */\n this._currentColor2 = new Color4(0, 0, 0, 0);\n /** @internal */\n this._currentSize1 = 0;\n /** @internal */\n this._currentSize2 = 0;\n /** @internal */\n this._currentAngularSpeed1 = 0;\n /** @internal */\n this._currentAngularSpeed2 = 0;\n /** @internal */\n this._currentVelocity1 = 0;\n /** @internal */\n this._currentVelocity2 = 0;\n /** @internal */\n this._currentLimitVelocity1 = 0;\n /** @internal */\n this._currentLimitVelocity2 = 0;\n /** @internal */\n this._currentDrag1 = 0;\n /** @internal */\n this._currentDrag2 = 0;\n this.id = Particle._Count++;\n if (!this.particleSystem.isAnimationSheetEnabled) {\n return;\n }\n this._updateCellInfoFromSystem();\n }\n _updateCellInfoFromSystem() {\n this.cellIndex = this.particleSystem.startSpriteCellID;\n }\n /**\n * Defines how the sprite cell index is updated for the particle\n */\n updateCellIndex() {\n let offsetAge = this.age;\n let changeSpeed = this.particleSystem.spriteCellChangeSpeed;\n if (this.particleSystem.spriteRandomStartCell) {\n if (this._randomCellOffset === undefined) {\n this._randomCellOffset = Math.random() * this.lifeTime;\n }\n if (changeSpeed === 0) {\n // Special case when speed = 0 meaning we want to stay on initial cell\n changeSpeed = 1;\n offsetAge = this._randomCellOffset;\n }\n else {\n offsetAge += this._randomCellOffset;\n }\n }\n const dist = this._initialEndSpriteCellID - this._initialStartSpriteCellID;\n let ratio;\n if (this._initialSpriteCellLoop) {\n ratio = Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);\n }\n else {\n ratio = Scalar.Clamp((offsetAge * changeSpeed) / this.lifeTime);\n }\n this.cellIndex = (this._initialStartSpriteCellID + ratio * dist) | 0;\n }\n /**\n * @internal\n */\n _inheritParticleInfoToSubEmitter(subEmitter) {\n if (subEmitter.particleSystem.emitter.position) {\n const emitterMesh = subEmitter.particleSystem.emitter;\n emitterMesh.position.copyFrom(this.position);\n if (subEmitter.inheritDirection) {\n const temp = TmpVectors.Vector3[0];\n this.direction.normalizeToRef(temp);\n emitterMesh.setDirection(temp, 0, Math.PI / 2);\n }\n }\n else {\n const emitterPosition = subEmitter.particleSystem.emitter;\n emitterPosition.copyFrom(this.position);\n }\n // Set inheritedVelocityOffset to be used when new particles are created\n this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, TmpVectors.Vector3[0]);\n subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(TmpVectors.Vector3[0]);\n }\n /** @internal */\n _inheritParticleInfoToSubEmitters() {\n if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {\n this._attachedSubEmitters.forEach((subEmitter) => {\n this._inheritParticleInfoToSubEmitter(subEmitter);\n });\n }\n }\n /** @internal */\n _reset() {\n this.age = 0;\n this.id = Particle._Count++;\n this._currentColorGradient = null;\n this._currentSizeGradient = null;\n this._currentAngularSpeedGradient = null;\n this._currentVelocityGradient = null;\n this._currentLimitVelocityGradient = null;\n this._currentDragGradient = null;\n this.cellIndex = this.particleSystem.startSpriteCellID;\n this._randomCellOffset = undefined;\n }\n /**\n * Copy the properties of particle to another one.\n * @param other the particle to copy the information to.\n */\n copyTo(other) {\n other.position.copyFrom(this.position);\n if (this._initialDirection) {\n if (other._initialDirection) {\n other._initialDirection.copyFrom(this._initialDirection);\n }\n else {\n other._initialDirection = this._initialDirection.clone();\n }\n }\n else {\n other._initialDirection = null;\n }\n other.direction.copyFrom(this.direction);\n if (this._localPosition) {\n if (other._localPosition) {\n other._localPosition.copyFrom(this._localPosition);\n }\n else {\n other._localPosition = this._localPosition.clone();\n }\n }\n other.color.copyFrom(this.color);\n other.colorStep.copyFrom(this.colorStep);\n other.lifeTime = this.lifeTime;\n other.age = this.age;\n other._randomCellOffset = this._randomCellOffset;\n other.size = this.size;\n other.scale.copyFrom(this.scale);\n other.angle = this.angle;\n other.angularSpeed = this.angularSpeed;\n other.particleSystem = this.particleSystem;\n other.cellIndex = this.cellIndex;\n other.id = this.id;\n other._attachedSubEmitters = this._attachedSubEmitters;\n if (this._currentColorGradient) {\n other._currentColorGradient = this._currentColorGradient;\n other._currentColor1.copyFrom(this._currentColor1);\n other._currentColor2.copyFrom(this._currentColor2);\n }\n if (this._currentSizeGradient) {\n other._currentSizeGradient = this._currentSizeGradient;\n other._currentSize1 = this._currentSize1;\n other._currentSize2 = this._currentSize2;\n }\n if (this._currentAngularSpeedGradient) {\n other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;\n other._currentAngularSpeed1 = this._currentAngularSpeed1;\n other._currentAngularSpeed2 = this._currentAngularSpeed2;\n }\n if (this._currentVelocityGradient) {\n other._currentVelocityGradient = this._currentVelocityGradient;\n other._currentVelocity1 = this._currentVelocity1;\n other._currentVelocity2 = this._currentVelocity2;\n }\n if (this._currentLimitVelocityGradient) {\n other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;\n other._currentLimitVelocity1 = this._currentLimitVelocity1;\n other._currentLimitVelocity2 = this._currentLimitVelocity2;\n }\n if (this._currentDragGradient) {\n other._currentDragGradient = this._currentDragGradient;\n other._currentDrag1 = this._currentDrag1;\n other._currentDrag2 = this._currentDrag2;\n }\n if (this.particleSystem.isAnimationSheetEnabled) {\n other._initialStartSpriteCellID = this._initialStartSpriteCellID;\n other._initialEndSpriteCellID = this._initialEndSpriteCellID;\n other._initialSpriteCellLoop = this._initialSpriteCellLoop;\n }\n if (this.particleSystem.useRampGradients) {\n if (other.remapData && this.remapData) {\n other.remapData.copyFrom(this.remapData);\n }\n else {\n other.remapData = new Vector4(0, 0, 0, 0);\n }\n }\n if (this._randomNoiseCoordinates1) {\n if (other._randomNoiseCoordinates1) {\n other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);\n other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);\n }\n else {\n other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();\n other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();\n }\n }\n }\n}\nParticle._Count = 0;\n//# sourceMappingURL=particle.js.map","import { FactorGradient, ColorGradient, Color3Gradient, GradientHelper } from \"../Misc/gradients.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Vector3, Matrix, TmpVectors, Vector4 } from \"../Maths/math.vector.js\";\nimport { Scalar } from \"../Maths/math.scalar.js\";\nimport { VertexBuffer, Buffer } from \"../Buffers/buffer.js\";\nimport { ImageProcessingConfiguration } from \"../Materials/imageProcessingConfiguration.js\";\nimport { RawTexture } from \"../Materials/Textures/rawTexture.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { BoxParticleEmitter, HemisphericParticleEmitter, SphereParticleEmitter, SphereDirectedParticleEmitter, CylinderParticleEmitter, ConeParticleEmitter, PointParticleEmitter, MeshParticleEmitter, CylinderDirectedParticleEmitter, } from \"../Particles/EmitterTypes/index.js\";\nimport { BaseParticleSystem } from \"./baseParticleSystem.js\";\nimport { Particle } from \"./particle.js\";\nimport { SubEmitter, SubEmitterType } from \"./subEmitter.js\";\n\nimport { SerializationHelper } from \"../Misc/decorators.js\";\nimport { GetClass } from \"../Misc/typeStore.js\";\nimport { DrawWrapper } from \"../Materials/drawWrapper.js\";\nimport \"../Shaders/particles.fragment.js\";\nimport \"../Shaders/particles.vertex.js\";\nimport { Color4, Color3, TmpColors } from \"../Maths/math.color.js\";\nimport { ThinEngine } from \"../Engines/thinEngine.js\";\nimport { MaterialHelper } from \"../Materials/materialHelper.js\";\nimport \"../Engines/Extensions/engine.alpha.js\";\nimport { addClipPlaneUniforms, prepareStringDefinesForClipPlanes, bindClipPlane } from \"../Materials/clipPlaneMaterialHelper.js\";\n/**\n * This represents a particle system in Babylon.\n * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.\n * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.\n * @example https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro\n */\nexport class ParticleSystem extends BaseParticleSystem {\n /**\n * Sets a callback that will be triggered when the system is disposed\n */\n set onDispose(callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n }\n /** Gets or sets a boolean indicating that ramp gradients must be used\n * @see https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro#ramp-gradients\n */\n get useRampGradients() {\n return this._useRampGradients;\n }\n set useRampGradients(value) {\n if (this._useRampGradients === value) {\n return;\n }\n this._useRampGradients = value;\n this._resetEffect();\n }\n //end of Sub-emitter\n /**\n * Gets the current list of active particles\n */\n get particles() {\n return this._particles;\n }\n /**\n * Gets the number of particles active at the same time.\n * @returns The number of active particles.\n */\n getActiveCount() {\n return this._particles.length;\n }\n /**\n * Returns the string \"ParticleSystem\"\n * @returns a string containing the class name\n */\n getClassName() {\n return \"ParticleSystem\";\n }\n /**\n * Gets a boolean indicating that the system is stopping\n * @returns true if the system is currently stopping\n */\n isStopping() {\n return this._stopped && this.isAlive();\n }\n /**\n * Gets the custom effect used to render the particles\n * @param blendMode Blend mode for which the effect should be retrieved\n * @returns The effect\n */\n getCustomEffect(blendMode = 0) {\n var _a, _b;\n return (_b = (_a = this._customWrappers[blendMode]) === null || _a === void 0 ? void 0 : _a.effect) !== null && _b !== void 0 ? _b : this._customWrappers[0].effect;\n }\n _getCustomDrawWrapper(blendMode = 0) {\n var _a;\n return (_a = this._customWrappers[blendMode]) !== null && _a !== void 0 ? _a : this._customWrappers[0];\n }\n /**\n * Sets the custom effect used to render the particles\n * @param effect The effect to set\n * @param blendMode Blend mode for which the effect should be set\n */\n setCustomEffect(effect, blendMode = 0) {\n this._customWrappers[blendMode] = new DrawWrapper(this._engine);\n this._customWrappers[blendMode].effect = effect;\n if (this._customWrappers[blendMode].drawContext) {\n this._customWrappers[blendMode].drawContext.useInstancing = this._useInstancing;\n }\n }\n /**\n * Observable that will be called just before the particles are drawn\n */\n get onBeforeDrawParticlesObservable() {\n if (!this._onBeforeDrawParticlesObservable) {\n this._onBeforeDrawParticlesObservable = new Observable();\n }\n return this._onBeforeDrawParticlesObservable;\n }\n /**\n * Gets the name of the particle vertex shader\n */\n get vertexShaderName() {\n return \"particles\";\n }\n /**\n * Gets the vertex buffers used by the particle system\n */\n get vertexBuffers() {\n return this._vertexBuffers;\n }\n /**\n * Gets the index buffer used by the particle system (or null if no index buffer is used (if _useInstancing=true))\n */\n get indexBuffer() {\n return this._indexBuffer;\n }\n /**\n * Instantiates a particle system.\n * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.\n * @param name The name of the particle system\n * @param capacity The max number of particles alive at the same time\n * @param sceneOrEngine The scene the particle system belongs to or the engine to use if no scene\n * @param customEffect a custom effect used to change the way particles are rendered by default\n * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture\n * @param epsilon Offset used to render the particles\n */\n constructor(name, capacity, sceneOrEngine, customEffect = null, isAnimationSheetEnabled = false, epsilon = 0.01) {\n super(name);\n this._emitterInverseWorldMatrix = Matrix.Identity();\n /**\n * @internal\n */\n this._inheritedVelocityOffset = new Vector3();\n /**\n * An event triggered when the system is disposed\n */\n this.onDisposeObservable = new Observable();\n /**\n * An event triggered when the system is stopped\n */\n this.onStoppedObservable = new Observable();\n this._particles = new Array();\n this._stockParticles = new Array();\n this._newPartsExcess = 0;\n this._vertexBuffers = {};\n this._scaledColorStep = new Color4(0, 0, 0, 0);\n this._colorDiff = new Color4(0, 0, 0, 0);\n this._scaledDirection = Vector3.Zero();\n this._scaledGravity = Vector3.Zero();\n this._currentRenderId = -1;\n this._useInstancing = false;\n this._started = false;\n this._stopped = false;\n this._actualFrame = 0;\n /** @internal */\n this._currentEmitRate1 = 0;\n /** @internal */\n this._currentEmitRate2 = 0;\n /** @internal */\n this._currentStartSize1 = 0;\n /** @internal */\n this._currentStartSize2 = 0;\n /** Indicates that the update of particles is done in the animate function */\n this.updateInAnimate = true;\n this._rawTextureWidth = 256;\n this._useRampGradients = false;\n /**\n * @internal\n * If the particle systems emitter should be disposed when the particle system is disposed\n */\n this._disposeEmitterOnDispose = false;\n /**\n * Specifies if the particles are updated in emitter local space or world space\n */\n this.isLocal = false;\n /** Indicates that the particle system is CPU based */\n this.isGPU = false;\n /** @internal */\n this._onBeforeDrawParticlesObservable = null;\n // start of sub system methods\n /**\n * \"Recycles\" one of the particle by copying it back to the \"stock\" of particles and removing it from the active list.\n * Its lifetime will start back at 0.\n * @param particle\n */\n this.recycleParticle = (particle) => {\n // move particle from activeParticle list to stock particles\n const lastParticle = this._particles.pop();\n if (lastParticle !== particle) {\n lastParticle.copyTo(particle);\n }\n this._stockParticles.push(lastParticle);\n };\n this._createParticle = () => {\n let particle;\n if (this._stockParticles.length !== 0) {\n particle = this._stockParticles.pop();\n particle._reset();\n }\n else {\n particle = new Particle(this);\n }\n // Attach emitters\n if (this._subEmitters && this._subEmitters.length > 0) {\n const subEmitters = this._subEmitters[Math.floor(Math.random() * this._subEmitters.length)];\n particle._attachedSubEmitters = [];\n subEmitters.forEach((subEmitter) => {\n if (subEmitter.type === SubEmitterType.ATTACHED) {\n const newEmitter = subEmitter.clone();\n particle._attachedSubEmitters.push(newEmitter);\n newEmitter.particleSystem.start();\n }\n });\n }\n return particle;\n };\n this._emitFromParticle = (particle) => {\n if (!this._subEmitters || this._subEmitters.length === 0) {\n return;\n }\n const templateIndex = Math.floor(Math.random() * this._subEmitters.length);\n this._subEmitters[templateIndex].forEach((subEmitter) => {\n if (subEmitter.type === SubEmitterType.END) {\n const subSystem = subEmitter.clone();\n particle._inheritParticleInfoToSubEmitter(subSystem);\n subSystem.particleSystem._rootParticleSystem = this;\n this.activeSubSystems.push(subSystem.particleSystem);\n subSystem.particleSystem.start();\n }\n });\n };\n this._capacity = capacity;\n this._epsilon = epsilon;\n this._isAnimationSheetEnabled = isAnimationSheetEnabled;\n if (!sceneOrEngine || sceneOrEngine.getClassName() === \"Scene\") {\n this._scene = sceneOrEngine || EngineStore.LastCreatedScene;\n this._engine = this._scene.getEngine();\n this.uniqueId = this._scene.getUniqueId();\n this._scene.particleSystems.push(this);\n }\n else {\n this._engine = sceneOrEngine;\n this.defaultProjectionMatrix = Matrix.PerspectiveFovLH(0.8, 1, 0.1, 100, this._engine.isNDCHalfZRange);\n }\n if (this._engine.getCaps().vertexArrayObject) {\n this._vertexArrayObject = null;\n }\n // Setup the default processing configuration to the scene.\n this._attachImageProcessingConfiguration(null);\n // eslint-disable-next-line @typescript-eslint/naming-convention\n this._customWrappers = { 0: new DrawWrapper(this._engine) };\n this._customWrappers[0].effect = customEffect;\n this._drawWrappers = [];\n this._useInstancing = this._engine.getCaps().instancedArrays;\n this._createIndexBuffer();\n this._createVertexBuffers();\n // Default emitter type\n this.particleEmitterType = new BoxParticleEmitter();\n let noiseTextureData = null;\n // Update\n this.updateFunction = (particles) => {\n var _a;\n let noiseTextureSize = null;\n if (this.noiseTexture) {\n // We need to get texture data back to CPU\n noiseTextureSize = this.noiseTexture.getSize();\n (_a = this.noiseTexture.getContent()) === null || _a === void 0 ? void 0 : _a.then((data) => {\n noiseTextureData = data;\n });\n }\n for (let index = 0; index < particles.length; index++) {\n const particle = particles[index];\n let scaledUpdateSpeed = this._scaledUpdateSpeed;\n const previousAge = particle.age;\n particle.age += scaledUpdateSpeed;\n // Evaluate step to death\n if (particle.age > particle.lifeTime) {\n const diff = particle.age - previousAge;\n const oldDiff = particle.lifeTime - previousAge;\n scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;\n particle.age = particle.lifeTime;\n }\n const ratio = particle.age / particle.lifeTime;\n // Color\n if (this._colorGradients && this._colorGradients.length > 0) {\n GradientHelper.GetCurrentGradient(ratio, this._colorGradients, (currentGradient, nextGradient, scale) => {\n if (currentGradient !== particle._currentColorGradient) {\n particle._currentColor1.copyFrom(particle._currentColor2);\n nextGradient.getColorToRef(particle._currentColor2);\n particle._currentColorGradient = currentGradient;\n }\n Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);\n });\n }\n else {\n particle.colorStep.scaleToRef(scaledUpdateSpeed, this._scaledColorStep);\n particle.color.addInPlace(this._scaledColorStep);\n if (particle.color.a < 0) {\n particle.color.a = 0;\n }\n }\n // Angular speed\n if (this._angularSpeedGradients && this._angularSpeedGradients.length > 0) {\n GradientHelper.GetCurrentGradient(ratio, this._angularSpeedGradients, (currentGradient, nextGradient, scale) => {\n if (currentGradient !== particle._currentAngularSpeedGradient) {\n particle._currentAngularSpeed1 = particle._currentAngularSpeed2;\n particle._currentAngularSpeed2 = nextGradient.getFactor();\n particle._currentAngularSpeedGradient = currentGradient;\n }\n particle.angularSpeed = Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);\n });\n }\n particle.angle += particle.angularSpeed * scaledUpdateSpeed;\n // Direction\n let directionScale = scaledUpdateSpeed;\n /// Velocity\n if (this._velocityGradients && this._velocityGradients.length > 0) {\n GradientHelper.GetCurrentGradient(ratio, this._velocityGradients, (currentGradient, nextGradient, scale) => {\n if (currentGradient !== particle._currentVelocityGradient) {\n particle._currentVelocity1 = particle._currentVelocity2;\n particle._currentVelocity2 = nextGradient.getFactor();\n particle._currentVelocityGradient = currentGradient;\n }\n directionScale *= Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);\n });\n }\n particle.direction.scaleToRef(directionScale, this._scaledDirection);\n /// Limit velocity\n if (this._limitVelocityGradients && this._limitVelocityGradients.length > 0) {\n GradientHelper.GetCurrentGradient(ratio, this._limitVelocityGradients, (currentGradient, nextGradient, scale) => {\n if (currentGradient !== particle._currentLimitVelocityGradient) {\n particle._currentLimitVelocity1 = particle._currentLimitVelocity2;\n particle._currentLimitVelocity2 = nextGradient.getFactor();\n particle._currentLimitVelocityGradient = currentGradient;\n }\n const limitVelocity = Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);\n const currentVelocity = particle.direction.length();\n if (currentVelocity > limitVelocity) {\n particle.direction.scaleInPlace(this.limitVelocityDamping);\n }\n });\n }\n /// Drag\n if (this._dragGradients && this._dragGradients.length > 0) {\n GradientHelper.GetCurrentGradient(ratio, this._dragGradients, (currentGradient, nextGradient, scale) => {\n if (currentGradient !== particle._currentDragGradient) {\n particle._currentDrag1 = particle._currentDrag2;\n particle._currentDrag2 = nextGradient.getFactor();\n particle._currentDragGradient = currentGradient;\n }\n const drag = Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);\n this._scaledDirection.scaleInPlace(1.0 - drag);\n });\n }\n if (this.isLocal && particle._localPosition) {\n particle._localPosition.addInPlace(this._scaledDirection);\n Vector3.TransformCoordinatesToRef(particle._localPosition, this._emitterWorldMatrix, particle.position);\n }\n else {\n particle.position.addInPlace(this._scaledDirection);\n }\n // Noise\n if (noiseTextureData && noiseTextureSize && particle._randomNoiseCoordinates1) {\n const fetchedColorR = this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);\n const fetchedColorG = this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);\n const fetchedColorB = this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);\n const force = TmpVectors.Vector3[0];\n const scaledForce = TmpVectors.Vector3[1];\n force.copyFromFloats((2 * fetchedColorR - 1) * this.noiseStrength.x, (2 * fetchedColorG - 1) * this.noiseStrength.y, (2 * fetchedColorB - 1) * this.noiseStrength.z);\n force.scaleToRef(scaledUpdateSpeed, scaledForce);\n particle.direction.addInPlace(scaledForce);\n }\n // Gravity\n this.gravity.scaleToRef(scaledUpdateSpeed, this._scaledGravity);\n particle.direction.addInPlace(this._scaledGravity);\n // Size\n if (this._sizeGradients && this._sizeGradients.length > 0) {\n GradientHelper.GetCurrentGradient(ratio, this._sizeGradients, (currentGradient, nextGradient, scale) => {\n if (currentGradient !== particle._currentSizeGradient) {\n particle._currentSize1 = particle._currentSize2;\n particle._currentSize2 = nextGradient.getFactor();\n particle._currentSizeGradient = currentGradient;\n }\n particle.size = Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);\n });\n }\n // Remap data\n if (this._useRampGradients) {\n if (this._colorRemapGradients && this._colorRemapGradients.length > 0) {\n GradientHelper.GetCurrentGradient(ratio, this._colorRemapGradients, (currentGradient, nextGradient, scale) => {\n const min = Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);\n const max = Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);\n particle.remapData.x = min;\n particle.remapData.y = max - min;\n });\n }\n if (this._alphaRemapGradients && this._alphaRemapGradients.length > 0) {\n GradientHelper.GetCurrentGradient(ratio, this._alphaRemapGradients, (currentGradient, nextGradient, scale) => {\n const min = Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);\n const max = Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);\n particle.remapData.z = min;\n particle.remapData.w = max - min;\n });\n }\n }\n if (this._isAnimationSheetEnabled) {\n particle.updateCellIndex();\n }\n // Update the position of the attached sub-emitters to match their attached particle\n particle._inheritParticleInfoToSubEmitters();\n if (particle.age >= particle.lifeTime) {\n // Recycle by swapping with last particle\n this._emitFromParticle(particle);\n if (particle._attachedSubEmitters) {\n particle._attachedSubEmitters.forEach((subEmitter) => {\n subEmitter.particleSystem.disposeOnStop = true;\n subEmitter.particleSystem.stop();\n });\n particle._attachedSubEmitters = null;\n }\n this.recycleParticle(particle);\n index--;\n continue;\n }\n }\n };\n }\n _addFactorGradient(factorGradients, gradient, factor, factor2) {\n const newGradient = new FactorGradient(gradient, factor, factor2);\n factorGradients.push(newGradient);\n factorGradients.sort((a, b) => {\n if (a.gradient < b.gradient) {\n return -1;\n }\n else if (a.gradient > b.gradient) {\n return 1;\n }\n return 0;\n });\n }\n _removeFactorGradient(factorGradients, gradient) {\n if (!factorGradients) {\n return;\n }\n let index = 0;\n for (const factorGradient of factorGradients) {\n if (factorGradient.gradient === gradient) {\n factorGradients.splice(index, 1);\n break;\n }\n index++;\n }\n }\n /**\n * Adds a new life time gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the life time factor to affect to the specified gradient\n * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from\n * @returns the current particle system\n */\n addLifeTimeGradient(gradient, factor, factor2) {\n if (!this._lifeTimeGradients) {\n this._lifeTimeGradients = [];\n }\n this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);\n return this;\n }\n /**\n * Remove a specific life time gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeLifeTimeGradient(gradient) {\n this._removeFactorGradient(this._lifeTimeGradients, gradient);\n return this;\n }\n /**\n * Adds a new size gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the size factor to affect to the specified gradient\n * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from\n * @returns the current particle system\n */\n addSizeGradient(gradient, factor, factor2) {\n if (!this._sizeGradients) {\n this._sizeGradients = [];\n }\n this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);\n return this;\n }\n /**\n * Remove a specific size gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeSizeGradient(gradient) {\n this._removeFactorGradient(this._sizeGradients, gradient);\n return this;\n }\n /**\n * Adds a new color remap gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param min defines the color remap minimal range\n * @param max defines the color remap maximal range\n * @returns the current particle system\n */\n addColorRemapGradient(gradient, min, max) {\n if (!this._colorRemapGradients) {\n this._colorRemapGradients = [];\n }\n this._addFactorGradient(this._colorRemapGradients, gradient, min, max);\n return this;\n }\n /**\n * Remove a specific color remap gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeColorRemapGradient(gradient) {\n this._removeFactorGradient(this._colorRemapGradients, gradient);\n return this;\n }\n /**\n * Adds a new alpha remap gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param min defines the alpha remap minimal range\n * @param max defines the alpha remap maximal range\n * @returns the current particle system\n */\n addAlphaRemapGradient(gradient, min, max) {\n if (!this._alphaRemapGradients) {\n this._alphaRemapGradients = [];\n }\n this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);\n return this;\n }\n /**\n * Remove a specific alpha remap gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeAlphaRemapGradient(gradient) {\n this._removeFactorGradient(this._alphaRemapGradients, gradient);\n return this;\n }\n /**\n * Adds a new angular speed gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the angular speed to affect to the specified gradient\n * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from\n * @returns the current particle system\n */\n addAngularSpeedGradient(gradient, factor, factor2) {\n if (!this._angularSpeedGradients) {\n this._angularSpeedGradients = [];\n }\n this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);\n return this;\n }\n /**\n * Remove a specific angular speed gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeAngularSpeedGradient(gradient) {\n this._removeFactorGradient(this._angularSpeedGradients, gradient);\n return this;\n }\n /**\n * Adds a new velocity gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the velocity to affect to the specified gradient\n * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from\n * @returns the current particle system\n */\n addVelocityGradient(gradient, factor, factor2) {\n if (!this._velocityGradients) {\n this._velocityGradients = [];\n }\n this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);\n return this;\n }\n /**\n * Remove a specific velocity gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeVelocityGradient(gradient) {\n this._removeFactorGradient(this._velocityGradients, gradient);\n return this;\n }\n /**\n * Adds a new limit velocity gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the limit velocity value to affect to the specified gradient\n * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from\n * @returns the current particle system\n */\n addLimitVelocityGradient(gradient, factor, factor2) {\n if (!this._limitVelocityGradients) {\n this._limitVelocityGradients = [];\n }\n this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);\n return this;\n }\n /**\n * Remove a specific limit velocity gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeLimitVelocityGradient(gradient) {\n this._removeFactorGradient(this._limitVelocityGradients, gradient);\n return this;\n }\n /**\n * Adds a new drag gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the drag value to affect to the specified gradient\n * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from\n * @returns the current particle system\n */\n addDragGradient(gradient, factor, factor2) {\n if (!this._dragGradients) {\n this._dragGradients = [];\n }\n this._addFactorGradient(this._dragGradients, gradient, factor, factor2);\n return this;\n }\n /**\n * Remove a specific drag gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeDragGradient(gradient) {\n this._removeFactorGradient(this._dragGradients, gradient);\n return this;\n }\n /**\n * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the emit rate value to affect to the specified gradient\n * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from\n * @returns the current particle system\n */\n addEmitRateGradient(gradient, factor, factor2) {\n if (!this._emitRateGradients) {\n this._emitRateGradients = [];\n }\n this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);\n return this;\n }\n /**\n * Remove a specific emit rate gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeEmitRateGradient(gradient) {\n this._removeFactorGradient(this._emitRateGradients, gradient);\n return this;\n }\n /**\n * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the start size value to affect to the specified gradient\n * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from\n * @returns the current particle system\n */\n addStartSizeGradient(gradient, factor, factor2) {\n if (!this._startSizeGradients) {\n this._startSizeGradients = [];\n }\n this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);\n return this;\n }\n /**\n * Remove a specific start size gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeStartSizeGradient(gradient) {\n this._removeFactorGradient(this._startSizeGradients, gradient);\n return this;\n }\n _createRampGradientTexture() {\n if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture || !this._scene) {\n return;\n }\n const data = new Uint8Array(this._rawTextureWidth * 4);\n const tmpColor = TmpColors.Color3[0];\n for (let x = 0; x < this._rawTextureWidth; x++) {\n const ratio = x / this._rawTextureWidth;\n GradientHelper.GetCurrentGradient(ratio, this._rampGradients, (currentGradient, nextGradient, scale) => {\n Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);\n data[x * 4] = tmpColor.r * 255;\n data[x * 4 + 1] = tmpColor.g * 255;\n data[x * 4 + 2] = tmpColor.b * 255;\n data[x * 4 + 3] = 255;\n });\n }\n this._rampGradientsTexture = RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, 1);\n }\n /**\n * Gets the current list of ramp gradients.\n * You must use addRampGradient and removeRampGradient to update this list\n * @returns the list of ramp gradients\n */\n getRampGradients() {\n return this._rampGradients;\n }\n /** Force the system to rebuild all gradients that need to be resync */\n forceRefreshGradients() {\n this._syncRampGradientTexture();\n }\n _syncRampGradientTexture() {\n if (!this._rampGradients) {\n return;\n }\n this._rampGradients.sort((a, b) => {\n if (a.gradient < b.gradient) {\n return -1;\n }\n else if (a.gradient > b.gradient) {\n return 1;\n }\n return 0;\n });\n if (this._rampGradientsTexture) {\n this._rampGradientsTexture.dispose();\n this._rampGradientsTexture = null;\n }\n this._createRampGradientTexture();\n }\n /**\n * Adds a new ramp gradient used to remap particle colors\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param color defines the color to affect to the specified gradient\n * @returns the current particle system\n */\n addRampGradient(gradient, color) {\n if (!this._rampGradients) {\n this._rampGradients = [];\n }\n const rampGradient = new Color3Gradient(gradient, color);\n this._rampGradients.push(rampGradient);\n this._syncRampGradientTexture();\n return this;\n }\n /**\n * Remove a specific ramp gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeRampGradient(gradient) {\n this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);\n this._rampGradientsTexture = null;\n if (this._rampGradients && this._rampGradients.length > 0) {\n this._createRampGradientTexture();\n }\n return this;\n }\n /**\n * Adds a new color gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param color1 defines the color to affect to the specified gradient\n * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from\n * @returns this particle system\n */\n addColorGradient(gradient, color1, color2) {\n if (!this._colorGradients) {\n this._colorGradients = [];\n }\n const colorGradient = new ColorGradient(gradient, color1, color2);\n this._colorGradients.push(colorGradient);\n this._colorGradients.sort((a, b) => {\n if (a.gradient < b.gradient) {\n return -1;\n }\n else if (a.gradient > b.gradient) {\n return 1;\n }\n return 0;\n });\n return this;\n }\n /**\n * Remove a specific color gradient\n * @param gradient defines the gradient to remove\n * @returns this particle system\n */\n removeColorGradient(gradient) {\n if (!this._colorGradients) {\n return this;\n }\n let index = 0;\n for (const colorGradient of this._colorGradients) {\n if (colorGradient.gradient === gradient) {\n this._colorGradients.splice(index, 1);\n break;\n }\n index++;\n }\n return this;\n }\n /**\n * Resets the draw wrappers cache\n */\n resetDrawCache() {\n for (const drawWrappers of this._drawWrappers) {\n if (drawWrappers) {\n for (const drawWrapper of drawWrappers) {\n drawWrapper === null || drawWrapper === void 0 ? void 0 : drawWrapper.dispose();\n }\n }\n }\n this._drawWrappers = [];\n }\n _fetchR(u, v, width, height, pixels) {\n u = Math.abs(u) * 0.5 + 0.5;\n v = Math.abs(v) * 0.5 + 0.5;\n const wrappedU = (u * width) % width | 0;\n const wrappedV = (v * height) % height | 0;\n const position = (wrappedU + wrappedV * width) * 4;\n return pixels[position] / 255;\n }\n _reset() {\n this._resetEffect();\n }\n _resetEffect() {\n if (this._vertexBuffer) {\n this._vertexBuffer.dispose();\n this._vertexBuffer = null;\n }\n if (this._spriteBuffer) {\n this._spriteBuffer.dispose();\n this._spriteBuffer = null;\n }\n if (this._vertexArrayObject) {\n this._engine.releaseVertexArrayObject(this._vertexArrayObject);\n this._vertexArrayObject = null;\n }\n this._createVertexBuffers();\n }\n _createVertexBuffers() {\n this._vertexBufferSize = this._useInstancing ? 10 : 12;\n if (this._isAnimationSheetEnabled) {\n this._vertexBufferSize += 1;\n }\n if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL) {\n this._vertexBufferSize += 3;\n }\n if (this._useRampGradients) {\n this._vertexBufferSize += 4;\n }\n const engine = this._engine;\n const vertexSize = this._vertexBufferSize * (this._useInstancing ? 1 : 4);\n this._vertexData = new Float32Array(this._capacity * vertexSize);\n this._vertexBuffer = new Buffer(engine, this._vertexData, true, vertexSize);\n let dataOffset = 0;\n const positions = this._vertexBuffer.createVertexBuffer(VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[VertexBuffer.PositionKind] = positions;\n dataOffset += 3;\n const colors = this._vertexBuffer.createVertexBuffer(VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[VertexBuffer.ColorKind] = colors;\n dataOffset += 4;\n const options = this._vertexBuffer.createVertexBuffer(\"angle\", dataOffset, 1, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[\"angle\"] = options;\n dataOffset += 1;\n const size = this._vertexBuffer.createVertexBuffer(\"size\", dataOffset, 2, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[\"size\"] = size;\n dataOffset += 2;\n if (this._isAnimationSheetEnabled) {\n const cellIndexBuffer = this._vertexBuffer.createVertexBuffer(\"cellIndex\", dataOffset, 1, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[\"cellIndex\"] = cellIndexBuffer;\n dataOffset += 1;\n }\n if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL) {\n const directionBuffer = this._vertexBuffer.createVertexBuffer(\"direction\", dataOffset, 3, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[\"direction\"] = directionBuffer;\n dataOffset += 3;\n }\n if (this._useRampGradients) {\n const rampDataBuffer = this._vertexBuffer.createVertexBuffer(\"remapData\", dataOffset, 4, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[\"remapData\"] = rampDataBuffer;\n dataOffset += 4;\n }\n let offsets;\n if (this._useInstancing) {\n const spriteData = new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]);\n this._spriteBuffer = new Buffer(engine, spriteData, false, 2);\n offsets = this._spriteBuffer.createVertexBuffer(\"offset\", 0, 2);\n }\n else {\n offsets = this._vertexBuffer.createVertexBuffer(\"offset\", dataOffset, 2, this._vertexBufferSize, this._useInstancing);\n dataOffset += 2;\n }\n this._vertexBuffers[\"offset\"] = offsets;\n this.resetDrawCache();\n }\n _createIndexBuffer() {\n if (this._useInstancing) {\n return;\n }\n const indices = [];\n let index = 0;\n for (let count = 0; count < this._capacity; count++) {\n indices.push(index);\n indices.push(index + 1);\n indices.push(index + 2);\n indices.push(index);\n indices.push(index + 2);\n indices.push(index + 3);\n index += 4;\n }\n this._indexBuffer = this._engine.createIndexBuffer(indices);\n }\n /**\n * Gets the maximum number of particles active at the same time.\n * @returns The max number of active particles.\n */\n getCapacity() {\n return this._capacity;\n }\n /**\n * Gets whether there are still active particles in the system.\n * @returns True if it is alive, otherwise false.\n */\n isAlive() {\n return this._alive;\n }\n /**\n * Gets if the system has been started. (Note: this will still be true after stop is called)\n * @returns True if it has been started, otherwise false.\n */\n isStarted() {\n return this._started;\n }\n _prepareSubEmitterInternalArray() {\n this._subEmitters = new Array();\n if (this.subEmitters) {\n this.subEmitters.forEach((subEmitter) => {\n if (subEmitter instanceof ParticleSystem) {\n this._subEmitters.push([new SubEmitter(subEmitter)]);\n }\n else if (subEmitter instanceof SubEmitter) {\n this._subEmitters.push([subEmitter]);\n }\n else if (subEmitter instanceof Array) {\n this._subEmitters.push(subEmitter);\n }\n });\n }\n }\n /**\n * Starts the particle system and begins to emit\n * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)\n */\n start(delay = this.startDelay) {\n var _a;\n if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {\n throw \"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set\";\n }\n if (delay) {\n setTimeout(() => {\n this.start(0);\n }, delay);\n return;\n }\n // Convert the subEmitters field to the constant type field _subEmitters\n this._prepareSubEmitterInternalArray();\n this._started = true;\n this._stopped = false;\n this._actualFrame = 0;\n if (this._subEmitters && this._subEmitters.length != 0) {\n this.activeSubSystems = new Array();\n }\n // Reset emit gradient so it acts the same on every start\n if (this._emitRateGradients) {\n if (this._emitRateGradients.length > 0) {\n this._currentEmitRateGradient = this._emitRateGradients[0];\n this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();\n this._currentEmitRate2 = this._currentEmitRate1;\n }\n if (this._emitRateGradients.length > 1) {\n this._currentEmitRate2 = this._emitRateGradients[1].getFactor();\n }\n }\n // Reset start size gradient so it acts the same on every start\n if (this._startSizeGradients) {\n if (this._startSizeGradients.length > 0) {\n this._currentStartSizeGradient = this._startSizeGradients[0];\n this._currentStartSize1 = this._currentStartSizeGradient.getFactor();\n this._currentStartSize2 = this._currentStartSize1;\n }\n if (this._startSizeGradients.length > 1) {\n this._currentStartSize2 = this._startSizeGradients[1].getFactor();\n }\n }\n if (this.preWarmCycles) {\n if (((_a = this.emitter) === null || _a === void 0 ? void 0 : _a.getClassName().indexOf(\"Mesh\")) !== -1) {\n this.emitter.computeWorldMatrix(true);\n }\n const noiseTextureAsProcedural = this.noiseTexture;\n if (noiseTextureAsProcedural && noiseTextureAsProcedural.onGeneratedObservable) {\n noiseTextureAsProcedural.onGeneratedObservable.addOnce(() => {\n setTimeout(() => {\n for (let index = 0; index < this.preWarmCycles; index++) {\n this.animate(true);\n noiseTextureAsProcedural.render();\n }\n });\n });\n }\n else {\n for (let index = 0; index < this.preWarmCycles; index++) {\n this.animate(true);\n }\n }\n }\n // Animations\n if (this.beginAnimationOnStart && this.animations && this.animations.length > 0 && this._scene) {\n this._scene.beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);\n }\n }\n /**\n * Stops the particle system.\n * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.\n */\n stop(stopSubEmitters = true) {\n if (this._stopped) {\n return;\n }\n this.onStoppedObservable.notifyObservers(this);\n this._stopped = true;\n if (stopSubEmitters) {\n this._stopSubEmitters();\n }\n }\n // animation sheet\n /**\n * Remove all active particles\n */\n reset() {\n this._stockParticles.length = 0;\n this._particles.length = 0;\n }\n /**\n * @internal (for internal use only)\n */\n _appendParticleVertex(index, particle, offsetX, offsetY) {\n let offset = index * this._vertexBufferSize;\n this._vertexData[offset++] = particle.position.x + this.worldOffset.x;\n this._vertexData[offset++] = particle.position.y + this.worldOffset.y;\n this._vertexData[offset++] = particle.position.z + this.worldOffset.z;\n this._vertexData[offset++] = particle.color.r;\n this._vertexData[offset++] = particle.color.g;\n this._vertexData[offset++] = particle.color.b;\n this._vertexData[offset++] = particle.color.a;\n this._vertexData[offset++] = particle.angle;\n this._vertexData[offset++] = particle.scale.x * particle.size;\n this._vertexData[offset++] = particle.scale.y * particle.size;\n if (this._isAnimationSheetEnabled) {\n this._vertexData[offset++] = particle.cellIndex;\n }\n if (!this._isBillboardBased) {\n if (particle._initialDirection) {\n let initialDirection = particle._initialDirection;\n if (this.isLocal) {\n Vector3.TransformNormalToRef(initialDirection, this._emitterWorldMatrix, TmpVectors.Vector3[0]);\n initialDirection = TmpVectors.Vector3[0];\n }\n if (initialDirection.x === 0 && initialDirection.z === 0) {\n initialDirection.x = 0.001;\n }\n this._vertexData[offset++] = initialDirection.x;\n this._vertexData[offset++] = initialDirection.y;\n this._vertexData[offset++] = initialDirection.z;\n }\n else {\n let direction = particle.direction;\n if (this.isLocal) {\n Vector3.TransformNormalToRef(direction, this._emitterWorldMatrix, TmpVectors.Vector3[0]);\n direction = TmpVectors.Vector3[0];\n }\n if (direction.x === 0 && direction.z === 0) {\n direction.x = 0.001;\n }\n this._vertexData[offset++] = direction.x;\n this._vertexData[offset++] = direction.y;\n this._vertexData[offset++] = direction.z;\n }\n }\n else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL) {\n this._vertexData[offset++] = particle.direction.x;\n this._vertexData[offset++] = particle.direction.y;\n this._vertexData[offset++] = particle.direction.z;\n }\n if (this._useRampGradients && particle.remapData) {\n this._vertexData[offset++] = particle.remapData.x;\n this._vertexData[offset++] = particle.remapData.y;\n this._vertexData[offset++] = particle.remapData.z;\n this._vertexData[offset++] = particle.remapData.w;\n }\n if (!this._useInstancing) {\n if (this._isAnimationSheetEnabled) {\n if (offsetX === 0) {\n offsetX = this._epsilon;\n }\n else if (offsetX === 1) {\n offsetX = 1 - this._epsilon;\n }\n if (offsetY === 0) {\n offsetY = this._epsilon;\n }\n else if (offsetY === 1) {\n offsetY = 1 - this._epsilon;\n }\n }\n this._vertexData[offset++] = offsetX;\n this._vertexData[offset++] = offsetY;\n }\n }\n _stopSubEmitters() {\n if (!this.activeSubSystems) {\n return;\n }\n this.activeSubSystems.forEach((subSystem) => {\n subSystem.stop(true);\n });\n this.activeSubSystems = new Array();\n }\n _removeFromRoot() {\n if (!this._rootParticleSystem) {\n return;\n }\n const index = this._rootParticleSystem.activeSubSystems.indexOf(this);\n if (index !== -1) {\n this._rootParticleSystem.activeSubSystems.splice(index, 1);\n }\n this._rootParticleSystem = null;\n }\n // End of sub system methods\n _update(newParticles) {\n // Update current\n this._alive = this._particles.length > 0;\n if (this.emitter.position) {\n const emitterMesh = this.emitter;\n this._emitterWorldMatrix = emitterMesh.getWorldMatrix();\n }\n else {\n const emitterPosition = this.emitter;\n this._emitterWorldMatrix = Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);\n }\n this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix);\n this.updateFunction(this._particles);\n // Add new ones\n let particle;\n for (let index = 0; index < newParticles; index++) {\n if (this._particles.length === this._capacity) {\n break;\n }\n particle = this._createParticle();\n this._particles.push(particle);\n // Life time\n if (this.targetStopDuration && this._lifeTimeGradients && this._lifeTimeGradients.length > 0) {\n const ratio = Scalar.Clamp(this._actualFrame / this.targetStopDuration);\n GradientHelper.GetCurrentGradient(ratio, this._lifeTimeGradients, (currentGradient, nextGradient) => {\n const factorGradient1 = currentGradient;\n const factorGradient2 = nextGradient;\n const lifeTime1 = factorGradient1.getFactor();\n const lifeTime2 = factorGradient2.getFactor();\n const gradient = (ratio - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);\n particle.lifeTime = Scalar.Lerp(lifeTime1, lifeTime2, gradient);\n });\n }\n else {\n particle.lifeTime = Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);\n }\n // Emitter\n const emitPower = Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);\n if (this.startPositionFunction) {\n this.startPositionFunction(this._emitterWorldMatrix, particle.position, particle, this.isLocal);\n }\n else {\n this.particleEmitterType.startPositionFunction(this._emitterWorldMatrix, particle.position, particle, this.isLocal);\n }\n if (this.isLocal) {\n if (!particle._localPosition) {\n particle._localPosition = particle.position.clone();\n }\n else {\n particle._localPosition.copyFrom(particle.position);\n }\n Vector3.TransformCoordinatesToRef(particle._localPosition, this._emitterWorldMatrix, particle.position);\n }\n if (this.startDirectionFunction) {\n this.startDirectionFunction(this._emitterWorldMatrix, particle.direction, particle, this.isLocal);\n }\n else {\n this.particleEmitterType.startDirectionFunction(this._emitterWorldMatrix, particle.direction, particle, this.isLocal, this._emitterInverseWorldMatrix);\n }\n if (emitPower === 0) {\n if (!particle._initialDirection) {\n particle._initialDirection = particle.direction.clone();\n }\n else {\n particle._initialDirection.copyFrom(particle.direction);\n }\n }\n else {\n particle._initialDirection = null;\n }\n particle.direction.scaleInPlace(emitPower);\n // Size\n if (!this._sizeGradients || this._sizeGradients.length === 0) {\n particle.size = Scalar.RandomRange(this.minSize, this.maxSize);\n }\n else {\n particle._currentSizeGradient = this._sizeGradients[0];\n particle._currentSize1 = particle._currentSizeGradient.getFactor();\n particle.size = particle._currentSize1;\n if (this._sizeGradients.length > 1) {\n particle._currentSize2 = this._sizeGradients[1].getFactor();\n }\n else {\n particle._currentSize2 = particle._currentSize1;\n }\n }\n // Size and scale\n particle.scale.copyFromFloats(Scalar.RandomRange(this.minScaleX, this.maxScaleX), Scalar.RandomRange(this.minScaleY, this.maxScaleY));\n // Adjust scale by start size\n if (this._startSizeGradients && this._startSizeGradients[0] && this.targetStopDuration) {\n const ratio = this._actualFrame / this.targetStopDuration;\n GradientHelper.GetCurrentGradient(ratio, this._startSizeGradients, (currentGradient, nextGradient, scale) => {\n if (currentGradient !== this._currentStartSizeGradient) {\n this._currentStartSize1 = this._currentStartSize2;\n this._currentStartSize2 = nextGradient.getFactor();\n this._currentStartSizeGradient = currentGradient;\n }\n const value = Scalar.Lerp(this._currentStartSize1, this._currentStartSize2, scale);\n particle.scale.scaleInPlace(value);\n });\n }\n // Angle\n if (!this._angularSpeedGradients || this._angularSpeedGradients.length === 0) {\n particle.angularSpeed = Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);\n }\n else {\n particle._currentAngularSpeedGradient = this._angularSpeedGradients[0];\n particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();\n particle._currentAngularSpeed1 = particle.angularSpeed;\n if (this._angularSpeedGradients.length > 1) {\n particle._currentAngularSpeed2 = this._angularSpeedGradients[1].getFactor();\n }\n else {\n particle._currentAngularSpeed2 = particle._currentAngularSpeed1;\n }\n }\n particle.angle = Scalar.RandomRange(this.minInitialRotation, this.maxInitialRotation);\n // Velocity\n if (this._velocityGradients && this._velocityGradients.length > 0) {\n particle._currentVelocityGradient = this._velocityGradients[0];\n particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();\n if (this._velocityGradients.length > 1) {\n particle._currentVelocity2 = this._velocityGradients[1].getFactor();\n }\n else {\n particle._currentVelocity2 = particle._currentVelocity1;\n }\n }\n // Limit velocity\n if (this._limitVelocityGradients && this._limitVelocityGradients.length > 0) {\n particle._currentLimitVelocityGradient = this._limitVelocityGradients[0];\n particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();\n if (this._limitVelocityGradients.length > 1) {\n particle._currentLimitVelocity2 = this._limitVelocityGradients[1].getFactor();\n }\n else {\n particle._currentLimitVelocity2 = particle._currentLimitVelocity1;\n }\n }\n // Drag\n if (this._dragGradients && this._dragGradients.length > 0) {\n particle._currentDragGradient = this._dragGradients[0];\n particle._currentDrag1 = particle._currentDragGradient.getFactor();\n if (this._dragGradients.length > 1) {\n particle._currentDrag2 = this._dragGradients[1].getFactor();\n }\n else {\n particle._currentDrag2 = particle._currentDrag1;\n }\n }\n // Color\n if (!this._colorGradients || this._colorGradients.length === 0) {\n const step = Scalar.RandomRange(0, 1.0);\n Color4.LerpToRef(this.color1, this.color2, step, particle.color);\n this.colorDead.subtractToRef(particle.color, this._colorDiff);\n this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);\n }\n else {\n particle._currentColorGradient = this._colorGradients[0];\n particle._currentColorGradient.getColorToRef(particle.color);\n particle._currentColor1.copyFrom(particle.color);\n if (this._colorGradients.length > 1) {\n this._colorGradients[1].getColorToRef(particle._currentColor2);\n }\n else {\n particle._currentColor2.copyFrom(particle.color);\n }\n }\n // Sheet\n if (this._isAnimationSheetEnabled) {\n particle._initialStartSpriteCellID = this.startSpriteCellID;\n particle._initialEndSpriteCellID = this.endSpriteCellID;\n particle._initialSpriteCellLoop = this.spriteCellLoop;\n }\n // Inherited Velocity\n particle.direction.addInPlace(this._inheritedVelocityOffset);\n // Ramp\n if (this._useRampGradients) {\n particle.remapData = new Vector4(0, 1, 0, 1);\n }\n // Noise texture coordinates\n if (this.noiseTexture) {\n if (particle._randomNoiseCoordinates1) {\n particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());\n particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());\n }\n else {\n particle._randomNoiseCoordinates1 = new Vector3(Math.random(), Math.random(), Math.random());\n particle._randomNoiseCoordinates2 = new Vector3(Math.random(), Math.random(), Math.random());\n }\n }\n // Update the position of the attached sub-emitters to match their attached particle\n particle._inheritParticleInfoToSubEmitters();\n }\n }\n /**\n * @internal\n */\n static _GetAttributeNamesOrOptions(isAnimationSheetEnabled = false, isBillboardBased = false, useRampGradients = false) {\n const attributeNamesOrOptions = [VertexBuffer.PositionKind, VertexBuffer.ColorKind, \"angle\", \"offset\", \"size\"];\n if (isAnimationSheetEnabled) {\n attributeNamesOrOptions.push(\"cellIndex\");\n }\n if (!isBillboardBased) {\n attributeNamesOrOptions.push(\"direction\");\n }\n if (useRampGradients) {\n attributeNamesOrOptions.push(\"remapData\");\n }\n return attributeNamesOrOptions;\n }\n /**\n * @internal\n */\n static _GetEffectCreationOptions(isAnimationSheetEnabled = false, useLogarithmicDepth = false) {\n const effectCreationOption = [\"invView\", \"view\", \"projection\", \"textureMask\", \"translationPivot\", \"eyePosition\"];\n addClipPlaneUniforms(effectCreationOption);\n if (isAnimationSheetEnabled) {\n effectCreationOption.push(\"particlesInfos\");\n }\n if (useLogarithmicDepth) {\n effectCreationOption.push(\"logarithmicDepthConstant\");\n }\n return effectCreationOption;\n }\n /**\n * Fill the defines array according to the current settings of the particle system\n * @param defines Array to be updated\n * @param blendMode blend mode to take into account when updating the array\n */\n fillDefines(defines, blendMode) {\n if (this._scene) {\n prepareStringDefinesForClipPlanes(this, this._scene, defines);\n }\n if (this._isAnimationSheetEnabled) {\n defines.push(\"#define ANIMATESHEET\");\n }\n if (this.useLogarithmicDepth) {\n defines.push(\"#define LOGARITHMICDEPTH\");\n }\n if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {\n defines.push(\"#define BLENDMULTIPLYMODE\");\n }\n if (this._useRampGradients) {\n defines.push(\"#define RAMPGRADIENT\");\n }\n if (this._isBillboardBased) {\n defines.push(\"#define BILLBOARD\");\n switch (this.billboardMode) {\n case ParticleSystem.BILLBOARDMODE_Y:\n defines.push(\"#define BILLBOARDY\");\n break;\n case ParticleSystem.BILLBOARDMODE_STRETCHED:\n case ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL:\n defines.push(\"#define BILLBOARDSTRETCHED\");\n if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL) {\n defines.push(\"#define BILLBOARDSTRETCHED_LOCAL\");\n }\n break;\n case ParticleSystem.BILLBOARDMODE_ALL:\n defines.push(\"#define BILLBOARDMODE_ALL\");\n break;\n default:\n break;\n }\n }\n if (this._imageProcessingConfiguration) {\n this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);\n defines.push(this._imageProcessingConfigurationDefines.toString());\n }\n }\n /**\n * Fill the uniforms, attributes and samplers arrays according to the current settings of the particle system\n * @param uniforms Uniforms array to fill\n * @param attributes Attributes array to fill\n * @param samplers Samplers array to fill\n */\n fillUniformsAttributesAndSamplerNames(uniforms, attributes, samplers) {\n attributes.push(...ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL, this._useRampGradients));\n uniforms.push(...ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled, this.useLogarithmicDepth));\n samplers.push(\"diffuseSampler\", \"rampSampler\");\n if (this._imageProcessingConfiguration) {\n ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);\n ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);\n }\n }\n /**\n * @internal\n */\n _getWrapper(blendMode) {\n const customWrapper = this._getCustomDrawWrapper(blendMode);\n if (customWrapper === null || customWrapper === void 0 ? void 0 : customWrapper.effect) {\n return customWrapper;\n }\n const defines = [];\n this.fillDefines(defines, blendMode);\n // Effect\n const currentRenderPassId = this._engine._features.supportRenderPasses ? this._engine.currentRenderPassId : 0;\n let drawWrappers = this._drawWrappers[currentRenderPassId];\n if (!drawWrappers) {\n drawWrappers = this._drawWrappers[currentRenderPassId] = [];\n }\n let drawWrapper = drawWrappers[blendMode];\n if (!drawWrapper) {\n drawWrapper = new DrawWrapper(this._engine);\n if (drawWrapper.drawContext) {\n drawWrapper.drawContext.useInstancing = this._useInstancing;\n }\n drawWrappers[blendMode] = drawWrapper;\n }\n const join = defines.join(\"\\n\");\n if (drawWrapper.defines !== join) {\n const attributesNamesOrOptions = [];\n const effectCreationOption = [];\n const samplers = [];\n this.fillUniformsAttributesAndSamplerNames(effectCreationOption, attributesNamesOrOptions, samplers);\n drawWrapper.setEffect(this._engine.createEffect(\"particles\", attributesNamesOrOptions, effectCreationOption, samplers, join), join);\n }\n return drawWrapper;\n }\n /**\n * Animates the particle system for the current frame by emitting new particles and or animating the living ones.\n * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)\n */\n animate(preWarmOnly = false) {\n var _a;\n if (!this._started) {\n return;\n }\n if (!preWarmOnly && this._scene) {\n // Check\n if (!this.isReady()) {\n return;\n }\n if (this._currentRenderId === this._scene.getFrameId()) {\n return;\n }\n this._currentRenderId = this._scene.getFrameId();\n }\n this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : ((_a = this._scene) === null || _a === void 0 ? void 0 : _a.getAnimationRatio()) || 1);\n // Determine the number of particles we need to create\n let newParticles;\n if (this.manualEmitCount > -1) {\n newParticles = this.manualEmitCount;\n this._newPartsExcess = 0;\n this.manualEmitCount = 0;\n }\n else {\n let rate = this.emitRate;\n if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {\n const ratio = this._actualFrame / this.targetStopDuration;\n GradientHelper.GetCurrentGradient(ratio, this._emitRateGradients, (currentGradient, nextGradient, scale) => {\n if (currentGradient !== this._currentEmitRateGradient) {\n this._currentEmitRate1 = this._currentEmitRate2;\n this._currentEmitRate2 = nextGradient.getFactor();\n this._currentEmitRateGradient = currentGradient;\n }\n rate = Scalar.Lerp(this._currentEmitRate1, this._currentEmitRate2, scale);\n });\n }\n newParticles = (rate * this._scaledUpdateSpeed) >> 0;\n this._newPartsExcess += rate * this._scaledUpdateSpeed - newParticles;\n }\n if (this._newPartsExcess > 1.0) {\n newParticles += this._newPartsExcess >> 0;\n this._newPartsExcess -= this._newPartsExcess >> 0;\n }\n this._alive = false;\n if (!this._stopped) {\n this._actualFrame += this._scaledUpdateSpeed;\n if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {\n this.stop();\n }\n }\n else {\n newParticles = 0;\n }\n this._update(newParticles);\n // Stopped?\n if (this._stopped) {\n if (!this._alive) {\n this._started = false;\n if (this.onAnimationEnd) {\n this.onAnimationEnd();\n }\n if (this.disposeOnStop && this._scene) {\n this._scene._toBeDisposed.push(this);\n }\n }\n }\n if (!preWarmOnly) {\n // Update VBO\n let offset = 0;\n for (let index = 0; index < this._particles.length; index++) {\n const particle = this._particles[index];\n this._appendParticleVertices(offset, particle);\n offset += this._useInstancing ? 1 : 4;\n }\n if (this._vertexBuffer) {\n this._vertexBuffer.updateDirectly(this._vertexData, 0, this._particles.length);\n }\n }\n if (this.manualEmitCount === 0 && this.disposeOnStop) {\n this.stop();\n }\n }\n _appendParticleVertices(offset, particle) {\n this._appendParticleVertex(offset++, particle, 0, 0);\n if (!this._useInstancing) {\n this._appendParticleVertex(offset++, particle, 1, 0);\n this._appendParticleVertex(offset++, particle, 1, 1);\n this._appendParticleVertex(offset++, particle, 0, 1);\n }\n }\n /**\n * Rebuilds the particle system.\n */\n rebuild() {\n var _a, _b;\n if (this._engine.getCaps().vertexArrayObject) {\n this._vertexArrayObject = null;\n }\n this._createIndexBuffer();\n (_a = this._spriteBuffer) === null || _a === void 0 ? void 0 : _a._rebuild();\n (_b = this._vertexBuffer) === null || _b === void 0 ? void 0 : _b._rebuild();\n for (const key in this._vertexBuffers) {\n this._vertexBuffers[key]._rebuild();\n }\n this.resetDrawCache();\n }\n /**\n * Is this system ready to be used/rendered\n * @returns true if the system is ready\n */\n isReady() {\n if (!this.emitter || (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.isReady()) || !this.particleTexture || !this.particleTexture.isReady()) {\n return false;\n }\n if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {\n if (!this._getWrapper(this.blendMode).effect.isReady()) {\n return false;\n }\n }\n else {\n if (!this._getWrapper(ParticleSystem.BLENDMODE_MULTIPLY).effect.isReady()) {\n return false;\n }\n if (!this._getWrapper(ParticleSystem.BLENDMODE_ADD).effect.isReady()) {\n return false;\n }\n }\n return true;\n }\n _render(blendMode) {\n var _a, _b;\n const drawWrapper = this._getWrapper(blendMode);\n const effect = drawWrapper.effect;\n const engine = this._engine;\n // Render\n engine.enableEffect(drawWrapper);\n const viewMatrix = (_a = this.defaultViewMatrix) !== null && _a !== void 0 ? _a : this._scene.getViewMatrix();\n effect.setTexture(\"diffuseSampler\", this.particleTexture);\n effect.setMatrix(\"view\", viewMatrix);\n effect.setMatrix(\"projection\", (_b = this.defaultProjectionMatrix) !== null && _b !== void 0 ? _b : this._scene.getProjectionMatrix());\n if (this._isAnimationSheetEnabled && this.particleTexture) {\n const baseSize = this.particleTexture.getBaseSize();\n effect.setFloat3(\"particlesInfos\", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, this.spriteCellWidth / baseSize.width);\n }\n effect.setVector2(\"translationPivot\", this.translationPivot);\n effect.setFloat4(\"textureMask\", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);\n if (this._isBillboardBased && this._scene) {\n const camera = this._scene.activeCamera;\n effect.setVector3(\"eyePosition\", camera.globalPosition);\n }\n if (this._rampGradientsTexture) {\n if (!this._rampGradients || !this._rampGradients.length) {\n this._rampGradientsTexture.dispose();\n this._rampGradientsTexture = null;\n }\n effect.setTexture(\"rampSampler\", this._rampGradientsTexture);\n }\n const defines = effect.defines;\n if (this._scene) {\n bindClipPlane(effect, this, this._scene);\n }\n if (defines.indexOf(\"#define BILLBOARDMODE_ALL\") >= 0) {\n viewMatrix.invertToRef(TmpVectors.Matrix[0]);\n effect.setMatrix(\"invView\", TmpVectors.Matrix[0]);\n }\n if (this._vertexArrayObject !== undefined) {\n if (!this._vertexArrayObject) {\n this._vertexArrayObject = this._engine.recordVertexArrayObject(this._vertexBuffers, this._indexBuffer, effect);\n }\n this._engine.bindVertexArrayObject(this._vertexArrayObject, this._indexBuffer);\n }\n else {\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);\n }\n // Log. depth\n if (this.useLogarithmicDepth && this._scene) {\n MaterialHelper.BindLogDepth(defines, effect, this._scene);\n }\n // image processing\n if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {\n this._imageProcessingConfiguration.bind(effect);\n }\n // Draw order\n switch (blendMode) {\n case ParticleSystem.BLENDMODE_ADD:\n engine.setAlphaMode(1);\n break;\n case ParticleSystem.BLENDMODE_ONEONE:\n engine.setAlphaMode(6);\n break;\n case ParticleSystem.BLENDMODE_STANDARD:\n engine.setAlphaMode(2);\n break;\n case ParticleSystem.BLENDMODE_MULTIPLY:\n engine.setAlphaMode(4);\n break;\n }\n if (this._onBeforeDrawParticlesObservable) {\n this._onBeforeDrawParticlesObservable.notifyObservers(effect);\n }\n if (this._useInstancing) {\n engine.drawArraysType(7, 0, 4, this._particles.length);\n }\n else {\n engine.drawElementsType(0, 0, this._particles.length * 6);\n }\n return this._particles.length;\n }\n /**\n * Renders the particle system in its current state.\n * @returns the current number of particles\n */\n render() {\n // Check\n if (!this.isReady() || !this._particles.length) {\n return 0;\n }\n const engine = this._engine;\n if (engine.setState) {\n engine.setState(false);\n if (this.forceDepthWrite) {\n engine.setDepthWrite(true);\n }\n }\n let outparticles = 0;\n if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {\n outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);\n }\n else {\n outparticles = this._render(this.blendMode);\n }\n this._engine.unbindInstanceAttributes();\n this._engine.setAlphaMode(0);\n return outparticles;\n }\n /**\n * Disposes the particle system and free the associated resources\n * @param disposeTexture defines if the particle texture must be disposed as well (true by default)\n */\n dispose(disposeTexture = true) {\n this.resetDrawCache();\n if (this._vertexBuffer) {\n this._vertexBuffer.dispose();\n this._vertexBuffer = null;\n }\n if (this._spriteBuffer) {\n this._spriteBuffer.dispose();\n this._spriteBuffer = null;\n }\n if (this._indexBuffer) {\n this._engine._releaseBuffer(this._indexBuffer);\n this._indexBuffer = null;\n }\n if (this._vertexArrayObject) {\n this._engine.releaseVertexArrayObject(this._vertexArrayObject);\n this._vertexArrayObject = null;\n }\n if (disposeTexture && this.particleTexture) {\n this.particleTexture.dispose();\n this.particleTexture = null;\n }\n if (disposeTexture && this.noiseTexture) {\n this.noiseTexture.dispose();\n this.noiseTexture = null;\n }\n if (this._rampGradientsTexture) {\n this._rampGradientsTexture.dispose();\n this._rampGradientsTexture = null;\n }\n this._removeFromRoot();\n if (this.subEmitters && !this._subEmitters) {\n this._prepareSubEmitterInternalArray();\n }\n if (this._subEmitters && this._subEmitters.length) {\n for (let index = 0; index < this._subEmitters.length; index++) {\n for (const subEmitter of this._subEmitters[index]) {\n subEmitter.dispose();\n }\n }\n this._subEmitters = [];\n this.subEmitters = [];\n }\n if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {\n this.emitter.dispose(true);\n }\n if (this._onBeforeDrawParticlesObservable) {\n this._onBeforeDrawParticlesObservable.clear();\n }\n // Remove from scene\n if (this._scene) {\n const index = this._scene.particleSystems.indexOf(this);\n if (index > -1) {\n this._scene.particleSystems.splice(index, 1);\n }\n this._scene._activeParticleSystems.dispose();\n }\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n this.onStoppedObservable.clear();\n this.reset();\n }\n // Clone\n /**\n * Clones the particle system.\n * @param name The name of the cloned object\n * @param newEmitter The new emitter to use\n * @param cloneTexture Also clone the textures if true\n * @returns the cloned particle system\n */\n clone(name, newEmitter, cloneTexture = false) {\n const custom = Object.assign({}, this._customWrappers);\n let program = null;\n const engine = this._engine;\n if (engine.createEffectForParticles) {\n if (this.customShader != null) {\n program = this.customShader;\n const defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join(\"\\n\") : \"\";\n const effect = engine.createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);\n if (!custom[0]) {\n this.setCustomEffect(effect, 0);\n }\n else {\n custom[0].effect = effect;\n }\n }\n }\n const serialization = this.serialize(cloneTexture);\n const result = ParticleSystem.Parse(serialization, this._scene || this._engine, this._rootUrl);\n result.name = name;\n result.customShader = program;\n result._customWrappers = custom;\n if (newEmitter === undefined) {\n newEmitter = this.emitter;\n }\n if (this.noiseTexture) {\n result.noiseTexture = this.noiseTexture.clone();\n }\n result.emitter = newEmitter;\n if (!this.preventAutoStart) {\n result.start();\n }\n return result;\n }\n /**\n * Serializes the particle system to a JSON object\n * @param serializeTexture defines if the texture must be serialized as well\n * @returns the JSON object\n */\n serialize(serializeTexture = false) {\n const serializationObject = {};\n ParticleSystem._Serialize(serializationObject, this, serializeTexture);\n serializationObject.textureMask = this.textureMask.asArray();\n serializationObject.customShader = this.customShader;\n serializationObject.preventAutoStart = this.preventAutoStart;\n // SubEmitters\n if (this.subEmitters) {\n serializationObject.subEmitters = [];\n if (!this._subEmitters) {\n this._prepareSubEmitterInternalArray();\n }\n for (const subs of this._subEmitters) {\n const cell = [];\n for (const sub of subs) {\n cell.push(sub.serialize(serializeTexture));\n }\n serializationObject.subEmitters.push(cell);\n }\n }\n return serializationObject;\n }\n /**\n * @internal\n */\n static _Serialize(serializationObject, particleSystem, serializeTexture) {\n serializationObject.name = particleSystem.name;\n serializationObject.id = particleSystem.id;\n serializationObject.capacity = particleSystem.getCapacity();\n serializationObject.disposeOnStop = particleSystem.disposeOnStop;\n serializationObject.manualEmitCount = particleSystem.manualEmitCount;\n // Emitter\n if (particleSystem.emitter.position) {\n const emitterMesh = particleSystem.emitter;\n serializationObject.emitterId = emitterMesh.id;\n }\n else {\n const emitterPosition = particleSystem.emitter;\n serializationObject.emitter = emitterPosition.asArray();\n }\n // Emitter\n if (particleSystem.particleEmitterType) {\n serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();\n }\n if (particleSystem.particleTexture) {\n if (serializeTexture) {\n serializationObject.texture = particleSystem.particleTexture.serialize();\n }\n else {\n serializationObject.textureName = particleSystem.particleTexture.name;\n serializationObject.invertY = !!particleSystem.particleTexture._invertY;\n }\n }\n serializationObject.isLocal = particleSystem.isLocal;\n // Animations\n SerializationHelper.AppendSerializedAnimations(particleSystem, serializationObject);\n serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;\n serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;\n serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;\n serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;\n // Particle system\n serializationObject.startDelay = particleSystem.startDelay;\n serializationObject.renderingGroupId = particleSystem.renderingGroupId;\n serializationObject.isBillboardBased = particleSystem.isBillboardBased;\n serializationObject.billboardMode = particleSystem.billboardMode;\n serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;\n serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;\n serializationObject.minSize = particleSystem.minSize;\n serializationObject.maxSize = particleSystem.maxSize;\n serializationObject.minScaleX = particleSystem.minScaleX;\n serializationObject.maxScaleX = particleSystem.maxScaleX;\n serializationObject.minScaleY = particleSystem.minScaleY;\n serializationObject.maxScaleY = particleSystem.maxScaleY;\n serializationObject.minEmitPower = particleSystem.minEmitPower;\n serializationObject.maxEmitPower = particleSystem.maxEmitPower;\n serializationObject.minLifeTime = particleSystem.minLifeTime;\n serializationObject.maxLifeTime = particleSystem.maxLifeTime;\n serializationObject.emitRate = particleSystem.emitRate;\n serializationObject.gravity = particleSystem.gravity.asArray();\n serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();\n serializationObject.color1 = particleSystem.color1.asArray();\n serializationObject.color2 = particleSystem.color2.asArray();\n serializationObject.colorDead = particleSystem.colorDead.asArray();\n serializationObject.updateSpeed = particleSystem.updateSpeed;\n serializationObject.targetStopDuration = particleSystem.targetStopDuration;\n serializationObject.blendMode = particleSystem.blendMode;\n serializationObject.preWarmCycles = particleSystem.preWarmCycles;\n serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;\n serializationObject.minInitialRotation = particleSystem.minInitialRotation;\n serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;\n serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;\n serializationObject.spriteCellLoop = particleSystem.spriteCellLoop;\n serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;\n serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;\n serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;\n serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;\n serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;\n serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;\n serializationObject.useLogarithmicDepth = particleSystem.useLogarithmicDepth;\n const colorGradients = particleSystem.getColorGradients();\n if (colorGradients) {\n serializationObject.colorGradients = [];\n for (const colorGradient of colorGradients) {\n const serializedGradient = {\n gradient: colorGradient.gradient,\n color1: colorGradient.color1.asArray(),\n };\n if (colorGradient.color2) {\n serializedGradient.color2 = colorGradient.color2.asArray();\n }\n else {\n serializedGradient.color2 = colorGradient.color1.asArray();\n }\n serializationObject.colorGradients.push(serializedGradient);\n }\n }\n const rampGradients = particleSystem.getRampGradients();\n if (rampGradients) {\n serializationObject.rampGradients = [];\n for (const rampGradient of rampGradients) {\n const serializedGradient = {\n gradient: rampGradient.gradient,\n color: rampGradient.color.asArray(),\n };\n serializationObject.rampGradients.push(serializedGradient);\n }\n serializationObject.useRampGradients = particleSystem.useRampGradients;\n }\n const colorRemapGradients = particleSystem.getColorRemapGradients();\n if (colorRemapGradients) {\n serializationObject.colorRemapGradients = [];\n for (const colorRemapGradient of colorRemapGradients) {\n const serializedGradient = {\n gradient: colorRemapGradient.gradient,\n factor1: colorRemapGradient.factor1,\n };\n if (colorRemapGradient.factor2 !== undefined) {\n serializedGradient.factor2 = colorRemapGradient.factor2;\n }\n else {\n serializedGradient.factor2 = colorRemapGradient.factor1;\n }\n serializationObject.colorRemapGradients.push(serializedGradient);\n }\n }\n const alphaRemapGradients = particleSystem.getAlphaRemapGradients();\n if (alphaRemapGradients) {\n serializationObject.alphaRemapGradients = [];\n for (const alphaRemapGradient of alphaRemapGradients) {\n const serializedGradient = {\n gradient: alphaRemapGradient.gradient,\n factor1: alphaRemapGradient.factor1,\n };\n if (alphaRemapGradient.factor2 !== undefined) {\n serializedGradient.factor2 = alphaRemapGradient.factor2;\n }\n else {\n serializedGradient.factor2 = alphaRemapGradient.factor1;\n }\n serializationObject.alphaRemapGradients.push(serializedGradient);\n }\n }\n const sizeGradients = particleSystem.getSizeGradients();\n if (sizeGradients) {\n serializationObject.sizeGradients = [];\n for (const sizeGradient of sizeGradients) {\n const serializedGradient = {\n gradient: sizeGradient.gradient,\n factor1: sizeGradient.factor1,\n };\n if (sizeGradient.factor2 !== undefined) {\n serializedGradient.factor2 = sizeGradient.factor2;\n }\n else {\n serializedGradient.factor2 = sizeGradient.factor1;\n }\n serializationObject.sizeGradients.push(serializedGradient);\n }\n }\n const angularSpeedGradients = particleSystem.getAngularSpeedGradients();\n if (angularSpeedGradients) {\n serializationObject.angularSpeedGradients = [];\n for (const angularSpeedGradient of angularSpeedGradients) {\n const serializedGradient = {\n gradient: angularSpeedGradient.gradient,\n factor1: angularSpeedGradient.factor1,\n };\n if (angularSpeedGradient.factor2 !== undefined) {\n serializedGradient.factor2 = angularSpeedGradient.factor2;\n }\n else {\n serializedGradient.factor2 = angularSpeedGradient.factor1;\n }\n serializationObject.angularSpeedGradients.push(serializedGradient);\n }\n }\n const velocityGradients = particleSystem.getVelocityGradients();\n if (velocityGradients) {\n serializationObject.velocityGradients = [];\n for (const velocityGradient of velocityGradients) {\n const serializedGradient = {\n gradient: velocityGradient.gradient,\n factor1: velocityGradient.factor1,\n };\n if (velocityGradient.factor2 !== undefined) {\n serializedGradient.factor2 = velocityGradient.factor2;\n }\n else {\n serializedGradient.factor2 = velocityGradient.factor1;\n }\n serializationObject.velocityGradients.push(serializedGradient);\n }\n }\n const dragGradients = particleSystem.getDragGradients();\n if (dragGradients) {\n serializationObject.dragGradients = [];\n for (const dragGradient of dragGradients) {\n const serializedGradient = {\n gradient: dragGradient.gradient,\n factor1: dragGradient.factor1,\n };\n if (dragGradient.factor2 !== undefined) {\n serializedGradient.factor2 = dragGradient.factor2;\n }\n else {\n serializedGradient.factor2 = dragGradient.factor1;\n }\n serializationObject.dragGradients.push(serializedGradient);\n }\n }\n const emitRateGradients = particleSystem.getEmitRateGradients();\n if (emitRateGradients) {\n serializationObject.emitRateGradients = [];\n for (const emitRateGradient of emitRateGradients) {\n const serializedGradient = {\n gradient: emitRateGradient.gradient,\n factor1: emitRateGradient.factor1,\n };\n if (emitRateGradient.factor2 !== undefined) {\n serializedGradient.factor2 = emitRateGradient.factor2;\n }\n else {\n serializedGradient.factor2 = emitRateGradient.factor1;\n }\n serializationObject.emitRateGradients.push(serializedGradient);\n }\n }\n const startSizeGradients = particleSystem.getStartSizeGradients();\n if (startSizeGradients) {\n serializationObject.startSizeGradients = [];\n for (const startSizeGradient of startSizeGradients) {\n const serializedGradient = {\n gradient: startSizeGradient.gradient,\n factor1: startSizeGradient.factor1,\n };\n if (startSizeGradient.factor2 !== undefined) {\n serializedGradient.factor2 = startSizeGradient.factor2;\n }\n else {\n serializedGradient.factor2 = startSizeGradient.factor1;\n }\n serializationObject.startSizeGradients.push(serializedGradient);\n }\n }\n const lifeTimeGradients = particleSystem.getLifeTimeGradients();\n if (lifeTimeGradients) {\n serializationObject.lifeTimeGradients = [];\n for (const lifeTimeGradient of lifeTimeGradients) {\n const serializedGradient = {\n gradient: lifeTimeGradient.gradient,\n factor1: lifeTimeGradient.factor1,\n };\n if (lifeTimeGradient.factor2 !== undefined) {\n serializedGradient.factor2 = lifeTimeGradient.factor2;\n }\n else {\n serializedGradient.factor2 = lifeTimeGradient.factor1;\n }\n serializationObject.lifeTimeGradients.push(serializedGradient);\n }\n }\n const limitVelocityGradients = particleSystem.getLimitVelocityGradients();\n if (limitVelocityGradients) {\n serializationObject.limitVelocityGradients = [];\n for (const limitVelocityGradient of limitVelocityGradients) {\n const serializedGradient = {\n gradient: limitVelocityGradient.gradient,\n factor1: limitVelocityGradient.factor1,\n };\n if (limitVelocityGradient.factor2 !== undefined) {\n serializedGradient.factor2 = limitVelocityGradient.factor2;\n }\n else {\n serializedGradient.factor2 = limitVelocityGradient.factor1;\n }\n serializationObject.limitVelocityGradients.push(serializedGradient);\n }\n serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;\n }\n if (particleSystem.noiseTexture) {\n serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();\n }\n }\n /**\n * @internal\n */\n static _Parse(parsedParticleSystem, particleSystem, sceneOrEngine, rootUrl) {\n var _a, _b, _c;\n let scene;\n if (sceneOrEngine instanceof ThinEngine) {\n scene = null;\n }\n else {\n scene = sceneOrEngine;\n }\n const internalClass = GetClass(\"BABYLON.Texture\");\n if (internalClass && scene) {\n // Texture\n if (parsedParticleSystem.texture) {\n particleSystem.particleTexture = internalClass.Parse(parsedParticleSystem.texture, scene, rootUrl);\n }\n else if (parsedParticleSystem.textureName) {\n particleSystem.particleTexture = new internalClass(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);\n particleSystem.particleTexture.name = parsedParticleSystem.textureName;\n }\n }\n // Emitter\n if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {\n particleSystem.emitter = Vector3.Zero();\n }\n else if (parsedParticleSystem.emitterId && scene) {\n particleSystem.emitter = scene.getLastMeshById(parsedParticleSystem.emitterId);\n }\n else {\n particleSystem.emitter = Vector3.FromArray(parsedParticleSystem.emitter);\n }\n particleSystem.isLocal = !!parsedParticleSystem.isLocal;\n // Misc.\n if (parsedParticleSystem.renderingGroupId !== undefined) {\n particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;\n }\n if (parsedParticleSystem.isBillboardBased !== undefined) {\n particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;\n }\n if (parsedParticleSystem.billboardMode !== undefined) {\n particleSystem.billboardMode = parsedParticleSystem.billboardMode;\n }\n if (parsedParticleSystem.useLogarithmicDepth !== undefined) {\n particleSystem.useLogarithmicDepth = parsedParticleSystem.useLogarithmicDepth;\n }\n // Animations\n if (parsedParticleSystem.animations) {\n for (let animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {\n const parsedAnimation = parsedParticleSystem.animations[animationIndex];\n const internalClass = GetClass(\"BABYLON.Animation\");\n if (internalClass) {\n particleSystem.animations.push(internalClass.Parse(parsedAnimation));\n }\n }\n particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;\n particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;\n particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;\n particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;\n }\n if (parsedParticleSystem.autoAnimate && scene) {\n scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);\n }\n // Particle system\n particleSystem.startDelay = parsedParticleSystem.startDelay | 0;\n particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;\n particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;\n particleSystem.minSize = parsedParticleSystem.minSize;\n particleSystem.maxSize = parsedParticleSystem.maxSize;\n if (parsedParticleSystem.minScaleX) {\n particleSystem.minScaleX = parsedParticleSystem.minScaleX;\n particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;\n particleSystem.minScaleY = parsedParticleSystem.minScaleY;\n particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;\n }\n if (parsedParticleSystem.preWarmCycles !== undefined) {\n particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;\n particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;\n }\n if (parsedParticleSystem.minInitialRotation !== undefined) {\n particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;\n particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;\n }\n particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;\n particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;\n particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;\n particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;\n particleSystem.emitRate = parsedParticleSystem.emitRate;\n particleSystem.gravity = Vector3.FromArray(parsedParticleSystem.gravity);\n if (parsedParticleSystem.noiseStrength) {\n particleSystem.noiseStrength = Vector3.FromArray(parsedParticleSystem.noiseStrength);\n }\n particleSystem.color1 = Color4.FromArray(parsedParticleSystem.color1);\n particleSystem.color2 = Color4.FromArray(parsedParticleSystem.color2);\n particleSystem.colorDead = Color4.FromArray(parsedParticleSystem.colorDead);\n particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;\n particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;\n particleSystem.blendMode = parsedParticleSystem.blendMode;\n if (parsedParticleSystem.colorGradients) {\n for (const colorGradient of parsedParticleSystem.colorGradients) {\n particleSystem.addColorGradient(colorGradient.gradient, Color4.FromArray(colorGradient.color1), colorGradient.color2 ? Color4.FromArray(colorGradient.color2) : undefined);\n }\n }\n if (parsedParticleSystem.rampGradients) {\n for (const rampGradient of parsedParticleSystem.rampGradients) {\n particleSystem.addRampGradient(rampGradient.gradient, Color3.FromArray(rampGradient.color));\n }\n particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;\n }\n if (parsedParticleSystem.colorRemapGradients) {\n for (const colorRemapGradient of parsedParticleSystem.colorRemapGradients) {\n particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);\n }\n }\n if (parsedParticleSystem.alphaRemapGradients) {\n for (const alphaRemapGradient of parsedParticleSystem.alphaRemapGradients) {\n particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);\n }\n }\n if (parsedParticleSystem.sizeGradients) {\n for (const sizeGradient of parsedParticleSystem.sizeGradients) {\n particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);\n }\n }\n if (parsedParticleSystem.angularSpeedGradients) {\n for (const angularSpeedGradient of parsedParticleSystem.angularSpeedGradients) {\n particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);\n }\n }\n if (parsedParticleSystem.velocityGradients) {\n for (const velocityGradient of parsedParticleSystem.velocityGradients) {\n particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);\n }\n }\n if (parsedParticleSystem.dragGradients) {\n for (const dragGradient of parsedParticleSystem.dragGradients) {\n particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);\n }\n }\n if (parsedParticleSystem.emitRateGradients) {\n for (const emitRateGradient of parsedParticleSystem.emitRateGradients) {\n particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);\n }\n }\n if (parsedParticleSystem.startSizeGradients) {\n for (const startSizeGradient of parsedParticleSystem.startSizeGradients) {\n particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);\n }\n }\n if (parsedParticleSystem.lifeTimeGradients) {\n for (const lifeTimeGradient of parsedParticleSystem.lifeTimeGradients) {\n particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);\n }\n }\n if (parsedParticleSystem.limitVelocityGradients) {\n for (const limitVelocityGradient of parsedParticleSystem.limitVelocityGradients) {\n particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);\n }\n particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;\n }\n if (parsedParticleSystem.noiseTexture && scene) {\n const internalClass = GetClass(\"BABYLON.ProceduralTexture\");\n particleSystem.noiseTexture = internalClass.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);\n }\n // Emitter\n let emitterType;\n if (parsedParticleSystem.particleEmitterType) {\n switch (parsedParticleSystem.particleEmitterType.type) {\n case \"SphereParticleEmitter\":\n emitterType = new SphereParticleEmitter();\n break;\n case \"SphereDirectedParticleEmitter\":\n emitterType = new SphereDirectedParticleEmitter();\n break;\n case \"ConeEmitter\":\n case \"ConeParticleEmitter\":\n emitterType = new ConeParticleEmitter();\n break;\n case \"CylinderParticleEmitter\":\n emitterType = new CylinderParticleEmitter();\n break;\n case \"CylinderDirectedParticleEmitter\":\n emitterType = new CylinderDirectedParticleEmitter();\n break;\n case \"HemisphericParticleEmitter\":\n emitterType = new HemisphericParticleEmitter();\n break;\n case \"PointParticleEmitter\":\n emitterType = new PointParticleEmitter();\n break;\n case \"MeshParticleEmitter\":\n emitterType = new MeshParticleEmitter();\n break;\n case \"BoxEmitter\":\n case \"BoxParticleEmitter\":\n default:\n emitterType = new BoxParticleEmitter();\n break;\n }\n emitterType.parse(parsedParticleSystem.particleEmitterType, scene);\n }\n else {\n emitterType = new BoxParticleEmitter();\n emitterType.parse(parsedParticleSystem, scene);\n }\n particleSystem.particleEmitterType = emitterType;\n // Animation sheet\n particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;\n particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;\n particleSystem.spriteCellLoop = (_a = parsedParticleSystem.spriteCellLoop) !== null && _a !== void 0 ? _a : true;\n particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;\n particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;\n particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;\n particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;\n particleSystem.disposeOnStop = (_b = parsedParticleSystem.disposeOnStop) !== null && _b !== void 0 ? _b : false;\n particleSystem.manualEmitCount = (_c = parsedParticleSystem.manualEmitCount) !== null && _c !== void 0 ? _c : -1;\n }\n /**\n * Parses a JSON object to create a particle system.\n * @param parsedParticleSystem The JSON object to parse\n * @param sceneOrEngine The scene or the engine to create the particle system in\n * @param rootUrl The root url to use to load external dependencies like texture\n * @param doNotStart Ignore the preventAutoStart attribute and does not start\n * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used)\n * @returns the Parsed particle system\n */\n static Parse(parsedParticleSystem, sceneOrEngine, rootUrl, doNotStart = false, capacity) {\n const name = parsedParticleSystem.name;\n let custom = null;\n let program = null;\n let engine;\n let scene;\n if (sceneOrEngine instanceof ThinEngine) {\n engine = sceneOrEngine;\n }\n else {\n scene = sceneOrEngine;\n engine = scene.getEngine();\n }\n if (parsedParticleSystem.customShader && engine.createEffectForParticles) {\n program = parsedParticleSystem.customShader;\n const defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join(\"\\n\") : \"\";\n custom = engine.createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);\n }\n const particleSystem = new ParticleSystem(name, capacity || parsedParticleSystem.capacity, sceneOrEngine, custom, parsedParticleSystem.isAnimationSheetEnabled);\n particleSystem.customShader = program;\n particleSystem._rootUrl = rootUrl;\n if (parsedParticleSystem.id) {\n particleSystem.id = parsedParticleSystem.id;\n }\n // SubEmitters\n if (parsedParticleSystem.subEmitters) {\n particleSystem.subEmitters = [];\n for (const cell of parsedParticleSystem.subEmitters) {\n const cellArray = [];\n for (const sub of cell) {\n cellArray.push(SubEmitter.Parse(sub, sceneOrEngine, rootUrl));\n }\n particleSystem.subEmitters.push(cellArray);\n }\n }\n ParticleSystem._Parse(parsedParticleSystem, particleSystem, sceneOrEngine, rootUrl);\n if (parsedParticleSystem.textureMask) {\n particleSystem.textureMask = Color4.FromArray(parsedParticleSystem.textureMask);\n }\n // Auto start\n if (parsedParticleSystem.preventAutoStart) {\n particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;\n }\n if (!doNotStart && !particleSystem.preventAutoStart) {\n particleSystem.start();\n }\n return particleSystem;\n }\n}\n/**\n * Billboard mode will only apply to Y axis\n */\nParticleSystem.BILLBOARDMODE_Y = 2;\n/**\n * Billboard mode will apply to all axes\n */\nParticleSystem.BILLBOARDMODE_ALL = 7;\n/**\n * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction\n */\nParticleSystem.BILLBOARDMODE_STRETCHED = 8;\n/**\n * Special billboard mode where the particle will be billboard to the camera but only around the axis of the direction of particle emission\n */\nParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL = 9;\nSubEmitter._ParseParticleSystem = ParticleSystem.Parse;\n//# sourceMappingURL=particleSystem.js.map","import { FactorGradient, ColorGradient, GradientHelper } from \"../Misc/gradients.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Matrix, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Color4, TmpColors } from \"../Maths/math.color.js\";\nimport { Scalar } from \"../Maths/math.scalar.js\";\nimport { VertexBuffer, Buffer } from \"../Buffers/buffer.js\";\nimport { BaseParticleSystem } from \"./baseParticleSystem.js\";\nimport { ParticleSystem } from \"./particleSystem.js\";\nimport { BoxParticleEmitter } from \"../Particles/EmitterTypes/boxParticleEmitter.js\";\nimport { MaterialHelper } from \"../Materials/materialHelper.js\";\nimport { ImageProcessingConfiguration } from \"../Materials/imageProcessingConfiguration.js\";\nimport { RawTexture } from \"../Materials/Textures/rawTexture.js\";\n\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { CustomParticleEmitter } from \"./EmitterTypes/customParticleEmitter.js\";\nimport { ThinEngine } from \"../Engines/thinEngine.js\";\nimport { DrawWrapper } from \"../Materials/drawWrapper.js\";\nimport { GetClass } from \"../Misc/typeStore.js\";\nimport { addClipPlaneUniforms, bindClipPlane, prepareStringDefinesForClipPlanes } from \"../Materials/clipPlaneMaterialHelper.js\";\nimport \"../Engines/Extensions/engine.transformFeedback.js\";\nimport \"../Shaders/gpuRenderParticles.fragment.js\";\nimport \"../Shaders/gpuRenderParticles.vertex.js\";\n/**\n * This represents a GPU particle system in Babylon\n * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data\n * @see https://www.babylonjs-playground.com/#PU4WYI#4\n */\nexport class GPUParticleSystem extends BaseParticleSystem {\n /**\n * Gets a boolean indicating if the GPU particles can be rendered on current browser\n */\n static get IsSupported() {\n if (!EngineStore.LastCreatedEngine) {\n return false;\n }\n const caps = EngineStore.LastCreatedEngine.getCaps();\n return caps.supportTransformFeedbacks || caps.supportComputeShaders;\n }\n /**\n * Gets the maximum number of particles active at the same time.\n * @returns The max number of active particles.\n */\n getCapacity() {\n return this._capacity;\n }\n /**\n * Gets or set the number of active particles\n */\n get activeParticleCount() {\n return this._activeCount;\n }\n set activeParticleCount(value) {\n this._activeCount = Math.min(value, this._capacity);\n }\n /**\n * Is this system ready to be used/rendered\n * @returns true if the system is ready\n */\n isReady() {\n if (!this.emitter || (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.isReady()) || !this.particleTexture || !this.particleTexture.isReady()) {\n return false;\n }\n if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {\n if (!this._getWrapper(this.blendMode).effect.isReady()) {\n return false;\n }\n }\n else {\n if (!this._getWrapper(ParticleSystem.BLENDMODE_MULTIPLY).effect.isReady()) {\n return false;\n }\n if (!this._getWrapper(ParticleSystem.BLENDMODE_ADD).effect.isReady()) {\n return false;\n }\n }\n if (!this._platform.isUpdateBufferCreated()) {\n this._recreateUpdateEffect();\n return false;\n }\n return this._platform.isUpdateBufferReady();\n }\n /**\n * Gets if the system has been started. (Note: this will still be true after stop is called)\n * @returns True if it has been started, otherwise false.\n */\n isStarted() {\n return this._started;\n }\n /**\n * Gets if the system has been stopped. (Note: rendering is still happening but the system is frozen)\n * @returns True if it has been stopped, otherwise false.\n */\n isStopped() {\n return this._stopped;\n }\n /**\n * Gets a boolean indicating that the system is stopping\n * @returns true if the system is currently stopping\n */\n isStopping() {\n return false; // Stop is immediate on GPU\n }\n /**\n * Gets the number of particles active at the same time.\n * @returns The number of active particles.\n */\n getActiveCount() {\n return this._currentActiveCount;\n }\n /**\n * Starts the particle system and begins to emit\n * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)\n */\n start(delay = this.startDelay) {\n if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {\n throw \"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set\";\n }\n if (delay) {\n setTimeout(() => {\n this.start(0);\n }, delay);\n return;\n }\n this._started = true;\n this._stopped = false;\n this._preWarmDone = false;\n // Animations\n if (this.beginAnimationOnStart && this.animations && this.animations.length > 0 && this._scene) {\n this._scene.beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);\n }\n }\n /**\n * Stops the particle system.\n */\n stop() {\n if (this._stopped) {\n return;\n }\n this._stopped = true;\n }\n /**\n * Remove all active particles\n */\n reset() {\n this._releaseBuffers();\n this._platform.releaseVertexBuffers();\n this._currentActiveCount = 0;\n this._targetIndex = 0;\n }\n /**\n * Returns the string \"GPUParticleSystem\"\n * @returns a string containing the class name\n */\n getClassName() {\n return \"GPUParticleSystem\";\n }\n /**\n * Gets the custom effect used to render the particles\n * @param blendMode Blend mode for which the effect should be retrieved\n * @returns The effect\n */\n getCustomEffect(blendMode = 0) {\n var _a, _b;\n return (_b = (_a = this._customWrappers[blendMode]) === null || _a === void 0 ? void 0 : _a.effect) !== null && _b !== void 0 ? _b : this._customWrappers[0].effect;\n }\n _getCustomDrawWrapper(blendMode = 0) {\n var _a;\n return (_a = this._customWrappers[blendMode]) !== null && _a !== void 0 ? _a : this._customWrappers[0];\n }\n /**\n * Sets the custom effect used to render the particles\n * @param effect The effect to set\n * @param blendMode Blend mode for which the effect should be set\n */\n setCustomEffect(effect, blendMode = 0) {\n this._customWrappers[blendMode] = new DrawWrapper(this._engine);\n this._customWrappers[blendMode].effect = effect;\n }\n /**\n * Observable that will be called just before the particles are drawn\n */\n get onBeforeDrawParticlesObservable() {\n if (!this._onBeforeDrawParticlesObservable) {\n this._onBeforeDrawParticlesObservable = new Observable();\n }\n return this._onBeforeDrawParticlesObservable;\n }\n /**\n * Gets the name of the particle vertex shader\n */\n get vertexShaderName() {\n return \"gpuRenderParticles\";\n }\n /**\n * Gets the vertex buffers used by the particle system\n * Should be called after render() has been called for the current frame so that the buffers returned are the ones that have been updated\n * in the current frame (there's a ping-pong between two sets of buffers - for a given frame, one set is used as the source and the other as the destination)\n */\n get vertexBuffers() {\n // We return the other buffers than those corresponding to this._targetIndex because it is assumed vertexBuffers will be called in the current frame\n // after render() has been called, meaning that the buffers have already been swapped and this._targetIndex points to the buffers that will be updated\n // in the next frame (and which are the sources in this frame) and (this._targetIndex ^ 1) points to the buffers that have been updated this frame\n // (and that will be the source buffers in the next frame)\n return this._renderVertexBuffers[this._targetIndex ^ 1];\n }\n /**\n * Gets the index buffer used by the particle system (null for GPU particle systems)\n */\n get indexBuffer() {\n return null;\n }\n _removeGradientAndTexture(gradient, gradients, texture) {\n super._removeGradientAndTexture(gradient, gradients, texture);\n this._releaseBuffers();\n return this;\n }\n /**\n * Adds a new color gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param color1 defines the color to affect to the specified gradient\n * @returns the current particle system\n */\n addColorGradient(gradient, color1) {\n if (!this._colorGradients) {\n this._colorGradients = [];\n }\n const colorGradient = new ColorGradient(gradient, color1);\n this._colorGradients.push(colorGradient);\n this._refreshColorGradient(true);\n this._releaseBuffers();\n return this;\n }\n _refreshColorGradient(reorder = false) {\n if (this._colorGradients) {\n if (reorder) {\n this._colorGradients.sort((a, b) => {\n if (a.gradient < b.gradient) {\n return -1;\n }\n else if (a.gradient > b.gradient) {\n return 1;\n }\n return 0;\n });\n }\n if (this._colorGradientsTexture) {\n this._colorGradientsTexture.dispose();\n this._colorGradientsTexture = null;\n }\n }\n }\n /** Force the system to rebuild all gradients that need to be resync */\n forceRefreshGradients() {\n this._refreshColorGradient();\n this._refreshFactorGradient(this._sizeGradients, \"_sizeGradientsTexture\");\n this._refreshFactorGradient(this._angularSpeedGradients, \"_angularSpeedGradientsTexture\");\n this._refreshFactorGradient(this._velocityGradients, \"_velocityGradientsTexture\");\n this._refreshFactorGradient(this._limitVelocityGradients, \"_limitVelocityGradientsTexture\");\n this._refreshFactorGradient(this._dragGradients, \"_dragGradientsTexture\");\n this.reset();\n }\n /**\n * Remove a specific color gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeColorGradient(gradient) {\n this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);\n this._colorGradientsTexture = null;\n return this;\n }\n /**\n * Resets the draw wrappers cache\n */\n resetDrawCache() {\n var _a;\n for (const blendMode in this._drawWrappers) {\n const drawWrapper = this._drawWrappers[blendMode];\n (_a = drawWrapper.drawContext) === null || _a === void 0 ? void 0 : _a.reset();\n }\n }\n _addFactorGradient(factorGradients, gradient, factor) {\n const valueGradient = new FactorGradient(gradient, factor);\n factorGradients.push(valueGradient);\n this._releaseBuffers();\n }\n /**\n * Adds a new size gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the size factor to affect to the specified gradient\n * @returns the current particle system\n */\n addSizeGradient(gradient, factor) {\n if (!this._sizeGradients) {\n this._sizeGradients = [];\n }\n this._addFactorGradient(this._sizeGradients, gradient, factor);\n this._refreshFactorGradient(this._sizeGradients, \"_sizeGradientsTexture\", true);\n this._releaseBuffers();\n return this;\n }\n /**\n * Remove a specific size gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeSizeGradient(gradient) {\n this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);\n this._sizeGradientsTexture = null;\n return this;\n }\n _refreshFactorGradient(factorGradients, textureName, reorder = false) {\n if (!factorGradients) {\n return;\n }\n if (reorder) {\n factorGradients.sort((a, b) => {\n if (a.gradient < b.gradient) {\n return -1;\n }\n else if (a.gradient > b.gradient) {\n return 1;\n }\n return 0;\n });\n }\n const that = this;\n if (that[textureName]) {\n that[textureName].dispose();\n that[textureName] = null;\n }\n }\n /**\n * Adds a new angular speed gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the angular speed to affect to the specified gradient\n * @returns the current particle system\n */\n addAngularSpeedGradient(gradient, factor) {\n if (!this._angularSpeedGradients) {\n this._angularSpeedGradients = [];\n }\n this._addFactorGradient(this._angularSpeedGradients, gradient, factor);\n this._refreshFactorGradient(this._angularSpeedGradients, \"_angularSpeedGradientsTexture\", true);\n this._releaseBuffers();\n return this;\n }\n /**\n * Remove a specific angular speed gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeAngularSpeedGradient(gradient) {\n this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);\n this._angularSpeedGradientsTexture = null;\n return this;\n }\n /**\n * Adds a new velocity gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the velocity to affect to the specified gradient\n * @returns the current particle system\n */\n addVelocityGradient(gradient, factor) {\n if (!this._velocityGradients) {\n this._velocityGradients = [];\n }\n this._addFactorGradient(this._velocityGradients, gradient, factor);\n this._refreshFactorGradient(this._velocityGradients, \"_velocityGradientsTexture\", true);\n this._releaseBuffers();\n return this;\n }\n /**\n * Remove a specific velocity gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeVelocityGradient(gradient) {\n this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);\n this._velocityGradientsTexture = null;\n return this;\n }\n /**\n * Adds a new limit velocity gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the limit velocity value to affect to the specified gradient\n * @returns the current particle system\n */\n addLimitVelocityGradient(gradient, factor) {\n if (!this._limitVelocityGradients) {\n this._limitVelocityGradients = [];\n }\n this._addFactorGradient(this._limitVelocityGradients, gradient, factor);\n this._refreshFactorGradient(this._limitVelocityGradients, \"_limitVelocityGradientsTexture\", true);\n this._releaseBuffers();\n return this;\n }\n /**\n * Remove a specific limit velocity gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeLimitVelocityGradient(gradient) {\n this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);\n this._limitVelocityGradientsTexture = null;\n return this;\n }\n /**\n * Adds a new drag gradient\n * @param gradient defines the gradient to use (between 0 and 1)\n * @param factor defines the drag value to affect to the specified gradient\n * @returns the current particle system\n */\n addDragGradient(gradient, factor) {\n if (!this._dragGradients) {\n this._dragGradients = [];\n }\n this._addFactorGradient(this._dragGradients, gradient, factor);\n this._refreshFactorGradient(this._dragGradients, \"_dragGradientsTexture\", true);\n this._releaseBuffers();\n return this;\n }\n /**\n * Remove a specific drag gradient\n * @param gradient defines the gradient to remove\n * @returns the current particle system\n */\n removeDragGradient(gradient) {\n this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);\n this._dragGradientsTexture = null;\n return this;\n }\n /**\n * Not supported by GPUParticleSystem\n * @returns the current particle system\n */\n addEmitRateGradient() {\n // Do nothing as emit rate is not supported by GPUParticleSystem\n return this;\n }\n /**\n * Not supported by GPUParticleSystem\n * @returns the current particle system\n */\n removeEmitRateGradient() {\n // Do nothing as emit rate is not supported by GPUParticleSystem\n return this;\n }\n /**\n * Not supported by GPUParticleSystem\n * @returns the current particle system\n */\n addStartSizeGradient() {\n // Do nothing as start size is not supported by GPUParticleSystem\n return this;\n }\n /**\n * Not supported by GPUParticleSystem\n * @returns the current particle system\n */\n removeStartSizeGradient() {\n // Do nothing as start size is not supported by GPUParticleSystem\n return this;\n }\n /**\n * Not supported by GPUParticleSystem\n * @returns the current particle system\n */\n addColorRemapGradient() {\n // Do nothing as start size is not supported by GPUParticleSystem\n return this;\n }\n /**\n * Not supported by GPUParticleSystem\n * @returns the current particle system\n */\n removeColorRemapGradient() {\n // Do nothing as start size is not supported by GPUParticleSystem\n return this;\n }\n /**\n * Not supported by GPUParticleSystem\n * @returns the current particle system\n */\n addAlphaRemapGradient() {\n // Do nothing as start size is not supported by GPUParticleSystem\n return this;\n }\n /**\n * Not supported by GPUParticleSystem\n * @returns the current particle system\n */\n removeAlphaRemapGradient() {\n // Do nothing as start size is not supported by GPUParticleSystem\n return this;\n }\n /**\n * Not supported by GPUParticleSystem\n * @returns the current particle system\n */\n addRampGradient() {\n //Not supported by GPUParticleSystem\n return this;\n }\n /**\n * Not supported by GPUParticleSystem\n * @returns the current particle system\n */\n removeRampGradient() {\n //Not supported by GPUParticleSystem\n return this;\n }\n /**\n * Not supported by GPUParticleSystem\n * @returns the list of ramp gradients\n */\n getRampGradients() {\n return null;\n }\n /**\n * Not supported by GPUParticleSystem\n * Gets or sets a boolean indicating that ramp gradients must be used\n * @see https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro#ramp-gradients\n */\n get useRampGradients() {\n //Not supported by GPUParticleSystem\n return false;\n }\n set useRampGradients(value) {\n //Not supported by GPUParticleSystem\n }\n /**\n * Not supported by GPUParticleSystem\n * @returns the current particle system\n */\n addLifeTimeGradient() {\n //Not supported by GPUParticleSystem\n return this;\n }\n /**\n * Not supported by GPUParticleSystem\n * @returns the current particle system\n */\n removeLifeTimeGradient() {\n //Not supported by GPUParticleSystem\n return this;\n }\n /**\n * Instantiates a GPU particle system.\n * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.\n * @param name The name of the particle system\n * @param options The options used to create the system\n * @param sceneOrEngine The scene the particle system belongs to or the engine to use if no scene\n * @param customEffect a custom effect used to change the way particles are rendered by default\n * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture\n */\n constructor(name, options, sceneOrEngine, customEffect = null, isAnimationSheetEnabled = false) {\n super(name);\n /**\n * The layer mask we are rendering the particles through.\n */\n this.layerMask = 0x0fffffff;\n this._accumulatedCount = 0;\n this._renderVertexBuffers = [];\n this._targetIndex = 0;\n this._currentRenderId = -1;\n this._currentRenderingCameraUniqueId = -1;\n this._started = false;\n this._stopped = false;\n this._timeDelta = 0;\n /** Indicates that the update of particles is done in the animate function (and not in render). Default: false */\n this.updateInAnimate = false;\n this._actualFrame = 0;\n this._rawTextureWidth = 256;\n /**\n * An event triggered when the system is disposed.\n */\n this.onDisposeObservable = new Observable();\n /**\n * An event triggered when the system is stopped\n */\n this.onStoppedObservable = new Observable();\n /**\n * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls\n * to override the particles.\n */\n this.forceDepthWrite = false;\n this._preWarmDone = false;\n /**\n * Specifies if the particles are updated in emitter local space or world space.\n */\n this.isLocal = false;\n /** Indicates that the particle system is GPU based */\n this.isGPU = true;\n /** @internal */\n this._onBeforeDrawParticlesObservable = null;\n if (!sceneOrEngine || sceneOrEngine.getClassName() === \"Scene\") {\n this._scene = sceneOrEngine || EngineStore.LastCreatedScene;\n this._engine = this._scene.getEngine();\n this.uniqueId = this._scene.getUniqueId();\n this._scene.particleSystems.push(this);\n }\n else {\n this._engine = sceneOrEngine;\n this.defaultProjectionMatrix = Matrix.PerspectiveFovLH(0.8, 1, 0.1, 100, this._engine.isNDCHalfZRange);\n }\n if (this._engine.getCaps().supportComputeShaders) {\n if (!GetClass(\"BABYLON.ComputeShaderParticleSystem\")) {\n throw new Error(\"The ComputeShaderParticleSystem class is not available! Make sure you have imported it.\");\n }\n this._platform = new (GetClass(\"BABYLON.ComputeShaderParticleSystem\"))(this, this._engine);\n }\n else {\n if (!GetClass(\"BABYLON.WebGL2ParticleSystem\")) {\n throw new Error(\"The WebGL2ParticleSystem class is not available! Make sure you have imported it.\");\n }\n this._platform = new (GetClass(\"BABYLON.WebGL2ParticleSystem\"))(this, this._engine);\n }\n this._customWrappers = { 0: new DrawWrapper(this._engine) };\n this._customWrappers[0].effect = customEffect;\n this._drawWrappers = { 0: new DrawWrapper(this._engine) };\n if (this._drawWrappers[0].drawContext) {\n this._drawWrappers[0].drawContext.useInstancing = true;\n }\n // Setup the default processing configuration to the scene.\n this._attachImageProcessingConfiguration(null);\n options = options !== null && options !== void 0 ? options : {};\n if (!options.randomTextureSize) {\n delete options.randomTextureSize;\n }\n const fullOptions = Object.assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);\n const optionsAsNumber = options;\n if (isFinite(optionsAsNumber)) {\n fullOptions.capacity = optionsAsNumber;\n }\n this._capacity = fullOptions.capacity;\n this._activeCount = fullOptions.capacity;\n this._currentActiveCount = 0;\n this._isAnimationSheetEnabled = isAnimationSheetEnabled;\n this.particleEmitterType = new BoxParticleEmitter();\n // Random data\n const maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);\n let d = [];\n for (let i = 0; i < maxTextureSize; ++i) {\n d.push(Math.random());\n d.push(Math.random());\n d.push(Math.random());\n d.push(Math.random());\n }\n this._randomTexture = new RawTexture(new Float32Array(d), maxTextureSize, 1, 5, sceneOrEngine, false, false, 1, 1);\n this._randomTexture.name = \"GPUParticleSystem_random1\";\n this._randomTexture.wrapU = 1;\n this._randomTexture.wrapV = 1;\n d = [];\n for (let i = 0; i < maxTextureSize; ++i) {\n d.push(Math.random());\n d.push(Math.random());\n d.push(Math.random());\n d.push(Math.random());\n }\n this._randomTexture2 = new RawTexture(new Float32Array(d), maxTextureSize, 1, 5, sceneOrEngine, false, false, 1, 1);\n this._randomTexture2.name = \"GPUParticleSystem_random2\";\n this._randomTexture2.wrapU = 1;\n this._randomTexture2.wrapV = 1;\n this._randomTextureSize = maxTextureSize;\n }\n _reset() {\n this._releaseBuffers();\n }\n _createVertexBuffers(updateBuffer, renderBuffer, spriteSource) {\n const renderVertexBuffers = {};\n renderVertexBuffers[\"position\"] = renderBuffer.createVertexBuffer(\"position\", 0, 3, this._attributesStrideSize, true);\n let offset = 3;\n renderVertexBuffers[\"age\"] = renderBuffer.createVertexBuffer(\"age\", offset, 1, this._attributesStrideSize, true);\n offset += 1;\n renderVertexBuffers[\"size\"] = renderBuffer.createVertexBuffer(\"size\", offset, 3, this._attributesStrideSize, true);\n offset += 3;\n renderVertexBuffers[\"life\"] = renderBuffer.createVertexBuffer(\"life\", offset, 1, this._attributesStrideSize, true);\n offset += 1;\n offset += 4; // seed\n if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {\n renderVertexBuffers[\"direction\"] = renderBuffer.createVertexBuffer(\"direction\", offset, 3, this._attributesStrideSize, true);\n }\n offset += 3; // direction\n if (this._platform.alignDataInBuffer) {\n offset += 1;\n }\n if (this.particleEmitterType instanceof CustomParticleEmitter) {\n offset += 3;\n if (this._platform.alignDataInBuffer) {\n offset += 1;\n }\n }\n if (!this._colorGradientsTexture) {\n renderVertexBuffers[\"color\"] = renderBuffer.createVertexBuffer(\"color\", offset, 4, this._attributesStrideSize, true);\n offset += 4;\n }\n if (!this._isBillboardBased) {\n renderVertexBuffers[\"initialDirection\"] = renderBuffer.createVertexBuffer(\"initialDirection\", offset, 3, this._attributesStrideSize, true);\n offset += 3;\n if (this._platform.alignDataInBuffer) {\n offset += 1;\n }\n }\n if (this.noiseTexture) {\n renderVertexBuffers[\"noiseCoordinates1\"] = renderBuffer.createVertexBuffer(\"noiseCoordinates1\", offset, 3, this._attributesStrideSize, true);\n offset += 3;\n if (this._platform.alignDataInBuffer) {\n offset += 1;\n }\n renderVertexBuffers[\"noiseCoordinates2\"] = renderBuffer.createVertexBuffer(\"noiseCoordinates2\", offset, 3, this._attributesStrideSize, true);\n offset += 3;\n if (this._platform.alignDataInBuffer) {\n offset += 1;\n }\n }\n renderVertexBuffers[\"angle\"] = renderBuffer.createVertexBuffer(\"angle\", offset, 1, this._attributesStrideSize, true);\n if (this._angularSpeedGradientsTexture) {\n offset++;\n }\n else {\n offset += 2;\n }\n if (this._isAnimationSheetEnabled) {\n renderVertexBuffers[\"cellIndex\"] = renderBuffer.createVertexBuffer(\"cellIndex\", offset, 1, this._attributesStrideSize, true);\n offset += 1;\n if (this.spriteRandomStartCell) {\n renderVertexBuffers[\"cellStartOffset\"] = renderBuffer.createVertexBuffer(\"cellStartOffset\", offset, 1, this._attributesStrideSize, true);\n offset += 1;\n }\n }\n renderVertexBuffers[\"offset\"] = spriteSource.createVertexBuffer(\"offset\", 0, 2);\n renderVertexBuffers[\"uv\"] = spriteSource.createVertexBuffer(\"uv\", 2, 2);\n this._renderVertexBuffers.push(renderVertexBuffers);\n this._platform.createVertexBuffers(updateBuffer, renderVertexBuffers);\n this.resetDrawCache();\n }\n _initialize(force = false) {\n if (this._buffer0 && !force) {\n return;\n }\n const engine = this._engine;\n const data = new Array();\n this._attributesStrideSize = 21;\n this._targetIndex = 0;\n if (this._platform.alignDataInBuffer) {\n this._attributesStrideSize += 1;\n }\n if (this.particleEmitterType instanceof CustomParticleEmitter) {\n this._attributesStrideSize += 3;\n if (this._platform.alignDataInBuffer) {\n this._attributesStrideSize += 1;\n }\n }\n if (!this.isBillboardBased) {\n this._attributesStrideSize += 3;\n if (this._platform.alignDataInBuffer) {\n this._attributesStrideSize += 1;\n }\n }\n if (this._colorGradientsTexture) {\n this._attributesStrideSize -= 4;\n }\n if (this._angularSpeedGradientsTexture) {\n this._attributesStrideSize -= 1;\n }\n if (this._isAnimationSheetEnabled) {\n this._attributesStrideSize += 1;\n if (this.spriteRandomStartCell) {\n this._attributesStrideSize += 1;\n }\n }\n if (this.noiseTexture) {\n this._attributesStrideSize += 6;\n if (this._platform.alignDataInBuffer) {\n this._attributesStrideSize += 2;\n }\n }\n if (this._platform.alignDataInBuffer) {\n this._attributesStrideSize += 3 - ((this._attributesStrideSize + 3) & 3); // round to multiple of 4\n }\n const usingCustomEmitter = this.particleEmitterType instanceof CustomParticleEmitter;\n const tmpVector = TmpVectors.Vector3[0];\n let offset = 0;\n for (let particleIndex = 0; particleIndex < this._capacity; particleIndex++) {\n // position\n data.push(0.0);\n data.push(0.0);\n data.push(0.0);\n // Age\n data.push(0.0); // create the particle as a dead one to create a new one at start\n // Size\n data.push(0.0);\n data.push(0.0);\n data.push(0.0);\n // life\n data.push(0.0);\n // Seed\n data.push(Math.random());\n data.push(Math.random());\n data.push(Math.random());\n data.push(Math.random());\n // direction\n if (usingCustomEmitter) {\n this.particleEmitterType.particleDestinationGenerator(particleIndex, null, tmpVector);\n data.push(tmpVector.x);\n data.push(tmpVector.y);\n data.push(tmpVector.z);\n }\n else {\n data.push(0.0);\n data.push(0.0);\n data.push(0.0);\n }\n if (this._platform.alignDataInBuffer) {\n data.push(0.0); // dummy0\n }\n offset += 16; // position, age, size, life, seed, direction, dummy0\n if (usingCustomEmitter) {\n this.particleEmitterType.particlePositionGenerator(particleIndex, null, tmpVector);\n data.push(tmpVector.x);\n data.push(tmpVector.y);\n data.push(tmpVector.z);\n if (this._platform.alignDataInBuffer) {\n data.push(0.0); // dummy1\n }\n offset += 4;\n }\n if (!this._colorGradientsTexture) {\n // color\n data.push(0.0);\n data.push(0.0);\n data.push(0.0);\n data.push(0.0);\n offset += 4;\n }\n if (!this.isBillboardBased) {\n // initialDirection\n data.push(0.0);\n data.push(0.0);\n data.push(0.0);\n if (this._platform.alignDataInBuffer) {\n data.push(0.0); // dummy2\n }\n offset += 4;\n }\n if (this.noiseTexture) {\n // Random coordinates for reading into noise texture\n data.push(Math.random());\n data.push(Math.random());\n data.push(Math.random());\n if (this._platform.alignDataInBuffer) {\n data.push(0.0); // dummy3\n }\n data.push(Math.random());\n data.push(Math.random());\n data.push(Math.random());\n if (this._platform.alignDataInBuffer) {\n data.push(0.0); // dummy4\n }\n offset += 8;\n }\n // angle\n data.push(0.0);\n offset += 1;\n if (!this._angularSpeedGradientsTexture) {\n data.push(0.0);\n offset += 1;\n }\n if (this._isAnimationSheetEnabled) {\n data.push(0.0);\n offset += 1;\n if (this.spriteRandomStartCell) {\n data.push(0.0);\n offset += 1;\n }\n }\n if (this._platform.alignDataInBuffer) {\n let numDummies = 3 - ((offset + 3) & 3);\n offset += numDummies;\n while (numDummies-- > 0) {\n data.push(0.0);\n }\n }\n }\n // Sprite data\n const spriteData = new Float32Array([0.5, 0.5, 1, 1, -0.5, 0.5, 0, 1, 0.5, -0.5, 1, 0, -0.5, -0.5, 0, 0]);\n const bufferData1 = this._platform.createParticleBuffer(data);\n const bufferData2 = this._platform.createParticleBuffer(data);\n // Buffers\n this._buffer0 = new Buffer(engine, bufferData1, false, this._attributesStrideSize);\n this._buffer1 = new Buffer(engine, bufferData2, false, this._attributesStrideSize);\n this._spriteBuffer = new Buffer(engine, spriteData, false, 4);\n // Update & Render vertex buffers\n this._renderVertexBuffers = [];\n this._createVertexBuffers(this._buffer0, this._buffer1, this._spriteBuffer);\n this._createVertexBuffers(this._buffer1, this._buffer0, this._spriteBuffer);\n // Links\n this._sourceBuffer = this._buffer0;\n this._targetBuffer = this._buffer1;\n }\n /** @internal */\n _recreateUpdateEffect() {\n this._createColorGradientTexture();\n this._createSizeGradientTexture();\n this._createAngularSpeedGradientTexture();\n this._createVelocityGradientTexture();\n this._createLimitVelocityGradientTexture();\n this._createDragGradientTexture();\n let defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : \"\";\n if (this._isBillboardBased) {\n defines += \"\\n#define BILLBOARD\";\n }\n if (this._colorGradientsTexture) {\n defines += \"\\n#define COLORGRADIENTS\";\n }\n if (this._sizeGradientsTexture) {\n defines += \"\\n#define SIZEGRADIENTS\";\n }\n if (this._angularSpeedGradientsTexture) {\n defines += \"\\n#define ANGULARSPEEDGRADIENTS\";\n }\n if (this._velocityGradientsTexture) {\n defines += \"\\n#define VELOCITYGRADIENTS\";\n }\n if (this._limitVelocityGradientsTexture) {\n defines += \"\\n#define LIMITVELOCITYGRADIENTS\";\n }\n if (this._dragGradientsTexture) {\n defines += \"\\n#define DRAGGRADIENTS\";\n }\n if (this.isAnimationSheetEnabled) {\n defines += \"\\n#define ANIMATESHEET\";\n if (this.spriteRandomStartCell) {\n defines += \"\\n#define ANIMATESHEETRANDOMSTART\";\n }\n }\n if (this.noiseTexture) {\n defines += \"\\n#define NOISE\";\n }\n if (this.isLocal) {\n defines += \"\\n#define LOCAL\";\n }\n if (this._platform.isUpdateBufferCreated() && this._cachedUpdateDefines === defines) {\n return true;\n }\n this._cachedUpdateDefines = defines;\n this._updateBuffer = this._platform.createUpdateBuffer(defines);\n return this._platform.isUpdateBufferReady();\n }\n /**\n * @internal\n */\n _getWrapper(blendMode) {\n const customWrapper = this._getCustomDrawWrapper(blendMode);\n if (customWrapper === null || customWrapper === void 0 ? void 0 : customWrapper.effect) {\n return customWrapper;\n }\n const defines = [];\n this.fillDefines(defines, blendMode);\n // Effect\n let drawWrapper = this._drawWrappers[blendMode];\n if (!drawWrapper) {\n drawWrapper = new DrawWrapper(this._engine);\n if (drawWrapper.drawContext) {\n drawWrapper.drawContext.useInstancing = true;\n }\n this._drawWrappers[blendMode] = drawWrapper;\n }\n const join = defines.join(\"\\n\");\n if (drawWrapper.defines !== join) {\n const attributes = [];\n const uniforms = [];\n const samplers = [];\n this.fillUniformsAttributesAndSamplerNames(uniforms, attributes, samplers);\n drawWrapper.setEffect(this._engine.createEffect(\"gpuRenderParticles\", attributes, uniforms, samplers, join), join);\n }\n return drawWrapper;\n }\n /**\n * @internal\n */\n static _GetAttributeNamesOrOptions(hasColorGradients = false, isAnimationSheetEnabled = false, isBillboardBased = false, isBillboardStretched = false) {\n const attributeNamesOrOptions = [VertexBuffer.PositionKind, \"age\", \"life\", \"size\", \"angle\"];\n if (!hasColorGradients) {\n attributeNamesOrOptions.push(VertexBuffer.ColorKind);\n }\n if (isAnimationSheetEnabled) {\n attributeNamesOrOptions.push(\"cellIndex\");\n }\n if (!isBillboardBased) {\n attributeNamesOrOptions.push(\"initialDirection\");\n }\n if (!isBillboardStretched) {\n attributeNamesOrOptions.push(\"direction\");\n }\n attributeNamesOrOptions.push(\"offset\", VertexBuffer.UVKind);\n return attributeNamesOrOptions;\n }\n /**\n * @internal\n */\n static _GetEffectCreationOptions(isAnimationSheetEnabled = false, useLogarithmicDepth = false) {\n const effectCreationOption = [\"emitterWM\", \"worldOffset\", \"view\", \"projection\", \"colorDead\", \"invView\", \"translationPivot\", \"eyePosition\"];\n addClipPlaneUniforms(effectCreationOption);\n if (isAnimationSheetEnabled) {\n effectCreationOption.push(\"sheetInfos\");\n }\n if (useLogarithmicDepth) {\n effectCreationOption.push(\"logarithmicDepthConstant\");\n }\n return effectCreationOption;\n }\n /**\n * Fill the defines array according to the current settings of the particle system\n * @param defines Array to be updated\n * @param blendMode blend mode to take into account when updating the array\n */\n fillDefines(defines, blendMode = 0) {\n if (this._scene) {\n prepareStringDefinesForClipPlanes(this, this._scene, defines);\n }\n if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {\n defines.push(\"#define BLENDMULTIPLYMODE\");\n }\n if (this.isLocal) {\n defines.push(\"#define LOCAL\");\n }\n if (this.useLogarithmicDepth) {\n defines.push(\"#define LOGARITHMICDEPTH\");\n }\n if (this._isBillboardBased) {\n defines.push(\"#define BILLBOARD\");\n switch (this.billboardMode) {\n case ParticleSystem.BILLBOARDMODE_Y:\n defines.push(\"#define BILLBOARDY\");\n break;\n case ParticleSystem.BILLBOARDMODE_STRETCHED:\n defines.push(\"#define BILLBOARDSTRETCHED\");\n break;\n case ParticleSystem.BILLBOARDMODE_ALL:\n defines.push(\"#define BILLBOARDMODE_ALL\");\n break;\n default:\n break;\n }\n }\n if (this._colorGradientsTexture) {\n defines.push(\"#define COLORGRADIENTS\");\n }\n if (this.isAnimationSheetEnabled) {\n defines.push(\"#define ANIMATESHEET\");\n }\n if (this._imageProcessingConfiguration) {\n this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);\n defines.push(\"\" + this._imageProcessingConfigurationDefines.toString());\n }\n }\n /**\n * Fill the uniforms, attributes and samplers arrays according to the current settings of the particle system\n * @param uniforms Uniforms array to fill\n * @param attributes Attributes array to fill\n * @param samplers Samplers array to fill\n */\n fillUniformsAttributesAndSamplerNames(uniforms, attributes, samplers) {\n attributes.push(...GPUParticleSystem._GetAttributeNamesOrOptions(!!this._colorGradientsTexture, this._isAnimationSheetEnabled, this._isBillboardBased, this._isBillboardBased && this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED));\n uniforms.push(...GPUParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled, this.useLogarithmicDepth));\n samplers.push(\"diffuseSampler\", \"colorGradientSampler\");\n if (this._imageProcessingConfiguration) {\n ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);\n ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);\n }\n }\n /**\n * Animates the particle system for the current frame by emitting new particles and or animating the living ones.\n * @param preWarm defines if we are in the pre-warmimg phase\n */\n animate(preWarm = false) {\n var _a;\n this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : ((_a = this._scene) === null || _a === void 0 ? void 0 : _a.getAnimationRatio()) || 1);\n this._actualFrame += this._timeDelta;\n if (!this._stopped) {\n if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {\n this.stop();\n }\n }\n if (this.updateInAnimate) {\n this._update();\n }\n }\n _createFactorGradientTexture(factorGradients, textureName) {\n const texture = this[textureName];\n if (!factorGradients || !factorGradients.length || texture) {\n return;\n }\n const data = new Float32Array(this._rawTextureWidth);\n for (let x = 0; x < this._rawTextureWidth; x++) {\n const ratio = x / this._rawTextureWidth;\n GradientHelper.GetCurrentGradient(ratio, factorGradients, (currentGradient, nextGradient, scale) => {\n data[x] = Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);\n });\n }\n this[textureName] = RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene || this._engine, false, false, 1);\n this[textureName].name = textureName.substring(1);\n }\n _createSizeGradientTexture() {\n this._createFactorGradientTexture(this._sizeGradients, \"_sizeGradientsTexture\");\n }\n _createAngularSpeedGradientTexture() {\n this._createFactorGradientTexture(this._angularSpeedGradients, \"_angularSpeedGradientsTexture\");\n }\n _createVelocityGradientTexture() {\n this._createFactorGradientTexture(this._velocityGradients, \"_velocityGradientsTexture\");\n }\n _createLimitVelocityGradientTexture() {\n this._createFactorGradientTexture(this._limitVelocityGradients, \"_limitVelocityGradientsTexture\");\n }\n _createDragGradientTexture() {\n this._createFactorGradientTexture(this._dragGradients, \"_dragGradientsTexture\");\n }\n _createColorGradientTexture() {\n if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {\n return;\n }\n const data = new Uint8Array(this._rawTextureWidth * 4);\n const tmpColor = TmpColors.Color4[0];\n for (let x = 0; x < this._rawTextureWidth; x++) {\n const ratio = x / this._rawTextureWidth;\n GradientHelper.GetCurrentGradient(ratio, this._colorGradients, (currentGradient, nextGradient, scale) => {\n Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);\n data[x * 4] = tmpColor.r * 255;\n data[x * 4 + 1] = tmpColor.g * 255;\n data[x * 4 + 2] = tmpColor.b * 255;\n data[x * 4 + 3] = tmpColor.a * 255;\n });\n }\n this._colorGradientsTexture = RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, 1);\n this._colorGradientsTexture.name = \"colorGradients\";\n }\n _render(blendMode, emitterWM) {\n var _a, _b;\n // Enable render effect\n const drawWrapper = this._getWrapper(blendMode);\n const effect = drawWrapper.effect;\n this._engine.enableEffect(drawWrapper);\n const viewMatrix = ((_a = this._scene) === null || _a === void 0 ? void 0 : _a.getViewMatrix()) || Matrix.IdentityReadOnly;\n effect.setMatrix(\"view\", viewMatrix);\n effect.setMatrix(\"projection\", (_b = this.defaultProjectionMatrix) !== null && _b !== void 0 ? _b : this._scene.getProjectionMatrix());\n effect.setTexture(\"diffuseSampler\", this.particleTexture);\n effect.setVector2(\"translationPivot\", this.translationPivot);\n effect.setVector3(\"worldOffset\", this.worldOffset);\n if (this.isLocal) {\n effect.setMatrix(\"emitterWM\", emitterWM);\n }\n if (this._colorGradientsTexture) {\n effect.setTexture(\"colorGradientSampler\", this._colorGradientsTexture);\n }\n else {\n effect.setDirectColor4(\"colorDead\", this.colorDead);\n }\n if (this._isAnimationSheetEnabled && this.particleTexture) {\n const baseSize = this.particleTexture.getBaseSize();\n effect.setFloat3(\"sheetInfos\", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);\n }\n if (this._isBillboardBased && this._scene) {\n const camera = this._scene.activeCamera;\n effect.setVector3(\"eyePosition\", camera.globalPosition);\n }\n const defines = effect.defines;\n if (this._scene) {\n bindClipPlane(effect, this, this._scene);\n }\n if (defines.indexOf(\"#define BILLBOARDMODE_ALL\") >= 0) {\n const invView = viewMatrix.clone();\n invView.invert();\n effect.setMatrix(\"invView\", invView);\n }\n // Log. depth\n if (this.useLogarithmicDepth && this._scene) {\n MaterialHelper.BindLogDepth(defines, effect, this._scene);\n }\n // image processing\n if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {\n this._imageProcessingConfiguration.bind(effect);\n }\n // Draw order\n switch (blendMode) {\n case ParticleSystem.BLENDMODE_ADD:\n this._engine.setAlphaMode(1);\n break;\n case ParticleSystem.BLENDMODE_ONEONE:\n this._engine.setAlphaMode(6);\n break;\n case ParticleSystem.BLENDMODE_STANDARD:\n this._engine.setAlphaMode(2);\n break;\n case ParticleSystem.BLENDMODE_MULTIPLY:\n this._engine.setAlphaMode(4);\n break;\n }\n // Bind source VAO\n this._platform.bindDrawBuffers(this._targetIndex, effect);\n if (this._onBeforeDrawParticlesObservable) {\n this._onBeforeDrawParticlesObservable.notifyObservers(effect);\n }\n // Render\n this._engine.drawArraysType(7, 0, 4, this._currentActiveCount);\n this._engine.setAlphaMode(0);\n return this._currentActiveCount;\n }\n /** @internal */\n _update(emitterWM) {\n if (!this.emitter || !this._targetBuffer) {\n return;\n }\n if (!this._recreateUpdateEffect()) {\n return;\n }\n if (!emitterWM) {\n if (this.emitter.position) {\n const emitterMesh = this.emitter;\n emitterWM = emitterMesh.getWorldMatrix();\n }\n else {\n const emitterPosition = this.emitter;\n emitterWM = TmpVectors.Matrix[0];\n Matrix.TranslationToRef(emitterPosition.x, emitterPosition.y, emitterPosition.z, emitterWM);\n }\n }\n this._platform.preUpdateParticleBuffer();\n this._updateBuffer.setFloat(\"currentCount\", this._currentActiveCount);\n this._updateBuffer.setFloat(\"timeDelta\", this._timeDelta);\n this._updateBuffer.setFloat(\"stopFactor\", this._stopped ? 0 : 1);\n this._updateBuffer.setInt(\"randomTextureSize\", this._randomTextureSize);\n this._updateBuffer.setFloat2(\"lifeTime\", this.minLifeTime, this.maxLifeTime);\n this._updateBuffer.setFloat2(\"emitPower\", this.minEmitPower, this.maxEmitPower);\n if (!this._colorGradientsTexture) {\n this._updateBuffer.setDirectColor4(\"color1\", this.color1);\n this._updateBuffer.setDirectColor4(\"color2\", this.color2);\n }\n this._updateBuffer.setFloat2(\"sizeRange\", this.minSize, this.maxSize);\n this._updateBuffer.setFloat4(\"scaleRange\", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);\n this._updateBuffer.setFloat4(\"angleRange\", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);\n this._updateBuffer.setVector3(\"gravity\", this.gravity);\n if (this._limitVelocityGradientsTexture) {\n this._updateBuffer.setFloat(\"limitVelocityDamping\", this.limitVelocityDamping);\n }\n if (this.particleEmitterType) {\n this.particleEmitterType.applyToShader(this._updateBuffer);\n }\n if (this._isAnimationSheetEnabled) {\n this._updateBuffer.setFloat4(\"cellInfos\", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed, this.spriteCellLoop ? 1 : 0);\n }\n if (this.noiseTexture) {\n this._updateBuffer.setVector3(\"noiseStrength\", this.noiseStrength);\n }\n if (!this.isLocal) {\n this._updateBuffer.setMatrix(\"emitterWM\", emitterWM);\n }\n this._platform.updateParticleBuffer(this._targetIndex, this._targetBuffer, this._currentActiveCount);\n // Switch VAOs\n this._targetIndex++;\n if (this._targetIndex === 2) {\n this._targetIndex = 0;\n }\n // Switch buffers\n const tmpBuffer = this._sourceBuffer;\n this._sourceBuffer = this._targetBuffer;\n this._targetBuffer = tmpBuffer;\n }\n /**\n * Renders the particle system in its current state\n * @param preWarm defines if the system should only update the particles but not render them\n * @param forceUpdateOnly if true, force to only update the particles and never display them (meaning, even if preWarm=false, when forceUpdateOnly=true the particles won't be displayed)\n * @returns the current number of particles\n */\n render(preWarm = false, forceUpdateOnly = false) {\n if (!this._started) {\n return 0;\n }\n if (!this.isReady()) {\n return 0;\n }\n if (!preWarm && this._scene) {\n if (!this._preWarmDone && this.preWarmCycles) {\n for (let index = 0; index < this.preWarmCycles; index++) {\n this.animate(true);\n this.render(true, true);\n }\n this._preWarmDone = true;\n }\n if (this._currentRenderId === this._scene.getRenderId() &&\n (!this._scene.activeCamera || (this._scene.activeCamera && this._currentRenderingCameraUniqueId === this._scene.activeCamera.uniqueId))) {\n return 0;\n }\n this._currentRenderId = this._scene.getRenderId();\n if (this._scene.activeCamera) {\n this._currentRenderingCameraUniqueId = this._scene.activeCamera.uniqueId;\n }\n }\n // Get everything ready to render\n this._initialize();\n this._accumulatedCount += this.emitRate * this._timeDelta;\n if (this._accumulatedCount > 1) {\n const intPart = this._accumulatedCount | 0;\n this._accumulatedCount -= intPart;\n this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);\n }\n if (!this._currentActiveCount) {\n return 0;\n }\n // Enable update effect\n let emitterWM;\n if (this.emitter.position) {\n const emitterMesh = this.emitter;\n emitterWM = emitterMesh.getWorldMatrix();\n }\n else {\n const emitterPosition = this.emitter;\n emitterWM = TmpVectors.Matrix[0];\n Matrix.TranslationToRef(emitterPosition.x, emitterPosition.y, emitterPosition.z, emitterWM);\n }\n const engine = this._engine;\n if (!this.updateInAnimate) {\n this._update(emitterWM);\n }\n let outparticles = 0;\n if (!preWarm && !forceUpdateOnly) {\n engine.setState(false);\n if (this.forceDepthWrite) {\n engine.setDepthWrite(true);\n }\n if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {\n outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY, emitterWM) + this._render(ParticleSystem.BLENDMODE_ADD, emitterWM);\n }\n else {\n outparticles = this._render(this.blendMode, emitterWM);\n }\n this._engine.setAlphaMode(0);\n }\n return outparticles;\n }\n /**\n * Rebuilds the particle system\n */\n rebuild() {\n this._initialize(true);\n }\n _releaseBuffers() {\n if (this._buffer0) {\n this._buffer0.dispose();\n this._buffer0 = null;\n }\n if (this._buffer1) {\n this._buffer1.dispose();\n this._buffer1 = null;\n }\n if (this._spriteBuffer) {\n this._spriteBuffer.dispose();\n this._spriteBuffer = null;\n }\n this._platform.releaseBuffers();\n }\n /**\n * Disposes the particle system and free the associated resources\n * @param disposeTexture defines if the particule texture must be disposed as well (true by default)\n */\n dispose(disposeTexture = true) {\n for (const blendMode in this._drawWrappers) {\n const drawWrapper = this._drawWrappers[blendMode];\n drawWrapper.dispose();\n }\n this._drawWrappers = {};\n if (this._scene) {\n const index = this._scene.particleSystems.indexOf(this);\n if (index > -1) {\n this._scene.particleSystems.splice(index, 1);\n }\n }\n this._releaseBuffers();\n this._platform.releaseVertexBuffers();\n for (let i = 0; i < this._renderVertexBuffers.length; ++i) {\n const rvb = this._renderVertexBuffers[i];\n for (const key in rvb) {\n rvb[key].dispose();\n }\n }\n this._renderVertexBuffers = [];\n if (this._colorGradientsTexture) {\n this._colorGradientsTexture.dispose();\n this._colorGradientsTexture = null;\n }\n if (this._sizeGradientsTexture) {\n this._sizeGradientsTexture.dispose();\n this._sizeGradientsTexture = null;\n }\n if (this._angularSpeedGradientsTexture) {\n this._angularSpeedGradientsTexture.dispose();\n this._angularSpeedGradientsTexture = null;\n }\n if (this._velocityGradientsTexture) {\n this._velocityGradientsTexture.dispose();\n this._velocityGradientsTexture = null;\n }\n if (this._limitVelocityGradientsTexture) {\n this._limitVelocityGradientsTexture.dispose();\n this._limitVelocityGradientsTexture = null;\n }\n if (this._dragGradientsTexture) {\n this._dragGradientsTexture.dispose();\n this._dragGradientsTexture = null;\n }\n if (this._randomTexture) {\n this._randomTexture.dispose();\n this._randomTexture = null;\n }\n if (this._randomTexture2) {\n this._randomTexture2.dispose();\n this._randomTexture2 = null;\n }\n if (disposeTexture && this.particleTexture) {\n this.particleTexture.dispose();\n this.particleTexture = null;\n }\n if (disposeTexture && this.noiseTexture) {\n this.noiseTexture.dispose();\n this.noiseTexture = null;\n }\n // Callback\n this.onStoppedObservable.clear();\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n }\n /**\n * Clones the particle system.\n * @param name The name of the cloned object\n * @param newEmitter The new emitter to use\n * @param cloneTexture Also clone the textures if true\n * @returns the cloned particle system\n */\n clone(name, newEmitter, cloneTexture = false) {\n const custom = Object.assign({}, this._customWrappers);\n let program = null;\n const engine = this._engine;\n if (engine.createEffectForParticles) {\n if (this.customShader != null) {\n program = this.customShader;\n const defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join(\"\\n\") : \"\";\n custom[0] = engine.createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines, undefined, undefined, undefined, this);\n }\n }\n const serialization = this.serialize(cloneTexture);\n const result = GPUParticleSystem.Parse(serialization, this._scene || this._engine, this._rootUrl);\n result.name = name;\n result.customShader = program;\n result._customWrappers = custom;\n if (newEmitter === undefined) {\n newEmitter = this.emitter;\n }\n if (this.noiseTexture) {\n result.noiseTexture = this.noiseTexture.clone();\n }\n result.emitter = newEmitter;\n return result;\n }\n /**\n * Serializes the particle system to a JSON object\n * @param serializeTexture defines if the texture must be serialized as well\n * @returns the JSON object\n */\n serialize(serializeTexture = false) {\n const serializationObject = {};\n ParticleSystem._Serialize(serializationObject, this, serializeTexture);\n serializationObject.activeParticleCount = this.activeParticleCount;\n serializationObject.randomTextureSize = this._randomTextureSize;\n serializationObject.customShader = this.customShader;\n return serializationObject;\n }\n /**\n * Parses a JSON object to create a GPU particle system.\n * @param parsedParticleSystem The JSON object to parse\n * @param sceneOrEngine The scene or the engine to create the particle system in\n * @param rootUrl The root url to use to load external dependencies like texture\n * @param doNotStart Ignore the preventAutoStart attribute and does not start\n * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used)\n * @returns the parsed GPU particle system\n */\n static Parse(parsedParticleSystem, sceneOrEngine, rootUrl, doNotStart = false, capacity) {\n const name = parsedParticleSystem.name;\n let engine;\n let scene;\n if (sceneOrEngine instanceof ThinEngine) {\n engine = sceneOrEngine;\n }\n else {\n scene = sceneOrEngine;\n engine = scene.getEngine();\n }\n const particleSystem = new GPUParticleSystem(name, { capacity: capacity || parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, sceneOrEngine, null, parsedParticleSystem.isAnimationSheetEnabled);\n particleSystem._rootUrl = rootUrl;\n if (parsedParticleSystem.customShader && engine.createEffectForParticles) {\n const program = parsedParticleSystem.customShader;\n const defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join(\"\\n\") : \"\";\n const custom = engine.createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines, undefined, undefined, undefined, particleSystem);\n particleSystem.setCustomEffect(custom, 0);\n particleSystem.customShader = program;\n }\n if (parsedParticleSystem.id) {\n particleSystem.id = parsedParticleSystem.id;\n }\n if (parsedParticleSystem.activeParticleCount) {\n particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;\n }\n ParticleSystem._Parse(parsedParticleSystem, particleSystem, sceneOrEngine, rootUrl);\n // Auto start\n if (parsedParticleSystem.preventAutoStart) {\n particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;\n }\n if (!doNotStart && !particleSystem.preventAutoStart) {\n particleSystem.start();\n }\n return particleSystem;\n }\n}\n//# sourceMappingURL=gpuParticleSystem.js.map","import { Color3 } from \"../Maths/math.color.js\";\nimport { CreateSphere } from \"../Meshes/Builders/sphereBuilder.js\";\nimport { GPUParticleSystem } from \"./gpuParticleSystem.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { ParticleSystem } from \"../Particles/particleSystem.js\";\nimport { StandardMaterial } from \"../Materials/standardMaterial.js\";\n/** Internal class used to store shapes for emitters */\nclass ParticleSystemSetEmitterCreationOptions {\n}\n/**\n * Represents a set of particle systems working together to create a specific effect\n */\nexport class ParticleSystemSet {\n constructor() {\n this._emitterNodeIsOwned = true;\n /**\n * Gets the particle system list\n */\n this.systems = new Array();\n }\n /**\n * Gets or sets the emitter node used with this set\n */\n get emitterNode() {\n return this._emitterNode;\n }\n set emitterNode(value) {\n if (this._emitterNodeIsOwned && this._emitterNode) {\n if (this._emitterNode.dispose) {\n this._emitterNode.dispose();\n }\n this._emitterNodeIsOwned = false;\n }\n for (const system of this.systems) {\n system.emitter = value;\n }\n this._emitterNode = value;\n }\n /**\n * Creates a new emitter mesh as a sphere\n * @param options defines the options used to create the sphere\n * @param options.diameter\n * @param options.segments\n * @param options.color\n * @param renderingGroupId defines the renderingGroupId to use for the sphere\n * @param scene defines the hosting scene\n */\n setEmitterAsSphere(options, renderingGroupId, scene) {\n if (this._emitterNodeIsOwned && this._emitterNode) {\n if (this._emitterNode.dispose) {\n this._emitterNode.dispose();\n }\n }\n this._emitterNodeIsOwned = true;\n this._emitterCreationOptions = {\n kind: \"Sphere\",\n options: options,\n renderingGroupId: renderingGroupId,\n };\n const emitterMesh = CreateSphere(\"emitterSphere\", { diameter: options.diameter, segments: options.segments }, scene);\n emitterMesh.renderingGroupId = renderingGroupId;\n const material = new StandardMaterial(\"emitterSphereMaterial\", scene);\n material.emissiveColor = options.color;\n emitterMesh.material = material;\n for (const system of this.systems) {\n system.emitter = emitterMesh;\n }\n this._emitterNode = emitterMesh;\n }\n /**\n * Starts all particle systems of the set\n * @param emitter defines an optional mesh to use as emitter for the particle systems\n */\n start(emitter) {\n for (const system of this.systems) {\n if (emitter) {\n system.emitter = emitter;\n }\n system.start();\n }\n }\n /**\n * Release all associated resources\n */\n dispose() {\n for (const system of this.systems) {\n system.dispose();\n }\n this.systems.length = 0;\n if (this._emitterNode) {\n if (this._emitterNode.dispose) {\n this._emitterNode.dispose();\n }\n this._emitterNode = null;\n }\n }\n /**\n * Serialize the set into a JSON compatible object\n * @param serializeTexture defines if the texture must be serialized as well\n * @returns a JSON compatible representation of the set\n */\n serialize(serializeTexture = false) {\n const result = {};\n result.systems = [];\n for (const system of this.systems) {\n result.systems.push(system.serialize(serializeTexture));\n }\n if (this._emitterNode) {\n result.emitter = this._emitterCreationOptions;\n }\n return result;\n }\n /**\n * Parse a new ParticleSystemSet from a serialized source\n * @param data defines a JSON compatible representation of the set\n * @param scene defines the hosting scene\n * @param gpu defines if we want GPU particles or CPU particles\n * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used)\n * @returns a new ParticleSystemSet\n */\n static Parse(data, scene, gpu = false, capacity) {\n const result = new ParticleSystemSet();\n const rootUrl = this.BaseAssetsUrl + \"/textures/\";\n scene = scene || EngineStore.LastCreatedScene;\n for (const system of data.systems) {\n result.systems.push(gpu ? GPUParticleSystem.Parse(system, scene, rootUrl, true, capacity) : ParticleSystem.Parse(system, scene, rootUrl, true, capacity));\n }\n if (data.emitter) {\n const options = data.emitter.options;\n switch (data.emitter.kind) {\n case \"Sphere\":\n result.setEmitterAsSphere({\n diameter: options.diameter,\n segments: options.segments,\n color: Color3.FromArray(options.color),\n }, data.emitter.renderingGroupId, scene);\n break;\n }\n }\n return result;\n }\n}\n/**\n * Gets or sets base Assets URL\n */\nParticleSystemSet.BaseAssetsUrl = \"https://assets.babylonjs.com/particles\";\n//# sourceMappingURL=particleSystemSet.js.map","import { Tools } from \"../Misc/tools.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { GPUParticleSystem } from \"./gpuParticleSystem.js\";\nimport { ParticleSystemSet } from \"./particleSystemSet.js\";\nimport { ParticleSystem } from \"./particleSystem.js\";\nimport { WebRequest } from \"../Misc/webRequest.js\";\n\n/**\n * This class is made for on one-liner static method to help creating particle system set.\n */\nexport class ParticleHelper {\n /**\n * Create a default particle system that you can tweak\n * @param emitter defines the emitter to use\n * @param capacity defines the system capacity (default is 500 particles)\n * @param scene defines the hosting scene\n * @param useGPU defines if a GPUParticleSystem must be created (default is false)\n * @returns the new Particle system\n */\n static CreateDefault(emitter, capacity = 500, scene, useGPU = false) {\n let system;\n if (useGPU) {\n system = new GPUParticleSystem(\"default system\", { capacity: capacity }, scene);\n }\n else {\n system = new ParticleSystem(\"default system\", capacity, scene);\n }\n system.emitter = emitter;\n system.particleTexture = new Texture(\"https://assets.babylonjs.com/textures/flare.png\", system.getScene());\n system.createConeEmitter(0.1, Math.PI / 4);\n // Particle color\n system.color1 = new Color4(1.0, 1.0, 1.0, 1.0);\n system.color2 = new Color4(1.0, 1.0, 1.0, 1.0);\n system.colorDead = new Color4(1.0, 1.0, 1.0, 0.0);\n // Particle Size\n system.minSize = 0.1;\n system.maxSize = 0.1;\n // Emission speed\n system.minEmitPower = 2;\n system.maxEmitPower = 2;\n // Update speed\n system.updateSpeed = 1 / 60;\n system.emitRate = 30;\n return system;\n }\n /**\n * This is the main static method (one-liner) of this helper to create different particle systems\n * @param type This string represents the type to the particle system to create\n * @param scene The scene where the particle system should live\n * @param gpu If the system will use gpu\n * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used)\n * @returns the ParticleSystemSet created\n */\n static CreateAsync(type, scene, gpu = false, capacity) {\n if (!scene) {\n scene = EngineStore.LastCreatedScene;\n }\n const token = {};\n scene.addPendingData(token);\n return new Promise((resolve, reject) => {\n if (gpu && !GPUParticleSystem.IsSupported) {\n scene.removePendingData(token);\n return reject(\"Particle system with GPU is not supported.\");\n }\n Tools.LoadFile(`${ParticleHelper.BaseAssetsUrl}/systems/${type}.json`, (data) => {\n scene.removePendingData(token);\n const newData = JSON.parse(data.toString());\n return resolve(ParticleSystemSet.Parse(newData, scene, gpu, capacity));\n }, undefined, undefined, undefined, () => {\n scene.removePendingData(token);\n return reject(`An error occurred with the creation of your particle system. Check if your type '${type}' exists.`);\n });\n });\n }\n /**\n * Static function used to export a particle system to a ParticleSystemSet variable.\n * Please note that the emitter shape is not exported\n * @param systems defines the particle systems to export\n * @returns the created particle system set\n */\n static ExportSet(systems) {\n const set = new ParticleSystemSet();\n for (const system of systems) {\n set.systems.push(system);\n }\n return set;\n }\n /**\n * Creates a particle system from a snippet saved in a remote file\n * @param name defines the name of the particle system to create (can be null or empty to use the one from the json data)\n * @param url defines the url to load from\n * @param scene defines the hosting scene\n * @param gpu If the system will use gpu\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used)\n * @returns a promise that will resolve to the new particle system\n */\n static ParseFromFileAsync(name, url, scene, gpu = false, rootUrl = \"\", capacity) {\n return new Promise((resolve, reject) => {\n const request = new WebRequest();\n request.addEventListener(\"readystatechange\", () => {\n if (request.readyState == 4) {\n if (request.status == 200) {\n const serializationObject = JSON.parse(request.responseText);\n let output;\n if (gpu) {\n output = GPUParticleSystem.Parse(serializationObject, scene, rootUrl, false, capacity);\n }\n else {\n output = ParticleSystem.Parse(serializationObject, scene, rootUrl, false, capacity);\n }\n if (name) {\n output.name = name;\n }\n resolve(output);\n }\n else {\n reject(\"Unable to load the particle system\");\n }\n }\n });\n request.open(\"GET\", url);\n request.send();\n });\n }\n /**\n * Creates a particle system from a snippet saved by the particle system editor\n * @param snippetId defines the snippet to load (can be set to _BLANK to create a default one)\n * @param scene defines the hosting scene\n * @param gpu If the system will use gpu\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used)\n * @returns a promise that will resolve to the new particle system\n */\n static ParseFromSnippetAsync(snippetId, scene, gpu = false, rootUrl = \"\", capacity) {\n if (snippetId === \"_BLANK\") {\n const system = this.CreateDefault(null);\n system.start();\n return Promise.resolve(system);\n }\n return new Promise((resolve, reject) => {\n const request = new WebRequest();\n request.addEventListener(\"readystatechange\", () => {\n if (request.readyState == 4) {\n if (request.status == 200) {\n const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload);\n const serializationObject = JSON.parse(snippet.particleSystem);\n let output;\n if (gpu) {\n output = GPUParticleSystem.Parse(serializationObject, scene, rootUrl, false, capacity);\n }\n else {\n output = ParticleSystem.Parse(serializationObject, scene, rootUrl, false, capacity);\n }\n output.snippetId = snippetId;\n resolve(output);\n }\n else {\n reject(\"Unable to load the snippet \" + snippetId);\n }\n }\n });\n request.open(\"GET\", this.SnippetUrl + \"/\" + snippetId.replace(/#/g, \"/\"));\n request.send();\n });\n }\n}\n/**\n * Gets or sets base Assets URL\n */\nParticleHelper.BaseAssetsUrl = ParticleSystemSet.BaseAssetsUrl;\n/** Define the Url to load snippets */\nParticleHelper.SnippetUrl = `https://snippet.babylonjs.com`;\n/**\n * Creates a particle system from a snippet saved by the particle system editor\n * @deprecated Please use ParseFromSnippetAsync instead\n * @param snippetId defines the snippet to load (can be set to _BLANK to create a default one)\n * @param scene defines the hosting scene\n * @param gpu If the system will use gpu\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used)\n * @returns a promise that will resolve to the new particle system\n */\nParticleHelper.CreateFromSnippetAsync = ParticleHelper.ParseFromSnippetAsync;\n//# sourceMappingURL=particleHelper.js.map","import { Vector3, TmpVectors, Quaternion, Vector4, Vector2 } from \"../Maths/math.vector.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { BoundingInfo } from \"../Culling/boundingInfo.js\";\nimport { BoundingSphere } from \"../Culling/boundingSphere.js\";\nimport { AbstractMesh } from \"../Meshes/abstractMesh.js\";\n/**\n * Represents one particle of a solid particle system.\n */\nexport class SolidParticle {\n /**\n * Particle BoundingInfo object\n * @returns a BoundingInfo\n */\n getBoundingInfo() {\n return this._boundingInfo;\n }\n /**\n * Returns true if there is already a bounding info\n */\n get hasBoundingInfo() {\n return this._boundingInfo !== null;\n }\n /**\n * Creates a Solid Particle object.\n * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()\n * @param particleIndex (integer) is the particle index in the Solid Particle System pool.\n * @param particleId (integer) is the particle identifier. Unless some particles are removed from the SPS, it's the same value than the particle idx.\n * @param positionIndex (integer) is the starting index of the particle vertices in the SPS \"positions\" array.\n * @param indiceIndex (integer) is the starting index of the particle indices in the SPS \"indices\" array.\n * @param model (ModelShape) is a reference to the model shape on what the particle is designed.\n * @param shapeId (integer) is the model shape identifier in the SPS.\n * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))\n * @param sps defines the sps it is associated to\n * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.\n * @param materialIndex is the particle material identifier (integer) when the MultiMaterials are enabled in the SPS.\n */\n constructor(particleIndex, particleId, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo = null, materialIndex = null) {\n /**\n * particle global index\n */\n this.idx = 0;\n /**\n * particle identifier\n */\n this.id = 0;\n /**\n * The color of the particle\n */\n this.color = new Color4(1.0, 1.0, 1.0, 1.0);\n /**\n * The world space position of the particle.\n */\n this.position = Vector3.Zero();\n /**\n * The world space rotation of the particle. (Not use if rotationQuaternion is set)\n */\n this.rotation = Vector3.Zero();\n /**\n * The scaling of the particle.\n */\n this.scaling = Vector3.One();\n /**\n * The uvs of the particle.\n */\n this.uvs = new Vector4(0.0, 0.0, 1.0, 1.0);\n /**\n * The current speed of the particle.\n */\n this.velocity = Vector3.Zero();\n /**\n * The pivot point in the particle local space.\n */\n this.pivot = Vector3.Zero();\n /**\n * Must the particle be translated from its pivot point in its local space ?\n * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.\n * Default : false\n */\n this.translateFromPivot = false;\n /**\n * Is the particle active or not ?\n */\n this.alive = true;\n /**\n * Is the particle visible or not ?\n */\n this.isVisible = true;\n /**\n * Index of this particle in the global \"positions\" array (Internal use)\n * @internal\n */\n this._pos = 0;\n /**\n * @internal Index of this particle in the global \"indices\" array (Internal use)\n */\n this._ind = 0;\n /**\n * ModelShape id of this particle\n */\n this.shapeId = 0;\n /**\n * Index of the particle in its shape id\n */\n this.idxInShape = 0;\n /**\n * @internal Still set as invisible in order to skip useless computations (Internal use)\n */\n this._stillInvisible = false;\n /**\n * @internal Last computed particle rotation matrix\n */\n this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];\n /**\n * Parent particle Id, if any.\n * Default null.\n */\n this.parentId = null;\n /**\n * The particle material identifier (integer) when MultiMaterials are enabled in the SPS.\n */\n this.materialIndex = null;\n /**\n * Custom object or properties.\n */\n this.props = null;\n /**\n * The culling strategy to use to check whether the solid particle must be culled or not when using isInFrustum().\n * The possible values are :\n * - AbstractMesh.CULLINGSTRATEGY_STANDARD\n * - AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY\n * - AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION\n * - AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY\n * The default value for solid particles is AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY\n * Please read each static variable documentation in the class AbstractMesh to get details about the culling process.\n * */\n this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY;\n /**\n * @internal Internal global position in the SPS.\n */\n this._globalPosition = Vector3.Zero();\n this.idx = particleIndex;\n this.id = particleId;\n this._pos = positionIndex;\n this._ind = indiceIndex;\n this._model = model;\n this.shapeId = shapeId;\n this.idxInShape = idxInShape;\n this._sps = sps;\n if (modelBoundingInfo) {\n this._modelBoundingInfo = modelBoundingInfo;\n this._boundingInfo = new BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);\n }\n if (materialIndex !== null) {\n this.materialIndex = materialIndex;\n }\n }\n /**\n * Copies the particle property values into the existing target : position, rotation, scaling, uvs, colors, pivot, parent, visibility, alive\n * @param target the particle target\n * @returns the current particle\n */\n copyToRef(target) {\n target.position.copyFrom(this.position);\n target.rotation.copyFrom(this.rotation);\n if (this.rotationQuaternion) {\n if (target.rotationQuaternion) {\n target.rotationQuaternion.copyFrom(this.rotationQuaternion);\n }\n else {\n target.rotationQuaternion = this.rotationQuaternion.clone();\n }\n }\n target.scaling.copyFrom(this.scaling);\n if (this.color) {\n if (target.color) {\n target.color.copyFrom(this.color);\n }\n else {\n target.color = this.color.clone();\n }\n }\n target.uvs.copyFrom(this.uvs);\n target.velocity.copyFrom(this.velocity);\n target.pivot.copyFrom(this.pivot);\n target.translateFromPivot = this.translateFromPivot;\n target.alive = this.alive;\n target.isVisible = this.isVisible;\n target.parentId = this.parentId;\n target.cullingStrategy = this.cullingStrategy;\n if (this.materialIndex !== null) {\n target.materialIndex = this.materialIndex;\n }\n return this;\n }\n /**\n * Legacy support, changed scale to scaling\n */\n get scale() {\n return this.scaling;\n }\n /**\n * Legacy support, changed scale to scaling\n */\n set scale(scale) {\n this.scaling = scale;\n }\n /**\n * Legacy support, changed quaternion to rotationQuaternion\n */\n get quaternion() {\n return this.rotationQuaternion;\n }\n /**\n * Legacy support, changed quaternion to rotationQuaternion\n */\n set quaternion(q) {\n this.rotationQuaternion = q;\n }\n /**\n * Returns a boolean. True if the particle intersects another particle or another mesh, else false.\n * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)\n * @param target is the object (solid particle or mesh) what the intersection is computed against.\n * @returns true if it intersects\n */\n intersectsMesh(target) {\n if (!this._boundingInfo || !target.hasBoundingInfo) {\n return false;\n }\n if (this._sps._bSphereOnly) {\n return BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target.getBoundingInfo().boundingSphere);\n }\n return this._boundingInfo.intersects(target.getBoundingInfo(), false);\n }\n /**\n * Returns `true` if the solid particle is within the frustum defined by the passed array of planes.\n * A particle is in the frustum if its bounding box intersects the frustum\n * @param frustumPlanes defines the frustum to test\n * @returns true if the particle is in the frustum planes\n */\n isInFrustum(frustumPlanes) {\n return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);\n }\n /**\n * get the rotation matrix of the particle\n * @internal\n */\n getRotationMatrix(m) {\n let quaternion;\n if (this.rotationQuaternion) {\n quaternion = this.rotationQuaternion;\n }\n else {\n quaternion = TmpVectors.Quaternion[0];\n const rotation = this.rotation;\n Quaternion.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, quaternion);\n }\n quaternion.toRotationMatrix(m);\n }\n}\n/**\n * Represents the shape of the model used by one particle of a solid particle system.\n * SPS internal tool, don't use it manually.\n */\nexport class ModelShape {\n /**\n * Get or set the shapeId\n * @deprecated Please use shapeId instead\n */\n get shapeID() {\n return this.shapeId;\n }\n set shapeID(shapeID) {\n this.shapeId = shapeID;\n }\n /**\n * Creates a ModelShape object. This is an internal simplified reference to a mesh used as for a model to replicate particles from by the SPS.\n * SPS internal tool, don't use it manually.\n * @internal\n */\n constructor(id, shape, indices, normals, colors, shapeUV, posFunction, vtxFunction, material) {\n /**\n * length of the shape in the model indices array (internal use)\n * @internal\n */\n this._indicesLength = 0;\n this.shapeId = id;\n this._shape = shape;\n this._indices = indices;\n this._indicesLength = indices.length;\n this._shapeUV = shapeUV;\n this._shapeColors = colors;\n this._normals = normals;\n this._positionFunction = posFunction;\n this._vertexFunction = vtxFunction;\n this._material = material;\n }\n}\n/**\n * Represents a Depth Sorted Particle in the solid particle system.\n * @internal\n */\nexport class DepthSortedParticle {\n /**\n * Creates a new sorted particle\n * @param idx\n * @param ind\n * @param indLength\n * @param materialIndex\n */\n constructor(idx, ind, indLength, materialIndex) {\n /**\n * Particle index\n */\n this.idx = 0;\n /**\n * Index of the particle in the \"indices\" array\n */\n this.ind = 0;\n /**\n * Length of the particle shape in the \"indices\" array\n */\n this.indicesLength = 0;\n /**\n * Squared distance from the particle to the camera\n */\n this.sqDistance = 0.0;\n /**\n * Material index when used with MultiMaterials\n */\n this.materialIndex = 0;\n this.idx = idx;\n this.ind = ind;\n this.indicesLength = indLength;\n this.materialIndex = materialIndex;\n }\n}\n/**\n * Represents a solid particle vertex\n */\nexport class SolidParticleVertex {\n /**\n * Creates a new solid particle vertex\n */\n constructor() {\n this.position = Vector3.Zero();\n this.color = new Color4(1.0, 1.0, 1.0, 1.0);\n this.uv = Vector2.Zero();\n }\n // Getters and Setters for back-compatibility\n /** Vertex x coordinate */\n get x() {\n return this.position.x;\n }\n set x(val) {\n this.position.x = val;\n }\n /** Vertex y coordinate */\n get y() {\n return this.position.y;\n }\n set y(val) {\n this.position.y = val;\n }\n /** Vertex z coordinate */\n get z() {\n return this.position.z;\n }\n set z(val) {\n this.position.z = val;\n }\n}\n//# sourceMappingURL=solidParticle.js.map","import { Vector3, Matrix, TmpVectors, Quaternion } from \"../Maths/math.vector.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { VertexData } from \"../Meshes/mesh.vertexData.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { CreateDisc } from \"../Meshes/Builders/discBuilder.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { DepthSortedParticle, SolidParticle, ModelShape, SolidParticleVertex } from \"./solidParticle.js\";\nimport { BoundingInfo } from \"../Culling/boundingInfo.js\";\nimport { Axis } from \"../Maths/math.axis.js\";\nimport { SubMesh } from \"../Meshes/subMesh.js\";\nimport { StandardMaterial } from \"../Materials/standardMaterial.js\";\nimport { MultiMaterial } from \"../Materials/multiMaterial.js\";\n/**\n * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces of this big mesh.\n *As it is just a mesh, the SPS has all the same properties than any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc.\n\n * The SPS is also a particle system. It provides some methods to manage the particles.\n * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.\n *\n * Full documentation here : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/sps_intro\n */\nexport class SolidParticleSystem {\n /**\n * Creates a SPS (Solid Particle System) object.\n * @param name (String) is the SPS name, this will be the underlying mesh name.\n * @param scene (Scene) is the scene in which the SPS is added.\n * @param options defines the options of the sps e.g.\n * * updatable (optional boolean, default true) : if the SPS must be updatable or immutable.\n * * isPickable (optional boolean, default false) : if the solid particles must be pickable.\n * * enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.\n * * useModelMaterial (optional boolean, default false) : if the model materials must be used to create the SPS multimaterial. This enables the multimaterial supports of the SPS.\n * * enableMultiMaterial (optional boolean, default false) : if the solid particles can be given different materials.\n * * expandable (optional boolean, default false) : if particles can still be added after the initial SPS mesh creation.\n * * particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.\n * * boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).\n * * bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the bounding sphere radius by in order to reduce it for instance.\n * * computeBoundingBox (optional boolean, default false): if the bounding box of the entire SPS will be computed (for occlusion detection, for example). If it is false, the bounding box will be the bounding box of the first particle.\n * * autoFixFaceOrientation (optional boolean, default false): if the particle face orientations will be flipped for transformations that change orientation (scale (-1, 1, 1), for example)\n * @param options.updatable\n * @param options.isPickable\n * @param options.enableDepthSort\n * @param options.particleIntersection\n * @param options.boundingSphereOnly\n * @param options.bSphereRadiusFactor\n * @param options.expandable\n * @param options.useModelMaterial\n * @param options.enableMultiMaterial\n * @param options.computeBoundingBox\n * @param options.autoFixFaceOrientation\n * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.\n */\n constructor(name, scene, options) {\n /**\n * The SPS array of Solid Particle objects. Just access each particle as with any classic array.\n * Example : var p = SPS.particles[i];\n */\n this.particles = new Array();\n /**\n * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.\n */\n this.nbParticles = 0;\n /**\n * If the particles must ever face the camera (default false). Useful for planar particles.\n */\n this.billboard = false;\n /**\n * Recompute normals when adding a shape\n */\n this.recomputeNormals = false;\n /**\n * This a counter ofr your own usage. It's not set by any SPS functions.\n */\n this.counter = 0;\n /**\n * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.\n * Please read : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/optimize_sps#limit-garbage-collection\n */\n this.vars = {};\n /**\n * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)\n * @internal\n */\n this._bSphereOnly = false;\n /**\n * A number to multiply the bounding sphere radius by in order to reduce it for instance. (Internal use only)\n * @internal\n */\n this._bSphereRadiusFactor = 1.0;\n this._positions = new Array();\n this._indices = new Array();\n this._normals = new Array();\n this._colors = new Array();\n this._uvs = new Array();\n this._index = 0; // indices index\n this._updatable = true;\n this._pickable = false;\n this._isVisibilityBoxLocked = false;\n this._alwaysVisible = false;\n this._depthSort = false;\n this._expandable = false;\n this._shapeCounter = 0;\n this._copy = new SolidParticle(0, 0, 0, 0, null, 0, 0, this);\n this._color = new Color4(0, 0, 0, 0);\n this._computeParticleColor = true;\n this._computeParticleTexture = true;\n this._computeParticleRotation = true;\n this._computeParticleVertex = false;\n this._computeBoundingBox = false;\n this._autoFixFaceOrientation = false;\n this._depthSortParticles = true;\n this._mustUnrotateFixedNormals = false;\n this._particlesIntersect = false;\n this._needs32Bits = false;\n this._isNotBuilt = true;\n this._lastParticleId = 0;\n this._idxOfId = []; // array : key = particle.id / value = particle.idx\n this._multimaterialEnabled = false;\n this._useModelMaterial = false;\n this._depthSortFunction = (p1, p2) => p2.sqDistance - p1.sqDistance;\n this._materialSortFunction = (p1, p2) => p1.materialIndex - p2.materialIndex;\n this._autoUpdateSubMeshes = false;\n this._recomputeInvisibles = false;\n this.name = name;\n this._scene = scene || EngineStore.LastCreatedScene;\n this._camera = scene.activeCamera;\n this._pickable = options ? options.isPickable : false;\n this._depthSort = options ? options.enableDepthSort : false;\n this._multimaterialEnabled = options ? options.enableMultiMaterial : false;\n this._useModelMaterial = options ? options.useModelMaterial : false;\n this._multimaterialEnabled = this._useModelMaterial ? true : this._multimaterialEnabled;\n this._expandable = options ? options.expandable : false;\n this._particlesIntersect = options ? options.particleIntersection : false;\n this._bSphereOnly = options ? options.boundingSphereOnly : false;\n this._bSphereRadiusFactor = options && options.bSphereRadiusFactor ? options.bSphereRadiusFactor : 1.0;\n this._computeBoundingBox = (options === null || options === void 0 ? void 0 : options.computeBoundingBox) ? options.computeBoundingBox : false;\n this._autoFixFaceOrientation = (options === null || options === void 0 ? void 0 : options.autoFixFaceOrientation) ? options.autoFixFaceOrientation : false;\n if (options && options.updatable !== undefined) {\n this._updatable = options.updatable;\n }\n else {\n this._updatable = true;\n }\n if (this._pickable) {\n this.pickedBySubMesh = [[]];\n this.pickedParticles = this.pickedBySubMesh[0];\n }\n if (this._depthSort || this._multimaterialEnabled) {\n this.depthSortedParticles = [];\n }\n if (this._multimaterialEnabled) {\n this._multimaterial = new MultiMaterial(this.name + \"MultiMaterial\", this._scene);\n this._materials = [];\n this._materialIndexesById = {};\n }\n this._tmpVertex = new SolidParticleVertex();\n }\n /**\n * Builds the SPS underlying mesh. Returns a standard Mesh.\n * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.\n * @returns the created mesh\n */\n buildMesh() {\n if (!this._isNotBuilt && this.mesh) {\n return this.mesh;\n }\n if (this.nbParticles === 0 && !this.mesh) {\n const triangle = CreateDisc(\"\", { radius: 1, tessellation: 3 }, this._scene);\n this.addShape(triangle, 1);\n triangle.dispose();\n }\n this._indices32 = this._needs32Bits ? new Uint32Array(this._indices) : new Uint16Array(this._indices);\n this._positions32 = new Float32Array(this._positions);\n this._uvs32 = new Float32Array(this._uvs);\n this._colors32 = new Float32Array(this._colors);\n if (!this.mesh) {\n // in case it's already expanded\n const mesh = new Mesh(this.name, this._scene);\n this.mesh = mesh;\n }\n if (!this._updatable && this._multimaterialEnabled) {\n this._sortParticlesByMaterial(); // this may reorder the indices32\n }\n if (this.recomputeNormals) {\n VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);\n }\n this._normals32 = new Float32Array(this._normals);\n this._fixedNormal32 = new Float32Array(this._normals);\n if (this._mustUnrotateFixedNormals) {\n // the particles could be created already rotated in the mesh with a positionFunction\n this._unrotateFixedNormals();\n }\n const vertexData = new VertexData();\n vertexData.indices = this._depthSort ? this._indices : this._indices32;\n vertexData.set(this._positions32, VertexBuffer.PositionKind);\n vertexData.set(this._normals32, VertexBuffer.NormalKind);\n if (this._uvs32.length > 0) {\n vertexData.set(this._uvs32, VertexBuffer.UVKind);\n }\n if (this._colors32.length > 0) {\n vertexData.set(this._colors32, VertexBuffer.ColorKind);\n }\n vertexData.applyToMesh(this.mesh, this._updatable);\n this.mesh.isPickable = this._pickable;\n if (this._pickable) {\n let faceId = 0;\n for (let p = 0; p < this.nbParticles; p++) {\n const part = this.particles[p];\n const lind = part._model._indicesLength;\n for (let i = 0; i < lind; i++) {\n const f = i % 3;\n if (f == 0) {\n const pickedData = { idx: part.idx, faceId: faceId };\n this.pickedParticles[faceId] = pickedData;\n faceId++;\n }\n }\n }\n }\n if (this._multimaterialEnabled) {\n this.setMultiMaterial(this._materials);\n }\n if (!this._expandable) {\n // free memory\n if (!this._depthSort && !this._multimaterialEnabled && !this._autoFixFaceOrientation) {\n this._indices = null;\n }\n this._positions = null;\n this._normals = null;\n this._uvs = null;\n this._colors = null;\n if (!this._updatable) {\n this.particles.length = 0;\n }\n }\n this._isNotBuilt = false;\n this.recomputeNormals = false;\n this._recomputeInvisibles = true;\n return this.mesh;\n }\n /**\n * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.\n * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.\n * Thus the particles generated from `digest()` have their property `position` set yet.\n * @param mesh ( Mesh ) is the mesh to be digested\n * @param options {facetNb} (optional integer, default 1) is the number of mesh facets per particle, this parameter is overridden by the parameter `number` if any\n * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets\n * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets\n * {storage} (optional existing array) is an array where the particles will be stored for a further use instead of being inserted in the SPS.\n * @param options.facetNb\n * @param options.number\n * @param options.delta\n * @param options.storage\n * @returns the current SPS\n */\n digest(mesh, options) {\n let size = (options && options.facetNb) || 1;\n let number = (options && options.number) || 0;\n let delta = (options && options.delta) || 0;\n const meshPos = mesh.getVerticesData(VertexBuffer.PositionKind);\n const meshInd = mesh.getIndices();\n const meshUV = mesh.getVerticesData(VertexBuffer.UVKind);\n const meshCol = mesh.getVerticesData(VertexBuffer.ColorKind);\n const meshNor = mesh.getVerticesData(VertexBuffer.NormalKind);\n const storage = options && options.storage ? options.storage : null;\n let f = 0; // facet counter\n const totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices\n // compute size from number\n if (number) {\n number = number > totalFacets ? totalFacets : number;\n size = Math.round(totalFacets / number);\n delta = 0;\n }\n else {\n size = size > totalFacets ? totalFacets : size;\n }\n const facetPos = []; // submesh positions\n const facetNor = [];\n const facetInd = []; // submesh indices\n const facetUV = []; // submesh UV\n const facetCol = []; // submesh colors\n const barycenter = Vector3.Zero();\n const sizeO = size;\n while (f < totalFacets) {\n size = sizeO + Math.floor((1 + delta) * Math.random());\n if (f > totalFacets - size) {\n size = totalFacets - f;\n }\n // reset temp arrays\n facetPos.length = 0;\n facetNor.length = 0;\n facetInd.length = 0;\n facetUV.length = 0;\n facetCol.length = 0;\n // iterate over \"size\" facets\n let fi = 0;\n for (let j = f * 3; j < (f + size) * 3; j++) {\n facetInd.push(fi);\n const i = meshInd[j];\n const i3 = i * 3;\n facetPos.push(meshPos[i3], meshPos[i3 + 1], meshPos[i3 + 2]);\n facetNor.push(meshNor[i3], meshNor[i3 + 1], meshNor[i3 + 2]);\n if (meshUV) {\n const i2 = i * 2;\n facetUV.push(meshUV[i2], meshUV[i2 + 1]);\n }\n if (meshCol) {\n const i4 = i * 4;\n facetCol.push(meshCol[i4], meshCol[i4 + 1], meshCol[i4 + 2], meshCol[i4 + 3]);\n }\n fi++;\n }\n // create a model shape for each single particle\n let idx = this.nbParticles;\n const shape = this._posToShape(facetPos);\n const shapeUV = this._uvsToShapeUV(facetUV);\n const shapeInd = facetInd.slice();\n const shapeCol = facetCol.slice();\n const shapeNor = facetNor.slice();\n // compute the barycenter of the shape\n barycenter.copyFromFloats(0, 0, 0);\n let v;\n for (v = 0; v < shape.length; v++) {\n barycenter.addInPlace(shape[v]);\n }\n barycenter.scaleInPlace(1 / shape.length);\n // shift the shape from its barycenter to the origin\n // and compute the BBox required for intersection.\n const minimum = new Vector3(Infinity, Infinity, Infinity);\n const maximum = new Vector3(-Infinity, -Infinity, -Infinity);\n for (v = 0; v < shape.length; v++) {\n shape[v].subtractInPlace(barycenter);\n minimum.minimizeInPlaceFromFloats(shape[v].x, shape[v].y, shape[v].z);\n maximum.maximizeInPlaceFromFloats(shape[v].x, shape[v].y, shape[v].z);\n }\n let bInfo;\n if (this._particlesIntersect) {\n bInfo = new BoundingInfo(minimum, maximum);\n }\n let material = null;\n if (this._useModelMaterial) {\n material = mesh.material ? mesh.material : this._setDefaultMaterial();\n }\n const modelShape = new ModelShape(this._shapeCounter, shape, shapeInd, shapeNor, shapeCol, shapeUV, null, null, material);\n // add the particle in the SPS\n const currentPos = this._positions.length;\n const currentInd = this._indices.length;\n this._meshBuilder(this._index, currentInd, shape, this._positions, shapeInd, this._indices, facetUV, this._uvs, shapeCol, this._colors, shapeNor, this._normals, idx, 0, null, modelShape);\n this._addParticle(idx, this._lastParticleId, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo, storage);\n // initialize the particle position\n this.particles[this.nbParticles].position.addInPlace(barycenter);\n if (!storage) {\n this._index += shape.length;\n idx++;\n this.nbParticles++;\n this._lastParticleId++;\n }\n this._shapeCounter++;\n f += size;\n }\n this._isNotBuilt = true; // buildMesh() is now expected for setParticles() to work\n return this;\n }\n /**\n * Unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()\n * @internal\n */\n _unrotateFixedNormals() {\n let index = 0;\n let idx = 0;\n const tmpNormal = TmpVectors.Vector3[0];\n const quaternion = TmpVectors.Quaternion[0];\n const invertedRotMatrix = TmpVectors.Matrix[0];\n for (let p = 0; p < this.particles.length; p++) {\n const particle = this.particles[p];\n const shape = particle._model._shape;\n // computing the inverse of the rotation matrix from the quaternion\n // is equivalent to computing the matrix of the inverse quaternion, i.e of the conjugate quaternion\n if (particle.rotationQuaternion) {\n particle.rotationQuaternion.conjugateToRef(quaternion);\n }\n else {\n const rotation = particle.rotation;\n Quaternion.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, quaternion);\n quaternion.conjugateInPlace();\n }\n quaternion.toRotationMatrix(invertedRotMatrix);\n for (let pt = 0; pt < shape.length; pt++) {\n idx = index + pt * 3;\n Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], invertedRotMatrix, tmpNormal);\n tmpNormal.toArray(this._fixedNormal32, idx);\n }\n index = idx + 3;\n }\n }\n /**\n * Resets the temporary working copy particle\n * @internal\n */\n _resetCopy() {\n const copy = this._copy;\n copy.position.setAll(0);\n copy.rotation.setAll(0);\n copy.rotationQuaternion = null;\n copy.scaling.setAll(1);\n copy.uvs.copyFromFloats(0.0, 0.0, 1.0, 1.0);\n copy.color = null;\n copy.translateFromPivot = false;\n copy.shapeId = 0;\n copy.materialIndex = null;\n }\n /**\n * Inserts the shape model geometry in the global SPS mesh by updating the positions, indices, normals, colors, uvs arrays\n * @param p the current index in the positions array to be updated\n * @param ind the current index in the indices array\n * @param shape a Vector3 array, the shape geometry\n * @param positions the positions array to be updated\n * @param meshInd the shape indices array\n * @param indices the indices array to be updated\n * @param meshUV the shape uv array\n * @param uvs the uv array to be updated\n * @param meshCol the shape color array\n * @param colors the color array to be updated\n * @param meshNor the shape normals array\n * @param normals the normals array to be updated\n * @param idx the particle index\n * @param idxInShape the particle index in its shape\n * @param options the addShape() method passed options\n * @param model\n * @model the particle model\n * @internal\n */\n _meshBuilder(p, ind, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options, model) {\n let i;\n let u = 0;\n let c = 0;\n let n = 0;\n this._resetCopy();\n const copy = this._copy;\n const storeApart = options && options.storage ? true : false;\n copy.idx = idx;\n copy.idxInShape = idxInShape;\n copy.shapeId = model.shapeId;\n if (this._useModelMaterial) {\n const materialId = model._material.uniqueId;\n const materialIndexesById = this._materialIndexesById;\n if (!Object.prototype.hasOwnProperty.call(materialIndexesById, materialId)) {\n materialIndexesById[materialId] = this._materials.length;\n this._materials.push(model._material);\n }\n const matIdx = materialIndexesById[materialId];\n copy.materialIndex = matIdx;\n }\n if (options && options.positionFunction) {\n // call to custom positionFunction\n options.positionFunction(copy, idx, idxInShape);\n this._mustUnrotateFixedNormals = true;\n }\n // in case the particle geometry must NOT be inserted in the SPS mesh geometry\n if (storeApart) {\n return copy;\n }\n const rotMatrix = TmpVectors.Matrix[0];\n const tmpVertex = this._tmpVertex;\n const tmpVector = tmpVertex.position;\n const tmpColor = tmpVertex.color;\n const tmpUV = tmpVertex.uv;\n const tmpRotated = TmpVectors.Vector3[1];\n const pivotBackTranslation = TmpVectors.Vector3[2];\n const scaledPivot = TmpVectors.Vector3[3];\n Matrix.IdentityToRef(rotMatrix);\n copy.getRotationMatrix(rotMatrix);\n copy.pivot.multiplyToRef(copy.scaling, scaledPivot);\n if (copy.translateFromPivot) {\n pivotBackTranslation.setAll(0.0);\n }\n else {\n pivotBackTranslation.copyFrom(scaledPivot);\n }\n const someVertexFunction = options && options.vertexFunction;\n for (i = 0; i < shape.length; i++) {\n tmpVector.copyFrom(shape[i]);\n if (copy.color) {\n tmpColor.copyFrom(copy.color);\n }\n if (meshUV) {\n tmpUV.copyFromFloats(meshUV[u], meshUV[u + 1]);\n }\n if (someVertexFunction) {\n options.vertexFunction(copy, tmpVertex, i);\n }\n tmpVector.multiplyInPlace(copy.scaling).subtractInPlace(scaledPivot);\n Vector3.TransformCoordinatesToRef(tmpVector, rotMatrix, tmpRotated);\n tmpRotated.addInPlace(pivotBackTranslation).addInPlace(copy.position);\n positions.push(tmpRotated.x, tmpRotated.y, tmpRotated.z);\n if (meshUV) {\n const copyUvs = copy.uvs;\n uvs.push((copyUvs.z - copyUvs.x) * tmpUV.x + copyUvs.x, (copyUvs.w - copyUvs.y) * tmpUV.y + copyUvs.y);\n u += 2;\n }\n if (copy.color) {\n this._color.copyFrom(tmpColor);\n }\n else {\n const color = this._color;\n if (meshCol && meshCol[c] !== undefined) {\n color.r = meshCol[c];\n color.g = meshCol[c + 1];\n color.b = meshCol[c + 2];\n color.a = meshCol[c + 3];\n }\n else {\n color.r = 1.0;\n color.g = 1.0;\n color.b = 1.0;\n color.a = 1.0;\n }\n }\n colors.push(this._color.r, this._color.g, this._color.b, this._color.a);\n c += 4;\n if (!this.recomputeNormals && meshNor) {\n Vector3.TransformNormalFromFloatsToRef(meshNor[n], meshNor[n + 1], meshNor[n + 2], rotMatrix, tmpVector);\n normals.push(tmpVector.x, tmpVector.y, tmpVector.z);\n n += 3;\n }\n }\n for (i = 0; i < meshInd.length; i++) {\n const current_ind = p + meshInd[i];\n indices.push(current_ind);\n if (current_ind > 65535) {\n this._needs32Bits = true;\n }\n }\n if (this._depthSort || this._multimaterialEnabled) {\n const matIndex = copy.materialIndex !== null ? copy.materialIndex : 0;\n this.depthSortedParticles.push(new DepthSortedParticle(idx, ind, meshInd.length, matIndex));\n }\n return copy;\n }\n /**\n * Returns a shape Vector3 array from positions float array\n * @param positions float array\n * @returns a vector3 array\n * @internal\n */\n _posToShape(positions) {\n const shape = [];\n for (let i = 0; i < positions.length; i += 3) {\n shape.push(Vector3.FromArray(positions, i));\n }\n return shape;\n }\n /**\n * Returns a shapeUV array from a float uvs (array deep copy)\n * @param uvs as a float array\n * @returns a shapeUV array\n * @internal\n */\n _uvsToShapeUV(uvs) {\n const shapeUV = [];\n if (uvs) {\n for (let i = 0; i < uvs.length; i++) {\n shapeUV.push(uvs[i]);\n }\n }\n return shapeUV;\n }\n /**\n * Adds a new particle object in the particles array\n * @param idx particle index in particles array\n * @param id particle id\n * @param idxpos positionIndex : the starting index of the particle vertices in the SPS \"positions\" array\n * @param idxind indiceIndex : he starting index of the particle indices in the SPS \"indices\" array\n * @param model particle ModelShape object\n * @param shapeId model shape identifier\n * @param idxInShape index of the particle in the current model\n * @param bInfo model bounding info object\n * @param storage target storage array, if any\n * @internal\n */\n _addParticle(idx, id, idxpos, idxind, model, shapeId, idxInShape, bInfo = null, storage = null) {\n const sp = new SolidParticle(idx, id, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);\n const target = storage ? storage : this.particles;\n target.push(sp);\n return sp;\n }\n /**\n * Adds some particles to the SPS from the model shape. Returns the shape id.\n * Please read the doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/immutable_sps\n * @param mesh is any Mesh object that will be used as a model for the solid particles.\n * @param nb (positive integer) the number of particles to be created from this model\n * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.\n * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation\n * {storage} (optional existing array) is an array where the particles will be stored for a further use instead of being inserted in the SPS.\n * @param options.positionFunction\n * @param options.vertexFunction\n * @param options.storage\n * @returns the number of shapes in the system\n */\n addShape(mesh, nb, options) {\n const meshPos = mesh.getVerticesData(VertexBuffer.PositionKind);\n const meshInd = mesh.getIndices();\n const meshUV = mesh.getVerticesData(VertexBuffer.UVKind);\n const meshCol = mesh.getVerticesData(VertexBuffer.ColorKind);\n const meshNor = mesh.getVerticesData(VertexBuffer.NormalKind);\n this.recomputeNormals = meshNor ? false : true;\n const indices = Array.from(meshInd);\n const shapeNormals = Array.from(meshNor);\n const shapeColors = meshCol ? Array.from(meshCol) : [];\n const storage = options && options.storage ? options.storage : null;\n let bbInfo = null;\n if (this._particlesIntersect) {\n bbInfo = mesh.getBoundingInfo();\n }\n const shape = this._posToShape(meshPos);\n const shapeUV = this._uvsToShapeUV(meshUV);\n const posfunc = options ? options.positionFunction : null;\n const vtxfunc = options ? options.vertexFunction : null;\n let material = null;\n if (this._useModelMaterial) {\n material = mesh.material ? mesh.material : this._setDefaultMaterial();\n }\n const modelShape = new ModelShape(this._shapeCounter, shape, indices, shapeNormals, shapeColors, shapeUV, posfunc, vtxfunc, material);\n // particles\n for (let i = 0; i < nb; i++) {\n this._insertNewParticle(this.nbParticles, i, modelShape, shape, meshInd, meshUV, meshCol, meshNor, bbInfo, storage, options);\n }\n this._shapeCounter++;\n this._isNotBuilt = true; // buildMesh() call is now expected for setParticles() to work\n return this._shapeCounter - 1;\n }\n /**\n * Rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices\n * @internal\n */\n _rebuildParticle(particle, reset = false) {\n this._resetCopy();\n const copy = this._copy;\n if (particle._model._positionFunction) {\n // recall to stored custom positionFunction\n particle._model._positionFunction(copy, particle.idx, particle.idxInShape);\n }\n const rotMatrix = TmpVectors.Matrix[0];\n const tmpVertex = TmpVectors.Vector3[0];\n const tmpRotated = TmpVectors.Vector3[1];\n const pivotBackTranslation = TmpVectors.Vector3[2];\n const scaledPivot = TmpVectors.Vector3[3];\n copy.getRotationMatrix(rotMatrix);\n particle.pivot.multiplyToRef(particle.scaling, scaledPivot);\n if (copy.translateFromPivot) {\n pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);\n }\n else {\n pivotBackTranslation.copyFrom(scaledPivot);\n }\n const shape = particle._model._shape;\n for (let pt = 0; pt < shape.length; pt++) {\n tmpVertex.copyFrom(shape[pt]);\n if (particle._model._vertexFunction) {\n particle._model._vertexFunction(copy, tmpVertex, pt); // recall to stored vertexFunction\n }\n tmpVertex.multiplyInPlace(copy.scaling).subtractInPlace(scaledPivot);\n Vector3.TransformCoordinatesToRef(tmpVertex, rotMatrix, tmpRotated);\n tmpRotated\n .addInPlace(pivotBackTranslation)\n .addInPlace(copy.position)\n .toArray(this._positions32, particle._pos + pt * 3);\n }\n if (reset) {\n particle.position.setAll(0.0);\n particle.rotation.setAll(0.0);\n particle.rotationQuaternion = null;\n particle.scaling.setAll(1.0);\n particle.uvs.setAll(0.0);\n particle.pivot.setAll(0.0);\n particle.translateFromPivot = false;\n particle.parentId = null;\n }\n }\n /**\n * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.\n * @param reset boolean, default false : if the particles must be reset at position and rotation zero, scaling 1, color white, initial UVs and not parented.\n * @returns the SPS.\n */\n rebuildMesh(reset = false) {\n for (let p = 0; p < this.particles.length; p++) {\n this._rebuildParticle(this.particles[p], reset);\n }\n this.mesh.updateVerticesData(VertexBuffer.PositionKind, this._positions32, false, false);\n return this;\n }\n /** Removes the particles from the start-th to the end-th included from an expandable SPS (required).\n * Returns an array with the removed particles.\n * If the number of particles to remove is lower than zero or greater than the global remaining particle number, then an empty array is returned.\n * The SPS can't be empty so at least one particle needs to remain in place.\n * Under the hood, the VertexData array, so the VBO buffer, is recreated each call.\n * @param start index of the first particle to remove\n * @param end index of the last particle to remove (included)\n * @returns an array populated with the removed particles\n */\n removeParticles(start, end) {\n const nb = end - start + 1;\n if (!this._expandable || nb <= 0 || nb >= this.nbParticles || !this._updatable) {\n return [];\n }\n const particles = this.particles;\n const currentNb = this.nbParticles;\n if (end < currentNb - 1) {\n // update the particle indexes in the positions array in case they're remaining particles after the last removed\n const firstRemaining = end + 1;\n const shiftPos = particles[firstRemaining]._pos - particles[start]._pos;\n const shifInd = particles[firstRemaining]._ind - particles[start]._ind;\n for (let i = firstRemaining; i < currentNb; i++) {\n const part = particles[i];\n part._pos -= shiftPos;\n part._ind -= shifInd;\n }\n }\n const removed = particles.splice(start, nb);\n this._positions.length = 0;\n this._indices.length = 0;\n this._colors.length = 0;\n this._uvs.length = 0;\n this._normals.length = 0;\n this._index = 0;\n this._idxOfId.length = 0;\n if (this._depthSort || this._multimaterialEnabled) {\n this.depthSortedParticles = [];\n }\n let ind = 0;\n const particlesLength = particles.length;\n for (let p = 0; p < particlesLength; p++) {\n const particle = particles[p];\n const model = particle._model;\n const shape = model._shape;\n const modelIndices = model._indices;\n const modelNormals = model._normals;\n const modelColors = model._shapeColors;\n const modelUVs = model._shapeUV;\n particle.idx = p;\n this._idxOfId[particle.id] = p;\n this._meshBuilder(this._index, ind, shape, this._positions, modelIndices, this._indices, modelUVs, this._uvs, modelColors, this._colors, modelNormals, this._normals, particle.idx, particle.idxInShape, null, model);\n this._index += shape.length;\n ind += modelIndices.length;\n }\n this.nbParticles -= nb;\n this._isNotBuilt = true; // buildMesh() call is now expected for setParticles() to work\n return removed;\n }\n /**\n * Inserts some pre-created particles in the solid particle system so that they can be managed by setParticles().\n * @param solidParticleArray an array populated with Solid Particles objects\n * @returns the SPS\n */\n insertParticlesFromArray(solidParticleArray) {\n if (!this._expandable) {\n return this;\n }\n let idxInShape = 0;\n let currentShapeId = solidParticleArray[0].shapeId;\n const nb = solidParticleArray.length;\n for (let i = 0; i < nb; i++) {\n const sp = solidParticleArray[i];\n const model = sp._model;\n const shape = model._shape;\n const meshInd = model._indices;\n const meshUV = model._shapeUV;\n const meshCol = model._shapeColors;\n const meshNor = model._normals;\n const noNor = meshNor ? false : true;\n this.recomputeNormals = noNor || this.recomputeNormals;\n const bbInfo = sp.getBoundingInfo();\n const newPart = this._insertNewParticle(this.nbParticles, idxInShape, model, shape, meshInd, meshUV, meshCol, meshNor, bbInfo, null, null);\n sp.copyToRef(newPart);\n idxInShape++;\n if (currentShapeId != sp.shapeId) {\n currentShapeId = sp.shapeId;\n idxInShape = 0;\n }\n }\n this._isNotBuilt = true; // buildMesh() call is now expected for setParticles() to work\n return this;\n }\n /**\n * Creates a new particle and modifies the SPS mesh geometry :\n * - calls _meshBuilder() to increase the SPS mesh geometry step by step\n * - calls _addParticle() to populate the particle array\n * factorized code from addShape() and insertParticlesFromArray()\n * @param idx particle index in the particles array\n * @param i particle index in its shape\n * @param modelShape particle ModelShape object\n * @param shape shape vertex array\n * @param meshInd shape indices array\n * @param meshUV shape uv array\n * @param meshCol shape color array\n * @param meshNor shape normals array\n * @param bbInfo shape bounding info\n * @param storage target particle storage\n * @param options\n * @options addShape() passed options\n * @internal\n */\n _insertNewParticle(idx, i, modelShape, shape, meshInd, meshUV, meshCol, meshNor, bbInfo, storage, options) {\n const currentPos = this._positions.length;\n const currentInd = this._indices.length;\n const currentCopy = this._meshBuilder(this._index, currentInd, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options, modelShape);\n let sp = null;\n if (this._updatable) {\n sp = this._addParticle(this.nbParticles, this._lastParticleId, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo, storage);\n sp.position.copyFrom(currentCopy.position);\n sp.rotation.copyFrom(currentCopy.rotation);\n if (currentCopy.rotationQuaternion) {\n if (sp.rotationQuaternion) {\n sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);\n }\n else {\n sp.rotationQuaternion = currentCopy.rotationQuaternion.clone();\n }\n }\n if (currentCopy.color) {\n if (sp.color) {\n sp.color.copyFrom(currentCopy.color);\n }\n else {\n sp.color = currentCopy.color.clone();\n }\n }\n sp.scaling.copyFrom(currentCopy.scaling);\n sp.uvs.copyFrom(currentCopy.uvs);\n if (currentCopy.materialIndex !== null) {\n sp.materialIndex = currentCopy.materialIndex;\n }\n if (this.expandable) {\n this._idxOfId[sp.id] = sp.idx;\n }\n }\n if (!storage) {\n this._index += shape.length;\n this.nbParticles++;\n this._lastParticleId++;\n }\n return sp;\n }\n /**\n * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.\n * This method calls `updateParticle()` for each particle of the SPS.\n * For an animated SPS, it is usually called within the render loop.\n * This methods does nothing if called on a non updatable or not yet built SPS. Example : buildMesh() not called after having added or removed particles from an expandable SPS.\n * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_\n * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_\n * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_\n * @returns the SPS.\n */\n setParticles(start = 0, end = this.nbParticles - 1, update = true) {\n if (!this._updatable || this._isNotBuilt) {\n return this;\n }\n // custom beforeUpdate\n this.beforeUpdateParticles(start, end, update);\n const rotMatrix = TmpVectors.Matrix[0];\n const invertedMatrix = TmpVectors.Matrix[1];\n const mesh = this.mesh;\n const colors32 = this._colors32;\n const positions32 = this._positions32;\n const normals32 = this._normals32;\n const uvs32 = this._uvs32;\n const indices32 = this._indices32;\n const indices = this._indices;\n const fixedNormal32 = this._fixedNormal32;\n const depthSortParticles = this._depthSort && this._depthSortParticles;\n const tempVectors = TmpVectors.Vector3;\n const camAxisX = tempVectors[5].copyFromFloats(1.0, 0.0, 0.0);\n const camAxisY = tempVectors[6].copyFromFloats(0.0, 1.0, 0.0);\n const camAxisZ = tempVectors[7].copyFromFloats(0.0, 0.0, 1.0);\n const minimum = tempVectors[8].setAll(Number.MAX_VALUE);\n const maximum = tempVectors[9].setAll(-Number.MAX_VALUE);\n const camInvertedPosition = tempVectors[10].setAll(0);\n const tmpVertex = this._tmpVertex;\n const tmpVector = tmpVertex.position;\n const tmpColor = tmpVertex.color;\n const tmpUV = tmpVertex.uv;\n // cases when the World Matrix is to be computed first\n if (this.billboard || this._depthSort) {\n this.mesh.computeWorldMatrix(true);\n this.mesh._worldMatrix.invertToRef(invertedMatrix);\n }\n // if the particles will always face the camera\n if (this.billboard) {\n // compute the camera position and un-rotate it by the current mesh rotation\n const tmpVector0 = tempVectors[0];\n this._camera.getDirectionToRef(Axis.Z, tmpVector0);\n Vector3.TransformNormalToRef(tmpVector0, invertedMatrix, camAxisZ);\n camAxisZ.normalize();\n // same for camera up vector extracted from the cam view matrix\n const view = this._camera.getViewMatrix(true);\n Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], invertedMatrix, camAxisY);\n Vector3.CrossToRef(camAxisY, camAxisZ, camAxisX);\n camAxisY.normalize();\n camAxisX.normalize();\n }\n // if depthSort, compute the camera global position in the mesh local system\n if (this._depthSort) {\n Vector3.TransformCoordinatesToRef(this._camera.globalPosition, invertedMatrix, camInvertedPosition); // then un-rotate the camera\n }\n Matrix.IdentityToRef(rotMatrix);\n let idx = 0; // current position index in the global array positions32\n let index = 0; // position start index in the global array positions32 of the current particle\n let colidx = 0; // current color index in the global array colors32\n let colorIndex = 0; // color start index in the global array colors32 of the current particle\n let uvidx = 0; // current uv index in the global array uvs32\n let uvIndex = 0; // uv start index in the global array uvs32 of the current particle\n let pt = 0; // current index in the particle model shape\n if (this.mesh.isFacetDataEnabled) {\n this._computeBoundingBox = true;\n }\n end = end >= this.nbParticles ? this.nbParticles - 1 : end;\n if (this._computeBoundingBox) {\n if (start != 0 || end != this.nbParticles - 1) {\n // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.\n const boundingInfo = this.mesh.getBoundingInfo();\n if (boundingInfo) {\n minimum.copyFrom(boundingInfo.minimum);\n maximum.copyFrom(boundingInfo.maximum);\n }\n }\n }\n // particle loop\n index = this.particles[start]._pos;\n const vpos = (index / 3) | 0;\n colorIndex = vpos * 4;\n uvIndex = vpos * 2;\n for (let p = start; p <= end; p++) {\n const particle = this.particles[p];\n // call to custom user function to update the particle properties\n this.updateParticle(particle);\n const shape = particle._model._shape;\n const shapeUV = particle._model._shapeUV;\n const particleRotationMatrix = particle._rotationMatrix;\n const particlePosition = particle.position;\n const particleRotation = particle.rotation;\n const particleScaling = particle.scaling;\n const particleGlobalPosition = particle._globalPosition;\n // camera-particle distance for depth sorting\n if (depthSortParticles) {\n const dsp = this.depthSortedParticles[p];\n dsp.idx = particle.idx;\n dsp.ind = particle._ind;\n dsp.indicesLength = particle._model._indicesLength;\n dsp.sqDistance = Vector3.DistanceSquared(particle.position, camInvertedPosition);\n }\n // skip the computations for inactive or already invisible particles\n if (!particle.alive || (particle._stillInvisible && !particle.isVisible && !this._recomputeInvisibles)) {\n // increment indexes for the next particle\n pt = shape.length;\n index += pt * 3;\n colorIndex += pt * 4;\n uvIndex += pt * 2;\n continue;\n }\n if (particle.isVisible) {\n particle._stillInvisible = false; // un-mark permanent invisibility\n const scaledPivot = tempVectors[12];\n particle.pivot.multiplyToRef(particleScaling, scaledPivot);\n // particle rotation matrix\n if (this.billboard) {\n particleRotation.x = 0.0;\n particleRotation.y = 0.0;\n }\n if (this._computeParticleRotation || this.billboard) {\n particle.getRotationMatrix(rotMatrix);\n }\n const particleHasParent = particle.parentId !== null;\n if (particleHasParent) {\n const parent = this.getParticleById(particle.parentId);\n if (parent) {\n const parentRotationMatrix = parent._rotationMatrix;\n const parentGlobalPosition = parent._globalPosition;\n const rotatedY = particlePosition.x * parentRotationMatrix[1] + particlePosition.y * parentRotationMatrix[4] + particlePosition.z * parentRotationMatrix[7];\n const rotatedX = particlePosition.x * parentRotationMatrix[0] + particlePosition.y * parentRotationMatrix[3] + particlePosition.z * parentRotationMatrix[6];\n const rotatedZ = particlePosition.x * parentRotationMatrix[2] + particlePosition.y * parentRotationMatrix[5] + particlePosition.z * parentRotationMatrix[8];\n particleGlobalPosition.x = parentGlobalPosition.x + rotatedX;\n particleGlobalPosition.y = parentGlobalPosition.y + rotatedY;\n particleGlobalPosition.z = parentGlobalPosition.z + rotatedZ;\n if (this._computeParticleRotation || this.billboard) {\n const rotMatrixValues = rotMatrix.m;\n particleRotationMatrix[0] =\n rotMatrixValues[0] * parentRotationMatrix[0] + rotMatrixValues[1] * parentRotationMatrix[3] + rotMatrixValues[2] * parentRotationMatrix[6];\n particleRotationMatrix[1] =\n rotMatrixValues[0] * parentRotationMatrix[1] + rotMatrixValues[1] * parentRotationMatrix[4] + rotMatrixValues[2] * parentRotationMatrix[7];\n particleRotationMatrix[2] =\n rotMatrixValues[0] * parentRotationMatrix[2] + rotMatrixValues[1] * parentRotationMatrix[5] + rotMatrixValues[2] * parentRotationMatrix[8];\n particleRotationMatrix[3] =\n rotMatrixValues[4] * parentRotationMatrix[0] + rotMatrixValues[5] * parentRotationMatrix[3] + rotMatrixValues[6] * parentRotationMatrix[6];\n particleRotationMatrix[4] =\n rotMatrixValues[4] * parentRotationMatrix[1] + rotMatrixValues[5] * parentRotationMatrix[4] + rotMatrixValues[6] * parentRotationMatrix[7];\n particleRotationMatrix[5] =\n rotMatrixValues[4] * parentRotationMatrix[2] + rotMatrixValues[5] * parentRotationMatrix[5] + rotMatrixValues[6] * parentRotationMatrix[8];\n particleRotationMatrix[6] =\n rotMatrixValues[8] * parentRotationMatrix[0] + rotMatrixValues[9] * parentRotationMatrix[3] + rotMatrixValues[10] * parentRotationMatrix[6];\n particleRotationMatrix[7] =\n rotMatrixValues[8] * parentRotationMatrix[1] + rotMatrixValues[9] * parentRotationMatrix[4] + rotMatrixValues[10] * parentRotationMatrix[7];\n particleRotationMatrix[8] =\n rotMatrixValues[8] * parentRotationMatrix[2] + rotMatrixValues[9] * parentRotationMatrix[5] + rotMatrixValues[10] * parentRotationMatrix[8];\n }\n }\n else {\n // in case the parent were removed at some moment\n particle.parentId = null;\n }\n }\n else {\n particleGlobalPosition.x = particlePosition.x;\n particleGlobalPosition.y = particlePosition.y;\n particleGlobalPosition.z = particlePosition.z;\n if (this._computeParticleRotation || this.billboard) {\n const rotMatrixValues = rotMatrix.m;\n particleRotationMatrix[0] = rotMatrixValues[0];\n particleRotationMatrix[1] = rotMatrixValues[1];\n particleRotationMatrix[2] = rotMatrixValues[2];\n particleRotationMatrix[3] = rotMatrixValues[4];\n particleRotationMatrix[4] = rotMatrixValues[5];\n particleRotationMatrix[5] = rotMatrixValues[6];\n particleRotationMatrix[6] = rotMatrixValues[8];\n particleRotationMatrix[7] = rotMatrixValues[9];\n particleRotationMatrix[8] = rotMatrixValues[10];\n }\n }\n const pivotBackTranslation = tempVectors[11];\n if (particle.translateFromPivot) {\n pivotBackTranslation.setAll(0.0);\n }\n else {\n pivotBackTranslation.copyFrom(scaledPivot);\n }\n // particle vertex loop\n for (pt = 0; pt < shape.length; pt++) {\n idx = index + pt * 3;\n colidx = colorIndex + pt * 4;\n uvidx = uvIndex + pt * 2;\n const iu = 2 * pt;\n const iv = iu + 1;\n tmpVector.copyFrom(shape[pt]);\n if (this._computeParticleColor && particle.color) {\n tmpColor.copyFrom(particle.color);\n }\n if (this._computeParticleTexture) {\n tmpUV.copyFromFloats(shapeUV[iu], shapeUV[iv]);\n }\n if (this._computeParticleVertex) {\n this.updateParticleVertex(particle, tmpVertex, pt);\n }\n // positions\n const vertexX = tmpVector.x * particleScaling.x - scaledPivot.x;\n const vertexY = tmpVector.y * particleScaling.y - scaledPivot.y;\n const vertexZ = tmpVector.z * particleScaling.z - scaledPivot.z;\n let rotatedX = vertexX * particleRotationMatrix[0] + vertexY * particleRotationMatrix[3] + vertexZ * particleRotationMatrix[6];\n let rotatedY = vertexX * particleRotationMatrix[1] + vertexY * particleRotationMatrix[4] + vertexZ * particleRotationMatrix[7];\n let rotatedZ = vertexX * particleRotationMatrix[2] + vertexY * particleRotationMatrix[5] + vertexZ * particleRotationMatrix[8];\n rotatedX += pivotBackTranslation.x;\n rotatedY += pivotBackTranslation.y;\n rotatedZ += pivotBackTranslation.z;\n const px = (positions32[idx] = particleGlobalPosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ);\n const py = (positions32[idx + 1] = particleGlobalPosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ);\n const pz = (positions32[idx + 2] = particleGlobalPosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ);\n if (this._computeBoundingBox) {\n minimum.minimizeInPlaceFromFloats(px, py, pz);\n maximum.maximizeInPlaceFromFloats(px, py, pz);\n }\n // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()\n if (!this._computeParticleVertex) {\n const normalx = fixedNormal32[idx];\n const normaly = fixedNormal32[idx + 1];\n const normalz = fixedNormal32[idx + 2];\n const rotatedx = normalx * particleRotationMatrix[0] + normaly * particleRotationMatrix[3] + normalz * particleRotationMatrix[6];\n const rotatedy = normalx * particleRotationMatrix[1] + normaly * particleRotationMatrix[4] + normalz * particleRotationMatrix[7];\n const rotatedz = normalx * particleRotationMatrix[2] + normaly * particleRotationMatrix[5] + normalz * particleRotationMatrix[8];\n normals32[idx] = camAxisX.x * rotatedx + camAxisY.x * rotatedy + camAxisZ.x * rotatedz;\n normals32[idx + 1] = camAxisX.y * rotatedx + camAxisY.y * rotatedy + camAxisZ.y * rotatedz;\n normals32[idx + 2] = camAxisX.z * rotatedx + camAxisY.z * rotatedy + camAxisZ.z * rotatedz;\n }\n if (this._computeParticleColor && particle.color) {\n const colors32 = this._colors32;\n colors32[colidx] = tmpColor.r;\n colors32[colidx + 1] = tmpColor.g;\n colors32[colidx + 2] = tmpColor.b;\n colors32[colidx + 3] = tmpColor.a;\n }\n if (this._computeParticleTexture) {\n const uvs = particle.uvs;\n uvs32[uvidx] = tmpUV.x * (uvs.z - uvs.x) + uvs.x;\n uvs32[uvidx + 1] = tmpUV.y * (uvs.w - uvs.y) + uvs.y;\n }\n }\n }\n // particle just set invisible : scaled to zero and positioned at the origin\n else {\n particle._stillInvisible = true; // mark the particle as invisible\n for (pt = 0; pt < shape.length; pt++) {\n idx = index + pt * 3;\n colidx = colorIndex + pt * 4;\n uvidx = uvIndex + pt * 2;\n positions32[idx] = positions32[idx + 1] = positions32[idx + 2] = 0;\n normals32[idx] = normals32[idx + 1] = normals32[idx + 2] = 0;\n if (this._computeParticleColor && particle.color) {\n const color = particle.color;\n colors32[colidx] = color.r;\n colors32[colidx + 1] = color.g;\n colors32[colidx + 2] = color.b;\n colors32[colidx + 3] = color.a;\n }\n if (this._computeParticleTexture) {\n const uvs = particle.uvs;\n uvs32[uvidx] = shapeUV[pt * 2] * (uvs.z - uvs.x) + uvs.x;\n uvs32[uvidx + 1] = shapeUV[pt * 2 + 1] * (uvs.w - uvs.y) + uvs.y;\n }\n }\n }\n // if the particle intersections must be computed : update the bbInfo\n if (this._particlesIntersect) {\n const bInfo = particle.getBoundingInfo();\n const bBox = bInfo.boundingBox;\n const bSphere = bInfo.boundingSphere;\n const modelBoundingInfo = particle._modelBoundingInfo;\n if (!this._bSphereOnly) {\n // place, scale and rotate the particle bbox within the SPS local system, then update it\n const modelBoundingInfoVectors = modelBoundingInfo.boundingBox.vectors;\n const tempMin = tempVectors[1];\n const tempMax = tempVectors[2];\n tempMin.setAll(Number.MAX_VALUE);\n tempMax.setAll(-Number.MAX_VALUE);\n for (let b = 0; b < 8; b++) {\n const scaledX = modelBoundingInfoVectors[b].x * particleScaling.x;\n const scaledY = modelBoundingInfoVectors[b].y * particleScaling.y;\n const scaledZ = modelBoundingInfoVectors[b].z * particleScaling.z;\n const rotatedX = scaledX * particleRotationMatrix[0] + scaledY * particleRotationMatrix[3] + scaledZ * particleRotationMatrix[6];\n const rotatedY = scaledX * particleRotationMatrix[1] + scaledY * particleRotationMatrix[4] + scaledZ * particleRotationMatrix[7];\n const rotatedZ = scaledX * particleRotationMatrix[2] + scaledY * particleRotationMatrix[5] + scaledZ * particleRotationMatrix[8];\n const x = particlePosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ;\n const y = particlePosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ;\n const z = particlePosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ;\n tempMin.minimizeInPlaceFromFloats(x, y, z);\n tempMax.maximizeInPlaceFromFloats(x, y, z);\n }\n bBox.reConstruct(tempMin, tempMax, mesh._worldMatrix);\n }\n // place and scale the particle bouding sphere in the SPS local system, then update it\n const minBbox = modelBoundingInfo.minimum.multiplyToRef(particleScaling, tempVectors[1]);\n const maxBbox = modelBoundingInfo.maximum.multiplyToRef(particleScaling, tempVectors[2]);\n const bSphereCenter = maxBbox.addToRef(minBbox, tempVectors[3]).scaleInPlace(0.5).addInPlace(particleGlobalPosition);\n const halfDiag = maxBbox.subtractToRef(minBbox, tempVectors[4]).scaleInPlace(0.5 * this._bSphereRadiusFactor);\n const bSphereMinBbox = bSphereCenter.subtractToRef(halfDiag, tempVectors[1]);\n const bSphereMaxBbox = bSphereCenter.addToRef(halfDiag, tempVectors[2]);\n bSphere.reConstruct(bSphereMinBbox, bSphereMaxBbox, mesh._worldMatrix);\n }\n // increment indexes for the next particle\n index = idx + 3;\n colorIndex = colidx + 4;\n uvIndex = uvidx + 2;\n }\n // if the VBO must be updated\n if (update) {\n if (this._computeParticleColor) {\n const vb = mesh.getVertexBuffer(VertexBuffer.ColorKind);\n if (vb && !mesh.isPickable) {\n vb.updateDirectly(colors32, 0);\n }\n else {\n mesh.updateVerticesData(VertexBuffer.ColorKind, colors32, false, false);\n }\n }\n if (this._computeParticleTexture) {\n const vb = mesh.getVertexBuffer(VertexBuffer.UVKind);\n if (vb && !mesh.isPickable) {\n vb.updateDirectly(uvs32, 0);\n }\n else {\n mesh.updateVerticesData(VertexBuffer.UVKind, uvs32, false, false);\n }\n }\n const vbp = mesh.getVertexBuffer(VertexBuffer.PositionKind);\n if (vbp && !mesh.isPickable) {\n vbp.updateDirectly(positions32, 0);\n }\n else {\n mesh.updateVerticesData(VertexBuffer.PositionKind, positions32, false, false);\n }\n if (!mesh.areNormalsFrozen || mesh.isFacetDataEnabled) {\n if (this._computeParticleVertex || mesh.isFacetDataEnabled) {\n // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]\n const params = mesh.isFacetDataEnabled ? mesh.getFacetDataParameters() : null;\n VertexData.ComputeNormals(positions32, indices32, normals32, params);\n for (let i = 0; i < normals32.length; i++) {\n fixedNormal32[i] = normals32[i];\n }\n }\n if (!mesh.areNormalsFrozen) {\n const vb = mesh.getVertexBuffer(VertexBuffer.NormalKind);\n if (vb && !mesh.isPickable) {\n vb.updateDirectly(normals32, 0);\n }\n else {\n mesh.updateVerticesData(VertexBuffer.NormalKind, normals32, false, false);\n }\n }\n }\n if (depthSortParticles) {\n const depthSortedParticles = this.depthSortedParticles;\n depthSortedParticles.sort(this._depthSortFunction);\n const dspl = depthSortedParticles.length;\n let sid = 0;\n let faceId = 0;\n for (let sorted = 0; sorted < dspl; sorted++) {\n const sortedParticle = depthSortedParticles[sorted];\n const lind = sortedParticle.indicesLength;\n const sind = sortedParticle.ind;\n for (let i = 0; i < lind; i++) {\n indices32[sid] = indices[sind + i];\n sid++;\n if (this._pickable) {\n const f = i % 3;\n if (f == 0) {\n const pickedData = this.pickedParticles[faceId];\n pickedData.idx = sortedParticle.idx;\n pickedData.faceId = faceId;\n faceId++;\n }\n }\n }\n }\n }\n if (this._autoFixFaceOrientation) {\n let particleInd = 0;\n for (let particleIdx = 0; particleIdx < this.particles.length; particleIdx++) {\n const particle = depthSortParticles ? this.particles[this.depthSortedParticles[particleIdx].idx] : this.particles[particleIdx];\n const flipFaces = particle.scale.x * particle.scale.y * particle.scale.z < 0;\n if (flipFaces) {\n for (let faceInd = 0; faceInd < particle._model._indicesLength; faceInd += 3) {\n const tmp = indices[particle._ind + faceInd];\n indices32[particleInd + faceInd] = indices[particle._ind + faceInd + 1];\n indices32[particleInd + faceInd + 1] = tmp;\n }\n }\n particleInd += particle._model._indicesLength;\n }\n }\n if (depthSortParticles || this._autoFixFaceOrientation) {\n mesh.updateIndices(indices32);\n }\n }\n if (this._computeBoundingBox) {\n if (mesh.hasBoundingInfo) {\n mesh.getBoundingInfo().reConstruct(minimum, maximum, mesh._worldMatrix);\n }\n else {\n mesh.buildBoundingInfo(minimum, maximum, mesh._worldMatrix);\n }\n }\n if (this._autoUpdateSubMeshes) {\n this.computeSubMeshes();\n }\n this._recomputeInvisibles = false;\n this.afterUpdateParticles(start, end, update);\n return this;\n }\n /**\n * Disposes the SPS.\n */\n dispose() {\n this.mesh.dispose();\n this.vars = null;\n // drop references to internal big arrays for the GC\n this._positions = null;\n this._indices = null;\n this._normals = null;\n this._uvs = null;\n this._colors = null;\n this._indices32 = null;\n this._positions32 = null;\n this._normals32 = null;\n this._fixedNormal32 = null;\n this._uvs32 = null;\n this._colors32 = null;\n this.pickedParticles = null;\n this.pickedBySubMesh = null;\n this._materials = null;\n this._materialIndexes = null;\n this._indicesByMaterial = null;\n this._idxOfId = null;\n }\n /** Returns an object {idx: number faceId: number} for the picked particle from the passed pickingInfo object.\n * idx is the particle index in the SPS\n * faceId is the picked face index counted within this particle.\n * Returns null if the pickInfo can't identify a picked particle.\n * @param pickingInfo (PickingInfo object)\n * @returns {idx: number, faceId: number} or null\n */\n pickedParticle(pickingInfo) {\n if (pickingInfo.hit) {\n const subMesh = pickingInfo.subMeshId;\n const faceId = pickingInfo.faceId - this.mesh.subMeshes[subMesh].indexStart / 3;\n const picked = this.pickedBySubMesh;\n if (picked[subMesh] && picked[subMesh][faceId]) {\n return picked[subMesh][faceId];\n }\n }\n return null;\n }\n /**\n * Returns a SolidParticle object from its identifier : particle.id\n * @param id (integer) the particle Id\n * @returns the searched particle or null if not found in the SPS.\n */\n getParticleById(id) {\n const p = this.particles[id];\n if (p && p.id == id) {\n return p;\n }\n const particles = this.particles;\n const idx = this._idxOfId[id];\n if (idx !== undefined) {\n return particles[idx];\n }\n let i = 0;\n const nb = this.nbParticles;\n while (i < nb) {\n const particle = particles[i];\n if (particle.id == id) {\n return particle;\n }\n i++;\n }\n return null;\n }\n /**\n * Returns a new array populated with the particles having the passed shapeId.\n * @param shapeId (integer) the shape identifier\n * @returns a new solid particle array\n */\n getParticlesByShapeId(shapeId) {\n const ref = [];\n this.getParticlesByShapeIdToRef(shapeId, ref);\n return ref;\n }\n /**\n * Populates the passed array \"ref\" with the particles having the passed shapeId.\n * @param shapeId the shape identifier\n * @returns the SPS\n * @param ref\n */\n getParticlesByShapeIdToRef(shapeId, ref) {\n ref.length = 0;\n for (let i = 0; i < this.nbParticles; i++) {\n const p = this.particles[i];\n if (p.shapeId == shapeId) {\n ref.push(p);\n }\n }\n return this;\n }\n /**\n * Computes the required SubMeshes according the materials assigned to the particles.\n * @returns the solid particle system.\n * Does nothing if called before the SPS mesh is built.\n */\n computeSubMeshes() {\n if (!this.mesh || !this._multimaterialEnabled) {\n return this;\n }\n const depthSortedParticles = this.depthSortedParticles;\n if (this.particles.length > 0) {\n for (let p = 0; p < this.particles.length; p++) {\n const part = this.particles[p];\n if (!part.materialIndex) {\n part.materialIndex = 0;\n }\n const sortedPart = depthSortedParticles[p];\n sortedPart.materialIndex = part.materialIndex;\n sortedPart.ind = part._ind;\n sortedPart.indicesLength = part._model._indicesLength;\n sortedPart.idx = part.idx;\n }\n }\n this._sortParticlesByMaterial();\n const indicesByMaterial = this._indicesByMaterial;\n const materialIndexes = this._materialIndexes;\n const mesh = this.mesh;\n mesh.subMeshes = [];\n const vcount = mesh.getTotalVertices();\n for (let m = 0; m < materialIndexes.length; m++) {\n const start = indicesByMaterial[m];\n const count = indicesByMaterial[m + 1] - start;\n const matIndex = materialIndexes[m];\n new SubMesh(matIndex, 0, vcount, start, count, mesh);\n }\n return this;\n }\n /**\n * Sorts the solid particles by material when MultiMaterial is enabled.\n * Updates the indices32 array.\n * Updates the indicesByMaterial array.\n * Updates the mesh indices array.\n * @returns the SPS\n * @internal\n */\n _sortParticlesByMaterial() {\n const indicesByMaterial = [0];\n this._indicesByMaterial = indicesByMaterial;\n const materialIndexes = [];\n this._materialIndexes = materialIndexes;\n const depthSortedParticles = this.depthSortedParticles;\n depthSortedParticles.sort(this._materialSortFunction);\n const length = depthSortedParticles.length;\n const indices32 = this._indices32;\n const indices = this._indices;\n let subMeshIndex = 0;\n let subMeshFaceId = 0;\n let sid = 0;\n let lastMatIndex = depthSortedParticles[0].materialIndex;\n materialIndexes.push(lastMatIndex);\n if (this._pickable) {\n this.pickedBySubMesh = [[]];\n this.pickedParticles = this.pickedBySubMesh[0];\n }\n for (let sorted = 0; sorted < length; sorted++) {\n const sortedPart = depthSortedParticles[sorted];\n const lind = sortedPart.indicesLength;\n const sind = sortedPart.ind;\n if (sortedPart.materialIndex !== lastMatIndex) {\n lastMatIndex = sortedPart.materialIndex;\n indicesByMaterial.push(sid);\n materialIndexes.push(lastMatIndex);\n if (this._pickable) {\n subMeshIndex++;\n this.pickedBySubMesh[subMeshIndex] = [];\n subMeshFaceId = 0;\n }\n }\n let faceId = 0;\n for (let i = 0; i < lind; i++) {\n indices32[sid] = indices[sind + i];\n if (this._pickable) {\n const f = i % 3;\n if (f == 0) {\n const pickedData = this.pickedBySubMesh[subMeshIndex][subMeshFaceId];\n if (pickedData) {\n pickedData.idx = sortedPart.idx;\n pickedData.faceId = faceId;\n }\n else {\n this.pickedBySubMesh[subMeshIndex][subMeshFaceId] = { idx: sortedPart.idx, faceId: faceId };\n }\n subMeshFaceId++;\n faceId++;\n }\n }\n sid++;\n }\n }\n indicesByMaterial.push(indices32.length); // add the last number to ease the indices start/count values for subMeshes creation\n if (this._updatable) {\n this.mesh.updateIndices(indices32);\n }\n return this;\n }\n /**\n * Sets the material indexes by id materialIndexesById[id] = materialIndex\n * @internal\n */\n _setMaterialIndexesById() {\n this._materialIndexesById = {};\n for (let i = 0; i < this._materials.length; i++) {\n const id = this._materials[i].uniqueId;\n this._materialIndexesById[id] = i;\n }\n }\n /**\n * Returns an array with unique values of Materials from the passed array\n * @param array the material array to be checked and filtered\n * @internal\n */\n _filterUniqueMaterialId(array) {\n const filtered = array.filter(function (value, index, self) {\n return self.indexOf(value) === index;\n });\n return filtered;\n }\n /**\n * Sets a new Standard Material as _defaultMaterial if not already set.\n * @internal\n */\n _setDefaultMaterial() {\n if (!this._defaultMaterial) {\n this._defaultMaterial = new StandardMaterial(this.name + \"DefaultMaterial\", this._scene);\n }\n return this._defaultMaterial;\n }\n /**\n * Visibility helper : Recomputes the visible size according to the mesh bounding box\n * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/sps_visibility\n * @returns the SPS.\n */\n refreshVisibleSize() {\n if (!this._isVisibilityBoxLocked) {\n this.mesh.refreshBoundingInfo();\n }\n return this;\n }\n /**\n * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.\n * @param size the size (float) of the visibility box\n * note : this doesn't lock the SPS mesh bounding box.\n * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/sps_visibility\n */\n setVisibilityBox(size) {\n const vis = size / 2;\n this.mesh.buildBoundingInfo(new Vector3(-vis, -vis, -vis), new Vector3(vis, vis, vis));\n }\n /**\n * Gets whether the SPS as always visible or not\n * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/sps_visibility\n */\n get isAlwaysVisible() {\n return this._alwaysVisible;\n }\n /**\n * Sets the SPS as always visible or not\n * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/sps_visibility\n */\n set isAlwaysVisible(val) {\n this._alwaysVisible = val;\n this.mesh.alwaysSelectAsActiveMesh = val;\n }\n /**\n * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.\n * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/sps_visibility\n */\n set isVisibilityBoxLocked(val) {\n this._isVisibilityBoxLocked = val;\n const boundingInfo = this.mesh.getBoundingInfo();\n boundingInfo.isLocked = val;\n }\n /**\n * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.\n * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/sps_visibility\n */\n get isVisibilityBoxLocked() {\n return this._isVisibilityBoxLocked;\n }\n /**\n * Tells to `setParticles()` to compute the particle rotations or not.\n * Default value : true. The SPS is faster when it's set to false.\n * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.\n */\n set computeParticleRotation(val) {\n this._computeParticleRotation = val;\n }\n /**\n * Tells to `setParticles()` to compute the particle colors or not.\n * Default value : true. The SPS is faster when it's set to false.\n * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.\n */\n set computeParticleColor(val) {\n this._computeParticleColor = val;\n }\n set computeParticleTexture(val) {\n this._computeParticleTexture = val;\n }\n /**\n * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.\n * Default value : false. The SPS is faster when it's set to false.\n * Note : the particle custom vertex positions aren't stored values.\n */\n set computeParticleVertex(val) {\n this._computeParticleVertex = val;\n }\n /**\n * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.\n */\n set computeBoundingBox(val) {\n this._computeBoundingBox = val;\n }\n /**\n * Tells to `setParticles()` to sort or not the distance between each particle and the camera.\n * Skipped when `enableDepthSort` is set to `false` (default) at construction time.\n * Default : `true`\n */\n set depthSortParticles(val) {\n this._depthSortParticles = val;\n }\n /**\n * Gets if `setParticles()` computes the particle rotations or not.\n * Default value : true. The SPS is faster when it's set to false.\n * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.\n */\n get computeParticleRotation() {\n return this._computeParticleRotation;\n }\n /**\n * Gets if `setParticles()` computes the particle colors or not.\n * Default value : true. The SPS is faster when it's set to false.\n * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.\n */\n get computeParticleColor() {\n return this._computeParticleColor;\n }\n /**\n * Gets if `setParticles()` computes the particle textures or not.\n * Default value : true. The SPS is faster when it's set to false.\n * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.\n */\n get computeParticleTexture() {\n return this._computeParticleTexture;\n }\n /**\n * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.\n * Default value : false. The SPS is faster when it's set to false.\n * Note : the particle custom vertex positions aren't stored values.\n */\n get computeParticleVertex() {\n return this._computeParticleVertex;\n }\n /**\n * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.\n */\n get computeBoundingBox() {\n return this._computeBoundingBox;\n }\n /**\n * Gets if `setParticles()` sorts or not the distance between each particle and the camera.\n * Skipped when `enableDepthSort` is set to `false` (default) at construction time.\n * Default : `true`\n */\n get depthSortParticles() {\n return this._depthSortParticles;\n }\n /**\n * Gets if the SPS is created as expandable at construction time.\n * Default : `false`\n */\n get expandable() {\n return this._expandable;\n }\n /**\n * Gets if the SPS supports the Multi Materials\n */\n get multimaterialEnabled() {\n return this._multimaterialEnabled;\n }\n /**\n * Gets if the SPS uses the model materials for its own multimaterial.\n */\n get useModelMaterial() {\n return this._useModelMaterial;\n }\n /**\n * The SPS used material array.\n */\n get materials() {\n return this._materials;\n }\n /**\n * Sets the SPS MultiMaterial from the passed materials.\n * Note : the passed array is internally copied and not used then by reference.\n * @param materials an array of material objects. This array indexes are the materialIndex values of the particles.\n */\n setMultiMaterial(materials) {\n this._materials = this._filterUniqueMaterialId(materials);\n this._setMaterialIndexesById();\n if (this._multimaterial) {\n this._multimaterial.dispose();\n }\n this._multimaterial = new MultiMaterial(this.name + \"MultiMaterial\", this._scene);\n for (let m = 0; m < this._materials.length; m++) {\n this._multimaterial.subMaterials.push(this._materials[m]);\n }\n this.computeSubMeshes();\n this.mesh.material = this._multimaterial;\n }\n /**\n * The SPS computed multimaterial object\n */\n get multimaterial() {\n return this._multimaterial;\n }\n set multimaterial(mm) {\n this._multimaterial = mm;\n }\n /**\n * If the subMeshes must be updated on the next call to setParticles()\n */\n get autoUpdateSubMeshes() {\n return this._autoUpdateSubMeshes;\n }\n set autoUpdateSubMeshes(val) {\n this._autoUpdateSubMeshes = val;\n }\n // =======================================================================\n // Particle behavior logic\n // these following methods may be overwritten by the user to fit his needs\n /**\n * This function does nothing. It may be overwritten to set all the particle first values.\n * The SPS doesn't call this function, you may have to call it by your own.\n * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/manage_sps_particles\n */\n initParticles() { }\n /**\n * This function does nothing. It may be overwritten to recycle a particle.\n * The SPS doesn't call this function, you may have to call it by your own.\n * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/manage_sps_particles\n * @param particle The particle to recycle\n * @returns the recycled particle\n */\n recycleParticle(particle) {\n return particle;\n }\n /**\n * Updates a particle : this function should be overwritten by the user.\n * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.\n * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/manage_sps_particles\n * @example : just set a particle position or velocity and recycle conditions\n * @param particle The particle to update\n * @returns the updated particle\n */\n updateParticle(particle) {\n return particle;\n }\n /**\n * Updates a vertex of a particle : it can be overwritten by the user.\n * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.\n * @param particle the current particle\n * @param vertex the current vertex of the current particle : a SolidParticleVertex object\n * @param pt the index of the current vertex in the particle shape\n * doc : https://doc.babylonjs.com/features/featuresDeepDive/particles/solid_particle_system/sps_vertices\n * @example : just set a vertex particle position or color\n * @returns the sps\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n updateParticleVertex(particle, vertex, pt) {\n return this;\n }\n /**\n * This will be called before any other treatment by `setParticles()` and will be passed three parameters.\n * This does nothing and may be overwritten by the user.\n * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()\n * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()\n * @param update the boolean update value actually passed to setParticles()\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n beforeUpdateParticles(start, stop, update) { }\n /**\n * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.\n * This will be passed three parameters.\n * This does nothing and may be overwritten by the user.\n * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()\n * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()\n * @param update the boolean update value actually passed to setParticles()\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n afterUpdateParticles(start, stop, update) { }\n}\n//# sourceMappingURL=solidParticleSystem.js.map","import { Color4, Vector2, Vector3, TmpVectors, Quaternion } from \"../Maths/math.js\";\n/**\n * Represents one particle of a points cloud system.\n */\nexport class CloudPoint {\n /**\n * Creates a Point Cloud object.\n * Don't create particles manually, use instead the PCS internal tools like _addParticle()\n * @param particleIndex (integer) is the particle index in the PCS pool. It's also the particle identifier.\n * @param group (PointsGroup) is the group the particle belongs to\n * @param groupId (integer) is the group identifier in the PCS.\n * @param idxInGroup (integer) is the index of the particle in the current point group (ex: the 10th point of addPoints(30))\n * @param pcs defines the PCS it is associated to\n */\n constructor(particleIndex, group, groupId, idxInGroup, pcs) {\n /**\n * particle global index\n */\n this.idx = 0;\n /**\n * The color of the particle\n */\n this.color = new Color4(1.0, 1.0, 1.0, 1.0);\n /**\n * The world space position of the particle.\n */\n this.position = Vector3.Zero();\n /**\n * The world space rotation of the particle. (Not use if rotationQuaternion is set)\n */\n this.rotation = Vector3.Zero();\n /**\n * The uv of the particle.\n */\n this.uv = new Vector2(0.0, 0.0);\n /**\n * The current speed of the particle.\n */\n this.velocity = Vector3.Zero();\n /**\n * The pivot point in the particle local space.\n */\n this.pivot = Vector3.Zero();\n /**\n * Must the particle be translated from its pivot point in its local space ?\n * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.\n * Default : false\n */\n this.translateFromPivot = false;\n /**\n * Index of this particle in the global \"positions\" array (Internal use)\n * @internal\n */\n this._pos = 0;\n /**\n * @internal Index of this particle in the global \"indices\" array (Internal use)\n */\n this._ind = 0;\n /**\n * Group id of this particle\n */\n this.groupId = 0;\n /**\n * Index of the particle in its group id (Internal use)\n */\n this.idxInGroup = 0;\n /**\n * @internal Still set as invisible in order to skip useless computations (Internal use)\n */\n this._stillInvisible = false;\n /**\n * @internal Last computed particle rotation matrix\n */\n this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];\n /**\n * Parent particle Id, if any.\n * Default null.\n */\n this.parentId = null;\n /**\n * @internal Internal global position in the PCS.\n */\n this._globalPosition = Vector3.Zero();\n this.idx = particleIndex;\n this._group = group;\n this.groupId = groupId;\n this.idxInGroup = idxInGroup;\n this._pcs = pcs;\n }\n /**\n * get point size\n */\n get size() {\n return this.size;\n }\n /**\n * Set point size\n */\n set size(scale) {\n this.size = scale;\n }\n /**\n * Legacy support, changed quaternion to rotationQuaternion\n */\n get quaternion() {\n return this.rotationQuaternion;\n }\n /**\n * Legacy support, changed quaternion to rotationQuaternion\n */\n set quaternion(q) {\n this.rotationQuaternion = q;\n }\n /**\n * Returns a boolean. True if the particle intersects a mesh, else false\n * The intersection is computed on the particle position and Axis Aligned Bounding Box (AABB) or Sphere\n * @param target is the object (point or mesh) what the intersection is computed against\n * @param isSphere is boolean flag when false (default) bounding box of mesh is used, when true the bounding sphere is used\n * @returns true if it intersects\n */\n intersectsMesh(target, isSphere) {\n if (!target.hasBoundingInfo) {\n return false;\n }\n if (!this._pcs.mesh) {\n throw new Error(\"Point Cloud System doesnt contain the Mesh\");\n }\n if (isSphere) {\n return target.getBoundingInfo().boundingSphere.intersectsPoint(this.position.add(this._pcs.mesh.position));\n }\n const bbox = target.getBoundingInfo().boundingBox;\n const maxX = bbox.maximumWorld.x;\n const minX = bbox.minimumWorld.x;\n const maxY = bbox.maximumWorld.y;\n const minY = bbox.minimumWorld.y;\n const maxZ = bbox.maximumWorld.z;\n const minZ = bbox.minimumWorld.z;\n const x = this.position.x + this._pcs.mesh.position.x;\n const y = this.position.y + this._pcs.mesh.position.y;\n const z = this.position.z + this._pcs.mesh.position.z;\n return minX <= x && x <= maxX && minY <= y && y <= maxY && minZ <= z && z <= maxZ;\n }\n /**\n * get the rotation matrix of the particle\n * @internal\n */\n getRotationMatrix(m) {\n let quaternion;\n if (this.rotationQuaternion) {\n quaternion = this.rotationQuaternion;\n }\n else {\n quaternion = TmpVectors.Quaternion[0];\n const rotation = this.rotation;\n Quaternion.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, quaternion);\n }\n quaternion.toRotationMatrix(m);\n }\n}\n/**\n * Represents a group of points in a points cloud system\n * * PCS internal tool, don't use it manually.\n */\nexport class PointsGroup {\n /**\n * Get or set the groupId\n * @deprecated Please use groupId instead\n */\n get groupID() {\n return this.groupId;\n }\n set groupID(groupID) {\n this.groupId = groupID;\n }\n /**\n * Creates a points group object. This is an internal reference to produce particles for the PCS.\n * PCS internal tool, don't use it manually.\n * @internal\n */\n constructor(id, posFunction) {\n this.groupId = id;\n this._positionFunction = posFunction;\n }\n}\n//# sourceMappingURL=cloudPoint.js.map","import { Color4, Color3 } from \"../Maths/math.js\";\nimport { Vector2, Vector3, Vector4, TmpVectors, Matrix } from \"../Maths/math.vector.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { VertexData } from \"../Meshes/mesh.vertexData.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { CloudPoint, PointsGroup } from \"./cloudPoint.js\";\nimport { Ray } from \"../Culling/ray.js\";\nimport { StandardMaterial } from \"../Materials/standardMaterial.js\";\nimport { BaseTexture } from \"./../Materials/Textures/baseTexture.js\";\nimport { Scalar } from \"../Maths/math.scalar.js\";\n/** Defines the 4 color options */\nexport var PointColor;\n(function (PointColor) {\n /** color value */\n PointColor[PointColor[\"Color\"] = 2] = \"Color\";\n /** uv value */\n PointColor[PointColor[\"UV\"] = 1] = \"UV\";\n /** random value */\n PointColor[PointColor[\"Random\"] = 0] = \"Random\";\n /** stated value */\n PointColor[PointColor[\"Stated\"] = 3] = \"Stated\";\n})(PointColor || (PointColor = {}));\n/**\n * The PointCloudSystem (PCS) is a single updatable mesh. The points corresponding to the vertices of this big mesh.\n * As it is just a mesh, the PointCloudSystem has all the same properties as any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc.\n\n * The PointCloudSystem is also a particle system, with each point being a particle. It provides some methods to manage the particles.\n * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.\n *\n * Full documentation here : TO BE ENTERED\n */\nexport class PointsCloudSystem {\n /**\n * Gets the particle positions computed by the Point Cloud System\n */\n get positions() {\n return this._positions32;\n }\n /**\n * Gets the particle colors computed by the Point Cloud System\n */\n get colors() {\n return this._colors32;\n }\n /**\n * Gets the particle uvs computed by the Point Cloud System\n */\n get uvs() {\n return this._uvs32;\n }\n /**\n * Creates a PCS (Points Cloud System) object\n * @param name (String) is the PCS name, this will be the underlying mesh name\n * @param pointSize (number) is the size for each point. Has no effect on a WebGPU engine.\n * @param scene (Scene) is the scene in which the PCS is added\n * @param options defines the options of the PCS e.g.\n * * updatable (optional boolean, default true) : if the PCS must be updatable or immutable\n * @param options.updatable\n */\n constructor(name, pointSize, scene, options) {\n /**\n * The PCS array of cloud point objects. Just access each particle as with any classic array.\n * Example : var p = SPS.particles[i];\n */\n this.particles = new Array();\n /**\n * The PCS total number of particles. Read only. Use PCS.counter instead if you need to set your own value.\n */\n this.nbParticles = 0;\n /**\n * This a counter for your own usage. It's not set by any SPS functions.\n */\n this.counter = 0;\n /**\n * This empty object is intended to store some PCS specific or temporary values in order to lower the Garbage Collector activity.\n * Please read :\n */\n this.vars = {};\n this._promises = [];\n this._positions = new Array();\n this._indices = new Array();\n this._normals = new Array();\n this._colors = new Array();\n this._uvs = new Array();\n this._updatable = true;\n this._isVisibilityBoxLocked = false;\n this._alwaysVisible = false;\n this._groups = new Array(); //start indices for each group of particles\n this._groupCounter = 0;\n this._computeParticleColor = true;\n this._computeParticleTexture = true;\n this._computeParticleRotation = true;\n this._computeBoundingBox = false;\n this._isReady = false;\n this.name = name;\n this._size = pointSize;\n this._scene = scene || EngineStore.LastCreatedScene;\n if (options && options.updatable !== undefined) {\n this._updatable = options.updatable;\n }\n else {\n this._updatable = true;\n }\n }\n /**\n * Builds the PCS underlying mesh. Returns a standard Mesh.\n * If no points were added to the PCS, the returned mesh is just a single point.\n * @param material The material to use to render the mesh. If not provided, will create a default one\n * @returns a promise for the created mesh\n */\n buildMeshAsync(material) {\n return Promise.all(this._promises).then(() => {\n this._isReady = true;\n return this._buildMesh(material);\n });\n }\n /**\n * @internal\n */\n _buildMesh(material) {\n if (this.nbParticles === 0) {\n this.addPoints(1);\n }\n this._positions32 = new Float32Array(this._positions);\n this._uvs32 = new Float32Array(this._uvs);\n this._colors32 = new Float32Array(this._colors);\n const vertexData = new VertexData();\n vertexData.set(this._positions32, VertexBuffer.PositionKind);\n if (this._uvs32.length > 0) {\n vertexData.set(this._uvs32, VertexBuffer.UVKind);\n }\n let ec = 0; //emissive color value 0 for UVs, 1 for color\n if (this._colors32.length > 0) {\n ec = 1;\n vertexData.set(this._colors32, VertexBuffer.ColorKind);\n }\n const mesh = new Mesh(this.name, this._scene);\n vertexData.applyToMesh(mesh, this._updatable);\n this.mesh = mesh;\n // free memory\n this._positions = null;\n this._uvs = null;\n this._colors = null;\n if (!this._updatable) {\n this.particles.length = 0;\n }\n let mat = material;\n if (!mat) {\n mat = new StandardMaterial(\"point cloud material\", this._scene);\n mat.emissiveColor = new Color3(ec, ec, ec);\n mat.disableLighting = true;\n mat.pointsCloud = true;\n mat.pointSize = this._size;\n }\n mesh.material = mat;\n return new Promise((resolve) => resolve(mesh));\n }\n // adds a new particle object in the particles array\n _addParticle(idx, group, groupId, idxInGroup) {\n const cp = new CloudPoint(idx, group, groupId, idxInGroup, this);\n this.particles.push(cp);\n return cp;\n }\n _randomUnitVector(particle) {\n particle.position = new Vector3(Math.random(), Math.random(), Math.random());\n particle.color = new Color4(1, 1, 1, 1);\n }\n _getColorIndicesForCoord(pointsGroup, x, y, width) {\n const imageData = pointsGroup._groupImageData;\n const color = y * (width * 4) + x * 4;\n const colorIndices = [color, color + 1, color + 2, color + 3];\n const redIndex = colorIndices[0];\n const greenIndex = colorIndices[1];\n const blueIndex = colorIndices[2];\n const alphaIndex = colorIndices[3];\n const redForCoord = imageData[redIndex];\n const greenForCoord = imageData[greenIndex];\n const blueForCoord = imageData[blueIndex];\n const alphaForCoord = imageData[alphaIndex];\n return new Color4(redForCoord / 255, greenForCoord / 255, blueForCoord / 255, alphaForCoord);\n }\n _setPointsColorOrUV(mesh, pointsGroup, isVolume, colorFromTexture, hasTexture, color, range) {\n if (isVolume) {\n mesh.updateFacetData();\n }\n const boundInfo = mesh.getBoundingInfo();\n const diameter = 2 * boundInfo.boundingSphere.radius;\n let meshPos = mesh.getVerticesData(VertexBuffer.PositionKind);\n const meshInd = mesh.getIndices();\n const meshUV = mesh.getVerticesData(VertexBuffer.UVKind);\n const meshCol = mesh.getVerticesData(VertexBuffer.ColorKind);\n const place = Vector3.Zero();\n mesh.computeWorldMatrix();\n const meshMatrix = mesh.getWorldMatrix();\n if (!meshMatrix.isIdentity()) {\n meshPos = meshPos.slice(0);\n for (let p = 0; p < meshPos.length / 3; p++) {\n Vector3.TransformCoordinatesFromFloatsToRef(meshPos[3 * p], meshPos[3 * p + 1], meshPos[3 * p + 2], meshMatrix, place);\n meshPos[3 * p] = place.x;\n meshPos[3 * p + 1] = place.y;\n meshPos[3 * p + 2] = place.z;\n }\n }\n let idxPoints = 0;\n let id0 = 0;\n let id1 = 0;\n let id2 = 0;\n let v0X = 0;\n let v0Y = 0;\n let v0Z = 0;\n let v1X = 0;\n let v1Y = 0;\n let v1Z = 0;\n let v2X = 0;\n let v2Y = 0;\n let v2Z = 0;\n const vertex0 = Vector3.Zero();\n const vertex1 = Vector3.Zero();\n const vertex2 = Vector3.Zero();\n const vec0 = Vector3.Zero();\n const vec1 = Vector3.Zero();\n let uv0X = 0;\n let uv0Y = 0;\n let uv1X = 0;\n let uv1Y = 0;\n let uv2X = 0;\n let uv2Y = 0;\n const uv0 = Vector2.Zero();\n const uv1 = Vector2.Zero();\n const uv2 = Vector2.Zero();\n const uvec0 = Vector2.Zero();\n const uvec1 = Vector2.Zero();\n let col0X = 0;\n let col0Y = 0;\n let col0Z = 0;\n let col0A = 0;\n let col1X = 0;\n let col1Y = 0;\n let col1Z = 0;\n let col1A = 0;\n let col2X = 0;\n let col2Y = 0;\n let col2Z = 0;\n let col2A = 0;\n const col0 = Vector4.Zero();\n const col1 = Vector4.Zero();\n const col2 = Vector4.Zero();\n const colvec0 = Vector4.Zero();\n const colvec1 = Vector4.Zero();\n let lamda = 0;\n let mu = 0;\n range = range ? range : 0;\n let facetPoint;\n let uvPoint;\n let colPoint = new Vector4(0, 0, 0, 0);\n let norm = Vector3.Zero();\n let tang = Vector3.Zero();\n let biNorm = Vector3.Zero();\n let angle = 0;\n let facetPlaneVec = Vector3.Zero();\n let gap = 0;\n let distance = 0;\n const ray = new Ray(Vector3.Zero(), new Vector3(1, 0, 0));\n let pickInfo;\n let direction = Vector3.Zero();\n for (let index = 0; index < meshInd.length / 3; index++) {\n id0 = meshInd[3 * index];\n id1 = meshInd[3 * index + 1];\n id2 = meshInd[3 * index + 2];\n v0X = meshPos[3 * id0];\n v0Y = meshPos[3 * id0 + 1];\n v0Z = meshPos[3 * id0 + 2];\n v1X = meshPos[3 * id1];\n v1Y = meshPos[3 * id1 + 1];\n v1Z = meshPos[3 * id1 + 2];\n v2X = meshPos[3 * id2];\n v2Y = meshPos[3 * id2 + 1];\n v2Z = meshPos[3 * id2 + 2];\n vertex0.set(v0X, v0Y, v0Z);\n vertex1.set(v1X, v1Y, v1Z);\n vertex2.set(v2X, v2Y, v2Z);\n vertex1.subtractToRef(vertex0, vec0);\n vertex2.subtractToRef(vertex1, vec1);\n if (meshUV) {\n uv0X = meshUV[2 * id0];\n uv0Y = meshUV[2 * id0 + 1];\n uv1X = meshUV[2 * id1];\n uv1Y = meshUV[2 * id1 + 1];\n uv2X = meshUV[2 * id2];\n uv2Y = meshUV[2 * id2 + 1];\n uv0.set(uv0X, uv0Y);\n uv1.set(uv1X, uv1Y);\n uv2.set(uv2X, uv2Y);\n uv1.subtractToRef(uv0, uvec0);\n uv2.subtractToRef(uv1, uvec1);\n }\n if (meshCol && colorFromTexture) {\n col0X = meshCol[4 * id0];\n col0Y = meshCol[4 * id0 + 1];\n col0Z = meshCol[4 * id0 + 2];\n col0A = meshCol[4 * id0 + 3];\n col1X = meshCol[4 * id1];\n col1Y = meshCol[4 * id1 + 1];\n col1Z = meshCol[4 * id1 + 2];\n col1A = meshCol[4 * id1 + 3];\n col2X = meshCol[4 * id2];\n col2Y = meshCol[4 * id2 + 1];\n col2Z = meshCol[4 * id2 + 2];\n col2A = meshCol[4 * id2 + 3];\n col0.set(col0X, col0Y, col0Z, col0A);\n col1.set(col1X, col1Y, col1Z, col1A);\n col2.set(col2X, col2Y, col2Z, col2A);\n col1.subtractToRef(col0, colvec0);\n col2.subtractToRef(col1, colvec1);\n }\n let width;\n let height;\n let deltaS;\n let deltaV;\n let h;\n let s;\n let v;\n let hsvCol;\n const statedColor = new Color3(0, 0, 0);\n const colPoint3 = new Color3(0, 0, 0);\n let pointColors;\n let particle;\n for (let i = 0; i < pointsGroup._groupDensity[index]; i++) {\n idxPoints = this.particles.length;\n this._addParticle(idxPoints, pointsGroup, this._groupCounter, index + i);\n particle = this.particles[idxPoints];\n //form a point inside the facet v0, v1, v2;\n lamda = Scalar.RandomRange(0, 1);\n mu = Scalar.RandomRange(0, 1);\n facetPoint = vertex0.add(vec0.scale(lamda)).add(vec1.scale(lamda * mu));\n if (isVolume) {\n norm = mesh.getFacetNormal(index).normalize().scale(-1);\n tang = vec0.clone().normalize();\n biNorm = Vector3.Cross(norm, tang);\n angle = Scalar.RandomRange(0, 2 * Math.PI);\n facetPlaneVec = tang.scale(Math.cos(angle)).add(biNorm.scale(Math.sin(angle)));\n angle = Scalar.RandomRange(0.1, Math.PI / 2);\n direction = facetPlaneVec.scale(Math.cos(angle)).add(norm.scale(Math.sin(angle)));\n ray.origin = facetPoint.add(direction.scale(0.00001));\n ray.direction = direction;\n ray.length = diameter;\n pickInfo = ray.intersectsMesh(mesh);\n if (pickInfo.hit) {\n distance = pickInfo.pickedPoint.subtract(facetPoint).length();\n gap = Scalar.RandomRange(0, 1) * distance;\n facetPoint.addInPlace(direction.scale(gap));\n }\n }\n particle.position = facetPoint.clone();\n this._positions.push(particle.position.x, particle.position.y, particle.position.z);\n if (colorFromTexture !== undefined) {\n if (meshUV) {\n uvPoint = uv0.add(uvec0.scale(lamda)).add(uvec1.scale(lamda * mu));\n if (colorFromTexture) {\n //Set particle color to texture color\n if (hasTexture && pointsGroup._groupImageData !== null) {\n width = pointsGroup._groupImgWidth;\n height = pointsGroup._groupImgHeight;\n pointColors = this._getColorIndicesForCoord(pointsGroup, Math.round(uvPoint.x * width), Math.round(uvPoint.y * height), width);\n particle.color = pointColors;\n this._colors.push(pointColors.r, pointColors.g, pointColors.b, pointColors.a);\n }\n else {\n if (meshCol) {\n //failure in texture and colors available\n colPoint = col0.add(colvec0.scale(lamda)).add(colvec1.scale(lamda * mu));\n particle.color = new Color4(colPoint.x, colPoint.y, colPoint.z, colPoint.w);\n this._colors.push(colPoint.x, colPoint.y, colPoint.z, colPoint.w);\n }\n else {\n colPoint = col0.set(Math.random(), Math.random(), Math.random(), 1);\n particle.color = new Color4(colPoint.x, colPoint.y, colPoint.z, colPoint.w);\n this._colors.push(colPoint.x, colPoint.y, colPoint.z, colPoint.w);\n }\n }\n }\n else {\n //Set particle uv based on a mesh uv\n particle.uv = uvPoint.clone();\n this._uvs.push(particle.uv.x, particle.uv.y);\n }\n }\n }\n else {\n if (color) {\n statedColor.set(color.r, color.g, color.b);\n deltaS = Scalar.RandomRange(-range, range);\n deltaV = Scalar.RandomRange(-range, range);\n hsvCol = statedColor.toHSV();\n h = hsvCol.r;\n s = hsvCol.g + deltaS;\n v = hsvCol.b + deltaV;\n if (s < 0) {\n s = 0;\n }\n if (s > 1) {\n s = 1;\n }\n if (v < 0) {\n v = 0;\n }\n if (v > 1) {\n v = 1;\n }\n Color3.HSVtoRGBToRef(h, s, v, colPoint3);\n colPoint.set(colPoint3.r, colPoint3.g, colPoint3.b, 1);\n }\n else {\n colPoint = col0.set(Math.random(), Math.random(), Math.random(), 1);\n }\n particle.color = new Color4(colPoint.x, colPoint.y, colPoint.z, colPoint.w);\n this._colors.push(colPoint.x, colPoint.y, colPoint.z, colPoint.w);\n }\n }\n }\n }\n // stores mesh texture in dynamic texture for color pixel retrieval\n // when pointColor type is color for surface points\n _colorFromTexture(mesh, pointsGroup, isVolume) {\n if (mesh.material === null) {\n Logger.Warn(mesh.name + \"has no material.\");\n pointsGroup._groupImageData = null;\n this._setPointsColorOrUV(mesh, pointsGroup, isVolume, true, false);\n return;\n }\n const mat = mesh.material;\n const textureList = mat.getActiveTextures();\n if (textureList.length === 0) {\n Logger.Warn(mesh.name + \"has no usable texture.\");\n pointsGroup._groupImageData = null;\n this._setPointsColorOrUV(mesh, pointsGroup, isVolume, true, false);\n return;\n }\n const clone = mesh.clone();\n clone.setEnabled(false);\n this._promises.push(new Promise((resolve) => {\n BaseTexture.WhenAllReady(textureList, () => {\n let n = pointsGroup._textureNb;\n if (n < 0) {\n n = 0;\n }\n if (n > textureList.length - 1) {\n n = textureList.length - 1;\n }\n const finalize = () => {\n pointsGroup._groupImgWidth = textureList[n].getSize().width;\n pointsGroup._groupImgHeight = textureList[n].getSize().height;\n this._setPointsColorOrUV(clone, pointsGroup, isVolume, true, true);\n clone.dispose();\n resolve();\n };\n pointsGroup._groupImageData = null;\n const dataPromise = textureList[n].readPixels();\n if (!dataPromise) {\n finalize();\n }\n else {\n dataPromise.then((data) => {\n pointsGroup._groupImageData = data;\n finalize();\n });\n }\n });\n }));\n }\n // calculates the point density per facet of a mesh for surface points\n _calculateDensity(nbPoints, positions, indices) {\n let density = new Array();\n let id0;\n let id1;\n let id2;\n let v0X;\n let v0Y;\n let v0Z;\n let v1X;\n let v1Y;\n let v1Z;\n let v2X;\n let v2Y;\n let v2Z;\n const vertex0 = Vector3.Zero();\n const vertex1 = Vector3.Zero();\n const vertex2 = Vector3.Zero();\n const vec0 = Vector3.Zero();\n const vec1 = Vector3.Zero();\n const vec2 = Vector3.Zero();\n let a; //length of side of triangle\n let b; //length of side of triangle\n let c; //length of side of triangle\n let p; //perimeter of triangle\n let area;\n const areas = new Array();\n let surfaceArea = 0;\n const nbFacets = indices.length / 3;\n //surface area\n for (let index = 0; index < nbFacets; index++) {\n id0 = indices[3 * index];\n id1 = indices[3 * index + 1];\n id2 = indices[3 * index + 2];\n v0X = positions[3 * id0];\n v0Y = positions[3 * id0 + 1];\n v0Z = positions[3 * id0 + 2];\n v1X = positions[3 * id1];\n v1Y = positions[3 * id1 + 1];\n v1Z = positions[3 * id1 + 2];\n v2X = positions[3 * id2];\n v2Y = positions[3 * id2 + 1];\n v2Z = positions[3 * id2 + 2];\n vertex0.set(v0X, v0Y, v0Z);\n vertex1.set(v1X, v1Y, v1Z);\n vertex2.set(v2X, v2Y, v2Z);\n vertex1.subtractToRef(vertex0, vec0);\n vertex2.subtractToRef(vertex1, vec1);\n vertex2.subtractToRef(vertex0, vec2);\n a = vec0.length();\n b = vec1.length();\n c = vec2.length();\n p = (a + b + c) / 2;\n area = Math.sqrt(p * (p - a) * (p - b) * (p - c));\n surfaceArea += area;\n areas[index] = area;\n }\n let pointCount = 0;\n for (let index = 0; index < nbFacets; index++) {\n density[index] = Math.floor((nbPoints * areas[index]) / surfaceArea);\n pointCount += density[index];\n }\n const diff = nbPoints - pointCount;\n const pointsPerFacet = Math.floor(diff / nbFacets);\n const extraPoints = diff % nbFacets;\n if (pointsPerFacet > 0) {\n density = density.map((x) => x + pointsPerFacet);\n }\n for (let index = 0; index < extraPoints; index++) {\n density[index] += 1;\n }\n return density;\n }\n /**\n * Adds points to the PCS in random positions within a unit sphere\n * @param nb (positive integer) the number of particles to be created from this model\n * @param pointFunction is an optional javascript function to be called for each particle on PCS creation\n * @returns the number of groups in the system\n */\n addPoints(nb, pointFunction = this._randomUnitVector) {\n const pointsGroup = new PointsGroup(this._groupCounter, pointFunction);\n let cp;\n // particles\n let idx = this.nbParticles;\n for (let i = 0; i < nb; i++) {\n cp = this._addParticle(idx, pointsGroup, this._groupCounter, i);\n if (pointsGroup && pointsGroup._positionFunction) {\n pointsGroup._positionFunction(cp, idx, i);\n }\n this._positions.push(cp.position.x, cp.position.y, cp.position.z);\n if (cp.color) {\n this._colors.push(cp.color.r, cp.color.g, cp.color.b, cp.color.a);\n }\n if (cp.uv) {\n this._uvs.push(cp.uv.x, cp.uv.y);\n }\n idx++;\n }\n this.nbParticles += nb;\n this._groupCounter++;\n return this._groupCounter;\n }\n /**\n * Adds points to the PCS from the surface of the model shape\n * @param mesh is any Mesh object that will be used as a surface model for the points\n * @param nb (positive integer) the number of particles to be created from this model\n * @param colorWith determines whether a point is colored using color (default), uv, random, stated or none (invisible)\n * @param color (color4) to be used when colorWith is stated or color (number) when used to specify texture position\n * @param range (number from 0 to 1) to determine the variation in shape and tone for a stated color\n * @returns the number of groups in the system\n */\n addSurfacePoints(mesh, nb, colorWith, color, range) {\n let colored = colorWith ? colorWith : PointColor.Random;\n if (isNaN(colored) || colored < 0 || colored > 3) {\n colored = PointColor.Random;\n }\n const meshPos = mesh.getVerticesData(VertexBuffer.PositionKind);\n const meshInd = mesh.getIndices();\n this._groups.push(this._groupCounter);\n const pointsGroup = new PointsGroup(this._groupCounter, null);\n pointsGroup._groupDensity = this._calculateDensity(nb, meshPos, meshInd);\n if (colored === PointColor.Color) {\n pointsGroup._textureNb = color ? color : 0;\n }\n else {\n color = color ? color : new Color4(1, 1, 1, 1);\n }\n switch (colored) {\n case PointColor.Color:\n this._colorFromTexture(mesh, pointsGroup, false);\n break;\n case PointColor.UV:\n this._setPointsColorOrUV(mesh, pointsGroup, false, false, false);\n break;\n case PointColor.Random:\n this._setPointsColorOrUV(mesh, pointsGroup, false);\n break;\n case PointColor.Stated:\n this._setPointsColorOrUV(mesh, pointsGroup, false, undefined, undefined, color, range);\n break;\n }\n this.nbParticles += nb;\n this._groupCounter++;\n return this._groupCounter - 1;\n }\n /**\n * Adds points to the PCS inside the model shape\n * @param mesh is any Mesh object that will be used as a surface model for the points\n * @param nb (positive integer) the number of particles to be created from this model\n * @param colorWith determines whether a point is colored using color (default), uv, random, stated or none (invisible)\n * @param color (color4) to be used when colorWith is stated or color (number) when used to specify texture position\n * @param range (number from 0 to 1) to determine the variation in shape and tone for a stated color\n * @returns the number of groups in the system\n */\n addVolumePoints(mesh, nb, colorWith, color, range) {\n let colored = colorWith ? colorWith : PointColor.Random;\n if (isNaN(colored) || colored < 0 || colored > 3) {\n colored = PointColor.Random;\n }\n const meshPos = mesh.getVerticesData(VertexBuffer.PositionKind);\n const meshInd = mesh.getIndices();\n this._groups.push(this._groupCounter);\n const pointsGroup = new PointsGroup(this._groupCounter, null);\n pointsGroup._groupDensity = this._calculateDensity(nb, meshPos, meshInd);\n if (colored === PointColor.Color) {\n pointsGroup._textureNb = color ? color : 0;\n }\n else {\n color = color ? color : new Color4(1, 1, 1, 1);\n }\n switch (colored) {\n case PointColor.Color:\n this._colorFromTexture(mesh, pointsGroup, true);\n break;\n case PointColor.UV:\n this._setPointsColorOrUV(mesh, pointsGroup, true, false, false);\n break;\n case PointColor.Random:\n this._setPointsColorOrUV(mesh, pointsGroup, true);\n break;\n case PointColor.Stated:\n this._setPointsColorOrUV(mesh, pointsGroup, true, undefined, undefined, color, range);\n break;\n }\n this.nbParticles += nb;\n this._groupCounter++;\n return this._groupCounter - 1;\n }\n /**\n * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.\n * This method calls `updateParticle()` for each particle of the SPS.\n * For an animated SPS, it is usually called within the render loop.\n * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_\n * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_\n * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_\n * @returns the PCS.\n */\n setParticles(start = 0, end = this.nbParticles - 1, update = true) {\n var _a, _b;\n if (!this._updatable || !this._isReady) {\n return this;\n }\n // custom beforeUpdate\n this.beforeUpdateParticles(start, end, update);\n const rotMatrix = TmpVectors.Matrix[0];\n const mesh = this.mesh;\n const colors32 = this._colors32;\n const positions32 = this._positions32;\n const uvs32 = this._uvs32;\n const tempVectors = TmpVectors.Vector3;\n const camAxisX = tempVectors[5].copyFromFloats(1.0, 0.0, 0.0);\n const camAxisY = tempVectors[6].copyFromFloats(0.0, 1.0, 0.0);\n const camAxisZ = tempVectors[7].copyFromFloats(0.0, 0.0, 1.0);\n const minimum = tempVectors[8].setAll(Number.MAX_VALUE);\n const maximum = tempVectors[9].setAll(-Number.MAX_VALUE);\n Matrix.IdentityToRef(rotMatrix);\n let idx = 0; // current index of the particle\n if ((_a = this.mesh) === null || _a === void 0 ? void 0 : _a.isFacetDataEnabled) {\n this._computeBoundingBox = true;\n }\n end = end >= this.nbParticles ? this.nbParticles - 1 : end;\n if (this._computeBoundingBox) {\n if (start != 0 || end != this.nbParticles - 1) {\n // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.\n const boundingInfo = (_b = this.mesh) === null || _b === void 0 ? void 0 : _b.getBoundingInfo();\n if (boundingInfo) {\n minimum.copyFrom(boundingInfo.minimum);\n maximum.copyFrom(boundingInfo.maximum);\n }\n }\n }\n idx = 0; // particle index\n let pindex = 0; //index in positions array\n let cindex = 0; //index in color array\n let uindex = 0; //index in uv array\n // particle loop\n for (let p = start; p <= end; p++) {\n const particle = this.particles[p];\n idx = particle.idx;\n pindex = 3 * idx;\n cindex = 4 * idx;\n uindex = 2 * idx;\n // call to custom user function to update the particle properties\n this.updateParticle(particle);\n const particleRotationMatrix = particle._rotationMatrix;\n const particlePosition = particle.position;\n const particleGlobalPosition = particle._globalPosition;\n if (this._computeParticleRotation) {\n particle.getRotationMatrix(rotMatrix);\n }\n const particleHasParent = particle.parentId !== null;\n if (particleHasParent) {\n const parent = this.particles[particle.parentId];\n const parentRotationMatrix = parent._rotationMatrix;\n const parentGlobalPosition = parent._globalPosition;\n const rotatedY = particlePosition.x * parentRotationMatrix[1] + particlePosition.y * parentRotationMatrix[4] + particlePosition.z * parentRotationMatrix[7];\n const rotatedX = particlePosition.x * parentRotationMatrix[0] + particlePosition.y * parentRotationMatrix[3] + particlePosition.z * parentRotationMatrix[6];\n const rotatedZ = particlePosition.x * parentRotationMatrix[2] + particlePosition.y * parentRotationMatrix[5] + particlePosition.z * parentRotationMatrix[8];\n particleGlobalPosition.x = parentGlobalPosition.x + rotatedX;\n particleGlobalPosition.y = parentGlobalPosition.y + rotatedY;\n particleGlobalPosition.z = parentGlobalPosition.z + rotatedZ;\n if (this._computeParticleRotation) {\n const rotMatrixValues = rotMatrix.m;\n particleRotationMatrix[0] =\n rotMatrixValues[0] * parentRotationMatrix[0] + rotMatrixValues[1] * parentRotationMatrix[3] + rotMatrixValues[2] * parentRotationMatrix[6];\n particleRotationMatrix[1] =\n rotMatrixValues[0] * parentRotationMatrix[1] + rotMatrixValues[1] * parentRotationMatrix[4] + rotMatrixValues[2] * parentRotationMatrix[7];\n particleRotationMatrix[2] =\n rotMatrixValues[0] * parentRotationMatrix[2] + rotMatrixValues[1] * parentRotationMatrix[5] + rotMatrixValues[2] * parentRotationMatrix[8];\n particleRotationMatrix[3] =\n rotMatrixValues[4] * parentRotationMatrix[0] + rotMatrixValues[5] * parentRotationMatrix[3] + rotMatrixValues[6] * parentRotationMatrix[6];\n particleRotationMatrix[4] =\n rotMatrixValues[4] * parentRotationMatrix[1] + rotMatrixValues[5] * parentRotationMatrix[4] + rotMatrixValues[6] * parentRotationMatrix[7];\n particleRotationMatrix[5] =\n rotMatrixValues[4] * parentRotationMatrix[2] + rotMatrixValues[5] * parentRotationMatrix[5] + rotMatrixValues[6] * parentRotationMatrix[8];\n particleRotationMatrix[6] =\n rotMatrixValues[8] * parentRotationMatrix[0] + rotMatrixValues[9] * parentRotationMatrix[3] + rotMatrixValues[10] * parentRotationMatrix[6];\n particleRotationMatrix[7] =\n rotMatrixValues[8] * parentRotationMatrix[1] + rotMatrixValues[9] * parentRotationMatrix[4] + rotMatrixValues[10] * parentRotationMatrix[7];\n particleRotationMatrix[8] =\n rotMatrixValues[8] * parentRotationMatrix[2] + rotMatrixValues[9] * parentRotationMatrix[5] + rotMatrixValues[10] * parentRotationMatrix[8];\n }\n }\n else {\n particleGlobalPosition.x = 0;\n particleGlobalPosition.y = 0;\n particleGlobalPosition.z = 0;\n if (this._computeParticleRotation) {\n const rotMatrixValues = rotMatrix.m;\n particleRotationMatrix[0] = rotMatrixValues[0];\n particleRotationMatrix[1] = rotMatrixValues[1];\n particleRotationMatrix[2] = rotMatrixValues[2];\n particleRotationMatrix[3] = rotMatrixValues[4];\n particleRotationMatrix[4] = rotMatrixValues[5];\n particleRotationMatrix[5] = rotMatrixValues[6];\n particleRotationMatrix[6] = rotMatrixValues[8];\n particleRotationMatrix[7] = rotMatrixValues[9];\n particleRotationMatrix[8] = rotMatrixValues[10];\n }\n }\n const pivotBackTranslation = tempVectors[11];\n if (particle.translateFromPivot) {\n pivotBackTranslation.setAll(0.0);\n }\n else {\n pivotBackTranslation.copyFrom(particle.pivot);\n }\n // positions\n const tmpVertex = tempVectors[0];\n tmpVertex.copyFrom(particle.position);\n const vertexX = tmpVertex.x - particle.pivot.x;\n const vertexY = tmpVertex.y - particle.pivot.y;\n const vertexZ = tmpVertex.z - particle.pivot.z;\n let rotatedX = vertexX * particleRotationMatrix[0] + vertexY * particleRotationMatrix[3] + vertexZ * particleRotationMatrix[6];\n let rotatedY = vertexX * particleRotationMatrix[1] + vertexY * particleRotationMatrix[4] + vertexZ * particleRotationMatrix[7];\n let rotatedZ = vertexX * particleRotationMatrix[2] + vertexY * particleRotationMatrix[5] + vertexZ * particleRotationMatrix[8];\n rotatedX += pivotBackTranslation.x;\n rotatedY += pivotBackTranslation.y;\n rotatedZ += pivotBackTranslation.z;\n const px = (positions32[pindex] = particleGlobalPosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ);\n const py = (positions32[pindex + 1] = particleGlobalPosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ);\n const pz = (positions32[pindex + 2] = particleGlobalPosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ);\n if (this._computeBoundingBox) {\n minimum.minimizeInPlaceFromFloats(px, py, pz);\n maximum.maximizeInPlaceFromFloats(px, py, pz);\n }\n if (this._computeParticleColor && particle.color) {\n const color = particle.color;\n const colors32 = this._colors32;\n colors32[cindex] = color.r;\n colors32[cindex + 1] = color.g;\n colors32[cindex + 2] = color.b;\n colors32[cindex + 3] = color.a;\n }\n if (this._computeParticleTexture && particle.uv) {\n const uv = particle.uv;\n const uvs32 = this._uvs32;\n uvs32[uindex] = uv.x;\n uvs32[uindex + 1] = uv.y;\n }\n }\n // if the VBO must be updated\n if (mesh) {\n if (update) {\n if (this._computeParticleColor) {\n mesh.updateVerticesData(VertexBuffer.ColorKind, colors32, false, false);\n }\n if (this._computeParticleTexture) {\n mesh.updateVerticesData(VertexBuffer.UVKind, uvs32, false, false);\n }\n mesh.updateVerticesData(VertexBuffer.PositionKind, positions32, false, false);\n }\n if (this._computeBoundingBox) {\n if (mesh.hasBoundingInfo) {\n mesh.getBoundingInfo().reConstruct(minimum, maximum, mesh._worldMatrix);\n }\n else {\n mesh.buildBoundingInfo(minimum, maximum, mesh._worldMatrix);\n }\n }\n }\n this.afterUpdateParticles(start, end, update);\n return this;\n }\n /**\n * Disposes the PCS.\n */\n dispose() {\n var _a;\n (_a = this.mesh) === null || _a === void 0 ? void 0 : _a.dispose();\n this.vars = null;\n // drop references to internal big arrays for the GC\n this._positions = null;\n this._indices = null;\n this._normals = null;\n this._uvs = null;\n this._colors = null;\n this._indices32 = null;\n this._positions32 = null;\n this._uvs32 = null;\n this._colors32 = null;\n }\n /**\n * Visibility helper : Recomputes the visible size according to the mesh bounding box\n * doc :\n * @returns the PCS.\n */\n refreshVisibleSize() {\n var _a;\n if (!this._isVisibilityBoxLocked) {\n (_a = this.mesh) === null || _a === void 0 ? void 0 : _a.refreshBoundingInfo();\n }\n return this;\n }\n /**\n * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.\n * @param size the size (float) of the visibility box\n * note : this doesn't lock the PCS mesh bounding box.\n * doc :\n */\n setVisibilityBox(size) {\n if (!this.mesh) {\n return;\n }\n const vis = size / 2;\n this.mesh.buildBoundingInfo(new Vector3(-vis, -vis, -vis), new Vector3(vis, vis, vis));\n }\n /**\n * Gets whether the PCS is always visible or not\n * doc :\n */\n get isAlwaysVisible() {\n return this._alwaysVisible;\n }\n /**\n * Sets the PCS as always visible or not\n * doc :\n */\n set isAlwaysVisible(val) {\n if (!this.mesh) {\n return;\n }\n this._alwaysVisible = val;\n this.mesh.alwaysSelectAsActiveMesh = val;\n }\n /**\n * Tells to `setParticles()` to compute the particle rotations or not\n * Default value : false. The PCS is faster when it's set to false\n * Note : particle rotations are only applied to parent particles\n * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate\n */\n set computeParticleRotation(val) {\n this._computeParticleRotation = val;\n }\n /**\n * Tells to `setParticles()` to compute the particle colors or not.\n * Default value : true. The PCS is faster when it's set to false.\n * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.\n */\n set computeParticleColor(val) {\n this._computeParticleColor = val;\n }\n set computeParticleTexture(val) {\n this._computeParticleTexture = val;\n }\n /**\n * Gets if `setParticles()` computes the particle colors or not.\n * Default value : false. The PCS is faster when it's set to false.\n * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.\n */\n get computeParticleColor() {\n return this._computeParticleColor;\n }\n /**\n * Gets if `setParticles()` computes the particle textures or not.\n * Default value : false. The PCS is faster when it's set to false.\n * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.\n */\n get computeParticleTexture() {\n return this._computeParticleTexture;\n }\n /**\n * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.\n */\n set computeBoundingBox(val) {\n this._computeBoundingBox = val;\n }\n /**\n * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.\n */\n get computeBoundingBox() {\n return this._computeBoundingBox;\n }\n // =======================================================================\n // Particle behavior logic\n // these following methods may be overwritten by users to fit their needs\n /**\n * This function does nothing. It may be overwritten to set all the particle first values.\n * The PCS doesn't call this function, you may have to call it by your own.\n * doc :\n */\n initParticles() { }\n /**\n * This function does nothing. It may be overwritten to recycle a particle\n * The PCS doesn't call this function, you can to call it\n * doc :\n * @param particle The particle to recycle\n * @returns the recycled particle\n */\n recycleParticle(particle) {\n return particle;\n }\n /**\n * Updates a particle : this function should be overwritten by the user.\n * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.\n * doc :\n * @example : just set a particle position or velocity and recycle conditions\n * @param particle The particle to update\n * @returns the updated particle\n */\n updateParticle(particle) {\n return particle;\n }\n /**\n * This will be called before any other treatment by `setParticles()` and will be passed three parameters.\n * This does nothing and may be overwritten by the user.\n * @param start the particle index in the particle array where to start to iterate, same than the value passed to setParticle()\n * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()\n * @param update the boolean update value actually passed to setParticles()\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n beforeUpdateParticles(start, stop, update) { }\n /**\n * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.\n * This will be passed three parameters.\n * This does nothing and may be overwritten by the user.\n * @param start the particle index in the particle array where to start to iterate, same than the value passed to setParticle()\n * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()\n * @param update the boolean update value actually passed to setParticles()\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n afterUpdateParticles(start, stop, update) { }\n}\n//# sourceMappingURL=pointsCloudSystem.js.map","/* eslint-disable import/export */\n/* eslint-disable import/no-internal-modules */\nexport * from \"./baseParticleSystem.js\";\nexport * from \"./EmitterTypes/index.js\";\nexport * from \"./webgl2ParticleSystem.js\";\nexport * from \"./computeShaderParticleSystem.js\";\nexport * from \"./gpuParticleSystem.js\";\nexport * from \"./IParticleSystem.js\";\nexport * from \"./particle.js\";\nexport * from \"./particleHelper.js\";\nexport * from \"./particleSystem.js\";\nimport \"./particleSystemComponent.js\";\n// eslint-disable-next-line no-duplicate-imports\nexport * from \"./particleSystemComponent.js\";\nexport * from \"./particleSystemSet.js\";\nexport * from \"./solidParticle.js\";\nexport * from \"./solidParticleSystem.js\";\nexport * from \"./cloudPoint.js\";\nexport * from \"./pointsCloudSystem.js\";\nexport * from \"./subEmitter.js\";\n//# sourceMappingURL=index.js.map","import { AbstractMesh } from \"../../Meshes/abstractMesh.js\";\nimport { PhysicsJoint } from \"./physicsJoint.js\";\nObject.defineProperty(AbstractMesh.prototype, \"physicsImpostor\", {\n get: function () {\n return this._physicsImpostor;\n },\n set: function (value) {\n if (this._physicsImpostor === value) {\n return;\n }\n if (this._disposePhysicsObserver) {\n this.onDisposeObservable.remove(this._disposePhysicsObserver);\n }\n this._physicsImpostor = value;\n if (value) {\n this._disposePhysicsObserver = this.onDisposeObservable.add(() => {\n // Physics\n if (this.physicsImpostor) {\n this.physicsImpostor.dispose( /*!doNotRecurse*/);\n this.physicsImpostor = null;\n }\n });\n }\n },\n enumerable: true,\n configurable: true,\n});\n/**\n * Gets the current physics impostor\n * @see https://doc.babylonjs.com/features/featuresDeepDive/physics\n * @returns a physics impostor or null\n */\nAbstractMesh.prototype.getPhysicsImpostor = function () {\n return this.physicsImpostor;\n};\n/**\n * Apply a physic impulse to the mesh\n * @param force defines the force to apply\n * @param contactPoint defines where to apply the force\n * @returns the current mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine\n */\nAbstractMesh.prototype.applyImpulse = function (force, contactPoint) {\n if (!this.physicsImpostor) {\n return this;\n }\n this.physicsImpostor.applyImpulse(force, contactPoint);\n return this;\n};\n/**\n * Creates a physic joint between two meshes\n * @param otherMesh defines the other mesh to use\n * @param pivot1 defines the pivot to use on this mesh\n * @param pivot2 defines the pivot to use on the other mesh\n * @param options defines additional options (can be plugin dependent)\n * @returns the current mesh\n * @see https://www.babylonjs-playground.com/#0BS5U0#0\n */\nAbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {\n if (!this.physicsImpostor || !otherMesh.physicsImpostor) {\n return this;\n }\n this.physicsImpostor.createJoint(otherMesh.physicsImpostor, PhysicsJoint.HingeJoint, {\n mainPivot: pivot1,\n connectedPivot: pivot2,\n nativeParams: options,\n });\n return this;\n};\n//# sourceMappingURL=physicsEngineComponent.js.map","export {};\n//# sourceMappingURL=IPhysicsEnginePlugin.js.map","export * from \"./cannonJSPlugin.js\";\nexport * from \"./ammoJSPlugin.js\";\nexport * from \"./oimoJSPlugin.js\";\n//# sourceMappingURL=index.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./IPhysicsEnginePlugin.js\";\nexport * from \"./physicsEngine.js\";\nexport * from \"./physicsEngineComponent.js\";\nexport * from \"./physicsImpostor.js\";\nexport * from \"./physicsJoint.js\";\nexport * from \"./Plugins/index.js\";\n//# sourceMappingURL=index.js.map","import { Vector3 } from \"../../Maths/math.vector.js\";\nimport { PhysicsRaycastResult } from \"../physicsRaycastResult.js\";\nimport { _WarnImport } from \"../../Misc/devTools.js\";\n/**\n * Class used to control physics engine\n * @see https://doc.babylonjs.com/features/featuresDeepDive/physics/usingPhysicsEngine\n */\nexport class PhysicsEngine {\n /**\n *\n * @returns physics plugin version\n */\n getPluginVersion() {\n return this._physicsPlugin.getPluginVersion();\n }\n /**\n * Factory used to create the default physics plugin.\n * @returns The default physics plugin\n */\n static DefaultPluginFactory() {\n throw _WarnImport(\"\");\n }\n /**\n * Creates a new Physics Engine\n * @param gravity defines the gravity vector used by the simulation\n * @param _physicsPlugin defines the plugin to use (CannonJS by default)\n */\n constructor(gravity, _physicsPlugin = PhysicsEngine.DefaultPluginFactory()) {\n this._physicsPlugin = _physicsPlugin;\n /** @internal */\n this._physicsBodies = [];\n this._subTimeStep = 0;\n gravity = gravity || new Vector3(0, -9.807, 0);\n this.setGravity(gravity);\n this.setTimeStep();\n }\n /**\n * Sets the gravity vector used by the simulation\n * @param gravity defines the gravity vector to use\n */\n setGravity(gravity) {\n this.gravity = gravity;\n this._physicsPlugin.setGravity(this.gravity);\n }\n /**\n * Set the time step of the physics engine.\n * Default is 1/60.\n * To slow it down, enter 1/600 for example.\n * To speed it up, 1/30\n * @param newTimeStep defines the new timestep to apply to this world.\n */\n setTimeStep(newTimeStep = 1 / 60) {\n this._physicsPlugin.setTimeStep(newTimeStep);\n }\n /**\n * Get the time step of the physics engine.\n * @returns the current time step\n */\n getTimeStep() {\n return this._physicsPlugin.getTimeStep();\n }\n /**\n * Set the sub time step of the physics engine.\n * Default is 0 meaning there is no sub steps\n * To increase physics resolution precision, set a small value (like 1 ms)\n * @param subTimeStep defines the new sub timestep used for physics resolution.\n */\n setSubTimeStep(subTimeStep = 0) {\n this._subTimeStep = subTimeStep;\n }\n /**\n * Get the sub time step of the physics engine.\n * @returns the current sub time step\n */\n getSubTimeStep() {\n return this._subTimeStep;\n }\n /**\n * Release all resources\n */\n dispose() {\n this._physicsPlugin.dispose();\n }\n /**\n * Gets the name of the current physics plugin\n * @returns the name of the plugin\n */\n getPhysicsPluginName() {\n return this._physicsPlugin.name;\n }\n /**\n * Adding a new impostor for the impostor tracking.\n * This will be done by the impostor itself.\n * @param impostor the impostor to add\n */\n /**\n * Called by the scene. No need to call it.\n * @param delta defines the timespan between frames\n */\n _step(delta) {\n if (delta > 0.1) {\n delta = 0.1;\n }\n else if (delta <= 0) {\n delta = 1.0 / 60.0;\n }\n this._physicsPlugin.executeStep(delta, this._physicsBodies);\n }\n /**\n * Add a body as an active component of this engine\n * @param body\n */\n addBody(physicsBody) {\n this._physicsBodies.push(physicsBody);\n }\n /**\n * Removes a particular body from this engine\n */\n removeBody(physicsBody) {\n const index = this._physicsBodies.indexOf(physicsBody);\n if (index > -1) {\n /*const removed =*/ this._physicsBodies.splice(index, 1);\n }\n }\n /**\n * Returns an array of bodies added to this engine\n\n */\n getBodies() {\n return this._physicsBodies;\n }\n /**\n * Gets the current plugin used to run the simulation\n * @returns current plugin\n */\n getPhysicsPlugin() {\n return this._physicsPlugin;\n }\n /**\n * Does a raycast in the physics world\n * @param from when should the ray start?\n * @param to when should the ray end?\n * @param result resulting PhysicsRaycastResult\n */\n raycastToRef(from, to, result, query) {\n this._physicsPlugin.raycast(from, to, result, query);\n }\n /**\n * Does a raycast in the physics world\n * @param from when should the ray start?\n * @param to when should the ray end?\n * @returns PhysicsRaycastResult\n */\n raycast(from, to, query) {\n const result = new PhysicsRaycastResult();\n this._physicsPlugin.raycast(from, to, result, query);\n return result;\n }\n}\n//# sourceMappingURL=physicsEngine.js.map","import { Vector3, Quaternion, TmpVectors } from \"../../Maths/math.vector.js\";\nimport { Space } from \"../../Maths/math.axis.js\";\n/**\n * PhysicsBody is useful for creating a physics body that can be used in a physics engine. It allows\n * the user to set the mass and velocity of the body, which can then be used to calculate the\n * motion of the body in the physics engine.\n */\nexport class PhysicsBody {\n /**\n * Constructs a new physics body for the given node.\n * @param transformNode - The Transform Node to construct the physics body for. For better performance, it is advised that this node does not have a parent.\n * @param motionType - The motion type of the physics body. The options are:\n * - PhysicsMotionType.STATIC - Static bodies are not moving and unaffected by forces or collisions. They are good for level boundaries or terrain.\n * - PhysicsMotionType.DYNAMIC - Dynamic bodies are fully simulated. They can move and collide with other objects.\n * - PhysicsMotionType.ANIMATED - They behave like dynamic bodies, but they won't be affected by other bodies, but still push other bodies out of the way.\n * @param startsAsleep - Whether the physics body should start in a sleeping state (not a guarantee). Defaults to false.\n * @param scene - The scene containing the physics engine.\n *\n * This code is useful for creating a physics body for a given Transform Node in a scene.\n * It checks the version of the physics engine and the physics plugin, and initializes the body accordingly.\n * It also sets the node's rotation quaternion if it is not already set. Finally, it adds the body to the physics engine.\n */\n constructor(transformNode, motionType, startsAsleep, scene) {\n /**\n * V2 Physics plugin private data for single Transform\n */\n this._pluginData = undefined;\n /**\n * V2 Physics plugin private data for instances\n */\n this._pluginDataInstances = [];\n /**\n * If the collision callback is enabled\n */\n this._collisionCBEnabled = false;\n /**\n * Disable pre-step that consists in updating Physics Body from Transform Node Translation/Orientation.\n * True by default for maximum performance.\n */\n this.disablePreStep = true;\n if (!scene) {\n return;\n }\n const physicsEngine = scene.getPhysicsEngine();\n if (!physicsEngine) {\n throw new Error(\"No Physics Engine available.\");\n }\n this._physicsEngine = physicsEngine;\n if (physicsEngine.getPluginVersion() != 2) {\n throw new Error(\"Plugin version is incorrect. Expected version 2.\");\n }\n const physicsPlugin = physicsEngine.getPhysicsPlugin();\n if (!physicsPlugin) {\n throw new Error(\"No Physics Plugin available.\");\n }\n this._physicsPlugin = physicsPlugin;\n if (!transformNode.rotationQuaternion) {\n transformNode.rotationQuaternion = Quaternion.FromEulerAngles(transformNode.rotation.x, transformNode.rotation.y, transformNode.rotation.z);\n }\n this.startAsleep = startsAsleep;\n // instances?\n const m = transformNode;\n if (m.hasThinInstances) {\n this._physicsPlugin.initBodyInstances(this, motionType, m);\n }\n else {\n // single instance\n if (transformNode.parent) {\n // Force computation of world matrix so that the parent transforms are correctly reflected in absolutePosition/absoluteRotationQuaternion.\n transformNode.computeWorldMatrix(true);\n }\n this._physicsPlugin.initBody(this, motionType, transformNode.absolutePosition, transformNode.absoluteRotationQuaternion);\n }\n this.transformNode = transformNode;\n transformNode.physicsBody = this;\n physicsEngine.addBody(this);\n this._nodeDisposeObserver = transformNode.onDisposeObservable.add(() => {\n this.dispose();\n });\n }\n /**\n * Returns the string \"PhysicsBody\".\n * @returns \"PhysicsBody\"\n */\n getClassName() {\n return \"PhysicsBody\";\n }\n /**\n * Clone the PhysicsBody to a new body and assign it to the transformNode parameter\n * @param transformNode transformNode that will be used for the cloned PhysicsBody\n * @returns the newly cloned PhysicsBody\n */\n clone(transformNode) {\n const clonedBody = new PhysicsBody(transformNode, this.getMotionType(), this.startAsleep, this.transformNode.getScene());\n clonedBody.shape = this.shape;\n return clonedBody;\n }\n /**\n * If a physics body is connected to an instanced node, update the number physic instances to match the number of node instances.\n */\n updateBodyInstances() {\n const m = this.transformNode;\n if (m.hasThinInstances) {\n this._physicsPlugin.updateBodyInstances(this, m);\n }\n }\n /**\n * This returns the number of internal instances of the physics body\n */\n get numInstances() {\n return this._pluginDataInstances.length;\n }\n /**\n * Sets the shape of the physics body.\n * @param shape - The shape of the physics body.\n *\n * This method is useful for setting the shape of the physics body, which is necessary for the physics engine to accurately simulate the body's behavior.\n * The shape is used to calculate the body's mass, inertia, and other properties.\n */\n set shape(shape) {\n this._physicsPlugin.setShape(this, shape);\n }\n /**\n * Retrieves the physics shape associated with this object.\n *\n * @returns The physics shape associated with this object, or `undefined` if no\n * shape is associated.\n *\n * This method is useful for retrieving the physics shape associated with this object,\n * which can be used to apply physical forces to the object or to detect collisions.\n */\n get shape() {\n return this._physicsPlugin.getShape(this);\n }\n /**\n * Sets the event mask for the physics engine.\n *\n * @param eventMask - A bitmask that determines which events will be sent to the physics engine.\n *\n * This method is useful for setting the event mask for the physics engine, which determines which events\n * will be sent to the physics engine. This allows the user to control which events the physics engine will respond to.\n */\n setEventMask(eventMask, instanceIndex) {\n this._physicsPlugin.setEventMask(this, eventMask, instanceIndex);\n }\n /**\n * Gets the event mask of the physics engine.\n *\n * @returns The event mask of the physics engine.\n *\n * This method is useful for getting the event mask of the physics engine,\n * which is used to determine which events the engine will respond to.\n * This is important for ensuring that the engine is responding to the correct events and not\n * wasting resources on unnecessary events.\n */\n getEventMask(instanceIndex) {\n return this._physicsPlugin.getEventMask(this, instanceIndex);\n }\n /**\n * Sets the motion type of the physics body. Can be STATIC, DYNAMIC, or ANIMATED.\n */\n setMotionType(motionType, instanceIndex) {\n this._physicsPlugin.setMotionType(this, motionType, instanceIndex);\n }\n /**\n * Gets the motion type of the physics body. Can be STATIC, DYNAMIC, or ANIMATED.\n */\n getMotionType(instanceIndex) {\n return this._physicsPlugin.getMotionType(this, instanceIndex);\n }\n /**\n * Computes the mass properties of the physics object, based on the set of physics shapes this body uses.\n * This method is useful for computing the initial mass properties of a physics object, such as its mass,\n * inertia, and center of mass; these values are important for accurately simulating the physics of the\n * object in the physics engine, and computing values based on the shape will provide you with reasonable\n * intial values, which you can then customize.\n */\n computeMassProperties(instanceIndex) {\n return this._physicsPlugin.computeMassProperties(this, instanceIndex);\n }\n /**\n * Sets the mass properties of the physics object.\n *\n * @param massProps - The mass properties to set.\n * @param instanceIndex - The index of the instance to set the mass properties for. If not defined, the mass properties will be set for all instances.\n *\n * This method is useful for setting the mass properties of a physics object, such as its mass,\n * inertia, and center of mass. This is important for accurately simulating the physics of the object in the physics engine.\n */\n setMassProperties(massProps, instanceIndex) {\n this._physicsPlugin.setMassProperties(this, massProps, instanceIndex);\n }\n /**\n * Retrieves the mass properties of the object.\n *\n * @returns The mass properties of the object.\n *\n * This method is useful for physics simulations, as it allows the user to\n * retrieve the mass properties of the object, such as its mass, center of mass,\n * and moment of inertia. This information is necessary for accurate physics\n * simulations.\n */\n getMassProperties(instanceIndex) {\n return this._physicsPlugin.getMassProperties(this, instanceIndex);\n }\n /**\n * Sets the linear damping of the physics body.\n *\n * @param damping - The linear damping value.\n *\n * This method is useful for controlling the linear damping of the physics body,\n * which is the rate at which the body's velocity decreases over time. This is useful for simulating\n * the effects of air resistance or other forms of friction.\n */\n setLinearDamping(damping, instanceIndex) {\n this._physicsPlugin.setLinearDamping(this, damping, instanceIndex);\n }\n /**\n * Gets the linear damping of the physics body.\n * @returns The linear damping of the physics body.\n *\n * This method is useful for retrieving the linear damping of the physics body, which is the amount of\n * resistance the body has to linear motion. This is useful for simulating realistic physics behavior\n * in a game.\n */\n getLinearDamping(instanceIndex) {\n return this._physicsPlugin.getLinearDamping(this, instanceIndex);\n }\n /**\n * Sets the angular damping of the physics body.\n * @param damping The angular damping of the body.\n *\n * This method is useful for controlling the angular velocity of a physics body.\n * By setting the damping, the body's angular velocity will be reduced over time, simulating the effect of friction.\n * This can be used to create realistic physical behavior in a physics engine.\n */\n setAngularDamping(damping, instanceIndex) {\n this._physicsPlugin.setAngularDamping(this, damping, instanceIndex);\n }\n /**\n * Gets the angular damping of the physics body.\n *\n * @returns The angular damping of the physics body.\n *\n * This method is useful for getting the angular damping of the physics body,\n * which is the rate of reduction of the angular velocity over time.\n * This is important for simulating realistic physics behavior in a game.\n */\n getAngularDamping(instanceIndex) {\n return this._physicsPlugin.getAngularDamping(this, instanceIndex);\n }\n /**\n * Sets the linear velocity of the physics object.\n * @param linVel - The linear velocity to set.\n *\n * This method is useful for setting the linear velocity of a physics object,\n * which is necessary for simulating realistic physics in a game engine.\n * By setting the linear velocity, the physics object will move in the direction and speed specified by the vector.\n * This allows for realistic physics simulations, such as simulating the motion of a ball rolling down a hill.\n */\n setLinearVelocity(linVel, instanceIndex) {\n this._physicsPlugin.setLinearVelocity(this, linVel, instanceIndex);\n }\n /**\n * Gets the linear velocity of the physics body and stores it in the given vector3.\n * @param linVel - The vector3 to store the linear velocity in.\n *\n * This method is useful for getting the linear velocity of a physics body in a physics engine.\n * This can be used to determine the speed and direction of the body, which can be used to calculate the motion of the body.*/\n getLinearVelocityToRef(linVel, instanceIndex) {\n return this._physicsPlugin.getLinearVelocityToRef(this, linVel, instanceIndex);\n }\n /**\n * Sets the angular velocity of the physics object.\n * @param angVel - The angular velocity to set.\n *\n * This method is useful for setting the angular velocity of a physics object, which is necessary for\n * simulating realistic physics behavior. The angular velocity is used to determine the rate of rotation of the object,\n * which is important for simulating realistic motion.\n */\n setAngularVelocity(angVel, instanceIndex) {\n this._physicsPlugin.setAngularVelocity(this, angVel, instanceIndex);\n }\n /**\n * Gets the angular velocity of the physics body and stores it in the given vector3.\n * @param angVel - The vector3 to store the angular velocity in.\n *\n * This method is useful for getting the angular velocity of a physics body, which can be used to determine the body's\n * rotational speed. This information can be used to create realistic physics simulations.\n */\n getAngularVelocityToRef(angVel, instanceIndex) {\n return this._physicsPlugin.getAngularVelocityToRef(this, angVel, instanceIndex);\n }\n /**\n * Applies an impulse to the physics object.\n *\n * @param impulse The impulse vector.\n * @param location The location of the impulse.\n * @param instanceIndex For a instanced body, the instance to where the impulse should be applied. If not specified, the impulse is applied to all instances.\n *\n * This method is useful for applying an impulse to a physics object, which can be used to simulate physical forces such as gravity,\n * collisions, and explosions. This can be used to create realistic physics simulations in a game or other application.\n */\n applyImpulse(impulse, location, instanceIndex) {\n this._physicsPlugin.applyImpulse(this, impulse, location, instanceIndex);\n }\n /**\n * Applies a force to the physics object.\n *\n * @param force The force vector.\n * @param location The location of the force.\n * @param instanceIndex For a instanced body, the instance to where the force should be applied. If not specified, the force is applied to all instances.\n *\n * This method is useful for applying a force to a physics object, which can be used to simulate physical forces such as gravity,\n * collisions, and explosions. This can be used to create realistic physics simulations in a game or other application.\n */\n applyForce(force, location, instanceIndex) {\n this._physicsPlugin.applyForce(this, force, location, instanceIndex);\n }\n /**\n * Retrieves the geometry of the body from the physics plugin.\n *\n * @returns The geometry of the body.\n *\n * This method is useful for retrieving the geometry of the body from the physics plugin, which can be used for various physics calculations.\n */\n getGeometry() {\n return this._physicsPlugin.getBodyGeometry(this);\n }\n /**\n * Returns an observable that will be notified for all collisions happening for event-enabled bodies\n * @returns Observable\n */\n getCollisionObservable() {\n return this._physicsPlugin.getCollisionObservable(this);\n }\n /**\n * Enable or disable collision callback for this PhysicsBody.\n * @param enabled true if PhysicsBody's collision will rise a collision event and notifies the observable\n */\n setCollisionCallbackEnabled(enabled) {\n this._collisionCBEnabled = enabled;\n this._physicsPlugin.setCollisionCallbackEnabled(this, enabled);\n }\n /*\n * Get the center of the object in world space.\n * @param instanceIndex - If this body is instanced, the index of the instance to get the center for.\n * @returns geometric center of the associated mesh\n */\n getObjectCenterWorld(instanceIndex) {\n const ref = new Vector3();\n return this.getObjectCenterWorldToRef(ref, instanceIndex);\n }\n /*\n * Get the center of the object in world space.\n * @param ref - The vector3 to store the result in.\n * @param instanceIndex - If this body is instanced, the index of the instance to get the center for.\n * @returns geometric center of the associated mesh\n */\n getObjectCenterWorldToRef(ref, instanceIndex) {\n var _a;\n if (((_a = this._pluginDataInstances) === null || _a === void 0 ? void 0 : _a.length) > 0) {\n const index = instanceIndex || 0;\n const matrixData = this.transformNode._thinInstanceDataStorage.matrixData;\n if (matrixData) {\n ref.set(matrixData[index * 16 + 12], matrixData[index * 16 + 13], matrixData[index * 16 + 14]);\n }\n }\n else {\n ref.copyFrom(this.transformNode.position);\n }\n return ref;\n }\n /**\n * Adds a constraint to the physics engine.\n *\n * @param childBody - The body to which the constraint will be applied.\n * @param constraint - The constraint to be applied.\n * @param instanceIndex - If this body is instanced, the index of the instance to which the constraint will be applied. If not specified, no constraint will be applied.\n * @param childInstanceIndex - If the child body is instanced, the index of the instance to which the constraint will be applied. If not specified, no constraint will be applied.\n *\n */\n addConstraint(childBody, constraint, instanceIndex, childInstanceIndex) {\n this._physicsPlugin.addConstraint(this, childBody, constraint, instanceIndex, childInstanceIndex);\n }\n /**\n * Sync with a bone\n * @param bone The bone that the impostor will be synced to.\n * @param boneMesh The mesh that the bone is influencing.\n * @param jointPivot The pivot of the joint / bone in local space.\n * @param distToJoint Optional distance from the impostor to the joint.\n * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.\n * @param boneAxis Optional vector3 axis the bone is aligned with\n */\n syncWithBone(bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {\n const mesh = this.transformNode;\n if (mesh.rotationQuaternion) {\n if (adjustRotation) {\n const tempQuat = TmpVectors.Quaternion[0];\n bone.getRotationQuaternionToRef(Space.WORLD, boneMesh, tempQuat);\n tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);\n }\n else {\n bone.getRotationQuaternionToRef(Space.WORLD, boneMesh, mesh.rotationQuaternion);\n }\n }\n const pos = TmpVectors.Vector3[0];\n const boneDir = TmpVectors.Vector3[1];\n if (!boneAxis) {\n boneAxis = TmpVectors.Vector3[2];\n boneAxis.x = 0;\n boneAxis.y = 1;\n boneAxis.z = 0;\n }\n bone.getDirectionToRef(boneAxis, boneMesh, boneDir);\n bone.getAbsolutePositionToRef(boneMesh, pos);\n if ((distToJoint === undefined || distToJoint === null) && jointPivot) {\n distToJoint = jointPivot.length();\n }\n if (distToJoint !== undefined && distToJoint !== null) {\n pos.x += boneDir.x * distToJoint;\n pos.y += boneDir.y * distToJoint;\n pos.z += boneDir.z * distToJoint;\n }\n mesh.setAbsolutePosition(pos);\n }\n /**\n * Executes a callback on the body or all of the instances of a body\n * @param callback the callback to execute\n */\n iterateOverAllInstances(callback) {\n var _a;\n if (((_a = this._pluginDataInstances) === null || _a === void 0 ? void 0 : _a.length) > 0) {\n for (let i = 0; i < this._pluginDataInstances.length; i++) {\n callback(this, i);\n }\n }\n else {\n callback(this, undefined);\n }\n }\n /**\n * Sets the gravity factor of the physics body\n * @param factor the gravity factor to set\n * @param instanceIndex the instance of the body to set, if undefined all instances will be set\n */\n setGravityFactor(factor, instanceIndex) {\n this._physicsPlugin.setGravityFactor(this, factor, instanceIndex);\n }\n /**\n * Gets the gravity factor of the physics body\n * @param instanceIndex the instance of the body to get, if undefined the value of first instance will be returned\n * @returns the gravity factor\n */\n getGravityFactor(instanceIndex) {\n return this._physicsPlugin.getGravityFactor(this, instanceIndex);\n }\n /**\n * Disposes the body from the physics engine.\n *\n * This method is useful for cleaning up the physics engine when a body is no longer needed. Disposing the body will free up resources and prevent memory leaks.\n */\n dispose() {\n // Disable collisions CB so it doesn't fire when the body is disposed\n if (this._collisionCBEnabled) {\n this.setCollisionCallbackEnabled(false);\n }\n if (this._nodeDisposeObserver) {\n this.transformNode.onDisposeObservable.remove(this._nodeDisposeObserver);\n this._nodeDisposeObserver = null;\n }\n this._physicsEngine.removeBody(this);\n this._physicsPlugin.removeBody(this);\n this._physicsPlugin.disposeBody(this);\n this._pluginData = null;\n this._pluginDataInstances.length = 0;\n }\n}\n//# sourceMappingURL=physicsBody.js.map","/** How a specific axis can be constrained */\nexport var PhysicsConstraintAxisLimitMode;\n(function (PhysicsConstraintAxisLimitMode) {\n /*\n * The axis is not restricted at all\n */\n PhysicsConstraintAxisLimitMode[PhysicsConstraintAxisLimitMode[\"FREE\"] = 0] = \"FREE\";\n /*\n * The axis has a minimum/maximum limit\n */\n PhysicsConstraintAxisLimitMode[PhysicsConstraintAxisLimitMode[\"LIMITED\"] = 1] = \"LIMITED\";\n /*\n * The axis allows no relative movement of the pivots\n */\n PhysicsConstraintAxisLimitMode[PhysicsConstraintAxisLimitMode[\"LOCKED\"] = 2] = \"LOCKED\";\n})(PhysicsConstraintAxisLimitMode || (PhysicsConstraintAxisLimitMode = {}));\n/** The constraint specific axis to use when setting Friction, `ConstraintAxisLimitMode`, max force, ... */\nexport var PhysicsConstraintAxis;\n(function (PhysicsConstraintAxis) {\n /*\n * Translation along the primary axis of the constraint (i.e. the\n * direction specified by PhysicsConstraintParameters.axisA/axisB)\n */\n PhysicsConstraintAxis[PhysicsConstraintAxis[\"LINEAR_X\"] = 0] = \"LINEAR_X\";\n /*\n * Translation along the second axis of the constraint (i.e. the\n * direction specified by PhysicsConstraintParameters.perpAxisA/perpAxisB)\n */\n PhysicsConstraintAxis[PhysicsConstraintAxis[\"LINEAR_Y\"] = 1] = \"LINEAR_Y\";\n /*\n * Translation along the third axis of the constraint. This axis is\n * computed from the cross product of axisA/axisB and perpAxisA/perpAxisB)\n */\n PhysicsConstraintAxis[PhysicsConstraintAxis[\"LINEAR_Z\"] = 2] = \"LINEAR_Z\";\n /*\n * Rotation around the primary axis of the constraint (i.e. the\n * axis specified by PhysicsConstraintParameters.axisA/axisB)\n */\n PhysicsConstraintAxis[PhysicsConstraintAxis[\"ANGULAR_X\"] = 3] = \"ANGULAR_X\";\n /*\n * Rotation around the second axis of the constraint (i.e. the\n * axis specified by PhysicsConstraintParameters.perpAxisA/perpAxisB)\n */\n PhysicsConstraintAxis[PhysicsConstraintAxis[\"ANGULAR_Y\"] = 4] = \"ANGULAR_Y\";\n /*\n * Rotation around the third axis of the constraint. This axis is\n * computed from the cross product of axisA/axisB and perpAxisA/perpAxisB)\n */\n PhysicsConstraintAxis[PhysicsConstraintAxis[\"ANGULAR_Z\"] = 5] = \"ANGULAR_Z\";\n /*\n * A 3D distance limit; similar to specifying the LINEAR_X/Y/Z axes\n * individually, but the distance calculation uses all three axes\n * simultaneously, instead of individually.\n */\n PhysicsConstraintAxis[PhysicsConstraintAxis[\"LINEAR_DISTANCE\"] = 6] = \"LINEAR_DISTANCE\";\n})(PhysicsConstraintAxis || (PhysicsConstraintAxis = {}));\n/** Type of Constraint */\nexport var PhysicsConstraintType;\n(function (PhysicsConstraintType) {\n /**\n * A ball and socket constraint will attempt to line up the pivot\n * positions in each body, and have no restrictions on rotation\n */\n PhysicsConstraintType[PhysicsConstraintType[\"BALL_AND_SOCKET\"] = 1] = \"BALL_AND_SOCKET\";\n /**\n * A distance constraint will attempt to keep the pivot locations\n * within a specified distance.\n */\n PhysicsConstraintType[PhysicsConstraintType[\"DISTANCE\"] = 2] = \"DISTANCE\";\n /**\n * A hinge constraint will keep the pivot positions aligned as well\n * as two angular axes. The remaining angular axis will be free to rotate.\n */\n PhysicsConstraintType[PhysicsConstraintType[\"HINGE\"] = 3] = \"HINGE\";\n /**\n * A slider constraint allows bodies to translate along one axis and\n * rotate about the same axis. The remaining two axes are locked in\n * place\n */\n PhysicsConstraintType[PhysicsConstraintType[\"SLIDER\"] = 4] = \"SLIDER\";\n /**\n * A lock constraint will attempt to keep the pivots completely lined\n * up between both bodies, allowing no relative movement.\n */\n PhysicsConstraintType[PhysicsConstraintType[\"LOCK\"] = 5] = \"LOCK\";\n /*\n * A prismatic will lock the rotations of the bodies, and allow translation\n * only along one axis\n */\n PhysicsConstraintType[PhysicsConstraintType[\"PRISMATIC\"] = 6] = \"PRISMATIC\";\n /*\n * A generic constraint; this starts with no limits on how the bodies can\n * move relative to each other, but limits can be added via the PhysicsConstraint\n * interfaces. This can be used to specify a large variety of constraints\n */\n PhysicsConstraintType[PhysicsConstraintType[\"SIX_DOF\"] = 7] = \"SIX_DOF\";\n})(PhysicsConstraintType || (PhysicsConstraintType = {}));\n/** Type of Shape */\nexport var PhysicsShapeType;\n(function (PhysicsShapeType) {\n PhysicsShapeType[PhysicsShapeType[\"SPHERE\"] = 0] = \"SPHERE\";\n PhysicsShapeType[PhysicsShapeType[\"CAPSULE\"] = 1] = \"CAPSULE\";\n PhysicsShapeType[PhysicsShapeType[\"CYLINDER\"] = 2] = \"CYLINDER\";\n PhysicsShapeType[PhysicsShapeType[\"BOX\"] = 3] = \"BOX\";\n PhysicsShapeType[PhysicsShapeType[\"CONVEX_HULL\"] = 4] = \"CONVEX_HULL\";\n PhysicsShapeType[PhysicsShapeType[\"CONTAINER\"] = 5] = \"CONTAINER\";\n PhysicsShapeType[PhysicsShapeType[\"MESH\"] = 6] = \"MESH\";\n PhysicsShapeType[PhysicsShapeType[\"HEIGHTFIELD\"] = 7] = \"HEIGHTFIELD\";\n})(PhysicsShapeType || (PhysicsShapeType = {}));\n/** Optional motor which attempts to move a body at a specific velocity, or at a specific position */\nexport var PhysicsConstraintMotorType;\n(function (PhysicsConstraintMotorType) {\n PhysicsConstraintMotorType[PhysicsConstraintMotorType[\"NONE\"] = 0] = \"NONE\";\n PhysicsConstraintMotorType[PhysicsConstraintMotorType[\"VELOCITY\"] = 1] = \"VELOCITY\";\n PhysicsConstraintMotorType[PhysicsConstraintMotorType[\"POSITION\"] = 2] = \"POSITION\";\n})(PhysicsConstraintMotorType || (PhysicsConstraintMotorType = {}));\n/**\n * Indicates how the body will behave.\n */\nexport var PhysicsMotionType;\n(function (PhysicsMotionType) {\n PhysicsMotionType[PhysicsMotionType[\"STATIC\"] = 0] = \"STATIC\";\n PhysicsMotionType[PhysicsMotionType[\"ANIMATED\"] = 1] = \"ANIMATED\";\n PhysicsMotionType[PhysicsMotionType[\"DYNAMIC\"] = 2] = \"DYNAMIC\";\n})(PhysicsMotionType || (PhysicsMotionType = {}));\n//# sourceMappingURL=IPhysicsEnginePlugin.js.map","import { PhysicsShapeType } from \"./IPhysicsEnginePlugin.js\";\nimport { Matrix, Vector3, Quaternion, TmpVectors } from \"../../Maths/math.vector.js\";\n/**\n * PhysicsShape class.\n * This class is useful for creating a physics shape that can be used in a physics engine.\n * A Physic Shape determine how collision are computed. It must be attached to a body.\n */\nexport class PhysicsShape {\n /**\n * Constructs a new physics shape.\n * @param options The options for the physics shape. These are:\n * * type: The type of the shape. This can be one of the following: SPHERE, BOX, CAPSULE, CYLINDER, CONVEX_HULL, MESH, HEIGHTFIELD, CONTAINER\n * * parameters: The parameters of the shape.\n * * pluginData: The plugin data of the shape. This is used if you already have a reference to the object on the plugin side.\n * You need to specify either type or pluginData.\n * @param scene The scene the shape belongs to.\n *\n * This code is useful for creating a new physics shape with the given type, options, and scene.\n * It also checks that the physics engine and plugin version are correct.\n * If not, it throws an error. This ensures that the shape is created with the correct parameters and is compatible with the physics engine.\n */\n constructor(options, scene) {\n var _a;\n /**\n * V2 Physics plugin private data for single shape\n */\n this._pluginData = undefined;\n if (!scene) {\n return;\n }\n const physicsEngine = scene.getPhysicsEngine();\n if (!physicsEngine) {\n throw new Error(\"No Physics Engine available.\");\n }\n if (physicsEngine.getPluginVersion() != 2) {\n throw new Error(\"Plugin version is incorrect. Expected version 2.\");\n }\n const physicsPlugin = physicsEngine.getPhysicsPlugin();\n if (!physicsPlugin) {\n throw new Error(\"No Physics Plugin available.\");\n }\n this._physicsPlugin = physicsPlugin;\n if (options.pluginData !== undefined && options.pluginData !== null) {\n this._pluginData = options.pluginData;\n this._type = this._physicsPlugin.getShapeType(this);\n }\n else if (options.type !== undefined && options.type !== null) {\n this._type = options.type;\n const parameters = (_a = options.parameters) !== null && _a !== void 0 ? _a : {};\n this._physicsPlugin.initShape(this, options.type, parameters);\n }\n }\n /**\n * Returns the string \"PhysicsShape\".\n * @returns \"PhysicsShape\"\n */\n getClassName() {\n return \"PhysicsShape\";\n }\n /**\n *\n */\n get type() {\n return this._type;\n }\n /**\n * Set the membership mask of a shape. This is a bitfield of arbitrary\n * \"categories\" to which the shape is a member. This is used in combination\n * with the collide mask to determine if this shape should collide with\n * another.\n *\n * @param membershipMask Bitfield of categories of this shape.\n */\n set filterMembershipMask(membershipMask) {\n this._physicsPlugin.setShapeFilterMembershipMask(this, membershipMask);\n }\n /**\n * Get the membership mask of a shape.\n * @returns Bitmask of categories which this shape is a member of.\n */\n get filterMembershipMask() {\n return this._physicsPlugin.getShapeFilterMembershipMask(this);\n }\n /**\n * Sets the collide mask of a shape. This is a bitfield of arbitrary\n * \"categories\" to which this shape collides with. Given two shapes,\n * the engine will check if the collide mask and membership overlap:\n * shapeA.filterMembershipMask & shapeB.filterCollideMask\n *\n * If this value is zero (i.e. shapeB only collides with categories\n * which shapeA is _not_ a member of) then the shapes will not collide.\n *\n * Note, the engine will also perform the same test with shapeA and\n * shapeB swapped; the shapes will not collide if either shape has\n * a collideMask which prevents collision with the other shape.\n *\n * @param collideMask Bitmask of categories this shape should collide with\n */\n set filterCollideMask(collideMask) {\n this._physicsPlugin.setShapeFilterCollideMask(this, collideMask);\n }\n /**\n *\n * @returns Bitmask of categories that this shape should collide with\n */\n get filterCollideMask() {\n return this._physicsPlugin.getShapeFilterCollideMask(this);\n }\n /**\n *\n * @param material\n */\n set material(material) {\n this._physicsPlugin.setMaterial(this, material);\n this._material = material;\n }\n /**\n *\n * @returns\n */\n get material() {\n return this._material;\n }\n /**\n *\n * @param density\n */\n set density(density) {\n this._physicsPlugin.setDensity(this, density);\n }\n /**\n *\n */\n get density() {\n return this._physicsPlugin.getDensity(this);\n }\n /**\n * Utility to add a child shape to this container,\n * automatically computing the relative transform between\n * the container shape and the child instance.\n *\n * @param parentTransform The transform node associated with this shape\n * @param newChild The new PhysicsShape to add\n * @param childTransform The transform node associated with the child shape\n */\n addChildFromParent(parentTransform, newChild, childTransform) {\n const childToWorld = childTransform.computeWorldMatrix(true);\n const parentToWorld = parentTransform.computeWorldMatrix(true);\n const childToParent = TmpVectors.Matrix[0];\n childToWorld.multiplyToRef(Matrix.Invert(parentToWorld), childToParent);\n const translation = TmpVectors.Vector3[0];\n const rotation = TmpVectors.Quaternion[0];\n const scale = TmpVectors.Vector3[1];\n childToParent.decompose(scale, rotation, translation);\n this._physicsPlugin.addChild(this, newChild, translation, rotation, scale);\n }\n /**\n * Adds a child shape to a container with an optional transform\n * @param newChild The new PhysicsShape to add\n * @param translation Optional position of the child shape relative to this shape\n * @param rotation Optional rotation of the child shape relative to this shape\n * @param scale Optional scale of the child shape relative to this shape\n */\n addChild(newChild, translation, rotation, scale) {\n this._physicsPlugin.addChild(this, newChild, translation, rotation, scale);\n }\n /**\n *\n * @param childIndex\n */\n removeChild(childIndex) {\n this._physicsPlugin.removeChild(this, childIndex);\n }\n /**\n *\n * @returns\n */\n getNumChildren() {\n return this._physicsPlugin.getNumChildren(this);\n }\n /**\n *\n */\n getBoundingBox() {\n return this._physicsPlugin.getBoundingBox(this);\n }\n /**\n *\n */\n dispose() {\n this._physicsPlugin.disposeShape(this);\n }\n}\n/**\n * Helper object to create a sphere shape\n */\nexport class PhysicsShapeSphere extends PhysicsShape {\n /**\n * Constructor for the Sphere Shape\n * @param center local center of the sphere\n * @param radius radius\n * @param scene scene to attach to\n */\n constructor(center, radius, scene) {\n super({ type: PhysicsShapeType.SPHERE, parameters: { center: center, radius: radius } }, scene);\n }\n /**\n *\n * @param mesh\n * @returns PhysicsShapeSphere\n */\n static FromMesh(mesh) {\n const bounds = mesh.getBoundingInfo();\n const centerLocal = bounds.boundingSphere.center;\n const he = bounds.boundingBox.extendSize;\n const radius = Math.max(he.x, he.y, he.z);\n return new PhysicsShapeSphere(centerLocal, radius, mesh.getScene());\n }\n}\n/**\n * Helper object to create a capsule shape\n */\nexport class PhysicsShapeCapsule extends PhysicsShape {\n /**\n *\n * @param pointA Starting point that defines the capsule segment\n * @param pointB ending point of that same segment\n * @param radius radius\n * @param scene scene to attach to\n */\n constructor(pointA, pointB, radius, scene) {\n super({ type: PhysicsShapeType.CAPSULE, parameters: { pointA: pointA, pointB: pointB, radius: radius } }, scene);\n }\n /**\n * Derive an approximate capsule from the transform node. Note, this is\n * not the optimal bounding capsule.\n * @param TransformNode node Node from which to derive a cylinder shape\n */\n static FromMesh(mesh) {\n const boundsLocal = mesh.getBoundingInfo();\n const radius = boundsLocal.boundingBox.extendSize.x;\n const pointFromCenter = new Vector3(0, boundsLocal.boundingBox.extendSize.y - radius, 0);\n const pointA = boundsLocal.boundingBox.center.add(pointFromCenter);\n const pointB = boundsLocal.boundingBox.center.subtract(pointFromCenter);\n return new PhysicsShapeCapsule(pointA, pointB, radius, mesh.getScene());\n }\n}\n/**\n * Helper object to create a cylinder shape\n */\nexport class PhysicsShapeCylinder extends PhysicsShape {\n /**\n *\n * @param pointA Starting point that defines the cylinder segment\n * @param pointB ending point of that same segment\n * @param radius radius\n * @param scene scene to attach to\n */\n constructor(pointA, pointB, radius, scene) {\n super({ type: PhysicsShapeType.CYLINDER, parameters: { pointA: pointA, pointB: pointB, radius: radius } }, scene);\n }\n /**\n * Derive an approximate cylinder from the transform node. Note, this is\n * not the optimal bounding cylinder.\n * @param TransformNode node Node from which to derive a cylinder shape\n */\n static FromMesh(mesh) {\n const boundsLocal = mesh.getBoundingInfo();\n const radius = boundsLocal.boundingBox.extendSize.x;\n const pointFromCenter = new Vector3(0, boundsLocal.boundingBox.extendSize.y, 0);\n const pointA = boundsLocal.boundingBox.center.add(pointFromCenter);\n const pointB = boundsLocal.boundingBox.center.subtract(pointFromCenter);\n return new PhysicsShapeCylinder(pointA, pointB, radius, mesh.getScene());\n }\n}\n/**\n * Helper object to create a box shape\n */\nexport class PhysicsShapeBox extends PhysicsShape {\n /**\n *\n * @param center local center of the sphere\n * @param rotation local orientation\n * @param extents size of the box in each direction\n * @param scene scene to attach to\n */\n constructor(center, rotation, extents, scene) {\n super({ type: PhysicsShapeType.BOX, parameters: { center: center, rotation: rotation, extents: extents } }, scene);\n }\n /**\n *\n * @param mesh\n * @returns PhysicsShapeBox\n */\n static FromMesh(mesh) {\n const bounds = mesh.getBoundingInfo();\n const centerLocal = bounds.boundingBox.center;\n const extents = bounds.boundingBox.extendSize.scale(2.0); // {\n this.dispose();\n });\n }\n _getObjectBoundingBox() {\n if (this.transformNode.getRawBoundingInfo) {\n return this.transformNode.getRawBoundingInfo().boundingBox;\n }\n else {\n return new BoundingBox(new Vector3(-0.5, -0.5, -0.5), new Vector3(0.5, 0.5, 0.5));\n }\n }\n _hasVertices(node) {\n return (node === null || node === void 0 ? void 0 : node.getTotalVertices()) > 0;\n }\n _addSizeOptions() {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n this.transformNode.computeWorldMatrix(true);\n const bb = this._getObjectBoundingBox();\n const extents = TmpVectors.Vector3[0];\n extents.copyFrom(bb.extendSize);\n extents.scaleInPlace(2);\n extents.multiplyInPlace(this.transformNode.scaling);\n const min = TmpVectors.Vector3[1];\n min.copyFrom(bb.minimum);\n min.multiplyInPlace(this.transformNode.scaling);\n if (!this._options.center) {\n const center = new Vector3();\n center.copyFrom(bb.center);\n center.multiplyInPlace(this.transformNode.scaling);\n this._options.center = center;\n }\n switch (this.type) {\n case PhysicsShapeType.SPHERE:\n if (!this._options.radius && Scalar.WithinEpsilon(extents.x, extents.y, 0.0001) && Scalar.WithinEpsilon(extents.x, extents.z, 0.0001)) {\n this._options.radius = extents.x / 2;\n }\n else if (!this._options.radius) {\n Logger.Warn(\"Non uniform scaling is unsupported for sphere shapes. Setting the radius to the biggest bounding box extent.\");\n this._options.radius = Math.max(extents.x, extents.y, extents.z) / 2;\n }\n break;\n case PhysicsShapeType.CAPSULE:\n {\n const capRadius = extents.x / 2;\n this._options.radius = (_a = this._options.radius) !== null && _a !== void 0 ? _a : capRadius;\n this._options.pointA = (_b = this._options.pointA) !== null && _b !== void 0 ? _b : new Vector3(0, min.y + capRadius, 0);\n this._options.pointB = (_c = this._options.pointB) !== null && _c !== void 0 ? _c : new Vector3(0, min.y + extents.y - capRadius, 0);\n }\n break;\n case PhysicsShapeType.CYLINDER:\n {\n const capRadius = extents.x / 2;\n this._options.radius = (_d = this._options.radius) !== null && _d !== void 0 ? _d : capRadius;\n this._options.pointA = (_e = this._options.pointA) !== null && _e !== void 0 ? _e : new Vector3(0, min.y, 0);\n this._options.pointB = (_f = this._options.pointB) !== null && _f !== void 0 ? _f : new Vector3(0, min.y + extents.y, 0);\n }\n break;\n case PhysicsShapeType.MESH:\n case PhysicsShapeType.CONVEX_HULL:\n if (!this._options.mesh && this._hasVertices(this.transformNode)) {\n this._options.mesh = this.transformNode;\n }\n else if (!this._options.mesh || !this._hasVertices(this._options.mesh)) {\n throw new Error(\"No valid mesh was provided for mesh or convex hull shape parameter. Please provide a mesh with valid geometry (number of vertices greater than 0).\");\n }\n break;\n case PhysicsShapeType.BOX:\n this._options.extents = (_g = this._options.extents) !== null && _g !== void 0 ? _g : new Vector3(extents.x, extents.y, extents.z);\n this._options.rotation = (_h = this._options.rotation) !== null && _h !== void 0 ? _h : Quaternion.Identity();\n break;\n }\n }\n /**\n * Releases the body, shape and material\n */\n dispose() {\n if (this._nodeDisposeObserver) {\n this.body.transformNode.onDisposeObservable.remove(this._nodeDisposeObserver);\n this._nodeDisposeObserver = null;\n }\n this.body.dispose();\n if (this._disposeShapeWhenDisposed) {\n this.shape.dispose();\n }\n }\n}\n//# sourceMappingURL=physicsAggregate.js.map","import { Matrix, Quaternion, TmpVectors, Vector3 } from \"../../../Maths/math.vector.js\";\nimport { PhysicsShapeType, PhysicsConstraintType, PhysicsMotionType, PhysicsConstraintMotorType, PhysicsConstraintAxis, PhysicsConstraintAxisLimitMode, } from \"../IPhysicsEnginePlugin.js\";\nimport { Logger } from \"../../../Misc/logger.js\";\nimport { PhysicsMaterialCombineMode } from \"../physicsMaterial.js\";\nimport { PhysicsShape } from \"../physicsShape.js\";\nimport { Mesh } from \"../../../Meshes/mesh.js\";\nimport { VertexBuffer } from \"../../../Buffers/buffer.js\";\nimport { ArrayTools } from \"../../../Misc/arrayTools.js\";\nimport { Observable } from \"../../../Misc/observable.js\";\nclass MeshAccumulator {\n /**\n * Constructor of the mesh accumulator\n * @param mesh - The mesh used to compute the world matrix.\n * @param collectIndices - use mesh indices\n * @param scene - The scene used to determine the right handed system.\n *\n * Merge mesh and its children so whole hierarchy can be used as a mesh shape or convex hull\n */\n constructor(mesh, collectIndices, scene) {\n this._vertices = []; /// Vertices in body space\n this._indices = [];\n this._isRightHanded = scene.useRightHandedSystem;\n this._collectIndices = collectIndices;\n }\n /**\n * Adds a mesh to the physics engine.\n * @param mesh The mesh to add.\n * @param includeChildren Whether to include the children of the mesh.\n *\n * This method adds a mesh to the physics engine by computing the world matrix,\n * multiplying it with the body from world matrix, and then transforming the\n * coordinates of the mesh's vertices. It also adds the indices of the mesh\n * to the physics engine. If includeChildren is true, it will also add the\n * children of the mesh to the physics engine, ignoring any children which\n * have a physics impostor. This is useful for creating a physics engine\n * that accurately reflects the mesh and its children.\n */\n addMesh(mesh, includeChildren) {\n const indexOffset = this._vertices.length;\n // Force absoluteScaling to be computed\n mesh.computeWorldMatrix(true);\n const shapeFromBody = TmpVectors.Matrix[0];\n Matrix.ScalingToRef(mesh.absoluteScaling.x, mesh.absoluteScaling.y, mesh.absoluteScaling.z, shapeFromBody);\n const vertexData = mesh.getVerticesData(VertexBuffer.PositionKind) || [];\n const numVerts = vertexData.length / 3;\n for (let v = 0; v < numVerts; v++) {\n const pos = new Vector3(vertexData[v * 3 + 0], vertexData[v * 3 + 1], vertexData[v * 3 + 2]);\n this._vertices.push(Vector3.TransformCoordinates(pos, shapeFromBody));\n }\n if (this._collectIndices) {\n const meshIndices = mesh.getIndices();\n if (meshIndices) {\n for (let i = 0; i < meshIndices.length; i += 3) {\n // Havok wants the correct triangle winding to enable the interior triangle optimization\n if (this._isRightHanded) {\n this._indices.push(meshIndices[i + 0] + indexOffset);\n this._indices.push(meshIndices[i + 1] + indexOffset);\n this._indices.push(meshIndices[i + 2] + indexOffset);\n }\n else {\n this._indices.push(meshIndices[i + 2] + indexOffset);\n this._indices.push(meshIndices[i + 1] + indexOffset);\n this._indices.push(meshIndices[i + 0] + indexOffset);\n }\n }\n }\n }\n if (includeChildren) {\n const children = mesh.getChildMeshes(false);\n // Ignore any children which have a physics body.\n // Other plugin implementations do not have this check, which appears to be\n // a bug, as otherwise, the mesh will have a duplicate collider\n children.filter((m) => !m.physicsBody).forEach((m) => this.addMesh(m, includeChildren));\n }\n }\n /**\n * Allocate and populate the vertex positions inside the physics plugin.\n *\n * @returns An array of floats, whose backing memory is inside the plugin. The array contains the\n * positions of the mesh vertices, where a position is defined by three floats. You must call\n * freeBuffer() on the returned array once you have finished with it, in order to free the\n * memory inside the plugin..\n */\n getVertices(plugin) {\n const nFloats = this._vertices.length * 3;\n const bytesPerFloat = 4;\n const nBytes = nFloats * bytesPerFloat;\n const bufferBegin = plugin._malloc(nBytes);\n const ret = new Float32Array(plugin.HEAPU8.buffer, bufferBegin, nFloats);\n for (let i = 0; i < this._vertices.length; i++) {\n ret[i * 3 + 0] = this._vertices[i].x;\n ret[i * 3 + 1] = this._vertices[i].y;\n ret[i * 3 + 2] = this._vertices[i].z;\n }\n return ret;\n }\n freeBuffer(plugin, arr) {\n plugin._free(arr.byteOffset);\n }\n /**\n * Allocate and populate the triangle indices inside the physics plugin\n *\n * @returns A new Int32Array, whose backing memory is inside the plugin. The array contains the indices\n * of the triangle positions, where a single triangle is defined by three indices. You must call\n * freeBuffer() on this array once you have finished with it, to free the memory inside the plugin..\n */\n getTriangles(plugin) {\n const bytesPerInt = 4;\n const nBytes = this._indices.length * bytesPerInt;\n const bufferBegin = plugin._malloc(nBytes);\n const ret = new Int32Array(plugin.HEAPU8.buffer, bufferBegin, this._indices.length);\n for (let i = 0; i < this._indices.length; i++) {\n ret[i] = this._indices[i];\n }\n return ret;\n }\n}\nclass BodyPluginData {\n constructor(bodyId) {\n this.hpBodyId = bodyId;\n this.userMassProps = { centerOfMass: undefined, mass: undefined, inertia: undefined, inertiaOrientation: undefined };\n }\n}\n/*\nclass ShapePath\n{\n public colliderId: number;\n public pathData: number;\n}\n*/\nclass ContactPoint {\n constructor() {\n this.bodyId = BigInt(0); //0,2\n //public colliderId: number = 0; //2,4\n //public shapePath: ShapePath = new ShapePath(); //4,8\n this.position = new Vector3(); //8,11\n this.normal = new Vector3(); //11,14\n //public triIdx: number = 0; //14,15\n }\n}\nclass CollisionEvent {\n constructor() {\n //public eventType: number = 0; //0,1\n this.contactOnA = new ContactPoint(); //1\n this.contactOnB = new ContactPoint();\n this.impulseApplied = 0;\n }\n static readToRef(buffer, offset, eventOut) {\n const intBuf = new Int32Array(buffer, offset);\n const floatBuf = new Float32Array(buffer, offset);\n const offA = 2;\n eventOut.contactOnA.bodyId = BigInt(intBuf[offA]); // 0) {\n for (const instance of body._pluginDataInstances) {\n this._bodyCollisionObservable.delete(instance.hpBodyId[0]);\n this._hknp.HP_World_RemoveBody(this.world, instance.hpBodyId);\n }\n }\n if (body._pluginData) {\n this._bodyCollisionObservable.delete(body._pluginData.hpBodyId[0]);\n this._hknp.HP_World_RemoveBody(this.world, body._pluginData.hpBodyId);\n }\n }\n /**\n * Initializes the body instances for a given physics body and mesh.\n *\n * @param body - The physics body to initialize.\n * @param motionType - How the body will be handled by the engine\n * @param mesh - The mesh to initialize.\n *\n * This code is useful for creating a physics body from a mesh. It creates a\n * body instance for each instance of the mesh and adds it to the world. It also\n * sets the position of the body instance to the position of the mesh instance.\n * This allows for the physics engine to accurately simulate the mesh in the\n * world.\n */\n initBodyInstances(body, motionType, mesh) {\n var _a, _b;\n const instancesCount = (_b = (_a = mesh._thinInstanceDataStorage) === null || _a === void 0 ? void 0 : _a.instancesCount) !== null && _b !== void 0 ? _b : 0;\n const matrixData = mesh._thinInstanceDataStorage.matrixData;\n if (!matrixData) {\n return; // TODO: error handling\n }\n this._createOrUpdateBodyInstances(body, motionType, matrixData, 0, instancesCount, false);\n body._pluginDataInstances.forEach((bodyId, index) => {\n this._bodies.set(bodyId.hpBodyId[0], { body: body, index: index });\n });\n }\n _createOrUpdateBodyInstances(body, motionType, matrixData, startIndex, endIndex, update) {\n const rotation = TmpVectors.Quaternion[0];\n const rotationMatrix = Matrix.Identity();\n for (let i = startIndex; i < endIndex; i++) {\n const position = [matrixData[i * 16 + 12], matrixData[i * 16 + 13], matrixData[i * 16 + 14]];\n let hkbody;\n if (!update) {\n hkbody = this._hknp.HP_Body_Create()[1];\n }\n else {\n hkbody = body._pluginDataInstances[i].hpBodyId;\n }\n rotationMatrix.setRowFromFloats(0, matrixData[i * 16 + 0], matrixData[i * 16 + 1], matrixData[i * 16 + 2], 0);\n rotationMatrix.setRowFromFloats(1, matrixData[i * 16 + 4], matrixData[i * 16 + 5], matrixData[i * 16 + 6], 0);\n rotationMatrix.setRowFromFloats(2, matrixData[i * 16 + 8], matrixData[i * 16 + 9], matrixData[i * 16 + 10], 0);\n Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);\n const transform = [position, [rotation.x, rotation.y, rotation.z, rotation.w]];\n this._hknp.HP_Body_SetQTransform(hkbody, transform);\n if (!update) {\n const pluginData = new BodyPluginData(hkbody);\n if (body._pluginDataInstances.length) {\n // If an instance already exists, copy any user-provided mass properties\n pluginData.userMassProps = body._pluginDataInstances[0].userMassProps;\n }\n this._internalSetMotionType(pluginData, motionType);\n this._internalUpdateMassProperties(pluginData);\n body._pluginDataInstances.push(pluginData);\n this._hknp.HP_World_AddBody(this.world, hkbody, body.startAsleep);\n pluginData.worldTransformOffset = this._hknp.HP_Body_GetWorldTransformOffset(hkbody)[1];\n }\n }\n }\n /**\n * Update the internal body instances for a given physics body to match the instances in a mesh.\n * @param body the body that will be updated\n * @param mesh the mesh with reference instances\n */\n updateBodyInstances(body, mesh) {\n var _a, _b;\n const instancesCount = (_b = (_a = mesh._thinInstanceDataStorage) === null || _a === void 0 ? void 0 : _a.instancesCount) !== null && _b !== void 0 ? _b : 0;\n const matrixData = mesh._thinInstanceDataStorage.matrixData;\n if (!matrixData) {\n return; // TODO: error handling\n }\n const pluginInstancesCount = body._pluginDataInstances.length;\n const motionType = this.getMotionType(body);\n if (instancesCount > pluginInstancesCount) {\n this._createOrUpdateBodyInstances(body, motionType, matrixData, pluginInstancesCount, instancesCount, false);\n const firstBodyShape = this._hknp.HP_Body_GetShape(body._pluginDataInstances[0].hpBodyId)[1];\n for (let i = pluginInstancesCount; i < instancesCount; i++) {\n this._hknp.HP_Body_SetShape(body._pluginDataInstances[i].hpBodyId, firstBodyShape);\n this._internalUpdateMassProperties(body._pluginDataInstances[i]);\n this._bodies.set(body._pluginDataInstances[i].hpBodyId[0], { body: body, index: i });\n }\n }\n else if (instancesCount < pluginInstancesCount) {\n const instancesToRemove = pluginInstancesCount - instancesCount;\n for (let i = 0; i < instancesToRemove; i++) {\n const hkbody = body._pluginDataInstances.pop();\n this._bodies.delete(hkbody.hpBodyId[0]);\n this._hknp.HP_World_RemoveBody(this.world, hkbody.hpBodyId);\n this._hknp.HP_Body_Release(hkbody.hpBodyId);\n }\n this._createOrUpdateBodyInstances(body, motionType, matrixData, 0, instancesCount, true);\n }\n }\n /**\n * Synchronizes the transform of a physics body with its transform node.\n * @param body - The physics body to synchronize.\n *\n * This function is useful for keeping the physics body's transform in sync with its transform node.\n * This is important for ensuring that the physics body is accurately represented in the physics engine.\n */\n sync(body) {\n this.syncTransform(body, body.transformNode);\n }\n /**\n * Synchronizes the transform of a physics body with the transform of its\n * corresponding transform node.\n *\n * @param body - The physics body to synchronize.\n * @param transformNode - The destination Transform Node.\n *\n * This code is useful for synchronizing the position and orientation of a\n * physics body with the position and orientation of its corresponding\n * transform node. This is important for ensuring that the physics body and\n * the transform node are in the same position and orientation in the scene.\n * This is necessary for the physics engine to accurately simulate the\n * physical behavior of the body.\n */\n syncTransform(body, transformNode) {\n var _a;\n if (body._pluginDataInstances.length) {\n // instances\n const m = transformNode;\n const matrixData = m._thinInstanceDataStorage.matrixData;\n if (!matrixData) {\n return; // TODO: error handling\n }\n const instancesCount = body._pluginDataInstances.length;\n for (let i = 0; i < instancesCount; i++) {\n const bufOffset = body._pluginDataInstances[i].worldTransformOffset;\n const transformBuffer = new Float32Array(this._hknp.HEAPU8.buffer, this._bodyBuffer + bufOffset, 16);\n const index = i * 16;\n for (let mi = 0; mi < 15; mi++) {\n if ((mi & 3) != 3) {\n matrixData[index + mi] = transformBuffer[mi];\n }\n }\n matrixData[index + 15] = 1;\n }\n m.thinInstanceBufferUpdated(\"matrix\");\n }\n else {\n try {\n // regular\n const bodyTransform = this._hknp.HP_Body_GetQTransform(body._pluginData.hpBodyId)[1];\n const bodyTranslation = bodyTransform[0];\n const bodyOrientation = bodyTransform[1];\n const quat = TmpVectors.Quaternion[0];\n quat.set(bodyOrientation[0], bodyOrientation[1], bodyOrientation[2], bodyOrientation[3]);\n const parent = transformNode.parent;\n // transform position/orientation in parent space\n if (parent && !parent.getWorldMatrix().isIdentity()) {\n parent.computeWorldMatrix(true);\n quat.normalize();\n const finalTransform = TmpVectors.Matrix[0];\n const finalTranslation = TmpVectors.Vector3[0];\n finalTranslation.copyFromFloats(bodyTranslation[0], bodyTranslation[1], bodyTranslation[2]);\n Matrix.ComposeToRef(transformNode.absoluteScaling, quat, finalTranslation, finalTransform);\n const parentInverseTransform = TmpVectors.Matrix[1];\n parent.getWorldMatrix().invertToRef(parentInverseTransform);\n const localTransform = TmpVectors.Matrix[2];\n finalTransform.multiplyToRef(parentInverseTransform, localTransform);\n localTransform.decomposeToTransformNode(transformNode);\n (_a = transformNode.rotationQuaternion) === null || _a === void 0 ? void 0 : _a.normalize();\n }\n else {\n transformNode.position.set(bodyTranslation[0], bodyTranslation[1], bodyTranslation[2]);\n if (transformNode.rotationQuaternion) {\n transformNode.rotationQuaternion.copyFrom(quat);\n }\n else {\n quat.toEulerAnglesToRef(transformNode.rotation);\n }\n }\n }\n catch (e) {\n console.log(`Syncing transform failed for node ${transformNode.name}: ${e.message}...`);\n }\n }\n }\n /**\n * Sets the shape of a physics body.\n * @param body - The physics body to set the shape for.\n * @param shape - The physics shape to set.\n *\n * This function is used to set the shape of a physics body. It is useful for\n * creating a physics body with a specific shape, such as a box or a sphere,\n * which can then be used to simulate physical interactions in a physics engine.\n * This function is especially useful for meshes with multiple instances, as it\n * will set the shape for each instance of the mesh.\n */\n setShape(body, shape) {\n var _a, _b, _c;\n const shapeHandle = shape && shape._pluginData ? shape._pluginData : BigInt(0);\n if (!(body.transformNode instanceof Mesh) || !((_a = body.transformNode._thinInstanceDataStorage) === null || _a === void 0 ? void 0 : _a.matrixData)) {\n this._hknp.HP_Body_SetShape(body._pluginData.hpBodyId, shapeHandle);\n this._internalUpdateMassProperties(body._pluginData);\n return;\n }\n const m = body.transformNode;\n const instancesCount = (_c = (_b = m._thinInstanceDataStorage) === null || _b === void 0 ? void 0 : _b.instancesCount) !== null && _c !== void 0 ? _c : 0;\n for (let i = 0; i < instancesCount; i++) {\n this._hknp.HP_Body_SetShape(body._pluginDataInstances[i].hpBodyId, shapeHandle);\n this._internalUpdateMassProperties(body._pluginDataInstances[i]);\n }\n }\n /**\n * Returns a reference to the first instance of the plugin data for a physics body.\n * @param body\n * @param instanceIndex\n * @returns a reference to the first instance\n */\n _getPluginReference(body, instanceIndex) {\n var _a;\n return ((_a = body._pluginDataInstances) === null || _a === void 0 ? void 0 : _a.length) ? body._pluginDataInstances[instanceIndex !== null && instanceIndex !== void 0 ? instanceIndex : 0] : body._pluginData;\n }\n /**\n * Gets the shape of a physics body. This will create a new shape object\n *\n * @param body - The physics body.\n * @returns The shape of the physics body.\n *\n */\n getShape(body) {\n const pluginRef = this._getPluginReference(body);\n const shapePluginData = this._hknp.HP_Body_GetShape(pluginRef.hpBodyId)[1];\n if (shapePluginData != 0) {\n const scene = body.transformNode.getScene();\n return new PhysicsShape({ pluginData: shapePluginData }, scene);\n }\n return null;\n }\n /**\n * Gets the type of a physics shape.\n * @param shape - The physics shape to get the type for.\n * @returns The type of the physics shape.\n *\n */\n getShapeType(shape) {\n if (shape.type) {\n return shape.type;\n }\n else {\n // {\n this._hknp.HP_Body_SetEventMask(bodyPluginData.hpBodyId, eventMask);\n }, instanceIndex);\n }\n /**\n * Retrieves the event mask of a physics body.\n *\n * @param body - The physics body to retrieve the event mask from.\n * @returns The event mask of the physics body.\n *\n */\n getEventMask(body, instanceIndex) {\n const pluginRef = this._getPluginReference(body, instanceIndex);\n return this._hknp.HP_Body_GetEventMask(pluginRef.hpBodyId)[1];\n }\n _fromMassPropertiesTuple(massPropsTuple) {\n return {\n centerOfMass: Vector3.FromArray(massPropsTuple[0]),\n mass: massPropsTuple[1],\n inertia: Vector3.FromArray(massPropsTuple[2]),\n inertiaOrientation: Quaternion.FromArray(massPropsTuple[3]),\n };\n }\n _internalUpdateMassProperties(pluginData) {\n // Recompute the mass based on the shape\n const newProps = this._internalComputeMassProperties(pluginData);\n const massProps = pluginData.userMassProps;\n // Override the computed values with any the user has set\n if (massProps.centerOfMass) {\n newProps[0] = massProps.centerOfMass.asArray();\n }\n if (massProps.mass != undefined) {\n newProps[1] = massProps.mass;\n }\n if (massProps.inertia) {\n newProps[2] = massProps.inertia.asArray();\n }\n if (massProps.inertiaOrientation) {\n newProps[3] = massProps.inertiaOrientation.asArray();\n }\n this._hknp.HP_Body_SetMassProperties(pluginData.hpBodyId, newProps);\n }\n _internalSetMotionType(pluginData, motionType) {\n switch (motionType) {\n case PhysicsMotionType.STATIC:\n this._hknp.HP_Body_SetMotionType(pluginData.hpBodyId, this._hknp.MotionType.STATIC);\n break;\n case PhysicsMotionType.ANIMATED:\n this._hknp.HP_Body_SetMotionType(pluginData.hpBodyId, this._hknp.MotionType.KINEMATIC);\n break;\n case PhysicsMotionType.DYNAMIC:\n this._hknp.HP_Body_SetMotionType(pluginData.hpBodyId, this._hknp.MotionType.DYNAMIC);\n break;\n }\n }\n setMotionType(body, motionType, instanceIndex) {\n this._applyToBodyOrInstances(body, (pluginData) => {\n this._internalSetMotionType(pluginData, motionType);\n }, instanceIndex);\n }\n getMotionType(body, instanceIndex) {\n const pluginRef = this._getPluginReference(body, instanceIndex);\n const type = this._hknp.HP_Body_GetMotionType(pluginRef.hpBodyId)[1];\n switch (type) {\n case this._hknp.MotionType.STATIC:\n return PhysicsMotionType.STATIC;\n case this._hknp.MotionType.KINEMATIC:\n return PhysicsMotionType.ANIMATED;\n case this._hknp.MotionType.DYNAMIC:\n return PhysicsMotionType.DYNAMIC;\n }\n throw new Error(\"Unknown motion type: \" + type);\n }\n _internalComputeMassProperties(pluginData) {\n const shapeRes = this._hknp.HP_Body_GetShape(pluginData.hpBodyId);\n if (shapeRes[0] == this._hknp.Result.RESULT_OK) {\n const shapeMass = this._hknp.HP_Shape_BuildMassProperties(shapeRes[1]);\n if (shapeMass[0] == this._hknp.Result.RESULT_OK) {\n return shapeMass[1];\n }\n }\n // Failed; return a unit inertia\n return [[0, 0, 0], 1, [1, 1, 1], [0, 0, 0, 1]];\n }\n /**\n * Computes the mass properties of a physics body, from it's shape\n *\n * @param body - The physics body to copmute the mass properties of\n */\n computeMassProperties(body, instanceIndex) {\n const pluginRef = this._getPluginReference(body, instanceIndex);\n const computed = this._internalComputeMassProperties(pluginRef);\n return this._fromMassPropertiesTuple(computed);\n }\n /**\n * Sets the mass properties of a physics body.\n *\n * @param body - The physics body to set the mass properties of.\n * @param massProps - The mass properties to set.\n * @param instanceIndex - The index of the instance to set the mass properties of. If undefined, the mass properties of all the bodies will be set.\n * This function is useful for setting the mass properties of a physics body,\n * such as its mass, inertia, and center of mass. This is important for\n * accurately simulating the physics of the body in the physics engine.\n *\n */\n setMassProperties(body, massProps, instanceIndex) {\n this._applyToBodyOrInstances(body, (pluginData) => {\n pluginData.userMassProps = massProps;\n this._internalUpdateMassProperties(pluginData);\n }, instanceIndex);\n }\n /**\n *\n */\n getMassProperties(body, instanceIndex) {\n const pluginRef = this._getPluginReference(body, instanceIndex);\n const massPropsTuple = this._hknp.HP_Body_GetMassProperties(pluginRef.hpBodyId)[1];\n return this._fromMassPropertiesTuple(massPropsTuple);\n }\n /**\n * Sets the linear damping of the given body.\n * @param body - The body to set the linear damping for.\n * @param damping - The linear damping to set.\n *\n * This method is useful for controlling the linear damping of a body in a physics engine.\n * Linear damping is a force that opposes the motion of the body, and is proportional to the velocity of the body.\n * This method allows the user to set the linear damping of a body, which can be used to control the motion of the body.\n */\n setLinearDamping(body, damping, instanceIndex) {\n this._applyToBodyOrInstances(body, (pluginData) => {\n this._hknp.HP_Body_SetLinearDamping(pluginData.hpBodyId, damping);\n }, instanceIndex);\n }\n /**\n * Gets the linear damping of the given body.\n * @param body - The body to get the linear damping from.\n * @returns The linear damping of the given body.\n *\n * This method is useful for getting the linear damping of a body in a physics engine.\n * Linear damping is a force that opposes the motion of the body and is proportional to the velocity of the body.\n * It is used to simulate the effects of air resistance and other forms of friction.\n */\n getLinearDamping(body, instanceIndex) {\n const pluginRef = this._getPluginReference(body, instanceIndex);\n return this._hknp.HP_Body_GetLinearDamping(pluginRef.hpBodyId)[1];\n }\n /**\n * Sets the angular damping of a physics body.\n * @param body - The physics body to set the angular damping for.\n * @param damping - The angular damping value to set.\n *\n * This function is useful for controlling the angular velocity of a physics body.\n * By setting the angular damping, the body's angular velocity will be reduced over time, allowing for more realistic physics simulations.\n */\n setAngularDamping(body, damping, instanceIndex) {\n this._applyToBodyOrInstances(body, (pluginData) => {\n this._hknp.HP_Body_SetAngularDamping(pluginData.hpBodyId, damping);\n }, instanceIndex);\n }\n /**\n * Gets the angular damping of a physics body.\n * @param body - The physics body to get the angular damping from.\n * @returns The angular damping of the body.\n *\n * This function is useful for retrieving the angular damping of a physics body,\n * which is used to control the rotational motion of the body. The angular damping is a value between 0 and 1, where 0 is no damping and 1 is full damping.\n */\n getAngularDamping(body, instanceIndex) {\n const pluginRef = this._getPluginReference(body, instanceIndex);\n return this._hknp.HP_Body_GetAngularDamping(pluginRef.hpBodyId)[1];\n }\n /**\n * Sets the linear velocity of a physics body.\n * @param body - The physics body to set the linear velocity of.\n * @param linVel - The linear velocity to set.\n *\n * This function is useful for setting the linear velocity of a physics body, which is necessary for simulating\n * motion in a physics engine. The linear velocity is the speed and direction of the body's movement.\n */\n setLinearVelocity(body, linVel, instanceIndex) {\n this._applyToBodyOrInstances(body, (pluginData) => {\n this._hknp.HP_Body_SetLinearVelocity(pluginData.hpBodyId, this._bVecToV3(linVel));\n }, instanceIndex);\n }\n /**\n * Gets the linear velocity of a physics body and stores it in a given vector.\n * @param body - The physics body to get the linear velocity from.\n * @param linVel - The vector to store the linear velocity in.\n *\n * This function is useful for retrieving the linear velocity of a physics body,\n * which can be used to determine the speed and direction of the body. This\n * information can be used to simulate realistic physics behavior in a game.\n */\n getLinearVelocityToRef(body, linVel, instanceIndex) {\n const pluginRef = this._getPluginReference(body, instanceIndex);\n const lv = this._hknp.HP_Body_GetLinearVelocity(pluginRef.hpBodyId)[1];\n this._v3ToBvecRef(lv, linVel);\n }\n /*\n * Apply an operation either to all instances of a body, if instanceIndex is not specified, or to a specific instance.\n */\n _applyToBodyOrInstances(body, fnToApply, instanceIndex) {\n var _a;\n if (((_a = body._pluginDataInstances) === null || _a === void 0 ? void 0 : _a.length) > 0 && instanceIndex === undefined) {\n for (let i = 0; i < body._pluginDataInstances.length; i++) {\n fnToApply(body._pluginDataInstances[i]);\n }\n }\n else {\n fnToApply(this._getPluginReference(body, instanceIndex));\n }\n }\n /**\n * Applies an impulse to a physics body at a given location.\n * @param body - The physics body to apply the impulse to.\n * @param impulse - The impulse vector to apply.\n * @param location - The location in world space to apply the impulse.\n * @param instanceIndex - The index of the instance to apply the impulse to. If not specified, the impulse will be applied to all instances.\n *\n * This method is useful for applying an impulse to a physics body at a given location.\n * This can be used to simulate physical forces such as explosions, collisions, and gravity.\n */\n applyImpulse(body, impulse, location, instanceIndex) {\n this._applyToBodyOrInstances(body, (pluginRef) => {\n this._hknp.HP_Body_ApplyImpulse(pluginRef.hpBodyId, this._bVecToV3(location), this._bVecToV3(impulse));\n }, instanceIndex);\n }\n /**\n * Applies a force to a physics body at a given location.\n * @param body - The physics body to apply the impulse to.\n * @param force - The force vector to apply.\n * @param location - The location in world space to apply the impulse.\n * @param instanceIndex - The index of the instance to apply the force to. If not specified, the force will be applied to all instances.\n *\n * This method is useful for applying a force to a physics body at a given location.\n * This can be used to simulate physical forces such as explosions, collisions, and gravity.\n */\n applyForce(body, force, location, instanceIndex) {\n force.scaleToRef(this.getTimeStep(), this._tmpVec3[0]);\n this.applyImpulse(body, this._tmpVec3[0], location, instanceIndex);\n }\n /**\n * Sets the angular velocity of a physics body.\n *\n * @param body - The physics body to set the angular velocity of.\n * @param angVel - The angular velocity to set.\n *\n * This function is useful for setting the angular velocity of a physics body in a physics engine.\n * This allows for more realistic simulations of physical objects, as they can be given a rotational velocity.\n */\n setAngularVelocity(body, angVel, instanceIndex) {\n this._applyToBodyOrInstances(body, (pluginRef) => {\n this._hknp.HP_Body_SetAngularVelocity(pluginRef.hpBodyId, this._bVecToV3(angVel));\n }, instanceIndex);\n }\n /**\n * Gets the angular velocity of a body.\n * @param body - The body to get the angular velocity from.\n * @param angVel - The vector3 to store the angular velocity.\n *\n * This method is useful for getting the angular velocity of a body in a physics engine. It\n * takes the body and a vector3 as parameters and stores the angular velocity of the body\n * in the vector3. This is useful for getting the angular velocity of a body in order to\n * calculate the motion of the body in the physics engine.\n */\n getAngularVelocityToRef(body, angVel, instanceIndex) {\n const pluginRef = this._getPluginReference(body, instanceIndex);\n const av = this._hknp.HP_Body_GetAngularVelocity(pluginRef.hpBodyId)[1];\n this._v3ToBvecRef(av, angVel);\n }\n /**\n * Sets the transformation of the given physics body to the given transform node.\n * @param body The physics body to set the transformation for.\n * @param node The transform node to set the transformation from.\n * Sets the transformation of the given physics body to the given transform node.\n *\n * This function is useful for setting the transformation of a physics body to a\n * transform node, which is necessary for the physics engine to accurately simulate\n * the motion of the body. It also takes into account instances of the transform\n * node, which is necessary for accurate simulation of multiple bodies with the\n * same transformation.\n */\n setPhysicsBodyTransformation(body, node) {\n const transformNode = body.transformNode;\n if (body.numInstances > 0) {\n // instances\n const m = transformNode;\n const matrixData = m._thinInstanceDataStorage.matrixData;\n if (!matrixData) {\n return; // TODO: error handling\n }\n const instancesCount = body.numInstances;\n this._createOrUpdateBodyInstances(body, body.getMotionType(), matrixData, 0, instancesCount, true);\n }\n else {\n // regular\n this._hknp.HP_Body_SetQTransform(body._pluginData.hpBodyId, this._getTransformInfos(node));\n }\n }\n /**\n * Sets the gravity factor of a body\n * @param body the physics body to set the gravity factor for\n * @param factor the gravity factor\n * @param instanceIndex the index of the instance in an instanced body\n */\n setGravityFactor(body, factor, instanceIndex) {\n this._applyToBodyOrInstances(body, (pluginRef) => {\n this._hknp.HP_Body_SetGravityFactor(pluginRef.hpBodyId, factor);\n }, instanceIndex);\n }\n /**\n * Get the gravity factor of a body\n * @param body the physics body to get the gravity factor from\n * @param instanceIndex the index of the instance in an instanced body. If not specified, the gravity factor of the first instance will be returned.\n * @returns the gravity factor\n */\n getGravityFactor(body, instanceIndex) {\n const pluginRef = this._getPluginReference(body, instanceIndex);\n return this._hknp.HP_Body_GetGravityFactor(pluginRef.hpBodyId)[1];\n }\n /**\n * Disposes a physics body.\n *\n * @param body - The physics body to dispose.\n *\n * This method is useful for releasing the resources associated with a physics body when it is no longer needed.\n * This is important for avoiding memory leaks in the physics engine.\n */\n disposeBody(body) {\n if (body._pluginDataInstances && body._pluginDataInstances.length > 0) {\n for (const instance of body._pluginDataInstances) {\n this._hknp.HP_Body_Release(instance.hpBodyId);\n instance.hpBodyId = undefined;\n }\n }\n if (body._pluginData) {\n this._hknp.HP_Body_Release(body._pluginData.hpBodyId);\n body._pluginData.hpBodyId = undefined;\n }\n }\n /**\n * Initializes a physics shape with the given type and parameters.\n * @param shape - The physics shape to initialize.\n * @param type - The type of shape to initialize.\n * @param options - The parameters for the shape.\n *\n * This code is useful for initializing a physics shape with the given type and parameters.\n * It allows for the creation of a sphere, box, capsule, container, cylinder, mesh, and heightfield.\n * Depending on the type of shape, different parameters are required.\n * For example, a sphere requires a radius, while a box requires extents and a rotation.\n */\n initShape(shape, type, options) {\n switch (type) {\n case PhysicsShapeType.SPHERE:\n {\n const radius = options.radius || 1;\n const center = options.center ? this._bVecToV3(options.center) : [0, 0, 0];\n shape._pluginData = this._hknp.HP_Shape_CreateSphere(center, radius)[1];\n }\n break;\n case PhysicsShapeType.BOX:\n {\n const rotation = options.rotation ? this._bQuatToV4(options.rotation) : [0, 0, 0, 1];\n const extent = options.extents ? this._bVecToV3(options.extents) : [1, 1, 1];\n const center = options.center ? this._bVecToV3(options.center) : [0, 0, 0];\n shape._pluginData = this._hknp.HP_Shape_CreateBox(center, rotation, extent)[1];\n }\n break;\n case PhysicsShapeType.CAPSULE:\n {\n const pointA = options.pointA ? this._bVecToV3(options.pointA) : [0, 0, 0];\n const pointB = options.pointB ? this._bVecToV3(options.pointB) : [0, 1, 0];\n const radius = options.radius || 0;\n shape._pluginData = this._hknp.HP_Shape_CreateCapsule(pointA, pointB, radius)[1];\n }\n break;\n case PhysicsShapeType.CONTAINER:\n {\n shape._pluginData = this._hknp.HP_Shape_CreateContainer()[1];\n }\n break;\n case PhysicsShapeType.CYLINDER:\n {\n const pointA = options.pointA ? this._bVecToV3(options.pointA) : [0, 0, 0];\n const pointB = options.pointB ? this._bVecToV3(options.pointB) : [0, 1, 0];\n const radius = options.radius || 0;\n shape._pluginData = this._hknp.HP_Shape_CreateCylinder(pointA, pointB, radius)[1];\n }\n break;\n case PhysicsShapeType.CONVEX_HULL:\n case PhysicsShapeType.MESH:\n {\n const mesh = options.mesh;\n if (mesh) {\n const includeChildMeshes = !!options.includeChildMeshes;\n const needIndices = type != PhysicsShapeType.CONVEX_HULL;\n const accum = new MeshAccumulator(mesh, needIndices, mesh === null || mesh === void 0 ? void 0 : mesh.getScene());\n accum.addMesh(mesh, includeChildMeshes);\n const positions = accum.getVertices(this._hknp);\n const numVec3s = positions.length / 3;\n if (type == PhysicsShapeType.CONVEX_HULL) {\n shape._pluginData = this._hknp.HP_Shape_CreateConvexHull(positions.byteOffset, numVec3s)[1];\n }\n else {\n const triangles = accum.getTriangles(this._hknp);\n const numTriangles = triangles.length / 3;\n shape._pluginData = this._hknp.HP_Shape_CreateMesh(positions.byteOffset, numVec3s, triangles.byteOffset, numTriangles)[1];\n accum.freeBuffer(this._hknp, triangles);\n }\n accum.freeBuffer(this._hknp, positions);\n }\n else {\n throw new Error(\"No mesh provided to create physics shape.\");\n }\n }\n break;\n default:\n throw new Error(\"Unsupported Shape Type.\");\n break;\n }\n }\n setShapeFilterMembershipMask(shape, membershipMask) {\n const collideWith = this._hknp.HP_Shape_GetFilterInfo(shape._pluginData)[1][1];\n this._hknp.HP_Shape_SetFilterInfo(shape._pluginData, [membershipMask, collideWith]);\n }\n getShapeFilterMembershipMask(shape) {\n return this._hknp.HP_Shape_GetFilterInfo(shape._pluginData)[1][0];\n }\n setShapeFilterCollideMask(shape, collideMask) {\n const membership = this._hknp.HP_Shape_GetFilterInfo(shape._pluginData)[1][0];\n this._hknp.HP_Shape_SetFilterInfo(shape._pluginData, [membership, collideMask]);\n }\n getShapeFilterCollideMask(shape) {\n return this._hknp.HP_Shape_GetFilterInfo(shape._pluginData)[1][1];\n }\n /**\n * Sets the material of a physics shape.\n * @param shape - The physics shape to set the material of.\n * @param material - The material to set.\n *\n */\n setMaterial(shape, material) {\n var _a, _b, _c, _d, _e;\n const dynamicFriction = (_a = material.friction) !== null && _a !== void 0 ? _a : 0.5;\n const staticFriction = (_b = material.staticFriction) !== null && _b !== void 0 ? _b : dynamicFriction;\n const restitution = (_c = material.restitution) !== null && _c !== void 0 ? _c : 0.0;\n const frictionCombine = (_d = material.frictionCombine) !== null && _d !== void 0 ? _d : PhysicsMaterialCombineMode.MINIMUM;\n const restitutionCombine = (_e = material.restitutionCombine) !== null && _e !== void 0 ? _e : PhysicsMaterialCombineMode.MAXIMUM;\n const hpMaterial = [staticFriction, dynamicFriction, restitution, this._materialCombineToNative(frictionCombine), this._materialCombineToNative(restitutionCombine)];\n this._hknp.HP_Shape_SetMaterial(shape._pluginData, hpMaterial);\n }\n /**\n * Sets the density of a physics shape.\n * @param shape - The physics shape to set the density of.\n * @param density - The density to set.\n *\n */\n setDensity(shape, density) {\n this._hknp.HP_Shape_SetDensity(shape._pluginData, density);\n }\n /**\n * Calculates the density of a given physics shape.\n *\n * @param shape - The physics shape to calculate the density of.\n * @returns The density of the given physics shape.\n *\n */\n getDensity(shape) {\n return this._hknp.HP_Shape_GetDensity(shape._pluginData)[1];\n }\n /**\n * Gets the transform infos of a given transform node.\n * @param node - The transform node.\n * @returns An array containing the position and orientation of the node.\n * This code is useful for getting the position and orientation of a given transform node.\n * It first checks if the node has a rotation quaternion, and if not, it creates one from the node's rotation.\n * It then creates an array containing the position and orientation of the node and returns it.\n */\n _getTransformInfos(node) {\n if (node.parent) {\n node.computeWorldMatrix(true);\n return [this._bVecToV3(node.absolutePosition), this._bQuatToV4(node.absoluteRotationQuaternion)];\n }\n let orientation = TmpVectors.Quaternion[0];\n if (node.rotationQuaternion) {\n orientation = node.rotationQuaternion;\n }\n else {\n const r = node.rotation;\n Quaternion.FromEulerAnglesToRef(r.x, r.y, r.z, orientation);\n }\n const transform = [this._bVecToV3(node.position), this._bQuatToV4(orientation)];\n return transform;\n }\n /**\n * Adds a child shape to the given shape.\n * @param shape - The parent shape.\n * @param newChild - The child shape to add.\n * @param childTransform - The transform of the child shape relative to the parent shape.\n *\n */\n addChild(shape, newChild, translation, rotation, scale) {\n const transformNative = [\n translation ? this._bVecToV3(translation) : [0, 0, 0],\n rotation ? this._bQuatToV4(rotation) : [0, 0, 0, 1],\n scale ? this._bVecToV3(scale) : [1, 1, 1],\n ];\n this._hknp.HP_Shape_AddChild(shape._pluginData, newChild._pluginData, transformNative);\n }\n /**\n * Removes a child shape from a parent shape.\n * @param shape - The parent shape.\n * @param childIndex - The index of the child shape to remove.\n *\n */\n removeChild(shape, childIndex) {\n this._hknp.HP_Shape_RemoveChild(shape._pluginData, childIndex);\n }\n /**\n * Returns the number of children of the given shape.\n *\n * @param shape - The shape to get the number of children from.\n * @returns The number of children of the given shape.\n *\n */\n getNumChildren(shape) {\n return this._hknp.HP_Shape_GetNumChildren(shape._pluginData)[1];\n }\n /**\n * Calculates the bounding box of a given physics shape.\n *\n * @param shape - The physics shape to calculate the bounding box for.\n * @returns The calculated bounding box.\n *\n * This method is useful for physics engines as it allows to calculate the\n * boundaries of a given shape. Knowing the boundaries of a shape is important\n * for collision detection and other physics calculations.\n */\n getBoundingBox(shape) {\n return {};\n }\n /**\n * Gets the geometry of a physics body.\n *\n * @param body - The physics body.\n * @returns An object containing the positions and indices of the body's geometry.\n *\n */\n getBodyGeometry(body) {\n var _a;\n const dataInfo = ((_a = body._pluginDataInstances) === null || _a === void 0 ? void 0 : _a.length) > 0 ? body._pluginDataInstances[0] : body._pluginData;\n const shape = this._hknp.HP_Body_GetShape(dataInfo.hpBodyId)[1];\n const geometryRes = this._hknp.HP_Shape_CreateDebugDisplayGeometry(shape);\n if (geometryRes[0] != this._hknp.Result.RESULT_OK) {\n return { positions: [], indices: [] };\n }\n const geometryInfo = this._hknp.HP_DebugGeometry_GetInfo(geometryRes[1])[1];\n const positionsInPlugin = new Float32Array(this._hknp.HEAPU8.buffer, geometryInfo[0], geometryInfo[1] * 3); // 3 floats per position\n const indicesInPlugin = new Uint32Array(this._hknp.HEAPU8.buffer, geometryInfo[2], geometryInfo[3] * 3); // 3 indices per triangle\n // HP_DebugGeometry_Release will free the buffer in the plugin. To avoid a\n // use-after-free, we need to make a copy of the data here.\n const positions = positionsInPlugin.slice(0);\n const indices = indicesInPlugin.slice(0);\n this._hknp.HP_DebugGeometry_Release(geometryRes[1]);\n return { positions: positions, indices: indices };\n }\n /**\n * Releases a physics shape from the physics engine.\n *\n * @param shape - The physics shape to be released.\n * @returns void\n *\n * This method is useful for releasing a physics shape from the physics engine, freeing up resources and preventing memory leaks.\n */\n disposeShape(shape) {\n this._hknp.HP_Shape_Release(shape._pluginData);\n shape._pluginData = undefined;\n }\n // constraint\n /**\n * Initializes a physics constraint with the given parameters.\n *\n * @param constraint - The physics constraint to be initialized.\n * @param body - The main body\n * @param childBody - The child body.\n * @param instanceIndex - If this body is instanced, the index of the instance to which the constraint will be applied. If not specified, no constraint will be applied.\n * @param childInstanceIndex - If the child body is instanced, the index of the instance to which the constraint will be applied. If not specified, no constraint will be applied.\n *\n * This function is useful for setting up a physics constraint in a physics engine.\n */\n initConstraint(constraint, body, childBody, instanceIndex, childInstanceIndex) {\n var _a, _b, _c, _d;\n const type = constraint.type;\n const options = constraint.options;\n if (!type || !options) {\n Logger.Warn(\"No constraint type or options. Constraint is invalid.\");\n return;\n }\n if ((body._pluginDataInstances.length > 0 && instanceIndex === undefined) || (childBody._pluginDataInstances.length > 0 && childInstanceIndex === undefined)) {\n Logger.Warn(\"Body is instanced but no instance index was specified. Constraint will not be applied.\");\n return;\n }\n const jointId = this._hknp.HP_Constraint_Create()[1];\n constraint._pluginData = jointId;\n // body parenting\n const bodyA = this._getPluginReference(body, instanceIndex).hpBodyId;\n const bodyB = this._getPluginReference(childBody, childInstanceIndex).hpBodyId;\n this._hknp.HP_Constraint_SetParentBody(jointId, bodyA);\n this._hknp.HP_Constraint_SetChildBody(jointId, bodyB);\n // anchors\n const pivotA = options.pivotA ? this._bVecToV3(options.pivotA) : this._bVecToV3(Vector3.Zero());\n const axisA = (_a = options.axisA) !== null && _a !== void 0 ? _a : new Vector3(1, 0, 0);\n const perpAxisA = this._tmpVec3[0];\n if (options.perpAxisA) {\n perpAxisA.copyFrom(options.perpAxisA);\n }\n else {\n axisA.getNormalToRef(perpAxisA);\n }\n this._hknp.HP_Constraint_SetAnchorInParent(jointId, pivotA, this._bVecToV3(axisA), this._bVecToV3(perpAxisA));\n const pivotB = options.pivotB ? this._bVecToV3(options.pivotB) : this._bVecToV3(Vector3.Zero());\n const axisB = (_b = options.axisB) !== null && _b !== void 0 ? _b : new Vector3(1, 0, 0);\n const perpAxisB = this._tmpVec3[0];\n if (options.perpAxisB) {\n perpAxisB.copyFrom(options.perpAxisB);\n }\n else {\n axisB.getNormalToRef(perpAxisB);\n }\n this._hknp.HP_Constraint_SetAnchorInChild(jointId, pivotB, this._bVecToV3(axisB), this._bVecToV3(perpAxisB));\n if (type == PhysicsConstraintType.LOCK) {\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_X, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_X, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED);\n }\n else if (type == PhysicsConstraintType.DISTANCE) {\n const distance = options.maxDistance || 0;\n const dist3d = this._hknp.ConstraintAxis.LINEAR_DISTANCE;\n this._hknp.HP_Constraint_SetAxisMode(jointId, dist3d, this._hknp.ConstraintAxisLimitMode.LIMITED);\n this._hknp.HP_Constraint_SetAxisMinLimit(jointId, dist3d, distance);\n this._hknp.HP_Constraint_SetAxisMaxLimit(jointId, dist3d, distance);\n }\n else if (type == PhysicsConstraintType.HINGE) {\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_X, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED);\n }\n else if (type == PhysicsConstraintType.PRISMATIC) {\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_X, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED);\n }\n else if (type == PhysicsConstraintType.SLIDER) {\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.ANGULAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED);\n }\n else if (type == PhysicsConstraintType.BALL_AND_SOCKET) {\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_X, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Y, this._hknp.ConstraintAxisLimitMode.LOCKED);\n this._hknp.HP_Constraint_SetAxisMode(jointId, this._hknp.ConstraintAxis.LINEAR_Z, this._hknp.ConstraintAxisLimitMode.LOCKED);\n }\n else if (type == PhysicsConstraintType.SIX_DOF) {\n const sixdofData = constraint;\n for (const l of sixdofData.limits) {\n const axId = this._constraintAxisToNative(l.axis);\n if (((_c = l.minLimit) !== null && _c !== void 0 ? _c : -1) == 0 && ((_d = l.maxLimit) !== null && _d !== void 0 ? _d : -1) == 0) {\n this._hknp.HP_Constraint_SetAxisMode(jointId, axId, this._hknp.ConstraintAxisLimitMode.LOCKED);\n }\n else {\n if (l.minLimit != undefined) {\n this._hknp.HP_Constraint_SetAxisMode(jointId, axId, this._hknp.ConstraintAxisLimitMode.LIMITED);\n this._hknp.HP_Constraint_SetAxisMinLimit(jointId, axId, l.minLimit);\n }\n if (l.maxLimit != undefined) {\n this._hknp.HP_Constraint_SetAxisMode(jointId, axId, this._hknp.ConstraintAxisLimitMode.LIMITED);\n this._hknp.HP_Constraint_SetAxisMaxLimit(jointId, axId, l.maxLimit);\n }\n }\n }\n }\n else {\n throw new Error(\"Unsupported Constraint Type.\");\n }\n const collisionEnabled = !!options.collision;\n this._hknp.HP_Constraint_SetCollisionsEnabled(jointId, collisionEnabled);\n this._hknp.HP_Constraint_SetEnabled(jointId, true);\n }\n /**\n * Adds a constraint to the physics engine.\n *\n * @param body - The main body to which the constraint is applied.\n * @param childBody - The body to which the constraint is applied.\n * @param constraint - The constraint to be applied.\n * @param instanceIndex - If this body is instanced, the index of the instance to which the constraint will be applied. If not specified, no constraint will be applied.\n * @param childInstanceIndex - If the child body is instanced, the index of the instance to which the constraint will be applied. If not specified, no constraint will be applied.\n */\n addConstraint(body, childBody, constraint, instanceIndex, childInstanceIndex) {\n // 0) {\n const hitData = this._hknp.HP_QueryCollector_GetCastRayResult(this._queryCollector, 0)[1];\n const hitPos = hitData[1][3];\n const hitNormal = hitData[1][4];\n const hitTriangle = hitData[1][5];\n result.setHitData({ x: hitNormal[0], y: hitNormal[1], z: hitNormal[2] }, { x: hitPos[0], y: hitPos[1], z: hitPos[2] }, hitTriangle);\n result.calculateHitDistance();\n const hitBody = this._bodies.get(hitData[1][0][0]);\n result.body = hitBody === null || hitBody === void 0 ? void 0 : hitBody.body;\n result.bodyIndex = hitBody === null || hitBody === void 0 ? void 0 : hitBody.index;\n }\n }\n /**\n * Return the collision observable for a particular physics body.\n * @param body the physics body\n */\n getCollisionObservable(body) {\n const bodyId = body._pluginData.hpBodyId[0];\n let observable = this._bodyCollisionObservable.get(bodyId);\n if (!observable) {\n observable = new Observable();\n this._bodyCollisionObservable.set(bodyId, observable);\n }\n return observable;\n }\n /**\n * Enable collision to be reported for a body when a callback is settup on the world\n * @param body the physics body\n * @param enabled\n */\n setCollisionCallbackEnabled(body, enabled) {\n // Register for collide events by default\n const collideEvents = this._hknp.EventType.COLLISION_STARTED.value | this._hknp.EventType.COLLISION_CONTINUED.value | this._hknp.EventType.COLLISION_FINISHED.value;\n if (body._pluginDataInstances && body._pluginDataInstances.length) {\n body._pluginDataInstances.forEach((bodyId) => {\n this._hknp.HP_Body_SetEventMask(bodyId.hpBodyId, enabled ? collideEvents : 0);\n });\n }\n else if (body._pluginData) {\n this._hknp.HP_Body_SetEventMask(body._pluginData.hpBodyId, enabled ? collideEvents : 0);\n }\n }\n /**\n * Runs thru all detected collisions and filter by body\n */\n _notifyCollisions() {\n let eventAddress = this._hknp.HP_World_GetCollisionEvents(this.world)[1];\n const event = new CollisionEvent();\n const worldAddr = Number(this.world);\n while (eventAddress) {\n CollisionEvent.readToRef(this._hknp.HEAPU8.buffer, eventAddress, event);\n event.contactOnB.position.subtractToRef(event.contactOnA.position, this._tmpVec3[0]);\n const distance = Vector3.Dot(this._tmpVec3[0], event.contactOnA.normal);\n const bodyInfoA = this._bodies.get(event.contactOnA.bodyId);\n const bodyInfoB = this._bodies.get(event.contactOnB.bodyId);\n const collisionInfo = {\n collider: bodyInfoA.body,\n colliderIndex: bodyInfoA.index,\n collidedAgainst: bodyInfoB.body,\n collidedAgainstIndex: bodyInfoB.index,\n point: event.contactOnA.position,\n distance: distance,\n impulse: event.impulseApplied,\n normal: event.contactOnA.normal,\n };\n this.onCollisionObservable.notifyObservers(collisionInfo);\n if (this._bodyCollisionObservable.size) {\n const observableA = this._bodyCollisionObservable.get(event.contactOnA.bodyId);\n const observableB = this._bodyCollisionObservable.get(event.contactOnB.bodyId);\n if (observableA) {\n observableA.notifyObservers(collisionInfo);\n }\n else if (observableB) {\n // {\n const index = camera.attachPostProcess(postProcess);\n this._indicesForCamera[cameraName].push(index);\n });\n if (!this._cameras[cameraName]) {\n this._cameras[cameraName] = camera;\n }\n }\n }\n /**\n * Detaches the effect on cameras\n * @param cameras The camera to detach from.\n * @internal\n */\n _detachCameras(cameras) {\n const cams = Tools.MakeArray(cameras || this._cameras);\n if (!cams) {\n return;\n }\n for (let i = 0; i < cams.length; i++) {\n const camera = cams[i];\n const cameraName = camera.name;\n const postProcesses = this._postProcesses[this._singleInstance ? 0 : cameraName];\n if (postProcesses) {\n postProcesses.forEach((postProcess) => {\n camera.detachPostProcess(postProcess);\n });\n }\n if (this._cameras[cameraName]) {\n this._cameras[cameraName] = null;\n }\n }\n }\n /**\n * Enables the effect on given cameras\n * @param cameras The camera to enable.\n * @internal\n */\n _enable(cameras) {\n const cams = Tools.MakeArray(cameras || this._cameras);\n if (!cams) {\n return;\n }\n for (let i = 0; i < cams.length; i++) {\n const camera = cams[i];\n const cameraName = camera.name;\n for (let j = 0; j < this._indicesForCamera[cameraName].length; j++) {\n if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {\n this._postProcesses[this._singleInstance ? 0 : cameraName].forEach((postProcess) => {\n cams[i].attachPostProcess(postProcess, this._indicesForCamera[cameraName][j]);\n });\n }\n }\n }\n }\n /**\n * Disables the effect on the given cameras\n * @param cameras The camera to disable.\n * @internal\n */\n _disable(cameras) {\n const cams = Tools.MakeArray(cameras || this._cameras);\n if (!cams) {\n return;\n }\n for (let i = 0; i < cams.length; i++) {\n const camera = cams[i];\n const cameraName = camera.name;\n this._postProcesses[this._singleInstance ? 0 : cameraName].forEach((postProcess) => {\n camera.detachPostProcess(postProcess);\n });\n }\n }\n /**\n * Gets a list of the post processes contained in the effect.\n * @param camera The camera to get the post processes on.\n * @returns The list of the post processes in the effect.\n */\n getPostProcesses(camera) {\n if (this._singleInstance) {\n return this._postProcesses[0];\n }\n else {\n if (!camera) {\n return null;\n }\n return this._postProcesses[camera.name];\n }\n }\n}\n//# sourceMappingURL=postProcessRenderEffect.js.map","import { Matrix } from \"../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\n\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { MultiRenderTarget } from \"../Materials/Textures/multiRenderTarget.js\";\nimport { MaterialHelper } from \"../Materials/materialHelper.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { _WarnImport } from \"../Misc/devTools.js\";\nimport { Material } from \"../Materials/material.js\";\nimport \"../Shaders/geometry.fragment.js\";\nimport \"../Shaders/geometry.vertex.js\";\nimport { MaterialFlags } from \"../Materials/materialFlags.js\";\nimport { addClipPlaneUniforms, bindClipPlane, prepareStringDefinesForClipPlanes } from \"../Materials/clipPlaneMaterialHelper.js\";\n/** list the uniforms used by the geometry renderer */\nconst uniforms = [\n \"world\",\n \"mBones\",\n \"viewProjection\",\n \"diffuseMatrix\",\n \"view\",\n \"previousWorld\",\n \"previousViewProjection\",\n \"mPreviousBones\",\n \"bumpMatrix\",\n \"reflectivityMatrix\",\n \"albedoMatrix\",\n \"reflectivityColor\",\n \"albedoColor\",\n \"metallic\",\n \"glossiness\",\n \"vTangentSpaceParams\",\n \"vBumpInfos\",\n \"morphTargetInfluences\",\n \"morphTargetTextureInfo\",\n \"morphTargetTextureIndices\",\n];\naddClipPlaneUniforms(uniforms);\n/**\n * This renderer is helpful to fill one of the render target with a geometry buffer.\n */\nexport class GeometryBufferRenderer {\n /**\n * @internal\n * Sets up internal structures to share outputs with PrePassRenderer\n * This method should only be called by the PrePassRenderer itself\n */\n _linkPrePassRenderer(prePassRenderer) {\n this._linkedWithPrePass = true;\n this._prePassRenderer = prePassRenderer;\n if (this._multiRenderTarget) {\n // prevents clearing of the RT since it's done by prepass\n this._multiRenderTarget.onClearObservable.clear();\n this._multiRenderTarget.onClearObservable.add(() => {\n // pass\n });\n }\n }\n /**\n * @internal\n * Separates internal structures from PrePassRenderer so the geometry buffer can now operate by itself.\n * This method should only be called by the PrePassRenderer itself\n */\n _unlinkPrePassRenderer() {\n this._linkedWithPrePass = false;\n this._createRenderTargets();\n }\n /**\n * @internal\n * Resets the geometry buffer layout\n */\n _resetLayout() {\n this._enablePosition = false;\n this._enableReflectivity = false;\n this._enableVelocity = false;\n this._attachmentsFromPrePass = [];\n }\n /**\n * @internal\n * Replaces a texture in the geometry buffer renderer\n * Useful when linking textures of the prepass renderer\n */\n _forceTextureType(geometryBufferType, index) {\n if (geometryBufferType === GeometryBufferRenderer.POSITION_TEXTURE_TYPE) {\n this._positionIndex = index;\n this._enablePosition = true;\n }\n else if (geometryBufferType === GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE) {\n this._velocityIndex = index;\n this._enableVelocity = true;\n }\n else if (geometryBufferType === GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE) {\n this._reflectivityIndex = index;\n this._enableReflectivity = true;\n }\n else if (geometryBufferType === GeometryBufferRenderer.DEPTH_TEXTURE_TYPE) {\n this._depthIndex = index;\n }\n else if (geometryBufferType === GeometryBufferRenderer.NORMAL_TEXTURE_TYPE) {\n this._normalIndex = index;\n }\n }\n /**\n * @internal\n * Sets texture attachments\n * Useful when linking textures of the prepass renderer\n */\n _setAttachments(attachments) {\n this._attachmentsFromPrePass = attachments;\n }\n /**\n * @internal\n * Replaces the first texture which is hard coded as a depth texture in the geometry buffer\n * Useful when linking textures of the prepass renderer\n */\n _linkInternalTexture(internalTexture) {\n this._multiRenderTarget.setInternalTexture(internalTexture, 0, false);\n }\n /**\n * Gets the render list (meshes to be rendered) used in the G buffer.\n */\n get renderList() {\n return this._multiRenderTarget.renderList;\n }\n /**\n * Set the render list (meshes to be rendered) used in the G buffer.\n */\n set renderList(meshes) {\n this._multiRenderTarget.renderList = meshes;\n }\n /**\n * Gets whether or not G buffer are supported by the running hardware.\n * This requires draw buffer supports\n */\n get isSupported() {\n return this._multiRenderTarget.isSupported;\n }\n /**\n * Returns the index of the given texture type in the G-Buffer textures array\n * @param textureType The texture type constant. For example GeometryBufferRenderer.POSITION_TEXTURE_INDEX\n * @returns the index of the given texture type in the G-Buffer textures array\n */\n getTextureIndex(textureType) {\n switch (textureType) {\n case GeometryBufferRenderer.POSITION_TEXTURE_TYPE:\n return this._positionIndex;\n case GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE:\n return this._velocityIndex;\n case GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE:\n return this._reflectivityIndex;\n default:\n return -1;\n }\n }\n /**\n * Gets a boolean indicating if objects positions are enabled for the G buffer.\n */\n get enablePosition() {\n return this._enablePosition;\n }\n /**\n * Sets whether or not objects positions are enabled for the G buffer.\n */\n set enablePosition(enable) {\n this._enablePosition = enable;\n // PrePass handles index and texture links\n if (!this._linkedWithPrePass) {\n this.dispose();\n this._createRenderTargets();\n }\n }\n /**\n * Gets a boolean indicating if objects velocities are enabled for the G buffer.\n */\n get enableVelocity() {\n return this._enableVelocity;\n }\n /**\n * Sets whether or not objects velocities are enabled for the G buffer.\n */\n set enableVelocity(enable) {\n this._enableVelocity = enable;\n if (!enable) {\n this._previousTransformationMatrices = {};\n }\n if (!this._linkedWithPrePass) {\n this.dispose();\n this._createRenderTargets();\n }\n this._scene.needsPreviousWorldMatrices = enable;\n }\n /**\n * Gets a boolean indicating if objects reflectivity are enabled in the G buffer.\n */\n get enableReflectivity() {\n return this._enableReflectivity;\n }\n /**\n * Sets whether or not objects reflectivity are enabled for the G buffer.\n * For Metallic-Roughness workflow with ORM texture, we assume that ORM texture is defined according to the default layout:\n * pbr.useRoughnessFromMetallicTextureAlpha = false;\n * pbr.useRoughnessFromMetallicTextureGreen = true;\n * pbr.useMetallnessFromMetallicTextureBlue = true;\n */\n set enableReflectivity(enable) {\n this._enableReflectivity = enable;\n if (!this._linkedWithPrePass) {\n this.dispose();\n this._createRenderTargets();\n }\n }\n /**\n * Gets the scene associated with the buffer.\n */\n get scene() {\n return this._scene;\n }\n /**\n * Gets the ratio used by the buffer during its creation.\n * How big is the buffer related to the main canvas.\n */\n get ratio() {\n return this._ratio;\n }\n /**\n * Creates a new G Buffer for the scene\n * @param scene The scene the buffer belongs to\n * @param ratio How big is the buffer related to the main canvas (default: 1)\n * @param depthFormat Format of the depth texture (default: 15)\n */\n constructor(scene, ratio = 1, depthFormat = 15) {\n /**\n * Dictionary used to store the previous transformation matrices of each rendered mesh\n * in order to compute objects velocities when enableVelocity is set to \"true\"\n * @internal\n */\n this._previousTransformationMatrices = {};\n /**\n * Dictionary used to store the previous bones transformation matrices of each rendered mesh\n * in order to compute objects velocities when enableVelocity is set to \"true\"\n * @internal\n */\n this._previousBonesTransformationMatrices = {};\n /**\n * Array used to store the ignored skinned meshes while computing velocity map (typically used by the motion blur post-process).\n * Avoids computing bones velocities and computes only mesh's velocity itself (position, rotation, scaling).\n */\n this.excludedSkinnedMeshesFromVelocity = [];\n /** Gets or sets a boolean indicating if transparent meshes should be rendered */\n this.renderTransparentMeshes = true;\n this._resizeObserver = null;\n this._enablePosition = false;\n this._enableVelocity = false;\n this._enableReflectivity = false;\n this._clearColor = new Color4(0, 0, 0, 0);\n this._clearDepthColor = new Color4(1e8, 0, 0, 1); // \"infinity\" value - depth in the depth texture is view.z, not a 0..1 value!\n this._positionIndex = -1;\n this._velocityIndex = -1;\n this._reflectivityIndex = -1;\n this._depthIndex = -1;\n this._normalIndex = -1;\n this._linkedWithPrePass = false;\n /**\n * If set to true (default: false), the depth texture will be cleared with the depth value corresponding to the far plane (1 in normal mode, 0 in reverse depth buffer mode)\n * If set to false, the depth texture is always cleared with 0.\n */\n this.useSpecificClearForDepthTexture = false;\n this._scene = scene;\n this._ratio = ratio;\n this._useUbo = scene.getEngine().supportsUniformBuffers;\n this._depthFormat = depthFormat;\n GeometryBufferRenderer._SceneComponentInitialization(this._scene);\n // Render target\n this._createRenderTargets();\n }\n /**\n * Checks whether everything is ready to render a submesh to the G buffer.\n * @param subMesh the submesh to check readiness for\n * @param useInstances is the mesh drawn using instance or not\n * @returns true if ready otherwise false\n */\n isReady(subMesh, useInstances) {\n const material = subMesh.getMaterial();\n if (material && material.disableDepthWrite) {\n return false;\n }\n const defines = [];\n const attribs = [VertexBuffer.PositionKind, VertexBuffer.NormalKind];\n const mesh = subMesh.getMesh();\n // Alpha test\n if (material) {\n let needUv = false;\n if (material.needAlphaTesting() && material.getAlphaTestTexture()) {\n defines.push(\"#define ALPHATEST\");\n defines.push(`#define ALPHATEST_UV${material.getAlphaTestTexture().coordinatesIndex + 1}`);\n needUv = true;\n }\n if (material.bumpTexture && MaterialFlags.BumpTextureEnabled) {\n defines.push(\"#define BUMP\");\n defines.push(`#define BUMP_UV${material.bumpTexture.coordinatesIndex + 1}`);\n needUv = true;\n }\n if (this._enableReflectivity) {\n let metallicWorkflow = false;\n // for PBR materials: cf. https://doc.babylonjs.com/features/featuresDeepDive/materials/using/masterPBR\n if (material.getClassName() === \"PBRMetallicRoughnessMaterial\") {\n // if it is a PBR material in MetallicRoughness Mode:\n if (material.metallicRoughnessTexture !== null) {\n defines.push(\"#define ORMTEXTURE\");\n defines.push(`#define REFLECTIVITY_UV${material.metallicRoughnessTexture.coordinatesIndex + 1}`);\n defines.push(\"#define METALLICWORKFLOW\");\n needUv = true;\n metallicWorkflow = true;\n }\n if (material.metallic !== null) {\n defines.push(\"#define METALLIC\");\n defines.push(\"#define METALLICWORKFLOW\");\n metallicWorkflow = true;\n }\n if (material.roughness !== null) {\n defines.push(\"#define ROUGHNESS\");\n defines.push(\"#define METALLICWORKFLOW\");\n metallicWorkflow = true;\n }\n if (metallicWorkflow) {\n if (material.baseTexture !== null) {\n defines.push(\"#define ALBEDOTEXTURE\");\n defines.push(`#define ALBEDO_UV${material.baseTexture.coordinatesIndex + 1}`);\n if (material.baseTexture.gammaSpace) {\n defines.push(\"#define GAMMAALBEDO\");\n }\n needUv = true;\n }\n if (material.baseColor !== null) {\n defines.push(\"#define ALBEDOCOLOR\");\n }\n }\n }\n else if (material.getClassName() === \"PBRSpecularGlossinessMaterial\") {\n // if it is a PBR material in Specular/Glossiness Mode:\n if (material.specularGlossinessTexture !== null) {\n defines.push(\"#define SPECULARGLOSSINESSTEXTURE\");\n defines.push(`#define REFLECTIVITY_UV${material.specularGlossinessTexture.coordinatesIndex + 1}`);\n needUv = true;\n if (material.specularGlossinessTexture.gammaSpace) {\n defines.push(\"#define GAMMAREFLECTIVITYTEXTURE\");\n }\n }\n else {\n if (material.specularColor !== null) {\n defines.push(\"#define REFLECTIVITYCOLOR\");\n }\n }\n if (material.glossiness !== null) {\n defines.push(\"#define GLOSSINESS\");\n }\n }\n else if (material.getClassName() === \"PBRMaterial\") {\n // if it is the bigger PBRMaterial\n if (material.metallicTexture !== null) {\n defines.push(\"#define ORMTEXTURE\");\n defines.push(`#define REFLECTIVITY_UV${material.metallicTexture.coordinatesIndex + 1}`);\n defines.push(\"#define METALLICWORKFLOW\");\n needUv = true;\n metallicWorkflow = true;\n }\n if (material.metallic !== null) {\n defines.push(\"#define METALLIC\");\n defines.push(\"#define METALLICWORKFLOW\");\n metallicWorkflow = true;\n }\n if (material.roughness !== null) {\n defines.push(\"#define ROUGHNESS\");\n defines.push(\"#define METALLICWORKFLOW\");\n metallicWorkflow = true;\n }\n if (metallicWorkflow) {\n if (material.albedoTexture !== null) {\n defines.push(\"#define ALBEDOTEXTURE\");\n defines.push(`#define ALBEDO_UV${material.albedoTexture.coordinatesIndex + 1}`);\n if (material.albedoTexture.gammaSpace) {\n defines.push(\"#define GAMMAALBEDO\");\n }\n needUv = true;\n }\n if (material.albedoColor !== null) {\n defines.push(\"#define ALBEDOCOLOR\");\n }\n }\n else {\n // SpecularGlossiness Model\n if (material.reflectivityTexture !== null) {\n defines.push(\"#define SPECULARGLOSSINESSTEXTURE\");\n defines.push(`#define REFLECTIVITY_UV${material.reflectivityTexture.coordinatesIndex + 1}`);\n if (material.reflectivityTexture.gammaSpace) {\n defines.push(\"#define GAMMAREFLECTIVITYTEXTURE\");\n }\n needUv = true;\n }\n else if (material.reflectivityColor !== null) {\n defines.push(\"#define REFLECTIVITYCOLOR\");\n }\n if (material.microSurface !== null) {\n defines.push(\"#define GLOSSINESS\");\n }\n }\n }\n else if (material.getClassName() === \"StandardMaterial\") {\n // if StandardMaterial:\n if (material.specularTexture !== null) {\n defines.push(\"#define REFLECTIVITYTEXTURE\");\n defines.push(`#define REFLECTIVITY_UV${material.specularTexture.coordinatesIndex + 1}`);\n if (material.specularTexture.gammaSpace) {\n defines.push(\"#define GAMMAREFLECTIVITYTEXTURE\");\n }\n needUv = true;\n }\n if (material.specularColor !== null) {\n defines.push(\"#define REFLECTIVITYCOLOR\");\n }\n }\n }\n if (needUv) {\n defines.push(\"#define NEED_UV\");\n if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {\n attribs.push(VertexBuffer.UVKind);\n defines.push(\"#define UV1\");\n }\n if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {\n attribs.push(VertexBuffer.UV2Kind);\n defines.push(\"#define UV2\");\n }\n }\n }\n // PrePass\n if (this._linkedWithPrePass) {\n defines.push(\"#define PREPASS\");\n if (this._depthIndex !== -1) {\n defines.push(\"#define DEPTH_INDEX \" + this._depthIndex);\n defines.push(\"#define PREPASS_DEPTH\");\n }\n if (this._normalIndex !== -1) {\n defines.push(\"#define NORMAL_INDEX \" + this._normalIndex);\n defines.push(\"#define PREPASS_NORMAL\");\n }\n }\n // Buffers\n if (this._enablePosition) {\n defines.push(\"#define POSITION\");\n defines.push(\"#define POSITION_INDEX \" + this._positionIndex);\n }\n if (this._enableVelocity) {\n defines.push(\"#define VELOCITY\");\n defines.push(\"#define VELOCITY_INDEX \" + this._velocityIndex);\n if (this.excludedSkinnedMeshesFromVelocity.indexOf(mesh) === -1) {\n defines.push(\"#define BONES_VELOCITY_ENABLED\");\n }\n }\n if (this._enableReflectivity) {\n defines.push(\"#define REFLECTIVITY\");\n defines.push(\"#define REFLECTIVITY_INDEX \" + this._reflectivityIndex);\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders) {\n attribs.push(VertexBuffer.MatricesIndicesKind);\n attribs.push(VertexBuffer.MatricesWeightsKind);\n if (mesh.numBoneInfluencers > 4) {\n attribs.push(VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(VertexBuffer.MatricesWeightsExtraKind);\n }\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n defines.push(\"#define BonesPerMesh \" + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Morph targets\n const morphTargetManager = mesh.morphTargetManager;\n let numMorphInfluencers = 0;\n if (morphTargetManager) {\n if (morphTargetManager.numInfluencers > 0) {\n numMorphInfluencers = morphTargetManager.numInfluencers;\n defines.push(\"#define MORPHTARGETS\");\n defines.push(\"#define NUM_MORPH_INFLUENCERS \" + numMorphInfluencers);\n if (morphTargetManager.isUsingTextureForTargets) {\n defines.push(\"#define MORPHTARGETS_TEXTURE\");\n }\n MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, numMorphInfluencers);\n }\n }\n // Instances\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n MaterialHelper.PushAttributesForInstances(attribs, this._enableVelocity);\n if (subMesh.getRenderingMesh().hasThinInstances) {\n defines.push(\"#define THIN_INSTANCES\");\n }\n }\n // Setup textures count\n if (this._linkedWithPrePass) {\n defines.push(\"#define RENDER_TARGET_COUNT \" + this._attachmentsFromPrePass.length);\n }\n else {\n defines.push(\"#define RENDER_TARGET_COUNT \" + this._multiRenderTarget.textures.length);\n }\n prepareStringDefinesForClipPlanes(material, this._scene, defines);\n // Get correct effect\n const engine = this._scene.getEngine();\n const drawWrapper = subMesh._getDrawWrapper(undefined, true);\n const cachedDefines = drawWrapper.defines;\n const join = defines.join(\"\\n\");\n if (cachedDefines !== join) {\n drawWrapper.setEffect(engine.createEffect(\"geometry\", {\n attributes: attribs,\n uniformsNames: uniforms,\n samplers: [\"diffuseSampler\", \"bumpSampler\", \"reflectivitySampler\", \"albedoSampler\", \"morphTargets\"],\n defines: join,\n onCompiled: null,\n fallbacks: null,\n onError: null,\n uniformBuffersNames: [\"Scene\"],\n indexParameters: { buffersCount: this._multiRenderTarget.textures.length - 1, maxSimultaneousMorphTargets: numMorphInfluencers },\n }, engine), join);\n }\n return drawWrapper.effect.isReady();\n }\n /**\n * Gets the current underlying G Buffer.\n * @returns the buffer\n */\n getGBuffer() {\n return this._multiRenderTarget;\n }\n /**\n * Gets the number of samples used to render the buffer (anti aliasing).\n */\n get samples() {\n return this._multiRenderTarget.samples;\n }\n /**\n * Sets the number of samples used to render the buffer (anti aliasing).\n */\n set samples(value) {\n this._multiRenderTarget.samples = value;\n }\n /**\n * Disposes the renderer and frees up associated resources.\n */\n dispose() {\n if (this._resizeObserver) {\n const engine = this._scene.getEngine();\n engine.onResizeObservable.remove(this._resizeObserver);\n this._resizeObserver = null;\n }\n this.getGBuffer().dispose();\n }\n _assignRenderTargetIndices() {\n const textureNames = [];\n let count = 2;\n textureNames.push(\"gBuffer_Depth\", \"gBuffer_Normal\");\n if (this._enablePosition) {\n this._positionIndex = count;\n count++;\n textureNames.push(\"gBuffer_Position\");\n }\n if (this._enableVelocity) {\n this._velocityIndex = count;\n count++;\n textureNames.push(\"gBuffer_Velocity\");\n }\n if (this._enableReflectivity) {\n this._reflectivityIndex = count;\n count++;\n textureNames.push(\"gBuffer_Reflectivity\");\n }\n return [count, textureNames];\n }\n _createRenderTargets() {\n const engine = this._scene.getEngine();\n const [count, textureNames] = this._assignRenderTargetIndices();\n let type = 0;\n if (engine._caps.textureFloat && engine._caps.textureFloatLinearFiltering) {\n type = 1;\n }\n else if (engine._caps.textureHalfFloat && engine._caps.textureHalfFloatLinearFiltering) {\n type = 2;\n }\n this._multiRenderTarget = new MultiRenderTarget(\"gBuffer\", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true, defaultType: type, depthTextureFormat: this._depthFormat }, textureNames.concat(\"gBuffer_DepthBuffer\"));\n if (!this.isSupported) {\n return;\n }\n this._multiRenderTarget.wrapU = Texture.CLAMP_ADDRESSMODE;\n this._multiRenderTarget.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._multiRenderTarget.refreshRate = 1;\n this._multiRenderTarget.renderParticles = false;\n this._multiRenderTarget.renderList = null;\n // Depth is always the first texture in the geometry buffer renderer!\n const layoutAttachmentsAll = [true];\n const layoutAttachmentsAllButDepth = [false];\n const layoutAttachmentsDepthOnly = [true];\n for (let i = 1; i < count; ++i) {\n layoutAttachmentsAll.push(true);\n layoutAttachmentsDepthOnly.push(false);\n layoutAttachmentsAllButDepth.push(true);\n }\n const attachmentsAll = engine.buildTextureLayout(layoutAttachmentsAll);\n const attachmentsAllButDepth = engine.buildTextureLayout(layoutAttachmentsAllButDepth);\n const attachmentsDepthOnly = engine.buildTextureLayout(layoutAttachmentsDepthOnly);\n this._multiRenderTarget.onClearObservable.add((engine) => {\n engine.bindAttachments(this.useSpecificClearForDepthTexture ? attachmentsAllButDepth : attachmentsAll);\n engine.clear(this._clearColor, true, true, true);\n if (this.useSpecificClearForDepthTexture) {\n engine.bindAttachments(attachmentsDepthOnly);\n engine.clear(this._clearDepthColor, true, true, true);\n }\n engine.bindAttachments(attachmentsAll);\n });\n this._resizeObserver = engine.onResizeObservable.add(() => {\n if (this._multiRenderTarget) {\n this._multiRenderTarget.resize({ width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio });\n }\n });\n // Custom render function\n const renderSubMesh = (subMesh) => {\n const renderingMesh = subMesh.getRenderingMesh();\n const effectiveMesh = subMesh.getEffectiveMesh();\n const scene = this._scene;\n const engine = scene.getEngine();\n const material = subMesh.getMaterial();\n if (!material) {\n return;\n }\n effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;\n // Velocity\n if (this._enableVelocity && !this._previousTransformationMatrices[effectiveMesh.uniqueId]) {\n this._previousTransformationMatrices[effectiveMesh.uniqueId] = {\n world: Matrix.Identity(),\n viewProjection: scene.getTransformMatrix(),\n };\n if (renderingMesh.skeleton) {\n const bonesTransformations = renderingMesh.skeleton.getTransformMatrices(renderingMesh);\n this._previousBonesTransformationMatrices[renderingMesh.uniqueId] = this._copyBonesTransformationMatrices(bonesTransformations, new Float32Array(bonesTransformations.length));\n }\n }\n // Managing instances\n const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());\n if (batch.mustReturn) {\n return;\n }\n const hardwareInstancedRendering = engine.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null || renderingMesh.hasThinInstances);\n const world = effectiveMesh.getWorldMatrix();\n if (this.isReady(subMesh, hardwareInstancedRendering)) {\n const drawWrapper = subMesh._getDrawWrapper();\n if (!drawWrapper) {\n return;\n }\n const effect = drawWrapper.effect;\n engine.enableEffect(drawWrapper);\n if (!hardwareInstancedRendering) {\n renderingMesh._bind(subMesh, effect, material.fillMode);\n }\n if (!this._useUbo) {\n effect.setMatrix(\"viewProjection\", scene.getTransformMatrix());\n effect.setMatrix(\"view\", scene.getViewMatrix());\n }\n else {\n MaterialHelper.BindSceneUniformBuffer(effect, this._scene.getSceneUniformBuffer());\n this._scene.finalizeSceneUbo();\n }\n let sideOrientation;\n const instanceDataStorage = renderingMesh._instanceDataStorage;\n if (!instanceDataStorage.isFrozen && (material.backFaceCulling || renderingMesh.overrideMaterialSideOrientation !== null)) {\n const mainDeterminant = effectiveMesh._getWorldMatrixDeterminant();\n sideOrientation = renderingMesh.overrideMaterialSideOrientation;\n if (sideOrientation === null) {\n sideOrientation = material.sideOrientation;\n }\n if (mainDeterminant < 0) {\n sideOrientation = sideOrientation === Material.ClockWiseSideOrientation ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation;\n }\n }\n else {\n sideOrientation = instanceDataStorage.sideOrientation;\n }\n material._preBind(drawWrapper, sideOrientation);\n // Alpha test\n if (material.needAlphaTesting()) {\n const alphaTexture = material.getAlphaTestTexture();\n if (alphaTexture) {\n effect.setTexture(\"diffuseSampler\", alphaTexture);\n effect.setMatrix(\"diffuseMatrix\", alphaTexture.getTextureMatrix());\n }\n }\n // Bump\n if (material.bumpTexture && scene.getEngine().getCaps().standardDerivatives && MaterialFlags.BumpTextureEnabled) {\n effect.setFloat3(\"vBumpInfos\", material.bumpTexture.coordinatesIndex, 1.0 / material.bumpTexture.level, material.parallaxScaleBias);\n effect.setMatrix(\"bumpMatrix\", material.bumpTexture.getTextureMatrix());\n effect.setTexture(\"bumpSampler\", material.bumpTexture);\n effect.setFloat2(\"vTangentSpaceParams\", material.invertNormalMapX ? -1.0 : 1.0, material.invertNormalMapY ? -1.0 : 1.0);\n }\n // Reflectivity\n if (this._enableReflectivity) {\n // for PBR materials: cf. https://doc.babylonjs.com/features/featuresDeepDive/materials/using/masterPBR\n if (material.getClassName() === \"PBRMetallicRoughnessMaterial\") {\n // if it is a PBR material in MetallicRoughness Mode:\n if (material.metallicRoughnessTexture !== null) {\n effect.setTexture(\"reflectivitySampler\", material.metallicRoughnessTexture);\n effect.setMatrix(\"reflectivityMatrix\", material.metallicRoughnessTexture.getTextureMatrix());\n }\n if (material.metallic !== null) {\n effect.setFloat(\"metallic\", material.metallic);\n }\n if (material.roughness !== null) {\n effect.setFloat(\"glossiness\", 1.0 - material.roughness);\n }\n if (material.baseTexture !== null) {\n effect.setTexture(\"albedoSampler\", material.baseTexture);\n effect.setMatrix(\"albedoMatrix\", material.baseTexture.getTextureMatrix());\n }\n if (material.baseColor !== null) {\n effect.setColor3(\"albedoColor\", material.baseColor);\n }\n }\n else if (material.getClassName() === \"PBRSpecularGlossinessMaterial\") {\n // if it is a PBR material in Specular/Glossiness Mode:\n if (material.specularGlossinessTexture !== null) {\n effect.setTexture(\"reflectivitySampler\", material.specularGlossinessTexture);\n effect.setMatrix(\"reflectivityMatrix\", material.specularGlossinessTexture.getTextureMatrix());\n }\n else {\n if (material.specularColor !== null) {\n effect.setColor3(\"reflectivityColor\", material.specularColor);\n }\n }\n if (material.glossiness !== null) {\n effect.setFloat(\"glossiness\", material.glossiness);\n }\n }\n else if (material.getClassName() === \"PBRMaterial\") {\n // if it is the bigger PBRMaterial\n if (material.metallicTexture !== null) {\n effect.setTexture(\"reflectivitySampler\", material.metallicTexture);\n effect.setMatrix(\"reflectivityMatrix\", material.metallicTexture.getTextureMatrix());\n }\n if (material.metallic !== null) {\n effect.setFloat(\"metallic\", material.metallic);\n }\n if (material.roughness !== null) {\n effect.setFloat(\"glossiness\", 1.0 - material.roughness);\n }\n if (material.roughness !== null || material.metallic !== null || material.metallicTexture !== null) {\n // MetallicRoughness Model\n if (material.albedoTexture !== null) {\n effect.setTexture(\"albedoSampler\", material.albedoTexture);\n effect.setMatrix(\"albedoMatrix\", material.albedoTexture.getTextureMatrix());\n }\n if (material.albedoColor !== null) {\n effect.setColor3(\"albedoColor\", material.albedoColor);\n }\n }\n else {\n // SpecularGlossiness Model\n if (material.reflectivityTexture !== null) {\n effect.setTexture(\"reflectivitySampler\", material.reflectivityTexture);\n effect.setMatrix(\"reflectivityMatrix\", material.reflectivityTexture.getTextureMatrix());\n }\n else if (material.reflectivityColor !== null) {\n effect.setColor3(\"reflectivityColor\", material.reflectivityColor);\n }\n if (material.microSurface !== null) {\n effect.setFloat(\"glossiness\", material.microSurface);\n }\n }\n }\n else if (material.getClassName() === \"StandardMaterial\") {\n // if StandardMaterial:\n if (material.specularTexture !== null) {\n effect.setTexture(\"reflectivitySampler\", material.specularTexture);\n effect.setMatrix(\"reflectivityMatrix\", material.specularTexture.getTextureMatrix());\n }\n if (material.specularColor !== null) {\n effect.setColor3(\"reflectivityColor\", material.specularColor);\n }\n }\n }\n // Clip plane\n bindClipPlane(effect, material, this._scene);\n // Bones\n if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) {\n effect.setMatrices(\"mBones\", renderingMesh.skeleton.getTransformMatrices(renderingMesh));\n if (this._enableVelocity) {\n effect.setMatrices(\"mPreviousBones\", this._previousBonesTransformationMatrices[renderingMesh.uniqueId]);\n }\n }\n // Morph targets\n MaterialHelper.BindMorphTargetParameters(renderingMesh, effect);\n if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) {\n renderingMesh.morphTargetManager._bind(effect);\n }\n // Velocity\n if (this._enableVelocity) {\n effect.setMatrix(\"previousWorld\", this._previousTransformationMatrices[effectiveMesh.uniqueId].world);\n effect.setMatrix(\"previousViewProjection\", this._previousTransformationMatrices[effectiveMesh.uniqueId].viewProjection);\n }\n if (hardwareInstancedRendering && renderingMesh.hasThinInstances) {\n effect.setMatrix(\"world\", world);\n }\n // Draw\n renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, w) => {\n if (!isInstance) {\n effect.setMatrix(\"world\", w);\n }\n });\n }\n // Velocity\n if (this._enableVelocity) {\n this._previousTransformationMatrices[effectiveMesh.uniqueId].world = world.clone();\n this._previousTransformationMatrices[effectiveMesh.uniqueId].viewProjection = this._scene.getTransformMatrix().clone();\n if (renderingMesh.skeleton) {\n this._copyBonesTransformationMatrices(renderingMesh.skeleton.getTransformMatrices(renderingMesh), this._previousBonesTransformationMatrices[effectiveMesh.uniqueId]);\n }\n }\n };\n this._multiRenderTarget.customIsReadyFunction = (mesh, refreshRate, preWarm) => {\n if ((preWarm || refreshRate === 0) && mesh.subMeshes) {\n for (let i = 0; i < mesh.subMeshes.length; ++i) {\n const subMesh = mesh.subMeshes[i];\n const material = subMesh.getMaterial();\n const renderingMesh = subMesh.getRenderingMesh();\n if (!material) {\n continue;\n }\n const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());\n const hardwareInstancedRendering = engine.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null || renderingMesh.hasThinInstances);\n if (!this.isReady(subMesh, hardwareInstancedRendering)) {\n return false;\n }\n }\n }\n return true;\n };\n this._multiRenderTarget.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => {\n let index;\n if (this._linkedWithPrePass) {\n if (!this._prePassRenderer.enabled) {\n return;\n }\n this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass);\n }\n if (depthOnlySubMeshes.length) {\n engine.setColorWrite(false);\n for (index = 0; index < depthOnlySubMeshes.length; index++) {\n renderSubMesh(depthOnlySubMeshes.data[index]);\n }\n engine.setColorWrite(true);\n }\n for (index = 0; index < opaqueSubMeshes.length; index++) {\n renderSubMesh(opaqueSubMeshes.data[index]);\n }\n engine.setDepthWrite(false);\n for (index = 0; index < alphaTestSubMeshes.length; index++) {\n renderSubMesh(alphaTestSubMeshes.data[index]);\n }\n if (this.renderTransparentMeshes) {\n for (index = 0; index < transparentSubMeshes.length; index++) {\n renderSubMesh(transparentSubMeshes.data[index]);\n }\n }\n engine.setDepthWrite(true);\n };\n }\n // Copies the bones transformation matrices into the target array and returns the target's reference\n _copyBonesTransformationMatrices(source, target) {\n for (let i = 0; i < source.length; i++) {\n target[i] = source[i];\n }\n return target;\n }\n}\n/**\n * Constant used to retrieve the depth texture index in the G-Buffer textures array\n * using getIndex(GeometryBufferRenderer.DEPTH_TEXTURE_INDEX)\n */\nGeometryBufferRenderer.DEPTH_TEXTURE_TYPE = 0;\n/**\n * Constant used to retrieve the normal texture index in the G-Buffer textures array\n * using getIndex(GeometryBufferRenderer.NORMAL_TEXTURE_INDEX)\n */\nGeometryBufferRenderer.NORMAL_TEXTURE_TYPE = 1;\n/**\n * Constant used to retrieve the position texture index in the G-Buffer textures array\n * using getIndex(GeometryBufferRenderer.POSITION_TEXTURE_INDEX)\n */\nGeometryBufferRenderer.POSITION_TEXTURE_TYPE = 2;\n/**\n * Constant used to retrieve the velocity texture index in the G-Buffer textures array\n * using getIndex(GeometryBufferRenderer.VELOCITY_TEXTURE_INDEX)\n */\nGeometryBufferRenderer.VELOCITY_TEXTURE_TYPE = 3;\n/**\n * Constant used to retrieve the reflectivity texture index in the G-Buffer textures array\n * using the getIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE)\n */\nGeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE = 4;\n/**\n * @internal\n */\nGeometryBufferRenderer._SceneComponentInitialization = (_) => {\n throw _WarnImport(\"GeometryBufferRendererSceneComponent\");\n};\n//# sourceMappingURL=geometryBufferRenderer.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { Matrix, TmpVectors, Vector2 } from \"../Maths/math.vector.js\";\nimport { PostProcess } from \"./postProcess.js\";\n\nimport { GeometryBufferRenderer } from \"../Rendering/geometryBufferRenderer.js\";\nimport { MotionBlurConfiguration } from \"../Rendering/motionBlurConfiguration.js\";\nimport \"../Animations/animatable.js\";\nimport \"../Rendering/geometryBufferRendererSceneComponent.js\";\nimport \"../Shaders/motionBlur.fragment.js\";\nimport { serialize, SerializationHelper } from \"../Misc/decorators.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\n/**\n * The Motion Blur Post Process which blurs an image based on the objects velocity in scene.\n * Velocity can be affected by each object's rotation, position and scale depending on the transformation speed.\n * As an example, all you have to do is to create the post-process:\n * var mb = new BABYLON.MotionBlurPostProcess(\n * 'mb', // The name of the effect.\n * scene, // The scene containing the objects to blur according to their velocity.\n * 1.0, // The required width/height ratio to downsize to before computing the render pass.\n * camera // The camera to apply the render pass to.\n * );\n * Then, all objects moving, rotating and/or scaling will be blurred depending on the transformation speed.\n */\nexport class MotionBlurPostProcess extends PostProcess {\n /**\n * Gets the number of iterations are used for motion blur quality. Default value is equal to 32\n */\n get motionBlurSamples() {\n return this._motionBlurSamples;\n }\n /**\n * Sets the number of iterations to be used for motion blur quality\n */\n set motionBlurSamples(samples) {\n this._motionBlurSamples = samples;\n this._updateEffect();\n }\n /**\n * Gets whether or not the motion blur post-process is in object based mode.\n */\n get isObjectBased() {\n return this._isObjectBased;\n }\n /**\n * Sets whether or not the motion blur post-process is in object based mode.\n */\n set isObjectBased(value) {\n if (this._isObjectBased === value) {\n return;\n }\n this._isObjectBased = value;\n this._applyMode();\n }\n get _geometryBufferRenderer() {\n if (!this._forceGeometryBuffer) {\n return null;\n }\n return this._scene.geometryBufferRenderer;\n }\n get _prePassRenderer() {\n if (this._forceGeometryBuffer) {\n return null;\n }\n return this._scene.prePassRenderer;\n }\n /**\n * Gets a string identifying the name of the class\n * @returns \"MotionBlurPostProcess\" string\n */\n getClassName() {\n return \"MotionBlurPostProcess\";\n }\n /**\n * Creates a new instance MotionBlurPostProcess\n * @param name The name of the effect.\n * @param scene The scene containing the objects to blur according to their velocity.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: true)\n * @param forceGeometryBuffer If this post process should use geometry buffer instead of prepass (default: false)\n */\n constructor(name, scene, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false, forceGeometryBuffer = false) {\n super(name, \"motionBlur\", [\"motionStrength\", \"motionScale\", \"screenSize\", \"inverseViewProjection\", \"prevViewProjection\", \"projection\"], [\"velocitySampler\", \"depthSampler\"], options, camera, samplingMode, engine, reusable, \"#define GEOMETRY_SUPPORTED\\n#define SAMPLES 64.0\\n#define OBJECT_BASED\", textureType, undefined, null, blockCompilation);\n /**\n * Defines how much the image is blurred by the movement. Default value is equal to 1\n */\n this.motionStrength = 1;\n this._motionBlurSamples = 32;\n this._isObjectBased = true;\n this._forceGeometryBuffer = false;\n this._invViewProjection = null;\n this._previousViewProjection = null;\n this._forceGeometryBuffer = forceGeometryBuffer;\n // Set up assets\n if (this._forceGeometryBuffer) {\n scene.enableGeometryBufferRenderer();\n if (this._geometryBufferRenderer) {\n this._geometryBufferRenderer.enableVelocity = true;\n }\n }\n else {\n scene.enablePrePassRenderer();\n if (this._prePassRenderer) {\n this._prePassRenderer.markAsDirty();\n this._prePassEffectConfiguration = new MotionBlurConfiguration();\n }\n }\n this._applyMode();\n }\n /**\n * Excludes the given skinned mesh from computing bones velocities.\n * Computing bones velocities can have a cost and that cost. The cost can be saved by calling this function and by passing the skinned mesh reference to ignore.\n * @param skinnedMesh The mesh containing the skeleton to ignore when computing the velocity map.\n */\n excludeSkinnedMesh(skinnedMesh) {\n if (skinnedMesh.skeleton) {\n let list;\n if (this._geometryBufferRenderer) {\n list = this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;\n }\n else if (this._prePassRenderer) {\n list = this._prePassRenderer.excludedSkinnedMesh;\n }\n else {\n return;\n }\n list.push(skinnedMesh);\n }\n }\n /**\n * Removes the given skinned mesh from the excluded meshes to integrate bones velocities while rendering the velocity map.\n * @param skinnedMesh The mesh containing the skeleton that has been ignored previously.\n * @see excludeSkinnedMesh to exclude a skinned mesh from bones velocity computation.\n */\n removeExcludedSkinnedMesh(skinnedMesh) {\n if (skinnedMesh.skeleton) {\n let list;\n if (this._geometryBufferRenderer) {\n list = this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;\n }\n else if (this._prePassRenderer) {\n list = this._prePassRenderer.excludedSkinnedMesh;\n }\n else {\n return;\n }\n const index = list.indexOf(skinnedMesh);\n if (index !== -1) {\n list.splice(index, 1);\n }\n }\n }\n /**\n * Disposes the post process.\n * @param camera The camera to dispose the post process on.\n */\n dispose(camera) {\n if (this._geometryBufferRenderer) {\n // Clear previous transformation matrices dictionary used to compute objects velocities\n this._geometryBufferRenderer._previousTransformationMatrices = {};\n this._geometryBufferRenderer._previousBonesTransformationMatrices = {};\n this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity = [];\n }\n super.dispose(camera);\n }\n /**\n * Called on the mode changed (object based or screen based).\n */\n _applyMode() {\n if (!this._geometryBufferRenderer && !this._prePassRenderer) {\n // We can't get a velocity or depth texture. So, work as a passthrough.\n Logger.Warn(\"Multiple Render Target support needed to compute object based motion blur\");\n return this.updateEffect();\n }\n this._updateEffect();\n this._invViewProjection = null;\n this._previousViewProjection = null;\n if (this.isObjectBased) {\n if (this._prePassRenderer && this._prePassEffectConfiguration) {\n this._prePassEffectConfiguration.texturesRequired[0] = 2;\n }\n this.onApply = (effect) => this._onApplyObjectBased(effect);\n }\n else {\n this._invViewProjection = Matrix.Identity();\n this._previousViewProjection = this._scene.getTransformMatrix().clone();\n if (this._prePassRenderer && this._prePassEffectConfiguration) {\n this._prePassEffectConfiguration.texturesRequired[0] = 5;\n }\n this.onApply = (effect) => this._onApplyScreenBased(effect);\n }\n }\n /**\n * Called on the effect is applied when the motion blur post-process is in object based mode.\n * @param effect\n */\n _onApplyObjectBased(effect) {\n effect.setVector2(\"screenSize\", new Vector2(this.width, this.height));\n effect.setFloat(\"motionScale\", this._scene.getAnimationRatio());\n effect.setFloat(\"motionStrength\", this.motionStrength);\n if (this._geometryBufferRenderer) {\n const velocityIndex = this._geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE);\n effect.setTexture(\"velocitySampler\", this._geometryBufferRenderer.getGBuffer().textures[velocityIndex]);\n }\n else if (this._prePassRenderer) {\n const velocityIndex = this._prePassRenderer.getIndex(2);\n effect.setTexture(\"velocitySampler\", this._prePassRenderer.getRenderTarget().textures[velocityIndex]);\n }\n }\n /**\n * Called on the effect is applied when the motion blur post-process is in screen based mode.\n * @param effect\n */\n _onApplyScreenBased(effect) {\n const viewProjection = TmpVectors.Matrix[0];\n viewProjection.copyFrom(this._scene.getTransformMatrix());\n viewProjection.invertToRef(this._invViewProjection);\n effect.setMatrix(\"inverseViewProjection\", this._invViewProjection);\n effect.setMatrix(\"prevViewProjection\", this._previousViewProjection);\n this._previousViewProjection.copyFrom(viewProjection);\n effect.setMatrix(\"projection\", this._scene.getProjectionMatrix());\n effect.setVector2(\"screenSize\", new Vector2(this.width, this.height));\n effect.setFloat(\"motionScale\", this._scene.getAnimationRatio());\n effect.setFloat(\"motionStrength\", this.motionStrength);\n if (this._geometryBufferRenderer) {\n const depthIndex = this._geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.DEPTH_TEXTURE_TYPE);\n effect.setTexture(\"depthSampler\", this._geometryBufferRenderer.getGBuffer().textures[depthIndex]);\n }\n else if (this._prePassRenderer) {\n const depthIndex = this._prePassRenderer.getIndex(5);\n effect.setTexture(\"depthSampler\", this._prePassRenderer.getRenderTarget().textures[depthIndex]);\n }\n }\n /**\n * Called on the effect must be updated (changed mode, samples count, etc.).\n */\n _updateEffect() {\n if (this._geometryBufferRenderer || this._prePassRenderer) {\n const defines = [\n \"#define GEOMETRY_SUPPORTED\",\n \"#define SAMPLES \" + this._motionBlurSamples.toFixed(1),\n this._isObjectBased ? \"#define OBJECT_BASED\" : \"#define SCREEN_BASED\",\n ];\n this.updateEffect(defines.join(\"\\n\"));\n }\n }\n /**\n * @internal\n */\n static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) {\n return SerializationHelper.Parse(() => {\n return new MotionBlurPostProcess(parsedPostProcess.name, scene, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable, parsedPostProcess.textureType, false);\n }, parsedPostProcess, scene, rootUrl);\n }\n}\n__decorate([\n serialize()\n], MotionBlurPostProcess.prototype, \"motionStrength\", void 0);\n__decorate([\n serialize()\n], MotionBlurPostProcess.prototype, \"motionBlurSamples\", null);\n__decorate([\n serialize()\n], MotionBlurPostProcess.prototype, \"isObjectBased\", null);\nRegisterClass(\"BABYLON.MotionBlurPostProcess\", MotionBlurPostProcess);\n//# sourceMappingURL=motionBlurPostProcess.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { PostProcess } from \"./postProcess.js\";\n\nimport { GeometryBufferRenderer } from \"../Rendering/geometryBufferRenderer.js\";\nimport { serialize, SerializationHelper } from \"../Misc/decorators.js\";\nimport { ScreenSpaceReflectionsConfiguration } from \"../Rendering/screenSpaceReflectionsConfiguration.js\";\nimport \"../Shaders/screenSpaceReflection.fragment.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\n/**\n * The ScreenSpaceReflectionPostProcess performs realtime reflections using only and only the available informations on the screen (positions and normals).\n * Basically, the screen space reflection post-process will compute reflections according the material's reflectivity.\n * @deprecated Use the new SSRRenderingPipeline instead.\n */\nexport class ScreenSpaceReflectionPostProcess extends PostProcess {\n get _geometryBufferRenderer() {\n if (!this._forceGeometryBuffer) {\n return null;\n }\n return this._scene.geometryBufferRenderer;\n }\n get _prePassRenderer() {\n if (this._forceGeometryBuffer) {\n return null;\n }\n return this._scene.prePassRenderer;\n }\n /**\n * Gets a string identifying the name of the class\n * @returns \"ScreenSpaceReflectionPostProcess\" string\n */\n getClassName() {\n return \"ScreenSpaceReflectionPostProcess\";\n }\n /**\n * Creates a new instance of ScreenSpaceReflectionPostProcess.\n * @param name The name of the effect.\n * @param scene The scene containing the objects to calculate reflections.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: true)\n * @param forceGeometryBuffer If this post process should use geometry buffer instead of prepass (default: false)\n */\n constructor(name, scene, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false, forceGeometryBuffer = false) {\n super(name, \"screenSpaceReflection\", [\"projection\", \"view\", \"threshold\", \"reflectionSpecularFalloffExponent\", \"strength\", \"stepSize\", \"roughnessFactor\"], [\"textureSampler\", \"normalSampler\", \"positionSampler\", \"reflectivitySampler\"], options, camera, samplingMode, engine, reusable, \"#define SSR_SUPPORTED\\n#define REFLECTION_SAMPLES 64\\n#define SMOOTH_STEPS 5\\n\", textureType, undefined, null, blockCompilation);\n /**\n * Gets or sets a reflection threshold mainly used to adjust the reflection's height.\n */\n this.threshold = 1.2;\n /**\n * Gets or sets the current reflection strength. 1.0 is an ideal value but can be increased/decreased for particular results.\n */\n this.strength = 1;\n /**\n * Gets or sets the falloff exponent used while computing fresnel. More the exponent is high, more the reflections will be discrete.\n */\n this.reflectionSpecularFalloffExponent = 3;\n /**\n * Gets or sets the step size used to iterate until the effect finds the color of the reflection's pixel. Typically in interval [0.1, 1.0]\n */\n this.step = 1.0;\n /**\n * Gets or sets the factor applied when computing roughness. Default value is 0.2.\n */\n this.roughnessFactor = 0.2;\n this._forceGeometryBuffer = false;\n this._enableSmoothReflections = false;\n this._reflectionSamples = 64;\n this._smoothSteps = 5;\n this._forceGeometryBuffer = forceGeometryBuffer;\n if (this._forceGeometryBuffer) {\n // Get geometry buffer renderer and update effect\n const geometryBufferRenderer = scene.enableGeometryBufferRenderer();\n if (geometryBufferRenderer) {\n if (geometryBufferRenderer.isSupported) {\n geometryBufferRenderer.enablePosition = true;\n geometryBufferRenderer.enableReflectivity = true;\n }\n }\n }\n else {\n const prePassRenderer = scene.enablePrePassRenderer();\n prePassRenderer === null || prePassRenderer === void 0 ? void 0 : prePassRenderer.markAsDirty();\n this._prePassEffectConfiguration = new ScreenSpaceReflectionsConfiguration();\n }\n this._updateEffectDefines();\n // On apply, send uniforms\n this.onApply = (effect) => {\n const geometryBufferRenderer = this._geometryBufferRenderer;\n const prePassRenderer = this._prePassRenderer;\n if (!prePassRenderer && !geometryBufferRenderer) {\n return;\n }\n if (geometryBufferRenderer) {\n // Samplers\n const positionIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.POSITION_TEXTURE_TYPE);\n const roughnessIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE);\n effect.setTexture(\"normalSampler\", geometryBufferRenderer.getGBuffer().textures[1]);\n effect.setTexture(\"positionSampler\", geometryBufferRenderer.getGBuffer().textures[positionIndex]);\n effect.setTexture(\"reflectivitySampler\", geometryBufferRenderer.getGBuffer().textures[roughnessIndex]);\n }\n else if (prePassRenderer) {\n // Samplers\n const positionIndex = prePassRenderer.getIndex(1);\n const roughnessIndex = prePassRenderer.getIndex(3);\n const normalIndex = prePassRenderer.getIndex(6);\n effect.setTexture(\"normalSampler\", prePassRenderer.getRenderTarget().textures[normalIndex]);\n effect.setTexture(\"positionSampler\", prePassRenderer.getRenderTarget().textures[positionIndex]);\n effect.setTexture(\"reflectivitySampler\", prePassRenderer.getRenderTarget().textures[roughnessIndex]);\n }\n // Uniforms\n const camera = scene.activeCamera;\n if (!camera) {\n return;\n }\n const viewMatrix = camera.getViewMatrix(true);\n const projectionMatrix = camera.getProjectionMatrix(true);\n effect.setMatrix(\"projection\", projectionMatrix);\n effect.setMatrix(\"view\", viewMatrix);\n effect.setFloat(\"threshold\", this.threshold);\n effect.setFloat(\"reflectionSpecularFalloffExponent\", this.reflectionSpecularFalloffExponent);\n effect.setFloat(\"strength\", this.strength);\n effect.setFloat(\"stepSize\", this.step);\n effect.setFloat(\"roughnessFactor\", this.roughnessFactor);\n };\n this._isSceneRightHanded = scene.useRightHandedSystem;\n }\n /**\n * Gets whether or not smoothing reflections is enabled.\n * Enabling smoothing will require more GPU power and can generate a drop in FPS.\n */\n get enableSmoothReflections() {\n return this._enableSmoothReflections;\n }\n /**\n * Sets whether or not smoothing reflections is enabled.\n * Enabling smoothing will require more GPU power and can generate a drop in FPS.\n */\n set enableSmoothReflections(enabled) {\n if (enabled === this._enableSmoothReflections) {\n return;\n }\n this._enableSmoothReflections = enabled;\n this._updateEffectDefines();\n }\n /**\n * Gets the number of samples taken while computing reflections. More samples count is high,\n * more the post-process wil require GPU power and can generate a drop in FPS. Basically in interval [25, 100].\n */\n get reflectionSamples() {\n return this._reflectionSamples;\n }\n /**\n * Sets the number of samples taken while computing reflections. More samples count is high,\n * more the post-process wil require GPU power and can generate a drop in FPS. Basically in interval [25, 100].\n */\n set reflectionSamples(samples) {\n if (samples === this._reflectionSamples) {\n return;\n }\n this._reflectionSamples = samples;\n this._updateEffectDefines();\n }\n /**\n * Gets the number of samples taken while smoothing reflections. More samples count is high,\n * more the post-process will require GPU power and can generate a drop in FPS.\n * Default value (5.0) work pretty well in all cases but can be adjusted.\n */\n get smoothSteps() {\n return this._smoothSteps;\n }\n /*\n * Sets the number of samples taken while smoothing reflections. More samples count is high,\n * more the post-process will require GPU power and can generate a drop in FPS.\n * Default value (5.0) work pretty well in all cases but can be adjusted.\n */\n set smoothSteps(steps) {\n if (steps === this._smoothSteps) {\n return;\n }\n this._smoothSteps = steps;\n this._updateEffectDefines();\n }\n _updateEffectDefines() {\n const defines = [];\n if (this._geometryBufferRenderer || this._prePassRenderer) {\n defines.push(\"#define SSR_SUPPORTED\");\n }\n if (this._enableSmoothReflections) {\n defines.push(\"#define ENABLE_SMOOTH_REFLECTIONS\");\n }\n if (this._isSceneRightHanded) {\n defines.push(\"#define RIGHT_HANDED_SCENE\");\n }\n defines.push(\"#define REFLECTION_SAMPLES \" + (this._reflectionSamples >> 0));\n defines.push(\"#define SMOOTH_STEPS \" + (this._smoothSteps >> 0));\n this.updateEffect(defines.join(\"\\n\"));\n }\n /**\n * @internal\n */\n static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) {\n return SerializationHelper.Parse(() => {\n return new ScreenSpaceReflectionPostProcess(parsedPostProcess.name, scene, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.textureType, parsedPostProcess.reusable);\n }, parsedPostProcess, scene, rootUrl);\n }\n}\n__decorate([\n serialize()\n], ScreenSpaceReflectionPostProcess.prototype, \"threshold\", void 0);\n__decorate([\n serialize()\n], ScreenSpaceReflectionPostProcess.prototype, \"strength\", void 0);\n__decorate([\n serialize()\n], ScreenSpaceReflectionPostProcess.prototype, \"reflectionSpecularFalloffExponent\", void 0);\n__decorate([\n serialize()\n], ScreenSpaceReflectionPostProcess.prototype, \"step\", void 0);\n__decorate([\n serialize()\n], ScreenSpaceReflectionPostProcess.prototype, \"roughnessFactor\", void 0);\n__decorate([\n serialize()\n], ScreenSpaceReflectionPostProcess.prototype, \"enableSmoothReflections\", null);\n__decorate([\n serialize()\n], ScreenSpaceReflectionPostProcess.prototype, \"reflectionSamples\", null);\n__decorate([\n serialize()\n], ScreenSpaceReflectionPostProcess.prototype, \"smoothSteps\", null);\nRegisterClass(\"BABYLON.ScreenSpaceReflectionPostProcess\", ScreenSpaceReflectionPostProcess);\n//# sourceMappingURL=screenSpaceReflectionPostProcess.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"filterPixelShader\";\nconst shader = `varying vec2 vUV;\runiform sampler2D textureSampler;\runiform mat4 kernelMatrix;\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\r{\rvec3 baseColor=texture2D(textureSampler,vUV).rgb;\rvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\rgl_FragColor=vec4(updatedColor,1.0);\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const filterPixelShader = { name, shader };\n//# sourceMappingURL=filter.fragment.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { PostProcess } from \"./postProcess.js\";\nimport \"../Shaders/filter.fragment.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\nimport { serializeAsMatrix, SerializationHelper } from \"../Misc/decorators.js\";\n/**\n * Applies a kernel filter to the image\n */\nexport class FilterPostProcess extends PostProcess {\n /**\n * Gets a string identifying the name of the class\n * @returns \"FilterPostProcess\" string\n */\n getClassName() {\n return \"FilterPostProcess\";\n }\n /**\n *\n * @param name The name of the effect.\n * @param kernelMatrix The matrix to be applied to the image\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n */\n constructor(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {\n super(name, \"filter\", [\"kernelMatrix\"], null, options, camera, samplingMode, engine, reusable);\n this.kernelMatrix = kernelMatrix;\n this.onApply = (effect) => {\n effect.setMatrix(\"kernelMatrix\", this.kernelMatrix);\n };\n }\n /**\n * @internal\n */\n static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) {\n return SerializationHelper.Parse(() => {\n return new FilterPostProcess(parsedPostProcess.name, parsedPostProcess.kernelMatrix, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable);\n }, parsedPostProcess, scene, rootUrl);\n }\n}\n__decorate([\n serializeAsMatrix()\n], FilterPostProcess.prototype, \"kernelMatrix\", void 0);\nRegisterClass(\"BABYLON.FilterPostProcess\", FilterPostProcess);\n//# sourceMappingURL=filterPostProcess.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"fxaaPixelShader\";\nconst shader = `#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nuniform sampler2D textureSampler;\runiform vec2 texelSize;\rvarying vec2 vUV;\rvarying vec2 sampleCoordS;\rvarying vec2 sampleCoordE;\rvarying vec2 sampleCoordN;\rvarying vec2 sampleCoordW;\rvarying vec2 sampleCoordNW;\rvarying vec2 sampleCoordSE;\rvarying vec2 sampleCoordNE;\rvarying vec2 sampleCoordSW;\rconst float fxaaQualitySubpix=1.0;\rconst float fxaaQualityEdgeThreshold=0.166;\rconst float fxaaQualityEdgeThresholdMin=0.0833;\rconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\r#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\rvec2 posM;\rposM.x=vUV.x;\rposM.y=vUV.y;\rvec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);\rfloat lumaM=FxaaLuma(rgbyM);\rfloat lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));\rfloat lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));\rfloat lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));\rfloat lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));\rfloat maxSM=max(lumaS,lumaM);\rfloat minSM=min(lumaS,lumaM);\rfloat maxESM=max(lumaE,maxSM);\rfloat minESM=min(lumaE,minSM);\rfloat maxWN=max(lumaN,lumaW);\rfloat minWN=min(lumaN,lumaW);\rfloat rangeMax=max(maxWN,maxESM);\rfloat rangeMin=min(minWN,minESM);\rfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\rfloat range=rangeMax-rangeMin;\rfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\r#ifndef MALI\nif(range=edgeVert;\rfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\rif (!horzSpan)\r{\rlumaN=lumaW;\r}\rif (!horzSpan) \r{\rlumaS=lumaE;\r}\rif (horzSpan) \r{\rlengthSign=texelSize.y;\r}\rfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\rfloat gradientN=lumaN-lumaM;\rfloat gradientS=lumaS-lumaM;\rfloat lumaNN=lumaN+lumaM;\rfloat lumaSS=lumaS+lumaM;\rbool pairN=abs(gradientN)>=abs(gradientS);\rfloat gradient=max(abs(gradientN),abs(gradientS));\rif (pairN)\r{\rlengthSign=-lengthSign;\r}\rfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\rvec2 posB;\rposB.x=posM.x;\rposB.y=posM.y;\rvec2 offNP;\roffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\roffNP.y=(horzSpan) ? 0.0 : texelSize.y;\rif (!horzSpan) \r{\rposB.x+=lengthSign*0.5;\r}\rif (horzSpan)\r{\rposB.y+=lengthSign*0.5;\r}\rvec2 posN;\rposN.x=posB.x-offNP.x*1.5;\rposN.y=posB.y-offNP.y*1.5;\rvec2 posP;\rposP.x=posB.x+offNP.x*1.5;\rposP.y=posB.y+offNP.y*1.5;\rfloat subpixD=((-2.0)*subpixC)+3.0;\rfloat lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));\rfloat subpixE=subpixC*subpixC;\rfloat lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));\rif (!pairN) \r{\rlumaNN=lumaSS;\r}\rfloat gradientScaled=gradient*1.0/4.0;\rfloat lumaMM=lumaM-lumaNN*0.5;\rfloat subpixF=subpixD*subpixE;\rbool lumaMLTZero=lumaMM<0.0;\rlumaEndN-=lumaNN*0.5;\rlumaEndP-=lumaNN*0.5;\rbool doneN=abs(lumaEndN)>=gradientScaled;\rbool doneP=abs(lumaEndP)>=gradientScaled;\rif (!doneN) \r{\rposN.x-=offNP.x*3.0;\r}\rif (!doneN) \r{\rposN.y-=offNP.y*3.0;\r}\rbool doneNP=(!doneN) || (!doneP);\rif (!doneP) \r{\rposP.x+=offNP.x*3.0;\r}\rif (!doneP)\r{\rposP.y+=offNP.y*3.0;\r}\rif (doneNP)\r{\rif (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));\rif (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));\rif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\rif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\rdoneN=abs(lumaEndN)>=gradientScaled;\rdoneP=abs(lumaEndP)>=gradientScaled;\rif (!doneN) posN.x-=offNP.x*12.0;\rif (!doneN) posN.y-=offNP.y*12.0;\rdoneNP=(!doneN) || (!doneP);\rif (!doneP) posP.x+=offNP.x*12.0;\rif (!doneP) posP.y+=offNP.y*12.0;\r}\rfloat dstN=posM.x-posN.x;\rfloat dstP=posP.x-posM.x;\rif (!horzSpan)\r{\rdstN=posM.y-posN.y;\r}\rif (!horzSpan) \r{\rdstP=posP.y-posM.y;\r}\rbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\rfloat spanLength=(dstP+dstN);\rbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\rfloat spanLengthRcp=1.0/spanLength;\rbool directionN=dstN {\n const texelSize = this.texelSize;\n effect.setFloat2(\"texelSize\", texelSize.x, texelSize.y);\n });\n }\n _getDefines() {\n const engine = this.getEngine();\n if (!engine) {\n return null;\n }\n const glInfo = engine.getGlInfo();\n if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf(\"mali\") > -1) {\n return \"#define MALI 1\\n\";\n }\n return null;\n }\n /**\n * @internal\n */\n static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) {\n return SerializationHelper.Parse(() => {\n return new FxaaPostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable);\n }, parsedPostProcess, scene, rootUrl);\n }\n}\nRegisterClass(\"BABYLON.FxaaPostProcess\", FxaaPostProcess);\n//# sourceMappingURL=fxaaPostProcess.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/helperFunctions.js\";\nconst name = \"grainPixelShader\";\nconst shader = `#include\nuniform sampler2D textureSampler; \runiform float intensity;\runiform float animatedSeed;\rvarying vec2 vUV;\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\r{\rgl_FragColor=texture2D(textureSampler,vUV);\rvec2 seed=vUV*(animatedSeed);\rfloat grain=dither(seed,intensity);\rfloat lum=getLuminance(gl_FragColor.rgb);\rfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\rgl_FragColor.rgb+=grain*grainAmount;\rgl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const grainPixelShader = { name, shader };\n//# sourceMappingURL=grain.fragment.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { PostProcess } from \"./postProcess.js\";\n\nimport \"../Shaders/grain.fragment.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\nimport { serialize, SerializationHelper } from \"../Misc/decorators.js\";\n/**\n * The GrainPostProcess adds noise to the image at mid luminance levels\n */\nexport class GrainPostProcess extends PostProcess {\n /**\n * Gets a string identifying the name of the class\n * @returns \"GrainPostProcess\" string\n */\n getClassName() {\n return \"GrainPostProcess\";\n }\n /**\n * Creates a new instance of @see GrainPostProcess\n * @param name The name of the effect.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n constructor(name, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) {\n super(name, \"grain\", [\"intensity\", \"animatedSeed\"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation);\n /**\n * The intensity of the grain added (default: 30)\n */\n this.intensity = 30;\n /**\n * If the grain should be randomized on every frame\n */\n this.animated = false;\n this.onApplyObservable.add((effect) => {\n effect.setFloat(\"intensity\", this.intensity);\n effect.setFloat(\"animatedSeed\", this.animated ? Math.random() + 1 : 1);\n });\n }\n /**\n * @internal\n */\n static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) {\n return SerializationHelper.Parse(() => {\n return new GrainPostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable);\n }, parsedPostProcess, scene, rootUrl);\n }\n}\n__decorate([\n serialize()\n], GrainPostProcess.prototype, \"intensity\", void 0);\n__decorate([\n serialize()\n], GrainPostProcess.prototype, \"animated\", void 0);\nRegisterClass(\"BABYLON.GrainPostProcess\", GrainPostProcess);\n//# sourceMappingURL=grainPostProcess.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"highlightsPixelShader\";\nconst shader = `varying vec2 vUV;\runiform sampler2D textureSampler;\rconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \r{\rvec4 tex=texture2D(textureSampler,vUV);\rvec3 c=tex.rgb;\rfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\rgl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const highlightsPixelShader = { name, shader };\n//# sourceMappingURL=highlights.fragment.js.map","import { PostProcess } from \"./postProcess.js\";\n\nimport \"../Shaders/highlights.fragment.js\";\n/**\n * Extracts highlights from the image\n * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses\n */\nexport class HighlightsPostProcess extends PostProcess {\n /**\n * Gets a string identifying the name of the class\n * @returns \"HighlightsPostProcess\" string\n */\n getClassName() {\n return \"HighlightsPostProcess\";\n }\n /**\n * Extracts highlights from the image\n * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses\n * @param name The name of the effect.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of texture for the post process (default: Engine.TEXTURETYPE_UNSIGNED_INT)\n */\n constructor(name, options, camera, samplingMode, engine, reusable, textureType = 0) {\n super(name, \"highlights\", null, null, options, camera, samplingMode, engine, reusable, null, textureType);\n }\n}\n//# sourceMappingURL=highlightsPostProcess.js.map","import { Texture } from \"../../../Materials/Textures/texture.js\";\nimport { DynamicTexture } from \"../../../Materials/Textures/dynamicTexture.js\";\nimport { PostProcess } from \"../../../PostProcesses/postProcess.js\";\nimport { PostProcessRenderPipeline } from \"../../../PostProcesses/RenderPipeline/postProcessRenderPipeline.js\";\nimport { PostProcessRenderEffect } from \"../../../PostProcesses/RenderPipeline/postProcessRenderEffect.js\";\nimport \"../../../PostProcesses/RenderPipeline/postProcessRenderPipelineManagerSceneComponent.js\";\nimport \"../../../Shaders/chromaticAberration.fragment.js\";\nimport \"../../../Shaders/lensHighlights.fragment.js\";\nimport \"../../../Shaders/depthOfField.fragment.js\";\n/**\n * BABYLON.JS Chromatic Aberration GLSL Shader\n * Author: Olivier Guyot\n * Separates very slightly R, G and B colors on the edges of the screen\n * Inspired by Francois Tarlier & Martins Upitis\n */\nexport class LensRenderingPipeline extends PostProcessRenderPipeline {\n /**\n * @constructor\n *\n * Effect parameters are as follow:\n * {\n * chromatic_aberration: number; // from 0 to x (1 for realism)\n * edge_blur: number; // from 0 to x (1 for realism)\n * distortion: number; // from 0 to x (1 for realism), note that this will effect the pointer position precision\n * grain_amount: number; // from 0 to 1\n * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise\n * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)\n * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)\n * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)\n * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like \"bokeh\" effect\n * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)\n * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)\n * blur_noise: boolean; // add a little bit of noise to the blur (default: true)\n * }\n * Note: if an effect parameter is unset, effect is disabled\n *\n * @param name The rendering pipeline name\n * @param parameters - An object containing all parameters (see above)\n * @param scene The scene linked to this pipeline\n * @param ratio The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)\n * @param cameras The array of cameras that the rendering pipeline will be attached to\n */\n constructor(name, parameters, scene, ratio = 1.0, cameras) {\n super(scene.getEngine(), name);\n // Lens effects can be of the following:\n // - chromatic aberration (slight shift of RGB colors)\n // - blur on the edge of the lens\n // - lens distortion\n // - depth-of-field blur & highlights enhancing\n // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)\n // - grain effect (noise or custom texture)\n // Two additional texture samplers are needed:\n // - depth map (for depth-of-field)\n // - grain texture\n /**\n * @ignore\n * The chromatic aberration PostProcess id in the pipeline\n */\n this.LensChromaticAberrationEffect = \"LensChromaticAberrationEffect\";\n /**\n * @ignore\n * The highlights enhancing PostProcess id in the pipeline\n */\n this.HighlightsEnhancingEffect = \"HighlightsEnhancingEffect\";\n /**\n * @ignore\n * The depth-of-field PostProcess id in the pipeline\n */\n this.LensDepthOfFieldEffect = \"LensDepthOfFieldEffect\";\n this._pentagonBokehIsEnabled = false;\n this._scene = scene;\n // Fetch texture samplers\n this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer \"on\"\n if (parameters.grain_texture) {\n this._grainTexture = parameters.grain_texture;\n }\n else {\n this._createGrainTexture();\n }\n // save parameters\n this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;\n this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;\n this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;\n this._distortion = parameters.distortion ? parameters.distortion : 0;\n this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;\n this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;\n this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;\n this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;\n this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;\n this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;\n this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;\n // Create effects\n this._createChromaticAberrationPostProcess(ratio);\n this._createHighlightsPostProcess(ratio);\n this._createDepthOfFieldPostProcess(ratio / 4);\n // Set up pipeline\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, () => {\n return this._chromaticAberrationPostProcess;\n }, true));\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, () => {\n return this._highlightsPostProcess;\n }, true));\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, () => {\n return this._depthOfFieldPostProcess;\n }, true));\n if (this._highlightsGain === -1) {\n this._disableEffect(this.HighlightsEnhancingEffect, null);\n }\n // Finish\n scene.postProcessRenderPipelineManager.addPipeline(this);\n if (cameras) {\n scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);\n }\n }\n /**\n * Get the class name\n * @returns \"LensRenderingPipeline\"\n */\n getClassName() {\n return \"LensRenderingPipeline\";\n }\n // Properties\n /**\n * Gets associated scene\n */\n get scene() {\n return this._scene;\n }\n /**\n * Gets or sets the edge blur\n */\n get edgeBlur() {\n return this._edgeBlur;\n }\n set edgeBlur(value) {\n this.setEdgeBlur(value);\n }\n /**\n * Gets or sets the grain amount\n */\n get grainAmount() {\n return this._grainAmount;\n }\n set grainAmount(value) {\n this.setGrainAmount(value);\n }\n /**\n * Gets or sets the chromatic aberration amount\n */\n get chromaticAberration() {\n return this._chromaticAberration;\n }\n set chromaticAberration(value) {\n this.setChromaticAberration(value);\n }\n /**\n * Gets or sets the depth of field aperture\n */\n get dofAperture() {\n return this._dofAperture;\n }\n set dofAperture(value) {\n this.setAperture(value);\n }\n /**\n * Gets or sets the edge distortion\n */\n get edgeDistortion() {\n return this._distortion;\n }\n set edgeDistortion(value) {\n this.setEdgeDistortion(value);\n }\n /**\n * Gets or sets the depth of field distortion\n */\n get dofDistortion() {\n return this._dofDistance;\n }\n set dofDistortion(value) {\n this.setFocusDistance(value);\n }\n /**\n * Gets or sets the darken out of focus amount\n */\n get darkenOutOfFocus() {\n return this._dofDarken;\n }\n set darkenOutOfFocus(value) {\n this.setDarkenOutOfFocus(value);\n }\n /**\n * Gets or sets a boolean indicating if blur noise is enabled\n */\n get blurNoise() {\n return this._blurNoise;\n }\n set blurNoise(value) {\n this._blurNoise = value;\n }\n /**\n * Gets or sets a boolean indicating if pentagon bokeh is enabled\n */\n get pentagonBokeh() {\n return this._pentagonBokehIsEnabled;\n }\n set pentagonBokeh(value) {\n if (value) {\n this.enablePentagonBokeh();\n }\n else {\n this.disablePentagonBokeh();\n }\n }\n /**\n * Gets or sets the highlight grain amount\n */\n get highlightsGain() {\n return this._highlightsGain;\n }\n set highlightsGain(value) {\n this.setHighlightsGain(value);\n }\n /**\n * Gets or sets the highlight threshold\n */\n get highlightsThreshold() {\n return this._highlightsThreshold;\n }\n set highlightsThreshold(value) {\n this.setHighlightsThreshold(value);\n }\n // public methods (self explanatory)\n /**\n * Sets the amount of blur at the edges\n * @param amount blur amount\n */\n setEdgeBlur(amount) {\n this._edgeBlur = amount;\n }\n /**\n * Sets edge blur to 0\n */\n disableEdgeBlur() {\n this._edgeBlur = 0;\n }\n /**\n * Sets the amount of grain\n * @param amount Amount of grain\n */\n setGrainAmount(amount) {\n this._grainAmount = amount;\n }\n /**\n * Set grain amount to 0\n */\n disableGrain() {\n this._grainAmount = 0;\n }\n /**\n * Sets the chromatic aberration amount\n * @param amount amount of chromatic aberration\n */\n setChromaticAberration(amount) {\n this._chromaticAberration = amount;\n }\n /**\n * Sets chromatic aberration amount to 0\n */\n disableChromaticAberration() {\n this._chromaticAberration = 0;\n }\n /**\n * Sets the EdgeDistortion amount\n * @param amount amount of EdgeDistortion\n */\n setEdgeDistortion(amount) {\n this._distortion = amount;\n }\n /**\n * Sets edge distortion to 0\n */\n disableEdgeDistortion() {\n this._distortion = 0;\n }\n /**\n * Sets the FocusDistance amount\n * @param amount amount of FocusDistance\n */\n setFocusDistance(amount) {\n this._dofDistance = amount;\n }\n /**\n * Disables depth of field\n */\n disableDepthOfField() {\n this._dofDistance = -1;\n }\n /**\n * Sets the Aperture amount\n * @param amount amount of Aperture\n */\n setAperture(amount) {\n this._dofAperture = amount;\n }\n /**\n * Sets the DarkenOutOfFocus amount\n * @param amount amount of DarkenOutOfFocus\n */\n setDarkenOutOfFocus(amount) {\n this._dofDarken = amount;\n }\n /**\n * Creates a pentagon bokeh effect\n */\n enablePentagonBokeh() {\n this._highlightsPostProcess.updateEffect(\"#define PENTAGON\\n\");\n this._pentagonBokehIsEnabled = true;\n }\n /**\n * Disables the pentagon bokeh effect\n */\n disablePentagonBokeh() {\n this._pentagonBokehIsEnabled = false;\n this._highlightsPostProcess.updateEffect();\n }\n /**\n * Enables noise blur\n */\n enableNoiseBlur() {\n this._blurNoise = true;\n }\n /**\n * Disables noise blur\n */\n disableNoiseBlur() {\n this._blurNoise = false;\n }\n /**\n * Sets the HighlightsGain amount\n * @param amount amount of HighlightsGain\n */\n setHighlightsGain(amount) {\n this._highlightsGain = amount;\n }\n /**\n * Sets the HighlightsThreshold amount\n * @param amount amount of HighlightsThreshold\n */\n setHighlightsThreshold(amount) {\n if (this._highlightsGain === -1) {\n this._highlightsGain = 1.0;\n }\n this._highlightsThreshold = amount;\n }\n /**\n * Disables highlights\n */\n disableHighlights() {\n this._highlightsGain = -1;\n }\n /**\n * Removes the internal pipeline assets and detaches the pipeline from the scene cameras\n * @param disableDepthRender If the scene's depth rendering should be disabled (default: false)\n */\n dispose(disableDepthRender = false) {\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);\n this._chromaticAberrationPostProcess = null;\n this._highlightsPostProcess = null;\n this._depthOfFieldPostProcess = null;\n this._grainTexture.dispose();\n if (disableDepthRender) {\n this._scene.disableDepthRenderer();\n }\n }\n // colors shifting and distortion\n _createChromaticAberrationPostProcess(ratio) {\n this._chromaticAberrationPostProcess = new PostProcess(\"LensChromaticAberration\", \"chromaticAberration\", [\"chromatic_aberration\", \"screen_width\", \"screen_height\", \"direction\", \"radialIntensity\", \"centerPosition\"], // uniforms\n [], // samplers\n ratio, null, Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);\n this._chromaticAberrationPostProcess.onApply = (effect) => {\n effect.setFloat(\"chromatic_aberration\", this._chromaticAberration);\n effect.setFloat(\"screen_width\", this._scene.getEngine().getRenderWidth());\n effect.setFloat(\"screen_height\", this._scene.getEngine().getRenderHeight());\n effect.setFloat(\"radialIntensity\", 1);\n effect.setFloat2(\"direction\", 17, 17);\n effect.setFloat2(\"centerPosition\", 0.5, 0.5);\n };\n }\n // highlights enhancing\n _createHighlightsPostProcess(ratio) {\n this._highlightsPostProcess = new PostProcess(\"LensHighlights\", \"lensHighlights\", [\"gain\", \"threshold\", \"screen_width\", \"screen_height\"], // uniforms\n [], // samplers\n ratio, null, Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? \"#define PENTAGON\\n\" : \"\");\n this._highlightsPostProcess.externalTextureSamplerBinding = true;\n this._highlightsPostProcess.onApply = (effect) => {\n effect.setFloat(\"gain\", this._highlightsGain);\n effect.setFloat(\"threshold\", this._highlightsThreshold);\n effect.setTextureFromPostProcess(\"textureSampler\", this._chromaticAberrationPostProcess);\n effect.setFloat(\"screen_width\", this._scene.getEngine().getRenderWidth());\n effect.setFloat(\"screen_height\", this._scene.getEngine().getRenderHeight());\n };\n }\n // colors shifting and distortion\n _createDepthOfFieldPostProcess(ratio) {\n this._depthOfFieldPostProcess = new PostProcess(\"LensDepthOfField\", \"depthOfField\", [\n \"grain_amount\",\n \"blur_noise\",\n \"screen_width\",\n \"screen_height\",\n \"distortion\",\n \"dof_enabled\",\n \"screen_distance\",\n \"aperture\",\n \"darken\",\n \"edge_blur\",\n \"highlights\",\n \"near\",\n \"far\",\n ], [\"depthSampler\", \"grainSampler\", \"highlightsSampler\"], ratio, null, Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);\n this._depthOfFieldPostProcess.externalTextureSamplerBinding = true;\n this._depthOfFieldPostProcess.onApply = (effect) => {\n effect.setTexture(\"depthSampler\", this._depthTexture);\n effect.setTexture(\"grainSampler\", this._grainTexture);\n effect.setTextureFromPostProcess(\"textureSampler\", this._highlightsPostProcess);\n effect.setTextureFromPostProcess(\"highlightsSampler\", this._depthOfFieldPostProcess);\n effect.setFloat(\"grain_amount\", this._grainAmount);\n effect.setBool(\"blur_noise\", this._blurNoise);\n effect.setFloat(\"screen_width\", this._scene.getEngine().getRenderWidth());\n effect.setFloat(\"screen_height\", this._scene.getEngine().getRenderHeight());\n effect.setFloat(\"distortion\", this._distortion);\n effect.setBool(\"dof_enabled\", this._dofDistance !== -1);\n effect.setFloat(\"screen_distance\", 1.0 / (0.1 - 1.0 / this._dofDistance));\n effect.setFloat(\"aperture\", this._dofAperture);\n effect.setFloat(\"darken\", this._dofDarken);\n effect.setFloat(\"edge_blur\", this._edgeBlur);\n effect.setBool(\"highlights\", this._highlightsGain !== -1);\n if (this._scene.activeCamera) {\n effect.setFloat(\"near\", this._scene.activeCamera.minZ);\n effect.setFloat(\"far\", this._scene.activeCamera.maxZ);\n }\n };\n }\n // creates a black and white random noise texture, 512x512\n _createGrainTexture() {\n const size = 512;\n this._grainTexture = new DynamicTexture(\"LensNoiseTexture\", size, this._scene, false, Texture.BILINEAR_SAMPLINGMODE);\n this._grainTexture.wrapU = Texture.WRAP_ADDRESSMODE;\n this._grainTexture.wrapV = Texture.WRAP_ADDRESSMODE;\n const context = this._grainTexture.getContext();\n const rand = (min, max) => {\n return Math.random() * (max - min) + min;\n };\n let value;\n for (let x = 0; x < size; x++) {\n for (let y = 0; y < size; y++) {\n value = Math.floor(rand(0.42, 0.58) * 255);\n context.fillStyle = \"rgb(\" + value + \", \" + value + \", \" + value + \")\";\n context.fillRect(x, y, 1, 1);\n }\n }\n this._grainTexture.update(false);\n }\n}\n//# sourceMappingURL=lensRenderingPipeline.js.map","\n/**\n * Contains all parameters needed for the prepass to perform\n * screen space subsurface scattering\n */\nexport class SSAO2Configuration {\n constructor() {\n /**\n * Is subsurface enabled\n */\n this.enabled = false;\n /**\n * Name of the configuration\n */\n this.name = \"ssao2\";\n /**\n * Textures that should be present in the MRT for this effect to work\n */\n this.texturesRequired = [6, 5];\n }\n}\n//# sourceMappingURL=ssao2Configuration.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"ssao2PixelShader\";\nconst shader = `precision highp float;\runiform sampler2D textureSampler;\rvarying vec2 vUV;\r#ifdef SSAO\nfloat scales[16]=float[16](\r0.1,\r0.11406250000000001,\r0.131640625,\r0.15625,\r0.187890625,\r0.2265625,\r0.272265625,\r0.325,\r0.384765625,\r0.4515625,\r0.525390625,\r0.60625,\r0.694140625,\r0.7890625,\r0.891015625,\r1.0\r);\runiform float near;\runiform float radius;\runiform sampler2D depthSampler;\runiform sampler2D randomSampler;\runiform sampler2D normalSampler;\runiform float randTextureTiles;\runiform float samplesFactor;\runiform vec3 sampleSphere[SAMPLES];\runiform float totalStrength;\runiform float base;\runiform float xViewport;\runiform float yViewport;\runiform mat3 depthProjection;\runiform float maxZ;\runiform float minZAspect;\runiform vec2 texelSize;\runiform mat4 projection;\rvoid main()\r{\rvec3 random=textureLod(randomSampler,vUV*randTextureTiles,0.0).rgb;\rfloat depth=textureLod(depthSampler,vUV,0.0).r;\rfloat depthSign=depth/abs(depth);\rdepth=depth*depthSign;\rvec3 normal=textureLod(normalSampler,vUV,0.0).rgb;\rfloat occlusion=0.0;\rfloat correctedRadius=min(radius,minZAspect*depth/near);\rvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\rvec3 vDepthFactor=depthProjection*vec3(1.0,1.0,depth);\rvec3 origin=vViewRay*vDepthFactor;\rvec3 rvec=random*2.0-1.0;\rrvec.z=0.0;\rfloat dotProduct=dot(rvec,normal);\rrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\rvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\rvec3 bitangent=cross(normal,tangent);\rmat3 tbn=mat3(tangent,bitangent,normal);\rfloat difference;\rfor (int i=0; i1.0 || offset.y>1.0) {\rcontinue;\r}\rfloat sampleDepth=abs(textureLod(depthSampler,offset.xy,0.0).r);\rdifference=depthSign*samplePosition.z-sampleDepth;\rfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\rocclusion+=step(EPSILON,difference)*rangeCheck;\r}\rocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\rfloat ao=1.0-totalStrength*occlusion*samplesFactor;\rfloat result=clamp(ao+base,0.0,1.0);\rgl_FragColor=vec4(vec3(result),1.0);\r}\r#endif\n#ifdef BLUR\nuniform float outSize;\runiform float soften;\runiform float tolerance;\runiform int samples;\r#ifndef BLUR_BYPASS\nuniform sampler2D depthSampler;\r#ifdef BLUR_LEGACY\n#define inline\nfloat blur13Bilateral(sampler2D image,vec2 uv,vec2 step) {\rfloat result=0.0;\rvec2 off1=vec2(1.411764705882353)*step;\rvec2 off2=vec2(3.2941176470588234)*step;\rvec2 off3=vec2(5.176470588235294)*step;\rfloat compareDepth=abs(textureLod(depthSampler,uv,0.0).r);\rfloat sampleDepth;\rfloat weight;\rfloat weightSum=30.0;\rresult+=textureLod(image,uv,0.0).r*30.0;\rsampleDepth=abs(textureLod(depthSampler,uv+off1,0.0).r);\rweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\rweightSum+= weight;\rresult+=textureLod(image,uv+off1,0.0).r*weight;\rsampleDepth=abs(textureLod(depthSampler,uv-off1,0.0).r);\rweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\rweightSum+= weight;\rresult+=textureLod(image,uv-off1,0.0).r*weight;\rsampleDepth=abs(textureLod(depthSampler,uv+off2,0.0).r);\rweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\rweightSum+=weight;\rresult+=textureLod(image,uv+off2,0.0).r*weight;\rsampleDepth=abs(textureLod(depthSampler,uv-off2,0.0).r);\rweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\rweightSum+=weight;\rresult+=textureLod(image,uv-off2,0.0).r*weight;\rsampleDepth=abs(textureLod(depthSampler,uv+off3,0.0).r);\rweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\rweightSum+=weight;\rresult+=textureLod(image,uv+off3,0.0).r*weight;\rsampleDepth=abs(textureLod(depthSampler,uv-off3,0.0).r);\rweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\rweightSum+=weight;\rresult+=textureLod(image,uv-off3,0.0).r*weight;\rreturn result/weightSum;\r}\r#endif\n#endif\nvoid main()\r{\rfloat result=0.0;\r#ifdef BLUR_BYPASS\nresult=textureLod(textureSampler,vUV,0.0).r;\r#else\n#ifdef BLUR_H\nvec2 step=vec2(1.0/outSize,0.0);\r#else\nvec2 step=vec2(0.0,1.0/outSize);\r#endif\n#ifdef BLUR_LEGACY\nresult=blur13Bilateral(textureSampler,vUV,step);\r#else\nfloat compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);\rfloat weightSum=0.0;\rfor (int i=-samples; i {\n return this._originalColorPostProcess;\n }, true));\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, () => {\n return this._ssaoPostProcess;\n }, true));\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, () => {\n return this._blurHPostProcess;\n }, true));\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, () => {\n return this._blurVPostProcess;\n }, true));\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, () => {\n return this._ssaoCombinePostProcess;\n }, true));\n // Finish\n scene.postProcessRenderPipelineManager.addPipeline(this);\n if (cameras) {\n scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);\n }\n }\n // Public Methods\n /**\n * Get the class name\n * @returns \"SSAO2RenderingPipeline\"\n */\n getClassName() {\n return \"SSAO2RenderingPipeline\";\n }\n /**\n * Removes the internal pipeline assets and detaches the pipeline from the scene cameras\n * @param disableGeometryBufferRenderer\n */\n dispose(disableGeometryBufferRenderer = false) {\n for (let i = 0; i < this._scene.cameras.length; i++) {\n const camera = this._scene.cameras[i];\n this._originalColorPostProcess.dispose(camera);\n this._ssaoPostProcess.dispose(camera);\n this._blurHPostProcess.dispose(camera);\n this._blurVPostProcess.dispose(camera);\n this._ssaoCombinePostProcess.dispose(camera);\n }\n this._randomTexture.dispose();\n if (disableGeometryBufferRenderer) {\n this._scene.disableGeometryBufferRenderer();\n }\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);\n super.dispose();\n }\n // Private Methods\n /** @internal */\n _rebuild() {\n super._rebuild();\n }\n _getSamplersForBlur(disabled) {\n return disabled ? [\"textureSampler\"] : [\"textureSampler\", \"depthSampler\"];\n }\n _getDefinesForBlur(bilateral, disabled) {\n let define = \"#define BLUR\\n\";\n if (disabled) {\n define += \"#define BLUR_BYPASS\\n\";\n }\n if (!bilateral) {\n define += \"#define BLUR_LEGACY\\n\";\n }\n return { h: define + \"#define BLUR_H\\n\", v: define };\n }\n _createBlurPostProcess(ssaoRatio, blurRatio, textureType) {\n const defines = this._getDefinesForBlur(this.expensiveBlur, this.bypassBlur);\n const samplers = this._getSamplersForBlur(this.bypassBlur);\n this._blurHPostProcess = this._createBlurFilter(\"BlurH\", samplers, ssaoRatio, defines.h, textureType, true);\n this._blurVPostProcess = this._createBlurFilter(\"BlurV\", samplers, blurRatio, defines.v, textureType, false);\n }\n _createBlurFilter(name, samplers, ratio, defines, textureType, horizontal) {\n const blurFilter = new PostProcess(name, \"ssao2\", [\"outSize\", \"samples\", \"soften\", \"tolerance\"], samplers, ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, defines, textureType);\n blurFilter.onApply = (effect) => {\n if (!this._scene.activeCamera) {\n return;\n }\n const ssaoCombineSize = horizontal ? this._ssaoCombinePostProcess.width : this._ssaoCombinePostProcess.height;\n const originalColorSize = horizontal ? this._originalColorPostProcess.width : this._originalColorPostProcess.height;\n effect.setFloat(\"outSize\", ssaoCombineSize > 0 ? ssaoCombineSize : originalColorSize);\n effect.setInt(\"samples\", this.bilateralSamples);\n effect.setFloat(\"soften\", this.bilateralSoften);\n effect.setFloat(\"tolerance\", this.bilateralTolerance);\n if (this._geometryBufferRenderer) {\n effect.setTexture(\"depthSampler\", this._geometryBufferRenderer.getGBuffer().textures[0]);\n }\n else if (this._prePassRenderer) {\n effect.setTexture(\"depthSampler\", this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]);\n }\n };\n blurFilter.samples = this.textureSamples;\n return blurFilter;\n }\n //Van der Corput radical inverse\n _radicalInverse_VdC(i) {\n this._bits[0] = i;\n this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;\n this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | (((this._bits[0] & 0xaaaaaaaa) >>> 1) >>> 0);\n this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | (((this._bits[0] & 0xcccccccc) >>> 2) >>> 0);\n this._bits[0] = ((this._bits[0] & 0x0f0f0f0f) << 4) | (((this._bits[0] & 0xf0f0f0f0) >>> 4) >>> 0);\n this._bits[0] = ((this._bits[0] & 0x00ff00ff) << 8) | (((this._bits[0] & 0xff00ff00) >>> 8) >>> 0);\n return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296\n }\n _hammersley(i, n) {\n return [i / n, this._radicalInverse_VdC(i)];\n }\n _hemisphereSample_uniform(u, v) {\n const phi = v * 2.0 * Math.PI;\n // rejecting samples that are close to tangent plane to avoid z-fighting artifacts\n const cosTheta = 1.0 - u * 0.85;\n const sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);\n return new Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);\n }\n _generateHemisphere() {\n const numSamples = this.samples;\n const result = [];\n let vector;\n let i = 0;\n while (i < numSamples) {\n if (numSamples < 16) {\n vector = this._hemisphereSample_uniform(Math.random(), Math.random());\n }\n else {\n const rand = this._hammersley(i, numSamples);\n vector = this._hemisphereSample_uniform(rand[0], rand[1]);\n }\n result.push(vector.x, vector.y, vector.z);\n i++;\n }\n return result;\n }\n _getDefinesForSSAO() {\n const defines = `#define SSAO\\n#define SAMPLES ${this.samples}\\n#define EPSILON ${this.epsilon.toFixed(4)}`;\n return defines;\n }\n _createSSAOPostProcess(ratio, textureType) {\n this._sampleSphere = this._generateHemisphere();\n const defines = this._getDefinesForSSAO();\n const samplers = [\"randomSampler\", \"depthSampler\", \"normalSampler\"];\n this._ssaoPostProcess = new PostProcess(\"ssao2\", \"ssao2\", [\n \"sampleSphere\",\n \"samplesFactor\",\n \"randTextureTiles\",\n \"totalStrength\",\n \"radius\",\n \"base\",\n \"range\",\n \"projection\",\n \"near\",\n \"texelSize\",\n \"xViewport\",\n \"yViewport\",\n \"maxZ\",\n \"minZAspect\",\n \"depthProjection\",\n ], samplers, ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, defines, textureType);\n this._ssaoPostProcess.onApply = (effect) => {\n var _a, _b, _c, _d;\n if (!this._scene.activeCamera) {\n return;\n }\n effect.setArray3(\"sampleSphere\", this._sampleSphere);\n effect.setFloat(\"randTextureTiles\", 32.0);\n effect.setFloat(\"samplesFactor\", 1 / this.samples);\n effect.setFloat(\"totalStrength\", this.totalStrength);\n effect.setFloat2(\"texelSize\", 1 / this._ssaoPostProcess.width, 1 / this._ssaoPostProcess.height);\n effect.setFloat(\"radius\", this.radius);\n effect.setFloat(\"maxZ\", this.maxZ);\n effect.setFloat(\"minZAspect\", this.minZAspect);\n effect.setFloat(\"base\", this.base);\n effect.setFloat(\"near\", this._scene.activeCamera.minZ);\n if (this._scene.activeCamera.mode === Camera.PERSPECTIVE_CAMERA) {\n effect.setMatrix3x3(\"depthProjection\", SSAO2RenderingPipeline.PERSPECTIVE_DEPTH_PROJECTION);\n effect.setFloat(\"xViewport\", Math.tan(this._scene.activeCamera.fov / 2) * this._scene.getEngine().getAspectRatio(this._scene.activeCamera, true));\n effect.setFloat(\"yViewport\", Math.tan(this._scene.activeCamera.fov / 2));\n }\n else {\n const halfWidth = this._scene.getEngine().getRenderWidth() / 2.0;\n const halfHeight = this._scene.getEngine().getRenderHeight() / 2.0;\n const orthoLeft = (_a = this._scene.activeCamera.orthoLeft) !== null && _a !== void 0 ? _a : -halfWidth;\n const orthoRight = (_b = this._scene.activeCamera.orthoRight) !== null && _b !== void 0 ? _b : halfWidth;\n const orthoBottom = (_c = this._scene.activeCamera.orthoBottom) !== null && _c !== void 0 ? _c : -halfHeight;\n const orthoTop = (_d = this._scene.activeCamera.orthoTop) !== null && _d !== void 0 ? _d : halfHeight;\n effect.setMatrix3x3(\"depthProjection\", SSAO2RenderingPipeline.ORTHO_DEPTH_PROJECTION);\n effect.setFloat(\"xViewport\", (orthoRight - orthoLeft) * 0.5);\n effect.setFloat(\"yViewport\", (orthoTop - orthoBottom) * 0.5);\n }\n effect.setMatrix(\"projection\", this._scene.getProjectionMatrix());\n if (this._geometryBufferRenderer) {\n effect.setTexture(\"depthSampler\", this._geometryBufferRenderer.getGBuffer().textures[0]);\n effect.setTexture(\"normalSampler\", this._geometryBufferRenderer.getGBuffer().textures[1]);\n }\n else if (this._prePassRenderer) {\n effect.setTexture(\"depthSampler\", this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]);\n effect.setTexture(\"normalSampler\", this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)]);\n }\n effect.setTexture(\"randomSampler\", this._randomTexture);\n };\n this._ssaoPostProcess.samples = this.textureSamples;\n if (!this._forceGeometryBuffer) {\n this._ssaoPostProcess._prePassEffectConfiguration = new SSAO2Configuration();\n }\n }\n _createSSAOCombinePostProcess(ratio, textureType) {\n this._ssaoCombinePostProcess = new PostProcess(\"ssaoCombine\", \"ssaoCombine\", [], [\"originalColor\", \"viewport\"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, undefined, textureType);\n this._ssaoCombinePostProcess.onApply = (effect) => {\n const viewport = this._scene.activeCamera.viewport;\n effect.setVector4(\"viewport\", TmpVectors.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));\n effect.setTextureFromPostProcessOutput(\"originalColor\", this._originalColorPostProcess);\n };\n this._ssaoCombinePostProcess.samples = this.textureSamples;\n }\n _createRandomTexture() {\n const size = 128;\n this._randomTexture = new DynamicTexture(\"SSAORandomTexture\", size, this._scene, false, Texture.BILINEAR_SAMPLINGMODE);\n this._randomTexture.wrapU = Texture.WRAP_ADDRESSMODE;\n this._randomTexture.wrapV = Texture.WRAP_ADDRESSMODE;\n const context = this._randomTexture.getContext();\n const rand = (min, max) => {\n return Math.random() * (max - min) + min;\n };\n const randVector = Vector3.Zero();\n for (let x = 0; x < size; x++) {\n for (let y = 0; y < size; y++) {\n randVector.x = rand(0.0, 1.0);\n randVector.y = rand(0.0, 1.0);\n randVector.z = 0.0;\n randVector.normalize();\n randVector.scaleInPlace(255);\n randVector.x = Math.floor(randVector.x);\n randVector.y = Math.floor(randVector.y);\n context.fillStyle = \"rgb(\" + randVector.x + \", \" + randVector.y + \", \" + randVector.z + \")\";\n context.fillRect(x, y, 1, 1);\n }\n }\n this._randomTexture.update(false);\n }\n /**\n * Serialize the rendering pipeline (Used when exporting)\n * @returns the serialized object\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this);\n serializationObject.customType = \"SSAO2RenderingPipeline\";\n return serializationObject;\n }\n /**\n * Parse the serialized pipeline\n * @param source Source pipeline.\n * @param scene The scene to load the pipeline to.\n * @param rootUrl The URL of the serialized pipeline.\n * @returns An instantiated pipeline from the serialized object.\n */\n static Parse(source, scene, rootUrl) {\n return SerializationHelper.Parse(() => new SSAO2RenderingPipeline(source._name, scene, source._ratio, undefined, source._forceGeometryBuffer, source._textureType), source, scene, rootUrl);\n }\n}\nSSAO2RenderingPipeline.ORTHO_DEPTH_PROJECTION = [1, 0, 0, 0, 1, 0, 0, 0, 1];\nSSAO2RenderingPipeline.PERSPECTIVE_DEPTH_PROJECTION = [0, 0, 0, 0, 0, 0, 1, 1, 1];\n__decorate([\n serialize()\n], SSAO2RenderingPipeline.prototype, \"totalStrength\", void 0);\n__decorate([\n serialize()\n], SSAO2RenderingPipeline.prototype, \"maxZ\", void 0);\n__decorate([\n serialize()\n], SSAO2RenderingPipeline.prototype, \"minZAspect\", void 0);\n__decorate([\n serialize(\"epsilon\")\n], SSAO2RenderingPipeline.prototype, \"_epsilon\", void 0);\n__decorate([\n serialize(\"samples\")\n], SSAO2RenderingPipeline.prototype, \"_samples\", void 0);\n__decorate([\n serialize(\"textureSamples\")\n], SSAO2RenderingPipeline.prototype, \"_textureSamples\", void 0);\n__decorate([\n serialize()\n], SSAO2RenderingPipeline.prototype, \"_forceGeometryBuffer\", void 0);\n__decorate([\n serialize()\n], SSAO2RenderingPipeline.prototype, \"_ratio\", void 0);\n__decorate([\n serialize()\n], SSAO2RenderingPipeline.prototype, \"_textureType\", void 0);\n__decorate([\n serialize()\n], SSAO2RenderingPipeline.prototype, \"radius\", void 0);\n__decorate([\n serialize()\n], SSAO2RenderingPipeline.prototype, \"base\", void 0);\n__decorate([\n serialize(\"bypassBlur\")\n], SSAO2RenderingPipeline.prototype, \"_bypassBlur\", void 0);\n__decorate([\n serialize(\"expensiveBlur\")\n], SSAO2RenderingPipeline.prototype, \"_expensiveBlur\", void 0);\n__decorate([\n serialize()\n], SSAO2RenderingPipeline.prototype, \"bilateralSamples\", void 0);\n__decorate([\n serialize()\n], SSAO2RenderingPipeline.prototype, \"bilateralSoften\", void 0);\n__decorate([\n serialize()\n], SSAO2RenderingPipeline.prototype, \"bilateralTolerance\", void 0);\nRegisterClass(\"BABYLON.SSAO2RenderingPipeline\", SSAO2RenderingPipeline);\n//# sourceMappingURL=ssao2RenderingPipeline.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"ssaoPixelShader\";\nconst shader = `uniform sampler2D textureSampler;\rvarying vec2 vUV;\r#ifdef SSAO\nuniform sampler2D randomSampler;\runiform float randTextureTiles;\runiform float samplesFactor;\runiform vec3 sampleSphere[SAMPLES];\runiform float totalStrength;\runiform float radius;\runiform float area;\runiform float fallOff;\runiform float base;\rvec3 normalFromDepth(float depth,vec2 coords)\r{\rvec2 offset1=vec2(0.0,radius);\rvec2 offset2=vec2(radius,0.0);\rfloat depth1=texture2D(textureSampler,coords+offset1).r;\rfloat depth2=texture2D(textureSampler,coords+offset2).r;\rvec3 p1=vec3(offset1,depth1-depth);\rvec3 p2=vec3(offset2,depth2-depth);\rvec3 normal=cross(p1,p2);\rnormal.z=-normal.z;\rreturn normalize(normal);\r}\rvoid main()\r{\rvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\rfloat depth=texture2D(textureSampler,vUV).r;\rvec3 position=vec3(vUV,depth);\rvec3 normal=normalFromDepth(depth,vUV);\rfloat radiusDepth=radius/depth;\rfloat occlusion=0.0;\rvec3 ray;\rvec3 hemiRay;\rfloat occlusionDepth;\rfloat difference;\rfor (int i=0; i {\n return this._originalColorPostProcess;\n }, true));\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, () => {\n return this._ssaoPostProcess;\n }, true));\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, () => {\n return this._blurHPostProcess;\n }, true));\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, () => {\n return this._blurVPostProcess;\n }, true));\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, () => {\n return this._ssaoCombinePostProcess;\n }, true));\n // Finish\n scene.postProcessRenderPipelineManager.addPipeline(this);\n if (cameras) {\n scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);\n }\n }\n /**\n * @internal\n */\n _attachCameras(cameras, unique) {\n super._attachCameras(cameras, unique);\n for (const camera of this._cameras) {\n this._scene.enableDepthRenderer(camera).getDepthMap(); // Force depth renderer \"on\"\n }\n }\n // Public Methods\n /**\n * Get the class name\n * @returns \"SSAORenderingPipeline\"\n */\n getClassName() {\n return \"SSAORenderingPipeline\";\n }\n /**\n * Removes the internal pipeline assets and detaches the pipeline from the scene cameras\n * @param disableDepthRender\n */\n dispose(disableDepthRender = false) {\n for (let i = 0; i < this._scene.cameras.length; i++) {\n const camera = this._scene.cameras[i];\n this._originalColorPostProcess.dispose(camera);\n this._ssaoPostProcess.dispose(camera);\n this._blurHPostProcess.dispose(camera);\n this._blurVPostProcess.dispose(camera);\n this._ssaoCombinePostProcess.dispose(camera);\n }\n this._randomTexture.dispose();\n if (disableDepthRender) {\n this._scene.disableDepthRenderer();\n }\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);\n super.dispose();\n }\n // Private Methods\n _createBlurPostProcess(ratio) {\n const size = 16;\n this._blurHPostProcess = new BlurPostProcess(\"BlurH\", new Vector2(1, 0), size, ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, 0);\n this._blurVPostProcess = new BlurPostProcess(\"BlurV\", new Vector2(0, 1), size, ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, 0);\n this._blurHPostProcess.onActivateObservable.add(() => {\n const dw = this._blurHPostProcess.width / this._scene.getEngine().getRenderWidth();\n this._blurHPostProcess.kernel = size * dw;\n });\n this._blurVPostProcess.onActivateObservable.add(() => {\n const dw = this._blurVPostProcess.height / this._scene.getEngine().getRenderHeight();\n this._blurVPostProcess.kernel = size * dw;\n });\n }\n /** @internal */\n _rebuild() {\n this._firstUpdate = true;\n super._rebuild();\n }\n _createSSAOPostProcess(ratio) {\n const numSamples = 16;\n const sampleSphere = [\n 0.5381, 0.1856, -0.4319, 0.1379, 0.2486, 0.443, 0.3371, 0.5679, -0.0057, -0.6999, -0.0451, -0.0019, 0.0689, -0.1598, -0.8547, 0.056, 0.0069, -0.1843, -0.0146, 0.1402,\n 0.0762, 0.01, -0.1924, -0.0344, -0.3577, -0.5301, -0.4358, -0.3169, 0.1063, 0.0158, 0.0103, -0.5869, 0.0046, -0.0897, -0.494, 0.3287, 0.7119, -0.0154, -0.0918, -0.0533,\n 0.0596, -0.5411, 0.0352, -0.0631, 0.546, -0.4776, 0.2847, -0.0271,\n ];\n const samplesFactor = 1.0 / numSamples;\n this._ssaoPostProcess = new PostProcess(\"ssao\", \"ssao\", [\"sampleSphere\", \"samplesFactor\", \"randTextureTiles\", \"totalStrength\", \"radius\", \"area\", \"fallOff\", \"base\", \"range\", \"viewport\"], [\"randomSampler\"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, \"#define SAMPLES \" + numSamples + \"\\n#define SSAO\");\n this._ssaoPostProcess.externalTextureSamplerBinding = true;\n this._ssaoPostProcess.onApply = (effect) => {\n if (this._firstUpdate) {\n effect.setArray3(\"sampleSphere\", sampleSphere);\n effect.setFloat(\"samplesFactor\", samplesFactor);\n effect.setFloat(\"randTextureTiles\", 4.0);\n }\n effect.setFloat(\"totalStrength\", this.totalStrength);\n effect.setFloat(\"radius\", this.radius);\n effect.setFloat(\"area\", this.area);\n effect.setFloat(\"fallOff\", this.fallOff);\n effect.setFloat(\"base\", this.base);\n effect.setTexture(\"textureSampler\", this._scene.enableDepthRenderer(this._scene.activeCamera).getDepthMap());\n effect.setTexture(\"randomSampler\", this._randomTexture);\n };\n }\n _createSSAOCombinePostProcess(ratio) {\n this._ssaoCombinePostProcess = new PostProcess(\"ssaoCombine\", \"ssaoCombine\", [], [\"originalColor\", \"viewport\"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);\n this._ssaoCombinePostProcess.onApply = (effect) => {\n effect.setVector4(\"viewport\", TmpVectors.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));\n effect.setTextureFromPostProcess(\"originalColor\", this._originalColorPostProcess);\n };\n }\n _createRandomTexture() {\n const size = 512;\n this._randomTexture = new DynamicTexture(\"SSAORandomTexture\", size, this._scene, false, Texture.TRILINEAR_SAMPLINGMODE);\n this._randomTexture.wrapU = Texture.WRAP_ADDRESSMODE;\n this._randomTexture.wrapV = Texture.WRAP_ADDRESSMODE;\n const context = this._randomTexture.getContext();\n const rand = (min, max) => {\n return Math.random() * (max - min) + min;\n };\n const randVector = Vector3.Zero();\n for (let x = 0; x < size; x++) {\n for (let y = 0; y < size; y++) {\n randVector.x = Math.floor(Math.max(0.0, rand(-1.0, 1.0)) * 255);\n randVector.y = Math.floor(Math.max(0.0, rand(-1.0, 1.0)) * 255);\n randVector.z = Math.floor(Math.max(0.0, rand(-1.0, 1.0)) * 255);\n context.fillStyle = \"rgb(\" + randVector.x + \", \" + randVector.y + \", \" + randVector.z + \")\";\n context.fillRect(x, y, 1, 1);\n }\n }\n this._randomTexture.update(false);\n }\n}\n__decorate([\n serialize()\n], SSAORenderingPipeline.prototype, \"totalStrength\", void 0);\n__decorate([\n serialize()\n], SSAORenderingPipeline.prototype, \"radius\", void 0);\n__decorate([\n serialize()\n], SSAORenderingPipeline.prototype, \"area\", void 0);\n__decorate([\n serialize()\n], SSAORenderingPipeline.prototype, \"fallOff\", void 0);\n__decorate([\n serialize()\n], SSAORenderingPipeline.prototype, \"base\", void 0);\n//# sourceMappingURL=ssaoRenderingPipeline.js.map","\n/**\n * Contains all parameters needed for the prepass to perform\n * screen space reflections\n */\nexport class ScreenSpaceReflectionsConfiguration {\n constructor() {\n /**\n * Is ssr enabled\n */\n this.enabled = false;\n /**\n * Name of the configuration\n */\n this.name = \"screenSpaceReflections\";\n /**\n * Textures that should be present in the MRT for this effect to work\n */\n this.texturesRequired = [6, 3, 1];\n }\n}\n//# sourceMappingURL=screenSpaceReflectionsConfiguration.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"screenSpaceReflectionPixelShader\";\nconst shader = `uniform sampler2D textureSampler;\r#ifdef SSR_SUPPORTED\nuniform sampler2D reflectivitySampler;\runiform sampler2D normalSampler;\runiform sampler2D positionSampler;\r#endif\nuniform mat4 view;\runiform mat4 projection;\runiform float stepSize;\runiform float strength;\runiform float threshold;\runiform float roughnessFactor;\runiform float reflectionSpecularFalloffExponent;\rvarying vec2 vUV;\r#ifdef SSR_SUPPORTED\nstruct ReflectionInfo {\rvec3 color;\rvec4 coords;\r};\r/**\r* According to specular,see https:\r*/\rvec3 fresnelSchlick(float cosTheta,vec3 F0)\r{\rreturn F0+(1.0-F0)*pow(1.0-cosTheta,5.0);\r}\r/**\r* Once the pixel's coordinates has been found,let's adjust (smooth) a little bit\r* by sampling multiple reflection pixels.\r*/\rReflectionInfo smoothReflectionInfo(vec3 dir,vec3 hitCoord)\r{\rReflectionInfo info;\rinfo.color=vec3(0.0);\rvec4 projectedCoord;\rfloat sampledDepth;\rfor(int i=0; i0.0)\rhitCoord-=dir;\relse\rhitCoord+=dir;\rinfo.color+=texture2D(textureSampler,projectedCoord.xy).rgb;\r}\rprojectedCoord=projection*vec4(hitCoord,1.0);\rprojectedCoord.xy/=projectedCoord.w;\rprojectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);\rinfo.coords=vec4(projectedCoord.xy,sampledDepth,1.0);\rinfo.color+=texture2D(textureSampler,projectedCoord.xy).rgb;\rinfo.color/=float(SMOOTH_STEPS+1);\rreturn info;\r}\r/**\r* Tests the given world position (hitCoord) according to the given reflection vector (dir)\r* until it finds a collision (means that depth is enough close to say \"it's the pixel to sample!\").\r*/\rReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord)\r{\rReflectionInfo info;\rvec4 projectedCoord;\rfloat sampledDepth;\rdir*=stepSize;\rfor(int i=0; ishadowPixelDepth)\raccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\rcurrentPosition+=stepL;\r}\raccumFog/=NB_STEPS;\rvec3 color=accumFog*scatteringPower;\rgl_FragColor=vec4(color*exp(color) ,1.0);\r}\r#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\rvoid main(void)\r{\rgl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\r}\r#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\rvoid main()\r{\rfloat average=0.0;\rvec4 color=vec4(0.0);\rfloat maximum=-1e20;\rvec3 weight=vec3(0.299,0.587,0.114);\rfor (int i=0; i<4; i++)\r{\rcolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\rfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\r#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\r#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\r#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\r#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\r#endif\nmaximum=max(maximum,GreyValue);\raverage+=(0.25*log(1e-5+GreyValue));\r}\raverage=exp(average);\rgl_FragColor=vec4(average,maximum,0.0,1.0);\r}\r#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\runiform float halfDestPixelSize;\r#ifdef FINAL_DOWN_SAMPLER\n#include\n#endif\nvoid main()\r{\rvec4 color=vec4(0.0);\rfloat average=0.0;\rfor (int i=0; i<9; i++)\r{\rcolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\raverage+=color.r;\r}\raverage/=9.0;\r#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\r#else\ngl_FragColor=vec4(average,average,0.0,1.0);\r#endif\n}\r#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\runiform float averageLuminance;\rvoid main()\r{\rvec4 color=texture2D(textureAdderSampler,vUV);\r#ifndef AUTO_EXPOSURE\nvec4 adjustedColor=color/averageLuminance;\rcolor=adjustedColor;\rcolor.a=1.0;\r#endif\ngl_FragColor=color;\r}\r#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\runiform float strength;\runiform float ghostDispersal;\runiform float haloWidth;\runiform vec2 resolution;\runiform float distortionStrength;\rfloat hash(vec2 p)\r{\rfloat h=dot(p,vec2(127.1,311.7));\rreturn -1.0+2.0*fract(sin(h)*43758.5453123);\r}\rfloat noise(in vec2 p)\r{\rvec2 i=floor(p);\rvec2 f=fract(p);\rvec2 u=f*f*(3.0-2.0*f);\rreturn mix(mix(hash(i+vec2(0.0,0.0)),\rhash(i+vec2(1.0,0.0)),u.x),\rmix(hash(i+vec2(0.0,1.0)),\rhash(i+vec2(1.0,1.0)),u.x),u.y);\r}\rfloat fbm(vec2 p)\r{\rfloat f=0.0;\rf+=0.5000*noise(p); p*=2.02;\rf+=0.2500*noise(p); p*=2.03;\rf+=0.1250*noise(p); p*=2.01;\rf+=0.0625*noise(p); p*=2.04;\rf/=0.9375;\rreturn f;\r}\rvec3 pattern(vec2 uv)\r{\rvec2 p=-1.0+2.0*uv;\rfloat p2=dot(p,p);\rfloat f=fbm(vec2(15.0*p2))/2.0;\rfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\rfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\rfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\rreturn (1.0-f)*vec3(r,g,b);\r}\rfloat luminance(vec3 color)\r{\rreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\r}\rvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\r{\rreturn vec4(\rtexture2D(tex,texcoord+direction*distortion.r).r,\rtexture2D(tex,texcoord+direction*distortion.g).g,\rtexture2D(tex,texcoord+direction*distortion.b).b,\r1.0\r);\r}\rvoid main(void)\r{\rvec2 uv=-vUV+vec2(1.0);\rvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\rvec2 texelSize=1.0/resolution;\rvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\rvec4 result=vec4(0.0);\rfloat ghostIndice=1.0;\rfor (int i=0; i=nSamples)\rbreak;\rvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\rresult+=texture2D(textureSampler,offset1);\r}\rgl_FragColor=result/float(nSamples);\r}\r#endif\n`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const standardPixelShader = { name, shader };\n//# sourceMappingURL=standard.fragment.js.map","import { __decorate } from \"../../../tslib.es6.js\";\nimport { serialize, serializeAsTexture, SerializationHelper } from \"../../../Misc/decorators.js\";\nimport { Logger } from \"../../../Misc/logger.js\";\nimport { Vector2, Vector3, Matrix, Vector4 } from \"../../../Maths/math.vector.js\";\nimport { Scalar } from \"../../../Maths/math.scalar.js\";\nimport { Texture } from \"../../../Materials/Textures/texture.js\";\nimport { PostProcess } from \"../../../PostProcesses/postProcess.js\";\nimport { PostProcessRenderPipeline } from \"../../../PostProcesses/RenderPipeline/postProcessRenderPipeline.js\";\nimport { PostProcessRenderEffect } from \"../../../PostProcesses/RenderPipeline/postProcessRenderEffect.js\";\nimport { BlurPostProcess } from \"../../../PostProcesses/blurPostProcess.js\";\nimport { FxaaPostProcess } from \"../../../PostProcesses/fxaaPostProcess.js\";\n\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { MotionBlurPostProcess } from \"../../motionBlurPostProcess.js\";\nimport { ScreenSpaceReflectionPostProcess } from \"../../screenSpaceReflectionPostProcess.js\";\nimport \"../../../PostProcesses/RenderPipeline/postProcessRenderPipelineManagerSceneComponent.js\";\nimport \"../../../Shaders/standard.fragment.js\";\n/**\n * Standard rendering pipeline\n * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/standardRenderingPipeline\n */\nexport class StandardRenderingPipeline extends PostProcessRenderPipeline {\n /**\n * Gets the overall exposure used by the pipeline\n */\n get exposure() {\n return this._fixedExposure;\n }\n /**\n * Sets the overall exposure used by the pipeline\n */\n set exposure(value) {\n this._fixedExposure = value;\n this._currentExposure = value;\n }\n /**\n * Gets whether or not the exposure of the overall pipeline should be automatically adjusted by the HDR post-process\n */\n get hdrAutoExposure() {\n return this._hdrAutoExposure;\n }\n /**\n * Sets whether or not the exposure of the overall pipeline should be automatically adjusted by the HDR post-process\n */\n set hdrAutoExposure(value) {\n this._hdrAutoExposure = value;\n if (this.hdrPostProcess) {\n const defines = [\"#define HDR\"];\n if (value) {\n defines.push(\"#define AUTO_EXPOSURE\");\n }\n this.hdrPostProcess.updateEffect(defines.join(\"\\n\"));\n }\n }\n /**\n * Gets how much the image is blurred by the movement while using the motion blur post-process\n */\n get motionStrength() {\n return this._motionStrength;\n }\n /**\n * Sets how much the image is blurred by the movement while using the motion blur post-process\n */\n set motionStrength(strength) {\n this._motionStrength = strength;\n if (this._isObjectBasedMotionBlur && this.motionBlurPostProcess) {\n this.motionBlurPostProcess.motionStrength = strength;\n }\n }\n /**\n * Gets whether or not the motion blur post-process is object based or screen based.\n */\n get objectBasedMotionBlur() {\n return this._isObjectBasedMotionBlur;\n }\n /**\n * Sets whether or not the motion blur post-process should be object based or screen based\n */\n set objectBasedMotionBlur(value) {\n const shouldRebuild = this._isObjectBasedMotionBlur !== value;\n this._isObjectBasedMotionBlur = value;\n if (shouldRebuild) {\n this._buildPipeline();\n }\n }\n /**\n * @ignore\n * Specifies if the bloom pipeline is enabled\n */\n get BloomEnabled() {\n return this._bloomEnabled;\n }\n set BloomEnabled(enabled) {\n if (this._bloomEnabled === enabled) {\n return;\n }\n this._bloomEnabled = enabled;\n this._buildPipeline();\n }\n /**\n * @ignore\n * Specifies if the depth of field pipeline is enabled\n */\n get DepthOfFieldEnabled() {\n return this._depthOfFieldEnabled;\n }\n set DepthOfFieldEnabled(enabled) {\n if (this._depthOfFieldEnabled === enabled) {\n return;\n }\n this._depthOfFieldEnabled = enabled;\n this._buildPipeline();\n }\n /**\n * @ignore\n * Specifies if the lens flare pipeline is enabled\n */\n get LensFlareEnabled() {\n return this._lensFlareEnabled;\n }\n set LensFlareEnabled(enabled) {\n if (this._lensFlareEnabled === enabled) {\n return;\n }\n this._lensFlareEnabled = enabled;\n this._buildPipeline();\n }\n /**\n * @ignore\n * Specifies if the HDR pipeline is enabled\n */\n get HDREnabled() {\n return this._hdrEnabled;\n }\n set HDREnabled(enabled) {\n if (this._hdrEnabled === enabled) {\n return;\n }\n this._hdrEnabled = enabled;\n this._buildPipeline();\n }\n /**\n * @ignore\n * Specifies if the volumetric lights scattering effect is enabled\n */\n get VLSEnabled() {\n return this._vlsEnabled;\n }\n // eslint-disable-next-line @typescript-eslint/naming-convention\n set VLSEnabled(enabled) {\n if (this._vlsEnabled === enabled) {\n return;\n }\n if (enabled) {\n const geometry = this._scene.enableGeometryBufferRenderer();\n if (!geometry) {\n Logger.Warn(\"Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline\");\n return;\n }\n }\n this._vlsEnabled = enabled;\n this._buildPipeline();\n }\n /**\n * @ignore\n * Specifies if the motion blur effect is enabled\n */\n get MotionBlurEnabled() {\n return this._motionBlurEnabled;\n }\n set MotionBlurEnabled(enabled) {\n if (this._motionBlurEnabled === enabled) {\n return;\n }\n this._motionBlurEnabled = enabled;\n this._buildPipeline();\n }\n /**\n * Specifies if anti-aliasing is enabled\n */\n get fxaaEnabled() {\n return this._fxaaEnabled;\n }\n set fxaaEnabled(enabled) {\n if (this._fxaaEnabled === enabled) {\n return;\n }\n this._fxaaEnabled = enabled;\n this._buildPipeline();\n }\n /**\n * Specifies if screen space reflections are enabled.\n */\n get screenSpaceReflectionsEnabled() {\n return this._screenSpaceReflectionsEnabled;\n }\n set screenSpaceReflectionsEnabled(enabled) {\n if (this._screenSpaceReflectionsEnabled === enabled) {\n return;\n }\n this._screenSpaceReflectionsEnabled = enabled;\n this._buildPipeline();\n }\n /**\n * Specifies the number of steps used to calculate the volumetric lights\n * Typically in interval [50, 200]\n */\n get volumetricLightStepsCount() {\n return this._volumetricLightStepsCount;\n }\n set volumetricLightStepsCount(count) {\n if (this.volumetricLightPostProcess) {\n this.volumetricLightPostProcess.updateEffect(\"#define VLS\\n#define NB_STEPS \" + count.toFixed(1));\n }\n this._volumetricLightStepsCount = count;\n }\n /**\n * Specifies the number of samples used for the motion blur effect\n * Typically in interval [16, 64]\n */\n get motionBlurSamples() {\n return this._motionBlurSamples;\n }\n set motionBlurSamples(samples) {\n if (this.motionBlurPostProcess) {\n if (this._isObjectBasedMotionBlur) {\n this.motionBlurPostProcess.motionBlurSamples = samples;\n }\n else {\n this.motionBlurPostProcess.updateEffect(\"#define MOTION_BLUR\\n#define MAX_MOTION_SAMPLES \" + samples.toFixed(1));\n }\n }\n this._motionBlurSamples = samples;\n }\n /**\n * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)\n */\n get samples() {\n return this._samples;\n }\n set samples(sampleCount) {\n if (this._samples === sampleCount) {\n return;\n }\n this._samples = sampleCount;\n this._buildPipeline();\n }\n /**\n * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.\n * @constructor\n * @param name The rendering pipeline name\n * @param scene The scene linked to this pipeline\n * @param ratio The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)\n * @param originalPostProcess the custom original color post-process. Must be \"reusable\". Can be null.\n * @param cameras The array of cameras that the rendering pipeline will be attached to\n */\n constructor(name, scene, ratio, originalPostProcess = null, cameras) {\n super(scene.getEngine(), name);\n /**\n * Post-process used to down scale an image x4\n */\n this.downSampleX4PostProcess = null;\n /**\n * Post-process used to calculate the illuminated surfaces controlled by a threshold\n */\n this.brightPassPostProcess = null;\n /**\n * Post-process array storing all the horizontal blur post-processes used by the pipeline\n */\n this.blurHPostProcesses = [];\n /**\n * Post-process array storing all the vertical blur post-processes used by the pipeline\n */\n this.blurVPostProcesses = [];\n /**\n * Post-process used to add colors of 2 textures (typically brightness + real scene color)\n */\n this.textureAdderPostProcess = null;\n /**\n * Post-process used to create volumetric lighting effect\n */\n this.volumetricLightPostProcess = null;\n /**\n * Post-process used to smooth the previous volumetric light post-process on the X axis\n */\n this.volumetricLightSmoothXPostProcess = null;\n /**\n * Post-process used to smooth the previous volumetric light post-process on the Y axis\n */\n this.volumetricLightSmoothYPostProcess = null;\n /**\n * Post-process used to merge the volumetric light effect and the real scene color\n */\n this.volumetricLightMergePostProces = null;\n /**\n * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)\n */\n this.volumetricLightFinalPostProcess = null;\n /**\n * Base post-process used to calculate the average luminance of the final image for HDR\n */\n this.luminancePostProcess = null;\n /**\n * Post-processes used to create down sample post-processes in order to get\n * the average luminance of the final image for HDR\n * Array of length \"StandardRenderingPipeline.LuminanceSteps\"\n */\n this.luminanceDownSamplePostProcesses = [];\n /**\n * Post-process used to create a HDR effect (light adaptation)\n */\n this.hdrPostProcess = null;\n /**\n * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)\n */\n this.textureAdderFinalPostProcess = null;\n /**\n * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)\n */\n this.lensFlareFinalPostProcess = null;\n /**\n * Post-process used to merge the final HDR post-process and the real scene color\n */\n this.hdrFinalPostProcess = null;\n /**\n * Post-process used to create a lens flare effect\n */\n this.lensFlarePostProcess = null;\n /**\n * Post-process that merges the result of the lens flare post-process and the real scene color\n */\n this.lensFlareComposePostProcess = null;\n /**\n * Post-process used to create a motion blur effect\n */\n this.motionBlurPostProcess = null;\n /**\n * Post-process used to create a depth of field effect\n */\n this.depthOfFieldPostProcess = null;\n /**\n * The Fast Approximate Anti-Aliasing post process which attempts to remove aliasing from an image.\n */\n this.fxaaPostProcess = null;\n /**\n * Post-process used to simulate realtime reflections using the screen space and geometry renderer.\n */\n this.screenSpaceReflectionPostProcess = null;\n // Values\n /**\n * Represents the brightness threshold in order to configure the illuminated surfaces\n */\n this.brightThreshold = 1.0;\n /**\n * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)\n */\n this.blurWidth = 512.0;\n /**\n * Sets if the blur for highlighted surfaces must be only horizontal\n */\n this.horizontalBlur = false;\n /**\n * Texture used typically to simulate \"dirty\" on camera lens\n */\n this.lensTexture = null;\n /**\n * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]\n */\n this.volumetricLightCoefficient = 0.2;\n /**\n * The overall power of volumetric lights, typically in interval [0, 10] maximum\n */\n this.volumetricLightPower = 4.0;\n /**\n * Used the set the blur intensity to smooth the volumetric lights\n */\n this.volumetricLightBlurScale = 64.0;\n /**\n * Light (spot or directional) used to generate the volumetric lights rays\n * The source light must have a shadow generate so the pipeline can get its\n * depth map\n */\n this.sourceLight = null;\n /**\n * For eye adaptation, represents the minimum luminance the eye can see\n */\n this.hdrMinimumLuminance = 1.0;\n /**\n * For eye adaptation, represents the decrease luminance speed\n */\n this.hdrDecreaseRate = 0.5;\n /**\n * For eye adaptation, represents the increase luminance speed\n */\n this.hdrIncreaseRate = 0.5;\n /**\n * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled\n */\n this.lensColorTexture = null;\n /**\n * The overall strength for the lens flare effect\n */\n this.lensFlareStrength = 20.0;\n /**\n * Dispersion coefficient for lens flare ghosts\n */\n this.lensFlareGhostDispersal = 1.4;\n /**\n * Main lens flare halo width\n */\n this.lensFlareHaloWidth = 0.7;\n /**\n * Based on the lens distortion effect, defines how much the lens flare result\n * is distorted\n */\n this.lensFlareDistortionStrength = 16.0;\n /**\n * Configures the blur intensity used for for lens flare (halo)\n */\n this.lensFlareBlurWidth = 512.0;\n /**\n * Lens star texture must be used to simulate rays on the flares and is available\n * in the documentation\n */\n this.lensStarTexture = null;\n /**\n * As the \"lensTexture\" (can be the same texture or different), it is used to apply the lens\n * flare effect by taking account of the dirt texture\n */\n this.lensFlareDirtTexture = null;\n /**\n * Represents the focal length for the depth of field effect\n */\n this.depthOfFieldDistance = 10.0;\n /**\n * Represents the blur intensity for the blurred part of the depth of field effect\n */\n this.depthOfFieldBlurWidth = 64.0;\n /**\n * List of animations for the pipeline (IAnimatable implementation)\n */\n this.animations = [];\n this._currentDepthOfFieldSource = null;\n this._fixedExposure = 1.0;\n this._currentExposure = 1.0;\n this._hdrAutoExposure = false;\n this._hdrCurrentLuminance = 1.0;\n this._motionStrength = 1.0;\n this._isObjectBasedMotionBlur = false;\n this._camerasToBeAttached = [];\n // Getters and setters\n this._bloomEnabled = false;\n this._depthOfFieldEnabled = false;\n this._vlsEnabled = false;\n this._lensFlareEnabled = false;\n this._hdrEnabled = false;\n this._motionBlurEnabled = false;\n this._fxaaEnabled = false;\n this._screenSpaceReflectionsEnabled = false;\n this._motionBlurSamples = 64.0;\n this._volumetricLightStepsCount = 50.0;\n this._samples = 1;\n this._cameras = cameras || scene.cameras;\n this._cameras = this._cameras.slice();\n this._camerasToBeAttached = this._cameras.slice();\n // Initialize\n this._scene = scene;\n this._basePostProcess = originalPostProcess;\n this._ratio = ratio;\n // Misc\n this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? 1 : 2;\n // Finish\n scene.postProcessRenderPipelineManager.addPipeline(this);\n this._buildPipeline();\n }\n _buildPipeline() {\n const ratio = this._ratio;\n const scene = this._scene;\n this._disposePostProcesses();\n if (this._cameras !== null) {\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);\n // get back cameras to be used to reattach pipeline\n this._cameras = this._camerasToBeAttached.slice();\n }\n this._reset();\n // Create pass post-process\n if (this._screenSpaceReflectionsEnabled) {\n this.screenSpaceReflectionPostProcess = new ScreenSpaceReflectionPostProcess(\"HDRPass\", scene, ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, this._floatTextureType);\n this.screenSpaceReflectionPostProcess.onApplyObservable.add(() => {\n this._currentDepthOfFieldSource = this.screenSpaceReflectionPostProcess;\n });\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRScreenSpaceReflections\", () => this.screenSpaceReflectionPostProcess, true));\n }\n if (!this._basePostProcess) {\n this.originalPostProcess = new PostProcess(\"HDRPass\", \"standard\", [], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define PASS_POST_PROCESS\", this._floatTextureType);\n }\n else {\n this.originalPostProcess = this._basePostProcess;\n }\n this.originalPostProcess.autoClear = !this.screenSpaceReflectionPostProcess;\n this.originalPostProcess.onApplyObservable.add(() => {\n this._currentDepthOfFieldSource = this.originalPostProcess;\n });\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRPassPostProcess\", () => this.originalPostProcess, true));\n if (this._bloomEnabled) {\n // Create down sample X4 post-process\n this._createDownSampleX4PostProcess(scene, ratio / 4);\n // Create bright pass post-process\n this._createBrightPassPostProcess(scene, ratio / 4);\n // Create gaussian blur post-processes (down sampling blurs)\n this._createBlurPostProcesses(scene, ratio / 4, 1);\n // Create texture adder post-process\n this._createTextureAdderPostProcess(scene, ratio);\n // Create depth-of-field source post-process\n this.textureAdderFinalPostProcess = new PostProcess(\"HDRDepthOfFieldSource\", \"standard\", [], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define PASS_POST_PROCESS\", 0);\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRBaseDepthOfFieldSource\", () => {\n return this.textureAdderFinalPostProcess;\n }, true));\n }\n if (this._vlsEnabled) {\n // Create volumetric light\n this._createVolumetricLightPostProcess(scene, ratio);\n // Create volumetric light final post-process\n this.volumetricLightFinalPostProcess = new PostProcess(\"HDRVLSFinal\", \"standard\", [], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define PASS_POST_PROCESS\", 0);\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRVLSFinal\", () => {\n return this.volumetricLightFinalPostProcess;\n }, true));\n }\n if (this._lensFlareEnabled) {\n // Create lens flare post-process\n this._createLensFlarePostProcess(scene, ratio);\n // Create depth-of-field source post-process post lens-flare and disable it now\n this.lensFlareFinalPostProcess = new PostProcess(\"HDRPostLensFlareDepthOfFieldSource\", \"standard\", [], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define PASS_POST_PROCESS\", 0);\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRPostLensFlareDepthOfFieldSource\", () => {\n return this.lensFlareFinalPostProcess;\n }, true));\n }\n if (this._hdrEnabled) {\n // Create luminance\n this._createLuminancePostProcesses(scene, this._floatTextureType);\n // Create HDR\n this._createHdrPostProcess(scene, ratio);\n // Create depth-of-field source post-process post hdr and disable it now\n this.hdrFinalPostProcess = new PostProcess(\"HDRPostHDReDepthOfFieldSource\", \"standard\", [], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define PASS_POST_PROCESS\", 0);\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRPostHDReDepthOfFieldSource\", () => {\n return this.hdrFinalPostProcess;\n }, true));\n }\n if (this._depthOfFieldEnabled) {\n // Create gaussian blur used by depth-of-field\n this._createBlurPostProcesses(scene, ratio / 2, 3, \"depthOfFieldBlurWidth\");\n // Create depth-of-field post-process\n this._createDepthOfFieldPostProcess(scene, ratio);\n }\n if (this._motionBlurEnabled) {\n // Create motion blur post-process\n this._createMotionBlurPostProcess(scene, ratio);\n }\n if (this._fxaaEnabled) {\n // Create fxaa post-process\n this.fxaaPostProcess = new FxaaPostProcess(\"fxaa\", 1.0, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, 0);\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRFxaa\", () => {\n return this.fxaaPostProcess;\n }, true));\n }\n if (this._cameras !== null) {\n this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);\n }\n if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {\n Logger.Warn(\"MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0\");\n }\n }\n // Down Sample X4 Post-Process\n _createDownSampleX4PostProcess(scene, ratio) {\n const downSampleX4Offsets = new Array(32);\n this.downSampleX4PostProcess = new PostProcess(\"HDRDownSampleX4\", \"standard\", [\"dsOffsets\"], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define DOWN_SAMPLE_X4\", this._floatTextureType);\n this.downSampleX4PostProcess.onApply = (effect) => {\n let id = 0;\n const width = this.downSampleX4PostProcess.width;\n const height = this.downSampleX4PostProcess.height;\n for (let i = -2; i < 2; i++) {\n for (let j = -2; j < 2; j++) {\n downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);\n downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);\n id += 2;\n }\n }\n effect.setArray2(\"dsOffsets\", downSampleX4Offsets);\n };\n // Add to pipeline\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRDownSampleX4\", () => {\n return this.downSampleX4PostProcess;\n }, true));\n }\n // Brightpass Post-Process\n _createBrightPassPostProcess(scene, ratio) {\n const brightOffsets = new Array(8);\n this.brightPassPostProcess = new PostProcess(\"HDRBrightPass\", \"standard\", [\"dsOffsets\", \"brightThreshold\"], [], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define BRIGHT_PASS\", this._floatTextureType);\n this.brightPassPostProcess.onApply = (effect) => {\n const sU = 1.0 / this.brightPassPostProcess.width;\n const sV = 1.0 / this.brightPassPostProcess.height;\n brightOffsets[0] = -0.5 * sU;\n brightOffsets[1] = 0.5 * sV;\n brightOffsets[2] = 0.5 * sU;\n brightOffsets[3] = 0.5 * sV;\n brightOffsets[4] = -0.5 * sU;\n brightOffsets[5] = -0.5 * sV;\n brightOffsets[6] = 0.5 * sU;\n brightOffsets[7] = -0.5 * sV;\n effect.setArray2(\"dsOffsets\", brightOffsets);\n effect.setFloat(\"brightThreshold\", this.brightThreshold);\n };\n // Add to pipeline\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRBrightPass\", () => {\n return this.brightPassPostProcess;\n }, true));\n }\n // Create blur H&V post-processes\n _createBlurPostProcesses(scene, ratio, indice, blurWidthKey = \"blurWidth\") {\n const engine = scene.getEngine();\n const blurX = new BlurPostProcess(\"HDRBlurH\" + \"_\" + indice, new Vector2(1, 0), this[blurWidthKey], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, this._floatTextureType);\n const blurY = new BlurPostProcess(\"HDRBlurV\" + \"_\" + indice, new Vector2(0, 1), this[blurWidthKey], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, this._floatTextureType);\n blurX.onActivateObservable.add(() => {\n const dw = blurX.width / engine.getRenderWidth();\n blurX.kernel = this[blurWidthKey] * dw;\n });\n blurY.onActivateObservable.add(() => {\n const dw = blurY.height / engine.getRenderHeight();\n blurY.kernel = this.horizontalBlur ? 64 * dw : this[blurWidthKey] * dw;\n });\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRBlurH\" + indice, () => {\n return blurX;\n }, true));\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRBlurV\" + indice, () => {\n return blurY;\n }, true));\n this.blurHPostProcesses.push(blurX);\n this.blurVPostProcesses.push(blurY);\n }\n // Create texture adder post-process\n _createTextureAdderPostProcess(scene, ratio) {\n this.textureAdderPostProcess = new PostProcess(\"HDRTextureAdder\", \"standard\", [\"exposure\"], [\"otherSampler\", \"lensSampler\"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define TEXTURE_ADDER\", this._floatTextureType);\n this.textureAdderPostProcess.onApply = (effect) => {\n effect.setTextureFromPostProcess(\"otherSampler\", this._vlsEnabled ? this._currentDepthOfFieldSource : this.originalPostProcess);\n effect.setTexture(\"lensSampler\", this.lensTexture);\n effect.setFloat(\"exposure\", this._currentExposure);\n this._currentDepthOfFieldSource = this.textureAdderFinalPostProcess;\n };\n // Add to pipeline\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRTextureAdder\", () => {\n return this.textureAdderPostProcess;\n }, true));\n }\n _createVolumetricLightPostProcess(scene, ratio) {\n const geometryRenderer = scene.enableGeometryBufferRenderer();\n geometryRenderer.enablePosition = true;\n const geometry = geometryRenderer.getGBuffer();\n // Base post-process\n this.volumetricLightPostProcess = new PostProcess(\"HDRVLS\", \"standard\", [\"shadowViewProjection\", \"cameraPosition\", \"sunDirection\", \"sunColor\", \"scatteringCoefficient\", \"scatteringPower\", \"depthValues\"], [\"shadowMapSampler\", \"positionSampler\"], ratio / 8, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define VLS\\n#define NB_STEPS \" + this._volumetricLightStepsCount.toFixed(1));\n const depthValues = Vector2.Zero();\n this.volumetricLightPostProcess.onApply = (effect) => {\n if (this.sourceLight && this.sourceLight.getShadowGenerator() && this._scene.activeCamera) {\n const generator = this.sourceLight.getShadowGenerator();\n effect.setTexture(\"shadowMapSampler\", generator.getShadowMap());\n effect.setTexture(\"positionSampler\", geometry.textures[2]);\n effect.setColor3(\"sunColor\", this.sourceLight.diffuse);\n effect.setVector3(\"sunDirection\", this.sourceLight.getShadowDirection());\n effect.setVector3(\"cameraPosition\", this._scene.activeCamera.globalPosition);\n effect.setMatrix(\"shadowViewProjection\", generator.getTransformMatrix());\n effect.setFloat(\"scatteringCoefficient\", this.volumetricLightCoefficient);\n effect.setFloat(\"scatteringPower\", this.volumetricLightPower);\n depthValues.x = this.sourceLight.getDepthMinZ(this._scene.activeCamera);\n depthValues.y = this.sourceLight.getDepthMaxZ(this._scene.activeCamera);\n effect.setVector2(\"depthValues\", depthValues);\n }\n };\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRVLS\", () => {\n return this.volumetricLightPostProcess;\n }, true));\n // Smooth\n this._createBlurPostProcesses(scene, ratio / 4, 0, \"volumetricLightBlurScale\");\n // Merge\n this.volumetricLightMergePostProces = new PostProcess(\"HDRVLSMerge\", \"standard\", [], [\"originalSampler\"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define VLSMERGE\");\n this.volumetricLightMergePostProces.onApply = (effect) => {\n effect.setTextureFromPostProcess(\"originalSampler\", this._bloomEnabled ? this.textureAdderFinalPostProcess : this.originalPostProcess);\n this._currentDepthOfFieldSource = this.volumetricLightFinalPostProcess;\n };\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRVLSMerge\", () => {\n return this.volumetricLightMergePostProces;\n }, true));\n }\n // Create luminance\n _createLuminancePostProcesses(scene, textureType) {\n // Create luminance\n let size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);\n this.luminancePostProcess = new PostProcess(\"HDRLuminance\", \"standard\", [\"lumOffsets\"], [], { width: size, height: size }, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define LUMINANCE\", textureType);\n const offsets = [];\n this.luminancePostProcess.onApply = (effect) => {\n const sU = 1.0 / this.luminancePostProcess.width;\n const sV = 1.0 / this.luminancePostProcess.height;\n offsets[0] = -0.5 * sU;\n offsets[1] = 0.5 * sV;\n offsets[2] = 0.5 * sU;\n offsets[3] = 0.5 * sV;\n offsets[4] = -0.5 * sU;\n offsets[5] = -0.5 * sV;\n offsets[6] = 0.5 * sU;\n offsets[7] = -0.5 * sV;\n effect.setArray2(\"lumOffsets\", offsets);\n };\n // Add to pipeline\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRLuminance\", () => {\n return this.luminancePostProcess;\n }, true));\n // Create down sample luminance\n for (let i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {\n size = Math.pow(3, i);\n let defines = \"#define LUMINANCE_DOWN_SAMPLE\\n\";\n if (i === 0) {\n defines += \"#define FINAL_DOWN_SAMPLER\";\n }\n const postProcess = new PostProcess(\"HDRLuminanceDownSample\" + i, \"standard\", [\"dsOffsets\", \"halfDestPixelSize\"], [], { width: size, height: size }, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);\n this.luminanceDownSamplePostProcesses.push(postProcess);\n }\n // Create callbacks and add effects\n let lastLuminance = this.luminancePostProcess;\n this.luminanceDownSamplePostProcesses.forEach((pp, index) => {\n const downSampleOffsets = new Array(18);\n pp.onApply = (effect) => {\n if (!lastLuminance) {\n return;\n }\n let id = 0;\n for (let x = -1; x < 2; x++) {\n for (let y = -1; y < 2; y++) {\n downSampleOffsets[id] = x / lastLuminance.width;\n downSampleOffsets[id + 1] = y / lastLuminance.height;\n id += 2;\n }\n }\n effect.setArray2(\"dsOffsets\", downSampleOffsets);\n effect.setFloat(\"halfDestPixelSize\", 0.5 / lastLuminance.width);\n if (index === this.luminanceDownSamplePostProcesses.length - 1) {\n lastLuminance = this.luminancePostProcess;\n }\n else {\n lastLuminance = pp;\n }\n };\n if (index === this.luminanceDownSamplePostProcesses.length - 1) {\n pp.onAfterRender = () => {\n const pixel = scene.getEngine().readPixels(0, 0, 1, 1);\n const bit_shift = new Vector4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\n pixel.then((pixel) => {\n const data = new Uint8Array(pixel.buffer);\n this._hdrCurrentLuminance = (data[0] * bit_shift.x + data[1] * bit_shift.y + data[2] * bit_shift.z + data[3] * bit_shift.w) / 100.0;\n });\n };\n }\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRLuminanceDownSample\" + index, () => {\n return pp;\n }, true));\n });\n }\n // Create HDR post-process\n _createHdrPostProcess(scene, ratio) {\n const defines = [\"#define HDR\"];\n if (this._hdrAutoExposure) {\n defines.push(\"#define AUTO_EXPOSURE\");\n }\n this.hdrPostProcess = new PostProcess(\"HDR\", \"standard\", [\"averageLuminance\"], [\"textureAdderSampler\"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines.join(\"\\n\"), 0);\n let outputLiminance = 1;\n let time = 0;\n let lastTime = 0;\n this.hdrPostProcess.onApply = (effect) => {\n effect.setTextureFromPostProcess(\"textureAdderSampler\", this._currentDepthOfFieldSource);\n time += scene.getEngine().getDeltaTime();\n if (outputLiminance < 0) {\n outputLiminance = this._hdrCurrentLuminance;\n }\n else {\n const dt = (lastTime - time) / 1000.0;\n if (this._hdrCurrentLuminance < outputLiminance + this.hdrDecreaseRate * dt) {\n outputLiminance += this.hdrDecreaseRate * dt;\n }\n else if (this._hdrCurrentLuminance > outputLiminance - this.hdrIncreaseRate * dt) {\n outputLiminance -= this.hdrIncreaseRate * dt;\n }\n else {\n outputLiminance = this._hdrCurrentLuminance;\n }\n }\n if (this.hdrAutoExposure) {\n this._currentExposure = this._fixedExposure / outputLiminance;\n }\n else {\n outputLiminance = Scalar.Clamp(outputLiminance, this.hdrMinimumLuminance, 1e20);\n effect.setFloat(\"averageLuminance\", outputLiminance);\n }\n lastTime = time;\n this._currentDepthOfFieldSource = this.hdrFinalPostProcess;\n };\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDR\", () => {\n return this.hdrPostProcess;\n }, true));\n }\n // Create lens flare post-process\n _createLensFlarePostProcess(scene, ratio) {\n this.lensFlarePostProcess = new PostProcess(\"HDRLensFlare\", \"standard\", [\"strength\", \"ghostDispersal\", \"haloWidth\", \"resolution\", \"distortionStrength\"], [\"lensColorSampler\"], ratio / 2, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define LENS_FLARE\", 0);\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRLensFlare\", () => {\n return this.lensFlarePostProcess;\n }, true));\n this._createBlurPostProcesses(scene, ratio / 4, 2, \"lensFlareBlurWidth\");\n this.lensFlareComposePostProcess = new PostProcess(\"HDRLensFlareCompose\", \"standard\", [\"lensStarMatrix\"], [\"otherSampler\", \"lensDirtSampler\", \"lensStarSampler\"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define LENS_FLARE_COMPOSE\", 0);\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRLensFlareCompose\", () => {\n return this.lensFlareComposePostProcess;\n }, true));\n const resolution = new Vector2(0, 0);\n // Lens flare\n this.lensFlarePostProcess.externalTextureSamplerBinding = true;\n this.lensFlarePostProcess.onApply = (effect) => {\n effect.setTextureFromPostProcess(\"textureSampler\", this._bloomEnabled ? this.blurHPostProcesses[0] : this.originalPostProcess);\n effect.setTexture(\"lensColorSampler\", this.lensColorTexture);\n effect.setFloat(\"strength\", this.lensFlareStrength);\n effect.setFloat(\"ghostDispersal\", this.lensFlareGhostDispersal);\n effect.setFloat(\"haloWidth\", this.lensFlareHaloWidth);\n // Shift\n resolution.x = this.lensFlarePostProcess.width;\n resolution.y = this.lensFlarePostProcess.height;\n effect.setVector2(\"resolution\", resolution);\n effect.setFloat(\"distortionStrength\", this.lensFlareDistortionStrength);\n };\n // Compose\n const scaleBias1 = Matrix.FromValues(2.0, 0.0, -1.0, 0.0, 0.0, 2.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);\n const scaleBias2 = Matrix.FromValues(0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);\n this.lensFlareComposePostProcess.onApply = (effect) => {\n if (!this._scene.activeCamera) {\n return;\n }\n effect.setTextureFromPostProcess(\"otherSampler\", this.lensFlarePostProcess);\n effect.setTexture(\"lensDirtSampler\", this.lensFlareDirtTexture);\n effect.setTexture(\"lensStarSampler\", this.lensStarTexture);\n // Lens start rotation matrix\n const camerax = this._scene.activeCamera.getViewMatrix().getRow(0);\n const cameraz = this._scene.activeCamera.getViewMatrix().getRow(2);\n let camRot = Vector3.Dot(camerax.toVector3(), new Vector3(1.0, 0.0, 0.0)) + Vector3.Dot(cameraz.toVector3(), new Vector3(0.0, 0.0, 1.0));\n camRot *= 4.0;\n const starRotation = Matrix.FromValues(Math.cos(camRot) * 0.5, -Math.sin(camRot), 0.0, 0.0, Math.sin(camRot), Math.cos(camRot) * 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);\n const lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);\n effect.setMatrix(\"lensStarMatrix\", lensStarMatrix);\n this._currentDepthOfFieldSource = this.lensFlareFinalPostProcess;\n };\n }\n // Create depth-of-field post-process\n _createDepthOfFieldPostProcess(scene, ratio) {\n this.depthOfFieldPostProcess = new PostProcess(\"HDRDepthOfField\", \"standard\", [\"distance\"], [\"otherSampler\", \"depthSampler\"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define DEPTH_OF_FIELD\", 0);\n this.depthOfFieldPostProcess.onApply = (effect) => {\n effect.setTextureFromPostProcess(\"otherSampler\", this._currentDepthOfFieldSource);\n effect.setTexture(\"depthSampler\", this._getDepthTexture());\n effect.setFloat(\"distance\", this.depthOfFieldDistance);\n };\n // Add to pipeline\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRDepthOfField\", () => {\n return this.depthOfFieldPostProcess;\n }, true));\n }\n // Create motion blur post-process\n _createMotionBlurPostProcess(scene, ratio) {\n if (this._isObjectBasedMotionBlur) {\n const mb = new MotionBlurPostProcess(\"HDRMotionBlur\", scene, ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, 0);\n mb.motionStrength = this.motionStrength;\n mb.motionBlurSamples = this.motionBlurSamples;\n this.motionBlurPostProcess = mb;\n }\n else {\n this.motionBlurPostProcess = new PostProcess(\"HDRMotionBlur\", \"standard\", [\"inverseViewProjection\", \"prevViewProjection\", \"screenSize\", \"motionScale\", \"motionStrength\"], [\"depthSampler\"], ratio, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, \"#define MOTION_BLUR\\n#define MAX_MOTION_SAMPLES \" + this.motionBlurSamples.toFixed(1), 0);\n let motionScale = 0;\n let prevViewProjection = Matrix.Identity();\n const invViewProjection = Matrix.Identity();\n let viewProjection = Matrix.Identity();\n const screenSize = Vector2.Zero();\n this.motionBlurPostProcess.onApply = (effect) => {\n viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());\n viewProjection.invertToRef(invViewProjection);\n effect.setMatrix(\"inverseViewProjection\", invViewProjection);\n effect.setMatrix(\"prevViewProjection\", prevViewProjection);\n prevViewProjection = viewProjection;\n screenSize.x = this.motionBlurPostProcess.width;\n screenSize.y = this.motionBlurPostProcess.height;\n effect.setVector2(\"screenSize\", screenSize);\n motionScale = scene.getEngine().getFps() / 60.0;\n effect.setFloat(\"motionScale\", motionScale);\n effect.setFloat(\"motionStrength\", this.motionStrength);\n effect.setTexture(\"depthSampler\", this._getDepthTexture());\n };\n }\n this.addEffect(new PostProcessRenderEffect(scene.getEngine(), \"HDRMotionBlur\", () => {\n return this.motionBlurPostProcess;\n }, true));\n }\n _getDepthTexture() {\n if (this._scene.getEngine().getCaps().drawBuffersExtension) {\n const renderer = this._scene.enableGeometryBufferRenderer();\n return renderer.getGBuffer().textures[0];\n }\n return this._scene.enableDepthRenderer().getDepthMap();\n }\n _disposePostProcesses() {\n for (let i = 0; i < this._cameras.length; i++) {\n const camera = this._cameras[i];\n if (this.originalPostProcess) {\n this.originalPostProcess.dispose(camera);\n }\n if (this.screenSpaceReflectionPostProcess) {\n this.screenSpaceReflectionPostProcess.dispose(camera);\n }\n if (this.downSampleX4PostProcess) {\n this.downSampleX4PostProcess.dispose(camera);\n }\n if (this.brightPassPostProcess) {\n this.brightPassPostProcess.dispose(camera);\n }\n if (this.textureAdderPostProcess) {\n this.textureAdderPostProcess.dispose(camera);\n }\n if (this.volumetricLightPostProcess) {\n this.volumetricLightPostProcess.dispose(camera);\n }\n if (this.volumetricLightSmoothXPostProcess) {\n this.volumetricLightSmoothXPostProcess.dispose(camera);\n }\n if (this.volumetricLightSmoothYPostProcess) {\n this.volumetricLightSmoothYPostProcess.dispose(camera);\n }\n if (this.volumetricLightMergePostProces) {\n this.volumetricLightMergePostProces.dispose(camera);\n }\n if (this.volumetricLightFinalPostProcess) {\n this.volumetricLightFinalPostProcess.dispose(camera);\n }\n if (this.lensFlarePostProcess) {\n this.lensFlarePostProcess.dispose(camera);\n }\n if (this.lensFlareComposePostProcess) {\n this.lensFlareComposePostProcess.dispose(camera);\n }\n for (let j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {\n this.luminanceDownSamplePostProcesses[j].dispose(camera);\n }\n if (this.luminancePostProcess) {\n this.luminancePostProcess.dispose(camera);\n }\n if (this.hdrPostProcess) {\n this.hdrPostProcess.dispose(camera);\n }\n if (this.hdrFinalPostProcess) {\n this.hdrFinalPostProcess.dispose(camera);\n }\n if (this.depthOfFieldPostProcess) {\n this.depthOfFieldPostProcess.dispose(camera);\n }\n if (this.motionBlurPostProcess) {\n this.motionBlurPostProcess.dispose(camera);\n }\n if (this.fxaaPostProcess) {\n this.fxaaPostProcess.dispose(camera);\n }\n for (let j = 0; j < this.blurHPostProcesses.length; j++) {\n this.blurHPostProcesses[j].dispose(camera);\n }\n for (let j = 0; j < this.blurVPostProcesses.length; j++) {\n this.blurVPostProcesses[j].dispose(camera);\n }\n }\n this.originalPostProcess = null;\n this.downSampleX4PostProcess = null;\n this.brightPassPostProcess = null;\n this.textureAdderPostProcess = null;\n this.textureAdderFinalPostProcess = null;\n this.volumetricLightPostProcess = null;\n this.volumetricLightSmoothXPostProcess = null;\n this.volumetricLightSmoothYPostProcess = null;\n this.volumetricLightMergePostProces = null;\n this.volumetricLightFinalPostProcess = null;\n this.lensFlarePostProcess = null;\n this.lensFlareComposePostProcess = null;\n this.luminancePostProcess = null;\n this.hdrPostProcess = null;\n this.hdrFinalPostProcess = null;\n this.depthOfFieldPostProcess = null;\n this.motionBlurPostProcess = null;\n this.fxaaPostProcess = null;\n this.screenSpaceReflectionPostProcess = null;\n this.luminanceDownSamplePostProcesses.length = 0;\n this.blurHPostProcesses.length = 0;\n this.blurVPostProcesses.length = 0;\n }\n /**\n * Dispose of the pipeline and stop all post processes\n */\n dispose() {\n this._disposePostProcesses();\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);\n super.dispose();\n }\n /**\n * Serialize the rendering pipeline (Used when exporting)\n * @returns the serialized object\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this);\n if (this.sourceLight) {\n serializationObject.sourceLightId = this.sourceLight.id;\n }\n if (this.screenSpaceReflectionPostProcess) {\n serializationObject.screenSpaceReflectionPostProcess = SerializationHelper.Serialize(this.screenSpaceReflectionPostProcess);\n }\n serializationObject.customType = \"StandardRenderingPipeline\";\n return serializationObject;\n }\n /**\n * Parse the serialized pipeline\n * @param source Source pipeline.\n * @param scene The scene to load the pipeline to.\n * @param rootUrl The URL of the serialized pipeline.\n * @returns An instantiated pipeline from the serialized object.\n */\n static Parse(source, scene, rootUrl) {\n const p = SerializationHelper.Parse(() => new StandardRenderingPipeline(source._name, scene, source._ratio), source, scene, rootUrl);\n if (source.sourceLightId) {\n p.sourceLight = scene.getLightById(source.sourceLightId);\n }\n if (source.screenSpaceReflectionPostProcess) {\n SerializationHelper.Parse(() => p.screenSpaceReflectionPostProcess, source.screenSpaceReflectionPostProcess, scene, rootUrl);\n }\n return p;\n }\n}\n/**\n * Luminance steps\n */\nStandardRenderingPipeline.LuminanceSteps = 6;\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"brightThreshold\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"blurWidth\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"horizontalBlur\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"exposure\", null);\n__decorate([\n serializeAsTexture(\"lensTexture\")\n], StandardRenderingPipeline.prototype, \"lensTexture\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"volumetricLightCoefficient\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"volumetricLightPower\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"volumetricLightBlurScale\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"hdrMinimumLuminance\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"hdrDecreaseRate\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"hdrIncreaseRate\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"hdrAutoExposure\", null);\n__decorate([\n serializeAsTexture(\"lensColorTexture\")\n], StandardRenderingPipeline.prototype, \"lensColorTexture\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"lensFlareStrength\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"lensFlareGhostDispersal\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"lensFlareHaloWidth\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"lensFlareDistortionStrength\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"lensFlareBlurWidth\", void 0);\n__decorate([\n serializeAsTexture(\"lensStarTexture\")\n], StandardRenderingPipeline.prototype, \"lensStarTexture\", void 0);\n__decorate([\n serializeAsTexture(\"lensFlareDirtTexture\")\n], StandardRenderingPipeline.prototype, \"lensFlareDirtTexture\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"depthOfFieldDistance\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"depthOfFieldBlurWidth\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"motionStrength\", null);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"objectBasedMotionBlur\", null);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"_ratio\", void 0);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"BloomEnabled\", null);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"DepthOfFieldEnabled\", null);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"LensFlareEnabled\", null);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"HDREnabled\", null);\n__decorate([\n serialize()\n // eslint-disable-next-line @typescript-eslint/naming-convention\n], StandardRenderingPipeline.prototype, \"VLSEnabled\", null);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"MotionBlurEnabled\", null);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"fxaaEnabled\", null);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"screenSpaceReflectionsEnabled\", null);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"volumetricLightStepsCount\", null);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"motionBlurSamples\", null);\n__decorate([\n serialize()\n], StandardRenderingPipeline.prototype, \"samples\", null);\nRegisterClass(\"BABYLON.StandardRenderingPipeline\", StandardRenderingPipeline);\n//# sourceMappingURL=standardRenderingPipeline.js.map","\n/**\n * Contains all parameters needed for the prepass to perform\n * screen space reflections\n */\nexport class ScreenSpaceReflections2Configuration {\n constructor() {\n /**\n * Is ssr enabled\n */\n this.enabled = false;\n /**\n * Name of the configuration\n */\n this.name = \"screenSpaceReflections2\";\n /**\n * Textures that should be present in the MRT for this effect to work\n */\n this.texturesRequired = [6, 3, 5];\n }\n}\n//# sourceMappingURL=screenSpaceReflections2Configuration.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"screenSpaceRayTrace\";\nconst shader = `float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); }\r/**\r\\param csOrigin Camera-space ray origin,which must be \rwithin the view volume and must have z>0.01 and project within the valid screen rectangle\r\\param csDirection Unit length camera-space ray direction\r\\param projectToPixelMatrix A projection matrix that maps to **pixel** coordinates \r(**not** [-1,+1] normalized device coordinates).\r\\param csZBuffer The camera-space Z buffer\r\\param csZBufferSize Dimensions of csZBuffer\r\\param csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer\r\\param nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value\rfor clipping rays headed towards the camera\r\\param stride Step in horizontal or vertical pixels between samples. This is a float\rbecause integer math is slow on GPUs,but should be set to an integer>=1\r\\param jitterFraction Number between 0 and 1 for how far to bump the ray in stride units\rto conceal banding artifacts,plus the stride ray offset.\r\\param maxSteps Maximum number of iterations. Higher gives better images but may be slow\r\\param maxRayTraceDistance Maximum camera-space distance to trace before returning a miss\r\\param selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions.\r1 is a reasonable value,depending on the scene you may need to set this value to 2\r\\param hitPixel Pixel coordinates of the first intersection with the scene\r\\param numIterations number of iterations performed\r\\param csHitPoint Camera space location of the ray hit\r*/\r#define inline\nbool traceScreenSpaceRay1(\rvec3 csOrigin,\rvec3 csDirection,\rmat4 projectToPixelMatrix,\rsampler2D csZBuffer,\rvec2 csZBufferSize,\r#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nsampler2D csZBackBuffer,\rfloat csZBackSizeFactor,\r#endif\nfloat csZThickness,\rfloat nearPlaneZ,\rfloat stride,\rfloat jitterFraction,\rfloat maxSteps,\rfloat maxRayTraceDistance,\rfloat selfCollisionNumSkip,\rout vec2 startPixel,\rout vec2 hitPixel,\rout vec3 csHitPoint,\rout float numIterations\r#ifdef SSRAYTRACE_DEBUG\n,out vec3 debugColor\r#endif\n)\r{\r#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance;\r#else\nfloat rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)yMax) || (P1.yyMax) ? yMax : yMin))/(P1.y-P0.y);\r}\rif ((P1.x>xMax) || (P1.xxMax) ? xMax : xMin))/(P1.x-P0.x));\r}\rP1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha);\r#endif\nP1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);\rvec2 delta=P1-P0;\rbool permute=false;\rif (abs(delta.x)rayZMax) { \rfloat t=rayZMin; rayZMin=rayZMax; rayZMax=t;\r}\rsceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r;\r#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;\rhit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax);\r#else\nhit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax);\r#endif\n#else\n#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER\nfloat sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;\rhit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0);\r#else\nhit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax);\r#endif\n#endif\n}\rpqk-=dPQK;\rstepCount-=1.0;\rif (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {\rhit=false;\r}\r#ifdef SSRAYTRACE_ENABLE_REFINEMENT\nif (stride>1.0 && hit) {\rpqk-=dPQK;\rstepCount-=1.0;\rfloat invStride=1.0/stride;\rdPQK*=invStride;\rfloat refinementStepCount=0.0;\rprevZMaxEstimate=pqk.z/pqk.w;\rrayZMax=prevZMaxEstimate;\rsceneZMax=rayZMax+1e7;\rfor (;\rrefinementStepCount<=1.0 ||\r(refinementStepCount<=stride*1.4) &&\r(rayZMaxend) {\rdebugColor=vec3(0,0,1);\r} else if ((stepCount+1.0)>=maxSteps) {\rdebugColor=vec3(1,0,0);\r} else if (sceneZMax==0.0) {\rdebugColor=vec3(1,1,0);\r} else {\rdebugColor=vec3(0,stepCount/maxSteps,0);\r}\r#endif\nreturn hit;\r}\r/**\rtexCoord: in the [0,1] range\rdepth: depth in view space (range [znear,zfar]])\r*/\rvec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {\rvec4 ndc;\rndc.xy=texCoord*2.0-1.0;\r#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE\nndc.z=-projection[2].z-projection[3].z/depth;\r#else\nndc.z=projection[2].z+projection[3].z/depth;\r#endif\nndc.w=1.0;\rvec4 eyePos=invProjectionMatrix*ndc;\reyePos.xyz/=eyePos.w;\rreturn eyePos.xyz;\r}\r`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const screenSpaceRayTrace = { name, shader };\n//# sourceMappingURL=screenSpaceRayTrace.js.map","import { __decorate } from \"../../../tslib.es6.js\";\n/* eslint-disable @typescript-eslint/naming-convention */\nimport { serialize, SerializationHelper } from \"../../../Misc/decorators.js\";\nimport { Vector3, Matrix, Quaternion, TmpVectors } from \"../../../Maths/math.vector.js\";\nimport { PostProcess } from \"../../postProcess.js\";\nimport { PostProcessRenderPipeline } from \"../postProcessRenderPipeline.js\";\nimport { PostProcessRenderEffect } from \"../postProcessRenderEffect.js\";\nimport { RegisterClass } from \"../../../Misc/typeStore.js\";\nimport { ScreenSpaceReflections2Configuration } from \"../../../Rendering/screenSpaceReflections2Configuration.js\";\nimport { GeometryBufferRenderer } from \"../../../Rendering/geometryBufferRenderer.js\";\n\nimport { DepthRenderer } from \"../../../Rendering/depthRenderer.js\";\nimport \"../postProcessRenderPipelineManagerSceneComponent.js\";\nimport \"../../../Shaders/screenSpaceReflection2.fragment.js\";\nimport \"../../../Shaders/screenSpaceReflection2Blur.fragment.js\";\nimport \"../../../Shaders/screenSpaceReflection2BlurCombiner.fragment.js\";\nconst trs = Matrix.Compose(new Vector3(0.5, 0.5, 0.5), Quaternion.Identity(), new Vector3(0.5, 0.5, 0.5));\nconst trsWebGPU = Matrix.Compose(new Vector3(0.5, 0.5, 1), Quaternion.Identity(), new Vector3(0.5, 0.5, 0));\n/**\n * Render pipeline to produce Screen Space Reflections (SSR) effect\n *\n * References:\n * Screen Space Ray Tracing:\n * - http://casual-effects.blogspot.com/2014/08/screen-space-ray-tracing.html\n * - https://sourceforge.net/p/g3d/code/HEAD/tree/G3D10/data-files/shader/screenSpaceRayTrace.glsl\n * - https://github.com/kode80/kode80SSR\n * SSR:\n * - general tips: https://sakibsaikia.github.io/graphics/2016/12/26/Screen-Space-Reflection-in-Killing-Floor-2.html\n * - computation of blur radius from roughness and distance: https://github.com/godotengine/godot/blob/master/servers/rendering/renderer_rd/shaders/effects/screen_space_reflection.glsl\n * - blur and usage of back depth buffer: https://github.com/kode80/kode80SSR\n */\nexport class SSRRenderingPipeline extends PostProcessRenderPipeline {\n /**\n * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)\n */\n set samples(sampleCount) {\n if (this._samples === sampleCount) {\n return;\n }\n this._samples = sampleCount;\n this._buildPipeline();\n }\n get samples() {\n return this._samples;\n }\n /**\n * Gets or sets the minimum value for one of the reflectivity component of the material to consider it for SSR (default: 0.04).\n * If all r/g/b components of the reflectivity is below or equal this value, the pixel will not be considered reflective and SSR won't be applied.\n */\n get reflectivityThreshold() {\n return this._reflectivityThreshold;\n }\n set reflectivityThreshold(threshold) {\n if (threshold === this._reflectivityThreshold) {\n return;\n }\n if ((threshold === 0 && this._reflectivityThreshold !== 0) || (threshold !== 0 && this._reflectivityThreshold === 0)) {\n this._reflectivityThreshold = threshold;\n this._buildPipeline();\n }\n else {\n this._reflectivityThreshold = threshold;\n }\n }\n /**\n * Gets or sets the downsample factor used to reduce the size of the texture used to compute the SSR contribution (default: 0).\n * Use 0 to render the SSR contribution at full resolution, 1 to render at half resolution, 2 to render at 1/3 resolution, etc.\n * Note that it is used only when blurring is enabled (blurDispersionStrength \\> 0), because in that mode the SSR contribution is generated in a separate texture.\n */\n get ssrDownsample() {\n return this._ssrDownsample;\n }\n set ssrDownsample(downsample) {\n if (downsample === this._ssrDownsample) {\n return;\n }\n this._ssrDownsample = downsample;\n this._buildPipeline();\n }\n /**\n * Gets or sets the blur dispersion strength. Set this value to 0 to disable blurring (default: 0.05)\n * The reflections are blurred based on the roughness of the surface and the distance between the pixel shaded and the reflected pixel: the higher the distance the more blurry the reflection is.\n * blurDispersionStrength allows to increase or decrease this effect.\n */\n get blurDispersionStrength() {\n return this._blurDispersionStrength;\n }\n set blurDispersionStrength(strength) {\n if (strength === this._blurDispersionStrength) {\n return;\n }\n const rebuild = (strength === 0 && this._blurDispersionStrength !== 0) || (strength !== 0 && this._blurDispersionStrength === 0);\n this._blurDispersionStrength = strength;\n if (rebuild) {\n this._buildPipeline();\n }\n }\n _useBlur() {\n return this._blurDispersionStrength > 0;\n }\n /**\n * Gets or sets the downsample factor used to reduce the size of the textures used to blur the reflection effect (default: 0).\n * Use 0 to blur at full resolution, 1 to render at half resolution, 2 to render at 1/3 resolution, etc.\n */\n get blurDownsample() {\n return this._blurDownsample;\n }\n set blurDownsample(downsample) {\n if (downsample === this._blurDownsample) {\n return;\n }\n this._blurDownsample = downsample;\n this._buildPipeline();\n }\n /**\n * Gets or sets whether or not smoothing reflections is enabled (default: false)\n * Enabling smoothing will require more GPU power.\n * Note that this setting has no effect if step = 1: it's only used if step \\> 1.\n */\n get enableSmoothReflections() {\n return this._enableSmoothReflections;\n }\n set enableSmoothReflections(enabled) {\n if (enabled === this._enableSmoothReflections) {\n return;\n }\n this._enableSmoothReflections = enabled;\n this._updateEffectDefines();\n }\n /**\n * Gets or sets the environment cube texture used to define the reflection when the reflected rays of SSR leave the view space or when the maxDistance/maxSteps is reached.\n */\n get environmentTexture() {\n return this._environmentTexture;\n }\n set environmentTexture(texture) {\n this._environmentTexture = texture;\n this._updateEffectDefines();\n }\n /**\n * Gets or sets the boolean defining if the environment texture is a standard cubemap (false) or a probe (true). Default value is false.\n * Note: a probe cube texture is treated differently than an ordinary cube texture because the Y axis is reversed.\n */\n get environmentTextureIsProbe() {\n return this._environmentTextureIsProbe;\n }\n set environmentTextureIsProbe(isProbe) {\n this._environmentTextureIsProbe = isProbe;\n this._updateEffectDefines();\n }\n /**\n * Gets or sets a boolean indicating if the reflections should be attenuated at the screen borders (default: true).\n */\n get attenuateScreenBorders() {\n return this._attenuateScreenBorders;\n }\n set attenuateScreenBorders(attenuate) {\n if (this._attenuateScreenBorders === attenuate) {\n return;\n }\n this._attenuateScreenBorders = attenuate;\n this._updateEffectDefines();\n }\n /**\n * Gets or sets a boolean indicating if the reflections should be attenuated according to the distance of the intersection (default: true).\n */\n get attenuateIntersectionDistance() {\n return this._attenuateIntersectionDistance;\n }\n set attenuateIntersectionDistance(attenuate) {\n if (this._attenuateIntersectionDistance === attenuate) {\n return;\n }\n this._attenuateIntersectionDistance = attenuate;\n this._updateEffectDefines();\n }\n /**\n * Gets or sets a boolean indicating if the reflections should be attenuated according to the number of iterations performed to find the intersection (default: true).\n */\n get attenuateIntersectionIterations() {\n return this._attenuateIntersectionIterations;\n }\n set attenuateIntersectionIterations(attenuate) {\n if (this._attenuateIntersectionIterations === attenuate) {\n return;\n }\n this._attenuateIntersectionIterations = attenuate;\n this._updateEffectDefines();\n }\n /**\n * Gets or sets a boolean indicating if the reflections should be attenuated when the reflection ray is facing the camera (the view direction) (default: false).\n */\n get attenuateFacingCamera() {\n return this._attenuateFacingCamera;\n }\n set attenuateFacingCamera(attenuate) {\n if (this._attenuateFacingCamera === attenuate) {\n return;\n }\n this._attenuateFacingCamera = attenuate;\n this._updateEffectDefines();\n }\n /**\n * Gets or sets a boolean indicating if the backface reflections should be attenuated (default: false).\n */\n get attenuateBackfaceReflection() {\n return this._attenuateBackfaceReflection;\n }\n set attenuateBackfaceReflection(attenuate) {\n if (this._attenuateBackfaceReflection === attenuate) {\n return;\n }\n this._attenuateBackfaceReflection = attenuate;\n this._updateEffectDefines();\n }\n /**\n * Gets or sets a boolean indicating if the ray should be clipped to the frustum (default: true).\n * You can try to set this parameter to false to save some performances: it may produce some artefacts in some cases, but generally they won't really be visible\n */\n get clipToFrustum() {\n return this._clipToFrustum;\n }\n set clipToFrustum(clip) {\n if (this._clipToFrustum === clip) {\n return;\n }\n this._clipToFrustum = clip;\n this._updateEffectDefines();\n }\n /**\n * Gets or sets a boolean indicating whether the blending between the current color pixel and the reflection color should be done with a Fresnel coefficient (default: false).\n * It is more physically accurate to use the Fresnel coefficient (otherwise it uses the reflectivity of the material for blending), but it is also more expensive when you use blur (when blurDispersionStrength \\> 0).\n */\n get useFresnel() {\n return this._useFresnel;\n }\n set useFresnel(fresnel) {\n if (this._useFresnel === fresnel) {\n return;\n }\n this._useFresnel = fresnel;\n this._buildPipeline();\n }\n /**\n * Gets or sets a boolean defining if geometry thickness should be computed automatically (default: false).\n * When enabled, a depth renderer is created which will render the back faces of the scene to a depth texture (meaning additional work for the GPU).\n * In that mode, the \"thickness\" property is still used as an offset to compute the ray intersection, but you can typically use a much lower\n * value than when enableAutomaticThicknessComputation is false (it's even possible to use a value of 0 when using low values for \"step\")\n * Note that for performance reasons, this option will only apply to the first camera to which the the rendering pipeline is attached!\n */\n get enableAutomaticThicknessComputation() {\n return this._enableAutomaticThicknessComputation;\n }\n set enableAutomaticThicknessComputation(automatic) {\n if (this._enableAutomaticThicknessComputation === automatic) {\n return;\n }\n this._enableAutomaticThicknessComputation = automatic;\n this._buildPipeline();\n }\n /**\n * Gets the depth renderer used to render the back faces of the scene to a depth texture.\n */\n get backfaceDepthRenderer() {\n return this._depthRenderer;\n }\n /**\n * Gets or sets the downsample factor (default: 0) used to create the backface depth texture - used only if enableAutomaticThicknessComputation = true.\n * Use 0 to render the depth at full resolution, 1 to render at half resolution, 2 to render at 1/4 resolution, etc.\n * Note that you will get rendering artefacts when using a value different from 0: it's a tradeoff between image quality and performances.\n */\n get backfaceDepthTextureDownsample() {\n return this._backfaceDepthTextureDownsample;\n }\n set backfaceDepthTextureDownsample(factor) {\n if (this._backfaceDepthTextureDownsample === factor) {\n return;\n }\n this._backfaceDepthTextureDownsample = factor;\n this._resizeDepthRenderer();\n }\n /**\n * Gets or sets a boolean (default: true) indicating if the depth of transparent meshes should be written to the backface depth texture (when automatic thickness computation is enabled).\n */\n get backfaceForceDepthWriteTransparentMeshes() {\n return this._backfaceForceDepthWriteTransparentMeshes;\n }\n set backfaceForceDepthWriteTransparentMeshes(force) {\n if (this._backfaceForceDepthWriteTransparentMeshes === force) {\n return;\n }\n this._backfaceForceDepthWriteTransparentMeshes = force;\n if (this._depthRenderer) {\n this._depthRenderer.forceDepthWriteTransparentMeshes = force;\n }\n }\n /**\n * Gets or sets a boolean indicating if the effect is enabled (default: true).\n */\n get isEnabled() {\n return this._isEnabled;\n }\n set isEnabled(value) {\n if (this._isEnabled === value) {\n return;\n }\n this._isEnabled = value;\n if (!value) {\n if (this._cameras !== null) {\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);\n this._cameras = this._camerasToBeAttached.slice();\n }\n }\n else if (value) {\n if (!this._isDirty) {\n if (this._cameras !== null) {\n this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);\n }\n }\n else {\n this._buildPipeline();\n }\n }\n }\n /**\n * Gets or sets a boolean defining if the input color texture is in gamma space (default: true)\n * The SSR effect works in linear space, so if the input texture is in gamma space, we must convert the texture to linear space before applying the effect\n */\n get inputTextureColorIsInGammaSpace() {\n return this._inputTextureColorIsInGammaSpace;\n }\n set inputTextureColorIsInGammaSpace(gammaSpace) {\n if (this._inputTextureColorIsInGammaSpace === gammaSpace) {\n return;\n }\n this._inputTextureColorIsInGammaSpace = gammaSpace;\n this._buildPipeline();\n }\n /**\n * Gets or sets a boolean defining if the output color texture generated by the SSR pipeline should be in gamma space (default: true)\n * If you have a post-process that comes after the SSR and that post-process needs the input to be in a linear space, you must disable generateOutputInGammaSpace\n */\n get generateOutputInGammaSpace() {\n return this._generateOutputInGammaSpace;\n }\n set generateOutputInGammaSpace(gammaSpace) {\n if (this._generateOutputInGammaSpace === gammaSpace) {\n return;\n }\n this._generateOutputInGammaSpace = gammaSpace;\n this._buildPipeline();\n }\n /**\n * Gets or sets a boolean indicating if the effect should be rendered in debug mode (default: false).\n * In this mode, colors have this meaning:\n * - blue: the ray hit the max distance (we reached maxDistance)\n * - red: the ray ran out of steps (we reached maxSteps)\n * - yellow: the ray went off screen\n * - green: the ray hit a surface. The brightness of the green color is proportional to the distance between the ray origin and the intersection point: A brighter green means more computation than a darker green.\n * In the first 3 cases, the final color is calculated by mixing the skybox color with the pixel color (if environmentTexture is defined), otherwise the pixel color is not modified\n * You should try to get as few blue/red/yellow pixels as possible, as this means that the ray has gone further than if it had hit a surface.\n */\n get debug() {\n return this._debug;\n }\n set debug(value) {\n if (this._debug === value) {\n return;\n }\n this._debug = value;\n this._buildPipeline();\n }\n /**\n * Gets the scene the effect belongs to.\n * @returns the scene the effect belongs to.\n */\n getScene() {\n return this._scene;\n }\n get _geometryBufferRenderer() {\n if (!this._forceGeometryBuffer) {\n return null;\n }\n return this._scene.geometryBufferRenderer;\n }\n get _prePassRenderer() {\n if (this._forceGeometryBuffer) {\n return null;\n }\n return this._scene.prePassRenderer;\n }\n /**\n * Gets active scene\n */\n get scene() {\n return this._scene;\n }\n /**\n * Returns true if SSR is supported by the running hardware\n */\n get isSupported() {\n const caps = this._scene.getEngine().getCaps();\n return caps.drawBuffersExtension && caps.texelFetch;\n }\n /**\n * Constructor of the SSR rendering pipeline\n * @param name The rendering pipeline name\n * @param scene The scene linked to this pipeline\n * @param cameras The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)\n * @param forceGeometryBuffer Set to true if you want to use the legacy geometry buffer renderer (default: false)\n * @param textureType The texture type used by the different post processes created by SSR (default: 0)\n */\n constructor(name, scene, cameras, forceGeometryBuffer = false, textureType = 0) {\n super(scene.getEngine(), name);\n /**\n * The SSR PostProcess effect id in the pipeline\n */\n this.SSRRenderEffect = \"SSRRenderEffect\";\n /**\n * The blur PostProcess effect id in the pipeline\n */\n this.SSRBlurRenderEffect = \"SSRBlurRenderEffect\";\n /**\n * The PostProcess effect id in the pipeline that combines the SSR-Blur output with the original scene color\n */\n this.SSRCombineRenderEffect = \"SSRCombineRenderEffect\";\n this._samples = 1;\n /**\n * Gets or sets the maxDistance used to define how far we look for reflection during the ray-marching on the reflected ray (default: 1000).\n * Note that this value is a view (camera) space distance (not pixels!).\n */\n this.maxDistance = 1000.0;\n /**\n * Gets or sets the step size used to iterate until the effect finds the color of the reflection's pixel. Should be an integer \\>= 1 as it is the number of pixels we advance at each step (default: 1).\n * Use higher values to improve performances (but at the expense of quality).\n */\n this.step = 1.0;\n /**\n * Gets or sets the thickness value used as tolerance when computing the intersection between the reflected ray and the scene (default: 0.5).\n * If setting \"enableAutomaticThicknessComputation\" to true, you can use lower values for \"thickness\" (even 0), as the geometry thickness\n * is automatically computed thank to the regular depth buffer + the backface depth buffer\n */\n this.thickness = 0.5;\n /**\n * Gets or sets the current reflection strength. 1.0 is an ideal value but can be increased/decreased for particular results (default: 1).\n */\n this.strength = 1;\n /**\n * Gets or sets the falloff exponent used to compute the reflection strength. Higher values lead to fainter reflections (default: 1).\n */\n this.reflectionSpecularFalloffExponent = 1;\n /**\n * Maximum number of steps during the ray marching process after which we consider an intersection could not be found (default: 1000).\n * Should be an integer value.\n */\n this.maxSteps = 1000.0;\n /**\n * Gets or sets the factor applied when computing roughness. Default value is 0.2.\n * When blurring based on roughness is enabled (meaning blurDispersionStrength \\> 0), roughnessFactor is used as a global roughness factor applied on all objects.\n * If you want to disable this global roughness set it to 0.\n */\n this.roughnessFactor = 0.2;\n /**\n * Number of steps to skip at start when marching the ray to avoid self collisions (default: 1)\n * 1 should normally be a good value, depending on the scene you may need to use a higher value (2 or 3)\n */\n this.selfCollisionNumSkip = 1;\n this._reflectivityThreshold = 0.04;\n this._ssrDownsample = 0;\n this._blurDispersionStrength = 0.03;\n this._blurDownsample = 0;\n this._enableSmoothReflections = false;\n this._environmentTextureIsProbe = false;\n this._attenuateScreenBorders = true;\n this._attenuateIntersectionDistance = true;\n this._attenuateIntersectionIterations = true;\n this._attenuateFacingCamera = false;\n this._attenuateBackfaceReflection = false;\n this._clipToFrustum = true;\n this._useFresnel = false;\n this._enableAutomaticThicknessComputation = false;\n this._backfaceDepthTextureDownsample = 0;\n this._backfaceForceDepthWriteTransparentMeshes = true;\n this._isEnabled = true;\n this._inputTextureColorIsInGammaSpace = true;\n this._generateOutputInGammaSpace = true;\n this._debug = false;\n this._forceGeometryBuffer = false;\n this._isDirty = false;\n this._camerasToBeAttached = [];\n this._cameras = cameras || scene.cameras;\n this._cameras = this._cameras.slice();\n this._camerasToBeAttached = this._cameras.slice();\n this._scene = scene;\n this._textureType = textureType;\n this._forceGeometryBuffer = forceGeometryBuffer;\n if (this.isSupported) {\n scene.postProcessRenderPipelineManager.addPipeline(this);\n if (this._forceGeometryBuffer) {\n const geometryBufferRenderer = scene.enableGeometryBufferRenderer();\n if (geometryBufferRenderer) {\n geometryBufferRenderer.enableReflectivity = true;\n geometryBufferRenderer.useSpecificClearForDepthTexture = true;\n }\n }\n else {\n const prePassRenderer = scene.enablePrePassRenderer();\n if (prePassRenderer) {\n prePassRenderer.useSpecificClearForDepthTexture = true;\n prePassRenderer.markAsDirty();\n }\n }\n this._buildPipeline();\n }\n }\n /**\n * Get the class name\n * @returns \"SSRRenderingPipeline\"\n */\n getClassName() {\n return \"SSRRenderingPipeline\";\n }\n /**\n * Adds a camera to the pipeline\n * @param camera the camera to be added\n */\n addCamera(camera) {\n this._camerasToBeAttached.push(camera);\n this._buildPipeline();\n }\n /**\n * Removes a camera from the pipeline\n * @param camera the camera to remove\n */\n removeCamera(camera) {\n const index = this._camerasToBeAttached.indexOf(camera);\n this._camerasToBeAttached.splice(index, 1);\n this._buildPipeline();\n }\n /**\n * Removes the internal pipeline assets and detaches the pipeline from the scene cameras\n * @param disableGeometryBufferRenderer\n */\n dispose(disableGeometryBufferRenderer = false) {\n this._disposeDepthRenderer();\n this._disposePostProcesses();\n if (disableGeometryBufferRenderer) {\n this._scene.disableGeometryBufferRenderer();\n }\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);\n super.dispose();\n }\n _getTextureSize() {\n var _a, _b;\n const engine = this._scene.getEngine();\n const prePassRenderer = this._prePassRenderer;\n let textureSize = { width: engine.getRenderWidth(), height: engine.getRenderHeight() };\n if (prePassRenderer && ((_a = this._scene.activeCamera) === null || _a === void 0 ? void 0 : _a._getFirstPostProcess()) === this._ssrPostProcess) {\n const renderTarget = prePassRenderer.getRenderTarget();\n if (renderTarget && renderTarget.textures) {\n textureSize = renderTarget.textures[prePassRenderer.getIndex(4)].getSize();\n }\n }\n else if ((_b = this._ssrPostProcess) === null || _b === void 0 ? void 0 : _b.inputTexture) {\n textureSize.width = this._ssrPostProcess.inputTexture.width;\n textureSize.height = this._ssrPostProcess.inputTexture.height;\n }\n return textureSize;\n }\n _updateEffectDefines() {\n var _a;\n const defines = [];\n if (this._geometryBufferRenderer || this._prePassRenderer) {\n defines.push(\"#define SSR_SUPPORTED\");\n }\n if (this._enableSmoothReflections) {\n defines.push(\"#define SSRAYTRACE_ENABLE_REFINEMENT\");\n }\n if (this._scene.useRightHandedSystem) {\n defines.push(\"#define SSRAYTRACE_RIGHT_HANDED_SCENE\");\n }\n if (this._environmentTexture) {\n defines.push(\"#define SSR_USE_ENVIRONMENT_CUBE\");\n if (this._environmentTexture.boundingBoxSize) {\n defines.push(\"#define SSR_USE_LOCAL_REFLECTIONMAP_CUBIC\");\n }\n if (this._environmentTexture.gammaSpace) {\n defines.push(\"#define SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE\");\n }\n }\n if (this._environmentTextureIsProbe) {\n defines.push(\"#define SSR_INVERTCUBICMAP\");\n }\n if (this._enableAutomaticThicknessComputation) {\n defines.push(\"#define SSRAYTRACE_USE_BACK_DEPTHBUFFER\");\n }\n if (this._attenuateScreenBorders) {\n defines.push(\"#define SSR_ATTENUATE_SCREEN_BORDERS\");\n }\n if (this._attenuateIntersectionDistance) {\n defines.push(\"#define SSR_ATTENUATE_INTERSECTION_DISTANCE\");\n }\n if (this._attenuateIntersectionIterations) {\n defines.push(\"#define SSR_ATTENUATE_INTERSECTION_NUMITERATIONS\");\n }\n if (this._attenuateFacingCamera) {\n defines.push(\"#define SSR_ATTENUATE_FACING_CAMERA\");\n }\n if (this._attenuateBackfaceReflection) {\n defines.push(\"#define SSR_ATTENUATE_BACKFACE_REFLECTION\");\n }\n if (this._clipToFrustum) {\n defines.push(\"#define SSRAYTRACE_CLIP_TO_FRUSTUM\");\n }\n if (this._useBlur()) {\n defines.push(\"#define SSR_USE_BLUR\");\n }\n if (this._debug) {\n defines.push(\"#define SSRAYTRACE_DEBUG\");\n }\n if (this._inputTextureColorIsInGammaSpace) {\n defines.push(\"#define SSR_INPUT_IS_GAMMA_SPACE\");\n }\n if (this._generateOutputInGammaSpace) {\n defines.push(\"#define SSR_OUTPUT_IS_GAMMA_SPACE\");\n }\n if (this._useFresnel) {\n defines.push(\"#define SSR_BLEND_WITH_FRESNEL\");\n }\n if (this._reflectivityThreshold === 0) {\n defines.push(\"#define SSR_DISABLE_REFLECTIVITY_TEST\");\n }\n (_a = this._ssrPostProcess) === null || _a === void 0 ? void 0 : _a.updateEffect(defines.join(\"\\n\"));\n }\n _buildPipeline() {\n var _a;\n if (!this.isSupported) {\n return;\n }\n if (!this._isEnabled) {\n this._isDirty = true;\n return;\n }\n this._isDirty = false;\n const engine = this._scene.getEngine();\n this._disposeDepthRenderer();\n this._disposePostProcesses();\n if (this._cameras !== null) {\n this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);\n // get back cameras to be used to reattach pipeline\n this._cameras = this._camerasToBeAttached.slice();\n }\n this._reset();\n if (this._enableAutomaticThicknessComputation) {\n const camera = (_a = this._cameras) === null || _a === void 0 ? void 0 : _a[0];\n if (camera) {\n this._depthRendererCamera = camera;\n this._depthRenderer = new DepthRenderer(this._scene, undefined, undefined, undefined, 1, true, \"SSRBackDepth\");\n this._depthRenderer.clearColor.r = 1e8; // \"infinity\": put a big value because we use the storeCameraSpaceZ mode\n this._depthRenderer.reverseCulling = true; // we generate depth for the back faces\n this._depthRenderer.forceDepthWriteTransparentMeshes = this._backfaceForceDepthWriteTransparentMeshes;\n this._resizeDepthRenderer();\n camera.customRenderTargets.push(this._depthRenderer.getDepthMap());\n }\n }\n this._createSSRPostProcess();\n this.addEffect(new PostProcessRenderEffect(engine, this.SSRRenderEffect, () => {\n return this._ssrPostProcess;\n }, true));\n if (this._useBlur()) {\n this._createBlurAndCombinerPostProcesses();\n this.addEffect(new PostProcessRenderEffect(engine, this.SSRBlurRenderEffect, () => {\n return [this._blurPostProcessX, this._blurPostProcessY];\n }, true));\n this.addEffect(new PostProcessRenderEffect(engine, this.SSRCombineRenderEffect, () => {\n return this._blurCombinerPostProcess;\n }, true));\n }\n if (this._cameras !== null) {\n this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);\n }\n }\n _resizeDepthRenderer() {\n if (!this._depthRenderer) {\n return;\n }\n const textureSize = this._getTextureSize();\n const depthRendererSize = this._depthRenderer.getDepthMap().getSize();\n const width = Math.floor(textureSize.width / (this._backfaceDepthTextureDownsample + 1));\n const height = Math.floor(textureSize.height / (this._backfaceDepthTextureDownsample + 1));\n if (depthRendererSize.width !== width || depthRendererSize.height !== height) {\n this._depthRenderer.getDepthMap().resize({ width, height });\n }\n }\n _disposeDepthRenderer() {\n var _a;\n if (this._depthRenderer) {\n if (this._depthRendererCamera) {\n const idx = (_a = this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap())) !== null && _a !== void 0 ? _a : -1;\n if (idx !== -1) {\n this._depthRendererCamera.customRenderTargets.splice(idx, 1);\n }\n }\n this._depthRendererCamera = null;\n this._depthRenderer.getDepthMap().dispose();\n }\n this._depthRenderer = null;\n }\n _disposePostProcesses() {\n var _a, _b, _c, _d;\n for (let i = 0; i < this._cameras.length; i++) {\n const camera = this._cameras[i];\n (_a = this._ssrPostProcess) === null || _a === void 0 ? void 0 : _a.dispose(camera);\n (_b = this._blurPostProcessX) === null || _b === void 0 ? void 0 : _b.dispose(camera);\n (_c = this._blurPostProcessY) === null || _c === void 0 ? void 0 : _c.dispose(camera);\n (_d = this._blurCombinerPostProcess) === null || _d === void 0 ? void 0 : _d.dispose(camera);\n }\n this._ssrPostProcess = null;\n this._blurPostProcessX = null;\n this._blurPostProcessY = null;\n this._blurCombinerPostProcess = null;\n }\n _createSSRPostProcess() {\n this._ssrPostProcess = new PostProcess(\"ssr\", \"screenSpaceReflection2\", [\n \"projection\",\n \"invProjectionMatrix\",\n \"view\",\n \"invView\",\n \"thickness\",\n \"reflectionSpecularFalloffExponent\",\n \"strength\",\n \"stepSize\",\n \"maxSteps\",\n \"roughnessFactor\",\n \"projectionPixel\",\n \"nearPlaneZ\",\n \"maxDistance\",\n \"selfCollisionNumSkip\",\n \"vReflectionPosition\",\n \"vReflectionSize\",\n \"backSizeFactor\",\n \"reflectivityThreshold\",\n ], [\"textureSampler\", \"normalSampler\", \"reflectivitySampler\", \"depthSampler\", \"envCubeSampler\", \"backDepthSampler\"], 1.0, null, this._textureType, this._scene.getEngine(), false, \"\", this._textureType);\n this._updateEffectDefines();\n this._ssrPostProcess.onApply = (effect) => {\n this._resizeDepthRenderer();\n const geometryBufferRenderer = this._geometryBufferRenderer;\n const prePassRenderer = this._prePassRenderer;\n if (!prePassRenderer && !geometryBufferRenderer) {\n return;\n }\n if (geometryBufferRenderer) {\n const roughnessIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE);\n effect.setTexture(\"normalSampler\", geometryBufferRenderer.getGBuffer().textures[1]);\n effect.setTexture(\"reflectivitySampler\", geometryBufferRenderer.getGBuffer().textures[roughnessIndex]);\n effect.setTexture(\"depthSampler\", geometryBufferRenderer.getGBuffer().textures[0]);\n }\n else if (prePassRenderer) {\n const depthIndex = prePassRenderer.getIndex(5);\n const roughnessIndex = prePassRenderer.getIndex(3);\n const normalIndex = prePassRenderer.getIndex(6);\n effect.setTexture(\"normalSampler\", prePassRenderer.getRenderTarget().textures[normalIndex]);\n effect.setTexture(\"depthSampler\", prePassRenderer.getRenderTarget().textures[depthIndex]);\n effect.setTexture(\"reflectivitySampler\", prePassRenderer.getRenderTarget().textures[roughnessIndex]);\n }\n if (this._enableAutomaticThicknessComputation && this._depthRenderer) {\n effect.setTexture(\"backDepthSampler\", this._depthRenderer.getDepthMap());\n effect.setFloat(\"backSizeFactor\", this._backfaceDepthTextureDownsample + 1);\n }\n const camera = this._scene.activeCamera;\n if (!camera) {\n return;\n }\n const viewMatrix = camera.getViewMatrix(true);\n const projectionMatrix = camera.getProjectionMatrix(true);\n projectionMatrix.invertToRef(TmpVectors.Matrix[0]);\n viewMatrix.invertToRef(TmpVectors.Matrix[1]);\n effect.setMatrix(\"projection\", projectionMatrix);\n effect.setMatrix(\"view\", viewMatrix);\n effect.setMatrix(\"invView\", TmpVectors.Matrix[1]);\n effect.setMatrix(\"invProjectionMatrix\", TmpVectors.Matrix[0]);\n effect.setFloat(\"thickness\", this.thickness);\n effect.setFloat(\"reflectionSpecularFalloffExponent\", this.reflectionSpecularFalloffExponent);\n effect.setFloat(\"strength\", this.strength);\n effect.setFloat(\"stepSize\", this.step);\n effect.setFloat(\"maxSteps\", this.maxSteps);\n effect.setFloat(\"roughnessFactor\", this.roughnessFactor);\n effect.setFloat(\"nearPlaneZ\", camera.minZ);\n effect.setFloat(\"maxDistance\", this.maxDistance);\n effect.setFloat(\"selfCollisionNumSkip\", this.selfCollisionNumSkip);\n effect.setFloat(\"reflectivityThreshold\", this._reflectivityThreshold);\n const textureSize = this._getTextureSize();\n Matrix.ScalingToRef(textureSize.width, textureSize.height, 1, TmpVectors.Matrix[2]);\n projectionMatrix.multiplyToRef(this._scene.getEngine().isWebGPU ? trsWebGPU : trs, TmpVectors.Matrix[3]);\n TmpVectors.Matrix[3].multiplyToRef(TmpVectors.Matrix[2], TmpVectors.Matrix[4]);\n effect.setMatrix(\"projectionPixel\", TmpVectors.Matrix[4]);\n if (this._environmentTexture) {\n effect.setTexture(\"envCubeSampler\", this._environmentTexture);\n if (this._environmentTexture.boundingBoxSize) {\n effect.setVector3(\"vReflectionPosition\", this._environmentTexture.boundingBoxPosition);\n effect.setVector3(\"vReflectionSize\", this._environmentTexture.boundingBoxSize);\n }\n }\n };\n this._ssrPostProcess.samples = this.samples;\n if (!this._forceGeometryBuffer) {\n this._ssrPostProcess._prePassEffectConfiguration = new ScreenSpaceReflections2Configuration();\n }\n }\n _createBlurAndCombinerPostProcesses() {\n const engine = this._scene.getEngine();\n this._blurPostProcessX = new PostProcess(\"SSRblurX\", \"screenSpaceReflection2Blur\", [\"texelOffsetScale\"], [\"textureSampler\"], this._useBlur() ? 1 / (this._ssrDownsample + 1) : 1, null, 2, engine, false, \"\", this._textureType);\n this._blurPostProcessX.autoClear = false;\n this._blurPostProcessX.onApplyObservable.add((effect) => {\n var _a, _b;\n const width = (_b = (_a = this._blurPostProcessX) === null || _a === void 0 ? void 0 : _a.inputTexture.width) !== null && _b !== void 0 ? _b : this._scene.getEngine().getRenderWidth();\n effect.setFloat2(\"texelOffsetScale\", this._blurDispersionStrength / width, 0);\n });\n this._blurPostProcessY = new PostProcess(\"SSRblurY\", \"screenSpaceReflection2Blur\", [\"texelOffsetScale\"], [\"textureSampler\"], this._useBlur() ? 1 / (this._blurDownsample + 1) : 1, null, 2, engine, false, \"\", this._textureType);\n this._blurPostProcessY.autoClear = false;\n this._blurPostProcessY.onApplyObservable.add((effect) => {\n var _a, _b;\n const height = (_b = (_a = this._blurPostProcessY) === null || _a === void 0 ? void 0 : _a.inputTexture.height) !== null && _b !== void 0 ? _b : this._scene.getEngine().getRenderHeight();\n effect.setFloat2(\"texelOffsetScale\", 0, this._blurDispersionStrength / height);\n });\n const uniformNames = [\"strength\", \"reflectionSpecularFalloffExponent\", \"reflectivityThreshold\"];\n const samplerNames = [\"textureSampler\", \"mainSampler\", \"reflectivitySampler\"];\n let defines = \"\";\n if (this._debug) {\n defines += \"#define SSRAYTRACE_DEBUG\\n\";\n }\n if (this._inputTextureColorIsInGammaSpace) {\n defines += \"#define SSR_INPUT_IS_GAMMA_SPACE\\n\";\n }\n if (this._generateOutputInGammaSpace) {\n defines += \"#define SSR_OUTPUT_IS_GAMMA_SPACE\\n\";\n }\n if (this.useFresnel) {\n defines += \"#define SSR_BLEND_WITH_FRESNEL\\n\";\n uniformNames.push(\"projection\", \"invProjectionMatrix\");\n samplerNames.push(\"depthSampler\", \"normalSampler\");\n }\n if (this._reflectivityThreshold === 0) {\n defines += \"#define SSR_DISABLE_REFLECTIVITY_TEST\";\n }\n this._blurCombinerPostProcess = new PostProcess(\"SSRblurCombiner\", \"screenSpaceReflection2BlurCombiner\", uniformNames, samplerNames, this._useBlur() ? 1 / (this._blurDownsample + 1) : 1, null, 1, engine, false, defines, this._textureType);\n this._blurCombinerPostProcess.autoClear = false;\n this._blurCombinerPostProcess.onApplyObservable.add((effect) => {\n var _a;\n const geometryBufferRenderer = this._geometryBufferRenderer;\n const prePassRenderer = this._prePassRenderer;\n if (!prePassRenderer && !geometryBufferRenderer) {\n return;\n }\n if (prePassRenderer && ((_a = this._scene.activeCamera) === null || _a === void 0 ? void 0 : _a._getFirstPostProcess()) === this._ssrPostProcess) {\n const renderTarget = prePassRenderer.getRenderTarget();\n if (renderTarget && renderTarget.textures) {\n effect.setTexture(\"mainSampler\", renderTarget.textures[prePassRenderer.getIndex(4)]);\n }\n }\n else {\n effect.setTextureFromPostProcess(\"mainSampler\", this._ssrPostProcess);\n }\n if (geometryBufferRenderer) {\n const roughnessIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE);\n effect.setTexture(\"reflectivitySampler\", geometryBufferRenderer.getGBuffer().textures[roughnessIndex]);\n if (this.useFresnel) {\n effect.setTexture(\"normalSampler\", geometryBufferRenderer.getGBuffer().textures[1]);\n effect.setTexture(\"depthSampler\", geometryBufferRenderer.getGBuffer().textures[0]);\n }\n }\n else if (prePassRenderer) {\n const roughnessIndex = prePassRenderer.getIndex(3);\n effect.setTexture(\"reflectivitySampler\", prePassRenderer.getRenderTarget().textures[roughnessIndex]);\n if (this.useFresnel) {\n const depthIndex = prePassRenderer.getIndex(5);\n const normalIndex = prePassRenderer.getIndex(6);\n effect.setTexture(\"normalSampler\", prePassRenderer.getRenderTarget().textures[normalIndex]);\n effect.setTexture(\"depthSampler\", prePassRenderer.getRenderTarget().textures[depthIndex]);\n }\n }\n effect.setFloat(\"strength\", this.strength);\n effect.setFloat(\"reflectionSpecularFalloffExponent\", this.reflectionSpecularFalloffExponent);\n effect.setFloat(\"reflectivityThreshold\", this._reflectivityThreshold);\n if (this.useFresnel) {\n const camera = this._scene.activeCamera;\n if (camera) {\n const projectionMatrix = camera.getProjectionMatrix();\n projectionMatrix.invertToRef(TmpVectors.Matrix[0]);\n effect.setMatrix(\"projection\", projectionMatrix);\n effect.setMatrix(\"invProjectionMatrix\", TmpVectors.Matrix[0]);\n }\n }\n });\n }\n /**\n * Serializes the rendering pipeline (Used when exporting)\n * @returns the serialized object\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this);\n serializationObject.customType = \"SSRRenderingPipeline\";\n return serializationObject;\n }\n /**\n * Parse the serialized pipeline\n * @param source Source pipeline.\n * @param scene The scene to load the pipeline to.\n * @param rootUrl The URL of the serialized pipeline.\n * @returns An instantiated pipeline from the serialized object.\n */\n static Parse(source, scene, rootUrl) {\n return SerializationHelper.Parse(() => new SSRRenderingPipeline(source._name, scene, source._ratio), source, scene, rootUrl);\n }\n}\n__decorate([\n serialize()\n], SSRRenderingPipeline.prototype, \"samples\", null);\n__decorate([\n serialize()\n], SSRRenderingPipeline.prototype, \"maxDistance\", void 0);\n__decorate([\n serialize()\n], SSRRenderingPipeline.prototype, \"step\", void 0);\n__decorate([\n serialize()\n], SSRRenderingPipeline.prototype, \"thickness\", void 0);\n__decorate([\n serialize()\n], SSRRenderingPipeline.prototype, \"strength\", void 0);\n__decorate([\n serialize()\n], SSRRenderingPipeline.prototype, \"reflectionSpecularFalloffExponent\", void 0);\n__decorate([\n serialize()\n], SSRRenderingPipeline.prototype, \"maxSteps\", void 0);\n__decorate([\n serialize()\n], SSRRenderingPipeline.prototype, \"roughnessFactor\", void 0);\n__decorate([\n serialize()\n], SSRRenderingPipeline.prototype, \"selfCollisionNumSkip\", void 0);\n__decorate([\n serialize()\n], SSRRenderingPipeline.prototype, \"_reflectivityThreshold\", void 0);\n__decorate([\n serialize(\"_ssrDownsample\")\n], SSRRenderingPipeline.prototype, \"_ssrDownsample\", void 0);\n__decorate([\n serialize()\n], SSRRenderingPipeline.prototype, \"ssrDownsample\", null);\n__decorate([\n serialize(\"blurDispersionStrength\")\n], SSRRenderingPipeline.prototype, \"_blurDispersionStrength\", void 0);\n__decorate([\n serialize(\"blurDownsample\")\n], SSRRenderingPipeline.prototype, \"_blurDownsample\", void 0);\n__decorate([\n serialize(\"enableSmoothReflections\")\n], SSRRenderingPipeline.prototype, \"_enableSmoothReflections\", void 0);\n__decorate([\n serialize(\"environmentTexture\")\n], SSRRenderingPipeline.prototype, \"_environmentTexture\", void 0);\n__decorate([\n serialize(\"environmentTextureIsProbe\")\n], SSRRenderingPipeline.prototype, \"_environmentTextureIsProbe\", void 0);\n__decorate([\n serialize(\"attenuateScreenBorders\")\n], SSRRenderingPipeline.prototype, \"_attenuateScreenBorders\", void 0);\n__decorate([\n serialize(\"attenuateIntersectionDistance\")\n], SSRRenderingPipeline.prototype, \"_attenuateIntersectionDistance\", void 0);\n__decorate([\n serialize(\"attenuateIntersectionIterations\")\n], SSRRenderingPipeline.prototype, \"_attenuateIntersectionIterations\", void 0);\n__decorate([\n serialize(\"attenuateFacingCamera\")\n], SSRRenderingPipeline.prototype, \"_attenuateFacingCamera\", void 0);\n__decorate([\n serialize(\"attenuateBackfaceReflection\")\n], SSRRenderingPipeline.prototype, \"_attenuateBackfaceReflection\", void 0);\n__decorate([\n serialize(\"clipToFrustum\")\n], SSRRenderingPipeline.prototype, \"_clipToFrustum\", void 0);\n__decorate([\n serialize(\"useFresnel\")\n], SSRRenderingPipeline.prototype, \"_useFresnel\", void 0);\n__decorate([\n serialize(\"enableAutomaticThicknessComputation\")\n], SSRRenderingPipeline.prototype, \"_enableAutomaticThicknessComputation\", void 0);\n__decorate([\n serialize(\"backfaceDepthTextureDownsample\")\n], SSRRenderingPipeline.prototype, \"_backfaceDepthTextureDownsample\", void 0);\n__decorate([\n serialize(\"backfaceForceDepthWriteTransparentMeshes\")\n], SSRRenderingPipeline.prototype, \"_backfaceForceDepthWriteTransparentMeshes\", void 0);\n__decorate([\n serialize(\"isEnabled\")\n], SSRRenderingPipeline.prototype, \"_isEnabled\", void 0);\n__decorate([\n serialize(\"inputTextureColorIsInGammaSpace\")\n], SSRRenderingPipeline.prototype, \"_inputTextureColorIsInGammaSpace\", void 0);\n__decorate([\n serialize(\"generateOutputInGammaSpace\")\n], SSRRenderingPipeline.prototype, \"_generateOutputInGammaSpace\", void 0);\n__decorate([\n serialize(\"debug\")\n], SSRRenderingPipeline.prototype, \"_debug\", void 0);\nRegisterClass(\"BABYLON.SSRRenderingPipeline\", SSRRenderingPipeline);\n//# sourceMappingURL=ssrRenderingPipeline.js.map","export * from \"./defaultRenderingPipeline.js\";\nexport * from \"./lensRenderingPipeline.js\";\nexport * from \"./ssao2RenderingPipeline.js\";\nexport * from \"./ssaoRenderingPipeline.js\";\nexport * from \"./standardRenderingPipeline.js\";\nexport * from \"./ssrRenderingPipeline.js\";\n//# sourceMappingURL=index.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./Pipelines/index.js\";\nexport * from \"./postProcessRenderEffect.js\";\nexport * from \"./postProcessRenderPipeline.js\";\nexport * from \"./postProcessRenderPipelineManager.js\";\nexport * from \"./postProcessRenderPipelineManagerSceneComponent.js\";\n//# sourceMappingURL=index.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"tonemapPixelShader\";\nconst shader = `varying vec2 vUV;\runiform sampler2D textureSampler;\runiform float _ExposureAdjustment;\r#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\rconst float B=0.50;\rconst float C=0.10;\rconst float D=0.20;\rconst float E=0.02;\rconst float F=0.30;\rconst float W=11.2;\r#endif\nfloat Luminance(vec3 c)\r{\rreturn dot(c,vec3(0.22,0.707,0.071));\r}\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \r{\rvec3 colour=texture2D(textureSampler,vUV).rgb;\r#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \rfloat lumTm=lum*_ExposureAdjustment;\rfloat scale=lumTm/(1.0+lumTm); \rcolour*=scale/lum;\r#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\rconst float ExposureBias=2.0;\rvec3 x=ExposureBias*colour;\rvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\rx=vec3(W,W,W);\rvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\rcolour=curr*whiteScale;\r#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\rvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\rvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\rcolour=retColor*retColor;\r#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\r#endif\ngl_FragColor=vec4(colour.rgb,1.0);\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const tonemapPixelShader = { name, shader };\n//# sourceMappingURL=tonemap.fragment.js.map","import { PostProcess } from \"./postProcess.js\";\n\nimport \"../Shaders/tonemap.fragment.js\";\n/** Defines operator used for tonemapping */\nexport var TonemappingOperator;\n(function (TonemappingOperator) {\n /** Hable */\n TonemappingOperator[TonemappingOperator[\"Hable\"] = 0] = \"Hable\";\n /** Reinhard */\n TonemappingOperator[TonemappingOperator[\"Reinhard\"] = 1] = \"Reinhard\";\n /** HejiDawson */\n TonemappingOperator[TonemappingOperator[\"HejiDawson\"] = 2] = \"HejiDawson\";\n /** Photographic */\n TonemappingOperator[TonemappingOperator[\"Photographic\"] = 3] = \"Photographic\";\n})(TonemappingOperator || (TonemappingOperator = {}));\n/**\n * Defines a post process to apply tone mapping\n */\nexport class TonemapPostProcess extends PostProcess {\n /**\n * Gets a string identifying the name of the class\n * @returns \"TonemapPostProcess\" string\n */\n getClassName() {\n return \"TonemapPostProcess\";\n }\n /**\n * Creates a new TonemapPostProcess\n * @param name defines the name of the postprocess\n * @param _operator defines the operator to use\n * @param exposureAdjustment defines the required exposure adjustment\n * @param camera defines the camera to use (can be null)\n * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)\n * @param engine defines the hosting engine (can be ignore if camera is set)\n * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n */\n constructor(name, _operator, \n /** Defines the required exposure adjustment */\n exposureAdjustment, camera, samplingMode = 2, engine, textureFormat = 0, reusable) {\n super(name, \"tonemap\", [\"_ExposureAdjustment\"], null, 1.0, camera, samplingMode, engine, reusable, null, textureFormat);\n this._operator = _operator;\n this.exposureAdjustment = exposureAdjustment;\n let defines = \"#define \";\n if (this._operator === TonemappingOperator.Hable) {\n defines += \"HABLE_TONEMAPPING\";\n }\n else if (this._operator === TonemappingOperator.Reinhard) {\n defines += \"REINHARD_TONEMAPPING\";\n }\n else if (this._operator === TonemappingOperator.HejiDawson) {\n defines += \"OPTIMIZED_HEJIDAWSON_TONEMAPPING\";\n }\n else if (this._operator === TonemappingOperator.Photographic) {\n defines += \"PHOTOGRAPHIC_TONEMAPPING\";\n }\n //sadly a second call to create the effect.\n this.updateEffect(defines);\n this.onApply = (effect) => {\n effect.setFloat(\"_ExposureAdjustment\", this.exposureAdjustment);\n };\n }\n}\n//# sourceMappingURL=tonemapPostProcess.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"volumetricLightScatteringPixelShader\";\nconst shader = `uniform sampler2D textureSampler;\runiform sampler2D lightScatteringSampler;\runiform float decay;\runiform float exposure;\runiform float weight;\runiform float density;\runiform vec2 meshPositionOnScreen;\rvarying vec2 vUV;\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_FRAGMENT_MAIN_BEGIN\nvec2 tc=vUV;\rvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\rdeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\rfloat illuminationDecay=1.0;\rvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\rfor(int i=0; i\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nuniform mat4 viewProjection;\runiform vec2 depthValues;\r#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\runiform mat4 diffuseMatrix;\r#ifdef UV1\nattribute vec2 uv;\r#endif\n#ifdef UV2\nattribute vec2 uv2;\r#endif\n#endif\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\r{\rvec3 positionUpdated=position;\r#if (defined(ALPHATEST) || defined(NEED_UV)) && defined(UV1)\nvec2 uvUpdated=uv;\r#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\r#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\r#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\r#endif\n#endif\n}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const volumetricLightScatteringPassVertexShader = { name, shader };\n//# sourceMappingURL=volumetricLightScatteringPass.vertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"volumetricLightScatteringPassPixelShader\";\nconst shader = `#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\r#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\r#endif\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void)\r{\r#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\rif (diffuseColor.a<0.4)\rdiscard;\r#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\r}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const volumetricLightScatteringPassPixelShader = { name, shader };\n//# sourceMappingURL=volumetricLightScatteringPass.fragment.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serializeAsVector3, serialize, serializeAsMeshReference } from \"../Misc/decorators.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { Vector2, Vector3, Matrix } from \"../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { AbstractMesh } from \"../Meshes/abstractMesh.js\";\nimport { Material } from \"../Materials/material.js\";\nimport { MaterialHelper } from \"../Materials/materialHelper.js\";\nimport { StandardMaterial } from \"../Materials/standardMaterial.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { RenderTargetTexture } from \"../Materials/Textures/renderTargetTexture.js\";\nimport { PostProcess } from \"./postProcess.js\";\n\nimport { CreatePlane } from \"../Meshes/Builders/planeBuilder.js\";\nimport \"../Shaders/depth.vertex.js\";\nimport \"../Shaders/volumetricLightScattering.fragment.js\";\nimport \"../Shaders/volumetricLightScatteringPass.vertex.js\";\nimport \"../Shaders/volumetricLightScatteringPass.fragment.js\";\nimport { Color4, Color3 } from \"../Maths/math.color.js\";\nimport { Viewport } from \"../Maths/math.viewport.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\n/**\n * Inspired by https://developer.nvidia.com/gpugems/gpugems3/part-ii-light-and-shadows/chapter-13-volumetric-light-scattering-post-process\n */\nexport class VolumetricLightScatteringPostProcess extends PostProcess {\n /**\n * @internal\n * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead\n */\n get useDiffuseColor() {\n Logger.Warn(\"VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead\");\n return false;\n }\n set useDiffuseColor(useDiffuseColor) {\n Logger.Warn(\"VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead\");\n }\n /**\n * @constructor\n * @param name The post-process name\n * @param ratio The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)\n * @param camera The camera that the post-process will be attached to\n * @param mesh The mesh used to create the light scattering\n * @param samples The post-process quality, default 100\n * @param samplingMode The post-process filtering mode\n * @param engine The babylon engine\n * @param reusable If the post-process is reusable\n * @param scene The constructor needs a scene reference to initialize internal components. If \"camera\" is null a \"scene\" must be provided\n */\n constructor(name, ratio, camera, mesh, samples = 100, samplingMode = Texture.BILINEAR_SAMPLINGMODE, engine, reusable, scene) {\n var _a, _b;\n super(name, \"volumetricLightScattering\", [\"decay\", \"exposure\", \"weight\", \"meshPositionOnScreen\", \"density\"], [\"lightScatteringSampler\"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, \"#define NUM_SAMPLES \" + samples);\n this._screenCoordinates = Vector2.Zero();\n /**\n * Custom position of the mesh. Used if \"useCustomMeshPosition\" is set to \"true\"\n */\n this.customMeshPosition = Vector3.Zero();\n /**\n * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)\n */\n this.useCustomMeshPosition = false;\n /**\n * If the post-process should inverse the light scattering direction\n */\n this.invert = true;\n /**\n * Array containing the excluded meshes not rendered in the internal pass\n */\n this.excludedMeshes = new Array();\n /**\n * Array containing the only meshes rendered in the internal pass.\n * If this array is not empty, only the meshes from this array are rendered in the internal pass\n */\n this.includedMeshes = new Array();\n /**\n * Controls the overall intensity of the post-process\n */\n this.exposure = 0.3;\n /**\n * Dissipates each sample's contribution in range [0, 1]\n */\n this.decay = 0.96815;\n /**\n * Controls the overall intensity of each sample\n */\n this.weight = 0.58767;\n /**\n * Controls the density of each sample\n */\n this.density = 0.926;\n scene = (_b = (_a = camera === null || camera === void 0 ? void 0 : camera.getScene()) !== null && _a !== void 0 ? _a : scene) !== null && _b !== void 0 ? _b : this._scene; // parameter \"scene\" can be null.\n engine = scene.getEngine();\n this._viewPort = new Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());\n // Configure mesh\n this.mesh = mesh !== null && mesh !== void 0 ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh(\"VolumetricLightScatteringMesh\", scene);\n // Configure\n this._createPass(scene, ratio.passRatio || ratio);\n this.onActivate = (camera) => {\n if (!this.isSupported) {\n this.dispose(camera);\n }\n this.onActivate = null;\n };\n this.onApplyObservable.add((effect) => {\n this._updateMeshScreenCoordinates(scene);\n effect.setTexture(\"lightScatteringSampler\", this._volumetricLightScatteringRTT);\n effect.setFloat(\"exposure\", this.exposure);\n effect.setFloat(\"decay\", this.decay);\n effect.setFloat(\"weight\", this.weight);\n effect.setFloat(\"density\", this.density);\n effect.setVector2(\"meshPositionOnScreen\", this._screenCoordinates);\n });\n }\n /**\n * Returns the string \"VolumetricLightScatteringPostProcess\"\n * @returns \"VolumetricLightScatteringPostProcess\"\n */\n getClassName() {\n return \"VolumetricLightScatteringPostProcess\";\n }\n _isReady(subMesh, useInstances) {\n var _a;\n const mesh = subMesh.getMesh();\n // Render this.mesh as default\n if (mesh === this.mesh && mesh.material) {\n return mesh.material.isReady(mesh);\n }\n const renderingMaterial = (_a = mesh._internalAbstractMeshDataInfo._materialForRenderPass) === null || _a === void 0 ? void 0 : _a[this._scene.getEngine().currentRenderPassId];\n if (renderingMaterial) {\n return renderingMaterial.isReadyForSubMesh(mesh, subMesh, useInstances);\n }\n const defines = [];\n const attribs = [VertexBuffer.PositionKind];\n const material = subMesh.getMaterial();\n // Alpha test\n if (material) {\n if (material.needAlphaTesting()) {\n defines.push(\"#define ALPHATEST\");\n }\n if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {\n attribs.push(VertexBuffer.UVKind);\n defines.push(\"#define UV1\");\n }\n if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {\n attribs.push(VertexBuffer.UV2Kind);\n defines.push(\"#define UV2\");\n }\n }\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders) {\n attribs.push(VertexBuffer.MatricesIndicesKind);\n attribs.push(VertexBuffer.MatricesWeightsKind);\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n defines.push(\"#define BonesPerMesh \" + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Instances\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n MaterialHelper.PushAttributesForInstances(attribs);\n if (subMesh.getRenderingMesh().hasThinInstances) {\n defines.push(\"#define THIN_INSTANCES\");\n }\n }\n // Get correct effect\n const drawWrapper = subMesh._getDrawWrapper(undefined, true);\n const cachedDefines = drawWrapper.defines;\n const join = defines.join(\"\\n\");\n if (cachedDefines !== join) {\n drawWrapper.setEffect(mesh\n .getScene()\n .getEngine()\n .createEffect(\"volumetricLightScatteringPass\", attribs, [\"world\", \"mBones\", \"viewProjection\", \"diffuseMatrix\"], [\"diffuseSampler\"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: mesh.numBoneInfluencers }), join);\n }\n return drawWrapper.effect.isReady();\n }\n /**\n * Sets the new light position for light scattering effect\n * @param position The new custom light position\n */\n setCustomMeshPosition(position) {\n this.customMeshPosition = position;\n }\n /**\n * Returns the light position for light scattering effect\n * @returns Vector3 The custom light position\n */\n getCustomMeshPosition() {\n return this.customMeshPosition;\n }\n /**\n * Disposes the internal assets and detaches the post-process from the camera\n * @param camera\n */\n dispose(camera) {\n const rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);\n if (rttIndex !== -1) {\n camera.getScene().customRenderTargets.splice(rttIndex, 1);\n }\n this._volumetricLightScatteringRTT.dispose();\n super.dispose(camera);\n }\n /**\n * Returns the render target texture used by the post-process\n * @returns the render target texture used by the post-process\n */\n getPass() {\n return this._volumetricLightScatteringRTT;\n }\n // Private methods\n _meshExcluded(mesh) {\n if ((this.includedMeshes.length > 0 && this.includedMeshes.indexOf(mesh) === -1) || (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1)) {\n return true;\n }\n return false;\n }\n _createPass(scene, ratio) {\n const engine = scene.getEngine();\n this._volumetricLightScatteringRTT = new RenderTargetTexture(\"volumetricLightScatteringMap\", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, 0);\n this._volumetricLightScatteringRTT.wrapU = Texture.CLAMP_ADDRESSMODE;\n this._volumetricLightScatteringRTT.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._volumetricLightScatteringRTT.renderList = null;\n this._volumetricLightScatteringRTT.renderParticles = false;\n this._volumetricLightScatteringRTT.ignoreCameraViewport = true;\n const camera = this.getCamera();\n if (camera) {\n camera.customRenderTargets.push(this._volumetricLightScatteringRTT);\n }\n else {\n scene.customRenderTargets.push(this._volumetricLightScatteringRTT);\n }\n // Custom render function for submeshes\n const renderSubMesh = (subMesh) => {\n var _a;\n const renderingMesh = subMesh.getRenderingMesh();\n const effectiveMesh = subMesh.getEffectiveMesh();\n if (this._meshExcluded(renderingMesh)) {\n return;\n }\n effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;\n const material = subMesh.getMaterial();\n if (!material) {\n return;\n }\n const scene = renderingMesh.getScene();\n const engine = scene.getEngine();\n // Culling\n engine.setState(material.backFaceCulling, undefined, undefined, undefined, material.cullBackFaces);\n // Managing instances\n const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());\n if (batch.mustReturn) {\n return;\n }\n const hardwareInstancedRendering = engine.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null || renderingMesh.hasThinInstances);\n if (this._isReady(subMesh, hardwareInstancedRendering)) {\n const renderingMaterial = (_a = effectiveMesh._internalAbstractMeshDataInfo._materialForRenderPass) === null || _a === void 0 ? void 0 : _a[engine.currentRenderPassId];\n let drawWrapper = subMesh._getDrawWrapper();\n if (renderingMesh === this.mesh && !drawWrapper) {\n drawWrapper = material._getDrawWrapper();\n }\n if (!drawWrapper) {\n return;\n }\n const effect = drawWrapper.effect;\n engine.enableEffect(drawWrapper);\n if (!hardwareInstancedRendering) {\n renderingMesh._bind(subMesh, effect, material.fillMode);\n }\n if (renderingMesh === this.mesh) {\n material.bind(effectiveMesh.getWorldMatrix(), renderingMesh);\n }\n else if (renderingMaterial) {\n renderingMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), effectiveMesh, subMesh);\n }\n else {\n effect.setMatrix(\"viewProjection\", scene.getTransformMatrix());\n // Alpha test\n if (material && material.needAlphaTesting()) {\n const alphaTexture = material.getAlphaTestTexture();\n effect.setTexture(\"diffuseSampler\", alphaTexture);\n if (alphaTexture) {\n effect.setMatrix(\"diffuseMatrix\", alphaTexture.getTextureMatrix());\n }\n }\n // Bones\n if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) {\n effect.setMatrices(\"mBones\", renderingMesh.skeleton.getTransformMatrices(renderingMesh));\n }\n }\n if (hardwareInstancedRendering && renderingMesh.hasThinInstances) {\n effect.setMatrix(\"world\", effectiveMesh.getWorldMatrix());\n }\n // Draw\n renderingMesh._processRendering(effectiveMesh, subMesh, effect, Material.TriangleFillMode, batch, hardwareInstancedRendering, (isInstance, world) => {\n if (!isInstance) {\n effect.setMatrix(\"world\", world);\n }\n });\n }\n };\n // Render target texture callbacks\n let savedSceneClearColor;\n const sceneClearColor = new Color4(0.0, 0.0, 0.0, 1.0);\n this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(() => {\n savedSceneClearColor = scene.clearColor;\n scene.clearColor = sceneClearColor;\n });\n this._volumetricLightScatteringRTT.onAfterRenderObservable.add(() => {\n scene.clearColor = savedSceneClearColor;\n });\n this._volumetricLightScatteringRTT.customIsReadyFunction = (mesh, refreshRate, preWarm) => {\n if ((preWarm || refreshRate === 0) && mesh.subMeshes) {\n for (let i = 0; i < mesh.subMeshes.length; ++i) {\n const subMesh = mesh.subMeshes[i];\n const material = subMesh.getMaterial();\n const renderingMesh = subMesh.getRenderingMesh();\n if (!material) {\n continue;\n }\n const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());\n const hardwareInstancedRendering = engine.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null || renderingMesh.hasThinInstances);\n if (!this._isReady(subMesh, hardwareInstancedRendering)) {\n return false;\n }\n }\n }\n return true;\n };\n this._volumetricLightScatteringRTT.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => {\n const engine = scene.getEngine();\n let index;\n if (depthOnlySubMeshes.length) {\n engine.setColorWrite(false);\n for (index = 0; index < depthOnlySubMeshes.length; index++) {\n renderSubMesh(depthOnlySubMeshes.data[index]);\n }\n engine.setColorWrite(true);\n }\n for (index = 0; index < opaqueSubMeshes.length; index++) {\n renderSubMesh(opaqueSubMeshes.data[index]);\n }\n for (index = 0; index < alphaTestSubMeshes.length; index++) {\n renderSubMesh(alphaTestSubMeshes.data[index]);\n }\n if (transparentSubMeshes.length) {\n // Sort sub meshes\n for (index = 0; index < transparentSubMeshes.length; index++) {\n const submesh = transparentSubMeshes.data[index];\n const boundingInfo = submesh.getBoundingInfo();\n if (boundingInfo && scene.activeCamera) {\n submesh._alphaIndex = submesh.getMesh().alphaIndex;\n submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();\n }\n }\n const sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);\n sortedArray.sort((a, b) => {\n // Alpha index first\n if (a._alphaIndex > b._alphaIndex) {\n return 1;\n }\n if (a._alphaIndex < b._alphaIndex) {\n return -1;\n }\n // Then distance to camera\n if (a._distanceToCamera < b._distanceToCamera) {\n return 1;\n }\n if (a._distanceToCamera > b._distanceToCamera) {\n return -1;\n }\n return 0;\n });\n // Render sub meshes\n engine.setAlphaMode(2);\n for (index = 0; index < sortedArray.length; index++) {\n renderSubMesh(sortedArray[index]);\n }\n engine.setAlphaMode(0);\n }\n };\n }\n _updateMeshScreenCoordinates(scene) {\n const transform = scene.getTransformMatrix();\n let meshPosition;\n if (this.useCustomMeshPosition) {\n meshPosition = this.customMeshPosition;\n }\n else if (this.attachedNode) {\n meshPosition = this.attachedNode.position;\n }\n else {\n meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;\n }\n const pos = Vector3.Project(meshPosition, Matrix.Identity(), transform, this._viewPort);\n this._screenCoordinates.x = pos.x / this._viewPort.width;\n this._screenCoordinates.y = pos.y / this._viewPort.height;\n if (this.invert) {\n this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;\n }\n }\n // Static methods\n /**\n * Creates a default mesh for the Volumeric Light Scattering post-process\n * @param name The mesh name\n * @param scene The scene where to create the mesh\n * @returns the default mesh\n */\n static CreateDefaultMesh(name, scene) {\n const mesh = CreatePlane(name, { size: 1 }, scene);\n mesh.billboardMode = AbstractMesh.BILLBOARDMODE_ALL;\n const material = new StandardMaterial(name + \"Material\", scene);\n material.emissiveColor = new Color3(1, 1, 1);\n mesh.material = material;\n return mesh;\n }\n}\n__decorate([\n serializeAsVector3()\n], VolumetricLightScatteringPostProcess.prototype, \"customMeshPosition\", void 0);\n__decorate([\n serialize()\n], VolumetricLightScatteringPostProcess.prototype, \"useCustomMeshPosition\", void 0);\n__decorate([\n serialize()\n], VolumetricLightScatteringPostProcess.prototype, \"invert\", void 0);\n__decorate([\n serializeAsMeshReference()\n], VolumetricLightScatteringPostProcess.prototype, \"mesh\", void 0);\n__decorate([\n serialize()\n], VolumetricLightScatteringPostProcess.prototype, \"excludedMeshes\", void 0);\n__decorate([\n serialize()\n], VolumetricLightScatteringPostProcess.prototype, \"includedMeshes\", void 0);\n__decorate([\n serialize()\n], VolumetricLightScatteringPostProcess.prototype, \"exposure\", void 0);\n__decorate([\n serialize()\n], VolumetricLightScatteringPostProcess.prototype, \"decay\", void 0);\n__decorate([\n serialize()\n], VolumetricLightScatteringPostProcess.prototype, \"weight\", void 0);\n__decorate([\n serialize()\n], VolumetricLightScatteringPostProcess.prototype, \"density\", void 0);\nRegisterClass(\"BABYLON.VolumetricLightScatteringPostProcess\", VolumetricLightScatteringPostProcess);\n//# sourceMappingURL=volumetricLightScatteringPostProcess.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"screenSpaceCurvaturePixelShader\";\nconst shader = `precision highp float;\rvarying vec2 vUV;\runiform sampler2D textureSampler;\runiform sampler2D normalSampler;\runiform float curvature_ridge;\runiform float curvature_valley;\r#ifndef CURVATURE_OFFSET\n#define CURVATURE_OFFSET 1\n#endif\nfloat curvature_soft_clamp(float curvature,float control)\r{\rif (curvature<0.5/control)\rreturn curvature*(1.0-curvature*control);\rreturn 0.25/control;\r}\rfloat calculate_curvature(ivec2 texel,float ridge,float valley)\r{\rvec2 normal_up =texelFetch(normalSampler,texel+ivec2(0, CURVATURE_OFFSET),0).rb;\rvec2 normal_down =texelFetch(normalSampler,texel+ivec2(0,-CURVATURE_OFFSET),0).rb;\rvec2 normal_left =texelFetch(normalSampler,texel+ivec2(-CURVATURE_OFFSET,0),0).rb;\rvec2 normal_right=texelFetch(normalSampler,texel+ivec2( CURVATURE_OFFSET,0),0).rb;\rfloat normal_diff=((normal_up.g-normal_down.g)+(normal_right.r-normal_left.r));\rif (normal_diff<0.0)\rreturn -2.0*curvature_soft_clamp(-normal_diff,valley);\rreturn 2.0*curvature_soft_clamp(normal_diff,ridge);\r}\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \r{\rivec2 texel=ivec2(gl_FragCoord.xy);\rvec4 baseColor=texture2D(textureSampler,vUV);\rfloat curvature=calculate_curvature(texel,curvature_ridge,curvature_valley);\rbaseColor.rgb*=curvature+1.0;\rgl_FragColor=baseColor;\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const screenSpaceCurvaturePixelShader = { name, shader };\n//# sourceMappingURL=screenSpaceCurvature.fragment.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { PostProcess } from \"./postProcess.js\";\n\nimport \"../Rendering/geometryBufferRendererSceneComponent.js\";\nimport \"../Shaders/screenSpaceCurvature.fragment.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\nimport { serialize, SerializationHelper } from \"../Misc/decorators.js\";\n/**\n * The Screen Space curvature effect can help highlighting ridge and valley of a model.\n */\nexport class ScreenSpaceCurvaturePostProcess extends PostProcess {\n /**\n * Gets a string identifying the name of the class\n * @returns \"ScreenSpaceCurvaturePostProcess\" string\n */\n getClassName() {\n return \"ScreenSpaceCurvaturePostProcess\";\n }\n /**\n * Creates a new instance ScreenSpaceCurvaturePostProcess\n * @param name The name of the effect.\n * @param scene The scene containing the objects to blur according to their velocity.\n * @param options The required width/height ratio to downsize to before computing the render pass.\n * @param camera The camera to apply the render pass to.\n * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)\n * @param engine The engine which the post process will be applied. (default: current engine)\n * @param reusable If the post process can be reused on the same frame. (default: false)\n * @param textureType Type of textures used when performing the post process. (default: 0)\n * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)\n */\n constructor(name, scene, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) {\n super(name, \"screenSpaceCurvature\", [\"curvature_ridge\", \"curvature_valley\"], [\"textureSampler\", \"normalSampler\"], options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation);\n /**\n * Defines how much ridge the curvature effect displays.\n */\n this.ridge = 1;\n /**\n * Defines how much valley the curvature effect displays.\n */\n this.valley = 1;\n this._geometryBufferRenderer = scene.enableGeometryBufferRenderer();\n if (!this._geometryBufferRenderer) {\n // Geometry buffer renderer is not supported. So, work as a passthrough.\n Logger.Error(\"Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.\");\n }\n else {\n // Geometry buffer renderer is supported.\n this.onApply = (effect) => {\n effect.setFloat(\"curvature_ridge\", 0.5 / Math.max(this.ridge * this.ridge, 1e-4));\n effect.setFloat(\"curvature_valley\", 0.7 / Math.max(this.valley * this.valley, 1e-4));\n const normalTexture = this._geometryBufferRenderer.getGBuffer().textures[1];\n effect.setTexture(\"normalSampler\", normalTexture);\n };\n }\n }\n /**\n * Support test.\n */\n static get IsSupported() {\n const engine = EngineStore.LastCreatedEngine;\n if (!engine) {\n return false;\n }\n return engine.getCaps().drawBuffersExtension;\n }\n /**\n * @internal\n */\n static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) {\n return SerializationHelper.Parse(() => {\n return new ScreenSpaceCurvaturePostProcess(parsedPostProcess.name, scene, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.textureType, parsedPostProcess.reusable);\n }, parsedPostProcess, scene, rootUrl);\n }\n}\n__decorate([\n serialize()\n], ScreenSpaceCurvaturePostProcess.prototype, \"ridge\", void 0);\n__decorate([\n serialize()\n], ScreenSpaceCurvaturePostProcess.prototype, \"valley\", void 0);\nRegisterClass(\"BABYLON.ScreenSpaceCurvaturePostProcess\", ScreenSpaceCurvaturePostProcess);\n//# sourceMappingURL=screenSpaceCurvaturePostProcess.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./anaglyphPostProcess.js\";\nexport * from \"./blackAndWhitePostProcess.js\";\nexport * from \"./bloomEffect.js\";\nexport * from \"./bloomMergePostProcess.js\";\nexport * from \"./blurPostProcess.js\";\nexport * from \"./chromaticAberrationPostProcess.js\";\nexport * from \"./circleOfConfusionPostProcess.js\";\nexport * from \"./colorCorrectionPostProcess.js\";\nexport * from \"./convolutionPostProcess.js\";\nexport * from \"./depthOfFieldBlurPostProcess.js\";\nexport * from \"./depthOfFieldEffect.js\";\nexport * from \"./depthOfFieldMergePostProcess.js\";\nexport * from \"./displayPassPostProcess.js\";\nexport * from \"./extractHighlightsPostProcess.js\";\nexport * from \"./filterPostProcess.js\";\nexport * from \"./fxaaPostProcess.js\";\nexport * from \"./grainPostProcess.js\";\nexport * from \"./highlightsPostProcess.js\";\nexport * from \"./imageProcessingPostProcess.js\";\nexport * from \"./motionBlurPostProcess.js\";\nexport * from \"./passPostProcess.js\";\nexport * from \"./postProcess.js\";\nexport * from \"./postProcessManager.js\";\nexport * from \"./refractionPostProcess.js\";\nexport * from \"./RenderPipeline/index.js\";\nexport * from \"./sharpenPostProcess.js\";\nexport * from \"./stereoscopicInterlacePostProcess.js\";\nexport * from \"./tonemapPostProcess.js\";\nexport * from \"./volumetricLightScatteringPostProcess.js\";\nexport * from \"./vrDistortionCorrectionPostProcess.js\";\nexport * from \"./vrMultiviewToSingleviewPostProcess.js\";\nexport * from \"./screenSpaceReflectionPostProcess.js\";\nexport * from \"./screenSpaceCurvaturePostProcess.js\";\n//# sourceMappingURL=index.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"boundingBoxRendererUboDeclaration\";\nconst shader = `#ifdef WEBGL2\nuniform vec4 color;\runiform mat4 world;\runiform mat4 viewProjection;\r#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\r#endif\n#else\nlayout(std140,column_major) uniform;\runiform BoundingBoxRenderer {\rvec4 color;\rmat4 world;\rmat4 viewProjection;\rmat4 viewProjectionR;\r};\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const boundingBoxRendererUboDeclaration = { name, shader };\n//# sourceMappingURL=boundingBoxRendererUboDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/boundingBoxRendererFragmentDeclaration.js\";\nimport \"./ShadersInclude/boundingBoxRendererUboDeclaration.js\";\nconst name = \"boundingBoxRendererPixelShader\";\nconst shader = `#include<__decl__boundingBoxRendererFragment>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_FRAGMENT_MAIN_BEGIN\ngl_FragColor=color;\r#define CUSTOM_FRAGMENT_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const boundingBoxRendererPixelShader = { name, shader };\n//# sourceMappingURL=boundingBoxRenderer.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"boundingBoxRendererVertexDeclaration\";\nconst shader = `uniform mat4 world;\runiform mat4 viewProjection;\r#ifdef MULTIVIEW\nuniform mat4 viewProjectionR;\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const boundingBoxRendererVertexDeclaration = { name, shader };\n//# sourceMappingURL=boundingBoxRendererVertexDeclaration.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/boundingBoxRendererVertexDeclaration.js\";\nimport \"./ShadersInclude/boundingBoxRendererUboDeclaration.js\";\nconst name = \"boundingBoxRendererVertexShader\";\nconst shader = `attribute vec3 position;\r#include<__decl__boundingBoxRendererVertex>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_VERTEX_MAIN_BEGIN\nvec4 worldPos=world*vec4(position,1.0);\r#ifdef MULTIVIEW\nif (gl_ViewID_OVR==0u) {\rgl_Position=viewProjection*worldPos;\r} else {\rgl_Position=viewProjectionR*worldPos;\r}\r#else\ngl_Position=viewProjection*worldPos;\r#endif\n#define CUSTOM_VERTEX_MAIN_END\n}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const boundingBoxRendererVertexShader = { name, shader };\n//# sourceMappingURL=boundingBoxRenderer.vertex.js.map","import { Scene } from \"../scene.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { AbstractMesh } from \"../Meshes/abstractMesh.js\";\nimport { Matrix } from \"../Maths/math.vector.js\";\nimport { SmartArray } from \"../Misc/smartArray.js\";\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { Material } from \"../Materials/material.js\";\nimport { ShaderMaterial } from \"../Materials/shaderMaterial.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { DrawWrapper } from \"../Materials/drawWrapper.js\";\nimport { UniformBuffer } from \"../Materials/uniformBuffer.js\";\nimport { CreateBoxVertexData } from \"../Meshes/Builders/boxBuilder.js\";\nimport \"../Shaders/boundingBoxRenderer.fragment.js\";\nimport \"../Shaders/boundingBoxRenderer.vertex.js\";\nObject.defineProperty(Scene.prototype, \"forceShowBoundingBoxes\", {\n get: function () {\n return this._forceShowBoundingBoxes || false;\n },\n set: function (value) {\n this._forceShowBoundingBoxes = value;\n // Lazyly creates a BB renderer if needed.\n if (value) {\n this.getBoundingBoxRenderer();\n }\n },\n enumerable: true,\n configurable: true,\n});\nScene.prototype.getBoundingBoxRenderer = function () {\n if (!this._boundingBoxRenderer) {\n this._boundingBoxRenderer = new BoundingBoxRenderer(this);\n }\n return this._boundingBoxRenderer;\n};\nObject.defineProperty(AbstractMesh.prototype, \"showBoundingBox\", {\n get: function () {\n return this._showBoundingBox || false;\n },\n set: function (value) {\n this._showBoundingBox = value;\n // Lazyly creates a BB renderer if needed.\n if (value) {\n this.getScene().getBoundingBoxRenderer();\n }\n },\n enumerable: true,\n configurable: true,\n});\n/**\n * Component responsible of rendering the bounding box of the meshes in a scene.\n * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties\n */\nexport class BoundingBoxRenderer {\n /**\n * Instantiates a new bounding box renderer in a scene.\n * @param scene the scene the renderer renders in\n */\n constructor(scene) {\n /**\n * The component name helpful to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;\n /**\n * Color of the bounding box lines placed in front of an object\n */\n this.frontColor = new Color3(1, 1, 1);\n /**\n * Color of the bounding box lines placed behind an object\n */\n this.backColor = new Color3(0.1, 0.1, 0.1);\n /**\n * Defines if the renderer should show the back lines or not\n */\n this.showBackLines = true;\n /**\n * Observable raised before rendering a bounding box\n */\n this.onBeforeBoxRenderingObservable = new Observable();\n /**\n * Observable raised after rendering a bounding box\n */\n this.onAfterBoxRenderingObservable = new Observable();\n /**\n * Observable raised after resources are created\n */\n this.onResourcesReadyObservable = new Observable();\n /**\n * When false, no bounding boxes will be rendered\n */\n this.enabled = true;\n /**\n * @internal\n */\n this.renderList = new SmartArray(32);\n this._vertexBuffers = {};\n this._fillIndexBuffer = null;\n this._fillIndexData = null;\n this.scene = scene;\n scene._addComponent(this);\n this._uniformBufferFront = new UniformBuffer(this.scene.getEngine(), undefined, undefined, \"BoundingBoxRendererFront\", !this.scene.getEngine().isWebGPU);\n this._buildUniformLayout(this._uniformBufferFront);\n this._uniformBufferBack = new UniformBuffer(this.scene.getEngine(), undefined, undefined, \"BoundingBoxRendererBack\", !this.scene.getEngine().isWebGPU);\n this._buildUniformLayout(this._uniformBufferBack);\n }\n _buildUniformLayout(ubo) {\n ubo.addUniform(\"color\", 4);\n ubo.addUniform(\"world\", 16);\n ubo.addUniform(\"viewProjection\", 16);\n ubo.addUniform(\"viewProjectionR\", 16);\n ubo.create();\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene._beforeEvaluateActiveMeshStage.registerStep(SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);\n this.scene._preActiveMeshStage.registerStep(SceneComponentConstants.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER, this, this._preActiveMesh);\n this.scene._evaluateSubMeshStage.registerStep(SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);\n this.scene._afterRenderingGroupDrawStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);\n }\n _evaluateSubMesh(mesh, subMesh) {\n if (mesh.showSubMeshesBoundingBox) {\n const boundingInfo = subMesh.getBoundingInfo();\n if (boundingInfo !== null && boundingInfo !== undefined) {\n boundingInfo.boundingBox._tag = mesh.renderingGroupId;\n this.renderList.push(boundingInfo.boundingBox);\n }\n }\n }\n _preActiveMesh(mesh) {\n if (mesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {\n const boundingInfo = mesh.getBoundingInfo();\n boundingInfo.boundingBox._tag = mesh.renderingGroupId;\n this.renderList.push(boundingInfo.boundingBox);\n }\n }\n _prepareResources() {\n if (this._colorShader) {\n return;\n }\n this._colorShader = new ShaderMaterial(\"colorShader\", this.scene, \"boundingBoxRenderer\", {\n attributes: [VertexBuffer.PositionKind],\n uniforms: [\"world\", \"viewProjection\", \"viewProjectionR\", \"color\"],\n uniformBuffers: [\"BoundingBoxRenderer\"],\n }, false);\n this._colorShader.doNotSerialize = true;\n this._colorShader.reservedDataStore = {\n hidden: true,\n };\n this._colorShaderForOcclusionQuery = new ShaderMaterial(\"colorShaderOccQuery\", this.scene, \"boundingBoxRenderer\", {\n attributes: [VertexBuffer.PositionKind],\n uniforms: [\"world\", \"viewProjection\", \"viewProjectionR\", \"color\"],\n uniformBuffers: [\"BoundingBoxRenderer\"],\n }, true);\n this._colorShaderForOcclusionQuery.doNotSerialize = true;\n this._colorShaderForOcclusionQuery.reservedDataStore = {\n hidden: true,\n };\n const engine = this.scene.getEngine();\n const boxdata = CreateBoxVertexData({ size: 1.0 });\n this._vertexBuffers[VertexBuffer.PositionKind] = new VertexBuffer(engine, boxdata.positions, VertexBuffer.PositionKind, false);\n this._createIndexBuffer();\n this._fillIndexData = boxdata.indices;\n this.onResourcesReadyObservable.notifyObservers(this);\n }\n _createIndexBuffer() {\n const engine = this.scene.getEngine();\n this._indexBuffer = engine.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n const vb = this._vertexBuffers[VertexBuffer.PositionKind];\n if (vb) {\n vb._rebuild();\n }\n this._createIndexBuffer();\n }\n /**\n * @internal\n */\n reset() {\n this.renderList.reset();\n }\n /**\n * Render the bounding boxes of a specific rendering group\n * @param renderingGroupId defines the rendering group to render\n */\n render(renderingGroupId) {\n var _a, _b;\n if (this.renderList.length === 0 || !this.enabled) {\n return;\n }\n this._prepareResources();\n if (!this._colorShader.isReady()) {\n return;\n }\n const engine = this.scene.getEngine();\n engine.setDepthWrite(false);\n const transformMatrix = this.scene.getTransformMatrix();\n for (let boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {\n const boundingBox = this.renderList.data[boundingBoxIndex];\n if (boundingBox._tag !== renderingGroupId) {\n continue;\n }\n this._createWrappersForBoundingBox(boundingBox);\n this.onBeforeBoxRenderingObservable.notifyObservers(boundingBox);\n const min = boundingBox.minimum;\n const max = boundingBox.maximum;\n const diff = max.subtract(min);\n const median = min.add(diff.scale(0.5));\n const worldMatrix = Matrix.Scaling(diff.x, diff.y, diff.z).multiply(Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());\n const useReverseDepthBuffer = engine.useReverseDepthBuffer;\n if (this.showBackLines) {\n const drawWrapperBack = (_a = boundingBox._drawWrapperBack) !== null && _a !== void 0 ? _a : this._colorShader._getDrawWrapper();\n this._colorShader._preBind(drawWrapperBack);\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());\n // Back\n if (useReverseDepthBuffer) {\n engine.setDepthFunctionToLessOrEqual();\n }\n else {\n engine.setDepthFunctionToGreaterOrEqual();\n }\n this._uniformBufferBack.bindToEffect(drawWrapperBack.effect, \"BoundingBoxRenderer\");\n this._uniformBufferBack.updateColor4(\"color\", this.backColor, 1);\n this._uniformBufferBack.updateMatrix(\"world\", worldMatrix);\n this._uniformBufferBack.updateMatrix(\"viewProjection\", transformMatrix);\n this._uniformBufferBack.update();\n // Draw order\n engine.drawElementsType(Material.LineListDrawMode, 0, 24);\n }\n const drawWrapperFront = (_b = boundingBox._drawWrapperFront) !== null && _b !== void 0 ? _b : this._colorShader._getDrawWrapper();\n this._colorShader._preBind(drawWrapperFront);\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());\n // Front\n if (useReverseDepthBuffer) {\n engine.setDepthFunctionToGreater();\n }\n else {\n engine.setDepthFunctionToLess();\n }\n this._uniformBufferFront.bindToEffect(drawWrapperFront.effect, \"BoundingBoxRenderer\");\n this._uniformBufferFront.updateColor4(\"color\", this.frontColor, 1);\n this._uniformBufferFront.updateMatrix(\"world\", worldMatrix);\n this._uniformBufferFront.updateMatrix(\"viewProjection\", transformMatrix);\n this._uniformBufferFront.update();\n // Draw order\n engine.drawElementsType(Material.LineListDrawMode, 0, 24);\n this.onAfterBoxRenderingObservable.notifyObservers(boundingBox);\n }\n this._colorShader.unbind();\n engine.setDepthFunctionToLessOrEqual();\n engine.setDepthWrite(true);\n }\n _createWrappersForBoundingBox(boundingBox) {\n if (!boundingBox._drawWrapperFront) {\n const engine = this.scene.getEngine();\n boundingBox._drawWrapperFront = new DrawWrapper(engine);\n boundingBox._drawWrapperBack = new DrawWrapper(engine);\n boundingBox._drawWrapperFront.setEffect(this._colorShader.getEffect());\n boundingBox._drawWrapperBack.setEffect(this._colorShader.getEffect());\n }\n }\n /**\n * In case of occlusion queries, we can render the occlusion bounding box through this method\n * @param mesh Define the mesh to render the occlusion bounding box for\n */\n renderOcclusionBoundingBox(mesh) {\n const engine = this.scene.getEngine();\n if (this._renderPassIdForOcclusionQuery === undefined) {\n this._renderPassIdForOcclusionQuery = engine.createRenderPassId(`Render pass for occlusion query`);\n }\n const currentRenderPassId = engine.currentRenderPassId;\n engine.currentRenderPassId = this._renderPassIdForOcclusionQuery;\n this._prepareResources();\n const subMesh = mesh.subMeshes[0];\n if (!this._colorShaderForOcclusionQuery.isReady(mesh, undefined, subMesh) || !mesh.hasBoundingInfo) {\n engine.currentRenderPassId = currentRenderPassId;\n return;\n }\n if (!this._fillIndexBuffer) {\n this._fillIndexBuffer = engine.createIndexBuffer(this._fillIndexData);\n }\n const useReverseDepthBuffer = engine.useReverseDepthBuffer;\n engine.setDepthWrite(false);\n engine.setColorWrite(false);\n const boundingBox = mesh.getBoundingInfo().boundingBox;\n const min = boundingBox.minimum;\n const max = boundingBox.maximum;\n const diff = max.subtract(min);\n const median = min.add(diff.scale(0.5));\n const worldMatrix = Matrix.Scaling(diff.x, diff.y, diff.z).multiply(Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());\n const drawWrapper = subMesh._drawWrapper;\n this._colorShaderForOcclusionQuery._preBind(drawWrapper);\n engine.bindBuffers(this._vertexBuffers, this._fillIndexBuffer, drawWrapper.effect);\n if (useReverseDepthBuffer) {\n engine.setDepthFunctionToGreater();\n }\n else {\n engine.setDepthFunctionToLess();\n }\n this.scene.resetCachedMaterial();\n this._uniformBufferFront.bindToEffect(drawWrapper.effect, \"BoundingBoxRenderer\");\n this._uniformBufferFront.updateMatrix(\"world\", worldMatrix);\n this._uniformBufferFront.updateMatrix(\"viewProjection\", this.scene.getTransformMatrix());\n this._uniformBufferFront.update();\n engine.drawElementsType(Material.TriangleFillMode, 0, 36);\n this._colorShaderForOcclusionQuery.unbind();\n engine.setDepthFunctionToLessOrEqual();\n engine.setDepthWrite(true);\n engine.setColorWrite(true);\n engine.currentRenderPassId = currentRenderPassId;\n }\n /**\n * Dispose and release the resources attached to this renderer.\n */\n dispose() {\n if (this._renderPassIdForOcclusionQuery !== undefined) {\n this.scene.getEngine().releaseRenderPassId(this._renderPassIdForOcclusionQuery);\n this._renderPassIdForOcclusionQuery = undefined;\n }\n if (!this._colorShader) {\n return;\n }\n this.onBeforeBoxRenderingObservable.clear();\n this.onAfterBoxRenderingObservable.clear();\n this.onResourcesReadyObservable.clear();\n this.renderList.dispose();\n this._colorShader.dispose();\n this._colorShaderForOcclusionQuery.dispose();\n this._uniformBufferFront.dispose();\n this._uniformBufferBack.dispose();\n const buffer = this._vertexBuffers[VertexBuffer.PositionKind];\n if (buffer) {\n buffer.dispose();\n this._vertexBuffers[VertexBuffer.PositionKind] = null;\n }\n this.scene.getEngine()._releaseBuffer(this._indexBuffer);\n if (this._fillIndexBuffer) {\n this.scene.getEngine()._releaseBuffer(this._fillIndexBuffer);\n this._fillIndexBuffer = null;\n }\n }\n}\n//# sourceMappingURL=boundingBoxRenderer.js.map","import { Scene } from \"../scene.js\";\nimport { DepthRenderer } from \"./depthRenderer.js\";\n\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nScene.prototype.enableDepthRenderer = function (camera, storeNonLinearDepth = false, force32bitsFloat = false, samplingMode = 3, storeCameraSpaceZ = false) {\n camera = camera || this.activeCamera;\n if (!camera) {\n throw \"No camera available to enable depth renderer\";\n }\n if (!this._depthRenderer) {\n this._depthRenderer = {};\n }\n if (!this._depthRenderer[camera.id]) {\n const supportFullfloat = !!this.getEngine().getCaps().textureFloatRender;\n let textureType = 0;\n if (this.getEngine().getCaps().textureHalfFloatRender && (!force32bitsFloat || !supportFullfloat)) {\n textureType = 2;\n }\n else if (supportFullfloat) {\n textureType = 1;\n }\n else {\n textureType = 0;\n }\n this._depthRenderer[camera.id] = new DepthRenderer(this, textureType, camera, storeNonLinearDepth, samplingMode, storeCameraSpaceZ);\n }\n return this._depthRenderer[camera.id];\n};\nScene.prototype.disableDepthRenderer = function (camera) {\n camera = camera || this.activeCamera;\n if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {\n return;\n }\n this._depthRenderer[camera.id].dispose();\n};\n/**\n * Defines the Depth Renderer scene component responsible to manage a depth buffer useful\n * in several rendering techniques.\n */\nexport class DepthRendererSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpful to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_DEPTHRENDERER;\n this.scene = scene;\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene._gatherRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);\n this.scene._gatherActiveCameraRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n // Nothing to do for this component\n }\n /**\n * Disposes the component and the associated resources\n */\n dispose() {\n for (const key in this.scene._depthRenderer) {\n this.scene._depthRenderer[key].dispose();\n }\n }\n _gatherRenderTargets(renderTargets) {\n if (this.scene._depthRenderer) {\n for (const key in this.scene._depthRenderer) {\n const depthRenderer = this.scene._depthRenderer[key];\n if (depthRenderer.enabled && !depthRenderer.useOnlyInActiveCamera) {\n renderTargets.push(depthRenderer.getDepthMap());\n }\n }\n }\n }\n _gatherActiveCameraRenderTargets(renderTargets) {\n if (this.scene._depthRenderer) {\n for (const key in this.scene._depthRenderer) {\n const depthRenderer = this.scene._depthRenderer[key];\n if (depthRenderer.enabled && depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {\n renderTargets.push(depthRenderer.getDepthMap());\n }\n }\n }\n }\n}\nDepthRenderer._SceneComponentInitialization = (scene) => {\n // Register the G Buffer component to the scene.\n let component = scene._getComponent(SceneComponentConstants.NAME_DEPTHRENDERER);\n if (!component) {\n component = new DepthRendererSceneComponent(scene);\n scene._addComponent(component);\n }\n};\n//# sourceMappingURL=depthRendererSceneComponent.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"oitFinalPixelShader\";\nconst shader = `precision highp float;\runiform sampler2D uFrontColor;\runiform sampler2D uBackColor;\rvoid main() {\rivec2 fragCoord=ivec2(gl_FragCoord.xy);\rvec4 frontColor=texelFetch(uFrontColor,fragCoord,0);\rvec4 backColor=texelFetch(uBackColor,fragCoord,0);\rfloat alphaMultiplier=1.0-frontColor.a;\rglFragColor=vec4(\rfrontColor.rgb+alphaMultiplier*backColor.rgb,\rfrontColor.a+backColor.a\r);\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const oitFinalPixelShader = { name, shader };\n//# sourceMappingURL=oitFinal.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"oitBackBlendPixelShader\";\nconst shader = `precision highp float;\runiform sampler2D uBackColor;\rvoid main() {\rglFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);\rif (glFragColor.a==0.0) { \rdiscard;\r}\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const oitBackBlendPixelShader = { name, shader };\n//# sourceMappingURL=oitBackBlend.fragment.js.map","/**\n * Implementation based on https://medium.com/@shrekshao_71662/dual-depth-peeling-implementation-in-webgl-11baa061ba4b\n */\n\nimport { MultiRenderTarget } from \"../Materials/Textures/multiRenderTarget.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { SmartArray } from \"../Misc/smartArray.js\";\nimport { ThinTexture } from \"../Materials/Textures/thinTexture.js\";\nimport { EffectRenderer, EffectWrapper } from \"../Materials/effectRenderer.js\";\nimport { RenderTargetTexture } from \"../Materials/Textures/renderTargetTexture.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { Material } from \"../Materials/material.js\";\nimport \"../Shaders/postprocess.vertex.js\";\nimport \"../Shaders/oitFinal.fragment.js\";\nimport \"../Shaders/oitBackBlend.fragment.js\";\nclass DepthPeelingEffectConfiguration {\n constructor() {\n /**\n * Is this effect enabled\n */\n this.enabled = true;\n /**\n * Name of the configuration\n */\n this.name = \"depthPeeling\";\n /**\n * Textures that should be present in the MRT for this effect to work\n */\n this.texturesRequired = [4];\n }\n}\n/**\n * The depth peeling renderer that performs\n * Order independant transparency (OIT).\n * This should not be instanciated directly, as it is part of a scene component\n */\nexport class DepthPeelingRenderer {\n /**\n * Number of depth peeling passes. As we are using dual depth peeling, each pass two levels of transparency are processed.\n */\n get passCount() {\n return this._passCount;\n }\n set passCount(count) {\n if (this._passCount === count) {\n return;\n }\n this._passCount = count;\n this._createRenderPassIds();\n }\n /**\n * Instructs the renderer to use render passes. It is an optimization that makes the rendering faster for some engines (like WebGPU) but that consumes more memory, so it is disabled by default.\n */\n get useRenderPasses() {\n return this._useRenderPasses;\n }\n set useRenderPasses(usePasses) {\n if (this._useRenderPasses === usePasses) {\n return;\n }\n this._useRenderPasses = usePasses;\n this._createRenderPassIds();\n }\n /**\n * Add a mesh in the exclusion list to prevent it to be handled by the depth peeling renderer\n * @param mesh The mesh to exclude from the depth peeling renderer\n */\n addExcludedMesh(mesh) {\n if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {\n this._excludedMeshes.push(mesh.uniqueId);\n }\n }\n /**\n * Remove a mesh from the exclusion list of the depth peeling renderer\n * @param mesh The mesh to remove\n */\n removeExcludedMesh(mesh) {\n const index = this._excludedMeshes.indexOf(mesh.uniqueId);\n if (index !== -1) {\n this._excludedMeshes.splice(index, 1);\n }\n }\n /**\n * Instanciates the depth peeling renderer\n * @param scene Scene to attach to\n * @param passCount Number of depth layers to peel\n * @returns The depth peeling renderer\n */\n constructor(scene, passCount = 5) {\n this._thinTextures = [];\n this._currentPingPongState = 0;\n this._layoutCacheFormat = [[true], [true, true], [true, true, true]];\n this._layoutCache = [];\n this._candidateSubMeshes = new SmartArray(10);\n this._excludedSubMeshes = new SmartArray(10);\n this._excludedMeshes = [];\n this._colorCache = [\n new Color4(DepthPeelingRenderer._DEPTH_CLEAR_VALUE, DepthPeelingRenderer._DEPTH_CLEAR_VALUE, 0, 0),\n new Color4(-DepthPeelingRenderer._MIN_DEPTH, DepthPeelingRenderer._MAX_DEPTH, 0, 0),\n new Color4(0, 0, 0, 0),\n ];\n this._scene = scene;\n this._engine = scene.getEngine();\n this._passCount = passCount;\n // We need a depth texture for opaque\n if (!scene.enablePrePassRenderer()) {\n Logger.Warn(\"Depth peeling for order independant transparency could not enable PrePass, aborting.\");\n return;\n }\n for (let i = 0; i < this._layoutCacheFormat.length; ++i) {\n this._layoutCache[i] = this._engine.buildTextureLayout(this._layoutCacheFormat[i]);\n }\n this._renderPassIds = [];\n this.useRenderPasses = false;\n this._prePassEffectConfiguration = new DepthPeelingEffectConfiguration();\n this._createTextures();\n this._createEffects();\n }\n _createRenderPassIds() {\n this._releaseRenderPassIds();\n if (this._useRenderPasses) {\n for (let i = 0; i < this._passCount + 1; ++i) {\n if (!this._renderPassIds[i]) {\n this._renderPassIds[i] = this._engine.createRenderPassId(`DepthPeelingRenderer - pass #${i}`);\n }\n }\n }\n }\n _releaseRenderPassIds() {\n for (let i = 0; i < this._renderPassIds.length; ++i) {\n this._engine.releaseRenderPassId(this._renderPassIds[i]);\n }\n this._renderPassIds = [];\n }\n _createTextures() {\n const size = {\n width: this._engine.getRenderWidth(),\n height: this._engine.getRenderHeight(),\n };\n // 2 for ping pong\n this._depthMrts = [new MultiRenderTarget(\"depthPeelingDepth0\", size, 3, this._scene), new MultiRenderTarget(\"depthPeelingDepth1\", size, 3, this._scene)];\n this._colorMrts = [\n new MultiRenderTarget(\"depthPeelingColor0\", size, 2, this._scene, { generateDepthBuffer: false }),\n new MultiRenderTarget(\"depthPeelingColor1\", size, 2, this._scene, { generateDepthBuffer: false }),\n ];\n this._blendBackMrt = new MultiRenderTarget(\"depthPeelingBack\", size, 1, this._scene, { generateDepthBuffer: false });\n this._outputRT = new RenderTargetTexture(\"depthPeelingOutput\", size, this._scene, false);\n // 0 is a depth texture\n // 1 is a color texture\n const optionsArray = [\n {\n format: 7,\n samplingMode: 1,\n type: this._engine.getCaps().textureFloatLinearFiltering ? 1 : 2,\n label: \"DepthPeelingRenderer-DepthTexture\",\n },\n {\n format: 5,\n samplingMode: 1,\n type: 2,\n label: \"DepthPeelingRenderer-ColorTexture\",\n },\n ];\n for (let i = 0; i < 2; i++) {\n const depthTexture = this._engine._createInternalTexture(size, optionsArray[0], false);\n const frontColorTexture = this._engine._createInternalTexture(size, optionsArray[1], false);\n const backColorTexture = this._engine._createInternalTexture(size, optionsArray[1], false);\n this._depthMrts[i].setInternalTexture(depthTexture, 0);\n this._depthMrts[i].setInternalTexture(frontColorTexture, 1);\n this._depthMrts[i].setInternalTexture(backColorTexture, 2);\n this._colorMrts[i].setInternalTexture(frontColorTexture, 0);\n this._colorMrts[i].setInternalTexture(backColorTexture, 1);\n this._thinTextures.push(new ThinTexture(depthTexture), new ThinTexture(frontColorTexture), new ThinTexture(backColorTexture));\n }\n }\n // TODO : explore again MSAA with depth peeling when\n // we are able to fetch individual samples in a multisampled renderbuffer\n // public set samples(value: number) {\n // for (let i = 0; i < 2; i++) {\n // this._depthMrts[i].samples = value;\n // this._colorMrts[i].samples = value;\n // }\n // this._scene.prePassRenderer!.samples = value;\n // }\n _disposeTextures() {\n for (let i = 0; i < this._thinTextures.length; i++) {\n if (i === 6) {\n // Do not dispose the shared texture with the prepass\n continue;\n }\n this._thinTextures[i].dispose();\n }\n for (let i = 0; i < 2; i++) {\n this._depthMrts[i].dispose(true);\n this._colorMrts[i].dispose(true);\n this._blendBackMrt.dispose(true);\n }\n this._outputRT.dispose();\n this._thinTextures = [];\n this._colorMrts = [];\n this._depthMrts = [];\n }\n _updateTextures() {\n if (this._depthMrts[0].getSize().width !== this._engine.getRenderWidth() || this._depthMrts[0].getSize().height !== this._engine.getRenderHeight()) {\n this._disposeTextures();\n this._createTextures();\n }\n return this._updateTextureReferences();\n }\n _updateTextureReferences() {\n var _a;\n const prePassRenderer = this._scene.prePassRenderer;\n if (!prePassRenderer) {\n return false;\n }\n // Retrieve opaque color texture\n const textureIndex = prePassRenderer.getIndex(4);\n const prePassTexture = ((_a = prePassRenderer.defaultRT.textures) === null || _a === void 0 ? void 0 : _a.length) ? prePassRenderer.defaultRT.textures[textureIndex].getInternalTexture() : null;\n if (!prePassTexture) {\n return false;\n }\n if (this._blendBackTexture !== prePassTexture) {\n this._blendBackTexture = prePassTexture;\n this._blendBackMrt.setInternalTexture(this._blendBackTexture, 0);\n if (this._thinTextures[6]) {\n this._thinTextures[6].dispose();\n }\n this._thinTextures[6] = new ThinTexture(this._blendBackTexture);\n prePassRenderer.defaultRT.renderTarget._shareDepth(this._depthMrts[0].renderTarget);\n }\n return true;\n }\n _createEffects() {\n this._blendBackEffectWrapper = new EffectWrapper({\n fragmentShader: \"oitBackBlend\",\n useShaderStore: true,\n engine: this._engine,\n samplerNames: [\"uBackColor\"],\n uniformNames: [],\n });\n this._blendBackEffectWrapperPingPong = new EffectWrapper({\n fragmentShader: \"oitBackBlend\",\n useShaderStore: true,\n engine: this._engine,\n samplerNames: [\"uBackColor\"],\n uniformNames: [],\n });\n this._finalEffectWrapper = new EffectWrapper({\n fragmentShader: \"oitFinal\",\n useShaderStore: true,\n engine: this._engine,\n samplerNames: [\"uFrontColor\", \"uBackColor\"],\n uniformNames: [],\n });\n this._effectRenderer = new EffectRenderer(this._engine);\n }\n /**\n * Links to the prepass renderer\n * @param prePassRenderer The scene PrePassRenderer\n */\n setPrePassRenderer(prePassRenderer) {\n prePassRenderer.addEffectConfiguration(this._prePassEffectConfiguration);\n }\n /**\n * Binds depth peeling textures on an effect\n * @param effect The effect to bind textures on\n */\n bind(effect) {\n effect.setTexture(\"oitDepthSampler\", this._thinTextures[this._currentPingPongState * 3]);\n effect.setTexture(\"oitFrontColorSampler\", this._thinTextures[this._currentPingPongState * 3 + 1]);\n }\n _renderSubMeshes(transparentSubMeshes) {\n let mapMaterialContext;\n if (this._useRenderPasses) {\n mapMaterialContext = {};\n }\n for (let j = 0; j < transparentSubMeshes.length; j++) {\n const material = transparentSubMeshes.data[j].getMaterial();\n let previousShaderHotSwapping = true;\n let previousBFC = false;\n const subMesh = transparentSubMeshes.data[j];\n let drawWrapper;\n let firstDraw = false;\n if (this._useRenderPasses) {\n drawWrapper = subMesh._getDrawWrapper();\n firstDraw = !drawWrapper;\n }\n if (material) {\n previousShaderHotSwapping = material.allowShaderHotSwapping;\n previousBFC = material.backFaceCulling;\n material.allowShaderHotSwapping = false;\n material.backFaceCulling = false;\n }\n subMesh.render(false);\n if (firstDraw) {\n // first time we draw this submesh: we replace the material context\n drawWrapper = subMesh._getDrawWrapper(); // we are sure it is now non empty as we just rendered the submesh\n if (drawWrapper.materialContext) {\n let newMaterialContext = mapMaterialContext[drawWrapper.materialContext.uniqueId];\n if (!newMaterialContext) {\n newMaterialContext = mapMaterialContext[drawWrapper.materialContext.uniqueId] = this._engine.createMaterialContext();\n }\n subMesh._getDrawWrapper().materialContext = newMaterialContext;\n }\n }\n if (material) {\n material.allowShaderHotSwapping = previousShaderHotSwapping;\n material.backFaceCulling = previousBFC;\n }\n }\n }\n _finalCompose(writeId) {\n var _a;\n const output = (_a = this._scene.prePassRenderer) === null || _a === void 0 ? void 0 : _a.setCustomOutput(this._outputRT);\n if (output) {\n this._engine.bindFramebuffer(this._outputRT.renderTarget);\n }\n else {\n this._engine.restoreDefaultFramebuffer();\n }\n this._engine.setAlphaMode(0);\n this._engine.applyStates();\n this._engine.enableEffect(this._finalEffectWrapper._drawWrapper);\n this._finalEffectWrapper.effect.setTexture(\"uFrontColor\", this._thinTextures[writeId * 3 + 1]);\n this._finalEffectWrapper.effect.setTexture(\"uBackColor\", this._thinTextures[6]);\n this._effectRenderer.render(this._finalEffectWrapper);\n }\n /**\n * Renders transparent submeshes with depth peeling\n * @param transparentSubMeshes List of transparent meshes to render\n * @returns The array of submeshes that could not be handled by this renderer\n */\n render(transparentSubMeshes) {\n this._candidateSubMeshes.length = 0;\n this._excludedSubMeshes.length = 0;\n if (!this._blendBackEffectWrapper.effect.isReady() ||\n !this._blendBackEffectWrapperPingPong.effect.isReady() ||\n !this._finalEffectWrapper.effect.isReady() ||\n !this._updateTextures()) {\n return this._excludedSubMeshes;\n }\n for (let i = 0; i < transparentSubMeshes.length; i++) {\n const subMesh = transparentSubMeshes.data[i];\n const material = subMesh.getMaterial();\n const fillMode = material && subMesh.getRenderingMesh()._getRenderingFillMode(material.fillMode);\n if (material &&\n (fillMode === Material.TriangleFanDrawMode || fillMode === Material.TriangleFillMode || fillMode === Material.TriangleStripDrawMode) &&\n this._excludedMeshes.indexOf(subMesh.getMesh().uniqueId) === -1) {\n this._candidateSubMeshes.push(subMesh);\n }\n else {\n this._excludedSubMeshes.push(subMesh);\n }\n }\n if (!this._candidateSubMeshes.length) {\n this._engine.bindFramebuffer(this._colorMrts[1].renderTarget);\n this._engine.bindAttachments(this._layoutCache[1]);\n this._engine.clear(this._colorCache[2], true, false, false);\n this._engine.unBindFramebuffer(this._colorMrts[1].renderTarget);\n this._finalCompose(1);\n return this._excludedSubMeshes;\n }\n const currentRenderPassId = this._engine.currentRenderPassId;\n this._scene.prePassRenderer._enabled = false;\n if (this._useRenderPasses) {\n this._engine.currentRenderPassId = this._renderPassIds[0];\n }\n // Clears\n this._engine.bindFramebuffer(this._depthMrts[0].renderTarget);\n this._engine.bindAttachments(this._layoutCache[0]);\n this._engine.clear(this._colorCache[0], true, false, false);\n this._engine.unBindFramebuffer(this._depthMrts[0].renderTarget);\n this._engine.bindFramebuffer(this._depthMrts[1].renderTarget);\n this._engine.bindAttachments(this._layoutCache[0]);\n this._engine.clear(this._colorCache[1], true, false, false);\n this._engine.unBindFramebuffer(this._depthMrts[1].renderTarget);\n this._engine.bindFramebuffer(this._colorMrts[0].renderTarget);\n this._engine.bindAttachments(this._layoutCache[1]);\n this._engine.clear(this._colorCache[2], true, false, false);\n this._engine.unBindFramebuffer(this._colorMrts[0].renderTarget);\n this._engine.bindFramebuffer(this._colorMrts[1].renderTarget);\n this._engine.bindAttachments(this._layoutCache[1]);\n this._engine.clear(this._colorCache[2], true, false, false);\n this._engine.unBindFramebuffer(this._colorMrts[1].renderTarget);\n // Draw depth for first pass\n this._engine.bindFramebuffer(this._depthMrts[0].renderTarget);\n this._engine.bindAttachments(this._layoutCache[0]);\n this._engine.setAlphaMode(11); // in WebGPU, when using MIN or MAX equation, the src / dst color factors should not use SRC_ALPHA and the src / dst alpha factors must be 1 else WebGPU will throw a validation error\n this._engine.setAlphaEquation(3);\n this._engine.depthCullingState.depthMask = false;\n this._engine.depthCullingState.depthTest = true;\n this._engine.applyStates();\n this._currentPingPongState = 1;\n // Render\n this._renderSubMeshes(this._candidateSubMeshes);\n this._engine.unBindFramebuffer(this._depthMrts[0].renderTarget);\n this._scene.resetCachedMaterial();\n // depth peeling ping-pong\n let readId = 0;\n let writeId = 0;\n for (let i = 0; i < this._passCount; i++) {\n readId = i % 2;\n writeId = 1 - readId;\n this._currentPingPongState = readId;\n if (this._useRenderPasses) {\n this._engine.currentRenderPassId = this._renderPassIds[i + 1];\n }\n // Clears\n this._engine.bindFramebuffer(this._depthMrts[writeId].renderTarget);\n this._engine.bindAttachments(this._layoutCache[0]);\n this._engine.clear(this._colorCache[0], true, false, false);\n this._engine.unBindFramebuffer(this._depthMrts[writeId].renderTarget);\n this._engine.bindFramebuffer(this._colorMrts[writeId].renderTarget);\n this._engine.bindAttachments(this._layoutCache[1]);\n this._engine.clear(this._colorCache[2], true, false, false);\n this._engine.unBindFramebuffer(this._colorMrts[writeId].renderTarget);\n this._engine.bindFramebuffer(this._depthMrts[writeId].renderTarget);\n this._engine.bindAttachments(this._layoutCache[2]);\n this._engine.setAlphaMode(11); // the value does not matter (as MAX operation does not use them) but the src and dst color factors should not use SRC_ALPHA else WebGPU will throw a validation error\n this._engine.setAlphaEquation(3);\n this._engine.depthCullingState.depthTest = false;\n this._engine.applyStates();\n // Render\n this._renderSubMeshes(this._candidateSubMeshes);\n this._engine.unBindFramebuffer(this._depthMrts[writeId].renderTarget);\n this._scene.resetCachedMaterial();\n // Back color\n this._engine.bindFramebuffer(this._blendBackMrt.renderTarget);\n this._engine.bindAttachments(this._layoutCache[0]);\n this._engine.setAlphaEquation(0);\n this._engine.setAlphaMode(17);\n this._engine.applyStates();\n const blendBackEffectWrapper = writeId === 0 || !this._useRenderPasses ? this._blendBackEffectWrapper : this._blendBackEffectWrapperPingPong;\n this._engine.enableEffect(blendBackEffectWrapper._drawWrapper);\n blendBackEffectWrapper.effect.setTexture(\"uBackColor\", this._thinTextures[writeId * 3 + 2]);\n this._effectRenderer.render(blendBackEffectWrapper);\n this._engine.unBindFramebuffer(this._blendBackMrt.renderTarget);\n }\n this._engine.currentRenderPassId = currentRenderPassId;\n // Final composition on default FB\n this._finalCompose(writeId);\n this._scene.prePassRenderer._enabled = true;\n this._engine.depthCullingState.depthMask = true;\n this._engine.depthCullingState.depthTest = true;\n return this._excludedSubMeshes;\n }\n /**\n * Disposes the depth peeling renderer and associated ressources\n */\n dispose() {\n this._disposeTextures();\n this._blendBackEffectWrapper.dispose();\n this._finalEffectWrapper.dispose();\n this._effectRenderer.dispose();\n this._releaseRenderPassIds();\n }\n}\nDepthPeelingRenderer._DEPTH_CLEAR_VALUE = -99999.0;\nDepthPeelingRenderer._MIN_DEPTH = 0;\nDepthPeelingRenderer._MAX_DEPTH = 1;\n//# sourceMappingURL=depthPeelingRenderer.js.map","\nimport { Scene } from \"../scene.js\";\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { DepthPeelingRenderer } from \"./depthPeelingRenderer.js\";\nObject.defineProperty(Scene.prototype, \"depthPeelingRenderer\", {\n get: function () {\n if (!this._depthPeelingRenderer) {\n let component = this._getComponent(SceneComponentConstants.NAME_DEPTHPEELINGRENDERER);\n if (!component) {\n component = new DepthPeelingSceneComponent(this);\n this._addComponent(component);\n }\n }\n return this._depthPeelingRenderer;\n },\n set: function (value) {\n this._depthPeelingRenderer = value;\n },\n enumerable: true,\n configurable: true,\n});\nObject.defineProperty(Scene.prototype, \"useOrderIndependentTransparency\", {\n get: function () {\n return this._useOrderIndependentTransparency;\n },\n set: function (value) {\n var _a;\n if (this._useOrderIndependentTransparency === value) {\n return;\n }\n this._useOrderIndependentTransparency = value;\n this.markAllMaterialsAsDirty(63);\n (_a = this.prePassRenderer) === null || _a === void 0 ? void 0 : _a.markAsDirty();\n },\n enumerable: true,\n configurable: true,\n});\n/**\n * Scene component to render order independent transparency with depth peeling\n */\nexport class DepthPeelingSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpful to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_DEPTHPEELINGRENDERER;\n this.scene = scene;\n scene.depthPeelingRenderer = new DepthPeelingRenderer(scene);\n }\n /**\n * Registers the component in a given scene\n */\n register() { }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() { }\n /**\n * Disposes the component and the associated resources.\n */\n dispose() {\n var _a;\n (_a = this.scene.depthPeelingRenderer) === null || _a === void 0 ? void 0 : _a.dispose();\n this.scene.depthPeelingRenderer = null;\n }\n}\n//# sourceMappingURL=depthPeelingSceneComponent.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/clipPlaneFragmentDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneFragment.js\";\nconst name = \"linePixelShader\";\nconst shader = `#include\nuniform vec4 color;\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\ngl_FragColor=color;\r#define CUSTOM_FRAGMENT_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const linePixelShader = { name, shader };\n//# sourceMappingURL=line.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/instancesDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneVertexDeclaration.js\";\nimport \"./ShadersInclude/instancesVertex.js\";\nimport \"./ShadersInclude/clipPlaneVertex.js\";\nconst name = \"lineVertexShader\";\nconst shader = `#include\n#include\nattribute vec3 position;\rattribute vec4 normal;\runiform mat4 viewProjection;\runiform float width;\runiform float aspectRatio;\r#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_VERTEX_MAIN_BEGIN\n#include\nmat4 worldViewProjection=viewProjection*finalWorld;\rvec4 viewPosition=worldViewProjection*vec4(position,1.0);\rvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\rvec2 currentScreen=viewPosition.xy/viewPosition.w;\rvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\rcurrentScreen.x*=aspectRatio;\rnextScreen.x*=aspectRatio;\rvec2 dir=normalize(nextScreen-currentScreen);\rvec2 normalDir=vec2(-dir.y,dir.x);\rnormalDir*=width/2.0;\rnormalDir.x/=aspectRatio;\rvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\rgl_Position=viewPosition+offset;\r#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6)\nvec4 worldPos=finalWorld*vec4(position,1.0);\r#include\n#endif\n#define CUSTOM_VERTEX_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const lineVertexShader = { name, shader };\n//# sourceMappingURL=line.vertex.js.map","import { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { AbstractMesh } from \"../Meshes/abstractMesh.js\";\nimport { LinesMesh, InstancedLinesMesh } from \"../Meshes/linesMesh.js\";\nimport { Vector3, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Material } from \"../Materials/material.js\";\nimport { ShaderMaterial } from \"../Materials/shaderMaterial.js\";\nimport { Camera } from \"../Cameras/camera.js\";\n\nimport \"../Shaders/line.fragment.js\";\nimport \"../Shaders/line.vertex.js\";\nimport { SmartArray } from \"../Misc/smartArray.js\";\nimport { DrawWrapper } from \"../Materials/drawWrapper.js\";\nAbstractMesh.prototype.disableEdgesRendering = function () {\n if (this._edgesRenderer) {\n this._edgesRenderer.dispose();\n this._edgesRenderer = null;\n }\n return this;\n};\nAbstractMesh.prototype.enableEdgesRendering = function (epsilon = 0.95, checkVerticesInsteadOfIndices = false, options) {\n this.disableEdgesRendering();\n this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices, true, options);\n return this;\n};\nObject.defineProperty(AbstractMesh.prototype, \"edgesRenderer\", {\n get: function () {\n return this._edgesRenderer;\n },\n enumerable: true,\n configurable: true,\n});\nLinesMesh.prototype.enableEdgesRendering = function (epsilon = 0.95, checkVerticesInsteadOfIndices = false) {\n this.disableEdgesRendering();\n this._edgesRenderer = new LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);\n return this;\n};\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nInstancedLinesMesh.prototype.enableEdgesRendering = function (epsilon = 0.95, checkVerticesInsteadOfIndices = false) {\n LinesMesh.prototype.enableEdgesRendering.apply(this, arguments);\n return this;\n};\n/**\n * FaceAdjacencies Helper class to generate edges\n */\nclass FaceAdjacencies {\n constructor() {\n this.edges = new Array();\n this.edgesConnectedCount = 0;\n }\n}\n/**\n * This class is used to generate edges of the mesh that could then easily be rendered in a scene.\n */\nexport class EdgesRenderer {\n /** Gets the vertices generated by the edge renderer */\n get linesPositions() {\n return this._linesPositions;\n }\n /** Gets the normals generated by the edge renderer */\n get linesNormals() {\n return this._linesNormals;\n }\n /** Gets the indices generated by the edge renderer */\n get linesIndices() {\n return this._linesIndices;\n }\n /**\n * Gets or sets the shader used to draw the lines\n */\n get lineShader() {\n return this._lineShader;\n }\n set lineShader(shader) {\n this._lineShader = shader;\n }\n static _GetShader(scene) {\n if (!scene._edgeRenderLineShader) {\n const shader = new ShaderMaterial(\"lineShader\", scene, \"line\", {\n attributes: [\"position\", \"normal\"],\n uniforms: [\"world\", \"viewProjection\", \"color\", \"width\", \"aspectRatio\"],\n }, false);\n shader.disableDepthWrite = true;\n shader.backFaceCulling = false;\n shader.checkReadyOnEveryCall = scene.getEngine().isWebGPU;\n scene._edgeRenderLineShader = shader;\n }\n return scene._edgeRenderLineShader;\n }\n /**\n * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.\n * Beware when you use this class with complex objects as the adjacencies computation can be really long\n * @param source Mesh used to create edges\n * @param epsilon sum of angles in adjacency to check for edge\n * @param checkVerticesInsteadOfIndices bases the edges detection on vertices vs indices. Note that this parameter is not used if options.useAlternateEdgeFinder = true\n * @param generateEdgesLines - should generate Lines or only prepare resources.\n * @param options The options to apply when generating the edges\n */\n constructor(source, epsilon = 0.95, checkVerticesInsteadOfIndices = false, generateEdgesLines = true, options) {\n var _a;\n /**\n * Define the size of the edges with an orthographic camera\n */\n this.edgesWidthScalerForOrthographic = 1000.0;\n /**\n * Define the size of the edges with a perspective camera\n */\n this.edgesWidthScalerForPerspective = 50.0;\n this._linesPositions = new Array();\n this._linesNormals = new Array();\n this._linesIndices = new Array();\n this._buffers = {};\n this._buffersForInstances = {};\n this._checkVerticesInsteadOfIndices = false;\n /** Gets or sets a boolean indicating if the edgesRenderer is active */\n this.isEnabled = true;\n /**\n * List of instances to render in case the source mesh has instances\n */\n this.customInstances = new SmartArray(32);\n this._source = source;\n this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;\n this._options = options !== null && options !== void 0 ? options : null;\n this._epsilon = epsilon;\n if (this._source.getScene().getEngine().isWebGPU) {\n this._drawWrapper = new DrawWrapper(source.getEngine());\n }\n this._prepareRessources();\n if (generateEdgesLines) {\n if ((_a = options === null || options === void 0 ? void 0 : options.useAlternateEdgeFinder) !== null && _a !== void 0 ? _a : true) {\n this._generateEdgesLinesAlternate();\n }\n else {\n this._generateEdgesLines();\n }\n }\n this._meshRebuildObserver = this._source.onRebuildObservable.add(() => {\n this._rebuild();\n });\n this._meshDisposeObserver = this._source.onDisposeObservable.add(() => {\n this.dispose();\n });\n }\n _prepareRessources() {\n if (this._lineShader) {\n return;\n }\n this._lineShader = EdgesRenderer._GetShader(this._source.getScene());\n }\n /** @internal */\n _rebuild() {\n let buffer = this._buffers[VertexBuffer.PositionKind];\n if (buffer) {\n buffer._rebuild();\n }\n buffer = this._buffers[VertexBuffer.NormalKind];\n if (buffer) {\n buffer._rebuild();\n }\n const scene = this._source.getScene();\n const engine = scene.getEngine();\n this._ib = engine.createIndexBuffer(this._linesIndices);\n }\n /**\n * Releases the required resources for the edges renderer\n */\n dispose() {\n var _a;\n this._source.onRebuildObservable.remove(this._meshRebuildObserver);\n this._source.onDisposeObservable.remove(this._meshDisposeObserver);\n let buffer = this._buffers[VertexBuffer.PositionKind];\n if (buffer) {\n buffer.dispose();\n this._buffers[VertexBuffer.PositionKind] = null;\n }\n buffer = this._buffers[VertexBuffer.NormalKind];\n if (buffer) {\n buffer.dispose();\n this._buffers[VertexBuffer.NormalKind] = null;\n }\n if (this._ib) {\n this._source.getScene().getEngine()._releaseBuffer(this._ib);\n }\n this._lineShader.dispose();\n (_a = this._drawWrapper) === null || _a === void 0 ? void 0 : _a.dispose();\n }\n _processEdgeForAdjacencies(pa, pb, p0, p1, p2) {\n if ((pa === p0 && pb === p1) || (pa === p1 && pb === p0)) {\n return 0;\n }\n if ((pa === p1 && pb === p2) || (pa === p2 && pb === p1)) {\n return 1;\n }\n if ((pa === p2 && pb === p0) || (pa === p0 && pb === p2)) {\n return 2;\n }\n return -1;\n }\n _processEdgeForAdjacenciesWithVertices(pa, pb, p0, p1, p2) {\n const eps = 1e-10;\n if ((pa.equalsWithEpsilon(p0, eps) && pb.equalsWithEpsilon(p1, eps)) || (pa.equalsWithEpsilon(p1, eps) && pb.equalsWithEpsilon(p0, eps))) {\n return 0;\n }\n if ((pa.equalsWithEpsilon(p1, eps) && pb.equalsWithEpsilon(p2, eps)) || (pa.equalsWithEpsilon(p2, eps) && pb.equalsWithEpsilon(p1, eps))) {\n return 1;\n }\n if ((pa.equalsWithEpsilon(p2, eps) && pb.equalsWithEpsilon(p0, eps)) || (pa.equalsWithEpsilon(p0, eps) && pb.equalsWithEpsilon(p2, eps))) {\n return 2;\n }\n return -1;\n }\n /**\n * Checks if the pair of p0 and p1 is en edge\n * @param faceIndex\n * @param edge\n * @param faceNormals\n * @param p0\n * @param p1\n * @private\n */\n _checkEdge(faceIndex, edge, faceNormals, p0, p1) {\n let needToCreateLine;\n if (edge === undefined) {\n needToCreateLine = true;\n }\n else {\n const dotProduct = Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);\n needToCreateLine = dotProduct < this._epsilon;\n }\n if (needToCreateLine) {\n this.createLine(p0, p1, this._linesPositions.length / 3);\n }\n }\n /**\n * push line into the position, normal and index buffer\n * @param p0\n * @param p1\n * @param offset\n * @protected\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n createLine(p0, p1, offset) {\n // Positions\n this._linesPositions.push(p0.x, p0.y, p0.z, p0.x, p0.y, p0.z, p1.x, p1.y, p1.z, p1.x, p1.y, p1.z);\n // Normals\n this._linesNormals.push(p1.x, p1.y, p1.z, -1, p1.x, p1.y, p1.z, 1, p0.x, p0.y, p0.z, -1, p0.x, p0.y, p0.z, 1);\n // Indices\n this._linesIndices.push(offset, offset + 1, offset + 2, offset, offset + 2, offset + 3);\n }\n /**\n * See https://playground.babylonjs.com/#R3JR6V#1 for a visual display of the algorithm\n * @param edgePoints\n * @param indexTriangle\n * @param indices\n * @param remapVertexIndices\n */\n _tessellateTriangle(edgePoints, indexTriangle, indices, remapVertexIndices) {\n const makePointList = (edgePoints, pointIndices, firstIndex) => {\n if (firstIndex >= 0) {\n pointIndices.push(firstIndex);\n }\n for (let i = 0; i < edgePoints.length; ++i) {\n pointIndices.push(edgePoints[i][0]);\n }\n };\n let startEdge = 0;\n if (edgePoints[1].length >= edgePoints[0].length && edgePoints[1].length >= edgePoints[2].length) {\n startEdge = 1;\n }\n else if (edgePoints[2].length >= edgePoints[0].length && edgePoints[2].length >= edgePoints[1].length) {\n startEdge = 2;\n }\n for (let e = 0; e < 3; ++e) {\n if (e === startEdge) {\n edgePoints[e].sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0));\n }\n else {\n edgePoints[e].sort((a, b) => (a[1] > b[1] ? -1 : a[1] < b[1] ? 1 : 0));\n }\n }\n const mainPointIndices = [], otherPointIndices = [];\n makePointList(edgePoints[startEdge], mainPointIndices, -1);\n const numMainPoints = mainPointIndices.length;\n for (let i = startEdge + 2; i >= startEdge + 1; --i) {\n makePointList(edgePoints[i % 3], otherPointIndices, i !== startEdge + 2 ? remapVertexIndices[indices[indexTriangle + ((i + 1) % 3)]] : -1);\n }\n const numOtherPoints = otherPointIndices.length;\n const idxMain = 0;\n const idxOther = 0;\n indices.push(remapVertexIndices[indices[indexTriangle + startEdge]], mainPointIndices[0], otherPointIndices[0]);\n indices.push(remapVertexIndices[indices[indexTriangle + ((startEdge + 1) % 3)]], otherPointIndices[numOtherPoints - 1], mainPointIndices[numMainPoints - 1]);\n const bucketIsMain = numMainPoints <= numOtherPoints;\n const bucketStep = bucketIsMain ? numMainPoints : numOtherPoints;\n const bucketLimit = bucketIsMain ? numOtherPoints : numMainPoints;\n const bucketIdxLimit = bucketIsMain ? numMainPoints - 1 : numOtherPoints - 1;\n const winding = bucketIsMain ? 0 : 1;\n let numTris = numMainPoints + numOtherPoints - 2;\n let bucketIdx = bucketIsMain ? idxMain : idxOther;\n let nbucketIdx = bucketIsMain ? idxOther : idxMain;\n const bucketPoints = bucketIsMain ? mainPointIndices : otherPointIndices;\n const nbucketPoints = bucketIsMain ? otherPointIndices : mainPointIndices;\n let bucket = 0;\n while (numTris-- > 0) {\n if (winding) {\n indices.push(bucketPoints[bucketIdx], nbucketPoints[nbucketIdx]);\n }\n else {\n indices.push(nbucketPoints[nbucketIdx], bucketPoints[bucketIdx]);\n }\n bucket += bucketStep;\n let lastIdx;\n if (bucket >= bucketLimit && bucketIdx < bucketIdxLimit) {\n lastIdx = bucketPoints[++bucketIdx];\n bucket -= bucketLimit;\n }\n else {\n lastIdx = nbucketPoints[++nbucketIdx];\n }\n indices.push(lastIdx);\n }\n indices[indexTriangle + 0] = indices[indices.length - 3];\n indices[indexTriangle + 1] = indices[indices.length - 2];\n indices[indexTriangle + 2] = indices[indices.length - 1];\n indices.length = indices.length - 3;\n }\n _generateEdgesLinesAlternate() {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;\n const positions = this._source.getVerticesData(VertexBuffer.PositionKind);\n let indices = this._source.getIndices();\n if (!indices || !positions) {\n return;\n }\n if (!Array.isArray(indices)) {\n indices = Array.from(indices);\n }\n /**\n * Find all vertices that are at the same location (with an epsilon) and remapp them on the same vertex\n */\n const useFastVertexMerger = (_b = (_a = this._options) === null || _a === void 0 ? void 0 : _a.useFastVertexMerger) !== null && _b !== void 0 ? _b : true;\n const epsVertexMerge = useFastVertexMerger ? Math.round(-Math.log((_d = (_c = this._options) === null || _c === void 0 ? void 0 : _c.epsilonVertexMerge) !== null && _d !== void 0 ? _d : 1e-6) / Math.log(10)) : (_f = (_e = this._options) === null || _e === void 0 ? void 0 : _e.epsilonVertexMerge) !== null && _f !== void 0 ? _f : 1e-6;\n const remapVertexIndices = [];\n const uniquePositions = []; // list of unique index of vertices - needed for tessellation\n if (useFastVertexMerger) {\n const mapVertices = {};\n for (let v1 = 0; v1 < positions.length; v1 += 3) {\n const x1 = positions[v1 + 0], y1 = positions[v1 + 1], z1 = positions[v1 + 2];\n const key = x1.toFixed(epsVertexMerge) + \"|\" + y1.toFixed(epsVertexMerge) + \"|\" + z1.toFixed(epsVertexMerge);\n if (mapVertices[key] !== undefined) {\n remapVertexIndices.push(mapVertices[key]);\n }\n else {\n const idx = v1 / 3;\n mapVertices[key] = idx;\n remapVertexIndices.push(idx);\n uniquePositions.push(idx);\n }\n }\n }\n else {\n for (let v1 = 0; v1 < positions.length; v1 += 3) {\n const x1 = positions[v1 + 0], y1 = positions[v1 + 1], z1 = positions[v1 + 2];\n let found = false;\n for (let v2 = 0; v2 < v1 && !found; v2 += 3) {\n const x2 = positions[v2 + 0], y2 = positions[v2 + 1], z2 = positions[v2 + 2];\n if (Math.abs(x1 - x2) < epsVertexMerge && Math.abs(y1 - y2) < epsVertexMerge && Math.abs(z1 - z2) < epsVertexMerge) {\n remapVertexIndices.push(v2 / 3);\n found = true;\n break;\n }\n }\n if (!found) {\n remapVertexIndices.push(v1 / 3);\n uniquePositions.push(v1 / 3);\n }\n }\n }\n if ((_g = this._options) === null || _g === void 0 ? void 0 : _g.applyTessellation) {\n /**\n * Tessellate triangles if necessary:\n *\n * A\n * +\n * |\\\n * | \\\n * | \\\n * E + \\\n * /| \\\n * / | \\\n * / | \\\n * +---+-------+ B\n * D C\n *\n * For the edges to be rendered correctly, the ABC triangle has to be split into ABE and BCE, else AC is considered to be an edge, whereas only AE should be.\n *\n * The tessellation process looks for the vertices like E that are in-between two other vertices making of an edge and create new triangles as necessary\n */\n // First step: collect the triangles to tessellate\n const epsVertexAligned = (_j = (_h = this._options) === null || _h === void 0 ? void 0 : _h.epsilonVertexAligned) !== null && _j !== void 0 ? _j : 1e-6;\n const mustTesselate = []; // liste of triangles that must be tessellated\n for (let index = 0; index < indices.length; index += 3) {\n // loop over all triangles\n let triangleToTessellate;\n for (let i = 0; i < 3; ++i) {\n // loop over the 3 edges of the triangle\n const p0Index = remapVertexIndices[indices[index + i]];\n const p1Index = remapVertexIndices[indices[index + ((i + 1) % 3)]];\n const p2Index = remapVertexIndices[indices[index + ((i + 2) % 3)]];\n if (p0Index === p1Index) {\n continue;\n } // degenerated triangle - don't process\n const p0x = positions[p0Index * 3 + 0], p0y = positions[p0Index * 3 + 1], p0z = positions[p0Index * 3 + 2];\n const p1x = positions[p1Index * 3 + 0], p1y = positions[p1Index * 3 + 1], p1z = positions[p1Index * 3 + 2];\n const p0p1 = Math.sqrt((p1x - p0x) * (p1x - p0x) + (p1y - p0y) * (p1y - p0y) + (p1z - p0z) * (p1z - p0z));\n for (let v = 0; v < uniquePositions.length - 1; v++) {\n // loop over all (unique) vertices and look for the ones that would be in-between p0 and p1\n const vIndex = uniquePositions[v];\n if (vIndex === p0Index || vIndex === p1Index || vIndex === p2Index) {\n continue;\n } // don't handle the vertex if it is a vertex of the current triangle\n const x = positions[vIndex * 3 + 0], y = positions[vIndex * 3 + 1], z = positions[vIndex * 3 + 2];\n const p0p = Math.sqrt((x - p0x) * (x - p0x) + (y - p0y) * (y - p0y) + (z - p0z) * (z - p0z));\n const pp1 = Math.sqrt((x - p1x) * (x - p1x) + (y - p1y) * (y - p1y) + (z - p1z) * (z - p1z));\n if (Math.abs(p0p + pp1 - p0p1) < epsVertexAligned) {\n // vertices are aligned and p in-between p0 and p1 if distance(p0, p) + distance (p, p1) ~ distance(p0, p1)\n if (!triangleToTessellate) {\n triangleToTessellate = {\n index: index,\n edgesPoints: [[], [], []],\n };\n mustTesselate.push(triangleToTessellate);\n }\n triangleToTessellate.edgesPoints[i].push([vIndex, p0p]);\n }\n }\n }\n }\n // Second step: tesselate the triangles\n for (let t = 0; t < mustTesselate.length; ++t) {\n const triangle = mustTesselate[t];\n this._tessellateTriangle(triangle.edgesPoints, triangle.index, indices, remapVertexIndices);\n }\n mustTesselate.length = 0;\n }\n /**\n * Collect the edges to render\n */\n const edges = {};\n for (let index = 0; index < indices.length; index += 3) {\n let faceNormal;\n for (let i = 0; i < 3; ++i) {\n let p0Index = remapVertexIndices[indices[index + i]];\n let p1Index = remapVertexIndices[indices[index + ((i + 1) % 3)]];\n const p2Index = remapVertexIndices[indices[index + ((i + 2) % 3)]];\n if (p0Index === p1Index || ((p0Index === p2Index || p1Index === p2Index) && ((_k = this._options) === null || _k === void 0 ? void 0 : _k.removeDegeneratedTriangles))) {\n continue;\n }\n TmpVectors.Vector3[0].copyFromFloats(positions[p0Index * 3 + 0], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);\n TmpVectors.Vector3[1].copyFromFloats(positions[p1Index * 3 + 0], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);\n TmpVectors.Vector3[2].copyFromFloats(positions[p2Index * 3 + 0], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);\n if (!faceNormal) {\n TmpVectors.Vector3[1].subtractToRef(TmpVectors.Vector3[0], TmpVectors.Vector3[3]);\n TmpVectors.Vector3[2].subtractToRef(TmpVectors.Vector3[1], TmpVectors.Vector3[4]);\n faceNormal = Vector3.Cross(TmpVectors.Vector3[3], TmpVectors.Vector3[4]);\n faceNormal.normalize();\n }\n if (p0Index > p1Index) {\n const tmp = p0Index;\n p0Index = p1Index;\n p1Index = tmp;\n }\n const key = p0Index + \"_\" + p1Index;\n const ei = edges[key];\n if (ei) {\n if (!ei.done) {\n const dotProduct = Vector3.Dot(faceNormal, ei.normal);\n if (dotProduct < this._epsilon) {\n this.createLine(TmpVectors.Vector3[0], TmpVectors.Vector3[1], this._linesPositions.length / 3);\n }\n ei.done = true;\n }\n }\n else {\n edges[key] = { normal: faceNormal, done: false, index: index, i: i };\n }\n }\n }\n for (const key in edges) {\n const ei = edges[key];\n if (!ei.done) {\n // Orphaned edge - we must display it\n const p0Index = remapVertexIndices[indices[ei.index + ei.i]];\n const p1Index = remapVertexIndices[indices[ei.index + ((ei.i + 1) % 3)]];\n TmpVectors.Vector3[0].copyFromFloats(positions[p0Index * 3 + 0], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);\n TmpVectors.Vector3[1].copyFromFloats(positions[p1Index * 3 + 0], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);\n this.createLine(TmpVectors.Vector3[0], TmpVectors.Vector3[1], this._linesPositions.length / 3);\n }\n }\n /**\n * Merge into a single mesh\n */\n const engine = this._source.getScene().getEngine();\n this._buffers[VertexBuffer.PositionKind] = new VertexBuffer(engine, this._linesPositions, VertexBuffer.PositionKind, false);\n this._buffers[VertexBuffer.NormalKind] = new VertexBuffer(engine, this._linesNormals, VertexBuffer.NormalKind, false, false, 4);\n this._buffersForInstances[VertexBuffer.PositionKind] = this._buffers[VertexBuffer.PositionKind];\n this._buffersForInstances[VertexBuffer.NormalKind] = this._buffers[VertexBuffer.NormalKind];\n this._ib = engine.createIndexBuffer(this._linesIndices);\n this._indicesCount = this._linesIndices.length;\n }\n /**\n * Generates lines edges from adjacencjes\n * @private\n */\n _generateEdgesLines() {\n const positions = this._source.getVerticesData(VertexBuffer.PositionKind);\n const indices = this._source.getIndices();\n if (!indices || !positions) {\n return;\n }\n // First let's find adjacencies\n const adjacencies = new Array();\n const faceNormals = new Array();\n let index;\n let faceAdjacencies;\n // Prepare faces\n for (index = 0; index < indices.length; index += 3) {\n faceAdjacencies = new FaceAdjacencies();\n const p0Index = indices[index];\n const p1Index = indices[index + 1];\n const p2Index = indices[index + 2];\n faceAdjacencies.p0 = new Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);\n faceAdjacencies.p1 = new Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);\n faceAdjacencies.p2 = new Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);\n const faceNormal = Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));\n faceNormal.normalize();\n faceNormals.push(faceNormal);\n adjacencies.push(faceAdjacencies);\n }\n // Scan\n for (index = 0; index < adjacencies.length; index++) {\n faceAdjacencies = adjacencies[index];\n for (let otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {\n const otherFaceAdjacencies = adjacencies[otherIndex];\n if (faceAdjacencies.edgesConnectedCount === 3) {\n // Full\n break;\n }\n if (otherFaceAdjacencies.edgesConnectedCount === 3) {\n // Full\n continue;\n }\n const otherP0 = indices[otherIndex * 3];\n const otherP1 = indices[otherIndex * 3 + 1];\n const otherP2 = indices[otherIndex * 3 + 2];\n for (let edgeIndex = 0; edgeIndex < 3; edgeIndex++) {\n let otherEdgeIndex = 0;\n if (faceAdjacencies.edges[edgeIndex] !== undefined) {\n continue;\n }\n switch (edgeIndex) {\n case 0:\n if (this._checkVerticesInsteadOfIndices) {\n otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);\n }\n else {\n otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);\n }\n break;\n case 1:\n if (this._checkVerticesInsteadOfIndices) {\n otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);\n }\n else {\n otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);\n }\n break;\n case 2:\n if (this._checkVerticesInsteadOfIndices) {\n otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);\n }\n else {\n otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);\n }\n break;\n }\n if (otherEdgeIndex === -1) {\n continue;\n }\n faceAdjacencies.edges[edgeIndex] = otherIndex;\n otherFaceAdjacencies.edges[otherEdgeIndex] = index;\n faceAdjacencies.edgesConnectedCount++;\n otherFaceAdjacencies.edgesConnectedCount++;\n if (faceAdjacencies.edgesConnectedCount === 3) {\n break;\n }\n }\n }\n }\n // Create lines\n for (index = 0; index < adjacencies.length; index++) {\n // We need a line when a face has no adjacency on a specific edge or if all the adjacencies has an angle greater than epsilon\n const current = adjacencies[index];\n this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);\n this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);\n this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);\n }\n // Merge into a single mesh\n const engine = this._source.getScene().getEngine();\n this._buffers[VertexBuffer.PositionKind] = new VertexBuffer(engine, this._linesPositions, VertexBuffer.PositionKind, false);\n this._buffers[VertexBuffer.NormalKind] = new VertexBuffer(engine, this._linesNormals, VertexBuffer.NormalKind, false, false, 4);\n this._buffersForInstances[VertexBuffer.PositionKind] = this._buffers[VertexBuffer.PositionKind];\n this._buffersForInstances[VertexBuffer.NormalKind] = this._buffers[VertexBuffer.NormalKind];\n this._ib = engine.createIndexBuffer(this._linesIndices);\n this._indicesCount = this._linesIndices.length;\n }\n /**\n * Checks whether or not the edges renderer is ready to render.\n * @returns true if ready, otherwise false.\n */\n isReady() {\n return this._lineShader.isReady(this._source, (this._source.hasInstances && this.customInstances.length > 0) || this._source.hasThinInstances);\n }\n /**\n * Renders the edges of the attached mesh,\n */\n render() {\n const scene = this._source.getScene();\n const currentDrawWrapper = this._lineShader._getDrawWrapper();\n if (this._drawWrapper) {\n this._lineShader._setDrawWrapper(this._drawWrapper);\n }\n if (!this.isReady() || !scene.activeCamera) {\n this._lineShader._setDrawWrapper(currentDrawWrapper);\n return;\n }\n const hasInstances = this._source.hasInstances && this.customInstances.length > 0;\n const useBuffersWithInstances = hasInstances || this._source.hasThinInstances;\n let instanceCount = 0;\n if (useBuffersWithInstances) {\n this._buffersForInstances[\"world0\"] = this._source.getVertexBuffer(\"world0\");\n this._buffersForInstances[\"world1\"] = this._source.getVertexBuffer(\"world1\");\n this._buffersForInstances[\"world2\"] = this._source.getVertexBuffer(\"world2\");\n this._buffersForInstances[\"world3\"] = this._source.getVertexBuffer(\"world3\");\n if (hasInstances) {\n const instanceStorage = this._source._instanceDataStorage;\n instanceCount = this.customInstances.length;\n if (!instanceStorage.instancesData) {\n if (!this._source.getScene()._activeMeshesFrozen) {\n this.customInstances.reset();\n }\n return;\n }\n if (!instanceStorage.isFrozen) {\n let offset = 0;\n for (let i = 0; i < instanceCount; ++i) {\n this.customInstances.data[i].copyToArray(instanceStorage.instancesData, offset);\n offset += 16;\n }\n instanceStorage.instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instanceCount);\n }\n }\n else {\n instanceCount = this._source.thinInstanceCount;\n }\n }\n const engine = scene.getEngine();\n this._lineShader._preBind();\n if (this._source.edgesColor.a !== 1) {\n engine.setAlphaMode(2);\n }\n else {\n engine.setAlphaMode(0);\n }\n // VBOs\n engine.bindBuffers(useBuffersWithInstances ? this._buffersForInstances : this._buffers, this._ib, this._lineShader.getEffect());\n scene.resetCachedMaterial();\n this._lineShader.setColor4(\"color\", this._source.edgesColor);\n if (scene.activeCamera.mode === Camera.ORTHOGRAPHIC_CAMERA) {\n this._lineShader.setFloat(\"width\", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);\n }\n else {\n this._lineShader.setFloat(\"width\", this._source.edgesWidth / this.edgesWidthScalerForPerspective);\n }\n this._lineShader.setFloat(\"aspectRatio\", engine.getAspectRatio(scene.activeCamera));\n this._lineShader.bind(this._source.getWorldMatrix());\n // Draw order\n engine.drawElementsType(Material.TriangleFillMode, 0, this._indicesCount, instanceCount);\n this._lineShader.unbind();\n if (useBuffersWithInstances) {\n engine.unbindInstanceAttributes();\n }\n if (!this._source.getScene()._activeMeshesFrozen) {\n this.customInstances.reset();\n }\n this._lineShader._setDrawWrapper(currentDrawWrapper);\n }\n}\n/**\n * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation\n */\nexport class LineEdgesRenderer extends EdgesRenderer {\n /**\n * This constructor turns off auto generating edges line in Edges Renderer to make it here.\n * @param source LineMesh used to generate edges\n * @param epsilon not important (specified angle for edge detection)\n * @param checkVerticesInsteadOfIndices not important for LineMesh\n */\n constructor(source, epsilon = 0.95, checkVerticesInsteadOfIndices = false) {\n super(source, epsilon, checkVerticesInsteadOfIndices, false);\n this._generateEdgesLines();\n }\n /**\n * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.\n */\n _generateEdgesLines() {\n const positions = this._source.getVerticesData(VertexBuffer.PositionKind);\n const indices = this._source.getIndices();\n if (!indices || !positions) {\n return;\n }\n const p0 = TmpVectors.Vector3[0];\n const p1 = TmpVectors.Vector3[1];\n const len = indices.length - 1;\n for (let i = 0, offset = 0; i < len; i += 2, offset += 4) {\n Vector3.FromArrayToRef(positions, 3 * indices[i], p0);\n Vector3.FromArrayToRef(positions, 3 * indices[i + 1], p1);\n this.createLine(p0, p1, offset);\n }\n // Merge into a single mesh\n const engine = this._source.getScene().getEngine();\n this._buffers[VertexBuffer.PositionKind] = new VertexBuffer(engine, this._linesPositions, VertexBuffer.PositionKind, false);\n this._buffers[VertexBuffer.NormalKind] = new VertexBuffer(engine, this._linesNormals, VertexBuffer.NormalKind, false, false, 4);\n this._ib = engine.createIndexBuffer(this._linesIndices);\n this._indicesCount = this._linesIndices.length;\n }\n}\n//# sourceMappingURL=edgesRenderer.js.map","import { PrePassRenderTarget } from \"../Materials/Textures/prePassRenderTarget.js\";\n\nimport { _WarnImport } from \"../Misc/devTools.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { Material } from \"../Materials/material.js\";\nimport { GeometryBufferRenderer } from \"../Rendering/geometryBufferRenderer.js\";\n/**\n * Renders a pre pass of the scene\n * This means every mesh in the scene will be rendered to a render target texture\n * And then this texture will be composited to the rendering canvas with post processes\n * It is necessary for effects like subsurface scattering or deferred shading\n */\nexport class PrePassRenderer {\n /**\n * Returns the index of a texture in the multi render target texture array.\n * @param type Texture type\n * @returns The index\n */\n getIndex(type) {\n return this._textureIndices[type];\n }\n /**\n * How many samples are used for MSAA of the scene render target\n */\n get samples() {\n return this.defaultRT.samples;\n }\n set samples(n) {\n this.defaultRT.samples = n;\n }\n /**\n * If set to true (default: false), the depth texture will be cleared with the depth value corresponding to the far plane (1 in normal mode, 0 in reverse depth buffer mode)\n * If set to false, the depth texture is always cleared with 0.\n */\n get useSpecificClearForDepthTexture() {\n return this._useSpecificClearForDepthTexture;\n }\n set useSpecificClearForDepthTexture(value) {\n if (this._useSpecificClearForDepthTexture === value) {\n return;\n }\n this._useSpecificClearForDepthTexture = value;\n this._isDirty = true;\n }\n /**\n * @returns the prepass render target for the rendering pass.\n * If we are currently rendering a render target, it returns the PrePassRenderTarget\n * associated with that render target. Otherwise, it returns the scene default PrePassRenderTarget\n */\n getRenderTarget() {\n return this._currentTarget;\n }\n /**\n * @internal\n * Managed by the scene component\n * @param prePassRenderTarget\n */\n _setRenderTarget(prePassRenderTarget) {\n var _a, _b;\n if (prePassRenderTarget) {\n this._currentTarget = prePassRenderTarget;\n }\n else {\n this._currentTarget = this.defaultRT;\n this._engine.currentRenderPassId = (_b = (_a = this._scene.activeCamera) === null || _a === void 0 ? void 0 : _a.renderPassId) !== null && _b !== void 0 ? _b : this._currentTarget.renderPassId;\n }\n }\n /**\n * Returns true if the currently rendered prePassRenderTarget is the one\n * associated with the scene.\n */\n get currentRTisSceneRT() {\n return this._currentTarget === this.defaultRT;\n }\n _refreshGeometryBufferRendererLink() {\n if (!this.doNotUseGeometryRendererFallback) {\n this._geometryBuffer = this._scene.enableGeometryBufferRenderer();\n if (!this._geometryBuffer) {\n // Not supported\n this.doNotUseGeometryRendererFallback = true;\n return;\n }\n this._geometryBuffer._linkPrePassRenderer(this);\n }\n else {\n if (this._geometryBuffer) {\n this._geometryBuffer._unlinkPrePassRenderer();\n }\n this._geometryBuffer = null;\n this._scene.disableGeometryBufferRenderer();\n }\n }\n /**\n * Indicates if the prepass is enabled\n */\n get enabled() {\n return this._enabled;\n }\n /**\n * Instantiates a prepass renderer\n * @param scene The scene\n */\n constructor(scene) {\n /**\n * To save performance, we can excluded skinned meshes from the prepass\n */\n this.excludedSkinnedMesh = [];\n /**\n * Force material to be excluded from the prepass\n * Can be useful when `useGeometryBufferFallback` is set to `true`\n * and you don't want a material to show in the effect.\n */\n this.excludedMaterials = [];\n /**\n * Number of textures in the multi render target texture where the scene is directly rendered\n */\n this.mrtCount = 0;\n this._mrtTypes = [];\n this._mrtFormats = [];\n this._mrtLayout = [];\n this._mrtNames = [];\n this._textureIndices = [];\n this._useSpecificClearForDepthTexture = false;\n this._isDirty = true;\n /**\n * Configuration for prepass effects\n */\n this._effectConfigurations = [];\n /**\n * Prevents the PrePassRenderer from using the GeometryBufferRenderer as a fallback\n */\n this.doNotUseGeometryRendererFallback = true;\n /**\n * All the render targets generated by prepass\n */\n this.renderTargets = [];\n this._clearColor = new Color4(0, 0, 0, 0);\n this._clearDepthColor = new Color4(1e8, 0, 0, 1); // \"infinity\" value - depth in the depth texture is view.z, not a 0..1 value!\n this._enabled = false;\n this._needsCompositionForThisPass = false;\n /**\n * Set to true to disable gamma transform in PrePass.\n * Can be useful in case you already proceed to gamma transform on a material level\n * and your post processes don't need to be in linear color space.\n */\n this.disableGammaTransform = false;\n this._scene = scene;\n this._engine = scene.getEngine();\n let type = 0;\n if (this._engine._caps.textureFloat && this._engine._caps.textureFloatLinearFiltering) {\n type = 1;\n }\n else if (this._engine._caps.textureHalfFloat && this._engine._caps.textureHalfFloatLinearFiltering) {\n type = 2;\n }\n if (type !== 1) {\n for (let i = 0; i < PrePassRenderer.TextureFormats.length; ++i) {\n if (PrePassRenderer.TextureFormats[i].type === 1) {\n PrePassRenderer.TextureFormats[5].type = type;\n }\n }\n }\n PrePassRenderer._SceneComponentInitialization(this._scene);\n this.defaultRT = this._createRenderTarget(\"sceneprePassRT\", null);\n this._currentTarget = this.defaultRT;\n }\n /**\n * Creates a new PrePassRenderTarget\n * This should be the only way to instantiate a `PrePassRenderTarget`\n * @param name Name of the `PrePassRenderTarget`\n * @param renderTargetTexture RenderTarget the `PrePassRenderTarget` will be attached to.\n * Can be `null` if the created `PrePassRenderTarget` is attached to the scene (default framebuffer).\n * @internal\n */\n _createRenderTarget(name, renderTargetTexture) {\n const rt = new PrePassRenderTarget(name, renderTargetTexture, { width: this._engine.getRenderWidth(), height: this._engine.getRenderHeight() }, 0, this._scene, {\n generateMipMaps: false,\n generateStencilBuffer: this._engine.isStencilEnable,\n defaultType: 0,\n types: [],\n drawOnlyOnFirstAttachmentByDefault: true,\n });\n this.renderTargets.push(rt);\n if (this._enabled) {\n // The pre-pass renderer is already enabled, so make sure we create the render target with the correct number of textures\n this._update();\n }\n return rt;\n }\n /**\n * Indicates if rendering a prepass is supported\n */\n get isSupported() {\n return this._scene.getEngine().getCaps().drawBuffersExtension;\n }\n /**\n * Sets the proper output textures to draw in the engine.\n * @param effect The effect that is drawn. It can be or not be compatible with drawing to several output textures.\n * @param subMesh Submesh on which the effect is applied\n */\n bindAttachmentsForEffect(effect, subMesh) {\n const material = subMesh.getMaterial();\n const isPrePassCapable = material && material.isPrePassCapable;\n const excluded = material && this.excludedMaterials.indexOf(material) !== -1;\n if (this.enabled && this._currentTarget.enabled) {\n if (effect._multiTarget && isPrePassCapable && !excluded) {\n this._engine.bindAttachments(this._multiRenderAttachments);\n }\n else {\n if (this._engine._currentRenderTarget) {\n this._engine.bindAttachments(this._defaultAttachments);\n }\n else {\n this._engine.restoreSingleAttachment();\n }\n if (this._geometryBuffer && this.currentRTisSceneRT && !excluded) {\n this._geometryBuffer.renderList.push(subMesh.getRenderingMesh());\n }\n }\n }\n }\n _reinitializeAttachments() {\n const multiRenderLayout = [];\n const clearLayout = [false];\n const clearDepthLayout = [false];\n const defaultLayout = [true];\n for (let i = 0; i < this.mrtCount; i++) {\n multiRenderLayout.push(true);\n if (i > 0) {\n if (this._useSpecificClearForDepthTexture && this._mrtLayout[i] === 5) {\n clearLayout.push(false);\n clearDepthLayout.push(true);\n }\n else {\n clearLayout.push(true);\n clearDepthLayout.push(false);\n }\n defaultLayout.push(false);\n }\n }\n this._multiRenderAttachments = this._engine.buildTextureLayout(multiRenderLayout);\n this._clearAttachments = this._engine.buildTextureLayout(clearLayout);\n this._clearDepthAttachments = this._engine.buildTextureLayout(clearDepthLayout);\n this._defaultAttachments = this._engine.buildTextureLayout(defaultLayout);\n }\n _resetLayout() {\n for (let i = 0; i < PrePassRenderer.TextureFormats.length; i++) {\n this._textureIndices[PrePassRenderer.TextureFormats[i].purpose] = -1;\n }\n this._textureIndices[4] = 0;\n this._mrtLayout = [4];\n this._mrtTypes = [PrePassRenderer.TextureFormats[4].type];\n this._mrtFormats = [PrePassRenderer.TextureFormats[4].format];\n this._mrtNames = [PrePassRenderer.TextureFormats[4].name];\n this.mrtCount = 1;\n }\n _updateGeometryBufferLayout() {\n this._refreshGeometryBufferRendererLink();\n if (this._geometryBuffer) {\n this._geometryBuffer._resetLayout();\n const texturesActivated = [];\n for (let i = 0; i < this._mrtLayout.length; i++) {\n texturesActivated.push(false);\n }\n this._geometryBuffer._linkInternalTexture(this.defaultRT.getInternalTexture());\n const matches = [\n {\n prePassConstant: 5,\n geometryBufferConstant: GeometryBufferRenderer.DEPTH_TEXTURE_TYPE,\n },\n {\n prePassConstant: 6,\n geometryBufferConstant: GeometryBufferRenderer.NORMAL_TEXTURE_TYPE,\n },\n {\n prePassConstant: 1,\n geometryBufferConstant: GeometryBufferRenderer.POSITION_TEXTURE_TYPE,\n },\n {\n prePassConstant: 3,\n geometryBufferConstant: GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE,\n },\n {\n prePassConstant: 2,\n geometryBufferConstant: GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE,\n },\n ];\n // replace textures in the geometryBuffer RT\n for (let i = 0; i < matches.length; i++) {\n const index = this._mrtLayout.indexOf(matches[i].prePassConstant);\n if (index !== -1) {\n this._geometryBuffer._forceTextureType(matches[i].geometryBufferConstant, index);\n texturesActivated[index] = true;\n }\n }\n this._geometryBuffer._setAttachments(this._engine.buildTextureLayout(texturesActivated));\n }\n }\n /**\n * Restores attachments for single texture draw.\n */\n restoreAttachments() {\n if (this.enabled && this._currentTarget.enabled && this._defaultAttachments) {\n if (this._engine._currentRenderTarget) {\n this._engine.bindAttachments(this._defaultAttachments);\n }\n else {\n this._engine.restoreSingleAttachment();\n }\n }\n }\n /**\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _beforeDraw(camera, faceIndex, layer) {\n // const previousEnabled = this._enabled && this._currentTarget.enabled;\n if (this._isDirty) {\n this._update();\n }\n if (!this._enabled || !this._currentTarget.enabled) {\n return;\n }\n if (this._geometryBuffer) {\n this._geometryBuffer.renderList = [];\n }\n this._setupOutputForThisPass(this._currentTarget, camera);\n }\n _prepareFrame(prePassRenderTarget, faceIndex, layer) {\n if (prePassRenderTarget.renderTargetTexture) {\n prePassRenderTarget.renderTargetTexture._prepareFrame(this._scene, faceIndex, layer, prePassRenderTarget.renderTargetTexture.useCameraPostProcesses);\n }\n else if (this._postProcessesSourceForThisPass.length) {\n this._scene.postProcessManager._prepareFrame();\n }\n else {\n this._engine.restoreDefaultFramebuffer();\n }\n }\n /**\n * Sets an intermediary texture between prepass and postprocesses. This texture\n * will be used as input for post processes\n * @param rt\n * @returns true if there are postprocesses that will use this texture,\n * false if there is no postprocesses - and the function has no effect\n */\n setCustomOutput(rt) {\n const firstPP = this._postProcessesSourceForThisPass[0];\n if (!firstPP) {\n return false;\n }\n firstPP.inputTexture = rt.renderTarget;\n return true;\n }\n _renderPostProcesses(prePassRenderTarget, faceIndex) {\n var _a;\n const firstPP = this._postProcessesSourceForThisPass[0];\n const outputTexture = firstPP ? firstPP.inputTexture : prePassRenderTarget.renderTargetTexture ? prePassRenderTarget.renderTargetTexture.renderTarget : null;\n // Build post process chain for this prepass post draw\n let postProcessChain = this._currentTarget._beforeCompositionPostProcesses;\n if (this._needsCompositionForThisPass) {\n postProcessChain = postProcessChain.concat([this._currentTarget.imageProcessingPostProcess]);\n }\n // Activates and renders the chain\n if (postProcessChain.length) {\n this._scene.postProcessManager._prepareFrame((_a = this._currentTarget.renderTarget) === null || _a === void 0 ? void 0 : _a.texture, postProcessChain);\n this._scene.postProcessManager.directRender(postProcessChain, outputTexture, false, faceIndex);\n }\n }\n /**\n * @internal\n */\n _afterDraw(faceIndex, layer) {\n if (this._enabled && this._currentTarget.enabled) {\n this._prepareFrame(this._currentTarget, faceIndex, layer);\n this._renderPostProcesses(this._currentTarget, faceIndex);\n }\n }\n /**\n * Clears the current prepass render target (in the sense of settings pixels to the scene clear color value)\n * @internal\n */\n _clear() {\n if (this._enabled && this._currentTarget.enabled) {\n this._bindFrameBuffer(this._currentTarget);\n // Clearing other attachment with 0 on all other attachments\n this._engine.bindAttachments(this._clearAttachments);\n this._engine.clear(this._clearColor, true, false, false);\n if (this._useSpecificClearForDepthTexture) {\n this._engine.bindAttachments(this._clearDepthAttachments);\n this._engine.clear(this._clearDepthColor, true, false, false);\n }\n // Regular clear color with the scene clear color of the 1st attachment\n this._engine.bindAttachments(this._defaultAttachments);\n }\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _bindFrameBuffer(prePassRenderTarget) {\n if (this._enabled && this._currentTarget.enabled) {\n this._currentTarget._checkSize();\n const internalTexture = this._currentTarget.renderTarget;\n if (internalTexture) {\n this._engine.bindFramebuffer(internalTexture);\n }\n }\n }\n _setEnabled(enabled) {\n this._enabled = enabled;\n }\n _setRenderTargetEnabled(prePassRenderTarget, enabled) {\n prePassRenderTarget.enabled = enabled;\n if (!enabled) {\n this._unlinkInternalTexture(prePassRenderTarget);\n }\n }\n /**\n * Adds an effect configuration to the prepass render target.\n * If an effect has already been added, it won't add it twice and will return the configuration\n * already present.\n * @param cfg the effect configuration\n * @returns the effect configuration now used by the prepass\n */\n addEffectConfiguration(cfg) {\n // Do not add twice\n for (let i = 0; i < this._effectConfigurations.length; i++) {\n if (this._effectConfigurations[i].name === cfg.name) {\n return this._effectConfigurations[i];\n }\n }\n this._effectConfigurations.push(cfg);\n return cfg;\n }\n _enable() {\n const previousMrtCount = this.mrtCount;\n for (let i = 0; i < this._effectConfigurations.length; i++) {\n if (this._effectConfigurations[i].enabled) {\n this._enableTextures(this._effectConfigurations[i].texturesRequired);\n }\n }\n for (let i = 0; i < this.renderTargets.length; i++) {\n if (this.mrtCount !== previousMrtCount || this.renderTargets[i].count !== this.mrtCount) {\n this.renderTargets[i].updateCount(this.mrtCount, { types: this._mrtTypes, formats: this._mrtFormats }, this._mrtNames.concat(\"prePass_DepthBuffer\"));\n }\n this.renderTargets[i]._resetPostProcessChain();\n for (let j = 0; j < this._effectConfigurations.length; j++) {\n if (this._effectConfigurations[j].enabled) {\n // TODO : subsurface scattering has 1 scene-wide effect configuration\n // solution : do not stock postProcess on effectConfiguration, but in the prepassRenderTarget (hashmap configuration => postProcess)\n // And call createPostProcess whenever the post process does not exist in the RT\n if (!this._effectConfigurations[j].postProcess && this._effectConfigurations[j].createPostProcess) {\n this._effectConfigurations[j].createPostProcess();\n }\n if (this._effectConfigurations[j].postProcess) {\n this.renderTargets[i]._beforeCompositionPostProcesses.push(this._effectConfigurations[j].postProcess);\n }\n }\n }\n }\n this._reinitializeAttachments();\n this._setEnabled(true);\n this._updateGeometryBufferLayout();\n }\n _disable() {\n this._setEnabled(false);\n for (let i = 0; i < this.renderTargets.length; i++) {\n this._setRenderTargetEnabled(this.renderTargets[i], false);\n }\n this._resetLayout();\n for (let i = 0; i < this._effectConfigurations.length; i++) {\n this._effectConfigurations[i].enabled = false;\n }\n }\n _getPostProcessesSource(prePassRenderTarget, camera) {\n if (camera) {\n return camera._postProcesses;\n }\n else if (prePassRenderTarget.renderTargetTexture) {\n if (prePassRenderTarget.renderTargetTexture.useCameraPostProcesses) {\n const camera = prePassRenderTarget.renderTargetTexture.activeCamera ? prePassRenderTarget.renderTargetTexture.activeCamera : this._scene.activeCamera;\n return camera ? camera._postProcesses : [];\n }\n else if (prePassRenderTarget.renderTargetTexture.postProcesses) {\n return prePassRenderTarget.renderTargetTexture.postProcesses;\n }\n else {\n return [];\n }\n }\n else {\n return this._scene.activeCamera ? this._scene.activeCamera._postProcesses : [];\n }\n }\n _setupOutputForThisPass(prePassRenderTarget, camera) {\n // Order is : draw ===> prePassRenderTarget._postProcesses ==> ipp ==> camera._postProcesses\n const secondaryCamera = camera && this._scene.activeCameras && !!this._scene.activeCameras.length && this._scene.activeCameras.indexOf(camera) !== 0;\n this._postProcessesSourceForThisPass = this._getPostProcessesSource(prePassRenderTarget, camera);\n this._postProcessesSourceForThisPass = this._postProcessesSourceForThisPass.filter((pp) => {\n return pp != null;\n });\n this._scene.autoClear = true;\n const cameraHasImageProcessing = this._hasImageProcessing(this._postProcessesSourceForThisPass);\n this._needsCompositionForThisPass = !cameraHasImageProcessing && !this.disableGammaTransform && this._needsImageProcessing() && !secondaryCamera;\n const firstCameraPP = this._getFirstPostProcess(this._postProcessesSourceForThisPass);\n const firstPrePassPP = prePassRenderTarget._beforeCompositionPostProcesses && prePassRenderTarget._beforeCompositionPostProcesses[0];\n let firstPP = null;\n // Setting the scene-wide post process configuration\n this._scene.imageProcessingConfiguration.applyByPostProcess = this._needsCompositionForThisPass || cameraHasImageProcessing;\n // Create composition effect if needed\n if (this._needsCompositionForThisPass && !prePassRenderTarget.imageProcessingPostProcess) {\n prePassRenderTarget._createCompositionEffect();\n }\n // Setting the prePassRenderTarget as input texture of the first PP\n if (firstPrePassPP) {\n firstPP = firstPrePassPP;\n }\n else if (this._needsCompositionForThisPass) {\n firstPP = prePassRenderTarget.imageProcessingPostProcess;\n }\n else if (firstCameraPP) {\n firstPP = firstCameraPP;\n }\n this._bindFrameBuffer(prePassRenderTarget);\n this._linkInternalTexture(prePassRenderTarget, firstPP);\n }\n _linkInternalTexture(prePassRenderTarget, postProcess) {\n if (postProcess) {\n postProcess.autoClear = false;\n postProcess.inputTexture = prePassRenderTarget.renderTarget;\n }\n if (prePassRenderTarget._outputPostProcess !== postProcess) {\n if (prePassRenderTarget._outputPostProcess) {\n this._unlinkInternalTexture(prePassRenderTarget);\n }\n prePassRenderTarget._outputPostProcess = postProcess;\n }\n if (prePassRenderTarget._internalTextureDirty) {\n this._updateGeometryBufferLayout();\n prePassRenderTarget._internalTextureDirty = false;\n }\n }\n /**\n * @internal\n */\n _unlinkInternalTexture(prePassRenderTarget) {\n if (prePassRenderTarget._outputPostProcess) {\n prePassRenderTarget._outputPostProcess.autoClear = true;\n prePassRenderTarget._outputPostProcess.restoreDefaultInputTexture();\n prePassRenderTarget._outputPostProcess = null;\n }\n }\n _needsImageProcessing() {\n for (let i = 0; i < this._effectConfigurations.length; i++) {\n if (this._effectConfigurations[i].enabled && this._effectConfigurations[i].needsImageProcessing) {\n return true;\n }\n }\n return false;\n }\n _hasImageProcessing(postProcesses) {\n var _a;\n let isIPPAlreadyPresent = false;\n if (postProcesses) {\n for (let i = 0; i < postProcesses.length; i++) {\n if (((_a = postProcesses[i]) === null || _a === void 0 ? void 0 : _a.getClassName()) === \"ImageProcessingPostProcess\") {\n isIPPAlreadyPresent = true;\n break;\n }\n }\n }\n return isIPPAlreadyPresent;\n }\n /**\n * Internal, gets the first post proces.\n * @param postProcesses\n * @returns the first post process to be run on this camera.\n */\n _getFirstPostProcess(postProcesses) {\n for (let ppIndex = 0; ppIndex < postProcesses.length; ppIndex++) {\n if (postProcesses[ppIndex] !== null) {\n return postProcesses[ppIndex];\n }\n }\n return null;\n }\n /**\n * Marks the prepass renderer as dirty, triggering a check if the prepass is necessary for the next rendering.\n */\n markAsDirty() {\n this._isDirty = true;\n }\n /**\n * Enables a texture on the MultiRenderTarget for prepass\n * @param types\n */\n _enableTextures(types) {\n // For velocity : enable storage of previous matrices for instances\n this._scene.needsPreviousWorldMatrices = false;\n for (let i = 0; i < types.length; i++) {\n const type = types[i];\n if (this._textureIndices[type] === -1) {\n this._textureIndices[type] = this._mrtLayout.length;\n this._mrtLayout.push(type);\n this._mrtTypes.push(PrePassRenderer.TextureFormats[type].type);\n this._mrtFormats.push(PrePassRenderer.TextureFormats[type].format);\n this._mrtNames.push(PrePassRenderer.TextureFormats[type].name);\n this.mrtCount++;\n }\n if (type === 2) {\n this._scene.needsPreviousWorldMatrices = true;\n }\n }\n }\n /**\n * Makes sure that the prepass renderer is up to date if it has been dirtified.\n */\n update() {\n if (this._isDirty) {\n this._update();\n }\n }\n _update() {\n this._disable();\n let enablePrePass = false;\n this._scene.imageProcessingConfiguration.applyByPostProcess = false;\n if (this._scene._depthPeelingRenderer && this._scene.useOrderIndependentTransparency) {\n this._scene._depthPeelingRenderer.setPrePassRenderer(this);\n enablePrePass = true;\n }\n for (let i = 0; i < this._scene.materials.length; i++) {\n if (this._scene.materials[i].setPrePassRenderer(this)) {\n enablePrePass = true;\n }\n }\n if (enablePrePass) {\n this._setRenderTargetEnabled(this.defaultRT, true);\n }\n let postProcesses;\n for (let i = 0; i < this.renderTargets.length; i++) {\n if (this.renderTargets[i].renderTargetTexture) {\n postProcesses = this._getPostProcessesSource(this.renderTargets[i]);\n }\n else {\n const camera = this._scene.activeCamera;\n if (!camera) {\n continue;\n }\n postProcesses = camera._postProcesses;\n }\n if (!postProcesses) {\n continue;\n }\n postProcesses = postProcesses.filter((pp) => {\n return pp != null;\n });\n if (postProcesses) {\n for (let j = 0; j < postProcesses.length; j++) {\n if (postProcesses[j].setPrePassRenderer(this)) {\n this._setRenderTargetEnabled(this.renderTargets[i], true);\n enablePrePass = true;\n }\n }\n if (this._hasImageProcessing(postProcesses)) {\n this._scene.imageProcessingConfiguration.applyByPostProcess = true;\n }\n }\n }\n this._markAllMaterialsAsPrePassDirty();\n this._isDirty = false;\n if (enablePrePass) {\n this._enable();\n }\n }\n _markAllMaterialsAsPrePassDirty() {\n const materials = this._scene.materials;\n for (let i = 0; i < materials.length; i++) {\n materials[i].markAsDirty(Material.PrePassDirtyFlag);\n }\n }\n /**\n * Disposes the prepass renderer.\n */\n dispose() {\n for (let i = this.renderTargets.length - 1; i >= 0; i--) {\n this.renderTargets[i].dispose();\n }\n for (let i = 0; i < this._effectConfigurations.length; i++) {\n if (this._effectConfigurations[i].dispose) {\n this._effectConfigurations[i].dispose();\n }\n }\n }\n}\n/**\n * @internal\n */\nPrePassRenderer._SceneComponentInitialization = (_) => {\n throw _WarnImport(\"PrePassRendererSceneComponent\");\n};\n/**\n * Describes the types and formats of the textures used by the pre-pass renderer\n */\nPrePassRenderer.TextureFormats = [\n {\n purpose: 0,\n type: 2,\n format: 5,\n name: \"prePass_Irradiance\",\n },\n {\n purpose: 1,\n type: 2,\n format: 5,\n name: \"prePass_Position\",\n },\n {\n purpose: 2,\n type: 0,\n format: 5,\n name: \"prePass_Velocity\",\n },\n {\n purpose: 3,\n type: 0,\n format: 5,\n name: \"prePass_Reflectivity\",\n },\n {\n purpose: 4,\n type: 2,\n format: 5,\n name: \"prePass_Color\",\n },\n {\n purpose: 5,\n type: 1,\n format: 6,\n name: \"prePass_Depth\",\n },\n {\n purpose: 6,\n type: 2,\n format: 5,\n name: \"prePass_Normal\",\n },\n {\n purpose: 7,\n type: 0,\n format: 5,\n name: \"prePass_Albedo\",\n },\n];\n//# sourceMappingURL=prePassRenderer.js.map","import { Scene } from \"../scene.js\";\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { PrePassRenderer } from \"./prePassRenderer.js\";\nimport { Logger } from \"../Misc/logger.js\";\nObject.defineProperty(Scene.prototype, \"prePassRenderer\", {\n get: function () {\n return this._prePassRenderer;\n },\n set: function (value) {\n if (value && value.isSupported) {\n this._prePassRenderer = value;\n }\n },\n enumerable: true,\n configurable: true,\n});\nScene.prototype.enablePrePassRenderer = function () {\n if (this._prePassRenderer) {\n return this._prePassRenderer;\n }\n this._prePassRenderer = new PrePassRenderer(this);\n if (!this._prePassRenderer.isSupported) {\n this._prePassRenderer = null;\n Logger.Error(\"PrePassRenderer needs WebGL 2 support.\\n\" + \"Maybe you tried to use the following features that need the PrePassRenderer :\\n\" + \" + Subsurface Scattering\");\n }\n return this._prePassRenderer;\n};\nScene.prototype.disablePrePassRenderer = function () {\n if (!this._prePassRenderer) {\n return;\n }\n this._prePassRenderer.dispose();\n this._prePassRenderer = null;\n};\n/**\n * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful\n * in several rendering techniques.\n */\nexport class PrePassRendererSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpful to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_PREPASSRENDERER;\n this.scene = scene;\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene._beforeCameraDrawStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERADRAW_PREPASS, this, this._beforeCameraDraw);\n this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_PREPASS, this, this._afterCameraDraw);\n this.scene._beforeRenderTargetDrawStage.registerStep(SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_PREPASS, this, this._beforeRenderTargetDraw);\n this.scene._afterRenderTargetDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_PREPASS, this, this._afterRenderTargetDraw);\n this.scene._beforeClearStage.registerStep(SceneComponentConstants.STEP_BEFORECLEAR_PREPASS, this, this._beforeClearStage);\n this.scene._beforeRenderTargetClearStage.registerStep(SceneComponentConstants.STEP_BEFORERENDERTARGETCLEAR_PREPASS, this, this._beforeRenderTargetClearStage);\n this.scene._beforeRenderingMeshStage.registerStep(SceneComponentConstants.STEP_BEFORERENDERINGMESH_PREPASS, this, this._beforeRenderingMeshStage);\n this.scene._afterRenderingMeshStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERINGMESH_PREPASS, this, this._afterRenderingMeshStage);\n }\n _beforeRenderTargetDraw(renderTarget, faceIndex, layer) {\n if (this.scene.prePassRenderer && !renderTarget.noPrePassRenderer) {\n this.scene.prePassRenderer._setRenderTarget(renderTarget._prePassRenderTarget);\n this.scene.prePassRenderer._beforeDraw(undefined, faceIndex, layer);\n }\n }\n _afterRenderTargetDraw(renderTarget, faceIndex, layer) {\n if (this.scene.prePassRenderer && !renderTarget.noPrePassRenderer) {\n this.scene.prePassRenderer._afterDraw(faceIndex, layer);\n }\n }\n _beforeRenderTargetClearStage(renderTarget) {\n if (this.scene.prePassRenderer && !renderTarget.noPrePassRenderer) {\n if (!renderTarget._prePassRenderTarget) {\n renderTarget._prePassRenderTarget = this.scene.prePassRenderer._createRenderTarget(renderTarget.name + \"_prePassRTT\", renderTarget);\n }\n this.scene.prePassRenderer._setRenderTarget(renderTarget._prePassRenderTarget);\n this.scene.prePassRenderer._clear();\n }\n }\n _beforeCameraDraw(camera) {\n if (this.scene.prePassRenderer) {\n this.scene.prePassRenderer._setRenderTarget(null);\n this.scene.prePassRenderer._beforeDraw(camera);\n }\n }\n _afterCameraDraw() {\n if (this.scene.prePassRenderer) {\n this.scene.prePassRenderer._afterDraw();\n }\n }\n _beforeClearStage() {\n if (this.scene.prePassRenderer) {\n this.scene.prePassRenderer._setRenderTarget(null);\n this.scene.prePassRenderer._clear();\n }\n }\n _beforeRenderingMeshStage(mesh, subMesh, batch, effect) {\n if (!effect) {\n return;\n }\n // Render to MRT\n const scene = mesh.getScene();\n if (scene.prePassRenderer) {\n scene.prePassRenderer.bindAttachmentsForEffect(effect, subMesh);\n }\n }\n _afterRenderingMeshStage(mesh) {\n const scene = mesh.getScene();\n if (scene.prePassRenderer) {\n scene.prePassRenderer.restoreAttachments();\n }\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n // Release textures first\n this.scene.disablePrePassRenderer();\n // Re-enable\n this.scene.enablePrePassRenderer();\n }\n /**\n * Disposes the component and the associated resources\n */\n dispose() {\n this.scene.disablePrePassRenderer();\n }\n}\nPrePassRenderer._SceneComponentInitialization = (scene) => {\n // Register the G Buffer component to the scene.\n let component = scene._getComponent(SceneComponentConstants.NAME_PREPASSRENDERER);\n if (!component) {\n component = new PrePassRendererSceneComponent(scene);\n scene._addComponent(component);\n }\n};\n//# sourceMappingURL=prePassRendererSceneComponent.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"fibonacci\";\nconst shader = `#define rcp(x) 1./x\n#define GOLDEN_RATIO 1.618033988749895\n#define TWO_PI 6.2831855\nvec2 Golden2dSeq(int i,float n)\r{\rreturn vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));\r}\rvec2 SampleDiskGolden(int i,int sampleCount)\r{\rvec2 f=Golden2dSeq(i,float(sampleCount));\rreturn vec2(sqrt(f.x),TWO_PI*f.y);\r}`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const fibonacci = { name, shader };\n//# sourceMappingURL=fibonacci.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"diffusionProfile\";\nconst shader = `uniform vec3 diffusionS[5];\runiform float diffusionD[5];\runiform float filterRadii[5];`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const diffusionProfile = { name, shader };\n//# sourceMappingURL=diffusionProfile.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/fibonacci.js\";\nimport \"./ShadersInclude/helperFunctions.js\";\nimport \"./ShadersInclude/subSurfaceScatteringFunctions.js\";\nimport \"./ShadersInclude/diffusionProfile.js\";\nconst name = \"subSurfaceScatteringPixelShader\";\nconst shader = `#include\n#include\n#include\n#include\nvarying vec2 vUV;\runiform vec2 texelSize;\runiform sampler2D textureSampler;\runiform sampler2D irradianceSampler;\runiform sampler2D depthSampler;\runiform sampler2D albedoSampler;\runiform vec2 viewportSize;\runiform float metersPerUnit;\rconst float LOG2_E=1.4426950408889634;\rconst float SSS_PIXELS_PER_SAMPLE=4.;\rconst int _SssSampleBudget=40;\r#define rcp(x) 1./x\n#define Sq(x) x*x\n#define SSS_BILATERAL_FILTER true\nvec3 EvalBurleyDiffusionProfile(float r,vec3 S)\r{\rvec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); \rvec3 expSum=exp_13*(1.+exp_13*exp_13); \rreturn (S*rcp(8.*PI))*expSum; \r}\rvec2 SampleBurleyDiffusionProfile(float u,float rcpS)\r{\ru=1.-u; \rfloat g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));\rfloat n=exp2(log2(g)*(-1.0/3.0)); \rfloat p=(g*n)*n; \rfloat c=1.+p+n; \rfloat d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); \rfloat x=(3./LOG2_E)*log2(c)-d; \rfloat rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));\rfloat r=x*rcpS;\rfloat rcpPdf=(8.*PI*rcpS)*rcpExp; \rreturn vec2(r,rcpPdf);\r}\rvec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf)\r{\r#ifndef SSS_BILATERAL_FILTER\nz=0.;\r#endif\nfloat r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));\rfloat area=rcpPdf;\r#if SSS_CLAMP_ARTIFACT\nreturn clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0);\r#else\nreturn EvalBurleyDiffusionProfile(r,S)*area;\r#endif\n}\rvoid EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm,\rfloat phase,inout vec3 totalIrradiance,inout vec3 totalWeight)\r{\rfloat scale =rcp(float(n));\rfloat offset=rcp(float(n))*0.5;\rfloat sinPhase,cosPhase;\rsinPhase=sin(phase);\rcosPhase=cos(phase);\rvec2 bdp=SampleBurleyDiffusionProfile(float(i)*scale+offset,d);\rfloat r=bdp.x;\rfloat rcpPdf=bdp.y;\rfloat phi=SampleDiskGolden(i,n).y;\rfloat sinPhi,cosPhi;\rsinPhi=sin(phi);\rcosPhi=cos(phi);\rfloat sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; \rfloat cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; \rvec2 vec=r*vec2(cosPsi,sinPsi);\rvec2 position; \rfloat xy2;\rposition=vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*texelSize;\rxy2 =r*r;\rvec4 textureSample=texture2D(irradianceSampler,position);\rfloat viewZ=texture2D(depthSampler,position).r;\rvec3 irradiance =textureSample.rgb;\rif (testLightingForSSS(textureSample.a))\r{\rfloat relZ=viewZ-centerPosVS.z;\rvec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);\rtotalIrradiance+=weight*irradiance;\rtotalWeight +=weight;\r}\relse\r{\r}\r}\r#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \r{\rvec4 irradianceAndDiffusionProfile =texture2D(irradianceSampler,vUV);\rvec3 centerIrradiance=irradianceAndDiffusionProfile.rgb;\rint diffusionProfileIndex=int(round(irradianceAndDiffusionProfile.a*255.));\rfloat centerDepth =0.;\rvec4 inputColor=texture2D(textureSampler,vUV);\rbool passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);\rif (passedStencilTest)\r{\rcenterDepth=texture2D(depthSampler,vUV).r;\r}\rif (!passedStencilTest) { \rgl_FragColor=inputColor;\rreturn;\r}\rfloat distScale =1.;\rvec3 S =diffusionS[diffusionProfileIndex];\rfloat d =diffusionD[diffusionProfileIndex];\rfloat filterRadius=filterRadii[diffusionProfileIndex];\rvec2 centerPosNDC=vUV;\rvec2 cornerPosNDC=vUV+0.5*texelSize;\rvec3 centerPosVS =vec3(centerPosNDC*viewportSize,1.0)*centerDepth; \rvec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; \rfloat mmPerUnit =1000.*(metersPerUnit*rcp(distScale));\rfloat unitsPerMm=rcp(mmPerUnit);\rfloat unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);\rfloat pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;\rfloat filterArea =PI*Sq(filterRadius*pixelsPerMm);\rint sampleCount =int(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));\rint sampleBudget=_SssSampleBudget;\rint texturingMode=0;\rvec3 albedo =texture2D(albedoSampler,vUV).rgb;\rif (distScale==0. || sampleCount<1)\r{\r#ifdef DEBUG_SSS_SAMPLES\nvec3 green=vec3(0.,1.,0.);\rgl_FragColor=vec4(green,1.0);\rreturn;\r#endif\ngl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);\rreturn;\r}\r#ifdef DEBUG_SSS_SAMPLES\nvec3 red =vec3(1.,0.,0.);\rvec3 blue=vec3(0.,0.,1.);\rgl_FragColor=vec4(mix(blue,red,clamp(float(sampleCount)/float(sampleBudget),0.0,1.0)),1.0);\rreturn;\r#endif\nfloat phase=0.;\rint n=min(sampleCount,sampleBudget);\rvec3 centerWeight =vec3(0.); \rvec3 totalIrradiance=vec3(0.);\rvec3 totalWeight =vec3(0.);\rfor (int i=0; i {\n if (!scene.prePassRenderer || !scene.subSurfaceConfiguration) {\n Logger.Error(\"PrePass and subsurface configuration needs to be enabled for subsurface scattering.\");\n return;\n }\n const texelSize = this.texelSize;\n effect.setFloat(\"metersPerUnit\", scene.subSurfaceConfiguration.metersPerUnit);\n effect.setFloat2(\"texelSize\", texelSize.x, texelSize.y);\n effect.setTexture(\"irradianceSampler\", scene.prePassRenderer.getRenderTarget().textures[scene.prePassRenderer.getIndex(0)]);\n effect.setTexture(\"depthSampler\", scene.prePassRenderer.getRenderTarget().textures[scene.prePassRenderer.getIndex(5)]);\n effect.setTexture(\"albedoSampler\", scene.prePassRenderer.getRenderTarget().textures[scene.prePassRenderer.getIndex(7)]);\n effect.setFloat2(\"viewportSize\", Math.tan(scene.activeCamera.fov / 2) * scene.getEngine().getAspectRatio(scene.activeCamera, true), Math.tan(scene.activeCamera.fov / 2));\n effect.setArray3(\"diffusionS\", scene.subSurfaceConfiguration.ssDiffusionS);\n effect.setArray(\"diffusionD\", scene.subSurfaceConfiguration.ssDiffusionD);\n effect.setArray(\"filterRadii\", scene.subSurfaceConfiguration.ssFilterRadii);\n });\n }\n}\n//# sourceMappingURL=subSurfaceScatteringPostProcess.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { SubSurfaceScatteringPostProcess } from \"../PostProcesses/subSurfaceScatteringPostProcess.js\";\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { _WarnImport } from \"../Misc/devTools.js\";\n\n/**\n * Contains all parameters needed for the prepass to perform\n * screen space subsurface scattering\n */\nexport class SubSurfaceConfiguration {\n /**\n * Diffusion profile color for subsurface scattering\n */\n get ssDiffusionS() {\n return this._ssDiffusionS;\n }\n /**\n * Diffusion profile max color channel value for subsurface scattering\n */\n get ssDiffusionD() {\n return this._ssDiffusionD;\n }\n /**\n * Diffusion profile filter radius for subsurface scattering\n */\n get ssFilterRadii() {\n return this._ssFilterRadii;\n }\n /**\n * Builds a subsurface configuration object\n * @param scene The scene\n */\n constructor(scene) {\n this._ssDiffusionS = [];\n this._ssFilterRadii = [];\n this._ssDiffusionD = [];\n /**\n * Is subsurface enabled\n */\n this.enabled = false;\n /**\n * Does the output of this prepass need to go through imageprocessing\n */\n this.needsImageProcessing = true;\n /**\n * Name of the configuration\n */\n this.name = SceneComponentConstants.NAME_SUBSURFACE;\n /**\n * Diffusion profile colors for subsurface scattering\n * You can add one diffusion color using `addDiffusionProfile` on `scene.prePassRenderer`\n * See ...\n * Note that you can only store up to 5 of them\n */\n this.ssDiffusionProfileColors = [];\n /**\n * Defines the ratio real world => scene units.\n * Used for subsurface scattering\n */\n this.metersPerUnit = 1;\n /**\n * Textures that should be present in the MRT for this effect to work\n */\n this.texturesRequired = [\n 5,\n 7,\n 4,\n 0,\n ];\n // Adding default diffusion profile\n this.addDiffusionProfile(new Color3(1, 1, 1));\n this._scene = scene;\n SubSurfaceConfiguration._SceneComponentInitialization(this._scene);\n }\n /**\n * Adds a new diffusion profile.\n * Useful for more realistic subsurface scattering on diverse materials.\n * @param color The color of the diffusion profile. Should be the average color of the material.\n * @returns The index of the diffusion profile for the material subsurface configuration\n */\n addDiffusionProfile(color) {\n if (this.ssDiffusionD.length >= 5) {\n // We only suppport 5 diffusion profiles\n Logger.Error(\"You already reached the maximum number of diffusion profiles.\");\n return 0; // default profile\n }\n // Do not add doubles\n for (let i = 0; i < this._ssDiffusionS.length / 3; i++) {\n if (this._ssDiffusionS[i * 3] === color.r && this._ssDiffusionS[i * 3 + 1] === color.g && this._ssDiffusionS[i * 3 + 2] === color.b) {\n return i;\n }\n }\n this._ssDiffusionS.push(color.r, color.b, color.g);\n this._ssDiffusionD.push(Math.max(Math.max(color.r, color.b), color.g));\n this._ssFilterRadii.push(this.getDiffusionProfileParameters(color));\n this.ssDiffusionProfileColors.push(color);\n return this._ssDiffusionD.length - 1;\n }\n /**\n * Creates the sss post process\n * @returns The created post process\n */\n createPostProcess() {\n this.postProcess = new SubSurfaceScatteringPostProcess(\"subSurfaceScattering\", this._scene, 1, null, undefined, this._scene.getEngine());\n this.postProcess.autoClear = false;\n return this.postProcess;\n }\n /**\n * Deletes all diffusion profiles.\n * Note that in order to render subsurface scattering, you should have at least 1 diffusion profile.\n */\n clearAllDiffusionProfiles() {\n this._ssDiffusionD = [];\n this._ssDiffusionS = [];\n this._ssFilterRadii = [];\n this.ssDiffusionProfileColors = [];\n }\n /**\n * Disposes this object\n */\n dispose() {\n this.clearAllDiffusionProfiles();\n if (this.postProcess) {\n this.postProcess.dispose();\n }\n }\n /**\n * @internal\n * https://zero-radiance.github.io/post/sampling-diffusion/\n *\n * Importance sample the normalized diffuse reflectance profile for the computed value of 's'.\n * ------------------------------------------------------------------------------------\n * R[r, phi, s] = s * (Exp[-r * s] + Exp[-r * s / 3]) / (8 * Pi * r)\n * PDF[r, phi, s] = r * R[r, phi, s]\n * CDF[r, s] = 1 - 1/4 * Exp[-r * s] - 3/4 * Exp[-r * s / 3]\n * ------------------------------------------------------------------------------------\n * We importance sample the color channel with the widest scattering distance.\n */\n getDiffusionProfileParameters(color) {\n const cdf = 0.997;\n const maxScatteringDistance = Math.max(color.r, color.g, color.b);\n return this._sampleBurleyDiffusionProfile(cdf, maxScatteringDistance);\n }\n /**\n * Performs sampling of a Normalized Burley diffusion profile in polar coordinates.\n * 'u' is the random number (the value of the CDF): [0, 1).\n * rcp(s) = 1 / ShapeParam = ScatteringDistance.\n * Returns the sampled radial distance, s.t. (u = 0 -> r = 0) and (u = 1 -> r = Inf).\n * @param u\n * @param rcpS\n */\n _sampleBurleyDiffusionProfile(u, rcpS) {\n u = 1 - u; // Convert CDF to CCDF\n const g = 1 + 4 * u * (2 * u + Math.sqrt(1 + 4 * u * u));\n const n = Math.pow(g, -1.0 / 3.0); // g^(-1/3)\n const p = g * n * n; // g^(+1/3)\n const c = 1 + p + n; // 1 + g^(+1/3) + g^(-1/3)\n const x = 3 * Math.log(c / (4 * u));\n return x * rcpS;\n }\n}\n/**\n * @internal\n */\nSubSurfaceConfiguration._SceneComponentInitialization = (_) => {\n throw _WarnImport(\"SubSurfaceSceneComponent\");\n};\n//# sourceMappingURL=subSurfaceConfiguration.js.map","import { Scene } from \"../scene.js\";\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { SubSurfaceConfiguration } from \"./subSurfaceConfiguration.js\";\nimport { AbstractScene } from \"../abstractScene.js\";\nimport { Color3 } from \"../Maths/math.color.js\";\n// Adds the parser to the scene parsers.\nAbstractScene.AddParser(SceneComponentConstants.NAME_SUBSURFACE, (parsedData, scene) => {\n // Diffusion profiles\n if (parsedData.ssDiffusionProfileColors !== undefined && parsedData.ssDiffusionProfileColors !== null) {\n scene.enableSubSurfaceForPrePass();\n if (scene.subSurfaceConfiguration) {\n for (let index = 0, cache = parsedData.ssDiffusionProfileColors.length; index < cache; index++) {\n const color = parsedData.ssDiffusionProfileColors[index];\n scene.subSurfaceConfiguration.addDiffusionProfile(new Color3(color.r, color.g, color.b));\n }\n }\n }\n});\nObject.defineProperty(Scene.prototype, \"subSurfaceConfiguration\", {\n get: function () {\n return this._subSurfaceConfiguration;\n },\n set: function (value) {\n if (value) {\n if (this.enablePrePassRenderer()) {\n this._subSurfaceConfiguration = value;\n }\n }\n },\n enumerable: true,\n configurable: true,\n});\nScene.prototype.enableSubSurfaceForPrePass = function () {\n if (this._subSurfaceConfiguration) {\n return this._subSurfaceConfiguration;\n }\n const prePassRenderer = this.enablePrePassRenderer();\n if (prePassRenderer) {\n this._subSurfaceConfiguration = new SubSurfaceConfiguration(this);\n prePassRenderer.addEffectConfiguration(this._subSurfaceConfiguration);\n return this._subSurfaceConfiguration;\n }\n return null;\n};\nScene.prototype.disableSubSurfaceForPrePass = function () {\n if (!this._subSurfaceConfiguration) {\n return;\n }\n this._subSurfaceConfiguration.dispose();\n this._subSurfaceConfiguration = null;\n};\n/**\n * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful\n * in several rendering techniques.\n */\nexport class SubSurfaceSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpful to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_PREPASSRENDERER;\n this.scene = scene;\n }\n /**\n * Registers the component in a given scene\n */\n register() { }\n /**\n * Serializes the component data to the specified json object\n * @param serializationObject The object to serialize to\n */\n serialize(serializationObject) {\n if (!this.scene.subSurfaceConfiguration) {\n return;\n }\n const ssDiffusionProfileColors = this.scene.subSurfaceConfiguration.ssDiffusionProfileColors;\n serializationObject.ssDiffusionProfileColors = [];\n for (let i = 0; i < ssDiffusionProfileColors.length; i++) {\n serializationObject.ssDiffusionProfileColors.push({\n r: ssDiffusionProfileColors[i].r,\n g: ssDiffusionProfileColors[i].g,\n b: ssDiffusionProfileColors[i].b,\n });\n }\n }\n /**\n * Adds all the elements from the container to the scene\n */\n addFromContainer() {\n // Nothing to do\n }\n /**\n * Removes all the elements in the container from the scene\n */\n removeFromContainer() {\n // Make sure nothing will be serialized\n if (!this.scene.prePassRenderer) {\n return;\n }\n if (this.scene.subSurfaceConfiguration) {\n this.scene.subSurfaceConfiguration.clearAllDiffusionProfiles();\n }\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n // Nothing to do for this component\n }\n /**\n * Disposes the component and the associated resources\n */\n dispose() {\n // Nothing to do for this component\n }\n}\nSubSurfaceConfiguration._SceneComponentInitialization = (scene) => {\n // Register the G Buffer component to the scene.\n let component = scene._getComponent(SceneComponentConstants.NAME_SUBSURFACE);\n if (!component) {\n component = new SubSurfaceSceneComponent(scene);\n scene._addComponent(component);\n }\n};\n//# sourceMappingURL=subSurfaceSceneComponent.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/clipPlaneFragmentDeclaration.js\";\nimport \"./ShadersInclude/logDepthDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneFragment.js\";\nimport \"./ShadersInclude/logDepthFragment.js\";\nconst name = \"outlinePixelShader\";\nconst shader = `#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\r#ifdef ALPHATEST\nvarying vec2 vUV;\runiform sampler2D diffuseSampler;\r#endif\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\rdiscard;\r#endif\n#include\ngl_FragColor=color;\r#define CUSTOM_FRAGMENT_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const outlinePixelShader = { name, shader };\n//# sourceMappingURL=outline.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/bonesDeclaration.js\";\nimport \"./ShadersInclude/bakedVertexAnimationDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexGlobalDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexDeclaration.js\";\nimport \"./ShadersInclude/clipPlaneVertexDeclaration.js\";\nimport \"./ShadersInclude/instancesDeclaration.js\";\nimport \"./ShadersInclude/logDepthDeclaration.js\";\nimport \"./ShadersInclude/morphTargetsVertexGlobal.js\";\nimport \"./ShadersInclude/morphTargetsVertex.js\";\nimport \"./ShadersInclude/instancesVertex.js\";\nimport \"./ShadersInclude/bonesVertex.js\";\nimport \"./ShadersInclude/bakedVertexAnimation.js\";\nimport \"./ShadersInclude/clipPlaneVertex.js\";\nimport \"./ShadersInclude/logDepthVertex.js\";\nconst name = \"outlineVertexShader\";\nconst shader = `attribute vec3 position;\rattribute vec3 normal;\r#include\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n#include\nuniform float offset;\r#include\nuniform mat4 viewProjection;\r#ifdef ALPHATEST\nvarying vec2 vUV;\runiform mat4 diffuseMatrix;\r#ifdef UV1\nattribute vec2 uv;\r#endif\n#ifdef UV2\nattribute vec2 uv2;\r#endif\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void)\r{\rvec3 positionUpdated=position;\rvec3 normalUpdated=normal;\r#ifdef UV1\nvec2 uvUpdated=uv;\r#endif\n#include\n#include[0..maxSimultaneousMorphTargets]\nvec3 offsetPosition=positionUpdated+(normalUpdated*offset);\r#include\n#include\n#include\nvec4 worldPos=finalWorld*vec4(offsetPosition,1.0);\rgl_Position=viewProjection*worldPos;\r#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0));\r#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\r#endif\n#endif\n#include\n#include\n}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const outlineVertexShader = { name, shader };\n//# sourceMappingURL=outline.vertex.js.map","import { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { Scene } from \"../scene.js\";\n\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { DrawWrapper } from \"../Materials/drawWrapper.js\";\nimport { MaterialHelper } from \"../Materials/materialHelper.js\";\nimport \"../Shaders/outline.fragment.js\";\nimport \"../Shaders/outline.vertex.js\";\nimport { addClipPlaneUniforms, bindClipPlane, prepareStringDefinesForClipPlanes } from \"../Materials/clipPlaneMaterialHelper.js\";\n/**\n * Gets the outline renderer associated with the scene\n * @returns a OutlineRenderer\n */\nScene.prototype.getOutlineRenderer = function () {\n if (!this._outlineRenderer) {\n this._outlineRenderer = new OutlineRenderer(this);\n }\n return this._outlineRenderer;\n};\nObject.defineProperty(Mesh.prototype, \"renderOutline\", {\n get: function () {\n return this._renderOutline;\n },\n set: function (value) {\n if (value) {\n // Lazy Load the component.\n this.getScene().getOutlineRenderer();\n }\n this._renderOutline = value;\n },\n enumerable: true,\n configurable: true,\n});\nObject.defineProperty(Mesh.prototype, \"renderOverlay\", {\n get: function () {\n return this._renderOverlay;\n },\n set: function (value) {\n if (value) {\n // Lazy Load the component.\n this.getScene().getOutlineRenderer();\n }\n this._renderOverlay = value;\n },\n enumerable: true,\n configurable: true,\n});\n/**\n * This class is responsible to draw the outline/overlay of meshes.\n * It should not be used directly but through the available method on mesh.\n */\nexport class OutlineRenderer {\n /**\n * Instantiates a new outline renderer. (There could be only one per scene).\n * @param scene Defines the scene it belongs to\n */\n constructor(scene) {\n /**\n * The name of the component. Each component must have a unique name.\n */\n this.name = SceneComponentConstants.NAME_OUTLINERENDERER;\n /**\n * Defines a zOffset default Factor to prevent zFighting between the overlay and the mesh.\n */\n this.zOffset = 1;\n /**\n * Defines a zOffset default Unit to prevent zFighting between the overlay and the mesh.\n */\n this.zOffsetUnits = 4; // 4 to account for projection a bit by default\n this.scene = scene;\n this._engine = scene.getEngine();\n this.scene._addComponent(this);\n this._passIdForDrawWrapper = [];\n for (let i = 0; i < 4; ++i) {\n this._passIdForDrawWrapper[i] = this._engine.createRenderPassId(`Outline Renderer (${i})`);\n }\n }\n /**\n * Register the component to one instance of a scene.\n */\n register() {\n this.scene._beforeRenderingMeshStage.registerStep(SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);\n this.scene._afterRenderingMeshStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n // Nothing to do here.\n }\n /**\n * Disposes the component and the associated resources.\n */\n dispose() {\n for (let i = 0; i < this._passIdForDrawWrapper.length; ++i) {\n this._engine.releaseRenderPassId(this._passIdForDrawWrapper[i]);\n }\n }\n /**\n * Renders the outline in the canvas.\n * @param subMesh Defines the sumesh to render\n * @param batch Defines the batch of meshes in case of instances\n * @param useOverlay Defines if the rendering is for the overlay or the outline\n * @param renderPassId Render pass id to use to render the mesh\n */\n render(subMesh, batch, useOverlay = false, renderPassId) {\n renderPassId = renderPassId !== null && renderPassId !== void 0 ? renderPassId : this._passIdForDrawWrapper[0];\n const scene = this.scene;\n const engine = scene.getEngine();\n const hardwareInstancedRendering = engine.getCaps().instancedArrays &&\n ((batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined) || subMesh.getRenderingMesh().hasThinInstances);\n if (!this.isReady(subMesh, hardwareInstancedRendering, renderPassId)) {\n return;\n }\n const ownerMesh = subMesh.getMesh();\n const replacementMesh = ownerMesh._internalAbstractMeshDataInfo._actAsRegularMesh ? ownerMesh : null;\n const renderingMesh = subMesh.getRenderingMesh();\n const effectiveMesh = replacementMesh ? replacementMesh : renderingMesh;\n const material = subMesh.getMaterial();\n if (!material || !scene.activeCamera) {\n return;\n }\n const drawWrapper = subMesh._getDrawWrapper(renderPassId);\n const effect = DrawWrapper.GetEffect(drawWrapper);\n engine.enableEffect(drawWrapper);\n // Logarithmic depth\n if (material.useLogarithmicDepth) {\n effect.setFloat(\"logarithmicDepthConstant\", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));\n }\n effect.setFloat(\"offset\", useOverlay ? 0 : renderingMesh.outlineWidth);\n effect.setColor4(\"color\", useOverlay ? renderingMesh.overlayColor : renderingMesh.outlineColor, useOverlay ? renderingMesh.overlayAlpha : material.alpha);\n effect.setMatrix(\"viewProjection\", scene.getTransformMatrix());\n effect.setMatrix(\"world\", effectiveMesh.getWorldMatrix());\n // Bones\n if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) {\n effect.setMatrices(\"mBones\", renderingMesh.skeleton.getTransformMatrices(renderingMesh));\n }\n if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) {\n renderingMesh.morphTargetManager._bind(effect);\n }\n // Morph targets\n MaterialHelper.BindMorphTargetParameters(renderingMesh, effect);\n if (!hardwareInstancedRendering) {\n renderingMesh._bind(subMesh, effect, material.fillMode);\n }\n // Alpha test\n if (material && material.needAlphaTesting()) {\n const alphaTexture = material.getAlphaTestTexture();\n if (alphaTexture) {\n effect.setTexture(\"diffuseSampler\", alphaTexture);\n effect.setMatrix(\"diffuseMatrix\", alphaTexture.getTextureMatrix());\n }\n }\n // Clip plane\n bindClipPlane(effect, material, scene);\n engine.setZOffset(-this.zOffset);\n engine.setZOffsetUnits(-this.zOffsetUnits);\n renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, world) => {\n effect.setMatrix(\"world\", world);\n });\n engine.setZOffset(0);\n engine.setZOffsetUnits(0);\n }\n /**\n * Returns whether or not the outline renderer is ready for a given submesh.\n * All the dependencies e.g. submeshes, texture, effect... mus be ready\n * @param subMesh Defines the submesh to check readiness for\n * @param useInstances Defines whether wee are trying to render instances or not\n * @param renderPassId Render pass id to use to render the mesh\n * @returns true if ready otherwise false\n */\n isReady(subMesh, useInstances, renderPassId) {\n renderPassId = renderPassId !== null && renderPassId !== void 0 ? renderPassId : this._passIdForDrawWrapper[0];\n const defines = [];\n const attribs = [VertexBuffer.PositionKind, VertexBuffer.NormalKind];\n const mesh = subMesh.getMesh();\n const material = subMesh.getMaterial();\n if (!material) {\n return false;\n }\n const scene = mesh.getScene();\n // Alpha test\n if (material.needAlphaTesting()) {\n defines.push(\"#define ALPHATEST\");\n if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {\n attribs.push(VertexBuffer.UVKind);\n defines.push(\"#define UV1\");\n }\n if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) {\n attribs.push(VertexBuffer.UV2Kind);\n defines.push(\"#define UV2\");\n }\n }\n //Logarithmic depth\n if (material.useLogarithmicDepth) {\n defines.push(\"#define LOGARITHMICDEPTH\");\n }\n // Clip planes\n prepareStringDefinesForClipPlanes(material, scene, defines);\n // Bones\n if (mesh.useBones && mesh.computeBonesUsingShaders) {\n attribs.push(VertexBuffer.MatricesIndicesKind);\n attribs.push(VertexBuffer.MatricesWeightsKind);\n if (mesh.numBoneInfluencers > 4) {\n attribs.push(VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(VertexBuffer.MatricesWeightsExtraKind);\n }\n defines.push(\"#define NUM_BONE_INFLUENCERS \" + mesh.numBoneInfluencers);\n defines.push(\"#define BonesPerMesh \" + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));\n }\n else {\n defines.push(\"#define NUM_BONE_INFLUENCERS 0\");\n }\n // Morph targets\n const morphTargetManager = mesh.morphTargetManager;\n let numMorphInfluencers = 0;\n if (morphTargetManager) {\n if (morphTargetManager.numInfluencers > 0) {\n numMorphInfluencers = morphTargetManager.numInfluencers;\n defines.push(\"#define MORPHTARGETS\");\n defines.push(\"#define NUM_MORPH_INFLUENCERS \" + numMorphInfluencers);\n if (morphTargetManager.isUsingTextureForTargets) {\n defines.push(\"#define MORPHTARGETS_TEXTURE\");\n }\n MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, numMorphInfluencers);\n }\n }\n // Instances\n if (useInstances) {\n defines.push(\"#define INSTANCES\");\n MaterialHelper.PushAttributesForInstances(attribs);\n if (subMesh.getRenderingMesh().hasThinInstances) {\n defines.push(\"#define THIN_INSTANCES\");\n }\n }\n // Get correct effect\n const drawWrapper = subMesh._getDrawWrapper(renderPassId, true);\n const cachedDefines = drawWrapper.defines;\n const join = defines.join(\"\\n\");\n if (cachedDefines !== join) {\n const uniforms = [\n \"world\",\n \"mBones\",\n \"viewProjection\",\n \"diffuseMatrix\",\n \"offset\",\n \"color\",\n \"logarithmicDepthConstant\",\n \"morphTargetInfluences\",\n \"morphTargetTextureInfo\",\n \"morphTargetTextureIndices\",\n ];\n addClipPlaneUniforms(uniforms);\n drawWrapper.setEffect(this.scene.getEngine().createEffect(\"outline\", attribs, uniforms, [\"diffuseSampler\", \"morphTargets\"], join, undefined, undefined, undefined, {\n maxSimultaneousMorphTargets: numMorphInfluencers,\n }), join);\n }\n return drawWrapper.effect.isReady();\n }\n _beforeRenderingMesh(mesh, subMesh, batch) {\n // Outline - step 1\n this._savedDepthWrite = this._engine.getDepthWrite();\n if (mesh.renderOutline) {\n const material = subMesh.getMaterial();\n if (material && material.needAlphaBlendingForMesh(mesh)) {\n this._engine.cacheStencilState();\n // Draw only to stencil buffer for the original mesh\n // The resulting stencil buffer will be used so the outline is not visible inside the mesh when the mesh is transparent\n this._engine.setDepthWrite(false);\n this._engine.setColorWrite(false);\n this._engine.setStencilBuffer(true);\n this._engine.setStencilOperationPass(7681);\n this._engine.setStencilFunction(519);\n this._engine.setStencilMask(OutlineRenderer._StencilReference);\n this._engine.setStencilFunctionReference(OutlineRenderer._StencilReference);\n this._engine.stencilStateComposer.useStencilGlobalOnly = true;\n this.render(subMesh, batch, /* This sets offset to 0 */ true, this._passIdForDrawWrapper[1]);\n this._engine.setColorWrite(true);\n this._engine.setStencilFunction(517);\n }\n // Draw the outline using the above stencil if needed to avoid drawing within the mesh\n this._engine.setDepthWrite(false);\n this.render(subMesh, batch, false, this._passIdForDrawWrapper[0]);\n this._engine.setDepthWrite(this._savedDepthWrite);\n if (material && material.needAlphaBlendingForMesh(mesh)) {\n this._engine.stencilStateComposer.useStencilGlobalOnly = false;\n this._engine.restoreStencilState();\n }\n }\n }\n _afterRenderingMesh(mesh, subMesh, batch) {\n // Overlay\n if (mesh.renderOverlay) {\n const currentMode = this._engine.getAlphaMode();\n const alphaBlendState = this._engine.alphaState.alphaBlend;\n this._engine.setAlphaMode(2);\n this.render(subMesh, batch, true, this._passIdForDrawWrapper[3]);\n this._engine.setAlphaMode(currentMode);\n this._engine.setDepthWrite(this._savedDepthWrite);\n this._engine.alphaState.alphaBlend = alphaBlendState;\n }\n // Outline - step 2\n if (mesh.renderOutline && this._savedDepthWrite) {\n this._engine.setDepthWrite(true);\n this._engine.setColorWrite(false);\n this.render(subMesh, batch, false, this._passIdForDrawWrapper[2]);\n this._engine.setColorWrite(true);\n }\n }\n}\n/**\n * Stencil value used to avoid outline being seen within the mesh when the mesh is transparent\n */\nOutlineRenderer._StencilReference = 0x04;\n//# sourceMappingURL=outlineRenderer.js.map","\nimport { EffectWrapper } from \"../../Materials/effectRenderer.js\";\nimport { Observable } from \"../../Misc/observable.js\";\n/**\n * Defines the base object used for fluid rendering.\n * It is based on a list of vertices (particles)\n */\nexport class FluidRenderingObject {\n /** Gets or sets the size of the particle */\n get particleSize() {\n return this._particleSize;\n }\n set particleSize(size) {\n if (size === this._particleSize) {\n return;\n }\n this._particleSize = size;\n this.onParticleSizeChanged.notifyObservers(this);\n }\n /** Indicates if the object uses instancing or not */\n get useInstancing() {\n return !this.indexBuffer;\n }\n /** Indicates if velocity of particles should be used when rendering the object. The vertex buffer set must contain a \"velocity\" buffer for this to work! */\n get useVelocity() {\n return this._useVelocity;\n }\n set useVelocity(use) {\n if (this._useVelocity === use || !this._hasVelocity()) {\n return;\n }\n this._useVelocity = use;\n this._effectsAreDirty = true;\n }\n _hasVelocity() {\n var _a;\n return !!((_a = this.vertexBuffers) === null || _a === void 0 ? void 0 : _a.velocity);\n }\n /**\n * Gets the index buffer (or null if the object is using instancing)\n */\n get indexBuffer() {\n return null;\n }\n /**\n * Gets the name of the class\n */\n getClassName() {\n return \"FluidRenderingObject\";\n }\n /**\n * Instantiates a fluid rendering object\n * @param scene The scene the object is part of\n */\n constructor(scene) {\n /** Defines the priority of the object. Objects will be rendered in ascending order of priority */\n this.priority = 0;\n this._particleSize = 0.1;\n /** Observable triggered when the size of the particle is changed */\n this.onParticleSizeChanged = new Observable();\n /** Defines the alpha value of a particle */\n this.particleThicknessAlpha = 0.05;\n this._useVelocity = false;\n this._scene = scene;\n this._engine = scene.getEngine();\n this._effectsAreDirty = true;\n this._depthEffectWrapper = null;\n this._thicknessEffectWrapper = null;\n }\n _createEffects() {\n const uniformNames = [\"view\", \"projection\", \"particleRadius\", \"size\"];\n const attributeNames = [\"position\", \"offset\"];\n const defines = [];\n this._effectsAreDirty = false;\n if (this.useVelocity) {\n attributeNames.push(\"velocity\");\n defines.push(\"#define FLUIDRENDERING_VELOCITY\");\n }\n if (this._scene.useRightHandedSystem) {\n defines.push(\"#define FLUIDRENDERING_RHS\");\n }\n this._depthEffectWrapper = new EffectWrapper({\n engine: this._engine,\n useShaderStore: true,\n vertexShader: \"fluidRenderingParticleDepth\",\n fragmentShader: \"fluidRenderingParticleDepth\",\n attributeNames,\n uniformNames,\n samplerNames: [],\n defines,\n });\n uniformNames.push(\"particleAlpha\");\n this._thicknessEffectWrapper = new EffectWrapper({\n engine: this._engine,\n useShaderStore: true,\n vertexShader: \"fluidRenderingParticleThickness\",\n fragmentShader: \"fluidRenderingParticleThickness\",\n attributeNames: [\"position\", \"offset\"],\n uniformNames,\n samplerNames: [],\n });\n }\n /**\n * Indicates if the object is ready to be rendered\n * @returns True if everything is ready for the object to be rendered, otherwise false\n */\n isReady() {\n if (this._effectsAreDirty) {\n this._createEffects();\n }\n if (!this._depthEffectWrapper || !this._thicknessEffectWrapper) {\n return false;\n }\n const depthEffect = this._depthEffectWrapper._drawWrapper.effect;\n const thicknessEffect = this._thicknessEffectWrapper._drawWrapper.effect;\n return depthEffect.isReady() && thicknessEffect.isReady();\n }\n /**\n * Render the depth texture for this object\n */\n renderDepthTexture() {\n const numParticles = this.numParticles;\n if (!this._depthEffectWrapper || numParticles === 0) {\n return;\n }\n const depthDrawWrapper = this._depthEffectWrapper._drawWrapper;\n const depthEffect = depthDrawWrapper.effect;\n this._engine.enableEffect(depthDrawWrapper);\n this._engine.bindBuffers(this.vertexBuffers, this.indexBuffer, depthEffect);\n depthEffect.setMatrix(\"view\", this._scene.getViewMatrix());\n depthEffect.setMatrix(\"projection\", this._scene.getProjectionMatrix());\n depthEffect.setFloat2(\"size\", this._particleSize, this._particleSize);\n depthEffect.setFloat(\"particleRadius\", this._particleSize / 2);\n if (this.useInstancing) {\n this._engine.drawArraysType(7, 0, 4, numParticles);\n }\n else {\n this._engine.drawElementsType(0, 0, numParticles);\n }\n }\n /**\n * Render the thickness texture for this object\n */\n renderThicknessTexture() {\n const numParticles = this.numParticles;\n if (!this._thicknessEffectWrapper || numParticles === 0) {\n return;\n }\n const thicknessDrawWrapper = this._thicknessEffectWrapper._drawWrapper;\n const thicknessEffect = thicknessDrawWrapper.effect;\n this._engine.setAlphaMode(6);\n this._engine.setDepthWrite(false);\n this._engine.enableEffect(thicknessDrawWrapper);\n this._engine.bindBuffers(this.vertexBuffers, this.indexBuffer, thicknessEffect);\n thicknessEffect.setMatrix(\"view\", this._scene.getViewMatrix());\n thicknessEffect.setMatrix(\"projection\", this._scene.getProjectionMatrix());\n thicknessEffect.setFloat(\"particleAlpha\", this.particleThicknessAlpha);\n thicknessEffect.setFloat2(\"size\", this._particleSize, this._particleSize);\n if (this.useInstancing) {\n this._engine.drawArraysType(7, 0, 4, numParticles);\n }\n else {\n this._engine.drawElementsType(0, 0, numParticles);\n }\n this._engine.setDepthWrite(true);\n this._engine.setAlphaMode(0);\n }\n /**\n * Render the diffuse texture for this object\n */\n renderDiffuseTexture() {\n // do nothing by default\n }\n /**\n * Releases the ressources used by the class\n */\n dispose() {\n var _a, _b;\n (_a = this._depthEffectWrapper) === null || _a === void 0 ? void 0 : _a.dispose();\n (_b = this._thicknessEffectWrapper) === null || _b === void 0 ? void 0 : _b.dispose();\n }\n}\n//# sourceMappingURL=fluidRenderingObject.js.map","\nimport { Texture } from \"../../Materials/Textures/texture.js\";\nimport { Vector2 } from \"../../Maths/math.vector.js\";\nimport { PostProcess } from \"../../PostProcesses/postProcess.js\";\nimport { Observable } from \"../../Misc/observable.js\";\n/** @internal */\nexport class FluidRenderingTextures {\n get blurNumIterations() {\n return this._blurNumIterations;\n }\n set blurNumIterations(numIterations) {\n if (this._blurNumIterations === numIterations) {\n return;\n }\n this._blurNumIterations = numIterations;\n if (this._blurPostProcesses !== null) {\n const blurX = this._blurPostProcesses[0];\n const blurY = this._blurPostProcesses[1];\n this._blurPostProcesses = [];\n for (let i = 0; i < this._blurNumIterations * 2; ++i) {\n this._blurPostProcesses[i] = i & 1 ? blurY : blurX;\n }\n }\n }\n get renderTarget() {\n return this._rt;\n }\n get renderTargetBlur() {\n return this._rtBlur;\n }\n get texture() {\n return this._texture;\n }\n get textureBlur() {\n return this._textureBlurred;\n }\n constructor(name, scene, width, height, blurTextureSizeX, blurTextureSizeY, textureType = 1, textureFormat = 6, blurTextureType = 1, blurTextureFormat = 6, useStandardBlur = false, camera = null, generateDepthBuffer = true, samples = 1) {\n this.enableBlur = true;\n this.blurSizeDivisor = 1;\n this.blurFilterSize = 7;\n this._blurNumIterations = 3;\n this.blurMaxFilterSize = 100;\n this.blurDepthScale = 10;\n this.particleSize = 0.02;\n this.onDisposeObservable = new Observable();\n this._name = name;\n this._scene = scene;\n this._camera = camera;\n this._engine = scene.getEngine();\n this._width = width;\n this._height = height;\n this._blurTextureSizeX = blurTextureSizeX;\n this._blurTextureSizeY = blurTextureSizeY;\n this._textureType = textureType;\n this._textureFormat = textureFormat;\n this._blurTextureType = blurTextureType;\n this._blurTextureFormat = blurTextureFormat;\n this._useStandardBlur = useStandardBlur;\n this._generateDepthBuffer = generateDepthBuffer;\n this._samples = samples;\n this._postProcessRunningIndex = 0;\n this.enableBlur = blurTextureSizeX !== 0 && blurTextureSizeY !== 0;\n this._rt = null;\n this._texture = null;\n this._rtBlur = null;\n this._textureBlurred = null;\n this._blurPostProcesses = null;\n }\n initialize() {\n this.dispose();\n this._createRenderTarget();\n if (this.enableBlur && this._texture) {\n const [rtBlur, textureBlurred, blurPostProcesses] = this._createBlurPostProcesses(this._texture, this._blurTextureType, this._blurTextureFormat, this.blurSizeDivisor, this._name, this._useStandardBlur);\n this._rtBlur = rtBlur;\n this._textureBlurred = textureBlurred;\n this._blurPostProcesses = blurPostProcesses;\n }\n }\n applyBlurPostProcesses() {\n if (this.enableBlur && this._blurPostProcesses) {\n this._postProcessRunningIndex = 0;\n this._scene.postProcessManager.directRender(this._blurPostProcesses, this._rtBlur, true);\n this._engine.unBindFramebuffer(this._rtBlur);\n }\n }\n _createRenderTarget() {\n this._rt = this._engine.createRenderTargetTexture({ width: this._width, height: this._height }, {\n generateMipMaps: false,\n type: this._textureType,\n format: this._textureFormat,\n samplingMode: 1,\n generateDepthBuffer: this._generateDepthBuffer,\n generateStencilBuffer: false,\n samples: this._samples,\n label: `FluidRenderingRTT-${this._name}`,\n });\n const renderTexture = this._rt.texture;\n renderTexture.incrementReferences();\n this._texture = new Texture(null, this._scene);\n this._texture.name = \"rtt\" + this._name;\n this._texture._texture = renderTexture;\n this._texture.wrapU = Texture.CLAMP_ADDRESSMODE;\n this._texture.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._texture.anisotropicFilteringLevel = 1;\n }\n _createBlurPostProcesses(textureBlurSource, textureType, textureFormat, blurSizeDivisor, debugName, useStandardBlur = false) {\n const engine = this._scene.getEngine();\n const targetSize = new Vector2(Math.floor(this._blurTextureSizeX / blurSizeDivisor), Math.floor(this._blurTextureSizeY / blurSizeDivisor));\n const useBilinearFiltering = (textureType === 1 && engine.getCaps().textureFloatLinearFiltering) ||\n (textureType === 2 && engine.getCaps().textureHalfFloatLinearFiltering);\n const rtBlur = this._engine.createRenderTargetTexture({ width: targetSize.x, height: targetSize.y }, {\n generateMipMaps: false,\n type: textureType,\n format: textureFormat,\n samplingMode: useBilinearFiltering ? 2 : 1,\n generateDepthBuffer: false,\n generateStencilBuffer: false,\n samples: this._samples,\n label: `FluidRenderingRTTBlur-${debugName}`,\n });\n const renderTexture = rtBlur.texture;\n renderTexture.incrementReferences();\n const texture = new Texture(null, this._scene);\n texture.name = \"rttBlurred\" + debugName;\n texture._texture = renderTexture;\n texture.wrapU = Texture.CLAMP_ADDRESSMODE;\n texture.wrapV = Texture.CLAMP_ADDRESSMODE;\n texture.anisotropicFilteringLevel = 1;\n if (useStandardBlur) {\n const kernelBlurXPostprocess = new PostProcess(\"BilateralBlurX\", \"fluidRenderingStandardBlur\", [\"filterSize\", \"blurDir\"], null, 1, null, 1, engine, true, null, textureType, undefined, undefined, undefined, textureFormat);\n kernelBlurXPostprocess.samples = this._samples;\n kernelBlurXPostprocess.externalTextureSamplerBinding = true;\n kernelBlurXPostprocess.onApplyObservable.add((effect) => {\n if (this._postProcessRunningIndex === 0) {\n effect.setTexture(\"textureSampler\", textureBlurSource);\n }\n else {\n effect._bindTexture(\"textureSampler\", kernelBlurXPostprocess.inputTexture.texture);\n }\n effect.setInt(\"filterSize\", this.blurFilterSize);\n effect.setFloat2(\"blurDir\", 1 / this._blurTextureSizeX, 0);\n this._postProcessRunningIndex++;\n });\n kernelBlurXPostprocess.onSizeChangedObservable.add(() => {\n kernelBlurXPostprocess._textures.forEach((rt) => {\n rt.texture.wrapU = Texture.CLAMP_ADDRESSMODE;\n rt.texture.wrapV = Texture.CLAMP_ADDRESSMODE;\n });\n });\n this._fixReusablePostProcess(kernelBlurXPostprocess);\n const kernelBlurYPostprocess = new PostProcess(\"BilateralBlurY\", \"fluidRenderingStandardBlur\", [\"filterSize\", \"blurDir\"], null, 1, null, 1, engine, true, null, textureType, undefined, undefined, undefined, textureFormat);\n kernelBlurYPostprocess.samples = this._samples;\n kernelBlurYPostprocess.onApplyObservable.add((effect) => {\n effect.setInt(\"filterSize\", this.blurFilterSize);\n effect.setFloat2(\"blurDir\", 0, 1 / this._blurTextureSizeY);\n this._postProcessRunningIndex++;\n });\n kernelBlurYPostprocess.onSizeChangedObservable.add(() => {\n kernelBlurYPostprocess._textures.forEach((rt) => {\n rt.texture.wrapU = Texture.CLAMP_ADDRESSMODE;\n rt.texture.wrapV = Texture.CLAMP_ADDRESSMODE;\n });\n });\n this._fixReusablePostProcess(kernelBlurYPostprocess);\n kernelBlurXPostprocess.autoClear = false;\n kernelBlurYPostprocess.autoClear = false;\n const blurList = [];\n for (let i = 0; i < this._blurNumIterations * 2; ++i) {\n blurList[i] = i & 1 ? kernelBlurYPostprocess : kernelBlurXPostprocess;\n }\n return [rtBlur, texture, blurList];\n }\n else {\n const uniforms = [\"maxFilterSize\", \"blurDir\", \"projectedParticleConstant\", \"depthThreshold\"];\n const kernelBlurXPostprocess = new PostProcess(\"BilateralBlurX\", \"fluidRenderingBilateralBlur\", uniforms, null, 1, null, 1, engine, true, null, textureType, undefined, undefined, undefined, textureFormat);\n kernelBlurXPostprocess.samples = this._samples;\n kernelBlurXPostprocess.externalTextureSamplerBinding = true;\n kernelBlurXPostprocess.onApplyObservable.add((effect) => {\n if (this._postProcessRunningIndex === 0) {\n effect.setTexture(\"textureSampler\", textureBlurSource);\n }\n else {\n effect._bindTexture(\"textureSampler\", kernelBlurXPostprocess.inputTexture.texture);\n }\n effect.setInt(\"maxFilterSize\", this.blurMaxFilterSize);\n effect.setFloat2(\"blurDir\", 1 / this._blurTextureSizeX, 0);\n effect.setFloat(\"projectedParticleConstant\", this._getProjectedParticleConstant());\n effect.setFloat(\"depthThreshold\", this._getDepthThreshold());\n this._postProcessRunningIndex++;\n });\n kernelBlurXPostprocess.onSizeChangedObservable.add(() => {\n kernelBlurXPostprocess._textures.forEach((rt) => {\n rt.texture.wrapU = Texture.CLAMP_ADDRESSMODE;\n rt.texture.wrapV = Texture.CLAMP_ADDRESSMODE;\n });\n });\n this._fixReusablePostProcess(kernelBlurXPostprocess);\n const kernelBlurYPostprocess = new PostProcess(\"BilateralBlurY\", \"fluidRenderingBilateralBlur\", uniforms, null, 1, null, 1, engine, true, null, textureType, undefined, undefined, undefined, textureFormat);\n kernelBlurYPostprocess.samples = this._samples;\n kernelBlurYPostprocess.onApplyObservable.add((effect) => {\n effect.setInt(\"maxFilterSize\", this.blurMaxFilterSize);\n effect.setFloat2(\"blurDir\", 0, 1 / this._blurTextureSizeY);\n effect.setFloat(\"projectedParticleConstant\", this._getProjectedParticleConstant());\n effect.setFloat(\"depthThreshold\", this._getDepthThreshold());\n this._postProcessRunningIndex++;\n });\n kernelBlurYPostprocess.onSizeChangedObservable.add(() => {\n kernelBlurYPostprocess._textures.forEach((rt) => {\n rt.texture.wrapU = Texture.CLAMP_ADDRESSMODE;\n rt.texture.wrapV = Texture.CLAMP_ADDRESSMODE;\n });\n });\n this._fixReusablePostProcess(kernelBlurYPostprocess);\n kernelBlurXPostprocess.autoClear = false;\n kernelBlurYPostprocess.autoClear = false;\n const blurList = [];\n for (let i = 0; i < this._blurNumIterations * 2; ++i) {\n blurList[i] = i & 1 ? kernelBlurYPostprocess : kernelBlurXPostprocess;\n }\n return [rtBlur, texture, blurList];\n }\n }\n _fixReusablePostProcess(pp) {\n if (!pp.isReusable()) {\n return;\n }\n pp.onActivateObservable.add(() => {\n // undo what calling activate() does which will make sure we will retrieve the right texture when getting the input for the post process\n pp._currentRenderTextureInd = (pp._currentRenderTextureInd + 1) % 2;\n });\n pp.onApplyObservable.add(() => {\n // now we can advance to the next texture\n pp._currentRenderTextureInd = (pp._currentRenderTextureInd + 1) % 2;\n });\n }\n _getProjectedParticleConstant() {\n var _a, _b;\n return (this.blurFilterSize * this.particleSize * 0.05 * (this._height / 2)) / Math.tan(((_b = (_a = this._camera) === null || _a === void 0 ? void 0 : _a.fov) !== null && _b !== void 0 ? _b : (45 * Math.PI) / 180) / 2);\n }\n _getDepthThreshold() {\n return (this.particleSize / 2) * this.blurDepthScale;\n }\n dispose() {\n var _a, _b, _c, _d;\n if (this.onDisposeObservable.hasObservers()) {\n this.onDisposeObservable.notifyObservers(this);\n }\n (_a = this._rt) === null || _a === void 0 ? void 0 : _a.dispose();\n this._rt = null;\n (_b = this._texture) === null || _b === void 0 ? void 0 : _b.dispose();\n this._texture = null;\n (_c = this._rtBlur) === null || _c === void 0 ? void 0 : _c.dispose();\n this._rtBlur = null;\n (_d = this._textureBlurred) === null || _d === void 0 ? void 0 : _d.dispose();\n this._textureBlurred = null;\n if (this._blurPostProcesses) {\n this._blurPostProcesses[0].dispose();\n this._blurPostProcesses[1].dispose();\n }\n this._blurPostProcesses = null;\n }\n}\n//# sourceMappingURL=fluidRenderingTextures.js.map","\nimport { Color3, Color4 } from \"../../Maths/math.color.js\";\nimport { Matrix, Vector2, Vector3 } from \"../../Maths/math.vector.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { PostProcess } from \"../../PostProcesses/postProcess.js\";\nimport { FluidRenderingTextures } from \"./fluidRenderingTextures.js\";\n/**\n * Textures that can be displayed as a debugging tool\n */\nexport var FluidRenderingDebug;\n(function (FluidRenderingDebug) {\n FluidRenderingDebug[FluidRenderingDebug[\"DepthTexture\"] = 0] = \"DepthTexture\";\n FluidRenderingDebug[FluidRenderingDebug[\"DepthBlurredTexture\"] = 1] = \"DepthBlurredTexture\";\n FluidRenderingDebug[FluidRenderingDebug[\"ThicknessTexture\"] = 2] = \"ThicknessTexture\";\n FluidRenderingDebug[FluidRenderingDebug[\"ThicknessBlurredTexture\"] = 3] = \"ThicknessBlurredTexture\";\n FluidRenderingDebug[FluidRenderingDebug[\"DiffuseTexture\"] = 4] = \"DiffuseTexture\";\n FluidRenderingDebug[FluidRenderingDebug[\"Normals\"] = 5] = \"Normals\";\n FluidRenderingDebug[FluidRenderingDebug[\"DiffuseRendering\"] = 6] = \"DiffuseRendering\";\n})(FluidRenderingDebug || (FluidRenderingDebug = {}));\n/**\n * Class used to render an object as a fluid thanks to different render target textures (depth, thickness, diffuse)\n */\nexport class FluidRenderingTargetRenderer {\n /**\n * Returns true if the class needs to be reinitialized (because of changes in parameterization)\n */\n get needInitialization() {\n return this._needInitialization;\n }\n /**\n * Gets or sets a boolean indicating that the diffuse texture should be generated and used for the rendering\n */\n get generateDiffuseTexture() {\n return this._generateDiffuseTexture;\n }\n set generateDiffuseTexture(generate) {\n if (this._generateDiffuseTexture === generate) {\n return;\n }\n this._generateDiffuseTexture = generate;\n this._needInitialization = true;\n }\n /**\n * Gets or sets the feature (texture) to be debugged. Not used if debug is false\n */\n get debugFeature() {\n return this._debugFeature;\n }\n set debugFeature(feature) {\n if (this._debugFeature === feature) {\n return;\n }\n this._needInitialization = true;\n this._debugFeature = feature;\n }\n /**\n * Gets or sets a boolean indicating if we should display a specific texture (given by debugFeature) for debugging purpose\n */\n get debug() {\n return this._debug;\n }\n set debug(debug) {\n if (this._debug === debug) {\n return;\n }\n this._debug = debug;\n this._needInitialization = true;\n }\n /**\n * Gets or sets the environment map used for the reflection part of the shading\n * If null, no map will be used. If undefined, the scene.environmentMap will be used (if defined)\n */\n get environmentMap() {\n return this._environmentMap;\n }\n set environmentMap(map) {\n if (this._environmentMap === map) {\n return;\n }\n this._needInitialization = true;\n this._environmentMap = map;\n }\n /**\n * Gets or sets a boolean indicating that the depth texture should be blurred\n */\n get enableBlurDepth() {\n return this._enableBlurDepth;\n }\n set enableBlurDepth(enable) {\n if (this._enableBlurDepth === enable) {\n return;\n }\n this._enableBlurDepth = enable;\n this._needInitialization = true;\n }\n /**\n * Gets or sets the depth size divisor (positive number, generally between 1 and 4), which is used as a divisor when creating the texture used for blurring the depth\n * For eg. if blurDepthSizeDivisor=2, the texture used to blur the depth will be half the size of the depth texture\n */\n get blurDepthSizeDivisor() {\n return this._blurDepthSizeDivisor;\n }\n set blurDepthSizeDivisor(scale) {\n if (this._blurDepthSizeDivisor === scale) {\n return;\n }\n this._blurDepthSizeDivisor = scale;\n this._needInitialization = true;\n }\n /**\n * Size of the kernel used to filter the depth blur texture (positive number, generally between 1 and 20 - higher values will require more processing power from the GPU)\n */\n get blurDepthFilterSize() {\n return this._blurDepthFilterSize;\n }\n set blurDepthFilterSize(filterSize) {\n if (this._blurDepthFilterSize === filterSize) {\n return;\n }\n this._blurDepthFilterSize = filterSize;\n this._setBlurParameters();\n }\n /**\n * Number of blurring iterations used to generate the depth blur texture (positive number, generally between 1 and 10 - higher values will require more processing power from the GPU)\n */\n get blurDepthNumIterations() {\n return this._blurDepthNumIterations;\n }\n set blurDepthNumIterations(numIterations) {\n if (this._blurDepthNumIterations === numIterations) {\n return;\n }\n this._blurDepthNumIterations = numIterations;\n this._setBlurParameters();\n }\n /**\n * Maximum size of the kernel used to blur the depth texture (positive number, generally between 1 and 200 - higher values will require more processing power from the GPU when the particles are larger on screen)\n */\n get blurDepthMaxFilterSize() {\n return this._blurDepthMaxFilterSize;\n }\n set blurDepthMaxFilterSize(maxFilterSize) {\n if (this._blurDepthMaxFilterSize === maxFilterSize) {\n return;\n }\n this._blurDepthMaxFilterSize = maxFilterSize;\n this._setBlurParameters();\n }\n /**\n * Depth weight in the calculation when applying the bilateral blur to generate the depth blur texture (positive number, generally between 0 and 100)\n */\n get blurDepthDepthScale() {\n return this._blurDepthDepthScale;\n }\n set blurDepthDepthScale(scale) {\n if (this._blurDepthDepthScale === scale) {\n return;\n }\n this._blurDepthDepthScale = scale;\n this._setBlurParameters();\n }\n /**\n * Gets or sets a boolean indicating that the thickness texture should be blurred\n */\n get enableBlurThickness() {\n return this._enableBlurThickness;\n }\n set enableBlurThickness(enable) {\n if (this._enableBlurThickness === enable) {\n return;\n }\n this._enableBlurThickness = enable;\n this._needInitialization = true;\n }\n /**\n * Gets or sets the thickness size divisor (positive number, generally between 1 and 4), which is used as a divisor when creating the texture used for blurring the thickness\n * For eg. if blurThicknessSizeDivisor=2, the texture used to blur the thickness will be half the size of the thickness texture\n */\n get blurThicknessSizeDivisor() {\n return this._blurThicknessSizeDivisor;\n }\n set blurThicknessSizeDivisor(scale) {\n if (this._blurThicknessSizeDivisor === scale) {\n return;\n }\n this._blurThicknessSizeDivisor = scale;\n this._needInitialization = true;\n }\n /**\n * Size of the kernel used to filter the thickness blur texture (positive number, generally between 1 and 20 - higher values will require more processing power from the GPU)\n */\n get blurThicknessFilterSize() {\n return this._blurThicknessFilterSize;\n }\n set blurThicknessFilterSize(filterSize) {\n if (this._blurThicknessFilterSize === filterSize) {\n return;\n }\n this._blurThicknessFilterSize = filterSize;\n this._setBlurParameters();\n }\n /**\n * Number of blurring iterations used to generate the thickness blur texture (positive number, generally between 1 and 10 - higher values will require more processing power from the GPU)\n */\n get blurThicknessNumIterations() {\n return this._blurThicknessNumIterations;\n }\n set blurThicknessNumIterations(numIterations) {\n if (this._blurThicknessNumIterations === numIterations) {\n return;\n }\n this._blurThicknessNumIterations = numIterations;\n this._setBlurParameters();\n }\n /**\n * Gets or sets a boolean indicating that a fixed thickness should be used instead of generating a thickness texture\n */\n get useFixedThickness() {\n return this._useFixedThickness;\n }\n set useFixedThickness(use) {\n if (this._useFixedThickness === use) {\n return;\n }\n this._useFixedThickness = use;\n this._needInitialization = true;\n }\n /**\n * Gets or sets a boolean indicating that the velocity should be used when rendering the particles as a fluid.\n * Note: the vertex buffers must contain a \"velocity\" buffer for this to work!\n */\n get useVelocity() {\n return this._useVelocity;\n }\n set useVelocity(use) {\n if (this._useVelocity === use) {\n return;\n }\n this._useVelocity = use;\n this._needInitialization = true;\n this._onUseVelocityChanged.notifyObservers(this);\n }\n /**\n * Defines the size of the depth texture.\n * If null, the texture will have the size of the screen\n */\n get depthMapSize() {\n return this._depthMapSize;\n }\n set depthMapSize(size) {\n if (this._depthMapSize === size) {\n return;\n }\n this._depthMapSize = size;\n this._needInitialization = true;\n }\n /**\n * Defines the size of the thickness texture.\n * If null, the texture will have the size of the screen\n */\n get thicknessMapSize() {\n return this._thicknessMapSize;\n }\n set thicknessMapSize(size) {\n if (this._thicknessMapSize === size) {\n return;\n }\n this._thicknessMapSize = size;\n this._needInitialization = true;\n }\n /**\n * Defines the size of the diffuse texture.\n * If null, the texture will have the size of the screen\n */\n get diffuseMapSize() {\n return this._diffuseMapSize;\n }\n set diffuseMapSize(size) {\n if (this._diffuseMapSize === size) {\n return;\n }\n this._diffuseMapSize = size;\n this._needInitialization = true;\n }\n /**\n * Gets or sets the number of samples used by MSAA\n * Note: changing this value in WebGL does not work because depth/stencil textures can't be created with MSAA (see https://github.com/BabylonJS/Babylon.js/issues/12444)\n */\n get samples() {\n return this._samples;\n }\n set samples(samples) {\n if (this._samples === samples) {\n return;\n }\n this._samples = samples;\n this._needInitialization = true;\n }\n /**\n * Gets the camera used for the rendering\n */\n get camera() {\n return this._camera;\n }\n /**\n * Creates an instance of the class\n * @param scene Scene used to render the fluid object into\n * @param camera Camera used to render the fluid object. If not provided, use the active camera of the scene instead\n */\n constructor(scene, camera) {\n this._generateDiffuseTexture = false;\n /**\n * Fluid color. Not used if generateDiffuseTexture is true\n */\n this.fluidColor = new Color3(0.085, 0.6375, 0.765);\n /**\n * Density of the fluid (positive number). The higher the value, the more opaque the fluid.\n */\n this.density = 2;\n /**\n * Strength of the refraction (positive number, but generally between 0 and 0.3).\n */\n this.refractionStrength = 0.1;\n /**\n * Strength of the fresnel effect (value between 0 and 1). Lower the value if you want to soften the specular effect\n */\n this.fresnelClamp = 1.0;\n /**\n * Strength of the specular power (positive number). Increase the value to make the specular effect more concentrated\n */\n this.specularPower = 250;\n /**\n * Minimum thickness of the particles (positive number). If useFixedThickness is true, minimumThickness is the thickness used\n */\n this.minimumThickness = 0;\n /**\n * Direction of the light. The fluid is assumed to be lit by a directional light\n */\n this.dirLight = new Vector3(-2, -1, 1).normalize();\n this._debugFeature = FluidRenderingDebug.DepthBlurredTexture;\n this._debug = false;\n this._enableBlurDepth = true;\n this._blurDepthSizeDivisor = 1;\n this._blurDepthFilterSize = 7;\n this._blurDepthNumIterations = 3;\n this._blurDepthMaxFilterSize = 100;\n this._blurDepthDepthScale = 10;\n this._enableBlurThickness = true;\n this._blurThicknessSizeDivisor = 1;\n this._blurThicknessFilterSize = 5;\n this._blurThicknessNumIterations = 1;\n this._useFixedThickness = false;\n /** @internal */\n this._onUseVelocityChanged = new Observable();\n this._useVelocity = false;\n this._depthMapSize = null;\n this._thicknessMapSize = null;\n this._diffuseMapSize = null;\n this._samples = 1;\n this._scene = scene;\n this._engine = scene.getEngine();\n this._camera = camera !== null && camera !== void 0 ? camera : scene.activeCamera;\n this._needInitialization = true;\n this._bgDepthTexture = null;\n this._invProjectionMatrix = new Matrix();\n this._depthClearColor = new Color4(1e6, 1e6, 1e6, 1);\n this._thicknessClearColor = new Color4(0, 0, 0, 1);\n this._depthRenderTarget = null;\n this._diffuseRenderTarget = null;\n this._thicknessRenderTarget = null;\n this._renderPostProcess = null;\n }\n /** @internal */\n _initialize() {\n var _a, _b, _c;\n this.dispose();\n this._needInitialization = false;\n const depthWidth = (_a = this._depthMapSize) !== null && _a !== void 0 ? _a : this._engine.getRenderWidth();\n const depthHeight = this._depthMapSize !== null ? Math.round((this._depthMapSize * this._engine.getRenderHeight()) / this._engine.getRenderWidth()) : this._engine.getRenderHeight();\n this._depthRenderTarget = new FluidRenderingTextures(\"Depth\", this._scene, depthWidth, depthHeight, depthWidth, depthHeight, 1, 7, 1, 7, false, this._camera, true, this._samples);\n this._initializeRenderTarget(this._depthRenderTarget);\n if (this.generateDiffuseTexture) {\n const diffuseWidth = (_b = this._diffuseMapSize) !== null && _b !== void 0 ? _b : this._engine.getRenderWidth();\n const diffuseHeight = this._diffuseMapSize !== null\n ? Math.round((this._diffuseMapSize * this._engine.getRenderHeight()) / this._engine.getRenderWidth())\n : this._engine.getRenderHeight();\n this._diffuseRenderTarget = new FluidRenderingTextures(\"Diffuse\", this._scene, diffuseWidth, diffuseHeight, 0, 0, 0, 5, 0, 5, true, this._camera, true, this._samples);\n this._initializeRenderTarget(this._diffuseRenderTarget);\n }\n const thicknessWidth = (_c = this._thicknessMapSize) !== null && _c !== void 0 ? _c : this._engine.getRenderWidth();\n const thicknessHeight = this._thicknessMapSize !== null\n ? Math.round((this._thicknessMapSize * this._engine.getRenderHeight()) / this._engine.getRenderWidth())\n : this._engine.getRenderHeight();\n if (!this._useFixedThickness) {\n this._thicknessRenderTarget = new FluidRenderingTextures(\"Thickness\", this._scene, thicknessWidth, thicknessHeight, thicknessWidth, thicknessHeight, 2, 6, 2, 6, true, this._camera, false, this._samples);\n this._initializeRenderTarget(this._thicknessRenderTarget);\n }\n this._createLiquidRenderingPostProcess();\n }\n _setBlurParameters(renderTarget = null) {\n if (renderTarget === null || renderTarget === this._depthRenderTarget) {\n this._setBlurDepthParameters();\n }\n if (renderTarget === null || renderTarget === this._thicknessRenderTarget) {\n this._setBlurThicknessParameters();\n }\n }\n _setBlurDepthParameters() {\n if (!this._depthRenderTarget) {\n return;\n }\n this._depthRenderTarget.blurFilterSize = this.blurDepthFilterSize;\n this._depthRenderTarget.blurMaxFilterSize = this.blurDepthMaxFilterSize;\n this._depthRenderTarget.blurNumIterations = this.blurDepthNumIterations;\n this._depthRenderTarget.blurDepthScale = this.blurDepthDepthScale;\n }\n _setBlurThicknessParameters() {\n if (!this._thicknessRenderTarget) {\n return;\n }\n this._thicknessRenderTarget.blurFilterSize = this.blurThicknessFilterSize;\n this._thicknessRenderTarget.blurNumIterations = this.blurThicknessNumIterations;\n }\n _initializeRenderTarget(renderTarget) {\n if (renderTarget !== this._diffuseRenderTarget) {\n renderTarget.enableBlur = renderTarget === this._depthRenderTarget ? this.enableBlurDepth : this.enableBlurThickness;\n renderTarget.blurSizeDivisor = renderTarget === this._depthRenderTarget ? this.blurDepthSizeDivisor : this.blurThicknessSizeDivisor;\n }\n this._setBlurParameters(renderTarget);\n renderTarget.initialize();\n }\n _createLiquidRenderingPostProcess() {\n var _a;\n const engine = this._scene.getEngine();\n const uniformNames = [\n \"viewMatrix\",\n \"projectionMatrix\",\n \"invProjectionMatrix\",\n \"texelSize\",\n \"dirLight\",\n \"cameraFar\",\n \"density\",\n \"refractionStrength\",\n \"fresnelClamp\",\n \"specularPower\",\n ];\n const samplerNames = [\"depthSampler\"];\n const defines = [];\n this.dispose(true);\n if (!this._camera) {\n return;\n }\n const texture = this._depthRenderTarget.enableBlur ? this._depthRenderTarget.textureBlur : this._depthRenderTarget.texture;\n const texelSize = new Vector2(1 / texture.getSize().width, 1 / texture.getSize().height);\n if (this._scene.useRightHandedSystem) {\n defines.push(\"#define FLUIDRENDERING_RHS\");\n }\n if (this._environmentMap !== null) {\n const envMap = (_a = this._environmentMap) !== null && _a !== void 0 ? _a : this._scene.environmentTexture;\n if (envMap) {\n samplerNames.push(\"reflectionSampler\");\n defines.push(\"#define FLUIDRENDERING_ENVIRONMENT\");\n }\n }\n if (this._diffuseRenderTarget) {\n samplerNames.push(\"diffuseSampler\");\n defines.push(\"#define FLUIDRENDERING_DIFFUSETEXTURE\");\n }\n else {\n uniformNames.push(\"diffuseColor\");\n }\n if (this._useVelocity) {\n samplerNames.push(\"velocitySampler\");\n defines.push(\"#define FLUIDRENDERING_VELOCITY\");\n }\n if (this._useFixedThickness) {\n uniformNames.push(\"thickness\");\n samplerNames.push(\"bgDepthSampler\");\n defines.push(\"#define FLUIDRENDERING_FIXED_THICKNESS\");\n }\n else {\n uniformNames.push(\"minimumThickness\");\n samplerNames.push(\"thicknessSampler\");\n }\n if (this._debug) {\n defines.push(\"#define FLUIDRENDERING_DEBUG\");\n if (this._debugFeature === FluidRenderingDebug.Normals) {\n defines.push(\"#define FLUIDRENDERING_DEBUG_SHOWNORMAL\");\n }\n else if (this._debugFeature === FluidRenderingDebug.DiffuseRendering) {\n defines.push(\"#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING\");\n }\n else {\n defines.push(\"#define FLUIDRENDERING_DEBUG_TEXTURE\");\n samplerNames.push(\"debugSampler\");\n if (this._debugFeature === FluidRenderingDebug.DepthTexture || this._debugFeature === FluidRenderingDebug.DepthBlurredTexture) {\n defines.push(\"#define FLUIDRENDERING_DEBUG_DEPTH\");\n }\n }\n }\n this._renderPostProcess = new PostProcess(\"FluidRendering\", \"fluidRenderingRender\", uniformNames, samplerNames, 1, null, 2, engine, false, null, 0, undefined, undefined, true, undefined);\n this._renderPostProcess.updateEffect(defines.join(\"\\n\"));\n this._renderPostProcess.samples = this._samples;\n this._renderPostProcess.onApplyObservable.add((effect) => {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y;\n this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix());\n this._invProjectionMatrix.invert();\n if (engine.isWebGPU) {\n effect.setTextureSampler(\"textureSamplerSampler\", this._renderPostProcess.inputTexture.texture);\n }\n if (!this._depthRenderTarget.enableBlur) {\n effect.setTexture(\"depthSampler\", this._depthRenderTarget.texture);\n if (engine.isWebGPU) {\n effect.setTextureSampler(\"depthSamplerSampler\", (_b = (_a = this._depthRenderTarget.texture) === null || _a === void 0 ? void 0 : _a.getInternalTexture()) !== null && _b !== void 0 ? _b : null);\n }\n }\n else {\n effect.setTexture(\"depthSampler\", this._depthRenderTarget.textureBlur);\n if (engine.isWebGPU) {\n effect.setTextureSampler(\"depthSamplerSampler\", (_d = (_c = this._depthRenderTarget.textureBlur) === null || _c === void 0 ? void 0 : _c.getInternalTexture()) !== null && _d !== void 0 ? _d : null);\n }\n }\n if (this._diffuseRenderTarget) {\n if (!this._diffuseRenderTarget.enableBlur) {\n effect.setTexture(\"diffuseSampler\", this._diffuseRenderTarget.texture);\n if (engine.isWebGPU) {\n effect.setTextureSampler(\"diffuseSamplerSampler\", (_f = (_e = this._diffuseRenderTarget.texture) === null || _e === void 0 ? void 0 : _e.getInternalTexture()) !== null && _f !== void 0 ? _f : null);\n }\n }\n else {\n effect.setTexture(\"diffuseSampler\", this._diffuseRenderTarget.textureBlur);\n if (engine.isWebGPU) {\n effect.setTextureSampler(\"diffuseSamplerSampler\", (_h = (_g = this._diffuseRenderTarget.textureBlur) === null || _g === void 0 ? void 0 : _g.getInternalTexture()) !== null && _h !== void 0 ? _h : null);\n }\n }\n }\n else {\n effect.setColor3(\"diffuseColor\", this.fluidColor);\n }\n if (this._useFixedThickness) {\n effect.setFloat(\"thickness\", this.minimumThickness);\n effect._bindTexture(\"bgDepthSampler\", this._bgDepthTexture);\n if (engine.isWebGPU) {\n effect.setTextureSampler(\"bgDepthSamplerSampler\", (_j = this._bgDepthTexture) !== null && _j !== void 0 ? _j : null);\n }\n }\n else {\n if (!this._thicknessRenderTarget.enableBlur) {\n effect.setTexture(\"thicknessSampler\", this._thicknessRenderTarget.texture);\n if (engine.isWebGPU) {\n effect.setTextureSampler(\"thicknessSamplerSampler\", (_l = (_k = this._thicknessRenderTarget.texture) === null || _k === void 0 ? void 0 : _k.getInternalTexture()) !== null && _l !== void 0 ? _l : null);\n }\n }\n else {\n effect.setTexture(\"thicknessSampler\", this._thicknessRenderTarget.textureBlur);\n if (engine.isWebGPU) {\n effect.setTextureSampler(\"thicknessSamplerSampler\", (_o = (_m = this._thicknessRenderTarget.textureBlur) === null || _m === void 0 ? void 0 : _m.getInternalTexture()) !== null && _o !== void 0 ? _o : null);\n }\n }\n effect.setFloat(\"minimumThickness\", this.minimumThickness);\n }\n if (this._environmentMap !== null) {\n const envMap = (_p = this._environmentMap) !== null && _p !== void 0 ? _p : this._scene.environmentTexture;\n if (envMap) {\n effect.setTexture(\"reflectionSampler\", envMap);\n if (engine.isWebGPU) {\n effect.setTextureSampler(\"reflectionSamplerSampler\", (_q = envMap === null || envMap === void 0 ? void 0 : envMap.getInternalTexture()) !== null && _q !== void 0 ? _q : null);\n }\n }\n }\n effect.setMatrix(\"viewMatrix\", this._scene.getViewMatrix());\n effect.setMatrix(\"invProjectionMatrix\", this._invProjectionMatrix);\n effect.setMatrix(\"projectionMatrix\", this._scene.getProjectionMatrix());\n effect.setVector2(\"texelSize\", texelSize);\n effect.setFloat(\"density\", this.density);\n effect.setFloat(\"refractionStrength\", this.refractionStrength);\n effect.setFloat(\"fresnelClamp\", this.fresnelClamp);\n effect.setFloat(\"specularPower\", this.specularPower);\n effect.setVector3(\"dirLight\", this.dirLight);\n effect.setFloat(\"cameraFar\", this._camera.maxZ);\n if (this._debug) {\n let texture = null;\n switch (this._debugFeature) {\n case FluidRenderingDebug.DepthTexture:\n texture = this._depthRenderTarget.texture;\n break;\n case FluidRenderingDebug.DepthBlurredTexture:\n texture = this._depthRenderTarget.enableBlur ? this._depthRenderTarget.textureBlur : this._depthRenderTarget.texture;\n break;\n case FluidRenderingDebug.ThicknessTexture:\n texture = (_s = (_r = this._thicknessRenderTarget) === null || _r === void 0 ? void 0 : _r.texture) !== null && _s !== void 0 ? _s : null;\n break;\n case FluidRenderingDebug.ThicknessBlurredTexture:\n texture = ((_t = this._thicknessRenderTarget) === null || _t === void 0 ? void 0 : _t.enableBlur) ? (_v = (_u = this._thicknessRenderTarget) === null || _u === void 0 ? void 0 : _u.textureBlur) !== null && _v !== void 0 ? _v : null : (_x = (_w = this._thicknessRenderTarget) === null || _w === void 0 ? void 0 : _w.texture) !== null && _x !== void 0 ? _x : null;\n break;\n case FluidRenderingDebug.DiffuseTexture:\n if (this._diffuseRenderTarget) {\n texture = this._diffuseRenderTarget.texture;\n }\n break;\n }\n if (this._debugFeature !== FluidRenderingDebug.Normals) {\n effect.setTexture(\"debugSampler\", texture);\n if (engine.isWebGPU) {\n effect.setTextureSampler(\"debugSamplerSampler\", (_y = texture === null || texture === void 0 ? void 0 : texture.getInternalTexture()) !== null && _y !== void 0 ? _y : null);\n }\n }\n }\n });\n }\n /** @internal */\n _clearTargets() {\n var _a, _b, _c;\n if ((_a = this._depthRenderTarget) === null || _a === void 0 ? void 0 : _a.renderTarget) {\n this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget);\n this._engine.clear(this._depthClearColor, true, true, false);\n this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget);\n }\n if ((_b = this._diffuseRenderTarget) === null || _b === void 0 ? void 0 : _b.renderTarget) {\n this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget);\n this._engine.clear(this._thicknessClearColor, true, true, false);\n this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget);\n }\n if ((_c = this._thicknessRenderTarget) === null || _c === void 0 ? void 0 : _c.renderTarget) {\n this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget);\n // we don't clear the depth buffer because it is the depth buffer that is coming from the scene and that we reuse in the thickness rendering pass\n this._engine.clear(this._thicknessClearColor, true, false, false);\n this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget);\n }\n }\n /** @internal */\n _render(fluidObject) {\n var _a, _b, _c, _d, _e, _f;\n if (this._needInitialization || !fluidObject.isReady()) {\n return;\n }\n const currentRenderTarget = this._engine._currentRenderTarget;\n this._engine.setState(false, undefined, undefined, undefined, true);\n this._engine.setDepthBuffer(true);\n this._engine.setDepthWrite(true);\n this._engine.setAlphaMode(0);\n // Render the particles in the depth texture\n if ((_a = this._depthRenderTarget) === null || _a === void 0 ? void 0 : _a.renderTarget) {\n this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget);\n fluidObject.renderDepthTexture();\n this._engine.unbindInstanceAttributes();\n this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget);\n }\n // Render the particles in the diffuse texture\n if ((_b = this._diffuseRenderTarget) === null || _b === void 0 ? void 0 : _b.renderTarget) {\n this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget);\n fluidObject.renderDiffuseTexture();\n this._engine.unbindInstanceAttributes();\n this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget);\n }\n // Render the particles in the thickness texture\n if ((_c = this._thicknessRenderTarget) === null || _c === void 0 ? void 0 : _c.renderTarget) {\n this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget);\n fluidObject.renderThicknessTexture();\n this._engine.unbindInstanceAttributes();\n this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget);\n }\n // Run the blur post processes\n (_d = this._depthRenderTarget) === null || _d === void 0 ? void 0 : _d.applyBlurPostProcesses();\n (_e = this._diffuseRenderTarget) === null || _e === void 0 ? void 0 : _e.applyBlurPostProcesses();\n (_f = this._thicknessRenderTarget) === null || _f === void 0 ? void 0 : _f.applyBlurPostProcesses();\n if (currentRenderTarget) {\n this._engine.bindFramebuffer(currentRenderTarget);\n }\n }\n /**\n * Releases all the ressources used by the class\n * @param onlyPostProcesses If true, releases only the ressources used by the render post processes\n */\n dispose(onlyPostProcesses = false) {\n var _a, _b, _c, _d;\n if (!onlyPostProcesses) {\n (_a = this._depthRenderTarget) === null || _a === void 0 ? void 0 : _a.dispose();\n this._depthRenderTarget = null;\n (_b = this._diffuseRenderTarget) === null || _b === void 0 ? void 0 : _b.dispose();\n this._diffuseRenderTarget = null;\n (_c = this._thicknessRenderTarget) === null || _c === void 0 ? void 0 : _c.dispose();\n this._thicknessRenderTarget = null;\n }\n if (this._renderPostProcess && this._camera) {\n this._camera.detachPostProcess(this._renderPostProcess);\n }\n (_d = this._renderPostProcess) === null || _d === void 0 ? void 0 : _d.dispose();\n this._renderPostProcess = null;\n this._needInitialization = false;\n }\n}\n//# sourceMappingURL=fluidRenderingTargetRenderer.js.map","import { VertexBuffer } from \"../../Buffers/buffer.js\";\n\nimport { EffectWrapper } from \"../../Materials/effectRenderer.js\";\nimport { FluidRenderingObject } from \"./fluidRenderingObject.js\";\n/**\n * Defines a rendering object based on a list of custom buffers\n * The list must contain at least a \"position\" buffer!\n */\nexport class FluidRenderingObjectCustomParticles extends FluidRenderingObject {\n /**\n * Gets the name of the class\n */\n getClassName() {\n return \"FluidRenderingObjectCustomParticles\";\n }\n /**\n * Gets the vertex buffers\n */\n get vertexBuffers() {\n return this._vertexBuffers;\n }\n /**\n * Creates a new instance of the class\n * @param scene The scene the particles should be rendered into\n * @param buffers The list of buffers (must contain at least one \"position\" buffer!). Note that you don't have to pass all (or any!) buffers at once in the constructor, you can use the addBuffers method to add more later.\n * @param numParticles Number of vertices to take into account from the buffers\n */\n constructor(scene, buffers, numParticles) {\n super(scene);\n this._numParticles = numParticles;\n this._diffuseEffectWrapper = null;\n this._vertexBuffers = {};\n this.addBuffers(buffers);\n }\n /**\n * Add some new buffers\n * @param buffers List of buffers\n */\n addBuffers(buffers) {\n for (const name in buffers) {\n let stride;\n let instanced = true;\n switch (name) {\n case \"velocity\":\n stride = 3;\n break;\n case \"offset\":\n instanced = false;\n break;\n }\n this._vertexBuffers[name] = new VertexBuffer(this._engine, buffers[name], name, true, false, stride, instanced);\n }\n }\n _createEffects() {\n super._createEffects();\n const uniformNames = [\"view\", \"projection\", \"size\"];\n const attributeNames = [\"position\", \"offset\", \"color\"];\n this._diffuseEffectWrapper = new EffectWrapper({\n engine: this._engine,\n useShaderStore: true,\n vertexShader: \"fluidRenderingParticleDiffuse\",\n fragmentShader: \"fluidRenderingParticleDiffuse\",\n attributeNames,\n uniformNames,\n samplerNames: [],\n });\n }\n /**\n * Indicates if the object is ready to be rendered\n * @returns True if everything is ready for the object to be rendered, otherwise false\n */\n isReady() {\n var _a, _b;\n if (!this._vertexBuffers[\"offset\"]) {\n this._vertexBuffers[\"offset\"] = new VertexBuffer(this._engine, [0, 0, 1, 0, 0, 1, 1, 1], \"offset\", false, false, 2);\n }\n return super.isReady() && ((_b = (_a = this._diffuseEffectWrapper) === null || _a === void 0 ? void 0 : _a.effect.isReady()) !== null && _b !== void 0 ? _b : false);\n }\n /**\n * Gets the number of particles in this object\n * @returns The number of particles\n */\n get numParticles() {\n return this._numParticles;\n }\n /**\n * Sets the number of particles in this object\n * @param num The number of particles to take into account\n */\n setNumParticles(num) {\n this._numParticles = num;\n }\n /**\n * Render the diffuse texture for this object\n */\n renderDiffuseTexture() {\n const numParticles = this.numParticles;\n if (!this._diffuseEffectWrapper || numParticles === 0) {\n return;\n }\n const diffuseDrawWrapper = this._diffuseEffectWrapper._drawWrapper;\n const diffuseEffect = diffuseDrawWrapper.effect;\n this._engine.enableEffect(diffuseDrawWrapper);\n this._engine.bindBuffers(this.vertexBuffers, this.indexBuffer, diffuseEffect);\n diffuseEffect.setMatrix(\"view\", this._scene.getViewMatrix());\n diffuseEffect.setMatrix(\"projection\", this._scene.getProjectionMatrix());\n if (this._particleSize !== null) {\n diffuseEffect.setFloat2(\"size\", this._particleSize, this._particleSize);\n }\n if (this.useInstancing) {\n this._engine.drawArraysType(7, 0, 4, numParticles);\n }\n else {\n this._engine.drawElementsType(0, 0, numParticles);\n }\n }\n /**\n * Releases the ressources used by the class\n */\n dispose() {\n var _a;\n super.dispose();\n (_a = this._diffuseEffectWrapper) === null || _a === void 0 ? void 0 : _a.dispose();\n for (const name in this._vertexBuffers) {\n this._vertexBuffers[name].dispose();\n }\n this._vertexBuffers = {};\n }\n}\n//# sourceMappingURL=fluidRenderingObjectCustomParticles.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/helperFunctions.js\";\nconst name = \"copyTextureToTexturePixelShader\";\nconst shader = `uniform float conversion;\runiform sampler2D textureSampler;\rvarying vec2 vUV;\r#include\nvoid main(void) \r{\rvec4 color=texture2D(textureSampler,vUV);\r#ifdef DEPTH_TEXTURE\ngl_FragDepth=color.r;\r#else\nif (conversion==1.) {\rcolor=toLinearSpace(color);\r} else if (conversion==2.) {\rcolor=toGammaSpace(color);\r}\rgl_FragColor=color;\r#endif\n}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const copyTextureToTexturePixelShader = { name, shader };\n//# sourceMappingURL=copyTextureToTexture.fragment.js.map","import { EffectRenderer, EffectWrapper } from \"../Materials/effectRenderer.js\";\n\nimport \"../Shaders/copyTextureToTexture.fragment.js\";\n/**\n * Conversion modes available when copying a texture into another one\n */\nexport var ConversionMode;\n(function (ConversionMode) {\n ConversionMode[ConversionMode[\"None\"] = 0] = \"None\";\n ConversionMode[ConversionMode[\"ToLinearSpace\"] = 1] = \"ToLinearSpace\";\n ConversionMode[ConversionMode[\"ToGammaSpace\"] = 2] = \"ToGammaSpace\";\n})(ConversionMode || (ConversionMode = {}));\n/**\n * Class used for fast copy from one texture to another\n */\nexport class CopyTextureToTexture {\n _textureIsInternal(texture) {\n return texture.getInternalTexture === undefined;\n }\n /**\n * Constructs a new instance of the class\n * @param engine The engine to use for the copy\n * @param isDepthTexture True means that we should write (using gl_FragDepth) into the depth texture attached to the destination (default: false)\n */\n constructor(engine, isDepthTexture = false) {\n this._engine = engine;\n this._isDepthTexture = isDepthTexture;\n this._renderer = new EffectRenderer(engine);\n this._effectWrapper = new EffectWrapper({\n engine: engine,\n name: \"CopyTextureToTexture\",\n fragmentShader: \"copyTextureToTexture\",\n useShaderStore: true,\n uniformNames: [\"conversion\"],\n samplerNames: [\"textureSampler\"],\n defines: isDepthTexture ? [\"#define DEPTH_TEXTURE\"] : [],\n });\n this._effectWrapper.onApplyObservable.add(() => {\n if (isDepthTexture) {\n engine.setState(false);\n engine.setDepthBuffer(true);\n engine.depthCullingState.depthMask = true;\n engine.depthCullingState.depthFunc = 519;\n }\n if (this._textureIsInternal(this._source)) {\n this._effectWrapper.effect._bindTexture(\"textureSampler\", this._source);\n }\n else {\n this._effectWrapper.effect.setTexture(\"textureSampler\", this._source);\n }\n this._effectWrapper.effect.setFloat(\"conversion\", this._conversion);\n });\n }\n /**\n * Indicates if the effect is ready to be used for the copy\n * @returns true if \"copy\" can be called without delay, else false\n */\n isReady() {\n return this._effectWrapper.effect.isReady();\n }\n /**\n * Copy one texture into another\n * @param source The source texture\n * @param destination The destination texture\n * @param conversion The conversion mode that should be applied when copying\n * @returns\n */\n copy(source, destination, conversion = ConversionMode.None) {\n if (!this.isReady()) {\n return false;\n }\n this._source = source;\n this._conversion = conversion;\n const engineDepthFunc = this._engine.depthCullingState.depthFunc;\n this._renderer.render(this._effectWrapper, destination);\n if (this._isDepthTexture && engineDepthFunc) {\n this._engine.depthCullingState.depthFunc = engineDepthFunc;\n }\n return true;\n }\n /**\n * Releases all the resources used by the class\n */\n dispose() {\n this._effectWrapper.dispose();\n this._renderer.dispose();\n }\n}\n//# sourceMappingURL=copyTextureToTexture.js.map","\nimport { CopyTextureToTexture } from \"../../Misc/copyTextureToTexture.js\";\n/** @internal */\nexport class FluidRenderingDepthTextureCopy {\n get depthRTWrapper() {\n return this._depthRTWrapper;\n }\n constructor(engine, width, height, samples = 1) {\n this._engine = engine;\n this._copyTextureToTexture = new CopyTextureToTexture(engine, true);\n this._depthRTWrapper = this._engine.createRenderTargetTexture({ width, height }, {\n generateMipMaps: false,\n type: 0,\n format: 6,\n samplingMode: 1,\n generateDepthBuffer: true,\n generateStencilBuffer: false,\n samples,\n noColorAttachment: true,\n label: \"FluidRenderingDepthTextureCopyRTT\",\n });\n this._depthRTWrapper.createDepthStencilTexture(0, false, false, 1, undefined, \"FluidRenderingDepthTextureCopyRTTDepthStencil\");\n }\n copy(source) {\n return this._copyTextureToTexture.copy(source, this._depthRTWrapper);\n }\n dispose() {\n this._depthRTWrapper.dispose();\n this._copyTextureToTexture.dispose();\n }\n}\n//# sourceMappingURL=fluidRenderingDepthTextureCopy.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"fluidRenderingParticleDepthVertexShader\";\nconst shader = `attribute vec3 position;\rattribute vec2 offset;\runiform mat4 view;\runiform mat4 projection;\runiform vec2 size;\rvarying vec2 uv;\rvarying vec3 viewPos;\rvarying float sphereRadius;\r#ifdef FLUIDRENDERING_VELOCITY\nattribute vec3 velocity;\rvarying float velocityNorm;\r#endif\nvoid main(void) {\rvec3 cornerPos;\rcornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;\rcornerPos.z=0.0;\rviewPos=(view*vec4(position,1.0)).xyz;\rgl_Position=projection*vec4(viewPos+cornerPos,1.0);\ruv=offset;\rsphereRadius=size.x/2.0;\r#ifdef FLUIDRENDERING_VELOCITY\nvelocityNorm=length(velocity);\r#endif\n}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const fluidRenderingParticleDepthVertexShader = { name, shader };\n//# sourceMappingURL=fluidRenderingParticleDepth.vertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"fluidRenderingParticleDepthPixelShader\";\nconst shader = `uniform mat4 projection;\rvarying vec2 uv;\rvarying vec3 viewPos;\rvarying float sphereRadius;\r#ifdef FLUIDRENDERING_VELOCITY\nvarying float velocityNorm;\r#endif\nvoid main(void) {\rvec3 normal;\rnormal.xy=uv*2.0-1.0;\rfloat r2=dot(normal.xy,normal.xy);\rif (r2>1.0) discard;\rnormal.z=sqrt(1.0-r2);\r#ifndef FLUIDRENDERING_RHS\nnormal.z=-normal.z;\r#endif\nvec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);\rvec4 clipSpacePos=projection*realViewPos;\r#ifdef WEBGPU\ngl_FragDepth=clipSpacePos.z/clipSpacePos.w;\r#else\ngl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5;\r#endif\n#ifdef FLUIDRENDERING_RHS\nrealViewPos.z=-realViewPos.z;\r#endif\n#ifdef FLUIDRENDERING_VELOCITY\nglFragColor=vec4(realViewPos.z,velocityNorm,0.,1.);\r#else\nglFragColor=vec4(realViewPos.z,0.,0.,1.);\r#endif\n}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const fluidRenderingParticleDepthPixelShader = { name, shader };\n//# sourceMappingURL=fluidRenderingParticleDepth.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"fluidRenderingParticleThicknessVertexShader\";\nconst shader = `attribute vec3 position;\rattribute vec2 offset;\runiform mat4 view;\runiform mat4 projection;\runiform vec2 size;\rvarying vec2 uv;\rvoid main(void) {\rvec3 cornerPos;\rcornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;\rcornerPos.z=0.0;\rvec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;\rgl_Position=projection*vec4(viewPos,1.0);\ruv=offset;\r}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const fluidRenderingParticleThicknessVertexShader = { name, shader };\n//# sourceMappingURL=fluidRenderingParticleThickness.vertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"fluidRenderingParticleThicknessPixelShader\";\nconst shader = `uniform float particleAlpha;\rvarying vec2 uv;\rvoid main(void) {\rvec3 normal;\rnormal.xy=uv*2.0-1.0;\rfloat r2=dot(normal.xy,normal.xy);\rif (r2>1.0) discard;\rfloat thickness=sqrt(1.0-r2);\rglFragColor=vec4(vec3(particleAlpha*thickness),1.0);\r}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const fluidRenderingParticleThicknessPixelShader = { name, shader };\n//# sourceMappingURL=fluidRenderingParticleThickness.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"fluidRenderingParticleDiffuseVertexShader\";\nconst shader = `attribute vec3 position;\rattribute vec2 offset;\rattribute vec4 color;\runiform mat4 view;\runiform mat4 projection;\runiform vec2 size;\rvarying vec2 uv;\rvarying vec3 diffuseColor;\rvoid main(void) {\rvec3 cornerPos;\rcornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;\rcornerPos.z=0.0;\rvec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;\rgl_Position=projection*vec4(viewPos,1.0);\ruv=offset;\rdiffuseColor=color.rgb;\r}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const fluidRenderingParticleDiffuseVertexShader = { name, shader };\n//# sourceMappingURL=fluidRenderingParticleDiffuse.vertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"fluidRenderingParticleDiffusePixelShader\";\nconst shader = `uniform float particleAlpha;\rvarying vec2 uv;\rvarying vec3 diffuseColor;\rvoid main(void) {\rvec3 normal;\rnormal.xy=uv*2.0-1.0;\rfloat r2=dot(normal.xy,normal.xy);\rif (r2>1.0) discard;\rglFragColor=vec4(diffuseColor,1.0);\r}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const fluidRenderingParticleDiffusePixelShader = { name, shader };\n//# sourceMappingURL=fluidRenderingParticleDiffuse.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"fluidRenderingBilateralBlurPixelShader\";\nconst shader = `uniform sampler2D textureSampler;\runiform int maxFilterSize;\runiform vec2 blurDir;\runiform float projectedParticleConstant;\runiform float depthThreshold;\rvarying vec2 vUV;\rvoid main(void) {\rfloat depth=textureLod(textureSampler,vUV,0.).x;\rif (depth>=1e6 || depth<=0.) {\rglFragColor=vec4(vec3(depth),1.);\rreturn;\r}\rint filterSize=min(maxFilterSize,int(ceil(projectedParticleConstant/depth)));\rfloat sigma=float(filterSize)/3.0;\rfloat two_sigma2=2.0*sigma*sigma;\rfloat sigmaDepth=depthThreshold/3.0;\rfloat two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;\rfloat sum=0.;\rfloat wsum=0.;\rfloat sumVel=0.;\rfor (int x=-filterSize; x<=filterSize; ++x) {\rvec2 coords=vec2(x);\rvec2 sampleDepthVel=textureLod(textureSampler,vUV+coords*blurDir,0.).rg;\rfloat r=dot(coords,coords);\rfloat w=exp(-r/two_sigma2);\rfloat rDepth=sampleDepthVel.r-depth;\rfloat wd=exp(-rDepth*rDepth/two_sigmaDepth2);\rsum+=sampleDepthVel.r*w*wd;\rsumVel+=sampleDepthVel.g*w*wd;\rwsum+=w*wd;\r}\rglFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);\r}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const fluidRenderingBilateralBlurPixelShader = { name, shader };\n//# sourceMappingURL=fluidRenderingBilateralBlur.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"fluidRenderingStandardBlurPixelShader\";\nconst shader = `uniform sampler2D textureSampler;\runiform int filterSize;\runiform vec2 blurDir;\rvarying vec2 vUV;\rvoid main(void) {\rvec4 s=textureLod(textureSampler,vUV,0.);\rif (s.r==0.) {\rglFragColor=vec4(0.,0.,0.,1.);\rreturn;\r}\rfloat sigma=float(filterSize)/3.0;\rfloat twoSigma2=2.0*sigma*sigma;\rvec4 sum=vec4(0.);\rfloat wsum=0.;\rfor (int x=-filterSize; x<=filterSize; ++x) {\rvec2 coords=vec2(x);\rvec4 sampl=textureLod(textureSampler,vUV+coords*blurDir,0.);\rfloat w=exp(-coords.x*coords.x/twoSigma2);\rsum+=sampl*w;\rwsum+=w;\r}\rsum/=wsum;\rglFragColor=vec4(sum.rgb,1.);\r}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const fluidRenderingStandardBlurPixelShader = { name, shader };\n//# sourceMappingURL=fluidRenderingStandardBlur.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"fluidRenderingRenderPixelShader\";\nconst shader = `/* disable_uniformity_analysis */\r#define IOR 1.333\n#define ETA 1.0/IOR\n#define F0 0.02\nuniform sampler2D textureSampler;\runiform sampler2D depthSampler;\r#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nuniform sampler2D diffuseSampler;\r#else\nuniform vec3 diffuseColor;\r#endif\n#ifdef FLUIDRENDERING_FIXED_THICKNESS\nuniform float thickness;\runiform sampler2D bgDepthSampler;\r#else\nuniform float minimumThickness;\runiform sampler2D thicknessSampler;\r#endif\n#ifdef FLUIDRENDERING_ENVIRONMENT\nuniform samplerCube reflectionSampler;\r#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nuniform sampler2D debugSampler;\r#endif\nuniform mat4 viewMatrix;\runiform mat4 projectionMatrix;\runiform mat4 invProjectionMatrix;\runiform vec2 texelSize;\runiform vec3 dirLight;\runiform float cameraFar;\runiform float density;\runiform float refractionStrength;\runiform float fresnelClamp;\runiform float specularPower;\rvarying vec2 vUV;\rvec3 computeViewPosFromUVDepth(vec2 texCoord,float depth) {\rvec4 ndc;\rndc.xy=texCoord*2.0-1.0;\r#ifdef FLUIDRENDERING_RHS\nndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth;\r#else\nndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth;\r#endif\nndc.w=1.0;\rvec4 eyePos=invProjectionMatrix*ndc;\reyePos.xyz/=eyePos.w;\rreturn eyePos.xyz;\r}\rvec3 getViewPosFromTexCoord(vec2 texCoord) {\rfloat depth=textureLod(depthSampler,texCoord,0.).x;\rreturn computeViewPosFromUVDepth(texCoord,depth);\r}\rvoid main(void) {\rvec2 texCoord=vUV;\r#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE)\nvec4 color=texture2D(debugSampler,texCoord);\r#ifdef FLUIDRENDERING_DEBUG_DEPTH\nglFragColor=vec4(color.rgb/vec3(2.0),1.);\rif (color.r>0.999 && color.g>0.999) {\rglFragColor=texture2D(textureSampler,texCoord);\r}\r#else\nglFragColor=vec4(color.rgb,1.);\rif (color.r<0.001 && color.g<0.001 && color.b<0.001) {\rglFragColor=texture2D(textureSampler,texCoord);\r}\r#endif\nreturn;\r#endif\nvec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;\rfloat depth=depthVel.r;\r#ifndef FLUIDRENDERING_FIXED_THICKNESS\nfloat thickness=texture2D(thicknessSampler,texCoord).x;\r#else\nfloat bgDepth=texture2D(bgDepthSampler,texCoord).x;\rfloat depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;\rdepthNonLinear=depthNonLinear*0.5+0.5;\r#endif\nvec4 backColor=texture2D(textureSampler,texCoord);\r#ifndef FLUIDRENDERING_FIXED_THICKNESS\nif (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) {\r#else\nif (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) {\r#endif\nglFragColor=backColor;\rreturn;\r}\rvec3 viewPos=computeViewPosFromUVDepth(texCoord,depth);\rvec3 ddx=getViewPosFromTexCoord(texCoord+vec2(texelSize.x,0.))-viewPos;\rvec3 ddy=getViewPosFromTexCoord(texCoord+vec2(0.,texelSize.y))-viewPos;\rvec3 ddx2=viewPos-getViewPosFromTexCoord(texCoord+vec2(-texelSize.x,0.));\rif (abs(ddx.z)>abs(ddx2.z)) {\rddx=ddx2;\r}\rvec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));\rif (abs(ddy.z)>abs(ddy2.z)) {\rddy=ddy2;\r}\rvec3 normal=normalize(cross(ddy,ddx));\r#ifdef FLUIDRENDERING_RHS\nnormal=-normal;\r#endif\n#ifndef WEBGPU\nif(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {\rnormal=vec3(0.,0.,-1.);\r}\r#endif\n#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL)\nglFragColor=vec4(normal*0.5+0.5,1.0);\rreturn;\r#endif\nvec3 rayDir=normalize(viewPos); \r#ifdef FLUIDRENDERING_DIFFUSETEXTURE\nvec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb;\r#endif\nvec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));\rvec3 H =normalize(lightDir-rayDir);\rfloat specular=pow(max(0.0,dot(H,normal)),specularPower);\r#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING\nfloat diffuse =max(0.0,dot(lightDir,normal))*1.0;\rglFragColor=vec4(vec3(0.1) /*ambient*/+vec3(0.42,0.50,1.00)*diffuse+vec3(0,0,0.2)+specular,1.);\rreturn;\r#endif\nvec3 refractionDir=refract(rayDir,normal,ETA);\rvec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0);\rvec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); \rvec3 refractionColor=transmitted.rgb*transmittance;\r#ifdef FLUIDRENDERING_ENVIRONMENT\nvec3 reflectionDir=reflect(rayDir,normal);\rvec3 reflectionColor=(textureCube(reflectionSampler,reflectionDir).rgb);\rfloat fresnel=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,fresnelClamp);\rvec3 finalColor=mix(refractionColor,reflectionColor,fresnel)+specular;\r#else\nvec3 finalColor=refractionColor+specular;\r#endif\n#ifdef FLUIDRENDERING_VELOCITY\nfloat velocity=depthVel.g;\rfinalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0));\r#endif\nglFragColor=vec4(finalColor,transmitted.a);\r}\r`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const fluidRenderingRenderPixelShader = { name, shader };\n//# sourceMappingURL=fluidRenderingRender.fragment.js.map","import { Scene } from \"../../scene.js\";\nimport { SceneComponentConstants } from \"../../sceneComponent.js\";\n\nimport { FluidRenderingObjectParticleSystem } from \"./fluidRenderingObjectParticleSystem.js\";\nimport { FluidRenderingTargetRenderer } from \"./fluidRenderingTargetRenderer.js\";\nimport { FluidRenderingObjectCustomParticles } from \"./fluidRenderingObjectCustomParticles.js\";\nimport { FluidRenderingDepthTextureCopy } from \"./fluidRenderingDepthTextureCopy.js\";\nimport \"../../Shaders/fluidRenderingParticleDepth.vertex.js\";\nimport \"../../Shaders/fluidRenderingParticleDepth.fragment.js\";\nimport \"../../Shaders/fluidRenderingParticleThickness.vertex.js\";\nimport \"../../Shaders/fluidRenderingParticleThickness.fragment.js\";\nimport \"../../Shaders/fluidRenderingParticleDiffuse.vertex.js\";\nimport \"../../Shaders/fluidRenderingParticleDiffuse.fragment.js\";\nimport \"../../Shaders/fluidRenderingBilateralBlur.fragment.js\";\nimport \"../../Shaders/fluidRenderingStandardBlur.fragment.js\";\nimport \"../../Shaders/fluidRenderingRender.fragment.js\";\nObject.defineProperty(Scene.prototype, \"fluidRenderer\", {\n get: function () {\n return this._fluidRenderer;\n },\n set: function (value) {\n this._fluidRenderer = value;\n },\n enumerable: true,\n configurable: true,\n});\nScene.prototype.enableFluidRenderer = function () {\n if (this._fluidRenderer) {\n return this._fluidRenderer;\n }\n this._fluidRenderer = new FluidRenderer(this);\n return this._fluidRenderer;\n};\nScene.prototype.disableFluidRenderer = function () {\n var _a;\n (_a = this._fluidRenderer) === null || _a === void 0 ? void 0 : _a.dispose();\n this._fluidRenderer = null;\n};\nfunction IsParticleSystemObject(obj) {\n return !!obj.particleSystem;\n}\n/**\n * Defines the fluid renderer scene component responsible to render objects as fluids\n */\nexport class FluidRendererSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpful to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_FLUIDRENDERER;\n this.scene = scene;\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene._gatherActiveCameraRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER, this, this._gatherActiveCameraRenderTargets);\n this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_FLUIDRENDERER, this, this._afterCameraDraw);\n }\n _gatherActiveCameraRenderTargets(_renderTargets) {\n var _a;\n (_a = this.scene.fluidRenderer) === null || _a === void 0 ? void 0 : _a._prepareRendering();\n }\n _afterCameraDraw(camera) {\n var _a;\n (_a = this.scene.fluidRenderer) === null || _a === void 0 ? void 0 : _a._render(camera);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n if (this.scene._fluidRenderer) {\n // Release resources first\n this.scene.disableFluidRenderer();\n // Re-enable\n this.scene.enableFluidRenderer();\n }\n }\n /**\n * Disposes the component and the associated resources\n */\n dispose() {\n this.scene.disableFluidRenderer();\n }\n}\n/**\n * Class responsible for fluid rendering.\n * It is implementing the method described in https://developer.download.nvidia.com/presentations/2010/gdc/Direct3D_Effects.pdf\n */\nexport class FluidRenderer {\n /** @internal */\n static _SceneComponentInitialization(scene) {\n let component = scene._getComponent(SceneComponentConstants.NAME_FLUIDRENDERER);\n if (!component) {\n component = new FluidRendererSceneComponent(scene);\n scene._addComponent(component);\n }\n }\n /**\n * Initializes the class\n * @param scene Scene in which the objects are part of\n */\n constructor(scene) {\n this._scene = scene;\n this._engine = scene.getEngine();\n this._onEngineResizeObserver = null;\n this.renderObjects = [];\n this.targetRenderers = [];\n this._cameras = new Map();\n FluidRenderer._SceneComponentInitialization(this._scene);\n this._onEngineResizeObserver = this._engine.onResizeObservable.add(() => {\n this._initialize();\n });\n }\n /**\n * Reinitializes the class\n * Can be used if you change the object priority (FluidRenderingObject.priority), to make sure the objects are rendered in the right order\n */\n recreate() {\n this._sortRenderingObjects();\n this._initialize();\n }\n /**\n * Gets the render object corresponding to a particle system (null if the particle system is not rendered as a fluid)\n * @param ps The particle system\n * @returns the render object corresponding to this particle system if any, otherwise null\n */\n getRenderObjectFromParticleSystem(ps) {\n const index = this._getParticleSystemIndex(ps);\n return index !== -1 ? this.renderObjects[index] : null;\n }\n /**\n * Adds a particle system to the fluid renderer.\n * Note that you should not normally call this method directly, as you can simply use the renderAsFluid property of the ParticleSystem/GPUParticleSystem class\n * @param ps particle system\n * @param generateDiffuseTexture True if you want to generate a diffuse texture from the particle system and use it as part of the fluid rendering (default: false)\n * @param targetRenderer The target renderer used to display the particle system as a fluid. If not provided, the method will create a new one\n * @param camera The camera used by the target renderer (if the target renderer is created by the method)\n * @returns the render object corresponding to the particle system\n */\n addParticleSystem(ps, generateDiffuseTexture, targetRenderer, camera) {\n const object = new FluidRenderingObjectParticleSystem(this._scene, ps);\n object.onParticleSizeChanged.add(this._setParticleSizeForRenderTargets.bind(this));\n if (!targetRenderer) {\n targetRenderer = new FluidRenderingTargetRenderer(this._scene, camera);\n this.targetRenderers.push(targetRenderer);\n }\n if (!targetRenderer._onUseVelocityChanged.hasObservers()) {\n targetRenderer._onUseVelocityChanged.add(this._setUseVelocityForRenderObject.bind(this));\n }\n if (generateDiffuseTexture !== undefined) {\n targetRenderer.generateDiffuseTexture = generateDiffuseTexture;\n }\n const renderObject = { object, targetRenderer };\n this.renderObjects.push(renderObject);\n this._sortRenderingObjects();\n this._setParticleSizeForRenderTargets();\n return renderObject;\n }\n /**\n * Adds a custom particle set to the fluid renderer.\n * @param buffers The list of buffers (should contain at least a \"position\" buffer!)\n * @param numParticles Number of particles in each buffer\n * @param generateDiffuseTexture True if you want to generate a diffuse texture from buffers and use it as part of the fluid rendering (default: false). For the texture to be generated correctly, you need a \"color\" buffer in the set!\n * @param targetRenderer The target renderer used to display the particle system as a fluid. If not provided, the method will create a new one\n * @param camera The camera used by the target renderer (if the target renderer is created by the method)\n * @returns the render object corresponding to the custom particle set\n */\n addCustomParticles(buffers, numParticles, generateDiffuseTexture, targetRenderer, camera) {\n const object = new FluidRenderingObjectCustomParticles(this._scene, buffers, numParticles);\n object.onParticleSizeChanged.add(this._setParticleSizeForRenderTargets.bind(this));\n if (!targetRenderer) {\n targetRenderer = new FluidRenderingTargetRenderer(this._scene, camera);\n this.targetRenderers.push(targetRenderer);\n }\n if (!targetRenderer._onUseVelocityChanged.hasObservers()) {\n targetRenderer._onUseVelocityChanged.add(this._setUseVelocityForRenderObject.bind(this));\n }\n if (generateDiffuseTexture !== undefined) {\n targetRenderer.generateDiffuseTexture = generateDiffuseTexture;\n }\n const renderObject = { object, targetRenderer };\n this.renderObjects.push(renderObject);\n this._sortRenderingObjects();\n this._setParticleSizeForRenderTargets();\n return renderObject;\n }\n /**\n * Removes a render object from the fluid renderer\n * @param renderObject the render object to remove\n * @param removeUnusedTargetRenderer True to remove/dispose of the target renderer if it's not used anymore (default: true)\n * @returns True if the render object has been found and released, else false\n */\n removeRenderObject(renderObject, removeUnusedTargetRenderer = true) {\n const index = this.renderObjects.indexOf(renderObject);\n if (index === -1) {\n return false;\n }\n renderObject.object.dispose();\n this.renderObjects.splice(index, 1);\n if (removeUnusedTargetRenderer && this._removeUnusedTargetRenderers()) {\n this._initialize();\n }\n else {\n this._setParticleSizeForRenderTargets();\n }\n return true;\n }\n _sortRenderingObjects() {\n this.renderObjects.sort((a, b) => {\n return a.object.priority < b.object.priority ? -1 : a.object.priority > b.object.priority ? 1 : 0;\n });\n }\n _removeUnusedTargetRenderers() {\n const indexes = {};\n for (let i = 0; i < this.renderObjects.length; ++i) {\n const targetRenderer = this.renderObjects[i].targetRenderer;\n indexes[this.targetRenderers.indexOf(targetRenderer)] = true;\n }\n let removed = false;\n const newList = [];\n for (let i = 0; i < this.targetRenderers.length; ++i) {\n if (!indexes[i]) {\n this.targetRenderers[i].dispose();\n removed = true;\n }\n else {\n newList.push(this.targetRenderers[i]);\n }\n }\n if (removed) {\n this.targetRenderers.length = 0;\n this.targetRenderers.push(...newList);\n }\n return removed;\n }\n _getParticleSystemIndex(ps) {\n for (let i = 0; i < this.renderObjects.length; ++i) {\n const obj = this.renderObjects[i].object;\n if (IsParticleSystemObject(obj) && obj.particleSystem === ps) {\n return i;\n }\n }\n return -1;\n }\n _initialize() {\n for (let i = 0; i < this.targetRenderers.length; ++i) {\n this.targetRenderers[i].dispose();\n }\n const cameras = new Map();\n for (let i = 0; i < this.targetRenderers.length; ++i) {\n const targetRenderer = this.targetRenderers[i];\n targetRenderer._initialize();\n if (targetRenderer.camera && targetRenderer._renderPostProcess) {\n let list = cameras.get(targetRenderer.camera);\n if (!list) {\n list = [[], {}];\n cameras.set(targetRenderer.camera, list);\n }\n list[0].push(targetRenderer);\n targetRenderer.camera.attachPostProcess(targetRenderer._renderPostProcess, i);\n }\n }\n let iterator = cameras.keys();\n for (let key = iterator.next(); key.done !== true; key = iterator.next()) {\n const camera = key.value;\n const list = cameras.get(camera);\n const firstPostProcess = camera._getFirstPostProcess();\n if (!firstPostProcess) {\n continue;\n }\n const [targetRenderers, copyDepthTextures] = list;\n firstPostProcess.onSizeChangedObservable.add(() => {\n var _a;\n if (!firstPostProcess.inputTexture.depthStencilTexture) {\n firstPostProcess.inputTexture.createDepthStencilTexture(0, true, this._engine.isStencilEnable, targetRenderers[0].samples, this._engine.isStencilEnable ? 13 : 14, `PostProcessRTTDepthStencil-${firstPostProcess.name}`);\n }\n for (const targetRenderer of targetRenderers) {\n const thicknessRT = (_a = targetRenderer._thicknessRenderTarget) === null || _a === void 0 ? void 0 : _a.renderTarget;\n const thicknessTexture = thicknessRT === null || thicknessRT === void 0 ? void 0 : thicknessRT.texture;\n if (thicknessRT && thicknessTexture) {\n const key = thicknessTexture.width + \"_\" + thicknessTexture.height;\n let copyDepthTexture = copyDepthTextures[key];\n if (!copyDepthTexture) {\n copyDepthTexture = copyDepthTextures[key] = new FluidRenderingDepthTextureCopy(this._engine, thicknessTexture.width, thicknessTexture.height);\n }\n copyDepthTexture.depthRTWrapper._shareDepth(thicknessRT);\n }\n }\n });\n }\n // Dispose the CopyDepthTexture instances that we don't need anymore\n iterator = this._cameras.keys();\n for (let key = iterator.next(); key.done !== true; key = iterator.next()) {\n const camera = key.value;\n const list = this._cameras.get(camera);\n const copyDepthTextures = list[1];\n const list2 = cameras.get(camera);\n if (!list2) {\n for (const key in copyDepthTextures) {\n copyDepthTextures[key].dispose();\n }\n }\n else {\n for (const key in copyDepthTextures) {\n if (!list2[1][key]) {\n copyDepthTextures[key].dispose();\n }\n }\n }\n }\n this._cameras.clear();\n this._cameras = cameras;\n this._setParticleSizeForRenderTargets();\n }\n _setParticleSizeForRenderTargets() {\n const particleSizes = new Map();\n for (let i = 0; i < this.renderObjects.length; ++i) {\n const renderingObject = this.renderObjects[i];\n let curSize = particleSizes.get(renderingObject.targetRenderer);\n if (curSize === undefined) {\n curSize = 0;\n }\n particleSizes.set(renderingObject.targetRenderer, Math.max(curSize, renderingObject.object.particleSize));\n }\n particleSizes.forEach((particleSize, targetRenderer) => {\n if (targetRenderer._depthRenderTarget) {\n targetRenderer._depthRenderTarget.particleSize = particleSize;\n }\n });\n }\n _setUseVelocityForRenderObject() {\n for (const renderingObject of this.renderObjects) {\n renderingObject.object.useVelocity = renderingObject.targetRenderer.useVelocity;\n }\n }\n /** @internal */\n _prepareRendering() {\n for (const renderer of this.targetRenderers) {\n if (renderer.needInitialization) {\n this._initialize();\n return;\n }\n }\n }\n /** @internal */\n _render(forCamera) {\n var _a;\n for (let i = 0; i < this.targetRenderers.length; ++i) {\n if (!forCamera || this.targetRenderers[i].camera === forCamera) {\n this.targetRenderers[i]._clearTargets();\n }\n }\n const iterator = this._cameras.keys();\n for (let key = iterator.next(); key.done !== true; key = iterator.next()) {\n const camera = key.value;\n const list = this._cameras.get(camera);\n if (forCamera && camera !== forCamera) {\n continue;\n }\n const firstPostProcess = camera._getFirstPostProcess();\n if (!firstPostProcess) {\n continue;\n }\n const sourceCopyDepth = (_a = firstPostProcess.inputTexture) === null || _a === void 0 ? void 0 : _a.depthStencilTexture;\n if (sourceCopyDepth) {\n const [targetRenderers, copyDepthTextures] = list;\n for (const targetRenderer of targetRenderers) {\n targetRenderer._bgDepthTexture = sourceCopyDepth;\n }\n for (const key in copyDepthTextures) {\n copyDepthTextures[key].copy(sourceCopyDepth);\n }\n }\n }\n for (let i = 0; i < this.renderObjects.length; ++i) {\n const renderingObject = this.renderObjects[i];\n if (!forCamera || renderingObject.targetRenderer.camera === forCamera) {\n renderingObject.targetRenderer._render(renderingObject.object);\n }\n }\n }\n /**\n * Disposes of all the ressources used by the class\n */\n dispose() {\n this._engine.onResizeObservable.remove(this._onEngineResizeObserver);\n this._onEngineResizeObserver = null;\n for (let i = 0; i < this.renderObjects.length; ++i) {\n this.renderObjects[i].object.dispose();\n }\n for (let i = 0; i < this.targetRenderers.length; ++i) {\n this.targetRenderers[i].dispose();\n }\n this._cameras.forEach((list) => {\n const copyDepthTextures = list[1];\n for (const key in copyDepthTextures) {\n copyDepthTextures[key].dispose();\n }\n });\n this.renderObjects = [];\n this.targetRenderers = [];\n this._cameras.clear();\n }\n}\n//# sourceMappingURL=fluidRenderer.js.map","export * from \"./fluidRenderer.js\";\nexport * from \"./fluidRenderingObject.js\";\nexport * from \"./fluidRenderingObjectParticleSystem.js\";\nexport * from \"./fluidRenderingObjectCustomParticles.js\";\nexport * from \"./fluidRenderingTargetRenderer.js\";\n//# sourceMappingURL=index.js.map","/**\n * ThinSprite Class used to represent a thin sprite\n * This is the base class for sprites but can also directly be used with ThinEngine\n * @see https://doc.babylonjs.com/features/featuresDeepDive/sprites\n */\nexport class ThinSprite {\n /**\n * Returns a boolean indicating if the animation is started\n */\n get animationStarted() {\n return this._animationStarted;\n }\n /** Gets the initial key for the animation (setting it will restart the animation) */\n get fromIndex() {\n return this._fromIndex;\n }\n /** Gets or sets the end key for the animation (setting it will restart the animation) */\n get toIndex() {\n return this._toIndex;\n }\n /** Gets or sets a boolean indicating if the animation is looping (setting it will restart the animation) */\n get loopAnimation() {\n return this._loopAnimation;\n }\n /** Gets or sets the delay between cell changes (setting it will restart the animation) */\n get delay() {\n return Math.max(this._delay, 1);\n }\n /**\n * Creates a new Thin Sprite\n */\n constructor() {\n /** Gets or sets the width */\n this.width = 1.0;\n /** Gets or sets the height */\n this.height = 1.0;\n /** Gets or sets rotation angle */\n this.angle = 0;\n /** Gets or sets a boolean indicating if UV coordinates should be inverted in U axis */\n this.invertU = false;\n /** Gets or sets a boolean indicating if UV coordinates should be inverted in B axis */\n this.invertV = false;\n /** Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true */\n this.isVisible = true;\n this._animationStarted = false;\n this._loopAnimation = false;\n this._fromIndex = 0;\n this._toIndex = 0;\n this._delay = 0;\n this._direction = 1;\n this._time = 0;\n this._onBaseAnimationEnd = null;\n this.position = { x: 1.0, y: 1.0, z: 1.0 };\n this.color = { r: 1.0, g: 1.0, b: 1.0, a: 1.0 };\n }\n /**\n * Starts an animation\n * @param from defines the initial key\n * @param to defines the end key\n * @param loop defines if the animation must loop\n * @param delay defines the start delay (in ms)\n * @param onAnimationEnd defines a callback for when the animation ends\n */\n playAnimation(from, to, loop, delay, onAnimationEnd) {\n this._fromIndex = from;\n this._toIndex = to;\n this._loopAnimation = loop;\n this._delay = delay || 1;\n this._animationStarted = true;\n this._onBaseAnimationEnd = onAnimationEnd;\n if (from < to) {\n this._direction = 1;\n }\n else {\n this._direction = -1;\n this._toIndex = from;\n this._fromIndex = to;\n }\n this.cellIndex = from;\n this._time = 0;\n }\n /** Stops current animation (if any) */\n stopAnimation() {\n this._animationStarted = false;\n }\n /**\n * @internal\n */\n _animate(deltaTime) {\n if (!this._animationStarted) {\n return;\n }\n this._time += deltaTime;\n if (this._time > this._delay) {\n this._time = this._time % this._delay;\n this.cellIndex += this._direction;\n if ((this._direction > 0 && this.cellIndex > this._toIndex) || (this._direction < 0 && this.cellIndex < this._fromIndex)) {\n if (this._loopAnimation) {\n this.cellIndex = this._direction > 0 ? this._fromIndex : this._toIndex;\n }\n else {\n this.cellIndex = this._toIndex;\n this._animationStarted = false;\n if (this._onBaseAnimationEnd) {\n this._onBaseAnimationEnd();\n }\n }\n }\n }\n }\n}\n//# sourceMappingURL=thinSprite.js.map","import { Vector3 } from \"../Maths/math.vector.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { ThinSprite } from \"./thinSprite.js\";\n/**\n * Class used to represent a sprite\n * @see https://doc.babylonjs.com/features/featuresDeepDive/sprites\n */\nexport class Sprite extends ThinSprite {\n /**\n * Gets or sets the sprite size\n */\n get size() {\n return this.width;\n }\n set size(value) {\n this.width = value;\n this.height = value;\n }\n /**\n * Gets the manager of this sprite\n */\n get manager() {\n return this._manager;\n }\n /**\n * Creates a new Sprite\n * @param name defines the name\n * @param manager defines the manager\n */\n constructor(\n /** defines the name */\n name, manager) {\n super();\n this.name = name;\n /** Gets the list of attached animations */\n this.animations = new Array();\n /** Gets or sets a boolean indicating if the sprite can be picked */\n this.isPickable = false;\n /** Gets or sets a boolean indicating that sprite texture alpha will be used for precise picking (false by default) */\n this.useAlphaForPicking = false;\n /**\n * An event triggered when the control has been disposed\n */\n this.onDisposeObservable = new Observable();\n this._onAnimationEnd = null;\n this._endAnimation = () => {\n if (this._onAnimationEnd) {\n this._onAnimationEnd();\n }\n if (this.disposeWhenFinishedAnimating) {\n this.dispose();\n }\n };\n this.color = new Color4(1.0, 1.0, 1.0, 1.0);\n this.position = Vector3.Zero();\n this._manager = manager;\n this._manager.sprites.push(this);\n this.uniqueId = this._manager.scene.getUniqueId();\n }\n /**\n * Returns the string \"Sprite\"\n * @returns \"Sprite\"\n */\n getClassName() {\n return \"Sprite\";\n }\n /** Gets or sets the initial key for the animation (setting it will restart the animation) */\n get fromIndex() {\n return this._fromIndex;\n }\n set fromIndex(value) {\n this.playAnimation(value, this._toIndex, this._loopAnimation, this._delay, this._onAnimationEnd);\n }\n /** Gets or sets the end key for the animation (setting it will restart the animation) */\n get toIndex() {\n return this._toIndex;\n }\n set toIndex(value) {\n this.playAnimation(this._fromIndex, value, this._loopAnimation, this._delay, this._onAnimationEnd);\n }\n /** Gets or sets a boolean indicating if the animation is looping (setting it will restart the animation) */\n get loopAnimation() {\n return this._loopAnimation;\n }\n set loopAnimation(value) {\n this.playAnimation(this._fromIndex, this._toIndex, value, this._delay, this._onAnimationEnd);\n }\n /** Gets or sets the delay between cell changes (setting it will restart the animation) */\n get delay() {\n return Math.max(this._delay, 1);\n }\n set delay(value) {\n this.playAnimation(this._fromIndex, this._toIndex, this._loopAnimation, value, this._onAnimationEnd);\n }\n /**\n * Starts an animation\n * @param from defines the initial key\n * @param to defines the end key\n * @param loop defines if the animation must loop\n * @param delay defines the start delay (in ms)\n * @param onAnimationEnd defines a callback to call when animation ends\n */\n playAnimation(from, to, loop, delay, onAnimationEnd = null) {\n this._onAnimationEnd = onAnimationEnd;\n super.playAnimation(from, to, loop, delay, this._endAnimation);\n }\n /** Release associated resources */\n dispose() {\n for (let i = 0; i < this._manager.sprites.length; i++) {\n if (this._manager.sprites[i] == this) {\n this._manager.sprites.splice(i, 1);\n }\n }\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n }\n /**\n * Serializes the sprite to a JSON object\n * @returns the JSON object\n */\n serialize() {\n const serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.position = this.position.asArray();\n serializationObject.color = this.color.asArray();\n serializationObject.width = this.width;\n serializationObject.height = this.height;\n serializationObject.angle = this.angle;\n serializationObject.cellIndex = this.cellIndex;\n serializationObject.cellRef = this.cellRef;\n serializationObject.invertU = this.invertU;\n serializationObject.invertV = this.invertV;\n serializationObject.disposeWhenFinishedAnimating = this.disposeWhenFinishedAnimating;\n serializationObject.isPickable = this.isPickable;\n serializationObject.isVisible = this.isVisible;\n serializationObject.useAlphaForPicking = this.useAlphaForPicking;\n serializationObject.animationStarted = this.animationStarted;\n serializationObject.fromIndex = this.fromIndex;\n serializationObject.toIndex = this.toIndex;\n serializationObject.loopAnimation = this.loopAnimation;\n serializationObject.delay = this.delay;\n return serializationObject;\n }\n /**\n * Parses a JSON object to create a new sprite\n * @param parsedSprite The JSON object to parse\n * @param manager defines the hosting manager\n * @returns the new sprite\n */\n static Parse(parsedSprite, manager) {\n const sprite = new Sprite(parsedSprite.name, manager);\n sprite.position = Vector3.FromArray(parsedSprite.position);\n sprite.color = Color4.FromArray(parsedSprite.color);\n sprite.width = parsedSprite.width;\n sprite.height = parsedSprite.height;\n sprite.angle = parsedSprite.angle;\n sprite.cellIndex = parsedSprite.cellIndex;\n sprite.cellRef = parsedSprite.cellRef;\n sprite.invertU = parsedSprite.invertU;\n sprite.invertV = parsedSprite.invertV;\n sprite.disposeWhenFinishedAnimating = parsedSprite.disposeWhenFinishedAnimating;\n sprite.isPickable = parsedSprite.isPickable;\n sprite.isVisible = parsedSprite.isVisible;\n sprite.useAlphaForPicking = parsedSprite.useAlphaForPicking;\n sprite.fromIndex = parsedSprite.fromIndex;\n sprite.toIndex = parsedSprite.toIndex;\n sprite.loopAnimation = parsedSprite.loopAnimation;\n sprite.delay = parsedSprite.delay;\n if (parsedSprite.animationStarted) {\n sprite.playAnimation(sprite.fromIndex, sprite.toIndex, sprite.loopAnimation, sprite.delay);\n }\n return sprite;\n }\n}\n//# sourceMappingURL=sprite.js.map","export {};\n//# sourceMappingURL=ISprites.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { Scene } from \"../scene.js\";\nimport { Ray } from \"../Culling/ray.js\";\nimport { PickingInfo } from \"../Collisions/pickingInfo.js\";\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { ActionEvent } from \"../Actions/actionEvent.js\";\n\nScene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {\n if (!PickingInfo) {\n return null;\n }\n let pickingInfo = null;\n if (!camera) {\n if (!this.activeCamera) {\n return null;\n }\n camera = this.activeCamera;\n }\n if (this.spriteManagers && this.spriteManagers.length > 0) {\n for (let spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {\n const spriteManager = this.spriteManagers[spriteIndex];\n if (!spriteManager.isPickable) {\n continue;\n }\n const result = spriteManager.intersects(ray, camera, predicate, fastCheck);\n if (!result || !result.hit) {\n continue;\n }\n if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {\n continue;\n }\n pickingInfo = result;\n if (fastCheck) {\n break;\n }\n }\n }\n return pickingInfo || new PickingInfo();\n};\nScene.prototype._internalMultiPickSprites = function (ray, predicate, camera) {\n if (!PickingInfo) {\n return null;\n }\n let pickingInfos = new Array();\n if (!camera) {\n if (!this.activeCamera) {\n return null;\n }\n camera = this.activeCamera;\n }\n if (this.spriteManagers && this.spriteManagers.length > 0) {\n for (let spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {\n const spriteManager = this.spriteManagers[spriteIndex];\n if (!spriteManager.isPickable) {\n continue;\n }\n const results = spriteManager.multiIntersects(ray, camera, predicate);\n if (results !== null) {\n pickingInfos = pickingInfos.concat(results);\n }\n }\n }\n return pickingInfos;\n};\nScene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {\n if (!this._tempSpritePickingRay) {\n return null;\n }\n this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);\n const result = this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);\n if (result) {\n result.ray = this.createPickingRayInCameraSpace(x, y, camera);\n }\n return result;\n};\nScene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {\n if (!this._tempSpritePickingRay) {\n return null;\n }\n if (!camera) {\n if (!this.activeCamera) {\n return null;\n }\n camera = this.activeCamera;\n }\n Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);\n const result = this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);\n if (result) {\n result.ray = ray;\n }\n return result;\n};\nScene.prototype.multiPickSprite = function (x, y, predicate, camera) {\n this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);\n return this._internalMultiPickSprites(this._tempSpritePickingRay, predicate, camera);\n};\nScene.prototype.multiPickSpriteWithRay = function (ray, predicate, camera) {\n if (!this._tempSpritePickingRay) {\n return null;\n }\n if (!camera) {\n if (!this.activeCamera) {\n return null;\n }\n camera = this.activeCamera;\n }\n Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);\n return this._internalMultiPickSprites(this._tempSpritePickingRay, predicate, camera);\n};\nScene.prototype.setPointerOverSprite = function (sprite) {\n if (this._pointerOverSprite === sprite) {\n return;\n }\n if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {\n this._pointerOverSprite.actionManager.processTrigger(10, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));\n }\n this._pointerOverSprite = sprite;\n if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {\n this._pointerOverSprite.actionManager.processTrigger(9, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));\n }\n};\nScene.prototype.getPointerOverSprite = function () {\n return this._pointerOverSprite;\n};\n/**\n * Defines the sprite scene component responsible to manage sprites\n * in a given scene.\n */\nexport class SpriteSceneComponent {\n /**\n * Creates a new instance of the component for the given scene\n * @param scene Defines the scene to register the component in\n */\n constructor(scene) {\n /**\n * The component name helpfull to identify the component in the list of scene components.\n */\n this.name = SceneComponentConstants.NAME_SPRITE;\n this.scene = scene;\n this.scene.spriteManagers = new Array();\n this.scene._tempSpritePickingRay = Ray ? Ray.Zero() : null;\n this.scene.onBeforeSpritesRenderingObservable = new Observable();\n this.scene.onAfterSpritesRenderingObservable = new Observable();\n this._spritePredicate = (sprite) => {\n if (!sprite.actionManager) {\n return false;\n }\n return sprite.isPickable && sprite.actionManager.hasPointerTriggers;\n };\n }\n /**\n * Registers the component in a given scene\n */\n register() {\n this.scene._pointerMoveStage.registerStep(SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);\n this.scene._pointerDownStage.registerStep(SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);\n this.scene._pointerUpStage.registerStep(SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);\n }\n /**\n * Rebuilds the elements related to this component in case of\n * context lost for instance.\n */\n rebuild() {\n /** Nothing to do for sprites */\n }\n /**\n * Disposes the component and the associated resources.\n */\n dispose() {\n this.scene.onBeforeSpritesRenderingObservable.clear();\n this.scene.onAfterSpritesRenderingObservable.clear();\n const spriteManagers = this.scene.spriteManagers;\n if (!spriteManagers) {\n return;\n }\n while (spriteManagers.length) {\n spriteManagers[0].dispose();\n }\n }\n _pickSpriteButKeepRay(originalPointerInfo, x, y, fastCheck, camera) {\n const result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);\n if (result) {\n result.ray = originalPointerInfo ? originalPointerInfo.ray : null;\n }\n return result;\n }\n _pointerMove(unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, element) {\n const scene = this.scene;\n if (isMeshPicked) {\n scene.setPointerOverSprite(null);\n }\n else {\n pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);\n if (pickResult && pickResult.hit && pickResult.pickedSprite) {\n scene.setPointerOverSprite(pickResult.pickedSprite);\n if (!scene.doNotHandleCursors && element) {\n if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {\n element.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;\n }\n else {\n element.style.cursor = scene.hoverCursor;\n }\n }\n }\n else {\n scene.setPointerOverSprite(null);\n }\n }\n return pickResult;\n }\n _pointerDown(unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {\n const scene = this.scene;\n scene._pickedDownSprite = null;\n if (scene.spriteManagers && scene.spriteManagers.length > 0) {\n pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);\n if (pickResult && pickResult.hit && pickResult.pickedSprite) {\n if (pickResult.pickedSprite.actionManager) {\n scene._pickedDownSprite = pickResult.pickedSprite;\n switch (evt.button) {\n case 0:\n pickResult.pickedSprite.actionManager.processTrigger(2, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));\n break;\n case 1:\n pickResult.pickedSprite.actionManager.processTrigger(4, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));\n break;\n case 2:\n pickResult.pickedSprite.actionManager.processTrigger(3, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));\n break;\n }\n if (pickResult.pickedSprite.actionManager) {\n pickResult.pickedSprite.actionManager.processTrigger(5, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));\n }\n }\n }\n }\n return pickResult;\n }\n _pointerUp(unTranslatedPointerX, unTranslatedPointerY, pickResult, evt, doubleClick) {\n const scene = this.scene;\n if (scene.spriteManagers && scene.spriteManagers.length > 0) {\n const spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);\n if (spritePickResult) {\n if (spritePickResult.hit && spritePickResult.pickedSprite) {\n if (spritePickResult.pickedSprite.actionManager) {\n spritePickResult.pickedSprite.actionManager.processTrigger(7, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));\n if (spritePickResult.pickedSprite.actionManager) {\n if (!this.scene._inputManager._isPointerSwiping()) {\n spritePickResult.pickedSprite.actionManager.processTrigger(1, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));\n }\n if (doubleClick) {\n spritePickResult.pickedSprite.actionManager.processTrigger(6, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));\n }\n }\n }\n }\n if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {\n scene._pickedDownSprite.actionManager.processTrigger(16, ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));\n }\n }\n }\n return pickResult;\n }\n}\n//# sourceMappingURL=spriteSceneComponent.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/fogVertexDeclaration.js\";\nconst name = \"spritesVertexShader\";\nconst shader = `attribute vec4 position;\rattribute vec2 options;\rattribute vec2 offsets;\rattribute vec2 inverts;\rattribute vec4 cellInfo;\rattribute vec4 color;\runiform mat4 view;\runiform mat4 projection;\rvarying vec2 vUV;\rvarying vec4 vColor;\r#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\r#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \rvec2 cornerPos;\rfloat angle=position.w;\rvec2 size=vec2(options.x,options.y);\rvec2 offset=offsets.xy;\rcornerPos=vec2(offset.x-0.5,offset.y -0.5)*size;\rvec3 rotatedCorner;\rrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\rrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\rrotatedCorner.z=0.;\rviewPos+=rotatedCorner;\rgl_Position=projection*vec4(viewPos,1.0); \rvColor=color;\rvec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));\rvec2 uvPlace=cellInfo.xy;\rvec2 uvSize=cellInfo.zw;\rvUV.x=uvPlace.x+uvSize.x*uvOffset.x;\rvUV.y=uvPlace.y+uvSize.y*uvOffset.y;\r#ifdef FOG\nvFogDistance=viewPos;\r#endif\n#define CUSTOM_VERTEX_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const spritesVertexShader = { name, shader };\n//# sourceMappingURL=sprites.vertex.js.map","// Do not edit.\nimport { ShaderStore } from \"../../Engines/shaderStore.js\";\nconst name = \"imageProcessingCompatibility\";\nconst shader = `#ifdef IMAGEPROCESSINGPOSTPROCESS\ngl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2));\r#endif\n`;\n// Sideeffect\nShaderStore.IncludesShadersStore[name] = shader;\n/** @internal */\nexport const imageProcessingCompatibility = { name, shader };\n//# sourceMappingURL=imageProcessingCompatibility.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nimport \"./ShadersInclude/fogFragmentDeclaration.js\";\nimport \"./ShadersInclude/fogFragment.js\";\nimport \"./ShadersInclude/imageProcessingCompatibility.js\";\nconst name = \"spritesPixelShader\";\nconst shader = `uniform bool alphaTest;\rvarying vec4 vColor;\rvarying vec2 vUV;\runiform sampler2D diffuseSampler;\r#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\n#ifdef PIXEL_PERFECT\nvec2 uvPixelPerfect(vec2 uv) {\rvec2 res=vec2(textureSize(diffuseSampler,0));\ruv=uv*res;\rvec2 seam=floor(uv+0.5);\ruv=seam+clamp((uv-seam)/fwidth(uv),-0.5,0.5);\rreturn uv/res;\r}\r#endif\nvoid main(void) {\r#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#ifdef PIXEL_PERFECT\nvec2 uv=uvPixelPerfect(vUV);\r#else\nvec2 uv=vUV;\r#endif\nvec4 color=texture2D(diffuseSampler,uv);\rfloat fAlphaTest=float(alphaTest);\rif (fAlphaTest != 0.)\r{\rif (color.a<0.95)\rdiscard;\r}\rcolor*=vColor;\r#include\ngl_FragColor=color;\r#include\n#define CUSTOM_FRAGMENT_MAIN_END\n}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const spritesPixelShader = { name, shader };\n//# sourceMappingURL=sprites.fragment.js.map","\nimport { Buffer, VertexBuffer } from \"../Buffers/buffer.js\";\nimport { DrawWrapper } from \"../Materials/drawWrapper.js\";\nimport \"../Engines/Extensions/engine.alpha.js\";\nimport \"../Engines/Extensions/engine.dynamicBuffer.js\";\nimport \"../Shaders/sprites.fragment.js\";\nimport \"../Shaders/sprites.vertex.js\";\n/**\n * Class used to render sprites.\n *\n * It can be used either to render Sprites or ThinSprites with ThinEngine only.\n */\nexport class SpriteRenderer {\n /**\n * Gets the capacity of the manager\n */\n get capacity() {\n return this._capacity;\n }\n /**\n * Gets or sets a boolean indicating if the renderer must render sprites with pixel perfect rendering\n * Note that pixel perfect mode is not supported in WebGL 1\n */\n get pixelPerfect() {\n return this._pixelPerfect;\n }\n set pixelPerfect(value) {\n if (this._pixelPerfect === value) {\n return;\n }\n this._pixelPerfect = value;\n this._createEffects();\n }\n /**\n * Creates a new sprite Renderer\n * @param engine defines the engine the renderer works with\n * @param capacity defines the maximum allowed number of sprites\n * @param epsilon defines the epsilon value to align texture (0.01 by default)\n * @param scene defines the hosting scene\n */\n constructor(engine, capacity, epsilon = 0.01, scene = null) {\n /**\n * Blend mode use to render the particle, it can be any of\n * the static undefined properties provided in this class.\n * Default value is 2\n */\n this.blendMode = 2;\n /**\n * Gets or sets a boolean indicating if alpha mode is automatically\n * reset.\n */\n this.autoResetAlpha = true;\n /**\n * Disables writing to the depth buffer when rendering the sprites.\n * It can be handy to disable depth writing when using textures without alpha channel\n * and setting some specific blend modes.\n */\n this.disableDepthWrite = false;\n /**\n * Gets or sets a boolean indicating if the manager must consider scene fog when rendering\n */\n this.fogEnabled = true;\n this._pixelPerfect = false;\n this._useVAO = false;\n this._useInstancing = false;\n this._vertexBuffers = {};\n this._capacity = capacity;\n this._epsilon = epsilon;\n this._engine = engine;\n this._useInstancing = engine.getCaps().instancedArrays && engine._features.supportSpriteInstancing;\n this._useVAO = engine.getCaps().vertexArrayObject && !engine.disableVertexArrayObjects;\n this._scene = scene;\n if (!this._useInstancing) {\n this._buildIndexBuffer();\n }\n // VBO\n // 18 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellLeft, cellTop, cellWidth, cellHeight, color r, color g, color b, color a)\n // 16 when using instances\n this._vertexBufferSize = this._useInstancing ? 16 : 18;\n this._vertexData = new Float32Array(capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));\n this._buffer = new Buffer(engine, this._vertexData, true, this._vertexBufferSize);\n const positions = this._buffer.createVertexBuffer(VertexBuffer.PositionKind, 0, 4, this._vertexBufferSize, this._useInstancing);\n const options = this._buffer.createVertexBuffer(\"options\", 4, 2, this._vertexBufferSize, this._useInstancing);\n let offset = 6;\n let offsets;\n if (this._useInstancing) {\n const spriteData = new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]);\n this._spriteBuffer = new Buffer(engine, spriteData, false, 2);\n offsets = this._spriteBuffer.createVertexBuffer(\"offsets\", 0, 2);\n }\n else {\n offsets = this._buffer.createVertexBuffer(\"offsets\", offset, 2, this._vertexBufferSize, this._useInstancing);\n offset += 2;\n }\n const inverts = this._buffer.createVertexBuffer(\"inverts\", offset, 2, this._vertexBufferSize, this._useInstancing);\n const cellInfo = this._buffer.createVertexBuffer(\"cellInfo\", offset + 2, 4, this._vertexBufferSize, this._useInstancing);\n const colors = this._buffer.createVertexBuffer(VertexBuffer.ColorKind, offset + 6, 4, this._vertexBufferSize, this._useInstancing);\n this._vertexBuffers[VertexBuffer.PositionKind] = positions;\n this._vertexBuffers[\"options\"] = options;\n this._vertexBuffers[\"offsets\"] = offsets;\n this._vertexBuffers[\"inverts\"] = inverts;\n this._vertexBuffers[\"cellInfo\"] = cellInfo;\n this._vertexBuffers[VertexBuffer.ColorKind] = colors;\n this._createEffects();\n }\n _createEffects() {\n var _a, _b, _c, _d;\n (_a = this._drawWrapperBase) === null || _a === void 0 ? void 0 : _a.dispose();\n (_b = this._drawWrapperFog) === null || _b === void 0 ? void 0 : _b.dispose();\n (_c = this._drawWrapperDepth) === null || _c === void 0 ? void 0 : _c.dispose();\n (_d = this._drawWrapperFogDepth) === null || _d === void 0 ? void 0 : _d.dispose();\n this._drawWrapperBase = new DrawWrapper(this._engine);\n this._drawWrapperFog = new DrawWrapper(this._engine);\n this._drawWrapperDepth = new DrawWrapper(this._engine, false);\n this._drawWrapperFogDepth = new DrawWrapper(this._engine, false);\n if (this._drawWrapperBase.drawContext) {\n this._drawWrapperBase.drawContext.useInstancing = this._useInstancing;\n }\n if (this._drawWrapperFog.drawContext) {\n this._drawWrapperFog.drawContext.useInstancing = this._useInstancing;\n }\n if (this._drawWrapperDepth.drawContext) {\n this._drawWrapperDepth.drawContext.useInstancing = this._useInstancing;\n }\n if (this._drawWrapperFogDepth.drawContext) {\n this._drawWrapperFogDepth.drawContext.useInstancing = this._useInstancing;\n }\n const defines = this._pixelPerfect ? \"#define PIXEL_PERFECT\\n\" : \"\";\n this._drawWrapperBase.effect = this._engine.createEffect(\"sprites\", [VertexBuffer.PositionKind, \"options\", \"offsets\", \"inverts\", \"cellInfo\", VertexBuffer.ColorKind], [\"view\", \"projection\", \"textureInfos\", \"alphaTest\"], [\"diffuseSampler\"], defines);\n this._drawWrapperDepth.effect = this._drawWrapperBase.effect;\n this._drawWrapperDepth.materialContext = this._drawWrapperBase.materialContext;\n if (this._scene) {\n this._drawWrapperFog.effect = this._scene\n .getEngine()\n .createEffect(\"sprites\", [VertexBuffer.PositionKind, \"options\", \"offsets\", \"inverts\", \"cellInfo\", VertexBuffer.ColorKind], [\"view\", \"projection\", \"textureInfos\", \"alphaTest\", \"vFogInfos\", \"vFogColor\"], [\"diffuseSampler\"], defines + \"#define FOG\");\n this._drawWrapperFogDepth.effect = this._drawWrapperFog.effect;\n this._drawWrapperFogDepth.materialContext = this._drawWrapperFog.materialContext;\n }\n }\n /**\n * Render all child sprites\n * @param sprites defines the list of sprites to render\n * @param deltaTime defines the time since last frame\n * @param viewMatrix defines the viewMatrix to use to render the sprites\n * @param projectionMatrix defines the projectionMatrix to use to render the sprites\n * @param customSpriteUpdate defines a custom function to update the sprites data before they render\n */\n render(sprites, deltaTime, viewMatrix, projectionMatrix, customSpriteUpdate = null) {\n if (!this.texture || !this.texture.isReady() || !sprites.length) {\n return;\n }\n let drawWrapper = this._drawWrapperBase;\n let drawWrapperDepth = this._drawWrapperDepth;\n let shouldRenderFog = false;\n if (this.fogEnabled && this._scene && this._scene.fogEnabled && this._scene.fogMode !== 0) {\n drawWrapper = this._drawWrapperFog;\n drawWrapperDepth = this._drawWrapperFogDepth;\n shouldRenderFog = true;\n }\n const effect = drawWrapper.effect;\n // Check\n if (!effect.isReady()) {\n return;\n }\n const engine = this._engine;\n const useRightHandedSystem = !!(this._scene && this._scene.useRightHandedSystem);\n const baseSize = this.texture.getBaseSize();\n // Sprites\n const max = Math.min(this._capacity, sprites.length);\n let offset = 0;\n let noSprite = true;\n for (let index = 0; index < max; index++) {\n const sprite = sprites[index];\n if (!sprite || !sprite.isVisible) {\n continue;\n }\n noSprite = false;\n sprite._animate(deltaTime);\n this._appendSpriteVertex(offset++, sprite, 0, 0, baseSize, useRightHandedSystem, customSpriteUpdate);\n if (!this._useInstancing) {\n this._appendSpriteVertex(offset++, sprite, 1, 0, baseSize, useRightHandedSystem, customSpriteUpdate);\n this._appendSpriteVertex(offset++, sprite, 1, 1, baseSize, useRightHandedSystem, customSpriteUpdate);\n this._appendSpriteVertex(offset++, sprite, 0, 1, baseSize, useRightHandedSystem, customSpriteUpdate);\n }\n }\n if (noSprite) {\n return;\n }\n this._buffer.update(this._vertexData);\n const culling = !!engine.depthCullingState.cull;\n const zOffset = engine.depthCullingState.zOffset;\n const zOffsetUnits = engine.depthCullingState.zOffsetUnits;\n engine.setState(culling, zOffset, false, false, undefined, undefined, zOffsetUnits);\n // Render\n engine.enableEffect(drawWrapper);\n effect.setTexture(\"diffuseSampler\", this.texture);\n effect.setMatrix(\"view\", viewMatrix);\n effect.setMatrix(\"projection\", projectionMatrix);\n // Scene Info\n if (shouldRenderFog) {\n const scene = this._scene;\n // Fog\n effect.setFloat4(\"vFogInfos\", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);\n effect.setColor3(\"vFogColor\", scene.fogColor);\n }\n if (this._useVAO) {\n if (!this._vertexArrayObject) {\n this._vertexArrayObject = engine.recordVertexArrayObject(this._vertexBuffers, this._indexBuffer, effect);\n }\n engine.bindVertexArrayObject(this._vertexArrayObject, this._indexBuffer);\n }\n else {\n // VBOs\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);\n }\n // Draw order\n engine.depthCullingState.depthFunc = engine.useReverseDepthBuffer ? 518 : 515;\n if (!this.disableDepthWrite) {\n effect.setBool(\"alphaTest\", true);\n engine.setColorWrite(false);\n engine.enableEffect(drawWrapperDepth);\n if (this._useInstancing) {\n engine.drawArraysType(7, 0, 4, offset);\n }\n else {\n engine.drawElementsType(0, 0, (offset / 4) * 6);\n }\n engine.enableEffect(drawWrapper);\n engine.setColorWrite(true);\n effect.setBool(\"alphaTest\", false);\n }\n engine.setAlphaMode(this.blendMode);\n if (this._useInstancing) {\n engine.drawArraysType(7, 0, 4, offset);\n }\n else {\n engine.drawElementsType(0, 0, (offset / 4) * 6);\n }\n if (this.autoResetAlpha) {\n engine.setAlphaMode(0);\n }\n // Restore Right Handed\n if (useRightHandedSystem) {\n this._scene.getEngine().setState(culling, zOffset, false, true, undefined, undefined, zOffsetUnits);\n }\n engine.unbindInstanceAttributes();\n }\n _appendSpriteVertex(index, sprite, offsetX, offsetY, baseSize, useRightHandedSystem, customSpriteUpdate) {\n let arrayOffset = index * this._vertexBufferSize;\n if (offsetX === 0) {\n offsetX = this._epsilon;\n }\n else if (offsetX === 1) {\n offsetX = 1 - this._epsilon;\n }\n if (offsetY === 0) {\n offsetY = this._epsilon;\n }\n else if (offsetY === 1) {\n offsetY = 1 - this._epsilon;\n }\n if (customSpriteUpdate) {\n customSpriteUpdate(sprite, baseSize);\n }\n else {\n if (!sprite.cellIndex) {\n sprite.cellIndex = 0;\n }\n const rowSize = baseSize.width / this.cellWidth;\n const offset = (sprite.cellIndex / rowSize) >> 0;\n sprite._xOffset = ((sprite.cellIndex - offset * rowSize) * this.cellWidth) / baseSize.width;\n sprite._yOffset = (offset * this.cellHeight) / baseSize.height;\n sprite._xSize = this.cellWidth;\n sprite._ySize = this.cellHeight;\n }\n // Positions\n this._vertexData[arrayOffset] = sprite.position.x;\n this._vertexData[arrayOffset + 1] = sprite.position.y;\n this._vertexData[arrayOffset + 2] = sprite.position.z;\n this._vertexData[arrayOffset + 3] = sprite.angle;\n // Options\n this._vertexData[arrayOffset + 4] = sprite.width;\n this._vertexData[arrayOffset + 5] = sprite.height;\n if (!this._useInstancing) {\n this._vertexData[arrayOffset + 6] = offsetX;\n this._vertexData[arrayOffset + 7] = offsetY;\n }\n else {\n arrayOffset -= 2;\n }\n // Inverts according to Right Handed\n if (useRightHandedSystem) {\n this._vertexData[arrayOffset + 8] = sprite.invertU ? 0 : 1;\n }\n else {\n this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;\n }\n this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;\n this._vertexData[arrayOffset + 10] = sprite._xOffset;\n this._vertexData[arrayOffset + 11] = sprite._yOffset;\n this._vertexData[arrayOffset + 12] = sprite._xSize / baseSize.width;\n this._vertexData[arrayOffset + 13] = sprite._ySize / baseSize.height;\n // Color\n this._vertexData[arrayOffset + 14] = sprite.color.r;\n this._vertexData[arrayOffset + 15] = sprite.color.g;\n this._vertexData[arrayOffset + 16] = sprite.color.b;\n this._vertexData[arrayOffset + 17] = sprite.color.a;\n }\n _buildIndexBuffer() {\n const indices = [];\n let index = 0;\n for (let count = 0; count < this._capacity; count++) {\n indices.push(index);\n indices.push(index + 1);\n indices.push(index + 2);\n indices.push(index);\n indices.push(index + 2);\n indices.push(index + 3);\n index += 4;\n }\n this._indexBuffer = this._engine.createIndexBuffer(indices);\n }\n /**\n * Rebuilds the renderer (after a context lost, for eg)\n */\n rebuild() {\n var _a;\n if (this._indexBuffer) {\n this._buildIndexBuffer();\n }\n if (this._useVAO) {\n this._vertexArrayObject = undefined;\n }\n this._buffer._rebuild();\n for (const key in this._vertexBuffers) {\n const vertexBuffer = this._vertexBuffers[key];\n vertexBuffer._rebuild();\n }\n (_a = this._spriteBuffer) === null || _a === void 0 ? void 0 : _a._rebuild();\n }\n /**\n * Release associated resources\n */\n dispose() {\n if (this._buffer) {\n this._buffer.dispose();\n this._buffer = null;\n }\n if (this._spriteBuffer) {\n this._spriteBuffer.dispose();\n this._spriteBuffer = null;\n }\n if (this._indexBuffer) {\n this._engine._releaseBuffer(this._indexBuffer);\n this._indexBuffer = null;\n }\n if (this._vertexArrayObject) {\n this._engine.releaseVertexArrayObject(this._vertexArrayObject);\n this._vertexArrayObject = null;\n }\n if (this.texture) {\n this.texture.dispose();\n this.texture = null;\n }\n this._drawWrapperBase.dispose();\n this._drawWrapperFog.dispose();\n this._drawWrapperDepth.dispose();\n this._drawWrapperFogDepth.dispose();\n }\n}\n//# sourceMappingURL=spriteRenderer.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { Vector3, TmpVectors, Matrix } from \"../Maths/math.vector.js\";\nimport { Sprite } from \"./sprite.js\";\nimport { SpriteSceneComponent } from \"./spriteSceneComponent.js\";\nimport { PickingInfo } from \"../Collisions/pickingInfo.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { SceneComponentConstants } from \"../sceneComponent.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { Tools } from \"../Misc/tools.js\";\nimport { WebRequest } from \"../Misc/webRequest.js\";\nimport { SpriteRenderer } from \"./spriteRenderer.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n\n/**\n * Class used to manage multiple sprites on the same spritesheet\n * @see https://doc.babylonjs.com/features/featuresDeepDive/sprites\n */\nexport class SpriteManager {\n /**\n * Callback called when the manager is disposed\n */\n set onDispose(callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n }\n /**\n * Gets the array of sprites\n */\n get children() {\n return this.sprites;\n }\n /**\n * Gets the hosting scene\n */\n get scene() {\n return this._scene;\n }\n /**\n * Gets the capacity of the manager\n */\n get capacity() {\n return this._spriteRenderer.capacity;\n }\n /**\n * Gets or sets the spritesheet texture\n */\n get texture() {\n return this._spriteRenderer.texture;\n }\n set texture(value) {\n value.wrapU = Texture.CLAMP_ADDRESSMODE;\n value.wrapV = Texture.CLAMP_ADDRESSMODE;\n this._spriteRenderer.texture = value;\n this._textureContent = null;\n }\n /** Defines the default width of a cell in the spritesheet */\n get cellWidth() {\n return this._spriteRenderer.cellWidth;\n }\n set cellWidth(value) {\n this._spriteRenderer.cellWidth = value;\n }\n /** Defines the default height of a cell in the spritesheet */\n get cellHeight() {\n return this._spriteRenderer.cellHeight;\n }\n set cellHeight(value) {\n this._spriteRenderer.cellHeight = value;\n }\n /** Gets or sets a boolean indicating if the manager must consider scene fog when rendering */\n get fogEnabled() {\n return this._spriteRenderer.fogEnabled;\n }\n set fogEnabled(value) {\n this._spriteRenderer.fogEnabled = value;\n }\n /**\n * Blend mode use to render the particle, it can be any of\n * the static undefined properties provided in this class.\n * Default value is 2\n */\n get blendMode() {\n return this._spriteRenderer.blendMode;\n }\n set blendMode(blendMode) {\n this._spriteRenderer.blendMode = blendMode;\n }\n /** Disables writing to the depth buffer when rendering the sprites.\n * It can be handy to disable depth writing when using textures without alpha channel\n * and setting some specific blend modes.\n */\n get disableDepthWrite() {\n return this._disableDepthWrite;\n }\n set disableDepthWrite(value) {\n this._disableDepthWrite = value;\n this._spriteRenderer.disableDepthWrite = value;\n }\n /**\n * Gets or sets a boolean indicating if the renderer must render sprites with pixel perfect rendering\n * In this mode, sprites are rendered as \"pixel art\", which means that they appear as pixelated but remain stable when moving or when rotated or scaled.\n * Note that for this mode to work as expected, the sprite texture must use the BILINEAR sampling mode, not NEAREST!\n */\n get pixelPerfect() {\n return this._spriteRenderer.pixelPerfect;\n }\n set pixelPerfect(value) {\n this._spriteRenderer.pixelPerfect = value;\n if (value && this.texture.samplingMode !== 3) {\n this.texture.updateSamplingMode(3);\n }\n }\n /**\n * Creates a new sprite manager\n * @param name defines the manager's name\n * @param imgUrl defines the sprite sheet url\n * @param capacity defines the maximum allowed number of sprites\n * @param cellSize defines the size of a sprite cell\n * @param scene defines the hosting scene\n * @param epsilon defines the epsilon value to align texture (0.01 by default)\n * @param samplingMode defines the sampling mode to use with spritesheet\n * @param fromPacked set to false; do not alter\n * @param spriteJSON null otherwise a JSON object defining sprite sheet data; do not alter\n */\n constructor(\n /** defines the manager's name */\n name, imgUrl, capacity, cellSize, scene, epsilon = 0.01, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, fromPacked = false, spriteJSON = null) {\n this.name = name;\n /** Gets the list of sprites */\n this.sprites = new Array();\n /** Gets or sets the rendering group id (0 by default) */\n this.renderingGroupId = 0;\n /** Gets or sets camera layer mask */\n this.layerMask = 0x0fffffff;\n /** Gets or sets a boolean indicating if the sprites are pickable */\n this.isPickable = false;\n /**\n * Gets or sets an object used to store user defined information for the sprite manager\n */\n this.metadata = null;\n /** @internal */\n this._wasDispatched = false;\n /**\n * An event triggered when the manager is disposed.\n */\n this.onDisposeObservable = new Observable();\n this._disableDepthWrite = false;\n /** True when packed cell data from JSON file is ready*/\n this._packedAndReady = false;\n this._customUpdate = (sprite, baseSize) => {\n if (!sprite.cellRef) {\n sprite.cellIndex = 0;\n }\n const num = sprite.cellIndex;\n if (typeof num === \"number\" && isFinite(num) && Math.floor(num) === num) {\n sprite.cellRef = this._spriteMap[sprite.cellIndex];\n }\n sprite._xOffset = this._cellData[sprite.cellRef].frame.x / baseSize.width;\n sprite._yOffset = this._cellData[sprite.cellRef].frame.y / baseSize.height;\n sprite._xSize = this._cellData[sprite.cellRef].frame.w;\n sprite._ySize = this._cellData[sprite.cellRef].frame.h;\n };\n if (!scene) {\n scene = EngineStore.LastCreatedScene;\n }\n if (!scene._getComponent(SceneComponentConstants.NAME_SPRITE)) {\n scene._addComponent(new SpriteSceneComponent(scene));\n }\n this._fromPacked = fromPacked;\n this._scene = scene;\n const engine = this._scene.getEngine();\n this._spriteRenderer = new SpriteRenderer(engine, capacity, epsilon, scene);\n if (cellSize.width && cellSize.height) {\n this.cellWidth = cellSize.width;\n this.cellHeight = cellSize.height;\n }\n else if (cellSize !== undefined) {\n this.cellWidth = cellSize;\n this.cellHeight = cellSize;\n }\n else {\n this._spriteRenderer = null;\n return;\n }\n this._scene.spriteManagers && this._scene.spriteManagers.push(this);\n this.uniqueId = this.scene.getUniqueId();\n if (imgUrl) {\n this.texture = new Texture(imgUrl, scene, true, false, samplingMode);\n }\n if (this._fromPacked) {\n this._makePacked(imgUrl, spriteJSON);\n }\n }\n /**\n * Returns the string \"SpriteManager\"\n * @returns \"SpriteManager\"\n */\n getClassName() {\n return \"SpriteManager\";\n }\n _makePacked(imgUrl, spriteJSON) {\n if (spriteJSON !== null) {\n try {\n //Get the JSON and Check its structure. If its an array parse it if its a JSON string etc...\n let celldata;\n if (typeof spriteJSON === \"string\") {\n celldata = JSON.parse(spriteJSON);\n }\n else {\n celldata = spriteJSON;\n }\n if (celldata.frames.length) {\n const frametemp = {};\n for (let i = 0; i < celldata.frames.length; i++) {\n const _f = celldata.frames[i];\n if (typeof Object.keys(_f)[0] !== \"string\") {\n throw new Error(\"Invalid JSON Format. Check the frame values and make sure the name is the first parameter.\");\n }\n const name = _f[Object.keys(_f)[0]];\n frametemp[name] = _f;\n }\n celldata.frames = frametemp;\n }\n const spritemap = Reflect.ownKeys(celldata.frames);\n this._spriteMap = spritemap;\n this._packedAndReady = true;\n this._cellData = celldata.frames;\n }\n catch (e) {\n this._fromPacked = false;\n this._packedAndReady = false;\n throw new Error(\"Invalid JSON from string. Spritesheet managed with constant cell size.\");\n }\n }\n else {\n const re = /\\./g;\n let li;\n do {\n li = re.lastIndex;\n re.test(imgUrl);\n } while (re.lastIndex > 0);\n const jsonUrl = imgUrl.substring(0, li - 1) + \".json\";\n const onerror = () => {\n Logger.Error(\"JSON ERROR: Unable to load JSON file.\");\n this._fromPacked = false;\n this._packedAndReady = false;\n };\n const onload = (data) => {\n try {\n const celldata = JSON.parse(data);\n const spritemap = Reflect.ownKeys(celldata.frames);\n this._spriteMap = spritemap;\n this._packedAndReady = true;\n this._cellData = celldata.frames;\n }\n catch (e) {\n this._fromPacked = false;\n this._packedAndReady = false;\n throw new Error(\"Invalid JSON format. Please check documentation for format specifications.\");\n }\n };\n Tools.LoadFile(jsonUrl, onload, undefined, undefined, false, onerror);\n }\n }\n _checkTextureAlpha(sprite, ray, distance, min, max) {\n if (!sprite.useAlphaForPicking || !this.texture) {\n return true;\n }\n const textureSize = this.texture.getSize();\n if (!this._textureContent) {\n this._textureContent = new Uint8Array(textureSize.width * textureSize.height * 4);\n this.texture.readPixels(0, 0, this._textureContent);\n }\n const contactPoint = TmpVectors.Vector3[0];\n contactPoint.copyFrom(ray.direction);\n contactPoint.normalize();\n contactPoint.scaleInPlace(distance);\n contactPoint.addInPlace(ray.origin);\n const contactPointU = (contactPoint.x - min.x) / (max.x - min.x);\n const contactPointV = 1.0 - (contactPoint.y - min.y) / (max.y - min.y);\n const u = (sprite._xOffset * textureSize.width + contactPointU * sprite._xSize) | 0;\n const v = (sprite._yOffset * textureSize.height + contactPointV * sprite._ySize) | 0;\n const alpha = this._textureContent[(u + v * textureSize.width) * 4 + 3];\n return alpha > 0.5;\n }\n /**\n * Intersects the sprites with a ray\n * @param ray defines the ray to intersect with\n * @param camera defines the current active camera\n * @param predicate defines a predicate used to select candidate sprites\n * @param fastCheck defines if a fast check only must be done (the first potential sprite is will be used and not the closer)\n * @returns null if no hit or a PickingInfo\n */\n intersects(ray, camera, predicate, fastCheck) {\n const count = Math.min(this.capacity, this.sprites.length);\n const min = Vector3.Zero();\n const max = Vector3.Zero();\n let distance = Number.MAX_VALUE;\n let currentSprite = null;\n const pickedPoint = TmpVectors.Vector3[0];\n const cameraSpacePosition = TmpVectors.Vector3[1];\n const cameraView = camera.getViewMatrix();\n let activeRay = ray;\n let pickedRay = ray;\n for (let index = 0; index < count; index++) {\n const sprite = this.sprites[index];\n if (!sprite) {\n continue;\n }\n if (predicate) {\n if (!predicate(sprite)) {\n continue;\n }\n }\n else if (!sprite.isPickable) {\n continue;\n }\n Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);\n if (sprite.angle) {\n // Create a rotation matrix to rotate the ray to the sprite's rotation\n Matrix.TranslationToRef(-cameraSpacePosition.x, -cameraSpacePosition.y, 0, TmpVectors.Matrix[1]);\n Matrix.TranslationToRef(cameraSpacePosition.x, cameraSpacePosition.y, 0, TmpVectors.Matrix[2]);\n Matrix.RotationZToRef(-sprite.angle, TmpVectors.Matrix[3]);\n // inv translation x rotation x translation\n TmpVectors.Matrix[1].multiplyToRef(TmpVectors.Matrix[3], TmpVectors.Matrix[4]);\n TmpVectors.Matrix[4].multiplyToRef(TmpVectors.Matrix[2], TmpVectors.Matrix[0]);\n activeRay = ray.clone();\n Vector3.TransformCoordinatesToRef(ray.origin, TmpVectors.Matrix[0], activeRay.origin);\n Vector3.TransformNormalToRef(ray.direction, TmpVectors.Matrix[0], activeRay.direction);\n }\n else {\n activeRay = ray;\n }\n min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);\n max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);\n if (activeRay.intersectsBoxMinMax(min, max)) {\n const currentDistance = Vector3.Distance(cameraSpacePosition, activeRay.origin);\n if (distance > currentDistance) {\n if (!this._checkTextureAlpha(sprite, activeRay, currentDistance, min, max)) {\n continue;\n }\n pickedRay = activeRay;\n distance = currentDistance;\n currentSprite = sprite;\n if (fastCheck) {\n break;\n }\n }\n }\n }\n if (currentSprite) {\n const result = new PickingInfo();\n cameraView.invertToRef(TmpVectors.Matrix[0]);\n result.hit = true;\n result.pickedSprite = currentSprite;\n result.distance = distance;\n // Get picked point\n const direction = TmpVectors.Vector3[2];\n direction.copyFrom(pickedRay.direction);\n direction.normalize();\n direction.scaleInPlace(distance);\n pickedRay.origin.addToRef(direction, pickedPoint);\n result.pickedPoint = Vector3.TransformCoordinates(pickedPoint, TmpVectors.Matrix[0]);\n return result;\n }\n return null;\n }\n /**\n * Intersects the sprites with a ray\n * @param ray defines the ray to intersect with\n * @param camera defines the current active camera\n * @param predicate defines a predicate used to select candidate sprites\n * @returns null if no hit or a PickingInfo array\n */\n multiIntersects(ray, camera, predicate) {\n const count = Math.min(this.capacity, this.sprites.length);\n const min = Vector3.Zero();\n const max = Vector3.Zero();\n let distance;\n const results = [];\n const pickedPoint = TmpVectors.Vector3[0].copyFromFloats(0, 0, 0);\n const cameraSpacePosition = TmpVectors.Vector3[1].copyFromFloats(0, 0, 0);\n const cameraView = camera.getViewMatrix();\n for (let index = 0; index < count; index++) {\n const sprite = this.sprites[index];\n if (!sprite) {\n continue;\n }\n if (predicate) {\n if (!predicate(sprite)) {\n continue;\n }\n }\n else if (!sprite.isPickable) {\n continue;\n }\n Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);\n min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);\n max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);\n if (ray.intersectsBoxMinMax(min, max)) {\n distance = Vector3.Distance(cameraSpacePosition, ray.origin);\n if (!this._checkTextureAlpha(sprite, ray, distance, min, max)) {\n continue;\n }\n const result = new PickingInfo();\n results.push(result);\n cameraView.invertToRef(TmpVectors.Matrix[0]);\n result.hit = true;\n result.pickedSprite = sprite;\n result.distance = distance;\n // Get picked point\n const direction = TmpVectors.Vector3[2];\n direction.copyFrom(ray.direction);\n direction.normalize();\n direction.scaleInPlace(distance);\n ray.origin.addToRef(direction, pickedPoint);\n result.pickedPoint = Vector3.TransformCoordinates(pickedPoint, TmpVectors.Matrix[0]);\n }\n }\n return results;\n }\n /**\n * Render all child sprites\n */\n render() {\n // Check\n if (this._fromPacked && (!this._packedAndReady || !this._spriteMap || !this._cellData)) {\n return;\n }\n const engine = this._scene.getEngine();\n const deltaTime = engine.getDeltaTime();\n if (this._packedAndReady) {\n this._spriteRenderer.render(this.sprites, deltaTime, this._scene.getViewMatrix(), this._scene.getProjectionMatrix(), this._customUpdate);\n }\n else {\n this._spriteRenderer.render(this.sprites, deltaTime, this._scene.getViewMatrix(), this._scene.getProjectionMatrix());\n }\n }\n /**\n * Rebuilds the manager (after a context lost, for eg)\n */\n rebuild() {\n var _a;\n (_a = this._spriteRenderer) === null || _a === void 0 ? void 0 : _a.rebuild();\n }\n /**\n * Release associated resources\n */\n dispose() {\n if (this._spriteRenderer) {\n this._spriteRenderer.dispose();\n this._spriteRenderer = null;\n }\n this._textureContent = null;\n // Remove from scene\n if (this._scene.spriteManagers) {\n const index = this._scene.spriteManagers.indexOf(this);\n this._scene.spriteManagers.splice(index, 1);\n }\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n this.metadata = null;\n }\n /**\n * Serializes the sprite manager to a JSON object\n * @param serializeTexture defines if the texture must be serialized as well\n * @returns the JSON object\n */\n serialize(serializeTexture = false) {\n const serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.capacity = this.capacity;\n serializationObject.cellWidth = this.cellWidth;\n serializationObject.cellHeight = this.cellHeight;\n serializationObject.fogEnabled = this.fogEnabled;\n serializationObject.blendMode = this.blendMode;\n serializationObject.disableDepthWrite = this.disableDepthWrite;\n serializationObject.pixelPerfect = this.pixelPerfect;\n if (this.texture) {\n if (serializeTexture) {\n serializationObject.texture = this.texture.serialize();\n }\n else {\n serializationObject.textureUrl = this.texture.name;\n serializationObject.invertY = this.texture._invertY;\n }\n }\n serializationObject.sprites = [];\n for (const sprite of this.sprites) {\n serializationObject.sprites.push(sprite.serialize());\n }\n serializationObject.metadata = this.metadata;\n return serializationObject;\n }\n /**\n * Parses a JSON object to create a new sprite manager.\n * @param parsedManager The JSON object to parse\n * @param scene The scene to create the sprite manager\n * @param rootUrl The root url to use to load external dependencies like texture\n * @returns the new sprite manager\n */\n static Parse(parsedManager, scene, rootUrl) {\n const manager = new SpriteManager(parsedManager.name, \"\", parsedManager.capacity, {\n width: parsedManager.cellWidth,\n height: parsedManager.cellHeight,\n }, scene);\n if (parsedManager.fogEnabled !== undefined) {\n manager.fogEnabled = parsedManager.fogEnabled;\n }\n if (parsedManager.blendMode !== undefined) {\n manager.blendMode = parsedManager.blendMode;\n }\n if (parsedManager.disableDepthWrite !== undefined) {\n manager.disableDepthWrite = parsedManager.disableDepthWrite;\n }\n if (parsedManager.pixelPerfect !== undefined) {\n manager.pixelPerfect = parsedManager.pixelPerfect;\n }\n if (parsedManager.metadata !== undefined) {\n manager.metadata = parsedManager.metadata;\n }\n if (parsedManager.texture) {\n manager.texture = Texture.Parse(parsedManager.texture, scene, rootUrl);\n }\n else if (parsedManager.textureName) {\n manager.texture = new Texture(rootUrl + parsedManager.textureUrl, scene, false, parsedManager.invertY !== undefined ? parsedManager.invertY : true);\n }\n for (const parsedSprite of parsedManager.sprites) {\n Sprite.Parse(parsedSprite, manager);\n }\n return manager;\n }\n /**\n * Creates a sprite manager from a snippet saved in a remote file\n * @param name defines the name of the sprite manager to create (can be null or empty to use the one from the json data)\n * @param url defines the url to load from\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @returns a promise that will resolve to the new sprite manager\n */\n static ParseFromFileAsync(name, url, scene, rootUrl = \"\") {\n return new Promise((resolve, reject) => {\n const request = new WebRequest();\n request.addEventListener(\"readystatechange\", () => {\n if (request.readyState == 4) {\n if (request.status == 200) {\n const serializationObject = JSON.parse(request.responseText);\n const output = SpriteManager.Parse(serializationObject, scene || EngineStore.LastCreatedScene, rootUrl);\n if (name) {\n output.name = name;\n }\n resolve(output);\n }\n else {\n reject(\"Unable to load the sprite manager\");\n }\n }\n });\n request.open(\"GET\", url);\n request.send();\n });\n }\n /**\n * Creates a sprite manager from a snippet saved by the sprite editor\n * @param snippetId defines the snippet to load (can be set to _BLANK to create a default one)\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @returns a promise that will resolve to the new sprite manager\n */\n static ParseFromSnippetAsync(snippetId, scene, rootUrl = \"\") {\n if (snippetId === \"_BLANK\") {\n return Promise.resolve(new SpriteManager(\"Default sprite manager\", \"//playground.babylonjs.com/textures/player.png\", 500, 64, scene));\n }\n return new Promise((resolve, reject) => {\n const request = new WebRequest();\n request.addEventListener(\"readystatechange\", () => {\n if (request.readyState == 4) {\n if (request.status == 200) {\n const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload);\n const serializationObject = JSON.parse(snippet.spriteManager);\n const output = SpriteManager.Parse(serializationObject, scene || EngineStore.LastCreatedScene, rootUrl);\n output.snippetId = snippetId;\n resolve(output);\n }\n else {\n reject(\"Unable to load the snippet \" + snippetId);\n }\n }\n });\n request.open(\"GET\", this.SnippetUrl + \"/\" + snippetId.replace(/#/g, \"/\"));\n request.send();\n });\n }\n}\n/** Define the Url to load snippets */\nSpriteManager.SnippetUrl = `https://snippet.babylonjs.com`;\n/**\n * Creates a sprite manager from a snippet saved by the sprite editor\n * @deprecated Please use ParseFromSnippetAsync instead\n * @param snippetId defines the snippet to load (can be set to _BLANK to create a default one)\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures and relative dependencies\n * @returns a promise that will resolve to the new sprite manager\n */\nSpriteManager.CreateFromSnippetAsync = SpriteManager.ParseFromSnippetAsync;\n//# sourceMappingURL=spriteManager.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"spriteMapPixelShader\";\nconst shader = `#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE)\n#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l)\n#else\n#define TEXTUREFUNC(s,c,b) texture2D(s,c,b)\n#endif\nprecision highp float;\rvarying vec3 vPosition;\rvarying vec2 vUV;\rvarying vec2 tUV;\runiform float time;\runiform float spriteCount;\runiform sampler2D spriteSheet;\runiform vec2 spriteMapSize;\runiform vec2 outputSize;\runiform vec2 stageSize;\runiform sampler2D frameMap;\runiform sampler2D tileMaps[LAYERS];\runiform sampler2D animationMap;\runiform vec3 colorMul;\rfloat mt;\rconst float fdStep=1./4.;\rconst float aFrameSteps=1./MAX_ANIMATION_FRAMES;\rmat4 getFrameData(float frameID){\rfloat fX=frameID/spriteCount;\rreturn mat4(\rtexture2D(frameMap,vec2(fX,0.),0.),\rtexture2D(frameMap,vec2(fX,fdStep*1.),0.),\rtexture2D(frameMap,vec2(fX,fdStep*2.),0.),\rvec4(0.)\r);\r}\rvoid main(){\rvec4 color=vec4(0.);\rvec2 tileUV=fract(tUV);\r#ifdef FLIPU\ntileUV.y=1.0-tileUV.y;\r#endif\nvec2 tileID=floor(tUV);\rvec2 sheetUnits=1./spriteMapSize;\rfloat spriteUnits=1./spriteCount;\rvec2 stageUnits=1./stageSize;\rfor(int i=0; i0.) {\rmt=mod(time*animationData.z,1.0);\rfor(float f=0.; fmt){\rframeID=animationData.x;\rbreak;\r}\ranimationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.);\r}\r}\rmat4 frameData=getFrameData(frameID+0.5);\rvec2 frameSize=(frameData[0].zw)/spriteMapSize;\rvec2 offset=frameData[0].xy*sheetUnits;\rvec2 ratio=frameData[2].xy/frameData[0].zw;\rif (frameData[2].z==1.){\rtileUV.xy=tileUV.yx;\r}\rvec4 nc=texture2D(spriteSheet,tileUV*frameSize+offset);\rif (i==0){\rcolor=nc;\r} else {\rfloat alpha=min(color.a+nc.a,1.0);\rvec3 mixed=mix(color.xyz,nc.xyz,nc.a);\rcolor=vec4(mixed,alpha);\r}\r}\rcolor.xyz*=colorMul;\rgl_FragColor=color;\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const spriteMapPixelShader = { name, shader };\n//# sourceMappingURL=spriteMap.fragment.js.map","// Do not edit.\nimport { ShaderStore } from \"../Engines/shaderStore.js\";\nconst name = \"spriteMapVertexShader\";\nconst shader = `precision highp float;\rattribute vec3 position;\rattribute vec3 normal;\rattribute vec2 uv;\rvarying vec3 vPosition;\rvarying vec2 vUV;\rvarying vec2 tUV;\rvarying vec2 stageUnits;\rvarying vec2 levelUnits;\rvarying vec2 tileID;\runiform float time;\runiform mat4 worldViewProjection;\runiform vec2 outputSize;\runiform vec2 stageSize;\runiform vec2 spriteMapSize;\runiform float stageScale;\rvoid main() {\rvec4 p=vec4( position,1. );\rvPosition=p.xyz;\rvUV=uv;\rtUV=uv*stageSize; \rgl_Position=worldViewProjection*p;\r}`;\n// Sideeffect\nShaderStore.ShadersStore[name] = shader;\n/** @internal */\nexport const spriteMapVertexShader = { name, shader };\n//# sourceMappingURL=spriteMap.vertex.js.map","import { Engine } from \"../Engines/engine.js\";\nimport { Vector2, Vector3 } from \"../Maths/math.vector.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { RawTexture } from \"../Materials/Textures/rawTexture.js\";\nimport { ShaderMaterial } from \"../Materials/shaderMaterial.js\";\nimport { Effect } from \"../Materials/effect.js\";\nimport { CreatePlane } from \"../Meshes/Builders/planeBuilder.js\";\nimport \"../Shaders/spriteMap.fragment.js\";\nimport \"../Shaders/spriteMap.vertex.js\";\n/**\n * Class used to manage a grid restricted sprite deployment on an Output plane.\n */\nexport class SpriteMap {\n /** Returns the Number of Sprites in the System */\n get spriteCount() {\n return this.sprites.length;\n }\n /** Returns the Position of Output Plane*/\n get position() {\n return this._output.position;\n }\n /** Returns the Position of Output Plane*/\n set position(v) {\n this._output.position = v;\n }\n /** Returns the Rotation of Output Plane*/\n get rotation() {\n return this._output.rotation;\n }\n /** Returns the Rotation of Output Plane*/\n set rotation(v) {\n this._output.rotation = v;\n }\n /** Sets the AnimationMap*/\n get animationMap() {\n return this._animationMap;\n }\n /** Sets the AnimationMap*/\n set animationMap(v) {\n const buffer = v._texture._bufferView;\n const am = this._createTileAnimationBuffer(buffer);\n this._animationMap.dispose();\n this._animationMap = am;\n this._material.setTexture(\"animationMap\", this._animationMap);\n }\n /**\n * Creates a new SpriteMap\n * @param name defines the SpriteMaps Name\n * @param atlasJSON is the JSON file that controls the Sprites Frames and Meta\n * @param spriteSheet is the Texture that the Sprites are on.\n * @param options a basic deployment configuration\n * @param scene The Scene that the map is deployed on\n */\n constructor(name, atlasJSON, spriteSheet, options, scene) {\n this.name = name;\n this.sprites = [];\n this.atlasJSON = atlasJSON;\n this.sprites = this.atlasJSON[\"frames\"];\n this.spriteSheet = spriteSheet;\n /**\n * Run through the options and set what ever defaults are needed that where not declared.\n */\n this.options = options;\n options.stageSize = options.stageSize || new Vector2(1, 1);\n options.outputSize = options.outputSize || options.stageSize;\n options.outputPosition = options.outputPosition || Vector3.Zero();\n options.outputRotation = options.outputRotation || Vector3.Zero();\n options.layerCount = options.layerCount || 1;\n options.maxAnimationFrames = options.maxAnimationFrames || 0;\n options.baseTile = options.baseTile || 0;\n options.flipU = options.flipU || false;\n options.colorMultiply = options.colorMultiply || new Vector3(1, 1, 1);\n this._scene = scene;\n this._frameMap = this._createFrameBuffer();\n this._tileMaps = new Array();\n for (let i = 0; i < options.layerCount; i++) {\n this._tileMaps.push(this._createTileBuffer(null, i));\n }\n this._animationMap = this._createTileAnimationBuffer(null);\n const defines = [];\n defines.push(\"#define LAYERS \" + options.layerCount);\n if (options.flipU) {\n defines.push(\"#define FLIPU\");\n }\n defines.push(`#define MAX_ANIMATION_FRAMES ${options.maxAnimationFrames}.0`);\n const shaderString = Effect.ShadersStore[\"spriteMapPixelShader\"];\n let layerSampleString;\n if (!scene.getEngine()._features.supportSwitchCaseInShader) {\n layerSampleString = \"\";\n for (let i = 0; i < options.layerCount; i++) {\n layerSampleString += `if (${i} == i) { frameID = texture2D(tileMaps[${i}], (tileID + 0.5) / stageSize, 0.).x; }`;\n }\n }\n else {\n layerSampleString = \"switch(i) {\";\n for (let i = 0; i < options.layerCount; i++) {\n layerSampleString += \"case \" + i + \" : frameID = texture(tileMaps[\" + i + \"], (tileID + 0.5) / stageSize, 0.).x;\";\n layerSampleString += \"break;\";\n }\n layerSampleString += \"}\";\n }\n Effect.ShadersStore[\"spriteMap\" + this.name + \"PixelShader\"] = shaderString.replace(\"#define LAYER_ID_SWITCH\", layerSampleString);\n this._material = new ShaderMaterial(\"spriteMap:\" + this.name, this._scene, {\n vertex: \"spriteMap\",\n fragment: \"spriteMap\" + this.name,\n }, {\n defines,\n attributes: [\"position\", \"normal\", \"uv\"],\n uniforms: [\"worldViewProjection\", \"time\", \"stageSize\", \"outputSize\", \"spriteMapSize\", \"spriteCount\", \"time\", \"colorMul\", \"mousePosition\", \"curTile\", \"flipU\"],\n samplers: [\"spriteSheet\", \"frameMap\", \"tileMaps\", \"animationMap\"],\n needAlphaBlending: true,\n });\n this._time = 0;\n this._material.setFloat(\"spriteCount\", this.spriteCount);\n this._material.setVector2(\"stageSize\", options.stageSize);\n this._material.setVector2(\"outputSize\", options.outputSize);\n this._material.setTexture(\"spriteSheet\", this.spriteSheet);\n this._material.setVector2(\"spriteMapSize\", new Vector2(1, 1));\n this._material.setVector3(\"colorMul\", options.colorMultiply);\n let tickSave = 0;\n const bindSpriteTexture = () => {\n if (this.spriteSheet && this.spriteSheet.isReady()) {\n if (this.spriteSheet._texture) {\n this._material.setVector2(\"spriteMapSize\", new Vector2(this.spriteSheet._texture.baseWidth || 1, this.spriteSheet._texture.baseHeight || 1));\n return;\n }\n }\n if (tickSave < 100) {\n setTimeout(() => {\n tickSave++;\n bindSpriteTexture();\n }, 100);\n }\n };\n bindSpriteTexture();\n this._material.setVector3(\"colorMul\", options.colorMultiply);\n this._material.setTexture(\"frameMap\", this._frameMap);\n this._material.setTextureArray(\"tileMaps\", this._tileMaps);\n this._material.setTexture(\"animationMap\", this._animationMap);\n this._material.setFloat(\"time\", this._time);\n this._output = CreatePlane(name + \":output\", { size: 1, updatable: true }, scene);\n this._output.scaling.x = options.outputSize.x;\n this._output.scaling.y = options.outputSize.y;\n this.position = options.outputPosition;\n this.rotation = options.outputRotation;\n const obfunction = () => {\n this._time += this._scene.getEngine().getDeltaTime();\n this._material.setFloat(\"time\", this._time);\n };\n this._scene.onBeforeRenderObservable.add(obfunction);\n this._output.material = this._material;\n }\n /**\n * Returns tileID location\n * @returns Vector2 the cell position ID\n */\n getTileID() {\n const p = this.getMousePosition();\n p.multiplyInPlace(this.options.stageSize || Vector2.Zero());\n p.x = Math.floor(p.x);\n p.y = Math.floor(p.y);\n return p;\n }\n /**\n * Gets the UV location of the mouse over the SpriteMap.\n * @returns Vector2 the UV position of the mouse interaction\n */\n getMousePosition() {\n const out = this._output;\n const pickinfo = this._scene.pick(this._scene.pointerX, this._scene.pointerY, (mesh) => {\n if (mesh !== out) {\n return false;\n }\n return true;\n });\n if (!pickinfo || !pickinfo.hit || !pickinfo.getTextureCoordinates) {\n return new Vector2(-1, -1);\n }\n const coords = pickinfo.getTextureCoordinates();\n if (coords) {\n return coords;\n }\n return new Vector2(-1, -1);\n }\n /**\n * Creates the \"frame\" texture Buffer\n * -------------------------------------\n * Structure of frames\n * \"filename\": \"Falling-Water-2.png\",\n * \"frame\": {\"x\":69,\"y\":103,\"w\":24,\"h\":32},\n * \"rotated\": true,\n * \"trimmed\": true,\n * \"spriteSourceSize\": {\"x\":4,\"y\":0,\"w\":24,\"h\":32},\n * \"sourceSize\": {\"w\":32,\"h\":32}\n * @returns RawTexture of the frameMap\n */\n _createFrameBuffer() {\n const data = new Array();\n //Do two Passes\n for (let i = 0; i < this.spriteCount; i++) {\n data.push(0, 0, 0, 0); //frame\n data.push(0, 0, 0, 0); //spriteSourceSize\n data.push(0, 0, 0, 0); //sourceSize, rotated, trimmed\n data.push(0, 0, 0, 0); //Keep it pow2 cause I\"m cool like that... it helps with sampling accuracy as well. Plus then we have 4 other parameters for future stuff.\n }\n //Second Pass\n for (let i = 0; i < this.spriteCount; i++) {\n const f = this.sprites[i][\"frame\"];\n const sss = this.sprites[i][\"spriteSourceSize\"];\n const ss = this.sprites[i][\"sourceSize\"];\n const r = this.sprites[i][\"rotated\"] ? 1 : 0;\n const t = this.sprites[i][\"trimmed\"] ? 1 : 0;\n //frame\n data[i * 4] = f.x;\n data[i * 4 + 1] = f.y;\n data[i * 4 + 2] = f.w;\n data[i * 4 + 3] = f.h;\n //spriteSourceSize\n data[i * 4 + this.spriteCount * 4] = sss.x;\n data[i * 4 + 1 + this.spriteCount * 4] = sss.y;\n data[i * 4 + 3 + this.spriteCount * 4] = sss.h;\n //sourceSize, rotated, trimmed\n data[i * 4 + this.spriteCount * 8] = ss.w;\n data[i * 4 + 1 + this.spriteCount * 8] = ss.h;\n data[i * 4 + 2 + this.spriteCount * 8] = r;\n data[i * 4 + 3 + this.spriteCount * 8] = t;\n }\n const floatArray = new Float32Array(data);\n const t = RawTexture.CreateRGBATexture(floatArray, this.spriteCount, 4, this._scene, false, false, Texture.NEAREST_NEAREST, Engine.TEXTURETYPE_FLOAT);\n return t;\n }\n /**\n * Creates the tileMap texture Buffer\n * @param buffer normally and array of numbers, or a false to generate from scratch\n * @param _layer indicates what layer for a logic trigger dealing with the baseTile. The system uses this\n * @returns RawTexture of the tileMap\n */\n _createTileBuffer(buffer, _layer = 0) {\n let data = new Array();\n const _ty = this.options.stageSize.y || 0;\n const _tx = this.options.stageSize.x || 0;\n if (!buffer) {\n let bt = this.options.baseTile;\n if (_layer != 0) {\n bt = 0;\n }\n for (let y = 0; y < _ty; y++) {\n for (let x = 0; x < _tx * 4; x += 4) {\n data.push(bt, 0, 0, 0);\n }\n }\n }\n else {\n data = buffer;\n }\n const floatArray = new Float32Array(data);\n const t = RawTexture.CreateRGBATexture(floatArray, _tx, _ty, this._scene, false, false, Texture.NEAREST_NEAREST, Engine.TEXTURETYPE_FLOAT);\n return t;\n }\n /**\n * Modifies the data of the tileMaps\n * @param _layer is the ID of the layer you want to edit on the SpriteMap\n * @param pos is the iVector2 Coordinates of the Tile\n * @param tile The SpriteIndex of the new Tile\n */\n changeTiles(_layer = 0, pos, tile = 0) {\n const buffer = this._tileMaps[_layer]._texture._bufferView;\n if (buffer === null) {\n return;\n }\n let p = new Array();\n if (pos instanceof Vector2) {\n p.push(pos);\n }\n else {\n p = pos;\n }\n const _tx = this.options.stageSize.x || 0;\n for (let i = 0; i < p.length; i++) {\n const _p = p[i];\n _p.x = Math.floor(_p.x);\n _p.y = Math.floor(_p.y);\n const id = _p.x * 4 + _p.y * (_tx * 4);\n buffer[id] = tile;\n }\n const t = this._createTileBuffer(buffer);\n this._tileMaps[_layer].dispose();\n this._tileMaps[_layer] = t;\n this._material.setTextureArray(\"tileMap\", this._tileMaps);\n }\n /**\n * Creates the animationMap texture Buffer\n * @param buffer normally and array of numbers, or a false to generate from scratch\n * @returns RawTexture of the animationMap\n */\n _createTileAnimationBuffer(buffer) {\n const data = new Array();\n let floatArray;\n if (!buffer) {\n for (let i = 0; i < this.spriteCount; i++) {\n data.push(0, 0, 0, 0);\n let count = 1;\n while (count < (this.options.maxAnimationFrames || 4)) {\n data.push(0, 0, 0, 0);\n count++;\n }\n }\n floatArray = new Float32Array(data);\n }\n else {\n floatArray = buffer;\n }\n const t = RawTexture.CreateRGBATexture(floatArray, this.spriteCount, this.options.maxAnimationFrames || 4, this._scene, false, false, Texture.NEAREST_NEAREST, Engine.TEXTURETYPE_FLOAT);\n return t;\n }\n /**\n * Modifies the data of the animationMap\n * @param cellID is the Index of the Sprite\n * @param _frame is the target Animation frame\n * @param toCell is the Target Index of the next frame of the animation\n * @param time is a value between 0-1 that is the trigger for when the frame should change tiles\n * @param speed is a global scalar of the time variable on the map.\n */\n addAnimationToTile(cellID = 0, _frame = 0, toCell = 0, time = 0, speed = 1) {\n const buffer = this._animationMap._texture._bufferView;\n const id = cellID * 4 + this.spriteCount * 4 * _frame;\n if (!buffer) {\n return;\n }\n buffer[id] = toCell;\n buffer[id + 1] = time;\n buffer[id + 2] = speed;\n const t = this._createTileAnimationBuffer(buffer);\n this._animationMap.dispose();\n this._animationMap = t;\n this._material.setTexture(\"animationMap\", this._animationMap);\n }\n /**\n * Exports the .tilemaps file\n */\n saveTileMaps() {\n let maps = \"\";\n for (let i = 0; i < this._tileMaps.length; i++) {\n if (i > 0) {\n maps += \"\\n\\r\";\n }\n maps += this._tileMaps[i]._texture._bufferView.toString();\n }\n const hiddenElement = document.createElement(\"a\");\n hiddenElement.href = \"data:octet/stream;charset=utf-8,\" + encodeURI(maps);\n hiddenElement.target = \"_blank\";\n hiddenElement.download = this.name + \".tilemaps\";\n hiddenElement.click();\n hiddenElement.remove();\n }\n /**\n * Imports the .tilemaps file\n * @param url of the .tilemaps file\n */\n loadTileMaps(url) {\n const xhr = new XMLHttpRequest();\n xhr.open(\"GET\", url);\n const _lc = this.options.layerCount || 0;\n xhr.onload = () => {\n const data = xhr.response.split(\"\\n\\r\");\n for (let i = 0; i < _lc; i++) {\n const d = data[i].split(\",\").map(Number);\n const t = this._createTileBuffer(d);\n this._tileMaps[i].dispose();\n this._tileMaps[i] = t;\n }\n this._material.setTextureArray(\"tileMap\", this._tileMaps);\n };\n xhr.send();\n }\n /**\n * Release associated resources\n */\n dispose() {\n this._output.dispose();\n this._material.dispose();\n this._animationMap.dispose();\n this._tileMaps.forEach((tm) => {\n tm.dispose();\n });\n this._frameMap.dispose();\n }\n}\n//# sourceMappingURL=spriteMap.js.map","import { SpriteManager } from \"./spriteManager.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\n/**\n * Class used to manage multiple sprites of different sizes on the same spritesheet\n * @see https://doc.babylonjs.com/features/featuresDeepDive/sprites\n */\nexport class SpritePackedManager extends SpriteManager {\n /**\n * Creates a new sprite manager from a packed sprite sheet\n * @param name defines the manager's name\n * @param imgUrl defines the sprite sheet url\n * @param capacity defines the maximum allowed number of sprites\n * @param scene defines the hosting scene\n * @param spriteJSON null otherwise a JSON object defining sprite sheet data\n * @param epsilon defines the epsilon value to align texture (0.01 by default)\n * @param samplingMode defines the sampling mode to use with spritesheet\n * @param fromPacked set to true; do not alter\n */\n constructor(\n /** defines the packed manager's name */\n name, imgUrl, capacity, scene, spriteJSON = null, epsilon = 0.01, samplingMode = Texture.TRILINEAR_SAMPLINGMODE) {\n //the cellSize parameter is not used when built from JSON which provides individual cell data, defaults to 64 if JSON load fails\n super(name, imgUrl, capacity, 64, scene, epsilon, samplingMode, true, spriteJSON);\n this.name = name;\n }\n}\n//# sourceMappingURL=spritePackedManager.js.map","export * from \"./sprite.js\";\nexport * from \"./ISprites.js\";\nexport * from \"./spriteManager.js\";\nexport * from \"./spriteMap.js\";\nexport * from \"./spritePackedManager.js\";\nexport * from \"./spriteSceneComponent.js\";\n//# sourceMappingURL=index.js.map","export * from \"./alphaCullingState.js\";\nexport * from \"./depthCullingState.js\";\nexport * from \"./stencilState.js\";\nexport * from \"./stencilStateComposer.js\";\n//# sourceMappingURL=index.js.map","import { SceneLoader, SceneLoaderAnimationGroupLoadingMode } from \"../Loading/sceneLoader.js\";\nimport { Tools } from \"./tools.js\";\nimport { Observable } from \"./observable.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { CubeTexture } from \"../Materials/Textures/cubeTexture.js\";\nimport { HDRCubeTexture } from \"../Materials/Textures/hdrCubeTexture.js\";\nimport { EquiRectangularCubeTexture } from \"../Materials/Textures/equiRectangularCubeTexture.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n/**\n * Defines the list of states available for a task inside a AssetsManager\n */\nexport var AssetTaskState;\n(function (AssetTaskState) {\n /**\n * Initialization\n */\n AssetTaskState[AssetTaskState[\"INIT\"] = 0] = \"INIT\";\n /**\n * Running\n */\n AssetTaskState[AssetTaskState[\"RUNNING\"] = 1] = \"RUNNING\";\n /**\n * Done\n */\n AssetTaskState[AssetTaskState[\"DONE\"] = 2] = \"DONE\";\n /**\n * Error\n */\n AssetTaskState[AssetTaskState[\"ERROR\"] = 3] = \"ERROR\";\n})(AssetTaskState || (AssetTaskState = {}));\n/**\n * Define an abstract asset task used with a AssetsManager class to load assets into a scene\n */\nexport class AbstractAssetTask {\n /**\n * Creates a new AssetsManager\n * @param name defines the name of the task\n */\n constructor(\n /**\n * Task name\n */ name) {\n this.name = name;\n this._isCompleted = false;\n this._taskState = AssetTaskState.INIT;\n }\n /**\n * Get if the task is completed\n */\n get isCompleted() {\n return this._isCompleted;\n }\n /**\n * Gets the current state of the task\n */\n get taskState() {\n return this._taskState;\n }\n /**\n * Gets the current error object (if task is in error)\n */\n get errorObject() {\n return this._errorObject;\n }\n /**\n * Internal only\n * @internal\n */\n _setErrorObject(message, exception) {\n if (this._errorObject) {\n return;\n }\n this._errorObject = {\n message: message,\n exception: exception,\n };\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n run(scene, onSuccess, onError) {\n this._taskState = AssetTaskState.RUNNING;\n this.runTask(scene, () => {\n this._onDoneCallback(onSuccess, onError);\n }, (msg, exception) => {\n this._onErrorCallback(onError, msg, exception);\n });\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n runTask(scene, onSuccess, onError) {\n throw new Error(\"runTask is not implemented\");\n }\n /**\n * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.\n * This can be used with failed tasks that have the reason for failure fixed.\n */\n reset() {\n this._taskState = AssetTaskState.INIT;\n }\n _onErrorCallback(onError, message, exception) {\n this._taskState = AssetTaskState.ERROR;\n this._errorObject = {\n message: message,\n exception: exception,\n };\n if (this.onError) {\n this.onError(this, message, exception);\n }\n onError();\n }\n _onDoneCallback(onSuccess, onError) {\n try {\n this._taskState = AssetTaskState.DONE;\n this._isCompleted = true;\n if (this.onSuccess) {\n this.onSuccess(this);\n }\n onSuccess();\n }\n catch (e) {\n this._onErrorCallback(onError, \"Task is done, error executing success callback(s)\", e);\n }\n }\n}\n/**\n * Class used to share progress information about assets loading\n */\nexport class AssetsProgressEvent {\n /**\n * Creates a AssetsProgressEvent\n * @param remainingCount defines the number of remaining tasks to process\n * @param totalCount defines the total number of tasks\n * @param task defines the task that was just processed\n */\n constructor(remainingCount, totalCount, task) {\n this.remainingCount = remainingCount;\n this.totalCount = totalCount;\n this.task = task;\n }\n}\n/**\n * Define a task used by AssetsManager to load assets into a container\n */\nexport class ContainerAssetTask extends AbstractAssetTask {\n /**\n * Creates a new ContainerAssetTask\n * @param name defines the name of the task\n * @param meshesNames defines the list of mesh's names you want to load\n * @param rootUrl defines the root url to use as a base to load your meshes and associated resources\n * @param sceneFilename defines the filename or File of the scene to load from\n */\n constructor(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the list of mesh's names you want to load\n */\n meshesNames, \n /**\n * Defines the root url to use as a base to load your meshes and associated resources\n */\n rootUrl, \n /**\n * Defines the filename or File of the scene to load from\n */\n sceneFilename, \n /**\n * Defines the extension to use to load the scene (if not defined, \".babylon\" will be used)\n */\n extension) {\n super(name);\n this.name = name;\n this.meshesNames = meshesNames;\n this.rootUrl = rootUrl;\n this.sceneFilename = sceneFilename;\n this.extension = extension;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n runTask(scene, onSuccess, onError) {\n SceneLoader.LoadAssetContainer(this.rootUrl, this.sceneFilename, scene, (container) => {\n this.loadedContainer = container;\n this.loadedMeshes = container.meshes;\n this.loadedTransformNodes = container.transformNodes;\n this.loadedParticleSystems = container.particleSystems;\n this.loadedSkeletons = container.skeletons;\n this.loadedAnimationGroups = container.animationGroups;\n onSuccess();\n }, null, (scene, message, exception) => {\n onError(message, exception);\n }, this.extension);\n }\n}\n/**\n * Define a task used by AssetsManager to load meshes\n */\nexport class MeshAssetTask extends AbstractAssetTask {\n /**\n * Creates a new MeshAssetTask\n * @param name defines the name of the task\n * @param meshesNames defines the list of mesh's names you want to load\n * @param rootUrl defines the root url to use as a base to load your meshes and associated resources\n * @param sceneFilename defines the filename or File of the scene to load from\n */\n constructor(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the list of mesh's names you want to load\n */\n meshesNames, \n /**\n * Defines the root url to use as a base to load your meshes and associated resources\n */\n rootUrl, \n /**\n * Defines the filename or File of the scene to load from\n */\n sceneFilename, \n /**\n * Defines the extension to use to load the scene (if not defined, \".babylon\" will be used)\n */\n extension) {\n super(name);\n this.name = name;\n this.meshesNames = meshesNames;\n this.rootUrl = rootUrl;\n this.sceneFilename = sceneFilename;\n this.extension = extension;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n runTask(scene, onSuccess, onError) {\n SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, (meshes, particleSystems, skeletons, animationGroups, transformNodes) => {\n this.loadedMeshes = meshes;\n this.loadedTransformNodes = transformNodes;\n this.loadedParticleSystems = particleSystems;\n this.loadedSkeletons = skeletons;\n this.loadedAnimationGroups = animationGroups;\n onSuccess();\n }, null, (scene, message, exception) => {\n onError(message, exception);\n }, this.extension);\n }\n}\n/**\n * Define a task used by AssetsManager to load animations\n */\nexport class AnimationAssetTask extends AbstractAssetTask {\n /**\n * Creates a new AnimationAssetTask\n * @param name defines the name of the task\n * @param rootUrl defines the root url to use as a base to load your meshes and associated resources\n * @param filename defines the filename or File of the scene to load from\n * @param targetConverter defines a function used to convert animation targets from loaded scene to current scene (default: search node by name)\n */\n constructor(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the root url to use as a base to load your meshes and associated resources\n */\n rootUrl, \n /**\n * Defines the filename to load from\n */\n filename, \n /**\n * Defines a function used to convert animation targets from loaded scene to current scene (default: search node by name)\n */\n targetConverter, \n /**\n * Defines the extension to use to load the scene (if not defined, \".babylon\" will be used)\n */\n extension) {\n super(name);\n this.name = name;\n this.rootUrl = rootUrl;\n this.filename = filename;\n this.targetConverter = targetConverter;\n this.extension = extension;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n runTask(scene, onSuccess, onError) {\n const startingIndexForNewAnimatables = scene.animatables.length;\n const startingIndexForNewAnimationGroups = scene.animationGroups.length;\n this.loadedAnimatables = [];\n this.loadedAnimationGroups = [];\n SceneLoader.ImportAnimations(this.rootUrl, this.filename, scene, false, SceneLoaderAnimationGroupLoadingMode.NoSync, this.targetConverter, () => {\n this.loadedAnimatables = scene.animatables.slice(startingIndexForNewAnimatables);\n this.loadedAnimationGroups = scene.animationGroups.slice(startingIndexForNewAnimationGroups);\n onSuccess();\n }, null, (scene, message, exception) => {\n onError(message, exception);\n }, this.extension);\n }\n}\n/**\n * Define a task used by AssetsManager to load text content\n */\nexport class TextFileAssetTask extends AbstractAssetTask {\n /**\n * Creates a new TextFileAssetTask object\n * @param name defines the name of the task\n * @param url defines the location of the file to load\n */\n constructor(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the location of the file to load\n */\n url) {\n super(name);\n this.name = name;\n this.url = url;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n runTask(scene, onSuccess, onError) {\n scene._loadFile(this.url, (data) => {\n this.text = data;\n onSuccess();\n }, undefined, false, false, (request, exception) => {\n if (request) {\n onError(request.status + \" \" + request.statusText, exception);\n }\n });\n }\n}\n/**\n * Define a task used by AssetsManager to load binary data\n */\nexport class BinaryFileAssetTask extends AbstractAssetTask {\n /**\n * Creates a new BinaryFileAssetTask object\n * @param name defines the name of the new task\n * @param url defines the location of the file to load\n */\n constructor(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the location of the file to load\n */\n url) {\n super(name);\n this.name = name;\n this.url = url;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n runTask(scene, onSuccess, onError) {\n scene._loadFile(this.url, (data) => {\n this.data = data;\n onSuccess();\n }, undefined, true, true, (request, exception) => {\n if (request) {\n onError(request.status + \" \" + request.statusText, exception);\n }\n });\n }\n}\n/**\n * Define a task used by AssetsManager to load images\n */\nexport class ImageAssetTask extends AbstractAssetTask {\n /**\n * Creates a new ImageAssetTask\n * @param name defines the name of the task\n * @param url defines the location of the image to load\n */\n constructor(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the location of the image to load\n */\n url) {\n super(name);\n this.name = name;\n this.url = url;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n runTask(scene, onSuccess, onError) {\n const img = new Image();\n Tools.SetCorsBehavior(this.url, img);\n img.onload = () => {\n this.image = img;\n onSuccess();\n };\n img.onerror = (err) => {\n onError(\"Error loading image\", err);\n };\n img.src = this.url;\n }\n}\n/**\n * Define a task used by AssetsManager to load 2D textures\n */\nexport class TextureAssetTask extends AbstractAssetTask {\n /**\n * Creates a new TextureAssetTask object\n * @param name defines the name of the task\n * @param url defines the location of the file to load\n * @param noMipmap defines if mipmap should not be generated (default is false)\n * @param invertY defines if texture must be inverted on Y axis (default is true)\n * @param samplingMode defines the sampling mode to use (default is Texture.TRILINEAR_SAMPLINGMODE)\n */\n constructor(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the location of the file to load\n */\n url, \n /**\n * Defines if mipmap should not be generated (default is false)\n */\n noMipmap, \n /**\n * Defines if texture must be inverted on Y axis (default is true)\n */\n invertY = true, \n /**\n * Defines the sampling mode to use (default is Texture.TRILINEAR_SAMPLINGMODE)\n */\n samplingMode = Texture.TRILINEAR_SAMPLINGMODE) {\n super(name);\n this.name = name;\n this.url = url;\n this.noMipmap = noMipmap;\n this.invertY = invertY;\n this.samplingMode = samplingMode;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n runTask(scene, onSuccess, onError) {\n const onload = () => {\n onSuccess();\n };\n const onerror = (message, exception) => {\n onError(message, exception);\n };\n this.texture = new Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);\n }\n}\n/**\n * Define a task used by AssetsManager to load cube textures\n */\nexport class CubeTextureAssetTask extends AbstractAssetTask {\n /**\n * Creates a new CubeTextureAssetTask\n * @param name defines the name of the task\n * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)\n * @param extensions defines the extensions to use to load files ([\"_px\", \"_py\", \"_pz\", \"_nx\", \"_ny\", \"_nz\"] by default)\n * @param noMipmap defines if mipmaps should not be generated (default is false)\n * @param files defines the explicit list of files (undefined by default)\n * @param prefiltered\n */\n constructor(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)\n */\n url, \n /**\n * Defines the extensions to use to load files ([\"_px\", \"_py\", \"_pz\", \"_nx\", \"_ny\", \"_nz\"] by default)\n */\n extensions, \n /**\n * Defines if mipmaps should not be generated (default is false)\n */\n noMipmap, \n /**\n * Defines the explicit list of files (undefined by default)\n */\n files, \n /**\n * Defines the prefiltered texture option (default is false)\n */\n prefiltered) {\n super(name);\n this.name = name;\n this.url = url;\n this.extensions = extensions;\n this.noMipmap = noMipmap;\n this.files = files;\n this.prefiltered = prefiltered;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n runTask(scene, onSuccess, onError) {\n const onload = () => {\n onSuccess();\n };\n const onerror = (message, exception) => {\n onError(message, exception);\n };\n this.texture = new CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror, undefined, this.prefiltered);\n }\n}\n/**\n * Define a task used by AssetsManager to load HDR cube textures\n */\nexport class HDRCubeTextureAssetTask extends AbstractAssetTask {\n /**\n * Creates a new HDRCubeTextureAssetTask object\n * @param name defines the name of the task\n * @param url defines the location of the file to load\n * @param size defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.\n * @param noMipmap defines if mipmaps should not be generated (default is false)\n * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)\n * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)\n * @param reserved Internal use only\n */\n constructor(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the location of the file to load\n */\n url, \n /**\n * Defines the desired size (the more it increases the longer the generation will be)\n */\n size, \n /**\n * Defines if mipmaps should not be generated (default is false)\n */\n noMipmap = false, \n /**\n * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)\n */\n generateHarmonics = true, \n /**\n * Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)\n */\n gammaSpace = false, \n /**\n * Internal Use Only\n */\n reserved = false) {\n super(name);\n this.name = name;\n this.url = url;\n this.size = size;\n this.noMipmap = noMipmap;\n this.generateHarmonics = generateHarmonics;\n this.gammaSpace = gammaSpace;\n this.reserved = reserved;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n runTask(scene, onSuccess, onError) {\n const onload = () => {\n onSuccess();\n };\n const onerror = (message, exception) => {\n onError(message, exception);\n };\n this.texture = new HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);\n }\n}\n/**\n * Define a task used by AssetsManager to load Equirectangular cube textures\n */\nexport class EquiRectangularCubeTextureAssetTask extends AbstractAssetTask {\n /**\n * Creates a new EquiRectangularCubeTextureAssetTask object\n * @param name defines the name of the task\n * @param url defines the location of the file to load\n * @param size defines the desired size (the more it increases the longer the generation will be)\n * If the size is omitted this implies you are using a preprocessed cubemap.\n * @param noMipmap defines if mipmaps should not be generated (default is false)\n * @param gammaSpace specifies if the texture will be used in gamma or linear space\n * (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)\n * (default is true)\n */\n constructor(\n /**\n * Defines the name of the task\n */\n name, \n /**\n * Defines the location of the file to load\n */\n url, \n /**\n * Defines the desired size (the more it increases the longer the generation will be)\n */\n size, \n /**\n * Defines if mipmaps should not be generated (default is false)\n */\n noMipmap = false, \n /**\n * Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space,\n * but the standard material would require them in Gamma space) (default is true)\n */\n gammaSpace = true) {\n super(name);\n this.name = name;\n this.url = url;\n this.size = size;\n this.noMipmap = noMipmap;\n this.gammaSpace = gammaSpace;\n }\n /**\n * Execute the current task\n * @param scene defines the scene where you want your assets to be loaded\n * @param onSuccess is a callback called when the task is successfully executed\n * @param onError is a callback called if an error occurs\n */\n runTask(scene, onSuccess, onError) {\n const onload = () => {\n onSuccess();\n };\n const onerror = (message, exception) => {\n onError(message, exception);\n };\n this.texture = new EquiRectangularCubeTexture(this.url, scene, this.size, this.noMipmap, this.gammaSpace, onload, onerror);\n }\n}\n/**\n * This class can be used to easily import assets into a scene\n * @see https://doc.babylonjs.com/features/featuresDeepDive/importers/assetManager\n */\nexport class AssetsManager {\n /**\n * Creates a new AssetsManager\n * @param scene defines the scene to work on\n */\n constructor(scene) {\n this._isLoading = false;\n this._tasks = new Array();\n this._waitingTasksCount = 0;\n this._totalTasksCount = 0;\n /**\n * Observable called when all tasks are processed\n */\n this.onTaskSuccessObservable = new Observable();\n /**\n * Observable called when a task had an error\n */\n this.onTaskErrorObservable = new Observable();\n /**\n * Observable called when all tasks were executed\n */\n this.onTasksDoneObservable = new Observable();\n /**\n * Observable called when a task is done (whatever the result is)\n */\n this.onProgressObservable = new Observable();\n /**\n * Gets or sets a boolean defining if the AssetsManager should use the default loading screen\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen\n */\n this.useDefaultLoadingScreen = true;\n /**\n * Gets or sets a boolean defining if the AssetsManager should automatically hide the loading screen\n * when all assets have been downloaded.\n * If set to false, you need to manually call in hideLoadingUI() once your scene is ready.\n */\n this.autoHideLoadingUI = true;\n this._scene = scene || EngineStore.LastCreatedScene;\n }\n /**\n * Add a ContainerAssetTask to the list of active tasks\n * @param taskName defines the name of the new task\n * @param meshesNames defines the name of meshes to load\n * @param rootUrl defines the root url to use to locate files\n * @param sceneFilename defines the filename of the scene file or the File itself\n * @param extension defines the extension to use to load the file\n * @returns a new ContainerAssetTask object\n */\n addContainerTask(taskName, meshesNames, rootUrl, sceneFilename, extension) {\n const task = new ContainerAssetTask(taskName, meshesNames, rootUrl, sceneFilename, extension);\n this._tasks.push(task);\n return task;\n }\n /**\n * Add a MeshAssetTask to the list of active tasks\n * @param taskName defines the name of the new task\n * @param meshesNames defines the name of meshes to load\n * @param rootUrl defines the root url to use to locate files\n * @param sceneFilename defines the filename of the scene file or the File itself\n * @param extension defines the extension to use to load the file\n * @returns a new MeshAssetTask object\n */\n addMeshTask(taskName, meshesNames, rootUrl, sceneFilename, extension) {\n const task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename, extension);\n this._tasks.push(task);\n return task;\n }\n /**\n * Add a TextFileAssetTask to the list of active tasks\n * @param taskName defines the name of the new task\n * @param url defines the url of the file to load\n * @returns a new TextFileAssetTask object\n */\n addTextFileTask(taskName, url) {\n const task = new TextFileAssetTask(taskName, url);\n this._tasks.push(task);\n return task;\n }\n /**\n * Add a BinaryFileAssetTask to the list of active tasks\n * @param taskName defines the name of the new task\n * @param url defines the url of the file to load\n * @returns a new BinaryFileAssetTask object\n */\n addBinaryFileTask(taskName, url) {\n const task = new BinaryFileAssetTask(taskName, url);\n this._tasks.push(task);\n return task;\n }\n /**\n * Add a ImageAssetTask to the list of active tasks\n * @param taskName defines the name of the new task\n * @param url defines the url of the file to load\n * @returns a new ImageAssetTask object\n */\n addImageTask(taskName, url) {\n const task = new ImageAssetTask(taskName, url);\n this._tasks.push(task);\n return task;\n }\n /**\n * Add a TextureAssetTask to the list of active tasks\n * @param taskName defines the name of the new task\n * @param url defines the url of the file to load\n * @param noMipmap defines if the texture must not receive mipmaps (false by default)\n * @param invertY defines if you want to invert Y axis of the loaded texture (true by default)\n * @param samplingMode defines the sampling mode to use (Texture.TRILINEAR_SAMPLINGMODE by default)\n * @returns a new TextureAssetTask object\n */\n addTextureTask(taskName, url, noMipmap, invertY, samplingMode = Texture.TRILINEAR_SAMPLINGMODE) {\n const task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);\n this._tasks.push(task);\n return task;\n }\n /**\n * Add a CubeTextureAssetTask to the list of active tasks\n * @param taskName defines the name of the new task\n * @param url defines the url of the file to load\n * @param extensions defines the extension to use to load the cube map (can be null)\n * @param noMipmap defines if the texture must not receive mipmaps (false by default)\n * @param files defines the list of files to load (can be null)\n * @param prefiltered defines the prefiltered texture option (default is false)\n * @returns a new CubeTextureAssetTask object\n */\n addCubeTextureTask(taskName, url, extensions, noMipmap, files, prefiltered) {\n const task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files, prefiltered);\n this._tasks.push(task);\n return task;\n }\n /**\n *\n * Add a HDRCubeTextureAssetTask to the list of active tasks\n * @param taskName defines the name of the new task\n * @param url defines the url of the file to load\n * @param size defines the size you want for the cubemap (can be null)\n * @param noMipmap defines if the texture must not receive mipmaps (false by default)\n * @param generateHarmonics defines if you want to automatically generate (true by default)\n * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)\n * @param reserved Internal use only\n * @returns a new HDRCubeTextureAssetTask object\n */\n addHDRCubeTextureTask(taskName, url, size, noMipmap = false, generateHarmonics = true, gammaSpace = false, reserved = false) {\n const task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);\n this._tasks.push(task);\n return task;\n }\n /**\n *\n * Add a EquiRectangularCubeTextureAssetTask to the list of active tasks\n * @param taskName defines the name of the new task\n * @param url defines the url of the file to load\n * @param size defines the size you want for the cubemap (can be null)\n * @param noMipmap defines if the texture must not receive mipmaps (false by default)\n * @param gammaSpace Specifies if the texture will be used in gamma or linear space\n * (the PBR material requires those textures in linear space, but the standard material would require them in Gamma space)\n * @returns a new EquiRectangularCubeTextureAssetTask object\n */\n addEquiRectangularCubeTextureAssetTask(taskName, url, size, noMipmap = false, gammaSpace = true) {\n const task = new EquiRectangularCubeTextureAssetTask(taskName, url, size, noMipmap, gammaSpace);\n this._tasks.push(task);\n return task;\n }\n /**\n * Remove a task from the assets manager.\n * @param task the task to remove\n */\n removeTask(task) {\n const index = this._tasks.indexOf(task);\n if (index > -1) {\n this._tasks.splice(index, 1);\n }\n }\n _decreaseWaitingTasksCount(task) {\n this._waitingTasksCount--;\n try {\n if (this.onProgress) {\n this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);\n }\n this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));\n }\n catch (e) {\n Logger.Error(\"Error running progress callbacks.\");\n console.log(e);\n }\n if (this._waitingTasksCount === 0) {\n try {\n const currentTasks = this._tasks.slice();\n if (this.onFinish) {\n // Calling onFinish with immutable array of tasks\n this.onFinish(currentTasks);\n }\n // Let's remove successful tasks\n for (const task of currentTasks) {\n if (task.taskState === AssetTaskState.DONE) {\n const index = this._tasks.indexOf(task);\n if (index > -1) {\n this._tasks.splice(index, 1);\n }\n }\n }\n this.onTasksDoneObservable.notifyObservers(this._tasks);\n }\n catch (e) {\n Logger.Error(\"Error running tasks-done callbacks.\");\n console.log(e);\n }\n this._isLoading = false;\n if (this.autoHideLoadingUI) {\n this._scene.getEngine().hideLoadingUI();\n }\n }\n }\n _runTask(task) {\n const done = () => {\n try {\n if (this.onTaskSuccess) {\n this.onTaskSuccess(task);\n }\n this.onTaskSuccessObservable.notifyObservers(task);\n this._decreaseWaitingTasksCount(task);\n }\n catch (e) {\n error(\"Error executing task success callbacks\", e);\n }\n };\n const error = (message, exception) => {\n task._setErrorObject(message, exception);\n if (this.onTaskError) {\n this.onTaskError(task);\n }\n else if (!task.onError) {\n Logger.Error(this._formatTaskErrorMessage(task));\n }\n this.onTaskErrorObservable.notifyObservers(task);\n this._decreaseWaitingTasksCount(task);\n };\n task.run(this._scene, done, error);\n }\n _formatTaskErrorMessage(task) {\n let errorMessage = \"Unable to complete task \" + task.name;\n if (task.errorObject.message) {\n errorMessage += `: ${task.errorObject.message}`;\n }\n if (task.errorObject.exception) {\n errorMessage += `: ${task.errorObject.exception}`;\n }\n return errorMessage;\n }\n /**\n * Reset the AssetsManager and remove all tasks\n * @returns the current instance of the AssetsManager\n */\n reset() {\n this._isLoading = false;\n this._tasks = new Array();\n return this;\n }\n /**\n * Start the loading process\n * @returns the current instance of the AssetsManager\n */\n load() {\n if (this._isLoading) {\n return this;\n }\n this._isLoading = true;\n this._waitingTasksCount = this._tasks.length;\n this._totalTasksCount = this._tasks.length;\n if (this._waitingTasksCount === 0) {\n this._isLoading = false;\n if (this.onFinish) {\n this.onFinish(this._tasks);\n }\n this.onTasksDoneObservable.notifyObservers(this._tasks);\n return this;\n }\n if (this.useDefaultLoadingScreen) {\n this._scene.getEngine().displayLoadingUI();\n }\n for (let index = 0; index < this._tasks.length; index++) {\n const task = this._tasks[index];\n if (task.taskState === AssetTaskState.INIT) {\n this._runTask(task);\n }\n }\n return this;\n }\n /**\n * Start the loading process as an async operation\n * @returns a promise returning the list of failed tasks\n */\n loadAsync() {\n return new Promise((resolve, reject) => {\n if (this._isLoading) {\n resolve();\n return;\n }\n this.onTasksDoneObservable.addOnce((remainingTasks) => {\n if (remainingTasks && remainingTasks.length) {\n reject(remainingTasks);\n }\n else {\n resolve();\n }\n });\n this.load();\n });\n }\n}\n//# sourceMappingURL=assetsManager.js.map","/**\n * Wrapper class for promise with external resolve and reject.\n */\nexport class Deferred {\n /**\n * The resolve method of the promise associated with this deferred object.\n */\n get resolve() {\n return this._resolve;\n }\n /**\n * The reject method of the promise associated with this deferred object.\n */\n get reject() {\n return this._reject;\n }\n /**\n * Constructor for this deferred object.\n */\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n}\n//# sourceMappingURL=deferred.js.map","import { Vector3 } from \"../Maths/math.vector.js\";\n/**\n * Class used to explode meshes (ie. to have a center and move them away from that center to better see the overall organization)\n */\nexport class MeshExploder {\n /**\n * Explodes meshes from a center mesh.\n * @param meshes The meshes to explode.\n * @param centerMesh The mesh to be center of explosion.\n */\n constructor(meshes, centerMesh) {\n this._meshesOrigins = [];\n this._toCenterVectors = [];\n this._scaledDirection = new Vector3(1, 1, 1);\n this._newPosition = Vector3.Zero();\n this._centerPosition = Vector3.Zero();\n this._meshes = meshes.slice();\n if (centerMesh) {\n this._centerMesh = centerMesh;\n }\n else {\n this._setCenterMesh();\n }\n this._centerMesh.computeWorldMatrix(true);\n const centerMeshIndex = this._meshes.indexOf(this._centerMesh);\n if (centerMeshIndex >= 0) {\n this._meshes.splice(centerMeshIndex, 1);\n }\n this._centerPosition = this._centerMesh.getAbsolutePosition().clone();\n for (let index = 0; index < this._meshes.length; index++) {\n if (this._meshes[index]) {\n const mesh = this._meshes[index];\n this._meshesOrigins[index] = mesh.getAbsolutePosition().clone();\n this._toCenterVectors[index] = Vector3.Zero();\n if (mesh.hasBoundingInfo && this._centerMesh.hasBoundingInfo) {\n mesh.computeWorldMatrix(true);\n mesh.getBoundingInfo().boundingBox.centerWorld.subtractToRef(this._centerMesh.getBoundingInfo().boundingBox.centerWorld, this._toCenterVectors[index]);\n }\n }\n }\n }\n _setCenterMesh() {\n let averageCenter = Vector3.Zero();\n const totalCenters = Vector3.Zero();\n let shortestToCenter = Number.MAX_VALUE;\n for (let index = 0; index < this._meshes.length; index++) {\n if (this._meshes[index]) {\n const mesh = this._meshes[index];\n const boundingInfo = mesh.getBoundingInfo();\n if (boundingInfo) {\n totalCenters.addInPlace(boundingInfo.boundingBox.centerWorld);\n }\n }\n }\n averageCenter = totalCenters.scale(1 / this._meshes.length);\n for (let index = 0; index < this._meshes.length; index++) {\n if (this._meshes[index]) {\n const mesh = this._meshes[index];\n const boundingInfo = mesh.getBoundingInfo();\n if (boundingInfo) {\n const distanceToCenter = boundingInfo.boundingBox.centerWorld.subtract(averageCenter).lengthSquared();\n if (distanceToCenter < shortestToCenter) {\n this._centerMesh = mesh;\n shortestToCenter = distanceToCenter;\n }\n }\n }\n }\n }\n /**\n * Get class name\n * @returns \"MeshExploder\"\n */\n getClassName() {\n return \"MeshExploder\";\n }\n /**\n * \"Exploded meshes\"\n * @returns Array of meshes with the centerMesh at index 0.\n */\n getMeshes() {\n const meshArray = this._meshes.slice();\n meshArray.unshift(this._centerMesh);\n return meshArray;\n }\n /**\n * Explodes meshes giving a specific direction\n * @param direction Number to multiply distance of each mesh's origin from center. Use a negative number to implode, or zero to reset.\n */\n explode(direction = 1.0) {\n for (let index = 0; index < this._meshes.length; index++) {\n if (this._meshes[index] && this._meshesOrigins[index] && this._toCenterVectors[index]) {\n this._toCenterVectors[index].scaleToRef(direction, this._scaledDirection);\n this._meshesOrigins[index].addToRef(this._scaledDirection, this._newPosition);\n this._meshes[index].setAbsolutePosition(this._newPosition);\n }\n }\n this._centerMesh.setAbsolutePosition(this._centerPosition);\n }\n}\n//# sourceMappingURL=meshExploder.js.map","import { SceneLoader } from \"../Loading/sceneLoader.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { FilesInputStore } from \"./filesInputStore.js\";\n/**\n * Class used to help managing file picking and drag-n-drop\n */\nexport class FilesInput {\n /**\n * List of files ready to be loaded\n */\n static get FilesToLoad() {\n return FilesInputStore.FilesToLoad;\n }\n /**\n * Creates a new FilesInput\n * @param engine defines the rendering engine\n * @param scene defines the hosting scene\n * @param sceneLoadedCallback callback called when scene (files provided) is loaded\n * @param progressCallback callback called to track progress\n * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop\n * @param textureLoadingCallback callback called when a texture is loading\n * @param startingProcessingFilesCallback callback called when the system is about to process all files\n * @param onReloadCallback callback called when a reload is requested\n * @param errorCallback callback call if an error occurs\n * @param useAppend defines if the file loaded must be appended (true) or have the scene replaced (false, default behavior)\n */\n constructor(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback, useAppend = false) {\n this.useAppend = useAppend;\n /**\n * Callback called when a file is processed\n */\n this.onProcessFileCallback = () => {\n return true;\n };\n this.displayLoadingUI = true;\n /**\n * Function used when loading the scene file\n * @param sceneFile\n * @param onProgress\n */\n this.loadAsync = (sceneFile, onProgress) => this.useAppend ? SceneLoader.AppendAsync(\"file:\", sceneFile, this._currentScene, onProgress) : SceneLoader.LoadAsync(\"file:\", sceneFile, this._engine, onProgress);\n this._engine = engine;\n this._currentScene = scene;\n this._sceneLoadedCallback = sceneLoadedCallback;\n this._progressCallback = progressCallback;\n this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;\n this._textureLoadingCallback = textureLoadingCallback;\n this._startingProcessingFilesCallback = startingProcessingFilesCallback;\n this._onReloadCallback = onReloadCallback;\n this._errorCallback = errorCallback;\n }\n /**\n * Calls this function to listen to drag'n'drop events on a specific DOM element\n * @param elementToMonitor defines the DOM element to track\n */\n monitorElementForDragNDrop(elementToMonitor) {\n if (elementToMonitor) {\n this._elementToMonitor = elementToMonitor;\n this._dragEnterHandler = (e) => {\n this._drag(e);\n };\n this._dragOverHandler = (e) => {\n this._drag(e);\n };\n this._dropHandler = (e) => {\n this._drop(e);\n };\n this._elementToMonitor.addEventListener(\"dragenter\", this._dragEnterHandler, false);\n this._elementToMonitor.addEventListener(\"dragover\", this._dragOverHandler, false);\n this._elementToMonitor.addEventListener(\"drop\", this._dropHandler, false);\n }\n }\n /** Gets the current list of files to load */\n get filesToLoad() {\n return this._filesToLoad;\n }\n /**\n * Release all associated resources\n */\n dispose() {\n if (!this._elementToMonitor) {\n return;\n }\n this._elementToMonitor.removeEventListener(\"dragenter\", this._dragEnterHandler);\n this._elementToMonitor.removeEventListener(\"dragover\", this._dragOverHandler);\n this._elementToMonitor.removeEventListener(\"drop\", this._dropHandler);\n }\n _renderFunction() {\n if (this._additionalRenderLoopLogicCallback) {\n this._additionalRenderLoopLogicCallback();\n }\n if (this._currentScene) {\n if (this._textureLoadingCallback) {\n const remaining = this._currentScene.getWaitingItemsCount();\n if (remaining > 0) {\n this._textureLoadingCallback(remaining);\n }\n }\n this._currentScene.render();\n }\n }\n _drag(e) {\n e.stopPropagation();\n e.preventDefault();\n }\n _drop(eventDrop) {\n eventDrop.stopPropagation();\n eventDrop.preventDefault();\n this.loadFiles(eventDrop);\n }\n _traverseFolder(folder, files, remaining, callback) {\n const reader = folder.createReader();\n const relativePath = folder.fullPath.replace(/^\\//, \"\").replace(/(.+?)\\/?$/, \"$1/\");\n reader.readEntries((entries) => {\n remaining.count += entries.length;\n for (const entry of entries) {\n if (entry.isFile) {\n entry.file((file) => {\n file.correctName = relativePath + file.name;\n files.push(file);\n if (--remaining.count === 0) {\n callback();\n }\n });\n }\n else if (entry.isDirectory) {\n this._traverseFolder(entry, files, remaining, callback);\n }\n }\n if (--remaining.count === 0) {\n callback();\n }\n });\n }\n _processFiles(files) {\n for (let i = 0; i < files.length; i++) {\n const name = files[i].correctName.toLowerCase();\n const extension = name.split(\".\").pop();\n if (!this.onProcessFileCallback(files[i], name, extension, (sceneFile) => (this._sceneFileToLoad = sceneFile))) {\n continue;\n }\n if (SceneLoader.IsPluginForExtensionAvailable(\".\" + extension)) {\n this._sceneFileToLoad = files[i];\n }\n FilesInput.FilesToLoad[name] = files[i];\n }\n }\n /**\n * Load files from a drop event\n * @param event defines the drop event to use as source\n */\n loadFiles(event) {\n // Handling data transfer via drag'n'drop\n if (event && event.dataTransfer && event.dataTransfer.files) {\n this._filesToLoad = event.dataTransfer.files;\n }\n // Handling files from input files\n if (event && event.target && event.target.files) {\n this._filesToLoad = event.target.files;\n }\n if (!this._filesToLoad || this._filesToLoad.length === 0) {\n return;\n }\n if (this._startingProcessingFilesCallback) {\n this._startingProcessingFilesCallback(this._filesToLoad);\n }\n if (this._filesToLoad && this._filesToLoad.length > 0) {\n const files = new Array();\n const folders = [];\n const items = event.dataTransfer ? event.dataTransfer.items : null;\n for (let i = 0; i < this._filesToLoad.length; i++) {\n const fileToLoad = this._filesToLoad[i];\n const name = fileToLoad.name.toLowerCase();\n let entry;\n fileToLoad.correctName = name;\n if (items) {\n const item = items[i];\n if (item.getAsEntry) {\n entry = item.getAsEntry();\n }\n else if (item.webkitGetAsEntry) {\n entry = item.webkitGetAsEntry();\n }\n }\n if (!entry) {\n files.push(fileToLoad);\n }\n else {\n if (entry.isDirectory) {\n folders.push(entry);\n }\n else {\n files.push(fileToLoad);\n }\n }\n }\n if (folders.length === 0) {\n this._processFiles(files);\n this._processReload();\n }\n else {\n const remaining = { count: folders.length };\n for (const folder of folders) {\n this._traverseFolder(folder, files, remaining, () => {\n this._processFiles(files);\n if (remaining.count === 0) {\n this._processReload();\n }\n });\n }\n }\n }\n }\n _processReload() {\n if (this._onReloadCallback) {\n this._onReloadCallback(this._sceneFileToLoad);\n }\n else {\n this.reload();\n }\n }\n /**\n * Reload the current scene from the loaded files\n */\n reload() {\n // If a scene file has been provided\n if (this._sceneFileToLoad) {\n if (!this.useAppend) {\n if (this._currentScene) {\n if (Logger.errorsCount > 0) {\n Logger.ClearLogCache();\n }\n this._engine.stopRenderLoop();\n }\n }\n SceneLoader.ShowLoadingScreen = false;\n if (this.displayLoadingUI) {\n this._engine.displayLoadingUI();\n }\n this.loadAsync(this._sceneFileToLoad, this._progressCallback)\n .then((scene) => {\n // if appending do nothing\n if (!this.useAppend) {\n if (this._currentScene) {\n this._currentScene.dispose();\n }\n this._currentScene = scene;\n // Wait for textures and shaders to be ready\n this._currentScene.executeWhenReady(() => {\n if (this.displayLoadingUI) {\n this._engine.hideLoadingUI();\n }\n this._engine.runRenderLoop(() => {\n this._renderFunction();\n });\n });\n }\n else {\n if (this.displayLoadingUI) {\n this._engine.hideLoadingUI();\n }\n }\n if (this._sceneLoadedCallback && this._currentScene) {\n this._sceneLoadedCallback(this._sceneFileToLoad, this._currentScene);\n }\n })\n .catch((error) => {\n if (this.displayLoadingUI) {\n this._engine.hideLoadingUI();\n }\n if (this._errorCallback) {\n this._errorCallback(this._sceneFileToLoad, this._currentScene, error.message);\n }\n });\n }\n else {\n Logger.Error(\"Please provide a valid .babylon file.\");\n }\n }\n}\n//# sourceMappingURL=filesInput.js.map","export * from \"./cubemapToSphericalPolynomial.js\";\nexport * from \"./hdr.js\";\nexport * from \"./panoramaToCubemap.js\";\n//# sourceMappingURL=index.js.map","import { Observable } from \"./observable.js\";\n/**\n * Represent a list of observers registered to multiple Observables object.\n */\nexport class MultiObserver {\n /**\n * Release associated resources\n */\n dispose() {\n if (this._observers && this._observables) {\n for (let index = 0; index < this._observers.length; index++) {\n this._observables[index].remove(this._observers[index]);\n }\n }\n this._observers = null;\n this._observables = null;\n }\n /**\n * Raise a callback when one of the observable will notify\n * @param observables defines a list of observables to watch\n * @param callback defines the callback to call on notification\n * @param mask defines the mask used to filter notifications\n * @param scope defines the current scope used to restore the JS context\n * @returns the new MultiObserver\n */\n static Watch(observables, callback, mask = -1, scope = null) {\n const result = new MultiObserver();\n result._observers = new Array();\n result._observables = observables;\n for (const observable of observables) {\n const observer = observable.add(callback, mask, false, scope);\n if (observer) {\n result._observers.push(observer);\n }\n }\n return result;\n }\n}\nObservable.prototype.notifyObserversWithPromise = async function (eventData, mask = -1, target, currentTarget, userInfo) {\n // create an empty promise\n let p = Promise.resolve(eventData);\n // no observers? return this promise.\n if (!this.observers.length) {\n return p;\n }\n const state = this._eventState;\n state.mask = mask;\n state.target = target;\n state.currentTarget = currentTarget;\n state.skipNextObservers = false;\n state.userInfo = userInfo;\n // execute one callback after another (not using Promise.all, the order is important)\n this.observers.forEach((obs) => {\n if (state.skipNextObservers) {\n return;\n }\n if (obs._willBeUnregistered) {\n return;\n }\n if (obs.mask & mask) {\n if (obs.scope) {\n p = p.then((lastReturnedValue) => {\n state.lastReturnValue = lastReturnedValue;\n return obs.callback.apply(obs.scope, [eventData, state]);\n });\n }\n else {\n p = p.then((lastReturnedValue) => {\n state.lastReturnValue = lastReturnedValue;\n return obs.callback(eventData, state);\n });\n }\n if (obs.unregisterOnNextCall) {\n this._deferUnregister(obs);\n }\n }\n });\n // return the eventData\n await p;\n return eventData;\n};\n//# sourceMappingURL=observable.extensions.js.map","import { EngineStore } from \"../Engines/engineStore.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { Observable } from \"./observable.js\";\n/**\n * Defines the root class used to create scene optimization to use with SceneOptimizer\n * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer\n */\nexport class SceneOptimization {\n /**\n * Gets a string describing the action executed by the current optimization\n * @returns description string\n */\n getDescription() {\n return \"\";\n }\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n apply(scene, optimizer) {\n return true;\n }\n /**\n * Creates the SceneOptimization object\n * @param priority defines the priority of this optimization (0 by default which means first in the list)\n */\n constructor(\n /**\n * Defines the priority of this optimization (0 by default which means first in the list)\n */\n priority = 0) {\n this.priority = priority;\n }\n}\n/**\n * Defines an optimization used to reduce the size of render target textures\n * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer\n */\nexport class TextureOptimization extends SceneOptimization {\n /**\n * Gets a string describing the action executed by the current optimization\n * @returns description string\n */\n getDescription() {\n return \"Reducing render target texture size to \" + this.maximumSize;\n }\n /**\n * Creates the TextureOptimization object\n * @param priority defines the priority of this optimization (0 by default which means first in the list)\n * @param maximumSize defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter\n * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.\n */\n constructor(\n /**\n * Defines the priority of this optimization (0 by default which means first in the list)\n */\n priority = 0, \n /**\n * Defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter\n */\n maximumSize = 1024, \n /**\n * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.\n */\n step = 0.5) {\n super(priority);\n this.priority = priority;\n this.maximumSize = maximumSize;\n this.step = step;\n }\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n apply(scene, optimizer) {\n let allDone = true;\n for (let index = 0; index < scene.textures.length; index++) {\n const texture = scene.textures[index];\n if (!texture.canRescale || texture.getContext) {\n continue;\n }\n const currentSize = texture.getSize();\n const maxDimension = Math.max(currentSize.width, currentSize.height);\n if (maxDimension > this.maximumSize) {\n texture.scale(this.step);\n allDone = false;\n }\n }\n return allDone;\n }\n}\n/**\n * Defines an optimization used to increase or decrease the rendering resolution\n * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer\n */\nexport class HardwareScalingOptimization extends SceneOptimization {\n /**\n * Gets a string describing the action executed by the current optimization\n * @returns description string\n */\n getDescription() {\n return \"Setting hardware scaling level to \" + this._currentScale;\n }\n /**\n * Creates the HardwareScalingOptimization object\n * @param priority defines the priority of this optimization (0 by default which means first in the list)\n * @param maximumScale defines the maximum scale to use (2 by default)\n * @param step defines the step to use between two passes (0.5 by default)\n */\n constructor(\n /**\n * Defines the priority of this optimization (0 by default which means first in the list)\n */\n priority = 0, \n /**\n * Defines the maximum scale to use (2 by default)\n */\n maximumScale = 2, \n /**\n * Defines the step to use between two passes (0.5 by default)\n */\n step = 0.25) {\n super(priority);\n this.priority = priority;\n this.maximumScale = maximumScale;\n this.step = step;\n this._currentScale = -1;\n this._directionOffset = 1;\n }\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n apply(scene, optimizer) {\n if (this._currentScale === -1) {\n this._currentScale = scene.getEngine().getHardwareScalingLevel();\n if (this._currentScale > this.maximumScale) {\n this._directionOffset = -1;\n }\n }\n this._currentScale += this._directionOffset * this.step;\n scene.getEngine().setHardwareScalingLevel(this._currentScale);\n return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;\n }\n}\n/**\n * Defines an optimization used to remove shadows\n * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer\n */\nexport class ShadowsOptimization extends SceneOptimization {\n /**\n * Gets a string describing the action executed by the current optimization\n * @returns description string\n */\n getDescription() {\n return \"Turning shadows on/off\";\n }\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n apply(scene, optimizer) {\n scene.shadowsEnabled = optimizer.isInImprovementMode;\n return true;\n }\n}\n/**\n * Defines an optimization used to turn post-processes off\n * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer\n */\nexport class PostProcessesOptimization extends SceneOptimization {\n /**\n * Gets a string describing the action executed by the current optimization\n * @returns description string\n */\n getDescription() {\n return \"Turning post-processes on/off\";\n }\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n apply(scene, optimizer) {\n scene.postProcessesEnabled = optimizer.isInImprovementMode;\n return true;\n }\n}\n/**\n * Defines an optimization used to turn lens flares off\n * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer\n */\nexport class LensFlaresOptimization extends SceneOptimization {\n /**\n * Gets a string describing the action executed by the current optimization\n * @returns description string\n */\n getDescription() {\n return \"Turning lens flares on/off\";\n }\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n apply(scene, optimizer) {\n scene.lensFlaresEnabled = optimizer.isInImprovementMode;\n return true;\n }\n}\n/**\n * Defines an optimization based on user defined callback.\n * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer\n */\nexport class CustomOptimization extends SceneOptimization {\n /**\n * Gets a string describing the action executed by the current optimization\n * @returns description string\n */\n getDescription() {\n if (this.onGetDescription) {\n return this.onGetDescription();\n }\n return \"Running user defined callback\";\n }\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n apply(scene, optimizer) {\n if (this.onApply) {\n return this.onApply(scene, optimizer);\n }\n return true;\n }\n}\n/**\n * Defines an optimization used to turn particles off\n * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer\n */\nexport class ParticlesOptimization extends SceneOptimization {\n /**\n * Gets a string describing the action executed by the current optimization\n * @returns description string\n */\n getDescription() {\n return \"Turning particles on/off\";\n }\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n apply(scene, optimizer) {\n scene.particlesEnabled = optimizer.isInImprovementMode;\n return true;\n }\n}\n/**\n * Defines an optimization used to turn render targets off\n * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer\n */\nexport class RenderTargetsOptimization extends SceneOptimization {\n /**\n * Gets a string describing the action executed by the current optimization\n * @returns description string\n */\n getDescription() {\n return \"Turning render targets off\";\n }\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @returns true if everything that can be done was applied\n */\n apply(scene, optimizer) {\n scene.renderTargetsEnabled = optimizer.isInImprovementMode;\n return true;\n }\n}\n/**\n * Defines an optimization used to merge meshes with compatible materials\n * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer\n */\nexport class MergeMeshesOptimization extends SceneOptimization {\n constructor() {\n super(...arguments);\n this._canBeMerged = (abstractMesh) => {\n if (!(abstractMesh instanceof Mesh)) {\n return false;\n }\n const mesh = abstractMesh;\n if (mesh.isDisposed()) {\n return false;\n }\n if (!mesh.isVisible || !mesh.isEnabled()) {\n return false;\n }\n if (mesh.instances.length > 0) {\n return false;\n }\n if (mesh.skeleton || mesh.hasLODLevels) {\n return false;\n }\n if (mesh.getTotalVertices() === 0) {\n return false;\n }\n return true;\n };\n }\n /**\n * Gets or sets a boolean which defines if optimization octree has to be updated\n */\n static get UpdateSelectionTree() {\n return MergeMeshesOptimization._UpdateSelectionTree;\n }\n /**\n * Gets or sets a boolean which defines if optimization octree has to be updated\n */\n static set UpdateSelectionTree(value) {\n MergeMeshesOptimization._UpdateSelectionTree = value;\n }\n /**\n * Gets a string describing the action executed by the current optimization\n * @returns description string\n */\n getDescription() {\n return \"Merging similar meshes together\";\n }\n /**\n * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization\n * @param scene defines the current scene where to apply this optimization\n * @param optimizer defines the current optimizer\n * @param updateSelectionTree defines that the selection octree has to be updated (false by default)\n * @returns true if everything that can be done was applied\n */\n apply(scene, optimizer, updateSelectionTree) {\n const globalPool = scene.meshes.slice(0);\n let globalLength = globalPool.length;\n for (let index = 0; index < globalLength; index++) {\n const currentPool = new Array();\n const current = globalPool[index];\n // Checks\n if (!this._canBeMerged(current)) {\n continue;\n }\n currentPool.push(current);\n // Find compatible meshes\n for (let subIndex = index + 1; subIndex < globalLength; subIndex++) {\n const otherMesh = globalPool[subIndex];\n if (!this._canBeMerged(otherMesh)) {\n continue;\n }\n if (otherMesh.material !== current.material) {\n continue;\n }\n if (otherMesh.checkCollisions !== current.checkCollisions) {\n continue;\n }\n currentPool.push(otherMesh);\n globalLength--;\n globalPool.splice(subIndex, 1);\n subIndex--;\n }\n if (currentPool.length < 2) {\n continue;\n }\n // Merge meshes\n Mesh.MergeMeshes(currentPool, undefined, true);\n }\n // Call the octree system optimization if it is defined.\n const sceneAsAny = scene;\n if (sceneAsAny.createOrUpdateSelectionOctree) {\n if (updateSelectionTree != undefined) {\n if (updateSelectionTree) {\n sceneAsAny.createOrUpdateSelectionOctree();\n }\n }\n else if (MergeMeshesOptimization.UpdateSelectionTree) {\n sceneAsAny.createOrUpdateSelectionOctree();\n }\n }\n return true;\n }\n}\nMergeMeshesOptimization._UpdateSelectionTree = false;\n/**\n * Defines a list of options used by SceneOptimizer\n * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer\n */\nexport class SceneOptimizerOptions {\n /**\n * Creates a new list of options used by SceneOptimizer\n * @param targetFrameRate defines the target frame rate to reach (60 by default)\n * @param trackerDuration defines the interval between two checks (2000ms by default)\n */\n constructor(\n /**\n * Defines the target frame rate to reach (60 by default)\n */\n targetFrameRate = 60, \n /**\n * Defines the interval between two checks (2000ms by default)\n */\n trackerDuration = 2000) {\n this.targetFrameRate = targetFrameRate;\n this.trackerDuration = trackerDuration;\n /**\n * Gets the list of optimizations to apply\n */\n this.optimizations = new Array();\n }\n /**\n * Add a new optimization\n * @param optimization defines the SceneOptimization to add to the list of active optimizations\n * @returns the current SceneOptimizerOptions\n */\n addOptimization(optimization) {\n this.optimizations.push(optimization);\n return this;\n }\n /**\n * Add a new custom optimization\n * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)\n * @param onGetDescription defines the callback called to get the description attached with the optimization.\n * @param priority defines the priority of this optimization (0 by default which means first in the list)\n * @returns the current SceneOptimizerOptions\n */\n addCustomOptimization(onApply, onGetDescription, priority = 0) {\n const optimization = new CustomOptimization(priority);\n optimization.onApply = onApply;\n optimization.onGetDescription = onGetDescription;\n this.optimizations.push(optimization);\n return this;\n }\n /**\n * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene\n * @param targetFrameRate defines the target frame rate (60 by default)\n * @returns a SceneOptimizerOptions object\n */\n static LowDegradationAllowed(targetFrameRate) {\n const result = new SceneOptimizerOptions(targetFrameRate);\n let priority = 0;\n result.addOptimization(new MergeMeshesOptimization(priority));\n result.addOptimization(new ShadowsOptimization(priority));\n result.addOptimization(new LensFlaresOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new PostProcessesOptimization(priority));\n result.addOptimization(new ParticlesOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new TextureOptimization(priority, 1024));\n return result;\n }\n /**\n * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual\n * @param targetFrameRate defines the target frame rate (60 by default)\n * @returns a SceneOptimizerOptions object\n */\n static ModerateDegradationAllowed(targetFrameRate) {\n const result = new SceneOptimizerOptions(targetFrameRate);\n let priority = 0;\n result.addOptimization(new MergeMeshesOptimization(priority));\n result.addOptimization(new ShadowsOptimization(priority));\n result.addOptimization(new LensFlaresOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new PostProcessesOptimization(priority));\n result.addOptimization(new ParticlesOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new TextureOptimization(priority, 512));\n // Next priority\n priority++;\n result.addOptimization(new RenderTargetsOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new HardwareScalingOptimization(priority, 2));\n return result;\n }\n /**\n * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual\n * @param targetFrameRate defines the target frame rate (60 by default)\n * @returns a SceneOptimizerOptions object\n */\n static HighDegradationAllowed(targetFrameRate) {\n const result = new SceneOptimizerOptions(targetFrameRate);\n let priority = 0;\n result.addOptimization(new MergeMeshesOptimization(priority));\n result.addOptimization(new ShadowsOptimization(priority));\n result.addOptimization(new LensFlaresOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new PostProcessesOptimization(priority));\n result.addOptimization(new ParticlesOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new TextureOptimization(priority, 256));\n // Next priority\n priority++;\n result.addOptimization(new RenderTargetsOptimization(priority));\n // Next priority\n priority++;\n result.addOptimization(new HardwareScalingOptimization(priority, 4));\n return result;\n }\n}\n/**\n * Class used to run optimizations in order to reach a target frame rate\n * @description More details at https://doc.babylonjs.com/features/featuresDeepDive/scene/sceneOptimizer\n */\nexport class SceneOptimizer {\n /**\n * Gets or sets a boolean indicating if the optimizer is in improvement mode\n */\n get isInImprovementMode() {\n return this._improvementMode;\n }\n set isInImprovementMode(value) {\n this._improvementMode = value;\n }\n /**\n * Gets the current priority level (0 at start)\n */\n get currentPriorityLevel() {\n return this._currentPriorityLevel;\n }\n /**\n * Gets the current frame rate checked by the SceneOptimizer\n */\n get currentFrameRate() {\n return this._currentFrameRate;\n }\n /**\n * Gets or sets the current target frame rate (60 by default)\n */\n get targetFrameRate() {\n return this._targetFrameRate;\n }\n /**\n * Gets or sets the current target frame rate (60 by default)\n */\n set targetFrameRate(value) {\n this._targetFrameRate = value;\n }\n /**\n * Gets or sets the current interval between two checks (every 2000ms by default)\n */\n get trackerDuration() {\n return this._trackerDuration;\n }\n /**\n * Gets or sets the current interval between two checks (every 2000ms by default)\n */\n set trackerDuration(value) {\n this._trackerDuration = value;\n }\n /**\n * Gets the list of active optimizations\n */\n get optimizations() {\n return this._options.optimizations;\n }\n /**\n * Creates a new SceneOptimizer\n * @param scene defines the scene to work on\n * @param options defines the options to use with the SceneOptimizer\n * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)\n * @param improvementMode defines if the scene optimizer must run the maximum optimization while staying over a target frame instead of trying to reach the target framerate (false by default)\n */\n constructor(scene, options, autoGeneratePriorities = true, improvementMode = false) {\n this._isRunning = false;\n this._currentPriorityLevel = 0;\n this._targetFrameRate = 60;\n this._trackerDuration = 2000;\n this._currentFrameRate = 0;\n this._improvementMode = false;\n /**\n * Defines an observable called when the optimizer reaches the target frame rate\n */\n this.onSuccessObservable = new Observable();\n /**\n * Defines an observable called when the optimizer enables an optimization\n */\n this.onNewOptimizationAppliedObservable = new Observable();\n /**\n * Defines an observable called when the optimizer is not able to reach the target frame rate\n */\n this.onFailureObservable = new Observable();\n if (!options) {\n this._options = new SceneOptimizerOptions();\n }\n else {\n this._options = options;\n }\n if (this._options.targetFrameRate) {\n this._targetFrameRate = this._options.targetFrameRate;\n }\n if (this._options.trackerDuration) {\n this._trackerDuration = this._options.trackerDuration;\n }\n if (autoGeneratePriorities) {\n let priority = 0;\n for (const optim of this._options.optimizations) {\n optim.priority = priority++;\n }\n }\n this._improvementMode = improvementMode;\n this._scene = scene || EngineStore.LastCreatedScene;\n this._sceneDisposeObserver = this._scene.onDisposeObservable.add(() => {\n this._sceneDisposeObserver = null;\n this.dispose();\n });\n }\n /**\n * Stops the current optimizer\n */\n stop() {\n this._isRunning = false;\n }\n /**\n * Reset the optimizer to initial step (current priority level = 0)\n */\n reset() {\n this._currentPriorityLevel = 0;\n }\n /**\n * Start the optimizer. By default it will try to reach a specific framerate\n * but if the optimizer is set with improvementMode === true then it will run all optimization while frame rate is above the target frame rate\n */\n start() {\n if (this._isRunning) {\n return;\n }\n this._isRunning = true;\n // Let's wait for the scene to be ready before running our check\n this._scene.executeWhenReady(() => {\n setTimeout(() => {\n this._checkCurrentState();\n }, this._trackerDuration);\n });\n }\n _checkCurrentState() {\n if (!this._isRunning) {\n return;\n }\n const scene = this._scene;\n const options = this._options;\n this._currentFrameRate = Math.round(scene.getEngine().getFps());\n if ((this._improvementMode && this._currentFrameRate <= this._targetFrameRate) || (!this._improvementMode && this._currentFrameRate >= this._targetFrameRate)) {\n this._isRunning = false;\n this.onSuccessObservable.notifyObservers(this);\n return;\n }\n // Apply current level of optimizations\n let allDone = true;\n let noOptimizationApplied = true;\n for (let index = 0; index < options.optimizations.length; index++) {\n const optimization = options.optimizations[index];\n if (optimization.priority === this._currentPriorityLevel) {\n noOptimizationApplied = false;\n allDone = allDone && optimization.apply(scene, this);\n this.onNewOptimizationAppliedObservable.notifyObservers(optimization);\n }\n }\n // If no optimization was applied, this is a failure :(\n if (noOptimizationApplied) {\n this._isRunning = false;\n this.onFailureObservable.notifyObservers(this);\n return;\n }\n // If all optimizations were done, move to next level\n if (allDone) {\n this._currentPriorityLevel++;\n }\n // Let's the system running for a specific amount of time before checking FPS\n scene.executeWhenReady(() => {\n setTimeout(() => {\n this._checkCurrentState();\n }, this._trackerDuration);\n });\n }\n /**\n * Release all resources\n */\n dispose() {\n this.stop();\n this.onSuccessObservable.clear();\n this.onFailureObservable.clear();\n this.onNewOptimizationAppliedObservable.clear();\n if (this._sceneDisposeObserver) {\n this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);\n }\n }\n /**\n * Helper function to create a SceneOptimizer with one single line of code\n * @param scene defines the scene to work on\n * @param options defines the options to use with the SceneOptimizer\n * @param onSuccess defines a callback to call on success\n * @param onFailure defines a callback to call on failure\n * @returns the new SceneOptimizer object\n */\n static OptimizeAsync(scene, options, onSuccess, onFailure) {\n const optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);\n if (onSuccess) {\n optimizer.onSuccessObservable.add(() => {\n onSuccess();\n });\n }\n if (onFailure) {\n optimizer.onFailureObservable.add(() => {\n onFailure();\n });\n }\n optimizer.start();\n return optimizer;\n }\n}\n//# sourceMappingURL=sceneOptimizer.js.map","import { Mesh } from \"../Meshes/mesh.js\";\n\nimport { MultiMaterial } from \"../Materials/multiMaterial.js\";\nimport { SerializationHelper } from \"./decorators.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nlet serializedGeometries = [];\nconst SerializeGeometry = (geometry, serializationGeometries) => {\n if (geometry.doNotSerialize) {\n return;\n }\n serializationGeometries.vertexData.push(geometry.serializeVerticeData());\n serializedGeometries[geometry.id] = true;\n};\nconst SerializeMesh = (mesh, serializationScene) => {\n const serializationObject = {};\n // Geometry\n const geometry = mesh._geometry;\n if (geometry) {\n if (!mesh.getScene().getGeometryById(geometry.id)) {\n // Geometry was in the memory but not added to the scene, nevertheless it's better to serialize to be able to reload the mesh with its geometry\n SerializeGeometry(geometry, serializationScene.geometries);\n }\n }\n // Custom\n if (mesh.serialize) {\n mesh.serialize(serializationObject);\n }\n return serializationObject;\n};\nconst FinalizeSingleMesh = (mesh, serializationObject) => {\n //only works if the mesh is already loaded\n if (mesh.delayLoadState === 1 || mesh.delayLoadState === 0) {\n const serializeMaterial = (material) => {\n serializationObject.materials = serializationObject.materials || [];\n if (mesh.material && !serializationObject.materials.some((mat) => mat.id === mesh.material.id)) {\n serializationObject.materials.push(material.serialize());\n }\n };\n //serialize material\n if (mesh.material && !mesh.material.doNotSerialize) {\n if (mesh.material instanceof MultiMaterial) {\n serializationObject.multiMaterials = serializationObject.multiMaterials || [];\n if (!serializationObject.multiMaterials.some((mat) => mat.id === mesh.material.id)) {\n serializationObject.multiMaterials.push(mesh.material.serialize());\n for (const submaterial of mesh.material.subMaterials) {\n if (submaterial) {\n serializeMaterial(submaterial);\n }\n }\n }\n }\n else {\n serializeMaterial(mesh.material);\n }\n }\n else if (!mesh.material) {\n serializeMaterial(mesh.getScene().defaultMaterial);\n }\n //serialize geometry\n const geometry = mesh._geometry;\n if (geometry) {\n if (!serializationObject.geometries) {\n serializationObject.geometries = {};\n serializationObject.geometries.boxes = [];\n serializationObject.geometries.spheres = [];\n serializationObject.geometries.cylinders = [];\n serializationObject.geometries.toruses = [];\n serializationObject.geometries.grounds = [];\n serializationObject.geometries.planes = [];\n serializationObject.geometries.torusKnots = [];\n serializationObject.geometries.vertexData = [];\n }\n SerializeGeometry(geometry, serializationObject.geometries);\n }\n // Skeletons\n if (mesh.skeleton && !mesh.skeleton.doNotSerialize) {\n serializationObject.skeletons = serializationObject.skeletons || [];\n serializationObject.skeletons.push(mesh.skeleton.serialize());\n }\n //serialize the actual mesh\n serializationObject.meshes = serializationObject.meshes || [];\n serializationObject.meshes.push(SerializeMesh(mesh, serializationObject));\n }\n};\n/**\n * Class used to serialize a scene into a string\n */\nexport class SceneSerializer {\n /**\n * Clear cache used by a previous serialization\n */\n static ClearCache() {\n serializedGeometries = [];\n }\n /**\n * Serialize a scene into a JSON compatible object\n * Note that if the current engine does not support synchronous texture reading (like WebGPU), you should use SerializeAsync instead\n * as else you may not retrieve the proper base64 encoded texture data (when using the Texture.ForceSerializeBuffers flag)\n * @param scene defines the scene to serialize\n * @returns a JSON compatible object\n */\n static Serialize(scene) {\n return SceneSerializer._Serialize(scene);\n }\n static _Serialize(scene, checkSyncReadSupported = true) {\n const serializationObject = {};\n if (checkSyncReadSupported && !scene.getEngine()._features.supportSyncTextureRead && Texture.ForceSerializeBuffers) {\n console.warn(\"The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead.\");\n }\n SceneSerializer.ClearCache();\n // Scene\n serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;\n serializationObject.autoClear = scene.autoClear;\n serializationObject.clearColor = scene.clearColor.asArray();\n serializationObject.ambientColor = scene.ambientColor.asArray();\n serializationObject.gravity = scene.gravity.asArray();\n serializationObject.collisionsEnabled = scene.collisionsEnabled;\n serializationObject.useRightHandedSystem = scene.useRightHandedSystem;\n // Fog\n if (scene.fogMode && scene.fogMode !== 0) {\n serializationObject.fogMode = scene.fogMode;\n serializationObject.fogColor = scene.fogColor.asArray();\n serializationObject.fogStart = scene.fogStart;\n serializationObject.fogEnd = scene.fogEnd;\n serializationObject.fogDensity = scene.fogDensity;\n }\n //Physics\n if (scene.isPhysicsEnabled()) {\n const physicEngine = scene.getPhysicsEngine();\n if (physicEngine) {\n serializationObject.physicsEnabled = true;\n serializationObject.physicsGravity = physicEngine.gravity.asArray();\n serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();\n }\n }\n // Metadata\n if (scene.metadata) {\n serializationObject.metadata = scene.metadata;\n }\n // Morph targets\n serializationObject.morphTargetManagers = [];\n for (const abstractMesh of scene.meshes) {\n const manager = abstractMesh.morphTargetManager;\n if (manager) {\n serializationObject.morphTargetManagers.push(manager.serialize());\n }\n }\n // Lights\n serializationObject.lights = [];\n let index;\n let light;\n for (index = 0; index < scene.lights.length; index++) {\n light = scene.lights[index];\n if (!light.doNotSerialize) {\n serializationObject.lights.push(light.serialize());\n }\n }\n // Cameras\n serializationObject.cameras = [];\n for (index = 0; index < scene.cameras.length; index++) {\n const camera = scene.cameras[index];\n if (!camera.doNotSerialize) {\n serializationObject.cameras.push(camera.serialize());\n }\n }\n if (scene.activeCamera) {\n serializationObject.activeCameraID = scene.activeCamera.id;\n }\n // Animations\n SerializationHelper.AppendSerializedAnimations(scene, serializationObject);\n // Animation Groups\n if (scene.animationGroups && scene.animationGroups.length > 0) {\n serializationObject.animationGroups = [];\n for (let animationGroupIndex = 0; animationGroupIndex < scene.animationGroups.length; animationGroupIndex++) {\n const animationGroup = scene.animationGroups[animationGroupIndex];\n serializationObject.animationGroups.push(animationGroup.serialize());\n }\n }\n // Reflection probes\n if (scene.reflectionProbes && scene.reflectionProbes.length > 0) {\n serializationObject.reflectionProbes = [];\n for (index = 0; index < scene.reflectionProbes.length; index++) {\n const reflectionProbe = scene.reflectionProbes[index];\n serializationObject.reflectionProbes.push(reflectionProbe.serialize());\n }\n }\n // Materials\n serializationObject.materials = [];\n serializationObject.multiMaterials = [];\n let material;\n for (index = 0; index < scene.materials.length; index++) {\n material = scene.materials[index];\n if (!material.doNotSerialize) {\n serializationObject.materials.push(material.serialize());\n }\n }\n // MultiMaterials\n serializationObject.multiMaterials = [];\n for (index = 0; index < scene.multiMaterials.length; index++) {\n const multiMaterial = scene.multiMaterials[index];\n serializationObject.multiMaterials.push(multiMaterial.serialize());\n }\n // Environment texture\n if (scene.environmentTexture) {\n if (scene.environmentTexture._files) {\n serializationObject.environmentTexture = scene.environmentTexture.serialize();\n }\n else {\n serializationObject.environmentTexture = scene.environmentTexture.name;\n serializationObject.environmentTextureRotationY = scene.environmentTexture.rotationY;\n }\n }\n // Environment Intensity\n serializationObject.environmentIntensity = scene.environmentIntensity;\n // Skeletons\n serializationObject.skeletons = [];\n for (index = 0; index < scene.skeletons.length; index++) {\n const skeleton = scene.skeletons[index];\n if (!skeleton.doNotSerialize) {\n serializationObject.skeletons.push(skeleton.serialize());\n }\n }\n // Transform nodes\n serializationObject.transformNodes = [];\n for (index = 0; index < scene.transformNodes.length; index++) {\n if (!scene.transformNodes[index].doNotSerialize) {\n serializationObject.transformNodes.push(scene.transformNodes[index].serialize());\n }\n }\n // Geometries\n serializationObject.geometries = {};\n serializationObject.geometries.boxes = [];\n serializationObject.geometries.spheres = [];\n serializationObject.geometries.cylinders = [];\n serializationObject.geometries.toruses = [];\n serializationObject.geometries.grounds = [];\n serializationObject.geometries.planes = [];\n serializationObject.geometries.torusKnots = [];\n serializationObject.geometries.vertexData = [];\n serializedGeometries = [];\n const geometries = scene.getGeometries();\n for (index = 0; index < geometries.length; index++) {\n const geometry = geometries[index];\n if (geometry.isReady()) {\n SerializeGeometry(geometry, serializationObject.geometries);\n }\n }\n // Meshes\n serializationObject.meshes = [];\n for (index = 0; index < scene.meshes.length; index++) {\n const abstractMesh = scene.meshes[index];\n if (abstractMesh instanceof Mesh) {\n const mesh = abstractMesh;\n if (!mesh.doNotSerialize) {\n if (mesh.delayLoadState === 1 || mesh.delayLoadState === 0) {\n serializationObject.meshes.push(SerializeMesh(mesh, serializationObject));\n }\n }\n }\n }\n // Particles Systems\n serializationObject.particleSystems = [];\n for (index = 0; index < scene.particleSystems.length; index++) {\n serializationObject.particleSystems.push(scene.particleSystems[index].serialize(false));\n }\n // Post processes\n serializationObject.postProcesses = [];\n for (index = 0; index < scene.postProcesses.length; index++) {\n serializationObject.postProcesses.push(scene.postProcesses[index].serialize());\n }\n // Action Manager\n if (scene.actionManager) {\n serializationObject.actions = scene.actionManager.serialize(\"scene\");\n }\n // Components\n for (const component of scene._serializableComponents) {\n component.serialize(serializationObject);\n }\n return serializationObject;\n }\n /**\n * Serialize a scene into a JSON compatible object\n * @param scene defines the scene to serialize\n * @returns a JSON promise compatible object\n */\n static SerializeAsync(scene) {\n const serializationObject = SceneSerializer._Serialize(scene, false);\n const promises = [];\n this._CollectPromises(serializationObject, promises);\n return Promise.all(promises).then(() => serializationObject);\n }\n static _CollectPromises(obj, promises) {\n if (Array.isArray(obj)) {\n for (let i = 0; i < obj.length; ++i) {\n const o = obj[i];\n if (o instanceof Promise) {\n promises.push(o.then((res) => (obj[i] = res)));\n }\n else if (o instanceof Object || Array.isArray(o)) {\n this._CollectPromises(o, promises);\n }\n }\n }\n else if (obj instanceof Object) {\n for (const name in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, name)) {\n const o = obj[name];\n if (o instanceof Promise) {\n promises.push(o.then((res) => (obj[name] = res)));\n }\n else if (o instanceof Object || Array.isArray(o)) {\n this._CollectPromises(o, promises);\n }\n }\n }\n }\n }\n /**\n * Serialize a mesh into a JSON compatible object\n * @param toSerialize defines the mesh to serialize\n * @param withParents defines if parents must be serialized as well\n * @param withChildren defines if children must be serialized as well\n * @returns a JSON compatible object\n */\n static SerializeMesh(toSerialize /* Mesh || Mesh[] */, withParents = false, withChildren = false) {\n const serializationObject = {};\n SceneSerializer.ClearCache();\n toSerialize = toSerialize instanceof Array ? toSerialize : [toSerialize];\n if (withParents || withChildren) {\n //deliberate for loop! not for each, appended should be processed as well.\n for (let i = 0; i < toSerialize.length; ++i) {\n if (withChildren) {\n toSerialize[i].getDescendants().forEach((node) => {\n if (node instanceof Mesh && toSerialize.indexOf(node) < 0 && !node.doNotSerialize) {\n toSerialize.push(node);\n }\n });\n }\n //make sure the array doesn't contain the object already\n if (withParents && toSerialize[i].parent && toSerialize.indexOf(toSerialize[i].parent) < 0 && !toSerialize[i].parent.doNotSerialize) {\n toSerialize.push(toSerialize[i].parent);\n }\n }\n }\n toSerialize.forEach((mesh) => {\n FinalizeSingleMesh(mesh, serializationObject);\n });\n return serializationObject;\n }\n}\n//# sourceMappingURL=sceneSerializer.js.map","import { Tools } from \"./tools.js\";\n/**\n * This can help with recording videos from BabylonJS.\n * This is based on the available WebRTC functionalities of the browser.\n *\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToVideo\n */\nexport class VideoRecorder {\n /**\n * Returns whether or not the VideoRecorder is available in your browser.\n * @param engine Defines the Babylon Engine.\n * @returns true if supported otherwise false.\n */\n static IsSupported(engine) {\n const canvas = engine.getRenderingCanvas();\n return !!canvas && typeof canvas.captureStream === \"function\";\n }\n /**\n * True when a recording is already in progress.\n */\n get isRecording() {\n return !!this._canvas && this._canvas.isRecording;\n }\n /**\n * Create a new VideoCapture object which can help converting what you see in Babylon to a video file.\n * @param engine Defines the BabylonJS Engine you wish to record.\n * @param options Defines options that can be used to customize the capture.\n */\n constructor(engine, options = {}) {\n if (!VideoRecorder.IsSupported(engine)) {\n throw \"Your browser does not support recording so far.\";\n }\n const canvas = engine.getRenderingCanvas();\n if (!canvas) {\n throw \"The babylon engine must have a canvas to be recorded\";\n }\n this._canvas = canvas;\n this._canvas.isRecording = false;\n this._options = Object.assign(Object.assign({}, VideoRecorder._DefaultOptions), options);\n const stream = this._canvas.captureStream(this._options.fps);\n if (this._options.audioTracks) {\n for (const track of this._options.audioTracks) {\n stream.addTrack(track);\n }\n }\n this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });\n this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);\n this._mediaRecorder.onerror = this._handleError.bind(this);\n this._mediaRecorder.onstop = this._handleStop.bind(this);\n }\n /**\n * Stops the current recording before the default capture timeout passed in the startRecording function.\n */\n stopRecording() {\n if (!this._canvas || !this._mediaRecorder) {\n return;\n }\n if (!this.isRecording) {\n return;\n }\n this._canvas.isRecording = false;\n this._mediaRecorder.stop();\n }\n /**\n * Starts recording the canvas for a max duration specified in parameters.\n * @param fileName Defines the name of the file to be downloaded when the recording stop.\n * If null no automatic download will start and you can rely on the promise to get the data back.\n * @param maxDuration Defines the maximum recording time in seconds.\n * It defaults to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.\n * @returns A promise callback at the end of the recording with the video data in Blob.\n */\n startRecording(fileName = \"babylonjs.webm\", maxDuration = 7) {\n if (!this._canvas || !this._mediaRecorder) {\n throw \"Recorder has already been disposed\";\n }\n if (this.isRecording) {\n throw \"Recording already in progress\";\n }\n if (maxDuration > 0) {\n setTimeout(() => {\n this.stopRecording();\n }, maxDuration * 1000);\n }\n this._fileName = fileName;\n this._recordedChunks = [];\n this._resolve = null;\n this._reject = null;\n this._canvas.isRecording = true;\n this._mediaRecorder.start(this._options.recordChunckSize);\n return new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n /**\n * Releases internal resources used during the recording.\n */\n dispose() {\n this._canvas = null;\n this._mediaRecorder = null;\n this._recordedChunks = [];\n this._fileName = null;\n this._resolve = null;\n this._reject = null;\n }\n _handleDataAvailable(event) {\n if (event.data.size > 0) {\n this._recordedChunks.push(event.data);\n }\n }\n _handleError(event) {\n this.stopRecording();\n if (this._reject) {\n this._reject(event.error);\n }\n else {\n throw new event.error();\n }\n }\n _handleStop() {\n this.stopRecording();\n const superBuffer = new Blob(this._recordedChunks);\n if (this._resolve) {\n this._resolve(superBuffer);\n }\n window.URL.createObjectURL(superBuffer);\n if (this._fileName) {\n Tools.Download(superBuffer, this._fileName);\n }\n }\n}\nVideoRecorder._DefaultOptions = {\n mimeType: \"video/webm\",\n fps: 25,\n recordChunckSize: 3000,\n};\n//# sourceMappingURL=videoRecorder.js.map","import { Texture } from \"../Materials/Textures/texture.js\";\nimport { RenderTargetTexture } from \"../Materials/Textures/renderTargetTexture.js\";\nimport { FxaaPostProcess } from \"../PostProcesses/fxaaPostProcess.js\";\n\nimport { Logger } from \"./logger.js\";\nimport { Tools } from \"./tools.js\";\nimport { DumpTools } from \"./dumpTools.js\";\nimport { ApplyPostProcess } from \"./textureTools.js\";\nlet screenshotCanvas = null;\n/**\n * Captures a screenshot of the current rendering\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine defines the rendering engine\n * @param camera defines the source camera\n * @param size This parameter can be set to a single number or to an object with the\n * following (optional) properties: precision, width, height. If a single number is passed,\n * it will be used for both width and height. If an object is passed, the screenshot size\n * will be derived from the parameters. The precision property is a multiplier allowing\n * rendering at a higher or lower resolution\n * @param successCallback defines the callback receives a single parameter which contains the\n * screenshot as a string of base64-encoded characters. This string can be assigned to the\n * src parameter of an to display it\n * @param mimeType defines the MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param forceDownload force the system to download the image even if a successCallback is provided\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n */\nexport function CreateScreenshot(engine, camera, size, successCallback, mimeType = \"image/png\", forceDownload = false, quality) {\n const { height, width } = _GetScreenshotSize(engine, camera, size);\n if (!(height && width)) {\n Logger.Error(\"Invalid 'size' parameter !\");\n return;\n }\n if (!screenshotCanvas) {\n screenshotCanvas = document.createElement(\"canvas\");\n }\n screenshotCanvas.width = width;\n screenshotCanvas.height = height;\n const renderContext = screenshotCanvas.getContext(\"2d\");\n const ratio = engine.getRenderWidth() / engine.getRenderHeight();\n let newWidth = width;\n let newHeight = newWidth / ratio;\n if (newHeight > height) {\n newHeight = height;\n newWidth = newHeight * ratio;\n }\n const offsetX = Math.max(0, width - newWidth) / 2;\n const offsetY = Math.max(0, height - newHeight) / 2;\n const scene = camera.getScene();\n if (scene.activeCamera !== camera) {\n CreateScreenshotUsingRenderTarget(engine, camera, size, (data) => {\n if (forceDownload) {\n const blob = new Blob([data]);\n Tools.DownloadBlob(blob);\n if (successCallback) {\n successCallback(\"\");\n }\n }\n else if (successCallback) {\n successCallback(data);\n }\n }, mimeType, 1.0, engine.getCreationOptions().antialias, undefined, undefined, undefined, undefined, quality);\n }\n else {\n engine.onEndFrameObservable.addOnce(() => {\n const renderingCanvas = engine.getRenderingCanvas();\n if (renderContext && renderingCanvas) {\n renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);\n }\n if (screenshotCanvas) {\n if (forceDownload) {\n Tools.EncodeScreenshotCanvasData(screenshotCanvas, undefined, mimeType, undefined, quality);\n if (successCallback) {\n successCallback(\"\");\n }\n }\n else {\n Tools.EncodeScreenshotCanvasData(screenshotCanvas, successCallback, mimeType, undefined, quality);\n }\n }\n });\n }\n}\n/**\n * Captures a screenshot of the current rendering\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine defines the rendering engine\n * @param camera defines the source camera\n * @param size This parameter can be set to a single number or to an object with the\n * following (optional) properties: precision, width, height. If a single number is passed,\n * it will be used for both width and height. If an object is passed, the screenshot size\n * will be derived from the parameters. The precision property is a multiplier allowing\n * rendering at a higher or lower resolution\n * @param mimeType defines the MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n * @returns screenshot as a string of base64-encoded characters. This string can be assigned\n * to the src parameter of an to display it\n */\nexport function CreateScreenshotAsync(engine, camera, size, mimeType = \"image/png\", quality) {\n return new Promise((resolve, reject) => {\n CreateScreenshot(engine, camera, size, (data) => {\n if (typeof data !== \"undefined\") {\n resolve(data);\n }\n else {\n reject(new Error(\"Data is undefined\"));\n }\n }, mimeType, undefined, quality);\n });\n}\n/**\n * Captures a screenshot of the current rendering for a specific size. This will render the entire canvas but will generate a blink (due to canvas resize)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine defines the rendering engine\n * @param camera defines the source camera\n * @param width defines the expected width\n * @param height defines the expected height\n * @param mimeType defines the MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n * @returns screenshot as a string of base64-encoded characters. This string can be assigned\n * to the src parameter of an to display it\n */\nexport function CreateScreenshotWithResizeAsync(engine, camera, width, height, mimeType = \"image/png\", quality) {\n return new Promise((resolve) => {\n CreateScreenshot(engine, camera, { width: width, height: height }, () => {\n resolve();\n }, mimeType, true, quality);\n });\n}\n/**\n * Generates an image screenshot from the specified camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine The engine to use for rendering\n * @param camera The camera to use for rendering\n * @param size This parameter can be set to a single number or to an object with the\n * following (optional) properties: precision, width, height, finalWidth, finalHeight. If a single number is passed,\n * it will be used for both width and height, as well as finalWidth, finalHeight. If an object is passed, the screenshot size\n * will be derived from the parameters. The precision property is a multiplier allowing\n * rendering at a higher or lower resolution\n * @param successCallback The callback receives a single parameter which contains the\n * screenshot as a string of base64-encoded characters. This string can be assigned to the\n * src parameter of an to display it\n * @param mimeType The MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param samples Texture samples (default: 1)\n * @param antialiasing Whether antialiasing should be turned on or not (default: false)\n * @param fileName A name for for the downloaded file.\n * @param renderSprites Whether the sprites should be rendered or not (default: false)\n * @param enableStencilBuffer Whether the stencil buffer should be enabled or not (default: false)\n * @param useLayerMask if the camera's layer mask should be used to filter what should be rendered (default: true)\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n */\nexport function CreateScreenshotUsingRenderTarget(engine, camera, size, successCallback, mimeType = \"image/png\", samples = 1, antialiasing = false, fileName, renderSprites = false, enableStencilBuffer = false, useLayerMask = true, quality) {\n const { height, width, finalWidth, finalHeight } = _GetScreenshotSize(engine, camera, size);\n const targetTextureSize = { width, height };\n if (!(height && width)) {\n Logger.Error(\"Invalid 'size' parameter !\");\n return;\n }\n const originalSize = { width: engine.getRenderWidth(), height: engine.getRenderHeight() };\n engine.setSize(width, height); // we need this call to trigger onResizeObservable with the screenshot width/height on all the subsystems that are observing this event and that needs to (re)create some resources with the right dimensions\n const scene = camera.getScene();\n // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)\n const texture = new RenderTargetTexture(\"screenShot\", targetTextureSize, scene, false, false, 0, false, Texture.BILINEAR_SAMPLINGMODE, undefined, enableStencilBuffer, undefined, undefined, undefined, samples);\n texture.renderList = scene.meshes.slice();\n texture.samples = samples;\n texture.renderSprites = renderSprites;\n texture.activeCamera = camera;\n texture.forceLayerMaskCheck = useLayerMask;\n const renderToTexture = () => {\n engine.onEndFrameObservable.addOnce(() => {\n if (finalWidth === width && finalHeight === height) {\n texture.readPixels(undefined, undefined, undefined, false).then((data) => {\n DumpTools.DumpData(width, height, data, successCallback, mimeType, fileName, true, undefined, quality);\n texture.dispose();\n });\n }\n else {\n ApplyPostProcess(\"pass\", texture.getInternalTexture(), scene, undefined, undefined, undefined, finalWidth, finalHeight).then((texture) => {\n engine._readTexturePixels(texture, finalWidth, finalHeight, -1, 0, null, true, false, 0, 0).then((data) => {\n DumpTools.DumpData(finalWidth, finalHeight, data, successCallback, mimeType, fileName, true, undefined, quality);\n texture.dispose();\n });\n });\n }\n });\n // render the RTT\n scene.incrementRenderId();\n scene.resetCachedMaterial();\n texture.render(true);\n // re-render the scene after the camera has been reset to the original camera to avoid a flicker that could occur\n // if the camera used for the RTT rendering stays in effect for the next frame (and if that camera was different from the original camera)\n scene.incrementRenderId();\n scene.resetCachedMaterial();\n engine.setSize(originalSize.width, originalSize.height);\n camera.getProjectionMatrix(true); // Force cache refresh;\n scene.render();\n };\n if (antialiasing) {\n const fxaaPostProcess = new FxaaPostProcess(\"antialiasing\", 1.0, scene.activeCamera);\n texture.addPostProcess(fxaaPostProcess);\n // Async Shader Compilation can lead to none ready effects in synchronous code\n if (!fxaaPostProcess.getEffect().isReady()) {\n fxaaPostProcess.getEffect().onCompiled = () => {\n renderToTexture();\n };\n }\n // The effect is ready we can render\n else {\n renderToTexture();\n }\n }\n else {\n // No need to wait for extra resources to be ready\n renderToTexture();\n }\n}\n/**\n * Generates an image screenshot from the specified camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine The engine to use for rendering\n * @param camera The camera to use for rendering\n * @param size This parameter can be set to a single number or to an object with the\n * following (optional) properties: precision, width, height. If a single number is passed,\n * it will be used for both width and height. If an object is passed, the screenshot size\n * will be derived from the parameters. The precision property is a multiplier allowing\n * rendering at a higher or lower resolution\n * @param mimeType The MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param samples Texture samples (default: 1)\n * @param antialiasing Whether antialiasing should be turned on or not (default: false)\n * @param fileName A name for for the downloaded file.\n * @param renderSprites Whether the sprites should be rendered or not (default: false)\n * @param enableStencilBuffer Whether the stencil buffer should be enabled or not (default: false)\n * @param useLayerMask if the camera's layer mask should be used to filter what should be rendered (default: true)\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n * @returns screenshot as a string of base64-encoded characters. This string can be assigned\n * to the src parameter of an to display it\n */\nexport function CreateScreenshotUsingRenderTargetAsync(engine, camera, size, mimeType = \"image/png\", samples = 1, antialiasing = false, fileName, renderSprites = false, enableStencilBuffer = false, useLayerMask = true, quality) {\n return new Promise((resolve, reject) => {\n CreateScreenshotUsingRenderTarget(engine, camera, size, (data) => {\n if (typeof data !== \"undefined\") {\n resolve(data);\n }\n else {\n reject(new Error(\"Data is undefined\"));\n }\n }, mimeType, samples, antialiasing, fileName, renderSprites, enableStencilBuffer, useLayerMask, quality);\n });\n}\n/**\n * Gets height and width for screenshot size\n * @param engine\n * @param camera\n * @param size\n * @private\n */\nfunction _GetScreenshotSize(engine, camera, size) {\n let height = 0;\n let width = 0;\n let finalWidth = 0;\n let finalHeight = 0;\n //If a size value defined as object\n if (typeof size === \"object\") {\n const precision = size.precision\n ? Math.abs(size.precision) // prevent GL_INVALID_VALUE : glViewport: negative width/height\n : 1;\n //If a width and height values is specified\n if (size.width && size.height) {\n height = size.height * precision;\n width = size.width * precision;\n }\n //If passing only width, computing height to keep display canvas ratio.\n else if (size.width && !size.height) {\n width = size.width * precision;\n height = Math.round(width / engine.getAspectRatio(camera));\n }\n //If passing only height, computing width to keep display canvas ratio.\n else if (size.height && !size.width) {\n height = size.height * precision;\n width = Math.round(height * engine.getAspectRatio(camera));\n }\n else {\n width = Math.round(engine.getRenderWidth() * precision);\n height = Math.round(width / engine.getAspectRatio(camera));\n }\n //If a finalWidth and finalHeight values is specified\n if (size.finalWidth && size.finalHeight) {\n finalHeight = size.finalHeight;\n finalWidth = size.finalWidth;\n }\n //If passing only finalWidth, computing finalHeight to keep display canvas ratio.\n else if (size.finalWidth && !size.finalHeight) {\n finalWidth = size.finalWidth;\n finalHeight = Math.round(finalWidth / engine.getAspectRatio(camera));\n }\n //If passing only finalHeight, computing finalWidth to keep display canvas ratio.\n else if (size.finalHeight && !size.finalWidth) {\n finalHeight = size.finalHeight;\n finalWidth = Math.round(finalHeight * engine.getAspectRatio(camera));\n }\n else {\n finalWidth = width;\n finalHeight = height;\n }\n }\n //Assuming here that \"size\" parameter is a number\n else if (!isNaN(size)) {\n height = size;\n width = size;\n finalWidth = size;\n finalHeight = size;\n }\n // When creating the image data from the CanvasRenderingContext2D, the width and height is clamped to the size of the _gl context\n // On certain GPUs, it seems as if the _gl context truncates to an integer automatically. Therefore, if a user tries to pass the width of their canvas element\n // and it happens to be a float (1000.5 x 600.5 px), the engine.readPixels will return a different size array than context.createImageData\n // to resolve this, we truncate the floats here to ensure the same size\n if (width) {\n width = Math.floor(width);\n }\n if (height) {\n height = Math.floor(height);\n }\n if (finalWidth) {\n finalWidth = Math.floor(finalWidth);\n }\n if (finalHeight) {\n finalHeight = Math.floor(finalHeight);\n }\n return { height: height | 0, width: width | 0, finalWidth: finalWidth | 0, finalHeight: finalHeight | 0 };\n}\n/**\n * Class containing a set of static utilities functions for screenshots\n */\nexport const ScreenshotTools = {\n /**\n * Captures a screenshot of the current rendering\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine defines the rendering engine\n * @param camera defines the source camera\n * @param size This parameter can be set to a single number or to an object with the\n * following (optional) properties: precision, width, height. If a single number is passed,\n * it will be used for both width and height. If an object is passed, the screenshot size\n * will be derived from the parameters. The precision property is a multiplier allowing\n * rendering at a higher or lower resolution\n * @param successCallback defines the callback receives a single parameter which contains the\n * screenshot as a string of base64-encoded characters. This string can be assigned to the\n * src parameter of an to display it\n * @param mimeType defines the MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param forceDownload force the system to download the image even if a successCallback is provided\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n */\n CreateScreenshot,\n /**\n * Captures a screenshot of the current rendering\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine defines the rendering engine\n * @param camera defines the source camera\n * @param size This parameter can be set to a single number or to an object with the\n * following (optional) properties: precision, width, height. If a single number is passed,\n * it will be used for both width and height. If an object is passed, the screenshot size\n * will be derived from the parameters. The precision property is a multiplier allowing\n * rendering at a higher or lower resolution\n * @param mimeType defines the MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n * @returns screenshot as a string of base64-encoded characters. This string can be assigned\n * to the src parameter of an to display it\n */\n CreateScreenshotAsync,\n /**\n * Captures a screenshot of the current rendering for a specific size. This will render the entire canvas but will generate a blink (due to canvas resize)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine defines the rendering engine\n * @param camera defines the source camera\n * @param width defines the expected width\n * @param height defines the expected height\n * @param mimeType defines the MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n * @returns screenshot as a string of base64-encoded characters. This string can be assigned\n * to the src parameter of an to display it\n */\n CreateScreenshotWithResizeAsync,\n /**\n * Generates an image screenshot from the specified camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine The engine to use for rendering\n * @param camera The camera to use for rendering\n * @param size This parameter can be set to a single number or to an object with the\n * following (optional) properties: precision, width, height. If a single number is passed,\n * it will be used for both width and height. If an object is passed, the screenshot size\n * will be derived from the parameters. The precision property is a multiplier allowing\n * rendering at a higher or lower resolution\n * @param successCallback The callback receives a single parameter which contains the\n * screenshot as a string of base64-encoded characters. This string can be assigned to the\n * src parameter of an to display it\n * @param mimeType The MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param samples Texture samples (default: 1)\n * @param antialiasing Whether antialiasing should be turned on or not (default: false)\n * @param fileName A name for for the downloaded file.\n * @param renderSprites Whether the sprites should be rendered or not (default: false)\n * @param enableStencilBuffer Whether the stencil buffer should be enabled or not (default: false)\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n */\n CreateScreenshotUsingRenderTarget,\n /**\n * Generates an image screenshot from the specified camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine The engine to use for rendering\n * @param camera The camera to use for rendering\n * @param size This parameter can be set to a single number or to an object with the\n * following (optional) properties: precision, width, height. If a single number is passed,\n * it will be used for both width and height. If an object is passed, the screenshot size\n * will be derived from the parameters. The precision property is a multiplier allowing\n * rendering at a higher or lower resolution\n * @param mimeType The MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param samples Texture samples (default: 1)\n * @param antialiasing Whether antialiasing should be turned on or not (default: false)\n * @param fileName A name for for the downloaded file.\n * @param renderSprites Whether the sprites should be rendered or not (default: false)\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n * @returns screenshot as a string of base64-encoded characters. This string can be assigned\n * to the src parameter of an to display it\n */\n CreateScreenshotUsingRenderTargetAsync,\n};\n/**\n * This will be executed automatically for UMD and es5.\n * If esm dev wants the side effects to execute they will have to run it manually\n * Once we build native modules those need to be exported.\n * @internal\n */\nconst initSideEffects = () => {\n // References the dependencies.\n Tools.CreateScreenshot = CreateScreenshot;\n Tools.CreateScreenshotAsync = CreateScreenshotAsync;\n Tools.CreateScreenshotUsingRenderTarget = CreateScreenshotUsingRenderTarget;\n Tools.CreateScreenshotUsingRenderTargetAsync = CreateScreenshotUsingRenderTargetAsync;\n};\ninitSideEffects();\n//# sourceMappingURL=screenshotTools.js.map","/**\n * Enum that determines the text-wrapping mode to use.\n */\nexport var InspectableType;\n(function (InspectableType) {\n /**\n * Checkbox for booleans\n */\n InspectableType[InspectableType[\"Checkbox\"] = 0] = \"Checkbox\";\n /**\n * Sliders for numbers\n */\n InspectableType[InspectableType[\"Slider\"] = 1] = \"Slider\";\n /**\n * Vector3\n */\n InspectableType[InspectableType[\"Vector3\"] = 2] = \"Vector3\";\n /**\n * Quaternions\n */\n InspectableType[InspectableType[\"Quaternion\"] = 3] = \"Quaternion\";\n /**\n * Color3\n */\n InspectableType[InspectableType[\"Color3\"] = 4] = \"Color3\";\n /**\n * String\n */\n InspectableType[InspectableType[\"String\"] = 5] = \"String\";\n /**\n * Button\n */\n InspectableType[InspectableType[\"Button\"] = 6] = \"Button\";\n /**\n * Options\n */\n InspectableType[InspectableType[\"Options\"] = 7] = \"Options\";\n /**\n * Tab\n */\n InspectableType[InspectableType[\"Tab\"] = 8] = \"Tab\";\n /**\n * File button\n */\n InspectableType[InspectableType[\"FileButton\"] = 9] = \"FileButton\";\n /**\n * Vector2\n */\n InspectableType[InspectableType[\"Vector2\"] = 10] = \"Vector2\";\n})(InspectableType || (InspectableType = {}));\n//# sourceMappingURL=iInspectable.js.map","export {};\n//# sourceMappingURL=fileRequest.js.map","export {};\n//# sourceMappingURL=customAnimationFrameRequester.js.map","export {};\n//# sourceMappingURL=screenshotSize.js.map","import { Decode } from \"./stringTools.js\";\n/**\n * Utility class for reading from a data buffer\n */\nexport class DataReader {\n /**\n * Constructor\n * @param buffer The buffer to read\n */\n constructor(buffer) {\n /**\n * The current byte offset from the beginning of the data buffer.\n */\n this.byteOffset = 0;\n this.buffer = buffer;\n }\n /**\n * Loads the given byte length.\n * @param byteLength The byte length to load\n * @returns A promise that resolves when the load is complete\n */\n loadAsync(byteLength) {\n return this.buffer.readAsync(this.byteOffset, byteLength).then((data) => {\n this._dataView = new DataView(data.buffer, data.byteOffset, data.byteLength);\n this._dataByteOffset = 0;\n });\n }\n /**\n * Read a unsigned 32-bit integer from the currently loaded data range.\n * @returns The 32-bit integer read\n */\n readUint32() {\n const value = this._dataView.getUint32(this._dataByteOffset, true);\n this._dataByteOffset += 4;\n this.byteOffset += 4;\n return value;\n }\n /**\n * Read a byte array from the currently loaded data range.\n * @param byteLength The byte length to read\n * @returns The byte array read\n */\n readUint8Array(byteLength) {\n const value = new Uint8Array(this._dataView.buffer, this._dataView.byteOffset + this._dataByteOffset, byteLength);\n this._dataByteOffset += byteLength;\n this.byteOffset += byteLength;\n return value;\n }\n /**\n * Read a string from the currently loaded data range.\n * @param byteLength The byte length to read\n * @returns The string read\n */\n readString(byteLength) {\n return Decode(this.readUint8Array(byteLength));\n }\n /**\n * Skips the given byte length the currently loaded data range.\n * @param byteLength The byte length to skip\n */\n skipBytes(byteLength) {\n this._dataByteOffset += byteLength;\n this.byteOffset += byteLength;\n }\n}\n//# sourceMappingURL=dataReader.js.map","/**\n * Class for storing data to local storage if available or in-memory storage otherwise\n */\nexport class DataStorage {\n static _GetStorage() {\n try {\n localStorage.setItem(\"test\", \"\");\n localStorage.removeItem(\"test\");\n return localStorage;\n }\n catch (_a) {\n const inMemoryStorage = {};\n return {\n getItem: (key) => {\n const value = inMemoryStorage[key];\n return value === undefined ? null : value;\n },\n setItem: (key, value) => {\n inMemoryStorage[key] = value;\n },\n };\n }\n }\n /**\n * Reads a string from the data storage\n * @param key The key to read\n * @param defaultValue The value if the key doesn't exist\n * @returns The string value\n */\n static ReadString(key, defaultValue) {\n const value = this._Storage.getItem(key);\n return value !== null ? value : defaultValue;\n }\n /**\n * Writes a string to the data storage\n * @param key The key to write\n * @param value The value to write\n */\n static WriteString(key, value) {\n this._Storage.setItem(key, value);\n }\n /**\n * Reads a boolean from the data storage\n * @param key The key to read\n * @param defaultValue The value if the key doesn't exist\n * @returns The boolean value\n */\n static ReadBoolean(key, defaultValue) {\n const value = this._Storage.getItem(key);\n return value !== null ? value === \"true\" : defaultValue;\n }\n /**\n * Writes a boolean to the data storage\n * @param key The key to write\n * @param value The value to write\n */\n static WriteBoolean(key, value) {\n this._Storage.setItem(key, value ? \"true\" : \"false\");\n }\n /**\n * Reads a number from the data storage\n * @param key The key to read\n * @param defaultValue The value if the key doesn't exist\n * @returns The number value\n */\n static ReadNumber(key, defaultValue) {\n const value = this._Storage.getItem(key);\n return value !== null ? parseFloat(value) : defaultValue;\n }\n /**\n * Writes a number to the data storage\n * @param key The key to write\n * @param value The value to write\n */\n static WriteNumber(key, value) {\n this._Storage.setItem(key, value.toString());\n }\n}\nDataStorage._Storage = DataStorage._GetStorage();\n//# sourceMappingURL=dataStorage.js.map","import { SceneSerializer } from \"./sceneSerializer.js\";\nimport { Mesh } from \"../Meshes/mesh.js\";\nimport { Light } from \"../Lights/light.js\";\nimport { Camera } from \"../Cameras/camera.js\";\nimport { Skeleton } from \"../Bones/skeleton.js\";\nimport { Material } from \"../Materials/material.js\";\nimport { MultiMaterial } from \"../Materials/multiMaterial.js\";\nimport { TransformNode } from \"../Meshes/transformNode.js\";\nimport { ParticleSystem } from \"../Particles/particleSystem.js\";\nimport { MorphTargetManager } from \"../Morph/morphTargetManager.js\";\nimport { ShadowGenerator } from \"../Lights/Shadows/shadowGenerator.js\";\nimport { PostProcess } from \"../PostProcesses/postProcess.js\";\nimport { Texture } from \"../Materials/Textures/texture.js\";\nimport { SerializationHelper } from \"./decorators.js\";\n/**\n * Class used to record delta files between 2 scene states\n */\nexport class SceneRecorder {\n constructor() {\n this._trackedScene = null;\n }\n /**\n * Track a given scene. This means the current scene state will be considered the original state\n * @param scene defines the scene to track\n */\n track(scene) {\n this._trackedScene = scene;\n SerializationHelper.AllowLoadingUniqueId = true;\n this._savedJSON = SceneSerializer.Serialize(scene);\n SerializationHelper.AllowLoadingUniqueId = false;\n }\n /**\n * Get the delta between current state and original state\n * @returns a any containing the delta\n */\n getDelta() {\n if (!this._trackedScene) {\n return null;\n }\n const currentForceSerializeBuffers = Texture.ForceSerializeBuffers;\n Texture.ForceSerializeBuffers = false;\n SerializationHelper.AllowLoadingUniqueId = true;\n const newJSON = SceneSerializer.Serialize(this._trackedScene);\n SerializationHelper.AllowLoadingUniqueId = false;\n const deltaJSON = {};\n for (const node in newJSON) {\n this._compareCollections(node, this._savedJSON[node], newJSON[node], deltaJSON);\n }\n Texture.ForceSerializeBuffers = currentForceSerializeBuffers;\n return deltaJSON;\n }\n _compareArray(key, original, current, deltaJSON) {\n if (original.length === 0 && current.length === 0) {\n return true;\n }\n // Numbers?\n if ((original.length && !isNaN(original[0])) || (current.length && !isNaN(current[0]))) {\n if (original.length !== current.length) {\n return false;\n }\n if (original.length === 0) {\n return true;\n }\n for (let index = 0; index < original.length; index++) {\n if (original[index] !== current[index]) {\n deltaJSON[key] = current;\n return false;\n }\n }\n return true;\n }\n // let's use uniqueId to find similar objects\n const originalUniqueIds = [];\n for (let index = 0; index < original.length; index++) {\n const originalObject = original[index];\n const originalUniqueId = originalObject.uniqueId;\n originalUniqueIds.push(originalUniqueId);\n // Look for that object in current state\n const currentObjects = current.filter((c) => c.uniqueId === originalUniqueId);\n if (currentObjects.length) {\n // We have a candidate\n const currentObject = currentObjects[0];\n const newObject = {};\n if (!this._compareObjects(originalObject, currentObject, newObject)) {\n if (!deltaJSON[key]) {\n deltaJSON[key] = [];\n }\n newObject.__state = {\n id: currentObject.id || currentObject.name,\n };\n deltaJSON[key].push(newObject);\n }\n }\n else {\n // We need to delete\n const newObject = {\n __state: {\n deleteId: originalObject.id || originalObject.name,\n },\n };\n if (!deltaJSON[key]) {\n deltaJSON[key] = [];\n }\n deltaJSON[key].push(newObject);\n }\n }\n // Checking for new objects\n for (let index = 0; index < current.length; index++) {\n const currentObject = current[index];\n const currentUniqueId = currentObject.uniqueId;\n // Object was added\n if (originalUniqueIds.indexOf(currentUniqueId) === -1) {\n if (!deltaJSON[key]) {\n deltaJSON[key] = [];\n }\n deltaJSON[key].push(currentObject);\n }\n }\n return true;\n }\n _compareObjects(originalObjet, currentObject, deltaJSON) {\n let aDifferenceWasFound = false;\n for (const prop in originalObjet) {\n if (!Object.prototype.hasOwnProperty.call(originalObjet, prop)) {\n continue;\n }\n const originalValue = originalObjet[prop];\n const currentValue = currentObject[prop];\n let diffFound = false;\n if (Array.isArray(originalValue)) {\n diffFound = JSON.stringify(originalValue) !== JSON.stringify(currentValue);\n }\n else if (!isNaN(originalValue) || Object.prototype.toString.call(originalValue) == \"[object String]\") {\n diffFound = originalValue !== currentValue;\n }\n else if (typeof originalValue === \"object\" && typeof currentValue === \"object\") {\n const newObject = {};\n if (!this._compareObjects(originalValue, currentValue, newObject)) {\n deltaJSON[prop] = newObject;\n aDifferenceWasFound = true;\n }\n }\n if (diffFound) {\n aDifferenceWasFound = true;\n deltaJSON[prop] = currentValue;\n }\n }\n return !aDifferenceWasFound;\n }\n _compareCollections(key, original, current, deltaJSON) {\n // Same ?\n if (original === current) {\n return;\n }\n if (original && current) {\n // Array?\n if (Array.isArray(original) && Array.isArray(current)) {\n if (this._compareArray(key, original, current, deltaJSON)) {\n return;\n }\n }\n else if (typeof original === \"object\" && typeof current === \"object\") {\n // Object\n const newObject = {};\n if (!this._compareObjects(original, current, newObject)) {\n deltaJSON[key] = newObject;\n }\n return;\n }\n }\n }\n static GetShadowGeneratorById(scene, id) {\n const allGenerators = scene.lights.map((l) => l.getShadowGenerators());\n for (const generators of allGenerators) {\n if (generators) {\n const iterator = generators.values();\n for (let key = iterator.next(); key.done !== true; key = iterator.next()) {\n const generator = key.value;\n if (generator && generator.id === id) {\n return generator;\n }\n }\n }\n }\n return null;\n }\n /**\n * Apply a given delta to a given scene\n * @param deltaJSON defines the JSON containing the delta\n * @param scene defines the scene to apply the delta to\n */\n static ApplyDelta(deltaJSON, scene) {\n if (typeof deltaJSON === \"string\") {\n deltaJSON = JSON.parse(deltaJSON);\n }\n // Scene\n const anyScene = scene;\n for (const prop in deltaJSON) {\n const source = deltaJSON[prop];\n const property = anyScene[prop];\n if (Array.isArray(property) || prop === \"shadowGenerators\") {\n // Restore array\n switch (prop) {\n case \"cameras\":\n this._ApplyDeltaForEntity(source, scene, scene.getCameraById.bind(scene), (data) => Camera.Parse(data, scene));\n break;\n case \"lights\":\n this._ApplyDeltaForEntity(source, scene, scene.getLightById.bind(scene), (data) => Light.Parse(data, scene));\n break;\n case \"shadowGenerators\":\n this._ApplyDeltaForEntity(source, scene, (id) => this.GetShadowGeneratorById(scene, id), (data) => ShadowGenerator.Parse(data, scene));\n break;\n case \"meshes\":\n this._ApplyDeltaForEntity(source, scene, scene.getMeshById.bind(scene), (data) => Mesh.Parse(data, scene, \"\"));\n break;\n case \"skeletons\":\n this._ApplyDeltaForEntity(source, scene, scene.getSkeletonById.bind(scene), (data) => Skeleton.Parse(data, scene));\n break;\n case \"materials\":\n this._ApplyDeltaForEntity(source, scene, scene.getMaterialById.bind(scene), (data) => Material.Parse(data, scene, \"\"));\n break;\n case \"multiMaterials\":\n this._ApplyDeltaForEntity(source, scene, scene.getMaterialById.bind(scene), (data) => MultiMaterial.Parse(data, scene, \"\"));\n break;\n case \"transformNodes\":\n this._ApplyDeltaForEntity(source, scene, scene.getTransformNodeById.bind(scene), (data) => TransformNode.Parse(data, scene, \"\"));\n break;\n case \"particleSystems\":\n this._ApplyDeltaForEntity(source, scene, scene.getParticleSystemById.bind(scene), (data) => ParticleSystem.Parse(data, scene, \"\"));\n break;\n case \"morphTargetManagers\":\n this._ApplyDeltaForEntity(source, scene, scene.getMorphTargetById.bind(scene), (data) => MorphTargetManager.Parse(data, scene));\n break;\n case \"postProcesses\":\n this._ApplyDeltaForEntity(source, scene, scene.getPostProcessByName.bind(scene), (data) => PostProcess.Parse(data, scene, \"\"));\n break;\n }\n }\n else if (!isNaN(property)) {\n anyScene[prop] = source;\n }\n else if (property.fromArray) {\n property.fromArray(source);\n }\n }\n }\n static _ApplyPropertiesToEntity(deltaJSON, entity) {\n for (const prop in deltaJSON) {\n const source = deltaJSON[prop];\n const property = entity[prop];\n if (property === undefined) {\n continue;\n }\n if (!isNaN(property) || Array.isArray(property)) {\n entity[prop] = source;\n }\n else if (property.fromArray) {\n property.fromArray(source);\n }\n else if (typeof property === \"object\" && property !== null) {\n this._ApplyPropertiesToEntity(source, property);\n }\n }\n }\n static _ApplyDeltaForEntity(sources, scene, finder, addNew) {\n for (const source of sources) {\n // Update\n if (source.__state && source.__state.id !== undefined) {\n const targetEntity = finder(source.__state.id);\n if (targetEntity) {\n // This first pass applies properties that aren't on the serialization list\n this._ApplyPropertiesToEntity(source, targetEntity);\n // The second pass applies the serializable properties\n SerializationHelper.ParseProperties(source, targetEntity, scene, null);\n }\n }\n else if (source.__state && source.__state.deleteId !== undefined) {\n const target = finder(source.__state.deleteId);\n target === null || target === void 0 ? void 0 : target.dispose();\n }\n else {\n // New\n addNew(source);\n }\n }\n }\n}\n//# sourceMappingURL=sceneRecorder.js.map","import { Matrix, Vector3 } from \"../Maths/math.vector.js\";\n// This implementation was based on the original MIT-licensed TRACE repository\n// from https://github.com/septagon/TRACE.\n/**\n * Generic implementation of Levenshtein distance.\n */\nvar Levenshtein;\n(function (Levenshtein) {\n /**\n * Alphabet from which to construct sequences to be compared using Levenshtein\n * distance.\n */\n class Alphabet {\n /**\n * Serialize the Alphabet to JSON string.\n * @returns JSON serialization\n */\n serialize() {\n const jsonObject = {};\n const characters = new Array(this._characterToIdx.size);\n this._characterToIdx.forEach((v, k) => {\n characters[v] = k;\n });\n jsonObject[\"characters\"] = characters;\n jsonObject[\"insertionCosts\"] = this._insertionCosts;\n jsonObject[\"deletionCosts\"] = this._deletionCosts;\n jsonObject[\"substitutionCosts\"] = this._substitutionCosts;\n return JSON.stringify(jsonObject);\n }\n /**\n * Parse an Alphabet from a JSON serialization.\n * @param json JSON string to deserialize\n * @returns deserialized Alphabet\n */\n static Deserialize(json) {\n const jsonObject = JSON.parse(json);\n const alphabet = new Alphabet(jsonObject[\"characters\"]);\n alphabet._insertionCosts = jsonObject[\"insertionCosts\"];\n alphabet._deletionCosts = jsonObject[\"deletionCosts\"];\n alphabet._substitutionCosts = jsonObject[\"substitutionCosts\"];\n return alphabet;\n }\n /**\n * Create a new Alphabet.\n * @param characters characters of the alphabet\n * @param charToInsertionCost function mapping characters to insertion costs\n * @param charToDeletionCost function mapping characters to deletion costs\n * @param charsToSubstitutionCost function mapping character pairs to substitution costs\n */\n constructor(characters, charToInsertionCost = null, charToDeletionCost = null, charsToSubstitutionCost = null) {\n charToInsertionCost = charToInsertionCost !== null && charToInsertionCost !== void 0 ? charToInsertionCost : (() => 1);\n charToDeletionCost = charToDeletionCost !== null && charToDeletionCost !== void 0 ? charToDeletionCost : (() => 1);\n charsToSubstitutionCost = charsToSubstitutionCost !== null && charsToSubstitutionCost !== void 0 ? charsToSubstitutionCost : ((a, b) => (a === b ? 0 : 1));\n this._characterToIdx = new Map();\n this._insertionCosts = new Array(characters.length);\n this._deletionCosts = new Array(characters.length);\n this._substitutionCosts = new Array(characters.length);\n let c;\n for (let outerIdx = 0; outerIdx < characters.length; ++outerIdx) {\n c = characters[outerIdx];\n this._characterToIdx.set(c, outerIdx);\n this._insertionCosts[outerIdx] = charToInsertionCost(c);\n this._deletionCosts[outerIdx] = charToDeletionCost(c);\n this._substitutionCosts[outerIdx] = new Array(characters.length);\n for (let innerIdx = outerIdx; innerIdx < characters.length; ++innerIdx) {\n this._substitutionCosts[outerIdx][innerIdx] = charsToSubstitutionCost(c, characters[innerIdx]);\n }\n }\n }\n /**\n * Get the index (internally-assigned number) for a character.\n * @param char character\n * @returns index\n */\n getCharacterIdx(char) {\n return this._characterToIdx.get(char);\n }\n /**\n * Get the insertion cost of a character from its index.\n * @param idx character index\n * @returns insertion cost\n */\n getInsertionCost(idx) {\n return this._insertionCosts[idx];\n }\n /**\n * Get the deletion cost of a character from its index.\n * @param idx character index\n * @returns deletion cost\n */\n getDeletionCost(idx) {\n return this._deletionCosts[idx];\n }\n /**\n * Gets the cost to substitute two characters. NOTE: this cost is\n * required to be bi-directional, meaning it cannot matter which of\n * the provided characters is being removed and which is being inserted.\n * @param idx1 the first character index\n * @param idx2 the second character index\n * @returns substitution cost\n */\n getSubstitutionCost(idx1, idx2) {\n const min = Math.min(idx1, idx2);\n const max = Math.max(idx1, idx2);\n return this._substitutionCosts[min][max];\n }\n }\n Levenshtein.Alphabet = Alphabet;\n /**\n * Character sequence intended to be compared against other Sequences created\n * with the same Alphabet in order to compute Levenshtein distance.\n */\n class Sequence {\n /**\n * Serialize to JSON string. JSON representation does NOT include the Alphabet\n * from which this Sequence was created; Alphabet must be independently\n * serialized.\n * @returns JSON string\n */\n serialize() {\n return JSON.stringify(this._characters);\n }\n /**\n * Deserialize from JSON string and Alphabet. This should be the same Alphabet\n * from which the Sequence was originally created, which must be serialized and\n * deserialized independently so that it can be passed in here.\n * @param json JSON string representation of Sequence\n * @param alphabet Alphabet from which Sequence was originally created\n * @returns Sequence\n */\n static Deserialize(json, alphabet) {\n const sequence = new Sequence([], alphabet);\n sequence._characters = JSON.parse(json);\n return sequence;\n }\n /**\n * Create a new Sequence.\n * @param characters characters in the new Sequence\n * @param alphabet Alphabet, which must include all used characters\n */\n constructor(characters, alphabet) {\n if (characters.length > Sequence._MAX_SEQUENCE_LENGTH) {\n throw new Error(\"Sequences longer than \" + Sequence._MAX_SEQUENCE_LENGTH + \" not supported.\");\n }\n this._alphabet = alphabet;\n this._characters = characters.map((c) => this._alphabet.getCharacterIdx(c));\n }\n /**\n * Get the distance between this Sequence and another.\n * @param other sequence to compare to\n * @returns Levenshtein distance\n */\n distance(other) {\n return Sequence._Distance(this, other);\n }\n /**\n * Compute the Levenshtein distance between two Sequences.\n * @param a first Sequence\n * @param b second Sequence\n * @returns Levenshtein distance\n */\n static _Distance(a, b) {\n const alphabet = a._alphabet;\n if (alphabet !== b._alphabet) {\n throw new Error(\"Cannot Levenshtein compare Sequences built from different alphabets.\");\n }\n const aChars = a._characters;\n const bChars = b._characters;\n const aLength = aChars.length;\n const bLength = bChars.length;\n const costMatrix = Sequence._CostMatrix;\n costMatrix[0][0] = 0;\n for (let idx = 0; idx < aLength; ++idx) {\n costMatrix[idx + 1][0] = costMatrix[idx][0] + alphabet.getInsertionCost(aChars[idx]);\n }\n for (let idx = 0; idx < bLength; ++idx) {\n costMatrix[0][idx + 1] = costMatrix[0][idx] + alphabet.getInsertionCost(bChars[idx]);\n }\n for (let aIdx = 0; aIdx < aLength; ++aIdx) {\n for (let bIdx = 0; bIdx < bLength; ++bIdx) {\n Sequence._InsertionCost = costMatrix[aIdx + 1][bIdx] + alphabet.getInsertionCost(bChars[bIdx]);\n Sequence._DeletionCost = costMatrix[aIdx][bIdx + 1] + alphabet.getDeletionCost(aChars[aIdx]);\n Sequence._SubstitutionCost = costMatrix[aIdx][bIdx] + alphabet.getSubstitutionCost(aChars[aIdx], bChars[bIdx]);\n costMatrix[aIdx + 1][bIdx + 1] = Math.min(Sequence._InsertionCost, Sequence._DeletionCost, Sequence._SubstitutionCost);\n }\n }\n return costMatrix[aLength][bLength];\n }\n }\n // Scratch values\n Sequence._MAX_SEQUENCE_LENGTH = 256;\n Sequence._CostMatrix = [...Array(Sequence._MAX_SEQUENCE_LENGTH + 1)].map(() => new Array(Sequence._MAX_SEQUENCE_LENGTH + 1));\n Levenshtein.Sequence = Sequence;\n})(Levenshtein || (Levenshtein = {}));\n/**\n * A 3D trajectory consisting of an order list of vectors describing a\n * path of motion through 3D space.\n */\nexport class Trajectory {\n /**\n * Serialize to JSON.\n * @returns serialized JSON string\n */\n serialize() {\n return JSON.stringify(this);\n }\n /**\n * Deserialize from JSON.\n * @param json serialized JSON string\n * @returns deserialized Trajectory\n */\n static Deserialize(json) {\n const jsonObject = JSON.parse(json);\n const trajectory = new Trajectory(jsonObject[\"_segmentLength\"]);\n trajectory._points = jsonObject[\"_points\"].map((pt) => {\n return new Vector3(pt[\"_x\"], pt[\"_y\"], pt[\"_z\"]);\n });\n return trajectory;\n }\n /**\n * Create a new empty Trajectory.\n * @param segmentLength radius of discretization for Trajectory points\n */\n constructor(segmentLength = 0.01) {\n this._points = [];\n this._segmentLength = segmentLength;\n }\n /**\n * Get the length of the Trajectory.\n * @returns length of the Trajectory\n */\n getLength() {\n return this._points.length * this._segmentLength;\n }\n /**\n * Append a new point to the Trajectory.\n * NOTE: This implementation has many allocations.\n * @param point point to append to the Trajectory\n */\n add(point) {\n let numPoints = this._points.length;\n if (numPoints === 0) {\n this._points.push(point.clone());\n }\n else {\n const getT = () => this._segmentLength / Vector3.Distance(this._points[numPoints - 1], point);\n for (let t = getT(); t <= 1.0; t = getT()) {\n const newPoint = this._points[numPoints - 1].scale(1.0 - t);\n point.scaleAndAddToRef(t, newPoint);\n this._points.push(newPoint);\n ++numPoints;\n }\n }\n }\n /**\n * Create a new Trajectory with a segment length chosen to make it\n * probable that the new Trajectory will have a specified number of\n * segments. This operation is imprecise.\n * @param targetResolution number of segments desired\n * @returns new Trajectory with approximately the requested number of segments\n */\n resampleAtTargetResolution(targetResolution) {\n const resampled = new Trajectory(this.getLength() / targetResolution);\n this._points.forEach((pt) => {\n resampled.add(pt);\n });\n return resampled;\n }\n /**\n * Convert Trajectory segments into tokenized representation. This\n * representation is an array of numbers where each nth number is the\n * index of the token which is most similar to the nth segment of the\n * Trajectory.\n * @param tokens list of vectors which serve as discrete tokens\n * @returns list of indices of most similar token per segment\n */\n tokenize(tokens) {\n const tokenization = [];\n const segmentDir = new Vector3();\n for (let idx = 2; idx < this._points.length; ++idx) {\n if (Trajectory._TransformSegmentDirToRef(this._points[idx - 2], this._points[idx - 1], this._points[idx], segmentDir)) {\n tokenization.push(Trajectory._TokenizeSegment(segmentDir, tokens));\n }\n }\n return tokenization;\n }\n /**\n * Transform the rotation (i.e., direction) of a segment to isolate\n * the relative transformation represented by the segment. This operation\n * may or may not succeed due to singularities in the equations that define\n * motion relativity in this context.\n * @param priorVec the origin of the prior segment\n * @param fromVec the origin of the current segment\n * @param toVec the destination of the current segment\n * @param result reference to output variable\n * @returns whether or not transformation was successful\n */\n static _TransformSegmentDirToRef(priorVec, fromVec, toVec, result) {\n const DOT_PRODUCT_SAMPLE_REJECTION_THRESHOLD = 0.98;\n fromVec.subtractToRef(priorVec, Trajectory._ForwardDir);\n Trajectory._ForwardDir.normalize();\n fromVec.scaleToRef(-1, Trajectory._InverseFromVec);\n Trajectory._InverseFromVec.normalize();\n if (Math.abs(Vector3.Dot(Trajectory._ForwardDir, Trajectory._InverseFromVec)) > DOT_PRODUCT_SAMPLE_REJECTION_THRESHOLD) {\n return false;\n }\n Vector3.CrossToRef(Trajectory._ForwardDir, Trajectory._InverseFromVec, Trajectory._UpDir);\n Trajectory._UpDir.normalize();\n Matrix.LookAtLHToRef(priorVec, fromVec, Trajectory._UpDir, Trajectory._LookMatrix);\n toVec.subtractToRef(fromVec, Trajectory._FromToVec);\n Trajectory._FromToVec.normalize();\n Vector3.TransformNormalToRef(Trajectory._FromToVec, Trajectory._LookMatrix, result);\n return true;\n }\n /**\n * Determine which token vector is most similar to the\n * segment vector.\n * @param segment segment vector\n * @param tokens token vector list\n * @returns index of the most similar token to the segment\n */\n static _TokenizeSegment(segment, tokens) {\n Trajectory._BestMatch = 0;\n Trajectory._Score = Vector3.Dot(segment, tokens[0]);\n Trajectory._BestScore = Trajectory._Score;\n for (let idx = 1; idx < tokens.length; ++idx) {\n Trajectory._Score = Vector3.Dot(segment, tokens[idx]);\n if (Trajectory._Score > Trajectory._BestScore) {\n Trajectory._BestMatch = idx;\n Trajectory._BestScore = Trajectory._Score;\n }\n }\n return Trajectory._BestMatch;\n }\n}\nTrajectory._ForwardDir = new Vector3();\nTrajectory._InverseFromVec = new Vector3();\nTrajectory._UpDir = new Vector3();\nTrajectory._FromToVec = new Vector3();\nTrajectory._LookMatrix = new Matrix();\n/**\n * Collection of vectors intended to be used as the basis of Trajectory\n * tokenization for Levenshtein distance comparison. Canonically, a\n * Vector3Alphabet will resemble a \"spikeball\" of vectors distributed\n * roughly evenly over the surface of the unit sphere.\n */\nclass Vector3Alphabet {\n /**\n * Helper method to create new \"spikeball\" Vector3Alphabets. Uses a naive\n * optimize-from-random strategy to space points around the unit sphere\n * surface as a simple alternative to really doing the math to tile the\n * sphere.\n * @param alphabetSize size of the desired alphabet\n * @param iterations number of iterations over which to optimize the \"spikeball\"\n * @param startingStepSize distance factor to move points in early optimization iterations\n * @param endingStepSize distance factor to move points in late optimization iterations\n * @param fixedValues alphabet \"characters\" that are required and cannot be moved by optimization\n * @returns a new randomly generated and optimized Vector3Alphabet of the specified size\n */\n static Generate(alphabetSize = 64, iterations = 256, startingStepSize = 0.1, endingStepSize = 0.001, fixedValues = []) {\n const EPSILON = 0.001;\n const EPSILON_SQUARED = EPSILON * EPSILON;\n const alphabet = new Vector3Alphabet(alphabetSize);\n for (let idx = 0; idx < alphabetSize; ++idx) {\n alphabet.chars[idx] = new Vector3(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5);\n alphabet.chars[idx].normalize();\n }\n for (let idx = 0; idx < fixedValues.length; ++idx) {\n alphabet.chars[idx].copyFrom(fixedValues[idx]);\n }\n let stepSize;\n let distSq;\n const force = new Vector3();\n const scratch = new Vector3();\n const lerp = (l, r, t) => (1.0 - t) * l + t * r;\n for (let iteration = 0; iteration < iterations; ++iteration) {\n stepSize = lerp(startingStepSize, endingStepSize, iteration / (iterations - 1));\n for (let idx = fixedValues.length; idx < alphabet.chars.length; ++idx) {\n force.copyFromFloats(0, 0, 0);\n alphabet.chars.forEach((pt) => {\n alphabet.chars[idx].subtractToRef(pt, scratch);\n distSq = scratch.lengthSquared();\n if (distSq > EPSILON_SQUARED) {\n scratch.scaleAndAddToRef(1 / (scratch.lengthSquared() * distSq), force);\n }\n });\n force.scaleInPlace(stepSize);\n alphabet.chars[idx].addInPlace(force);\n alphabet.chars[idx].normalize();\n }\n }\n return alphabet;\n }\n /**\n * Serialize to JSON.\n * @returns JSON serialization\n */\n serialize() {\n return JSON.stringify(this.chars);\n }\n /**\n * Deserialize from JSON.\n * @param json JSON serialization\n * @returns deserialized Vector3Alphabet\n */\n static Deserialize(json) {\n const jsonObject = JSON.parse(json);\n const alphabet = new Vector3Alphabet(jsonObject.length);\n for (let idx = 0; idx < jsonObject.length; ++idx) {\n alphabet.chars[idx] = new Vector3(jsonObject[idx][\"_x\"], jsonObject[idx][\"_y\"], jsonObject[idx][\"_z\"]);\n }\n return alphabet;\n }\n constructor(size) {\n this.chars = new Array(size);\n }\n}\n/**\n * Class which formalizes the manner in which a Vector3Alphabet is used to tokenize and\n * describe a Trajectory. This class houses the functionality which determines what\n * attributes of Trajectories are and are not considered important, such as scale.\n */\nclass TrajectoryDescriptor {\n /**\n * Serialize to JSON.\n * @returns JSON serialization\n */\n serialize() {\n return JSON.stringify(this._sequences.map((sequence) => sequence.serialize()));\n }\n /**\n * Deserialize from JSON string and Alphabet. This should be the same Alphabet\n * from which the descriptor was originally created, which must be serialized and\n * deserialized independently so that it can be passed in here.\n * @param json JSON serialization\n * @param alphabet Alphabet from which descriptor was originally created\n * @returns deserialized TrajectoryDescriptor\n */\n static Deserialize(json, alphabet) {\n const descriptor = new TrajectoryDescriptor();\n descriptor._sequences = JSON.parse(json).map((s) => Levenshtein.Sequence.Deserialize(s, alphabet));\n return descriptor;\n }\n /**\n * Create a new TrajectoryDescriptor to describe a provided Trajectory according\n * to the provided alphabets.\n * @param trajectory Trajectory to be described\n * @param vector3Alphabet Vector3Alphabet to be used to tokenize the Trajectory\n * @param levenshteinAlphabet Levenshtein.Alphabet to be used as basis for comparison with other descriptors\n * @returns TrajectoryDescriptor describing provided Trajectory\n */\n static CreateFromTrajectory(trajectory, vector3Alphabet, levenshteinAlphabet) {\n return TrajectoryDescriptor.CreateFromTokenizationPyramid(TrajectoryDescriptor._GetTokenizationPyramid(trajectory, vector3Alphabet), levenshteinAlphabet);\n }\n /**\n * Create a new TrajectoryDescriptor from a pre-existing pyramid of tokens.\n * NOTE: This function exists to support an outdated serialization mechanism and should\n * be deleted if it is no longer useful.\n * @param pyramid tokenization pyramid\n * @param levenshteinAlphabet Levenshtein.Alphabet to be uses as basis for comparison with other descriptors\n * @returns TrajectoryDescriptor describing the Trajectory from which the pyramid was built\n */\n static CreateFromTokenizationPyramid(pyramid, levenshteinAlphabet) {\n const descriptor = new TrajectoryDescriptor();\n descriptor._sequences = pyramid.map((tokens) => new Levenshtein.Sequence(tokens, levenshteinAlphabet));\n return descriptor;\n }\n constructor() {\n this._sequences = [];\n }\n /**\n * Create the tokenization pyramid for the provided Trajectory according to the given\n * Vector3Alphabet.\n * @param trajectory Trajectory to be tokenized\n * @param alphabet Vector3Alphabet containing tokens\n * @param targetResolution finest resolution of descriptor\n * @returns tokenization pyramid for Trajectory\n */\n static _GetTokenizationPyramid(trajectory, alphabet, targetResolution = TrajectoryDescriptor._FINEST_DESCRIPTOR_RESOLUTION) {\n const pyramid = [];\n for (let res = targetResolution; res > 4; res = Math.floor(res / 2)) {\n pyramid.push(trajectory.resampleAtTargetResolution(res).tokenize(alphabet.chars));\n }\n return pyramid;\n }\n /**\n * Calculate a distance metric between this TrajectoryDescriptor and another. This is\n * essentially a similarity score and does not directly represent Euclidean distance,\n * edit distance, or any other formal distance metric.\n * @param other TrajectoryDescriptor from which to determine distance\n * @returns distance, a nonnegative similarity score where larger values indicate dissimilarity\n */\n distance(other) {\n let totalDistance = 0;\n let weight;\n for (let idx = 0; idx < this._sequences.length; ++idx) {\n weight = Math.pow(2, idx);\n totalDistance += weight * this._sequences[idx].distance(other._sequences[idx]);\n }\n return totalDistance;\n }\n}\nTrajectoryDescriptor._FINEST_DESCRIPTOR_RESOLUTION = 32;\n/**\n * A set of TrajectoryDescriptors defined to be \"the same.\" This is essentially a helper\n * class to facilitate methods of Trajectory clustering.\n */\nclass TrajectoryClass {\n /**\n * Serialize to JSON.\n * @returns JSON serialization\n */\n serialize() {\n const jsonObject = {};\n jsonObject.descriptors = this._descriptors.map((desc) => desc.serialize());\n jsonObject.centroidIdx = this._centroidIdx;\n jsonObject.averageDistance = this._averageDistance;\n return JSON.stringify(jsonObject);\n }\n /**\n * Deserialize from JSON string and Alphabet. This should be the same Alphabet\n * from which the descriptors were originally created, which must be serialized and\n * deserialized independently so that it can be passed in here.\n * @param json JSON string representation\n * @param alphabet Alphabet from which TrajectoryDescriptors were originally created\n * @returns deserialized TrajectoryDescriptor\n */\n static Deserialize(json, alphabet) {\n const jsonObject = JSON.parse(json);\n const described = new TrajectoryClass();\n described._descriptors = jsonObject.descriptors.map((s) => TrajectoryDescriptor.Deserialize(s, alphabet));\n described._centroidIdx = jsonObject.centroidIdx;\n described._averageDistance = jsonObject.averageDistance;\n return described;\n }\n /**\n * Create a new DescribedTrajectory.\n * @param descriptors currently-known TrajectoryDescriptors, if any\n */\n constructor(descriptors = []) {\n this._descriptors = descriptors;\n this._centroidIdx = -1;\n this._averageDistance = 0;\n this._refreshDescription();\n }\n /**\n * Add a new TrajectoryDescriptor to the list of descriptors known to describe\n * this same DescribedTrajectory.\n * @param descriptor descriptor to be added\n */\n add(descriptor) {\n this._descriptors.push(descriptor);\n this._refreshDescription();\n }\n /**\n * Compute the cost, which is inversely related to the likelihood that the provided\n * TrajectoryDescriptor describes a Trajectory that is considered to be the same as\n * the class represented by this DescribedTrajectory.\n * @param descriptor the descriptor to be costed\n * @returns cost of the match, which is a nonnegative similarity metric where larger values indicate dissimilarity\n */\n getMatchCost(descriptor) {\n return descriptor.distance(this._descriptors[this._centroidIdx]) / this._averageDistance;\n }\n /**\n * Compute the minimum distance between the queried TrajectoryDescriptor and a\n * descriptor which is a member of this collection. This is an alternative way of\n * conceptualizing match cost from getMatchCost(), and it serves a different function.\n * @param descriptor the descriptor to find the minimum distance to\n * @returns minimum descriptor distance to a member descriptor of this DescribedTrajectory\n */\n getMatchMinimumDistance(descriptor) {\n return Math.min(...this._descriptors.map((desc) => desc.distance(descriptor)));\n }\n /**\n * Refreshes the internal representation of this DescribedTrajectory.\n */\n _refreshDescription() {\n this._centroidIdx = -1;\n let sum;\n const distances = this._descriptors.map((a) => {\n sum = 0;\n this._descriptors.forEach((b) => {\n sum += a.distance(b);\n });\n return sum;\n });\n for (let idx = 0; idx < distances.length; ++idx) {\n if (this._centroidIdx < 0 || distances[idx] < distances[this._centroidIdx]) {\n this._centroidIdx = idx;\n }\n }\n this._averageDistance = 0;\n this._descriptors.forEach((desc) => {\n this._averageDistance += desc.distance(this._descriptors[this._centroidIdx]);\n });\n if (this._descriptors.length > 0) {\n this._averageDistance = Math.max(this._averageDistance / this._descriptors.length, TrajectoryClass._MIN_AVERAGE_DISTANCE);\n }\n }\n}\nTrajectoryClass._MIN_AVERAGE_DISTANCE = 1;\n/**\n * Class representing a set of known, named trajectories to which Trajectories can be\n * added and using which Trajectories can be recognized.\n */\nexport class TrajectoryClassifier {\n /**\n * Serialize to JSON.\n * @returns JSON serialization\n */\n serialize() {\n const jsonObject = {};\n jsonObject.maximumAllowableMatchCost = this._maximumAllowableMatchCost;\n jsonObject.vector3Alphabet = this._vector3Alphabet.serialize();\n jsonObject.levenshteinAlphabet = this._levenshteinAlphabet.serialize();\n jsonObject.nameToDescribedTrajectory = [];\n this._nameToDescribedTrajectory.forEach((described, name) => {\n jsonObject.nameToDescribedTrajectory.push(name);\n jsonObject.nameToDescribedTrajectory.push(described.serialize());\n });\n return JSON.stringify(jsonObject);\n }\n /**\n * Deserialize from JSON.\n * @param json JSON serialization\n * @returns deserialized TrajectorySet\n */\n static Deserialize(json) {\n const jsonObject = JSON.parse(json);\n const classifier = new TrajectoryClassifier();\n classifier._maximumAllowableMatchCost = jsonObject.maximumAllowableMatchCost;\n classifier._vector3Alphabet = Vector3Alphabet.Deserialize(jsonObject.vector3Alphabet);\n classifier._levenshteinAlphabet = Levenshtein.Alphabet.Deserialize(jsonObject.levenshteinAlphabet);\n for (let idx = 0; idx < jsonObject.nameToDescribedTrajectory.length; idx += 2) {\n classifier._nameToDescribedTrajectory.set(jsonObject.nameToDescribedTrajectory[idx], TrajectoryClass.Deserialize(jsonObject.nameToDescribedTrajectory[idx + 1], classifier._levenshteinAlphabet));\n }\n return classifier;\n }\n /**\n * Initialize a new empty TrajectorySet with auto-generated Alphabets.\n * VERY naive, need to be generating these things from known\n * sets. Better version later, probably eliminating this one.\n * @returns auto-generated TrajectorySet\n */\n static Generate() {\n const vecs = Vector3Alphabet.Generate(64, 256, 0.1, 0.001, [Vector3.Forward()]);\n const charIdxs = new Array(vecs.chars.length);\n for (let idx = 0; idx < charIdxs.length; ++idx) {\n charIdxs[idx] = idx;\n }\n const alphabet = new Levenshtein.Alphabet(charIdxs, (idx) => (idx === 0 ? 0 : 1), (idx) => (idx === 0 ? 0 : 1), (a, b) => Math.min(1 - Vector3.Dot(vecs.chars[a], vecs.chars[b]), 1));\n const trajectorySet = new TrajectoryClassifier();\n trajectorySet._vector3Alphabet = vecs;\n trajectorySet._levenshteinAlphabet = alphabet;\n return trajectorySet;\n }\n constructor() {\n this._maximumAllowableMatchCost = 4;\n this._nameToDescribedTrajectory = new Map();\n }\n /**\n * Add a new Trajectory to the set with a given name.\n * @param trajectory new Trajectory to be added\n * @param classification name to which to add the Trajectory\n */\n addTrajectoryToClassification(trajectory, classification) {\n if (!this._nameToDescribedTrajectory.has(classification)) {\n this._nameToDescribedTrajectory.set(classification, new TrajectoryClass());\n }\n this._nameToDescribedTrajectory.get(classification).add(TrajectoryDescriptor.CreateFromTrajectory(trajectory, this._vector3Alphabet, this._levenshteinAlphabet));\n }\n /**\n * Remove a known named trajectory and all Trajectories associated with it.\n * @param classification name to remove\n * @returns whether anything was removed\n */\n deleteClassification(classification) {\n return this._nameToDescribedTrajectory.delete(classification);\n }\n /**\n * Attempt to recognize a Trajectory from among all the classifications\n * already known to the classifier.\n * @param trajectory Trajectory to be recognized\n * @returns classification of Trajectory if recognized, null otherwise\n */\n classifyTrajectory(trajectory) {\n const descriptor = TrajectoryDescriptor.CreateFromTrajectory(trajectory, this._vector3Alphabet, this._levenshteinAlphabet);\n const allowableMatches = [];\n this._nameToDescribedTrajectory.forEach((trajectoryClass, classification) => {\n if (trajectoryClass.getMatchCost(descriptor) < this._maximumAllowableMatchCost) {\n allowableMatches.push(classification);\n }\n });\n if (allowableMatches.length === 0) {\n return null;\n }\n let bestIdx = 0;\n let bestMatch = this._nameToDescribedTrajectory.get(allowableMatches[bestIdx]).getMatchMinimumDistance(descriptor);\n let match;\n for (let idx = 0; idx < allowableMatches.length; ++idx) {\n match = this._nameToDescribedTrajectory.get(allowableMatches[idx]).getMatchMinimumDistance(descriptor);\n if (match < bestMatch) {\n bestMatch = match;\n bestIdx = idx;\n }\n }\n return allowableMatches[bestIdx];\n }\n}\n//# sourceMappingURL=trajectoryClassifier.js.map","import { Logger } from \"./logger.js\";\nimport { SceneSerializer } from \"./sceneSerializer.js\";\n/**\n * Class used to connect with the reflector zone of the sandbox via the reflector bridge\n * @since 5.0.0\n */\nexport class Reflector {\n /**\n * Constructs a reflector object.\n * @param scene The scene to use\n * @param hostname The hostname of the reflector bridge\n * @param port The port of the reflector bridge\n */\n constructor(scene, hostname, port) {\n this._scene = scene;\n Logger.Log(`[Reflector] Connecting to ws://${hostname}:${port}`);\n this._webSocket = new WebSocket(`ws://${hostname}:${port}`);\n this._webSocket.onmessage = (event) => {\n const message = event.data;\n if (message.startsWith(Reflector._SERVER_PREFIX)) {\n const serverMessage = message.substr(Reflector._SERVER_PREFIX.length);\n Logger.Log(`[Reflector] Received server message: ${serverMessage.substr(0, 64)}`);\n this._handleServerMessage(serverMessage);\n return;\n }\n else {\n Logger.Log(`[Reflector] Received client message: ${message.substr(0, 64)}`);\n this._handleClientMessage();\n }\n };\n this._webSocket.onclose = (event) => {\n Logger.Log(`[Reflector] Disconnected ${event.code} ${event.reason}`);\n };\n }\n /**\n * Closes the reflector connection\n */\n close() {\n this._webSocket.close();\n }\n _handleServerMessage(message) {\n switch (message) {\n case \"connected\": {\n SceneSerializer.SerializeAsync(this._scene).then((serialized) => {\n this._webSocket.send(`load|${JSON.stringify(serialized)}`);\n });\n break;\n }\n }\n }\n _handleClientMessage() {\n // do nothing\n }\n}\nReflector._SERVER_PREFIX = \"$$\";\n//# sourceMappingURL=reflector.js.map","import { Observable } from \"./observable.js\";\n/**\n * A wrapper for the experimental pressure api which allows a callback to be called whenever certain thresholds are met.\n */\nexport class PressureObserverWrapper {\n /**\n * A pressure observer will call this callback, whenever these thresholds are met.\n * @param options An object containing the thresholds used to decide what value to to return for each update property (average of start and end of a threshold boundary).\n */\n constructor(options) {\n this._observer = null;\n this._currentState = [];\n /**\n * An event triggered when the cpu usage/speed meets certain thresholds.\n * Note: pressure is an experimental API.\n */\n this.onPressureChanged = new Observable();\n if (PressureObserverWrapper.IsAvailable) {\n this._observer = new PressureObserver((update) => {\n this._currentState = update;\n this.onPressureChanged.notifyObservers(update);\n }, options);\n }\n }\n /**\n * Returns true if PressureObserver is available for use, false otherwise.\n */\n static get IsAvailable() {\n return typeof PressureObserver !== \"undefined\" && PressureObserver.supportedSources.includes(\"cpu\");\n }\n /**\n * Method that must be called to begin observing changes, and triggering callbacks.\n * @param source defines the source to observe\n */\n observe(source) {\n var _a;\n try {\n (_a = this._observer) === null || _a === void 0 ? void 0 : _a.observe(source);\n this.onPressureChanged.notifyObservers(this._currentState);\n }\n catch (_b) {\n // Ignore error\n }\n }\n /**\n * Method that must be called to stop observing changes and triggering callbacks (cleanup function).\n * @param source defines the source to unobserve\n */\n unobserve(source) {\n var _a;\n try {\n (_a = this._observer) === null || _a === void 0 ? void 0 : _a.unobserve(source);\n }\n catch (_b) {\n // Ignore error\n }\n }\n /**\n * Release the associated resources.\n */\n dispose() {\n var _a;\n (_a = this._observer) === null || _a === void 0 ? void 0 : _a.disconnect();\n this._observer = null;\n this.onPressureChanged.clear();\n }\n}\n//# sourceMappingURL=pressureObserverWrapper.js.map","const growthFactor = 1.5;\n/**\n * A class acting as a dynamic float32array used in the performance viewer\n */\nexport class DynamicFloat32Array {\n /**\n * Creates a new DynamicFloat32Array with the desired item capacity.\n * @param itemCapacity The initial item capacity you would like to set for the array.\n */\n constructor(itemCapacity) {\n this._view = new Float32Array(itemCapacity);\n this._itemLength = 0;\n }\n /**\n * The number of items currently in the array.\n */\n get itemLength() {\n return this._itemLength;\n }\n /**\n * Gets value at index, NaN if no such index exists.\n * @param index the index to get the value at.\n * @returns the value at the index provided.\n */\n at(index) {\n if (index < 0 || index >= this._itemLength) {\n return NaN;\n }\n return this._view[index];\n }\n /**\n * Gets a view of the original array from start to end (exclusive of end).\n * @param start starting index.\n * @param end ending index.\n * @returns a subarray of the original array.\n */\n subarray(start, end) {\n if (start >= end || start < 0) {\n return new Float32Array(0);\n }\n if (end > this._itemLength) {\n end = this._itemLength;\n }\n return this._view.subarray(start, end);\n }\n /**\n * Pushes items to the end of the array.\n * @param item The item to push into the array.\n */\n push(item) {\n this._view[this._itemLength] = item;\n this._itemLength++;\n if (this._itemLength >= this._view.length) {\n this._growArray();\n }\n }\n /**\n * Grows the array by the growth factor when necessary.\n */\n _growArray() {\n const newCapacity = Math.floor(this._view.length * growthFactor);\n const view = new Float32Array(newCapacity);\n view.set(this._view);\n this._view = view;\n }\n}\n//# sourceMappingURL=dynamicFloat32Array.js.map","import { EventState, Observable } from \"../observable.js\";\nimport { PrecisionDate } from \"../precisionDate.js\";\nimport { Tools } from \"../tools.js\";\nimport { DynamicFloat32Array } from \"./dynamicFloat32Array.js\";\n// the initial size of our array, should be a multiple of two!\nconst InitialArraySize = 1800;\n// three octets in a hexcode. #[AA][BB][CC], i.e. 24 bits of data.\nconst NumberOfBitsInHexcode = 24;\n// Allows single numeral hex numbers to be appended by a 0.\nconst HexPadding = \"0\";\n// header for the timestamp column\nconst TimestampColHeader = \"timestamp\";\n// header for the numPoints column\nconst NumPointsColHeader = \"numPoints\";\n// regex to capture all carriage returns in the string.\nconst CarriageReturnRegex = /\\r/g;\n// string to use as separator when exporting extra information along with the dataset id\nconst ExportedDataSeparator = \"@\";\n/**\n * The collector class handles the collection and storage of data into the appropriate array.\n * The collector also handles notifying any observers of any updates.\n */\nexport class PerformanceViewerCollector {\n /**\n * The offset for when actual data values start appearing inside a slice.\n */\n static get SliceDataOffset() {\n return 2;\n }\n /**\n * The offset for the value of the number of points inside a slice.\n */\n static get NumberOfPointsOffset() {\n return 1;\n }\n /**\n * Handles the creation of a performance viewer collector.\n * @param _scene the scene to collect on.\n * @param _enabledStrategyCallbacks the list of data to collect with callbacks for initialization purposes.\n */\n constructor(_scene, _enabledStrategyCallbacks) {\n this._scene = _scene;\n /**\n * Collects data for every dataset by using the appropriate strategy. This is called every frame.\n * This method will then notify all observers with the latest slice.\n */\n this._collectDataAtFrame = () => {\n const timestamp = PrecisionDate.Now - this._startingTimestamp;\n const numPoints = this.datasets.ids.length;\n // add the starting index for the slice\n const numberOfIndices = this.datasets.startingIndices.itemLength;\n let startingIndex = 0;\n if (numberOfIndices > 0) {\n const previousStartingIndex = this.datasets.startingIndices.at(numberOfIndices - 1);\n startingIndex =\n previousStartingIndex + this.datasets.data.at(previousStartingIndex + PerformanceViewerCollector.NumberOfPointsOffset) + PerformanceViewerCollector.SliceDataOffset;\n }\n this.datasets.startingIndices.push(startingIndex);\n // add the first 2 items in our slice.\n this.datasets.data.push(timestamp);\n this.datasets.data.push(numPoints);\n // add the values inside the slice.\n this.datasets.ids.forEach((id) => {\n const strategy = this._strategies.get(id);\n if (!strategy) {\n return;\n }\n this.datasets.data.push(strategy.getData());\n });\n if (this.datasetObservable.hasObservers()) {\n const slice = [timestamp, numPoints];\n for (let i = 0; i < numPoints; i++) {\n slice.push(this.datasets.data.at(startingIndex + PerformanceViewerCollector.SliceDataOffset + i));\n }\n this.datasetObservable.notifyObservers(slice);\n }\n };\n this.datasets = {\n ids: [],\n data: new DynamicFloat32Array(InitialArraySize),\n startingIndices: new DynamicFloat32Array(InitialArraySize),\n };\n this._strategies = new Map();\n this._datasetMeta = new Map();\n this._eventRestoreSet = new Set();\n this._customEventObservable = new Observable();\n this.datasetObservable = new Observable();\n this.metadataObservable = new Observable((observer) => observer.callback(this._datasetMeta, new EventState(0)));\n if (_enabledStrategyCallbacks) {\n this.addCollectionStrategies(..._enabledStrategyCallbacks);\n }\n }\n /**\n * Registers a custom string event which will be callable via sendEvent. This method returns an event object which will contain the id of the event.\n * The user can set a value optionally, which will be used in the sendEvent method. If the value is set, we will record this value at the end of each frame,\n * if not we will increment our counter and record the value of the counter at the end of each frame. The value recorded is 0 if no sendEvent method is called, within a frame.\n * @param name The name of the event to register\n * @param forceUpdate if the code should force add an event, and replace the last one.\n * @param category the category for that event\n * @returns The event registered, used in sendEvent\n */\n registerEvent(name, forceUpdate, category) {\n var _a;\n if (this._strategies.has(name) && !forceUpdate) {\n return;\n }\n if (this._strategies.has(name) && forceUpdate) {\n (_a = this._strategies.get(name)) === null || _a === void 0 ? void 0 : _a.dispose();\n this._strategies.delete(name);\n }\n const strategy = (scene) => {\n let counter = 0;\n let value = 0;\n const afterRenderObserver = scene.onAfterRenderObservable.add(() => {\n value = counter;\n counter = 0;\n });\n const stringObserver = this._customEventObservable.add((eventVal) => {\n if (name !== eventVal.name) {\n return;\n }\n if (eventVal.value !== undefined) {\n counter = eventVal.value;\n }\n else {\n counter++;\n }\n });\n return {\n id: name,\n getData: () => value,\n dispose: () => {\n scene.onAfterRenderObservable.remove(afterRenderObserver);\n this._customEventObservable.remove(stringObserver);\n },\n };\n };\n const event = {\n name,\n };\n this._eventRestoreSet.add(name);\n this.addCollectionStrategies({ strategyCallback: strategy, category });\n return event;\n }\n /**\n * Lets the perf collector handle an event, occurences or event value depending on if the event.value params is set.\n * @param event the event to handle an occurence for\n */\n sendEvent(event) {\n this._customEventObservable.notifyObservers(event);\n }\n /**\n * This event restores all custom string events if necessary.\n */\n _restoreStringEvents() {\n if (this._eventRestoreSet.size !== this._customEventObservable.observers.length) {\n this._eventRestoreSet.forEach((event) => {\n this.registerEvent(event, true);\n });\n }\n }\n /**\n * This method adds additional collection strategies for data collection purposes.\n * @param strategyCallbacks the list of data to collect with callbacks.\n */\n addCollectionStrategies(...strategyCallbacks) {\n // eslint-disable-next-line prefer-const\n for (let { strategyCallback, category, hidden } of strategyCallbacks) {\n const strategy = strategyCallback(this._scene);\n if (this._strategies.has(strategy.id)) {\n strategy.dispose();\n continue;\n }\n this.datasets.ids.push(strategy.id);\n if (category) {\n category = category.replace(new RegExp(ExportedDataSeparator, \"g\"), \"\");\n }\n this._datasetMeta.set(strategy.id, {\n color: this._getHexColorFromId(strategy.id),\n category,\n hidden,\n });\n this._strategies.set(strategy.id, strategy);\n }\n this.metadataObservable.notifyObservers(this._datasetMeta);\n }\n /**\n * Gets a 6 character hexcode representing the colour from a passed in string.\n * @param id the string to get a hex code for.\n * @returns a hexcode hashed from the id.\n */\n _getHexColorFromId(id) {\n // this first bit is just a known way of hashing a string.\n let hash = 0;\n for (let i = 0; i < id.length; i++) {\n // (hash << 5) - hash is the same as hash * 31\n hash = id.charCodeAt(i) + ((hash << 5) - hash);\n }\n // then we build the string octet by octet.\n let hex = \"#\";\n for (let i = 0; i < NumberOfBitsInHexcode; i += 8) {\n const octet = (hash >> i) & 0xff;\n hex += (HexPadding + octet.toString(16)).substr(-2);\n }\n return hex;\n }\n /**\n * Collects and then sends the latest slice to any observers by using the appropriate strategy when the user wants.\n * The slice will be of the form [timestamp, numberOfPoints, value1, value2...]\n * This method does not add onto the collected data accessible via the datasets variable.\n */\n getCurrentSlice() {\n const timestamp = PrecisionDate.Now - this._startingTimestamp;\n const numPoints = this.datasets.ids.length;\n const slice = [timestamp, numPoints];\n // add the values inside the slice.\n this.datasets.ids.forEach((id) => {\n const strategy = this._strategies.get(id);\n if (!strategy) {\n return;\n }\n if (this.datasetObservable.hasObservers()) {\n slice.push(strategy.getData());\n }\n });\n if (this.datasetObservable.hasObservers()) {\n this.datasetObservable.notifyObservers(slice);\n }\n }\n /**\n * Updates a property for a dataset's metadata with the value provided.\n * @param id the id of the dataset which needs its metadata updated.\n * @param prop the property to update.\n * @param value the value to update the property with.\n */\n updateMetadata(id, prop, value) {\n const meta = this._datasetMeta.get(id);\n if (!meta) {\n return;\n }\n meta[prop] = value;\n this.metadataObservable.notifyObservers(this._datasetMeta);\n }\n /**\n * Completely clear, data, ids, and strategies saved to this performance collector.\n * @param preserveStringEventsRestore if it should preserve the string events, by default will clear string events registered when called.\n */\n clear(preserveStringEventsRestore) {\n this.datasets.data = new DynamicFloat32Array(InitialArraySize);\n this.datasets.ids.length = 0;\n this.datasets.startingIndices = new DynamicFloat32Array(InitialArraySize);\n this._datasetMeta.clear();\n this._strategies.forEach((strategy) => strategy.dispose());\n this._strategies.clear();\n if (!preserveStringEventsRestore) {\n this._eventRestoreSet.clear();\n }\n this._hasLoadedData = false;\n }\n /**\n * Accessor which lets the caller know if the performance collector has data loaded from a file or not!\n * Call clear() to reset this value.\n * @returns true if the data is loaded from a file, false otherwise.\n */\n get hasLoadedData() {\n return this._hasLoadedData;\n }\n /**\n * Given a string containing file data, this function parses the file data into the datasets object.\n * It returns a boolean to indicate if this object was successfully loaded with the data.\n * @param data string content representing the file data.\n * @param keepDatasetMeta if it should use reuse the existing dataset metadata\n * @returns true if the data was successfully loaded, false otherwise.\n */\n loadFromFileData(data, keepDatasetMeta) {\n const lines = data\n .replace(CarriageReturnRegex, \"\")\n .split(\"\\n\")\n .map((line) => line.split(\",\").filter((s) => s.length > 0))\n .filter((line) => line.length > 0);\n const timestampIndex = 0;\n const numPointsIndex = PerformanceViewerCollector.NumberOfPointsOffset;\n if (lines.length < 2) {\n return false;\n }\n const parsedDatasets = {\n ids: [],\n data: new DynamicFloat32Array(InitialArraySize),\n startingIndices: new DynamicFloat32Array(InitialArraySize),\n };\n // parse first line separately to populate ids!\n const [firstLine, ...dataLines] = lines;\n // make sure we have the correct beginning headers\n if (firstLine.length < 2 || firstLine[timestampIndex] !== TimestampColHeader || firstLine[numPointsIndex] !== NumPointsColHeader) {\n return false;\n }\n const idCategoryMap = new Map();\n // populate the ids.\n for (let i = PerformanceViewerCollector.SliceDataOffset; i < firstLine.length; i++) {\n const [id, category] = firstLine[i].split(ExportedDataSeparator);\n parsedDatasets.ids.push(id);\n idCategoryMap.set(id, category);\n }\n let startingIndex = 0;\n for (const line of dataLines) {\n if (line.length < 2) {\n return false;\n }\n const timestamp = parseFloat(line[timestampIndex]);\n const numPoints = parseInt(line[numPointsIndex]);\n if (isNaN(numPoints) || isNaN(timestamp)) {\n return false;\n }\n parsedDatasets.data.push(timestamp);\n parsedDatasets.data.push(numPoints);\n if (numPoints + PerformanceViewerCollector.SliceDataOffset !== line.length) {\n return false;\n }\n for (let i = PerformanceViewerCollector.SliceDataOffset; i < line.length; i++) {\n const val = parseFloat(line[i]);\n if (isNaN(val)) {\n return false;\n }\n parsedDatasets.data.push(val);\n }\n parsedDatasets.startingIndices.push(startingIndex);\n startingIndex += line.length;\n }\n this.datasets.ids = parsedDatasets.ids;\n this.datasets.data = parsedDatasets.data;\n this.datasets.startingIndices = parsedDatasets.startingIndices;\n if (!keepDatasetMeta) {\n this._datasetMeta.clear();\n }\n this._strategies.forEach((strategy) => strategy.dispose());\n this._strategies.clear();\n // populate metadata.\n if (!keepDatasetMeta) {\n for (const id of this.datasets.ids) {\n const category = idCategoryMap.get(id);\n this._datasetMeta.set(id, { category, color: this._getHexColorFromId(id) });\n }\n }\n this.metadataObservable.notifyObservers(this._datasetMeta);\n this._hasLoadedData = true;\n return true;\n }\n /**\n * Exports the datasets inside of the collector to a csv.\n */\n exportDataToCsv() {\n let csvContent = \"\";\n // create the header line.\n csvContent += `${TimestampColHeader},${NumPointsColHeader}`;\n for (let i = 0; i < this.datasets.ids.length; i++) {\n csvContent += `,${this.datasets.ids[i]}`;\n if (this._datasetMeta) {\n const meta = this._datasetMeta.get(this.datasets.ids[i]);\n if (meta === null || meta === void 0 ? void 0 : meta.category) {\n csvContent += `${ExportedDataSeparator}${meta.category}`;\n }\n }\n }\n csvContent += \"\\n\";\n // create the data lines\n for (let i = 0; i < this.datasets.startingIndices.itemLength; i++) {\n const startingIndex = this.datasets.startingIndices.at(i);\n const timestamp = this.datasets.data.at(startingIndex);\n const numPoints = this.datasets.data.at(startingIndex + PerformanceViewerCollector.NumberOfPointsOffset);\n csvContent += `${timestamp},${numPoints}`;\n for (let offset = 0; offset < numPoints; offset++) {\n csvContent += `,${this.datasets.data.at(startingIndex + PerformanceViewerCollector.SliceDataOffset + offset)}`;\n }\n // add extra commas.\n for (let diff = 0; diff < this.datasets.ids.length - numPoints; diff++) {\n csvContent += \",\";\n }\n csvContent += \"\\n\";\n }\n const fileName = `${new Date().toISOString()}-perfdata.csv`;\n Tools.Download(new Blob([csvContent], { type: \"text/csv\" }), fileName);\n }\n /**\n * Starts the realtime collection of data.\n * @param shouldPreserve optional boolean param, if set will preserve the dataset between calls of start.\n */\n start(shouldPreserve) {\n if (!shouldPreserve) {\n this.datasets.data = new DynamicFloat32Array(InitialArraySize);\n this.datasets.startingIndices = new DynamicFloat32Array(InitialArraySize);\n this._startingTimestamp = PrecisionDate.Now;\n }\n else if (this._startingTimestamp === undefined) {\n this._startingTimestamp = PrecisionDate.Now;\n }\n this._scene.onAfterRenderObservable.add(this._collectDataAtFrame);\n this._restoreStringEvents();\n this._isStarted = true;\n }\n /**\n * Stops the collection of data.\n */\n stop() {\n this._scene.onAfterRenderObservable.removeCallback(this._collectDataAtFrame);\n this._isStarted = false;\n }\n /**\n * Returns if the perf collector has been started or not.\n */\n get isStarted() {\n return this._isStarted;\n }\n /**\n * Disposes of the object\n */\n dispose() {\n this._scene.onAfterRenderObservable.removeCallback(this._collectDataAtFrame);\n this._datasetMeta.clear();\n this._strategies.forEach((strategy) => {\n strategy.dispose();\n });\n this.datasetObservable.clear();\n this.metadataObservable.clear();\n this._isStarted = false;\n this.datasets = null;\n }\n}\n//# sourceMappingURL=performanceViewerCollector.js.map","import { EngineInstrumentation } from \"../../Instrumentation/engineInstrumentation.js\";\nimport { PrecisionDate } from \"../precisionDate.js\";\nimport { SceneInstrumentation } from \"../../Instrumentation/sceneInstrumentation.js\";\nimport { PressureObserverWrapper } from \"../pressureObserverWrapper.js\";\n// Dispose which does nothing.\nconst defaultDisposeImpl = () => { };\n/**\n * Defines the predefined strategies used in the performance viewer.\n */\nexport class PerfCollectionStrategy {\n /**\n * Gets the initializer for the strategy used for collection of fps metrics\n * @returns the initializer for the fps strategy\n */\n static FpsStrategy() {\n return (scene) => {\n const engine = scene.getEngine();\n return {\n id: \"FPS\",\n getData: () => engine.getFps(),\n dispose: defaultDisposeImpl,\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of thermal utilization metrics.\n * Needs the experimental pressure API.\n * @returns the initializer for the thermal utilization strategy\n */\n static ThermalStrategy() {\n return this._PressureStrategy(\"Thermal utilization\", \"thermal\");\n }\n /**\n * Gets the initializer for the strategy used for collection of power supply utilization metrics.\n * Needs the experimental pressure API.\n * @returns the initializer for the power supply utilization strategy\n */\n static PowerSupplyStrategy() {\n return this._PressureStrategy(\"Power supply utilization\", \"power-supply\");\n }\n /**\n * Gets the initializer for the strategy used for collection of pressure metrics.\n * Needs the experimental pressure API.\n * @returns the initializer for the pressure strategy\n */\n static PressureStrategy() {\n return this._PressureStrategy(\"Pressure\");\n }\n static _PressureStrategy(name, factor = null) {\n return () => {\n let value = 0;\n const wrapper = new PressureObserverWrapper();\n wrapper.observe(\"cpu\");\n wrapper.onPressureChanged.add((update) => {\n for (const record of update) {\n if ((factor && record.factors.includes(factor)) || (!factor && record.factors.length === 0)) {\n // Let s consider each step being 25% of the total pressure.\n switch (record.state) {\n case \"nominal\":\n value = 0;\n break;\n case \"fair\":\n value = 0.25;\n break;\n case \"serious\":\n value = 0.5;\n break;\n case \"critical\":\n value = 1;\n break;\n }\n }\n }\n });\n return {\n id: name,\n getData: () => value,\n dispose: () => wrapper.dispose(),\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of total meshes metrics.\n * @returns the initializer for the total meshes strategy\n */\n static TotalMeshesStrategy() {\n return (scene) => {\n return {\n id: \"Total meshes\",\n getData: () => scene.meshes.length,\n dispose: defaultDisposeImpl,\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of active meshes metrics.\n * @returns the initializer for the active meshes strategy\n */\n static ActiveMeshesStrategy() {\n return (scene) => {\n return {\n id: \"Active meshes\",\n getData: () => scene.getActiveMeshes().length,\n dispose: defaultDisposeImpl,\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of active indices metrics.\n * @returns the initializer for the active indices strategy\n */\n static ActiveIndicesStrategy() {\n return (scene) => {\n return {\n id: \"Active indices\",\n getData: () => scene.getActiveIndices(),\n dispose: defaultDisposeImpl,\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of active faces metrics.\n * @returns the initializer for the active faces strategy\n */\n static ActiveFacesStrategy() {\n return (scene) => {\n return {\n id: \"Active faces\",\n getData: () => scene.getActiveIndices() / 3,\n dispose: defaultDisposeImpl,\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of active bones metrics.\n * @returns the initializer for the active bones strategy\n */\n static ActiveBonesStrategy() {\n return (scene) => {\n return {\n id: \"Active bones\",\n getData: () => scene.getActiveBones(),\n dispose: defaultDisposeImpl,\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of active particles metrics.\n * @returns the initializer for the active particles strategy\n */\n static ActiveParticlesStrategy() {\n return (scene) => {\n return {\n id: \"Active particles\",\n getData: () => scene.getActiveParticles(),\n dispose: defaultDisposeImpl,\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of draw calls metrics.\n * @returns the initializer for the draw calls strategy\n */\n static DrawCallsStrategy() {\n return (scene) => {\n let drawCalls = 0;\n const onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(() => {\n scene.getEngine()._drawCalls.fetchNewFrame();\n });\n const onAfterRenderObserver = scene.onAfterRenderObservable.add(() => {\n drawCalls = scene.getEngine()._drawCalls.current;\n });\n return {\n id: \"Draw calls\",\n getData: () => drawCalls,\n dispose: () => {\n scene.onBeforeAnimationsObservable.remove(onBeforeAnimationsObserver);\n scene.onAfterRenderObservable.remove(onAfterRenderObserver);\n },\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of total lights metrics.\n * @returns the initializer for the total lights strategy\n */\n static TotalLightsStrategy() {\n return (scene) => {\n return {\n id: \"Total lights\",\n getData: () => scene.lights.length,\n dispose: defaultDisposeImpl,\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of total vertices metrics.\n * @returns the initializer for the total vertices strategy\n */\n static TotalVerticesStrategy() {\n return (scene) => {\n return {\n id: \"Total vertices\",\n getData: () => scene.getTotalVertices(),\n dispose: defaultDisposeImpl,\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of total materials metrics.\n * @returns the initializer for the total materials strategy\n */\n static TotalMaterialsStrategy() {\n return (scene) => {\n return {\n id: \"Total materials\",\n getData: () => scene.materials.length,\n dispose: defaultDisposeImpl,\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of total textures metrics.\n * @returns the initializer for the total textures strategy\n */\n static TotalTexturesStrategy() {\n return (scene) => {\n return {\n id: \"Total textures\",\n getData: () => scene.textures.length,\n dispose: defaultDisposeImpl,\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of absolute fps metrics.\n * @returns the initializer for the absolute fps strategy\n */\n static AbsoluteFpsStrategy() {\n return (scene) => {\n const sceneInstrumentation = new SceneInstrumentation(scene);\n sceneInstrumentation.captureFrameTime = true;\n return {\n id: \"Absolute FPS\",\n getData: () => {\n return 1000.0 / sceneInstrumentation.frameTimeCounter.lastSecAverage;\n },\n dispose: defaultDisposeImpl,\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of meshes selection time metrics.\n * @returns the initializer for the meshes selection time strategy\n */\n static MeshesSelectionStrategy() {\n return (scene) => {\n let startTime = PrecisionDate.Now;\n let timeTaken = 0;\n const onBeforeActiveMeshesObserver = scene.onBeforeActiveMeshesEvaluationObservable.add(() => {\n startTime = PrecisionDate.Now;\n });\n const onAfterActiveMeshesObserver = scene.onAfterActiveMeshesEvaluationObservable.add(() => {\n timeTaken = PrecisionDate.Now - startTime;\n });\n return {\n id: \"Meshes Selection\",\n getData: () => timeTaken,\n dispose: () => {\n scene.onBeforeActiveMeshesEvaluationObservable.remove(onBeforeActiveMeshesObserver);\n scene.onAfterActiveMeshesEvaluationObservable.remove(onAfterActiveMeshesObserver);\n },\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of render targets time metrics.\n * @returns the initializer for the render targets time strategy\n */\n static RenderTargetsStrategy() {\n return (scene) => {\n let startTime = PrecisionDate.Now;\n let timeTaken = 0;\n const onBeforeRenderTargetsObserver = scene.onBeforeRenderTargetsRenderObservable.add(() => {\n startTime = PrecisionDate.Now;\n });\n const onAfterRenderTargetsObserver = scene.onAfterRenderTargetsRenderObservable.add(() => {\n timeTaken = PrecisionDate.Now - startTime;\n });\n return {\n id: \"Render Targets\",\n getData: () => timeTaken,\n dispose: () => {\n scene.onBeforeRenderTargetsRenderObservable.remove(onBeforeRenderTargetsObserver);\n scene.onAfterRenderTargetsRenderObservable.remove(onAfterRenderTargetsObserver);\n },\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of particles time metrics.\n * @returns the initializer for the particles time strategy\n */\n static ParticlesStrategy() {\n return (scene) => {\n let startTime = PrecisionDate.Now;\n let timeTaken = 0;\n const onBeforeParticlesObserver = scene.onBeforeParticlesRenderingObservable.add(() => {\n startTime = PrecisionDate.Now;\n });\n const onAfterParticlesObserver = scene.onAfterParticlesRenderingObservable.add(() => {\n timeTaken = PrecisionDate.Now - startTime;\n });\n return {\n id: \"Particles\",\n getData: () => timeTaken,\n dispose: () => {\n scene.onBeforeParticlesRenderingObservable.remove(onBeforeParticlesObserver);\n scene.onAfterParticlesRenderingObservable.remove(onAfterParticlesObserver);\n },\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of sprites time metrics.\n * @returns the initializer for the sprites time strategy\n */\n static SpritesStrategy() {\n return (scene) => {\n var _a, _b;\n let startTime = PrecisionDate.Now;\n let timeTaken = 0;\n const onBeforeSpritesObserver = (_a = scene.onBeforeSpritesRenderingObservable) === null || _a === void 0 ? void 0 : _a.add(() => {\n startTime = PrecisionDate.Now;\n });\n const onAfterSpritesObserver = (_b = scene.onAfterSpritesRenderingObservable) === null || _b === void 0 ? void 0 : _b.add(() => {\n timeTaken = PrecisionDate.Now - startTime;\n });\n return {\n id: \"Sprites\",\n getData: () => timeTaken,\n dispose: () => {\n var _a, _b;\n (_a = scene.onBeforeSpritesRenderingObservable) === null || _a === void 0 ? void 0 : _a.remove(onBeforeSpritesObserver);\n (_b = scene.onAfterSpritesRenderingObservable) === null || _b === void 0 ? void 0 : _b.remove(onAfterSpritesObserver);\n },\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of animations time metrics.\n * @returns the initializer for the animations time strategy\n */\n static AnimationsStrategy() {\n return (scene) => {\n let startTime = PrecisionDate.Now;\n let timeTaken = 0;\n const onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(() => {\n startTime = PrecisionDate.Now;\n });\n const onAfterAnimationsObserver = scene.onAfterAnimationsObservable.add(() => {\n timeTaken = PrecisionDate.Now - startTime;\n });\n return {\n id: \"Animations\",\n getData: () => timeTaken,\n dispose: () => {\n scene.onBeforeAnimationsObservable.remove(onBeforeAnimationsObserver);\n scene.onAfterAnimationsObservable.remove(onAfterAnimationsObserver);\n },\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of physics time metrics.\n * @returns the initializer for the physics time strategy\n */\n static PhysicsStrategy() {\n return (scene) => {\n var _a, _b;\n let startTime = PrecisionDate.Now;\n let timeTaken = 0;\n const onBeforePhysicsObserver = (_a = scene.onBeforePhysicsObservable) === null || _a === void 0 ? void 0 : _a.add(() => {\n startTime = PrecisionDate.Now;\n });\n const onAfterPhysicsObserver = (_b = scene.onAfterPhysicsObservable) === null || _b === void 0 ? void 0 : _b.add(() => {\n timeTaken = PrecisionDate.Now - startTime;\n });\n return {\n id: \"Physics\",\n getData: () => timeTaken,\n dispose: () => {\n var _a, _b;\n (_a = scene.onBeforePhysicsObservable) === null || _a === void 0 ? void 0 : _a.remove(onBeforePhysicsObserver);\n (_b = scene.onAfterPhysicsObservable) === null || _b === void 0 ? void 0 : _b.remove(onAfterPhysicsObserver);\n },\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of render time metrics.\n * @returns the initializer for the render time strategy\n */\n static RenderStrategy() {\n return (scene) => {\n let startTime = PrecisionDate.Now;\n let timeTaken = 0;\n const onBeforeDrawPhaseObserver = scene.onBeforeDrawPhaseObservable.add(() => {\n startTime = PrecisionDate.Now;\n });\n const onAfterDrawPhaseObserver = scene.onAfterDrawPhaseObservable.add(() => {\n timeTaken = PrecisionDate.Now - startTime;\n });\n return {\n id: \"Render\",\n getData: () => timeTaken,\n dispose: () => {\n scene.onBeforeDrawPhaseObservable.remove(onBeforeDrawPhaseObserver);\n scene.onAfterDrawPhaseObservable.remove(onAfterDrawPhaseObserver);\n },\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of total frame time metrics.\n * @returns the initializer for the total frame time strategy\n */\n static FrameTotalStrategy() {\n return (scene) => {\n let startTime = PrecisionDate.Now;\n let timeTaken = 0;\n const onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(() => {\n startTime = PrecisionDate.Now;\n });\n const onAfterRenderObserver = scene.onAfterRenderObservable.add(() => {\n timeTaken = PrecisionDate.Now - startTime;\n });\n return {\n id: \"Frame Total\",\n getData: () => timeTaken,\n dispose: () => {\n scene.onBeforeAnimationsObservable.remove(onBeforeAnimationsObserver);\n scene.onAfterRenderObservable.remove(onAfterRenderObserver);\n },\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of inter-frame time metrics.\n * @returns the initializer for the inter-frame time strategy\n */\n static InterFrameStrategy() {\n return (scene) => {\n let startTime = PrecisionDate.Now;\n let timeTaken = 0;\n const onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(() => {\n timeTaken = PrecisionDate.Now - startTime;\n });\n const onAfterRenderObserver = scene.onAfterRenderObservable.add(() => {\n startTime = PrecisionDate.Now;\n });\n return {\n id: \"Inter-frame\",\n getData: () => timeTaken,\n dispose: () => {\n scene.onBeforeAnimationsObservable.remove(onBeforeAnimationsObserver);\n scene.onAfterRenderObservable.remove(onAfterRenderObserver);\n },\n };\n };\n }\n /**\n * Gets the initializer for the strategy used for collection of gpu frame time metrics.\n * @returns the initializer for the gpu frame time strategy\n */\n static GpuFrameTimeStrategy() {\n return (scene) => {\n const engineInstrumentation = new EngineInstrumentation(scene.getEngine());\n engineInstrumentation.captureGPUFrameTime = true;\n return {\n id: \"GPU frame time\",\n getData: () => Math.max(engineInstrumentation.gpuFrameTimeCounter.current * 0.000001, 0),\n dispose: () => {\n engineInstrumentation.dispose();\n },\n };\n };\n }\n}\n//# sourceMappingURL=performanceViewerCollectionStrategies.js.map","import { Observable } from \"./observable.js\";\nimport { runCoroutineAsync, inlineScheduler } from \"./coroutine.js\";\nfunction CreateObservableScheduler(observable) {\n const coroutines = new Array();\n const onSteps = new Array();\n const onErrors = new Array();\n const observer = observable.add(() => {\n const count = coroutines.length;\n for (let i = 0; i < count; i++) {\n inlineScheduler(coroutines.shift(), onSteps.shift(), onErrors.shift());\n }\n });\n const scheduler = (coroutine, onStep, onError) => {\n coroutines.push(coroutine);\n onSteps.push(onStep);\n onErrors.push(onError);\n };\n return {\n scheduler: scheduler,\n dispose: () => {\n observable.remove(observer);\n },\n };\n}\nObservable.prototype.runCoroutineAsync = function (coroutine) {\n if (!this._coroutineScheduler) {\n const schedulerAndDispose = CreateObservableScheduler(this);\n this._coroutineScheduler = schedulerAndDispose.scheduler;\n this._coroutineSchedulerDispose = schedulerAndDispose.dispose;\n }\n return runCoroutineAsync(coroutine, this._coroutineScheduler);\n};\nObservable.prototype.cancelAllCoroutines = function () {\n if (this._coroutineSchedulerDispose) {\n this._coroutineSchedulerDispose();\n }\n this._coroutineScheduler = undefined;\n this._coroutineSchedulerDispose = undefined;\n};\n//# sourceMappingURL=observableCoroutine.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./andOrNotEvaluator.js\";\nexport * from \"./assetsManager.js\";\nexport * from \"./basis.js\";\nexport * from \"./dds.js\";\nexport * from \"./decorators.js\";\nexport * from \"./deferred.js\";\nexport * from \"./environmentTextureTools.js\";\nexport * from \"./meshExploder.js\";\nexport * from \"./filesInput.js\";\nexport * from \"./HighDynamicRange/index.js\";\nexport * from \"./khronosTextureContainer.js\";\nexport * from \"./observable.js\";\nexport * from \"./observable.extensions.js\";\nexport * from \"./performanceMonitor.js\";\nexport * from \"./sceneOptimizer.js\";\nexport * from \"./sceneSerializer.js\";\nexport * from \"./smartArray.js\";\nexport * from \"./stringDictionary.js\";\nexport * from \"./tags.js\";\nexport * from \"./textureTools.js\";\nexport * from \"./tga.js\";\nexport * from \"./tools.js\";\nexport * from \"./videoRecorder.js\";\nexport * from \"./virtualJoystick.js\";\nexport * from \"./workerPool.js\";\nexport * from \"./logger.js\";\nexport * from \"./typeStore.js\";\nexport * from \"./filesInputStore.js\";\nexport * from \"./deepCopier.js\";\nexport * from \"./pivotTools.js\";\nexport * from \"./precisionDate.js\";\nexport * from \"./screenshotTools.js\";\nexport * from \"./webRequest.js\";\nexport * from \"./iInspectable.js\";\nexport * from \"./brdfTextureTools.js\";\nexport * from \"./rgbdTextureTools.js\";\nexport * from \"./gradients.js\";\nexport * from \"./perfCounter.js\";\nexport * from \"./fileRequest.js\";\nexport * from \"./customAnimationFrameRequester.js\";\nexport * from \"./retryStrategy.js\";\nexport * from \"./interfaces/screenshotSize.js\";\nexport * from \"./interfaces/iPerfViewer.js\";\nexport * from \"./fileTools.js\";\nexport * from \"./stringTools.js\";\nexport * from \"./dataReader.js\";\nexport * from \"./minMaxReducer.js\";\nexport * from \"./depthReducer.js\";\nexport * from \"./dataStorage.js\";\nexport * from \"./sceneRecorder.js\";\nexport * from \"./khronosTextureContainer2.js\";\nexport * from \"./trajectoryClassifier.js\";\nexport * from \"./timer.js\";\nexport * from \"./copyTools.js\";\nexport * from \"./reflector.js\";\nexport * from \"./domManagement.js\";\nexport * from \"./pressureObserverWrapper.js\";\nexport * from \"./PerformanceViewer/index.js\";\nexport * from \"./coroutine.js\";\nexport * from \"./guid.js\";\nexport * from \"./error.js\";\n// eslint-disable-next-line import/export\nexport * from \"./observableCoroutine.js\";\nexport * from \"./copyTextureToTexture.js\";\nexport * from \"./dumpTools.js\";\nexport * from \"./greasedLineTools.js\";\n//# sourceMappingURL=index.js.map","import { WebXRFeaturesManager, WebXRFeatureName } from \"../webXRFeaturesManager.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { Vector3, Matrix } from \"../../Maths/math.vector.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * The currently-working hit-test module.\n * Hit test (or Ray-casting) is used to interact with the real world.\n * For further information read here - https://github.com/immersive-web/hit-test\n */\nexport class WebXRHitTestLegacy extends WebXRAbstractFeature {\n /**\n * Creates a new instance of the (legacy version) hit test feature\n * @param _xrSessionManager an instance of WebXRSessionManager\n * @param options options to use when constructing this feature\n */\n constructor(_xrSessionManager, \n /**\n * options to use when constructing this feature\n */\n options = {}) {\n super(_xrSessionManager);\n this.options = options;\n // in XR space z-forward is negative\n this._direction = new Vector3(0, 0, -1);\n this._mat = new Matrix();\n this._onSelectEnabled = false;\n this._origin = new Vector3(0, 0, 0);\n /**\n * Populated with the last native XR Hit Results\n */\n this.lastNativeXRHitResults = [];\n /**\n * Triggered when new babylon (transformed) hit test results are available\n */\n this.onHitTestResultObservable = new Observable();\n this._onHitTestResults = (xrResults) => {\n const mats = xrResults.map((result) => {\n const mat = Matrix.FromArray(result.hitMatrix);\n if (!this._xrSessionManager.scene.useRightHandedSystem) {\n mat.toggleModelMatrixHandInPlace();\n }\n // if (this.options.coordinatesSpace === Space.WORLD) {\n if (this.options.worldParentNode) {\n mat.multiplyToRef(this.options.worldParentNode.getWorldMatrix(), mat);\n }\n return {\n xrHitResult: result,\n transformationMatrix: mat,\n };\n });\n this.lastNativeXRHitResults = xrResults;\n this.onHitTestResultObservable.notifyObservers(mats);\n };\n // can be done using pointerdown event, and xrSessionManager.currentFrame\n this._onSelect = (event) => {\n if (!this._onSelectEnabled) {\n return;\n }\n WebXRHitTestLegacy.XRHitTestWithSelectEvent(event, this._xrSessionManager.referenceSpace);\n };\n this.xrNativeFeatureName = \"hit-test\";\n Tools.Warn(\"A newer version of this plugin is available\");\n }\n /**\n * execute a hit test with an XR Ray\n *\n * @param xrSession a native xrSession that will execute this hit test\n * @param xrRay the ray (position and direction) to use for ray-casting\n * @param referenceSpace native XR reference space to use for the hit-test\n * @param filter filter function that will filter the results\n * @returns a promise that resolves with an array of native XR hit result in xr coordinates system\n */\n static XRHitTestWithRay(xrSession, xrRay, referenceSpace, filter) {\n return xrSession.requestHitTest(xrRay, referenceSpace).then((results) => {\n const filterFunction = filter || ((result) => !!result.hitMatrix);\n return results.filter(filterFunction);\n });\n }\n /**\n * Execute a hit test on the current running session using a select event returned from a transient input (such as touch)\n * @param event the (select) event to use to select with\n * @param referenceSpace the reference space to use for this hit test\n * @returns a promise that resolves with an array of native XR hit result in xr coordinates system\n */\n static XRHitTestWithSelectEvent(event, referenceSpace) {\n const targetRayPose = event.frame.getPose(event.inputSource.targetRaySpace, referenceSpace);\n if (!targetRayPose) {\n return Promise.resolve([]);\n }\n const targetRay = new XRRay(targetRayPose.transform);\n return this.XRHitTestWithRay(event.frame.session, targetRay, referenceSpace);\n }\n /**\n * attach this feature\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n attach() {\n if (!super.attach()) {\n return false;\n }\n if (this.options.testOnPointerDownOnly) {\n this._xrSessionManager.session.addEventListener(\"select\", this._onSelect, false);\n }\n return true;\n }\n /**\n * detach this feature.\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n detach() {\n if (!super.detach()) {\n return false;\n }\n // disable select\n this._onSelectEnabled = false;\n this._xrSessionManager.session.removeEventListener(\"select\", this._onSelect);\n return true;\n }\n /**\n * Dispose this feature and all of the resources attached\n */\n dispose() {\n super.dispose();\n this.onHitTestResultObservable.clear();\n }\n _onXRFrame(frame) {\n // make sure we do nothing if (async) not attached\n if (!this.attached || this.options.testOnPointerDownOnly) {\n return;\n }\n const pose = frame.getViewerPose(this._xrSessionManager.referenceSpace);\n if (!pose) {\n return;\n }\n Matrix.FromArrayToRef(pose.transform.matrix, 0, this._mat);\n Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, this._mat, this._origin);\n Vector3.TransformCoordinatesFromFloatsToRef(0, 0, -1, this._mat, this._direction);\n this._direction.subtractInPlace(this._origin);\n this._direction.normalize();\n const ray = new XRRay({ x: this._origin.x, y: this._origin.y, z: this._origin.z, w: 0 }, { x: this._direction.x, y: this._direction.y, z: this._direction.z, w: 0 });\n WebXRHitTestLegacy.XRHitTestWithRay(this._xrSessionManager.session, ray, this._xrSessionManager.referenceSpace).then(this._onHitTestResults);\n }\n}\n/**\n * The module's name\n */\nWebXRHitTestLegacy.Name = WebXRFeatureName.HIT_TEST;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRHitTestLegacy.Version = 1;\n//register the plugin versions\nWebXRFeaturesManager.AddWebXRFeature(WebXRHitTestLegacy.Name, (xrSessionManager, options) => {\n return () => new WebXRHitTestLegacy(xrSessionManager, options);\n}, WebXRHitTestLegacy.Version, false);\n//# sourceMappingURL=WebXRHitTestLegacy.js.map","import { WebXRFeatureName, WebXRFeaturesManager } from \"../webXRFeaturesManager.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { Matrix, Vector3, Quaternion } from \"../../Maths/math.vector.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nlet anchorIdProvider = 0;\n/**\n * An implementation of the anchor system for WebXR.\n * For further information see https://github.com/immersive-web/anchors/\n */\nexport class WebXRAnchorSystem extends WebXRAbstractFeature {\n /**\n * Set the reference space to use for anchor creation, when not using a hit test.\n * Will default to the session's reference space if not defined\n */\n set referenceSpaceForFrameAnchors(referenceSpace) {\n this._referenceSpaceForFrameAnchors = referenceSpace;\n }\n /**\n * constructs a new anchor system\n * @param _xrSessionManager an instance of WebXRSessionManager\n * @param _options configuration object for this feature\n */\n constructor(_xrSessionManager, _options = {}) {\n super(_xrSessionManager);\n this._options = _options;\n this._lastFrameDetected = new Set();\n this._trackedAnchors = [];\n this._futureAnchors = [];\n /**\n * Observers registered here will be executed when a new anchor was added to the session\n */\n this.onAnchorAddedObservable = new Observable();\n /**\n * Observers registered here will be executed when an anchor was removed from the session\n */\n this.onAnchorRemovedObservable = new Observable();\n /**\n * Observers registered here will be executed when an existing anchor updates\n * This can execute N times every frame\n */\n this.onAnchorUpdatedObservable = new Observable();\n this._tmpVector = new Vector3();\n this._tmpQuaternion = new Quaternion();\n this.xrNativeFeatureName = \"anchors\";\n }\n _populateTmpTransformation(position, rotationQuaternion) {\n this._tmpVector.copyFrom(position);\n this._tmpQuaternion.copyFrom(rotationQuaternion);\n if (!this._xrSessionManager.scene.useRightHandedSystem) {\n this._tmpVector.z *= -1;\n this._tmpQuaternion.z *= -1;\n this._tmpQuaternion.w *= -1;\n }\n return {\n position: this._tmpVector,\n rotationQuaternion: this._tmpQuaternion,\n };\n }\n /**\n * Create a new anchor point using a hit test result at a specific point in the scene\n * An anchor is tracked only after it is added to the trackerAnchors in xrFrame. The promise returned here does not yet guaranty that.\n * Use onAnchorAddedObservable to get newly added anchors if you require tracking guaranty.\n *\n * @param hitTestResult The hit test result to use for this anchor creation\n * @param position an optional position offset for this anchor\n * @param rotationQuaternion an optional rotation offset for this anchor\n * @returns A promise that fulfills when babylon has created the corresponding WebXRAnchor object and tracking has begun\n */\n async addAnchorPointUsingHitTestResultAsync(hitTestResult, position = new Vector3(), rotationQuaternion = new Quaternion()) {\n // convert to XR space (right handed) if needed\n this._populateTmpTransformation(position, rotationQuaternion);\n // the matrix that we'll use\n const m = new XRRigidTransform({ x: this._tmpVector.x, y: this._tmpVector.y, z: this._tmpVector.z }, { x: this._tmpQuaternion.x, y: this._tmpQuaternion.y, z: this._tmpQuaternion.z, w: this._tmpQuaternion.w });\n if (!hitTestResult.xrHitResult.createAnchor) {\n this.detach();\n throw new Error(\"Anchors not enabled in this environment/browser\");\n }\n else {\n try {\n const nativeAnchor = await hitTestResult.xrHitResult.createAnchor(m);\n return new Promise((resolve, reject) => {\n this._futureAnchors.push({\n nativeAnchor,\n resolved: false,\n submitted: true,\n xrTransformation: m,\n resolve,\n reject,\n });\n });\n }\n catch (error) {\n throw new Error(error);\n }\n }\n }\n /**\n * Add a new anchor at a specific position and rotation\n * This function will add a new anchor per default in the next available frame. Unless forced, the createAnchor function\n * will be called in the next xrFrame loop to make sure that the anchor can be created correctly.\n * An anchor is tracked only after it is added to the trackerAnchors in xrFrame. The promise returned here does not yet guaranty that.\n * Use onAnchorAddedObservable to get newly added anchors if you require tracking guaranty.\n *\n * @param position the position in which to add an anchor\n * @param rotationQuaternion an optional rotation for the anchor transformation\n * @param forceCreateInCurrentFrame force the creation of this anchor in the current frame. Must be called inside xrFrame loop!\n * @returns A promise that fulfills when babylon has created the corresponding WebXRAnchor object and tracking has begun\n */\n async addAnchorAtPositionAndRotationAsync(position, rotationQuaternion = new Quaternion(), forceCreateInCurrentFrame = false) {\n // convert to XR space (right handed) if needed\n this._populateTmpTransformation(position, rotationQuaternion);\n // the matrix that we'll use\n const xrTransformation = new XRRigidTransform({ x: this._tmpVector.x, y: this._tmpVector.y, z: this._tmpVector.z }, { x: this._tmpQuaternion.x, y: this._tmpQuaternion.y, z: this._tmpQuaternion.z, w: this._tmpQuaternion.w });\n const xrAnchor = forceCreateInCurrentFrame && this.attached && this._xrSessionManager.currentFrame\n ? await this._createAnchorAtTransformation(xrTransformation, this._xrSessionManager.currentFrame)\n : undefined;\n // add the transformation to the future anchors list\n return new Promise((resolve, reject) => {\n this._futureAnchors.push({\n nativeAnchor: xrAnchor,\n resolved: false,\n submitted: false,\n xrTransformation,\n resolve,\n reject,\n });\n });\n }\n /**\n * Get the list of anchors currently being tracked by the system\n */\n get anchors() {\n return this._trackedAnchors;\n }\n /**\n * detach this feature.\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n detach() {\n if (!super.detach()) {\n return false;\n }\n if (!this._options.doNotRemoveAnchorsOnSessionEnded) {\n while (this._trackedAnchors.length) {\n const toRemove = this._trackedAnchors.pop();\n if (toRemove) {\n try {\n // try to natively remove it as well\n toRemove.remove();\n }\n catch (e) {\n // no-op\n }\n // as the xr frame loop is removed, we need to notify manually\n this.onAnchorRemovedObservable.notifyObservers(toRemove);\n }\n }\n }\n return true;\n }\n /**\n * Dispose this feature and all of the resources attached\n */\n dispose() {\n this._futureAnchors.length = 0;\n super.dispose();\n this.onAnchorAddedObservable.clear();\n this.onAnchorRemovedObservable.clear();\n this.onAnchorUpdatedObservable.clear();\n }\n _onXRFrame(frame) {\n if (!this.attached || !frame) {\n return;\n }\n const trackedAnchors = frame.trackedAnchors;\n if (trackedAnchors) {\n const toRemove = this._trackedAnchors\n .filter((anchor) => !trackedAnchors.has(anchor.xrAnchor))\n .map((anchor) => {\n const index = this._trackedAnchors.indexOf(anchor);\n return index;\n });\n let idxTracker = 0;\n toRemove.forEach((index) => {\n const anchor = this._trackedAnchors.splice(index - idxTracker, 1)[0];\n this.onAnchorRemovedObservable.notifyObservers(anchor);\n idxTracker++;\n });\n // now check for new ones\n trackedAnchors.forEach((xrAnchor) => {\n if (!this._lastFrameDetected.has(xrAnchor)) {\n const newAnchor = {\n id: anchorIdProvider++,\n xrAnchor: xrAnchor,\n remove: () => xrAnchor.delete(),\n };\n const anchor = this._updateAnchorWithXRFrame(xrAnchor, newAnchor, frame);\n this._trackedAnchors.push(anchor);\n this.onAnchorAddedObservable.notifyObservers(anchor);\n // search for the future anchor promise that matches this\n const results = this._futureAnchors.filter((futureAnchor) => futureAnchor.nativeAnchor === xrAnchor);\n const result = results[0];\n if (result) {\n result.resolve(anchor);\n result.resolved = true;\n }\n }\n else {\n const index = this._findIndexInAnchorArray(xrAnchor);\n const anchor = this._trackedAnchors[index];\n try {\n // anchors update every frame\n this._updateAnchorWithXRFrame(xrAnchor, anchor, frame);\n if (anchor.attachedNode) {\n anchor.attachedNode.rotationQuaternion = anchor.attachedNode.rotationQuaternion || new Quaternion();\n anchor.transformationMatrix.decompose(anchor.attachedNode.scaling, anchor.attachedNode.rotationQuaternion, anchor.attachedNode.position);\n }\n this.onAnchorUpdatedObservable.notifyObservers(anchor);\n }\n catch (e) {\n Tools.Warn(`Anchor could not be updated`);\n }\n }\n });\n this._lastFrameDetected = trackedAnchors;\n }\n // process future anchors\n this._futureAnchors.forEach((futureAnchor) => {\n if (!futureAnchor.resolved && !futureAnchor.submitted) {\n this._createAnchorAtTransformation(futureAnchor.xrTransformation, frame).then((nativeAnchor) => {\n futureAnchor.nativeAnchor = nativeAnchor;\n }, (error) => {\n futureAnchor.resolved = true;\n futureAnchor.reject(error);\n });\n futureAnchor.submitted = true;\n }\n });\n }\n /**\n * avoiding using Array.find for global support.\n * @param xrAnchor the plane to find in the array\n */\n _findIndexInAnchorArray(xrAnchor) {\n for (let i = 0; i < this._trackedAnchors.length; ++i) {\n if (this._trackedAnchors[i].xrAnchor === xrAnchor) {\n return i;\n }\n }\n return -1;\n }\n _updateAnchorWithXRFrame(xrAnchor, anchor, xrFrame) {\n // matrix\n const pose = xrFrame.getPose(xrAnchor.anchorSpace, this._xrSessionManager.referenceSpace);\n if (pose) {\n const mat = anchor.transformationMatrix || new Matrix();\n Matrix.FromArrayToRef(pose.transform.matrix, 0, mat);\n if (!this._xrSessionManager.scene.useRightHandedSystem) {\n mat.toggleModelMatrixHandInPlace();\n }\n anchor.transformationMatrix = mat;\n if (!this._options.worldParentNode) {\n // Logger.Warn(\"Please provide a world parent node to apply world transformation\");\n }\n else {\n mat.multiplyToRef(this._options.worldParentNode.getWorldMatrix(), mat);\n }\n }\n return anchor;\n }\n async _createAnchorAtTransformation(xrTransformation, xrFrame) {\n var _a;\n if (xrFrame.createAnchor) {\n try {\n return xrFrame.createAnchor(xrTransformation, (_a = this._referenceSpaceForFrameAnchors) !== null && _a !== void 0 ? _a : this._xrSessionManager.referenceSpace);\n }\n catch (error) {\n throw new Error(error);\n }\n }\n else {\n this.detach();\n throw new Error(\"Anchors are not enabled in your browser\");\n }\n }\n}\n/**\n * The module's name\n */\nWebXRAnchorSystem.Name = WebXRFeatureName.ANCHOR_SYSTEM;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRAnchorSystem.Version = 1;\n// register the plugin\nWebXRFeaturesManager.AddWebXRFeature(WebXRAnchorSystem.Name, (xrSessionManager, options) => {\n return () => new WebXRAnchorSystem(xrSessionManager, options);\n}, WebXRAnchorSystem.Version);\n//# sourceMappingURL=WebXRAnchorSystem.js.map","import { WebXRFeaturesManager, WebXRFeatureName } from \"../webXRFeaturesManager.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { Vector3, Matrix } from \"../../Maths/math.vector.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nlet planeIdProvider = 0;\n/**\n * The plane detector is used to detect planes in the real world when in AR\n * For more information see https://github.com/immersive-web/real-world-geometry/\n */\nexport class WebXRPlaneDetector extends WebXRAbstractFeature {\n /**\n * construct a new Plane Detector\n * @param _xrSessionManager an instance of xr Session manager\n * @param _options configuration to use when constructing this feature\n */\n constructor(_xrSessionManager, _options = {}) {\n super(_xrSessionManager);\n this._options = _options;\n this._detectedPlanes = [];\n this._enabled = false;\n this._lastFrameDetected = new Set();\n /**\n * Observers registered here will be executed when a new plane was added to the session\n */\n this.onPlaneAddedObservable = new Observable();\n /**\n * Observers registered here will be executed when a plane is no longer detected in the session\n */\n this.onPlaneRemovedObservable = new Observable();\n /**\n * Observers registered here will be executed when an existing plane updates (for example - expanded)\n * This can execute N times every frame\n */\n this.onPlaneUpdatedObservable = new Observable();\n this.xrNativeFeatureName = \"plane-detection\";\n if (this._xrSessionManager.session) {\n this._init();\n }\n else {\n this._xrSessionManager.onXRSessionInit.addOnce(() => {\n this._init();\n });\n }\n }\n /**\n * detach this feature.\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n detach() {\n if (!super.detach()) {\n return false;\n }\n if (!this._options.doNotRemovePlanesOnSessionEnded) {\n while (this._detectedPlanes.length) {\n const toRemove = this._detectedPlanes.pop();\n if (toRemove) {\n this.onPlaneRemovedObservable.notifyObservers(toRemove);\n }\n }\n }\n return true;\n }\n /**\n * Dispose this feature and all of the resources attached\n */\n dispose() {\n super.dispose();\n this.onPlaneAddedObservable.clear();\n this.onPlaneRemovedObservable.clear();\n this.onPlaneUpdatedObservable.clear();\n }\n /**\n * Check if the needed objects are defined.\n * This does not mean that the feature is enabled, but that the objects needed are well defined.\n */\n isCompatible() {\n return typeof XRPlane !== \"undefined\";\n }\n _onXRFrame(frame) {\n var _a;\n if (!this.attached || !this._enabled || !frame) {\n return;\n }\n const detectedPlanes = frame.detectedPlanes || ((_a = frame.worldInformation) === null || _a === void 0 ? void 0 : _a.detectedPlanes);\n if (detectedPlanes) {\n // remove all planes that are not currently detected in the frame\n for (let planeIdx = 0; planeIdx < this._detectedPlanes.length; planeIdx++) {\n const plane = this._detectedPlanes[planeIdx];\n if (!detectedPlanes.has(plane.xrPlane)) {\n this._detectedPlanes.splice(planeIdx--, 1);\n this.onPlaneRemovedObservable.notifyObservers(plane);\n }\n }\n // now check for new ones\n detectedPlanes.forEach((xrPlane) => {\n if (!this._lastFrameDetected.has(xrPlane)) {\n const newPlane = {\n id: planeIdProvider++,\n xrPlane: xrPlane,\n polygonDefinition: [],\n };\n const plane = this._updatePlaneWithXRPlane(xrPlane, newPlane, frame);\n this._detectedPlanes.push(plane);\n this.onPlaneAddedObservable.notifyObservers(plane);\n }\n else {\n // updated?\n if (xrPlane.lastChangedTime === this._xrSessionManager.currentTimestamp) {\n const index = this._findIndexInPlaneArray(xrPlane);\n const plane = this._detectedPlanes[index];\n this._updatePlaneWithXRPlane(xrPlane, plane, frame);\n this.onPlaneUpdatedObservable.notifyObservers(plane);\n }\n }\n });\n this._lastFrameDetected = detectedPlanes;\n }\n }\n _init() {\n const internalInit = () => {\n this._enabled = true;\n if (this._detectedPlanes.length) {\n this._detectedPlanes.length = 0;\n }\n };\n // Only supported by BabylonNative\n if (!!this._xrSessionManager.isNative && !!this._options.preferredDetectorOptions && !!this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions) {\n this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions);\n }\n if (!this._xrSessionManager.session.updateWorldTrackingState) {\n internalInit();\n return;\n }\n this._xrSessionManager.session.updateWorldTrackingState({ planeDetectionState: { enabled: true } });\n internalInit();\n }\n _updatePlaneWithXRPlane(xrPlane, plane, xrFrame) {\n plane.polygonDefinition = xrPlane.polygon.map((xrPoint) => {\n const rightHandedSystem = this._xrSessionManager.scene.useRightHandedSystem ? 1 : -1;\n return new Vector3(xrPoint.x, xrPoint.y, xrPoint.z * rightHandedSystem);\n });\n // matrix\n const pose = xrFrame.getPose(xrPlane.planeSpace, this._xrSessionManager.referenceSpace);\n if (pose) {\n const mat = plane.transformationMatrix || new Matrix();\n Matrix.FromArrayToRef(pose.transform.matrix, 0, mat);\n if (!this._xrSessionManager.scene.useRightHandedSystem) {\n mat.toggleModelMatrixHandInPlace();\n }\n plane.transformationMatrix = mat;\n if (this._options.worldParentNode) {\n mat.multiplyToRef(this._options.worldParentNode.getWorldMatrix(), mat);\n }\n }\n return plane;\n }\n /**\n * avoiding using Array.find for global support.\n * @param xrPlane the plane to find in the array\n */\n _findIndexInPlaneArray(xrPlane) {\n for (let i = 0; i < this._detectedPlanes.length; ++i) {\n if (this._detectedPlanes[i].xrPlane === xrPlane) {\n return i;\n }\n }\n return -1;\n }\n}\n/**\n * The module's name\n */\nWebXRPlaneDetector.Name = WebXRFeatureName.PLANE_DETECTION;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRPlaneDetector.Version = 1;\n//register the plugin\nWebXRFeaturesManager.AddWebXRFeature(WebXRPlaneDetector.Name, (xrSessionManager, options) => {\n return () => new WebXRPlaneDetector(xrSessionManager, options);\n}, WebXRPlaneDetector.Version);\n//# sourceMappingURL=WebXRPlaneDetector.js.map","import { WebXRFeaturesManager, WebXRFeatureName } from \"../webXRFeaturesManager.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\n/**\n * A module that will automatically disable background meshes when entering AR and will enable them when leaving AR.\n */\nexport class WebXRBackgroundRemover extends WebXRAbstractFeature {\n /**\n * constructs a new background remover module\n * @param _xrSessionManager the session manager for this module\n * @param options read-only options to be used in this module\n */\n constructor(_xrSessionManager, \n /**\n * read-only options to be used in this module\n */\n options = {}) {\n super(_xrSessionManager);\n this.options = options;\n /**\n * registered observers will be triggered when the background state changes\n */\n this.onBackgroundStateChangedObservable = new Observable();\n }\n /**\n * attach this feature\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n attach() {\n this._setBackgroundState(false);\n return super.attach();\n }\n /**\n * detach this feature.\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n detach() {\n this._setBackgroundState(true);\n return super.detach();\n }\n /**\n * Dispose this feature and all of the resources attached\n */\n dispose() {\n super.dispose();\n this.onBackgroundStateChangedObservable.clear();\n }\n _onXRFrame(_xrFrame) {\n // no-op\n }\n _setBackgroundState(newState) {\n const scene = this._xrSessionManager.scene;\n if (!this.options.ignoreEnvironmentHelper) {\n if (this.options.environmentHelperRemovalFlags) {\n if (this.options.environmentHelperRemovalFlags.skyBox) {\n const backgroundSkybox = scene.getMeshByName(\"BackgroundSkybox\");\n if (backgroundSkybox) {\n backgroundSkybox.setEnabled(newState);\n }\n }\n if (this.options.environmentHelperRemovalFlags.ground) {\n const backgroundPlane = scene.getMeshByName(\"BackgroundPlane\");\n if (backgroundPlane) {\n backgroundPlane.setEnabled(newState);\n }\n }\n }\n else {\n const backgroundHelper = scene.getMeshByName(\"BackgroundHelper\");\n if (backgroundHelper) {\n backgroundHelper.setEnabled(newState);\n }\n }\n }\n if (this.options.backgroundMeshes) {\n this.options.backgroundMeshes.forEach((mesh) => mesh.setEnabled(newState));\n }\n this.onBackgroundStateChangedObservable.notifyObservers(newState);\n }\n}\n/**\n * The module's name\n */\nWebXRBackgroundRemover.Name = WebXRFeatureName.BACKGROUND_REMOVER;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRBackgroundRemover.Version = 1;\n//register the plugin\nWebXRFeaturesManager.AddWebXRFeature(WebXRBackgroundRemover.Name, (xrSessionManager, options) => {\n return () => new WebXRBackgroundRemover(xrSessionManager, options);\n}, WebXRBackgroundRemover.Version, true);\n//# sourceMappingURL=WebXRBackgroundRemover.js.map","import { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nimport { Vector3, Quaternion } from \"../../Maths/math.vector.js\";\nimport { PhysicsImpostor } from \"../../Physics/v1/physicsImpostor.js\";\nimport { CreateSphere } from \"../../Meshes/Builders/sphereBuilder.js\";\nimport { WebXRFeatureName, WebXRFeaturesManager } from \"../webXRFeaturesManager.js\";\nimport { Logger } from \"../../Misc/logger.js\";\n/**\n * Options for the controller physics feature\n */\nexport class IWebXRControllerPhysicsOptions {\n}\n/**\n * Add physics impostor to your webxr controllers,\n * including naive calculation of their linear and angular velocity\n */\nexport class WebXRControllerPhysics extends WebXRAbstractFeature {\n _createPhysicsImpostor(xrController) {\n const impostorType = this._options.physicsProperties.impostorType || PhysicsImpostor.SphereImpostor;\n const impostorSize = this._options.physicsProperties.impostorSize || 0.1;\n const impostorMesh = CreateSphere(\"impostor-mesh-\" + xrController.uniqueId, {\n diameterX: typeof impostorSize === \"number\" ? impostorSize : impostorSize.width,\n diameterY: typeof impostorSize === \"number\" ? impostorSize : impostorSize.height,\n diameterZ: typeof impostorSize === \"number\" ? impostorSize : impostorSize.depth,\n });\n impostorMesh.isVisible = this._debugMode;\n impostorMesh.isPickable = false;\n impostorMesh.rotationQuaternion = new Quaternion();\n const controllerMesh = xrController.grip || xrController.pointer;\n impostorMesh.position.copyFrom(controllerMesh.position);\n impostorMesh.rotationQuaternion.copyFrom(controllerMesh.rotationQuaternion);\n const impostor = new PhysicsImpostor(impostorMesh, impostorType, Object.assign({ mass: 0 }, this._options.physicsProperties));\n this._controllers[xrController.uniqueId] = {\n xrController,\n impostor,\n impostorMesh,\n };\n }\n /**\n * Construct a new Controller Physics Feature\n * @param _xrSessionManager the corresponding xr session manager\n * @param _options options to create this feature with\n */\n constructor(_xrSessionManager, _options) {\n super(_xrSessionManager);\n this._options = _options;\n this._attachController = (xrController) => {\n if (this._controllers[xrController.uniqueId]) {\n // already attached\n return;\n }\n if (!this._xrSessionManager.scene.isPhysicsEnabled()) {\n Logger.Warn(\"physics engine not enabled, skipped. Please add this controller manually.\");\n }\n // if no motion controller available, create impostors!\n if (this._options.physicsProperties.useControllerMesh && xrController.inputSource.gamepad) {\n xrController.onMotionControllerInitObservable.addOnce((motionController) => {\n if (!motionController._doNotLoadControllerMesh) {\n motionController.onModelLoadedObservable.addOnce(() => {\n const impostor = new PhysicsImpostor(motionController.rootMesh, PhysicsImpostor.MeshImpostor, Object.assign({ mass: 0 }, this._options.physicsProperties));\n const controllerMesh = xrController.grip || xrController.pointer;\n this._controllers[xrController.uniqueId] = {\n xrController,\n impostor,\n oldPos: controllerMesh.position.clone(),\n oldRotation: controllerMesh.rotationQuaternion.clone(),\n };\n });\n }\n else {\n // This controller isn't using a model, create impostors instead\n this._createPhysicsImpostor(xrController);\n }\n });\n }\n else {\n this._createPhysicsImpostor(xrController);\n }\n };\n this._controllers = {};\n this._debugMode = false;\n this._delta = 0;\n this._lastTimestamp = 0;\n this._tmpQuaternion = new Quaternion();\n this._tmpVector = new Vector3();\n if (!this._options.physicsProperties) {\n this._options.physicsProperties = {};\n }\n }\n /**\n * @internal\n * enable debugging - will show console outputs and the impostor mesh\n */\n _enablePhysicsDebug() {\n this._debugMode = true;\n Object.keys(this._controllers).forEach((controllerId) => {\n const controllerData = this._controllers[controllerId];\n if (controllerData.impostorMesh) {\n controllerData.impostorMesh.isVisible = true;\n }\n });\n }\n /**\n * Manually add a controller (if no xrInput was provided or physics engine was not enabled)\n * @param xrController the controller to add\n */\n addController(xrController) {\n this._attachController(xrController);\n }\n /**\n * attach this feature\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n attach() {\n if (!super.attach()) {\n return false;\n }\n if (!this._options.xrInput) {\n return true;\n }\n this._options.xrInput.controllers.forEach(this._attachController);\n this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController);\n this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, (controller) => {\n // REMOVE the controller\n this._detachController(controller.uniqueId);\n });\n if (this._options.enableHeadsetImpostor) {\n const params = this._options.headsetImpostorParams || {\n impostorType: PhysicsImpostor.SphereImpostor,\n restitution: 0.8,\n impostorSize: 0.3,\n };\n const impostorSize = params.impostorSize || 0.3;\n this._headsetMesh = CreateSphere(\"headset-mesh\", {\n diameterX: typeof impostorSize === \"number\" ? impostorSize : impostorSize.width,\n diameterY: typeof impostorSize === \"number\" ? impostorSize : impostorSize.height,\n diameterZ: typeof impostorSize === \"number\" ? impostorSize : impostorSize.depth,\n });\n this._headsetMesh.rotationQuaternion = new Quaternion();\n this._headsetMesh.isVisible = false;\n this._headsetImpostor = new PhysicsImpostor(this._headsetMesh, params.impostorType, Object.assign({ mass: 0 }, params));\n }\n return true;\n }\n /**\n * detach this feature.\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n detach() {\n if (!super.detach()) {\n return false;\n }\n Object.keys(this._controllers).forEach((controllerId) => {\n this._detachController(controllerId);\n });\n if (this._headsetMesh) {\n this._headsetMesh.dispose();\n }\n return true;\n }\n /**\n * Get the headset impostor, if enabled\n * @returns the impostor\n */\n getHeadsetImpostor() {\n return this._headsetImpostor;\n }\n /**\n * Get the physics impostor of a specific controller.\n * The impostor is not attached to a mesh because a mesh for each controller is not obligatory\n * @param controller the controller or the controller id of which to get the impostor\n * @returns the impostor or null\n */\n getImpostorForController(controller) {\n const id = typeof controller === \"string\" ? controller : controller.uniqueId;\n if (this._controllers[id]) {\n return this._controllers[id].impostor;\n }\n else {\n return null;\n }\n }\n /**\n * Update the physics properties provided in the constructor\n * @param newProperties the new properties object\n * @param newProperties.impostorType\n * @param newProperties.impostorSize\n * @param newProperties.friction\n * @param newProperties.restitution\n */\n setPhysicsProperties(newProperties) {\n this._options.physicsProperties = Object.assign(Object.assign({}, this._options.physicsProperties), newProperties);\n }\n _onXRFrame(_xrFrame) {\n var _a, _b;\n this._delta = this._xrSessionManager.currentTimestamp - this._lastTimestamp;\n this._lastTimestamp = this._xrSessionManager.currentTimestamp;\n if (this._headsetMesh && this._headsetImpostor) {\n this._headsetMesh.position.copyFrom(this._options.xrInput.xrCamera.globalPosition);\n this._headsetMesh.rotationQuaternion.copyFrom(this._options.xrInput.xrCamera.absoluteRotation);\n if ((_a = this._options.xrInput.xrCamera._lastXRViewerPose) === null || _a === void 0 ? void 0 : _a.linearVelocity) {\n const lv = this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity;\n this._tmpVector.set(lv.x, lv.y, lv.z);\n this._headsetImpostor.setLinearVelocity(this._tmpVector);\n }\n if ((_b = this._options.xrInput.xrCamera._lastXRViewerPose) === null || _b === void 0 ? void 0 : _b.angularVelocity) {\n const av = this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity;\n this._tmpVector.set(av.x, av.y, av.z);\n this._headsetImpostor.setAngularVelocity(this._tmpVector);\n }\n }\n Object.keys(this._controllers).forEach((controllerId) => {\n var _a, _b;\n const controllerData = this._controllers[controllerId];\n const controllerMesh = controllerData.xrController.grip || controllerData.xrController.pointer;\n const comparedPosition = controllerData.oldPos || controllerData.impostorMesh.position;\n if ((_a = controllerData.xrController._lastXRPose) === null || _a === void 0 ? void 0 : _a.linearVelocity) {\n const lv = controllerData.xrController._lastXRPose.linearVelocity;\n this._tmpVector.set(lv.x, lv.y, lv.z);\n controllerData.impostor.setLinearVelocity(this._tmpVector);\n }\n else {\n controllerMesh.position.subtractToRef(comparedPosition, this._tmpVector);\n this._tmpVector.scaleInPlace(1000 / this._delta);\n controllerData.impostor.setLinearVelocity(this._tmpVector);\n }\n comparedPosition.copyFrom(controllerMesh.position);\n if (this._debugMode) {\n console.log(this._tmpVector, \"linear\");\n }\n const comparedQuaternion = controllerData.oldRotation || controllerData.impostorMesh.rotationQuaternion;\n if ((_b = controllerData.xrController._lastXRPose) === null || _b === void 0 ? void 0 : _b.angularVelocity) {\n const av = controllerData.xrController._lastXRPose.angularVelocity;\n this._tmpVector.set(av.x, av.y, av.z);\n controllerData.impostor.setAngularVelocity(this._tmpVector);\n }\n else {\n if (!comparedQuaternion.equalsWithEpsilon(controllerMesh.rotationQuaternion)) {\n // roughly based on this - https://www.gamedev.net/forums/topic/347752-quaternion-and-angular-velocity/\n comparedQuaternion.conjugateInPlace().multiplyToRef(controllerMesh.rotationQuaternion, this._tmpQuaternion);\n const len = Math.sqrt(this._tmpQuaternion.x * this._tmpQuaternion.x + this._tmpQuaternion.y * this._tmpQuaternion.y + this._tmpQuaternion.z * this._tmpQuaternion.z);\n this._tmpVector.set(this._tmpQuaternion.x, this._tmpQuaternion.y, this._tmpQuaternion.z);\n // define a better epsilon\n if (len < 0.001) {\n this._tmpVector.scaleInPlace(2);\n }\n else {\n const angle = 2 * Math.atan2(len, this._tmpQuaternion.w);\n this._tmpVector.scaleInPlace(angle / (len * (this._delta / 1000)));\n }\n controllerData.impostor.setAngularVelocity(this._tmpVector);\n }\n }\n comparedQuaternion.copyFrom(controllerMesh.rotationQuaternion);\n if (this._debugMode) {\n console.log(this._tmpVector, this._tmpQuaternion, \"angular\");\n }\n });\n }\n _detachController(xrControllerUniqueId) {\n const controllerData = this._controllers[xrControllerUniqueId];\n if (!controllerData) {\n return;\n }\n if (controllerData.impostorMesh) {\n controllerData.impostorMesh.dispose();\n }\n // remove from the map\n delete this._controllers[xrControllerUniqueId];\n }\n}\n/**\n * The module's name\n */\nWebXRControllerPhysics.Name = WebXRFeatureName.PHYSICS_CONTROLLERS;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the webxr specs version\n */\nWebXRControllerPhysics.Version = 1;\n//register the plugin\nWebXRFeaturesManager.AddWebXRFeature(WebXRControllerPhysics.Name, (xrSessionManager, options) => {\n return () => new WebXRControllerPhysics(xrSessionManager, options);\n}, WebXRControllerPhysics.Version, true);\n//# sourceMappingURL=WebXRControllerPhysics.js.map","import { WebXRFeaturesManager, WebXRFeatureName } from \"../webXRFeaturesManager.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { Vector3, Matrix, Quaternion } from \"../../Maths/math.vector.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * The currently-working hit-test module.\n * Hit test (or Ray-casting) is used to interact with the real world.\n * For further information read here - https://github.com/immersive-web/hit-test\n *\n * Tested on chrome (mobile) 80.\n */\nexport class WebXRHitTest extends WebXRAbstractFeature {\n /**\n * Creates a new instance of the hit test feature\n * @param _xrSessionManager an instance of WebXRSessionManager\n * @param options options to use when constructing this feature\n */\n constructor(_xrSessionManager, \n /**\n * options to use when constructing this feature\n */\n options = {}) {\n super(_xrSessionManager);\n this.options = options;\n this._tmpMat = new Matrix();\n this._tmpPos = new Vector3();\n this._tmpQuat = new Quaternion();\n this._initHitTestSource = (referenceSpace) => {\n if (!referenceSpace) {\n return;\n }\n const offsetRay = new XRRay(this.options.offsetRay || {});\n const hitTestOptions = {\n space: this.options.useReferenceSpace ? referenceSpace : this._xrSessionManager.viewerReferenceSpace,\n offsetRay: offsetRay,\n };\n if (this.options.entityTypes) {\n hitTestOptions.entityTypes = this.options.entityTypes;\n }\n if (!hitTestOptions.space) {\n Tools.Warn(\"waiting for viewer reference space to initialize\");\n return;\n }\n this._xrSessionManager.session.requestHitTestSource(hitTestOptions).then((hitTestSource) => {\n if (this._xrHitTestSource) {\n this._xrHitTestSource.cancel();\n }\n this._xrHitTestSource = hitTestSource;\n });\n };\n /**\n * When set to true, each hit test will have its own position/rotation objects\n * When set to false, position and rotation objects will be reused for each hit test. It is expected that\n * the developers will clone them or copy them as they see fit.\n */\n this.autoCloneTransformation = false;\n /**\n * Triggered when new babylon (transformed) hit test results are available\n * Note - this will be called when results come back from the device. It can be an empty array!!\n */\n this.onHitTestResultObservable = new Observable();\n /**\n * Use this to temporarily pause hit test checks.\n */\n this.paused = false;\n this.xrNativeFeatureName = \"hit-test\";\n Tools.Warn(\"Hit test is an experimental and unstable feature.\");\n }\n /**\n * attach this feature\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n attach() {\n if (!super.attach()) {\n return false;\n }\n // Feature enabled, but not available\n if (!this._xrSessionManager.session.requestHitTestSource) {\n return false;\n }\n if (!this.options.disablePermanentHitTest) {\n if (this._xrSessionManager.referenceSpace) {\n this._initHitTestSource(this._xrSessionManager.referenceSpace);\n }\n this._xrSessionManager.onXRReferenceSpaceChanged.add(this._initHitTestSource);\n }\n if (this.options.enableTransientHitTest) {\n const offsetRay = new XRRay(this.options.transientOffsetRay || {});\n this._xrSessionManager.session.requestHitTestSourceForTransientInput({\n profile: this.options.transientHitTestProfile || \"generic-touchscreen\",\n offsetRay,\n entityTypes: this.options.entityTypes,\n }).then((hitSource) => {\n this._transientXrHitTestSource = hitSource;\n });\n }\n return true;\n }\n /**\n * detach this feature.\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n detach() {\n if (!super.detach()) {\n return false;\n }\n if (this._xrHitTestSource) {\n this._xrHitTestSource.cancel();\n this._xrHitTestSource = null;\n }\n this._xrSessionManager.onXRReferenceSpaceChanged.removeCallback(this._initHitTestSource);\n if (this._transientXrHitTestSource) {\n this._transientXrHitTestSource.cancel();\n this._transientXrHitTestSource = null;\n }\n return true;\n }\n /**\n * Dispose this feature and all of the resources attached\n */\n dispose() {\n super.dispose();\n this.onHitTestResultObservable.clear();\n }\n _onXRFrame(frame) {\n // make sure we do nothing if (async) not attached\n if (!this.attached || this.paused) {\n return;\n }\n if (this._xrHitTestSource) {\n const results = frame.getHitTestResults(this._xrHitTestSource);\n this._processWebXRHitTestResult(results);\n }\n if (this._transientXrHitTestSource) {\n const hitTestResultsPerInputSource = frame.getHitTestResultsForTransientInput(this._transientXrHitTestSource);\n hitTestResultsPerInputSource.forEach((resultsPerInputSource) => {\n this._processWebXRHitTestResult(resultsPerInputSource.results, resultsPerInputSource.inputSource);\n });\n }\n }\n _processWebXRHitTestResult(hitTestResults, inputSource) {\n const results = [];\n hitTestResults.forEach((hitTestResult) => {\n const pose = hitTestResult.getPose(this._xrSessionManager.referenceSpace);\n if (!pose) {\n return;\n }\n const pos = pose.transform.position;\n const quat = pose.transform.orientation;\n this._tmpPos.set(pos.x, pos.y, pos.z);\n this._tmpQuat.set(quat.x, quat.y, quat.z, quat.w);\n Matrix.FromFloat32ArrayToRefScaled(pose.transform.matrix, 0, 1, this._tmpMat);\n if (!this._xrSessionManager.scene.useRightHandedSystem) {\n this._tmpPos.z *= -1;\n this._tmpQuat.z *= -1;\n this._tmpQuat.w *= -1;\n this._tmpMat.toggleModelMatrixHandInPlace();\n }\n const result = {\n position: this.autoCloneTransformation ? this._tmpPos.clone() : this._tmpPos,\n rotationQuaternion: this.autoCloneTransformation ? this._tmpQuat.clone() : this._tmpQuat,\n transformationMatrix: this.autoCloneTransformation ? this._tmpMat.clone() : this._tmpMat,\n inputSource: inputSource,\n isTransient: !!inputSource,\n xrHitResult: hitTestResult,\n };\n results.push(result);\n });\n this.onHitTestResultObservable.notifyObservers(results);\n }\n}\n/**\n * The module's name\n */\nWebXRHitTest.Name = WebXRFeatureName.HIT_TEST;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRHitTest.Version = 2;\n//register the plugin versions\nWebXRFeaturesManager.AddWebXRFeature(WebXRHitTest.Name, (xrSessionManager, options) => {\n return () => new WebXRHitTest(xrSessionManager, options);\n}, WebXRHitTest.Version, false);\n//# sourceMappingURL=WebXRHitTest.js.map","import { WebXRFeaturesManager, WebXRFeatureName } from \"../webXRFeaturesManager.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\n/**\n * The feature point system is used to detect feature points from real world geometry.\n * This feature is currently experimental and only supported on BabylonNative, and should not be used in the browser.\n * The newly introduced API can be seen in webxr.nativeextensions.d.ts and described in FeaturePoints.md.\n */\nexport class WebXRFeaturePointSystem extends WebXRAbstractFeature {\n /**\n * The current feature point cloud maintained across frames.\n */\n get featurePointCloud() {\n return this._featurePointCloud;\n }\n /**\n * construct the feature point system\n * @param _xrSessionManager an instance of xr Session manager\n */\n constructor(_xrSessionManager) {\n super(_xrSessionManager);\n this._enabled = false;\n this._featurePointCloud = [];\n /**\n * Observers registered here will be executed whenever new feature points are added (on XRFrame while the session is tracking).\n * Will notify the observers about which feature points have been added.\n */\n this.onFeaturePointsAddedObservable = new Observable();\n /**\n * Observers registered here will be executed whenever a feature point has been updated (on XRFrame while the session is tracking).\n * Will notify the observers about which feature points have been updated.\n */\n this.onFeaturePointsUpdatedObservable = new Observable();\n this.xrNativeFeatureName = \"bjsfeature-points\";\n if (this._xrSessionManager.session) {\n this._init();\n }\n else {\n this._xrSessionManager.onXRSessionInit.addOnce(() => {\n this._init();\n });\n }\n }\n /**\n * Detach this feature.\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n detach() {\n if (!super.detach()) {\n return false;\n }\n this.featurePointCloud.length = 0;\n return true;\n }\n /**\n * Dispose this feature and all of the resources attached\n */\n dispose() {\n super.dispose();\n this._featurePointCloud.length = 0;\n this.onFeaturePointsUpdatedObservable.clear();\n this.onFeaturePointsAddedObservable.clear();\n }\n /**\n * On receiving a new XR frame if this feature is attached notify observers new feature point data is available.\n * @param frame\n */\n _onXRFrame(frame) {\n if (!this.attached || !this._enabled || !frame) {\n return;\n }\n const featurePointRawData = frame.featurePointCloud;\n if (!featurePointRawData || featurePointRawData.length === 0) {\n return;\n }\n else {\n if (featurePointRawData.length % 5 !== 0) {\n throw new Error(\"Received malformed feature point cloud of length: \" + featurePointRawData.length);\n }\n const numberOfFeaturePoints = featurePointRawData.length / 5;\n const updatedFeaturePoints = new Array();\n const addedFeaturePoints = new Array();\n for (let i = 0; i < numberOfFeaturePoints; i++) {\n const rawIndex = i * 5;\n const id = featurePointRawData[rawIndex + 4];\n // IDs should be durable across frames and strictly increasing from 0 up, so use them as indexing into the feature point array.\n if (!this._featurePointCloud[id]) {\n this._featurePointCloud[id] = { position: new Vector3(), confidenceValue: 0 };\n addedFeaturePoints.push(id);\n }\n else {\n updatedFeaturePoints.push(id);\n }\n // Set the feature point values.\n this._featurePointCloud[id].position.x = featurePointRawData[rawIndex];\n this._featurePointCloud[id].position.y = featurePointRawData[rawIndex + 1];\n this._featurePointCloud[id].position.z = featurePointRawData[rawIndex + 2];\n this._featurePointCloud[id].confidenceValue = featurePointRawData[rawIndex + 3];\n }\n // Signal observers that feature points have been added if necessary.\n if (addedFeaturePoints.length > 0) {\n this.onFeaturePointsAddedObservable.notifyObservers(addedFeaturePoints);\n }\n // Signal observers that feature points have been updated if necessary.\n if (updatedFeaturePoints.length > 0) {\n this.onFeaturePointsUpdatedObservable.notifyObservers(updatedFeaturePoints);\n }\n }\n }\n /**\n * Initializes the feature. If the feature point feature is not available for this environment do not mark the feature as enabled.\n */\n _init() {\n if (!this._xrSessionManager.session.trySetFeaturePointCloudEnabled || !this._xrSessionManager.session.trySetFeaturePointCloudEnabled(true)) {\n // fail silently\n return;\n }\n this._enabled = true;\n }\n}\n/**\n * The module's name\n */\nWebXRFeaturePointSystem.Name = WebXRFeatureName.FEATURE_POINTS;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRFeaturePointSystem.Version = 1;\n// register the plugin\nWebXRFeaturesManager.AddWebXRFeature(WebXRFeaturePointSystem.Name, (xrSessionManager) => {\n return () => new WebXRFeaturePointSystem(xrSessionManager);\n}, WebXRFeaturePointSystem.Version);\n//# sourceMappingURL=WebXRFeaturePointSystem.js.map","import { WebXRFeaturesManager, WebXRFeatureName } from \"../webXRFeaturesManager.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nimport { Matrix } from \"../../Maths/math.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nlet meshIdProvider = 0;\n/**\n * The mesh detector is used to detect meshes in the real world when in AR\n */\nexport class WebXRMeshDetector extends WebXRAbstractFeature {\n constructor(_xrSessionManager, _options = {}) {\n super(_xrSessionManager);\n this._options = _options;\n this._detectedMeshes = new Map();\n /**\n * Observers registered here will be executed when a new mesh was added to the session\n */\n this.onMeshAddedObservable = new Observable();\n /**\n * Observers registered here will be executed when a mesh is no longer detected in the session\n */\n this.onMeshRemovedObservable = new Observable();\n /**\n * Observers registered here will be executed when an existing mesh updates\n */\n this.onMeshUpdatedObservable = new Observable();\n this.xrNativeFeatureName = \"mesh-detection\";\n if (this._xrSessionManager.session) {\n this._init();\n }\n else {\n this._xrSessionManager.onXRSessionInit.addOnce(() => {\n this._init();\n });\n }\n }\n detach() {\n if (!super.detach()) {\n return false;\n }\n // Only supported by BabylonNative\n if (!!this._xrSessionManager.isNative && !!this._xrSessionManager.session.trySetMeshDetectorEnabled) {\n this._xrSessionManager.session.trySetMeshDetectorEnabled(false);\n }\n if (!this._options.doNotRemoveMeshesOnSessionEnded) {\n this._detectedMeshes.forEach((mesh) => {\n this.onMeshRemovedObservable.notifyObservers(mesh);\n });\n this._detectedMeshes.clear();\n }\n return true;\n }\n dispose() {\n super.dispose();\n this.onMeshAddedObservable.clear();\n this.onMeshRemovedObservable.clear();\n this.onMeshUpdatedObservable.clear();\n }\n _onXRFrame(frame) {\n var _a;\n // TODO remove try catch\n try {\n if (!this.attached || !frame) {\n return;\n }\n const detectedMeshes = (_a = frame.worldInformation) === null || _a === void 0 ? void 0 : _a.detectedMeshes;\n if (detectedMeshes) {\n const toRemove = new Set();\n this._detectedMeshes.forEach((vertexData, xrMesh) => {\n if (!detectedMeshes.has(xrMesh)) {\n toRemove.add(xrMesh);\n }\n });\n toRemove.forEach((xrMesh) => {\n const vertexData = this._detectedMeshes.get(xrMesh);\n if (vertexData) {\n this.onMeshRemovedObservable.notifyObservers(vertexData);\n this._detectedMeshes.delete(xrMesh);\n }\n });\n // now check for new ones\n detectedMeshes.forEach((xrMesh) => {\n if (!this._detectedMeshes.has(xrMesh)) {\n const partialVertexData = {\n id: meshIdProvider++,\n xrMesh: xrMesh,\n };\n const vertexData = this._updateVertexDataWithXRMesh(xrMesh, partialVertexData, frame);\n this._detectedMeshes.set(xrMesh, vertexData);\n this.onMeshAddedObservable.notifyObservers(vertexData);\n }\n else {\n // updated?\n if (xrMesh.lastChangedTime === this._xrSessionManager.currentTimestamp) {\n const vertexData = this._detectedMeshes.get(xrMesh);\n if (vertexData) {\n this._updateVertexDataWithXRMesh(xrMesh, vertexData, frame);\n this.onMeshUpdatedObservable.notifyObservers(vertexData);\n }\n }\n }\n });\n }\n }\n catch (error) {\n console.log(error.stack);\n }\n }\n _init() {\n // Only supported by BabylonNative\n if (this._xrSessionManager.isNative) {\n if (this._xrSessionManager.session.trySetMeshDetectorEnabled) {\n this._xrSessionManager.session.trySetMeshDetectorEnabled(true);\n }\n if (!!this._options.preferredDetectorOptions && !!this._xrSessionManager.session.trySetPreferredMeshDetectorOptions) {\n this._xrSessionManager.session.trySetPreferredMeshDetectorOptions(this._options.preferredDetectorOptions);\n }\n }\n }\n _updateVertexDataWithXRMesh(xrMesh, mesh, xrFrame) {\n mesh.xrMesh = xrMesh;\n mesh.worldParentNode = this._options.worldParentNode;\n if (this._options.convertCoordinateSystems) {\n if (!this._xrSessionManager.scene.useRightHandedSystem) {\n mesh.positions = new Float32Array(xrMesh.positions.length);\n for (let i = 0; i < xrMesh.positions.length; i += 3) {\n mesh.positions[i] = xrMesh.positions[i];\n mesh.positions[i + 1] = xrMesh.positions[i + 1];\n mesh.positions[i + 2] = -1 * xrMesh.positions[i + 2];\n }\n if (xrMesh.normals) {\n mesh.normals = new Float32Array(xrMesh.normals.length);\n for (let i = 0; i < xrMesh.normals.length; i += 3) {\n mesh.normals[i] = xrMesh.normals[i];\n mesh.normals[i + 1] = xrMesh.normals[i + 1];\n mesh.normals[i + 2] = -1 * xrMesh.normals[i + 2];\n }\n }\n }\n else {\n mesh.positions = xrMesh.positions;\n mesh.normals = xrMesh.normals;\n }\n // WebXR should provide indices in a counterclockwise winding order regardless of coordinate system handedness\n mesh.indices = xrMesh.indices;\n // matrix\n const pose = xrFrame.getPose(xrMesh.meshSpace, this._xrSessionManager.referenceSpace);\n if (pose) {\n const mat = mesh.transformationMatrix || new Matrix();\n Matrix.FromArrayToRef(pose.transform.matrix, 0, mat);\n if (!this._xrSessionManager.scene.useRightHandedSystem) {\n mat.toggleModelMatrixHandInPlace();\n }\n mesh.transformationMatrix = mat;\n if (this._options.worldParentNode) {\n mat.multiplyToRef(this._options.worldParentNode.getWorldMatrix(), mat);\n }\n }\n }\n return mesh;\n }\n}\n/**\n * The module's name\n */\nWebXRMeshDetector.Name = WebXRFeatureName.MESH_DETECTION;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRMeshDetector.Version = 1;\nWebXRFeaturesManager.AddWebXRFeature(WebXRMeshDetector.Name, (xrSessionManager, options) => {\n return () => new WebXRMeshDetector(xrSessionManager, options);\n}, WebXRMeshDetector.Version, false);\n//# sourceMappingURL=WebXRMeshDetector.js.map","import { WebXRFeaturesManager, WebXRFeatureName } from \"../webXRFeaturesManager.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nimport { Matrix } from \"../../Maths/math.vector.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * Enum that describes the state of the image trackability score status for this session.\n */\nvar ImageTrackingScoreStatus;\n(function (ImageTrackingScoreStatus) {\n // AR Session has not yet assessed image trackability scores.\n ImageTrackingScoreStatus[ImageTrackingScoreStatus[\"NotReceived\"] = 0] = \"NotReceived\";\n // A request to retrieve trackability scores has been sent, but no response has been received.\n ImageTrackingScoreStatus[ImageTrackingScoreStatus[\"Waiting\"] = 1] = \"Waiting\";\n // Image trackability scores have been received for this session\n ImageTrackingScoreStatus[ImageTrackingScoreStatus[\"Received\"] = 2] = \"Received\";\n})(ImageTrackingScoreStatus || (ImageTrackingScoreStatus = {}));\n/**\n * Image tracking for immersive AR sessions.\n * Providing a list of images and their estimated widths will enable tracking those images in the real world.\n */\nexport class WebXRImageTracking extends WebXRAbstractFeature {\n /**\n * constructs the image tracking feature\n * @param _xrSessionManager the session manager for this module\n * @param options read-only options to be used in this module\n */\n constructor(_xrSessionManager, \n /**\n * read-only options to be used in this module\n */\n options) {\n super(_xrSessionManager);\n this.options = options;\n /**\n * This will be triggered if the underlying system deems an image untrackable.\n * The index is the index of the image from the array used to initialize the feature.\n */\n this.onUntrackableImageFoundObservable = new Observable();\n /**\n * An image was deemed trackable, and the system will start tracking it.\n */\n this.onTrackableImageFoundObservable = new Observable();\n /**\n * The image was found and its state was updated.\n */\n this.onTrackedImageUpdatedObservable = new Observable();\n this._trackableScoreStatus = ImageTrackingScoreStatus.NotReceived;\n this._trackedImages = [];\n this.xrNativeFeatureName = \"image-tracking\";\n }\n /**\n * attach this feature\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n attach() {\n return super.attach();\n }\n /**\n * detach this feature.\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n detach() {\n return super.detach();\n }\n /**\n * Get a tracked image by its ID.\n *\n * @param id the id of the image to load (position in the init array)\n * @returns a trackable image, if exists in this location\n */\n getTrackedImageById(id) {\n return this._trackedImages[id] || null;\n }\n /**\n * Dispose this feature and all of the resources attached\n */\n dispose() {\n super.dispose();\n this._trackedImages.forEach((trackedImage) => {\n trackedImage.originalBitmap.close();\n });\n this._trackedImages.length = 0;\n this.onTrackableImageFoundObservable.clear();\n this.onUntrackableImageFoundObservable.clear();\n this.onTrackedImageUpdatedObservable.clear();\n }\n /**\n * Extends the session init object if needed\n * @returns augmentation object fo the xr session init object.\n */\n async getXRSessionInitExtension() {\n if (!this.options.images || !this.options.images.length) {\n return {};\n }\n const promises = this.options.images.map((image) => {\n if (typeof image.src === \"string\") {\n return this._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(image.src);\n }\n else {\n return Promise.resolve(image.src); // resolve is probably unneeded\n }\n });\n try {\n const images = await Promise.all(promises);\n this._originalTrackingRequest = images.map((image, idx) => {\n return {\n image,\n widthInMeters: this.options.images[idx].estimatedRealWorldWidth,\n };\n });\n return {\n trackedImages: this._originalTrackingRequest,\n };\n }\n catch (ex) {\n Tools.Error(\"Error loading images for tracking, WebXRImageTracking disabled for this session.\");\n return {};\n }\n }\n _onXRFrame(_xrFrame) {\n if (!_xrFrame.getImageTrackingResults || this._trackableScoreStatus === ImageTrackingScoreStatus.Waiting) {\n return;\n }\n // Image tracking scores may be generated a few frames after the XR Session initializes.\n // If we haven't received scores yet, then kick off the task to check scores and return immediately.\n if (this._trackableScoreStatus === ImageTrackingScoreStatus.NotReceived) {\n this._checkScoresAsync();\n return;\n }\n const imageTrackedResults = _xrFrame.getImageTrackingResults();\n for (const result of imageTrackedResults) {\n let changed = false;\n const imageIndex = result.index;\n const imageObject = this._trackedImages[imageIndex];\n if (!imageObject) {\n // something went wrong!\n continue;\n }\n imageObject.xrTrackingResult = result;\n if (imageObject.realWorldWidth !== result.measuredWidthInMeters) {\n imageObject.realWorldWidth = result.measuredWidthInMeters;\n changed = true;\n }\n // Get the pose of the image relative to a reference space.\n const pose = _xrFrame.getPose(result.imageSpace, this._xrSessionManager.referenceSpace);\n if (pose) {\n const mat = imageObject.transformationMatrix;\n Matrix.FromArrayToRef(pose.transform.matrix, 0, mat);\n if (!this._xrSessionManager.scene.useRightHandedSystem) {\n mat.toggleModelMatrixHandInPlace();\n }\n changed = true;\n }\n const state = result.trackingState;\n const emulated = state === \"emulated\";\n if (imageObject.emulated !== emulated) {\n imageObject.emulated = emulated;\n changed = true;\n }\n if (changed) {\n this.onTrackedImageUpdatedObservable.notifyObservers(imageObject);\n }\n }\n }\n async _checkScoresAsync() {\n if (!this._xrSessionManager.session.getTrackedImageScores || this._trackableScoreStatus !== ImageTrackingScoreStatus.NotReceived) {\n return;\n }\n this._trackableScoreStatus = ImageTrackingScoreStatus.Waiting;\n const imageScores = await this._xrSessionManager.session.getTrackedImageScores();\n if (!imageScores || imageScores.length === 0) {\n this._trackableScoreStatus = ImageTrackingScoreStatus.NotReceived;\n return;\n }\n // check the scores for all\n for (let idx = 0; idx < imageScores.length; ++idx) {\n if (imageScores[idx] == \"untrackable\") {\n this.onUntrackableImageFoundObservable.notifyObservers(idx);\n }\n else {\n const originalBitmap = this._originalTrackingRequest[idx].image;\n const imageObject = {\n id: idx,\n originalBitmap,\n transformationMatrix: new Matrix(),\n ratio: originalBitmap.width / originalBitmap.height,\n };\n this._trackedImages[idx] = imageObject;\n this.onTrackableImageFoundObservable.notifyObservers(imageObject);\n }\n }\n this._trackableScoreStatus = imageScores.length > 0 ? ImageTrackingScoreStatus.Received : ImageTrackingScoreStatus.NotReceived;\n }\n}\n/**\n * The module's name\n */\nWebXRImageTracking.Name = WebXRFeatureName.IMAGE_TRACKING;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRImageTracking.Version = 1;\n//register the plugin\nWebXRFeaturesManager.AddWebXRFeature(WebXRImageTracking.Name, (xrSessionManager, options) => {\n return () => new WebXRImageTracking(xrSessionManager, options);\n}, WebXRImageTracking.Version, false);\n//# sourceMappingURL=WebXRImageTracking.js.map","import { Tools } from \"../../Misc/tools.js\";\nimport { WebXRFeatureName, WebXRFeaturesManager } from \"../webXRFeaturesManager.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\n/**\n * DOM Overlay Feature\n *\n * @since 5.0.0\n */\nexport class WebXRDomOverlay extends WebXRAbstractFeature {\n /**\n * Creates a new instance of the dom-overlay feature\n * @param _xrSessionManager an instance of WebXRSessionManager\n * @param options options to use when constructing this feature\n */\n constructor(_xrSessionManager, \n /**\n * options to use when constructing this feature\n */\n options) {\n super(_xrSessionManager);\n this.options = options;\n /**\n * Type of overlay - non-null when available\n */\n this._domOverlayType = null;\n /**\n * Event Listener to supress \"beforexrselect\" events.\n */\n this._beforeXRSelectListener = null;\n /**\n * Element used for overlay\n */\n this._element = null;\n this.xrNativeFeatureName = \"dom-overlay\";\n // https://immersive-web.github.io/dom-overlays/\n Tools.Warn(\"dom-overlay is an experimental and unstable feature.\");\n }\n /**\n * attach this feature\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n attach() {\n if (!super.attach()) {\n return false;\n }\n // Feature not available\n if (!this._xrSessionManager.session.domOverlayState || this._xrSessionManager.session.domOverlayState.type === null) {\n return false;\n }\n this._domOverlayType = this._xrSessionManager.session.domOverlayState.type;\n if (this._element !== null && this.options.supressXRSelectEvents === true) {\n this._beforeXRSelectListener = (ev) => {\n ev.preventDefault();\n };\n this._element.addEventListener(\"beforexrselect\", this._beforeXRSelectListener);\n }\n return true;\n }\n /**\n * The type of DOM overlay (null when not supported). Provided by UA and remains unchanged for duration of session.\n */\n get domOverlayType() {\n return this._domOverlayType;\n }\n /**\n * Dispose this feature and all of the resources attached\n */\n dispose() {\n super.dispose();\n if (this._element !== null && this._beforeXRSelectListener) {\n this._element.removeEventListener(\"beforexrselect\", this._beforeXRSelectListener);\n }\n }\n _onXRFrame(_xrFrame) {\n /* empty */\n }\n /**\n * Extends the session init object if needed\n * @returns augmentation object for the xr session init object.\n */\n async getXRSessionInitExtension() {\n if (this.options.element === undefined) {\n Tools.Warn('\"element\" option must be provided to attach xr-dom-overlay feature.');\n return {};\n }\n else if (typeof this.options.element === \"string\") {\n const selectedElement = document.querySelector(this.options.element);\n if (selectedElement === null) {\n Tools.Warn(`element not found '${this.options.element}' (not requesting xr-dom-overlay)`);\n return {};\n }\n this._element = selectedElement;\n }\n else {\n this._element = this.options.element;\n }\n return {\n domOverlay: {\n root: this._element,\n },\n };\n }\n}\n/**\n * The module's name\n */\nWebXRDomOverlay.Name = WebXRFeatureName.DOM_OVERLAY;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRDomOverlay.Version = 1;\n//register the plugin\nWebXRFeaturesManager.AddWebXRFeature(WebXRDomOverlay.Name, (xrSessionManager, options) => {\n return () => new WebXRDomOverlay(xrSessionManager, options);\n}, WebXRDomOverlay.Version, false);\n//# sourceMappingURL=WebXRDOMOverlay.js.map","import { WebXRFeaturesManager, WebXRFeatureName } from \"../webXRFeaturesManager.js\";\nimport { WebXRControllerComponent } from \"../motionController/webXRControllerComponent.js\";\nimport { Matrix, Quaternion, Vector3 } from \"../../Maths/math.vector.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nimport { Tools } from \"../../Misc/tools.js\";\n/**\n * This is a movement feature to be used with WebXR-enabled motion controllers.\n * When enabled and attached, the feature will allow a user to move around and rotate in the scene using\n * the input of the attached controllers.\n */\nexport class WebXRControllerMovement extends WebXRAbstractFeature {\n /**\n * Current movement direction. Will be null before XR Frames have been processed.\n */\n get movementDirection() {\n return this._movementDirection;\n }\n /**\n * Is movement enabled\n */\n get movementEnabled() {\n return this._featureContext.movementEnabled;\n }\n /**\n * Sets whether movement is enabled or not\n * @param enabled is movement enabled\n */\n set movementEnabled(enabled) {\n this._featureContext.movementEnabled = enabled;\n }\n /**\n * If movement follows viewer pose\n */\n get movementOrientationFollowsViewerPose() {\n return this._featureContext.movementOrientationFollowsViewerPose;\n }\n /**\n * Sets whether movement follows viewer pose\n * @param followsPose is movement should follow viewer pose\n */\n set movementOrientationFollowsViewerPose(followsPose) {\n this._featureContext.movementOrientationFollowsViewerPose = followsPose;\n }\n /**\n * Gets movement speed\n */\n get movementSpeed() {\n return this._featureContext.movementSpeed;\n }\n /**\n * Sets movement speed\n * @param movementSpeed movement speed\n */\n set movementSpeed(movementSpeed) {\n this._featureContext.movementSpeed = movementSpeed;\n }\n /**\n * Gets minimum threshold the controller's thumbstick/touchpad must pass before being recognized for movement (avoids jitter/unintentional movement)\n */\n get movementThreshold() {\n return this._featureContext.movementThreshold;\n }\n /**\n * Sets minimum threshold the controller's thumbstick/touchpad must pass before being recognized for movement (avoids jitter/unintentional movement)\n * @param movementThreshold new threshold\n */\n set movementThreshold(movementThreshold) {\n this._featureContext.movementThreshold = movementThreshold;\n }\n /**\n * Is rotation enabled\n */\n get rotationEnabled() {\n return this._featureContext.rotationEnabled;\n }\n /**\n * Sets whether rotation is enabled or not\n * @param enabled is rotation enabled\n */\n set rotationEnabled(enabled) {\n this._featureContext.rotationEnabled = enabled;\n }\n /**\n * Gets rotation speed factor\n */\n get rotationSpeed() {\n return this._featureContext.rotationSpeed;\n }\n /**\n * Sets rotation speed factor (1.0 is default)\n * @param rotationSpeed new rotation speed factor\n */\n set rotationSpeed(rotationSpeed) {\n this._featureContext.rotationSpeed = rotationSpeed;\n }\n /**\n * Gets minimum threshold the controller's thumbstick/touchpad must pass before being recognized for rotation (avoids jitter/unintentional rotation)\n */\n get rotationThreshold() {\n return this._featureContext.rotationThreshold;\n }\n /**\n * Sets minimum threshold the controller's thumbstick/touchpad must pass before being recognized for rotation (avoids jitter/unintentional rotation)\n * @param threshold new threshold\n */\n set rotationThreshold(threshold) {\n this._featureContext.rotationThreshold = threshold;\n }\n /**\n * constructs a new movement controller system\n * @param _xrSessionManager an instance of WebXRSessionManager\n * @param options configuration object for this feature\n */\n constructor(_xrSessionManager, options) {\n var _a, _b, _c, _d, _e, _f;\n super(_xrSessionManager);\n this._controllers = {};\n this._currentRegistrationConfigurations = [];\n // forward direction for movement, which may differ from viewer pose.\n this._movementDirection = null;\n // unused\n this._tmpRotationMatrix = Matrix.Identity();\n this._tmpTranslationDirection = new Vector3();\n this._tmpMovementTranslation = new Vector3();\n this._attachController = (xrController) => {\n if (this._controllers[xrController.uniqueId]) {\n // already attached\n return;\n }\n this._controllers[xrController.uniqueId] = {\n xrController,\n registeredComponents: [],\n };\n const controllerData = this._controllers[xrController.uniqueId];\n // movement controller only available to gamepad-enabled input sources.\n if (controllerData.xrController.inputSource.targetRayMode === \"tracked-pointer\" && controllerData.xrController.inputSource.gamepad) {\n // motion controller support\n const initController = () => {\n if (xrController.motionController) {\n for (const registration of this._currentRegistrationConfigurations) {\n let component = null;\n if (registration.allowedComponentTypes) {\n for (const componentType of registration.allowedComponentTypes) {\n const componentOfType = xrController.motionController.getComponentOfType(componentType);\n if (componentOfType !== null) {\n component = componentOfType;\n break;\n }\n }\n }\n if (registration.mainComponentOnly) {\n const mainComponent = xrController.motionController.getMainComponent();\n if (mainComponent === null) {\n continue;\n }\n component = mainComponent;\n }\n if (typeof registration.componentSelectionPredicate === \"function\") {\n // if does not match we do want to ignore a previously found component\n component = registration.componentSelectionPredicate(xrController);\n }\n if (component && registration.forceHandedness) {\n if (xrController.inputSource.handedness !== registration.forceHandedness) {\n continue; // do not register\n }\n }\n if (component === null) {\n continue; // do not register\n }\n const registeredComponent = {\n registrationConfiguration: registration,\n component,\n };\n controllerData.registeredComponents.push(registeredComponent);\n if (\"axisChangedHandler\" in registration) {\n registeredComponent.onAxisChangedObserver = component.onAxisValueChangedObservable.add((axesData) => {\n registration.axisChangedHandler(axesData, this._movementState, this._featureContext, this._xrInput);\n });\n }\n if (\"buttonChangedhandler\" in registration) {\n registeredComponent.onButtonChangedObserver = component.onButtonStateChangedObservable.add(() => {\n if (component.changes.pressed) {\n registration.buttonChangedhandler(component.changes.pressed, this._movementState, this._featureContext, this._xrInput);\n }\n });\n }\n }\n }\n };\n if (xrController.motionController) {\n initController();\n }\n else {\n xrController.onMotionControllerInitObservable.addOnce(() => {\n initController();\n });\n }\n }\n };\n if (!options || options.xrInput === undefined) {\n Tools.Error('WebXRControllerMovement feature requires \"xrInput\" option.');\n return;\n }\n if (Array.isArray(options.customRegistrationConfigurations)) {\n this._currentRegistrationConfigurations = options.customRegistrationConfigurations;\n }\n else {\n this._currentRegistrationConfigurations = WebXRControllerMovement.REGISTRATIONS.default;\n }\n // synchronized from feature setter properties\n this._featureContext = {\n movementEnabled: options.movementEnabled || true,\n movementOrientationFollowsViewerPose: (_a = options.movementOrientationFollowsViewerPose) !== null && _a !== void 0 ? _a : true,\n movementSpeed: (_b = options.movementSpeed) !== null && _b !== void 0 ? _b : 1,\n movementThreshold: (_c = options.movementThreshold) !== null && _c !== void 0 ? _c : 0.25,\n rotationEnabled: (_d = options.rotationEnabled) !== null && _d !== void 0 ? _d : true,\n rotationSpeed: (_e = options.rotationSpeed) !== null && _e !== void 0 ? _e : 1.0,\n rotationThreshold: (_f = options.rotationThreshold) !== null && _f !== void 0 ? _f : 0.25,\n };\n this._movementState = {\n moveX: 0,\n moveY: 0,\n rotateX: 0,\n rotateY: 0,\n };\n this._xrInput = options.xrInput;\n }\n attach() {\n if (!super.attach()) {\n return false;\n }\n this._xrInput.controllers.forEach(this._attachController);\n this._addNewAttachObserver(this._xrInput.onControllerAddedObservable, this._attachController);\n this._addNewAttachObserver(this._xrInput.onControllerRemovedObservable, (controller) => {\n // REMOVE the controller\n this._detachController(controller.uniqueId);\n });\n return true;\n }\n detach() {\n if (!super.detach()) {\n return false;\n }\n Object.keys(this._controllers).forEach((controllerId) => {\n this._detachController(controllerId);\n });\n this._controllers = {};\n return true;\n }\n /**\n * Occurs on every XR frame.\n * @param _xrFrame\n */\n _onXRFrame(_xrFrame) {\n if (!this.attach) {\n return;\n }\n if (this._movementDirection === null) {\n this._movementDirection = this._xrInput.xrCamera.rotationQuaternion.clone();\n }\n if (this._movementState.rotateX !== 0 && this._featureContext.rotationEnabled) {\n // smooth rotation\n const deltaMillis = this._xrSessionManager.scene.getEngine().getDeltaTime();\n const rotationY = deltaMillis * 0.001 * this._featureContext.rotationSpeed * this._movementState.rotateX * (this._xrSessionManager.scene.useRightHandedSystem ? -1 : 1);\n if (this._featureContext.movementOrientationFollowsViewerPose === true) {\n this._xrInput.xrCamera.cameraRotation.y += rotationY;\n this._movementDirection = this._xrInput.xrCamera.rotationQuaternion.multiply(Quaternion.RotationYawPitchRoll(rotationY, 0, 0));\n }\n else {\n // movement orientation direction does not affect camera. We use rotation speed multiplier\n // otherwise need to implement inertia and constraints for same feel as TargetCamera.\n this._movementDirection.multiplyInPlace(Quaternion.RotationYawPitchRoll(rotationY * 3.0, 0, 0));\n }\n }\n else if (this._featureContext.movementOrientationFollowsViewerPose === true) {\n this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion);\n }\n if ((this._movementState.moveX !== 0 || this._movementState.moveY !== 0) && this._featureContext.movementEnabled) {\n Matrix.FromQuaternionToRef(this._movementDirection, this._tmpRotationMatrix);\n this._tmpTranslationDirection.set(this._movementState.moveX, 0, this._movementState.moveY * (this._xrSessionManager.scene.useRightHandedSystem ? 1.0 : -1.0));\n // move according to forward direction based on camera speed\n Vector3.TransformCoordinatesToRef(this._tmpTranslationDirection, this._tmpRotationMatrix, this._tmpMovementTranslation);\n this._tmpMovementTranslation.scaleInPlace(this._xrInput.xrCamera._computeLocalCameraSpeed() * this._featureContext.movementSpeed);\n this._xrInput.xrCamera.cameraDirection.addInPlace(this._tmpMovementTranslation);\n }\n }\n _detachController(xrControllerUniqueId) {\n const controllerData = this._controllers[xrControllerUniqueId];\n if (!controllerData) {\n return;\n }\n for (const registeredComponent of controllerData.registeredComponents) {\n if (registeredComponent.onAxisChangedObserver) {\n registeredComponent.component.onAxisValueChangedObservable.remove(registeredComponent.onAxisChangedObserver);\n }\n if (registeredComponent.onButtonChangedObserver) {\n registeredComponent.component.onButtonStateChangedObservable.remove(registeredComponent.onButtonChangedObserver);\n }\n }\n // remove from the map\n delete this._controllers[xrControllerUniqueId];\n }\n}\n/**\n * The module's name\n */\nWebXRControllerMovement.Name = WebXRFeatureName.MOVEMENT;\n/**\n * Standard controller configurations.\n */\nWebXRControllerMovement.REGISTRATIONS = {\n default: [\n {\n allowedComponentTypes: [WebXRControllerComponent.THUMBSTICK_TYPE, WebXRControllerComponent.TOUCHPAD_TYPE],\n forceHandedness: \"left\",\n axisChangedHandler: (axes, movementState, featureContext) => {\n movementState.rotateX = Math.abs(axes.x) > featureContext.rotationThreshold ? axes.x : 0;\n movementState.rotateY = Math.abs(axes.y) > featureContext.rotationThreshold ? axes.y : 0;\n },\n },\n {\n allowedComponentTypes: [WebXRControllerComponent.THUMBSTICK_TYPE, WebXRControllerComponent.TOUCHPAD_TYPE],\n forceHandedness: \"right\",\n axisChangedHandler: (axes, movementState, featureContext) => {\n movementState.moveX = Math.abs(axes.x) > featureContext.movementThreshold ? axes.x : 0;\n movementState.moveY = Math.abs(axes.y) > featureContext.movementThreshold ? axes.y : 0;\n },\n },\n ],\n};\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the webxr specs version\n */\nWebXRControllerMovement.Version = 1;\nWebXRFeaturesManager.AddWebXRFeature(WebXRControllerMovement.Name, (xrSessionManager, options) => {\n return () => new WebXRControllerMovement(xrSessionManager, options);\n}, WebXRControllerMovement.Version, true);\n//# sourceMappingURL=WebXRControllerMovement.js.map","import { WebGLHardwareTexture } from \"../../Engines/WebGL/webGLHardwareTexture.js\";\nimport { InternalTexture, InternalTextureSource } from \"../../Materials/Textures/internalTexture.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { Tools } from \"../../Misc/tools.js\";\nimport { WebXRFeatureName, WebXRFeaturesManager } from \"../webXRFeaturesManager.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\n\nimport { Color3 } from \"../../Maths/math.color.js\";\nimport { Vector3 } from \"../../Maths/math.vector.js\";\nimport { DirectionalLight } from \"../../Lights/directionalLight.js\";\nimport { BaseTexture } from \"../../Materials/Textures/baseTexture.js\";\nimport { SphericalHarmonics, SphericalPolynomial } from \"../../Maths/sphericalPolynomial.js\";\nimport { LightConstants } from \"../../Lights/lightConstants.js\";\n/**\n * Light Estimation Feature\n *\n * @since 5.0.0\n */\nexport class WebXRLightEstimation extends WebXRAbstractFeature {\n /**\n * Creates a new instance of the light estimation feature\n * @param _xrSessionManager an instance of WebXRSessionManager\n * @param options options to use when constructing this feature\n */\n constructor(_xrSessionManager, \n /**\n * options to use when constructing this feature\n */\n options) {\n super(_xrSessionManager);\n this.options = options;\n this._canvasContext = null;\n this._reflectionCubeMap = null;\n this._xrLightEstimate = null;\n this._xrLightProbe = null;\n this._xrWebGLBinding = null;\n this._lightDirection = Vector3.Up().negateInPlace();\n this._lightColor = Color3.White();\n this._intensity = 1;\n this._sphericalHarmonics = new SphericalHarmonics();\n this._cubeMapPollTime = Date.now();\n this._lightEstimationPollTime = Date.now();\n /**\n * ARCore's reflection cube map size is 16x16.\n * Once other systems support this feature we will need to change this to be dynamic.\n * see https://github.com/immersive-web/lighting-estimation/blob/main/lighting-estimation-explainer.md#cube-map-open-questions\n */\n this._reflectionCubeMapTextureSize = 16;\n /**\n * If createDirectionalLightSource is set to true this light source will be created automatically.\n * Otherwise this can be set with an external directional light source.\n * This light will be updated whenever the light estimation values change.\n */\n this.directionalLight = null;\n /**\n * This observable will notify when the reflection cube map is updated.\n */\n this.onReflectionCubeMapUpdatedObservable = new Observable();\n /**\n * Event Listener for \"reflectionchange\" events.\n */\n this._updateReflectionCubeMap = () => {\n var _a;\n if (!this._xrLightProbe) {\n return;\n }\n // check poll time, do not update if it has not been long enough\n if (this.options.cubeMapPollInterval) {\n const now = Date.now();\n if (now - this._cubeMapPollTime < this.options.cubeMapPollInterval) {\n return;\n }\n this._cubeMapPollTime = now;\n }\n const lp = this._getXRGLBinding().getReflectionCubeMap(this._xrLightProbe);\n if (lp && this._reflectionCubeMap) {\n if (!this._reflectionCubeMap._texture) {\n const internalTexture = new InternalTexture(this._xrSessionManager.scene.getEngine(), InternalTextureSource.Unknown);\n internalTexture.isCube = true;\n internalTexture.invertY = false;\n internalTexture._useSRGBBuffer = this.options.reflectionFormat === \"srgba8\";\n internalTexture.format = 5;\n internalTexture.generateMipMaps = true;\n internalTexture.type = this.options.reflectionFormat !== \"srgba8\" ? 2 : 0;\n internalTexture.samplingMode = 3;\n internalTexture.width = this._reflectionCubeMapTextureSize;\n internalTexture.height = this._reflectionCubeMapTextureSize;\n internalTexture._cachedWrapU = 1;\n internalTexture._cachedWrapV = 1;\n internalTexture._hardwareTexture = new WebGLHardwareTexture(lp, this._getCanvasContext());\n this._reflectionCubeMap._texture = internalTexture;\n }\n else {\n (_a = this._reflectionCubeMap._texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.set(lp);\n this._reflectionCubeMap._texture.getEngine().resetTextureCache();\n }\n this._reflectionCubeMap._texture.isReady = true;\n this._xrSessionManager.scene.markAllMaterialsAsDirty(1);\n this.onReflectionCubeMapUpdatedObservable.notifyObservers(this._reflectionCubeMap);\n }\n };\n this.xrNativeFeatureName = \"light-estimation\";\n if (this.options.createDirectionalLightSource) {\n this.directionalLight = new DirectionalLight(\"light estimation directional\", this._lightDirection, this._xrSessionManager.scene);\n this.directionalLight.position = new Vector3(0, 8, 0);\n // intensity will be set later\n this.directionalLight.intensity = 0;\n this.directionalLight.falloffType = LightConstants.FALLOFF_GLTF;\n }\n // https://immersive-web.github.io/lighting-estimation/\n Tools.Warn(\"light-estimation is an experimental and unstable feature.\");\n }\n /**\n * While the estimated cube map is expected to update over time to better reflect the user's environment as they move around those changes are unlikely to happen with every XRFrame.\n * Since creating and processing the cube map is potentially expensive, especially if mip maps are needed, you can listen to the onReflectionCubeMapUpdatedObservable to determine\n * when it has been updated.\n */\n get reflectionCubeMapTexture() {\n return this._reflectionCubeMap;\n }\n /**\n * The most recent light estimate. Available starting on the first frame where the device provides a light probe.\n */\n get xrLightingEstimate() {\n if (this._xrLightEstimate) {\n return {\n lightColor: this._lightColor,\n lightDirection: this._lightDirection,\n lightIntensity: this._intensity,\n sphericalHarmonics: this._sphericalHarmonics,\n };\n }\n return this._xrLightEstimate;\n }\n _getCanvasContext() {\n if (this._canvasContext === null) {\n this._canvasContext = this._xrSessionManager.scene.getEngine()._gl;\n }\n return this._canvasContext;\n }\n _getXRGLBinding() {\n if (this._xrWebGLBinding === null) {\n const context = this._getCanvasContext();\n this._xrWebGLBinding = new XRWebGLBinding(this._xrSessionManager.session, context);\n }\n return this._xrWebGLBinding;\n }\n /**\n * attach this feature\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n attach() {\n var _a;\n if (!super.attach()) {\n return false;\n }\n const reflectionFormat = (_a = this.options.reflectionFormat) !== null && _a !== void 0 ? _a : (this._xrSessionManager.session.preferredReflectionFormat || \"srgba8\");\n this.options.reflectionFormat = reflectionFormat;\n this._xrSessionManager.session\n .requestLightProbe({\n reflectionFormat,\n })\n .then((xrLightProbe) => {\n this._xrLightProbe = xrLightProbe;\n if (!this.options.disableCubeMapReflection) {\n if (!this._reflectionCubeMap) {\n this._reflectionCubeMap = new BaseTexture(this._xrSessionManager.scene);\n this._reflectionCubeMap._isCube = true;\n this._reflectionCubeMap.coordinatesMode = 3;\n if (this.options.setSceneEnvironmentTexture) {\n this._xrSessionManager.scene.environmentTexture = this._reflectionCubeMap;\n }\n }\n this._xrLightProbe.addEventListener(\"reflectionchange\", this._updateReflectionCubeMap);\n }\n });\n return true;\n }\n /**\n * detach this feature.\n * Will usually be called by the features manager\n *\n * @returns true if successful.\n */\n detach() {\n const detached = super.detach();\n if (this._xrLightProbe !== null && !this.options.disableCubeMapReflection) {\n this._xrLightProbe.removeEventListener(\"reflectionchange\", this._updateReflectionCubeMap);\n this._xrLightProbe = null;\n }\n this._canvasContext = null;\n this._xrLightEstimate = null;\n // When the session ends (on detach) we must clear our XRWebGLBinging instance, which references the ended session.\n this._xrWebGLBinding = null;\n return detached;\n }\n /**\n * Dispose this feature and all of the resources attached\n */\n dispose() {\n super.dispose();\n this.onReflectionCubeMapUpdatedObservable.clear();\n if (this.directionalLight) {\n this.directionalLight.dispose();\n this.directionalLight = null;\n }\n if (this._reflectionCubeMap !== null) {\n if (this._reflectionCubeMap._texture) {\n this._reflectionCubeMap._texture.dispose();\n }\n this._reflectionCubeMap.dispose();\n this._reflectionCubeMap = null;\n }\n }\n _onXRFrame(_xrFrame) {\n var _a;\n if (this._xrLightProbe !== null) {\n if (this.options.lightEstimationPollInterval) {\n const now = Date.now();\n if (now - this._lightEstimationPollTime < this.options.lightEstimationPollInterval) {\n return;\n }\n this._lightEstimationPollTime = now;\n }\n this._xrLightEstimate = _xrFrame.getLightEstimate(this._xrLightProbe);\n if (this._xrLightEstimate) {\n this._intensity = Math.max(1.0, this._xrLightEstimate.primaryLightIntensity.x, this._xrLightEstimate.primaryLightIntensity.y, this._xrLightEstimate.primaryLightIntensity.z);\n const rhsFactor = this._xrSessionManager.scene.useRightHandedSystem ? 1.0 : -1.0;\n // recreate the vector caches, so that the last one provided to the user will persist\n if (this.options.disableVectorReuse) {\n this._lightDirection = new Vector3();\n this._lightColor = new Color3();\n if (this.directionalLight) {\n this.directionalLight.direction = this._lightDirection;\n this.directionalLight.diffuse = this._lightColor;\n }\n }\n this._lightDirection.copyFromFloats(this._xrLightEstimate.primaryLightDirection.x, this._xrLightEstimate.primaryLightDirection.y, this._xrLightEstimate.primaryLightDirection.z * rhsFactor);\n this._lightColor.copyFromFloats(this._xrLightEstimate.primaryLightIntensity.x / this._intensity, this._xrLightEstimate.primaryLightIntensity.y / this._intensity, this._xrLightEstimate.primaryLightIntensity.z / this._intensity);\n this._sphericalHarmonics.updateFromFloatsArray(this._xrLightEstimate.sphericalHarmonicsCoefficients);\n if (this._reflectionCubeMap && !this.options.disableSphericalPolynomial) {\n this._reflectionCubeMap.sphericalPolynomial = this._reflectionCubeMap.sphericalPolynomial || new SphericalPolynomial();\n (_a = this._reflectionCubeMap.sphericalPolynomial) === null || _a === void 0 ? void 0 : _a.updateFromHarmonics(this._sphericalHarmonics);\n }\n // direction from instead of direction to\n this._lightDirection.negateInPlace();\n // set the values after calculating them\n if (this.directionalLight) {\n this.directionalLight.direction.copyFrom(this._lightDirection);\n this.directionalLight.intensity = Math.min(this._intensity, 1.0);\n this.directionalLight.diffuse.copyFrom(this._lightColor);\n }\n }\n }\n }\n}\n/**\n * The module's name\n */\nWebXRLightEstimation.Name = WebXRFeatureName.LIGHT_ESTIMATION;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRLightEstimation.Version = 1;\n// register the plugin\nWebXRFeaturesManager.AddWebXRFeature(WebXRLightEstimation.Name, (xrSessionManager, options) => {\n return () => new WebXRLightEstimation(xrSessionManager, options);\n}, WebXRLightEstimation.Version, false);\n//# sourceMappingURL=WebXRLightEstimation.js.map","import { TmpVectors, Vector2, Vector3 } from \"../../Maths/math.vector.js\";\nimport { Logger } from \"../../Misc/logger.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { WebXRFeatureName, WebXRFeaturesManager } from \"../webXRFeaturesManager.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nclass CircleBuffer {\n constructor(numSamples, initializer) {\n this._samples = [];\n this._idx = 0;\n for (let idx = 0; idx < numSamples; ++idx) {\n this._samples.push(initializer ? initializer() : Vector2.Zero());\n }\n }\n get length() {\n return this._samples.length;\n }\n push(x, y) {\n this._idx = (this._idx + this._samples.length - 1) % this._samples.length;\n this.at(0).copyFromFloats(x, y);\n }\n at(idx) {\n if (idx >= this._samples.length) {\n throw new Error(\"Index out of bounds\");\n }\n return this._samples[(this._idx + idx) % this._samples.length];\n }\n}\nclass FirstStepDetector {\n constructor() {\n this._samples = new CircleBuffer(20);\n this._entropy = 0;\n this.onFirstStepDetected = new Observable();\n }\n update(posX, posY, forwardX, forwardY) {\n this._samples.push(posX, posY);\n const origin = this._samples.at(0);\n this._entropy *= this._entropyDecayFactor;\n this._entropy += Vector2.Distance(origin, this._samples.at(1));\n if (this._entropy > this._entropyThreshold) {\n return;\n }\n let samePointIdx;\n for (samePointIdx = this._samePointCheckStartIdx; samePointIdx < this._samples.length; ++samePointIdx) {\n if (Vector2.DistanceSquared(origin, this._samples.at(samePointIdx)) < this._samePointSquaredDistanceThreshold) {\n break;\n }\n }\n if (samePointIdx === this._samples.length) {\n return;\n }\n let apexDistSquared = -1;\n let apexIdx = 0;\n for (let distSquared, idx = 1; idx < samePointIdx; ++idx) {\n distSquared = Vector2.DistanceSquared(origin, this._samples.at(idx));\n if (distSquared > apexDistSquared) {\n apexIdx = idx;\n apexDistSquared = distSquared;\n }\n }\n if (apexDistSquared < this._apexSquaredDistanceThreshold) {\n return;\n }\n const apex = this._samples.at(apexIdx);\n const axis = apex.subtract(origin);\n axis.normalize();\n const vec = TmpVectors.Vector2[0];\n let dot;\n let sample;\n let sumSquaredProjectionDistances = 0;\n for (let idx = 1; idx < samePointIdx; ++idx) {\n sample = this._samples.at(idx);\n sample.subtractToRef(origin, vec);\n dot = Vector2.Dot(axis, vec);\n sumSquaredProjectionDistances += vec.lengthSquared() - dot * dot;\n }\n if (sumSquaredProjectionDistances > samePointIdx * this._squaredProjectionDistanceThreshold) {\n return;\n }\n const forwardVec = TmpVectors.Vector3[0];\n forwardVec.set(forwardX, forwardY, 0);\n const axisVec = TmpVectors.Vector3[1];\n axisVec.set(axis.x, axis.y, 0);\n const isApexLeft = Vector3.Cross(forwardVec, axisVec).z > 0;\n const leftApex = origin.clone();\n const rightApex = origin.clone();\n apex.subtractToRef(origin, axis);\n if (isApexLeft) {\n axis.scaleAndAddToRef(this._axisToApexShrinkFactor, leftApex);\n axis.scaleAndAddToRef(this._axisToApexExtendFactor, rightApex);\n }\n else {\n axis.scaleAndAddToRef(this._axisToApexExtendFactor, leftApex);\n axis.scaleAndAddToRef(this._axisToApexShrinkFactor, rightApex);\n }\n this.onFirstStepDetected.notifyObservers({\n leftApex: leftApex,\n rightApex: rightApex,\n currentPosition: origin,\n currentStepDirection: isApexLeft ? \"right\" : \"left\",\n });\n }\n reset() {\n for (let idx = 0; idx < this._samples.length; ++idx) {\n this._samples.at(idx).copyFromFloats(0, 0);\n }\n }\n get _samePointCheckStartIdx() {\n return Math.floor(this._samples.length / 3);\n }\n get _samePointSquaredDistanceThreshold() {\n return 0.03 * 0.03;\n }\n get _apexSquaredDistanceThreshold() {\n return 0.09 * 0.09;\n }\n get _squaredProjectionDistanceThreshold() {\n return 0.03 * 0.03;\n }\n get _axisToApexShrinkFactor() {\n return 0.8;\n }\n get _axisToApexExtendFactor() {\n return -1.6;\n }\n get _entropyDecayFactor() {\n return 0.93;\n }\n get _entropyThreshold() {\n return 0.4;\n }\n}\nclass WalkingTracker {\n constructor(leftApex, rightApex, currentPosition, currentStepDirection) {\n this._leftApex = new Vector2();\n this._rightApex = new Vector2();\n this._currentPosition = new Vector2();\n this._axis = new Vector2();\n this._axisLength = -1;\n this._forward = new Vector2();\n this._steppingLeft = false;\n this._t = -1;\n this._maxT = -1;\n this._maxTPosition = new Vector2();\n this._vitality = 0;\n this.onMovement = new Observable();\n this.onFootfall = new Observable();\n this._reset(leftApex, rightApex, currentPosition, currentStepDirection === \"left\");\n }\n _reset(leftApex, rightApex, currentPosition, steppingLeft) {\n this._leftApex.copyFrom(leftApex);\n this._rightApex.copyFrom(rightApex);\n this._steppingLeft = steppingLeft;\n if (this._steppingLeft) {\n this._leftApex.subtractToRef(this._rightApex, this._axis);\n this._forward.copyFromFloats(-this._axis.y, this._axis.x);\n }\n else {\n this._rightApex.subtractToRef(this._leftApex, this._axis);\n this._forward.copyFromFloats(this._axis.y, -this._axis.x);\n }\n this._axisLength = this._axis.length();\n this._forward.scaleInPlace(1 / this._axisLength);\n this._updateTAndVitality(currentPosition.x, currentPosition.y);\n this._maxT = this._t;\n this._maxTPosition.copyFrom(currentPosition);\n this._vitality = 1;\n }\n _updateTAndVitality(x, y) {\n this._currentPosition.copyFromFloats(x, y);\n if (this._steppingLeft) {\n this._currentPosition.subtractInPlace(this._rightApex);\n }\n else {\n this._currentPosition.subtractInPlace(this._leftApex);\n }\n const priorT = this._t;\n const dot = Vector2.Dot(this._currentPosition, this._axis);\n this._t = dot / (this._axisLength * this._axisLength);\n const projDistSquared = this._currentPosition.lengthSquared() - (dot / this._axisLength) * (dot / this._axisLength);\n // TODO: Extricate the magic.\n this._vitality *= 0.92 - 100 * Math.max(projDistSquared - 0.0016, 0) + Math.max(this._t - priorT, 0);\n }\n update(x, y) {\n if (this._vitality < this._vitalityThreshold) {\n return false;\n }\n const priorT = this._t;\n this._updateTAndVitality(x, y);\n if (this._t > this._maxT) {\n this._maxT = this._t;\n this._maxTPosition.copyFromFloats(x, y);\n }\n if (this._vitality < this._vitalityThreshold) {\n return false;\n }\n if (this._t > priorT) {\n this.onMovement.notifyObservers({ deltaT: this._t - priorT });\n if (priorT < 0.5 && this._t >= 0.5) {\n this.onFootfall.notifyObservers({ foot: this._steppingLeft ? \"left\" : \"right\" });\n }\n }\n if (this._t < 0.95 * this._maxT) {\n this._currentPosition.copyFromFloats(x, y);\n if (this._steppingLeft) {\n this._leftApex.copyFrom(this._maxTPosition);\n }\n else {\n this._rightApex.copyFrom(this._maxTPosition);\n }\n this._reset(this._leftApex, this._rightApex, this._currentPosition, !this._steppingLeft);\n }\n if (this._axisLength < 0.03) {\n return false;\n }\n return true;\n }\n get _vitalityThreshold() {\n return 0.1;\n }\n get forward() {\n return this._forward;\n }\n}\nclass Walker {\n static get _MillisecondsPerUpdate() {\n // 15 FPS\n return 1000 / 15;\n }\n constructor(engine) {\n this._detector = new FirstStepDetector();\n this._walker = null;\n this._movement = new Vector2();\n this._millisecondsSinceLastUpdate = Walker._MillisecondsPerUpdate;\n this.movementThisFrame = Vector3.Zero();\n this._engine = engine;\n this._detector.onFirstStepDetected.add((event) => {\n if (!this._walker) {\n this._walker = new WalkingTracker(event.leftApex, event.rightApex, event.currentPosition, event.currentStepDirection);\n this._walker.onFootfall.add(() => {\n console.log(\"Footfall!\");\n });\n this._walker.onMovement.add((event) => {\n this._walker.forward.scaleAndAddToRef(0.024 * event.deltaT, this._movement);\n });\n }\n });\n }\n update(position, forward) {\n forward.y = 0;\n forward.normalize();\n // Enforce reduced framerate\n this._millisecondsSinceLastUpdate += this._engine.getDeltaTime();\n if (this._millisecondsSinceLastUpdate >= Walker._MillisecondsPerUpdate) {\n this._millisecondsSinceLastUpdate -= Walker._MillisecondsPerUpdate;\n this._detector.update(position.x, position.z, forward.x, forward.z);\n if (this._walker) {\n const updated = this._walker.update(position.x, position.z);\n if (!updated) {\n this._walker = null;\n }\n }\n this._movement.scaleInPlace(0.85);\n }\n this.movementThisFrame.set(this._movement.x, 0, this._movement.y);\n }\n}\n/**\n * A module that will enable VR locomotion by detecting when the user walks in place.\n */\nexport class WebXRWalkingLocomotion extends WebXRAbstractFeature {\n /**\n * The module's name.\n */\n static get Name() {\n return WebXRFeatureName.WALKING_LOCOMOTION;\n }\n /**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number has no external basis.\n */\n static get Version() {\n return 1;\n }\n /**\n * The target to be articulated by walking locomotion.\n * When the walking locomotion feature detects walking in place, this element's\n * X and Z coordinates will be modified to reflect locomotion. This target should\n * be either the XR space's origin (i.e., the parent node of the WebXRCamera) or\n * the WebXRCamera itself. Note that the WebXRCamera path will modify the position\n * of the WebXRCamera directly and is thus discouraged.\n */\n get locomotionTarget() {\n return this._locomotionTarget;\n }\n /**\n * The target to be articulated by walking locomotion.\n * When the walking locomotion feature detects walking in place, this element's\n * X and Z coordinates will be modified to reflect locomotion. This target should\n * be either the XR space's origin (i.e., the parent node of the WebXRCamera) or\n * the WebXRCamera itself. Note that the WebXRCamera path will modify the position\n * of the WebXRCamera directly and is thus discouraged.\n */\n set locomotionTarget(locomotionTarget) {\n this._locomotionTarget = locomotionTarget;\n this._isLocomotionTargetWebXRCamera = this._locomotionTarget.getClassName() === \"WebXRCamera\";\n }\n /**\n * Construct a new Walking Locomotion feature.\n * @param sessionManager manager for the current XR session\n * @param options creation options, prominently including the vector target for locomotion\n */\n constructor(sessionManager, options) {\n super(sessionManager);\n this._up = new Vector3();\n this._forward = new Vector3();\n this._position = new Vector3();\n this._movement = new Vector3();\n this._sessionManager = sessionManager;\n this.locomotionTarget = options.locomotionTarget;\n if (this._isLocomotionTargetWebXRCamera) {\n Logger.Warn(\"Using walking locomotion directly on a WebXRCamera may have unintended interactions with other XR techniques. Using an XR space parent is highly recommended\");\n }\n }\n /**\n * Checks whether this feature is compatible with the current WebXR session.\n * Walking locomotion is only compatible with \"immersive-vr\" sessions.\n * @returns true if compatible, false otherwise\n */\n isCompatible() {\n return this._sessionManager.sessionMode === undefined || this._sessionManager.sessionMode === \"immersive-vr\";\n }\n /**\n * Attaches the feature.\n * Typically called automatically by the features manager.\n * @returns true if attach succeeded, false otherwise\n */\n attach() {\n if (!this.isCompatible || !super.attach()) {\n return false;\n }\n this._walker = new Walker(this._sessionManager.scene.getEngine());\n return true;\n }\n /**\n * Detaches the feature.\n * Typically called automatically by the features manager.\n * @returns true if detach succeeded, false otherwise\n */\n detach() {\n if (!super.detach()) {\n return false;\n }\n this._walker = null;\n return true;\n }\n _onXRFrame(frame) {\n const pose = frame.getViewerPose(this._sessionManager.baseReferenceSpace);\n if (!pose) {\n return;\n }\n const handednessScalar = this.locomotionTarget.getScene().useRightHandedSystem ? 1 : -1;\n const m = pose.transform.matrix;\n this._up.copyFromFloats(m[4], m[5], handednessScalar * m[6]);\n this._forward.copyFromFloats(m[8], m[9], handednessScalar * m[10]);\n this._position.copyFromFloats(m[12], m[13], handednessScalar * m[14]);\n // Compute the nape position\n this._forward.scaleAndAddToRef(0.05, this._position);\n this._up.scaleAndAddToRef(-0.05, this._position);\n this._walker.update(this._position, this._forward);\n this._movement.copyFrom(this._walker.movementThisFrame);\n if (!this._isLocomotionTargetWebXRCamera) {\n Vector3.TransformNormalToRef(this._movement, this.locomotionTarget.getWorldMatrix(), this._movement);\n }\n this.locomotionTarget.position.addInPlace(this._movement);\n }\n}\n//register the plugin\nWebXRFeaturesManager.AddWebXRFeature(WebXRWalkingLocomotion.Name, (xrSessionManager, options) => {\n return () => new WebXRWalkingLocomotion(xrSessionManager, options);\n}, WebXRWalkingLocomotion.Version, false);\n//# sourceMappingURL=WebXRWalkingLocomotion.js.map","import { WebXRFeatureName, WebXRFeaturesManager } from \"../webXRFeaturesManager.js\";\nimport { WebXRAbstractFeature } from \"./WebXRAbstractFeature.js\";\nimport { Matrix } from \"../../Maths/math.vector.js\";\nimport { RenderTargetTexture } from \"../../Materials/Textures/renderTargetTexture.js\";\n\nimport { ShaderMaterial } from \"../../Materials/shaderMaterial.js\";\nimport \"../../Shaders/velocity.fragment.js\";\nimport \"../../Shaders/velocity.vertex.js\";\n/**\n * Used for Space Warp render process\n */\nexport class XRSpaceWarpRenderTarget extends RenderTargetTexture {\n /**\n * Creates a Space Warp render target\n * @param motionVectorTexture WebGLTexture provided by WebGLSubImage\n * @param depthStencilTexture WebGLTexture provided by WebGLSubImage\n * @param scene scene used with the render target\n * @param size the size of the render target (used for each view)\n */\n constructor(motionVectorTexture, depthStencilTexture, scene, size = 512) {\n super(\"spacewarp rtt\", size, scene, false, true, 2, false, undefined, false, false, true, undefined, true);\n this._originalPairing = [];\n this._previousWorldMatrices = [];\n this._previousTransforms = [Matrix.Identity(), Matrix.Identity()];\n this._renderTarget = this.getScene()\n .getEngine()\n .createMultiviewRenderTargetTexture(this.getRenderWidth(), this.getRenderHeight(), motionVectorTexture, depthStencilTexture);\n this._renderTarget._disposeOnlyFramebuffers = true;\n this._texture = this._renderTarget.texture;\n this._texture.isMultiview = true;\n this._texture.format = 5;\n if (scene) {\n this._velocityMaterial = new ShaderMaterial(\"velocity shader material\", scene, {\n vertex: \"velocity\",\n fragment: \"velocity\",\n }, {\n uniforms: [\"world\", \"previousWorld\", \"viewProjection\", \"viewProjectionR\", \"previousViewProjection\", \"previousViewProjectionR\"],\n });\n this._velocityMaterial._materialHelperNeedsPreviousMatrices = true;\n this._velocityMaterial.onBindObservable.add((mesh) => {\n // mesh. getWorldMatrix can be incorrect under rare conditions (e.g. when using a effective mesh in the render function).\n // If the case arise that will require changing it we will need to change the bind process in the material class to also provide the world matrix as a parameter\n this._previousWorldMatrices[mesh.uniqueId] = this._previousWorldMatrices[mesh.uniqueId] || mesh.getWorldMatrix();\n this._velocityMaterial.getEffect().setMatrix(\"previousWorld\", this._previousWorldMatrices[mesh.uniqueId]);\n this._previousWorldMatrices[mesh.uniqueId] = mesh.getWorldMatrix();\n // now set the scene's previous matrix\n this._velocityMaterial.getEffect().setMatrix(\"previousViewProjection\", this._previousTransforms[0]);\n // multiview for sure\n this._velocityMaterial.getEffect().setMatrix(\"previousViewProjectionR\", this._previousTransforms[1]);\n // store the previous (current, to be exact) transforms\n this._previousTransforms[0].copyFrom(scene.getTransformMatrix());\n this._previousTransforms[1].copyFrom(scene._transformMatrixR);\n });\n this._velocityMaterial.freeze();\n }\n }\n /**\n * {@inheritDoc}\n */\n render(useCameraPostProcess = false, dumpForDebug = false) {\n // Swap to use velocity material\n this._originalPairing.length = 0;\n const scene = this.getScene();\n // set the velocity material to render the velocity RTT\n if (scene && this._velocityMaterial) {\n scene.getActiveMeshes().forEach((mesh) => {\n this._originalPairing.push([mesh, mesh.material]);\n mesh.material = this._velocityMaterial;\n });\n }\n super.render(useCameraPostProcess, dumpForDebug);\n // Restore original materials\n this._originalPairing.forEach((tuple) => {\n tuple[0].material = tuple[1];\n });\n }\n /**\n * @internal\n */\n _bindFrameBuffer() {\n if (!this._renderTarget) {\n return;\n }\n this.getScene().getEngine().bindSpaceWarpFramebuffer(this._renderTarget);\n }\n /**\n * Gets the number of views the corresponding to the texture (eg. a SpaceWarpRenderTarget will have > 1)\n * @returns the view count\n */\n getViewCount() {\n return 2;\n }\n /**\n * {@inheritdoc}\n */\n dispose() {\n super.dispose();\n this._velocityMaterial.dispose();\n this._previousTransforms.length = 0;\n this._previousWorldMatrices.length = 0;\n this._originalPairing.length = 0;\n }\n}\n/**\n * WebXR Space Warp Render Target Texture Provider\n */\nexport class WebXRSpaceWarpRenderTargetTextureProvider {\n constructor(_scene, _xrSessionManager, _xrWebGLBinding) {\n this._scene = _scene;\n this._xrSessionManager = _xrSessionManager;\n this._xrWebGLBinding = _xrWebGLBinding;\n this._lastSubImages = new Map();\n this._renderTargetTextures = new Map();\n this._engine = _scene.getEngine();\n }\n _getSubImageForView(view) {\n const layerWrapper = this._xrSessionManager._getBaseLayerWrapper();\n if (!layerWrapper) {\n throw new Error(\"For Space Warp, the base layer should be a WebXR Projection Layer.\");\n }\n if (layerWrapper.layerType !== \"XRProjectionLayer\") {\n throw new Error('For Space Warp, the base layer type should \"XRProjectionLayer\".');\n }\n const layer = layerWrapper.layer;\n return this._xrWebGLBinding.getViewSubImage(layer, view);\n }\n _setViewportForSubImage(viewport, subImage) {\n viewport.x = 0;\n viewport.y = 0;\n viewport.width = subImage.motionVectorTextureWidth;\n viewport.height = subImage.motionVectorTextureHeight;\n }\n _createRenderTargetTexture(width, height, framebuffer, motionVectorTexture, depthStencilTexture) {\n if (!this._engine) {\n throw new Error(\"Engine is disposed\");\n }\n const textureSize = { width, height };\n // Create render target texture from the internal texture\n const renderTargetTexture = new XRSpaceWarpRenderTarget(motionVectorTexture, depthStencilTexture, this._scene, textureSize);\n const renderTargetWrapper = renderTargetTexture.renderTarget;\n if (framebuffer) {\n renderTargetWrapper._framebuffer = framebuffer;\n }\n // Create internal texture\n renderTargetWrapper._colorTextureArray = motionVectorTexture;\n renderTargetWrapper._depthStencilTextureArray = depthStencilTexture;\n renderTargetTexture.disableRescaling();\n renderTargetTexture.renderListPredicate = () => true;\n return renderTargetTexture;\n }\n _getRenderTargetForSubImage(subImage, view) {\n const lastSubImage = this._lastSubImages.get(view);\n let renderTargetTexture = this._renderTargetTextures.get(view.eye);\n const width = subImage.motionVectorTextureWidth;\n const height = subImage.motionVectorTextureHeight;\n if (!renderTargetTexture || (lastSubImage === null || lastSubImage === void 0 ? void 0 : lastSubImage.textureWidth) !== width || (lastSubImage === null || lastSubImage === void 0 ? void 0 : lastSubImage.textureHeight) != height) {\n renderTargetTexture = this._createRenderTargetTexture(width, height, null, subImage.motionVectorTexture, subImage.depthStencilTexture);\n this._renderTargetTextures.set(view.eye, renderTargetTexture);\n this._framebufferDimensions = {\n framebufferWidth: width,\n framebufferHeight: height,\n };\n }\n this._lastSubImages.set(view, subImage);\n return renderTargetTexture;\n }\n /**\n * {@inheritDoc}\n */\n trySetViewportForView(viewport, view) {\n const subImage = this._lastSubImages.get(view) || this._getSubImageForView(view);\n if (subImage) {\n this._setViewportForSubImage(viewport, subImage);\n return true;\n }\n return false;\n }\n /**\n * Access the motion vector (which will turn on Space Warp)\n * @param view the view to access the motion vector texture for\n */\n accessMotionVector(view) {\n const subImage = this._getSubImageForView(view);\n if (subImage) {\n // Meta Quest Browser uses accessing these textures as a sign for turning on Space Warp\n subImage.motionVectorTexture;\n subImage.depthStencilTexture;\n }\n }\n /**\n * {@inheritDoc}\n */\n getRenderTargetTextureForEye(_eye) {\n return null;\n }\n /**\n * {@inheritDoc}\n */\n getRenderTargetTextureForView(view) {\n const subImage = this._getSubImageForView(view);\n if (subImage) {\n return this._getRenderTargetForSubImage(subImage, view);\n }\n return null;\n }\n /**\n * {@inheritDoc}\n */\n dispose() {\n this._renderTargetTextures.forEach((rtt) => rtt.dispose());\n this._renderTargetTextures.clear();\n }\n}\n/**\n * the WebXR Space Warp feature.\n */\nexport class WebXRSpaceWarp extends WebXRAbstractFeature {\n /**\n * constructor for the space warp feature\n * @param _xrSessionManager the xr session manager for this feature\n */\n constructor(_xrSessionManager) {\n super(_xrSessionManager);\n /**\n * {@inheritdoc}\n */\n this.dependsOn = [WebXRFeatureName.LAYERS];\n this.xrNativeFeatureName = \"space-warp\";\n this._xrSessionManager.scene.needsPreviousWorldMatrices = true;\n }\n /**\n * Attach this feature.\n * Will usually be called by the features manager.\n *\n * @returns true if successful.\n */\n attach() {\n if (!super.attach()) {\n return false;\n }\n const engine = this._xrSessionManager.scene.getEngine();\n this._glContext = engine._gl;\n this._xrWebGLBinding = new XRWebGLBinding(this._xrSessionManager.session, this._glContext);\n this.spaceWarpRTTProvider = new WebXRSpaceWarpRenderTargetTextureProvider(this._xrSessionManager.scene, this._xrSessionManager, this._xrWebGLBinding);\n this._xrSessionManager.scene.onAfterRenderObservable.add(this._onAfterRender.bind(this));\n return true;\n }\n _onAfterRender() {\n if (this.attached && this._renderTargetTexture) {\n this._renderTargetTexture.render(false, false);\n }\n }\n /**\n * {@inheritdoc}\n */\n isCompatible() {\n return this._xrSessionManager.scene.getEngine().getCaps().colorBufferHalfFloat || false;\n }\n /**\n * {@inheritdoc}\n */\n dispose() {\n super.dispose();\n }\n _onXRFrame(_xrFrame) {\n const pose = _xrFrame.getViewerPose(this._xrSessionManager.referenceSpace);\n if (!pose) {\n return;\n }\n // get the first view to which we will create a texture (or update it)\n const view = pose.views[0];\n this._renderTargetTexture = this._renderTargetTexture || this.spaceWarpRTTProvider.getRenderTargetTextureForView(view);\n this.spaceWarpRTTProvider.accessMotionVector(view);\n }\n}\n/**\n * The module's name\n */\nWebXRSpaceWarp.Name = WebXRFeatureName.SPACE_WARP;\n/**\n * The (Babylon) version of this module.\n * This is an integer representing the implementation version.\n * This number does not correspond to the WebXR specs version\n */\nWebXRSpaceWarp.Version = 1;\n//register the plugin\nWebXRFeaturesManager.AddWebXRFeature(WebXRSpaceWarp.Name, (xrSessionManager) => {\n return () => new WebXRSpaceWarp(xrSessionManager);\n}, WebXRSpaceWarp.Version, false);\n//# sourceMappingURL=WebXRSpaceWarp.js.map","export * from \"./WebXRAbstractFeature.js\";\nexport * from \"./WebXRHitTestLegacy.js\";\nexport * from \"./WebXRAnchorSystem.js\";\nexport * from \"./WebXRPlaneDetector.js\";\nexport * from \"./WebXRBackgroundRemover.js\";\nexport * from \"./WebXRControllerTeleportation.js\";\nexport * from \"./WebXRControllerPointerSelection.js\";\nexport * from \"./WebXRControllerPhysics.js\";\nexport * from \"./WebXRHitTest.js\";\nexport * from \"./WebXRFeaturePointSystem.js\";\nexport * from \"./WebXRHandTracking.js\";\nexport * from \"./WebXRMeshDetector.js\";\nexport * from \"./WebXRImageTracking.js\";\nexport * from \"./WebXRNearInteraction.js\";\nexport * from \"./WebXRDOMOverlay.js\";\nexport * from \"./WebXRControllerMovement.js\";\nexport * from \"./WebXRLightEstimation.js\";\nexport * from \"./WebXREyeTracking.js\";\nexport * from \"./WebXRWalkingLocomotion.js\";\nexport * from \"./WebXRLayers.js\";\nexport * from \"./WebXRDepthSensing.js\";\nexport * from \"./WebXRSpaceWarp.js\";\n//# sourceMappingURL=index.js.map","import { WebXRAbstractMotionController } from \"./webXRAbstractMotionController.js\";\nimport { WebXRMotionControllerManager } from \"./webXRMotionControllerManager.js\";\nimport { Mesh } from \"../../Meshes/mesh.js\";\nimport { Quaternion } from \"../../Maths/math.vector.js\";\nimport { SceneLoader } from \"../../Loading/sceneLoader.js\";\nimport { Logger } from \"../../Misc/logger.js\";\n/**\n * The motion controller class for all microsoft mixed reality controllers\n */\nexport class WebXRMicrosoftMixedRealityController extends WebXRAbstractMotionController {\n constructor(scene, gamepadObject, handedness) {\n super(scene, MixedRealityProfile[\"left-right\"], gamepadObject, handedness);\n // use this in the future - https://github.com/immersive-web/webxr-input-profiles/tree/master/packages/assets/profiles/microsoft\n this._mapping = {\n defaultButton: {\n valueNodeName: \"VALUE\",\n unpressedNodeName: \"UNPRESSED\",\n pressedNodeName: \"PRESSED\",\n },\n defaultAxis: {\n valueNodeName: \"VALUE\",\n minNodeName: \"MIN\",\n maxNodeName: \"MAX\",\n },\n buttons: {\n \"xr-standard-trigger\": {\n rootNodeName: \"SELECT\",\n componentProperty: \"button\",\n states: [\"default\", \"touched\", \"pressed\"],\n },\n \"xr-standard-squeeze\": {\n rootNodeName: \"GRASP\",\n componentProperty: \"state\",\n states: [\"pressed\"],\n },\n \"xr-standard-touchpad\": {\n rootNodeName: \"TOUCHPAD_PRESS\",\n labelAnchorNodeName: \"squeeze-label\",\n touchPointNodeName: \"TOUCH\", // TODO - use this for visual feedback\n },\n \"xr-standard-thumbstick\": {\n rootNodeName: \"THUMBSTICK_PRESS\",\n componentProperty: \"state\",\n states: [\"pressed\"],\n },\n },\n axes: {\n \"xr-standard-touchpad\": {\n \"x-axis\": {\n rootNodeName: \"TOUCHPAD_TOUCH_X\",\n },\n \"y-axis\": {\n rootNodeName: \"TOUCHPAD_TOUCH_Y\",\n },\n },\n \"xr-standard-thumbstick\": {\n \"x-axis\": {\n rootNodeName: \"THUMBSTICK_X\",\n },\n \"y-axis\": {\n rootNodeName: \"THUMBSTICK_Y\",\n },\n },\n },\n };\n this.profileId = \"microsoft-mixed-reality\";\n }\n _getFilenameAndPath() {\n let filename = \"\";\n if (this.handedness === \"left\") {\n filename = WebXRMicrosoftMixedRealityController.MODEL_LEFT_FILENAME;\n }\n else {\n // Right is the default if no hand is specified\n filename = WebXRMicrosoftMixedRealityController.MODEL_RIGHT_FILENAME;\n }\n const device = \"default\";\n const path = WebXRMicrosoftMixedRealityController.MODEL_BASE_URL + device + \"/\";\n return {\n filename,\n path,\n };\n }\n _getModelLoadingConstraints() {\n const glbLoaded = SceneLoader.IsPluginForExtensionAvailable(\".glb\");\n if (!glbLoaded) {\n Logger.Warn(\"glTF / glb loaded was not registered, using generic controller instead\");\n }\n return glbLoaded;\n }\n _processLoadedModel(_meshes) {\n if (!this.rootMesh) {\n return;\n }\n // Button Meshes\n this.getComponentIds().forEach((id, i) => {\n if (this.disableAnimation) {\n return;\n }\n if (id && this.rootMesh) {\n const buttonMap = this._mapping.buttons[id];\n const buttonMeshName = buttonMap.rootNodeName;\n if (!buttonMeshName) {\n Logger.Log(\"Skipping unknown button at index: \" + i + \" with mapped name: \" + id);\n return;\n }\n const buttonMesh = this._getChildByName(this.rootMesh, buttonMeshName);\n if (!buttonMesh) {\n Logger.Warn(\"Missing button mesh with name: \" + buttonMeshName);\n return;\n }\n buttonMap.valueMesh = this._getImmediateChildByName(buttonMesh, this._mapping.defaultButton.valueNodeName);\n buttonMap.pressedMesh = this._getImmediateChildByName(buttonMesh, this._mapping.defaultButton.pressedNodeName);\n buttonMap.unpressedMesh = this._getImmediateChildByName(buttonMesh, this._mapping.defaultButton.unpressedNodeName);\n if (buttonMap.valueMesh && buttonMap.pressedMesh && buttonMap.unpressedMesh) {\n const comp = this.getComponent(id);\n if (comp) {\n comp.onButtonStateChangedObservable.add((component) => {\n this._lerpTransform(buttonMap, component.value);\n }, undefined, true);\n }\n }\n else {\n // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.\n Logger.Warn(\"Missing button submesh under mesh with name: \" + buttonMeshName);\n }\n }\n });\n // Axis Meshes\n this.getComponentIds().forEach((id) => {\n const comp = this.getComponent(id);\n if (!comp.isAxes()) {\n return;\n }\n [\"x-axis\", \"y-axis\"].forEach((axis) => {\n if (!this.rootMesh) {\n return;\n }\n const axisMap = this._mapping.axes[id][axis];\n const axisMesh = this._getChildByName(this.rootMesh, axisMap.rootNodeName);\n if (!axisMesh) {\n Logger.Warn(\"Missing axis mesh with name: \" + axisMap.rootNodeName);\n return;\n }\n axisMap.valueMesh = this._getImmediateChildByName(axisMesh, this._mapping.defaultAxis.valueNodeName);\n axisMap.minMesh = this._getImmediateChildByName(axisMesh, this._mapping.defaultAxis.minNodeName);\n axisMap.maxMesh = this._getImmediateChildByName(axisMesh, this._mapping.defaultAxis.maxNodeName);\n if (axisMap.valueMesh && axisMap.minMesh && axisMap.maxMesh) {\n if (comp) {\n comp.onAxisValueChangedObservable.add((axisValues) => {\n const value = axis === \"x-axis\" ? axisValues.x : axisValues.y;\n this._lerpTransform(axisMap, value, true);\n }, undefined, true);\n }\n }\n else {\n // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.\n Logger.Warn(\"Missing axis submesh under mesh with name: \" + axisMap.rootNodeName);\n }\n });\n });\n }\n _setRootMesh(meshes) {\n this.rootMesh = new Mesh(this.profileId + \" \" + this.handedness, this.scene);\n this.rootMesh.isPickable = false;\n let rootMesh;\n // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'\n for (let i = 0; i < meshes.length; i++) {\n const mesh = meshes[i];\n mesh.isPickable = false;\n if (!mesh.parent) {\n // Handle root node, attach to the new parentMesh\n rootMesh = mesh;\n }\n }\n if (rootMesh) {\n rootMesh.setParent(this.rootMesh);\n }\n if (!this.scene.useRightHandedSystem) {\n this.rootMesh.rotationQuaternion = Quaternion.FromEulerAngles(0, Math.PI, 0);\n }\n }\n _updateModel() {\n // no-op. model is updated using observables.\n }\n}\n/**\n * The base url used to load the left and right controller models\n */\nWebXRMicrosoftMixedRealityController.MODEL_BASE_URL = \"https://controllers.babylonjs.com/microsoft/\";\n/**\n * The name of the left controller model file\n */\nWebXRMicrosoftMixedRealityController.MODEL_LEFT_FILENAME = \"left.glb\";\n/**\n * The name of the right controller model file\n */\nWebXRMicrosoftMixedRealityController.MODEL_RIGHT_FILENAME = \"right.glb\";\n// register the profile\nWebXRMotionControllerManager.RegisterController(\"windows-mixed-reality\", (xrInput, scene) => {\n return new WebXRMicrosoftMixedRealityController(scene, xrInput.gamepad, xrInput.handedness);\n});\n// https://github.com/immersive-web/webxr-input-profiles/blob/master/packages/registry/profiles/microsoft/microsoft-mixed-reality.json\nconst MixedRealityProfile = {\n left: {\n selectComponentId: \"xr-standard-trigger\",\n components: {\n \"xr-standard-trigger\": {\n type: \"trigger\",\n gamepadIndices: {\n button: 0,\n },\n rootNodeName: \"xr_standard_trigger\",\n visualResponses: {\n xr_standard_trigger_pressed: {\n componentProperty: \"button\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_trigger_pressed_value\",\n minNodeName: \"xr_standard_trigger_pressed_min\",\n maxNodeName: \"xr_standard_trigger_pressed_max\",\n },\n },\n },\n \"xr-standard-squeeze\": {\n type: \"squeeze\",\n gamepadIndices: {\n button: 1,\n },\n rootNodeName: \"xr_standard_squeeze\",\n visualResponses: {\n xr_standard_squeeze_pressed: {\n componentProperty: \"button\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_squeeze_pressed_value\",\n minNodeName: \"xr_standard_squeeze_pressed_min\",\n maxNodeName: \"xr_standard_squeeze_pressed_max\",\n },\n },\n },\n \"xr-standard-touchpad\": {\n type: \"touchpad\",\n gamepadIndices: {\n button: 2,\n xAxis: 0,\n yAxis: 1,\n },\n rootNodeName: \"xr_standard_touchpad\",\n visualResponses: {\n xr_standard_touchpad_pressed: {\n componentProperty: \"button\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_touchpad_pressed_value\",\n minNodeName: \"xr_standard_touchpad_pressed_min\",\n maxNodeName: \"xr_standard_touchpad_pressed_max\",\n },\n xr_standard_touchpad_xaxis_pressed: {\n componentProperty: \"xAxis\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_touchpad_xaxis_pressed_value\",\n minNodeName: \"xr_standard_touchpad_xaxis_pressed_min\",\n maxNodeName: \"xr_standard_touchpad_xaxis_pressed_max\",\n },\n xr_standard_touchpad_yaxis_pressed: {\n componentProperty: \"yAxis\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_touchpad_yaxis_pressed_value\",\n minNodeName: \"xr_standard_touchpad_yaxis_pressed_min\",\n maxNodeName: \"xr_standard_touchpad_yaxis_pressed_max\",\n },\n xr_standard_touchpad_xaxis_touched: {\n componentProperty: \"xAxis\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_touchpad_xaxis_touched_value\",\n minNodeName: \"xr_standard_touchpad_xaxis_touched_min\",\n maxNodeName: \"xr_standard_touchpad_xaxis_touched_max\",\n },\n xr_standard_touchpad_yaxis_touched: {\n componentProperty: \"yAxis\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_touchpad_yaxis_touched_value\",\n minNodeName: \"xr_standard_touchpad_yaxis_touched_min\",\n maxNodeName: \"xr_standard_touchpad_yaxis_touched_max\",\n },\n xr_standard_touchpad_axes_touched: {\n componentProperty: \"state\",\n states: [\"touched\", \"pressed\"],\n valueNodeProperty: \"visibility\",\n valueNodeName: \"xr_standard_touchpad_axes_touched_value\",\n },\n },\n touchPointNodeName: \"xr_standard_touchpad_axes_touched_value\",\n },\n \"xr-standard-thumbstick\": {\n type: \"thumbstick\",\n gamepadIndices: {\n button: 3,\n xAxis: 2,\n yAxis: 3,\n },\n rootNodeName: \"xr_standard_thumbstick\",\n visualResponses: {\n xr_standard_thumbstick_pressed: {\n componentProperty: \"button\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_thumbstick_pressed_value\",\n minNodeName: \"xr_standard_thumbstick_pressed_min\",\n maxNodeName: \"xr_standard_thumbstick_pressed_max\",\n },\n xr_standard_thumbstick_xaxis_pressed: {\n componentProperty: \"xAxis\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_thumbstick_xaxis_pressed_value\",\n minNodeName: \"xr_standard_thumbstick_xaxis_pressed_min\",\n maxNodeName: \"xr_standard_thumbstick_xaxis_pressed_max\",\n },\n xr_standard_thumbstick_yaxis_pressed: {\n componentProperty: \"yAxis\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_thumbstick_yaxis_pressed_value\",\n minNodeName: \"xr_standard_thumbstick_yaxis_pressed_min\",\n maxNodeName: \"xr_standard_thumbstick_yaxis_pressed_max\",\n },\n },\n },\n },\n gamepadMapping: \"xr-standard\",\n rootNodeName: \"microsoft-mixed-reality-left\",\n assetPath: \"left.glb\",\n },\n right: {\n selectComponentId: \"xr-standard-trigger\",\n components: {\n \"xr-standard-trigger\": {\n type: \"trigger\",\n gamepadIndices: {\n button: 0,\n },\n rootNodeName: \"xr_standard_trigger\",\n visualResponses: {\n xr_standard_trigger_pressed: {\n componentProperty: \"button\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_trigger_pressed_value\",\n minNodeName: \"xr_standard_trigger_pressed_min\",\n maxNodeName: \"xr_standard_trigger_pressed_max\",\n },\n },\n },\n \"xr-standard-squeeze\": {\n type: \"squeeze\",\n gamepadIndices: {\n button: 1,\n },\n rootNodeName: \"xr_standard_squeeze\",\n visualResponses: {\n xr_standard_squeeze_pressed: {\n componentProperty: \"button\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_squeeze_pressed_value\",\n minNodeName: \"xr_standard_squeeze_pressed_min\",\n maxNodeName: \"xr_standard_squeeze_pressed_max\",\n },\n },\n },\n \"xr-standard-touchpad\": {\n type: \"touchpad\",\n gamepadIndices: {\n button: 2,\n xAxis: 0,\n yAxis: 1,\n },\n rootNodeName: \"xr_standard_touchpad\",\n visualResponses: {\n xr_standard_touchpad_pressed: {\n componentProperty: \"button\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_touchpad_pressed_value\",\n minNodeName: \"xr_standard_touchpad_pressed_min\",\n maxNodeName: \"xr_standard_touchpad_pressed_max\",\n },\n xr_standard_touchpad_xaxis_pressed: {\n componentProperty: \"xAxis\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_touchpad_xaxis_pressed_value\",\n minNodeName: \"xr_standard_touchpad_xaxis_pressed_min\",\n maxNodeName: \"xr_standard_touchpad_xaxis_pressed_max\",\n },\n xr_standard_touchpad_yaxis_pressed: {\n componentProperty: \"yAxis\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_touchpad_yaxis_pressed_value\",\n minNodeName: \"xr_standard_touchpad_yaxis_pressed_min\",\n maxNodeName: \"xr_standard_touchpad_yaxis_pressed_max\",\n },\n xr_standard_touchpad_xaxis_touched: {\n componentProperty: \"xAxis\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_touchpad_xaxis_touched_value\",\n minNodeName: \"xr_standard_touchpad_xaxis_touched_min\",\n maxNodeName: \"xr_standard_touchpad_xaxis_touched_max\",\n },\n xr_standard_touchpad_yaxis_touched: {\n componentProperty: \"yAxis\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_touchpad_yaxis_touched_value\",\n minNodeName: \"xr_standard_touchpad_yaxis_touched_min\",\n maxNodeName: \"xr_standard_touchpad_yaxis_touched_max\",\n },\n xr_standard_touchpad_axes_touched: {\n componentProperty: \"state\",\n states: [\"touched\", \"pressed\"],\n valueNodeProperty: \"visibility\",\n valueNodeName: \"xr_standard_touchpad_axes_touched_value\",\n },\n },\n touchPointNodeName: \"xr_standard_touchpad_axes_touched_value\",\n },\n \"xr-standard-thumbstick\": {\n type: \"thumbstick\",\n gamepadIndices: {\n button: 3,\n xAxis: 2,\n yAxis: 3,\n },\n rootNodeName: \"xr_standard_thumbstick\",\n visualResponses: {\n xr_standard_thumbstick_pressed: {\n componentProperty: \"button\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_thumbstick_pressed_value\",\n minNodeName: \"xr_standard_thumbstick_pressed_min\",\n maxNodeName: \"xr_standard_thumbstick_pressed_max\",\n },\n xr_standard_thumbstick_xaxis_pressed: {\n componentProperty: \"xAxis\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_thumbstick_xaxis_pressed_value\",\n minNodeName: \"xr_standard_thumbstick_xaxis_pressed_min\",\n maxNodeName: \"xr_standard_thumbstick_xaxis_pressed_max\",\n },\n xr_standard_thumbstick_yaxis_pressed: {\n componentProperty: \"yAxis\",\n states: [\"default\", \"touched\", \"pressed\"],\n valueNodeProperty: \"transform\",\n valueNodeName: \"xr_standard_thumbstick_yaxis_pressed_value\",\n minNodeName: \"xr_standard_thumbstick_yaxis_pressed_min\",\n maxNodeName: \"xr_standard_thumbstick_yaxis_pressed_max\",\n },\n },\n },\n },\n gamepadMapping: \"xr-standard\",\n rootNodeName: \"microsoft-mixed-reality-right\",\n assetPath: \"right.glb\",\n },\n};\n//# sourceMappingURL=webXRMicrosoftMixedRealityController.js.map","import { WebXRAbstractMotionController } from \"./webXRAbstractMotionController.js\";\nimport { WebXRMotionControllerManager } from \"./webXRMotionControllerManager.js\";\nimport { Mesh } from \"../../Meshes/mesh.js\";\nimport { Quaternion } from \"../../Maths/math.vector.js\";\n/**\n * The motion controller class for oculus touch (quest, rift).\n * This class supports legacy mapping as well the standard xr mapping\n */\nexport class WebXROculusTouchMotionController extends WebXRAbstractMotionController {\n constructor(scene, gamepadObject, handedness, _legacyMapping = false, _forceLegacyControllers = false) {\n super(scene, OculusTouchLayouts[handedness], gamepadObject, handedness);\n this._forceLegacyControllers = _forceLegacyControllers;\n this.profileId = \"oculus-touch\";\n }\n _getFilenameAndPath() {\n let filename = \"\";\n if (this.handedness === \"left\") {\n filename = WebXROculusTouchMotionController.MODEL_LEFT_FILENAME;\n }\n else {\n // Right is the default if no hand is specified\n filename = WebXROculusTouchMotionController.MODEL_RIGHT_FILENAME;\n }\n const path = this._isQuest() ? WebXROculusTouchMotionController.QUEST_MODEL_BASE_URL : WebXROculusTouchMotionController.MODEL_BASE_URL;\n return {\n filename,\n path,\n };\n }\n _getModelLoadingConstraints() {\n return true;\n }\n _processLoadedModel(_meshes) {\n const isQuest = this._isQuest();\n const triggerDirection = this.handedness === \"right\" ? -1 : 1;\n this.getComponentIds().forEach((id) => {\n const comp = id && this.getComponent(id);\n if (comp) {\n comp.onButtonStateChangedObservable.add((component) => {\n if (!this.rootMesh || this.disableAnimation) {\n return;\n }\n switch (id) {\n case \"xr-standard-trigger\": // index trigger\n if (!isQuest) {\n this._modelRootNode.getChildren()[3].rotation.x = -component.value * 0.2;\n this._modelRootNode.getChildren()[3].position.y = -component.value * 0.005;\n this._modelRootNode.getChildren()[3].position.z = -component.value * 0.005;\n }\n return;\n case \"xr-standard-squeeze\": // secondary trigger\n if (!isQuest) {\n this._modelRootNode.getChildren()[4].position.x = triggerDirection * component.value * 0.0035;\n }\n return;\n case \"xr-standard-thumbstick\": // thumbstick\n return;\n case \"a-button\":\n case \"x-button\":\n if (!isQuest) {\n if (component.pressed) {\n this._modelRootNode.getChildren()[1].position.y = -0.001;\n }\n else {\n this._modelRootNode.getChildren()[1].position.y = 0;\n }\n }\n return;\n case \"b-button\":\n case \"y-button\":\n if (!isQuest) {\n if (component.pressed) {\n this._modelRootNode.getChildren()[2].position.y = -0.001;\n }\n else {\n this._modelRootNode.getChildren()[2].position.y = 0;\n }\n }\n return;\n }\n }, undefined, true);\n }\n });\n }\n _setRootMesh(meshes) {\n this.rootMesh = new Mesh(this.profileId + \" \" + this.handedness, this.scene);\n if (!this.scene.useRightHandedSystem) {\n this.rootMesh.rotationQuaternion = Quaternion.FromEulerAngles(0, Math.PI, 0);\n }\n meshes.forEach((mesh) => {\n mesh.isPickable = false;\n });\n if (this._isQuest()) {\n this._modelRootNode = meshes[0];\n }\n else {\n this._modelRootNode = meshes[1];\n this.rootMesh.position.y = 0.034;\n this.rootMesh.position.z = 0.052;\n }\n this._modelRootNode.parent = this.rootMesh;\n }\n _updateModel() {\n // no-op. model is updated using observables.\n }\n /**\n * Is this the new type of oculus touch. At the moment both have the same profile and it is impossible to differentiate\n * between the touch and touch 2.\n */\n _isQuest() {\n // this is SADLY the only way to currently check. Until proper profiles will be available.\n return !!navigator.userAgent.match(/Quest/gi) && !this._forceLegacyControllers;\n }\n}\n/**\n * The base url used to load the left and right controller models\n */\nWebXROculusTouchMotionController.MODEL_BASE_URL = \"https://controllers.babylonjs.com/oculus/\";\n/**\n * The name of the left controller model file\n */\nWebXROculusTouchMotionController.MODEL_LEFT_FILENAME = \"left.babylon\";\n/**\n * The name of the right controller model file\n */\nWebXROculusTouchMotionController.MODEL_RIGHT_FILENAME = \"right.babylon\";\n/**\n * Base Url for the Quest controller model.\n */\nWebXROculusTouchMotionController.QUEST_MODEL_BASE_URL = \"https://controllers.babylonjs.com/oculusQuest/\";\n// register the profile\nWebXRMotionControllerManager.RegisterController(\"oculus-touch\", (xrInput, scene) => {\n return new WebXROculusTouchMotionController(scene, xrInput.gamepad, xrInput.handedness);\n});\nWebXRMotionControllerManager.RegisterController(\"oculus-touch-legacy\", (xrInput, scene) => {\n return new WebXROculusTouchMotionController(scene, xrInput.gamepad, xrInput.handedness, true);\n});\nconst OculusTouchLayouts = {\n left: {\n selectComponentId: \"xr-standard-trigger\",\n components: {\n \"xr-standard-trigger\": {\n type: \"trigger\",\n gamepadIndices: {\n button: 0,\n },\n rootNodeName: \"xr_standard_trigger\",\n visualResponses: {},\n },\n \"xr-standard-squeeze\": {\n type: \"squeeze\",\n gamepadIndices: {\n button: 1,\n },\n rootNodeName: \"xr_standard_squeeze\",\n visualResponses: {},\n },\n \"xr-standard-thumbstick\": {\n type: \"thumbstick\",\n gamepadIndices: {\n button: 3,\n xAxis: 2,\n yAxis: 3,\n },\n rootNodeName: \"xr_standard_thumbstick\",\n visualResponses: {},\n },\n \"x-button\": {\n type: \"button\",\n gamepadIndices: {\n button: 4,\n },\n rootNodeName: \"x_button\",\n visualResponses: {},\n },\n \"y-button\": {\n type: \"button\",\n gamepadIndices: {\n button: 5,\n },\n rootNodeName: \"y_button\",\n visualResponses: {},\n },\n thumbrest: {\n type: \"button\",\n gamepadIndices: {\n button: 6,\n },\n rootNodeName: \"thumbrest\",\n visualResponses: {},\n },\n },\n gamepadMapping: \"xr-standard\",\n rootNodeName: \"oculus-touch-v2-left\",\n assetPath: \"left.glb\",\n },\n right: {\n selectComponentId: \"xr-standard-trigger\",\n components: {\n \"xr-standard-trigger\": {\n type: \"trigger\",\n gamepadIndices: {\n button: 0,\n },\n rootNodeName: \"xr_standard_trigger\",\n visualResponses: {},\n },\n \"xr-standard-squeeze\": {\n type: \"squeeze\",\n gamepadIndices: {\n button: 1,\n },\n rootNodeName: \"xr_standard_squeeze\",\n visualResponses: {},\n },\n \"xr-standard-thumbstick\": {\n type: \"thumbstick\",\n gamepadIndices: {\n button: 3,\n xAxis: 2,\n yAxis: 3,\n },\n rootNodeName: \"xr_standard_thumbstick\",\n visualResponses: {},\n },\n \"a-button\": {\n type: \"button\",\n gamepadIndices: {\n button: 4,\n },\n rootNodeName: \"a_button\",\n visualResponses: {},\n },\n \"b-button\": {\n type: \"button\",\n gamepadIndices: {\n button: 5,\n },\n rootNodeName: \"b_button\",\n visualResponses: {},\n },\n thumbrest: {\n type: \"button\",\n gamepadIndices: {\n button: 6,\n },\n rootNodeName: \"thumbrest\",\n visualResponses: {},\n },\n },\n gamepadMapping: \"xr-standard\",\n rootNodeName: \"oculus-touch-v2-right\",\n assetPath: \"right.glb\",\n },\n};\n//# sourceMappingURL=webXROculusTouchMotionController.js.map","import { RegisterNativeTypeAsync } from \"../../Engines/nativeEngine.js\";\n/** @internal */\nexport class NativeXRFrame {\n get session() {\n return this._nativeImpl.session;\n }\n constructor(_nativeImpl) {\n this._nativeImpl = _nativeImpl;\n this._xrTransform = new XRRigidTransform();\n this._xrPose = {\n transform: this._xrTransform,\n emulatedPosition: false,\n };\n // Enough space for position, orientation\n this._xrPoseVectorData = new Float32Array(4 + 4);\n this.fillPoses = this._nativeImpl.fillPoses.bind(this._nativeImpl);\n this.getViewerPose = this._nativeImpl.getViewerPose.bind(this._nativeImpl);\n this.getHitTestResults = this._nativeImpl.getHitTestResults.bind(this._nativeImpl);\n this.getHitTestResultsForTransientInput = () => {\n throw new Error(\"XRFrame.getHitTestResultsForTransientInput not supported on native.\");\n };\n this.createAnchor = this._nativeImpl.createAnchor.bind(this._nativeImpl);\n this.getJointPose = this._nativeImpl.getJointPose.bind(this._nativeImpl);\n this.fillJointRadii = this._nativeImpl.fillJointRadii.bind(this._nativeImpl);\n this.getLightEstimate = () => {\n throw new Error(\"XRFrame.getLightEstimate not supported on native.\");\n };\n this.getImageTrackingResults = () => {\n var _a;\n return (_a = this._nativeImpl._imageTrackingResults) !== null && _a !== void 0 ? _a : [];\n };\n }\n getPose(space, baseSpace) {\n if (!this._nativeImpl.getPoseData(space, baseSpace, this._xrPoseVectorData.buffer, this._xrTransform.matrix.buffer)) {\n return undefined;\n }\n const position = this._xrTransform.position;\n position.x = this._xrPoseVectorData[0];\n position.y = this._xrPoseVectorData[1];\n position.z = this._xrPoseVectorData[2];\n position.w = this._xrPoseVectorData[3];\n const orientation = this._xrTransform.orientation;\n orientation.x = this._xrPoseVectorData[4];\n orientation.y = this._xrPoseVectorData[5];\n orientation.z = this._xrPoseVectorData[6];\n orientation.w = this._xrPoseVectorData[7];\n return this._xrPose;\n }\n get trackedAnchors() {\n return this._nativeImpl.trackedAnchors;\n }\n get worldInformation() {\n return this._nativeImpl.worldInformation;\n }\n get detectedPlanes() {\n return this._nativeImpl.detectedPlanes;\n }\n get featurePointCloud() {\n return this._nativeImpl.featurePointCloud;\n }\n getDepthInformation(view) {\n throw new Error(\"This function is not available in Babylon Native\");\n // return this._nativeImpl.getDepthInformation(view);\n }\n}\nRegisterNativeTypeAsync(\"NativeXRFrame\", NativeXRFrame);\n//# sourceMappingURL=nativeXRFrame.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./abstractScene.js\";\nexport * from \"./Actions/index.js\";\nexport * from \"./Animations/index.js\";\nexport * from \"./assetContainer.js\";\nexport * from \"./Audio/index.js\";\nexport * from \"./BakedVertexAnimation/index.js\";\nexport * from \"./Behaviors/index.js\";\nexport * from \"./Bones/index.js\";\nexport * from \"./Buffers/index.js\";\nexport * from \"./Cameras/index.js\";\nexport * from \"./Collisions/index.js\";\nexport * from \"./Compute/index.js\";\nexport * from \"./Culling/index.js\";\nexport * from \"./Debug/index.js\";\nexport * from \"./DeviceInput/index.js\";\nexport * from \"./Engines/index.js\";\nexport * from \"./Events/index.js\";\nexport * from \"./Gamepads/index.js\";\nexport * from \"./Gizmos/index.js\";\nexport * from \"./Helpers/index.js\";\nexport * from \"./Instrumentation/index.js\";\nexport * from \"./Layers/index.js\";\nexport * from \"./LensFlares/index.js\";\nexport * from \"./Lights/index.js\";\nexport * from \"./Loading/index.js\";\nexport * from \"./Materials/index.js\";\nexport * from \"./Maths/index.js\";\nexport * from \"./Meshes/index.js\";\nexport * from \"./Morph/index.js\";\nexport * from \"./Navigation/index.js\";\nexport * from \"./node.js\";\nexport * from \"./Offline/index.js\";\nexport * from \"./Particles/index.js\";\nexport * from \"./Physics/index.js\";\nexport * from \"./PostProcesses/index.js\";\nexport * from \"./Probes/index.js\";\nexport * from \"./Rendering/index.js\";\nexport * from \"./scene.js\";\nexport * from \"./sceneComponent.js\";\nexport * from \"./Sprites/index.js\";\nexport * from \"./States/index.js\";\nexport * from \"./Misc/index.js\";\nexport * from \"./XR/index.js\";\nexport * from \"./types.js\";\nexport * from \"./Compat/index.js\";\n//# sourceMappingURL=index.js.map","import { Tools } from \"@babylonjs/core/Misc/tools.js\";\nfunction validateAsync(data, rootUrl, fileName, getExternalResource) {\n const options = {\n externalResourceFunction: (uri) => getExternalResource(uri).then((value) => new Uint8Array(value)),\n };\n if (fileName) {\n options.uri = rootUrl === \"file:\" ? fileName : rootUrl + fileName;\n }\n return data instanceof ArrayBuffer ? GLTFValidator.validateBytes(new Uint8Array(data), options) : GLTFValidator.validateString(data, options);\n}\n/**\n * The worker function that gets converted to a blob url to pass into a worker.\n */\nfunction workerFunc() {\n const pendingExternalResources = [];\n onmessage = (message) => {\n const data = message.data;\n switch (data.id) {\n case \"init\": {\n importScripts(data.url);\n break;\n }\n case \"validate\": {\n validateAsync(data.data, data.rootUrl, data.fileName, (uri) => new Promise((resolve, reject) => {\n const index = pendingExternalResources.length;\n pendingExternalResources.push({ resolve, reject });\n postMessage({ id: \"getExternalResource\", index: index, uri: uri });\n })).then((value) => {\n postMessage({ id: \"validate.resolve\", value: value });\n }, (reason) => {\n postMessage({ id: \"validate.reject\", reason: reason });\n });\n break;\n }\n case \"getExternalResource.resolve\": {\n pendingExternalResources[data.index].resolve(data.value);\n break;\n }\n case \"getExternalResource.reject\": {\n pendingExternalResources[data.index].reject(data.reason);\n break;\n }\n }\n };\n}\n/**\n * glTF validation\n */\nexport class GLTFValidation {\n /**\n * Validate a glTF asset using the glTF-Validator.\n * @param data The JSON of a glTF or the array buffer of a binary glTF\n * @param rootUrl The root url for the glTF\n * @param fileName The file name for the glTF\n * @param getExternalResource The callback to get external resources for the glTF validator\n * @returns A promise that resolves with the glTF validation results once complete\n */\n static ValidateAsync(data, rootUrl, fileName, getExternalResource) {\n const dataCopy = ArrayBuffer.isView(data) ? data.slice().buffer : data;\n if (typeof Worker === \"function\") {\n return new Promise((resolve, reject) => {\n const workerContent = `${validateAsync}(${workerFunc})()`;\n const workerBlobUrl = URL.createObjectURL(new Blob([workerContent], { type: \"application/javascript\" }));\n const worker = new Worker(workerBlobUrl);\n const onError = (error) => {\n worker.removeEventListener(\"error\", onError);\n worker.removeEventListener(\"message\", onMessage);\n reject(error);\n };\n const onMessage = (message) => {\n const data = message.data;\n switch (data.id) {\n case \"getExternalResource\": {\n getExternalResource(data.uri).then((value) => {\n worker.postMessage({ id: \"getExternalResource.resolve\", index: data.index, value: value }, [value]);\n }, (reason) => {\n worker.postMessage({ id: \"getExternalResource.reject\", index: data.index, reason: reason });\n });\n break;\n }\n case \"validate.resolve\": {\n worker.removeEventListener(\"error\", onError);\n worker.removeEventListener(\"message\", onMessage);\n resolve(data.value);\n worker.terminate();\n break;\n }\n case \"validate.reject\": {\n worker.removeEventListener(\"error\", onError);\n worker.removeEventListener(\"message\", onMessage);\n reject(data.reason);\n worker.terminate();\n }\n }\n };\n worker.addEventListener(\"error\", onError);\n worker.addEventListener(\"message\", onMessage);\n worker.postMessage({ id: \"init\", url: this.Configuration.url });\n worker.postMessage({ id: \"validate\", data: dataCopy, rootUrl: rootUrl, fileName: fileName });\n });\n }\n else {\n if (!this._LoadScriptPromise) {\n this._LoadScriptPromise = Tools.LoadScriptAsync(this.Configuration.url);\n }\n return this._LoadScriptPromise.then(() => {\n return validateAsync(dataCopy, rootUrl, fileName, getExternalResource);\n });\n }\n }\n}\n/**\n * The configuration. Defaults to `{ url: \"https://preview.babylonjs.com/gltf_validator.js\" }`.\n */\nGLTFValidation.Configuration = {\n url: \"https://preview.babylonjs.com/gltf_validator.js\",\n};\n//# sourceMappingURL=glTFValidation.js.map","import { Observable } from \"@babylonjs/core/Misc/observable.js\";\nimport { Tools } from \"@babylonjs/core/Misc/tools.js\";\nimport { SceneLoader } from \"@babylonjs/core/Loading/sceneLoader.js\";\nimport { AssetContainer } from \"@babylonjs/core/assetContainer.js\";\nimport { Logger } from \"@babylonjs/core/Misc/logger.js\";\nimport { DataReader } from \"@babylonjs/core/Misc/dataReader.js\";\nimport { GLTFValidation } from \"./glTFValidation.js\";\nimport { DecodeBase64UrlToBinary } from \"@babylonjs/core/Misc/fileTools.js\";\nimport { RuntimeError, ErrorCodes } from \"@babylonjs/core/Misc/error.js\";\nfunction readAsync(arrayBuffer, byteOffset, byteLength) {\n try {\n return Promise.resolve(new Uint8Array(arrayBuffer, byteOffset, byteLength));\n }\n catch (e) {\n return Promise.reject(e);\n }\n}\nfunction readViewAsync(arrayBufferView, byteOffset, byteLength) {\n try {\n if (arrayBufferView.byteOffset + byteLength > arrayBufferView.byteLength) {\n throw new Error(\"Array length out of bounds.\");\n }\n return Promise.resolve(new Uint8Array(arrayBufferView.buffer, arrayBufferView.byteOffset + byteOffset, byteLength));\n }\n catch (e) {\n return Promise.reject(e);\n }\n}\n/**\n * Mode that determines the coordinate system to use.\n */\nexport var GLTFLoaderCoordinateSystemMode;\n(function (GLTFLoaderCoordinateSystemMode) {\n /**\n * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.\n */\n GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode[\"AUTO\"] = 0] = \"AUTO\";\n /**\n * Sets the useRightHandedSystem flag on the scene.\n */\n GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode[\"FORCE_RIGHT_HANDED\"] = 1] = \"FORCE_RIGHT_HANDED\";\n})(GLTFLoaderCoordinateSystemMode || (GLTFLoaderCoordinateSystemMode = {}));\n/**\n * Mode that determines what animations will start.\n */\nexport var GLTFLoaderAnimationStartMode;\n(function (GLTFLoaderAnimationStartMode) {\n /**\n * No animation will start.\n */\n GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode[\"NONE\"] = 0] = \"NONE\";\n /**\n * The first animation will start.\n */\n GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode[\"FIRST\"] = 1] = \"FIRST\";\n /**\n * All animations will start.\n */\n GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode[\"ALL\"] = 2] = \"ALL\";\n})(GLTFLoaderAnimationStartMode || (GLTFLoaderAnimationStartMode = {}));\n/**\n * Loader state.\n */\nexport var GLTFLoaderState;\n(function (GLTFLoaderState) {\n /**\n * The asset is loading.\n */\n GLTFLoaderState[GLTFLoaderState[\"LOADING\"] = 0] = \"LOADING\";\n /**\n * The asset is ready for rendering.\n */\n GLTFLoaderState[GLTFLoaderState[\"READY\"] = 1] = \"READY\";\n /**\n * The asset is completely loaded.\n */\n GLTFLoaderState[GLTFLoaderState[\"COMPLETE\"] = 2] = \"COMPLETE\";\n})(GLTFLoaderState || (GLTFLoaderState = {}));\n/**\n * File loader for loading glTF files into a scene.\n */\nexport class GLTFFileLoader {\n constructor() {\n // --------------\n // Common options\n // --------------\n /**\n * Raised when the asset has been parsed\n */\n this.onParsedObservable = new Observable();\n // ----------\n // V2 options\n // ----------\n /**\n * The coordinate system mode. Defaults to AUTO.\n */\n this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;\n /**\n * The animation start mode. Defaults to FIRST.\n */\n this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;\n /**\n * Defines if the loader should compile materials before raising the success callback. Defaults to false.\n */\n this.compileMaterials = false;\n /**\n * Defines if the loader should also compile materials with clip planes. Defaults to false.\n */\n this.useClipPlane = false;\n /**\n * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.\n */\n this.compileShadowGenerators = false;\n /**\n * Defines if the Alpha blended materials are only applied as coverage.\n * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.\n * If true, no extra effects are applied to transparent pixels.\n */\n this.transparencyAsCoverage = false;\n /**\n * Defines if the loader should use range requests when load binary glTF files from HTTP.\n * Enabling will disable offline support and glTF validator.\n * Defaults to false.\n */\n this.useRangeRequests = false;\n /**\n * Defines if the loader should create instances when multiple glTF nodes point to the same glTF mesh. Defaults to true.\n */\n this.createInstances = true;\n /**\n * Defines if the loader should always compute the bounding boxes of meshes and not use the min/max values from the position accessor. Defaults to false.\n */\n this.alwaysComputeBoundingBox = false;\n /**\n * If true, load all materials defined in the file, even if not used by any mesh. Defaults to false.\n */\n this.loadAllMaterials = false;\n /**\n * If true, load only the materials defined in the file. Defaults to false.\n */\n this.loadOnlyMaterials = false;\n /**\n * If true, do not load any materials defined in the file. Defaults to false.\n */\n this.skipMaterials = false;\n /**\n * If true, load the color (gamma encoded) textures into sRGB buffers (if supported by the GPU), which will yield more accurate results when sampling the texture. Defaults to true.\n */\n this.useSRGBBuffers = true;\n /**\n * When loading glTF animations, which are defined in seconds, target them to this FPS. Defaults to 60.\n */\n this.targetFps = 60;\n /**\n * Defines if the loader should always compute the nearest common ancestor of the skeleton joints instead of using `skin.skeleton`. Defaults to false.\n * Set this to true if loading assets with invalid `skin.skeleton` values.\n */\n this.alwaysComputeSkeletonRootNode = false;\n /**\n * Function called before loading a url referenced by the asset.\n * @param url\n */\n this.preprocessUrlAsync = (url) => Promise.resolve(url);\n /**\n * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.\n * Note that the observable is raised as soon as the mesh object is created, meaning some data may not have been setup yet for this mesh (vertex data, morph targets, material, ...)\n */\n this.onMeshLoadedObservable = new Observable();\n /**\n * Callback raised when the loader creates a skin after parsing the glTF properties of the skin node.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/importers/glTF/glTFSkinning#ignoring-the-transform-of-the-skinned-mesh\n * @param node - the transform node that corresponds to the original glTF skin node used for animations\n * @param skinnedNode - the transform node that is the skinned mesh itself or the parent of the skinned meshes\n */\n this.onSkinLoadedObservable = new Observable();\n /**\n * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.\n */\n this.onTextureLoadedObservable = new Observable();\n /**\n * Observable raised when the loader creates a material after parsing the glTF properties of the material.\n */\n this.onMaterialLoadedObservable = new Observable();\n /**\n * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.\n */\n this.onCameraLoadedObservable = new Observable();\n /**\n * Observable raised when the asset is completely loaded, immediately before the loader is disposed.\n * For assets with LODs, raised when all of the LODs are complete.\n * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.\n */\n this.onCompleteObservable = new Observable();\n /**\n * Observable raised when an error occurs.\n */\n this.onErrorObservable = new Observable();\n /**\n * Observable raised after the loader is disposed.\n */\n this.onDisposeObservable = new Observable();\n /**\n * Observable raised after a loader extension is created.\n * Set additional options for a loader extension in this event.\n */\n this.onExtensionLoadedObservable = new Observable();\n /**\n * Defines if the loader should validate the asset.\n */\n this.validate = false;\n /**\n * Observable raised after validation when validate is set to true. The event data is the result of the validation.\n */\n this.onValidatedObservable = new Observable();\n this._loader = null;\n this._state = null;\n this._requests = new Array();\n /**\n * Name of the loader (\"gltf\")\n */\n this.name = \"gltf\";\n /** @internal */\n this.extensions = {\n \".gltf\": { isBinary: false },\n \".glb\": { isBinary: true },\n };\n /**\n * Observable raised when the loader state changes.\n */\n this.onLoaderStateChangedObservable = new Observable();\n this._logIndentLevel = 0;\n this._loggingEnabled = false;\n /** @internal */\n this._log = this._logDisabled;\n this._capturePerformanceCounters = false;\n /** @internal */\n this._startPerformanceCounter = this._startPerformanceCounterDisabled;\n /** @internal */\n this._endPerformanceCounter = this._endPerformanceCounterDisabled;\n }\n /**\n * Raised when the asset has been parsed\n */\n set onParsed(callback) {\n if (this._onParsedObserver) {\n this.onParsedObservable.remove(this._onParsedObserver);\n }\n this._onParsedObserver = this.onParsedObservable.add(callback);\n }\n /**\n * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.\n * Note that the callback is called as soon as the mesh object is created, meaning some data may not have been setup yet for this mesh (vertex data, morph targets, material, ...)\n */\n set onMeshLoaded(callback) {\n if (this._onMeshLoadedObserver) {\n this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);\n }\n this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);\n }\n /**\n * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.\n */\n set onTextureLoaded(callback) {\n if (this._onTextureLoadedObserver) {\n this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);\n }\n this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);\n }\n /**\n * Callback raised when the loader creates a material after parsing the glTF properties of the material.\n */\n set onMaterialLoaded(callback) {\n if (this._onMaterialLoadedObserver) {\n this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);\n }\n this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);\n }\n /**\n * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.\n */\n set onCameraLoaded(callback) {\n if (this._onCameraLoadedObserver) {\n this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);\n }\n this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);\n }\n /**\n * Callback raised when the asset is completely loaded, immediately before the loader is disposed.\n * For assets with LODs, raised when all of the LODs are complete.\n * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.\n */\n set onComplete(callback) {\n if (this._onCompleteObserver) {\n this.onCompleteObservable.remove(this._onCompleteObserver);\n }\n this._onCompleteObserver = this.onCompleteObservable.add(callback);\n }\n /**\n * Callback raised when an error occurs.\n */\n set onError(callback) {\n if (this._onErrorObserver) {\n this.onErrorObservable.remove(this._onErrorObserver);\n }\n this._onErrorObserver = this.onErrorObservable.add(callback);\n }\n /**\n * Callback raised after the loader is disposed.\n */\n set onDispose(callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n }\n /**\n * Callback raised after a loader extension is created.\n */\n set onExtensionLoaded(callback) {\n if (this._onExtensionLoadedObserver) {\n this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);\n }\n this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);\n }\n /**\n * Defines if the loader logging is enabled.\n */\n get loggingEnabled() {\n return this._loggingEnabled;\n }\n set loggingEnabled(value) {\n if (this._loggingEnabled === value) {\n return;\n }\n this._loggingEnabled = value;\n if (this._loggingEnabled) {\n this._log = this._logEnabled;\n }\n else {\n this._log = this._logDisabled;\n }\n }\n /**\n * Defines if the loader should capture performance counters.\n */\n get capturePerformanceCounters() {\n return this._capturePerformanceCounters;\n }\n set capturePerformanceCounters(value) {\n if (this._capturePerformanceCounters === value) {\n return;\n }\n this._capturePerformanceCounters = value;\n if (this._capturePerformanceCounters) {\n this._startPerformanceCounter = this._startPerformanceCounterEnabled;\n this._endPerformanceCounter = this._endPerformanceCounterEnabled;\n }\n else {\n this._startPerformanceCounter = this._startPerformanceCounterDisabled;\n this._endPerformanceCounter = this._endPerformanceCounterDisabled;\n }\n }\n /**\n * Callback raised after a loader extension is created.\n */\n set onValidated(callback) {\n if (this._onValidatedObserver) {\n this.onValidatedObservable.remove(this._onValidatedObserver);\n }\n this._onValidatedObserver = this.onValidatedObservable.add(callback);\n }\n /**\n * Disposes the loader, releases resources during load, and cancels any outstanding requests.\n */\n dispose() {\n if (this._loader) {\n this._loader.dispose();\n this._loader = null;\n }\n for (const request of this._requests) {\n request.abort();\n }\n this._requests.length = 0;\n delete this._progressCallback;\n this.preprocessUrlAsync = (url) => Promise.resolve(url);\n this.onMeshLoadedObservable.clear();\n this.onSkinLoadedObservable.clear();\n this.onTextureLoadedObservable.clear();\n this.onMaterialLoadedObservable.clear();\n this.onCameraLoadedObservable.clear();\n this.onCompleteObservable.clear();\n this.onExtensionLoadedObservable.clear();\n this.onDisposeObservable.notifyObservers(undefined);\n this.onDisposeObservable.clear();\n }\n /**\n * @internal\n */\n loadFile(scene, fileOrUrl, rootUrl, onSuccess, onProgress, useArrayBuffer, onError, name) {\n if (ArrayBuffer.isView(fileOrUrl)) {\n this._loadBinary(scene, fileOrUrl, rootUrl, onSuccess, onError, name);\n return null;\n }\n this._progressCallback = onProgress;\n const fileName = fileOrUrl.name || Tools.GetFilename(fileOrUrl);\n if (useArrayBuffer) {\n if (this.useRangeRequests) {\n if (this.validate) {\n Logger.Warn(\"glTF validation is not supported when range requests are enabled\");\n }\n const fileRequest = {\n abort: () => { },\n onCompleteObservable: new Observable(),\n };\n const dataBuffer = {\n readAsync: (byteOffset, byteLength) => {\n return new Promise((resolve, reject) => {\n this._loadFile(scene, fileOrUrl, (data) => {\n resolve(new Uint8Array(data));\n }, true, (error) => {\n reject(error);\n }, (webRequest) => {\n webRequest.setRequestHeader(\"Range\", `bytes=${byteOffset}-${byteOffset + byteLength - 1}`);\n });\n });\n },\n byteLength: 0,\n };\n this._unpackBinaryAsync(new DataReader(dataBuffer)).then((loaderData) => {\n fileRequest.onCompleteObservable.notifyObservers(fileRequest);\n onSuccess(loaderData);\n }, onError ? (error) => onError(undefined, error) : undefined);\n return fileRequest;\n }\n return this._loadFile(scene, fileOrUrl, (data) => {\n this._validate(scene, new Uint8Array(data), rootUrl, fileName);\n this._unpackBinaryAsync(new DataReader({\n readAsync: (byteOffset, byteLength) => readAsync(data, byteOffset, byteLength),\n byteLength: data.byteLength,\n })).then((loaderData) => {\n onSuccess(loaderData);\n }, onError ? (error) => onError(undefined, error) : undefined);\n }, true, onError);\n }\n return this._loadFile(scene, fileOrUrl, (data) => {\n this._validate(scene, new Uint8Array(data), rootUrl, fileName);\n onSuccess({ json: this._parseJson(data) });\n }, useArrayBuffer, onError);\n }\n /**\n * @internal\n */\n _loadBinary(scene, data, rootUrl, onSuccess, onError, fileName) {\n this._validate(scene, data, rootUrl, fileName);\n this._unpackBinaryAsync(new DataReader({\n readAsync: (byteOffset, byteLength) => readViewAsync(data, byteOffset, byteLength),\n byteLength: data.byteLength,\n })).then((loaderData) => {\n onSuccess(loaderData);\n }, onError ? (error) => onError(undefined, error) : undefined);\n }\n /**\n * @internal\n */\n importMeshAsync(meshesNames, scene, data, rootUrl, onProgress, fileName) {\n return Promise.resolve().then(() => {\n this.onParsedObservable.notifyObservers(data);\n this.onParsedObservable.clear();\n this._log(`Loading ${fileName || \"\"}`);\n this._loader = this._getLoader(data);\n return this._loader.importMeshAsync(meshesNames, scene, null, data, rootUrl, onProgress, fileName);\n });\n }\n /**\n * @internal\n */\n loadAsync(scene, data, rootUrl, onProgress, fileName) {\n return Promise.resolve().then(() => {\n this.onParsedObservable.notifyObservers(data);\n this.onParsedObservable.clear();\n this._log(`Loading ${fileName || \"\"}`);\n this._loader = this._getLoader(data);\n return this._loader.loadAsync(scene, data, rootUrl, onProgress, fileName);\n });\n }\n /**\n * @internal\n */\n loadAssetContainerAsync(scene, data, rootUrl, onProgress, fileName) {\n return Promise.resolve().then(() => {\n this.onParsedObservable.notifyObservers(data);\n this.onParsedObservable.clear();\n this._log(`Loading ${fileName || \"\"}`);\n this._loader = this._getLoader(data);\n // Prepare the asset container.\n const container = new AssetContainer(scene);\n // Get materials/textures when loading to add to container\n const materials = [];\n this.onMaterialLoadedObservable.add((material) => {\n materials.push(material);\n });\n const textures = [];\n this.onTextureLoadedObservable.add((texture) => {\n textures.push(texture);\n });\n const cameras = [];\n this.onCameraLoadedObservable.add((camera) => {\n cameras.push(camera);\n });\n const morphTargetManagers = [];\n this.onMeshLoadedObservable.add((mesh) => {\n if (mesh.morphTargetManager) {\n morphTargetManagers.push(mesh.morphTargetManager);\n }\n });\n return this._loader.importMeshAsync(null, scene, container, data, rootUrl, onProgress, fileName).then((result) => {\n Array.prototype.push.apply(container.geometries, result.geometries);\n Array.prototype.push.apply(container.meshes, result.meshes);\n Array.prototype.push.apply(container.particleSystems, result.particleSystems);\n Array.prototype.push.apply(container.skeletons, result.skeletons);\n Array.prototype.push.apply(container.animationGroups, result.animationGroups);\n Array.prototype.push.apply(container.materials, materials);\n Array.prototype.push.apply(container.textures, textures);\n Array.prototype.push.apply(container.lights, result.lights);\n Array.prototype.push.apply(container.transformNodes, result.transformNodes);\n Array.prototype.push.apply(container.cameras, cameras);\n Array.prototype.push.apply(container.morphTargetManagers, morphTargetManagers);\n return container;\n });\n });\n }\n /**\n * @internal\n */\n canDirectLoad(data) {\n return ((data.indexOf(\"asset\") !== -1 && data.indexOf(\"version\") !== -1) ||\n data.startsWith(\"data:base64,\" + GLTFFileLoader._MagicBase64Encoded) || // this is technically incorrect, but will continue to support for backcompat.\n data.startsWith(\"data:;base64,\" + GLTFFileLoader._MagicBase64Encoded) ||\n data.startsWith(\"data:application/octet-stream;base64,\" + GLTFFileLoader._MagicBase64Encoded) ||\n data.startsWith(\"data:model/gltf-binary;base64,\" + GLTFFileLoader._MagicBase64Encoded));\n }\n /**\n * @internal\n */\n directLoad(scene, data) {\n if (data.startsWith(\"base64,\" + GLTFFileLoader._MagicBase64Encoded) || // this is technically incorrect, but will continue to support for backcompat.\n data.startsWith(\";base64,\" + GLTFFileLoader._MagicBase64Encoded) ||\n data.startsWith(\"application/octet-stream;base64,\" + GLTFFileLoader._MagicBase64Encoded) ||\n data.startsWith(\"model/gltf-binary;base64,\" + GLTFFileLoader._MagicBase64Encoded)) {\n const arrayBuffer = DecodeBase64UrlToBinary(data);\n this._validate(scene, new Uint8Array(arrayBuffer));\n return this._unpackBinaryAsync(new DataReader({\n readAsync: (byteOffset, byteLength) => readAsync(arrayBuffer, byteOffset, byteLength),\n byteLength: arrayBuffer.byteLength,\n }));\n }\n this._validate(scene, data);\n return Promise.resolve({ json: this._parseJson(data) });\n }\n /** @internal */\n createPlugin() {\n return new GLTFFileLoader();\n }\n /**\n * The loader state or null if the loader is not active.\n */\n get loaderState() {\n return this._state;\n }\n /**\n * Returns a promise that resolves when the asset is completely loaded.\n * @returns a promise that resolves when the asset is completely loaded.\n */\n whenCompleteAsync() {\n return new Promise((resolve, reject) => {\n this.onCompleteObservable.addOnce(() => {\n resolve();\n });\n this.onErrorObservable.addOnce((reason) => {\n reject(reason);\n });\n });\n }\n /**\n * @internal\n */\n _setState(state) {\n if (this._state === state) {\n return;\n }\n this._state = state;\n this.onLoaderStateChangedObservable.notifyObservers(this._state);\n this._log(GLTFLoaderState[this._state]);\n }\n /**\n * @internal\n */\n _loadFile(scene, fileOrUrl, onSuccess, useArrayBuffer, onError, onOpened) {\n const request = scene._loadFile(fileOrUrl, onSuccess, (event) => {\n this._onProgress(event, request);\n }, true, useArrayBuffer, onError, onOpened);\n request.onCompleteObservable.add((request) => {\n this._requests.splice(this._requests.indexOf(request), 1);\n });\n this._requests.push(request);\n return request;\n }\n _onProgress(event, request) {\n if (!this._progressCallback) {\n return;\n }\n request._lengthComputable = event.lengthComputable;\n request._loaded = event.loaded;\n request._total = event.total;\n let lengthComputable = true;\n let loaded = 0;\n let total = 0;\n for (const request of this._requests) {\n if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {\n return;\n }\n lengthComputable = lengthComputable && request._lengthComputable;\n loaded += request._loaded;\n total += request._total;\n }\n this._progressCallback({\n lengthComputable: lengthComputable,\n loaded: loaded,\n total: lengthComputable ? total : 0,\n });\n }\n _validate(scene, data, rootUrl = \"\", fileName = \"\") {\n if (!this.validate) {\n return;\n }\n this._startPerformanceCounter(\"Validate JSON\");\n GLTFValidation.ValidateAsync(data, rootUrl, fileName, (uri) => {\n return this.preprocessUrlAsync(rootUrl + uri).then((url) => scene._loadFileAsync(url, undefined, true, true));\n }).then((result) => {\n this._endPerformanceCounter(\"Validate JSON\");\n this.onValidatedObservable.notifyObservers(result);\n this.onValidatedObservable.clear();\n }, (reason) => {\n this._endPerformanceCounter(\"Validate JSON\");\n Tools.Warn(`Failed to validate: ${reason.message}`);\n this.onValidatedObservable.clear();\n });\n }\n _getLoader(loaderData) {\n const asset = loaderData.json.asset || {};\n this._log(`Asset version: ${asset.version}`);\n asset.minVersion && this._log(`Asset minimum version: ${asset.minVersion}`);\n asset.generator && this._log(`Asset generator: ${asset.generator}`);\n const version = GLTFFileLoader._parseVersion(asset.version);\n if (!version) {\n throw new Error(\"Invalid version: \" + asset.version);\n }\n if (asset.minVersion !== undefined) {\n const minVersion = GLTFFileLoader._parseVersion(asset.minVersion);\n if (!minVersion) {\n throw new Error(\"Invalid minimum version: \" + asset.minVersion);\n }\n if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {\n throw new Error(\"Incompatible minimum version: \" + asset.minVersion);\n }\n }\n const createLoaders = {\n 1: GLTFFileLoader._CreateGLTF1Loader,\n 2: GLTFFileLoader._CreateGLTF2Loader,\n };\n const createLoader = createLoaders[version.major];\n if (!createLoader) {\n throw new Error(\"Unsupported version: \" + asset.version);\n }\n return createLoader(this);\n }\n _parseJson(json) {\n this._startPerformanceCounter(\"Parse JSON\");\n this._log(`JSON length: ${json.length}`);\n const parsed = JSON.parse(json);\n this._endPerformanceCounter(\"Parse JSON\");\n return parsed;\n }\n _unpackBinaryAsync(dataReader) {\n this._startPerformanceCounter(\"Unpack Binary\");\n // Read magic + version + length + json length + json format\n return dataReader.loadAsync(20).then(() => {\n const Binary = {\n Magic: 0x46546c67,\n };\n const magic = dataReader.readUint32();\n if (magic !== Binary.Magic) {\n throw new RuntimeError(\"Unexpected magic: \" + magic, ErrorCodes.GLTFLoaderUnexpectedMagicError);\n }\n const version = dataReader.readUint32();\n if (this.loggingEnabled) {\n this._log(`Binary version: ${version}`);\n }\n const length = dataReader.readUint32();\n if (!this.useRangeRequests && length !== dataReader.buffer.byteLength) {\n Logger.Warn(`Length in header does not match actual data length: ${length} != ${dataReader.buffer.byteLength}`);\n }\n let unpacked;\n switch (version) {\n case 1: {\n unpacked = this._unpackBinaryV1Async(dataReader, length);\n break;\n }\n case 2: {\n unpacked = this._unpackBinaryV2Async(dataReader, length);\n break;\n }\n default: {\n throw new Error(\"Unsupported version: \" + version);\n }\n }\n this._endPerformanceCounter(\"Unpack Binary\");\n return unpacked;\n });\n }\n _unpackBinaryV1Async(dataReader, length) {\n const ContentFormat = {\n JSON: 0,\n };\n const contentLength = dataReader.readUint32();\n const contentFormat = dataReader.readUint32();\n if (contentFormat !== ContentFormat.JSON) {\n throw new Error(`Unexpected content format: ${contentFormat}`);\n }\n const bodyLength = length - dataReader.byteOffset;\n const data = { json: this._parseJson(dataReader.readString(contentLength)), bin: null };\n if (bodyLength !== 0) {\n const startByteOffset = dataReader.byteOffset;\n data.bin = {\n readAsync: (byteOffset, byteLength) => dataReader.buffer.readAsync(startByteOffset + byteOffset, byteLength),\n byteLength: bodyLength,\n };\n }\n return Promise.resolve(data);\n }\n _unpackBinaryV2Async(dataReader, length) {\n const ChunkFormat = {\n JSON: 0x4e4f534a,\n BIN: 0x004e4942,\n };\n // Read the JSON chunk header.\n const chunkLength = dataReader.readUint32();\n const chunkFormat = dataReader.readUint32();\n if (chunkFormat !== ChunkFormat.JSON) {\n throw new Error(\"First chunk format is not JSON\");\n }\n // Bail if there are no other chunks.\n if (dataReader.byteOffset + chunkLength === length) {\n return dataReader.loadAsync(chunkLength).then(() => {\n return { json: this._parseJson(dataReader.readString(chunkLength)), bin: null };\n });\n }\n // Read the JSON chunk and the length and type of the next chunk.\n return dataReader.loadAsync(chunkLength + 8).then(() => {\n const data = { json: this._parseJson(dataReader.readString(chunkLength)), bin: null };\n const readAsync = () => {\n const chunkLength = dataReader.readUint32();\n const chunkFormat = dataReader.readUint32();\n switch (chunkFormat) {\n case ChunkFormat.JSON: {\n throw new Error(\"Unexpected JSON chunk\");\n }\n case ChunkFormat.BIN: {\n const startByteOffset = dataReader.byteOffset;\n data.bin = {\n readAsync: (byteOffset, byteLength) => dataReader.buffer.readAsync(startByteOffset + byteOffset, byteLength),\n byteLength: chunkLength,\n };\n dataReader.skipBytes(chunkLength);\n break;\n }\n default: {\n // ignore unrecognized chunkFormat\n dataReader.skipBytes(chunkLength);\n break;\n }\n }\n if (dataReader.byteOffset !== length) {\n return dataReader.loadAsync(8).then(readAsync);\n }\n return Promise.resolve(data);\n };\n return readAsync();\n });\n }\n static _parseVersion(version) {\n if (version === \"1.0\" || version === \"1.0.1\") {\n return {\n major: 1,\n minor: 0,\n };\n }\n const match = (version + \"\").match(/^(\\d+)\\.(\\d+)/);\n if (!match) {\n return null;\n }\n return {\n major: parseInt(match[1]),\n minor: parseInt(match[2]),\n };\n }\n static _compareVersion(a, b) {\n if (a.major > b.major) {\n return 1;\n }\n if (a.major < b.major) {\n return -1;\n }\n if (a.minor > b.minor) {\n return 1;\n }\n if (a.minor < b.minor) {\n return -1;\n }\n return 0;\n }\n /**\n * @internal\n */\n _logOpen(message) {\n this._log(message);\n this._logIndentLevel++;\n }\n /** @internal */\n _logClose() {\n --this._logIndentLevel;\n }\n _logEnabled(message) {\n const spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);\n Logger.Log(`${spaces}${message}`);\n }\n _logDisabled(message) { }\n _startPerformanceCounterEnabled(counterName) {\n Tools.StartPerformanceCounter(counterName);\n }\n _startPerformanceCounterDisabled(counterName) { }\n _endPerformanceCounterEnabled(counterName) {\n Tools.EndPerformanceCounter(counterName);\n }\n _endPerformanceCounterDisabled(counterName) { }\n}\n// ----------\n// V1 options\n// ----------\n/**\n * Set this property to false to disable incremental loading which delays the loader from calling the success callback until after loading the meshes and shaders.\n * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.\n * Defaults to true.\n * @internal\n */\nGLTFFileLoader.IncrementalLoading = true;\n/**\n * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.\n * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.\n * @internal\n */\nGLTFFileLoader.HomogeneousCoordinates = false;\nGLTFFileLoader._MagicBase64Encoded = \"Z2xURg\"; // \"glTF\" base64 encoded (without the quotes!)\nGLTFFileLoader._logSpaces = \" \";\nif (SceneLoader) {\n SceneLoader.RegisterPlugin(new GLTFFileLoader());\n}\n//# sourceMappingURL=glTFFileLoader.js.map","export * from \"./nativeXRRenderTarget.js\";\nexport * from \"./nativeXRFrame.js\";\n//# sourceMappingURL=index.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./webXRCamera.js\";\nexport * from \"./webXREnterExitUI.js\";\nexport * from \"./webXRExperienceHelper.js\";\nexport * from \"./webXRInput.js\";\nexport * from \"./webXRInputSource.js\";\nexport * from \"./webXRManagedOutputCanvas.js\";\nexport * from \"./webXRTypes.js\";\nexport * from \"./webXRSessionManager.js\";\nexport * from \"./webXRDefaultExperience.js\";\nexport * from \"./webXRFeaturesManager.js\";\nexport * from \"./features/index.js\";\nexport * from \"./motionController/index.js\";\nexport * from \"./native/index.js\";\n//# sourceMappingURL=index.js.map","export {};\n/** @internal */\n/* interface DeepImmutableMap extends ReadonlyMap, DeepImmutable> {} // es2015+ only */\n//# sourceMappingURL=types.js.map","export * from \"./compatibilityOptions.js\";\n//# sourceMappingURL=index.js.map","import { EParameterType, ETextureWrapMode, ETextureFilterType, EComponentType } from \"./glTFLoaderInterfaces.js\";\nimport { Vector2, Vector3, Vector4, Matrix } from \"@babylonjs/core/Maths/math.vector.js\";\nimport { Color4 } from \"@babylonjs/core/Maths/math.color.js\";\nimport { Effect } from \"@babylonjs/core/Materials/effect.js\";\nimport { ShaderMaterial } from \"@babylonjs/core/Materials/shaderMaterial.js\";\nimport { Texture } from \"@babylonjs/core/Materials/Textures/texture.js\";\n/**\n * Utils functions for GLTF\n * @internal\n * @deprecated\n */\nexport class GLTFUtils {\n /**\n * Sets the given \"parameter\" matrix\n * @param scene the Scene object\n * @param source the source node where to pick the matrix\n * @param parameter the GLTF technique parameter\n * @param uniformName the name of the shader's uniform\n * @param shaderMaterial the shader material\n */\n static SetMatrix(scene, source, parameter, uniformName, shaderMaterial) {\n let mat = null;\n if (parameter.semantic === \"MODEL\") {\n mat = source.getWorldMatrix();\n }\n else if (parameter.semantic === \"PROJECTION\") {\n mat = scene.getProjectionMatrix();\n }\n else if (parameter.semantic === \"VIEW\") {\n mat = scene.getViewMatrix();\n }\n else if (parameter.semantic === \"MODELVIEWINVERSETRANSPOSE\") {\n mat = Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());\n }\n else if (parameter.semantic === \"MODELVIEW\") {\n mat = source.getWorldMatrix().multiply(scene.getViewMatrix());\n }\n else if (parameter.semantic === \"MODELVIEWPROJECTION\") {\n mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());\n }\n else if (parameter.semantic === \"MODELINVERSE\") {\n mat = source.getWorldMatrix().invert();\n }\n else if (parameter.semantic === \"VIEWINVERSE\") {\n mat = scene.getViewMatrix().invert();\n }\n else if (parameter.semantic === \"PROJECTIONINVERSE\") {\n mat = scene.getProjectionMatrix().invert();\n }\n else if (parameter.semantic === \"MODELVIEWINVERSE\") {\n mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();\n }\n else if (parameter.semantic === \"MODELVIEWPROJECTIONINVERSE\") {\n mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();\n }\n else if (parameter.semantic === \"MODELINVERSETRANSPOSE\") {\n mat = Matrix.Transpose(source.getWorldMatrix().invert());\n }\n if (mat) {\n switch (parameter.type) {\n case EParameterType.FLOAT_MAT2:\n shaderMaterial.setMatrix2x2(uniformName, Matrix.GetAsMatrix2x2(mat));\n break;\n case EParameterType.FLOAT_MAT3:\n shaderMaterial.setMatrix3x3(uniformName, Matrix.GetAsMatrix3x3(mat));\n break;\n case EParameterType.FLOAT_MAT4:\n shaderMaterial.setMatrix(uniformName, mat);\n break;\n default:\n break;\n }\n }\n }\n /**\n * Sets the given \"parameter\" matrix\n * @param shaderMaterial the shader material\n * @param uniform the name of the shader's uniform\n * @param value the value of the uniform\n * @param type the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)\n */\n static SetUniform(shaderMaterial, uniform, value, type) {\n switch (type) {\n case EParameterType.FLOAT:\n shaderMaterial.setFloat(uniform, value);\n return true;\n case EParameterType.FLOAT_VEC2:\n shaderMaterial.setVector2(uniform, Vector2.FromArray(value));\n return true;\n case EParameterType.FLOAT_VEC3:\n shaderMaterial.setVector3(uniform, Vector3.FromArray(value));\n return true;\n case EParameterType.FLOAT_VEC4:\n shaderMaterial.setVector4(uniform, Vector4.FromArray(value));\n return true;\n default:\n return false;\n }\n }\n /**\n * Returns the wrap mode of the texture\n * @param mode the mode value\n */\n static GetWrapMode(mode) {\n switch (mode) {\n case ETextureWrapMode.CLAMP_TO_EDGE:\n return Texture.CLAMP_ADDRESSMODE;\n case ETextureWrapMode.MIRRORED_REPEAT:\n return Texture.MIRROR_ADDRESSMODE;\n case ETextureWrapMode.REPEAT:\n return Texture.WRAP_ADDRESSMODE;\n default:\n return Texture.WRAP_ADDRESSMODE;\n }\n }\n /**\n * Returns the byte stride giving an accessor\n * @param accessor the GLTF accessor objet\n */\n static GetByteStrideFromType(accessor) {\n // Needs this function since \"byteStride\" isn't requiered in glTF format\n const type = accessor.type;\n switch (type) {\n case \"VEC2\":\n return 2;\n case \"VEC3\":\n return 3;\n case \"VEC4\":\n return 4;\n case \"MAT2\":\n return 4;\n case \"MAT3\":\n return 9;\n case \"MAT4\":\n return 16;\n default:\n return 1;\n }\n }\n /**\n * Returns the texture filter mode giving a mode value\n * @param mode the filter mode value\n * @returns the filter mode (TODO - needs to be a type?)\n */\n static GetTextureFilterMode(mode) {\n switch (mode) {\n case ETextureFilterType.LINEAR:\n case ETextureFilterType.LINEAR_MIPMAP_NEAREST:\n case ETextureFilterType.LINEAR_MIPMAP_LINEAR:\n return Texture.TRILINEAR_SAMPLINGMODE;\n case ETextureFilterType.NEAREST:\n case ETextureFilterType.NEAREST_MIPMAP_NEAREST:\n return Texture.NEAREST_SAMPLINGMODE;\n default:\n return Texture.BILINEAR_SAMPLINGMODE;\n }\n }\n static GetBufferFromBufferView(gltfRuntime, bufferView, byteOffset, byteLength, componentType) {\n byteOffset = bufferView.byteOffset + byteOffset;\n const loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];\n if (byteOffset + byteLength > loadedBufferView.byteLength) {\n throw new Error(\"Buffer access is out of range\");\n }\n const buffer = loadedBufferView.buffer;\n byteOffset += loadedBufferView.byteOffset;\n switch (componentType) {\n case EComponentType.BYTE:\n return new Int8Array(buffer, byteOffset, byteLength);\n case EComponentType.UNSIGNED_BYTE:\n return new Uint8Array(buffer, byteOffset, byteLength);\n case EComponentType.SHORT:\n return new Int16Array(buffer, byteOffset, byteLength);\n case EComponentType.UNSIGNED_SHORT:\n return new Uint16Array(buffer, byteOffset, byteLength);\n default:\n return new Float32Array(buffer, byteOffset, byteLength);\n }\n }\n /**\n * Returns a buffer from its accessor\n * @param gltfRuntime the GLTF runtime\n * @param accessor the GLTF accessor\n */\n static GetBufferFromAccessor(gltfRuntime, accessor) {\n const bufferView = gltfRuntime.bufferViews[accessor.bufferView];\n const byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);\n return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);\n }\n /**\n * Decodes a buffer view into a string\n * @param view the buffer view\n */\n static DecodeBufferToText(view) {\n let result = \"\";\n const length = view.byteLength;\n for (let i = 0; i < length; ++i) {\n result += String.fromCharCode(view[i]);\n }\n return result;\n }\n /**\n * Returns the default material of gltf. Related to\n * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material\n * @param scene the Babylon.js scene\n */\n static GetDefaultMaterial(scene) {\n if (!GLTFUtils._DefaultMaterial) {\n Effect.ShadersStore[\"GLTFDefaultMaterialVertexShader\"] = [\n \"precision highp float;\",\n \"\",\n \"uniform mat4 worldView;\",\n \"uniform mat4 projection;\",\n \"\",\n \"attribute vec3 position;\",\n \"\",\n \"void main(void)\",\n \"{\",\n \" gl_Position = projection * worldView * vec4(position, 1.0);\",\n \"}\",\n ].join(\"\\n\");\n Effect.ShadersStore[\"GLTFDefaultMaterialPixelShader\"] = [\n \"precision highp float;\",\n \"\",\n \"uniform vec4 u_emission;\",\n \"\",\n \"void main(void)\",\n \"{\",\n \" gl_FragColor = u_emission;\",\n \"}\",\n ].join(\"\\n\");\n const shaderPath = {\n vertex: \"GLTFDefaultMaterial\",\n fragment: \"GLTFDefaultMaterial\",\n };\n const options = {\n attributes: [\"position\"],\n uniforms: [\"worldView\", \"projection\", \"u_emission\"],\n samplers: new Array(),\n needAlphaBlending: false,\n };\n GLTFUtils._DefaultMaterial = new ShaderMaterial(\"GLTFDefaultMaterial\", scene, shaderPath, options);\n GLTFUtils._DefaultMaterial.setColor4(\"u_emission\", new Color4(0.5, 0.5, 0.5, 1.0));\n }\n return GLTFUtils._DefaultMaterial;\n }\n}\n// The GLTF default material\nGLTFUtils._DefaultMaterial = null;\n//# sourceMappingURL=glTFLoaderUtils.js.map","/**\n * Enums\n * @internal\n */\nexport var EComponentType;\n(function (EComponentType) {\n EComponentType[EComponentType[\"BYTE\"] = 5120] = \"BYTE\";\n EComponentType[EComponentType[\"UNSIGNED_BYTE\"] = 5121] = \"UNSIGNED_BYTE\";\n EComponentType[EComponentType[\"SHORT\"] = 5122] = \"SHORT\";\n EComponentType[EComponentType[\"UNSIGNED_SHORT\"] = 5123] = \"UNSIGNED_SHORT\";\n EComponentType[EComponentType[\"FLOAT\"] = 5126] = \"FLOAT\";\n})(EComponentType || (EComponentType = {}));\n/** @internal */\nexport var EShaderType;\n(function (EShaderType) {\n EShaderType[EShaderType[\"FRAGMENT\"] = 35632] = \"FRAGMENT\";\n EShaderType[EShaderType[\"VERTEX\"] = 35633] = \"VERTEX\";\n})(EShaderType || (EShaderType = {}));\n/** @internal */\nexport var EParameterType;\n(function (EParameterType) {\n EParameterType[EParameterType[\"BYTE\"] = 5120] = \"BYTE\";\n EParameterType[EParameterType[\"UNSIGNED_BYTE\"] = 5121] = \"UNSIGNED_BYTE\";\n EParameterType[EParameterType[\"SHORT\"] = 5122] = \"SHORT\";\n EParameterType[EParameterType[\"UNSIGNED_SHORT\"] = 5123] = \"UNSIGNED_SHORT\";\n EParameterType[EParameterType[\"INT\"] = 5124] = \"INT\";\n EParameterType[EParameterType[\"UNSIGNED_INT\"] = 5125] = \"UNSIGNED_INT\";\n EParameterType[EParameterType[\"FLOAT\"] = 5126] = \"FLOAT\";\n EParameterType[EParameterType[\"FLOAT_VEC2\"] = 35664] = \"FLOAT_VEC2\";\n EParameterType[EParameterType[\"FLOAT_VEC3\"] = 35665] = \"FLOAT_VEC3\";\n EParameterType[EParameterType[\"FLOAT_VEC4\"] = 35666] = \"FLOAT_VEC4\";\n EParameterType[EParameterType[\"INT_VEC2\"] = 35667] = \"INT_VEC2\";\n EParameterType[EParameterType[\"INT_VEC3\"] = 35668] = \"INT_VEC3\";\n EParameterType[EParameterType[\"INT_VEC4\"] = 35669] = \"INT_VEC4\";\n EParameterType[EParameterType[\"BOOL\"] = 35670] = \"BOOL\";\n EParameterType[EParameterType[\"BOOL_VEC2\"] = 35671] = \"BOOL_VEC2\";\n EParameterType[EParameterType[\"BOOL_VEC3\"] = 35672] = \"BOOL_VEC3\";\n EParameterType[EParameterType[\"BOOL_VEC4\"] = 35673] = \"BOOL_VEC4\";\n EParameterType[EParameterType[\"FLOAT_MAT2\"] = 35674] = \"FLOAT_MAT2\";\n EParameterType[EParameterType[\"FLOAT_MAT3\"] = 35675] = \"FLOAT_MAT3\";\n EParameterType[EParameterType[\"FLOAT_MAT4\"] = 35676] = \"FLOAT_MAT4\";\n EParameterType[EParameterType[\"SAMPLER_2D\"] = 35678] = \"SAMPLER_2D\";\n})(EParameterType || (EParameterType = {}));\n/** @internal */\nexport var ETextureWrapMode;\n(function (ETextureWrapMode) {\n ETextureWrapMode[ETextureWrapMode[\"CLAMP_TO_EDGE\"] = 33071] = \"CLAMP_TO_EDGE\";\n ETextureWrapMode[ETextureWrapMode[\"MIRRORED_REPEAT\"] = 33648] = \"MIRRORED_REPEAT\";\n ETextureWrapMode[ETextureWrapMode[\"REPEAT\"] = 10497] = \"REPEAT\";\n})(ETextureWrapMode || (ETextureWrapMode = {}));\n/** @internal */\nexport var ETextureFilterType;\n(function (ETextureFilterType) {\n ETextureFilterType[ETextureFilterType[\"NEAREST\"] = 9728] = \"NEAREST\";\n ETextureFilterType[ETextureFilterType[\"LINEAR\"] = 9728] = \"LINEAR\";\n ETextureFilterType[ETextureFilterType[\"NEAREST_MIPMAP_NEAREST\"] = 9984] = \"NEAREST_MIPMAP_NEAREST\";\n ETextureFilterType[ETextureFilterType[\"LINEAR_MIPMAP_NEAREST\"] = 9985] = \"LINEAR_MIPMAP_NEAREST\";\n ETextureFilterType[ETextureFilterType[\"NEAREST_MIPMAP_LINEAR\"] = 9986] = \"NEAREST_MIPMAP_LINEAR\";\n ETextureFilterType[ETextureFilterType[\"LINEAR_MIPMAP_LINEAR\"] = 9987] = \"LINEAR_MIPMAP_LINEAR\";\n})(ETextureFilterType || (ETextureFilterType = {}));\n/** @internal */\nexport var ETextureFormat;\n(function (ETextureFormat) {\n ETextureFormat[ETextureFormat[\"ALPHA\"] = 6406] = \"ALPHA\";\n ETextureFormat[ETextureFormat[\"RGB\"] = 6407] = \"RGB\";\n ETextureFormat[ETextureFormat[\"RGBA\"] = 6408] = \"RGBA\";\n ETextureFormat[ETextureFormat[\"LUMINANCE\"] = 6409] = \"LUMINANCE\";\n ETextureFormat[ETextureFormat[\"LUMINANCE_ALPHA\"] = 6410] = \"LUMINANCE_ALPHA\";\n})(ETextureFormat || (ETextureFormat = {}));\n/** @internal */\nexport var ECullingType;\n(function (ECullingType) {\n ECullingType[ECullingType[\"FRONT\"] = 1028] = \"FRONT\";\n ECullingType[ECullingType[\"BACK\"] = 1029] = \"BACK\";\n ECullingType[ECullingType[\"FRONT_AND_BACK\"] = 1032] = \"FRONT_AND_BACK\";\n})(ECullingType || (ECullingType = {}));\n/** @internal */\nexport var EBlendingFunction;\n(function (EBlendingFunction) {\n EBlendingFunction[EBlendingFunction[\"ZERO\"] = 0] = \"ZERO\";\n EBlendingFunction[EBlendingFunction[\"ONE\"] = 1] = \"ONE\";\n EBlendingFunction[EBlendingFunction[\"SRC_COLOR\"] = 768] = \"SRC_COLOR\";\n EBlendingFunction[EBlendingFunction[\"ONE_MINUS_SRC_COLOR\"] = 769] = \"ONE_MINUS_SRC_COLOR\";\n EBlendingFunction[EBlendingFunction[\"DST_COLOR\"] = 774] = \"DST_COLOR\";\n EBlendingFunction[EBlendingFunction[\"ONE_MINUS_DST_COLOR\"] = 775] = \"ONE_MINUS_DST_COLOR\";\n EBlendingFunction[EBlendingFunction[\"SRC_ALPHA\"] = 770] = \"SRC_ALPHA\";\n EBlendingFunction[EBlendingFunction[\"ONE_MINUS_SRC_ALPHA\"] = 771] = \"ONE_MINUS_SRC_ALPHA\";\n EBlendingFunction[EBlendingFunction[\"DST_ALPHA\"] = 772] = \"DST_ALPHA\";\n EBlendingFunction[EBlendingFunction[\"ONE_MINUS_DST_ALPHA\"] = 773] = \"ONE_MINUS_DST_ALPHA\";\n EBlendingFunction[EBlendingFunction[\"CONSTANT_COLOR\"] = 32769] = \"CONSTANT_COLOR\";\n EBlendingFunction[EBlendingFunction[\"ONE_MINUS_CONSTANT_COLOR\"] = 32770] = \"ONE_MINUS_CONSTANT_COLOR\";\n EBlendingFunction[EBlendingFunction[\"CONSTANT_ALPHA\"] = 32771] = \"CONSTANT_ALPHA\";\n EBlendingFunction[EBlendingFunction[\"ONE_MINUS_CONSTANT_ALPHA\"] = 32772] = \"ONE_MINUS_CONSTANT_ALPHA\";\n EBlendingFunction[EBlendingFunction[\"SRC_ALPHA_SATURATE\"] = 776] = \"SRC_ALPHA_SATURATE\";\n})(EBlendingFunction || (EBlendingFunction = {}));\n//# sourceMappingURL=glTFLoaderInterfaces.js.map","import { EParameterType, ETextureFilterType, ECullingType, EBlendingFunction, EShaderType } from \"./glTFLoaderInterfaces.js\";\nimport { Quaternion, Vector3, Matrix } from \"@babylonjs/core/Maths/math.vector.js\";\nimport { Color3 } from \"@babylonjs/core/Maths/math.color.js\";\nimport { Tools } from \"@babylonjs/core/Misc/tools.js\";\nimport { Camera } from \"@babylonjs/core/Cameras/camera.js\";\nimport { FreeCamera } from \"@babylonjs/core/Cameras/freeCamera.js\";\nimport { Animation } from \"@babylonjs/core/Animations/animation.js\";\nimport { Bone } from \"@babylonjs/core/Bones/bone.js\";\nimport { Skeleton } from \"@babylonjs/core/Bones/skeleton.js\";\nimport { Effect } from \"@babylonjs/core/Materials/effect.js\";\nimport { Material } from \"@babylonjs/core/Materials/material.js\";\nimport { MultiMaterial } from \"@babylonjs/core/Materials/multiMaterial.js\";\nimport { StandardMaterial } from \"@babylonjs/core/Materials/standardMaterial.js\";\nimport { ShaderMaterial } from \"@babylonjs/core/Materials/shaderMaterial.js\";\nimport { Texture } from \"@babylonjs/core/Materials/Textures/texture.js\";\nimport { VertexData } from \"@babylonjs/core/Meshes/mesh.vertexData.js\";\nimport { VertexBuffer } from \"@babylonjs/core/Buffers/buffer.js\";\nimport { Geometry } from \"@babylonjs/core/Meshes/geometry.js\";\nimport { SubMesh } from \"@babylonjs/core/Meshes/subMesh.js\";\nimport { AbstractMesh } from \"@babylonjs/core/Meshes/abstractMesh.js\";\nimport { Mesh } from \"@babylonjs/core/Meshes/mesh.js\";\nimport { HemisphericLight } from \"@babylonjs/core/Lights/hemisphericLight.js\";\nimport { DirectionalLight } from \"@babylonjs/core/Lights/directionalLight.js\";\nimport { PointLight } from \"@babylonjs/core/Lights/pointLight.js\";\nimport { SpotLight } from \"@babylonjs/core/Lights/spotLight.js\";\nimport { GLTFUtils } from \"./glTFLoaderUtils.js\";\nimport { GLTFFileLoader } from \"../glTFFileLoader.js\";\nimport { Constants } from \"@babylonjs/core/Engines/constants.js\";\n/**\n * Tokenizer. Used for shaders compatibility\n * Automatically map world, view, projection, worldViewProjection, attributes and so on\n */\nvar ETokenType;\n(function (ETokenType) {\n ETokenType[ETokenType[\"IDENTIFIER\"] = 1] = \"IDENTIFIER\";\n ETokenType[ETokenType[\"UNKNOWN\"] = 2] = \"UNKNOWN\";\n ETokenType[ETokenType[\"END_OF_INPUT\"] = 3] = \"END_OF_INPUT\";\n})(ETokenType || (ETokenType = {}));\nclass Tokenizer {\n constructor(toParse) {\n this._pos = 0;\n this.currentToken = ETokenType.UNKNOWN;\n this.currentIdentifier = \"\";\n this.currentString = \"\";\n this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;\n this._toParse = toParse;\n this._maxPos = toParse.length;\n }\n getNextToken() {\n if (this.isEnd()) {\n return ETokenType.END_OF_INPUT;\n }\n this.currentString = this.read();\n this.currentToken = ETokenType.UNKNOWN;\n if (this.currentString === \"_\" || this.isLetterOrDigitPattern.test(this.currentString)) {\n this.currentToken = ETokenType.IDENTIFIER;\n this.currentIdentifier = this.currentString;\n while (!this.isEnd() && (this.isLetterOrDigitPattern.test((this.currentString = this.peek())) || this.currentString === \"_\")) {\n this.currentIdentifier += this.currentString;\n this.forward();\n }\n }\n return this.currentToken;\n }\n peek() {\n return this._toParse[this._pos];\n }\n read() {\n return this._toParse[this._pos++];\n }\n forward() {\n this._pos++;\n }\n isEnd() {\n return this._pos >= this._maxPos;\n }\n}\n/**\n * Values\n */\nconst glTFTransforms = [\"MODEL\", \"VIEW\", \"PROJECTION\", \"MODELVIEW\", \"MODELVIEWPROJECTION\", \"JOINTMATRIX\"];\nconst babylonTransforms = [\"world\", \"view\", \"projection\", \"worldView\", \"worldViewProjection\", \"mBones\"];\nconst glTFAnimationPaths = [\"translation\", \"rotation\", \"scale\"];\nconst babylonAnimationPaths = [\"position\", \"rotationQuaternion\", \"scaling\"];\n/**\n * Parse\n * @param parsedBuffers\n * @param gltfRuntime\n */\nconst parseBuffers = (parsedBuffers, gltfRuntime) => {\n for (const buf in parsedBuffers) {\n const parsedBuffer = parsedBuffers[buf];\n gltfRuntime.buffers[buf] = parsedBuffer;\n gltfRuntime.buffersCount++;\n }\n};\nconst parseShaders = (parsedShaders, gltfRuntime) => {\n for (const sha in parsedShaders) {\n const parsedShader = parsedShaders[sha];\n gltfRuntime.shaders[sha] = parsedShader;\n gltfRuntime.shaderscount++;\n }\n};\nconst parseObject = (parsedObjects, runtimeProperty, gltfRuntime) => {\n for (const object in parsedObjects) {\n const parsedObject = parsedObjects[object];\n gltfRuntime[runtimeProperty][object] = parsedObject;\n }\n};\n/**\n * Utils\n * @param buffer\n */\nconst normalizeUVs = (buffer) => {\n if (!buffer) {\n return;\n }\n for (let i = 0; i < buffer.length / 2; i++) {\n buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];\n }\n};\nconst getAttribute = (attributeParameter) => {\n if (attributeParameter.semantic === \"NORMAL\") {\n return \"normal\";\n }\n else if (attributeParameter.semantic === \"POSITION\") {\n return \"position\";\n }\n else if (attributeParameter.semantic === \"JOINT\") {\n return \"matricesIndices\";\n }\n else if (attributeParameter.semantic === \"WEIGHT\") {\n return \"matricesWeights\";\n }\n else if (attributeParameter.semantic === \"COLOR\") {\n return \"color\";\n }\n else if (attributeParameter.semantic && attributeParameter.semantic.indexOf(\"TEXCOORD_\") !== -1) {\n const channel = Number(attributeParameter.semantic.split(\"_\")[1]);\n return \"uv\" + (channel === 0 ? \"\" : channel + 1);\n }\n return null;\n};\n/**\n * Loads and creates animations\n * @param gltfRuntime\n */\nconst loadAnimations = (gltfRuntime) => {\n for (const anim in gltfRuntime.animations) {\n const animation = gltfRuntime.animations[anim];\n if (!animation.channels || !animation.samplers) {\n continue;\n }\n let lastAnimation = null;\n for (let i = 0; i < animation.channels.length; i++) {\n // Get parameters and load buffers\n const channel = animation.channels[i];\n const sampler = animation.samplers[channel.sampler];\n if (!sampler) {\n continue;\n }\n let inputData = null;\n let outputData = null;\n if (animation.parameters) {\n inputData = animation.parameters[sampler.input];\n outputData = animation.parameters[sampler.output];\n }\n else {\n inputData = sampler.input;\n outputData = sampler.output;\n }\n const bufferInput = GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);\n const bufferOutput = GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);\n const targetId = channel.target.id;\n let targetNode = gltfRuntime.scene.getNodeById(targetId);\n if (targetNode === null) {\n targetNode = gltfRuntime.scene.getNodeByName(targetId);\n }\n if (targetNode === null) {\n Tools.Warn(\"Creating animation named \" + anim + \". But cannot find node named \" + targetId + \" to attach to\");\n continue;\n }\n const isBone = targetNode instanceof Bone;\n // Get target path (position, rotation or scaling)\n let targetPath = channel.target.path;\n const targetPathIndex = glTFAnimationPaths.indexOf(targetPath);\n if (targetPathIndex !== -1) {\n targetPath = babylonAnimationPaths[targetPathIndex];\n }\n // Determine animation type\n let animationType = Animation.ANIMATIONTYPE_MATRIX;\n if (!isBone) {\n if (targetPath === \"rotationQuaternion\") {\n animationType = Animation.ANIMATIONTYPE_QUATERNION;\n targetNode.rotationQuaternion = new Quaternion();\n }\n else {\n animationType = Animation.ANIMATIONTYPE_VECTOR3;\n }\n }\n // Create animation and key frames\n let babylonAnimation = null;\n const keys = [];\n let arrayOffset = 0;\n let modifyKey = false;\n if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {\n babylonAnimation = lastAnimation;\n modifyKey = true;\n }\n if (!modifyKey) {\n gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;\n babylonAnimation = new Animation(anim, isBone ? \"_matrix\" : targetPath, 1, animationType, Animation.ANIMATIONLOOPMODE_CYCLE);\n gltfRuntime.scene._blockEntityCollection = false;\n }\n // For each frame\n for (let j = 0; j < bufferInput.length; j++) {\n let value = null;\n if (targetPath === \"rotationQuaternion\") {\n // VEC4\n value = Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);\n arrayOffset += 4;\n }\n else {\n // Position and scaling are VEC3\n value = Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);\n arrayOffset += 3;\n }\n if (isBone) {\n const bone = targetNode;\n let translation = Vector3.Zero();\n let rotationQuaternion = new Quaternion();\n let scaling = Vector3.Zero();\n // Warning on decompose\n let mat = bone.getBaseMatrix();\n if (modifyKey && lastAnimation) {\n mat = lastAnimation.getKeys()[j].value;\n }\n mat.decompose(scaling, rotationQuaternion, translation);\n if (targetPath === \"position\") {\n translation = value;\n }\n else if (targetPath === \"rotationQuaternion\") {\n rotationQuaternion = value;\n }\n else {\n scaling = value;\n }\n value = Matrix.Compose(scaling, rotationQuaternion, translation);\n }\n if (!modifyKey) {\n keys.push({\n frame: bufferInput[j],\n value: value,\n });\n }\n else if (lastAnimation) {\n lastAnimation.getKeys()[j].value = value;\n }\n }\n // Finish\n if (!modifyKey && babylonAnimation) {\n babylonAnimation.setKeys(keys);\n targetNode.animations.push(babylonAnimation);\n }\n lastAnimation = babylonAnimation;\n gltfRuntime.scene.stopAnimation(targetNode);\n gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);\n }\n }\n};\n/**\n * Returns the bones transformation matrix\n * @param node\n */\nconst configureBoneTransformation = (node) => {\n let mat = null;\n if (node.translation || node.rotation || node.scale) {\n const scale = Vector3.FromArray(node.scale || [1, 1, 1]);\n const rotation = Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);\n const position = Vector3.FromArray(node.translation || [0, 0, 0]);\n mat = Matrix.Compose(scale, rotation, position);\n }\n else {\n mat = Matrix.FromArray(node.matrix);\n }\n return mat;\n};\n/**\n * Returns the parent bone\n * @param gltfRuntime\n * @param skins\n * @param jointName\n * @param newSkeleton\n */\nconst getParentBone = (gltfRuntime, skins, jointName, newSkeleton) => {\n // Try to find\n for (let i = 0; i < newSkeleton.bones.length; i++) {\n if (newSkeleton.bones[i].name === jointName) {\n return newSkeleton.bones[i];\n }\n }\n // Not found, search in gltf nodes\n const nodes = gltfRuntime.nodes;\n for (const nde in nodes) {\n const node = nodes[nde];\n if (!node.jointName) {\n continue;\n }\n const children = node.children;\n for (let i = 0; i < children.length; i++) {\n const child = gltfRuntime.nodes[children[i]];\n if (!child.jointName) {\n continue;\n }\n if (child.jointName === jointName) {\n const mat = configureBoneTransformation(node);\n const bone = new Bone(node.name || \"\", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);\n bone.id = nde;\n return bone;\n }\n }\n }\n return null;\n};\n/**\n * Returns the appropriate root node\n * @param nodesToRoot\n * @param id\n */\nconst getNodeToRoot = (nodesToRoot, id) => {\n for (let i = 0; i < nodesToRoot.length; i++) {\n const nodeToRoot = nodesToRoot[i];\n for (let j = 0; j < nodeToRoot.node.children.length; j++) {\n const child = nodeToRoot.node.children[j];\n if (child === id) {\n return nodeToRoot.bone;\n }\n }\n }\n return null;\n};\n/**\n * Returns the node with the joint name\n * @param gltfRuntime\n * @param jointName\n */\nconst getJointNode = (gltfRuntime, jointName) => {\n const nodes = gltfRuntime.nodes;\n let node = nodes[jointName];\n if (node) {\n return {\n node: node,\n id: jointName,\n };\n }\n for (const nde in nodes) {\n node = nodes[nde];\n if (node.jointName === jointName) {\n return {\n node: node,\n id: nde,\n };\n }\n }\n return null;\n};\n/**\n * Checks if a nodes is in joints\n * @param skins\n * @param id\n */\nconst nodeIsInJoints = (skins, id) => {\n for (let i = 0; i < skins.jointNames.length; i++) {\n if (skins.jointNames[i] === id) {\n return true;\n }\n }\n return false;\n};\n/**\n * Fills the nodes to root for bones and builds hierarchy\n * @param gltfRuntime\n * @param newSkeleton\n * @param skins\n * @param nodesToRoot\n */\nconst getNodesToRoot = (gltfRuntime, newSkeleton, skins, nodesToRoot) => {\n // Creates nodes for root\n for (const nde in gltfRuntime.nodes) {\n const node = gltfRuntime.nodes[nde];\n const id = nde;\n if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {\n continue;\n }\n // Create node to root bone\n const mat = configureBoneTransformation(node);\n const bone = new Bone(node.name || \"\", newSkeleton, null, mat);\n bone.id = id;\n nodesToRoot.push({ bone: bone, node: node, id: id });\n }\n // Parenting\n for (let i = 0; i < nodesToRoot.length; i++) {\n const nodeToRoot = nodesToRoot[i];\n const children = nodeToRoot.node.children;\n for (let j = 0; j < children.length; j++) {\n let child = null;\n for (let k = 0; k < nodesToRoot.length; k++) {\n if (nodesToRoot[k].id === children[j]) {\n child = nodesToRoot[k];\n break;\n }\n }\n if (child) {\n child.bone._parent = nodeToRoot.bone;\n nodeToRoot.bone.children.push(child.bone);\n }\n }\n }\n};\n/**\n * Imports a skeleton\n * @param gltfRuntime\n * @param skins\n * @param mesh\n * @param newSkeleton\n */\nconst importSkeleton = (gltfRuntime, skins, mesh, newSkeleton) => {\n if (!newSkeleton) {\n newSkeleton = new Skeleton(skins.name || \"\", \"\", gltfRuntime.scene);\n }\n if (!skins.babylonSkeleton) {\n return newSkeleton;\n }\n // Find the root bones\n const nodesToRoot = [];\n const nodesToRootToAdd = [];\n getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);\n newSkeleton.bones = [];\n // Joints\n for (let i = 0; i < skins.jointNames.length; i++) {\n const jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);\n if (!jointNode) {\n continue;\n }\n const node = jointNode.node;\n if (!node) {\n Tools.Warn(\"Joint named \" + skins.jointNames[i] + \" does not exist\");\n continue;\n }\n const id = jointNode.id;\n // Optimize, if the bone already exists...\n const existingBone = gltfRuntime.scene.getBoneById(id);\n if (existingBone) {\n newSkeleton.bones.push(existingBone);\n continue;\n }\n // Search for parent bone\n let foundBone = false;\n let parentBone = null;\n for (let j = 0; j < i; j++) {\n const jointNode = getJointNode(gltfRuntime, skins.jointNames[j]);\n if (!jointNode) {\n continue;\n }\n const joint = jointNode.node;\n if (!joint) {\n Tools.Warn(\"Joint named \" + skins.jointNames[j] + \" does not exist when looking for parent\");\n continue;\n }\n const children = joint.children;\n if (!children) {\n continue;\n }\n foundBone = false;\n for (let k = 0; k < children.length; k++) {\n if (children[k] === id) {\n parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);\n foundBone = true;\n break;\n }\n }\n if (foundBone) {\n break;\n }\n }\n // Create bone\n const mat = configureBoneTransformation(node);\n if (!parentBone && nodesToRoot.length > 0) {\n parentBone = getNodeToRoot(nodesToRoot, id);\n if (parentBone) {\n if (nodesToRootToAdd.indexOf(parentBone) === -1) {\n nodesToRootToAdd.push(parentBone);\n }\n }\n }\n const bone = new Bone(node.jointName || \"\", newSkeleton, parentBone, mat);\n bone.id = id;\n }\n // Polish\n const bones = newSkeleton.bones;\n newSkeleton.bones = [];\n for (let i = 0; i < skins.jointNames.length; i++) {\n const jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);\n if (!jointNode) {\n continue;\n }\n for (let j = 0; j < bones.length; j++) {\n if (bones[j].id === jointNode.id) {\n newSkeleton.bones.push(bones[j]);\n break;\n }\n }\n }\n newSkeleton.prepare();\n // Finish\n for (let i = 0; i < nodesToRootToAdd.length; i++) {\n newSkeleton.bones.push(nodesToRootToAdd[i]);\n }\n return newSkeleton;\n};\n/**\n * Imports a mesh and its geometries\n * @param gltfRuntime\n * @param node\n * @param meshes\n * @param id\n * @param newMesh\n */\nconst importMesh = (gltfRuntime, node, meshes, id, newMesh) => {\n if (!newMesh) {\n gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;\n newMesh = new Mesh(node.name || \"\", gltfRuntime.scene);\n newMesh._parentContainer = gltfRuntime.assetContainer;\n gltfRuntime.scene._blockEntityCollection = false;\n newMesh.id = id;\n }\n if (!node.babylonNode) {\n return newMesh;\n }\n const subMaterials = [];\n let vertexData = null;\n const verticesStarts = new Array();\n const verticesCounts = new Array();\n const indexStarts = new Array();\n const indexCounts = new Array();\n for (let meshIndex = 0; meshIndex < meshes.length; meshIndex++) {\n const meshId = meshes[meshIndex];\n const mesh = gltfRuntime.meshes[meshId];\n if (!mesh) {\n continue;\n }\n // Positions, normals and UVs\n for (let i = 0; i < mesh.primitives.length; i++) {\n // Temporary vertex data\n const tempVertexData = new VertexData();\n const primitive = mesh.primitives[i];\n if (primitive.mode !== 4) {\n // continue;\n }\n const attributes = primitive.attributes;\n let accessor = null;\n let buffer = null;\n // Set positions, normal and uvs\n for (const semantic in attributes) {\n // Link accessor and buffer view\n accessor = gltfRuntime.accessors[attributes[semantic]];\n buffer = GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);\n if (semantic === \"NORMAL\") {\n tempVertexData.normals = new Float32Array(buffer.length);\n tempVertexData.normals.set(buffer);\n }\n else if (semantic === \"POSITION\") {\n if (GLTFFileLoader.HomogeneousCoordinates) {\n tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);\n for (let j = 0; j < buffer.length; j += 4) {\n tempVertexData.positions[j] = buffer[j];\n tempVertexData.positions[j + 1] = buffer[j + 1];\n tempVertexData.positions[j + 2] = buffer[j + 2];\n }\n }\n else {\n tempVertexData.positions = new Float32Array(buffer.length);\n tempVertexData.positions.set(buffer);\n }\n verticesCounts.push(tempVertexData.positions.length);\n }\n else if (semantic.indexOf(\"TEXCOORD_\") !== -1) {\n const channel = Number(semantic.split(\"_\")[1]);\n const uvKind = VertexBuffer.UVKind + (channel === 0 ? \"\" : channel + 1);\n const uvs = new Float32Array(buffer.length);\n uvs.set(buffer);\n normalizeUVs(uvs);\n tempVertexData.set(uvs, uvKind);\n }\n else if (semantic === \"JOINT\") {\n tempVertexData.matricesIndices = new Float32Array(buffer.length);\n tempVertexData.matricesIndices.set(buffer);\n }\n else if (semantic === \"WEIGHT\") {\n tempVertexData.matricesWeights = new Float32Array(buffer.length);\n tempVertexData.matricesWeights.set(buffer);\n }\n else if (semantic === \"COLOR\") {\n tempVertexData.colors = new Float32Array(buffer.length);\n tempVertexData.colors.set(buffer);\n }\n }\n // Indices\n accessor = gltfRuntime.accessors[primitive.indices];\n if (accessor) {\n buffer = GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);\n tempVertexData.indices = new Int32Array(buffer.length);\n tempVertexData.indices.set(buffer);\n indexCounts.push(tempVertexData.indices.length);\n }\n else {\n // Set indices on the fly\n const indices = [];\n for (let j = 0; j < tempVertexData.positions.length / 3; j++) {\n indices.push(j);\n }\n tempVertexData.indices = new Int32Array(indices);\n indexCounts.push(tempVertexData.indices.length);\n }\n if (!vertexData) {\n vertexData = tempVertexData;\n }\n else {\n vertexData.merge(tempVertexData);\n }\n // Sub material\n const material = gltfRuntime.scene.getMaterialById(primitive.material);\n subMaterials.push(material === null ? GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);\n // Update vertices start and index start\n verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);\n indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);\n }\n }\n let material;\n gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;\n if (subMaterials.length > 1) {\n material = new MultiMaterial(\"multimat\" + id, gltfRuntime.scene);\n material.subMaterials = subMaterials;\n }\n else {\n material = new StandardMaterial(\"multimat\" + id, gltfRuntime.scene);\n }\n if (subMaterials.length === 1) {\n material = subMaterials[0];\n }\n material._parentContainer = gltfRuntime.assetContainer;\n if (!newMesh.material) {\n newMesh.material = material;\n }\n // Apply geometry\n new Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);\n newMesh.computeWorldMatrix(true);\n gltfRuntime.scene._blockEntityCollection = false;\n // Apply submeshes\n newMesh.subMeshes = [];\n let index = 0;\n for (let meshIndex = 0; meshIndex < meshes.length; meshIndex++) {\n const meshId = meshes[meshIndex];\n const mesh = gltfRuntime.meshes[meshId];\n if (!mesh) {\n continue;\n }\n for (let i = 0; i < mesh.primitives.length; i++) {\n if (mesh.primitives[i].mode !== 4) {\n //continue;\n }\n SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);\n index++;\n }\n }\n // Finish\n return newMesh;\n};\n/**\n * Configure node transformation from position, rotation and scaling\n * @param newNode\n * @param position\n * @param rotation\n * @param scaling\n */\nconst configureNode = (newNode, position, rotation, scaling) => {\n if (newNode.position) {\n newNode.position = position;\n }\n if (newNode.rotationQuaternion || newNode.rotation) {\n newNode.rotationQuaternion = rotation;\n }\n if (newNode.scaling) {\n newNode.scaling = scaling;\n }\n};\n/**\n * Configures node from transformation matrix\n * @param newNode\n * @param node\n */\nconst configureNodeFromMatrix = (newNode, node) => {\n if (node.matrix) {\n const position = new Vector3(0, 0, 0);\n const rotation = new Quaternion();\n const scaling = new Vector3(0, 0, 0);\n const mat = Matrix.FromArray(node.matrix);\n mat.decompose(scaling, rotation, position);\n configureNode(newNode, position, rotation, scaling);\n }\n else if (node.translation && node.rotation && node.scale) {\n configureNode(newNode, Vector3.FromArray(node.translation), Quaternion.FromArray(node.rotation), Vector3.FromArray(node.scale));\n }\n newNode.computeWorldMatrix(true);\n};\n/**\n * Imports a node\n * @param gltfRuntime\n * @param node\n * @param id\n */\nconst importNode = (gltfRuntime, node, id) => {\n let lastNode = null;\n if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {\n if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || \"\") === -1) {\n return null;\n }\n }\n // Meshes\n if (node.skin) {\n if (node.meshes) {\n const skin = gltfRuntime.skins[node.skin];\n const newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);\n newMesh.skeleton = gltfRuntime.scene.getLastSkeletonById(node.skin);\n if (newMesh.skeleton === null) {\n newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton);\n if (!skin.babylonSkeleton) {\n skin.babylonSkeleton = newMesh.skeleton;\n }\n }\n lastNode = newMesh;\n }\n }\n else if (node.meshes) {\n /**\n * Improve meshes property\n */\n const newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);\n lastNode = newMesh;\n }\n // Lights\n else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {\n const light = gltfRuntime.lights[node.light];\n if (light) {\n if (light.type === \"ambient\") {\n const ambienLight = light[light.type];\n const hemiLight = new HemisphericLight(node.light, Vector3.Zero(), gltfRuntime.scene);\n hemiLight.name = node.name || \"\";\n if (ambienLight.color) {\n hemiLight.diffuse = Color3.FromArray(ambienLight.color);\n }\n lastNode = hemiLight;\n }\n else if (light.type === \"directional\") {\n const directionalLight = light[light.type];\n const dirLight = new DirectionalLight(node.light, Vector3.Zero(), gltfRuntime.scene);\n dirLight.name = node.name || \"\";\n if (directionalLight.color) {\n dirLight.diffuse = Color3.FromArray(directionalLight.color);\n }\n lastNode = dirLight;\n }\n else if (light.type === \"point\") {\n const pointLight = light[light.type];\n const ptLight = new PointLight(node.light, Vector3.Zero(), gltfRuntime.scene);\n ptLight.name = node.name || \"\";\n if (pointLight.color) {\n ptLight.diffuse = Color3.FromArray(pointLight.color);\n }\n lastNode = ptLight;\n }\n else if (light.type === \"spot\") {\n const spotLight = light[light.type];\n const spLight = new SpotLight(node.light, Vector3.Zero(), Vector3.Zero(), 0, 0, gltfRuntime.scene);\n spLight.name = node.name || \"\";\n if (spotLight.color) {\n spLight.diffuse = Color3.FromArray(spotLight.color);\n }\n if (spotLight.fallOfAngle) {\n spLight.angle = spotLight.fallOfAngle;\n }\n if (spotLight.fallOffExponent) {\n spLight.exponent = spotLight.fallOffExponent;\n }\n lastNode = spLight;\n }\n }\n }\n // Cameras\n else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {\n const camera = gltfRuntime.cameras[node.camera];\n if (camera) {\n gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;\n if (camera.type === \"orthographic\") {\n const orthoCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene, false);\n orthoCamera.name = node.name || \"\";\n orthoCamera.mode = Camera.ORTHOGRAPHIC_CAMERA;\n orthoCamera.attachControl();\n lastNode = orthoCamera;\n orthoCamera._parentContainer = gltfRuntime.assetContainer;\n }\n else if (camera.type === \"perspective\") {\n const perspectiveCamera = camera[camera.type];\n const persCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene, false);\n persCamera.name = node.name || \"\";\n persCamera.attachControl();\n if (!perspectiveCamera.aspectRatio) {\n perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();\n }\n if (perspectiveCamera.znear && perspectiveCamera.zfar) {\n persCamera.maxZ = perspectiveCamera.zfar;\n persCamera.minZ = perspectiveCamera.znear;\n }\n lastNode = persCamera;\n persCamera._parentContainer = gltfRuntime.assetContainer;\n }\n gltfRuntime.scene._blockEntityCollection = false;\n }\n }\n // Empty node\n if (!node.jointName) {\n if (node.babylonNode) {\n return node.babylonNode;\n }\n else if (lastNode === null) {\n gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;\n const dummy = new Mesh(node.name || \"\", gltfRuntime.scene);\n dummy._parentContainer = gltfRuntime.assetContainer;\n gltfRuntime.scene._blockEntityCollection = false;\n node.babylonNode = dummy;\n lastNode = dummy;\n }\n }\n if (lastNode !== null) {\n if (node.matrix && lastNode instanceof Mesh) {\n configureNodeFromMatrix(lastNode, node);\n }\n else {\n const translation = node.translation || [0, 0, 0];\n const rotation = node.rotation || [0, 0, 0, 1];\n const scale = node.scale || [1, 1, 1];\n configureNode(lastNode, Vector3.FromArray(translation), Quaternion.FromArray(rotation), Vector3.FromArray(scale));\n }\n lastNode.updateCache(true);\n node.babylonNode = lastNode;\n }\n return lastNode;\n};\n/**\n * Traverses nodes and creates them\n * @param gltfRuntime\n * @param id\n * @param parent\n * @param meshIncluded\n */\nconst traverseNodes = (gltfRuntime, id, parent, meshIncluded = false) => {\n const node = gltfRuntime.nodes[id];\n let newNode = null;\n if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {\n if (gltfRuntime.importMeshesNames.indexOf(node.name || \"\") !== -1 || gltfRuntime.importMeshesNames.length === 0) {\n meshIncluded = true;\n }\n else {\n meshIncluded = false;\n }\n }\n else {\n meshIncluded = true;\n }\n if (!node.jointName && meshIncluded) {\n newNode = importNode(gltfRuntime, node, id);\n if (newNode !== null) {\n newNode.id = id;\n newNode.parent = parent;\n }\n }\n if (node.children) {\n for (let i = 0; i < node.children.length; i++) {\n traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);\n }\n }\n};\n/**\n * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)\n * @param gltfRuntime\n */\nconst postLoad = (gltfRuntime) => {\n // Nodes\n let currentScene = gltfRuntime.currentScene;\n if (currentScene) {\n for (let i = 0; i < currentScene.nodes.length; i++) {\n traverseNodes(gltfRuntime, currentScene.nodes[i], null);\n }\n }\n else {\n for (const thing in gltfRuntime.scenes) {\n currentScene = gltfRuntime.scenes[thing];\n for (let i = 0; i < currentScene.nodes.length; i++) {\n traverseNodes(gltfRuntime, currentScene.nodes[i], null);\n }\n }\n }\n // Set animations\n loadAnimations(gltfRuntime);\n for (let i = 0; i < gltfRuntime.scene.skeletons.length; i++) {\n const skeleton = gltfRuntime.scene.skeletons[i];\n gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);\n }\n};\n/**\n * onBind shaderrs callback to set uniforms and matrices\n * @param mesh\n * @param gltfRuntime\n * @param unTreatedUniforms\n * @param shaderMaterial\n * @param technique\n * @param material\n * @param onSuccess\n */\nconst onBindShaderMaterial = (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) => {\n const materialValues = material.values || technique.parameters;\n for (const unif in unTreatedUniforms) {\n const uniform = unTreatedUniforms[unif];\n const type = uniform.type;\n if (type === EParameterType.FLOAT_MAT2 || type === EParameterType.FLOAT_MAT3 || type === EParameterType.FLOAT_MAT4) {\n if (uniform.semantic && !uniform.source && !uniform.node) {\n GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());\n }\n else if (uniform.semantic && (uniform.source || uniform.node)) {\n let source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || \"\");\n if (source === null) {\n source = gltfRuntime.scene.getNodeById(uniform.source || uniform.node || \"\");\n }\n if (source === null) {\n continue;\n }\n GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());\n }\n }\n else {\n const value = materialValues[technique.uniforms[unif]];\n if (!value) {\n continue;\n }\n if (type === EParameterType.SAMPLER_2D) {\n const texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;\n if (texture === null || texture === undefined) {\n continue;\n }\n shaderMaterial.getEffect().setTexture(unif, texture);\n }\n else {\n GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);\n }\n }\n }\n onSuccess(shaderMaterial);\n};\n/**\n * Prepare uniforms to send the only one time\n * Loads the appropriate textures\n * @param gltfRuntime\n * @param shaderMaterial\n * @param technique\n * @param material\n */\nconst prepareShaderMaterialUniforms = (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) => {\n const materialValues = material.values || technique.parameters;\n const techniqueUniforms = technique.uniforms;\n /**\n * Prepare values here (not matrices)\n */\n for (const unif in unTreatedUniforms) {\n const uniform = unTreatedUniforms[unif];\n const type = uniform.type;\n let value = materialValues[techniqueUniforms[unif]];\n if (value === undefined) {\n // In case the value is the same for all materials\n value = uniform.value;\n }\n if (!value) {\n continue;\n }\n const onLoadTexture = (uniformName) => {\n return (texture) => {\n if (uniform.value && uniformName) {\n // Static uniform\n shaderMaterial.setTexture(uniformName, texture);\n delete unTreatedUniforms[uniformName];\n }\n };\n };\n // Texture (sampler2D)\n if (type === EParameterType.SAMPLER_2D) {\n GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), () => onLoadTexture(null));\n }\n // Others\n else {\n if (uniform.value && GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {\n // Static uniform\n delete unTreatedUniforms[unif];\n }\n }\n }\n};\n/**\n * Shader compilation failed\n * @param program\n * @param shaderMaterial\n * @param onError\n */\nconst onShaderCompileError = (program, shaderMaterial, onError) => {\n return (effect, error) => {\n shaderMaterial.dispose(true);\n onError(\"Cannot compile program named \" + program.name + \". Error: \" + error + \". Default material will be applied\");\n };\n};\n/**\n * Shader compilation success\n * @param gltfRuntime\n * @param shaderMaterial\n * @param technique\n * @param material\n * @param unTreatedUniforms\n * @param onSuccess\n */\nconst onShaderCompileSuccess = (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) => {\n return (_) => {\n prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);\n shaderMaterial.onBind = (mesh) => {\n onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);\n };\n };\n};\n/**\n * Returns the appropriate uniform if already handled by babylon\n * @param tokenizer\n * @param technique\n */\nconst parseShaderUniforms = (tokenizer, technique, unTreatedUniforms) => {\n for (const unif in technique.uniforms) {\n const uniform = technique.uniforms[unif];\n const uniformParameter = technique.parameters[uniform];\n if (tokenizer.currentIdentifier === unif) {\n if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {\n const transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);\n if (transformIndex !== -1) {\n delete unTreatedUniforms[unif];\n return babylonTransforms[transformIndex];\n }\n }\n }\n }\n return tokenizer.currentIdentifier;\n};\n/**\n * All shaders loaded. Create materials one by one\n * @param gltfRuntime\n */\nconst importMaterials = (gltfRuntime) => {\n // Create materials\n for (const mat in gltfRuntime.materials) {\n GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, () => { }, () => { });\n }\n};\n/**\n * Implementation of the base glTF spec\n * @internal\n */\nexport class GLTFLoaderBase {\n static CreateRuntime(parsedData, scene, rootUrl) {\n const gltfRuntime = {\n extensions: {},\n accessors: {},\n buffers: {},\n bufferViews: {},\n meshes: {},\n lights: {},\n cameras: {},\n nodes: {},\n images: {},\n textures: {},\n shaders: {},\n programs: {},\n samplers: {},\n techniques: {},\n materials: {},\n animations: {},\n skins: {},\n extensionsUsed: [],\n scenes: {},\n buffersCount: 0,\n shaderscount: 0,\n scene: scene,\n rootUrl: rootUrl,\n loadedBufferCount: 0,\n loadedBufferViews: {},\n loadedShaderCount: 0,\n importOnlyMeshes: false,\n dummyNodes: [],\n assetContainer: null,\n };\n // Parse\n if (parsedData.extensions) {\n parseObject(parsedData.extensions, \"extensions\", gltfRuntime);\n }\n if (parsedData.extensionsUsed) {\n parseObject(parsedData.extensionsUsed, \"extensionsUsed\", gltfRuntime);\n }\n if (parsedData.buffers) {\n parseBuffers(parsedData.buffers, gltfRuntime);\n }\n if (parsedData.bufferViews) {\n parseObject(parsedData.bufferViews, \"bufferViews\", gltfRuntime);\n }\n if (parsedData.accessors) {\n parseObject(parsedData.accessors, \"accessors\", gltfRuntime);\n }\n if (parsedData.meshes) {\n parseObject(parsedData.meshes, \"meshes\", gltfRuntime);\n }\n if (parsedData.lights) {\n parseObject(parsedData.lights, \"lights\", gltfRuntime);\n }\n if (parsedData.cameras) {\n parseObject(parsedData.cameras, \"cameras\", gltfRuntime);\n }\n if (parsedData.nodes) {\n parseObject(parsedData.nodes, \"nodes\", gltfRuntime);\n }\n if (parsedData.images) {\n parseObject(parsedData.images, \"images\", gltfRuntime);\n }\n if (parsedData.textures) {\n parseObject(parsedData.textures, \"textures\", gltfRuntime);\n }\n if (parsedData.shaders) {\n parseShaders(parsedData.shaders, gltfRuntime);\n }\n if (parsedData.programs) {\n parseObject(parsedData.programs, \"programs\", gltfRuntime);\n }\n if (parsedData.samplers) {\n parseObject(parsedData.samplers, \"samplers\", gltfRuntime);\n }\n if (parsedData.techniques) {\n parseObject(parsedData.techniques, \"techniques\", gltfRuntime);\n }\n if (parsedData.materials) {\n parseObject(parsedData.materials, \"materials\", gltfRuntime);\n }\n if (parsedData.animations) {\n parseObject(parsedData.animations, \"animations\", gltfRuntime);\n }\n if (parsedData.skins) {\n parseObject(parsedData.skins, \"skins\", gltfRuntime);\n }\n if (parsedData.scenes) {\n gltfRuntime.scenes = parsedData.scenes;\n }\n if (parsedData.scene && parsedData.scenes) {\n gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];\n }\n return gltfRuntime;\n }\n static LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress) {\n const buffer = gltfRuntime.buffers[id];\n if (Tools.IsBase64(buffer.uri)) {\n setTimeout(() => onSuccess(new Uint8Array(Tools.DecodeBase64(buffer.uri))));\n }\n else {\n Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, (data) => onSuccess(new Uint8Array(data)), onProgress, undefined, true, (request) => {\n if (request) {\n onError(request.status + \" \" + request.statusText);\n }\n });\n }\n }\n static LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError) {\n const texture = gltfRuntime.textures[id];\n if (!texture || !texture.source) {\n onError(\"\");\n return;\n }\n if (texture.babylonTexture) {\n onSuccess(null);\n return;\n }\n const source = gltfRuntime.images[texture.source];\n if (Tools.IsBase64(source.uri)) {\n setTimeout(() => onSuccess(new Uint8Array(Tools.DecodeBase64(source.uri))));\n }\n else {\n Tools.LoadFile(gltfRuntime.rootUrl + source.uri, (data) => onSuccess(new Uint8Array(data)), undefined, undefined, true, (request) => {\n if (request) {\n onError(request.status + \" \" + request.statusText);\n }\n });\n }\n }\n static CreateTextureAsync(gltfRuntime, id, buffer, onSuccess) {\n const texture = gltfRuntime.textures[id];\n if (texture.babylonTexture) {\n onSuccess(texture.babylonTexture);\n return;\n }\n const sampler = gltfRuntime.samplers[texture.sampler];\n const createMipMaps = sampler.minFilter === ETextureFilterType.NEAREST_MIPMAP_NEAREST ||\n sampler.minFilter === ETextureFilterType.NEAREST_MIPMAP_LINEAR ||\n sampler.minFilter === ETextureFilterType.LINEAR_MIPMAP_NEAREST ||\n sampler.minFilter === ETextureFilterType.LINEAR_MIPMAP_LINEAR;\n const samplingMode = Texture.BILINEAR_SAMPLINGMODE;\n const blob = buffer == null ? new Blob() : new Blob([buffer]);\n const blobURL = URL.createObjectURL(blob);\n const revokeBlobURL = () => URL.revokeObjectURL(blobURL);\n const newTexture = new Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);\n if (sampler.wrapS !== undefined) {\n newTexture.wrapU = GLTFUtils.GetWrapMode(sampler.wrapS);\n }\n if (sampler.wrapT !== undefined) {\n newTexture.wrapV = GLTFUtils.GetWrapMode(sampler.wrapT);\n }\n newTexture.name = id;\n texture.babylonTexture = newTexture;\n onSuccess(newTexture);\n }\n static LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError) {\n const shader = gltfRuntime.shaders[id];\n if (Tools.IsBase64(shader.uri)) {\n const shaderString = atob(shader.uri.split(\",\")[1]);\n if (onSuccess) {\n onSuccess(shaderString);\n }\n }\n else {\n Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, (request) => {\n if (request && onError) {\n onError(request.status + \" \" + request.statusText);\n }\n });\n }\n }\n static LoadMaterialAsync(gltfRuntime, id, onSuccess, onError) {\n const material = gltfRuntime.materials[id];\n if (!material.technique) {\n if (onError) {\n onError(\"No technique found.\");\n }\n return;\n }\n const technique = gltfRuntime.techniques[material.technique];\n if (!technique) {\n gltfRuntime.scene._blockEntityCollection = !!gltfRuntime.assetContainer;\n const defaultMaterial = new StandardMaterial(id, gltfRuntime.scene);\n defaultMaterial._parentContainer = gltfRuntime.assetContainer;\n gltfRuntime.scene._blockEntityCollection = false;\n defaultMaterial.diffuseColor = new Color3(0.5, 0.5, 0.5);\n defaultMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;\n onSuccess(defaultMaterial);\n return;\n }\n const program = gltfRuntime.programs[technique.program];\n const states = technique.states;\n const vertexShader = Effect.ShadersStore[program.vertexShader + \"VertexShader\"];\n const pixelShader = Effect.ShadersStore[program.fragmentShader + \"PixelShader\"];\n let newVertexShader = \"\";\n let newPixelShader = \"\";\n const vertexTokenizer = new Tokenizer(vertexShader);\n const pixelTokenizer = new Tokenizer(pixelShader);\n const unTreatedUniforms = {};\n const uniforms = [];\n const attributes = [];\n const samplers = [];\n // Fill uniform, sampler2D and attributes\n for (const unif in technique.uniforms) {\n const uniform = technique.uniforms[unif];\n const uniformParameter = technique.parameters[uniform];\n unTreatedUniforms[unif] = uniformParameter;\n if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {\n const transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);\n if (transformIndex !== -1) {\n uniforms.push(babylonTransforms[transformIndex]);\n delete unTreatedUniforms[unif];\n }\n else {\n uniforms.push(unif);\n }\n }\n else if (uniformParameter.type === EParameterType.SAMPLER_2D) {\n samplers.push(unif);\n }\n else {\n uniforms.push(unif);\n }\n }\n for (const attr in technique.attributes) {\n const attribute = technique.attributes[attr];\n const attributeParameter = technique.parameters[attribute];\n if (attributeParameter.semantic) {\n const name = getAttribute(attributeParameter);\n if (name) {\n attributes.push(name);\n }\n }\n }\n // Configure vertex shader\n while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {\n const tokenType = vertexTokenizer.currentToken;\n if (tokenType !== ETokenType.IDENTIFIER) {\n newVertexShader += vertexTokenizer.currentString;\n continue;\n }\n let foundAttribute = false;\n for (const attr in technique.attributes) {\n const attribute = technique.attributes[attr];\n const attributeParameter = technique.parameters[attribute];\n if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {\n newVertexShader += getAttribute(attributeParameter);\n foundAttribute = true;\n break;\n }\n }\n if (foundAttribute) {\n continue;\n }\n newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);\n }\n // Configure pixel shader\n while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {\n const tokenType = pixelTokenizer.currentToken;\n if (tokenType !== ETokenType.IDENTIFIER) {\n newPixelShader += pixelTokenizer.currentString;\n continue;\n }\n newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);\n }\n // Create shader material\n const shaderPath = {\n vertex: program.vertexShader + id,\n fragment: program.fragmentShader + id,\n };\n const options = {\n attributes: attributes,\n uniforms: uniforms,\n samplers: samplers,\n needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1,\n };\n Effect.ShadersStore[program.vertexShader + id + \"VertexShader\"] = newVertexShader;\n Effect.ShadersStore[program.fragmentShader + id + \"PixelShader\"] = newPixelShader;\n const shaderMaterial = new ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);\n shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);\n shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);\n shaderMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;\n if (states && states.functions) {\n const functions = states.functions;\n if (functions.cullFace && functions.cullFace[0] !== ECullingType.BACK) {\n shaderMaterial.backFaceCulling = false;\n }\n const blendFunc = functions.blendFuncSeparate;\n if (blendFunc) {\n if (blendFunc[0] === EBlendingFunction.SRC_ALPHA &&\n blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_ALPHA &&\n blendFunc[2] === EBlendingFunction.ONE &&\n blendFunc[3] === EBlendingFunction.ONE) {\n shaderMaterial.alphaMode = Constants.ALPHA_COMBINE;\n }\n else if (blendFunc[0] === EBlendingFunction.ONE &&\n blendFunc[1] === EBlendingFunction.ONE &&\n blendFunc[2] === EBlendingFunction.ZERO &&\n blendFunc[3] === EBlendingFunction.ONE) {\n shaderMaterial.alphaMode = Constants.ALPHA_ONEONE;\n }\n else if (blendFunc[0] === EBlendingFunction.SRC_ALPHA &&\n blendFunc[1] === EBlendingFunction.ONE &&\n blendFunc[2] === EBlendingFunction.ZERO &&\n blendFunc[3] === EBlendingFunction.ONE) {\n shaderMaterial.alphaMode = Constants.ALPHA_ADD;\n }\n else if (blendFunc[0] === EBlendingFunction.ZERO &&\n blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR &&\n blendFunc[2] === EBlendingFunction.ONE &&\n blendFunc[3] === EBlendingFunction.ONE) {\n shaderMaterial.alphaMode = Constants.ALPHA_SUBTRACT;\n }\n else if (blendFunc[0] === EBlendingFunction.DST_COLOR &&\n blendFunc[1] === EBlendingFunction.ZERO &&\n blendFunc[2] === EBlendingFunction.ONE &&\n blendFunc[3] === EBlendingFunction.ONE) {\n shaderMaterial.alphaMode = Constants.ALPHA_MULTIPLY;\n }\n else if (blendFunc[0] === EBlendingFunction.SRC_ALPHA &&\n blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR &&\n blendFunc[2] === EBlendingFunction.ONE &&\n blendFunc[3] === EBlendingFunction.ONE) {\n shaderMaterial.alphaMode = Constants.ALPHA_MAXIMIZED;\n }\n }\n }\n }\n}\n/**\n * glTF V1 Loader\n * @internal\n * @deprecated\n */\nexport class GLTFLoader {\n static RegisterExtension(extension) {\n if (GLTFLoader.Extensions[extension.name]) {\n Tools.Error('Tool with the same name \"' + extension.name + '\" already exists');\n return;\n }\n GLTFLoader.Extensions[extension.name] = extension;\n }\n dispose() {\n // do nothing\n }\n _importMeshAsync(meshesNames, scene, data, rootUrl, assetContainer, onSuccess, onProgress, onError) {\n scene.useRightHandedSystem = true;\n GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, (gltfRuntime) => {\n gltfRuntime.assetContainer = assetContainer;\n gltfRuntime.importOnlyMeshes = true;\n if (meshesNames === \"\") {\n gltfRuntime.importMeshesNames = [];\n }\n else if (typeof meshesNames === \"string\") {\n gltfRuntime.importMeshesNames = [meshesNames];\n }\n else if (meshesNames && !(meshesNames instanceof Array)) {\n gltfRuntime.importMeshesNames = [meshesNames];\n }\n else {\n gltfRuntime.importMeshesNames = [];\n Tools.Warn(\"Argument meshesNames must be of type string or string[]\");\n }\n // Create nodes\n this._createNodes(gltfRuntime);\n const meshes = new Array();\n const skeletons = new Array();\n // Fill arrays of meshes and skeletons\n for (const nde in gltfRuntime.nodes) {\n const node = gltfRuntime.nodes[nde];\n if (node.babylonNode instanceof AbstractMesh) {\n meshes.push(node.babylonNode);\n }\n }\n for (const skl in gltfRuntime.skins) {\n const skin = gltfRuntime.skins[skl];\n if (skin.babylonSkeleton instanceof Skeleton) {\n skeletons.push(skin.babylonSkeleton);\n }\n }\n // Load buffers, shaders, materials, etc.\n this._loadBuffersAsync(gltfRuntime, () => {\n this._loadShadersAsync(gltfRuntime, () => {\n importMaterials(gltfRuntime);\n postLoad(gltfRuntime);\n if (!GLTFFileLoader.IncrementalLoading && onSuccess) {\n onSuccess(meshes, skeletons);\n }\n });\n });\n if (GLTFFileLoader.IncrementalLoading && onSuccess) {\n onSuccess(meshes, skeletons);\n }\n }, onError);\n return true;\n }\n /**\n * Imports one or more meshes from a loaded gltf file and adds them to the scene\n * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file\n * @param scene the scene the meshes should be added to\n * @param assetContainer defines the asset container to use (can be null)\n * @param data gltf data containing information of the meshes in a loaded file\n * @param rootUrl root url to load from\n * @param onProgress event that fires when loading progress has occured\n * @returns a promise containg the loaded meshes, particles, skeletons and animations\n */\n importMeshAsync(meshesNames, scene, assetContainer, data, rootUrl, onProgress) {\n return new Promise((resolve, reject) => {\n this._importMeshAsync(meshesNames, scene, data, rootUrl, assetContainer, (meshes, skeletons) => {\n resolve({\n meshes: meshes,\n particleSystems: [],\n skeletons: skeletons,\n animationGroups: [],\n lights: [],\n transformNodes: [],\n geometries: [],\n });\n }, onProgress, (message) => {\n reject(new Error(message));\n });\n });\n }\n _loadAsync(scene, data, rootUrl, onSuccess, onProgress, onError) {\n scene.useRightHandedSystem = true;\n GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, (gltfRuntime) => {\n // Load runtime extensios\n GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, () => {\n // Create nodes\n this._createNodes(gltfRuntime);\n // Load buffers, shaders, materials, etc.\n this._loadBuffersAsync(gltfRuntime, () => {\n this._loadShadersAsync(gltfRuntime, () => {\n importMaterials(gltfRuntime);\n postLoad(gltfRuntime);\n if (!GLTFFileLoader.IncrementalLoading) {\n onSuccess();\n }\n });\n });\n if (GLTFFileLoader.IncrementalLoading) {\n onSuccess();\n }\n }, onError);\n }, onError);\n }\n /**\n * Imports all objects from a loaded gltf file and adds them to the scene\n * @param scene the scene the objects should be added to\n * @param data gltf data containing information of the meshes in a loaded file\n * @param rootUrl root url to load from\n * @param onProgress event that fires when loading progress has occured\n * @returns a promise which completes when objects have been loaded to the scene\n */\n loadAsync(scene, data, rootUrl, onProgress) {\n return new Promise((resolve, reject) => {\n this._loadAsync(scene, data, rootUrl, () => {\n resolve();\n }, onProgress, (message) => {\n reject(new Error(message));\n });\n });\n }\n _loadShadersAsync(gltfRuntime, onload) {\n let hasShaders = false;\n const processShader = (sha, shader) => {\n GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, (shaderString) => {\n if (shaderString instanceof ArrayBuffer) {\n return;\n }\n gltfRuntime.loadedShaderCount++;\n if (shaderString) {\n Effect.ShadersStore[sha + (shader.type === EShaderType.VERTEX ? \"VertexShader\" : \"PixelShader\")] = shaderString;\n }\n if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {\n onload();\n }\n }, () => {\n Tools.Error(\"Error when loading shader program named \" + sha + \" located at \" + shader.uri);\n });\n };\n for (const sha in gltfRuntime.shaders) {\n hasShaders = true;\n const shader = gltfRuntime.shaders[sha];\n if (shader) {\n processShader.bind(this, sha, shader)();\n }\n else {\n Tools.Error(\"No shader named: \" + sha);\n }\n }\n if (!hasShaders) {\n onload();\n }\n }\n _loadBuffersAsync(gltfRuntime, onLoad) {\n let hasBuffers = false;\n const processBuffer = (buf, buffer) => {\n GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, (bufferView) => {\n gltfRuntime.loadedBufferCount++;\n if (bufferView) {\n if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {\n Tools.Error(\"Buffer named \" + buf + \" is length \" + bufferView.byteLength + \". Expected: \" + buffer.byteLength); // Improve error message\n }\n gltfRuntime.loadedBufferViews[buf] = bufferView;\n }\n if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {\n onLoad();\n }\n }, () => {\n Tools.Error(\"Error when loading buffer named \" + buf + \" located at \" + buffer.uri);\n });\n };\n for (const buf in gltfRuntime.buffers) {\n hasBuffers = true;\n const buffer = gltfRuntime.buffers[buf];\n if (buffer) {\n processBuffer.bind(this, buf, buffer)();\n }\n else {\n Tools.Error(\"No buffer named: \" + buf);\n }\n }\n if (!hasBuffers) {\n onLoad();\n }\n }\n _createNodes(gltfRuntime) {\n let currentScene = gltfRuntime.currentScene;\n if (currentScene) {\n // Only one scene even if multiple scenes are defined\n for (let i = 0; i < currentScene.nodes.length; i++) {\n traverseNodes(gltfRuntime, currentScene.nodes[i], null);\n }\n }\n else {\n // Load all scenes\n for (const thing in gltfRuntime.scenes) {\n currentScene = gltfRuntime.scenes[thing];\n for (let i = 0; i < currentScene.nodes.length; i++) {\n traverseNodes(gltfRuntime, currentScene.nodes[i], null);\n }\n }\n }\n }\n}\nGLTFLoader.Extensions = {};\n/** @internal */\nexport class GLTFLoaderExtension {\n constructor(name) {\n this._name = name;\n }\n get name() {\n return this._name;\n }\n /**\n * Defines an override for loading the runtime\n * Return true to stop further extensions from loading the runtime\n * @param scene\n * @param data\n * @param rootUrl\n * @param onSuccess\n * @param onError\n */\n loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError) {\n return false;\n }\n /**\n * Defines an onverride for creating gltf runtime\n * Return true to stop further extensions from creating the runtime\n * @param gltfRuntime\n * @param onSuccess\n * @param onError\n */\n loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError) {\n return false;\n }\n /**\n * Defines an override for loading buffers\n * Return true to stop further extensions from loading this buffer\n * @param gltfRuntime\n * @param id\n * @param onSuccess\n * @param onError\n * @param onProgress\n */\n loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress) {\n return false;\n }\n /**\n * Defines an override for loading texture buffers\n * Return true to stop further extensions from loading this texture data\n * @param gltfRuntime\n * @param id\n * @param onSuccess\n * @param onError\n */\n loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError) {\n return false;\n }\n /**\n * Defines an override for creating textures\n * Return true to stop further extensions from loading this texture\n * @param gltfRuntime\n * @param id\n * @param buffer\n * @param onSuccess\n * @param onError\n */\n createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError) {\n return false;\n }\n /**\n * Defines an override for loading shader strings\n * Return true to stop further extensions from loading this shader data\n * @param gltfRuntime\n * @param id\n * @param onSuccess\n * @param onError\n */\n loadShaderStringAsync(gltfRuntime, id, onSuccess, onError) {\n return false;\n }\n /**\n * Defines an override for loading materials\n * Return true to stop further extensions from loading this material\n * @param gltfRuntime\n * @param id\n * @param onSuccess\n * @param onError\n */\n loadMaterialAsync(gltfRuntime, id, onSuccess, onError) {\n return false;\n }\n // ---------\n // Utilities\n // ---------\n static LoadRuntimeAsync(scene, data, rootUrl, onSuccess, onError) {\n GLTFLoaderExtension._ApplyExtensions((loaderExtension) => {\n return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);\n }, () => {\n setTimeout(() => {\n if (!onSuccess) {\n return;\n }\n onSuccess(GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));\n });\n });\n }\n static LoadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError) {\n GLTFLoaderExtension._ApplyExtensions((loaderExtension) => {\n return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);\n }, () => {\n setTimeout(() => {\n onSuccess();\n });\n });\n }\n static LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress) {\n GLTFLoaderExtension._ApplyExtensions((loaderExtension) => {\n return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);\n }, () => {\n GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);\n });\n }\n static LoadTextureAsync(gltfRuntime, id, onSuccess, onError) {\n GLTFLoaderExtension._LoadTextureBufferAsync(gltfRuntime, id, (buffer) => {\n if (buffer) {\n GLTFLoaderExtension._CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);\n }\n }, onError);\n }\n static LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError) {\n GLTFLoaderExtension._ApplyExtensions((loaderExtension) => {\n return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);\n }, () => {\n GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);\n });\n }\n static LoadMaterialAsync(gltfRuntime, id, onSuccess, onError) {\n GLTFLoaderExtension._ApplyExtensions((loaderExtension) => {\n return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);\n }, () => {\n GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);\n });\n }\n static _LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError) {\n GLTFLoaderExtension._ApplyExtensions((loaderExtension) => {\n return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);\n }, () => {\n GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);\n });\n }\n static _CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError) {\n GLTFLoaderExtension._ApplyExtensions((loaderExtension) => {\n return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);\n }, () => {\n GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess);\n });\n }\n static _ApplyExtensions(func, defaultFunc) {\n for (const extensionName in GLTFLoader.Extensions) {\n const loaderExtension = GLTFLoader.Extensions[extensionName];\n if (func(loaderExtension)) {\n return;\n }\n }\n defaultFunc();\n }\n}\nGLTFFileLoader._CreateGLTF1Loader = () => new GLTFLoader();\n//# sourceMappingURL=glTFLoader.js.map","import { GLTFLoaderExtension, GLTFLoader, GLTFLoaderBase } from \"./glTFLoader.js\";\nimport { GLTFUtils } from \"./glTFLoaderUtils.js\";\nimport { EComponentType } from \"./glTFLoaderInterfaces.js\";\nconst BinaryExtensionBufferName = \"binary_glTF\";\n/**\n * @internal\n * @deprecated\n */\nexport class GLTFBinaryExtension extends GLTFLoaderExtension {\n constructor() {\n super(\"KHR_binary_glTF\");\n }\n loadRuntimeAsync(scene, data, rootUrl, onSuccess) {\n const extensionsUsed = data.json.extensionsUsed;\n if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {\n return false;\n }\n this._bin = data.bin;\n onSuccess(GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));\n return true;\n }\n loadBufferAsync(gltfRuntime, id, onSuccess, onError) {\n if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {\n return false;\n }\n if (id !== BinaryExtensionBufferName) {\n return false;\n }\n this._bin.readAsync(0, this._bin.byteLength).then(onSuccess, (error) => onError(error.message));\n return true;\n }\n loadTextureBufferAsync(gltfRuntime, id, onSuccess) {\n const texture = gltfRuntime.textures[id];\n const source = gltfRuntime.images[texture.source];\n if (!source.extensions || !(this.name in source.extensions)) {\n return false;\n }\n const sourceExt = source.extensions[this.name];\n const bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];\n const buffer = GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, EComponentType.UNSIGNED_BYTE);\n onSuccess(buffer);\n return true;\n }\n loadShaderStringAsync(gltfRuntime, id, onSuccess) {\n const shader = gltfRuntime.shaders[id];\n if (!shader.extensions || !(this.name in shader.extensions)) {\n return false;\n }\n const binaryExtensionShader = shader.extensions[this.name];\n const bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];\n const shaderBytes = GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, EComponentType.UNSIGNED_BYTE);\n setTimeout(() => {\n const shaderString = GLTFUtils.DecodeBufferToText(shaderBytes);\n onSuccess(shaderString);\n });\n return true;\n }\n}\nGLTFLoader.RegisterExtension(new GLTFBinaryExtension());\n//# sourceMappingURL=glTFBinaryExtension.js.map","import { GLTFLoaderExtension, GLTFLoaderBase, GLTFLoader } from \"./glTFLoader.js\";\nimport { Vector3 } from \"@babylonjs/core/Maths/math.vector.js\";\nimport { Color3 } from \"@babylonjs/core/Maths/math.color.js\";\nimport { Tools } from \"@babylonjs/core/Misc/tools.js\";\nimport { Material } from \"@babylonjs/core/Materials/material.js\";\nimport { StandardMaterial } from \"@babylonjs/core/Materials/standardMaterial.js\";\nimport { HemisphericLight } from \"@babylonjs/core/Lights/hemisphericLight.js\";\nimport { DirectionalLight } from \"@babylonjs/core/Lights/directionalLight.js\";\nimport { PointLight } from \"@babylonjs/core/Lights/pointLight.js\";\nimport { SpotLight } from \"@babylonjs/core/Lights/spotLight.js\";\n/**\n * @internal\n * @deprecated\n */\nexport class GLTFMaterialsCommonExtension extends GLTFLoaderExtension {\n constructor() {\n super(\"KHR_materials_common\");\n }\n loadRuntimeExtensionsAsync(gltfRuntime) {\n if (!gltfRuntime.extensions) {\n return false;\n }\n const extension = gltfRuntime.extensions[this.name];\n if (!extension) {\n return false;\n }\n // Create lights\n const lights = extension.lights;\n if (lights) {\n for (const thing in lights) {\n const light = lights[thing];\n switch (light.type) {\n case \"ambient\": {\n const ambientLight = new HemisphericLight(light.name, new Vector3(0, 1, 0), gltfRuntime.scene);\n const ambient = light.ambient;\n if (ambient) {\n ambientLight.diffuse = Color3.FromArray(ambient.color || [1, 1, 1]);\n }\n break;\n }\n case \"point\": {\n const pointLight = new PointLight(light.name, new Vector3(10, 10, 10), gltfRuntime.scene);\n const point = light.point;\n if (point) {\n pointLight.diffuse = Color3.FromArray(point.color || [1, 1, 1]);\n }\n break;\n }\n case \"directional\": {\n const dirLight = new DirectionalLight(light.name, new Vector3(0, -1, 0), gltfRuntime.scene);\n const directional = light.directional;\n if (directional) {\n dirLight.diffuse = Color3.FromArray(directional.color || [1, 1, 1]);\n }\n break;\n }\n case \"spot\": {\n const spot = light.spot;\n if (spot) {\n const spotLight = new SpotLight(light.name, new Vector3(0, 10, 0), new Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);\n spotLight.diffuse = Color3.FromArray(spot.color || [1, 1, 1]);\n }\n break;\n }\n default:\n Tools.Warn('GLTF Material Common extension: light type \"' + light.type + \"” not supported\");\n break;\n }\n }\n }\n return false;\n }\n loadMaterialAsync(gltfRuntime, id, onSuccess, onError) {\n const material = gltfRuntime.materials[id];\n if (!material || !material.extensions) {\n return false;\n }\n const extension = material.extensions[this.name];\n if (!extension) {\n return false;\n }\n const standardMaterial = new StandardMaterial(id, gltfRuntime.scene);\n standardMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;\n if (extension.technique === \"CONSTANT\") {\n standardMaterial.disableLighting = true;\n }\n standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;\n standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;\n standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;\n // Ambient\n if (typeof extension.values.ambient === \"string\") {\n this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, \"ambientTexture\", onError);\n }\n else {\n standardMaterial.ambientColor = Color3.FromArray(extension.values.ambient || [0, 0, 0]);\n }\n // Diffuse\n if (typeof extension.values.diffuse === \"string\") {\n this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, \"diffuseTexture\", onError);\n }\n else {\n standardMaterial.diffuseColor = Color3.FromArray(extension.values.diffuse || [0, 0, 0]);\n }\n // Emission\n if (typeof extension.values.emission === \"string\") {\n this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, \"emissiveTexture\", onError);\n }\n else {\n standardMaterial.emissiveColor = Color3.FromArray(extension.values.emission || [0, 0, 0]);\n }\n // Specular\n if (typeof extension.values.specular === \"string\") {\n this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, \"specularTexture\", onError);\n }\n else {\n standardMaterial.specularColor = Color3.FromArray(extension.values.specular || [0, 0, 0]);\n }\n return true;\n }\n _loadTexture(gltfRuntime, id, material, propertyPath, onError) {\n // Create buffer from texture url\n GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, (buffer) => {\n // Create texture from buffer\n GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, (texture) => (material[propertyPath] = texture));\n }, onError);\n }\n}\nGLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());\n//# sourceMappingURL=glTFMaterialsCommonExtension.js.map","export * from \"./glTFBinaryExtension.js\";\nexport * from \"./glTFLoader.js\";\nexport * from \"./glTFLoaderInterfaces.js\";\nexport * from \"./glTFLoaderUtils.js\";\nexport * from \"./glTFMaterialsCommonExtension.js\";\n//# sourceMappingURL=index.js.map","import { Animation } from \"@babylonjs/core/Animations/animation.js\";\nimport { Quaternion, Vector3 } from \"@babylonjs/core/Maths/math.vector.js\";\n/** @internal */\nexport function getVector3(_target, source, offset, scale) {\n return Vector3.FromArray(source, offset).scaleInPlace(scale);\n}\n/** @internal */\nexport function getQuaternion(_target, source, offset, scale) {\n return Quaternion.FromArray(source, offset).scaleInPlace(scale);\n}\n/** @internal */\nexport function getWeights(target, source, offset, scale) {\n const value = new Array(target._numMorphTargets);\n for (let i = 0; i < value.length; i++) {\n value[i] = source[offset++] * scale;\n }\n return value;\n}\n/** @internal */\nexport class AnimationPropertyInfo {\n /** @internal */\n constructor(type, name, getValue, getStride) {\n this.type = type;\n this.name = name;\n this.getValue = getValue;\n this.getStride = getStride;\n }\n _buildAnimation(name, fps, keys) {\n const babylonAnimation = new Animation(name, this.name, fps, this.type);\n babylonAnimation.setKeys(keys);\n return babylonAnimation;\n }\n}\n/** @internal */\nexport class TransformNodeAnimationPropertyInfo extends AnimationPropertyInfo {\n /** @internal */\n buildAnimations(target, name, fps, keys, callback) {\n callback(target._babylonTransformNode, this._buildAnimation(name, fps, keys));\n }\n}\n/** @internal */\nexport class WeightAnimationPropertyInfo extends AnimationPropertyInfo {\n buildAnimations(target, name, fps, keys, callback) {\n if (target._numMorphTargets) {\n for (let targetIndex = 0; targetIndex < target._numMorphTargets; targetIndex++) {\n const babylonAnimation = new Animation(`${name}_${targetIndex}`, this.name, fps, this.type);\n babylonAnimation.setKeys(keys.map((key) => ({\n frame: key.frame,\n inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,\n value: key.value[targetIndex],\n outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined,\n interpolation: key.interpolation,\n })));\n if (target._primitiveBabylonMeshes) {\n for (const babylonMesh of target._primitiveBabylonMeshes) {\n if (babylonMesh.morphTargetManager) {\n const morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);\n const babylonAnimationClone = babylonAnimation.clone();\n morphTarget.animations.push(babylonAnimationClone);\n callback(morphTarget, babylonAnimationClone);\n }\n }\n }\n }\n }\n }\n}\n/** @internal */\nexport const nodeAnimationData = {\n translation: [new TransformNodeAnimationPropertyInfo(Animation.ANIMATIONTYPE_VECTOR3, \"position\", getVector3, () => 3)],\n rotation: [new TransformNodeAnimationPropertyInfo(Animation.ANIMATIONTYPE_QUATERNION, \"rotationQuaternion\", getQuaternion, () => 4)],\n scale: [new TransformNodeAnimationPropertyInfo(Animation.ANIMATIONTYPE_VECTOR3, \"scaling\", getVector3, () => 3)],\n weights: [new WeightAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"influence\", getWeights, (target) => target._numMorphTargets)],\n};\n//# sourceMappingURL=glTFLoaderAnimation.js.map","import { Deferred } from \"@babylonjs/core/Misc/deferred.js\";\nimport { Quaternion, Vector3, Matrix, TmpVectors } from \"@babylonjs/core/Maths/math.vector.js\";\nimport { Color3 } from \"@babylonjs/core/Maths/math.color.js\";\nimport { Tools } from \"@babylonjs/core/Misc/tools.js\";\nimport { Camera } from \"@babylonjs/core/Cameras/camera.js\";\nimport { FreeCamera } from \"@babylonjs/core/Cameras/freeCamera.js\";\nimport { AnimationKeyInterpolation } from \"@babylonjs/core/Animations/animationKey.js\";\nimport { AnimationGroup } from \"@babylonjs/core/Animations/animationGroup.js\";\nimport { Bone } from \"@babylonjs/core/Bones/bone.js\";\nimport { Skeleton } from \"@babylonjs/core/Bones/skeleton.js\";\nimport { Material } from \"@babylonjs/core/Materials/material.js\";\nimport { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { Texture } from \"@babylonjs/core/Materials/Textures/texture.js\";\nimport { TransformNode } from \"@babylonjs/core/Meshes/transformNode.js\";\nimport { Buffer, VertexBuffer } from \"@babylonjs/core/Buffers/buffer.js\";\nimport { Geometry } from \"@babylonjs/core/Meshes/geometry.js\";\nimport { Mesh } from \"@babylonjs/core/Meshes/mesh.js\";\nimport { MorphTarget } from \"@babylonjs/core/Morph/morphTarget.js\";\nimport { MorphTargetManager } from \"@babylonjs/core/Morph/morphTargetManager.js\";\nimport { GLTFFileLoader, GLTFLoaderState, GLTFLoaderCoordinateSystemMode, GLTFLoaderAnimationStartMode } from \"../glTFFileLoader.js\";\nimport { DecodeBase64UrlToBinary, IsBase64DataUrl, LoadFileError } from \"@babylonjs/core/Misc/fileTools.js\";\nimport { Logger } from \"@babylonjs/core/Misc/logger.js\";\nimport { BoundingInfo } from \"@babylonjs/core/Culling/boundingInfo.js\";\nimport { nodeAnimationData } from \"./glTFLoaderAnimation.js\";\n// https://stackoverflow.com/a/48218209\nfunction mergeDeep(...objects) {\n const isObject = (obj) => obj && typeof obj === \"object\";\n return objects.reduce((prev, obj) => {\n Object.keys(obj).forEach((key) => {\n const pVal = prev[key];\n const oVal = obj[key];\n if (Array.isArray(pVal) && Array.isArray(oVal)) {\n prev[key] = pVal.concat(...oVal);\n }\n else if (isObject(pVal) && isObject(oVal)) {\n prev[key] = mergeDeep(pVal, oVal);\n }\n else {\n prev[key] = oVal;\n }\n });\n return prev;\n }, {});\n}\n/**\n * Helper class for working with arrays when loading the glTF asset\n */\nexport class ArrayItem {\n /**\n * Gets an item from the given array.\n * @param context The context when loading the asset\n * @param array The array to get the item from\n * @param index The index to the array\n * @returns The array item\n */\n static Get(context, array, index) {\n if (!array || index == undefined || !array[index]) {\n throw new Error(`${context}: Failed to find index (${index})`);\n }\n return array[index];\n }\n /**\n * Assign an `index` field to each item of the given array.\n * @param array The array of items\n */\n static Assign(array) {\n if (array) {\n for (let index = 0; index < array.length; index++) {\n array[index].index = index;\n }\n }\n }\n}\n/**\n * The glTF 2.0 loader\n */\nexport class GLTFLoader {\n /**\n * Registers a loader extension.\n * @param name The name of the loader extension.\n * @param factory The factory function that creates the loader extension.\n */\n static RegisterExtension(name, factory) {\n if (GLTFLoader.UnregisterExtension(name)) {\n Logger.Warn(`Extension with the name '${name}' already exists`);\n }\n GLTFLoader._RegisteredExtensions[name] = {\n factory: factory,\n };\n }\n /**\n * Unregisters a loader extension.\n * @param name The name of the loader extension.\n * @returns A boolean indicating whether the extension has been unregistered\n */\n static UnregisterExtension(name) {\n if (!GLTFLoader._RegisteredExtensions[name]) {\n return false;\n }\n delete GLTFLoader._RegisteredExtensions[name];\n return true;\n }\n /**\n * The object that represents the glTF JSON.\n */\n get gltf() {\n if (!this._gltf) {\n throw new Error(\"glTF JSON is not available\");\n }\n return this._gltf;\n }\n /**\n * The BIN chunk of a binary glTF.\n */\n get bin() {\n return this._bin;\n }\n /**\n * The parent file loader.\n */\n get parent() {\n return this._parent;\n }\n /**\n * The Babylon scene when loading the asset.\n */\n get babylonScene() {\n if (!this._babylonScene) {\n throw new Error(\"Scene is not available\");\n }\n return this._babylonScene;\n }\n /**\n * The root Babylon mesh when loading the asset.\n */\n get rootBabylonMesh() {\n return this._rootBabylonMesh;\n }\n /**\n * @internal\n */\n constructor(parent) {\n /** @internal */\n this._completePromises = new Array();\n /** @internal */\n this._assetContainer = null;\n /** Storage */\n this._babylonLights = [];\n /** @internal */\n this._disableInstancedMesh = 0;\n this._extensions = new Array();\n this._disposed = false;\n this._rootUrl = null;\n this._fileName = null;\n this._uniqueRootUrl = null;\n this._bin = null;\n this._rootBabylonMesh = null;\n this._defaultBabylonMaterialData = {};\n this._postSceneLoadActions = new Array();\n this._parent = parent;\n }\n /** @internal */\n dispose() {\n if (this._disposed) {\n return;\n }\n this._disposed = true;\n this._completePromises.length = 0;\n this._extensions.forEach((extension) => extension.dispose && extension.dispose());\n this._extensions.length = 0;\n this._gltf = null; // TODO\n this._bin = null;\n this._babylonScene = null; // TODO\n this._rootBabylonMesh = null;\n this._defaultBabylonMaterialData = {};\n this._postSceneLoadActions.length = 0;\n this._parent.dispose();\n }\n /**\n * @internal\n */\n importMeshAsync(meshesNames, scene, container, data, rootUrl, onProgress, fileName = \"\") {\n return Promise.resolve().then(() => {\n this._babylonScene = scene;\n this._assetContainer = container;\n this._loadData(data);\n let nodes = null;\n if (meshesNames) {\n const nodeMap = {};\n if (this._gltf.nodes) {\n for (const node of this._gltf.nodes) {\n if (node.name) {\n nodeMap[node.name] = node.index;\n }\n }\n }\n const names = meshesNames instanceof Array ? meshesNames : [meshesNames];\n nodes = names.map((name) => {\n const node = nodeMap[name];\n if (node === undefined) {\n throw new Error(`Failed to find node '${name}'`);\n }\n return node;\n });\n }\n return this._loadAsync(rootUrl, fileName, nodes, () => {\n return {\n meshes: this._getMeshes(),\n particleSystems: [],\n skeletons: this._getSkeletons(),\n animationGroups: this._getAnimationGroups(),\n lights: this._babylonLights,\n transformNodes: this._getTransformNodes(),\n geometries: this._getGeometries(),\n };\n });\n });\n }\n /**\n * @internal\n */\n loadAsync(scene, data, rootUrl, onProgress, fileName = \"\") {\n return Promise.resolve().then(() => {\n this._babylonScene = scene;\n this._loadData(data);\n return this._loadAsync(rootUrl, fileName, null, () => undefined);\n });\n }\n _loadAsync(rootUrl, fileName, nodes, resultFunc) {\n return Promise.resolve()\n .then(() => {\n this._rootUrl = rootUrl;\n this._uniqueRootUrl = !rootUrl.startsWith(\"file:\") && fileName ? rootUrl : `${rootUrl}${Date.now()}/`;\n this._fileName = fileName;\n this._loadExtensions();\n this._checkExtensions();\n const loadingToReadyCounterName = `${GLTFLoaderState[GLTFLoaderState.LOADING]} => ${GLTFLoaderState[GLTFLoaderState.READY]}`;\n const loadingToCompleteCounterName = `${GLTFLoaderState[GLTFLoaderState.LOADING]} => ${GLTFLoaderState[GLTFLoaderState.COMPLETE]}`;\n this._parent._startPerformanceCounter(loadingToReadyCounterName);\n this._parent._startPerformanceCounter(loadingToCompleteCounterName);\n this._parent._setState(GLTFLoaderState.LOADING);\n this._extensionsOnLoading();\n const promises = new Array();\n // Block the marking of materials dirty until the scene is loaded.\n const oldBlockMaterialDirtyMechanism = this._babylonScene.blockMaterialDirtyMechanism;\n this._babylonScene.blockMaterialDirtyMechanism = true;\n if (!this.parent.loadOnlyMaterials) {\n if (nodes) {\n promises.push(this.loadSceneAsync(\"/nodes\", { nodes: nodes, index: -1 }));\n }\n else if (this._gltf.scene != undefined || (this._gltf.scenes && this._gltf.scenes[0])) {\n const scene = ArrayItem.Get(`/scene`, this._gltf.scenes, this._gltf.scene || 0);\n promises.push(this.loadSceneAsync(`/scenes/${scene.index}`, scene));\n }\n }\n if (!this.parent.skipMaterials && this.parent.loadAllMaterials && this._gltf.materials) {\n for (let m = 0; m < this._gltf.materials.length; ++m) {\n const material = this._gltf.materials[m];\n const context = \"/materials/\" + m;\n const babylonDrawMode = Material.TriangleFillMode;\n promises.push(this._loadMaterialAsync(context, material, null, babylonDrawMode, () => { }));\n }\n }\n // Restore the blocking of material dirty.\n this._babylonScene.blockMaterialDirtyMechanism = oldBlockMaterialDirtyMechanism;\n if (this._parent.compileMaterials) {\n promises.push(this._compileMaterialsAsync());\n }\n if (this._parent.compileShadowGenerators) {\n promises.push(this._compileShadowGeneratorsAsync());\n }\n const resultPromise = Promise.all(promises).then(() => {\n if (this._rootBabylonMesh) {\n this._rootBabylonMesh.setEnabled(true);\n }\n this._extensionsOnReady();\n this._parent._setState(GLTFLoaderState.READY);\n this._startAnimations();\n return resultFunc();\n });\n return resultPromise.then((result) => {\n this._parent._endPerformanceCounter(loadingToReadyCounterName);\n Tools.SetImmediate(() => {\n if (!this._disposed) {\n Promise.all(this._completePromises).then(() => {\n this._parent._endPerformanceCounter(loadingToCompleteCounterName);\n this._parent._setState(GLTFLoaderState.COMPLETE);\n this._parent.onCompleteObservable.notifyObservers(undefined);\n this._parent.onCompleteObservable.clear();\n this.dispose();\n }, (error) => {\n this._parent.onErrorObservable.notifyObservers(error);\n this._parent.onErrorObservable.clear();\n this.dispose();\n });\n }\n });\n return result;\n });\n })\n .catch((error) => {\n if (!this._disposed) {\n this._parent.onErrorObservable.notifyObservers(error);\n this._parent.onErrorObservable.clear();\n this.dispose();\n }\n throw error;\n });\n }\n _loadData(data) {\n this._gltf = data.json;\n this._setupData();\n if (data.bin) {\n const buffers = this._gltf.buffers;\n if (buffers && buffers[0] && !buffers[0].uri) {\n const binaryBuffer = buffers[0];\n if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {\n Logger.Warn(`Binary buffer length (${binaryBuffer.byteLength}) from JSON does not match chunk length (${data.bin.byteLength})`);\n }\n this._bin = data.bin;\n }\n else {\n Logger.Warn(\"Unexpected BIN chunk\");\n }\n }\n }\n _setupData() {\n ArrayItem.Assign(this._gltf.accessors);\n ArrayItem.Assign(this._gltf.animations);\n ArrayItem.Assign(this._gltf.buffers);\n ArrayItem.Assign(this._gltf.bufferViews);\n ArrayItem.Assign(this._gltf.cameras);\n ArrayItem.Assign(this._gltf.images);\n ArrayItem.Assign(this._gltf.materials);\n ArrayItem.Assign(this._gltf.meshes);\n ArrayItem.Assign(this._gltf.nodes);\n ArrayItem.Assign(this._gltf.samplers);\n ArrayItem.Assign(this._gltf.scenes);\n ArrayItem.Assign(this._gltf.skins);\n ArrayItem.Assign(this._gltf.textures);\n if (this._gltf.nodes) {\n const nodeParents = {};\n for (const node of this._gltf.nodes) {\n if (node.children) {\n for (const index of node.children) {\n nodeParents[index] = node.index;\n }\n }\n }\n const rootNode = this._createRootNode();\n for (const node of this._gltf.nodes) {\n const parentIndex = nodeParents[node.index];\n node.parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];\n }\n }\n }\n _loadExtensions() {\n for (const name in GLTFLoader._RegisteredExtensions) {\n const extension = GLTFLoader._RegisteredExtensions[name].factory(this);\n if (extension.name !== name) {\n Logger.Warn(`The name of the glTF loader extension instance does not match the registered name: ${extension.name} !== ${name}`);\n }\n this._extensions.push(extension);\n this._parent.onExtensionLoadedObservable.notifyObservers(extension);\n }\n this._extensions.sort((a, b) => (a.order || Number.MAX_VALUE) - (b.order || Number.MAX_VALUE));\n this._parent.onExtensionLoadedObservable.clear();\n }\n _checkExtensions() {\n if (this._gltf.extensionsRequired) {\n for (const name of this._gltf.extensionsRequired) {\n const available = this._extensions.some((extension) => extension.name === name && extension.enabled);\n if (!available) {\n throw new Error(`Require extension ${name} is not available`);\n }\n }\n }\n }\n _createRootNode() {\n this._babylonScene._blockEntityCollection = !!this._assetContainer;\n this._rootBabylonMesh = new Mesh(\"__root__\", this._babylonScene);\n this._rootBabylonMesh._parentContainer = this._assetContainer;\n this._babylonScene._blockEntityCollection = false;\n this._rootBabylonMesh.setEnabled(false);\n const rootNode = {\n _babylonTransformNode: this._rootBabylonMesh,\n index: -1,\n };\n switch (this._parent.coordinateSystemMode) {\n case GLTFLoaderCoordinateSystemMode.AUTO: {\n if (!this._babylonScene.useRightHandedSystem) {\n rootNode.rotation = [0, 1, 0, 0];\n rootNode.scale = [1, 1, -1];\n GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);\n }\n break;\n }\n case GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {\n this._babylonScene.useRightHandedSystem = true;\n break;\n }\n default: {\n throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`);\n }\n }\n this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);\n return rootNode;\n }\n /**\n * Loads a glTF scene.\n * @param context The context when loading the asset\n * @param scene The glTF scene property\n * @returns A promise that resolves when the load is complete\n */\n loadSceneAsync(context, scene) {\n const extensionPromise = this._extensionsLoadSceneAsync(context, scene);\n if (extensionPromise) {\n return extensionPromise;\n }\n const promises = new Array();\n this.logOpen(`${context} ${scene.name || \"\"}`);\n if (scene.nodes) {\n for (const index of scene.nodes) {\n const node = ArrayItem.Get(`${context}/nodes/${index}`, this._gltf.nodes, index);\n promises.push(this.loadNodeAsync(`/nodes/${node.index}`, node, (babylonMesh) => {\n babylonMesh.parent = this._rootBabylonMesh;\n }));\n }\n }\n for (const action of this._postSceneLoadActions) {\n action();\n }\n promises.push(this._loadAnimationsAsync());\n this.logClose();\n return Promise.all(promises).then(() => { });\n }\n _forEachPrimitive(node, callback) {\n if (node._primitiveBabylonMeshes) {\n for (const babylonMesh of node._primitiveBabylonMeshes) {\n callback(babylonMesh);\n }\n }\n }\n _getGeometries() {\n const geometries = new Array();\n const nodes = this._gltf.nodes;\n if (nodes) {\n for (const node of nodes) {\n this._forEachPrimitive(node, (babylonMesh) => {\n const geometry = babylonMesh.geometry;\n if (geometry && geometries.indexOf(geometry) === -1) {\n geometries.push(geometry);\n }\n });\n }\n }\n return geometries;\n }\n _getMeshes() {\n const meshes = new Array();\n // Root mesh is always first, if available.\n if (this._rootBabylonMesh) {\n meshes.push(this._rootBabylonMesh);\n }\n const nodes = this._gltf.nodes;\n if (nodes) {\n for (const node of nodes) {\n this._forEachPrimitive(node, (babylonMesh) => {\n meshes.push(babylonMesh);\n });\n }\n }\n return meshes;\n }\n _getTransformNodes() {\n const transformNodes = new Array();\n const nodes = this._gltf.nodes;\n if (nodes) {\n for (const node of nodes) {\n if (node._babylonTransformNode && node._babylonTransformNode.getClassName() === \"TransformNode\") {\n transformNodes.push(node._babylonTransformNode);\n }\n if (node._babylonTransformNodeForSkin) {\n transformNodes.push(node._babylonTransformNodeForSkin);\n }\n }\n }\n return transformNodes;\n }\n _getSkeletons() {\n const skeletons = new Array();\n const skins = this._gltf.skins;\n if (skins) {\n for (const skin of skins) {\n if (skin._data) {\n skeletons.push(skin._data.babylonSkeleton);\n }\n }\n }\n return skeletons;\n }\n _getAnimationGroups() {\n const animationGroups = new Array();\n const animations = this._gltf.animations;\n if (animations) {\n for (const animation of animations) {\n if (animation._babylonAnimationGroup) {\n animationGroups.push(animation._babylonAnimationGroup);\n }\n }\n }\n return animationGroups;\n }\n _startAnimations() {\n switch (this._parent.animationStartMode) {\n case GLTFLoaderAnimationStartMode.NONE: {\n // do nothing\n break;\n }\n case GLTFLoaderAnimationStartMode.FIRST: {\n const babylonAnimationGroups = this._getAnimationGroups();\n if (babylonAnimationGroups.length !== 0) {\n babylonAnimationGroups[0].start(true);\n }\n break;\n }\n case GLTFLoaderAnimationStartMode.ALL: {\n const babylonAnimationGroups = this._getAnimationGroups();\n for (const babylonAnimationGroup of babylonAnimationGroups) {\n babylonAnimationGroup.start(true);\n }\n break;\n }\n default: {\n Logger.Error(`Invalid animation start mode (${this._parent.animationStartMode})`);\n return;\n }\n }\n }\n /**\n * Loads a glTF node.\n * @param context The context when loading the asset\n * @param node The glTF node property\n * @param assign A function called synchronously after parsing the glTF properties\n * @returns A promise that resolves with the loaded Babylon mesh when the load is complete\n */\n loadNodeAsync(context, node, assign = () => { }) {\n const extensionPromise = this._extensionsLoadNodeAsync(context, node, assign);\n if (extensionPromise) {\n return extensionPromise;\n }\n if (node._babylonTransformNode) {\n throw new Error(`${context}: Invalid recursive node hierarchy`);\n }\n const promises = new Array();\n this.logOpen(`${context} ${node.name || \"\"}`);\n const loadNode = (babylonTransformNode) => {\n GLTFLoader.AddPointerMetadata(babylonTransformNode, context);\n GLTFLoader._LoadTransform(node, babylonTransformNode);\n if (node.camera != undefined) {\n const camera = ArrayItem.Get(`${context}/camera`, this._gltf.cameras, node.camera);\n promises.push(this.loadCameraAsync(`/cameras/${camera.index}`, camera, (babylonCamera) => {\n babylonCamera.parent = babylonTransformNode;\n }));\n }\n if (node.children) {\n for (const index of node.children) {\n const childNode = ArrayItem.Get(`${context}/children/${index}`, this._gltf.nodes, index);\n promises.push(this.loadNodeAsync(`/nodes/${childNode.index}`, childNode, (childBabylonMesh) => {\n childBabylonMesh.parent = babylonTransformNode;\n }));\n }\n }\n assign(babylonTransformNode);\n };\n if (node.mesh == undefined || node.skin != undefined) {\n const nodeName = node.name || `node${node.index}`;\n this._babylonScene._blockEntityCollection = !!this._assetContainer;\n const transformNode = new TransformNode(nodeName, this._babylonScene);\n transformNode._parentContainer = this._assetContainer;\n this._babylonScene._blockEntityCollection = false;\n if (node.mesh == undefined) {\n node._babylonTransformNode = transformNode;\n }\n else {\n node._babylonTransformNodeForSkin = transformNode;\n }\n loadNode(transformNode);\n }\n if (node.mesh != undefined) {\n if (node.skin == undefined) {\n const mesh = ArrayItem.Get(`${context}/mesh`, this._gltf.meshes, node.mesh);\n promises.push(this._loadMeshAsync(`/meshes/${mesh.index}`, node, mesh, loadNode));\n }\n else {\n // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)\n // This code path will place the skinned mesh as a sibling of the skeleton root node without loading the\n // transform, which effectively ignores the transform of the skinned mesh, as per spec.\n const mesh = ArrayItem.Get(`${context}/mesh`, this._gltf.meshes, node.mesh);\n promises.push(this._loadMeshAsync(`/meshes/${mesh.index}`, node, mesh, (babylonTransformNode) => {\n const babylonTransformNodeForSkin = node._babylonTransformNodeForSkin;\n // Merge the metadata from the skin node to the skinned mesh in case a loader extension added metadata.\n babylonTransformNode.metadata = mergeDeep(babylonTransformNodeForSkin.metadata, babylonTransformNode.metadata || {});\n const skin = ArrayItem.Get(`${context}/skin`, this._gltf.skins, node.skin);\n promises.push(this._loadSkinAsync(`/skins/${skin.index}`, node, skin, (babylonSkeleton) => {\n this._forEachPrimitive(node, (babylonMesh) => {\n babylonMesh.skeleton = babylonSkeleton;\n });\n // Wait until all the nodes are parented before parenting the skinned mesh.\n this._postSceneLoadActions.push(() => {\n if (skin.skeleton != undefined) {\n // Place the skinned mesh node as a sibling of the skeleton root node.\n // Handle special case when the parent of the skeleton root is the skinned mesh.\n const parentNode = ArrayItem.Get(`/skins/${skin.index}/skeleton`, this._gltf.nodes, skin.skeleton).parent;\n if (node.index === parentNode.index) {\n babylonTransformNode.parent = babylonTransformNodeForSkin.parent;\n }\n else {\n babylonTransformNode.parent = parentNode._babylonTransformNode;\n }\n }\n else {\n babylonTransformNode.parent = this._rootBabylonMesh;\n }\n this._parent.onSkinLoadedObservable.notifyObservers({ node: babylonTransformNodeForSkin, skinnedNode: babylonTransformNode });\n });\n }));\n }));\n }\n }\n this.logClose();\n return Promise.all(promises).then(() => {\n this._forEachPrimitive(node, (babylonMesh) => {\n if (babylonMesh.geometry && babylonMesh.geometry.useBoundingInfoFromGeometry) {\n // simply apply the world matrices to the bounding info - the extends are already ok\n babylonMesh._updateBoundingInfo();\n }\n else {\n babylonMesh.refreshBoundingInfo(true);\n }\n });\n return node._babylonTransformNode;\n });\n }\n _loadMeshAsync(context, node, mesh, assign) {\n const primitives = mesh.primitives;\n if (!primitives || !primitives.length) {\n throw new Error(`${context}: Primitives are missing`);\n }\n if (primitives[0].index == undefined) {\n ArrayItem.Assign(primitives);\n }\n const promises = new Array();\n this.logOpen(`${context} ${mesh.name || \"\"}`);\n const name = node.name || `node${node.index}`;\n if (primitives.length === 1) {\n const primitive = mesh.primitives[0];\n promises.push(this._loadMeshPrimitiveAsync(`${context}/primitives/${primitive.index}`, name, node, mesh, primitive, (babylonMesh) => {\n node._babylonTransformNode = babylonMesh;\n node._primitiveBabylonMeshes = [babylonMesh];\n }));\n }\n else {\n this._babylonScene._blockEntityCollection = !!this._assetContainer;\n node._babylonTransformNode = new TransformNode(name, this._babylonScene);\n node._babylonTransformNode._parentContainer = this._assetContainer;\n this._babylonScene._blockEntityCollection = false;\n node._primitiveBabylonMeshes = [];\n for (const primitive of primitives) {\n promises.push(this._loadMeshPrimitiveAsync(`${context}/primitives/${primitive.index}`, `${name}_primitive${primitive.index}`, node, mesh, primitive, (babylonMesh) => {\n babylonMesh.parent = node._babylonTransformNode;\n node._primitiveBabylonMeshes.push(babylonMesh);\n }));\n }\n }\n assign(node._babylonTransformNode);\n this.logClose();\n return Promise.all(promises).then(() => {\n return node._babylonTransformNode;\n });\n }\n /**\n * @internal Define this method to modify the default behavior when loading data for mesh primitives.\n * @param context The context when loading the asset\n * @param name The mesh name when loading the asset\n * @param node The glTF node when loading the asset\n * @param mesh The glTF mesh when loading the asset\n * @param primitive The glTF mesh primitive property\n * @param assign A function called synchronously after parsing the glTF properties\n * @returns A promise that resolves with the loaded mesh when the load is complete or null if not handled\n */\n _loadMeshPrimitiveAsync(context, name, node, mesh, primitive, assign) {\n const extensionPromise = this._extensionsLoadMeshPrimitiveAsync(context, name, node, mesh, primitive, assign);\n if (extensionPromise) {\n return extensionPromise;\n }\n this.logOpen(`${context}`);\n const shouldInstance = this._disableInstancedMesh === 0 && this._parent.createInstances && node.skin == undefined && !mesh.primitives[0].targets;\n let babylonAbstractMesh;\n let promise;\n if (shouldInstance && primitive._instanceData) {\n this._babylonScene._blockEntityCollection = !!this._assetContainer;\n babylonAbstractMesh = primitive._instanceData.babylonSourceMesh.createInstance(name);\n babylonAbstractMesh._parentContainer = this._assetContainer;\n this._babylonScene._blockEntityCollection = false;\n promise = primitive._instanceData.promise;\n }\n else {\n const promises = new Array();\n this._babylonScene._blockEntityCollection = !!this._assetContainer;\n const babylonMesh = new Mesh(name, this._babylonScene);\n babylonMesh._parentContainer = this._assetContainer;\n this._babylonScene._blockEntityCollection = false;\n babylonMesh.overrideMaterialSideOrientation = this._babylonScene.useRightHandedSystem ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation;\n this._createMorphTargets(context, node, mesh, primitive, babylonMesh);\n promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then((babylonGeometry) => {\n return this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(() => {\n if (this._disposed) {\n return;\n }\n this._babylonScene._blockEntityCollection = !!this._assetContainer;\n babylonGeometry.applyToMesh(babylonMesh);\n babylonGeometry._parentContainer = this._assetContainer;\n this._babylonScene._blockEntityCollection = false;\n });\n }));\n const babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);\n if (primitive.material == undefined) {\n let babylonMaterial = this._defaultBabylonMaterialData[babylonDrawMode];\n if (!babylonMaterial) {\n babylonMaterial = this._createDefaultMaterial(\"__GLTFLoader._default\", babylonDrawMode);\n this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);\n this._defaultBabylonMaterialData[babylonDrawMode] = babylonMaterial;\n }\n babylonMesh.material = babylonMaterial;\n }\n else if (!this.parent.skipMaterials) {\n const material = ArrayItem.Get(`${context}/material`, this._gltf.materials, primitive.material);\n promises.push(this._loadMaterialAsync(`/materials/${material.index}`, material, babylonMesh, babylonDrawMode, (babylonMaterial) => {\n babylonMesh.material = babylonMaterial;\n }));\n }\n promise = Promise.all(promises);\n if (shouldInstance) {\n primitive._instanceData = {\n babylonSourceMesh: babylonMesh,\n promise: promise,\n };\n }\n babylonAbstractMesh = babylonMesh;\n }\n GLTFLoader.AddPointerMetadata(babylonAbstractMesh, context);\n this._parent.onMeshLoadedObservable.notifyObservers(babylonAbstractMesh);\n assign(babylonAbstractMesh);\n this.logClose();\n return promise.then(() => {\n return babylonAbstractMesh;\n });\n }\n _loadVertexDataAsync(context, primitive, babylonMesh) {\n const extensionPromise = this._extensionsLoadVertexDataAsync(context, primitive, babylonMesh);\n if (extensionPromise) {\n return extensionPromise;\n }\n const attributes = primitive.attributes;\n if (!attributes) {\n throw new Error(`${context}: Attributes are missing`);\n }\n const promises = new Array();\n const babylonGeometry = new Geometry(babylonMesh.name, this._babylonScene);\n if (primitive.indices == undefined) {\n babylonMesh.isUnIndexed = true;\n }\n else {\n const accessor = ArrayItem.Get(`${context}/indices`, this._gltf.accessors, primitive.indices);\n promises.push(this._loadIndicesAccessorAsync(`/accessors/${accessor.index}`, accessor).then((data) => {\n babylonGeometry.setIndices(data);\n }));\n }\n const loadAttribute = (attribute, kind, callback) => {\n if (attributes[attribute] == undefined) {\n return;\n }\n babylonMesh._delayInfo = babylonMesh._delayInfo || [];\n if (babylonMesh._delayInfo.indexOf(kind) === -1) {\n babylonMesh._delayInfo.push(kind);\n }\n const accessor = ArrayItem.Get(`${context}/attributes/${attribute}`, this._gltf.accessors, attributes[attribute]);\n promises.push(this._loadVertexAccessorAsync(`/accessors/${accessor.index}`, accessor, kind).then((babylonVertexBuffer) => {\n if (babylonVertexBuffer.getKind() === VertexBuffer.PositionKind && !this.parent.alwaysComputeBoundingBox && !babylonMesh.skeleton) {\n if (accessor.min && accessor.max) {\n const min = TmpVectors.Vector3[0].copyFromFloats(...accessor.min);\n const max = TmpVectors.Vector3[1].copyFromFloats(...accessor.max);\n if (accessor.normalized && accessor.componentType !== 5126 /* AccessorComponentType.FLOAT */) {\n let divider = 1;\n switch (accessor.componentType) {\n case 5120 /* AccessorComponentType.BYTE */:\n divider = 127.0;\n break;\n case 5121 /* AccessorComponentType.UNSIGNED_BYTE */:\n divider = 255.0;\n break;\n case 5122 /* AccessorComponentType.SHORT */:\n divider = 32767.0;\n break;\n case 5123 /* AccessorComponentType.UNSIGNED_SHORT */:\n divider = 65535.0;\n break;\n }\n const oneOverDivider = 1 / divider;\n min.scaleInPlace(oneOverDivider);\n max.scaleInPlace(oneOverDivider);\n }\n babylonGeometry._boundingInfo = new BoundingInfo(min, max);\n babylonGeometry.useBoundingInfoFromGeometry = true;\n }\n }\n babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);\n }));\n if (kind == VertexBuffer.MatricesIndicesExtraKind) {\n babylonMesh.numBoneInfluencers = 8;\n }\n if (callback) {\n callback(accessor);\n }\n };\n loadAttribute(\"POSITION\", VertexBuffer.PositionKind);\n loadAttribute(\"NORMAL\", VertexBuffer.NormalKind);\n loadAttribute(\"TANGENT\", VertexBuffer.TangentKind);\n loadAttribute(\"TEXCOORD_0\", VertexBuffer.UVKind);\n loadAttribute(\"TEXCOORD_1\", VertexBuffer.UV2Kind);\n loadAttribute(\"TEXCOORD_2\", VertexBuffer.UV3Kind);\n loadAttribute(\"TEXCOORD_3\", VertexBuffer.UV4Kind);\n loadAttribute(\"TEXCOORD_4\", VertexBuffer.UV5Kind);\n loadAttribute(\"TEXCOORD_5\", VertexBuffer.UV6Kind);\n loadAttribute(\"JOINTS_0\", VertexBuffer.MatricesIndicesKind);\n loadAttribute(\"WEIGHTS_0\", VertexBuffer.MatricesWeightsKind);\n loadAttribute(\"JOINTS_1\", VertexBuffer.MatricesIndicesExtraKind);\n loadAttribute(\"WEIGHTS_1\", VertexBuffer.MatricesWeightsExtraKind);\n loadAttribute(\"COLOR_0\", VertexBuffer.ColorKind, (accessor) => {\n if (accessor.type === \"VEC4\" /* AccessorType.VEC4 */) {\n babylonMesh.hasVertexAlpha = true;\n }\n });\n return Promise.all(promises).then(() => {\n return babylonGeometry;\n });\n }\n _createMorphTargets(context, node, mesh, primitive, babylonMesh) {\n if (!primitive.targets) {\n return;\n }\n if (node._numMorphTargets == undefined) {\n node._numMorphTargets = primitive.targets.length;\n }\n else if (primitive.targets.length !== node._numMorphTargets) {\n throw new Error(`${context}: Primitives do not have the same number of targets`);\n }\n const targetNames = mesh.extras ? mesh.extras.targetNames : null;\n this._babylonScene._blockEntityCollection = !!this._assetContainer;\n babylonMesh.morphTargetManager = new MorphTargetManager(this._babylonScene);\n babylonMesh.morphTargetManager._parentContainer = this._assetContainer;\n this._babylonScene._blockEntityCollection = false;\n babylonMesh.morphTargetManager.areUpdatesFrozen = true;\n for (let index = 0; index < primitive.targets.length; index++) {\n const weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;\n const name = targetNames ? targetNames[index] : `morphTarget${index}`;\n babylonMesh.morphTargetManager.addTarget(new MorphTarget(name, weight, babylonMesh.getScene()));\n // TODO: tell the target whether it has positions, normals, tangents\n }\n }\n _loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry) {\n if (!primitive.targets) {\n return Promise.resolve();\n }\n const promises = new Array();\n const morphTargetManager = babylonMesh.morphTargetManager;\n for (let index = 0; index < morphTargetManager.numTargets; index++) {\n const babylonMorphTarget = morphTargetManager.getTarget(index);\n promises.push(this._loadMorphTargetVertexDataAsync(`${context}/targets/${index}`, babylonGeometry, primitive.targets[index], babylonMorphTarget));\n }\n return Promise.all(promises).then(() => {\n morphTargetManager.areUpdatesFrozen = false;\n });\n }\n _loadMorphTargetVertexDataAsync(context, babylonGeometry, attributes, babylonMorphTarget) {\n const promises = new Array();\n const loadAttribute = (attribute, kind, setData) => {\n if (attributes[attribute] == undefined) {\n return;\n }\n const babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);\n if (!babylonVertexBuffer) {\n return;\n }\n const accessor = ArrayItem.Get(`${context}/${attribute}`, this._gltf.accessors, attributes[attribute]);\n promises.push(this._loadFloatAccessorAsync(`/accessors/${accessor.index}`, accessor).then((data) => {\n setData(babylonVertexBuffer, data);\n }));\n };\n loadAttribute(\"POSITION\", VertexBuffer.PositionKind, (babylonVertexBuffer, data) => {\n const positions = new Float32Array(data.length);\n babylonVertexBuffer.forEach(data.length, (value, index) => {\n positions[index] = data[index] + value;\n });\n babylonMorphTarget.setPositions(positions);\n });\n loadAttribute(\"NORMAL\", VertexBuffer.NormalKind, (babylonVertexBuffer, data) => {\n const normals = new Float32Array(data.length);\n babylonVertexBuffer.forEach(normals.length, (value, index) => {\n normals[index] = data[index] + value;\n });\n babylonMorphTarget.setNormals(normals);\n });\n loadAttribute(\"TANGENT\", VertexBuffer.TangentKind, (babylonVertexBuffer, data) => {\n const tangents = new Float32Array((data.length / 3) * 4);\n let dataIndex = 0;\n babylonVertexBuffer.forEach((data.length / 3) * 4, (value, index) => {\n // Tangent data for morph targets is stored as xyz delta.\n // The vertexData.tangent is stored as xyzw.\n // So we need to skip every fourth vertexData.tangent.\n if ((index + 1) % 4 !== 0) {\n tangents[dataIndex] = data[dataIndex] + value;\n dataIndex++;\n }\n });\n babylonMorphTarget.setTangents(tangents);\n });\n return Promise.all(promises).then(() => { });\n }\n static _LoadTransform(node, babylonNode) {\n // Ignore the TRS of skinned nodes.\n // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)\n if (node.skin != undefined) {\n return;\n }\n let position = Vector3.Zero();\n let rotation = Quaternion.Identity();\n let scaling = Vector3.One();\n if (node.matrix) {\n const matrix = Matrix.FromArray(node.matrix);\n matrix.decompose(scaling, rotation, position);\n }\n else {\n if (node.translation) {\n position = Vector3.FromArray(node.translation);\n }\n if (node.rotation) {\n rotation = Quaternion.FromArray(node.rotation);\n }\n if (node.scale) {\n scaling = Vector3.FromArray(node.scale);\n }\n }\n babylonNode.position = position;\n babylonNode.rotationQuaternion = rotation;\n babylonNode.scaling = scaling;\n }\n _loadSkinAsync(context, node, skin, assign) {\n const extensionPromise = this._extensionsLoadSkinAsync(context, node, skin);\n if (extensionPromise) {\n return extensionPromise;\n }\n if (skin._data) {\n assign(skin._data.babylonSkeleton);\n return skin._data.promise;\n }\n const skeletonId = `skeleton${skin.index}`;\n this._babylonScene._blockEntityCollection = !!this._assetContainer;\n const babylonSkeleton = new Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);\n babylonSkeleton._parentContainer = this._assetContainer;\n this._babylonScene._blockEntityCollection = false;\n this._loadBones(context, skin, babylonSkeleton);\n const promise = this._loadSkinInverseBindMatricesDataAsync(context, skin).then((inverseBindMatricesData) => {\n this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);\n });\n skin._data = {\n babylonSkeleton: babylonSkeleton,\n promise: promise,\n };\n assign(babylonSkeleton);\n return promise;\n }\n _loadBones(context, skin, babylonSkeleton) {\n if (skin.skeleton == undefined || this._parent.alwaysComputeSkeletonRootNode) {\n const rootNode = this._findSkeletonRootNode(`${context}/joints`, skin.joints);\n if (rootNode) {\n if (skin.skeleton === undefined) {\n skin.skeleton = rootNode.index;\n }\n else {\n const isParent = (a, b) => {\n for (; b.parent; b = b.parent) {\n if (b.parent === a) {\n return true;\n }\n }\n return false;\n };\n const skeletonNode = ArrayItem.Get(`${context}/skeleton`, this._gltf.nodes, skin.skeleton);\n if (skeletonNode !== rootNode && !isParent(skeletonNode, rootNode)) {\n Logger.Warn(`${context}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`);\n skin.skeleton = rootNode.index;\n }\n }\n }\n else {\n Logger.Warn(`${context}: Failed to find common root`);\n }\n }\n const babylonBones = {};\n for (const index of skin.joints) {\n const node = ArrayItem.Get(`${context}/joints/${index}`, this._gltf.nodes, index);\n this._loadBone(node, skin, babylonSkeleton, babylonBones);\n }\n }\n _findSkeletonRootNode(context, joints) {\n if (joints.length === 0) {\n return null;\n }\n const paths = {};\n for (const index of joints) {\n const path = new Array();\n let node = ArrayItem.Get(`${context}/${index}`, this._gltf.nodes, index);\n while (node.index !== -1) {\n path.unshift(node);\n node = node.parent;\n }\n paths[index] = path;\n }\n let rootNode = null;\n for (let i = 0;; ++i) {\n let path = paths[joints[0]];\n if (i >= path.length) {\n return rootNode;\n }\n const node = path[i];\n for (let j = 1; j < joints.length; ++j) {\n path = paths[joints[j]];\n if (i >= path.length || node !== path[i]) {\n return rootNode;\n }\n }\n rootNode = node;\n }\n }\n _loadBone(node, skin, babylonSkeleton, babylonBones) {\n let babylonBone = babylonBones[node.index];\n if (babylonBone) {\n return babylonBone;\n }\n let parentBabylonBone = null;\n if (node.index !== skin.skeleton) {\n if (node.parent && node.parent.index !== -1) {\n parentBabylonBone = this._loadBone(node.parent, skin, babylonSkeleton, babylonBones);\n }\n else if (skin.skeleton !== undefined) {\n Logger.Warn(`/skins/${skin.index}/skeleton: Skeleton node is not a common root`);\n }\n }\n const boneIndex = skin.joints.indexOf(node.index);\n babylonBone = new Bone(node.name || `joint${node.index}`, babylonSkeleton, parentBabylonBone, this._getNodeMatrix(node), null, null, boneIndex);\n babylonBones[node.index] = babylonBone;\n // Wait until the scene is loaded to ensure the transform nodes are loaded.\n this._postSceneLoadActions.push(() => {\n // Link the Babylon bone with the corresponding Babylon transform node.\n // A glTF joint is a pointer to a glTF node in the glTF node hierarchy similar to Unity3D.\n babylonBone.linkTransformNode(node._babylonTransformNode);\n });\n return babylonBone;\n }\n _loadSkinInverseBindMatricesDataAsync(context, skin) {\n if (skin.inverseBindMatrices == undefined) {\n return Promise.resolve(null);\n }\n const accessor = ArrayItem.Get(`${context}/inverseBindMatrices`, this._gltf.accessors, skin.inverseBindMatrices);\n return this._loadFloatAccessorAsync(`/accessors/${accessor.index}`, accessor);\n }\n _updateBoneMatrices(babylonSkeleton, inverseBindMatricesData) {\n for (const babylonBone of babylonSkeleton.bones) {\n const baseMatrix = Matrix.Identity();\n const boneIndex = babylonBone._index;\n if (inverseBindMatricesData && boneIndex !== -1) {\n Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);\n baseMatrix.invertToRef(baseMatrix);\n }\n const babylonParentBone = babylonBone.getParent();\n if (babylonParentBone) {\n baseMatrix.multiplyToRef(babylonParentBone.getAbsoluteInverseBindMatrix(), baseMatrix);\n }\n babylonBone.updateMatrix(baseMatrix, false, false);\n babylonBone._updateAbsoluteBindMatrices(undefined, false);\n }\n }\n _getNodeMatrix(node) {\n return node.matrix\n ? Matrix.FromArray(node.matrix)\n : Matrix.Compose(node.scale ? Vector3.FromArray(node.scale) : Vector3.One(), node.rotation ? Quaternion.FromArray(node.rotation) : Quaternion.Identity(), node.translation ? Vector3.FromArray(node.translation) : Vector3.Zero());\n }\n /**\n * Loads a glTF camera.\n * @param context The context when loading the asset\n * @param camera The glTF camera property\n * @param assign A function called synchronously after parsing the glTF properties\n * @returns A promise that resolves with the loaded Babylon camera when the load is complete\n */\n loadCameraAsync(context, camera, assign = () => { }) {\n const extensionPromise = this._extensionsLoadCameraAsync(context, camera, assign);\n if (extensionPromise) {\n return extensionPromise;\n }\n const promises = new Array();\n this.logOpen(`${context} ${camera.name || \"\"}`);\n this._babylonScene._blockEntityCollection = !!this._assetContainer;\n const babylonCamera = new FreeCamera(camera.name || `camera${camera.index}`, Vector3.Zero(), this._babylonScene, false);\n babylonCamera._parentContainer = this._assetContainer;\n this._babylonScene._blockEntityCollection = false;\n babylonCamera.ignoreParentScaling = true;\n camera._babylonCamera = babylonCamera;\n babylonCamera.rotation = new Vector3(0, Math.PI, 0);\n switch (camera.type) {\n case \"perspective\" /* CameraType.PERSPECTIVE */: {\n const perspective = camera.perspective;\n if (!perspective) {\n throw new Error(`${context}: Camera perspective properties are missing`);\n }\n babylonCamera.fov = perspective.yfov;\n babylonCamera.minZ = perspective.znear;\n babylonCamera.maxZ = perspective.zfar || 0;\n break;\n }\n case \"orthographic\" /* CameraType.ORTHOGRAPHIC */: {\n if (!camera.orthographic) {\n throw new Error(`${context}: Camera orthographic properties are missing`);\n }\n babylonCamera.mode = Camera.ORTHOGRAPHIC_CAMERA;\n babylonCamera.orthoLeft = -camera.orthographic.xmag;\n babylonCamera.orthoRight = camera.orthographic.xmag;\n babylonCamera.orthoBottom = -camera.orthographic.ymag;\n babylonCamera.orthoTop = camera.orthographic.ymag;\n babylonCamera.minZ = camera.orthographic.znear;\n babylonCamera.maxZ = camera.orthographic.zfar;\n break;\n }\n default: {\n throw new Error(`${context}: Invalid camera type (${camera.type})`);\n }\n }\n GLTFLoader.AddPointerMetadata(babylonCamera, context);\n this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);\n assign(babylonCamera);\n this.logClose();\n return Promise.all(promises).then(() => {\n return babylonCamera;\n });\n }\n _loadAnimationsAsync() {\n const animations = this._gltf.animations;\n if (!animations) {\n return Promise.resolve();\n }\n const promises = new Array();\n for (let index = 0; index < animations.length; index++) {\n const animation = animations[index];\n promises.push(this.loadAnimationAsync(`/animations/${animation.index}`, animation).then((animationGroup) => {\n // Delete the animation group if it ended up not having any animations in it.\n if (animationGroup.targetedAnimations.length === 0) {\n animationGroup.dispose();\n }\n }));\n }\n return Promise.all(promises).then(() => { });\n }\n /**\n * Loads a glTF animation.\n * @param context The context when loading the asset\n * @param animation The glTF animation property\n * @returns A promise that resolves with the loaded Babylon animation group when the load is complete\n */\n loadAnimationAsync(context, animation) {\n const promise = this._extensionsLoadAnimationAsync(context, animation);\n if (promise) {\n return promise;\n }\n this._babylonScene._blockEntityCollection = !!this._assetContainer;\n const babylonAnimationGroup = new AnimationGroup(animation.name || `animation${animation.index}`, this._babylonScene);\n babylonAnimationGroup._parentContainer = this._assetContainer;\n this._babylonScene._blockEntityCollection = false;\n animation._babylonAnimationGroup = babylonAnimationGroup;\n const promises = new Array();\n ArrayItem.Assign(animation.channels);\n ArrayItem.Assign(animation.samplers);\n for (const channel of animation.channels) {\n promises.push(this._loadAnimationChannelAsync(`${context}/channels/${channel.index}`, context, animation, channel, (babylonTarget, babylonAnimation) => {\n babylonTarget.animations = babylonTarget.animations || [];\n babylonTarget.animations.push(babylonAnimation);\n babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonTarget);\n }));\n }\n return Promise.all(promises).then(() => {\n babylonAnimationGroup.normalize(0);\n return babylonAnimationGroup;\n });\n }\n /**\n * @hidden\n * Loads a glTF animation channel.\n * @param context The context when loading the asset\n * @param animationContext The context of the animation when loading the asset\n * @param animation The glTF animation property\n * @param channel The glTF animation channel property\n * @param onLoad Called for each animation loaded\n * @returns A void promise that resolves when the load is complete\n */\n _loadAnimationChannelAsync(context, animationContext, animation, channel, onLoad) {\n const promise = this._extensionsLoadAnimationChannelAsync(context, animationContext, animation, channel, onLoad);\n if (promise) {\n return promise;\n }\n if (channel.target.node == undefined) {\n return Promise.resolve();\n }\n const targetNode = ArrayItem.Get(`${context}/target/node`, this._gltf.nodes, channel.target.node);\n // Ignore animations that have no animation targets.\n if ((channel.target.path === \"weights\" /* AnimationChannelTargetPath.WEIGHTS */ && !targetNode._numMorphTargets) ||\n (channel.target.path !== \"weights\" /* AnimationChannelTargetPath.WEIGHTS */ && !targetNode._babylonTransformNode)) {\n return Promise.resolve();\n }\n let properties;\n switch (channel.target.path) {\n case \"translation\" /* AnimationChannelTargetPath.TRANSLATION */: {\n properties = nodeAnimationData.translation;\n break;\n }\n case \"rotation\" /* AnimationChannelTargetPath.ROTATION */: {\n properties = nodeAnimationData.rotation;\n break;\n }\n case \"scale\" /* AnimationChannelTargetPath.SCALE */: {\n properties = nodeAnimationData.scale;\n break;\n }\n case \"weights\" /* AnimationChannelTargetPath.WEIGHTS */: {\n properties = nodeAnimationData.weights;\n break;\n }\n default: {\n throw new Error(`${context}/target/path: Invalid value (${channel.target.path})`);\n }\n }\n const targetInfo = {\n target: targetNode,\n properties: properties,\n };\n return this._loadAnimationChannelFromTargetInfoAsync(context, animationContext, animation, channel, targetInfo, onLoad);\n }\n /**\n * @hidden\n * Loads a glTF animation channel.\n * @param context The context when loading the asset\n * @param animationContext The context of the animation when loading the asset\n * @param animation The glTF animation property\n * @param channel The glTF animation channel property\n * @param targetInfo The glTF target and properties\n * @param onLoad Called for each animation loaded\n * @returns A void promise that resolves when the load is complete\n */\n _loadAnimationChannelFromTargetInfoAsync(context, animationContext, animation, channel, targetInfo, onLoad) {\n const fps = this.parent.targetFps;\n const invfps = 1 / fps;\n const sampler = ArrayItem.Get(`${context}/sampler`, animation.samplers, channel.sampler);\n return this._loadAnimationSamplerAsync(`${animationContext}/samplers/${channel.sampler}`, sampler).then((data) => {\n let numAnimations = 0;\n // Extract the corresponding values from the read value.\n // GLTF values may be dispatched to several Babylon properties.\n // For example, baseColorFactor [`r`, `g`, `b`, `a`] is dispatched to\n // - albedoColor as Color3(`r`, `g`, `b`)\n // - alpha as `a`\n for (const property of targetInfo.properties) {\n const stride = property.getStride(targetInfo.target);\n const input = data.input;\n const output = data.output;\n const keys = new Array(input.length);\n let outputOffset = 0;\n switch (data.interpolation) {\n case \"STEP\" /* AnimationSamplerInterpolation.STEP */: {\n for (let index = 0; index < input.length; index++) {\n const value = property.getValue(targetInfo.target, output, outputOffset, 1);\n outputOffset += stride;\n keys[index] = {\n frame: input[index] * fps,\n value: value,\n interpolation: AnimationKeyInterpolation.STEP,\n };\n }\n break;\n }\n case \"CUBICSPLINE\" /* AnimationSamplerInterpolation.CUBICSPLINE */: {\n for (let index = 0; index < input.length; index++) {\n const inTangent = property.getValue(targetInfo.target, output, outputOffset, invfps);\n outputOffset += stride;\n const value = property.getValue(targetInfo.target, output, outputOffset, 1);\n outputOffset += stride;\n const outTangent = property.getValue(targetInfo.target, output, outputOffset, invfps);\n outputOffset += stride;\n keys[index] = {\n frame: input[index] * fps,\n inTangent: inTangent,\n value: value,\n outTangent: outTangent,\n };\n }\n break;\n }\n case \"LINEAR\" /* AnimationSamplerInterpolation.LINEAR */: {\n for (let index = 0; index < input.length; index++) {\n const value = property.getValue(targetInfo.target, output, outputOffset, 1);\n outputOffset += stride;\n keys[index] = {\n frame: input[index] * fps,\n value: value,\n };\n }\n break;\n }\n }\n if (outputOffset > 0) {\n const name = `${animation.name || `animation${animation.index}`}_channel${channel.index}_${numAnimations}`;\n property.buildAnimations(targetInfo.target, name, fps, keys, (babylonAnimatable, babylonAnimation) => {\n ++numAnimations;\n onLoad(babylonAnimatable, babylonAnimation);\n });\n }\n }\n });\n }\n _loadAnimationSamplerAsync(context, sampler) {\n if (sampler._data) {\n return sampler._data;\n }\n const interpolation = sampler.interpolation || \"LINEAR\" /* AnimationSamplerInterpolation.LINEAR */;\n switch (interpolation) {\n case \"STEP\" /* AnimationSamplerInterpolation.STEP */:\n case \"LINEAR\" /* AnimationSamplerInterpolation.LINEAR */:\n case \"CUBICSPLINE\" /* AnimationSamplerInterpolation.CUBICSPLINE */: {\n break;\n }\n default: {\n throw new Error(`${context}/interpolation: Invalid value (${sampler.interpolation})`);\n }\n }\n const inputAccessor = ArrayItem.Get(`${context}/input`, this._gltf.accessors, sampler.input);\n const outputAccessor = ArrayItem.Get(`${context}/output`, this._gltf.accessors, sampler.output);\n sampler._data = Promise.all([\n this._loadFloatAccessorAsync(`/accessors/${inputAccessor.index}`, inputAccessor),\n this._loadFloatAccessorAsync(`/accessors/${outputAccessor.index}`, outputAccessor),\n ]).then(([inputData, outputData]) => {\n return {\n input: inputData,\n interpolation: interpolation,\n output: outputData,\n };\n });\n return sampler._data;\n }\n /**\n * Loads a glTF buffer.\n * @param context The context when loading the asset\n * @param buffer The glTF buffer property\n * @param byteOffset The byte offset to use\n * @param byteLength The byte length to use\n * @returns A promise that resolves with the loaded data when the load is complete\n */\n loadBufferAsync(context, buffer, byteOffset, byteLength) {\n const extensionPromise = this._extensionsLoadBufferAsync(context, buffer, byteOffset, byteLength);\n if (extensionPromise) {\n return extensionPromise;\n }\n if (!buffer._data) {\n if (buffer.uri) {\n buffer._data = this.loadUriAsync(`${context}/uri`, buffer, buffer.uri);\n }\n else {\n if (!this._bin) {\n throw new Error(`${context}: Uri is missing or the binary glTF is missing its binary chunk`);\n }\n buffer._data = this._bin.readAsync(0, buffer.byteLength);\n }\n }\n return buffer._data.then((data) => {\n try {\n return new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);\n }\n catch (e) {\n throw new Error(`${context}: ${e.message}`);\n }\n });\n }\n /**\n * Loads a glTF buffer view.\n * @param context The context when loading the asset\n * @param bufferView The glTF buffer view property\n * @returns A promise that resolves with the loaded data when the load is complete\n */\n loadBufferViewAsync(context, bufferView) {\n const extensionPromise = this._extensionsLoadBufferViewAsync(context, bufferView);\n if (extensionPromise) {\n return extensionPromise;\n }\n if (bufferView._data) {\n return bufferView._data;\n }\n const buffer = ArrayItem.Get(`${context}/buffer`, this._gltf.buffers, bufferView.buffer);\n bufferView._data = this.loadBufferAsync(`/buffers/${buffer.index}`, buffer, bufferView.byteOffset || 0, bufferView.byteLength);\n return bufferView._data;\n }\n _loadAccessorAsync(context, accessor, constructor) {\n if (accessor._data) {\n return accessor._data;\n }\n const numComponents = GLTFLoader._GetNumComponents(context, accessor.type);\n const byteStride = numComponents * VertexBuffer.GetTypeByteLength(accessor.componentType);\n const length = numComponents * accessor.count;\n if (accessor.bufferView == undefined) {\n accessor._data = Promise.resolve(new constructor(length));\n }\n else {\n const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, accessor.bufferView);\n accessor._data = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView).then((data) => {\n if (accessor.componentType === 5126 /* AccessorComponentType.FLOAT */ && !accessor.normalized && (!bufferView.byteStride || bufferView.byteStride === byteStride)) {\n return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);\n }\n else {\n const typedArray = new constructor(length);\n VertexBuffer.ForEach(data, accessor.byteOffset || 0, bufferView.byteStride || byteStride, numComponents, accessor.componentType, typedArray.length, accessor.normalized || false, (value, index) => {\n typedArray[index] = value;\n });\n return typedArray;\n }\n });\n }\n if (accessor.sparse) {\n const sparse = accessor.sparse;\n accessor._data = accessor._data.then((data) => {\n const typedArray = data;\n const indicesBufferView = ArrayItem.Get(`${context}/sparse/indices/bufferView`, this._gltf.bufferViews, sparse.indices.bufferView);\n const valuesBufferView = ArrayItem.Get(`${context}/sparse/values/bufferView`, this._gltf.bufferViews, sparse.values.bufferView);\n return Promise.all([\n this.loadBufferViewAsync(`/bufferViews/${indicesBufferView.index}`, indicesBufferView),\n this.loadBufferViewAsync(`/bufferViews/${valuesBufferView.index}`, valuesBufferView),\n ]).then(([indicesData, valuesData]) => {\n const indices = GLTFLoader._GetTypedArray(`${context}/sparse/indices`, sparse.indices.componentType, indicesData, sparse.indices.byteOffset, sparse.count);\n const sparseLength = numComponents * sparse.count;\n let values;\n if (accessor.componentType === 5126 /* AccessorComponentType.FLOAT */ && !accessor.normalized) {\n values = GLTFLoader._GetTypedArray(`${context}/sparse/values`, accessor.componentType, valuesData, sparse.values.byteOffset, sparseLength);\n }\n else {\n const sparseData = GLTFLoader._GetTypedArray(`${context}/sparse/values`, accessor.componentType, valuesData, sparse.values.byteOffset, sparseLength);\n values = new constructor(sparseLength);\n VertexBuffer.ForEach(sparseData, 0, byteStride, numComponents, accessor.componentType, values.length, accessor.normalized || false, (value, index) => {\n values[index] = value;\n });\n }\n let valuesIndex = 0;\n for (let indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {\n let dataIndex = indices[indicesIndex] * numComponents;\n for (let componentIndex = 0; componentIndex < numComponents; componentIndex++) {\n typedArray[dataIndex++] = values[valuesIndex++];\n }\n }\n return typedArray;\n });\n });\n }\n return accessor._data;\n }\n /**\n * @internal\n */\n _loadFloatAccessorAsync(context, accessor) {\n return this._loadAccessorAsync(context, accessor, Float32Array);\n }\n /**\n * @internal\n */\n _loadIndicesAccessorAsync(context, accessor) {\n if (accessor.type !== \"SCALAR\" /* AccessorType.SCALAR */) {\n throw new Error(`${context}/type: Invalid value ${accessor.type}`);\n }\n if (accessor.componentType !== 5121 /* AccessorComponentType.UNSIGNED_BYTE */ &&\n accessor.componentType !== 5123 /* AccessorComponentType.UNSIGNED_SHORT */ &&\n accessor.componentType !== 5125 /* AccessorComponentType.UNSIGNED_INT */) {\n throw new Error(`${context}/componentType: Invalid value ${accessor.componentType}`);\n }\n if (accessor._data) {\n return accessor._data;\n }\n if (accessor.sparse) {\n const constructor = GLTFLoader._GetTypedArrayConstructor(`${context}/componentType`, accessor.componentType);\n accessor._data = this._loadAccessorAsync(context, accessor, constructor);\n }\n else {\n const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, accessor.bufferView);\n accessor._data = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView).then((data) => {\n return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);\n });\n }\n return accessor._data;\n }\n /**\n * @internal\n */\n _loadVertexBufferViewAsync(bufferView) {\n if (bufferView._babylonBuffer) {\n return bufferView._babylonBuffer;\n }\n const engine = this._babylonScene.getEngine();\n bufferView._babylonBuffer = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView).then((data) => {\n return new Buffer(engine, data, false);\n });\n return bufferView._babylonBuffer;\n }\n /**\n * @internal\n */\n _loadVertexAccessorAsync(context, accessor, kind) {\n var _a;\n if ((_a = accessor._babylonVertexBuffer) === null || _a === void 0 ? void 0 : _a[kind]) {\n return accessor._babylonVertexBuffer[kind];\n }\n if (!accessor._babylonVertexBuffer) {\n accessor._babylonVertexBuffer = {};\n }\n const engine = this._babylonScene.getEngine();\n if (accessor.sparse) {\n accessor._babylonVertexBuffer[kind] = this._loadFloatAccessorAsync(context, accessor).then((data) => {\n return new VertexBuffer(engine, data, kind, false);\n });\n }\n // Load joint indices as a float array since the shaders expect float data but glTF uses unsigned byte/short.\n // This prevents certain platforms (e.g. D3D) from having to convert the data to float on the fly.\n else if (kind === VertexBuffer.MatricesIndicesKind || kind === VertexBuffer.MatricesIndicesExtraKind) {\n accessor._babylonVertexBuffer[kind] = this._loadFloatAccessorAsync(context, accessor).then((data) => {\n return new VertexBuffer(engine, data, kind, false);\n });\n }\n else {\n const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, accessor.bufferView);\n accessor._babylonVertexBuffer[kind] = this._loadVertexBufferViewAsync(bufferView).then((babylonBuffer) => {\n const size = GLTFLoader._GetNumComponents(context, accessor.type);\n return new VertexBuffer(engine, babylonBuffer, kind, false, false, bufferView.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true, 1, true);\n });\n }\n return accessor._babylonVertexBuffer[kind];\n }\n _loadMaterialMetallicRoughnessPropertiesAsync(context, properties, babylonMaterial) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n const promises = new Array();\n if (properties) {\n if (properties.baseColorFactor) {\n babylonMaterial.albedoColor = Color3.FromArray(properties.baseColorFactor);\n babylonMaterial.alpha = properties.baseColorFactor[3];\n }\n else {\n babylonMaterial.albedoColor = Color3.White();\n }\n babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;\n babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;\n if (properties.baseColorTexture) {\n promises.push(this.loadTextureInfoAsync(`${context}/baseColorTexture`, properties.baseColorTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Base Color)`;\n babylonMaterial.albedoTexture = texture;\n }));\n }\n if (properties.metallicRoughnessTexture) {\n properties.metallicRoughnessTexture.nonColorData = true;\n promises.push(this.loadTextureInfoAsync(`${context}/metallicRoughnessTexture`, properties.metallicRoughnessTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Metallic Roughness)`;\n babylonMaterial.metallicTexture = texture;\n }));\n babylonMaterial.useMetallnessFromMetallicTextureBlue = true;\n babylonMaterial.useRoughnessFromMetallicTextureGreen = true;\n babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;\n }\n }\n return Promise.all(promises).then(() => { });\n }\n /**\n * @internal\n */\n _loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign = () => { }) {\n const extensionPromise = this._extensionsLoadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign);\n if (extensionPromise) {\n return extensionPromise;\n }\n material._data = material._data || {};\n let babylonData = material._data[babylonDrawMode];\n if (!babylonData) {\n this.logOpen(`${context} ${material.name || \"\"}`);\n const babylonMaterial = this.createMaterial(context, material, babylonDrawMode);\n babylonData = {\n babylonMaterial: babylonMaterial,\n babylonMeshes: [],\n promise: this.loadMaterialPropertiesAsync(context, material, babylonMaterial),\n };\n material._data[babylonDrawMode] = babylonData;\n GLTFLoader.AddPointerMetadata(babylonMaterial, context);\n this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);\n this.logClose();\n }\n if (babylonMesh) {\n babylonData.babylonMeshes.push(babylonMesh);\n babylonMesh.onDisposeObservable.addOnce(() => {\n const index = babylonData.babylonMeshes.indexOf(babylonMesh);\n if (index !== -1) {\n babylonData.babylonMeshes.splice(index, 1);\n }\n });\n }\n assign(babylonData.babylonMaterial);\n return babylonData.promise.then(() => {\n return babylonData.babylonMaterial;\n });\n }\n _createDefaultMaterial(name, babylonDrawMode) {\n this._babylonScene._blockEntityCollection = !!this._assetContainer;\n const babylonMaterial = new PBRMaterial(name, this._babylonScene);\n babylonMaterial._parentContainer = this._assetContainer;\n this._babylonScene._blockEntityCollection = false;\n // Moved to mesh so user can change materials on gltf meshes: babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation;\n babylonMaterial.fillMode = babylonDrawMode;\n babylonMaterial.enableSpecularAntiAliasing = true;\n babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;\n babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;\n babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_OPAQUE;\n babylonMaterial.metallic = 1;\n babylonMaterial.roughness = 1;\n return babylonMaterial;\n }\n /**\n * Creates a Babylon material from a glTF material.\n * @param context The context when loading the asset\n * @param material The glTF material property\n * @param babylonDrawMode The draw mode for the Babylon material\n * @returns The Babylon material\n */\n createMaterial(context, material, babylonDrawMode) {\n const extensionPromise = this._extensionsCreateMaterial(context, material, babylonDrawMode);\n if (extensionPromise) {\n return extensionPromise;\n }\n const name = material.name || `material${material.index}`;\n const babylonMaterial = this._createDefaultMaterial(name, babylonDrawMode);\n return babylonMaterial;\n }\n /**\n * Loads properties from a glTF material into a Babylon material.\n * @param context The context when loading the asset\n * @param material The glTF material property\n * @param babylonMaterial The Babylon material\n * @returns A promise that resolves when the load is complete\n */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n const extensionPromise = this._extensionsLoadMaterialPropertiesAsync(context, material, babylonMaterial);\n if (extensionPromise) {\n return extensionPromise;\n }\n const promises = new Array();\n promises.push(this.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));\n if (material.pbrMetallicRoughness) {\n promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${context}/pbrMetallicRoughness`, material.pbrMetallicRoughness, babylonMaterial));\n }\n this.loadMaterialAlphaProperties(context, material, babylonMaterial);\n return Promise.all(promises).then(() => { });\n }\n /**\n * Loads the normal, occlusion, and emissive properties from a glTF material into a Babylon material.\n * @param context The context when loading the asset\n * @param material The glTF material property\n * @param babylonMaterial The Babylon material\n * @returns A promise that resolves when the load is complete\n */\n loadMaterialBasePropertiesAsync(context, material, babylonMaterial) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n const promises = new Array();\n babylonMaterial.emissiveColor = material.emissiveFactor ? Color3.FromArray(material.emissiveFactor) : new Color3(0, 0, 0);\n if (material.doubleSided) {\n babylonMaterial.backFaceCulling = false;\n babylonMaterial.twoSidedLighting = true;\n }\n if (material.normalTexture) {\n material.normalTexture.nonColorData = true;\n promises.push(this.loadTextureInfoAsync(`${context}/normalTexture`, material.normalTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Normal)`;\n babylonMaterial.bumpTexture = texture;\n }));\n babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;\n babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;\n if (material.normalTexture.scale != undefined && babylonMaterial.bumpTexture) {\n babylonMaterial.bumpTexture.level = material.normalTexture.scale;\n }\n babylonMaterial.forceIrradianceInFragment = true;\n }\n if (material.occlusionTexture) {\n material.occlusionTexture.nonColorData = true;\n promises.push(this.loadTextureInfoAsync(`${context}/occlusionTexture`, material.occlusionTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Occlusion)`;\n babylonMaterial.ambientTexture = texture;\n }));\n babylonMaterial.useAmbientInGrayScale = true;\n if (material.occlusionTexture.strength != undefined) {\n babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;\n }\n }\n if (material.emissiveTexture) {\n promises.push(this.loadTextureInfoAsync(`${context}/emissiveTexture`, material.emissiveTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Emissive)`;\n babylonMaterial.emissiveTexture = texture;\n }));\n }\n return Promise.all(promises).then(() => { });\n }\n /**\n * Loads the alpha properties from a glTF material into a Babylon material.\n * Must be called after the setting the albedo texture of the Babylon material when the material has an albedo texture.\n * @param context The context when loading the asset\n * @param material The glTF material property\n * @param babylonMaterial The Babylon material\n */\n loadMaterialAlphaProperties(context, material, babylonMaterial) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n const alphaMode = material.alphaMode || \"OPAQUE\" /* MaterialAlphaMode.OPAQUE */;\n switch (alphaMode) {\n case \"OPAQUE\" /* MaterialAlphaMode.OPAQUE */: {\n babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_OPAQUE;\n break;\n }\n case \"MASK\" /* MaterialAlphaMode.MASK */: {\n babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHATEST;\n babylonMaterial.alphaCutOff = material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff;\n if (babylonMaterial.albedoTexture) {\n babylonMaterial.albedoTexture.hasAlpha = true;\n }\n break;\n }\n case \"BLEND\" /* MaterialAlphaMode.BLEND */: {\n babylonMaterial.transparencyMode = PBRMaterial.PBRMATERIAL_ALPHABLEND;\n if (babylonMaterial.albedoTexture) {\n babylonMaterial.albedoTexture.hasAlpha = true;\n babylonMaterial.useAlphaFromAlbedoTexture = true;\n }\n break;\n }\n default: {\n throw new Error(`${context}/alphaMode: Invalid value (${material.alphaMode})`);\n }\n }\n }\n /**\n * Loads a glTF texture info.\n * @param context The context when loading the asset\n * @param textureInfo The glTF texture info property\n * @param assign A function called synchronously after parsing the glTF properties\n * @returns A promise that resolves with the loaded Babylon texture when the load is complete\n */\n loadTextureInfoAsync(context, textureInfo, assign = () => { }) {\n const extensionPromise = this._extensionsLoadTextureInfoAsync(context, textureInfo, assign);\n if (extensionPromise) {\n return extensionPromise;\n }\n this.logOpen(`${context}`);\n if (textureInfo.texCoord >= 6) {\n throw new Error(`${context}/texCoord: Invalid value (${textureInfo.texCoord})`);\n }\n const texture = ArrayItem.Get(`${context}/index`, this._gltf.textures, textureInfo.index);\n texture._textureInfo = textureInfo;\n const promise = this._loadTextureAsync(`/textures/${textureInfo.index}`, texture, (babylonTexture) => {\n babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;\n GLTFLoader.AddPointerMetadata(babylonTexture, context);\n this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);\n assign(babylonTexture);\n });\n this.logClose();\n return promise;\n }\n /**\n * @internal\n */\n _loadTextureAsync(context, texture, assign = () => { }) {\n const extensionPromise = this._extensionsLoadTextureAsync(context, texture, assign);\n if (extensionPromise) {\n return extensionPromise;\n }\n this.logOpen(`${context} ${texture.name || \"\"}`);\n const sampler = texture.sampler == undefined ? GLTFLoader.DefaultSampler : ArrayItem.Get(`${context}/sampler`, this._gltf.samplers, texture.sampler);\n const image = ArrayItem.Get(`${context}/source`, this._gltf.images, texture.source);\n const promise = this._createTextureAsync(context, sampler, image, assign, undefined, !texture._textureInfo.nonColorData);\n this.logClose();\n return promise;\n }\n /**\n * @internal\n */\n _createTextureAsync(context, sampler, image, assign = () => { }, textureLoaderOptions, useSRGBBuffer) {\n const samplerData = this._loadSampler(`/samplers/${sampler.index}`, sampler);\n const promises = new Array();\n const deferred = new Deferred();\n this._babylonScene._blockEntityCollection = !!this._assetContainer;\n const textureCreationOptions = {\n noMipmap: samplerData.noMipMaps,\n invertY: false,\n samplingMode: samplerData.samplingMode,\n onLoad: () => {\n if (!this._disposed) {\n deferred.resolve();\n }\n },\n onError: (message, exception) => {\n if (!this._disposed) {\n deferred.reject(new Error(`${context}: ${exception && exception.message ? exception.message : message || \"Failed to load texture\"}`));\n }\n },\n mimeType: image.mimeType,\n loaderOptions: textureLoaderOptions,\n useSRGBBuffer: !!useSRGBBuffer && this._parent.useSRGBBuffers,\n };\n const babylonTexture = new Texture(null, this._babylonScene, textureCreationOptions);\n babylonTexture._parentContainer = this._assetContainer;\n this._babylonScene._blockEntityCollection = false;\n promises.push(deferred.promise);\n promises.push(this.loadImageAsync(`/images/${image.index}`, image).then((data) => {\n const name = image.uri || `${this._fileName}#image${image.index}`;\n const dataUrl = `data:${this._uniqueRootUrl}${name}`;\n babylonTexture.updateURL(dataUrl, data);\n }));\n babylonTexture.wrapU = samplerData.wrapU;\n babylonTexture.wrapV = samplerData.wrapV;\n assign(babylonTexture);\n return Promise.all(promises).then(() => {\n return babylonTexture;\n });\n }\n _loadSampler(context, sampler) {\n if (!sampler._data) {\n sampler._data = {\n noMipMaps: sampler.minFilter === 9728 /* TextureMinFilter.NEAREST */ || sampler.minFilter === 9729 /* TextureMinFilter.LINEAR */,\n samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler),\n wrapU: GLTFLoader._GetTextureWrapMode(`${context}/wrapS`, sampler.wrapS),\n wrapV: GLTFLoader._GetTextureWrapMode(`${context}/wrapT`, sampler.wrapT),\n };\n }\n return sampler._data;\n }\n /**\n * Loads a glTF image.\n * @param context The context when loading the asset\n * @param image The glTF image property\n * @returns A promise that resolves with the loaded data when the load is complete\n */\n loadImageAsync(context, image) {\n if (!image._data) {\n this.logOpen(`${context} ${image.name || \"\"}`);\n if (image.uri) {\n image._data = this.loadUriAsync(`${context}/uri`, image, image.uri);\n }\n else {\n const bufferView = ArrayItem.Get(`${context}/bufferView`, this._gltf.bufferViews, image.bufferView);\n image._data = this.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView);\n }\n this.logClose();\n }\n return image._data;\n }\n /**\n * Loads a glTF uri.\n * @param context The context when loading the asset\n * @param property The glTF property associated with the uri\n * @param uri The base64 or relative uri\n * @returns A promise that resolves with the loaded data when the load is complete\n */\n loadUriAsync(context, property, uri) {\n const extensionPromise = this._extensionsLoadUriAsync(context, property, uri);\n if (extensionPromise) {\n return extensionPromise;\n }\n if (!GLTFLoader._ValidateUri(uri)) {\n throw new Error(`${context}: '${uri}' is invalid`);\n }\n if (IsBase64DataUrl(uri)) {\n const data = new Uint8Array(DecodeBase64UrlToBinary(uri));\n this.log(`${context}: Decoded ${uri.substr(0, 64)}... (${data.length} bytes)`);\n return Promise.resolve(data);\n }\n this.log(`${context}: Loading ${uri}`);\n return this._parent.preprocessUrlAsync(this._rootUrl + uri).then((url) => {\n return new Promise((resolve, reject) => {\n this._parent._loadFile(this._babylonScene, url, (data) => {\n if (!this._disposed) {\n this.log(`${context}: Loaded ${uri} (${data.byteLength} bytes)`);\n resolve(new Uint8Array(data));\n }\n }, true, (request) => {\n reject(new LoadFileError(`${context}: Failed to load '${uri}'${request ? \": \" + request.status + \" \" + request.statusText : \"\"}`, request));\n });\n });\n });\n }\n /**\n * Adds a JSON pointer to the _internalMetadata of the Babylon object at `._internalMetadata.gltf.pointers`.\n * @param babylonObject the Babylon object with _internalMetadata\n * @param pointer the JSON pointer\n */\n static AddPointerMetadata(babylonObject, pointer) {\n babylonObject.metadata = babylonObject.metadata || {};\n const metadata = (babylonObject._internalMetadata = babylonObject._internalMetadata || {});\n const gltf = (metadata.gltf = metadata.gltf || {});\n const pointers = (gltf.pointers = gltf.pointers || []);\n pointers.push(pointer);\n }\n static _GetTextureWrapMode(context, mode) {\n // Set defaults if undefined\n mode = mode == undefined ? 10497 /* TextureWrapMode.REPEAT */ : mode;\n switch (mode) {\n case 33071 /* TextureWrapMode.CLAMP_TO_EDGE */:\n return Texture.CLAMP_ADDRESSMODE;\n case 33648 /* TextureWrapMode.MIRRORED_REPEAT */:\n return Texture.MIRROR_ADDRESSMODE;\n case 10497 /* TextureWrapMode.REPEAT */:\n return Texture.WRAP_ADDRESSMODE;\n default:\n Logger.Warn(`${context}: Invalid value (${mode})`);\n return Texture.WRAP_ADDRESSMODE;\n }\n }\n static _GetTextureSamplingMode(context, sampler) {\n // Set defaults if undefined\n const magFilter = sampler.magFilter == undefined ? 9729 /* TextureMagFilter.LINEAR */ : sampler.magFilter;\n const minFilter = sampler.minFilter == undefined ? 9987 /* TextureMinFilter.LINEAR_MIPMAP_LINEAR */ : sampler.minFilter;\n if (magFilter === 9729 /* TextureMagFilter.LINEAR */) {\n switch (minFilter) {\n case 9728 /* TextureMinFilter.NEAREST */:\n return Texture.LINEAR_NEAREST;\n case 9729 /* TextureMinFilter.LINEAR */:\n return Texture.LINEAR_LINEAR;\n case 9984 /* TextureMinFilter.NEAREST_MIPMAP_NEAREST */:\n return Texture.LINEAR_NEAREST_MIPNEAREST;\n case 9985 /* TextureMinFilter.LINEAR_MIPMAP_NEAREST */:\n return Texture.LINEAR_LINEAR_MIPNEAREST;\n case 9986 /* TextureMinFilter.NEAREST_MIPMAP_LINEAR */:\n return Texture.LINEAR_NEAREST_MIPLINEAR;\n case 9987 /* TextureMinFilter.LINEAR_MIPMAP_LINEAR */:\n return Texture.LINEAR_LINEAR_MIPLINEAR;\n default:\n Logger.Warn(`${context}/minFilter: Invalid value (${minFilter})`);\n return Texture.LINEAR_LINEAR_MIPLINEAR;\n }\n }\n else {\n if (magFilter !== 9728 /* TextureMagFilter.NEAREST */) {\n Logger.Warn(`${context}/magFilter: Invalid value (${magFilter})`);\n }\n switch (minFilter) {\n case 9728 /* TextureMinFilter.NEAREST */:\n return Texture.NEAREST_NEAREST;\n case 9729 /* TextureMinFilter.LINEAR */:\n return Texture.NEAREST_LINEAR;\n case 9984 /* TextureMinFilter.NEAREST_MIPMAP_NEAREST */:\n return Texture.NEAREST_NEAREST_MIPNEAREST;\n case 9985 /* TextureMinFilter.LINEAR_MIPMAP_NEAREST */:\n return Texture.NEAREST_LINEAR_MIPNEAREST;\n case 9986 /* TextureMinFilter.NEAREST_MIPMAP_LINEAR */:\n return Texture.NEAREST_NEAREST_MIPLINEAR;\n case 9987 /* TextureMinFilter.LINEAR_MIPMAP_LINEAR */:\n return Texture.NEAREST_LINEAR_MIPLINEAR;\n default:\n Logger.Warn(`${context}/minFilter: Invalid value (${minFilter})`);\n return Texture.NEAREST_NEAREST_MIPNEAREST;\n }\n }\n }\n static _GetTypedArrayConstructor(context, componentType) {\n switch (componentType) {\n case 5120 /* AccessorComponentType.BYTE */:\n return Int8Array;\n case 5121 /* AccessorComponentType.UNSIGNED_BYTE */:\n return Uint8Array;\n case 5122 /* AccessorComponentType.SHORT */:\n return Int16Array;\n case 5123 /* AccessorComponentType.UNSIGNED_SHORT */:\n return Uint16Array;\n case 5125 /* AccessorComponentType.UNSIGNED_INT */:\n return Uint32Array;\n case 5126 /* AccessorComponentType.FLOAT */:\n return Float32Array;\n default:\n throw new Error(`${context}: Invalid component type ${componentType}`);\n }\n }\n static _GetTypedArray(context, componentType, bufferView, byteOffset, length) {\n const buffer = bufferView.buffer;\n byteOffset = bufferView.byteOffset + (byteOffset || 0);\n const constructor = GLTFLoader._GetTypedArrayConstructor(`${context}/componentType`, componentType);\n const componentTypeLength = VertexBuffer.GetTypeByteLength(componentType);\n if (byteOffset % componentTypeLength !== 0) {\n // HACK: Copy the buffer if byte offset is not a multiple of component type byte length.\n Logger.Warn(`${context}: Copying buffer as byte offset (${byteOffset}) is not a multiple of component type byte length (${componentTypeLength})`);\n return new constructor(buffer.slice(byteOffset, byteOffset + length * componentTypeLength), 0);\n }\n return new constructor(buffer, byteOffset, length);\n }\n static _GetNumComponents(context, type) {\n switch (type) {\n case \"SCALAR\":\n return 1;\n case \"VEC2\":\n return 2;\n case \"VEC3\":\n return 3;\n case \"VEC4\":\n return 4;\n case \"MAT2\":\n return 4;\n case \"MAT3\":\n return 9;\n case \"MAT4\":\n return 16;\n }\n throw new Error(`${context}: Invalid type (${type})`);\n }\n static _ValidateUri(uri) {\n return Tools.IsBase64(uri) || uri.indexOf(\"..\") === -1;\n }\n /**\n * @internal\n */\n static _GetDrawMode(context, mode) {\n if (mode == undefined) {\n mode = 4 /* MeshPrimitiveMode.TRIANGLES */;\n }\n switch (mode) {\n case 0 /* MeshPrimitiveMode.POINTS */:\n return Material.PointListDrawMode;\n case 1 /* MeshPrimitiveMode.LINES */:\n return Material.LineListDrawMode;\n case 2 /* MeshPrimitiveMode.LINE_LOOP */:\n return Material.LineLoopDrawMode;\n case 3 /* MeshPrimitiveMode.LINE_STRIP */:\n return Material.LineStripDrawMode;\n case 4 /* MeshPrimitiveMode.TRIANGLES */:\n return Material.TriangleFillMode;\n case 5 /* MeshPrimitiveMode.TRIANGLE_STRIP */:\n return Material.TriangleStripDrawMode;\n case 6 /* MeshPrimitiveMode.TRIANGLE_FAN */:\n return Material.TriangleFanDrawMode;\n }\n throw new Error(`${context}: Invalid mesh primitive mode (${mode})`);\n }\n _compileMaterialsAsync() {\n this._parent._startPerformanceCounter(\"Compile materials\");\n const promises = new Array();\n if (this._gltf.materials) {\n for (const material of this._gltf.materials) {\n if (material._data) {\n for (const babylonDrawMode in material._data) {\n const babylonData = material._data[babylonDrawMode];\n for (const babylonMesh of babylonData.babylonMeshes) {\n // Ensure nonUniformScaling is set if necessary.\n babylonMesh.computeWorldMatrix(true);\n const babylonMaterial = babylonData.babylonMaterial;\n promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));\n promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { useInstances: true }));\n if (this._parent.useClipPlane) {\n promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));\n promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true, useInstances: true }));\n }\n }\n }\n }\n }\n }\n return Promise.all(promises).then(() => {\n this._parent._endPerformanceCounter(\"Compile materials\");\n });\n }\n _compileShadowGeneratorsAsync() {\n this._parent._startPerformanceCounter(\"Compile shadow generators\");\n const promises = new Array();\n const lights = this._babylonScene.lights;\n for (const light of lights) {\n const generator = light.getShadowGenerator();\n if (generator) {\n promises.push(generator.forceCompilationAsync());\n }\n }\n return Promise.all(promises).then(() => {\n this._parent._endPerformanceCounter(\"Compile shadow generators\");\n });\n }\n _forEachExtensions(action) {\n for (const extension of this._extensions) {\n if (extension.enabled) {\n action(extension);\n }\n }\n }\n _applyExtensions(property, functionName, actionAsync) {\n for (const extension of this._extensions) {\n if (extension.enabled) {\n const id = `${extension.name}.${functionName}`;\n const loaderProperty = property;\n loaderProperty._activeLoaderExtensionFunctions = loaderProperty._activeLoaderExtensionFunctions || {};\n const activeLoaderExtensionFunctions = loaderProperty._activeLoaderExtensionFunctions;\n if (!activeLoaderExtensionFunctions[id]) {\n activeLoaderExtensionFunctions[id] = true;\n try {\n const result = actionAsync(extension);\n if (result) {\n return result;\n }\n }\n finally {\n delete activeLoaderExtensionFunctions[id];\n }\n }\n }\n }\n return null;\n }\n _extensionsOnLoading() {\n this._forEachExtensions((extension) => extension.onLoading && extension.onLoading());\n }\n _extensionsOnReady() {\n this._forEachExtensions((extension) => extension.onReady && extension.onReady());\n }\n _extensionsLoadSceneAsync(context, scene) {\n return this._applyExtensions(scene, \"loadScene\", (extension) => extension.loadSceneAsync && extension.loadSceneAsync(context, scene));\n }\n _extensionsLoadNodeAsync(context, node, assign) {\n return this._applyExtensions(node, \"loadNode\", (extension) => extension.loadNodeAsync && extension.loadNodeAsync(context, node, assign));\n }\n _extensionsLoadCameraAsync(context, camera, assign) {\n return this._applyExtensions(camera, \"loadCamera\", (extension) => extension.loadCameraAsync && extension.loadCameraAsync(context, camera, assign));\n }\n _extensionsLoadVertexDataAsync(context, primitive, babylonMesh) {\n return this._applyExtensions(primitive, \"loadVertexData\", (extension) => extension._loadVertexDataAsync && extension._loadVertexDataAsync(context, primitive, babylonMesh));\n }\n _extensionsLoadMeshPrimitiveAsync(context, name, node, mesh, primitive, assign) {\n return this._applyExtensions(primitive, \"loadMeshPrimitive\", (extension) => extension._loadMeshPrimitiveAsync && extension._loadMeshPrimitiveAsync(context, name, node, mesh, primitive, assign));\n }\n _extensionsLoadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign) {\n return this._applyExtensions(material, \"loadMaterial\", (extension) => extension._loadMaterialAsync && extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign));\n }\n _extensionsCreateMaterial(context, material, babylonDrawMode) {\n return this._applyExtensions(material, \"createMaterial\", (extension) => extension.createMaterial && extension.createMaterial(context, material, babylonDrawMode));\n }\n _extensionsLoadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return this._applyExtensions(material, \"loadMaterialProperties\", (extension) => extension.loadMaterialPropertiesAsync && extension.loadMaterialPropertiesAsync(context, material, babylonMaterial));\n }\n _extensionsLoadTextureInfoAsync(context, textureInfo, assign) {\n return this._applyExtensions(textureInfo, \"loadTextureInfo\", (extension) => extension.loadTextureInfoAsync && extension.loadTextureInfoAsync(context, textureInfo, assign));\n }\n _extensionsLoadTextureAsync(context, texture, assign) {\n return this._applyExtensions(texture, \"loadTexture\", (extension) => extension._loadTextureAsync && extension._loadTextureAsync(context, texture, assign));\n }\n _extensionsLoadAnimationAsync(context, animation) {\n return this._applyExtensions(animation, \"loadAnimation\", (extension) => extension.loadAnimationAsync && extension.loadAnimationAsync(context, animation));\n }\n _extensionsLoadAnimationChannelAsync(context, animationContext, animation, channel, onLoad) {\n return this._applyExtensions(animation, \"loadAnimationChannel\", (extension) => extension._loadAnimationChannelAsync && extension._loadAnimationChannelAsync(context, animationContext, animation, channel, onLoad));\n }\n _extensionsLoadSkinAsync(context, node, skin) {\n return this._applyExtensions(skin, \"loadSkin\", (extension) => extension._loadSkinAsync && extension._loadSkinAsync(context, node, skin));\n }\n _extensionsLoadUriAsync(context, property, uri) {\n return this._applyExtensions(property, \"loadUri\", (extension) => extension._loadUriAsync && extension._loadUriAsync(context, property, uri));\n }\n _extensionsLoadBufferViewAsync(context, bufferView) {\n return this._applyExtensions(bufferView, \"loadBufferView\", (extension) => extension.loadBufferViewAsync && extension.loadBufferViewAsync(context, bufferView));\n }\n _extensionsLoadBufferAsync(context, buffer, byteOffset, byteLength) {\n return this._applyExtensions(buffer, \"loadBuffer\", (extension) => extension.loadBufferAsync && extension.loadBufferAsync(context, buffer, byteOffset, byteLength));\n }\n /**\n * Helper method called by a loader extension to load an glTF extension.\n * @param context The context when loading the asset\n * @param property The glTF property to load the extension from\n * @param extensionName The name of the extension to load\n * @param actionAsync The action to run\n * @returns The promise returned by actionAsync or null if the extension does not exist\n */\n static LoadExtensionAsync(context, property, extensionName, actionAsync) {\n if (!property.extensions) {\n return null;\n }\n const extensions = property.extensions;\n const extension = extensions[extensionName];\n if (!extension) {\n return null;\n }\n return actionAsync(`${context}/extensions/${extensionName}`, extension);\n }\n /**\n * Helper method called by a loader extension to load a glTF extra.\n * @param context The context when loading the asset\n * @param property The glTF property to load the extra from\n * @param extensionName The name of the extension to load\n * @param actionAsync The action to run\n * @returns The promise returned by actionAsync or null if the extra does not exist\n */\n static LoadExtraAsync(context, property, extensionName, actionAsync) {\n if (!property.extras) {\n return null;\n }\n const extras = property.extras;\n const extra = extras[extensionName];\n if (!extra) {\n return null;\n }\n return actionAsync(`${context}/extras/${extensionName}`, extra);\n }\n /**\n * Checks for presence of an extension.\n * @param name The name of the extension to check\n * @returns A boolean indicating the presence of the given extension name in `extensionsUsed`\n */\n isExtensionUsed(name) {\n return !!this._gltf.extensionsUsed && this._gltf.extensionsUsed.indexOf(name) !== -1;\n }\n /**\n * Increments the indentation level and logs a message.\n * @param message The message to log\n */\n logOpen(message) {\n this._parent._logOpen(message);\n }\n /**\n * Decrements the indentation level.\n */\n logClose() {\n this._parent._logClose();\n }\n /**\n * Logs a message\n * @param message The message to log\n */\n log(message) {\n this._parent._log(message);\n }\n /**\n * Starts a performance counter.\n * @param counterName The name of the performance counter\n */\n startPerformanceCounter(counterName) {\n this._parent._startPerformanceCounter(counterName);\n }\n /**\n * Ends a performance counter.\n * @param counterName The name of the performance counter\n */\n endPerformanceCounter(counterName) {\n this._parent._endPerformanceCounter(counterName);\n }\n}\nGLTFLoader._RegisteredExtensions = {};\n/**\n * The default glTF sampler.\n */\nGLTFLoader.DefaultSampler = { index: -1 };\nGLTFFileLoader._CreateGLTF2Loader = (parent) => new GLTFLoader(parent);\n//# sourceMappingURL=glTFLoader.js.map","export {};\n//# sourceMappingURL=glTFLoaderExtension.js.map","import { Scalar } from \"@babylonjs/core/Maths/math.scalar.js\";\nimport { SphericalHarmonics, SphericalPolynomial } from \"@babylonjs/core/Maths/sphericalPolynomial.js\";\nimport { Quaternion, Matrix } from \"@babylonjs/core/Maths/math.vector.js\";\nimport { RawCubeTexture } from \"@babylonjs/core/Materials/Textures/rawCubeTexture.js\";\nimport { GLTFLoader, ArrayItem } from \"../glTFLoader.js\";\nconst NAME = \"EXT_lights_image_based\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Vendor/EXT_lights_image_based/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class EXT_lights_image_based {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n delete this._lights;\n }\n /** @internal */\n onLoading() {\n const extensions = this._loader.gltf.extensions;\n if (extensions && extensions[this.name]) {\n const extension = extensions[this.name];\n this._lights = extension.lights;\n }\n }\n /**\n * @internal\n */\n loadSceneAsync(context, scene) {\n return GLTFLoader.LoadExtensionAsync(context, scene, this.name, (extensionContext, extension) => {\n const promises = new Array();\n promises.push(this._loader.loadSceneAsync(context, scene));\n this._loader.logOpen(`${extensionContext}`);\n const light = ArrayItem.Get(`${extensionContext}/light`, this._lights, extension.light);\n promises.push(this._loadLightAsync(`/extensions/${this.name}/lights/${extension.light}`, light).then((texture) => {\n this._loader.babylonScene.environmentTexture = texture;\n }));\n this._loader.logClose();\n return Promise.all(promises).then(() => { });\n });\n }\n _loadLightAsync(context, light) {\n if (!light._loaded) {\n const promises = new Array();\n this._loader.logOpen(`${context}`);\n const imageData = new Array(light.specularImages.length);\n for (let mipmap = 0; mipmap < light.specularImages.length; mipmap++) {\n const faces = light.specularImages[mipmap];\n imageData[mipmap] = new Array(faces.length);\n for (let face = 0; face < faces.length; face++) {\n const specularImageContext = `${context}/specularImages/${mipmap}/${face}`;\n this._loader.logOpen(`${specularImageContext}`);\n const index = faces[face];\n const image = ArrayItem.Get(specularImageContext, this._loader.gltf.images, index);\n promises.push(this._loader.loadImageAsync(`/images/${index}`, image).then((data) => {\n imageData[mipmap][face] = data;\n }));\n this._loader.logClose();\n }\n }\n this._loader.logClose();\n light._loaded = Promise.all(promises).then(() => {\n const babylonTexture = new RawCubeTexture(this._loader.babylonScene, null, light.specularImageSize);\n babylonTexture.name = light.name || \"environment\";\n light._babylonTexture = babylonTexture;\n if (light.intensity != undefined) {\n babylonTexture.level = light.intensity;\n }\n if (light.rotation) {\n let rotation = Quaternion.FromArray(light.rotation);\n // Invert the rotation so that positive rotation is counter-clockwise.\n if (!this._loader.babylonScene.useRightHandedSystem) {\n rotation = Quaternion.Inverse(rotation);\n }\n Matrix.FromQuaternionToRef(rotation, babylonTexture.getReflectionTextureMatrix());\n }\n if (!light.irradianceCoefficients) {\n throw new Error(`${context}: Irradiance coefficients are missing`);\n }\n const sphericalHarmonics = SphericalHarmonics.FromArray(light.irradianceCoefficients);\n sphericalHarmonics.scaleInPlace(light.intensity);\n sphericalHarmonics.convertIrradianceToLambertianRadiance();\n const sphericalPolynomial = SphericalPolynomial.FromHarmonics(sphericalHarmonics);\n // Compute the lod generation scale to fit exactly to the number of levels available.\n const lodGenerationScale = (imageData.length - 1) / Scalar.Log2(light.specularImageSize);\n return babylonTexture.updateRGBDAsync(imageData, sphericalPolynomial, lodGenerationScale);\n });\n }\n return light._loaded.then(() => {\n return light._babylonTexture;\n });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new EXT_lights_image_based(loader));\n//# sourceMappingURL=EXT_lights_image_based.js.map","export {};\n//# sourceMappingURL=glTFLoaderInterfaces.js.map","import { Vector3, Quaternion, Matrix, TmpVectors } from \"@babylonjs/core/Maths/math.vector.js\";\nimport { GLTFLoader, ArrayItem } from \"../glTFLoader.js\";\nimport \"@babylonjs/core/Meshes/thinInstanceMesh.js\";\nconst NAME = \"EXT_mesh_gpu_instancing\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Vendor/EXT_mesh_gpu_instancing/README.md)\n * [Playground Sample](https://playground.babylonjs.com/#QFIGLW#9)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class EXT_mesh_gpu_instancing {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadNodeAsync(context, node, assign) {\n return GLTFLoader.LoadExtensionAsync(context, node, this.name, (extensionContext, extension) => {\n this._loader._disableInstancedMesh++;\n const promise = this._loader.loadNodeAsync(`/nodes/${node.index}`, node, assign);\n this._loader._disableInstancedMesh--;\n if (!node._primitiveBabylonMeshes) {\n return promise;\n }\n const promises = new Array();\n let instanceCount = 0;\n const loadAttribute = (attribute) => {\n if (extension.attributes[attribute] == undefined) {\n promises.push(Promise.resolve(null));\n return;\n }\n const accessor = ArrayItem.Get(`${extensionContext}/attributes/${attribute}`, this._loader.gltf.accessors, extension.attributes[attribute]);\n promises.push(this._loader._loadFloatAccessorAsync(`/accessors/${accessor.bufferView}`, accessor));\n if (instanceCount === 0) {\n instanceCount = accessor.count;\n }\n else if (instanceCount !== accessor.count) {\n throw new Error(`${extensionContext}/attributes: Instance buffer accessors do not have the same count.`);\n }\n };\n loadAttribute(\"TRANSLATION\");\n loadAttribute(\"ROTATION\");\n loadAttribute(\"SCALE\");\n return promise.then((babylonTransformNode) => {\n return Promise.all(promises).then(([translationBuffer, rotationBuffer, scaleBuffer]) => {\n const matrices = new Float32Array(instanceCount * 16);\n TmpVectors.Vector3[0].copyFromFloats(0, 0, 0); // translation\n TmpVectors.Quaternion[0].copyFromFloats(0, 0, 0, 1); // rotation\n TmpVectors.Vector3[1].copyFromFloats(1, 1, 1); // scale\n for (let i = 0; i < instanceCount; ++i) {\n translationBuffer && Vector3.FromArrayToRef(translationBuffer, i * 3, TmpVectors.Vector3[0]);\n rotationBuffer && Quaternion.FromArrayToRef(rotationBuffer, i * 4, TmpVectors.Quaternion[0]);\n scaleBuffer && Vector3.FromArrayToRef(scaleBuffer, i * 3, TmpVectors.Vector3[1]);\n Matrix.ComposeToRef(TmpVectors.Vector3[1], TmpVectors.Quaternion[0], TmpVectors.Vector3[0], TmpVectors.Matrix[0]);\n TmpVectors.Matrix[0].copyToArray(matrices, i * 16);\n }\n for (const babylonMesh of node._primitiveBabylonMeshes) {\n babylonMesh.thinInstanceSetBuffer(\"matrix\", matrices, 16, true);\n }\n return babylonTransformNode;\n });\n });\n });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new EXT_mesh_gpu_instancing(loader));\n//# sourceMappingURL=EXT_mesh_gpu_instancing.js.map","import { ArrayItem, GLTFLoader } from \"../glTFLoader.js\";\nimport { MeshoptCompression } from \"@babylonjs/core/Meshes/Compression/meshoptCompression.js\";\nconst NAME = \"EXT_meshopt_compression\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Vendor/EXT_meshopt_compression/README.md)\n *\n * This extension uses a WebAssembly decoder module from https://github.com/zeux/meshoptimizer/tree/master/js\n * @since 5.0.0\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class EXT_meshopt_compression {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n this.enabled = loader.isExtensionUsed(NAME);\n this._loader = loader;\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadBufferViewAsync(context, bufferView) {\n return GLTFLoader.LoadExtensionAsync(context, bufferView, this.name, (extensionContext, extension) => {\n const bufferViewMeshopt = bufferView;\n if (bufferViewMeshopt._meshOptData) {\n return bufferViewMeshopt._meshOptData;\n }\n const buffer = ArrayItem.Get(`${context}/buffer`, this._loader.gltf.buffers, extension.buffer);\n bufferViewMeshopt._meshOptData = this._loader.loadBufferAsync(`/buffers/${buffer.index}`, buffer, extension.byteOffset || 0, extension.byteLength).then((buffer) => {\n return MeshoptCompression.Default.decodeGltfBufferAsync(buffer, extension.count, extension.byteStride, extension.mode, extension.filter);\n });\n return bufferViewMeshopt._meshOptData;\n });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new EXT_meshopt_compression(loader));\n//# sourceMappingURL=EXT_meshopt_compression.js.map","import { GLTFLoader, ArrayItem } from \"../glTFLoader.js\";\nconst NAME = \"EXT_texture_webp\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Vendor/EXT_texture_webp/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class EXT_texture_webp {\n /**\n * @internal\n */\n constructor(loader) {\n /** The name of this extension. */\n this.name = NAME;\n this._loader = loader;\n this.enabled = loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n _loadTextureAsync(context, texture, assign) {\n return GLTFLoader.LoadExtensionAsync(context, texture, this.name, (extensionContext, extension) => {\n const sampler = texture.sampler == undefined ? GLTFLoader.DefaultSampler : ArrayItem.Get(`${context}/sampler`, this._loader.gltf.samplers, texture.sampler);\n const image = ArrayItem.Get(`${extensionContext}/source`, this._loader.gltf.images, extension.source);\n return this._loader._createTextureAsync(context, sampler, image, (babylonTexture) => {\n assign(babylonTexture);\n }, undefined, !texture._textureInfo.nonColorData);\n });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new EXT_texture_webp(loader));\n//# sourceMappingURL=EXT_texture_webp.js.map","import { DracoCompression } from \"@babylonjs/core/Meshes/Compression/dracoCompression.js\";\nimport { VertexBuffer } from \"@babylonjs/core/Buffers/buffer.js\";\nimport { Geometry } from \"@babylonjs/core/Meshes/geometry.js\";\nimport { GLTFLoader, ArrayItem } from \"../glTFLoader.js\";\nconst NAME = \"KHR_draco_mesh_compression\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_draco_mesh_compression/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_draco_mesh_compression {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n this._loader = loader;\n this.enabled = DracoCompression.DecoderAvailable && this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n delete this.dracoCompression;\n this._loader = null;\n }\n /**\n * @internal\n */\n _loadVertexDataAsync(context, primitive, babylonMesh) {\n return GLTFLoader.LoadExtensionAsync(context, primitive, this.name, (extensionContext, extension) => {\n if (primitive.mode != undefined) {\n if (primitive.mode !== 5 /* MeshPrimitiveMode.TRIANGLE_STRIP */ && primitive.mode !== 4 /* MeshPrimitiveMode.TRIANGLES */) {\n throw new Error(`${context}: Unsupported mode ${primitive.mode}`);\n }\n // TODO: handle triangle strips\n if (primitive.mode === 5 /* MeshPrimitiveMode.TRIANGLE_STRIP */) {\n throw new Error(`${context}: Mode ${primitive.mode} is not currently supported`);\n }\n }\n const attributes = {};\n const dividers = {};\n const loadAttribute = (name, kind) => {\n const uniqueId = extension.attributes[name];\n if (uniqueId === undefined || primitive.attributes[name] === undefined) {\n return;\n }\n attributes[kind] = uniqueId;\n const accessor = ArrayItem.Get(`${context}/attributes/${name}`, this._loader.gltf.accessors, primitive.attributes[name]);\n if (accessor.normalized && accessor.componentType !== 5126 /* AccessorComponentType.FLOAT */) {\n let divider = 1;\n switch (accessor.componentType) {\n case 5120 /* AccessorComponentType.BYTE */:\n divider = 127.0;\n break;\n case 5121 /* AccessorComponentType.UNSIGNED_BYTE */:\n divider = 255.0;\n break;\n case 5122 /* AccessorComponentType.SHORT */:\n divider = 32767.0;\n break;\n case 5123 /* AccessorComponentType.UNSIGNED_SHORT */:\n divider = 65535.0;\n break;\n }\n dividers[kind] = divider;\n }\n babylonMesh._delayInfo = babylonMesh._delayInfo || [];\n if (babylonMesh._delayInfo.indexOf(kind) === -1) {\n babylonMesh._delayInfo.push(kind);\n }\n };\n loadAttribute(\"POSITION\", VertexBuffer.PositionKind);\n loadAttribute(\"NORMAL\", VertexBuffer.NormalKind);\n loadAttribute(\"TANGENT\", VertexBuffer.TangentKind);\n loadAttribute(\"TEXCOORD_0\", VertexBuffer.UVKind);\n loadAttribute(\"TEXCOORD_1\", VertexBuffer.UV2Kind);\n loadAttribute(\"TEXCOORD_2\", VertexBuffer.UV3Kind);\n loadAttribute(\"TEXCOORD_3\", VertexBuffer.UV4Kind);\n loadAttribute(\"TEXCOORD_4\", VertexBuffer.UV5Kind);\n loadAttribute(\"TEXCOORD_5\", VertexBuffer.UV6Kind);\n loadAttribute(\"JOINTS_0\", VertexBuffer.MatricesIndicesKind);\n loadAttribute(\"WEIGHTS_0\", VertexBuffer.MatricesWeightsKind);\n loadAttribute(\"COLOR_0\", VertexBuffer.ColorKind);\n const bufferView = ArrayItem.Get(extensionContext, this._loader.gltf.bufferViews, extension.bufferView);\n if (!bufferView._dracoBabylonGeometry) {\n bufferView._dracoBabylonGeometry = this._loader.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView).then((data) => {\n const dracoCompression = this.dracoCompression || DracoCompression.Default;\n return dracoCompression\n .decodeMeshAsync(data, attributes, dividers)\n .then((babylonVertexData) => {\n const babylonGeometry = new Geometry(babylonMesh.name, this._loader.babylonScene);\n babylonVertexData.applyToGeometry(babylonGeometry);\n return babylonGeometry;\n })\n .catch((error) => {\n throw new Error(`${context}: ${error.message}`);\n });\n });\n }\n return bufferView._dracoBabylonGeometry;\n });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_draco_mesh_compression(loader));\n//# sourceMappingURL=KHR_draco_mesh_compression.js.map","import { Vector3 } from \"@babylonjs/core/Maths/math.vector.js\";\nimport { Color3 } from \"@babylonjs/core/Maths/math.color.js\";\nimport { DirectionalLight } from \"@babylonjs/core/Lights/directionalLight.js\";\nimport { PointLight } from \"@babylonjs/core/Lights/pointLight.js\";\nimport { SpotLight } from \"@babylonjs/core/Lights/spotLight.js\";\nimport { Light } from \"@babylonjs/core/Lights/light.js\";\nimport { GLTFLoader, ArrayItem } from \"../glTFLoader.js\";\nconst NAME = \"KHR_lights_punctual\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_lights_punctual/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_lights {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n delete this._lights;\n }\n /** @internal */\n onLoading() {\n const extensions = this._loader.gltf.extensions;\n if (extensions && extensions[this.name]) {\n const extension = extensions[this.name];\n this._lights = extension.lights;\n ArrayItem.Assign(this._lights);\n }\n }\n /**\n * @internal\n */\n loadNodeAsync(context, node, assign) {\n return GLTFLoader.LoadExtensionAsync(context, node, this.name, (extensionContext, extension) => {\n return this._loader.loadNodeAsync(context, node, (babylonMesh) => {\n let babylonLight;\n const light = ArrayItem.Get(extensionContext, this._lights, extension.light);\n const name = light.name || babylonMesh.name;\n this._loader.babylonScene._blockEntityCollection = !!this._loader._assetContainer;\n switch (light.type) {\n case \"directional\" /* KHRLightsPunctual_LightType.DIRECTIONAL */: {\n const babylonDirectionalLight = new DirectionalLight(name, Vector3.Backward(), this._loader.babylonScene);\n babylonDirectionalLight.position.setAll(0);\n babylonLight = babylonDirectionalLight;\n break;\n }\n case \"point\" /* KHRLightsPunctual_LightType.POINT */: {\n babylonLight = new PointLight(name, Vector3.Zero(), this._loader.babylonScene);\n break;\n }\n case \"spot\" /* KHRLightsPunctual_LightType.SPOT */: {\n const babylonSpotLight = new SpotLight(name, Vector3.Zero(), Vector3.Backward(), 0, 1, this._loader.babylonScene);\n babylonSpotLight.angle = ((light.spot && light.spot.outerConeAngle) || Math.PI / 4) * 2;\n babylonSpotLight.innerAngle = ((light.spot && light.spot.innerConeAngle) || 0) * 2;\n babylonLight = babylonSpotLight;\n break;\n }\n default: {\n this._loader.babylonScene._blockEntityCollection = false;\n throw new Error(`${extensionContext}: Invalid light type (${light.type})`);\n }\n }\n babylonLight._parentContainer = this._loader._assetContainer;\n this._loader.babylonScene._blockEntityCollection = false;\n light._babylonLight = babylonLight;\n babylonLight.falloffType = Light.FALLOFF_GLTF;\n babylonLight.diffuse = light.color ? Color3.FromArray(light.color) : Color3.White();\n babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;\n babylonLight.range = light.range == undefined ? Number.MAX_VALUE : light.range;\n babylonLight.parent = babylonMesh;\n this._loader._babylonLights.push(babylonLight);\n GLTFLoader.AddPointerMetadata(babylonLight, extensionContext);\n assign(babylonMesh);\n });\n });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_lights(loader));\n//# sourceMappingURL=KHR_lights_punctual.js.map","import { Color3 } from \"@babylonjs/core/Maths/math.color.js\";\nimport { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"KHR_materials_pbrSpecularGlossiness\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Archived/KHR_materials_pbrSpecularGlossiness/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_materials_pbrSpecularGlossiness {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 200;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => {\n const promises = new Array();\n promises.push(this._loader.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));\n this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial);\n return Promise.all(promises).then(() => { });\n });\n }\n _loadSpecularGlossinessPropertiesAsync(context, material, properties, babylonMaterial) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n const promises = new Array();\n babylonMaterial.metallic = null;\n babylonMaterial.roughness = null;\n if (properties.diffuseFactor) {\n babylonMaterial.albedoColor = Color3.FromArray(properties.diffuseFactor);\n babylonMaterial.alpha = properties.diffuseFactor[3];\n }\n else {\n babylonMaterial.albedoColor = Color3.White();\n }\n babylonMaterial.reflectivityColor = properties.specularFactor ? Color3.FromArray(properties.specularFactor) : Color3.White();\n babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;\n if (properties.diffuseTexture) {\n promises.push(this._loader.loadTextureInfoAsync(`${context}/diffuseTexture`, properties.diffuseTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Diffuse)`;\n babylonMaterial.albedoTexture = texture;\n }));\n }\n if (properties.specularGlossinessTexture) {\n promises.push(this._loader.loadTextureInfoAsync(`${context}/specularGlossinessTexture`, properties.specularGlossinessTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Specular Glossiness)`;\n babylonMaterial.reflectivityTexture = texture;\n babylonMaterial.reflectivityTexture.hasAlpha = true;\n }));\n babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;\n }\n return Promise.all(promises).then(() => { });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_materials_pbrSpecularGlossiness(loader));\n//# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map","import { Color3 } from \"@babylonjs/core/Maths/math.color.js\";\nimport { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"KHR_materials_unlit\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_unlit/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_materials_unlit {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 210;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtensionAsync(context, material, this.name, () => {\n return this._loadUnlitPropertiesAsync(context, material, babylonMaterial);\n });\n }\n _loadUnlitPropertiesAsync(context, material, babylonMaterial) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n const promises = new Array();\n babylonMaterial.unlit = true;\n const properties = material.pbrMetallicRoughness;\n if (properties) {\n if (properties.baseColorFactor) {\n babylonMaterial.albedoColor = Color3.FromArray(properties.baseColorFactor);\n babylonMaterial.alpha = properties.baseColorFactor[3];\n }\n else {\n babylonMaterial.albedoColor = Color3.White();\n }\n if (properties.baseColorTexture) {\n promises.push(this._loader.loadTextureInfoAsync(`${context}/baseColorTexture`, properties.baseColorTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Base Color)`;\n babylonMaterial.albedoTexture = texture;\n }));\n }\n }\n if (material.doubleSided) {\n babylonMaterial.backFaceCulling = false;\n babylonMaterial.twoSidedLighting = true;\n }\n this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial);\n return Promise.all(promises).then(() => { });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_materials_unlit(loader));\n//# sourceMappingURL=KHR_materials_unlit.js.map","import { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"KHR_materials_clearcoat\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_clearcoat/README.md)\n * [Playground Sample](https://www.babylonjs-playground.com/frame.html#7F7PN6#8)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_materials_clearcoat {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 190;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => {\n const promises = new Array();\n promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loadClearCoatPropertiesAsync(extensionContext, extension, babylonMaterial));\n return Promise.all(promises).then(() => { });\n });\n }\n _loadClearCoatPropertiesAsync(context, properties, babylonMaterial) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n const promises = new Array();\n babylonMaterial.clearCoat.isEnabled = true;\n babylonMaterial.clearCoat.useRoughnessFromMainTexture = false;\n babylonMaterial.clearCoat.remapF0OnInterfaceChange = false;\n if (properties.clearcoatFactor != undefined) {\n babylonMaterial.clearCoat.intensity = properties.clearcoatFactor;\n }\n else {\n babylonMaterial.clearCoat.intensity = 0;\n }\n if (properties.clearcoatTexture) {\n promises.push(this._loader.loadTextureInfoAsync(`${context}/clearcoatTexture`, properties.clearcoatTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (ClearCoat Intensity)`;\n babylonMaterial.clearCoat.texture = texture;\n }));\n }\n if (properties.clearcoatRoughnessFactor != undefined) {\n babylonMaterial.clearCoat.roughness = properties.clearcoatRoughnessFactor;\n }\n else {\n babylonMaterial.clearCoat.roughness = 0;\n }\n if (properties.clearcoatRoughnessTexture) {\n properties.clearcoatRoughnessTexture.nonColorData = true;\n promises.push(this._loader.loadTextureInfoAsync(`${context}/clearcoatRoughnessTexture`, properties.clearcoatRoughnessTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (ClearCoat Roughness)`;\n babylonMaterial.clearCoat.textureRoughness = texture;\n }));\n }\n if (properties.clearcoatNormalTexture) {\n properties.clearcoatNormalTexture.nonColorData = true;\n promises.push(this._loader.loadTextureInfoAsync(`${context}/clearcoatNormalTexture`, properties.clearcoatNormalTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (ClearCoat Normal)`;\n babylonMaterial.clearCoat.bumpTexture = texture;\n }));\n babylonMaterial.invertNormalMapX = !babylonMaterial.getScene().useRightHandedSystem;\n babylonMaterial.invertNormalMapY = babylonMaterial.getScene().useRightHandedSystem;\n if (properties.clearcoatNormalTexture.scale != undefined) {\n babylonMaterial.clearCoat.bumpTexture.level = properties.clearcoatNormalTexture.scale;\n }\n }\n return Promise.all(promises).then(() => { });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_materials_clearcoat(loader));\n//# sourceMappingURL=KHR_materials_clearcoat.js.map","import { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"KHR_materials_iridescence\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_iridescence/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_materials_iridescence {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 195;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => {\n const promises = new Array();\n promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loadIridescencePropertiesAsync(extensionContext, extension, babylonMaterial));\n return Promise.all(promises).then(() => { });\n });\n }\n _loadIridescencePropertiesAsync(context, properties, babylonMaterial) {\n var _a, _b, _c, _d, _e;\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n const promises = new Array();\n babylonMaterial.iridescence.isEnabled = true;\n babylonMaterial.iridescence.intensity = (_a = properties.iridescenceFactor) !== null && _a !== void 0 ? _a : 0;\n babylonMaterial.iridescence.indexOfRefraction = (_c = (_b = properties.iridescenceIor) !== null && _b !== void 0 ? _b : properties.iridescenceIOR) !== null && _c !== void 0 ? _c : 1.3;\n babylonMaterial.iridescence.minimumThickness = (_d = properties.iridescenceThicknessMinimum) !== null && _d !== void 0 ? _d : 100;\n babylonMaterial.iridescence.maximumThickness = (_e = properties.iridescenceThicknessMaximum) !== null && _e !== void 0 ? _e : 400;\n if (properties.iridescenceTexture) {\n promises.push(this._loader.loadTextureInfoAsync(`${context}/iridescenceTexture`, properties.iridescenceTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Iridescence Intensity)`;\n babylonMaterial.iridescence.texture = texture;\n }));\n }\n if (properties.iridescenceThicknessTexture) {\n promises.push(this._loader.loadTextureInfoAsync(`${context}/iridescenceThicknessTexture`, properties.iridescenceThicknessTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Iridescence Thickness)`;\n babylonMaterial.iridescence.thicknessTexture = texture;\n }));\n }\n return Promise.all(promises).then(() => { });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_materials_iridescence(loader));\n//# sourceMappingURL=KHR_materials_iridescence.js.map","import { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"KHR_materials_anisotropy\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_anisotropy)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_materials_anisotropy {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 195;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => {\n const promises = new Array();\n promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loadIridescencePropertiesAsync(extensionContext, extension, babylonMaterial));\n return Promise.all(promises).then(() => { });\n });\n }\n _loadIridescencePropertiesAsync(context, properties, babylonMaterial) {\n var _a, _b;\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n const promises = new Array();\n babylonMaterial.anisotropy.isEnabled = true;\n babylonMaterial.anisotropy.intensity = (_a = properties.anisotropyStrength) !== null && _a !== void 0 ? _a : 0;\n babylonMaterial.anisotropy.angle = (_b = properties.anisotropyRotation) !== null && _b !== void 0 ? _b : 0;\n if (properties.anisotropyTexture) {\n promises.push(this._loader.loadTextureInfoAsync(`${context}/anisotropyTexture`, properties.anisotropyTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Anisotropy Intensity)`;\n babylonMaterial.anisotropy.texture = texture;\n }));\n }\n return Promise.all(promises).then(() => { });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_materials_anisotropy(loader));\n//# sourceMappingURL=KHR_materials_anisotropy.js.map","import { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"KHR_materials_emissive_strength\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_emissive_strength/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_materials_emissive_strength {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 170;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => {\n return this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial).then(() => {\n this._loadEmissiveProperties(extensionContext, extension, babylonMaterial);\n });\n });\n }\n _loadEmissiveProperties(context, properties, babylonMaterial) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n if (properties.emissiveStrength !== undefined) {\n babylonMaterial.emissiveColor.scaleToRef(properties.emissiveStrength, babylonMaterial.emissiveColor);\n }\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_materials_emissive_strength(loader));\n//# sourceMappingURL=KHR_materials_emissive_strength.js.map","import { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nimport { Color3 } from \"@babylonjs/core/Maths/math.color.js\";\nconst NAME = \"KHR_materials_sheen\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_sheen/README.md)\n * [Playground Sample](https://www.babylonjs-playground.com/frame.html#BNIZX6#4)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_materials_sheen {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 190;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => {\n const promises = new Array();\n promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loadSheenPropertiesAsync(extensionContext, extension, babylonMaterial));\n return Promise.all(promises).then(() => { });\n });\n }\n _loadSheenPropertiesAsync(context, properties, babylonMaterial) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n const promises = new Array();\n babylonMaterial.sheen.isEnabled = true;\n babylonMaterial.sheen.intensity = 1;\n if (properties.sheenColorFactor != undefined) {\n babylonMaterial.sheen.color = Color3.FromArray(properties.sheenColorFactor);\n }\n else {\n babylonMaterial.sheen.color = Color3.Black();\n }\n if (properties.sheenColorTexture) {\n promises.push(this._loader.loadTextureInfoAsync(`${context}/sheenColorTexture`, properties.sheenColorTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Sheen Color)`;\n babylonMaterial.sheen.texture = texture;\n }));\n }\n if (properties.sheenRoughnessFactor !== undefined) {\n babylonMaterial.sheen.roughness = properties.sheenRoughnessFactor;\n }\n else {\n babylonMaterial.sheen.roughness = 0;\n }\n if (properties.sheenRoughnessTexture) {\n properties.sheenRoughnessTexture.nonColorData = true;\n promises.push(this._loader.loadTextureInfoAsync(`${context}/sheenRoughnessTexture`, properties.sheenRoughnessTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Sheen Roughness)`;\n babylonMaterial.sheen.textureRoughness = texture;\n }));\n }\n babylonMaterial.sheen.albedoScaling = true;\n babylonMaterial.sheen.useRoughnessFromMainTexture = false;\n return Promise.all(promises).then(() => { });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_materials_sheen(loader));\n//# sourceMappingURL=KHR_materials_sheen.js.map","import { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nimport { Color3 } from \"@babylonjs/core/Maths/math.color.js\";\nconst NAME = \"KHR_materials_specular\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_specular/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_materials_specular {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 190;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => {\n const promises = new Array();\n promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loadSpecularPropertiesAsync(extensionContext, extension, babylonMaterial));\n return Promise.all(promises).then(() => { });\n });\n }\n _loadSpecularPropertiesAsync(context, properties, babylonMaterial) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n const promises = new Array();\n if (properties.specularFactor !== undefined) {\n babylonMaterial.metallicF0Factor = properties.specularFactor;\n }\n if (properties.specularColorFactor !== undefined) {\n babylonMaterial.metallicReflectanceColor = Color3.FromArray(properties.specularColorFactor);\n }\n if (properties.specularTexture) {\n properties.specularTexture.nonColorData = true;\n promises.push(this._loader.loadTextureInfoAsync(`${context}/specularTexture`, properties.specularTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Specular F0 Strength)`;\n babylonMaterial.metallicReflectanceTexture = texture;\n babylonMaterial.useOnlyMetallicFromMetallicReflectanceTexture = true;\n }));\n }\n if (properties.specularColorTexture) {\n promises.push(this._loader.loadTextureInfoAsync(`${context}/specularColorTexture`, properties.specularColorTexture, (texture) => {\n texture.name = `${babylonMaterial.name} (Specular F0 Color)`;\n babylonMaterial.reflectanceTexture = texture;\n }));\n }\n return Promise.all(promises).then(() => { });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_materials_specular(loader));\n//# sourceMappingURL=KHR_materials_specular.js.map","import { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"KHR_materials_ior\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_ior/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_materials_ior {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 180;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => {\n const promises = new Array();\n promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loadIorPropertiesAsync(extensionContext, extension, babylonMaterial));\n return Promise.all(promises).then(() => { });\n });\n }\n _loadIorPropertiesAsync(context, properties, babylonMaterial) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n if (properties.ior !== undefined) {\n babylonMaterial.indexOfRefraction = properties.ior;\n }\n else {\n babylonMaterial.indexOfRefraction = KHR_materials_ior._DEFAULT_IOR;\n }\n return Promise.resolve();\n }\n}\n/**\n * Default ior Value from the spec.\n */\nKHR_materials_ior._DEFAULT_IOR = 1.5;\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_materials_ior(loader));\n//# sourceMappingURL=KHR_materials_ior.js.map","import { GLTFLoader, ArrayItem } from \"../glTFLoader.js\";\nimport { Mesh } from \"@babylonjs/core/Meshes/mesh.js\";\nconst NAME = \"KHR_materials_variants\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_variants/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_materials_variants {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * Gets the list of available variant names for this asset.\n * @param rootMesh The glTF root mesh\n * @returns the list of all the variant names for this model\n */\n static GetAvailableVariants(rootMesh) {\n const extensionMetadata = this._GetExtensionMetadata(rootMesh);\n if (!extensionMetadata) {\n return [];\n }\n return Object.keys(extensionMetadata.variants);\n }\n /**\n * Gets the list of available variant names for this asset.\n * @param rootMesh The glTF root mesh\n * @returns the list of all the variant names for this model\n */\n getAvailableVariants(rootMesh) {\n return KHR_materials_variants.GetAvailableVariants(rootMesh);\n }\n /**\n * Select a variant given a variant name or a list of variant names.\n * @param rootMesh The glTF root mesh\n * @param variantName The variant name(s) to select.\n */\n static SelectVariant(rootMesh, variantName) {\n const extensionMetadata = this._GetExtensionMetadata(rootMesh);\n if (!extensionMetadata) {\n throw new Error(`Cannot select variant on a glTF mesh that does not have the ${NAME} extension`);\n }\n const select = (variantName) => {\n const entries = extensionMetadata.variants[variantName];\n if (entries) {\n for (const entry of entries) {\n entry.mesh.material = entry.material;\n }\n }\n };\n if (variantName instanceof Array) {\n for (const name of variantName) {\n select(name);\n }\n }\n else {\n select(variantName);\n }\n extensionMetadata.lastSelected = variantName;\n }\n /**\n * Select a variant given a variant name or a list of variant names.\n * @param rootMesh The glTF root mesh\n * @param variantName The variant name(s) to select.\n */\n selectVariant(rootMesh, variantName) {\n return KHR_materials_variants.SelectVariant(rootMesh, variantName);\n }\n /**\n * Reset back to the original before selecting a variant.\n * @param rootMesh The glTF root mesh\n */\n static Reset(rootMesh) {\n const extensionMetadata = this._GetExtensionMetadata(rootMesh);\n if (!extensionMetadata) {\n throw new Error(`Cannot reset on a glTF mesh that does not have the ${NAME} extension`);\n }\n for (const entry of extensionMetadata.original) {\n entry.mesh.material = entry.material;\n }\n extensionMetadata.lastSelected = null;\n }\n /**\n * Reset back to the original before selecting a variant.\n * @param rootMesh The glTF root mesh\n */\n reset(rootMesh) {\n return KHR_materials_variants.Reset(rootMesh);\n }\n /**\n * Gets the last selected variant name(s) or null if original.\n * @param rootMesh The glTF root mesh\n * @returns The selected variant name(s).\n */\n static GetLastSelectedVariant(rootMesh) {\n const extensionMetadata = this._GetExtensionMetadata(rootMesh);\n if (!extensionMetadata) {\n throw new Error(`Cannot get the last selected variant on a glTF mesh that does not have the ${NAME} extension`);\n }\n return extensionMetadata.lastSelected;\n }\n /**\n * Gets the last selected variant name(s) or null if original.\n * @param rootMesh The glTF root mesh\n * @returns The selected variant name(s).\n */\n getLastSelectedVariant(rootMesh) {\n return KHR_materials_variants.GetLastSelectedVariant(rootMesh);\n }\n static _GetExtensionMetadata(rootMesh) {\n var _a, _b;\n return ((_b = (_a = rootMesh === null || rootMesh === void 0 ? void 0 : rootMesh._internalMetadata) === null || _a === void 0 ? void 0 : _a.gltf) === null || _b === void 0 ? void 0 : _b[NAME]) || null;\n }\n /** @internal */\n onLoading() {\n const extensions = this._loader.gltf.extensions;\n if (extensions && extensions[this.name]) {\n const extension = extensions[this.name];\n this._variants = extension.variants;\n }\n }\n /**\n * @internal\n */\n _loadMeshPrimitiveAsync(context, name, node, mesh, primitive, assign) {\n return GLTFLoader.LoadExtensionAsync(context, primitive, this.name, (extensionContext, extension) => {\n const promises = new Array();\n promises.push(this._loader._loadMeshPrimitiveAsync(context, name, node, mesh, primitive, (babylonMesh) => {\n assign(babylonMesh);\n if (babylonMesh instanceof Mesh) {\n const babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);\n const root = this._loader.rootBabylonMesh;\n const metadata = root ? (root._internalMetadata = root._internalMetadata || {}) : {};\n const gltf = (metadata.gltf = metadata.gltf || {});\n const extensionMetadata = (gltf[NAME] = gltf[NAME] || { lastSelected: null, original: [], variants: {} });\n // Store the original material.\n extensionMetadata.original.push({ mesh: babylonMesh, material: babylonMesh.material });\n // For each mapping, look at the variants and make a new entry for them.\n for (let mappingIndex = 0; mappingIndex < extension.mappings.length; ++mappingIndex) {\n const mapping = extension.mappings[mappingIndex];\n const material = ArrayItem.Get(`${extensionContext}/mappings/${mappingIndex}/material`, this._loader.gltf.materials, mapping.material);\n promises.push(this._loader._loadMaterialAsync(`#/materials/${mapping.material}`, material, babylonMesh, babylonDrawMode, (babylonMaterial) => {\n for (let mappingVariantIndex = 0; mappingVariantIndex < mapping.variants.length; ++mappingVariantIndex) {\n const variantIndex = mapping.variants[mappingVariantIndex];\n const variant = ArrayItem.Get(`/extensions/${NAME}/variants/${variantIndex}`, this._variants, variantIndex);\n extensionMetadata.variants[variant.name] = extensionMetadata.variants[variant.name] || [];\n extensionMetadata.variants[variant.name].push({\n mesh: babylonMesh,\n material: babylonMaterial,\n });\n // Replace the target when original mesh is cloned\n babylonMesh.onClonedObservable.add((newOne) => {\n const newMesh = newOne;\n let metadata = null;\n let newRoot = newMesh;\n // Find root to get medata\n do {\n newRoot = newRoot.parent;\n if (!newRoot) {\n return;\n }\n metadata = KHR_materials_variants._GetExtensionMetadata(newRoot);\n } while (metadata === null);\n // Need to clone the metadata on the root (first time only)\n if (root && metadata === KHR_materials_variants._GetExtensionMetadata(root)) {\n // Copy main metadata\n newRoot._internalMetadata = {};\n for (const key in root._internalMetadata) {\n newRoot._internalMetadata[key] = root._internalMetadata[key];\n }\n // Copy the gltf metadata\n newRoot._internalMetadata.gltf = [];\n for (const key in root._internalMetadata.gltf) {\n newRoot._internalMetadata.gltf[key] = root._internalMetadata.gltf[key];\n }\n // Duplicate the extension specific metadata\n newRoot._internalMetadata.gltf[NAME] = { lastSelected: null, original: [], variants: {} };\n for (const original of metadata.original) {\n newRoot._internalMetadata.gltf[NAME].original.push({\n mesh: original.mesh,\n material: original.material,\n });\n }\n for (const key in metadata.variants) {\n if (Object.prototype.hasOwnProperty.call(metadata.variants, key)) {\n newRoot._internalMetadata.gltf[NAME].variants[key] = [];\n for (const variantEntry of metadata.variants[key]) {\n newRoot._internalMetadata.gltf[NAME].variants[key].push({\n mesh: variantEntry.mesh,\n material: variantEntry.material,\n });\n }\n }\n }\n metadata = newRoot._internalMetadata.gltf[NAME];\n }\n // Relocate\n for (const target of metadata.original) {\n if (target.mesh === babylonMesh) {\n target.mesh = newMesh;\n }\n }\n for (const target of metadata.variants[variant.name]) {\n if (target.mesh === babylonMesh) {\n target.mesh = newMesh;\n }\n }\n });\n }\n }));\n }\n }\n }));\n return Promise.all(promises).then(([babylonMesh]) => {\n return babylonMesh;\n });\n });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_materials_variants(loader));\n//# sourceMappingURL=KHR_materials_variants.js.map","import { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nimport { RenderTargetTexture } from \"@babylonjs/core/Materials/Textures/renderTargetTexture.js\";\nimport { Observable } from \"@babylonjs/core/Misc/observable.js\";\nimport { Constants } from \"@babylonjs/core/Engines/constants.js\";\nimport { Tools } from \"@babylonjs/core/Misc/tools.js\";\n/**\n * A class to handle setting up the rendering of opaque objects to be shown through transmissive objects.\n */\nclass TransmissionHelper {\n /**\n * Creates the default options for the helper.\n */\n static _GetDefaultOptions() {\n return {\n renderSize: 1024,\n samples: 4,\n lodGenerationScale: 1,\n lodGenerationOffset: -4,\n renderTargetTextureType: Constants.TEXTURETYPE_HALF_FLOAT,\n generateMipmaps: true,\n };\n }\n /**\n * constructor\n * @param options Defines the options we want to customize the helper\n * @param scene The scene to add the material to\n */\n constructor(options, scene) {\n this._opaqueRenderTarget = null;\n this._opaqueMeshesCache = [];\n this._transparentMeshesCache = [];\n this._materialObservers = {};\n this._options = {\n ...TransmissionHelper._GetDefaultOptions(),\n ...options,\n };\n this._scene = scene;\n this._scene._transmissionHelper = this;\n this.onErrorObservable = new Observable();\n this._scene.onDisposeObservable.addOnce(() => {\n this.dispose();\n });\n this._parseScene();\n this._setupRenderTargets();\n }\n /**\n * Updates the background according to the new options\n * @param options\n */\n updateOptions(options) {\n // First check if any options are actually being changed. If not, exit.\n const newValues = Object.keys(options).filter((key) => this._options[key] !== options[key]);\n if (!newValues.length) {\n return;\n }\n const newOptions = {\n ...this._options,\n ...options,\n };\n const oldOptions = this._options;\n this._options = newOptions;\n // If size changes, recreate everything\n if (newOptions.renderSize !== oldOptions.renderSize ||\n newOptions.renderTargetTextureType !== oldOptions.renderTargetTextureType ||\n newOptions.generateMipmaps !== oldOptions.generateMipmaps ||\n !this._opaqueRenderTarget) {\n this._setupRenderTargets();\n }\n else {\n this._opaqueRenderTarget.samples = newOptions.samples;\n this._opaqueRenderTarget.lodGenerationScale = newOptions.lodGenerationScale;\n this._opaqueRenderTarget.lodGenerationOffset = newOptions.lodGenerationOffset;\n }\n }\n /**\n * Gets the opaque render target texture or null if not available.\n */\n getOpaqueTarget() {\n return this._opaqueRenderTarget;\n }\n _shouldRenderAsTransmission(material) {\n if (!material) {\n return false;\n }\n if (material instanceof PBRMaterial && material.subSurface.isRefractionEnabled) {\n return true;\n }\n return false;\n }\n _addMesh(mesh) {\n this._materialObservers[mesh.uniqueId] = mesh.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this));\n // we need to defer the processing because _addMesh may be called as part as an instance mesh creation, in which case some\n // internal properties are not setup yet, like _sourceMesh (needed when doing mesh.material below)\n Tools.SetImmediate(() => {\n if (this._shouldRenderAsTransmission(mesh.material)) {\n mesh.material.refractionTexture = this._opaqueRenderTarget;\n if (this._transparentMeshesCache.indexOf(mesh) === -1) {\n this._transparentMeshesCache.push(mesh);\n }\n }\n else {\n if (this._opaqueMeshesCache.indexOf(mesh) === -1) {\n this._opaqueMeshesCache.push(mesh);\n }\n }\n });\n }\n _removeMesh(mesh) {\n mesh.onMaterialChangedObservable.remove(this._materialObservers[mesh.uniqueId]);\n delete this._materialObservers[mesh.uniqueId];\n let idx = this._transparentMeshesCache.indexOf(mesh);\n if (idx !== -1) {\n this._transparentMeshesCache.splice(idx, 1);\n }\n idx = this._opaqueMeshesCache.indexOf(mesh);\n if (idx !== -1) {\n this._opaqueMeshesCache.splice(idx, 1);\n }\n }\n _parseScene() {\n this._scene.meshes.forEach(this._addMesh.bind(this));\n // Listen for when a mesh is added to the scene and add it to our cache lists.\n this._scene.onNewMeshAddedObservable.add(this._addMesh.bind(this));\n // Listen for when a mesh is removed from to the scene and remove it from our cache lists.\n this._scene.onMeshRemovedObservable.add(this._removeMesh.bind(this));\n }\n // When one of the meshes in the scene has its material changed, make sure that it's in the correct cache list.\n _onMeshMaterialChanged(mesh) {\n const transparentIdx = this._transparentMeshesCache.indexOf(mesh);\n const opaqueIdx = this._opaqueMeshesCache.indexOf(mesh);\n // If the material is transparent, make sure that it's added to the transparent list and removed from the opaque list\n const useTransmission = this._shouldRenderAsTransmission(mesh.material);\n if (useTransmission) {\n if (mesh.material instanceof PBRMaterial) {\n mesh.material.subSurface.refractionTexture = this._opaqueRenderTarget;\n }\n if (opaqueIdx !== -1) {\n this._opaqueMeshesCache.splice(opaqueIdx, 1);\n this._transparentMeshesCache.push(mesh);\n }\n else if (transparentIdx === -1) {\n this._transparentMeshesCache.push(mesh);\n }\n // If the material is opaque, make sure that it's added to the opaque list and removed from the transparent list\n }\n else {\n if (transparentIdx !== -1) {\n this._transparentMeshesCache.splice(transparentIdx, 1);\n this._opaqueMeshesCache.push(mesh);\n }\n else if (opaqueIdx === -1) {\n this._opaqueMeshesCache.push(mesh);\n }\n }\n }\n /**\n * Setup the render targets according to the specified options.\n */\n _setupRenderTargets() {\n var _a, _b;\n if (this._opaqueRenderTarget) {\n this._opaqueRenderTarget.dispose();\n }\n this._opaqueRenderTarget = new RenderTargetTexture(\"opaqueSceneTexture\", this._options.renderSize, this._scene, this._options.generateMipmaps, undefined, this._options.renderTargetTextureType);\n this._opaqueRenderTarget.ignoreCameraViewport = true;\n this._opaqueRenderTarget.renderList = this._opaqueMeshesCache;\n this._opaqueRenderTarget.clearColor = (_b = (_a = this._options.clearColor) === null || _a === void 0 ? void 0 : _a.clone()) !== null && _b !== void 0 ? _b : this._scene.clearColor.clone();\n this._opaqueRenderTarget.gammaSpace = false;\n this._opaqueRenderTarget.lodGenerationScale = this._options.lodGenerationScale;\n this._opaqueRenderTarget.lodGenerationOffset = this._options.lodGenerationOffset;\n this._opaqueRenderTarget.samples = this._options.samples;\n let sceneImageProcessingapplyByPostProcess;\n let saveSceneEnvIntensity;\n this._opaqueRenderTarget.onBeforeBindObservable.add((opaqueRenderTarget) => {\n saveSceneEnvIntensity = this._scene.environmentIntensity;\n this._scene.environmentIntensity = 1.0;\n sceneImageProcessingapplyByPostProcess = this._scene.imageProcessingConfiguration.applyByPostProcess;\n if (!this._options.clearColor) {\n this._scene.clearColor.toLinearSpaceToRef(opaqueRenderTarget.clearColor, this._scene.getEngine().useExactSrgbConversions);\n }\n else {\n opaqueRenderTarget.clearColor.copyFrom(this._options.clearColor);\n }\n // we do not use the applyByPostProcess setter to avoid flagging all the materials as \"image processing dirty\"!\n this._scene.imageProcessingConfiguration._applyByPostProcess = true;\n });\n this._opaqueRenderTarget.onAfterUnbindObservable.add(() => {\n this._scene.environmentIntensity = saveSceneEnvIntensity;\n this._scene.imageProcessingConfiguration._applyByPostProcess = sceneImageProcessingapplyByPostProcess;\n });\n this._transparentMeshesCache.forEach((mesh) => {\n if (this._shouldRenderAsTransmission(mesh.material)) {\n mesh.material.refractionTexture = this._opaqueRenderTarget;\n }\n });\n }\n /**\n * Dispose all the elements created by the Helper.\n */\n dispose() {\n this._scene._transmissionHelper = undefined;\n if (this._opaqueRenderTarget) {\n this._opaqueRenderTarget.dispose();\n this._opaqueRenderTarget = null;\n }\n this._transparentMeshesCache = [];\n this._opaqueMeshesCache = [];\n }\n}\nconst NAME = \"KHR_materials_transmission\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_transmission/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_materials_transmission {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 175;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n if (this.enabled) {\n loader.parent.transparencyAsCoverage = true;\n }\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => {\n const promises = new Array();\n promises.push(this._loader.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loadTransparentPropertiesAsync(extensionContext, material, babylonMaterial, extension));\n return Promise.all(promises).then(() => { });\n });\n }\n _loadTransparentPropertiesAsync(context, material, babylonMaterial, extension) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n const pbrMaterial = babylonMaterial;\n // Enables \"refraction\" texture which represents transmitted light.\n pbrMaterial.subSurface.isRefractionEnabled = true;\n // Since this extension models thin-surface transmission only, we must make IOR = 1.0\n pbrMaterial.subSurface.volumeIndexOfRefraction = 1.0;\n // Albedo colour will tint transmission.\n pbrMaterial.subSurface.useAlbedoToTintRefraction = true;\n if (extension.transmissionFactor !== undefined) {\n pbrMaterial.subSurface.refractionIntensity = extension.transmissionFactor;\n const scene = pbrMaterial.getScene();\n if (pbrMaterial.subSurface.refractionIntensity && !scene._transmissionHelper) {\n new TransmissionHelper({}, pbrMaterial.getScene());\n }\n }\n else {\n pbrMaterial.subSurface.refractionIntensity = 0.0;\n pbrMaterial.subSurface.isRefractionEnabled = false;\n return Promise.resolve();\n }\n pbrMaterial.subSurface.minimumThickness = 0.0;\n pbrMaterial.subSurface.maximumThickness = 0.0;\n if (extension.transmissionTexture) {\n extension.transmissionTexture.nonColorData = true;\n return this._loader.loadTextureInfoAsync(`${context}/transmissionTexture`, extension.transmissionTexture, undefined).then((texture) => {\n pbrMaterial.subSurface.refractionIntensityTexture = texture;\n pbrMaterial.subSurface.useGltfStyleTextures = true;\n });\n }\n else {\n return Promise.resolve();\n }\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_materials_transmission(loader));\n//# sourceMappingURL=KHR_materials_transmission.js.map","import { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"KHR_materials_translucency\";\n/**\n * [Proposed Specification](https://github.com/KhronosGroup/glTF/pull/1825)\n * !!! Experimental Extension Subject to Changes !!!\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_materials_translucency {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 174;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n if (this.enabled) {\n loader.parent.transparencyAsCoverage = true;\n }\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => {\n const promises = new Array();\n promises.push(this._loader.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loadTranslucentPropertiesAsync(extensionContext, material, babylonMaterial, extension));\n return Promise.all(promises).then(() => { });\n });\n }\n _loadTranslucentPropertiesAsync(context, material, babylonMaterial, extension) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n const pbrMaterial = babylonMaterial;\n // Enables \"translucency\" texture which represents diffusely-transmitted light.\n pbrMaterial.subSurface.isTranslucencyEnabled = true;\n // Since this extension models thin-surface transmission only, we must make the\n // internal IOR == 1.0 and set the thickness to 0.\n pbrMaterial.subSurface.volumeIndexOfRefraction = 1.0;\n pbrMaterial.subSurface.minimumThickness = 0.0;\n pbrMaterial.subSurface.maximumThickness = 0.0;\n // Albedo colour will tint transmission.\n pbrMaterial.subSurface.useAlbedoToTintTranslucency = true;\n if (extension.translucencyFactor !== undefined) {\n pbrMaterial.subSurface.translucencyIntensity = extension.translucencyFactor;\n }\n else {\n pbrMaterial.subSurface.translucencyIntensity = 0.0;\n pbrMaterial.subSurface.isTranslucencyEnabled = false;\n return Promise.resolve();\n }\n if (extension.translucencyTexture) {\n extension.translucencyTexture.nonColorData = true;\n return this._loader.loadTextureInfoAsync(`${context}/translucencyTexture`, extension.translucencyTexture).then((texture) => {\n pbrMaterial.subSurface.translucencyIntensityTexture = texture;\n });\n }\n else {\n return Promise.resolve();\n }\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_materials_translucency(loader));\n//# sourceMappingURL=KHR_materials_translucency.js.map","import { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"KHR_materials_volume\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_materials_volume/README.md)\n * @since 5.0.0\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_materials_volume {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 173;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n if (this.enabled) {\n // We need to disable instance usage because the attenuation factor depends on the node scale of each individual mesh\n this._loader._disableInstancedMesh++;\n }\n }\n /** @internal */\n dispose() {\n if (this.enabled) {\n this._loader._disableInstancedMesh--;\n }\n this._loader = null;\n }\n /**\n * @internal\n */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => {\n const promises = new Array();\n promises.push(this._loader.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial));\n promises.push(this._loadVolumePropertiesAsync(extensionContext, material, babylonMaterial, extension));\n return Promise.all(promises).then(() => { });\n });\n }\n _loadVolumePropertiesAsync(context, material, babylonMaterial, extension) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${context}: Material type not supported`);\n }\n // If transparency isn't enabled already, this extension shouldn't do anything.\n // i.e. it requires either the KHR_materials_transmission or KHR_materials_translucency extensions.\n if ((!babylonMaterial.subSurface.isRefractionEnabled && !babylonMaterial.subSurface.isTranslucencyEnabled) || !extension.thicknessFactor) {\n return Promise.resolve();\n }\n // IOR in this extension only affects interior.\n babylonMaterial.subSurface.volumeIndexOfRefraction = babylonMaterial.indexOfRefraction;\n const attenuationDistance = extension.attenuationDistance !== undefined ? extension.attenuationDistance : Number.MAX_VALUE;\n babylonMaterial.subSurface.tintColorAtDistance = attenuationDistance;\n if (extension.attenuationColor !== undefined && extension.attenuationColor.length == 3) {\n babylonMaterial.subSurface.tintColor.copyFromFloats(extension.attenuationColor[0], extension.attenuationColor[1], extension.attenuationColor[2]);\n }\n babylonMaterial.subSurface.minimumThickness = 0.0;\n babylonMaterial.subSurface.maximumThickness = extension.thicknessFactor;\n babylonMaterial.subSurface.useThicknessAsDepth = true;\n if (extension.thicknessTexture) {\n extension.thicknessTexture.nonColorData = true;\n return this._loader.loadTextureInfoAsync(`${context}/thicknessTexture`, extension.thicknessTexture).then((texture) => {\n babylonMaterial.subSurface.thicknessTexture = texture;\n babylonMaterial.subSurface.useGltfStyleTextures = true;\n });\n }\n else {\n return Promise.resolve();\n }\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_materials_volume(loader));\n//# sourceMappingURL=KHR_materials_volume.js.map","import { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"KHR_mesh_quantization\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_mesh_quantization/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_mesh_quantization {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n this.enabled = loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() { }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_mesh_quantization(loader));\n//# sourceMappingURL=KHR_mesh_quantization.js.map","import { GLTFLoader, ArrayItem } from \"../glTFLoader.js\";\nconst NAME = \"KHR_texture_basisu\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_texture_basisu/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_texture_basisu {\n /**\n * @internal\n */\n constructor(loader) {\n /** The name of this extension. */\n this.name = NAME;\n this._loader = loader;\n this.enabled = loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n _loadTextureAsync(context, texture, assign) {\n return GLTFLoader.LoadExtensionAsync(context, texture, this.name, (extensionContext, extension) => {\n const sampler = texture.sampler == undefined ? GLTFLoader.DefaultSampler : ArrayItem.Get(`${context}/sampler`, this._loader.gltf.samplers, texture.sampler);\n const image = ArrayItem.Get(`${extensionContext}/source`, this._loader.gltf.images, extension.source);\n return this._loader._createTextureAsync(context, sampler, image, (babylonTexture) => {\n assign(babylonTexture);\n }, texture._textureInfo.nonColorData ? { useRGBAIfASTCBC7NotAvailableWhenUASTC: true } : undefined, !texture._textureInfo.nonColorData);\n });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_texture_basisu(loader));\n//# sourceMappingURL=KHR_texture_basisu.js.map","import { Texture } from \"@babylonjs/core/Materials/Textures/texture.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"KHR_texture_transform\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_texture_transform/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_texture_transform {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadTextureInfoAsync(context, textureInfo, assign) {\n return GLTFLoader.LoadExtensionAsync(context, textureInfo, this.name, (extensionContext, extension) => {\n return this._loader.loadTextureInfoAsync(context, textureInfo, (babylonTexture) => {\n if (!(babylonTexture instanceof Texture)) {\n throw new Error(`${extensionContext}: Texture type not supported`);\n }\n if (extension.offset) {\n babylonTexture.uOffset = extension.offset[0];\n babylonTexture.vOffset = extension.offset[1];\n }\n // Always rotate around the origin.\n babylonTexture.uRotationCenter = 0;\n babylonTexture.vRotationCenter = 0;\n if (extension.rotation) {\n babylonTexture.wAng = -extension.rotation;\n }\n if (extension.scale) {\n babylonTexture.uScale = extension.scale[0];\n babylonTexture.vScale = extension.scale[1];\n }\n if (extension.texCoord != undefined) {\n babylonTexture.coordinatesIndex = extension.texCoord;\n }\n assign(babylonTexture);\n });\n });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_texture_transform(loader));\n//# sourceMappingURL=KHR_texture_transform.js.map","import { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"KHR_xmp_json_ld\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_xmp_json_ld/README.md)\n * @since 5.0.0\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_xmp_json_ld {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 100;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * Called after the loader state changes to LOADING.\n */\n onLoading() {\n var _a, _b, _c;\n if (this._loader.rootBabylonMesh === null) {\n return;\n }\n const xmp_gltf = (_a = this._loader.gltf.extensions) === null || _a === void 0 ? void 0 : _a.KHR_xmp_json_ld;\n const xmp_node = (_c = (_b = this._loader.gltf.asset) === null || _b === void 0 ? void 0 : _b.extensions) === null || _c === void 0 ? void 0 : _c.KHR_xmp_json_ld;\n if (xmp_gltf && xmp_node) {\n const packet = +xmp_node.packet;\n if (xmp_gltf.packets && packet < xmp_gltf.packets.length) {\n this._loader.rootBabylonMesh.metadata = this._loader.rootBabylonMesh.metadata || {};\n this._loader.rootBabylonMesh.metadata.xmp = xmp_gltf.packets[packet];\n }\n }\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_xmp_json_ld(loader));\n//# sourceMappingURL=KHR_xmp_json_ld.js.map","/* eslint-disable @typescript-eslint/naming-convention */\nimport { Animation } from \"@babylonjs/core/Animations/animation.js\";\nimport { AnimationPropertyInfo, nodeAnimationData } from \"../glTFLoaderAnimation.js\";\nimport { Color3 } from \"@babylonjs/core/Maths/math.color.js\";\nfunction getColor3(_target, source, offset, scale) {\n return Color3.FromArray(source, offset).scale(scale);\n}\nfunction getAlpha(_target, source, offset, scale) {\n return source[offset + 3] * scale;\n}\nfunction getFloat(_target, source, offset, scale) {\n return source[offset] * scale;\n}\nfunction getMinusFloat(_target, source, offset, scale) {\n return -source[offset] * scale;\n}\nfunction getNextFloat(_target, source, offset, scale) {\n return source[offset + 1] * scale;\n}\nfunction getFloatBy2(_target, source, offset, scale) {\n return source[offset] * scale * 2;\n}\nfunction getTextureTransformTree(textureName) {\n return {\n scale: [\n new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, `${textureName}.uScale`, getFloat, () => 2),\n new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, `${textureName}.vScale`, getNextFloat, () => 2),\n ],\n offset: [\n new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, `${textureName}.uOffset`, getFloat, () => 2),\n new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, `${textureName}.vOffset`, getNextFloat, () => 2),\n ],\n rotation: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, `${textureName}.wAng`, getMinusFloat, () => 1)],\n };\n}\nclass CameraAnimationPropertyInfo extends AnimationPropertyInfo {\n /** @internal */\n buildAnimations(target, name, fps, keys, callback) {\n callback(target._babylonCamera, this._buildAnimation(name, fps, keys));\n }\n}\nclass MaterialAnimationPropertyInfo extends AnimationPropertyInfo {\n /** @internal */\n buildAnimations(target, name, fps, keys, callback) {\n for (const fillMode in target._data) {\n callback(target._data[fillMode].babylonMaterial, this._buildAnimation(name, fps, keys));\n }\n }\n}\nclass LightAnimationPropertyInfo extends AnimationPropertyInfo {\n /** @internal */\n buildAnimations(target, name, fps, keys, callback) {\n callback(target._babylonLight, this._buildAnimation(name, fps, keys));\n }\n}\nconst nodesTree = {\n __array__: {\n __target__: true,\n ...nodeAnimationData,\n },\n};\nconst camerasTree = {\n __array__: {\n __target__: true,\n orthographic: {\n xmag: [\n new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"orthoLeft\", getMinusFloat, () => 1),\n new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"orthoRight\", getNextFloat, () => 1),\n ],\n ymag: [\n new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"orthoBottom\", getMinusFloat, () => 1),\n new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"orthoTop\", getNextFloat, () => 1),\n ],\n zfar: [new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"maxZ\", getFloat, () => 1)],\n znear: [new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"minZ\", getFloat, () => 1)],\n },\n perspective: {\n yfov: [new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"fov\", getFloat, () => 1)],\n zfar: [new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"maxZ\", getFloat, () => 1)],\n znear: [new CameraAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"minZ\", getFloat, () => 1)],\n },\n },\n};\nconst materialsTree = {\n __array__: {\n __target__: true,\n pbrMetallicRoughness: {\n baseColorFactor: [\n new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_COLOR3, \"albedoColor\", getColor3, () => 4),\n new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"alpha\", getAlpha, () => 4),\n ],\n metallicFactor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"metallic\", getFloat, () => 1)],\n roughnessFactor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"roughness\", getFloat, () => 1)],\n baseColorTexture: {\n extensions: {\n KHR_texture_transform: getTextureTransformTree(\"albedoTexture\"),\n },\n },\n },\n emissiveFactor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_COLOR3, \"emissiveColor\", getColor3, () => 3)],\n normalTexture: {\n scale: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"bumpTexture.level\", getFloat, () => 1)],\n },\n occlusionTexture: {\n strength: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"ambientTextureStrength\", getFloat, () => 1)],\n extensions: {\n KHR_texture_transform: getTextureTransformTree(\"ambientTexture\"),\n },\n },\n emissiveTexture: {\n extensions: {\n KHR_texture_transform: getTextureTransformTree(\"emissiveTexture\"),\n },\n },\n extensions: {\n KHR_materials_ior: {\n ior: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"indexOfRefraction\", getFloat, () => 1)],\n },\n KHR_materials_clearcoat: {\n clearcoatFactor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"clearCoat.intensity\", getFloat, () => 1)],\n clearcoatRoughnessFactor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"clearCoat.roughness\", getFloat, () => 1)],\n },\n KHR_materials_sheen: {\n sheenColorFactor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_COLOR3, \"sheen.color\", getColor3, () => 3)],\n sheenRoughnessFactor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"sheen.roughness\", getFloat, () => 1)],\n },\n KHR_materials_specular: {\n specularFactor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"metallicF0Factor\", getFloat, () => 1)],\n specularColorFactor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_COLOR3, \"metallicReflectanceColor\", getColor3, () => 3)],\n },\n KHR_materials_emissive_strength: {\n emissiveStrength: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"emissiveIntensity\", getFloat, () => 1)],\n },\n KHR_materials_transmission: {\n transmissionFactor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"subSurface.refractionIntensity\", getFloat, () => 1)],\n },\n KHR_materials_volume: {\n attenuationColor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_COLOR3, \"subSurface.tintColor\", getColor3, () => 3)],\n attenuationDistance: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"subSurface.tintColorAtDistance\", getFloat, () => 1)],\n thicknessFactor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"subSurface.maximumThickness\", getFloat, () => 1)],\n },\n KHR_materials_iridescence: {\n iridescenceFactor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"iridescence.intensity\", getFloat, () => 1)],\n iridescenceIor: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"iridescence.indexOfRefraction\", getFloat, () => 1)],\n iridescenceThicknessMinimum: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"iridescence.minimumThickness\", getFloat, () => 1)],\n iridescenceThicknessMaximum: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"iridescence.maximumThickness\", getFloat, () => 1)],\n },\n KHR_materials_anisotropy: {\n anisotropyStrength: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"anisotropy.intensity\", getFloat, () => 1)],\n anisotropyRotation: [new MaterialAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"anisotropy.angle\", getFloat, () => 1)],\n },\n },\n },\n};\nconst extensionsTree = {\n KHR_lights_punctual: {\n lights: {\n __array__: {\n __target__: true,\n color: [new LightAnimationPropertyInfo(Animation.ANIMATIONTYPE_COLOR3, \"diffuse\", getColor3, () => 3)],\n intensity: [new LightAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"intensity\", getFloat, () => 1)],\n range: [new LightAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"range\", getFloat, () => 1)],\n spot: {\n innerConeAngle: [new LightAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"innerAngle\", getFloatBy2, () => 1)],\n outerConeAngle: [new LightAnimationPropertyInfo(Animation.ANIMATIONTYPE_FLOAT, \"angle\", getFloatBy2, () => 1)],\n },\n },\n },\n },\n};\n/** @internal */\nexport const animationPointerTree = {\n nodes: nodesTree,\n materials: materialsTree,\n cameras: camerasTree,\n extensions: extensionsTree,\n};\n//# sourceMappingURL=KHR_animation_pointer.data.js.map","import { GLTFLoader } from \"../glTFLoader.js\";\nimport { Logger } from \"@babylonjs/core/Misc/logger.js\";\nimport { animationPointerTree } from \"./KHR_animation_pointer.data.js\";\nconst NAME = \"KHR_animation_pointer\";\n/**\n * [Specification PR](https://github.com/KhronosGroup/glTF/pull/2147)\n * !!! Experimental Extension Subject to Changes !!!\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class KHR_animation_pointer {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n this._loader = loader;\n }\n /**\n * Defines whether this extension is enabled.\n */\n get enabled() {\n return this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * Loads a glTF animation channel.\n * @param context The context when loading the asset\n * @param animationContext The context of the animation when loading the asset\n * @param animation The glTF animation property\n * @param channel The glTF animation channel property\n * @param onLoad Called for each animation loaded\n * @returns A void promise that resolves when the load is complete or null if not handled\n */\n _loadAnimationChannelAsync(context, animationContext, animation, channel, onLoad) {\n var _a;\n const extension = (_a = channel.target.extensions) === null || _a === void 0 ? void 0 : _a.KHR_animation_pointer;\n if (!extension) {\n return null;\n }\n if (channel.target.path !== \"pointer\" /* AnimationChannelTargetPath.POINTER */) {\n Logger.Warn(`${context}/target/path: Value (${channel.target.path}) must be (${\"pointer\" /* AnimationChannelTargetPath.POINTER */}) when using the ${this.name} extension`);\n }\n if (channel.target.node != undefined) {\n Logger.Warn(`${context}/target/node: Value (${channel.target.node}) must not be present when using the ${this.name} extension`);\n }\n const extensionContext = `${context}/extensions/${this.name}`;\n const pointer = extension.pointer;\n if (!pointer) {\n throw new Error(`${extensionContext}: Pointer is missing`);\n }\n const targetInfo = this._parseAnimationPointer(`${extensionContext}/pointer`, pointer);\n if (!targetInfo) {\n Logger.Warn(`${extensionContext}/pointer: Invalid pointer (${pointer}) skipped`);\n return null;\n }\n return this._loader._loadAnimationChannelFromTargetInfoAsync(context, animationContext, animation, channel, targetInfo, onLoad);\n }\n /**\n * The pointer string is represented by a [JSON pointer](https://datatracker.ietf.org/doc/html/rfc6901).\n * := ///\n * := \"nodes\" | \"materials\" | \"meshes\" | \"cameras\" | \"extensions\"\n * := | \n * := | \n * := \"extensions\"//\n * := | /\n * := W+\n * := D+\n *\n * Examples:\n * - \"/nodes/0/rotation\"\n * - \"/materials/2/emissiveFactor\"\n * - \"/materials/2/pbrMetallicRoughness/baseColorFactor\"\n * - \"/materials/2/extensions/KHR_materials_emissive_strength/emissiveStrength\"\n */\n _parseAnimationPointer(context, pointer) {\n if (!pointer.startsWith(\"/\")) {\n Logger.Warn(`${context}: Value (${pointer}) must start with a slash`);\n return null;\n }\n const parts = pointer.split(\"/\");\n // Remove the first part since it will be empty string as pointers must start with a slash.\n parts.shift();\n let node = animationPointerTree;\n let gltfCurrentNode = this._loader.gltf;\n let gltfTargetNode = undefined;\n for (const part of parts) {\n if (node.__array__) {\n node = node.__array__;\n }\n else {\n node = node[part];\n if (!node) {\n return null;\n }\n }\n gltfCurrentNode = gltfCurrentNode && gltfCurrentNode[part];\n if (node.__target__) {\n gltfTargetNode = gltfCurrentNode;\n }\n }\n if (!gltfTargetNode || !Array.isArray(node)) {\n return null;\n }\n return {\n target: gltfTargetNode,\n properties: node,\n };\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new KHR_animation_pointer(loader));\n//# sourceMappingURL=KHR_animation_pointer.js.map","import { Vector3 } from \"@babylonjs/core/Maths/math.vector.js\";\nimport { Tools } from \"@babylonjs/core/Misc/tools.js\";\nimport { AnimationEvent } from \"@babylonjs/core/Animations/animationEvent.js\";\nimport { Sound } from \"@babylonjs/core/Audio/sound.js\";\nimport { WeightedSound } from \"@babylonjs/core/Audio/weightedsound.js\";\nimport { GLTFLoader, ArrayItem } from \"../glTFLoader.js\";\nconst NAME = \"MSFT_audio_emitter\";\n/**\n * [Specification](https://github.com/najadojo/glTF/blob/MSFT_audio_emitter/extensions/2.0/Vendor/MSFT_audio_emitter/README.md)\n * !!! Experimental Extension Subject to Changes !!!\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class MSFT_audio_emitter {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n this._clips = null;\n this._emitters = null;\n }\n /** @internal */\n onLoading() {\n const extensions = this._loader.gltf.extensions;\n if (extensions && extensions[this.name]) {\n const extension = extensions[this.name];\n this._clips = extension.clips;\n this._emitters = extension.emitters;\n ArrayItem.Assign(this._clips);\n ArrayItem.Assign(this._emitters);\n }\n }\n /**\n * @internal\n */\n loadSceneAsync(context, scene) {\n return GLTFLoader.LoadExtensionAsync(context, scene, this.name, (extensionContext, extension) => {\n const promises = new Array();\n promises.push(this._loader.loadSceneAsync(context, scene));\n for (const emitterIndex of extension.emitters) {\n const emitter = ArrayItem.Get(`${extensionContext}/emitters`, this._emitters, emitterIndex);\n if (emitter.refDistance != undefined ||\n emitter.maxDistance != undefined ||\n emitter.rolloffFactor != undefined ||\n emitter.distanceModel != undefined ||\n emitter.innerAngle != undefined ||\n emitter.outerAngle != undefined) {\n throw new Error(`${extensionContext}: Direction or Distance properties are not allowed on emitters attached to a scene`);\n }\n promises.push(this._loadEmitterAsync(`${extensionContext}/emitters/${emitter.index}`, emitter));\n }\n return Promise.all(promises).then(() => { });\n });\n }\n /**\n * @internal\n */\n loadNodeAsync(context, node, assign) {\n return GLTFLoader.LoadExtensionAsync(context, node, this.name, (extensionContext, extension) => {\n const promises = new Array();\n return this._loader\n .loadNodeAsync(extensionContext, node, (babylonMesh) => {\n for (const emitterIndex of extension.emitters) {\n const emitter = ArrayItem.Get(`${extensionContext}/emitters`, this._emitters, emitterIndex);\n promises.push(this._loadEmitterAsync(`${extensionContext}/emitters/${emitter.index}`, emitter).then(() => {\n for (const sound of emitter._babylonSounds) {\n sound.attachToMesh(babylonMesh);\n if (emitter.innerAngle != undefined || emitter.outerAngle != undefined) {\n sound.setLocalDirectionToMesh(Vector3.Forward());\n sound.setDirectionalCone(2 * Tools.ToDegrees(emitter.innerAngle == undefined ? Math.PI : emitter.innerAngle), 2 * Tools.ToDegrees(emitter.outerAngle == undefined ? Math.PI : emitter.outerAngle), 0);\n }\n }\n }));\n }\n assign(babylonMesh);\n })\n .then((babylonMesh) => {\n return Promise.all(promises).then(() => {\n return babylonMesh;\n });\n });\n });\n }\n /**\n * @internal\n */\n loadAnimationAsync(context, animation) {\n return GLTFLoader.LoadExtensionAsync(context, animation, this.name, (extensionContext, extension) => {\n return this._loader.loadAnimationAsync(context, animation).then((babylonAnimationGroup) => {\n const promises = new Array();\n ArrayItem.Assign(extension.events);\n for (const event of extension.events) {\n promises.push(this._loadAnimationEventAsync(`${extensionContext}/events/${event.index}`, context, animation, event, babylonAnimationGroup));\n }\n return Promise.all(promises).then(() => {\n return babylonAnimationGroup;\n });\n });\n });\n }\n _loadClipAsync(context, clip) {\n if (clip._objectURL) {\n return clip._objectURL;\n }\n let promise;\n if (clip.uri) {\n promise = this._loader.loadUriAsync(context, clip, clip.uri);\n }\n else {\n const bufferView = ArrayItem.Get(`${context}/bufferView`, this._loader.gltf.bufferViews, clip.bufferView);\n promise = this._loader.loadBufferViewAsync(`/bufferViews/${bufferView.index}`, bufferView);\n }\n clip._objectURL = promise.then((data) => {\n return URL.createObjectURL(new Blob([data], { type: clip.mimeType }));\n });\n return clip._objectURL;\n }\n _loadEmitterAsync(context, emitter) {\n emitter._babylonSounds = emitter._babylonSounds || [];\n if (!emitter._babylonData) {\n const clipPromises = new Array();\n const name = emitter.name || `emitter${emitter.index}`;\n const options = {\n loop: false,\n autoplay: false,\n volume: emitter.volume == undefined ? 1 : emitter.volume,\n };\n for (let i = 0; i < emitter.clips.length; i++) {\n const clipContext = `/extensions/${this.name}/clips`;\n const clip = ArrayItem.Get(clipContext, this._clips, emitter.clips[i].clip);\n clipPromises.push(this._loadClipAsync(`${clipContext}/${emitter.clips[i].clip}`, clip).then((objectURL) => {\n const sound = (emitter._babylonSounds[i] = new Sound(name, objectURL, this._loader.babylonScene, null, options));\n sound.refDistance = emitter.refDistance || 1;\n sound.maxDistance = emitter.maxDistance || 256;\n sound.rolloffFactor = emitter.rolloffFactor || 1;\n sound.distanceModel = emitter.distanceModel || \"exponential\";\n }));\n }\n const promise = Promise.all(clipPromises).then(() => {\n const weights = emitter.clips.map((clip) => {\n return clip.weight || 1;\n });\n const weightedSound = new WeightedSound(emitter.loop || false, emitter._babylonSounds, weights);\n if (emitter.innerAngle) {\n weightedSound.directionalConeInnerAngle = 2 * Tools.ToDegrees(emitter.innerAngle);\n }\n if (emitter.outerAngle) {\n weightedSound.directionalConeOuterAngle = 2 * Tools.ToDegrees(emitter.outerAngle);\n }\n if (emitter.volume) {\n weightedSound.volume = emitter.volume;\n }\n emitter._babylonData.sound = weightedSound;\n });\n emitter._babylonData = {\n loaded: promise,\n };\n }\n return emitter._babylonData.loaded;\n }\n _getEventAction(context, sound, action, time, startOffset) {\n switch (action) {\n case \"play\" /* IMSFTAudioEmitter_AnimationEventAction.play */: {\n return (currentFrame) => {\n const frameOffset = (startOffset || 0) + (currentFrame - time);\n sound.play(frameOffset);\n };\n }\n case \"stop\" /* IMSFTAudioEmitter_AnimationEventAction.stop */: {\n return () => {\n sound.stop();\n };\n }\n case \"pause\" /* IMSFTAudioEmitter_AnimationEventAction.pause */: {\n return () => {\n sound.pause();\n };\n }\n default: {\n throw new Error(`${context}: Unsupported action ${action}`);\n }\n }\n }\n _loadAnimationEventAsync(context, animationContext, animation, event, babylonAnimationGroup) {\n if (babylonAnimationGroup.targetedAnimations.length == 0) {\n return Promise.resolve();\n }\n const babylonAnimation = babylonAnimationGroup.targetedAnimations[0];\n const emitterIndex = event.emitter;\n const emitter = ArrayItem.Get(`/extensions/${this.name}/emitters`, this._emitters, emitterIndex);\n return this._loadEmitterAsync(context, emitter).then(() => {\n const sound = emitter._babylonData.sound;\n if (sound) {\n const babylonAnimationEvent = new AnimationEvent(event.time, this._getEventAction(context, sound, event.action, event.time, event.startOffset));\n babylonAnimation.animation.addEvent(babylonAnimationEvent);\n // Make sure all started audio stops when this animation is terminated.\n babylonAnimationGroup.onAnimationGroupEndObservable.add(() => {\n sound.stop();\n });\n babylonAnimationGroup.onAnimationGroupPauseObservable.add(() => {\n sound.pause();\n });\n }\n });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new MSFT_audio_emitter(loader));\n//# sourceMappingURL=MSFT_audio_emitter.js.map","import { Observable } from \"@babylonjs/core/Misc/observable.js\";\nimport { Deferred } from \"@babylonjs/core/Misc/deferred.js\";\nimport { GLTFLoader, ArrayItem } from \"../glTFLoader.js\";\nconst NAME = \"MSFT_lod\";\n/**\n * [Specification](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Vendor/MSFT_lod/README.md)\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class MSFT_lod {\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines a number that determines the order the extensions are applied.\n */\n this.order = 100;\n /**\n * Maximum number of LODs to load, starting from the lowest LOD.\n */\n this.maxLODsToLoad = 10;\n /**\n * Observable raised when all node LODs of one level are loaded.\n * The event data is the index of the loaded LOD starting from zero.\n * Dispose the loader to cancel the loading of the next level of LODs.\n */\n this.onNodeLODsLoadedObservable = new Observable();\n /**\n * Observable raised when all material LODs of one level are loaded.\n * The event data is the index of the loaded LOD starting from zero.\n * Dispose the loader to cancel the loading of the next level of LODs.\n */\n this.onMaterialLODsLoadedObservable = new Observable();\n this._bufferLODs = new Array();\n this._nodeIndexLOD = null;\n this._nodeSignalLODs = new Array();\n this._nodePromiseLODs = new Array();\n this._nodeBufferLODs = new Array();\n this._materialIndexLOD = null;\n this._materialSignalLODs = new Array();\n this._materialPromiseLODs = new Array();\n this._materialBufferLODs = new Array();\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n this._nodeIndexLOD = null;\n this._nodeSignalLODs.length = 0;\n this._nodePromiseLODs.length = 0;\n this._nodeBufferLODs.length = 0;\n this._materialIndexLOD = null;\n this._materialSignalLODs.length = 0;\n this._materialPromiseLODs.length = 0;\n this._materialBufferLODs.length = 0;\n this.onMaterialLODsLoadedObservable.clear();\n this.onNodeLODsLoadedObservable.clear();\n }\n /** @internal */\n onReady() {\n for (let indexLOD = 0; indexLOD < this._nodePromiseLODs.length; indexLOD++) {\n const promise = Promise.all(this._nodePromiseLODs[indexLOD]).then(() => {\n if (indexLOD !== 0) {\n this._loader.endPerformanceCounter(`Node LOD ${indexLOD}`);\n this._loader.log(`Loaded node LOD ${indexLOD}`);\n }\n this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);\n if (indexLOD !== this._nodePromiseLODs.length - 1) {\n this._loader.startPerformanceCounter(`Node LOD ${indexLOD + 1}`);\n this._loadBufferLOD(this._nodeBufferLODs, indexLOD + 1);\n if (this._nodeSignalLODs[indexLOD]) {\n this._nodeSignalLODs[indexLOD].resolve();\n }\n }\n });\n this._loader._completePromises.push(promise);\n }\n for (let indexLOD = 0; indexLOD < this._materialPromiseLODs.length; indexLOD++) {\n const promise = Promise.all(this._materialPromiseLODs[indexLOD]).then(() => {\n if (indexLOD !== 0) {\n this._loader.endPerformanceCounter(`Material LOD ${indexLOD}`);\n this._loader.log(`Loaded material LOD ${indexLOD}`);\n }\n this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);\n if (indexLOD !== this._materialPromiseLODs.length - 1) {\n this._loader.startPerformanceCounter(`Material LOD ${indexLOD + 1}`);\n this._loadBufferLOD(this._materialBufferLODs, indexLOD + 1);\n if (this._materialSignalLODs[indexLOD]) {\n this._materialSignalLODs[indexLOD].resolve();\n }\n }\n });\n this._loader._completePromises.push(promise);\n }\n }\n /**\n * @internal\n */\n loadSceneAsync(context, scene) {\n const promise = this._loader.loadSceneAsync(context, scene);\n this._loadBufferLOD(this._bufferLODs, 0);\n return promise;\n }\n /**\n * @internal\n */\n loadNodeAsync(context, node, assign) {\n return GLTFLoader.LoadExtensionAsync(context, node, this.name, (extensionContext, extension) => {\n let firstPromise;\n const nodeLODs = this._getLODs(extensionContext, node, this._loader.gltf.nodes, extension.ids);\n this._loader.logOpen(`${extensionContext}`);\n for (let indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {\n const nodeLOD = nodeLODs[indexLOD];\n if (indexLOD !== 0) {\n this._nodeIndexLOD = indexLOD;\n this._nodeSignalLODs[indexLOD] = this._nodeSignalLODs[indexLOD] || new Deferred();\n }\n const assignWrap = (babylonTransformNode) => {\n assign(babylonTransformNode);\n babylonTransformNode.setEnabled(false);\n };\n const promise = this._loader.loadNodeAsync(`/nodes/${nodeLOD.index}`, nodeLOD, assignWrap).then((babylonMesh) => {\n if (indexLOD !== 0) {\n // TODO: should not rely on _babylonTransformNode\n const previousNodeLOD = nodeLODs[indexLOD - 1];\n if (previousNodeLOD._babylonTransformNode) {\n this._disposeTransformNode(previousNodeLOD._babylonTransformNode);\n delete previousNodeLOD._babylonTransformNode;\n }\n }\n babylonMesh.setEnabled(true);\n return babylonMesh;\n });\n this._nodePromiseLODs[indexLOD] = this._nodePromiseLODs[indexLOD] || [];\n if (indexLOD === 0) {\n firstPromise = promise;\n }\n else {\n this._nodeIndexLOD = null;\n this._nodePromiseLODs[indexLOD].push(promise);\n }\n }\n this._loader.logClose();\n return firstPromise;\n });\n }\n /**\n * @internal\n */\n _loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign) {\n // Don't load material LODs if already loading a node LOD.\n if (this._nodeIndexLOD) {\n return null;\n }\n return GLTFLoader.LoadExtensionAsync(context, material, this.name, (extensionContext, extension) => {\n let firstPromise;\n const materialLODs = this._getLODs(extensionContext, material, this._loader.gltf.materials, extension.ids);\n this._loader.logOpen(`${extensionContext}`);\n for (let indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {\n const materialLOD = materialLODs[indexLOD];\n if (indexLOD !== 0) {\n this._materialIndexLOD = indexLOD;\n }\n const promise = this._loader\n ._loadMaterialAsync(`/materials/${materialLOD.index}`, materialLOD, babylonMesh, babylonDrawMode, (babylonMaterial) => {\n if (indexLOD === 0) {\n assign(babylonMaterial);\n }\n })\n .then((babylonMaterial) => {\n if (indexLOD !== 0) {\n assign(babylonMaterial);\n // TODO: should not rely on _data\n const previousDataLOD = materialLODs[indexLOD - 1]._data;\n if (previousDataLOD[babylonDrawMode]) {\n this._disposeMaterials([previousDataLOD[babylonDrawMode].babylonMaterial]);\n delete previousDataLOD[babylonDrawMode];\n }\n }\n return babylonMaterial;\n });\n this._materialPromiseLODs[indexLOD] = this._materialPromiseLODs[indexLOD] || [];\n if (indexLOD === 0) {\n firstPromise = promise;\n }\n else {\n this._materialIndexLOD = null;\n this._materialPromiseLODs[indexLOD].push(promise);\n }\n }\n this._loader.logClose();\n return firstPromise;\n });\n }\n /**\n * @internal\n */\n _loadUriAsync(context, property, uri) {\n // Defer the loading of uris if loading a node or material LOD.\n if (this._nodeIndexLOD !== null) {\n this._loader.log(`deferred`);\n const previousIndexLOD = this._nodeIndexLOD - 1;\n this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new Deferred();\n return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(() => {\n return this._loader.loadUriAsync(context, property, uri);\n });\n }\n else if (this._materialIndexLOD !== null) {\n this._loader.log(`deferred`);\n const previousIndexLOD = this._materialIndexLOD - 1;\n this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new Deferred();\n return this._materialSignalLODs[previousIndexLOD].promise.then(() => {\n return this._loader.loadUriAsync(context, property, uri);\n });\n }\n return null;\n }\n /**\n * @internal\n */\n loadBufferAsync(context, buffer, byteOffset, byteLength) {\n if (this._loader.parent.useRangeRequests && !buffer.uri) {\n if (!this._loader.bin) {\n throw new Error(`${context}: Uri is missing or the binary glTF is missing its binary chunk`);\n }\n const loadAsync = (bufferLODs, indexLOD) => {\n const start = byteOffset;\n const end = start + byteLength - 1;\n let bufferLOD = bufferLODs[indexLOD];\n if (bufferLOD) {\n bufferLOD.start = Math.min(bufferLOD.start, start);\n bufferLOD.end = Math.max(bufferLOD.end, end);\n }\n else {\n bufferLOD = { start: start, end: end, loaded: new Deferred() };\n bufferLODs[indexLOD] = bufferLOD;\n }\n return bufferLOD.loaded.promise.then((data) => {\n return new Uint8Array(data.buffer, data.byteOffset + byteOffset - bufferLOD.start, byteLength);\n });\n };\n this._loader.log(`deferred`);\n if (this._nodeIndexLOD !== null) {\n return loadAsync(this._nodeBufferLODs, this._nodeIndexLOD);\n }\n else if (this._materialIndexLOD !== null) {\n return loadAsync(this._materialBufferLODs, this._materialIndexLOD);\n }\n else {\n return loadAsync(this._bufferLODs, 0);\n }\n }\n return null;\n }\n _loadBufferLOD(bufferLODs, indexLOD) {\n const bufferLOD = bufferLODs[indexLOD];\n if (bufferLOD) {\n this._loader.log(`Loading buffer range [${bufferLOD.start}-${bufferLOD.end}]`);\n this._loader.bin.readAsync(bufferLOD.start, bufferLOD.end - bufferLOD.start + 1).then((data) => {\n bufferLOD.loaded.resolve(data);\n }, (error) => {\n bufferLOD.loaded.reject(error);\n });\n }\n }\n /**\n * Gets an array of LOD properties from lowest to highest.\n * @param context\n * @param property\n * @param array\n * @param ids\n */\n _getLODs(context, property, array, ids) {\n if (this.maxLODsToLoad <= 0) {\n throw new Error(\"maxLODsToLoad must be greater than zero\");\n }\n const properties = new Array();\n for (let i = ids.length - 1; i >= 0; i--) {\n properties.push(ArrayItem.Get(`${context}/ids/${ids[i]}`, array, ids[i]));\n if (properties.length === this.maxLODsToLoad) {\n return properties;\n }\n }\n properties.push(property);\n return properties;\n }\n _disposeTransformNode(babylonTransformNode) {\n const babylonMaterials = new Array();\n const babylonMaterial = babylonTransformNode.material;\n if (babylonMaterial) {\n babylonMaterials.push(babylonMaterial);\n }\n for (const babylonMesh of babylonTransformNode.getChildMeshes()) {\n if (babylonMesh.material) {\n babylonMaterials.push(babylonMesh.material);\n }\n }\n babylonTransformNode.dispose();\n const babylonMaterialsToDispose = babylonMaterials.filter((babylonMaterial) => this._loader.babylonScene.meshes.every((mesh) => mesh.material != babylonMaterial));\n this._disposeMaterials(babylonMaterialsToDispose);\n }\n _disposeMaterials(babylonMaterials) {\n const babylonTextures = {};\n for (const babylonMaterial of babylonMaterials) {\n for (const babylonTexture of babylonMaterial.getActiveTextures()) {\n babylonTextures[babylonTexture.uniqueId] = babylonTexture;\n }\n babylonMaterial.dispose();\n }\n for (const uniqueId in babylonTextures) {\n for (const babylonMaterial of this._loader.babylonScene.materials) {\n if (babylonMaterial.hasTexture(babylonTextures[uniqueId])) {\n delete babylonTextures[uniqueId];\n }\n }\n }\n for (const uniqueId in babylonTextures) {\n babylonTextures[uniqueId].dispose();\n }\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new MSFT_lod(loader));\n//# sourceMappingURL=MSFT_lod.js.map","import { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"MSFT_minecraftMesh\";\n/** @internal */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class MSFT_minecraftMesh {\n /** @internal */\n constructor(loader) {\n /** @internal */\n this.name = NAME;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /** @internal */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtraAsync(context, material, this.name, (extraContext, extra) => {\n if (extra) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${extraContext}: Material type not supported`);\n }\n const promise = this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial);\n if (babylonMaterial.needAlphaBlending()) {\n babylonMaterial.forceDepthWrite = true;\n babylonMaterial.separateCullingPass = true;\n }\n babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;\n babylonMaterial.twoSidedLighting = true;\n return promise;\n }\n return null;\n });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new MSFT_minecraftMesh(loader));\n//# sourceMappingURL=MSFT_minecraftMesh.js.map","import { PBRMaterial } from \"@babylonjs/core/Materials/PBR/pbrMaterial.js\";\nimport { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"MSFT_sRGBFactors\";\n/** @internal */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class MSFT_sRGBFactors {\n /** @internal */\n constructor(loader) {\n /** @internal */\n this.name = NAME;\n this._loader = loader;\n this.enabled = this._loader.isExtensionUsed(NAME);\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /** @internal */\n loadMaterialPropertiesAsync(context, material, babylonMaterial) {\n return GLTFLoader.LoadExtraAsync(context, material, this.name, (extraContext, extra) => {\n if (extra) {\n if (!(babylonMaterial instanceof PBRMaterial)) {\n throw new Error(`${extraContext}: Material type not supported`);\n }\n const promise = this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial);\n const useExactSrgbConversions = babylonMaterial.getScene().getEngine().useExactSrgbConversions;\n if (!babylonMaterial.albedoTexture) {\n babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor, useExactSrgbConversions);\n }\n if (!babylonMaterial.reflectivityTexture) {\n babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor, useExactSrgbConversions);\n }\n return promise;\n }\n return null;\n });\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new MSFT_sRGBFactors(loader));\n//# sourceMappingURL=MSFT_sRGBFactors.js.map","import { GLTFLoader } from \"../glTFLoader.js\";\nconst NAME = \"ExtrasAsMetadata\";\n/**\n * Store glTF extras (if present) in BJS objects' metadata\n */\nexport class ExtrasAsMetadata {\n _assignExtras(babylonObject, gltfProp) {\n if (gltfProp.extras && Object.keys(gltfProp.extras).length > 0) {\n const metadata = (babylonObject.metadata = babylonObject.metadata || {});\n const gltf = (metadata.gltf = metadata.gltf || {});\n gltf.extras = gltfProp.extras;\n }\n }\n /**\n * @internal\n */\n constructor(loader) {\n /**\n * The name of this extension.\n */\n this.name = NAME;\n /**\n * Defines whether this extension is enabled.\n */\n this.enabled = true;\n this._loader = loader;\n }\n /** @internal */\n dispose() {\n this._loader = null;\n }\n /**\n * @internal\n */\n loadNodeAsync(context, node, assign) {\n return this._loader.loadNodeAsync(context, node, (babylonTransformNode) => {\n this._assignExtras(babylonTransformNode, node);\n assign(babylonTransformNode);\n });\n }\n /**\n * @internal\n */\n loadCameraAsync(context, camera, assign) {\n return this._loader.loadCameraAsync(context, camera, (babylonCamera) => {\n this._assignExtras(babylonCamera, camera);\n assign(babylonCamera);\n });\n }\n /**\n * @internal\n */\n createMaterial(context, material, babylonDrawMode) {\n const babylonMaterial = this._loader.createMaterial(context, material, babylonDrawMode);\n this._assignExtras(babylonMaterial, material);\n return babylonMaterial;\n }\n}\nGLTFLoader.RegisterExtension(NAME, (loader) => new ExtrasAsMetadata(loader));\n//# sourceMappingURL=ExtrasAsMetadata.js.map","import { DataBuffer } from \"./dataBuffer.js\";\n/**\n * Class used to store data that will be store in GPU memory\n */\nexport class Buffer {\n /**\n * Constructor\n * @param engine the engine\n * @param data the data to use for this buffer\n * @param updatable whether the data is updatable\n * @param stride the stride (optional)\n * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)\n * @param instanced whether the buffer is instanced (optional)\n * @param useBytes set to true if the stride in in bytes (optional)\n * @param divisor sets an optional divisor for instances (1 by default)\n */\n constructor(engine, data, updatable, stride = 0, postponeInternalCreation = false, instanced = false, useBytes = false, divisor) {\n this._isAlreadyOwned = false;\n if (engine.getScene) {\n // old versions of VertexBuffer accepted 'mesh' instead of 'engine'\n this._engine = engine.getScene().getEngine();\n }\n else {\n this._engine = engine;\n }\n this._updatable = updatable;\n this._instanced = instanced;\n this._divisor = divisor || 1;\n if (data instanceof DataBuffer) {\n this._data = null;\n this._buffer = data;\n }\n else {\n this._data = data;\n this._buffer = null;\n }\n this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;\n if (!postponeInternalCreation) {\n // by default\n this.create();\n }\n }\n /**\n * Create a new VertexBuffer based on the current buffer\n * @param kind defines the vertex buffer kind (position, normal, etc.)\n * @param offset defines offset in the buffer (0 by default)\n * @param size defines the size in floats of attributes (position is 3 for instance)\n * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)\n * @param instanced defines if the vertex buffer contains indexed data\n * @param useBytes defines if the offset and stride are in bytes *\n * @param divisor sets an optional divisor for instances (1 by default)\n * @returns the new vertex buffer\n */\n createVertexBuffer(kind, offset, size, stride, instanced, useBytes = false, divisor) {\n const byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;\n const byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;\n // a lot of these parameters are ignored as they are overridden by the buffer\n return new VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true, this._divisor || divisor);\n }\n // Properties\n /**\n * Gets a boolean indicating if the Buffer is updatable?\n * @returns true if the buffer is updatable\n */\n isUpdatable() {\n return this._updatable;\n }\n /**\n * Gets current buffer's data\n * @returns a DataArray or null\n */\n getData() {\n return this._data;\n }\n /**\n * Gets underlying native buffer\n * @returns underlying native buffer\n */\n getBuffer() {\n return this._buffer;\n }\n /**\n * Gets the stride in float32 units (i.e. byte stride / 4).\n * May not be an integer if the byte stride is not divisible by 4.\n * @returns the stride in float32 units\n * @deprecated Please use byteStride instead.\n */\n getStrideSize() {\n return this.byteStride / Float32Array.BYTES_PER_ELEMENT;\n }\n // Methods\n /**\n * Store data into the buffer. Creates the buffer if not used already.\n * If the buffer was already used, it will be updated only if it is updatable, otherwise it will do nothing.\n * @param data defines the data to store\n */\n create(data = null) {\n if (!data && this._buffer) {\n return; // nothing to do\n }\n data = data || this._data;\n if (!data) {\n return;\n }\n if (!this._buffer) {\n // create buffer\n if (this._updatable) {\n this._buffer = this._engine.createDynamicVertexBuffer(data);\n this._data = data;\n }\n else {\n this._buffer = this._engine.createVertexBuffer(data);\n }\n }\n else if (this._updatable) {\n // update buffer\n this._engine.updateDynamicVertexBuffer(this._buffer, data);\n this._data = data;\n }\n }\n /** @internal */\n _rebuild() {\n this._buffer = null;\n this.create(this._data);\n }\n /**\n * Update current buffer data\n * @param data defines the data to store\n */\n update(data) {\n this.create(data);\n }\n /**\n * Updates the data directly.\n * @param data the new data\n * @param offset the new offset\n * @param vertexCount the vertex count (optional)\n * @param useBytes set to true if the offset is in bytes\n */\n updateDirectly(data, offset, vertexCount, useBytes = false) {\n if (!this._buffer) {\n return;\n }\n if (this._updatable) {\n // update buffer\n this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, vertexCount ? vertexCount * this.byteStride : undefined);\n if (offset === 0 && vertexCount === undefined) {\n // Keep the data if we easily can\n this._data = data;\n }\n else {\n this._data = null;\n }\n }\n }\n /** @internal */\n _increaseReferences() {\n if (!this._buffer) {\n return;\n }\n if (!this._isAlreadyOwned) {\n this._isAlreadyOwned = true;\n return;\n }\n this._buffer.references++;\n }\n /**\n * Release all resources\n */\n dispose() {\n if (!this._buffer) {\n return;\n }\n if (this._engine._releaseBuffer(this._buffer)) {\n this._buffer = null;\n this._data = null;\n }\n }\n}\n/**\n * Specialized buffer used to store vertex data\n */\nexport class VertexBuffer {\n /**\n * Gets or sets the instance divisor when in instanced mode\n */\n get instanceDivisor() {\n return this._instanceDivisor;\n }\n set instanceDivisor(value) {\n const isInstanced = value != 0;\n this._instanceDivisor = value;\n if (isInstanced !== this._instanced) {\n this._instanced = isInstanced;\n this._computeHashCode();\n }\n }\n /**\n * Constructor\n * @param engine the engine\n * @param data the data to use for this vertex buffer\n * @param kind the vertex buffer kind\n * @param updatable whether the data is updatable\n * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)\n * @param stride the stride (optional)\n * @param instanced whether the buffer is instanced (optional)\n * @param offset the offset of the data (optional)\n * @param size the number of components (optional)\n * @param type the type of the component (optional)\n * @param normalized whether the data contains normalized data (optional)\n * @param useBytes set to true if stride and offset are in bytes (optional)\n * @param divisor defines the instance divisor to use (1 by default)\n * @param takeBufferOwnership defines if the buffer should be released when the vertex buffer is disposed\n */\n constructor(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized = false, useBytes = false, divisor = 1, takeBufferOwnership = false) {\n if (data instanceof Buffer) {\n this._buffer = data;\n this._ownsBuffer = takeBufferOwnership;\n }\n else {\n this._buffer = new Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);\n this._ownsBuffer = true;\n }\n this.uniqueId = VertexBuffer._Counter++;\n this._kind = kind;\n if (type == undefined) {\n const vertexData = this.getData();\n this.type = VertexBuffer.FLOAT;\n if (vertexData instanceof Int8Array) {\n this.type = VertexBuffer.BYTE;\n }\n else if (vertexData instanceof Uint8Array) {\n this.type = VertexBuffer.UNSIGNED_BYTE;\n }\n else if (vertexData instanceof Int16Array) {\n this.type = VertexBuffer.SHORT;\n }\n else if (vertexData instanceof Uint16Array) {\n this.type = VertexBuffer.UNSIGNED_SHORT;\n }\n else if (vertexData instanceof Int32Array) {\n this.type = VertexBuffer.INT;\n }\n else if (vertexData instanceof Uint32Array) {\n this.type = VertexBuffer.UNSIGNED_INT;\n }\n }\n else {\n this.type = type;\n }\n const typeByteLength = VertexBuffer.GetTypeByteLength(this.type);\n if (useBytes) {\n this._size = size || (stride ? stride / typeByteLength : VertexBuffer.DeduceStride(kind));\n this.byteStride = stride || this._buffer.byteStride || this._size * typeByteLength;\n this.byteOffset = offset || 0;\n }\n else {\n this._size = size || stride || VertexBuffer.DeduceStride(kind);\n this.byteStride = stride ? stride * typeByteLength : this._buffer.byteStride || this._size * typeByteLength;\n this.byteOffset = (offset || 0) * typeByteLength;\n }\n this.normalized = normalized;\n this._instanced = instanced !== undefined ? instanced : false;\n this._instanceDivisor = instanced ? divisor : 0;\n this._computeHashCode();\n }\n _computeHashCode() {\n // note: cast to any because the property is declared readonly\n this.hashCode =\n ((this.type - 5120) << 0) +\n ((this.normalized ? 1 : 0) << 3) +\n (this._size << 4) +\n ((this._instanced ? 1 : 0) << 6) +\n /* keep 5 bits free */\n (this.byteStride << 12);\n }\n /** @internal */\n _rebuild() {\n if (!this._buffer) {\n return;\n }\n this._buffer._rebuild();\n }\n /**\n * Returns the kind of the VertexBuffer (string)\n * @returns a string\n */\n getKind() {\n return this._kind;\n }\n // Properties\n /**\n * Gets a boolean indicating if the VertexBuffer is updatable?\n * @returns true if the buffer is updatable\n */\n isUpdatable() {\n return this._buffer.isUpdatable();\n }\n /**\n * Gets current buffer's data\n * @returns a DataArray or null\n */\n getData() {\n return this._buffer.getData();\n }\n /**\n * Gets current buffer's data as a float array. Float data is constructed if the vertex buffer data cannot be returned directly.\n * @param totalVertices number of vertices in the buffer to take into account\n * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it\n * @returns a float array containing vertex data\n */\n getFloatData(totalVertices, forceCopy) {\n const data = this.getData();\n if (!data) {\n return null;\n }\n const tightlyPackedByteStride = this.getSize() * VertexBuffer.GetTypeByteLength(this.type);\n const count = totalVertices * this.getSize();\n if (this.type !== VertexBuffer.FLOAT || this.byteStride !== tightlyPackedByteStride) {\n const copy = new Float32Array(count);\n this.forEach(count, (value, index) => (copy[index] = value));\n return copy;\n }\n if (!(data instanceof Array || data instanceof Float32Array) || this.byteOffset !== 0 || data.length !== count) {\n if (data instanceof Array) {\n const offset = this.byteOffset / 4;\n return data.slice(offset, offset + count);\n }\n else if (data instanceof ArrayBuffer) {\n return new Float32Array(data, this.byteOffset, count);\n }\n else {\n let offset = data.byteOffset + this.byteOffset;\n if (forceCopy) {\n const result = new Float32Array(count);\n const source = new Float32Array(data.buffer, offset, count);\n result.set(source);\n return result;\n }\n // Protect against bad data\n const remainder = offset % 4;\n if (remainder) {\n offset = Math.max(0, offset - remainder);\n }\n return new Float32Array(data.buffer, offset, count);\n }\n }\n if (forceCopy) {\n return data.slice();\n }\n return data;\n }\n /**\n * Gets underlying native buffer\n * @returns underlying native buffer\n */\n getBuffer() {\n return this._buffer.getBuffer();\n }\n /**\n * Gets the stride in float32 units (i.e. byte stride / 4).\n * May not be an integer if the byte stride is not divisible by 4.\n * @returns the stride in float32 units\n * @deprecated Please use byteStride instead.\n */\n getStrideSize() {\n return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);\n }\n /**\n * Returns the offset as a multiple of the type byte length.\n * @returns the offset in bytes\n * @deprecated Please use byteOffset instead.\n */\n getOffset() {\n return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);\n }\n /**\n * Returns the number of components or the byte size per vertex attribute\n * @param sizeInBytes If true, returns the size in bytes or else the size in number of components of the vertex attribute (default: false)\n * @returns the number of components\n */\n getSize(sizeInBytes = false) {\n return sizeInBytes ? this._size * VertexBuffer.GetTypeByteLength(this.type) : this._size;\n }\n /**\n * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced\n * @returns true if this buffer is instanced\n */\n getIsInstanced() {\n return this._instanced;\n }\n /**\n * Returns the instancing divisor, zero for non-instanced (integer).\n * @returns a number\n */\n getInstanceDivisor() {\n return this._instanceDivisor;\n }\n // Methods\n /**\n * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property\n * @param data defines the data to store\n */\n create(data) {\n this._buffer.create(data);\n }\n /**\n * Updates the underlying buffer according to the passed numeric array or Float32Array.\n * This function will create a new buffer if the current one is not updatable\n * @param data defines the data to store\n */\n update(data) {\n this._buffer.update(data);\n }\n /**\n * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.\n * Returns the directly updated WebGLBuffer.\n * @param data the new data\n * @param offset the new offset\n * @param useBytes set to true if the offset is in bytes\n */\n updateDirectly(data, offset, useBytes = false) {\n this._buffer.updateDirectly(data, offset, undefined, useBytes);\n }\n /**\n * Disposes the VertexBuffer and the underlying WebGLBuffer.\n */\n dispose() {\n if (this._ownsBuffer) {\n this._buffer.dispose();\n }\n }\n /**\n * Enumerates each value of this vertex buffer as numbers.\n * @param count the number of values to enumerate\n * @param callback the callback function called for each value\n */\n forEach(count, callback) {\n VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);\n }\n /**\n * Deduces the stride given a kind.\n * @param kind The kind string to deduce\n * @returns The deduced stride\n */\n static DeduceStride(kind) {\n switch (kind) {\n case VertexBuffer.UVKind:\n case VertexBuffer.UV2Kind:\n case VertexBuffer.UV3Kind:\n case VertexBuffer.UV4Kind:\n case VertexBuffer.UV5Kind:\n case VertexBuffer.UV6Kind:\n return 2;\n case VertexBuffer.NormalKind:\n case VertexBuffer.PositionKind:\n return 3;\n case VertexBuffer.ColorKind:\n case VertexBuffer.MatricesIndicesKind:\n case VertexBuffer.MatricesIndicesExtraKind:\n case VertexBuffer.MatricesWeightsKind:\n case VertexBuffer.MatricesWeightsExtraKind:\n case VertexBuffer.TangentKind:\n return 4;\n default:\n throw new Error(\"Invalid kind '\" + kind + \"'\");\n }\n }\n /**\n * Gets the byte length of the given type.\n * @param type the type\n * @returns the number of bytes\n */\n static GetTypeByteLength(type) {\n switch (type) {\n case VertexBuffer.BYTE:\n case VertexBuffer.UNSIGNED_BYTE:\n return 1;\n case VertexBuffer.SHORT:\n case VertexBuffer.UNSIGNED_SHORT:\n return 2;\n case VertexBuffer.INT:\n case VertexBuffer.UNSIGNED_INT:\n case VertexBuffer.FLOAT:\n return 4;\n default:\n throw new Error(`Invalid type '${type}'`);\n }\n }\n /**\n * Enumerates each value of the given parameters as numbers.\n * @param data the data to enumerate\n * @param byteOffset the byte offset of the data\n * @param byteStride the byte stride of the data\n * @param componentCount the number of components per element\n * @param componentType the type of the component\n * @param count the number of values to enumerate\n * @param normalized whether the data is normalized\n * @param callback the callback function called for each value\n */\n static ForEach(data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {\n if (data instanceof Array) {\n let offset = byteOffset / 4;\n const stride = byteStride / 4;\n for (let index = 0; index < count; index += componentCount) {\n for (let componentIndex = 0; componentIndex < componentCount; componentIndex++) {\n callback(data[offset + componentIndex], index + componentIndex);\n }\n offset += stride;\n }\n }\n else {\n const dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);\n const componentByteLength = VertexBuffer.GetTypeByteLength(componentType);\n for (let index = 0; index < count; index += componentCount) {\n let componentByteOffset = byteOffset;\n for (let componentIndex = 0; componentIndex < componentCount; componentIndex++) {\n const value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);\n callback(value, index + componentIndex);\n componentByteOffset += componentByteLength;\n }\n byteOffset += byteStride;\n }\n }\n }\n static _GetFloatValue(dataView, type, byteOffset, normalized) {\n switch (type) {\n case VertexBuffer.BYTE: {\n let value = dataView.getInt8(byteOffset);\n if (normalized) {\n value = Math.max(value / 127, -1);\n }\n return value;\n }\n case VertexBuffer.UNSIGNED_BYTE: {\n let value = dataView.getUint8(byteOffset);\n if (normalized) {\n value = value / 255;\n }\n return value;\n }\n case VertexBuffer.SHORT: {\n let value = dataView.getInt16(byteOffset, true);\n if (normalized) {\n value = Math.max(value / 32767, -1);\n }\n return value;\n }\n case VertexBuffer.UNSIGNED_SHORT: {\n let value = dataView.getUint16(byteOffset, true);\n if (normalized) {\n value = value / 65535;\n }\n return value;\n }\n case VertexBuffer.INT: {\n return dataView.getInt32(byteOffset, true);\n }\n case VertexBuffer.UNSIGNED_INT: {\n return dataView.getUint32(byteOffset, true);\n }\n case VertexBuffer.FLOAT: {\n return dataView.getFloat32(byteOffset, true);\n }\n default: {\n throw new Error(`Invalid component type ${type}`);\n }\n }\n }\n}\nVertexBuffer._Counter = 0;\n/**\n * The byte type.\n */\nVertexBuffer.BYTE = 5120;\n/**\n * The unsigned byte type.\n */\nVertexBuffer.UNSIGNED_BYTE = 5121;\n/**\n * The short type.\n */\nVertexBuffer.SHORT = 5122;\n/**\n * The unsigned short type.\n */\nVertexBuffer.UNSIGNED_SHORT = 5123;\n/**\n * The integer type.\n */\nVertexBuffer.INT = 5124;\n/**\n * The unsigned integer type.\n */\nVertexBuffer.UNSIGNED_INT = 5125;\n/**\n * The float type.\n */\nVertexBuffer.FLOAT = 5126;\n// Enums\n/**\n * Positions\n */\nVertexBuffer.PositionKind = \"position\";\n/**\n * Normals\n */\nVertexBuffer.NormalKind = \"normal\";\n/**\n * Tangents\n */\nVertexBuffer.TangentKind = \"tangent\";\n/**\n * Texture coordinates\n */\nVertexBuffer.UVKind = \"uv\";\n/**\n * Texture coordinates 2\n */\nVertexBuffer.UV2Kind = \"uv2\";\n/**\n * Texture coordinates 3\n */\nVertexBuffer.UV3Kind = \"uv3\";\n/**\n * Texture coordinates 4\n */\nVertexBuffer.UV4Kind = \"uv4\";\n/**\n * Texture coordinates 5\n */\nVertexBuffer.UV5Kind = \"uv5\";\n/**\n * Texture coordinates 6\n */\nVertexBuffer.UV6Kind = \"uv6\";\n/**\n * Colors\n */\nVertexBuffer.ColorKind = \"color\";\n/**\n * Instance Colors\n */\nVertexBuffer.ColorInstanceKind = \"instanceColor\";\n/**\n * Matrix indices (for bones)\n */\nVertexBuffer.MatricesIndicesKind = \"matricesIndices\";\n/**\n * Matrix weights (for bones)\n */\nVertexBuffer.MatricesWeightsKind = \"matricesWeights\";\n/**\n * Additional matrix indices (for bones)\n */\nVertexBuffer.MatricesIndicesExtraKind = \"matricesIndicesExtra\";\n/**\n * Additional matrix weights (for bones)\n */\nVertexBuffer.MatricesWeightsExtraKind = \"matricesWeightsExtra\";\n//# sourceMappingURL=buffer.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize, SerializationHelper, serializeAsVector3 } from \"../Misc/decorators.js\";\nimport { SmartArray } from \"../Misc/smartArray.js\";\nimport { Tools } from \"../Misc/tools.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Matrix, Vector3, Quaternion } from \"../Maths/math.vector.js\";\nimport { Node } from \"../node.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { GetClass } from \"../Misc/typeStore.js\";\nimport { _WarnImport } from \"../Misc/devTools.js\";\nimport { Viewport } from \"../Maths/math.viewport.js\";\nimport { Frustum } from \"../Maths/math.frustum.js\";\n\n/**\n * This is the base class of all the camera used in the application.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras\n */\nexport class Camera extends Node {\n /**\n * Define the current local position of the camera in the scene\n */\n get position() {\n return this._position;\n }\n set position(newPosition) {\n this._position = newPosition;\n }\n /**\n * The vector the camera should consider as up.\n * (default is Vector3(0, 1, 0) aka Vector3.Up())\n */\n set upVector(vec) {\n this._upVector = vec;\n }\n get upVector() {\n return this._upVector;\n }\n /**\n * The screen area in scene units squared\n */\n get screenArea() {\n var _a, _b, _c, _d;\n let x = 0;\n let y = 0;\n if (this.mode === Camera.PERSPECTIVE_CAMERA) {\n if (this.fovMode === Camera.FOVMODE_VERTICAL_FIXED) {\n y = this.minZ * 2 * Math.tan(this.fov / 2);\n x = this.getEngine().getAspectRatio(this) * y;\n }\n else {\n x = this.minZ * 2 * Math.tan(this.fov / 2);\n y = x / this.getEngine().getAspectRatio(this);\n }\n }\n else {\n const halfWidth = this.getEngine().getRenderWidth() / 2.0;\n const halfHeight = this.getEngine().getRenderHeight() / 2.0;\n x = ((_a = this.orthoRight) !== null && _a !== void 0 ? _a : halfWidth) - ((_b = this.orthoLeft) !== null && _b !== void 0 ? _b : -halfWidth);\n y = ((_c = this.orthoTop) !== null && _c !== void 0 ? _c : halfHeight) - ((_d = this.orthoBottom) !== null && _d !== void 0 ? _d : -halfHeight);\n }\n return x * y;\n }\n set orthoLeft(value) {\n this._orthoLeft = value;\n for (const rigCamera of this._rigCameras) {\n rigCamera.orthoLeft = value;\n }\n }\n get orthoLeft() {\n return this._orthoLeft;\n }\n set orthoRight(value) {\n this._orthoRight = value;\n for (const rigCamera of this._rigCameras) {\n rigCamera.orthoRight = value;\n }\n }\n get orthoRight() {\n return this._orthoRight;\n }\n set orthoBottom(value) {\n this._orthoBottom = value;\n for (const rigCamera of this._rigCameras) {\n rigCamera.orthoBottom = value;\n }\n }\n get orthoBottom() {\n return this._orthoBottom;\n }\n set orthoTop(value) {\n this._orthoTop = value;\n for (const rigCamera of this._rigCameras) {\n rigCamera.orthoTop = value;\n }\n }\n get orthoTop() {\n return this._orthoTop;\n }\n set mode(mode) {\n this._mode = mode;\n // Pass the mode down to the rig cameras\n for (const rigCamera of this._rigCameras) {\n rigCamera.mode = mode;\n }\n }\n get mode() {\n return this._mode;\n }\n /**\n * Instantiates a new camera object.\n * This should not be used directly but through the inherited cameras: ArcRotate, Free...\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras\n * @param name Defines the name of the camera in the scene\n * @param position Defines the position of the camera\n * @param scene Defines the scene the camera belongs too\n * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene\n */\n constructor(name, position, scene, setActiveOnSceneIfNoneActive = true) {\n super(name, scene);\n /** @internal */\n this._position = Vector3.Zero();\n this._upVector = Vector3.Up();\n /**\n * Define the current limit on the left side for an orthographic camera\n * In scene unit\n */\n this._orthoLeft = null;\n /**\n * Define the current limit on the right side for an orthographic camera\n * In scene unit\n */\n this._orthoRight = null;\n /**\n * Define the current limit on the bottom side for an orthographic camera\n * In scene unit\n */\n this._orthoBottom = null;\n /**\n * Define the current limit on the top side for an orthographic camera\n * In scene unit\n */\n this._orthoTop = null;\n /**\n * Field Of View is set in Radians. (default is 0.8)\n */\n this.fov = 0.8;\n /**\n * Projection plane tilt around the X axis (horizontal), set in Radians. (default is 0)\n * Can be used to make vertical lines in world space actually vertical on the screen.\n * See https://forum.babylonjs.com/t/add-vertical-shift-to-3ds-max-exporter-babylon-cameras/17480\n */\n this.projectionPlaneTilt = 0;\n /**\n * Define the minimum distance the camera can see from.\n * This is important to note that the depth buffer are not infinite and the closer it starts\n * the more your scene might encounter depth fighting issue.\n */\n this.minZ = 1;\n /**\n * Define the maximum distance the camera can see to.\n * This is important to note that the depth buffer are not infinite and the further it end\n * the more your scene might encounter depth fighting issue.\n */\n this.maxZ = 10000.0;\n /**\n * Define the default inertia of the camera.\n * This helps giving a smooth feeling to the camera movement.\n */\n this.inertia = 0.9;\n /**\n * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.ORTHOGRAPHIC_CAMERA)\n */\n this._mode = Camera.PERSPECTIVE_CAMERA;\n /**\n * Define whether the camera is intermediate.\n * This is useful to not present the output directly to the screen in case of rig without post process for instance\n */\n this.isIntermediate = false;\n /**\n * Define the viewport of the camera.\n * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.\n */\n this.viewport = new Viewport(0, 0, 1.0, 1.0);\n /**\n * Restricts the camera to viewing objects with the same layerMask.\n * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0\n */\n this.layerMask = 0x0fffffff;\n /**\n * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)\n */\n this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;\n /**\n * Rig mode of the camera.\n * This is useful to create the camera with two \"eyes\" instead of one to create VR or stereoscopic scenes.\n * This is normally controlled byt the camera themselves as internal use.\n */\n this.cameraRigMode = Camera.RIG_MODE_NONE;\n /**\n * Defines the list of custom render target which are rendered to and then used as the input to this camera's render. Eg. display another camera view on a TV in the main scene\n * This is pretty helpful if you wish to make a camera render to a texture you could reuse somewhere\n * else in the scene. (Eg. security camera)\n *\n * To change the final output target of the camera, camera.outputRenderTarget should be used instead (eg. webXR renders to a render target corresponding to an HMD)\n */\n this.customRenderTargets = new Array();\n /**\n * When set, the camera will render to this render target instead of the default canvas\n *\n * If the desire is to use the output of a camera as a texture in the scene consider using camera.customRenderTargets instead\n */\n this.outputRenderTarget = null;\n /**\n * Observable triggered when the camera view matrix has changed.\n */\n this.onViewMatrixChangedObservable = new Observable();\n /**\n * Observable triggered when the camera Projection matrix has changed.\n */\n this.onProjectionMatrixChangedObservable = new Observable();\n /**\n * Observable triggered when the inputs have been processed.\n */\n this.onAfterCheckInputsObservable = new Observable();\n /**\n * Observable triggered when reset has been called and applied to the camera.\n */\n this.onRestoreStateObservable = new Observable();\n /**\n * Is this camera a part of a rig system?\n */\n this.isRigCamera = false;\n /** @internal */\n this._rigCameras = new Array();\n this._webvrViewMatrix = Matrix.Identity();\n /** @internal */\n this._skipRendering = false;\n /** @internal */\n this._projectionMatrix = new Matrix();\n /** @internal */\n this._postProcesses = new Array();\n /** @internal */\n this._activeMeshes = new SmartArray(256);\n this._globalPosition = Vector3.Zero();\n /** @internal */\n this._computedViewMatrix = Matrix.Identity();\n this._doNotComputeProjectionMatrix = false;\n this._transformMatrix = Matrix.Zero();\n this._refreshFrustumPlanes = true;\n this._absoluteRotation = Quaternion.Identity();\n /** @internal */\n this._isCamera = true;\n /** @internal */\n this._isLeftCamera = false;\n /** @internal */\n this._isRightCamera = false;\n this.getScene().addCamera(this);\n if (setActiveOnSceneIfNoneActive && !this.getScene().activeCamera) {\n this.getScene().activeCamera = this;\n }\n this.position = position;\n this.renderPassId = this.getScene().getEngine().createRenderPassId(`Camera ${name}`);\n }\n /**\n * Store current camera state (fov, position, etc..)\n * @returns the camera\n */\n storeState() {\n this._stateStored = true;\n this._storedFov = this.fov;\n return this;\n }\n /**\n * Restores the camera state values if it has been stored. You must call storeState() first\n */\n _restoreStateValues() {\n if (!this._stateStored) {\n return false;\n }\n this.fov = this._storedFov;\n return true;\n }\n /**\n * Restored camera state. You must call storeState() first.\n * @returns true if restored and false otherwise\n */\n restoreState() {\n if (this._restoreStateValues()) {\n this.onRestoreStateObservable.notifyObservers(this);\n return true;\n }\n return false;\n }\n /**\n * Gets the class name of the camera.\n * @returns the class name\n */\n getClassName() {\n return \"Camera\";\n }\n /**\n * Gets a string representation of the camera useful for debug purpose.\n * @param fullDetails Defines that a more verbose level of logging is required\n * @returns the string representation\n */\n toString(fullDetails) {\n let ret = \"Name: \" + this.name;\n ret += \", type: \" + this.getClassName();\n if (this.animations) {\n for (let i = 0; i < this.animations.length; i++) {\n ret += \", animation[0]: \" + this.animations[i].toString(fullDetails);\n }\n }\n return ret;\n }\n /**\n * Automatically tilts the projection plane, using `projectionPlaneTilt`, to correct the perspective effect on vertical lines.\n */\n applyVerticalCorrection() {\n const rot = this.absoluteRotation.toEulerAngles();\n this.projectionPlaneTilt = this._scene.useRightHandedSystem ? -rot.x : rot.x;\n }\n /**\n * Gets the current world space position of the camera.\n */\n get globalPosition() {\n return this._globalPosition;\n }\n /**\n * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)\n * @returns the active meshe list\n */\n getActiveMeshes() {\n return this._activeMeshes;\n }\n /**\n * Check whether a mesh is part of the current active mesh list of the camera\n * @param mesh Defines the mesh to check\n * @returns true if active, false otherwise\n */\n isActiveMesh(mesh) {\n return this._activeMeshes.indexOf(mesh) !== -1;\n }\n /**\n * Is this camera ready to be used/rendered\n * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)\n * @returns true if the camera is ready\n */\n isReady(completeCheck = false) {\n if (completeCheck) {\n for (const pp of this._postProcesses) {\n if (pp && !pp.isReady()) {\n return false;\n }\n }\n }\n return super.isReady(completeCheck);\n }\n /** @internal */\n _initCache() {\n super._initCache();\n this._cache.position = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._cache.upVector = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n this._cache.mode = undefined;\n this._cache.minZ = undefined;\n this._cache.maxZ = undefined;\n this._cache.fov = undefined;\n this._cache.fovMode = undefined;\n this._cache.aspectRatio = undefined;\n this._cache.orthoLeft = undefined;\n this._cache.orthoRight = undefined;\n this._cache.orthoBottom = undefined;\n this._cache.orthoTop = undefined;\n this._cache.renderWidth = undefined;\n this._cache.renderHeight = undefined;\n }\n /**\n * @internal\n */\n _updateCache(ignoreParentClass) {\n if (!ignoreParentClass) {\n super._updateCache();\n }\n this._cache.position.copyFrom(this.position);\n this._cache.upVector.copyFrom(this.upVector);\n }\n /** @internal */\n _isSynchronized() {\n return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();\n }\n /** @internal */\n _isSynchronizedViewMatrix() {\n if (!super._isSynchronized()) {\n return false;\n }\n return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();\n }\n /** @internal */\n _isSynchronizedProjectionMatrix() {\n let check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;\n if (!check) {\n return false;\n }\n const engine = this.getEngine();\n if (this.mode === Camera.PERSPECTIVE_CAMERA) {\n check =\n this._cache.fov === this.fov &&\n this._cache.fovMode === this.fovMode &&\n this._cache.aspectRatio === engine.getAspectRatio(this) &&\n this._cache.projectionPlaneTilt === this.projectionPlaneTilt;\n }\n else {\n check =\n this._cache.orthoLeft === this.orthoLeft &&\n this._cache.orthoRight === this.orthoRight &&\n this._cache.orthoBottom === this.orthoBottom &&\n this._cache.orthoTop === this.orthoTop &&\n this._cache.renderWidth === engine.getRenderWidth() &&\n this._cache.renderHeight === engine.getRenderHeight();\n }\n return check;\n }\n /**\n * Attach the input controls to a specific dom element to get the input from.\n * This function is here because typescript removes the typing of the last function.\n * @param _ignored defines an ignored parameter kept for backward compatibility.\n * @param _noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n */\n attachControl(_ignored, _noPreventDefault) { }\n /**\n * Detach the current controls from the specified dom element.\n * This function is here because typescript removes the typing of the last function.\n * @param _ignored defines an ignored parameter kept for backward compatibility.\n */\n detachControl(_ignored) { }\n /**\n * Update the camera state according to the different inputs gathered during the frame.\n */\n update() {\n this._checkInputs();\n if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {\n this._updateRigCameras();\n }\n // Attempt to update the camera's view and projection matrices.\n // This call is being made because these matrices are no longer being updated\n // as a part of the picking ray process (in addition to scene.render).\n this.getViewMatrix();\n this.getProjectionMatrix();\n }\n /** @internal */\n _checkInputs() {\n this.onAfterCheckInputsObservable.notifyObservers(this);\n }\n /** @internal */\n get rigCameras() {\n return this._rigCameras;\n }\n /**\n * Gets the post process used by the rig cameras\n */\n get rigPostProcess() {\n return this._rigPostProcess;\n }\n /**\n * Internal, gets the first post process.\n * @returns the first post process to be run on this camera.\n */\n _getFirstPostProcess() {\n for (let ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {\n if (this._postProcesses[ppIndex] !== null) {\n return this._postProcesses[ppIndex];\n }\n }\n return null;\n }\n _cascadePostProcessesToRigCams() {\n // invalidate framebuffer\n const firstPostProcess = this._getFirstPostProcess();\n if (firstPostProcess) {\n firstPostProcess.markTextureDirty();\n }\n // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera\n for (let i = 0, len = this._rigCameras.length; i < len; i++) {\n const cam = this._rigCameras[i];\n const rigPostProcess = cam._rigPostProcess;\n // for VR rig, there does not have to be a post process\n if (rigPostProcess) {\n const isPass = rigPostProcess.getEffectName() === \"pass\";\n if (isPass) {\n // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses\n cam.isIntermediate = this._postProcesses.length === 0;\n }\n cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);\n rigPostProcess.markTextureDirty();\n }\n else {\n cam._postProcesses = this._postProcesses.slice(0);\n }\n }\n }\n /**\n * Attach a post process to the camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses#attach-postprocess\n * @param postProcess The post process to attach to the camera\n * @param insertAt The position of the post process in case several of them are in use in the scene\n * @returns the position the post process has been inserted at\n */\n attachPostProcess(postProcess, insertAt = null) {\n if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {\n Logger.Error(\"You're trying to reuse a post process not defined as reusable.\");\n return 0;\n }\n if (insertAt == null || insertAt < 0) {\n this._postProcesses.push(postProcess);\n }\n else if (this._postProcesses[insertAt] === null) {\n this._postProcesses[insertAt] = postProcess;\n }\n else {\n this._postProcesses.splice(insertAt, 0, postProcess);\n }\n this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated\n // Update prePass\n if (this._scene.prePassRenderer) {\n this._scene.prePassRenderer.markAsDirty();\n }\n return this._postProcesses.indexOf(postProcess);\n }\n /**\n * Detach a post process to the camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses#attach-postprocess\n * @param postProcess The post process to detach from the camera\n */\n detachPostProcess(postProcess) {\n const idx = this._postProcesses.indexOf(postProcess);\n if (idx !== -1) {\n this._postProcesses[idx] = null;\n }\n // Update prePass\n if (this._scene.prePassRenderer) {\n this._scene.prePassRenderer.markAsDirty();\n }\n this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated\n }\n /**\n * Gets the current world matrix of the camera\n */\n getWorldMatrix() {\n if (this._isSynchronizedViewMatrix()) {\n return this._worldMatrix;\n }\n // Getting the the view matrix will also compute the world matrix.\n this.getViewMatrix();\n return this._worldMatrix;\n }\n /** @internal */\n _getViewMatrix() {\n return Matrix.Identity();\n }\n /**\n * Gets the current view matrix of the camera.\n * @param force forces the camera to recompute the matrix without looking at the cached state\n * @returns the view matrix\n */\n getViewMatrix(force) {\n if (!force && this._isSynchronizedViewMatrix()) {\n return this._computedViewMatrix;\n }\n this.updateCache();\n this._computedViewMatrix = this._getViewMatrix();\n this._currentRenderId = this.getScene().getRenderId();\n this._childUpdateId++;\n this._refreshFrustumPlanes = true;\n if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {\n this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);\n }\n // Notify parent camera if rig camera is changed\n if (this.parent && this.parent.onViewMatrixChangedObservable) {\n this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent);\n }\n this.onViewMatrixChangedObservable.notifyObservers(this);\n this._computedViewMatrix.invertToRef(this._worldMatrix);\n return this._computedViewMatrix;\n }\n /**\n * Freeze the projection matrix.\n * It will prevent the cache check of the camera projection compute and can speed up perf\n * if no parameter of the camera are meant to change\n * @param projection Defines manually a projection if necessary\n */\n freezeProjectionMatrix(projection) {\n this._doNotComputeProjectionMatrix = true;\n if (projection !== undefined) {\n this._projectionMatrix = projection;\n }\n }\n /**\n * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.\n */\n unfreezeProjectionMatrix() {\n this._doNotComputeProjectionMatrix = false;\n }\n /**\n * Gets the current projection matrix of the camera.\n * @param force forces the camera to recompute the matrix without looking at the cached state\n * @returns the projection matrix\n */\n getProjectionMatrix(force) {\n var _a, _b, _c, _d, _e, _f, _g, _h;\n if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {\n return this._projectionMatrix;\n }\n // Cache\n this._cache.mode = this.mode;\n this._cache.minZ = this.minZ;\n this._cache.maxZ = this.maxZ;\n // Matrix\n this._refreshFrustumPlanes = true;\n const engine = this.getEngine();\n const scene = this.getScene();\n const reverseDepth = engine.useReverseDepthBuffer;\n if (this.mode === Camera.PERSPECTIVE_CAMERA) {\n this._cache.fov = this.fov;\n this._cache.fovMode = this.fovMode;\n this._cache.aspectRatio = engine.getAspectRatio(this);\n this._cache.projectionPlaneTilt = this.projectionPlaneTilt;\n if (this.minZ <= 0) {\n this.minZ = 0.1;\n }\n let getProjectionMatrix;\n if (scene.useRightHandedSystem) {\n getProjectionMatrix = Matrix.PerspectiveFovRHToRef;\n }\n else {\n getProjectionMatrix = Matrix.PerspectiveFovLHToRef;\n }\n getProjectionMatrix(this.fov, engine.getAspectRatio(this), reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED, engine.isNDCHalfZRange, this.projectionPlaneTilt, reverseDepth);\n }\n else {\n const halfWidth = engine.getRenderWidth() / 2.0;\n const halfHeight = engine.getRenderHeight() / 2.0;\n if (scene.useRightHandedSystem) {\n Matrix.OrthoOffCenterRHToRef((_a = this.orthoLeft) !== null && _a !== void 0 ? _a : -halfWidth, (_b = this.orthoRight) !== null && _b !== void 0 ? _b : halfWidth, (_c = this.orthoBottom) !== null && _c !== void 0 ? _c : -halfHeight, (_d = this.orthoTop) !== null && _d !== void 0 ? _d : halfHeight, reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this._projectionMatrix, engine.isNDCHalfZRange);\n }\n else {\n Matrix.OrthoOffCenterLHToRef((_e = this.orthoLeft) !== null && _e !== void 0 ? _e : -halfWidth, (_f = this.orthoRight) !== null && _f !== void 0 ? _f : halfWidth, (_g = this.orthoBottom) !== null && _g !== void 0 ? _g : -halfHeight, (_h = this.orthoTop) !== null && _h !== void 0 ? _h : halfHeight, reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this._projectionMatrix, engine.isNDCHalfZRange);\n }\n this._cache.orthoLeft = this.orthoLeft;\n this._cache.orthoRight = this.orthoRight;\n this._cache.orthoBottom = this.orthoBottom;\n this._cache.orthoTop = this.orthoTop;\n this._cache.renderWidth = engine.getRenderWidth();\n this._cache.renderHeight = engine.getRenderHeight();\n }\n this.onProjectionMatrixChangedObservable.notifyObservers(this);\n return this._projectionMatrix;\n }\n /**\n * Gets the transformation matrix (ie. the multiplication of view by projection matrices)\n * @returns a Matrix\n */\n getTransformationMatrix() {\n this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);\n return this._transformMatrix;\n }\n _updateFrustumPlanes() {\n if (!this._refreshFrustumPlanes) {\n return;\n }\n this.getTransformationMatrix();\n if (!this._frustumPlanes) {\n this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix);\n }\n else {\n Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);\n }\n this._refreshFrustumPlanes = false;\n }\n /**\n * Checks if a cullable object (mesh...) is in the camera frustum\n * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check\n * @param target The object to check\n * @param checkRigCameras If the rig cameras should be checked (eg. with webVR camera both eyes should be checked) (Default: false)\n * @returns true if the object is in frustum otherwise false\n */\n isInFrustum(target, checkRigCameras = false) {\n this._updateFrustumPlanes();\n if (checkRigCameras && this.rigCameras.length > 0) {\n let result = false;\n this.rigCameras.forEach((cam) => {\n cam._updateFrustumPlanes();\n result = result || target.isInFrustum(cam._frustumPlanes);\n });\n return result;\n }\n else {\n return target.isInFrustum(this._frustumPlanes);\n }\n }\n /**\n * Checks if a cullable object (mesh...) is in the camera frustum\n * Unlike isInFrustum this checks the full bounding box\n * @param target The object to check\n * @returns true if the object is in frustum otherwise false\n */\n isCompletelyInFrustum(target) {\n this._updateFrustumPlanes();\n return target.isCompletelyInFrustum(this._frustumPlanes);\n }\n /**\n * Gets a ray in the forward direction from the camera.\n * @param length Defines the length of the ray to create\n * @param transform Defines the transform to apply to the ray, by default the world matrix is used to create a workd space ray\n * @param origin Defines the start point of the ray which defaults to the camera position\n * @returns the forward ray\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getForwardRay(length = 100, transform, origin) {\n throw _WarnImport(\"Ray\");\n }\n /**\n * Gets a ray in the forward direction from the camera.\n * @param refRay the ray to (re)use when setting the values\n * @param length Defines the length of the ray to create\n * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray\n * @param origin Defines the start point of the ray which defaults to the camera position\n * @returns the forward ray\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getForwardRayToRef(refRay, length = 100, transform, origin) {\n throw _WarnImport(\"Ray\");\n }\n /**\n * Releases resources associated with this node.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n dispose(doNotRecurse, disposeMaterialAndTextures = false) {\n // Observables\n this.onViewMatrixChangedObservable.clear();\n this.onProjectionMatrixChangedObservable.clear();\n this.onAfterCheckInputsObservable.clear();\n this.onRestoreStateObservable.clear();\n // Inputs\n if (this.inputs) {\n this.inputs.clear();\n }\n // Animations\n this.getScene().stopAnimation(this);\n // Remove from scene\n this.getScene().removeCamera(this);\n while (this._rigCameras.length > 0) {\n const camera = this._rigCameras.pop();\n if (camera) {\n camera.dispose();\n }\n }\n if (this._parentContainer) {\n const index = this._parentContainer.cameras.indexOf(this);\n if (index > -1) {\n this._parentContainer.cameras.splice(index, 1);\n }\n this._parentContainer = null;\n }\n // Postprocesses\n if (this._rigPostProcess) {\n this._rigPostProcess.dispose(this);\n this._rigPostProcess = null;\n this._postProcesses.length = 0;\n }\n else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {\n this._rigPostProcess = null;\n this._postProcesses.length = 0;\n }\n else {\n let i = this._postProcesses.length;\n while (--i >= 0) {\n const postProcess = this._postProcesses[i];\n if (postProcess) {\n postProcess.dispose(this);\n }\n }\n }\n // Render targets\n let i = this.customRenderTargets.length;\n while (--i >= 0) {\n this.customRenderTargets[i].dispose();\n }\n this.customRenderTargets.length = 0;\n // Active Meshes\n this._activeMeshes.dispose();\n this.getScene().getEngine().releaseRenderPassId(this.renderPassId);\n super.dispose(doNotRecurse, disposeMaterialAndTextures);\n }\n /**\n * Gets the left camera of a rig setup in case of Rigged Camera\n */\n get isLeftCamera() {\n return this._isLeftCamera;\n }\n /**\n * Gets the right camera of a rig setup in case of Rigged Camera\n */\n get isRightCamera() {\n return this._isRightCamera;\n }\n /**\n * Gets the left camera of a rig setup in case of Rigged Camera\n */\n get leftCamera() {\n if (this._rigCameras.length < 1) {\n return null;\n }\n return this._rigCameras[0];\n }\n /**\n * Gets the right camera of a rig setup in case of Rigged Camera\n */\n get rightCamera() {\n if (this._rigCameras.length < 2) {\n return null;\n }\n return this._rigCameras[1];\n }\n /**\n * Gets the left camera target of a rig setup in case of Rigged Camera\n * @returns the target position\n */\n getLeftTarget() {\n if (this._rigCameras.length < 1) {\n return null;\n }\n return this._rigCameras[0].getTarget();\n }\n /**\n * Gets the right camera target of a rig setup in case of Rigged Camera\n * @returns the target position\n */\n getRightTarget() {\n if (this._rigCameras.length < 2) {\n return null;\n }\n return this._rigCameras[1].getTarget();\n }\n /**\n * @internal\n */\n setCameraRigMode(mode, rigParams) {\n if (this.cameraRigMode === mode) {\n return;\n }\n while (this._rigCameras.length > 0) {\n const camera = this._rigCameras.pop();\n if (camera) {\n camera.dispose();\n }\n }\n this.cameraRigMode = mode;\n this._cameraRigParams = {};\n //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,\n //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced\n this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;\n this._cameraRigParams.stereoHalfAngle = Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);\n // create the rig cameras, unless none\n if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {\n const leftCamera = this.createRigCamera(this.name + \"_L\", 0);\n if (leftCamera) {\n leftCamera._isLeftCamera = true;\n }\n const rightCamera = this.createRigCamera(this.name + \"_R\", 1);\n if (rightCamera) {\n rightCamera._isRightCamera = true;\n }\n if (leftCamera && rightCamera) {\n this._rigCameras.push(leftCamera);\n this._rigCameras.push(rightCamera);\n }\n }\n this._setRigMode(rigParams);\n this._cascadePostProcessesToRigCams();\n this.update();\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _setRigMode(rigParams) {\n // no-op\n }\n /** @internal */\n _getVRProjectionMatrix() {\n Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix, true, this.getEngine().isNDCHalfZRange);\n this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);\n return this._projectionMatrix;\n }\n _updateCameraRotationMatrix() {\n //Here for WebVR\n }\n _updateWebVRCameraRotationMatrix() {\n //Here for WebVR\n }\n /**\n * This function MUST be overwritten by the different WebVR cameras available.\n * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.\n * @internal\n */\n _getWebVRProjectionMatrix() {\n return Matrix.Identity();\n }\n /**\n * This function MUST be overwritten by the different WebVR cameras available.\n * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.\n * @internal\n */\n _getWebVRViewMatrix() {\n return Matrix.Identity();\n }\n /**\n * @internal\n */\n setCameraRigParameter(name, value) {\n if (!this._cameraRigParams) {\n this._cameraRigParams = {};\n }\n this._cameraRigParams[name] = value;\n //provisionnally:\n if (name === \"interaxialDistance\") {\n this._cameraRigParams.stereoHalfAngle = Tools.ToRadians(value / 0.0637);\n }\n }\n /**\n * needs to be overridden by children so sub has required properties to be copied\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n createRigCamera(name, cameraIndex) {\n return null;\n }\n /**\n * May need to be overridden by children\n * @internal\n */\n _updateRigCameras() {\n for (let i = 0; i < this._rigCameras.length; i++) {\n this._rigCameras[i].minZ = this.minZ;\n this._rigCameras[i].maxZ = this.maxZ;\n this._rigCameras[i].fov = this.fov;\n this._rigCameras[i].upVector.copyFrom(this.upVector);\n }\n // only update viewport when ANAGLYPH\n if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {\n this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;\n }\n }\n /** @internal */\n _setupInputs() { }\n /**\n * Serialiaze the camera setup to a json representation\n * @returns the JSON representation\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this);\n serializationObject.uniqueId = this.uniqueId;\n // Type\n serializationObject.type = this.getClassName();\n // Parent\n if (this.parent) {\n this.parent._serializeAsParent(serializationObject);\n }\n if (this.inputs) {\n this.inputs.serialize(serializationObject);\n }\n // Animations\n SerializationHelper.AppendSerializedAnimations(this, serializationObject);\n serializationObject.ranges = this.serializeAnimationRanges();\n serializationObject.isEnabled = this.isEnabled();\n return serializationObject;\n }\n /**\n * Clones the current camera.\n * @param name The cloned camera name\n * @param newParent The cloned camera's new parent (none by default)\n * @returns the cloned camera\n */\n clone(name, newParent = null) {\n const camera = SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);\n camera.name = name;\n camera.parent = newParent;\n this.onClonedObservable.notifyObservers(camera);\n return camera;\n }\n /**\n * Gets the direction of the camera relative to a given local axis.\n * @param localAxis Defines the reference axis to provide a relative direction.\n * @returns the direction\n */\n getDirection(localAxis) {\n const result = Vector3.Zero();\n this.getDirectionToRef(localAxis, result);\n return result;\n }\n /**\n * Returns the current camera absolute rotation\n */\n get absoluteRotation() {\n this.getWorldMatrix().decompose(undefined, this._absoluteRotation);\n return this._absoluteRotation;\n }\n /**\n * Gets the direction of the camera relative to a given local axis into a passed vector.\n * @param localAxis Defines the reference axis to provide a relative direction.\n * @param result Defines the vector to store the result in\n */\n getDirectionToRef(localAxis, result) {\n Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);\n }\n /**\n * Gets a camera constructor for a given camera type\n * @param type The type of the camera to construct (should be equal to one of the camera class name)\n * @param name The name of the camera the result will be able to instantiate\n * @param scene The scene the result will construct the camera in\n * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes\n * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side\n * @returns a factory method to construct the camera\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static GetConstructorFromName(type, name, scene, interaxial_distance = 0, isStereoscopicSideBySide = true) {\n const constructorFunc = Node.Construct(type, name, scene, {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n interaxial_distance: interaxial_distance,\n isStereoscopicSideBySide: isStereoscopicSideBySide,\n });\n if (constructorFunc) {\n return constructorFunc;\n }\n // Default to universal camera\n return () => Camera._CreateDefaultParsedCamera(name, scene);\n }\n /**\n * Compute the world matrix of the camera.\n * @returns the camera world matrix\n */\n computeWorldMatrix() {\n return this.getWorldMatrix();\n }\n /**\n * Parse a JSON and creates the camera from the parsed information\n * @param parsedCamera The JSON to parse\n * @param scene The scene to instantiate the camera in\n * @returns the newly constructed camera\n */\n static Parse(parsedCamera, scene) {\n const type = parsedCamera.type;\n const construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);\n const camera = SerializationHelper.Parse(construct, parsedCamera, scene);\n // Parent\n if (parsedCamera.parentId !== undefined) {\n camera._waitingParentId = parsedCamera.parentId;\n }\n // Parent instance index\n if (parsedCamera.parentInstanceIndex !== undefined) {\n camera._waitingParentInstanceIndex = parsedCamera.parentInstanceIndex;\n }\n //If camera has an input manager, let it parse inputs settings\n if (camera.inputs) {\n camera.inputs.parse(parsedCamera);\n camera._setupInputs();\n }\n if (parsedCamera.upVector) {\n camera.upVector = Vector3.FromArray(parsedCamera.upVector); // need to force the upVector\n }\n if (camera.setPosition) {\n // need to force position\n camera.position.copyFromFloats(0, 0, 0);\n camera.setPosition(Vector3.FromArray(parsedCamera.position));\n }\n // Target\n if (parsedCamera.target) {\n if (camera.setTarget) {\n camera.setTarget(Vector3.FromArray(parsedCamera.target));\n }\n }\n // Apply 3d rig, when found\n if (parsedCamera.cameraRigMode) {\n const rigParams = parsedCamera.interaxial_distance ? { interaxialDistance: parsedCamera.interaxial_distance } : {};\n camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);\n }\n // Animations\n if (parsedCamera.animations) {\n for (let animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {\n const parsedAnimation = parsedCamera.animations[animationIndex];\n const internalClass = GetClass(\"BABYLON.Animation\");\n if (internalClass) {\n camera.animations.push(internalClass.Parse(parsedAnimation));\n }\n }\n Node.ParseAnimationRanges(camera, parsedCamera, scene);\n }\n if (parsedCamera.autoAnimate) {\n scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);\n }\n // Check if isEnabled is defined to be back compatible with prior serialized versions.\n if (parsedCamera.isEnabled !== undefined) {\n camera.setEnabled(parsedCamera.isEnabled);\n }\n return camera;\n }\n}\n/**\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nCamera._CreateDefaultParsedCamera = (name, scene) => {\n throw _WarnImport(\"UniversalCamera\");\n};\n/**\n * This is the default projection mode used by the cameras.\n * It helps recreating a feeling of perspective and better appreciate depth.\n * This is the best way to simulate real life cameras.\n */\nCamera.PERSPECTIVE_CAMERA = 0;\n/**\n * This helps creating camera with an orthographic mode.\n * Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object.\n */\nCamera.ORTHOGRAPHIC_CAMERA = 1;\n/**\n * This is the default FOV mode for perspective cameras.\n * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.\n */\nCamera.FOVMODE_VERTICAL_FIXED = 0;\n/**\n * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.\n */\nCamera.FOVMODE_HORIZONTAL_FIXED = 1;\n/**\n * This specifies there is no need for a camera rig.\n * Basically only one eye is rendered corresponding to the camera.\n */\nCamera.RIG_MODE_NONE = 0;\n/**\n * Simulates a camera Rig with one blue eye and one red eye.\n * This can be use with 3d blue and red glasses.\n */\nCamera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;\n/**\n * Defines that both eyes of the camera will be rendered side by side with a parallel target.\n */\nCamera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;\n/**\n * Defines that both eyes of the camera will be rendered side by side with a none parallel target.\n */\nCamera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;\n/**\n * Defines that both eyes of the camera will be rendered over under each other.\n */\nCamera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;\n/**\n * Defines that both eyes of the camera will be rendered on successive lines interlaced for passive 3d monitors.\n */\nCamera.RIG_MODE_STEREOSCOPIC_INTERLACED = 14;\n/**\n * Defines that both eyes of the camera should be renderered in a VR mode (carbox).\n */\nCamera.RIG_MODE_VR = 20;\n/**\n * Defines that both eyes of the camera should be renderered in a VR mode (webVR).\n */\nCamera.RIG_MODE_WEBVR = 21;\n/**\n * Custom rig mode allowing rig cameras to be populated manually with any number of cameras\n */\nCamera.RIG_MODE_CUSTOM = 22;\n/**\n * Defines if by default attaching controls should prevent the default javascript event to continue.\n */\nCamera.ForceAttachControlToAlwaysPreventDefault = false;\n__decorate([\n serializeAsVector3(\"position\")\n], Camera.prototype, \"_position\", void 0);\n__decorate([\n serializeAsVector3(\"upVector\")\n], Camera.prototype, \"_upVector\", void 0);\n__decorate([\n serialize()\n], Camera.prototype, \"orthoLeft\", null);\n__decorate([\n serialize()\n], Camera.prototype, \"orthoRight\", null);\n__decorate([\n serialize()\n], Camera.prototype, \"orthoBottom\", null);\n__decorate([\n serialize()\n], Camera.prototype, \"orthoTop\", null);\n__decorate([\n serialize()\n], Camera.prototype, \"fov\", void 0);\n__decorate([\n serialize()\n], Camera.prototype, \"projectionPlaneTilt\", void 0);\n__decorate([\n serialize()\n], Camera.prototype, \"minZ\", void 0);\n__decorate([\n serialize()\n], Camera.prototype, \"maxZ\", void 0);\n__decorate([\n serialize()\n], Camera.prototype, \"inertia\", void 0);\n__decorate([\n serialize()\n], Camera.prototype, \"mode\", null);\n__decorate([\n serialize()\n], Camera.prototype, \"layerMask\", void 0);\n__decorate([\n serialize()\n], Camera.prototype, \"fovMode\", void 0);\n__decorate([\n serialize()\n], Camera.prototype, \"cameraRigMode\", void 0);\n__decorate([\n serialize()\n], Camera.prototype, \"interaxialDistance\", void 0);\n__decorate([\n serialize()\n], Camera.prototype, \"isStereoscopicSideBySide\", void 0);\n//# sourceMappingURL=camera.js.map","export * from \"./EXT_lights_image_based.js\";\nexport * from \"./EXT_mesh_gpu_instancing.js\";\nexport * from \"./EXT_meshopt_compression.js\";\nexport * from \"./EXT_texture_webp.js\";\nexport * from \"./KHR_draco_mesh_compression.js\";\nexport * from \"./KHR_lights_punctual.js\";\nexport * from \"./KHR_materials_pbrSpecularGlossiness.js\";\nexport * from \"./KHR_materials_unlit.js\";\nexport * from \"./KHR_materials_clearcoat.js\";\nexport * from \"./KHR_materials_iridescence.js\";\nexport * from \"./KHR_materials_anisotropy.js\";\nexport * from \"./KHR_materials_emissive_strength.js\";\nexport * from \"./KHR_materials_sheen.js\";\nexport * from \"./KHR_materials_specular.js\";\nexport * from \"./KHR_materials_ior.js\";\nexport * from \"./KHR_materials_variants.js\";\nexport * from \"./KHR_materials_transmission.js\";\nexport * from \"./KHR_materials_translucency.js\";\nexport * from \"./KHR_materials_volume.js\";\nexport * from \"./KHR_mesh_quantization.js\";\nexport * from \"./KHR_texture_basisu.js\";\nexport * from \"./KHR_texture_transform.js\";\nexport * from \"./KHR_xmp_json_ld.js\";\nexport * from \"./KHR_animation_pointer.js\";\nexport * from \"./MSFT_audio_emitter.js\";\nexport * from \"./MSFT_lod.js\";\nexport * from \"./MSFT_minecraftMesh.js\";\nexport * from \"./MSFT_sRGBFactors.js\";\nexport * from \"./ExtrasAsMetadata.js\";\n//# sourceMappingURL=index.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./glTFLoader.js\";\nexport * from \"./glTFLoaderExtension.js\";\nexport * from \"./glTFLoaderInterfaces.js\";\nexport * from \"./Extensions/index.js\";\n//# sourceMappingURL=index.js.map","/* eslint-disable import/no-internal-modules */\nexport * from \"./glTFFileLoader.js\";\nexport * from \"./glTFValidation.js\";\nimport * as GLTF1 from \"./1.0/index.js\";\nimport * as GLTF2 from \"./2.0/index.js\";\nexport { GLTF1, GLTF2 };\n//# sourceMappingURL=index.js.map","import {\n Engine,\n Animation,\n AbstractMesh,\n ArcRotateCamera,\n Color4,\n Vector3,\n HemisphericLight,\n Scene,\n Tools,\n SceneLoader,\n} from \"@babylonjs/core\";\nimport \"@babylonjs/loaders/glTF\";\nimport { BabylonjsProps } from \"babylonjs-hook\";\n\nlet scene: Scene;\nlet offscreenCanvas: OffscreenCanvas;\nlet camera: ArcRotateCamera;\nlet drone: AbstractMesh;\n\n// ZOOM animation\nconst getZoomAnimation = (duration: number) => {\n const frameRate = 20;\n const lastFrame = duration * frameRate;\n\n const zoom = new Animation(\n \"zoom\",\n \"position\",\n 20,\n Animation.ANIMATIONTYPE_VECTOR3,\n Animation.ANIMATIONLOOPMODE_CONSTANT\n );\n zoom.setKeys([\n { frame: 0, value: new Vector3(0, 70, 0) },\n { frame: lastFrame, value: new Vector3(3, 7, -15) },\n ]);\n\n return {\n animation: [zoom],\n lastFrame,\n };\n};\n\n// SCENE READY handler\nconst onSceneReady = async (scene: Scene) => {\n // transparent background\n scene.clearColor = Color4.FromHexString(\"#000\");\n\n // camera creation\n camera = new ArcRotateCamera(\n \"camera1\",\n Tools.ToRadians(0),\n Tools.ToRadians(0),\n 15,\n Vector3.Zero(),\n scene\n );\n\n // figure creation\n const { meshes } = await SceneLoader.ImportMeshAsync(\n \"\",\n \"buster_drone/\",\n \"drone.gltf\",\n scene\n );\n drone = meshes[0];\n drone.scaling = new Vector3(3, 3, 3);\n drone.alwaysSelectAsActiveMesh = true;\n drone.enablePointerMoveEvents = true;\n drone.isNearPickable = true;\n\n // get canvas\n const canvas = scene.getEngine().getRenderingCanvas();\n\n // camera settings\n camera.allowUpsideDown;\n camera.wheelDeltaPercentage = 0.01;\n camera.lowerRadiusLimit = 8;\n camera.upperRadiusLimit = 70;\n camera.setTarget(drone);\n camera.attachControl(canvas, false);\n\n // lights\n const light = new HemisphericLight(\"light\", new Vector3(0, 10, 10), scene);\n const light2 = new HemisphericLight(\"light2\", new Vector3(0, -10, 10), scene);\n light.intensity = 2.5;\n light2.intensity = 1.5;\n\n // animation\n const { animation, lastFrame } = getZoomAnimation(4);\n scene.beginDirectAnimation(camera, animation, 0, lastFrame, false);\n};\n\n// BABYLON INITIALIZATION\nconst initBabylonScene = ({\n antialias,\n engineOptions,\n adaptToDeviceRatio,\n sceneOptions,\n onRender,\n onSceneReady,\n canvas,\n}: BabylonjsProps & { canvas: OffscreenCanvas }) => {\n const engine = new Engine(\n canvas,\n antialias,\n engineOptions,\n adaptToDeviceRatio\n );\n const scene = new Scene(engine, sceneOptions);\n if (scene.isReady()) {\n onSceneReady(scene);\n } else {\n scene.onReadyObservable.addOnce((scene) => onSceneReady(scene));\n }\n\n engine.runRenderLoop(() => {\n if (typeof onRender === \"function\") onRender(scene);\n scene.render();\n });\n\n return { scene, canvas };\n};\n\n// WORKER EVENT HANDLER\nself.onmessage = async ({\n data: { canvas, width, height, dispose, wheel, x, y },\n}: MessageEvent<{\n canvas?: OffscreenCanvas;\n width?: number;\n height?: number;\n dispose?: boolean;\n wheel?: number;\n x?: number;\n y?: number;\n}>) => {\n // initialization\n if (canvas) {\n const elements = initBabylonScene({\n antialias: true,\n onSceneReady,\n canvas: canvas,\n });\n scene = elements.scene;\n offscreenCanvas = elements.canvas;\n self.postMessage(\"ready\");\n }\n\n // resize\n if (scene && offscreenCanvas && !canvas && width && height) {\n offscreenCanvas.width = width;\n offscreenCanvas.height = height;\n scene.getEngine().resize(true);\n }\n\n // dispose\n if (dispose && scene) {\n scene.getEngine().dispose();\n }\n\n // zoom\n if (camera && wheel) {\n camera.radius = camera.radius + wheel * camera.wheelDeltaPercentage;\n }\n\n // camera rotation\n if (scene && x !== undefined && y !== undefined) {\n camera.alpha -= x / 100;\n camera.beta -= y / 100;\n }\n};\n","\n/**\n * Abstract class used to decouple action Manager from scene and meshes.\n * Do not instantiate.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\nexport class AbstractActionManager {\n constructor() {\n /** Gets the cursor to use when hovering items */\n this.hoverCursor = \"\";\n /** Gets the list of actions */\n this.actions = new Array();\n /**\n * Gets or sets a boolean indicating that the manager is recursive meaning that it can trigger action from children\n */\n this.isRecursive = false;\n }\n /**\n * Does exist one action manager with at least one trigger\n **/\n static get HasTriggers() {\n for (const t in AbstractActionManager.Triggers) {\n if (Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers, t)) {\n return true;\n }\n }\n return false;\n }\n /**\n * Does exist one action manager with at least one pick trigger\n **/\n static get HasPickTriggers() {\n for (const t in AbstractActionManager.Triggers) {\n if (Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers, t)) {\n const tAsInt = parseInt(t);\n if (tAsInt >= 1 && tAsInt <= 7) {\n return true;\n }\n }\n }\n return false;\n }\n /**\n * Does exist one action manager that handles actions of a given trigger\n * @param trigger defines the trigger to be tested\n * @returns a boolean indicating whether the trigger is handled by at least one action manager\n **/\n static HasSpecificTrigger(trigger) {\n for (const t in AbstractActionManager.Triggers) {\n if (Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers, t)) {\n const tAsInt = parseInt(t);\n if (tAsInt === trigger) {\n return true;\n }\n }\n }\n return false;\n }\n}\n/** Gets the list of active triggers */\nAbstractActionManager.Triggers = {};\n//# sourceMappingURL=abstractActionManager.js.map","/**\n * ActionEvent is the event being sent when an action is triggered.\n */\nexport class ActionEvent {\n /**\n * Creates a new ActionEvent\n * @param source The mesh or sprite that triggered the action\n * @param pointerX The X mouse cursor position at the time of the event\n * @param pointerY The Y mouse cursor position at the time of the event\n * @param meshUnderPointer The mesh that is currently pointed at (can be null)\n * @param sourceEvent the original (browser) event that triggered the ActionEvent\n * @param additionalData additional data for the event\n */\n constructor(\n /** The mesh or sprite that triggered the action */\n source, \n /** The X mouse cursor position at the time of the event */\n pointerX, \n /** The Y mouse cursor position at the time of the event */\n pointerY, \n /** The mesh that is currently pointed at (can be null) */\n meshUnderPointer, \n /** the original (browser) event that triggered the ActionEvent */\n sourceEvent, \n /** additional data for the event */\n additionalData) {\n this.source = source;\n this.pointerX = pointerX;\n this.pointerY = pointerY;\n this.meshUnderPointer = meshUnderPointer;\n this.sourceEvent = sourceEvent;\n this.additionalData = additionalData;\n }\n /**\n * Helper function to auto-create an ActionEvent from a source mesh.\n * @param source The source mesh that triggered the event\n * @param evt The original (browser) event\n * @param additionalData additional data for the event\n * @returns the new ActionEvent\n */\n static CreateNew(source, evt, additionalData) {\n const scene = source.getScene();\n return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer || source, evt, additionalData);\n }\n /**\n * Helper function to auto-create an ActionEvent from a source sprite\n * @param source The source sprite that triggered the event\n * @param scene Scene associated with the sprite\n * @param evt The original (browser) event\n * @param additionalData additional data for the event\n * @returns the new ActionEvent\n */\n static CreateNewFromSprite(source, scene, evt, additionalData) {\n return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);\n }\n /**\n * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew\n * @param scene the scene where the event occurred\n * @param evt The original (browser) event\n * @returns the new ActionEvent\n */\n static CreateNewFromScene(scene, evt) {\n return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);\n }\n /**\n * Helper function to auto-create an ActionEvent from a primitive\n * @param prim defines the target primitive\n * @param pointerPos defines the pointer position\n * @param evt The original (browser) event\n * @param additionalData additional data for the event\n * @returns the new ActionEvent\n */\n static CreateNewFromPrimitive(prim, pointerPos, evt, additionalData) {\n return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);\n }\n}\n//# sourceMappingURL=actionEvent.js.map","/**\n * Class used to store gfx data (like WebGLBuffer)\n */\nexport class DataBuffer {\n /**\n * Gets the underlying buffer\n */\n get underlyingResource() {\n return null;\n }\n /**\n * Constructs the buffer\n */\n constructor() {\n /**\n * Gets or sets the number of objects referencing this buffer\n */\n this.references = 0;\n /** Gets or sets the size of the underlying buffer */\n this.capacity = 0;\n /**\n * Gets or sets a boolean indicating if the buffer contains 32bits indices\n */\n this.is32Bits = false;\n this.uniqueId = DataBuffer._Counter++;\n }\n}\nDataBuffer._Counter = 0;\n//# sourceMappingURL=dataBuffer.js.map","/**\n * @internal\n */\nexport class IntersectionInfo {\n constructor(bu, bv, distance) {\n this.bu = bu;\n this.bv = bv;\n this.distance = distance;\n this.faceId = 0;\n this.subMeshId = 0;\n }\n}\n//# sourceMappingURL=intersectionInfo.js.map","import { Vector3 } from \"../Maths/math.vector.js\";\n/**\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport class _MeshCollisionData {\n constructor() {\n this._checkCollisions = false;\n this._collisionMask = -1;\n this._collisionGroup = -1;\n this._surroundingMeshes = null;\n this._collider = null;\n this._oldPositionForCollisions = new Vector3(0, 0, 0);\n this._diffPositionForCollisions = new Vector3(0, 0, 0);\n this._collisionResponse = true;\n }\n}\n//# sourceMappingURL=meshCollisionData.js.map","import { Vector3, Vector2, TmpVectors } from \"../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\n/**\n * Information about the result of picking within a scene\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/picking_collisions\n */\nexport class PickingInfo {\n constructor() {\n /**\n * If the pick collided with an object\n */\n this.hit = false;\n /**\n * Distance away where the pick collided\n */\n this.distance = 0;\n /**\n * The location of pick collision\n */\n this.pickedPoint = null;\n /**\n * The mesh corresponding the pick collision\n */\n this.pickedMesh = null;\n /** (See getTextureCoordinates) The barycentric U coordinate that is used when calculating the texture coordinates of the collision.*/\n this.bu = 0;\n /** (See getTextureCoordinates) The barycentric V coordinate that is used when calculating the texture coordinates of the collision.*/\n this.bv = 0;\n /** The index of the face on the mesh that was picked, or the index of the Line if the picked Mesh is a LinesMesh */\n this.faceId = -1;\n /** The index of the face on the subMesh that was picked, or the index of the Line if the picked Mesh is a LinesMesh */\n this.subMeshFaceId = -1;\n /** Id of the submesh that was picked */\n this.subMeshId = 0;\n /** If a sprite was picked, this will be the sprite the pick collided with */\n this.pickedSprite = null;\n /** If we are picking a mesh with thin instance, this will give you the picked thin instance */\n this.thinInstanceIndex = -1;\n /**\n * The ray that was used to perform the picking.\n */\n this.ray = null;\n /**\n * If a mesh was used to do the picking (eg. 6dof controller) as a \"near interaction\", this will be populated.\n */\n this.originMesh = null;\n /**\n * The aim-space transform of the input used for picking, if it is an XR input source.\n */\n this.aimTransform = null;\n /**\n * The grip-space transform of the input used for picking, if it is an XR input source.\n * Some XR sources, such as input coming from head mounted displays, do not have this.\n */\n this.gripTransform = null;\n }\n /**\n * Gets the normal corresponding to the face the pick collided with\n * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)\n * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map (default: true)\n * @returns The normal corresponding to the face the pick collided with\n * @remarks Note that the returned normal will always point towards the picking ray.\n */\n getNormal(useWorldCoordinates = false, useVerticesNormals = true) {\n if (!this.pickedMesh || (useVerticesNormals && !this.pickedMesh.isVerticesDataPresent(VertexBuffer.NormalKind))) {\n return null;\n }\n let indices = this.pickedMesh.getIndices();\n if ((indices === null || indices === void 0 ? void 0 : indices.length) === 0) {\n indices = null;\n }\n let result;\n const tmp0 = TmpVectors.Vector3[0];\n const tmp1 = TmpVectors.Vector3[1];\n const tmp2 = TmpVectors.Vector3[2];\n if (useVerticesNormals) {\n const normals = this.pickedMesh.getVerticesData(VertexBuffer.NormalKind);\n let normal0 = indices\n ? Vector3.FromArrayToRef(normals, indices[this.faceId * 3] * 3, tmp0)\n : tmp0.copyFromFloats(normals[this.faceId * 3 * 3], normals[this.faceId * 3 * 3 + 1], normals[this.faceId * 3 * 3 + 2]);\n let normal1 = indices\n ? Vector3.FromArrayToRef(normals, indices[this.faceId * 3 + 1] * 3, tmp1)\n : tmp1.copyFromFloats(normals[(this.faceId * 3 + 1) * 3], normals[(this.faceId * 3 + 1) * 3 + 1], normals[(this.faceId * 3 + 1) * 3 + 2]);\n let normal2 = indices\n ? Vector3.FromArrayToRef(normals, indices[this.faceId * 3 + 2] * 3, tmp2)\n : tmp2.copyFromFloats(normals[(this.faceId * 3 + 2) * 3], normals[(this.faceId * 3 + 2) * 3 + 1], normals[(this.faceId * 3 + 2) * 3 + 2]);\n normal0 = normal0.scale(this.bu);\n normal1 = normal1.scale(this.bv);\n normal2 = normal2.scale(1.0 - this.bu - this.bv);\n result = new Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);\n }\n else {\n const positions = this.pickedMesh.getVerticesData(VertexBuffer.PositionKind);\n const vertex1 = indices\n ? Vector3.FromArrayToRef(positions, indices[this.faceId * 3] * 3, tmp0)\n : tmp0.copyFromFloats(positions[this.faceId * 3 * 3], positions[this.faceId * 3 * 3 + 1], positions[this.faceId * 3 * 3 + 2]);\n const vertex2 = indices\n ? Vector3.FromArrayToRef(positions, indices[this.faceId * 3 + 1] * 3, tmp1)\n : tmp1.copyFromFloats(positions[(this.faceId * 3 + 1) * 3], positions[(this.faceId * 3 + 1) * 3 + 1], positions[(this.faceId * 3 + 1) * 3 + 2]);\n const vertex3 = indices\n ? Vector3.FromArrayToRef(positions, indices[this.faceId * 3 + 2] * 3, tmp2)\n : tmp2.copyFromFloats(positions[(this.faceId * 3 + 2) * 3], positions[(this.faceId * 3 + 2) * 3 + 1], positions[(this.faceId * 3 + 2) * 3 + 2]);\n const p1p2 = vertex1.subtract(vertex2);\n const p3p2 = vertex3.subtract(vertex2);\n result = Vector3.Cross(p1p2, p3p2);\n }\n const transformNormalToWorld = (pickedMesh, n) => {\n let wm = pickedMesh.getWorldMatrix();\n if (pickedMesh.nonUniformScaling) {\n TmpVectors.Matrix[0].copyFrom(wm);\n wm = TmpVectors.Matrix[0];\n wm.setTranslationFromFloats(0, 0, 0);\n wm.invert();\n wm.transposeToRef(TmpVectors.Matrix[1]);\n wm = TmpVectors.Matrix[1];\n }\n Vector3.TransformNormalToRef(n, wm, n);\n };\n if (useWorldCoordinates) {\n transformNormalToWorld(this.pickedMesh, result);\n }\n if (this.ray) {\n const normalForDirectionChecking = TmpVectors.Vector3[0].copyFrom(result);\n if (!useWorldCoordinates) {\n // the normal has not been transformed to world space as part as the normal processing, so we must do it now\n transformNormalToWorld(this.pickedMesh, normalForDirectionChecking);\n }\n // Flip the normal if the picking ray is in the same direction.\n if (Vector3.Dot(normalForDirectionChecking, this.ray.direction) > 0) {\n result.negateInPlace();\n }\n }\n result.normalize();\n return result;\n }\n /**\n * Gets the texture coordinates of where the pick occurred\n * @param uvSet The UV set to use to calculate the texture coordinates (default: VertexBuffer.UVKind)\n * @returns The vector containing the coordinates of the texture\n */\n getTextureCoordinates(uvSet = VertexBuffer.UVKind) {\n if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(uvSet)) {\n return null;\n }\n const indices = this.pickedMesh.getIndices();\n if (!indices) {\n return null;\n }\n const uvs = this.pickedMesh.getVerticesData(uvSet);\n if (!uvs) {\n return null;\n }\n let uv0 = Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);\n let uv1 = Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);\n let uv2 = Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);\n uv0 = uv0.scale(this.bu);\n uv1 = uv1.scale(this.bv);\n uv2 = uv2.scale(1.0 - this.bu - this.bv);\n return new Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);\n }\n}\n//# sourceMappingURL=pickingInfo.js.map","/**\n * Options used to control default behaviors regarding compatibility support\n */\nexport class CompatibilityOptions {\n}\n/**\n * Defines if the system should use OpenGL convention for UVs when creating geometry or loading .babylon files (false by default)\n */\nCompatibilityOptions.UseOpenGLOrientationForUV = false;\n//# sourceMappingURL=compatibilityOptions.js.map","import { ArrayTools } from \"../Misc/arrayTools.js\";\nimport { Matrix, Vector3 } from \"../Maths/math.vector.js\";\nimport { Epsilon } from \"../Maths/math.constants.js\";\n/**\n * Class used to store bounding box information\n */\nexport class BoundingBox {\n /**\n * Creates a new bounding box\n * @param min defines the minimum vector (in local space)\n * @param max defines the maximum vector (in local space)\n * @param worldMatrix defines the new world matrix\n */\n constructor(min, max, worldMatrix) {\n /**\n * Gets the 8 vectors representing the bounding box in local space\n */\n this.vectors = ArrayTools.BuildArray(8, Vector3.Zero);\n /**\n * Gets the center of the bounding box in local space\n */\n this.center = Vector3.Zero();\n /**\n * Gets the center of the bounding box in world space\n */\n this.centerWorld = Vector3.Zero();\n /**\n * Gets the extend size in local space\n */\n this.extendSize = Vector3.Zero();\n /**\n * Gets the extend size in world space\n */\n this.extendSizeWorld = Vector3.Zero();\n /**\n * Gets the OBB (object bounding box) directions\n */\n this.directions = ArrayTools.BuildArray(3, Vector3.Zero);\n /**\n * Gets the 8 vectors representing the bounding box in world space\n */\n this.vectorsWorld = ArrayTools.BuildArray(8, Vector3.Zero);\n /**\n * Gets the minimum vector in world space\n */\n this.minimumWorld = Vector3.Zero();\n /**\n * Gets the maximum vector in world space\n */\n this.maximumWorld = Vector3.Zero();\n /**\n * Gets the minimum vector in local space\n */\n this.minimum = Vector3.Zero();\n /**\n * Gets the maximum vector in local space\n */\n this.maximum = Vector3.Zero();\n /** @internal */\n this._drawWrapperFront = null;\n /** @internal */\n this._drawWrapperBack = null;\n this.reConstruct(min, max, worldMatrix);\n }\n // Methods\n /**\n * Recreates the entire bounding box from scratch as if we call the constructor in place\n * @param min defines the new minimum vector (in local space)\n * @param max defines the new maximum vector (in local space)\n * @param worldMatrix defines the new world matrix\n */\n reConstruct(min, max, worldMatrix) {\n const minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;\n const vectors = this.vectors;\n this.minimum.copyFromFloats(minX, minY, minZ);\n this.maximum.copyFromFloats(maxX, maxY, maxZ);\n vectors[0].copyFromFloats(minX, minY, minZ);\n vectors[1].copyFromFloats(maxX, maxY, maxZ);\n vectors[2].copyFromFloats(maxX, minY, minZ);\n vectors[3].copyFromFloats(minX, maxY, minZ);\n vectors[4].copyFromFloats(minX, minY, maxZ);\n vectors[5].copyFromFloats(maxX, maxY, minZ);\n vectors[6].copyFromFloats(minX, maxY, maxZ);\n vectors[7].copyFromFloats(maxX, minY, maxZ);\n // OBB\n max.addToRef(min, this.center).scaleInPlace(0.5);\n max.subtractToRef(min, this.extendSize).scaleInPlace(0.5);\n this._worldMatrix = worldMatrix || Matrix.IdentityReadOnly;\n this._update(this._worldMatrix);\n }\n /**\n * Scale the current bounding box by applying a scale factor\n * @param factor defines the scale factor to apply\n * @returns the current bounding box\n */\n scale(factor) {\n const tmpVectors = BoundingBox._TmpVector3;\n const diff = this.maximum.subtractToRef(this.minimum, tmpVectors[0]);\n const len = diff.length();\n diff.normalizeFromLength(len);\n const distance = len * factor;\n const newRadius = diff.scaleInPlace(distance * 0.5);\n const min = this.center.subtractToRef(newRadius, tmpVectors[1]);\n const max = this.center.addToRef(newRadius, tmpVectors[2]);\n this.reConstruct(min, max, this._worldMatrix);\n return this;\n }\n /**\n * Gets the world matrix of the bounding box\n * @returns a matrix\n */\n getWorldMatrix() {\n return this._worldMatrix;\n }\n /**\n * @internal\n */\n _update(world) {\n const minWorld = this.minimumWorld;\n const maxWorld = this.maximumWorld;\n const directions = this.directions;\n const vectorsWorld = this.vectorsWorld;\n const vectors = this.vectors;\n if (!world.isIdentity()) {\n minWorld.setAll(Number.MAX_VALUE);\n maxWorld.setAll(-Number.MAX_VALUE);\n for (let index = 0; index < 8; ++index) {\n const v = vectorsWorld[index];\n Vector3.TransformCoordinatesToRef(vectors[index], world, v);\n minWorld.minimizeInPlace(v);\n maxWorld.maximizeInPlace(v);\n }\n // Extend\n maxWorld.subtractToRef(minWorld, this.extendSizeWorld).scaleInPlace(0.5);\n maxWorld.addToRef(minWorld, this.centerWorld).scaleInPlace(0.5);\n }\n else {\n minWorld.copyFrom(this.minimum);\n maxWorld.copyFrom(this.maximum);\n for (let index = 0; index < 8; ++index) {\n vectorsWorld[index].copyFrom(vectors[index]);\n }\n // Extend\n this.extendSizeWorld.copyFrom(this.extendSize);\n this.centerWorld.copyFrom(this.center);\n }\n Vector3.FromArrayToRef(world.m, 0, directions[0]);\n Vector3.FromArrayToRef(world.m, 4, directions[1]);\n Vector3.FromArrayToRef(world.m, 8, directions[2]);\n this._worldMatrix = world;\n }\n /**\n * Tests if the bounding box is intersecting the frustum planes\n * @param frustumPlanes defines the frustum planes to test\n * @returns true if there is an intersection\n */\n isInFrustum(frustumPlanes) {\n return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);\n }\n /**\n * Tests if the bounding box is entirely inside the frustum planes\n * @param frustumPlanes defines the frustum planes to test\n * @returns true if there is an inclusion\n */\n isCompletelyInFrustum(frustumPlanes) {\n return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);\n }\n /**\n * Tests if a point is inside the bounding box\n * @param point defines the point to test\n * @returns true if the point is inside the bounding box\n */\n intersectsPoint(point) {\n const min = this.minimumWorld;\n const max = this.maximumWorld;\n const minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;\n const pointX = point.x, pointY = point.y, pointZ = point.z;\n const delta = -Epsilon;\n if (maxX - pointX < delta || delta > pointX - minX) {\n return false;\n }\n if (maxY - pointY < delta || delta > pointY - minY) {\n return false;\n }\n if (maxZ - pointZ < delta || delta > pointZ - minZ) {\n return false;\n }\n return true;\n }\n /**\n * Tests if the bounding box intersects with a bounding sphere\n * @param sphere defines the sphere to test\n * @returns true if there is an intersection\n */\n intersectsSphere(sphere) {\n return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);\n }\n /**\n * Tests if the bounding box intersects with a box defined by a min and max vectors\n * @param min defines the min vector to use\n * @param max defines the max vector to use\n * @returns true if there is an intersection\n */\n intersectsMinMax(min, max) {\n const myMin = this.minimumWorld;\n const myMax = this.maximumWorld;\n const myMinX = myMin.x, myMinY = myMin.y, myMinZ = myMin.z, myMaxX = myMax.x, myMaxY = myMax.y, myMaxZ = myMax.z;\n const minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;\n if (myMaxX < minX || myMinX > maxX) {\n return false;\n }\n if (myMaxY < minY || myMinY > maxY) {\n return false;\n }\n if (myMaxZ < minZ || myMinZ > maxZ) {\n return false;\n }\n return true;\n }\n /**\n * Disposes the resources of the class\n */\n dispose() {\n var _a, _b;\n (_a = this._drawWrapperFront) === null || _a === void 0 ? void 0 : _a.dispose();\n (_b = this._drawWrapperBack) === null || _b === void 0 ? void 0 : _b.dispose();\n }\n // Statics\n /**\n * Tests if two bounding boxes are intersections\n * @param box0 defines the first box to test\n * @param box1 defines the second box to test\n * @returns true if there is an intersection\n */\n static Intersects(box0, box1) {\n return box0.intersectsMinMax(box1.minimumWorld, box1.maximumWorld);\n }\n /**\n * Tests if a bounding box defines by a min/max vectors intersects a sphere\n * @param minPoint defines the minimum vector of the bounding box\n * @param maxPoint defines the maximum vector of the bounding box\n * @param sphereCenter defines the sphere center\n * @param sphereRadius defines the sphere radius\n * @returns true if there is an intersection\n */\n static IntersectsSphere(minPoint, maxPoint, sphereCenter, sphereRadius) {\n const vector = BoundingBox._TmpVector3[0];\n Vector3.ClampToRef(sphereCenter, minPoint, maxPoint, vector);\n const num = Vector3.DistanceSquared(sphereCenter, vector);\n return num <= sphereRadius * sphereRadius;\n }\n /**\n * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes\n * @param boundingVectors defines an array of 8 vectors representing a bounding box\n * @param frustumPlanes defines the frustum planes to test\n * @returns true if there is an inclusion\n */\n static IsCompletelyInFrustum(boundingVectors, frustumPlanes) {\n for (let p = 0; p < 6; ++p) {\n const frustumPlane = frustumPlanes[p];\n for (let i = 0; i < 8; ++i) {\n if (frustumPlane.dotCoordinate(boundingVectors[i]) < 0) {\n return false;\n }\n }\n }\n return true;\n }\n /**\n * Tests if a bounding box defined with 8 vectors intersects frustum planes\n * @param boundingVectors defines an array of 8 vectors representing a bounding box\n * @param frustumPlanes defines the frustum planes to test\n * @returns true if there is an intersection\n */\n static IsInFrustum(boundingVectors, frustumPlanes) {\n for (let p = 0; p < 6; ++p) {\n let canReturnFalse = true;\n const frustumPlane = frustumPlanes[p];\n for (let i = 0; i < 8; ++i) {\n if (frustumPlane.dotCoordinate(boundingVectors[i]) >= 0) {\n canReturnFalse = false;\n break;\n }\n }\n if (canReturnFalse) {\n return false;\n }\n }\n return true;\n }\n}\nBoundingBox._TmpVector3 = ArrayTools.BuildArray(3, Vector3.Zero);\n//# sourceMappingURL=boundingBox.js.map","import { ArrayTools } from \"../Misc/arrayTools.js\";\nimport { TmpVectors } from \"../Maths/math.vector.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\n\nimport { BoundingBox } from \"./boundingBox.js\";\nimport { BoundingSphere } from \"./boundingSphere.js\";\nconst _result0 = { min: 0, max: 0 };\nconst _result1 = { min: 0, max: 0 };\nconst computeBoxExtents = (axis, box, result) => {\n const p = Vector3.Dot(box.centerWorld, axis);\n const r0 = Math.abs(Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;\n const r1 = Math.abs(Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;\n const r2 = Math.abs(Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;\n const r = r0 + r1 + r2;\n result.min = p - r;\n result.max = p + r;\n};\nconst axisOverlap = (axis, box0, box1) => {\n computeBoxExtents(axis, box0, _result0);\n computeBoxExtents(axis, box1, _result1);\n return !(_result0.min > _result1.max || _result1.min > _result0.max);\n};\n/**\n * Info for a bounding data of a mesh\n */\nexport class BoundingInfo {\n /**\n * Constructs bounding info\n * @param minimum min vector of the bounding box/sphere\n * @param maximum max vector of the bounding box/sphere\n * @param worldMatrix defines the new world matrix\n */\n constructor(minimum, maximum, worldMatrix) {\n this._isLocked = false;\n this.boundingBox = new BoundingBox(minimum, maximum, worldMatrix);\n this.boundingSphere = new BoundingSphere(minimum, maximum, worldMatrix);\n }\n /**\n * Recreates the entire bounding info from scratch as if we call the constructor in place\n * @param min defines the new minimum vector (in local space)\n * @param max defines the new maximum vector (in local space)\n * @param worldMatrix defines the new world matrix\n */\n reConstruct(min, max, worldMatrix) {\n this.boundingBox.reConstruct(min, max, worldMatrix);\n this.boundingSphere.reConstruct(min, max, worldMatrix);\n }\n /**\n * min vector of the bounding box/sphere\n */\n get minimum() {\n return this.boundingBox.minimum;\n }\n /**\n * max vector of the bounding box/sphere\n */\n get maximum() {\n return this.boundingBox.maximum;\n }\n /**\n * If the info is locked and won't be updated to avoid perf overhead\n */\n get isLocked() {\n return this._isLocked;\n }\n set isLocked(value) {\n this._isLocked = value;\n }\n // Methods\n /**\n * Updates the bounding sphere and box\n * @param world world matrix to be used to update\n */\n update(world) {\n if (this._isLocked) {\n return;\n }\n this.boundingBox._update(world);\n this.boundingSphere._update(world);\n }\n /**\n * Recreate the bounding info to be centered around a specific point given a specific extend.\n * @param center New center of the bounding info\n * @param extend New extend of the bounding info\n * @returns the current bounding info\n */\n centerOn(center, extend) {\n const minimum = BoundingInfo._TmpVector3[0].copyFrom(center).subtractInPlace(extend);\n const maximum = BoundingInfo._TmpVector3[1].copyFrom(center).addInPlace(extend);\n this.boundingBox.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix());\n this.boundingSphere.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix());\n return this;\n }\n /**\n * Grows the bounding info to include the given point.\n * @param point The point that will be included in the current bounding info (in local space)\n * @returns the current bounding info\n */\n encapsulate(point) {\n const minimum = Vector3.Minimize(this.minimum, point);\n const maximum = Vector3.Maximize(this.maximum, point);\n this.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix());\n return this;\n }\n /**\n * Grows the bounding info to encapsulate the given bounding info.\n * @param toEncapsulate The bounding info that will be encapsulated in the current bounding info\n * @returns the current bounding info\n */\n encapsulateBoundingInfo(toEncapsulate) {\n const invw = TmpVectors.Matrix[0];\n this.boundingBox.getWorldMatrix().invertToRef(invw);\n const v = TmpVectors.Vector3[0];\n Vector3.TransformCoordinatesToRef(toEncapsulate.boundingBox.minimumWorld, invw, v);\n this.encapsulate(v);\n Vector3.TransformCoordinatesToRef(toEncapsulate.boundingBox.maximumWorld, invw, v);\n this.encapsulate(v);\n return this;\n }\n /**\n * Scale the current bounding info by applying a scale factor\n * @param factor defines the scale factor to apply\n * @returns the current bounding info\n */\n scale(factor) {\n this.boundingBox.scale(factor);\n this.boundingSphere.scale(factor);\n return this;\n }\n /**\n * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.\n * @param frustumPlanes defines the frustum to test\n * @param strategy defines the strategy to use for the culling (default is BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD)\n * The different strategies available are:\n * * BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD most accurate but slower @see https://doc.babylonjs.com/typedoc/classes/BABYLON.AbstractMesh#CULLINGSTRATEGY_STANDARD\n * * BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY faster but less accurate @see https://doc.babylonjs.com/typedoc/classes/BABYLON.AbstractMesh#CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY\n * * BABYLON.AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION can be faster if always visible @see https://doc.babylonjs.com/typedoc/classes/BABYLON.AbstractMesh#CULLINGSTRATEGY_OPTIMISTIC_INCLUSION\n * * BABYLON.AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY can be faster if always visible @see https://doc.babylonjs.com/typedoc/classes/BABYLON.AbstractMesh#CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY\n * @returns true if the bounding info is in the frustum planes\n */\n isInFrustum(frustumPlanes, strategy = 0) {\n const inclusionTest = strategy === 2 || strategy === 3;\n if (inclusionTest) {\n if (this.boundingSphere.isCenterInFrustum(frustumPlanes)) {\n return true;\n }\n }\n if (!this.boundingSphere.isInFrustum(frustumPlanes)) {\n return false;\n }\n const bSphereOnlyTest = strategy === 1 || strategy === 3;\n if (bSphereOnlyTest) {\n return true;\n }\n return this.boundingBox.isInFrustum(frustumPlanes);\n }\n /**\n * Gets the world distance between the min and max points of the bounding box\n */\n get diagonalLength() {\n const boundingBox = this.boundingBox;\n const diag = boundingBox.maximumWorld.subtractToRef(boundingBox.minimumWorld, BoundingInfo._TmpVector3[0]);\n return diag.length();\n }\n /**\n * Checks if a cullable object (mesh...) is in the camera frustum\n * Unlike isInFrustum this checks the full bounding box\n * @param frustumPlanes Camera near/planes\n * @returns true if the object is in frustum otherwise false\n */\n isCompletelyInFrustum(frustumPlanes) {\n return this.boundingBox.isCompletelyInFrustum(frustumPlanes);\n }\n /**\n * @internal\n */\n _checkCollision(collider) {\n return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);\n }\n /**\n * Checks if a point is inside the bounding box and bounding sphere or the mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/mesh_intersect\n * @param point the point to check intersection with\n * @returns if the point intersects\n */\n intersectsPoint(point) {\n if (!this.boundingSphere.centerWorld) {\n return false;\n }\n if (!this.boundingSphere.intersectsPoint(point)) {\n return false;\n }\n if (!this.boundingBox.intersectsPoint(point)) {\n return false;\n }\n return true;\n }\n /**\n * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/mesh_intersect\n * @param boundingInfo the bounding info to check intersection with\n * @param precise if the intersection should be done using OBB\n * @returns if the bounding info intersects\n */\n intersects(boundingInfo, precise) {\n if (!BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {\n return false;\n }\n if (!BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {\n return false;\n }\n if (!precise) {\n return true;\n }\n const box0 = this.boundingBox;\n const box1 = boundingInfo.boundingBox;\n if (!axisOverlap(box0.directions[0], box0, box1)) {\n return false;\n }\n if (!axisOverlap(box0.directions[1], box0, box1)) {\n return false;\n }\n if (!axisOverlap(box0.directions[2], box0, box1)) {\n return false;\n }\n if (!axisOverlap(box1.directions[0], box0, box1)) {\n return false;\n }\n if (!axisOverlap(box1.directions[1], box0, box1)) {\n return false;\n }\n if (!axisOverlap(box1.directions[2], box0, box1)) {\n return false;\n }\n if (!axisOverlap(Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1)) {\n return false;\n }\n if (!axisOverlap(Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1)) {\n return false;\n }\n if (!axisOverlap(Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1)) {\n return false;\n }\n if (!axisOverlap(Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1)) {\n return false;\n }\n if (!axisOverlap(Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1)) {\n return false;\n }\n if (!axisOverlap(Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1)) {\n return false;\n }\n if (!axisOverlap(Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1)) {\n return false;\n }\n if (!axisOverlap(Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1)) {\n return false;\n }\n if (!axisOverlap(Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1)) {\n return false;\n }\n return true;\n }\n}\nBoundingInfo._TmpVector3 = ArrayTools.BuildArray(2, Vector3.Zero);\n//# sourceMappingURL=boundingInfo.js.map","import { ArrayTools } from \"../Misc/arrayTools.js\";\nimport { Matrix, Vector3 } from \"../Maths/math.vector.js\";\n/**\n * Class used to store bounding sphere information\n */\nexport class BoundingSphere {\n /**\n * Creates a new bounding sphere\n * @param min defines the minimum vector (in local space)\n * @param max defines the maximum vector (in local space)\n * @param worldMatrix defines the new world matrix\n */\n constructor(min, max, worldMatrix) {\n /**\n * Gets the center of the bounding sphere in local space\n */\n this.center = Vector3.Zero();\n /**\n * Gets the center of the bounding sphere in world space\n */\n this.centerWorld = Vector3.Zero();\n /**\n * Gets the minimum vector in local space\n */\n this.minimum = Vector3.Zero();\n /**\n * Gets the maximum vector in local space\n */\n this.maximum = Vector3.Zero();\n this.reConstruct(min, max, worldMatrix);\n }\n /**\n * Recreates the entire bounding sphere from scratch as if we call the constructor in place\n * @param min defines the new minimum vector (in local space)\n * @param max defines the new maximum vector (in local space)\n * @param worldMatrix defines the new world matrix\n */\n reConstruct(min, max, worldMatrix) {\n this.minimum.copyFrom(min);\n this.maximum.copyFrom(max);\n const distance = Vector3.Distance(min, max);\n max.addToRef(min, this.center).scaleInPlace(0.5);\n this.radius = distance * 0.5;\n this._update(worldMatrix || Matrix.IdentityReadOnly);\n }\n /**\n * Scale the current bounding sphere by applying a scale factor\n * @param factor defines the scale factor to apply\n * @returns the current bounding box\n */\n scale(factor) {\n const newRadius = this.radius * factor;\n const tmpVectors = BoundingSphere._TmpVector3;\n const tempRadiusVector = tmpVectors[0].setAll(newRadius);\n const min = this.center.subtractToRef(tempRadiusVector, tmpVectors[1]);\n const max = this.center.addToRef(tempRadiusVector, tmpVectors[2]);\n this.reConstruct(min, max, this._worldMatrix);\n return this;\n }\n /**\n * Gets the world matrix of the bounding box\n * @returns a matrix\n */\n getWorldMatrix() {\n return this._worldMatrix;\n }\n // Methods\n /**\n * @internal\n */\n _update(worldMatrix) {\n if (!worldMatrix.isIdentity()) {\n Vector3.TransformCoordinatesToRef(this.center, worldMatrix, this.centerWorld);\n const tempVector = BoundingSphere._TmpVector3[0];\n Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, worldMatrix, tempVector);\n this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius;\n }\n else {\n this.centerWorld.copyFrom(this.center);\n this.radiusWorld = this.radius;\n }\n }\n /**\n * Tests if the bounding sphere is intersecting the frustum planes\n * @param frustumPlanes defines the frustum planes to test\n * @returns true if there is an intersection\n */\n isInFrustum(frustumPlanes) {\n const center = this.centerWorld;\n const radius = this.radiusWorld;\n for (let i = 0; i < 6; i++) {\n if (frustumPlanes[i].dotCoordinate(center) <= -radius) {\n return false;\n }\n }\n return true;\n }\n /**\n * Tests if the bounding sphere center is in between the frustum planes.\n * Used for optimistic fast inclusion.\n * @param frustumPlanes defines the frustum planes to test\n * @returns true if the sphere center is in between the frustum planes\n */\n isCenterInFrustum(frustumPlanes) {\n const center = this.centerWorld;\n for (let i = 0; i < 6; i++) {\n if (frustumPlanes[i].dotCoordinate(center) < 0) {\n return false;\n }\n }\n return true;\n }\n /**\n * Tests if a point is inside the bounding sphere\n * @param point defines the point to test\n * @returns true if the point is inside the bounding sphere\n */\n intersectsPoint(point) {\n const squareDistance = Vector3.DistanceSquared(this.centerWorld, point);\n if (this.radiusWorld * this.radiusWorld < squareDistance) {\n return false;\n }\n return true;\n }\n // Statics\n /**\n * Checks if two sphere intersect\n * @param sphere0 sphere 0\n * @param sphere1 sphere 1\n * @returns true if the spheres intersect\n */\n static Intersects(sphere0, sphere1) {\n const squareDistance = Vector3.DistanceSquared(sphere0.centerWorld, sphere1.centerWorld);\n const radiusSum = sphere0.radiusWorld + sphere1.radiusWorld;\n if (radiusSum * radiusSum < squareDistance) {\n return false;\n }\n return true;\n }\n /**\n * Creates a sphere from a center and a radius\n * @param center The center\n * @param radius radius\n * @param matrix Optional worldMatrix\n * @returns The sphere\n */\n static CreateFromCenterAndRadius(center, radius, matrix) {\n this._TmpVector3[0].copyFrom(center);\n this._TmpVector3[1].copyFromFloats(0, 0, radius);\n this._TmpVector3[2].copyFrom(center);\n this._TmpVector3[0].addInPlace(this._TmpVector3[1]);\n this._TmpVector3[2].subtractInPlace(this._TmpVector3[1]);\n const sphere = new BoundingSphere(this._TmpVector3[0], this._TmpVector3[2]);\n if (matrix) {\n sphere._worldMatrix = matrix;\n }\n else {\n sphere._worldMatrix = Matrix.Identity();\n }\n return sphere;\n }\n}\nBoundingSphere._TmpVector3 = ArrayTools.BuildArray(3, Vector3.Zero);\n//# sourceMappingURL=boundingSphere.js.map","/**\n * Enum for Device Types\n */\nexport var DeviceType;\n(function (DeviceType) {\n /** Generic */\n DeviceType[DeviceType[\"Generic\"] = 0] = \"Generic\";\n /** Keyboard */\n DeviceType[DeviceType[\"Keyboard\"] = 1] = \"Keyboard\";\n /** Mouse */\n DeviceType[DeviceType[\"Mouse\"] = 2] = \"Mouse\";\n /** Touch Pointers */\n DeviceType[DeviceType[\"Touch\"] = 3] = \"Touch\";\n /** PS4 Dual Shock */\n DeviceType[DeviceType[\"DualShock\"] = 4] = \"DualShock\";\n /** Xbox */\n DeviceType[DeviceType[\"Xbox\"] = 5] = \"Xbox\";\n /** Switch Controller */\n DeviceType[DeviceType[\"Switch\"] = 6] = \"Switch\";\n /** PS5 DualSense */\n DeviceType[DeviceType[\"DualSense\"] = 7] = \"DualSense\";\n})(DeviceType || (DeviceType = {}));\n// Device Enums\n/**\n * Enum for All Pointers (Touch/Mouse)\n */\nexport var PointerInput;\n(function (PointerInput) {\n /** Horizontal Axis (Not used in events/observables; only in polling) */\n PointerInput[PointerInput[\"Horizontal\"] = 0] = \"Horizontal\";\n /** Vertical Axis (Not used in events/observables; only in polling) */\n PointerInput[PointerInput[\"Vertical\"] = 1] = \"Vertical\";\n /** Left Click or Touch */\n PointerInput[PointerInput[\"LeftClick\"] = 2] = \"LeftClick\";\n /** Middle Click */\n PointerInput[PointerInput[\"MiddleClick\"] = 3] = \"MiddleClick\";\n /** Right Click */\n PointerInput[PointerInput[\"RightClick\"] = 4] = \"RightClick\";\n /** Browser Back */\n PointerInput[PointerInput[\"BrowserBack\"] = 5] = \"BrowserBack\";\n /** Browser Forward */\n PointerInput[PointerInput[\"BrowserForward\"] = 6] = \"BrowserForward\";\n /** Mouse Wheel X */\n PointerInput[PointerInput[\"MouseWheelX\"] = 7] = \"MouseWheelX\";\n /** Mouse Wheel Y */\n PointerInput[PointerInput[\"MouseWheelY\"] = 8] = \"MouseWheelY\";\n /** Mouse Wheel Z */\n PointerInput[PointerInput[\"MouseWheelZ\"] = 9] = \"MouseWheelZ\";\n /** Used in events/observables to identify if x/y changes occurred */\n PointerInput[PointerInput[\"Move\"] = 12] = \"Move\";\n})(PointerInput || (PointerInput = {}));\n/** @internal */\nexport var NativePointerInput;\n(function (NativePointerInput) {\n /** Horizontal Axis */\n NativePointerInput[NativePointerInput[\"Horizontal\"] = 0] = \"Horizontal\";\n /** Vertical Axis */\n NativePointerInput[NativePointerInput[\"Vertical\"] = 1] = \"Vertical\";\n /** Left Click or Touch */\n NativePointerInput[NativePointerInput[\"LeftClick\"] = 2] = \"LeftClick\";\n /** Middle Click */\n NativePointerInput[NativePointerInput[\"MiddleClick\"] = 3] = \"MiddleClick\";\n /** Right Click */\n NativePointerInput[NativePointerInput[\"RightClick\"] = 4] = \"RightClick\";\n /** Browser Back */\n NativePointerInput[NativePointerInput[\"BrowserBack\"] = 5] = \"BrowserBack\";\n /** Browser Forward */\n NativePointerInput[NativePointerInput[\"BrowserForward\"] = 6] = \"BrowserForward\";\n /** Mouse Wheel X */\n NativePointerInput[NativePointerInput[\"MouseWheelX\"] = 7] = \"MouseWheelX\";\n /** Mouse Wheel Y */\n NativePointerInput[NativePointerInput[\"MouseWheelY\"] = 8] = \"MouseWheelY\";\n /** Mouse Wheel Z */\n NativePointerInput[NativePointerInput[\"MouseWheelZ\"] = 9] = \"MouseWheelZ\";\n /** Delta X */\n NativePointerInput[NativePointerInput[\"DeltaHorizontal\"] = 10] = \"DeltaHorizontal\";\n /** Delta Y */\n NativePointerInput[NativePointerInput[\"DeltaVertical\"] = 11] = \"DeltaVertical\";\n})(NativePointerInput || (NativePointerInput = {}));\n/**\n * Enum for Dual Shock Gamepad\n */\nexport var DualShockInput;\n(function (DualShockInput) {\n /** Cross */\n DualShockInput[DualShockInput[\"Cross\"] = 0] = \"Cross\";\n /** Circle */\n DualShockInput[DualShockInput[\"Circle\"] = 1] = \"Circle\";\n /** Square */\n DualShockInput[DualShockInput[\"Square\"] = 2] = \"Square\";\n /** Triangle */\n DualShockInput[DualShockInput[\"Triangle\"] = 3] = \"Triangle\";\n /** L1 */\n DualShockInput[DualShockInput[\"L1\"] = 4] = \"L1\";\n /** R1 */\n DualShockInput[DualShockInput[\"R1\"] = 5] = \"R1\";\n /** L2 */\n DualShockInput[DualShockInput[\"L2\"] = 6] = \"L2\";\n /** R2 */\n DualShockInput[DualShockInput[\"R2\"] = 7] = \"R2\";\n /** Share */\n DualShockInput[DualShockInput[\"Share\"] = 8] = \"Share\";\n /** Options */\n DualShockInput[DualShockInput[\"Options\"] = 9] = \"Options\";\n /** L3 */\n DualShockInput[DualShockInput[\"L3\"] = 10] = \"L3\";\n /** R3 */\n DualShockInput[DualShockInput[\"R3\"] = 11] = \"R3\";\n /** DPadUp */\n DualShockInput[DualShockInput[\"DPadUp\"] = 12] = \"DPadUp\";\n /** DPadDown */\n DualShockInput[DualShockInput[\"DPadDown\"] = 13] = \"DPadDown\";\n /** DPadLeft */\n DualShockInput[DualShockInput[\"DPadLeft\"] = 14] = \"DPadLeft\";\n /** DRight */\n DualShockInput[DualShockInput[\"DPadRight\"] = 15] = \"DPadRight\";\n /** Home */\n DualShockInput[DualShockInput[\"Home\"] = 16] = \"Home\";\n /** TouchPad */\n DualShockInput[DualShockInput[\"TouchPad\"] = 17] = \"TouchPad\";\n /** LStickXAxis */\n DualShockInput[DualShockInput[\"LStickXAxis\"] = 18] = \"LStickXAxis\";\n /** LStickYAxis */\n DualShockInput[DualShockInput[\"LStickYAxis\"] = 19] = \"LStickYAxis\";\n /** RStickXAxis */\n DualShockInput[DualShockInput[\"RStickXAxis\"] = 20] = \"RStickXAxis\";\n /** RStickYAxis */\n DualShockInput[DualShockInput[\"RStickYAxis\"] = 21] = \"RStickYAxis\";\n})(DualShockInput || (DualShockInput = {}));\n/**\n * Enum for Dual Sense Gamepad\n */\nexport var DualSenseInput;\n(function (DualSenseInput) {\n /** Cross */\n DualSenseInput[DualSenseInput[\"Cross\"] = 0] = \"Cross\";\n /** Circle */\n DualSenseInput[DualSenseInput[\"Circle\"] = 1] = \"Circle\";\n /** Square */\n DualSenseInput[DualSenseInput[\"Square\"] = 2] = \"Square\";\n /** Triangle */\n DualSenseInput[DualSenseInput[\"Triangle\"] = 3] = \"Triangle\";\n /** L1 */\n DualSenseInput[DualSenseInput[\"L1\"] = 4] = \"L1\";\n /** R1 */\n DualSenseInput[DualSenseInput[\"R1\"] = 5] = \"R1\";\n /** L2 */\n DualSenseInput[DualSenseInput[\"L2\"] = 6] = \"L2\";\n /** R2 */\n DualSenseInput[DualSenseInput[\"R2\"] = 7] = \"R2\";\n /** Create */\n DualSenseInput[DualSenseInput[\"Create\"] = 8] = \"Create\";\n /** Options */\n DualSenseInput[DualSenseInput[\"Options\"] = 9] = \"Options\";\n /** L3 */\n DualSenseInput[DualSenseInput[\"L3\"] = 10] = \"L3\";\n /** R3 */\n DualSenseInput[DualSenseInput[\"R3\"] = 11] = \"R3\";\n /** DPadUp */\n DualSenseInput[DualSenseInput[\"DPadUp\"] = 12] = \"DPadUp\";\n /** DPadDown */\n DualSenseInput[DualSenseInput[\"DPadDown\"] = 13] = \"DPadDown\";\n /** DPadLeft */\n DualSenseInput[DualSenseInput[\"DPadLeft\"] = 14] = \"DPadLeft\";\n /** DRight */\n DualSenseInput[DualSenseInput[\"DPadRight\"] = 15] = \"DPadRight\";\n /** Home */\n DualSenseInput[DualSenseInput[\"Home\"] = 16] = \"Home\";\n /** TouchPad */\n DualSenseInput[DualSenseInput[\"TouchPad\"] = 17] = \"TouchPad\";\n /** LStickXAxis */\n DualSenseInput[DualSenseInput[\"LStickXAxis\"] = 18] = \"LStickXAxis\";\n /** LStickYAxis */\n DualSenseInput[DualSenseInput[\"LStickYAxis\"] = 19] = \"LStickYAxis\";\n /** RStickXAxis */\n DualSenseInput[DualSenseInput[\"RStickXAxis\"] = 20] = \"RStickXAxis\";\n /** RStickYAxis */\n DualSenseInput[DualSenseInput[\"RStickYAxis\"] = 21] = \"RStickYAxis\";\n})(DualSenseInput || (DualSenseInput = {}));\n/**\n * Enum for Xbox Gamepad\n */\nexport var XboxInput;\n(function (XboxInput) {\n /** A */\n XboxInput[XboxInput[\"A\"] = 0] = \"A\";\n /** B */\n XboxInput[XboxInput[\"B\"] = 1] = \"B\";\n /** X */\n XboxInput[XboxInput[\"X\"] = 2] = \"X\";\n /** Y */\n XboxInput[XboxInput[\"Y\"] = 3] = \"Y\";\n /** LB */\n XboxInput[XboxInput[\"LB\"] = 4] = \"LB\";\n /** RB */\n XboxInput[XboxInput[\"RB\"] = 5] = \"RB\";\n /** LT */\n XboxInput[XboxInput[\"LT\"] = 6] = \"LT\";\n /** RT */\n XboxInput[XboxInput[\"RT\"] = 7] = \"RT\";\n /** Back */\n XboxInput[XboxInput[\"Back\"] = 8] = \"Back\";\n /** Start */\n XboxInput[XboxInput[\"Start\"] = 9] = \"Start\";\n /** LS */\n XboxInput[XboxInput[\"LS\"] = 10] = \"LS\";\n /** RS */\n XboxInput[XboxInput[\"RS\"] = 11] = \"RS\";\n /** DPadUp */\n XboxInput[XboxInput[\"DPadUp\"] = 12] = \"DPadUp\";\n /** DPadDown */\n XboxInput[XboxInput[\"DPadDown\"] = 13] = \"DPadDown\";\n /** DPadLeft */\n XboxInput[XboxInput[\"DPadLeft\"] = 14] = \"DPadLeft\";\n /** DRight */\n XboxInput[XboxInput[\"DPadRight\"] = 15] = \"DPadRight\";\n /** Home */\n XboxInput[XboxInput[\"Home\"] = 16] = \"Home\";\n /** LStickXAxis */\n XboxInput[XboxInput[\"LStickXAxis\"] = 17] = \"LStickXAxis\";\n /** LStickYAxis */\n XboxInput[XboxInput[\"LStickYAxis\"] = 18] = \"LStickYAxis\";\n /** RStickXAxis */\n XboxInput[XboxInput[\"RStickXAxis\"] = 19] = \"RStickXAxis\";\n /** RStickYAxis */\n XboxInput[XboxInput[\"RStickYAxis\"] = 20] = \"RStickYAxis\";\n})(XboxInput || (XboxInput = {}));\n/**\n * Enum for Switch (Pro/JoyCon L+R) Gamepad\n */\nexport var SwitchInput;\n(function (SwitchInput) {\n /** B */\n SwitchInput[SwitchInput[\"B\"] = 0] = \"B\";\n /** A */\n SwitchInput[SwitchInput[\"A\"] = 1] = \"A\";\n /** Y */\n SwitchInput[SwitchInput[\"Y\"] = 2] = \"Y\";\n /** X */\n SwitchInput[SwitchInput[\"X\"] = 3] = \"X\";\n /** L */\n SwitchInput[SwitchInput[\"L\"] = 4] = \"L\";\n /** R */\n SwitchInput[SwitchInput[\"R\"] = 5] = \"R\";\n /** ZL */\n SwitchInput[SwitchInput[\"ZL\"] = 6] = \"ZL\";\n /** ZR */\n SwitchInput[SwitchInput[\"ZR\"] = 7] = \"ZR\";\n /** Minus */\n SwitchInput[SwitchInput[\"Minus\"] = 8] = \"Minus\";\n /** Plus */\n SwitchInput[SwitchInput[\"Plus\"] = 9] = \"Plus\";\n /** LS */\n SwitchInput[SwitchInput[\"LS\"] = 10] = \"LS\";\n /** RS */\n SwitchInput[SwitchInput[\"RS\"] = 11] = \"RS\";\n /** DPadUp */\n SwitchInput[SwitchInput[\"DPadUp\"] = 12] = \"DPadUp\";\n /** DPadDown */\n SwitchInput[SwitchInput[\"DPadDown\"] = 13] = \"DPadDown\";\n /** DPadLeft */\n SwitchInput[SwitchInput[\"DPadLeft\"] = 14] = \"DPadLeft\";\n /** DRight */\n SwitchInput[SwitchInput[\"DPadRight\"] = 15] = \"DPadRight\";\n /** Home */\n SwitchInput[SwitchInput[\"Home\"] = 16] = \"Home\";\n /** Capture */\n SwitchInput[SwitchInput[\"Capture\"] = 17] = \"Capture\";\n /** LStickXAxis */\n SwitchInput[SwitchInput[\"LStickXAxis\"] = 18] = \"LStickXAxis\";\n /** LStickYAxis */\n SwitchInput[SwitchInput[\"LStickYAxis\"] = 19] = \"LStickYAxis\";\n /** RStickXAxis */\n SwitchInput[SwitchInput[\"RStickXAxis\"] = 20] = \"RStickXAxis\";\n /** RStickYAxis */\n SwitchInput[SwitchInput[\"RStickYAxis\"] = 21] = \"RStickYAxis\";\n})(SwitchInput || (SwitchInput = {}));\n//# sourceMappingURL=deviceEnums.js.map","import { Observable } from \"../../Misc/observable.js\";\n/**\n * Class that handles all input for a specific device\n */\nexport class DeviceSource {\n /**\n * Default Constructor\n * @param deviceInputSystem - Reference to DeviceInputSystem\n * @param deviceType - Type of device\n * @param deviceSlot - \"Slot\" or index that device is referenced in\n */\n constructor(deviceInputSystem, \n /** Type of device */\n deviceType, \n /** \"Slot\" or index that device is referenced in */\n deviceSlot = 0) {\n this.deviceType = deviceType;\n this.deviceSlot = deviceSlot;\n // Public Members\n /**\n * Observable to handle device input changes per device\n */\n this.onInputChangedObservable = new Observable();\n this._deviceInputSystem = deviceInputSystem;\n }\n /**\n * Get input for specific input\n * @param inputIndex - index of specific input on device\n * @returns Input value from DeviceInputSystem\n */\n getInput(inputIndex) {\n return this._deviceInputSystem.pollInput(this.deviceType, this.deviceSlot, inputIndex);\n }\n}\n//# sourceMappingURL=deviceSource.js.map","\nimport { EventConstants } from \"../Events/deviceInputEvents.js\";\nimport { DeviceType, NativePointerInput, PointerInput } from \"./InputDevices/deviceEnums.js\";\n/**\n * Class to wrap DeviceInputSystem data into an event object\n */\nexport class DeviceEventFactory {\n /**\n * Create device input events based on provided type and slot\n *\n * @param deviceType Type of device\n * @param deviceSlot \"Slot\" or index that device is referenced in\n * @param inputIndex Id of input to be checked\n * @param currentState Current value for given input\n * @param deviceInputSystem Reference to DeviceInputSystem\n * @param elementToAttachTo HTMLElement to reference as target for inputs\n * @returns IUIEvent object\n */\n static CreateDeviceEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo, pointerId) {\n switch (deviceType) {\n case DeviceType.Keyboard:\n return this._CreateKeyboardEvent(inputIndex, currentState, deviceInputSystem, elementToAttachTo);\n case DeviceType.Mouse:\n if (inputIndex === PointerInput.MouseWheelX || inputIndex === PointerInput.MouseWheelY || inputIndex === PointerInput.MouseWheelZ) {\n return this._CreateWheelEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo);\n }\n // eslint-disable-next-line no-fallthrough\n case DeviceType.Touch:\n return this._CreatePointerEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo, pointerId);\n default:\n throw `Unable to generate event for device ${DeviceType[deviceType]}`;\n }\n }\n /**\n * Creates pointer event\n *\n * @param deviceType Type of device\n * @param deviceSlot \"Slot\" or index that device is referenced in\n * @param inputIndex Id of input to be checked\n * @param currentState Current value for given input\n * @param deviceInputSystem Reference to DeviceInputSystem\n * @param elementToAttachTo HTMLElement to reference as target for inputs\n * @returns IUIEvent object (Pointer)\n */\n static _CreatePointerEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo, pointerId) {\n const evt = this._CreateMouseEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo);\n if (deviceType === DeviceType.Mouse) {\n evt.deviceType = DeviceType.Mouse;\n evt.pointerId = 1;\n evt.pointerType = \"mouse\";\n }\n else {\n evt.deviceType = DeviceType.Touch;\n evt.pointerId = pointerId !== null && pointerId !== void 0 ? pointerId : deviceSlot;\n evt.pointerType = \"touch\";\n }\n if (inputIndex === PointerInput.Move) {\n evt.type = \"pointermove\";\n }\n else if (inputIndex >= PointerInput.LeftClick && inputIndex <= PointerInput.RightClick) {\n evt.type = currentState === 1 ? \"pointerdown\" : \"pointerup\";\n evt.button = inputIndex - 2;\n }\n return evt;\n }\n /**\n * Create Mouse Wheel Event\n * @param deviceType Type of device\n * @param deviceSlot \"Slot\" or index that device is referenced in\n * @param inputIndex Id of input to be checked\n * @param currentState Current value for given input\n * @param deviceInputSystem Reference to DeviceInputSystem\n * @param elementToAttachTo HTMLElement to reference as target for inputs\n * @returns IUIEvent object (Wheel)\n */\n static _CreateWheelEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo) {\n const evt = this._CreateMouseEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo);\n // While WheelEvents don't generally have a pointerId, we used to add one in the InputManager\n // This line has been added to make the InputManager more platform-agnostic\n // Similar code exists in the WebDeviceInputSystem to handle browser created events\n evt.pointerId = 1;\n evt.type = \"wheel\";\n evt.deltaMode = EventConstants.DOM_DELTA_PIXEL;\n evt.deltaX = 0;\n evt.deltaY = 0;\n evt.deltaZ = 0;\n switch (inputIndex) {\n case PointerInput.MouseWheelX:\n evt.deltaX = currentState;\n break;\n case PointerInput.MouseWheelY:\n evt.deltaY = currentState;\n break;\n case PointerInput.MouseWheelZ:\n evt.deltaZ = currentState;\n break;\n }\n return evt;\n }\n /**\n * Create Mouse Event\n * @param deviceType Type of device\n * @param deviceSlot \"Slot\" or index that device is referenced in\n * @param inputIndex Id of input to be checked\n * @param currentState Current value for given input\n * @param deviceInputSystem Reference to DeviceInputSystem\n * @param elementToAttachTo HTMLElement to reference as target for inputs\n * @returns IUIEvent object (Mouse)\n */\n static _CreateMouseEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo) {\n const evt = this._CreateEvent(elementToAttachTo);\n const pointerX = deviceInputSystem.pollInput(deviceType, deviceSlot, PointerInput.Horizontal);\n const pointerY = deviceInputSystem.pollInput(deviceType, deviceSlot, PointerInput.Vertical);\n // Handle offsets/deltas based on existence of HTMLElement\n if (elementToAttachTo) {\n evt.movementX = 0;\n evt.movementY = 0;\n evt.offsetX = evt.movementX - elementToAttachTo.getBoundingClientRect().x;\n evt.offsetY = evt.movementY - elementToAttachTo.getBoundingClientRect().y;\n }\n else {\n evt.movementX = deviceInputSystem.pollInput(deviceType, deviceSlot, NativePointerInput.DeltaHorizontal); // DeltaHorizontal\n evt.movementY = deviceInputSystem.pollInput(deviceType, deviceSlot, NativePointerInput.DeltaVertical); // DeltaVertical\n evt.offsetX = 0;\n evt.offsetY = 0;\n }\n this._CheckNonCharacterKeys(evt, deviceInputSystem);\n evt.clientX = pointerX;\n evt.clientY = pointerY;\n evt.x = pointerX;\n evt.y = pointerY;\n evt.deviceType = deviceType;\n evt.deviceSlot = deviceSlot;\n evt.inputIndex = inputIndex;\n return evt;\n }\n /**\n * Create Keyboard Event\n * @param inputIndex Id of input to be checked\n * @param currentState Current value for given input\n * @param deviceInputSystem Reference to DeviceInputSystem\n * @param elementToAttachTo HTMLElement to reference as target for inputs\n * @returns IEvent object (Keyboard)\n */\n static _CreateKeyboardEvent(inputIndex, currentState, deviceInputSystem, elementToAttachTo) {\n const evt = this._CreateEvent(elementToAttachTo);\n this._CheckNonCharacterKeys(evt, deviceInputSystem);\n evt.deviceType = DeviceType.Keyboard;\n evt.deviceSlot = 0;\n evt.inputIndex = inputIndex;\n evt.type = currentState === 1 ? \"keydown\" : \"keyup\";\n evt.key = String.fromCharCode(inputIndex);\n evt.keyCode = inputIndex;\n return evt;\n }\n /**\n * Add parameters for non-character keys (Ctrl, Alt, Meta, Shift)\n * @param evt Event object to add parameters to\n * @param deviceInputSystem DeviceInputSystem to pull values from\n */\n static _CheckNonCharacterKeys(evt, deviceInputSystem) {\n const isKeyboardActive = deviceInputSystem.isDeviceAvailable(DeviceType.Keyboard);\n const altKey = isKeyboardActive && deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 18) === 1;\n const ctrlKey = isKeyboardActive && deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 17) === 1;\n const metaKey = isKeyboardActive &&\n (deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 91) === 1 ||\n deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 92) === 1 ||\n deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 93) === 1);\n const shiftKey = isKeyboardActive && deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 16) === 1;\n evt.altKey = altKey;\n evt.ctrlKey = ctrlKey;\n evt.metaKey = metaKey;\n evt.shiftKey = shiftKey;\n }\n /**\n * Create base event object\n * @param elementToAttachTo Value to use as event target\n * @returns\n */\n static _CreateEvent(elementToAttachTo) {\n const evt = {};\n evt.preventDefault = () => { };\n evt.target = elementToAttachTo;\n return evt;\n }\n}\n//# sourceMappingURL=eventFactory.js.map","import { DeviceEventFactory } from \"./eventFactory.js\";\nimport { DeviceType } from \"./InputDevices/deviceEnums.js\";\n/** @internal */\nexport class NativeDeviceInputSystem {\n constructor(onDeviceConnected, onDeviceDisconnected, onInputChanged) {\n this._nativeInput = _native.DeviceInputSystem\n ? new _native.DeviceInputSystem(onDeviceConnected, onDeviceDisconnected, (deviceType, deviceSlot, inputIndex, currentState) => {\n const evt = DeviceEventFactory.CreateDeviceEvent(deviceType, deviceSlot, inputIndex, currentState, this);\n onInputChanged(deviceType, deviceSlot, evt);\n })\n : this._createDummyNativeInput();\n }\n // Public functions\n /**\n * Checks for current device input value, given an id and input index. Throws exception if requested device not initialized.\n * @param deviceType Enum specifying device type\n * @param deviceSlot \"Slot\" or index that device is referenced in\n * @param inputIndex Id of input to be checked\n * @returns Current value of input\n */\n pollInput(deviceType, deviceSlot, inputIndex) {\n return this._nativeInput.pollInput(deviceType, deviceSlot, inputIndex);\n }\n /**\n * Check for a specific device in the DeviceInputSystem\n * @param deviceType Type of device to check for\n * @returns bool with status of device's existence\n */\n isDeviceAvailable(deviceType) {\n //TODO: FIx native side first\n return deviceType === DeviceType.Mouse || deviceType === DeviceType.Touch;\n }\n /**\n * Dispose of all the observables\n */\n dispose() {\n this._nativeInput.dispose();\n }\n /**\n * For versions of BabylonNative that don't have the NativeInput plugin initialized, create a dummy version\n * @returns Object with dummy functions\n */\n _createDummyNativeInput() {\n const nativeInput = {\n pollInput: () => {\n return 0;\n },\n isDeviceAvailable: () => {\n return false;\n },\n dispose: () => { },\n };\n return nativeInput;\n }\n}\n//# sourceMappingURL=nativeDeviceInputSystem.js.map","import { DomManagement, IsNavigatorAvailable } from \"../Misc/domManagement.js\";\nimport { Tools } from \"../Misc/tools.js\";\nimport { DeviceEventFactory } from \"./eventFactory.js\";\nimport { DeviceType, PointerInput } from \"./InputDevices/deviceEnums.js\";\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst MAX_KEYCODES = 255;\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst MAX_POINTER_INPUTS = Object.keys(PointerInput).length / 2;\n/** @internal */\nexport class WebDeviceInputSystem {\n constructor(engine, onDeviceConnected, onDeviceDisconnected, onInputChanged) {\n // Private Members\n this._inputs = [];\n this._keyboardActive = false;\n this._pointerActive = false;\n this._usingSafari = Tools.IsSafari();\n // Found solution for determining if MacOS is being used here:\n // https://stackoverflow.com/questions/10527983/best-way-to-detect-mac-os-x-or-windows-computers-with-javascript-or-jquery\n this._usingMacOS = IsNavigatorAvailable() && /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this._keyboardDownEvent = (evt) => { };\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this._keyboardUpEvent = (evt) => { };\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this._keyboardBlurEvent = (evt) => { };\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this._pointerMoveEvent = (evt) => { };\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this._pointerDownEvent = (evt) => { };\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this._pointerUpEvent = (evt) => { };\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this._pointerCancelEvent = (evt) => { };\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this._pointerWheelEvent = (evt) => { };\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this._pointerBlurEvent = (evt) => { };\n this._eventsAttached = false;\n this._mouseId = -1;\n this._isUsingFirefox = DomManagement.IsNavigatorAvailable() && navigator.userAgent && navigator.userAgent.indexOf(\"Firefox\") !== -1;\n this._maxTouchPoints = 0;\n this._pointerInputClearObserver = null;\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this._gamepadConnectedEvent = (evt) => { };\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n this._gamepadDisconnectedEvent = (evt) => { };\n this._eventPrefix = Tools.GetPointerPrefix(engine);\n this._engine = engine;\n this._onDeviceConnected = onDeviceConnected;\n this._onDeviceDisconnected = onDeviceDisconnected;\n this._onInputChanged = onInputChanged;\n // If we need a pointerId, set one for future use\n this._mouseId = this._isUsingFirefox ? 0 : 1;\n this._enableEvents();\n if (this._usingMacOS) {\n this._metaKeys = [];\n }\n // Set callback to enable event handler switching when inputElement changes\n if (!this._engine._onEngineViewChanged) {\n this._engine._onEngineViewChanged = () => {\n this._enableEvents();\n };\n }\n }\n // Public functions\n /**\n * Checks for current device input value, given an id and input index. Throws exception if requested device not initialized.\n * @param deviceType Enum specifying device type\n * @param deviceSlot \"Slot\" or index that device is referenced in\n * @param inputIndex Id of input to be checked\n * @returns Current value of input\n */\n pollInput(deviceType, deviceSlot, inputIndex) {\n const device = this._inputs[deviceType][deviceSlot];\n if (!device) {\n throw `Unable to find device ${DeviceType[deviceType]}`;\n }\n if (deviceType >= DeviceType.DualShock && deviceType <= DeviceType.DualSense) {\n this._updateDevice(deviceType, deviceSlot, inputIndex);\n }\n const currentValue = device[inputIndex];\n if (currentValue === undefined) {\n throw `Unable to find input ${inputIndex} for device ${DeviceType[deviceType]} in slot ${deviceSlot}`;\n }\n if (inputIndex === PointerInput.Move) {\n Tools.Warn(`Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data.`);\n }\n return currentValue;\n }\n /**\n * Check for a specific device in the DeviceInputSystem\n * @param deviceType Type of device to check for\n * @returns bool with status of device's existence\n */\n isDeviceAvailable(deviceType) {\n return this._inputs[deviceType] !== undefined;\n }\n /**\n * Dispose of all the eventlisteners\n */\n dispose() {\n // Callbacks\n this._onDeviceConnected = () => { };\n this._onDeviceDisconnected = () => { };\n this._onInputChanged = () => { };\n delete this._engine._onEngineViewChanged;\n if (this._elementToAttachTo) {\n this._disableEvents();\n }\n }\n /**\n * Enable listening for user input events\n */\n _enableEvents() {\n const inputElement = this === null || this === void 0 ? void 0 : this._engine.getInputElement();\n if (inputElement && (!this._eventsAttached || this._elementToAttachTo !== inputElement)) {\n // Remove events before adding to avoid double events or simultaneous events on multiple canvases\n this._disableEvents();\n // If the inputs array has already been created, zero it out to before setting up events\n if (this._inputs) {\n for (const inputs of this._inputs) {\n if (inputs) {\n for (const deviceSlotKey in inputs) {\n const deviceSlot = +deviceSlotKey;\n const device = inputs[deviceSlot];\n if (device) {\n for (let inputIndex = 0; inputIndex < device.length; inputIndex++) {\n device[inputIndex] = 0;\n }\n }\n }\n }\n }\n }\n this._elementToAttachTo = inputElement;\n // Set tab index for the inputElement to the engine's canvasTabIndex, if and only if the element's tab index is -1\n this._elementToAttachTo.tabIndex = this._elementToAttachTo.tabIndex !== -1 ? this._elementToAttachTo.tabIndex : this._engine.canvasTabIndex;\n this._handleKeyActions();\n this._handlePointerActions();\n this._handleGamepadActions();\n this._eventsAttached = true;\n // Check for devices that are already connected but aren't registered. Currently, only checks for gamepads and mouse\n this._checkForConnectedDevices();\n }\n }\n /**\n * Disable listening for user input events\n */\n _disableEvents() {\n if (this._elementToAttachTo) {\n // Blur Events\n this._elementToAttachTo.removeEventListener(\"blur\", this._keyboardBlurEvent);\n this._elementToAttachTo.removeEventListener(\"blur\", this._pointerBlurEvent);\n // Keyboard Events\n this._elementToAttachTo.removeEventListener(\"keydown\", this._keyboardDownEvent);\n this._elementToAttachTo.removeEventListener(\"keyup\", this._keyboardUpEvent);\n // Pointer Events\n this._elementToAttachTo.removeEventListener(this._eventPrefix + \"move\", this._pointerMoveEvent);\n this._elementToAttachTo.removeEventListener(this._eventPrefix + \"down\", this._pointerDownEvent);\n this._elementToAttachTo.removeEventListener(this._eventPrefix + \"up\", this._pointerUpEvent);\n this._elementToAttachTo.removeEventListener(this._eventPrefix + \"cancel\", this._pointerCancelEvent);\n this._elementToAttachTo.removeEventListener(this._wheelEventName, this._pointerWheelEvent);\n // Gamepad Events\n window.removeEventListener(\"gamepadconnected\", this._gamepadConnectedEvent);\n window.removeEventListener(\"gamepaddisconnected\", this._gamepadDisconnectedEvent);\n }\n if (this._pointerInputClearObserver) {\n this._engine.onEndFrameObservable.remove(this._pointerInputClearObserver);\n }\n this._eventsAttached = false;\n }\n /**\n * Checks for existing connections to devices and register them, if necessary\n * Currently handles gamepads and mouse\n */\n _checkForConnectedDevices() {\n if (navigator.getGamepads) {\n const gamepads = navigator.getGamepads();\n for (const gamepad of gamepads) {\n if (gamepad) {\n this._addGamePad(gamepad);\n }\n }\n }\n // If the device in use has mouse capabilities, pre-register mouse\n if (typeof matchMedia === \"function\" && matchMedia(\"(pointer:fine)\").matches) {\n // This will provide a dummy value for the cursor position and is expected to be overridden when the first mouse event happens.\n // There isn't any good way to get the current position outside of a pointer event so that's why this was done.\n this._addPointerDevice(DeviceType.Mouse, 0, 0, 0);\n }\n }\n // Private functions\n /**\n * Add a gamepad to the DeviceInputSystem\n * @param gamepad A single DOM Gamepad object\n */\n _addGamePad(gamepad) {\n const deviceType = this._getGamepadDeviceType(gamepad.id);\n const deviceSlot = gamepad.index;\n this._gamepads = this._gamepads || new Array(gamepad.index + 1);\n this._registerDevice(deviceType, deviceSlot, gamepad.buttons.length + gamepad.axes.length);\n this._gamepads[deviceSlot] = deviceType;\n }\n /**\n * Add pointer device to DeviceInputSystem\n * @param deviceType Type of Pointer to add\n * @param deviceSlot Pointer ID (0 for mouse, pointerId for Touch)\n * @param currentX Current X at point of adding\n * @param currentY Current Y at point of adding\n */\n _addPointerDevice(deviceType, deviceSlot, currentX, currentY) {\n if (!this._pointerActive) {\n this._pointerActive = true;\n }\n this._registerDevice(deviceType, deviceSlot, MAX_POINTER_INPUTS);\n const pointer = this._inputs[deviceType][deviceSlot]; /* initialize our pointer position immediately after registration */\n pointer[0] = currentX;\n pointer[1] = currentY;\n }\n /**\n * Add device and inputs to device array\n * @param deviceType Enum specifying device type\n * @param deviceSlot \"Slot\" or index that device is referenced in\n * @param numberOfInputs Number of input entries to create for given device\n */\n _registerDevice(deviceType, deviceSlot, numberOfInputs) {\n if (deviceSlot === undefined) {\n throw `Unable to register device ${DeviceType[deviceType]} to undefined slot.`;\n }\n if (!this._inputs[deviceType]) {\n this._inputs[deviceType] = {};\n }\n if (!this._inputs[deviceType][deviceSlot]) {\n const device = new Array(numberOfInputs);\n device.fill(0);\n this._inputs[deviceType][deviceSlot] = device;\n this._onDeviceConnected(deviceType, deviceSlot);\n }\n }\n /**\n * Given a specific device name, remove that device from the device map\n * @param deviceType Enum specifying device type\n * @param deviceSlot \"Slot\" or index that device is referenced in\n */\n _unregisterDevice(deviceType, deviceSlot) {\n if (this._inputs[deviceType][deviceSlot]) {\n delete this._inputs[deviceType][deviceSlot];\n this._onDeviceDisconnected(deviceType, deviceSlot);\n }\n }\n /**\n * Handle all actions that come from keyboard interaction\n */\n _handleKeyActions() {\n this._keyboardDownEvent = (evt) => {\n if (!this._keyboardActive) {\n this._keyboardActive = true;\n this._registerDevice(DeviceType.Keyboard, 0, MAX_KEYCODES);\n }\n const kbKey = this._inputs[DeviceType.Keyboard][0];\n if (kbKey) {\n kbKey[evt.keyCode] = 1;\n const deviceEvent = evt;\n deviceEvent.inputIndex = evt.keyCode;\n if (this._usingMacOS && evt.metaKey && evt.key !== \"Meta\") {\n if (!this._metaKeys.includes(evt.keyCode)) {\n this._metaKeys.push(evt.keyCode);\n }\n }\n this._onInputChanged(DeviceType.Keyboard, 0, deviceEvent);\n }\n };\n this._keyboardUpEvent = (evt) => {\n if (!this._keyboardActive) {\n this._keyboardActive = true;\n this._registerDevice(DeviceType.Keyboard, 0, MAX_KEYCODES);\n }\n const kbKey = this._inputs[DeviceType.Keyboard][0];\n if (kbKey) {\n kbKey[evt.keyCode] = 0;\n const deviceEvent = evt;\n deviceEvent.inputIndex = evt.keyCode;\n if (this._usingMacOS && evt.key === \"Meta\" && this._metaKeys.length > 0) {\n for (const keyCode of this._metaKeys) {\n const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Keyboard, 0, keyCode, 0, this, this._elementToAttachTo);\n kbKey[keyCode] = 0;\n this._onInputChanged(DeviceType.Keyboard, 0, deviceEvent);\n }\n this._metaKeys.splice(0, this._metaKeys.length);\n }\n this._onInputChanged(DeviceType.Keyboard, 0, deviceEvent);\n }\n };\n this._keyboardBlurEvent = () => {\n if (this._keyboardActive) {\n const kbKey = this._inputs[DeviceType.Keyboard][0];\n for (let i = 0; i < kbKey.length; i++) {\n if (kbKey[i] !== 0) {\n kbKey[i] = 0;\n const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Keyboard, 0, i, 0, this, this._elementToAttachTo);\n this._onInputChanged(DeviceType.Keyboard, 0, deviceEvent);\n }\n }\n if (this._usingMacOS) {\n this._metaKeys.splice(0, this._metaKeys.length);\n }\n }\n };\n this._elementToAttachTo.addEventListener(\"keydown\", this._keyboardDownEvent);\n this._elementToAttachTo.addEventListener(\"keyup\", this._keyboardUpEvent);\n this._elementToAttachTo.addEventListener(\"blur\", this._keyboardBlurEvent);\n }\n /**\n * Handle all actions that come from pointer interaction\n */\n _handlePointerActions() {\n // If maxTouchPoints is defined, use that value. Otherwise, allow for a minimum for supported gestures like pinch\n this._maxTouchPoints = (DomManagement.IsNavigatorAvailable() && navigator.maxTouchPoints) || 2;\n if (!this._activeTouchIds) {\n this._activeTouchIds = new Array(this._maxTouchPoints);\n }\n for (let i = 0; i < this._maxTouchPoints; i++) {\n this._activeTouchIds[i] = -1;\n }\n this._pointerMoveEvent = (evt) => {\n const deviceType = this._getPointerType(evt);\n const deviceSlot = deviceType === DeviceType.Mouse ? 0 : this._activeTouchIds.indexOf(evt.pointerId);\n if (!this._inputs[deviceType]) {\n this._inputs[deviceType] = {};\n }\n if (!this._inputs[deviceType][deviceSlot]) {\n this._addPointerDevice(deviceType, deviceSlot, evt.clientX, evt.clientY);\n }\n const pointer = this._inputs[deviceType][deviceSlot];\n if (pointer) {\n const deviceEvent = evt;\n deviceEvent.inputIndex = PointerInput.Move;\n pointer[PointerInput.Horizontal] = evt.clientX;\n pointer[PointerInput.Vertical] = evt.clientY;\n if (evt.pointerId === undefined) {\n evt.pointerId = this._mouseId;\n }\n this._onInputChanged(deviceType, deviceSlot, deviceEvent);\n // Lets Propagate the event for move with same position.\n if (!this._usingSafari && evt.button !== -1) {\n deviceEvent.inputIndex = evt.button + 2;\n pointer[evt.button + 2] = pointer[evt.button + 2] ? 0 : 1; // Reverse state of button if evt.button has value\n this._onInputChanged(deviceType, deviceSlot, deviceEvent);\n }\n }\n };\n this._pointerDownEvent = (evt) => {\n const deviceType = this._getPointerType(evt);\n let deviceSlot = deviceType === DeviceType.Mouse ? 0 : evt.pointerId;\n if (deviceType === DeviceType.Touch) {\n const idx = this._activeTouchIds.indexOf(-1);\n if (idx >= 0) {\n deviceSlot = idx;\n this._activeTouchIds[idx] = evt.pointerId;\n }\n else {\n // We can't find an open slot to store new pointer so just return (can only support max number of touches)\n Tools.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);\n return;\n }\n }\n if (!this._inputs[deviceType]) {\n this._inputs[deviceType] = {};\n }\n if (!this._inputs[deviceType][deviceSlot]) {\n this._addPointerDevice(deviceType, deviceSlot, evt.clientX, evt.clientY);\n }\n else if (deviceType === DeviceType.Touch) {\n this._onDeviceConnected(deviceType, deviceSlot);\n }\n const pointer = this._inputs[deviceType][deviceSlot];\n if (pointer) {\n const previousHorizontal = pointer[PointerInput.Horizontal];\n const previousVertical = pointer[PointerInput.Vertical];\n if (deviceType === DeviceType.Mouse) {\n // Mouse; Set pointerId if undefined\n if (evt.pointerId === undefined) {\n evt.pointerId = this._mouseId;\n }\n if (!document.pointerLockElement) {\n try {\n this._elementToAttachTo.setPointerCapture(this._mouseId);\n }\n catch (e) {\n // DO NOTHING\n }\n }\n }\n else {\n // Touch; Since touches are dynamically assigned, only set capture if we have an id\n if (evt.pointerId && !document.pointerLockElement) {\n try {\n this._elementToAttachTo.setPointerCapture(evt.pointerId);\n }\n catch (e) {\n // DO NOTHING\n }\n }\n }\n pointer[PointerInput.Horizontal] = evt.clientX;\n pointer[PointerInput.Vertical] = evt.clientY;\n pointer[evt.button + 2] = 1;\n const deviceEvent = evt;\n // NOTE: The +2 used here to is because PointerInput has the same value progression for its mouse buttons as PointerEvent.button\n // However, we have our X and Y values front-loaded to group together the touch inputs but not break this progression\n // EG. ([X, Y, Left-click], Middle-click, etc...)\n deviceEvent.inputIndex = evt.button + 2;\n this._onInputChanged(deviceType, deviceSlot, deviceEvent);\n if (previousHorizontal !== evt.clientX || previousVertical !== evt.clientY) {\n deviceEvent.inputIndex = PointerInput.Move;\n this._onInputChanged(deviceType, deviceSlot, deviceEvent);\n }\n }\n };\n this._pointerUpEvent = (evt) => {\n var _a, _b, _c, _d, _e;\n const deviceType = this._getPointerType(evt);\n const deviceSlot = deviceType === DeviceType.Mouse ? 0 : this._activeTouchIds.indexOf(evt.pointerId);\n if (deviceType === DeviceType.Touch) {\n if (deviceSlot === -1) {\n return;\n }\n else {\n this._activeTouchIds[deviceSlot] = -1;\n }\n }\n const pointer = (_a = this._inputs[deviceType]) === null || _a === void 0 ? void 0 : _a[deviceSlot];\n if (pointer && pointer[evt.button + 2] !== 0) {\n const previousHorizontal = pointer[PointerInput.Horizontal];\n const previousVertical = pointer[PointerInput.Vertical];\n pointer[PointerInput.Horizontal] = evt.clientX;\n pointer[PointerInput.Vertical] = evt.clientY;\n pointer[evt.button + 2] = 0;\n const deviceEvent = evt;\n if (evt.pointerId === undefined) {\n evt.pointerId = this._mouseId;\n }\n if (previousHorizontal !== evt.clientX || previousVertical !== evt.clientY) {\n deviceEvent.inputIndex = PointerInput.Move;\n this._onInputChanged(deviceType, deviceSlot, deviceEvent);\n }\n // NOTE: The +2 used here to is because PointerInput has the same value progression for its mouse buttons as PointerEvent.button\n // However, we have our X and Y values front-loaded to group together the touch inputs but not break this progression\n // EG. ([X, Y, Left-click], Middle-click, etc...)\n deviceEvent.inputIndex = evt.button + 2;\n if (deviceType === DeviceType.Mouse && this._mouseId >= 0 && ((_c = (_b = this._elementToAttachTo).hasPointerCapture) === null || _c === void 0 ? void 0 : _c.call(_b, this._mouseId))) {\n this._elementToAttachTo.releasePointerCapture(this._mouseId);\n }\n else if (evt.pointerId && ((_e = (_d = this._elementToAttachTo).hasPointerCapture) === null || _e === void 0 ? void 0 : _e.call(_d, evt.pointerId))) {\n this._elementToAttachTo.releasePointerCapture(evt.pointerId);\n }\n this._onInputChanged(deviceType, deviceSlot, deviceEvent);\n if (deviceType === DeviceType.Touch) {\n this._onDeviceDisconnected(deviceType, deviceSlot);\n }\n }\n };\n this._pointerCancelEvent = (evt) => {\n var _a, _b, _c, _d;\n if (evt.pointerType === \"mouse\") {\n const pointer = this._inputs[DeviceType.Mouse][0];\n if (this._mouseId >= 0 && ((_b = (_a = this._elementToAttachTo).hasPointerCapture) === null || _b === void 0 ? void 0 : _b.call(_a, this._mouseId))) {\n this._elementToAttachTo.releasePointerCapture(this._mouseId);\n }\n for (let inputIndex = PointerInput.LeftClick; inputIndex <= PointerInput.BrowserForward; inputIndex++) {\n if (pointer[inputIndex] === 1) {\n pointer[inputIndex] = 0;\n const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Mouse, 0, inputIndex, 0, this, this._elementToAttachTo);\n this._onInputChanged(DeviceType.Mouse, 0, deviceEvent);\n }\n }\n }\n else {\n const deviceSlot = this._activeTouchIds.indexOf(evt.pointerId);\n if ((_d = (_c = this._elementToAttachTo).hasPointerCapture) === null || _d === void 0 ? void 0 : _d.call(_c, evt.pointerId)) {\n this._elementToAttachTo.releasePointerCapture(evt.pointerId);\n }\n this._inputs[DeviceType.Touch][deviceSlot][PointerInput.LeftClick] = 0;\n const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Touch, deviceSlot, PointerInput.LeftClick, 0, this, this._elementToAttachTo, evt.pointerId);\n this._onInputChanged(DeviceType.Touch, deviceSlot, deviceEvent);\n this._activeTouchIds[deviceSlot] = -1;\n this._onDeviceDisconnected(DeviceType.Touch, deviceSlot);\n }\n };\n // Set Wheel Event Name, code originally from scene.inputManager\n this._wheelEventName =\n \"onwheel\" in document.createElement(\"div\")\n ? \"wheel\" // Modern browsers support \"wheel\"\n : document.onmousewheel !== undefined\n ? \"mousewheel\" // Webkit and IE support at least \"mousewheel\"\n : \"DOMMouseScroll\"; // let's assume that remaining browsers are older Firefox\n // Code originally in scene.inputManager.ts\n // Chrome reports warning in console if wheel listener doesn't set an explicit passive option.\n // IE11 only supports captureEvent:boolean, not options:object, and it defaults to false.\n // Feature detection technique copied from: https://github.com/github/eventlistener-polyfill (MIT license)\n let passiveSupported = false;\n const noop = function () { };\n try {\n const options = Object.defineProperty({}, \"passive\", {\n get: function () {\n passiveSupported = true;\n },\n });\n this._elementToAttachTo.addEventListener(\"test\", noop, options);\n this._elementToAttachTo.removeEventListener(\"test\", noop, options);\n }\n catch (e) {\n /* */\n }\n this._pointerBlurEvent = () => {\n var _a, _b, _c, _d, _e;\n // Handle mouse buttons\n if (this.isDeviceAvailable(DeviceType.Mouse)) {\n const pointer = this._inputs[DeviceType.Mouse][0];\n if (this._mouseId >= 0 && ((_b = (_a = this._elementToAttachTo).hasPointerCapture) === null || _b === void 0 ? void 0 : _b.call(_a, this._mouseId))) {\n this._elementToAttachTo.releasePointerCapture(this._mouseId);\n }\n for (let inputIndex = PointerInput.LeftClick; inputIndex <= PointerInput.BrowserForward; inputIndex++) {\n if (pointer[inputIndex] === 1) {\n pointer[inputIndex] = 0;\n const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Mouse, 0, inputIndex, 0, this, this._elementToAttachTo);\n this._onInputChanged(DeviceType.Mouse, 0, deviceEvent);\n }\n }\n }\n // Handle Active Touches\n if (this.isDeviceAvailable(DeviceType.Touch)) {\n const pointer = this._inputs[DeviceType.Touch];\n for (let deviceSlot = 0; deviceSlot < this._activeTouchIds.length; deviceSlot++) {\n const pointerId = this._activeTouchIds[deviceSlot];\n if ((_d = (_c = this._elementToAttachTo).hasPointerCapture) === null || _d === void 0 ? void 0 : _d.call(_c, pointerId)) {\n this._elementToAttachTo.releasePointerCapture(pointerId);\n }\n if (pointerId !== -1 && ((_e = pointer[deviceSlot]) === null || _e === void 0 ? void 0 : _e[PointerInput.LeftClick]) === 1) {\n pointer[deviceSlot][PointerInput.LeftClick] = 0;\n const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Touch, deviceSlot, PointerInput.LeftClick, 0, this, this._elementToAttachTo, pointerId);\n this._onInputChanged(DeviceType.Touch, deviceSlot, deviceEvent);\n this._activeTouchIds[deviceSlot] = -1;\n this._onDeviceDisconnected(DeviceType.Touch, deviceSlot);\n }\n }\n }\n };\n this._pointerWheelEvent = (evt) => {\n const deviceType = DeviceType.Mouse;\n const deviceSlot = 0;\n if (!this._inputs[deviceType]) {\n this._inputs[deviceType] = [];\n }\n if (!this._inputs[deviceType][deviceSlot]) {\n this._pointerActive = true;\n this._registerDevice(deviceType, deviceSlot, MAX_POINTER_INPUTS);\n }\n const pointer = this._inputs[deviceType][deviceSlot];\n if (pointer) {\n pointer[PointerInput.MouseWheelX] = evt.deltaX || 0;\n pointer[PointerInput.MouseWheelY] = evt.deltaY || evt.wheelDelta || 0;\n pointer[PointerInput.MouseWheelZ] = evt.deltaZ || 0;\n const deviceEvent = evt;\n // By default, there is no pointerId for mouse wheel events so we'll add one here\n // This logic was originally in the InputManager but was added here to make the\n // InputManager more platform-agnostic\n if (evt.pointerId === undefined) {\n evt.pointerId = this._mouseId;\n }\n if (pointer[PointerInput.MouseWheelX] !== 0) {\n deviceEvent.inputIndex = PointerInput.MouseWheelX;\n this._onInputChanged(deviceType, deviceSlot, deviceEvent);\n }\n if (pointer[PointerInput.MouseWheelY] !== 0) {\n deviceEvent.inputIndex = PointerInput.MouseWheelY;\n this._onInputChanged(deviceType, deviceSlot, deviceEvent);\n }\n if (pointer[PointerInput.MouseWheelZ] !== 0) {\n deviceEvent.inputIndex = PointerInput.MouseWheelZ;\n this._onInputChanged(deviceType, deviceSlot, deviceEvent);\n }\n }\n };\n this._elementToAttachTo.addEventListener(this._eventPrefix + \"move\", this._pointerMoveEvent);\n this._elementToAttachTo.addEventListener(this._eventPrefix + \"down\", this._pointerDownEvent);\n this._elementToAttachTo.addEventListener(this._eventPrefix + \"up\", this._pointerUpEvent);\n this._elementToAttachTo.addEventListener(this._eventPrefix + \"cancel\", this._pointerCancelEvent);\n this._elementToAttachTo.addEventListener(\"blur\", this._pointerBlurEvent);\n this._elementToAttachTo.addEventListener(this._wheelEventName, this._pointerWheelEvent, passiveSupported ? { passive: false } : false);\n // Since there's no up or down event for mouse wheel or delta x/y, clear mouse values at end of frame\n this._pointerInputClearObserver = this._engine.onEndFrameObservable.add(() => {\n if (this.isDeviceAvailable(DeviceType.Mouse)) {\n const pointer = this._inputs[DeviceType.Mouse][0];\n pointer[PointerInput.MouseWheelX] = 0;\n pointer[PointerInput.MouseWheelY] = 0;\n pointer[PointerInput.MouseWheelZ] = 0;\n }\n });\n }\n /**\n * Handle all actions that come from gamepad interaction\n */\n _handleGamepadActions() {\n this._gamepadConnectedEvent = (evt) => {\n this._addGamePad(evt.gamepad);\n };\n this._gamepadDisconnectedEvent = (evt) => {\n if (this._gamepads) {\n const deviceType = this._getGamepadDeviceType(evt.gamepad.id);\n const deviceSlot = evt.gamepad.index;\n this._unregisterDevice(deviceType, deviceSlot);\n delete this._gamepads[deviceSlot];\n }\n };\n window.addEventListener(\"gamepadconnected\", this._gamepadConnectedEvent);\n window.addEventListener(\"gamepaddisconnected\", this._gamepadDisconnectedEvent);\n }\n /**\n * Update all non-event based devices with each frame\n * @param deviceType Enum specifying device type\n * @param deviceSlot \"Slot\" or index that device is referenced in\n * @param inputIndex Id of input to be checked\n */\n _updateDevice(deviceType, deviceSlot, inputIndex) {\n // Gamepads\n const gp = navigator.getGamepads()[deviceSlot];\n if (gp && deviceType === this._gamepads[deviceSlot]) {\n const device = this._inputs[deviceType][deviceSlot];\n if (inputIndex >= gp.buttons.length) {\n device[inputIndex] = gp.axes[inputIndex - gp.buttons.length].valueOf();\n }\n else {\n device[inputIndex] = gp.buttons[inputIndex].value;\n }\n }\n }\n /**\n * Gets DeviceType from the device name\n * @param deviceName Name of Device from DeviceInputSystem\n * @returns DeviceType enum value\n */\n _getGamepadDeviceType(deviceName) {\n if (deviceName.indexOf(\"054c\") !== -1) {\n // DualShock 4 Gamepad\n return deviceName.indexOf(\"0ce6\") !== -1 ? DeviceType.DualSense : DeviceType.DualShock;\n }\n else if (deviceName.indexOf(\"Xbox One\") !== -1 || deviceName.search(\"Xbox 360\") !== -1 || deviceName.search(\"xinput\") !== -1) {\n // Xbox Gamepad\n return DeviceType.Xbox;\n }\n else if (deviceName.indexOf(\"057e\") !== -1) {\n // Switch Gamepad\n return DeviceType.Switch;\n }\n return DeviceType.Generic;\n }\n /**\n * Get DeviceType from a given pointer/mouse/touch event.\n * @param evt PointerEvent to evaluate\n * @returns DeviceType interpreted from event\n */\n _getPointerType(evt) {\n let deviceType = DeviceType.Mouse;\n if (evt.pointerType === \"touch\" || evt.pointerType === \"pen\" || evt.touches) {\n deviceType = DeviceType.Touch;\n }\n return deviceType;\n }\n}\n//# sourceMappingURL=webDeviceInputSystem.js.map","import { DeviceType } from \"./InputDevices/deviceEnums.js\";\nimport { NativeDeviceInputSystem } from \"./nativeDeviceInputSystem.js\";\nimport { WebDeviceInputSystem } from \"./webDeviceInputSystem.js\";\nimport { DeviceSource } from \"./InputDevices/deviceSource.js\";\n/** @internal */\nexport class InternalDeviceSourceManager {\n constructor(engine) {\n this._registeredManagers = new Array();\n this._refCount = 0;\n // Public Functions\n this.registerManager = (manager) => {\n for (let deviceType = 0; deviceType < this._devices.length; deviceType++) {\n const device = this._devices[deviceType];\n for (const deviceSlotKey in device) {\n const deviceSlot = +deviceSlotKey;\n manager._addDevice(new DeviceSource(this._deviceInputSystem, deviceType, deviceSlot));\n }\n }\n this._registeredManagers.push(manager);\n };\n this.unregisterManager = (manager) => {\n const idx = this._registeredManagers.indexOf(manager);\n if (idx > -1) {\n this._registeredManagers.splice(idx, 1);\n }\n };\n const numberOfDeviceTypes = Object.keys(DeviceType).length / 2;\n this._devices = new Array(numberOfDeviceTypes);\n const onDeviceConnected = (deviceType, deviceSlot) => {\n if (!this._devices[deviceType]) {\n this._devices[deviceType] = new Array();\n }\n if (!this._devices[deviceType][deviceSlot]) {\n this._devices[deviceType][deviceSlot] = deviceSlot;\n }\n for (const manager of this._registeredManagers) {\n const deviceSource = new DeviceSource(this._deviceInputSystem, deviceType, deviceSlot);\n manager._addDevice(deviceSource);\n }\n };\n const onDeviceDisconnected = (deviceType, deviceSlot) => {\n var _a;\n if ((_a = this._devices[deviceType]) === null || _a === void 0 ? void 0 : _a[deviceSlot]) {\n delete this._devices[deviceType][deviceSlot];\n }\n for (const manager of this._registeredManagers) {\n manager._removeDevice(deviceType, deviceSlot);\n }\n };\n const onInputChanged = (deviceType, deviceSlot, eventData) => {\n if (eventData) {\n for (const manager of this._registeredManagers) {\n manager._onInputChanged(deviceType, deviceSlot, eventData);\n }\n }\n };\n if (typeof _native !== \"undefined\") {\n this._deviceInputSystem = new NativeDeviceInputSystem(onDeviceConnected, onDeviceDisconnected, onInputChanged);\n }\n else {\n this._deviceInputSystem = new WebDeviceInputSystem(engine, onDeviceConnected, onDeviceDisconnected, onInputChanged);\n }\n }\n dispose() {\n this._deviceInputSystem.dispose();\n }\n}\n//# sourceMappingURL=internalDeviceSourceManager.js.map","import { DeviceType } from \"./deviceEnums.js\";\nimport { Observable } from \"../../Misc/observable.js\";\nimport { InternalDeviceSourceManager } from \"../internalDeviceSourceManager.js\";\n/**\n * Class to keep track of devices\n */\nexport class DeviceSourceManager {\n // Public Functions\n /**\n * Gets a DeviceSource, given a type and slot\n * @param deviceType - Type of Device\n * @param deviceSlot - Slot or ID of device\n * @returns DeviceSource\n */\n getDeviceSource(deviceType, deviceSlot) {\n if (deviceSlot === undefined) {\n if (this._firstDevice[deviceType] === undefined) {\n return null;\n }\n deviceSlot = this._firstDevice[deviceType];\n }\n if (!this._devices[deviceType] || this._devices[deviceType][deviceSlot] === undefined) {\n return null;\n }\n return this._devices[deviceType][deviceSlot];\n }\n /**\n * Gets an array of DeviceSource objects for a given device type\n * @param deviceType - Type of Device\n * @returns All available DeviceSources of a given type\n */\n getDeviceSources(deviceType) {\n // If device type hasn't had any devices connected yet, return empty array.\n if (!this._devices[deviceType]) {\n return [];\n }\n return this._devices[deviceType].filter((source) => {\n return !!source;\n });\n }\n /**\n * Default constructor\n * @param engine - Used to get canvas (if applicable)\n */\n constructor(engine) {\n const numberOfDeviceTypes = Object.keys(DeviceType).length / 2;\n this._devices = new Array(numberOfDeviceTypes);\n this._firstDevice = new Array(numberOfDeviceTypes);\n this._engine = engine;\n if (!this._engine._deviceSourceManager) {\n this._engine._deviceSourceManager = new InternalDeviceSourceManager(engine);\n }\n this._engine._deviceSourceManager._refCount++;\n // Observables\n this.onDeviceConnectedObservable = new Observable((observer) => {\n for (const devices of this._devices) {\n if (devices) {\n for (const device of devices) {\n if (device) {\n this.onDeviceConnectedObservable.notifyObserver(observer, device);\n }\n }\n }\n }\n });\n this.onDeviceDisconnectedObservable = new Observable();\n this._engine._deviceSourceManager.registerManager(this);\n this._onDisposeObserver = engine.onDisposeObservable.add(() => {\n this.dispose();\n });\n }\n /**\n * Dispose of DeviceSourceManager\n */\n dispose() {\n // Null out observable refs\n this.onDeviceConnectedObservable.clear();\n this.onDeviceDisconnectedObservable.clear();\n if (this._engine._deviceSourceManager) {\n this._engine._deviceSourceManager.unregisterManager(this);\n if (--this._engine._deviceSourceManager._refCount < 1) {\n this._engine._deviceSourceManager.dispose();\n delete this._engine._deviceSourceManager;\n }\n }\n this._engine.onDisposeObservable.remove(this._onDisposeObserver);\n }\n // Hidden Functions\n /**\n * @param deviceSource - Source to add\n * @internal\n */\n _addDevice(deviceSource) {\n if (!this._devices[deviceSource.deviceType]) {\n this._devices[deviceSource.deviceType] = new Array();\n }\n if (!this._devices[deviceSource.deviceType][deviceSource.deviceSlot]) {\n this._devices[deviceSource.deviceType][deviceSource.deviceSlot] = deviceSource;\n this._updateFirstDevices(deviceSource.deviceType);\n }\n this.onDeviceConnectedObservable.notifyObservers(deviceSource);\n }\n /**\n * @param deviceType - DeviceType\n * @param deviceSlot - DeviceSlot\n * @internal\n */\n _removeDevice(deviceType, deviceSlot) {\n var _a, _b;\n const deviceSource = (_a = this._devices[deviceType]) === null || _a === void 0 ? void 0 : _a[deviceSlot]; // Grab local reference to use before removing from devices\n this.onDeviceDisconnectedObservable.notifyObservers(deviceSource);\n if ((_b = this._devices[deviceType]) === null || _b === void 0 ? void 0 : _b[deviceSlot]) {\n delete this._devices[deviceType][deviceSlot];\n }\n // Even if we don't delete a device, we should still check for the first device as things may have gotten out of sync.\n this._updateFirstDevices(deviceType);\n }\n /**\n * @param deviceType - DeviceType\n * @param deviceSlot - DeviceSlot\n * @param eventData - Event\n * @internal\n */\n _onInputChanged(deviceType, deviceSlot, eventData) {\n var _a, _b;\n (_b = (_a = this._devices[deviceType]) === null || _a === void 0 ? void 0 : _a[deviceSlot]) === null || _b === void 0 ? void 0 : _b.onInputChangedObservable.notifyObservers(eventData);\n }\n // Private Functions\n _updateFirstDevices(type) {\n switch (type) {\n case DeviceType.Keyboard:\n case DeviceType.Mouse:\n this._firstDevice[type] = 0;\n break;\n case DeviceType.Touch:\n case DeviceType.DualSense:\n case DeviceType.DualShock:\n case DeviceType.Xbox:\n case DeviceType.Switch:\n case DeviceType.Generic: {\n delete this._firstDevice[type];\n // eslint-disable-next-line no-case-declarations\n const devices = this._devices[type];\n if (devices) {\n for (let i = 0; i < devices.length; i++) {\n if (devices[i]) {\n this._firstDevice[type] = i;\n break;\n }\n }\n }\n break;\n }\n }\n }\n}\n//# sourceMappingURL=deviceSourceManager.js.map","import { ThinEngine } from \"../../Engines/thinEngine.js\";\n\nThinEngine.prototype.setAlphaConstants = function (r, g, b, a) {\n this._alphaState.setAlphaBlendConstants(r, g, b, a);\n};\nThinEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange = false) {\n if (this._alphaMode === mode) {\n if (!noDepthWriteChange) {\n // Make sure we still have the correct depth mask according to the alpha mode (a transparent material could have forced writting to the depth buffer, for instance)\n const depthMask = mode === 0;\n if (this.depthCullingState.depthMask !== depthMask) {\n this.depthCullingState.depthMask = depthMask;\n }\n }\n return;\n }\n switch (mode) {\n case 0:\n this._alphaState.alphaBlend = false;\n break;\n case 7:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case 8:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);\n this._alphaState.alphaBlend = true;\n break;\n case 2:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case 6:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case 1:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case 3:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case 4:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case 5:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case 9:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);\n this._alphaState.alphaBlend = true;\n break;\n case 10:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);\n this._alphaState.alphaBlend = true;\n break;\n case 11:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ONE, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case 12:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ZERO);\n this._alphaState.alphaBlend = true;\n break;\n case 13:\n 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);\n this._alphaState.alphaBlend = true;\n break;\n case 14:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);\n this._alphaState.alphaBlend = true;\n break;\n case 15:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ONE, this._gl.ZERO);\n this._alphaState.alphaBlend = true;\n break;\n case 16:\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ZERO, this._gl.ONE);\n this._alphaState.alphaBlend = true;\n break;\n case 17:\n // Same as ALPHA_COMBINE but accumulates (1 - alpha) values in the alpha channel for a later readout in order independant transparency\n this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);\n this._alphaState.alphaBlend = true;\n break;\n }\n if (!noDepthWriteChange) {\n this.depthCullingState.depthMask = mode === 0;\n }\n this._alphaMode = mode;\n};\nThinEngine.prototype.getAlphaMode = function () {\n return this._alphaMode;\n};\nThinEngine.prototype.setAlphaEquation = function (equation) {\n if (this._alphaEquation === equation) {\n return;\n }\n switch (equation) {\n case 0:\n this._alphaState.setAlphaEquationParameters(32774, 32774);\n break;\n case 1:\n this._alphaState.setAlphaEquationParameters(32778, 32778);\n break;\n case 2:\n this._alphaState.setAlphaEquationParameters(32779, 32779);\n break;\n case 3:\n this._alphaState.setAlphaEquationParameters(32776, 32776);\n break;\n case 4:\n this._alphaState.setAlphaEquationParameters(32775, 32775);\n break;\n case 5:\n this._alphaState.setAlphaEquationParameters(32775, 32774);\n break;\n }\n this._alphaEquation = equation;\n};\nThinEngine.prototype.getAlphaEquation = function () {\n return this._alphaEquation;\n};\n//# sourceMappingURL=engine.alpha.js.map","import { ThinEngine } from \"../../Engines/thinEngine.js\";\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nThinEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset = 0) {\n // Force cache update\n this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;\n this.bindIndexBuffer(indexBuffer);\n let view;\n if (indexBuffer.is32Bits) {\n // anything else than Uint32Array needs to be converted to Uint32Array\n view = indices instanceof Uint32Array ? indices : new Uint32Array(indices);\n }\n else {\n // anything else than Uint16Array needs to be converted to Uint16Array\n view = indices instanceof Uint16Array ? indices : new Uint16Array(indices);\n }\n this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, view, this._gl.DYNAMIC_DRAW);\n this._resetIndexBufferBinding();\n};\nThinEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {\n this.bindArrayBuffer(vertexBuffer);\n if (byteOffset === undefined) {\n byteOffset = 0;\n }\n const dataLength = data.byteLength || data.length;\n if (byteLength === undefined || (byteLength >= dataLength && byteOffset === 0)) {\n if (data instanceof Array) {\n this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));\n }\n else {\n this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);\n }\n }\n else {\n if (data instanceof Array) {\n this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));\n }\n else {\n if (data instanceof ArrayBuffer) {\n data = new Uint8Array(data, byteOffset, byteLength);\n }\n else {\n data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);\n }\n this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);\n }\n }\n this._resetVertexBufferBinding();\n};\n//# sourceMappingURL=engine.dynamicBuffer.js.map","import { ThinEngine } from \"../../Engines/thinEngine.js\";\n\n/**\n * Allocate a typed array depending on a texture type. Optionally can copy existing data in the buffer.\n * @param type type of the texture\n * @param sizeOrDstBuffer size of the array OR an existing buffer that will be used as the destination of the copy (if copyBuffer is provided)\n * @param sizeInBytes true if the size of the array is given in bytes, false if it is the number of elements of the array\n * @param copyBuffer if provided, buffer to copy into the destination buffer (either a newly allocated buffer if sizeOrDstBuffer is a number or use sizeOrDstBuffer as the destination buffer otherwise)\n * @returns the allocated buffer or sizeOrDstBuffer if the latter is an ArrayBuffer\n */\nexport function allocateAndCopyTypedBuffer(type, sizeOrDstBuffer, sizeInBytes = false, copyBuffer) {\n switch (type) {\n case 3: {\n const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Int8Array(sizeOrDstBuffer) : new Int8Array(sizeOrDstBuffer);\n if (copyBuffer) {\n buffer.set(new Int8Array(copyBuffer));\n }\n return buffer;\n }\n case 0: {\n const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint8Array(sizeOrDstBuffer) : new Uint8Array(sizeOrDstBuffer);\n if (copyBuffer) {\n buffer.set(new Uint8Array(copyBuffer));\n }\n return buffer;\n }\n case 4: {\n const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Int16Array(sizeOrDstBuffer) : new Int16Array(sizeInBytes ? sizeOrDstBuffer / 2 : sizeOrDstBuffer);\n if (copyBuffer) {\n buffer.set(new Int16Array(copyBuffer));\n }\n return buffer;\n }\n case 5:\n case 8:\n case 9:\n case 10:\n case 2: {\n const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint16Array(sizeOrDstBuffer) : new Uint16Array(sizeInBytes ? sizeOrDstBuffer / 2 : sizeOrDstBuffer);\n if (copyBuffer) {\n buffer.set(new Uint16Array(copyBuffer));\n }\n return buffer;\n }\n case 6: {\n const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Int32Array(sizeOrDstBuffer) : new Int32Array(sizeInBytes ? sizeOrDstBuffer / 4 : sizeOrDstBuffer);\n if (copyBuffer) {\n buffer.set(new Int32Array(copyBuffer));\n }\n return buffer;\n }\n case 7:\n case 11:\n case 12:\n case 13:\n case 14:\n case 15: {\n const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint32Array(sizeOrDstBuffer) : new Uint32Array(sizeInBytes ? sizeOrDstBuffer / 4 : sizeOrDstBuffer);\n if (copyBuffer) {\n buffer.set(new Uint32Array(copyBuffer));\n }\n return buffer;\n }\n case 1: {\n const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Float32Array(sizeOrDstBuffer) : new Float32Array(sizeInBytes ? sizeOrDstBuffer / 4 : sizeOrDstBuffer);\n if (copyBuffer) {\n buffer.set(new Float32Array(copyBuffer));\n }\n return buffer;\n }\n }\n const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint8Array(sizeOrDstBuffer) : new Uint8Array(sizeOrDstBuffer);\n if (copyBuffer) {\n buffer.set(new Uint8Array(copyBuffer));\n }\n return buffer;\n}\nThinEngine.prototype._readTexturePixelsSync = function (texture, width, height, faceIndex = -1, level = 0, buffer = null, flushRenderer = true, noDataConversion = false, x = 0, y = 0) {\n var _a, _b;\n const gl = this._gl;\n if (!gl) {\n throw new Error(\"Engine does not have gl rendering context.\");\n }\n if (!this._dummyFramebuffer) {\n const dummy = gl.createFramebuffer();\n if (!dummy) {\n throw new Error(\"Unable to create dummy framebuffer\");\n }\n this._dummyFramebuffer = dummy;\n }\n gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);\n if (faceIndex > -1) {\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, (_a = texture._hardwareTexture) === null || _a === void 0 ? void 0 : _a.underlyingResource, level);\n }\n else {\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, (_b = texture._hardwareTexture) === null || _b === void 0 ? void 0 : _b.underlyingResource, level);\n }\n let readType = texture.type !== undefined ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;\n if (!noDataConversion) {\n switch (readType) {\n case gl.UNSIGNED_BYTE:\n if (!buffer) {\n buffer = new Uint8Array(4 * width * height);\n }\n readType = gl.UNSIGNED_BYTE;\n break;\n default:\n if (!buffer) {\n buffer = new Float32Array(4 * width * height);\n }\n readType = gl.FLOAT;\n break;\n }\n }\n else if (!buffer) {\n buffer = allocateAndCopyTypedBuffer(texture.type, 4 * width * height);\n }\n if (flushRenderer) {\n this.flushFramebuffer();\n }\n gl.readPixels(x, y, width, height, gl.RGBA, readType, buffer);\n gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);\n return buffer;\n};\nThinEngine.prototype._readTexturePixels = function (texture, width, height, faceIndex = -1, level = 0, buffer = null, flushRenderer = true, noDataConversion = false, x = 0, y = 0) {\n return Promise.resolve(this._readTexturePixelsSync(texture, width, height, faceIndex, level, buffer, flushRenderer, noDataConversion, x, y));\n};\n//# sourceMappingURL=engine.readTexture.js.map","import { ThinEngine } from \"../../Engines/thinEngine.js\";\nimport { WebGLDataBuffer } from \"../../Meshes/WebGL/webGLDataBuffer.js\";\nThinEngine.prototype.createUniformBuffer = function (elements) {\n const ubo = this._gl.createBuffer();\n if (!ubo) {\n throw new Error(\"Unable to create uniform buffer\");\n }\n const result = new WebGLDataBuffer(ubo);\n this.bindUniformBuffer(result);\n if (elements instanceof Float32Array) {\n this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);\n }\n else {\n this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);\n }\n this.bindUniformBuffer(null);\n result.references = 1;\n return result;\n};\nThinEngine.prototype.createDynamicUniformBuffer = function (elements) {\n const ubo = this._gl.createBuffer();\n if (!ubo) {\n throw new Error(\"Unable to create dynamic uniform buffer\");\n }\n const result = new WebGLDataBuffer(ubo);\n this.bindUniformBuffer(result);\n if (elements instanceof Float32Array) {\n this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);\n }\n else {\n this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);\n }\n this.bindUniformBuffer(null);\n result.references = 1;\n return result;\n};\nThinEngine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {\n this.bindUniformBuffer(uniformBuffer);\n if (offset === undefined) {\n offset = 0;\n }\n if (count === undefined) {\n if (elements instanceof Float32Array) {\n this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);\n }\n else {\n this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));\n }\n }\n else {\n if (elements instanceof Float32Array) {\n this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));\n }\n else {\n this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));\n }\n }\n this.bindUniformBuffer(null);\n};\nThinEngine.prototype.bindUniformBuffer = function (buffer) {\n this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer ? buffer.underlyingResource : null);\n};\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nThinEngine.prototype.bindUniformBufferBase = function (buffer, location, name) {\n this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer ? buffer.underlyingResource : null);\n};\nThinEngine.prototype.bindUniformBlock = function (pipelineContext, blockName, index) {\n const program = pipelineContext.program;\n const uniformLocation = this._gl.getUniformBlockIndex(program, blockName);\n if (uniformLocation !== 0xffffffff) {\n this._gl.uniformBlockBinding(program, uniformLocation, index);\n }\n};\n//# sourceMappingURL=engine.uniformBuffer.js.map","const defaultAttributeKeywordName = \"attribute\";\nconst defaultVaryingKeywordName = \"varying\";\n/** @internal */\nexport class ShaderCodeNode {\n constructor() {\n this.children = [];\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isValid(preprocessors) {\n return true;\n }\n process(preprocessors, options) {\n var _a, _b, _c, _d, _e, _f, _g;\n let result = \"\";\n if (this.line) {\n let value = this.line;\n const processor = options.processor;\n if (processor) {\n // This must be done before other replacements to avoid mistakenly changing something that was already changed.\n if (processor.lineProcessor) {\n value = processor.lineProcessor(value, options.isFragment, options.processingContext);\n }\n const attributeKeyword = (_b = (_a = options.processor) === null || _a === void 0 ? void 0 : _a.attributeKeywordName) !== null && _b !== void 0 ? _b : defaultAttributeKeywordName;\n const varyingKeyword = options.isFragment && ((_c = options.processor) === null || _c === void 0 ? void 0 : _c.varyingFragmentKeywordName)\n ? (_d = options.processor) === null || _d === void 0 ? void 0 : _d.varyingFragmentKeywordName\n : !options.isFragment && ((_e = options.processor) === null || _e === void 0 ? void 0 : _e.varyingVertexKeywordName)\n ? (_f = options.processor) === null || _f === void 0 ? void 0 : _f.varyingVertexKeywordName\n : defaultVaryingKeywordName;\n if (!options.isFragment && processor.attributeProcessor && this.line.startsWith(attributeKeyword)) {\n value = processor.attributeProcessor(this.line, preprocessors, options.processingContext);\n }\n else if (processor.varyingProcessor &&\n (((_g = processor.varyingCheck) === null || _g === void 0 ? void 0 : _g.call(processor, this.line, options.isFragment)) || (!processor.varyingCheck && this.line.startsWith(varyingKeyword)))) {\n value = processor.varyingProcessor(this.line, options.isFragment, preprocessors, options.processingContext);\n }\n else if (processor.uniformProcessor && processor.uniformRegexp && processor.uniformRegexp.test(this.line)) {\n if (!options.lookForClosingBracketForUniformBuffer) {\n value = processor.uniformProcessor(this.line, options.isFragment, preprocessors, options.processingContext);\n }\n }\n else if (processor.uniformBufferProcessor && processor.uniformBufferRegexp && processor.uniformBufferRegexp.test(this.line)) {\n if (!options.lookForClosingBracketForUniformBuffer) {\n value = processor.uniformBufferProcessor(this.line, options.isFragment, options.processingContext);\n options.lookForClosingBracketForUniformBuffer = true;\n }\n }\n else if (processor.textureProcessor && processor.textureRegexp && processor.textureRegexp.test(this.line)) {\n value = processor.textureProcessor(this.line, options.isFragment, preprocessors, options.processingContext);\n }\n else if ((processor.uniformProcessor || processor.uniformBufferProcessor) && this.line.startsWith(\"uniform\") && !options.lookForClosingBracketForUniformBuffer) {\n const regex = /uniform\\s+(?:(?:highp)?|(?:lowp)?)\\s*(\\S+)\\s+(\\S+)\\s*;/;\n if (regex.test(this.line)) {\n // uniform\n if (processor.uniformProcessor) {\n value = processor.uniformProcessor(this.line, options.isFragment, preprocessors, options.processingContext);\n }\n }\n else {\n // Uniform buffer\n if (processor.uniformBufferProcessor) {\n value = processor.uniformBufferProcessor(this.line, options.isFragment, options.processingContext);\n options.lookForClosingBracketForUniformBuffer = true;\n }\n }\n }\n if (options.lookForClosingBracketForUniformBuffer && this.line.indexOf(\"}\") !== -1) {\n options.lookForClosingBracketForUniformBuffer = false;\n if (processor.endOfUniformBufferProcessor) {\n value = processor.endOfUniformBufferProcessor(this.line, options.isFragment, options.processingContext);\n }\n }\n }\n result += value + \"\\r\\n\";\n }\n this.children.forEach((child) => {\n result += child.process(preprocessors, options);\n });\n if (this.additionalDefineKey) {\n preprocessors[this.additionalDefineKey] = this.additionalDefineValue || \"true\";\n }\n return result;\n }\n}\n//# sourceMappingURL=shaderCodeNode.js.map","/** @internal */\nexport class ShaderCodeCursor {\n constructor() {\n this._lines = [];\n }\n get currentLine() {\n return this._lines[this.lineIndex];\n }\n get canRead() {\n return this.lineIndex < this._lines.length - 1;\n }\n set lines(value) {\n this._lines.length = 0;\n for (const line of value) {\n // Prevent removing line break in macros.\n if (line[0] === \"#\") {\n this._lines.push(line);\n continue;\n }\n // Do not split single line comments\n if (line.trim().startsWith(\"//\")) {\n this._lines.push(line);\n continue;\n }\n const split = line.split(\";\");\n for (let index = 0; index < split.length; index++) {\n let subLine = split[index];\n subLine = subLine.trim();\n if (!subLine) {\n continue;\n }\n this._lines.push(subLine + (index !== split.length - 1 ? \";\" : \"\"));\n }\n }\n }\n}\n//# sourceMappingURL=shaderCodeCursor.js.map","import { ShaderCodeNode } from \"./shaderCodeNode.js\";\n/** @internal */\nexport class ShaderCodeConditionNode extends ShaderCodeNode {\n process(preprocessors, options) {\n for (let index = 0; index < this.children.length; index++) {\n const node = this.children[index];\n if (node.isValid(preprocessors)) {\n return node.process(preprocessors, options);\n }\n }\n return \"\";\n }\n}\n//# sourceMappingURL=shaderCodeConditionNode.js.map","import { ShaderCodeNode } from \"./shaderCodeNode.js\";\n/** @internal */\nexport class ShaderCodeTestNode extends ShaderCodeNode {\n isValid(preprocessors) {\n return this.testExpression.isTrue(preprocessors);\n }\n}\n//# sourceMappingURL=shaderCodeTestNode.js.map","/* eslint-disable @typescript-eslint/naming-convention */\n/** @internal */\nexport class ShaderDefineExpression {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isTrue(preprocessors) {\n return true;\n }\n static postfixToInfix(postfix) {\n const stack = [];\n for (const c of postfix) {\n if (ShaderDefineExpression._OperatorPriority[c] === undefined) {\n stack.push(c);\n }\n else {\n const v1 = stack[stack.length - 1], v2 = stack[stack.length - 2];\n stack.length -= 2;\n stack.push(`(${v2}${c}${v1})`);\n }\n }\n return stack[stack.length - 1];\n }\n /**\n * Converts an infix expression to a postfix expression.\n *\n * This method is used to transform infix expressions, which are more human-readable,\n * into postfix expressions, also known as Reverse Polish Notation (RPN), that can be\n * evaluated more efficiently by a computer. The conversion is based on the operator\n * priority defined in _OperatorPriority.\n *\n * The function employs a stack-based algorithm for the conversion and caches the result\n * to improve performance. The cache keeps track of each converted expression's access time\n * to manage the cache size and optimize memory usage. When the cache size exceeds a specified\n * limit, the least recently accessed items in the cache are deleted.\n *\n * The cache mechanism is particularly helpful for shader compilation, where the same infix\n * expressions might be encountered repeatedly, hence the caching can speed up the process.\n *\n * @param infix - The infix expression to be converted.\n * @returns The postfix expression as an array of strings.\n */\n static infixToPostfix(infix) {\n // Is infix already in cache\n const cacheItem = ShaderDefineExpression._InfixToPostfixCache.get(infix);\n if (cacheItem) {\n cacheItem.accessTime = Date.now();\n return cacheItem.result;\n }\n // Is infix contain any operator\n if (!infix.includes(\"&&\") && !infix.includes(\"||\") && !infix.includes(\")\") && !infix.includes(\"(\")) {\n return [infix];\n }\n const result = [];\n let stackIdx = -1;\n const pushOperand = () => {\n operand = operand.trim();\n if (operand !== \"\") {\n result.push(operand);\n operand = \"\";\n }\n };\n const push = (s) => {\n if (stackIdx < ShaderDefineExpression._Stack.length - 1) {\n ShaderDefineExpression._Stack[++stackIdx] = s;\n }\n };\n const peek = () => ShaderDefineExpression._Stack[stackIdx];\n const pop = () => (stackIdx === -1 ? \"!!INVALID EXPRESSION!!\" : ShaderDefineExpression._Stack[stackIdx--]);\n let idx = 0, operand = \"\";\n while (idx < infix.length) {\n const c = infix.charAt(idx), token = idx < infix.length - 1 ? infix.substr(idx, 2) : \"\";\n if (c === \"(\") {\n operand = \"\";\n push(c);\n }\n else if (c === \")\") {\n pushOperand();\n while (stackIdx !== -1 && peek() !== \"(\") {\n result.push(pop());\n }\n pop();\n }\n else if (ShaderDefineExpression._OperatorPriority[token] > 1) {\n pushOperand();\n while (stackIdx !== -1 && ShaderDefineExpression._OperatorPriority[peek()] >= ShaderDefineExpression._OperatorPriority[token]) {\n result.push(pop());\n }\n push(token);\n idx++;\n }\n else {\n operand += c;\n }\n idx++;\n }\n pushOperand();\n while (stackIdx !== -1) {\n if (peek() === \"(\") {\n pop();\n }\n else {\n result.push(pop());\n }\n }\n // If the cache is at capacity, clear it before adding a new item\n if (ShaderDefineExpression._InfixToPostfixCache.size >= ShaderDefineExpression.InfixToPostfixCacheLimitSize) {\n ShaderDefineExpression.ClearCache();\n }\n // Add the new item to the cache, including the current time as the last access time\n ShaderDefineExpression._InfixToPostfixCache.set(infix, { result, accessTime: Date.now() });\n return result;\n }\n static ClearCache() {\n // Convert the cache to an array and sort by last access time\n const sortedCache = Array.from(ShaderDefineExpression._InfixToPostfixCache.entries()).sort((a, b) => a[1].accessTime - b[1].accessTime);\n // Remove the least recently accessed half of the cache\n for (let i = 0; i < ShaderDefineExpression.InfixToPostfixCacheCleanupSize; i++) {\n ShaderDefineExpression._InfixToPostfixCache.delete(sortedCache[i][0]);\n }\n }\n}\n/**\n * Cache items count limit for the InfixToPostfix cache.\n * It uses to improve the performance of the shader compilation.\n * For details see PR: https://github.com/BabylonJS/Babylon.js/pull/13936\n */\nShaderDefineExpression.InfixToPostfixCacheLimitSize = 50000;\n/**\n * When the cache size is exceeded, a cache cleanup will be triggered\n * and the cache will be reduced by the size specified\n * in the InfixToPostfixCacheCleanupSize variable, removing entries\n * that have not been accessed the longest.\n */\nShaderDefineExpression.InfixToPostfixCacheCleanupSize = 25000;\nShaderDefineExpression._InfixToPostfixCache = new Map();\nShaderDefineExpression._OperatorPriority = {\n \")\": 0,\n \"(\": 1,\n \"||\": 2,\n \"&&\": 3,\n};\nShaderDefineExpression._Stack = [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"];\n//# sourceMappingURL=shaderDefineExpression.js.map","import { ShaderDefineExpression } from \"../shaderDefineExpression.js\";\n/** @internal */\nexport class ShaderDefineIsDefinedOperator extends ShaderDefineExpression {\n constructor(define, not = false) {\n super();\n this.define = define;\n this.not = not;\n }\n isTrue(preprocessors) {\n let condition = preprocessors[this.define] !== undefined;\n if (this.not) {\n condition = !condition;\n }\n return condition;\n }\n}\n//# sourceMappingURL=shaderDefineIsDefinedOperator.js.map","import { ShaderDefineExpression } from \"../shaderDefineExpression.js\";\n/** @internal */\nexport class ShaderDefineAndOperator extends ShaderDefineExpression {\n isTrue(preprocessors) {\n return this.leftOperand.isTrue(preprocessors) && this.rightOperand.isTrue(preprocessors);\n }\n}\n//# sourceMappingURL=shaderDefineAndOperator.js.map","import { ShaderDefineExpression } from \"../shaderDefineExpression.js\";\n/** @internal */\nexport class ShaderDefineArithmeticOperator extends ShaderDefineExpression {\n constructor(define, operand, testValue) {\n super();\n this.define = define;\n this.operand = operand;\n this.testValue = testValue;\n }\n isTrue(preprocessors) {\n let value = preprocessors[this.define];\n if (value === undefined) {\n value = this.define;\n }\n let condition = false;\n const left = parseInt(value);\n const right = parseInt(this.testValue);\n switch (this.operand) {\n case \">\":\n condition = left > right;\n break;\n case \"<\":\n condition = left < right;\n break;\n case \"<=\":\n condition = left <= right;\n break;\n case \">=\":\n condition = left >= right;\n break;\n case \"==\":\n condition = left === right;\n break;\n case \"!=\":\n condition = left !== right;\n break;\n }\n return condition;\n }\n}\n//# sourceMappingURL=shaderDefineArithmeticOperator.js.map","/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { ShaderCodeNode } from \"./shaderCodeNode.js\";\nimport { ShaderCodeCursor } from \"./shaderCodeCursor.js\";\nimport { ShaderCodeConditionNode } from \"./shaderCodeConditionNode.js\";\nimport { ShaderCodeTestNode } from \"./shaderCodeTestNode.js\";\nimport { ShaderDefineIsDefinedOperator } from \"./Expressions/Operators/shaderDefineIsDefinedOperator.js\";\nimport { ShaderDefineOrOperator } from \"./Expressions/Operators/shaderDefineOrOperator.js\";\nimport { ShaderDefineAndOperator } from \"./Expressions/Operators/shaderDefineAndOperator.js\";\nimport { ShaderDefineExpression } from \"./Expressions/shaderDefineExpression.js\";\nimport { ShaderDefineArithmeticOperator } from \"./Expressions/Operators/shaderDefineArithmeticOperator.js\";\nimport { _WarnImport } from \"../../Misc/devTools.js\";\nimport { ShaderLanguage } from \"../../Materials/shaderLanguage.js\";\nconst regexSE = /defined\\s*?\\((.+?)\\)/g;\nconst regexSERevert = /defined\\s*?\\[(.+?)\\]/g;\nconst regexShaderInclude = /#include\\s?<(.+)>(\\((.*)\\))*(\\[(.*)\\])*/g;\nconst regexShaderDecl = /__decl__/;\nconst regexLightX = /light\\{X\\}.(\\w*)/g;\nconst regexX = /\\{X\\}/g;\nconst reusableMatches = [];\n/** @internal */\nexport class ShaderProcessor {\n static Initialize(options) {\n if (options.processor && options.processor.initializeShaders) {\n options.processor.initializeShaders(options.processingContext);\n }\n }\n static Process(sourceCode, options, callback, engine) {\n var _a;\n if ((_a = options.processor) === null || _a === void 0 ? void 0 : _a.preProcessShaderCode) {\n sourceCode = options.processor.preProcessShaderCode(sourceCode, options.isFragment);\n }\n this._ProcessIncludes(sourceCode, options, (codeWithIncludes) => {\n if (options.processCodeAfterIncludes) {\n codeWithIncludes = options.processCodeAfterIncludes(options.isFragment ? \"fragment\" : \"vertex\", codeWithIncludes);\n }\n const migratedCode = this._ProcessShaderConversion(codeWithIncludes, options, engine);\n callback(migratedCode, codeWithIncludes);\n });\n }\n static PreProcess(sourceCode, options, callback, engine) {\n var _a;\n if ((_a = options.processor) === null || _a === void 0 ? void 0 : _a.preProcessShaderCode) {\n sourceCode = options.processor.preProcessShaderCode(sourceCode, options.isFragment);\n }\n this._ProcessIncludes(sourceCode, options, (codeWithIncludes) => {\n if (options.processCodeAfterIncludes) {\n codeWithIncludes = options.processCodeAfterIncludes(options.isFragment ? \"fragment\" : \"vertex\", codeWithIncludes);\n }\n const migratedCode = this._ApplyPreProcessing(codeWithIncludes, options, engine);\n callback(migratedCode, codeWithIncludes);\n });\n }\n static Finalize(vertexCode, fragmentCode, options) {\n if (!options.processor || !options.processor.finalizeShaders) {\n return { vertexCode, fragmentCode };\n }\n return options.processor.finalizeShaders(vertexCode, fragmentCode, options.processingContext);\n }\n static _ProcessPrecision(source, options) {\n var _a;\n if ((_a = options.processor) === null || _a === void 0 ? void 0 : _a.noPrecision) {\n return source;\n }\n const shouldUseHighPrecisionShader = options.shouldUseHighPrecisionShader;\n if (source.indexOf(\"precision highp float\") === -1) {\n if (!shouldUseHighPrecisionShader) {\n source = \"precision mediump float;\\n\" + source;\n }\n else {\n source = \"precision highp float;\\n\" + source;\n }\n }\n else {\n if (!shouldUseHighPrecisionShader) {\n // Moving highp to mediump\n source = source.replace(\"precision highp float\", \"precision mediump float\");\n }\n }\n return source;\n }\n static _ExtractOperation(expression) {\n const regex = /defined\\((.+)\\)/;\n const match = regex.exec(expression);\n if (match && match.length) {\n return new ShaderDefineIsDefinedOperator(match[1].trim(), expression[0] === \"!\");\n }\n const operators = [\"==\", \"!=\", \">=\", \"<=\", \"<\", \">\"];\n let operator = \"\";\n let indexOperator = 0;\n for (operator of operators) {\n indexOperator = expression.indexOf(operator);\n if (indexOperator > -1) {\n break;\n }\n }\n if (indexOperator === -1) {\n return new ShaderDefineIsDefinedOperator(expression);\n }\n const define = expression.substring(0, indexOperator).trim();\n const value = expression.substring(indexOperator + operator.length).trim();\n return new ShaderDefineArithmeticOperator(define, operator, value);\n }\n static _BuildSubExpression(expression) {\n expression = expression.replace(regexSE, \"defined[$1]\");\n const postfix = ShaderDefineExpression.infixToPostfix(expression);\n const stack = [];\n for (const c of postfix) {\n if (c !== \"||\" && c !== \"&&\") {\n stack.push(c);\n }\n else if (stack.length >= 2) {\n let v1 = stack[stack.length - 1], v2 = stack[stack.length - 2];\n stack.length -= 2;\n const operator = c == \"&&\" ? new ShaderDefineAndOperator() : new ShaderDefineOrOperator();\n if (typeof v1 === \"string\") {\n v1 = v1.replace(regexSERevert, \"defined($1)\");\n }\n if (typeof v2 === \"string\") {\n v2 = v2.replace(regexSERevert, \"defined($1)\");\n }\n operator.leftOperand = typeof v2 === \"string\" ? this._ExtractOperation(v2) : v2;\n operator.rightOperand = typeof v1 === \"string\" ? this._ExtractOperation(v1) : v1;\n stack.push(operator);\n }\n }\n let result = stack[stack.length - 1];\n if (typeof result === \"string\") {\n result = result.replace(regexSERevert, \"defined($1)\");\n }\n // note: stack.length !== 1 if there was an error in the parsing\n return typeof result === \"string\" ? this._ExtractOperation(result) : result;\n }\n static _BuildExpression(line, start) {\n const node = new ShaderCodeTestNode();\n const command = line.substring(0, start);\n let expression = line.substring(start);\n expression = expression.substring(0, (expression.indexOf(\"//\") + 1 || expression.length + 1) - 1).trim();\n if (command === \"#ifdef\") {\n node.testExpression = new ShaderDefineIsDefinedOperator(expression);\n }\n else if (command === \"#ifndef\") {\n node.testExpression = new ShaderDefineIsDefinedOperator(expression, true);\n }\n else {\n node.testExpression = this._BuildSubExpression(expression);\n }\n return node;\n }\n static _MoveCursorWithinIf(cursor, rootNode, ifNode) {\n let line = cursor.currentLine;\n while (this._MoveCursor(cursor, ifNode)) {\n line = cursor.currentLine;\n const first5 = line.substring(0, 5).toLowerCase();\n if (first5 === \"#else\") {\n const elseNode = new ShaderCodeNode();\n rootNode.children.push(elseNode);\n this._MoveCursor(cursor, elseNode);\n return;\n }\n else if (first5 === \"#elif\") {\n const elifNode = this._BuildExpression(line, 5);\n rootNode.children.push(elifNode);\n ifNode = elifNode;\n }\n }\n }\n static _MoveCursor(cursor, rootNode) {\n while (cursor.canRead) {\n cursor.lineIndex++;\n const line = cursor.currentLine;\n if (line.indexOf(\"#\") >= 0) {\n const matches = ShaderProcessor._MoveCursorRegex.exec(line);\n if (matches && matches.length) {\n const keyword = matches[0];\n switch (keyword) {\n case \"#ifdef\": {\n const newRootNode = new ShaderCodeConditionNode();\n rootNode.children.push(newRootNode);\n const ifNode = this._BuildExpression(line, 6);\n newRootNode.children.push(ifNode);\n this._MoveCursorWithinIf(cursor, newRootNode, ifNode);\n break;\n }\n case \"#else\":\n case \"#elif\":\n return true;\n case \"#endif\":\n return false;\n case \"#ifndef\": {\n const newRootNode = new ShaderCodeConditionNode();\n rootNode.children.push(newRootNode);\n const ifNode = this._BuildExpression(line, 7);\n newRootNode.children.push(ifNode);\n this._MoveCursorWithinIf(cursor, newRootNode, ifNode);\n break;\n }\n case \"#if\": {\n const newRootNode = new ShaderCodeConditionNode();\n const ifNode = this._BuildExpression(line, 3);\n rootNode.children.push(newRootNode);\n newRootNode.children.push(ifNode);\n this._MoveCursorWithinIf(cursor, newRootNode, ifNode);\n break;\n }\n }\n continue;\n }\n }\n const newNode = new ShaderCodeNode();\n newNode.line = line;\n rootNode.children.push(newNode);\n // Detect additional defines\n if (line[0] === \"#\" && line[1] === \"d\") {\n const split = line.replace(\";\", \"\").split(\" \");\n newNode.additionalDefineKey = split[1];\n if (split.length === 3) {\n newNode.additionalDefineValue = split[2];\n }\n }\n }\n return false;\n }\n static _EvaluatePreProcessors(sourceCode, preprocessors, options) {\n const rootNode = new ShaderCodeNode();\n const cursor = new ShaderCodeCursor();\n cursor.lineIndex = -1;\n cursor.lines = sourceCode.split(\"\\n\");\n // Decompose (We keep it in 2 steps so it is easier to maintain and perf hit is insignificant)\n this._MoveCursor(cursor, rootNode);\n // Recompose\n return rootNode.process(preprocessors, options);\n }\n static _PreparePreProcessors(options, engine) {\n var _a;\n const defines = options.defines;\n const preprocessors = {};\n for (const define of defines) {\n const keyValue = define.replace(\"#define\", \"\").replace(\";\", \"\").trim();\n const split = keyValue.split(\" \");\n preprocessors[split[0]] = split.length > 1 ? split[1] : \"\";\n }\n if (((_a = options.processor) === null || _a === void 0 ? void 0 : _a.shaderLanguage) === ShaderLanguage.GLSL) {\n preprocessors[\"GL_ES\"] = \"true\";\n }\n preprocessors[\"__VERSION__\"] = options.version;\n preprocessors[options.platformName] = \"true\";\n engine._getGlobalDefines(preprocessors);\n return preprocessors;\n }\n static _ProcessShaderConversion(sourceCode, options, engine) {\n let preparedSourceCode = this._ProcessPrecision(sourceCode, options);\n if (!options.processor) {\n return preparedSourceCode;\n }\n // Already converted\n if (options.processor.shaderLanguage === ShaderLanguage.GLSL && preparedSourceCode.indexOf(\"#version 3\") !== -1) {\n preparedSourceCode = preparedSourceCode.replace(\"#version 300 es\", \"\");\n if (!options.processor.parseGLES3) {\n return preparedSourceCode;\n }\n }\n const defines = options.defines;\n const preprocessors = this._PreparePreProcessors(options, engine);\n // General pre processing\n if (options.processor.preProcessor) {\n preparedSourceCode = options.processor.preProcessor(preparedSourceCode, defines, options.isFragment, options.processingContext);\n }\n preparedSourceCode = this._EvaluatePreProcessors(preparedSourceCode, preprocessors, options);\n // Post processing\n if (options.processor.postProcessor) {\n preparedSourceCode = options.processor.postProcessor(preparedSourceCode, defines, options.isFragment, options.processingContext, engine);\n }\n // Inline functions tagged with #define inline\n if (engine._features.needShaderCodeInlining) {\n preparedSourceCode = engine.inlineShaderCode(preparedSourceCode);\n }\n return preparedSourceCode;\n }\n static _ApplyPreProcessing(sourceCode, options, engine) {\n var _a, _b;\n let preparedSourceCode = sourceCode;\n const defines = options.defines;\n const preprocessors = this._PreparePreProcessors(options, engine);\n // General pre processing\n if ((_a = options.processor) === null || _a === void 0 ? void 0 : _a.preProcessor) {\n preparedSourceCode = options.processor.preProcessor(preparedSourceCode, defines, options.isFragment, options.processingContext);\n }\n preparedSourceCode = this._EvaluatePreProcessors(preparedSourceCode, preprocessors, options);\n // Post processing\n if ((_b = options.processor) === null || _b === void 0 ? void 0 : _b.postProcessor) {\n preparedSourceCode = options.processor.postProcessor(preparedSourceCode, defines, options.isFragment, options.processingContext, engine);\n }\n // Inline functions tagged with #define inline\n if (engine._features.needShaderCodeInlining) {\n preparedSourceCode = engine.inlineShaderCode(preparedSourceCode);\n }\n return preparedSourceCode;\n }\n static _ProcessIncludes(sourceCode, options, callback) {\n reusableMatches.length = 0;\n let match;\n // stay back-compat to the old matchAll syntax\n while ((match = regexShaderInclude.exec(sourceCode)) !== null) {\n reusableMatches.push(match);\n }\n let returnValue = String(sourceCode);\n let parts = [sourceCode];\n let keepProcessing = false;\n for (const match of reusableMatches) {\n let includeFile = match[1];\n // Uniform declaration\n if (includeFile.indexOf(\"__decl__\") !== -1) {\n includeFile = includeFile.replace(regexShaderDecl, \"\");\n if (options.supportsUniformBuffers) {\n includeFile = includeFile.replace(\"Vertex\", \"Ubo\").replace(\"Fragment\", \"Ubo\");\n }\n includeFile = includeFile + \"Declaration\";\n }\n if (options.includesShadersStore[includeFile]) {\n // Substitution\n let includeContent = options.includesShadersStore[includeFile];\n if (match[2]) {\n const splits = match[3].split(\",\");\n for (let index = 0; index < splits.length; index += 2) {\n const source = new RegExp(splits[index], \"g\");\n const dest = splits[index + 1];\n includeContent = includeContent.replace(source, dest);\n }\n }\n if (match[4]) {\n const indexString = match[5];\n if (indexString.indexOf(\"..\") !== -1) {\n const indexSplits = indexString.split(\"..\");\n const minIndex = parseInt(indexSplits[0]);\n let maxIndex = parseInt(indexSplits[1]);\n let sourceIncludeContent = includeContent.slice(0);\n includeContent = \"\";\n if (isNaN(maxIndex)) {\n maxIndex = options.indexParameters[indexSplits[1]];\n }\n for (let i = minIndex; i < maxIndex; i++) {\n if (!options.supportsUniformBuffers) {\n // Ubo replacement\n sourceIncludeContent = sourceIncludeContent.replace(regexLightX, (str, p1) => {\n return p1 + \"{X}\";\n });\n }\n includeContent += sourceIncludeContent.replace(regexX, i.toString()) + \"\\n\";\n }\n }\n else {\n if (!options.supportsUniformBuffers) {\n // Ubo replacement\n includeContent = includeContent.replace(regexLightX, (str, p1) => {\n return p1 + \"{X}\";\n });\n }\n includeContent = includeContent.replace(regexX, indexString);\n }\n }\n // Replace\n // Split all parts on match[0] and intersperse the parts with the include content\n const newParts = [];\n for (const part of parts) {\n const splitPart = part.split(match[0]);\n for (let i = 0; i < splitPart.length - 1; i++) {\n newParts.push(splitPart[i]);\n newParts.push(includeContent);\n }\n newParts.push(splitPart[splitPart.length - 1]);\n }\n parts = newParts;\n keepProcessing = keepProcessing || includeContent.indexOf(\"#include<\") >= 0 || includeContent.indexOf(\"#include <\") >= 0;\n }\n else {\n const includeShaderUrl = options.shadersRepository + \"ShadersInclude/\" + includeFile + \".fx\";\n ShaderProcessor._FileToolsLoadFile(includeShaderUrl, (fileContent) => {\n options.includesShadersStore[includeFile] = fileContent;\n this._ProcessIncludes(parts.join(\"\"), options, callback);\n });\n return;\n }\n }\n reusableMatches.length = 0;\n returnValue = parts.join(\"\");\n if (keepProcessing) {\n this._ProcessIncludes(returnValue.toString(), options, callback);\n }\n else {\n callback(returnValue);\n }\n }\n /**\n * Loads a file from a url\n * @param url url to load\n * @param onSuccess callback called when the file successfully loads\n * @param onProgress callback called while file is loading (if the server supports this mode)\n * @param offlineProvider defines the offline provider for caching\n * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer\n * @param onError callback called when the file fails to load\n * @returns a file request object\n * @internal\n */\n static _FileToolsLoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) {\n throw _WarnImport(\"FileTools\");\n }\n}\nShaderProcessor._MoveCursorRegex = /(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;\n//# sourceMappingURL=shaderProcessor.js.map","import { ShaderLanguage } from \"../../Materials/shaderLanguage.js\";\nconst varyingRegex = /(flat\\s)?\\s*varying\\s*.*/;\n/** @internal */\nexport class WebGL2ShaderProcessor {\n constructor() {\n this.shaderLanguage = ShaderLanguage.GLSL;\n }\n attributeProcessor(attribute) {\n return attribute.replace(\"attribute\", \"in\");\n }\n varyingCheck(varying, _isFragment) {\n return varyingRegex.test(varying);\n }\n varyingProcessor(varying, isFragment) {\n return varying.replace(\"varying\", isFragment ? \"in\" : \"out\");\n }\n postProcessor(code, defines, isFragment) {\n const hasDrawBuffersExtension = code.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;\n // Remove extensions\n const regex = /#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;\n code = code.replace(regex, \"\");\n // Replace instructions\n code = code.replace(/texture2D\\s*\\(/g, \"texture(\");\n if (isFragment) {\n code = code.replace(/texture2DLodEXT\\s*\\(/g, \"textureLod(\");\n code = code.replace(/textureCubeLodEXT\\s*\\(/g, \"textureLod(\");\n code = code.replace(/textureCube\\s*\\(/g, \"texture(\");\n code = code.replace(/gl_FragDepthEXT/g, \"gl_FragDepth\");\n code = code.replace(/gl_FragColor/g, \"glFragColor\");\n code = code.replace(/gl_FragData/g, \"glFragData\");\n code = code.replace(/void\\s+?main\\s*\\(/g, (hasDrawBuffersExtension ? \"\" : \"layout(location = 0) out vec4 glFragColor;\\n\") + \"void main(\");\n }\n else {\n const hasMultiviewExtension = defines.indexOf(\"#define MULTIVIEW\") !== -1;\n if (hasMultiviewExtension) {\n return \"#extension GL_OVR_multiview2 : require\\nlayout (num_views = 2) in;\\n\" + code;\n }\n }\n return code;\n }\n}\n//# sourceMappingURL=webGL2ShaderProcessors.js.map","/** @internal */\nexport class WebGLHardwareTexture {\n get underlyingResource() {\n return this._webGLTexture;\n }\n constructor(existingTexture = null, context) {\n // There can be multiple buffers for a single WebGL texture because different layers of a 2DArrayTexture / 3DTexture\n // or different faces of a cube texture can be bound to different render targets at the same time.\n this._MSAARenderBuffers = null;\n this._context = context;\n if (!existingTexture) {\n existingTexture = context.createTexture();\n if (!existingTexture) {\n throw new Error(\"Unable to create webGL texture\");\n }\n }\n this.set(existingTexture);\n }\n setUsage() { }\n set(hardwareTexture) {\n this._webGLTexture = hardwareTexture;\n }\n reset() {\n this._webGLTexture = null;\n this._MSAARenderBuffers = null;\n }\n addMSAARenderBuffer(buffer) {\n if (!this._MSAARenderBuffers) {\n this._MSAARenderBuffers = [];\n }\n this._MSAARenderBuffers.push(buffer);\n }\n releaseMSAARenderBuffers() {\n if (this._MSAARenderBuffers) {\n for (const buffer of this._MSAARenderBuffers) {\n this._context.deleteRenderbuffer(buffer);\n }\n this._MSAARenderBuffers = null;\n }\n }\n release() {\n this.releaseMSAARenderBuffers();\n if (this._webGLTexture) {\n this._context.deleteTexture(this._webGLTexture);\n }\n this.reset();\n }\n}\n//# sourceMappingURL=webGLHardwareTexture.js.map","/** @internal */\nexport class WebGLPipelineContext {\n constructor() {\n this._valueCache = {};\n this.vertexCompilationError = null;\n this.fragmentCompilationError = null;\n this.programLinkError = null;\n this.programValidationError = null;\n }\n get isAsync() {\n return this.isParallelCompiled;\n }\n get isReady() {\n if (this.program) {\n if (this.isParallelCompiled) {\n return this.engine._isRenderingStateCompiled(this);\n }\n return true;\n }\n return false;\n }\n _handlesSpectorRebuildCallback(onCompiled) {\n if (onCompiled && this.program) {\n onCompiled(this.program);\n }\n }\n _fillEffectInformation(effect, uniformBuffersNames, uniformsNames, uniforms, samplerList, samplers, attributesNames, attributes) {\n const engine = this.engine;\n if (engine.supportsUniformBuffers) {\n for (const name in uniformBuffersNames) {\n effect.bindUniformBlock(name, uniformBuffersNames[name]);\n }\n }\n const effectAvailableUniforms = this.engine.getUniforms(this, uniformsNames);\n effectAvailableUniforms.forEach((uniform, index) => {\n uniforms[uniformsNames[index]] = uniform;\n });\n this._uniforms = uniforms;\n let index;\n for (index = 0; index < samplerList.length; index++) {\n const sampler = effect.getUniform(samplerList[index]);\n if (sampler == null) {\n samplerList.splice(index, 1);\n index--;\n }\n }\n samplerList.forEach((name, index) => {\n samplers[name] = index;\n });\n for (const attr of engine.getAttributes(this, attributesNames)) {\n attributes.push(attr);\n }\n }\n /**\n * Release all associated resources.\n **/\n dispose() {\n this._uniforms = {};\n }\n /**\n * @internal\n */\n _cacheMatrix(uniformName, matrix) {\n const cache = this._valueCache[uniformName];\n const flag = matrix.updateFlag;\n if (cache !== undefined && cache === flag) {\n return false;\n }\n this._valueCache[uniformName] = flag;\n return true;\n }\n /**\n * @internal\n */\n _cacheFloat2(uniformName, x, y) {\n let cache = this._valueCache[uniformName];\n if (!cache || cache.length !== 2) {\n cache = [x, y];\n this._valueCache[uniformName] = cache;\n return true;\n }\n let changed = false;\n if (cache[0] !== x) {\n cache[0] = x;\n changed = true;\n }\n if (cache[1] !== y) {\n cache[1] = y;\n changed = true;\n }\n return changed;\n }\n /**\n * @internal\n */\n _cacheFloat3(uniformName, x, y, z) {\n let cache = this._valueCache[uniformName];\n if (!cache || cache.length !== 3) {\n cache = [x, y, z];\n this._valueCache[uniformName] = cache;\n return true;\n }\n let changed = false;\n if (cache[0] !== x) {\n cache[0] = x;\n changed = true;\n }\n if (cache[1] !== y) {\n cache[1] = y;\n changed = true;\n }\n if (cache[2] !== z) {\n cache[2] = z;\n changed = true;\n }\n return changed;\n }\n /**\n * @internal\n */\n _cacheFloat4(uniformName, x, y, z, w) {\n let cache = this._valueCache[uniformName];\n if (!cache || cache.length !== 4) {\n cache = [x, y, z, w];\n this._valueCache[uniformName] = cache;\n return true;\n }\n let changed = false;\n if (cache[0] !== x) {\n cache[0] = x;\n changed = true;\n }\n if (cache[1] !== y) {\n cache[1] = y;\n changed = true;\n }\n if (cache[2] !== z) {\n cache[2] = z;\n changed = true;\n }\n if (cache[3] !== w) {\n cache[3] = w;\n changed = true;\n }\n return changed;\n }\n /**\n * Sets an integer value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value Value to be set.\n */\n setInt(uniformName, value) {\n const cache = this._valueCache[uniformName];\n if (cache !== undefined && cache === value) {\n return;\n }\n if (this.engine.setInt(this._uniforms[uniformName], value)) {\n this._valueCache[uniformName] = value;\n }\n }\n /**\n * Sets a int2 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First int in int2.\n * @param y Second int in int2.\n */\n setInt2(uniformName, x, y) {\n if (this._cacheFloat2(uniformName, x, y)) {\n if (!this.engine.setInt2(this._uniforms[uniformName], x, y)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a int3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First int in int3.\n * @param y Second int in int3.\n * @param z Third int in int3.\n */\n setInt3(uniformName, x, y, z) {\n if (this._cacheFloat3(uniformName, x, y, z)) {\n if (!this.engine.setInt3(this._uniforms[uniformName], x, y, z)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a int4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First int in int4.\n * @param y Second int in int4.\n * @param z Third int in int4.\n * @param w Fourth int in int4.\n */\n setInt4(uniformName, x, y, z, w) {\n if (this._cacheFloat4(uniformName, x, y, z, w)) {\n if (!this.engine.setInt4(this._uniforms[uniformName], x, y, z, w)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets an int array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setIntArray(uniformName, array) {\n this._valueCache[uniformName] = null;\n this.engine.setIntArray(this._uniforms[uniformName], array);\n }\n /**\n * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setIntArray2(uniformName, array) {\n this._valueCache[uniformName] = null;\n this.engine.setIntArray2(this._uniforms[uniformName], array);\n }\n /**\n * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setIntArray3(uniformName, array) {\n this._valueCache[uniformName] = null;\n this.engine.setIntArray3(this._uniforms[uniformName], array);\n }\n /**\n * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setIntArray4(uniformName, array) {\n this._valueCache[uniformName] = null;\n this.engine.setIntArray4(this._uniforms[uniformName], array);\n }\n /**\n * Sets an unsigned integer value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value Value to be set.\n */\n setUInt(uniformName, value) {\n const cache = this._valueCache[uniformName];\n if (cache !== undefined && cache === value) {\n return;\n }\n if (this.engine.setUInt(this._uniforms[uniformName], value)) {\n this._valueCache[uniformName] = value;\n }\n }\n /**\n * Sets an unsigned int2 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First unsigned int in uint2.\n * @param y Second unsigned int in uint2.\n */\n setUInt2(uniformName, x, y) {\n if (this._cacheFloat2(uniformName, x, y)) {\n if (!this.engine.setUInt2(this._uniforms[uniformName], x, y)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets an unsigned int3 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First unsigned int in uint3.\n * @param y Second unsigned int in uint3.\n * @param z Third unsigned int in uint3.\n */\n setUInt3(uniformName, x, y, z) {\n if (this._cacheFloat3(uniformName, x, y, z)) {\n if (!this.engine.setUInt3(this._uniforms[uniformName], x, y, z)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets an unsigned int4 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First unsigned int in uint4.\n * @param y Second unsigned int in uint4.\n * @param z Third unsigned int in uint4.\n * @param w Fourth unsigned int in uint4.\n */\n setUInt4(uniformName, x, y, z, w) {\n if (this._cacheFloat4(uniformName, x, y, z, w)) {\n if (!this.engine.setUInt4(this._uniforms[uniformName], x, y, z, w)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets an unsigned int array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setUIntArray(uniformName, array) {\n this._valueCache[uniformName] = null;\n this.engine.setUIntArray(this._uniforms[uniformName], array);\n }\n /**\n * Sets an unsigned int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setUIntArray2(uniformName, array) {\n this._valueCache[uniformName] = null;\n this.engine.setUIntArray2(this._uniforms[uniformName], array);\n }\n /**\n * Sets an unsigned int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setUIntArray3(uniformName, array) {\n this._valueCache[uniformName] = null;\n this.engine.setUIntArray3(this._uniforms[uniformName], array);\n }\n /**\n * Sets an unsigned int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setUIntArray4(uniformName, array) {\n this._valueCache[uniformName] = null;\n this.engine.setUIntArray4(this._uniforms[uniformName], array);\n }\n /**\n * Sets an array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setArray(uniformName, array) {\n this._valueCache[uniformName] = null;\n this.engine.setArray(this._uniforms[uniformName], array);\n }\n /**\n * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setArray2(uniformName, array) {\n this._valueCache[uniformName] = null;\n this.engine.setArray2(this._uniforms[uniformName], array);\n }\n /**\n * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setArray3(uniformName, array) {\n this._valueCache[uniformName] = null;\n this.engine.setArray3(this._uniforms[uniformName], array);\n }\n /**\n * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n */\n setArray4(uniformName, array) {\n this._valueCache[uniformName] = null;\n this.engine.setArray4(this._uniforms[uniformName], array);\n }\n /**\n * Sets matrices on a uniform variable.\n * @param uniformName Name of the variable.\n * @param matrices matrices to be set.\n */\n setMatrices(uniformName, matrices) {\n if (!matrices) {\n return;\n }\n this._valueCache[uniformName] = null;\n this.engine.setMatrices(this._uniforms[uniformName], matrices);\n }\n /**\n * Sets matrix on a uniform variable.\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n */\n setMatrix(uniformName, matrix) {\n if (this._cacheMatrix(uniformName, matrix)) {\n if (!this.engine.setMatrices(this._uniforms[uniformName], matrix.toArray())) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a 3x3 matrix on a uniform variable. (Specified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n */\n setMatrix3x3(uniformName, matrix) {\n this._valueCache[uniformName] = null;\n this.engine.setMatrix3x3(this._uniforms[uniformName], matrix);\n }\n /**\n * Sets a 2x2 matrix on a uniform variable. (Specified as [1,2,3,4] will result in [1,2][3,4] matrix)\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n */\n setMatrix2x2(uniformName, matrix) {\n this._valueCache[uniformName] = null;\n this.engine.setMatrix2x2(this._uniforms[uniformName], matrix);\n }\n /**\n * Sets a float on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value value to be set.\n * @returns this effect.\n */\n setFloat(uniformName, value) {\n const cache = this._valueCache[uniformName];\n if (cache !== undefined && cache === value) {\n return;\n }\n if (this.engine.setFloat(this._uniforms[uniformName], value)) {\n this._valueCache[uniformName] = value;\n }\n }\n /**\n * Sets a Vector2 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector2 vector2 to be set.\n */\n setVector2(uniformName, vector2) {\n if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {\n if (!this.engine.setFloat2(this._uniforms[uniformName], vector2.x, vector2.y)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a float2 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float2.\n * @param y Second float in float2.\n */\n setFloat2(uniformName, x, y) {\n if (this._cacheFloat2(uniformName, x, y)) {\n if (!this.engine.setFloat2(this._uniforms[uniformName], x, y)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a Vector3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector3 Value to be set.\n */\n setVector3(uniformName, vector3) {\n if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {\n if (!this.engine.setFloat3(this._uniforms[uniformName], vector3.x, vector3.y, vector3.z)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a float3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float3.\n * @param y Second float in float3.\n * @param z Third float in float3.\n */\n setFloat3(uniformName, x, y, z) {\n if (this._cacheFloat3(uniformName, x, y, z)) {\n if (!this.engine.setFloat3(this._uniforms[uniformName], x, y, z)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a Vector4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector4 Value to be set.\n */\n setVector4(uniformName, vector4) {\n if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {\n if (!this.engine.setFloat4(this._uniforms[uniformName], vector4.x, vector4.y, vector4.z, vector4.w)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a Quaternion on a uniform variable.\n * @param uniformName Name of the variable.\n * @param quaternion Value to be set.\n */\n setQuaternion(uniformName, quaternion) {\n if (this._cacheFloat4(uniformName, quaternion.x, quaternion.y, quaternion.z, quaternion.w)) {\n if (!this.engine.setFloat4(this._uniforms[uniformName], quaternion.x, quaternion.y, quaternion.z, quaternion.w)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a float4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float4.\n * @param y Second float in float4.\n * @param z Third float in float4.\n * @param w Fourth float in float4.\n * @returns this effect.\n */\n setFloat4(uniformName, x, y, z, w) {\n if (this._cacheFloat4(uniformName, x, y, z, w)) {\n if (!this.engine.setFloat4(this._uniforms[uniformName], x, y, z, w)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a Color3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param color3 Value to be set.\n */\n setColor3(uniformName, color3) {\n if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {\n if (!this.engine.setFloat3(this._uniforms[uniformName], color3.r, color3.g, color3.b)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a Color4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param color3 Value to be set.\n * @param alpha Alpha value to be set.\n */\n setColor4(uniformName, color3, alpha) {\n if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {\n if (!this.engine.setFloat4(this._uniforms[uniformName], color3.r, color3.g, color3.b, alpha)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n /**\n * Sets a Color4 on a uniform variable\n * @param uniformName defines the name of the variable\n * @param color4 defines the value to be set\n */\n setDirectColor4(uniformName, color4) {\n if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {\n if (!this.engine.setFloat4(this._uniforms[uniformName], color4.r, color4.g, color4.b, color4.a)) {\n this._valueCache[uniformName] = null;\n }\n }\n }\n _getVertexShaderCode() {\n return this.vertexShader ? this.engine._getShaderSource(this.vertexShader) : null;\n }\n _getFragmentShaderCode() {\n return this.fragmentShader ? this.engine._getShaderSource(this.fragmentShader) : null;\n }\n}\n//# sourceMappingURL=webGLPipelineContext.js.map","import { ShaderLanguage } from \"../../Materials/shaderLanguage.js\";\n/** @internal */\nexport class WebGLShaderProcessor {\n constructor() {\n this.shaderLanguage = ShaderLanguage.GLSL;\n }\n postProcessor(code, defines, isFragment, processingContext, engine) {\n // Remove extensions\n if (!engine.getCaps().drawBuffersExtension) {\n // even if enclosed in #if/#endif, IE11 does parse the #extension declaration, so we need to remove it altogether\n const regex = /#extension.+GL_EXT_draw_buffers.+(enable|require)/g;\n code = code.replace(regex, \"\");\n }\n return code;\n }\n}\n//# sourceMappingURL=webGLShaderProcessors.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { InternalTexture, InternalTextureSource } from \"../Materials/Textures/internalTexture.js\";\nimport { IsDocumentAvailable, IsWindowObjectExist } from \"../Misc/domManagement.js\";\nimport { EngineStore } from \"./engineStore.js\";\nimport { _WarnImport } from \"../Misc/devTools.js\";\nimport { ThinEngine } from \"./thinEngine.js\";\n\nimport { PerformanceMonitor } from \"../Misc/performanceMonitor.js\";\nimport { PerfCounter } from \"../Misc/perfCounter.js\";\nimport { WebGLDataBuffer } from \"../Meshes/WebGL/webGLDataBuffer.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { WebGLHardwareTexture } from \"./WebGL/webGLHardwareTexture.js\";\nimport \"./Extensions/engine.alpha.js\";\nimport \"./Extensions/engine.readTexture.js\";\nimport \"./Extensions/engine.dynamicBuffer.js\";\n/**\n * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio\n */\nexport class Engine extends ThinEngine {\n /**\n * Returns the current npm package of the sdk\n */\n // Not mixed with Version for tooling purpose.\n static get NpmPackage() {\n return ThinEngine.NpmPackage;\n }\n /**\n * Returns the current version of the framework\n */\n static get Version() {\n return ThinEngine.Version;\n }\n /** Gets the list of created engines */\n static get Instances() {\n return EngineStore.Instances;\n }\n /**\n * Gets the latest created engine\n */\n static get LastCreatedEngine() {\n return EngineStore.LastCreatedEngine;\n }\n /**\n * Gets the latest created scene\n */\n static get LastCreatedScene() {\n return EngineStore.LastCreatedScene;\n }\n /** @internal */\n /**\n * Engine abstraction for loading and creating an image bitmap from a given source string.\n * @param imageSource source to load the image from.\n * @param options An object that sets options for the image's extraction.\n * @returns ImageBitmap.\n */\n _createImageBitmapFromSource(imageSource, options) {\n const promise = new Promise((resolve, reject) => {\n const image = new Image();\n image.onload = () => {\n image.decode().then(() => {\n this.createImageBitmap(image, options).then((imageBitmap) => {\n resolve(imageBitmap);\n });\n });\n };\n image.onerror = () => {\n reject(`Error loading image ${image.src}`);\n };\n image.src = imageSource;\n });\n return promise;\n }\n /**\n * Engine abstraction for createImageBitmap\n * @param image source for image\n * @param options An object that sets options for the image's extraction.\n * @returns ImageBitmap\n */\n createImageBitmap(image, options) {\n return createImageBitmap(image, options);\n }\n /**\n * Resize an image and returns the image data as an uint8array\n * @param image image to resize\n * @param bufferWidth destination buffer width\n * @param bufferHeight destination buffer height\n * @returns an uint8array containing RGBA values of bufferWidth * bufferHeight size\n */\n resizeImageBitmap(image, bufferWidth, bufferHeight) {\n const canvas = this.createCanvas(bufferWidth, bufferHeight);\n const context = canvas.getContext(\"2d\");\n if (!context) {\n throw new Error(\"Unable to get 2d context for resizeImageBitmap\");\n }\n context.drawImage(image, 0, 0);\n // Create VertexData from map data\n // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949\n const buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;\n return buffer;\n }\n /**\n * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation\n * @param flag defines which part of the materials must be marked as dirty\n * @param predicate defines a predicate used to filter which materials should be affected\n */\n static MarkAllMaterialsAsDirty(flag, predicate) {\n for (let engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {\n const engine = Engine.Instances[engineIndex];\n for (let sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {\n engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);\n }\n }\n }\n /**\n * Method called to create the default loading screen.\n * This can be overridden in your own app.\n * @param canvas The rendering canvas element\n * @returns The loading screen\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n static DefaultLoadingScreenFactory(canvas) {\n throw _WarnImport(\"LoadingScreen\");\n }\n get _supportsHardwareTextureRescaling() {\n return !!Engine._RescalePostProcessFactory;\n }\n /**\n * Gets the performance monitor attached to this engine\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#engineinstrumentation\n */\n get performanceMonitor() {\n return this._performanceMonitor;\n }\n /**\n * (WebGPU only) True (default) to be in compatibility mode, meaning rendering all existing scenes without artifacts (same rendering than WebGL).\n * Setting the property to false will improve performances but may not work in some scenes if some precautions are not taken.\n * See https://doc.babylonjs.com/setup/support/webGPU/webGPUOptimization/webGPUNonCompatibilityMode for more details\n */\n get compatibilityMode() {\n return this._compatibilityMode;\n }\n set compatibilityMode(mode) {\n // not supported in WebGL\n this._compatibilityMode = true;\n }\n // Events\n /**\n * Gets the HTML element used to attach event listeners\n * @returns a HTML element\n */\n getInputElement() {\n return this._renderingCanvas;\n }\n /**\n * Creates a new engine\n * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which already used the WebGL context\n * @param antialias defines enable antialiasing (default: false)\n * @param options defines further options to be sent to the getContext() function\n * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)\n */\n constructor(canvasOrContext, antialias, options, adaptToDeviceRatio = false) {\n super(canvasOrContext, antialias, options, adaptToDeviceRatio);\n // Members\n /**\n * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest\n **/\n this.enableOfflineSupport = false;\n /**\n * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (js will always consider the database is up to date)\n **/\n this.disableManifestCheck = false;\n /**\n * Gets or sets a boolean to enable/disable the context menu (right-click) from appearing on the main canvas\n */\n this.disableContextMenu = true;\n /**\n * Gets the list of created scenes\n */\n this.scenes = new Array();\n /** @internal */\n this._virtualScenes = new Array();\n /**\n * Event raised when a new scene is created\n */\n this.onNewSceneAddedObservable = new Observable();\n /**\n * Gets the list of created postprocesses\n */\n this.postProcesses = new Array();\n /**\n * Gets a boolean indicating if the pointer is currently locked\n */\n this.isPointerLock = false;\n // Observables\n /**\n * Observable event triggered each time the rendering canvas is resized\n */\n this.onResizeObservable = new Observable();\n /**\n * Observable event triggered each time the canvas loses focus\n */\n this.onCanvasBlurObservable = new Observable();\n /**\n * Observable event triggered each time the canvas gains focus\n */\n this.onCanvasFocusObservable = new Observable();\n /**\n * Observable event triggered each time the canvas receives pointerout event\n */\n this.onCanvasPointerOutObservable = new Observable();\n /**\n * Observable raised when the engine begins a new frame\n */\n this.onBeginFrameObservable = new Observable();\n /**\n * If set, will be used to request the next animation frame for the render loop\n */\n this.customAnimationFrameRequester = null;\n /**\n * Observable raised when the engine ends the current frame\n */\n this.onEndFrameObservable = new Observable();\n /**\n * Observable raised when the engine is about to compile a shader\n */\n this.onBeforeShaderCompilationObservable = new Observable();\n /**\n * Observable raised when the engine has just compiled a shader\n */\n this.onAfterShaderCompilationObservable = new Observable();\n // Deterministic lockstepMaxSteps\n this._deterministicLockstep = false;\n this._lockstepMaxSteps = 4;\n this._timeStep = 1 / 60;\n // FPS\n this._fps = 60;\n this._deltaTime = 0;\n /** @internal */\n this._drawCalls = new PerfCounter();\n /** Gets or sets the tab index to set to the rendering canvas. 1 is the minimum value to set to be able to capture keyboard events */\n this.canvasTabIndex = 1;\n /**\n * Turn this value on if you want to pause FPS computation when in background\n */\n this.disablePerformanceMonitorInBackground = false;\n this._performanceMonitor = new PerformanceMonitor();\n this._compatibilityMode = true;\n /**\n * Gets or sets the current render pass id\n */\n this.currentRenderPassId = 0;\n this._renderPassNames = [\"main\"];\n Engine.Instances.push(this);\n if (!canvasOrContext) {\n return;\n }\n this._features.supportRenderPasses = true;\n options = this._creationOptions;\n if (canvasOrContext.getContext) {\n const canvas = canvasOrContext;\n this._sharedInit(canvas);\n this._connectVREvents();\n }\n // Load WebVR Devices\n this._prepareVRComponent();\n if (options.autoEnableWebVR) {\n this.initWebVR();\n }\n }\n _initGLContext() {\n super._initGLContext();\n this._rescalePostProcess = null;\n }\n /**\n * Shared initialization across engines types.\n * @param canvas The canvas associated with this instance of the engine.\n */\n _sharedInit(canvas) {\n super._sharedInit(canvas);\n this._onCanvasFocus = () => {\n this.onCanvasFocusObservable.notifyObservers(this);\n };\n this._onCanvasBlur = () => {\n this.onCanvasBlurObservable.notifyObservers(this);\n };\n this._onCanvasContextMenu = (evt) => {\n if (this.disableContextMenu) {\n evt.preventDefault();\n }\n };\n canvas.addEventListener(\"focus\", this._onCanvasFocus);\n canvas.addEventListener(\"blur\", this._onCanvasBlur);\n canvas.addEventListener(\"contextmenu\", this._onCanvasContextMenu);\n this._onBlur = () => {\n if (this.disablePerformanceMonitorInBackground) {\n this._performanceMonitor.disable();\n }\n this._windowIsBackground = true;\n };\n this._onFocus = () => {\n if (this.disablePerformanceMonitorInBackground) {\n this._performanceMonitor.enable();\n }\n this._windowIsBackground = false;\n };\n this._onCanvasPointerOut = (ev) => {\n // Check that the element at the point of the pointer out isn't the canvas and if it isn't, notify observers\n // Note: This is a workaround for a bug with Safari\n if (document.elementFromPoint(ev.clientX, ev.clientY) !== canvas) {\n this.onCanvasPointerOutObservable.notifyObservers(ev);\n }\n };\n const hostWindow = this.getHostWindow(); // it calls IsWindowObjectExist()\n if (hostWindow && typeof hostWindow.addEventListener === \"function\") {\n hostWindow.addEventListener(\"blur\", this._onBlur);\n hostWindow.addEventListener(\"focus\", this._onFocus);\n }\n canvas.addEventListener(\"pointerout\", this._onCanvasPointerOut);\n if (!this._creationOptions.doNotHandleTouchAction) {\n this._disableTouchAction();\n }\n // Create Audio Engine if needed.\n if (!Engine.audioEngine && this._creationOptions.audioEngine && Engine.AudioEngineFactory) {\n Engine.audioEngine = Engine.AudioEngineFactory(this.getRenderingCanvas(), this.getAudioContext(), this.getAudioDestination());\n }\n if (IsDocumentAvailable()) {\n // Fullscreen\n this._onFullscreenChange = () => {\n this.isFullscreen = !!document.fullscreenElement;\n // Pointer lock\n if (this.isFullscreen && this._pointerLockRequested && canvas) {\n Engine._RequestPointerlock(canvas);\n }\n };\n document.addEventListener(\"fullscreenchange\", this._onFullscreenChange, false);\n document.addEventListener(\"webkitfullscreenchange\", this._onFullscreenChange, false);\n // Pointer lock\n this._onPointerLockChange = () => {\n this.isPointerLock = document.pointerLockElement === canvas;\n };\n document.addEventListener(\"pointerlockchange\", this._onPointerLockChange, false);\n document.addEventListener(\"webkitpointerlockchange\", this._onPointerLockChange, false);\n }\n this.enableOfflineSupport = Engine.OfflineProviderFactory !== undefined;\n this._deterministicLockstep = !!this._creationOptions.deterministicLockstep;\n this._lockstepMaxSteps = this._creationOptions.lockstepMaxSteps || 0;\n this._timeStep = this._creationOptions.timeStep || 1 / 60;\n }\n /** @internal */\n _verifyPointerLock() {\n var _a;\n (_a = this._onPointerLockChange) === null || _a === void 0 ? void 0 : _a.call(this);\n }\n /**\n * Gets current aspect ratio\n * @param viewportOwner defines the camera to use to get the aspect ratio\n * @param useScreen defines if screen size must be used (or the current render target if any)\n * @returns a number defining the aspect ratio\n */\n getAspectRatio(viewportOwner, useScreen = false) {\n const viewport = viewportOwner.viewport;\n return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);\n }\n /**\n * Gets current screen aspect ratio\n * @returns a number defining the aspect ratio\n */\n getScreenAspectRatio() {\n return this.getRenderWidth(true) / this.getRenderHeight(true);\n }\n /**\n * Gets the client rect of the HTML canvas attached with the current webGL context\n * @returns a client rectangle\n */\n getRenderingCanvasClientRect() {\n if (!this._renderingCanvas) {\n return null;\n }\n return this._renderingCanvas.getBoundingClientRect();\n }\n /**\n * Gets the client rect of the HTML element used for events\n * @returns a client rectangle\n */\n getInputElementClientRect() {\n if (!this._renderingCanvas) {\n return null;\n }\n return this.getInputElement().getBoundingClientRect();\n }\n /**\n * Gets a boolean indicating that the engine is running in deterministic lock step mode\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep\n * @returns true if engine is in deterministic lock step mode\n */\n isDeterministicLockStep() {\n return this._deterministicLockstep;\n }\n /**\n * Gets the max steps when engine is running in deterministic lock step\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep\n * @returns the max steps\n */\n getLockstepMaxSteps() {\n return this._lockstepMaxSteps;\n }\n /**\n * Returns the time in ms between steps when using deterministic lock step.\n * @returns time step in (ms)\n */\n getTimeStep() {\n return this._timeStep * 1000;\n }\n /**\n * Force the mipmap generation for the given render target texture\n * @param texture defines the render target texture to use\n * @param unbind defines whether or not to unbind the texture after generation. Defaults to true.\n */\n generateMipMapsForCubemap(texture, unbind = true) {\n if (texture.generateMipMaps) {\n const gl = this._gl;\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);\n gl.generateMipmap(gl.TEXTURE_CUBE_MAP);\n if (unbind) {\n this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);\n }\n }\n }\n /** States */\n /**\n * Gets a boolean indicating if depth writing is enabled\n * @returns the current depth writing state\n */\n getDepthWrite() {\n return this._depthCullingState.depthMask;\n }\n /**\n * Enable or disable depth writing\n * @param enable defines the state to set\n */\n setDepthWrite(enable) {\n this._depthCullingState.depthMask = enable;\n }\n /**\n * Gets a boolean indicating if stencil buffer is enabled\n * @returns the current stencil buffer state\n */\n getStencilBuffer() {\n return this._stencilState.stencilTest;\n }\n /**\n * Enable or disable the stencil buffer\n * @param enable defines if the stencil buffer must be enabled or disabled\n */\n setStencilBuffer(enable) {\n this._stencilState.stencilTest = enable;\n }\n /**\n * Gets the current stencil mask\n * @returns a number defining the new stencil mask to use\n */\n getStencilMask() {\n return this._stencilState.stencilMask;\n }\n /**\n * Sets the current stencil mask\n * @param mask defines the new stencil mask to use\n */\n setStencilMask(mask) {\n this._stencilState.stencilMask = mask;\n }\n /**\n * Gets the current stencil function\n * @returns a number defining the stencil function to use\n */\n getStencilFunction() {\n return this._stencilState.stencilFunc;\n }\n /**\n * Gets the current stencil reference value\n * @returns a number defining the stencil reference value to use\n */\n getStencilFunctionReference() {\n return this._stencilState.stencilFuncRef;\n }\n /**\n * Gets the current stencil mask\n * @returns a number defining the stencil mask to use\n */\n getStencilFunctionMask() {\n return this._stencilState.stencilFuncMask;\n }\n /**\n * Sets the current stencil function\n * @param stencilFunc defines the new stencil function to use\n */\n setStencilFunction(stencilFunc) {\n this._stencilState.stencilFunc = stencilFunc;\n }\n /**\n * Sets the current stencil reference\n * @param reference defines the new stencil reference to use\n */\n setStencilFunctionReference(reference) {\n this._stencilState.stencilFuncRef = reference;\n }\n /**\n * Sets the current stencil mask\n * @param mask defines the new stencil mask to use\n */\n setStencilFunctionMask(mask) {\n this._stencilState.stencilFuncMask = mask;\n }\n /**\n * Gets the current stencil operation when stencil fails\n * @returns a number defining stencil operation to use when stencil fails\n */\n getStencilOperationFail() {\n return this._stencilState.stencilOpStencilFail;\n }\n /**\n * Gets the current stencil operation when depth fails\n * @returns a number defining stencil operation to use when depth fails\n */\n getStencilOperationDepthFail() {\n return this._stencilState.stencilOpDepthFail;\n }\n /**\n * Gets the current stencil operation when stencil passes\n * @returns a number defining stencil operation to use when stencil passes\n */\n getStencilOperationPass() {\n return this._stencilState.stencilOpStencilDepthPass;\n }\n /**\n * Sets the stencil operation to use when stencil fails\n * @param operation defines the stencil operation to use when stencil fails\n */\n setStencilOperationFail(operation) {\n this._stencilState.stencilOpStencilFail = operation;\n }\n /**\n * Sets the stencil operation to use when depth fails\n * @param operation defines the stencil operation to use when depth fails\n */\n setStencilOperationDepthFail(operation) {\n this._stencilState.stencilOpDepthFail = operation;\n }\n /**\n * Sets the stencil operation to use when stencil passes\n * @param operation defines the stencil operation to use when stencil passes\n */\n setStencilOperationPass(operation) {\n this._stencilState.stencilOpStencilDepthPass = operation;\n }\n /**\n * Sets a boolean indicating if the dithering state is enabled or disabled\n * @param value defines the dithering state\n */\n setDitheringState(value) {\n if (value) {\n this._gl.enable(this._gl.DITHER);\n }\n else {\n this._gl.disable(this._gl.DITHER);\n }\n }\n /**\n * Sets a boolean indicating if the rasterizer state is enabled or disabled\n * @param value defines the rasterizer state\n */\n setRasterizerState(value) {\n if (value) {\n this._gl.disable(this._gl.RASTERIZER_DISCARD);\n }\n else {\n this._gl.enable(this._gl.RASTERIZER_DISCARD);\n }\n }\n /**\n * Gets the current depth function\n * @returns a number defining the depth function\n */\n getDepthFunction() {\n return this._depthCullingState.depthFunc;\n }\n /**\n * Sets the current depth function\n * @param depthFunc defines the function to use\n */\n setDepthFunction(depthFunc) {\n this._depthCullingState.depthFunc = depthFunc;\n }\n /**\n * Sets the current depth function to GREATER\n */\n setDepthFunctionToGreater() {\n this.setDepthFunction(516);\n }\n /**\n * Sets the current depth function to GEQUAL\n */\n setDepthFunctionToGreaterOrEqual() {\n this.setDepthFunction(518);\n }\n /**\n * Sets the current depth function to LESS\n */\n setDepthFunctionToLess() {\n this.setDepthFunction(513);\n }\n /**\n * Sets the current depth function to LEQUAL\n */\n setDepthFunctionToLessOrEqual() {\n this.setDepthFunction(515);\n }\n /**\n * Caches the the state of the stencil buffer\n */\n cacheStencilState() {\n this._cachedStencilBuffer = this.getStencilBuffer();\n this._cachedStencilFunction = this.getStencilFunction();\n this._cachedStencilMask = this.getStencilMask();\n this._cachedStencilOperationPass = this.getStencilOperationPass();\n this._cachedStencilOperationFail = this.getStencilOperationFail();\n this._cachedStencilOperationDepthFail = this.getStencilOperationDepthFail();\n this._cachedStencilReference = this.getStencilFunctionReference();\n }\n /**\n * Restores the state of the stencil buffer\n */\n restoreStencilState() {\n this.setStencilFunction(this._cachedStencilFunction);\n this.setStencilMask(this._cachedStencilMask);\n this.setStencilBuffer(this._cachedStencilBuffer);\n this.setStencilOperationPass(this._cachedStencilOperationPass);\n this.setStencilOperationFail(this._cachedStencilOperationFail);\n this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail);\n this.setStencilFunctionReference(this._cachedStencilReference);\n }\n /**\n * Directly set the WebGL Viewport\n * @param x defines the x coordinate of the viewport (in screen space)\n * @param y defines the y coordinate of the viewport (in screen space)\n * @param width defines the width of the viewport (in screen space)\n * @param height defines the height of the viewport (in screen space)\n * @returns the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state\n */\n setDirectViewport(x, y, width, height) {\n const currentViewport = this._cachedViewport;\n this._cachedViewport = null;\n this._viewport(x, y, width, height);\n return currentViewport;\n }\n /**\n * Executes a scissor clear (ie. a clear on a specific portion of the screen)\n * @param x defines the x-coordinate of the bottom left corner of the clear rectangle\n * @param y defines the y-coordinate of the corner of the clear rectangle\n * @param width defines the width of the clear rectangle\n * @param height defines the height of the clear rectangle\n * @param clearColor defines the clear color\n */\n scissorClear(x, y, width, height, clearColor) {\n this.enableScissor(x, y, width, height);\n this.clear(clearColor, true, true, true);\n this.disableScissor();\n }\n /**\n * Enable scissor test on a specific rectangle (ie. render will only be executed on a specific portion of the screen)\n * @param x defines the x-coordinate of the bottom left corner of the clear rectangle\n * @param y defines the y-coordinate of the corner of the clear rectangle\n * @param width defines the width of the clear rectangle\n * @param height defines the height of the clear rectangle\n */\n enableScissor(x, y, width, height) {\n const gl = this._gl;\n // Change state\n gl.enable(gl.SCISSOR_TEST);\n gl.scissor(x, y, width, height);\n }\n /**\n * Disable previously set scissor test rectangle\n */\n disableScissor() {\n const gl = this._gl;\n gl.disable(gl.SCISSOR_TEST);\n }\n /**\n * @internal\n */\n _reportDrawCall(numDrawCalls = 1) {\n this._drawCalls.addCount(numDrawCalls, false);\n }\n /**\n * Initializes a webVR display and starts listening to display change events\n * The onVRDisplayChangedObservable will be notified upon these changes\n * @returns The onVRDisplayChangedObservable\n */\n initWebVR() {\n throw _WarnImport(\"WebVRCamera\");\n }\n /** @internal */\n _prepareVRComponent() {\n // Do nothing as the engine side effect will overload it\n }\n /**\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _connectVREvents(canvas, document) {\n // Do nothing as the engine side effect will overload it\n }\n /** @internal */\n _submitVRFrame() {\n // Do nothing as the engine side effect will overload it\n }\n /**\n * Call this function to leave webVR mode\n * Will do nothing if webVR is not supported or if there is no webVR device\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/webVRCamera\n */\n disableVR() {\n // Do nothing as the engine side effect will overload it\n }\n /**\n * Gets a boolean indicating that the system is in VR mode and is presenting\n * @returns true if VR mode is engaged\n */\n isVRPresenting() {\n return false;\n }\n /** @internal */\n _requestVRFrame() {\n // Do nothing as the engine side effect will overload it\n }\n /**\n * @internal\n */\n _loadFileAsync(url, offlineProvider, useArrayBuffer) {\n return new Promise((resolve, reject) => {\n this._loadFile(url, (data) => {\n resolve(data);\n }, undefined, offlineProvider, useArrayBuffer, (request, exception) => {\n reject(exception);\n });\n });\n }\n /**\n * Gets the source code of the vertex shader associated with a specific webGL program\n * @param program defines the program to use\n * @returns a string containing the source code of the vertex shader associated with the program\n */\n getVertexShaderSource(program) {\n const shaders = this._gl.getAttachedShaders(program);\n if (!shaders) {\n return null;\n }\n return this._gl.getShaderSource(shaders[0]);\n }\n /**\n * Gets the source code of the fragment shader associated with a specific webGL program\n * @param program defines the program to use\n * @returns a string containing the source code of the fragment shader associated with the program\n */\n getFragmentShaderSource(program) {\n const shaders = this._gl.getAttachedShaders(program);\n if (!shaders) {\n return null;\n }\n return this._gl.getShaderSource(shaders[1]);\n }\n /**\n * Sets a depth stencil texture from a render target to the according uniform.\n * @param channel The texture channel\n * @param uniform The uniform to set\n * @param texture The render target texture containing the depth stencil texture to apply\n * @param name The texture name\n */\n setDepthStencilTexture(channel, uniform, texture, name) {\n if (channel === undefined) {\n return;\n }\n if (uniform) {\n this._boundUniforms[channel] = uniform;\n }\n if (!texture || !texture.depthStencilTexture) {\n this._setTexture(channel, null, undefined, undefined, name);\n }\n else {\n this._setTexture(channel, texture, false, true, name);\n }\n }\n /**\n * Sets a texture to the webGL context from a postprocess\n * @param channel defines the channel to use\n * @param postProcess defines the source postprocess\n * @param name name of the channel\n */\n setTextureFromPostProcess(channel, postProcess, name) {\n var _a;\n let postProcessInput = null;\n if (postProcess) {\n if (postProcess._forcedOutputTexture) {\n postProcessInput = postProcess._forcedOutputTexture;\n }\n else if (postProcess._textures.data[postProcess._currentRenderTextureInd]) {\n postProcessInput = postProcess._textures.data[postProcess._currentRenderTextureInd];\n }\n }\n this._bindTexture(channel, (_a = postProcessInput === null || postProcessInput === void 0 ? void 0 : postProcessInput.texture) !== null && _a !== void 0 ? _a : null, name);\n }\n /**\n * Binds the output of the passed in post process to the texture channel specified\n * @param channel The channel the texture should be bound to\n * @param postProcess The post process which's output should be bound\n * @param name name of the channel\n */\n setTextureFromPostProcessOutput(channel, postProcess, name) {\n var _a, _b;\n this._bindTexture(channel, (_b = (_a = postProcess === null || postProcess === void 0 ? void 0 : postProcess._outputTexture) === null || _a === void 0 ? void 0 : _a.texture) !== null && _b !== void 0 ? _b : null, name);\n }\n _rebuildBuffers() {\n // Index / Vertex\n for (const scene of this.scenes) {\n scene.resetCachedMaterial();\n scene._rebuildGeometries();\n scene._rebuildTextures();\n }\n for (const scene of this._virtualScenes) {\n scene.resetCachedMaterial();\n scene._rebuildGeometries();\n scene._rebuildTextures();\n }\n super._rebuildBuffers();\n }\n /** @internal */\n _renderFrame() {\n for (let index = 0; index < this._activeRenderLoops.length; index++) {\n const renderFunction = this._activeRenderLoops[index];\n renderFunction();\n }\n }\n _renderLoop() {\n if (!this._contextWasLost) {\n let shouldRender = true;\n if (this.isDisposed || (!this.renderEvenInBackground && this._windowIsBackground)) {\n shouldRender = false;\n }\n if (shouldRender) {\n // Start new frame\n this.beginFrame();\n // Child canvases\n if (!this._renderViews()) {\n // Main frame\n this._renderFrame();\n }\n // Present\n this.endFrame();\n }\n }\n if (this._activeRenderLoops.length > 0) {\n // Register new frame\n if (this.customAnimationFrameRequester) {\n this.customAnimationFrameRequester.requestID = this._queueNewFrame(this.customAnimationFrameRequester.renderFunction || this._boundRenderFunction, this.customAnimationFrameRequester);\n this._frameHandler = this.customAnimationFrameRequester.requestID;\n }\n else if (this.isVRPresenting()) {\n this._requestVRFrame();\n }\n else {\n this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow());\n }\n }\n else {\n this._renderingQueueLaunched = false;\n }\n }\n /** @internal */\n _renderViews() {\n return false;\n }\n /**\n * Toggle full screen mode\n * @param requestPointerLock defines if a pointer lock should be requested from the user\n */\n switchFullscreen(requestPointerLock) {\n if (this.isFullscreen) {\n this.exitFullscreen();\n }\n else {\n this.enterFullscreen(requestPointerLock);\n }\n }\n /**\n * Enters full screen mode\n * @param requestPointerLock defines if a pointer lock should be requested from the user\n */\n enterFullscreen(requestPointerLock) {\n if (!this.isFullscreen) {\n this._pointerLockRequested = requestPointerLock;\n if (this._renderingCanvas) {\n Engine._RequestFullscreen(this._renderingCanvas);\n }\n }\n }\n /**\n * Exits full screen mode\n */\n exitFullscreen() {\n if (this.isFullscreen) {\n Engine._ExitFullscreen();\n }\n }\n /**\n * Enters Pointerlock mode\n */\n enterPointerlock() {\n if (this._renderingCanvas) {\n Engine._RequestPointerlock(this._renderingCanvas);\n }\n }\n /**\n * Exits Pointerlock mode\n */\n exitPointerlock() {\n Engine._ExitPointerlock();\n }\n /**\n * Begin a new frame\n */\n beginFrame() {\n this._measureFps();\n this.onBeginFrameObservable.notifyObservers(this);\n super.beginFrame();\n }\n /**\n * End the current frame\n */\n endFrame() {\n super.endFrame();\n this._submitVRFrame();\n this.onEndFrameObservable.notifyObservers(this);\n }\n /**\n * Resize the view according to the canvas' size\n * @param forceSetSize true to force setting the sizes of the underlying canvas\n */\n resize(forceSetSize = false) {\n // We're not resizing the size of the canvas while in VR mode & presenting\n if (this.isVRPresenting()) {\n return;\n }\n super.resize(forceSetSize);\n }\n /**\n * Force a specific size of the canvas\n * @param width defines the new canvas' width\n * @param height defines the new canvas' height\n * @param forceSetSize true to force setting the sizes of the underlying canvas\n * @returns true if the size was changed\n */\n setSize(width, height, forceSetSize = false) {\n if (!this._renderingCanvas) {\n return false;\n }\n if (!super.setSize(width, height, forceSetSize)) {\n return false;\n }\n if (this.scenes) {\n for (let index = 0; index < this.scenes.length; index++) {\n const scene = this.scenes[index];\n for (let camIndex = 0; camIndex < scene.cameras.length; camIndex++) {\n const cam = scene.cameras[camIndex];\n cam._currentRenderId = 0;\n }\n }\n if (this.onResizeObservable.hasObservers()) {\n this.onResizeObservable.notifyObservers(this);\n }\n }\n return true;\n }\n _deletePipelineContext(pipelineContext) {\n const webGLPipelineContext = pipelineContext;\n if (webGLPipelineContext && webGLPipelineContext.program) {\n if (webGLPipelineContext.transformFeedback) {\n this.deleteTransformFeedback(webGLPipelineContext.transformFeedback);\n webGLPipelineContext.transformFeedback = null;\n }\n }\n super._deletePipelineContext(pipelineContext);\n }\n createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context, transformFeedbackVaryings = null) {\n context = context || this._gl;\n this.onBeforeShaderCompilationObservable.notifyObservers(this);\n const program = super.createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context, transformFeedbackVaryings);\n this.onAfterShaderCompilationObservable.notifyObservers(this);\n return program;\n }\n _createShaderProgram(pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings = null) {\n const shaderProgram = context.createProgram();\n pipelineContext.program = shaderProgram;\n if (!shaderProgram) {\n throw new Error(\"Unable to create program\");\n }\n context.attachShader(shaderProgram, vertexShader);\n context.attachShader(shaderProgram, fragmentShader);\n if (this.webGLVersion > 1 && transformFeedbackVaryings) {\n const transformFeedback = this.createTransformFeedback();\n this.bindTransformFeedback(transformFeedback);\n this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);\n pipelineContext.transformFeedback = transformFeedback;\n }\n context.linkProgram(shaderProgram);\n if (this.webGLVersion > 1 && transformFeedbackVaryings) {\n this.bindTransformFeedback(null);\n }\n pipelineContext.context = context;\n pipelineContext.vertexShader = vertexShader;\n pipelineContext.fragmentShader = fragmentShader;\n if (!pipelineContext.isParallelCompiled) {\n this._finalizePipelineContext(pipelineContext);\n }\n return shaderProgram;\n }\n /**\n * @internal\n */\n _releaseTexture(texture) {\n super._releaseTexture(texture);\n }\n /**\n * @internal\n */\n _releaseRenderTargetWrapper(rtWrapper) {\n super._releaseRenderTargetWrapper(rtWrapper);\n // Set output texture of post process to null if the framebuffer has been released/disposed\n this.scenes.forEach((scene) => {\n scene.postProcesses.forEach((postProcess) => {\n if (postProcess._outputTexture === rtWrapper) {\n postProcess._outputTexture = null;\n }\n });\n scene.cameras.forEach((camera) => {\n camera._postProcesses.forEach((postProcess) => {\n if (postProcess) {\n if (postProcess._outputTexture === rtWrapper) {\n postProcess._outputTexture = null;\n }\n }\n });\n });\n });\n }\n /**\n * Gets the names of the render passes that are currently created\n * @returns list of the render pass names\n */\n getRenderPassNames() {\n return this._renderPassNames;\n }\n /**\n * Gets the name of the current render pass\n * @returns name of the current render pass\n */\n getCurrentRenderPassName() {\n return this._renderPassNames[this.currentRenderPassId];\n }\n /**\n * Creates a render pass id\n * @param name Name of the render pass (for debug purpose only)\n * @returns the id of the new render pass\n */\n createRenderPassId(name) {\n // Note: render pass id == 0 is always for the main render pass\n const id = ++Engine._RenderPassIdCounter;\n this._renderPassNames[id] = name !== null && name !== void 0 ? name : \"NONAME\";\n return id;\n }\n /**\n * Releases a render pass id\n * @param id id of the render pass to release\n */\n releaseRenderPassId(id) {\n this._renderPassNames[id] = undefined;\n for (let s = 0; s < this.scenes.length; ++s) {\n const scene = this.scenes[s];\n for (let m = 0; m < scene.meshes.length; ++m) {\n const mesh = scene.meshes[m];\n if (mesh.subMeshes) {\n for (let b = 0; b < mesh.subMeshes.length; ++b) {\n const subMesh = mesh.subMeshes[b];\n subMesh._removeDrawWrapper(id);\n }\n }\n }\n }\n }\n /**\n * @internal\n * Rescales a texture\n * @param source input texture\n * @param destination destination texture\n * @param scene scene to use to render the resize\n * @param internalFormat format to use when resizing\n * @param onComplete callback to be called when resize has completed\n */\n _rescaleTexture(source, destination, scene, internalFormat, onComplete) {\n this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, this._gl.LINEAR);\n this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR);\n this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);\n this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);\n const rtt = this.createRenderTargetTexture({\n width: destination.width,\n height: destination.height,\n }, {\n generateMipMaps: false,\n type: 0,\n samplingMode: 2,\n generateDepthBuffer: false,\n generateStencilBuffer: false,\n });\n if (!this._rescalePostProcess && Engine._RescalePostProcessFactory) {\n this._rescalePostProcess = Engine._RescalePostProcessFactory(this);\n }\n if (this._rescalePostProcess) {\n this._rescalePostProcess.externalTextureSamplerBinding = true;\n this._rescalePostProcess.getEffect().executeWhenCompiled(() => {\n this._rescalePostProcess.onApply = function (effect) {\n effect._bindTexture(\"textureSampler\", source);\n };\n let hostingScene = scene;\n if (!hostingScene) {\n hostingScene = this.scenes[this.scenes.length - 1];\n }\n hostingScene.postProcessManager.directRender([this._rescalePostProcess], rtt, true);\n this._bindTextureDirectly(this._gl.TEXTURE_2D, destination, true);\n this._gl.copyTexImage2D(this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);\n this.unBindFramebuffer(rtt);\n rtt.dispose();\n if (onComplete) {\n onComplete();\n }\n });\n }\n }\n // FPS\n /**\n * Gets the current framerate\n * @returns a number representing the framerate\n */\n getFps() {\n return this._fps;\n }\n /**\n * Gets the time spent between current and previous frame\n * @returns a number representing the delta time in ms\n */\n getDeltaTime() {\n return this._deltaTime;\n }\n _measureFps() {\n this._performanceMonitor.sampleFrame();\n this._fps = this._performanceMonitor.averageFPS;\n this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;\n }\n /**\n * Wraps an external web gl texture in a Babylon texture.\n * @param texture defines the external texture\n * @param hasMipMaps defines whether the external texture has mip maps (default: false)\n * @param samplingMode defines the sampling mode for the external texture (default: 3)\n * @returns the babylon internal texture\n */\n wrapWebGLTexture(texture, hasMipMaps = false, samplingMode = 3) {\n const hardwareTexture = new WebGLHardwareTexture(texture, this._gl);\n const internalTexture = new InternalTexture(this, InternalTextureSource.Unknown, true);\n internalTexture._hardwareTexture = hardwareTexture;\n internalTexture.isReady = true;\n internalTexture.useMipMaps = hasMipMaps;\n this.updateTextureSamplingMode(samplingMode, internalTexture);\n return internalTexture;\n }\n /**\n * @internal\n */\n _uploadImageToTexture(texture, image, faceIndex = 0, lod = 0) {\n const gl = this._gl;\n const textureType = this._getWebGLTextureType(texture.type);\n const format = this._getInternalFormat(texture.format);\n const internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);\n const bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;\n this._bindTextureDirectly(bindTarget, texture, true);\n this._unpackFlipY(texture.invertY);\n let target = gl.TEXTURE_2D;\n if (texture.isCube) {\n target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;\n }\n gl.texImage2D(target, lod, internalFormat, format, textureType, image);\n this._bindTextureDirectly(bindTarget, null, true);\n }\n /**\n * Updates a depth texture Comparison Mode and Function.\n * If the comparison Function is equal to 0, the mode will be set to none.\n * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.\n * @param texture The texture to set the comparison function for\n * @param comparisonFunction The comparison function to set, 0 if no comparison required\n */\n updateTextureComparisonFunction(texture, comparisonFunction) {\n if (this.webGLVersion === 1) {\n Logger.Error(\"WebGL 1 does not support texture comparison.\");\n return;\n }\n const gl = this._gl;\n if (texture.isCube) {\n this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);\n if (comparisonFunction === 0) {\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, 515);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);\n }\n else {\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);\n }\n else {\n this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);\n if (comparisonFunction === 0) {\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, 515);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);\n }\n else {\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);\n }\n this._bindTextureDirectly(this._gl.TEXTURE_2D, null);\n }\n texture._comparisonFunction = comparisonFunction;\n }\n /**\n * Creates a webGL buffer to use with instantiation\n * @param capacity defines the size of the buffer\n * @returns the webGL buffer\n */\n createInstancesBuffer(capacity) {\n const buffer = this._gl.createBuffer();\n if (!buffer) {\n throw new Error(\"Unable to create instance buffer\");\n }\n const result = new WebGLDataBuffer(buffer);\n result.capacity = capacity;\n this.bindArrayBuffer(result);\n this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);\n result.references = 1;\n return result;\n }\n /**\n * Delete a webGL buffer used with instantiation\n * @param buffer defines the webGL buffer to delete\n */\n deleteInstancesBuffer(buffer) {\n this._gl.deleteBuffer(buffer);\n }\n _clientWaitAsync(sync, flags = 0, intervalms = 10) {\n const gl = this._gl;\n return new Promise((resolve, reject) => {\n const check = () => {\n const res = gl.clientWaitSync(sync, flags, 0);\n if (res == gl.WAIT_FAILED) {\n reject();\n return;\n }\n if (res == gl.TIMEOUT_EXPIRED) {\n setTimeout(check, intervalms);\n return;\n }\n resolve();\n };\n check();\n });\n }\n /**\n * @internal\n */\n _readPixelsAsync(x, y, w, h, format, type, outputBuffer) {\n if (this._webGLVersion < 2) {\n throw new Error(\"_readPixelsAsync only work on WebGL2+\");\n }\n const gl = this._gl;\n const buf = gl.createBuffer();\n gl.bindBuffer(gl.PIXEL_PACK_BUFFER, buf);\n gl.bufferData(gl.PIXEL_PACK_BUFFER, outputBuffer.byteLength, gl.STREAM_READ);\n gl.readPixels(x, y, w, h, format, type, 0);\n gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);\n const sync = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0);\n if (!sync) {\n return null;\n }\n gl.flush();\n return this._clientWaitAsync(sync, 0, 10).then(() => {\n gl.deleteSync(sync);\n gl.bindBuffer(gl.PIXEL_PACK_BUFFER, buf);\n gl.getBufferSubData(gl.PIXEL_PACK_BUFFER, 0, outputBuffer);\n gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);\n gl.deleteBuffer(buf);\n return outputBuffer;\n });\n }\n dispose() {\n this.hideLoadingUI();\n this.onNewSceneAddedObservable.clear();\n // Release postProcesses\n while (this.postProcesses.length) {\n this.postProcesses[0].dispose();\n }\n // Rescale PP\n if (this._rescalePostProcess) {\n this._rescalePostProcess.dispose();\n }\n // Release scenes\n while (this.scenes.length) {\n this.scenes[0].dispose();\n }\n while (this._virtualScenes.length) {\n this._virtualScenes[0].dispose();\n }\n // Release audio engine\n if (EngineStore.Instances.length === 1 && Engine.audioEngine) {\n Engine.audioEngine.dispose();\n Engine.audioEngine = null;\n }\n //WebVR\n this.disableVR();\n // Events\n const hostWindow = this.getHostWindow(); // it calls IsWindowObjectExist()\n if (hostWindow && typeof hostWindow.removeEventListener === \"function\") {\n hostWindow.removeEventListener(\"blur\", this._onBlur);\n hostWindow.removeEventListener(\"focus\", this._onFocus);\n }\n if (this._renderingCanvas) {\n this._renderingCanvas.removeEventListener(\"focus\", this._onCanvasFocus);\n this._renderingCanvas.removeEventListener(\"blur\", this._onCanvasBlur);\n this._renderingCanvas.removeEventListener(\"pointerout\", this._onCanvasPointerOut);\n this._renderingCanvas.removeEventListener(\"contextmenu\", this._onCanvasContextMenu);\n }\n if (IsDocumentAvailable()) {\n document.removeEventListener(\"fullscreenchange\", this._onFullscreenChange);\n document.removeEventListener(\"mozfullscreenchange\", this._onFullscreenChange);\n document.removeEventListener(\"webkitfullscreenchange\", this._onFullscreenChange);\n document.removeEventListener(\"msfullscreenchange\", this._onFullscreenChange);\n document.removeEventListener(\"pointerlockchange\", this._onPointerLockChange);\n document.removeEventListener(\"mspointerlockchange\", this._onPointerLockChange);\n document.removeEventListener(\"mozpointerlockchange\", this._onPointerLockChange);\n document.removeEventListener(\"webkitpointerlockchange\", this._onPointerLockChange);\n }\n super.dispose();\n // Remove from Instances\n const index = EngineStore.Instances.indexOf(this);\n if (index >= 0) {\n EngineStore.Instances.splice(index, 1);\n }\n // no more engines left in the engine store? Notify!\n if (!Engine.Instances.length) {\n EngineStore.OnEnginesDisposedObservable.notifyObservers(this);\n }\n // Observables\n this.onResizeObservable.clear();\n this.onCanvasBlurObservable.clear();\n this.onCanvasFocusObservable.clear();\n this.onCanvasPointerOutObservable.clear();\n this.onBeginFrameObservable.clear();\n this.onEndFrameObservable.clear();\n }\n _disableTouchAction() {\n if (!this._renderingCanvas || !this._renderingCanvas.setAttribute) {\n return;\n }\n this._renderingCanvas.setAttribute(\"touch-action\", \"none\");\n this._renderingCanvas.style.touchAction = \"none\";\n this._renderingCanvas.style.webkitTapHighlightColor = \"transparent\";\n }\n // Loading screen\n /**\n * Display the loading screen\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen\n */\n displayLoadingUI() {\n if (!IsWindowObjectExist()) {\n return;\n }\n const loadingScreen = this.loadingScreen;\n if (loadingScreen) {\n loadingScreen.displayLoadingUI();\n }\n }\n /**\n * Hide the loading screen\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen\n */\n hideLoadingUI() {\n if (!IsWindowObjectExist()) {\n return;\n }\n const loadingScreen = this._loadingScreen;\n if (loadingScreen) {\n loadingScreen.hideLoadingUI();\n }\n }\n /**\n * Gets the current loading screen object\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen\n */\n get loadingScreen() {\n if (!this._loadingScreen && this._renderingCanvas) {\n this._loadingScreen = Engine.DefaultLoadingScreenFactory(this._renderingCanvas);\n }\n return this._loadingScreen;\n }\n /**\n * Sets the current loading screen object\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen\n */\n set loadingScreen(loadingScreen) {\n this._loadingScreen = loadingScreen;\n }\n /**\n * Sets the current loading screen text\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen\n */\n set loadingUIText(text) {\n this.loadingScreen.loadingUIText = text;\n }\n /**\n * Sets the current loading screen background color\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/customLoadingScreen\n */\n set loadingUIBackgroundColor(color) {\n this.loadingScreen.loadingUIBackgroundColor = color;\n }\n /**\n * creates and returns a new video element\n * @param constraints video constraints\n * @returns video element\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n createVideoElement(constraints) {\n return document.createElement(\"video\");\n }\n /** Pointerlock and fullscreen */\n /**\n * Ask the browser to promote the current element to pointerlock mode\n * @param element defines the DOM element to promote\n */\n static _RequestPointerlock(element) {\n if (element.requestPointerLock) {\n // In some browsers, requestPointerLock returns a promise.\n // Handle possible rejections to avoid an unhandled top-level exception.\n const promise = element.requestPointerLock();\n if (promise instanceof Promise)\n promise\n .then(() => {\n element.focus();\n })\n .catch(() => { });\n else\n element.focus();\n }\n }\n /**\n * Asks the browser to exit pointerlock mode\n */\n static _ExitPointerlock() {\n if (document.exitPointerLock) {\n document.exitPointerLock();\n }\n }\n /**\n * Ask the browser to promote the current element to fullscreen rendering mode\n * @param element defines the DOM element to promote\n */\n static _RequestFullscreen(element) {\n const requestFunction = element.requestFullscreen || element.webkitRequestFullscreen;\n if (!requestFunction) {\n return;\n }\n requestFunction.call(element);\n }\n /**\n * Asks the browser to exit fullscreen mode\n */\n static _ExitFullscreen() {\n const anyDoc = document;\n if (document.exitFullscreen) {\n document.exitFullscreen();\n }\n else if (anyDoc.webkitCancelFullScreen) {\n anyDoc.webkitCancelFullScreen();\n }\n }\n /**\n * Get Font size information\n * @param font font name\n * @returns an object containing ascent, height and descent\n */\n getFontOffset(font) {\n const text = document.createElement(\"span\");\n text.innerHTML = \"Hg\";\n text.setAttribute(\"style\", `font: ${font} !important`);\n const block = document.createElement(\"div\");\n block.style.display = \"inline-block\";\n block.style.width = \"1px\";\n block.style.height = \"0px\";\n block.style.verticalAlign = \"bottom\";\n const div = document.createElement(\"div\");\n div.style.whiteSpace = \"nowrap\";\n div.appendChild(text);\n div.appendChild(block);\n document.body.appendChild(div);\n let fontAscent = 0;\n let fontHeight = 0;\n try {\n fontHeight = block.getBoundingClientRect().top - text.getBoundingClientRect().top;\n block.style.verticalAlign = \"baseline\";\n fontAscent = block.getBoundingClientRect().top - text.getBoundingClientRect().top;\n }\n finally {\n document.body.removeChild(div);\n }\n return { ascent: fontAscent, height: fontHeight, descent: fontHeight - fontAscent };\n }\n}\n// Const statics\n/** Defines that alpha blending is disabled */\nEngine.ALPHA_DISABLE = 0;\n/** Defines that alpha blending to SRC ALPHA * SRC + DEST */\nEngine.ALPHA_ADD = 1;\n/** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */\nEngine.ALPHA_COMBINE = 2;\n/** Defines that alpha blending to DEST - SRC * DEST */\nEngine.ALPHA_SUBTRACT = 3;\n/** Defines that alpha blending to SRC * DEST */\nEngine.ALPHA_MULTIPLY = 4;\n/** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */\nEngine.ALPHA_MAXIMIZED = 5;\n/** Defines that alpha blending to SRC + DEST */\nEngine.ALPHA_ONEONE = 6;\n/** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */\nEngine.ALPHA_PREMULTIPLIED = 7;\n/**\n * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST\n * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA\n */\nEngine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;\n/** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */\nEngine.ALPHA_INTERPOLATE = 9;\n/**\n * Defines that alpha blending to SRC + (1 - SRC) * DEST\n * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA\n */\nEngine.ALPHA_SCREENMODE = 10;\n/** Defines that the resource is not delayed*/\nEngine.DELAYLOADSTATE_NONE = 0;\n/** Defines that the resource was successfully delay loaded */\nEngine.DELAYLOADSTATE_LOADED = 1;\n/** Defines that the resource is currently delay loading */\nEngine.DELAYLOADSTATE_LOADING = 2;\n/** Defines that the resource is delayed and has not started loading */\nEngine.DELAYLOADSTATE_NOTLOADED = 4;\n// Depht or Stencil test Constants.\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */\nEngine.NEVER = 512;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */\nEngine.ALWAYS = 519;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */\nEngine.LESS = 513;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */\nEngine.EQUAL = 514;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */\nEngine.LEQUAL = 515;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */\nEngine.GREATER = 516;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */\nEngine.GEQUAL = 518;\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */\nEngine.NOTEQUAL = 517;\n// Stencil Actions Constants.\n/** Passed to stencilOperation to specify that stencil value must be kept */\nEngine.KEEP = 7680;\n/** Passed to stencilOperation to specify that stencil value must be replaced */\nEngine.REPLACE = 7681;\n/** Passed to stencilOperation to specify that stencil value must be incremented */\nEngine.INCR = 7682;\n/** Passed to stencilOperation to specify that stencil value must be decremented */\nEngine.DECR = 7683;\n/** Passed to stencilOperation to specify that stencil value must be inverted */\nEngine.INVERT = 5386;\n/** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */\nEngine.INCR_WRAP = 34055;\n/** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */\nEngine.DECR_WRAP = 34056;\n/** Texture is not repeating outside of 0..1 UVs */\nEngine.TEXTURE_CLAMP_ADDRESSMODE = 0;\n/** Texture is repeating outside of 0..1 UVs */\nEngine.TEXTURE_WRAP_ADDRESSMODE = 1;\n/** Texture is repeating and mirrored */\nEngine.TEXTURE_MIRROR_ADDRESSMODE = 2;\n/** ALPHA */\nEngine.TEXTUREFORMAT_ALPHA = 0;\n/** LUMINANCE */\nEngine.TEXTUREFORMAT_LUMINANCE = 1;\n/** LUMINANCE_ALPHA */\nEngine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;\n/** RGB */\nEngine.TEXTUREFORMAT_RGB = 4;\n/** RGBA */\nEngine.TEXTUREFORMAT_RGBA = 5;\n/** RED */\nEngine.TEXTUREFORMAT_RED = 6;\n/** RED (2nd reference) */\nEngine.TEXTUREFORMAT_R = 6;\n/** RG */\nEngine.TEXTUREFORMAT_RG = 7;\n/** RED_INTEGER */\nEngine.TEXTUREFORMAT_RED_INTEGER = 8;\n/** RED_INTEGER (2nd reference) */\nEngine.TEXTUREFORMAT_R_INTEGER = 8;\n/** RG_INTEGER */\nEngine.TEXTUREFORMAT_RG_INTEGER = 9;\n/** RGB_INTEGER */\nEngine.TEXTUREFORMAT_RGB_INTEGER = 10;\n/** RGBA_INTEGER */\nEngine.TEXTUREFORMAT_RGBA_INTEGER = 11;\n/** UNSIGNED_BYTE */\nEngine.TEXTURETYPE_UNSIGNED_BYTE = 0;\n/** UNSIGNED_BYTE (2nd reference) */\nEngine.TEXTURETYPE_UNSIGNED_INT = 0;\n/** FLOAT */\nEngine.TEXTURETYPE_FLOAT = 1;\n/** HALF_FLOAT */\nEngine.TEXTURETYPE_HALF_FLOAT = 2;\n/** BYTE */\nEngine.TEXTURETYPE_BYTE = 3;\n/** SHORT */\nEngine.TEXTURETYPE_SHORT = 4;\n/** UNSIGNED_SHORT */\nEngine.TEXTURETYPE_UNSIGNED_SHORT = 5;\n/** INT */\nEngine.TEXTURETYPE_INT = 6;\n/** UNSIGNED_INT */\nEngine.TEXTURETYPE_UNSIGNED_INTEGER = 7;\n/** UNSIGNED_SHORT_4_4_4_4 */\nEngine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;\n/** UNSIGNED_SHORT_5_5_5_1 */\nEngine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;\n/** UNSIGNED_SHORT_5_6_5 */\nEngine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;\n/** UNSIGNED_INT_2_10_10_10_REV */\nEngine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;\n/** UNSIGNED_INT_24_8 */\nEngine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;\n/** UNSIGNED_INT_10F_11F_11F_REV */\nEngine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;\n/** UNSIGNED_INT_5_9_9_9_REV */\nEngine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;\n/** FLOAT_32_UNSIGNED_INT_24_8_REV */\nEngine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;\n/** nearest is mag = nearest and min = nearest and mip = none */\nEngine.TEXTURE_NEAREST_SAMPLINGMODE = 1;\n/** Bilinear is mag = linear and min = linear and mip = nearest */\nEngine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;\n/** Trilinear is mag = linear and min = linear and mip = linear */\nEngine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;\n/** nearest is mag = nearest and min = nearest and mip = linear */\nEngine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 8;\n/** Bilinear is mag = linear and min = linear and mip = nearest */\nEngine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 11;\n/** Trilinear is mag = linear and min = linear and mip = linear */\nEngine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;\n/** mag = nearest and min = nearest and mip = nearest */\nEngine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;\n/** mag = nearest and min = linear and mip = nearest */\nEngine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;\n/** mag = nearest and min = linear and mip = linear */\nEngine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;\n/** mag = nearest and min = linear and mip = none */\nEngine.TEXTURE_NEAREST_LINEAR = 7;\n/** mag = nearest and min = nearest and mip = none */\nEngine.TEXTURE_NEAREST_NEAREST = 1;\n/** mag = linear and min = nearest and mip = nearest */\nEngine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;\n/** mag = linear and min = nearest and mip = linear */\nEngine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;\n/** mag = linear and min = linear and mip = none */\nEngine.TEXTURE_LINEAR_LINEAR = 2;\n/** mag = linear and min = nearest and mip = none */\nEngine.TEXTURE_LINEAR_NEAREST = 12;\n/** Explicit coordinates mode */\nEngine.TEXTURE_EXPLICIT_MODE = 0;\n/** Spherical coordinates mode */\nEngine.TEXTURE_SPHERICAL_MODE = 1;\n/** Planar coordinates mode */\nEngine.TEXTURE_PLANAR_MODE = 2;\n/** Cubic coordinates mode */\nEngine.TEXTURE_CUBIC_MODE = 3;\n/** Projection coordinates mode */\nEngine.TEXTURE_PROJECTION_MODE = 4;\n/** Skybox coordinates mode */\nEngine.TEXTURE_SKYBOX_MODE = 5;\n/** Inverse Cubic coordinates mode */\nEngine.TEXTURE_INVCUBIC_MODE = 6;\n/** Equirectangular coordinates mode */\nEngine.TEXTURE_EQUIRECTANGULAR_MODE = 7;\n/** Equirectangular Fixed coordinates mode */\nEngine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;\n/** Equirectangular Fixed Mirrored coordinates mode */\nEngine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;\n// Texture rescaling mode\n/** Defines that texture rescaling will use a floor to find the closer power of 2 size */\nEngine.SCALEMODE_FLOOR = 1;\n/** Defines that texture rescaling will look for the nearest power of 2 size */\nEngine.SCALEMODE_NEAREST = 2;\n/** Defines that texture rescaling will use a ceil to find the closer power of 2 size */\nEngine.SCALEMODE_CEILING = 3;\n/**\n * Method called to create the default rescale post process on each engine.\n */\nEngine._RescalePostProcessFactory = null;\n// eslint-disable-next-line @typescript-eslint/naming-convention\nEngine._RenderPassIdCounter = 0;\n//# sourceMappingURL=engine.js.map","import { Observable } from \"../Misc/observable.js\";\n/**\n * The engine store class is responsible to hold all the instances of Engine and Scene created\n * during the life time of the application.\n */\nexport class EngineStore {\n /**\n * Gets the latest created engine\n */\n static get LastCreatedEngine() {\n if (this.Instances.length === 0) {\n return null;\n }\n return this.Instances[this.Instances.length - 1];\n }\n /**\n * Gets the latest created scene\n */\n static get LastCreatedScene() {\n return this._LastCreatedScene;\n }\n}\n/** Gets the list of created engines */\nEngineStore.Instances = new Array();\n/**\n * Notifies when an engine was disposed.\n * Mainly used for static/cache cleanup\n */\nEngineStore.OnEnginesDisposedObservable = new Observable();\n/** @internal */\nEngineStore._LastCreatedScene = null;\n/**\n * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded\n * @ignorenaming\n */\nEngineStore.UseFallbackTexture = true;\n/**\n * Texture content used if a texture cannot loaded\n * @ignorenaming\n */\nEngineStore.FallbackTexture = \"\";\n//# sourceMappingURL=engineStore.js.map","import { ShaderLanguage } from \"../Materials/shaderLanguage.js\";\n/**\n * Defines the shader related stores and directory\n */\nexport class ShaderStore {\n /**\n * Gets the shaders repository path for a given shader language\n * @param shaderLanguage the shader language\n * @returns the path to the shaders repository\n */\n static GetShadersRepository(shaderLanguage = ShaderLanguage.GLSL) {\n return shaderLanguage === ShaderLanguage.GLSL ? ShaderStore.ShadersRepository : ShaderStore.ShadersRepositoryWGSL;\n }\n /**\n * Gets the shaders store of a given shader language\n * @param shaderLanguage the shader language\n * @returns the shaders store\n */\n static GetShadersStore(shaderLanguage = ShaderLanguage.GLSL) {\n return shaderLanguage === ShaderLanguage.GLSL ? ShaderStore.ShadersStore : ShaderStore.ShadersStoreWGSL;\n }\n /**\n * Gets the include shaders store of a given shader language\n * @param shaderLanguage the shader language\n * @returns the include shaders store\n */\n static GetIncludesShadersStore(shaderLanguage = ShaderLanguage.GLSL) {\n return shaderLanguage === ShaderLanguage.GLSL ? ShaderStore.IncludesShadersStore : ShaderStore.IncludesShadersStoreWGSL;\n }\n}\n/**\n * Gets or sets the relative url used to load shaders if using the engine in non-minified mode\n */\nShaderStore.ShadersRepository = \"src/Shaders/\";\n/**\n * Store of each shader (The can be looked up using effect.key)\n */\nShaderStore.ShadersStore = {};\n/**\n * Store of each included file for a shader (The can be looked up using effect.key)\n */\nShaderStore.IncludesShadersStore = {};\n/**\n * Gets or sets the relative url used to load shaders (WGSL) if using the engine in non-minified mode\n */\nShaderStore.ShadersRepositoryWGSL = \"src/ShadersWGSL/\";\n/**\n * Store of each shader (WGSL)\n */\nShaderStore.ShadersStoreWGSL = {};\n/**\n * Store of each included file for a shader (WGSL)\n */\nShaderStore.IncludesShadersStoreWGSL = {};\n//# sourceMappingURL=shaderStore.js.map","/**\n * Event Types\n */\nexport var DeviceInputEventType;\n(function (DeviceInputEventType) {\n // Pointers\n /** PointerMove */\n DeviceInputEventType[DeviceInputEventType[\"PointerMove\"] = 0] = \"PointerMove\";\n /** PointerDown */\n DeviceInputEventType[DeviceInputEventType[\"PointerDown\"] = 1] = \"PointerDown\";\n /** PointerUp */\n DeviceInputEventType[DeviceInputEventType[\"PointerUp\"] = 2] = \"PointerUp\";\n})(DeviceInputEventType || (DeviceInputEventType = {}));\n/**\n * Constants used for Events\n */\nexport class EventConstants {\n}\n/**\n * Pixel delta for Wheel Events (Default)\n */\nEventConstants.DOM_DELTA_PIXEL = 0x00;\n/**\n * Line delta for Wheel Events\n */\nEventConstants.DOM_DELTA_LINE = 0x01;\n/**\n * Page delta for Wheel Events\n */\nEventConstants.DOM_DELTA_PAGE = 0x02;\n//# sourceMappingURL=deviceInputEvents.js.map","/**\n * Gather the list of keyboard event types as constants.\n */\nexport class KeyboardEventTypes {\n}\n/**\n * The keydown event is fired when a key becomes active (pressed).\n */\nKeyboardEventTypes.KEYDOWN = 0x01;\n/**\n * The keyup event is fired when a key has been released.\n */\nKeyboardEventTypes.KEYUP = 0x02;\n/**\n * This class is used to store keyboard related info for the onKeyboardObservable event.\n */\nexport class KeyboardInfo {\n /**\n * Instantiates a new keyboard info.\n * This class is used to store keyboard related info for the onKeyboardObservable event.\n * @param type Defines the type of event (KeyboardEventTypes)\n * @param event Defines the related dom event\n */\n constructor(\n /**\n * Defines the type of event (KeyboardEventTypes)\n */\n type, \n /**\n * Defines the related dom event\n */\n event) {\n this.type = type;\n this.event = event;\n }\n}\n/**\n * This class is used to store keyboard related info for the onPreKeyboardObservable event.\n * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable\n */\nexport class KeyboardInfoPre extends KeyboardInfo {\n /**\n * Defines whether the engine should skip the next onKeyboardObservable associated to this pre.\n * @deprecated use skipOnKeyboardObservable property instead\n */\n get skipOnPointerObservable() {\n return this.skipOnKeyboardObservable;\n }\n set skipOnPointerObservable(value) {\n this.skipOnKeyboardObservable = value;\n }\n /**\n * Instantiates a new keyboard pre info.\n * This class is used to store keyboard related info for the onPreKeyboardObservable event.\n * @param type Defines the type of event (KeyboardEventTypes)\n * @param event Defines the related dom event\n */\n constructor(\n /**\n * Defines the type of event (KeyboardEventTypes)\n */\n type, \n /**\n * Defines the related dom event\n */\n event) {\n super(type, event);\n this.type = type;\n this.event = event;\n this.skipOnKeyboardObservable = false;\n }\n}\n//# sourceMappingURL=keyboardEvents.js.map","import { Vector2 } from \"../Maths/math.vector.js\";\n/**\n * Gather the list of pointer event types as constants.\n */\nexport class PointerEventTypes {\n}\n/**\n * The pointerdown event is fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer.\n */\nPointerEventTypes.POINTERDOWN = 0x01;\n/**\n * The pointerup event is fired when a pointer is no longer active.\n */\nPointerEventTypes.POINTERUP = 0x02;\n/**\n * The pointermove event is fired when a pointer changes coordinates.\n */\nPointerEventTypes.POINTERMOVE = 0x04;\n/**\n * The pointerwheel event is fired when a mouse wheel has been rotated.\n */\nPointerEventTypes.POINTERWHEEL = 0x08;\n/**\n * The pointerpick event is fired when a mesh or sprite has been picked by the pointer.\n */\nPointerEventTypes.POINTERPICK = 0x10;\n/**\n * The pointertap event is fired when a the object has been touched and released without drag.\n */\nPointerEventTypes.POINTERTAP = 0x20;\n/**\n * The pointerdoubletap event is fired when a the object has been touched and released twice without drag.\n */\nPointerEventTypes.POINTERDOUBLETAP = 0x40;\n/**\n * Base class of pointer info types.\n */\nexport class PointerInfoBase {\n /**\n * Instantiates the base class of pointers info.\n * @param type Defines the type of event (PointerEventTypes)\n * @param event Defines the related dom event\n */\n constructor(\n /**\n * Defines the type of event (PointerEventTypes)\n */\n type, \n /**\n * Defines the related dom event\n */\n event) {\n this.type = type;\n this.event = event;\n }\n}\n/**\n * This class is used to store pointer related info for the onPrePointerObservable event.\n * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable\n */\nexport class PointerInfoPre extends PointerInfoBase {\n /**\n * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event.\n * @param type Defines the type of event (PointerEventTypes)\n * @param event Defines the related dom event\n * @param localX Defines the local x coordinates of the pointer when the event occured\n * @param localY Defines the local y coordinates of the pointer when the event occured\n */\n constructor(type, event, localX, localY) {\n super(type, event);\n /**\n * Ray from a pointer if available (eg. 6dof controller)\n */\n this.ray = null;\n /**\n * The original picking info that was used to trigger the pointer event\n */\n this.originalPickingInfo = null;\n this.skipOnPointerObservable = false;\n this.localPosition = new Vector2(localX, localY);\n }\n}\n/**\n * This type contains all the data related to a pointer event in Babylon.js.\n * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.\n */\nexport class PointerInfo extends PointerInfoBase {\n /**\n * Defines the picking info associated with this PointerInfo object (if applicable)\n */\n get pickInfo() {\n if (!this._pickInfo) {\n this._generatePickInfo();\n }\n return this._pickInfo;\n }\n /**\n * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event.\n * @param type Defines the type of event (PointerEventTypes)\n * @param event Defines the related dom event\n * @param pickInfo Defines the picking info associated to the info (if any)\n * @param inputManager Defines the InputManager to use if there is no pickInfo\n */\n constructor(type, event, pickInfo, inputManager = null) {\n super(type, event);\n this._pickInfo = pickInfo;\n this._inputManager = inputManager;\n }\n /**\n * Generates the picking info if needed\n */\n /** @internal */\n _generatePickInfo() {\n if (this._inputManager) {\n this._pickInfo = this._inputManager._pickMove(this.event);\n this._inputManager._setRayOnPointerInfo(this._pickInfo, this.event);\n this._inputManager = null;\n }\n }\n}\n//# sourceMappingURL=pointerEvents.js.map","/**\n * Class used to store configuration data associated with pointer picking\n */\nexport class PointerPickingConfiguration {\n constructor() {\n /**\n * Gets or sets a predicate used to select candidate meshes for a pointer down event\n */\n this.pointerDownFastCheck = false;\n /**\n * Gets or sets a predicate used to select candidate meshes for a pointer up event\n */\n this.pointerUpFastCheck = false;\n /**\n * Gets or sets a predicate used to select candidate meshes for a pointer move event\n */\n this.pointerMoveFastCheck = false;\n /**\n * Gets or sets a boolean indicating if the user want to entirely skip the picking phase when a pointer move event occurs.\n */\n this.skipPointerMovePicking = false;\n /**\n * Gets or sets a boolean indicating if the user want to entirely skip the picking phase when a pointer down event occurs.\n */\n this.skipPointerDownPicking = false;\n /**\n * Gets or sets a boolean indicating if the user want to entirely skip the picking phase when a pointer up event occurs. Off by default.\n */\n this.skipPointerUpPicking = false;\n }\n}\n//# sourceMappingURL=pointerPickingConfiguration.js.map","import { PointerInfoPre, PointerInfo, PointerEventTypes } from \"../Events/pointerEvents.js\";\nimport { AbstractActionManager } from \"../Actions/abstractActionManager.js\";\nimport { PickingInfo } from \"../Collisions/pickingInfo.js\";\nimport { Vector2, Matrix } from \"../Maths/math.vector.js\";\n\nimport { ActionEvent } from \"../Actions/actionEvent.js\";\nimport { KeyboardEventTypes, KeyboardInfoPre, KeyboardInfo } from \"../Events/keyboardEvents.js\";\nimport { DeviceType, PointerInput } from \"../DeviceInput/InputDevices/deviceEnums.js\";\nimport { DeviceSourceManager } from \"../DeviceInput/InputDevices/deviceSourceManager.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\n/** @internal */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nclass _ClickInfo {\n constructor() {\n this._singleClick = false;\n this._doubleClick = false;\n this._hasSwiped = false;\n this._ignore = false;\n }\n get singleClick() {\n return this._singleClick;\n }\n get doubleClick() {\n return this._doubleClick;\n }\n get hasSwiped() {\n return this._hasSwiped;\n }\n get ignore() {\n return this._ignore;\n }\n set singleClick(b) {\n this._singleClick = b;\n }\n set doubleClick(b) {\n this._doubleClick = b;\n }\n set hasSwiped(b) {\n this._hasSwiped = b;\n }\n set ignore(b) {\n this._ignore = b;\n }\n}\n/**\n * Class used to manage all inputs for the scene.\n */\nexport class InputManager {\n /**\n * Creates a new InputManager\n * @param scene - defines the hosting scene\n */\n constructor(scene) {\n /** This is a defensive check to not allow control attachment prior to an already active one. If already attached, previous control is unattached before attaching the new one. */\n this._alreadyAttached = false;\n this._meshPickProceed = false;\n this._currentPickResult = null;\n this._previousPickResult = null;\n this._totalPointersPressed = 0;\n this._doubleClickOccured = false;\n this._isSwiping = false;\n this._swipeButtonPressed = -1;\n this._skipPointerTap = false;\n this._isMultiTouchGesture = false;\n this._pointerX = 0;\n this._pointerY = 0;\n this._startingPointerPosition = new Vector2(0, 0);\n this._previousStartingPointerPosition = new Vector2(0, 0);\n this._startingPointerTime = 0;\n this._previousStartingPointerTime = 0;\n this._pointerCaptures = {};\n this._meshUnderPointerId = {};\n this._movePointerInfo = null;\n this._cameraObserverCount = 0;\n this._delayedClicks = [null, null, null, null, null];\n this._deviceSourceManager = null;\n this._scene = scene || EngineStore.LastCreatedScene;\n if (!this._scene) {\n return;\n }\n }\n /**\n * Gets the mesh that is currently under the pointer\n * @returns Mesh that the pointer is pointer is hovering over\n */\n get meshUnderPointer() {\n if (this._movePointerInfo) {\n // Because _pointerOverMesh is populated as part of _pickMove, we need to force a pick to update it.\n // Calling _pickMove calls _setCursorAndPointerOverMesh which calls setPointerOverMesh\n this._movePointerInfo._generatePickInfo();\n // Once we have what we need, we can clear _movePointerInfo because we don't need it anymore\n this._movePointerInfo = null;\n }\n return this._pointerOverMesh;\n }\n /**\n * When using more than one pointer (for example in XR) you can get the mesh under the specific pointer\n * @param pointerId - the pointer id to use\n * @returns The mesh under this pointer id or null if not found\n */\n getMeshUnderPointerByPointerId(pointerId) {\n return this._meshUnderPointerId[pointerId] || null;\n }\n /**\n * Gets the pointer coordinates in 2D without any translation (ie. straight out of the pointer event)\n * @returns Vector with X/Y values directly from pointer event\n */\n get unTranslatedPointer() {\n return new Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);\n }\n /**\n * Gets or sets the current on-screen X position of the pointer\n * @returns Translated X with respect to screen\n */\n get pointerX() {\n return this._pointerX;\n }\n set pointerX(value) {\n this._pointerX = value;\n }\n /**\n * Gets or sets the current on-screen Y position of the pointer\n * @returns Translated Y with respect to screen\n */\n get pointerY() {\n return this._pointerY;\n }\n set pointerY(value) {\n this._pointerY = value;\n }\n _updatePointerPosition(evt) {\n const canvasRect = this._scene.getEngine().getInputElementClientRect();\n if (!canvasRect) {\n return;\n }\n this._pointerX = evt.clientX - canvasRect.left;\n this._pointerY = evt.clientY - canvasRect.top;\n this._unTranslatedPointerX = this._pointerX;\n this._unTranslatedPointerY = this._pointerY;\n }\n _processPointerMove(pickResult, evt) {\n const scene = this._scene;\n const engine = scene.getEngine();\n const canvas = engine.getInputElement();\n if (canvas) {\n canvas.tabIndex = engine.canvasTabIndex;\n // Restore pointer\n if (!scene.doNotHandleCursors) {\n canvas.style.cursor = scene.defaultCursor;\n }\n }\n this._setCursorAndPointerOverMesh(pickResult, evt, scene);\n for (const step of scene._pointerMoveStage) {\n // If _pointerMoveState is defined, we have an active spriteManager and can't use Lazy Picking\n // Therefore, we need to force a pick to update the pickResult\n pickResult = pickResult || this._pickMove(evt);\n const isMeshPicked = (pickResult === null || pickResult === void 0 ? void 0 : pickResult.pickedMesh) ? true : false;\n pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);\n }\n const type = evt.inputIndex >= PointerInput.MouseWheelX && evt.inputIndex <= PointerInput.MouseWheelZ ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;\n if (scene.onPointerMove) {\n // Because of lazy picking, we need to force a pick to update the pickResult\n pickResult = pickResult || this._pickMove(evt);\n scene.onPointerMove(evt, pickResult, type);\n }\n let pointerInfo;\n if (pickResult) {\n pointerInfo = new PointerInfo(type, evt, pickResult);\n this._setRayOnPointerInfo(pickResult, evt);\n }\n else {\n pointerInfo = new PointerInfo(type, evt, null, this);\n this._movePointerInfo = pointerInfo;\n }\n if (scene.onPointerObservable.hasObservers()) {\n scene.onPointerObservable.notifyObservers(pointerInfo, type);\n }\n }\n // Pointers handling\n /** @internal */\n _setRayOnPointerInfo(pickInfo, event) {\n const scene = this._scene;\n if (pickInfo && scene._pickingAvailable) {\n if (!pickInfo.ray) {\n pickInfo.ray = scene.createPickingRay(event.offsetX, event.offsetY, Matrix.Identity(), scene.activeCamera);\n }\n }\n }\n /** @internal */\n _addCameraPointerObserver(observer, mask) {\n this._cameraObserverCount++;\n return this._scene.onPointerObservable.add(observer, mask);\n }\n /** @internal */\n _removeCameraPointerObserver(observer) {\n this._cameraObserverCount--;\n return this._scene.onPointerObservable.remove(observer);\n }\n _checkForPicking() {\n return !!(this._scene.onPointerObservable.observers.length > this._cameraObserverCount || this._scene.onPointerPick);\n }\n _checkPrePointerObservable(pickResult, evt, type) {\n const scene = this._scene;\n const pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);\n if (pickResult) {\n pi.originalPickingInfo = pickResult;\n pi.ray = pickResult.ray;\n if (pickResult.originMesh) {\n pi.nearInteractionPickingInfo = pickResult;\n }\n }\n scene.onPrePointerObservable.notifyObservers(pi, type);\n if (pi.skipOnPointerObservable) {\n return true;\n }\n else {\n return false;\n }\n }\n /** @internal */\n _pickMove(evt) {\n const scene = this._scene;\n const pickResult = scene.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, scene.pointerMovePredicate, scene.pointerMoveFastCheck, scene.cameraToUseForPointers, scene.pointerMoveTrianglePredicate);\n this._setCursorAndPointerOverMesh(pickResult, evt, scene);\n return pickResult;\n }\n _setCursorAndPointerOverMesh(pickResult, evt, scene) {\n const engine = scene.getEngine();\n const canvas = engine.getInputElement();\n if (pickResult === null || pickResult === void 0 ? void 0 : pickResult.pickedMesh) {\n this.setPointerOverMesh(pickResult.pickedMesh, evt.pointerId, pickResult, evt);\n if (!scene.doNotHandleCursors && canvas && this._pointerOverMesh) {\n const actionManager = this._pointerOverMesh._getActionManagerForTrigger();\n if (actionManager && actionManager.hasPointerTriggers) {\n canvas.style.cursor = actionManager.hoverCursor || scene.hoverCursor;\n }\n }\n }\n else {\n this.setPointerOverMesh(null, evt.pointerId, pickResult, evt);\n }\n }\n /**\n * Use this method to simulate a pointer move on a mesh\n * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay\n * @param pickResult - pickingInfo of the object wished to simulate pointer event on\n * @param pointerEventInit - pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)\n */\n simulatePointerMove(pickResult, pointerEventInit) {\n const evt = new PointerEvent(\"pointermove\", pointerEventInit);\n evt.inputIndex = PointerInput.Move;\n if (this._checkPrePointerObservable(pickResult, evt, PointerEventTypes.POINTERMOVE)) {\n return;\n }\n this._processPointerMove(pickResult, evt);\n }\n /**\n * Use this method to simulate a pointer down on a mesh\n * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay\n * @param pickResult - pickingInfo of the object wished to simulate pointer event on\n * @param pointerEventInit - pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)\n */\n simulatePointerDown(pickResult, pointerEventInit) {\n const evt = new PointerEvent(\"pointerdown\", pointerEventInit);\n evt.inputIndex = evt.button + 2;\n if (this._checkPrePointerObservable(pickResult, evt, PointerEventTypes.POINTERDOWN)) {\n return;\n }\n this._processPointerDown(pickResult, evt);\n }\n _processPointerDown(pickResult, evt) {\n const scene = this._scene;\n if (pickResult === null || pickResult === void 0 ? void 0 : pickResult.pickedMesh) {\n this._pickedDownMesh = pickResult.pickedMesh;\n const actionManager = pickResult.pickedMesh._getActionManagerForTrigger();\n if (actionManager) {\n if (actionManager.hasPickTriggers) {\n actionManager.processTrigger(5, ActionEvent.CreateNew(pickResult.pickedMesh, evt));\n switch (evt.button) {\n case 0:\n actionManager.processTrigger(2, ActionEvent.CreateNew(pickResult.pickedMesh, evt));\n break;\n case 1:\n actionManager.processTrigger(4, ActionEvent.CreateNew(pickResult.pickedMesh, evt));\n break;\n case 2:\n actionManager.processTrigger(3, ActionEvent.CreateNew(pickResult.pickedMesh, evt));\n break;\n }\n }\n if (actionManager.hasSpecificTrigger(8)) {\n window.setTimeout(() => {\n const pickResult = scene.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, (mesh) => ((mesh.isPickable &&\n mesh.isVisible &&\n mesh.isReady() &&\n mesh.actionManager &&\n mesh.actionManager.hasSpecificTrigger(8) &&\n mesh === this._pickedDownMesh)), false, scene.cameraToUseForPointers);\n if ((pickResult === null || pickResult === void 0 ? void 0 : pickResult.pickedMesh) && actionManager) {\n if (this._totalPointersPressed !== 0 && Date.now() - this._startingPointerTime > InputManager.LongPressDelay && !this._isPointerSwiping()) {\n this._startingPointerTime = 0;\n actionManager.processTrigger(8, ActionEvent.CreateNew(pickResult.pickedMesh, evt));\n }\n }\n }, InputManager.LongPressDelay);\n }\n }\n }\n else {\n for (const step of scene._pointerDownStage) {\n pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt, false);\n }\n }\n let pointerInfo;\n const type = PointerEventTypes.POINTERDOWN;\n if (pickResult) {\n if (scene.onPointerDown) {\n scene.onPointerDown(evt, pickResult, type);\n }\n pointerInfo = new PointerInfo(type, evt, pickResult);\n this._setRayOnPointerInfo(pickResult, evt);\n }\n else {\n pointerInfo = new PointerInfo(type, evt, null, this);\n }\n if (scene.onPointerObservable.hasObservers()) {\n scene.onPointerObservable.notifyObservers(pointerInfo, type);\n }\n }\n /**\n * @internal\n * @internals Boolean if delta for pointer exceeds drag movement threshold\n */\n _isPointerSwiping() {\n return this._isSwiping;\n }\n /**\n * Use this method to simulate a pointer up on a mesh\n * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay\n * @param pickResult - pickingInfo of the object wished to simulate pointer event on\n * @param pointerEventInit - pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)\n * @param doubleTap - indicates that the pointer up event should be considered as part of a double click (false by default)\n */\n simulatePointerUp(pickResult, pointerEventInit, doubleTap) {\n const evt = new PointerEvent(\"pointerup\", pointerEventInit);\n evt.inputIndex = PointerInput.Move;\n const clickInfo = new _ClickInfo();\n if (doubleTap) {\n clickInfo.doubleClick = true;\n }\n else {\n clickInfo.singleClick = true;\n }\n if (this._checkPrePointerObservable(pickResult, evt, PointerEventTypes.POINTERUP)) {\n return;\n }\n this._processPointerUp(pickResult, evt, clickInfo);\n }\n _processPointerUp(pickResult, evt, clickInfo) {\n const scene = this._scene;\n if (pickResult === null || pickResult === void 0 ? void 0 : pickResult.pickedMesh) {\n this._pickedUpMesh = pickResult.pickedMesh;\n if (this._pickedDownMesh === this._pickedUpMesh) {\n if (scene.onPointerPick) {\n scene.onPointerPick(evt, pickResult);\n }\n if (clickInfo.singleClick && !clickInfo.ignore && scene.onPointerObservable.observers.length > this._cameraObserverCount) {\n const type = PointerEventTypes.POINTERPICK;\n const pi = new PointerInfo(type, evt, pickResult);\n this._setRayOnPointerInfo(pickResult, evt);\n scene.onPointerObservable.notifyObservers(pi, type);\n }\n }\n const actionManager = pickResult.pickedMesh._getActionManagerForTrigger();\n if (actionManager && !clickInfo.ignore) {\n actionManager.processTrigger(7, ActionEvent.CreateNew(pickResult.pickedMesh, evt, pickResult));\n if (!clickInfo.hasSwiped && clickInfo.singleClick) {\n actionManager.processTrigger(1, ActionEvent.CreateNew(pickResult.pickedMesh, evt, pickResult));\n }\n const doubleClickActionManager = pickResult.pickedMesh._getActionManagerForTrigger(6);\n if (clickInfo.doubleClick && doubleClickActionManager) {\n doubleClickActionManager.processTrigger(6, ActionEvent.CreateNew(pickResult.pickedMesh, evt, pickResult));\n }\n }\n }\n else {\n if (!clickInfo.ignore) {\n for (const step of scene._pointerUpStage) {\n pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt, clickInfo.doubleClick);\n }\n }\n }\n if (this._pickedDownMesh && this._pickedDownMesh !== this._pickedUpMesh) {\n const pickedDownActionManager = this._pickedDownMesh._getActionManagerForTrigger(16);\n if (pickedDownActionManager) {\n pickedDownActionManager.processTrigger(16, ActionEvent.CreateNew(this._pickedDownMesh, evt));\n }\n }\n if (!clickInfo.ignore) {\n const pi = new PointerInfo(PointerEventTypes.POINTERUP, evt, pickResult);\n // Set ray on picking info. Note that this info will also be reused for the tap notification.\n this._setRayOnPointerInfo(pickResult, evt);\n scene.onPointerObservable.notifyObservers(pi, PointerEventTypes.POINTERUP);\n if (scene.onPointerUp) {\n scene.onPointerUp(evt, pickResult, PointerEventTypes.POINTERUP);\n }\n if (!clickInfo.hasSwiped && !this._skipPointerTap && !this._isMultiTouchGesture) {\n let type = 0;\n if (clickInfo.singleClick) {\n type = PointerEventTypes.POINTERTAP;\n }\n else if (clickInfo.doubleClick) {\n type = PointerEventTypes.POINTERDOUBLETAP;\n }\n if (type) {\n const pi = new PointerInfo(type, evt, pickResult);\n if (scene.onPointerObservable.hasObservers() && scene.onPointerObservable.hasSpecificMask(type)) {\n scene.onPointerObservable.notifyObservers(pi, type);\n }\n }\n }\n }\n }\n /**\n * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)\n * @param pointerId - defines the pointer id to use in a multi-touch scenario (0 by default)\n * @returns true if the pointer was captured\n */\n isPointerCaptured(pointerId = 0) {\n return this._pointerCaptures[pointerId];\n }\n /**\n * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp\n * @param attachUp - defines if you want to attach events to pointerup\n * @param attachDown - defines if you want to attach events to pointerdown\n * @param attachMove - defines if you want to attach events to pointermove\n * @param elementToAttachTo - defines the target DOM element to attach to (will use the canvas by default)\n */\n attachControl(attachUp = true, attachDown = true, attachMove = true, elementToAttachTo = null) {\n const scene = this._scene;\n const engine = scene.getEngine();\n if (!elementToAttachTo) {\n elementToAttachTo = engine.getInputElement();\n }\n if (this._alreadyAttached) {\n this.detachControl();\n }\n if (elementToAttachTo) {\n this._alreadyAttachedTo = elementToAttachTo;\n }\n this._deviceSourceManager = new DeviceSourceManager(engine);\n // Because this is only called from _initClickEvent, which is called in _onPointerUp, we'll use the pointerUpPredicate for the pick call\n this._initActionManager = (act) => {\n if (!this._meshPickProceed) {\n const pickResult = scene.skipPointerUpPicking || (scene._registeredActions === 0 && !this._checkForPicking() && !scene.onPointerUp)\n ? null\n : scene.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, scene.pointerUpPredicate, scene.pointerUpFastCheck, scene.cameraToUseForPointers);\n this._currentPickResult = pickResult;\n if (pickResult) {\n act = pickResult.hit && pickResult.pickedMesh ? pickResult.pickedMesh._getActionManagerForTrigger() : null;\n }\n this._meshPickProceed = true;\n }\n return act;\n };\n this._delayedSimpleClick = (btn, clickInfo, cb) => {\n // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different\n if ((Date.now() - this._previousStartingPointerTime > InputManager.DoubleClickDelay && !this._doubleClickOccured) || btn !== this._previousButtonPressed) {\n this._doubleClickOccured = false;\n clickInfo.singleClick = true;\n clickInfo.ignore = false;\n // If we have a delayed click, we need to resolve the TAP event\n if (this._delayedClicks[btn]) {\n const evt = this._delayedClicks[btn].evt;\n const type = PointerEventTypes.POINTERTAP;\n const pi = new PointerInfo(type, evt, this._currentPickResult);\n if (scene.onPointerObservable.hasObservers() && scene.onPointerObservable.hasSpecificMask(type)) {\n scene.onPointerObservable.notifyObservers(pi, type);\n }\n // Clear the delayed click\n this._delayedClicks[btn] = null;\n }\n }\n };\n this._initClickEvent = (obs1, obs2, evt, cb) => {\n var _a, _b;\n const clickInfo = new _ClickInfo();\n this._currentPickResult = null;\n let act = null;\n let checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) ||\n obs2.hasSpecificMask(PointerEventTypes.POINTERPICK) ||\n obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) ||\n obs2.hasSpecificMask(PointerEventTypes.POINTERTAP) ||\n obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||\n obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);\n if (!checkPicking && AbstractActionManager) {\n act = this._initActionManager(act, clickInfo);\n if (act) {\n checkPicking = act.hasPickTriggers;\n }\n }\n let needToIgnoreNext = false;\n if (checkPicking) {\n const btn = evt.button;\n clickInfo.hasSwiped = this._isPointerSwiping();\n if (!clickInfo.hasSwiped) {\n let checkSingleClickImmediately = !InputManager.ExclusiveDoubleClickMode;\n if (!checkSingleClickImmediately) {\n checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) && !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);\n if (checkSingleClickImmediately && !AbstractActionManager.HasSpecificTrigger(6)) {\n act = this._initActionManager(act, clickInfo);\n if (act) {\n checkSingleClickImmediately = !act.hasSpecificTrigger(6);\n }\n }\n }\n if (checkSingleClickImmediately) {\n // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required\n if (Date.now() - this._previousStartingPointerTime > InputManager.DoubleClickDelay || btn !== this._previousButtonPressed) {\n clickInfo.singleClick = true;\n cb(clickInfo, this._currentPickResult);\n needToIgnoreNext = true;\n }\n }\n // at least one double click is required to be check and exclusive double click is enabled\n else {\n // Queue up a delayed click, just in case this isn't a double click\n // It should be noted that while this delayed event happens\n // because of user input, it shouldn't be considered as a direct,\n // timing-dependent result of that input. It's meant to just fire the TAP event\n const delayedClick = {\n evt: evt,\n clickInfo: clickInfo,\n timeoutId: window.setTimeout(this._delayedSimpleClick.bind(this, btn, clickInfo, cb), InputManager.DoubleClickDelay),\n };\n this._delayedClicks[btn] = delayedClick;\n }\n let checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);\n if (!checkDoubleClick && AbstractActionManager.HasSpecificTrigger(6)) {\n act = this._initActionManager(act, clickInfo);\n if (act) {\n checkDoubleClick = act.hasSpecificTrigger(6);\n }\n }\n if (checkDoubleClick) {\n // two successive keys pressed are equal, double click delay is not over and double click has not just occurred\n if (btn === this._previousButtonPressed && Date.now() - this._previousStartingPointerTime < InputManager.DoubleClickDelay && !this._doubleClickOccured) {\n // pointer has not moved for 2 clicks, it's a double click\n if (!clickInfo.hasSwiped && !this._isPointerSwiping()) {\n this._previousStartingPointerTime = 0;\n this._doubleClickOccured = true;\n clickInfo.doubleClick = true;\n clickInfo.ignore = false;\n // If we have a pending click, we need to cancel it\n if (InputManager.ExclusiveDoubleClickMode && this._delayedClicks[btn]) {\n clearTimeout((_a = this._delayedClicks[btn]) === null || _a === void 0 ? void 0 : _a.timeoutId);\n this._delayedClicks[btn] = null;\n }\n cb(clickInfo, this._currentPickResult);\n }\n // if the two successive clicks are too far, it's just two simple clicks\n else {\n this._doubleClickOccured = false;\n this._previousStartingPointerTime = this._startingPointerTime;\n this._previousStartingPointerPosition.x = this._startingPointerPosition.x;\n this._previousStartingPointerPosition.y = this._startingPointerPosition.y;\n this._previousButtonPressed = btn;\n if (InputManager.ExclusiveDoubleClickMode) {\n // If we have a delayed click, we need to cancel it\n if (this._delayedClicks[btn]) {\n clearTimeout((_b = this._delayedClicks[btn]) === null || _b === void 0 ? void 0 : _b.timeoutId);\n this._delayedClicks[btn] = null;\n }\n cb(clickInfo, this._previousPickResult);\n }\n else {\n cb(clickInfo, this._currentPickResult);\n }\n }\n needToIgnoreNext = true;\n }\n // just the first click of the double has been raised\n else {\n this._doubleClickOccured = false;\n this._previousStartingPointerTime = this._startingPointerTime;\n this._previousStartingPointerPosition.x = this._startingPointerPosition.x;\n this._previousStartingPointerPosition.y = this._startingPointerPosition.y;\n this._previousButtonPressed = btn;\n }\n }\n }\n }\n // Even if ExclusiveDoubleClickMode is true, we need to always handle\n // up events at time of execution, unless we're explicitly ignoring them.\n if (!needToIgnoreNext) {\n cb(clickInfo, this._currentPickResult);\n }\n };\n this._onPointerMove = (evt) => {\n this._updatePointerPosition(evt);\n // Check if pointer leaves DragMovementThreshold range to determine if swipe is occurring\n if (!this._isSwiping && this._swipeButtonPressed !== -1) {\n this._isSwiping =\n Math.abs(this._startingPointerPosition.x - this._pointerX) > InputManager.DragMovementThreshold ||\n Math.abs(this._startingPointerPosition.y - this._pointerY) > InputManager.DragMovementThreshold;\n }\n // Because there's a race condition between pointermove and pointerlockchange events, we need to\n // verify that the pointer is still locked after each pointermove event.\n if (engine.isPointerLock) {\n engine._verifyPointerLock();\n }\n // PreObservable support\n if (this._checkPrePointerObservable(null, evt, evt.inputIndex >= PointerInput.MouseWheelX && evt.inputIndex <= PointerInput.MouseWheelZ ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE)) {\n return;\n }\n if (!scene.cameraToUseForPointers && !scene.activeCamera) {\n return;\n }\n if (scene.skipPointerMovePicking) {\n this._processPointerMove(new PickingInfo(), evt);\n return;\n }\n if (!scene.pointerMovePredicate) {\n scene.pointerMovePredicate = (mesh) => mesh.isPickable &&\n mesh.isVisible &&\n mesh.isReady() &&\n mesh.isEnabled() &&\n (mesh.enablePointerMoveEvents || scene.constantlyUpdateMeshUnderPointer || mesh._getActionManagerForTrigger() !== null) &&\n (!scene.cameraToUseForPointers || (scene.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0);\n }\n const pickResult = scene._registeredActions > 0 || scene.constantlyUpdateMeshUnderPointer ? this._pickMove(evt) : null;\n this._processPointerMove(pickResult, evt);\n };\n this._onPointerDown = (evt) => {\n var _a;\n this._totalPointersPressed++;\n this._pickedDownMesh = null;\n this._meshPickProceed = false;\n // If ExclusiveDoubleClickMode is true, we need to resolve any pending delayed clicks\n if (InputManager.ExclusiveDoubleClickMode) {\n for (let i = 0; i < this._delayedClicks.length; i++) {\n if (this._delayedClicks[i]) {\n // If the button that was pressed is the same as the one that was released,\n // just clear the timer. This will be resolved in the up event.\n if (evt.button === i) {\n clearTimeout((_a = this._delayedClicks[i]) === null || _a === void 0 ? void 0 : _a.timeoutId);\n }\n else {\n // Otherwise, we need to resolve the click\n const clickInfo = this._delayedClicks[i].clickInfo;\n this._doubleClickOccured = false;\n clickInfo.singleClick = true;\n clickInfo.ignore = false;\n const prevEvt = this._delayedClicks[i].evt;\n const type = PointerEventTypes.POINTERTAP;\n const pi = new PointerInfo(type, prevEvt, this._currentPickResult);\n if (scene.onPointerObservable.hasObservers() && scene.onPointerObservable.hasSpecificMask(type)) {\n scene.onPointerObservable.notifyObservers(pi, type);\n }\n // Clear the delayed click\n this._delayedClicks[i] = null;\n }\n }\n }\n }\n this._updatePointerPosition(evt);\n if (this._swipeButtonPressed === -1) {\n this._swipeButtonPressed = evt.button;\n }\n if (scene.preventDefaultOnPointerDown && elementToAttachTo) {\n evt.preventDefault();\n elementToAttachTo.focus();\n }\n this._startingPointerPosition.x = this._pointerX;\n this._startingPointerPosition.y = this._pointerY;\n this._startingPointerTime = Date.now();\n // PreObservable support\n if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERDOWN)) {\n return;\n }\n if (!scene.cameraToUseForPointers && !scene.activeCamera) {\n return;\n }\n this._pointerCaptures[evt.pointerId] = true;\n if (!scene.pointerDownPredicate) {\n scene.pointerDownPredicate = (mesh) => {\n return (mesh.isPickable &&\n mesh.isVisible &&\n mesh.isReady() &&\n mesh.isEnabled() &&\n (!scene.cameraToUseForPointers || (scene.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0));\n };\n }\n // Meshes\n this._pickedDownMesh = null;\n let pickResult;\n if (scene.skipPointerDownPicking || (scene._registeredActions === 0 && !this._checkForPicking() && !scene.onPointerDown)) {\n pickResult = new PickingInfo();\n }\n else {\n pickResult = scene.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, scene.pointerDownPredicate, scene.pointerDownFastCheck, scene.cameraToUseForPointers);\n }\n this._processPointerDown(pickResult, evt);\n };\n this._onPointerUp = (evt) => {\n if (this._totalPointersPressed === 0) {\n // We are attaching the pointer up to windows because of a bug in FF\n return; // So we need to test it the pointer down was pressed before.\n }\n this._totalPointersPressed--;\n this._pickedUpMesh = null;\n this._meshPickProceed = false;\n this._updatePointerPosition(evt);\n if (scene.preventDefaultOnPointerUp && elementToAttachTo) {\n evt.preventDefault();\n elementToAttachTo.focus();\n }\n this._initClickEvent(scene.onPrePointerObservable, scene.onPointerObservable, evt, (clickInfo, pickResult) => {\n // PreObservable support\n if (scene.onPrePointerObservable.hasObservers()) {\n this._skipPointerTap = false;\n if (!clickInfo.ignore) {\n if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERUP)) {\n // If we're skipping the next observable, we need to reset the swipe state before returning\n if (this._swipeButtonPressed === evt.button) {\n this._isSwiping = false;\n this._swipeButtonPressed = -1;\n }\n return;\n }\n if (!clickInfo.hasSwiped) {\n if (clickInfo.singleClick && scene.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {\n if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERTAP)) {\n this._skipPointerTap = true;\n }\n }\n if (clickInfo.doubleClick && scene.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {\n if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERDOUBLETAP)) {\n this._skipPointerTap = true;\n }\n }\n }\n }\n }\n // There should be a pointer captured at this point so if there isn't we should reset and return\n if (!this._pointerCaptures[evt.pointerId]) {\n if (this._swipeButtonPressed === evt.button) {\n this._isSwiping = false;\n this._swipeButtonPressed = -1;\n }\n return;\n }\n // Only release capture if all buttons are released\n if (evt.buttons === 0) {\n this._pointerCaptures[evt.pointerId] = false;\n }\n if (!scene.cameraToUseForPointers && !scene.activeCamera) {\n return;\n }\n if (!scene.pointerUpPredicate) {\n scene.pointerUpPredicate = (mesh) => {\n return (mesh.isPickable &&\n mesh.isVisible &&\n mesh.isReady() &&\n mesh.isEnabled() &&\n (!scene.cameraToUseForPointers || (scene.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0));\n };\n }\n // Meshes\n if (!this._meshPickProceed && ((AbstractActionManager && AbstractActionManager.HasTriggers) || this._checkForPicking() || scene.onPointerUp)) {\n this._initActionManager(null, clickInfo);\n }\n if (!pickResult) {\n pickResult = this._currentPickResult;\n }\n this._processPointerUp(pickResult, evt, clickInfo);\n this._previousPickResult = this._currentPickResult;\n if (this._swipeButtonPressed === evt.button) {\n this._isSwiping = false;\n this._swipeButtonPressed = -1;\n }\n });\n };\n this._onKeyDown = (evt) => {\n const type = KeyboardEventTypes.KEYDOWN;\n if (scene.onPreKeyboardObservable.hasObservers()) {\n const pi = new KeyboardInfoPre(type, evt);\n scene.onPreKeyboardObservable.notifyObservers(pi, type);\n if (pi.skipOnKeyboardObservable) {\n return;\n }\n }\n if (scene.onKeyboardObservable.hasObservers()) {\n const pi = new KeyboardInfo(type, evt);\n scene.onKeyboardObservable.notifyObservers(pi, type);\n }\n if (scene.actionManager) {\n scene.actionManager.processTrigger(14, ActionEvent.CreateNewFromScene(scene, evt));\n }\n };\n this._onKeyUp = (evt) => {\n const type = KeyboardEventTypes.KEYUP;\n if (scene.onPreKeyboardObservable.hasObservers()) {\n const pi = new KeyboardInfoPre(type, evt);\n scene.onPreKeyboardObservable.notifyObservers(pi, type);\n if (pi.skipOnKeyboardObservable) {\n return;\n }\n }\n if (scene.onKeyboardObservable.hasObservers()) {\n const pi = new KeyboardInfo(type, evt);\n scene.onKeyboardObservable.notifyObservers(pi, type);\n }\n if (scene.actionManager) {\n scene.actionManager.processTrigger(15, ActionEvent.CreateNewFromScene(scene, evt));\n }\n };\n // If a device connects that we can handle, wire up the observable\n this._deviceSourceManager.onDeviceConnectedObservable.add((deviceSource) => {\n if (deviceSource.deviceType === DeviceType.Mouse) {\n deviceSource.onInputChangedObservable.add((eventData) => {\n if (eventData.inputIndex === PointerInput.LeftClick ||\n eventData.inputIndex === PointerInput.MiddleClick ||\n eventData.inputIndex === PointerInput.RightClick ||\n eventData.inputIndex === PointerInput.BrowserBack ||\n eventData.inputIndex === PointerInput.BrowserForward) {\n if (attachDown && deviceSource.getInput(eventData.inputIndex) === 1) {\n this._onPointerDown(eventData);\n }\n else if (attachUp && deviceSource.getInput(eventData.inputIndex) === 0) {\n this._onPointerUp(eventData);\n }\n }\n else if (attachMove) {\n if (eventData.inputIndex === PointerInput.Move) {\n this._onPointerMove(eventData);\n }\n else if (eventData.inputIndex === PointerInput.MouseWheelX ||\n eventData.inputIndex === PointerInput.MouseWheelY ||\n eventData.inputIndex === PointerInput.MouseWheelZ) {\n this._onPointerMove(eventData);\n }\n }\n });\n }\n else if (deviceSource.deviceType === DeviceType.Touch) {\n deviceSource.onInputChangedObservable.add((eventData) => {\n if (eventData.inputIndex === PointerInput.LeftClick) {\n if (attachDown && deviceSource.getInput(eventData.inputIndex) === 1) {\n this._onPointerDown(eventData);\n if (this._totalPointersPressed > 1) {\n this._isMultiTouchGesture = true;\n }\n }\n else if (attachUp && deviceSource.getInput(eventData.inputIndex) === 0) {\n this._onPointerUp(eventData);\n if (this._totalPointersPressed === 0) {\n this._isMultiTouchGesture = false;\n }\n }\n }\n if (attachMove && eventData.inputIndex === PointerInput.Move) {\n this._onPointerMove(eventData);\n }\n });\n }\n else if (deviceSource.deviceType === DeviceType.Keyboard) {\n deviceSource.onInputChangedObservable.add((eventData) => {\n if (eventData.type === \"keydown\") {\n this._onKeyDown(eventData);\n }\n else if (eventData.type === \"keyup\") {\n this._onKeyUp(eventData);\n }\n });\n }\n });\n this._alreadyAttached = true;\n }\n /**\n * Detaches all event handlers\n */\n detachControl() {\n if (this._alreadyAttached) {\n this._deviceSourceManager.dispose();\n this._deviceSourceManager = null;\n // Cursor\n if (this._alreadyAttachedTo && !this._scene.doNotHandleCursors) {\n this._alreadyAttachedTo.style.cursor = this._scene.defaultCursor;\n }\n this._alreadyAttached = false;\n this._alreadyAttachedTo = null;\n }\n }\n /**\n * Force the value of meshUnderPointer\n * @param mesh - defines the mesh to use\n * @param pointerId - optional pointer id when using more than one pointer. Defaults to 0\n * @param pickResult - optional pickingInfo data used to find mesh\n * @param evt - optional pointer event\n */\n setPointerOverMesh(mesh, pointerId = 0, pickResult, evt) {\n if (this._meshUnderPointerId[pointerId] === mesh && (!mesh || !mesh._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting)) {\n return;\n }\n const underPointerMesh = this._meshUnderPointerId[pointerId];\n let actionManager;\n if (underPointerMesh) {\n actionManager = underPointerMesh._getActionManagerForTrigger(10);\n if (actionManager) {\n actionManager.processTrigger(10, ActionEvent.CreateNew(underPointerMesh, evt, { pointerId }));\n }\n }\n if (mesh) {\n this._meshUnderPointerId[pointerId] = mesh;\n this._pointerOverMesh = mesh;\n actionManager = mesh._getActionManagerForTrigger(9);\n if (actionManager) {\n actionManager.processTrigger(9, ActionEvent.CreateNew(mesh, evt, { pointerId, pickResult }));\n }\n }\n else {\n delete this._meshUnderPointerId[pointerId];\n this._pointerOverMesh = null;\n }\n }\n /**\n * Gets the mesh under the pointer\n * @returns a Mesh or null if no mesh is under the pointer\n */\n getPointerOverMesh() {\n return this.meshUnderPointer;\n }\n /**\n * @param mesh - Mesh to invalidate\n * @internal\n */\n _invalidateMesh(mesh) {\n if (this._pointerOverMesh === mesh) {\n this._pointerOverMesh = null;\n }\n if (this._pickedDownMesh === mesh) {\n this._pickedDownMesh = null;\n }\n if (this._pickedUpMesh === mesh) {\n this._pickedUpMesh = null;\n }\n for (const pointerId in this._meshUnderPointerId) {\n if (this._meshUnderPointerId[pointerId] === mesh) {\n delete this._meshUnderPointerId[pointerId];\n }\n }\n }\n}\n/** The distance in pixel that you have to move to prevent some events */\nInputManager.DragMovementThreshold = 10; // in pixels\n/** Time in milliseconds to wait to raise long press events if button is still pressed */\nInputManager.LongPressDelay = 500; // in milliseconds\n/** Time in milliseconds with two consecutive clicks will be considered as a double click */\nInputManager.DoubleClickDelay = 300; // in milliseconds\n/**\n * This flag will modify the behavior so that, when true, a click will happen if and only if\n * another click DOES NOT happen within the DoubleClickDelay time frame. If another click does\n * happen within that time frame, the first click will not fire an event and and a double click will occur.\n */\nInputManager.ExclusiveDoubleClickMode = false;\n//# sourceMappingURL=scene.inputManager.js.map","/** Defines the cross module constantsused by lights to avoid circular dependencies */\nexport class LightConstants {\n /**\n * Sort function to order lights for rendering.\n * @param a First Light object to compare to second.\n * @param b Second Light object to compare first.\n * @returns -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.\n */\n static CompareLightsPriority(a, b) {\n //shadow-casting lights have priority over non-shadow-casting lights\n //the renderPriority is a secondary sort criterion\n if (a.shadowEnabled !== b.shadowEnabled) {\n return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);\n }\n return b.renderPriority - a.renderPriority;\n }\n}\n/**\n * Falloff Default: light is falling off following the material specification:\n * standard material is using standard falloff whereas pbr material can request special falloff per materials.\n */\nLightConstants.FALLOFF_DEFAULT = 0;\n/**\n * Falloff Physical: light is falling off following the inverse squared distance law.\n */\nLightConstants.FALLOFF_PHYSICAL = 1;\n/**\n * Falloff gltf: light is falling off as described in the gltf moving to PBR document\n * to enhance interoperability with other engines.\n */\nLightConstants.FALLOFF_GLTF = 2;\n/**\n * Falloff Standard: light is falling off like in the standard material\n * to enhance interoperability with other materials.\n */\nLightConstants.FALLOFF_STANDARD = 3;\n//lightmapMode Consts\n/**\n * If every light affecting the material is in this lightmapMode,\n * material.lightmapTexture adds or multiplies\n * (depends on material.useLightmapAsShadowmap)\n * after every other light calculations.\n */\nLightConstants.LIGHTMAP_DEFAULT = 0;\n/**\n * material.lightmapTexture as only diffuse lighting from this light\n * adds only specular lighting from this light\n * adds dynamic shadows\n */\nLightConstants.LIGHTMAP_SPECULAR = 1;\n/**\n * material.lightmapTexture as only lighting\n * no light calculation from this light\n * only adds dynamic shadows from this light\n */\nLightConstants.LIGHTMAP_SHADOWSONLY = 2;\n// Intensity Mode Consts\n/**\n * Each light type uses the default quantity according to its type:\n * point/spot lights use luminous intensity\n * directional lights use illuminance\n */\nLightConstants.INTENSITYMODE_AUTOMATIC = 0;\n/**\n * lumen (lm)\n */\nLightConstants.INTENSITYMODE_LUMINOUSPOWER = 1;\n/**\n * candela (lm/sr)\n */\nLightConstants.INTENSITYMODE_LUMINOUSINTENSITY = 2;\n/**\n * lux (lm/m^2)\n */\nLightConstants.INTENSITYMODE_ILLUMINANCE = 3;\n/**\n * nit (cd/m^2)\n */\nLightConstants.INTENSITYMODE_LUMINANCE = 4;\n// Light types ids const.\n/**\n * Light type const id of the point light.\n */\nLightConstants.LIGHTTYPEID_POINTLIGHT = 0;\n/**\n * Light type const id of the directional light.\n */\nLightConstants.LIGHTTYPEID_DIRECTIONALLIGHT = 1;\n/**\n * Light type const id of the spot light.\n */\nLightConstants.LIGHTTYPEID_SPOTLIGHT = 2;\n/**\n * Light type const id of the hemispheric light.\n */\nLightConstants.LIGHTTYPEID_HEMISPHERICLIGHT = 3;\n//# sourceMappingURL=lightConstants.js.map","\n/**\n * Class used to represent data loading progression\n */\nexport class SceneLoaderFlags {\n /**\n * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data\n */\n static get ForceFullSceneLoadingForIncremental() {\n return SceneLoaderFlags._ForceFullSceneLoadingForIncremental;\n }\n static set ForceFullSceneLoadingForIncremental(value) {\n SceneLoaderFlags._ForceFullSceneLoadingForIncremental = value;\n }\n /**\n * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene\n */\n static get ShowLoadingScreen() {\n return SceneLoaderFlags._ShowLoadingScreen;\n }\n static set ShowLoadingScreen(value) {\n SceneLoaderFlags._ShowLoadingScreen = value;\n }\n /**\n * Defines the current logging level (while loading the scene)\n * @ignorenaming\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static get loggingLevel() {\n return SceneLoaderFlags._LoggingLevel;\n }\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static set loggingLevel(value) {\n SceneLoaderFlags._LoggingLevel = value;\n }\n /**\n * Gets or set a boolean indicating if matrix weights must be cleaned upon loading\n */\n static get CleanBoneMatrixWeights() {\n return SceneLoaderFlags._CleanBoneMatrixWeights;\n }\n static set CleanBoneMatrixWeights(value) {\n SceneLoaderFlags._CleanBoneMatrixWeights = value;\n }\n}\n// Flags\nSceneLoaderFlags._ForceFullSceneLoadingForIncremental = false;\nSceneLoaderFlags._ShowLoadingScreen = true;\nSceneLoaderFlags._CleanBoneMatrixWeights = false;\nSceneLoaderFlags._LoggingLevel = 0;\n//# sourceMappingURL=sceneLoaderFlags.js.map","import { Observable } from \"../../Misc/observable.js\";\nimport { TextureSampler } from \"./textureSampler.js\";\n/**\n * Defines the source of the internal texture\n */\nexport var InternalTextureSource;\n(function (InternalTextureSource) {\n /**\n * The source of the texture data is unknown\n */\n InternalTextureSource[InternalTextureSource[\"Unknown\"] = 0] = \"Unknown\";\n /**\n * Texture data comes from an URL\n */\n InternalTextureSource[InternalTextureSource[\"Url\"] = 1] = \"Url\";\n /**\n * Texture data is only used for temporary storage\n */\n InternalTextureSource[InternalTextureSource[\"Temp\"] = 2] = \"Temp\";\n /**\n * Texture data comes from raw data (ArrayBuffer)\n */\n InternalTextureSource[InternalTextureSource[\"Raw\"] = 3] = \"Raw\";\n /**\n * Texture content is dynamic (video or dynamic texture)\n */\n InternalTextureSource[InternalTextureSource[\"Dynamic\"] = 4] = \"Dynamic\";\n /**\n * Texture content is generated by rendering to it\n */\n InternalTextureSource[InternalTextureSource[\"RenderTarget\"] = 5] = \"RenderTarget\";\n /**\n * Texture content is part of a multi render target process\n */\n InternalTextureSource[InternalTextureSource[\"MultiRenderTarget\"] = 6] = \"MultiRenderTarget\";\n /**\n * Texture data comes from a cube data file\n */\n InternalTextureSource[InternalTextureSource[\"Cube\"] = 7] = \"Cube\";\n /**\n * Texture data comes from a raw cube data\n */\n InternalTextureSource[InternalTextureSource[\"CubeRaw\"] = 8] = \"CubeRaw\";\n /**\n * Texture data come from a prefiltered cube data file\n */\n InternalTextureSource[InternalTextureSource[\"CubePrefiltered\"] = 9] = \"CubePrefiltered\";\n /**\n * Texture content is raw 3D data\n */\n InternalTextureSource[InternalTextureSource[\"Raw3D\"] = 10] = \"Raw3D\";\n /**\n * Texture content is raw 2D array data\n */\n InternalTextureSource[InternalTextureSource[\"Raw2DArray\"] = 11] = \"Raw2DArray\";\n /**\n * Texture content is a depth/stencil texture\n */\n InternalTextureSource[InternalTextureSource[\"DepthStencil\"] = 12] = \"DepthStencil\";\n /**\n * Texture data comes from a raw cube data encoded with RGBD\n */\n InternalTextureSource[InternalTextureSource[\"CubeRawRGBD\"] = 13] = \"CubeRawRGBD\";\n /**\n * Texture content is a depth texture\n */\n InternalTextureSource[InternalTextureSource[\"Depth\"] = 14] = \"Depth\";\n})(InternalTextureSource || (InternalTextureSource = {}));\n/**\n * Class used to store data associated with WebGL texture data for the engine\n * This class should not be used directly\n */\nexport class InternalTexture extends TextureSampler {\n /**\n * Gets a boolean indicating if the texture uses mipmaps\n * TODO implements useMipMaps as a separate setting from generateMipMaps\n */\n get useMipMaps() {\n return this.generateMipMaps;\n }\n set useMipMaps(value) {\n this.generateMipMaps = value;\n }\n /** Gets the unique id of the internal texture */\n get uniqueId() {\n return this._uniqueId;\n }\n /** @internal */\n _setUniqueId(id) {\n this._uniqueId = id;\n }\n /**\n * Gets the Engine the texture belongs to.\n * @returns The babylon engine\n */\n getEngine() {\n return this._engine;\n }\n /**\n * Gets the data source type of the texture\n */\n get source() {\n return this._source;\n }\n /**\n * Creates a new InternalTexture\n * @param engine defines the engine to use\n * @param source defines the type of data that will be used\n * @param delayAllocation if the texture allocation should be delayed (default: false)\n */\n constructor(engine, source, delayAllocation = false) {\n super();\n /**\n * Defines if the texture is ready\n */\n this.isReady = false;\n /**\n * Defines if the texture is a cube texture\n */\n this.isCube = false;\n /**\n * Defines if the texture contains 3D data\n */\n this.is3D = false;\n /**\n * Defines if the texture contains 2D array data\n */\n this.is2DArray = false;\n /**\n * Defines if the texture contains multiview data\n */\n this.isMultiview = false;\n /**\n * Gets the URL used to load this texture\n */\n this.url = \"\";\n /**\n * Gets a boolean indicating if the texture needs mipmaps generation\n */\n this.generateMipMaps = false;\n /**\n * Gets the number of samples used by the texture (WebGL2+ only)\n */\n this.samples = 0;\n /**\n * Gets the type of the texture (int, float...)\n */\n this.type = -1;\n /**\n * Gets the format of the texture (RGB, RGBA...)\n */\n this.format = -1;\n /**\n * Observable called when the texture is loaded\n */\n this.onLoadedObservable = new Observable();\n /**\n * Observable called when the texture load is raising an error\n */\n this.onErrorObservable = new Observable();\n /**\n * If this callback is defined it will be called instead of the default _rebuild function\n */\n this.onRebuildCallback = null;\n /**\n * Gets the width of the texture\n */\n this.width = 0;\n /**\n * Gets the height of the texture\n */\n this.height = 0;\n /**\n * Gets the depth of the texture\n */\n this.depth = 0;\n /**\n * Gets the initial width of the texture (It could be rescaled if the current system does not support non power of two textures)\n */\n this.baseWidth = 0;\n /**\n * Gets the initial height of the texture (It could be rescaled if the current system does not support non power of two textures)\n */\n this.baseHeight = 0;\n /**\n * Gets the initial depth of the texture (It could be rescaled if the current system does not support non power of two textures)\n */\n this.baseDepth = 0;\n /**\n * Gets a boolean indicating if the texture is inverted on Y axis\n */\n this.invertY = false;\n // Private\n /** @internal */\n this._invertVScale = false;\n /** @internal */\n this._associatedChannel = -1;\n /** @internal */\n this._source = InternalTextureSource.Unknown;\n /** @internal */\n this._buffer = null;\n /** @internal */\n this._bufferView = null;\n /** @internal */\n this._bufferViewArray = null;\n /** @internal */\n this._bufferViewArrayArray = null;\n /** @internal */\n this._size = 0;\n /** @internal */\n this._extension = \"\";\n /** @internal */\n this._files = null;\n /** @internal */\n this._workingCanvas = null;\n /** @internal */\n this._workingContext = null;\n /** @internal */\n this._cachedCoordinatesMode = null;\n /** @internal */\n this._isDisabled = false;\n /** @internal */\n this._compression = null;\n /** @internal */\n this._sphericalPolynomial = null;\n /** @internal */\n this._sphericalPolynomialPromise = null;\n /** @internal */\n this._sphericalPolynomialComputed = false;\n /** @internal */\n this._lodGenerationScale = 0;\n /** @internal */\n this._lodGenerationOffset = 0;\n /** @internal */\n this._useSRGBBuffer = false;\n // The following three fields helps sharing generated fixed LODs for texture filtering\n // In environment not supporting the textureLOD extension like EDGE. They are for internal use only.\n // They are at the level of the gl texture to benefit from the cache.\n /** @internal */\n this._lodTextureHigh = null;\n /** @internal */\n this._lodTextureMid = null;\n /** @internal */\n this._lodTextureLow = null;\n /** @internal */\n this._isRGBD = false;\n /** @internal */\n this._linearSpecularLOD = false;\n /** @internal */\n this._irradianceTexture = null;\n /** @internal */\n this._hardwareTexture = null;\n /** @internal */\n this._maxLodLevel = null;\n /** @internal */\n this._references = 1;\n /** @internal */\n this._gammaSpace = null;\n this._engine = engine;\n this._source = source;\n this._uniqueId = InternalTexture._Counter++;\n if (!delayAllocation) {\n this._hardwareTexture = engine._createHardwareTexture();\n }\n }\n /**\n * Increments the number of references (ie. the number of Texture that point to it)\n */\n incrementReferences() {\n this._references++;\n }\n /**\n * Change the size of the texture (not the size of the content)\n * @param width defines the new width\n * @param height defines the new height\n * @param depth defines the new depth (1 by default)\n */\n updateSize(width, height, depth = 1) {\n this._engine.updateTextureDimensions(this, width, height, depth);\n this.width = width;\n this.height = height;\n this.depth = depth;\n this.baseWidth = width;\n this.baseHeight = height;\n this.baseDepth = depth;\n this._size = width * height * depth;\n }\n /** @internal */\n _rebuild() {\n var _a;\n this.isReady = false;\n this._cachedCoordinatesMode = null;\n this._cachedWrapU = null;\n this._cachedWrapV = null;\n this._cachedWrapR = null;\n this._cachedAnisotropicFilteringLevel = null;\n if (this.onRebuildCallback) {\n const data = this.onRebuildCallback(this);\n const swapAndSetIsReady = (proxyInternalTexture) => {\n proxyInternalTexture._swapAndDie(this, false);\n this.isReady = data.isReady;\n };\n if (data.isAsync) {\n data.proxy.then(swapAndSetIsReady);\n }\n else {\n swapAndSetIsReady(data.proxy);\n }\n return;\n }\n let proxy;\n switch (this.source) {\n case InternalTextureSource.Temp:\n break;\n case InternalTextureSource.Url:\n proxy = this._engine.createTexture((_a = this._originalUrl) !== null && _a !== void 0 ? _a : this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, \n // Do not use Proxy here as it could be fully synchronous\n // and proxy would be undefined.\n (temp) => {\n temp._swapAndDie(this, false);\n this.isReady = true;\n }, null, this._buffer, undefined, this.format, this._extension, undefined, undefined, undefined, this._useSRGBBuffer);\n return;\n case InternalTextureSource.Raw:\n proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type, undefined, this._useSRGBBuffer);\n proxy._swapAndDie(this, false);\n this.isReady = true;\n break;\n case InternalTextureSource.Raw3D:\n proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type);\n proxy._swapAndDie(this, false);\n this.isReady = true;\n break;\n case InternalTextureSource.Raw2DArray:\n proxy = this._engine.createRawTexture2DArray(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type);\n proxy._swapAndDie(this, false);\n this.isReady = true;\n break;\n case InternalTextureSource.Dynamic:\n proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);\n proxy._swapAndDie(this, false);\n this._engine.updateDynamicTexture(this, this._engine.getRenderingCanvas(), this.invertY, undefined, undefined, true);\n // The engine will make sure to update content so no need to flag it as isReady = true\n break;\n case InternalTextureSource.Cube:\n proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, () => {\n proxy._swapAndDie(this, false);\n this.isReady = true;\n }, null, this.format, this._extension, false, 0, 0, null, undefined, this._useSRGBBuffer);\n return;\n case InternalTextureSource.CubeRaw:\n proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);\n proxy._swapAndDie(this, false);\n this.isReady = true;\n break;\n case InternalTextureSource.CubeRawRGBD:\n // This case is being handeled by the environment texture tools and is not a part of the rebuild process.\n // To use CubeRawRGBD use updateRGBDAsync on the cube texture.\n return;\n case InternalTextureSource.CubePrefiltered:\n proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, (proxy) => {\n if (proxy) {\n proxy._swapAndDie(this, false);\n }\n this.isReady = true;\n }, null, this.format, this._extension);\n proxy._sphericalPolynomial = this._sphericalPolynomial;\n return;\n }\n }\n /**\n * @internal\n */\n _swapAndDie(target, swapAll = true) {\n // TODO what about refcount on target?\n var _a;\n (_a = this._hardwareTexture) === null || _a === void 0 ? void 0 : _a.setUsage(target._source, this.generateMipMaps, this.isCube, this.width, this.height);\n target._hardwareTexture = this._hardwareTexture;\n if (swapAll) {\n target._isRGBD = this._isRGBD;\n }\n if (this._lodTextureHigh) {\n if (target._lodTextureHigh) {\n target._lodTextureHigh.dispose();\n }\n target._lodTextureHigh = this._lodTextureHigh;\n }\n if (this._lodTextureMid) {\n if (target._lodTextureMid) {\n target._lodTextureMid.dispose();\n }\n target._lodTextureMid = this._lodTextureMid;\n }\n if (this._lodTextureLow) {\n if (target._lodTextureLow) {\n target._lodTextureLow.dispose();\n }\n target._lodTextureLow = this._lodTextureLow;\n }\n if (this._irradianceTexture) {\n if (target._irradianceTexture) {\n target._irradianceTexture.dispose();\n }\n target._irradianceTexture = this._irradianceTexture;\n }\n const cache = this._engine.getLoadedTexturesCache();\n let index = cache.indexOf(this);\n if (index !== -1) {\n cache.splice(index, 1);\n }\n index = cache.indexOf(target);\n if (index === -1) {\n cache.push(target);\n }\n }\n /**\n * Dispose the current allocated resources\n */\n dispose() {\n this._references--;\n this.onLoadedObservable.clear();\n this.onErrorObservable.clear();\n if (this._references === 0) {\n this._engine._releaseTexture(this);\n this._hardwareTexture = null;\n }\n }\n}\n/** @internal */\nInternalTexture._Counter = 0;\n//# sourceMappingURL=internalTexture.js.map","\n/**\n * Class used to store a texture sampler data\n */\nexport class TextureSampler {\n /**\n * | Value | Type | Description |\n * | ----- | ------------------ | ----------- |\n * | 0 | CLAMP_ADDRESSMODE | |\n * | 1 | WRAP_ADDRESSMODE | |\n * | 2 | MIRROR_ADDRESSMODE | |\n */\n get wrapU() {\n return this._cachedWrapU;\n }\n set wrapU(value) {\n this._cachedWrapU = value;\n }\n /**\n * | Value | Type | Description |\n * | ----- | ------------------ | ----------- |\n * | 0 | CLAMP_ADDRESSMODE | |\n * | 1 | WRAP_ADDRESSMODE | |\n * | 2 | MIRROR_ADDRESSMODE | |\n */\n get wrapV() {\n return this._cachedWrapV;\n }\n set wrapV(value) {\n this._cachedWrapV = value;\n }\n /**\n * | Value | Type | Description |\n * | ----- | ------------------ | ----------- |\n * | 0 | CLAMP_ADDRESSMODE | |\n * | 1 | WRAP_ADDRESSMODE | |\n * | 2 | MIRROR_ADDRESSMODE | |\n */\n get wrapR() {\n return this._cachedWrapR;\n }\n set wrapR(value) {\n this._cachedWrapR = value;\n }\n /**\n * With compliant hardware and browser (supporting anisotropic filtering)\n * this defines the level of anisotropic filtering in the texture.\n * The higher the better but the slower.\n */\n get anisotropicFilteringLevel() {\n return this._cachedAnisotropicFilteringLevel;\n }\n set anisotropicFilteringLevel(value) {\n this._cachedAnisotropicFilteringLevel = value;\n }\n /**\n * Gets or sets the comparison function (513, 514, etc). Set 0 to not use a comparison function\n */\n get comparisonFunction() {\n return this._comparisonFunction;\n }\n set comparisonFunction(value) {\n this._comparisonFunction = value;\n }\n /**\n * Indicates to use the mip maps (if available on the texture).\n * Thanks to this flag, you can instruct the sampler to not sample the mipmaps even if they exist (and if the sampling mode is set to a value that normally samples the mipmaps!)\n */\n get useMipMaps() {\n return this._useMipMaps;\n }\n set useMipMaps(value) {\n this._useMipMaps = value;\n }\n /**\n * Creates a Sampler instance\n */\n constructor() {\n /**\n * Gets the sampling mode of the texture\n */\n this.samplingMode = -1;\n this._useMipMaps = true;\n /** @internal */\n this._cachedWrapU = null;\n /** @internal */\n this._cachedWrapV = null;\n /** @internal */\n this._cachedWrapR = null;\n /** @internal */\n this._cachedAnisotropicFilteringLevel = null;\n /** @internal */\n this._comparisonFunction = 0;\n }\n /**\n * Sets all the parameters of the sampler\n * @param wrapU u address mode (default: TEXTURE_WRAP_ADDRESSMODE)\n * @param wrapV v address mode (default: TEXTURE_WRAP_ADDRESSMODE)\n * @param wrapR r address mode (default: TEXTURE_WRAP_ADDRESSMODE)\n * @param anisotropicFilteringLevel anisotropic level (default: 1)\n * @param samplingMode sampling mode (default: 2)\n * @param comparisonFunction comparison function (default: 0 - no comparison function)\n * @returns the current sampler instance\n */\n setParameters(wrapU = 1, wrapV = 1, wrapR = 1, anisotropicFilteringLevel = 1, samplingMode = 2, comparisonFunction = 0) {\n this._cachedWrapU = wrapU;\n this._cachedWrapV = wrapV;\n this._cachedWrapR = wrapR;\n this._cachedAnisotropicFilteringLevel = anisotropicFilteringLevel;\n this.samplingMode = samplingMode;\n this._comparisonFunction = comparisonFunction;\n return this;\n }\n /**\n * Compares this sampler with another one\n * @param other sampler to compare with\n * @returns true if the samplers have the same parametres, else false\n */\n compareSampler(other) {\n return (this._cachedWrapU === other._cachedWrapU &&\n this._cachedWrapV === other._cachedWrapV &&\n this._cachedWrapR === other._cachedWrapR &&\n this._cachedAnisotropicFilteringLevel === other._cachedAnisotropicFilteringLevel &&\n this.samplingMode === other.samplingMode &&\n this._comparisonFunction === other._comparisonFunction &&\n this._useMipMaps === other._useMipMaps);\n }\n}\n//# sourceMappingURL=textureSampler.js.map","/** @internal */\nexport function addClipPlaneUniforms(uniforms) {\n if (uniforms.indexOf(\"vClipPlane\") === -1) {\n uniforms.push(\"vClipPlane\");\n }\n if (uniforms.indexOf(\"vClipPlane2\") === -1) {\n uniforms.push(\"vClipPlane2\");\n }\n if (uniforms.indexOf(\"vClipPlane3\") === -1) {\n uniforms.push(\"vClipPlane3\");\n }\n if (uniforms.indexOf(\"vClipPlane4\") === -1) {\n uniforms.push(\"vClipPlane4\");\n }\n if (uniforms.indexOf(\"vClipPlane5\") === -1) {\n uniforms.push(\"vClipPlane5\");\n }\n if (uniforms.indexOf(\"vClipPlane6\") === -1) {\n uniforms.push(\"vClipPlane6\");\n }\n}\n/** @internal */\nexport function prepareStringDefinesForClipPlanes(primaryHolder, secondaryHolder, defines) {\n var _a, _b, _c, _d, _e, _f;\n const clipPlane = !!((_a = primaryHolder.clipPlane) !== null && _a !== void 0 ? _a : secondaryHolder.clipPlane);\n const clipPlane2 = !!((_b = primaryHolder.clipPlane2) !== null && _b !== void 0 ? _b : secondaryHolder.clipPlane2);\n const clipPlane3 = !!((_c = primaryHolder.clipPlane3) !== null && _c !== void 0 ? _c : secondaryHolder.clipPlane3);\n const clipPlane4 = !!((_d = primaryHolder.clipPlane4) !== null && _d !== void 0 ? _d : secondaryHolder.clipPlane4);\n const clipPlane5 = !!((_e = primaryHolder.clipPlane5) !== null && _e !== void 0 ? _e : secondaryHolder.clipPlane5);\n const clipPlane6 = !!((_f = primaryHolder.clipPlane6) !== null && _f !== void 0 ? _f : secondaryHolder.clipPlane6);\n if (clipPlane)\n defines.push(\"#define CLIPPLANE\");\n if (clipPlane2)\n defines.push(\"#define CLIPPLANE2\");\n if (clipPlane3)\n defines.push(\"#define CLIPPLANE3\");\n if (clipPlane4)\n defines.push(\"#define CLIPPLANE4\");\n if (clipPlane5)\n defines.push(\"#define CLIPPLANE5\");\n if (clipPlane6)\n defines.push(\"#define CLIPPLANE6\");\n}\n/** @internal */\nexport function prepareDefinesForClipPlanes(primaryHolder, secondaryHolder, defines) {\n var _a, _b, _c, _d, _e, _f;\n let changed = false;\n const clipPlane = !!((_a = primaryHolder.clipPlane) !== null && _a !== void 0 ? _a : secondaryHolder.clipPlane);\n const clipPlane2 = !!((_b = primaryHolder.clipPlane2) !== null && _b !== void 0 ? _b : secondaryHolder.clipPlane2);\n const clipPlane3 = !!((_c = primaryHolder.clipPlane3) !== null && _c !== void 0 ? _c : secondaryHolder.clipPlane3);\n const clipPlane4 = !!((_d = primaryHolder.clipPlane4) !== null && _d !== void 0 ? _d : secondaryHolder.clipPlane4);\n const clipPlane5 = !!((_e = primaryHolder.clipPlane5) !== null && _e !== void 0 ? _e : secondaryHolder.clipPlane5);\n const clipPlane6 = !!((_f = primaryHolder.clipPlane6) !== null && _f !== void 0 ? _f : secondaryHolder.clipPlane6);\n // Do not factorize this code, it breaks browsers optimizations.\n if (defines[\"CLIPPLANE\"] !== clipPlane) {\n defines[\"CLIPPLANE\"] = clipPlane;\n changed = true;\n }\n if (defines[\"CLIPPLANE2\"] !== clipPlane2) {\n defines[\"CLIPPLANE2\"] = clipPlane2;\n changed = true;\n }\n if (defines[\"CLIPPLANE3\"] !== clipPlane3) {\n defines[\"CLIPPLANE3\"] = clipPlane3;\n changed = true;\n }\n if (defines[\"CLIPPLANE4\"] !== clipPlane4) {\n defines[\"CLIPPLANE4\"] = clipPlane4;\n changed = true;\n }\n if (defines[\"CLIPPLANE5\"] !== clipPlane5) {\n defines[\"CLIPPLANE5\"] = clipPlane5;\n changed = true;\n }\n if (defines[\"CLIPPLANE6\"] !== clipPlane6) {\n defines[\"CLIPPLANE6\"] = clipPlane6;\n changed = true;\n }\n return changed;\n}\n/** @internal */\nexport function bindClipPlane(effect, primaryHolder, secondaryHolder) {\n var _a, _b, _c, _d, _e, _f;\n let clipPlane = (_a = primaryHolder.clipPlane) !== null && _a !== void 0 ? _a : secondaryHolder.clipPlane;\n setClipPlane(effect, \"vClipPlane\", clipPlane);\n clipPlane = (_b = primaryHolder.clipPlane2) !== null && _b !== void 0 ? _b : secondaryHolder.clipPlane2;\n setClipPlane(effect, \"vClipPlane2\", clipPlane);\n clipPlane = (_c = primaryHolder.clipPlane3) !== null && _c !== void 0 ? _c : secondaryHolder.clipPlane3;\n setClipPlane(effect, \"vClipPlane3\", clipPlane);\n clipPlane = (_d = primaryHolder.clipPlane4) !== null && _d !== void 0 ? _d : secondaryHolder.clipPlane4;\n setClipPlane(effect, \"vClipPlane4\", clipPlane);\n clipPlane = (_e = primaryHolder.clipPlane5) !== null && _e !== void 0 ? _e : secondaryHolder.clipPlane5;\n setClipPlane(effect, \"vClipPlane5\", clipPlane);\n clipPlane = (_f = primaryHolder.clipPlane6) !== null && _f !== void 0 ? _f : secondaryHolder.clipPlane6;\n setClipPlane(effect, \"vClipPlane6\", clipPlane);\n}\nfunction setClipPlane(effect, uniformName, clipPlane) {\n if (clipPlane) {\n effect.setFloat4(uniformName, clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);\n }\n}\n//# sourceMappingURL=clipPlaneMaterialHelper.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { SerializationHelper, serialize } from \"../Misc/decorators.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\n/**\n * The color grading curves provide additional color adjustment that is applied after any color grading transform (3D LUT).\n * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.\n * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;\n * corresponding to low luminance, medium luminance, and high luminance areas respectively.\n */\nexport class ColorCurves {\n constructor() {\n this._dirty = true;\n this._tempColor = new Color4(0, 0, 0, 0);\n this._globalCurve = new Color4(0, 0, 0, 0);\n this._highlightsCurve = new Color4(0, 0, 0, 0);\n this._midtonesCurve = new Color4(0, 0, 0, 0);\n this._shadowsCurve = new Color4(0, 0, 0, 0);\n this._positiveCurve = new Color4(0, 0, 0, 0);\n this._negativeCurve = new Color4(0, 0, 0, 0);\n this._globalHue = 30;\n this._globalDensity = 0;\n this._globalSaturation = 0;\n this._globalExposure = 0;\n this._highlightsHue = 30;\n this._highlightsDensity = 0;\n this._highlightsSaturation = 0;\n this._highlightsExposure = 0;\n this._midtonesHue = 30;\n this._midtonesDensity = 0;\n this._midtonesSaturation = 0;\n this._midtonesExposure = 0;\n this._shadowsHue = 30;\n this._shadowsDensity = 0;\n this._shadowsSaturation = 0;\n this._shadowsExposure = 0;\n }\n /**\n * Gets the global Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n get globalHue() {\n return this._globalHue;\n }\n /**\n * Sets the global Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n set globalHue(value) {\n this._globalHue = value;\n this._dirty = true;\n }\n /**\n * Gets the global Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n get globalDensity() {\n return this._globalDensity;\n }\n /**\n * Sets the global Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n set globalDensity(value) {\n this._globalDensity = value;\n this._dirty = true;\n }\n /**\n * Gets the global Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n get globalSaturation() {\n return this._globalSaturation;\n }\n /**\n * Sets the global Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n set globalSaturation(value) {\n this._globalSaturation = value;\n this._dirty = true;\n }\n /**\n * Gets the global Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n get globalExposure() {\n return this._globalExposure;\n }\n /**\n * Sets the global Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n set globalExposure(value) {\n this._globalExposure = value;\n this._dirty = true;\n }\n /**\n * Gets the highlights Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n get highlightsHue() {\n return this._highlightsHue;\n }\n /**\n * Sets the highlights Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n set highlightsHue(value) {\n this._highlightsHue = value;\n this._dirty = true;\n }\n /**\n * Gets the highlights Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n get highlightsDensity() {\n return this._highlightsDensity;\n }\n /**\n * Sets the highlights Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n set highlightsDensity(value) {\n this._highlightsDensity = value;\n this._dirty = true;\n }\n /**\n * Gets the highlights Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n get highlightsSaturation() {\n return this._highlightsSaturation;\n }\n /**\n * Sets the highlights Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n set highlightsSaturation(value) {\n this._highlightsSaturation = value;\n this._dirty = true;\n }\n /**\n * Gets the highlights Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n get highlightsExposure() {\n return this._highlightsExposure;\n }\n /**\n * Sets the highlights Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n set highlightsExposure(value) {\n this._highlightsExposure = value;\n this._dirty = true;\n }\n /**\n * Gets the midtones Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n get midtonesHue() {\n return this._midtonesHue;\n }\n /**\n * Sets the midtones Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n set midtonesHue(value) {\n this._midtonesHue = value;\n this._dirty = true;\n }\n /**\n * Gets the midtones Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n get midtonesDensity() {\n return this._midtonesDensity;\n }\n /**\n * Sets the midtones Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n set midtonesDensity(value) {\n this._midtonesDensity = value;\n this._dirty = true;\n }\n /**\n * Gets the midtones Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n get midtonesSaturation() {\n return this._midtonesSaturation;\n }\n /**\n * Sets the midtones Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n set midtonesSaturation(value) {\n this._midtonesSaturation = value;\n this._dirty = true;\n }\n /**\n * Gets the midtones Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n get midtonesExposure() {\n return this._midtonesExposure;\n }\n /**\n * Sets the midtones Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n set midtonesExposure(value) {\n this._midtonesExposure = value;\n this._dirty = true;\n }\n /**\n * Gets the shadows Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n get shadowsHue() {\n return this._shadowsHue;\n }\n /**\n * Sets the shadows Hue value.\n * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).\n */\n set shadowsHue(value) {\n this._shadowsHue = value;\n this._dirty = true;\n }\n /**\n * Gets the shadows Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n get shadowsDensity() {\n return this._shadowsDensity;\n }\n /**\n * Sets the shadows Density value.\n * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.\n * Values less than zero provide a filter of opposite hue.\n */\n set shadowsDensity(value) {\n this._shadowsDensity = value;\n this._dirty = true;\n }\n /**\n * Gets the shadows Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n get shadowsSaturation() {\n return this._shadowsSaturation;\n }\n /**\n * Sets the shadows Saturation value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.\n */\n set shadowsSaturation(value) {\n this._shadowsSaturation = value;\n this._dirty = true;\n }\n /**\n * Gets the shadows Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n get shadowsExposure() {\n return this._shadowsExposure;\n }\n /**\n * Sets the shadows Exposure value.\n * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.\n */\n set shadowsExposure(value) {\n this._shadowsExposure = value;\n this._dirty = true;\n }\n /**\n * Returns the class name\n * @returns The class name\n */\n getClassName() {\n return \"ColorCurves\";\n }\n /**\n * Binds the color curves to the shader.\n * @param colorCurves The color curve to bind\n * @param effect The effect to bind to\n * @param positiveUniform The positive uniform shader parameter\n * @param neutralUniform The neutral uniform shader parameter\n * @param negativeUniform The negative uniform shader parameter\n */\n static Bind(colorCurves, effect, positiveUniform = \"vCameraColorCurvePositive\", neutralUniform = \"vCameraColorCurveNeutral\", negativeUniform = \"vCameraColorCurveNegative\") {\n if (colorCurves._dirty) {\n colorCurves._dirty = false;\n // Fill in global info.\n colorCurves._getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);\n // Compute highlights info.\n colorCurves._getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);\n colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);\n // Compute midtones info.\n colorCurves._getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);\n colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);\n // Compute shadows info.\n colorCurves._getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);\n colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);\n // Compute deltas (neutral is midtones).\n colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);\n colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);\n }\n if (effect) {\n effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);\n effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);\n effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);\n }\n }\n /**\n * Prepare the list of uniforms associated with the ColorCurves effects.\n * @param uniformsList The list of uniforms used in the effect\n */\n static PrepareUniforms(uniformsList) {\n uniformsList.push(\"vCameraColorCurveNeutral\", \"vCameraColorCurvePositive\", \"vCameraColorCurveNegative\");\n }\n /**\n * Returns color grading data based on a hue, density, saturation and exposure value.\n * @param hue\n * @param density\n * @param saturation The saturation.\n * @param exposure The exposure.\n * @param result The result data container.\n */\n _getColorGradingDataToRef(hue, density, saturation, exposure, result) {\n if (hue == null) {\n return;\n }\n hue = ColorCurves._Clamp(hue, 0, 360);\n density = ColorCurves._Clamp(density, -100, 100);\n saturation = ColorCurves._Clamp(saturation, -100, 100);\n exposure = ColorCurves._Clamp(exposure, -100, 100);\n // Remap the slider/config filter density with non-linear mapping and also scale by half\n // so that the maximum filter density is only 50% control. This provides fine control\n // for small values and reasonable range.\n density = ColorCurves._ApplyColorGradingSliderNonlinear(density);\n density *= 0.5;\n exposure = ColorCurves._ApplyColorGradingSliderNonlinear(exposure);\n if (density < 0) {\n density *= -1;\n hue = (hue + 180) % 360;\n }\n ColorCurves._FromHSBToRef(hue, density, 50 + 0.25 * exposure, result);\n result.scaleToRef(2, result);\n result.a = 1 + 0.01 * saturation;\n }\n /**\n * Takes an input slider value and returns an adjusted value that provides extra control near the centre.\n * @param value The input slider value in range [-100,100].\n * @returns Adjusted value.\n */\n static _ApplyColorGradingSliderNonlinear(value) {\n value /= 100;\n let x = Math.abs(value);\n x = Math.pow(x, 2);\n if (value < 0) {\n x *= -1;\n }\n x *= 100;\n return x;\n }\n /**\n * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).\n * @param hue The hue (H) input.\n * @param saturation The saturation (S) input.\n * @param brightness The brightness (B) input.\n * @param result\n * @result An RGBA color represented as Vector4.\n */\n static _FromHSBToRef(hue, saturation, brightness, result) {\n let h = ColorCurves._Clamp(hue, 0, 360);\n const s = ColorCurves._Clamp(saturation / 100, 0, 1);\n const v = ColorCurves._Clamp(brightness / 100, 0, 1);\n if (s === 0) {\n result.r = v;\n result.g = v;\n result.b = v;\n }\n else {\n // sector 0 to 5\n h /= 60;\n const i = Math.floor(h);\n // fractional part of h\n const f = h - i;\n const p = v * (1 - s);\n const q = v * (1 - s * f);\n const t = v * (1 - s * (1 - f));\n switch (i) {\n case 0:\n result.r = v;\n result.g = t;\n result.b = p;\n break;\n case 1:\n result.r = q;\n result.g = v;\n result.b = p;\n break;\n case 2:\n result.r = p;\n result.g = v;\n result.b = t;\n break;\n case 3:\n result.r = p;\n result.g = q;\n result.b = v;\n break;\n case 4:\n result.r = t;\n result.g = p;\n result.b = v;\n break;\n default:\n // case 5:\n result.r = v;\n result.g = p;\n result.b = q;\n break;\n }\n }\n result.a = 1;\n }\n /**\n * Returns a value clamped between min and max\n * @param value The value to clamp\n * @param min The minimum of value\n * @param max The maximum of value\n * @returns The clamped value.\n */\n static _Clamp(value, min, max) {\n return Math.min(Math.max(value, min), max);\n }\n /**\n * Clones the current color curve instance.\n * @returns The cloned curves\n */\n clone() {\n return SerializationHelper.Clone(() => new ColorCurves(), this);\n }\n /**\n * Serializes the current color curve instance to a json representation.\n * @returns a JSON representation\n */\n serialize() {\n return SerializationHelper.Serialize(this);\n }\n /**\n * Parses the color curve from a json representation.\n * @param source the JSON source to parse\n * @returns The parsed curves\n */\n static Parse(source) {\n return SerializationHelper.Parse(() => new ColorCurves(), source, null, null);\n }\n}\n__decorate([\n serialize()\n], ColorCurves.prototype, \"_globalHue\", void 0);\n__decorate([\n serialize()\n], ColorCurves.prototype, \"_globalDensity\", void 0);\n__decorate([\n serialize()\n], ColorCurves.prototype, \"_globalSaturation\", void 0);\n__decorate([\n serialize()\n], ColorCurves.prototype, \"_globalExposure\", void 0);\n__decorate([\n serialize()\n], ColorCurves.prototype, \"_highlightsHue\", void 0);\n__decorate([\n serialize()\n], ColorCurves.prototype, \"_highlightsDensity\", void 0);\n__decorate([\n serialize()\n], ColorCurves.prototype, \"_highlightsSaturation\", void 0);\n__decorate([\n serialize()\n], ColorCurves.prototype, \"_highlightsExposure\", void 0);\n__decorate([\n serialize()\n], ColorCurves.prototype, \"_midtonesHue\", void 0);\n__decorate([\n serialize()\n], ColorCurves.prototype, \"_midtonesDensity\", void 0);\n__decorate([\n serialize()\n], ColorCurves.prototype, \"_midtonesSaturation\", void 0);\n__decorate([\n serialize()\n], ColorCurves.prototype, \"_midtonesExposure\", void 0);\n// References the dependencies.\nSerializationHelper._ColorCurvesParser = ColorCurves.Parse;\n//# sourceMappingURL=colorCurves.js.map","/** @internal */\nexport class DrawWrapper {\n static IsWrapper(effect) {\n return effect.getPipelineContext === undefined;\n }\n static GetEffect(effect) {\n return effect.getPipelineContext === undefined ? effect.effect : effect;\n }\n constructor(engine, createMaterialContext = true) {\n this.effect = null;\n this.defines = null;\n this.drawContext = engine.createDrawContext();\n if (createMaterialContext) {\n this.materialContext = engine.createMaterialContext();\n }\n }\n setEffect(effect, defines, resetContext = true) {\n var _a;\n this.effect = effect;\n if (defines !== undefined) {\n this.defines = defines;\n }\n if (resetContext) {\n (_a = this.drawContext) === null || _a === void 0 ? void 0 : _a.reset();\n }\n }\n dispose() {\n var _a;\n (_a = this.drawContext) === null || _a === void 0 ? void 0 : _a.dispose();\n }\n}\n//# sourceMappingURL=drawWrapper.js.map","import { Observable } from \"../Misc/observable.js\";\n\nimport { GetDOMTextContent, IsWindowObjectExist } from \"../Misc/domManagement.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { ShaderProcessor } from \"../Engines/Processors/shaderProcessor.js\";\nimport { ShaderStore as EngineShaderStore } from \"../Engines/shaderStore.js\";\nimport { ShaderLanguage } from \"./shaderLanguage.js\";\n/**\n * Effect containing vertex and fragment shader that can be executed on an object.\n */\nexport class Effect {\n /**\n * Gets or sets the relative url used to load shaders if using the engine in non-minified mode\n */\n static get ShadersRepository() {\n return EngineShaderStore.ShadersRepository;\n }\n static set ShadersRepository(repo) {\n EngineShaderStore.ShadersRepository = repo;\n }\n /**\n * Observable that will be called when effect is bound.\n */\n get onBindObservable() {\n if (!this._onBindObservable) {\n this._onBindObservable = new Observable();\n }\n return this._onBindObservable;\n }\n /**\n * Instantiates an effect.\n * An effect can be used to create/manage/execute vertex and fragment shaders.\n * @param baseName Name of the effect.\n * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.\n * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.\n * @param samplers List of sampler variables that will be passed to the shader.\n * @param engine Engine to be used to render the effect\n * @param defines Define statements to be added to the shader.\n * @param fallbacks Possible fallbacks for this effect to improve performance when needed.\n * @param onCompiled Callback that will be called when the shader is compiled.\n * @param onError Callback that will be called if an error occurs during shader compilation.\n * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})\n * @param key Effect Key identifying uniquely compiled shader variants\n * @param shaderLanguage the language the shader is written in (default: GLSL)\n */\n constructor(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers = null, engine, defines = null, fallbacks = null, onCompiled = null, onError = null, indexParameters, key = \"\", shaderLanguage = ShaderLanguage.GLSL) {\n var _a, _b, _c;\n /**\n * Name of the effect.\n */\n this.name = null;\n /**\n * String container all the define statements that should be set on the shader.\n */\n this.defines = \"\";\n /**\n * Callback that will be called when the shader is compiled.\n */\n this.onCompiled = null;\n /**\n * Callback that will be called if an error occurs during shader compilation.\n */\n this.onError = null;\n /**\n * Callback that will be called when effect is bound.\n */\n this.onBind = null;\n /**\n * Unique ID of the effect.\n */\n this.uniqueId = 0;\n /**\n * Observable that will be called when the shader is compiled.\n * It is recommended to use executeWhenCompile() or to make sure that scene.isReady() is called to get this observable raised.\n */\n this.onCompileObservable = new Observable();\n /**\n * Observable that will be called if an error occurs during shader compilation.\n */\n this.onErrorObservable = new Observable();\n /** @internal */\n this._onBindObservable = null;\n /**\n * @internal\n * Specifies if the effect was previously ready\n */\n this._wasPreviouslyReady = false;\n /**\n * @internal\n * Forces the code from bindForSubMesh to be fully run the next time it is called\n * It is used in frozen mode to make sure the effect is properly rebound when a new effect is created\n */\n this._forceRebindOnNextCall = false;\n /**\n * @internal\n * Specifies if the effect was previously using instances\n */\n this._wasPreviouslyUsingInstances = null;\n this._isDisposed = false;\n /** @internal */\n this._bonesComputationForcedToCPU = false;\n /** @internal */\n this._uniformBuffersNames = {};\n /** @internal */\n this._multiTarget = false;\n this._samplers = {};\n this._isReady = false;\n this._compilationError = \"\";\n this._allFallbacksProcessed = false;\n this._uniforms = {};\n /**\n * Key for the effect.\n * @internal\n */\n this._key = \"\";\n this._fallbacks = null;\n this._vertexSourceCodeOverride = \"\";\n this._fragmentSourceCodeOverride = \"\";\n this._transformFeedbackVaryings = null;\n /**\n * Compiled shader to webGL program.\n * @internal\n */\n this._pipelineContext = null;\n /** @internal */\n this._vertexSourceCode = \"\";\n /** @internal */\n this._fragmentSourceCode = \"\";\n /** @internal */\n this._vertexSourceCodeBeforeMigration = \"\";\n /** @internal */\n this._fragmentSourceCodeBeforeMigration = \"\";\n /** @internal */\n this._rawVertexSourceCode = \"\";\n /** @internal */\n this._rawFragmentSourceCode = \"\";\n this.name = baseName;\n this._key = key;\n let processCodeAfterIncludes = undefined;\n let processFinalCode = null;\n if (attributesNamesOrOptions.attributes) {\n const options = attributesNamesOrOptions;\n this._engine = uniformsNamesOrEngine;\n this._attributesNames = options.attributes;\n this._uniformsNames = options.uniformsNames.concat(options.samplers);\n this._samplerList = options.samplers.slice();\n this.defines = options.defines;\n this.onError = options.onError;\n this.onCompiled = options.onCompiled;\n this._fallbacks = options.fallbacks;\n this._indexParameters = options.indexParameters;\n this._transformFeedbackVaryings = options.transformFeedbackVaryings || null;\n this._multiTarget = !!options.multiTarget;\n this._shaderLanguage = (_a = options.shaderLanguage) !== null && _a !== void 0 ? _a : ShaderLanguage.GLSL;\n if (options.uniformBuffersNames) {\n this._uniformBuffersNamesList = options.uniformBuffersNames.slice();\n for (let i = 0; i < options.uniformBuffersNames.length; i++) {\n this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;\n }\n }\n processFinalCode = (_b = options.processFinalCode) !== null && _b !== void 0 ? _b : null;\n processCodeAfterIncludes = (_c = options.processCodeAfterIncludes) !== null && _c !== void 0 ? _c : undefined;\n }\n else {\n this._engine = engine;\n this.defines = defines == null ? \"\" : defines;\n this._uniformsNames = uniformsNamesOrEngine.concat(samplers);\n this._samplerList = samplers ? samplers.slice() : [];\n this._attributesNames = attributesNamesOrOptions;\n this._uniformBuffersNamesList = [];\n this._shaderLanguage = shaderLanguage;\n this.onError = onError;\n this.onCompiled = onCompiled;\n this._indexParameters = indexParameters;\n this._fallbacks = fallbacks;\n }\n this._attributeLocationByName = {};\n this.uniqueId = Effect._UniqueIdSeed++;\n let vertexSource;\n let fragmentSource;\n const hostDocument = IsWindowObjectExist() ? this._engine.getHostDocument() : null;\n if (baseName.vertexSource) {\n vertexSource = \"source:\" + baseName.vertexSource;\n }\n else if (baseName.vertexElement) {\n vertexSource = hostDocument ? hostDocument.getElementById(baseName.vertexElement) : null;\n if (!vertexSource) {\n vertexSource = baseName.vertexElement;\n }\n }\n else {\n vertexSource = baseName.vertex || baseName;\n }\n if (baseName.fragmentSource) {\n fragmentSource = \"source:\" + baseName.fragmentSource;\n }\n else if (baseName.fragmentElement) {\n fragmentSource = hostDocument ? hostDocument.getElementById(baseName.fragmentElement) : null;\n if (!fragmentSource) {\n fragmentSource = baseName.fragmentElement;\n }\n }\n else {\n fragmentSource = baseName.fragment || baseName;\n }\n this._processingContext = this._engine._getShaderProcessingContext(this._shaderLanguage);\n let processorOptions = {\n defines: this.defines.split(\"\\n\"),\n indexParameters: this._indexParameters,\n isFragment: false,\n shouldUseHighPrecisionShader: this._engine._shouldUseHighPrecisionShader,\n processor: this._engine._getShaderProcessor(this._shaderLanguage),\n supportsUniformBuffers: this._engine.supportsUniformBuffers,\n shadersRepository: EngineShaderStore.GetShadersRepository(this._shaderLanguage),\n includesShadersStore: EngineShaderStore.GetIncludesShadersStore(this._shaderLanguage),\n version: (this._engine.version * 100).toString(),\n platformName: this._engine.shaderPlatformName,\n processingContext: this._processingContext,\n isNDCHalfZRange: this._engine.isNDCHalfZRange,\n useReverseDepthBuffer: this._engine.useReverseDepthBuffer,\n processCodeAfterIncludes,\n };\n const shaderCodes = [undefined, undefined];\n const shadersLoaded = () => {\n if (shaderCodes[0] && shaderCodes[1]) {\n processorOptions.isFragment = true;\n const [migratedVertexCode, fragmentCode] = shaderCodes;\n ShaderProcessor.Process(fragmentCode, processorOptions, (migratedFragmentCode, codeBeforeMigration) => {\n this._fragmentSourceCodeBeforeMigration = codeBeforeMigration;\n if (processFinalCode) {\n migratedFragmentCode = processFinalCode(\"fragment\", migratedFragmentCode);\n }\n const finalShaders = ShaderProcessor.Finalize(migratedVertexCode, migratedFragmentCode, processorOptions);\n processorOptions = null;\n this._useFinalCode(finalShaders.vertexCode, finalShaders.fragmentCode, baseName);\n }, this._engine);\n }\n };\n this._loadShader(vertexSource, \"Vertex\", \"\", (vertexCode) => {\n ShaderProcessor.Initialize(processorOptions);\n ShaderProcessor.Process(vertexCode, processorOptions, (migratedVertexCode, codeBeforeMigration) => {\n this._rawVertexSourceCode = vertexCode;\n this._vertexSourceCodeBeforeMigration = codeBeforeMigration;\n if (processFinalCode) {\n migratedVertexCode = processFinalCode(\"vertex\", migratedVertexCode);\n }\n shaderCodes[0] = migratedVertexCode;\n shadersLoaded();\n }, this._engine);\n });\n this._loadShader(fragmentSource, \"Fragment\", \"Pixel\", (fragmentCode) => {\n this._rawFragmentSourceCode = fragmentCode;\n shaderCodes[1] = fragmentCode;\n shadersLoaded();\n });\n }\n _useFinalCode(migratedVertexCode, migratedFragmentCode, baseName) {\n if (baseName) {\n const vertex = baseName.vertexElement || baseName.vertex || baseName.spectorName || baseName;\n const fragment = baseName.fragmentElement || baseName.fragment || baseName.spectorName || baseName;\n this._vertexSourceCode = (this._shaderLanguage === ShaderLanguage.WGSL ? \"//\" : \"\") + \"#define SHADER_NAME vertex:\" + vertex + \"\\n\" + migratedVertexCode;\n this._fragmentSourceCode = (this._shaderLanguage === ShaderLanguage.WGSL ? \"//\" : \"\") + \"#define SHADER_NAME fragment:\" + fragment + \"\\n\" + migratedFragmentCode;\n }\n else {\n this._vertexSourceCode = migratedVertexCode;\n this._fragmentSourceCode = migratedFragmentCode;\n }\n this._prepareEffect();\n }\n /**\n * Unique key for this effect\n */\n get key() {\n return this._key;\n }\n /**\n * If the effect has been compiled and prepared.\n * @returns if the effect is compiled and prepared.\n */\n isReady() {\n try {\n return this._isReadyInternal();\n }\n catch (_a) {\n return false;\n }\n }\n _isReadyInternal() {\n if (this._isReady) {\n return true;\n }\n if (this._pipelineContext) {\n return this._pipelineContext.isReady;\n }\n return false;\n }\n /**\n * The engine the effect was initialized with.\n * @returns the engine.\n */\n getEngine() {\n return this._engine;\n }\n /**\n * The pipeline context for this effect\n * @returns the associated pipeline context\n */\n getPipelineContext() {\n return this._pipelineContext;\n }\n /**\n * The set of names of attribute variables for the shader.\n * @returns An array of attribute names.\n */\n getAttributesNames() {\n return this._attributesNames;\n }\n /**\n * Returns the attribute at the given index.\n * @param index The index of the attribute.\n * @returns The location of the attribute.\n */\n getAttributeLocation(index) {\n return this._attributes[index];\n }\n /**\n * Returns the attribute based on the name of the variable.\n * @param name of the attribute to look up.\n * @returns the attribute location.\n */\n getAttributeLocationByName(name) {\n return this._attributeLocationByName[name];\n }\n /**\n * The number of attributes.\n * @returns the number of attributes.\n */\n getAttributesCount() {\n return this._attributes.length;\n }\n /**\n * Gets the index of a uniform variable.\n * @param uniformName of the uniform to look up.\n * @returns the index.\n */\n getUniformIndex(uniformName) {\n return this._uniformsNames.indexOf(uniformName);\n }\n /**\n * Returns the attribute based on the name of the variable.\n * @param uniformName of the uniform to look up.\n * @returns the location of the uniform.\n */\n getUniform(uniformName) {\n return this._uniforms[uniformName];\n }\n /**\n * Returns an array of sampler variable names\n * @returns The array of sampler variable names.\n */\n getSamplers() {\n return this._samplerList;\n }\n /**\n * Returns an array of uniform variable names\n * @returns The array of uniform variable names.\n */\n getUniformNames() {\n return this._uniformsNames;\n }\n /**\n * Returns an array of uniform buffer variable names\n * @returns The array of uniform buffer variable names.\n */\n getUniformBuffersNames() {\n return this._uniformBuffersNamesList;\n }\n /**\n * Returns the index parameters used to create the effect\n * @returns The index parameters object\n */\n getIndexParameters() {\n return this._indexParameters;\n }\n /**\n * The error from the last compilation.\n * @returns the error string.\n */\n getCompilationError() {\n return this._compilationError;\n }\n /**\n * Gets a boolean indicating that all fallbacks were used during compilation\n * @returns true if all fallbacks were used\n */\n allFallbacksProcessed() {\n return this._allFallbacksProcessed;\n }\n /**\n * Adds a callback to the onCompiled observable and call the callback immediately if already ready.\n * @param func The callback to be used.\n */\n executeWhenCompiled(func) {\n if (this.isReady()) {\n func(this);\n return;\n }\n this.onCompileObservable.add((effect) => {\n func(effect);\n });\n if (!this._pipelineContext || this._pipelineContext.isAsync) {\n setTimeout(() => {\n this._checkIsReady(null);\n }, 16);\n }\n }\n _checkIsReady(previousPipelineContext) {\n try {\n if (this._isReadyInternal()) {\n return;\n }\n }\n catch (e) {\n this._processCompilationErrors(e, previousPipelineContext);\n return;\n }\n if (this._isDisposed) {\n return;\n }\n setTimeout(() => {\n this._checkIsReady(previousPipelineContext);\n }, 16);\n }\n _loadShader(shader, key, optionalKey, callback) {\n if (typeof HTMLElement !== \"undefined\") {\n // DOM element ?\n if (shader instanceof HTMLElement) {\n const shaderCode = GetDOMTextContent(shader);\n callback(shaderCode);\n return;\n }\n }\n // Direct source ?\n if (shader.substr(0, 7) === \"source:\") {\n callback(shader.substr(7));\n return;\n }\n // Base64 encoded ?\n if (shader.substr(0, 7) === \"base64:\") {\n const shaderBinary = window.atob(shader.substr(7));\n callback(shaderBinary);\n return;\n }\n const shaderStore = EngineShaderStore.GetShadersStore(this._shaderLanguage);\n // Is in local store ?\n if (shaderStore[shader + key + \"Shader\"]) {\n callback(shaderStore[shader + key + \"Shader\"]);\n return;\n }\n if (optionalKey && shaderStore[shader + optionalKey + \"Shader\"]) {\n callback(shaderStore[shader + optionalKey + \"Shader\"]);\n return;\n }\n let shaderUrl;\n if (shader[0] === \".\" || shader[0] === \"/\" || shader.indexOf(\"http\") > -1) {\n shaderUrl = shader;\n }\n else {\n shaderUrl = EngineShaderStore.GetShadersRepository(this._shaderLanguage) + shader;\n }\n // Vertex shader\n this._engine._loadFile(shaderUrl + \".\" + key.toLowerCase() + \".fx\", callback);\n }\n /**\n * Gets the vertex shader source code of this effect\n * This is the final source code that will be compiled, after all the processing has been done (pre-processing applied, code injection/replacement, etc)\n */\n get vertexSourceCode() {\n var _a, _b;\n return this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride\n ? this._vertexSourceCodeOverride\n : (_b = (_a = this._pipelineContext) === null || _a === void 0 ? void 0 : _a._getVertexShaderCode()) !== null && _b !== void 0 ? _b : this._vertexSourceCode;\n }\n /**\n * Gets the fragment shader source code of this effect\n * This is the final source code that will be compiled, after all the processing has been done (pre-processing applied, code injection/replacement, etc)\n */\n get fragmentSourceCode() {\n var _a, _b;\n return this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride\n ? this._fragmentSourceCodeOverride\n : (_b = (_a = this._pipelineContext) === null || _a === void 0 ? void 0 : _a._getFragmentShaderCode()) !== null && _b !== void 0 ? _b : this._fragmentSourceCode;\n }\n /**\n * Gets the vertex shader source code before migration.\n * This is the source code after the include directives have been replaced by their contents but before the code is migrated, i.e. before ShaderProcess._ProcessShaderConversion is executed.\n * This method is, among other things, responsible for parsing #if/#define directives as well as converting GLES2 syntax to GLES3 (in the case of WebGL).\n */\n get vertexSourceCodeBeforeMigration() {\n return this._vertexSourceCodeBeforeMigration;\n }\n /**\n * Gets the fragment shader source code before migration.\n * This is the source code after the include directives have been replaced by their contents but before the code is migrated, i.e. before ShaderProcess._ProcessShaderConversion is executed.\n * This method is, among other things, responsible for parsing #if/#define directives as well as converting GLES2 syntax to GLES3 (in the case of WebGL).\n */\n get fragmentSourceCodeBeforeMigration() {\n return this._fragmentSourceCodeBeforeMigration;\n }\n /**\n * Gets the vertex shader source code before it has been modified by any processing\n */\n get rawVertexSourceCode() {\n return this._rawVertexSourceCode;\n }\n /**\n * Gets the fragment shader source code before it has been modified by any processing\n */\n get rawFragmentSourceCode() {\n return this._rawFragmentSourceCode;\n }\n /**\n * Recompiles the webGL program\n * @param vertexSourceCode The source code for the vertex shader.\n * @param fragmentSourceCode The source code for the fragment shader.\n * @param onCompiled Callback called when completed.\n * @param onError Callback called on error.\n * @internal\n */\n _rebuildProgram(vertexSourceCode, fragmentSourceCode, onCompiled, onError) {\n this._isReady = false;\n this._vertexSourceCodeOverride = vertexSourceCode;\n this._fragmentSourceCodeOverride = fragmentSourceCode;\n this.onError = (effect, error) => {\n if (onError) {\n onError(error);\n }\n };\n this.onCompiled = () => {\n const scenes = this.getEngine().scenes;\n if (scenes) {\n for (let i = 0; i < scenes.length; i++) {\n scenes[i].markAllMaterialsAsDirty(63);\n }\n }\n this._pipelineContext._handlesSpectorRebuildCallback(onCompiled);\n };\n this._fallbacks = null;\n this._prepareEffect();\n }\n /**\n * Prepares the effect\n * @internal\n */\n _prepareEffect() {\n const attributesNames = this._attributesNames;\n const defines = this.defines;\n const previousPipelineContext = this._pipelineContext;\n this._isReady = false;\n try {\n const engine = this._engine;\n this._pipelineContext = engine.createPipelineContext(this._processingContext);\n this._pipelineContext._name = this._key;\n const rebuildRebind = this._rebuildProgram.bind(this);\n if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {\n engine._preparePipelineContext(this._pipelineContext, this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, true, this._rawVertexSourceCode, this._rawFragmentSourceCode, rebuildRebind, null, this._transformFeedbackVaryings, this._key);\n }\n else {\n engine._preparePipelineContext(this._pipelineContext, this._vertexSourceCode, this._fragmentSourceCode, false, this._rawVertexSourceCode, this._rawFragmentSourceCode, rebuildRebind, defines, this._transformFeedbackVaryings, this._key);\n }\n engine._executeWhenRenderingStateIsCompiled(this._pipelineContext, () => {\n this._attributes = [];\n this._pipelineContext._fillEffectInformation(this, this._uniformBuffersNames, this._uniformsNames, this._uniforms, this._samplerList, this._samplers, attributesNames, this._attributes);\n // Caches attribute locations.\n if (attributesNames) {\n for (let i = 0; i < attributesNames.length; i++) {\n const name = attributesNames[i];\n this._attributeLocationByName[name] = this._attributes[i];\n }\n }\n engine.bindSamplers(this);\n this._compilationError = \"\";\n this._isReady = true;\n if (this.onCompiled) {\n this.onCompiled(this);\n }\n this.onCompileObservable.notifyObservers(this);\n this.onCompileObservable.clear();\n // Unbind mesh reference in fallbacks\n if (this._fallbacks) {\n this._fallbacks.unBindMesh();\n }\n if (previousPipelineContext) {\n this.getEngine()._deletePipelineContext(previousPipelineContext);\n }\n });\n if (this._pipelineContext.isAsync) {\n this._checkIsReady(previousPipelineContext);\n }\n }\n catch (e) {\n this._processCompilationErrors(e, previousPipelineContext);\n }\n }\n _getShaderCodeAndErrorLine(code, error, isFragment) {\n const regexp = isFragment ? /FRAGMENT SHADER ERROR: 0:(\\d+?):/ : /VERTEX SHADER ERROR: 0:(\\d+?):/;\n let errorLine = null;\n if (error && code) {\n const res = error.match(regexp);\n if (res && res.length === 2) {\n const lineNumber = parseInt(res[1]);\n const lines = code.split(\"\\n\", -1);\n if (lines.length >= lineNumber) {\n errorLine = `Offending line [${lineNumber}] in ${isFragment ? \"fragment\" : \"vertex\"} code: ${lines[lineNumber - 1]}`;\n }\n }\n }\n return [code, errorLine];\n }\n _processCompilationErrors(e, previousPipelineContext = null) {\n var _a, _b, _c;\n this._compilationError = e.message;\n const attributesNames = this._attributesNames;\n const fallbacks = this._fallbacks;\n // Let's go through fallbacks then\n Logger.Error(\"Unable to compile effect:\");\n Logger.Error(\"Uniforms: \" +\n this._uniformsNames.map(function (uniform) {\n return \" \" + uniform;\n }));\n Logger.Error(\"Attributes: \" +\n attributesNames.map(function (attribute) {\n return \" \" + attribute;\n }));\n Logger.Error(\"Defines:\\r\\n\" + this.defines);\n if (Effect.LogShaderCodeOnCompilationError) {\n let lineErrorVertex = null, lineErrorFragment = null, code = null;\n if ((_a = this._pipelineContext) === null || _a === void 0 ? void 0 : _a._getVertexShaderCode()) {\n [code, lineErrorVertex] = this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(), this._compilationError, false);\n if (code) {\n Logger.Error(\"Vertex code:\");\n Logger.Error(code);\n }\n }\n if ((_b = this._pipelineContext) === null || _b === void 0 ? void 0 : _b._getFragmentShaderCode()) {\n [code, lineErrorFragment] = this._getShaderCodeAndErrorLine((_c = this._pipelineContext) === null || _c === void 0 ? void 0 : _c._getFragmentShaderCode(), this._compilationError, true);\n if (code) {\n Logger.Error(\"Fragment code:\");\n Logger.Error(code);\n }\n }\n if (lineErrorVertex) {\n Logger.Error(lineErrorVertex);\n }\n if (lineErrorFragment) {\n Logger.Error(lineErrorFragment);\n }\n }\n Logger.Error(\"Error: \" + this._compilationError);\n const notifyErrors = () => {\n if (this.onError) {\n this.onError(this, this._compilationError);\n }\n this.onErrorObservable.notifyObservers(this);\n };\n // In case a previous compilation was successful, we need to restore the previous pipeline context\n if (previousPipelineContext) {\n this._pipelineContext = previousPipelineContext;\n this._isReady = true;\n notifyErrors();\n }\n // Lets try to compile fallbacks as long as we have some.\n if (fallbacks) {\n this._pipelineContext = null;\n if (fallbacks.hasMoreFallbacks) {\n this._allFallbacksProcessed = false;\n Logger.Error(\"Trying next fallback.\");\n this.defines = fallbacks.reduce(this.defines, this);\n this._prepareEffect();\n }\n else {\n // Sorry we did everything we can\n this._allFallbacksProcessed = true;\n notifyErrors();\n this.onErrorObservable.clear();\n // Unbind mesh reference in fallbacks\n if (this._fallbacks) {\n this._fallbacks.unBindMesh();\n }\n }\n }\n else {\n this._allFallbacksProcessed = true;\n // In case of error, without any prior successful compilation, let s notify observers\n if (!previousPipelineContext) {\n notifyErrors();\n }\n }\n }\n /**\n * Checks if the effect is supported. (Must be called after compilation)\n */\n get isSupported() {\n return this._compilationError === \"\";\n }\n /**\n * Binds a texture to the engine to be used as output of the shader.\n * @param channel Name of the output variable.\n * @param texture Texture to bind.\n * @internal\n */\n _bindTexture(channel, texture) {\n this._engine._bindTexture(this._samplers[channel], texture, channel);\n }\n /**\n * Sets a texture on the engine to be used in the shader.\n * @param channel Name of the sampler variable.\n * @param texture Texture to set.\n */\n setTexture(channel, texture) {\n this._engine.setTexture(this._samplers[channel], this._uniforms[channel], texture, channel);\n }\n /**\n * Sets a depth stencil texture from a render target on the engine to be used in the shader.\n * @param channel Name of the sampler variable.\n * @param texture Texture to set.\n */\n setDepthStencilTexture(channel, texture) {\n this._engine.setDepthStencilTexture(this._samplers[channel], this._uniforms[channel], texture, channel);\n }\n /**\n * Sets an array of textures on the engine to be used in the shader.\n * @param channel Name of the variable.\n * @param textures Textures to set.\n */\n setTextureArray(channel, textures) {\n const exName = channel + \"Ex\";\n if (this._samplerList.indexOf(exName + \"0\") === -1) {\n const initialPos = this._samplerList.indexOf(channel);\n for (let index = 1; index < textures.length; index++) {\n const currentExName = exName + (index - 1).toString();\n this._samplerList.splice(initialPos + index, 0, currentExName);\n }\n // Reset every channels\n let channelIndex = 0;\n for (const key of this._samplerList) {\n this._samplers[key] = channelIndex;\n channelIndex += 1;\n }\n }\n this._engine.setTextureArray(this._samplers[channel], this._uniforms[channel], textures, channel);\n }\n /**\n * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)\n * @param channel Name of the sampler variable.\n * @param postProcess Post process to get the input texture from.\n */\n setTextureFromPostProcess(channel, postProcess) {\n this._engine.setTextureFromPostProcess(this._samplers[channel], postProcess, channel);\n }\n /**\n * (Warning! setTextureFromPostProcessOutput may be desired instead)\n * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)\n * @param channel Name of the sampler variable.\n * @param postProcess Post process to get the output texture from.\n */\n setTextureFromPostProcessOutput(channel, postProcess) {\n this._engine.setTextureFromPostProcessOutput(this._samplers[channel], postProcess, channel);\n }\n /**\n * Binds a buffer to a uniform.\n * @param buffer Buffer to bind.\n * @param name Name of the uniform variable to bind to.\n */\n bindUniformBuffer(buffer, name) {\n const bufferName = this._uniformBuffersNames[name];\n if (bufferName === undefined || (Effect._BaseCache[bufferName] === buffer && this._engine._features.useUBOBindingCache)) {\n return;\n }\n Effect._BaseCache[bufferName] = buffer;\n this._engine.bindUniformBufferBase(buffer, bufferName, name);\n }\n /**\n * Binds block to a uniform.\n * @param blockName Name of the block to bind.\n * @param index Index to bind.\n */\n bindUniformBlock(blockName, index) {\n this._engine.bindUniformBlock(this._pipelineContext, blockName, index);\n }\n /**\n * Sets an integer value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value Value to be set.\n * @returns this effect.\n */\n setInt(uniformName, value) {\n this._pipelineContext.setInt(uniformName, value);\n return this;\n }\n /**\n * Sets an int2 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First int in int2.\n * @param y Second int in int2.\n * @returns this effect.\n */\n setInt2(uniformName, x, y) {\n this._pipelineContext.setInt2(uniformName, x, y);\n return this;\n }\n /**\n * Sets an int3 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First int in int3.\n * @param y Second int in int3.\n * @param z Third int in int3.\n * @returns this effect.\n */\n setInt3(uniformName, x, y, z) {\n this._pipelineContext.setInt3(uniformName, x, y, z);\n return this;\n }\n /**\n * Sets an int4 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First int in int4.\n * @param y Second int in int4.\n * @param z Third int in int4.\n * @param w Fourth int in int4.\n * @returns this effect.\n */\n setInt4(uniformName, x, y, z, w) {\n this._pipelineContext.setInt4(uniformName, x, y, z, w);\n return this;\n }\n /**\n * Sets an int array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setIntArray(uniformName, array) {\n this._pipelineContext.setIntArray(uniformName, array);\n return this;\n }\n /**\n * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setIntArray2(uniformName, array) {\n this._pipelineContext.setIntArray2(uniformName, array);\n return this;\n }\n /**\n * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setIntArray3(uniformName, array) {\n this._pipelineContext.setIntArray3(uniformName, array);\n return this;\n }\n /**\n * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setIntArray4(uniformName, array) {\n this._pipelineContext.setIntArray4(uniformName, array);\n return this;\n }\n /**\n * Sets an unsigned integer value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value Value to be set.\n * @returns this effect.\n */\n setUInt(uniformName, value) {\n this._pipelineContext.setInt(uniformName, value);\n return this;\n }\n /**\n * Sets an unsigned int2 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First unsigned int in uint2.\n * @param y Second unsigned int in uint2.\n * @returns this effect.\n */\n setUInt2(uniformName, x, y) {\n this._pipelineContext.setInt2(uniformName, x, y);\n return this;\n }\n /**\n * Sets an unsigned int3 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First unsigned int in uint3.\n * @param y Second unsigned int in uint3.\n * @param z Third unsigned int in uint3.\n * @returns this effect.\n */\n setUInt3(uniformName, x, y, z) {\n this._pipelineContext.setInt3(uniformName, x, y, z);\n return this;\n }\n /**\n * Sets an unsigned int4 value on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First unsigned int in uint4.\n * @param y Second unsigned int in uint4.\n * @param z Third unsigned int in uint4.\n * @param w Fourth unsigned int in uint4.\n * @returns this effect.\n */\n setUInt4(uniformName, x, y, z, w) {\n this._pipelineContext.setInt4(uniformName, x, y, z, w);\n return this;\n }\n /**\n * Sets an unsigned int array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setUIntArray(uniformName, array) {\n this._pipelineContext.setUIntArray(uniformName, array);\n return this;\n }\n /**\n * Sets an unsigned int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setUIntArray2(uniformName, array) {\n this._pipelineContext.setUIntArray2(uniformName, array);\n return this;\n }\n /**\n * Sets an unsigned int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setUIntArray3(uniformName, array) {\n this._pipelineContext.setUIntArray3(uniformName, array);\n return this;\n }\n /**\n * Sets an unsigned int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setUIntArray4(uniformName, array) {\n this._pipelineContext.setUIntArray4(uniformName, array);\n return this;\n }\n /**\n * Sets an float array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setFloatArray(uniformName, array) {\n this._pipelineContext.setArray(uniformName, array);\n return this;\n }\n /**\n * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setFloatArray2(uniformName, array) {\n this._pipelineContext.setArray2(uniformName, array);\n return this;\n }\n /**\n * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setFloatArray3(uniformName, array) {\n this._pipelineContext.setArray3(uniformName, array);\n return this;\n }\n /**\n * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setFloatArray4(uniformName, array) {\n this._pipelineContext.setArray4(uniformName, array);\n return this;\n }\n /**\n * Sets an array on a uniform variable.\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setArray(uniformName, array) {\n this._pipelineContext.setArray(uniformName, array);\n return this;\n }\n /**\n * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setArray2(uniformName, array) {\n this._pipelineContext.setArray2(uniformName, array);\n return this;\n }\n /**\n * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setArray3(uniformName, array) {\n this._pipelineContext.setArray3(uniformName, array);\n return this;\n }\n /**\n * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)\n * @param uniformName Name of the variable.\n * @param array array to be set.\n * @returns this effect.\n */\n setArray4(uniformName, array) {\n this._pipelineContext.setArray4(uniformName, array);\n return this;\n }\n /**\n * Sets matrices on a uniform variable.\n * @param uniformName Name of the variable.\n * @param matrices matrices to be set.\n * @returns this effect.\n */\n setMatrices(uniformName, matrices) {\n this._pipelineContext.setMatrices(uniformName, matrices);\n return this;\n }\n /**\n * Sets matrix on a uniform variable.\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n * @returns this effect.\n */\n setMatrix(uniformName, matrix) {\n this._pipelineContext.setMatrix(uniformName, matrix);\n return this;\n }\n /**\n * Sets a 3x3 matrix on a uniform variable. (Specified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n * @returns this effect.\n */\n setMatrix3x3(uniformName, matrix) {\n // the cast is ok because it is gl.uniformMatrix3fv() which is called at the end, and this function accepts Float32Array and Array\n this._pipelineContext.setMatrix3x3(uniformName, matrix);\n return this;\n }\n /**\n * Sets a 2x2 matrix on a uniform variable. (Specified as [1,2,3,4] will result in [1,2][3,4] matrix)\n * @param uniformName Name of the variable.\n * @param matrix matrix to be set.\n * @returns this effect.\n */\n setMatrix2x2(uniformName, matrix) {\n // the cast is ok because it is gl.uniformMatrix3fv() which is called at the end, and this function accepts Float32Array and Array\n this._pipelineContext.setMatrix2x2(uniformName, matrix);\n return this;\n }\n /**\n * Sets a float on a uniform variable.\n * @param uniformName Name of the variable.\n * @param value value to be set.\n * @returns this effect.\n */\n setFloat(uniformName, value) {\n this._pipelineContext.setFloat(uniformName, value);\n return this;\n }\n /**\n * Sets a boolean on a uniform variable.\n * @param uniformName Name of the variable.\n * @param bool value to be set.\n * @returns this effect.\n */\n setBool(uniformName, bool) {\n this._pipelineContext.setInt(uniformName, bool ? 1 : 0);\n return this;\n }\n /**\n * Sets a Vector2 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector2 vector2 to be set.\n * @returns this effect.\n */\n setVector2(uniformName, vector2) {\n this._pipelineContext.setVector2(uniformName, vector2);\n return this;\n }\n /**\n * Sets a float2 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float2.\n * @param y Second float in float2.\n * @returns this effect.\n */\n setFloat2(uniformName, x, y) {\n this._pipelineContext.setFloat2(uniformName, x, y);\n return this;\n }\n /**\n * Sets a Vector3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector3 Value to be set.\n * @returns this effect.\n */\n setVector3(uniformName, vector3) {\n this._pipelineContext.setVector3(uniformName, vector3);\n return this;\n }\n /**\n * Sets a float3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float3.\n * @param y Second float in float3.\n * @param z Third float in float3.\n * @returns this effect.\n */\n setFloat3(uniformName, x, y, z) {\n this._pipelineContext.setFloat3(uniformName, x, y, z);\n return this;\n }\n /**\n * Sets a Vector4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param vector4 Value to be set.\n * @returns this effect.\n */\n setVector4(uniformName, vector4) {\n this._pipelineContext.setVector4(uniformName, vector4);\n return this;\n }\n /**\n * Sets a Quaternion on a uniform variable.\n * @param uniformName Name of the variable.\n * @param quaternion Value to be set.\n * @returns this effect.\n */\n setQuaternion(uniformName, quaternion) {\n this._pipelineContext.setQuaternion(uniformName, quaternion);\n return this;\n }\n /**\n * Sets a float4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param x First float in float4.\n * @param y Second float in float4.\n * @param z Third float in float4.\n * @param w Fourth float in float4.\n * @returns this effect.\n */\n setFloat4(uniformName, x, y, z, w) {\n this._pipelineContext.setFloat4(uniformName, x, y, z, w);\n return this;\n }\n /**\n * Sets a Color3 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param color3 Value to be set.\n * @returns this effect.\n */\n setColor3(uniformName, color3) {\n this._pipelineContext.setColor3(uniformName, color3);\n return this;\n }\n /**\n * Sets a Color4 on a uniform variable.\n * @param uniformName Name of the variable.\n * @param color3 Value to be set.\n * @param alpha Alpha value to be set.\n * @returns this effect.\n */\n setColor4(uniformName, color3, alpha) {\n this._pipelineContext.setColor4(uniformName, color3, alpha);\n return this;\n }\n /**\n * Sets a Color4 on a uniform variable\n * @param uniformName defines the name of the variable\n * @param color4 defines the value to be set\n * @returns this effect.\n */\n setDirectColor4(uniformName, color4) {\n this._pipelineContext.setDirectColor4(uniformName, color4);\n return this;\n }\n /**\n * Release all associated resources.\n **/\n dispose() {\n if (this._pipelineContext) {\n this._pipelineContext.dispose();\n }\n this._engine._releaseEffect(this);\n this._isDisposed = true;\n }\n /**\n * This function will add a new shader to the shader store\n * @param name the name of the shader\n * @param pixelShader optional pixel shader content\n * @param vertexShader optional vertex shader content\n * @param shaderLanguage the language the shader is written in (default: GLSL)\n */\n static RegisterShader(name, pixelShader, vertexShader, shaderLanguage = ShaderLanguage.GLSL) {\n if (pixelShader) {\n EngineShaderStore.GetShadersStore(shaderLanguage)[`${name}PixelShader`] = pixelShader;\n }\n if (vertexShader) {\n EngineShaderStore.GetShadersStore(shaderLanguage)[`${name}VertexShader`] = vertexShader;\n }\n }\n /**\n * Resets the cache of effects.\n */\n static ResetCache() {\n Effect._BaseCache = {};\n }\n}\n/**\n * Enable logging of the shader code when a compilation error occurs\n */\nEffect.LogShaderCodeOnCompilationError = true;\nEffect._UniqueIdSeed = 0;\nEffect._BaseCache = {};\n/**\n * Store of each shader (The can be looked up using effect.key)\n */\nEffect.ShadersStore = EngineShaderStore.ShadersStore;\n/**\n * Store of each included file for a shader (The can be looked up using effect.key)\n */\nEffect.IncludesShadersStore = EngineShaderStore.IncludesShadersStore;\n//# sourceMappingURL=effect.js.map","import { __decorate } from \"../tslib.es6.js\";\n/* eslint-disable @typescript-eslint/naming-convention */\nimport { serialize, SerializationHelper, serializeAsTexture, serializeAsColorCurves, serializeAsColor4 } from \"../Misc/decorators.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Tools } from \"../Misc/tools.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { MaterialDefines } from \"../Materials/materialDefines.js\";\nimport { ColorCurves } from \"../Materials/colorCurves.js\";\n/**\n * @internal\n */\nexport class ImageProcessingConfigurationDefines extends MaterialDefines {\n constructor() {\n super();\n this.IMAGEPROCESSING = false;\n this.VIGNETTE = false;\n this.VIGNETTEBLENDMODEMULTIPLY = false;\n this.VIGNETTEBLENDMODEOPAQUE = false;\n this.TONEMAPPING = false;\n this.TONEMAPPING_ACES = false;\n this.CONTRAST = false;\n this.COLORCURVES = false;\n this.COLORGRADING = false;\n this.COLORGRADING3D = false;\n this.SAMPLER3DGREENDEPTH = false;\n this.SAMPLER3DBGRMAP = false;\n this.DITHER = false;\n this.IMAGEPROCESSINGPOSTPROCESS = false;\n this.EXPOSURE = false;\n this.SKIPFINALCOLORCLAMP = false;\n this.rebuild();\n }\n}\n/**\n * This groups together the common properties used for image processing either in direct forward pass\n * or through post processing effect depending on the use of the image processing pipeline in your scene\n * or not.\n */\nexport class ImageProcessingConfiguration {\n constructor() {\n /**\n * Color curves setup used in the effect if colorCurvesEnabled is set to true\n */\n this.colorCurves = new ColorCurves();\n this._colorCurvesEnabled = false;\n this._colorGradingEnabled = false;\n this._colorGradingWithGreenDepth = true;\n this._colorGradingBGR = true;\n /** @internal */\n this._exposure = 1.0;\n this._toneMappingEnabled = false;\n this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;\n this._contrast = 1.0;\n /**\n * Vignette stretch size.\n */\n this.vignetteStretch = 0;\n /**\n * Vignette center X Offset.\n */\n this.vignetteCenterX = 0;\n /**\n * Vignette center Y Offset.\n */\n this.vignetteCenterY = 0;\n /**\n * Vignette weight or intensity of the vignette effect.\n */\n this.vignetteWeight = 1.5;\n /**\n * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)\n * if vignetteEnabled is set to true.\n */\n this.vignetteColor = new Color4(0, 0, 0, 0);\n /**\n * Camera field of view used by the Vignette effect.\n */\n this.vignetteCameraFov = 0.5;\n this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;\n this._vignetteEnabled = false;\n this._ditheringEnabled = false;\n this._ditheringIntensity = 1.0 / 255.0;\n /** @internal */\n this._skipFinalColorClamp = false;\n /** @internal */\n this._applyByPostProcess = false;\n this._isEnabled = true;\n /**\n * An event triggered when the configuration changes and requires Shader to Update some parameters.\n */\n this.onUpdateParameters = new Observable();\n }\n /**\n * Gets whether the color curves effect is enabled.\n */\n get colorCurvesEnabled() {\n return this._colorCurvesEnabled;\n }\n /**\n * Sets whether the color curves effect is enabled.\n */\n set colorCurvesEnabled(value) {\n if (this._colorCurvesEnabled === value) {\n return;\n }\n this._colorCurvesEnabled = value;\n this._updateParameters();\n }\n /**\n * Color grading LUT texture used in the effect if colorGradingEnabled is set to true\n */\n get colorGradingTexture() {\n return this._colorGradingTexture;\n }\n /**\n * Color grading LUT texture used in the effect if colorGradingEnabled is set to true\n */\n set colorGradingTexture(value) {\n if (this._colorGradingTexture === value) {\n return;\n }\n this._colorGradingTexture = value;\n this._updateParameters();\n }\n /**\n * Gets whether the color grading effect is enabled.\n */\n get colorGradingEnabled() {\n return this._colorGradingEnabled;\n }\n /**\n * Sets whether the color grading effect is enabled.\n */\n set colorGradingEnabled(value) {\n if (this._colorGradingEnabled === value) {\n return;\n }\n this._colorGradingEnabled = value;\n this._updateParameters();\n }\n /**\n * Gets whether the color grading effect is using a green depth for the 3d Texture.\n */\n get colorGradingWithGreenDepth() {\n return this._colorGradingWithGreenDepth;\n }\n /**\n * Sets whether the color grading effect is using a green depth for the 3d Texture.\n */\n set colorGradingWithGreenDepth(value) {\n if (this._colorGradingWithGreenDepth === value) {\n return;\n }\n this._colorGradingWithGreenDepth = value;\n this._updateParameters();\n }\n /**\n * Gets whether the color grading texture contains BGR values.\n */\n get colorGradingBGR() {\n return this._colorGradingBGR;\n }\n /**\n * Sets whether the color grading texture contains BGR values.\n */\n set colorGradingBGR(value) {\n if (this._colorGradingBGR === value) {\n return;\n }\n this._colorGradingBGR = value;\n this._updateParameters();\n }\n /**\n * Gets the Exposure used in the effect.\n */\n get exposure() {\n return this._exposure;\n }\n /**\n * Sets the Exposure used in the effect.\n */\n set exposure(value) {\n if (this._exposure === value) {\n return;\n }\n this._exposure = value;\n this._updateParameters();\n }\n /**\n * Gets whether the tone mapping effect is enabled.\n */\n get toneMappingEnabled() {\n return this._toneMappingEnabled;\n }\n /**\n * Sets whether the tone mapping effect is enabled.\n */\n set toneMappingEnabled(value) {\n if (this._toneMappingEnabled === value) {\n return;\n }\n this._toneMappingEnabled = value;\n this._updateParameters();\n }\n /**\n * Gets the type of tone mapping effect.\n */\n get toneMappingType() {\n return this._toneMappingType;\n }\n /**\n * Sets the type of tone mapping effect used in BabylonJS.\n */\n set toneMappingType(value) {\n if (this._toneMappingType === value) {\n return;\n }\n this._toneMappingType = value;\n this._updateParameters();\n }\n /**\n * Gets the contrast used in the effect.\n */\n get contrast() {\n return this._contrast;\n }\n /**\n * Sets the contrast used in the effect.\n */\n set contrast(value) {\n if (this._contrast === value) {\n return;\n }\n this._contrast = value;\n this._updateParameters();\n }\n /**\n * Back Compat: Vignette center Y Offset.\n * @deprecated use vignetteCenterY instead\n */\n get vignetteCentreY() {\n return this.vignetteCenterY;\n }\n set vignetteCentreY(value) {\n this.vignetteCenterY = value;\n }\n /**\n * Back Compat: Vignette center X Offset.\n * @deprecated use vignetteCenterX instead\n */\n get vignetteCentreX() {\n return this.vignetteCenterX;\n }\n set vignetteCentreX(value) {\n this.vignetteCenterX = value;\n }\n /**\n * Gets the vignette blend mode allowing different kind of effect.\n */\n get vignetteBlendMode() {\n return this._vignetteBlendMode;\n }\n /**\n * Sets the vignette blend mode allowing different kind of effect.\n */\n set vignetteBlendMode(value) {\n if (this._vignetteBlendMode === value) {\n return;\n }\n this._vignetteBlendMode = value;\n this._updateParameters();\n }\n /**\n * Gets whether the vignette effect is enabled.\n */\n get vignetteEnabled() {\n return this._vignetteEnabled;\n }\n /**\n * Sets whether the vignette effect is enabled.\n */\n set vignetteEnabled(value) {\n if (this._vignetteEnabled === value) {\n return;\n }\n this._vignetteEnabled = value;\n this._updateParameters();\n }\n /**\n * Gets whether the dithering effect is enabled.\n * The dithering effect can be used to reduce banding.\n */\n get ditheringEnabled() {\n return this._ditheringEnabled;\n }\n /**\n * Sets whether the dithering effect is enabled.\n * The dithering effect can be used to reduce banding.\n */\n set ditheringEnabled(value) {\n if (this._ditheringEnabled === value) {\n return;\n }\n this._ditheringEnabled = value;\n this._updateParameters();\n }\n /**\n * Gets the dithering intensity. 0 is no dithering. Default is 1.0 / 255.0.\n */\n get ditheringIntensity() {\n return this._ditheringIntensity;\n }\n /**\n * Sets the dithering intensity. 0 is no dithering. Default is 1.0 / 255.0.\n */\n set ditheringIntensity(value) {\n if (this._ditheringIntensity === value) {\n return;\n }\n this._ditheringIntensity = value;\n this._updateParameters();\n }\n /**\n * If apply by post process is set to true, setting this to true will skip the the final color clamp step in the fragment shader\n * Applies to PBR materials.\n */\n get skipFinalColorClamp() {\n return this._skipFinalColorClamp;\n }\n /**\n * If apply by post process is set to true, setting this to true will skip the the final color clamp step in the fragment shader\n * Applies to PBR materials.\n */\n set skipFinalColorClamp(value) {\n if (this._skipFinalColorClamp === value) {\n return;\n }\n this._skipFinalColorClamp = value;\n this._updateParameters();\n }\n /**\n * Gets whether the image processing is applied through a post process or not.\n */\n get applyByPostProcess() {\n return this._applyByPostProcess;\n }\n /**\n * Sets whether the image processing is applied through a post process or not.\n */\n set applyByPostProcess(value) {\n if (this._applyByPostProcess === value) {\n return;\n }\n this._applyByPostProcess = value;\n this._updateParameters();\n }\n /**\n * Gets whether the image processing is enabled or not.\n */\n get isEnabled() {\n return this._isEnabled;\n }\n /**\n * Sets whether the image processing is enabled or not.\n */\n set isEnabled(value) {\n if (this._isEnabled === value) {\n return;\n }\n this._isEnabled = value;\n this._updateParameters();\n }\n /**\n * Method called each time the image processing information changes requires to recompile the effect.\n */\n _updateParameters() {\n this.onUpdateParameters.notifyObservers(this);\n }\n /**\n * Gets the current class name.\n * @returns \"ImageProcessingConfiguration\"\n */\n getClassName() {\n return \"ImageProcessingConfiguration\";\n }\n /**\n * Prepare the list of uniforms associated with the Image Processing effects.\n * @param uniforms The list of uniforms used in the effect\n * @param defines the list of defines currently in use\n */\n static PrepareUniforms(uniforms, defines) {\n if (defines.EXPOSURE) {\n uniforms.push(\"exposureLinear\");\n }\n if (defines.CONTRAST) {\n uniforms.push(\"contrast\");\n }\n if (defines.COLORGRADING) {\n uniforms.push(\"colorTransformSettings\");\n }\n if (defines.VIGNETTE || defines.DITHER) {\n uniforms.push(\"vInverseScreenSize\");\n }\n if (defines.VIGNETTE) {\n uniforms.push(\"vignetteSettings1\");\n uniforms.push(\"vignetteSettings2\");\n }\n if (defines.COLORCURVES) {\n ColorCurves.PrepareUniforms(uniforms);\n }\n if (defines.DITHER) {\n uniforms.push(\"ditherIntensity\");\n }\n }\n /**\n * Prepare the list of samplers associated with the Image Processing effects.\n * @param samplersList The list of uniforms used in the effect\n * @param defines the list of defines currently in use\n */\n static PrepareSamplers(samplersList, defines) {\n if (defines.COLORGRADING) {\n samplersList.push(\"txColorTransform\");\n }\n }\n /**\n * Prepare the list of defines associated to the shader.\n * @param defines the list of defines to complete\n * @param forPostProcess Define if we are currently in post process mode or not\n */\n prepareDefines(defines, forPostProcess = false) {\n if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {\n defines.VIGNETTE = false;\n defines.TONEMAPPING = false;\n defines.TONEMAPPING_ACES = false;\n defines.CONTRAST = false;\n defines.EXPOSURE = false;\n defines.COLORCURVES = false;\n defines.COLORGRADING = false;\n defines.COLORGRADING3D = false;\n defines.DITHER = false;\n defines.IMAGEPROCESSING = false;\n defines.SKIPFINALCOLORCLAMP = this.skipFinalColorClamp;\n defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;\n return;\n }\n defines.VIGNETTE = this.vignetteEnabled;\n defines.VIGNETTEBLENDMODEMULTIPLY = this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY;\n defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;\n defines.TONEMAPPING = this.toneMappingEnabled;\n switch (this._toneMappingType) {\n case ImageProcessingConfiguration.TONEMAPPING_ACES:\n defines.TONEMAPPING_ACES = true;\n break;\n default:\n defines.TONEMAPPING_ACES = false;\n break;\n }\n defines.CONTRAST = this.contrast !== 1.0;\n defines.EXPOSURE = this.exposure !== 1.0;\n defines.COLORCURVES = this.colorCurvesEnabled && !!this.colorCurves;\n defines.COLORGRADING = this.colorGradingEnabled && !!this.colorGradingTexture;\n if (defines.COLORGRADING) {\n defines.COLORGRADING3D = this.colorGradingTexture.is3D;\n }\n else {\n defines.COLORGRADING3D = false;\n }\n defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;\n defines.SAMPLER3DBGRMAP = this.colorGradingBGR;\n defines.DITHER = this._ditheringEnabled;\n defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;\n defines.SKIPFINALCOLORCLAMP = this.skipFinalColorClamp;\n defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.DITHER;\n }\n /**\n * Returns true if all the image processing information are ready.\n * @returns True if ready, otherwise, false\n */\n isReady() {\n // Color Grading texture can not be none blocking.\n return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();\n }\n /**\n * Binds the image processing to the shader.\n * @param effect The effect to bind to\n * @param overrideAspectRatio Override the aspect ratio of the effect\n */\n bind(effect, overrideAspectRatio) {\n // Color Curves\n if (this._colorCurvesEnabled && this.colorCurves) {\n ColorCurves.Bind(this.colorCurves, effect);\n }\n // Vignette and dither handled together due to common uniform.\n if (this._vignetteEnabled || this._ditheringEnabled) {\n const inverseWidth = 1 / effect.getEngine().getRenderWidth();\n const inverseHeight = 1 / effect.getEngine().getRenderHeight();\n effect.setFloat2(\"vInverseScreenSize\", inverseWidth, inverseHeight);\n if (this._ditheringEnabled) {\n effect.setFloat(\"ditherIntensity\", 0.5 * this._ditheringIntensity);\n }\n if (this._vignetteEnabled) {\n const aspectRatio = overrideAspectRatio != null ? overrideAspectRatio : inverseHeight / inverseWidth;\n let vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);\n let vignetteScaleX = vignetteScaleY * aspectRatio;\n const vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);\n vignetteScaleX = Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);\n vignetteScaleY = Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);\n effect.setFloat4(\"vignetteSettings1\", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCenterX, -vignetteScaleY * this.vignetteCenterY);\n const vignettePower = -2.0 * this.vignetteWeight;\n effect.setFloat4(\"vignetteSettings2\", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);\n }\n }\n // Exposure\n effect.setFloat(\"exposureLinear\", this.exposure);\n // Contrast\n effect.setFloat(\"contrast\", this.contrast);\n // Color transform settings\n if (this.colorGradingTexture) {\n effect.setTexture(\"txColorTransform\", this.colorGradingTexture);\n const textureSize = this.colorGradingTexture.getSize().height;\n effect.setFloat4(\"colorTransformSettings\", (textureSize - 1) / textureSize, // textureScale\n 0.5 / textureSize, // textureOffset\n textureSize, // textureSize\n this.colorGradingTexture.level // weight\n );\n }\n }\n /**\n * Clones the current image processing instance.\n * @returns The cloned image processing\n */\n clone() {\n return SerializationHelper.Clone(() => new ImageProcessingConfiguration(), this);\n }\n /**\n * Serializes the current image processing instance to a json representation.\n * @returns a JSON representation\n */\n serialize() {\n return SerializationHelper.Serialize(this);\n }\n /**\n * Parses the image processing from a json representation.\n * @param source the JSON source to parse\n * @returns The parsed image processing\n */\n static Parse(source) {\n const parsed = SerializationHelper.Parse(() => new ImageProcessingConfiguration(), source, null, null);\n // Backward compatibility\n if (source.vignetteCentreX !== undefined) {\n parsed.vignetteCenterX = source.vignetteCentreX;\n }\n if (source.vignetteCentreY !== undefined) {\n parsed.vignetteCenterY = source.vignetteCentreY;\n }\n return parsed;\n }\n /**\n * Used to apply the vignette as a mix with the pixel color.\n */\n static get VIGNETTEMODE_MULTIPLY() {\n return this._VIGNETTEMODE_MULTIPLY;\n }\n /**\n * Used to apply the vignette as a replacement of the pixel color.\n */\n static get VIGNETTEMODE_OPAQUE() {\n return this._VIGNETTEMODE_OPAQUE;\n }\n}\n/**\n * Default tone mapping applied in BabylonJS.\n */\nImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;\n/**\n * ACES Tone mapping (used by default in unreal and unity). This can help getting closer\n * to other engines rendering to increase portability.\n */\nImageProcessingConfiguration.TONEMAPPING_ACES = 1;\n// Static constants associated to the image processing.\nImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;\nImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;\n__decorate([\n serializeAsColorCurves()\n], ImageProcessingConfiguration.prototype, \"colorCurves\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_colorCurvesEnabled\", void 0);\n__decorate([\n serializeAsTexture(\"colorGradingTexture\")\n], ImageProcessingConfiguration.prototype, \"_colorGradingTexture\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_colorGradingEnabled\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_colorGradingWithGreenDepth\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_colorGradingBGR\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_exposure\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_toneMappingEnabled\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_toneMappingType\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_contrast\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"vignetteStretch\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"vignetteCenterX\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"vignetteCenterY\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"vignetteWeight\", void 0);\n__decorate([\n serializeAsColor4()\n], ImageProcessingConfiguration.prototype, \"vignetteColor\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"vignetteCameraFov\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_vignetteBlendMode\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_vignetteEnabled\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_ditheringEnabled\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_ditheringIntensity\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_skipFinalColorClamp\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_applyByPostProcess\", void 0);\n__decorate([\n serialize()\n], ImageProcessingConfiguration.prototype, \"_isEnabled\", void 0);\n// References the dependencies.\nSerializationHelper._ImageProcessingConfigurationParser = ImageProcessingConfiguration.Parse;\n//# sourceMappingURL=imageProcessingConfiguration.js.map","import { __decorate } from \"../tslib.es6.js\";\n\nimport { SerializationHelper, serialize } from \"../Misc/decorators.js\";\n/**\n * Class that holds the different stencil states of a material\n * Usage example: https://playground.babylonjs.com/#CW5PRI#10\n */\nexport class MaterialStencilState {\n /**\n * Creates a material stencil state instance\n */\n constructor() {\n this.reset();\n }\n /**\n * Resets all the stencil states to default values\n */\n reset() {\n this.enabled = false;\n this.mask = 0xff;\n this.func = 519;\n this.funcRef = 1;\n this.funcMask = 0xff;\n this.opStencilFail = 7680;\n this.opDepthFail = 7680;\n this.opStencilDepthPass = 7681;\n }\n /**\n * Gets or sets the stencil function\n */\n get func() {\n return this._func;\n }\n set func(value) {\n this._func = value;\n }\n /**\n * Gets or sets the stencil function reference\n */\n get funcRef() {\n return this._funcRef;\n }\n set funcRef(value) {\n this._funcRef = value;\n }\n /**\n * Gets or sets the stencil function mask\n */\n get funcMask() {\n return this._funcMask;\n }\n set funcMask(value) {\n this._funcMask = value;\n }\n /**\n * Gets or sets the operation when the stencil test fails\n */\n get opStencilFail() {\n return this._opStencilFail;\n }\n set opStencilFail(value) {\n this._opStencilFail = value;\n }\n /**\n * Gets or sets the operation when the depth test fails\n */\n get opDepthFail() {\n return this._opDepthFail;\n }\n set opDepthFail(value) {\n this._opDepthFail = value;\n }\n /**\n * Gets or sets the operation when the stencil+depth test succeeds\n */\n get opStencilDepthPass() {\n return this._opStencilDepthPass;\n }\n set opStencilDepthPass(value) {\n this._opStencilDepthPass = value;\n }\n /**\n * Gets or sets the stencil mask\n */\n get mask() {\n return this._mask;\n }\n set mask(value) {\n this._mask = value;\n }\n /**\n * Enables or disables the stencil test\n */\n get enabled() {\n return this._enabled;\n }\n set enabled(value) {\n this._enabled = value;\n }\n /**\n * Get the current class name, useful for serialization or dynamic coding.\n * @returns \"MaterialStencilState\"\n */\n getClassName() {\n return \"MaterialStencilState\";\n }\n /**\n * Makes a duplicate of the current configuration into another one.\n * @param stencilState defines stencil state where to copy the info\n */\n copyTo(stencilState) {\n SerializationHelper.Clone(() => stencilState, this);\n }\n /**\n * Serializes this stencil configuration.\n * @returns - An object with the serialized config.\n */\n serialize() {\n return SerializationHelper.Serialize(this);\n }\n /**\n * Parses a stencil state configuration from a serialized object.\n * @param source - Serialized object.\n * @param scene Defines the scene we are parsing for\n * @param rootUrl Defines the rootUrl to load from\n */\n parse(source, scene, rootUrl) {\n SerializationHelper.Parse(() => this, source, scene, rootUrl);\n }\n}\n__decorate([\n serialize()\n], MaterialStencilState.prototype, \"func\", null);\n__decorate([\n serialize()\n], MaterialStencilState.prototype, \"funcRef\", null);\n__decorate([\n serialize()\n], MaterialStencilState.prototype, \"funcMask\", null);\n__decorate([\n serialize()\n], MaterialStencilState.prototype, \"opStencilFail\", null);\n__decorate([\n serialize()\n], MaterialStencilState.prototype, \"opDepthFail\", null);\n__decorate([\n serialize()\n], MaterialStencilState.prototype, \"opStencilDepthPass\", null);\n__decorate([\n serialize()\n], MaterialStencilState.prototype, \"mask\", null);\n__decorate([\n serialize()\n], MaterialStencilState.prototype, \"enabled\", null);\n//# sourceMappingURL=materialStencilState.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize, SerializationHelper } from \"../Misc/decorators.js\";\nimport { Tools } from \"../Misc/tools.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { SubMesh } from \"../Meshes/subMesh.js\";\nimport { UniformBuffer } from \"./uniformBuffer.js\";\n\nimport { Logger } from \"../Misc/logger.js\";\nimport { Plane } from \"../Maths/math.plane.js\";\nimport { MaterialHelper } from \"./materialHelper.js\";\nimport { DrawWrapper } from \"./drawWrapper.js\";\nimport { MaterialStencilState } from \"./materialStencilState.js\";\nimport { ScenePerformancePriority } from \"../scene.js\";\nimport { MaterialPluginEvent } from \"./materialPluginEvent.js\";\n/**\n * Base class for the main features of a material in Babylon.js\n */\nexport class Material {\n /**\n * If the material can be rendered to several textures with MRT extension\n */\n get canRenderToMRT() {\n // By default, shaders are not compatible with MRTs\n // Base classes should override that if their shader supports MRT\n return false;\n }\n /**\n * Sets the alpha value of the material\n */\n set alpha(value) {\n if (this._alpha === value) {\n return;\n }\n const oldValue = this._alpha;\n this._alpha = value;\n // Only call dirty when there is a state change (no alpha / alpha)\n if (oldValue === 1 || value === 1) {\n this.markAsDirty(Material.MiscDirtyFlag + Material.PrePassDirtyFlag);\n }\n }\n /**\n * Gets the alpha value of the material\n */\n get alpha() {\n return this._alpha;\n }\n /**\n * Sets the culling state (true to enable culling, false to disable)\n */\n set backFaceCulling(value) {\n if (this._backFaceCulling === value) {\n return;\n }\n this._backFaceCulling = value;\n this.markAsDirty(Material.TextureDirtyFlag);\n }\n /**\n * Gets the culling state\n */\n get backFaceCulling() {\n return this._backFaceCulling;\n }\n /**\n * Sets the type of faces that should be culled (true for back faces, false for front faces)\n */\n set cullBackFaces(value) {\n if (this._cullBackFaces === value) {\n return;\n }\n this._cullBackFaces = value;\n this.markAsDirty(Material.TextureDirtyFlag);\n }\n /**\n * Gets the type of faces that should be culled\n */\n get cullBackFaces() {\n return this._cullBackFaces;\n }\n /**\n * Block the dirty-mechanism for this specific material\n * When set to false after being true the material will be marked as dirty.\n */\n get blockDirtyMechanism() {\n return this._blockDirtyMechanism;\n }\n set blockDirtyMechanism(value) {\n if (this._blockDirtyMechanism === value) {\n return;\n }\n this._blockDirtyMechanism = value;\n if (!value) {\n this.markDirty();\n }\n }\n /**\n * This allows you to modify the material without marking it as dirty after every change.\n * This function should be used if you need to make more than one dirty-enabling change to the material - adding a texture, setting a new fill mode and so on.\n * The callback will pass the material as an argument, so you can make your changes to it.\n * @param callback the callback to be executed that will update the material\n */\n atomicMaterialsUpdate(callback) {\n this.blockDirtyMechanism = true;\n try {\n callback(this);\n }\n finally {\n this.blockDirtyMechanism = false;\n }\n }\n /**\n * Gets a boolean indicating that current material needs to register RTT\n */\n get hasRenderTargetTextures() {\n this._eventInfo.hasRenderTargetTextures = false;\n this._callbackPluginEventHasRenderTargetTextures(this._eventInfo);\n return this._eventInfo.hasRenderTargetTextures;\n }\n /**\n * Called during a dispose event\n */\n set onDispose(callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n }\n /**\n * An event triggered when the material is bound\n */\n get onBindObservable() {\n if (!this._onBindObservable) {\n this._onBindObservable = new Observable();\n }\n return this._onBindObservable;\n }\n /**\n * Called during a bind event\n */\n set onBind(callback) {\n if (this._onBindObserver) {\n this.onBindObservable.remove(this._onBindObserver);\n }\n this._onBindObserver = this.onBindObservable.add(callback);\n }\n /**\n * An event triggered when the material is unbound\n */\n get onUnBindObservable() {\n if (!this._onUnBindObservable) {\n this._onUnBindObservable = new Observable();\n }\n return this._onUnBindObservable;\n }\n /**\n * An event triggered when the effect is (re)created\n */\n get onEffectCreatedObservable() {\n if (!this._onEffectCreatedObservable) {\n this._onEffectCreatedObservable = new Observable();\n }\n return this._onEffectCreatedObservable;\n }\n /**\n * Sets the value of the alpha mode.\n *\n * | Value | Type | Description |\n * | --- | --- | --- |\n * | 0 | ALPHA_DISABLE | |\n * | 1 | ALPHA_ADD | |\n * | 2 | ALPHA_COMBINE | |\n * | 3 | ALPHA_SUBTRACT | |\n * | 4 | ALPHA_MULTIPLY | |\n * | 5 | ALPHA_MAXIMIZED | |\n * | 6 | ALPHA_ONEONE | |\n * | 7 | ALPHA_PREMULTIPLIED | |\n * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |\n * | 9 | ALPHA_INTERPOLATE | |\n * | 10 | ALPHA_SCREENMODE | |\n *\n */\n set alphaMode(value) {\n if (this._alphaMode === value) {\n return;\n }\n this._alphaMode = value;\n this.markAsDirty(Material.TextureDirtyFlag);\n }\n /**\n * Gets the value of the alpha mode\n */\n get alphaMode() {\n return this._alphaMode;\n }\n /**\n * Sets the need depth pre-pass value\n */\n set needDepthPrePass(value) {\n if (this._needDepthPrePass === value) {\n return;\n }\n this._needDepthPrePass = value;\n if (this._needDepthPrePass) {\n this.checkReadyOnEveryCall = true;\n }\n }\n /**\n * Gets the depth pre-pass value\n */\n get needDepthPrePass() {\n return this._needDepthPrePass;\n }\n /**\n * Can this material render to prepass\n */\n get isPrePassCapable() {\n return false;\n }\n /**\n * Sets the state for enabling fog\n */\n set fogEnabled(value) {\n if (this._fogEnabled === value) {\n return;\n }\n this._fogEnabled = value;\n this.markAsDirty(Material.MiscDirtyFlag);\n }\n /**\n * Gets the value of the fog enabled state\n */\n get fogEnabled() {\n return this._fogEnabled;\n }\n get wireframe() {\n switch (this._fillMode) {\n case Material.WireFrameFillMode:\n case Material.LineListDrawMode:\n case Material.LineLoopDrawMode:\n case Material.LineStripDrawMode:\n return true;\n }\n return this._scene.forceWireframe;\n }\n /**\n * Sets the state of wireframe mode\n */\n set wireframe(value) {\n this.fillMode = value ? Material.WireFrameFillMode : Material.TriangleFillMode;\n }\n /**\n * Gets the value specifying if point clouds are enabled\n */\n get pointsCloud() {\n switch (this._fillMode) {\n case Material.PointFillMode:\n case Material.PointListDrawMode:\n return true;\n }\n return this._scene.forcePointsCloud;\n }\n /**\n * Sets the state of point cloud mode\n */\n set pointsCloud(value) {\n this.fillMode = value ? Material.PointFillMode : Material.TriangleFillMode;\n }\n /**\n * Gets the material fill mode\n */\n get fillMode() {\n return this._fillMode;\n }\n /**\n * Sets the material fill mode\n */\n set fillMode(value) {\n if (this._fillMode === value) {\n return;\n }\n this._fillMode = value;\n this.markAsDirty(Material.MiscDirtyFlag);\n }\n /** @internal */\n _getDrawWrapper() {\n return this._drawWrapper;\n }\n /**\n * @internal\n */\n _setDrawWrapper(drawWrapper) {\n this._drawWrapper = drawWrapper;\n }\n /**\n * Creates a material instance\n * @param name defines the name of the material\n * @param scene defines the scene to reference\n * @param doNotAdd specifies if the material should be added to the scene\n */\n constructor(name, scene, doNotAdd) {\n /**\n * Custom shadow depth material to use for shadow rendering instead of the in-built one\n */\n this.shadowDepthWrapper = null;\n /**\n * Gets or sets a boolean indicating that the material is allowed (if supported) to do shader hot swapping.\n * This means that the material can keep using a previous shader while a new one is being compiled.\n * This is mostly used when shader parallel compilation is supported (true by default)\n */\n this.allowShaderHotSwapping = true;\n /**\n * Gets or sets user defined metadata\n */\n this.metadata = null;\n /**\n * For internal use only. Please do not use.\n */\n this.reservedDataStore = null;\n /**\n * Specifies if the ready state should be checked on each call\n */\n this.checkReadyOnEveryCall = false;\n /**\n * Specifies if the ready state should be checked once\n */\n this.checkReadyOnlyOnce = false;\n /**\n * The state of the material\n */\n this.state = \"\";\n /**\n * The alpha value of the material\n */\n this._alpha = 1.0;\n /**\n * Specifies if back face culling is enabled\n */\n this._backFaceCulling = true;\n /**\n * Specifies if back or front faces should be culled (when culling is enabled)\n */\n this._cullBackFaces = true;\n this._blockDirtyMechanism = false;\n /**\n * Callback triggered when the material is compiled\n */\n this.onCompiled = null;\n /**\n * Callback triggered when an error occurs\n */\n this.onError = null;\n /**\n * Callback triggered to get the render target textures\n */\n this.getRenderTargetTextures = null;\n /**\n * Specifies if the material should be serialized\n */\n this.doNotSerialize = false;\n /**\n * @internal\n */\n this._storeEffectOnSubMeshes = false;\n /**\n * Stores the animations for the material\n */\n this.animations = null;\n /**\n * An event triggered when the material is disposed\n */\n this.onDisposeObservable = new Observable();\n /**\n * An observer which watches for dispose events\n */\n this._onDisposeObserver = null;\n this._onUnBindObservable = null;\n /**\n * An observer which watches for bind events\n */\n this._onBindObserver = null;\n /**\n * Stores the value of the alpha mode\n */\n this._alphaMode = 2;\n /**\n * Stores the state of the need depth pre-pass value\n */\n this._needDepthPrePass = false;\n /**\n * Specifies if depth writing should be disabled\n */\n this.disableDepthWrite = false;\n /**\n * Specifies if color writing should be disabled\n */\n this.disableColorWrite = false;\n /**\n * Specifies if depth writing should be forced\n */\n this.forceDepthWrite = false;\n /**\n * Specifies the depth function that should be used. 0 means the default engine function\n */\n this.depthFunction = 0;\n /**\n * Specifies if there should be a separate pass for culling\n */\n this.separateCullingPass = false;\n /**\n * Stores the state specifying if fog should be enabled\n */\n this._fogEnabled = true;\n /**\n * Stores the size of points\n */\n this.pointSize = 1.0;\n /**\n * Stores the z offset Factor value\n */\n this.zOffset = 0;\n /**\n * Stores the z offset Units value\n */\n this.zOffsetUnits = 0;\n /**\n * Gives access to the stencil properties of the material\n */\n this.stencil = new MaterialStencilState();\n /**\n * Specifies if uniform buffers should be used\n */\n this._useUBO = false;\n /**\n * Stores the fill mode state\n */\n this._fillMode = Material.TriangleFillMode;\n /**\n * Specifies if the depth write state should be cached\n */\n this._cachedDepthWriteState = false;\n /**\n * Specifies if the color write state should be cached\n */\n this._cachedColorWriteState = false;\n /**\n * Specifies if the depth function state should be cached\n */\n this._cachedDepthFunctionState = 0;\n /** @internal */\n this._indexInSceneMaterialArray = -1;\n /** @internal */\n this.meshMap = null;\n /** @internal */\n this._parentContainer = null;\n /** @internal */\n this._uniformBufferLayoutBuilt = false;\n this._eventInfo = {}; // will be initialized before each event notification\n /** @internal */\n this._callbackPluginEventGeneric = () => void 0;\n /** @internal */\n this._callbackPluginEventIsReadyForSubMesh = () => void 0;\n /** @internal */\n this._callbackPluginEventPrepareDefines = () => void 0;\n /** @internal */\n this._callbackPluginEventPrepareDefinesBeforeAttributes = () => void 0;\n /** @internal */\n this._callbackPluginEventHardBindForSubMesh = () => void 0;\n /** @internal */\n this._callbackPluginEventBindForSubMesh = () => void 0;\n /** @internal */\n this._callbackPluginEventHasRenderTargetTextures = () => void 0;\n /** @internal */\n this._callbackPluginEventFillRenderTargetTextures = () => void 0;\n /**\n * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.\n */\n this._forceAlphaTest = false;\n /**\n * The transparency mode of the material.\n */\n this._transparencyMode = null;\n this.name = name;\n const setScene = scene || EngineStore.LastCreatedScene;\n if (!setScene) {\n return;\n }\n this._scene = setScene;\n this._dirtyCallbacks = {};\n this._dirtyCallbacks[1] = this._markAllSubMeshesAsTexturesDirty.bind(this);\n this._dirtyCallbacks[2] = this._markAllSubMeshesAsLightsDirty.bind(this);\n this._dirtyCallbacks[4] = this._markAllSubMeshesAsFresnelDirty.bind(this);\n this._dirtyCallbacks[8] = this._markAllSubMeshesAsAttributesDirty.bind(this);\n this._dirtyCallbacks[16] = this._markAllSubMeshesAsMiscDirty.bind(this);\n this._dirtyCallbacks[32] = this._markAllSubMeshesAsPrePassDirty.bind(this);\n this._dirtyCallbacks[63] = this._markAllSubMeshesAsAllDirty.bind(this);\n this.id = name || Tools.RandomId();\n this.uniqueId = this._scene.getUniqueId();\n this._materialContext = this._scene.getEngine().createMaterialContext();\n this._drawWrapper = new DrawWrapper(this._scene.getEngine(), false);\n this._drawWrapper.materialContext = this._materialContext;\n if (this._scene.useRightHandedSystem) {\n this.sideOrientation = Material.ClockWiseSideOrientation;\n }\n else {\n this.sideOrientation = Material.CounterClockWiseSideOrientation;\n }\n this._uniformBuffer = new UniformBuffer(this._scene.getEngine(), undefined, undefined, name);\n this._useUBO = this.getScene().getEngine().supportsUniformBuffers;\n if (!doNotAdd) {\n this._scene.addMaterial(this);\n }\n if (this._scene.useMaterialMeshMap) {\n this.meshMap = {};\n }\n Material.OnEventObservable.notifyObservers(this, MaterialPluginEvent.Created);\n }\n /**\n * Returns a string representation of the current material\n * @param fullDetails defines a boolean indicating which levels of logging is desired\n * @returns a string with material information\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n toString(fullDetails) {\n const ret = \"Name: \" + this.name;\n return ret;\n }\n /**\n * Gets the class name of the material\n * @returns a string with the class name of the material\n */\n getClassName() {\n return \"Material\";\n }\n /** @internal */\n get _isMaterial() {\n return true;\n }\n /**\n * Specifies if updates for the material been locked\n */\n get isFrozen() {\n return this.checkReadyOnlyOnce;\n }\n /**\n * Locks updates for the material\n */\n freeze() {\n this.markDirty();\n this.checkReadyOnlyOnce = true;\n }\n /**\n * Unlocks updates for the material\n */\n unfreeze() {\n this.markDirty();\n this.checkReadyOnlyOnce = false;\n }\n /**\n * Specifies if the material is ready to be used\n * @param mesh defines the mesh to check\n * @param useInstances specifies if instances should be used\n * @returns a boolean indicating if the material is ready to be used\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isReady(mesh, useInstances) {\n return true;\n }\n /**\n * Specifies that the submesh is ready to be used\n * @param mesh defines the mesh to check\n * @param subMesh defines which submesh to check\n * @param useInstances specifies that instances should be used\n * @returns a boolean indicating that the submesh is ready or not\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isReadyForSubMesh(mesh, subMesh, useInstances) {\n const defines = subMesh.materialDefines;\n if (!defines) {\n return false;\n }\n this._eventInfo.isReadyForSubMesh = true;\n this._eventInfo.defines = defines;\n this._callbackPluginEventIsReadyForSubMesh(this._eventInfo);\n return this._eventInfo.isReadyForSubMesh;\n }\n /**\n * Returns the material effect\n * @returns the effect associated with the material\n */\n getEffect() {\n return this._drawWrapper.effect;\n }\n /**\n * Returns the current scene\n * @returns a Scene\n */\n getScene() {\n return this._scene;\n }\n /**\n * Gets the current transparency mode.\n */\n get transparencyMode() {\n return this._transparencyMode;\n }\n /**\n * Sets the transparency mode of the material.\n *\n * | Value | Type | Description |\n * | ----- | ----------------------------------- | ----------- |\n * | 0 | OPAQUE | |\n * | 1 | ALPHATEST | |\n * | 2 | ALPHABLEND | |\n * | 3 | ALPHATESTANDBLEND | |\n *\n */\n set transparencyMode(value) {\n if (this._transparencyMode === value) {\n return;\n }\n this._transparencyMode = value;\n this._forceAlphaTest = value === Material.MATERIAL_ALPHATESTANDBLEND;\n this._markAllSubMeshesAsTexturesAndMiscDirty();\n }\n /**\n * Returns true if alpha blending should be disabled.\n */\n get _disableAlphaBlending() {\n return this._transparencyMode === Material.MATERIAL_OPAQUE || this._transparencyMode === Material.MATERIAL_ALPHATEST;\n }\n /**\n * Specifies whether or not this material should be rendered in alpha blend mode.\n * @returns a boolean specifying if alpha blending is needed\n */\n needAlphaBlending() {\n if (this._disableAlphaBlending) {\n return false;\n }\n return this.alpha < 1.0;\n }\n /**\n * Specifies if the mesh will require alpha blending\n * @param mesh defines the mesh to check\n * @returns a boolean specifying if alpha blending is needed for the mesh\n */\n needAlphaBlendingForMesh(mesh) {\n if (mesh.visibility < 1.0) {\n return true;\n }\n if (this._disableAlphaBlending) {\n return false;\n }\n return mesh.hasVertexAlpha || this.needAlphaBlending();\n }\n /**\n * Specifies whether or not this material should be rendered in alpha test mode.\n * @returns a boolean specifying if an alpha test is needed.\n */\n needAlphaTesting() {\n if (this._forceAlphaTest) {\n return true;\n }\n return false;\n }\n /**\n * Specifies if material alpha testing should be turned on for the mesh\n * @param mesh defines the mesh to check\n */\n _shouldTurnAlphaTestOn(mesh) {\n return !this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting();\n }\n /**\n * Gets the texture used for the alpha test\n * @returns the texture to use for alpha testing\n */\n getAlphaTestTexture() {\n return null;\n }\n /**\n * Marks the material to indicate that it needs to be re-calculated\n * @param forceMaterialDirty - Forces the material to be marked as dirty for all components (same as this.markAsDirty(Material.AllDirtyFlag)). You should use this flag if the material is frozen and you want to force a recompilation.\n */\n markDirty(forceMaterialDirty = false) {\n const meshes = this.getScene().meshes;\n for (const mesh of meshes) {\n if (!mesh.subMeshes) {\n continue;\n }\n for (const subMesh of mesh.subMeshes) {\n if (subMesh.getMaterial() !== this) {\n continue;\n }\n if (!subMesh.effect) {\n continue;\n }\n subMesh.effect._wasPreviouslyReady = false;\n subMesh.effect._wasPreviouslyUsingInstances = null;\n subMesh.effect._forceRebindOnNextCall = forceMaterialDirty;\n }\n }\n if (forceMaterialDirty) {\n this.markAsDirty(Material.AllDirtyFlag);\n }\n }\n /**\n * @internal\n */\n _preBind(effect, overrideOrientation = null) {\n const engine = this._scene.getEngine();\n const orientation = overrideOrientation == null ? this.sideOrientation : overrideOrientation;\n const reverse = orientation === Material.ClockWiseSideOrientation;\n engine.enableEffect(effect ? effect : this._getDrawWrapper());\n engine.setState(this.backFaceCulling, this.zOffset, false, reverse, this._scene._mirroredCameraPosition ? !this.cullBackFaces : this.cullBackFaces, this.stencil, this.zOffsetUnits);\n return reverse;\n }\n /**\n * Binds the material to the mesh\n * @param world defines the world transformation matrix\n * @param mesh defines the mesh to bind the material to\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n bind(world, mesh) { }\n /**\n * Initializes the uniform buffer layout for the shader.\n */\n buildUniformLayout() {\n const ubo = this._uniformBuffer;\n this._eventInfo.ubo = ubo;\n this._callbackPluginEventGeneric(MaterialPluginEvent.PrepareUniformBuffer, this._eventInfo);\n ubo.create();\n this._uniformBufferLayoutBuilt = true;\n }\n /**\n * Binds the submesh to the material\n * @param world defines the world transformation matrix\n * @param mesh defines the mesh containing the submesh\n * @param subMesh defines the submesh to bind the material to\n */\n bindForSubMesh(world, mesh, subMesh) {\n const effect = subMesh.effect;\n if (!effect) {\n return;\n }\n this._eventInfo.subMesh = subMesh;\n this._callbackPluginEventBindForSubMesh(this._eventInfo);\n effect._forceRebindOnNextCall = false;\n }\n /**\n * Binds the world matrix to the material\n * @param world defines the world transformation matrix\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n bindOnlyWorldMatrix(world) { }\n /**\n * Binds the view matrix to the effect\n * @param effect defines the effect to bind the view matrix to\n */\n bindView(effect) {\n if (!this._useUBO) {\n effect.setMatrix(\"view\", this.getScene().getViewMatrix());\n }\n else {\n this._needToBindSceneUbo = true;\n }\n }\n /**\n * Binds the view projection and projection matrices to the effect\n * @param effect defines the effect to bind the view projection and projection matrices to\n */\n bindViewProjection(effect) {\n if (!this._useUBO) {\n effect.setMatrix(\"viewProjection\", this.getScene().getTransformMatrix());\n effect.setMatrix(\"projection\", this.getScene().getProjectionMatrix());\n }\n else {\n this._needToBindSceneUbo = true;\n }\n }\n /**\n * Binds the view matrix to the effect\n * @param effect defines the effect to bind the view matrix to\n * @param variableName name of the shader variable that will hold the eye position\n */\n bindEyePosition(effect, variableName) {\n if (!this._useUBO) {\n this._scene.bindEyePosition(effect, variableName);\n }\n else {\n this._needToBindSceneUbo = true;\n }\n }\n /**\n * Processes to execute after binding the material to a mesh\n * @param mesh defines the rendered mesh\n * @param effect\n */\n _afterBind(mesh, effect = null) {\n this._scene._cachedMaterial = this;\n if (this._needToBindSceneUbo) {\n if (effect) {\n this._needToBindSceneUbo = false;\n MaterialHelper.BindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());\n this._scene.finalizeSceneUbo();\n }\n }\n if (mesh) {\n this._scene._cachedVisibility = mesh.visibility;\n }\n else {\n this._scene._cachedVisibility = 1;\n }\n if (this._onBindObservable && mesh) {\n this._onBindObservable.notifyObservers(mesh);\n }\n if (this.disableDepthWrite) {\n const engine = this._scene.getEngine();\n this._cachedDepthWriteState = engine.getDepthWrite();\n engine.setDepthWrite(false);\n }\n if (this.disableColorWrite) {\n const engine = this._scene.getEngine();\n this._cachedColorWriteState = engine.getColorWrite();\n engine.setColorWrite(false);\n }\n if (this.depthFunction !== 0) {\n const engine = this._scene.getEngine();\n this._cachedDepthFunctionState = engine.getDepthFunction() || 0;\n engine.setDepthFunction(this.depthFunction);\n }\n }\n /**\n * Unbinds the material from the mesh\n */\n unbind() {\n if (this._onUnBindObservable) {\n this._onUnBindObservable.notifyObservers(this);\n }\n if (this.depthFunction !== 0) {\n const engine = this._scene.getEngine();\n engine.setDepthFunction(this._cachedDepthFunctionState);\n }\n if (this.disableDepthWrite) {\n const engine = this._scene.getEngine();\n engine.setDepthWrite(this._cachedDepthWriteState);\n }\n if (this.disableColorWrite) {\n const engine = this._scene.getEngine();\n engine.setColorWrite(this._cachedColorWriteState);\n }\n }\n /**\n * Returns the animatable textures.\n * @returns - Array of animatable textures.\n */\n getAnimatables() {\n this._eventInfo.animatables = [];\n this._callbackPluginEventGeneric(MaterialPluginEvent.GetAnimatables, this._eventInfo);\n return this._eventInfo.animatables;\n }\n /**\n * Gets the active textures from the material\n * @returns an array of textures\n */\n getActiveTextures() {\n this._eventInfo.activeTextures = [];\n this._callbackPluginEventGeneric(MaterialPluginEvent.GetActiveTextures, this._eventInfo);\n return this._eventInfo.activeTextures;\n }\n /**\n * Specifies if the material uses a texture\n * @param texture defines the texture to check against the material\n * @returns a boolean specifying if the material uses the texture\n */\n hasTexture(texture) {\n this._eventInfo.hasTexture = false;\n this._eventInfo.texture = texture;\n this._callbackPluginEventGeneric(MaterialPluginEvent.HasTexture, this._eventInfo);\n return this._eventInfo.hasTexture;\n }\n /**\n * Makes a duplicate of the material, and gives it a new name\n * @param name defines the new name for the duplicated material\n * @returns the cloned material\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n clone(name) {\n return null;\n }\n _clonePlugins(targetMaterial, rootUrl) {\n const serializationObject = {};\n // Create plugins in targetMaterial in case they don't exist\n this._serializePlugins(serializationObject);\n Material._parsePlugins(serializationObject, targetMaterial, this._scene, rootUrl);\n // Copy the properties of the current plugins to the cloned material's plugins\n if (this.pluginManager) {\n for (const plugin of this.pluginManager._plugins) {\n const targetPlugin = targetMaterial.pluginManager.getPlugin(plugin.name);\n plugin.copyTo(targetPlugin);\n }\n }\n }\n /**\n * Gets the meshes bound to the material\n * @returns an array of meshes bound to the material\n */\n getBindedMeshes() {\n if (this.meshMap) {\n const result = new Array();\n for (const meshId in this.meshMap) {\n const mesh = this.meshMap[meshId];\n if (mesh) {\n result.push(mesh);\n }\n }\n return result;\n }\n else {\n const meshes = this._scene.meshes;\n return meshes.filter((mesh) => mesh.material === this);\n }\n }\n /**\n * Force shader compilation\n * @param mesh defines the mesh associated with this material\n * @param onCompiled defines a function to execute once the material is compiled\n * @param options defines the options to configure the compilation\n * @param onError defines a function to execute if the material fails compiling\n */\n forceCompilation(mesh, onCompiled, options, onError) {\n const localOptions = Object.assign({ clipPlane: false, useInstances: false }, options);\n const scene = this.getScene();\n const currentHotSwapingState = this.allowShaderHotSwapping;\n this.allowShaderHotSwapping = false; // Turned off to let us evaluate the real compilation state\n const checkReady = () => {\n if (!this._scene || !this._scene.getEngine()) {\n return;\n }\n const clipPlaneState = scene.clipPlane;\n if (localOptions.clipPlane) {\n scene.clipPlane = new Plane(0, 0, 0, 1);\n }\n if (this._storeEffectOnSubMeshes) {\n let allDone = true, lastError = null;\n if (mesh.subMeshes) {\n const tempSubMesh = new SubMesh(0, 0, 0, 0, 0, mesh, undefined, false, false);\n if (tempSubMesh.materialDefines) {\n tempSubMesh.materialDefines._renderId = -1;\n }\n if (!this.isReadyForSubMesh(mesh, tempSubMesh, localOptions.useInstances)) {\n if (tempSubMesh.effect && tempSubMesh.effect.getCompilationError() && tempSubMesh.effect.allFallbacksProcessed()) {\n lastError = tempSubMesh.effect.getCompilationError();\n }\n else {\n allDone = false;\n setTimeout(checkReady, 16);\n }\n }\n }\n if (allDone) {\n this.allowShaderHotSwapping = currentHotSwapingState;\n if (lastError) {\n if (onError) {\n onError(lastError);\n }\n }\n if (onCompiled) {\n onCompiled(this);\n }\n }\n }\n else {\n if (this.isReady()) {\n this.allowShaderHotSwapping = currentHotSwapingState;\n if (onCompiled) {\n onCompiled(this);\n }\n }\n else {\n setTimeout(checkReady, 16);\n }\n }\n if (localOptions.clipPlane) {\n scene.clipPlane = clipPlaneState;\n }\n };\n checkReady();\n }\n /**\n * Force shader compilation\n * @param mesh defines the mesh that will use this material\n * @param options defines additional options for compiling the shaders\n * @returns a promise that resolves when the compilation completes\n */\n forceCompilationAsync(mesh, options) {\n return new Promise((resolve, reject) => {\n this.forceCompilation(mesh, () => {\n resolve();\n }, options, (reason) => {\n reject(reason);\n });\n });\n }\n /**\n * Marks a define in the material to indicate that it needs to be re-computed\n * @param flag defines a flag used to determine which parts of the material have to be marked as dirty\n */\n markAsDirty(flag) {\n if (this.getScene().blockMaterialDirtyMechanism || this._blockDirtyMechanism) {\n return;\n }\n Material._DirtyCallbackArray.length = 0;\n if (flag & Material.TextureDirtyFlag) {\n Material._DirtyCallbackArray.push(Material._TextureDirtyCallBack);\n }\n if (flag & Material.LightDirtyFlag) {\n Material._DirtyCallbackArray.push(Material._LightsDirtyCallBack);\n }\n if (flag & Material.FresnelDirtyFlag) {\n Material._DirtyCallbackArray.push(Material._FresnelDirtyCallBack);\n }\n if (flag & Material.AttributesDirtyFlag) {\n Material._DirtyCallbackArray.push(Material._AttributeDirtyCallBack);\n }\n if (flag & Material.MiscDirtyFlag) {\n Material._DirtyCallbackArray.push(Material._MiscDirtyCallBack);\n }\n if (flag & Material.PrePassDirtyFlag) {\n Material._DirtyCallbackArray.push(Material._PrePassDirtyCallBack);\n }\n if (Material._DirtyCallbackArray.length) {\n this._markAllSubMeshesAsDirty(Material._RunDirtyCallBacks);\n }\n this.getScene().resetCachedMaterial();\n }\n /**\n * Resets the draw wrappers cache for all submeshes that are using this material\n */\n resetDrawCache() {\n const meshes = this.getScene().meshes;\n for (const mesh of meshes) {\n if (!mesh.subMeshes) {\n continue;\n }\n for (const subMesh of mesh.subMeshes) {\n if (subMesh.getMaterial() !== this) {\n continue;\n }\n subMesh.resetDrawCache();\n }\n }\n }\n /**\n * Marks all submeshes of a material to indicate that their material defines need to be re-calculated\n * @param func defines a function which checks material defines against the submeshes\n */\n _markAllSubMeshesAsDirty(func) {\n if (this.getScene().blockMaterialDirtyMechanism || this._blockDirtyMechanism) {\n return;\n }\n const meshes = this.getScene().meshes;\n for (const mesh of meshes) {\n if (!mesh.subMeshes) {\n continue;\n }\n for (const subMesh of mesh.subMeshes) {\n // We want to skip the submeshes which are not using this material or which have not yet rendered at least once\n if (subMesh.getMaterial(false) !== this) {\n continue;\n }\n for (const drawWrapper of subMesh._drawWrappers) {\n if (!drawWrapper || !drawWrapper.defines || !drawWrapper.defines.markAllAsDirty) {\n continue;\n }\n if (this._materialContext === drawWrapper.materialContext) {\n func(drawWrapper.defines);\n }\n }\n }\n }\n }\n /**\n * Indicates that the scene should check if the rendering now needs a prepass\n */\n _markScenePrePassDirty() {\n if (this.getScene().blockMaterialDirtyMechanism || this._blockDirtyMechanism) {\n return;\n }\n const prePassRenderer = this.getScene().enablePrePassRenderer();\n if (prePassRenderer) {\n prePassRenderer.markAsDirty();\n }\n }\n /**\n * Indicates that we need to re-calculated for all submeshes\n */\n _markAllSubMeshesAsAllDirty() {\n this._markAllSubMeshesAsDirty(Material._AllDirtyCallBack);\n }\n /**\n * Indicates that image processing needs to be re-calculated for all submeshes\n */\n _markAllSubMeshesAsImageProcessingDirty() {\n this._markAllSubMeshesAsDirty(Material._ImageProcessingDirtyCallBack);\n }\n /**\n * Indicates that textures need to be re-calculated for all submeshes\n */\n _markAllSubMeshesAsTexturesDirty() {\n this._markAllSubMeshesAsDirty(Material._TextureDirtyCallBack);\n }\n /**\n * Indicates that fresnel needs to be re-calculated for all submeshes\n */\n _markAllSubMeshesAsFresnelDirty() {\n this._markAllSubMeshesAsDirty(Material._FresnelDirtyCallBack);\n }\n /**\n * Indicates that fresnel and misc need to be re-calculated for all submeshes\n */\n _markAllSubMeshesAsFresnelAndMiscDirty() {\n this._markAllSubMeshesAsDirty(Material._FresnelAndMiscDirtyCallBack);\n }\n /**\n * Indicates that lights need to be re-calculated for all submeshes\n */\n _markAllSubMeshesAsLightsDirty() {\n this._markAllSubMeshesAsDirty(Material._LightsDirtyCallBack);\n }\n /**\n * Indicates that attributes need to be re-calculated for all submeshes\n */\n _markAllSubMeshesAsAttributesDirty() {\n this._markAllSubMeshesAsDirty(Material._AttributeDirtyCallBack);\n }\n /**\n * Indicates that misc needs to be re-calculated for all submeshes\n */\n _markAllSubMeshesAsMiscDirty() {\n this._markAllSubMeshesAsDirty(Material._MiscDirtyCallBack);\n }\n /**\n * Indicates that prepass needs to be re-calculated for all submeshes\n */\n _markAllSubMeshesAsPrePassDirty() {\n this._markAllSubMeshesAsDirty(Material._MiscDirtyCallBack);\n }\n /**\n * Indicates that textures and misc need to be re-calculated for all submeshes\n */\n _markAllSubMeshesAsTexturesAndMiscDirty() {\n this._markAllSubMeshesAsDirty(Material._TextureAndMiscDirtyCallBack);\n }\n _checkScenePerformancePriority() {\n if (this._scene.performancePriority !== ScenePerformancePriority.BackwardCompatible) {\n this.checkReadyOnlyOnce = true;\n // re-set the flag when the perf priority changes\n const observer = this._scene.onScenePerformancePriorityChangedObservable.addOnce(() => {\n this.checkReadyOnlyOnce = false;\n });\n // if this material is disposed before the scene is disposed, cleanup the observer\n this.onDisposeObservable.add(() => {\n this._scene.onScenePerformancePriorityChangedObservable.remove(observer);\n });\n }\n }\n /**\n * Sets the required values to the prepass renderer.\n * @param prePassRenderer defines the prepass renderer to setup.\n * @returns true if the pre pass is needed.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n setPrePassRenderer(prePassRenderer) {\n // Do Nothing by default\n return false;\n }\n /**\n * Disposes the material\n * @param forceDisposeEffect specifies if effects should be forcefully disposed\n * @param forceDisposeTextures specifies if textures should be forcefully disposed\n * @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh\n */\n dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {\n const scene = this.getScene();\n // Animations\n scene.stopAnimation(this);\n scene.freeProcessedMaterials();\n // Remove from scene\n scene.removeMaterial(this);\n this._eventInfo.forceDisposeTextures = forceDisposeTextures;\n this._callbackPluginEventGeneric(MaterialPluginEvent.Disposed, this._eventInfo);\n if (this._parentContainer) {\n const index = this._parentContainer.materials.indexOf(this);\n if (index > -1) {\n this._parentContainer.materials.splice(index, 1);\n }\n this._parentContainer = null;\n }\n if (notBoundToMesh !== true) {\n // Remove from meshes\n if (this.meshMap) {\n for (const meshId in this.meshMap) {\n const mesh = this.meshMap[meshId];\n if (mesh) {\n mesh.material = null; // will set the entry in the map to undefined\n this.releaseVertexArrayObject(mesh, forceDisposeEffect);\n }\n }\n }\n else {\n const meshes = scene.meshes;\n for (const mesh of meshes) {\n if (mesh.material === this && !mesh.sourceMesh) {\n mesh.material = null;\n this.releaseVertexArrayObject(mesh, forceDisposeEffect);\n }\n }\n }\n }\n this._uniformBuffer.dispose();\n // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect\n if (forceDisposeEffect && this._drawWrapper.effect) {\n if (!this._storeEffectOnSubMeshes) {\n this._drawWrapper.effect.dispose();\n }\n this._drawWrapper.effect = null;\n }\n this.metadata = null;\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n if (this._onBindObservable) {\n this._onBindObservable.clear();\n }\n if (this._onUnBindObservable) {\n this._onUnBindObservable.clear();\n }\n if (this._onEffectCreatedObservable) {\n this._onEffectCreatedObservable.clear();\n }\n if (this._eventInfo) {\n this._eventInfo = {};\n }\n }\n /**\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n releaseVertexArrayObject(mesh, forceDisposeEffect) {\n if (mesh.geometry) {\n const geometry = mesh.geometry;\n if (this._storeEffectOnSubMeshes) {\n for (const subMesh of mesh.subMeshes) {\n geometry._releaseVertexArrayObject(subMesh.effect);\n if (forceDisposeEffect && subMesh.effect) {\n subMesh.effect.dispose();\n }\n }\n }\n else {\n geometry._releaseVertexArrayObject(this._drawWrapper.effect);\n }\n }\n }\n /**\n * Serializes this material\n * @returns the serialized material object\n */\n serialize() {\n const serializationObject = SerializationHelper.Serialize(this);\n serializationObject.stencil = this.stencil.serialize();\n serializationObject.uniqueId = this.uniqueId;\n this._serializePlugins(serializationObject);\n return serializationObject;\n }\n _serializePlugins(serializationObject) {\n serializationObject.plugins = {};\n if (this.pluginManager) {\n for (const plugin of this.pluginManager._plugins) {\n serializationObject.plugins[plugin.getClassName()] = plugin.serialize();\n }\n }\n }\n /**\n * Creates a material from parsed material data\n * @param parsedMaterial defines parsed material data\n * @param scene defines the hosting scene\n * @param rootUrl defines the root URL to use to load textures\n * @returns a new material\n */\n static Parse(parsedMaterial, scene, rootUrl) {\n if (!parsedMaterial.customType) {\n parsedMaterial.customType = \"BABYLON.StandardMaterial\";\n }\n else if (parsedMaterial.customType === \"BABYLON.PBRMaterial\" && parsedMaterial.overloadedAlbedo) {\n parsedMaterial.customType = \"BABYLON.LegacyPBRMaterial\";\n if (!BABYLON.LegacyPBRMaterial) {\n Logger.Error(\"Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.\");\n return null;\n }\n }\n const materialType = Tools.Instantiate(parsedMaterial.customType);\n const material = materialType.Parse(parsedMaterial, scene, rootUrl);\n material._loadedUniqueId = parsedMaterial.uniqueId;\n return material;\n }\n static _parsePlugins(serializationObject, material, scene, rootUrl) {\n var _a;\n if (!serializationObject.plugins) {\n return;\n }\n for (const pluginClassName in serializationObject.plugins) {\n const pluginData = serializationObject.plugins[pluginClassName];\n let plugin = (_a = material.pluginManager) === null || _a === void 0 ? void 0 : _a.getPlugin(pluginData.name);\n if (!plugin) {\n const pluginClassType = Tools.Instantiate(\"BABYLON.\" + pluginClassName);\n if (pluginClassType) {\n plugin = new pluginClassType(material);\n }\n }\n plugin === null || plugin === void 0 ? void 0 : plugin.parse(pluginData, scene, rootUrl);\n }\n }\n}\n/**\n * Returns the triangle fill mode\n */\nMaterial.TriangleFillMode = 0;\n/**\n * Returns the wireframe mode\n */\nMaterial.WireFrameFillMode = 1;\n/**\n * Returns the point fill mode\n */\nMaterial.PointFillMode = 2;\n/**\n * Returns the point list draw mode\n */\nMaterial.PointListDrawMode = 3;\n/**\n * Returns the line list draw mode\n */\nMaterial.LineListDrawMode = 4;\n/**\n * Returns the line loop draw mode\n */\nMaterial.LineLoopDrawMode = 5;\n/**\n * Returns the line strip draw mode\n */\nMaterial.LineStripDrawMode = 6;\n/**\n * Returns the triangle strip draw mode\n */\nMaterial.TriangleStripDrawMode = 7;\n/**\n * Returns the triangle fan draw mode\n */\nMaterial.TriangleFanDrawMode = 8;\n/**\n * Stores the clock-wise side orientation\n */\nMaterial.ClockWiseSideOrientation = 0;\n/**\n * Stores the counter clock-wise side orientation\n */\nMaterial.CounterClockWiseSideOrientation = 1;\n/**\n * The dirty texture flag value\n */\nMaterial.TextureDirtyFlag = 1;\n/**\n * The dirty light flag value\n */\nMaterial.LightDirtyFlag = 2;\n/**\n * The dirty fresnel flag value\n */\nMaterial.FresnelDirtyFlag = 4;\n/**\n * The dirty attribute flag value\n */\nMaterial.AttributesDirtyFlag = 8;\n/**\n * The dirty misc flag value\n */\nMaterial.MiscDirtyFlag = 16;\n/**\n * The dirty prepass flag value\n */\nMaterial.PrePassDirtyFlag = 32;\n/**\n * The all dirty flag value\n */\nMaterial.AllDirtyFlag = 63;\n/**\n * MaterialTransparencyMode: No transparency mode, Alpha channel is not use.\n */\nMaterial.MATERIAL_OPAQUE = 0;\n/**\n * MaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.\n */\nMaterial.MATERIAL_ALPHATEST = 1;\n/**\n * MaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.\n */\nMaterial.MATERIAL_ALPHABLEND = 2;\n/**\n * MaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.\n * They are also discarded below the alpha cutoff threshold to improve performances.\n */\nMaterial.MATERIAL_ALPHATESTANDBLEND = 3;\n/**\n * The Whiteout method is used to blend normals.\n * Details of the algorithm can be found here: https://blog.selfshadow.com/publications/blending-in-detail/\n */\nMaterial.MATERIAL_NORMALBLENDMETHOD_WHITEOUT = 0;\n/**\n * The Reoriented Normal Mapping method is used to blend normals.\n * Details of the algorithm can be found here: https://blog.selfshadow.com/publications/blending-in-detail/\n */\nMaterial.MATERIAL_NORMALBLENDMETHOD_RNM = 1;\n/**\n * Event observable which raises global events common to all materials (like MaterialPluginEvent.Created)\n */\nMaterial.OnEventObservable = new Observable();\nMaterial._AllDirtyCallBack = (defines) => defines.markAllAsDirty();\nMaterial._ImageProcessingDirtyCallBack = (defines) => defines.markAsImageProcessingDirty();\nMaterial._TextureDirtyCallBack = (defines) => defines.markAsTexturesDirty();\nMaterial._FresnelDirtyCallBack = (defines) => defines.markAsFresnelDirty();\nMaterial._MiscDirtyCallBack = (defines) => defines.markAsMiscDirty();\nMaterial._PrePassDirtyCallBack = (defines) => defines.markAsPrePassDirty();\nMaterial._LightsDirtyCallBack = (defines) => defines.markAsLightDirty();\nMaterial._AttributeDirtyCallBack = (defines) => defines.markAsAttributesDirty();\nMaterial._FresnelAndMiscDirtyCallBack = (defines) => {\n Material._FresnelDirtyCallBack(defines);\n Material._MiscDirtyCallBack(defines);\n};\nMaterial._TextureAndMiscDirtyCallBack = (defines) => {\n Material._TextureDirtyCallBack(defines);\n Material._MiscDirtyCallBack(defines);\n};\nMaterial._DirtyCallbackArray = [];\nMaterial._RunDirtyCallBacks = (defines) => {\n for (const cb of Material._DirtyCallbackArray) {\n cb(defines);\n }\n};\n__decorate([\n serialize()\n], Material.prototype, \"id\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"uniqueId\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"name\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"metadata\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"checkReadyOnEveryCall\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"checkReadyOnlyOnce\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"state\", void 0);\n__decorate([\n serialize(\"alpha\")\n], Material.prototype, \"_alpha\", void 0);\n__decorate([\n serialize(\"backFaceCulling\")\n], Material.prototype, \"_backFaceCulling\", void 0);\n__decorate([\n serialize(\"cullBackFaces\")\n], Material.prototype, \"_cullBackFaces\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"sideOrientation\", void 0);\n__decorate([\n serialize(\"alphaMode\")\n], Material.prototype, \"_alphaMode\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"_needDepthPrePass\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"disableDepthWrite\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"disableColorWrite\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"forceDepthWrite\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"depthFunction\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"separateCullingPass\", void 0);\n__decorate([\n serialize(\"fogEnabled\")\n], Material.prototype, \"_fogEnabled\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"pointSize\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"zOffset\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"zOffsetUnits\", void 0);\n__decorate([\n serialize()\n], Material.prototype, \"pointsCloud\", null);\n__decorate([\n serialize()\n], Material.prototype, \"fillMode\", null);\n__decorate([\n serialize()\n], Material.prototype, \"transparencyMode\", null);\n//# sourceMappingURL=material.js.map","/**\n * Manages the defines for the Material\n */\nexport class MaterialDefines {\n /**\n * Creates a new instance\n * @param externalProperties list of external properties to inject into the object\n */\n constructor(externalProperties) {\n /** @internal */\n this._keys = [];\n this._isDirty = true;\n /** @internal */\n this._areLightsDirty = true;\n /** @internal */\n this._areLightsDisposed = false;\n /** @internal */\n this._areAttributesDirty = true;\n /** @internal */\n this._areTexturesDirty = true;\n /** @internal */\n this._areFresnelDirty = true;\n /** @internal */\n this._areMiscDirty = true;\n /** @internal */\n this._arePrePassDirty = true;\n /** @internal */\n this._areImageProcessingDirty = true;\n /** @internal */\n this._normals = false;\n /** @internal */\n this._uvs = false;\n /** @internal */\n this._needNormals = false;\n /** @internal */\n this._needUVs = false;\n this._externalProperties = externalProperties;\n // Initialize External Properties\n if (externalProperties) {\n for (const prop in externalProperties) {\n if (Object.prototype.hasOwnProperty.call(externalProperties, prop)) {\n this._setDefaultValue(prop);\n }\n }\n }\n }\n /**\n * Specifies if the material needs to be re-calculated\n */\n get isDirty() {\n return this._isDirty;\n }\n /**\n * Marks the material to indicate that it has been re-calculated\n */\n markAsProcessed() {\n this._isDirty = false;\n this._areAttributesDirty = false;\n this._areTexturesDirty = false;\n this._areFresnelDirty = false;\n this._areLightsDirty = false;\n this._areLightsDisposed = false;\n this._areMiscDirty = false;\n this._arePrePassDirty = false;\n this._areImageProcessingDirty = false;\n }\n /**\n * Marks the material to indicate that it needs to be re-calculated\n */\n markAsUnprocessed() {\n this._isDirty = true;\n }\n /**\n * Marks the material to indicate all of its defines need to be re-calculated\n */\n markAllAsDirty() {\n this._areTexturesDirty = true;\n this._areAttributesDirty = true;\n this._areLightsDirty = true;\n this._areFresnelDirty = true;\n this._areMiscDirty = true;\n this._arePrePassDirty = false;\n this._areImageProcessingDirty = true;\n this._isDirty = true;\n }\n /**\n * Marks the material to indicate that image processing needs to be re-calculated\n */\n markAsImageProcessingDirty() {\n this._areImageProcessingDirty = true;\n this._isDirty = true;\n }\n /**\n * Marks the material to indicate the lights need to be re-calculated\n * @param disposed Defines whether the light is dirty due to dispose or not\n */\n markAsLightDirty(disposed = false) {\n this._areLightsDirty = true;\n this._areLightsDisposed = this._areLightsDisposed || disposed;\n this._isDirty = true;\n }\n /**\n * Marks the attribute state as changed\n */\n markAsAttributesDirty() {\n this._areAttributesDirty = true;\n this._isDirty = true;\n }\n /**\n * Marks the texture state as changed\n */\n markAsTexturesDirty() {\n this._areTexturesDirty = true;\n this._isDirty = true;\n }\n /**\n * Marks the fresnel state as changed\n */\n markAsFresnelDirty() {\n this._areFresnelDirty = true;\n this._isDirty = true;\n }\n /**\n * Marks the misc state as changed\n */\n markAsMiscDirty() {\n this._areMiscDirty = true;\n this._isDirty = true;\n }\n /**\n * Marks the prepass state as changed\n */\n markAsPrePassDirty() {\n this._arePrePassDirty = true;\n this._isDirty = true;\n }\n /**\n * Rebuilds the material defines\n */\n rebuild() {\n this._keys.length = 0;\n for (const key of Object.keys(this)) {\n if (key[0] === \"_\") {\n continue;\n }\n this._keys.push(key);\n }\n if (this._externalProperties) {\n for (const name in this._externalProperties) {\n if (this._keys.indexOf(name) === -1) {\n this._keys.push(name);\n }\n }\n }\n }\n /**\n * Specifies if two material defines are equal\n * @param other - A material define instance to compare to\n * @returns - Boolean indicating if the material defines are equal (true) or not (false)\n */\n isEqual(other) {\n if (this._keys.length !== other._keys.length) {\n return false;\n }\n for (let index = 0; index < this._keys.length; index++) {\n const prop = this._keys[index];\n if (this[prop] !== other[prop]) {\n return false;\n }\n }\n return true;\n }\n /**\n * Clones this instance's defines to another instance\n * @param other - material defines to clone values to\n */\n cloneTo(other) {\n if (this._keys.length !== other._keys.length) {\n other._keys = this._keys.slice(0);\n }\n for (let index = 0; index < this._keys.length; index++) {\n const prop = this._keys[index];\n other[prop] = this[prop];\n }\n }\n /**\n * Resets the material define values\n */\n reset() {\n this._keys.forEach((prop) => this._setDefaultValue(prop));\n }\n _setDefaultValue(prop) {\n var _a, _b, _c, _d, _e;\n const type = (_c = (_b = (_a = this._externalProperties) === null || _a === void 0 ? void 0 : _a[prop]) === null || _b === void 0 ? void 0 : _b.type) !== null && _c !== void 0 ? _c : typeof this[prop];\n const defValue = (_e = (_d = this._externalProperties) === null || _d === void 0 ? void 0 : _d[prop]) === null || _e === void 0 ? void 0 : _e.default;\n switch (type) {\n case \"number\":\n this[prop] = defValue !== null && defValue !== void 0 ? defValue : 0;\n break;\n case \"string\":\n this[prop] = defValue !== null && defValue !== void 0 ? defValue : \"\";\n break;\n default:\n this[prop] = defValue !== null && defValue !== void 0 ? defValue : false;\n break;\n }\n }\n /**\n * Converts the material define values to a string\n * @returns - String of material define information\n */\n toString() {\n let result = \"\";\n for (let index = 0; index < this._keys.length; index++) {\n const prop = this._keys[index];\n const value = this[prop];\n const type = typeof value;\n switch (type) {\n case \"number\":\n case \"string\":\n result += \"#define \" + prop + \" \" + value + \"\\n\";\n break;\n default:\n if (value) {\n result += \"#define \" + prop + \"\\n\";\n }\n break;\n }\n }\n return result;\n }\n}\n//# sourceMappingURL=materialDefines.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { Camera } from \"../Cameras/camera.js\";\nimport { Scene } from \"../scene.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { LightConstants } from \"../Lights/lightConstants.js\";\n\nimport { Color3 } from \"../Maths/math.color.js\";\nimport { prepareDefinesForClipPlanes } from \"./clipPlaneMaterialHelper.js\";\n/**\n * \"Static Class\" containing the most commonly used helper while dealing with material for rendering purpose.\n *\n * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.\n *\n * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.\n */\nexport class MaterialHelper {\n /**\n * Binds the scene's uniform buffer to the effect.\n * @param effect defines the effect to bind to the scene uniform buffer\n * @param sceneUbo defines the uniform buffer storing scene data\n */\n static BindSceneUniformBuffer(effect, sceneUbo) {\n sceneUbo.bindToEffect(effect, \"Scene\");\n }\n /**\n * Helps preparing the defines values about the UVs in used in the effect.\n * UVs are shared as much as we can across channels in the shaders.\n * @param texture The texture we are preparing the UVs for\n * @param defines The defines to update\n * @param key The channel key \"diffuse\", \"specular\"... used in the shader\n */\n static PrepareDefinesForMergedUV(texture, defines, key) {\n defines._needUVs = true;\n defines[key] = true;\n if (texture.optimizeUVAllocation && texture.getTextureMatrix().isIdentityAs3x2()) {\n defines[key + \"DIRECTUV\"] = texture.coordinatesIndex + 1;\n defines[\"MAINUV\" + (texture.coordinatesIndex + 1)] = true;\n }\n else {\n defines[key + \"DIRECTUV\"] = 0;\n }\n }\n /**\n * Binds a texture matrix value to its corresponding uniform\n * @param texture The texture to bind the matrix for\n * @param uniformBuffer The uniform buffer receiving the data\n * @param key The channel key \"diffuse\", \"specular\"... used in the shader\n */\n static BindTextureMatrix(texture, uniformBuffer, key) {\n const matrix = texture.getTextureMatrix();\n uniformBuffer.updateMatrix(key + \"Matrix\", matrix);\n }\n /**\n * Gets the current status of the fog (should it be enabled?)\n * @param mesh defines the mesh to evaluate for fog support\n * @param scene defines the hosting scene\n * @returns true if fog must be enabled\n */\n static GetFogState(mesh, scene) {\n return scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE;\n }\n /**\n * Helper used to prepare the list of defines associated with misc. values for shader compilation\n * @param mesh defines the current mesh\n * @param scene defines the current scene\n * @param useLogarithmicDepth defines if logarithmic depth has to be turned on\n * @param pointsCloud defines if point cloud rendering has to be turned on\n * @param fogEnabled defines if fog has to be turned on\n * @param alphaTest defines if alpha testing has to be turned on\n * @param defines defines the current list of defines\n */\n static PrepareDefinesForMisc(mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {\n if (defines._areMiscDirty) {\n defines[\"LOGARITHMICDEPTH\"] = useLogarithmicDepth;\n defines[\"POINTSIZE\"] = pointsCloud;\n defines[\"FOG\"] = fogEnabled && this.GetFogState(mesh, scene);\n defines[\"NONUNIFORMSCALING\"] = mesh.nonUniformScaling;\n defines[\"ALPHATEST\"] = alphaTest;\n }\n }\n /**\n * Helper used to prepare the defines relative to the active camera\n * @param scene defines the current scene\n * @param defines specifies the list of active defines\n * @returns true if the defines have been updated, else false\n */\n static PrepareDefinesForCamera(scene, defines) {\n let changed = false;\n if (scene.activeCamera) {\n const wasOrtho = defines[\"CAMERA_ORTHOGRAPHIC\"] ? 1 : 0;\n const wasPersp = defines[\"CAMERA_PERSPECTIVE\"] ? 1 : 0;\n const isOrtho = scene.activeCamera.mode === Camera.ORTHOGRAPHIC_CAMERA ? 1 : 0;\n const isPersp = scene.activeCamera.mode === Camera.PERSPECTIVE_CAMERA ? 1 : 0;\n if (wasOrtho ^ isOrtho || wasPersp ^ isPersp) {\n defines[\"CAMERA_ORTHOGRAPHIC\"] = isOrtho === 1;\n defines[\"CAMERA_PERSPECTIVE\"] = isPersp === 1;\n changed = true;\n }\n }\n return changed;\n }\n /**\n * Helper used to prepare the list of defines associated with frame values for shader compilation\n * @param scene defines the current scene\n * @param engine defines the current engine\n * @param material defines the material we are compiling the shader for\n * @param defines specifies the list of active defines\n * @param useInstances defines if instances have to be turned on\n * @param useClipPlane defines if clip plane have to be turned on\n * @param useThinInstances defines if thin instances have to be turned on\n */\n static PrepareDefinesForFrameBoundValues(scene, engine, material, defines, useInstances, useClipPlane = null, useThinInstances = false) {\n let changed = MaterialHelper.PrepareDefinesForCamera(scene, defines);\n if (useClipPlane !== false) {\n changed = prepareDefinesForClipPlanes(material, scene, defines);\n }\n if (defines[\"DEPTHPREPASS\"] !== !engine.getColorWrite()) {\n defines[\"DEPTHPREPASS\"] = !defines[\"DEPTHPREPASS\"];\n changed = true;\n }\n if (defines[\"INSTANCES\"] !== useInstances) {\n defines[\"INSTANCES\"] = useInstances;\n changed = true;\n }\n if (defines[\"THIN_INSTANCES\"] !== useThinInstances) {\n defines[\"THIN_INSTANCES\"] = useThinInstances;\n changed = true;\n }\n if (changed) {\n defines.markAsUnprocessed();\n }\n }\n /**\n * Prepares the defines for bones\n * @param mesh The mesh containing the geometry data we will draw\n * @param defines The defines to update\n */\n static PrepareDefinesForBones(mesh, defines) {\n if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {\n defines[\"NUM_BONE_INFLUENCERS\"] = mesh.numBoneInfluencers;\n const materialSupportsBoneTexture = defines[\"BONETEXTURE\"] !== undefined;\n if (mesh.skeleton.isUsingTextureForMatrices && materialSupportsBoneTexture) {\n defines[\"BONETEXTURE\"] = true;\n }\n else {\n defines[\"BonesPerMesh\"] = mesh.skeleton.bones.length + 1;\n defines[\"BONETEXTURE\"] = materialSupportsBoneTexture ? false : undefined;\n const prePassRenderer = mesh.getScene().prePassRenderer;\n if (prePassRenderer && prePassRenderer.enabled) {\n const nonExcluded = prePassRenderer.excludedSkinnedMesh.indexOf(mesh) === -1;\n defines[\"BONES_VELOCITY_ENABLED\"] = nonExcluded;\n }\n }\n }\n else {\n defines[\"NUM_BONE_INFLUENCERS\"] = 0;\n defines[\"BonesPerMesh\"] = 0;\n if (defines[\"BONETEXTURE\"] !== undefined) {\n defines[\"BONETEXTURE\"] = false;\n }\n }\n }\n /**\n * Prepares the defines for morph targets\n * @param mesh The mesh containing the geometry data we will draw\n * @param defines The defines to update\n */\n static PrepareDefinesForMorphTargets(mesh, defines) {\n const manager = mesh.morphTargetManager;\n if (manager) {\n defines[\"MORPHTARGETS_UV\"] = manager.supportsUVs && defines[\"UV1\"];\n defines[\"MORPHTARGETS_TANGENT\"] = manager.supportsTangents && defines[\"TANGENT\"];\n defines[\"MORPHTARGETS_NORMAL\"] = manager.supportsNormals && defines[\"NORMAL\"];\n defines[\"MORPHTARGETS\"] = manager.numInfluencers > 0;\n defines[\"NUM_MORPH_INFLUENCERS\"] = manager.numInfluencers;\n defines[\"MORPHTARGETS_TEXTURE\"] = manager.isUsingTextureForTargets;\n }\n else {\n defines[\"MORPHTARGETS_UV\"] = false;\n defines[\"MORPHTARGETS_TANGENT\"] = false;\n defines[\"MORPHTARGETS_NORMAL\"] = false;\n defines[\"MORPHTARGETS\"] = false;\n defines[\"NUM_MORPH_INFLUENCERS\"] = 0;\n }\n }\n /**\n * Prepares the defines for baked vertex animation\n * @param mesh The mesh containing the geometry data we will draw\n * @param defines The defines to update\n */\n static PrepareDefinesForBakedVertexAnimation(mesh, defines) {\n const manager = mesh.bakedVertexAnimationManager;\n defines[\"BAKED_VERTEX_ANIMATION_TEXTURE\"] = manager && manager.isEnabled ? true : false;\n }\n /**\n * Prepares the defines used in the shader depending on the attributes data available in the mesh\n * @param mesh The mesh containing the geometry data we will draw\n * @param defines The defines to update\n * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)\n * @param useBones Precise whether bones should be used or not (override mesh info)\n * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)\n * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)\n * @param useBakedVertexAnimation Precise whether baked vertex animation should be used or not (override mesh info)\n * @returns false if defines are considered not dirty and have not been checked\n */\n static PrepareDefinesForAttributes(mesh, defines, useVertexColor, useBones, useMorphTargets = false, useVertexAlpha = true, useBakedVertexAnimation = true) {\n if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {\n return false;\n }\n defines._normals = defines._needNormals;\n defines._uvs = defines._needUVs;\n defines[\"NORMAL\"] = defines._needNormals && mesh.isVerticesDataPresent(VertexBuffer.NormalKind);\n if (defines._needNormals && mesh.isVerticesDataPresent(VertexBuffer.TangentKind)) {\n defines[\"TANGENT\"] = true;\n }\n for (let i = 1; i <= 6; ++i) {\n defines[\"UV\" + i] = defines._needUVs ? mesh.isVerticesDataPresent(`uv${i === 1 ? \"\" : i}`) : false;\n }\n if (useVertexColor) {\n const hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(VertexBuffer.ColorKind);\n defines[\"VERTEXCOLOR\"] = hasVertexColors;\n defines[\"VERTEXALPHA\"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;\n }\n if (mesh.isVerticesDataPresent(VertexBuffer.ColorInstanceKind) && (mesh.hasInstances || mesh.hasThinInstances)) {\n defines[\"INSTANCESCOLOR\"] = true;\n }\n if (useBones) {\n this.PrepareDefinesForBones(mesh, defines);\n }\n if (useMorphTargets) {\n this.PrepareDefinesForMorphTargets(mesh, defines);\n }\n if (useBakedVertexAnimation) {\n this.PrepareDefinesForBakedVertexAnimation(mesh, defines);\n }\n return true;\n }\n /**\n * Prepares the defines related to multiview\n * @param scene The scene we are intending to draw\n * @param defines The defines to update\n */\n static PrepareDefinesForMultiview(scene, defines) {\n if (scene.activeCamera) {\n const previousMultiview = defines.MULTIVIEW;\n defines.MULTIVIEW = scene.activeCamera.outputRenderTarget !== null && scene.activeCamera.outputRenderTarget.getViewCount() > 1;\n if (defines.MULTIVIEW != previousMultiview) {\n defines.markAsUnprocessed();\n }\n }\n }\n /**\n * Prepares the defines related to order independant transparency\n * @param scene The scene we are intending to draw\n * @param defines The defines to update\n * @param needAlphaBlending Determines if the material needs alpha blending\n */\n static PrepareDefinesForOIT(scene, defines, needAlphaBlending) {\n const previousDefine = defines.ORDER_INDEPENDENT_TRANSPARENCY;\n const previousDefine16Bits = defines.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;\n defines.ORDER_INDEPENDENT_TRANSPARENCY = scene.useOrderIndependentTransparency && needAlphaBlending;\n defines.ORDER_INDEPENDENT_TRANSPARENCY_16BITS = !scene.getEngine().getCaps().textureFloatLinearFiltering;\n if (previousDefine !== defines.ORDER_INDEPENDENT_TRANSPARENCY || previousDefine16Bits !== defines.ORDER_INDEPENDENT_TRANSPARENCY_16BITS) {\n defines.markAsUnprocessed();\n }\n }\n /**\n * Prepares the defines related to the prepass\n * @param scene The scene we are intending to draw\n * @param defines The defines to update\n * @param canRenderToMRT Indicates if this material renders to several textures in the prepass\n */\n static PrepareDefinesForPrePass(scene, defines, canRenderToMRT) {\n const previousPrePass = defines.PREPASS;\n if (!defines._arePrePassDirty) {\n return;\n }\n const texturesList = [\n {\n type: 1,\n define: \"PREPASS_POSITION\",\n index: \"PREPASS_POSITION_INDEX\",\n },\n {\n type: 2,\n define: \"PREPASS_VELOCITY\",\n index: \"PREPASS_VELOCITY_INDEX\",\n },\n {\n type: 3,\n define: \"PREPASS_REFLECTIVITY\",\n index: \"PREPASS_REFLECTIVITY_INDEX\",\n },\n {\n type: 0,\n define: \"PREPASS_IRRADIANCE\",\n index: \"PREPASS_IRRADIANCE_INDEX\",\n },\n {\n type: 7,\n define: \"PREPASS_ALBEDO_SQRT\",\n index: \"PREPASS_ALBEDO_SQRT_INDEX\",\n },\n {\n type: 5,\n define: \"PREPASS_DEPTH\",\n index: \"PREPASS_DEPTH_INDEX\",\n },\n {\n type: 6,\n define: \"PREPASS_NORMAL\",\n index: \"PREPASS_NORMAL_INDEX\",\n },\n ];\n if (scene.prePassRenderer && scene.prePassRenderer.enabled && canRenderToMRT) {\n defines.PREPASS = true;\n defines.SCENE_MRT_COUNT = scene.prePassRenderer.mrtCount;\n for (let i = 0; i < texturesList.length; i++) {\n const index = scene.prePassRenderer.getIndex(texturesList[i].type);\n if (index !== -1) {\n defines[texturesList[i].define] = true;\n defines[texturesList[i].index] = index;\n }\n else {\n defines[texturesList[i].define] = false;\n }\n }\n }\n else {\n defines.PREPASS = false;\n for (let i = 0; i < texturesList.length; i++) {\n defines[texturesList[i].define] = false;\n }\n }\n if (defines.PREPASS != previousPrePass) {\n defines.markAsUnprocessed();\n defines.markAsImageProcessingDirty();\n }\n }\n /**\n * Prepares the defines related to the light information passed in parameter\n * @param scene The scene we are intending to draw\n * @param mesh The mesh the effect is compiling for\n * @param light The light the effect is compiling for\n * @param lightIndex The index of the light\n * @param defines The defines to update\n * @param specularSupported Specifies whether specular is supported or not (override lights data)\n * @param state Defines the current state regarding what is needed (normals, etc...)\n * @param state.needNormals\n * @param state.needRebuild\n * @param state.shadowEnabled\n * @param state.specularEnabled\n * @param state.lightmapMode\n */\n static PrepareDefinesForLight(scene, mesh, light, lightIndex, defines, specularSupported, state) {\n var _a;\n state.needNormals = true;\n if (defines[\"LIGHT\" + lightIndex] === undefined) {\n state.needRebuild = true;\n }\n defines[\"LIGHT\" + lightIndex] = true;\n defines[\"SPOTLIGHT\" + lightIndex] = false;\n defines[\"HEMILIGHT\" + lightIndex] = false;\n defines[\"POINTLIGHT\" + lightIndex] = false;\n defines[\"DIRLIGHT\" + lightIndex] = false;\n light.prepareLightSpecificDefines(defines, lightIndex);\n // FallOff.\n defines[\"LIGHT_FALLOFF_PHYSICAL\" + lightIndex] = false;\n defines[\"LIGHT_FALLOFF_GLTF\" + lightIndex] = false;\n defines[\"LIGHT_FALLOFF_STANDARD\" + lightIndex] = false;\n switch (light.falloffType) {\n case LightConstants.FALLOFF_GLTF:\n defines[\"LIGHT_FALLOFF_GLTF\" + lightIndex] = true;\n break;\n case LightConstants.FALLOFF_PHYSICAL:\n defines[\"LIGHT_FALLOFF_PHYSICAL\" + lightIndex] = true;\n break;\n case LightConstants.FALLOFF_STANDARD:\n defines[\"LIGHT_FALLOFF_STANDARD\" + lightIndex] = true;\n break;\n }\n // Specular\n if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {\n state.specularEnabled = true;\n }\n // Shadows\n defines[\"SHADOW\" + lightIndex] = false;\n defines[\"SHADOWCSM\" + lightIndex] = false;\n defines[\"SHADOWCSMDEBUG\" + lightIndex] = false;\n defines[\"SHADOWCSMNUM_CASCADES\" + lightIndex] = false;\n defines[\"SHADOWCSMUSESHADOWMAXZ\" + lightIndex] = false;\n defines[\"SHADOWCSMNOBLEND\" + lightIndex] = false;\n defines[\"SHADOWCSM_RIGHTHANDED\" + lightIndex] = false;\n defines[\"SHADOWPCF\" + lightIndex] = false;\n defines[\"SHADOWPCSS\" + lightIndex] = false;\n defines[\"SHADOWPOISSON\" + lightIndex] = false;\n defines[\"SHADOWESM\" + lightIndex] = false;\n defines[\"SHADOWCLOSEESM\" + lightIndex] = false;\n defines[\"SHADOWCUBE\" + lightIndex] = false;\n defines[\"SHADOWLOWQUALITY\" + lightIndex] = false;\n defines[\"SHADOWMEDIUMQUALITY\" + lightIndex] = false;\n if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {\n const shadowGenerator = (_a = light.getShadowGenerator(scene.activeCamera)) !== null && _a !== void 0 ? _a : light.getShadowGenerator();\n if (shadowGenerator) {\n const shadowMap = shadowGenerator.getShadowMap();\n if (shadowMap) {\n if (shadowMap.renderList && shadowMap.renderList.length > 0) {\n state.shadowEnabled = true;\n shadowGenerator.prepareDefines(defines, lightIndex);\n }\n }\n }\n }\n if (light.lightmapMode != LightConstants.LIGHTMAP_DEFAULT) {\n state.lightmapMode = true;\n defines[\"LIGHTMAPEXCLUDED\" + lightIndex] = true;\n defines[\"LIGHTMAPNOSPECULAR\" + lightIndex] = light.lightmapMode == LightConstants.LIGHTMAP_SHADOWSONLY;\n }\n else {\n defines[\"LIGHTMAPEXCLUDED\" + lightIndex] = false;\n defines[\"LIGHTMAPNOSPECULAR\" + lightIndex] = false;\n }\n }\n /**\n * Prepares the defines related to the light information passed in parameter\n * @param scene The scene we are intending to draw\n * @param mesh The mesh the effect is compiling for\n * @param defines The defines to update\n * @param specularSupported Specifies whether specular is supported or not (override lights data)\n * @param maxSimultaneousLights Specifies how manuy lights can be added to the effect at max\n * @param disableLighting Specifies whether the lighting is disabled (override scene and light)\n * @returns true if normals will be required for the rest of the effect\n */\n static PrepareDefinesForLights(scene, mesh, defines, specularSupported, maxSimultaneousLights = 4, disableLighting = false) {\n if (!defines._areLightsDirty) {\n return defines._needNormals;\n }\n let lightIndex = 0;\n const state = {\n needNormals: defines._needNormals,\n needRebuild: false,\n lightmapMode: false,\n shadowEnabled: false,\n specularEnabled: false,\n };\n if (scene.lightsEnabled && !disableLighting) {\n for (const light of mesh.lightSources) {\n this.PrepareDefinesForLight(scene, mesh, light, lightIndex, defines, specularSupported, state);\n lightIndex++;\n if (lightIndex === maxSimultaneousLights) {\n break;\n }\n }\n }\n defines[\"SPECULARTERM\"] = state.specularEnabled;\n defines[\"SHADOWS\"] = state.shadowEnabled;\n // Resetting all other lights if any\n for (let index = lightIndex; index < maxSimultaneousLights; index++) {\n if (defines[\"LIGHT\" + index] !== undefined) {\n defines[\"LIGHT\" + index] = false;\n defines[\"HEMILIGHT\" + index] = false;\n defines[\"POINTLIGHT\" + index] = false;\n defines[\"DIRLIGHT\" + index] = false;\n defines[\"SPOTLIGHT\" + index] = false;\n defines[\"SHADOW\" + index] = false;\n defines[\"SHADOWCSM\" + index] = false;\n defines[\"SHADOWCSMDEBUG\" + index] = false;\n defines[\"SHADOWCSMNUM_CASCADES\" + index] = false;\n defines[\"SHADOWCSMUSESHADOWMAXZ\" + index] = false;\n defines[\"SHADOWCSMNOBLEND\" + index] = false;\n defines[\"SHADOWCSM_RIGHTHANDED\" + index] = false;\n defines[\"SHADOWPCF\" + index] = false;\n defines[\"SHADOWPCSS\" + index] = false;\n defines[\"SHADOWPOISSON\" + index] = false;\n defines[\"SHADOWESM\" + index] = false;\n defines[\"SHADOWCLOSEESM\" + index] = false;\n defines[\"SHADOWCUBE\" + index] = false;\n defines[\"SHADOWLOWQUALITY\" + index] = false;\n defines[\"SHADOWMEDIUMQUALITY\" + index] = false;\n }\n }\n const caps = scene.getEngine().getCaps();\n if (defines[\"SHADOWFLOAT\"] === undefined) {\n state.needRebuild = true;\n }\n defines[\"SHADOWFLOAT\"] =\n state.shadowEnabled && ((caps.textureFloatRender && caps.textureFloatLinearFiltering) || (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));\n defines[\"LIGHTMAPEXCLUDED\"] = state.lightmapMode;\n if (state.needRebuild) {\n defines.rebuild();\n }\n return state.needNormals;\n }\n /**\n * Prepares the uniforms and samplers list to be used in the effect (for a specific light)\n * @param lightIndex defines the light index\n * @param uniformsList The uniform list\n * @param samplersList The sampler list\n * @param projectedLightTexture defines if projected texture must be used\n * @param uniformBuffersList defines an optional list of uniform buffers\n * @param updateOnlyBuffersList True to only update the uniformBuffersList array\n */\n static PrepareUniformsAndSamplersForLight(lightIndex, uniformsList, samplersList, projectedLightTexture, uniformBuffersList = null, updateOnlyBuffersList = false) {\n if (uniformBuffersList) {\n uniformBuffersList.push(\"Light\" + lightIndex);\n }\n if (updateOnlyBuffersList) {\n return;\n }\n uniformsList.push(\"vLightData\" + lightIndex, \"vLightDiffuse\" + lightIndex, \"vLightSpecular\" + lightIndex, \"vLightDirection\" + lightIndex, \"vLightFalloff\" + lightIndex, \"vLightGround\" + lightIndex, \"lightMatrix\" + lightIndex, \"shadowsInfo\" + lightIndex, \"depthValues\" + lightIndex);\n samplersList.push(\"shadowSampler\" + lightIndex);\n samplersList.push(\"depthSampler\" + lightIndex);\n uniformsList.push(\"viewFrustumZ\" + lightIndex, \"cascadeBlendFactor\" + lightIndex, \"lightSizeUVCorrection\" + lightIndex, \"depthCorrection\" + lightIndex, \"penumbraDarkness\" + lightIndex, \"frustumLengths\" + lightIndex);\n if (projectedLightTexture) {\n samplersList.push(\"projectionLightSampler\" + lightIndex);\n uniformsList.push(\"textureProjectionMatrix\" + lightIndex);\n }\n }\n /**\n * Prepares the uniforms and samplers list to be used in the effect\n * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the list and extra information\n * @param samplersList The sampler list\n * @param defines The defines helping in the list generation\n * @param maxSimultaneousLights The maximum number of simultaneous light allowed in the effect\n */\n static PrepareUniformsAndSamplersList(uniformsListOrOptions, samplersList, defines, maxSimultaneousLights = 4) {\n let uniformsList;\n let uniformBuffersList = null;\n if (uniformsListOrOptions.uniformsNames) {\n const options = uniformsListOrOptions;\n uniformsList = options.uniformsNames;\n uniformBuffersList = options.uniformBuffersNames;\n samplersList = options.samplers;\n defines = options.defines;\n maxSimultaneousLights = options.maxSimultaneousLights || 0;\n }\n else {\n uniformsList = uniformsListOrOptions;\n if (!samplersList) {\n samplersList = [];\n }\n }\n for (let lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {\n if (!defines[\"LIGHT\" + lightIndex]) {\n break;\n }\n this.PrepareUniformsAndSamplersForLight(lightIndex, uniformsList, samplersList, defines[\"PROJECTEDLIGHTTEXTURE\" + lightIndex], uniformBuffersList);\n }\n if (defines[\"NUM_MORPH_INFLUENCERS\"]) {\n uniformsList.push(\"morphTargetInfluences\");\n }\n if (defines[\"BAKED_VERTEX_ANIMATION_TEXTURE\"]) {\n uniformsList.push(\"bakedVertexAnimationSettings\");\n uniformsList.push(\"bakedVertexAnimationTextureSizeInverted\");\n uniformsList.push(\"bakedVertexAnimationTime\");\n samplersList.push(\"bakedVertexAnimationTexture\");\n }\n }\n /**\n * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)\n * @param defines The defines to update while falling back\n * @param fallbacks The authorized effect fallbacks\n * @param maxSimultaneousLights The maximum number of lights allowed\n * @param rank the current rank of the Effect\n * @returns The newly affected rank\n */\n static HandleFallbacksForShadows(defines, fallbacks, maxSimultaneousLights = 4, rank = 0) {\n let lightFallbackRank = 0;\n for (let lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {\n if (!defines[\"LIGHT\" + lightIndex]) {\n break;\n }\n if (lightIndex > 0) {\n lightFallbackRank = rank + lightIndex;\n fallbacks.addFallback(lightFallbackRank, \"LIGHT\" + lightIndex);\n }\n if (!defines[\"SHADOWS\"]) {\n if (defines[\"SHADOW\" + lightIndex]) {\n fallbacks.addFallback(rank, \"SHADOW\" + lightIndex);\n }\n if (defines[\"SHADOWPCF\" + lightIndex]) {\n fallbacks.addFallback(rank, \"SHADOWPCF\" + lightIndex);\n }\n if (defines[\"SHADOWPCSS\" + lightIndex]) {\n fallbacks.addFallback(rank, \"SHADOWPCSS\" + lightIndex);\n }\n if (defines[\"SHADOWPOISSON\" + lightIndex]) {\n fallbacks.addFallback(rank, \"SHADOWPOISSON\" + lightIndex);\n }\n if (defines[\"SHADOWESM\" + lightIndex]) {\n fallbacks.addFallback(rank, \"SHADOWESM\" + lightIndex);\n }\n if (defines[\"SHADOWCLOSEESM\" + lightIndex]) {\n fallbacks.addFallback(rank, \"SHADOWCLOSEESM\" + lightIndex);\n }\n }\n }\n return lightFallbackRank++;\n }\n /**\n * Prepares the list of attributes required for morph targets according to the effect defines.\n * @param attribs The current list of supported attribs\n * @param mesh The mesh to prepare the morph targets attributes for\n * @param influencers The number of influencers\n */\n static PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, influencers) {\n this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS = influencers;\n this.PrepareAttributesForMorphTargets(attribs, mesh, this._TmpMorphInfluencers);\n }\n /**\n * Prepares the list of attributes required for morph targets according to the effect defines.\n * @param attribs The current list of supported attribs\n * @param mesh The mesh to prepare the morph targets attributes for\n * @param defines The current Defines of the effect\n */\n static PrepareAttributesForMorphTargets(attribs, mesh, defines) {\n const influencers = defines[\"NUM_MORPH_INFLUENCERS\"];\n if (influencers > 0 && EngineStore.LastCreatedEngine) {\n const maxAttributesCount = EngineStore.LastCreatedEngine.getCaps().maxVertexAttribs;\n const manager = mesh.morphTargetManager;\n if (manager === null || manager === void 0 ? void 0 : manager.isUsingTextureForTargets) {\n return;\n }\n const normal = manager && manager.supportsNormals && defines[\"NORMAL\"];\n const tangent = manager && manager.supportsTangents && defines[\"TANGENT\"];\n const uv = manager && manager.supportsUVs && defines[\"UV1\"];\n for (let index = 0; index < influencers; index++) {\n attribs.push(VertexBuffer.PositionKind + index);\n if (normal) {\n attribs.push(VertexBuffer.NormalKind + index);\n }\n if (tangent) {\n attribs.push(VertexBuffer.TangentKind + index);\n }\n if (uv) {\n attribs.push(VertexBuffer.UVKind + \"_\" + index);\n }\n if (attribs.length > maxAttributesCount) {\n Logger.Error(\"Cannot add more vertex attributes for mesh \" + mesh.name);\n }\n }\n }\n }\n /**\n * Prepares the list of attributes required for baked vertex animations according to the effect defines.\n * @param attribs The current list of supported attribs\n * @param mesh The mesh to prepare the morph targets attributes for\n * @param defines The current Defines of the effect\n */\n static PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines) {\n const enabled = defines[\"BAKED_VERTEX_ANIMATION_TEXTURE\"] && defines[\"INSTANCES\"];\n if (enabled) {\n attribs.push(\"bakedVertexAnimationSettingsInstanced\");\n }\n }\n /**\n * Prepares the list of attributes required for bones according to the effect defines.\n * @param attribs The current list of supported attribs\n * @param mesh The mesh to prepare the bones attributes for\n * @param defines The current Defines of the effect\n * @param fallbacks The current effect fallback strategy\n */\n static PrepareAttributesForBones(attribs, mesh, defines, fallbacks) {\n if (defines[\"NUM_BONE_INFLUENCERS\"] > 0) {\n fallbacks.addCPUSkinningFallback(0, mesh);\n attribs.push(VertexBuffer.MatricesIndicesKind);\n attribs.push(VertexBuffer.MatricesWeightsKind);\n if (defines[\"NUM_BONE_INFLUENCERS\"] > 4) {\n attribs.push(VertexBuffer.MatricesIndicesExtraKind);\n attribs.push(VertexBuffer.MatricesWeightsExtraKind);\n }\n }\n }\n /**\n * Check and prepare the list of attributes required for instances according to the effect defines.\n * @param attribs The current list of supported attribs\n * @param defines The current MaterialDefines of the effect\n */\n static PrepareAttributesForInstances(attribs, defines) {\n if (defines[\"INSTANCES\"] || defines[\"THIN_INSTANCES\"]) {\n this.PushAttributesForInstances(attribs, !!defines[\"PREPASS_VELOCITY\"]);\n }\n if (defines.INSTANCESCOLOR) {\n attribs.push(VertexBuffer.ColorInstanceKind);\n }\n }\n /**\n * Add the list of attributes required for instances to the attribs array.\n * @param attribs The current list of supported attribs\n * @param needsPreviousMatrices If the shader needs previous matrices\n */\n static PushAttributesForInstances(attribs, needsPreviousMatrices = false) {\n attribs.push(\"world0\");\n attribs.push(\"world1\");\n attribs.push(\"world2\");\n attribs.push(\"world3\");\n if (needsPreviousMatrices) {\n attribs.push(\"previousWorld0\");\n attribs.push(\"previousWorld1\");\n attribs.push(\"previousWorld2\");\n attribs.push(\"previousWorld3\");\n }\n }\n /**\n * Binds the light information to the effect.\n * @param light The light containing the generator\n * @param effect The effect we are binding the data to\n * @param lightIndex The light index in the effect used to render\n */\n static BindLightProperties(light, effect, lightIndex) {\n light.transferToEffect(effect, lightIndex + \"\");\n }\n /**\n * Binds the lights information from the scene to the effect for the given mesh.\n * @param light Light to bind\n * @param lightIndex Light index\n * @param scene The scene where the light belongs to\n * @param effect The effect we are binding the data to\n * @param useSpecular Defines if specular is supported\n * @param receiveShadows Defines if the effect (mesh) we bind the light for receives shadows\n */\n static BindLight(light, lightIndex, scene, effect, useSpecular, receiveShadows = true) {\n light._bindLight(lightIndex, scene, effect, useSpecular, receiveShadows);\n }\n /**\n * Binds the lights information from the scene to the effect for the given mesh.\n * @param scene The scene the lights belongs to\n * @param mesh The mesh we are binding the information to render\n * @param effect The effect we are binding the data to\n * @param defines The generated defines for the effect\n * @param maxSimultaneousLights The maximum number of light that can be bound to the effect\n */\n static BindLights(scene, mesh, effect, defines, maxSimultaneousLights = 4) {\n const len = Math.min(mesh.lightSources.length, maxSimultaneousLights);\n for (let i = 0; i < len; i++) {\n const light = mesh.lightSources[i];\n this.BindLight(light, i, scene, effect, typeof defines === \"boolean\" ? defines : defines[\"SPECULARTERM\"], mesh.receiveShadows);\n }\n }\n /**\n * Binds the fog information from the scene to the effect for the given mesh.\n * @param scene The scene the lights belongs to\n * @param mesh The mesh we are binding the information to render\n * @param effect The effect we are binding the data to\n * @param linearSpace Defines if the fog effect is applied in linear space\n */\n static BindFogParameters(scene, mesh, effect, linearSpace = false) {\n if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) {\n effect.setFloat4(\"vFogInfos\", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);\n // Convert fog color to linear space if used in a linear space computed shader.\n if (linearSpace) {\n scene.fogColor.toLinearSpaceToRef(this._TempFogColor, scene.getEngine().useExactSrgbConversions);\n effect.setColor3(\"vFogColor\", this._TempFogColor);\n }\n else {\n effect.setColor3(\"vFogColor\", scene.fogColor);\n }\n }\n }\n /**\n * Binds the bones information from the mesh to the effect.\n * @param mesh The mesh we are binding the information to render\n * @param effect The effect we are binding the data to\n * @param prePassConfiguration Configuration for the prepass, in case prepass is activated\n */\n static BindBonesParameters(mesh, effect, prePassConfiguration) {\n if (!effect || !mesh) {\n return;\n }\n if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {\n mesh.computeBonesUsingShaders = false;\n }\n if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {\n const skeleton = mesh.skeleton;\n if (skeleton.isUsingTextureForMatrices && effect.getUniformIndex(\"boneTextureWidth\") > -1) {\n const boneTexture = skeleton.getTransformMatrixTexture(mesh);\n effect.setTexture(\"boneSampler\", boneTexture);\n effect.setFloat(\"boneTextureWidth\", 4.0 * (skeleton.bones.length + 1));\n }\n else {\n const matrices = skeleton.getTransformMatrices(mesh);\n if (matrices) {\n effect.setMatrices(\"mBones\", matrices);\n if (prePassConfiguration && mesh.getScene().prePassRenderer && mesh.getScene().prePassRenderer.getIndex(2)) {\n if (!prePassConfiguration.previousBones[mesh.uniqueId]) {\n prePassConfiguration.previousBones[mesh.uniqueId] = matrices.slice();\n }\n effect.setMatrices(\"mPreviousBones\", prePassConfiguration.previousBones[mesh.uniqueId]);\n MaterialHelper._CopyBonesTransformationMatrices(matrices, prePassConfiguration.previousBones[mesh.uniqueId]);\n }\n }\n }\n }\n }\n // Copies the bones transformation matrices into the target array and returns the target's reference\n static _CopyBonesTransformationMatrices(source, target) {\n target.set(source);\n return target;\n }\n /**\n * Binds the morph targets information from the mesh to the effect.\n * @param abstractMesh The mesh we are binding the information to render\n * @param effect The effect we are binding the data to\n */\n static BindMorphTargetParameters(abstractMesh, effect) {\n const manager = abstractMesh.morphTargetManager;\n if (!abstractMesh || !manager) {\n return;\n }\n effect.setFloatArray(\"morphTargetInfluences\", manager.influences);\n }\n /**\n * Binds the logarithmic depth information from the scene to the effect for the given defines.\n * @param defines The generated defines used in the effect\n * @param effect The effect we are binding the data to\n * @param scene The scene we are willing to render with logarithmic scale for\n */\n static BindLogDepth(defines, effect, scene) {\n if (!defines || defines[\"LOGARITHMICDEPTH\"] || (defines.indexOf && defines.indexOf(\"LOGARITHMICDEPTH\") >= 0)) {\n const camera = scene.activeCamera;\n if (camera.mode === Camera.ORTHOGRAPHIC_CAMERA) {\n Logger.Error(\"Logarithmic depth is not compatible with orthographic cameras!\", 20);\n }\n effect.setFloat(\"logarithmicDepthConstant\", 2.0 / (Math.log(camera.maxZ + 1.0) / Math.LN2));\n }\n }\n}\n// eslint-disable-next-line @typescript-eslint/naming-convention\nMaterialHelper._TmpMorphInfluencers = { NUM_MORPH_INFLUENCERS: 0 };\nMaterialHelper._TempFogColor = Color3.Black();\n//# sourceMappingURL=materialHelper.js.map","/**\n * @internal\n */\nexport var MaterialPluginEvent;\n(function (MaterialPluginEvent) {\n MaterialPluginEvent[MaterialPluginEvent[\"Created\"] = 1] = \"Created\";\n MaterialPluginEvent[MaterialPluginEvent[\"Disposed\"] = 2] = \"Disposed\";\n MaterialPluginEvent[MaterialPluginEvent[\"GetDefineNames\"] = 4] = \"GetDefineNames\";\n MaterialPluginEvent[MaterialPluginEvent[\"PrepareUniformBuffer\"] = 8] = \"PrepareUniformBuffer\";\n MaterialPluginEvent[MaterialPluginEvent[\"IsReadyForSubMesh\"] = 16] = \"IsReadyForSubMesh\";\n MaterialPluginEvent[MaterialPluginEvent[\"PrepareDefines\"] = 32] = \"PrepareDefines\";\n MaterialPluginEvent[MaterialPluginEvent[\"BindForSubMesh\"] = 64] = \"BindForSubMesh\";\n MaterialPluginEvent[MaterialPluginEvent[\"PrepareEffect\"] = 128] = \"PrepareEffect\";\n MaterialPluginEvent[MaterialPluginEvent[\"GetAnimatables\"] = 256] = \"GetAnimatables\";\n MaterialPluginEvent[MaterialPluginEvent[\"GetActiveTextures\"] = 512] = \"GetActiveTextures\";\n MaterialPluginEvent[MaterialPluginEvent[\"HasTexture\"] = 1024] = \"HasTexture\";\n MaterialPluginEvent[MaterialPluginEvent[\"FillRenderTargetTextures\"] = 2048] = \"FillRenderTargetTextures\";\n MaterialPluginEvent[MaterialPluginEvent[\"HasRenderTargetTextures\"] = 4096] = \"HasRenderTargetTextures\";\n MaterialPluginEvent[MaterialPluginEvent[\"HardBindForSubMesh\"] = 8192] = \"HardBindForSubMesh\";\n})(MaterialPluginEvent || (MaterialPluginEvent = {}));\n//# sourceMappingURL=materialPluginEvent.js.map","import { Material } from \"../Materials/material.js\";\nimport { Tags } from \"../Misc/tags.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\n/**\n * A multi-material is used to apply different materials to different parts of the same object without the need of\n * separate meshes. This can be use to improve performances.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/multiMaterials\n */\nexport class MultiMaterial extends Material {\n /**\n * Gets or Sets the list of Materials used within the multi material.\n * They need to be ordered according to the submeshes order in the associated mesh\n */\n get subMaterials() {\n return this._subMaterials;\n }\n set subMaterials(value) {\n this._subMaterials = value;\n this._hookArray(value);\n }\n /**\n * Function used to align with Node.getChildren()\n * @returns the list of Materials used within the multi material\n */\n getChildren() {\n return this.subMaterials;\n }\n /**\n * Instantiates a new Multi Material\n * A multi-material is used to apply different materials to different parts of the same object without the need of\n * separate meshes. This can be use to improve performances.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/multiMaterials\n * @param name Define the name in the scene\n * @param scene Define the scene the material belongs to\n */\n constructor(name, scene) {\n super(name, scene, true);\n /** @internal */\n this._waitingSubMaterialsUniqueIds = [];\n this.getScene().addMultiMaterial(this);\n this.subMaterials = new Array();\n this._storeEffectOnSubMeshes = true; // multimaterial is considered like a push material\n }\n _hookArray(array) {\n const oldPush = array.push;\n array.push = (...items) => {\n const result = oldPush.apply(array, items);\n this._markAllSubMeshesAsTexturesDirty();\n return result;\n };\n const oldSplice = array.splice;\n array.splice = (index, deleteCount) => {\n const deleted = oldSplice.apply(array, [index, deleteCount]);\n this._markAllSubMeshesAsTexturesDirty();\n return deleted;\n };\n }\n /**\n * Get one of the submaterial by its index in the submaterials array\n * @param index The index to look the sub material at\n * @returns The Material if the index has been defined\n */\n getSubMaterial(index) {\n if (index < 0 || index >= this.subMaterials.length) {\n return this.getScene().defaultMaterial;\n }\n return this.subMaterials[index];\n }\n /**\n * Get the list of active textures for the whole sub materials list.\n * @returns All the textures that will be used during the rendering\n */\n getActiveTextures() {\n return super.getActiveTextures().concat(...this.subMaterials.map((subMaterial) => {\n if (subMaterial) {\n return subMaterial.getActiveTextures();\n }\n else {\n return [];\n }\n }));\n }\n /**\n * Specifies if any sub-materials of this multi-material use a given texture.\n * @param texture Defines the texture to check against this multi-material's sub-materials.\n * @returns A boolean specifying if any sub-material of this multi-material uses the texture.\n */\n hasTexture(texture) {\n var _a;\n if (super.hasTexture(texture)) {\n return true;\n }\n for (let i = 0; i < this.subMaterials.length; i++) {\n if ((_a = this.subMaterials[i]) === null || _a === void 0 ? void 0 : _a.hasTexture(texture)) {\n return true;\n }\n }\n return false;\n }\n /**\n * Gets the current class name of the material e.g. \"MultiMaterial\"\n * Mainly use in serialization.\n * @returns the class name\n */\n getClassName() {\n return \"MultiMaterial\";\n }\n /**\n * Checks if the material is ready to render the requested sub mesh\n * @param mesh Define the mesh the submesh belongs to\n * @param subMesh Define the sub mesh to look readiness for\n * @param useInstances Define whether or not the material is used with instances\n * @returns true if ready, otherwise false\n */\n isReadyForSubMesh(mesh, subMesh, useInstances) {\n for (let index = 0; index < this.subMaterials.length; index++) {\n const subMaterial = this.subMaterials[index];\n if (subMaterial) {\n if (subMaterial._storeEffectOnSubMeshes) {\n if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {\n return false;\n }\n continue;\n }\n if (!subMaterial.isReady(mesh)) {\n return false;\n }\n }\n }\n return true;\n }\n /**\n * Clones the current material and its related sub materials\n * @param name Define the name of the newly cloned material\n * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance\n * @returns the cloned material\n */\n clone(name, cloneChildren) {\n const newMultiMaterial = new MultiMaterial(name, this.getScene());\n for (let index = 0; index < this.subMaterials.length; index++) {\n let subMaterial = null;\n const current = this.subMaterials[index];\n if (cloneChildren && current) {\n subMaterial = current.clone(name + \"-\" + current.name);\n }\n else {\n subMaterial = this.subMaterials[index];\n }\n newMultiMaterial.subMaterials.push(subMaterial);\n }\n return newMultiMaterial;\n }\n /**\n * Serializes the materials into a JSON representation.\n * @returns the JSON representation\n */\n serialize() {\n const serializationObject = {};\n serializationObject.name = this.name;\n serializationObject.id = this.id;\n serializationObject.uniqueId = this.uniqueId;\n if (Tags) {\n serializationObject.tags = Tags.GetTags(this);\n }\n serializationObject.materialsUniqueIds = [];\n serializationObject.materials = [];\n for (let matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {\n const subMat = this.subMaterials[matIndex];\n if (subMat) {\n serializationObject.materialsUniqueIds.push(subMat.uniqueId);\n serializationObject.materials.push(subMat.id);\n }\n else {\n serializationObject.materialsUniqueIds.push(null);\n serializationObject.materials.push(null);\n }\n }\n return serializationObject;\n }\n /**\n * Dispose the material and release its associated resources\n * @param forceDisposeEffect Define if we want to force disposing the associated effect (if false the shader is not released and could be reuse later on)\n * @param forceDisposeTextures Define if we want to force disposing the associated textures (if false, they will not be disposed and can still be use elsewhere in the app)\n * @param forceDisposeChildren Define if we want to force disposing the associated submaterials (if false, they will not be disposed and can still be use elsewhere in the app)\n */\n dispose(forceDisposeEffect, forceDisposeTextures, forceDisposeChildren) {\n const scene = this.getScene();\n if (!scene) {\n return;\n }\n if (forceDisposeChildren) {\n for (let index = 0; index < this.subMaterials.length; index++) {\n const subMaterial = this.subMaterials[index];\n if (subMaterial) {\n subMaterial.dispose(forceDisposeEffect, forceDisposeTextures);\n }\n }\n }\n const index = scene.multiMaterials.indexOf(this);\n if (index >= 0) {\n scene.multiMaterials.splice(index, 1);\n }\n super.dispose(forceDisposeEffect, forceDisposeTextures);\n }\n /**\n * Creates a MultiMaterial from parsed MultiMaterial data.\n * @param parsedMultiMaterial defines parsed MultiMaterial data.\n * @param scene defines the hosting scene\n * @returns a new MultiMaterial\n */\n static ParseMultiMaterial(parsedMultiMaterial, scene) {\n const multiMaterial = new MultiMaterial(parsedMultiMaterial.name, scene);\n multiMaterial.id = parsedMultiMaterial.id;\n multiMaterial._loadedUniqueId = parsedMultiMaterial.uniqueId;\n if (Tags) {\n Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);\n }\n if (parsedMultiMaterial.materialsUniqueIds) {\n multiMaterial._waitingSubMaterialsUniqueIds = parsedMultiMaterial.materialsUniqueIds;\n }\n else {\n parsedMultiMaterial.materials.forEach((subMatId) => multiMaterial.subMaterials.push(scene.getLastMaterialById(subMatId)));\n }\n return multiMaterial;\n }\n}\nRegisterClass(\"BABYLON.MultiMaterial\", MultiMaterial);\n//# sourceMappingURL=multiMaterial.js.map","/**\n * Language of the shader code\n */\nexport var ShaderLanguage;\n(function (ShaderLanguage) {\n /** language is GLSL (used by WebGL) */\n ShaderLanguage[ShaderLanguage[\"GLSL\"] = 0] = \"GLSL\";\n /** language is WGSL (used by WebGPU) */\n ShaderLanguage[ShaderLanguage[\"WGSL\"] = 1] = \"WGSL\";\n})(ShaderLanguage || (ShaderLanguage = {}));\n//# sourceMappingURL=shaderLanguage.js.map","import { Logger } from \"../Misc/logger.js\";\nimport { Tools } from \"../Misc/tools.js\";\nimport \"../Engines/Extensions/engine.uniformBuffer.js\";\n/**\n * Uniform buffer objects.\n *\n * Handles blocks of uniform on the GPU.\n *\n * If WebGL 2 is not available, this class falls back on traditional setUniformXXX calls.\n *\n * For more information, please refer to :\n * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object\n */\nexport class UniformBuffer {\n /**\n * Instantiates a new Uniform buffer objects.\n *\n * Handles blocks of uniform on the GPU.\n *\n * If WebGL 2 is not available, this class falls back on traditional setUniformXXX calls.\n *\n * For more information, please refer to :\n * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object\n * @param engine Define the engine the buffer is associated with\n * @param data Define the data contained in the buffer\n * @param dynamic Define if the buffer is updatable\n * @param name to assign to the buffer (debugging purpose)\n * @param forceNoUniformBuffer define that this object must not rely on UBO objects\n */\n constructor(engine, data, dynamic, name, forceNoUniformBuffer = false) {\n // Matrix cache\n this._valueCache = {};\n this._engine = engine;\n this._noUBO = !engine.supportsUniformBuffers || forceNoUniformBuffer;\n this._dynamic = dynamic;\n this._name = name !== null && name !== void 0 ? name : \"no-name\";\n this._data = data || [];\n this._uniformLocations = {};\n this._uniformSizes = {};\n this._uniformArraySizes = {};\n this._uniformLocationPointer = 0;\n this._needSync = false;\n if (this._engine._features.trackUbosInFrame) {\n this._buffers = [];\n this._bufferIndex = -1;\n this._createBufferOnWrite = false;\n this._currentFrameId = 0;\n }\n if (this._noUBO) {\n this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;\n this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;\n this.updateFloat = this._updateFloatForEffect;\n this.updateFloat2 = this._updateFloat2ForEffect;\n this.updateFloat3 = this._updateFloat3ForEffect;\n this.updateFloat4 = this._updateFloat4ForEffect;\n this.updateFloatArray = this._updateFloatArrayForEffect;\n this.updateArray = this._updateArrayForEffect;\n this.updateIntArray = this._updateIntArrayForEffect;\n this.updateUIntArray = this._updateUIntArrayForEffect;\n this.updateMatrix = this._updateMatrixForEffect;\n this.updateMatrices = this._updateMatricesForEffect;\n this.updateVector3 = this._updateVector3ForEffect;\n this.updateVector4 = this._updateVector4ForEffect;\n this.updateColor3 = this._updateColor3ForEffect;\n this.updateColor4 = this._updateColor4ForEffect;\n this.updateDirectColor4 = this._updateDirectColor4ForEffect;\n this.updateInt = this._updateIntForEffect;\n this.updateInt2 = this._updateInt2ForEffect;\n this.updateInt3 = this._updateInt3ForEffect;\n this.updateInt4 = this._updateInt4ForEffect;\n this.updateUInt = this._updateUIntForEffect;\n this.updateUInt2 = this._updateUInt2ForEffect;\n this.updateUInt3 = this._updateUInt3ForEffect;\n this.updateUInt4 = this._updateUInt4ForEffect;\n }\n else {\n this._engine._uniformBuffers.push(this);\n this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;\n this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;\n this.updateFloat = this._updateFloatForUniform;\n this.updateFloat2 = this._updateFloat2ForUniform;\n this.updateFloat3 = this._updateFloat3ForUniform;\n this.updateFloat4 = this._updateFloat4ForUniform;\n this.updateFloatArray = this._updateFloatArrayForUniform;\n this.updateArray = this._updateArrayForUniform;\n this.updateIntArray = this._updateIntArrayForUniform;\n this.updateUIntArray = this._updateUIntArrayForUniform;\n this.updateMatrix = this._updateMatrixForUniform;\n this.updateMatrices = this._updateMatricesForUniform;\n this.updateVector3 = this._updateVector3ForUniform;\n this.updateVector4 = this._updateVector4ForUniform;\n this.updateColor3 = this._updateColor3ForUniform;\n this.updateColor4 = this._updateColor4ForUniform;\n this.updateDirectColor4 = this._updateDirectColor4ForUniform;\n this.updateInt = this._updateIntForUniform;\n this.updateInt2 = this._updateInt2ForUniform;\n this.updateInt3 = this._updateInt3ForUniform;\n this.updateInt4 = this._updateInt4ForUniform;\n this.updateUInt = this._updateUIntForUniform;\n this.updateUInt2 = this._updateUInt2ForUniform;\n this.updateUInt3 = this._updateUInt3ForUniform;\n this.updateUInt4 = this._updateUInt4ForUniform;\n }\n }\n /**\n * Indicates if the buffer is using the WebGL2 UBO implementation,\n * or just falling back on setUniformXXX calls.\n */\n get useUbo() {\n return !this._noUBO;\n }\n /**\n * Indicates if the WebGL underlying uniform buffer is in sync\n * with the javascript cache data.\n */\n get isSync() {\n return !this._needSync;\n }\n /**\n * Indicates if the WebGL underlying uniform buffer is dynamic.\n * Also, a dynamic UniformBuffer will disable cache verification and always\n * update the underlying WebGL uniform buffer to the GPU.\n * @returns if Dynamic, otherwise false\n */\n isDynamic() {\n return this._dynamic !== undefined;\n }\n /**\n * The data cache on JS side.\n * @returns the underlying data as a float array\n */\n getData() {\n return this._bufferData;\n }\n /**\n * The underlying WebGL Uniform buffer.\n * @returns the webgl buffer\n */\n getBuffer() {\n return this._buffer;\n }\n /**\n * std140 layout specifies how to align data within an UBO structure.\n * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159\n * for specs.\n * @param size\n */\n _fillAlignment(size) {\n // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components\n // and 4x4 matrices\n // TODO : change if other types are used\n let alignment;\n if (size <= 2) {\n alignment = size;\n }\n else {\n alignment = 4;\n }\n if (this._uniformLocationPointer % alignment !== 0) {\n const oldPointer = this._uniformLocationPointer;\n this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);\n const diff = this._uniformLocationPointer - oldPointer;\n for (let i = 0; i < diff; i++) {\n this._data.push(0);\n }\n }\n }\n /**\n * Adds an uniform in the buffer.\n * Warning : the subsequents calls of this function must be in the same order as declared in the shader\n * for the layout to be correct ! The addUniform function only handles types like float, vec2, vec3, vec4, mat4,\n * meaning size=1,2,3,4 or 16. It does not handle struct types.\n * @param name Name of the uniform, as used in the uniform block in the shader.\n * @param size Data size, or data directly.\n * @param arraySize The number of elements in the array, 0 if not an array.\n */\n addUniform(name, size, arraySize = 0) {\n if (this._noUBO) {\n return;\n }\n if (this._uniformLocations[name] !== undefined) {\n // Already existing uniform\n return;\n }\n // This function must be called in the order of the shader layout !\n // size can be the size of the uniform, or data directly\n let data;\n // std140 FTW...\n if (arraySize > 0) {\n if (size instanceof Array) {\n throw \"addUniform should not be use with Array in UBO: \" + name;\n }\n this._fillAlignment(4);\n this._uniformArraySizes[name] = { strideSize: size, arraySize };\n if (size == 16) {\n size = size * arraySize;\n }\n else {\n const perElementPadding = 4 - size;\n const totalPadding = perElementPadding * arraySize;\n size = size * arraySize + totalPadding;\n }\n data = [];\n // Fill with zeros\n for (let i = 0; i < size; i++) {\n data.push(0);\n }\n }\n else {\n if (size instanceof Array) {\n data = size;\n size = data.length;\n }\n else {\n size = size;\n data = [];\n // Fill with zeros\n for (let i = 0; i < size; i++) {\n data.push(0);\n }\n }\n this._fillAlignment(size);\n }\n this._uniformSizes[name] = size;\n this._uniformLocations[name] = this._uniformLocationPointer;\n this._uniformLocationPointer += size;\n for (let i = 0; i < size; i++) {\n this._data.push(data[i]);\n }\n this._needSync = true;\n }\n /**\n * Adds a Matrix 4x4 to the uniform buffer.\n * @param name Name of the uniform, as used in the uniform block in the shader.\n * @param mat A 4x4 matrix.\n */\n addMatrix(name, mat) {\n this.addUniform(name, Array.prototype.slice.call(mat.toArray()));\n }\n /**\n * Adds a vec2 to the uniform buffer.\n * @param name Name of the uniform, as used in the uniform block in the shader.\n * @param x Define the x component value of the vec2\n * @param y Define the y component value of the vec2\n */\n addFloat2(name, x, y) {\n const temp = [x, y];\n this.addUniform(name, temp);\n }\n /**\n * Adds a vec3 to the uniform buffer.\n * @param name Name of the uniform, as used in the uniform block in the shader.\n * @param x Define the x component value of the vec3\n * @param y Define the y component value of the vec3\n * @param z Define the z component value of the vec3\n */\n addFloat3(name, x, y, z) {\n const temp = [x, y, z];\n this.addUniform(name, temp);\n }\n /**\n * Adds a vec3 to the uniform buffer.\n * @param name Name of the uniform, as used in the uniform block in the shader.\n * @param color Define the vec3 from a Color\n */\n addColor3(name, color) {\n const temp = [color.r, color.g, color.b];\n this.addUniform(name, temp);\n }\n /**\n * Adds a vec4 to the uniform buffer.\n * @param name Name of the uniform, as used in the uniform block in the shader.\n * @param color Define the rgb components from a Color\n * @param alpha Define the a component of the vec4\n */\n addColor4(name, color, alpha) {\n const temp = [color.r, color.g, color.b, alpha];\n this.addUniform(name, temp);\n }\n /**\n * Adds a vec3 to the uniform buffer.\n * @param name Name of the uniform, as used in the uniform block in the shader.\n * @param vector Define the vec3 components from a Vector\n */\n addVector3(name, vector) {\n const temp = [vector.x, vector.y, vector.z];\n this.addUniform(name, temp);\n }\n /**\n * Adds a Matrix 3x3 to the uniform buffer.\n * @param name Name of the uniform, as used in the uniform block in the shader.\n */\n addMatrix3x3(name) {\n this.addUniform(name, 12);\n }\n /**\n * Adds a Matrix 2x2 to the uniform buffer.\n * @param name Name of the uniform, as used in the uniform block in the shader.\n */\n addMatrix2x2(name) {\n this.addUniform(name, 8);\n }\n /**\n * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.\n */\n create() {\n if (this._noUBO) {\n return;\n }\n if (this._buffer) {\n return; // nothing to do\n }\n // See spec, alignment must be filled as a vec4\n this._fillAlignment(4);\n this._bufferData = new Float32Array(this._data);\n this._rebuild();\n this._needSync = true;\n }\n /** @internal */\n _rebuild() {\n if (this._noUBO || !this._bufferData) {\n return;\n }\n if (this._dynamic) {\n this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);\n }\n else {\n this._buffer = this._engine.createUniformBuffer(this._bufferData);\n }\n if (this._engine._features.trackUbosInFrame) {\n this._buffers.push([this._buffer, this._engine._features.checkUbosContentBeforeUpload ? this._bufferData.slice() : undefined]);\n this._bufferIndex = this._buffers.length - 1;\n this._createBufferOnWrite = false;\n }\n }\n /** @internal */\n get _numBuffers() {\n return this._buffers.length;\n }\n /** @internal */\n get _indexBuffer() {\n return this._bufferIndex;\n }\n /** Gets the name of this buffer */\n get name() {\n return this._name;\n }\n /** Gets the current effect */\n get currentEffect() {\n return this._currentEffect;\n }\n _buffersEqual(buf1, buf2) {\n for (let i = 0; i < buf1.length; ++i) {\n if (buf1[i] !== buf2[i]) {\n return false;\n }\n }\n return true;\n }\n _copyBuffer(src, dst) {\n for (let i = 0; i < src.length; ++i) {\n dst[i] = src[i];\n }\n }\n /**\n * Updates the WebGL Uniform Buffer on the GPU.\n * If the `dynamic` flag is set to true, no cache comparison is done.\n * Otherwise, the buffer will be updated only if the cache differs.\n */\n update() {\n if (this._noUBO) {\n return;\n }\n this.bindUniformBuffer();\n if (!this._buffer) {\n this.create();\n return;\n }\n if (!this._dynamic && !this._needSync) {\n this._createBufferOnWrite = this._engine._features.trackUbosInFrame;\n return;\n }\n if (this._buffers && this._buffers.length > 1 && this._buffers[this._bufferIndex][1]) {\n if (this._buffersEqual(this._bufferData, this._buffers[this._bufferIndex][1])) {\n this._needSync = false;\n this._createBufferOnWrite = this._engine._features.trackUbosInFrame;\n return;\n }\n else {\n this._copyBuffer(this._bufferData, this._buffers[this._bufferIndex][1]);\n }\n }\n this._engine.updateUniformBuffer(this._buffer, this._bufferData);\n if (this._engine._features._collectUbosUpdatedInFrame) {\n if (!UniformBuffer._UpdatedUbosInFrame[this._name]) {\n UniformBuffer._UpdatedUbosInFrame[this._name] = 0;\n }\n UniformBuffer._UpdatedUbosInFrame[this._name]++;\n }\n this._needSync = false;\n this._createBufferOnWrite = this._engine._features.trackUbosInFrame;\n }\n _createNewBuffer() {\n if (this._bufferIndex + 1 < this._buffers.length) {\n this._bufferIndex++;\n this._buffer = this._buffers[this._bufferIndex][0];\n this._createBufferOnWrite = false;\n this._needSync = true;\n }\n else {\n this._rebuild();\n }\n }\n _checkNewFrame() {\n if (this._engine._features.trackUbosInFrame && this._currentFrameId !== this._engine.frameId) {\n this._currentFrameId = this._engine.frameId;\n this._createBufferOnWrite = false;\n if (this._buffers && this._buffers.length > 0) {\n this._needSync = this._bufferIndex !== 0;\n this._bufferIndex = 0;\n this._buffer = this._buffers[this._bufferIndex][0];\n }\n else {\n this._bufferIndex = -1;\n }\n }\n }\n /**\n * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.\n * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.\n * @param data Define the flattened data\n * @param size Define the size of the data.\n */\n updateUniform(uniformName, data, size) {\n this._checkNewFrame();\n let location = this._uniformLocations[uniformName];\n if (location === undefined) {\n if (this._buffer) {\n // Cannot add an uniform if the buffer is already created\n Logger.Error(\"Cannot add an uniform after UBO has been created.\");\n return;\n }\n this.addUniform(uniformName, size);\n location = this._uniformLocations[uniformName];\n }\n if (!this._buffer) {\n this.create();\n }\n if (!this._dynamic) {\n // Cache for static uniform buffers\n let changed = false;\n for (let i = 0; i < size; i++) {\n // We are checking the matrix cache before calling updateUniform so we do not need to check it here\n // Hence the test for size === 16 to simply commit the matrix values\n if ((size === 16 && !this._engine._features.uniformBufferHardCheckMatrix) || this._bufferData[location + i] !== Tools.FloatRound(data[i])) {\n changed = true;\n if (this._createBufferOnWrite) {\n this._createNewBuffer();\n }\n this._bufferData[location + i] = data[i];\n }\n }\n this._needSync = this._needSync || changed;\n }\n else {\n // No cache for dynamic\n for (let i = 0; i < size; i++) {\n this._bufferData[location + i] = data[i];\n }\n }\n }\n /**\n * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.\n * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.\n * @param data Define the flattened data\n * @param size Define the size of the data.\n */\n updateUniformArray(uniformName, data, size) {\n this._checkNewFrame();\n const location = this._uniformLocations[uniformName];\n if (location === undefined) {\n Logger.Error(\"Cannot add an uniform Array dynamically. Please, add it using addUniform and make sure that uniform buffers are supported by the current engine.\");\n return;\n }\n if (!this._buffer) {\n this.create();\n }\n const arraySizes = this._uniformArraySizes[uniformName];\n if (!this._dynamic) {\n // Cache for static uniform buffers\n let changed = false;\n let countToFour = 0;\n let baseStride = 0;\n for (let i = 0; i < size; i++) {\n if (this._bufferData[location + baseStride * 4 + countToFour] !== Tools.FloatRound(data[i])) {\n changed = true;\n if (this._createBufferOnWrite) {\n this._createNewBuffer();\n }\n this._bufferData[location + baseStride * 4 + countToFour] = data[i];\n }\n countToFour++;\n if (countToFour === arraySizes.strideSize) {\n for (; countToFour < 4; countToFour++) {\n this._bufferData[location + baseStride * 4 + countToFour] = 0;\n }\n countToFour = 0;\n baseStride++;\n }\n }\n this._needSync = this._needSync || changed;\n }\n else {\n // No cache for dynamic\n for (let i = 0; i < size; i++) {\n this._bufferData[location + i] = data[i];\n }\n }\n }\n _cacheMatrix(name, matrix) {\n this._checkNewFrame();\n const cache = this._valueCache[name];\n const flag = matrix.updateFlag;\n if (cache !== undefined && cache === flag) {\n return false;\n }\n this._valueCache[name] = flag;\n return true;\n }\n // Update methods\n _updateMatrix3x3ForUniform(name, matrix) {\n // To match std140, matrix must be realigned\n for (let i = 0; i < 3; i++) {\n UniformBuffer._TempBuffer[i * 4] = matrix[i * 3];\n UniformBuffer._TempBuffer[i * 4 + 1] = matrix[i * 3 + 1];\n UniformBuffer._TempBuffer[i * 4 + 2] = matrix[i * 3 + 2];\n UniformBuffer._TempBuffer[i * 4 + 3] = 0.0;\n }\n this.updateUniform(name, UniformBuffer._TempBuffer, 12);\n }\n _updateMatrix3x3ForEffect(name, matrix) {\n this._currentEffect.setMatrix3x3(name, matrix);\n }\n _updateMatrix2x2ForEffect(name, matrix) {\n this._currentEffect.setMatrix2x2(name, matrix);\n }\n _updateMatrix2x2ForUniform(name, matrix) {\n // To match std140, matrix must be realigned\n for (let i = 0; i < 2; i++) {\n UniformBuffer._TempBuffer[i * 4] = matrix[i * 2];\n UniformBuffer._TempBuffer[i * 4 + 1] = matrix[i * 2 + 1];\n UniformBuffer._TempBuffer[i * 4 + 2] = 0.0;\n UniformBuffer._TempBuffer[i * 4 + 3] = 0.0;\n }\n this.updateUniform(name, UniformBuffer._TempBuffer, 8);\n }\n _updateFloatForEffect(name, x) {\n this._currentEffect.setFloat(name, x);\n }\n _updateFloatForUniform(name, x) {\n UniformBuffer._TempBuffer[0] = x;\n this.updateUniform(name, UniformBuffer._TempBuffer, 1);\n }\n _updateFloat2ForEffect(name, x, y, suffix = \"\") {\n this._currentEffect.setFloat2(name + suffix, x, y);\n }\n _updateFloat2ForUniform(name, x, y) {\n UniformBuffer._TempBuffer[0] = x;\n UniformBuffer._TempBuffer[1] = y;\n this.updateUniform(name, UniformBuffer._TempBuffer, 2);\n }\n _updateFloat3ForEffect(name, x, y, z, suffix = \"\") {\n this._currentEffect.setFloat3(name + suffix, x, y, z);\n }\n _updateFloat3ForUniform(name, x, y, z) {\n UniformBuffer._TempBuffer[0] = x;\n UniformBuffer._TempBuffer[1] = y;\n UniformBuffer._TempBuffer[2] = z;\n this.updateUniform(name, UniformBuffer._TempBuffer, 3);\n }\n _updateFloat4ForEffect(name, x, y, z, w, suffix = \"\") {\n this._currentEffect.setFloat4(name + suffix, x, y, z, w);\n }\n _updateFloat4ForUniform(name, x, y, z, w) {\n UniformBuffer._TempBuffer[0] = x;\n UniformBuffer._TempBuffer[1] = y;\n UniformBuffer._TempBuffer[2] = z;\n UniformBuffer._TempBuffer[3] = w;\n this.updateUniform(name, UniformBuffer._TempBuffer, 4);\n }\n _updateFloatArrayForEffect(name, array) {\n this._currentEffect.setFloatArray(name, array);\n }\n _updateFloatArrayForUniform(name, array) {\n this.updateUniformArray(name, array, array.length);\n }\n _updateArrayForEffect(name, array) {\n this._currentEffect.setArray(name, array);\n }\n _updateArrayForUniform(name, array) {\n this.updateUniformArray(name, array, array.length);\n }\n _updateIntArrayForEffect(name, array) {\n this._currentEffect.setIntArray(name, array);\n }\n _updateIntArrayForUniform(name, array) {\n UniformBuffer._TempBufferInt32View.set(array);\n this.updateUniformArray(name, UniformBuffer._TempBuffer, array.length);\n }\n _updateUIntArrayForEffect(name, array) {\n this._currentEffect.setUIntArray(name, array);\n }\n _updateUIntArrayForUniform(name, array) {\n UniformBuffer._TempBufferUInt32View.set(array);\n this.updateUniformArray(name, UniformBuffer._TempBuffer, array.length);\n }\n _updateMatrixForEffect(name, mat) {\n this._currentEffect.setMatrix(name, mat);\n }\n _updateMatrixForUniform(name, mat) {\n if (this._cacheMatrix(name, mat)) {\n this.updateUniform(name, mat.toArray(), 16);\n }\n }\n _updateMatricesForEffect(name, mat) {\n this._currentEffect.setMatrices(name, mat);\n }\n _updateMatricesForUniform(name, mat) {\n this.updateUniform(name, mat, mat.length);\n }\n _updateVector3ForEffect(name, vector) {\n this._currentEffect.setVector3(name, vector);\n }\n _updateVector3ForUniform(name, vector) {\n UniformBuffer._TempBuffer[0] = vector.x;\n UniformBuffer._TempBuffer[1] = vector.y;\n UniformBuffer._TempBuffer[2] = vector.z;\n this.updateUniform(name, UniformBuffer._TempBuffer, 3);\n }\n _updateVector4ForEffect(name, vector) {\n this._currentEffect.setVector4(name, vector);\n }\n _updateVector4ForUniform(name, vector) {\n UniformBuffer._TempBuffer[0] = vector.x;\n UniformBuffer._TempBuffer[1] = vector.y;\n UniformBuffer._TempBuffer[2] = vector.z;\n UniformBuffer._TempBuffer[3] = vector.w;\n this.updateUniform(name, UniformBuffer._TempBuffer, 4);\n }\n _updateColor3ForEffect(name, color, suffix = \"\") {\n this._currentEffect.setColor3(name + suffix, color);\n }\n _updateColor3ForUniform(name, color) {\n UniformBuffer._TempBuffer[0] = color.r;\n UniformBuffer._TempBuffer[1] = color.g;\n UniformBuffer._TempBuffer[2] = color.b;\n this.updateUniform(name, UniformBuffer._TempBuffer, 3);\n }\n _updateColor4ForEffect(name, color, alpha, suffix = \"\") {\n this._currentEffect.setColor4(name + suffix, color, alpha);\n }\n _updateDirectColor4ForEffect(name, color, suffix = \"\") {\n this._currentEffect.setDirectColor4(name + suffix, color);\n }\n _updateColor4ForUniform(name, color, alpha) {\n UniformBuffer._TempBuffer[0] = color.r;\n UniformBuffer._TempBuffer[1] = color.g;\n UniformBuffer._TempBuffer[2] = color.b;\n UniformBuffer._TempBuffer[3] = alpha;\n this.updateUniform(name, UniformBuffer._TempBuffer, 4);\n }\n _updateDirectColor4ForUniform(name, color) {\n UniformBuffer._TempBuffer[0] = color.r;\n UniformBuffer._TempBuffer[1] = color.g;\n UniformBuffer._TempBuffer[2] = color.b;\n UniformBuffer._TempBuffer[3] = color.a;\n this.updateUniform(name, UniformBuffer._TempBuffer, 4);\n }\n _updateIntForEffect(name, x, suffix = \"\") {\n this._currentEffect.setInt(name + suffix, x);\n }\n _updateIntForUniform(name, x) {\n UniformBuffer._TempBufferInt32View[0] = x;\n this.updateUniform(name, UniformBuffer._TempBuffer, 1);\n }\n _updateInt2ForEffect(name, x, y, suffix = \"\") {\n this._currentEffect.setInt2(name + suffix, x, y);\n }\n _updateInt2ForUniform(name, x, y) {\n UniformBuffer._TempBufferInt32View[0] = x;\n UniformBuffer._TempBufferInt32View[1] = y;\n this.updateUniform(name, UniformBuffer._TempBuffer, 2);\n }\n _updateInt3ForEffect(name, x, y, z, suffix = \"\") {\n this._currentEffect.setInt3(name + suffix, x, y, z);\n }\n _updateInt3ForUniform(name, x, y, z) {\n UniformBuffer._TempBufferInt32View[0] = x;\n UniformBuffer._TempBufferInt32View[1] = y;\n UniformBuffer._TempBufferInt32View[2] = z;\n this.updateUniform(name, UniformBuffer._TempBuffer, 3);\n }\n _updateInt4ForEffect(name, x, y, z, w, suffix = \"\") {\n this._currentEffect.setInt4(name + suffix, x, y, z, w);\n }\n _updateInt4ForUniform(name, x, y, z, w) {\n UniformBuffer._TempBufferInt32View[0] = x;\n UniformBuffer._TempBufferInt32View[1] = y;\n UniformBuffer._TempBufferInt32View[2] = z;\n UniformBuffer._TempBufferInt32View[3] = w;\n this.updateUniform(name, UniformBuffer._TempBuffer, 4);\n }\n _updateUIntForEffect(name, x, suffix = \"\") {\n this._currentEffect.setUInt(name + suffix, x);\n }\n _updateUIntForUniform(name, x) {\n UniformBuffer._TempBufferUInt32View[0] = x;\n this.updateUniform(name, UniformBuffer._TempBuffer, 1);\n }\n _updateUInt2ForEffect(name, x, y, suffix = \"\") {\n this._currentEffect.setUInt2(name + suffix, x, y);\n }\n _updateUInt2ForUniform(name, x, y) {\n UniformBuffer._TempBufferUInt32View[0] = x;\n UniformBuffer._TempBufferUInt32View[1] = y;\n this.updateUniform(name, UniformBuffer._TempBuffer, 2);\n }\n _updateUInt3ForEffect(name, x, y, z, suffix = \"\") {\n this._currentEffect.setUInt3(name + suffix, x, y, z);\n }\n _updateUInt3ForUniform(name, x, y, z) {\n UniformBuffer._TempBufferUInt32View[0] = x;\n UniformBuffer._TempBufferUInt32View[1] = y;\n UniformBuffer._TempBufferUInt32View[2] = z;\n this.updateUniform(name, UniformBuffer._TempBuffer, 3);\n }\n _updateUInt4ForEffect(name, x, y, z, w, suffix = \"\") {\n this._currentEffect.setUInt4(name + suffix, x, y, z, w);\n }\n _updateUInt4ForUniform(name, x, y, z, w) {\n UniformBuffer._TempBufferUInt32View[0] = x;\n UniformBuffer._TempBufferUInt32View[1] = y;\n UniformBuffer._TempBufferUInt32View[2] = z;\n UniformBuffer._TempBufferUInt32View[3] = w;\n this.updateUniform(name, UniformBuffer._TempBuffer, 4);\n }\n /**\n * Sets a sampler uniform on the effect.\n * @param name Define the name of the sampler.\n * @param texture Define the texture to set in the sampler\n */\n setTexture(name, texture) {\n this._currentEffect.setTexture(name, texture);\n }\n /**\n * Directly updates the value of the uniform in the cache AND on the GPU.\n * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.\n * @param data Define the flattened data\n */\n updateUniformDirectly(uniformName, data) {\n this.updateUniform(uniformName, data, data.length);\n this.update();\n }\n /**\n * Associates an effect to this uniform buffer\n * @param effect Define the effect to associate the buffer to\n * @param name Name of the uniform block in the shader.\n */\n bindToEffect(effect, name) {\n this._currentEffect = effect;\n this._currentEffectName = name;\n }\n /**\n * Binds the current (GPU) buffer to the effect\n */\n bindUniformBuffer() {\n if (!this._noUBO && this._buffer && this._currentEffect) {\n this._currentEffect.bindUniformBuffer(this._buffer, this._currentEffectName);\n }\n }\n /**\n * Dissociates the current effect from this uniform buffer\n */\n unbindEffect() {\n this._currentEffect = undefined;\n this._currentEffectName = undefined;\n }\n /**\n * Sets the current state of the class (_bufferIndex, _buffer) to point to the data buffer passed in parameter if this buffer is one of the buffers handled by the class (meaning if it can be found in the _buffers array)\n * This method is meant to be able to update a buffer at any time: just call setDataBuffer to set the class in the right state, call some updateXXX methods and then call udpate() => that will update the GPU buffer on the graphic card\n * @param dataBuffer buffer to look for\n * @returns true if the buffer has been found and the class internal state points to it, else false\n */\n setDataBuffer(dataBuffer) {\n if (!this._buffers) {\n return this._buffer === dataBuffer;\n }\n for (let b = 0; b < this._buffers.length; ++b) {\n const buffer = this._buffers[b];\n if (buffer[0] === dataBuffer) {\n this._bufferIndex = b;\n this._buffer = dataBuffer;\n this._createBufferOnWrite = false;\n this._currentEffect = undefined;\n return true;\n }\n }\n return false;\n }\n /**\n * Disposes the uniform buffer.\n */\n dispose() {\n if (this._noUBO) {\n return;\n }\n const uniformBuffers = this._engine._uniformBuffers;\n const index = uniformBuffers.indexOf(this);\n if (index !== -1) {\n uniformBuffers[index] = uniformBuffers[uniformBuffers.length - 1];\n uniformBuffers.pop();\n }\n if (this._engine._features.trackUbosInFrame && this._buffers) {\n for (let i = 0; i < this._buffers.length; ++i) {\n const buffer = this._buffers[i][0];\n this._engine._releaseBuffer(buffer);\n }\n }\n else if (this._buffer && this._engine._releaseBuffer(this._buffer)) {\n this._buffer = null;\n }\n }\n}\n/** @internal */\nUniformBuffer._UpdatedUbosInFrame = {};\n// Pool for avoiding memory leaks\nUniformBuffer._MAX_UNIFORM_SIZE = 256;\nUniformBuffer._TempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);\nUniformBuffer._TempBufferInt32View = new Int32Array(UniformBuffer._TempBuffer.buffer);\nUniformBuffer._TempBufferUInt32View = new Uint32Array(UniformBuffer._TempBuffer.buffer);\n//# sourceMappingURL=uniformBuffer.js.map","import { Vector3 } from \"./math.vector.js\";\n/** Defines supported spaces */\nexport var Space;\n(function (Space) {\n /** Local (object) space */\n Space[Space[\"LOCAL\"] = 0] = \"LOCAL\";\n /** World space */\n Space[Space[\"WORLD\"] = 1] = \"WORLD\";\n /** Bone space */\n Space[Space[\"BONE\"] = 2] = \"BONE\";\n})(Space || (Space = {}));\n/** Defines the 3 main axes */\nexport class Axis {\n}\n/** X axis */\nAxis.X = new Vector3(1.0, 0.0, 0.0);\n/** Y axis */\nAxis.Y = new Vector3(0.0, 1.0, 0.0);\n/** Z axis */\nAxis.Z = new Vector3(0.0, 0.0, 1.0);\n/**\n * Defines cartesian components.\n */\nexport var Coordinate;\n(function (Coordinate) {\n /** X axis */\n Coordinate[Coordinate[\"X\"] = 0] = \"X\";\n /** Y axis */\n Coordinate[Coordinate[\"Y\"] = 1] = \"Y\";\n /** Z axis */\n Coordinate[Coordinate[\"Z\"] = 2] = \"Z\";\n})(Coordinate || (Coordinate = {}));\n//# sourceMappingURL=math.axis.js.map","import { Scalar } from \"./math.scalar.js\";\nimport { ToLinearSpace, ToGammaSpace } from \"./math.constants.js\";\nimport { ArrayTools } from \"../Misc/arrayTools.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\nfunction colorChannelToLinearSpace(color) {\n return Math.pow(color, ToLinearSpace);\n}\nfunction colorChannelToLinearSpaceExact(color) {\n if (color <= 0.04045) {\n return 0.0773993808 * color;\n }\n return Math.pow(0.947867299 * (color + 0.055), 2.4);\n}\nfunction colorChannelToGammaSpace(color) {\n return Math.pow(color, ToGammaSpace);\n}\nfunction colorChannelToGammaSpaceExact(color) {\n if (color <= 0.0031308) {\n return 12.92 * color;\n }\n return 1.055 * Math.pow(color, 0.41666) - 0.055;\n}\n/**\n * Class used to hold a RGB color\n */\nexport class Color3 {\n /**\n * Creates a new Color3 object from red, green, blue values, all between 0 and 1\n * @param r defines the red component (between 0 and 1, default is 0)\n * @param g defines the green component (between 0 and 1, default is 0)\n * @param b defines the blue component (between 0 and 1, default is 0)\n */\n constructor(\n /**\n * Defines the red component (between 0 and 1, default is 0)\n */\n r = 0, \n /**\n * Defines the green component (between 0 and 1, default is 0)\n */\n g = 0, \n /**\n * Defines the blue component (between 0 and 1, default is 0)\n */\n b = 0) {\n this.r = r;\n this.g = g;\n this.b = b;\n }\n /**\n * Creates a string with the Color3 current values\n * @returns the string representation of the Color3 object\n */\n toString() {\n return \"{R: \" + this.r + \" G:\" + this.g + \" B:\" + this.b + \"}\";\n }\n /**\n * Returns the string \"Color3\"\n * @returns \"Color3\"\n */\n getClassName() {\n return \"Color3\";\n }\n /**\n * Compute the Color3 hash code\n * @returns an unique number that can be used to hash Color3 objects\n */\n getHashCode() {\n let hash = (this.r * 255) | 0;\n hash = (hash * 397) ^ ((this.g * 255) | 0);\n hash = (hash * 397) ^ ((this.b * 255) | 0);\n return hash;\n }\n // Operators\n /**\n * Stores in the given array from the given starting index the red, green, blue values as successive elements\n * @param array defines the array where to store the r,g,b components\n * @param index defines an optional index in the target array to define where to start storing values\n * @returns the current Color3 object\n */\n toArray(array, index = 0) {\n array[index] = this.r;\n array[index + 1] = this.g;\n array[index + 2] = this.b;\n return this;\n }\n /**\n * Update the current color with values stored in an array from the starting index of the given array\n * @param array defines the source array\n * @param offset defines an offset in the source array\n * @returns the current Color3 object\n */\n fromArray(array, offset = 0) {\n Color3.FromArrayToRef(array, offset, this);\n return this;\n }\n /**\n * Returns a new Color4 object from the current Color3 and the given alpha\n * @param alpha defines the alpha component on the new Color4 object (default is 1)\n * @returns a new Color4 object\n */\n toColor4(alpha = 1) {\n return new Color4(this.r, this.g, this.b, alpha);\n }\n /**\n * Returns a new array populated with 3 numeric elements : red, green and blue values\n * @returns the new array\n */\n asArray() {\n return [this.r, this.g, this.b];\n }\n /**\n * Returns the luminance value\n * @returns a float value\n */\n toLuminance() {\n return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;\n }\n /**\n * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object\n * @param otherColor defines the second operand\n * @returns the new Color3 object\n */\n multiply(otherColor) {\n return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);\n }\n /**\n * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object \"result\"\n * @param otherColor defines the second operand\n * @param result defines the Color3 object where to store the result\n * @returns the current Color3\n */\n multiplyToRef(otherColor, result) {\n result.r = this.r * otherColor.r;\n result.g = this.g * otherColor.g;\n result.b = this.b * otherColor.b;\n return this;\n }\n /**\n * Determines equality between Color3 objects\n * @param otherColor defines the second operand\n * @returns true if the rgb values are equal to the given ones\n */\n equals(otherColor) {\n return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;\n }\n /**\n * Determines equality between the current Color3 object and a set of r,b,g values\n * @param r defines the red component to check\n * @param g defines the green component to check\n * @param b defines the blue component to check\n * @returns true if the rgb values are equal to the given ones\n */\n equalsFloats(r, g, b) {\n return this.r === r && this.g === g && this.b === b;\n }\n /**\n * Creates a new Color3 with the current Color3 values multiplied by scale\n * @param scale defines the scaling factor to apply\n * @returns a new Color3 object\n */\n scale(scale) {\n return new Color3(this.r * scale, this.g * scale, this.b * scale);\n }\n /**\n * Multiplies the Color3 values by the float \"scale\"\n * @param scale defines the scaling factor to apply\n * @returns the current updated Color3\n */\n scaleInPlace(scale) {\n this.r *= scale;\n this.g *= scale;\n this.b *= scale;\n return this;\n }\n /**\n * Multiplies the rgb values by scale and stores the result into \"result\"\n * @param scale defines the scaling factor\n * @param result defines the Color3 object where to store the result\n * @returns the unmodified current Color3\n */\n scaleToRef(scale, result) {\n result.r = this.r * scale;\n result.g = this.g * scale;\n result.b = this.b * scale;\n return this;\n }\n /**\n * Scale the current Color3 values by a factor and add the result to a given Color3\n * @param scale defines the scale factor\n * @param result defines color to store the result into\n * @returns the unmodified current Color3\n */\n scaleAndAddToRef(scale, result) {\n result.r += this.r * scale;\n result.g += this.g * scale;\n result.b += this.b * scale;\n return this;\n }\n /**\n * Clamps the rgb values by the min and max values and stores the result into \"result\"\n * @param min defines minimum clamping value (default is 0)\n * @param max defines maximum clamping value (default is 1)\n * @param result defines color to store the result into\n * @returns the original Color3\n */\n clampToRef(min = 0, max = 1, result) {\n result.r = Scalar.Clamp(this.r, min, max);\n result.g = Scalar.Clamp(this.g, min, max);\n result.b = Scalar.Clamp(this.b, min, max);\n return this;\n }\n /**\n * Creates a new Color3 set with the added values of the current Color3 and of the given one\n * @param otherColor defines the second operand\n * @returns the new Color3\n */\n add(otherColor) {\n return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);\n }\n /**\n * Stores the result of the addition of the current Color3 and given one rgb values into \"result\"\n * @param otherColor defines the second operand\n * @param result defines Color3 object to store the result into\n * @returns the unmodified current Color3\n */\n addToRef(otherColor, result) {\n result.r = this.r + otherColor.r;\n result.g = this.g + otherColor.g;\n result.b = this.b + otherColor.b;\n return this;\n }\n /**\n * Returns a new Color3 set with the subtracted values of the given one from the current Color3\n * @param otherColor defines the second operand\n * @returns the new Color3\n */\n subtract(otherColor) {\n return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);\n }\n /**\n * Stores the result of the subtraction of given one from the current Color3 rgb values into \"result\"\n * @param otherColor defines the second operand\n * @param result defines Color3 object to store the result into\n * @returns the unmodified current Color3\n */\n subtractToRef(otherColor, result) {\n result.r = this.r - otherColor.r;\n result.g = this.g - otherColor.g;\n result.b = this.b - otherColor.b;\n return this;\n }\n /**\n * Copy the current object\n * @returns a new Color3 copied the current one\n */\n clone() {\n return new Color3(this.r, this.g, this.b);\n }\n /**\n * Copies the rgb values from the source in the current Color3\n * @param source defines the source Color3 object\n * @returns the updated Color3 object\n */\n copyFrom(source) {\n this.r = source.r;\n this.g = source.g;\n this.b = source.b;\n return this;\n }\n /**\n * Updates the Color3 rgb values from the given floats\n * @param r defines the red component to read from\n * @param g defines the green component to read from\n * @param b defines the blue component to read from\n * @returns the current Color3 object\n */\n copyFromFloats(r, g, b) {\n this.r = r;\n this.g = g;\n this.b = b;\n return this;\n }\n /**\n * Updates the Color3 rgb values from the given floats\n * @param r defines the red component to read from\n * @param g defines the green component to read from\n * @param b defines the blue component to read from\n * @returns the current Color3 object\n */\n set(r, g, b) {\n return this.copyFromFloats(r, g, b);\n }\n /**\n * Compute the Color3 hexadecimal code as a string\n * @returns a string containing the hexadecimal representation of the Color3 object\n */\n toHexString() {\n const intR = Math.round(this.r * 255);\n const intG = Math.round(this.g * 255);\n const intB = Math.round(this.b * 255);\n return \"#\" + Scalar.ToHex(intR) + Scalar.ToHex(intG) + Scalar.ToHex(intB);\n }\n /**\n * Converts current color in rgb space to HSV values\n * @returns a new color3 representing the HSV values\n */\n toHSV() {\n const result = new Color3();\n this.toHSVToRef(result);\n return result;\n }\n /**\n * Converts current color in rgb space to HSV values\n * @param result defines the Color3 where to store the HSV values\n */\n toHSVToRef(result) {\n const r = this.r;\n const g = this.g;\n const b = this.b;\n const max = Math.max(r, g, b);\n const min = Math.min(r, g, b);\n let h = 0;\n let s = 0;\n const v = max;\n const dm = max - min;\n if (max !== 0) {\n s = dm / max;\n }\n if (max != min) {\n if (max == r) {\n h = (g - b) / dm;\n if (g < b) {\n h += 6;\n }\n }\n else if (max == g) {\n h = (b - r) / dm + 2;\n }\n else if (max == b) {\n h = (r - g) / dm + 4;\n }\n h *= 60;\n }\n result.r = h;\n result.g = s;\n result.b = v;\n }\n /**\n * Computes a new Color3 converted from the current one to linear space\n * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false)\n * @returns a new Color3 object\n */\n toLinearSpace(exact = false) {\n const convertedColor = new Color3();\n this.toLinearSpaceToRef(convertedColor, exact);\n return convertedColor;\n }\n /**\n * Converts the Color3 values to linear space and stores the result in \"convertedColor\"\n * @param convertedColor defines the Color3 object where to store the linear space version\n * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false)\n * @returns the unmodified Color3\n */\n toLinearSpaceToRef(convertedColor, exact = false) {\n if (exact) {\n convertedColor.r = colorChannelToLinearSpaceExact(this.r);\n convertedColor.g = colorChannelToLinearSpaceExact(this.g);\n convertedColor.b = colorChannelToLinearSpaceExact(this.b);\n }\n else {\n convertedColor.r = colorChannelToLinearSpace(this.r);\n convertedColor.g = colorChannelToLinearSpace(this.g);\n convertedColor.b = colorChannelToLinearSpace(this.b);\n }\n return this;\n }\n /**\n * Computes a new Color3 converted from the current one to gamma space\n * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false)\n * @returns a new Color3 object\n */\n toGammaSpace(exact = false) {\n const convertedColor = new Color3();\n this.toGammaSpaceToRef(convertedColor, exact);\n return convertedColor;\n }\n /**\n * Converts the Color3 values to gamma space and stores the result in \"convertedColor\"\n * @param convertedColor defines the Color3 object where to store the gamma space version\n * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false)\n * @returns the unmodified Color3\n */\n toGammaSpaceToRef(convertedColor, exact = false) {\n if (exact) {\n convertedColor.r = colorChannelToGammaSpaceExact(this.r);\n convertedColor.g = colorChannelToGammaSpaceExact(this.g);\n convertedColor.b = colorChannelToGammaSpaceExact(this.b);\n }\n else {\n convertedColor.r = colorChannelToGammaSpace(this.r);\n convertedColor.g = colorChannelToGammaSpace(this.g);\n convertedColor.b = colorChannelToGammaSpace(this.b);\n }\n return this;\n }\n /**\n * Converts Hue, saturation and value to a Color3 (RGB)\n * @param hue defines the hue\n * @param saturation defines the saturation\n * @param value defines the value\n * @param result defines the Color3 where to store the RGB values\n */\n static HSVtoRGBToRef(hue, saturation, value, result) {\n const chroma = value * saturation;\n const h = hue / 60;\n const x = chroma * (1 - Math.abs((h % 2) - 1));\n let r = 0;\n let g = 0;\n let b = 0;\n if (h >= 0 && h <= 1) {\n r = chroma;\n g = x;\n }\n else if (h >= 1 && h <= 2) {\n r = x;\n g = chroma;\n }\n else if (h >= 2 && h <= 3) {\n g = chroma;\n b = x;\n }\n else if (h >= 3 && h <= 4) {\n g = x;\n b = chroma;\n }\n else if (h >= 4 && h <= 5) {\n r = x;\n b = chroma;\n }\n else if (h >= 5 && h <= 6) {\n r = chroma;\n b = x;\n }\n const m = value - chroma;\n result.set(r + m, g + m, b + m);\n }\n /**\n * Converts Hue, saturation and value to a new Color3 (RGB)\n * @param hue defines the hue (value between 0 and 360)\n * @param saturation defines the saturation (value between 0 and 1)\n * @param value defines the value (value between 0 and 1)\n * @returns a new Color3 object\n */\n static FromHSV(hue, saturation, value) {\n const result = new Color3(0, 0, 0);\n Color3.HSVtoRGBToRef(hue, saturation, value, result);\n return result;\n }\n /**\n * Creates a new Color3 from the string containing valid hexadecimal values\n * @param hex defines a string containing valid hexadecimal values\n * @returns a new Color3 object\n */\n static FromHexString(hex) {\n if (hex.substring(0, 1) !== \"#\" || hex.length !== 7) {\n return new Color3(0, 0, 0);\n }\n const r = parseInt(hex.substring(1, 3), 16);\n const g = parseInt(hex.substring(3, 5), 16);\n const b = parseInt(hex.substring(5, 7), 16);\n return Color3.FromInts(r, g, b);\n }\n /**\n * Creates a new Color3 from the starting index of the given array\n * @param array defines the source array\n * @param offset defines an offset in the source array\n * @returns a new Color3 object\n */\n static FromArray(array, offset = 0) {\n return new Color3(array[offset], array[offset + 1], array[offset + 2]);\n }\n /**\n * Creates a new Color3 from the starting index element of the given array\n * @param array defines the source array to read from\n * @param offset defines the offset in the source array\n * @param result defines the target Color3 object\n */\n static FromArrayToRef(array, offset = 0, result) {\n result.r = array[offset];\n result.g = array[offset + 1];\n result.b = array[offset + 2];\n }\n /**\n * Creates a new Color3 from integer values (< 256)\n * @param r defines the red component to read from (value between 0 and 255)\n * @param g defines the green component to read from (value between 0 and 255)\n * @param b defines the blue component to read from (value between 0 and 255)\n * @returns a new Color3 object\n */\n static FromInts(r, g, b) {\n return new Color3(r / 255.0, g / 255.0, b / 255.0);\n }\n /**\n * Creates a new Color3 with values linearly interpolated of \"amount\" between the start Color3 and the end Color3\n * @param start defines the start Color3 value\n * @param end defines the end Color3 value\n * @param amount defines the gradient value between start and end\n * @returns a new Color3 object\n */\n static Lerp(start, end, amount) {\n const result = new Color3(0.0, 0.0, 0.0);\n Color3.LerpToRef(start, end, amount, result);\n return result;\n }\n /**\n * Creates a new Color3 with values linearly interpolated of \"amount\" between the start Color3 and the end Color3\n * @param left defines the start value\n * @param right defines the end value\n * @param amount defines the gradient factor\n * @param result defines the Color3 object where to store the result\n */\n static LerpToRef(left, right, amount, result) {\n result.r = left.r + (right.r - left.r) * amount;\n result.g = left.g + (right.g - left.g) * amount;\n result.b = left.b + (right.b - left.b) * amount;\n }\n /**\n * Returns a new Color3 located for \"amount\" (float) on the Hermite interpolation spline defined by the vectors \"value1\", \"tangent1\", \"value2\", \"tangent2\"\n * @param value1 defines the first control point\n * @param tangent1 defines the first tangent Color3\n * @param value2 defines the second control point\n * @param tangent2 defines the second tangent Color3\n * @param amount defines the amount on the interpolation spline (between 0 and 1)\n * @returns the new Color3\n */\n static Hermite(value1, tangent1, value2, tangent2, amount) {\n const squared = amount * amount;\n const cubed = amount * squared;\n const part1 = 2.0 * cubed - 3.0 * squared + 1.0;\n const part2 = -2.0 * cubed + 3.0 * squared;\n const part3 = cubed - 2.0 * squared + amount;\n const part4 = cubed - squared;\n const r = value1.r * part1 + value2.r * part2 + tangent1.r * part3 + tangent2.r * part4;\n const g = value1.g * part1 + value2.g * part2 + tangent1.g * part3 + tangent2.g * part4;\n const b = value1.b * part1 + value2.b * part2 + tangent1.b * part3 + tangent2.b * part4;\n return new Color3(r, g, b);\n }\n /**\n * Returns a new Color3 which is the 1st derivative of the Hermite spline defined by the colors \"value1\", \"value2\", \"tangent1\", \"tangent2\".\n * @param value1 defines the first control point\n * @param tangent1 defines the first tangent\n * @param value2 defines the second control point\n * @param tangent2 defines the second tangent\n * @param time define where the derivative must be done\n * @returns 1st derivative\n */\n static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) {\n const result = Color3.Black();\n this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result);\n return result;\n }\n /**\n * Returns a new Color3 which is the 1st derivative of the Hermite spline defined by the colors \"value1\", \"value2\", \"tangent1\", \"tangent2\".\n * @param value1 defines the first control point\n * @param tangent1 defines the first tangent\n * @param value2 defines the second control point\n * @param tangent2 defines the second tangent\n * @param time define where the derivative must be done\n * @param result define where to store the derivative\n */\n static Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result) {\n const t2 = time * time;\n result.r = (t2 - time) * 6 * value1.r + (3 * t2 - 4 * time + 1) * tangent1.r + (-t2 + time) * 6 * value2.r + (3 * t2 - 2 * time) * tangent2.r;\n result.g = (t2 - time) * 6 * value1.g + (3 * t2 - 4 * time + 1) * tangent1.g + (-t2 + time) * 6 * value2.g + (3 * t2 - 2 * time) * tangent2.g;\n result.b = (t2 - time) * 6 * value1.b + (3 * t2 - 4 * time + 1) * tangent1.b + (-t2 + time) * 6 * value2.b + (3 * t2 - 2 * time) * tangent2.b;\n }\n /**\n * Returns a Color3 value containing a red color\n * @returns a new Color3 object\n */\n static Red() {\n return new Color3(1, 0, 0);\n }\n /**\n * Returns a Color3 value containing a green color\n * @returns a new Color3 object\n */\n static Green() {\n return new Color3(0, 1, 0);\n }\n /**\n * Returns a Color3 value containing a blue color\n * @returns a new Color3 object\n */\n static Blue() {\n return new Color3(0, 0, 1);\n }\n /**\n * Returns a Color3 value containing a black color\n * @returns a new Color3 object\n */\n static Black() {\n return new Color3(0, 0, 0);\n }\n /**\n * Gets a Color3 value containing a black color that must not be updated\n */\n static get BlackReadOnly() {\n return Color3._BlackReadOnly;\n }\n /**\n * Returns a Color3 value containing a white color\n * @returns a new Color3 object\n */\n static White() {\n return new Color3(1, 1, 1);\n }\n /**\n * Returns a Color3 value containing a purple color\n * @returns a new Color3 object\n */\n static Purple() {\n return new Color3(0.5, 0, 0.5);\n }\n /**\n * Returns a Color3 value containing a magenta color\n * @returns a new Color3 object\n */\n static Magenta() {\n return new Color3(1, 0, 1);\n }\n /**\n * Returns a Color3 value containing a yellow color\n * @returns a new Color3 object\n */\n static Yellow() {\n return new Color3(1, 1, 0);\n }\n /**\n * Returns a Color3 value containing a gray color\n * @returns a new Color3 object\n */\n static Gray() {\n return new Color3(0.5, 0.5, 0.5);\n }\n /**\n * Returns a Color3 value containing a teal color\n * @returns a new Color3 object\n */\n static Teal() {\n return new Color3(0, 1.0, 1.0);\n }\n /**\n * Returns a Color3 value containing a random color\n * @returns a new Color3 object\n */\n static Random() {\n return new Color3(Math.random(), Math.random(), Math.random());\n }\n}\n// Statics\nColor3._BlackReadOnly = Color3.Black();\n/**\n * Class used to hold a RBGA color\n */\nexport class Color4 {\n /**\n * Creates a new Color4 object from red, green, blue values, all between 0 and 1\n * @param r defines the red component (between 0 and 1, default is 0)\n * @param g defines the green component (between 0 and 1, default is 0)\n * @param b defines the blue component (between 0 and 1, default is 0)\n * @param a defines the alpha component (between 0 and 1, default is 1)\n */\n constructor(\n /**\n * Defines the red component (between 0 and 1, default is 0)\n */\n r = 0, \n /**\n * Defines the green component (between 0 and 1, default is 0)\n */\n g = 0, \n /**\n * Defines the blue component (between 0 and 1, default is 0)\n */\n b = 0, \n /**\n * Defines the alpha component (between 0 and 1, default is 1)\n */\n a = 1) {\n this.r = r;\n this.g = g;\n this.b = b;\n this.a = a;\n }\n // Operators\n /**\n * Adds in place the given Color4 values to the current Color4 object\n * @param right defines the second operand\n * @returns the current updated Color4 object\n */\n addInPlace(right) {\n this.r += right.r;\n this.g += right.g;\n this.b += right.b;\n this.a += right.a;\n return this;\n }\n /**\n * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values\n * @returns the new array\n */\n asArray() {\n return [this.r, this.g, this.b, this.a];\n }\n /**\n * Stores from the starting index in the given array the Color4 successive values\n * @param array defines the array where to store the r,g,b components\n * @param index defines an optional index in the target array to define where to start storing values\n * @returns the current Color4 object\n */\n toArray(array, index = 0) {\n array[index] = this.r;\n array[index + 1] = this.g;\n array[index + 2] = this.b;\n array[index + 3] = this.a;\n return this;\n }\n /**\n * Update the current color with values stored in an array from the starting index of the given array\n * @param array defines the source array\n * @param offset defines an offset in the source array\n * @returns the current Color4 object\n */\n fromArray(array, offset = 0) {\n Color4.FromArrayToRef(array, offset, this);\n return this;\n }\n /**\n * Determines equality between Color4 objects\n * @param otherColor defines the second operand\n * @returns true if the rgba values are equal to the given ones\n */\n equals(otherColor) {\n return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b && this.a === otherColor.a;\n }\n /**\n * Creates a new Color4 set with the added values of the current Color4 and of the given one\n * @param right defines the second operand\n * @returns a new Color4 object\n */\n add(right) {\n return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);\n }\n /**\n * Creates a new Color4 set with the subtracted values of the given one from the current Color4\n * @param right defines the second operand\n * @returns a new Color4 object\n */\n subtract(right) {\n return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);\n }\n /**\n * Subtracts the given ones from the current Color4 values and stores the results in \"result\"\n * @param right defines the second operand\n * @param result defines the Color4 object where to store the result\n * @returns the current Color4 object\n */\n subtractToRef(right, result) {\n result.r = this.r - right.r;\n result.g = this.g - right.g;\n result.b = this.b - right.b;\n result.a = this.a - right.a;\n return this;\n }\n /**\n * Creates a new Color4 with the current Color4 values multiplied by scale\n * @param scale defines the scaling factor to apply\n * @returns a new Color4 object\n */\n scale(scale) {\n return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);\n }\n /**\n * Multiplies the Color4 values by the float \"scale\"\n * @param scale defines the scaling factor to apply\n * @returns the current updated Color4\n */\n scaleInPlace(scale) {\n this.r *= scale;\n this.g *= scale;\n this.b *= scale;\n this.a *= scale;\n return this;\n }\n /**\n * Multiplies the current Color4 values by scale and stores the result in \"result\"\n * @param scale defines the scaling factor to apply\n * @param result defines the Color4 object where to store the result\n * @returns the current unmodified Color4\n */\n scaleToRef(scale, result) {\n result.r = this.r * scale;\n result.g = this.g * scale;\n result.b = this.b * scale;\n result.a = this.a * scale;\n return this;\n }\n /**\n * Scale the current Color4 values by a factor and add the result to a given Color4\n * @param scale defines the scale factor\n * @param result defines the Color4 object where to store the result\n * @returns the unmodified current Color4\n */\n scaleAndAddToRef(scale, result) {\n result.r += this.r * scale;\n result.g += this.g * scale;\n result.b += this.b * scale;\n result.a += this.a * scale;\n return this;\n }\n /**\n * Clamps the rgb values by the min and max values and stores the result into \"result\"\n * @param min defines minimum clamping value (default is 0)\n * @param max defines maximum clamping value (default is 1)\n * @param result defines color to store the result into.\n * @returns the current Color4\n */\n clampToRef(min = 0, max = 1, result) {\n result.r = Scalar.Clamp(this.r, min, max);\n result.g = Scalar.Clamp(this.g, min, max);\n result.b = Scalar.Clamp(this.b, min, max);\n result.a = Scalar.Clamp(this.a, min, max);\n return this;\n }\n /**\n * Multiply an Color4 value by another and return a new Color4 object\n * @param color defines the Color4 value to multiply by\n * @returns a new Color4 object\n */\n multiply(color) {\n return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);\n }\n /**\n * Multiply a Color4 value by another and push the result in a reference value\n * @param color defines the Color4 value to multiply by\n * @param result defines the Color4 to fill the result in\n * @returns the result Color4\n */\n multiplyToRef(color, result) {\n result.r = this.r * color.r;\n result.g = this.g * color.g;\n result.b = this.b * color.b;\n result.a = this.a * color.a;\n return result;\n }\n /**\n * Creates a string with the Color4 current values\n * @returns the string representation of the Color4 object\n */\n toString() {\n return \"{R: \" + this.r + \" G:\" + this.g + \" B:\" + this.b + \" A:\" + this.a + \"}\";\n }\n /**\n * Returns the string \"Color4\"\n * @returns \"Color4\"\n */\n getClassName() {\n return \"Color4\";\n }\n /**\n * Compute the Color4 hash code\n * @returns an unique number that can be used to hash Color4 objects\n */\n getHashCode() {\n let hash = (this.r * 255) | 0;\n hash = (hash * 397) ^ ((this.g * 255) | 0);\n hash = (hash * 397) ^ ((this.b * 255) | 0);\n hash = (hash * 397) ^ ((this.a * 255) | 0);\n return hash;\n }\n /**\n * Creates a new Color4 copied from the current one\n * @returns a new Color4 object\n */\n clone() {\n return new Color4(this.r, this.g, this.b, this.a);\n }\n /**\n * Copies the given Color4 values into the current one\n * @param source defines the source Color4 object\n * @returns the current updated Color4 object\n */\n copyFrom(source) {\n this.r = source.r;\n this.g = source.g;\n this.b = source.b;\n this.a = source.a;\n return this;\n }\n /**\n * Copies the given float values into the current one\n * @param r defines the red component to read from\n * @param g defines the green component to read from\n * @param b defines the blue component to read from\n * @param a defines the alpha component to read from\n * @returns the current updated Color4 object\n */\n copyFromFloats(r, g, b, a) {\n this.r = r;\n this.g = g;\n this.b = b;\n this.a = a;\n return this;\n }\n /**\n * Copies the given float values into the current one\n * @param r defines the red component to read from\n * @param g defines the green component to read from\n * @param b defines the blue component to read from\n * @param a defines the alpha component to read from\n * @returns the current updated Color4 object\n */\n set(r, g, b, a) {\n return this.copyFromFloats(r, g, b, a);\n }\n /**\n * Compute the Color4 hexadecimal code as a string\n * @param returnAsColor3 defines if the string should only contains RGB values (off by default)\n * @returns a string containing the hexadecimal representation of the Color4 object\n */\n toHexString(returnAsColor3 = false) {\n const intR = Math.round(this.r * 255);\n const intG = Math.round(this.g * 255);\n const intB = Math.round(this.b * 255);\n if (returnAsColor3) {\n return \"#\" + Scalar.ToHex(intR) + Scalar.ToHex(intG) + Scalar.ToHex(intB);\n }\n const intA = Math.round(this.a * 255);\n return \"#\" + Scalar.ToHex(intR) + Scalar.ToHex(intG) + Scalar.ToHex(intB) + Scalar.ToHex(intA);\n }\n /**\n * Computes a new Color4 converted from the current one to linear space\n * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false)\n * @returns a new Color4 object\n */\n toLinearSpace(exact = false) {\n const convertedColor = new Color4();\n this.toLinearSpaceToRef(convertedColor, exact);\n return convertedColor;\n }\n /**\n * Converts the Color4 values to linear space and stores the result in \"convertedColor\"\n * @param convertedColor defines the Color4 object where to store the linear space version\n * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false)\n * @returns the unmodified Color4\n */\n toLinearSpaceToRef(convertedColor, exact = false) {\n if (exact) {\n convertedColor.r = colorChannelToLinearSpaceExact(this.r);\n convertedColor.g = colorChannelToLinearSpaceExact(this.g);\n convertedColor.b = colorChannelToLinearSpaceExact(this.b);\n }\n else {\n convertedColor.r = colorChannelToLinearSpace(this.r);\n convertedColor.g = colorChannelToLinearSpace(this.g);\n convertedColor.b = colorChannelToLinearSpace(this.b);\n }\n convertedColor.a = this.a;\n return this;\n }\n /**\n * Computes a new Color4 converted from the current one to gamma space\n * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false)\n * @returns a new Color4 object\n */\n toGammaSpace(exact = false) {\n const convertedColor = new Color4();\n this.toGammaSpaceToRef(convertedColor, exact);\n return convertedColor;\n }\n /**\n * Converts the Color4 values to gamma space and stores the result in \"convertedColor\"\n * @param convertedColor defines the Color4 object where to store the gamma space version\n * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false)\n * @returns the unmodified Color4\n */\n toGammaSpaceToRef(convertedColor, exact = false) {\n if (exact) {\n convertedColor.r = colorChannelToGammaSpaceExact(this.r);\n convertedColor.g = colorChannelToGammaSpaceExact(this.g);\n convertedColor.b = colorChannelToGammaSpaceExact(this.b);\n }\n else {\n convertedColor.r = colorChannelToGammaSpace(this.r);\n convertedColor.g = colorChannelToGammaSpace(this.g);\n convertedColor.b = colorChannelToGammaSpace(this.b);\n }\n convertedColor.a = this.a;\n return this;\n }\n // Statics\n /**\n * Creates a new Color4 from the string containing valid hexadecimal values.\n *\n * A valid hex string is either in the format #RRGGBB or #RRGGBBAA.\n *\n * When a hex string without alpha is passed, the resulting Color4 has\n * its alpha value set to 1.0.\n *\n * An invalid string results in a Color with all its channels set to 0.0,\n * i.e. \"transparent black\".\n *\n * @param hex defines a string containing valid hexadecimal values\n * @returns a new Color4 object\n */\n static FromHexString(hex) {\n if (hex.substring(0, 1) !== \"#\" || (hex.length !== 9 && hex.length !== 7)) {\n return new Color4(0.0, 0.0, 0.0, 0.0);\n }\n const r = parseInt(hex.substring(1, 3), 16);\n const g = parseInt(hex.substring(3, 5), 16);\n const b = parseInt(hex.substring(5, 7), 16);\n const a = hex.length === 9 ? parseInt(hex.substring(7, 9), 16) : 255;\n return Color4.FromInts(r, g, b, a);\n }\n /**\n * Creates a new Color4 object set with the linearly interpolated values of \"amount\" between the left Color4 object and the right Color4 object\n * @param left defines the start value\n * @param right defines the end value\n * @param amount defines the gradient factor\n * @returns a new Color4 object\n */\n static Lerp(left, right, amount) {\n const result = new Color4(0.0, 0.0, 0.0, 0.0);\n Color4.LerpToRef(left, right, amount, result);\n return result;\n }\n /**\n * Set the given \"result\" with the linearly interpolated values of \"amount\" between the left Color4 object and the right Color4 object\n * @param left defines the start value\n * @param right defines the end value\n * @param amount defines the gradient factor\n * @param result defines the Color4 object where to store data\n */\n static LerpToRef(left, right, amount, result) {\n result.r = left.r + (right.r - left.r) * amount;\n result.g = left.g + (right.g - left.g) * amount;\n result.b = left.b + (right.b - left.b) * amount;\n result.a = left.a + (right.a - left.a) * amount;\n }\n /**\n * Interpolate between two Color4 using Hermite interpolation\n * @param value1 defines first Color4\n * @param tangent1 defines the incoming tangent\n * @param value2 defines second Color4\n * @param tangent2 defines the outgoing tangent\n * @param amount defines the target Color4\n * @returns the new interpolated Color4\n */\n static Hermite(value1, tangent1, value2, tangent2, amount) {\n const squared = amount * amount;\n const cubed = amount * squared;\n const part1 = 2.0 * cubed - 3.0 * squared + 1.0;\n const part2 = -2.0 * cubed + 3.0 * squared;\n const part3 = cubed - 2.0 * squared + amount;\n const part4 = cubed - squared;\n const r = value1.r * part1 + value2.r * part2 + tangent1.r * part3 + tangent2.r * part4;\n const g = value1.g * part1 + value2.g * part2 + tangent1.g * part3 + tangent2.g * part4;\n const b = value1.b * part1 + value2.b * part2 + tangent1.b * part3 + tangent2.b * part4;\n const a = value1.a * part1 + value2.a * part2 + tangent1.a * part3 + tangent2.a * part4;\n return new Color4(r, g, b, a);\n }\n /**\n * Returns a new Color4 which is the 1st derivative of the Hermite spline defined by the colors \"value1\", \"value2\", \"tangent1\", \"tangent2\".\n * @param value1 defines the first control point\n * @param tangent1 defines the first tangent\n * @param value2 defines the second control point\n * @param tangent2 defines the second tangent\n * @param time define where the derivative must be done\n * @returns 1st derivative\n */\n static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) {\n const result = new Color4();\n this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result);\n return result;\n }\n /**\n * Update a Color4 with the 1st derivative of the Hermite spline defined by the colors \"value1\", \"value2\", \"tangent1\", \"tangent2\".\n * @param value1 defines the first control point\n * @param tangent1 defines the first tangent\n * @param value2 defines the second control point\n * @param tangent2 defines the second tangent\n * @param time define where the derivative must be done\n * @param result define where to store the derivative\n */\n static Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result) {\n const t2 = time * time;\n result.r = (t2 - time) * 6 * value1.r + (3 * t2 - 4 * time + 1) * tangent1.r + (-t2 + time) * 6 * value2.r + (3 * t2 - 2 * time) * tangent2.r;\n result.g = (t2 - time) * 6 * value1.g + (3 * t2 - 4 * time + 1) * tangent1.g + (-t2 + time) * 6 * value2.g + (3 * t2 - 2 * time) * tangent2.g;\n result.b = (t2 - time) * 6 * value1.b + (3 * t2 - 4 * time + 1) * tangent1.b + (-t2 + time) * 6 * value2.b + (3 * t2 - 2 * time) * tangent2.b;\n result.a = (t2 - time) * 6 * value1.a + (3 * t2 - 4 * time + 1) * tangent1.a + (-t2 + time) * 6 * value2.a + (3 * t2 - 2 * time) * tangent2.a;\n }\n /**\n * Creates a new Color4 from a Color3 and an alpha value\n * @param color3 defines the source Color3 to read from\n * @param alpha defines the alpha component (1.0 by default)\n * @returns a new Color4 object\n */\n static FromColor3(color3, alpha = 1.0) {\n return new Color4(color3.r, color3.g, color3.b, alpha);\n }\n /**\n * Creates a new Color4 from the starting index element of the given array\n * @param array defines the source array to read from\n * @param offset defines the offset in the source array\n * @returns a new Color4 object\n */\n static FromArray(array, offset = 0) {\n return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);\n }\n /**\n * Creates a new Color4 from the starting index element of the given array\n * @param array defines the source array to read from\n * @param offset defines the offset in the source array\n * @param result defines the target Color4 object\n */\n static FromArrayToRef(array, offset = 0, result) {\n result.r = array[offset];\n result.g = array[offset + 1];\n result.b = array[offset + 2];\n result.a = array[offset + 3];\n }\n /**\n * Creates a new Color3 from integer values (< 256)\n * @param r defines the red component to read from (value between 0 and 255)\n * @param g defines the green component to read from (value between 0 and 255)\n * @param b defines the blue component to read from (value between 0 and 255)\n * @param a defines the alpha component to read from (value between 0 and 255)\n * @returns a new Color3 object\n */\n static FromInts(r, g, b, a) {\n return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);\n }\n /**\n * Check the content of a given array and convert it to an array containing RGBA data\n * If the original array was already containing count * 4 values then it is returned directly\n * @param colors defines the array to check\n * @param count defines the number of RGBA data to expect\n * @returns an array containing count * 4 values (RGBA)\n */\n static CheckColors4(colors, count) {\n // Check if color3 was used\n if (colors.length === count * 3) {\n const colors4 = [];\n for (let index = 0; index < colors.length; index += 3) {\n const newIndex = (index / 3) * 4;\n colors4[newIndex] = colors[index];\n colors4[newIndex + 1] = colors[index + 1];\n colors4[newIndex + 2] = colors[index + 2];\n colors4[newIndex + 3] = 1.0;\n }\n return colors4;\n }\n return colors;\n }\n}\n/**\n * @internal\n */\nexport class TmpColors {\n}\nTmpColors.Color3 = ArrayTools.BuildArray(3, Color3.Black);\nTmpColors.Color4 = ArrayTools.BuildArray(3, () => new Color4(0, 0, 0, 0));\nRegisterClass(\"BABYLON.Color3\", Color3);\nRegisterClass(\"BABYLON.Color4\", Color4);\n//# sourceMappingURL=math.color.js.map","/**\n * Constant used to convert a value to gamma space\n * @ignorenaming\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const ToGammaSpace = 1 / 2.2;\n/**\n * Constant used to convert a value to linear space\n * @ignorenaming\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const ToLinearSpace = 2.2;\n/**\n * Constant Golden Ratio value in Babylon.js\n * @ignorenaming\n */\nexport const PHI = (1 + Math.sqrt(5)) / 2;\n/**\n * Constant used to define the minimal number value in Babylon.js\n * @ignorenaming\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst Epsilon = 0.001;\nexport { Epsilon };\n//# sourceMappingURL=math.constants.js.map","import { Plane } from \"./math.plane.js\";\n/**\n * Represents a camera frustum\n */\nexport class Frustum {\n /**\n * Gets the planes representing the frustum\n * @param transform matrix to be applied to the returned planes\n * @returns a new array of 6 Frustum planes computed by the given transformation matrix.\n */\n static GetPlanes(transform) {\n const frustumPlanes = [];\n for (let index = 0; index < 6; index++) {\n frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));\n }\n Frustum.GetPlanesToRef(transform, frustumPlanes);\n return frustumPlanes;\n }\n /**\n * Gets the near frustum plane transformed by the transform matrix\n * @param transform transformation matrix to be applied to the resulting frustum plane\n * @param frustumPlane the resulting frustum plane\n */\n static GetNearPlaneToRef(transform, frustumPlane) {\n const m = transform.m;\n frustumPlane.normal.x = m[3] + m[2];\n frustumPlane.normal.y = m[7] + m[6];\n frustumPlane.normal.z = m[11] + m[10];\n frustumPlane.d = m[15] + m[14];\n frustumPlane.normalize();\n }\n /**\n * Gets the far frustum plane transformed by the transform matrix\n * @param transform transformation matrix to be applied to the resulting frustum plane\n * @param frustumPlane the resulting frustum plane\n */\n static GetFarPlaneToRef(transform, frustumPlane) {\n const m = transform.m;\n frustumPlane.normal.x = m[3] - m[2];\n frustumPlane.normal.y = m[7] - m[6];\n frustumPlane.normal.z = m[11] - m[10];\n frustumPlane.d = m[15] - m[14];\n frustumPlane.normalize();\n }\n /**\n * Gets the left frustum plane transformed by the transform matrix\n * @param transform transformation matrix to be applied to the resulting frustum plane\n * @param frustumPlane the resulting frustum plane\n */\n static GetLeftPlaneToRef(transform, frustumPlane) {\n const m = transform.m;\n frustumPlane.normal.x = m[3] + m[0];\n frustumPlane.normal.y = m[7] + m[4];\n frustumPlane.normal.z = m[11] + m[8];\n frustumPlane.d = m[15] + m[12];\n frustumPlane.normalize();\n }\n /**\n * Gets the right frustum plane transformed by the transform matrix\n * @param transform transformation matrix to be applied to the resulting frustum plane\n * @param frustumPlane the resulting frustum plane\n */\n static GetRightPlaneToRef(transform, frustumPlane) {\n const m = transform.m;\n frustumPlane.normal.x = m[3] - m[0];\n frustumPlane.normal.y = m[7] - m[4];\n frustumPlane.normal.z = m[11] - m[8];\n frustumPlane.d = m[15] - m[12];\n frustumPlane.normalize();\n }\n /**\n * Gets the top frustum plane transformed by the transform matrix\n * @param transform transformation matrix to be applied to the resulting frustum plane\n * @param frustumPlane the resulting frustum plane\n */\n static GetTopPlaneToRef(transform, frustumPlane) {\n const m = transform.m;\n frustumPlane.normal.x = m[3] - m[1];\n frustumPlane.normal.y = m[7] - m[5];\n frustumPlane.normal.z = m[11] - m[9];\n frustumPlane.d = m[15] - m[13];\n frustumPlane.normalize();\n }\n /**\n * Gets the bottom frustum plane transformed by the transform matrix\n * @param transform transformation matrix to be applied to the resulting frustum plane\n * @param frustumPlane the resulting frustum plane\n */\n static GetBottomPlaneToRef(transform, frustumPlane) {\n const m = transform.m;\n frustumPlane.normal.x = m[3] + m[1];\n frustumPlane.normal.y = m[7] + m[5];\n frustumPlane.normal.z = m[11] + m[9];\n frustumPlane.d = m[15] + m[13];\n frustumPlane.normalize();\n }\n /**\n * Sets the given array \"frustumPlanes\" with the 6 Frustum planes computed by the given transformation matrix.\n * @param transform transformation matrix to be applied to the resulting frustum planes\n * @param frustumPlanes the resulting frustum planes\n */\n static GetPlanesToRef(transform, frustumPlanes) {\n // Near\n Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);\n // Far\n Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);\n // Left\n Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);\n // Right\n Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);\n // Top\n Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);\n // Bottom\n Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);\n }\n /**\n * Tests if a point is located between the frustum planes.\n * @param point defines the point to test\n * @param frustumPlanes defines the frustum planes to test\n * @returns true if the point is located between the frustum planes\n */\n static IsPointInFrustum(point, frustumPlanes) {\n for (let i = 0; i < 6; i++) {\n if (frustumPlanes[i].dotCoordinate(point) < 0) {\n return false;\n }\n }\n return true;\n }\n}\n//# sourceMappingURL=math.frustum.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { Vector3 } from \"./math.vector.js\";\nimport { nativeOverride } from \"../Misc/decorators.js\";\n// This helper class is only here so we can apply the nativeOverride decorator to functions.\nclass MathHelpers {\n static extractMinAndMaxIndexed(positions, indices, indexStart, indexCount, minimum, maximum) {\n for (let index = indexStart; index < indexStart + indexCount; index++) {\n const offset = indices[index] * 3;\n const x = positions[offset];\n const y = positions[offset + 1];\n const z = positions[offset + 2];\n minimum.minimizeInPlaceFromFloats(x, y, z);\n maximum.maximizeInPlaceFromFloats(x, y, z);\n }\n }\n static extractMinAndMax(positions, start, count, stride, minimum, maximum) {\n for (let index = start, offset = start * stride; index < start + count; index++, offset += stride) {\n const x = positions[offset];\n const y = positions[offset + 1];\n const z = positions[offset + 2];\n minimum.minimizeInPlaceFromFloats(x, y, z);\n maximum.maximizeInPlaceFromFloats(x, y, z);\n }\n }\n}\n__decorate([\n nativeOverride.filter((...[positions, indices]) => !Array.isArray(positions) && !Array.isArray(indices))\n // eslint-disable-next-line @typescript-eslint/naming-convention\n], MathHelpers, \"extractMinAndMaxIndexed\", null);\n__decorate([\n nativeOverride.filter((...[positions]) => !Array.isArray(positions))\n // eslint-disable-next-line @typescript-eslint/naming-convention\n], MathHelpers, \"extractMinAndMax\", null);\n/**\n * Extracts minimum and maximum values from a list of indexed positions\n * @param positions defines the positions to use\n * @param indices defines the indices to the positions\n * @param indexStart defines the start index\n * @param indexCount defines the end index\n * @param bias defines bias value to add to the result\n * @returns minimum and maximum values\n */\nexport function extractMinAndMaxIndexed(positions, indices, indexStart, indexCount, bias = null) {\n const minimum = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n const maximum = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);\n MathHelpers.extractMinAndMaxIndexed(positions, indices, indexStart, indexCount, minimum, maximum);\n if (bias) {\n minimum.x -= minimum.x * bias.x + bias.y;\n minimum.y -= minimum.y * bias.x + bias.y;\n minimum.z -= minimum.z * bias.x + bias.y;\n maximum.x += maximum.x * bias.x + bias.y;\n maximum.y += maximum.y * bias.x + bias.y;\n maximum.z += maximum.z * bias.x + bias.y;\n }\n return {\n minimum: minimum,\n maximum: maximum,\n };\n}\n/**\n * Extracts minimum and maximum values from a list of positions\n * @param positions defines the positions to use\n * @param start defines the start index in the positions array\n * @param count defines the number of positions to handle\n * @param bias defines bias value to add to the result\n * @param stride defines the stride size to use (distance between two positions in the positions array)\n * @returns minimum and maximum values\n */\nexport function extractMinAndMax(positions, start, count, bias = null, stride) {\n const minimum = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n const maximum = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);\n if (!stride) {\n stride = 3;\n }\n MathHelpers.extractMinAndMax(positions, start, count, stride, minimum, maximum);\n if (bias) {\n minimum.x -= minimum.x * bias.x + bias.y;\n minimum.y -= minimum.y * bias.x + bias.y;\n minimum.z -= minimum.z * bias.x + bias.y;\n maximum.x += maximum.x * bias.x + bias.y;\n maximum.y += maximum.y * bias.x + bias.y;\n maximum.z += maximum.z * bias.x + bias.y;\n }\n return {\n minimum: minimum,\n maximum: maximum,\n };\n}\n//# sourceMappingURL=math.functions.js.map","import { Vector3, Matrix } from \"./math.vector.js\";\n/**\n * Represents a plane by the equation ax + by + cz + d = 0\n */\nexport class Plane {\n /**\n * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0\n * @param a a component of the plane\n * @param b b component of the plane\n * @param c c component of the plane\n * @param d d component of the plane\n */\n constructor(a, b, c, d) {\n this.normal = new Vector3(a, b, c);\n this.d = d;\n }\n /**\n * @returns the plane coordinates as a new array of 4 elements [a, b, c, d].\n */\n asArray() {\n return [this.normal.x, this.normal.y, this.normal.z, this.d];\n }\n // Methods\n /**\n * @returns a new plane copied from the current Plane.\n */\n clone() {\n return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);\n }\n /**\n * @returns the string \"Plane\".\n */\n getClassName() {\n return \"Plane\";\n }\n /**\n * @returns the Plane hash code.\n */\n getHashCode() {\n let hash = this.normal.getHashCode();\n hash = (hash * 397) ^ (this.d | 0);\n return hash;\n }\n /**\n * Normalize the current Plane in place.\n * @returns the updated Plane.\n */\n normalize() {\n const norm = Math.sqrt(this.normal.x * this.normal.x + this.normal.y * this.normal.y + this.normal.z * this.normal.z);\n let magnitude = 0.0;\n if (norm !== 0) {\n magnitude = 1.0 / norm;\n }\n this.normal.x *= magnitude;\n this.normal.y *= magnitude;\n this.normal.z *= magnitude;\n this.d *= magnitude;\n return this;\n }\n /**\n * Applies a transformation the plane and returns the result\n * @param transformation the transformation matrix to be applied to the plane\n * @returns a new Plane as the result of the transformation of the current Plane by the given matrix.\n */\n transform(transformation) {\n const invertedMatrix = Plane._TmpMatrix;\n transformation.invertToRef(invertedMatrix);\n const m = invertedMatrix.m;\n const x = this.normal.x;\n const y = this.normal.y;\n const z = this.normal.z;\n const d = this.d;\n const normalX = x * m[0] + y * m[1] + z * m[2] + d * m[3];\n const normalY = x * m[4] + y * m[5] + z * m[6] + d * m[7];\n const normalZ = x * m[8] + y * m[9] + z * m[10] + d * m[11];\n const finalD = x * m[12] + y * m[13] + z * m[14] + d * m[15];\n return new Plane(normalX, normalY, normalZ, finalD);\n }\n /**\n * Compute the dot product between the point and the plane normal\n * @param point point to calculate the dot product with\n * @returns the dot product (float) of the point coordinates and the plane normal.\n */\n dotCoordinate(point) {\n return this.normal.x * point.x + this.normal.y * point.y + this.normal.z * point.z + this.d;\n }\n /**\n * Updates the current Plane from the plane defined by the three given points.\n * @param point1 one of the points used to construct the plane\n * @param point2 one of the points used to construct the plane\n * @param point3 one of the points used to construct the plane\n * @returns the updated Plane.\n */\n copyFromPoints(point1, point2, point3) {\n const x1 = point2.x - point1.x;\n const y1 = point2.y - point1.y;\n const z1 = point2.z - point1.z;\n const x2 = point3.x - point1.x;\n const y2 = point3.y - point1.y;\n const z2 = point3.z - point1.z;\n const yz = y1 * z2 - z1 * y2;\n const xz = z1 * x2 - x1 * z2;\n const xy = x1 * y2 - y1 * x2;\n const pyth = Math.sqrt(yz * yz + xz * xz + xy * xy);\n let invPyth;\n if (pyth !== 0) {\n invPyth = 1.0 / pyth;\n }\n else {\n invPyth = 0.0;\n }\n this.normal.x = yz * invPyth;\n this.normal.y = xz * invPyth;\n this.normal.z = xy * invPyth;\n this.d = -(this.normal.x * point1.x + this.normal.y * point1.y + this.normal.z * point1.z);\n return this;\n }\n /**\n * Checks if the plane is facing a given direction (meaning if the plane's normal is pointing in the opposite direction of the given vector).\n * Note that for this function to work as expected you should make sure that:\n * - direction and the plane normal are normalized\n * - epsilon is a number just bigger than -1, something like -0.99 for eg\n * @param direction the direction to check if the plane is facing\n * @param epsilon value the dot product is compared against (returns true if dot <= epsilon)\n * @returns True if the plane is facing the given direction\n */\n isFrontFacingTo(direction, epsilon) {\n const dot = Vector3.Dot(this.normal, direction);\n return dot <= epsilon;\n }\n /**\n * Calculates the distance to a point\n * @param point point to calculate distance to\n * @returns the signed distance (float) from the given point to the Plane.\n */\n signedDistanceTo(point) {\n return Vector3.Dot(point, this.normal) + this.d;\n }\n // Statics\n /**\n * Creates a plane from an array\n * @param array the array to create a plane from\n * @returns a new Plane from the given array.\n */\n static FromArray(array) {\n return new Plane(array[0], array[1], array[2], array[3]);\n }\n /**\n * Creates a plane from three points\n * @param point1 point used to create the plane\n * @param point2 point used to create the plane\n * @param point3 point used to create the plane\n * @returns a new Plane defined by the three given points.\n */\n static FromPoints(point1, point2, point3) {\n const result = new Plane(0.0, 0.0, 0.0, 0.0);\n result.copyFromPoints(point1, point2, point3);\n return result;\n }\n /**\n * Creates a plane from an origin point and a normal\n * @param origin origin of the plane to be constructed\n * @param normal normal of the plane to be constructed\n * @returns a new Plane the normal vector to this plane at the given origin point.\n * Note : the vector \"normal\" is updated because normalized.\n */\n static FromPositionAndNormal(origin, normal) {\n const result = new Plane(0.0, 0.0, 0.0, 0.0);\n normal.normalize();\n result.normal = normal;\n result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);\n return result;\n }\n /**\n * Calculates the distance from a plane and a point\n * @param origin origin of the plane to be constructed\n * @param normal normal of the plane to be constructed\n * @param point point to calculate distance to\n * @returns the signed distance between the plane defined by the normal vector at the \"origin\"\" point and the given other point.\n */\n static SignedDistanceToPlaneFromPositionAndNormal(origin, normal, point) {\n const d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);\n return Vector3.Dot(point, normal) + d;\n }\n}\nPlane._TmpMatrix = Matrix.Identity();\n//# sourceMappingURL=math.plane.js.map","/**\n * Scalar computation library\n */\nexport class Scalar {\n /**\n * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)\n * @param a number\n * @param b number\n * @param epsilon (default = 1.401298E-45)\n * @returns true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)\n */\n static WithinEpsilon(a, b, epsilon = 1.401298e-45) {\n return Math.abs(a - b) <= epsilon;\n }\n /**\n * Returns a string : the upper case translation of the number i to hexadecimal.\n * @param i number\n * @returns the upper case translation of the number i to hexadecimal.\n */\n static ToHex(i) {\n const str = i.toString(16);\n if (i <= 15) {\n return (\"0\" + str).toUpperCase();\n }\n return str.toUpperCase();\n }\n /**\n * Returns -1 if value is negative and +1 is value is positive.\n * @param value the value\n * @returns the value itself if it's equal to zero.\n */\n static Sign(value) {\n value = +value; // convert to a number\n if (value === 0 || isNaN(value)) {\n return value;\n }\n return value > 0 ? 1 : -1;\n }\n /**\n * Returns the value itself if it's between min and max.\n * Returns min if the value is lower than min.\n * Returns max if the value is greater than max.\n * @param value the value to clmap\n * @param min the min value to clamp to (default: 0)\n * @param max the max value to clamp to (default: 1)\n * @returns the clamped value\n */\n static Clamp(value, min = 0, max = 1) {\n return Math.min(max, Math.max(min, value));\n }\n /**\n * the log2 of value.\n * @param value the value to compute log2 of\n * @returns the log2 of value.\n */\n static Log2(value) {\n return Math.log(value) * Math.LOG2E;\n }\n /**\n * the floor part of a log2 value.\n * @param value the value to compute log2 of\n * @returns the log2 of value.\n */\n static ILog2(value) {\n if (Math.log2) {\n return Math.floor(Math.log2(value));\n }\n if (value < 0) {\n return NaN;\n }\n else if (value === 0) {\n return -Infinity;\n }\n let n = 0;\n if (value < 1) {\n while (value < 1) {\n n++;\n value = value * 2;\n }\n n = -n;\n }\n else if (value > 1) {\n while (value > 1) {\n n++;\n value = Math.floor(value / 2);\n }\n }\n return n;\n }\n /**\n * Loops the value, so that it is never larger than length and never smaller than 0.\n *\n * This is similar to the modulo operator but it works with floating point numbers.\n * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.\n * With t = 5 and length = 2.5, the result would be 0.0.\n * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator\n * @param value the value\n * @param length the length\n * @returns the looped value\n */\n static Repeat(value, length) {\n return value - Math.floor(value / length) * length;\n }\n /**\n * Normalize the value between 0.0 and 1.0 using min and max values\n * @param value value to normalize\n * @param min max to normalize between\n * @param max min to normalize between\n * @returns the normalized value\n */\n static Normalize(value, min, max) {\n return (value - min) / (max - min);\n }\n /**\n * Denormalize the value from 0.0 and 1.0 using min and max values\n * @param normalized value to denormalize\n * @param min max to denormalize between\n * @param max min to denormalize between\n * @returns the denormalized value\n */\n static Denormalize(normalized, min, max) {\n return normalized * (max - min) + min;\n }\n /**\n * Calculates the shortest difference between two given angles given in degrees.\n * @param current current angle in degrees\n * @param target target angle in degrees\n * @returns the delta\n */\n static DeltaAngle(current, target) {\n let num = Scalar.Repeat(target - current, 360.0);\n if (num > 180.0) {\n num -= 360.0;\n }\n return num;\n }\n /**\n * PingPongs the value t, so that it is never larger than length and never smaller than 0.\n * @param tx value\n * @param length length\n * @returns The returned value will move back and forth between 0 and length\n */\n static PingPong(tx, length) {\n const t = Scalar.Repeat(tx, length * 2.0);\n return length - Math.abs(t - length);\n }\n /**\n * Interpolates between min and max with smoothing at the limits.\n *\n * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up\n * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.\n * @param from from\n * @param to to\n * @param tx value\n * @returns the smooth stepped value\n */\n static SmoothStep(from, to, tx) {\n let t = Scalar.Clamp(tx);\n t = -2.0 * t * t * t + 3.0 * t * t;\n return to * t + from * (1.0 - t);\n }\n /**\n * Moves a value current towards target.\n *\n * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.\n * Negative values of maxDelta pushes the value away from target.\n * @param current current value\n * @param target target value\n * @param maxDelta max distance to move\n * @returns resulting value\n */\n static MoveTowards(current, target, maxDelta) {\n let result = 0;\n if (Math.abs(target - current) <= maxDelta) {\n result = target;\n }\n else {\n result = current + Scalar.Sign(target - current) * maxDelta;\n }\n return result;\n }\n /**\n * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.\n *\n * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta\n * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.\n * @param current current value\n * @param target target value\n * @param maxDelta max distance to move\n * @returns resulting angle\n */\n static MoveTowardsAngle(current, target, maxDelta) {\n const num = Scalar.DeltaAngle(current, target);\n let result = 0;\n if (-maxDelta < num && num < maxDelta) {\n result = target;\n }\n else {\n target = current + num;\n result = Scalar.MoveTowards(current, target, maxDelta);\n }\n return result;\n }\n /**\n * Creates a new scalar with values linearly interpolated of \"amount\" between the start scalar and the end scalar.\n * @param start start value\n * @param end target value\n * @param amount amount to lerp between\n * @returns the lerped value\n */\n static Lerp(start, end, amount) {\n return start + (end - start) * amount;\n }\n /**\n * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.\n * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.\n * @param start start value\n * @param end target value\n * @param amount amount to lerp between\n * @returns the lerped value\n */\n static LerpAngle(start, end, amount) {\n let num = Scalar.Repeat(end - start, 360.0);\n if (num > 180.0) {\n num -= 360.0;\n }\n return start + num * Scalar.Clamp(amount);\n }\n /**\n * Calculates the linear parameter t that produces the interpolant value within the range [a, b].\n * @param a start value\n * @param b target value\n * @param value value between a and b\n * @returns the inverseLerp value\n */\n static InverseLerp(a, b, value) {\n let result = 0;\n if (a != b) {\n result = Scalar.Clamp((value - a) / (b - a));\n }\n else {\n result = 0.0;\n }\n return result;\n }\n /**\n * Returns a new scalar located for \"amount\" (float) on the Hermite spline defined by the scalars \"value1\", \"value3\", \"tangent1\", \"tangent2\".\n * @see http://mathworld.wolfram.com/HermitePolynomial.html\n * @param value1 defines the first control point\n * @param tangent1 defines the first tangent\n * @param value2 defines the second control point\n * @param tangent2 defines the second tangent\n * @param amount defines the amount on the interpolation spline (between 0 and 1)\n * @returns hermite result\n */\n static Hermite(value1, tangent1, value2, tangent2, amount) {\n const squared = amount * amount;\n const cubed = amount * squared;\n const part1 = 2.0 * cubed - 3.0 * squared + 1.0;\n const part2 = -2.0 * cubed + 3.0 * squared;\n const part3 = cubed - 2.0 * squared + amount;\n const part4 = cubed - squared;\n return value1 * part1 + value2 * part2 + tangent1 * part3 + tangent2 * part4;\n }\n /**\n * Returns a new scalar which is the 1st derivative of the Hermite spline defined by the scalars \"value1\", \"value2\", \"tangent1\", \"tangent2\".\n * @param value1 defines the first control point\n * @param tangent1 defines the first tangent\n * @param value2 defines the second control point\n * @param tangent2 defines the second tangent\n * @param time define where the derivative must be done\n * @returns 1st derivative\n */\n static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) {\n const t2 = time * time;\n return (t2 - time) * 6 * value1 + (3 * t2 - 4 * time + 1) * tangent1 + (-t2 + time) * 6 * value2 + (3 * t2 - 2 * time) * tangent2;\n }\n /**\n * Returns a random float number between and min and max values\n * @param min min value of random\n * @param max max value of random\n * @returns random value\n */\n static RandomRange(min, max) {\n if (min === max) {\n return min;\n }\n return Math.random() * (max - min) + min;\n }\n /**\n * This function returns percentage of a number in a given range.\n *\n * RangeToPercent(40,20,60) will return 0.5 (50%)\n * RangeToPercent(34,0,100) will return 0.34 (34%)\n * @param number to convert to percentage\n * @param min min range\n * @param max max range\n * @returns the percentage\n */\n static RangeToPercent(number, min, max) {\n return (number - min) / (max - min);\n }\n /**\n * This function returns number that corresponds to the percentage in a given range.\n *\n * PercentToRange(0.34,0,100) will return 34.\n * @param percent to convert to number\n * @param min min range\n * @param max max range\n * @returns the number\n */\n static PercentToRange(percent, min, max) {\n return (max - min) * percent + min;\n }\n /**\n * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.\n * @param angle The angle to normalize in radian.\n * @returns The converted angle.\n */\n static NormalizeRadians(angle) {\n // More precise but slower version kept for reference.\n // angle = angle % Tools.TwoPi;\n // angle = (angle + Tools.TwoPi) % Tools.TwoPi;\n //if (angle > Math.PI) {\n //\tangle -= Tools.TwoPi;\n //}\n angle -= Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi);\n return angle;\n }\n /**\n * Returns the highest common factor of two integers.\n * @param a first parameter\n * @param b second parameter\n * @returns HCF of a and b\n */\n static HCF(a, b) {\n const r = a % b;\n if (r === 0) {\n return b;\n }\n return Scalar.HCF(b, r);\n }\n}\n/**\n * Two pi constants convenient for computation.\n */\nScalar.TwoPi = Math.PI * 2;\n//# sourceMappingURL=math.scalar.js.map","/**\n * Class used to represent a viewport on screen\n */\nexport class Viewport {\n /**\n * Creates a Viewport object located at (x, y) and sized (width, height)\n * @param x defines viewport left coordinate\n * @param y defines viewport top coordinate\n * @param width defines the viewport width\n * @param height defines the viewport height\n */\n constructor(\n /** viewport left coordinate */\n x, \n /** viewport top coordinate */\n y, \n /**viewport width */\n width, \n /** viewport height */\n height) {\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n }\n /**\n * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)\n * @param renderWidth defines the rendering width\n * @param renderHeight defines the rendering height\n * @returns a new Viewport\n */\n toGlobal(renderWidth, renderHeight) {\n return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);\n }\n /**\n * Stores absolute viewport value into a target viewport (from 0-> width, 0-> height instead of 0->1)\n * @param renderWidth defines the rendering width\n * @param renderHeight defines the rendering height\n * @param ref defines the target viewport\n * @returns the current viewport\n */\n toGlobalToRef(renderWidth, renderHeight, ref) {\n ref.x = this.x * renderWidth;\n ref.y = this.y * renderHeight;\n ref.width = this.width * renderWidth;\n ref.height = this.height * renderHeight;\n return this;\n }\n /**\n * Returns a new Viewport copied from the current one\n * @returns a new Viewport\n */\n clone() {\n return new Viewport(this.x, this.y, this.width, this.height);\n }\n}\n//# sourceMappingURL=math.viewport.js.map","import { DataBuffer } from \"../../Buffers/dataBuffer.js\";\n/** @internal */\nexport class WebGLDataBuffer extends DataBuffer {\n constructor(resource) {\n super();\n this._buffer = resource;\n }\n get underlyingResource() {\n return this._buffer;\n }\n}\n//# sourceMappingURL=webGLDataBuffer.js.map","import { Observable } from \"../Misc/observable.js\";\nimport { ScenePerformancePriority } from \"../scene.js\";\nimport { Quaternion, Matrix, Vector3, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Engine } from \"../Engines/engine.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { VertexData } from \"../Meshes/mesh.vertexData.js\";\nimport { TransformNode } from \"../Meshes/transformNode.js\";\nimport { PickingInfo } from \"../Collisions/pickingInfo.js\";\nimport { BoundingInfo } from \"../Culling/boundingInfo.js\";\n\nimport { UniformBuffer } from \"../Materials/uniformBuffer.js\";\nimport { _MeshCollisionData } from \"../Collisions/meshCollisionData.js\";\nimport { _WarnImport } from \"../Misc/devTools.js\";\nimport { extractMinAndMax } from \"../Maths/math.functions.js\";\nimport { Color3, Color4 } from \"../Maths/math.color.js\";\nimport { Epsilon } from \"../Maths/math.constants.js\";\nimport { Axis } from \"../Maths/math.axis.js\";\nimport { RegisterClass } from \"../Misc/typeStore.js\";\n/** @internal */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nclass _FacetDataStorage {\n constructor() {\n this.facetNb = 0; // facet number\n this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partitioning space\n this.partitioningBBoxRatio = 1.01; // the partitioning array space is by default 1% bigger than the bounding box\n this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ?\n this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation\n this.bbSize = Vector3.Zero(); // bbox size approximated for facet data\n this.subDiv = {\n // actual number of subdivisions per axis for ComputeNormals()\n max: 1,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n X: 1,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Y: 1,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Z: 1,\n };\n this.facetDepthSort = false; // is the facet depth sort to be computed\n this.facetDepthSortEnabled = false; // is the facet depth sort initialized\n }\n}\n/**\n * @internal\n **/\n// eslint-disable-next-line @typescript-eslint/naming-convention\nclass _InternalAbstractMeshDataInfo {\n constructor() {\n this._hasVertexAlpha = false;\n this._useVertexColors = true;\n this._numBoneInfluencers = 4;\n this._applyFog = true;\n this._receiveShadows = false;\n this._facetData = new _FacetDataStorage();\n this._visibility = 1.0;\n this._skeleton = null;\n this._layerMask = 0x0fffffff;\n this._computeBonesUsingShaders = true;\n this._isActive = false;\n this._onlyForInstances = false;\n this._isActiveIntermediate = false;\n this._onlyForInstancesIntermediate = false;\n this._actAsRegularMesh = false;\n this._currentLOD = null;\n this._currentLODIsUpToDate = false;\n this._collisionRetryCount = 3;\n this._morphTargetManager = null;\n this._renderingGroupId = 0;\n this._bakedVertexAnimationManager = null;\n this._material = null;\n this._positions = null;\n this._pointerOverDisableMeshTesting = false;\n // Collisions\n this._meshCollisionData = new _MeshCollisionData();\n this._enableDistantPicking = false;\n /** @internal\n * Bounding info that is unnafected by the addition of thin instances\n */\n this._rawBoundingInfo = null;\n }\n}\n/**\n * Class used to store all common mesh properties\n */\nexport class AbstractMesh extends TransformNode {\n /**\n * No billboard\n */\n static get BILLBOARDMODE_NONE() {\n return TransformNode.BILLBOARDMODE_NONE;\n }\n /** Billboard on X axis */\n static get BILLBOARDMODE_X() {\n return TransformNode.BILLBOARDMODE_X;\n }\n /** Billboard on Y axis */\n static get BILLBOARDMODE_Y() {\n return TransformNode.BILLBOARDMODE_Y;\n }\n /** Billboard on Z axis */\n static get BILLBOARDMODE_Z() {\n return TransformNode.BILLBOARDMODE_Z;\n }\n /** Billboard on all axes */\n static get BILLBOARDMODE_ALL() {\n return TransformNode.BILLBOARDMODE_ALL;\n }\n /** Billboard on using position instead of orientation */\n static get BILLBOARDMODE_USE_POSITION() {\n return TransformNode.BILLBOARDMODE_USE_POSITION;\n }\n /**\n * Gets the number of facets in the mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#what-is-a-mesh-facet\n */\n get facetNb() {\n return this._internalAbstractMeshDataInfo._facetData.facetNb;\n }\n /**\n * Gets or set the number (integer) of subdivisions per axis in the partitioning space\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#tweaking-the-partitioning\n */\n get partitioningSubdivisions() {\n return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions;\n }\n set partitioningSubdivisions(nb) {\n this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions = nb;\n }\n /**\n * The ratio (float) to apply to the bounding box size to set to the partitioning space.\n * Ex : 1.01 (default) the partitioning space is 1% bigger than the bounding box\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#tweaking-the-partitioning\n */\n get partitioningBBoxRatio() {\n return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio;\n }\n set partitioningBBoxRatio(ratio) {\n this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio = ratio;\n }\n /**\n * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.\n * Works only for updatable meshes.\n * Doesn't work with multi-materials\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#facet-depth-sort\n */\n get mustDepthSortFacets() {\n return this._internalAbstractMeshDataInfo._facetData.facetDepthSort;\n }\n set mustDepthSortFacets(sort) {\n this._internalAbstractMeshDataInfo._facetData.facetDepthSort = sort;\n }\n /**\n * The location (Vector3) where the facet depth sort must be computed from.\n * By default, the active camera position.\n * Used only when facet depth sort is enabled\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#facet-depth-sort\n */\n get facetDepthSortFrom() {\n return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom;\n }\n set facetDepthSortFrom(location) {\n this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom = location;\n }\n /** number of collision detection tries. Change this value if not all collisions are detected and handled properly */\n get collisionRetryCount() {\n return this._internalAbstractMeshDataInfo._collisionRetryCount;\n }\n set collisionRetryCount(retryCount) {\n this._internalAbstractMeshDataInfo._collisionRetryCount = retryCount;\n }\n /**\n * gets a boolean indicating if facetData is enabled\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#what-is-a-mesh-facet\n */\n get isFacetDataEnabled() {\n return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled;\n }\n /**\n * Gets or sets the morph target manager\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/morphTargets\n */\n get morphTargetManager() {\n return this._internalAbstractMeshDataInfo._morphTargetManager;\n }\n set morphTargetManager(value) {\n if (this._internalAbstractMeshDataInfo._morphTargetManager === value) {\n return;\n }\n this._internalAbstractMeshDataInfo._morphTargetManager = value;\n this._syncGeometryWithMorphTargetManager();\n }\n /**\n * Gets or sets the baked vertex animation manager\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/baked_texture_animations\n */\n get bakedVertexAnimationManager() {\n return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager;\n }\n set bakedVertexAnimationManager(value) {\n if (this._internalAbstractMeshDataInfo._bakedVertexAnimationManager === value) {\n return;\n }\n this._internalAbstractMeshDataInfo._bakedVertexAnimationManager = value;\n this._markSubMeshesAsAttributesDirty();\n }\n /** @internal */\n _syncGeometryWithMorphTargetManager() { }\n /**\n * @internal\n */\n _updateNonUniformScalingState(value) {\n if (!super._updateNonUniformScalingState(value)) {\n return false;\n }\n this._markSubMeshesAsMiscDirty();\n return true;\n }\n /** @internal */\n get rawBoundingInfo() {\n return this._internalAbstractMeshDataInfo._rawBoundingInfo;\n }\n set rawBoundingInfo(boundingInfo) {\n this._internalAbstractMeshDataInfo._rawBoundingInfo = boundingInfo;\n }\n /** Set a function to call when this mesh collides with another one */\n set onCollide(callback) {\n if (this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver) {\n this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver);\n }\n this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver = this.onCollideObservable.add(callback);\n }\n /** Set a function to call when the collision's position changes */\n set onCollisionPositionChange(callback) {\n if (this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver) {\n this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver);\n }\n this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);\n }\n /**\n * Gets or sets mesh visibility between 0 and 1 (default is 1)\n */\n get visibility() {\n return this._internalAbstractMeshDataInfo._visibility;\n }\n /**\n * Gets or sets mesh visibility between 0 and 1 (default is 1)\n */\n set visibility(value) {\n if (this._internalAbstractMeshDataInfo._visibility === value) {\n return;\n }\n const oldValue = this._internalAbstractMeshDataInfo._visibility;\n this._internalAbstractMeshDataInfo._visibility = value;\n if ((oldValue === 1 && value !== 1) || (oldValue !== 1 && value === 1)) {\n this._markSubMeshesAsDirty((defines) => {\n defines.markAsMiscDirty();\n defines.markAsPrePassDirty();\n });\n }\n }\n /**\n * Gets or sets the property which disables the test that is checking that the mesh under the pointer is the same than the previous time we tested for it (default: false).\n * Set this property to true if you want thin instances picking to be reported accurately when moving over the mesh.\n * Note that setting this property to true will incur some performance penalties when dealing with pointer events for this mesh so use it sparingly.\n */\n get pointerOverDisableMeshTesting() {\n return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting;\n }\n set pointerOverDisableMeshTesting(disable) {\n this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting = disable;\n }\n /**\n * Specifies the rendering group id for this mesh (0 by default)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/transparent_rendering#rendering-groups\n */\n get renderingGroupId() {\n return this._internalAbstractMeshDataInfo._renderingGroupId;\n }\n set renderingGroupId(value) {\n this._internalAbstractMeshDataInfo._renderingGroupId = value;\n }\n /** Gets or sets current material */\n get material() {\n return this._internalAbstractMeshDataInfo._material;\n }\n set material(value) {\n if (this._internalAbstractMeshDataInfo._material === value) {\n return;\n }\n // remove from material mesh map id needed\n if (this._internalAbstractMeshDataInfo._material && this._internalAbstractMeshDataInfo._material.meshMap) {\n this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId] = undefined;\n }\n this._internalAbstractMeshDataInfo._material = value;\n if (value && value.meshMap) {\n value.meshMap[this.uniqueId] = this;\n }\n if (this.onMaterialChangedObservable.hasObservers()) {\n this.onMaterialChangedObservable.notifyObservers(this);\n }\n if (!this.subMeshes) {\n return;\n }\n this.resetDrawCache();\n this._unBindEffect();\n }\n /**\n * Gets the material used to render the mesh in a specific render pass\n * @param renderPassId render pass id\n * @returns material used for the render pass. If no specific material is used for this render pass, undefined is returned (meaning mesh.material is used for this pass)\n */\n getMaterialForRenderPass(renderPassId) {\n var _a;\n return (_a = this._internalAbstractMeshDataInfo._materialForRenderPass) === null || _a === void 0 ? void 0 : _a[renderPassId];\n }\n /**\n * Sets the material to be used to render the mesh in a specific render pass\n * @param renderPassId render pass id\n * @param material material to use for this render pass. If undefined is passed, no specific material will be used for this render pass but the regular material will be used instead (mesh.material)\n */\n setMaterialForRenderPass(renderPassId, material) {\n this.resetDrawCache(renderPassId);\n if (!this._internalAbstractMeshDataInfo._materialForRenderPass) {\n this._internalAbstractMeshDataInfo._materialForRenderPass = [];\n }\n this._internalAbstractMeshDataInfo._materialForRenderPass[renderPassId] = material;\n }\n /**\n * Gets or sets a boolean indicating that this mesh can receive realtime shadows\n * @see https://doc.babylonjs.com/features/featuresDeepDive/lights/shadows\n */\n get receiveShadows() {\n return this._internalAbstractMeshDataInfo._receiveShadows;\n }\n set receiveShadows(value) {\n if (this._internalAbstractMeshDataInfo._receiveShadows === value) {\n return;\n }\n this._internalAbstractMeshDataInfo._receiveShadows = value;\n this._markSubMeshesAsLightDirty();\n }\n /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */\n get hasVertexAlpha() {\n return this._internalAbstractMeshDataInfo._hasVertexAlpha;\n }\n set hasVertexAlpha(value) {\n if (this._internalAbstractMeshDataInfo._hasVertexAlpha === value) {\n return;\n }\n this._internalAbstractMeshDataInfo._hasVertexAlpha = value;\n this._markSubMeshesAsAttributesDirty();\n this._markSubMeshesAsMiscDirty();\n }\n /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */\n get useVertexColors() {\n return this._internalAbstractMeshDataInfo._useVertexColors;\n }\n set useVertexColors(value) {\n if (this._internalAbstractMeshDataInfo._useVertexColors === value) {\n return;\n }\n this._internalAbstractMeshDataInfo._useVertexColors = value;\n this._markSubMeshesAsAttributesDirty();\n }\n /**\n * Gets or sets a boolean indicating that bone animations must be computed by the GPU (true by default)\n */\n get computeBonesUsingShaders() {\n return this._internalAbstractMeshDataInfo._computeBonesUsingShaders;\n }\n set computeBonesUsingShaders(value) {\n if (this._internalAbstractMeshDataInfo._computeBonesUsingShaders === value) {\n return;\n }\n this._internalAbstractMeshDataInfo._computeBonesUsingShaders = value;\n this._markSubMeshesAsAttributesDirty();\n }\n /** Gets or sets the number of allowed bone influences per vertex (4 by default) */\n get numBoneInfluencers() {\n return this._internalAbstractMeshDataInfo._numBoneInfluencers;\n }\n set numBoneInfluencers(value) {\n if (this._internalAbstractMeshDataInfo._numBoneInfluencers === value) {\n return;\n }\n this._internalAbstractMeshDataInfo._numBoneInfluencers = value;\n this._markSubMeshesAsAttributesDirty();\n }\n /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */\n get applyFog() {\n return this._internalAbstractMeshDataInfo._applyFog;\n }\n set applyFog(value) {\n if (this._internalAbstractMeshDataInfo._applyFog === value) {\n return;\n }\n this._internalAbstractMeshDataInfo._applyFog = value;\n this._markSubMeshesAsMiscDirty();\n }\n /** When enabled, decompose picking matrices for better precision with large values for mesh position and scling */\n get enableDistantPicking() {\n return this._internalAbstractMeshDataInfo._enableDistantPicking;\n }\n set enableDistantPicking(value) {\n this._internalAbstractMeshDataInfo._enableDistantPicking = value;\n }\n /**\n * Gets or sets the current layer mask (default is 0x0FFFFFFF)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/layerMasksAndMultiCam\n */\n get layerMask() {\n return this._internalAbstractMeshDataInfo._layerMask;\n }\n set layerMask(value) {\n if (value === this._internalAbstractMeshDataInfo._layerMask) {\n return;\n }\n this._internalAbstractMeshDataInfo._layerMask = value;\n this._resyncLightSources();\n }\n /**\n * Gets or sets a collision mask used to mask collisions (default is -1).\n * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0\n */\n get collisionMask() {\n return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask;\n }\n set collisionMask(mask) {\n this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask = !isNaN(mask) ? mask : -1;\n }\n /**\n * Gets or sets a collision response flag (default is true).\n * when collisionResponse is false, events are still triggered but colliding entity has no response\n * This helps creating trigger volume when user wants collision feedback events but not position/velocity\n * to respond to the collision.\n */\n get collisionResponse() {\n return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse;\n }\n set collisionResponse(response) {\n this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse = response;\n }\n /**\n * Gets or sets the current collision group mask (-1 by default).\n * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0\n */\n get collisionGroup() {\n return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup;\n }\n set collisionGroup(mask) {\n this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup = !isNaN(mask) ? mask : -1;\n }\n /**\n * Gets or sets current surrounding meshes (null by default).\n *\n * By default collision detection is tested against every mesh in the scene.\n * It is possible to set surroundingMeshes to a defined list of meshes and then only these specified\n * meshes will be tested for the collision.\n *\n * Note: if set to an empty array no collision will happen when this mesh is moved.\n */\n get surroundingMeshes() {\n return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes;\n }\n set surroundingMeshes(meshes) {\n this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes = meshes;\n }\n /** Gets the list of lights affecting that mesh */\n get lightSources() {\n return this._lightSources;\n }\n /** @internal */\n get _positions() {\n return null;\n }\n /**\n * Gets or sets a skeleton to apply skinning transformations\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons\n */\n set skeleton(value) {\n const skeleton = this._internalAbstractMeshDataInfo._skeleton;\n if (skeleton && skeleton.needInitialSkinMatrix) {\n skeleton._unregisterMeshWithPoseMatrix(this);\n }\n if (value && value.needInitialSkinMatrix) {\n value._registerMeshWithPoseMatrix(this);\n }\n this._internalAbstractMeshDataInfo._skeleton = value;\n if (!this._internalAbstractMeshDataInfo._skeleton) {\n this._bonesTransformMatrices = null;\n }\n this._markSubMeshesAsAttributesDirty();\n }\n get skeleton() {\n return this._internalAbstractMeshDataInfo._skeleton;\n }\n // Constructor\n /**\n * Creates a new AbstractMesh\n * @param name defines the name of the mesh\n * @param scene defines the hosting scene\n */\n constructor(name, scene = null) {\n super(name, scene, false);\n // Internal data\n /** @internal */\n this._internalAbstractMeshDataInfo = new _InternalAbstractMeshDataInfo();\n /** @internal */\n this._waitingMaterialId = null;\n /**\n * The culling strategy to use to check whether the mesh must be rendered or not.\n * This value can be changed at any time and will be used on the next render mesh selection.\n * The possible values are :\n * - AbstractMesh.CULLINGSTRATEGY_STANDARD\n * - AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY\n * - AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION\n * - AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY\n * Please read each static variable documentation to get details about the culling process.\n * */\n this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY;\n // Events\n /**\n * An event triggered when this mesh collides with another one\n */\n this.onCollideObservable = new Observable();\n /**\n * An event triggered when the collision's position changes\n */\n this.onCollisionPositionChangeObservable = new Observable();\n /**\n * An event triggered when material is changed\n */\n this.onMaterialChangedObservable = new Observable();\n // Properties\n /**\n * Gets or sets the orientation for POV movement & rotation\n */\n this.definedFacingForward = true;\n /** @internal */\n this._occlusionQuery = null;\n /** @internal */\n this._renderingGroup = null;\n /** Gets or sets the alpha index used to sort transparent meshes\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/transparent_rendering#alpha-index\n */\n this.alphaIndex = Number.MAX_VALUE;\n /**\n * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true\n */\n this.isVisible = true;\n /**\n * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true\n */\n this.isPickable = true;\n /**\n * Gets or sets a boolean indicating if the mesh can be near picked. Default is false\n */\n this.isNearPickable = false;\n /**\n * Gets or sets a boolean indicating if the mesh can be near grabbed. Default is false\n */\n this.isNearGrabbable = false;\n /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */\n this.showSubMeshesBoundingBox = false;\n /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/lenseFlare\n */\n this.isBlocker = false;\n /**\n * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)\n */\n this.enablePointerMoveEvents = false;\n /** Defines color to use when rendering outline */\n this.outlineColor = Color3.Red();\n /** Define width to use when rendering outline */\n this.outlineWidth = 0.02;\n /** Defines color to use when rendering overlay */\n this.overlayColor = Color3.Red();\n /** Defines alpha to use when rendering overlay */\n this.overlayAlpha = 0.5;\n /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */\n this.useOctreeForRenderingSelection = true;\n /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */\n this.useOctreeForPicking = true;\n /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */\n this.useOctreeForCollisions = true;\n /**\n * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)\n */\n this.alwaysSelectAsActiveMesh = false;\n /**\n * Gets or sets a boolean indicating that the bounding info does not need to be kept in sync (for performance reason)\n */\n this.doNotSyncBoundingInfo = false;\n /**\n * Gets or sets the current action manager\n * @see https://doc.babylonjs.com/features/featuresDeepDive/events/actions\n */\n this.actionManager = null;\n /**\n * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions\n */\n this.ellipsoid = new Vector3(0.5, 1, 0.5);\n /**\n * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions\n */\n this.ellipsoidOffset = new Vector3(0, 0, 0);\n // Edges\n /**\n * Defines edge width used when edgesRenderer is enabled\n * @see https://www.babylonjs-playground.com/#10OJSG#13\n */\n this.edgesWidth = 1;\n /**\n * Defines edge color used when edgesRenderer is enabled\n * @see https://www.babylonjs-playground.com/#10OJSG#13\n */\n this.edgesColor = new Color4(1, 0, 0, 1);\n /** @internal */\n this._edgesRenderer = null;\n /** @internal */\n this._masterMesh = null;\n this._boundingInfo = null;\n this._boundingInfoIsDirty = true;\n /** @internal */\n this._renderId = 0;\n /** @internal */\n this._intersectionsInProgress = new Array();\n /** @internal */\n this._unIndexed = false;\n /** @internal */\n this._lightSources = new Array();\n // Loading properties\n /** @internal */\n this._waitingData = {\n lods: null,\n actions: null,\n freezeWorldMatrix: null,\n };\n /** @internal */\n this._bonesTransformMatrices = null;\n /** @internal */\n this._transformMatrixTexture = null;\n /**\n * An event triggered when the mesh is rebuilt.\n */\n this.onRebuildObservable = new Observable();\n this._onCollisionPositionChange = (collisionId, newPosition, collidedMesh = null) => {\n newPosition.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions, this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions);\n if (this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length() > Engine.CollisionsEpsilon) {\n this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions);\n }\n if (collidedMesh) {\n this.onCollideObservable.notifyObservers(collidedMesh);\n }\n this.onCollisionPositionChangeObservable.notifyObservers(this.position);\n };\n scene = this.getScene();\n scene.addMesh(this);\n this._resyncLightSources();\n // Mesh Uniform Buffer.\n this._uniformBuffer = new UniformBuffer(this.getScene().getEngine(), undefined, undefined, name, !this.getScene().getEngine().isWebGPU);\n this._buildUniformLayout();\n switch (scene.performancePriority) {\n case ScenePerformancePriority.Aggressive:\n this.doNotSyncBoundingInfo = true;\n // eslint-disable-next-line no-fallthrough\n case ScenePerformancePriority.Intermediate:\n this.alwaysSelectAsActiveMesh = true;\n this.isPickable = false;\n break;\n }\n }\n _buildUniformLayout() {\n this._uniformBuffer.addUniform(\"world\", 16);\n this._uniformBuffer.addUniform(\"visibility\", 1);\n this._uniformBuffer.create();\n }\n /**\n * Transfer the mesh values to its UBO.\n * @param world The world matrix associated with the mesh\n */\n transferToEffect(world) {\n const ubo = this._uniformBuffer;\n ubo.updateMatrix(\"world\", world);\n ubo.updateFloat(\"visibility\", this._internalAbstractMeshDataInfo._visibility);\n ubo.update();\n }\n /**\n * Gets the mesh uniform buffer.\n * @returns the uniform buffer of the mesh.\n */\n getMeshUniformBuffer() {\n return this._uniformBuffer;\n }\n /**\n * Returns the string \"AbstractMesh\"\n * @returns \"AbstractMesh\"\n */\n getClassName() {\n return \"AbstractMesh\";\n }\n /**\n * Gets a string representation of the current mesh\n * @param fullDetails defines a boolean indicating if full details must be included\n * @returns a string representation of the current mesh\n */\n toString(fullDetails) {\n let ret = \"Name: \" + this.name + \", isInstance: \" + (this.getClassName() !== \"InstancedMesh\" ? \"YES\" : \"NO\");\n ret += \", # of submeshes: \" + (this.subMeshes ? this.subMeshes.length : 0);\n const skeleton = this._internalAbstractMeshDataInfo._skeleton;\n if (skeleton) {\n ret += \", skeleton: \" + skeleton.name;\n }\n if (fullDetails) {\n ret += \", billboard mode: \" + [\"NONE\", \"X\", \"Y\", null, \"Z\", null, null, \"ALL\"][this.billboardMode];\n ret += \", freeze wrld mat: \" + (this._isWorldMatrixFrozen || this._waitingData.freezeWorldMatrix ? \"YES\" : \"NO\");\n }\n return ret;\n }\n /**\n * @internal\n */\n _getEffectiveParent() {\n if (this._masterMesh && this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {\n return this._masterMesh;\n }\n return super._getEffectiveParent();\n }\n /**\n * @internal\n */\n _getActionManagerForTrigger(trigger, initialCall = true) {\n if (this.actionManager && (initialCall || this.actionManager.isRecursive)) {\n if (trigger) {\n if (this.actionManager.hasSpecificTrigger(trigger)) {\n return this.actionManager;\n }\n }\n else {\n return this.actionManager;\n }\n }\n if (!this.parent) {\n return null;\n }\n return this.parent._getActionManagerForTrigger(trigger, false);\n }\n /**\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _rebuild(dispose = false) {\n this.onRebuildObservable.notifyObservers(this);\n if (this._occlusionQuery !== null) {\n this._occlusionQuery = null;\n }\n if (!this.subMeshes) {\n return;\n }\n for (const subMesh of this.subMeshes) {\n subMesh._rebuild();\n }\n }\n /** @internal */\n _resyncLightSources() {\n this._lightSources.length = 0;\n for (const light of this.getScene().lights) {\n if (!light.isEnabled()) {\n continue;\n }\n if (light.canAffectMesh(this)) {\n this._lightSources.push(light);\n }\n }\n this._markSubMeshesAsLightDirty();\n }\n /**\n * @internal\n */\n _resyncLightSource(light) {\n const isIn = light.isEnabled() && light.canAffectMesh(this);\n const index = this._lightSources.indexOf(light);\n let removed = false;\n if (index === -1) {\n if (!isIn) {\n return;\n }\n this._lightSources.push(light);\n }\n else {\n if (isIn) {\n return;\n }\n removed = true;\n this._lightSources.splice(index, 1);\n }\n this._markSubMeshesAsLightDirty(removed);\n }\n /** @internal */\n _unBindEffect() {\n for (const subMesh of this.subMeshes) {\n subMesh.setEffect(null);\n }\n }\n /**\n * @internal\n */\n _removeLightSource(light, dispose) {\n const index = this._lightSources.indexOf(light);\n if (index === -1) {\n return;\n }\n this._lightSources.splice(index, 1);\n this._markSubMeshesAsLightDirty(dispose);\n }\n _markSubMeshesAsDirty(func) {\n if (!this.subMeshes) {\n return;\n }\n for (const subMesh of this.subMeshes) {\n for (let i = 0; i < subMesh._drawWrappers.length; ++i) {\n const drawWrapper = subMesh._drawWrappers[i];\n if (!drawWrapper || !drawWrapper.defines || !drawWrapper.defines.markAllAsDirty) {\n continue;\n }\n func(drawWrapper.defines);\n }\n }\n }\n /**\n * @internal\n */\n _markSubMeshesAsLightDirty(dispose = false) {\n this._markSubMeshesAsDirty((defines) => defines.markAsLightDirty(dispose));\n }\n /** @internal */\n _markSubMeshesAsAttributesDirty() {\n this._markSubMeshesAsDirty((defines) => defines.markAsAttributesDirty());\n }\n /** @internal */\n _markSubMeshesAsMiscDirty() {\n this._markSubMeshesAsDirty((defines) => defines.markAsMiscDirty());\n }\n /**\n * Flag the AbstractMesh as dirty (Forcing it to update everything)\n * @param property if set to \"rotation\" the objects rotationQuaternion will be set to null\n * @returns this AbstractMesh\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n markAsDirty(property) {\n this._currentRenderId = Number.MAX_VALUE;\n this._isDirty = true;\n return this;\n }\n /**\n * Resets the draw wrappers cache for all submeshes of this abstract mesh\n * @param passId If provided, releases only the draw wrapper corresponding to this render pass id\n */\n resetDrawCache(passId) {\n if (!this.subMeshes) {\n return;\n }\n for (const subMesh of this.subMeshes) {\n subMesh.resetDrawCache(passId);\n }\n }\n // Methods\n /**\n * Returns true if the mesh is blocked. Implemented by child classes\n */\n get isBlocked() {\n return false;\n }\n /**\n * Returns the mesh itself by default. Implemented by child classes\n * @param camera defines the camera to use to pick the right LOD level\n * @returns the currentAbstractMesh\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getLOD(camera) {\n return this;\n }\n /**\n * Returns 0 by default. Implemented by child classes\n * @returns an integer\n */\n getTotalVertices() {\n return 0;\n }\n /**\n * Returns a positive integer : the total number of indices in this mesh geometry.\n * @returns the number of indices or zero if the mesh has no geometry.\n */\n getTotalIndices() {\n return 0;\n }\n /**\n * Returns null by default. Implemented by child classes\n * @returns null\n */\n getIndices() {\n return null;\n }\n /**\n * Returns the array of the requested vertex data kind. Implemented by child classes\n * @param kind defines the vertex data kind to use\n * @returns null\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getVerticesData(kind) {\n return null;\n }\n /**\n * Sets the vertex data of the mesh geometry for the requested `kind`.\n * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.\n * Note that a new underlying VertexBuffer object is created each call.\n * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.\n * @param kind defines vertex data kind:\n * * VertexBuffer.PositionKind\n * * VertexBuffer.UVKind\n * * VertexBuffer.UV2Kind\n * * VertexBuffer.UV3Kind\n * * VertexBuffer.UV4Kind\n * * VertexBuffer.UV5Kind\n * * VertexBuffer.UV6Kind\n * * VertexBuffer.ColorKind\n * * VertexBuffer.MatricesIndicesKind\n * * VertexBuffer.MatricesIndicesExtraKind\n * * VertexBuffer.MatricesWeightsKind\n * * VertexBuffer.MatricesWeightsExtraKind\n * @param data defines the data source\n * @param updatable defines if the data must be flagged as updatable (or static)\n * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind\n * @returns the current mesh\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n setVerticesData(kind, data, updatable, stride) {\n return this;\n }\n /**\n * Updates the existing vertex data of the mesh geometry for the requested `kind`.\n * If the mesh has no geometry, it is simply returned as it is.\n * @param kind defines vertex data kind:\n * * VertexBuffer.PositionKind\n * * VertexBuffer.UVKind\n * * VertexBuffer.UV2Kind\n * * VertexBuffer.UV3Kind\n * * VertexBuffer.UV4Kind\n * * VertexBuffer.UV5Kind\n * * VertexBuffer.UV6Kind\n * * VertexBuffer.ColorKind\n * * VertexBuffer.MatricesIndicesKind\n * * VertexBuffer.MatricesIndicesExtraKind\n * * VertexBuffer.MatricesWeightsKind\n * * VertexBuffer.MatricesWeightsExtraKind\n * @param data defines the data source\n * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed\n * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh\n * @returns the current mesh\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n updateVerticesData(kind, data, updateExtends, makeItUnique) {\n return this;\n }\n /**\n * Sets the mesh indices,\n * If the mesh has no geometry, a new Geometry object is created and set to the mesh.\n * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)\n * @param totalVertices Defines the total number of vertices\n * @returns the current mesh\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n setIndices(indices, totalVertices) {\n return this;\n }\n /**\n * Gets a boolean indicating if specific vertex data is present\n * @param kind defines the vertex data kind to use\n * @returns true is data kind is present\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isVerticesDataPresent(kind) {\n return false;\n }\n /**\n * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined.\n * Note that it returns a shallow bounding of the mesh (i.e. it does not include children).\n * However, if the mesh contains thin instances, it will be expanded to include them. If you want the \"raw\" bounding data instead, then use `getRawBoundingInfo()`.\n * To get the full bounding of all children, call `getHierarchyBoundingVectors` instead.\n * @returns a BoundingInfo\n */\n getBoundingInfo() {\n if (this._masterMesh) {\n return this._masterMesh.getBoundingInfo();\n }\n if (this._boundingInfoIsDirty) {\n this._boundingInfoIsDirty = false;\n // this._boundingInfo is being created if undefined\n this._updateBoundingInfo();\n }\n // cannot be null.\n return this._boundingInfo;\n }\n /**\n * Returns the bounding info unnafected by instance data.\n * @returns the bounding info of the mesh unaffected by instance data.\n */\n getRawBoundingInfo() {\n var _a;\n return (_a = this.rawBoundingInfo) !== null && _a !== void 0 ? _a : this.getBoundingInfo();\n }\n /**\n * Overwrite the current bounding info\n * @param boundingInfo defines the new bounding info\n * @returns the current mesh\n */\n setBoundingInfo(boundingInfo) {\n this._boundingInfo = boundingInfo;\n return this;\n }\n /**\n * Returns true if there is already a bounding info\n */\n get hasBoundingInfo() {\n return this._boundingInfo !== null;\n }\n /**\n * Creates a new bounding info for the mesh\n * @param minimum min vector of the bounding box/sphere\n * @param maximum max vector of the bounding box/sphere\n * @param worldMatrix defines the new world matrix\n * @returns the new bounding info\n */\n buildBoundingInfo(minimum, maximum, worldMatrix) {\n this._boundingInfo = new BoundingInfo(minimum, maximum, worldMatrix);\n return this._boundingInfo;\n }\n /**\n * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)\n * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box. Default is false\n * @param ignoreRotation ignore rotation when computing the scale (ie. object will be axis aligned). Default is false\n * @param predicate predicate that is passed in to getHierarchyBoundingVectors when selecting which object should be included when scaling\n * @returns the current mesh\n */\n normalizeToUnitCube(includeDescendants = true, ignoreRotation = false, predicate) {\n return super.normalizeToUnitCube(includeDescendants, ignoreRotation, predicate);\n }\n /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */\n get useBones() {\n return ((this.skeleton &&\n this.getScene().skeletonsEnabled &&\n this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind) &&\n this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)));\n }\n /** @internal */\n _preActivate() { }\n /**\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _preActivateForIntermediateRendering(renderId) { }\n /**\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _activate(renderId, intermediateRendering) {\n this._renderId = renderId;\n return true;\n }\n /** @internal */\n _postActivate() {\n // Do nothing\n }\n /** @internal */\n _freeze() {\n // Do nothing\n }\n /** @internal */\n _unFreeze() {\n // Do nothing\n }\n /**\n * Gets the current world matrix\n * @returns a Matrix\n */\n getWorldMatrix() {\n if (this._masterMesh && this.billboardMode === TransformNode.BILLBOARDMODE_NONE) {\n return this._masterMesh.getWorldMatrix();\n }\n return super.getWorldMatrix();\n }\n /** @internal */\n _getWorldMatrixDeterminant() {\n if (this._masterMesh) {\n return this._masterMesh._getWorldMatrixDeterminant();\n }\n return super._getWorldMatrixDeterminant();\n }\n /**\n * Gets a boolean indicating if this mesh is an instance or a regular mesh\n */\n get isAnInstance() {\n return false;\n }\n /**\n * Gets a boolean indicating if this mesh has instances\n */\n get hasInstances() {\n return false;\n }\n /**\n * Gets a boolean indicating if this mesh has thin instances\n */\n get hasThinInstances() {\n return false;\n }\n // ================================== Point of View Movement =================================\n /**\n * Perform relative position change from the point of view of behind the front of the mesh.\n * This is performed taking into account the meshes current rotation, so you do not have to care.\n * Supports definition of mesh facing forward or backward {@link definedFacingForwardSearch | See definedFacingForwardSearch }.\n * @param amountRight defines the distance on the right axis\n * @param amountUp defines the distance on the up axis\n * @param amountForward defines the distance on the forward axis\n * @returns the current mesh\n */\n movePOV(amountRight, amountUp, amountForward) {\n this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));\n return this;\n }\n /**\n * Calculate relative position change from the point of view of behind the front of the mesh.\n * This is performed taking into account the meshes current rotation, so you do not have to care.\n * Supports definition of mesh facing forward or backward {@link definedFacingForwardSearch | See definedFacingForwardSearch }.\n * @param amountRight defines the distance on the right axis\n * @param amountUp defines the distance on the up axis\n * @param amountForward defines the distance on the forward axis\n * @returns the new displacement vector\n */\n calcMovePOV(amountRight, amountUp, amountForward) {\n const rotMatrix = new Matrix();\n const rotQuaternion = this.rotationQuaternion ? this.rotationQuaternion : Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);\n rotQuaternion.toRotationMatrix(rotMatrix);\n const translationDelta = Vector3.Zero();\n const defForwardMult = this.definedFacingForward ? -1 : 1;\n Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);\n return translationDelta;\n }\n // ================================== Point of View Rotation =================================\n /**\n * Perform relative rotation change from the point of view of behind the front of the mesh.\n * Supports definition of mesh facing forward or backward {@link definedFacingForwardSearch | See definedFacingForwardSearch }.\n * @param flipBack defines the flip\n * @param twirlClockwise defines the twirl\n * @param tiltRight defines the tilt\n * @returns the current mesh\n */\n rotatePOV(flipBack, twirlClockwise, tiltRight) {\n this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));\n return this;\n }\n /**\n * Calculate relative rotation change from the point of view of behind the front of the mesh.\n * Supports definition of mesh facing forward or backward {@link definedFacingForwardSearch | See definedFacingForwardSearch }.\n * @param flipBack defines the flip\n * @param twirlClockwise defines the twirl\n * @param tiltRight defines the tilt\n * @returns the new rotation vector\n */\n calcRotatePOV(flipBack, twirlClockwise, tiltRight) {\n const defForwardMult = this.definedFacingForward ? 1 : -1;\n return new Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);\n }\n /**\n * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.\n * This means the mesh underlying bounding box and sphere are recomputed.\n * @param applySkeleton defines whether to apply the skeleton before computing the bounding info\n * @param applyMorph defines whether to apply the morph target before computing the bounding info\n * @returns the current mesh\n */\n refreshBoundingInfo(applySkeleton = false, applyMorph = false) {\n if (this._boundingInfo && this._boundingInfo.isLocked) {\n return this;\n }\n this._refreshBoundingInfo(this._getPositionData(applySkeleton, applyMorph), null);\n return this;\n }\n /**\n * @internal\n */\n _refreshBoundingInfo(data, bias) {\n if (data) {\n const extend = extractMinAndMax(data, 0, this.getTotalVertices(), bias);\n if (this._boundingInfo) {\n this._boundingInfo.reConstruct(extend.minimum, extend.maximum);\n }\n else {\n this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);\n }\n }\n if (this.subMeshes) {\n for (let index = 0; index < this.subMeshes.length; index++) {\n this.subMeshes[index].refreshBoundingInfo(data);\n }\n }\n this._updateBoundingInfo();\n }\n /**\n * Internal function to get buffer data and possibly apply morphs and normals\n * @param applySkeleton\n * @param applyMorph\n * @param data\n * @param kind the kind of data you want. Can be Normal or Position\n */\n _getData(applySkeleton = false, applyMorph = false, data, kind = VertexBuffer.PositionKind) {\n data = data !== null && data !== void 0 ? data : this.getVerticesData(kind).slice();\n if (data && applyMorph && this.morphTargetManager) {\n let faceIndexCount = 0;\n let positionIndex = 0;\n for (let vertexCount = 0; vertexCount < data.length; vertexCount++) {\n for (let targetCount = 0; targetCount < this.morphTargetManager.numTargets; targetCount++) {\n const targetMorph = this.morphTargetManager.getTarget(targetCount);\n const influence = targetMorph.influence;\n if (influence > 0.0) {\n const morphTargetPositions = targetMorph.getPositions();\n if (morphTargetPositions) {\n data[vertexCount] += (morphTargetPositions[vertexCount] - data[vertexCount]) * influence;\n }\n }\n }\n faceIndexCount++;\n if (kind === VertexBuffer.PositionKind) {\n if (this._positions && faceIndexCount === 3) {\n // We want to merge into positions every 3 indices starting (but not 0)\n faceIndexCount = 0;\n const index = positionIndex * 3;\n this._positions[positionIndex++].copyFromFloats(data[index], data[index + 1], data[index + 2]);\n }\n }\n }\n }\n if (data && applySkeleton && this.skeleton) {\n const matricesIndicesData = this.getVerticesData(VertexBuffer.MatricesIndicesKind);\n const matricesWeightsData = this.getVerticesData(VertexBuffer.MatricesWeightsKind);\n if (matricesWeightsData && matricesIndicesData) {\n const needExtras = this.numBoneInfluencers > 4;\n const matricesIndicesExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind) : null;\n const matricesWeightsExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind) : null;\n const skeletonMatrices = this.skeleton.getTransformMatrices(this);\n const tempVector = TmpVectors.Vector3[0];\n const finalMatrix = TmpVectors.Matrix[0];\n const tempMatrix = TmpVectors.Matrix[1];\n let matWeightIdx = 0;\n for (let index = 0; index < data.length; index += 3, matWeightIdx += 4) {\n finalMatrix.reset();\n let inf;\n let weight;\n for (inf = 0; inf < 4; inf++) {\n weight = matricesWeightsData[matWeightIdx + inf];\n if (weight > 0) {\n Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);\n finalMatrix.addToSelf(tempMatrix);\n }\n }\n if (needExtras) {\n for (inf = 0; inf < 4; inf++) {\n weight = matricesWeightsExtraData[matWeightIdx + inf];\n if (weight > 0) {\n Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);\n finalMatrix.addToSelf(tempMatrix);\n }\n }\n }\n if (kind === VertexBuffer.NormalKind) {\n Vector3.TransformNormalFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);\n }\n else {\n Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);\n }\n tempVector.toArray(data, index);\n if (kind === VertexBuffer.PositionKind && this._positions) {\n this._positions[index / 3].copyFrom(tempVector);\n }\n }\n }\n }\n return data;\n }\n /**\n * Get the normals vertex data and optionally apply skeleton and morphing.\n * @param applySkeleton defines whether to apply the skeleton\n * @param applyMorph defines whether to apply the morph target\n * @returns the normals data\n */\n getNormalsData(applySkeleton = false, applyMorph = false) {\n return this._getData(applySkeleton, applyMorph, null, VertexBuffer.NormalKind);\n }\n /**\n * Get the position vertex data and optionally apply skeleton and morphing.\n * @param applySkeleton defines whether to apply the skeleton\n * @param applyMorph defines whether to apply the morph target\n * @param data defines the position data to apply the skeleton and morph to\n * @returns the position data\n */\n getPositionData(applySkeleton = false, applyMorph = false, data) {\n return this._getData(applySkeleton, applyMorph, data, VertexBuffer.PositionKind);\n }\n /**\n * @internal\n */\n _getPositionData(applySkeleton, applyMorph) {\n var _a;\n let data = this.getVerticesData(VertexBuffer.PositionKind);\n if (this._internalAbstractMeshDataInfo._positions) {\n this._internalAbstractMeshDataInfo._positions = null;\n }\n if (data && ((applySkeleton && this.skeleton) || (applyMorph && this.morphTargetManager))) {\n data = data.slice();\n this._generatePointsArray();\n if (this._positions) {\n const pos = this._positions;\n this._internalAbstractMeshDataInfo._positions = new Array(pos.length);\n for (let i = 0; i < pos.length; i++) {\n this._internalAbstractMeshDataInfo._positions[i] = ((_a = pos[i]) === null || _a === void 0 ? void 0 : _a.clone()) || new Vector3();\n }\n }\n return this.getPositionData(applySkeleton, applyMorph, data);\n }\n return data;\n }\n /** @internal */\n _updateBoundingInfo() {\n if (this._boundingInfo) {\n this._boundingInfo.update(this.worldMatrixFromCache);\n }\n else {\n this._boundingInfo = new BoundingInfo(Vector3.Zero(), Vector3.Zero(), this.worldMatrixFromCache);\n }\n this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);\n return this;\n }\n /**\n * @internal\n */\n _updateSubMeshesBoundingInfo(matrix) {\n if (!this.subMeshes) {\n return this;\n }\n const count = this.subMeshes.length;\n for (let subIndex = 0; subIndex < count; subIndex++) {\n const subMesh = this.subMeshes[subIndex];\n if (count > 1 || !subMesh.IsGlobal) {\n subMesh.updateBoundingInfo(matrix);\n }\n }\n return this;\n }\n /** @internal */\n _afterComputeWorldMatrix() {\n if (this.doNotSyncBoundingInfo) {\n return;\n }\n // Bounding info\n this._boundingInfoIsDirty = true;\n }\n /**\n * Returns `true` if the mesh is within the frustum defined by the passed array of planes.\n * A mesh is in the frustum if its bounding box intersects the frustum\n * @param frustumPlanes defines the frustum to test\n * @returns true if the mesh is in the frustum planes\n */\n isInFrustum(frustumPlanes) {\n return this.getBoundingInfo().isInFrustum(frustumPlanes, this.cullingStrategy);\n }\n /**\n * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.\n * A mesh is completely in the frustum if its bounding box it completely inside the frustum.\n * @param frustumPlanes defines the frustum to test\n * @returns true if the mesh is completely in the frustum planes\n */\n isCompletelyInFrustum(frustumPlanes) {\n return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);\n }\n /**\n * True if the mesh intersects another mesh or a SolidParticle object\n * @param mesh defines a target mesh or SolidParticle to test\n * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)\n * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes\n * @returns true if there is an intersection\n */\n intersectsMesh(mesh, precise = false, includeDescendants) {\n const boundingInfo = this.getBoundingInfo();\n const otherBoundingInfo = mesh.getBoundingInfo();\n if (boundingInfo.intersects(otherBoundingInfo, precise)) {\n return true;\n }\n if (includeDescendants) {\n for (const child of this.getChildMeshes()) {\n if (child.intersectsMesh(mesh, precise, true)) {\n return true;\n }\n }\n }\n return false;\n }\n /**\n * Returns true if the passed point (Vector3) is inside the mesh bounding box\n * @param point defines the point to test\n * @returns true if there is an intersection\n */\n intersectsPoint(point) {\n return this.getBoundingInfo().intersectsPoint(point);\n }\n // Collisions\n /**\n * Gets or sets a boolean indicating that this mesh can be used in the collision engine\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions\n */\n get checkCollisions() {\n return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions;\n }\n set checkCollisions(collisionEnabled) {\n this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions = collisionEnabled;\n }\n /**\n * Gets Collider object used to compute collisions (not physics)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions\n */\n get collider() {\n return this._internalAbstractMeshDataInfo._meshCollisionData._collider;\n }\n /**\n * Move the mesh using collision engine\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions\n * @param displacement defines the requested displacement vector\n * @returns the current mesh\n */\n moveWithCollisions(displacement) {\n const globalPosition = this.getAbsolutePosition();\n globalPosition.addToRef(this.ellipsoidOffset, this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);\n const coordinator = this.getScene().collisionCoordinator;\n if (!this._internalAbstractMeshDataInfo._meshCollisionData._collider) {\n this._internalAbstractMeshDataInfo._meshCollisionData._collider = coordinator.createCollider();\n }\n this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius = this.ellipsoid;\n coordinator.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions, displacement, this._internalAbstractMeshDataInfo._meshCollisionData._collider, this.collisionRetryCount, this, this._onCollisionPositionChange, this.uniqueId);\n return this;\n }\n // Collisions\n /**\n * @internal\n */\n _collideForSubMesh(subMesh, transformMatrix, collider) {\n var _a;\n this._generatePointsArray();\n if (!this._positions) {\n return this;\n }\n // Transformation\n if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {\n subMesh._lastColliderTransformMatrix = transformMatrix.clone();\n subMesh._lastColliderWorldVertices = [];\n subMesh._trianglePlanes = [];\n const start = subMesh.verticesStart;\n const end = subMesh.verticesStart + subMesh.verticesCount;\n for (let i = start; i < end; i++) {\n subMesh._lastColliderWorldVertices.push(Vector3.TransformCoordinates(this._positions[i], transformMatrix));\n }\n }\n // Collide\n collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial(), this, this._shouldConvertRHS(), ((_a = subMesh.getMaterial()) === null || _a === void 0 ? void 0 : _a.fillMode) === 7);\n return this;\n }\n /**\n * @internal\n */\n _processCollisionsForSubMeshes(collider, transformMatrix) {\n const subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);\n const len = subMeshes.length;\n for (let index = 0; index < len; index++) {\n const subMesh = subMeshes.data[index];\n // Bounding test\n if (len > 1 && !subMesh._checkCollision(collider)) {\n continue;\n }\n this._collideForSubMesh(subMesh, transformMatrix, collider);\n }\n return this;\n }\n /** @internal */\n _shouldConvertRHS() {\n return false;\n }\n /**\n * @internal\n */\n _checkCollision(collider) {\n // Bounding box test\n if (!this.getBoundingInfo()._checkCollision(collider)) {\n return this;\n }\n // Transformation matrix\n const collisionsScalingMatrix = TmpVectors.Matrix[0];\n const collisionsTransformMatrix = TmpVectors.Matrix[1];\n Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, collisionsScalingMatrix);\n this.worldMatrixFromCache.multiplyToRef(collisionsScalingMatrix, collisionsTransformMatrix);\n this._processCollisionsForSubMeshes(collider, collisionsTransformMatrix);\n return this;\n }\n // Picking\n /** @internal */\n _generatePointsArray() {\n return false;\n }\n /**\n * Checks if the passed Ray intersects with the mesh. A mesh triangle can be picked both from its front and back sides,\n * irrespective of orientation.\n * @param ray defines the ray to use. It should be in the mesh's LOCAL coordinate space.\n * @param fastCheck defines if fast mode (but less precise) must be used (false by default)\n * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected\n * @param onlyBoundingInfo defines a boolean indicating if picking should only happen using bounding info (false by default)\n * @param worldToUse defines the world matrix to use to get the world coordinate of the intersection point\n * @param skipBoundingInfo a boolean indicating if we should skip the bounding info check\n * @returns the picking info\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/mesh_intersect\n */\n intersects(ray, fastCheck, trianglePredicate, onlyBoundingInfo = false, worldToUse, skipBoundingInfo = false) {\n const pickingInfo = new PickingInfo();\n const className = this.getClassName();\n const intersectionThreshold = className === \"InstancedLinesMesh\" || className === \"LinesMesh\" || className === \"GreasedLineMesh\" ? this.intersectionThreshold : 0;\n const boundingInfo = this.getBoundingInfo();\n if (!this.subMeshes) {\n return pickingInfo;\n }\n if (!skipBoundingInfo &&\n (!ray.intersectsSphere(boundingInfo.boundingSphere, intersectionThreshold) || !ray.intersectsBox(boundingInfo.boundingBox, intersectionThreshold))) {\n return pickingInfo;\n }\n if (onlyBoundingInfo) {\n pickingInfo.hit = skipBoundingInfo ? false : true;\n pickingInfo.pickedMesh = skipBoundingInfo ? null : this;\n pickingInfo.distance = skipBoundingInfo ? 0 : Vector3.Distance(ray.origin, boundingInfo.boundingSphere.center);\n pickingInfo.subMeshId = 0;\n return pickingInfo;\n }\n if (!this._generatePointsArray()) {\n return pickingInfo;\n }\n let intersectInfo = null;\n const subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);\n const len = subMeshes.length;\n // Check if all submeshes are using a material that don't allow picking (point/lines rendering)\n // if no submesh can be picked that way, then fallback to BBox picking\n let anySubmeshSupportIntersect = false;\n for (let index = 0; index < len; index++) {\n const subMesh = subMeshes.data[index];\n const material = subMesh.getMaterial();\n if (!material) {\n continue;\n }\n if (material.fillMode == 7 ||\n material.fillMode == 0 ||\n material.fillMode == 1 ||\n material.fillMode == 2 ||\n material.fillMode == 4) {\n anySubmeshSupportIntersect = true;\n break;\n }\n }\n // no sub mesh support intersection, fallback to BBox that has already be done\n if (!anySubmeshSupportIntersect) {\n pickingInfo.hit = true;\n pickingInfo.pickedMesh = this;\n pickingInfo.distance = Vector3.Distance(ray.origin, boundingInfo.boundingSphere.center);\n pickingInfo.subMeshId = -1;\n return pickingInfo;\n }\n // at least 1 submesh supports intersection, keep going\n for (let index = 0; index < len; index++) {\n const subMesh = subMeshes.data[index];\n // Bounding test\n if (len > 1 && !subMesh.canIntersects(ray)) {\n continue;\n }\n const currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck, trianglePredicate);\n if (currentIntersectInfo) {\n if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {\n intersectInfo = currentIntersectInfo;\n intersectInfo.subMeshId = index;\n if (fastCheck) {\n break;\n }\n }\n }\n }\n if (intersectInfo) {\n // Get picked point\n const world = worldToUse !== null && worldToUse !== void 0 ? worldToUse : this.getWorldMatrix();\n const worldOrigin = TmpVectors.Vector3[0];\n const direction = TmpVectors.Vector3[1];\n Vector3.TransformCoordinatesToRef(ray.origin, world, worldOrigin);\n ray.direction.scaleToRef(intersectInfo.distance, direction);\n const worldDirection = Vector3.TransformNormal(direction, world);\n const pickedPoint = worldDirection.addInPlace(worldOrigin);\n // Return result\n pickingInfo.hit = true;\n pickingInfo.distance = Vector3.Distance(worldOrigin, pickedPoint);\n pickingInfo.pickedPoint = pickedPoint;\n pickingInfo.pickedMesh = this;\n pickingInfo.bu = intersectInfo.bu || 0;\n pickingInfo.bv = intersectInfo.bv || 0;\n pickingInfo.subMeshFaceId = intersectInfo.faceId;\n pickingInfo.faceId = intersectInfo.faceId + subMeshes.data[intersectInfo.subMeshId].indexStart / (this.getClassName().indexOf(\"LinesMesh\") !== -1 ? 2 : 3);\n pickingInfo.subMeshId = intersectInfo.subMeshId;\n return pickingInfo;\n }\n return pickingInfo;\n }\n /**\n * Clones the current mesh\n * @param name defines the mesh name\n * @param newParent defines the new mesh parent\n * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)\n * @returns the new mesh\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n clone(name, newParent, doNotCloneChildren) {\n return null;\n }\n /**\n * Disposes all the submeshes of the current meshnp\n * @returns the current mesh\n */\n releaseSubMeshes() {\n if (this.subMeshes) {\n while (this.subMeshes.length) {\n this.subMeshes[0].dispose();\n }\n }\n else {\n this.subMeshes = new Array();\n }\n return this;\n }\n /**\n * Releases resources associated with this abstract mesh.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n dispose(doNotRecurse, disposeMaterialAndTextures = false) {\n let index;\n // mesh map release.\n if (this._scene.useMaterialMeshMap) {\n // remove from material mesh map id needed\n if (this._internalAbstractMeshDataInfo._material && this._internalAbstractMeshDataInfo._material.meshMap) {\n this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId] = undefined;\n }\n }\n // Smart Array Retainers.\n this.getScene().freeActiveMeshes();\n this.getScene().freeRenderingGroups();\n // Action manager\n if (this.actionManager !== undefined && this.actionManager !== null) {\n this.actionManager.dispose();\n this.actionManager = null;\n }\n // Skeleton\n this._internalAbstractMeshDataInfo._skeleton = null;\n if (this._transformMatrixTexture) {\n this._transformMatrixTexture.dispose();\n this._transformMatrixTexture = null;\n }\n // Intersections in progress\n for (index = 0; index < this._intersectionsInProgress.length; index++) {\n const other = this._intersectionsInProgress[index];\n const pos = other._intersectionsInProgress.indexOf(this);\n other._intersectionsInProgress.splice(pos, 1);\n }\n this._intersectionsInProgress.length = 0;\n // Lights\n const lights = this.getScene().lights;\n lights.forEach((light) => {\n let meshIndex = light.includedOnlyMeshes.indexOf(this);\n if (meshIndex !== -1) {\n light.includedOnlyMeshes.splice(meshIndex, 1);\n }\n meshIndex = light.excludedMeshes.indexOf(this);\n if (meshIndex !== -1) {\n light.excludedMeshes.splice(meshIndex, 1);\n }\n // Shadow generators\n const generators = light.getShadowGenerators();\n if (generators) {\n const iterator = generators.values();\n for (let key = iterator.next(); key.done !== true; key = iterator.next()) {\n const generator = key.value;\n const shadowMap = generator.getShadowMap();\n if (shadowMap && shadowMap.renderList) {\n meshIndex = shadowMap.renderList.indexOf(this);\n if (meshIndex !== -1) {\n shadowMap.renderList.splice(meshIndex, 1);\n }\n }\n }\n }\n });\n // SubMeshes\n if (this.getClassName() !== \"InstancedMesh\" || this.getClassName() !== \"InstancedLinesMesh\") {\n this.releaseSubMeshes();\n }\n // Query\n const engine = this.getScene().getEngine();\n if (this._occlusionQuery !== null) {\n this.isOcclusionQueryInProgress = false;\n engine.deleteQuery(this._occlusionQuery);\n this._occlusionQuery = null;\n }\n // Engine\n engine.wipeCaches();\n // Remove from scene\n this.getScene().removeMesh(this);\n if (this._parentContainer) {\n const index = this._parentContainer.meshes.indexOf(this);\n if (index > -1) {\n this._parentContainer.meshes.splice(index, 1);\n }\n this._parentContainer = null;\n }\n if (disposeMaterialAndTextures) {\n if (this.material) {\n if (this.material.getClassName() === \"MultiMaterial\") {\n this.material.dispose(false, true, true);\n }\n else {\n this.material.dispose(false, true);\n }\n }\n }\n if (!doNotRecurse) {\n // Particles\n for (index = 0; index < this.getScene().particleSystems.length; index++) {\n if (this.getScene().particleSystems[index].emitter === this) {\n this.getScene().particleSystems[index].dispose();\n index--;\n }\n }\n }\n // facet data\n if (this._internalAbstractMeshDataInfo._facetData.facetDataEnabled) {\n this.disableFacetData();\n }\n this._uniformBuffer.dispose();\n this.onAfterWorldMatrixUpdateObservable.clear();\n this.onCollideObservable.clear();\n this.onCollisionPositionChangeObservable.clear();\n this.onRebuildObservable.clear();\n super.dispose(doNotRecurse, disposeMaterialAndTextures);\n }\n /**\n * Adds the passed mesh as a child to the current mesh\n * @param mesh defines the child mesh\n * @param preserveScalingSign if true, keep scaling sign of child. Otherwise, scaling sign might change.\n * @returns the current mesh\n */\n addChild(mesh, preserveScalingSign = false) {\n mesh.setParent(this, preserveScalingSign);\n return this;\n }\n /**\n * Removes the passed mesh from the current mesh children list\n * @param mesh defines the child mesh\n * @param preserveScalingSign if true, keep scaling sign of child. Otherwise, scaling sign might change.\n * @returns the current mesh\n */\n removeChild(mesh, preserveScalingSign = false) {\n mesh.setParent(null, preserveScalingSign);\n return this;\n }\n // Facet data\n /** @internal */\n _initFacetData() {\n const data = this._internalAbstractMeshDataInfo._facetData;\n if (!data.facetNormals) {\n data.facetNormals = new Array();\n }\n if (!data.facetPositions) {\n data.facetPositions = new Array();\n }\n if (!data.facetPartitioning) {\n data.facetPartitioning = new Array();\n }\n data.facetNb = (this.getIndices().length / 3) | 0;\n data.partitioningSubdivisions = data.partitioningSubdivisions ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10\n data.partitioningBBoxRatio = data.partitioningBBoxRatio ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box\n for (let f = 0; f < data.facetNb; f++) {\n data.facetNormals[f] = Vector3.Zero();\n data.facetPositions[f] = Vector3.Zero();\n }\n data.facetDataEnabled = true;\n return this;\n }\n /**\n * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.\n * This method can be called within the render loop.\n * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation\n * @returns the current mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData\n */\n updateFacetData() {\n const data = this._internalAbstractMeshDataInfo._facetData;\n if (!data.facetDataEnabled) {\n this._initFacetData();\n }\n const positions = this.getVerticesData(VertexBuffer.PositionKind);\n const indices = this.getIndices();\n const normals = this.getVerticesData(VertexBuffer.NormalKind);\n const bInfo = this.getBoundingInfo();\n if (data.facetDepthSort && !data.facetDepthSortEnabled) {\n // init arrays, matrix and sort function on first call\n data.facetDepthSortEnabled = true;\n if (indices instanceof Uint16Array) {\n data.depthSortedIndices = new Uint16Array(indices);\n }\n else if (indices instanceof Uint32Array) {\n data.depthSortedIndices = new Uint32Array(indices);\n }\n else {\n let needs32bits = false;\n for (let i = 0; i < indices.length; i++) {\n if (indices[i] > 65535) {\n needs32bits = true;\n break;\n }\n }\n if (needs32bits) {\n data.depthSortedIndices = new Uint32Array(indices);\n }\n else {\n data.depthSortedIndices = new Uint16Array(indices);\n }\n }\n data.facetDepthSortFunction = function (f1, f2) {\n return f2.sqDistance - f1.sqDistance;\n };\n if (!data.facetDepthSortFrom) {\n const camera = this.getScene().activeCamera;\n data.facetDepthSortFrom = camera ? camera.position : Vector3.Zero();\n }\n data.depthSortedFacets = [];\n for (let f = 0; f < data.facetNb; f++) {\n const depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };\n data.depthSortedFacets.push(depthSortedFacet);\n }\n data.invertedMatrix = Matrix.Identity();\n data.facetDepthSortOrigin = Vector3.Zero();\n }\n data.bbSize.x = bInfo.maximum.x - bInfo.minimum.x > Epsilon ? bInfo.maximum.x - bInfo.minimum.x : Epsilon;\n data.bbSize.y = bInfo.maximum.y - bInfo.minimum.y > Epsilon ? bInfo.maximum.y - bInfo.minimum.y : Epsilon;\n data.bbSize.z = bInfo.maximum.z - bInfo.minimum.z > Epsilon ? bInfo.maximum.z - bInfo.minimum.z : Epsilon;\n let bbSizeMax = data.bbSize.x > data.bbSize.y ? data.bbSize.x : data.bbSize.y;\n bbSizeMax = bbSizeMax > data.bbSize.z ? bbSizeMax : data.bbSize.z;\n data.subDiv.max = data.partitioningSubdivisions;\n data.subDiv.X = Math.floor((data.subDiv.max * data.bbSize.x) / bbSizeMax); // adjust the number of subdivisions per axis\n data.subDiv.Y = Math.floor((data.subDiv.max * data.bbSize.y) / bbSizeMax); // according to each bbox size per axis\n data.subDiv.Z = Math.floor((data.subDiv.max * data.bbSize.z) / bbSizeMax);\n data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision\n data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;\n data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;\n // set the parameters for ComputeNormals()\n data.facetParameters.facetNormals = this.getFacetLocalNormals();\n data.facetParameters.facetPositions = this.getFacetLocalPositions();\n data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();\n data.facetParameters.bInfo = bInfo;\n data.facetParameters.bbSize = data.bbSize;\n data.facetParameters.subDiv = data.subDiv;\n data.facetParameters.ratio = this.partitioningBBoxRatio;\n data.facetParameters.depthSort = data.facetDepthSort;\n if (data.facetDepthSort && data.facetDepthSortEnabled) {\n this.computeWorldMatrix(true);\n this._worldMatrix.invertToRef(data.invertedMatrix);\n Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);\n data.facetParameters.distanceTo = data.facetDepthSortOrigin;\n }\n data.facetParameters.depthSortedFacets = data.depthSortedFacets;\n if (normals) {\n VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);\n }\n if (data.facetDepthSort && data.facetDepthSortEnabled) {\n data.depthSortedFacets.sort(data.facetDepthSortFunction);\n const l = (data.depthSortedIndices.length / 3) | 0;\n for (let f = 0; f < l; f++) {\n const sind = data.depthSortedFacets[f].ind;\n data.depthSortedIndices[f * 3] = indices[sind];\n data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];\n data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];\n }\n this.updateIndices(data.depthSortedIndices, undefined, true);\n }\n return this;\n }\n /**\n * Returns the facetLocalNormals array.\n * The normals are expressed in the mesh local spac\n * @returns an array of Vector3\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData\n */\n getFacetLocalNormals() {\n const facetData = this._internalAbstractMeshDataInfo._facetData;\n if (!facetData.facetNormals) {\n this.updateFacetData();\n }\n return facetData.facetNormals;\n }\n /**\n * Returns the facetLocalPositions array.\n * The facet positions are expressed in the mesh local space\n * @returns an array of Vector3\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData\n */\n getFacetLocalPositions() {\n const facetData = this._internalAbstractMeshDataInfo._facetData;\n if (!facetData.facetPositions) {\n this.updateFacetData();\n }\n return facetData.facetPositions;\n }\n /**\n * Returns the facetLocalPartitioning array\n * @returns an array of array of numbers\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData\n */\n getFacetLocalPartitioning() {\n const facetData = this._internalAbstractMeshDataInfo._facetData;\n if (!facetData.facetPartitioning) {\n this.updateFacetData();\n }\n return facetData.facetPartitioning;\n }\n /**\n * Returns the i-th facet position in the world system.\n * This method allocates a new Vector3 per call\n * @param i defines the facet index\n * @returns a new Vector3\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData\n */\n getFacetPosition(i) {\n const pos = Vector3.Zero();\n this.getFacetPositionToRef(i, pos);\n return pos;\n }\n /**\n * Sets the reference Vector3 with the i-th facet position in the world system\n * @param i defines the facet index\n * @param ref defines the target vector\n * @returns the current mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData\n */\n getFacetPositionToRef(i, ref) {\n const localPos = this.getFacetLocalPositions()[i];\n const world = this.getWorldMatrix();\n Vector3.TransformCoordinatesToRef(localPos, world, ref);\n return this;\n }\n /**\n * Returns the i-th facet normal in the world system.\n * This method allocates a new Vector3 per call\n * @param i defines the facet index\n * @returns a new Vector3\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData\n */\n getFacetNormal(i) {\n const norm = Vector3.Zero();\n this.getFacetNormalToRef(i, norm);\n return norm;\n }\n /**\n * Sets the reference Vector3 with the i-th facet normal in the world system\n * @param i defines the facet index\n * @param ref defines the target vector\n * @returns the current mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData\n */\n getFacetNormalToRef(i, ref) {\n const localNorm = this.getFacetLocalNormals()[i];\n Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);\n return this;\n }\n /**\n * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system)\n * @param x defines x coordinate\n * @param y defines y coordinate\n * @param z defines z coordinate\n * @returns the array of facet indexes\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData\n */\n getFacetsAtLocalCoordinates(x, y, z) {\n const bInfo = this.getBoundingInfo();\n const data = this._internalAbstractMeshDataInfo._facetData;\n const ox = Math.floor(((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio) / data.bbSize.x);\n const oy = Math.floor(((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio) / data.bbSize.y);\n const oz = Math.floor(((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio) / data.bbSize.z);\n if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {\n return null;\n }\n return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];\n }\n /**\n * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found\n * @param x defines x coordinate\n * @param y defines y coordinate\n * @param z defines z coordinate\n * @param projected sets as the (x,y,z) world projection on the facet\n * @param checkFace if true (default false), only the facet \"facing\" to (x,y,z) or only the ones \"turning their backs\", according to the parameter \"facing\" are returned\n * @param facing if facing and checkFace are true, only the facet \"facing\" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet \"turning their backs\" to (x, y, z) are returned : negative dot (x, y, z) * facet position\n * @returns the face index if found (or null instead)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData\n */\n getClosestFacetAtCoordinates(x, y, z, projected, checkFace = false, facing = true) {\n const world = this.getWorldMatrix();\n const invMat = TmpVectors.Matrix[5];\n world.invertToRef(invMat);\n const invVect = TmpVectors.Vector3[8];\n Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space\n const closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);\n if (projected) {\n // transform the local computed projected vector to world coordinates\n Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);\n }\n return closest;\n }\n /**\n * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found\n * @param x defines x coordinate\n * @param y defines y coordinate\n * @param z defines z coordinate\n * @param projected sets as the (x,y,z) local projection on the facet\n * @param checkFace if true (default false), only the facet \"facing\" to (x,y,z) or only the ones \"turning their backs\", according to the parameter \"facing\" are returned\n * @param facing if facing and checkFace are true, only the facet \"facing\" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet \"turning their backs\" to (x, y, z) are returned : negative dot (x, y, z) * facet position\n * @returns the face index if found (or null instead)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData\n */\n getClosestFacetAtLocalCoordinates(x, y, z, projected, checkFace = false, facing = true) {\n let closest = null;\n let tmpx = 0.0;\n let tmpy = 0.0;\n let tmpz = 0.0;\n let d = 0.0; // tmp dot facet normal * facet position\n let t0 = 0.0;\n let projx = 0.0;\n let projy = 0.0;\n let projz = 0.0;\n // Get all the facets in the same partitioning block than (x, y, z)\n const facetPositions = this.getFacetLocalPositions();\n const facetNormals = this.getFacetLocalNormals();\n const facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);\n if (!facetsInBlock) {\n return null;\n }\n // Get the closest facet to (x, y, z)\n let shortest = Number.MAX_VALUE; // init distance vars\n let tmpDistance = shortest;\n let fib; // current facet in the block\n let norm; // current facet normal\n let p0; // current facet barycenter position\n // loop on all the facets in the current partitioning block\n for (let idx = 0; idx < facetsInBlock.length; idx++) {\n fib = facetsInBlock[idx];\n norm = facetNormals[fib];\n p0 = facetPositions[fib];\n d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;\n if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {\n // compute (x,y,z) projection on the facet = (projx, projy, projz)\n d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;\n t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);\n projx = x + norm.x * t0;\n projy = y + norm.y * t0;\n projz = z + norm.z * t0;\n tmpx = projx - x;\n tmpy = projy - y;\n tmpz = projz - z;\n tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet\n if (tmpDistance < shortest) {\n // just keep the closest facet to (x, y, z)\n shortest = tmpDistance;\n closest = fib;\n if (projected) {\n projected.x = projx;\n projected.y = projy;\n projected.z = projz;\n }\n }\n }\n }\n return closest;\n }\n /**\n * Returns the object \"parameter\" set with all the expected parameters for facetData computation by ComputeNormals()\n * @returns the parameters\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData\n */\n getFacetDataParameters() {\n return this._internalAbstractMeshDataInfo._facetData.facetParameters;\n }\n /**\n * Disables the feature FacetData and frees the related memory\n * @returns the current mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData\n */\n disableFacetData() {\n const facetData = this._internalAbstractMeshDataInfo._facetData;\n if (facetData.facetDataEnabled) {\n facetData.facetDataEnabled = false;\n facetData.facetPositions = new Array();\n facetData.facetNormals = new Array();\n facetData.facetPartitioning = new Array();\n facetData.facetParameters = null;\n facetData.depthSortedIndices = new Uint32Array(0);\n }\n return this;\n }\n /**\n * Updates the AbstractMesh indices array\n * @param indices defines the data source\n * @param offset defines the offset in the index buffer where to store the new data (can be null)\n * @param gpuMemoryOnly defines a boolean indicating that only the GPU memory must be updated leaving the CPU version of the indices unchanged (false by default)\n * @returns the current mesh\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n updateIndices(indices, offset, gpuMemoryOnly = false) {\n return this;\n }\n /**\n * Creates new normals data for the mesh\n * @param updatable defines if the normal vertex buffer must be flagged as updatable\n * @returns the current mesh\n */\n createNormals(updatable) {\n const positions = this.getVerticesData(VertexBuffer.PositionKind);\n const indices = this.getIndices();\n let normals;\n if (this.isVerticesDataPresent(VertexBuffer.NormalKind)) {\n normals = this.getVerticesData(VertexBuffer.NormalKind);\n }\n else {\n normals = [];\n }\n VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });\n this.setVerticesData(VertexBuffer.NormalKind, normals, updatable);\n return this;\n }\n /**\n * Align the mesh with a normal\n * @param normal defines the normal to use\n * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)\n * @returns the current mesh\n */\n alignWithNormal(normal, upDirection) {\n if (!upDirection) {\n upDirection = Axis.Y;\n }\n const axisX = TmpVectors.Vector3[0];\n const axisZ = TmpVectors.Vector3[1];\n Vector3.CrossToRef(upDirection, normal, axisZ);\n Vector3.CrossToRef(normal, axisZ, axisX);\n if (this.rotationQuaternion) {\n Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);\n }\n else {\n Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);\n }\n return this;\n }\n /** @internal */\n _checkOcclusionQuery() {\n // Will be replaced by correct code if Occlusion queries are referenced\n return false;\n }\n /**\n * Disables the mesh edge rendering mode\n * @returns the currentAbstractMesh\n */\n disableEdgesRendering() {\n throw _WarnImport(\"EdgesRenderer\");\n }\n /**\n * Enables the edge rendering mode on the mesh.\n * This mode makes the mesh edges visible\n * @param epsilon defines the maximal distance between two angles to detect a face\n * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces\n * @param options options to the edge renderer\n * @returns the currentAbstractMesh\n * @see https://www.babylonjs-playground.com/#19O9TU#0\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n enableEdgesRendering(epsilon, checkVerticesInsteadOfIndices, options) {\n throw _WarnImport(\"EdgesRenderer\");\n }\n /**\n * This function returns all of the particle systems in the scene that use the mesh as an emitter.\n * @returns an array of particle systems in the scene that use the mesh as an emitter\n */\n getConnectedParticleSystems() {\n return this._scene.particleSystems.filter((particleSystem) => particleSystem.emitter === this);\n }\n}\n/** No occlusion */\nAbstractMesh.OCCLUSION_TYPE_NONE = 0;\n/** Occlusion set to optimistic */\nAbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;\n/** Occlusion set to strict */\nAbstractMesh.OCCLUSION_TYPE_STRICT = 2;\n/** Use an accurate occlusion algorithm */\nAbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;\n/** Use a conservative occlusion algorithm */\nAbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;\n/** Default culling strategy : this is an exclusion test and it's the more accurate.\n * Test order :\n * Is the bounding sphere outside the frustum ?\n * If not, are the bounding box vertices outside the frustum ?\n * It not, then the cullable object is in the frustum.\n */\nAbstractMesh.CULLINGSTRATEGY_STANDARD = 0;\n/** Culling strategy : Bounding Sphere Only.\n * This is an exclusion test. It's faster than the standard strategy because the bounding box is not tested.\n * It's also less accurate than the standard because some not visible objects can still be selected.\n * Test : is the bounding sphere outside the frustum ?\n * If not, then the cullable object is in the frustum.\n */\nAbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;\n/** Culling strategy : Optimistic Inclusion.\n * This in an inclusion test first, then the standard exclusion test.\n * This can be faster when a cullable object is expected to be almost always in the camera frustum.\n * This could also be a little slower than the standard test when the tested object center is not the frustum but one of its bounding box vertex is still inside.\n * Anyway, it's as accurate as the standard strategy.\n * Test :\n * Is the cullable object bounding sphere center in the frustum ?\n * If not, apply the default culling strategy.\n */\nAbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION = 2;\n/** Culling strategy : Optimistic Inclusion then Bounding Sphere Only.\n * This in an inclusion test first, then the bounding sphere only exclusion test.\n * This can be the fastest test when a cullable object is expected to be almost always in the camera frustum.\n * This could also be a little slower than the BoundingSphereOnly strategy when the tested object center is not in the frustum but its bounding sphere still intersects it.\n * It's less accurate than the standard strategy and as accurate as the BoundingSphereOnly strategy.\n * Test :\n * Is the cullable object bounding sphere center in the frustum ?\n * If not, apply the Bounding Sphere Only strategy. No Bounding Box is tested here.\n */\nAbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY = 3;\nRegisterClass(\"BABYLON.AbstractMesh\", AbstractMesh);\n//# sourceMappingURL=abstractMesh.js.map","import { Vector3 } from \"../Maths/math.vector.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { VertexData } from \"../Meshes/mesh.vertexData.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { SubMesh } from \"../Meshes/subMesh.js\";\nimport { SceneLoaderFlags } from \"../Loading/sceneLoaderFlags.js\";\nimport { BoundingInfo } from \"../Culling/boundingInfo.js\";\n\nimport { Tools } from \"../Misc/tools.js\";\nimport { Tags } from \"../Misc/tags.js\";\nimport { extractMinAndMax } from \"../Maths/math.functions.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { CompatibilityOptions } from \"../Compat/compatibilityOptions.js\";\n/**\n * Class used to store geometry data (vertex buffers + index buffer)\n */\nexport class Geometry {\n /**\n * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y\n */\n get boundingBias() {\n return this._boundingBias;\n }\n /**\n * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y\n */\n set boundingBias(value) {\n if (this._boundingBias) {\n this._boundingBias.copyFrom(value);\n }\n else {\n this._boundingBias = value.clone();\n }\n this._updateBoundingInfo(true, null);\n }\n /**\n * Static function used to attach a new empty geometry to a mesh\n * @param mesh defines the mesh to attach the geometry to\n * @returns the new Geometry\n */\n static CreateGeometryForMesh(mesh) {\n const geometry = new Geometry(Geometry.RandomId(), mesh.getScene());\n geometry.applyToMesh(mesh);\n return geometry;\n }\n /** Get the list of meshes using this geometry */\n get meshes() {\n return this._meshes;\n }\n /**\n * Creates a new geometry\n * @param id defines the unique ID\n * @param scene defines the hosting scene\n * @param vertexData defines the VertexData used to get geometry data\n * @param updatable defines if geometry must be updatable (false by default)\n * @param mesh defines the mesh that will be associated with the geometry\n */\n constructor(id, scene, vertexData, updatable = false, mesh = null) {\n /**\n * Gets the delay loading state of the geometry (none by default which means not delayed)\n */\n this.delayLoadState = 0;\n this._totalVertices = 0;\n this._isDisposed = false;\n this._indexBufferIsUpdatable = false;\n this._positionsCache = [];\n /** @internal */\n this._parentContainer = null;\n /**\n * If set to true (false by default), the bounding info applied to the meshes sharing this geometry will be the bounding info defined at the class level\n * and won't be computed based on the vertex positions (which is what we get when useBoundingInfoFromGeometry = false)\n */\n this.useBoundingInfoFromGeometry = false;\n this._scene = scene || EngineStore.LastCreatedScene;\n if (!this._scene) {\n return;\n }\n this.id = id;\n this.uniqueId = this._scene.getUniqueId();\n this._engine = this._scene.getEngine();\n this._meshes = [];\n //Init vertex buffer cache\n this._vertexBuffers = {};\n this._indices = [];\n this._updatable = updatable;\n // vertexData\n if (vertexData) {\n this.setAllVerticesData(vertexData, updatable);\n }\n else {\n this._totalVertices = 0;\n }\n if (this._engine.getCaps().vertexArrayObject) {\n this._vertexArrayObjects = {};\n }\n // applyToMesh\n if (mesh) {\n this.applyToMesh(mesh);\n mesh.computeWorldMatrix(true);\n }\n }\n /**\n * Gets the current extend of the geometry\n */\n get extend() {\n return this._extend;\n }\n /**\n * Gets the hosting scene\n * @returns the hosting Scene\n */\n getScene() {\n return this._scene;\n }\n /**\n * Gets the hosting engine\n * @returns the hosting Engine\n */\n getEngine() {\n return this._engine;\n }\n /**\n * Defines if the geometry is ready to use\n * @returns true if the geometry is ready to be used\n */\n isReady() {\n return this.delayLoadState === 1 || this.delayLoadState === 0;\n }\n /**\n * Gets a value indicating that the geometry should not be serialized\n */\n get doNotSerialize() {\n for (let index = 0; index < this._meshes.length; index++) {\n if (!this._meshes[index].doNotSerialize) {\n return false;\n }\n }\n return true;\n }\n /** @internal */\n _rebuild() {\n if (this._vertexArrayObjects) {\n this._vertexArrayObjects = {};\n }\n // Index buffer\n if (this._meshes.length !== 0 && this._indices) {\n this._indexBuffer = this._engine.createIndexBuffer(this._indices, this._updatable);\n }\n // Vertex buffers\n for (const key in this._vertexBuffers) {\n const vertexBuffer = this._vertexBuffers[key];\n vertexBuffer._rebuild();\n }\n }\n /**\n * Affects all geometry data in one call\n * @param vertexData defines the geometry data\n * @param updatable defines if the geometry must be flagged as updatable (false as default)\n */\n setAllVerticesData(vertexData, updatable) {\n vertexData.applyToGeometry(this, updatable);\n this._notifyUpdate();\n }\n /**\n * Set specific vertex data\n * @param kind defines the data kind (Position, normal, etc...)\n * @param data defines the vertex data to use\n * @param updatable defines if the vertex must be flagged as updatable (false as default)\n * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified\n */\n setVerticesData(kind, data, updatable = false, stride) {\n if (updatable && Array.isArray(data)) {\n // to avoid converting to Float32Array at each draw call in engine.updateDynamicVertexBuffer, we make the conversion a single time here\n data = new Float32Array(data);\n }\n const buffer = new VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);\n this.setVerticesBuffer(buffer);\n }\n /**\n * Removes a specific vertex data\n * @param kind defines the data kind (Position, normal, etc...)\n */\n removeVerticesData(kind) {\n if (this._vertexBuffers[kind]) {\n this._vertexBuffers[kind].dispose();\n delete this._vertexBuffers[kind];\n }\n if (this._vertexArrayObjects) {\n this._disposeVertexArrayObjects();\n }\n }\n /**\n * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data\n * @param buffer defines the vertex buffer to use\n * @param totalVertices defines the total number of vertices for position kind (could be null)\n * @param disposeExistingBuffer disposes the existing buffer, if any (default: true)\n */\n setVerticesBuffer(buffer, totalVertices = null, disposeExistingBuffer = true) {\n const kind = buffer.getKind();\n if (this._vertexBuffers[kind] && disposeExistingBuffer) {\n this._vertexBuffers[kind].dispose();\n }\n if (buffer._buffer) {\n buffer._buffer._increaseReferences();\n }\n this._vertexBuffers[kind] = buffer;\n const meshes = this._meshes;\n const numOfMeshes = meshes.length;\n if (kind === VertexBuffer.PositionKind) {\n const data = buffer.getData();\n if (totalVertices != null) {\n this._totalVertices = totalVertices;\n }\n else {\n if (data != null) {\n this._totalVertices = data.length / (buffer.type === VertexBuffer.BYTE ? buffer.byteStride : buffer.byteStride / 4);\n }\n }\n this._updateExtend(data);\n this._resetPointsArrayCache();\n for (let index = 0; index < numOfMeshes; index++) {\n const mesh = meshes[index];\n mesh.buildBoundingInfo(this._extend.minimum, this._extend.maximum);\n mesh._createGlobalSubMesh(mesh.isUnIndexed);\n mesh.computeWorldMatrix(true);\n mesh.synchronizeInstances();\n }\n }\n this._notifyUpdate(kind);\n }\n /**\n * Update a specific vertex buffer\n * This function will directly update the underlying DataBuffer according to the passed numeric array or Float32Array\n * It will do nothing if the buffer is not updatable\n * @param kind defines the data kind (Position, normal, etc...)\n * @param data defines the data to use\n * @param offset defines the offset in the target buffer where to store the data\n * @param useBytes set to true if the offset is in bytes\n */\n updateVerticesDataDirectly(kind, data, offset, useBytes = false) {\n const vertexBuffer = this.getVertexBuffer(kind);\n if (!vertexBuffer) {\n return;\n }\n vertexBuffer.updateDirectly(data, offset, useBytes);\n this._notifyUpdate(kind);\n }\n /**\n * Update a specific vertex buffer\n * This function will create a new buffer if the current one is not updatable\n * @param kind defines the data kind (Position, normal, etc...)\n * @param data defines the data to use\n * @param updateExtends defines if the geometry extends must be recomputed (false by default)\n */\n updateVerticesData(kind, data, updateExtends = false) {\n const vertexBuffer = this.getVertexBuffer(kind);\n if (!vertexBuffer) {\n return;\n }\n vertexBuffer.update(data);\n if (kind === VertexBuffer.PositionKind) {\n this._updateBoundingInfo(updateExtends, data);\n }\n this._notifyUpdate(kind);\n }\n _updateBoundingInfo(updateExtends, data) {\n if (updateExtends) {\n this._updateExtend(data);\n }\n this._resetPointsArrayCache();\n if (updateExtends) {\n const meshes = this._meshes;\n for (const mesh of meshes) {\n if (mesh.hasBoundingInfo) {\n mesh.getBoundingInfo().reConstruct(this._extend.minimum, this._extend.maximum);\n }\n else {\n mesh.buildBoundingInfo(this._extend.minimum, this._extend.maximum);\n }\n const subMeshes = mesh.subMeshes;\n for (const subMesh of subMeshes) {\n subMesh.refreshBoundingInfo();\n }\n }\n }\n }\n /**\n * @internal\n */\n _bind(effect, indexToBind, overrideVertexBuffers, overrideVertexArrayObjects) {\n if (!effect) {\n return;\n }\n if (indexToBind === undefined) {\n indexToBind = this._indexBuffer;\n }\n const vbs = this.getVertexBuffers();\n if (!vbs) {\n return;\n }\n if (indexToBind != this._indexBuffer || (!this._vertexArrayObjects && !overrideVertexArrayObjects)) {\n this._engine.bindBuffers(vbs, indexToBind, effect, overrideVertexBuffers);\n return;\n }\n const vaos = overrideVertexArrayObjects ? overrideVertexArrayObjects : this._vertexArrayObjects;\n // Using VAO\n if (!vaos[effect.key]) {\n vaos[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect, overrideVertexBuffers);\n }\n this._engine.bindVertexArrayObject(vaos[effect.key], indexToBind);\n }\n /**\n * Gets total number of vertices\n * @returns the total number of vertices\n */\n getTotalVertices() {\n if (!this.isReady()) {\n return 0;\n }\n return this._totalVertices;\n }\n /**\n * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.\n * @param kind defines the data kind (Position, normal, etc...)\n * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes\n * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it\n * @returns a float array containing vertex data\n */\n getVerticesData(kind, copyWhenShared, forceCopy) {\n const vertexBuffer = this.getVertexBuffer(kind);\n if (!vertexBuffer) {\n return null;\n }\n return vertexBuffer.getFloatData(this._totalVertices, forceCopy || (copyWhenShared && this._meshes.length !== 1));\n }\n /**\n * Returns a boolean defining if the vertex data for the requested `kind` is updatable\n * @param kind defines the data kind (Position, normal, etc...)\n * @returns true if the vertex buffer with the specified kind is updatable\n */\n isVertexBufferUpdatable(kind) {\n const vb = this._vertexBuffers[kind];\n if (!vb) {\n return false;\n }\n return vb.isUpdatable();\n }\n /**\n * Gets a specific vertex buffer\n * @param kind defines the data kind (Position, normal, etc...)\n * @returns a VertexBuffer\n */\n getVertexBuffer(kind) {\n if (!this.isReady()) {\n return null;\n }\n return this._vertexBuffers[kind];\n }\n /**\n * Returns all vertex buffers\n * @returns an object holding all vertex buffers indexed by kind\n */\n getVertexBuffers() {\n if (!this.isReady()) {\n return null;\n }\n return this._vertexBuffers;\n }\n /**\n * Gets a boolean indicating if specific vertex buffer is present\n * @param kind defines the data kind (Position, normal, etc...)\n * @returns true if data is present\n */\n isVerticesDataPresent(kind) {\n if (!this._vertexBuffers) {\n if (this._delayInfo) {\n return this._delayInfo.indexOf(kind) !== -1;\n }\n return false;\n }\n return this._vertexBuffers[kind] !== undefined;\n }\n /**\n * Gets a list of all attached data kinds (Position, normal, etc...)\n * @returns a list of string containing all kinds\n */\n getVerticesDataKinds() {\n const result = [];\n let kind;\n if (!this._vertexBuffers && this._delayInfo) {\n for (kind in this._delayInfo) {\n result.push(kind);\n }\n }\n else {\n for (kind in this._vertexBuffers) {\n result.push(kind);\n }\n }\n return result;\n }\n /**\n * Update index buffer\n * @param indices defines the indices to store in the index buffer\n * @param offset defines the offset in the target buffer where to store the data\n * @param gpuMemoryOnly defines a boolean indicating that only the GPU memory must be updated leaving the CPU version of the indices unchanged (false by default)\n */\n updateIndices(indices, offset, gpuMemoryOnly = false) {\n if (!this._indexBuffer) {\n return;\n }\n if (!this._indexBufferIsUpdatable) {\n this.setIndices(indices, null, true);\n }\n else {\n const needToUpdateSubMeshes = indices.length !== this._indices.length;\n if (!gpuMemoryOnly) {\n this._indices = indices.slice();\n }\n this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);\n if (needToUpdateSubMeshes) {\n for (const mesh of this._meshes) {\n mesh._createGlobalSubMesh(true);\n }\n }\n }\n }\n /**\n * Creates a new index buffer\n * @param indices defines the indices to store in the index buffer\n * @param totalVertices defines the total number of vertices (could be null)\n * @param updatable defines if the index buffer must be flagged as updatable (false by default)\n */\n setIndices(indices, totalVertices = null, updatable = false) {\n if (this._indexBuffer) {\n this._engine._releaseBuffer(this._indexBuffer);\n }\n this._indices = indices;\n this._indexBufferIsUpdatable = updatable;\n if (this._meshes.length !== 0 && this._indices) {\n this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);\n }\n if (totalVertices != undefined) {\n // including null and undefined\n this._totalVertices = totalVertices;\n }\n for (const mesh of this._meshes) {\n mesh._createGlobalSubMesh(true);\n mesh.synchronizeInstances();\n }\n this._notifyUpdate();\n }\n /**\n * Return the total number of indices\n * @returns the total number of indices\n */\n getTotalIndices() {\n if (!this.isReady()) {\n return 0;\n }\n return this._indices.length;\n }\n /**\n * Gets the index buffer array\n * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes\n * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it\n * @returns the index buffer array\n */\n getIndices(copyWhenShared, forceCopy) {\n if (!this.isReady()) {\n return null;\n }\n const orig = this._indices;\n if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {\n return orig;\n }\n else {\n return orig.slice();\n }\n }\n /**\n * Gets the index buffer\n * @returns the index buffer\n */\n getIndexBuffer() {\n if (!this.isReady()) {\n return null;\n }\n return this._indexBuffer;\n }\n /**\n * @internal\n */\n _releaseVertexArrayObject(effect = null) {\n if (!effect || !this._vertexArrayObjects) {\n return;\n }\n if (this._vertexArrayObjects[effect.key]) {\n this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);\n delete this._vertexArrayObjects[effect.key];\n }\n }\n /**\n * Release the associated resources for a specific mesh\n * @param mesh defines the source mesh\n * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it\n */\n releaseForMesh(mesh, shouldDispose) {\n const meshes = this._meshes;\n const index = meshes.indexOf(mesh);\n if (index === -1) {\n return;\n }\n meshes.splice(index, 1);\n if (this._vertexArrayObjects) {\n mesh._invalidateInstanceVertexArrayObject();\n }\n mesh._geometry = null;\n if (meshes.length === 0 && shouldDispose) {\n this.dispose();\n }\n }\n /**\n * Apply current geometry to a given mesh\n * @param mesh defines the mesh to apply geometry to\n */\n applyToMesh(mesh) {\n if (mesh._geometry === this) {\n return;\n }\n const previousGeometry = mesh._geometry;\n if (previousGeometry) {\n previousGeometry.releaseForMesh(mesh);\n }\n if (this._vertexArrayObjects) {\n mesh._invalidateInstanceVertexArrayObject();\n }\n const meshes = this._meshes;\n // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()\n mesh._geometry = this;\n mesh._internalAbstractMeshDataInfo._positions = null;\n this._scene.pushGeometry(this);\n meshes.push(mesh);\n if (this.isReady()) {\n this._applyToMesh(mesh);\n }\n else if (this._boundingInfo) {\n mesh.setBoundingInfo(this._boundingInfo);\n }\n }\n _updateExtend(data = null) {\n if (this.useBoundingInfoFromGeometry && this._boundingInfo) {\n this._extend = {\n minimum: this._boundingInfo.minimum.clone(),\n maximum: this._boundingInfo.maximum.clone(),\n };\n }\n else {\n if (!data) {\n data = this.getVerticesData(VertexBuffer.PositionKind);\n // This can happen if the buffer comes from a Hardware Buffer where\n // The data have not been uploaded by Babylon. (ex: Compute Shaders and Storage Buffers)\n if (!data) {\n return;\n }\n }\n this._extend = extractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);\n }\n }\n _applyToMesh(mesh) {\n const numOfMeshes = this._meshes.length;\n // vertexBuffers\n for (const kind in this._vertexBuffers) {\n if (numOfMeshes === 1) {\n this._vertexBuffers[kind].create();\n }\n if (kind === VertexBuffer.PositionKind) {\n if (!this._extend) {\n this._updateExtend();\n }\n mesh.buildBoundingInfo(this._extend.minimum, this._extend.maximum);\n mesh._createGlobalSubMesh(mesh.isUnIndexed);\n //bounding info was just created again, world matrix should be applied again.\n mesh._updateBoundingInfo();\n }\n }\n // indexBuffer\n if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {\n this._indexBuffer = this._engine.createIndexBuffer(this._indices, this._updatable);\n }\n // morphTargets\n mesh._syncGeometryWithMorphTargetManager();\n // instances\n mesh.synchronizeInstances();\n }\n _notifyUpdate(kind) {\n if (this.onGeometryUpdated) {\n this.onGeometryUpdated(this, kind);\n }\n if (this._vertexArrayObjects) {\n this._disposeVertexArrayObjects();\n }\n for (const mesh of this._meshes) {\n mesh._markSubMeshesAsAttributesDirty();\n }\n }\n /**\n * Load the geometry if it was flagged as delay loaded\n * @param scene defines the hosting scene\n * @param onLoaded defines a callback called when the geometry is loaded\n */\n load(scene, onLoaded) {\n if (this.delayLoadState === 2) {\n return;\n }\n if (this.isReady()) {\n if (onLoaded) {\n onLoaded();\n }\n return;\n }\n this.delayLoadState = 2;\n this._queueLoad(scene, onLoaded);\n }\n _queueLoad(scene, onLoaded) {\n if (!this.delayLoadingFile) {\n return;\n }\n scene.addPendingData(this);\n scene._loadFile(this.delayLoadingFile, (data) => {\n if (!this._delayLoadingFunction) {\n return;\n }\n this._delayLoadingFunction(JSON.parse(data), this);\n this.delayLoadState = 1;\n this._delayInfo = [];\n scene.removePendingData(this);\n const meshes = this._meshes;\n const numOfMeshes = meshes.length;\n for (let index = 0; index < numOfMeshes; index++) {\n this._applyToMesh(meshes[index]);\n }\n if (onLoaded) {\n onLoaded();\n }\n }, undefined, true);\n }\n /**\n * Invert the geometry to move from a right handed system to a left handed one.\n */\n toLeftHanded() {\n // Flip faces\n const tIndices = this.getIndices(false);\n if (tIndices != null && tIndices.length > 0) {\n for (let i = 0; i < tIndices.length; i += 3) {\n const tTemp = tIndices[i + 0];\n tIndices[i + 0] = tIndices[i + 2];\n tIndices[i + 2] = tTemp;\n }\n this.setIndices(tIndices);\n }\n // Negate position.z\n const tPositions = this.getVerticesData(VertexBuffer.PositionKind, false);\n if (tPositions != null && tPositions.length > 0) {\n for (let i = 0; i < tPositions.length; i += 3) {\n tPositions[i + 2] = -tPositions[i + 2];\n }\n this.setVerticesData(VertexBuffer.PositionKind, tPositions, false);\n }\n // Negate normal.z\n const tNormals = this.getVerticesData(VertexBuffer.NormalKind, false);\n if (tNormals != null && tNormals.length > 0) {\n for (let i = 0; i < tNormals.length; i += 3) {\n tNormals[i + 2] = -tNormals[i + 2];\n }\n this.setVerticesData(VertexBuffer.NormalKind, tNormals, false);\n }\n }\n // Cache\n /** @internal */\n _resetPointsArrayCache() {\n this._positions = null;\n }\n /** @internal */\n _generatePointsArray() {\n if (this._positions) {\n return true;\n }\n const data = this.getVerticesData(VertexBuffer.PositionKind);\n if (!data || data.length === 0) {\n return false;\n }\n for (let index = this._positionsCache.length * 3, arrayIdx = this._positionsCache.length; index < data.length; index += 3, ++arrayIdx) {\n this._positionsCache[arrayIdx] = Vector3.FromArray(data, index);\n }\n for (let index = 0, arrayIdx = 0; index < data.length; index += 3, ++arrayIdx) {\n this._positionsCache[arrayIdx].set(data[0 + index], data[1 + index], data[2 + index]);\n }\n // just in case the number of positions was reduced, splice the array\n this._positionsCache.length = data.length / 3;\n this._positions = this._positionsCache;\n return true;\n }\n /**\n * Gets a value indicating if the geometry is disposed\n * @returns true if the geometry was disposed\n */\n isDisposed() {\n return this._isDisposed;\n }\n _disposeVertexArrayObjects() {\n if (this._vertexArrayObjects) {\n for (const kind in this._vertexArrayObjects) {\n this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);\n }\n this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported\n const meshes = this._meshes;\n const numOfMeshes = meshes.length;\n for (let index = 0; index < numOfMeshes; index++) {\n meshes[index]._invalidateInstanceVertexArrayObject();\n }\n }\n }\n /**\n * Free all associated resources\n */\n dispose() {\n const meshes = this._meshes;\n const numOfMeshes = meshes.length;\n let index;\n for (index = 0; index < numOfMeshes; index++) {\n this.releaseForMesh(meshes[index]);\n }\n this._meshes.length = 0;\n this._disposeVertexArrayObjects();\n for (const kind in this._vertexBuffers) {\n this._vertexBuffers[kind].dispose();\n }\n this._vertexBuffers = {};\n this._totalVertices = 0;\n if (this._indexBuffer) {\n this._engine._releaseBuffer(this._indexBuffer);\n }\n this._indexBuffer = null;\n this._indices = [];\n this.delayLoadState = 0;\n this.delayLoadingFile = null;\n this._delayLoadingFunction = null;\n this._delayInfo = [];\n this._boundingInfo = null;\n this._scene.removeGeometry(this);\n if (this._parentContainer) {\n const index = this._parentContainer.geometries.indexOf(this);\n if (index > -1) {\n this._parentContainer.geometries.splice(index, 1);\n }\n this._parentContainer = null;\n }\n this._isDisposed = true;\n }\n /**\n * Clone the current geometry into a new geometry\n * @param id defines the unique ID of the new geometry\n * @returns a new geometry object\n */\n copy(id) {\n const vertexData = new VertexData();\n vertexData.indices = [];\n const indices = this.getIndices();\n if (indices) {\n for (let index = 0; index < indices.length; index++) {\n vertexData.indices.push(indices[index]);\n }\n }\n let updatable = false;\n let stopChecking = false;\n let kind;\n for (kind in this._vertexBuffers) {\n // using slice() to make a copy of the array and not just reference it\n const data = this.getVerticesData(kind);\n if (data) {\n if (data instanceof Float32Array) {\n vertexData.set(new Float32Array(data), kind);\n }\n else {\n vertexData.set(data.slice(0), kind);\n }\n if (!stopChecking) {\n const vb = this.getVertexBuffer(kind);\n if (vb) {\n updatable = vb.isUpdatable();\n stopChecking = !updatable;\n }\n }\n }\n }\n const geometry = new Geometry(id, this._scene, vertexData, updatable);\n geometry.delayLoadState = this.delayLoadState;\n geometry.delayLoadingFile = this.delayLoadingFile;\n geometry._delayLoadingFunction = this._delayLoadingFunction;\n for (kind in this._delayInfo) {\n geometry._delayInfo = geometry._delayInfo || [];\n geometry._delayInfo.push(kind);\n }\n // Bounding info\n geometry._boundingInfo = new BoundingInfo(this._extend.minimum, this._extend.maximum);\n return geometry;\n }\n /**\n * Serialize the current geometry info (and not the vertices data) into a JSON object\n * @returns a JSON representation of the current geometry data (without the vertices data)\n */\n serialize() {\n const serializationObject = {};\n serializationObject.id = this.id;\n serializationObject.uniqueId = this.uniqueId;\n serializationObject.updatable = this._updatable;\n if (Tags && Tags.HasTags(this)) {\n serializationObject.tags = Tags.GetTags(this);\n }\n return serializationObject;\n }\n _toNumberArray(origin) {\n if (Array.isArray(origin)) {\n return origin;\n }\n else {\n return Array.prototype.slice.call(origin);\n }\n }\n /**\n * Release any memory retained by the cached data on the Geometry.\n *\n * Call this function to reduce memory footprint of the mesh.\n * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)\n */\n clearCachedData() {\n this._indices = [];\n this._resetPointsArrayCache();\n for (const vbName in this._vertexBuffers) {\n if (!Object.prototype.hasOwnProperty.call(this._vertexBuffers, vbName)) {\n continue;\n }\n this._vertexBuffers[vbName]._buffer._data = null;\n }\n }\n /**\n * Serialize all vertices data into a JSON object\n * @returns a JSON representation of the current geometry data\n */\n serializeVerticeData() {\n const serializationObject = this.serialize();\n if (this.isVerticesDataPresent(VertexBuffer.PositionKind)) {\n serializationObject.positions = this._toNumberArray(this.getVerticesData(VertexBuffer.PositionKind));\n if (this.isVertexBufferUpdatable(VertexBuffer.PositionKind)) {\n serializationObject.positions._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(VertexBuffer.NormalKind)) {\n serializationObject.normals = this._toNumberArray(this.getVerticesData(VertexBuffer.NormalKind));\n if (this.isVertexBufferUpdatable(VertexBuffer.NormalKind)) {\n serializationObject.normals._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(VertexBuffer.TangentKind)) {\n serializationObject.tangents = this._toNumberArray(this.getVerticesData(VertexBuffer.TangentKind));\n if (this.isVertexBufferUpdatable(VertexBuffer.TangentKind)) {\n serializationObject.tangents._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(VertexBuffer.UVKind)) {\n serializationObject.uvs = this._toNumberArray(this.getVerticesData(VertexBuffer.UVKind));\n if (this.isVertexBufferUpdatable(VertexBuffer.UVKind)) {\n serializationObject.uvs._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(VertexBuffer.UV2Kind)) {\n serializationObject.uv2s = this._toNumberArray(this.getVerticesData(VertexBuffer.UV2Kind));\n if (this.isVertexBufferUpdatable(VertexBuffer.UV2Kind)) {\n serializationObject.uv2s._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(VertexBuffer.UV3Kind)) {\n serializationObject.uv3s = this._toNumberArray(this.getVerticesData(VertexBuffer.UV3Kind));\n if (this.isVertexBufferUpdatable(VertexBuffer.UV3Kind)) {\n serializationObject.uv3s._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(VertexBuffer.UV4Kind)) {\n serializationObject.uv4s = this._toNumberArray(this.getVerticesData(VertexBuffer.UV4Kind));\n if (this.isVertexBufferUpdatable(VertexBuffer.UV4Kind)) {\n serializationObject.uv4s._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(VertexBuffer.UV5Kind)) {\n serializationObject.uv5s = this._toNumberArray(this.getVerticesData(VertexBuffer.UV5Kind));\n if (this.isVertexBufferUpdatable(VertexBuffer.UV5Kind)) {\n serializationObject.uv5s._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(VertexBuffer.UV6Kind)) {\n serializationObject.uv6s = this._toNumberArray(this.getVerticesData(VertexBuffer.UV6Kind));\n if (this.isVertexBufferUpdatable(VertexBuffer.UV6Kind)) {\n serializationObject.uv6s._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(VertexBuffer.ColorKind)) {\n serializationObject.colors = this._toNumberArray(this.getVerticesData(VertexBuffer.ColorKind));\n if (this.isVertexBufferUpdatable(VertexBuffer.ColorKind)) {\n serializationObject.colors._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) {\n serializationObject.matricesIndices = this._toNumberArray(this.getVerticesData(VertexBuffer.MatricesIndicesKind));\n serializationObject.matricesIndices._isExpanded = true;\n if (this.isVertexBufferUpdatable(VertexBuffer.MatricesIndicesKind)) {\n serializationObject.matricesIndices._updatable = true;\n }\n }\n if (this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {\n serializationObject.matricesWeights = this._toNumberArray(this.getVerticesData(VertexBuffer.MatricesWeightsKind));\n if (this.isVertexBufferUpdatable(VertexBuffer.MatricesWeightsKind)) {\n serializationObject.matricesWeights._updatable = true;\n }\n }\n serializationObject.indices = this._toNumberArray(this.getIndices());\n return serializationObject;\n }\n // Statics\n /**\n * Extracts a clone of a mesh geometry\n * @param mesh defines the source mesh\n * @param id defines the unique ID of the new geometry object\n * @returns the new geometry object\n */\n static ExtractFromMesh(mesh, id) {\n const geometry = mesh._geometry;\n if (!geometry) {\n return null;\n }\n return geometry.copy(id);\n }\n /**\n * You should now use Tools.RandomId(), this method is still here for legacy reasons.\n * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523\n * Be aware Math.random() could cause collisions, but:\n * \"All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide\"\n * @returns a string containing a new GUID\n */\n static RandomId() {\n return Tools.RandomId();\n }\n static _GetGeometryByLoadedUniqueId(uniqueId, scene) {\n for (let index = 0; index < scene.geometries.length; index++) {\n if (scene.geometries[index]._loadedUniqueId === uniqueId) {\n return scene.geometries[index];\n }\n }\n return null;\n }\n /**\n * @internal\n */\n static _ImportGeometry(parsedGeometry, mesh) {\n const scene = mesh.getScene();\n // Geometry\n const geometryUniqueId = parsedGeometry.geometryUniqueId;\n const geometryId = parsedGeometry.geometryId;\n if (geometryUniqueId || geometryId) {\n const geometry = geometryUniqueId ? this._GetGeometryByLoadedUniqueId(geometryUniqueId, scene) : scene.getGeometryById(geometryId);\n if (geometry) {\n geometry.applyToMesh(mesh);\n }\n }\n else if (parsedGeometry instanceof ArrayBuffer) {\n const binaryInfo = mesh._binaryInfo;\n if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {\n const positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);\n mesh.setVerticesData(VertexBuffer.PositionKind, positionsData, false);\n }\n if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {\n const normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);\n mesh.setVerticesData(VertexBuffer.NormalKind, normalsData, false);\n }\n if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {\n const tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);\n mesh.setVerticesData(VertexBuffer.TangentKind, tangentsData, false);\n }\n if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {\n const uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);\n if (CompatibilityOptions.UseOpenGLOrientationForUV) {\n for (let index = 1; index < uvsData.length; index += 2) {\n uvsData[index] = 1 - uvsData[index];\n }\n }\n mesh.setVerticesData(VertexBuffer.UVKind, uvsData, false);\n }\n if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {\n const uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);\n if (CompatibilityOptions.UseOpenGLOrientationForUV) {\n for (let index = 1; index < uvs2Data.length; index += 2) {\n uvs2Data[index] = 1 - uvs2Data[index];\n }\n }\n mesh.setVerticesData(VertexBuffer.UV2Kind, uvs2Data, false);\n }\n if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {\n const uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);\n if (CompatibilityOptions.UseOpenGLOrientationForUV) {\n for (let index = 1; index < uvs3Data.length; index += 2) {\n uvs3Data[index] = 1 - uvs3Data[index];\n }\n }\n mesh.setVerticesData(VertexBuffer.UV3Kind, uvs3Data, false);\n }\n if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {\n const uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);\n if (CompatibilityOptions.UseOpenGLOrientationForUV) {\n for (let index = 1; index < uvs4Data.length; index += 2) {\n uvs4Data[index] = 1 - uvs4Data[index];\n }\n }\n mesh.setVerticesData(VertexBuffer.UV4Kind, uvs4Data, false);\n }\n if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {\n const uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);\n if (CompatibilityOptions.UseOpenGLOrientationForUV) {\n for (let index = 1; index < uvs5Data.length; index += 2) {\n uvs5Data[index] = 1 - uvs5Data[index];\n }\n }\n mesh.setVerticesData(VertexBuffer.UV5Kind, uvs5Data, false);\n }\n if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {\n const uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);\n if (CompatibilityOptions.UseOpenGLOrientationForUV) {\n for (let index = 1; index < uvs6Data.length; index += 2) {\n uvs6Data[index] = 1 - uvs6Data[index];\n }\n }\n mesh.setVerticesData(VertexBuffer.UV6Kind, uvs6Data, false);\n }\n if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {\n const colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);\n mesh.setVerticesData(VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);\n }\n if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {\n const matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);\n const floatIndices = [];\n for (let i = 0; i < matricesIndicesData.length; i++) {\n const index = matricesIndicesData[i];\n floatIndices.push(index & 0x000000ff);\n floatIndices.push((index & 0x0000ff00) >> 8);\n floatIndices.push((index & 0x00ff0000) >> 16);\n floatIndices.push((index >> 24) & 0xff); // & 0xFF to convert to v + 256 if v < 0\n }\n mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, floatIndices, false);\n }\n if (binaryInfo.matricesIndicesExtraAttrDesc && binaryInfo.matricesIndicesExtraAttrDesc.count > 0) {\n const matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesExtraAttrDesc.offset, binaryInfo.matricesIndicesExtraAttrDesc.count);\n const floatIndices = [];\n for (let i = 0; i < matricesIndicesData.length; i++) {\n const index = matricesIndicesData[i];\n floatIndices.push(index & 0x000000ff);\n floatIndices.push((index & 0x0000ff00) >> 8);\n floatIndices.push((index & 0x00ff0000) >> 16);\n floatIndices.push((index >> 24) & 0xff); // & 0xFF to convert to v + 256 if v < 0\n }\n mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);\n }\n if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {\n const matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);\n mesh.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);\n }\n if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {\n const indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);\n mesh.setIndices(indicesData, null);\n }\n if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {\n const subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);\n mesh.subMeshes = [];\n for (let i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {\n const materialIndex = subMeshesData[i * 5 + 0];\n const verticesStart = subMeshesData[i * 5 + 1];\n const verticesCount = subMeshesData[i * 5 + 2];\n const indexStart = subMeshesData[i * 5 + 3];\n const indexCount = subMeshesData[i * 5 + 4];\n SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);\n }\n }\n }\n else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {\n mesh.setVerticesData(VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);\n mesh.setVerticesData(VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);\n if (parsedGeometry.tangents) {\n mesh.setVerticesData(VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);\n }\n if (parsedGeometry.uvs) {\n mesh.setVerticesData(VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);\n }\n if (parsedGeometry.uvs2) {\n mesh.setVerticesData(VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);\n }\n if (parsedGeometry.uvs3) {\n mesh.setVerticesData(VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);\n }\n if (parsedGeometry.uvs4) {\n mesh.setVerticesData(VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);\n }\n if (parsedGeometry.uvs5) {\n mesh.setVerticesData(VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);\n }\n if (parsedGeometry.uvs6) {\n mesh.setVerticesData(VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);\n }\n if (parsedGeometry.colors) {\n mesh.setVerticesData(VertexBuffer.ColorKind, Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);\n }\n if (parsedGeometry.matricesIndices) {\n if (!parsedGeometry.matricesIndices._isExpanded) {\n const floatIndices = [];\n for (let i = 0; i < parsedGeometry.matricesIndices.length; i++) {\n const matricesIndex = parsedGeometry.matricesIndices[i];\n floatIndices.push(matricesIndex & 0x000000ff);\n floatIndices.push((matricesIndex & 0x0000ff00) >> 8);\n floatIndices.push((matricesIndex & 0x00ff0000) >> 16);\n floatIndices.push((matricesIndex >> 24) & 0xff); // & 0xFF to convert to v + 256 if v < 0\n }\n mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);\n }\n else {\n delete parsedGeometry.matricesIndices._isExpanded;\n mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);\n }\n }\n if (parsedGeometry.matricesIndicesExtra) {\n if (!parsedGeometry.matricesIndicesExtra._isExpanded) {\n const floatIndices = [];\n for (let i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {\n const matricesIndex = parsedGeometry.matricesIndicesExtra[i];\n floatIndices.push(matricesIndex & 0x000000ff);\n floatIndices.push((matricesIndex & 0x0000ff00) >> 8);\n floatIndices.push((matricesIndex & 0x00ff0000) >> 16);\n floatIndices.push((matricesIndex >> 24) & 0xff); // & 0xFF to convert to v + 256 if v < 0\n }\n mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);\n }\n else {\n delete parsedGeometry.matricesIndices._isExpanded;\n mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);\n }\n }\n if (parsedGeometry.matricesWeights) {\n Geometry._CleanMatricesWeights(parsedGeometry, mesh);\n mesh.setVerticesData(VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);\n }\n if (parsedGeometry.matricesWeightsExtra) {\n mesh.setVerticesData(VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);\n }\n mesh.setIndices(parsedGeometry.indices, null);\n }\n // SubMeshes\n if (parsedGeometry.subMeshes) {\n mesh.subMeshes = [];\n for (let subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {\n const parsedSubMesh = parsedGeometry.subMeshes[subIndex];\n SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);\n }\n }\n // Flat shading\n if (mesh._shouldGenerateFlatShading) {\n mesh.convertToFlatShadedMesh();\n mesh._shouldGenerateFlatShading = false;\n }\n // Update\n mesh.computeWorldMatrix(true);\n scene.onMeshImportedObservable.notifyObservers(mesh);\n }\n static _CleanMatricesWeights(parsedGeometry, mesh) {\n const epsilon = 1e-3;\n if (!SceneLoaderFlags.CleanBoneMatrixWeights) {\n return;\n }\n let noInfluenceBoneIndex = 0.0;\n if (parsedGeometry.skeletonId > -1) {\n const skeleton = mesh.getScene().getLastSkeletonById(parsedGeometry.skeletonId);\n if (!skeleton) {\n return;\n }\n noInfluenceBoneIndex = skeleton.bones.length;\n }\n else {\n return;\n }\n const matricesIndices = mesh.getVerticesData(VertexBuffer.MatricesIndicesKind);\n const matricesIndicesExtra = mesh.getVerticesData(VertexBuffer.MatricesIndicesExtraKind);\n const matricesWeights = parsedGeometry.matricesWeights;\n const matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;\n const influencers = parsedGeometry.numBoneInfluencer;\n const size = matricesWeights.length;\n for (let i = 0; i < size; i += 4) {\n let weight = 0.0;\n let firstZeroWeight = -1;\n for (let j = 0; j < 4; j++) {\n const w = matricesWeights[i + j];\n weight += w;\n if (w < epsilon && firstZeroWeight < 0) {\n firstZeroWeight = j;\n }\n }\n if (matricesWeightsExtra) {\n for (let j = 0; j < 4; j++) {\n const w = matricesWeightsExtra[i + j];\n weight += w;\n if (w < epsilon && firstZeroWeight < 0) {\n firstZeroWeight = j + 4;\n }\n }\n }\n if (firstZeroWeight < 0 || firstZeroWeight > influencers - 1) {\n firstZeroWeight = influencers - 1;\n }\n if (weight > epsilon) {\n const mweight = 1.0 / weight;\n for (let j = 0; j < 4; j++) {\n matricesWeights[i + j] *= mweight;\n }\n if (matricesWeightsExtra) {\n for (let j = 0; j < 4; j++) {\n matricesWeightsExtra[i + j] *= mweight;\n }\n }\n }\n else {\n if (firstZeroWeight >= 4) {\n matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;\n matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;\n }\n else {\n matricesWeights[i + firstZeroWeight] = 1.0 - weight;\n matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;\n }\n }\n }\n mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, matricesIndices);\n if (parsedGeometry.matricesWeightsExtra) {\n mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);\n }\n }\n /**\n * Create a new geometry from persisted data (Using .babylon file format)\n * @param parsedVertexData defines the persisted data\n * @param scene defines the hosting scene\n * @param rootUrl defines the root url to use to load assets (like delayed data)\n * @returns the new geometry object\n */\n static Parse(parsedVertexData, scene, rootUrl) {\n const geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);\n geometry._loadedUniqueId = parsedVertexData.uniqueId;\n if (Tags) {\n Tags.AddTagsTo(geometry, parsedVertexData.tags);\n }\n if (parsedVertexData.delayLoadingFile) {\n geometry.delayLoadState = 4;\n geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;\n geometry._boundingInfo = new BoundingInfo(Vector3.FromArray(parsedVertexData.boundingBoxMinimum), Vector3.FromArray(parsedVertexData.boundingBoxMaximum));\n geometry._delayInfo = [];\n if (parsedVertexData.hasUVs) {\n geometry._delayInfo.push(VertexBuffer.UVKind);\n }\n if (parsedVertexData.hasUVs2) {\n geometry._delayInfo.push(VertexBuffer.UV2Kind);\n }\n if (parsedVertexData.hasUVs3) {\n geometry._delayInfo.push(VertexBuffer.UV3Kind);\n }\n if (parsedVertexData.hasUVs4) {\n geometry._delayInfo.push(VertexBuffer.UV4Kind);\n }\n if (parsedVertexData.hasUVs5) {\n geometry._delayInfo.push(VertexBuffer.UV5Kind);\n }\n if (parsedVertexData.hasUVs6) {\n geometry._delayInfo.push(VertexBuffer.UV6Kind);\n }\n if (parsedVertexData.hasColors) {\n geometry._delayInfo.push(VertexBuffer.ColorKind);\n }\n if (parsedVertexData.hasMatricesIndices) {\n geometry._delayInfo.push(VertexBuffer.MatricesIndicesKind);\n }\n if (parsedVertexData.hasMatricesWeights) {\n geometry._delayInfo.push(VertexBuffer.MatricesWeightsKind);\n }\n geometry._delayLoadingFunction = VertexData.ImportVertexData;\n }\n else {\n VertexData.ImportVertexData(parsedVertexData, geometry);\n }\n scene.pushGeometry(geometry, true);\n return geometry;\n }\n}\n//# sourceMappingURL=geometry.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { Vector3, Vector4, TmpVectors } from \"../Maths/math.vector.js\";\nimport { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { _WarnImport } from \"../Misc/devTools.js\";\nimport { Color4 } from \"../Maths/math.color.js\";\nimport { Logger } from \"../Misc/logger.js\";\nimport { nativeOverride } from \"../Misc/decorators.js\";\nimport { makeSyncFunction, runCoroutineSync } from \"../Misc/coroutine.js\";\nimport { RuntimeError, ErrorCodes } from \"../Misc/error.js\";\n/**\n * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance\n */\nexport class VertexData {\n constructor() {\n this._applyTo = makeSyncFunction(this._applyToCoroutine.bind(this));\n }\n /**\n * Uses the passed data array to set the set the values for the specified kind of data\n * @param data a linear array of floating numbers\n * @param kind the type of data that is being set, eg positions, colors etc\n */\n set(data, kind) {\n if (!data.length) {\n Logger.Warn(`Setting vertex data kind '${kind}' with an empty array`);\n }\n switch (kind) {\n case VertexBuffer.PositionKind:\n this.positions = data;\n break;\n case VertexBuffer.NormalKind:\n this.normals = data;\n break;\n case VertexBuffer.TangentKind:\n this.tangents = data;\n break;\n case VertexBuffer.UVKind:\n this.uvs = data;\n break;\n case VertexBuffer.UV2Kind:\n this.uvs2 = data;\n break;\n case VertexBuffer.UV3Kind:\n this.uvs3 = data;\n break;\n case VertexBuffer.UV4Kind:\n this.uvs4 = data;\n break;\n case VertexBuffer.UV5Kind:\n this.uvs5 = data;\n break;\n case VertexBuffer.UV6Kind:\n this.uvs6 = data;\n break;\n case VertexBuffer.ColorKind:\n this.colors = data;\n break;\n case VertexBuffer.MatricesIndicesKind:\n this.matricesIndices = data;\n break;\n case VertexBuffer.MatricesWeightsKind:\n this.matricesWeights = data;\n break;\n case VertexBuffer.MatricesIndicesExtraKind:\n this.matricesIndicesExtra = data;\n break;\n case VertexBuffer.MatricesWeightsExtraKind:\n this.matricesWeightsExtra = data;\n break;\n }\n }\n /**\n * Associates the vertexData to the passed Mesh.\n * Sets it as updatable or not (default `false`)\n * @param mesh the mesh the vertexData is applied to\n * @param updatable when used and having the value true allows new data to update the vertexData\n * @returns the VertexData\n */\n applyToMesh(mesh, updatable) {\n this._applyTo(mesh, updatable, false);\n return this;\n }\n /**\n * Associates the vertexData to the passed Geometry.\n * Sets it as updatable or not (default `false`)\n * @param geometry the geometry the vertexData is applied to\n * @param updatable when used and having the value true allows new data to update the vertexData\n * @returns VertexData\n */\n applyToGeometry(geometry, updatable) {\n this._applyTo(geometry, updatable, false);\n return this;\n }\n /**\n * Updates the associated mesh\n * @param mesh the mesh to be updated\n * @returns VertexData\n */\n updateMesh(mesh) {\n this._update(mesh);\n return this;\n }\n /**\n * Updates the associated geometry\n * @param geometry the geometry to be updated\n * @returns VertexData.\n */\n updateGeometry(geometry) {\n this._update(geometry);\n return this;\n }\n /**\n * @internal\n */\n *_applyToCoroutine(meshOrGeometry, updatable = false, isAsync) {\n if (this.positions) {\n meshOrGeometry.setVerticesData(VertexBuffer.PositionKind, this.positions, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.normals) {\n meshOrGeometry.setVerticesData(VertexBuffer.NormalKind, this.normals, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.tangents) {\n meshOrGeometry.setVerticesData(VertexBuffer.TangentKind, this.tangents, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.uvs) {\n meshOrGeometry.setVerticesData(VertexBuffer.UVKind, this.uvs, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.uvs2) {\n meshOrGeometry.setVerticesData(VertexBuffer.UV2Kind, this.uvs2, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.uvs3) {\n meshOrGeometry.setVerticesData(VertexBuffer.UV3Kind, this.uvs3, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.uvs4) {\n meshOrGeometry.setVerticesData(VertexBuffer.UV4Kind, this.uvs4, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.uvs5) {\n meshOrGeometry.setVerticesData(VertexBuffer.UV5Kind, this.uvs5, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.uvs6) {\n meshOrGeometry.setVerticesData(VertexBuffer.UV6Kind, this.uvs6, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.colors) {\n meshOrGeometry.setVerticesData(VertexBuffer.ColorKind, this.colors, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.matricesIndices) {\n meshOrGeometry.setVerticesData(VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.matricesWeights) {\n meshOrGeometry.setVerticesData(VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.matricesIndicesExtra) {\n meshOrGeometry.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.matricesWeightsExtra) {\n meshOrGeometry.setVerticesData(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);\n if (isAsync) {\n yield;\n }\n }\n if (this.indices) {\n meshOrGeometry.setIndices(this.indices, null, updatable);\n if (isAsync) {\n yield;\n }\n }\n else {\n meshOrGeometry.setIndices([], null);\n }\n return this;\n }\n _update(meshOrGeometry, updateExtends, makeItUnique) {\n if (this.positions) {\n meshOrGeometry.updateVerticesData(VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);\n }\n if (this.normals) {\n meshOrGeometry.updateVerticesData(VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);\n }\n if (this.tangents) {\n meshOrGeometry.updateVerticesData(VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);\n }\n if (this.uvs) {\n meshOrGeometry.updateVerticesData(VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);\n }\n if (this.uvs2) {\n meshOrGeometry.updateVerticesData(VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);\n }\n if (this.uvs3) {\n meshOrGeometry.updateVerticesData(VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);\n }\n if (this.uvs4) {\n meshOrGeometry.updateVerticesData(VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);\n }\n if (this.uvs5) {\n meshOrGeometry.updateVerticesData(VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);\n }\n if (this.uvs6) {\n meshOrGeometry.updateVerticesData(VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);\n }\n if (this.colors) {\n meshOrGeometry.updateVerticesData(VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);\n }\n if (this.matricesIndices) {\n meshOrGeometry.updateVerticesData(VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);\n }\n if (this.matricesWeights) {\n meshOrGeometry.updateVerticesData(VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);\n }\n if (this.matricesIndicesExtra) {\n meshOrGeometry.updateVerticesData(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);\n }\n if (this.matricesWeightsExtra) {\n meshOrGeometry.updateVerticesData(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);\n }\n if (this.indices) {\n meshOrGeometry.setIndices(this.indices, null);\n }\n return this;\n }\n static _TransformVector3Coordinates(coordinates, transformation, offset = 0, length = coordinates.length) {\n const coordinate = TmpVectors.Vector3[0];\n const transformedCoordinate = TmpVectors.Vector3[1];\n for (let index = offset; index < offset + length; index += 3) {\n Vector3.FromArrayToRef(coordinates, index, coordinate);\n Vector3.TransformCoordinatesToRef(coordinate, transformation, transformedCoordinate);\n coordinates[index] = transformedCoordinate.x;\n coordinates[index + 1] = transformedCoordinate.y;\n coordinates[index + 2] = transformedCoordinate.z;\n }\n }\n static _TransformVector3Normals(normals, transformation, offset = 0, length = normals.length) {\n const normal = TmpVectors.Vector3[0];\n const transformedNormal = TmpVectors.Vector3[1];\n for (let index = offset; index < offset + length; index += 3) {\n Vector3.FromArrayToRef(normals, index, normal);\n Vector3.TransformNormalToRef(normal, transformation, transformedNormal);\n normals[index] = transformedNormal.x;\n normals[index + 1] = transformedNormal.y;\n normals[index + 2] = transformedNormal.z;\n }\n }\n static _TransformVector4Normals(normals, transformation, offset = 0, length = normals.length) {\n const normal = TmpVectors.Vector4[0];\n const transformedNormal = TmpVectors.Vector4[1];\n for (let index = offset; index < offset + length; index += 4) {\n Vector4.FromArrayToRef(normals, index, normal);\n Vector4.TransformNormalToRef(normal, transformation, transformedNormal);\n normals[index] = transformedNormal.x;\n normals[index + 1] = transformedNormal.y;\n normals[index + 2] = transformedNormal.z;\n normals[index + 3] = transformedNormal.w;\n }\n }\n static _FlipFaces(indices, offset = 0, length = indices.length) {\n for (let index = offset; index < offset + length; index += 3) {\n const tmp = indices[index + 1];\n indices[index + 1] = indices[index + 2];\n indices[index + 2] = tmp;\n }\n }\n /**\n * Transforms each position and each normal of the vertexData according to the passed Matrix\n * @param matrix the transforming matrix\n * @returns the VertexData\n */\n transform(matrix) {\n const flip = matrix.determinant() < 0;\n if (this.positions) {\n VertexData._TransformVector3Coordinates(this.positions, matrix);\n }\n if (this.normals) {\n VertexData._TransformVector3Normals(this.normals, matrix);\n }\n if (this.tangents) {\n VertexData._TransformVector4Normals(this.tangents, matrix);\n }\n if (flip && this.indices) {\n VertexData._FlipFaces(this.indices);\n }\n return this;\n }\n /**\n * Merges the passed VertexData into the current one\n * @param others the VertexData to be merged into the current one\n * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array\n * @param forceCloneIndices defines a boolean indicating if indices are forced to be cloned\n * @returns the modified VertexData\n */\n merge(others, use32BitsIndices = false, forceCloneIndices = false) {\n const vertexDatas = Array.isArray(others)\n ? others.map((other) => {\n return { vertexData: other };\n })\n : [{ vertexData: others }];\n return runCoroutineSync(this._mergeCoroutine(undefined, vertexDatas, use32BitsIndices, false, forceCloneIndices));\n }\n /**\n * @internal\n */\n *_mergeCoroutine(transform, vertexDatas, use32BitsIndices = false, isAsync, forceCloneIndices) {\n var _a, _b, _c, _d;\n this._validate();\n const others = vertexDatas.map((vertexData) => vertexData.vertexData);\n for (const other of others) {\n other._validate();\n if (!this.normals !== !other.normals ||\n !this.tangents !== !other.tangents ||\n !this.uvs !== !other.uvs ||\n !this.uvs2 !== !other.uvs2 ||\n !this.uvs3 !== !other.uvs3 ||\n !this.uvs4 !== !other.uvs4 ||\n !this.uvs5 !== !other.uvs5 ||\n !this.uvs6 !== !other.uvs6 ||\n !this.colors !== !other.colors ||\n !this.matricesIndices !== !other.matricesIndices ||\n !this.matricesWeights !== !other.matricesWeights ||\n !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||\n !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {\n throw new Error(\"Cannot merge vertex data that do not have the same set of attributes\");\n }\n }\n const totalIndices = others.reduce((indexSum, vertexData) => { var _a, _b; return indexSum + ((_b = (_a = vertexData.indices) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0); }, (_b = (_a = this.indices) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0);\n const sliceIndices = forceCloneIndices || others.some((vertexData) => vertexData.indices === this.indices);\n let indices = sliceIndices ? (_c = this.indices) === null || _c === void 0 ? void 0 : _c.slice() : this.indices;\n if (totalIndices > 0) {\n let indicesOffset = (_d = indices === null || indices === void 0 ? void 0 : indices.length) !== null && _d !== void 0 ? _d : 0;\n if (!indices) {\n indices = new Array(totalIndices);\n }\n if (indices.length !== totalIndices) {\n if (Array.isArray(indices)) {\n indices.length = totalIndices;\n }\n else {\n const temp = use32BitsIndices || indices instanceof Uint32Array ? new Uint32Array(totalIndices) : new Uint16Array(totalIndices);\n temp.set(indices);\n indices = temp;\n }\n if (transform && transform.determinant() < 0) {\n VertexData._FlipFaces(indices, 0, indicesOffset);\n }\n }\n let positionsOffset = this.positions ? this.positions.length / 3 : 0;\n for (const { vertexData: other, transform } of vertexDatas) {\n if (other.indices) {\n for (let index = 0; index < other.indices.length; index++) {\n indices[indicesOffset + index] = other.indices[index] + positionsOffset;\n }\n if (transform && transform.determinant() < 0) {\n VertexData._FlipFaces(indices, indicesOffset, other.indices.length);\n }\n // The call to _validate already checked for positions\n positionsOffset += other.positions.length / 3;\n indicesOffset += other.indices.length;\n if (isAsync) {\n yield;\n }\n }\n }\n }\n this.indices = indices;\n this.positions = VertexData._MergeElement(VertexBuffer.PositionKind, this.positions, transform, vertexDatas.map((other) => [other.vertexData.positions, other.transform]));\n if (isAsync) {\n yield;\n }\n this.normals = VertexData._MergeElement(VertexBuffer.NormalKind, this.normals, transform, vertexDatas.map((other) => [other.vertexData.normals, other.transform]));\n if (isAsync) {\n yield;\n }\n this.tangents = VertexData._MergeElement(VertexBuffer.TangentKind, this.tangents, transform, vertexDatas.map((other) => [other.vertexData.tangents, other.transform]));\n if (isAsync) {\n yield;\n }\n this.uvs = VertexData._MergeElement(VertexBuffer.UVKind, this.uvs, transform, vertexDatas.map((other) => [other.vertexData.uvs, other.transform]));\n if (isAsync) {\n yield;\n }\n this.uvs2 = VertexData._MergeElement(VertexBuffer.UV2Kind, this.uvs2, transform, vertexDatas.map((other) => [other.vertexData.uvs2, other.transform]));\n if (isAsync) {\n yield;\n }\n this.uvs3 = VertexData._MergeElement(VertexBuffer.UV3Kind, this.uvs3, transform, vertexDatas.map((other) => [other.vertexData.uvs3, other.transform]));\n if (isAsync) {\n yield;\n }\n this.uvs4 = VertexData._MergeElement(VertexBuffer.UV4Kind, this.uvs4, transform, vertexDatas.map((other) => [other.vertexData.uvs4, other.transform]));\n if (isAsync) {\n yield;\n }\n this.uvs5 = VertexData._MergeElement(VertexBuffer.UV5Kind, this.uvs5, transform, vertexDatas.map((other) => [other.vertexData.uvs5, other.transform]));\n if (isAsync) {\n yield;\n }\n this.uvs6 = VertexData._MergeElement(VertexBuffer.UV6Kind, this.uvs6, transform, vertexDatas.map((other) => [other.vertexData.uvs6, other.transform]));\n if (isAsync) {\n yield;\n }\n this.colors = VertexData._MergeElement(VertexBuffer.ColorKind, this.colors, transform, vertexDatas.map((other) => [other.vertexData.colors, other.transform]));\n if (isAsync) {\n yield;\n }\n this.matricesIndices = VertexData._MergeElement(VertexBuffer.MatricesIndicesKind, this.matricesIndices, transform, vertexDatas.map((other) => [other.vertexData.matricesIndices, other.transform]));\n if (isAsync) {\n yield;\n }\n this.matricesWeights = VertexData._MergeElement(VertexBuffer.MatricesWeightsKind, this.matricesWeights, transform, vertexDatas.map((other) => [other.vertexData.matricesWeights, other.transform]));\n if (isAsync) {\n yield;\n }\n this.matricesIndicesExtra = VertexData._MergeElement(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, transform, vertexDatas.map((other) => [other.vertexData.matricesIndicesExtra, other.transform]));\n if (isAsync) {\n yield;\n }\n this.matricesWeightsExtra = VertexData._MergeElement(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, transform, vertexDatas.map((other) => [other.vertexData.matricesWeightsExtra, other.transform]));\n return this;\n }\n static _MergeElement(kind, source, transform, others) {\n const nonNullOthers = others.filter((other) => other[0] !== null && other[0] !== undefined);\n // If there is no source to copy and no other non-null sources then skip this element.\n if (!source && nonNullOthers.length == 0) {\n return source;\n }\n if (!source) {\n return this._MergeElement(kind, nonNullOthers[0][0], nonNullOthers[0][1], nonNullOthers.slice(1));\n }\n const len = nonNullOthers.reduce((sumLen, elements) => sumLen + elements[0].length, source.length);\n const transformRange = kind === VertexBuffer.PositionKind\n ? VertexData._TransformVector3Coordinates\n : kind === VertexBuffer.NormalKind\n ? VertexData._TransformVector3Normals\n : kind === VertexBuffer.TangentKind\n ? VertexData._TransformVector4Normals\n : () => { };\n if (source instanceof Float32Array) {\n // use non-loop method when the source is Float32Array\n const ret32 = new Float32Array(len);\n ret32.set(source);\n transform && transformRange(ret32, transform, 0, source.length);\n let offset = source.length;\n for (const [vertexData, transform] of nonNullOthers) {\n ret32.set(vertexData, offset);\n transform && transformRange(ret32, transform, offset, vertexData.length);\n offset += vertexData.length;\n }\n return ret32;\n }\n else {\n // don't use concat as it is super slow, just loop for other cases\n const ret = new Array(len);\n for (let i = 0; i < source.length; i++) {\n ret[i] = source[i];\n }\n transform && transformRange(ret, transform, 0, source.length);\n let offset = source.length;\n for (const [vertexData, transform] of nonNullOthers) {\n for (let i = 0; i < vertexData.length; i++) {\n ret[offset + i] = vertexData[i];\n }\n transform && transformRange(ret, transform, offset, vertexData.length);\n offset += vertexData.length;\n }\n return ret;\n }\n }\n _validate() {\n if (!this.positions) {\n throw new RuntimeError(\"Positions are required\", ErrorCodes.MeshInvalidPositionsError);\n }\n const getElementCount = (kind, values) => {\n const stride = VertexBuffer.DeduceStride(kind);\n if (values.length % stride !== 0) {\n throw new Error(\"The \" + kind + \"s array count must be a multiple of \" + stride);\n }\n return values.length / stride;\n };\n const positionsElementCount = getElementCount(VertexBuffer.PositionKind, this.positions);\n const validateElementCount = (kind, values) => {\n const elementCount = getElementCount(kind, values);\n if (elementCount !== positionsElementCount) {\n throw new Error(\"The \" + kind + \"s element count (\" + elementCount + \") does not match the positions count (\" + positionsElementCount + \")\");\n }\n };\n if (this.normals) {\n validateElementCount(VertexBuffer.NormalKind, this.normals);\n }\n if (this.tangents) {\n validateElementCount(VertexBuffer.TangentKind, this.tangents);\n }\n if (this.uvs) {\n validateElementCount(VertexBuffer.UVKind, this.uvs);\n }\n if (this.uvs2) {\n validateElementCount(VertexBuffer.UV2Kind, this.uvs2);\n }\n if (this.uvs3) {\n validateElementCount(VertexBuffer.UV3Kind, this.uvs3);\n }\n if (this.uvs4) {\n validateElementCount(VertexBuffer.UV4Kind, this.uvs4);\n }\n if (this.uvs5) {\n validateElementCount(VertexBuffer.UV5Kind, this.uvs5);\n }\n if (this.uvs6) {\n validateElementCount(VertexBuffer.UV6Kind, this.uvs6);\n }\n if (this.colors) {\n validateElementCount(VertexBuffer.ColorKind, this.colors);\n }\n if (this.matricesIndices) {\n validateElementCount(VertexBuffer.MatricesIndicesKind, this.matricesIndices);\n }\n if (this.matricesWeights) {\n validateElementCount(VertexBuffer.MatricesWeightsKind, this.matricesWeights);\n }\n if (this.matricesIndicesExtra) {\n validateElementCount(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);\n }\n if (this.matricesWeightsExtra) {\n validateElementCount(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);\n }\n }\n /**\n * Serializes the VertexData\n * @returns a serialized object\n */\n serialize() {\n const serializationObject = {};\n if (this.positions) {\n serializationObject.positions = this.positions;\n }\n if (this.normals) {\n serializationObject.normals = this.normals;\n }\n if (this.tangents) {\n serializationObject.tangents = this.tangents;\n }\n if (this.uvs) {\n serializationObject.uvs = this.uvs;\n }\n if (this.uvs2) {\n serializationObject.uvs2 = this.uvs2;\n }\n if (this.uvs3) {\n serializationObject.uvs3 = this.uvs3;\n }\n if (this.uvs4) {\n serializationObject.uvs4 = this.uvs4;\n }\n if (this.uvs5) {\n serializationObject.uvs5 = this.uvs5;\n }\n if (this.uvs6) {\n serializationObject.uvs6 = this.uvs6;\n }\n if (this.colors) {\n serializationObject.colors = this.colors;\n }\n if (this.matricesIndices) {\n serializationObject.matricesIndices = this.matricesIndices;\n serializationObject.matricesIndices._isExpanded = true;\n }\n if (this.matricesWeights) {\n serializationObject.matricesWeights = this.matricesWeights;\n }\n if (this.matricesIndicesExtra) {\n serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;\n serializationObject.matricesIndicesExtra._isExpanded = true;\n }\n if (this.matricesWeightsExtra) {\n serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;\n }\n serializationObject.indices = this.indices;\n return serializationObject;\n }\n // Statics\n /**\n * Extracts the vertexData from a mesh\n * @param mesh the mesh from which to extract the VertexData\n * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false\n * @param forceCopy indicating that the VertexData must be cloned, optional, default false\n * @returns the object VertexData associated to the passed mesh\n */\n static ExtractFromMesh(mesh, copyWhenShared, forceCopy) {\n return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);\n }\n /**\n * Extracts the vertexData from the geometry\n * @param geometry the geometry from which to extract the VertexData\n * @param copyWhenShared defines if the VertexData must be cloned when the geometry is shared between multiple meshes, optional, default false\n * @param forceCopy indicating that the VertexData must be cloned, optional, default false\n * @returns the object VertexData associated to the passed mesh\n */\n static ExtractFromGeometry(geometry, copyWhenShared, forceCopy) {\n return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);\n }\n static _ExtractFrom(meshOrGeometry, copyWhenShared, forceCopy) {\n const result = new VertexData();\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.PositionKind)) {\n result.positions = meshOrGeometry.getVerticesData(VertexBuffer.PositionKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.NormalKind)) {\n result.normals = meshOrGeometry.getVerticesData(VertexBuffer.NormalKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.TangentKind)) {\n result.tangents = meshOrGeometry.getVerticesData(VertexBuffer.TangentKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UVKind)) {\n result.uvs = meshOrGeometry.getVerticesData(VertexBuffer.UVKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV2Kind)) {\n result.uvs2 = meshOrGeometry.getVerticesData(VertexBuffer.UV2Kind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV3Kind)) {\n result.uvs3 = meshOrGeometry.getVerticesData(VertexBuffer.UV3Kind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV4Kind)) {\n result.uvs4 = meshOrGeometry.getVerticesData(VertexBuffer.UV4Kind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV5Kind)) {\n result.uvs5 = meshOrGeometry.getVerticesData(VertexBuffer.UV5Kind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV6Kind)) {\n result.uvs6 = meshOrGeometry.getVerticesData(VertexBuffer.UV6Kind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.ColorKind)) {\n result.colors = meshOrGeometry.getVerticesData(VertexBuffer.ColorKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) {\n result.matricesIndices = meshOrGeometry.getVerticesData(VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {\n result.matricesWeights = meshOrGeometry.getVerticesData(VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.MatricesIndicesExtraKind)) {\n result.matricesIndicesExtra = meshOrGeometry.getVerticesData(VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);\n }\n if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.MatricesWeightsExtraKind)) {\n result.matricesWeightsExtra = meshOrGeometry.getVerticesData(VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);\n }\n result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);\n return result;\n }\n /**\n * Creates the VertexData for a Ribbon\n * @param options an object used to set the following optional parameters for the ribbon, required but can be empty\n * * pathArray array of paths, each of which an array of successive Vector3\n * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false\n * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false\n * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false\n * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional\n * * colors a linear array, of length 4 * number of vertices, of custom color values, optional\n * @param options.pathArray\n * @param options.closeArray\n * @param options.closePath\n * @param options.offset\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @param options.invertUV\n * @param options.uvs\n * @param options.colors\n * @returns the VertexData of the ribbon\n * @deprecated use CreateRibbonVertexData instead\n */\n static CreateRibbon(options) {\n throw _WarnImport(\"ribbonBuilder\");\n }\n /**\n * Creates the VertexData for a box\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * size sets the width, height and depth of the box to the value of size, optional default 1\n * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size\n * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size\n * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size\n * * faceUV an array of 6 Vector4 elements used to set different images to each box side\n * * faceColors an array of 6 Color3 elements used to set different colors to each box side\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.size\n * @param options.width\n * @param options.height\n * @param options.depth\n * @param options.faceUV\n * @param options.faceColors\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the box\n * @deprecated Please use CreateBoxVertexData from the BoxBuilder file instead\n */\n static CreateBox(options) {\n throw _WarnImport(\"boxBuilder\");\n }\n /**\n * Creates the VertexData for a tiled box\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * faceTiles sets the pattern, tile size and number of tiles for a face\n * * faceUV an array of 6 Vector4 elements used to set different images to each box side\n * * faceColors an array of 6 Color3 elements used to set different colors to each box side\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * @param options.pattern\n * @param options.width\n * @param options.height\n * @param options.depth\n * @param options.tileSize\n * @param options.tileWidth\n * @param options.tileHeight\n * @param options.alignHorizontal\n * @param options.alignVertical\n * @param options.faceUV\n * @param options.faceColors\n * @param options.sideOrientation\n * @returns the VertexData of the box\n * @deprecated Please use CreateTiledBoxVertexData instead\n */\n static CreateTiledBox(options) {\n throw _WarnImport(\"tiledBoxBuilder\");\n }\n /**\n * Creates the VertexData for a tiled plane\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * pattern a limited pattern arrangement depending on the number\n * * tileSize sets the width, height and depth of the tile to the value of size, optional default 1\n * * tileWidth sets the width (x direction) of the tile, overwrites the width set by size, optional, default size\n * * tileHeight sets the height (y direction) of the tile, overwrites the height set by size, optional, default size\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.pattern\n * @param options.tileSize\n * @param options.tileWidth\n * @param options.tileHeight\n * @param options.size\n * @param options.width\n * @param options.height\n * @param options.alignHorizontal\n * @param options.alignVertical\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the tiled plane\n * @deprecated use CreateTiledPlaneVertexData instead\n */\n static CreateTiledPlane(options) {\n throw _WarnImport(\"tiledPlaneBuilder\");\n }\n /**\n * Creates the VertexData for an ellipsoid, defaults to a sphere\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * segments sets the number of horizontal strips optional, default 32\n * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1\n * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter\n * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter\n * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter\n * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1\n * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.segments\n * @param options.diameter\n * @param options.diameterX\n * @param options.diameterY\n * @param options.diameterZ\n * @param options.arc\n * @param options.slice\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the ellipsoid\n * @deprecated use CreateSphereVertexData instead\n */\n static CreateSphere(options) {\n throw _WarnImport(\"sphereBuilder\");\n }\n /**\n * Creates the VertexData for a cylinder, cone or prism\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * height sets the height (y direction) of the cylinder, optional, default 2\n * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter\n * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter\n * * diameter sets the diameter of the top and bottom of the cone, optional default 1\n * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24\n * * subdivisions` the number of rings along the cylinder height, optional, default 1\n * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1\n * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively\n * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively\n * * hasRings when true makes each subdivision independently treated as a face for faceUV and faceColors, optional, default false\n * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.height\n * @param options.diameterTop\n * @param options.diameterBottom\n * @param options.diameter\n * @param options.tessellation\n * @param options.subdivisions\n * @param options.arc\n * @param options.faceColors\n * @param options.faceUV\n * @param options.hasRings\n * @param options.enclose\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the cylinder, cone or prism\n * @deprecated please use CreateCylinderVertexData instead\n */\n static CreateCylinder(options) {\n throw _WarnImport(\"cylinderBuilder\");\n }\n /**\n * Creates the VertexData for a torus\n * @param options an object used to set the following optional parameters for the box, required but can be empty\n * * diameter the diameter of the torus, optional default 1\n * * thickness the diameter of the tube forming the torus, optional default 0.5\n * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.diameter\n * @param options.thickness\n * @param options.tessellation\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the torus\n * @deprecated use CreateTorusVertexData instead\n */\n static CreateTorus(options) {\n throw _WarnImport(\"torusBuilder\");\n }\n /**\n * Creates the VertexData of the LineSystem\n * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty\n * - lines an array of lines, each line being an array of successive Vector3\n * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point\n * @param options.lines\n * @param options.colors\n * @returns the VertexData of the LineSystem\n * @deprecated use CreateLineSystemVertexData instead\n */\n static CreateLineSystem(options) {\n throw _WarnImport(\"linesBuilder\");\n }\n /**\n * Create the VertexData for a DashedLines\n * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty\n * - points an array successive Vector3\n * - dashSize the size of the dashes relative to the dash number, optional, default 3\n * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1\n * - dashNb the intended total number of dashes, optional, default 200\n * @param options.points\n * @param options.dashSize\n * @param options.gapSize\n * @param options.dashNb\n * @returns the VertexData for the DashedLines\n * @deprecated use CreateDashedLinesVertexData instead\n */\n static CreateDashedLines(options) {\n throw _WarnImport(\"linesBuilder\");\n }\n /**\n * Creates the VertexData for a Ground\n * @param options an object used to set the following optional parameters for the Ground, required but can be empty\n * - width the width (x direction) of the ground, optional, default 1\n * - height the height (z direction) of the ground, optional, default 1\n * - subdivisions the number of subdivisions per side, optional, default 1\n * @param options.width\n * @param options.height\n * @param options.subdivisions\n * @param options.subdivisionsX\n * @param options.subdivisionsY\n * @returns the VertexData of the Ground\n * @deprecated Please use CreateGroundVertexData instead\n */\n static CreateGround(options) {\n throw _WarnImport(\"groundBuilder\");\n }\n /**\n * Creates the VertexData for a TiledGround by subdividing the ground into tiles\n * @param options an object used to set the following optional parameters for the Ground, required but can be empty\n * * xmin the ground minimum X coordinate, optional, default -1\n * * zmin the ground minimum Z coordinate, optional, default -1\n * * xmax the ground maximum X coordinate, optional, default 1\n * * zmax the ground maximum Z coordinate, optional, default 1\n * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}\n * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}\n * @param options.xmin\n * @param options.zmin\n * @param options.xmax\n * @param options.zmax\n * @param options.subdivisions\n * @param options.subdivisions.w\n * @param options.subdivisions.h\n * @param options.precision\n * @param options.precision.w\n * @param options.precision.h\n * @returns the VertexData of the TiledGround\n * @deprecated use CreateTiledGroundVertexData instead\n */\n static CreateTiledGround(options) {\n throw _WarnImport(\"groundBuilder\");\n }\n /**\n * Creates the VertexData of the Ground designed from a heightmap\n * @param options an object used to set the following parameters for the Ground, required and provided by CreateGroundFromHeightMap\n * * width the width (x direction) of the ground\n * * height the height (z direction) of the ground\n * * subdivisions the number of subdivisions per side\n * * minHeight the minimum altitude on the ground, optional, default 0\n * * maxHeight the maximum altitude on the ground, optional default 1\n * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)\n * * buffer the array holding the image color data\n * * bufferWidth the width of image\n * * bufferHeight the height of image\n * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)\n * @param options.width\n * @param options.height\n * @param options.subdivisions\n * @param options.minHeight\n * @param options.maxHeight\n * @param options.colorFilter\n * @param options.buffer\n * @param options.bufferWidth\n * @param options.bufferHeight\n * @param options.alphaFilter\n * @returns the VertexData of the Ground designed from a heightmap\n * @deprecated use CreateGroundFromHeightMapVertexData instead\n */\n static CreateGroundFromHeightMap(options) {\n throw _WarnImport(\"groundBuilder\");\n }\n /**\n * Creates the VertexData for a Plane\n * @param options an object used to set the following optional parameters for the plane, required but can be empty\n * * size sets the width and height of the plane to the value of size, optional default 1\n * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size\n * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.size\n * @param options.width\n * @param options.height\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the box\n * @deprecated use CreatePlaneVertexData instead\n */\n static CreatePlane(options) {\n throw _WarnImport(\"planeBuilder\");\n }\n /**\n * Creates the VertexData of the Disc or regular Polygon\n * @param options an object used to set the following optional parameters for the disc, required but can be empty\n * * radius the radius of the disc, optional default 0.5\n * * tessellation the number of polygon sides, optional, default 64\n * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.radius\n * @param options.tessellation\n * @param options.arc\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the box\n * @deprecated use CreateDiscVertexData instead\n */\n static CreateDisc(options) {\n throw _WarnImport(\"discBuilder\");\n }\n /**\n * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()\n * All parameters are provided by CreatePolygon as needed\n * @param polygon a mesh built from polygonTriangulation.build()\n * @param sideOrientation takes the values Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively\n * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively\n * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param wrap a boolean, default false, when true and fUVs used texture is wrapped around all sides, when false texture is applied side\n * @returns the VertexData of the Polygon\n * @deprecated use CreatePolygonVertexData instead\n */\n static CreatePolygon(polygon, sideOrientation, fUV, fColors, frontUVs, backUVs, wrap) {\n throw _WarnImport(\"polygonBuilder\");\n }\n /**\n * Creates the VertexData of the IcoSphere\n * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty\n * * radius the radius of the IcoSphere, optional default 1\n * * radiusX allows stretching in the x direction, optional, default radius\n * * radiusY allows stretching in the y direction, optional, default radius\n * * radiusZ allows stretching in the z direction, optional, default radius\n * * flat when true creates a flat shaded mesh, optional, default true\n * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.radius\n * @param options.radiusX\n * @param options.radiusY\n * @param options.radiusZ\n * @param options.flat\n * @param options.subdivisions\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the IcoSphere\n * @deprecated use CreateIcoSphereVertexData instead\n */\n static CreateIcoSphere(options) {\n throw _WarnImport(\"icoSphereBuilder\");\n }\n // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html\n /**\n * Creates the VertexData for a Polyhedron\n * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty\n * * type provided types are:\n * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)\n * * 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)\n * * size the size of the IcoSphere, optional default 1\n * * sizeX allows stretching in the x direction, optional, default size\n * * sizeY allows stretching in the y direction, optional, default size\n * * sizeZ allows stretching in the z direction, optional, default size\n * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor\n * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively\n * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively\n * * flat when true creates a flat shaded mesh, optional, default true\n * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.type\n * @param options.size\n * @param options.sizeX\n * @param options.sizeY\n * @param options.sizeZ\n * @param options.custom\n * @param options.faceUV\n * @param options.faceColors\n * @param options.flat\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the Polyhedron\n * @deprecated use CreatePolyhedronVertexData instead\n */\n static CreatePolyhedron(options) {\n throw _WarnImport(\"polyhedronBuilder\");\n }\n /**\n * Creates the VertexData for a Capsule, inspired from https://github.com/maximeq/three-js-capsule-geometry/blob/master/src/CapsuleBufferGeometry.js\n * @param options an object used to set the following optional parameters for the capsule, required but can be empty\n * @returns the VertexData of the Capsule\n * @deprecated Please use CreateCapsuleVertexData from the capsuleBuilder file instead\n */\n static CreateCapsule(options = {\n orientation: Vector3.Up(),\n subdivisions: 2,\n tessellation: 16,\n height: 1,\n radius: 0.25,\n capSubdivisions: 6,\n }) {\n throw _WarnImport(\"capsuleBuilder\");\n }\n // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473\n /**\n * Creates the VertexData for a TorusKnot\n * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty\n * * radius the radius of the torus knot, optional, default 2\n * * tube the thickness of the tube, optional, default 0.5\n * * radialSegments the number of sides on each tube segments, optional, default 32\n * * tubularSegments the number of tubes to decompose the knot into, optional, default 32\n * * p the number of windings around the z axis, optional, default 2\n * * q the number of windings around the x axis, optional, default 3\n * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE\n * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)\n * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)\n * @param options.radius\n * @param options.tube\n * @param options.radialSegments\n * @param options.tubularSegments\n * @param options.p\n * @param options.q\n * @param options.sideOrientation\n * @param options.frontUVs\n * @param options.backUVs\n * @returns the VertexData of the Torus Knot\n * @deprecated use CreateTorusKnotVertexData instead\n */\n static CreateTorusKnot(options) {\n throw _WarnImport(\"torusKnotBuilder\");\n }\n // Tools\n /**\n * Compute normals for given positions and indices\n * @param positions an array of vertex positions, [...., x, y, z, ......]\n * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]\n * @param normals an array of vertex normals, [...., x, y, z, ......]\n * @param options an object used to set the following optional parameters for the TorusKnot, optional\n * * facetNormals : optional array of facet normals (vector3)\n * * facetPositions : optional array of facet positions (vector3)\n * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation\n * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation\n * * bInfo : optional bounding info, required for facetPartitioning computation\n * * bbSize : optional bounding box size data, required for facetPartitioning computation\n * * subDiv : optional partitioning data about subdivisions on each axis (int), required for facetPartitioning computation\n * * useRightHandedSystem: optional boolean to for right handed system computation\n * * depthSort : optional boolean to enable the facet depth sort computation\n * * distanceTo : optional Vector3 to compute the facet depth from this location\n * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location\n * @param options.facetNormals\n * @param options.facetPositions\n * @param options.facetPartitioning\n * @param options.ratio\n * @param options.bInfo\n * @param options.bbSize\n * @param options.subDiv\n * @param options.useRightHandedSystem\n * @param options.depthSort\n * @param options.distanceTo\n * @param options.depthSortedFacets\n */\n static ComputeNormals(positions, indices, normals, options) {\n // temporary scalar variables\n let index = 0; // facet index\n let p1p2x = 0.0; // p1p2 vector x coordinate\n let p1p2y = 0.0; // p1p2 vector y coordinate\n let p1p2z = 0.0; // p1p2 vector z coordinate\n let p3p2x = 0.0; // p3p2 vector x coordinate\n let p3p2y = 0.0; // p3p2 vector y coordinate\n let p3p2z = 0.0; // p3p2 vector z coordinate\n let faceNormalx = 0.0; // facet normal x coordinate\n let faceNormaly = 0.0; // facet normal y coordinate\n let faceNormalz = 0.0; // facet normal z coordinate\n let length = 0.0; // facet normal length before normalization\n let v1x = 0; // vector1 x index in the positions array\n let v1y = 0; // vector1 y index in the positions array\n let v1z = 0; // vector1 z index in the positions array\n let v2x = 0; // vector2 x index in the positions array\n let v2y = 0; // vector2 y index in the positions array\n let v2z = 0; // vector2 z index in the positions array\n let v3x = 0; // vector3 x index in the positions array\n let v3y = 0; // vector3 y index in the positions array\n let v3z = 0; // vector3 z index in the positions array\n let computeFacetNormals = false;\n let computeFacetPositions = false;\n let computeFacetPartitioning = false;\n let computeDepthSort = false;\n let faceNormalSign = 1;\n let ratio = 0;\n let distanceTo = null;\n if (options) {\n computeFacetNormals = options.facetNormals ? true : false;\n computeFacetPositions = options.facetPositions ? true : false;\n computeFacetPartitioning = options.facetPartitioning ? true : false;\n faceNormalSign = options.useRightHandedSystem === true ? -1 : 1;\n ratio = options.ratio || 0;\n computeDepthSort = options.depthSort ? true : false;\n distanceTo = options.distanceTo;\n if (computeDepthSort) {\n if (distanceTo === undefined) {\n distanceTo = Vector3.Zero();\n }\n }\n }\n // facetPartitioning reinit if needed\n let xSubRatio = 0;\n let ySubRatio = 0;\n let zSubRatio = 0;\n let subSq = 0;\n if (computeFacetPartitioning && options && options.bbSize) {\n //let bbSizeMax = options.bbSize.x > options.bbSize.y ? options.bbSize.x : options.bbSize.y;\n //bbSizeMax = bbSizeMax > options.bbSize.z ? bbSizeMax : options.bbSize.z;\n xSubRatio = (options.subDiv.X * ratio) / options.bbSize.x;\n ySubRatio = (options.subDiv.Y * ratio) / options.bbSize.y;\n zSubRatio = (options.subDiv.Z * ratio) / options.bbSize.z;\n subSq = options.subDiv.max * options.subDiv.max;\n options.facetPartitioning.length = 0;\n }\n // reset the normals\n for (index = 0; index < positions.length; index++) {\n normals[index] = 0.0;\n }\n // Loop : 1 indice triplet = 1 facet\n const nbFaces = (indices.length / 3) | 0;\n for (index = 0; index < nbFaces; index++) {\n // get the indexes of the coordinates of each vertex of the facet\n v1x = indices[index * 3] * 3;\n v1y = v1x + 1;\n v1z = v1x + 2;\n v2x = indices[index * 3 + 1] * 3;\n v2y = v2x + 1;\n v2z = v2x + 2;\n v3x = indices[index * 3 + 2] * 3;\n v3y = v3x + 1;\n v3z = v3x + 2;\n p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2\n p1p2y = positions[v1y] - positions[v2y];\n p1p2z = positions[v1z] - positions[v2z];\n p3p2x = positions[v3x] - positions[v2x];\n p3p2y = positions[v3y] - positions[v2y];\n p3p2z = positions[v3z] - positions[v2z];\n // compute the face normal with the cross product\n faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);\n faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);\n faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);\n // normalize this normal and store it in the array facetData\n length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);\n length = length === 0 ? 1.0 : length;\n faceNormalx /= length;\n faceNormaly /= length;\n faceNormalz /= length;\n if (computeFacetNormals && options) {\n options.facetNormals[index].x = faceNormalx;\n options.facetNormals[index].y = faceNormaly;\n options.facetNormals[index].z = faceNormalz;\n }\n if (computeFacetPositions && options) {\n // compute and the facet barycenter coordinates in the array facetPositions\n options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;\n options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;\n options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;\n }\n if (computeFacetPartitioning && options) {\n // store the facet indexes in arrays in the main facetPartitioning array :\n // compute each facet vertex (+ facet barycenter) index in the partiniong array\n const ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);\n const oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);\n const oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);\n const b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);\n const b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);\n const b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);\n const b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);\n const b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);\n const b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);\n const b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);\n const b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);\n const b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);\n const block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;\n const block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;\n const block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;\n const block_idx_o = ox + options.subDiv.max * oy + subSq * oz;\n options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();\n options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();\n options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();\n options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();\n // push each facet index in each block containing the vertex\n options.facetPartitioning[block_idx_v1].push(index);\n if (block_idx_v2 != block_idx_v1) {\n options.facetPartitioning[block_idx_v2].push(index);\n }\n if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {\n options.facetPartitioning[block_idx_v3].push(index);\n }\n if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {\n options.facetPartitioning[block_idx_o].push(index);\n }\n }\n if (computeDepthSort && options && options.facetPositions) {\n const dsf = options.depthSortedFacets[index];\n dsf.ind = index * 3;\n dsf.sqDistance = Vector3.DistanceSquared(options.facetPositions[index], distanceTo);\n }\n // compute the normals anyway\n normals[v1x] += faceNormalx; // accumulate all the normals per face\n normals[v1y] += faceNormaly;\n normals[v1z] += faceNormalz;\n normals[v2x] += faceNormalx;\n normals[v2y] += faceNormaly;\n normals[v2z] += faceNormalz;\n normals[v3x] += faceNormalx;\n normals[v3y] += faceNormaly;\n normals[v3z] += faceNormalz;\n }\n // last normalization of each normal\n for (index = 0; index < normals.length / 3; index++) {\n faceNormalx = normals[index * 3];\n faceNormaly = normals[index * 3 + 1];\n faceNormalz = normals[index * 3 + 2];\n length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);\n length = length === 0 ? 1.0 : length;\n faceNormalx /= length;\n faceNormaly /= length;\n faceNormalz /= length;\n normals[index * 3] = faceNormalx;\n normals[index * 3 + 1] = faceNormaly;\n normals[index * 3 + 2] = faceNormalz;\n }\n }\n /**\n * @internal\n */\n static _ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {\n const li = indices.length;\n const ln = normals.length;\n let i;\n let n;\n sideOrientation = sideOrientation || VertexData.DEFAULTSIDE;\n switch (sideOrientation) {\n case VertexData.FRONTSIDE:\n // nothing changed\n break;\n case VertexData.BACKSIDE:\n // indices\n for (i = 0; i < li; i += 3) {\n const tmp = indices[i];\n indices[i] = indices[i + 2];\n indices[i + 2] = tmp;\n }\n // normals\n for (n = 0; n < ln; n++) {\n normals[n] = -normals[n];\n }\n break;\n case VertexData.DOUBLESIDE: {\n // positions\n const lp = positions.length;\n const l = lp / 3;\n for (let p = 0; p < lp; p++) {\n positions[lp + p] = positions[p];\n }\n // indices\n for (i = 0; i < li; i += 3) {\n indices[i + li] = indices[i + 2] + l;\n indices[i + 1 + li] = indices[i + 1] + l;\n indices[i + 2 + li] = indices[i] + l;\n }\n // normals\n for (n = 0; n < ln; n++) {\n normals[ln + n] = -normals[n];\n }\n // uvs\n const lu = uvs.length;\n let u = 0;\n for (u = 0; u < lu; u++) {\n uvs[u + lu] = uvs[u];\n }\n frontUVs = frontUVs ? frontUVs : new Vector4(0.0, 0.0, 1.0, 1.0);\n backUVs = backUVs ? backUVs : new Vector4(0.0, 0.0, 1.0, 1.0);\n u = 0;\n for (i = 0; i < lu / 2; i++) {\n uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];\n uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];\n uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];\n uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];\n u += 2;\n }\n break;\n }\n }\n }\n /**\n * Applies VertexData created from the imported parameters to the geometry\n * @param parsedVertexData the parsed data from an imported file\n * @param geometry the geometry to apply the VertexData to\n */\n static ImportVertexData(parsedVertexData, geometry) {\n const vertexData = new VertexData();\n // positions\n const positions = parsedVertexData.positions;\n if (positions) {\n vertexData.set(positions, VertexBuffer.PositionKind);\n }\n // normals\n const normals = parsedVertexData.normals;\n if (normals) {\n vertexData.set(normals, VertexBuffer.NormalKind);\n }\n // tangents\n const tangents = parsedVertexData.tangents;\n if (tangents) {\n vertexData.set(tangents, VertexBuffer.TangentKind);\n }\n // uvs\n const uvs = parsedVertexData.uvs;\n if (uvs) {\n vertexData.set(uvs, VertexBuffer.UVKind);\n }\n // uv2s\n const uv2s = parsedVertexData.uv2s;\n if (uv2s) {\n vertexData.set(uv2s, VertexBuffer.UV2Kind);\n }\n // uv3s\n const uv3s = parsedVertexData.uv3s;\n if (uv3s) {\n vertexData.set(uv3s, VertexBuffer.UV3Kind);\n }\n // uv4s\n const uv4s = parsedVertexData.uv4s;\n if (uv4s) {\n vertexData.set(uv4s, VertexBuffer.UV4Kind);\n }\n // uv5s\n const uv5s = parsedVertexData.uv5s;\n if (uv5s) {\n vertexData.set(uv5s, VertexBuffer.UV5Kind);\n }\n // uv6s\n const uv6s = parsedVertexData.uv6s;\n if (uv6s) {\n vertexData.set(uv6s, VertexBuffer.UV6Kind);\n }\n // colors\n const colors = parsedVertexData.colors;\n if (colors) {\n vertexData.set(Color4.CheckColors4(colors, positions.length / 3), VertexBuffer.ColorKind);\n }\n // matricesIndices\n const matricesIndices = parsedVertexData.matricesIndices;\n if (matricesIndices) {\n vertexData.set(matricesIndices, VertexBuffer.MatricesIndicesKind);\n }\n // matricesWeights\n const matricesWeights = parsedVertexData.matricesWeights;\n if (matricesWeights) {\n vertexData.set(matricesWeights, VertexBuffer.MatricesWeightsKind);\n }\n // indices\n const indices = parsedVertexData.indices;\n if (indices) {\n vertexData.indices = indices;\n }\n geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);\n }\n}\n/**\n * Mesh side orientation : usually the external or front surface\n */\nVertexData.FRONTSIDE = 0;\n/**\n * Mesh side orientation : usually the internal or back surface\n */\nVertexData.BACKSIDE = 1;\n/**\n * Mesh side orientation : both internal and external or front and back surfaces\n */\nVertexData.DOUBLESIDE = 2;\n/**\n * Mesh side orientation : by default, `FRONTSIDE`\n */\nVertexData.DEFAULTSIDE = 0;\n__decorate([\n nativeOverride.filter((...[coordinates]) => !Array.isArray(coordinates))\n], VertexData, \"_TransformVector3Coordinates\", null);\n__decorate([\n nativeOverride.filter((...[normals]) => !Array.isArray(normals))\n], VertexData, \"_TransformVector3Normals\", null);\n__decorate([\n nativeOverride.filter((...[normals]) => !Array.isArray(normals))\n], VertexData, \"_TransformVector4Normals\", null);\n__decorate([\n nativeOverride.filter((...[indices]) => !Array.isArray(indices))\n], VertexData, \"_FlipFaces\", null);\n//# sourceMappingURL=mesh.vertexData.js.map","/**\n * Class used to represent a specific level of detail of a mesh\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/LOD\n */\nexport class MeshLODLevel {\n /**\n * Creates a new LOD level\n * @param distanceOrScreenCoverage defines either the distance or the screen coverage where this level should start being displayed\n * @param mesh defines the mesh to use to render this level\n */\n constructor(\n /** Either distance from the center of the object to show this level or the screen coverage if `useLODScreenCoverage` is set to `true` on the mesh*/\n distanceOrScreenCoverage, \n /** Defines the mesh to use to render this level */\n mesh) {\n this.distanceOrScreenCoverage = distanceOrScreenCoverage;\n this.mesh = mesh;\n }\n}\n//# sourceMappingURL=meshLODLevel.js.map","import { VertexBuffer } from \"../Buffers/buffer.js\";\nimport { IntersectionInfo } from \"../Collisions/intersectionInfo.js\";\nimport { BoundingInfo } from \"../Culling/boundingInfo.js\";\n\nimport { extractMinAndMaxIndexed } from \"../Maths/math.functions.js\";\nimport { DrawWrapper } from \"../Materials/drawWrapper.js\";\n/**\n * Defines a subdivision inside a mesh\n */\nexport class SubMesh {\n /**\n * Gets material defines used by the effect associated to the sub mesh\n */\n get materialDefines() {\n var _a;\n return this._mainDrawWrapperOverride ? this._mainDrawWrapperOverride.defines : (_a = this._getDrawWrapper()) === null || _a === void 0 ? void 0 : _a.defines;\n }\n /**\n * Sets material defines used by the effect associated to the sub mesh\n */\n set materialDefines(defines) {\n var _a;\n const drawWrapper = (_a = this._mainDrawWrapperOverride) !== null && _a !== void 0 ? _a : this._getDrawWrapper(undefined, true);\n drawWrapper.defines = defines;\n }\n /**\n * @internal\n */\n _getDrawWrapper(passId, createIfNotExisting = false) {\n passId = passId !== null && passId !== void 0 ? passId : this._engine.currentRenderPassId;\n let drawWrapper = this._drawWrappers[passId];\n if (!drawWrapper && createIfNotExisting) {\n this._drawWrappers[passId] = drawWrapper = new DrawWrapper(this._mesh.getScene().getEngine());\n }\n return drawWrapper;\n }\n /**\n * @internal\n */\n _removeDrawWrapper(passId, disposeWrapper = true) {\n var _a;\n if (disposeWrapper) {\n (_a = this._drawWrappers[passId]) === null || _a === void 0 ? void 0 : _a.dispose();\n }\n this._drawWrappers[passId] = undefined;\n }\n /**\n * Gets associated (main) effect (possibly the effect override if defined)\n */\n get effect() {\n var _a, _b;\n return this._mainDrawWrapperOverride ? this._mainDrawWrapperOverride.effect : (_b = (_a = this._getDrawWrapper()) === null || _a === void 0 ? void 0 : _a.effect) !== null && _b !== void 0 ? _b : null;\n }\n /** @internal */\n get _drawWrapper() {\n var _a;\n return (_a = this._mainDrawWrapperOverride) !== null && _a !== void 0 ? _a : this._getDrawWrapper(undefined, true);\n }\n /** @internal */\n get _drawWrapperOverride() {\n return this._mainDrawWrapperOverride;\n }\n /**\n * @internal\n */\n _setMainDrawWrapperOverride(wrapper) {\n this._mainDrawWrapperOverride = wrapper;\n }\n /**\n * Sets associated effect (effect used to render this submesh)\n * @param effect defines the effect to associate with\n * @param defines defines the set of defines used to compile this effect\n * @param materialContext material context associated to the effect\n * @param resetContext true to reset the draw context\n */\n setEffect(effect, defines = null, materialContext, resetContext = true) {\n const drawWrapper = this._drawWrapper;\n drawWrapper.setEffect(effect, defines, resetContext);\n if (materialContext !== undefined) {\n drawWrapper.materialContext = materialContext;\n }\n if (!effect) {\n drawWrapper.defines = null;\n drawWrapper.materialContext = undefined;\n }\n }\n /**\n * Resets the draw wrappers cache\n * @param passId If provided, releases only the draw wrapper corresponding to this render pass id\n */\n resetDrawCache(passId) {\n if (this._drawWrappers) {\n if (passId !== undefined) {\n this._removeDrawWrapper(passId);\n return;\n }\n else {\n for (const drawWrapper of this._drawWrappers) {\n drawWrapper === null || drawWrapper === void 0 ? void 0 : drawWrapper.dispose();\n }\n }\n }\n this._drawWrappers = [];\n }\n /**\n * Add a new submesh to a mesh\n * @param materialIndex defines the material index to use\n * @param verticesStart defines vertex index start\n * @param verticesCount defines vertices count\n * @param indexStart defines index start\n * @param indexCount defines indices count\n * @param mesh defines the parent mesh\n * @param renderingMesh defines an optional rendering mesh\n * @param createBoundingBox defines if bounding box should be created for this submesh\n * @returns the new submesh\n */\n static AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox = true) {\n return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);\n }\n /**\n * Creates a new submesh\n * @param materialIndex defines the material index to use\n * @param verticesStart defines vertex index start\n * @param verticesCount defines vertices count\n * @param indexStart defines index start\n * @param indexCount defines indices count\n * @param mesh defines the parent mesh\n * @param renderingMesh defines an optional rendering mesh\n * @param createBoundingBox defines if bounding box should be created for this submesh\n * @param addToMesh defines a boolean indicating that the submesh must be added to the mesh.subMeshes array (true by default)\n */\n constructor(\n /** the material index to use */\n materialIndex, \n /** vertex index start */\n verticesStart, \n /** vertices count */\n verticesCount, \n /** index start */\n indexStart, \n /** indices count */\n indexCount, mesh, renderingMesh, createBoundingBox = true, addToMesh = true) {\n this.materialIndex = materialIndex;\n this.verticesStart = verticesStart;\n this.verticesCount = verticesCount;\n this.indexStart = indexStart;\n this.indexCount = indexCount;\n this._mainDrawWrapperOverride = null;\n /** @internal */\n this._linesIndexCount = 0;\n this._linesIndexBuffer = null;\n /** @internal */\n this._lastColliderWorldVertices = null;\n /** @internal */\n this._lastColliderTransformMatrix = null;\n /** @internal */\n this._wasDispatched = false;\n /** @internal */\n this._renderId = 0;\n /** @internal */\n this._alphaIndex = 0;\n /** @internal */\n this._distanceToCamera = 0;\n this._currentMaterial = null;\n this._mesh = mesh;\n this._renderingMesh = renderingMesh || mesh;\n if (addToMesh) {\n mesh.subMeshes.push(this);\n }\n this._engine = this._mesh.getScene().getEngine();\n this.resetDrawCache();\n this._trianglePlanes = [];\n this._id = mesh.subMeshes.length - 1;\n if (createBoundingBox) {\n this.refreshBoundingInfo();\n mesh.computeWorldMatrix(true);\n }\n }\n /**\n * Returns true if this submesh covers the entire parent mesh\n * @ignorenaming\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n get IsGlobal() {\n return this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices() && this.indexStart === 0 && this.indexCount === this._mesh.getTotalIndices();\n }\n /**\n * Returns the submesh BoundingInfo object\n * @returns current bounding info (or mesh's one if the submesh is global)\n */\n getBoundingInfo() {\n if (this.IsGlobal) {\n return this._mesh.getBoundingInfo();\n }\n return this._boundingInfo;\n }\n /**\n * Sets the submesh BoundingInfo\n * @param boundingInfo defines the new bounding info to use\n * @returns the SubMesh\n */\n setBoundingInfo(boundingInfo) {\n this._boundingInfo = boundingInfo;\n return this;\n }\n /**\n * Returns the mesh of the current submesh\n * @returns the parent mesh\n */\n getMesh() {\n return this._mesh;\n }\n /**\n * Returns the rendering mesh of the submesh\n * @returns the rendering mesh (could be different from parent mesh)\n */\n getRenderingMesh() {\n return this._renderingMesh;\n }\n /**\n * Returns the replacement mesh of the submesh\n * @returns the replacement mesh (could be different from parent mesh)\n */\n getReplacementMesh() {\n return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : null;\n }\n /**\n * Returns the effective mesh of the submesh\n * @returns the effective mesh (could be different from parent mesh)\n */\n getEffectiveMesh() {\n const replacementMesh = this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : null;\n return replacementMesh ? replacementMesh : this._renderingMesh;\n }\n /**\n * Returns the submesh material\n * @param getDefaultMaterial Defines whether or not to get the default material if nothing has been defined.\n * @returns null or the current material\n */\n getMaterial(getDefaultMaterial = true) {\n var _a;\n const rootMaterial = (_a = this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId)) !== null && _a !== void 0 ? _a : this._renderingMesh.material;\n if (!rootMaterial) {\n return getDefaultMaterial ? this._mesh.getScene().defaultMaterial : null;\n }\n else if (this._isMultiMaterial(rootMaterial)) {\n const effectiveMaterial = rootMaterial.getSubMaterial(this.materialIndex);\n if (this._currentMaterial !== effectiveMaterial) {\n this._currentMaterial = effectiveMaterial;\n this.resetDrawCache();\n }\n return effectiveMaterial;\n }\n return rootMaterial;\n }\n _isMultiMaterial(material) {\n return material.getSubMaterial !== undefined;\n }\n // Methods\n /**\n * Sets a new updated BoundingInfo object to the submesh\n * @param data defines an optional position array to use to determine the bounding info\n * @returns the SubMesh\n */\n refreshBoundingInfo(data = null) {\n this._lastColliderWorldVertices = null;\n if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {\n return this;\n }\n if (!data) {\n data = this._renderingMesh.getVerticesData(VertexBuffer.PositionKind);\n }\n if (!data) {\n this._boundingInfo = this._mesh.getBoundingInfo();\n return this;\n }\n const indices = this._renderingMesh.getIndices();\n let extend;\n //is this the only submesh?\n if (this.indexStart === 0 && this.indexCount === indices.length) {\n const boundingInfo = this._renderingMesh.getBoundingInfo();\n //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.\n extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };\n }\n else {\n extend = extractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);\n }\n if (this._boundingInfo) {\n this._boundingInfo.reConstruct(extend.minimum, extend.maximum);\n }\n else {\n this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);\n }\n return this;\n }\n /**\n * @internal\n */\n _checkCollision(collider) {\n const boundingInfo = this.getBoundingInfo();\n return boundingInfo._checkCollision(collider);\n }\n /**\n * Updates the submesh BoundingInfo\n * @param world defines the world matrix to use to update the bounding info\n * @returns the submesh\n */\n updateBoundingInfo(world) {\n let boundingInfo = this.getBoundingInfo();\n if (!boundingInfo) {\n this.refreshBoundingInfo();\n boundingInfo = this.getBoundingInfo();\n }\n if (boundingInfo) {\n boundingInfo.update(world);\n }\n return this;\n }\n /**\n * True is the submesh bounding box intersects the frustum defined by the passed array of planes.\n * @param frustumPlanes defines the frustum planes\n * @returns true if the submesh is intersecting with the frustum\n */\n isInFrustum(frustumPlanes) {\n const boundingInfo = this.getBoundingInfo();\n if (!boundingInfo) {\n return false;\n }\n return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy);\n }\n /**\n * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes\n * @param frustumPlanes defines the frustum planes\n * @returns true if the submesh is inside the frustum\n */\n isCompletelyInFrustum(frustumPlanes) {\n const boundingInfo = this.getBoundingInfo();\n if (!boundingInfo) {\n return false;\n }\n return boundingInfo.isCompletelyInFrustum(frustumPlanes);\n }\n /**\n * Renders the submesh\n * @param enableAlphaMode defines if alpha needs to be used\n * @returns the submesh\n */\n render(enableAlphaMode) {\n this._renderingMesh.render(this, enableAlphaMode, this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : undefined);\n return this;\n }\n /**\n * @internal\n */\n _getLinesIndexBuffer(indices, engine) {\n if (!this._linesIndexBuffer) {\n const linesIndices = [];\n for (let index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {\n linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);\n }\n this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);\n this._linesIndexCount = linesIndices.length;\n }\n return this._linesIndexBuffer;\n }\n /**\n * Checks if the submesh intersects with a ray\n * @param ray defines the ray to test\n * @returns true is the passed ray intersects the submesh bounding box\n */\n canIntersects(ray) {\n const boundingInfo = this.getBoundingInfo();\n if (!boundingInfo) {\n return false;\n }\n return ray.intersectsBox(boundingInfo.boundingBox);\n }\n /**\n * Intersects current submesh with a ray\n * @param ray defines the ray to test\n * @param positions defines mesh's positions array\n * @param indices defines mesh's indices array\n * @param fastCheck defines if the first intersection will be used (and not the closest)\n * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected\n * @returns intersection info or null if no intersection\n */\n intersects(ray, positions, indices, fastCheck, trianglePredicate) {\n const material = this.getMaterial();\n if (!material) {\n return null;\n }\n let step = 3;\n let checkStopper = false;\n switch (material.fillMode) {\n case 3:\n case 5:\n case 6:\n case 8:\n return null;\n case 7:\n step = 1;\n checkStopper = true;\n break;\n default:\n break;\n }\n // LineMesh first as it's also a Mesh...\n if (material.fillMode === 4) {\n // Check if mesh is unindexed\n if (!indices.length) {\n return this._intersectUnIndexedLines(ray, positions, indices, this._mesh.intersectionThreshold, fastCheck);\n }\n return this._intersectLines(ray, positions, indices, this._mesh.intersectionThreshold, fastCheck);\n }\n else {\n // Check if mesh is unindexed\n if (!indices.length && this._mesh._unIndexed) {\n return this._intersectUnIndexedTriangles(ray, positions, indices, fastCheck, trianglePredicate);\n }\n return this._intersectTriangles(ray, positions, indices, step, checkStopper, fastCheck, trianglePredicate);\n }\n }\n /**\n * @internal\n */\n _intersectLines(ray, positions, indices, intersectionThreshold, fastCheck) {\n let intersectInfo = null;\n // Line test\n for (let index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {\n const p0 = positions[indices[index]];\n const p1 = positions[indices[index + 1]];\n const length = ray.intersectionSegment(p0, p1, intersectionThreshold);\n if (length < 0) {\n continue;\n }\n if (fastCheck || !intersectInfo || length < intersectInfo.distance) {\n intersectInfo = new IntersectionInfo(null, null, length);\n intersectInfo.faceId = index / 2;\n if (fastCheck) {\n break;\n }\n }\n }\n return intersectInfo;\n }\n /**\n * @internal\n */\n _intersectUnIndexedLines(ray, positions, indices, intersectionThreshold, fastCheck) {\n let intersectInfo = null;\n // Line test\n for (let index = this.verticesStart; index < this.verticesStart + this.verticesCount; index += 2) {\n const p0 = positions[index];\n const p1 = positions[index + 1];\n const length = ray.intersectionSegment(p0, p1, intersectionThreshold);\n if (length < 0) {\n continue;\n }\n if (fastCheck || !intersectInfo || length < intersectInfo.distance) {\n intersectInfo = new IntersectionInfo(null, null, length);\n intersectInfo.faceId = index / 2;\n if (fastCheck) {\n break;\n }\n }\n }\n return intersectInfo;\n }\n /**\n * @internal\n */\n _intersectTriangles(ray, positions, indices, step, checkStopper, fastCheck, trianglePredicate) {\n let intersectInfo = null;\n // Triangles test\n let faceId = -1;\n for (let index = this.indexStart; index < this.indexStart + this.indexCount - (3 - step); index += step) {\n faceId++;\n const indexA = indices[index];\n const indexB = indices[index + 1];\n const indexC = indices[index + 2];\n if (checkStopper && indexC === 0xffffffff) {\n index += 2;\n continue;\n }\n const p0 = positions[indexA];\n const p1 = positions[indexB];\n const p2 = positions[indexC];\n // stay defensive and don't check against undefined positions.\n if (!p0 || !p1 || !p2) {\n continue;\n }\n if (trianglePredicate && !trianglePredicate(p0, p1, p2, ray, indexA, indexB, indexC)) {\n continue;\n }\n const currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);\n if (currentIntersectInfo) {\n if (currentIntersectInfo.distance < 0) {\n continue;\n }\n if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {\n intersectInfo = currentIntersectInfo;\n intersectInfo.faceId = faceId;\n if (fastCheck) {\n break;\n }\n }\n }\n }\n return intersectInfo;\n }\n /**\n * @internal\n */\n _intersectUnIndexedTriangles(ray, positions, indices, fastCheck, trianglePredicate) {\n let intersectInfo = null;\n // Triangles test\n for (let index = this.verticesStart; index < this.verticesStart + this.verticesCount; index += 3) {\n const p0 = positions[index];\n const p1 = positions[index + 1];\n const p2 = positions[index + 2];\n if (trianglePredicate && !trianglePredicate(p0, p1, p2, ray, -1, -1, -1)) {\n continue;\n }\n const currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);\n if (currentIntersectInfo) {\n if (currentIntersectInfo.distance < 0) {\n continue;\n }\n if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {\n intersectInfo = currentIntersectInfo;\n intersectInfo.faceId = index / 3;\n if (fastCheck) {\n break;\n }\n }\n }\n }\n return intersectInfo;\n }\n /** @internal */\n _rebuild() {\n if (this._linesIndexBuffer) {\n this._linesIndexBuffer = null;\n }\n }\n // Clone\n /**\n * Creates a new submesh from the passed mesh\n * @param newMesh defines the new hosting mesh\n * @param newRenderingMesh defines an optional rendering mesh\n * @returns the new submesh\n */\n clone(newMesh, newRenderingMesh) {\n const result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);\n if (!this.IsGlobal) {\n const boundingInfo = this.getBoundingInfo();\n if (!boundingInfo) {\n return result;\n }\n result._boundingInfo = new BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);\n }\n return result;\n }\n // Dispose\n /**\n * Release associated resources\n */\n dispose() {\n if (this._linesIndexBuffer) {\n this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);\n this._linesIndexBuffer = null;\n }\n // Remove from mesh\n const index = this._mesh.subMeshes.indexOf(this);\n this._mesh.subMeshes.splice(index, 1);\n this.resetDrawCache();\n }\n /**\n * Gets the class name\n * @returns the string \"SubMesh\".\n */\n getClassName() {\n return \"SubMesh\";\n }\n // Statics\n /**\n * Creates a new submesh from indices data\n * @param materialIndex the index of the main mesh material\n * @param startIndex the index where to start the copy in the mesh indices array\n * @param indexCount the number of indices to copy then from the startIndex\n * @param mesh the main mesh to create the submesh from\n * @param renderingMesh the optional rendering mesh\n * @param createBoundingBox defines if bounding box should be created for this submesh\n * @returns a new submesh\n */\n static CreateFromIndices(materialIndex, startIndex, indexCount, mesh, renderingMesh, createBoundingBox = true) {\n let minVertexIndex = Number.MAX_VALUE;\n let maxVertexIndex = -Number.MAX_VALUE;\n const whatWillRender = renderingMesh || mesh;\n const indices = whatWillRender.getIndices();\n for (let index = startIndex; index < startIndex + indexCount; index++) {\n const vertexIndex = indices[index];\n if (vertexIndex < minVertexIndex) {\n minVertexIndex = vertexIndex;\n }\n if (vertexIndex > maxVertexIndex) {\n maxVertexIndex = vertexIndex;\n }\n }\n return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh, createBoundingBox);\n }\n}\n//# sourceMappingURL=subMesh.js.map","import { __decorate } from \"../tslib.es6.js\";\nimport { serialize, serializeAsVector3, serializeAsQuaternion, SerializationHelper } from \"../Misc/decorators.js\";\nimport { Observable } from \"../Misc/observable.js\";\nimport { Quaternion, Matrix, Vector3, TmpVectors } from \"../Maths/math.vector.js\";\nimport { Node } from \"../node.js\";\nimport { Space } from \"../Maths/math.axis.js\";\nconst convertRHSToLHS = Matrix.Compose(Vector3.One(), Quaternion.FromEulerAngles(0, Math.PI, 0), Vector3.Zero());\n/**\n * A TransformNode is an object that is not rendered but can be used as a center of transformation. This can decrease memory usage and increase rendering speed compared to using an empty mesh as a parent and is less complicated than using a pivot matrix.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/parent_pivot/transform_node\n */\nexport class TransformNode extends Node {\n /**\n * Gets or sets the billboard mode. Default is 0.\n *\n * | Value | Type | Description |\n * | --- | --- | --- |\n * | 0 | BILLBOARDMODE_NONE | |\n * | 1 | BILLBOARDMODE_X | |\n * | 2 | BILLBOARDMODE_Y | |\n * | 4 | BILLBOARDMODE_Z | |\n * | 7 | BILLBOARDMODE_ALL | |\n *\n */\n get billboardMode() {\n return this._billboardMode;\n }\n set billboardMode(value) {\n if (this._billboardMode === value) {\n return;\n }\n this._billboardMode = value;\n this._cache.useBillboardPosition = (this._billboardMode & TransformNode.BILLBOARDMODE_USE_POSITION) !== 0;\n this._computeUseBillboardPath();\n }\n /**\n * Gets or sets a boolean indicating that parent rotation should be preserved when using billboards.\n * This could be useful for glTF objects where parent rotation helps converting from right handed to left handed\n */\n get preserveParentRotationForBillboard() {\n return this._preserveParentRotationForBillboard;\n }\n set preserveParentRotationForBillboard(value) {\n if (value === this._preserveParentRotationForBillboard) {\n return;\n }\n this._preserveParentRotationForBillboard = value;\n this._computeUseBillboardPath();\n }\n _computeUseBillboardPath() {\n this._cache.useBillboardPath = this._billboardMode !== TransformNode.BILLBOARDMODE_NONE && !this.preserveParentRotationForBillboard;\n }\n /**\n * Gets or sets the distance of the object to max, often used by skybox\n */\n get infiniteDistance() {\n return this._infiniteDistance;\n }\n set infiniteDistance(value) {\n if (this._infiniteDistance === value) {\n return;\n }\n this._infiniteDistance = value;\n }\n constructor(name, scene = null, isPure = true) {\n super(name, scene);\n this._forward = new Vector3(0, 0, 1);\n this._up = new Vector3(0, 1, 0);\n this._right = new Vector3(1, 0, 0);\n // Properties\n this._position = Vector3.Zero();\n this._rotation = Vector3.Zero();\n this._rotationQuaternion = null;\n this._scaling = Vector3.One();\n this._transformToBoneReferal = null;\n this._isAbsoluteSynced = false;\n this._billboardMode = TransformNode.BILLBOARDMODE_NONE;\n this._preserveParentRotationForBillboard = false;\n /**\n * Multiplication factor on scale x/y/z when computing the world matrix. Eg. for a 1x1x1 cube setting this to 2 will make it a 2x2x2 cube\n */\n this.scalingDeterminant = 1;\n this._infiniteDistance = false;\n /**\n * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.\n * By default the system will update normals to compensate\n */\n this.ignoreNonUniformScaling = false;\n /**\n * Gets or sets a boolean indicating that even if rotationQuaternion is defined, you can keep updating rotation property and Babylon.js will just mix both\n */\n this.reIntegrateRotationIntoRotationQuaternion = false;\n // Cache\n /** @internal */\n this._poseMatrix = null;\n /** @internal */\n this._localMatrix = Matrix.Zero();\n this._usePivotMatrix = false;\n this._absolutePosition = Vector3.Zero();\n this._absoluteScaling = Vector3.Zero();\n this._absoluteRotationQuaternion = Quaternion.Identity();\n this._pivotMatrix = Matrix.Identity();\n /** @internal */\n this._postMultiplyPivotMatrix = false;\n this._isWorldMatrixFrozen = false;\n /** @internal */\n this._indexInSceneTransformNodesArray = -1;\n /**\n * An event triggered after the world matrix is updated\n */\n this.onAfterWorldMatrixUpdateObservable = new Observable();\n this._nonUniformScaling = false;\n if (isPure) {\n this.getScene().addTransformNode(this);\n }\n }\n /**\n * Gets a string identifying the name of the class\n * @returns \"TransformNode\" string\n */\n getClassName() {\n return \"TransformNode\";\n }\n /**\n * Gets or set the node position (default is (0.0, 0.0, 0.0))\n */\n get position() {\n return this._position;\n }\n set position(newPosition) {\n this._position = newPosition;\n this._isDirty = true;\n }\n /**\n * return true if a pivot has been set\n * @returns true if a pivot matrix is used\n */\n isUsingPivotMatrix() {\n return this._usePivotMatrix;\n }\n /**\n * Gets or sets the rotation property : a Vector3 defining the rotation value in radians around each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).\n * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion\n */\n get rotation() {\n return this._rotation;\n }\n set rotation(newRotation) {\n this._rotation = newRotation;\n this._rotationQuaternion = null;\n this._isDirty = true;\n }\n /**\n * Gets or sets the scaling property : a Vector3 defining the node scaling along each local axis X, Y, Z (default is (1.0, 1.0, 1.0)).\n */\n get scaling() {\n return this._scaling;\n }\n set scaling(newScaling) {\n this._scaling = newScaling;\n this._isDirty = true;\n }\n /**\n * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (undefined by default, but can be null).\n * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)\n */\n get rotationQuaternion() {\n return this._rotationQuaternion;\n }\n set rotationQuaternion(quaternion) {\n this._rotationQuaternion = quaternion;\n //reset the rotation vector.\n if (quaternion) {\n this._rotation.setAll(0.0);\n }\n this._isDirty = true;\n }\n /**\n * The forward direction of that transform in world space.\n */\n get forward() {\n Vector3.TransformNormalFromFloatsToRef(0, 0, this.getScene().useRightHandedSystem ? -1.0 : 1.0, this.getWorldMatrix(), this._forward);\n return this._forward.normalize();\n }\n /**\n * The up direction of that transform in world space.\n */\n get up() {\n Vector3.TransformNormalFromFloatsToRef(0, 1, 0, this.getWorldMatrix(), this._up);\n return this._up.normalize();\n }\n /**\n * The right direction of that transform in world space.\n */\n get right() {\n Vector3.TransformNormalFromFloatsToRef(this.getScene().useRightHandedSystem ? -1.0 : 1.0, 0, 0, this.getWorldMatrix(), this._right);\n return this._right.normalize();\n }\n /**\n * Copies the parameter passed Matrix into the mesh Pose matrix.\n * @param matrix the matrix to copy the pose from\n * @returns this TransformNode.\n */\n updatePoseMatrix(matrix) {\n if (!this._poseMatrix) {\n this._poseMatrix = matrix.clone();\n return this;\n }\n this._poseMatrix.copyFrom(matrix);\n return this;\n }\n /**\n * Returns the mesh Pose matrix.\n * @returns the pose matrix\n */\n getPoseMatrix() {\n if (!this._poseMatrix) {\n this._poseMatrix = Matrix.Identity();\n }\n return this._poseMatrix;\n }\n /** @internal */\n _isSynchronized() {\n const cache = this._cache;\n if (this._billboardMode !== cache.billboardMode || this._billboardMode !== TransformNode.BILLBOARDMODE_NONE) {\n return false;\n }\n if (cache.pivotMatrixUpdated) {\n return false;\n }\n if (this._infiniteDistance) {\n return false;\n }\n if (this._position._isDirty) {\n return false;\n }\n if (this._scaling._isDirty) {\n return false;\n }\n if ((this._rotationQuaternion && this._rotationQuaternion._isDirty) || this._rotation._isDirty) {\n return false;\n }\n return true;\n }\n /** @internal */\n _initCache() {\n super._initCache();\n const cache = this._cache;\n cache.localMatrixUpdated = false;\n cache.billboardMode = -1;\n cache.infiniteDistance = false;\n cache.useBillboardPosition = false;\n cache.useBillboardPath = false;\n }\n /**\n * Returns the current mesh absolute position.\n * Returns a Vector3.\n */\n get absolutePosition() {\n return this.getAbsolutePosition();\n }\n /**\n * Returns the current mesh absolute scaling.\n * Returns a Vector3.\n */\n get absoluteScaling() {\n this._syncAbsoluteScalingAndRotation();\n return this._absoluteScaling;\n }\n /**\n * Returns the current mesh absolute rotation.\n * Returns a Quaternion.\n */\n get absoluteRotationQuaternion() {\n this._syncAbsoluteScalingAndRotation();\n return this._absoluteRotationQuaternion;\n }\n /**\n * Sets a new matrix to apply before all other transformation\n * @param matrix defines the transform matrix\n * @returns the current TransformNode\n */\n setPreTransformMatrix(matrix) {\n return this.setPivotMatrix(matrix, false);\n }\n /**\n * Sets a new pivot matrix to the current node\n * @param matrix defines the new pivot matrix to use\n * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect\n * @returns the current TransformNode\n */\n setPivotMatrix(matrix, postMultiplyPivotMatrix = true) {\n this._pivotMatrix.copyFrom(matrix);\n this._usePivotMatrix = !this._pivotMatrix.isIdentity();\n this._cache.pivotMatrixUpdated = true;\n this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;\n if (this._postMultiplyPivotMatrix) {\n if (!this._pivotMatrixInverse) {\n this._pivotMatrixInverse = Matrix.Invert(this._pivotMatrix);\n }\n else {\n this._pivotMatrix.invertToRef(this._pivotMatrixInverse);\n }\n }\n return this;\n }\n /**\n * Returns the mesh pivot matrix.\n * Default : Identity.\n * @returns the matrix\n */\n getPivotMatrix() {\n return this._pivotMatrix;\n }\n /**\n * Instantiate (when possible) or clone that node with its hierarchy\n * @param newParent defines the new parent to use for the instance (or clone)\n * @param options defines options to configure how copy is done\n * @param options.doNotInstantiate defines if the model must be instantiated or just cloned\n * @param onNewNodeCreated defines an option callback to call when a clone or an instance is created\n * @returns an instance (or a clone) of the current node with its hierarchy\n */\n instantiateHierarchy(newParent = null, options, onNewNodeCreated) {\n const clone = this.clone(\"Clone of \" + (this.name || this.id), newParent || this.parent, true);\n if (clone) {\n if (onNewNodeCreated) {\n onNewNodeCreated(this, clone);\n }\n }\n for (const child of this.getChildTransformNodes(true)) {\n child.instantiateHierarchy(clone, options, onNewNodeCreated);\n }\n return clone;\n }\n /**\n * Prevents the World matrix to be computed any longer\n * @param newWorldMatrix defines an optional matrix to use as world matrix\n * @param decompose defines whether to decompose the given newWorldMatrix or directly assign\n * @returns the TransformNode.\n */\n freezeWorldMatrix(newWorldMatrix = null, decompose = false) {\n if (newWorldMatrix) {\n if (decompose) {\n this._rotation.setAll(0);\n this._rotationQuaternion = this._rotationQuaternion || Quaternion.Identity();\n newWorldMatrix.decompose(this._scaling, this._rotationQuaternion, this._position);\n this.computeWorldMatrix(true);\n }\n else {\n this._worldMatrix = newWorldMatrix;\n this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);\n this._afterComputeWorldMatrix();\n }\n }\n else {\n this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily\n this.computeWorldMatrix(true);\n }\n this._isDirty = false;\n this._isWorldMatrixFrozen = true;\n return this;\n }\n /**\n * Allows back the World matrix computation.\n * @returns the TransformNode.\n */\n unfreezeWorldMatrix() {\n this._isWorldMatrixFrozen = false;\n this.computeWorldMatrix(true);\n return this;\n }\n /**\n * True if the World matrix has been frozen.\n */\n get isWorldMatrixFrozen() {\n return this._isWorldMatrixFrozen;\n }\n /**\n * Returns the mesh absolute position in the World.\n * @returns a Vector3.\n */\n getAbsolutePosition() {\n this.computeWorldMatrix();\n return this._absolutePosition;\n }\n /**\n * Sets the mesh absolute position in the World from a Vector3 or an Array(3).\n * @param absolutePosition the absolute position to set\n * @returns the TransformNode.\n */\n setAbsolutePosition(absolutePosition) {\n if (!absolutePosition) {\n return this;\n }\n let absolutePositionX;\n let absolutePositionY;\n let absolutePositionZ;\n if (absolutePosition.x === undefined) {\n if (arguments.length < 3) {\n return this;\n }\n absolutePositionX = arguments[0];\n absolutePositionY = arguments[1];\n absolutePositionZ = arguments[2];\n }\n else {\n absolutePositionX = absolutePosition.x;\n absolutePositionY = absolutePosition.y;\n absolutePositionZ = absolutePosition.z;\n }\n if (this.parent) {\n const invertParentWorldMatrix = TmpVectors.Matrix[0];\n this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix);\n Vector3.TransformCoordinatesFromFloatsToRef(absolutePositionX, absolutePositionY, absolutePositionZ, invertParentWorldMatrix, this.position);\n }\n else {\n this.position.x = absolutePositionX;\n this.position.y = absolutePositionY;\n this.position.z = absolutePositionZ;\n }\n this._absolutePosition.copyFrom(absolutePosition);\n return this;\n }\n /**\n * Sets the mesh position in its local space.\n * @param vector3 the position to set in localspace\n * @returns the TransformNode.\n */\n setPositionWithLocalVector(vector3) {\n this.computeWorldMatrix();\n this.position = Vector3.TransformNormal(vector3, this._localMatrix);\n return this;\n }\n /**\n * Returns the mesh position in the local space from the current World matrix values.\n * @returns a new Vector3.\n */\n getPositionExpressedInLocalSpace() {\n this.computeWorldMatrix();\n const invLocalWorldMatrix = TmpVectors.Matrix[0];\n this._localMatrix.invertToRef(invLocalWorldMatrix);\n return Vector3.TransformNormal(this.position, invLocalWorldMatrix);\n }\n /**\n * Translates the mesh along the passed Vector3 in its local space.\n * @param vector3 the distance to translate in localspace\n * @returns the TransformNode.\n */\n locallyTranslate(vector3) {\n this.computeWorldMatrix(true);\n this.position = Vector3.TransformCoordinates(vector3, this._localMatrix);\n return this;\n }\n /**\n * Orients a mesh towards a target point. Mesh must be drawn facing user.\n * @param targetPoint the position (must be in same space as current mesh) to look at\n * @param yawCor optional yaw (y-axis) correction in radians\n * @param pitchCor optional pitch (x-axis) correction in radians\n * @param rollCor optional roll (z-axis) correction in radians\n * @param space the chosen space of the target\n * @returns the TransformNode.\n */\n lookAt(targetPoint, yawCor = 0, pitchCor = 0, rollCor = 0, space = Space.LOCAL) {\n const dv = TransformNode._LookAtVectorCache;\n const pos = space === Space.LOCAL ? this.position : this.getAbsolutePosition();\n targetPoint.subtractToRef(pos, dv);\n this.setDirection(dv, yawCor, pitchCor, rollCor);\n // Correct for parent's rotation offset\n if (space === Space.WORLD && this.parent) {\n if (this.rotationQuaternion) {\n // Get local rotation matrix of the looking object\n const rotationMatrix = TmpVectors.Matrix[0];\n this.rotationQuaternion.toRotationMatrix(rotationMatrix);\n // Offset rotation by parent's inverted rotation matrix to correct in world space\n const parentRotationMatrix = TmpVectors.Matrix[1];\n this.parent.getWorldMatrix().getRotationMatrixToRef(parentRotationMatrix);\n parentRotationMatrix.invert();\n rotationMatrix.multiplyToRef(parentRotationMatrix, rotationMatrix);\n this.rotationQuaternion.fromRotationMatrix(rotationMatrix);\n }\n else {\n // Get local rotation matrix of the looking object\n const quaternionRotation = TmpVectors.Quaternion[0];\n Quaternion.FromEulerVectorToRef(this.rotation, quaternionRotation);\n const rotationMatrix = TmpVectors.Matrix[0];\n quaternionRotation.toRotationMatrix(rotationMatrix);\n // Offset rotation by parent's inverted rotation matrix to correct in world space\n const parentRotationMatrix = TmpVectors.Matrix[1];\n this.parent.getWorldMatrix().getRotationMatrixToRef(parentRotationMatrix);\n parentRotationMatrix.invert();\n rotationMatrix.multiplyToRef(parentRotationMatrix, rotationMatrix);\n quaternionRotation.fromRotationMatrix(rotationMatrix);\n quaternionRotation.toEulerAnglesToRef(this.rotation);\n }\n }\n return this;\n }\n /**\n * Returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.\n * This Vector3 is expressed in the World space.\n * @param localAxis axis to rotate\n * @returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.\n */\n getDirection(localAxis) {\n const result = Vector3.Zero();\n this.getDirectionToRef(localAxis, result);\n return result;\n }\n /**\n * Sets the Vector3 \"result\" as the rotated Vector3 \"localAxis\" in the same rotation than the mesh.\n * localAxis is expressed in the mesh local space.\n * result is computed in the World space from the mesh World matrix.\n * @param localAxis axis to rotate\n * @param result the resulting transformnode\n * @returns this TransformNode.\n */\n getDirectionToRef(localAxis, result) {\n Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);\n return this;\n }\n /**\n * Sets this transform node rotation to the given local axis.\n * @param localAxis the axis in local space\n * @param yawCor optional yaw (y-axis) correction in radians\n * @param pitchCor optional pitch (x-axis) correction in radians\n * @param rollCor optional roll (z-axis) correction in radians\n * @returns this TransformNode\n */\n setDirection(localAxis, yawCor = 0, pitchCor = 0, rollCor = 0) {\n const yaw = -Math.atan2(localAxis.z, localAxis.x) + Math.PI / 2;\n const len = Math.sqrt(localAxis.x * localAxis.x + localAxis.z * localAxis.z);\n const pitch = -Math.atan2(localAxis.y, len);\n if (this.rotationQuaternion) {\n Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);\n }\n else {\n this.rotation.x = pitch + pitchCor;\n this.rotation.y = yaw + yawCor;\n this.rotation.z = rollCor;\n }\n return this;\n }\n /**\n * Sets a new pivot point to the current node\n * @param point defines the new pivot point to use\n * @param space defines if the point is in world or local space (local by default)\n * @returns the current TransformNode\n */\n setPivotPoint(point, space = Space.LOCAL) {\n if (this.getScene().getRenderId() == 0) {\n this.computeWorldMatrix(true);\n }\n const wm = this.getWorldMatrix();\n if (space == Space.WORLD) {\n const tmat = TmpVectors.Matrix[0];\n wm.invertToRef(tmat);\n point = Vector3.TransformCoordinates(point, tmat);\n }\n return this.setPivotMatrix(Matrix.Translation(-point.x, -point.y, -point.z), true);\n }\n /**\n * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.\n * @returns the pivot point\n */\n getPivotPoint() {\n const point = Vector3.Zero();\n this.getPivotPointToRef(point);\n return point;\n }\n /**\n * Sets the passed Vector3 \"result\" with the coordinates of the mesh pivot point in the local space.\n * @param result the vector3 to store the result\n * @returns this TransformNode.\n */\n getPivotPointToRef(result) {\n result.x = -this._pivotMatrix.m[12];\n result.y = -this._pivotMatrix.m[13];\n result.z = -this._pivotMatrix.m[14];\n return this;\n }\n /**\n * Returns a new Vector3 set with the mesh pivot point World coordinates.\n * @returns a new Vector3 set with the mesh pivot point World coordinates.\n */\n getAbsolutePivotPoint() {\n const point = Vector3.Zero();\n this.getAbsolutePivotPointToRef(point);\n return point;\n }\n /**\n * Sets the Vector3 \"result\" coordinates with the mesh pivot point World coordinates.\n * @param result vector3 to store the result\n * @returns this TransformNode.\n */\n getAbsolutePivotPointToRef(result) {\n this.getPivotPointToRef(result);\n Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);\n return this;\n }\n /**\n * Flag the transform node as dirty (Forcing it to update everything)\n * @param property if set to \"rotation\" the objects rotationQuaternion will be set to null\n * @returns this node\n */\n markAsDirty(property) {\n if (this._isDirty) {\n return this;\n }\n // We need to explicitly update the children\n // as the scene.evaluateActiveMeshes will not poll the transform nodes\n if (this._children) {\n for (const child of this._children) {\n child.markAsDirty(property);\n }\n }\n return super.markAsDirty(property);\n }\n /**\n * Defines the passed node as the parent of the current node.\n * The node will remain exactly where it is and its position / rotation will be updated accordingly.\n * Note that if the mesh has a pivot matrix / point defined it will be applied after the parent was updated.\n * In that case the node will not remain in the same space as it is, as the pivot will be applied.\n * To avoid this, you can set updatePivot to true and the pivot will be updated to identity\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/parent_pivot/parent\n * @param node the node ot set as the parent\n * @param preserveScalingSign if true, keep scaling sign of child. Otherwise, scaling sign might change.\n * @param updatePivot if true, update the pivot matrix to keep the node in the same space as before\n * @returns this TransformNode.\n */\n setParent(node, preserveScalingSign = false, updatePivot = false) {\n if (!node && !this.parent) {\n return this;\n }\n const quatRotation = TmpVectors.Quaternion[0];\n const position = TmpVectors.Vector3[0];\n const scale = TmpVectors.Vector3[1];\n const invParentMatrix = TmpVectors.Matrix[1];\n Matrix.IdentityToRef(invParentMatrix);\n const composedMatrix = TmpVectors.Matrix[0];\n this.computeWorldMatrix(true);\n let currentRotation = this.rotationQuaternion;\n if (!currentRotation) {\n currentRotation = TransformNode._TmpRotation;\n Quaternion.RotationYawPitchRollToRef(this._rotation.y, this._rotation.x, this._rotation.z, currentRotation);\n }\n // current global transformation without pivot\n Matrix.ComposeToRef(this.scaling, currentRotation, this.position, composedMatrix);\n if (this.parent) {\n composedMatrix.multiplyToRef(this.parent.computeWorldMatrix(true), composedMatrix);\n }\n // is a node was set, calculate the difference between this and the node\n if (node) {\n node.computeWorldMatrix(true).invertToRef(invParentMatrix);\n composedMatrix.multiplyToRef(invParentMatrix, composedMatrix);\n }\n composedMatrix.decompose(scale, quatRotation, position, preserveScalingSign ? this : undefined);\n if (this.rotationQuaternion) {\n this.rotationQuaternion.copyFrom(quatRotation);\n }\n else {\n quatRotation.toEulerAnglesToRef(this.rotation);\n }\n this.scaling.copyFrom(scale);\n this.position.copyFrom(position);\n this.parent = node;\n if (updatePivot) {\n this.setPivotMatrix(Matrix.Identity());\n }\n return this;\n }\n /**\n * True if the scaling property of this object is non uniform eg. (1,2,1)\n */\n get nonUniformScaling() {\n return this._nonUniformScaling;\n }\n /**\n * @internal\n */\n _updateNonUniformScalingState(value) {\n if (this._nonUniformScaling === value) {\n return false;\n }\n this._nonUniformScaling = value;\n return true;\n }\n /**\n * Attach the current TransformNode to another TransformNode associated with a bone\n * @param bone Bone affecting the TransformNode\n * @param affectedTransformNode TransformNode associated with the bone\n * @returns this object\n */\n attachToBone(bone, affectedTransformNode) {\n this._currentParentWhenAttachingToBone = this.parent;\n this._transformToBoneReferal = affectedTransformNode;\n this.parent = bone;\n bone.getSkeleton().prepare(); // make sure bone.getFinalMatrix() is up to date\n if (bone.getFinalMatrix().determinant() < 0) {\n this.scalingDeterminant *= -1;\n }\n return this;\n }\n /**\n * Detach the transform node if its associated with a bone\n * @param resetToPreviousParent Indicates if the parent that was in effect when attachToBone was called should be set back or if we should set parent to null instead (defaults to the latter)\n * @returns this object\n */\n detachFromBone(resetToPreviousParent = false) {\n if (!this.parent) {\n if (resetToPreviousParent) {\n this.parent = this._currentParentWhenAttachingToBone;\n }\n return this;\n }\n if (this.parent.getWorldMatrix().determinant() < 0) {\n this.scalingDeterminant *= -1;\n }\n this._transformToBoneReferal = null;\n if (resetToPreviousParent) {\n this.parent = this._currentParentWhenAttachingToBone;\n }\n else {\n this.parent = null;\n }\n return this;\n }\n /**\n * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.\n * space (default LOCAL) can be either Space.LOCAL, either Space.WORLD.\n * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.\n * The passed axis is also normalized.\n * @param axis the axis to rotate around\n * @param amount the amount to rotate in radians\n * @param space Space to rotate in (Default: local)\n * @returns the TransformNode.\n */\n rotate(axis, amount, space) {\n axis.normalize();\n if (!this.rotationQuaternion) {\n this.rotationQuaternion = this.rotation.toQuaternion();\n this.rotation.setAll(0);\n }\n let rotationQuaternion;\n if (!space || space === Space.LOCAL) {\n rotationQuaternion = Quaternion.RotationAxisToRef(axis, amount, TransformNode._RotationAxisCache);\n this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);\n }\n else {\n if (this.parent) {\n const invertParentWorldMatrix = TmpVectors.Matrix[0];\n this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix);\n axis = Vector3.TransformNormal(axis, invertParentWorldMatrix);\n }\n rotationQuaternion = Quaternion.RotationAxisToRef(axis, amount, TransformNode._RotationAxisCache);\n rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);\n }\n return this;\n }\n /**\n * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.\n * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.\n * The passed axis is also normalized. .\n * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm\n * @param point the point to rotate around\n * @param axis the axis to rotate around\n * @param amount the amount to rotate in radians\n * @returns the TransformNode\n */\n rotateAround(point, axis, amount) {\n axis.normalize();\n if (!this.rotationQuaternion) {\n this.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);\n this.rotation.setAll(0);\n }\n const tmpVector = TmpVectors.Vector3[0];\n const finalScale = TmpVectors.Vector3[1];\n const finalTranslation = TmpVectors.Vector3[2];\n const finalRotation = TmpVectors.Quaternion[0];\n const translationMatrix = TmpVectors.Matrix[0]; // T\n const translationMatrixInv = TmpVectors.Matrix[1]; // T'\n const rotationMatrix = TmpVectors.Matrix[2]; // R\n const finalMatrix = TmpVectors.Matrix[3]; // T' x R x T\n point.subtractToRef(this.position, tmpVector);\n Matrix.TranslationToRef(tmpVector.x, tmpVector.y, tmpVector.z, translationMatrix); // T\n Matrix.TranslationToRef(-tmpVector.x, -tmpVector.y, -tmpVector.z, translationMatrixInv); // T'\n Matrix.RotationAxisToRef(axis, amount, rotationMatrix); // R\n translationMatrixInv.multiplyToRef(rotationMatrix, finalMatrix); // T' x R\n finalMatrix.multiplyToRef(translationMatrix, finalMatrix); // T' x R x T\n finalMatrix.decompose(finalScale, finalRotation, finalTranslation);\n this.position.addInPlace(finalTranslation);\n finalRotation.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);\n return this;\n }\n /**\n * Translates the mesh along the axis vector for the passed distance in the given space.\n * space (default LOCAL) can be either Space.LOCAL, either Space.WORLD.\n * @param axis the axis to translate in\n * @param distance the distance to translate\n * @param space Space to rotate in (Default: local)\n * @returns the TransformNode.\n */\n translate(axis, distance, space) {\n const displacementVector = axis.scale(distance);\n if (!space || space === Space.LOCAL) {\n const tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);\n this.setPositionWithLocalVector(tempV3);\n }\n else {\n this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));\n }\n return this;\n }\n /**\n * Adds a rotation step to the mesh current rotation.\n * x, y, z are Euler angles expressed in radians.\n * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.\n * This means this rotation is made in the mesh local space only.\n * It's useful to set a custom rotation order different from the BJS standard one YXZ.\n * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.\n * ```javascript\n * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);\n * ```\n * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.\n * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.\n * @param x Rotation to add\n * @param y Rotation to add\n * @param z Rotation to add\n * @returns the TransformNode.\n */\n addRotation(x, y, z) {\n let rotationQuaternion;\n if (this.rotationQuaternion) {\n rotationQuaternion = this.rotationQuaternion;\n }\n else {\n rotationQuaternion = TmpVectors.Quaternion[1];\n Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);\n }\n const accumulation = TmpVectors.Quaternion[0];\n Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);\n rotationQuaternion.multiplyInPlace(accumulation);\n if (!this.rotationQuaternion) {\n rotationQuaternion.toEulerAnglesToRef(this.rotation);\n }\n return this;\n }\n /**\n * @internal\n */\n _getEffectiveParent() {\n return this.parent;\n }\n /**\n * Returns whether the transform node world matrix computation needs the camera information to be computed.\n * This is the case when the node is a billboard or has an infinite distance for instance.\n * @returns true if the world matrix computation needs the camera information to be computed\n */\n isWorldMatrixCameraDependent() {\n return (this._infiniteDistance && !this.parent) || (this._billboardMode !== TransformNode.BILLBOARDMODE_NONE && !this.preserveParentRotationForBillboard);\n }\n /**\n * Computes the world matrix of the node\n * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch\n * @param camera defines the camera used if different from the scene active camera (This is used with modes like Billboard or infinite distance)\n * @returns the world matrix\n */\n computeWorldMatrix(force = false, camera = null) {\n if (this._isWorldMatrixFrozen && !this._isDirty) {\n return this._worldMatrix;\n }\n const currentRenderId = this.getScene().getRenderId();\n if (!this._isDirty && !force && (this._currentRenderId === currentRenderId || this.isSynchronized())) {\n this._currentRenderId = currentRenderId;\n return this._worldMatrix;\n }\n camera = camera || this.getScene().activeCamera;\n this._updateCache();\n const cache = this._cache;\n cache.pivotMatrixUpdated = false;\n cache.billboardMode = this.billboardMode;\n cache.infiniteDistance = this.infiniteDistance;\n cache.parent = this._parentNode;\n this._currentRenderId = currentRenderId;\n this._childUpdateId += 1;\n this._isDirty = false;\n this._position._isDirty = false;\n this._rotation._isDirty = false;\n this._scaling._isDirty = false;\n const parent = this._getEffectiveParent();\n // Scaling\n const scaling = TransformNode._TmpScaling;\n let translation = this._position;\n // Translation\n if (this._infiniteDistance) {\n if (!this.parent && camera) {\n const cameraWorldMatrix = camera.getWorldMatrix();\n const cameraGlobalPosition = new Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);\n translation = TransformNode._TmpTranslation;\n translation.copyFromFloats(this._position.x + cameraGlobalPosition.x, this._position.y + cameraGlobalPosition.y, this._position.z + cameraGlobalPosition.z);\n }\n }\n // Scaling\n scaling.copyFromFloats(this._scaling.x * this.scalingDeterminant, this._scaling.y * this.scalingDeterminant, this._scaling.z * this.scalingDeterminant);\n // Rotation\n let rotation;\n if (this._rotationQuaternion) {\n this._rotationQuaternion._isDirty = false;\n rotation = this._rotationQuaternion;\n if (this.reIntegrateRotationIntoRotationQuaternion) {\n const len = this.rotation.lengthSquared();\n if (len) {\n this._rotationQuaternion.multiplyInPlace(Quaternion.RotationYawPitchRoll(this._rotation.y, this._rotation.x, this._rotation.z));\n this._rotation.copyFromFloats(0, 0, 0);\n }\n }\n }\n else {\n rotation = TransformNode._TmpRotation;\n Quaternion.RotationYawPitchRollToRef(this._rotation.y, this._rotation.x, this._rotation.z, rotation);\n }\n // Compose\n if (this._usePivotMatrix) {\n const scaleMatrix = TmpVectors.Matrix[1];\n Matrix.ScalingToRef(scaling.x, scaling.y, scaling.z, scaleMatrix);\n // Rotation\n const rotationMatrix = TmpVectors.Matrix[0];\n rotation.toRotationMatrix(rotationMatrix);\n // Composing transformations\n this._pivotMatrix.multiplyToRef(scaleMatrix, TmpVectors.Matrix[4]);\n TmpVectors.Matrix[4].multiplyToRef(rotationMatrix, this._localMatrix);\n // Post multiply inverse of pivotMatrix\n if (this._postMultiplyPivotMatrix) {\n this._localMatrix.multiplyToRef(this._pivotMatrixInverse, this._localMatrix);\n }\n this._localMatrix.addTranslationFromFloats(translation.x, translation.y, translation.z);\n }\n else {\n Matrix.ComposeToRef(scaling, rotation, translation, this._localMatrix);\n }\n // Parent\n if (parent && parent.getWorldMatrix) {\n if (force) {\n parent.computeWorldMatrix(force);\n }\n if (cache.useBillboardPath) {\n if (this._transformToBoneReferal) {\n parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), TmpVectors.Matrix[7]);\n }\n else {\n TmpVectors.Matrix[7].copyFrom(parent.getWorldMatrix());\n }\n // Extract scaling and translation from parent\n const translation = TmpVectors.Vector3[5];\n const scale = TmpVectors.Vector3[6];\n const orientation = TmpVectors.Quaternion[0];\n TmpVectors.Matrix[7].decompose(scale, orientation, translation);\n Matrix.ScalingToRef(scale.x, scale.y, scale.z, TmpVectors.Matrix[7]);\n TmpVectors.Matrix[7].setTranslation(translation);\n if (TransformNode.BillboardUseParentOrientation) {\n // set localMatrix translation to be transformed against parent's orientation.\n this._position.applyRotationQuaternionToRef(orientation, translation);\n this._localMatrix.setTranslation(translation);\n }\n this._localMatrix.multiplyToRef(TmpVectors.Matrix[7], this._worldMatrix);\n }\n else {\n if (this._transformToBoneReferal) {\n this._localMatrix.multiplyToRef(parent.getWorldMatrix(), TmpVectors.Matrix[6]);\n TmpVectors.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);\n }\n else {\n this._localMatrix.multiplyToRef(parent.getWorldMatrix(), this._worldMatrix);\n }\n }\n this._markSyncedWithParent();\n }\n else {\n this._worldMatrix.copyFrom(this._localMatrix);\n }\n // Billboarding based on camera orientation (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)\n if (cache.useBillboardPath && camera && this.billboardMode && !cache.useBillboardPosition) {\n const storedTranslation = TmpVectors.Vector3[0];\n this._worldMatrix.getTranslationToRef(storedTranslation); // Save translation\n // Cancel camera rotation\n TmpVectors.Matrix[1].copyFrom(camera.getViewMatrix());\n if (this._scene.useRightHandedSystem) {\n TmpVectors.Matrix[1].multiplyToRef(convertRHSToLHS, TmpVectors.Matrix[1]);\n }\n TmpVectors.Matrix[1].setTranslationFromFloats(0, 0, 0);\n TmpVectors.Matrix[1].invertToRef(TmpVectors.Matrix[0]);\n if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {\n TmpVectors.Matrix[0].decompose(undefined, TmpVectors.Quaternion[0], undefined);\n const eulerAngles = TmpVectors.Vector3[1];\n TmpVectors.Quaternion[0].toEulerAnglesToRef(eulerAngles);\n if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) !== TransformNode.BILLBOARDMODE_X) {\n eulerAngles.x = 0;\n }\n if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) !== TransformNode.BILLBOARDMODE_Y) {\n eulerAngles.y = 0;\n }\n if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) !== TransformNode.BILLBOARDMODE_Z) {\n eulerAngles.z = 0;\n }\n Matrix.RotationYawPitchRollToRef(eulerAngles.y, eulerAngles.x, eulerAngles.z, TmpVectors.Matrix[0]);\n }\n this._worldMatrix.setTranslationFromFloats(0, 0, 0);\n this._worldMatrix.multiplyToRef(TmpVectors.Matrix[0], this._worldMatrix);\n // Restore translation\n this._worldMatrix.setTranslation(TmpVectors.Vector3[0]);\n }\n // Billboarding based on camera position\n else if (cache.useBillboardPath && camera && cache.useBillboardPosition) {\n const storedTranslation = TmpVectors.Vector3[0];\n // Save translation\n this._worldMatrix.getTranslationToRef(storedTranslation);\n // Compute camera position in local space\n const cameraPosition = camera.globalPosition;\n this._worldMatrix.invertToRef(TmpVectors.Matrix[1]);\n const camInObjSpace = TmpVectors.Vector3[1];\n Vector3.TransformCoordinatesToRef(cameraPosition, TmpVectors.Matrix[1], camInObjSpace);\n camInObjSpace.normalize();\n // Find the lookAt info in local space\n const yaw = -Math.atan2(camInObjSpace.z, camInObjSpace.x) + Math.PI / 2;\n const len = Math.sqrt(camInObjSpace.x * camInObjSpace.x + camInObjSpace.z * camInObjSpace.z);\n const pitch = -Math.atan2(camInObjSpace.y, len);\n Quaternion.RotationYawPitchRollToRef(yaw, pitch, 0, TmpVectors.Quaternion[0]);\n if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {\n const eulerAngles = TmpVectors.Vector3[1];\n TmpVectors.Quaternion[0].toEulerAnglesToRef(eulerAngles);\n if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) !== TransformNode.BILLBOARDMODE_X) {\n eulerAngles.x = 0;\n }\n if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) !== TransformNode.BILLBOARDMODE_Y) {\n eulerAngles.y = 0;\n }\n if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) !== TransformNode.BILLBOARDMODE_Z) {\n eulerAngles.z = 0;\n }\n Matrix.RotationYawPitchRollToRef(eulerAngles.y, eulerAngles.x, eulerAngles.z, TmpVectors.Matrix[0]);\n }\n else {\n Matrix.FromQuaternionToRef(TmpVectors.Quaternion[0], TmpVectors.Matrix[0]);\n }\n // Cancel translation\n this._worldMatrix.setTranslationFromFloats(0, 0, 0);\n // Rotate according to lookat (diff from local to lookat)\n this._worldMatrix.multiplyToRef(TmpVectors.Matrix[0], this._worldMatrix);\n // Restore translation\n this._worldMatrix.setTranslation(TmpVectors.Vector3[0]);\n }\n // Normal matrix\n if (!this.ignoreNonUniformScaling) {\n if (this._scaling.isNonUniformWithinEpsilon(0.000001)) {\n this._updateNonUniformScalingState(true);\n }\n else if (parent && parent._nonUniformScaling) {\n this._updateNonUniformScalingState(parent._nonUniformScaling);\n }\n else {\n this._updateNonUniformScalingState(false);\n }\n }\n else {\n this._updateNonUniformScalingState(false);\n }\n this._afterComputeWorldMatrix();\n // Absolute position\n this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);\n this._isAbsoluteSynced = false;\n // Callbacks\n this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);\n if (!this._poseMatrix) {\n this._poseMatrix = Matrix.Invert(this._worldMatrix);\n }\n // Cache the determinant\n this._worldMatrixDeterminantIsDirty = true;\n return this._worldMatrix;\n }\n /**\n * Resets this nodeTransform's local matrix to Matrix.Identity().\n * @param independentOfChildren indicates if all child nodeTransform's world-space transform should be preserved.\n */\n resetLocalMatrix(independentOfChildren = true) {\n this.computeWorldMatrix();\n if (independentOfChildren) {\n const children = this.getChildren();\n for (let i = 0; i < children.length; ++i) {\n const child = children[i];\n if (child) {\n child.computeWorldMatrix();\n const bakedMatrix = TmpVectors.Matrix[0];\n child._localMatrix.multiplyToRef(this._localMatrix, bakedMatrix);\n const tmpRotationQuaternion = TmpVectors.Quaternion[0];\n bakedMatrix.decompose(child.scaling, tmpRotationQuaternion, child.position);\n if (child.rotationQuaternion) {\n child.rotationQuaternion.copyFrom(tmpRotationQuaternion);\n }\n else {\n tmpRotationQuaternion.toEulerAnglesToRef(child.rotation);\n }\n }\n }\n }\n this.scaling.copyFromFloats(1, 1, 1);\n this.position.copyFromFloats(0, 0, 0);\n this.rotation.copyFromFloats(0, 0, 0);\n //only if quaternion is already set\n if (this.rotationQuaternion) {\n this.rotationQuaternion = Quaternion.Identity();\n }\n this._worldMatrix = Matrix.Identity();\n }\n _afterComputeWorldMatrix() { }\n /**\n * If you'd like to be called back after the mesh position, rotation or scaling has been updated.\n * @param func callback function to add\n *\n * @returns the TransformNode.\n */\n registerAfterWorldMatrixUpdate(func) {\n this.onAfterWorldMatrixUpdateObservable.add(func);\n return this;\n }\n /**\n * Removes a registered callback function.\n * @param func callback function to remove\n * @returns the TransformNode.\n */\n unregisterAfterWorldMatrixUpdate(func) {\n this.onAfterWorldMatrixUpdateObservable.removeCallback(func);\n return this;\n }\n /**\n * Gets the position of the current mesh in camera space\n * @param camera defines the camera to use\n * @returns a position\n */\n getPositionInCameraSpace(camera = null) {\n if (!camera) {\n camera = this.getScene().activeCamera;\n }\n return Vector3.TransformCoordinates(this.getAbsolutePosition(), camera.getViewMatrix());\n }\n /**\n * Returns the distance from the mesh to the active camera\n * @param camera defines the camera to use\n * @returns the distance\n */\n getDistanceToCamera(camera = null) {\n if (!camera) {\n camera = this.getScene().activeCamera;\n }\n return this.getAbsolutePosition().subtract(camera.globalPosition).length();\n }\n /**\n * Clone the current transform node\n * @param name Name of the new clone\n * @param newParent New parent for the clone\n * @param doNotCloneChildren Do not clone children hierarchy\n * @returns the new transform node\n */\n clone(name, newParent, doNotCloneChildren) {\n const result = SerializationHelper.Clone(() => new TransformNode(name, this.getScene()), this);\n result.name = name;\n result.id = name;\n if (newParent) {\n result.parent = newParent;\n }\n if (!doNotCloneChildren) {\n // Children\n const directDescendants = this.getDescendants(true);\n for (let index = 0; index < directDescendants.length; index++) {\n const child = directDescendants[index];\n if (child.clone) {\n child.clone(name + \".\" + child.name, result);\n }\n }\n }\n return result;\n }\n /**\n * Serializes the objects information.\n * @param currentSerializationObject defines the object to serialize in\n * @returns the serialized object\n */\n serialize(currentSerializationObject) {\n const serializationObject = SerializationHelper.Serialize(this, currentSerializationObject);\n serializationObject.type = this.getClassName();\n serializationObject.uniqueId = this.uniqueId;\n // Parent\n if (this.parent) {\n this.parent._serializeAsParent(serializationObject);\n }\n serializationObject.localMatrix = this.getPivotMatrix().asArray();\n serializationObject.isEnabled = this.isEnabled();\n return serializationObject;\n }\n // Statics\n /**\n * Returns a new TransformNode object parsed from the source provided.\n * @param parsedTransformNode is the source.\n * @param scene the scene the object belongs to\n * @param rootUrl is a string, it's the root URL to prefix the `delayLoadingFile` property with\n * @returns a new TransformNode object parsed from the source provided.\n */\n static Parse(parsedTransformNode, scene, rootUrl) {\n const transformNode = SerializationHelper.Parse(() => new TransformNode(parsedTransformNode.name, scene), parsedTransformNode, scene, rootUrl);\n if (parsedTransformNode.localMatrix) {\n transformNode.setPreTransformMatrix(Matrix.FromArray(parsedTransformNode.localMatrix));\n }\n else if (parsedTransformNode.pivotMatrix) {\n transformNode.setPivotMatrix(Matrix.FromArray(parsedTransformNode.pivotMatrix));\n }\n transformNode.setEnabled(parsedTransformNode.isEnabled);\n transformNode._waitingParsedUniqueId = parsedTransformNode.uniqueId;\n // Parent\n if (parsedTransformNode.parentId !== undefined) {\n transformNode._waitingParentId = parsedTransformNode.parentId;\n }\n if (parsedTransformNode.parentInstanceIndex !== undefined) {\n transformNode._waitingParentInstanceIndex = parsedTransformNode.parentInstanceIndex;\n }\n return transformNode;\n }\n /**\n * Get all child-transformNodes of this node\n * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered\n * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored\n * @returns an array of TransformNode\n */\n getChildTransformNodes(directDescendantsOnly, predicate) {\n const results = [];\n this._getDescendants(results, directDescendantsOnly, (node) => {\n return (!predicate || predicate(node)) && node instanceof TransformNode;\n });\n return results;\n }\n /**\n * Releases resources associated with this transform node.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n dispose(doNotRecurse, disposeMaterialAndTextures = false) {\n // Animations\n this.getScene().stopAnimation(this);\n // Remove from scene\n this.getScene().removeTransformNode(this);\n if (this._parentContainer) {\n const index = this._parentContainer.transformNodes.indexOf(this);\n if (index > -1) {\n this._parentContainer.transformNodes.splice(index, 1);\n }\n this._parentContainer = null;\n }\n this.onAfterWorldMatrixUpdateObservable.clear();\n if (doNotRecurse) {\n const transformNodes = this.getChildTransformNodes(true);\n for (const transformNode of transformNodes) {\n transformNode.parent = null;\n transformNode.computeWorldMatrix(true);\n }\n }\n super.dispose(doNotRecurse, disposeMaterialAndTextures);\n }\n /**\n * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)\n * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box. Default is false\n * @param ignoreRotation ignore rotation when computing the scale (ie. object will be axis aligned). Default is false\n * @param predicate predicate that is passed in to getHierarchyBoundingVectors when selecting which object should be included when scaling\n * @returns the current mesh\n */\n normalizeToUnitCube(includeDescendants = true, ignoreRotation = false, predicate) {\n let storedRotation = null;\n let storedRotationQuaternion = null;\n if (ignoreRotation) {\n if (this.rotationQuaternion) {\n storedRotationQuaternion = this.rotationQuaternion.clone();\n this.rotationQuaternion.copyFromFloats(0, 0, 0, 1);\n }\n else if (this.rotation) {\n storedRotation = this.rotation.clone();\n this.rotation.copyFromFloats(0, 0, 0);\n }\n }\n const boundingVectors = this.getHierarchyBoundingVectors(includeDescendants, predicate);\n const sizeVec = boundingVectors.max.subtract(boundingVectors.min);\n const maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);\n if (maxDimension === 0) {\n return this;\n }\n const scale = 1 / maxDimension;\n this.scaling.scaleInPlace(scale);\n if (ignoreRotation) {\n if (this.rotationQuaternion && storedRotationQuaternion) {\n this.rotationQuaternion.copyFrom(storedRotationQuaternion);\n }\n else if (this.rotation && storedRotation) {\n this.rotation.copyFrom(storedRotation);\n }\n }\n return this;\n }\n _syncAbsoluteScalingAndRotation() {\n if (!this._isAbsoluteSynced) {\n this._worldMatrix.decompose(this._absoluteScaling, this._absoluteRotationQuaternion);\n this._isAbsoluteSynced = true;\n }\n }\n}\n// Statics\n/**\n * Object will not rotate to face the camera\n */\nTransformNode.BILLBOARDMODE_NONE = 0;\n/**\n * Object will rotate to face the camera but only on the x axis\n */\nTransformNode.BILLBOARDMODE_X = 1;\n/**\n * Object will rotate to face the camera but only on the y axis\n */\nTransformNode.BILLBOARDMODE_Y = 2;\n/**\n * Object will rotate to face the camera but only on the z axis\n */\nTransformNode.BILLBOARDMODE_Z = 4;\n/**\n * Object will rotate to face the camera\n */\nTransformNode.BILLBOARDMODE_ALL = 7;\n/**\n * Object will rotate to face the camera's position instead of orientation\n */\nTransformNode.BILLBOARDMODE_USE_POSITION = 128;\n/**\n * Child transform with Billboard flags should or should not apply parent rotation (default if off)\n */\nTransformNode.BillboardUseParentOrientation = false;\nTransformNode._TmpRotation = Quaternion.Zero();\nTransformNode._TmpScaling = Vector3.Zero();\nTransformNode._TmpTranslation = Vector3.Zero();\nTransformNode._LookAtVectorCache = new Vector3(0, 0, 0);\nTransformNode._RotationAxisCache = new Quaternion();\n__decorate([\n serializeAsVector3(\"position\")\n], TransformNode.prototype, \"_position\", void 0);\n__decorate([\n serializeAsVector3(\"rotation\")\n], TransformNode.prototype, \"_rotation\", void 0);\n__decorate([\n serializeAsQuaternion(\"rotationQuaternion\")\n], TransformNode.prototype, \"_rotationQuaternion\", void 0);\n__decorate([\n serializeAsVector3(\"scaling\")\n], TransformNode.prototype, \"_scaling\", void 0);\n__decorate([\n serialize(\"billboardMode\")\n], TransformNode.prototype, \"_billboardMode\", void 0);\n__decorate([\n serialize()\n], TransformNode.prototype, \"scalingDeterminant\", void 0);\n__decorate([\n serialize(\"infiniteDistance\")\n], TransformNode.prototype, \"_infiniteDistance\", void 0);\n__decorate([\n serialize()\n], TransformNode.prototype, \"ignoreNonUniformScaling\", void 0);\n__decorate([\n serialize()\n], TransformNode.prototype, \"reIntegrateRotationIntoRotationQuaternion\", void 0);\n//# sourceMappingURL=transformNode.js.map","/**\n * Class used to evaluate queries containing `and` and `or` operators\n */\nexport class AndOrNotEvaluator {\n /**\n * Evaluate a query\n * @param query defines the query to evaluate\n * @param evaluateCallback defines the callback used to filter result\n * @returns true if the query matches\n */\n static Eval(query, evaluateCallback) {\n if (!query.match(/\\([^()]*\\)/g)) {\n query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);\n }\n else {\n query = query.replace(/\\([^()]*\\)/g, (r) => {\n // remove parenthesis\n r = r.slice(1, r.length - 1);\n return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);\n });\n }\n if (query === \"true\") {\n return true;\n }\n if (query === \"false\") {\n return false;\n }\n return AndOrNotEvaluator.Eval(query, evaluateCallback);\n }\n static _HandleParenthesisContent(parenthesisContent, evaluateCallback) {\n evaluateCallback =\n evaluateCallback ||\n ((r) => {\n return r === \"true\" ? true : false;\n });\n let result;\n const or = parenthesisContent.split(\"||\");\n for (const i in or) {\n if (Object.prototype.hasOwnProperty.call(or, i)) {\n let ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());\n const and = ori.split(\"&&\");\n if (and.length > 1) {\n for (let j = 0; j < and.length; ++j) {\n const andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());\n if (andj !== \"true\" && andj !== \"false\") {\n if (andj[0] === \"!\") {\n result = !evaluateCallback(andj.substring(1));\n }\n else {\n result = evaluateCallback(andj);\n }\n }\n else {\n result = andj === \"true\" ? true : false;\n }\n if (!result) {\n // no need to continue since 'false && ... && ...' will always return false\n ori = \"false\";\n break;\n }\n }\n }\n if (result || ori === \"true\") {\n // no need to continue since 'true || ... || ...' will always return true\n result = true;\n break;\n }\n // result equals false (or undefined)\n if (ori !== \"true\" && ori !== \"false\") {\n if (ori[0] === \"!\") {\n result = !evaluateCallback(ori.substring(1));\n }\n else {\n result = evaluateCallback(ori);\n }\n }\n else {\n result = ori === \"true\" ? true : false;\n }\n }\n }\n // the whole parenthesis scope is replaced by 'true' or 'false'\n return result ? \"true\" : \"false\";\n }\n static _SimplifyNegation(booleanString) {\n booleanString = booleanString.replace(/^[\\s!]+/, (r) => {\n // remove whitespaces\n r = r.replace(/[\\s]/g, () => \"\");\n return r.length % 2 ? \"!\" : \"\";\n });\n booleanString = booleanString.trim();\n if (booleanString === \"!true\") {\n booleanString = \"false\";\n }\n else if (booleanString === \"!false\") {\n booleanString = \"true\";\n }\n return booleanString;\n }\n}\n//# sourceMappingURL=andOrNotEvaluator.js.map","/* eslint-disable @typescript-eslint/naming-convention */\n/**\n * Class containing a set of static utilities functions for arrays.\n */\nexport class ArrayTools {\n /**\n * Returns an array of the given size filled with elements built from the given constructor and the parameters.\n * @param size the number of element to construct and put in the array.\n * @param itemBuilder a callback responsible for creating new instance of item. Called once per array entry.\n * @returns a new array filled with new objects.\n */\n static BuildArray(size, itemBuilder) {\n const a = [];\n for (let i = 0; i < size; ++i) {\n a.push(itemBuilder());\n }\n return a;\n }\n /**\n * Returns a tuple of the given size filled with elements built from the given constructor and the parameters.\n * @param size he number of element to construct and put in the tuple.\n * @param itemBuilder a callback responsible for creating new instance of item. Called once per tuple entry.\n * @returns a new tuple filled with new objects.\n */\n static BuildTuple(size, itemBuilder) {\n return ArrayTools.BuildArray(size, itemBuilder);\n }\n}\n/**\n * Observes a function and calls the given callback when it is called.\n * @param object Defines the object the function to observe belongs to.\n * @param functionName Defines the name of the function to observe.\n * @param callback Defines the callback to call when the function is called.\n * @returns A function to call to stop observing\n */\nfunction _observeArrayfunction(object, functionName, callback) {\n // Finds the function to observe\n const oldFunction = object[functionName];\n if (typeof oldFunction !== \"function\") {\n return null;\n }\n // Creates a new function that calls the callback and the old function\n const newFunction = function () {\n const previousLength = object.length;\n const returnValue = newFunction.previous.apply(object, arguments);\n callback(functionName, previousLength);\n return returnValue;\n };\n // Doublishly links the new function and the old function\n oldFunction.next = newFunction;\n newFunction.previous = oldFunction;\n // Replaces the old function with the new function\n object[functionName] = newFunction;\n // Returns a function to disable the hook\n return () => {\n // Only unhook if the function is still hooked\n const previous = newFunction.previous;\n if (!previous) {\n return;\n }\n // Finds the ref to the next function in the chain\n const next = newFunction.next;\n // If in the middle of the chain, link the previous and next functions\n if (next) {\n previous.next = next;\n next.previous = previous;\n }\n // If at the end of the chain, remove the reference to the previous function\n // and restore the previous function\n else {\n previous.next = undefined;\n object[functionName] = previous;\n }\n // Lose reference to the previous and next functions\n newFunction.next = undefined;\n newFunction.previous = undefined;\n };\n}\n/**\n * Defines the list of functions to proxy when observing an array.\n * The scope is currently reduced to the common functions used in the render target render list and the scene cameras.\n */\nconst observedArrayFunctions = [\"push\", \"splice\", \"pop\", \"shift\", \"unshift\"];\n/**\n * Observes an array and notifies the given observer when the array is modified.\n * @param array Defines the array to observe\n * @param callback Defines the function to call when the array is modified (in the limit of the observed array functions)\n * @returns A function to call to stop observing the array\n * @internal\n */\nexport function _ObserveArray(array, callback) {\n // Observes all the required array functions and stores the unhook functions\n const unObserveFunctions = observedArrayFunctions.map((name) => {\n return _observeArrayfunction(array, name, callback);\n });\n // Returns a function that unhook all the observed functions\n return () => {\n unObserveFunctions.forEach((unObserveFunction) => {\n unObserveFunction === null || unObserveFunction === void 0 ? void 0 : unObserveFunction();\n });\n };\n}\n//# sourceMappingURL=arrayTools.js.map","/* eslint-disable @typescript-eslint/naming-convention */\n// \"Coroutines are computer program components that generalize subroutines for non-preemptive multitasking, by allowing execution to be suspended and resumed.\"\n// https://en.wikipedia.org/wiki/Coroutine\n// The inline scheduler simply steps the coroutine synchronously. This is useful for running a coroutine synchronously, and also as a helper function for other schedulers.\n/**\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function inlineScheduler(coroutine, onStep, onError) {\n try {\n const step = coroutine.next();\n if (step.done) {\n onStep(step);\n }\n else if (!step.value) {\n // NOTE: The properties of step have been narrowed, but the type of step itself is not narrowed, so the cast below is the most type safe way to deal with this without instantiating a new object to hold the values.\n onStep(step);\n }\n else {\n step.value.then(() => {\n step.value = undefined;\n onStep(step);\n }, onError);\n }\n }\n catch (error) {\n onError(error);\n }\n}\n// The yielding scheduler steps the coroutine synchronously until the specified time interval has elapsed, then yields control so other operations can be performed.\n// A single instance of a yielding scheduler could be shared across multiple coroutines to yield when their collective work exceeds the threshold.\n/**\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function createYieldingScheduler(yieldAfterMS = 25) {\n let startTime;\n return (coroutine, onStep, onError) => {\n const currentTime = performance.now();\n if (startTime === undefined || currentTime - startTime > yieldAfterMS) {\n // If this is the first coroutine step, or if the time interval has elapsed, record a new start time, and schedule the coroutine step to happen later, effectively yielding control of the execution context.\n startTime = currentTime;\n setTimeout(() => {\n inlineScheduler(coroutine, onStep, onError);\n }, 0);\n }\n else {\n // Otherwise it is not time to yield yet, so step the coroutine synchronously.\n inlineScheduler(coroutine, onStep, onError);\n }\n };\n}\n// Runs the specified coroutine with the specified scheduler. The success or error callback will be invoked when the coroutine finishes.\n/**\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function runCoroutine(coroutine, scheduler, onSuccess, onError, abortSignal) {\n const resume = () => {\n let reschedule;\n const onStep = (stepResult) => {\n if (stepResult.done) {\n // If the coroutine is done, report success.\n onSuccess(stepResult.value);\n }\n else {\n // If the coroutine is not done, resume the coroutine (via the scheduler).\n if (reschedule === undefined) {\n // If reschedule is undefined at this point, then the coroutine must have stepped synchronously, so just flag another loop iteration.\n reschedule = true;\n }\n else {\n // If reschedule is defined at this point, then the coroutine must have stepped asynchronously, so call resume to restart the step loop.\n resume();\n }\n }\n };\n do {\n reschedule = undefined;\n if (!abortSignal || !abortSignal.aborted) {\n scheduler(coroutine, onStep, onError);\n }\n else {\n onError(new Error(\"Aborted\"));\n }\n if (reschedule === undefined) {\n // If reschedule is undefined at this point, then the coroutine must have stepped asynchronously, so stop looping and let the coroutine be resumed later.\n reschedule = false;\n }\n } while (reschedule);\n };\n resume();\n}\n// Runs the specified coroutine synchronously.\n/**\n * @internal\n */\nexport function runCoroutineSync(coroutine, abortSignal) {\n // Run the coroutine with the inline scheduler, storing the returned value, or re-throwing the error (since the error callback will be called synchronously by the inline scheduler).\n let result;\n runCoroutine(coroutine, inlineScheduler, (r) => (result = r), (e) => {\n throw e;\n }, abortSignal);\n // Synchronously return the result of the coroutine.\n return result;\n}\n// Runs the specified coroutine asynchronously with the specified scheduler.\n/**\n * @internal\n */\nexport function runCoroutineAsync(coroutine, scheduler, abortSignal) {\n // Run the coroutine with a yielding scheduler, resolving or rejecting the result promise when the coroutine finishes.\n return new Promise((resolve, reject) => {\n runCoroutine(coroutine, scheduler, resolve, reject, abortSignal);\n });\n}\n/**\n * Given a function that returns a Coroutine, produce a function with the same parameters that returns a T.\n * The returned function runs the coroutine synchronously.\n * @param coroutineFactory A function that returns a Coroutine.\n * @param abortSignal\n * @returns A function that runs the coroutine synchronously.\n * @internal\n */\nexport function makeSyncFunction(coroutineFactory, abortSignal) {\n return (...params) => {\n // Run the coroutine synchronously.\n return runCoroutineSync(coroutineFactory(...params), abortSignal);\n };\n}\n/**\n * Given a function that returns a Coroutine, product a function with the same parameters that returns a Promise.\n * The returned function runs the coroutine asynchronously, yield control of the execution context occasionally to enable a more responsive experience.\n * @param coroutineFactory A function that returns a Coroutine.\n * @param scheduler\n * @param abortSignal\n * @returns A function that runs the coroutine asynchronously.\n * @internal\n */\nexport function makeAsyncFunction(coroutineFactory, scheduler, abortSignal) {\n return (...params) => {\n // Run the coroutine asynchronously.\n return runCoroutineAsync(coroutineFactory(...params), scheduler, abortSignal);\n };\n}\n//# sourceMappingURL=coroutine.js.map","/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable @typescript-eslint/naming-convention */\nimport { Tags } from \"../Misc/tags.js\";\nimport { Quaternion, Vector2, Vector3, Matrix } from \"../Maths/math.vector.js\";\nimport { _WarnImport } from \"./devTools.js\";\nimport { Color4, Color3 } from \"../Maths/math.color.js\";\nconst __decoratorInitialStore = {};\nconst __mergedStore = {};\nconst _copySource = function (creationFunction, source, instanciate, options = {}) {\n const destination = creationFunction();\n // Tags\n if (Tags && Tags.HasTags(source)) {\n Tags.AddTagsTo(destination, Tags.GetTags(source, true));\n }\n const classStore = getMergedStore(destination);\n // Map from source texture uniqueId to destination texture\n const textureMap = {};\n // Properties\n for (const property in classStore) {\n const propertyDescriptor = classStore[property];\n const sourceProperty = source[property];\n const propertyType = propertyDescriptor.type;\n if (sourceProperty !== undefined && sourceProperty !== null && (property !== \"uniqueId\" || SerializationHelper.AllowLoadingUniqueId)) {\n switch (propertyType) {\n case 0: // Value\n case 6: // Mesh reference\n case 11: // Camera reference\n destination[property] = sourceProperty;\n break;\n case 1: // Texture\n if (options.cloneTexturesOnlyOnce && textureMap[sourceProperty.uniqueId]) {\n destination[property] = textureMap[sourceProperty.uniqueId];\n }\n else {\n destination[property] = instanciate || sourceProperty.isRenderTarget ? sourceProperty : sourceProperty.clone();\n textureMap[sourceProperty.uniqueId] = destination[property];\n }\n break;\n case 2: // Color3\n case 3: // FresnelParameters\n case 4: // Vector2\n case 5: // Vector3\n case 7: // Color Curves\n case 10: // Quaternion\n case 12: // Matrix\n destination[property] = instanciate ? sourceProperty : sourceProperty.clone();\n break;\n }\n }\n }\n return destination;\n};\nfunction getDirectStore(target) {\n const classKey = target.getClassName();\n if (!__decoratorInitialStore[classKey]) {\n __decoratorInitialStore[classKey] = {};\n }\n return __decoratorInitialStore[classKey];\n}\n/**\n * Return the list of properties flagged as serializable\n * @param target host object\n */\nfunction getMergedStore(target) {\n const classKey = target.getClassName();\n if (__mergedStore[classKey]) {\n return __mergedStore[classKey];\n }\n __mergedStore[classKey] = {};\n const store = __mergedStore[classKey];\n let currentTarget = target;\n let currentKey = classKey;\n while (currentKey) {\n const initialStore = __decoratorInitialStore[currentKey];\n for (const property in initialStore) {\n store[property] = initialStore[property];\n }\n let parent;\n let done = false;\n do {\n parent = Object.getPrototypeOf(currentTarget);\n if (!parent.getClassName) {\n done = true;\n break;\n }\n if (parent.getClassName() !== currentKey) {\n break;\n }\n currentTarget = parent;\n } while (parent);\n if (done) {\n break;\n }\n currentKey = parent.getClassName();\n currentTarget = parent;\n }\n return store;\n}\nfunction generateSerializableMember(type, sourceName) {\n return (target, propertyKey) => {\n const classStore = getDirectStore(target);\n if (!classStore[propertyKey]) {\n classStore[propertyKey] = { type: type, sourceName: sourceName };\n }\n };\n}\nfunction generateExpandMember(setCallback, targetKey = null) {\n return (target, propertyKey) => {\n const key = targetKey || \"_\" + propertyKey;\n Object.defineProperty(target, propertyKey, {\n get: function () {\n return this[key];\n },\n set: function (value) {\n // does this object (i.e. vector3) has an equals function? use it!\n // Note - not using \"with epsilon\" here, it is expected te behave like the internal cache does.\n if (typeof this.equals === \"function\") {\n if (this.equals(value)) {\n return;\n }\n }\n if (this[key] === value) {\n return;\n }\n this[key] = value;\n target[setCallback].apply(this);\n },\n enumerable: true,\n configurable: true,\n });\n };\n}\nexport function expandToProperty(callback, targetKey = null) {\n return generateExpandMember(callback, targetKey);\n}\nexport function serialize(sourceName) {\n return generateSerializableMember(0, sourceName); // value member\n}\nexport function serializeAsTexture(sourceName) {\n return generateSerializableMember(1, sourceName); // texture member\n}\nexport function serializeAsColor3(sourceName) {\n return generateSerializableMember(2, sourceName); // color3 member\n}\nexport function serializeAsFresnelParameters(sourceName) {\n return generateSerializableMember(3, sourceName); // fresnel parameters member\n}\nexport function serializeAsVector2(sourceName) {\n return generateSerializableMember(4, sourceName); // vector2 member\n}\nexport function serializeAsVector3(sourceName) {\n return generateSerializableMember(5, sourceName); // vector3 member\n}\nexport function serializeAsMeshReference(sourceName) {\n return generateSerializableMember(6, sourceName); // mesh reference member\n}\nexport function serializeAsColorCurves(sourceName) {\n return generateSerializableMember(7, sourceName); // color curves\n}\nexport function serializeAsColor4(sourceName) {\n return generateSerializableMember(8, sourceName); // color 4\n}\nexport function serializeAsImageProcessingConfiguration(sourceName) {\n return generateSerializableMember(9, sourceName); // image processing\n}\nexport function serializeAsQuaternion(sourceName) {\n return generateSerializableMember(10, sourceName); // quaternion member\n}\nexport function serializeAsMatrix(sourceName) {\n return generateSerializableMember(12, sourceName); // matrix member\n}\n/**\n * Decorator used to define property that can be serialized as reference to a camera\n * @param sourceName defines the name of the property to decorate\n */\nexport function serializeAsCameraReference(sourceName) {\n return generateSerializableMember(11, sourceName); // camera reference member\n}\n/**\n * Class used to help serialization objects\n */\nexport class SerializationHelper {\n /**\n * Appends the serialized animations from the source animations\n * @param source Source containing the animations\n * @param destination Target to store the animations\n */\n static AppendSerializedAnimations(source, destination) {\n if (source.animations) {\n destination.animations = [];\n for (let animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {\n const animation = source.animations[animationIndex];\n destination.animations.push(animation.serialize());\n }\n }\n }\n /**\n * Static function used to serialized a specific entity\n * @param entity defines the entity to serialize\n * @param serializationObject defines the optional target object where serialization data will be stored\n * @returns a JSON compatible object representing the serialization of the entity\n */\n static Serialize(entity, serializationObject) {\n if (!serializationObject) {\n serializationObject = {};\n }\n // Tags\n if (Tags) {\n serializationObject.tags = Tags.GetTags(entity);\n }\n const serializedProperties = getMergedStore(entity);\n // Properties\n for (const property in serializedProperties) {\n const propertyDescriptor = serializedProperties[property];\n const targetPropertyName = propertyDescriptor.sourceName || property;\n const propertyType = propertyDescriptor.type;\n const sourceProperty = entity[property];\n if (sourceProperty !== undefined && sourceProperty !== null && (property !== \"uniqueId\" || SerializationHelper.AllowLoadingUniqueId)) {\n switch (propertyType) {\n case 0: // Value\n serializationObject[targetPropertyName] = sourceProperty;\n break;\n case 1: // Texture\n serializationObject[targetPropertyName] = sourceProperty.serialize();\n break;\n case 2: // Color3\n serializationObject[targetPropertyName] = sourceProperty.asArray();\n break;\n case 3: // FresnelParameters\n serializationObject[targetPropertyName] = sourceProperty.serialize();\n break;\n case 4: // Vector2\n serializationObject[targetPropertyName] = sourceProperty.asArray();\n break;\n case 5: // Vector3\n serializationObject[targetPropertyName] = sourceProperty.asArray();\n break;\n case 6: // Mesh reference\n serializationObject[targetPropertyName] = sourceProperty.id;\n break;\n case 7: // Color Curves\n serializationObject[targetPropertyName] = sourceProperty.serialize();\n break;\n case 8: // Color 4\n serializationObject[targetPropertyName] = sourceProperty.asArray();\n break;\n case 9: // Image Processing\n serializationObject[targetPropertyName] = sourceProperty.serialize();\n break;\n case 10: // Quaternion\n serializationObject[targetPropertyName] = sourceProperty.asArray();\n break;\n case 11: // Camera reference\n serializationObject[targetPropertyName] = sourceProperty.id;\n break;\n case 12: // Matrix\n serializationObject[targetPropertyName] = sourceProperty.asArray();\n break;\n }\n }\n }\n return serializationObject;\n }\n /**\n * Given a source json and a destination object in a scene, this function will parse the source and will try to apply its content to the destination object\n * @param source the source json data\n * @param destination the destination object\n * @param scene the scene where the object is\n * @param rootUrl root url to use to load assets\n */\n static ParseProperties(source, destination, scene, rootUrl) {\n if (!rootUrl) {\n rootUrl = \"\";\n }\n const classStore = getMergedStore(destination);\n // Properties\n for (const property in classStore) {\n const propertyDescriptor = classStore[property];\n const sourceProperty = source[propertyDescriptor.sourceName || property];\n const propertyType = propertyDescriptor.type;\n if (sourceProperty !== undefined && sourceProperty !== null && (property !== \"uniqueId\" || SerializationHelper.AllowLoadingUniqueId)) {\n const dest = destination;\n switch (propertyType) {\n case 0: // Value\n dest[property] = sourceProperty;\n break;\n case 1: // Texture\n if (scene) {\n dest[property] = SerializationHelper._TextureParser(sourceProperty, scene, rootUrl);\n }\n break;\n case 2: // Color3\n dest[property] = Color3.FromArray(sourceProperty);\n break;\n case 3: // FresnelParameters\n dest[property] = SerializationHelper._FresnelParametersParser(sourceProperty);\n break;\n case 4: // Vector2\n dest[property] = Vector2.FromArray(sourceProperty);\n break;\n case 5: // Vector3\n dest[property] = Vector3.FromArray(sourceProperty);\n break;\n case 6: // Mesh reference\n if (scene) {\n dest[property] = scene.getLastMeshById(sourceProperty);\n }\n break;\n case 7: // Color Curves\n dest[property] = SerializationHelper._ColorCurvesParser(sourceProperty);\n break;\n case 8: // Color 4\n dest[property] = Color4.FromArray(sourceProperty);\n break;\n case 9: // Image Processing\n dest[property] = SerializationHelper._ImageProcessingConfigurationParser(sourceProperty);\n break;\n case 10: // Quaternion\n dest[property] = Quaternion.FromArray(sourceProperty);\n break;\n case 11: // Camera reference\n if (scene) {\n dest[property] = scene.getCameraById(sourceProperty);\n }\n break;\n case 12: // Matrix\n dest[property] = Matrix.FromArray(sourceProperty);\n break;\n }\n }\n }\n }\n /**\n * Creates a new entity from a serialization data object\n * @param creationFunction defines a function used to instanciated the new entity\n * @param source defines the source serialization data\n * @param scene defines the hosting scene\n * @param rootUrl defines the root url for resources\n * @returns a new entity\n */\n static Parse(creationFunction, source, scene, rootUrl = null) {\n const destination = creationFunction();\n // Tags\n if (Tags) {\n Tags.AddTagsTo(destination, source.tags);\n }\n SerializationHelper.ParseProperties(source, destination, scene, rootUrl);\n return destination;\n }\n /**\n * Clones an object\n * @param creationFunction defines the function used to instanciate the new object\n * @param source defines the source object\n * @returns the cloned object\n */\n static Clone(creationFunction, source, options = {}) {\n return _copySource(creationFunction, source, false, options);\n }\n /**\n * Instanciates a new object based on a source one (some data will be shared between both object)\n * @param creationFunction defines the function used to instanciate the new object\n * @param source defines the source object\n * @returns the new object\n */\n static Instanciate(creationFunction, source) {\n return _copySource(creationFunction, source, true);\n }\n}\n/**\n * Gets or sets a boolean to indicate if the UniqueId property should be serialized\n */\nSerializationHelper.AllowLoadingUniqueId = false;\n/**\n * @internal\n */\nSerializationHelper._ImageProcessingConfigurationParser = (sourceProperty) => {\n throw _WarnImport(\"ImageProcessingConfiguration\");\n};\n/**\n * @internal\n */\nSerializationHelper._FresnelParametersParser = (sourceProperty) => {\n throw _WarnImport(\"FresnelParameters\");\n};\n/**\n * @internal\n */\nSerializationHelper._ColorCurvesParser = (sourceProperty) => {\n throw _WarnImport(\"ColorCurves\");\n};\n/**\n * @internal\n */\nSerializationHelper._TextureParser = (sourceProperty, scene, rootUrl) => {\n throw _WarnImport(\"Texture\");\n};\n/**\n * Decorator used to redirect a function to a native implementation if available.\n * @internal\n */\nexport function nativeOverride(target, propertyKey, descriptor, predicate) {\n // Cache the original JS function for later.\n const jsFunc = descriptor.value;\n // Override the JS function to check for a native override on first invocation. Setting descriptor.value overrides the function at the early stage of code being loaded/imported.\n descriptor.value = (...params) => {\n // Assume the resolved function will be the original JS function, then we will check for the Babylon Native context.\n let func = jsFunc;\n // Check if we are executing in a Babylon Native context (e.g. check the presence of the _native global property) and if so also check if a function override is available.\n if (typeof _native !== \"undefined\" && _native[propertyKey]) {\n const nativeFunc = _native[propertyKey];\n // If a predicate was provided, then we'll need to invoke the predicate on each invocation of the underlying function to determine whether to call the native function or the JS function.\n if (predicate) {\n // The resolved function will execute the predicate and then either execute the native function or the JS function.\n func = (...params) => (predicate(...params) ? nativeFunc(...params) : jsFunc(...params));\n }\n else {\n // The resolved function will directly execute the native function.\n func = nativeFunc;\n }\n }\n // Override the JS function again with the final resolved target function.\n target[propertyKey] = func;\n // The JS function has now been overridden based on whether we're executing in the context of Babylon Native, but we still need to invoke that function.\n // Future invocations of the function will just directly invoke the final overridden function, not any of the decorator setup logic above.\n return func(...params);\n };\n}\n/**\n * Decorator factory that applies the nativeOverride decorator, but determines whether to redirect to the native implementation based on a filter function that evaluates the function arguments.\n * @param predicate\n * @example @nativeOverride.filter((...[arg1]: Parameters) => arg1.length > 20)\n * public someMethod(arg1: string, arg2: number): string {\n * @internal\n */\nnativeOverride.filter = function (predicate) {\n return (target, propertyKey, descriptor) => nativeOverride(target, propertyKey, descriptor, predicate);\n};\n//# sourceMappingURL=decorators.js.map","import { Logger } from \"./logger.js\";\nconst CloneValue = (source, destinationObject) => {\n if (!source) {\n return null;\n }\n if (source.getClassName && source.getClassName() === \"Mesh\") {\n return null;\n }\n if (source.getClassName && (source.getClassName() === \"SubMesh\" || source.getClassName() === \"PhysicsBody\")) {\n return source.clone(destinationObject);\n }\n else if (source.clone) {\n return source.clone();\n }\n else if (Array.isArray(source)) {\n return source.slice();\n }\n return null;\n};\nfunction GetAllPropertyNames(obj) {\n const props = [];\n do {\n Object.getOwnPropertyNames(obj).forEach(function (prop) {\n if (props.indexOf(prop) === -1) {\n props.push(prop);\n }\n });\n } while ((obj = Object.getPrototypeOf(obj)));\n return props;\n}\n/**\n * Class containing a set of static utilities functions for deep copy.\n */\nexport class DeepCopier {\n /**\n * Tries to copy an object by duplicating every property\n * @param source defines the source object\n * @param destination defines the target object\n * @param doNotCopyList defines a list of properties to avoid\n * @param mustCopyList defines a list of properties to copy (even if they start with _)\n */\n static DeepCopy(source, destination, doNotCopyList, mustCopyList) {\n const properties = GetAllPropertyNames(source);\n for (const prop of properties) {\n if (prop[0] === \"_\" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {\n continue;\n }\n if (prop.endsWith(\"Observable\")) {\n continue;\n }\n if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {\n continue;\n }\n const sourceValue = source[prop];\n const typeOfSourceValue = typeof sourceValue;\n if (typeOfSourceValue === \"function\") {\n continue;\n }\n try {\n if (typeOfSourceValue === \"object\") {\n if (sourceValue instanceof Uint8Array) {\n destination[prop] = Uint8Array.from(sourceValue);\n }\n else if (sourceValue instanceof Array) {\n destination[prop] = [];\n if (sourceValue.length > 0) {\n if (typeof sourceValue[0] == \"object\") {\n for (let index = 0; index < sourceValue.length; index++) {\n const clonedValue = CloneValue(sourceValue[index], destination);\n if (destination[prop].indexOf(clonedValue) === -1) {\n // Test if auto inject was not done\n destination[prop].push(clonedValue);\n }\n }\n }\n else {\n destination[prop] = sourceValue.slice(0);\n }\n }\n }\n else {\n destination[prop] = CloneValue(sourceValue, destination);\n }\n }\n else {\n destination[prop] = sourceValue;\n }\n }\n catch (e) {\n // Log a warning (it could be because of a read-only property)\n Logger.Warn(e.message);\n }\n }\n }\n}\n//# sourceMappingURL=deepCopier.js.map","/**\n * @internal\n */\nexport function _WarnImport(name) {\n return `${name} needs to be imported before as it contains a side-effect required by your code.`;\n}\n//# sourceMappingURL=devTools.js.map","/* eslint-disable @typescript-eslint/naming-convention */\n/**\n * Checks if the window object exists\n * @returns true if the window object exists\n */\nexport function IsWindowObjectExist() {\n return typeof window !== \"undefined\";\n}\n/**\n * Checks if the navigator object exists\n * @returns true if the navigator object exists\n */\nexport function IsNavigatorAvailable() {\n return typeof navigator !== \"undefined\";\n}\n/**\n * Check if the document object exists\n * @returns true if the document object exists\n */\nexport function IsDocumentAvailable() {\n return typeof document !== \"undefined\";\n}\n/**\n * Extracts text content from a DOM element hierarchy\n * @param element defines the root element\n * @returns a string\n */\nexport function GetDOMTextContent(element) {\n let result = \"\";\n let child = element.firstChild;\n while (child) {\n if (child.nodeType === 3) {\n result += child.textContent;\n }\n child = child.nextSibling;\n }\n return result;\n}\n/**\n * Sets of helpers dealing with the DOM and some of the recurrent functions needed in\n * Babylon.js\n */\nexport const DomManagement = {\n /**\n * Checks if the window object exists\n * @returns true if the window object exists\n */\n IsWindowObjectExist,\n /**\n * Checks if the navigator object exists\n * @returns true if the navigator object exists\n */\n IsNavigatorAvailable,\n /**\n * Check if the document object exists\n * @returns true if the document object exists\n */\n IsDocumentAvailable,\n /**\n * Extracts text content from a DOM element hierarchy\n * @param element defines the root element\n * @returns a string\n */\n GetDOMTextContent,\n};\n//# sourceMappingURL=domManagement.js.map","/* eslint-disable @typescript-eslint/naming-convention */\n/**\n * Base error. Due to limitations of typedoc-check and missing documentation\n * in lib.es5.d.ts, cannot extend Error directly for RuntimeError.\n * @ignore\n */\nexport class BaseError extends Error {\n}\n// See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript\n// and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work\n// Polyfill for Object.setPrototypeOf if necessary.\nBaseError._setPrototypeOf = Object.setPrototypeOf ||\n ((o, proto) => {\n o.__proto__ = proto;\n return o;\n });\n/* IMP! DO NOT CHANGE THE NUMBERING OF EXISTING ERROR CODES */\n/**\n * Error codes for BaseError\n */\nexport const ErrorCodes = {\n // Mesh errors 0-999\n /** Invalid or empty mesh vertex positions. */\n MeshInvalidPositionsError: 0,\n // Texture errors 1000-1999\n /** Unsupported texture found. */\n UnsupportedTextureError: 1000,\n // GLTFLoader errors 2000-2999\n /** Unexpected magic number found in GLTF file header. */\n GLTFLoaderUnexpectedMagicError: 2000,\n // SceneLoader errors 3000-3999\n /** SceneLoader generic error code. Ideally wraps the inner exception. */\n SceneLoaderError: 3000,\n // File related errors 4000-4999\n /** Load file error */\n LoadFileError: 4000,\n /** Request file error */\n RequestFileError: 4001,\n /** Read file error */\n ReadFileError: 4002,\n};\n/**\n * Application runtime error\n */\nexport class RuntimeError extends BaseError {\n /**\n * Creates a new RuntimeError\n * @param message defines the message of the error\n * @param errorCode the error code\n * @param innerError the error that caused the outer error\n */\n constructor(message, errorCode, innerError) {\n super(message);\n this.errorCode = errorCode;\n this.innerError = innerError;\n this.name = \"RuntimeError\";\n BaseError._setPrototypeOf(this, RuntimeError.prototype);\n }\n}\n//# sourceMappingURL=error.js.map","/* eslint-disable @typescript-eslint/naming-convention */\nimport { WebRequest } from \"./webRequest.js\";\nimport { IsWindowObjectExist } from \"./domManagement.js\";\nimport { Observable } from \"./observable.js\";\nimport { FilesInputStore } from \"./filesInputStore.js\";\nimport { RetryStrategy } from \"./retryStrategy.js\";\nimport { BaseError, ErrorCodes, RuntimeError } from \"./error.js\";\nimport { DecodeBase64ToBinary, DecodeBase64ToString, EncodeArrayBufferToBase64 } from \"./stringTools.js\";\nimport { ShaderProcessor } from \"../Engines/Processors/shaderProcessor.js\";\nimport { ThinEngine } from \"../Engines/thinEngine.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { Logger } from \"./logger.js\";\nimport { TimingTools } from \"./timingTools.js\";\nconst Base64DataUrlRegEx = new RegExp(/^data:([^,]+\\/[^,]+)?;base64,/i);\n/** @ignore */\nexport class LoadFileError extends RuntimeError {\n /**\n * Creates a new LoadFileError\n * @param message defines the message of the error\n * @param object defines the optional web request\n */\n constructor(message, object) {\n super(message, ErrorCodes.LoadFileError);\n this.name = \"LoadFileError\";\n BaseError._setPrototypeOf(this, LoadFileError.prototype);\n if (object instanceof WebRequest) {\n this.request = object;\n }\n else {\n this.file = object;\n }\n }\n}\n/** @ignore */\nexport class RequestFileError extends RuntimeError {\n /**\n * Creates a new LoadFileError\n * @param message defines the message of the error\n * @param request defines the optional web request\n */\n constructor(message, request) {\n super(message, ErrorCodes.RequestFileError);\n this.request = request;\n this.name = \"RequestFileError\";\n BaseError._setPrototypeOf(this, RequestFileError.prototype);\n }\n}\n/** @ignore */\nexport class ReadFileError extends RuntimeError {\n /**\n * Creates a new ReadFileError\n * @param message defines the message of the error\n * @param file defines the optional file\n */\n constructor(message, file) {\n super(message, ErrorCodes.ReadFileError);\n this.file = file;\n this.name = \"ReadFileError\";\n BaseError._setPrototypeOf(this, ReadFileError.prototype);\n }\n}\n/**\n * @internal\n */\nexport const FileToolsOptions = {\n /**\n * Gets or sets the retry strategy to apply when an error happens while loading an asset.\n * When defining this function, return the wait time before trying again or return -1 to\n * stop retrying and error out.\n */\n DefaultRetryStrategy: RetryStrategy.ExponentialBackoff(),\n /**\n * Gets or sets the base URL to use to load assets\n */\n BaseUrl: \"\",\n /**\n * Default behaviour for cors in the application.\n * It can be a string if the expected behavior is identical in the entire app.\n * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)\n */\n CorsBehavior: \"anonymous\",\n /**\n * Gets or sets a function used to pre-process url before using them to load assets\n * @param url\n */\n PreprocessUrl: (url) => {\n return url;\n },\n};\n/**\n * Removes unwanted characters from an url\n * @param url defines the url to clean\n * @returns the cleaned url\n */\nconst _CleanUrl = (url) => {\n url = url.replace(/#/gm, \"%23\");\n return url;\n};\n/**\n * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.\n * @param url define the url we are trying\n * @param element define the dom element where to configure the cors policy\n * @internal\n */\nexport const SetCorsBehavior = (url, element) => {\n if (url && url.indexOf(\"data:\") === 0) {\n return;\n }\n if (FileToolsOptions.CorsBehavior) {\n if (typeof FileToolsOptions.CorsBehavior === \"string\" || FileToolsOptions.CorsBehavior instanceof String) {\n element.crossOrigin = FileToolsOptions.CorsBehavior;\n }\n else {\n const result = FileToolsOptions.CorsBehavior(url);\n if (result) {\n element.crossOrigin = result;\n }\n }\n }\n};\n/**\n * Loads an image as an HTMLImageElement.\n * @param input url string, ArrayBuffer, or Blob to load\n * @param onLoad callback called when the image successfully loads\n * @param onError callback called when the image fails to load\n * @param offlineProvider offline provider for caching\n * @param mimeType optional mime type\n * @param imageBitmapOptions\n * @returns the HTMLImageElement of the loaded image\n * @internal\n */\nexport const LoadImage = (input, onLoad, onError, offlineProvider, mimeType = \"\", imageBitmapOptions) => {\n var _a;\n let url;\n let usingObjectURL = false;\n if (input instanceof ArrayBuffer || ArrayBuffer.isView(input)) {\n if (typeof Blob !== \"undefined\" && typeof URL !== \"undefined\") {\n url = URL.createObjectURL(new Blob([input], { type: mimeType }));\n usingObjectURL = true;\n }\n else {\n url = `data:${mimeType};base64,` + EncodeArrayBufferToBase64(input);\n }\n }\n else if (input instanceof Blob) {\n url = URL.createObjectURL(input);\n usingObjectURL = true;\n }\n else {\n url = _CleanUrl(input);\n url = FileToolsOptions.PreprocessUrl(input);\n }\n const engine = EngineStore.LastCreatedEngine;\n const onErrorHandler = (exception) => {\n if (onError) {\n const inputText = url || input.toString();\n onError(`Error while trying to load image: ${inputText.indexOf(\"http\") === 0 || inputText.length <= 128 ? inputText : inputText.slice(0, 128) + \"...\"}`, exception);\n }\n };\n if (typeof Image === \"undefined\" || ((_a = engine === null || engine === void 0 ? void 0 : engine._features.forceBitmapOverHTMLImageElement) !== null && _a !== void 0 ? _a : false)) {\n LoadFile(url, (data) => {\n engine\n .createImageBitmap(new Blob([data], { type: mimeType }), Object.assign({ premultiplyAlpha: \"none\" }, imageBitmapOptions))\n .then((imgBmp) => {\n onLoad(imgBmp);\n if (usingObjectURL) {\n URL.revokeObjectURL(url);\n }\n })\n .catch((reason) => {\n if (onError) {\n onError(\"Error while trying to load image: \" + input, reason);\n }\n });\n }, undefined, offlineProvider || undefined, true, (request, exception) => {\n onErrorHandler(exception);\n });\n return null;\n }\n const img = new Image();\n SetCorsBehavior(url, img);\n const handlersList = [];\n const loadHandlersList = () => {\n handlersList.forEach((handler) => {\n handler.target.addEventListener(handler.name, handler.handler);\n });\n };\n const unloadHandlersList = () => {\n handlersList.forEach((handler) => {\n handler.target.removeEventListener(handler.name, handler.handler);\n });\n handlersList.length = 0;\n };\n const loadHandler = () => {\n unloadHandlersList();\n onLoad(img);\n // Must revoke the URL after calling onLoad to avoid security exceptions in\n // certain scenarios (e.g. when hosted in vscode).\n if (usingObjectURL && img.src) {\n URL.revokeObjectURL(img.src);\n }\n };\n const errorHandler = (err) => {\n unloadHandlersList();\n onErrorHandler(err);\n if (usingObjectURL && img.src) {\n URL.revokeObjectURL(img.src);\n }\n };\n const cspHandler = (err) => {\n if (err.blockedURI !== img.src) {\n return;\n }\n unloadHandlersList();\n const cspException = new Error(`CSP violation of policy ${err.effectiveDirective} ${err.blockedURI}. Current policy is ${err.originalPolicy}`);\n EngineStore.UseFallbackTexture = false;\n onErrorHandler(cspException);\n if (usingObjectURL && img.src) {\n URL.revokeObjectURL(img.src);\n }\n img.src = \"\";\n };\n handlersList.push({ target: img, name: \"load\", handler: loadHandler });\n handlersList.push({ target: img, name: \"error\", handler: errorHandler });\n handlersList.push({ target: document, name: \"securitypolicyviolation\", handler: cspHandler });\n loadHandlersList();\n const fromBlob = url.substring(0, 5) === \"blob:\";\n const fromData = url.substring(0, 5) === \"data:\";\n const noOfflineSupport = () => {\n if (fromBlob || fromData) {\n img.src = url;\n }\n else {\n LoadFile(url, (data, _, contentType) => {\n const type = !mimeType && contentType ? contentType : mimeType;\n const blob = new Blob([data], { type });\n const url = URL.createObjectURL(blob);\n usingObjectURL = true;\n img.src = url;\n }, undefined, offlineProvider || undefined, true, (request, exception) => {\n onErrorHandler(exception);\n });\n }\n };\n const loadFromOfflineSupport = () => {\n if (offlineProvider) {\n offlineProvider.loadImage(url, img);\n }\n };\n if (!fromBlob && !fromData && offlineProvider && offlineProvider.enableTexturesOffline) {\n offlineProvider.open(loadFromOfflineSupport, noOfflineSupport);\n }\n else {\n if (url.indexOf(\"file:\") !== -1) {\n const textureName = decodeURIComponent(url.substring(5).toLowerCase());\n if (FilesInputStore.FilesToLoad[textureName] && typeof URL !== \"undefined\") {\n try {\n let blobURL;\n try {\n blobURL = URL.createObjectURL(FilesInputStore.FilesToLoad[textureName]);\n }\n catch (ex) {\n // Chrome doesn't support oneTimeOnly parameter\n blobURL = URL.createObjectURL(FilesInputStore.FilesToLoad[textureName]);\n }\n img.src = blobURL;\n usingObjectURL = true;\n }\n catch (e) {\n img.src = \"\";\n }\n return img;\n }\n }\n noOfflineSupport();\n }\n return img;\n};\n/**\n * Reads a file from a File object\n * @param file defines the file to load\n * @param onSuccess defines the callback to call when data is loaded\n * @param onProgress defines the callback to call during loading process\n * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer\n * @param onError defines the callback to call when an error occurs\n * @returns a file request object\n * @internal\n */\nexport const ReadFile = (file, onSuccess, onProgress, useArrayBuffer, onError) => {\n const reader = new FileReader();\n const fileRequest = {\n onCompleteObservable: new Observable(),\n abort: () => reader.abort(),\n };\n reader.onloadend = () => fileRequest.onCompleteObservable.notifyObservers(fileRequest);\n if (onError) {\n reader.onerror = () => {\n onError(new ReadFileError(`Unable to read ${file.name}`, file));\n };\n }\n reader.onload = (e) => {\n //target doesn't have result from ts 1.3\n onSuccess(e.target[\"result\"]);\n };\n if (onProgress) {\n reader.onprogress = onProgress;\n }\n if (!useArrayBuffer) {\n // Asynchronous read\n reader.readAsText(file);\n }\n else {\n reader.readAsArrayBuffer(file);\n }\n return fileRequest;\n};\n/**\n * Loads a file from a url, a data url, or a file url\n * @param fileOrUrl file, url, data url, or file url to load\n * @param onSuccess callback called when the file successfully loads\n * @param onProgress callback called while file is loading (if the server supports this mode)\n * @param offlineProvider defines the offline provider for caching\n * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer\n * @param onError callback called when the file fails to load\n * @param onOpened\n * @returns a file request object\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport const LoadFile = (fileOrUrl, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError, onOpened) => {\n if (fileOrUrl.name) {\n return ReadFile(fileOrUrl, onSuccess, onProgress, useArrayBuffer, onError\n ? (error) => {\n onError(undefined, error);\n }\n : undefined);\n }\n const url = fileOrUrl;\n // If file and file input are set\n if (url.indexOf(\"file:\") !== -1) {\n let fileName = decodeURIComponent(url.substring(5).toLowerCase());\n if (fileName.indexOf(\"./\") === 0) {\n fileName = fileName.substring(2);\n }\n const file = FilesInputStore.FilesToLoad[fileName];\n if (file) {\n return ReadFile(file, onSuccess, onProgress, useArrayBuffer, onError ? (error) => onError(undefined, new LoadFileError(error.message, error.file)) : undefined);\n }\n }\n // For a Base64 Data URL\n const { match, type } = TestBase64DataUrl(url);\n if (match) {\n const fileRequest = {\n onCompleteObservable: new Observable(),\n abort: () => () => { },\n };\n try {\n const data = useArrayBuffer ? DecodeBase64UrlToBinary(url) : DecodeBase64UrlToString(url);\n onSuccess(data, undefined, type);\n }\n catch (error) {\n if (onError) {\n onError(undefined, error);\n }\n else {\n Logger.Error(error.message || \"Failed to parse the Data URL\");\n }\n }\n TimingTools.SetImmediate(() => {\n fileRequest.onCompleteObservable.notifyObservers(fileRequest);\n });\n return fileRequest;\n }\n return RequestFile(url, (data, request) => {\n onSuccess(data, request === null || request === void 0 ? void 0 : request.responseURL, request === null || request === void 0 ? void 0 : request.getResponseHeader(\"content-type\"));\n }, onProgress, offlineProvider, useArrayBuffer, onError\n ? (error) => {\n onError(error.request, new LoadFileError(error.message, error.request));\n }\n : undefined, onOpened);\n};\n/**\n * Loads a file from a url\n * @param url url to load\n * @param onSuccess callback called when the file successfully loads\n * @param onProgress callback called while file is loading (if the server supports this mode)\n * @param offlineProvider defines the offline provider for caching\n * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer\n * @param onError callback called when the file fails to load\n * @param onOpened callback called when the web request is opened\n * @returns a file request object\n * @internal\n */\nexport const RequestFile = (url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError, onOpened) => {\n url = _CleanUrl(url);\n url = FileToolsOptions.PreprocessUrl(url);\n const loadUrl = FileToolsOptions.BaseUrl + url;\n let aborted = false;\n const fileRequest = {\n onCompleteObservable: new Observable(),\n abort: () => (aborted = true),\n };\n const requestFile = () => {\n let request = new WebRequest();\n let retryHandle = null;\n let onReadyStateChange;\n const unbindEvents = () => {\n if (!request) {\n return;\n }\n if (onProgress) {\n request.removeEventListener(\"progress\", onProgress);\n }\n if (onReadyStateChange) {\n request.removeEventListener(\"readystatechange\", onReadyStateChange);\n }\n request.removeEventListener(\"loadend\", onLoadEnd);\n };\n let onLoadEnd = () => {\n unbindEvents();\n fileRequest.onCompleteObservable.notifyObservers(fileRequest);\n fileRequest.onCompleteObservable.clear();\n onProgress = undefined;\n onReadyStateChange = null;\n onLoadEnd = null;\n onError = undefined;\n onOpened = undefined;\n onSuccess = undefined;\n };\n fileRequest.abort = () => {\n aborted = true;\n if (onLoadEnd) {\n onLoadEnd();\n }\n if (request && request.readyState !== (XMLHttpRequest.DONE || 4)) {\n request.abort();\n }\n if (retryHandle !== null) {\n clearTimeout(retryHandle);\n retryHandle = null;\n }\n request = null;\n };\n const handleError = (error) => {\n const message = error.message || \"Unknown error\";\n if (onError && request) {\n onError(new RequestFileError(message, request));\n }\n else {\n Logger.Error(message);\n }\n };\n const retryLoop = (retryIndex) => {\n if (!request) {\n return;\n }\n request.open(\"GET\", loadUrl);\n if (onOpened) {\n try {\n onOpened(request);\n }\n catch (e) {\n handleError(e);\n return;\n }\n }\n if (useArrayBuffer) {\n request.responseType = \"arraybuffer\";\n }\n if (onProgress) {\n request.addEventListener(\"progress\", onProgress);\n }\n if (onLoadEnd) {\n request.addEventListener(\"loadend\", onLoadEnd);\n }\n onReadyStateChange = () => {\n if (aborted || !request) {\n return;\n }\n // In case of undefined state in some browsers.\n if (request.readyState === (XMLHttpRequest.DONE || 4)) {\n // Some browsers have issues where onreadystatechange can be called multiple times with the same value.\n if (onReadyStateChange) {\n request.removeEventListener(\"readystatechange\", onReadyStateChange);\n }\n if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!IsWindowObjectExist() || IsFileURL()))) {\n try {\n if (onSuccess) {\n onSuccess(useArrayBuffer ? request.response : request.responseText, request);\n }\n }\n catch (e) {\n handleError(e);\n }\n return;\n }\n const retryStrategy = FileToolsOptions.DefaultRetryStrategy;\n if (retryStrategy) {\n const waitTime = retryStrategy(loadUrl, request, retryIndex);\n if (waitTime !== -1) {\n // Prevent the request from completing for retry.\n unbindEvents();\n request = new WebRequest();\n retryHandle = setTimeout(() => retryLoop(retryIndex + 1), waitTime);\n return;\n }\n }\n const error = new RequestFileError(\"Error status: \" + request.status + \" \" + request.statusText + \" - Unable to load \" + loadUrl, request);\n if (onError) {\n onError(error);\n }\n }\n };\n request.addEventListener(\"readystatechange\", onReadyStateChange);\n request.send();\n };\n retryLoop(0);\n };\n // Caching all files\n if (offlineProvider && offlineProvider.enableSceneOffline) {\n const noOfflineSupport = (request) => {\n if (request && request.status > 400) {\n if (onError) {\n onError(request);\n }\n }\n else {\n requestFile();\n }\n };\n const loadFromOfflineSupport = () => {\n // TODO: database needs to support aborting and should return a IFileRequest\n if (offlineProvider) {\n offlineProvider.loadFile(FileToolsOptions.BaseUrl + url, (data) => {\n if (!aborted && onSuccess) {\n onSuccess(data);\n }\n fileRequest.onCompleteObservable.notifyObservers(fileRequest);\n }, onProgress\n ? (event) => {\n if (!aborted && onProgress) {\n onProgress(event);\n }\n }\n : undefined, noOfflineSupport, useArrayBuffer);\n }\n };\n offlineProvider.open(loadFromOfflineSupport, noOfflineSupport);\n }\n else {\n requestFile();\n }\n return fileRequest;\n};\n/**\n * Checks if the loaded document was accessed via `file:`-Protocol.\n * @returns boolean\n * @internal\n */\nexport const IsFileURL = () => {\n return typeof location !== \"undefined\" && location.protocol === \"file:\";\n};\n/**\n * Test if the given uri is a valid base64 data url\n * @param uri The uri to test\n * @returns True if the uri is a base64 data url or false otherwise\n * @internal\n */\nexport const IsBase64DataUrl = (uri) => {\n return Base64DataUrlRegEx.test(uri);\n};\nexport const TestBase64DataUrl = (uri) => {\n const results = Base64DataUrlRegEx.exec(uri);\n if (results === null || results.length === 0) {\n return { match: false, type: \"\" };\n }\n else {\n const type = results[0].replace(\"data:\", \"\").replace(\"base64,\", \"\");\n return { match: true, type };\n }\n};\n/**\n * Decode the given base64 uri.\n * @param uri The uri to decode\n * @returns The decoded base64 data.\n * @internal\n */\nexport function DecodeBase64UrlToBinary(uri) {\n return DecodeBase64ToBinary(uri.split(\",\")[1]);\n}\n/**\n * Decode the given base64 uri into a UTF-8 encoded string.\n * @param uri The uri to decode\n * @returns The decoded base64 data.\n * @internal\n */\nexport const DecodeBase64UrlToString = (uri) => {\n return DecodeBase64ToString(uri.split(\",\")[1]);\n};\n/**\n * This will be executed automatically for UMD and es5.\n * If esm dev wants the side effects to execute they will have to run it manually\n * Once we build native modules those need to be exported.\n * @internal\n */\nconst initSideEffects = () => {\n ThinEngine._FileToolsLoadImage = LoadImage;\n ThinEngine._FileToolsLoadFile = LoadFile;\n ShaderProcessor._FileToolsLoadFile = LoadFile;\n};\ninitSideEffects();\n/**\n* FileTools defined as any.\n* This should not be imported or used in future releases or in any module in the framework\n* @internal\n* @deprecated import the needed function from fileTools.ts\n*/\nexport let FileTools;\n/**\n * @param DecodeBase64UrlToBinary\n * @param DecodeBase64UrlToString\n * @param FileToolsOptions\n * @internal\n */\nexport const _injectLTSFileTools = (DecodeBase64UrlToBinary, DecodeBase64UrlToString, FileToolsOptions, IsBase64DataUrl, IsFileURL, LoadFile, LoadImage, ReadFile, RequestFile, SetCorsBehavior) => {\n /**\n * Backwards compatibility.\n * @internal\n * @deprecated\n */\n FileTools = {\n DecodeBase64UrlToBinary,\n DecodeBase64UrlToString,\n DefaultRetryStrategy: FileToolsOptions.DefaultRetryStrategy,\n BaseUrl: FileToolsOptions.BaseUrl,\n CorsBehavior: FileToolsOptions.CorsBehavior,\n PreprocessUrl: FileToolsOptions.PreprocessUrl,\n IsBase64DataUrl,\n IsFileURL,\n LoadFile,\n LoadImage,\n ReadFile,\n RequestFile,\n SetCorsBehavior,\n };\n Object.defineProperty(FileTools, \"DefaultRetryStrategy\", {\n get: function () {\n return FileToolsOptions.DefaultRetryStrategy;\n },\n set: function (value) {\n FileToolsOptions.DefaultRetryStrategy = value;\n },\n });\n Object.defineProperty(FileTools, \"BaseUrl\", {\n get: function () {\n return FileToolsOptions.BaseUrl;\n },\n set: function (value) {\n FileToolsOptions.BaseUrl = value;\n },\n });\n Object.defineProperty(FileTools, \"PreprocessUrl\", {\n get: function () {\n return FileToolsOptions.PreprocessUrl;\n },\n set: function (value) {\n FileToolsOptions.PreprocessUrl = value;\n },\n });\n Object.defineProperty(FileTools, \"CorsBehavior\", {\n get: function () {\n return FileToolsOptions.CorsBehavior;\n },\n set: function (value) {\n FileToolsOptions.CorsBehavior = value;\n },\n });\n};\n_injectLTSFileTools(DecodeBase64UrlToBinary, DecodeBase64UrlToString, FileToolsOptions, IsBase64DataUrl, IsFileURL, LoadFile, LoadImage, ReadFile, RequestFile, SetCorsBehavior);\n//# sourceMappingURL=fileTools.js.map","import { Logger } from \"./logger.js\";\nimport { GetClass } from \"./typeStore.js\";\n/**\n * Class used to enable instantiation of objects by class name\n */\nexport class InstantiationTools {\n /**\n * Tries to instantiate a new object from a given class name\n * @param className defines the class name to instantiate\n * @returns the new object or null if the system was not able to do the instantiation\n */\n static Instantiate(className) {\n if (this.RegisteredExternalClasses && this.RegisteredExternalClasses[className]) {\n return this.RegisteredExternalClasses[className];\n }\n const internalClass = GetClass(className);\n if (internalClass) {\n return internalClass;\n }\n Logger.Warn(className + \" not found, you may have missed an import.\");\n const arr = className.split(\".\");\n let fn = window || this;\n for (let i = 0, len = arr.length; i < len; i++) {\n fn = fn[arr[i]];\n }\n if (typeof fn !== \"function\") {\n return null;\n }\n return fn;\n }\n}\n/**\n * Use this object to register external classes like custom textures or material\n * to allow the loaders to instantiate them\n */\nInstantiationTools.RegisteredExternalClasses = {};\n//# sourceMappingURL=instantiationTools.js.map","/**\n * Class used to help managing file picking and drag'n'drop\n * File Storage\n */\nexport class FilesInputStore {\n}\n/**\n * List of files ready to be loaded\n */\nFilesInputStore.FilesToLoad = {};\n//# sourceMappingURL=filesInputStore.js.map","/**\n * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523\n * Be aware Math.random() could cause collisions, but:\n * \"All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide\"\n * @returns a pseudo random id\n */\nexport function RandomGUID() {\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0, v = c === \"x\" ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n/**\n * Class used to manipulate GUIDs\n */\nexport const GUID = {\n /**\n * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523\n * Be aware Math.random() could cause collisions, but:\n * \"All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide\"\n * @returns a pseudo random id\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n RandomId: RandomGUID,\n};\n//# sourceMappingURL=guid.js.map","/**\n * Logger used throughout the application to allow configuration of\n * the log level required for the messages.\n */\nexport class Logger {\n static _CheckLimit(message, limit) {\n let entry = Logger._LogLimitOutputs[message];\n if (!entry) {\n entry = { limit, current: 1 };\n Logger._LogLimitOutputs[message] = entry;\n }\n else {\n entry.current++;\n }\n return entry.current <= entry.limit;\n }\n static _GenerateLimitMessage(message, level = 1) {\n var _a;\n const entry = Logger._LogLimitOutputs[message];\n if (!entry || !Logger.MessageLimitReached) {\n return;\n }\n const type = this._Levels[level];\n if (entry.current === entry.limit) {\n Logger[type.name](Logger.MessageLimitReached.replace(/%LIMIT%/g, \"\" + entry.limit).replace(/%TYPE%/g, (_a = type.name) !== null && _a !== void 0 ? _a : \"\"));\n }\n }\n static _AddLogEntry(entry) {\n Logger._LogCache = entry + Logger._LogCache;\n if (Logger.OnNewCacheEntry) {\n Logger.OnNewCacheEntry(entry);\n }\n }\n static _FormatMessage(message) {\n const padStr = (i) => (i < 10 ? \"0\" + i : \"\" + i);\n const date = new Date();\n return \"[\" + padStr(date.getHours()) + \":\" + padStr(date.getMinutes()) + \":\" + padStr(date.getSeconds()) + \"]: \" + message;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n static _LogDisabled(message, limit) {\n // nothing to do\n }\n static _LogEnabled(level = 1, message, limit) {\n if (limit !== undefined && !Logger._CheckLimit(message, limit)) {\n return;\n }\n const formattedMessage = Logger._FormatMessage(message);\n const type = this._Levels[level];\n type.logFunc && type.logFunc(\"BJS - \" + formattedMessage);\n const entry = `
${formattedMessage}

`;\n Logger._AddLogEntry(entry);\n Logger._GenerateLimitMessage(message, level);\n }\n /**\n * Gets current log cache (list of logs)\n */\n static get LogCache() {\n return Logger._LogCache;\n }\n /**\n * Clears the log cache\n */\n static ClearLogCache() {\n Logger._LogCache = \"\";\n Logger._LogLimitOutputs = {};\n Logger.errorsCount = 0;\n }\n /**\n * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)\n */\n static set LogLevels(level) {\n Logger.Log = Logger._LogDisabled;\n Logger.Warn = Logger._LogDisabled;\n Logger.Error = Logger._LogDisabled;\n [Logger.MessageLogLevel, Logger.WarningLogLevel, Logger.ErrorLogLevel].forEach((l) => {\n if ((level & l) === l) {\n const type = this._Levels[l];\n Logger[type.name] = Logger._LogEnabled.bind(Logger, l);\n }\n });\n }\n}\n/**\n * No log\n */\nLogger.NoneLogLevel = 0;\n/**\n * Only message logs\n */\nLogger.MessageLogLevel = 1;\n/**\n * Only warning logs\n */\nLogger.WarningLogLevel = 2;\n/**\n * Only error logs\n */\nLogger.ErrorLogLevel = 4;\n/**\n * All logs\n */\nLogger.AllLogLevel = 7;\n/**\n * Message to display when a message has been logged too many times\n */\nLogger.MessageLimitReached = \"Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.\";\nLogger._LogCache = \"\";\nLogger._LogLimitOutputs = {};\n// levels according to the (binary) numbering.\nLogger._Levels = [\n {},\n { color: \"white\", logFunc: console.log, name: \"Log\" },\n { color: \"orange\", logFunc: console.warn, name: \"Warn\" },\n {},\n { color: \"red\", logFunc: console.error, name: \"Error\" },\n];\n/**\n * Gets a value indicating the number of loading errors\n * @ignorenaming\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nLogger.errorsCount = 0;\n/**\n * Log a message to the console\n */\nLogger.Log = Logger._LogEnabled.bind(Logger, Logger.MessageLogLevel);\n/**\n * Write a warning message to the console\n */\nLogger.Warn = Logger._LogEnabled.bind(Logger, Logger.WarningLogLevel);\n/**\n * Write an error message to the console\n */\nLogger.Error = Logger._LogEnabled.bind(Logger, Logger.ErrorLogLevel);\n//# sourceMappingURL=logger.js.map","/**\n * A class serves as a medium between the observable and its observers\n */\nexport class EventState {\n /**\n * Create a new EventState\n * @param mask defines the mask associated with this state\n * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true\n * @param target defines the original target of the state\n * @param currentTarget defines the current target of the state\n */\n constructor(mask, skipNextObservers = false, target, currentTarget) {\n this.initialize(mask, skipNextObservers, target, currentTarget);\n }\n /**\n * Initialize the current event state\n * @param mask defines the mask associated with this state\n * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true\n * @param target defines the original target of the state\n * @param currentTarget defines the current target of the state\n * @returns the current event state\n */\n initialize(mask, skipNextObservers = false, target, currentTarget) {\n this.mask = mask;\n this.skipNextObservers = skipNextObservers;\n this.target = target;\n this.currentTarget = currentTarget;\n return this;\n }\n}\n/**\n * Represent an Observer registered to a given Observable object.\n */\nexport class Observer {\n /**\n * Creates a new observer\n * @param callback defines the callback to call when the observer is notified\n * @param mask defines the mask of the observer (used to filter notifications)\n * @param scope defines the current scope used to restore the JS context\n */\n constructor(\n /**\n * Defines the callback to call when the observer is notified\n */\n callback, \n /**\n * Defines the mask of the observer (used to filter notifications)\n */\n mask, \n /**\n * Defines the current scope used to restore the JS context\n */\n scope = null) {\n this.callback = callback;\n this.mask = mask;\n this.scope = scope;\n /** @internal */\n this._willBeUnregistered = false;\n /**\n * Gets or sets a property defining that the observer as to be unregistered after the next notification\n */\n this.unregisterOnNextCall = false;\n /**\n * this function can be used to remove the observer from the observable.\n * It will be set by the observable that the observer belongs to.\n * @internal\n */\n this._remove = null;\n }\n /**\n * Remove the observer from its observable\n * This can be used instead of using the observable's remove function.\n */\n remove() {\n if (this._remove) {\n this._remove();\n }\n }\n}\n/**\n * The Observable class is a simple implementation of the Observable pattern.\n *\n * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.\n * This enable a more fine grained execution without having to rely on multiple different Observable objects.\n * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).\n * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.\n */\nexport class Observable {\n /**\n * Create an observable from a Promise.\n * @param promise a promise to observe for fulfillment.\n * @param onErrorObservable an observable to notify if a promise was rejected.\n * @returns the new Observable\n */\n static FromPromise(promise, onErrorObservable) {\n const observable = new Observable();\n promise\n .then((ret) => {\n observable.notifyObservers(ret);\n })\n .catch((err) => {\n if (onErrorObservable) {\n onErrorObservable.notifyObservers(err);\n }\n else {\n throw err;\n }\n });\n return observable;\n }\n /**\n * Gets the list of observers\n * Note that observers that were recently deleted may still be present in the list because they are only really deleted on the next javascript tick!\n */\n get observers() {\n return this._observers;\n }\n /**\n * Creates a new observable\n * @param onObserverAdded defines a callback to call when a new observer is added\n * @param notifyIfTriggered If set to true the observable will notify when an observer was added if the observable was already triggered.\n */\n constructor(onObserverAdded, \n /**\n * If set to true the observable will notify when an observer was added if the observable was already triggered.\n * This is helpful to single-state observables like the scene onReady or the dispose observable.\n */\n notifyIfTriggered = false) {\n this.notifyIfTriggered = notifyIfTriggered;\n this._observers = new Array();\n this._numObserversMarkedAsDeleted = 0;\n this._hasNotified = false;\n this._eventState = new EventState(0);\n if (onObserverAdded) {\n this._onObserverAdded = onObserverAdded;\n }\n }\n /**\n * Create a new Observer with the specified callback\n * @param callback the callback that will be executed for that Observer\n * @param mask the mask used to filter observers\n * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.\n * @param scope optional scope for the callback to be called from\n * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification\n * @returns the new observer created for the callback\n */\n add(callback, mask = -1, insertFirst = false, scope = null, unregisterOnFirstCall = false) {\n if (!callback) {\n return null;\n }\n const observer = new Observer(callback, mask, scope);\n observer.unregisterOnNextCall = unregisterOnFirstCall;\n if (insertFirst) {\n this._observers.unshift(observer);\n }\n else {\n this._observers.push(observer);\n }\n if (this._onObserverAdded) {\n this._onObserverAdded(observer);\n }\n // If the observable was already triggered and the observable is set to notify if triggered, notify the new observer\n if (this._hasNotified && this.notifyIfTriggered) {\n if (this._lastNotifiedValue !== undefined) {\n this.notifyObserver(observer, this._lastNotifiedValue);\n }\n }\n // attach the remove function to the observer\n observer._remove = () => {\n this.remove(observer);\n };\n return observer;\n }\n /**\n * Create a new Observer with the specified callback and unregisters after the next notification\n * @param callback the callback that will be executed for that Observer\n * @returns the new observer created for the callback\n */\n addOnce(callback) {\n return this.add(callback, undefined, undefined, undefined, true);\n }\n /**\n * Remove an Observer from the Observable object\n * @param observer the instance of the Observer to remove\n * @returns false if it doesn't belong to this Observable\n */\n remove(observer) {\n if (!observer) {\n return false;\n }\n observer._remove = null;\n const index = this._observers.indexOf(observer);\n if (index !== -1) {\n this._deferUnregister(observer);\n return true;\n }\n return false;\n }\n /**\n * Remove a callback from the Observable object\n * @param callback the callback to remove\n * @param scope optional scope. If used only the callbacks with this scope will be removed\n * @returns false if it doesn't belong to this Observable\n */\n removeCallback(callback, scope) {\n for (let index = 0; index < this._observers.length; index++) {\n const observer = this._observers[index];\n if (observer._willBeUnregistered) {\n continue;\n }\n if (observer.callback === callback && (!scope || scope === observer.scope)) {\n this._deferUnregister(observer);\n return true;\n }\n }\n return false;\n }\n /**\n * @internal\n */\n _deferUnregister(observer) {\n if (observer._willBeUnregistered) {\n return;\n }\n this._numObserversMarkedAsDeleted++;\n observer.unregisterOnNextCall = false;\n observer._willBeUnregistered = true;\n setTimeout(() => {\n this._remove(observer);\n }, 0);\n }\n // This should only be called when not iterating over _observers to avoid callback skipping.\n // Removes an observer from the _observer Array.\n _remove(observer, updateCounter = true) {\n if (!observer) {\n return false;\n }\n const index = this._observers.indexOf(observer);\n if (index !== -1) {\n if (updateCounter) {\n this._numObserversMarkedAsDeleted--;\n }\n this._observers.splice(index, 1);\n return true;\n }\n return false;\n }\n /**\n * Moves the observable to the top of the observer list making it get called first when notified\n * @param observer the observer to move\n */\n makeObserverTopPriority(observer) {\n this._remove(observer, false);\n this._observers.unshift(observer);\n }\n /**\n * Moves the observable to the bottom of the observer list making it get called last when notified\n * @param observer the observer to move\n */\n makeObserverBottomPriority(observer) {\n this._remove(observer, false);\n this._observers.push(observer);\n }\n /**\n * Notify all Observers by calling their respective callback with the given data\n * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute\n * @param eventData defines the data to send to all observers\n * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)\n * @param target defines the original target of the state\n * @param currentTarget defines the current target of the state\n * @param userInfo defines any user info to send to observers\n * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)\n */\n notifyObservers(eventData, mask = -1, target, currentTarget, userInfo) {\n // this prevents potential memory leaks - if an object is disposed but the observable doesn't get cleared.\n if (this.notifyIfTriggered) {\n this._hasNotified = true;\n this._lastNotifiedValue = eventData;\n }\n if (!this._observers.length) {\n return true;\n }\n const state = this._eventState;\n state.mask = mask;\n state.target = target;\n state.currentTarget = currentTarget;\n state.skipNextObservers = false;\n state.lastReturnValue = eventData;\n state.userInfo = userInfo;\n for (const obs of this._observers) {\n if (obs._willBeUnregistered) {\n continue;\n }\n if (obs.mask & mask) {\n if (obs.unregisterOnNextCall) {\n this._deferUnregister(obs);\n }\n if (obs.scope) {\n state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);\n }\n else {\n state.lastReturnValue = obs.callback(eventData, state);\n }\n }\n if (state.skipNextObservers) {\n return false;\n }\n }\n return true;\n }\n /**\n * Notify a specific observer\n * @param observer defines the observer to notify\n * @param eventData defines the data to be sent to each callback\n * @param mask is used to filter observers defaults to -1\n */\n notifyObserver(observer, eventData, mask = -1) {\n // this prevents potential memory leaks - if an object is disposed but the observable doesn't get cleared.\n if (this.notifyIfTriggered) {\n this._hasNotified = true;\n this._lastNotifiedValue = eventData;\n }\n if (observer._willBeUnregistered) {\n return;\n }\n const state = this._eventState;\n state.mask = mask;\n state.skipNextObservers = false;\n if (observer.unregisterOnNextCall) {\n this._deferUnregister(observer);\n }\n observer.callback(eventData, state);\n }\n /**\n * Gets a boolean indicating if the observable has at least one observer\n * @returns true is the Observable has at least one Observer registered\n */\n hasObservers() {\n return this._observers.length - this._numObserversMarkedAsDeleted > 0;\n }\n /**\n * Clear the list of observers\n */\n clear() {\n while (this._observers.length) {\n const o = this._observers.pop();\n if (o) {\n o._remove = null;\n }\n }\n this._onObserverAdded = null;\n this._numObserversMarkedAsDeleted = 0;\n this.cleanLastNotifiedState();\n }\n /**\n * Clean the last notified state - both the internal last value and the has-notified flag\n */\n cleanLastNotifiedState() {\n this._hasNotified = false;\n this._lastNotifiedValue = undefined;\n }\n /**\n * Clone the current observable\n * @returns a new observable\n */\n clone() {\n const result = new Observable();\n result._observers = this._observers.slice(0);\n return result;\n }\n /**\n * Does this observable handles observer registered with a given mask\n * @param mask defines the mask to be tested\n * @returns whether or not one observer registered with the given mask is handled\n **/\n hasSpecificMask(mask = -1) {\n for (const obs of this._observers) {\n if (obs.mask & mask || obs.mask === mask) {\n return true;\n }\n }\n return false;\n }\n}\n//# sourceMappingURL=observable.js.map","import { PrecisionDate } from \"./precisionDate.js\";\n/**\n * This class is used to track a performance counter which is number based.\n * The user has access to many properties which give statistics of different nature.\n *\n * The implementer can track two kinds of Performance Counter: time and count.\n * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.\n * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.\n */\nexport class PerfCounter {\n /**\n * Returns the smallest value ever\n */\n get min() {\n return this._min;\n }\n /**\n * Returns the biggest value ever\n */\n get max() {\n return this._max;\n }\n /**\n * Returns the average value since the performance counter is running\n */\n get average() {\n return this._average;\n }\n /**\n * Returns the average value of the last second the counter was monitored\n */\n get lastSecAverage() {\n return this._lastSecAverage;\n }\n /**\n * Returns the current value\n */\n get current() {\n return this._current;\n }\n /**\n * Gets the accumulated total\n */\n get total() {\n return this._totalAccumulated;\n }\n /**\n * Gets the total value count\n */\n get count() {\n return this._totalValueCount;\n }\n /**\n * Creates a new counter\n */\n constructor() {\n this._startMonitoringTime = 0;\n this._min = 0;\n this._max = 0;\n this._average = 0;\n this._lastSecAverage = 0;\n this._current = 0;\n this._totalValueCount = 0;\n this._totalAccumulated = 0;\n this._lastSecAccumulated = 0;\n this._lastSecTime = 0;\n this._lastSecValueCount = 0;\n }\n /**\n * Call this method to start monitoring a new frame.\n * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.\n */\n fetchNewFrame() {\n this._totalValueCount++;\n this._current = 0;\n this._lastSecValueCount++;\n }\n /**\n * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)\n * @param newCount the count value to add to the monitored count\n * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.\n */\n addCount(newCount, fetchResult) {\n if (!PerfCounter.Enabled) {\n return;\n }\n this._current += newCount;\n if (fetchResult) {\n this._fetchResult();\n }\n }\n /**\n * Start monitoring this performance counter\n */\n beginMonitoring() {\n if (!PerfCounter.Enabled) {\n return;\n }\n this._startMonitoringTime = PrecisionDate.Now;\n }\n /**\n * Compute the time lapsed since the previous beginMonitoring() call.\n * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter\n */\n endMonitoring(newFrame = true) {\n if (!PerfCounter.Enabled) {\n return;\n }\n if (newFrame) {\n this.fetchNewFrame();\n }\n const currentTime = PrecisionDate.Now;\n this._current = currentTime - this._startMonitoringTime;\n if (newFrame) {\n this._fetchResult();\n }\n }\n /**\n * Call this method to end the monitoring of a frame.\n * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the end of the frame, after beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.\n */\n endFrame() {\n this._fetchResult();\n }\n _fetchResult() {\n this._totalAccumulated += this._current;\n this._lastSecAccumulated += this._current;\n // Min/Max update\n this._min = Math.min(this._min, this._current);\n this._max = Math.max(this._max, this._current);\n this._average = this._totalAccumulated / this._totalValueCount;\n // Reset last sec?\n const now = PrecisionDate.Now;\n if (now - this._lastSecTime > 1000) {\n this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;\n this._lastSecTime = now;\n this._lastSecAccumulated = 0;\n this._lastSecValueCount = 0;\n }\n }\n}\n/**\n * Gets or sets a global boolean to turn on and off all the counters\n */\nPerfCounter.Enabled = true;\n//# sourceMappingURL=perfCounter.js.map","import { PrecisionDate } from \"./precisionDate.js\";\n/**\n * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window\n */\nexport class PerformanceMonitor {\n /**\n * constructor\n * @param frameSampleSize The number of samples required to saturate the sliding window\n */\n constructor(frameSampleSize = 30) {\n this._enabled = true;\n this._rollingFrameTime = new RollingAverage(frameSampleSize);\n }\n /**\n * Samples current frame\n * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames\n */\n sampleFrame(timeMs = PrecisionDate.Now) {\n if (!this._enabled) {\n return;\n }\n if (this._lastFrameTimeMs != null) {\n const dt = timeMs - this._lastFrameTimeMs;\n this._rollingFrameTime.add(dt);\n }\n this._lastFrameTimeMs = timeMs;\n }\n /**\n * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)\n */\n get averageFrameTime() {\n return this._rollingFrameTime.average;\n }\n /**\n * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)\n */\n get averageFrameTimeVariance() {\n return this._rollingFrameTime.variance;\n }\n /**\n * Returns the frame time of the most recent frame\n */\n get instantaneousFrameTime() {\n return this._rollingFrameTime.history(0);\n }\n /**\n * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)\n */\n get averageFPS() {\n return 1000.0 / this._rollingFrameTime.average;\n }\n /**\n * Returns the average framerate in frames per second using the most recent frame time\n */\n get instantaneousFPS() {\n const history = this._rollingFrameTime.history(0);\n if (history === 0) {\n return 0;\n }\n return 1000.0 / history;\n }\n /**\n * Returns true if enough samples have been taken to completely fill the sliding window\n */\n get isSaturated() {\n return this._rollingFrameTime.isSaturated();\n }\n /**\n * Enables contributions to the sliding window sample set\n */\n enable() {\n this._enabled = true;\n }\n /**\n * Disables contributions to the sliding window sample set\n * Samples will not be interpolated over the disabled period\n */\n disable() {\n this._enabled = false;\n //clear last sample to avoid interpolating over the disabled period when next enabled\n this._lastFrameTimeMs = null;\n }\n /**\n * Returns true if sampling is enabled\n */\n get isEnabled() {\n return this._enabled;\n }\n /**\n * Resets performance monitor\n */\n reset() {\n //clear last sample to avoid interpolating over the disabled period when next enabled\n this._lastFrameTimeMs = null;\n //wipe record\n this._rollingFrameTime.reset();\n }\n}\n/**\n * RollingAverage\n *\n * Utility to efficiently compute the rolling average and variance over a sliding window of samples\n */\nexport class RollingAverage {\n /**\n * constructor\n * @param length The number of samples required to saturate the sliding window\n */\n constructor(length) {\n this._samples = new Array(length);\n this.reset();\n }\n /**\n * Adds a sample to the sample set\n * @param v The sample value\n */\n add(v) {\n //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance\n let delta;\n //we need to check if we've already wrapped round\n if (this.isSaturated()) {\n //remove bottom of stack from mean\n const bottomValue = this._samples[this._pos];\n delta = bottomValue - this.average;\n this.average -= delta / (this._sampleCount - 1);\n this._m2 -= delta * (bottomValue - this.average);\n }\n else {\n this._sampleCount++;\n }\n //add new value to mean\n delta = v - this.average;\n this.average += delta / this._sampleCount;\n this._m2 += delta * (v - this.average);\n //set the new variance\n this.variance = this._m2 / (this._sampleCount - 1);\n this._samples[this._pos] = v;\n this._pos++;\n this._pos %= this._samples.length; //positive wrap around\n }\n /**\n * Returns previously added values or null if outside of history or outside the sliding window domain\n * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that\n * @returns Value previously recorded with add() or null if outside of range\n */\n history(i) {\n if (i >= this._sampleCount || i >= this._samples.length) {\n return 0;\n }\n const i0 = this._wrapPosition(this._pos - 1.0);\n return this._samples[this._wrapPosition(i0 - i)];\n }\n /**\n * Returns true if enough samples have been taken to completely fill the sliding window\n * @returns true if sample-set saturated\n */\n isSaturated() {\n return this._sampleCount >= this._samples.length;\n }\n /**\n * Resets the rolling average (equivalent to 0 samples taken so far)\n */\n reset() {\n this.average = 0;\n this.variance = 0;\n this._sampleCount = 0;\n this._pos = 0;\n this._m2 = 0;\n }\n /**\n * Wraps a value around the sample range boundaries\n * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.\n * @returns Wrapped position in sample range\n */\n _wrapPosition(i) {\n const max = this._samples.length;\n return ((i % max) + max) % max;\n }\n}\n//# sourceMappingURL=performanceMonitor.js.map","import { DomManagement } from \"./domManagement.js\";\n/**\n * Class containing a set of static utilities functions for precision date\n */\nexport class PrecisionDate {\n /**\n * Gets either window.performance.now() if supported or Date.now() else\n */\n static get Now() {\n if (DomManagement.IsWindowObjectExist() && window.performance && window.performance.now) {\n return window.performance.now();\n }\n return Date.now();\n }\n}\n//# sourceMappingURL=precisionDate.js.map","/**\n * Class used to define a retry strategy when error happens while loading assets\n */\nexport class RetryStrategy {\n /**\n * Function used to defines an exponential back off strategy\n * @param maxRetries defines the maximum number of retries (3 by default)\n * @param baseInterval defines the interval between retries\n * @returns the strategy function to use\n */\n static ExponentialBackoff(maxRetries = 3, baseInterval = 500) {\n return (url, request, retryIndex) => {\n if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf(\"file:\") !== -1) {\n return -1;\n }\n return Math.pow(2, retryIndex) * baseInterval;\n };\n }\n}\n//# sourceMappingURL=retryStrategy.js.map","/**\n * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.\n */\nexport class SmartArray {\n /**\n * Instantiates a Smart Array.\n * @param capacity defines the default capacity of the array.\n */\n constructor(capacity) {\n /**\n * The active length of the array.\n */\n this.length = 0;\n this.data = new Array(capacity);\n this._id = SmartArray._GlobalId++;\n }\n /**\n * Pushes a value at the end of the active data.\n * @param value defines the object to push in the array.\n */\n push(value) {\n this.data[this.length++] = value;\n if (this.length > this.data.length) {\n this.data.length *= 2;\n }\n }\n /**\n * Iterates over the active data and apply the lambda to them.\n * @param func defines the action to apply on each value.\n */\n forEach(func) {\n for (let index = 0; index < this.length; index++) {\n func(this.data[index]);\n }\n }\n /**\n * Sorts the full sets of data.\n * @param compareFn defines the comparison function to apply.\n */\n sort(compareFn) {\n this.data.sort(compareFn);\n }\n /**\n * Resets the active data to an empty array.\n */\n reset() {\n this.length = 0;\n }\n /**\n * Releases all the data from the array as well as the array.\n */\n dispose() {\n this.reset();\n if (this.data) {\n this.data.length = 0;\n }\n }\n /**\n * Concats the active data with a given array.\n * @param array defines the data to concatenate with.\n */\n concat(array) {\n if (array.length === 0) {\n return;\n }\n if (this.length + array.length > this.data.length) {\n this.data.length = (this.length + array.length) * 2;\n }\n for (let index = 0; index < array.length; index++) {\n this.data[this.length++] = (array.data || array)[index];\n }\n }\n /**\n * Returns the position of a value in the active data.\n * @param value defines the value to find the index for\n * @returns the index if found in the active data otherwise -1\n */\n indexOf(value) {\n const position = this.data.indexOf(value);\n if (position >= this.length) {\n return -1;\n }\n return position;\n }\n /**\n * Returns whether an element is part of the active data.\n * @param value defines the value to look for\n * @returns true if found in the active data otherwise false\n */\n contains(value) {\n return this.indexOf(value) !== -1;\n }\n}\n// Statics\nSmartArray._GlobalId = 0;\n/**\n * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.\n * The data in this array can only be present once\n */\nexport class SmartArrayNoDuplicate extends SmartArray {\n constructor() {\n super(...arguments);\n this._duplicateId = 0;\n }\n /**\n * Pushes a value at the end of the active data.\n * THIS DOES NOT PREVENT DUPPLICATE DATA\n * @param value defines the object to push in the array.\n */\n push(value) {\n super.push(value);\n if (!value.__smartArrayFlags) {\n value.__smartArrayFlags = {};\n }\n value.__smartArrayFlags[this._id] = this._duplicateId;\n }\n /**\n * Pushes a value at the end of the active data.\n * If the data is already present, it won t be added again\n * @param value defines the object to push in the array.\n * @returns true if added false if it was already present\n */\n pushNoDuplicate(value) {\n if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {\n return false;\n }\n this.push(value);\n return true;\n }\n /**\n * Resets the active data to an empty array.\n */\n reset() {\n super.reset();\n this._duplicateId++;\n }\n /**\n * Concats the active data with a given array.\n * This ensures no duplicate will be present in the result.\n * @param array defines the data to concatenate with.\n */\n concatWithNoDuplicate(array) {\n if (array.length === 0) {\n return;\n }\n if (this.length + array.length > this.data.length) {\n this.data.length = (this.length + array.length) * 2;\n }\n for (let index = 0; index < array.length; index++) {\n const item = (array.data || array)[index];\n this.pushNoDuplicate(item);\n }\n }\n}\n//# sourceMappingURL=smartArray.js.map","/**\n * This class implement a typical dictionary using a string as key and the generic type T as value.\n * The underlying implementation relies on an associative array to ensure the best performances.\n * The value can be anything including 'null' but except 'undefined'\n */\nexport class StringDictionary {\n constructor() {\n this._count = 0;\n this._data = {};\n }\n /**\n * This will clear this dictionary and copy the content from the 'source' one.\n * If the T value is a custom object, it won't be copied/cloned, the same object will be used\n * @param source the dictionary to take the content from and copy to this dictionary\n */\n copyFrom(source) {\n this.clear();\n source.forEach((t, v) => this.add(t, v));\n }\n /**\n * Get a value based from its key\n * @param key the given key to get the matching value from\n * @returns the value if found, otherwise undefined is returned\n */\n get(key) {\n const val = this._data[key];\n if (val !== undefined) {\n return val;\n }\n return undefined;\n }\n /**\n * Get a value from its key or add it if it doesn't exist.\n * This method will ensure you that a given key/data will be present in the dictionary.\n * @param key the given key to get the matching value from\n * @param factory the factory that will create the value if the key is not present in the dictionary.\n * The factory will only be invoked if there's no data for the given key.\n * @returns the value corresponding to the key.\n */\n getOrAddWithFactory(key, factory) {\n let val = this.get(key);\n if (val !== undefined) {\n return val;\n }\n val = factory(key);\n if (val) {\n this.add(key, val);\n }\n return val;\n }\n /**\n * Get a value from its key if present in the dictionary otherwise add it\n * @param key the key to get the value from\n * @param val if there's no such key/value pair in the dictionary add it with this value\n * @returns the value corresponding to the key\n */\n getOrAdd(key, val) {\n const curVal = this.get(key);\n if (curVal !== undefined) {\n return curVal;\n }\n this.add(key, val);\n return val;\n }\n /**\n * Check if there's a given key in the dictionary\n * @param key the key to check for\n * @returns true if the key is present, false otherwise\n */\n contains(key) {\n return this._data[key] !== undefined;\n }\n /**\n * Add a new key and its corresponding value\n * @param key the key to add\n * @param value the value corresponding to the key\n * @returns true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary\n */\n add(key, value) {\n if (this._data[key] !== undefined) {\n return false;\n }\n this._data[key] = value;\n ++this._count;\n return true;\n }\n /**\n * Update a specific value associated to a key\n * @param key defines the key to use\n * @param value defines the value to store\n * @returns true if the value was updated (or false if the key was not found)\n */\n set(key, value) {\n if (this._data[key] === undefined) {\n return false;\n }\n this._data[key] = value;\n return true;\n }\n /**\n * Get the element of the given key and remove it from the dictionary\n * @param key defines the key to search\n * @returns the value associated with the key or null if not found\n */\n getAndRemove(key) {\n const val = this.get(key);\n if (val !== undefined) {\n delete this._data[key];\n --this._count;\n return val;\n }\n return null;\n }\n /**\n * Remove a key/value from the dictionary.\n * @param key the key to remove\n * @returns true if the item was successfully deleted, false if no item with such key exist in the dictionary\n */\n remove(key) {\n if (this.contains(key)) {\n delete this._data[key];\n --this._count;\n return true;\n }\n return false;\n }\n /**\n * Clear the whole content of the dictionary\n */\n clear() {\n this._data = {};\n this._count = 0;\n }\n /**\n * Gets the current count\n */\n get count() {\n return this._count;\n }\n /**\n * Execute a callback on each key/val of the dictionary.\n * Note that you can remove any element in this dictionary in the callback implementation\n * @param callback the callback to execute on a given key/value pair\n */\n forEach(callback) {\n for (const cur in this._data) {\n const val = this._data[cur];\n callback(cur, val);\n }\n }\n /**\n * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.\n * If the callback returns null or undefined the method will iterate to the next key/value pair\n * Note that you can remove any element in this dictionary in the callback implementation\n * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned\n * @returns the first item\n */\n first(callback) {\n for (const cur in this._data) {\n const val = this._data[cur];\n const res = callback(cur, val);\n if (res) {\n return res;\n }\n }\n return null;\n }\n}\n//# sourceMappingURL=stringDictionary.js.map","/* eslint-disable @typescript-eslint/naming-convention */\n/**\n * Checks for a matching suffix at the end of a string (for ES5 and lower)\n * @param str Source string\n * @param suffix Suffix to search for in the source string\n * @returns Boolean indicating whether the suffix was found (true) or not (false)\n * @deprecated Please use native string function instead\n */\nexport const EndsWith = (str, suffix) => {\n return str.endsWith(suffix);\n};\n/**\n * Checks for a matching suffix at the beginning of a string (for ES5 and lower)\n * @param str Source string\n * @param suffix Suffix to search for in the source string\n * @returns Boolean indicating whether the suffix was found (true) or not (false)\n * @deprecated Please use native string function instead\n */\nexport const StartsWith = (str, suffix) => {\n if (!str) {\n return false;\n }\n return str.startsWith(suffix);\n};\n/**\n * Decodes a buffer into a string\n * @param buffer The buffer to decode\n * @returns The decoded string\n */\nexport const Decode = (buffer) => {\n if (typeof TextDecoder !== \"undefined\") {\n return new TextDecoder().decode(buffer);\n }\n let result = \"\";\n for (let i = 0; i < buffer.byteLength; i++) {\n result += String.fromCharCode(buffer[i]);\n }\n return result;\n};\n/**\n * Encode a buffer to a base64 string\n * @param buffer defines the buffer to encode\n * @returns the encoded string\n */\nexport const EncodeArrayBufferToBase64 = (buffer) => {\n const keyStr = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\n let output = \"\";\n let chr1, chr2, chr3, enc1, enc2, enc3, enc4;\n let i = 0;\n const bytes = ArrayBuffer.isView(buffer) ? new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength) : new Uint8Array(buffer);\n while (i < bytes.length) {\n chr1 = bytes[i++];\n chr2 = i < bytes.length ? bytes[i++] : Number.NaN;\n chr3 = i < bytes.length ? bytes[i++] : Number.NaN;\n enc1 = chr1 >> 2;\n enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);\n enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);\n enc4 = chr3 & 63;\n if (isNaN(chr2)) {\n enc3 = enc4 = 64;\n }\n else if (isNaN(chr3)) {\n enc4 = 64;\n }\n output += keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);\n }\n return output;\n};\n/**\n * Converts a given base64 string as an ASCII encoded stream of data\n * @param base64Data The base64 encoded string to decode\n * @returns Decoded ASCII string\n */\nexport const DecodeBase64ToString = (base64Data) => {\n return atob(base64Data);\n};\n/**\n * Converts a given base64 string into an ArrayBuffer of raw byte data\n * @param base64Data The base64 encoded string to decode\n * @returns ArrayBuffer of byte data\n */\nexport const DecodeBase64ToBinary = (base64Data) => {\n const decodedString = DecodeBase64ToString(base64Data);\n const bufferLength = decodedString.length;\n const bufferView = new Uint8Array(new ArrayBuffer(bufferLength));\n for (let i = 0; i < bufferLength; i++) {\n bufferView[i] = decodedString.charCodeAt(i);\n }\n return bufferView.buffer;\n};\n/**\n * Converts a number to string and pads with preceding zeroes until it is of specified length.\n * @param num the number to convert and pad\n * @param length the expected length of the string\n * @returns the padded string\n */\nexport const PadNumber = (num, length) => {\n let str = String(num);\n while (str.length < length) {\n str = \"0\" + str;\n }\n return str;\n};\n/**\n * Helper to manipulate strings\n */\nexport const StringTools = {\n EndsWith,\n StartsWith,\n Decode,\n EncodeArrayBufferToBase64,\n DecodeBase64ToString,\n DecodeBase64ToBinary,\n PadNumber,\n};\n//# sourceMappingURL=stringTools.js.map","import { AndOrNotEvaluator } from \"./andOrNotEvaluator.js\";\n/**\n * Class used to store custom tags\n */\nexport class Tags {\n /**\n * Adds support for tags on the given object\n * @param obj defines the object to use\n */\n static EnableFor(obj) {\n obj._tags = obj._tags || {};\n obj.hasTags = () => {\n return Tags.HasTags(obj);\n };\n obj.addTags = (tagsString) => {\n return Tags.AddTagsTo(obj, tagsString);\n };\n obj.removeTags = (tagsString) => {\n return Tags.RemoveTagsFrom(obj, tagsString);\n };\n obj.matchesTagsQuery = (tagsQuery) => {\n return Tags.MatchesQuery(obj, tagsQuery);\n };\n }\n /**\n * Removes tags support\n * @param obj defines the object to use\n */\n static DisableFor(obj) {\n delete obj._tags;\n delete obj.hasTags;\n delete obj.addTags;\n delete obj.removeTags;\n delete obj.matchesTagsQuery;\n }\n /**\n * Gets a boolean indicating if the given object has tags\n * @param obj defines the object to use\n * @returns a boolean\n */\n static HasTags(obj) {\n if (!obj._tags) {\n return false;\n }\n const tags = obj._tags;\n for (const i in tags) {\n if (Object.prototype.hasOwnProperty.call(tags, i)) {\n return true;\n }\n }\n return false;\n }\n /**\n * Gets the tags available on a given object\n * @param obj defines the object to use\n * @param asString defines if the tags must be returned as a string instead of an array of strings\n * @returns the tags\n */\n static GetTags(obj, asString = true) {\n if (!obj._tags) {\n return null;\n }\n if (asString) {\n const tagsArray = [];\n for (const tag in obj._tags) {\n if (Object.prototype.hasOwnProperty.call(obj._tags, tag) && obj._tags[tag] === true) {\n tagsArray.push(tag);\n }\n }\n return tagsArray.join(\" \");\n }\n else {\n return obj._tags;\n }\n }\n /**\n * Adds tags to an object\n * @param obj defines the object to use\n * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags.\n * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces\n */\n static AddTagsTo(obj, tagsString) {\n if (!tagsString) {\n return;\n }\n if (typeof tagsString !== \"string\") {\n return;\n }\n const tags = tagsString.split(\" \");\n tags.forEach(function (tag) {\n Tags._AddTagTo(obj, tag);\n });\n }\n /**\n * @internal\n */\n static _AddTagTo(obj, tag) {\n tag = tag.trim();\n if (tag === \"\" || tag === \"true\" || tag === \"false\") {\n return;\n }\n if (tag.match(/[\\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {\n return;\n }\n Tags.EnableFor(obj);\n obj._tags[tag] = true;\n }\n /**\n * Removes specific tags from a specific object\n * @param obj defines the object to use\n * @param tagsString defines the tags to remove\n */\n static RemoveTagsFrom(obj, tagsString) {\n if (!Tags.HasTags(obj)) {\n return;\n }\n const tags = tagsString.split(\" \");\n for (const t in tags) {\n Tags._RemoveTagFrom(obj, tags[t]);\n }\n }\n /**\n * @internal\n */\n static _RemoveTagFrom(obj, tag) {\n delete obj._tags[tag];\n }\n /**\n * Defines if tags hosted on an object match a given query\n * @param obj defines the object to use\n * @param tagsQuery defines the tag query\n * @returns a boolean\n */\n static MatchesQuery(obj, tagsQuery) {\n if (tagsQuery === undefined) {\n return true;\n }\n if (tagsQuery === \"\") {\n return Tags.HasTags(obj);\n }\n return AndOrNotEvaluator.Eval(tagsQuery, (r) => Tags.HasTags(obj) && obj._tags[r]);\n }\n}\n//# sourceMappingURL=tags.js.map","import { IsWindowObjectExist } from \"./domManagement.js\";\n/**\n * Class used to provide helper for timing\n */\nexport class TimingTools {\n /**\n * Polyfill for setImmediate\n * @param action defines the action to execute after the current execution block\n */\n static SetImmediate(action) {\n if (IsWindowObjectExist() && window.setImmediate) {\n window.setImmediate(action);\n }\n else {\n setTimeout(action, 1);\n }\n }\n}\n//# sourceMappingURL=timingTools.js.map","import { Observable } from \"./observable.js\";\nimport { GetDOMTextContent, IsNavigatorAvailable, IsWindowObjectExist } from \"./domManagement.js\";\nimport { Logger } from \"./logger.js\";\nimport { DeepCopier } from \"./deepCopier.js\";\nimport { PrecisionDate } from \"./precisionDate.js\";\nimport { _WarnImport } from \"./devTools.js\";\nimport { WebRequest } from \"./webRequest.js\";\nimport { EngineStore } from \"../Engines/engineStore.js\";\nimport { FileToolsOptions, DecodeBase64UrlToBinary, IsBase64DataUrl, LoadFile as FileToolsLoadFile, LoadImage as FileToolLoadImage, ReadFile as FileToolsReadFile, SetCorsBehavior, } from \"./fileTools.js\";\nimport { TimingTools } from \"./timingTools.js\";\nimport { InstantiationTools } from \"./instantiationTools.js\";\nimport { RandomGUID } from \"./guid.js\";\n/**\n * Class containing a set of static utilities functions\n */\nexport class Tools {\n /**\n * Gets or sets the base URL to use to load assets\n */\n static get BaseUrl() {\n return FileToolsOptions.BaseUrl;\n }\n static set BaseUrl(value) {\n FileToolsOptions.BaseUrl = value;\n }\n /**\n * Gets or sets the retry strategy to apply when an error happens while loading an asset\n */\n static get DefaultRetryStrategy() {\n return FileToolsOptions.DefaultRetryStrategy;\n }\n static set DefaultRetryStrategy(strategy) {\n FileToolsOptions.DefaultRetryStrategy = strategy;\n }\n /**\n * Default behaviour for cors in the application.\n * It can be a string if the expected behavior is identical in the entire app.\n * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)\n */\n static get CorsBehavior() {\n return FileToolsOptions.CorsBehavior;\n }\n static set CorsBehavior(value) {\n FileToolsOptions.CorsBehavior = value;\n }\n /**\n * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded\n * @ignorenaming\n */\n static get UseFallbackTexture() {\n return EngineStore.UseFallbackTexture;\n }\n static set UseFallbackTexture(value) {\n EngineStore.UseFallbackTexture = value;\n }\n /**\n * Use this object to register external classes like custom textures or material\n * to allow the loaders to instantiate them\n */\n static get RegisteredExternalClasses() {\n return InstantiationTools.RegisteredExternalClasses;\n }\n static set RegisteredExternalClasses(classes) {\n InstantiationTools.RegisteredExternalClasses = classes;\n }\n /**\n * Texture content used if a texture cannot loaded\n * @ignorenaming\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static get fallbackTexture() {\n return EngineStore.FallbackTexture;\n }\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static set fallbackTexture(value) {\n EngineStore.FallbackTexture = value;\n }\n /**\n * Read the content of a byte array at a specified coordinates (taking in account wrapping)\n * @param u defines the coordinate on X axis\n * @param v defines the coordinate on Y axis\n * @param width defines the width of the source data\n * @param height defines the height of the source data\n * @param pixels defines the source byte array\n * @param color defines the output color\n */\n static FetchToRef(u, v, width, height, pixels, color) {\n const wrappedU = (Math.abs(u) * width) % width | 0;\n const wrappedV = (Math.abs(v) * height) % height | 0;\n const position = (wrappedU + wrappedV * width) * 4;\n color.r = pixels[position] / 255;\n color.g = pixels[position + 1] / 255;\n color.b = pixels[position + 2] / 255;\n color.a = pixels[position + 3] / 255;\n }\n /**\n * Interpolates between a and b via alpha\n * @param a The lower value (returned when alpha = 0)\n * @param b The upper value (returned when alpha = 1)\n * @param alpha The interpolation-factor\n * @returns The mixed value\n */\n static Mix(a, b, alpha) {\n return a * (1 - alpha) + b * alpha;\n }\n /**\n * Tries to instantiate a new object from a given class name\n * @param className defines the class name to instantiate\n * @returns the new object or null if the system was not able to do the instantiation\n */\n static Instantiate(className) {\n return InstantiationTools.Instantiate(className);\n }\n /**\n * Polyfill for setImmediate\n * @param action defines the action to execute after the current execution block\n */\n static SetImmediate(action) {\n TimingTools.SetImmediate(action);\n }\n /**\n * Function indicating if a number is an exponent of 2\n * @param value defines the value to test\n * @returns true if the value is an exponent of 2\n */\n static IsExponentOfTwo(value) {\n let count = 1;\n do {\n count *= 2;\n } while (count < value);\n return count === value;\n }\n /**\n * Returns the nearest 32-bit single precision float representation of a Number\n * @param value A Number. If the parameter is of a different type, it will get converted\n * to a number or to NaN if it cannot be converted\n * @returns number\n */\n static FloatRound(value) {\n if (Math.fround) {\n return Math.fround(value);\n }\n return (Tools._TmpFloatArray[0] = value), Tools._TmpFloatArray[0];\n }\n /**\n * Extracts the filename from a path\n * @param path defines the path to use\n * @returns the filename\n */\n static GetFilename(path) {\n const index = path.lastIndexOf(\"/\");\n if (index < 0) {\n return path;\n }\n return path.substring(index + 1);\n }\n /**\n * Extracts the \"folder\" part of a path (everything before the filename).\n * @param uri The URI to extract the info from\n * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present\n * @returns The \"folder\" part of the path\n */\n static GetFolderPath(uri, returnUnchangedIfNoSlash = false) {\n const index = uri.lastIndexOf(\"/\");\n if (index < 0) {\n if (returnUnchangedIfNoSlash) {\n return uri;\n }\n return \"\";\n }\n return uri.substring(0, index + 1);\n }\n /**\n * Convert an angle in radians to degrees\n * @param angle defines the angle to convert\n * @returns the angle in degrees\n */\n static ToDegrees(angle) {\n return (angle * 180) / Math.PI;\n }\n /**\n * Convert an angle in degrees to radians\n * @param angle defines the angle to convert\n * @returns the angle in radians\n */\n static ToRadians(angle) {\n return (angle * Math.PI) / 180;\n }\n /**\n * Smooth angle changes (kind of low-pass filter), in particular for device orientation \"shaking\"\n * Use trigonometric functions to avoid discontinuity (0/360, -180/180)\n * @param previousAngle defines last angle value, in degrees\n * @param newAngle defines new angle value, in degrees\n * @param smoothFactor defines smoothing sensitivity; min 0: no smoothing, max 1: new data ignored\n * @returns the angle in degrees\n */\n static SmoothAngleChange(previousAngle, newAngle, smoothFactor = 0.9) {\n const previousAngleRad = this.ToRadians(previousAngle);\n const newAngleRad = this.ToRadians(newAngle);\n return this.ToDegrees(Math.atan2((1 - smoothFactor) * Math.sin(newAngleRad) + smoothFactor * Math.sin(previousAngleRad), (1 - smoothFactor) * Math.cos(newAngleRad) + smoothFactor * Math.cos(previousAngleRad)));\n }\n /**\n * Returns an array if obj is not an array\n * @param obj defines the object to evaluate as an array\n * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined\n * @returns either obj directly if obj is an array or a new array containing obj\n */\n static MakeArray(obj, allowsNullUndefined) {\n if (allowsNullUndefined !== true && (obj === undefined || obj == null)) {\n return null;\n }\n return Array.isArray(obj) ? obj : [obj];\n }\n /**\n * Gets the pointer prefix to use\n * @param engine defines the engine we are finding the prefix for\n * @returns \"pointer\" if touch is enabled. Else returns \"mouse\"\n */\n static GetPointerPrefix(engine) {\n let eventPrefix = \"pointer\";\n // Check if pointer events are supported\n if (IsWindowObjectExist() && !window.PointerEvent) {\n eventPrefix = \"mouse\";\n }\n // Special Fallback MacOS Safari...\n if (engine._badDesktopOS &&\n !engine._badOS &&\n // And not ipad pros who claim to be macs...\n !(document && \"ontouchend\" in document)) {\n eventPrefix = \"mouse\";\n }\n return eventPrefix;\n }\n /**\n * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.\n * @param url define the url we are trying\n * @param element define the dom element where to configure the cors policy\n * @param element.crossOrigin\n */\n static SetCorsBehavior(url, element) {\n SetCorsBehavior(url, element);\n }\n /**\n * Sets the referrerPolicy behavior on a dom element.\n * @param referrerPolicy define the referrer policy to use\n * @param element define the dom element where to configure the referrer policy\n * @param element.referrerPolicy\n */\n static SetReferrerPolicyBehavior(referrerPolicy, element) {\n element.referrerPolicy = referrerPolicy;\n }\n // External files\n /**\n * Removes unwanted characters from an url\n * @param url defines the url to clean\n * @returns the cleaned url\n */\n static CleanUrl(url) {\n url = url.replace(/#/gm, \"%23\");\n return url;\n }\n /**\n * Gets or sets a function used to pre-process url before using them to load assets\n */\n static get PreprocessUrl() {\n return FileToolsOptions.PreprocessUrl;\n }\n static set PreprocessUrl(processor) {\n FileToolsOptions.PreprocessUrl = processor;\n }\n /**\n * Loads an image as an HTMLImageElement.\n * @param input url string, ArrayBuffer, or Blob to load\n * @param onLoad callback called when the image successfully loads\n * @param onError callback called when the image fails to load\n * @param offlineProvider offline provider for caching\n * @param mimeType optional mime type\n * @param imageBitmapOptions optional the options to use when creating an ImageBitmap\n * @returns the HTMLImageElement of the loaded image\n */\n static LoadImage(input, onLoad, onError, offlineProvider, mimeType, imageBitmapOptions) {\n return FileToolLoadImage(input, onLoad, onError, offlineProvider, mimeType, imageBitmapOptions);\n }\n /**\n * Loads a file from a url\n * @param url url string, ArrayBuffer, or Blob to load\n * @param onSuccess callback called when the file successfully loads\n * @param onProgress callback called while file is loading (if the server supports this mode)\n * @param offlineProvider defines the offline provider for caching\n * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer\n * @param onError callback called when the file fails to load\n * @returns a file request object\n */\n static LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) {\n return FileToolsLoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError);\n }\n /**\n * Loads a file from a url\n * @param url the file url to load\n * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer\n * @returns a promise containing an ArrayBuffer corresponding to the loaded file\n */\n static LoadFileAsync(url, useArrayBuffer = true) {\n return new Promise((resolve, reject) => {\n FileToolsLoadFile(url, (data) => {\n resolve(data);\n }, undefined, undefined, useArrayBuffer, (request, exception) => {\n reject(exception);\n });\n });\n }\n /**\n * Load a script (identified by an url). When the url returns, the\n * content of this file is added into a new script element, attached to the DOM (body element)\n * @param scriptUrl defines the url of the script to laod\n * @param onSuccess defines the callback called when the script is loaded\n * @param onError defines the callback to call if an error occurs\n * @param scriptId defines the id of the script element\n */\n static LoadScript(scriptUrl, onSuccess, onError, scriptId) {\n if (typeof importScripts === \"function\") {\n try {\n importScripts(scriptUrl);\n onSuccess();\n }\n catch (e) {\n onError === null || onError === void 0 ? void 0 : onError(`Unable to load script '${scriptUrl}' in worker`, e);\n }\n return;\n }\n else if (!IsWindowObjectExist()) {\n onError === null || onError === void 0 ? void 0 : onError(`Cannot load script '${scriptUrl}' outside of a window or a worker`);\n return;\n }\n const head = document.getElementsByTagName(\"head\")[0];\n const script = document.createElement(\"script\");\n script.setAttribute(\"type\", \"text/javascript\");\n script.setAttribute(\"src\", scriptUrl);\n if (scriptId) {\n script.id = scriptId;\n }\n script.onload = () => {\n if (onSuccess) {\n onSuccess();\n }\n };\n script.onerror = (e) => {\n if (onError) {\n onError(`Unable to load script '${scriptUrl}'`, e);\n }\n };\n head.appendChild(script);\n }\n /**\n * Load an asynchronous script (identified by an url). When the url returns, the\n * content of this file is added into a new script element, attached to the DOM (body element)\n * @param scriptUrl defines the url of the script to laod\n * @returns a promise request object\n */\n static LoadScriptAsync(scriptUrl) {\n return new Promise((resolve, reject) => {\n this.LoadScript(scriptUrl, () => {\n resolve();\n }, (message, exception) => {\n reject(exception || new Error(message));\n });\n });\n }\n /**\n * Loads a file from a blob\n * @param fileToLoad defines the blob to use\n * @param callback defines the callback to call when data is loaded\n * @param progressCallback defines the callback to call during loading process\n * @returns a file request object\n */\n static ReadFileAsDataURL(fileToLoad, callback, progressCallback) {\n const reader = new FileReader();\n const request = {\n onCompleteObservable: new Observable(),\n abort: () => reader.abort(),\n };\n reader.onloadend = () => {\n request.onCompleteObservable.notifyObservers(request);\n };\n reader.onload = (e) => {\n //target doesn't have result from ts 1.3\n callback(e.target[\"result\"]);\n };\n reader.onprogress = progressCallback;\n reader.readAsDataURL(fileToLoad);\n return request;\n }\n /**\n * Reads a file from a File object\n * @param file defines the file to load\n * @param onSuccess defines the callback to call when data is loaded\n * @param onProgress defines the callback to call during loading process\n * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer\n * @param onError defines the callback to call when an error occurs\n * @returns a file request object\n */\n static ReadFile(file, onSuccess, onProgress, useArrayBuffer, onError) {\n return FileToolsReadFile(file, onSuccess, onProgress, useArrayBuffer, onError);\n }\n /**\n * Creates a data url from a given string content\n * @param content defines the content to convert\n * @returns the new data url link\n */\n static FileAsURL(content) {\n const fileBlob = new Blob([content]);\n const url = window.URL;\n const link = url.createObjectURL(fileBlob);\n return link;\n }\n /**\n * Format the given number to a specific decimal format\n * @param value defines the number to format\n * @param decimals defines the number of decimals to use\n * @returns the formatted string\n */\n static Format(value, decimals = 2) {\n return value.toFixed(decimals);\n }\n /**\n * Tries to copy an object by duplicating every property\n * @param source defines the source object\n * @param destination defines the target object\n * @param doNotCopyList defines a list of properties to avoid\n * @param mustCopyList defines a list of properties to copy (even if they start with _)\n */\n static DeepCopy(source, destination, doNotCopyList, mustCopyList) {\n DeepCopier.DeepCopy(source, destination, doNotCopyList, mustCopyList);\n }\n /**\n * Gets a boolean indicating if the given object has no own property\n * @param obj defines the object to test\n * @returns true if object has no own property\n */\n static IsEmpty(obj) {\n for (const i in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, i)) {\n return false;\n }\n }\n return true;\n }\n /**\n * Function used to register events at window level\n * @param windowElement defines the Window object to use\n * @param events defines the events to register\n */\n static RegisterTopRootEvents(windowElement, events) {\n for (let index = 0; index < events.length; index++) {\n const event = events[index];\n windowElement.addEventListener(event.name, event.handler, false);\n try {\n if (window.parent) {\n window.parent.addEventListener(event.name, event.handler, false);\n }\n }\n catch (e) {\n // Silently fails...\n }\n }\n }\n /**\n * Function used to unregister events from window level\n * @param windowElement defines the Window object to use\n * @param events defines the events to unregister\n */\n static UnregisterTopRootEvents(windowElement, events) {\n for (let index = 0; index < events.length; index++) {\n const event = events[index];\n windowElement.removeEventListener(event.name, event.handler);\n try {\n if (windowElement.parent) {\n windowElement.parent.removeEventListener(event.name, event.handler);\n }\n }\n catch (e) {\n // Silently fails...\n }\n }\n }\n /**\n * Dumps the current bound framebuffer\n * @param width defines the rendering width\n * @param height defines the rendering height\n * @param engine defines the hosting engine\n * @param successCallback defines the callback triggered once the data are available\n * @param mimeType defines the mime type of the result\n * @param fileName defines the filename to download. If present, the result will automatically be downloaded\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n * @returns a void promise\n */\n static async DumpFramebuffer(width, height, engine, successCallback, mimeType = \"image/png\", fileName, quality) {\n throw _WarnImport(\"DumpTools\");\n }\n /**\n * Dumps an array buffer\n * @param width defines the rendering width\n * @param height defines the rendering height\n * @param data the data array\n * @param successCallback defines the callback triggered once the data are available\n * @param mimeType defines the mime type of the result\n * @param fileName defines the filename to download. If present, the result will automatically be downloaded\n * @param invertY true to invert the picture in the Y dimension\n * @param toArrayBuffer true to convert the data to an ArrayBuffer (encoded as `mimeType`) instead of a base64 string\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n */\n static DumpData(width, height, data, successCallback, mimeType = \"image/png\", fileName, invertY = false, toArrayBuffer = false, quality) {\n throw _WarnImport(\"DumpTools\");\n }\n /**\n * Dumps an array buffer\n * @param width defines the rendering width\n * @param height defines the rendering height\n * @param data the data array\n * @param mimeType defines the mime type of the result\n * @param fileName defines the filename to download. If present, the result will automatically be downloaded\n * @param invertY true to invert the picture in the Y dimension\n * @param toArrayBuffer true to convert the data to an ArrayBuffer (encoded as `mimeType`) instead of a base64 string\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n * @returns a promise that resolve to the final data\n */\n static DumpDataAsync(width, height, data, mimeType = \"image/png\", fileName, invertY = false, toArrayBuffer = false, quality) {\n throw _WarnImport(\"DumpTools\");\n }\n static _IsOffScreenCanvas(canvas) {\n return canvas.convertToBlob !== undefined;\n }\n /**\n * Converts the canvas data to blob.\n * This acts as a polyfill for browsers not supporting the to blob function.\n * @param canvas Defines the canvas to extract the data from (can be an offscreen canvas)\n * @param successCallback Defines the callback triggered once the data are available\n * @param mimeType Defines the mime type of the result\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n */\n static ToBlob(canvas, successCallback, mimeType = \"image/png\", quality) {\n // We need HTMLCanvasElement.toBlob for HD screenshots\n if (!Tools._IsOffScreenCanvas(canvas) && !canvas.toBlob) {\n // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)\n canvas.toBlob = function (callback, type, quality) {\n setTimeout(() => {\n const binStr = atob(this.toDataURL(type, quality).split(\",\")[1]), len = binStr.length, arr = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n arr[i] = binStr.charCodeAt(i);\n }\n callback(new Blob([arr]));\n });\n };\n }\n if (Tools._IsOffScreenCanvas(canvas)) {\n canvas\n .convertToBlob({\n type: mimeType,\n quality,\n })\n .then((blob) => successCallback(blob));\n }\n else {\n canvas.toBlob(function (blob) {\n successCallback(blob);\n }, mimeType, quality);\n }\n }\n /**\n * Download a Blob object\n * @param blob the Blob object\n * @param fileName the file name to download\n * @returns\n */\n static DownloadBlob(blob, fileName) {\n //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.\n if (\"download\" in document.createElement(\"a\")) {\n if (!fileName) {\n const date = new Date();\n const stringDate = (date.getFullYear() + \"-\" + (date.getMonth() + 1)).slice(2) + \"-\" + date.getDate() + \"_\" + date.getHours() + \"-\" + (\"0\" + date.getMinutes()).slice(-2);\n fileName = \"screenshot_\" + stringDate + \".png\";\n }\n Tools.Download(blob, fileName);\n }\n else {\n if (blob && typeof URL !== \"undefined\") {\n const url = URL.createObjectURL(blob);\n const newWindow = window.open(\"\");\n if (!newWindow) {\n return;\n }\n const img = newWindow.document.createElement(\"img\");\n img.onload = function () {\n // no longer need to read the blob so it's revoked\n URL.revokeObjectURL(url);\n };\n img.src = url;\n newWindow.document.body.appendChild(img);\n }\n }\n }\n /**\n * Encodes the canvas data to base 64, or automatically downloads the result if `fileName` is defined.\n * @param canvas The canvas to get the data from, which can be an offscreen canvas.\n * @param successCallback The callback which is triggered once the data is available. If `fileName` is defined, the callback will be invoked after the download occurs, and the `data` argument will be an empty string.\n * @param mimeType The mime type of the result.\n * @param fileName The name of the file to download. If defined, the result will automatically be downloaded. If not defined, and `successCallback` is also not defined, the result will automatically be downloaded with an auto-generated file name.\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n */\n static EncodeScreenshotCanvasData(canvas, successCallback, mimeType = \"image/png\", fileName, quality) {\n if (typeof fileName === \"string\" || !successCallback) {\n this.ToBlob(canvas, function (blob) {\n if (blob) {\n Tools.DownloadBlob(blob, fileName);\n }\n if (successCallback) {\n successCallback(\"\");\n }\n }, mimeType, quality);\n }\n else if (successCallback) {\n if (Tools._IsOffScreenCanvas(canvas)) {\n canvas\n .convertToBlob({\n type: mimeType,\n quality,\n })\n .then((blob) => {\n const reader = new FileReader();\n reader.readAsDataURL(blob);\n reader.onloadend = () => {\n const base64data = reader.result;\n successCallback(base64data);\n };\n });\n return;\n }\n const base64Image = canvas.toDataURL(mimeType, quality);\n successCallback(base64Image);\n }\n }\n /**\n * Downloads a blob in the browser\n * @param blob defines the blob to download\n * @param fileName defines the name of the downloaded file\n */\n static Download(blob, fileName) {\n if (typeof URL === \"undefined\") {\n return;\n }\n const url = window.URL.createObjectURL(blob);\n const a = document.createElement(\"a\");\n document.body.appendChild(a);\n a.style.display = \"none\";\n a.href = url;\n a.download = fileName;\n a.addEventListener(\"click\", () => {\n if (a.parentElement) {\n a.parentElement.removeChild(a);\n }\n });\n a.click();\n window.URL.revokeObjectURL(url);\n }\n /**\n * Will return the right value of the noPreventDefault variable\n * Needed to keep backwards compatibility to the old API.\n *\n * @param args arguments passed to the attachControl function\n * @returns the correct value for noPreventDefault\n */\n static BackCompatCameraNoPreventDefault(args) {\n // is it used correctly?\n if (typeof args[0] === \"boolean\") {\n return args[0];\n }\n else if (typeof args[1] === \"boolean\") {\n return args[1];\n }\n return false;\n }\n /**\n * Captures a screenshot of the current rendering\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine defines the rendering engine\n * @param camera defines the source camera\n * @param size This parameter can be set to a single number or to an object with the\n * following (optional) properties: precision, width, height. If a single number is passed,\n * it will be used for both width and height. If an object is passed, the screenshot size\n * will be derived from the parameters. The precision property is a multiplier allowing\n * rendering at a higher or lower resolution\n * @param successCallback defines the callback receives a single parameter which contains the\n * screenshot as a string of base64-encoded characters. This string can be assigned to the\n * src parameter of an to display it\n * @param mimeType defines the MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param forceDownload force the system to download the image even if a successCallback is provided\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n static CreateScreenshot(engine, camera, size, successCallback, mimeType = \"image/png\", forceDownload = false, quality) {\n throw _WarnImport(\"ScreenshotTools\");\n }\n /**\n * Captures a screenshot of the current rendering\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine defines the rendering engine\n * @param camera defines the source camera\n * @param size This parameter can be set to a single number or to an object with the\n * following (optional) properties: precision, width, height. If a single number is passed,\n * it will be used for both width and height. If an object is passed, the screenshot size\n * will be derived from the parameters. The precision property is a multiplier allowing\n * rendering at a higher or lower resolution\n * @param mimeType defines the MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n * @returns screenshot as a string of base64-encoded characters. This string can be assigned\n * to the src parameter of an to display it\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n static CreateScreenshotAsync(engine, camera, size, mimeType = \"image/png\", quality) {\n throw _WarnImport(\"ScreenshotTools\");\n }\n /**\n * Generates an image screenshot from the specified camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine The engine to use for rendering\n * @param camera The camera to use for rendering\n * @param size This parameter can be set to a single number or to an object with the\n * following (optional) properties: precision, width, height. If a single number is passed,\n * it will be used for both width and height. If an object is passed, the screenshot size\n * will be derived from the parameters. The precision property is a multiplier allowing\n * rendering at a higher or lower resolution\n * @param successCallback The callback receives a single parameter which contains the\n * screenshot as a string of base64-encoded characters. This string can be assigned to the\n * src parameter of an to display it\n * @param mimeType The MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param samples Texture samples (default: 1)\n * @param antialiasing Whether antialiasing should be turned on or not (default: false)\n * @param fileName A name for for the downloaded file.\n * @param renderSprites Whether the sprites should be rendered or not (default: false)\n * @param enableStencilBuffer Whether the stencil buffer should be enabled or not (default: false)\n * @param useLayerMask if the camera's layer mask should be used to filter what should be rendered (default: true)\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n static CreateScreenshotUsingRenderTarget(engine, camera, size, successCallback, mimeType = \"image/png\", samples = 1, antialiasing = false, fileName, renderSprites = false, enableStencilBuffer = false, useLayerMask = true, quality) {\n throw _WarnImport(\"ScreenshotTools\");\n }\n /**\n * Generates an image screenshot from the specified camera.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG\n * @param engine The engine to use for rendering\n * @param camera The camera to use for rendering\n * @param size This parameter can be set to a single number or to an object with the\n * following (optional) properties: precision, width, height. If a single number is passed,\n * it will be used for both width and height. If an object is passed, the screenshot size\n * will be derived from the parameters. The precision property is a multiplier allowing\n * rendering at a higher or lower resolution\n * @param mimeType The MIME type of the screenshot image (default: image/png).\n * Check your browser for supported MIME types\n * @param samples Texture samples (default: 1)\n * @param antialiasing Whether antialiasing should be turned on or not (default: false)\n * @param fileName A name for for the downloaded file.\n * @returns screenshot as a string of base64-encoded characters. This string can be assigned\n * @param renderSprites Whether the sprites should be rendered or not (default: false)\n * @param enableStencilBuffer Whether the stencil buffer should be enabled or not (default: false)\n * @param useLayerMask if the camera's layer mask should be used to filter what should be rendered (default: true)\n * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter.\n * to the src parameter of an to display it\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n static CreateScreenshotUsingRenderTargetAsync(engine, camera, size, mimeType = \"image/png\", samples = 1, antialiasing = false, fileName, renderSprites = false, enableStencilBuffer = false, useLayerMask = true, quality) {\n throw _WarnImport(\"ScreenshotTools\");\n }\n /**\n * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523\n * Be aware Math.random() could cause collisions, but:\n * \"All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide\"\n * @returns a pseudo random id\n */\n static RandomId() {\n return RandomGUID();\n }\n /**\n * Test if the given uri is a base64 string\n * @deprecated Please use FileTools.IsBase64DataUrl instead.\n * @param uri The uri to test\n * @returns True if the uri is a base64 string or false otherwise\n */\n static IsBase64(uri) {\n return IsBase64DataUrl(uri);\n }\n /**\n * Decode the given base64 uri.\n * @deprecated Please use FileTools.DecodeBase64UrlToBinary instead.\n * @param uri The uri to decode\n * @returns The decoded base64 data.\n */\n static DecodeBase64(uri) {\n return DecodeBase64UrlToBinary(uri);\n }\n /**\n * Gets a value indicating the number of loading errors\n * @ignorenaming\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static get errorsCount() {\n return Logger.errorsCount;\n }\n /**\n * Log a message to the console\n * @param message defines the message to log\n */\n static Log(message) {\n Logger.Log(message);\n }\n /**\n * Write a warning message to the console\n * @param message defines the message to log\n */\n static Warn(message) {\n Logger.Warn(message);\n }\n /**\n * Write an error message to the console\n * @param message defines the message to log\n */\n static Error(message) {\n Logger.Error(message);\n }\n /**\n * Gets current log cache (list of logs)\n */\n static get LogCache() {\n return Logger.LogCache;\n }\n /**\n * Clears the log cache\n */\n static ClearLogCache() {\n Logger.ClearLogCache();\n }\n /**\n * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)\n */\n static set LogLevels(level) {\n Logger.LogLevels = level;\n }\n /**\n * Sets the current performance log level\n */\n static set PerformanceLogLevel(level) {\n if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {\n Tools.StartPerformanceCounter = Tools._StartUserMark;\n Tools.EndPerformanceCounter = Tools._EndUserMark;\n return;\n }\n if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {\n Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;\n Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;\n return;\n }\n Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;\n Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;\n }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n static _StartPerformanceCounterDisabled(counterName, condition) { }\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n static _EndPerformanceCounterDisabled(counterName, condition) { }\n static _StartUserMark(counterName, condition = true) {\n if (!Tools._Performance) {\n if (!IsWindowObjectExist()) {\n return;\n }\n Tools._Performance = window.performance;\n }\n if (!condition || !Tools._Performance.mark) {\n return;\n }\n Tools._Performance.mark(counterName + \"-Begin\");\n }\n static _EndUserMark(counterName, condition = true) {\n if (!condition || !Tools._Performance.mark) {\n return;\n }\n Tools._Performance.mark(counterName + \"-End\");\n Tools._Performance.measure(counterName, counterName + \"-Begin\", counterName + \"-End\");\n }\n static _StartPerformanceConsole(counterName, condition = true) {\n if (!condition) {\n return;\n }\n Tools._StartUserMark(counterName, condition);\n if (console.time) {\n console.time(counterName);\n }\n }\n static _EndPerformanceConsole(counterName, condition = true) {\n if (!condition) {\n return;\n }\n Tools._EndUserMark(counterName, condition);\n console.timeEnd(counterName);\n }\n /**\n * Gets either window.performance.now() if supported or Date.now() else\n */\n static get Now() {\n return PrecisionDate.Now;\n }\n /**\n * This method will return the name of the class used to create the instance of the given object.\n * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.\n * @param object the object to get the class name from\n * @param isType defines if the object is actually a type\n * @returns the name of the class, will be \"object\" for a custom data type not using the @className decorator\n */\n static GetClassName(object, isType = false) {\n let name = null;\n if (!isType && object.getClassName) {\n name = object.getClassName();\n }\n else {\n if (object instanceof Object) {\n const classObj = isType ? object : Object.getPrototypeOf(object);\n name = classObj.constructor[\"__bjsclassName__\"];\n }\n if (!name) {\n name = typeof object;\n }\n }\n return name;\n }\n /**\n * Gets the first element of an array satisfying a given predicate\n * @param array defines the array to browse\n * @param predicate defines the predicate to use\n * @returns null if not found or the element\n */\n static First(array, predicate) {\n for (const el of array) {\n if (predicate(el)) {\n return el;\n }\n }\n return null;\n }\n /**\n * This method will return the name of the full name of the class, including its owning module (if any).\n * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).\n * @param object the object to get the class name from\n * @param isType defines if the object is actually a type\n * @returns a string that can have two forms: \"moduleName.className\" if module was specified when the class' Name was registered or \"className\" if there was not module specified.\n * @ignorenaming\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static getFullClassName(object, isType = false) {\n let className = null;\n let moduleName = null;\n if (!isType && object.getClassName) {\n className = object.getClassName();\n }\n else {\n if (object instanceof Object) {\n const classObj = isType ? object : Object.getPrototypeOf(object);\n className = classObj.constructor[\"__bjsclassName__\"];\n moduleName = classObj.constructor[\"__bjsmoduleName__\"];\n }\n if (!className) {\n className = typeof object;\n }\n }\n if (!className) {\n return null;\n }\n return (moduleName != null ? moduleName + \".\" : \"\") + className;\n }\n /**\n * Returns a promise that resolves after the given amount of time.\n * @param delay Number of milliseconds to delay\n * @returns Promise that resolves after the given amount of time\n */\n static DelayAsync(delay) {\n return new Promise((resolve) => {\n setTimeout(() => {\n resolve();\n }, delay);\n });\n }\n /**\n * Utility function to detect if the current user agent is Safari\n * @returns whether or not the current user agent is safari\n */\n static IsSafari() {\n if (!IsNavigatorAvailable()) {\n return false;\n }\n return /^((?!chrome|android).)*safari/i.test(navigator.userAgent);\n }\n}\n/**\n * Enable/Disable Custom HTTP Request Headers globally.\n * default = false\n * @see CustomRequestHeaders\n */\nTools.UseCustomRequestHeaders = false;\n/**\n * Custom HTTP Request Headers to be sent with XMLHttpRequests\n * i.e. when loading files, where the server/service expects an Authorization header\n */\nTools.CustomRequestHeaders = WebRequest.CustomRequestHeaders;\nTools._TmpFloatArray = new Float32Array(1);\n/**\n * Extracts text content from a DOM element hierarchy\n * Back Compat only, please use GetDOMTextContent instead.\n */\nTools.GetDOMTextContent = GetDOMTextContent;\nTools.GetAbsoluteUrl = typeof document === \"object\"\n ? (url) => {\n const a = document.createElement(\"a\");\n a.href = url;\n return a.href;\n }\n : typeof URL === \"function\" && typeof location === \"object\"\n ? (url) => new URL(url, location.origin).href\n : () => {\n throw new Error(\"Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.\");\n };\n// Logs\n/**\n * No log\n */\nTools.NoneLogLevel = Logger.NoneLogLevel;\n/**\n * Only message logs\n */\nTools.MessageLogLevel = Logger.MessageLogLevel;\n/**\n * Only warning logs\n */\nTools.WarningLogLevel = Logger.WarningLogLevel;\n/**\n * Only error logs\n */\nTools.ErrorLogLevel = Logger.ErrorLogLevel;\n/**\n * All logs\n */\nTools.AllLogLevel = Logger.AllLogLevel;\n/**\n * Checks if the window object exists\n * Back Compat only, please use IsWindowObjectExist instead.\n */\nTools.IsWindowObjectExist = IsWindowObjectExist;\n// Performances\n/**\n * No performance log\n */\nTools.PerformanceNoneLogLevel = 0;\n/**\n * Use user marks to log performance\n */\nTools.PerformanceUserMarkLogLevel = 1;\n/**\n * Log performance to the console\n */\nTools.PerformanceConsoleLogLevel = 2;\n/**\n * Starts a performance counter\n */\nTools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;\n/**\n * Ends a specific performance counter\n */\nTools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;\n/**\n * Use this className as a decorator on a given class definition to add it a name and optionally its module.\n * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.\n * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified\n * @param name The name of the class, case should be preserved\n * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.\n */\nexport function className(name, module) {\n return (target) => {\n target[\"__bjsclassName__\"] = name;\n target[\"__bjsmoduleName__\"] = module != null ? module : null;\n };\n}\n/**\n * An implementation of a loop for asynchronous functions.\n */\nexport class AsyncLoop {\n /**\n * Constructor.\n * @param iterations the number of iterations.\n * @param func the function to run each iteration\n * @param successCallback the callback that will be called upon successful execution\n * @param offset starting offset.\n */\n constructor(\n /**\n * Defines the number of iterations for the loop\n */\n iterations, func, successCallback, offset = 0) {\n this.iterations = iterations;\n this.index = offset - 1;\n this._done = false;\n this._fn = func;\n this._successCallback = successCallback;\n }\n /**\n * Execute the next iteration. Must be called after the last iteration was finished.\n */\n executeNext() {\n if (!this._done) {\n if (this.index + 1 < this.iterations) {\n ++this.index;\n this._fn(this);\n }\n else {\n this.breakLoop();\n }\n }\n }\n /**\n * Break the loop and run the success callback.\n */\n breakLoop() {\n this._done = true;\n this._successCallback();\n }\n /**\n * Create and run an async loop.\n * @param iterations the number of iterations.\n * @param fn the function to run each iteration\n * @param successCallback the callback that will be called upon successful execution\n * @param offset starting offset.\n * @returns the created async loop object\n */\n static Run(iterations, fn, successCallback, offset = 0) {\n const loop = new AsyncLoop(iterations, fn, successCallback, offset);\n loop.executeNext();\n return loop;\n }\n /**\n * A for-loop that will run a given number of iterations synchronous and the rest async.\n * @param iterations total number of iterations\n * @param syncedIterations number of synchronous iterations in each async iteration.\n * @param fn the function to call each iteration.\n * @param callback a success call back that will be called when iterating stops.\n * @param breakFunction a break condition (optional)\n * @param timeout timeout settings for the setTimeout function. default - 0.\n * @returns the created async loop object\n */\n static SyncAsyncForLoop(iterations, syncedIterations, fn, callback, breakFunction, timeout = 0) {\n return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), (loop) => {\n if (breakFunction && breakFunction()) {\n loop.breakLoop();\n }\n else {\n setTimeout(() => {\n for (let i = 0; i < syncedIterations; ++i) {\n const iteration = loop.index * syncedIterations + i;\n if (iteration >= iterations) {\n break;\n }\n fn(iteration);\n if (breakFunction && breakFunction()) {\n loop.breakLoop();\n break;\n }\n }\n loop.executeNext();\n }, timeout);\n }\n }, callback);\n }\n}\n// Will only be define if Tools is imported freeing up some space when only engine is required\nEngineStore.FallbackTexture =\n \"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\";\n//# sourceMappingURL=tools.js.map","/** @internal */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst _RegisteredTypes = {};\n/**\n * @internal\n */\nexport function RegisterClass(className, type) {\n _RegisteredTypes[className] = type;\n}\n/**\n * @internal\n */\nexport function GetClass(fqdn) {\n return _RegisteredTypes[fqdn];\n}\n//# sourceMappingURL=typeStore.js.map","/**\n * Helper class used to generate session unique ID\n */\nexport class UniqueIdGenerator {\n /**\n * Gets an unique (relatively to the current scene) Id\n */\n static get UniqueId() {\n const result = this._UniqueIdCounter;\n this._UniqueIdCounter++;\n return result;\n }\n}\n// Statics\nUniqueIdGenerator._UniqueIdCounter = 1;\n//# sourceMappingURL=uniqueIdGenerator.js.map","/** @internal */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nfunction createXMLHttpRequest() {\n // If running in Babylon Native, then defer to the native XMLHttpRequest, which has the same public contract\n if (typeof _native !== \"undefined\" && _native.XMLHttpRequest) {\n return new _native.XMLHttpRequest();\n }\n else {\n return new XMLHttpRequest();\n }\n}\n/**\n * Extended version of XMLHttpRequest with support for customizations (headers, ...)\n */\nexport class WebRequest {\n constructor() {\n this._xhr = createXMLHttpRequest();\n this._requestURL = \"\";\n }\n _injectCustomRequestHeaders() {\n if (this._shouldSkipRequestModifications(this._requestURL)) {\n return;\n }\n for (const key in WebRequest.CustomRequestHeaders) {\n const val = WebRequest.CustomRequestHeaders[key];\n if (val) {\n this._xhr.setRequestHeader(key, val);\n }\n }\n }\n _shouldSkipRequestModifications(url) {\n return WebRequest.SkipRequestModificationForBabylonCDN && (url.includes(\"preview.babylonjs.com\") || url.includes(\"cdn.babylonjs.com\"));\n }\n /**\n * Gets or sets a function to be called when loading progress changes\n */\n get onprogress() {\n return this._xhr.onprogress;\n }\n set onprogress(value) {\n this._xhr.onprogress = value;\n }\n /**\n * Returns client's state\n */\n get readyState() {\n return this._xhr.readyState;\n }\n /**\n * Returns client's status\n */\n get status() {\n return this._xhr.status;\n }\n /**\n * Returns client's status as a text\n */\n get statusText() {\n return this._xhr.statusText;\n }\n /**\n * Returns client's response\n */\n get response() {\n return this._xhr.response;\n }\n /**\n * Returns client's response url\n */\n get responseURL() {\n return this._xhr.responseURL;\n }\n /**\n * Returns client's response as text\n */\n get responseText() {\n return this._xhr.responseText;\n }\n /**\n * Gets or sets the expected response type\n */\n get responseType() {\n return this._xhr.responseType;\n }\n set responseType(value) {\n this._xhr.responseType = value;\n }\n /**\n * Gets or sets the timeout value in milliseconds\n */\n get timeout() {\n return this._xhr.timeout;\n }\n set timeout(value) {\n this._xhr.timeout = value;\n }\n addEventListener(type, listener, options) {\n this._xhr.addEventListener(type, listener, options);\n }\n removeEventListener(type, listener, options) {\n this._xhr.removeEventListener(type, listener, options);\n }\n /**\n * Cancels any network activity\n */\n abort() {\n this._xhr.abort();\n }\n /**\n * Initiates the request. The optional argument provides the request body. The argument is ignored if request method is GET or HEAD\n * @param body defines an optional request body\n */\n send(body) {\n if (WebRequest.CustomRequestHeaders) {\n this._injectCustomRequestHeaders();\n }\n this._xhr.send(body);\n }\n /**\n * Sets the request method, request URL\n * @param method defines the method to use (GET, POST, etc..)\n * @param url defines the url to connect with\n */\n open(method, url) {\n for (const update of WebRequest.CustomRequestModifiers) {\n if (this._shouldSkipRequestModifications(url)) {\n return;\n }\n update(this._xhr, url);\n }\n // Clean url\n url = url.replace(\"file:http:\", \"http:\");\n url = url.replace(\"file:https:\", \"https:\");\n this._requestURL = url;\n return this._xhr.open(method, url, true);\n }\n /**\n * Sets the value of a request header.\n * @param name The name of the header whose value is to be set\n * @param value The value to set as the body of the header\n */\n setRequestHeader(name, value) {\n this._xhr.setRequestHeader(name, value);\n }\n /**\n * Get the string containing the text of a particular header's value.\n * @param name The name of the header\n * @returns The string containing the text of the given header name\n */\n getResponseHeader(name) {\n return this._xhr.getResponseHeader(name);\n }\n}\n/**\n * Custom HTTP Request Headers to be sent with XMLHttpRequests\n * i.e. when loading files, where the server/service expects an Authorization header\n */\nWebRequest.CustomRequestHeaders = {};\n/**\n * Add callback functions in this array to update all the requests before they get sent to the network\n */\nWebRequest.CustomRequestModifiers = new Array();\nWebRequest.SkipRequestModificationForBabylonCDN = true;\n//# sourceMappingURL=webRequest.js.map","import { VertexBuffer } from \"../Buffers/buffer.js\";\n\n/**\n * PostProcessManager is used to manage one or more post processes or post process pipelines\n * See https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses\n */\nexport class PostProcessManager {\n /**\n * Creates a new instance PostProcess\n * @param scene The scene that the post process is associated with.\n */\n constructor(scene) {\n this._vertexBuffers = {};\n this._scene = scene;\n }\n _prepareBuffers() {\n if (this._vertexBuffers[VertexBuffer.PositionKind]) {\n return;\n }\n // VBO\n const vertices = [];\n vertices.push(1, 1);\n vertices.push(-1, 1);\n vertices.push(-1, -1);\n vertices.push(1, -1);\n this._vertexBuffers[VertexBuffer.PositionKind] = new VertexBuffer(this._scene.getEngine(), vertices, VertexBuffer.PositionKind, false, false, 2);\n this._buildIndexBuffer();\n }\n _buildIndexBuffer() {\n // Indices\n const indices = [];\n indices.push(0);\n indices.push(1);\n indices.push(2);\n indices.push(0);\n indices.push(2);\n indices.push(3);\n this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);\n }\n /**\n * Rebuilds the vertex buffers of the manager.\n * @internal\n */\n _rebuild() {\n const vb = this._vertexBuffers[VertexBuffer.PositionKind];\n if (!vb) {\n return;\n }\n vb._rebuild();\n this._buildIndexBuffer();\n }\n // Methods\n /**\n * Prepares a frame to be run through a post process.\n * @param sourceTexture The input texture to the post processes. (default: null)\n * @param postProcesses An array of post processes to be run. (default: null)\n * @returns True if the post processes were able to be run.\n * @internal\n */\n _prepareFrame(sourceTexture = null, postProcesses = null) {\n const camera = this._scene.activeCamera;\n if (!camera) {\n return false;\n }\n postProcesses = postProcesses || camera._postProcesses.filter((pp) => {\n return pp != null;\n });\n if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {\n return false;\n }\n postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);\n return true;\n }\n /**\n * Manually render a set of post processes to a texture.\n * Please note, the frame buffer won't be unbound after the call in case you have more render to do.\n * @param postProcesses An array of post processes to be run.\n * @param targetTexture The render target wrapper to render to.\n * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight\n * @param faceIndex defines the face to render to if a cubemap is defined as the target\n * @param lodLevel defines which lod of the texture to render to\n * @param doNotBindFrambuffer If set to true, assumes that the framebuffer has been bound previously\n */\n directRender(postProcesses, targetTexture = null, forceFullscreenViewport = false, faceIndex = 0, lodLevel = 0, doNotBindFrambuffer = false) {\n var _a;\n const engine = this._scene.getEngine();\n for (let index = 0; index < postProcesses.length; index++) {\n if (index < postProcesses.length - 1) {\n postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture === null || targetTexture === void 0 ? void 0 : targetTexture.texture);\n }\n else {\n if (targetTexture) {\n engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, lodLevel);\n }\n else if (!doNotBindFrambuffer) {\n engine.restoreDefaultFramebuffer();\n }\n (_a = engine._debugInsertMarker) === null || _a === void 0 ? void 0 : _a.call(engine, `post process ${postProcesses[index].name} output`);\n }\n const pp = postProcesses[index];\n const effect = pp.apply();\n if (effect) {\n pp.onBeforeRenderObservable.notifyObservers(effect);\n // VBOs\n this._prepareBuffers();\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);\n // Draw order\n engine.drawElementsType(0, 0, 6);\n pp.onAfterRenderObservable.notifyObservers(effect);\n }\n }\n // Restore depth buffer\n engine.setDepthBuffer(true);\n engine.setDepthWrite(true);\n }\n /**\n * Finalize the result of the output of the postprocesses.\n * @param doNotPresent If true the result will not be displayed to the screen.\n * @param targetTexture The render target wrapper to render to.\n * @param faceIndex The index of the face to bind the target texture to.\n * @param postProcesses The array of post processes to render.\n * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)\n * @internal\n */\n _finalizeFrame(doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport = false) {\n var _a;\n const camera = this._scene.activeCamera;\n if (!camera) {\n return;\n }\n postProcesses = postProcesses || camera._postProcesses.filter((pp) => {\n return pp != null;\n });\n if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {\n return;\n }\n const engine = this._scene.getEngine();\n for (let index = 0, len = postProcesses.length; index < len; index++) {\n const pp = postProcesses[index];\n if (index < len - 1) {\n pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture === null || targetTexture === void 0 ? void 0 : targetTexture.texture);\n }\n else {\n if (targetTexture) {\n engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);\n pp._outputTexture = targetTexture;\n }\n else {\n engine.restoreDefaultFramebuffer();\n pp._outputTexture = null;\n }\n (_a = engine._debugInsertMarker) === null || _a === void 0 ? void 0 : _a.call(engine, `post process ${postProcesses[index].name} output`);\n }\n if (doNotPresent) {\n break;\n }\n const effect = pp.apply();\n if (effect) {\n pp.onBeforeRenderObservable.notifyObservers(effect);\n // VBOs\n this._prepareBuffers();\n engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);\n // Draw order\n engine.drawElementsType(0, 0, 6);\n pp.onAfterRenderObservable.notifyObservers(effect);\n }\n }\n // Restore states\n engine.setDepthBuffer(true);\n engine.setDepthWrite(true);\n engine.setAlphaMode(0);\n }\n /**\n * Disposes of the post process manager.\n */\n dispose() {\n const buffer = this._vertexBuffers[VertexBuffer.PositionKind];\n if (buffer) {\n buffer.dispose();\n this._vertexBuffers[VertexBuffer.PositionKind] = null;\n }\n if (this._indexBuffer) {\n this._scene.getEngine()._releaseBuffer(this._indexBuffer);\n this._indexBuffer = null;\n }\n }\n}\n//# sourceMappingURL=postProcessManager.js.map","import { SmartArray, SmartArrayNoDuplicate } from \"../Misc/smartArray.js\";\nimport { Vector3 } from \"../Maths/math.vector.js\";\n\n/**\n * This represents the object necessary to create a rendering group.\n * This is exclusively used and created by the rendering manager.\n * To modify the behavior, you use the available helpers in your scene or meshes.\n * @internal\n */\nexport class RenderingGroup {\n /**\n * Set the opaque sort comparison function.\n * If null the sub meshes will be render in the order they were created\n */\n set opaqueSortCompareFn(value) {\n if (value) {\n this._opaqueSortCompareFn = value;\n }\n else {\n this._opaqueSortCompareFn = RenderingGroup.PainterSortCompare;\n }\n this._renderOpaque = this._renderOpaqueSorted;\n }\n /**\n * Set the alpha test sort comparison function.\n * If null the sub meshes will be render in the order they were created\n */\n set alphaTestSortCompareFn(value) {\n if (value) {\n this._alphaTestSortCompareFn = value;\n }\n else {\n this._alphaTestSortCompareFn = RenderingGroup.PainterSortCompare;\n }\n this._renderAlphaTest = this._renderAlphaTestSorted;\n }\n /**\n * Set the transparent sort comparison function.\n * If null the sub meshes will be render in the order they were created\n */\n set transparentSortCompareFn(value) {\n if (value) {\n this._transparentSortCompareFn = value;\n }\n else {\n this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;\n }\n this._renderTransparent = this._renderTransparentSorted;\n }\n /**\n * Creates a new rendering group.\n * @param index The rendering group index\n * @param scene\n * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied\n * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied\n * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied\n */\n constructor(index, scene, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) {\n this.index = index;\n this._opaqueSubMeshes = new SmartArray(256);\n this._transparentSubMeshes = new SmartArray(256);\n this._alphaTestSubMeshes = new SmartArray(256);\n this._depthOnlySubMeshes = new SmartArray(256);\n this._particleSystems = new SmartArray(256);\n this._spriteManagers = new SmartArray(256);\n /** @internal */\n this._empty = true;\n /** @internal */\n this._edgesRenderers = new SmartArrayNoDuplicate(16);\n this._scene = scene;\n this.opaqueSortCompareFn = opaqueSortCompareFn;\n this.alphaTestSortCompareFn = alphaTestSortCompareFn;\n this.transparentSortCompareFn = transparentSortCompareFn;\n }\n /**\n * Render all the sub meshes contained in the group.\n * @param customRenderFunction Used to override the default render behaviour of the group.\n * @param renderSprites\n * @param renderParticles\n * @param activeMeshes\n * @returns true if rendered some submeshes.\n */\n render(customRenderFunction, renderSprites, renderParticles, activeMeshes) {\n if (customRenderFunction) {\n customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);\n return;\n }\n const engine = this._scene.getEngine();\n // Depth only\n if (this._depthOnlySubMeshes.length !== 0) {\n engine.setColorWrite(false);\n this._renderAlphaTest(this._depthOnlySubMeshes);\n engine.setColorWrite(true);\n }\n // Opaque\n if (this._opaqueSubMeshes.length !== 0) {\n this._renderOpaque(this._opaqueSubMeshes);\n }\n // Alpha test\n if (this._alphaTestSubMeshes.length !== 0) {\n this._renderAlphaTest(this._alphaTestSubMeshes);\n }\n const stencilState = engine.getStencilBuffer();\n engine.setStencilBuffer(false);\n // Sprites\n if (renderSprites) {\n this._renderSprites();\n }\n // Particles\n if (renderParticles) {\n this._renderParticles(activeMeshes);\n }\n if (this.onBeforeTransparentRendering) {\n this.onBeforeTransparentRendering();\n }\n // Transparent\n if (this._transparentSubMeshes.length !== 0 || this._scene.useOrderIndependentTransparency) {\n engine.setStencilBuffer(stencilState);\n if (this._scene.useOrderIndependentTransparency) {\n const excludedMeshes = this._scene.depthPeelingRenderer.render(this._transparentSubMeshes);\n if (excludedMeshes.length) {\n // Render leftover meshes that could not be processed by depth peeling\n this._renderTransparent(excludedMeshes);\n }\n }\n else {\n this._renderTransparent(this._transparentSubMeshes);\n }\n engine.setAlphaMode(0);\n }\n // Set back stencil to false in case it changes before the edge renderer.\n engine.setStencilBuffer(false);\n // Edges\n if (this._edgesRenderers.length) {\n for (let edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {\n this._edgesRenderers.data[edgesRendererIndex].render();\n }\n engine.setAlphaMode(0);\n }\n // Restore Stencil state.\n engine.setStencilBuffer(stencilState);\n }\n /**\n * Renders the opaque submeshes in the order from the opaqueSortCompareFn.\n * @param subMeshes The submeshes to render\n */\n _renderOpaqueSorted(subMeshes) {\n return RenderingGroup._RenderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);\n }\n /**\n * Renders the opaque submeshes in the order from the alphatestSortCompareFn.\n * @param subMeshes The submeshes to render\n */\n _renderAlphaTestSorted(subMeshes) {\n return RenderingGroup._RenderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);\n }\n /**\n * Renders the opaque submeshes in the order from the transparentSortCompareFn.\n * @param subMeshes The submeshes to render\n */\n _renderTransparentSorted(subMeshes) {\n return RenderingGroup._RenderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);\n }\n /**\n * Renders the submeshes in a specified order.\n * @param subMeshes The submeshes to sort before render\n * @param sortCompareFn The comparison function use to sort\n * @param camera The camera position use to preprocess the submeshes to help sorting\n * @param transparent Specifies to activate blending if true\n */\n static _RenderSorted(subMeshes, sortCompareFn, camera, transparent) {\n let subIndex = 0;\n let subMesh;\n const cameraPosition = camera ? camera.globalPosition : RenderingGroup._ZeroVector;\n if (transparent) {\n for (; subIndex < subMeshes.length; subIndex++) {\n subMesh = subMeshes.data[subIndex];\n subMesh._alphaIndex = subMesh.getMesh().alphaIndex;\n subMesh._distanceToCamera = Vector3.Distance(subMesh.getBoundingInfo().boundingSphere.centerWorld, cameraPosition);\n }\n }\n const sortedArray = subMeshes.length === subMeshes.data.length ? subMeshes.data : subMeshes.data.slice(0, subMeshes.length);\n if (sortCompareFn) {\n sortedArray.sort(sortCompareFn);\n }\n const scene = sortedArray[0].getMesh().getScene();\n for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {\n subMesh = sortedArray[subIndex];\n if (scene._activeMeshesFrozenButKeepClipping && !subMesh.isInFrustum(scene._frustumPlanes)) {\n continue;\n }\n if (transparent) {\n const material = subMesh.getMaterial();\n if (material && material.needDepthPrePass) {\n const engine = material.getScene().getEngine();\n engine.setColorWrite(false);\n engine.setAlphaMode(0);\n subMesh.render(false);\n engine.setColorWrite(true);\n }\n }\n subMesh.render(transparent);\n }\n }\n /**\n * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)\n * are rendered back to front if in the same alpha index.\n *\n * @param a The first submesh\n * @param b The second submesh\n * @returns The result of the comparison\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static defaultTransparentSortCompare(a, b) {\n // Alpha index first\n if (a._alphaIndex > b._alphaIndex) {\n return 1;\n }\n if (a._alphaIndex < b._alphaIndex) {\n return -1;\n }\n // Then distance to camera\n return RenderingGroup.backToFrontSortCompare(a, b);\n }\n /**\n * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)\n * are rendered back to front.\n *\n * @param a The first submesh\n * @param b The second submesh\n * @returns The result of the comparison\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static backToFrontSortCompare(a, b) {\n // Then distance to camera\n if (a._distanceToCamera < b._distanceToCamera) {\n return 1;\n }\n if (a._distanceToCamera > b._distanceToCamera) {\n return -1;\n }\n return 0;\n }\n /**\n * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)\n * are rendered front to back (prevent overdraw).\n *\n * @param a The first submesh\n * @param b The second submesh\n * @returns The result of the comparison\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention\n static frontToBackSortCompare(a, b) {\n // Then distance to camera\n if (a._distanceToCamera < b._distanceToCamera) {\n return -1;\n }\n if (a._distanceToCamera > b._distanceToCamera) {\n return 1;\n }\n return 0;\n }\n /**\n * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)\n * are grouped by material then geometry.\n *\n * @param a The first submesh\n * @param b The second submesh\n * @returns The result of the comparison\n */\n static PainterSortCompare(a, b) {\n const meshA = a.getMesh();\n const meshB = b.getMesh();\n if (meshA.material && meshB.material) {\n return meshA.material.uniqueId - meshB.material.uniqueId;\n }\n return meshA.uniqueId - meshB.uniqueId;\n }\n /**\n * Resets the different lists of submeshes to prepare a new frame.\n */\n prepare() {\n this._opaqueSubMeshes.reset();\n this._transparentSubMeshes.reset();\n this._alphaTestSubMeshes.reset();\n this._depthOnlySubMeshes.reset();\n this._particleSystems.reset();\n this.prepareSprites();\n this._edgesRenderers.reset();\n this._empty = true;\n }\n /**\n * Resets the different lists of sprites to prepare a new frame.\n */\n prepareSprites() {\n this._spriteManagers.reset();\n }\n dispose() {\n this._opaqueSubMeshes.dispose();\n this._transparentSubMeshes.dispose();\n this._alphaTestSubMeshes.dispose();\n this._depthOnlySubMeshes.dispose();\n this._particleSystems.dispose();\n this._spriteManagers.dispose();\n this._edgesRenderers.dispose();\n }\n /**\n * Inserts the submesh in its correct queue depending on its material.\n * @param subMesh The submesh to dispatch\n * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.\n * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.\n */\n dispatch(subMesh, mesh, material) {\n // Get mesh and materials if not provided\n if (mesh === undefined) {\n mesh = subMesh.getMesh();\n }\n if (material === undefined) {\n material = subMesh.getMaterial();\n }\n if (material === null || material === undefined) {\n return;\n }\n if (material.needAlphaBlendingForMesh(mesh)) {\n // Transparent\n this._transparentSubMeshes.push(subMesh);\n }\n else if (material.needAlphaTesting()) {\n // Alpha test\n if (material.needDepthPrePass) {\n this._depthOnlySubMeshes.push(subMesh);\n }\n this._alphaTestSubMeshes.push(subMesh);\n }\n else {\n if (material.needDepthPrePass) {\n this._depthOnlySubMeshes.push(subMesh);\n }\n this._opaqueSubMeshes.push(subMesh); // Opaque\n }\n mesh._renderingGroup = this;\n if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {\n this._edgesRenderers.pushNoDuplicate(mesh._edgesRenderer);\n }\n this._empty = false;\n }\n dispatchSprites(spriteManager) {\n this._spriteManagers.push(spriteManager);\n this._empty = false;\n }\n dispatchParticles(particleSystem) {\n this._particleSystems.push(particleSystem);\n this._empty = false;\n }\n _renderParticles(activeMeshes) {\n if (this._particleSystems.length === 0) {\n return;\n }\n // Particles\n const activeCamera = this._scene.activeCamera;\n this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);\n for (let particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {\n const particleSystem = this._particleSystems.data[particleIndex];\n if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {\n continue;\n }\n const emitter = particleSystem.emitter;\n if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {\n this._scene._activeParticles.addCount(particleSystem.render(), false);\n }\n }\n this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);\n }\n _renderSprites() {\n if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {\n return;\n }\n // Sprites\n const activeCamera = this._scene.activeCamera;\n this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);\n for (let id = 0; id < this._spriteManagers.length; id++) {\n const spriteManager = this._spriteManagers.data[id];\n if ((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0) {\n spriteManager.render();\n }\n }\n this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);\n }\n}\nRenderingGroup._ZeroVector = Vector3.Zero();\n//# sourceMappingURL=renderingGroup.js.map","import { RenderingGroup } from \"./renderingGroup.js\";\n/**\n * This class is used by the onRenderingGroupObservable\n */\nexport class RenderingGroupInfo {\n}\n/**\n * This is the manager responsible of all the rendering for meshes sprites and particles.\n * It is enable to manage the different groups as well as the different necessary sort functions.\n * This should not be used directly aside of the few static configurations\n */\nexport class RenderingManager {\n /**\n * Gets or sets a boolean indicating that the manager will not reset between frames.\n * This means that if a mesh becomes invisible or transparent it will not be visible until this boolean is set to false again.\n * By default, the rendering manager will dispatch all active meshes per frame (moving them to the transparent, opaque or alpha testing lists).\n * By turning this property on, you will accelerate the rendering by keeping all these lists unchanged between frames.\n */\n get maintainStateBetweenFrames() {\n return this._maintainStateBetweenFrames;\n }\n set maintainStateBetweenFrames(value) {\n if (value === this._maintainStateBetweenFrames) {\n return;\n }\n this._maintainStateBetweenFrames = value;\n // Restore wasDispatched flags when switching to maintainStateBetweenFrames to false\n if (!this._maintainStateBetweenFrames) {\n for (const mesh of this._scene.meshes) {\n if (mesh.subMeshes) {\n for (const subMesh of mesh.subMeshes) {\n subMesh._wasDispatched = false;\n }\n }\n }\n if (this._scene.spriteManagers) {\n for (const spriteManager of this._scene.spriteManagers) {\n spriteManager._wasDispatched = false;\n }\n }\n for (const particleSystem of this._scene.particleSystems) {\n particleSystem._wasDispatched = false;\n }\n }\n }\n /**\n * Instantiates a new rendering group for a particular scene\n * @param scene Defines the scene the groups belongs to\n */\n constructor(scene) {\n /**\n * @internal\n */\n this._useSceneAutoClearSetup = false;\n this._renderingGroups = new Array();\n this._autoClearDepthStencil = {};\n this._customOpaqueSortCompareFn = {};\n this._customAlphaTestSortCompareFn = {};\n this._customTransparentSortCompareFn = {};\n this._renderingGroupInfo = new RenderingGroupInfo();\n this._maintainStateBetweenFrames = false;\n this._scene = scene;\n for (let i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {\n this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };\n }\n }\n /**\n * Gets the rendering group with the specified id.\n */\n getRenderingGroup(id) {\n const renderingGroupId = id || 0;\n this._prepareRenderingGroup(renderingGroupId);\n return this._renderingGroups[renderingGroupId];\n }\n _clearDepthStencilBuffer(depth = true, stencil = true) {\n if (this._depthStencilBufferAlreadyCleaned) {\n return;\n }\n this._scene.getEngine().clear(null, false, depth, stencil);\n this._depthStencilBufferAlreadyCleaned = true;\n }\n /**\n * Renders the entire managed groups. This is used by the scene or the different render targets.\n * @internal\n */\n render(customRenderFunction, activeMeshes, renderParticles, renderSprites) {\n // Update the observable context (not null as it only goes away on dispose)\n const info = this._renderingGroupInfo;\n info.scene = this._scene;\n info.camera = this._scene.activeCamera;\n // Dispatch sprites\n if (this._scene.spriteManagers && renderSprites) {\n for (let index = 0; index < this._scene.spriteManagers.length; index++) {\n const manager = this._scene.spriteManagers[index];\n this.dispatchSprites(manager);\n }\n }\n // Render\n for (let index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {\n this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;\n const renderingGroup = this._renderingGroups[index];\n if (!renderingGroup || renderingGroup._empty) {\n continue;\n }\n const renderingGroupMask = Math.pow(2, index);\n info.renderingGroupId = index;\n // Before Observable\n this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);\n // Clear depth/stencil if needed\n if (RenderingManager.AUTOCLEAR) {\n const autoClear = this._useSceneAutoClearSetup ? this._scene.getAutoClearDepthStencilSetup(index) : this._autoClearDepthStencil[index];\n if (autoClear && autoClear.autoClear) {\n this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);\n }\n }\n // Render\n for (const step of this._scene._beforeRenderingGroupDrawStage) {\n step.action(index);\n }\n renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);\n for (const step of this._scene._afterRenderingGroupDrawStage) {\n step.action(index);\n }\n // After Observable\n this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);\n }\n }\n /**\n * Resets the different information of the group to prepare a new frame\n * @internal\n */\n reset() {\n if (this.maintainStateBetweenFrames) {\n return;\n }\n for (let index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {\n const renderingGroup = this._renderingGroups[index];\n if (renderingGroup) {\n renderingGroup.prepare();\n }\n }\n }\n /**\n * Resets the sprites information of the group to prepare a new frame\n * @internal\n */\n resetSprites() {\n if (this.maintainStateBetweenFrames) {\n return;\n }\n for (let index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {\n const renderingGroup = this._renderingGroups[index];\n if (renderingGroup) {\n renderingGroup.prepareSprites();\n }\n }\n }\n /**\n * Dispose and release the group and its associated resources.\n * @internal\n */\n dispose() {\n this.freeRenderingGroups();\n this._renderingGroups.length = 0;\n this._renderingGroupInfo = null;\n }\n /**\n * Clear the info related to rendering groups preventing retention points during dispose.\n */\n freeRenderingGroups() {\n for (let index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {\n const renderingGroup = this._renderingGroups[index];\n if (renderingGroup) {\n renderingGroup.dispose();\n }\n }\n }\n _prepareRenderingGroup(renderingGroupId) {\n if (this._renderingGroups[renderingGroupId] === undefined) {\n this._renderingGroups[renderingGroupId] = new RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);\n }\n }\n /**\n * Add a sprite manager to the rendering manager in order to render it this frame.\n * @param spriteManager Define the sprite manager to render\n */\n dispatchSprites(spriteManager) {\n if (this.maintainStateBetweenFrames && spriteManager._wasDispatched) {\n return;\n }\n spriteManager._wasDispatched = true;\n this.getRenderingGroup(spriteManager.renderingGroupId).dispatchSprites(spriteManager);\n }\n /**\n * Add a particle system to the rendering manager in order to render it this frame.\n * @param particleSystem Define the particle system to render\n */\n dispatchParticles(particleSystem) {\n if (this.maintainStateBetweenFrames && particleSystem._wasDispatched) {\n return;\n }\n particleSystem._wasDispatched = true;\n this.getRenderingGroup(particleSystem.renderingGroupId).dispatchParticles(particleSystem);\n }\n /**\n * Add a submesh to the manager in order to render it this frame\n * @param subMesh The submesh to dispatch\n * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.\n * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.\n */\n dispatch(subMesh, mesh, material) {\n if (mesh === undefined) {\n mesh = subMesh.getMesh();\n }\n if (this.maintainStateBetweenFrames && subMesh._wasDispatched) {\n return;\n }\n subMesh._wasDispatched = true;\n this.getRenderingGroup(mesh.renderingGroupId).dispatch(subMesh, mesh, material);\n }\n /**\n * Overrides the default sort function applied in the rendering group to prepare the meshes.\n * This allowed control for front to back rendering or reversely depending of the special needs.\n *\n * @param renderingGroupId The rendering group id corresponding to its index\n * @param opaqueSortCompareFn The opaque queue comparison function use to sort.\n * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.\n * @param transparentSortCompareFn The transparent queue comparison function use to sort.\n */\n setRenderingOrder(renderingGroupId, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) {\n this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;\n this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;\n this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;\n if (this._renderingGroups[renderingGroupId]) {\n const group = this._renderingGroups[renderingGroupId];\n group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];\n group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];\n group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];\n }\n }\n /**\n * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.\n *\n * @param renderingGroupId The rendering group id corresponding to its index\n * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.\n * @param depth Automatically clears depth between groups if true and autoClear is true.\n * @param stencil Automatically clears stencil between groups if true and autoClear is true.\n */\n setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth = true, stencil = true) {\n this._autoClearDepthStencil[renderingGroupId] = {\n autoClear: autoClearDepthStencil,\n depth: depth,\n stencil: stencil,\n };\n }\n /**\n * Gets the current auto clear configuration for one rendering group of the rendering\n * manager.\n * @param index the rendering group index to get the information for\n * @returns The auto clear setup for the requested rendering group\n */\n getAutoClearDepthStencilSetup(index) {\n return this._autoClearDepthStencil[index];\n }\n}\n/**\n * The max id used for rendering groups (not included)\n */\nRenderingManager.MAX_RENDERINGGROUPS = 4;\n/**\n * The min id used for rendering groups (included)\n */\nRenderingManager.MIN_RENDERINGGROUPS = 0;\n/**\n * Used to globally prevent autoclearing scenes.\n */\nRenderingManager.AUTOCLEAR = true;\n//# sourceMappingURL=renderingManager.js.map","/**\n * @internal\n **/\nexport class AlphaState {\n /**\n * Initializes the state.\n */\n constructor() {\n this._blendFunctionParameters = new Array(4);\n this._blendEquationParameters = new Array(2);\n this._blendConstants = new Array(4);\n this._isBlendConstantsDirty = false;\n this._alphaBlend = false;\n this._isAlphaBlendDirty = false;\n this._isBlendFunctionParametersDirty = false;\n this._isBlendEquationParametersDirty = false;\n this.reset();\n }\n get isDirty() {\n return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty || this._isBlendEquationParametersDirty;\n }\n get alphaBlend() {\n return this._alphaBlend;\n }\n set alphaBlend(value) {\n if (this._alphaBlend === value) {\n return;\n }\n this._alphaBlend = value;\n this._isAlphaBlendDirty = true;\n }\n setAlphaBlendConstants(r, g, b, a) {\n if (this._blendConstants[0] === r && this._blendConstants[1] === g && this._blendConstants[2] === b && this._blendConstants[3] === a) {\n return;\n }\n this._blendConstants[0] = r;\n this._blendConstants[1] = g;\n this._blendConstants[2] = b;\n this._blendConstants[3] = a;\n this._isBlendConstantsDirty = true;\n }\n setAlphaBlendFunctionParameters(value0, value1, value2, value3) {\n if (this._blendFunctionParameters[0] === value0 &&\n this._blendFunctionParameters[1] === value1 &&\n this._blendFunctionParameters[2] === value2 &&\n this._blendFunctionParameters[3] === value3) {\n return;\n }\n this._blendFunctionParameters[0] = value0;\n this._blendFunctionParameters[1] = value1;\n this._blendFunctionParameters[2] = value2;\n this._blendFunctionParameters[3] = value3;\n this._isBlendFunctionParametersDirty = true;\n }\n setAlphaEquationParameters(rgb, alpha) {\n if (this._blendEquationParameters[0] === rgb && this._blendEquationParameters[1] === alpha) {\n return;\n }\n this._blendEquationParameters[0] = rgb;\n this._blendEquationParameters[1] = alpha;\n this._isBlendEquationParametersDirty = true;\n }\n reset() {\n this._alphaBlend = false;\n this._blendFunctionParameters[0] = null;\n this._blendFunctionParameters[1] = null;\n this._blendFunctionParameters[2] = null;\n this._blendFunctionParameters[3] = null;\n this._blendEquationParameters[0] = null;\n this._blendEquationParameters[1] = null;\n this._blendConstants[0] = null;\n this._blendConstants[1] = null;\n this._blendConstants[2] = null;\n this._blendConstants[3] = null;\n this._isAlphaBlendDirty = true;\n this._isBlendFunctionParametersDirty = false;\n this._isBlendEquationParametersDirty = false;\n this._isBlendConstantsDirty = false;\n }\n apply(gl) {\n if (!this.isDirty) {\n return;\n }\n // Alpha blend\n if (this._isAlphaBlendDirty) {\n if (this._alphaBlend) {\n gl.enable(gl.BLEND);\n }\n else {\n gl.disable(gl.BLEND);\n }\n this._isAlphaBlendDirty = false;\n }\n // Alpha function\n if (this._isBlendFunctionParametersDirty) {\n gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);\n this._isBlendFunctionParametersDirty = false;\n }\n // Alpha equation\n if (this._isBlendEquationParametersDirty) {\n gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);\n this._isBlendEquationParametersDirty = false;\n }\n // Constants\n if (this._isBlendConstantsDirty) {\n gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);\n this._isBlendConstantsDirty = false;\n }\n }\n}\n//# sourceMappingURL=alphaCullingState.js.map","/**\n * @internal\n **/\nexport class DepthCullingState {\n /**\n * Initializes the state.\n * @param reset\n */\n constructor(reset = true) {\n this._isDepthTestDirty = false;\n this._isDepthMaskDirty = false;\n this._isDepthFuncDirty = false;\n this._isCullFaceDirty = false;\n this._isCullDirty = false;\n this._isZOffsetDirty = false;\n this._isFrontFaceDirty = false;\n if (reset) {\n this.reset();\n }\n }\n get isDirty() {\n return (this._isDepthFuncDirty ||\n this._isDepthTestDirty ||\n this._isDepthMaskDirty ||\n this._isCullFaceDirty ||\n this._isCullDirty ||\n this._isZOffsetDirty ||\n this._isFrontFaceDirty);\n }\n get zOffset() {\n return this._zOffset;\n }\n set zOffset(value) {\n if (this._zOffset === value) {\n return;\n }\n this._zOffset = value;\n this._isZOffsetDirty = true;\n }\n get zOffsetUnits() {\n return this._zOffsetUnits;\n }\n set zOffsetUnits(value) {\n if (this._zOffsetUnits === value) {\n return;\n }\n this._zOffsetUnits = value;\n this._isZOffsetDirty = true;\n }\n get cullFace() {\n return this._cullFace;\n }\n set cullFace(value) {\n if (this._cullFace === value) {\n return;\n }\n this._cullFace = value;\n this._isCullFaceDirty = true;\n }\n get cull() {\n return this._cull;\n }\n set cull(value) {\n if (this._cull === value) {\n return;\n }\n this._cull = value;\n this._isCullDirty = true;\n }\n get depthFunc() {\n return this._depthFunc;\n }\n set depthFunc(value) {\n if (this._depthFunc === value) {\n return;\n }\n this._depthFunc = value;\n this._isDepthFuncDirty = true;\n }\n get depthMask() {\n return this._depthMask;\n }\n set depthMask(value) {\n if (this._depthMask === value) {\n return;\n }\n this._depthMask = value;\n this._isDepthMaskDirty = true;\n }\n get depthTest() {\n return this._depthTest;\n }\n set depthTest(value) {\n if (this._depthTest === value) {\n return;\n }\n this._depthTest = value;\n this._isDepthTestDirty = true;\n }\n get frontFace() {\n return this._frontFace;\n }\n set frontFace(value) {\n if (this._frontFace === value) {\n return;\n }\n this._frontFace = value;\n this._isFrontFaceDirty = true;\n }\n reset() {\n this._depthMask = true;\n this._depthTest = true;\n this._depthFunc = null;\n this._cullFace = null;\n this._cull = null;\n this._zOffset = 0;\n this._zOffsetUnits = 0;\n this._frontFace = null;\n this._isDepthTestDirty = true;\n this._isDepthMaskDirty = true;\n this._isDepthFuncDirty = false;\n this._isCullFaceDirty = false;\n this._isCullDirty = false;\n this._isZOffsetDirty = true;\n this._isFrontFaceDirty = false;\n }\n apply(gl) {\n if (!this.isDirty) {\n return;\n }\n // Cull\n if (this._isCullDirty) {\n if (this.cull) {\n gl.enable(gl.CULL_FACE);\n }\n else {\n gl.disable(gl.CULL_FACE);\n }\n this._isCullDirty = false;\n }\n // Cull face\n if (this._isCullFaceDirty) {\n gl.cullFace(this.cullFace);\n this._isCullFaceDirty = false;\n }\n // Depth mask\n if (this._isDepthMaskDirty) {\n gl.depthMask(this.depthMask);\n this._isDepthMaskDirty = false;\n }\n // Depth test\n if (this._isDepthTestDirty) {\n if (this.depthTest) {\n gl.enable(gl.DEPTH_TEST);\n }\n else {\n gl.disable(gl.DEPTH_TEST);\n }\n this._isDepthTestDirty = false;\n }\n // Depth func\n if (this._isDepthFuncDirty) {\n gl.depthFunc(this.depthFunc);\n this._isDepthFuncDirty = false;\n }\n // zOffset\n if (this._isZOffsetDirty) {\n if (this.zOffset || this.zOffsetUnits) {\n gl.enable(gl.POLYGON_OFFSET_FILL);\n gl.polygonOffset(this.zOffset, this.zOffsetUnits);\n }\n else {\n gl.disable(gl.POLYGON_OFFSET_FILL);\n }\n this._isZOffsetDirty = false;\n }\n // Front face\n if (this._isFrontFaceDirty) {\n gl.frontFace(this.frontFace);\n this._isFrontFaceDirty = false;\n }\n }\n}\n//# sourceMappingURL=depthCullingState.js.map","\n/**\n * @internal\n **/\nexport class StencilState {\n constructor() {\n this.reset();\n }\n reset() {\n this.enabled = false;\n this.mask = 0xff;\n this.func = StencilState.ALWAYS;\n this.funcRef = 1;\n this.funcMask = 0xff;\n this.opStencilFail = StencilState.KEEP;\n this.opDepthFail = StencilState.KEEP;\n this.opStencilDepthPass = StencilState.REPLACE;\n }\n get stencilFunc() {\n return this.func;\n }\n set stencilFunc(value) {\n this.func = value;\n }\n get stencilFuncRef() {\n return this.funcRef;\n }\n set stencilFuncRef(value) {\n this.funcRef = value;\n }\n get stencilFuncMask() {\n return this.funcMask;\n }\n set stencilFuncMask(value) {\n this.funcMask = value;\n }\n get stencilOpStencilFail() {\n return this.opStencilFail;\n }\n set stencilOpStencilFail(value) {\n this.opStencilFail = value;\n }\n get stencilOpDepthFail() {\n return this.opDepthFail;\n }\n set stencilOpDepthFail(value) {\n this.opDepthFail = value;\n }\n get stencilOpStencilDepthPass() {\n return this.opStencilDepthPass;\n }\n set stencilOpStencilDepthPass(value) {\n this.opStencilDepthPass = value;\n }\n get stencilMask() {\n return this.mask;\n }\n set stencilMask(value) {\n this.mask = value;\n }\n get stencilTest() {\n return this.enabled;\n }\n set stencilTest(value) {\n this.enabled = value;\n }\n}\n/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */\nStencilState.ALWAYS = 519;\n/** Passed to stencilOperation to specify that stencil value must be kept */\nStencilState.KEEP = 7680;\n/** Passed to stencilOperation to specify that stencil value must be replaced */\nStencilState.REPLACE = 7681;\n//# sourceMappingURL=stencilState.js.map","/**\n * @internal\n **/\nexport class StencilStateComposer {\n get isDirty() {\n return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;\n }\n get func() {\n return this._func;\n }\n set func(value) {\n if (this._func === value) {\n return;\n }\n this._func = value;\n this._isStencilFuncDirty = true;\n }\n get funcRef() {\n return this._funcRef;\n }\n set funcRef(value) {\n if (this._funcRef === value) {\n return;\n }\n this._funcRef = value;\n this._isStencilFuncDirty = true;\n }\n get funcMask() {\n return this._funcMask;\n }\n set funcMask(value) {\n if (this._funcMask === value) {\n return;\n }\n this._funcMask = value;\n this._isStencilFuncDirty = true;\n }\n get opStencilFail() {\n return this._opStencilFail;\n }\n set opStencilFail(value) {\n if (this._opStencilFail === value) {\n return;\n }\n this._opStencilFail = value;\n this._isStencilOpDirty = true;\n }\n get opDepthFail() {\n return this._opDepthFail;\n }\n set opDepthFail(value) {\n if (this._opDepthFail === value) {\n return;\n }\n this._opDepthFail = value;\n this._isStencilOpDirty = true;\n }\n get opStencilDepthPass() {\n return this._opStencilDepthPass;\n }\n set opStencilDepthPass(value) {\n if (this._opStencilDepthPass === value) {\n return;\n }\n this._opStencilDepthPass = value;\n this._isStencilOpDirty = true;\n }\n get mask() {\n return this._mask;\n }\n set mask(value) {\n if (this._mask === value) {\n return;\n }\n this._mask = value;\n this._isStencilMaskDirty = true;\n }\n get enabled() {\n return this._enabled;\n }\n set enabled(value) {\n if (this._enabled === value) {\n return;\n }\n this._enabled = value;\n this._isStencilTestDirty = true;\n }\n constructor(reset = true) {\n this._isStencilTestDirty = false;\n this._isStencilMaskDirty = false;\n this._isStencilFuncDirty = false;\n this._isStencilOpDirty = false;\n this.useStencilGlobalOnly = false;\n if (reset) {\n this.reset();\n }\n }\n reset() {\n var _a;\n this.stencilMaterial = undefined;\n (_a = this.stencilGlobal) === null || _a === void 0 ? void 0 : _a.reset();\n this._isStencilTestDirty = true;\n this._isStencilMaskDirty = true;\n this._isStencilFuncDirty = true;\n this._isStencilOpDirty = true;\n }\n apply(gl) {\n var _a;\n if (!gl) {\n return;\n }\n const stencilMaterialEnabled = !this.useStencilGlobalOnly && !!((_a = this.stencilMaterial) === null || _a === void 0 ? void 0 : _a.enabled);\n this.enabled = stencilMaterialEnabled ? this.stencilMaterial.enabled : this.stencilGlobal.enabled;\n this.func = stencilMaterialEnabled ? this.stencilMaterial.func : this.stencilGlobal.func;\n this.funcRef = stencilMaterialEnabled ? this.stencilMaterial.funcRef : this.stencilGlobal.funcRef;\n this.funcMask = stencilMaterialEnabled ? this.stencilMaterial.funcMask : this.stencilGlobal.funcMask;\n this.opStencilFail = stencilMaterialEnabled ? this.stencilMaterial.opStencilFail : this.stencilGlobal.opStencilFail;\n this.opDepthFail = stencilMaterialEnabled ? this.stencilMaterial.opDepthFail : this.stencilGlobal.opDepthFail;\n this.opStencilDepthPass = stencilMaterialEnabled ? this.stencilMaterial.opStencilDepthPass : this.stencilGlobal.opStencilDepthPass;\n this.mask = stencilMaterialEnabled ? this.stencilMaterial.mask : this.stencilGlobal.mask;\n if (!this.isDirty) {\n return;\n }\n // Stencil test\n if (this._isStencilTestDirty) {\n if (this.enabled) {\n gl.enable(gl.STENCIL_TEST);\n }\n else {\n gl.disable(gl.STENCIL_TEST);\n }\n this._isStencilTestDirty = false;\n }\n // Stencil mask\n if (this._isStencilMaskDirty) {\n gl.stencilMask(this.mask);\n this._isStencilMaskDirty = false;\n }\n // Stencil func\n if (this._isStencilFuncDirty) {\n gl.stencilFunc(this.func, this.funcRef, this.funcMask);\n this._isStencilFuncDirty = false;\n }\n // Stencil op\n if (this._isStencilOpDirty) {\n gl.stencilOp(this.opStencilFail, this.opDepthFail, this.opStencilDepthPass);\n this._isStencilOpDirty = false;\n }\n }\n}\n//# sourceMappingURL=stencilStateComposer.js.map","/**\n * Base class of the scene acting as a container for the different elements composing a scene.\n * This class is dynamically extended by the different components of the scene increasing\n * flexibility and reducing coupling\n */\nexport class AbstractScene {\n constructor() {\n /**\n * Gets the list of root nodes (ie. nodes with no parent)\n */\n this.rootNodes = new Array();\n /** All of the cameras added to this scene\n * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras\n */\n this.cameras = new Array();\n /**\n * All of the lights added to this scene\n * @see https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction\n */\n this.lights = new Array();\n /**\n * All of the (abstract) meshes added to this scene\n */\n this.meshes = new Array();\n /**\n * The list of skeletons added to the scene\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons\n */\n this.skeletons = new Array();\n /**\n * All of the particle systems added to this scene\n * @see https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro\n */\n this.particleSystems = new Array();\n /**\n * Gets a list of Animations associated with the scene\n */\n this.animations = [];\n /**\n * All of the animation groups added to this scene\n * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/groupAnimations\n */\n this.animationGroups = new Array();\n /**\n * All of the multi-materials added to this scene\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/multiMaterials\n */\n this.multiMaterials = new Array();\n /**\n * All of the materials added to this scene\n * In the context of a Scene, it is not supposed to be modified manually.\n * Any addition or removal should be done using the addMaterial and removeMaterial Scene methods.\n * Note also that the order of the Material within the array is not significant and might change.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction\n */\n this.materials = new Array();\n /**\n * The list of morph target managers added to the scene\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph\n */\n this.morphTargetManagers = new Array();\n /**\n * The list of geometries used in the scene.\n */\n this.geometries = new Array();\n /**\n * All of the transform nodes added to this scene\n * In the context of a Scene, it is not supposed to be modified manually.\n * Any addition or removal should be done using the addTransformNode and removeTransformNode Scene methods.\n * Note also that the order of the TransformNode within the array is not significant and might change.\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/parent_pivot/transform_node\n */\n this.transformNodes = new Array();\n /**\n * ActionManagers available on the scene.\n * @deprecated\n */\n this.actionManagers = new Array();\n /**\n * Textures to keep.\n */\n this.textures = new Array();\n /** @internal */\n this._environmentTexture = null;\n /**\n * The list of postprocesses added to the scene\n */\n this.postProcesses = new Array();\n }\n /**\n * Adds a parser in the list of available ones\n * @param name Defines the name of the parser\n * @param parser Defines the parser to add\n */\n static AddParser(name, parser) {\n this._BabylonFileParsers[name] = parser;\n }\n /**\n * Gets a general parser from the list of available ones\n * @param name Defines the name of the parser\n * @returns the requested parser or null\n */\n static GetParser(name) {\n if (this._BabylonFileParsers[name]) {\n return this._BabylonFileParsers[name];\n }\n return null;\n }\n /**\n * Adds n individual parser in the list of available ones\n * @param name Defines the name of the parser\n * @param parser Defines the parser to add\n */\n static AddIndividualParser(name, parser) {\n this._IndividualBabylonFileParsers[name] = parser;\n }\n /**\n * Gets an individual parser from the list of available ones\n * @param name Defines the name of the parser\n * @returns the requested parser or null\n */\n static GetIndividualParser(name) {\n if (this._IndividualBabylonFileParsers[name]) {\n return this._IndividualBabylonFileParsers[name];\n }\n return null;\n }\n /**\n * Parser json data and populate both a scene and its associated container object\n * @param jsonData Defines the data to parse\n * @param scene Defines the scene to parse the data for\n * @param container Defines the container attached to the parsing sequence\n * @param rootUrl Defines the root url of the data\n */\n static Parse(jsonData, scene, container, rootUrl) {\n for (const parserName in this._BabylonFileParsers) {\n if (Object.prototype.hasOwnProperty.call(this._BabylonFileParsers, parserName)) {\n this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);\n }\n }\n }\n /**\n * Texture used in all pbr material as the reflection texture.\n * As in the majority of the scene they are the same (exception for multi room and so on),\n * this is easier to reference from here than from all the materials.\n */\n get environmentTexture() {\n return this._environmentTexture;\n }\n set environmentTexture(value) {\n this._environmentTexture = value;\n }\n /**\n * @returns all meshes, lights, cameras, transformNodes and bones\n */\n getNodes() {\n let nodes = new Array();\n nodes = nodes.concat(this.meshes);\n nodes = nodes.concat(this.lights);\n nodes = nodes.concat(this.cameras);\n nodes = nodes.concat(this.transformNodes); // dummies\n this.skeletons.forEach((skeleton) => (nodes = nodes.concat(skeleton.bones)));\n return nodes;\n }\n}\n/**\n * Stores the list of available parsers in the application.\n */\nAbstractScene._BabylonFileParsers = {};\n/**\n * Stores the list of available individual parsers in the application.\n */\nAbstractScene._IndividualBabylonFileParsers = {};\n//# sourceMappingURL=abstractScene.js.map","import { __decorate } from \"./tslib.es6.js\";\nimport { Matrix, Vector3 } from \"./Maths/math.vector.js\";\nimport { SerializationHelper, serialize } from \"./Misc/decorators.js\";\nimport { Observable } from \"./Misc/observable.js\";\nimport { EngineStore } from \"./Engines/engineStore.js\";\nimport { _WarnImport } from \"./Misc/devTools.js\";\n/** @internal */\nclass _InternalNodeDataInfo {\n constructor() {\n this._doNotSerialize = false;\n this._isDisposed = false;\n this._sceneRootNodesIndex = -1;\n this._isEnabled = true;\n this._isParentEnabled = true;\n this._isReady = true;\n this._onEnabledStateChangedObservable = new Observable();\n this._onClonedObservable = new Observable();\n }\n}\n/**\n * Node is the basic class for all scene objects (Mesh, Light, Camera.)\n */\nexport class Node {\n /**\n * Add a new node constructor\n * @param type defines the type name of the node to construct\n * @param constructorFunc defines the constructor function\n */\n static AddNodeConstructor(type, constructorFunc) {\n this._NodeConstructors[type] = constructorFunc;\n }\n /**\n * Returns a node constructor based on type name\n * @param type defines the type name\n * @param name defines the new node name\n * @param scene defines the hosting scene\n * @param options defines optional options to transmit to constructors\n * @returns the new constructor or null\n */\n static Construct(type, name, scene, options) {\n const constructorFunc = this._NodeConstructors[type];\n if (!constructorFunc) {\n return null;\n }\n return constructorFunc(name, scene, options);\n }\n /**\n * Gets or sets the accessibility tag to describe the node for accessibility purpose.\n */\n set accessibilityTag(value) {\n this._accessibilityTag = value;\n this.onAccessibilityTagChangedObservable.notifyObservers(value);\n }\n get accessibilityTag() {\n return this._accessibilityTag;\n }\n /**\n * Gets or sets a boolean used to define if the node must be serialized\n */\n get doNotSerialize() {\n if (this._nodeDataStorage._doNotSerialize) {\n return true;\n }\n if (this._parentNode) {\n return this._parentNode.doNotSerialize;\n }\n return false;\n }\n set doNotSerialize(value) {\n this._nodeDataStorage._doNotSerialize = value;\n }\n /**\n * Gets a boolean indicating if the node has been disposed\n * @returns true if the node was disposed\n */\n isDisposed() {\n return this._nodeDataStorage._isDisposed;\n }\n /**\n * Gets or sets the parent of the node (without keeping the current position in the scene)\n * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/parent_pivot/parent\n */\n set parent(parent) {\n if (this._parentNode === parent) {\n return;\n }\n const previousParentNode = this._parentNode;\n // Remove self from list of children of parent\n if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {\n const index = this._parentNode._children.indexOf(this);\n if (index !== -1) {\n this._parentNode._children.splice(index, 1);\n }\n if (!parent && !this._nodeDataStorage._isDisposed) {\n this._addToSceneRootNodes();\n }\n }\n // Store new parent\n this._parentNode = parent;\n // Add as child to new parent\n if (this._parentNode) {\n if (this._parentNode._children === undefined || this._parentNode._children === null) {\n this._parentNode._children = new Array();\n }\n this._parentNode._children.push(this);\n if (!previousParentNode) {\n this._removeFromSceneRootNodes();\n }\n }\n // Enabled state\n this._syncParentEnabledState();\n }\n get parent() {\n return this._parentNode;\n }\n /**\n * @internal\n */\n _serializeAsParent(serializationObject) {\n serializationObject.parentId = this.uniqueId;\n }\n /** @internal */\n _addToSceneRootNodes() {\n if (this._nodeDataStorage._sceneRootNodesIndex === -1) {\n this._nodeDataStorage._sceneRootNodesIndex = this._scene.rootNodes.length;\n this._scene.rootNodes.push(this);\n }\n }\n /** @internal */\n _removeFromSceneRootNodes() {\n if (this._nodeDataStorage._sceneRootNodesIndex !== -1) {\n const rootNodes = this._scene.rootNodes;\n const lastIdx = rootNodes.length - 1;\n rootNodes[this._nodeDataStorage._sceneRootNodesIndex] = rootNodes[lastIdx];\n rootNodes[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex = this._nodeDataStorage._sceneRootNodesIndex;\n this._scene.rootNodes.pop();\n this._nodeDataStorage._sceneRootNodesIndex = -1;\n }\n }\n /**\n * Gets or sets the animation properties override\n */\n get animationPropertiesOverride() {\n if (!this._animationPropertiesOverride) {\n return this._scene.animationPropertiesOverride;\n }\n return this._animationPropertiesOverride;\n }\n set animationPropertiesOverride(value) {\n this._animationPropertiesOverride = value;\n }\n /**\n * Gets a string identifying the name of the class\n * @returns \"Node\" string\n */\n getClassName() {\n return \"Node\";\n }\n /**\n * Sets a callback that will be raised when the node will be disposed\n */\n set onDispose(callback) {\n if (this._onDisposeObserver) {\n this.onDisposeObservable.remove(this._onDisposeObserver);\n }\n this._onDisposeObserver = this.onDisposeObservable.add(callback);\n }\n /**\n * An event triggered when the enabled state of the node changes\n */\n get onEnabledStateChangedObservable() {\n return this._nodeDataStorage._onEnabledStateChangedObservable;\n }\n /**\n * An event triggered when the node is cloned\n */\n get onClonedObservable() {\n return this._nodeDataStorage._onClonedObservable;\n }\n /**\n * Creates a new Node\n * @param name the name and id to be given to this node\n * @param scene the scene this node will be added to\n */\n constructor(name, scene = null) {\n this._isDirty = false;\n this._nodeDataStorage = new _InternalNodeDataInfo();\n /**\n * Gets or sets a string used to store user defined state for the node\n */\n this.state = \"\";\n /**\n * Gets or sets an object used to store user defined information for the node\n */\n this.metadata = null;\n /**\n * For internal use only. Please do not use.\n */\n this.reservedDataStore = null;\n this._accessibilityTag = null;\n this.onAccessibilityTagChangedObservable = new Observable();\n /** @internal */\n this._parentContainer = null;\n /**\n * Gets a list of Animations associated with the node\n */\n this.animations = new Array();\n this._ranges = {};\n /**\n * Callback raised when the node is ready to be used\n */\n this.onReady = null;\n /** @internal */\n this._currentRenderId = -1;\n this._parentUpdateId = -1;\n /** @internal */\n this._childUpdateId = -1;\n /** @internal */\n this._waitingParentId = null;\n /** @internal */\n this._waitingParentInstanceIndex = null;\n /** @internal */\n this._waitingParsedUniqueId = null;\n /** @internal */\n this._cache = {};\n this._parentNode = null;\n /** @internal */\n this._children = null;\n /** @internal */\n this._worldMatrix = Matrix.Identity();\n /** @internal */\n this._worldMatrixDeterminant = 0;\n /** @internal */\n this._worldMatrixDeterminantIsDirty = true;\n this._animationPropertiesOverride = null;\n /** @internal */\n this._isNode = true;\n /**\n * An event triggered when the mesh is disposed\n */\n this.onDisposeObservable = new Observable();\n this._onDisposeObserver = null;\n // Behaviors\n this._behaviors = new Array();\n this.name = name;\n this.id = name;\n this._scene = (scene || EngineStore.LastCreatedScene);\n this.uniqueId = this._scene.getUniqueId();\n this._initCache();\n }\n /**\n * Gets the scene of the node\n * @returns a scene\n */\n getScene() {\n return this._scene;\n }\n /**\n * Gets the engine of the node\n * @returns a Engine\n */\n getEngine() {\n return this._scene.getEngine();\n }\n /**\n * Attach a behavior to the node\n * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors\n * @param behavior defines the behavior to attach\n * @param attachImmediately defines that the behavior must be attached even if the scene is still loading\n * @returns the current Node\n */\n addBehavior(behavior, attachImmediately = false) {\n const index = this._behaviors.indexOf(behavior);\n if (index !== -1) {\n return this;\n }\n behavior.init();\n if (this._scene.isLoading && !attachImmediately) {\n // We defer the attach when the scene will be loaded\n this._scene.onDataLoadedObservable.addOnce(() => {\n behavior.attach(this);\n });\n }\n else {\n behavior.attach(this);\n }\n this._behaviors.push(behavior);\n return this;\n }\n /**\n * Remove an attached behavior\n * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors\n * @param behavior defines the behavior to attach\n * @returns the current Node\n */\n removeBehavior(behavior) {\n const index = this._behaviors.indexOf(behavior);\n if (index === -1) {\n return this;\n }\n this._behaviors[index].detach();\n this._behaviors.splice(index, 1);\n return this;\n }\n /**\n * Gets the list of attached behaviors\n * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors\n */\n get behaviors() {\n return this._behaviors;\n }\n /**\n * Gets an attached behavior by name\n * @param name defines the name of the behavior to look for\n * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors\n * @returns null if behavior was not found else the requested behavior\n */\n getBehaviorByName(name) {\n for (const behavior of this._behaviors) {\n if (behavior.name === name) {\n return behavior;\n }\n }\n return null;\n }\n /**\n * Returns the latest update of the World matrix\n * @returns a Matrix\n */\n getWorldMatrix() {\n if (this._currentRenderId !== this._scene.getRenderId()) {\n this.computeWorldMatrix();\n }\n return this._worldMatrix;\n }\n /** @internal */\n _getWorldMatrixDeterminant() {\n if (this._worldMatrixDeterminantIsDirty) {\n this._worldMatrixDeterminantIsDirty = false;\n this._worldMatrixDeterminant = this._worldMatrix.determinant();\n }\n return this._worldMatrixDeterminant;\n }\n /**\n * Returns directly the latest state of the mesh World matrix.\n * A Matrix is returned.\n */\n get worldMatrixFromCache() {\n return this._worldMatrix;\n }\n // override it in derived class if you add new variables to the cache\n // and call the parent class method\n /** @internal */\n _initCache() {\n this._cache = {};\n this._cache.parent = undefined;\n }\n /**\n * @internal\n */\n updateCache(force) {\n if (!force && this.isSynchronized()) {\n return;\n }\n this._cache.parent = this.parent;\n this._updateCache();\n }\n /**\n * @internal\n */\n _getActionManagerForTrigger(trigger, _initialCall = true) {\n if (!this.parent) {\n return null;\n }\n return this.parent._getActionManagerForTrigger(trigger, false);\n }\n // override it in derived class if you add new variables to the cache\n // and call the parent class method if !ignoreParentClass\n /**\n * @internal\n */\n _updateCache(_ignoreParentClass) { }\n // override it in derived class if you add new variables to the cache\n /** @internal */\n _isSynchronized() {\n return true;\n }\n /** @internal */\n _markSyncedWithParent() {\n if (this._parentNode) {\n this._parentUpdateId = this._parentNode._childUpdateId;\n }\n }\n /** @internal */\n isSynchronizedWithParent() {\n if (!this._parentNode) {\n return true;\n }\n if (this._parentNode._isDirty || this._parentUpdateId !== this._parentNode._childUpdateId) {\n return false;\n }\n return this._parentNode.isSynchronized();\n }\n /** @internal */\n isSynchronized() {\n if (this._cache.parent !== this._parentNode) {\n this._cache.parent = this._parentNode;\n return false;\n }\n if (this._parentNode && !this.isSynchronizedWithParent()) {\n return false;\n }\n return this._isSynchronized();\n }\n /**\n * Is this node ready to be used/rendered\n * @param _completeCheck defines if a complete check (including materials and lights) has to be done (false by default)\n * @returns true if the node is ready\n */\n isReady(_completeCheck = false) {\n return this._nodeDataStorage._isReady;\n }\n /**\n * Flag the node as dirty (Forcing it to update everything)\n * @param _property helps children apply precise \"dirtyfication\"\n * @returns this node\n */\n markAsDirty(_property) {\n this._currentRenderId = Number.MAX_VALUE;\n this._isDirty = true;\n return this;\n }\n /**\n * Is this node enabled?\n * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true\n * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors\n * @returns whether this node (and its parent) is enabled\n */\n isEnabled(checkAncestors = true) {\n if (checkAncestors === false) {\n return this._nodeDataStorage._isEnabled;\n }\n if (!this._nodeDataStorage._isEnabled) {\n return false;\n }\n return this._nodeDataStorage._isParentEnabled;\n }\n /** @internal */\n _syncParentEnabledState() {\n this._nodeDataStorage._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;\n if (this._children) {\n this._children.forEach((c) => {\n c._syncParentEnabledState(); // Force children to update accordingly\n });\n }\n }\n /**\n * Set the enabled state of this node\n * @param value defines the new enabled state\n */\n setEnabled(value) {\n if (this._nodeDataStorage._isEnabled === value) {\n return;\n }\n this._nodeDataStorage._isEnabled = value;\n this._syncParentEnabledState();\n this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(value);\n }\n /**\n * Is this node a descendant of the given node?\n * The function will iterate up the hierarchy until the ancestor was found or no more parents defined\n * @param ancestor defines the parent node to inspect\n * @returns a boolean indicating if this node is a descendant of the given node\n */\n isDescendantOf(ancestor) {\n if (this.parent) {\n if (this.parent === ancestor) {\n return true;\n }\n return this.parent.isDescendantOf(ancestor);\n }\n return false;\n }\n /**\n * @internal\n */\n _getDescendants(results, directDescendantsOnly = false, predicate) {\n if (!this._children) {\n return;\n }\n for (let index = 0; index < this._children.length; index++) {\n const item = this._children[index];\n if (!predicate || predicate(item)) {\n results.push(item);\n }\n if (!directDescendantsOnly) {\n item._getDescendants(results, false, predicate);\n }\n }\n }\n /**\n * Will return all nodes that have this node as ascendant\n * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered\n * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored\n * @returns all children nodes of all types\n */\n getDescendants(directDescendantsOnly, predicate) {\n const results = new Array();\n this._getDescendants(results, directDescendantsOnly, predicate);\n return results;\n }\n /**\n * Get all child-meshes of this node\n * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered (Default: false)\n * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored\n * @returns an array of AbstractMesh\n */\n getChildMeshes(directDescendantsOnly, predicate) {\n const results = [];\n this._getDescendants(results, directDescendantsOnly, (node) => {\n return (!predicate || predicate(node)) && node.cullingStrategy !== undefined;\n });\n return results;\n }\n /**\n * Get all direct children of this node\n * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored\n * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered (Default: true)\n * @returns an array of Node\n */\n getChildren(predicate, directDescendantsOnly = true) {\n return this.getDescendants(directDescendantsOnly, predicate);\n }\n /**\n * @internal\n */\n _setReady(state) {\n if (state === this._nodeDataStorage._isReady) {\n return;\n }\n if (!state) {\n this._nodeDataStorage._isReady = false;\n return;\n }\n if (this.onReady) {\n this.onReady(this);\n }\n this._nodeDataStorage._isReady = true;\n }\n /**\n * Get an animation by name\n * @param name defines the name of the animation to look for\n * @returns null if not found else the requested animation\n */\n getAnimationByName(name) {\n for (let i = 0; i < this.animations.length; i++) {\n const animation = this.animations[i];\n if (animation.name === name) {\n return animation;\n }\n }\n return null;\n }\n /**\n * Creates an animation range for this node\n * @param name defines the name of the range\n * @param from defines the starting key\n * @param to defines the end key\n */\n createAnimationRange(name, from, to) {\n // check name not already in use\n if (!this._ranges[name]) {\n this._ranges[name] = Node._AnimationRangeFactory(name, from, to);\n for (let i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {\n if (this.animations[i]) {\n this.animations[i].createRange(name, from, to);\n }\n }\n }\n }\n /**\n * Delete a specific animation range\n * @param name defines the name of the range to delete\n * @param deleteFrames defines if animation frames from the range must be deleted as well\n */\n deleteAnimationRange(name, deleteFrames = true) {\n for (let i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {\n if (this.animations[i]) {\n this.animations[i].deleteRange(name, deleteFrames);\n }\n }\n this._ranges[name] = null; // said much faster than 'delete this._range[name]'\n }\n /**\n * Get an animation range by name\n * @param name defines the name of the animation range to look for\n * @returns null if not found else the requested animation range\n */\n getAnimationRange(name) {\n return this._ranges[name] || null;\n }\n /**\n * Clone the current node\n * @param name Name of the new clone\n * @param newParent New parent for the clone\n * @param doNotCloneChildren Do not clone children hierarchy\n * @returns the new transform node\n */\n clone(name, newParent, doNotCloneChildren) {\n const result = SerializationHelper.Clone(() => new Node(name, this.getScene()), this);\n if (newParent) {\n result.parent = newParent;\n }\n if (!doNotCloneChildren) {\n // Children\n const directDescendants = this.getDescendants(true);\n for (let index = 0; index < directDescendants.length; index++) {\n const child = directDescendants[index];\n child.clone(name + \".\" + child.name, result);\n }\n }\n return result;\n }\n /**\n * Gets the list of all animation ranges defined on this node\n * @returns an array\n */\n getAnimationRanges() {\n const animationRanges = [];\n let name;\n for (name in this._ranges) {\n animationRanges.push(this._ranges[name]);\n }\n return animationRanges;\n }\n /**\n * Will start the animation sequence\n * @param name defines the range frames for animation sequence\n * @param loop defines if the animation should loop (false by default)\n * @param speedRatio defines the speed factor in which to run the animation (1 by default)\n * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)\n * @returns the object created for this animation. If range does not exist, it will return null\n */\n beginAnimation(name, loop, speedRatio, onAnimationEnd) {\n const range = this.getAnimationRange(name);\n if (!range) {\n return null;\n }\n return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);\n }\n /**\n * Serialize animation ranges into a JSON compatible object\n * @returns serialization object\n */\n serializeAnimationRanges() {\n const serializationRanges = [];\n for (const name in this._ranges) {\n const localRange = this._ranges[name];\n if (!localRange) {\n continue;\n }\n const range = {};\n range.name = name;\n range.from = localRange.from;\n range.to = localRange.to;\n serializationRanges.push(range);\n }\n return serializationRanges;\n }\n /**\n * Computes the world matrix of the node\n * @param _force defines if the cache version should be invalidated forcing the world matrix to be created from scratch\n * @returns the world matrix\n */\n computeWorldMatrix(_force) {\n if (!this._worldMatrix) {\n this._worldMatrix = Matrix.Identity();\n }\n return this._worldMatrix;\n }\n /**\n * Releases resources associated with this node.\n * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)\n * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)\n */\n dispose(doNotRecurse, disposeMaterialAndTextures = false) {\n this._nodeDataStorage._isDisposed = true;\n if (!doNotRecurse) {\n const nodes = this.getDescendants(true);\n for (const node of nodes) {\n node.dispose(doNotRecurse, disposeMaterialAndTextures);\n }\n }\n if (!this.parent) {\n this._removeFromSceneRootNodes();\n }\n else {\n this.parent = null;\n }\n // Callback\n this.onDisposeObservable.notifyObservers(this);\n this.onDisposeObservable.clear();\n this.onEnabledStateChangedObservable.clear();\n this.onClonedObservable.clear();\n // Behaviors\n for (const behavior of this._behaviors) {\n behavior.detach();\n }\n this._behaviors.length = 0;\n this.metadata = null;\n }\n /**\n * Parse animation range data from a serialization object and store them into a given node\n * @param node defines where to store the animation ranges\n * @param parsedNode defines the serialization object to read data from\n * @param _scene defines the hosting scene\n */\n static ParseAnimationRanges(node, parsedNode, _scene) {\n if (parsedNode.ranges) {\n for (let index = 0; index < parsedNode.ranges.length; index++) {\n const data = parsedNode.ranges[index];\n node.createAnimationRange(data.name, data.from, data.to);\n }\n }\n }\n /**\n * Return the minimum and maximum world vectors of the entire hierarchy under current node\n * @param includeDescendants Include bounding info from descendants as well (true by default)\n * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors\n * @returns the new bounding vectors\n */\n getHierarchyBoundingVectors(includeDescendants = true, predicate = null) {\n // Ensures that all world matrix will be recomputed.\n this.getScene().incrementRenderId();\n this.computeWorldMatrix(true);\n let min;\n let max;\n const thisAbstractMesh = this;\n if (thisAbstractMesh.getBoundingInfo && thisAbstractMesh.subMeshes) {\n // If this is an abstract mesh get its bounding info\n const boundingInfo = thisAbstractMesh.getBoundingInfo();\n min = boundingInfo.boundingBox.minimumWorld.clone();\n max = boundingInfo.boundingBox.maximumWorld.clone();\n }\n else {\n min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\n max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);\n }\n if (includeDescendants) {\n const descendants = this.getDescendants(false);\n for (const descendant of descendants) {\n const childMesh = descendant;\n childMesh.computeWorldMatrix(true);\n // Filters meshes based on custom predicate function.\n if (predicate && !predicate(childMesh)) {\n continue;\n }\n //make sure we have the needed params to get mix and max\n if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {\n continue;\n }\n const childBoundingInfo = childMesh.getBoundingInfo();\n const boundingBox = childBoundingInfo.boundingBox;\n const minBox = boundingBox.minimumWorld;\n const maxBox = boundingBox.maximumWorld;\n Vector3.CheckExtends(minBox, min, max);\n Vector3.CheckExtends(maxBox, min, max);\n }\n }\n return {\n min: min,\n max: max,\n };\n }\n}\n/**\n * @internal\n */\nNode._AnimationRangeFactory = (_name, _from, _to) => {\n throw _WarnImport(\"AnimationRange\");\n};\nNode._NodeConstructors = {};\n__decorate([\n serialize()\n], Node.prototype, \"name\", void 0);\n__decorate([\n serialize()\n], Node.prototype, \"id\", void 0);\n__decorate([\n serialize()\n], Node.prototype, \"uniqueId\", void 0);\n__decorate([\n serialize()\n], Node.prototype, \"state\", void 0);\n__decorate([\n serialize()\n], Node.prototype, \"metadata\", void 0);\n//# sourceMappingURL=node.js.map","/**\n * Groups all the scene component constants in one place to ease maintenance.\n * @internal\n */\nexport class SceneComponentConstants {\n}\nSceneComponentConstants.NAME_EFFECTLAYER = \"EffectLayer\";\nSceneComponentConstants.NAME_LAYER = \"Layer\";\nSceneComponentConstants.NAME_LENSFLARESYSTEM = \"LensFlareSystem\";\nSceneComponentConstants.NAME_BOUNDINGBOXRENDERER = \"BoundingBoxRenderer\";\nSceneComponentConstants.NAME_PARTICLESYSTEM = \"ParticleSystem\";\nSceneComponentConstants.NAME_GAMEPAD = \"Gamepad\";\nSceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = \"SimplificationQueue\";\nSceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = \"GeometryBufferRenderer\";\nSceneComponentConstants.NAME_PREPASSRENDERER = \"PrePassRenderer\";\nSceneComponentConstants.NAME_DEPTHRENDERER = \"DepthRenderer\";\nSceneComponentConstants.NAME_DEPTHPEELINGRENDERER = \"DepthPeelingRenderer\";\nSceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = \"PostProcessRenderPipelineManager\";\nSceneComponentConstants.NAME_SPRITE = \"Sprite\";\nSceneComponentConstants.NAME_SUBSURFACE = \"SubSurface\";\nSceneComponentConstants.NAME_OUTLINERENDERER = \"Outline\";\nSceneComponentConstants.NAME_PROCEDURALTEXTURE = \"ProceduralTexture\";\nSceneComponentConstants.NAME_SHADOWGENERATOR = \"ShadowGenerator\";\nSceneComponentConstants.NAME_OCTREE = \"Octree\";\nSceneComponentConstants.NAME_PHYSICSENGINE = \"PhysicsEngine\";\nSceneComponentConstants.NAME_AUDIO = \"Audio\";\nSceneComponentConstants.NAME_FLUIDRENDERER = \"FluidRenderer\";\nSceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;\nSceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;\nSceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;\nSceneComponentConstants.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER = 0;\nSceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;\nSceneComponentConstants.STEP_BEFORECAMERADRAW_PREPASS = 0;\nSceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 1;\nSceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 2;\nSceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_PREPASS = 0;\nSceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_LAYER = 1;\nSceneComponentConstants.STEP_BEFORERENDERINGMESH_PREPASS = 0;\nSceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 1;\nSceneComponentConstants.STEP_AFTERRENDERINGMESH_PREPASS = 0;\nSceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 1;\nSceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;\nSceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;\nSceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;\nSceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;\nSceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;\nSceneComponentConstants.STEP_BEFORECLEAR_PREPASS = 1;\nSceneComponentConstants.STEP_BEFORERENDERTARGETCLEAR_PREPASS = 0;\nSceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_PREPASS = 0;\nSceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_LAYER = 1;\nSceneComponentConstants.STEP_AFTERCAMERADRAW_PREPASS = 0;\nSceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 1;\nSceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 2;\nSceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;\nSceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;\nSceneComponentConstants.STEP_AFTERCAMERADRAW_FLUIDRENDERER = 5;\nSceneComponentConstants.STEP_AFTERCAMERAPOSTPROCESS_LAYER = 0;\nSceneComponentConstants.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER = 0;\nSceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;\nSceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 0;\nSceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;\nSceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 2;\nSceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;\nSceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;\nSceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER = 1;\nSceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;\nSceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;\nSceneComponentConstants.STEP_POINTERUP_SPRITE = 0;\n/**\n * Representation of a stage in the scene (Basically a list of ordered steps)\n * @internal\n */\nexport class Stage extends Array {\n /**\n * Hide ctor from the rest of the world.\n * @param items The items to add.\n */\n constructor(items) {\n super(...items);\n }\n /**\n * Creates a new Stage.\n * @returns A new instance of a Stage\n */\n static Create() {\n return Object.create(Stage.prototype);\n }\n /**\n * Registers a step in an ordered way in the targeted stage.\n * @param index Defines the position to register the step in\n * @param component Defines the component attached to the step\n * @param action Defines the action to launch during the step\n */\n registerStep(index, component, action) {\n let i = 0;\n let maxIndex = Number.MAX_VALUE;\n for (; i < this.length; i++) {\n const step = this[i];\n maxIndex = step.index;\n if (index < maxIndex) {\n break;\n }\n }\n this.splice(i, 0, { index, component, action: action.bind(component) });\n }\n /**\n * Clears all the steps from the stage.\n */\n clear() {\n this.length = 0;\n }\n}\n//# sourceMappingURL=sceneComponent.js.map","\n/******************************************************************************\nCopyright (c) Microsoft Corporation.\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n// the startup function\n__webpack_require__.x = function() {\n\t// Load entry module and return exports\n\t// This entry module depends on other loaded chunks and execution need to be delayed\n\tvar __webpack_exports__ = __webpack_require__.O(undefined, [315,568,770,942], function() { return __webpack_require__(4201); })\n\t__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n\treturn __webpack_exports__;\n};\n\n","var deferred = [];\n__webpack_require__.O = function(result, chunkIds, fn, priority) {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar chunkIds = deferred[i][0];\n\t\tvar fn = deferred[i][1];\n\t\tvar priority = deferred[i][2];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every(function(key) { return __webpack_require__.O[key](chunkIds[j]); })) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","// define getter functions for harmony exports\n__webpack_require__.d = function(exports, definition) {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = function(chunkId) {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce(function(promises, key) {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks and sibling chunks for the entrypoint\n__webpack_require__.u = function(chunkId) {\n\t// return url for filenames based on template\n\treturn \"\" + {\"315\":\"c2b82a6e\",\"568\":\"87a06baf\",\"770\":\"088d5a4e\",\"942\":\"256b551e\"}[chunkId] + \"-\" + {\"315\":\"1e3631aca5d8280099d6\",\"568\":\"5d3ac30d48950f0f9b7a\",\"770\":\"4f2cb64570bdf3425971\",\"942\":\"1832dd584c826cd29ac8\"}[chunkId] + \".js\";\n};","// This function allow to reference all chunks\n__webpack_require__.miniCssF = function(chunkId) {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }","__webpack_require__.p = \"https://codecave.pro-new/\";","// no baseURI\n\n// object to store loaded chunks\n// \"1\" means \"already loaded\"\nvar installedChunks = {\n\t475: 1\n};\n\n// importScripts chunk loading\nvar installChunk = function(data) {\n\tvar chunkIds = data[0];\n\tvar moreModules = data[1];\n\tvar runtime = data[2];\n\tfor(var moduleId in moreModules) {\n\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t}\n\t}\n\tif(runtime) runtime(__webpack_require__);\n\twhile(chunkIds.length)\n\t\tinstalledChunks[chunkIds.pop()] = 1;\n\tparentChunkLoadingFunction(data);\n};\n__webpack_require__.f.i = function(chunkId, promises) {\n\t// \"1\" is the signal for \"already loaded\"\n\tif(!installedChunks[chunkId]) {\n\t\tif(true) { // all chunks have JS\n\t\t\timportScripts(__webpack_require__.p + __webpack_require__.u(chunkId));\n\t\t}\n\t}\n};\n\nvar chunkLoadingGlobal = self[\"webpackChunkcode_cave\"] = self[\"webpackChunkcode_cave\"] || [];\nvar parentChunkLoadingFunction = chunkLoadingGlobal.push.bind(chunkLoadingGlobal);\nchunkLoadingGlobal.push = installChunk;\n\n// no HMR\n\n// no HMR manifest","var next = __webpack_require__.x;\n__webpack_require__.x = function() {\n\treturn Promise.all([315,568,770,942].map(__webpack_require__.e, __webpack_require__)).then(next);\n};","// run startup\nvar __webpack_exports__ = __webpack_require__.x();\n"],"names":["Action","constructor","triggerOptions","condition","this","onBeforeExecuteObservable","parameter","trigger","_triggerParameter","_nextActiveAction","_condition","_prepare","getTriggerParameter","setTriggerParameter","value","_evaluateConditionForCurrentFrame","currentRenderId","_actionManager","getScene","getRenderId","_evaluationId","_currentResult","isValid","_executeCurrent","evt","notifyObservers","execute","skipToNextActiveAction","_child","then","action","_getProperty","propertyPath","_getEffectiveTarget","target","serialize","parent","_serialize","serializedAction","serializationObject","type","children","name","properties","serializedCondition","push","_SerializeValueAsString","toString","x","y","z","r","g","b","a","_GetTargetProperty","targetType","_isMesh","_isLight","_isCamera","_isMaterial","_isScene","Condition","actionManager","ValueCondition","IsEqual","_IsEqual","IsDifferent","_IsDifferent","IsGreater","_IsGreater","IsLesser","_IsLesser","operator","super","_target","_effectiveTarget","_property","check","equals","GetOperatorName","static","predicate","state","DoNothingAction","SetParentAction","_parent","invertParentWorldMatrix","getWorldMatrix","clone","invert","position","TransformCoordinates","func","stopAnimation","from","to","loop","beginAnimation","String","Warn","markAsDirty","enableChildrenConditions","index","length","combine","i","ActionManager","scene","LastCreatedScene","_scene","actionManagers","dispose","indexOf","actions","Triggers","splice","hasSpecificTriggers","triggers","hasSpecificTriggers2","triggerA","triggerB","hasSpecificTrigger","parameterPredicate","hasPointerTriggers","OnPickTrigger","OnPointerOutTrigger","hasPickTriggers","OnPickUpTrigger","registerAction","OnEveryFrameTrigger","_registeredActions","unregisterAction","processTrigger","OnKeyUpTrigger","OnKeyDownTrigger","sourceEvent","keyCode","toLowerCase","lowerCase","key","unicode","charCode","fromCharCode","split","root","Array","triggerObject","GetTriggerName","Node","DeepCopy","mesh","_meshId","id","parsedActions","object","parseParameter","floatValue","parseFloat","isNaN","effectiveTarget","values","FromArray","traverse","parsedAction","combineArray","detached","parameters","j","NothingTrigger","getMaterialByName","getNodeByName","getSoundByName","param","newAction","params","internalClassType","instantiate","nothing","triggerParams","getMeshByName","getMeshById","OnLeftPickTrigger","OnRightPickTrigger","OnCenterPickTrigger","OnPickDownTrigger","OnDoublePickTrigger","OnPickOutTrigger","OnLongPressTrigger","OnPointerOverTrigger","OnIntersectionEnterTrigger","OnIntersectionExitTrigger","sound","_sound","undefined","play","stop","AnimationKeyInterpolation","AnimationRange","Size","width","height","getClassName","getHashCode","hash","copyFrom","src","copyFromFloats","set","multiplyByFloats","w","h","other","surface","add","otherSize","subtract","start","end","amount","targetProperty","framePerSecond","totalFrame","loopMode","easingFunction","dataType","isFinite","ANIMATIONTYPE_FLOAT","ANIMATIONTYPE_QUATERNION","ANIMATIONTYPE_VECTOR3","ANIMATIONTYPE_VECTOR2","ANIMATIONTYPE_COLOR3","ANIMATIONTYPE_COLOR4","ANIMATIONTYPE_SIZE","animation","keys","frame","setKeys","setEasingFunction","property","animationType","ANIMATIONLOOPMODE_CONSTANT","onAnimationEnd","_PrepareAnimation","beginDirectAnimation","node","directDescendantsOnly","beginDirectHierarchyAnimation","animations","sourceAnimation","referenceFrame","range","cloneOriginal","clonedName","_keys","startIndex","firstKey","endIndex","lastKey","valueStore","referenceValue","referencePosition","Vector3","referenceQuaternion","Quaternion","referenceScaling","keyPosition","keyQuaternion","keyScaling","referenceFound","rangeValue","getRange","fromKeyFound","toKeyFound","_getKeyValue","currentKey","nextKey","animationState","repeatCount","_interpolate","normalize","conjugateInPlace","ANIMATIONTYPE_MATRIX","decompose","subtractInPlace","divideInPlace","multiplyToRef","ComposeToRef","subtractToRef","targetValue","host","frameRate","transition","duration","endFrame","runtimeAnimations","_runtimeAnimations","hasRunningRuntimeAnimations","runtimeAnimation","isStopped","enableBlending","_easingFunction","_events","blendingSpeed","_ranges","targetPropertyPath","ANIMATIONLOOPMODE_CYCLE","uniqueId","_UniqueIdGenerator","fullDetails","ret","Object","first","addEvent","event","sort","removeEvents","getEvents","createRange","deleteRange","deleteFrames","getKeys","getHighestFrame","nKeys","getEasingFunction","floatInterpolateFunction","startValue","endValue","gradient","Lerp","floatInterpolateFunctionWithTangents","outTangent","inTangent","Hermite","quaternionInterpolateFunction","Slerp","quaternionInterpolateFunctionWithTangents","vector3InterpolateFunction","vector3InterpolateFunctionWithTangents","vector2InterpolateFunction","vector2InterpolateFunctionWithTangents","sizeInterpolateFunction","color3InterpolateFunction","color3InterpolateFunctionWithTangents","color4InterpolateFunction","color4InterpolateFunctionWithTangents","evaluate","currentFrame","highLimitValue","keysLength","startKey","endKey","interpolation","STEP","useTangent","frameDelta","ease","ANIMATIONLOOPMODE_YOYO","ANIMATIONLOOPMODE_RELATIVE","offsetValue","quatValue","scale","addInPlace","vec3Value","vec2Value","color3Value","color4Value","AllowMatricesInterpolation","matrixInterpolateFunction","workValue","result","AllowMatrixDecomposeForInterpolation","DecomposeLerpToRef","DecomposeLerp","LerpToRef","join","slice","loopBehavior","animationKey","asArray","ranges","source","left","right","toFixed","parsedAnimation","data","_inTangent","Zero","_outTangent","keyData","destination","AppendSerializedAnimations","url","Promise","resolve","reject","request","addEventListener","readyState","status","JSON","parse","responseText","output","serializedAnimation","Parse","open","send","snippetId","snippet","jsonPayload","outputs","SnippetUrl","replace","CreateFromSnippetAsync","ParseFromSnippetAsync","N","_AnimationRangeFactory","stopOtherAnimations","onInterpolationDone","onInterpolationDoneObservable","_staticOffsetValueQuaternion","freeze","_staticOffsetValueVector3","_staticOffsetValueVector2","_staticOffsetValueSize","_staticOffsetValueColor3","Black","RuntimeAnimation","_currentFrame","weight","_weight","currentValue","_currentValue","targetPath","_targetPath","_currentActiveTarget","isAdditive","_host","_originalValue","_originalBlendValue","_offsetsCache","_highLimitsCache","_stopped","_blendingFactor","_directTarget","_ratioOffset","_previousDelay","_previousRatio","_targetIsArray","_animation","_activeTargets","_animationState","_getCorrectLoopMode","_minFrame","_maxFrame","_minValue","_maxValue","newKey","_preparePath","_getOriginalValues","events","forEach","e","_clone","_enableBlending","animationPropertiesOverride","targetIndex","reset","restoreOriginal","_setValue","isDone","setValue","originalValue","getRestPose","m","_UniversalLerp","_registerTargetForLateAnimationBinding","goToFrame","onlyOnce","_prepareForSpeedRatioChange","newSpeedRatio","newRatio","animate","delay","speedRatio","returnValue","ratio","Math","abs","sin","PI","keyOffset","fromValue","toValue","syncRoot","masterFrame","fromFrame","toFrame","_onLoop","Bone","_matrix","_compose","_localMatrix","_needToCompose","updateFlag","_markAsDirtyAndDecompose","skeleton","parentBone","localMatrix","restMatrix","bindMatrix","_a","_index","_scalingDeterminant","_needToDecompose","_linkedTransformNode","_waitingTransformNodeId","_skeleton","Identity","_restMatrix","_bindMatrix","_absoluteMatrix","_absoluteBindMatrix","_absoluteInverseBindMatrix","_finalMatrix","bones","setParent","_updateAbsoluteBindMatrices","getSkeleton","_parentNode","getParent","getChildren","getIndex","newParent","updateAbsoluteBindMatrices","getLocalMatrix","getBindMatrix","getBaseMatrix","getRestMatrix","setRestMatrix","matrix","setRestPose","getBindPose","setBindMatrix","updateMatrix","setBindPose","getFinalMatrix","returnToRest","localScaling","localRotation","localPosition","rotationQuaternion","scaling","getAbsoluteInverseBindMatrix","getInvertedAbsoluteTransform","getAbsoluteMatrix","getAbsoluteTransform","linkTransformNode","transformNode","_numBonesWithLinkedTransformNode","getTransformNode","_decompose","_localPosition","newPosition","_markAsDirtyAndCompose","rotation","getRotation","newRotation","setRotation","_localRotation","setRotationQuaternion","getScale","newScaling","setScale","_localScaling","updateLocalMatrix","updateChildren","invertToRef","determinant","_currentRenderId","_childUpdateId","_markAsDirty","_updatePosition","vec","space","LOCAL","tNode","translationMode","lm","addAtIndex","setTranslationFromFloats","wm","computeAbsoluteMatrices","tmat","_TmpMats","tvec","_TmpVecs","IdentityToRef","TransformCoordinatesToRef","translate","setPosition","setAbsolutePosition","WORLD","scaleChildren","locMat","scaleMat","ScalingToRef","child","cm","multiplyAtIndex","getScaleToRef","setYawPitchRoll","yaw","pitch","roll","quat","_TmpQuat","RotationYawPitchRollToRef","rotMatInv","_getAbsoluteInverseMatrixUnscaledToRef","rotMat","_rotateWithMatrix","rotate","axis","rmat","RotationAxisToRef","setAxisAngle","angle","FromQuaternionToRef","setRotationMatrix","FromRotationMatrixToRef","rotMat2","lmat","lx","ly","lz","parentScale","parentScaleInv","scaleMatrix","getPosition","pos","getPositionToRef","getAbsolutePosition","getAbsolutePositionToRef","poseMatrix","getPoseMatrix","len","computeAbsoluteTransforms","getDirection","localAxis","getDirectionToRef","mat","TransformNormalToRef","getRotationToRef","getRotationQuaternionToRef","toEulerAnglesToRef","getRotationQuaternion","amat","getRotationMatrix","getRotationMatrixToRef","getAbsolutePositionFromLocal","getAbsolutePositionFromLocalToRef","getLocalPositionFromAbsolute","getLocalPositionFromAbsoluteToRef","setCurrentPoseAsRest","BuildArray","Animatable","_syncRoot","min","max","_speedRatio","_goToFrame","loopAnimation","onAnimationLoop","_localDelayOffset","_pausedDelay","_manualJumpDelay","_paused","_frameToSyncFromJump","disposeOnEnd","animationStarted","onAnimationEndObservable","onAnimationLoopObservable","appendAnimations","_activeAnimatables","syncWith","getAnimations","newRuntimeAnimation","getAnimationByTargetProperty","getRuntimeAnimationByTargetProperty","disableBlending","fps","pause","restart","_raiseOnAnimationEnd","animationName","targetMask","useGlobalSplice","idx","waitAsync","_animate","running","isRunning","clear","prototype","animationsEnabled","now","Now","_animationTimeLast","_pendingData","deltaTime","useConstantAnimationDeltaTime","animationTimeScale","animatables","_animationTime","animationTime","animatable","_processLateAnimationBindings","beginWeightedAnimation","returnedAnimatable","stopCurrent","shouldRunTargetAnimations","getAnimatables","beginHierarchyAnimation","getDescendants","temp","getAnimatableByTarget","getAllAnimatablesByTarget","stopAllAnimations","group","animationGroups","_registeredForLateAnimationBindings","pushNoDuplicate","_lateAnimationHolders","totalWeight","totalAdditiveWeight","additiveAnimations","_processLateAnimationBindingsForMatrices","holder","normalizer","finalPosition","finalScaling","finalQuaternion","originalAnimation","skipOverride","scaleInPlace","animIndex","currentPosition","currentScaling","currentQuaternion","scaleAndAddToRef","Dot","SlerpToRef","Matrix","_processLateAnimationBindingsForQuaternions","refQuaternion","cumulativeQuaternion","quaternions","weights","cumulativeAmount","path","matrixDecomposeMode","finalValue","copyAnimationRange","rangeName","frameOffset","rescaleAsRequired","skelDimensionsRatio","sourceRange","sourceKeys","sourceBoneLength","sourceParent","parentScalingReqd","parentRatio","dimensionsScalingReqd","destKeys","orig","origTranslation","getTranslation","setTranslation","multiplyInPlace","Orientation","Angle","radians","_radians","degrees","delta","theta","atan2","Arc2","startPoint","midPoint","endPoint","pow","startToMid","midToEnd","det","centerPoint","radius","startAngle","BetweenTwoPoints","a1","a2","a3","orientation","CW","CCW","FromDegrees","_points","_length","closed","addLineTo","newPoint","previousPoint","addArcTo","midX","midY","endX","endY","numberOfSegments","arc","increment","currentAngle","cos","addQuadraticCurveTo","controlX","controlY","equation","t","val0","val1","val2","step","addBezierCurveTo","originTangentX","originTangentY","destinationTangentX","destinationTangentY","val3","isPointInside","point","isInside","count","p","q","edgeLow","edgeHigh","edgeDx","edgeDy","Number","EPSILON","perpEdge","close","lastPoint","area","n","getPoints","getPointAtLengthPosition","normalizedLengthPosition","lengthPosition","previousOffset","bToA","nextOffset","dir","localOffset","Path3D","firstNormal","raw","alignTangentsWithPath","_curve","_distances","_tangents","_normals","_binormals","_pointAtData","previousPointArrayIndex","subPosition","interpolateReady","interpolationMatrix","_raw","_alignTangentsWithPath","_compute","getCurve","getTangents","getNormals","getBinormals","getDistances","getPointAt","_updatePointAtData","getTangentAt","interpolated","Forward","getNormalAt","Right","getBinormalAt","UpReadOnly","getDistanceAt","getPreviousPointIndexAt","getSubPositionAt","getClosestPositionTo","smallestDistance","MAX_VALUE","closestPosition","tangent","subLength","Distance","distance","_start","curvePoints","slicePoints","update","l","_getFirstNonNullVector","tg0","pp0","_normalVector","prev","cur","curTang","prevNor","prevBinor","Cross","_getLastNonNullVector","NaN","nNVector","nLVector","vt","va","normal0","tgl","WithinEpsilon","CrossToRef","interpolateTNB","_updateInterpolationMatrix","_setPointAtData","currentPoint","currentLength","targetLength","diff","parentIndex","tangentFrom","normalFrom","binormalFrom","tangentTo","normalTo","binormalTo","quatFrom","RotationQuaternionFromAxis","quatTo","toRotationMatrix","Curve3","v0","v1","v2","nbPoints","bez","v3","p1","t1","p2","t2","nSeg","hermite","points","catmullRom","pointsCount","c","CatmullRom","totalPoints","apply","second","third","steps","fullCircle","vec1","vec2","vec3","zAxis","len4","len1_sq","lengthSquared","len2_sq","len3_sq","len4_sq","center","xAxis","yAxis","dStep","equalsWithEpsilon","_computeLength","continue","curve","continuedPoints","EasingFunction","_easingMode","EASINGMODE_EASEIN","setEasingMode","easingMode","getEasingMode","easeInCore","Error","EASINGMODE_EASEOUT","EASINGMODE_EASEINOUT","CircleEase","sqrt","QuadraticEase","SineEase","AnimationEvent","TargetedAnimation","targetId","AnimationGroup","_from","_to","isStarted","_isStarted","isPlaying","_isPaused","_animatables","_loopAnimation","_isAdditive","targetedAnimations","_targetedAnimations","_parentContainer","onAnimationGroupLoopObservable","onAnimationGroupEndObservable","onAnimationGroupPauseObservable","onAnimationGroupPlayObservable","metadata","_animationLoopFlags","getUniqueId","addAnimationGroup","addTargetedAnimation","targetedAnimation","removeTargetedAnimation","beginFrame","_processLoop","_animationLoopCount","_checkAnimationGroupEnded","list","curIndex","setWeightForAllAnimatables","syncAllAnimationsWith","newName","targetConverter","cloneAnimations","newGroup","targetAnimation","targetedAnimationIndex","HasTags","tags","GetTags","parsedAnimationGroup","animationGroup","morphTarget","getMorphTargetById","targetNode","getNodeById","AddTagsTo","sourceAnimationGroup","MakeAnimationAdditive","_instancedMeshFactory","instance","InstancedMesh","instancedBuffers","_indexInSourceMeshInstanceArray","_distanceToCamera","addInstance","_sourceMesh","_unIndexed","getAnimationRanges","createAnimationRange","infiniteDistance","setPivotMatrix","getPivotMatrix","refreshBoundingInfo","_syncSubMeshes","lightSources","_lightSources","_resyncLightSources","_resyncLightSource","_removeLightSource","receiveShadows","_value","material","visibility","renderingGroupId","getTotalVertices","getTotalIndices","sourceMesh","createInstance","isReady","completeCheck","getVerticesData","kind","copyWhenShared","forceCopy","setVerticesData","updatable","stride","updateVerticesData","updateExtends","makeItUnique","setIndices","indices","totalVertices","isVerticesDataPresent","getIndices","_positions","applySkeleton","applyMorph","hasBoundingInfo","getBoundingInfo","isLocked","bias","geometry","boundingBias","_refreshBoundingInfo","_getPositionData","_preActivate","_currentLOD","_activate","renderId","intermediateRendering","subMeshes","_getWorldMatrixDeterminant","_internalAbstractMeshDataInfo","_actAsRegularMesh","_registerInstanceForRenderId","_isActiveIntermediate","_onlyForInstancesIntermediate","_isActive","_onlyForInstances","_postActivate","edgesShareWithInstances","_edgesRenderer","isEnabled","_renderingGroup","_edgesRenderers","customInstances","billboardMode","BILLBOARDMODE_NONE","_masterMesh","_billboardWorldMatrix","tempMaster","computeWorldMatrix","isAnInstance","getLOD","camera","sourceMeshLODLevels","getLODLevels","boundingInfo","boundingSphere","_preActivateForIntermediateRendering","releaseSubMeshes","_generatePointsArray","_updateBoundingInfo","worldMatrixFromCache","buildBoundingInfo","absolutePosition","_updateSubMeshesBoundingInfo","doNotCloneChildren","newSourceMesh","meshes","onClonedObservable","doNotRecurse","disposeMaterialAndTextures","removeInstance","_serializeAsParent","parentId","parentInstanceIndex","instantiateHierarchy","options","onNewNodeCreated","newSourcedMesh","getChildTransformNodes","registerInstancedBuffer","_b","_userInstancedBuffersStorage","vertexBuffers","instances","strides","sizes","vertexArrayObjects","getEngine","getCaps","vertexArrayObject","Float32Array","_invalidateInstanceVertexArrayObject","_markSubMeshesAsAttributesDirty","_processInstancedBuffers","visibleInstances","renderSelf","instanceCount","size","expectedSize","offset","toArray","copyToArray","instanceIndex","updateDirectly","releaseVertexArrayObject","_disposeInstanceSpecificData","_instanceDataStorage","instancesBuffer","_range","_inverseSquaredRange","intensityMode","_intensityMode","_computePhotometricScale","_radius","shadowEnabled","_shadowEnabled","_markMeshesAsLightDirty","includedOnlyMeshes","_includedOnlyMeshes","_hookArrayForIncludedOnly","excludedMeshes","_excludedMeshes","_hookArrayForExcluded","excludeWithLayerMask","_excludeWithLayerMask","_resyncMeshes","includeOnlyWithLayerMask","_includeOnlyWithLayerMask","lightmapMode","_lightmapMode","diffuse","specular","falloffType","FALLOFF_DEFAULT","intensity","_photometricScale","INTENSITYMODE_AUTOMATIC","renderPriority","_shadowGenerators","_excludedMeshesIds","_includedOnlyMeshesIds","addLight","_uniformBuffer","_buildUniformLayout","transferTexturesToEffect","effect","lightIndex","_bindLight","useSpecular","iAsString","needUpdate","bindToEffect","_renderId","_lastUseSpecular","useUbo","scaledIntensity","getScaledIntensity","transferToEffect","scaleToRef","Color3","updateColor4","shadowsEnabled","shadowGenerator","getShadowGenerator","activeCamera","bindShadowLight","bindUniformBuffer","getTypeID","_syncParentEnabledState","isDisposed","setEnabled","get","getShadowGenerators","canAffectMesh","layerMask","iterator","next","done","lights","removeLight","GetConstructorFromName","clonedLight","Clone","Serialize","excludedMeshesIds","includedOnlyMeshesIds","serializeAnimationRanges","constructorFunc","Construct","parsedLight","light","_waitingParentId","_waitingParentInstanceIndex","animationIndex","internalClass","ParseAnimationRanges","autoAnimate","autoAnimateFrom","autoAnimateTo","autoAnimateLoop","autoAnimateSpeed","array","oldPush","items","item","oldSplice","deleteCount","deleted","_markSubMeshesAsLightDirty","_getPhotometricScale","resetCachedMaterial","photometricScale","lightTypeID","photometricMode","LIGHTTYPEID_DIRECTIONALLIGHT","INTENSITYMODE_ILLUMINANCE","INTENSITYMODE_LUMINOUSINTENSITY","LIGHTTYPEID_POINTLIGHT","LIGHTTYPEID_SPOTLIGHT","INTENSITYMODE_LUMINOUSPOWER","INTENSITYMODE_LUMINANCE","apexAngleRadians","LIGHTTYPEID_HEMISPHERICLIGHT","_reorderLightsInScene","_renderPriority","requireLightSorting","sortLightsByPriority","FALLOFF_PHYSICAL","FALLOFF_GLTF","FALLOFF_STANDARD","LIGHTMAP_DEFAULT","LIGHTMAP_SPECULAR","LIGHTMAP_SHADOWSONLY","KeepAssets","InstantiatedEntries","rootNodes","skeletons","o","AssetContainer","_wasAddedToScene","onDisposeObservable","_onContextRestoredObserver","onContextRestoredObservable","geometries","_rebuild","system","particleSystems","rebuild","texture","textures","_topologicalSort","nodes","nodesUidMap","Map","dependencyGraph","dependsOn","dependedBy","nodeId","Set","masterMesh","has","childId","sortedNodes","leaves","delete","visitList","nodeToVisit","shift","dependedByVisitedNode","dependedByVisitedNodeId","dependsOnDependedByVisitedNode","console","error","_addNodeAndDescendantsToList","addedIds","rootNode","_isNodeInContainer","transformNodes","cameras","_isValidHierarchy","instantiateModelsToScene","nameFunction","cloneMaterials","conversionMap","storeMap","alreadySwappedSkeletons","alreadySwappedMaterials","localOptions","assign","doNotInstantiate","nodesToSort","idsOnSortList","onNewCreated","clonedMesh","morphTargetManager","oldMorphTargetManager","numTargets","oldTarget","getTarget","newTarget","onClone","replicatedParentId","replicatedParent","sourceMaterial","swap","multi","subMaterials","map","multiMaterials","addMultiMaterial","materials","addMaterial","instancedNode","replicatedSourceId","replicatedInstancedNode","canInstance","replicatedNode","s","copy","bone","addAllToScene","addToScene","environmentTexture","component","_serializableComponents","addFromContainer","remove","addCamera","addMesh","addSkeleton","addAnimation","morphTargetManagers","addMorphTargetManager","addGeometry","addTransformNode","addActionManager","addTexture","reflectionProbes","addReflectionProbe","removeAllFromScene","removeFromScene","removeFromContainer","removeCamera","removeMesh","removeSkeleton","removeAnimation","removeAnimationGroup","removeMultiMaterial","removeMaterial","removeMorphTargetManager","removeGeometry","removeTransformNode","removeActionManager","removeTexture","removeReflectionProbe","_moveAssets","sourceAssets","targetAssets","keepAssets","asset","move","keepAsset","moveAllFromScene","hasOwnProperty","call","createRootMesh","rootMesh","addChild","unshift","mergeAnimationsTo","_targetConverter","getTransformNodeByName","getMorphTargetByName","getNodes","nodeInAC","nodeInScene","animationInAC","animationsWithSameProperty","filter","animationInScene","animationWithSameProperty","concat","newAnimationGroups","animationGroupInAC","AudioEngineFactory","hostElement","audioContext","audioDestination","AudioEngine","_audioContextInitialized","unlocked","_muteButton","_displayMuteButton","_initializeAudioContext","_audioContext","_audioDestination","canUseWebAudio","WarnedWebAudioUnsupported","isMP3supported","isOGGsupported","useCustomUnlockedButton","onAudioUnlockedObservable","onAudioLockedObservable","_tryToRun","_onResize","_moveButtonToTopLeft","window","AudioContext","audioElem","document","createElement","_hostElement","canPlayType","lock","_triggerSuspendedState","unlock","_triggerRunningState","_resumeAudioContext","resume","masterGain","createGain","gain","connect","message","_hideMuteButton","catch","className","title","css","SVGSVGElement","style","appendChild","createTextNode","getElementsByTagName","body","top","offsetTop","offsetLeft","removeChild","_connectedAnalyser","stopDebugCanvas","disconnect","removeEventListener","getGlobalVolume","setGlobalVolume","newVolume","connectToAnalyser","analyser","connectAudioNodes","Sound","_loop","updateOptions","currentTime","_htmlAudioElement","audioEngine","isPaused","timeSinceLastStart","_startTime","_currentTime","spatialSound","_spatialSound","newValue","_createSpatialParameters","urlOrArrayBuffer","readyToPlayCallback","_c","_d","_e","autoplay","useCustomAttenuation","refDistance","rolloffFactor","maxDistance","distanceModel","onEndedObservable","_panningModel","_playbackRate","_streaming","_position","_localDirection","_volume","_isReadyToPlay","_isDirectional","_coneInnerAngle","_coneOuterAngle","_coneOuterGain","_isOutputConnected","_urlType","_SceneComponentInitialization","_readyToPlayCallback","_customAttenuationFunction","currentVolume","currentDistance","volume","playbackRate","streaming","_offset","_soundGain","_inputAudioNode","_outputAudioNode","mainSoundTrack","addSound","validParameter","ArrayBuffer","HTMLMediaElement","MediaStream","AudioBuffer","isArray","urls","codecSupportedFound","_streamingSource","createMediaElementSource","createMediaStreamSource","byteLength","_soundLoaded","_audioBufferLoaded","skipCodecCheck","Audio","controls","SetCorsBehavior","preload","load","_loadFile","exception","removeSound","setTimeout","ex","soundTrackId","soundTracks","_soundPanner","_soundSource","_audioBuffer","_connectedTransformNode","_registerFunc","unregisterAfterWorldMatrixUpdate","buffer","audioData","decodeAudioData","err","setAudioBuffer","audioBuffer","_f","_g","_h","_j","_k","_setOffset","setVolume","_updateSpatialParameters","loopStart","loopEnd","headphone","createPanner","panningModel","switchPanningModelToHRTF","_switchPanningModel","switchPanningModelToEqualPower","connectToSoundTrackAudioNode","soundTrackAudioNode","setDirectionalCone","coneInnerAngle","coneOuterAngle","coneOuterGain","directionalConeInnerAngle","directionalConeOuterAngle","positionX","positionY","positionZ","setLocalDirectionToMesh","newLocalDirection","_updateDirection","direction","TransformNormal","orientationX","orientationY","orientationZ","updateDistanceFromListener","audioListenerPositionProvider","getDistanceToCamera","setAttenuationFunction","callback","time","audioEnabled","startTime","setOrientation","onended","_onended","tryToPlay","playPromise","addOnce","oldSource","createBufferSource","actualOffset","stopTime","cancelScheduledValues","setValueAtTime","linearRampToValueAtTime","setPlaybackRate","newPlaybackRate","getPlaybackRate","getVolume","attachToMesh","_onRegisterAfterWorldMatrixUpdate","registerAfterWorldMatrixUpdate","detachFromMesh","centerWorld","setBufferAndRun","clonedSound","getAudioBuffer","currentOptions","getSoundSource","getSoundGain","connectedMeshId","isDirectional","localDirectionToMesh","parsedSound","rootUrl","sourceSound","soundName","soundUrl","newSound","removePendingData","addPendingData","soundPosition","connectedMesh","_","SoundTrack","_isInitialized","soundCollection","_options","mainTrack","_initializeSoundTrackAudioGraph","AddParser","NAME_AUDIO","parsedData","container","loadedSound","loadedSounds","sounds","cache","defineProperty","compo","_getComponent","AudioSceneComponent","_addComponent","_mainSoundTrack","enumerable","configurable","sdIndex","enableAudio","disableAudio","switchAudioModeForHeadphones","switchAudioModeForNormalSpeakers","audioListenerRotationProvider","audioPositioningRefreshRate","_audioEnabled","_headphone","_cachedCameraDirection","_cachedCameraPosition","_lastCheck","_invertMatrixTemp","_cameraDirectionTemp","register","_afterRenderStage","registerStep","STEP_AFTERRENDER_AUDIO","_afterRender","soundtrack","soundId","scIndex","suspend","listeningCamera","activeCameras","listener","globalPosition","rigCameras","getViewMatrix","_CameraDirection","WeightedSound","_sounds","_weights","weightSum","invWeightSum","_currentIndex","startOffset","randomValue","random","total","BakedVertexAnimationManager","_texture","_isEnabled","animationParameters","bakedVertexAnimationManager","bind","useInstances","getSize","setFloat2","setFloat","setVector4","setTexture","copyTo","setAnimationParameters","startFrame","speedFramesPerSecond","forceDisposeTextures","vatMap","wrapU","_wrapU","wrapV","_wrapV","coordinatesMode","isCube","is3D","is2DArray","_shareDepth","internalTexture","wrapR","anisotropicFilteringLevel","delayLoadState","_engine","_cachedSize","_cachedBaseSize","_initialSamplingMode","_IsRenderTargetWrapper","delayLoad","getInternalTexture","_size","getBaseSize","baseWidth","baseHeight","samplingMode","updateSamplingMode","updateTextureSamplingMode","releaseInternalTexture","hasAlpha","_hasAlpha","markAllMaterialsAsDirty","hasTexture","getAlphaFromRGB","_getAlphaFromRGB","coordinatesIndex","_coordinatesIndex","_coordinatesMode","_isCube","gammaSpace","_gammaSpace","_useSRGBBuffer","gamma","_markAllSubMeshesAsTexturesDirty","isRGBD","_isRGBD","noMipmap","lodGenerationOffset","_lodGenerationOffset","lodGenerationScale","_lodGenerationScale","linearSpecularLOD","_linearSpecularLOD","irradianceTexture","_irradianceTexture","uid","_uid","onDispose","_onDisposeObserver","isBlocking","loadingError","_loadingError","errorObject","_errorObject","sceneOrEngine","reservedDataStore","level","optimizeUVAllocation","DEFAULT_ANISOTROPIC_FILTERING_LEVEL","invertZ","lodLevelInAlpha","isRenderTarget","_prefiltered","_forceSerialize","_IsScene","_getEngine","checkTransformsAreIdentical","getTextureMatrix","IdentityReadOnly","getReflectionTextureMatrix","getRefractionTextureMatrix","isReadyOrNotBlocking","canRescale","_getFromCache","sampling","invertY","useSRGBBuffer","engine","correctedUseSRGBBuffer","_getUseSRGBBuffer","texturesCache","getLoadedTexturesCache","texturesCacheEntry","generateMipMaps","incrementReferences","textureType","textureFormat","format","readPixels","faceIndex","flushRenderer","noDataConversion","maxWidth","maxHeight","round","_readTexturePixels","_readPixelsSync","_readTexturePixelsSync","_lodTextureHigh","_lodTextureMid","_lodTextureLow","onTextureRemovedObservable","allowEmptyName","numRemaining","onLoadObservable","GenerateBase64StringFromPixelData","pixels","BYTES_PER_ELEMENT","npixels","Uint8Array","val","canvas","ctx","getContext","imageData","createImageData","putImageData","canvas2","ctx2","drawImage","toDataURL","GenerateBase64StringFromTexture","async","GenerateBase64StringFromTextureAsync","_noMipmap","mimeType","_mimeType","_isBlocking","_invertY","noMipmapOrOptions","TRILINEAR_SAMPLINGMODE","onLoad","onError","deleteBuffer","loaderOptions","creationFlags","forcedExtension","uOffset","vOffset","uScale","vScale","uAng","vAng","wAng","uRotationCenter","vRotationCenter","wRotationCenter","homogeneousRotationInUVTransform","inspectableCustomProperties","_rowGenerationMatrix","_cachedTextureMatrix","_projectionModeMatrix","_t0","_t1","_t2","_cachedUOffset","_cachedVOffset","_cachedUScale","_cachedVScale","_cachedUAng","_cachedVAng","_cachedWAng","_cachedReflectionProjectionMatrixId","_cachedURotationCenter","_cachedVRotationCenter","_cachedWRotationCenter","_cachedHomogeneousRotationInUVTransform","_cachedReflectionTextureMatrix","_cachedReflectionUOffset","_cachedReflectionVOffset","_cachedReflectionUScale","_cachedReflectionVScale","_cachedReflectionCoordinatesMode","_buffer","_deleteBuffer","_format","_delayedOnLoad","_delayedOnError","UseOpenGLOrientationForUV","_loaderOptions","_creationFlags","_forcedExtension","onBeforeTextureInitObservable","_invertVScale","_cachedWrapU","_cachedWrapV","_cachedWrapR","hasObservers","errorHandler","OnTextureLoadErrorObservable","SetImmediate","loadObserver","onLoadedObservable","onErrorObservable","useDelayedTextureLoading","createTexture","updateURL","startsWith","_prepareRowForTextureGeneration","TransformCoordinatesFromFloatsToRef","uBase","TranslationToRef","setRowFromFloats","FromValuesToRef","PROJECTION_MODE","getProjectionMatrix","flagMaterialsAsTextureDirty","PLANAR_MODE","projectionMatrix","getActiveTextures","savedName","SerializeBuffers","_SerializeInternalTextureUniqueId","ForceSerializeBuffers","substr","base64String","_features","supportSyncTextureRead","internalTextureUniqueId","parsedTexture","customType","parsedCustomTexture","Instantiate","_samplingMode","_CubeTextureParser","hasInternalTextureUniqueId","onLoaded","_setUniqueId","mirrorPlane","mirrorTexture","_CreateMirror","renderTargetSize","_waitingRenderList","renderList","renderTargetTexture","probe","cubeTexture","_CreateRenderTargetTexture","CreateFromBase64String","UseSerializedUrlIfAny","jsonTexture","NEAREST_SAMPLINGMODE","NEAREST_NEAREST_MIPLINEAR","BILINEAR_SAMPLINGMODE","LINEAR_LINEAR_MIPNEAREST","LINEAR_LINEAR_MIPLINEAR","NEAREST_NEAREST_MIPNEAREST","NEAREST_LINEAR_MIPNEAREST","NEAREST_LINEAR_MIPLINEAR","NEAREST_LINEAR","NEAREST_NEAREST","LINEAR_NEAREST_MIPNEAREST","LINEAR_NEAREST_MIPLINEAR","LINEAR_LINEAR","LINEAR_NEAREST","EXPLICIT_MODE","SPHERICAL_MODE","CUBIC_MODE","SKYBOX_MODE","INVCUBIC_MODE","EQUIRECTANGULAR_MODE","FIXED_EQUIRECTANGULAR_MODE","FIXED_EQUIRECTANGULAR_MIRRORED_MODE","CLAMP_ADDRESSMODE","WRAP_ADDRESSMODE","MIRROR_ADDRESSMODE","_TextureParser","_convertRGBtoRGBATextureData","rgbData","rgbaData","Uint16Array","Uint32Array","newIndex","_makeCreateRawTextureFunction","depth","compression","_gl","TEXTURE_3D","TEXTURE_2D_ARRAY","Raw3D","Raw2DArray","baseDepth","_doNotHandleContextLost","_bufferView","updateRawTexture3D","updateRawTexture2DArray","_bindTextureDirectly","filters","_getSamplingParameters","texParameteri","TEXTURE_MAG_FILTER","mag","TEXTURE_MIN_FILTER","generateMipmap","_internalTexturesCache","_makeUpdateRawTextureFunction","internalType","_getWebGLTextureType","internalFormat","_getInternalFormat","internalSizedFomat","_getRGBABufferInternalSizedFormat","_unpackFlipY","_compression","pixelStorei","UNPACK_ALIGNMENT","compressedTexImage3D","s3tc","texImage3D","updateRawTexture","TEXTURE_2D","compressedTexImage2D","texImage2D","createRawTexture","Raw","createRawCubeTexture","gl","CubeRaw","_bufferViewArray","RGB","RGBA","FLOAT","_caps","textureFloatLinearFiltering","HALF_FLOAT_OES","textureHalfFloatLinearFiltering","textureFloatRender","HALF_FLOAT","colorBufferFloat","needPOTTextures","IsExponentOfTwo","updateRawCubeTexture","TEXTURE_CUBE_MAP","TEXTURE_CUBE_MAP_POSITIVE_X","TEXTURE_WRAP_S","CLAMP_TO_EDGE","TEXTURE_WRAP_T","needConversion","faceData","createRawCubeTextureFromUrl","mipmapGenerator","internalCallback","faceDataArrays","mipData","mipSize","mipFaceData","offlineProvider","statusText","createRawTexture2DArray","createRawTexture3D","AutoRotationBehavior","_zoomStopsAnimation","_idleRotationSpeed","_idleRotationWaitTime","_idleRotationSpinupTime","targetAlpha","_isPointerDown","_lastFrameTime","_lastInteractionTime","Infinity","_cameraRotationSpeed","_lastFrameRadius","zoomStopsAnimation","flag","idleRotationSpeed","speed","idleRotationWaitTime","idleRotationSpinupTime","rotationInProgress","init","attach","_attachedCamera","_onPrePointerObservableObserver","onPrePointerObservable","pointerInfoPre","POINTERDOWN","POINTERUP","_onAfterCheckInputsObserver","onAfterCheckInputsObservable","_reachTargetAlpha","dt","_applyUserInteraction","timeToRotation","alpha","detach","resetLastInteractionTime","customTime","_userIsZooming","inertialRadiusOffset","_shouldAnimationStopForInteraction","zoomHasHitLimit","_userIsMoving","inertialAlphaOffset","inertialBetaOffset","inertialPanningX","inertialPanningY","BouncingBehavior","transitionDuration","lowerRadiusTransitionRange","upperRadiusTransitionRange","_autoTransitionRange","_radiusIsAnimating","_radiusBounceTransition","autoTransitionRange","_onMeshTargetChangedObserver","onMeshTargetChangedObservable","diagonal","diagonalLength","_isRadiusAtLimit","lowerRadiusLimit","_applyBoundRadiusAnimation","upperRadiusLimit","radiusLimit","radiusDelta","EasingMode","CreateAnimation","_cachedWheelPrecision","wheelPrecision","TransitionTo","_clearAnimationLocks","amplitude","num","FramingBehavior","onTargetFramingAnimationEndObservable","_mode","FitFrustumSidesMode","_radiusScale","_positionScale","_defaultElevation","_elevationReturnTime","_elevationReturnWaitTime","_framingTime","autoCorrectCameraLimitsAndSensibility","_betaIsAnimating","mode","radiusScale","positionScale","defaultElevation","elevation","elevationReturnTime","elevationReturnWaitTime","framingTime","zoomOnMesh","_maintainCameraAboveGround","focusOnOriginXZ","boundingBox","zoomOnBoundingInfo","minimumWorld","maximumWorld","zoomOnMeshHierarchy","getHierarchyBoundingVectors","zoomOnMeshesHierarchy","CheckExtends","zoomTarget","bottom","zoomTargetY","radiusWorld","_vectorTransition","_calculateLowerRadiusFromModelBoundingSphere","minZ","IgnoreBoundsSizeMode","extend","panningSensibility","_radiusTransition","useInputToRestoreState","storeState","boxVectorGlobalDiagonal","frustumSlope","_getFrustumSlope","distanceForHorizontalFrustum","distanceForVerticalFrustum","timeSinceInteraction","defaultBeta","limitBeta","beta","_betaTransition","animatabe","aspectRatio","getAspectRatio","frustumSlopeY","tan","fov","frustumSlopeX","isUserIsMoving","exponent","exp","origin","intersectsBoxMinMax","minimum","maximum","intersectionTreshold","newMinimum","_TmpVector3","newMaximum","inv","d","maxValue","intersectsBox","box","intersectsSphere","sphere","pyth","rr","dot","intersectsTriangle","vertex0","vertex1","vertex2","edge1","edge2","pvec","qvec","invdet","bv","bw","intersectsPlane","plane","result1","normal","result2","intersectsAxis","intersectsMesh","fastCheck","trianglePredicate","onlyBoundingInfo","worldToUse","skipBoundingInfo","tm","_tmpRay","TransformToRef","Transform","intersects","intersectsMeshes","results","pickInfo","hit","_comparePickingInfo","pickingInfoA","pickingInfoB","intersectionSegment","sega","segb","threshold","u","rsegb","v","_Rayl","addToRef","D","sN","tN","sD","tD","_Smallnum","sc","tc","qtc","qsc","dP","viewportWidth","viewportHeight","world","view","projection","enableDistantPicking","_RayDistant","unprojectRayToRef","ray","sourceX","sourceY","nearScreenSource","LastCreatedEngine","isNDCHalfZRange","farScreenSource","nearVec3","farVec3","_UnprojectFromInvertedMatrixToRef","createPickingRay","cameraViewSpace","createPickingRayToRef","viewport","toGlobal","getRenderWidth","getRenderHeight","getHardwareScalingLevel","createPickingRayInCameraSpace","createPickingRayInCameraSpaceToRef","identity","_internalPickForMesh","pickingInfo","rayFunction","_internalPick","computeWorldMatrixForCamera","cameraToUseForPointers","currentCamera","meshIndex","isVisible","isPickable","forceCompute","isWorldMatrixCameraDependent","hasThinInstances","thinInstanceEnablePicking","tmpMatrix","thinMatrices","thinInstanceGetWorldMatrices","thinInstanceIndex","_internalMultiPick","pickingInfos","pickWithBoundingInfo","_tempPickingRay","pick","_enableDistantPicking","pickWithRay","_pickWithRayInverseMatrix","_cachedRayForTransform","multiPick","multiPickWithRay","getForwardRay","transform","getForwardRayToRef","refRay","useRightHandedSystem","NormalizeToRef","_PivotCached","getPivotPointToRef","_OldPivotPoint","_PivotPostMultiplyPivotMatrix","_postMultiplyPivotMatrix","equalsToFloats","getPivotPoint","_PivotTranslation","_PivotTmpVector","setPivotPoint","CreatePlaneVertexData","positions","normals","uvs","sideOrientation","DEFAULTSIDE","halfWidth","halfHeight","_ComputeSides","frontUVs","backUVs","vertexData","_GetDefaultSideOrientation","_originalBuilderSideOrientation","applyToMesh","sourcePlane","setDirection","CreatePlane","currentDraggingPointerID","currentDraggingPointerId","enabled","_enabled","onEnabledObservable","_useAlternatePickedPointAboveMaxDragAngleDragSpeed","_activeDragButton","maxDragAngle","dragButtons","_useAlternatePickedPointAboveMaxDragAngle","dragging","dragDeltaRatio","updateDragPlane","_debugMode","_moving","onDragObservable","onDragStartObservable","onDragEndObservable","moveAttached","startAndReleaseDragOnPointerEvents","detachCameraControls","useObjectOrientationForDragging","validateDrag","targetPosition","_tmpVector","_alternatePickedPoint","_worldDragAxis","_targetPosition","_attachedToElement","_startDragRay","_lastPointerRay","_dragDelta","_pointA","_pointC","_localAxis","_lookAt","optionCount","dragAxis","dragPlaneNormal","ownerNode","isNearGrabbable","attachedNode","_PlaneScene","virtual","detachControl","_dragPlane","DOUBLESIDE","lastDragPosition","pickPredicate","isDescendantOf","_pointerObserver","onPointerObservable","pointerInfo","pickedMesh","pickedPoint","button","_activePointerInfo","_startDrag","pointerId","releaseDrag","POINTERMOVE","_AnyMouseId","pointerType","hostInformation","isMobile","MouseEvent","_moveDrag","_beforeRenderObserver","onBeforeRenderObservable","needMatrixUpdate","_RemoveAndStorePivotPoint","_RestorePivotPoint","dragPlanePoint","leftCamera","arcRotateCamera","attachControl","inputs","noPreventDefault","_useCtrlForPanning","_panningMouseButton","startDrag","fromRay","startPickedPoint","lastRay","getTranslationToRef","_updateDragPlanePosition","_pickWithRayOnDragPlane","attachedToElement","dragLength","dragDistance","forward","acos","pickResult","dragPlanePosition","lookAt","ANCHOR_SYSTEM","BACKGROUND_REMOVER","HIT_TEST","MESH_DETECTION","PHYSICS_CONTROLLERS","PLANE_DETECTION","POINTER_SELECTION","TELEPORTATION","FEATURE_POINTS","HAND_TRACKING","IMAGE_TRACKING","NEAR_INTERACTION","DOM_OVERLAY","MOVEMENT","LIGHT_ESTIMATION","EYE_TRACKING","WALKING_LOCOMOTION","LAYERS","DEPTH_SENSING","SPACE_WARP","WebXRFeaturesManager","_xrSessionManager","onXRSessionInit","getEnabledFeatures","featureName","feature","featureImplementation","attached","disableAutoAttach","attachFeature","onXRSessionEnded","detachFeature","constructorFunction","version","stable","_AvailableFeatures","latest","xrSessionManager","disableFeature","Name","enableFeature","moduleOptions","attachIfPossible","required","versionToLoad","GetStableVersionOfFeature","GetLatestVersionOfFeature","conflictingFeature","_ConflictingFeatures","constructFunction","ConstructFeature","constructed","dependentsFound","every","isCompatible","session","getEnabledFeature","xrSessionInit","enabledFeatures","nativeName","xrNativeFeatureName","requiredFeatures","optionalFeatures","getXRSessionInitExtension","extended","WebXRAbstractFeature","_attached","_removeOnDetach","force","_addNewAttachObserver","onXRFrameObservable","_onXRFrame","toRemove","observable","observer","PhysicsJoint","jointData","nativeParams","physicsJoint","_physicsJoint","newJoint","physicsPlugin","_physicsPlugin","executeNativeFunction","DistanceJoint","HingeJoint","BallAndSocketJoint","WheelJoint","SliderJoint","PrismaticJoint","UniversalJoint","Hinge2Joint","PointToPointJoint","SpringJoint","LockJoint","_PhysicsImpostorParser","physicObject","jsonObject","physicsImpostor","mass","physicsMass","friction","physicsFriction","restitution","physicsRestitution","_isDisposed","_physicsEngine","getPhysicsPlugin","getBodyMass","setMass","getBodyFriction","setBodyFriction","getBodyRestitution","setBodyRestitution","pressure","plugin","setBodyPressure","getBodyPressure","stiffness","getBodyStiffness","setBodyStiffness","velocityIterations","getBodyVelocityIterations","setBodyVelocityIterations","positionIterations","getBodyPositionIterations","setBodyPositionIterations","_pluginData","_bodyUpdateRequired","_onBeforePhysicsStepCallbacks","_onAfterPhysicsStepCallbacks","_onPhysicsCollideCallbacks","_deltaPosition","soft","segments","_tmpQuat","_tmpQuat2","beforeStep","_deltaRotationConjugated","getParentsRotation","disableBidirectionalTransformation","setPhysicsBodyTransformation","afterStep","setTransformationFromPhysicsBody","_deltaRotation","applyRotationQuaternionToRef","onCollideEvent","onCollide","otherImpostor","getImpostorWithPhysicsBody","obj","otherImpostors","impulse","getPhysicsEngine","RotationYawPitchRoll","fixedPoints","margin","damping","shape","_joints","ignoreParent","_init","removeImpostor","physicsBody","_getPhysicsParent","addImpostor","isBodyInitRequired","_physicsBody","setScalingUpdated","forceUpdate","removePhysicsBody","resetUpdateFlags","getObjectExtents","IDENTITY_QUATERNION","worldMatrix","extendSize","DEFAULT_OBJECT_SIZE","getObjectCenter","getParam","paramName","setParam","setBodyMass","getLinearVelocity","setLinearVelocity","velocity","getAngularVelocity","setAngularVelocity","registerBeforePhysicsStep","unregisterBeforePhysicsStep","registerAfterPhysicsStep","unregisterAfterPhysicsStep","registerOnPhysicsCollide","collideAgainst","collidedAgainstList","unregisterOnPhysicsCollide","some","cbDef","sameList","impostor","applyForce","contactPoint","applyImpulse","createJoint","jointType","joint","addJoint","addAnchor","influence","noCollisionBetweenLinkedBodies","appendAnchor","addHook","appendHook","sleep","sleepBody","wakeUp","wakeUpBody","newObject","removeJoint","setDeltaPosition","setDeltaRotation","conjugate","getBoxSizeToRef","getRadius","syncBoneWithImpostor","boneMesh","jointPivot","distToJoint","adjustRotation","tempVec","tempQuat","syncImpostorWithBone","boneAxis","boneDir","NoImpostor","SphereImpostor","BoxImpostor","PlaneImpostor","MeshImpostor","CapsuleImpostor","CylinderImpostor","ParticleImpostor","HeightmapImpostor","ConvexHullImpostor","CustomImpostor","RopeImpostor","ClothImpostor","SoftbodyImpostor","SceneLoaderAnimationGroupLoadingMode","ForceFullSceneLoadingForIncremental","ShowLoadingScreen","loggingLevel","CleanBoneMatrixWeights","_RegisteredPlugins","extension","registeredPlugin","GetDefaultPlugin","canDirectLoad","sceneFilename","queryStringPosition","substring","dotPosition","lastIndexOf","_GetPluginForExtension","fileInfo","errorMessage","rawData","onSuccess","onProgress","pluginExtension","directLoad","_GetDirectLoad","_GetPluginForDirectLoad","_GetPluginForFilename","isBinary","createPlugin","OnPluginActivatedObservable","useArrayBuffer","dataCallback","responseURL","pluginDisposed","abort","manifestChecked","errorCallback","loadFile","file","canUseOfflineSupport","enableOfflineSupport","exceptionFound","regex","disableOfflineSupportExceptionRules","test","OfflineProviderFactory","disableManifestCheck","sceneFile","isView","filename","GetFilename","GetFolderPath","extensions","meshNames","_GetFileInfo","loadingToken","disposeHandler","_FormatErrorMessage","SceneLoaderError","progressHandler","successHandler","importedMeshesFiles","_LoadData","rewriteRootURL","importMesh","syncedPlugin","loadingPluginName","importMeshAsync","ImportMesh","Append","Load","_ShowingLoadingScreen","displayLoadingUI","executeWhenReady","hideLoadingUI","loadAsync","assets","loadAssetContainer","assetContainer","loadAssetContainerAsync","LoadAssetContainer","overwriteAnimations","animationGroupLoadingMode","Clean","Stop","Sync","NoSync","startingIndexForNewAnimatables","onAnimationFileImportedObservable","ImportAnimations","NO_LOGGING","MINIMAL_LOGGING","SUMMARY_LOGGING","DETAILED_LOGGING","NodeMaterialBlockConnectionPointTypes","NodeMaterialBlockTargets","PushMaterial","storeEffectOnSubMeshes","_normalMatrix","_storeEffectOnSubMeshes","getEffect","_activeEffect","isReadyForSubMesh","_isReadyForSubMesh","subMesh","defines","materialDefines","checkReadyOnEveryCall","bindOnlyWorldMatrix","setMatrix","bindOnlyNormalMatrix","normalMatrix","bindForSubMesh","_afterBind","_cachedEffect","_forceRebindOnNextCall","_mustRebind","isCachedMaterialInvalid","forceDisposeEffect","notBoundToMesh","NodeMaterialBuildState","supportUniformBuffers","attributes","uniforms","constants","samplers","functions","counters","_attributeDeclaration","_uniformDeclaration","_constantDeclaration","_samplerDeclaration","_varyingTransfer","_injectAtEnd","_repeatableContentAnchorIndex","_builtCompilationString","compilationString","finalize","emitComments","sharedData","isFragmentMode","Fragment","functionCode","functionName","varyingDeclaration","extensionName","_repeatableContentAnchor","_getFreeVariableName","prefix","variableNames","_getFreeDefineName","defineNames","_excludeVariableName","_emit2DSampler","_emit2DArraySampler","_getGLType","Float","Int","Vector2","Color4","Vector4","_emitExtension","define","_emitFunction","code","comments","_emitCodeFromInclude","includeName","repeatKey","substitutionVars","IncludesShadersStore","replaceStrings","replaceString","search","_emitFunctionFromInclude","storeKey","removeAttributes","removeUniforms","removeVaryings","removeIfDef","_registerTempVariable","temps","_emitVaryingFromString","notDefine","varyings","_emitUniformFromString","_emitFloat","NodeMaterialBuildStateSharedData","inputBlocks","textureBlocks","bindableBlocks","forcedBindableBlocks","blocksWithFallbacks","blocksWithDefines","repeatableContentBlocks","dynamicUniformBlocks","blockingBlocks","animatedInputs","hints","needWorldViewMatrix","needWorldViewProjectionMatrix","needAlphaBlending","needAlphaTesting","checks","emitVertex","emitFragment","notConnectedNonOptionalInputs","allowEmptyVertexProgram","emitErrors","notConnectedInput","ownerBlock","NodeMaterialConnectionPointCompatibilityStates","NodeMaterialConnectionPointDirection","NodeMaterialConnectionPoint","type1","type2","_direction","associatedVariableName","_ownerBlock","isInput","_enforceAssociatedVariableName","_associatedVariableName","_connectedPoint","innerType","_linkedConnectionSource","isConnected","_type","AutoDetect","BasedOnInput","_typeConnectionSource","_defaultConnectionPointType","_prioritizeVertex","VertexAndFragment","Vertex","connectedPoint","hasEndpoints","isConnectedToInputBlock","connectInputBlock","sourceBlock","connectedBlocks","_endpoints","endpoints","isDirectlyConnectedToVertexOutput","endpoint","Neutral","isConnectedInVertexShader","isConnectedInFragmentShader","createCustomInputBlock","_acceptedConnectionPointType","needDualDirectionValidation","acceptedConnectionPointTypes","excludedConnectionPointTypes","onConnectionObservable","isExposedOnFrame","exposedPortPosition","canConnectTo","connectionPoint","checkCompatibilityState","Compatible","otherBlock","TargetIncompatible","AreEquivalentTypes","TypeIncompatible","targetBlock","Input","isAnAncestorOf","HierarchyIssue","connectTo","ignoreConstraints","disconnectFrom","addExcludedConnectionPointFromAllowedTypes","mask","bitmask","All","displayName","inputName","targetBlockId","targetConnectionName","PropertyTypeForEdition","NodeMaterialBlock","_name","validateBlockName","isUnique","_isUnique","isFinalMerger","_isFinalMerger","_isInput","buildId","_buildId","_inputs","_outputs","getInputByName","getOutputByName","inputsAreExclusive","_codeVariableName","visibleInInspector","visibleOnFrame","_originalTargetIsNeutral","UniqueId","_setInitialTarget","initialize","nodeMaterial","_declareOutput","_writeVariable","_writeFloat","stringVersion","registerInput","isOptional","registerOutput","Output","getFirstAvailableInput","forOutput","input","getFirstAvailableOutput","forBlock","getSiblingOutput","current","block","notFound","_buildBlock","updateUniformsAndSamples","uniformBuffers","provideFallbacks","fallbacks","initializeDefines","prepareDefines","autoConfigure","replaceRepeatableContent","vertexShaderState","fragmentShaderState","willBeGeneratedIntoVertexShaderFromFragmentShader","_linkConnectionTypes","inputIndex0","inputIndex1","looseCoupling","_processBuild","activeBlocks","build","localBlockIsFragment","_vertexState","otherBlockWasGeneratedInVertexShader","_buildTarget","isAttribute","_noContextSwitch","reservedNames","reservedName","verbose","log","_inputRename","_outputRename","_dumpPropertiesCode","variableName","_dumpCode","uniqueNames","alreadyDumped","codeString","nameAsVariableName","connectedBlock","_dumpCodeForOutputConnections","connectedOutput","blockType","_deserialize","_deserializePortDisplayNamesAndExposedOnFrame","serializedInputs","serializedOutputs","port","TransformBlock","complementW","complementZ","otherAsInput","vector","xyz","transformName","nonUniformScaling","VertexOutputBlock","_isLogarithmicDepthEnabled","nodeList","useLogarithmicDepth","fragmentOutputNodes","editableInPropertyPage","propertyType","Boolean","groupName","propertyKey","propStore","_propStore","propertyName","NodeMaterialBlockConnectionPointMode","NodeMaterialSystemValues","FragmentOutputBlock","convertToGammaSpace","convertToLinearSpace","rgb","rgba","_linearDefineName","_gammaDefineName","BindLogDepth","aValue","notifiers","AnimatedInputBlockTypes","remapAttributeName","position2d","particle_uv","particle_color","particle_texturemask","particle_positionw","attributeInFragmentOnly","attributeAsUniform","InputBlock","isUniform","isSystemValue","_systemValue","World","WorldView","WorldViewProjection","View","ViewProjection","Projection","CameraPosition","FogColor","DeltaTime","MaterialAlpha","CameraParameters","Undefined","_animationType","None","isBoolean","matrixMode","isConstant","groupInInspector","onValueChangedObservable","setDefaultValue","setAsAttribute","attributeName","Attribute","setAsSystemValue","systemValue","_storedValue","Uniform","valueCallback","_valueCallback","isUndefined","isVarying","Varying","Time","getAnimationRatio","RealTime","_emitDefine","White","_emitConstant","toGammaSpaceToRef","useExactSrgbConversions","toLinearSpaceToRef","_emit","_transmitWorld","worldView","worldViewProjection","_transmit","getTransformMatrix","bindEyePosition","setColor3","fogColor","setFloat4","hasOriginBottomLeft","maxZ","setInt","setDirectColor4","setVector2","setVector3","codes","valueString","valueType","wellKnownValue","CurrentScreenBlock","_samplerName","uv","_injectVertexCode","uvInput","_mainUVName","_writeTextureRead","_writeOutput","vertexMode","_tempTextureRead","swizzle","ParticleTextureBlock","getInputBlockByPredicate","ParticleRampGradientBlock","color","rampColor","ParticleBlendMultiplyBlock","alphaTexture","alphaColor","blendColor","EffectFallbacks","_defines","_currentRank","_maxRank","_mesh","unBindMesh","addFallback","rank","addCPUSkinningFallback","hasMoreFallbacks","reduce","currentDefines","computeBonesUsingShaders","numBoneInfluencers","_bonesComputationForcedToCPU","otherMesh","currentFallbacks","shader","targetTypes","layerCounts","rtWrapper","NodeMaterialModes","xy","zwInput","_tempVector","P","particleEmitterType","direction1","direction2","minEmitBox","maxEmitBox","meshToRender","layer","TrigonometryBlockOperations","operation","HandPart","WebXRHandJoint","handMeshes","_bone1","localTarget","xzlen","ang1","ang2","_uniqueId","currentRotation","rotationChange","keysUp","keysDown","keysLeft","keysRight","keysUpward","keysDownward","keysRotateLeft","keysRotateRight","keysRotateUp","keysRotateDown","preventDefault","VirtualJoystick","_VJCanvasContext","stroke","pointers","keyboard","PoseEnabledControllerType","browserGamepad","buttons","_babylonGamepads","ClearCoatTintTextureEnabled","f","uniform","particle","depthOnlySubMeshes","setColorWrite","renderSubMesh","opaqueSubMeshes","transparentSubMeshes","V"],"sourceRoot":""} \ No newline at end of file diff --git a/6bc48222ba83afa56babedfa3f8ecf0aa4bc5b28-a5360fdffd7950e5762f.js b/6bc48222ba83afa56babedfa3f8ecf0aa4bc5b28-a5360fdffd7950e5762f.js deleted file mode 100644 index 2d4f678b..00000000 --- a/6bc48222ba83afa56babedfa3f8ecf0aa4bc5b28-a5360fdffd7950e5762f.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict";(self.webpackChunkcode_cave=self.webpackChunkcode_cave||[]).push([[517],{3204:function(e){const t=/[\p{Lu}]/u,a=/[\p{Ll}]/u,r=/^[\p{Lu}](?![\p{Lu}])/gu,n=/([\p{Alpha}\p{N}_]|$)/u,s=/[_.\- ]+/,i=new RegExp("^"+s.source),o=new RegExp(s.source+n.source,"gu"),l=new RegExp("\\d+"+n.source,"gu"),c=(e,n)=>{if("string"!=typeof e&&!Array.isArray(e))throw new TypeError("Expected the input to be `string | string[]`");if(n={pascalCase:!1,preserveConsecutiveUppercase:!1,...n},0===(e=Array.isArray(e)?e.map((e=>e.trim())).filter((e=>e.length)).join("-"):e.trim()).length)return"";const s=!1===n.locale?e=>e.toLowerCase():e=>e.toLocaleLowerCase(n.locale),c=!1===n.locale?e=>e.toUpperCase():e=>e.toLocaleUpperCase(n.locale);if(1===e.length)return n.pascalCase?c(e):s(e);return e!==s(e)&&(e=((e,r,n)=>{let s=!1,i=!1,o=!1;for(let l=0;l(r.lastIndex=0,e.replace(r,(e=>t(e)))))(e,s):s(e),n.pascalCase&&(e=c(e.charAt(0))+e.slice(1)),((e,t)=>(o.lastIndex=0,l.lastIndex=0,e.replace(o,((e,a)=>t(a))).replace(l,(e=>t(e)))))(e,c)};e.exports=c,e.exports.default=c},8032:function(e,t,a){a.d(t,{G:function(){return _},L:function(){return h},M:function(){return k},P:function(){return x},_:function(){return o},a:function(){return i},b:function(){return d},c:function(){return c},g:function(){return g},h:function(){return l}});var r=a(7294),n=(a(3204),a(5697)),s=a.n(n);function i(){return i=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0||(n[a]=e[a]);return n}const l=()=>"undefined"!=typeof HTMLImageElement&&"loading"in HTMLImageElement.prototype;const c=e=>{var t;return(e=>{var t,a;return Boolean(null==e||null==(t=e.images)||null==(a=t.fallback)?void 0:a.src)})(e)?e:(e=>Boolean(null==e?void 0:e.gatsbyImageData))(e)?e.gatsbyImageData:(e=>Boolean(null==e?void 0:e.gatsbyImage))(e)?e.gatsbyImage:null==e||null==(t=e.childImageSharp)?void 0:t.gatsbyImageData};function u(e,t,a){const r={};let n="gatsby-image-wrapper";return"fixed"===a?(r.width=e,r.height=t):"constrained"===a&&(n="gatsby-image-wrapper gatsby-image-wrapper-constrained"),{className:n,"data-gatsby-image-wrapper":"",style:r}}function d(e,t,a,r,n){return void 0===n&&(n={}),i({},a,{loading:r,shouldLoad:e,"data-main-image":"",style:i({},n,{opacity:t?1:0})})}function g(e,t,a,r,n,s,o,l){const c={};s&&(c.backgroundColor=s,"fixed"===a?(c.width=r,c.height=n,c.backgroundColor=s,c.position="relative"):("constrained"===a||"fullWidth"===a)&&(c.position="absolute",c.top=0,c.left=0,c.bottom=0,c.right=0)),o&&(c.objectFit=o),l&&(c.objectPosition=l);const u=i({},e,{"aria-hidden":!0,"data-placeholder-image":"",style:i({opacity:t?0:1,transition:"opacity 500ms linear"},c)});return u}const p=["children"],m=function(e){let{layout:t,width:a,height:n}=e;return"fullWidth"===t?r.createElement("div",{"aria-hidden":!0,style:{paddingTop:n/a*100+"%"}}):"constrained"===t?r.createElement("div",{style:{maxWidth:a,display:"block"}},r.createElement("img",{alt:"",role:"presentation","aria-hidden":"true",src:"data:image/svg+xml;charset=utf-8,%3Csvg%20height='"+n+"'%20width='"+a+"'%20xmlns='http://www.w3.org/2000/svg'%20version='1.1'%3E%3C/svg%3E",style:{maxWidth:"100%",display:"block",position:"static"}})):null},h=function(e){let{children:t}=e,a=o(e,p);return r.createElement(r.Fragment,null,r.createElement(m,i({},a)),t,null)},y=["src","srcSet","loading","alt","shouldLoad"],f=["fallback","sources","shouldLoad"],b=function(e){let{src:t,srcSet:a,loading:n,alt:s="",shouldLoad:l}=e,c=o(e,y);return r.createElement("img",i({},c,{decoding:"async",loading:n,src:l?t:void 0,"data-src":l?void 0:t,srcSet:l?a:void 0,"data-srcset":l?void 0:a,alt:s}))},v=function(e){let{fallback:t,sources:a=[],shouldLoad:n=!0}=e,s=o(e,f);const l=s.sizes||(null==t?void 0:t.sizes),c=r.createElement(b,i({},s,t,{sizes:l,shouldLoad:n}));return a.length?r.createElement("picture",null,a.map((e=>{let{media:t,srcSet:a,type:s}=e;return r.createElement("source",{key:t+"-"+s+"-"+a,type:s,media:t,srcSet:n?a:void 0,"data-srcset":n?void 0:a,sizes:l})})),c):c};var w;b.propTypes={src:n.string.isRequired,alt:n.string.isRequired,sizes:n.string,srcSet:n.string,shouldLoad:n.bool},v.displayName="Picture",v.propTypes={alt:n.string.isRequired,shouldLoad:n.bool,fallback:n.exact({src:n.string.isRequired,srcSet:n.string,sizes:n.string}),sources:n.arrayOf(n.oneOfType([n.exact({media:n.string.isRequired,type:n.string,sizes:n.string,srcSet:n.string.isRequired}),n.exact({media:n.string,type:n.string.isRequired,sizes:n.string,srcSet:n.string.isRequired})]))};const E=["fallback"],x=function(e){let{fallback:t}=e,a=o(e,E);return t?r.createElement(v,i({},a,{fallback:{src:t},"aria-hidden":!0,alt:""})):r.createElement("div",i({},a))};x.displayName="Placeholder",x.propTypes={fallback:n.string,sources:null==(w=v.propTypes)?void 0:w.sources,alt:function(e,t,a){return e[t]?new Error("Invalid prop `"+t+"` supplied to `"+a+"`. Validation failed."):null}};const k=function(e){return r.createElement(r.Fragment,null,r.createElement(v,i({},e)),r.createElement("noscript",null,r.createElement(v,i({},e,{shouldLoad:!0}))))};k.displayName="MainImage",k.propTypes=v.propTypes;const L=["as","className","class","style","image","loading","imgClassName","imgStyle","backgroundColor","objectFit","objectPosition"],C=["style","className"],S=e=>e.replace(/\n/g,""),I=function(e,t,a){for(var r=arguments.length,n=new Array(r>3?r-3:0),i=3;iJSON.stringify(n.images)),[n.images]);g&&(d=g);const S=function(e,t,a){let r="";return"fullWidth"===e&&(r=''),"constrained"===e&&(r='
"),r}(v,f,b);return(0,r.useEffect)((()=>{q||(q=a.e(731).then(a.bind(a,6731)).then((e=>{let{renderImageToString:t,swapPlaceholderImage:a}=e;return P=t,{renderImageToString:t,swapPlaceholderImage:a}})));const e=L.current.querySelector("[data-gatsby-image-ssr]");if(e&&l())return e.complete?(null==p||p({wasCached:!0}),null==m||m({wasCached:!0}),setTimeout((()=>{e.removeAttribute("data-gatsby-image-ssr")}),0)):(null==p||p({wasCached:!0}),e.addEventListener("load",(function t(){e.removeEventListener("load",t),null==m||m({wasCached:!0}),setTimeout((()=>{e.removeAttribute("data-gatsby-image-ssr")}),0)}))),void O.add(C);if(P&&O.has(C))return;let t,r;return q.then((e=>{let{renderImageToString:a,swapPlaceholderImage:o}=e;L.current&&(L.current.innerHTML=a(i({isLoading:!0,isLoaded:O.has(C),image:n},y)),O.has(C)||(t=requestAnimationFrame((()=>{L.current&&(r=o(L.current,C,O,s,p,m,h))}))))})),()=>{t&&cancelAnimationFrame(t),r&&r()}}),[n]),(0,r.useLayoutEffect)((()=>{O.has(C)&&P&&(L.current.innerHTML=P(i({isLoading:O.has(C),isLoaded:O.has(C),image:n},y)),null==p||p({wasCached:!0}),null==m||m({wasCached:!0}))}),[n]),(0,r.createElement)(t,i({},k,{style:i({},E,s,{backgroundColor:c}),className:x+(d?" "+d:""),ref:L,dangerouslySetInnerHTML:{__html:S},suppressHydrationWarning:!0}))},_=(0,r.memo)((function(e){return e.image?(0,r.createElement)(R,e):null}));_.propTypes=N,_.displayName="GatsbyImage";const A=["src","__imageData","__error","width","height","aspectRatio","tracedSVGOptions","placeholder","formats","quality","transformOptions","jpgOptions","pngOptions","webpOptions","avifOptions","blurredOptions","breakpoints","outputPixelDensities"];function W(e){return function(t){let{src:a,__imageData:n,__error:s}=t,l=o(t,A);return s&&console.warn(s),n?r.createElement(e,i({image:n},l)):(console.warn("Image not loaded",a),null)}}const z=W((function(e){let{as:t="div",className:a,class:n,style:s,image:l,loading:c="lazy",imgClassName:p,imgStyle:m,backgroundColor:y,objectFit:f,objectPosition:b}=e,v=o(e,L);if(!l)return console.warn("[gatsby-plugin-image] Missing image prop"),null;n&&(a=n),m=i({objectFit:f,objectPosition:b,backgroundColor:y},m);const{width:w,height:E,layout:I,images:N,placeholder:T,backgroundColor:j}=l,O=u(w,E,I),{style:q,className:P}=O,R=o(O,C),_={fallback:void 0,sources:[]};return N.fallback&&(_.fallback=i({},N.fallback,{srcSet:N.fallback.srcSet?S(N.fallback.srcSet):void 0})),N.sources&&(_.sources=N.sources.map((e=>i({},e,{srcSet:S(e.srcSet)})))),r.createElement(t,i({},R,{style:i({},q,s,{backgroundColor:y}),className:P+(a?" "+a:"")}),r.createElement(h,{layout:I,width:w,height:E},r.createElement(x,i({},g(T,!1,I,w,E,j,f,b))),r.createElement(k,i({"data-gatsby-image-ssr":"",className:p},v,d("eager"===c,!1,_,c,m)))))})),M=function(e,t){for(var a=arguments.length,r=new Array(a>2?a-2:0),n=2;n{if(void 0!==e.layout&&!F.has(e.layout))return new Error("Invalid value "+e.layout+'" provided for prop "layout". Defaulting to "constrained". Valid values are "fixed", "fullWidth" or "constrained".')}};z.displayName="StaticImage",z.propTypes=D;const H=W(_);H.displayName="StaticImage",H.propTypes=D},6745:function(e,t,a){var r=a(7294),n=a(1883),s=a(8032),i=a(9165);t.Z=e=>{let{project:t,className:a,theme:o}=e;const l=(0,s.c)(t.frontmatter.cover),{title:c}=t.frontmatter,u="light"===o?"text-main-100 hover:text-main-10":"text-secondary-100 hover:text-secondary-10",d="light"===o?"bg-secondary-70 hover:bg-secondary-100":"bg-main-100 hover:bg-main-100";return r.createElement(n.Link,{to:"/projects/"+t.id,className:d+" "+u+" flex flex-col grow-1 justify-between hover:text-main-10 rounded-2xl "+a,itemScope:!0,itemType:"https://schema.org/CreativeWork"},l?r.createElement(s.G,{image:l,alt:c,itemProp:"image",className:"aspect-square object-cover w-full rounded-t-2xl"}):null,r.createElement("h4",{className:"text-2xl p-6 flex grow items-center font-extrabold h-24",itemProp:"description"},c.toUpperCase()),r.createElement(i.L,{itemProp:"author"}))}}}]); -//# sourceMappingURL=6bc48222ba83afa56babedfa3f8ecf0aa4bc5b28-a5360fdffd7950e5762f.js.map \ No newline at end of file diff --git a/6bc48222ba83afa56babedfa3f8ecf0aa4bc5b28-a5360fdffd7950e5762f.js.map b/6bc48222ba83afa56babedfa3f8ecf0aa4bc5b28-a5360fdffd7950e5762f.js.map deleted file mode 100644 index 19a26548..00000000 --- a/6bc48222ba83afa56babedfa3f8ecf0aa4bc5b28-a5360fdffd7950e5762f.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"6bc48222ba83afa56babedfa3f8ecf0aa4bc5b28-a5360fdffd7950e5762f.js","mappings":"uGAEA,MAAMA,EAAY,YACZC,EAAY,YACZC,EAAkB,0BAClBC,EAAa,yBACbC,EAAa,WAEbC,EAAqB,IAAIC,OAAO,IAAMF,EAAWG,QACjDC,EAA4B,IAAIF,OAAOF,EAAWG,OAASJ,EAAWI,OAAQ,MAC9EE,EAAyB,IAAIH,OAAO,OAASH,EAAWI,OAAQ,MA6ChEG,EAAY,CAACC,EAAOC,KACzB,GAAuB,iBAAVD,IAAsBE,MAAMC,QAAQH,GAChD,MAAM,IAAII,UAAU,gDAiBrB,GAdAH,EAAU,CACTI,YAAY,EACZC,8BAA8B,KAC3BL,GAWiB,KAPpBD,EADGE,MAAMC,QAAQH,GACTA,EAAMO,KAAIC,GAAKA,EAAEC,SACvBC,QAAOF,GAAKA,EAAEG,SACdC,KAAK,KAECZ,EAAMS,QAGLE,OACT,MAAO,GAGR,MAAME,GAAiC,IAAnBZ,EAAQa,OAC3BC,GAAUA,EAAOF,cACjBE,GAAUA,EAAOC,kBAAkBf,EAAQa,QACtCG,GAAiC,IAAnBhB,EAAQa,OAC3BC,GAAUA,EAAOE,cACjBF,GAAUA,EAAOG,kBAAkBjB,EAAQa,QAE5C,GAAqB,IAAjBd,EAAMW,OACT,OAAOV,EAAQI,WAAaY,EAAYjB,GAASa,EAAYb,GAqB9D,OAlBqB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,WAAwBA,IACzBD,EAAMC,GAAA0E,IAAAA,OAMSC,MANTD,IAAA,CAMgB3E,EAAOC,GAAA4E,OAAa3E,IAJnC,IAASgE,MAAC,IACXjE,EAAA,KAAaD,EAAMC,GAAA,iDAMXiJ,EAAG,IAAI/D,IAAI,CAAQ,QAAa,YAAe,gBAEpDgE,EAAY,CACvB7I,IAAKqE,IAAAA,OAAiBb,WACtBnB,IAAK4B,EACL3D,MAAOmI,EACPlI,OAAQkI,EACRxF,MAAOoB,IAAAA,OACPpC,OAASvC,IACP,YAAIA,EAAMuC,SAGN2G,EAAazB,IAAIzH,EAAMuC,QAI3B,OAAW,IAAA2B,MAAA,iBACQlE,EAAMuC,OAAA,qHAA0H,GAKvJoG,EAAY5E,YAAc,cAC1B4E,EAAY9E,UAAYsF,EC7FlB,MAAAC,EACJd,EAAgBF,GAElBgB,EAAYrF,YAAc,cAC1BqF,EAAYvF,UAAYsF,C,mECmCxB,IA/CuBE,IAQhB,IARiB,QACtBC,EAAO,UACPxI,EAAS,MACTyI,GAKDF,EACC,MAAMG,GAAQC,EAAAA,EAAAA,GAASH,EAAQI,YAAYF,QACrC,MAAEG,GAAUL,EAAQI,YAEpBE,EACM,UAAVL,EACI,mCACA,6CACAM,EACM,UAAVN,EACI,yCACA,gCAEN,OACEO,EAAAA,cAACC,EAAAA,KAAI,CACHC,GAAE,aAAeV,EAAQW,GACzBnJ,UAAc+I,EAAQ,IAAID,EAAgB,wEAAwE9I,EAClHoJ,WAAS,EACTC,SAAS,mCAERX,EACCM,EAAAA,cAACM,EAAAA,EAAW,CACVrF,MAAOyE,EACP7G,IAAKgH,EACLU,SAAS,QACTvJ,UAAU,oDAEV,KACJgJ,EAAAA,cAAA,MACEhJ,UAAU,0DACVuJ,SAAS,eAERV,EAAMnL,eAETsL,EAAAA,cAACQ,EAAAA,EAAqB,CAACD,SAAS,WAC3B,C","sources":["webpack://code-cave/./node_modules/camelcase/index.js","webpack://code-cave/../src/image-utils.ts","webpack://code-cave/../src/components/hooks.ts","webpack://code-cave/../src/components/layout-wrapper.tsx","webpack://code-cave/../src/components/picture.tsx","webpack://code-cave/../src/components/placeholder.tsx","webpack://code-cave/../src/components/main-image.tsx","webpack://code-cave/../src/components/gatsby-image.server.tsx","webpack://code-cave/../src/components/gatsby-image.browser.tsx","webpack://code-cave/../src/components/static-image.server.tsx","webpack://code-cave/../src/components/static-image.tsx","webpack://code-cave/./src/components/projects/projectPreview.tsx"],"sourcesContent":["'use strict';\n\nconst UPPERCASE = /[\\p{Lu}]/u;\nconst LOWERCASE = /[\\p{Ll}]/u;\nconst LEADING_CAPITAL = /^[\\p{Lu}](?![\\p{Lu}])/gu;\nconst IDENTIFIER = /([\\p{Alpha}\\p{N}_]|$)/u;\nconst SEPARATORS = /[_.\\- ]+/;\n\nconst LEADING_SEPARATORS = new RegExp('^' + SEPARATORS.source);\nconst SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, 'gu');\nconst NUMBERS_AND_IDENTIFIER = new RegExp('\\\\d+' + IDENTIFIER.source, 'gu');\n\nconst preserveCamelCase = (string, toLowerCase, toUpperCase) => {\n\tlet isLastCharLower = false;\n\tlet isLastCharUpper = false;\n\tlet isLastLastCharUpper = false;\n\n\tfor (let i = 0; i < string.length; i++) {\n\t\tconst character = string[i];\n\n\t\tif (isLastCharLower && UPPERCASE.test(character)) {\n\t\t\tstring = string.slice(0, i) + '-' + string.slice(i);\n\t\t\tisLastCharLower = false;\n\t\t\tisLastLastCharUpper = isLastCharUpper;\n\t\t\tisLastCharUpper = true;\n\t\t\ti++;\n\t\t} else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) {\n\t\t\tstring = string.slice(0, i - 1) + '-' + string.slice(i - 1);\n\t\t\tisLastLastCharUpper = isLastCharUpper;\n\t\t\tisLastCharUpper = false;\n\t\t\tisLastCharLower = true;\n\t\t} else {\n\t\t\tisLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character;\n\t\t\tisLastLastCharUpper = isLastCharUpper;\n\t\t\tisLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character;\n\t\t}\n\t}\n\n\treturn string;\n};\n\nconst preserveConsecutiveUppercase = (input, toLowerCase) => {\n\tLEADING_CAPITAL.lastIndex = 0;\n\n\treturn input.replace(LEADING_CAPITAL, m1 => toLowerCase(m1));\n};\n\nconst postProcess = (input, toUpperCase) => {\n\tSEPARATORS_AND_IDENTIFIER.lastIndex = 0;\n\tNUMBERS_AND_IDENTIFIER.lastIndex = 0;\n\n\treturn input.replace(SEPARATORS_AND_IDENTIFIER, (_, identifier) => toUpperCase(identifier))\n\t\t.replace(NUMBERS_AND_IDENTIFIER, m => toUpperCase(m));\n};\n\nconst camelCase = (input, options) => {\n\tif (!(typeof input === 'string' || Array.isArray(input))) {\n\t\tthrow new TypeError('Expected the input to be `string | string[]`');\n\t}\n\n\toptions = {\n\t\tpascalCase: false,\n\t\tpreserveConsecutiveUppercase: false,\n\t\t...options\n\t};\n\n\tif (Array.isArray(input)) {\n\t\tinput = input.map(x => x.trim())\n\t\t\t.filter(x => x.length)\n\t\t\t.join('-');\n\t} else {\n\t\tinput = input.trim();\n\t}\n\n\tif (input.length === 0) {\n\t\treturn '';\n\t}\n\n\tconst toLowerCase = options.locale === false ?\n\t\tstring => string.toLowerCase() :\n\t\tstring => string.toLocaleLowerCase(options.locale);\n\tconst toUpperCase = options.locale === false ?\n\t\tstring => string.toUpperCase() :\n\t\tstring => string.toLocaleUpperCase(options.locale);\n\n\tif (input.length === 1) {\n\t\treturn options.pascalCase ? toUpperCase(input) : toLowerCase(input);\n\t}\n\n\tconst hasUpperCase = input !== toLowerCase(input);\n\n\tif (hasUpperCase) {\n\t\tinput = preserveCamelCase(input, toLowerCase, toUpperCase);\n\t}\n\n\tinput = input.replace(LEADING_SEPARATORS, '');\n\n\tif (options.preserveConsecutiveUppercase) {\n\t\tinput = preserveConsecutiveUppercase(input, toLowerCase);\n\t} else {\n\t\tinput = toLowerCase(input);\n\t}\n\n\tif (options.pascalCase) {\n\t\tinput = toUpperCase(input.charAt(0)) + input.slice(1);\n\t}\n\n\treturn postProcess(input, toUpperCase);\n};\n\nmodule.exports = camelCase;\n// TODO: Remove this for the next major release\nmodule.exports.default = camelCase;\n","import camelCase from \"camelcase\"\nimport type { IGatsbyImageData } from \"./index\"\n\nconst DEFAULT_PIXEL_DENSITIES = [0.25, 0.5, 1, 2]\nexport const DEFAULT_BREAKPOINTS = [750, 1080, 1366, 1920]\nexport const EVERY_BREAKPOINT = [\n 320, 654, 768, 1024, 1366, 1600, 1920, 2048, 2560, 3440, 3840, 4096,\n]\nconst DEFAULT_FLUID_WIDTH = 800\nconst DEFAULT_FIXED_WIDTH = 800\nconst DEFAULT_ASPECT_RATIO = 4 / 3\n\nexport type Fit = \"cover\" | \"fill\" | \"inside\" | \"outside\" | \"contain\"\n\nexport type Layout = \"fixed\" | \"fullWidth\" | \"constrained\"\nexport type ImageFormat = \"jpg\" | \"png\" | \"webp\" | \"avif\" | \"auto\" | \"\"\n\n/**\n * The minimal required reporter, as we don't want to import it from gatsby-cli\n */\nexport interface IReporter {\n warn(message: string): void\n}\n\nexport interface ISharpGatsbyImageArgs {\n layout?: Layout\n formats?: Array\n placeholder?: \"tracedSVG\" | \"dominantColor\" | \"blurred\" | \"none\"\n tracedSVGOptions?: Record\n width?: number\n height?: number\n aspectRatio?: number\n sizes?: string\n quality?: number\n transformOptions?: {\n fit?: Fit\n cropFocus?: number | string\n duotone?: {\n highlight: string\n shadow: string\n opacity?: number\n }\n grayscale?: boolean\n rotate?: number\n trim?: number\n }\n jpgOptions?: Record\n pngOptions?: Record\n webpOptions?: Record\n avifOptions?: Record\n blurredOptions?: { width?: number; toFormat?: ImageFormat }\n breakpoints?: Array\n outputPixelDensities?: Array\n backgroundColor?: string\n}\n\nexport interface IImageSizeArgs {\n width?: number\n height?: number\n layout?: Layout\n filename: string\n outputPixelDensities?: Array\n breakpoints?: Array\n fit?: Fit\n reporter?: IReporter\n sourceMetadata: { width: number; height: number }\n}\n\nexport interface IImageSizes {\n sizes: Array\n presentationWidth: number\n presentationHeight: number\n aspectRatio: number\n unscaledWidth: number\n}\n\nexport interface IImage {\n src: string\n width: number\n height: number\n format: ImageFormat\n}\n\nexport interface IGatsbyImageHelperArgs {\n pluginName: string\n generateImageSource: (\n filename: string,\n width: number,\n height: number,\n format: ImageFormat,\n fit?: Fit,\n options?: Record\n ) => IImage\n layout?: Layout\n formats?: Array\n filename: string\n placeholderURL?: string\n width?: number\n height?: number\n sizes?: string\n reporter?: IReporter\n sourceMetadata?: { width: number; height: number; format: ImageFormat }\n fit?: Fit\n options?: Record\n breakpoints?: Array\n backgroundColor?: string\n aspectRatio?: number\n}\n\nconst warn = (message: string): void => console.warn(message)\n\nconst sortNumeric = (a: number, b: number): number => a - b\n\nexport const getSizes = (width: number, layout: Layout): string | undefined => {\n switch (layout) {\n // If screen is wider than the max size, image width is the max size,\n // otherwise it's the width of the screen\n case `constrained`:\n return `(min-width: ${width}px) ${width}px, 100vw`\n\n // Image is always the same width, whatever the size of the screen\n case `fixed`:\n return `${width}px`\n\n // Image is always the width of the screen\n case `fullWidth`:\n return `100vw`\n\n default:\n return undefined\n }\n}\n\nexport const getSrcSet = (images: Array): string =>\n images.map(image => `${image.src} ${image.width}w`).join(`,\\n`)\n\nexport function formatFromFilename(filename: string): ImageFormat | undefined {\n const dot = filename.lastIndexOf(`.`)\n if (dot !== -1) {\n const ext = filename.slice(dot + 1)\n if (ext === `jpeg`) {\n return `jpg`\n }\n if (ext.length === 3 || ext.length === 4) {\n return ext as ImageFormat\n }\n }\n return undefined\n}\n\nexport function setDefaultDimensions(\n args: IGatsbyImageHelperArgs\n): IGatsbyImageHelperArgs {\n let {\n layout = `constrained`,\n width,\n height,\n sourceMetadata,\n breakpoints,\n aspectRatio,\n formats = [`auto`, `webp`],\n } = args\n formats = formats.map(format => format.toLowerCase() as ImageFormat)\n layout = camelCase(layout) as Layout\n\n if (width && height) {\n return { ...args, formats, layout, aspectRatio: width / height }\n }\n if (sourceMetadata.width && sourceMetadata.height && !aspectRatio) {\n aspectRatio = sourceMetadata.width / sourceMetadata.height\n }\n\n if (layout === `fullWidth`) {\n width = width || sourceMetadata.width || breakpoints[breakpoints.length - 1]\n height = height || Math.round(width / (aspectRatio || DEFAULT_ASPECT_RATIO))\n } else {\n if (!width) {\n if (height && aspectRatio) {\n width = height * aspectRatio\n } else if (sourceMetadata.width) {\n width = sourceMetadata.width\n } else if (height) {\n width = Math.round(height / DEFAULT_ASPECT_RATIO)\n } else {\n width = DEFAULT_FIXED_WIDTH\n }\n }\n\n if (aspectRatio && !height) {\n height = Math.round(width / aspectRatio)\n } else if (!aspectRatio) {\n aspectRatio = width / height\n }\n }\n return { ...args, width, height, aspectRatio, layout, formats }\n}\n\n/**\n * Use this for getting an image for the blurred placeholder. This ensures the\n * aspect ratio and crop match the main image\n */\nexport function getLowResolutionImageURL(\n args: IGatsbyImageHelperArgs,\n width = 20\n): string {\n args = setDefaultDimensions(args)\n const { generateImageSource, filename, aspectRatio } = args\n return generateImageSource(\n filename,\n width,\n Math.round(width / aspectRatio),\n args.sourceMetadata.format || `jpg`,\n args.fit,\n args.options\n )?.src\n}\n\nexport function generateImageData(\n args: IGatsbyImageHelperArgs\n): IGatsbyImageData {\n args = setDefaultDimensions(args)\n\n let {\n pluginName,\n sourceMetadata,\n generateImageSource,\n layout,\n fit,\n options,\n width,\n height,\n filename,\n reporter = { warn },\n backgroundColor,\n placeholderURL,\n } = args\n\n if (!pluginName) {\n reporter.warn(\n `[gatsby-plugin-image] \"generateImageData\" was not passed a plugin name`\n )\n }\n\n if (typeof generateImageSource !== `function`) {\n throw new Error(`generateImageSource must be a function`)\n }\n\n if (!sourceMetadata || (!sourceMetadata.width && !sourceMetadata.height)) {\n // No metadata means we let the CDN handle max size etc, aspect ratio etc\n sourceMetadata = {\n width,\n height,\n format: sourceMetadata?.format || formatFromFilename(filename) || `auto`,\n }\n } else if (!sourceMetadata.format) {\n sourceMetadata.format = formatFromFilename(filename)\n }\n\n const formats = new Set(args.formats)\n\n if (formats.size === 0 || formats.has(`auto`) || formats.has(``)) {\n formats.delete(`auto`)\n formats.delete(``)\n formats.add(sourceMetadata.format)\n }\n\n if (formats.has(`jpg`) && formats.has(`png`)) {\n reporter.warn(\n `[${pluginName}] Specifying both 'jpg' and 'png' formats is not supported. Using 'auto' instead`\n )\n if (sourceMetadata.format === `jpg`) {\n formats.delete(`png`)\n } else {\n formats.delete(`jpg`)\n }\n }\n\n const imageSizes = calculateImageSizes({ ...args, sourceMetadata })\n\n const result: IGatsbyImageData[\"images\"] = {\n sources: [],\n }\n\n let sizes = args.sizes\n if (!sizes) {\n sizes = getSizes(imageSizes.presentationWidth, layout)\n }\n\n formats.forEach(format => {\n const images = imageSizes.sizes\n .map(size => {\n const imageSrc = generateImageSource(\n filename,\n size,\n Math.round(size / imageSizes.aspectRatio),\n format,\n fit,\n options\n )\n if (\n !imageSrc?.width ||\n !imageSrc.height ||\n !imageSrc.src ||\n !imageSrc.format\n ) {\n reporter.warn(\n `[${pluginName}] The resolver for image ${filename} returned an invalid value.`\n )\n return undefined\n }\n return imageSrc\n })\n .filter(Boolean)\n\n if (format === `jpg` || format === `png` || format === `auto`) {\n const unscaled =\n images.find(img => img.width === imageSizes.unscaledWidth) || images[0]\n\n if (unscaled) {\n result.fallback = {\n src: unscaled.src,\n srcSet: getSrcSet(images),\n sizes,\n }\n }\n } else {\n result.sources?.push({\n srcSet: getSrcSet(images),\n sizes,\n type: `image/${format}`,\n })\n }\n })\n\n const imageProps: Partial = {\n images: result,\n layout,\n backgroundColor,\n }\n\n if (placeholderURL) {\n imageProps.placeholder = { fallback: placeholderURL }\n }\n\n switch (layout) {\n case `fixed`:\n imageProps.width = imageSizes.presentationWidth\n imageProps.height = imageSizes.presentationHeight\n break\n\n case `fullWidth`:\n imageProps.width = 1\n imageProps.height = 1 / imageSizes.aspectRatio\n break\n\n case `constrained`:\n imageProps.width = args.width || imageSizes.presentationWidth || 1\n imageProps.height = (imageProps.width || 1) / imageSizes.aspectRatio\n }\n\n return imageProps as IGatsbyImageData\n}\n\nconst dedupeAndSortDensities = (values: Array): Array =>\n Array.from(new Set([1, ...values])).sort(sortNumeric)\n\nexport function calculateImageSizes(args: IImageSizeArgs): IImageSizes {\n const {\n width,\n height,\n filename,\n layout = `constrained`,\n sourceMetadata: imgDimensions,\n reporter = { warn },\n breakpoints = DEFAULT_BREAKPOINTS,\n } = args\n\n // check that all dimensions provided are positive\n const userDimensions = { width, height }\n const erroneousUserDimensions = Object.entries(userDimensions).filter(\n ([_, size]) => typeof size === `number` && size < 1\n )\n if (erroneousUserDimensions.length) {\n throw new Error(\n `Specified dimensions for images must be positive numbers (> 0). Problem dimensions you have are ${erroneousUserDimensions\n .map(dim => dim.join(`: `))\n .join(`, `)}`\n )\n }\n\n if (layout === `fixed`) {\n return fixedImageSizes(args)\n } else if (layout === `constrained`) {\n return responsiveImageSizes(args)\n } else if (layout === `fullWidth`) {\n return responsiveImageSizes({ breakpoints, ...args })\n } else {\n reporter.warn(\n `No valid layout was provided for the image at ${filename}. Valid image layouts are fixed, fullWidth, and constrained. Found ${layout}`\n )\n return {\n sizes: [imgDimensions.width],\n presentationWidth: imgDimensions.width,\n presentationHeight: imgDimensions.height,\n aspectRatio: imgDimensions.width / imgDimensions.height,\n unscaledWidth: imgDimensions.width,\n }\n }\n}\nexport function fixedImageSizes({\n filename,\n sourceMetadata: imgDimensions,\n width,\n height,\n fit = `cover`,\n outputPixelDensities = DEFAULT_PIXEL_DENSITIES,\n reporter = { warn },\n}: IImageSizeArgs): IImageSizes {\n let aspectRatio = imgDimensions.width / imgDimensions.height\n // Sort, dedupe and ensure there's a 1\n const densities = dedupeAndSortDensities(outputPixelDensities)\n\n // If both are provided then we need to check the fit\n if (width && height) {\n const calculated = getDimensionsAndAspectRatio(imgDimensions, {\n width,\n height,\n fit,\n })\n width = calculated.width\n height = calculated.height\n aspectRatio = calculated.aspectRatio\n }\n\n if (!width) {\n if (!height) {\n width = DEFAULT_FIXED_WIDTH\n } else {\n width = Math.round(height * aspectRatio)\n }\n } else if (!height) {\n height = Math.round(width / aspectRatio)\n }\n\n const originalWidth = width // will use this for presentationWidth, don't want to lose it\n const isTopSizeOverriden =\n imgDimensions.width < width || imgDimensions.height < (height as number)\n\n // If the image is smaller than requested, warn the user that it's being processed as such\n // print out this message with the necessary information before we overwrite it for sizing\n if (isTopSizeOverriden) {\n const fixedDimension = imgDimensions.width < width ? `width` : `height`\n reporter.warn(`\nThe requested ${fixedDimension} \"${\n fixedDimension === `width` ? width : height\n }px\" for the image ${filename} was larger than the actual image ${fixedDimension} of ${\n imgDimensions[fixedDimension]\n }px. If possible, replace the current image with a larger one.`)\n\n if (fixedDimension === `width`) {\n width = imgDimensions.width\n height = Math.round(width / aspectRatio)\n } else {\n height = imgDimensions.height\n width = height * aspectRatio\n }\n }\n\n const sizes = densities\n .filter(size => size >= 1) // remove smaller densities because fixed images don't need them\n .map(density => Math.round(density * (width as number)))\n .filter(size => size <= imgDimensions.width)\n\n return {\n sizes,\n aspectRatio,\n presentationWidth: originalWidth,\n presentationHeight: Math.round(originalWidth / aspectRatio),\n unscaledWidth: width,\n }\n}\n\nexport function responsiveImageSizes({\n sourceMetadata: imgDimensions,\n width,\n height,\n fit = `cover`,\n outputPixelDensities = DEFAULT_PIXEL_DENSITIES,\n breakpoints,\n layout,\n}: IImageSizeArgs): IImageSizes {\n let sizes\n let aspectRatio = imgDimensions.width / imgDimensions.height\n // Sort, dedupe and ensure there's a 1\n const densities = dedupeAndSortDensities(outputPixelDensities)\n\n // If both are provided then we need to check the fit\n if (width && height) {\n const calculated = getDimensionsAndAspectRatio(imgDimensions, {\n width,\n height,\n fit,\n })\n width = calculated.width\n height = calculated.height\n aspectRatio = calculated.aspectRatio\n }\n\n // Case 1: width of height were passed in, make sure it isn't larger than the actual image\n width = width && Math.min(width, imgDimensions.width)\n height = height && Math.min(height, imgDimensions.height)\n\n // Case 2: neither width or height were passed in, use default size\n if (!width && !height) {\n width = Math.min(DEFAULT_FLUID_WIDTH, imgDimensions.width)\n height = width / aspectRatio\n }\n\n // if it still hasn't been found, calculate width from the derived height.\n // TS isn't smart enough to realise the type for height has been narrowed here\n if (!width) {\n width = (height as number) * aspectRatio\n }\n\n const originalWidth = width\n const isTopSizeOverriden =\n imgDimensions.width < width || imgDimensions.height < (height as number)\n if (isTopSizeOverriden) {\n width = imgDimensions.width\n height = imgDimensions.height\n }\n\n width = Math.round(width)\n\n if (breakpoints?.length > 0) {\n sizes = breakpoints.filter(size => size <= imgDimensions.width)\n\n // If a larger breakpoint has been filtered-out, add the actual image width instead\n if (\n sizes.length < breakpoints.length &&\n !sizes.includes(imgDimensions.width)\n ) {\n sizes.push(imgDimensions.width)\n }\n } else {\n sizes = densities.map(density => Math.round(density * (width as number)))\n sizes = sizes.filter(size => size <= imgDimensions.width)\n }\n\n // ensure that the size passed in is included in the final output\n if (layout === `constrained` && !sizes.includes(width)) {\n sizes.push(width)\n }\n sizes = sizes.sort(sortNumeric)\n return {\n sizes,\n aspectRatio,\n presentationWidth: originalWidth,\n presentationHeight: Math.round(originalWidth / aspectRatio),\n unscaledWidth: width,\n }\n}\n\nexport function getDimensionsAndAspectRatio(\n dimensions,\n options\n): { width: number; height: number; aspectRatio: number } {\n // Calculate the eventual width/height of the image.\n const imageAspectRatio = dimensions.width / dimensions.height\n\n let width = options.width\n let height = options.height\n\n switch (options.fit) {\n case `fill`: {\n width = options.width ? options.width : dimensions.width\n height = options.height ? options.height : dimensions.height\n break\n }\n case `inside`: {\n const widthOption = options.width\n ? options.width\n : Number.MAX_SAFE_INTEGER\n const heightOption = options.height\n ? options.height\n : Number.MAX_SAFE_INTEGER\n\n width = Math.min(widthOption, Math.round(heightOption * imageAspectRatio))\n height = Math.min(\n heightOption,\n Math.round(widthOption / imageAspectRatio)\n )\n break\n }\n case `outside`: {\n const widthOption = options.width ? options.width : 0\n const heightOption = options.height ? options.height : 0\n\n width = Math.max(widthOption, Math.round(heightOption * imageAspectRatio))\n height = Math.max(\n heightOption,\n Math.round(widthOption / imageAspectRatio)\n )\n break\n }\n\n default: {\n if (options.width && !options.height) {\n width = options.width\n height = Math.round(options.width / imageAspectRatio)\n }\n\n if (options.height && !options.width) {\n width = Math.round(options.height * imageAspectRatio)\n height = options.height\n }\n }\n }\n\n return {\n width,\n height,\n aspectRatio: width / height,\n }\n}\n","/* global GATSBY___IMAGE */\nimport { generateImageData, EVERY_BREAKPOINT } from \"../image-utils\"\nimport type { CSSProperties, HTMLAttributes, ImgHTMLAttributes } from \"react\"\nimport type { Node } from \"gatsby\"\nimport type { PlaceholderProps } from \"./placeholder\"\nimport type { MainImageProps } from \"./main-image\"\nimport type { IGatsbyImageData } from \"./gatsby-image.browser\"\nimport type {\n IGatsbyImageHelperArgs,\n Layout,\n IImage,\n ImageFormat,\n} from \"../image-utils\"\n\n// Native lazy-loading support: https://addyosmani.com/blog/lazy-loading/\nexport const hasNativeLazyLoadSupport = (): boolean =>\n typeof HTMLImageElement !== `undefined` &&\n `loading` in HTMLImageElement.prototype\n\nexport function gatsbyImageIsInstalled(): boolean {\n return typeof GATSBY___IMAGE !== `undefined` && GATSBY___IMAGE\n}\n\nexport type IGatsbyImageDataParent = T & {\n gatsbyImageData: IGatsbyImageData\n}\nexport type IGatsbyImageParent = T & {\n gatsbyImage: IGatsbyImageData\n}\nexport type FileNode = Partial & {\n childImageSharp?: IGatsbyImageDataParent>\n}\n\nconst isGatsbyImageData = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n node: IGatsbyImageData | any\n): node is IGatsbyImageData =>\n // 🦆 check for a deep prop to be sure this is a valid gatsbyImageData object\n Boolean(node?.images?.fallback?.src)\n\nconst isGatsbyImageDataParent = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n node: IGatsbyImageDataParent | any\n): node is IGatsbyImageDataParent => Boolean(node?.gatsbyImageData)\n\nconst isGatsbyImageParent = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n node: IGatsbyImageParent | any\n): node is IGatsbyImageParent => Boolean(node?.gatsbyImage)\n\nexport type ImageDataLike =\n | FileNode\n | IGatsbyImageDataParent\n | IGatsbyImageParent\n | IGatsbyImageData\n\nexport const getImage = (\n node: ImageDataLike | null\n): IGatsbyImageData | undefined => {\n // This checks both for gatsbyImageData and gatsbyImage\n if (isGatsbyImageData(node)) {\n return node\n }\n // gatsbyImageData GraphQL field\n if (isGatsbyImageDataParent(node)) {\n return node.gatsbyImageData\n }\n // gatsbyImage GraphQL field for Gatsby's Image CDN service\n if (isGatsbyImageParent(node)) {\n return node.gatsbyImage\n }\n return node?.childImageSharp?.gatsbyImageData\n}\n\nexport const getSrc = (node: ImageDataLike): string | undefined =>\n getImage(node)?.images?.fallback?.src\n\nexport const getSrcSet = (node: ImageDataLike): string | undefined =>\n getImage(node)?.images?.fallback?.srcSet\n\nexport function getWrapperProps(\n width: number,\n height: number,\n layout: Layout\n): Pick, \"className\" | \"style\"> & {\n \"data-gatsby-image-wrapper\": string\n} {\n const wrapperStyle: CSSProperties = {}\n\n let className = `gatsby-image-wrapper`\n\n // If the plugin isn't installed we need to apply the styles inline\n if (!gatsbyImageIsInstalled()) {\n wrapperStyle.position = `relative`\n wrapperStyle.overflow = `hidden`\n }\n\n if (layout === `fixed`) {\n wrapperStyle.width = width\n wrapperStyle.height = height\n } else if (layout === `constrained`) {\n if (!gatsbyImageIsInstalled()) {\n wrapperStyle.display = `inline-block`\n wrapperStyle.verticalAlign = `top`\n }\n className = `gatsby-image-wrapper gatsby-image-wrapper-constrained`\n }\n\n return {\n className,\n \"data-gatsby-image-wrapper\": ``,\n style: wrapperStyle,\n }\n}\n\nexport interface IUrlBuilderArgs {\n width: number\n height: number\n baseUrl: string\n format: ImageFormat\n options: OptionsType\n}\nexport interface IGetImageDataArgs> {\n baseUrl: string\n /**\n * For constrained and fixed images, the size of the image element\n */\n width?: number\n height?: number\n /**\n * If available, pass the source image width and height\n */\n sourceWidth?: number\n sourceHeight?: number\n /**\n * If only one dimension is passed, then this will be used to calculate the other.\n */\n aspectRatio?: number\n layout?: Layout\n /**\n * Returns a URL based on the passed arguments. Should be a pure function\n */\n urlBuilder: (args: IUrlBuilderArgs) => string\n\n /**\n * Should be a data URI\n */\n placeholderURL?: string\n backgroundColor?: string\n /**\n * Used in error messages etc\n */\n pluginName?: string\n\n /**\n * If you do not support auto-format, pass an array of image types here\n */\n formats?: Array\n\n breakpoints?: Array\n\n /**\n * Passed to the urlBuilder function\n */\n options?: OptionsType\n}\n\n/**\n * Use this hook to generate gatsby-plugin-image data in the browser.\n */\nexport function getImageData({\n baseUrl,\n urlBuilder,\n sourceWidth,\n sourceHeight,\n pluginName = `getImageData`,\n formats = [`auto`],\n breakpoints,\n options,\n ...props\n}: IGetImageDataArgs): IGatsbyImageData {\n if (\n !breakpoints?.length &&\n (props.layout === `fullWidth` || (props.layout as string) === `FULL_WIDTH`)\n ) {\n breakpoints = EVERY_BREAKPOINT\n }\n const generateImageSource = (\n baseUrl: string,\n width: number,\n height?: number,\n format?: ImageFormat\n ): IImage => {\n return {\n width,\n height,\n format,\n src: urlBuilder({ baseUrl, width, height, options, format }),\n }\n }\n\n const sourceMetadata: IGatsbyImageHelperArgs[\"sourceMetadata\"] = {\n width: sourceWidth,\n height: sourceHeight,\n format: `auto`,\n }\n\n const args: IGatsbyImageHelperArgs = {\n ...props,\n pluginName,\n generateImageSource,\n filename: baseUrl,\n formats,\n breakpoints,\n sourceMetadata,\n }\n return generateImageData(args)\n}\n\nexport function getMainProps(\n isLoading: boolean,\n isLoaded: boolean,\n images: IGatsbyImageData[\"images\"],\n loading?: \"eager\" | \"lazy\",\n style: CSSProperties = {}\n): Partial {\n // fallback when it's not configured in gatsby-config.\n if (!gatsbyImageIsInstalled()) {\n style = {\n height: `100%`,\n left: 0,\n position: `absolute`,\n top: 0,\n transform: `translateZ(0)`,\n transition: `opacity 250ms linear`,\n width: `100%`,\n willChange: `opacity`,\n ...style,\n }\n }\n\n const result = {\n ...images,\n loading,\n shouldLoad: isLoading,\n \"data-main-image\": ``,\n style: {\n ...style,\n opacity: isLoaded ? 1 : 0,\n },\n }\n\n return result\n}\n\nexport type PlaceholderImageAttrs = ImgHTMLAttributes &\n Pick & {\n \"data-placeholder-image\"?: string\n }\n\nexport function getPlaceholderProps(\n placeholder: PlaceholderImageAttrs | undefined,\n isLoaded: boolean,\n layout: Layout,\n width?: number,\n height?: number,\n backgroundColor?: string,\n objectFit?: CSSProperties[\"objectFit\"],\n objectPosition?: CSSProperties[\"objectPosition\"]\n): PlaceholderImageAttrs {\n const wrapperStyle: CSSProperties = {}\n\n if (backgroundColor) {\n wrapperStyle.backgroundColor = backgroundColor\n\n if (layout === `fixed`) {\n wrapperStyle.width = width\n wrapperStyle.height = height\n wrapperStyle.backgroundColor = backgroundColor\n wrapperStyle.position = `relative`\n } else if (layout === `constrained`) {\n wrapperStyle.position = `absolute`\n wrapperStyle.top = 0\n wrapperStyle.left = 0\n wrapperStyle.bottom = 0\n wrapperStyle.right = 0\n } else if (layout === `fullWidth`) {\n wrapperStyle.position = `absolute`\n wrapperStyle.top = 0\n wrapperStyle.left = 0\n wrapperStyle.bottom = 0\n wrapperStyle.right = 0\n }\n }\n\n if (objectFit) {\n wrapperStyle.objectFit = objectFit\n }\n\n if (objectPosition) {\n wrapperStyle.objectPosition = objectPosition\n }\n const result: PlaceholderImageAttrs = {\n ...placeholder,\n \"aria-hidden\": true,\n \"data-placeholder-image\": ``,\n style: {\n opacity: isLoaded ? 0 : 1,\n transition: `opacity 500ms linear`,\n ...wrapperStyle,\n },\n }\n\n // fallback when it's not configured in gatsby-config.\n if (!gatsbyImageIsInstalled()) {\n result.style = {\n height: `100%`,\n left: 0,\n position: `absolute`,\n top: 0,\n width: `100%`,\n }\n }\n\n return result\n}\n\nexport interface IArtDirectedImage {\n media: string\n image: IGatsbyImageData\n}\n\n/**\n * Generate a Gatsby image data object with multiple, art-directed images that display at different\n * resolutions.\n *\n * @param defaultImage The image displayed when no media query matches.\n * It is also used for all other settings applied to the image, such as width, height and layout.\n * You should pass a className to the component with media queries to adjust the size of the container,\n * as this cannot be adjusted automatically.\n * @param artDirected Array of objects which each contains a `media` string which is a media query\n * such as `(min-width: 320px)`, and the image object to use when that query matches.\n */\nexport function withArtDirection(\n defaultImage: IGatsbyImageData,\n artDirected: Array\n): IGatsbyImageData {\n const { images, placeholder, ...props } = defaultImage\n const output: IGatsbyImageData = {\n ...props,\n images: {\n ...images,\n sources: [],\n },\n placeholder: placeholder && {\n ...placeholder,\n sources: [],\n },\n }\n\n artDirected.forEach(({ media, image }) => {\n if (!media) {\n if (process.env.NODE_ENV === `development`) {\n console.warn(\n \"[gatsby-plugin-image] All art-directed images passed to must have a value set for `media`. Skipping.\"\n )\n }\n return\n }\n\n if (\n image.layout !== defaultImage.layout &&\n process.env.NODE_ENV === `development`\n ) {\n console.warn(\n `[gatsby-plugin-image] Mismatched image layout: expected \"${defaultImage.layout}\" but received \"${image.layout}\". All art-directed images use the same layout as the default image`\n )\n }\n\n output.images.sources.push(\n ...image.images.sources.map(source => {\n return { ...source, media }\n }),\n {\n media,\n srcSet: image.images.fallback.srcSet,\n }\n )\n\n if (!output.placeholder) {\n return\n }\n\n output.placeholder.sources.push({\n media,\n srcSet: image.placeholder.fallback,\n })\n })\n output.images.sources.push(...images.sources)\n if (placeholder?.sources) {\n output.placeholder?.sources.push(...placeholder.sources)\n }\n return output\n}\n","import React, { Fragment, FunctionComponent, PropsWithChildren } from \"react\"\nimport terserMacro from \"../../macros/terser.macro\"\nimport { Layout } from \"../image-utils\"\n\nexport interface ILayoutWrapperProps {\n layout: Layout\n width: number\n height: number\n}\n\nconst NativeScriptLoading: FunctionComponent = () => (\n \n)\n\nexport function getSizer(\n layout: Layout,\n width: number,\n height: number\n): string {\n let sizer = ``\n if (layout === `fullWidth`) {\n sizer = `
`\n }\n\n if (layout === `constrained`) {\n sizer = `
\"\"
`\n }\n\n return sizer\n}\n\nconst Sizer: FunctionComponent = function Sizer({\n layout,\n width,\n height,\n}) {\n if (layout === `fullWidth`) {\n return (\n
\n )\n }\n\n if (layout === `constrained`) {\n return (\n
\n \n
\n )\n }\n\n return null\n}\n\nexport const LayoutWrapper: FunctionComponent<\n PropsWithChildren\n> = function LayoutWrapper({ children, ...props }) {\n return (\n \n \n {children}\n\n {SERVER ? : null}\n \n )\n}\n","import React, { FunctionComponent, ImgHTMLAttributes } from \"react\"\nimport * as PropTypes from \"prop-types\"\n\nexport interface IResponsiveImageProps {\n sizes?: string\n srcSet: string\n}\n\nexport type SourceProps = IResponsiveImageProps &\n (\n | {\n media: string\n type?: string\n }\n | {\n media?: string\n type: string\n }\n )\n\ntype FallbackProps = { src: string } & Partial\n\ntype ImageProps = ImgHTMLAttributes & {\n src: string\n alt: string\n shouldLoad: boolean\n}\n\nexport type PictureProps = ImgHTMLAttributes & {\n fallback?: FallbackProps\n sources?: Array\n alt: string\n shouldLoad?: boolean\n}\n\nconst Image: FunctionComponent = function Image({\n src,\n srcSet,\n loading,\n alt = ``,\n shouldLoad,\n ...props\n}) {\n return (\n \n )\n}\n\nexport const Picture: React.FC = function Picture({\n fallback,\n sources = [],\n shouldLoad = true,\n ...props\n}) {\n const sizes = props.sizes || fallback?.sizes\n const fallbackImage = (\n \n )\n\n if (!sources.length) {\n return fallbackImage\n }\n\n return (\n \n {sources.map(({ media, srcSet, type }) => (\n \n ))}\n {fallbackImage}\n \n )\n}\n\nImage.propTypes = {\n src: PropTypes.string.isRequired,\n alt: PropTypes.string.isRequired,\n sizes: PropTypes.string,\n srcSet: PropTypes.string,\n shouldLoad: PropTypes.bool,\n}\n\nPicture.displayName = `Picture`\nPicture.propTypes = {\n alt: PropTypes.string.isRequired,\n shouldLoad: PropTypes.bool,\n fallback: PropTypes.exact({\n src: PropTypes.string.isRequired,\n srcSet: PropTypes.string,\n sizes: PropTypes.string,\n }),\n sources: PropTypes.arrayOf(\n PropTypes.oneOfType([\n PropTypes.exact({\n media: PropTypes.string.isRequired,\n type: PropTypes.string,\n sizes: PropTypes.string,\n srcSet: PropTypes.string.isRequired,\n }),\n PropTypes.exact({\n media: PropTypes.string,\n type: PropTypes.string.isRequired,\n sizes: PropTypes.string,\n srcSet: PropTypes.string.isRequired,\n }),\n ])\n ),\n}\n","import React, { FunctionComponent, ImgHTMLAttributes } from \"react\"\nimport * as PropTypes from \"prop-types\"\nimport { Picture, SourceProps } from \"./picture\"\n\nexport type PlaceholderProps = ImgHTMLAttributes & {\n fallback?: string\n sources?: Array\n}\n\nexport const Placeholder: FunctionComponent =\n function Placeholder({ fallback, ...props }) {\n if (fallback) {\n return (\n \n )\n } else {\n return
\n }\n }\n\nPlaceholder.displayName = `Placeholder`\nPlaceholder.propTypes = {\n fallback: PropTypes.string,\n sources: Picture.propTypes?.sources,\n alt: function (props, propName, componentName): Error | null {\n if (!props[propName]) {\n return null\n }\n\n return new Error(\n `Invalid prop \\`${propName}\\` supplied to \\`${componentName}\\`. Validation failed.`\n )\n },\n}\n","import React from \"react\"\nimport { Picture, PictureProps } from \"./picture\"\n\nexport type MainImageProps = PictureProps\n\nexport const MainImage: React.FC = function MainImage(props) {\n return (\n <>\n \n \n \n )\n}\n\nMainImage.displayName = `MainImage`\nMainImage.propTypes = Picture.propTypes\n","import React from \"react\"\nimport { getWrapperProps, getMainProps, getPlaceholderProps } from \"./hooks\"\nimport { Placeholder } from \"./placeholder\"\nimport { MainImage, MainImageProps } from \"./main-image\"\nimport { LayoutWrapper } from \"./layout-wrapper\"\nimport PropTypes from \"prop-types\"\nimport type { FunctionComponent, WeakValidationMap } from \"react\"\nimport type { GatsbyImageProps, IGatsbyImageData } from \"./gatsby-image.browser\"\n\nconst removeNewLines = (str: string): string => str.replace(/\\n/g, ``)\n\nexport const GatsbyImage: FunctionComponent =\n function GatsbyImage({\n as = `div`,\n className,\n class: preactClass,\n style,\n image,\n loading = `lazy`,\n imgClassName,\n imgStyle,\n backgroundColor,\n objectFit,\n objectPosition,\n ...props\n }) {\n if (!image) {\n console.warn(`[gatsby-plugin-image] Missing image prop`)\n return null\n }\n\n if (preactClass) {\n className = preactClass\n }\n\n imgStyle = {\n objectFit,\n objectPosition,\n backgroundColor,\n ...imgStyle,\n }\n\n const {\n width,\n height,\n layout,\n images,\n placeholder,\n backgroundColor: placeholderBackgroundColor,\n } = image\n\n const {\n style: wStyle,\n className: wClass,\n ...wrapperProps\n } = getWrapperProps(width, height, layout)\n\n const cleanedImages: IGatsbyImageData[\"images\"] = {\n fallback: undefined,\n sources: [],\n }\n if (images.fallback) {\n cleanedImages.fallback = {\n ...images.fallback,\n srcSet: images.fallback.srcSet\n ? removeNewLines(images.fallback.srcSet)\n : undefined,\n }\n }\n\n if (images.sources) {\n cleanedImages.sources = images.sources.map(source => {\n return {\n ...source,\n srcSet: removeNewLines(source.srcSet),\n }\n })\n }\n\n return React.createElement(\n as,\n {\n ...wrapperProps,\n style: {\n ...wStyle,\n ...style,\n backgroundColor,\n },\n className: `${wClass}${className ? ` ${className}` : ``}`,\n },\n \n \n\n )}\n // When eager is set we want to start the isLoading state on true (we want to load the img without react)\n {...getMainProps(\n loading === `eager`,\n false,\n cleanedImages,\n loading,\n imgStyle\n )}\n />\n \n )\n }\n\nexport const altValidator: PropTypes.Validator = (\n props: GatsbyImageProps,\n propName,\n componentName,\n ...rest\n): Error | undefined => {\n if (!props.alt && props.alt !== ``) {\n return new Error(\n `The \"alt\" prop is required in ${componentName}. If the image is purely presentational then pass an empty string: e.g. alt=\"\". Learn more: https://a11y-style-guide.com/style-guide/section-media.html`\n )\n }\n\n return PropTypes.string(props, propName, componentName, ...rest)\n}\n\nexport const propTypes = {\n image: PropTypes.object.isRequired,\n alt: altValidator,\n} as WeakValidationMap\n","import {\n createElement,\n memo,\n useMemo,\n useEffect,\n useLayoutEffect,\n useRef,\n} from \"react\"\nimport {\n getWrapperProps,\n gatsbyImageIsInstalled,\n hasNativeLazyLoadSupport,\n} from \"./hooks\"\nimport { getSizer } from \"./layout-wrapper\"\nimport { propTypes } from \"./gatsby-image.server\"\nimport type {\n FC,\n ElementType,\n FunctionComponent,\n ImgHTMLAttributes,\n CSSProperties,\n ReactEventHandler,\n} from \"react\"\nimport type { renderImageToString } from \"./lazy-hydrate\"\nimport type { PlaceholderProps } from \"./placeholder\"\nimport type { MainImageProps } from \"./main-image\"\nimport type { Layout } from \"../image-utils\"\n\nconst imageCache = new Set()\nlet renderImageToStringPromise\nlet renderImage: typeof renderImageToString | undefined\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport interface GatsbyImageProps\n extends Omit<\n ImgHTMLAttributes,\n \"placeholder\" | \"onLoad\" | \"src\" | \"srcSet\" | \"width\" | \"height\"\n > {\n alt: string\n as?: ElementType\n className?: string\n class?: string\n imgClassName?: string\n image: IGatsbyImageData\n imgStyle?: CSSProperties\n backgroundColor?: string\n objectFit?: CSSProperties[\"objectFit\"]\n objectPosition?: CSSProperties[\"objectPosition\"]\n onLoad?: (props: { wasCached: boolean }) => void\n onError?: ReactEventHandler\n onStartLoad?: (props: { wasCached: boolean }) => void\n}\n\nexport interface IGatsbyImageData {\n layout: Layout\n width: number\n height: number\n backgroundColor?: string\n images: Pick\n placeholder?: Pick\n}\n\nconst GatsbyImageHydrator: FC = function GatsbyImageHydrator({\n as = `div`,\n image,\n style,\n backgroundColor,\n className,\n class: preactClass,\n onStartLoad,\n onLoad,\n onError,\n ...props\n}) {\n const { width, height, layout } = image\n const {\n style: wStyle,\n className: wClass,\n ...wrapperProps\n } = getWrapperProps(width, height, layout)\n const root = useRef()\n const cacheKey = useMemo(() => JSON.stringify(image.images), [image.images])\n\n // Preact uses class instead of className so we need to check for both\n if (preactClass) {\n className = preactClass\n }\n\n const sizer = getSizer(layout, width, height)\n\n useEffect(() => {\n if (!renderImageToStringPromise) {\n renderImageToStringPromise = import(`./lazy-hydrate`).then(\n ({ renderImageToString, swapPlaceholderImage }) => {\n renderImage = renderImageToString\n\n return {\n renderImageToString,\n swapPlaceholderImage,\n }\n }\n )\n }\n\n // The plugin image component is a bit special where if it's server-side rendered, we add extra script tags to support lazy-loading without\n // In this case we stop hydration but fire the correct events.\n const ssrImage = root.current.querySelector(\n `[data-gatsby-image-ssr]`\n ) as HTMLImageElement\n if (ssrImage && hasNativeLazyLoadSupport()) {\n if (ssrImage.complete) {\n // Trigger onStartload and onLoad events\n onStartLoad?.({\n wasCached: true,\n })\n onLoad?.({\n wasCached: true,\n })\n\n // remove ssr key for state updates but add delay to not fight with native code snippt of gatsby-ssr\n setTimeout(() => {\n ssrImage.removeAttribute(`data-gatsby-image-ssr`)\n }, 0)\n } else {\n onStartLoad?.({\n wasCached: true,\n })\n\n ssrImage.addEventListener(`load`, function onLoadListener() {\n ssrImage.removeEventListener(`load`, onLoadListener)\n\n onLoad?.({\n wasCached: true,\n })\n // remove ssr key for state updates but add delay to not fight with native code snippt of gatsby-ssr\n setTimeout(() => {\n ssrImage.removeAttribute(`data-gatsby-image-ssr`)\n }, 0)\n })\n }\n\n imageCache.add(cacheKey)\n\n return\n }\n\n if (renderImage && imageCache.has(cacheKey)) {\n return\n }\n\n let animationFrame\n let cleanupCallback\n renderImageToStringPromise.then(\n ({ renderImageToString, swapPlaceholderImage }) => {\n if (!root.current) {\n return\n }\n\n root.current.innerHTML = renderImageToString({\n isLoading: true,\n isLoaded: imageCache.has(cacheKey),\n image,\n ...props,\n })\n\n if (!imageCache.has(cacheKey)) {\n animationFrame = requestAnimationFrame(() => {\n if (root.current) {\n cleanupCallback = swapPlaceholderImage(\n root.current,\n cacheKey,\n imageCache,\n style,\n onStartLoad,\n onLoad,\n onError\n )\n }\n })\n }\n }\n )\n\n // eslint-disable-next-line consistent-return\n return (): void => {\n if (animationFrame) {\n cancelAnimationFrame(animationFrame)\n }\n if (cleanupCallback) {\n cleanupCallback()\n }\n }\n }, [image])\n\n // useLayoutEffect is ran before React commits to the DOM. This allows us to make sure our HTML is using our cached image version\n useLayoutEffect(() => {\n if (imageCache.has(cacheKey) && renderImage) {\n root.current.innerHTML = renderImage({\n isLoading: imageCache.has(cacheKey),\n isLoaded: imageCache.has(cacheKey),\n image,\n ...props,\n })\n\n // Trigger onStartload and onLoad events\n onStartLoad?.({\n wasCached: true,\n })\n onLoad?.({\n wasCached: true,\n })\n }\n }, [image])\n\n // By keeping all props equal React will keep the component in the DOM\n return createElement(as, {\n ...wrapperProps,\n style: {\n ...wStyle,\n ...style,\n backgroundColor,\n },\n className: `${wClass}${className ? ` ${className}` : ``}`,\n ref: root,\n dangerouslySetInnerHTML: {\n __html: sizer,\n },\n suppressHydrationWarning: true,\n })\n}\n\nexport const GatsbyImage: FunctionComponent = memo(\n function GatsbyImage(props) {\n if (!props.image) {\n if (process.env.NODE_ENV === `development`) {\n console.warn(`[gatsby-plugin-image] Missing image prop`)\n }\n\n return null\n }\n\n if (!gatsbyImageIsInstalled() && process.env.NODE_ENV === `development`) {\n console.warn(\n `[gatsby-plugin-image] You're missing out on some cool performance features. Please add \"gatsby-plugin-image\" to your gatsby-config.js`\n )\n }\n\n return createElement(GatsbyImageHydrator, props)\n }\n)\n\nGatsbyImage.propTypes = propTypes\nGatsbyImage.displayName = `GatsbyImage`\n","import React, { FunctionComponent, ReactElement } from \"react\"\nimport {\n altValidator,\n GatsbyImage as GatsbyImageServer,\n} from \"./gatsby-image.server\"\nimport { GatsbyImageProps, IGatsbyImageData } from \"./gatsby-image.browser\"\nimport PropTypes from \"prop-types\"\nimport { ISharpGatsbyImageArgs } from \"../image-utils\"\n\nexport interface IStaticImageProps\n extends Omit,\n Omit {\n src: string\n filename?: string\n}\n\n// These values are added by Babel. Do not add them manually\ninterface IPrivateProps {\n __imageData?: IGatsbyImageData\n __error?: string\n}\n\nexport function _getStaticImage(\n GatsbyImage: FunctionComponent\n): React.FC {\n return function StaticImage({\n src,\n __imageData: imageData,\n __error,\n // We extract these because they're not meant to be passed-down to GatsbyImage\n /* eslint-disable @typescript-eslint/no-unused-vars */\n width,\n height,\n aspectRatio,\n tracedSVGOptions,\n placeholder,\n formats,\n quality,\n transformOptions,\n jpgOptions,\n pngOptions,\n webpOptions,\n avifOptions,\n blurredOptions,\n breakpoints,\n outputPixelDensities,\n /* eslint-enable @typescript-eslint/no-unused-vars */\n ...props\n }): ReactElement {\n if (__error) {\n console.warn(__error)\n }\n\n if (imageData) {\n return \n }\n console.warn(`Image not loaded`, src)\n if (!__error && process.env.NODE_ENV === `development`) {\n console.warn(\n `Please ensure that \"gatsby-plugin-image\" is included in the plugins array in gatsby-config.js, and that your version of gatsby is at least 2.24.78`\n )\n }\n return null\n }\n}\n\nconst StaticImage: React.FC =\n _getStaticImage(GatsbyImageServer)\n\nconst checkDimensionProps: PropTypes.Validator = (\n props: IStaticImageProps & IPrivateProps,\n propName: keyof IStaticImageProps & IPrivateProps,\n ...rest\n) => {\n if (\n props.layout === `fullWidth` &&\n (propName === `width` || propName === `height`) &&\n props[propName]\n ) {\n return new Error(\n `\"${propName}\" ${props[propName]} may not be passed when layout is fullWidth.`\n )\n }\n return PropTypes.number(props, propName, ...rest)\n}\n\nconst validLayouts = new Set([`fixed`, `fullWidth`, `constrained`])\n\nexport const propTypes = {\n src: PropTypes.string.isRequired,\n alt: altValidator,\n width: checkDimensionProps,\n height: checkDimensionProps,\n sizes: PropTypes.string,\n layout: (props: IStaticImageProps & IPrivateProps): Error | undefined => {\n if (props.layout === undefined) {\n return undefined\n }\n if (validLayouts.has(props.layout)) {\n return undefined\n }\n\n return new Error(\n `Invalid value ${props.layout}\" provided for prop \"layout\". Defaulting to \"constrained\". Valid values are \"fixed\", \"fullWidth\" or \"constrained\".`\n )\n },\n}\n\nStaticImage.displayName = `StaticImage`\nStaticImage.propTypes = propTypes\n\nexport { StaticImage }\n","import {\n GatsbyImage as GatsbyImageBrowser,\n IGatsbyImageData,\n} from \"./gatsby-image.browser\"\nimport React from \"react\"\nimport {\n _getStaticImage,\n propTypes,\n IStaticImageProps,\n} from \"./static-image.server\"\n// These values are added by Babel. Do not add them manually\ninterface IPrivateProps {\n __imageData?: IGatsbyImageData\n __error?: string\n}\n\nconst StaticImage: React.FC =\n _getStaticImage(GatsbyImageBrowser)\n\nStaticImage.displayName = `StaticImage`\nStaticImage.propTypes = propTypes\n\nexport { StaticImage }\n","import React from \"react\";\n\nimport { Link } from \"gatsby\";\n\nimport { IProjectPreviewQueryResult } from \"../../types/project.type\";\nimport { GatsbyImage, getImage } from \"gatsby-plugin-image\";\nimport { LocalBusinessMetadata } from \"../common/metadata\";\n\nconst ProjectPreview = ({\n project,\n className,\n theme,\n}: {\n project: IProjectPreviewQueryResult;\n className?: string;\n theme: \"dark\" | \"light\";\n}) => {\n const cover = getImage(project.frontmatter.cover);\n const { title } = project.frontmatter;\n\n const fontColorClass10 =\n theme === \"light\"\n ? \"text-main-100 hover:text-main-10\"\n : \"text-secondary-100 hover:text-secondary-10\";\n const bgColors =\n theme === \"light\"\n ? \"bg-secondary-70 hover:bg-secondary-100\"\n : \"bg-main-100 hover:bg-main-100\";\n\n return (\n \n {cover ? (\n \n ) : null}\n \n {title.toUpperCase()}\n \n \n \n );\n};\n\nexport default ProjectPreview;\n"],"names":["UPPERCASE","LOWERCASE","LEADING_CAPITAL","IDENTIFIER","SEPARATORS","LEADING_SEPARATORS","RegExp","source","SEPARATORS_AND_IDENTIFIER","NUMBERS_AND_IDENTIFIER","camelCase","input","options","Array","isArray","TypeError","pascalCase","preserveConsecutiveUppercase","map","x","trim","filter","length","join","toLowerCase","locale","string","toLocaleLowerCase","toUpperCase","toLocaleUpperCase","isLastCharLower","isLastCharUpper","isLastLastCharUpper","i","character","test","slice","preserveCamelCase","replace","lastIndex","m1","charAt","_","identifier","m","postProcess","module","exports","W","hasNativeLazyLoadSupport","HTMLImageElement","prototype","e","t","a","Boolean","images","fallback","src","gatsbyImageData","gatsbyImage","childImageSharp","z","s","width","height","className","style","P","h","loading","shouldLoad","opacity","A","r","n","o","l","backgroundColor","position","top","left","bottom","right","objectFit","objectPosition","d","transition","H","F","_ref5","layout","paddingTop","maxWidth","display","alt","role","G","children","u","V","B","U","srcSet","decoding","Y","sources","sizes","_ref6","media","type","key","X","propTypes","isRequired","displayName","J","Z","Error","K","Q","ee","te","ae","_len","arguments","_key","c","apply","concat","ie","image","se","re","ne","Set","oe","le","de","as","class","g","onStartLoad","p","onLoad","onError","f","w","y","b","v","E","k","S","M","N","$","JSON","stringify","I","then","_ref7","renderImageToString","swapPlaceholderImage","current","querySelector","complete","wasCached","setTimeout","removeAttribute","addEventListener","removeEventListener","add","has","_ref8","innerHTML","isLoading","isLoaded","requestAnimationFrame","cancelAnimationFrame","ref","dangerouslySetInnerHTML","__html","suppressHydrationWarning","ce","he","ue","__imageData","__error","console","warn","ge","imgClassName","imgStyle","placeholder","pe","_len2","_key2","me","fe","we","_ref","project","theme","cover","getImage","frontmatter","title","fontColorClass10","bgColors","React","Link","to","id","itemScope","itemType","GatsbyImage","itemProp","LocalBusinessMetadata"],"sourceRoot":""} \ No newline at end of file diff --git a/6bc48222ba83afa56babedfa3f8ecf0aa4bc5b28-cd60fa92803063beafa0.js b/6bc48222ba83afa56babedfa3f8ecf0aa4bc5b28-cd60fa92803063beafa0.js new file mode 100644 index 00000000..c0045818 --- /dev/null +++ b/6bc48222ba83afa56babedfa3f8ecf0aa4bc5b28-cd60fa92803063beafa0.js @@ -0,0 +1,2 @@ +"use strict";(self.webpackChunkcode_cave=self.webpackChunkcode_cave||[]).push([[517],{3204:function(e){const t=/[\p{Lu}]/u,a=/[\p{Ll}]/u,r=/^[\p{Lu}](?![\p{Lu}])/gu,n=/([\p{Alpha}\p{N}_]|$)/u,s=/[_.\- ]+/,i=new RegExp("^"+s.source),o=new RegExp(s.source+n.source,"gu"),l=new RegExp("\\d+"+n.source,"gu"),c=(e,n)=>{if("string"!=typeof e&&!Array.isArray(e))throw new TypeError("Expected the input to be `string | string[]`");if(n={pascalCase:!1,preserveConsecutiveUppercase:!1,...n},0===(e=Array.isArray(e)?e.map((e=>e.trim())).filter((e=>e.length)).join("-"):e.trim()).length)return"";const s=!1===n.locale?e=>e.toLowerCase():e=>e.toLocaleLowerCase(n.locale),c=!1===n.locale?e=>e.toUpperCase():e=>e.toLocaleUpperCase(n.locale);if(1===e.length)return n.pascalCase?c(e):s(e);return e!==s(e)&&(e=((e,r,n)=>{let s=!1,i=!1,o=!1;for(let l=0;l(r.lastIndex=0,e.replace(r,(e=>t(e)))))(e,s):s(e),n.pascalCase&&(e=c(e.charAt(0))+e.slice(1)),((e,t)=>(o.lastIndex=0,l.lastIndex=0,e.replace(o,((e,a)=>t(a))).replace(l,(e=>t(e)))))(e,c)};e.exports=c,e.exports.default=c},8032:function(e,t,a){a.d(t,{G:function(){return R},L:function(){return h},M:function(){return k},P:function(){return x},_:function(){return o},a:function(){return i},b:function(){return d},c:function(){return c},g:function(){return g},h:function(){return l}});var r=a(7294),n=(a(3204),a(5697)),s=a.n(n);function i(){return i=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0||(n[a]=e[a]);return n}const l=()=>"undefined"!=typeof HTMLImageElement&&"loading"in HTMLImageElement.prototype;const c=e=>{var t;return(e=>{var t,a;return Boolean(null==e||null==(t=e.images)||null==(a=t.fallback)?void 0:a.src)})(e)?e:(e=>Boolean(null==e?void 0:e.gatsbyImageData))(e)?e.gatsbyImageData:(e=>Boolean(null==e?void 0:e.gatsbyImage))(e)?e.gatsbyImage:null==e||null==(t=e.childImageSharp)?void 0:t.gatsbyImageData};function u(e,t,a){const r={};let n="gatsby-image-wrapper";return"fixed"===a?(r.width=e,r.height=t):"constrained"===a&&(n="gatsby-image-wrapper gatsby-image-wrapper-constrained"),{className:n,"data-gatsby-image-wrapper":"",style:r}}function d(e,t,a,r,n){return void 0===n&&(n={}),i({},a,{loading:r,shouldLoad:e,"data-main-image":"",style:i({},n,{opacity:t?1:0})})}function g(e,t,a,r,n,s,o,l){const c={};s&&(c.backgroundColor=s,"fixed"===a?(c.width=r,c.height=n,c.backgroundColor=s,c.position="relative"):("constrained"===a||"fullWidth"===a)&&(c.position="absolute",c.top=0,c.left=0,c.bottom=0,c.right=0)),o&&(c.objectFit=o),l&&(c.objectPosition=l);const u=i({},e,{"aria-hidden":!0,"data-placeholder-image":"",style:i({opacity:t?0:1,transition:"opacity 500ms linear"},c)});return u}const p=["children"],m=function(e){let{layout:t,width:a,height:n}=e;return"fullWidth"===t?r.createElement("div",{"aria-hidden":!0,style:{paddingTop:n/a*100+"%"}}):"constrained"===t?r.createElement("div",{style:{maxWidth:a,display:"block"}},r.createElement("img",{alt:"",role:"presentation","aria-hidden":"true",src:`data:image/svg+xml;charset=utf-8,%3Csvg%20height='${n}'%20width='${a}'%20xmlns='http://www.w3.org/2000/svg'%20version='1.1'%3E%3C/svg%3E`,style:{maxWidth:"100%",display:"block",position:"static"}})):null},h=function(e){let{children:t}=e,a=o(e,p);return r.createElement(r.Fragment,null,r.createElement(m,i({},a)),t,null)},y=["src","srcSet","loading","alt","shouldLoad"],f=["fallback","sources","shouldLoad"],b=function(e){let{src:t,srcSet:a,loading:n,alt:s="",shouldLoad:l}=e,c=o(e,y);return r.createElement("img",i({},c,{decoding:"async",loading:n,src:l?t:void 0,"data-src":l?void 0:t,srcSet:l?a:void 0,"data-srcset":l?void 0:a,alt:s}))},v=function(e){let{fallback:t,sources:a=[],shouldLoad:n=!0}=e,s=o(e,f);const l=s.sizes||(null==t?void 0:t.sizes),c=r.createElement(b,i({},s,t,{sizes:l,shouldLoad:n}));return a.length?r.createElement("picture",null,a.map((e=>{let{media:t,srcSet:a,type:s}=e;return r.createElement("source",{key:`${t}-${s}-${a}`,type:s,media:t,srcSet:n?a:void 0,"data-srcset":n?void 0:a,sizes:l})})),c):c};var w;b.propTypes={src:n.string.isRequired,alt:n.string.isRequired,sizes:n.string,srcSet:n.string,shouldLoad:n.bool},v.displayName="Picture",v.propTypes={alt:n.string.isRequired,shouldLoad:n.bool,fallback:n.exact({src:n.string.isRequired,srcSet:n.string,sizes:n.string}),sources:n.arrayOf(n.oneOfType([n.exact({media:n.string.isRequired,type:n.string,sizes:n.string,srcSet:n.string.isRequired}),n.exact({media:n.string,type:n.string.isRequired,sizes:n.string,srcSet:n.string.isRequired})]))};const E=["fallback"],x=function(e){let{fallback:t}=e,a=o(e,E);return t?r.createElement(v,i({},a,{fallback:{src:t},"aria-hidden":!0,alt:""})):r.createElement("div",i({},a))};x.displayName="Placeholder",x.propTypes={fallback:n.string,sources:null==(w=v.propTypes)?void 0:w.sources,alt:function(e,t,a){return e[t]?new Error(`Invalid prop \`${t}\` supplied to \`${a}\`. Validation failed.`):null}};const k=function(e){return r.createElement(r.Fragment,null,r.createElement(v,i({},e)),r.createElement("noscript",null,r.createElement(v,i({},e,{shouldLoad:!0}))))};k.displayName="MainImage",k.propTypes=v.propTypes;const L=["as","className","class","style","image","loading","imgClassName","imgStyle","backgroundColor","objectFit","objectPosition"],C=["style","className"],S=e=>e.replace(/\n/g,""),I=function(e,t,a){for(var r=arguments.length,n=new Array(r>3?r-3:0),i=3;iJSON.stringify(n.images)),[n.images]);g&&(d=g);const S=function(e,t,a){let r="";return"fullWidth"===e&&(r=``),"constrained"===e&&(r=`
`),r}(v,f,b);return(0,r.useEffect)((()=>{O||(O=a.e(731).then(a.bind(a,6731)).then((e=>{let{renderImageToString:t,swapPlaceholderImage:a}=e;return q=t,{renderImageToString:t,swapPlaceholderImage:a}})));const e=L.current.querySelector("[data-gatsby-image-ssr]");if(e&&l())return e.complete?(null==p||p({wasCached:!0}),null==m||m({wasCached:!0}),setTimeout((()=>{e.removeAttribute("data-gatsby-image-ssr")}),0)):(null==p||p({wasCached:!0}),e.addEventListener("load",(function t(){e.removeEventListener("load",t),null==m||m({wasCached:!0}),setTimeout((()=>{e.removeAttribute("data-gatsby-image-ssr")}),0)}))),void j.add(C);if(q&&j.has(C))return;let t,r;return O.then((e=>{let{renderImageToString:a,swapPlaceholderImage:o}=e;L.current&&(L.current.innerHTML=a(i({isLoading:!0,isLoaded:j.has(C),image:n},y)),j.has(C)||(t=requestAnimationFrame((()=>{L.current&&(r=o(L.current,C,j,s,p,m,h))}))))})),()=>{t&&cancelAnimationFrame(t),r&&r()}}),[n]),(0,r.useLayoutEffect)((()=>{j.has(C)&&q&&(L.current.innerHTML=q(i({isLoading:j.has(C),isLoaded:j.has(C),image:n},y)),null==p||p({wasCached:!0}),null==m||m({wasCached:!0}))}),[n]),(0,r.createElement)(t,i({},k,{style:i({},E,s,{backgroundColor:c}),className:`${x}${d?` ${d}`:""}`,ref:L,dangerouslySetInnerHTML:{__html:S},suppressHydrationWarning:!0}))},R=(0,r.memo)((function(e){return e.image?(0,r.createElement)(P,e):null}));R.propTypes=N,R.displayName="GatsbyImage";const _=["src","__imageData","__error","width","height","aspectRatio","tracedSVGOptions","placeholder","formats","quality","transformOptions","jpgOptions","pngOptions","webpOptions","avifOptions","blurredOptions","breakpoints","outputPixelDensities"];function A(e){return function(t){let{src:a,__imageData:n,__error:s}=t,l=o(t,_);return s&&console.warn(s),n?r.createElement(e,i({image:n},l)):(console.warn("Image not loaded",a),null)}}const W=A((function(e){let{as:t="div",className:a,class:n,style:s,image:l,loading:c="lazy",imgClassName:p,imgStyle:m,backgroundColor:y,objectFit:f,objectPosition:b}=e,v=o(e,L);if(!l)return console.warn("[gatsby-plugin-image] Missing image prop"),null;n&&(a=n),m=i({objectFit:f,objectPosition:b,backgroundColor:y},m);const{width:w,height:E,layout:I,images:N,placeholder:$,backgroundColor:T}=l,j=u(w,E,I),{style:O,className:q}=j,P=o(j,C),R={fallback:void 0,sources:[]};return N.fallback&&(R.fallback=i({},N.fallback,{srcSet:N.fallback.srcSet?S(N.fallback.srcSet):void 0})),N.sources&&(R.sources=N.sources.map((e=>i({},e,{srcSet:S(e.srcSet)})))),r.createElement(t,i({},P,{style:i({},O,s,{backgroundColor:y}),className:`${q}${a?` ${a}`:""}`}),r.createElement(h,{layout:I,width:w,height:E},r.createElement(x,i({},g($,!1,I,w,E,T,f,b))),r.createElement(k,i({"data-gatsby-image-ssr":"",className:p},v,d("eager"===c,!1,R,c,m)))))})),z=function(e,t){for(var a=arguments.length,r=new Array(a>2?a-2:0),n=2;n{if(void 0!==e.layout&&!M.has(e.layout))return new Error(`Invalid value ${e.layout}" provided for prop "layout". Defaulting to "constrained". Valid values are "fixed", "fullWidth" or "constrained".`)}};W.displayName="StaticImage",W.propTypes=F;const D=A(R);D.displayName="StaticImage",D.propTypes=F},6745:function(e,t,a){var r=a(7294),n=a(4854),s=a(8032),i=a(9165);t.Z=e=>{let{project:t,className:a,theme:o}=e;const l=(0,s.c)(t.frontmatter.cover),{title:c}=t.frontmatter,u="light"===o?"text-main-100 hover:text-main-10":"text-secondary-100 hover:text-secondary-10",d="light"===o?"bg-secondary-70 hover:bg-secondary-100":"bg-main-100 hover:bg-main-100";return r.createElement(n.Link,{to:`/projects/${t.id}`,className:`${d} ${u} flex flex-col grow-1 justify-between hover:text-main-10 rounded-2xl ${a}`,itemScope:!0,itemType:"https://schema.org/CreativeWork"},l?r.createElement(s.G,{image:l,alt:c,itemProp:"image",className:"aspect-square object-cover w-full rounded-t-2xl"}):null,r.createElement("h4",{className:"text-2xl p-6 flex grow items-center font-extrabold h-24",itemProp:"description"},c.toUpperCase()),r.createElement(i.L,{itemProp:"author"}))}}}]); +//# sourceMappingURL=6bc48222ba83afa56babedfa3f8ecf0aa4bc5b28-cd60fa92803063beafa0.js.map \ No newline at end of file diff --git a/6bc48222ba83afa56babedfa3f8ecf0aa4bc5b28-cd60fa92803063beafa0.js.map b/6bc48222ba83afa56babedfa3f8ecf0aa4bc5b28-cd60fa92803063beafa0.js.map new file mode 100644 index 00000000..80da220f --- /dev/null +++ b/6bc48222ba83afa56babedfa3f8ecf0aa4bc5b28-cd60fa92803063beafa0.js.map @@ -0,0 +1 @@ +{"version":3,"file":"6bc48222ba83afa56babedfa3f8ecf0aa4bc5b28-cd60fa92803063beafa0.js","mappings":"uGAEA,MAAMA,EAAY,YACZC,EAAY,YACZC,EAAkB,0BAClBC,EAAa,yBACbC,EAAa,WAEbC,EAAqB,IAAIC,OAAO,IAAMF,EAAWG,QACjDC,EAA4B,IAAIF,OAAOF,EAA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ACPxI,EAAS,MACTyI,GAKDF,EACC,MAAMG,GAAQC,EAAAA,EAAAA,GAASH,EAAQI,YAAYF,QACrC,MAAEG,GAAUL,EAAQI,YAEpBE,EACM,UAAVL,EACI,mCACA,6CACAM,EACM,UAAVN,EACI,yCACA,gCAEN,OACEO,EAAAA,cAACC,EAAAA,KAAI,CACHC,GAAK,aAAYV,EAAQW,KACzBnJ,UAAY,GAAE+I,KAAYD,yEAAwF9I,IAClHoJ,WAAS,EACTC,SAAS,mCAERX,EACCM,EAAAA,cAACM,EAAAA,EAAW,CACVrF,MAAOyE,EACP7G,IAAKgH,EACLU,SAAS,QACTvJ,UAAU,oDAEV,KACJgJ,EAAAA,cAAA,MACEhJ,UAAU,0DACVuJ,SAAS,eAERV,EAAMnL,eAETsL,EAAAA,cAACQ,EAAAA,EAAqB,CAACD,SAAS,WAC3B,C","sources":["webpack://code-cave/./node_modules/camelcase/index.js","webpack://code-cave/../src/image-utils.ts","webpack://code-cave/../src/components/hooks.ts","webpack://code-cave/../src/components/layout-wrapper.tsx","webpack://code-cave/../src/components/picture.tsx","webpack://code-cave/../src/components/placeholder.tsx","webpack://code-cave/../src/components/main-image.tsx","webpack://code-cave/../src/components/gatsby-image.server.tsx","webpack://code-cave/../src/components/gatsby-image.browser.tsx","webpack://code-cave/../src/components/static-image.server.tsx","webpack://code-cave/../src/components/static-image.tsx","webpack://code-cave/./src/components/projects/projectPreview.tsx"],"sourcesContent":["'use strict';\n\nconst UPPERCASE = /[\\p{Lu}]/u;\nconst LOWERCASE = /[\\p{Ll}]/u;\nconst LEADING_CAPITAL = /^[\\p{Lu}](?![\\p{Lu}])/gu;\nconst IDENTIFIER = /([\\p{Alpha}\\p{N}_]|$)/u;\nconst SEPARATORS = /[_.\\- ]+/;\n\nconst LEADING_SEPARATORS = new RegExp('^' + SEPARATORS.source);\nconst SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, 'gu');\nconst NUMBERS_AND_IDENTIFIER = new RegExp('\\\\d+' + IDENTIFIER.source, 'gu');\n\nconst preserveCamelCase = (string, toLowerCase, toUpperCase) => {\n\tlet isLastCharLower = false;\n\tlet isLastCharUpper = false;\n\tlet isLastLastCharUpper = false;\n\n\tfor (let i = 0; i < string.length; i++) {\n\t\tconst character = string[i];\n\n\t\tif (isLastCharLower && UPPERCASE.test(character)) {\n\t\t\tstring = string.slice(0, i) + '-' + string.slice(i);\n\t\t\tisLastCharLower = false;\n\t\t\tisLastLastCharUpper = isLastCharUpper;\n\t\t\tisLastCharUpper = true;\n\t\t\ti++;\n\t\t} else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) {\n\t\t\tstring = string.slice(0, i - 1) + '-' + string.slice(i - 1);\n\t\t\tisLastLastCharUpper = isLastCharUpper;\n\t\t\tisLastCharUpper = false;\n\t\t\tisLastCharLower = true;\n\t\t} else {\n\t\t\tisLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character;\n\t\t\tisLastLastCharUpper = isLastCharUpper;\n\t\t\tisLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character;\n\t\t}\n\t}\n\n\treturn string;\n};\n\nconst preserveConsecutiveUppercase = (input, toLowerCase) => {\n\tLEADING_CAPITAL.lastIndex = 0;\n\n\treturn input.replace(LEADING_CAPITAL, m1 => toLowerCase(m1));\n};\n\nconst postProcess = (input, toUpperCase) => {\n\tSEPARATORS_AND_IDENTIFIER.lastIndex = 0;\n\tNUMBERS_AND_IDENTIFIER.lastIndex = 0;\n\n\treturn input.replace(SEPARATORS_AND_IDENTIFIER, (_, identifier) => toUpperCase(identifier))\n\t\t.replace(NUMBERS_AND_IDENTIFIER, m => toUpperCase(m));\n};\n\nconst camelCase = (input, options) => {\n\tif (!(typeof input === 'string' || Array.isArray(input))) {\n\t\tthrow new TypeError('Expected the input to be `string | string[]`');\n\t}\n\n\toptions = {\n\t\tpascalCase: false,\n\t\tpreserveConsecutiveUppercase: false,\n\t\t...options\n\t};\n\n\tif (Array.isArray(input)) {\n\t\tinput = input.map(x => x.trim())\n\t\t\t.filter(x => x.length)\n\t\t\t.join('-');\n\t} else {\n\t\tinput = input.trim();\n\t}\n\n\tif (input.length === 0) {\n\t\treturn '';\n\t}\n\n\tconst toLowerCase = options.locale === false ?\n\t\tstring => string.toLowerCase() :\n\t\tstring => string.toLocaleLowerCase(options.locale);\n\tconst toUpperCase = options.locale === false ?\n\t\tstring => string.toUpperCase() :\n\t\tstring => string.toLocaleUpperCase(options.locale);\n\n\tif (input.length === 1) {\n\t\treturn options.pascalCase ? toUpperCase(input) : toLowerCase(input);\n\t}\n\n\tconst hasUpperCase = input !== toLowerCase(input);\n\n\tif (hasUpperCase) {\n\t\tinput = preserveCamelCase(input, toLowerCase, toUpperCase);\n\t}\n\n\tinput = input.replace(LEADING_SEPARATORS, '');\n\n\tif (options.preserveConsecutiveUppercase) {\n\t\tinput = preserveConsecutiveUppercase(input, toLowerCase);\n\t} else {\n\t\tinput = toLowerCase(input);\n\t}\n\n\tif (options.pascalCase) {\n\t\tinput = toUpperCase(input.charAt(0)) + input.slice(1);\n\t}\n\n\treturn postProcess(input, toUpperCase);\n};\n\nmodule.exports = camelCase;\n// TODO: Remove this for the next major release\nmodule.exports.default = camelCase;\n","import camelCase from \"camelcase\"\nimport type { IGatsbyImageData } from \"./index\"\n\nconst DEFAULT_PIXEL_DENSITIES = [0.25, 0.5, 1, 2]\nexport const DEFAULT_BREAKPOINTS = [750, 1080, 1366, 1920]\nexport const EVERY_BREAKPOINT = [\n 320, 654, 768, 1024, 1366, 1600, 1920, 2048, 2560, 3440, 3840, 4096,\n]\nconst DEFAULT_FLUID_WIDTH = 800\nconst DEFAULT_FIXED_WIDTH = 800\nconst DEFAULT_ASPECT_RATIO = 4 / 3\n\nexport type Fit = \"cover\" | \"fill\" | \"inside\" | \"outside\" | \"contain\"\n\nexport type Layout = \"fixed\" | \"fullWidth\" | \"constrained\"\nexport type ImageFormat = \"jpg\" | \"png\" | \"webp\" | \"avif\" | \"auto\" | \"\"\n\n/**\n * The minimal required reporter, as we don't want to import it from gatsby-cli\n */\nexport interface IReporter {\n warn(message: string): void\n}\n\nexport interface ISharpGatsbyImageArgs {\n layout?: Layout\n formats?: Array\n placeholder?: \"tracedSVG\" | \"dominantColor\" | \"blurred\" | \"none\"\n tracedSVGOptions?: Record\n width?: number\n height?: number\n aspectRatio?: number\n sizes?: string\n quality?: number\n transformOptions?: {\n fit?: Fit\n cropFocus?: number | string\n duotone?: {\n highlight: string\n shadow: string\n opacity?: number\n }\n grayscale?: boolean\n rotate?: number\n trim?: number\n }\n jpgOptions?: Record\n pngOptions?: Record\n webpOptions?: Record\n avifOptions?: Record\n blurredOptions?: { width?: number; toFormat?: ImageFormat }\n breakpoints?: Array\n outputPixelDensities?: Array\n backgroundColor?: string\n}\n\nexport interface IImageSizeArgs {\n width?: number\n height?: number\n layout?: Layout\n filename: string\n outputPixelDensities?: Array\n breakpoints?: Array\n fit?: Fit\n reporter?: IReporter\n sourceMetadata: { width: number; height: number }\n}\n\nexport interface IImageSizes {\n sizes: Array\n presentationWidth: number\n presentationHeight: number\n aspectRatio: number\n unscaledWidth: number\n}\n\nexport interface IImage {\n src: string\n width: number\n height: number\n format: ImageFormat\n}\n\nexport interface IGatsbyImageHelperArgs {\n pluginName: string\n generateImageSource: (\n filename: string,\n width: number,\n height: number,\n format: ImageFormat,\n fit?: Fit,\n options?: Record\n ) => IImage\n layout?: Layout\n formats?: Array\n filename: string\n placeholderURL?: string\n width?: number\n height?: number\n sizes?: string\n reporter?: IReporter\n sourceMetadata?: { width: number; height: number; format: ImageFormat }\n fit?: Fit\n options?: Record\n breakpoints?: Array\n backgroundColor?: string\n aspectRatio?: number\n}\n\nconst warn = (message: string): void => console.warn(message)\n\nconst sortNumeric = (a: number, b: number): number => a - b\n\nexport const getSizes = (width: number, layout: Layout): string | undefined => {\n switch (layout) {\n // If screen is wider than the max size, image width is the max size,\n // otherwise it's the width of the screen\n case `constrained`:\n return `(min-width: ${width}px) ${width}px, 100vw`\n\n // Image is always the same width, whatever the size of the screen\n case `fixed`:\n return `${width}px`\n\n // Image is always the width of the screen\n case `fullWidth`:\n return `100vw`\n\n default:\n return undefined\n }\n}\n\nexport const getSrcSet = (images: Array): string =>\n images.map(image => `${image.src} ${image.width}w`).join(`,\\n`)\n\nexport function formatFromFilename(filename: string): ImageFormat | undefined {\n const dot = filename.lastIndexOf(`.`)\n if (dot !== -1) {\n const ext = filename.slice(dot + 1)\n if (ext === `jpeg`) {\n return `jpg`\n }\n if (ext.length === 3 || ext.length === 4) {\n return ext as ImageFormat\n }\n }\n return undefined\n}\n\nexport function setDefaultDimensions(\n args: IGatsbyImageHelperArgs\n): IGatsbyImageHelperArgs {\n let {\n layout = `constrained`,\n width,\n height,\n sourceMetadata,\n breakpoints,\n aspectRatio,\n formats = [`auto`, `webp`],\n } = args\n formats = formats.map(format => format.toLowerCase() as ImageFormat)\n layout = camelCase(layout) as Layout\n\n if (width && height) {\n return { ...args, formats, layout, aspectRatio: width / height }\n }\n if (sourceMetadata.width && sourceMetadata.height && !aspectRatio) {\n aspectRatio = sourceMetadata.width / sourceMetadata.height\n }\n\n if (layout === `fullWidth`) {\n width = width || sourceMetadata.width || breakpoints[breakpoints.length - 1]\n height = height || Math.round(width / (aspectRatio || DEFAULT_ASPECT_RATIO))\n } else {\n if (!width) {\n if (height && aspectRatio) {\n width = height * aspectRatio\n } else if (sourceMetadata.width) {\n width = sourceMetadata.width\n } else if (height) {\n width = Math.round(height / DEFAULT_ASPECT_RATIO)\n } else {\n width = DEFAULT_FIXED_WIDTH\n }\n }\n\n if (aspectRatio && !height) {\n height = Math.round(width / aspectRatio)\n } else if (!aspectRatio) {\n aspectRatio = width / height\n }\n }\n return { ...args, width, height, aspectRatio, layout, formats }\n}\n\n/**\n * Use this for getting an image for the blurred placeholder. This ensures the\n * aspect ratio and crop match the main image\n */\nexport function getLowResolutionImageURL(\n args: IGatsbyImageHelperArgs,\n width = 20\n): string {\n args = setDefaultDimensions(args)\n const { generateImageSource, filename, aspectRatio } = args\n return generateImageSource(\n filename,\n width,\n Math.round(width / aspectRatio),\n args.sourceMetadata.format || `jpg`,\n args.fit,\n args.options\n )?.src\n}\n\nexport function generateImageData(\n args: IGatsbyImageHelperArgs\n): IGatsbyImageData {\n args = setDefaultDimensions(args)\n\n let {\n pluginName,\n sourceMetadata,\n generateImageSource,\n layout,\n fit,\n options,\n width,\n height,\n filename,\n reporter = { warn },\n backgroundColor,\n placeholderURL,\n } = args\n\n if (!pluginName) {\n reporter.warn(\n `[gatsby-plugin-image] \"generateImageData\" was not passed a plugin name`\n )\n }\n\n if (typeof generateImageSource !== `function`) {\n throw new Error(`generateImageSource must be a function`)\n }\n\n if (!sourceMetadata || (!sourceMetadata.width && !sourceMetadata.height)) {\n // No metadata means we let the CDN handle max size etc, aspect ratio etc\n sourceMetadata = {\n width,\n height,\n format: sourceMetadata?.format || formatFromFilename(filename) || `auto`,\n }\n } else if (!sourceMetadata.format) {\n sourceMetadata.format = formatFromFilename(filename)\n }\n\n const formats = new Set(args.formats)\n\n if (formats.size === 0 || formats.has(`auto`) || formats.has(``)) {\n formats.delete(`auto`)\n formats.delete(``)\n formats.add(sourceMetadata.format)\n }\n\n if (formats.has(`jpg`) && formats.has(`png`)) {\n reporter.warn(\n `[${pluginName}] Specifying both 'jpg' and 'png' formats is not supported. Using 'auto' instead`\n )\n if (sourceMetadata.format === `jpg`) {\n formats.delete(`png`)\n } else {\n formats.delete(`jpg`)\n }\n }\n\n const imageSizes = calculateImageSizes({ ...args, sourceMetadata })\n\n const result: IGatsbyImageData[\"images\"] = {\n sources: [],\n }\n\n let sizes = args.sizes\n if (!sizes) {\n sizes = getSizes(imageSizes.presentationWidth, layout)\n }\n\n formats.forEach(format => {\n const images = imageSizes.sizes\n .map(size => {\n const imageSrc = generateImageSource(\n filename,\n size,\n Math.round(size / imageSizes.aspectRatio),\n format,\n fit,\n options\n )\n if (\n !imageSrc?.width ||\n !imageSrc.height ||\n !imageSrc.src ||\n !imageSrc.format\n ) {\n reporter.warn(\n `[${pluginName}] The resolver for image ${filename} returned an invalid value.`\n )\n return undefined\n }\n return imageSrc\n })\n .filter(Boolean)\n\n if (format === `jpg` || format === `png` || format === `auto`) {\n const unscaled =\n images.find(img => img.width === imageSizes.unscaledWidth) || images[0]\n\n if (unscaled) {\n result.fallback = {\n src: unscaled.src,\n srcSet: getSrcSet(images),\n sizes,\n }\n }\n } else {\n result.sources?.push({\n srcSet: getSrcSet(images),\n sizes,\n type: `image/${format}`,\n })\n }\n })\n\n const imageProps: Partial = {\n images: result,\n layout,\n backgroundColor,\n }\n\n if (placeholderURL) {\n imageProps.placeholder = { fallback: placeholderURL }\n }\n\n switch (layout) {\n case `fixed`:\n imageProps.width = imageSizes.presentationWidth\n imageProps.height = imageSizes.presentationHeight\n break\n\n case `fullWidth`:\n imageProps.width = 1\n imageProps.height = 1 / imageSizes.aspectRatio\n break\n\n case `constrained`:\n imageProps.width = args.width || imageSizes.presentationWidth || 1\n imageProps.height = (imageProps.width || 1) / imageSizes.aspectRatio\n }\n\n return imageProps as IGatsbyImageData\n}\n\nconst dedupeAndSortDensities = (values: Array): Array =>\n Array.from(new Set([1, ...values])).sort(sortNumeric)\n\nexport function calculateImageSizes(args: IImageSizeArgs): IImageSizes {\n const {\n width,\n height,\n filename,\n layout = `constrained`,\n sourceMetadata: imgDimensions,\n reporter = { warn },\n breakpoints = DEFAULT_BREAKPOINTS,\n } = args\n\n // check that all dimensions provided are positive\n const userDimensions = { width, height }\n const erroneousUserDimensions = Object.entries(userDimensions).filter(\n ([_, size]) => typeof size === `number` && size < 1\n )\n if (erroneousUserDimensions.length) {\n throw new Error(\n `Specified dimensions for images must be positive numbers (> 0). Problem dimensions you have are ${erroneousUserDimensions\n .map(dim => dim.join(`: `))\n .join(`, `)}`\n )\n }\n\n if (layout === `fixed`) {\n return fixedImageSizes(args)\n } else if (layout === `constrained`) {\n return responsiveImageSizes(args)\n } else if (layout === `fullWidth`) {\n return responsiveImageSizes({ breakpoints, ...args })\n } else {\n reporter.warn(\n `No valid layout was provided for the image at ${filename}. Valid image layouts are fixed, fullWidth, and constrained. Found ${layout}`\n )\n return {\n sizes: [imgDimensions.width],\n presentationWidth: imgDimensions.width,\n presentationHeight: imgDimensions.height,\n aspectRatio: imgDimensions.width / imgDimensions.height,\n unscaledWidth: imgDimensions.width,\n }\n }\n}\nexport function fixedImageSizes({\n filename,\n sourceMetadata: imgDimensions,\n width,\n height,\n fit = `cover`,\n outputPixelDensities = DEFAULT_PIXEL_DENSITIES,\n reporter = { warn },\n}: IImageSizeArgs): IImageSizes {\n let aspectRatio = imgDimensions.width / imgDimensions.height\n // Sort, dedupe and ensure there's a 1\n const densities = dedupeAndSortDensities(outputPixelDensities)\n\n // If both are provided then we need to check the fit\n if (width && height) {\n const calculated = getDimensionsAndAspectRatio(imgDimensions, {\n width,\n height,\n fit,\n })\n width = calculated.width\n height = calculated.height\n aspectRatio = calculated.aspectRatio\n }\n\n if (!width) {\n if (!height) {\n width = DEFAULT_FIXED_WIDTH\n } else {\n width = Math.round(height * aspectRatio)\n }\n } else if (!height) {\n height = Math.round(width / aspectRatio)\n }\n\n const originalWidth = width // will use this for presentationWidth, don't want to lose it\n const isTopSizeOverriden =\n imgDimensions.width < width || imgDimensions.height < (height as number)\n\n // If the image is smaller than requested, warn the user that it's being processed as such\n // print out this message with the necessary information before we overwrite it for sizing\n if (isTopSizeOverriden) {\n const fixedDimension = imgDimensions.width < width ? `width` : `height`\n reporter.warn(`\nThe requested ${fixedDimension} \"${\n fixedDimension === `width` ? width : height\n }px\" for the image ${filename} was larger than the actual image ${fixedDimension} of ${\n imgDimensions[fixedDimension]\n }px. If possible, replace the current image with a larger one.`)\n\n if (fixedDimension === `width`) {\n width = imgDimensions.width\n height = Math.round(width / aspectRatio)\n } else {\n height = imgDimensions.height\n width = height * aspectRatio\n }\n }\n\n const sizes = densities\n .filter(size => size >= 1) // remove smaller densities because fixed images don't need them\n .map(density => Math.round(density * (width as number)))\n .filter(size => size <= imgDimensions.width)\n\n return {\n sizes,\n aspectRatio,\n presentationWidth: originalWidth,\n presentationHeight: Math.round(originalWidth / aspectRatio),\n unscaledWidth: width,\n }\n}\n\nexport function responsiveImageSizes({\n sourceMetadata: imgDimensions,\n width,\n height,\n fit = `cover`,\n outputPixelDensities = DEFAULT_PIXEL_DENSITIES,\n breakpoints,\n layout,\n}: IImageSizeArgs): IImageSizes {\n let sizes\n let aspectRatio = imgDimensions.width / imgDimensions.height\n // Sort, dedupe and ensure there's a 1\n const densities = dedupeAndSortDensities(outputPixelDensities)\n\n // If both are provided then we need to check the fit\n if (width && height) {\n const calculated = getDimensionsAndAspectRatio(imgDimensions, {\n width,\n height,\n fit,\n })\n width = calculated.width\n height = calculated.height\n aspectRatio = calculated.aspectRatio\n }\n\n // Case 1: width of height were passed in, make sure it isn't larger than the actual image\n width = width && Math.min(width, imgDimensions.width)\n height = height && Math.min(height, imgDimensions.height)\n\n // Case 2: neither width or height were passed in, use default size\n if (!width && !height) {\n width = Math.min(DEFAULT_FLUID_WIDTH, imgDimensions.width)\n height = width / aspectRatio\n }\n\n // if it still hasn't been found, calculate width from the derived height.\n // TS isn't smart enough to realise the type for height has been narrowed here\n if (!width) {\n width = (height as number) * aspectRatio\n }\n\n const originalWidth = width\n const isTopSizeOverriden =\n imgDimensions.width < width || imgDimensions.height < (height as number)\n if (isTopSizeOverriden) {\n width = imgDimensions.width\n height = imgDimensions.height\n }\n\n width = Math.round(width)\n\n if (breakpoints?.length > 0) {\n sizes = breakpoints.filter(size => size <= imgDimensions.width)\n\n // If a larger breakpoint has been filtered-out, add the actual image width instead\n if (\n sizes.length < breakpoints.length &&\n !sizes.includes(imgDimensions.width)\n ) {\n sizes.push(imgDimensions.width)\n }\n } else {\n sizes = densities.map(density => Math.round(density * (width as number)))\n sizes = sizes.filter(size => size <= imgDimensions.width)\n }\n\n // ensure that the size passed in is included in the final output\n if (layout === `constrained` && !sizes.includes(width)) {\n sizes.push(width)\n }\n sizes = sizes.sort(sortNumeric)\n return {\n sizes,\n aspectRatio,\n presentationWidth: originalWidth,\n presentationHeight: Math.round(originalWidth / aspectRatio),\n unscaledWidth: width,\n }\n}\n\nexport function getDimensionsAndAspectRatio(\n dimensions,\n options\n): { width: number; height: number; aspectRatio: number } {\n // Calculate the eventual width/height of the image.\n const imageAspectRatio = dimensions.width / dimensions.height\n\n let width = options.width\n let height = options.height\n\n switch (options.fit) {\n case `fill`: {\n width = options.width ? options.width : dimensions.width\n height = options.height ? options.height : dimensions.height\n break\n }\n case `inside`: {\n const widthOption = options.width\n ? options.width\n : Number.MAX_SAFE_INTEGER\n const heightOption = options.height\n ? options.height\n : Number.MAX_SAFE_INTEGER\n\n width = Math.min(widthOption, Math.round(heightOption * imageAspectRatio))\n height = Math.min(\n heightOption,\n Math.round(widthOption / imageAspectRatio)\n )\n break\n }\n case `outside`: {\n const widthOption = options.width ? options.width : 0\n const heightOption = options.height ? options.height : 0\n\n width = Math.max(widthOption, Math.round(heightOption * imageAspectRatio))\n height = Math.max(\n heightOption,\n Math.round(widthOption / imageAspectRatio)\n )\n break\n }\n\n default: {\n if (options.width && !options.height) {\n width = options.width\n height = Math.round(options.width / imageAspectRatio)\n }\n\n if (options.height && !options.width) {\n width = Math.round(options.height * imageAspectRatio)\n height = options.height\n }\n }\n }\n\n return {\n width,\n height,\n aspectRatio: width / height,\n }\n}\n","/* global GATSBY___IMAGE */\nimport { generateImageData, EVERY_BREAKPOINT } from \"../image-utils\"\nimport type { CSSProperties, HTMLAttributes, ImgHTMLAttributes } from \"react\"\nimport type { Node } from \"gatsby\"\nimport type { PlaceholderProps } from \"./placeholder\"\nimport type { MainImageProps } from \"./main-image\"\nimport type { IGatsbyImageData } from \"./gatsby-image.browser\"\nimport type {\n IGatsbyImageHelperArgs,\n Layout,\n IImage,\n ImageFormat,\n} from \"../image-utils\"\n\n// Native lazy-loading support: https://addyosmani.com/blog/lazy-loading/\nexport const hasNativeLazyLoadSupport = (): boolean =>\n typeof HTMLImageElement !== `undefined` &&\n `loading` in HTMLImageElement.prototype\n\nexport function gatsbyImageIsInstalled(): boolean {\n return typeof GATSBY___IMAGE !== `undefined` && GATSBY___IMAGE\n}\n\nexport type IGatsbyImageDataParent = T & {\n gatsbyImageData: IGatsbyImageData\n}\nexport type IGatsbyImageParent = T & {\n gatsbyImage: IGatsbyImageData\n}\nexport type FileNode = Partial & {\n childImageSharp?: IGatsbyImageDataParent>\n}\n\nconst isGatsbyImageData = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n node: IGatsbyImageData | any\n): node is IGatsbyImageData =>\n // 🦆 check for a deep prop to be sure this is a valid gatsbyImageData object\n Boolean(node?.images?.fallback?.src)\n\nconst isGatsbyImageDataParent = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n node: IGatsbyImageDataParent | any\n): node is IGatsbyImageDataParent => Boolean(node?.gatsbyImageData)\n\nconst isGatsbyImageParent = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n node: IGatsbyImageParent | any\n): node is IGatsbyImageParent => Boolean(node?.gatsbyImage)\n\nexport type ImageDataLike =\n | FileNode\n | IGatsbyImageDataParent\n | IGatsbyImageParent\n | IGatsbyImageData\n\nexport const getImage = (\n node: ImageDataLike | null\n): IGatsbyImageData | undefined => {\n // This checks both for gatsbyImageData and gatsbyImage\n if (isGatsbyImageData(node)) {\n return node\n }\n // gatsbyImageData GraphQL field\n if (isGatsbyImageDataParent(node)) {\n return node.gatsbyImageData\n }\n // gatsbyImage GraphQL field for Gatsby's Image CDN service\n if (isGatsbyImageParent(node)) {\n return node.gatsbyImage\n }\n return node?.childImageSharp?.gatsbyImageData\n}\n\nexport const getSrc = (node: ImageDataLike): string | undefined =>\n getImage(node)?.images?.fallback?.src\n\nexport const getSrcSet = (node: ImageDataLike): string | undefined =>\n getImage(node)?.images?.fallback?.srcSet\n\nexport function getWrapperProps(\n width: number,\n height: number,\n layout: Layout\n): Pick, \"className\" | \"style\"> & {\n \"data-gatsby-image-wrapper\": string\n} {\n const wrapperStyle: CSSProperties = {}\n\n let className = `gatsby-image-wrapper`\n\n // If the plugin isn't installed we need to apply the styles inline\n if (!gatsbyImageIsInstalled()) {\n wrapperStyle.position = `relative`\n wrapperStyle.overflow = `hidden`\n }\n\n if (layout === `fixed`) {\n wrapperStyle.width = width\n wrapperStyle.height = height\n } else if (layout === `constrained`) {\n if (!gatsbyImageIsInstalled()) {\n wrapperStyle.display = `inline-block`\n wrapperStyle.verticalAlign = `top`\n }\n className = `gatsby-image-wrapper gatsby-image-wrapper-constrained`\n }\n\n return {\n className,\n \"data-gatsby-image-wrapper\": ``,\n style: wrapperStyle,\n }\n}\n\nexport interface IUrlBuilderArgs {\n width: number\n height: number\n baseUrl: string\n format: ImageFormat\n options: OptionsType\n}\nexport interface IGetImageDataArgs> {\n baseUrl: string\n /**\n * For constrained and fixed images, the size of the image element\n */\n width?: number\n height?: number\n /**\n * If available, pass the source image width and height\n */\n sourceWidth?: number\n sourceHeight?: number\n /**\n * If only one dimension is passed, then this will be used to calculate the other.\n */\n aspectRatio?: number\n layout?: Layout\n /**\n * Returns a URL based on the passed arguments. Should be a pure function\n */\n urlBuilder: (args: IUrlBuilderArgs) => string\n\n /**\n * Should be a data URI\n */\n placeholderURL?: string\n backgroundColor?: string\n /**\n * Used in error messages etc\n */\n pluginName?: string\n\n /**\n * If you do not support auto-format, pass an array of image types here\n */\n formats?: Array\n\n breakpoints?: Array\n\n /**\n * Passed to the urlBuilder function\n */\n options?: OptionsType\n}\n\n/**\n * Use this hook to generate gatsby-plugin-image data in the browser.\n */\nexport function getImageData({\n baseUrl,\n urlBuilder,\n sourceWidth,\n sourceHeight,\n pluginName = `getImageData`,\n formats = [`auto`],\n breakpoints,\n options,\n ...props\n}: IGetImageDataArgs): IGatsbyImageData {\n if (\n !breakpoints?.length &&\n (props.layout === `fullWidth` || (props.layout as string) === `FULL_WIDTH`)\n ) {\n breakpoints = EVERY_BREAKPOINT\n }\n const generateImageSource = (\n baseUrl: string,\n width: number,\n height?: number,\n format?: ImageFormat\n ): IImage => {\n return {\n width,\n height,\n format,\n src: urlBuilder({ baseUrl, width, height, options, format }),\n }\n }\n\n const sourceMetadata: IGatsbyImageHelperArgs[\"sourceMetadata\"] = {\n width: sourceWidth,\n height: sourceHeight,\n format: `auto`,\n }\n\n const args: IGatsbyImageHelperArgs = {\n ...props,\n pluginName,\n generateImageSource,\n filename: baseUrl,\n formats,\n breakpoints,\n sourceMetadata,\n }\n return generateImageData(args)\n}\n\nexport function getMainProps(\n isLoading: boolean,\n isLoaded: boolean,\n images: IGatsbyImageData[\"images\"],\n loading?: \"eager\" | \"lazy\",\n style: CSSProperties = {}\n): Partial {\n // fallback when it's not configured in gatsby-config.\n if (!gatsbyImageIsInstalled()) {\n style = {\n height: `100%`,\n left: 0,\n position: `absolute`,\n top: 0,\n transform: `translateZ(0)`,\n transition: `opacity 250ms linear`,\n width: `100%`,\n willChange: `opacity`,\n ...style,\n }\n }\n\n const result = {\n ...images,\n loading,\n shouldLoad: isLoading,\n \"data-main-image\": ``,\n style: {\n ...style,\n opacity: isLoaded ? 1 : 0,\n },\n }\n\n return result\n}\n\nexport type PlaceholderImageAttrs = ImgHTMLAttributes &\n Pick & {\n \"data-placeholder-image\"?: string\n }\n\nexport function getPlaceholderProps(\n placeholder: PlaceholderImageAttrs | undefined,\n isLoaded: boolean,\n layout: Layout,\n width?: number,\n height?: number,\n backgroundColor?: string,\n objectFit?: CSSProperties[\"objectFit\"],\n objectPosition?: CSSProperties[\"objectPosition\"]\n): PlaceholderImageAttrs {\n const wrapperStyle: CSSProperties = {}\n\n if (backgroundColor) {\n wrapperStyle.backgroundColor = backgroundColor\n\n if (layout === `fixed`) {\n wrapperStyle.width = width\n wrapperStyle.height = height\n wrapperStyle.backgroundColor = backgroundColor\n wrapperStyle.position = `relative`\n } else if (layout === `constrained`) {\n wrapperStyle.position = `absolute`\n wrapperStyle.top = 0\n wrapperStyle.left = 0\n wrapperStyle.bottom = 0\n wrapperStyle.right = 0\n } else if (layout === `fullWidth`) {\n wrapperStyle.position = `absolute`\n wrapperStyle.top = 0\n wrapperStyle.left = 0\n wrapperStyle.bottom = 0\n wrapperStyle.right = 0\n }\n }\n\n if (objectFit) {\n wrapperStyle.objectFit = objectFit\n }\n\n if (objectPosition) {\n wrapperStyle.objectPosition = objectPosition\n }\n const result: PlaceholderImageAttrs = {\n ...placeholder,\n \"aria-hidden\": true,\n \"data-placeholder-image\": ``,\n style: {\n opacity: isLoaded ? 0 : 1,\n transition: `opacity 500ms linear`,\n ...wrapperStyle,\n },\n }\n\n // fallback when it's not configured in gatsby-config.\n if (!gatsbyImageIsInstalled()) {\n result.style = {\n height: `100%`,\n left: 0,\n position: `absolute`,\n top: 0,\n width: `100%`,\n }\n }\n\n return result\n}\n\nexport interface IArtDirectedImage {\n media: string\n image: IGatsbyImageData\n}\n\n/**\n * Generate a Gatsby image data object with multiple, art-directed images that display at different\n * resolutions.\n *\n * @param defaultImage The image displayed when no media query matches.\n * It is also used for all other settings applied to the image, such as width, height and layout.\n * You should pass a className to the component with media queries to adjust the size of the container,\n * as this cannot be adjusted automatically.\n * @param artDirected Array of objects which each contains a `media` string which is a media query\n * such as `(min-width: 320px)`, and the image object to use when that query matches.\n */\nexport function withArtDirection(\n defaultImage: IGatsbyImageData,\n artDirected: Array\n): IGatsbyImageData {\n const { images, placeholder, ...props } = defaultImage\n const output: IGatsbyImageData = {\n ...props,\n images: {\n ...images,\n sources: [],\n },\n placeholder: placeholder && {\n ...placeholder,\n sources: [],\n },\n }\n\n artDirected.forEach(({ media, image }) => {\n if (!media) {\n if (process.env.NODE_ENV === `development`) {\n console.warn(\n \"[gatsby-plugin-image] All art-directed images passed to must have a value set for `media`. Skipping.\"\n )\n }\n return\n }\n\n if (\n image.layout !== defaultImage.layout &&\n process.env.NODE_ENV === `development`\n ) {\n console.warn(\n `[gatsby-plugin-image] Mismatched image layout: expected \"${defaultImage.layout}\" but received \"${image.layout}\". All art-directed images use the same layout as the default image`\n )\n }\n\n output.images.sources.push(\n ...image.images.sources.map(source => {\n return { ...source, media }\n }),\n {\n media,\n srcSet: image.images.fallback.srcSet,\n }\n )\n\n if (!output.placeholder) {\n return\n }\n\n output.placeholder.sources.push({\n media,\n srcSet: image.placeholder.fallback,\n })\n })\n output.images.sources.push(...images.sources)\n if (placeholder?.sources) {\n output.placeholder?.sources.push(...placeholder.sources)\n }\n return output\n}\n","import React, { Fragment, FunctionComponent, PropsWithChildren } from \"react\"\nimport terserMacro from \"../../macros/terser.macro\"\nimport { Layout } from \"../image-utils\"\n\nexport interface ILayoutWrapperProps {\n layout: Layout\n width: number\n height: number\n}\n\nconst NativeScriptLoading: FunctionComponent = () => (\n \n)\n\nexport function getSizer(\n layout: Layout,\n width: number,\n height: number\n): string {\n let sizer = ``\n if (layout === `fullWidth`) {\n sizer = `
`\n }\n\n if (layout === `constrained`) {\n sizer = `
\"\"
`\n }\n\n return sizer\n}\n\nconst Sizer: FunctionComponent = function Sizer({\n layout,\n width,\n height,\n}) {\n if (layout === `fullWidth`) {\n return (\n
\n )\n }\n\n if (layout === `constrained`) {\n return (\n
\n \n
\n )\n }\n\n return null\n}\n\nexport const LayoutWrapper: FunctionComponent<\n PropsWithChildren\n> = function LayoutWrapper({ children, ...props }) {\n return (\n \n \n {children}\n\n {SERVER ? : null}\n \n )\n}\n","import React, { FunctionComponent, ImgHTMLAttributes } from \"react\"\nimport * as PropTypes from \"prop-types\"\n\nexport interface IResponsiveImageProps {\n sizes?: string\n srcSet: string\n}\n\nexport type SourceProps = IResponsiveImageProps &\n (\n | {\n media: string\n type?: string\n }\n | {\n media?: string\n type: string\n }\n )\n\ntype FallbackProps = { src: string } & Partial\n\ntype ImageProps = ImgHTMLAttributes & {\n src: string\n alt: string\n shouldLoad: boolean\n}\n\nexport type PictureProps = ImgHTMLAttributes & {\n fallback?: FallbackProps\n sources?: Array\n alt: string\n shouldLoad?: boolean\n}\n\nconst Image: FunctionComponent = function Image({\n src,\n srcSet,\n loading,\n alt = ``,\n shouldLoad,\n ...props\n}) {\n return (\n \n )\n}\n\nexport const Picture: React.FC = function Picture({\n fallback,\n sources = [],\n shouldLoad = true,\n ...props\n}) {\n const sizes = props.sizes || fallback?.sizes\n const fallbackImage = (\n \n )\n\n if (!sources.length) {\n return fallbackImage\n }\n\n return (\n \n {sources.map(({ media, srcSet, type }) => (\n \n ))}\n {fallbackImage}\n \n )\n}\n\nImage.propTypes = {\n src: PropTypes.string.isRequired,\n alt: PropTypes.string.isRequired,\n sizes: PropTypes.string,\n srcSet: PropTypes.string,\n shouldLoad: PropTypes.bool,\n}\n\nPicture.displayName = `Picture`\nPicture.propTypes = {\n alt: PropTypes.string.isRequired,\n shouldLoad: PropTypes.bool,\n fallback: PropTypes.exact({\n src: PropTypes.string.isRequired,\n srcSet: PropTypes.string,\n sizes: PropTypes.string,\n }),\n sources: PropTypes.arrayOf(\n PropTypes.oneOfType([\n PropTypes.exact({\n media: PropTypes.string.isRequired,\n type: PropTypes.string,\n sizes: PropTypes.string,\n srcSet: PropTypes.string.isRequired,\n }),\n PropTypes.exact({\n media: PropTypes.string,\n type: PropTypes.string.isRequired,\n sizes: PropTypes.string,\n srcSet: PropTypes.string.isRequired,\n }),\n ])\n ),\n}\n","import React, { FunctionComponent, ImgHTMLAttributes } from \"react\"\nimport * as PropTypes from \"prop-types\"\nimport { Picture, SourceProps } from \"./picture\"\n\nexport type PlaceholderProps = ImgHTMLAttributes & {\n fallback?: string\n sources?: Array\n}\n\nexport const Placeholder: FunctionComponent =\n function Placeholder({ fallback, ...props }) {\n if (fallback) {\n return (\n \n )\n } else {\n return
\n }\n }\n\nPlaceholder.displayName = `Placeholder`\nPlaceholder.propTypes = {\n fallback: PropTypes.string,\n sources: Picture.propTypes?.sources,\n alt: function (props, propName, componentName): Error | null {\n if (!props[propName]) {\n return null\n }\n\n return new Error(\n `Invalid prop \\`${propName}\\` supplied to \\`${componentName}\\`. Validation failed.`\n )\n },\n}\n","import React from \"react\"\nimport { Picture, PictureProps } from \"./picture\"\n\nexport type MainImageProps = PictureProps\n\nexport const MainImage: React.FC = function MainImage(props) {\n return (\n <>\n \n \n \n )\n}\n\nMainImage.displayName = `MainImage`\nMainImage.propTypes = Picture.propTypes\n","import React from \"react\"\nimport { getWrapperProps, getMainProps, getPlaceholderProps } from \"./hooks\"\nimport { Placeholder } from \"./placeholder\"\nimport { MainImage, MainImageProps } from \"./main-image\"\nimport { LayoutWrapper } from \"./layout-wrapper\"\nimport PropTypes from \"prop-types\"\nimport type { FunctionComponent, WeakValidationMap } from \"react\"\nimport type { GatsbyImageProps, IGatsbyImageData } from \"./gatsby-image.browser\"\n\nconst removeNewLines = (str: string): string => str.replace(/\\n/g, ``)\n\nexport const GatsbyImage: FunctionComponent =\n function GatsbyImage({\n as = `div`,\n className,\n class: preactClass,\n style,\n image,\n loading = `lazy`,\n imgClassName,\n imgStyle,\n backgroundColor,\n objectFit,\n objectPosition,\n ...props\n }) {\n if (!image) {\n console.warn(`[gatsby-plugin-image] Missing image prop`)\n return null\n }\n\n if (preactClass) {\n className = preactClass\n }\n\n imgStyle = {\n objectFit,\n objectPosition,\n backgroundColor,\n ...imgStyle,\n }\n\n const {\n width,\n height,\n layout,\n images,\n placeholder,\n backgroundColor: placeholderBackgroundColor,\n } = image\n\n const {\n style: wStyle,\n className: wClass,\n ...wrapperProps\n } = getWrapperProps(width, height, layout)\n\n const cleanedImages: IGatsbyImageData[\"images\"] = {\n fallback: undefined,\n sources: [],\n }\n if (images.fallback) {\n cleanedImages.fallback = {\n ...images.fallback,\n srcSet: images.fallback.srcSet\n ? removeNewLines(images.fallback.srcSet)\n : undefined,\n }\n }\n\n if (images.sources) {\n cleanedImages.sources = images.sources.map(source => {\n return {\n ...source,\n srcSet: removeNewLines(source.srcSet),\n }\n })\n }\n\n return React.createElement(\n as,\n {\n ...wrapperProps,\n style: {\n ...wStyle,\n ...style,\n backgroundColor,\n },\n className: `${wClass}${className ? ` ${className}` : ``}`,\n },\n \n \n\n )}\n // When eager is set we want to start the isLoading state on true (we want to load the img without react)\n {...getMainProps(\n loading === `eager`,\n false,\n cleanedImages,\n loading,\n imgStyle\n )}\n />\n \n )\n }\n\nexport const altValidator: PropTypes.Validator = (\n props: GatsbyImageProps,\n propName,\n componentName,\n ...rest\n): Error | undefined => {\n if (!props.alt && props.alt !== ``) {\n return new Error(\n `The \"alt\" prop is required in ${componentName}. If the image is purely presentational then pass an empty string: e.g. alt=\"\". Learn more: https://a11y-style-guide.com/style-guide/section-media.html`\n )\n }\n\n return PropTypes.string(props, propName, componentName, ...rest)\n}\n\nexport const propTypes = {\n image: PropTypes.object.isRequired,\n alt: altValidator,\n} as WeakValidationMap\n","import {\n createElement,\n memo,\n useMemo,\n useEffect,\n useLayoutEffect,\n useRef,\n} from \"react\"\nimport {\n getWrapperProps,\n gatsbyImageIsInstalled,\n hasNativeLazyLoadSupport,\n} from \"./hooks\"\nimport { getSizer } from \"./layout-wrapper\"\nimport { propTypes } from \"./gatsby-image.server\"\nimport type {\n FC,\n ElementType,\n FunctionComponent,\n ImgHTMLAttributes,\n CSSProperties,\n ReactEventHandler,\n} from \"react\"\nimport type { renderImageToString } from \"./lazy-hydrate\"\nimport type { PlaceholderProps } from \"./placeholder\"\nimport type { MainImageProps } from \"./main-image\"\nimport type { Layout } from \"../image-utils\"\n\nconst imageCache = new Set()\nlet renderImageToStringPromise\nlet renderImage: typeof renderImageToString | undefined\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport interface GatsbyImageProps\n extends Omit<\n ImgHTMLAttributes,\n \"placeholder\" | \"onLoad\" | \"src\" | \"srcSet\" | \"width\" | \"height\"\n > {\n alt: string\n as?: ElementType\n className?: string\n class?: string\n imgClassName?: string\n image: IGatsbyImageData\n imgStyle?: CSSProperties\n backgroundColor?: string\n objectFit?: CSSProperties[\"objectFit\"]\n objectPosition?: CSSProperties[\"objectPosition\"]\n onLoad?: (props: { wasCached: boolean }) => void\n onError?: ReactEventHandler\n onStartLoad?: (props: { wasCached: boolean }) => void\n}\n\nexport interface IGatsbyImageData {\n layout: Layout\n width: number\n height: number\n backgroundColor?: string\n images: Pick\n placeholder?: Pick\n}\n\nconst GatsbyImageHydrator: FC = function GatsbyImageHydrator({\n as = `div`,\n image,\n style,\n backgroundColor,\n className,\n class: preactClass,\n onStartLoad,\n onLoad,\n onError,\n ...props\n}) {\n const { width, height, layout } = image\n const {\n style: wStyle,\n className: wClass,\n ...wrapperProps\n } = getWrapperProps(width, height, layout)\n const root = useRef()\n const cacheKey = useMemo(() => JSON.stringify(image.images), [image.images])\n\n // Preact uses class instead of className so we need to check for both\n if (preactClass) {\n className = preactClass\n }\n\n const sizer = getSizer(layout, width, height)\n\n useEffect(() => {\n if (!renderImageToStringPromise) {\n renderImageToStringPromise = import(`./lazy-hydrate`).then(\n ({ renderImageToString, swapPlaceholderImage }) => {\n renderImage = renderImageToString\n\n return {\n renderImageToString,\n swapPlaceholderImage,\n }\n }\n )\n }\n\n // The plugin image component is a bit special where if it's server-side rendered, we add extra script tags to support lazy-loading without\n // In this case we stop hydration but fire the correct events.\n const ssrImage = root.current.querySelector(\n `[data-gatsby-image-ssr]`\n ) as HTMLImageElement\n if (ssrImage && hasNativeLazyLoadSupport()) {\n if (ssrImage.complete) {\n // Trigger onStartload and onLoad events\n onStartLoad?.({\n wasCached: true,\n })\n onLoad?.({\n wasCached: true,\n })\n\n // remove ssr key for state updates but add delay to not fight with native code snippt of gatsby-ssr\n setTimeout(() => {\n ssrImage.removeAttribute(`data-gatsby-image-ssr`)\n }, 0)\n } else {\n onStartLoad?.({\n wasCached: true,\n })\n\n ssrImage.addEventListener(`load`, function onLoadListener() {\n ssrImage.removeEventListener(`load`, onLoadListener)\n\n onLoad?.({\n wasCached: true,\n })\n // remove ssr key for state updates but add delay to not fight with native code snippt of gatsby-ssr\n setTimeout(() => {\n ssrImage.removeAttribute(`data-gatsby-image-ssr`)\n }, 0)\n })\n }\n\n imageCache.add(cacheKey)\n\n return\n }\n\n if (renderImage && imageCache.has(cacheKey)) {\n return\n }\n\n let animationFrame\n let cleanupCallback\n renderImageToStringPromise.then(\n ({ renderImageToString, swapPlaceholderImage }) => {\n if (!root.current) {\n return\n }\n\n root.current.innerHTML = renderImageToString({\n isLoading: true,\n isLoaded: imageCache.has(cacheKey),\n image,\n ...props,\n })\n\n if (!imageCache.has(cacheKey)) {\n animationFrame = requestAnimationFrame(() => {\n if (root.current) {\n cleanupCallback = swapPlaceholderImage(\n root.current,\n cacheKey,\n imageCache,\n style,\n onStartLoad,\n onLoad,\n onError\n )\n }\n })\n }\n }\n )\n\n // eslint-disable-next-line consistent-return\n return (): void => {\n if (animationFrame) {\n cancelAnimationFrame(animationFrame)\n }\n if (cleanupCallback) {\n cleanupCallback()\n }\n }\n }, [image])\n\n // useLayoutEffect is ran before React commits to the DOM. This allows us to make sure our HTML is using our cached image version\n useLayoutEffect(() => {\n if (imageCache.has(cacheKey) && renderImage) {\n root.current.innerHTML = renderImage({\n isLoading: imageCache.has(cacheKey),\n isLoaded: imageCache.has(cacheKey),\n image,\n ...props,\n })\n\n // Trigger onStartload and onLoad events\n onStartLoad?.({\n wasCached: true,\n })\n onLoad?.({\n wasCached: true,\n })\n }\n }, [image])\n\n // By keeping all props equal React will keep the component in the DOM\n return createElement(as, {\n ...wrapperProps,\n style: {\n ...wStyle,\n ...style,\n backgroundColor,\n },\n className: `${wClass}${className ? ` ${className}` : ``}`,\n ref: root,\n dangerouslySetInnerHTML: {\n __html: sizer,\n },\n suppressHydrationWarning: true,\n })\n}\n\nexport const GatsbyImage: FunctionComponent = memo(\n function GatsbyImage(props) {\n if (!props.image) {\n if (process.env.NODE_ENV === `development`) {\n console.warn(`[gatsby-plugin-image] Missing image prop`)\n }\n\n return null\n }\n\n if (!gatsbyImageIsInstalled() && process.env.NODE_ENV === `development`) {\n console.warn(\n `[gatsby-plugin-image] You're missing out on some cool performance features. Please add \"gatsby-plugin-image\" to your gatsby-config.js`\n )\n }\n\n return createElement(GatsbyImageHydrator, props)\n }\n)\n\nGatsbyImage.propTypes = propTypes\nGatsbyImage.displayName = `GatsbyImage`\n","import React, { FunctionComponent, ReactElement } from \"react\"\nimport {\n altValidator,\n GatsbyImage as GatsbyImageServer,\n} from \"./gatsby-image.server\"\nimport { GatsbyImageProps, IGatsbyImageData } from \"./gatsby-image.browser\"\nimport PropTypes from \"prop-types\"\nimport { ISharpGatsbyImageArgs } from \"../image-utils\"\n\nexport interface IStaticImageProps\n extends Omit,\n Omit {\n src: string\n filename?: string\n}\n\n// These values are added by Babel. Do not add them manually\ninterface IPrivateProps {\n __imageData?: IGatsbyImageData\n __error?: string\n}\n\nexport function _getStaticImage(\n GatsbyImage: FunctionComponent\n): React.FC {\n return function StaticImage({\n src,\n __imageData: imageData,\n __error,\n // We extract these because they're not meant to be passed-down to GatsbyImage\n /* eslint-disable @typescript-eslint/no-unused-vars */\n width,\n height,\n aspectRatio,\n tracedSVGOptions,\n placeholder,\n formats,\n quality,\n transformOptions,\n jpgOptions,\n pngOptions,\n webpOptions,\n avifOptions,\n blurredOptions,\n breakpoints,\n outputPixelDensities,\n /* eslint-enable @typescript-eslint/no-unused-vars */\n ...props\n }): ReactElement {\n if (__error) {\n console.warn(__error)\n }\n\n if (imageData) {\n return \n }\n console.warn(`Image not loaded`, src)\n if (!__error && process.env.NODE_ENV === `development`) {\n console.warn(\n `Please ensure that \"gatsby-plugin-image\" is included in the plugins array in gatsby-config.js, and that your version of gatsby is at least 2.24.78`\n )\n }\n return null\n }\n}\n\nconst StaticImage: React.FC =\n _getStaticImage(GatsbyImageServer)\n\nconst checkDimensionProps: PropTypes.Validator = (\n props: IStaticImageProps & IPrivateProps,\n propName: keyof IStaticImageProps & IPrivateProps,\n ...rest\n) => {\n if (\n props.layout === `fullWidth` &&\n (propName === `width` || propName === `height`) &&\n props[propName]\n ) {\n return new Error(\n `\"${propName}\" ${props[propName]} may not be passed when layout is fullWidth.`\n )\n }\n return PropTypes.number(props, propName, ...rest)\n}\n\nconst validLayouts = new Set([`fixed`, `fullWidth`, `constrained`])\n\nexport const propTypes = {\n src: PropTypes.string.isRequired,\n alt: altValidator,\n width: checkDimensionProps,\n height: checkDimensionProps,\n sizes: PropTypes.string,\n layout: (props: IStaticImageProps & IPrivateProps): Error | undefined => {\n if (props.layout === undefined) {\n return undefined\n }\n if (validLayouts.has(props.layout)) {\n return undefined\n }\n\n return new Error(\n `Invalid value ${props.layout}\" provided for prop \"layout\". Defaulting to \"constrained\". Valid values are \"fixed\", \"fullWidth\" or \"constrained\".`\n )\n },\n}\n\nStaticImage.displayName = `StaticImage`\nStaticImage.propTypes = propTypes\n\nexport { StaticImage }\n","import {\n GatsbyImage as GatsbyImageBrowser,\n IGatsbyImageData,\n} from \"./gatsby-image.browser\"\nimport React from \"react\"\nimport {\n _getStaticImage,\n propTypes,\n IStaticImageProps,\n} from \"./static-image.server\"\n// These values are added by Babel. Do not add them manually\ninterface IPrivateProps {\n __imageData?: IGatsbyImageData\n __error?: string\n}\n\nconst StaticImage: React.FC =\n _getStaticImage(GatsbyImageBrowser)\n\nStaticImage.displayName = `StaticImage`\nStaticImage.propTypes = propTypes\n\nexport { StaticImage }\n","import React from \"react\";\n\nimport { Link } from \"gatsby\";\n\nimport { IProjectPreviewQueryResult } from \"../../types/project.type\";\nimport { GatsbyImage, getImage } from \"gatsby-plugin-image\";\nimport { LocalBusinessMetadata } from \"../common/metadata\";\n\nconst ProjectPreview = ({\n project,\n className,\n theme,\n}: {\n project: IProjectPreviewQueryResult;\n className?: string;\n theme: \"dark\" | \"light\";\n}) => {\n const cover = getImage(project.frontmatter.cover);\n const { title } = project.frontmatter;\n\n const fontColorClass10 =\n theme === \"light\"\n ? \"text-main-100 hover:text-main-10\"\n : \"text-secondary-100 hover:text-secondary-10\";\n const bgColors =\n theme === \"light\"\n ? \"bg-secondary-70 hover:bg-secondary-100\"\n : \"bg-main-100 hover:bg-main-100\";\n\n return (\n \n {cover ? (\n \n ) : null}\n \n {title.toUpperCase()}\n \n \n \n );\n};\n\nexport default ProjectPreview;\n"],"names":["UPPERCASE","LOWERCASE","LEADING_CAPITAL","IDENTIFIER","SEPARATORS","LEADING_SEPARATORS","RegExp","source","SEPARATORS_AND_IDENTIFIER","NUMBERS_AND_IDENTIFIER","camelCase","input","options","Array","isArray","TypeError","pascalCase","preserveConsecutiveUppercase","map","x","trim","filter","length","join","toLowerCase","locale","string","toLocaleLowerCase","toUpperCase","toLocaleUpperCase","isLastCharLower","isLastCharUpper","isLastLastCharUpper","i","character","test","slice","preserveCamelCase","replace","lastIndex","m1","charAt","_","identifier","m","postProcess","module","exports","W","hasNativeLazyLoadSupport","HTMLImageElement","prototype","e","t","a","Boolean","images","fallback","src","gatsbyImageData","gatsbyImage","childImageSharp","z","s","width","height","className","style","P","h","loading","shouldLoad","opacity","A","r","n","o","l","backgroundColor","position","top","left","bottom","right","objectFit","objectPosition","d","transition","H","F","_ref5","layout","paddingTop","maxWidth","display","alt","role","G","children","u","V","B","U","srcSet","decoding","Y","sources","sizes","_ref6","media","type","key","X","propTypes","isRequired","displayName","J","Z","Error","K","Q","ee","te","ae","_len","arguments","_key","c","apply","concat","ie","image","se","re","ne","Set","oe","le","de","as","class","g","onStartLoad","p","onLoad","onError","f","w","y","b","v","E","k","S","M","N","$","JSON","stringify","I","then","_ref7","renderImageToString","swapPlaceholderImage","current","querySelector","complete","wasCached","setTimeout","removeAttribute","addEventListener","removeEventListener","add","has","_ref8","innerHTML","isLoading","isLoaded","requestAnimationFrame","cancelAnimationFrame","ref","dangerouslySetInnerHTML","__html","suppressHydrationWarning","ce","he","ue","__imageData","__error","console","warn","ge","imgClassName","imgStyle","placeholder","pe","_len2","_key2","me","fe","we","_ref","project","theme","cover","getImage","frontmatter","title","fontColorClass10","bgColors","React","Link","to","id","itemScope","itemType","GatsbyImage","itemProp","LocalBusinessMetadata"],"sourceRoot":""} \ No newline at end of file diff --git a/731-9eed37b9b450ac75eb5a.js b/731-fc2222e8bcbd3a323b37.js similarity index 97% rename from 731-9eed37b9b450ac75eb5a.js rename to 731-fc2222e8bcbd3a323b37.js index 7e17f443..49a4b59a 100644 --- a/731-9eed37b9b450ac75eb5a.js +++ b/731-fc2222e8bcbd3a323b37.js @@ -1,3 +1,3 @@ -/*! For license information please see 731-9eed37b9b450ac75eb5a.js.LICENSE.txt */ -"use strict";(self.webpackChunkcode_cave=self.webpackChunkcode_cave||[]).push([[731],{6731:function(e,t,n){n.r(t),n.d(t,{renderImageToString:function(){return p},swapPlaceholderImage:function(){return f}});var r=n(8032),o=n(7294),a=n(7762);n(3204);let l;const i=new WeakMap,u=navigator.connection||navigator.mozConnection||navigator.webkitConnection,s=["image","loading","isLoading","isLoaded","imgClassName","imgStyle","objectPosition","backgroundColor","objectFit"];function c(e,t){e.style.opacity="1",t&&(t.style.opacity="0")}function d(e,t,n,r,o,a){const l=e.querySelector("[data-main-image]"),i=e.querySelector("[data-placeholder-image]"),u=n.has(t);function s(e){this.removeEventListener("load",s);const t=e.currentTarget,n=new Image;n.src=t.currentSrc,n.decode?n.decode().then((()=>{c(this,i),null==o||o({wasCached:u})})).catch((e=>{c(this,i),null==a||a(e)})):(c(this,i),null==o||o({wasCached:u}))}return l.addEventListener("load",s),null==r||r({wasCached:u}),Array.from(l.parentElement.children).forEach((e=>{const t=e.getAttribute("data-src"),n=e.getAttribute("data-srcset");t&&(e.removeAttribute("data-src"),e.setAttribute("src",t)),n&&(e.removeAttribute("data-srcset"),e.setAttribute("srcset",n))})),n.add(t),l.complete&&s.call(l,{currentTarget:l}),()=>{l&&l.removeEventListener("load",s)}}function f(e,t,o,a,s,c,f){if(!(0,r.h)()){let r;const m=(g=()=>{r=d(e,t,o,s,c,f)},"IntersectionObserver"in window?(l||(l=new IntersectionObserver((e=>{e.forEach((e=>{var t;e.isIntersecting&&(null==(t=i.get(e.target))||t(),i.delete(e.target))}))}),{rootMargin:"4g"!==(null==u?void 0:u.effectiveType)||null!=u&&u.saveData?"2500px":"1250px"})),function(e){return i.set(e,g),l.observe(e),function(){l&&e&&(i.delete(e),l.unobserve(e))}}):function(){return g(),function(){}}),b=m(e);var p,h;return"objectFit"in document.documentElement.style||(e.dataset.objectFit=null!=(p=a.objectFit)?p:"cover",e.dataset.objectPosition=""+(null!=(h=a.objectPosition)?h:"50% 50%"),async function(e){"objectFitPolyfill"in window||await n.e(843).then(n.t.bind(n,4843,23)),window.objectFitPolyfill(e)}(e)),()=>{r&&r(),b()}}var g;return d(e,t,o,s,c,f)}function p(e){let{image:t,loading:n="lazy",isLoading:l,isLoaded:i,imgClassName:u,imgStyle:c={},objectPosition:d,backgroundColor:f,objectFit:p="cover"}=e,h=(0,r._)(e,s);const{width:g,height:m,layout:b,images:y,placeholder:v,backgroundColor:S}=t;return c=(0,r.a)({objectFit:p,objectPosition:d,backgroundColor:f},c),(0,a.uS)(o.createElement(r.L,{layout:b,width:g,height:m},o.createElement(r.P,(0,r.a)({},(0,r.g)(v,i,b,g,m,S,p,d))),o.createElement(r.M,(0,r.a)({},h,{width:g,height:m,className:u},(0,r.b)(l,i,y,n,c)))))}},7774:function(e,t,n){var r=n(7294);function o(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n
\n \n \n \n );\n};\n\nexport default Navbar;\n","import React from \"react\";\nimport { Link } from \"gatsby\";\n\nimport FooterLogo from \"../../assets/common/footer-logo.svg\";\n\nimport ContentContainer from \"../common/contentContainer\";\nimport ContactLinks from \"./contactLinks\";\n\nconst Footer = () => {\n const links = [\"Services\", \"Workflow\", \"Projects\", \"Blog\"];\n\n return (\n
\n \n
\n \n \n \n );\n};\n\nexport default Footer;\n","import React, { useEffect, useRef, useState } from \"react\";\n\nimport { FaChevronUp } from \"@react-icons/all-files/fa/FaChevronUp\";\n\nconst UpButton = () => {\n const isInitial = useRef(true);\n const [isShow, setIsShow] = useState(false);\n\n const showHideUpButton = () => {\n const isScrolled = window.innerHeight < window.scrollY;\n\n if (isScrolled) setIsShow(true);\n if (!isScrolled) setIsShow(false);\n };\n\n useEffect(() => {\n if (!window || !isInitial.current) return;\n\n isInitial.current = false;\n window.addEventListener(\"scroll\", showHideUpButton);\n\n return () => window.removeEventListener(\"scroll\", showHideUpButton);\n }, []);\n\n const onClick = () => {\n if (!window) return;\n window.scrollTo({ top: 0, behavior: \"smooth\" });\n };\n\n return (\n <>\n {isShow ? (\n \n \n \n ) : null}\n \n );\n};\n\nexport default UpButton;\n","import React from \"react\";\n\nimport Navbar from \"./navbar\";\nimport Footer from \"./footer\";\nimport { BasicMetadata } from \"../common/metadata\";\nimport { PageProps } from \"gatsby\";\nimport UpButton from \"../common/upButton\";\n\nconst Layout = ({ path, children }: PageProps) => {\n return (\n \n \n \n {children}\n